{"text": "Load loadpath.\nRequire Import ZArith Znumtheory Coq.Lists.List.\nRequire Import veristar.variables veristar.datatypes veristar.clauses\n               veristar.superpose veristar.basic veristar.compare.\nImport Superposition.\nRequire Recdef.\n\nModule HeapResolve.\n\n(** Normalization Rules *)\n\nDefinition normalize1_3 (pc sc : clause) : clause :=\n  match pc , sc with\n  | PureClause gamma (Eqv (Var x) y :: delta) _ _,\n    PosSpaceClause gamma' delta' sigma =>\n        PosSpaceClause (rsort_uniq pure_atom_cmp (gamma++gamma'))\n                       (rsort_uniq pure_atom_cmp (delta++delta'))\n                       (subst_spaces x y sigma)\n  | PureClause gamma (Eqv (Var x) y :: delta) _ _,\n    NegSpaceClause gamma' sigma delta' =>\n         NegSpaceClause (rsort_uniq pure_atom_cmp (gamma++gamma'))\n                        (subst_spaces x y sigma)\n                        (rsort_uniq pure_atom_cmp (delta++delta'))\n  | _ , _  => sc\n  end.\n\nDefinition normalize2_4 (sc : clause) : clause :=\n  match sc with\n  | PosSpaceClause gamma delta sigma =>\n        PosSpaceClause gamma delta (drop_reflex_lseg sigma)\n  | NegSpaceClause gamma sigma delta =>\n        NegSpaceClause gamma (drop_reflex_lseg sigma) delta\n  | _ => sc\n  end.\n\nDefinition norm (s:  M.t) (sc: clause) : clause :=\n  normalize2_4 (List.fold_right normalize1_3 sc\n    (rsort (rev_cmp compare_clause2) (M.elements s))).\n\n(** Wellformedness Rules *)\n\nFixpoint do_well1_2 (sc: list space_atom) : list (list pure_atom) :=\n  match sc with\n  | Next Nil _ :: sc' => nil :: do_well1_2 sc'\n  | Lseg Nil y :: sc' => [Eqv y Nil] :: do_well1_2 sc'\n  | _ :: sc' => do_well1_2 sc'\n  | nil => nil\n  end.\n\n(** Next x ? \\in sc *)\nFixpoint next_in_dom (x : Ident.t) (sc : list space_atom) : bool :=\n  match sc with\n  | nil => false\n  | Next (Var x') y :: sc' =>\n    if Ident.eq_dec x x' then true\n    else next_in_dom x sc'\n  | _ :: sc' => next_in_dom x sc'\n  end.\n\n(** Next x ? \\in sc, ?=y *)\nFixpoint next_in_dom1 (x : Ident.t) (y : expr) (sc : list space_atom) : bool :=\n  match sc with\n  | nil => false\n  | Next (Var x') y' :: sc' =>\n    if Ident.eq_dec x x' then if expr_eq y y' then true\n    else next_in_dom1 x y sc' else next_in_dom1 x y sc'\n  | _ :: sc' => next_in_dom1 x y sc'\n  end.\n\n(** Next x ? \\in sc, ?<>y *)\n\nFixpoint next_in_dom2 (x : Ident.t) (y : expr) (sc : list space_atom)\n  : option expr :=\n  match sc with\n  | nil => None\n  | Next (Var x') y' :: sc' =>\n    if Ident.eq_dec x x' then if expr_eq y y' then next_in_dom2 x y sc'\n                                 else Some y'\n    else next_in_dom2 x y sc'\n  | _ :: sc' => next_in_dom2 x y sc'\n  end.\n\nFixpoint do_well3 (sc: list space_atom) : list (list pure_atom) :=\n  match sc with\n  | Next (Var x) y :: sc' =>\n    if next_in_dom x sc'\n      then nil :: do_well3 sc'\n      else do_well3 sc'\n  | _ :: sc' => do_well3 sc'\n  | nil => nil\n  end.\n\n(** Lseg x ?, ?<>y *)\n\nFixpoint lseg_in_dom2 (x : Ident.t) (y : expr) (sc : list space_atom)\n  : option expr :=\n  match sc with\n  | Lseg (Var x' as x0) y0 :: sc' =>\n    if Ident.eq_dec x x'\n      then if negb (expr_eq y0 y) then Some y0 else lseg_in_dom2 x y sc'\n      else lseg_in_dom2 x y sc'\n  | _ :: sc' => lseg_in_dom2 x y sc'\n  | nil => None\n  end.\n\nFixpoint lseg_in_dom_atoms (x : Ident.t) (sc : list space_atom)\n  : list pure_atom :=\n  match sc with\n  | Lseg (Var x' as x0) y0 :: sc' =>\n    if Ident.eq_dec x x'\n      then order_eqv_pure_atom (Eqv x0 y0) :: lseg_in_dom_atoms x sc'\n      else lseg_in_dom_atoms x sc'\n  | _ :: sc' => lseg_in_dom_atoms x sc'\n  | nil => nil\n  end.\n\nFixpoint do_well4_5 (sc : list space_atom) : list (list pure_atom) :=\n  match sc with\n  | Next (Var x') y :: sc' =>\n    let atms := map (fun a => [a]) (lseg_in_dom_atoms x' sc') in\n      atms ++ do_well4_5 sc'\n  | Lseg (Var x' as x0) y :: sc' =>\n    let l0 := lseg_in_dom_atoms x' sc' in\n      match l0 with\n      | nil => do_well4_5 sc'\n      | _ :: _ =>\n        let atms := map (fun a => normalize_atoms [Eqv x0 y, a]) l0 in\n          atms ++ do_well4_5 sc'\n      end\n  | _ as a :: sc' => do_well4_5 sc'\n  | nil => nil\n  end.\n\nDefinition do_well (sc : list space_atom) : list (list pure_atom) :=\n  do_well1_2 sc ++ do_well3 sc ++ do_well4_5 sc.\n\nDefinition do_wellformed (sc: clause) : M.t :=\n match sc with\n | PosSpaceClause gamma delta sigma =>\n   let sigma' := rsort (rev_cmp compare_space_atom) sigma in\n     clause_list2set\n       (map (fun ats => mkPureClause gamma (normalize_atoms (ats++delta)))\n         (do_well sigma'))\n | _ => M.empty\n end.\n\n(** Unfolding Rules *)\n\nDefinition spatial_resolution (pc nc : clause) : M.t :=\n  match pc , nc with\n  | PosSpaceClause gamma' delta' sigma' , NegSpaceClause gamma sigma delta =>\n    match eq_space_atomlist (rsort compare_space_atom sigma)\n                            (rsort compare_space_atom sigma') with\n    | true => M.singleton (order_eqv_clause (mkPureClause (gamma++gamma') (delta++delta')))\n    | false => M.empty\n      end\n  | _ , _ => M.empty\n  end.\n\nFixpoint unfolding1' (sigma0 sigma1 sigma2 : list space_atom)\n  : list (pure_atom * list space_atom) :=\n  match sigma2 with\n  | Lseg (Var x' as x) z :: sigma2' =>\n    if next_in_dom1 x' z sigma1\n    (*need to reinsert since replacing lseg with next doesn't always preserve\n    sorted order*)\n      then\n        (Eqv x z,\n          insert (rev_cmp compare_space_atom) (Next x z) (rev sigma0 ++ sigma2'))\n        :: unfolding1' (Lseg x z :: sigma0) sigma1 sigma2'\n      else unfolding1' (Lseg x z :: sigma0) sigma1 sigma2'\n  | a :: sigma2' => unfolding1' (a :: sigma0) sigma1 sigma2'\n  | nil => nil\n  end.\n\nDefinition unfolding1 (sc1 sc2 : clause) : list clause :=\n  match sc1 , sc2 with\n  | PosSpaceClause gamma delta sigma1 , NegSpaceClause gamma' sigma2 delta' =>\n    let l0 := unfolding1' nil sigma1 sigma2 in\n    let build_clause p :=\n      match p with (atm, sigma2') =>\n        NegSpaceClause gamma' sigma2'\n          (insert_uniq pure_atom_cmp (order_eqv_pure_atom atm) delta')\n      end in\n      map build_clause l0\n  | _ , _ => nil\n  end.\n\nFixpoint unfolding2' (sigma0 sigma1 sigma2 : list space_atom)\n  : list (pure_atom * list space_atom) :=\n  match sigma2 with\n  | Lseg (Var x' as x) z :: sigma2' =>\n    match next_in_dom2 x' z sigma1 with\n    | Some y =>\n      (Eqv x z,\n          insert (rev_cmp compare_space_atom) (Next x y)\n            (insert (rev_cmp compare_space_atom) (Lseg y z) (rev sigma0 ++ sigma2')))\n        :: unfolding2' (Lseg x z :: sigma0) sigma1 sigma2'\n    | None => unfolding2' (Lseg x z :: sigma0) sigma1 sigma2'\n    end\n  | a :: sigma2' => unfolding2' (a :: sigma0) sigma1 sigma2'\n  | nil => nil\n  end.\n\nDefinition unfolding2 (sc1 sc2 : clause) : list clause :=\n  match sc1 , sc2 with\n  | PosSpaceClause gamma delta sigma1 , NegSpaceClause gamma' sigma2 delta' =>\n    let l0 := unfolding2' nil sigma1 sigma2 in\n    let build_clause p :=\n      match p with (atm, sigma2') =>\n        NegSpaceClause gamma' sigma2'\n          (insert_uniq pure_atom_cmp (order_eqv_pure_atom atm) delta')\n      end in\n      map build_clause l0\n  | _ , _ => nil\n  end.\n\nFixpoint unfolding3' (sigma0 sigma1 sigma2 : list space_atom) :\n  list (list space_atom) :=\n  match sigma2 with\n  | Lseg (Var x' as x) Nil :: sigma2' =>\n    match lseg_in_dom2 x' Nil sigma1 with\n    | Some y =>\n          insert (rev_cmp compare_space_atom) (Lseg x y)\n            (insert (rev_cmp compare_space_atom) (Lseg y Nil) (rev sigma0 ++ sigma2'))\n        :: unfolding3' (Lseg x Nil :: sigma0) sigma1 sigma2'\n    | None => unfolding3' (Lseg x Nil :: sigma0) sigma1 sigma2'\n    end\n  | a :: sigma2' => unfolding3' (a :: sigma0) sigma1 sigma2'\n  | nil => nil\n  end.\n\nDefinition unfolding3 (sc1 sc2 : clause) : list clause :=\n  match sc1 , sc2 with\n  | PosSpaceClause gamma delta sigma1 , NegSpaceClause gamma' sigma2 delta' =>\n    let l0 := unfolding3' nil sigma1 sigma2 in\n    let build_clause sigma2' := NegSpaceClause gamma' sigma2' delta' in\n      map build_clause l0\n  | _ , _ => nil\n  end.\n\n(** NPR's rule given in the paper. Confirmed unsound by NP.*)\n\nFixpoint unfolding4NPR' (sigma0 sigma1 sigma2 : list space_atom)\n  : list (list space_atom) :=\n  match sigma2 with\n  | Lseg (Var x' as x) (Var z' as z) :: sigma2' =>\n    match lseg_in_dom2 x' z sigma1 with\n    | Some y =>\n      if next_in_dom z' sigma1 then\n          insert (rev_cmp compare_space_atom) (Lseg x y)\n            (insert (rev_cmp compare_space_atom) (Lseg y z) (rev sigma0 ++ sigma2'))\n        :: unfolding4NPR' (Lseg x z :: sigma0) sigma1 sigma2'\n      else unfolding4NPR' (Lseg x z :: sigma0) sigma1 sigma2'\n    | None => unfolding4NPR' (Lseg x z :: sigma0) sigma1 sigma2'\n    end\n  | a :: sigma2' => unfolding4NPR' (a :: sigma0) sigma1 sigma2'\n  | nil => nil\n  end.\n\nDefinition unfoldingNPR4 (sc1 sc2 : clause) : list clause :=\n  match sc1 , sc2 with\n  | PosSpaceClause gamma delta sigma1 , NegSpaceClause gamma' sigma2 delta' =>\n    let l0 := unfolding4NPR' nil sigma1 sigma2 in\n    let build_clause sigma2' := NegSpaceClause gamma' sigma2' delta' in\n      map build_clause l0\n  | _ , _ => nil\n  end.\n\n(** Our rule; also suggested by NP. *)\n\nDefinition unfolding4 (sc1 sc2 : clause) : list clause :=\n  match sc1 , sc2 with\n  | PosSpaceClause gamma delta sigma1 , NegSpaceClause gamma' sigma2 delta' =>\n    let l0 := unfolding4NPR' nil sigma1 sigma2 in\n    let GG' := rsort_uniq pure_atom_cmp (gamma ++ gamma') in\n    let DD' := rsort_uniq pure_atom_cmp (delta ++ delta') in\n    let build_clause sigma2' := NegSpaceClause GG' sigma2' DD' in\n      map build_clause l0\n  | _ , _ => nil\n  end.\n\n\n(** Unsound rule as given in NPR's paper *)\n\nFixpoint unfolding5NPR' (sigma0 sigma1 sigma2 : list space_atom)\n  : list (pure_atom * list space_atom) :=\n  match sigma2 with\n  | Lseg (Var x' as x) (Var z' as z) :: sigma2' =>\n    match lseg_in_dom2 x' z sigma1 with\n    | Some y =>\n      let atms := lseg_in_dom_atoms z' sigma1 in\n      let build_res atm :=\n        (atm,\n          insert (rev_cmp compare_space_atom) (Lseg x y)\n            (insert (rev_cmp compare_space_atom) (Lseg y z)\n              (rev sigma0 ++ sigma2'))) in\n        map build_res atms ++ unfolding5NPR' (Lseg x z :: sigma0) sigma1 sigma2'\n    | None => unfolding5NPR' (Lseg x z :: sigma0) sigma1 sigma2'\n    end\n  | a :: sigma2' => unfolding5NPR' (a :: sigma0) sigma1 sigma2'\n  | nil => nil\n  end.\n\nDefinition unfolding5NPR (sc1 sc2 : clause) : list clause :=\n  match sc1 , sc2 with\n  | PosSpaceClause gamma delta sigma1 , NegSpaceClause gamma' sigma2 delta' =>\n    let l0 := unfolding5NPR' nil sigma1 sigma2 in\n    let build_clause p :=\n      match p with (atm, sigma2') =>\n        NegSpaceClause gamma' sigma2'\n          (insert_uniq pure_atom_cmp (order_eqv_pure_atom atm) delta')\n      end in\n      map build_clause l0\n  | _ , _ => nil\n  end.\n\n(** Rule as given in NPR's paper, corrected variable uses *)\n\nFixpoint unfolding5NPRALT' (sigma0 sigma1 sigma2 : list space_atom)\n  : list (pure_atom * list space_atom) :=\n  match sigma2 with\n  | Lseg (Var x' as x) (Var z' as z) :: sigma2' =>\n    match lseg_in_dom2 x' z sigma1, lseg_in_dom2 x' z sigma1 with\n    | Some y, _ =>\n      let atms := lseg_in_dom_atoms z' sigma1 in\n      let build_res atm :=\n        (atm,\n          insert (rev_cmp compare_space_atom) (Lseg x y)\n            (insert (rev_cmp compare_space_atom) (Lseg y z)\n              (rev sigma0 ++ sigma2'))) in\n        map build_res atms ++ unfolding5NPR' (Lseg x z :: sigma0) sigma1 sigma2'\n    | None, _ => unfolding5NPR' (Lseg x z :: sigma0) sigma1 sigma2'\n    end\n  | a :: sigma2' => unfolding5NPR' (a :: sigma0) sigma1 sigma2'\n  | nil => nil\n  end.\n\n(** Our version - also suggested by NP in his reply. *)\n\nDefinition unfolding5 (sc1 sc2 : clause) : list clause :=\n  match sc1 , sc2 with\n  | PosSpaceClause gamma delta sigma1 , NegSpaceClause gamma' sigma2 delta' =>\n    let l0 := unfolding5NPR' nil sigma1 sigma2 in\n    let GG' := rsort_uniq pure_atom_cmp (gamma ++ gamma') in\n    let DD' := rsort_uniq pure_atom_cmp (delta ++ delta') in\n    let build_clause p :=\n      match p with (atm, sigma2') =>\n        NegSpaceClause GG' sigma2'\n          (insert_uniq pure_atom_cmp (order_eqv_pure_atom atm) DD')\n      end in\n      map build_clause l0\n  | _ , _ => nil\n  end.\n\n(** Same as unfolding5NPR', but with added side-condition *)\n\nFixpoint unfolding6NPR' (sigma0 sigma1 sigma2 : list space_atom)\n  : list (pure_atom * list space_atom) :=\n  match sigma2 with\n  | Lseg (Var x' as x) (Var z' as z) :: sigma2' =>\n    if Ident.eq_dec x' z' then unfolding6NPR' sigma0 sigma1 sigma2' else\n    match lseg_in_dom2 x' z sigma1 with\n    | Some y =>\n      let atms := lseg_in_dom_atoms z' sigma1 in\n      let build_res atm :=\n        (atm,\n          insert (rev_cmp compare_space_atom) (Lseg x y)\n            (insert (rev_cmp compare_space_atom) (Lseg y z)\n              (rev sigma0 ++ sigma2'))) in\n        map build_res atms ++ unfolding6NPR' (Lseg x z :: sigma0) sigma1 sigma2'\n    | None =>\n       unfolding6NPR' (Lseg x z :: sigma0) sigma1 sigma2'\n    end\n  | a :: sigma2' => unfolding6NPR' (a :: sigma0) sigma1 sigma2'\n  | nil => nil\n  end.\n\nDefinition unfolding6 (sc1 sc2 : clause) : list clause :=\n  match sc1 , sc2 with\n  | PosSpaceClause gamma delta sigma1 , NegSpaceClause gamma' sigma2 delta' =>\n    let l0 := unfolding6NPR' nil sigma1 sigma2 in\n    let GG' := rsort_uniq pure_atom_cmp (gamma ++ gamma') in\n    let DD' := rsort_uniq pure_atom_cmp (delta ++ delta') in\n    let build_clause p :=\n      match p with (atm, sigma2') =>\n        NegSpaceClause GG' sigma2'\n          (insert_uniq pure_atom_cmp (order_eqv_pure_atom atm) DD')\n      end in\n      (map build_clause l0)\n  | _ , _ => nil\n  end.\n\nDefinition mem_add (x: M.elt) (s: M.t) : option M.t :=\n if M.mem x s then None else Some (M.add x s).\n\nDefinition add_list_to_set_simple (l: list M.elt) (s: M.t) : M.t :=\n  fold_left (Basics.flip M.add) l s.\n\nFixpoint add_list_to_set (l: list M.elt) (s: M.t) : option M.t :=\n match l with\n | x::xs => match mem_add x s with\n                  | None => add_list_to_set xs s\n                  | Some s' => Some (add_list_to_set_simple xs s')\n                  end\n | nil => None\n end.\n\nDefinition do_unfold' pc nc l :=\n  unfolding1 pc nc ++\n  unfolding2 pc nc ++ unfolding3 pc nc ++\n  unfolding4 pc nc ++ unfolding6 pc nc ++ l.\n\nFixpoint do_unfold (n: nat) (pc : clause) (s : M.t) : M.t :=\n  match n with\n  | O => s\n  | S n' =>\n   match add_list_to_set  (M.fold (do_unfold' pc) s nil)  s with\n   | Some s'' => do_unfold n' pc s''\n   | None => s\n   end\n  end.\n\nDefinition unfolding (pc nc : clause) : M.t :=\n  M.fold (fun c => M.union (spatial_resolution pc c))\n            (do_unfold 500 pc (M.add nc M.empty)) M.empty.\n\nEnd HeapResolve.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/veristar/heapresolve.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24999511416865197}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nRequire Import ZArith EqNat Classical.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssrnat_ext.\nRequire Import integral_type seplog frag.\nRequire Import topsy_hm topsy_hmInit_prg.\n\nRequire Import expr_b_dp.\nImport seplog_Z_m.assert_m.expr_m.\nImport seplog_Z_m.assert_m.\nImport seplog_Z_m.\n\nLocal Close Scope Z_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope seplog_expr_scope.\nLocal Open Scope seplog_assert_scope.\nLocal Open Scope seplog_cmd_scope.\nLocal Open Scope seplog_hoare_scope.\n\n(** This file contains the verification of hmInit in two flavors:\n  (1) semi-automatic using the \"frag\" tactic, (2) manual. *)\n\nDefinition hmInit_specif := forall p sz, sz >= 4 ->\n  {{ Array p sz }} hmInit p sz {{ Heap_List ((sz - 4, topsy_hm.free) :: nil) p }}.\n\nDefinition hmInit_precond (adr sz : nat) :=\n  (true_b, star\n    (star (cell (nat_e adr)) (cell (nat_e adr \\+ cst_e 1%Z)))\n    (star (cell (nat_e adr \\+ nat_e sz \\- cst_e 2%Z)) (cell (nat_e adr \\+ nat_e sz \\- cst_e 1%Z)))).\n\nDefinition hmInit_postcond (adr sz : nat):=\n  (true_b, star\n    (star (singl (nat_e adr) Free) (singl (nat_e adr \\+ cst_e 1%Z) (nat_e adr \\+ nat_e sz \\- cst_e 2%Z)))\n    (star (singl (nat_e adr \\+ nat_e sz \\- cst_e 2%Z) Allocated)\n      (singl (nat_e adr \\+ nat_e sz \\- cst_e 1%Z) (nat_e 0)))).\n\nLemma frag_precond startp sizep : sizep >= 4 ->\n  Array startp sizep ===> assrt_interp (hmInit_precond startp sizep) ** Array (startp + 2) (sizep - 4).\nProof.\nmove=> H.\nrewrite /while.entails => s h H0.\nTArray_concat_split_l_l 2 H; clear H0.\ncase_sepcon H1.\nTArray_concat_split_l_r 2 H1_h2; clear H1_h2.\ncase_sepcon H0.\nCompose_sepcon (h1 \\U h22) h21.\nrewrite /=; split; first by done.\nCompose_sepcon h1 h22.\nsimpl in H1_h1.\ncase_sepcon H1_h1.\ncase_sepcon H1_h1_h12.\nCompose_sepcon h11 h121; auto.\ncase: H1_h1_h12_h121 => x ?; exists x; by Mapsto.\nsimpl in H0_h22.\ncase_sepcon H0_h22.\ncase_sepcon H0_h22_h222.\nCompose_sepcon h221 h2221; auto.\ncase: H0_h22_h221 => x ?; exists x; by Mapsto.\ncase: H0_h22_h222_h2221 => x ?; exists x; by Mapsto.\nby Array_equiv.\nQed.\n\nLemma frag_postcond startp sizep : sizep >= 4 ->\n  assrt_interp (hmInit_postcond startp sizep) ** Array (startp + 2) (sizep - 4) ===>\n  Heap_List ((sizep - 4, true) :: nil) startp.\nProof.\nmove=> H s h H0.\ncase_sepcon H0.\nrewrite /= in H0_h1; case H0_h1 => _ H5.\ncase_sepcon H5.\nCompose_sepcon (h11 \\U h2) h12.\neapply hl_Free with (h1 := h11 \\U h2) (h2 := heap.emp); [by map_tac_m.Disj | by map_tac_m.Equal | auto | intuition | idtac | idtac].\ncase_sepcon H5_h11.\nCompose_sepcon h11 h2; [idtac | by Array_equiv].\nsimpl; Compose_sepcon h111 h112; first by done.\nCompose_sepcon h112 heap.emp; by [Mapsto | red; auto].\nby apply hl_last.\ncase_sepcon H5_h12.\nsimpl; Compose_sepcon h121 h122.\nby Mapsto.\nCompose_sepcon h122 assert_m.heap.emp; by [Mapsto | red; auto].\nQed.\n\nLemma hmInit_verif_auto : hmInit_specif.\nProof.\nrewrite /hmInit_specif /hmInit.\nmove=> p size H.\neapply hoare_prop_m.hoare_weak.\n- by apply (frag_postcond p size H).\n- eapply hoare_prop_m.hoare_stren.\n  by apply (frag_precond p size H).\n  Frame_rule (Array (p + 2) (size - 4)); [idtac | eapply Array_inde_list].\n  rewrite /hmInit_precond /hmInit_postcond /hmStart /hmEnd /next /status /Allocated /Free.\n  eapply LWP_use.\n  + rewrite /=; reflexivity.\n  + by LWP_Resolve.\nQed.\n\nLemma hmInit_verif_manual : hmInit_specif.\nProof.\nrewrite /hmInit_specif /hmInit => p sz H.\n\n(**\n<<\nhmStart <- nat_e p;\n>>\n*)\n\nStep (fun s h => Array p sz s h /\\ [ var_e hmStart \\= nat_e p ]b_s).\n\nrewrite /wp_assign.\nResolve_topsy.\nby Array_equiv.\n\n(**\n<<\nhmStart -.> next *<- (nat_e p \\+ nat_e size) \\- cst_e 2%Z;\n>>\n*)\n\nStep (fun s h => (Array p 1 **\n  (var_e hmStart \\+ nat_e 1 |~> nat_e p \\+ nat_e sz \\- cst_e 2%Z) **\n  Array (p + 2) (sz - 2)) s h /\\ [ var_e hmStart \\= nat_e p ]b_s).\n\ncase : H0 => H1 H2.\nTArray_concat_split_l_l 2 H2.\ncase_sepcon H0.\nrewrite /= in H0_h1; case_sepcon H0_h1.\ncase_sepcon H0_h1_h12.\ncase : H0_h1_h12_h121 => x H0_h1_h12_h121.\nexists (cst_e x).\nCompose_sepcon h121 (h2 \\U h11).\n- rewrite /next; by Mapsto.\n- rewrite /imp => h121' [X1 X2] h' Hh'.\n  split; last by assumption.\n  rewrite -conAE.\n  Compose_sepcon (h11 \\U h121') h2; last by assumption.\n  Compose_sepcon h11 h121'; last by assumption.\n  by Compose_sepcon h11 heap.emp.\n\n(**\n<<\nhmStart -.> status *<- Free;\n>>\n*)\n\nStep (fun s h => (var_e hmStart |~> Free **\n    var_e hmStart \\+ nat_e 1 |~> nat_e p \\+ nat_e sz \\- cst_e 2%Z **\n    Array (p + 2) (sz - 2)) s h /\\ [ var_e hmStart \\= nat_e p ]b_s).\n\ncase : H0 => H1 H2.\nrewrite -conAE in H1.\ncase_sepcon H1.\ncase_sepcon H1_h1.\nrewrite /= in H1_h1_h11; case_sepcon H1_h1_h11.\ncase : H1_h1_h11_h111 => x H1_h1_h11_h111.\nexists (cst_e x).\nCompose_sepcon h111 (h12 \\U h2).\n- rewrite /status; by Mapsto.\n- rewrite /imp => h111' [X1 X2] h' Hh'.\n  split; last by assumption.\n  rewrite -conAE.\n  Compose_sepcon (h111' \\U h12) h2; last by assumption.\n  Compose_sepcon h111' h12; last by assumption.\n  rewrite /status in X2; by Mapsto.\n\n(**\n<<\nhmEnd <-* hmStart -.> next;\n>>\n*)\n\nStep (fun s h => (var_e hmStart |~> Free **\n    var_e hmStart \\+ nat_e 1 |~> nat_e p \\+ nat_e sz \\- cst_e 2%Z **\n    Array (p + 2) (sz - 2)) s h /\\ [ var_e hmStart \\= nat_e p ]b_s /\\\n  [ var_e hmEnd \\= nat_e p \\+ nat_e sz \\- cst_e 2%Z ]b_s).\n\ncase : H0 => H1 H2.\nrewrite -conAE in H1.\ncase_sepcon H1.\ncase_sepcon H1_h1.\nexists ((nat_e p \\+ nat_e sz) \\- cst_e 2%Z).\nCompose_sepcon h12 (h11 \\U h2).\n- rewrite /next; by Mapsto.\n- rewrite /imp => h12' [X1 X2] h' Hh'.\n  rewrite /wp_assign; split.\n  + rewrite -conAE.\n    Compose_sepcon (h11 \\U h12') h2.\n    Compose_sepcon h11 h12'; apply mapsto_store_upd_subst => /=; by Mapsto.\n    by Array_equiv.\n  + by Resolve_topsy.\n\n(**\n<<\nhmEnd -.> next *<- cst_e 0%Z;\n>>\n*)\n\nStep (fun s h => (var_e hmStart |~> Free **\n  var_e hmStart \\+ nat_e 1 |~> nat_e p \\+ nat_e sz \\- cst_e 2%Z **\n    Array (p + 2) (sz - 4) ** Array (p + sz - 2) 1 **\n    (var_e hmEnd \\+ nat_e 1|~> cst_e 0%Z)) s h /\\\n  [ var_e hmStart \\= nat_e p ]b_s /\\\n  [ var_e hmEnd \\= nat_e p \\+ nat_e sz \\- cst_e 2%Z ]b_s ).\n\ncase: H0 => H1 [H3 H4].\nrewrite -conAE in H1.\ncase_sepcon H1.\ncase_sepcon H1_h1.\nTArray_concat_split_l_l (sz - 4) H6.\ncase_sepcon H0.\nrewrite (_ : sz - 2 - (sz - 4) = 2) /= in H0_h22; last by ssromega.\ncase_sepcon H0_h22.\ncase_sepcon H0_h22_h222.\ncase: H0_h22_h222_h2221 => x H0_h22_h222_h2221.\nexists (cst_e x).\nCompose_sepcon h2221 (h221 \\U h21 \\U h1).\n- rewrite /next; by Mapsto.\n- rewrite /imp => h2221' [X1 X2] h' Hh'.\n  split.\n    rewrite -3!conAE.\n    Compose_sepcon (h221 \\U h21 \\U h1) h2221'; last by Mapsto.\n    Compose_sepcon (h21 \\U h1) h221.\n    Compose_sepcon h1 h21.\n    Compose_sepcon h11 h12; by Mapsto.\n    by Array_equiv.\n  rewrite /=; Compose_sepcon h221 heap.emp; last by done.\n  case: H0_h22_h221 => x0 H0_h22_h221.\n  exists x0; by Mapsto.\n  by Resolve_topsy.\n\n(**\n<<\nhmEnd -.> status *<- Allocated\n>>\n*)\n\nStep TT.\n\nrewrite /while.entails => s h [H1 [H3 h4]].\nrewrite -3!conAE in H1.\ncase_sepcon H1.\ncase_sepcon H1_h1.\ncase_sepcon H1_h1_h11.\ncase_sepcon H1_h1_h11_h111.\nrewrite /= in H1_h1_h12; case_sepcon H1_h1_h12.\ncase: H1_h1_h12_h121 => x H1_h1_h12_h121.\nexists (cst_e x).\nCompose_sepcon h121 (h122 \\U h11 \\U h2).\n- rewrite /status; by Mapsto.\n- rewrite /imp => h121' [X1 X2] h' Hh'.\n  Compose_sepcon (h11 \\U h122) (h121' \\U h2).\n  + eapply hl_Free with (h1 := h11 \\U h122) (h2 := heap.emp).\n    * by map_tac_m.Disj.\n    * by map_tac_m.Equal.\n    * reflexivity.\n    * reflexivity.\n    * Compose_sepcon (h1111 \\U h1112) h112; last by assumption.\n      Compose_sepcon h1111 h1112; first by Mapsto.\n      Compose_sepcon h1112 heap.emp; [by Mapsto | done].\n    * by apply hl_last.\n  + rewrite /mapstos /=.\n    Compose_sepcon h121' h2.\n    rewrite /status in X2; by Mapsto.\n    Compose_sepcon h2 heap.emp; [by Mapsto | done].\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/seplog/topsy_hmInit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24999511416865197}}
{"text": "From Perennial.base_logic.lib Require Import iprop own.\nFrom iris.proofmode Require Import base tactics classes.\nFrom iris.algebra Require Import auth dfrac gmap.\nFrom Perennial.algebra Require Import auth_frac.\nFrom iris.bi.lib Require Import fractional.\nFrom iris.prelude Require Import options.\n\n(* Monotone list. Almost exactly the \"mlist\" construction code by Hai Dang from the sra-gps proof of RCU,\n   just generalized slightly to operate over arbitrary lists instead of RCU data *)\n\nSection cmra_mlist.\n\n  Context (A: Type) `{EqDecision A}.\n  Implicit Types (D: list A).\n\n  Inductive mlist :=\n    | MList D : mlist\n    | MListBot : mlist.\n\n  Inductive mlist_equiv : Equiv mlist :=\n    | MList_equiv D1 D2:\n        D1 = D2 → MList D1 ≡ MList D2\n    | MListBot_equiv : MListBot ≡ MListBot.\n\n  Existing Instance mlist_equiv.\n  Local Instance mlist_equiv_Equivalence : @Equivalence mlist equiv.\n  Proof.\n    split.\n    - move => [|]; by constructor.\n    - move => [?|] [?|]; inversion 1; subst; by constructor.\n    - move => [?|] [?|] [?|];\n      inversion 1; inversion 1; subst; by constructor.\n  Qed.\n\n  Canonical Structure mlistC : ofe := discreteO mlist.\n\n  Local Instance mlist_valid : Valid mlist :=\n    λ x, match x with MList _ => True | MListBot => False end.\n\n  Local Instance mlist_op : Op mlist := λ x y,\n    match x, y with\n    | MList D1, MList D2 =>\n        if (decide (D1 `prefix_of` D2))\n        then MList D2\n        else\n          if (decide (D2 `prefix_of` D1))\n          then MList D1\n          else MListBot\n    | _, _ => MListBot\n    end.\n\n  Local Arguments op _ _ !_ !_ /.\n\n  Local Instance mlist_PCore : PCore mlist := Some.\n\n  Local Instance anti_symm_prefix_of : AntiSymm eq (@prefix A).\n  Proof.\n    intros l1 l2 Hpre1 Hpre2.\n    destruct Hpre1 as (D1'&Hpre1). destruct Hpre2 as (D2'&Hpre2).\n    rewrite Hpre2 in Hpre1.\n    apply (f_equal (length)) in Hpre1. rewrite ?app_length in Hpre1.\n    destruct D2', D1'; simpl in Hpre1; try lia.\n    by rewrite Hpre2 right_id.\n  Qed.\n\n  Global Instance mlist_op_comm: Comm equiv mlist_op.\n  Proof.\n    intros [D1|] [D2|]; auto. simpl.\n    destruct (decide _) as [Hpre1|Hnpre]; last auto.\n    destruct (decide _) as [Hpre2|Hnpre]; last auto.\n    constructor.\n    apply (anti_symm prefix); auto.\n  Qed.\n\n  Global Instance mlist_op_idemp : IdemP eq mlist_op.\n  Proof. intros [|]; [by simpl; rewrite decide_True|auto]. Qed.\n\n  Lemma mlist_op_l D1 D2 (Le: D1 `prefix_of` D2) :\n    MList D1 ⋅ MList D2 = MList D2.\n  Proof. simpl. case_decide; done. Qed.\n\n  Lemma mlist_op_r D1 D2 (Le: D1 `prefix_of` D2) :\n    MList D2 ⋅ MList D1 ≡ MList D2.\n  Proof. by rewrite (comm (op: Op mlist)) mlist_op_l. Qed.\n\n  Lemma prefix_of_down_total {X: Type} (l1 l2 l3: list X):\n    l1 `prefix_of` l3 →\n    l2 `prefix_of` l3 →\n    (l1 `prefix_of` l2 ∨ l2 `prefix_of` l1).\n  Proof.\n    destruct 1 as (l1'&Heq1).\n    destruct 1 as (l2'&Heq2).\n    rewrite Heq2 in Heq1.\n    apply app_eq_inv in Heq1 as [H2_is_prefix|H1_is_prefix].\n    { left. destruct H2_is_prefix as (k&?&?). exists k. eauto. }\n    { right. destruct H1_is_prefix as (k&?&?). exists k. eauto. }\n  Qed.\n\n  Global Instance mlist_op_assoc: Assoc equiv (op: Op mlist).\n  Proof.\n    intros [D1|] [D2|] [D3|]; eauto; simpl.\n    - repeat (case_decide; auto).\n      + rewrite !mlist_op_l; auto. etrans; eauto.\n      + simpl. repeat case_decide; last done; exfalso.\n        * feed pose proof (prefix_of_down_total D1 D2 D3); auto.\n          intuition.\n        * apply H1. by etrans.\n      + rewrite mlist_op_l; [by rewrite mlist_op_r|auto].\n      + rewrite !mlist_op_r; auto. by etrans.\n      + simpl. rewrite !decide_False; auto.\n      + simpl. rewrite !decide_False; auto.\n      + simpl. case_decide.\n        * exfalso. apply H. by etrans.\n        * case_decide; last done. exfalso.\n          feed pose proof (prefix_of_down_total D2 D3 D1); auto.\n          intuition.\n    - simpl. repeat case_decide; auto.\n  Qed.\n\n  Lemma mlist_included D1 D2 :\n    MList D1 ≼ MList D2 ↔ D1 `prefix_of` D2.\n  Proof.\n    split.\n    - move => [[?|]]; simpl; last inversion 1.\n      case_decide; first by (inversion 1; subst).\n      case_decide; inversion 1. by subst.\n    - intros. exists (MList D2). by rewrite mlist_op_l.\n  Qed.\n\n  Lemma mlist_valid_op D1 D2 :\n    ✓ (MList D1 ⋅ MList D2) → D1 `prefix_of` D2 ∨ D2 `prefix_of` D1.\n  Proof. simpl. case_decide; first by left. case_decide; [by right|done]. Qed.\n\n  Lemma mlist_core_self (X: mlist) : core X = X.\n  Proof. done. Qed.\n\n  Local Instance mlist_unit : Unit mlist := MList [].\n\n  Definition mlist_ra_mixin : RAMixin mlist.\n  Proof.\n    apply ra_total_mixin; eauto.\n    - intros [?|] [?|] [?|]; auto; inversion 1.\n      subst. simpl. repeat case_decide; done.\n    - by destruct 1; constructor.\n    - by destruct 1.\n    - apply mlist_op_assoc.\n    - apply mlist_op_comm.\n    - intros ?. by rewrite mlist_core_self idemp_L.\n    - intros [|] [|]; simpl; done.\n  Qed.\n\n  Canonical Structure mlistR := discreteR mlist mlist_ra_mixin.\n\n  Global Instance mlistR_cmra_discrete : CmraDiscrete mlistR.\n  Proof. apply discrete_cmra_discrete. Qed.\n\n  Definition mlist_ucmra_mixin : UcmraMixin mlist.\n  Proof.\n    split; [done| |auto]. intros [|]; [simpl|done].\n    reflexivity.\n  Qed.\n\n  Canonical Structure mlistUR :=\n    Ucmra mlist mlist_ucmra_mixin.\n\n  Lemma mlist_local_update D1 X D2 :\n    D1 `prefix_of` D2 → (MList D1, X) ~l~> (MList D2, MList D2).\n  Proof.\n    intros Le. rewrite local_update_discrete.\n    move => [[D3|]|] /= ? Eq; split => //; last first; move : Eq.\n    - destruct X; by inversion 1.\n    - destruct X; rewrite /cmra_op /= => Eq;\n      repeat case_decide; auto; inversion Eq; subst.\n      + constructor. by apply: anti_symm.\n      + by exfalso.\n      + constructor. apply : anti_symm; [done|by etrans].\n      + exfalso. apply H2. by etrans.\n  Qed.\n\n  Global Instance mlist_core_id (x : mlist) : CoreId x.\n  Proof. by constructor. Qed.\n\nEnd cmra_mlist.\n\nGlobal Arguments MList {_} _.\n\nDefinition fmlistUR (A: Type) {Heq: EqDecision A} := authUR (mlistUR A).\nClass fmlistG (A: Type) {Heq: EqDecision A} Σ :=\n  { fmlist_inG :> inG Σ (fmlistUR A) }.\nDefinition fmlistΣ (A: Type) {Heq: EqDecision A} : gFunctors :=\n  #[GFunctor (fmlistUR A)].\n\nGlobal Instance subG_fmlistΣ (A: Type) {Heq: EqDecision A} {Σ} : subG (fmlistΣ A) Σ → (fmlistG A) Σ.\nProof. solve_inG. Qed.\n\nSection fmlist_props.\nContext `{fmlistG A Σ}.\nImplicit Types l : list A.\n\nDefinition fmlist γ (dq : dfrac) l:= own γ (●{dq} (MList l)).\nDefinition fmlist_lb γ l := own γ (◯ (MList l)).\nDefinition fmlist_idx γ i a := (∃ l, ⌜ l !! i = Some a ⌝ ∗ fmlist_lb γ l)%I.\n\nLocal Instance inj_MList_equiv : Inj eq equiv (@MList A).\nProof. intros l1 l2. inversion 1. subst; eauto. Qed.\n\nLemma fmlist_agree_1 γ q1 q2 l1 l2:\n  fmlist γ q1 l1 -∗ fmlist γ q2 l2 -∗ ⌜ l1 = l2 ⌝.\nProof.\n  iIntros \"Hγ1 Hγ2\". iDestruct (own_valid_2 with \"Hγ1 Hγ2\") as %Hval.\n  apply auth_auth_dfrac_op_inv in Hval.\n  iPureIntro. apply (inj MList); auto.\nQed.\n\nLemma fmlist_agree_2 γ q1 l1 l2 :\n  fmlist γ q1 l1 -∗ fmlist_lb γ l2 -∗ ⌜ l2 `prefix_of` l1 ⌝.\nProof.\n  iIntros \"Hγ1 Hγ2\". iDestruct (own_valid_2 with \"Hγ1 Hγ2\") as %Hval.\n  by apply @auth_both_dfrac_valid_discrete in Hval as (?&Hle%mlist_included&?); last apply _.\nQed.\n\nLemma fmlist_lb_agree γ l1 l2 :\n  fmlist_lb γ l1 -∗ fmlist_lb γ l2 -∗ ⌜ l1 `prefix_of` l2 ∨ l2 `prefix_of` l1⌝.\nProof.\n  iIntros \"Hγ1 Hγ2\". iDestruct (own_valid_2 with \"Hγ1 Hγ2\") as %Hval.\n  revert Hval; rewrite -auth_frag_op auth_frag_valid => Hval.\n  iPureIntro. by apply mlist_valid_op in Hval.\nQed.\n\nLemma fmlist_idx_agree_1 γ i a1 a2:\n  fmlist_idx γ i a1 -∗ fmlist_idx γ i a2 -∗ ⌜ a1 = a2 ⌝.\nProof.\n  iDestruct 1 as (l1 Hlookup1) \"H1\".\n  iDestruct 1 as (l2 Hlookup2) \"H2\".\n  iDestruct (fmlist_lb_agree with \"H1 H2\") as %Hprefix.\n  iPureIntro.\n  destruct Hprefix as [Hpre|Hpre]; eapply prefix_lookup in Hpre; eauto; congruence.\nQed.\n\nLemma fmlist_idx_agree_2 γ q l i a :\n  fmlist γ q l -∗ fmlist_idx γ i a -∗ ⌜ l !! i = Some a ⌝.\nProof.\n  iIntros \"H1\".\n  iDestruct 1 as (l2 Hlookup2) \"H2\".\n  iDestruct (fmlist_agree_2 with \"H1 H2\") as %Hpre.\n  iPureIntro.\n  eapply prefix_lookup in Hpre; eauto; congruence.\nQed.\n\nLemma fmlist_lb_mono γ l1 l2:\n  l1 `prefix_of` l2 ->\n  fmlist_lb γ l2 -∗ fmlist_lb γ l1.\nProof.\n  iIntros (Hle) \"Hlb\".\n  rewrite /fmlist_lb.\n  iApply (own_mono with \"Hlb\").\n  apply @auth_frag_mono.\n  apply mlist_included; auto.\nQed.\n\nLemma fmlist_sep γ dq1 dq2 l:\n  fmlist γ (dq1 ⋅ dq2) l ⊣⊢ fmlist γ dq1 l ∗ fmlist γ dq2 l.\nProof.\n  iSplit.\n  - iIntros \"(Hm1&Hm2)\". iFrame.\n  - iIntros \"(Hm1&Hm2)\". iCombine \"Hm1 Hm2\" as \"$\".\nQed.\n\nLemma fmlist_to_lb γ dq l:\n  fmlist γ dq l ==∗ fmlist_lb γ l.\nProof.\n  iIntros \"Hm\".\n  iMod (own_update _ _ ((●{dq} (MList l)) ⋅ ◯ (MList l)) with \"Hm\") as \"(?&$)\"; last done.\n  { apply auth_frac_update_core_id; eauto. apply _. }\nQed.\n\nLemma fmlist_get_lb γ dq l:\n  fmlist γ dq l ==∗ fmlist γ dq l ∗ fmlist_lb γ l.\nProof.\n  iIntros \"Hm\".\n  iMod (own_update _ _ ((●{dq} (MList l)) ⋅ ◯ (MList l)) with \"Hm\") as \"(?&$)\"; last done.\n  { apply auth_frac_update_core_id; eauto. apply _. }\nQed.\n\nLemma fmlist_lb_to_idx γ l i a:\n  l !! i = Some a →\n  fmlist_lb γ l -∗ fmlist_idx γ i a.\nProof. iIntros (Hlookup) \"H\". iExists l. iFrame. eauto. Qed.\n\nLemma fmlist_update l' γ l:\n  l `prefix_of` l' ->\n  fmlist γ (DfracOwn 1) l ==∗ fmlist γ (DfracOwn 1) l' ∗ fmlist_lb γ l'.\nProof.\n  iIntros (Hlt) \"Hm\".\n  iMod (own_update with \"Hm\") as \"($&?)\"; last done.\n  apply auth_update_alloc, mlist_local_update; auto.\nQed.\n\nLemma fmlist_freeze γ l q :\n  fmlist γ (DfracOwn q) l ==∗ fmlist γ (DfracDiscarded) l.\nProof.\n  iIntros \"Hm\".\n  iMod (own_update with \"Hm\") as \"$\"; last done.\n  apply auth_update_auth_persist.\nQed.\n\nLemma fmlist_alloc l :\n  ⊢ |==> ∃ γ, fmlist γ (DfracOwn 1) l.\nProof.\n  iStartProof.\n  iMod (own_alloc (● (MList l))) as (γ) \"H\".\n  { apply auth_auth_valid.\n    cbv; auto. }\n  iModIntro.\n  iExists _; iFrame.\nQed.\n\nGlobal Instance fmlist_lb_pers γ l: Persistent (fmlist_lb γ l).\nProof. rewrite /fmlist_lb. apply _. Qed.\n\nGlobal Instance fmlist_lb_timeless γ l: Timeless (fmlist_lb γ l).\nProof. apply _. Qed.\n\nGlobal Instance fmlist_idx_pers γ i a: Persistent (fmlist_idx γ i a).\nProof. apply _. Qed.\n\nGlobal Instance fmlist_idx_timeless γ i a: Timeless (fmlist_idx γ i a).\nProof. apply _. Qed.\n\nGlobal Instance fmlist_timeless γ q n: Timeless (fmlist γ q n).\nProof. apply _. Qed.\n\nGlobal Instance fmlist_fractional γ n: Fractional (λ q, fmlist γ (DfracOwn q) n).\nProof. intros p q. rewrite -fmlist_sep //. Qed.\n\nGlobal Instance fmlist_as_fractional γ q n :\n  AsFractional (fmlist γ (DfracOwn q) n) (λ q, fmlist γ (DfracOwn q) n) q.\nProof. split; first by done. apply _. Qed.\n\nGlobal Instance fmlist_into_sep γ n :\n  IntoSep (fmlist γ (DfracOwn 1) n) (fmlist γ (DfracOwn (1/2)) n) (fmlist γ (DfracOwn (1/2)) n).\nProof. apply _. Qed.\n\nGlobal Instance fmlist_discarded_pers γ l: Persistent (fmlist γ DfracDiscarded l).\nProof. apply _. Qed.\n\nEnd fmlist_props.\n\nTypeclasses Opaque fmlist fmlist_lb fmlist_idx.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/algebra/mlist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24999511416865194}}
{"text": "Require Export VST.floyd.proofauto.\nRequire Export CertiGraph.lib.find_lemmas.\nRequire Export CertiGraph.priq.is_empty_lemmas.\nRequire Export CertiGraph.priq.priq_arr.\n\n(* Specs for Anshuman's simple array-based PQ *)\nSection PQSpec.\n\nContext {size : Z}.\nContext {inf : Z}.\nParameter free_tok : val -> Z -> mpred.\nContext {Z_EqDec : EquivDec.EqDec Z eq}. \n\nDefinition weight_inrange_priq item :=\n  Int.min_signed <= item <= inf.\n\nDefinition inrange_priq (priq : list Z) :=\n  Forall (fun x => Int.min_signed <= x <= inf + 1) priq.\n\nDefinition mallocN_spec {CS: compspecs} :=\n  DECLARE _mallocN\n  WITH n: Z\n  PRE [tint]\n  PROP (4 <= n <= Int.max_unsigned)\n  PARAMS (Vint (Int.repr n))\n  GLOBALS ()\n  SEP ()\n  POST [ tptr tvoid ]\n  EX v: pointer_val,\n  PROP (malloc_compatible n (pointer_val_val v))\n  LOCAL (temp ret_temp (pointer_val_val v))\n  SEP (data_at_ Tsh (tarray tint (n / sizeof tint)) (pointer_val_val v) *\n       free_tok (pointer_val_val v) n).\n\nDefinition freePQ_spec {CS: compspecs} :=\n  DECLARE _freePQ\n  WITH sh: share, p: pointer_val, n: Z, contents: list Z\n    PRE [tptr tvoid]\n    PROP ()\n    PARAMS (pointer_val_val p)\n    GLOBALS ()\n    SEP (data_at sh (tarray tint n)\n                 (map Vint (map Int.repr contents))\n                 (pointer_val_val p) *\n        free_tok (pointer_val_val p) (sizeof tint * n))\n  POST [tvoid]\n    PROP () LOCAL () SEP (emp).\n\nDefinition init_spec {CS: compspecs} :=\n  DECLARE _init\n  WITH _: unit (* how to take nothing? *)\n  PRE [tint]\n  PROP (Int.min_signed <= size * 4 <= Int.max_signed;\n       0 < size)\n  PARAMS (Vint (Int.repr size))\n  GLOBALS ()\n  SEP ()\n  POST [tptr tint]\n  EX pq: pointer_val,\n  PROP ()\n  LOCAL (temp ret_temp (pointer_val_val pq))\n  SEP (data_at_ Tsh (tarray tint size) (pointer_val_val pq) *\n      free_tok (pointer_val_val pq) (sizeof tint * size)).\n\nDefinition push_spec {CS: compspecs} :=\n  DECLARE _push\n  WITH pq: val, vertex : Z, weight : Z, priq_contents_val: list val\n  PRE [tint, tint, tptr tint]\n  PROP (0 <= vertex < size;\n       (@weight_inrange_priq weight))\n  PARAMS (Vint (Int.repr vertex);\n          Vint (Int.repr weight);\n          pq)\n  GLOBALS ()\n  SEP (data_at Tsh (tarray tint size) priq_contents_val pq)\n  POST [tvoid]\n  PROP ()\n  LOCAL ()\n  SEP (data_at Tsh (tarray tint size)\n               (upd_Znth vertex\n                         priq_contents_val (Vint (Int.repr weight))) pq).\n    \nDefinition pq_emp_spec {CS: compspecs} := \n  DECLARE _pq_emp\n  WITH pq: val, priq_contents: list Z\n  PRE [tint, tint, tptr tint]\n  PROP (@inrange_priq priq_contents;\n       0 <= size <= Int.max_signed;\n       0 <= inf;\n       Int.min_signed < inf + 1 <= Int.max_signed)\n   PARAMS (Vint (Int.repr size);\n           Vint (Int.repr inf);\n           pq)\n   GLOBALS ()\n   SEP (data_at Tsh (tarray tint size) (map Vint (map Int.repr priq_contents)) pq)\n  POST [ tint ]\n   PROP ()\n   LOCAL (temp ret_temp (@isEmpty inf priq_contents))\n   SEP (data_at Tsh (tarray tint size) (map Vint (map Int.repr priq_contents)) pq).\n\nDefinition adjustWeight_spec {CS: compspecs} :=\n  DECLARE _adjustWeight\n  WITH pq: val, vertex : Z, newWeight : Z, priq_contents: list Z\n  PRE [tint, tint, tptr tint]\n  PROP (0 <= vertex < size;\n       @weight_inrange_priq newWeight)\n  PARAMS (Vint (Int.repr vertex);\n          Vint (Int.repr newWeight);\n          pq)\n  GLOBALS ()\n  SEP (data_at Tsh (tarray tint size) (map Vint (map Int.repr priq_contents)) pq)\n  POST [tvoid]\n  PROP ()\n  LOCAL ()\n  SEP (data_at Tsh (tarray tint size)\n               (upd_Znth vertex\n                  (map Vint (map Int.repr priq_contents)) (Vint (Int.repr newWeight))) pq).\n\nDefinition popMin_spec {CS: compspecs} :=\n  DECLARE _popMin\n  WITH pq: val, priq_contents: list Z\n  PRE [tint, tint, tptr tint]\n   PROP (@inrange_priq priq_contents;\n        @isEmpty inf priq_contents = Vzero;\n        0 < size <= Int.max_signed;\n        0 <= inf;\n        Int.min_signed < inf + 1 <= Int.max_signed)\n   PARAMS (Vint (Int.repr size);\n           Vint (Int.repr inf);\n           pq)\n   GLOBALS ()\n   SEP   (data_at Tsh (tarray tint size) (map Vint (map Int.repr priq_contents)) pq)\n  POST [ tint ]\n   EX rt : Z,\n   PROP (rt = find priq_contents (fold_right Z.min (hd 0 priq_contents) priq_contents) 0)\n   LOCAL (temp ret_temp  (Vint (Int.repr rt)))\n   SEP   (data_at Tsh (tarray tint size) (upd_Znth\n                                            (find priq_contents (fold_right Z.min (Znth 0 priq_contents) priq_contents) 0)\n                                            (map Vint (map Int.repr priq_contents)) (Vint (Int.repr (inf+1)))) pq).\n\nDefinition Gprog {CS: compspecs}: funspecs :=\n  ltac:(with_library prog\n                     [mallocN_spec;\n                     freePQ_spec;\n                     init_spec;\n                     push_spec;\n                     pq_emp_spec;\n                     adjustWeight_spec;\n                     popMin_spec]).\n\nEnd PQSpec.\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/priq/priq_arr_specs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2499951077019508}}
{"text": "Require Export Ascii String.\n\nRequire Import QArith.\nRequire Export DTimeQ.\n\nRequire Export MinBFT.\nRequire Export RunSM.\n\nRequire Export ComponentSM2.\nRequire Export ComponentSM4.\n\n\n\n\n\n(* ================== MINBFT CONTEXT ================== *)\n\nDefinition minbft_digest : Set := list nat.\n\nDefinition minbft_digest_def : minbft_digest := [].\n\nLemma minbft_digest_deq : Deq minbft_digest.\nProof.\n  introv; apply list_eq_dec.\n  apply deq_nat.\nDefined.\n\nInductive sending_key_stub : Set :=\n| minbft_sending_key_stub.\n\nInductive receiving_key_stub : Set :=\n| minbft_receiving_key_stub.\n\nDefinition minbft_sending_key   : Set := sending_key_stub.\nDefinition minbft_receiving_key : Set := receiving_key_stub.\n\n(*Definition F : nat := 1.*)\nDefinition nreps (F : nat) : nat := 2 * F + 1.\n\nDefinition replica (F : nat) : Set := nat_n (nreps F).\n\nLemma replica_deq (F : nat) : Deq (replica F).\nProof.\n  apply nat_n_deq.\nDefined.\n\nDefinition reps2nat (F : nat) : replica F -> nat_n (nreps F) := fun n => n.\n\nLemma bijective_reps2nat (F : nat) : bijective (reps2nat F).\nProof.\n  exists (fun n : nat_n (nreps F) => n); introv; unfold reps2nat; auto.\nDefined.\n\nDefinition replica0 (F : nat) : replica F.\nProof.\n  exists 0.\n  apply leb_correct.\n  unfold nreps.\n  omega.\nDefined.\n\nDefinition replica1 : replica 1.\nProof.\n  exists 1.\n  apply leb_correct.\n  unfold nreps.\n  omega.\nDefined.\n\nDefinition replica2 : replica 1.\nProof.\n  exists 2.\n  apply leb_correct.\n  unfold nreps.\n  omega.\nDefined.\n\nDefinition nclients (C : nat) : nat := S C.\n\nDefinition client (C : nat) : Set := nat_n (nclients C).\n\nDefinition client0 (C : nat) : client C.\nProof.\n  exists 0.\n  apply leb_correct.\n  unfold nclients.\n  omega.\nDefined.\n\nLemma client_deq (C : nat) : Deq (client C).\nProof.\n  apply nat_n_deq.\nDefined.\n\nDefinition clients2nat (C : nat) : client C -> nat_n (nclients C) := fun n => n.\n\nLemma bijective_clients2nat (C : nat) : bijective (clients2nat C).\nProof.\n  exists (fun n : nat_n (nclients C) => n); introv; unfold clients2nat; auto.\nDefined.\n\nInductive minbft_data_message :=\n| minbft_data_message_plus (n : nat)\n| minbft_data_message_minus (n : nat).\n\nLemma minbft_data_message_deq : Deq minbft_data_message.\nProof.\n  introv; destruct x as [x|x], y as [y|y];\n    destruct (deq_nat x y); prove_dec.\nDefined.\n\nDefinition minbft_result := nat.\n\nLemma minbft_result_deq : Deq minbft_result.\nProof.\n  introv; apply deq_nat.\nDefined.\n\nDefinition minbft_sm_state := nat.\n\nDefinition minbft_sm_initial_state : minbft_sm_state := 0.\n\nDefinition minbft_sm_update\n           (C : nat)\n           (c : client C)\n           (s : minbft_sm_state)\n           (m : minbft_data_message) : minbft_result * minbft_sm_state :=\n  match m with\n  | minbft_data_message_plus  n => let x := s + n in (x,x)\n  | minbft_data_message_minus n => let x := s - n in (x,x)\n  end.\n\nDefinition F := 1.\nDefinition C := 0.\n\nGlobal Instance MinBFT_I_context : MinBFT_context :=\n  Build_MinBFT_context\n    minbft_digest\n    minbft_digest_deq\n    minbft_sending_key\n    minbft_receiving_key\n    F\n    (replica F)\n    (replica_deq F)\n    (reps2nat F)\n    (bijective_reps2nat F)\n    (nclients C)\n    (client C)\n    (client_deq C)\n    (clients2nat C)\n    (bijective_clients2nat C)\n    minbft_data_message\n    minbft_data_message_deq\n    minbft_result\n    minbft_result_deq\n    minbft_sm_state\n    minbft_sm_initial_state\n    (minbft_sm_update C).\n\n\n\n\n(* =========================== *)\n(* ====== GENERIC STUFF ====== *)\n\n(* Replace during extraction *)\nInductive ref_stub (T : Type) :=\n| ref_stub_cons (t : T).\nGlobal Arguments ref_stub_cons [T] _.\n\n(* Replace during extraction *)\nDefinition ref_stub_get {T : Type} (t : ref_stub T) : T :=\n  match t with\n  | ref_stub_cons t => t\n  end.\n\n(* Replace during extraction *)\nDefinition ref_stub_update {T : Type} (r : ref_stub T) (t : T) : unit := tt.\n\nDefinition lookup_table : ref_stub (list {cn : CompName & {n : nat & cio_I (fio cn) -> (unit * cio_O (fio cn))}}) :=\n  ref_stub_cons [].\n\nDefinition update_lookup (level : nat) (name : CompName) (sm : cio_I (fio name) -> (unit * cio_O (fio name))) :=\n  ref_stub_update\n    lookup_table\n    ((existT _ name (existT _ level sm)) :: ref_stub_get lookup_table).\n\nModule Type SM.\n  Parameter level : nat.\n  Parameter name  : CompName.\n  Parameter sm    : n_proc level name.\nEnd SM.\n\nModule Type SMat.\n  Parameter level : nat.\n  Parameter name  : CompName.\n  Parameter sm    : n_proc_at level name.\nEnd SMat.\n\nModule Msm (sm : SM).\n  Definition state : ref_stub (sf sm.name) := ref_stub_cons (sm2state sm.sm).\n\n  Definition update (i : cio_I (fio sm.name)) : unit * cio_O (fio sm.name) :=\n    let (sop,o) := M_break_nil (sm2update sm.sm (ref_stub_get state) i) in\n    let u := match sop with | Some s => ref_stub_update state s| None => tt end in\n    (u,o).\n\n  Fixpoint run (l : list (cio_I (fio sm.name))) : list (cio_O (fio sm.name)) :=\n    match l with\n    | [] => []\n    | i :: rest => snd (update i) :: run rest\n    end.\n\n  Definition upd_lkup := update_lookup sm.level sm.name update.\nEnd Msm.\n\nModule Msmat (sm : SMat).\n  Definition state : ref_stub (sf sm.name) := ref_stub_cons (ComponentSM.sm_state sm.sm).\n\n  Definition update (i : cio_I (fio sm.name)) : unit * cio_O (fio sm.name) :=\n    let (sop,o) := M_break_nil (sm_update sm.sm (ref_stub_get state) i) in\n    let u := match sop with | Some s => ref_stub_update state s | None => tt end in\n    (u,o).\n\n  Fixpoint run (l : list (cio_I (fio sm.name))) : list (cio_O (fio sm.name)) :=\n    match l with\n    | [] => []\n    | i :: rest => snd (update i) :: run rest\n    end.\n\n  Definition upd_lkup := update_lookup sm.level sm.name update.\nEnd Msmat.\n\n(* =========================== *)\n\n\n\n\n(* ================== SIGNATURE ================== *)\n\nDefinition minbft_create_signature\n           (m  : MinBFT_Bare_Msg)\n           (ks : sending_keys) : list MinBFT_digest := [minbft_digest_def].\n\nDefinition minbft_verify_signature\n           (m : MinBFT_Bare_Msg)\n           (n : name)\n           (k : receiving_key)\n           (a : MinBFT_digest) : bool := true.\n\nGlobal Instance MinBFT_I_auth : MinBFT_auth :=\n  MkMinBFT_auth minbft_create_signature minbft_verify_signature.\n\n\nDefinition minbft_lookup_replica_sending_key   (src : Rep)    : minbft_sending_key   := minbft_sending_key_stub.\nDefinition minbft_lookup_replica_receiving_key (dst : Rep)    : minbft_receiving_key := minbft_receiving_key_stub.\nDefinition minbft_lookup_client_sending_key    (c   : Client) : minbft_sending_key   := minbft_sending_key_stub.\nDefinition minbft_lookup_client_receiving_key  (c   : Client) : minbft_receiving_key := minbft_receiving_key_stub.\n\nDefinition initial_minbft_local_key_map_replicas (src : name) : local_key_map :=\n  match src with\n  | MinBFT_replica i =>\n    MkLocalKeyMap\n      (map (fun c => MkDSKey [MinBFT_client c] (minbft_lookup_client_sending_key c)) clients)\n      (map (fun c => MkDRKey [MinBFT_client c] (minbft_lookup_client_receiving_key c)) clients)\n  | MinBFT_client _ => MkLocalKeyMap [] []\n  end.\n\nGlobal Instance MinBFT_I_keys : MinBFT_initial_keys :=\n  MkMinBFT_initial_keys initial_minbft_local_key_map_replicas.\n\n\n\n(* ================== USIG HASH ================== *)\n\nDefinition minbft_create_hash_usig\n           (hd : HashData)\n           (lk : local_key_map) : MinBFT_digest := [].\n\nDefinition minbft_verify_hash_usig\n           (hd : HashData)\n           (d  : MinBFT_digest)\n           (lk : local_key_map) : bool := true.\n\nLemma minbft_verify_create_hash_usig :\n  forall (hd : HashData) (keys : local_key_map),\n    minbft_verify_hash_usig hd (minbft_create_hash_usig hd keys) keys = true.\nProof.\n  tcsp.\nQed.\n\nGlobal Instance MinBFT_I_usig_hash : USIG_hash :=\n  MkMinBFThash\n    minbft_create_hash_usig\n    minbft_verify_hash_usig\n    minbft_verify_create_hash_usig.\n\n\n\n(* ================== TIME ================== *)\n\nDefinition time_I_type : Set := unit.\n\nDefinition time_I_get_time : unit -> time_I_type := fun _ => tt.\n\nDefinition time_I_sub : time_I_type -> time_I_type -> time_I_type := fun _ _ => tt.\n\nDefinition time_I_2string : time_I_type -> string := fun _ => \"\".\n\nGlobal Instance TIME_I : Time.\nProof.\n  exists time_I_type.\n  { exact time_I_get_time. }\n  { exact time_I_sub. }\n  { exact time_I_2string. }\nDefined.\n\n\n\n(* ================== PRETTY PRINTING ================== *)\n\n(* Fix: to finish *)\nDefinition tokens2string (toks : Tokens) : string := \"-\".\n\n(* Fix: to finish *)\nDefinition minbft_digest2string (d : minbft_digest) : string := \"-\".\n\n(* Fix: to finish *)\nDefinition minbft_result2string (r : minbft_result) : string := nat2string r.\n\n(* Fix: there's only one client anyway *)\nDefinition client2string (c : client C) : string := \"-\".\n\nDefinition timestamp2string (ts : Timestamp) : string :=\n  match ts with\n  | time_stamp n => nat2string n\n  end.\n\nDefinition view2string (v : View) : string :=\n  match v with\n  | view n => nat2string n\n  end.\n\nDefinition seq2string (s : SeqNum) : string :=\n  match s with\n  | seq_num n => nat2string n\n  end.\n\nDefinition minbft_data_message2string (opr : minbft_data_message) : string :=\n  match opr with\n  | minbft_data_message_plus  n => str_concat [\"+\", nat2string n]\n  | minbft_data_message_minus n => str_concat [\"-\", nat2string n]\n  end.\n\nDefinition nat_n2string {m} (n : nat_n m) : string := nat2string (proj1_sig n).\n\nDefinition replica2string (r : replica F) : string := nat_n2string r.\n\nDefinition bare_request2string (br : Bare_Request) : string :=\n  match br with\n  | bare_request c ts m =>\n    str_concat [client2string c,\n                \",\",\n                timestamp2string ts,\n                \",\",\n                minbft_data_message2string m]\n  end.\n\nDefinition request2string (r : Request) : string :=\n  match r with\n  | request br a => str_concat [\"REQUEST(\", bare_request2string br, \",\", tokens2string a, \")\"]\n  end.\n\nDefinition bare_prepare2string (bp : Bare_Prepare) : string :=\n  match bp with\n  | bare_prepare v m =>\n    str_concat [view2string v,\n                \",\",\n                request2string m]\n  end.\n\nDefinition pre_ui2string (pui : preUI) : string :=\n  match pui with\n  | Build_preUI id counter =>\n    str_concat [replica2string id,\n                \",\",\n                nat2string counter]\n  end.\n\nDefinition ui2string (ui : UI) : string :=\n  match ui with\n  | Build_UI pui d =>\n    str_concat [pre_ui2string pui,\n                \",\",\n                minbft_digest2string d]\n  end.\n\nDefinition bare_commit2string (bc : Bare_Commit) : string :=\n  match bc with\n  | bare_commit v m ui =>\n    str_concat [view2string v,\n                \",\",\n                request2string m,\n                \",\",\n                ui2string ui]\n  end.\n\nDefinition prepare2string (p : Prepare) : string :=\n  match p with\n  | prepare bp a => str_concat [\"PREPARE(\", bare_prepare2string bp, \",\", ui2string a, \")\"]\n  end.\n\nDefinition commit2string (c : Commit) : string :=\n  match c with\n  | commit bc a => str_concat [\"COMMIT(\", bare_commit2string bc, \",\", ui2string a, \")\"]\n  end.\n\nDefinition accept2string (r : Accept) : string :=\n  match r with\n  | accept r c => str_concat [\"ACCEPT(\", request2string r, \",\", nat2string c, \")\"]\n  end.\n\nDefinition bare_reply2string (br : Bare_Reply) : string :=\n  match br with\n  | bare_reply req res i v => str_concat [request2string req, \",\", nat2string res, \",\", replica2string i, \",\", view2string v]\n  end.\n\nDefinition reply2string (r : Reply) : string :=\n  match r with\n  | reply br a => str_concat [\"REPLY(\", bare_reply2string br, \",\", tokens2string a, \")\"]\n  end.\n\n\nDefinition msg2string (m : MinBFT_msg) : string :=\n  match m with\n  | MinBFT_request r => request2string r\n  | MinBFT_reply r   => reply2string r\n  | MinBFT_prepare p => prepare2string p\n  | MinBFT_commit  c => commit2string  c\n  | MinBFT_accept  a => accept2string  a\n  | MinBFT_debug   s => s\n  end.\n\nDefinition name2string (n : name) : string :=\n  match n with\n  | MinBFT_replica r => replica2string r\n  | MinBFT_client c => client2string c\n  end.\n\nFixpoint names2string (l : list name) : string :=\n  match l with\n  | [] => \"\"\n  | [n] => name2string n\n  | n :: ns => str_concat [name2string n, \",\", names2string ns]\n  end.\n\nDefinition delay2string (delay : nat) : string := nat2string delay.\n\nDefinition z2string (z : Z) : string := \"\".\nDefinition pos2string (p : positive) : string := \"\".\n\nDefinition q2string (q : Q) : string :=\n  str_concat [\"(\" ,\n              z2string (Qnum q),\n              \"/\",\n              pos2string (Qden q),\n              \")\"].\n\nDefinition posdtime2string (p : PosDTime) : string :=\n  q2string (pos_dt_t p).\n\nDefinition DirectedMsg2string (dm : DirectedMsg) : string :=\n  match dm with\n  | MkDMsg msg dst delay =>\n    str_concat [msg2string msg, \":\", \"[\", names2string dst, \"]\", \":\", posdtime2string delay]\n  end.\n\nFixpoint DirectedMsgs2string (l : DirectedMsgs) : string :=\n  match l with\n  | [] => \"\"\n  | [dm] => DirectedMsg2string dm\n  | dm :: dmsgs => str_concat [DirectedMsg2string dm, CR, DirectedMsgs2string dmsgs]\n  end.\n\nDefinition TimedDirectedMsg2string (m : TimedDirectedMsg) : string :=\n  match m with\n  | MkTimedDMsg dm time => str_concat [DirectedMsg2string dm, \":\", time_I_2string time]\n  end.\n\nFixpoint TimedDirectedMsgs2string (l : TimedDirectedMsgs) : string :=\n  match l with\n  | [] => \"\"\n  | [dm] => TimedDirectedMsg2string dm\n  | dm :: dmsgs => str_concat [TimedDirectedMsg2string dm, CR, TimedDirectedMsgs2string dmsgs]\n  end.\n\nDefinition SimState2string (s : SimState) : string :=\n  match s with\n  | MkSimState fls sys step out_inflight in_inflight delivered =>\n    str_concat\n      [CR,\n       \"====== STEP ======\",\n       CR,\n       nat2string step,\n       CR,\n       \"====== IN FLIGHT (from outside the system) ======\",\n       CR,\n       DirectedMsgs2string out_inflight,\n       CR,\n       \"====== IN FLIGHT (from inside the system) ======\",\n       CR,\n       DirectedMsgs2string in_inflight,\n       CR,\n       \"====== DELIVERED ======\",\n       CR,\n       TimedDirectedMsgs2string delivered,\n       CR]\n  end.\n\n  (* ================== SYSTEM ================== *)\n\n  (* FIX: do we need this one? *)\n  Definition dummy_usig_initial_state : USIG_state :=\n    Build_USIG\n      replica1\n      0\n      (MkLocalKeyMap [] []).\n\n  (* do we need this one? *)\n  Definition dummy_log_initial_state : LOG_state := [].\n\n  (* do we need this one? *)\n  Definition dummy_initial_state : MAIN_state :=\n    Build_State\n      (MkLocalKeyMap [] [])\n      initial_view\n      MinBFT_sm_initial_state\n      initial_latest_executed_counter\n      initial_latest_executed_request\n      initial_highest_received_counter_value\n      None.\n\n  Definition dummy_LocalSystem : MLocalSystem 0 1 :=\n    MkLocalSystem\n      (MP_haltedSM munit_comp_name 0 tt)\n      [].\n\n  Definition MinBFT_instance_sys : M_USystem MinBFTfunLevelSpace :=\n    fun name =>\n      match name with\n      | MinBFT_replica n => MinBFTlocalSys n\n      | _ =>  MkLocalSystem (MP_haltedSM munit_comp_name 0 tt) []\n      end.\n\n(* ================== STATE ================== *)\n\nDefinition mk_request\n           (c  : Client)\n           (ts : Timestamp)\n           (m  : MinBFT_data_message) : msg :=\n  MinBFT_request (request (bare_request c ts m) [minbft_digest_def]).\n\nDefinition send_request\n           (c  : Client)\n           (ts : Timestamp)\n           (m  : MinBFT_data_message) :=\n  MkDMsg\n    (mk_request c ts m)\n    [MinBFT_replica (MinBFTprimary (view 0))]\n    ('0).\n\nDefinition minbft_init_sim_state : SimState :=\n  let c  := client0 C in\n  let ts := time_stamp 0 in\n  let m  := minbft_data_message_plus 17 in\n  MkInitSimState\n    MinBFTsys\n    [send_request c ts m].\n\nDefinition minbft_sim_state1 : SimState :=\n  run_n_steps [0,0] minbft_init_sim_state.\n\nEval compute in (let p0  := replica0 F in\n                 let km  := initial_minbft_local_key_map_replicas (MinBFT_replica p0) in\n                 let c   := client0 C in\n                 let ts  := time_stamp 0 in\n                 let m   := minbft_data_message_plus 17 in\n                 let r   := request (bare_request c ts m) [minbft_digest_def] in\n                 let s   := initial_state p0 in\n                 valid_request p0 km r s).\n\nEval compute in (let v   := view 0 in\n                 let p0  := replica0 F in\n                 let p1  := replica1 in\n                 let km  := initial_minbft_local_key_map_replicas (MinBFT_replica p1) in\n                 let c   := client0 C in\n                 let ts  := time_stamp 0 in\n                 let m   := minbft_data_message_plus 17 in\n                 let r   := request (bare_request c ts m) [minbft_digest_def] in\n                 let ui  := snd (create_UI v r (USIG_initial p0)) in\n                 let p   := prepare (bare_prepare v r) ui in\n                 let s   := initial_state p1 in\n                 valid_prepare p1 km v p s).\n\n\n\n\n(* ================== EXTRACTION ================== *)\n\n\nExtraction Language Ocaml.\n\n\n(* printing stuff *)\nExtract Inlined Constant print_endline => \"Prelude.print_coq_endline\".\nExtract Inlined Constant nat2string    => \"Prelude.char_list_of_int\".\nExtract Inlined Constant CR            => \"['\\n']\".\n\n(* numbers *)\nExtract Inlined Constant Nat.modulo    => \"(mod)\".\n\n(* lists *)\nExtract Inlined Constant forallb => \"List.for_all\".\nExtract Inlined Constant existsb => \"List.exists\".\nExtract Inlined Constant length  => \"List.length\".\nExtract Inlined Constant app     => \"List.append\".\nExtract Inlined Constant map     => \"List.map\".\nExtract Inlined Constant filter  => \"List.filter\".\n\n(* timing stuff *)\nExtract Inlined Constant time_I_type     => \"float\".\nExtract Inlined Constant time_I_get_time => \"Prelude.Time.get_time\".\nExtract Inlined Constant time_I_sub      => \"Prelude.Time.sub_time\".\nExtract Inlined Constant time_I_2string  => \"Prelude.Time.time2string\".\n\n\nRequire Export ExtrOcamlBasic.\nRequire Export ExtrOcamlNatInt.\nRequire Export ExtrOcamlString.\n\n\n(* do we still need this one?\nDefinition MinBFT_sim_state_pp : unit :=\n  print_endline (SimState2string minbft_sim_state1).\n\nExtraction \"MinBFTtest.ml\" MinBFT_sim_state_pp.\n*)\n\nDefinition local_system:=\n  @MinBFTlocalSys.\n\n\n\n(* ================== MODULES ================== *)\n\nParameter self : Rep.\n\n(* ====== USIG ====== *)\n\nModule SMUSIG <: SM.\n  Definition level := 1.\n  Definition name  := USIGname.\n  Definition sm    := USIG_comp self.\nEnd SMUSIG.\n\nModule MUSIG := Msm (SMUSIG).\n\n\n(* ====== LOG ====== *)\n\nModule SMLOG <: SM.\n  Definition level := 1.\n  Definition name  := LOGname.\n  Definition sm    := LOG_comp.\nEnd SMLOG.\n\nModule MLOG := Msm (SMLOG).\n\n\n(* ====== Main ====== *)\n\nModule SMMAIN <: SMat.\n  Definition level := 1.\n  Definition name  := MAINname.\n  Definition sm    := MAIN_comp self.\nEnd SMMAIN.\n\nModule MMAIN := Msmat (SMMAIN).\n\n\nDefinition mtest : unit :=\n  let c  := client0 C in\n  let ts := time_stamp 0 in\n  let m  := minbft_data_message_plus 17 in\n  print_endline (DirectedMsgs2string (snd (MMAIN.update (mk_request c ts m)))).\n\n(* =========================== *)\n(* =========================== *)\n\n\n\nExtract Inductive ref_stub => \"ref\" [\"ref\"].\nExtract Inlined Constant ref_stub_get => \"!\".\nExtract Inlined Constant ref_stub_update => \"(:=)\".\n\nExtract Inductive sigT => \"(*)\" [\"\"].\n\nExtract Inductive Proc => \"Prelude.SM.id\" [\"Prelude.SM.ret\"\n                                             \"Prelude.SM.bind\"\n                                             \"Prelude.SM.call_proc lookup_table\"].\n(*Extract Inductive MP_StateMachine => \"MP_SM\" [\"Prelude.SM.mk_sm\"].*)\n\n(*Extract Constant MP_SM \"'p\" => \"n_proc\".*)\nExtract Constant n_proc => \"unit mP_StateMachine\".\nExtract Constant M_n \"'a\" => \"'a\".\nExtract Constant M_p \"'a\" \"'b\" => \"'b\".\nExtract Constant UProc \"'s\" => \"'s -> cio_I -> ('s * cio_O) m_n\".\n\n\nExtract Constant bind => \"fun _ _ _ _ _ _ _ _ _ m f -> Prelude.SM.bind (m,f)\".\nExtract Constant ret => \"fun _ _ _ _ _ _ _ _ _ a -> Prelude.SM.ret a\".\nExtract Constant M_on_pred => \"fun _ _ _ _ _ _ _ _ _ x -> x\".\nExtract Constant M_simple_break => \"fun _ _ _ _ _ _ _ _ _ sm subs f -> f sm\".\nExtract Constant M_break_nil => \"fun _ _ _ _ _ _ _ _ _ sm -> sm\".\n\n\nExtraction Inline interp_s_proc.\nExtraction Inline proc_bind_pair.\nExtraction Inline to_proc_some_state.\n\n\n\nExtract Inlined Constant interp_proc => \"(fun _ _ _ _ _ _ _ _ _ x -> x)\".\n(*Extract Inlined Constant interp_s_proc => \"\".\nExtract Inlined Constant incr_n_proc => \"\".\nExtract Inlined Constant incr_n_nproc => \"\".\nExtract Inlined Constant incr_n_procs => \"\".\nExtract Inlined Constant incr_pred_n_proc => \"\".\nExtract Inlined Constant incr_pred_n_nproc => \"\".\nExtract Inlined Constant incr_pred_n_procs => \"\".*)\n\n\nExtract Inlined Constant M_StateMachine => \"n_proc\".\nExtract Inlined Constant n_proc_at => \"n_proc\".\nExtract Inlined Constant n_procs => \"((unit mP_StateMachine) p_nproc) list\".\n(*Extract Inlined Constant sm_halted => \"Prelude.SM.sm_halted\".\nExtract Inlined Constant sm_update => \"Prelude.SM.sm_update\".\nExtract Inlined Constant sm_state => \"Prelude.SM.sm_state\".*)\n\n(*Extraction Implicit lift_M_O [1].*)\n\n\n(*Extract Constant M_Update \"'a\" => \"'a -> cio_I -> option 'a * cio_O\".*)\n(*Extract Constant n_nproc => \"unit MP_StateMachine\".*)\n(*Extract Constant n_proc_at => \"unit MP_StateMachine\".*)\n\n\nExtraction \"MinbftReplica.ml\" lookup_table MUSIG MLOG MMAIN mtest.\n\n(*\nThen:\n    (1) Move [lookup_table] to just above its first use (I'll fix that later)\n    (2) change the definition of self into [Obj.magic 0]\n    (3) Compile using: ocamlbuild -tag thread -use-ocamlfind -package ppx_jane,async,core_extended,batteries,rpc_parallel,nocrypto.unix MinbftReplica.native\n*)\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/runtime_w_sgx/MinBFTinstance_original.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2499951077019508}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU Lesser General Public License for more details.                *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\n(**********************************************************************\n    Proof of Huffman algorithm: Weight.v                             \n                                                                     \n                                                                     \n                                    Laurent.Thery@inria.fr (2003)    \n **********************************************************************)\n\nFrom Huffman Require Export Code.\nFrom Huffman Require Export Frequency.\nFrom Huffman Require Export ISort.\nFrom Huffman Require Export Permutation.\nFrom Huffman Require Export UniqueKey.\n\nSection Weight.\nVariable A : Type.\nVariable eqA_dec : forall a b : A, {a = b} + {a <> b}.\n \nTheorem fold_plus_split :\n forall (B : Type) (l : list B) (c : nat) (f : B -> nat),\n c + fold_left (fun (a : nat) (b : B) => a + f b) l 0 =\n fold_left (fun (a : nat) (b : B) => a + f b) l c.\nProof using.\nintros B l; elim l; simpl in |- *; auto.\nintros a l0 H c f.\nrewrite <- (H (f a)).\nrewrite <- (H (c + f a)).\nrewrite plus_assoc_reverse; auto.\nQed.\n \nTheorem fold_plus_permutation :\n forall (B : Type) (l1 l2 : list B) (c : nat) (f : B -> nat),\n permutation l1 l2 ->\n fold_left (fun (a : nat) (b : B) => a + f b) l1 c =\n fold_left (fun (a : nat) (b : B) => a + f b) l2 c.\nProof using.\nintros B l1 l2 c f H; generalize c f; elim H; clear H l1 l2 c f;\n simpl in |- *; auto.\nintros a b L c f; repeat rewrite <- plus_assoc; rewrite (plus_comm (f a));\n auto.\nintros L1 L2 L3 H H0 H1 H2 c f; apply trans_equal with (1 := H0 c f); auto.\nQed.\n \nTheorem length_encode_nId :\n forall a l1 l n,\n length (encode eqA_dec ((a, l1) :: l) (id_list a n)) = n * length l1.\nProof using.\nintros a l1 l n; elim n; simpl in |- *; auto.\nintros n0 H; case (eqA_dec a a); auto.\nintros e; rewrite length_app; rewrite H; auto.\nintros H1; case H1; auto.\nQed.\n \nTheorem frequency_length :\n forall (m : list A) (c : code A),\n unique_key c ->\n length (encode eqA_dec c m) =\n fold_left\n   (fun a b => a + number_of_occurrences eqA_dec (fst b) m * length (snd b))\n   c 0.\nProof using.\nintros m c; generalize m; elim c; clear c m; simpl in |- *; auto.\nintros m; elim m; simpl in |- *; auto.\nintros (a, l1) l Rec m H; simpl in |- *.\ncase (number_of_occurrences_permutation_ex A eqA_dec m a);\n intros m1 (Hm1, Hm2).\nrewrite\n permutation_length\n                    with\n                    (1 := \n                      encode_permutation_val _ eqA_dec _ _ ((a, l1) :: l) Hm1).\nrewrite encode_app; auto.\nrewrite length_app; auto.\nrewrite length_encode_nId.\nrewrite encode_cons_inv; auto.\nrewrite Rec; simpl in |- *; auto.\nrewrite <-\n fold_plus_split\n                 with\n                 (f := \n                   fun b : A * list bool =>\n                   number_of_occurrences eqA_dec (fst b) m * length (snd b))\n                (c := number_of_occurrences eqA_dec a m * length l1).\napply f_equal2 with (f := plus); auto.\ncut (forall l2, ~ In (a, l2) l).\nelim l; simpl in |- *; auto.\nintros (a2, l2) l3; simpl in |- *; intros Rec1 H4.\nrewrite <-\n fold_plus_split\n                 with\n                 (c := number_of_occurrences eqA_dec a2 m1 * length l2)\n                (f := \n                  fun b : A * list bool =>\n                  number_of_occurrences eqA_dec (fst b) m1 * length (snd b)).\nrewrite <-\n fold_plus_split\n                 with\n                 (c := number_of_occurrences eqA_dec a2 m * length l2)\n                (f := \n                  fun b : A * list bool =>\n                  number_of_occurrences eqA_dec (fst b) m * length (snd b)).\napply f_equal2 with (f := plus); auto.\n2: apply Rec1; auto.\n2: intros l0; red in |- *; intros H0; case (H4 l0); auto.\n2: intros l2; red in |- *; intros H0;\n    case unique_key_in with (1 := H) (a := a) (b2 := l2); \n    auto.\n2: apply unique_key_inv with (1 := H); auto.\napply f_equal2 with (f := mult); auto.\napply\n trans_equal\n  with\n    (2 := number_of_occurrences_permutation _ eqA_dec _ _ a2\n            (permutation_sym _ _ _ Hm1)).\nrewrite number_of_occurrences_app.\nreplace\n (number_of_occurrences eqA_dec a2\n    (id_list a (number_of_occurrences eqA_dec a m))) with 0; \n auto.\ncut (a2 <> a).\nelim (number_of_occurrences eqA_dec a m); simpl in |- *; auto.\nintros n H0 H1; case (eqA_dec a2 a); simpl in |- *; auto.\nintros e; case H1; auto.\nred in |- *; intros H0; case (H4 l2); left;\n apply f_equal2 with (f := pair (A:=A) (B:=list bool)); \n auto.\nQed.\n \nDefinition weight m c := length (encode eqA_dec c m).\n \nTheorem weight_permutation :\n forall m c1 c2,\n unique_prefix c1 -> permutation c1 c2 -> weight m c1 = weight m c2.\nProof using.\nintros m c1 c2 H H0; unfold weight in |- *.\napply f_equal with (f := length (A:=bool)).\napply encode_permutation; auto.\nQed.\n \nDefinition restrict_code (m : list A) (c : code A) : \n  code A :=\n  map (fun x => (fst x, find_code eqA_dec (fst x) c))\n    (frequency_list eqA_dec m).\n \nTheorem ulist_unique_key :\n forall (A B : Type) (l : list (A * B)),\n ulist (map (fst (B:=_)) l) -> unique_key l.\nProof using.\nintros AA BB l; elim l; simpl in |- *; auto.\nintros a; case a.\nintros a0 b l0 H H0; apply unique_key_cons; auto.\nintros b0; red in |- *; intros H1; absurd (In a0 (map (fst (B:=_)) l0)); auto.\ninversion H0; auto.\nchange (In (fst (a0, b0)) (map (fst (B:=_)) l0)) in |- *; auto with datatypes.\napply in_map; auto.\napply H; apply ulist_inv with (1 := H0); auto.\nQed.\n \nTheorem restrict_code_unique_key :\n forall (m : list A) (c : code A), unique_key (restrict_code m c).\nProof using.\nintros m c; apply ulist_unique_key.\nunfold restrict_code in |- *.\nreplace\n (map (fst (B:=_))\n    (map (fun x : A * nat => (fst x, find_code eqA_dec (fst x) c))\n       (frequency_list eqA_dec m))) with\n (map (fst (B:=_)) (frequency_list eqA_dec m)).\napply unique_key_ulist; auto.\nelim (frequency_list eqA_dec m); simpl in |- *; auto with datatypes.\nintros a l H; apply f_equal2 with (f := cons (A:=A)); auto.\nQed.\n\nTheorem restrict_code_in :\n forall (m : list A) (a : A) (c : code A),\n In a m -> find_code eqA_dec a c = find_code eqA_dec a (restrict_code m c).\nProof using.\nintros m a c H.\napply sym_equal; apply find_code_correct2; auto.\napply restrict_code_unique_key.\ngeneralize (in_frequency_map _ eqA_dec m a H).\nunfold restrict_code in |- *; elim (frequency_list eqA_dec m); simpl in |- *;\n auto with datatypes.\nintros a0; case a0; simpl in |- *; auto with datatypes.\nintros a1 n l H0 [H1| H1]; try rewrite H1; auto.\nQed.\n \nTheorem restrict_code_encode_length_inc :\n forall (m m1 : list A) (c : code A),\n incl m1 m -> encode eqA_dec c m1 = encode eqA_dec (restrict_code m c) m1.\nProof using.\nintros m m1 c; elim m1; simpl in |- *; auto.\nintros a l H H0.\napply f_equal2 with (f := app (A:=bool)); auto with datatypes.\napply restrict_code_in; auto with datatypes.\napply H; apply incl_tran with (2 := H0); auto with datatypes.\nQed.\n \nTheorem restrict_code_encode_length :\n forall (m : list A) (c : code A),\n encode eqA_dec c m = encode eqA_dec (restrict_code m c) m.\nProof using.\nintros m c; apply restrict_code_encode_length_inc; auto with datatypes.\nQed.\n \nEnd Weight.\nArguments weight [A].\nArguments restrict_code [A].\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/huffman/theories/Weight.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.24998474183179775}}
{"text": "(* * Syntax and semantics of the Jasmin source language *)\n\n(* ** Imports and settings *)\nFrom mathcomp Require Import all_ssreflect all_algebra.\nFrom mathcomp Require Import word_ssrZ.\nRequire Import Psatz xseq.\nRequire Export array type expr gen_map low_memory warray_ sem_type sem_op_typed values.\nRequire Export\n  flag_combination\n  sem_params.\nImport Utf8.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* ** Variable map\n * -------------------------------------------------------------------- *)\n\nNotation vmap     := (Fv.t (fun t => exec (sem_t t))).\n\nDefinition undef_addr t :=\n  match t return exec (sem_t t) with\n  | sbool | sint | sword _ => undef_error\n  | sarr n => ok (WArray.empty n)\n  end.\n\nDefinition vmap0 : vmap :=\n  @Fv.empty (fun t => exec (sem_t t)) (fun x => undef_addr x.(vtype)).\n\nDefinition on_vu t r (fv: t -> r) (fu:exec r) (v:exec t) : exec r :=\n  match v with\n  | Ok v => ok (fv v)\n  | Error ErrAddrUndef => fu\n  | Error e            => Error e\n  end.\n\nLemma on_vuP T R (fv: T -> R) (fu: exec R) (v:exec T) r P:\n  (forall t, v = ok t -> fv t = r -> P) ->\n  (v = undef_error -> fu = ok r -> P) ->\n  on_vu fv fu v = ok r -> P.\nProof. by case: v => [a | []] Hfv Hfu //=;[case; apply: Hfv | apply Hfu]. Qed.\n\n(* An access to a undefined value, leads to an error *)\nDefinition get_var (m:vmap) x :=\n  on_vu (@to_val (vtype x)) undef_error (m.[x]%vmap).\n\n(* Assigning undefined value is allowed only for bool *)\nDefinition set_var (m:vmap) x v : exec vmap :=\n  on_vu (fun v => m.[x<-ok v]%vmap)\n        (if is_sbool x.(vtype) then ok m.[x<-undef_addr x.(vtype)]%vmap\n         else type_error)\n        (of_val (vtype x) v).\n\nLemma set_varP (m m':vmap) x v P :\n   (forall t, of_val (vtype x) v = ok t -> m.[x <- ok t]%vmap = m' -> P) ->\n   ( is_sbool x.(vtype) -> of_val (vtype x) v = undef_error ->\n     m.[x<-undef_addr x.(vtype)]%vmap = m' -> P) ->\n   set_var m x v = ok m' -> P.\nProof.\n  move=> H1 H2;apply on_vuP => //.\n  by case:ifPn => // hb herr []; apply : H2.\nQed.\n\n(* ** Parameter expressions\n * -------------------------------------------------------------------- *)\n\nDefinition sem_sop1 (o: sop1) (v: value) : exec value :=\n  let t := type_of_op1 o in\n  Let x := of_val _ v in\n  ok (to_val (sem_sop1_typed o x)).\n\nLemma sem_sop1I y x f:\n  sem_sop1 f x = ok y →\n  exists2 w : sem_t (type_of_op1 f).1,\n    of_val _ x = ok w &\n    y = to_val (sem_sop1_typed f w).\nProof. by rewrite /sem_sop1; t_xrbindP => w ok_w <-; eauto. Qed.\n\nDefinition sem_sop2 (o: sop2) (v1 v2: value) : exec value :=\n  let t := type_of_op2 o in\n  Let x1 := of_val _ v1 in\n  Let x2 := of_val _ v2 in\n  Let r  := sem_sop2_typed o x1 x2 in\n  ok (to_val r).\n\nLemma sem_sop2I v v1 v2 f:\n  sem_sop2 f v1 v2 = ok v →\n  ∃ (w1 : sem_t (type_of_op2 f).1.1) (w2 : sem_t (type_of_op2 f).1.2)\n    (w3: sem_t (type_of_op2 f).2),\n    [/\\ of_val _ v1 = ok w1,\n        of_val _ v2 = ok w2,\n        sem_sop2_typed f w1 w2 = ok w3 &\n        v = to_val w3].\nProof.\n  by rewrite /sem_sop2; t_xrbindP => w1 ok_w1 w2 ok_w2 w3 ok_w3 <- {v}; exists w1, w2, w3.\nQed.\n\nDefinition sem_opN\n  {cfcd : FlagCombinationParams} (op: opN) (vs: values) : exec value :=\n  Let w := app_sopn _ (sem_opN_typed op) vs in\n  ok (to_val w).\n\nRecord estate\n  {syscall_state : Type}\n  {ep : EstateParams syscall_state} := Estate\n  {\n    escs : syscall_state;\n    emem : mem;\n    evm  : vmap\n  }.\n\nArguments Estate {syscall_state}%type_scope {ep} _ _ _.\n\nDefinition get_global_value (gd: glob_decls) (g: var) : option glob_value :=\n  assoc gd g.\n\nDefinition gv2val (gd:glob_value) := \n  match gd with\n  | Gword ws w => Vword w\n  | Garr p a   => Varr a \n  end.\n\nDefinition get_global gd g : exec value :=\n  if get_global_value gd g is Some ga then\n    let v := gv2val ga in\n    if type_of_val v == vtype g then ok v\n    else type_error\n  else type_error.\n\nLemma get_globalI gd g v :\n  get_global gd g = ok v →\n  exists gv : glob_value, [/\\ get_global_value gd g = Some gv, v = gv2val gv & type_of_val v = vtype g].\nProof.\n  rewrite /get_global; case: get_global_value => // gv.\n  by case:eqP => // <- [<-];exists gv.\nQed.\n\nDefinition get_gvar (gd: glob_decls) (vm: vmap) (x:gvar) :=\n  if is_lvar x then get_var vm x.(gv)\n  else get_global gd x.(gv).\n\nDefinition on_arr_var A (v:exec value) (f:forall n, WArray.array n -> exec A) :=\n  Let v := v  in\n  match v with\n  | Varr n t => f n t\n  | _ => type_error\n  end.\n\nNotation \"'Let' ( n , t ) ':=' s '.[' v ']' 'in' body\" :=\n  (@on_arr_var _ (get_var s.(evm) v) (fun n (t:WArray.array n) => body)) (at level 25, s at level 0).\n\nNotation \"'Let' ( n , t ) ':=' gd ',' s '.[' v ']' 'in' body\" :=\n  (@on_arr_var _ (get_gvar gd s.(evm) v) (fun n (t:WArray.array n) => body)) (at level 25, gd at level 0, s at level 0).\n\nLemma type_of_get_var x vm v :\n  get_var vm x = ok v ->\n  type_of_val v = x.(vtype).\nProof. by rewrite /get_var; apply : on_vuP => // t _ <-; apply type_of_to_val. Qed.\n\nLemma on_arr_varP {syscall_state : Type} {ep : EstateParams syscall_state}\n  A (f : forall n, WArray.array n -> exec A) v s x P :\n  (forall n t, vtype x = sarr n ->\n               get_var (evm s) x = ok (@Varr n t) ->\n               f n t = ok v -> P) ->\n  on_arr_var (get_var (evm s) x) f = ok v -> P.\nProof.\n  rewrite /on_arr_var=> H;apply: rbindP => vx hx.\n  have h := type_of_get_var hx; case: vx h hx => // len t h.\n  by apply: H;rewrite -h.\nQed.\n\nLemma type_of_get_global gd g v :\n  get_global gd g = ok v -> type_of_val v = vtype g. \nProof. by move=> /get_globalI [?[]]. Qed.\n\nLemma type_of_get_gvar x gd vm v :\n  get_gvar gd vm x = ok v ->\n  type_of_val v = vtype x.(gv).\nProof. \n  rewrite /get_gvar;case:ifP => ?.\n  + by apply type_of_get_var.\n  by apply type_of_get_global.\nQed.\n\nLemma on_arr_gvarP A (f : forall n, WArray.array n -> exec A) v gd s x P:\n  (forall n t, vtype x.(gv) = sarr n ->\n               get_gvar gd s x = ok (@Varr n t) ->\n               f n t = ok v -> P) ->\n  on_arr_var (get_gvar gd s x) f = ok v -> P.\nProof.\n  rewrite /on_arr_var=> H;apply: rbindP => vx hx.\n  have h := type_of_get_gvar hx; case: vx h hx => // len t h.\n  by apply: H;rewrite -h.\nQed.\n\nSection SEM_PEXPR.\n\nContext\n  {asm_op syscall_state : Type}\n  {ep : EstateParams syscall_state}\n  {spp : SemPexprParams}\n  (gd : glob_decls).\n\nFixpoint sem_pexpr (s:estate) (e : pexpr) : exec value :=\n  match e with\n  | Pconst z => ok (Vint z)\n  | Pbool b  => ok (Vbool b)\n  | Parr_init n => ok (Varr (WArray.empty n))\n  | Pvar v => get_gvar gd s.(evm) v\n  | Pget aa ws x e =>\n      Let (n, t) := gd, s.[x] in\n      Let i := sem_pexpr s e >>= to_int in\n      Let w := WArray.get aa ws t i in\n      ok (Vword w)\n  | Psub aa ws len x e =>\n      Let (n, t) := gd, s.[x] in\n      Let i := sem_pexpr s e >>= to_int in\n      Let t' := WArray.get_sub aa ws len t i in\n      ok (Varr t')\n  | Pload sz x e =>\n    Let w1 := get_var s.(evm) x >>= to_pointer in\n    Let w2 := sem_pexpr s e >>= to_pointer in\n    Let w  := read s.(emem) (w1 + w2)%R sz in\n    ok (@to_val (sword sz) w)\n  | Papp1 o e1 =>\n    Let v1 := sem_pexpr s e1 in\n    sem_sop1 o v1\n  | Papp2 o e1 e2 =>\n    Let v1 := sem_pexpr s e1 in\n    Let v2 := sem_pexpr s e2 in\n    sem_sop2 o v1 v2\n  | PappN op es =>\n    Let vs := mapM (sem_pexpr s) es in\n    sem_opN op vs\n  | Pif t e e1 e2 =>\n    Let b := sem_pexpr s e >>= to_bool in\n    Let v1 := sem_pexpr s e1 >>= truncate_val t in\n    Let v2 := sem_pexpr s e2 >>= truncate_val t in\n    ok (if b then v1 else v2)\n  end.\n\nDefinition sem_pexprs s := mapM (sem_pexpr s).\n\nDefinition write_var (x:var_i) (v:value) (s:estate) : exec estate :=\n  Let vm := set_var s.(evm) x v in\n  ok ({| escs := s.(escs); emem := s.(emem); evm := vm |}).\n\nDefinition write_vars xs vs s :=\n  fold2 ErrType write_var xs vs s.\n\nDefinition write_none (s:estate) ty v :=\n  on_vu (fun v => s) (if is_sbool ty then ok s else type_error)\n          (of_val ty v).\n\nDefinition write_lval (l:lval) (v:value) (s:estate) : exec estate :=\n  match l with\n  | Lnone _ ty => write_none s ty v\n  | Lvar x => write_var x v s\n  | Lmem sz x e =>\n    Let vx := get_var (evm s) x >>= to_pointer in\n    Let ve := sem_pexpr s e >>= to_pointer in\n    let p := (vx + ve)%R in (* should we add the size of value, i.e vx + sz * se *)\n    Let w := to_word sz v in\n    Let m :=  write s.(emem) p w in\n    ok {| escs := s.(escs); emem := m;  evm := s.(evm) |}\n  | Laset aa ws x i =>\n    Let (n,t) := s.[x] in\n    Let i := sem_pexpr s i >>= to_int in\n    Let v := to_word ws v in\n    Let t := WArray.set t aa i v in\n    write_var x (@to_val (sarr n) t) s\n  | Lasub aa ws len x i =>\n    Let (n,t) := s.[x] in\n    Let i := sem_pexpr s i >>= to_int in\n    Let t' := to_arr (Z.to_pos (arr_size ws len)) v in \n    Let t := @WArray.set_sub n aa ws len t i t' in\n    write_var x (@to_val (sarr n) t) s\n  end.\n\nDefinition write_lvals (s:estate) xs vs :=\n   fold2 ErrType write_lval xs vs s.\n\nEnd SEM_PEXPR.\n\nSection EXEC_SYSCALL.\n\nContext\n  {syscall_state : Type}\n  {scs : syscall_sem syscall_state} .\n\nDefinition exec_getrandom (scs : syscall_state) len vs :=\n  Let _ :=\n    match vs with\n    | [:: v] => to_arr len v\n    | _ => type_error\n    end in\n  let sd := get_random scs (Zpos len) in\n  Let t := WArray.fill len sd.2 in\n  ok (sd.1, [::Varr t]).\n\nDefinition exec_syscall\n  {pd : PointerData}\n  (scs : syscall_state_t)\n  (m : mem)\n  (o : syscall_t)\n  (vs : values) :\n  exec (syscall_state_t * mem * values) :=\n  match o with\n  | RandomBytes len =>\n      Let sv := exec_getrandom scs len vs in\n      ok (sv.1, m, sv.2)\n  end.\n\nEnd EXEC_SYSCALL.\n\nSection EXEC_ASM.\n\nContext\n  {asm_op syscall_state : Type}\n  {ep : EstateParams syscall_state}\n  {spp : SemPexprParams}\n  {asmop : asmOp asm_op}.\n\nDefinition exec_sopn (o:sopn) (vs:values) : exec values :=\n  let semi := sopn_sem o in\n  Let t := app_sopn _ semi vs in\n  ok (list_ltuple t).\n\nLemma sopn_toutP o vs vs' : exec_sopn o vs = ok vs' ->\n  List.map type_of_val vs' = sopn_tout o.\nProof.\n  rewrite /exec_sopn /sopn_tout /sopn_sem.\n  t_xrbindP => p _ <-;apply type_of_val_ltuple.\nQed.\n\nDefinition sem_sopn gd o m lvs args :=\n  sem_pexprs gd m args >>= exec_sopn o >>= write_lvals gd m lvs.\n\nEnd EXEC_ASM.\n\nSection SEM.\n\nContext\n  {asm_op syscall_state : Type}\n  {ep : EstateParams syscall_state}\n  {spp : SemPexprParams}\n  {sip : SemInstrParams asm_op syscall_state}\n  (P : uprog).\n\nNotation gd := (p_globs P).\n\nInductive sem : estate -> cmd -> estate -> Prop :=\n| Eskip s :\n    sem s [::] s\n\n| Eseq s1 s2 s3 i c :\n    sem_I s1 i s2 -> sem s2 c s3 -> sem s1 (i::c) s3\n\nwith sem_I : estate -> instr -> estate -> Prop :=\n| EmkI ii i s1 s2:\n    sem_i s1 i s2 ->\n    sem_I s1 (MkI ii i) s2\n\nwith sem_i : estate -> instr_r -> estate -> Prop :=\n| Eassgn s1 s2 (x:lval) tag ty e v v':\n    sem_pexpr gd s1 e = ok v ->\n    truncate_val ty v = ok v' →\n    write_lval gd x v' s1 = ok s2 ->\n    sem_i s1 (Cassgn x tag ty e) s2\n\n| Eopn s1 s2 t o xs es:\n    sem_sopn gd o s1 xs es = ok s2 ->\n    sem_i s1 (Copn xs t o es) s2\n\n| Esyscall s1 scs m s2 xs o es ves vs:\n    sem_pexprs gd s1 es = ok ves →\n    exec_syscall s1.(escs) s1.(emem) o ves = ok (scs, m, vs) →\n    write_lvals gd {| escs := scs; emem := m; evm := s1.(evm) |} xs vs = ok s2 →\n    sem_i s1 (Csyscall xs o es) s2\n\n| Eif_true s1 s2 e c1 c2 :\n    sem_pexpr gd s1 e = ok (Vbool true) ->\n    sem s1 c1 s2 ->\n    sem_i s1 (Cif e c1 c2) s2\n\n| Eif_false s1 s2 e c1 c2 :\n    sem_pexpr gd s1 e = ok (Vbool false) ->\n    sem s1 c2 s2 ->\n    sem_i s1 (Cif e c1 c2) s2\n\n| Ewhile_true s1 s2 s3 s4 a c e c' :\n    sem s1 c s2 ->\n    sem_pexpr gd s2 e = ok (Vbool true) ->\n    sem s2 c' s3 ->\n    sem_i s3 (Cwhile a c e c') s4 ->\n    sem_i s1 (Cwhile a c e c') s4\n\n| Ewhile_false s1 s2 a c e c' :\n    sem s1 c s2 ->\n    sem_pexpr gd s2 e = ok (Vbool false) ->\n    sem_i s1 (Cwhile a c e c') s2\n\n| Efor s1 s2 (i:var_i) d lo hi c vlo vhi :\n    sem_pexpr gd s1 lo = ok (Vint vlo) ->\n    sem_pexpr gd s1 hi = ok (Vint vhi) ->\n    sem_for i (wrange d vlo vhi) s1 c s2 ->\n    sem_i s1 (Cfor i (d, lo, hi) c) s2\n\n| Ecall s1 scs2 m2 s2 ii xs f args vargs vs :\n    sem_pexprs gd s1 args = ok vargs ->\n    sem_call s1.(escs) s1.(emem) f vargs scs2 m2 vs ->\n    write_lvals gd {|escs := scs2; emem:= m2; evm := s1.(evm) |} xs vs = ok s2 ->\n    sem_i s1 (Ccall ii xs f args) s2\n\nwith sem_for : var_i -> seq Z -> estate -> cmd -> estate -> Prop :=\n| EForDone s i c :\n    sem_for i [::] s c s\n\n| EForOne s1 s1' s2 s3 i w ws c :\n    write_var i (Vint w) s1 = ok s1' ->\n    sem s1' c s2 ->\n    sem_for i ws s2 c s3 ->\n    sem_for i (w :: ws) s1 c s3\n\nwith sem_call : syscall_state_t -> mem -> funname -> seq value -> syscall_state_t -> mem -> seq value -> Prop :=\n| EcallRun scs1 m1 scs2 m2 fn f vargs vargs' s1 vm2 vres vres' :\n    get_fundef (p_funcs P) fn = Some f ->\n    mapM2 ErrType truncate_val f.(f_tyin) vargs' = ok vargs ->\n    write_vars f.(f_params) vargs (Estate scs1 m1 vmap0) = ok s1 ->\n    sem s1 f.(f_body) (Estate scs2 m2 vm2) ->\n    mapM (fun (x:var_i) => get_var vm2 x) f.(f_res) = ok vres ->\n    mapM2 ErrType truncate_val f.(f_tyout) vres = ok vres' ->\n    sem_call scs1 m1 fn vargs' scs2 m2 vres'.\n\n(* We define a custom induction principle for program semantics. *)\nSection SEM_IND.\n\n  Variables\n    (Pc   : estate -> cmd -> estate -> Prop)\n    (Pi_r : estate -> instr_r -> estate -> Prop)\n    (Pi : estate -> instr -> estate -> Prop)\n    (Pfor : var_i -> seq Z -> estate -> cmd -> estate -> Prop)\n    (Pfun : syscall_state_t -> mem -> funname -> seq value -> syscall_state_t -> mem -> seq value -> Prop).\n\n  Definition sem_Ind_nil : Prop :=\n    forall s : estate, Pc s [::] s.\n\n  Definition sem_Ind_cons : Prop :=\n    forall (s1 s2 s3 : estate) (i : instr) (c : cmd),\n      sem_I s1 i s2 -> Pi s1 i s2 -> sem s2 c s3 -> Pc s2 c s3 -> Pc s1 (i :: c) s3.\n\n  Hypotheses\n    (Hnil: sem_Ind_nil)\n    (Hcons: sem_Ind_cons)\n  .\n\n  Definition sem_Ind_mkI : Prop :=\n    forall (ii : instr_info) (i : instr_r) (s1 s2 : estate),\n      sem_i s1 i s2 -> Pi_r s1 i s2 -> Pi s1 (MkI ii i) s2.\n\n  Hypothesis HmkI : sem_Ind_mkI.\n\n  Definition sem_Ind_assgn : Prop :=\n    forall (s1 s2 : estate) (x : lval) (tag : assgn_tag) ty (e : pexpr) v v',\n      sem_pexpr gd s1 e = ok v ->\n      truncate_val ty v = ok v' →\n      write_lval gd x v' s1 = Ok error s2 ->\n      Pi_r s1 (Cassgn x tag ty e) s2.\n\n  Definition sem_Ind_opn : Prop :=\n    forall (s1 s2 : estate) t (o : sopn) (xs : lvals) (es : pexprs),\n      sem_sopn gd o s1 xs es = Ok error s2 ->\n      Pi_r s1 (Copn xs t o es) s2.\n\n  Definition sem_Ind_syscall : Prop := \n    forall s1 scs m s2 xs o es ves vs,\n      sem_pexprs gd s1 es = ok ves →\n      exec_syscall s1.(escs) s1.(emem) o ves = ok (scs, m, vs) →\n      write_lvals gd {| escs := scs; emem := m; evm := s1.(evm) |} xs vs = ok s2 →\n      Pi_r s1 (Csyscall xs o es) s2.\n\n  Definition sem_Ind_if_true : Prop :=\n    forall (s1 s2 : estate) (e : pexpr) (c1 c2 : cmd),\n      sem_pexpr gd s1 e = ok (Vbool true) ->\n      sem s1 c1 s2 -> Pc s1 c1 s2 -> Pi_r s1 (Cif e c1 c2) s2.\n\n  Definition sem_Ind_if_false : Prop :=\n    forall (s1 s2 : estate) (e : pexpr) (c1 c2 : cmd),\n      sem_pexpr gd s1 e = ok (Vbool false) ->\n      sem s1 c2 s2 -> Pc s1 c2 s2 -> Pi_r s1 (Cif e c1 c2) s2.\n\n  Definition sem_Ind_while_true : Prop :=\n    forall (s1 s2 s3 s4 : estate) a (c : cmd) (e : pexpr) (c' : cmd),\n      sem s1 c s2 -> Pc s1 c s2 ->\n      sem_pexpr gd s2 e = ok (Vbool true) ->\n      sem s2 c' s3 -> Pc s2 c' s3 ->\n      sem_i s3 (Cwhile a c e c') s4 -> Pi_r s3 (Cwhile a c e c') s4 -> Pi_r s1 (Cwhile a c e c') s4.\n\n  Definition sem_Ind_while_false : Prop :=\n    forall (s1 s2 : estate) a (c : cmd) (e : pexpr) (c' : cmd),\n      sem s1 c s2 -> Pc s1 c s2 ->\n      sem_pexpr gd s2 e = ok (Vbool false) ->\n      Pi_r s1 (Cwhile a c e c') s2.\n\n  Hypotheses\n    (Hasgn: sem_Ind_assgn)\n    (Hopn: sem_Ind_opn)\n    (Hsyscall: sem_Ind_syscall)\n    (Hif_true: sem_Ind_if_true)\n    (Hif_false: sem_Ind_if_false)\n    (Hwhile_true: sem_Ind_while_true)\n    (Hwhile_false: sem_Ind_while_false)\n  .\n\n  Definition sem_Ind_for : Prop :=\n    forall (s1 s2 : estate) (i : var_i) (d : dir) (lo hi : pexpr) (c : cmd) (vlo vhi : Z),\n      sem_pexpr gd s1 lo = ok (Vint vlo) ->\n      sem_pexpr gd s1 hi = ok (Vint vhi) ->\n      sem_for i (wrange d vlo vhi) s1 c s2 ->\n      Pfor i (wrange d vlo vhi) s1 c s2 -> Pi_r s1 (Cfor i (d, lo, hi) c) s2.\n\n  Definition sem_Ind_for_nil : Prop :=\n    forall (s : estate) (i : var_i) (c : cmd),\n      Pfor i [::] s c s.\n\n  Definition sem_Ind_for_cons : Prop :=\n    forall (s1 s1' s2 s3 : estate) (i : var_i) (w : Z) (ws : seq Z) (c : cmd),\n      write_var i w s1 = Ok error s1' ->\n      sem s1' c s2 -> Pc s1' c s2 ->\n      sem_for i ws s2 c s3 -> Pfor i ws s2 c s3 -> Pfor i (w :: ws) s1 c s3.\n\n  Hypotheses\n    (Hfor: sem_Ind_for)\n    (Hfor_nil: sem_Ind_for_nil)\n    (Hfor_cons: sem_Ind_for_cons)\n  .\n\n  Definition sem_Ind_call : Prop :=\n    forall (s1 : estate) (scs2 : syscall_state_t) (m2 : mem) (s2 : estate)\n           (ii : inline_info) (xs : lvals)\n           (fn : funname) (args : pexprs) (vargs vs : seq value),\n      sem_pexprs gd s1 args = Ok error vargs ->\n      sem_call (escs s1) (emem s1) fn vargs scs2 m2 vs -> Pfun (escs s1) (emem s1) fn vargs scs2 m2 vs ->\n      write_lvals gd {| escs := scs2; emem := m2; evm := evm s1 |} xs vs = Ok error s2 ->\n      Pi_r s1 (Ccall ii xs fn args) s2.\n\n  Definition sem_Ind_proc : Prop :=\n    forall (scs1 : syscall_state_t) (m1 : mem) (scs2 : syscall_state_t) (m2 : mem) (fn:funname) (f : fundef) (vargs vargs': seq value)\n           (s1 : estate) (vm2 : vmap) (vres vres': seq value),\n      get_fundef (p_funcs P) fn = Some f ->\n      mapM2 ErrType truncate_val f.(f_tyin) vargs' = ok vargs ->\n      write_vars (f_params f) vargs {| escs := scs1; emem := m1; evm := vmap0 |} = ok s1 ->\n      sem s1 (f_body f) {| escs := scs2; emem := m2; evm := vm2 |} ->\n      Pc s1 (f_body f) {| escs := scs2; emem := m2; evm := vm2 |} ->\n      mapM (fun x : var_i => get_var vm2 x) (f_res f) = ok vres ->\n      mapM2 ErrType truncate_val f.(f_tyout) vres = ok vres' ->\n      Pfun scs1 m1 fn vargs' scs2 m2 vres'.\n\n  Hypotheses\n    (Hcall: sem_Ind_call)\n    (Hproc: sem_Ind_proc)\n  .\n\n  Fixpoint sem_Ind (e : estate) (l : cmd) (e0 : estate) (s : sem e l e0) {struct s} :\n    Pc e l e0 :=\n    match s in (sem e1 l0 e2) return (Pc e1 l0 e2) with\n    | Eskip s0 => Hnil s0\n    | @Eseq s1 s2 s3 i c s0 s4 =>\n        @Hcons s1 s2 s3 i c s0 (@sem_I_Ind s1 i s2 s0) s4 (@sem_Ind s2 c s3 s4)\n    end\n\n  with sem_i_Ind (e : estate) (i : instr_r) (e0 : estate) (s : sem_i e i e0) {struct s} :\n    Pi_r e i e0 :=\n    match s in (sem_i e1 i0 e2) return (Pi_r e1 i0 e2) with\n    | @Eassgn s1 s2 x tag ty e1 v v' h1 h2 h3 => @Hasgn s1 s2 x tag ty e1 v v' h1 h2 h3\n    | @Eopn s1 s2 t o xs es e1 => @Hopn s1 s2 t o xs es e1\n    | @Esyscall s1 scs m s2 xs o es ves vs h1 h2 h3 => @Hsyscall s1 scs m s2 xs o es ves vs h1 h2 h3\n    | @Eif_true s1 s2 e1 c1 c2 e2 s0 =>\n      @Hif_true s1 s2 e1 c1 c2 e2 s0 (@sem_Ind s1 c1 s2 s0)\n    | @Eif_false s1 s2 e1 c1 c2 e2 s0 =>\n      @Hif_false s1 s2 e1 c1 c2 e2 s0 (@sem_Ind s1 c2 s2 s0)\n    | @Ewhile_true s1 s2 s3 s4 a c e1 c' h1 h2 h3 h4 =>\n      @Hwhile_true s1 s2 s3 s4 a c e1 c' h1 (@sem_Ind s1 c s2 h1) h2 h3 (@sem_Ind s2 c' s3 h3) \n          h4 (@sem_i_Ind s3 (Cwhile a c e1 c') s4 h4)\n    | @Ewhile_false s1 s2 a c e1 c' s0 e2 =>\n      @Hwhile_false s1 s2 a c e1 c' s0 (@sem_Ind s1 c s2 s0) e2\n    | @Efor s1 s2 i0 d lo hi c vlo vhi e1 e2 s0 =>\n      @Hfor s1 s2 i0 d lo hi c vlo vhi e1 e2 s0\n        (@sem_for_Ind i0 (wrange d vlo vhi) s1 c s2 s0)\n    | @Ecall s1 scs2 m2 s2 ii xs f13 args vargs vs e2 s0 e3 =>\n      @Hcall s1 scs2 m2 s2 ii xs f13 args vargs vs e2 s0\n        (@sem_call_Ind (escs s1) (emem s1) f13 vargs scs2 m2 vs s0) e3\n    end\n\n  with sem_I_Ind (e : estate) (i : instr) (e0 : estate) (s : sem_I e i e0) {struct s} :\n    Pi e i e0 :=\n    match s in (sem_I e1 i0 e2) return (Pi e1 i0 e2) with\n    | @EmkI ii i0 s1 s2 s0 => @HmkI ii i0 s1 s2 s0 (@sem_i_Ind s1 i0 s2 s0)\n    end\n\n  with sem_for_Ind (v : var_i) (l : seq Z) (e : estate) (l0 : cmd) (e0 : estate)\n         (s : sem_for v l e l0 e0) {struct s} : Pfor v l e l0 e0 :=\n    match s in (sem_for v0 l1 e1 l2 e2) return (Pfor v0 l1 e1 l2 e2) with\n    | EForDone s0 i c => Hfor_nil s0 i c\n    | @EForOne s1 s1' s2 s3 i w ws c e1 s0 s4 =>\n      @Hfor_cons s1 s1' s2 s3 i w ws c e1 s0 (@sem_Ind s1' c s2 s0)\n         s4 (@sem_for_Ind i ws s2 c s3 s4)\n    end\n\n  with sem_call_Ind (scs : syscall_state_t) (m : mem) (f13 : funname) (l : seq value) (scs0 : syscall_state_t) (m0 : mem)\n         (l0 : seq value) (s : sem_call scs m f13 l scs0 m0 l0) {struct s} : Pfun scs m f13 l scs0 m0 l0 :=\n    match s with\n    | @EcallRun scs1 m1 scs2 m2 fn f vargs vargs' s1 vm2 vres vres' Hget Hctin Hw Hsem Hvres Hctout =>\n       @Hproc scs1 m1 scs2 m2 fn f vargs vargs' s1 vm2 vres vres' Hget Hctin Hw Hsem (sem_Ind Hsem) Hvres Hctout\n    end.\n\nEnd SEM_IND.\n\nEnd SEM.\n", "meta": {"author": "jasmin-lang", "repo": "jasmin", "sha": "3c783b662000c371ba924a953d444fd80b860d9f", "save_path": "github-repos/coq/jasmin-lang-jasmin", "path": "github-repos/coq/jasmin-lang-jasmin/jasmin-3c783b662000c371ba924a953d444fd80b860d9f/proofs/lang/sem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.24993408376257825}}
{"text": "Require Coq.Classes.EquivDec.\nRequire Coq.Lists.List.\nImport List.ListNotations.\nRequire Import Coq.Program.Program.\nRequire Import Leapfrog.Syntax.\nRequire Import Leapfrog.FinType.\nRequire Import Leapfrog.Sum.\nRequire Import Leapfrog.Notations.\n\nRequire Import Leapfrog.BisimChecker.\n\nOpen Scope p4a.\n\nLtac prep_equiv :=\n  unfold Equivalence.equiv, RelationClasses.complement in *;\n  program_simpl; try congruence.\n\nObligation Tactic := prep_equiv.\n\nModule TimestampRefKeepSingle.\n  Inductive state :=\n  | Start\n  | ParseValue1\n  | ParseValue2\n  | ParseValue3\n  | ParseValue4\n  | ParseValue5\n  | ParseValue6.\n\n  Scheme Equality for state.\n  Global Instance state_eqdec: EquivDec.EqDec state eq := state_eq_dec.\n  Global Instance state_finite: @Finite state _ state_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Inductive header :=\n  | Typ\n  | Len\n  | Value\n  | Scratch8\n  | Scratch16\n  | Scratch24\n  | Scratch32\n  | Scratch40.\n\n  Scheme Equality for header.\n  Global Instance header_eqdec: EquivDec.EqDec header eq := header_eq_dec.\n  Global Instance header_finite: @Finite header _ header_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Definition sz (h: header): nat :=\n    match h with\n    | Typ => 8\n    | Len => 8\n    | Value => 48\n    | Scratch8 => 8\n    | Scratch16 => 16\n    | Scratch24 => 24\n    | Scratch32 => 32\n    | Scratch40 => 40\n    end.\n\n  Definition states (s: state) : Syntax.state state sz :=\n    match s with\n    | Start =>\n      {| st_op :=\n          extract(Typ) ;;\n          extract(Len) ;\n        st_trans := transition select (| EHdr Len |) {{\n          [| exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n          [| exact #b|0|0|0|0|0|0|0|1 |] ==> inl ParseValue1 ;;;\n          [| exact #b|0|0|0|0|0|0|1|0 |] ==> inl ParseValue2 ;;;\n          [| exact #b|0|0|0|0|0|0|1|1 |] ==> inl ParseValue3 ;;;\n          [| exact #b|0|0|0|0|0|1|0|0 |] ==> inl ParseValue4 ;;;\n          [| exact #b|0|0|0|0|0|1|0|1 |] ==> inl ParseValue5 ;;;\n          [| exact #b|0|0|0|0|0|1|1|0 |] ==> inl ParseValue6 ;;;\n            reject\n        }}\n      |}\n    | ParseValue1 =>\n      {| st_op :=\n          extract(Scratch8) ;;\n          Value <- EConcat (m := 40) (EHdr Scratch8) ((@EHdr _ sz Value)[48--8])  ;\n        st_trans := transition accept\n      |}\n    | ParseValue2 =>\n      {| st_op :=\n          extract(Scratch16) ;;\n          Value <- EConcat (m := 32) (EHdr Scratch16) ((@EHdr _ sz Value)[48--16])  ;\n        st_trans := transition accept\n      |}\n    | ParseValue3 =>\n      {| st_op :=\n          extract(Scratch24) ;;\n          Value <- EConcat (m := 24) (EHdr Scratch24) ((@EHdr _ sz Value)[48--24])  ;\n        st_trans := transition accept\n      |}\n    | ParseValue4 =>\n      {| st_op :=\n          extract(Scratch32) ;;\n          Value <- EConcat (m := 16) (EHdr Scratch32) ((@EHdr _ sz Value)[48--32])  ;\n        st_trans := transition accept\n      |}\n    | ParseValue5 =>\n      {| st_op :=\n          extract(Scratch40) ;;\n          Value <- EConcat (m := 8) (EHdr Scratch40) ((@EHdr _ sz Value)[48--40])  ;\n        st_trans := transition accept\n      |}\n    | ParseValue6 =>\n      {| st_op := extract(Value) ;\n        st_trans := transition accept\n      |}\n    end.\n\n  Program Definition aut: Syntax.t state sz :=\n    {| t_states := states |}.\n  Solve Obligations with (destruct s || destruct h; cbv; Lia.lia).\n\nEnd TimestampRefKeepSingle.\n\nModule TimestampRefZeroSingle.\n  Inductive state :=\n  | Start\n  | ParseValue1\n  | ParseValue2\n  | ParseValue3\n  | ParseValue4\n  | ParseValue5\n  | ParseValue6.\n\n  Scheme Equality for state.\n  Global Instance state_eqdec: EquivDec.EqDec state eq := state_eq_dec.\n  Global Instance state_finite: @Finite state _ state_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Inductive header :=\n  | Typ\n  | Len\n  | Value\n  | Scratch8\n  | Scratch16\n  | Scratch24\n  | Scratch32\n  | Scratch40.\n\n  Scheme Equality for header.\n  Global Instance header_eqdec: EquivDec.EqDec header eq := header_eq_dec.\n  Global Instance header_finite: @Finite header _ header_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Definition sz (h: header): nat :=\n    match h with\n    | Typ => 8\n    | Len => 8\n    | Value => 48\n    | Scratch8 => 8\n    | Scratch16 => 16\n    | Scratch24 => 24\n    | Scratch32 => 32\n    | Scratch40 => 40\n    end.\n\n  Definition states (s: state) :=\n    match s with\n    | Start =>\n      {| st_op :=\n          extract(Typ) ;;\n          extract(Len) ;\n        st_trans := transition select (| EHdr Len |) {{\n          [| exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n          [| exact #b|0|0|0|0|0|0|0|1 |] ==> inl ParseValue1 ;;;\n          [| exact #b|0|0|0|0|0|0|1|0 |] ==> inl ParseValue2 ;;;\n          [| exact #b|0|0|0|0|0|0|1|1 |] ==> inl ParseValue3 ;;;\n          [| exact #b|0|0|0|0|0|1|0|0 |] ==> inl ParseValue4 ;;;\n          [| exact #b|0|0|0|0|0|1|0|1 |] ==> inl ParseValue5 ;;;\n          [| exact #b|0|0|0|0|0|1|1|0 |] ==> inl ParseValue6 ;;;\n            reject\n        }}\n      |}\n    | ParseValue1 =>\n      {| st_op :=\n          extract(Scratch8) ;;\n          Value <- EConcat (n := 8) (EHdr (Hdr_sz := sz) Scratch8) (ELit _ (Ntuple.n_tuple_repeat 40 false))  ;\n        st_trans := transition accept\n      |}\n    | ParseValue2 =>\n      {| st_op :=\n          extract(Scratch16) ;;\n          Value <- EConcat (n := 16) (EHdr (Hdr_sz := sz) Scratch16) (ELit _ (Ntuple.n_tuple_repeat 32 false))  ;\n        st_trans := transition accept\n      |}\n    | ParseValue3 =>\n      {| st_op :=\n          extract(Scratch24) ;;\n          Value <- EConcat (n := 24) (EHdr (Hdr_sz := sz) Scratch24) (ELit _ (Ntuple.n_tuple_repeat 24 false))  ;\n        st_trans := transition accept\n      |}\n    | ParseValue4 =>\n      {| st_op :=\n          extract(Scratch32) ;;\n          Value <- EConcat (n := 32) (EHdr (Hdr_sz := sz) Scratch32) (ELit _ (Ntuple.n_tuple_repeat 16 false))  ;\n        st_trans := transition accept\n      |}\n    | ParseValue5 =>\n      {| st_op :=\n          extract(Scratch40) ;;\n          Value <- EConcat (n := 40) (EHdr (Hdr_sz := sz) Scratch40) (ELit _ (Ntuple.n_tuple_repeat 8 false))  ;\n        st_trans := transition accept\n      |}\n    | ParseValue6 =>\n      {| st_op := extract(Value) ;\n        st_trans := transition accept\n      |}\n    end.\n\n  Program Definition aut: Syntax.t state sz :=\n    {| t_states := states |}.\n  Solve Obligations with (destruct s || destruct h; cbv; Lia.lia).\n\nEnd TimestampRefZeroSingle.\n\nModule TimestampSpecSingle.\n  Inductive state :=\n  | Start\n  | ParseValue1\n  | ParseValue2\n  | ParseValue3\n  | ParseValue4\n  | ParseValue5\n  | ParseValue6\n  | ParseTimestamp.\n\n  Scheme Equality for state.\n  Global Instance state_eqdec: EquivDec.EqDec state eq := state_eq_dec.\n  Global Instance state_finite: @Finite state _ state_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Inductive header :=\n  | Typ\n  | Len\n  | Scratch8\n  | Scratch16\n  | Scratch24\n  | Scratch32\n  | Scratch40\n  | Scratch48\n  | Pointer\n  | Overflow\n  | Flag\n  | Timestamp.\n\n  Definition sz (h: header): nat :=\n    match h with\n    | Typ => 8\n    | Len => 8\n    | Scratch8 => 8\n    | Scratch16 => 16\n    | Scratch24 => 24\n    | Scratch32 => 32\n    | Scratch40 => 40\n    | Scratch48 => 48\n    | Pointer => 8\n    | Overflow => 4\n    | Flag => 4\n    | Timestamp => 32\n    end.\n\n  Scheme Equality for header.\n  Global Instance header_eqdec: EquivDec.EqDec header eq := header_eq_dec.\n  Global Instance header_finite: @Finite header _ header_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Definition states (s: state) : Syntax.state state sz :=\n    match s with\n    | Start =>\n      {| st_op :=\n          extract(Typ) ;;\n          extract(Len) ;\n        st_trans := transition select (| EHdr Typ, EHdr Len |) {{\n          [| exact #b|0|1|0|0|0|1|0|0, exact #b|0|0|0|0|0|1|1|0 |] ==> inl ParseTimestamp ;;;\n          [| *, exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n          [| *, exact #b|0|0|0|0|0|0|0|1 |] ==> inl ParseValue1 ;;;\n          [| *, exact #b|0|0|0|0|0|0|1|0 |] ==> inl ParseValue2 ;;;\n          [| *, exact #b|0|0|0|0|0|0|1|1 |] ==> inl ParseValue3 ;;;\n          [| *, exact #b|0|0|0|0|0|1|0|0 |] ==> inl ParseValue4 ;;;\n          [| *, exact #b|0|0|0|0|0|1|0|1 |] ==> inl ParseValue5 ;;;\n          [| *, exact #b|0|0|0|0|0|1|1|0 |] ==> inl ParseValue6 ;;;\n            reject\n        }}\n      |}\n    | ParseTimestamp =>\n      {| st_op :=\n          extract(Pointer) ;;\n          extract(Overflow) ;;\n          extract(Flag) ;;\n          extract(Timestamp) ;\n        st_trans := transition accept (* TODO: validate pointer and flag? *)\n      |}\n    | ParseValue1 =>\n      {| st_op :=\n          extract(Scratch8) ;\n        st_trans := transition accept\n      |}\n    | ParseValue2 =>\n      {| st_op :=\n          extract(Scratch16) ;\n        st_trans := transition accept\n      |}\n    | ParseValue3 =>\n      {| st_op :=\n          extract(Scratch24) ;\n        st_trans := transition accept\n      |}\n    | ParseValue4 =>\n      {| st_op :=\n          extract(Scratch32) ;\n        st_trans := transition accept\n      |}\n    | ParseValue5 =>\n      {| st_op :=\n          extract(Scratch40) ;\n        st_trans := transition accept\n      |}\n    | ParseValue6 =>\n      {| st_op := extract(Scratch48) ;\n        st_trans := transition accept\n      |}\n    end.\n\n  Program Definition aut: Syntax.t state sz :=\n    {| t_states := states |}.\n  Solve Obligations with (destruct s || destruct h; cbv; Lia.lia).\n\nEnd TimestampSpecSingle.\n\n\nModule TimestampRefSmall.\n  Inductive state :=\n  | Start\n  | Parse1\n  | Parse2\n  | Parse3.\n\n  Scheme Equality for state.\n  Global Instance state_eqdec: EquivDec.EqDec state eq := state_eq_dec.\n  Global Instance state_finite: @Finite state _ state_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Inductive header :=\n  | Len\n  | Pref1\n  | Pref2\n  | Timestamps.\n\n  Definition sz (h: header): nat :=\n    match h with\n    | Len => 2\n    | Pref1 => 8\n    | Pref2 => 16\n    | Timestamps => 24\n    end.\n\n  Scheme Equality for header.\n  Global Instance header_eqdec: EquivDec.EqDec header eq := header_eq_dec.\n  Global Instance header_finite: @Finite header _ header_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Definition states (s: state) :=\n    match s with\n    | Start =>\n      {| st_op :=\n          extract(Len) ;\n         st_trans := transition select (| EHdr Len |) {{\n           [| exact #b|0|0 |] ==> accept ;;;\n           [| exact #b|0|1 |] ==> inl Parse1 ;;;\n           [| exact #b|1|0 |] ==> inl Parse2 ;;;\n           [| exact #b|1|1 |] ==> inl Parse3 ;;;\n            reject\n         }}\n      |}\n    | Parse1 =>\n      {| st_op :=\n          extract(Pref1) ;;\n          Timestamps <- EConcat (m := 16) (EHdr Pref1) ((EHdr (Hdr_sz := sz) Timestamps)[24--8])  ;\n         st_trans := transition accept\n      |}\n    | Parse2 =>\n      {| st_op :=\n          extract(Pref2) ;;\n          Timestamps <- EConcat (m := 8) (EHdr Pref2) ((EHdr (Hdr_sz := sz) Timestamps)[24--16]) ;\n         st_trans := transition accept\n      |}\n    | Parse3 =>\n      {| st_op := extract(Timestamps) ;\n         st_trans := transition accept\n      |}\n    end.\n\n  Program Definition aut: Syntax.t state sz :=\n    {| t_states := states |}.\n  Solve Obligations with (destruct s || destruct h; cbv; Lia.lia).\n\nEnd TimestampRefSmall.\n\nModule TimestampSpecSmall.\n  Inductive state :=\n  | Start\n  | Parse1\n  | Parse2\n  | Parse3.\n\n  Scheme Equality for state.\n  Global Instance state_eqdec: EquivDec.EqDec state eq := state_eq_dec.\n  Global Instance state_finite: @Finite state _ state_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Inductive header :=\n  | Len\n  | T1\n  | T2\n  | T3.\n\n  Definition sz (h: header): nat :=\n    match h with\n    | Len => 2\n    | T1 | T2 | T3 => 8\n    end.\n\n  Scheme Equality for header.\n  Global Instance header_eqdec: EquivDec.EqDec header eq := header_eq_dec.\n  Global Instance header_finite: @Finite header _ header_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Definition states (s: state) : Syntax.state state sz :=\n    match s with\n    | Start =>\n      {| st_op :=\n          extract(Len) ;\n         st_trans := transition select (| EHdr Len |) {{\n           [| exact #b|0|0 |] ==> accept ;;;\n           [| exact #b|0|1 |] ==> inl Parse1 ;;;\n           [| exact #b|1|0 |] ==> inl Parse2 ;;;\n           [| exact #b|1|1 |] ==> inl Parse3 ;;;\n            reject\n         }}\n      |}\n    | Parse1 =>\n      {| st_op :=\n          extract(T1) ;\n         st_trans := transition accept\n      |}\n    | Parse2 =>\n      {| st_op :=\n          extract(T1) ;;\n          extract(T2) ;\n         st_trans := transition accept\n      |}\n    | Parse3 =>\n      {| st_op :=\n          extract(T1) ;;\n          extract(T2) ;;\n          extract(T3) ;\n         st_trans := transition accept\n      |}\n    end.\n\n  Program Definition aut: Syntax.t state sz :=\n    {| t_states := states |}.\n  Solve Obligations with (destruct s || destruct h; cbv; Lia.lia).\n\nEnd TimestampSpecSmall.\n\n(* parse 2 options of between 0-6 bytes, and if a timestamp option is present, parse it into a timestamp structure *)\nModule TimestampSpec2.\n  Inductive state :=\n  | Parse0\n  | Parse1\n\n  | Parse0S\n  | Parse1S\n\n  | Parse01\n  | Parse11\n\n  | Parse02\n  | Parse12\n\n  | Parse03\n  | Parse13\n\n  | Parse04\n  | Parse14\n\n  | Parse05\n  | Parse15\n\n  | Parse06\n  | Parse16.\n\n  Scheme Equality for state.\n  Global Instance state_eqdec: EquivDec.EqDec state eq := state_eq_dec.\n  Global Instance state_finite: @Finite state _ state_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Inductive header :=\n  | Scratch8\n  | Scratch16\n  | Scratch24\n  | Scratch32\n  | Scratch40\n  | T0\n  | L0\n  | V0\n  | T1\n  | L1\n  | V1\n  | Pointer\n  | Overflow\n  | Flag\n  | Timestamp.\n\n  Definition sz (h: header): nat :=\n    match h with\n    | Scratch8  => 8\n    | Scratch16  => 16\n    | Scratch24  => 24\n    | Scratch32  => 32\n    | Scratch40  => 40\n    | T0  => 8\n    | L0  => 8\n    | V0  => 48\n    | T1  => 8\n    | L1  => 8\n    | V1  => 48\n    | Pointer  => 8\n    | Overflow => 4\n    | Flag => 4\n    | Timestamp => 32\n    end.\n\n  Scheme Equality for header.\n  Global Instance header_eqdec: EquivDec.EqDec header eq := header_eq_dec.\n  Global Instance header_finite: @Finite header _ header_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Definition states (s: state) : Syntax.state state sz :=\n    match s with\n    | Parse0 =>\n      {| st_op :=\n          extract(T0) ;;\n          extract(L0) ;\n         st_trans := transition select (| EHdr (Hdr_sz := sz) T0, EHdr (Hdr_sz := sz) L0 |) {{\n           [| exact #b|0|1|0|0|0|1|0|0, exact #b|0|0|0|0|0|1|1|0 |] ==> inl Parse0S;;;\n           [| exact #b|0|0|0|0|0|0|0|0, exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n           [| exact #b|0|0|0|0|0|0|0|1, exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n           [| *, exact #b|0|0|0|0|0|0|0|1 |] ==> inl Parse01 ;;;\n           [| *, exact #b|0|0|0|0|0|0|1|0 |] ==> inl Parse02 ;;;\n           [| *, exact #b|0|0|0|0|0|0|1|1 |] ==> inl Parse03 ;;;\n           [| *, exact #b|0|0|0|0|0|1|0|0 |] ==> inl Parse04 ;;;\n           [| *, exact #b|0|0|0|0|0|1|0|1 |] ==> inl Parse05 ;;;\n           [| *, exact #b|0|0|0|0|0|1|1|0 |] ==> inl Parse06 ;;;\n            reject\n         }}\n      |}\n    | Parse01 =>\n      {| st_op :=\n          extract(Scratch8) ;;\n          V0 <- EConcat (m := 40) (EHdr (Hdr_sz := sz) Scratch8) ((EHdr (Hdr_sz := sz) V0)[48--8]) ;\n         st_trans := transition inl Parse1;\n      |}\n    | Parse02 =>\n      {| st_op :=\n          extract(Scratch16) ;;\n          V0 <- EConcat (m := 32) (EHdr (Hdr_sz := sz) Scratch16) ((EHdr (Hdr_sz := sz) V0)[48--16]) ;\n         st_trans := transition inl Parse1;\n      |}\n    | Parse03 =>\n      {| st_op :=\n          extract(Scratch24) ;;\n          V0 <- EConcat (m := 24) (EHdr (Hdr_sz := sz) Scratch24) ((EHdr (Hdr_sz := sz) V0)[48--24]) ;\n         st_trans := transition inl Parse1;\n      |}\n    | Parse04 =>\n      {| st_op :=\n          extract(Scratch32) ;;\n          V0 <- EConcat (m := 16) (EHdr (Hdr_sz := sz) Scratch32) ((EHdr (Hdr_sz := sz) V0)[48--32]) ;\n         st_trans := transition inl Parse1;\n      |}\n    | Parse05 =>\n      {| st_op :=\n          extract(Scratch40) ;;\n          V0 <- EConcat (m := 8) (EHdr (Hdr_sz := sz) Scratch40) ((EHdr (Hdr_sz := sz) V0)[48--40]) ;\n         st_trans := transition inl Parse1;\n      |}\n    | Parse06 =>\n      {| st_op :=\n          extract(V0) ;\n         st_trans := transition inl Parse1;\n      |}\n\n    | Parse0S =>\n      {| st_op :=\n          extract(Pointer) ;;\n          extract(Overflow) ;;\n          extract(Flag) ;;\n          extract(Timestamp) ;\n        st_trans := transition inl Parse1 ;\n      |}\n\n    | Parse1 =>\n      {| st_op :=\n          extract(T1) ;;\n          extract(L1) ;\n         st_trans := transition select (| EHdr (Hdr_sz := sz) T1, EHdr (Hdr_sz := sz) L1 |) {{\n           [| exact #b|0|1|0|0|0|1|0|0, exact #b|0|0|0|0|0|1|1|0 |] ==> inl Parse1S;;;\n           [| exact #b|0|0|0|0|0|0|0|0, exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n           [| exact #b|0|0|0|0|0|0|0|1, exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n           [| *, exact #b|0|0|0|0|0|0|0|1 |] ==> inl Parse11 ;;;\n           [| *, exact #b|0|0|0|0|0|0|1|0 |] ==> inl Parse12 ;;;\n           [| *, exact #b|0|0|0|0|0|0|1|1 |] ==> inl Parse13 ;;;\n           [| *, exact #b|0|0|0|0|0|1|0|0 |] ==> inl Parse14 ;;;\n           [| *, exact #b|0|0|0|0|0|1|0|1 |] ==> inl Parse15 ;;;\n           [| *, exact #b|0|0|0|0|0|1|1|0 |] ==> inl Parse16 ;;;\n            reject\n         }}\n      |}\n    | Parse11 =>\n      {| st_op :=\n          extract(Scratch8) ;;\n          V1 <- EConcat (m := 40) (EHdr (Hdr_sz := sz) Scratch8) ((EHdr (Hdr_sz := sz) V1)[48--8]) ;\n         st_trans := transition accept;\n      |}\n    | Parse12 =>\n      {| st_op :=\n          extract(Scratch16) ;;\n          V1 <- EConcat (m := 32) (EHdr (Hdr_sz := sz) Scratch16) ((EHdr (Hdr_sz := sz) V1)[48--16]) ;\n         st_trans := transition accept;\n      |}\n    | Parse13 =>\n      {| st_op :=\n          extract(Scratch24) ;;\n          V1 <- EConcat (m := 24) (EHdr (Hdr_sz := sz) Scratch24) ((EHdr (Hdr_sz := sz) V1)[48--24]) ;\n         st_trans := transition accept;\n      |}\n    | Parse14 =>\n      {| st_op :=\n          extract(Scratch32) ;;\n          V1 <- EConcat (m := 16) (EHdr (Hdr_sz := sz) Scratch32) ((EHdr (Hdr_sz := sz) V1)[48--32]) ;\n         st_trans := transition accept;\n      |}\n    | Parse15 =>\n      {| st_op :=\n          extract(Scratch40) ;;\n          V1 <- EConcat (m := 8) (EHdr (Hdr_sz := sz) Scratch40) ((EHdr (Hdr_sz := sz) V1)[48--40]) ;\n         st_trans := transition accept;\n      |}\n    | Parse16 =>\n      {| st_op :=\n          extract(V1) ;\n         st_trans := transition accept;\n      |}\n    | Parse1S =>\n      {| st_op :=\n          extract(Pointer) ;;\n          extract(Overflow) ;;\n          extract(Flag) ;;\n          extract(Timestamp) ;\n        st_trans := transition accept ;\n      |}\n    end.\n\n  Program Definition aut: Syntax.t state sz :=\n    {| t_states := states |}.\n  Solve Obligations with (destruct s || destruct h; cbv; Lia.lia).\n\nEnd TimestampSpec2.\n\n\n(* parse 3 options of between 0-6 bytes, and if a timestamp option is present, parse it into a timestamp structure *)\nModule TimestampSpec3.\n  Inductive state :=\n  | Parse0\n  | Parse1\n  | Parse2\n\n  | Parse0S\n  | Parse1S\n  | Parse2S\n\n  | Parse01\n  | Parse11\n  | Parse21\n\n  | Parse02\n  | Parse12\n  | Parse22\n\n  | Parse03\n  | Parse13\n  | Parse23\n\n  | Parse04\n  | Parse14\n  | Parse24\n\n  | Parse05\n  | Parse15\n  | Parse25\n\n  | Parse06\n  | Parse16\n  | Parse26.\n\n  Scheme Equality for state.\n  Global Instance state_eqdec: EquivDec.EqDec state eq := state_eq_dec.\n  Global Instance state_finite: @Finite state _ state_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Inductive header :=\n  | Scratch8\n  | Scratch16\n  | Scratch24\n  | Scratch32\n  | Scratch40\n  | T0\n  | L0\n  | V0\n  | T1\n  | L1\n  | V1\n  | T2\n  | L2\n  | V2\n  | Pointer\n  | Overflow\n  | Flag\n  | Timestamp.\n\n  Definition sz (h: header): nat :=\n    match h with\n    | Scratch8  => 8\n    | Scratch16  => 16\n    | Scratch24  => 24\n    | Scratch32  => 32\n    | Scratch40  => 40\n    | T0  => 8\n    | L0  => 8\n    | V0  => 48\n    | T1  => 8\n    | L1  => 8\n    | V1  => 48\n    | T2  => 8\n    | L2  => 8\n    | V2  => 48\n    | Pointer  => 8\n    | Overflow => 4\n    | Flag => 4\n    | Timestamp => 32\n    end.\n\n  Scheme Equality for header.\n  Global Instance header_eqdec: EquivDec.EqDec header eq := header_eq_dec.\n  Global Instance header_finite: @Finite header _ header_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Definition states (s: state) : Syntax.state state sz :=\n    match s with\n    | Parse0 =>\n      {| st_op :=\n          extract(T0) ;;\n          extract(L0) ;\n         st_trans := transition select (| EHdr (Hdr_sz := sz) T0, EHdr (Hdr_sz := sz) L0 |) {{\n           [| exact #b|0|1|0|0|0|1|0|0, exact #b|0|0|0|0|0|1|1|0 |] ==> inl Parse0S;;;\n           [| exact #b|0|0|0|0|0|0|0|0, exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n           [| exact #b|0|0|0|0|0|0|0|1, exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n           [| *, exact #b|0|0|0|0|0|0|0|1 |] ==> inl Parse01 ;;;\n           [| *, exact #b|0|0|0|0|0|0|1|0 |] ==> inl Parse02 ;;;\n           [| *, exact #b|0|0|0|0|0|0|1|1 |] ==> inl Parse03 ;;;\n           [| *, exact #b|0|0|0|0|0|1|0|0 |] ==> inl Parse04 ;;;\n           [| *, exact #b|0|0|0|0|0|1|0|1 |] ==> inl Parse05 ;;;\n           [| *, exact #b|0|0|0|0|0|1|1|0 |] ==> inl Parse06 ;;;\n            reject\n         }}\n      |}\n    | Parse01 =>\n      {| st_op :=\n          extract(Scratch8) ;;\n          V0 <- EConcat (m := 40) (EHdr (Hdr_sz := sz) Scratch8) ((EHdr (Hdr_sz := sz) V0)[48--8]) ;\n         st_trans := transition inl Parse1;\n      |}\n    | Parse02 =>\n      {| st_op :=\n          extract(Scratch16) ;;\n          V0 <- EConcat (m := 32) (EHdr (Hdr_sz := sz) Scratch16) ((EHdr (Hdr_sz := sz) V0)[48--16]) ;\n         st_trans := transition inl Parse1;\n      |}\n    | Parse03 =>\n      {| st_op :=\n          extract(Scratch24) ;;\n          V0 <- EConcat (m := 24) (EHdr (Hdr_sz := sz) Scratch24) ((EHdr (Hdr_sz := sz) V0)[48--24]) ;\n         st_trans := transition inl Parse1;\n      |}\n    | Parse04 =>\n      {| st_op :=\n          extract(Scratch32) ;;\n          V0 <- EConcat (m := 16) (EHdr (Hdr_sz := sz) Scratch32) ((EHdr (Hdr_sz := sz) V0)[48--32]) ;\n         st_trans := transition inl Parse1;\n      |}\n    | Parse05 =>\n      {| st_op :=\n          extract(Scratch40) ;;\n          V0 <- EConcat (m := 8) (EHdr (Hdr_sz := sz) Scratch40) ((EHdr (Hdr_sz := sz) V0)[48--40]) ;\n         st_trans := transition inl Parse1;\n      |}\n    | Parse06 =>\n      {| st_op :=\n          extract(V0) ;\n         st_trans := transition inl Parse1;\n      |}\n\n    | Parse0S =>\n      {| st_op :=\n          extract(Pointer) ;;\n          extract(Overflow) ;;\n          extract(Flag) ;;\n          extract(Timestamp) ;\n        st_trans := transition inl Parse1 ;\n      |}\n\n    | Parse1 =>\n      {| st_op :=\n          extract(T1) ;;\n          extract(L1) ;\n         st_trans := transition select (| EHdr (Hdr_sz := sz) T1, EHdr (Hdr_sz := sz) L1 |) {{\n           [| exact #b|0|1|0|0|0|1|0|0, exact #b|0|0|0|0|0|1|1|0 |] ==> inl Parse1S;;;\n           [| exact #b|0|0|0|0|0|0|0|0, exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n           [| exact #b|0|0|0|0|0|0|0|1, exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n           [| *, exact #b|0|0|0|0|0|0|0|1 |] ==> inl Parse11 ;;;\n           [| *, exact #b|0|0|0|0|0|0|1|0 |] ==> inl Parse12 ;;;\n           [| *, exact #b|0|0|0|0|0|0|1|1 |] ==> inl Parse13 ;;;\n           [| *, exact #b|0|0|0|0|0|1|0|0 |] ==> inl Parse14 ;;;\n           [| *, exact #b|0|0|0|0|0|1|0|1 |] ==> inl Parse15 ;;;\n           [| *, exact #b|0|0|0|0|0|1|1|0 |] ==> inl Parse16 ;;;\n            reject\n         }}\n      |}\n    | Parse11 =>\n      {| st_op :=\n          extract(Scratch8) ;;\n          V1 <- EConcat (m := 40) (EHdr (Hdr_sz := sz) Scratch8) ((EHdr (Hdr_sz := sz) V1)[48--8]) ;\n         st_trans := transition inl Parse2;\n      |}\n    | Parse12 =>\n      {| st_op :=\n          extract(Scratch16) ;;\n          V1 <- EConcat (m := 32) (EHdr (Hdr_sz := sz) Scratch16) ((EHdr (Hdr_sz := sz) V1)[48--16]) ;\n         st_trans := transition inl Parse2;\n      |}\n    | Parse13 =>\n      {| st_op :=\n          extract(Scratch24) ;;\n          V1 <- EConcat (m := 24) (EHdr (Hdr_sz := sz) Scratch24) ((EHdr (Hdr_sz := sz) V1)[48--24]) ;\n         st_trans := transition inl Parse2;\n      |}\n    | Parse14 =>\n      {| st_op :=\n          extract(Scratch32) ;;\n          V1 <- EConcat (m := 16) (EHdr (Hdr_sz := sz) Scratch32) ((EHdr (Hdr_sz := sz) V1)[48--32]) ;\n         st_trans := transition inl Parse2;\n      |}\n    | Parse15 =>\n      {| st_op :=\n          extract(Scratch40) ;;\n          V1 <- EConcat (m := 8) (EHdr (Hdr_sz := sz) Scratch40) ((EHdr (Hdr_sz := sz) V1)[48--40]) ;\n         st_trans := transition inl Parse2;\n      |}\n    | Parse16 =>\n      {| st_op :=\n          extract(V1) ;\n         st_trans := transition inl Parse2;\n      |}\n    | Parse1S =>\n      {| st_op :=\n          extract(Pointer) ;;\n          extract(Overflow) ;;\n          extract(Flag) ;;\n          extract(Timestamp) ;\n        st_trans := transition inl Parse2 ;\n      |}\n\n    | Parse2 =>\n      {| st_op :=\n          extract(T2) ;;\n          extract(L2) ;\n         st_trans := transition select (| EHdr (Hdr_sz := sz) T2, EHdr (Hdr_sz := sz) L2 |) {{\n           [| exact #b|0|1|0|0|0|1|0|0, exact #b|0|0|0|0|0|1|1|0 |] ==> inl Parse2S;;;\n           [| exact #b|0|0|0|0|0|0|0|0, exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n           [| exact #b|0|0|0|0|0|0|0|1, exact #b|0|0|0|0|0|0|0|0 |] ==> accept ;;;\n           [| *, exact #b|0|0|0|0|0|0|0|1 |] ==> inl Parse21 ;;;\n           [| *, exact #b|0|0|0|0|0|0|1|0 |] ==> inl Parse22 ;;;\n           [| *, exact #b|0|0|0|0|0|0|1|1 |] ==> inl Parse23 ;;;\n           [| *, exact #b|0|0|0|0|0|1|0|0 |] ==> inl Parse24 ;;;\n           [| *, exact #b|0|0|0|0|0|1|0|1 |] ==> inl Parse25 ;;;\n           [| *, exact #b|0|0|0|0|0|1|1|0 |] ==> inl Parse26 ;;;\n            reject\n         }}\n      |}\n    | Parse21 =>\n      {| st_op :=\n          extract(Scratch8) ;;\n          V1 <- EConcat (m := 40) (EHdr (Hdr_sz := sz) Scratch8) ((EHdr (Hdr_sz := sz) V2)[48--8]) ;\n         st_trans := transition accept;\n      |}\n    | Parse22 =>\n      {| st_op :=\n          extract(Scratch16) ;;\n          V2 <- EConcat (m := 32) (EHdr (Hdr_sz := sz) Scratch16) ((EHdr (Hdr_sz := sz) V2)[48--16]) ;\n         st_trans := transition accept;\n      |}\n    | Parse23 =>\n      {| st_op :=\n          extract(Scratch24) ;;\n          V2 <- EConcat (m := 24) (EHdr (Hdr_sz := sz) Scratch24) ((EHdr (Hdr_sz := sz) V2)[48--24]) ;\n         st_trans := transition accept;\n      |}\n    | Parse24 =>\n      {| st_op :=\n          extract(Scratch32) ;;\n          V2 <- EConcat (m := 16) (EHdr (Hdr_sz := sz) Scratch32) ((EHdr (Hdr_sz := sz) V2)[48--32]) ;\n         st_trans := transition accept;\n      |}\n    | Parse25 =>\n      {| st_op :=\n          extract(Scratch40) ;;\n          V2 <- EConcat (m := 8) (EHdr (Hdr_sz := sz) Scratch40) ((EHdr (Hdr_sz := sz) V2)[48--40]) ;\n         st_trans := transition accept;\n      |}\n    | Parse26 =>\n      {| st_op :=\n          extract(V2) ;\n         st_trans := transition accept;\n      |}\n    | Parse2S =>\n      {| st_op :=\n          extract(Pointer) ;;\n          extract(Overflow) ;;\n          extract(Flag) ;;\n          extract(Timestamp) ;\n        st_trans := transition accept ;\n      |}\n    end.\n\n  Program Definition aut: Syntax.t state sz :=\n    {| t_states := states |}.\n  Solve Obligations with (destruct s || destruct h; cbv; Lia.lia).\n\nEnd TimestampSpec3.\n\n", "meta": {"author": "verified-network-toolchain", "repo": "leapfrog", "sha": "fe8c4e60c9d1c2660ca2a199909bef04c81e5634", "save_path": "github-repos/coq/verified-network-toolchain-leapfrog", "path": "github-repos/coq/verified-network-toolchain-leapfrog/leapfrog-fe8c4e60c9d1c2660ca2a199909bef04c81e5634/lib/Benchmarks/Timestamp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24993408376257822}}
{"text": "From Undecidability Require Import TM.Util.Prelim TM.Util.TM_facts.\n\n(* * Mirror Operator *)\n\nSection Mirror.\n  Variable (n : nat) (sig : finType).\n\n  Definition mirror_act : (option sig * move) -> (option sig * move) :=\n    map_snd mirror_move.\n\n  Definition mirror_acts : Vector.t (option sig * move) n -> Vector.t (option sig * move) n :=\n    Vector.map mirror_act.\n\n  Lemma mirror_act_involution a : mirror_act (mirror_act a) = a.\n  Proof. destruct a. cbn. rewrite mirror_move_involution. reflexivity. Qed.\n\n  Lemma mirror_acts_involution acts :\n    mirror_acts (mirror_acts acts) = acts.\n  Proof.\n    unfold mirror_acts. apply Vector.eq_nth_iff. intros ? ? ->.\n    erewrite !Vector.nth_map; eauto. apply mirror_act_involution.\n  Qed.\n\n\n  Variable F : finType.\n  Variable pM : pTM sig F n.\n\n  Definition Mirror_trans :\n    state (projT1 pM) * Vector.t (option sig) n ->\n    state (projT1 pM) *\n    Vector.t (option sig * move) n :=\n    fun qsym =>\n      let (q', act) := trans qsym in\n      (q', mirror_acts act).\n\n  Definition MirrorTM : TM sig n :=\n    {|\n      trans := Mirror_trans;\n      start := start (projT1 pM);\n      halt := halt (m := projT1 pM);\n    |}.\n\n  Definition Mirror : pTM sig F n :=\n    (MirrorTM; projT2 pM).\n\n  Definition mirrorConf : mconfig sig (state (projT1 pM)) n -> mconfig sig (state (projT1 pM)) n :=\n    fun c => mk_mconfig (cstate c) (mirror_tapes (ctapes c)).\n\n  Lemma mirrorConf_involution c : mirrorConf (mirrorConf c) = c.\n  Proof. destruct c as [q t]. unfold mirrorConf. cbn. f_equal. apply mirror_tapes_involution. Qed.\n\n  Lemma mirrorConf_injective c1 c2 : mirrorConf c1 = mirrorConf c2 -> c1 = c2.\n  Proof. destruct c1 as [q1 t1], c2 as [q2 t2]. unfold mirrorConf. cbn. intros H; inv H. f_equal. now apply mirror_tapes_injective. Qed.\n\n  Lemma current_chars_mirror_tapes (t : tapes sig n) :\n    current_chars (mirror_tapes t) = current_chars t.\n  Proof. apply Vector.eq_nth_iff; intros i ? <-. autounfold with tape. now simpl_tape. Qed.\n\n  Lemma doAct_mirror (t : tape sig) (act : option sig * move) :\n    doAct (mirror_tape t) act = mirror_tape (doAct t (mirror_act act)).\n  Proof. now destruct act as [ [ s | ] [ | | ]]; cbn; simpl_tape. Qed.\n\n  Lemma doAct_mirror_multi (t : tapes sig n) (acts : Vector.t (option sig * move) n) :\n    doAct_multi (mirror_tapes t) acts = mirror_tapes (doAct_multi t (mirror_acts acts)).\n  Proof. apply Vector.eq_nth_iff; intros i ? <-. unfold doAct_multi, mirror_acts, mirror_tapes. simpl_tape. apply doAct_mirror. Qed.\n\n  Lemma mirror_step c :\n    step (M := projT1 pM) (mirrorConf c) = mirrorConf (step (M := projT1 Mirror) c).\n  Proof.\n    unfold step; cbn -[doAct_multi]. unfold Mirror_trans. cbn.\n    destruct c as [q t]; cbn. rewrite current_chars_mirror_tapes.\n    destruct (trans (q, current_chars t)) as [q' acts].\n    unfold mirrorConf; cbn. f_equal. apply doAct_mirror_multi.\n  Qed.\n\n  Lemma mirror_lift k c1 c2 :\n    loopM (M := projT1 Mirror)             c1  k = Some             c2 ->\n    loopM (M := projT1 pM    ) (mirrorConf c1) k = Some (mirrorConf c2).\n  Proof.\n    unfold loopM. intros HLoop.\n    apply loop_lift with (lift := mirrorConf) (f' := step (M:=projT1 pM)) (h' := haltConf (M:=projT1 pM)) in HLoop; auto.\n    - intros ? _. now apply mirror_step.\n  Qed.\n\n  Lemma mirror_unlift k c1 c2 :\n    loopM (M := projT1     pM) (mirrorConf c1) k = Some (mirrorConf c2) ->\n    loopM (M := projT1 Mirror) (           c1) k = Some (           c2).\n  Proof.\n    unfold loopM. intros HLoop.\n    apply loop_unlift with (lift := mirrorConf) (f := step (M:=MirrorTM)) (h := haltConf (M:=MirrorTM)) in HLoop\n      as (? & HLoop & <- % mirrorConf_injective); auto.\n    - intros ? _. now apply mirror_step.\n  Qed.\n\n\n  Definition Mirror_Rel (R : pRel sig F n) : pRel sig F n :=\n    fun t '(l, t') => R (mirror_tapes t) (l, mirror_tapes t').\n\n  Lemma Mirror_Realise R :\n    pM ⊨ R -> Mirror ⊨ Mirror_Rel R.\n  Proof.\n    intros HRealise. intros t i outc HLoop.\n    apply (HRealise (mirror_tapes t) i (mirrorConf outc)).\n    now apply mirror_lift in HLoop.\n  Qed.\n\n  Definition Mirror_T (T : tRel sig n) : tRel sig n :=\n    fun t k => T (mirror_tapes t) k.\n\n  Lemma Mirror_Terminates T :\n    projT1 pM ↓ T -> projT1 Mirror ↓ Mirror_T T.\n  Proof.\n    intros HTerm. hnf. intros t1 k H1. hnf in HTerm. specialize (HTerm (mirror_tapes t1) k H1) as (outc&H).\n    exists (mirrorConf outc). apply mirror_unlift. cbn. now rewrite mirrorConf_involution.\n  Qed.\n\n  Lemma Mirror_RealiseIn R (k : nat) :\n    pM ⊨c(k) R -> Mirror ⊨c(k) Mirror_Rel R.\n  Proof.\n    intros H.\n    eapply Realise_total. split.\n    - eapply Mirror_Realise. now eapply Realise_total.\n    - eapply TerminatesIn_monotone.\n      + eapply Mirror_Terminates. now eapply Realise_total.\n      + firstorder.\n  Qed.\n\nEnd Mirror.\n\nArguments Mirror : simpl never.\nArguments Mirror_Rel { n sig F } R x y /.\nArguments Mirror_T { n sig } T x y /.\n\n\nLtac smpl_TM_Mirror :=\n  once lazymatch goal with\n  | [ |- Mirror _ ⊨ _ ] => eapply Mirror_Realise\n  | [ |- Mirror _ ⊨c(_) _ ] => eapply Mirror_RealiseIn\n  | [ |- projT1 (Mirror _) ↓ _ ] => eapply Mirror_Terminates\n  end.\n\nSmpl Add smpl_TM_Mirror : TM_Correct.", "meta": {"author": "uds-psl", "repo": "time-invariance-thesis-for-L", "sha": "41f4eb1f788cc4f096d9c7c286c9ca907588859f", "save_path": "github-repos/coq/uds-psl-time-invariance-thesis-for-L", "path": "github-repos/coq/uds-psl-time-invariance-thesis-for-L/time-invariance-thesis-for-L-41f4eb1f788cc4f096d9c7c286c9ca907588859f/theories/TM/Combinators/Mirror.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136564, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24993407701023124}}
{"text": "\nFrom Coq Require Import Arith ZArith OrderedType.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq.\nFrom nbits Require Import NBits.\nFrom ssrlib Require Import Var Types SsrOrder Nats ZAriths Store FSets Tactics.\nFrom BitBlasting Require Import Typ TypEnv State QFBV CNF BBCommon.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection Conform .\n\n  Fixpoint conform_exp (e : QFBV.exp) (s : SSAStore.t) (te : SSATE.env) : bool :=\n    match e with\n    | QFBV.Evar v => SSATE.vsize v te == size (SSAStore.acc v s)\n    | QFBV.Econst _ => true\n    | QFBV.Eunop op e => conform_exp e s te\n    | QFBV.Ebinop op e1 e2 => conform_exp e1 s te && conform_exp e2 s te\n    | QFBV.Eite b e1 e2 =>\n      conform_bexp b s te && conform_exp e1 s te && conform_exp e2 s te\n    end\n  with\n  conform_bexp (b : QFBV.bexp) (s : SSAStore.t) (te : SSATE.env) : bool :=\n    match b with\n    | QFBV.Bfalse\n    | QFBV.Btrue => true\n    | QFBV.Bbinop _ e1 e2 => conform_exp e1 s te && conform_exp e2 s te\n    | QFBV.Blneg b => conform_bexp b s te\n    | QFBV.Bconj b1 b2\n    | QFBV.Bdisj b1 b2 => conform_bexp b1 s te && conform_bexp b2 s te\n    end.\n\n  (*\n  Lemma conform_exp_upd x ty v s te :\n    sizeof_typ ty = size v ->\n    conform_exp (QFBV.Evar v) s te -> conform_exp (QFBV.Evar v) (SSAStore.upd x v s) (SSATE.add x ty te) .\n  Proof.\n    move=> Hs Hcon y. case Hyx: (y == x).\n    - by rewrite (TypEnv.vsize_add_eq Hyx) (Store.acc_upd_eq Hyx).\n    - move/idP/negP: Hyx => Hyx. rewrite (TypEnv.mem_add_neq Hyx) => Hmem.\n      rewrite (Store.acc_upd_neq Hyx) (TypEnv.vsize_add_neq Hyx). exact: (Hcon _ Hmem).\n  Qed.\n   *)\n  Lemma eval_conform_exp_size e te s :\n    QFBV.well_formed_exp e te -> conform_exp e s te -> size (QFBV.eval_exp e s) = QFBV.exp_size e te.\n  Proof .\n    (* QFBV.exp *)\n    elim e; rewrite /= .\n    - move => v _ Hsize; rewrite (eqP Hsize) // .\n    - done .\n    - elim; rewrite /= .\n      + move => e0 IH Hwf Hcf .\n        rewrite -(IH Hwf Hcf) /invB size_map // .\n      + move => e0 IH Hwf Hcf .\n        rewrite -(IH Hwf Hcf) /negB /invB size_succB size_map // .\n      + move => i j e0 _ _ _; rewrite size_extract // .\n      + move => n e0 _ _ _; rewrite size_high // .\n      + move => n e0 _ _ _; rewrite size_low // .\n      + move => n e0 IH Hwf Hcf .\n        rewrite -(IH Hwf Hcf) /zext size_cat size_zeros // .\n      + move => n e0 IH Hwf Hcf .\n        rewrite -(IH Hwf Hcf) /sext size_cat size_copy // .\n      + move => n e0 IH Hwf Hcf .\n        rewrite -(IH Hwf Hcf) size_repeat // .\n      + move => n e0 IH Hwf Hcf .\n        rewrite -(IH Hwf Hcf) size_rolB // .\n      + move => n e0 IH Hwf Hcf .\n        rewrite -(IH Hwf Hcf) size_rorB // .\n    - elim; rewrite /=;\n       move => e0 IH0 e1 IH1\n                  /andP [/andP [/andP [Hwf0 Hwf1] Hszgt0] Hsize]\n                  /andP [Hcf0 Hcf1] .\n      + rewrite /andB size_lift (IH0 Hwf0 Hcf0) (IH1 Hwf1 Hcf1) (eqP Hsize) .\n        reflexivity.\n      + rewrite /orB size_lift (IH0 Hwf0 Hcf0) (IH1 Hwf1 Hcf1) (eqP Hsize) .\n        reflexivity.\n      + rewrite /xorB size_lift (IH0 Hwf0 Hcf0) (IH1 Hwf1 Hcf1) (eqP Hsize) .\n        reflexivity.\n      + rewrite size_addB (IH0 Hwf0 Hcf0) (IH1 Hwf1 Hcf1) (eqP Hsize) .\n        reflexivity.\n      + rewrite size_subB (IH0 Hwf0 Hcf0) (IH1 Hwf1 Hcf1) (eqP Hsize) .\n        reflexivity.\n      + rewrite size_mulB (IH0 Hwf0 Hcf0) . reflexivity.\n      + rewrite size_udivB (IH0 Hwf0 Hcf0). reflexivity.\n      + rewrite size_uremB (IH0 Hwf0 Hcf0). reflexivity.\n      + rewrite size_sdivB (IH0 Hwf0 Hcf0). reflexivity.\n      + rewrite size_sremB (IH0 Hwf0 Hcf0). reflexivity.\n      + rewrite size_smodB_ss.\n        * rewrite (IH0 Hwf0 Hcf0). reflexivity.\n        * rewrite (IH0 Hwf0 Hcf0) (IH1 Hwf1 Hcf1). exact: (eqP Hsize).\n      + rewrite shlBB_shlB size_shlB (IH0 Hwf0 Hcf0) . reflexivity.\n      + rewrite shrBB_shrB size_shrB (IH0 Hwf0 Hcf0) . reflexivity.\n      + rewrite sarBB_sarB size_sarB (IH0 Hwf0 Hcf0) . reflexivity.\n      + rewrite size_cat (IH0 Hwf0 Hcf0) (IH1 Hwf1 Hcf1) addnC // .\n      + reflexivity.\n    - move => b e0 IH0 e1 IH1\n                /andP [/andP [/andP [Hwfb Hwf0] Hwf1] Hsize]\n                /andP [/andP [Hcfb Hcf0] Hcf1] .\n      case (QFBV.eval_bexp b s) .\n      * rewrite -(eqP Hsize) (IH0 Hwf0 Hcf0) maxnn. reflexivity.\n      * rewrite (eqP Hsize) (IH1 Hwf1 Hcf1) maxnn. reflexivity.\n  Qed .\n\n\n  Fixpoint conform_bexps (bs : seq QFBV.bexp) s te : bool :=\n    match bs with\n    | [::] => true\n    | b :: bs' => conform_bexp b s te && conform_bexps bs' s te\n    end.\n\n\n  Lemma conform_exp_mem E e s v :\n    conform_exp e s E ->\n    SSAVS.mem v (QFBV.vars_exp e) ->\n    size (SSAStore.acc v s) = SSATE.vsize v E\n  with conform_bexp_mem E e s v :\n    conform_bexp e s E ->\n    SSAVS.mem v (QFBV.vars_bexp e) ->\n    size (SSAStore.acc v s) = SSATE.vsize v E.\n  Proof.\n    (* conform_exp_mem *)\n    case: e => //=.\n    - move=> x /eqP Hs Hmem. move: (SSAVS.Lemmas.mem_singleton1 Hmem) => Heq.\n      rewrite (eqP Heq) Hs. reflexivity.\n    - move=> _ e Hco Hmem. exact: (conform_exp_mem _ _ _ _ Hco Hmem).\n    - move=> _ e1 e2 /andP [Hco1 Hco2]. rewrite SSAVS.Lemmas.mem_union.\n      case/orP=> Hmem.\n      + exact: (conform_exp_mem _ _ _ _ Hco1 Hmem).\n      + exact: (conform_exp_mem _ _ _ _ Hco2 Hmem).\n    - move=> b e1 e2 /andP [/andP [Hco_b Hco1] Hco2].\n      rewrite !SSAVS.Lemmas.mem_union. (case/orP; last case/orP) => Hmem.\n      + exact: (conform_bexp_mem _ _ _ _ Hco_b Hmem).\n      + exact: (conform_exp_mem _ _ _ _ Hco1 Hmem).\n      + exact: (conform_exp_mem _ _ _ _ Hco2 Hmem).\n    (* conform_bexp_mem *)\n    case: e => //=.\n    - move=> _ e1 e2 /andP [Hco1 Hco2]. rewrite SSAVS.Lemmas.mem_union.\n      case/orP=> Hmem.\n      + exact: (conform_exp_mem _ _ _ _ Hco1 Hmem).\n      + exact: (conform_exp_mem _ _ _ _ Hco2 Hmem).\n    - move=> e Hco Hmem. exact: (conform_bexp_mem _ _ _ _ Hco Hmem).\n    - move=> e1 e2 /andP [Hco1 Hco2]. rewrite SSAVS.Lemmas.mem_union.\n      case/orP=> Hmem.\n      + exact: (conform_bexp_mem _ _ _ _ Hco1 Hmem).\n      + exact: (conform_bexp_mem _ _ _ _ Hco2 Hmem).\n    - move=> e1 e2 /andP [Hco1 Hco2]. rewrite SSAVS.Lemmas.mem_union.\n      case/orP=> Hmem.\n      + exact: (conform_bexp_mem _ _ _ _ Hco1 Hmem).\n      + exact: (conform_bexp_mem _ _ _ _ Hco2 Hmem).\n  Qed.\n\nEnd Conform .\n\nSection Adhere .\n\n  Definition adhere (m : vm) (te : SSATE.env) : Prop :=\n    forall v, SSAVM.mem v m -> exists ls, SSAVM.find v m = Some ls /\\\n                                          SSATE.vsize v te == size ls .\n  \nEnd Adhere .\n\nSection Bound .\n  Fixpoint bound_exp e (vm : vm) : bool :=\n    match e with\n    | QFBV.Evar v => SSAVM.mem v vm\n    | QFBV.Econst _ => true\n    | QFBV.Eunop op e => bound_exp e vm\n    | QFBV.Ebinop op e1 e2 => bound_exp e1 vm && bound_exp e2 vm\n    | QFBV.Eite b e1 e2 =>\n      bound_bexp b vm && bound_exp e1 vm && bound_exp e2 vm\n    end\n  with\n  bound_bexp b vm : bool :=\n    match b with\n    | QFBV.Bfalse\n    | QFBV.Btrue => true\n    | QFBV.Bbinop _ e1 e2 => bound_exp e1 vm && bound_exp e2 vm\n    | QFBV.Blneg b => bound_bexp b vm\n    | QFBV.Bconj b1 b2\n    | QFBV.Bdisj b1 b2 => bound_bexp b1 vm && bound_bexp b2 vm\n    end.\n\n  Lemma vm_preserve_bound_exp :\n    forall e vm vm', bound_exp e vm -> vm_preserve vm vm' -> bound_exp e vm'\n  with\n  vm_preserve_bound_bexp :\n    forall e vm vm', bound_bexp e vm -> vm_preserve vm vm' -> bound_bexp e vm' .\n  Proof .\n    (* vm_preserve_bound_exp *)\n    elim; rewrite /= .\n    - move => v vm vm' Hmem Hpsrv .\n      elim : (SSAVM.Lemmas.mem_find_some Hmem) => ls Hfind .\n      move : (Hpsrv v ls Hfind) .\n      exact : SSAVM.Lemmas.find_some_mem .\n    - done .\n    - move => unop e IHe vm vm' He Hpsrv .\n      exact : (IHe _ _ He Hpsrv) .\n    - move => binop e0 IH0 e1 IH1 vm vm' /andP [He0 He1] Hpsrv .\n      rewrite (IH0 _ _ He0 Hpsrv) (IH1 _ _ He1 Hpsrv) // .\n    - move => c e0 IH0 e1 IH1 vm vm' /andP [/andP [Hc He0] He1] Hpsrv .\n      rewrite (vm_preserve_bound_bexp c _ _ Hc Hpsrv)\n              (IH0 _ _ He0 Hpsrv) (IH1 _ _ He1 Hpsrv) // .\n    (* vm_preserve_bound_bexp *)\n    elim; rewrite /= .\n    - done .\n    - done .\n    - move => binop e0 e1 vm vm' /andP [He0 He1] Hpsrv .\n      rewrite (vm_preserve_bound_exp e0 _ _ He0 Hpsrv)\n              (vm_preserve_bound_exp e1 _ _ He1 Hpsrv) // .\n    - move => b IHb; exact : IHb .\n    - move => b0 IH0 b1 IH1 vm vm' /andP [Hb0 Hb1] Hpsrv .\n      rewrite (IH0 _ _ Hb0 Hpsrv) (IH1 _ _ Hb1 Hpsrv) // .\n    - move => b0 IH0 b1 IH1 vm vm' /andP [Hb0 Hb1] Hpsrv .\n      rewrite (IH0 _ _ Hb0 Hpsrv) (IH1 _ _ Hb1 Hpsrv) // .\n  Qed .\n\n  Lemma consistent_conform_exp :\n    forall e m te E s, bound_exp e m -> adhere m te ->\n                       consistent m E s -> conform_exp e s te\n  with\n  consistent_conform_bexp :\n    forall e m te E s, bound_bexp e m -> adhere m te ->\n                       consistent m E s -> conform_bexp e s te.\n  Proof .\n    (* consistent_conform_exp *)\n    elim; rewrite /= .\n    - move => v m te E s Hmem Had Hcon.\n      elim : (Had _ Hmem) => ls [Hfind Hsize] .\n      rewrite (eqP Hsize). \n      move: (Hcon v). rewrite /consistent1 Hfind => Henc. \n      apply /eqP. exact: (enc_bits_size Henc).\n    - done .\n    - done .\n    - elim => /= e0 IH0 e1 IH1 m te E s /andP [Hbnd0 Hbnd1] Had Hcon;\n      rewrite (IH0 _ _ _ _ Hbnd0 Had Hcon) (IH1 _ _ _ _ Hbnd1 Had Hcon) // .\n    - move => c e0 IH0 e1 IH1 m te E s \n                /andP [/andP [Hbndc Hbnd0] Hbnd1] Had Hcon.\n      rewrite (consistent_conform_bexp c _ _ _ _ Hbndc Had Hcon)\n              (IH0 _ _ _ _ Hbnd0 Had Hcon) (IH1 _ _ _ _ Hbnd1 Had Hcon) // .\n    (* consistent_conform_bexp *)\n    elim; rewrite /= .\n    - done .\n    - done .\n    - elim => e0 e1 m te E s /andP [Hbnd0 Hbnd1] Had Hcon;\n      rewrite (consistent_conform_exp e0 _ _ _ _ Hbnd0 Had Hcon)\n              (consistent_conform_exp e1 _ _ _ _ Hbnd1 Had Hcon) // .\n    - done . \n    - move => b0 IH0 b1 IH1 m te E s /andP [Hbnd0 Hbnd1] Had Hcon;\n      rewrite (IH0 _ _ _ _ Hbnd0 Had Hcon) (IH1 _ _ _ _ Hbnd1 Had Hcon) // .\n    - move => b0 IH0 b1 IH1 m te E s /andP [Hbnd0 Hbnd1] Had Hcon;\n      rewrite (IH0 _ _ _ _ Hbnd0 Had Hcon) (IH1 _ _ _ _ Hbnd1 Had Hcon) // .\n  Qed .\n\n  Fixpoint bound_bexps (bs : seq QFBV.bexp) vm : bool :=\n    match bs with\n    | [::] => true\n    | b :: bs' => bound_bexp b vm && bound_bexps bs' vm\n    end.\n\n  Lemma vm_preserve_bound_bexps :\n    forall es m m', vm_preserve m m' -> bound_bexps es m -> bound_bexps es m'.\n  Proof.\n    elim.\n    - move=> m m' Hpre. done.\n    - move=> e es IHes m m' Hpre /= /andP [Hbdem Hbdesm].\n      move: (vm_preserve_bound_bexp Hbdem Hpre) => Hbdem'.\n      move: (IHes _ _ Hpre Hbdesm) => Hbdesm'.\n        by rewrite Hbdem' Hbdesm'.\n  Qed.\n  \nEnd Bound .\n", "meta": {"author": "fmlab-iis", "repo": "coq-qfbv", "sha": "0e9521febd1564747723a773d25e54781e81b762", "save_path": "github-repos/coq/fmlab-iis-coq-qfbv", "path": "github-repos/coq/fmlab-iis-coq-qfbv/coq-qfbv-0e9521febd1564747723a773d25e54781e81b762/src/AdhereConform.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24993064803243029}}
{"text": "Require Import Coq.Lists.List. Import ListNotations.\nFrom SyDPaCC.Bsml Require Import  Model.Core Model.Pid\n     DataStructures.DistributedList\n     DataStructures.DistributedVector\n     Skeletons.StdLib Skeletons.MapReduce.\nFrom SyDPaCC.Core Require Import Bmf Parallelization.\nFrom SyDPaCC.Tree Require Import\n     LTree Closure Support.NOption BTree VerticalComposition.\nFrom SyDPaCC.Support Require Import Option UIP.\n\nGeneralizable All Variables.\n\nOpen Scope N_scope.\nOpen Scope sydpacc_scope.\n\n  (** * Parallel Binary Trees and their Algorithmic Skeletons *)\n\nModule Make (Import Bsml: Core.BSML).\n\n  Typeclasses eauto := (bfs).\n  \n  Module Pid       := Pid.Make Bsml.Bsp.\n  Module StdLib    := StdLib.Make Bsml Pid.\n  Module Import ReplPar   := ReplicatedValue.C Bsml Pid.\n  Module Import ParList   := DistributedList.C Bsml Pid.\n  Module Import MapReduce := MapReduce.Make Bsml Pid StdLib ParList ReplPar.\n\n  (** ** Parallel Linearized Binary Trees *)\n\n  Definition PLTree A B :=\n    { plt: par(list(segment A B)) | valid_tree(ParList.join plt) = true }.\n\n  Program Definition join `(plt: PLTree A B) : LTree A B :=\n    ParList.join plt.\n  Next Obligation.\n    now destruct plt.\n  Qed.\n  \n  #[export] Instance tc_ltree_pltree A B : TypeCorr (@join A B).\n  Proof.\n    repeat constructor.\n    intros [segs Hsegs]; simpl.\n    assert(H: exists psegs, ParList.join psegs = segs)\n      by apply surjective.\n    destruct H as [psegs Hpsegs].\n    assert(H: valid_tree(ParList.join psegs) = true)\n      by (subst; auto).\n    exists(exist _ psegs H).\n    unfold join. subst. simpl.\n    f_equal.\n    apply UIP.Bool.UIP.\n  Defined.\n\n  #[export] Instance tc_btree_pltree A B :\n    TypeCorr ( (@LTree.join A B) ∘ (@join A B) ).\n  Proof. typeclasses eauto. Defined.\n\n  (** ** Algorithmic Skeleetons on Parallel Linearized Binary Trees *)\n  \n  Section Skeletons.\n      \n    Definition map_par {A B C D} (kL:A->C) (kN:B->D) :\n      par (list (segment A B)) -> par (list (segment C D)) :=\n      Eval sydpacc in\n      parallel (List.map (map_local kL kN)).\n    \n    Program Definition map {A B C D} (kL:A->C) (kN:B->D) :\n      PLTree A B->PLTree C D :=\n      (map_par kL kN) ∘ (@proj1_sig _ _ ).\n    Next Obligation.\n      autounfold with sydpacc. unfold valid_tree, map_par.\n      erewrite @fun_corr with (fp:=MapReduce.par_map (map_local kL kN));\n        eauto; try typeclasses eauto.\n      destruct x as [ tree Htree ]. simpl proj1_sig.\n      set(H:=valid_tree_map).\n      specialize (H A B C D kL kN (ParList.join tree) Htree).\n      now unfold valid_tree in H.\n    Qed.\n\n    #[export] Instance map_ltree_map_par A B C D (kL:A->C) (kN:B->D):\n      FunCorr (LTree.map kL kN) (map kL kN).\n    Proof.\n      constructor. intros [plt Hplt] _.\n      unfold map, map_par, join, LTree.map. autounfold with sydpacc; simpl.\n      apply ltree_inj; simpl.\n      now apply fun_corr.\n    Defined.\n\n    #[export] Instance map_tree_map_par `(kL:A->C) `(kN:B->D):\n      FunCorr (BTree.map kL kN) (map kL kN).\n    Proof.\n      typeclasses eauto.\n    Defined.\n    \n    Definition reduce_par {A B C} (k: (A * B * A) -> A)\n               `{Hclose: @ClosureU A B C k phi psiN psiL psiR}\n               (v:par(list(segment A B))) :\n      option A :=\n      let local : par (list (sum A C)) :=\n          parfun (map_filter_some (reduce_local k phi psiL psiR))\n                 v in\n      let list : list (sum A C) := ParList.join local in\n      reduce_global psiN list. \n    \n    Definition reduce {A B C} (k: (A * B * A) -> A) \n               `{Hclose: @ClosureU A B C k phi psiN psiL psiR} :\n      PLTree A B -> option A := (reduce_par k) ∘ (@proj1_sig _ _).\n\n    (* Generalization of map correspondence, should be put in MapReduce: *)\n    #[export] Instance parfun_corr `(f:list A->list B)\n           `{H: Homomorphic _ _ f (@List.app _)} :\n      FunCorr f (parfun f).\n    Proof.\n      constructor. intros ap _.\n      unfold ParList.join.\n      apply Pid.pids_ind.\n      - simpl; autounfold with bsml.\n        now autorewrite with bsml list.\n      - intros n Hn IH; rewrite Pid.pid_up_to_succ.\n        autorewrite with bsml; rewrite IH.\n        autounfold with bsml; f_equal; simpl.\n        autorewrite with bsml list.\n        symmetry. apply homomorphic.\n    Defined.\n\n    #[export] Instance homorphic_map_filter_some `(f:A->option B) :\n      Homomorphic (map_filter_some f) (@List.app _).\n    Proof.\n      constructor. intros.\n      match goal with\n      |[ |- ?x = ?y ] => assert(H: List.map Some x = List.map Some y)\n      end.\n      repeat( repeat rewrite map_app; repeat rewrite map_filter_some_prop).\n      now rewrite filter_app.\n      apply Pid.map_inj with (f:=Some); auto.\n      intros a a' Heq. now inversion Heq.\n    Defined.\n      \n    #[export] Instance reduce_ltree_reduce_par `(k:A*B*A->A)\n             `{Hclose: @ClosureU A B C k phi psiN psiL psiR}:\n      FunCorr (LTree.reduce k) (reduce k).\n    Proof. \n      repeat constructor. intros [plt Hplt] _.\n      unfold reduce, reduce_par, LTree.reduce; autounfold with sydpacc.\n      unfold reduce_segs.\n      f_equal.\n      eapply @fun_corr with (join_A:=@ParList.join (segment A B)); eauto.\n      typeclasses eauto.\n    Defined.\n      \n    #[export] Instance reduce_tree_reduce_par `(k:A*B*A->A)\n           `{Hclose: @ClosureU A B C k phi psiN psiL psiR} :\n      FunCorr (Some ∘ (BTree.reduce k)) (reduce k)(join_B:=(fun x=>x)∘(fun x=>x)).\n    Proof. typeclasses eauto. Defined.\n    \n  End Skeletons.\n\nEnd Make.\n\nClose Scope sydpacc_scope.\nClose Scope N_scope.\n", "meta": {"author": "SyDPaCC", "repo": "sydpacc", "sha": "640f0f74f21524ee203b192255ecfa9e456fb7d1", "save_path": "github-repos/coq/SyDPaCC-sydpacc", "path": "github-repos/coq/SyDPaCC-sydpacc/sydpacc-640f0f74f21524ee203b192255ecfa9e456fb7d1/Tree/Skeletons.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.24993064262526826}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect.\nRequire Import ssrbool.\nRequire Import funs.\nRequire Import dataset.\nRequire Import ssrnat.\nRequire Import seq.\nRequire Import finset.\nRequire Import paths.\nRequire Import connect.\nRequire Import hypermap.\nRequire Import geometry.\nRequire Import color.\nRequire Import coloring.\nRequire Import cfmap.\nRequire Import ctree.\nRequire Import cfcolor.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* Compute the contract of a configuration construction: a cprog whose ring  *)\n(* colorings coincides with the contract colorings of the initial cprog.     *)\n(* Also, check the validity of the contract (sparseness, and possibly the    *)\n(* existence of a triad.                                                     *)\n(* The darts in the contract sequence are represented by the index at which  *)\n(* they are removed from the internal ring; each Y step (except the final    *)\n(* one) has a single index, while each H step has three. The first index of  *)\n(* the H step corresponds to the middle edge, which is actually never part   *)\n(* of a ring; the next two are for the left and right feet of the H.         *)\n(* The last Y does not have an index because it removes only one dart of the *)\n(* central edge pair.                                                        *)\n\nSection ConfigContract.\n\nFixpoint ctrmsize (cp : cprog) : nat :=\n  match cp with\n  | Adds (CpR _) cp' => ctrmsize cp'\n  | Adds CpY seq0 => 0\n  | Adds CpY cp' => S (ctrmsize cp')\n  | Adds CpH cp' => S (S (S (ctrmsize cp')))\n  | _ => 0\n  end.\n\nFixpoint ctrmask_rec (cci : natseq) (i n : nat) {struct n} : bitseq :=\n  if n is S n' then Adds (cci i) (ctrmask_rec cci (S i) n') else seq0.\n\nDefinition ctrmask (cp : cprog) (cci : natseq) : bitseq :=\n  ctrmask_rec cci 0 (ctrmsize cp).\n\nLemma size_ctrmask : forall cp ms, size (ctrmask cp ms) = ctrmsize cp.\nProof.\nby move=> cp ms; rewrite /ctrmask; elim: (ctrmsize cp) 0 => //= *; congr S.\nQed.\n\nFixpoint ctrenum (cp : cprog) : seq (cpmap cp) :=\n  match cp as cp' return (seq (cpmap cp')) with\n  | Adds (CpR _) cp' => ctrenum cp'\n  | Adds CpY cp' => let g := cpmap cp' in\n    if cp' is Seq0 then seq0 else maps (icpY g) (Adds (node g) (ctrenum cp'))\n  | Adds CpH cp' => let g := cpmap cp' in\n    Adds (face (ecpH g)) (maps (icpH g) (Seq (node g) g & (ctrenum cp')))\n  | _ => seq0\n  end.\n\nLemma size_ctrenum : forall cp, size (ctrenum cp) = ctrmsize cp.\nProof.\nelim=> [|[n||||||] cp Hrec] //=; rewrite -{}Hrec ?size_maps //.\nby case: cp => //= *; rewrite size_maps.\nQed.\n\nLemma insertE_icpY : forall (g : hypermap) (x : g) p,\n insertE (maps (icpY x) p) = maps (icpY x) (insertE p).\nProof. by move=> g x; elim=> // *; repeat congr Adds. Qed.\n\nLemma insertE_icpH : forall (g : hypermap) (x : g) p,\n insertE (maps (icpH x) p) = maps (icpH x) (insertE p).\nProof. by move=> g x; elim=> // *; repeat congr Adds. Qed.\n\nLemma uniq_ctrenum : forall cp,\n config_prog cp -> uniq (insertE (cat (cpring (cpmap cp)) (ctrenum cp))).\nProof.\nelim=> //=; case=> // [n||] cp Hrec.\n    move/Hrec=> {Hrec}; apply: etrans; set g := cpmap cp.\n    rewrite cpring_ecpR /rot !insertE_cat -catA uniq_catCA catA.\n    by rewrite -insertE_cat cat_take_drop.\ncase Dcp: cp => // [s cp']; move: Dcp => <- {c cp'} Hcp; move: {Hrec}(Hrec Hcp).\n  set g := cpmap cp => Hrec; rewrite cpring_ecpY.\n  rewrite -!cat1s !(@insertE_cat (ecpY g)) uniq_catCA.\n  rewrite {1}[cat]lock -!catA catA -lock uniq_catCA -!insertE_cat -maps_cat.\n  rewrite !cat1s -maps_adds -cat_adds -head_cpring insertE_cat.\n  rewrite (insertE_icpY g) uniq_cat (uniq_maps (@icpY_inj _ g)) Hrec.\n  by rewrite has_maps /comp /= /setU1 /= has_set0.\nmove=> Hcp; move: (cpmap_proper (config_prog_cubic Hcp)) {Hrec}(Hrec Hcp).\nset g := cpmap cp => Hgp Hrec.\nrewrite (cpring_ecpH Hgp) -!cat1s !(@insertE_cat (ecpH g)).\nrewrite {1}[cat]lock !catA -lock uniq_catCA {2 6}[cat]lock -!catA uniq_catCA.\nrewrite -!lock -!catA -3!insertE_cat !cat1s -maps_cat -!maps_adds.\nrewrite -!cat_adds -(head_proper_cpring Hgp) (insertE_icpH g) !catA.\nrewrite [insertE]lock /= /long_cpring /= Enode (negbE Hgp) /= -!lock.\nrewrite uniq_cat (uniq_maps (@icpH_inj _ g)) Hrec has_maps /comp /= /setU1 /=.\nby rewrite has_set0.\nQed.\n\nLet nsp (b : bool) := if b then orb else andb.\n\nFixpoint cfctr (mr mc : bitseq) (cp : cprog) {struct cp} : option cprog :=\n  match cp, mr, mc with\n  | Adds (CpR i) cp', _, _ =>\n    let mr' := rotr i mr in\n    if cfctr mr' mc cp' is Some cpc then\n      Some (Adds (CpR (count negb (take i mr'))) cpc)\n    else None\n  | Adds CpY seq0, (Seq b1 b2 b3 & _), _ =>\n    if nsp b1 b2 b3 then None else\n    Some (if b1 || (b2 || b3) then seq0 else seq1 CpY)\n  | Adds CpY cp', (Seq b1 b2 & mr'), (Seq b3 & mc') =>\n    if nsp b1 b2 b3 then None else\n    if cfctr (Adds b3 mr') mc' cp' is Some cpc then\n      Some (if b1 || b2 then cpc else Adds (if b3 then CpU else CpY) cpc)\n    else None\n  | Adds CpH cp', (Seq b1 b2 & mr'), (Seq b3 b4 b5 & mc') =>\n    if nsp b3 b1 b4 || nsp b3 b2 b5 then None else\n    if and3b b1 b2 (all (fun b => b) mr') then None else\n    if cfctr (Seq b4 b5 & mr') mc' cp' is Some cpc then\n      Some (if b3 then cpc else\n            if b1 then\n               if b2 then Adds CpA cpc else\n               if b5 then cpc else Adds CpK cpc\n             else\n               if b2 then (if b4 then cpc else Adds CpK cpc) else\n               if b4 then (if b5 then Adds CpU cpc else Adds CpY cpc) else\n               if b5 then Adds CpY cpc else Adds CpH cpc)\n     else None\n  | _, _, _ => None\n  end.\n\nLemma cfctr_config_prog : forall mr mc cp,\n if cfctr mr mc cp is Some _ then config_prog cp else true.\nProof.\nmove=> mr mc cp; elim: cp mr mc => //=; case=> // [n||] cp Hrec mr mc.\n- by case: (cfctr (rotr n mr) mc cp) (Hrec (rotr n mr) mc).\n- case Dcp: cp mr => [|s cp'] [|b1 [|b2 mr]] //.\n    case: mr => [|b3 mr]; last by case (nsp b1 b2 b3).\n    by case: mc => [|b3 mc] //; case: (nsp b1 b2 b3).\n  rewrite -{}Dcp; case: mc => [|b3 mc] //; case: (nsp b1 b2 b3) => //.\n  by case: (cfctr (Adds b3 mr) mc cp) (Hrec (Adds b3 mr) mc).\ncase: mr mc => [|b1 [|b2 mr]] [|b3 [|b4 [|b5 mc]]] //=.\ncase: (nsp b3 b1 b4 || nsp b3 b2 b5) => //.\ncase: (and3b _ _ _) => //.\nby set mr' := Seq b4 b5 & mr; case: (cfctr mr' mc cp) (Hrec mr' mc).\nQed.\n\nLemma cfctr_correct : forall mr mc cp,\n  size mr = cprsize cp -> size mc = ctrmsize cp ->\n  let g := cpmap cp in let r := cpring g in\n  let cc := cat (sieve mr r) (sieve mc (ctrenum cp)) in\n  forall k : g -> color, cc_coloring cc k ->\n  if cfctr mr mc cp is Some cpc then\n    let r' := cpring (cpmap cpc) in\n    exists2 k', coloring k' & maps k' r' = maps k (sieve (maps negb mr) r)\n  else True.\nProof.\nmove=> /= mr mc cp; elim: cp mr mc => [|s cp Hrec] mr mc //.\nmove: (cfctr_config_prog mr mc (Adds s cp)).\ncase Dcpc: (cfctr mr mc (Adds s cp)) => // [cpc].\ncase: s Dcpc => // [n||] Dcpc Hcp' Emr Emc;\n  have Hcp := config_prog_cubic Hcp'; simpl in Dcpc, Hcp, Emr, Emc;\n  move: Hrec (cpmap_plain Hcp) (cpmap_proper Hcp); rewrite /cpmap -/cpmap;\n  set g := cpmap cp => Hrec HgE Hgp.\n- rewrite cpring_ecpR; rewrite -(size_rotr n) in Emr.\n  move=> k [HkE HkF]; move: {Hrec}(Hrec _ _ Emr Emc k).\n  case: (cfctr (rotr n mr) mc cp) cpc Dcpc => // [cpc] _ [<-].\n  rewrite /cpmap -/cpmap; set gc := cpmap cpc.\n  case; first split=> // x.\n    rewrite HkE !(mem_insertE HgE); apply: {x}eq_has_r => x.\n    rewrite !mem_cat; congr orb; rewrite -{1}(rot_rotr n mr).\n    by apply: mem_sieve_rot; rewrite Emr -size_ring_cpmap.\n  move=> k' Hk' Ek'; exists k'; first done.\n  rewrite cpring_ecpR -{3}(rot_rotr n mr) !maps_rot {}Ek' sieve_rot.\n    by rewrite maps_rot -maps_take count_maps.\n  by rewrite size_maps /g size_ring_cpmap.\n- rewrite /g.\n  case Dcp: cp mc mr Emc Emr Dcpc => [|s cp'] [|b3 mc] [|b1 [|b2 mr]] //.\n    case: mr {cp Dcp Hcp' Hcp g Hrec HgE Hgp} => [|b3 [|b4 mr]] // _ _.\n    case Hb123: (nsp b1 b2 b3) => // [] [<-] {cpc}; rewrite cpring_ecpY.\n    set x0 : cpmap seq0 := cpmap seq0.\n    case: b1 Hb123; case: b2 => //; case: b3 => // _ k [HkE HkF].\n    - exists (fun y => k (icpY x0 y)).\n        by split; [ move=> y; case: y (HkE (icpY x0 y)) | case; apply/eqP ].\n      congr Adds; move: (HkE (node (ecpY _))); rewrite /= /setU1 /=; move/eqcP.\n      by rewrite /= -(eqcP (HkF _)) /=; move->; rewrite -(eqcP (HkF _)) /=.\n    - exists (fun y => k (icpY x0 y)).\n        by split; [ move=> y; case: y (HkE (icpY x0 y)) | case; apply/eqP ].\n      by congr Adds; rewrite /= -(eqcP (HkF _)).\n    - exists (fun y => k (if y is true then ecpY x0 else node (ecpY x0))) => //.\n      split; last by case; apply/eqP.\n      have HkEx0 := HkE (node (ecpY x0)).\n      rewrite /invariant -(eqcP (HkF _)) Enode in HkEx0.\n      by case=> //; rewrite /invariant eqd_sym.\n    by exists k; split.\n  rewrite -Dcp cpring_ecpY [size _]/= [size _ = _]/= => [] [Emc] [Emr].\n  have Ecp: ctrenum (Adds CpY cp) = maps (icpY g) (Adds (node g) (ctrenum cp)).\n    by rewrite /= /g Dcp.\n  have Hg'E: plain (ecpY g) by apply: plain_ecpY.\n  case Hb123: (nsp b1 b2 b3) {s cp' Dcp} => //.\n  case: (cfctr (Adds b3 mr) mc cp) {Hrec Emr}(Hrec (Adds b3 mr) mc Emr Emc) => //.\n  move: cpc => _ cpc Hrec [<-] k [HkE HkF].\n  pose h x := k (icpY g x).\n  have HhF: invariant face h =1 g.\n    move=> x; apply/eqP; apply: (fconnect_invariant HkF).\n    by rewrite cface_icpY Sface fconnect1.\n  have HhE: invariant edge h =1\n             insertE (cat (sieve (Adds b3 mr) (cpring g)) (sieve mc (ctrenum cp))).\n    move=> x; rewrite /invariant /h -icpY_edge; apply: (etrans (HkE _)).\n    rewrite !mem_insertE // /behead -/g head_cpring Ecp.\n    rewrite (eq_has (plain_orbit HgE x)) (eq_has (plain_orbit Hg'E (icpY g x))).\n    rewrite !has_cat icpY_edge maps_adds !has_sieve_adds !andbF !orFb.\n    by rewrite orbCA -!orbA; congr orb; rewrite -!maps_sieve !has_maps.\n  case: {Hrec}(Hrec h) {Emc}; first by split.\n  set gc := cpmap cpc => h' Hh' Eh.\n  move: Hh' (coloring_proper_cpring gc Hh') => [Hh'E Hh'F] Hgcp.\n  case Hb12: (b1 || b2).\n    exists h'; first by split.\n    rewrite -/gc {h' HhE Hh'E Hh'F Eh'nX}Eh /behead head_cpring /h.\n    rewrite !maps_sieve (maps_comp k (icpY _)) !maps_adds.\n    rewrite -/g -(fconnect_invariant HkF (cface_node_ecpY g)).\n    case: b1 b2 b3 Hb12 Hb123 HkE => [|] [|] [|] // _ _ HkE; congr Adds.\n    move: (etrans (HkE _) (setU11 _ _)).\n    by rewrite /invariant -(eqcP (HkF _)) Enode; move/eqP.\n  have HrgE: all (invariant edge h) (sieve (Adds b3 mr) (cpring g)).\n    apply/allP => [x Hx]; rewrite HhE mem_insertE //.\n    apply/hasP; exists x; last by apply connect0.\n    by rewrite mem_cat /setU Hx.\n  have HrgN: fpath (finv node) (node g) (behead (cpring g)).\n  move: (cycle_rev_cpring g); rewrite head_cpring lastI rev_add_last -lastI.\n    by rewrite (cycle_path g) /= -(fpath_finv (Inode g)); case/andP.\n  have Eh'nX: h' (node gc) = h (node g).\n    rewrite head_cpring in Eh; move: HrgE Eh {HhE HkE}; rewrite head_cpring.\n    elim: {mr}(Adds b3 mr) (node g) (behead (cpring g)) HrgN => // [b mr Hrec].\n    case: b; last by move=> x p _ _ [Dx _].\n    move=> x [|y p] //=; first by case mr.\n    case/andP; move/eqP=> Dy Hp; case/andP; move/eqcP=> <-.\n    rewrite -(eqcP (HhF (edge x))) -(f_finv (Inode g) x) Enode Dy; eauto.\n  case: b1 b2 b3 Hb12 Eh HkE HhE HrgE {Hb123} => [|] [|] [|] // _ Eh HkE HhE HrgE.\n    pose a u x := cface u (icpU gc x).\n    have EaF: a =2 comp a face by move=> u x; exact: cface1.\n    pose k' u := if pick (a u) is Some x then h' x else k (ecpY g).\n    have Hk'F: invariant face k' =1 ecpU gc.\n      by move=> u; apply/eqP; rewrite /k' (eq_pick (EaF u)).\n    have Ek': forall x, k' (icpU gc x) = h' x.\n      move=> x; rewrite /k'; case: pickP => [y Hy|Hx].\n        by rewrite /a cface_icpU Sface in Hy; apply: (fconnect_invariant Hh'F).\n      case/idP: (Hx x); exact: connect0.\n    have Ek'X: k' (ecpU gc) = k (ecpY g).\n      by rewrite /k'; case: pickP => // y; rewrite /a cface_ecpU.\n    have Ek'nX: k' (node (ecpU gc)) = k (node (ecpY g)).\n      rewrite /g (fconnect_invariant HkF (cface_node_ecpY _)).\n      by rewrite -(eqcP (Hk'F _)) /= -/(icpU gc) Ek' -/gc Eh'nX.\n    exists k'; first split=> //.\n      have Hk'EX: invariant edge k' (ecpU gc) = false.\n        apply/eqP => Hk'X; move: (esym (HkE (node (ecpY g)))).\n        rewrite /invariant -Ek'nX -(eqcP (HkF _)) Enode -Ek'X -Hk'X set11.\n        move: (uniq_ctrenum Hcp'); rewrite /cpmap -/cpmap -/g cpring_ecpY.\n        move: {mc HkE HhE}(Adds true mc) (ctrenum (Adds CpY cp)) => mc p.\n        move: (node (ecpY g)) => x /=; move/andP=> [H _]; move: H.\n        do 3 case/norP => _; rewrite !(mem_insertE Hg'E).\n        move=> H; move/hasP=> [y Hy Hxy]; case/hasP: H; exists y; auto.\n        rewrite !mem_cat in Hy |- *; apply/orP; case/orP: Hy; move/mem_sieve; auto.\n      move=> [||x] //; first by rewrite /invariant eqd_sym.\n      rewrite -/cpmap -/gc in x |- *; rewrite -/(icpU gc x).\n      rewrite /invariant -(icpU_edge gc) !Ek'; exact: Hh'E.\n    rewrite /cpmap -/cpmap cpring_ecpU !maps_adds {1 2}/negb.\n    rewrite -/gc Ek'nX !sieve_adds !maps_cat !maps_seqn Ek'X; do 2 congr Adds.\n    rewrite -maps_sieve -!maps_comp /comp -/h.\n    by rewrite (@eq_maps _ _ (comp k' (icpU _)) _ Ek') -/gc Eh head_cpring.\n  pose a u x := cface u (icpY gc x).\n  have EaF: a =2 comp a face by move=> u x; exact: cface1.\n  pose k' u := if pick (a u) is Some x then h' x else k (ecpY g).\n  have Hk'F: invariant face k' =1 ecpY gc.\n    by move=> u; apply/eqP; rewrite /k' (eq_pick (EaF u)).\n  have Ek': forall x, k' (icpY gc x) = h' x.\n    move=> x; rewrite /k' -/gc; case: pickP => [y Hy|Hx].\n      by rewrite /a cface_icpY Sface in Hy; apply: (fconnect_invariant Hh'F).\n    case/idP: (Hx x); exact: connect0.\n  have Ek'X: k' (ecpY gc) = k (ecpY g).\n    by rewrite /k' -/gc; case: pickP => // y; rewrite /a cface_ecpY.\n  have Ek'nX: k' (node (ecpY gc)) = k (node (ecpY g)).\n    rewrite (fconnect_invariant Hk'F (cface_node_ecpY _)) Ek' Eh'nX.\n    by rewrite /g (fconnect_invariant HkF (cface_node_ecpY _)).\n  have Eh'X: h' gc = h g.\n    rewrite head_proper_cpring // in Eh.\n    move: HrgN Eh HrgE {HhE HkE}; rewrite head_proper_cpring //=.\n    case/andP=> [_ H] [_ E]; move: H E.\n    elim: mr (g : g) (drop 2 (cpring g)) => // [b mr Hrec].\n    case: b; last by move=> x p _ [Dx _].\n    move=> x [|y p] //=; first by case mr.\n    case/andP; move/eqP=> Dy Hp Eh; case/andP; move/eqcP=> <-; move: Eh.\n    by rewrite -(eqcP (HhF (edge x))) -(f_finv (Inode g) x) Enode Dy; eauto.\n  exists k'; first split => //.\n    have Hk'EX: forall u, cface u (ecpY gc) -> invariant edge k' u = false.\n      move=> u HuX; rewrite /invariant (fconnect_invariant Hk'F HuX) Ek'X.\n      have HeuX: adj (ecpY gc) (edge u) by rewrite -(adjF HuX) adjE.\n      rewrite (adj_ecpY Hgcp) /fband in HeuX; case/hasP: HeuX {HuX} => v.\n      case/mapsP=> [y Hy <-] {v} H; rewrite {u H}(fconnect_invariant Hk'F H) Ek'.\n      move: (uniq_ctrenum Hcp') HkE; rewrite /cpmap -/cpmap -/g cpring_ecpY.\n      move: {mc HkE HhE}(Adds false mc) (ctrenum (Adds CpY cp)) {x Hx} => mc p.\n      move Dx: (ecpY g : ecpY g) => x; move Dnx: (node x) => nx.\n      simpl; case/and4P=> [H _ H' _]; move: H H'; rewrite /setU1 /=.\n      do 3 case/norP => _; rewrite !(mem_insertE Hg'E).\n      move=> Hnx; move/norP=> [_ Hx] HkE.\n      rewrite mem_seq2 in Hy; case/orP: Hy; move/eqP=> <- {y}.\n        rewrite -[x]Enode Dnx Eh'nX /h eqd_sym.\n        move: (eqcP (HkF (edge nx))) (fconnect_invariant HkF (cface_node_ecpY _)).\n        rewrite -/g; move->; move <-; rewrite Dx Dnx.\n        apply: (etrans (HkE nx)); rewrite (mem_insertE Hg'E).\n        apply/hasP => [] [z Hz Hxz]; case/hasP: Hnx; exists z; last done.\n        rewrite !mem_cat in Hz |- *; apply/orP; case/orP: Hz; move/mem_sieve; auto.\n      have <-: k (edge x) = h' gc.\n        by rewrite -(eqcP (HkF (edge x))) -/g Eh'X -Dx /= Enode (negbE Hgp) /=.\n      apply: (etrans (HkE x)); rewrite (mem_insertE Hg'E).\n      apply/hasP => [] [z Hz Hxz]; case/hasP: Hx; exists z; last done.\n      rewrite !mem_cat in Hz |- *; apply/orP; case/orP: Hz; move/mem_sieve; auto.\n    move=> u; case: (@fband_icpY _ gc u) => [[x Hx]|Hu].\n      case: (@fband_icpY _ gc (edge u)) => [[y Hy]|Heu].\n        rewrite /invariant (fconnect_invariant Hk'F Hx).\n        rewrite (fconnect_invariant Hk'F Hy) !Ek'.\n        have Hxy: adj x y.\n          by rewrite -(adj_icpY gc); apply/adjP; exists u; rewrite // Sface.\n        case/adjP: Hxy => [z Hxz Hzy]; rewrite (fconnect_invariant Hh'F Hxz).\n        rewrite -(fconnect_invariant Hh'F Hzy); exact: Hh'E.\n      have Deeu: edge (edge u) = u.\n        by move: Heu {Hx}; rewrite cface_ecpY; case: u => [||[||z]].\n      by rewrite /invariant eqd_sym -{1}Deeu; apply: Hk'EX; rewrite Sface.\n    by apply: Hk'EX; rewrite Sface.\n  rewrite /cpmap -/cpmap !cpring_ecpY !maps_adds {1 2}/negb -/gc.\n  rewrite Ek'nX !sieve_adds !maps_cat !maps_seqn Ek'X; do 2 congr Adds.\n  rewrite -maps_sieve -!maps_comp /comp -/gc -/h.\n  rewrite (@eq_maps _ _ (comp k' (icpY gc)) _ Ek').\n  by rewrite head_cpring (head_cpring g) in Eh; case: Eh.\ncase: mr mc Emc Emr Dcpc => [|b1 [|b2 mr]] // [|b3 [|b4 [|b5 mc]]] //.\ncase Hb: (nsp b3 b1 b4 || nsp b3 b2 b5); first done.\ncase HbA: (and3b _ _ _); first done.\nrewrite [size _]/= [size _ = _]/= => [] [Emc] [Emr].\nmove: {Hrec}(Hrec (Adds b4 (Adds b5 mr)) mc Emr Emc).\ncase: (cfctr (Seq b4 b5 & mr) mc cp) cpc => // [cpc] _ Hrec [<-] k [HkE HkF].\npose h x := k (icpH g x).\nhave HhF: invariant face h =1 g.\n  move=> x; apply/eqP; apply: (fconnect_invariant HkF).\n  by rewrite cface_icpH Sface fconnect1.\nhave Hg'E := plain_ecpH g HgE.\nhave HhE: invariant edge h =1\n   insertE (cat (sieve (Seq b4 b5 & mr) (cpring g)) (sieve mc (ctrenum cp))).\n  move=> x; rewrite /invariant /h -icpH_edge; apply: (etrans (HkE _)).\n  rewrite !mem_insertE // cpring_ecpH //.\n  rewrite {2}head_proper_cpring //.\n  rewrite (eq_has (plain_orbit HgE x)) (eq_has (plain_orbit Hg'E (icpH g x))).\n  rewrite !has_cat icpH_edge [ctrenum _]/= !has_sieve_adds.\n  rewrite !andbF !orFb orbCA -!orbA; congr 1 orb.\n  rewrite [_ && _]/= /long_cpring [_ && _]/= Enode (negbE Hgp) andbF orFb orbCA.\n  by do 2 congr orb; rewrite -maps_sieve has_maps; apply: eq_has.\ncase: {Hrec}(Hrec h); first by split.\nset gc := cpmap cpc => h' Hh' Eh.\nmove: Hh' (coloring_proper_cpring gc Hh') => [Hh'E Hh'F] Hgcp.\nhave EkefX: k (edge (face (ecpH g))) = h g.\n  apply: (fconnect_invariant HkF); apply connect1; apply/eqP.\n  by rewrite /= Enode (negbE Hgp).\nhave HrgE: (all (invariant edge h) (sieve (Seq b4 b5 & mr) (cpring g))).\n  apply/allP => [x Hx]; rewrite HhE mem_insertE //.\n  apply/hasP; exists x; last exact: connect0.\n  by rewrite mem_cat /setU Hx.\nhave HrgN: (fpath (finv node) (node g) (add_last (behead (cpring g)) (node g))).\n  rewrite (fpath_finv (Inode g)) last_add_last belast_add_last -head_cpring.\n  move: (cycle_rev_cpring g).\n  by rewrite head_cpring (cycle_path g) rev_adds last_add_last.\ncase: b3 Hb HhE HrgE HkE Eh.\n  case: b1 {HbA} => //; case: b2 => //; case: b4 b5 => [|] [|] // _ _ _ HkE Eh.\n  exists h'; first by split.\n  rewrite -/gc Eh head_proper_cpring // cpring_ecpH //.\n  rewrite !maps_sieve !maps_adds -maps_comp.\n  rewrite (fconnect_invariant HkF (cface_node_ecpH Hgp)) -/(h (node g)).\n  do 2 congr Adds; apply: eqP; rewrite -(eqcP (HkF _)) -EkefX.\n  apply: (etrans (HkE _)).\n  by rewrite insertE_cat mem_cat; apply/orP; right; exact: setU11.\ncase Hb12: (b1 && b2).\n  case: b1 Hb12 HbA => //; case: b2 => //  _ HbA.\n  case: b4 => //; case: b5 => // _ HhE HrgE HkE Eh.\n  have Hgcl: long_cpring gc.\n    rewrite size_long_cpring -(size_maps h') Eh; move/(introT eqP): Emr HbA.\n    rewrite -size_ring_cpmap -/g; case: (cpring g) => [|x0 [|x1 p]] {x0 x1}//=.\n    by rewrite !ltnS !eqdSS; elim: (mr) p => [|[|] m Hrec] [|x p] //=; auto.\n  rewrite (head_proper_cpring Hgp) head_proper_cpring //= in Eh.\n  move: Eh => [EhnX EhX Eh].\n  have EhfeX: h' (face (edge gc)) = h (face (edge g)).\n    rewrite head_long_cpring //= in Eh; move: HrgN Eh HrgE.\n    rewrite head_proper_cpring //= drop0; case/andP=> _.\n    elim: (mr) {-2}(g : g) (drop 2 (cpring g)) => [|b m Hrec] // x [|y p] //=.\n    case/andP; move/eqP=> Dy Hp; rewrite -(finv_eq_monic (Enode g) x) Dy.\n    case: b; last by case.\n    move=> /= Eh; case/andP; move/eqcP=> <- Hmp.\n    by rewrite -(eqcP (HhF (edge y))); eauto.\n  have Eh'A: h' (node gc) = h' (face (edge gc)).\n    rewrite EhnX EhfeX (eqcP (HhF (edge g))).\n    rewrite /h -(fconnect_invariant HkF (cface_node_ecpH Hgp)).\n    transitivity (k (face (edge (node (ecpH g))))); apply: eqP.\n      rewrite eqd_sym (eqcP (HkF _)); apply: (etrans (HkE _)).\n      rewrite head_cpring; exact: setU11.\n    rewrite Enode eqd_sym -(eqcP (HkF _)) /= Enode (negbE Hgp) set11.\n    apply: (etrans (HkE (ecpH g))).\n    by rewrite cpring_ecpH //; do 2 apply: setU1r; apply: setU11.\n  have Hh'FA: @invariant (ecpA gc) face _ h' =1 gc.\n    rewrite /invariant /= /ecpA_face => x.\n    case (cface (edge gc) (node gc)); first exact: Hh'F.\n    case: (x =P edge gc) => [Dx|_].\n      by rewrite /setA -(eqcP (Hh'F x)) Dx -Eh'A set11.\n    case: (face x =P node gc) => [Dx|_]; last exact: Hh'F.\n    by rewrite /setA -(eqcP (Hh'F x)) Dx -Eh'A set11.\n  exists h'.\n    split; last done; rewrite /invariant /= /ecpA_edge /= -/gc => x.\n    case (cface (edge gc) (node gc)); last exact: Hh'E.\n     case: (x =P gc) => /= [Dx|_].\n       rewrite -(eqcP (Hh'F _)) Enode Eh'A (eqcP (Hh'F _)) Dx; exact: Hh'E.\n     case: (x =P node (node gc)) => /= [Dx|_]; last exact: Hh'E.\n     rewrite -(eqcP (Hh'F _)) -Eh'A -[node gc]Enode -Dx (eqcP (Hh'F _)).\n     exact: Hh'E.\n  rewrite /cpmap -/cpmap -/gc cpring_ecpA Hgcl cpring_ecpH //=.\n  by rewrite -maps_sieve -maps_comp; rewrite drop_behead in Eh.\ncase: b1 b2 b4 b5 Hb12 {HbA} => [|] [|] // [|] [|] // _ _;\n  rewrite /cpmap -/cpmap -/gc.\n- move=> _ _ HkE Eh; exists h'; first by split.\n  rewrite Eh (head_proper_cpring Hgp) cpring_ecpH // !maps_sieve !maps_adds.\n  rewrite -maps_comp; congr Adds; apply: eqP.\n  rewrite /h -(fconnect_invariant HkF (cface_node_ecpH Hgp)) eqd_sym.\n  rewrite -{1}[ecpH g : dart _]Enode (eqcP (HkF _)).\n  by apply: (etrans (HkE _)); rewrite head_cpring; exact: setU11.\n- move=> HhE HrgE HkE Eh.\n  pose a u x := cface u (icpK gc x).\n  have EaF: a =2 comp a face by move=> u x; exact: cface1.\n  pose k' u := if pick (a u) is Some x then h' x else Color0.\n  have Hk'F: invariant face k' =1 ecpK gc.\n    by move=> u; apply/eqP; rewrite /k' (eq_pick (EaF u)).\n  have Ek': forall x, k' (icpK _ x) = h' x.\n    move=> x; rewrite /k' -/gc; case: pickP => [y Hy|Hx].\n      by rewrite /a cface_icpK Sface in Hy; apply: (fconnect_invariant Hh'F).\n    case/idP: (Hx x); exact: connect0.\n  rewrite (head_proper_cpring Hgp) (head_proper_cpring Hgcp) /= in Eh.\n  move: Eh => [EhnX EhX Eh].\n  have EkX: (k (ecpH g) = h' (node gc)).\n    apply: eqP; rewrite EhnX -[ecpH g : ecpH g]Enode (eqcP (HkF _)).\n    rewrite /h -(fconnect_invariant HkF (cface_node_ecpH Hgp)).\n    apply: (etrans (HkE _)); rewrite head_cpring; exact: setU11.\n  exists k'; first split=> //.\n    set x0 : ecpK gc := ecpN (ecpR' gc).\n    have Hk'EX: invariant edge k' x0 = false.\n      rewrite /invariant; have <-: h' (face (edge gc)) = k' (edge x0).\n        rewrite (eqcP (Hh'F _)) -Ek'; apply: (fconnect_invariant Hk'F).\n        by apply connect1; apply/eqP; rewrite /ecpK /x0 ecpR'_eq /= Enode set11.\n      have <-: k (ecpH g) = k' x0.\n        symmetry; rewrite EkX -Ek'; apply: (fconnect_invariant Hk'F).\n        by apply connect1; apply/eqP; rewrite /ecpK /x0 ecpR'_eq.\n      have <-: (h (face (edge g)) = h' (face (edge gc))).\n        move: HrgN HrgE (introT eqP Emr); rewrite -size_ring_cpmap -/g.\n        rewrite (head_proper_cpring Hgp) /= !eqdSS; case/andP; clear.\n        move: {-2}(g : g) (drop 2 (cpring g)) Eh.\n        elim: (mr) => [|b m Hrec] x [|y p] //= Eh; case/andP;\n         move/eqP=> Dy; rewrite -(finv_eq_monic (Enode g) x) {}Dy.\n          have Hgcl: long_cpring gc = false; last by move/eqP: Hgcl => ->.\n          by rewrite size_long_cpring -(size_maps h') head_proper_cpring //= Eh.\n        case: b Eh => [|] /= Eh Hp.\n          by case/andP; move/eqcP=> <-; rewrite -(eqcP (HhF (edge y))); eauto.\n        have Hgcl: long_cpring gc.\n          by rewrite size_long_cpring -(size_maps h') head_proper_cpring //= Eh.\n        by rewrite head_long_cpring // in Eh; case: Eh.\n      have <-: k (edge (ecpH g)) = h (face (edge g)).\n        rewrite (eqcP (HhF (edge g))); symmetry; apply: (fconnect_invariant HkF).\n        by apply: connect1; apply/eqP; rewrite /= Enode (negbE Hgp) set11.\n      apply: (etrans (HkE _)).\n      move: (uniq_ctrenum Hcp'); rewrite /cpmap -/cpmap -/g cpring_ecpH //.\n      rewrite !cat_adds -2!cat1s 2!insertE_cat uniq_catC -catA uniq_cat.\n      case/and3P=> [_ Ug _]; rewrite -rot_size_cat has_rot -insertE_cat in Ug.\n      rewrite has_sym catA in Ug; move: {Ug}(hasPn Ug _ (setU11 _ _)).\n      rewrite !mem_insertE //; move=> Ug; apply/hasP => [[v Hv Huv]].\n      case/hasP: Ug; exists v; last done; move: Hv; rewrite !mem_cat.\n      case/orP=> Hv; apply/orP; last by right; apply: (mem_sieve Hv).\n      by left; apply: (@mem_sieve _ (Adds true mr)).\n    move=> [||x] //; first by rewrite /invariant eqd_sym.\n    rewrite -[Icp x]/(icpK gc x) /invariant icpK_edge !Ek'; exact: Hh'E.\n  rewrite cpring_ecpK cpring_ecpH // maps_sieve !maps_adds -!maps_comp.\n  rewrite (@eq_maps _ _ (comp k' (icpK gc)) _ Ek') Eh maps_sieve; congr Adds.\n  by rewrite EkX (fconnect_invariant Hk'F (cface_node_ecpK _)) Ek'.\n- move=> HhE _ _ Eh; exists h'; first by split.\n  rewrite Eh (head_proper_cpring Hgp) cpring_ecpH // !maps_sieve !maps_adds.\n  rewrite -maps_comp; congr Adds; apply: eqP.\n  rewrite (fconnect_invariant HkF (cface_node_ecpH Hgp)).\n  rewrite -{1}[g : g]Enode (eqcP (HhF _)).\n  by apply: (etrans (HhE _)); rewrite head_cpring; apply: setU11.\n- move=> HhE HrgE HkE Eh.\n  pose a u x := cface u (icpK gc x).\n  have EaF: a =2 comp a face by move=> u x; exact: cface1.\n  pose k' u := if pick (a u) is Some x then h' x else Color0.\n  have Hk'F: invariant face k' =1 ecpK gc.\n    by move=> u; apply/eqP; rewrite /k' (eq_pick (EaF u)).\n  have Ek': forall x, k' (icpK _ x) = h' x.\n    move=> x; rewrite /k' -/gc; case: pickP => [y Hy|Hx].\n      by rewrite /a cface_icpK Sface in Hy; apply: (fconnect_invariant Hh'F).\n    case/idP: (Hx x); exact: connect0.\n  rewrite (head_proper_cpring Hgp) (head_proper_cpring Hgcp) /= in Eh.\n  move: Eh => [EhnX EhX Eh].\n  exists k'; first split=> //.\n    set x0 : ecpK gc := ecpN (ecpR' gc).\n    have Hk'EX: invariant edge k' x0 = false.\n      rewrite /invariant; have <-: h' (face (edge gc)) = k' (edge x0).\n        rewrite (eqcP (Hh'F _)) -Ek'; apply: (fconnect_invariant Hk'F).\n        by apply connect1; apply/eqP; rewrite /ecpK /x0 ecpR'_eq /= Enode set11.\n      have <-: h (face (edge g)) = h' (face (edge gc)).\n      move: HrgN HrgE (introT eqP Emr); rewrite -size_ring_cpmap -/g.\n        rewrite (head_proper_cpring Hgp) /= !eqdSS; case/andP=> _.\n        move: {-2}(g : g) (drop 2 (cpring g)) Eh.\n        elim: (mr) => [|b m Hrec] x [|y p] //= Eh; case/andP;\n          move/eqP=> Dy; rewrite -(finv_eq_monic (Enode g) x) {}Dy.\n          have Hgcl: long_cpring gc = false.\n            by rewrite size_long_cpring -(size_maps h') head_proper_cpring //= Eh.\n          by move/eqP: Hgcl; move->.\n        case: b Eh => [|] /= Eh Hp.\n          by case/andP; move/eqcP=> <-; rewrite -(eqcP (HhF (edge y))); eauto.\n        have Hgcl: (long_cpring gc).\n          by rewrite size_long_cpring -(size_maps h') head_proper_cpring //= Eh.\n        by rewrite head_long_cpring // in Eh; case: Eh.\n      have <-: k (edge (ecpH g)) = h (face (edge g)).\n        rewrite (eqcP (HhF (edge g))); symmetry; apply: (fconnect_invariant HkF).\n        by apply: connect1; apply/eqP; rewrite /= Enode (negbE Hgp) set11.\n      have <-: k (node (ecpH g)) = k' x0.\n        rewrite (fconnect_invariant HkF (cface_node_ecpH Hgp)) -/(h (node g)).\n        symmetry; rewrite -EhnX -Ek'; apply: (fconnect_invariant Hk'F).\n        by apply connect1; apply/eqP; rewrite /ecpK /x0 ecpR'_eq.\n      have <-: k (edge (node (ecpH g))) = k (edge (ecpH g)).\n        rewrite -(eqcP (HkF _)) Enode; symmetry; apply: eqP.\n        apply: (etrans (HkE _)); rewrite cpring_ecpH //; exact: setU11.\n      apply: (etrans (HkE _)).\n      move: (uniq_ctrenum Hcp'); rewrite /cpmap -/cpmap -/g cpring_ecpH //.\n      rewrite !cat_adds -cat1s insertE_cat uniq_cat; case/and3P=> [_ Ug _].\n      rewrite has_sym -cat_adds in Ug; move: {Ug}(hasPn Ug _ (setU11 _ _)).\n      rewrite !mem_insertE // => Ug; apply/hasP => [] [v Hv Huv].\n      case/hasP: Ug; exists v; last done; move: Hv; rewrite !mem_cat.\n      case/orP=> Hv; apply/orP; last by right; apply: (mem_sieve Hv).\n      by left; apply: (@mem_sieve _ (Adds true mr)).\n    move=> [||x] //; first by rewrite /invariant eqd_sym.\n    rewrite -[Icp x]/(icpK gc x) /invariant icpK_edge !Ek'; exact: Hh'E.\n  rewrite cpring_ecpK cpring_ecpH // maps_sieve !maps_adds -!maps_comp.\n  rewrite (@eq_maps _ _ (comp k' (icpK gc)) _ Ek') Eh maps_sieve; congr Adds.\n  rewrite (fconnect_invariant Hk'F (cface_node_ecpK _)) Ek'.\n  by rewrite (fconnect_invariant HkF (cface_node_ecpH Hgp)).\n- move=> HhE HrgE HkE Eh.\n  pose a u x := cface u (icpU gc x).\n  have EaF: a =2 comp a face by move=> u x; exact: cface1.\n  pose k' u := if pick (a u) is Some x then h' x else k (ecpH g).\n  have Hk'F: invariant face k' =1 ecpU gc.\n    by move=> u; apply/eqP; rewrite /k' (eq_pick (EaF u)).\n  have Ek': forall x, k' (icpU _ x) = h' x.\n    move=> x; rewrite /k' -/gc.\n    case: pickP => [y Hy|Hx].\n      by rewrite /a cface_icpU Sface in Hy; apply: (fconnect_invariant Hh'F).\n    case/idP: (Hx x); exact: connect0.\n  have Ek'X: k' (ecpU gc) = k (ecpH g).\n    by rewrite /k'; case: pickP => // y; rewrite /a cface_ecpU.\n  rewrite (head_proper_cpring Hgp) head_cpring /= in Eh.\n  have Ek'eX: h (face (edge g)) = k' (edge (ecpU gc)).\n    have <-: h' (node gc) = k' (edge (ecpU gc)).\n      by rewrite -(eqcP (Hk'F _)) -Ek'.\n    move: HrgN HrgE; rewrite (head_proper_cpring Hgp) /=.\n    move/andP=> [_ H]; move/and3P=> [_ _ H']; move: H H'.\n    move: {-2}(g : g) (drop 2 (cpring g)) Eh.\n    elim: (mr) => [|b m Hrec] x [|y p] //= Eh.\n    case/andP; move/eqP=> Dy; rewrite -(finv_eq_monic (Enode g) x) {}Dy.\n    case: b Eh => [|] /= Eh Hp; last by case: Eh.\n    by case/andP; move/eqcP=> <-; rewrite -(eqcP (HhF (edge y))); eauto.\n  exists k'; first split=> //.\n    have Hk'EX: invariant edge k' (ecpU gc) = false.\n      rewrite /invariant Ek'X -Ek'eX.\n      have <-: (k (edge (ecpH g)) = h (face (edge g))).\n        rewrite (eqcP (HhF (edge g))); symmetry; apply: (fconnect_invariant HkF).\n        by apply: connect1; apply/eqP; rewrite /= Enode (negbE Hgp) set11.\n      apply: (etrans (HkE _)).\n      move: (uniq_ctrenum Hcp'); rewrite /cpmap -/cpmap -/g cpring_ecpH //.\n      rewrite !cat_adds -2!cat1s 2!insertE_cat !uniq_cat.\n      case/and5P=> [_ _ _ Ug _]; rewrite has_sym in Ug.\n      move: {Ug}(hasPn Ug _ (setU11 _ _)); rewrite !mem_insertE // => Ug.\n      apply/hasP => [] [v Hv Huv]; case/hasP: Ug; exists v; last done.\n      move: Hv; rewrite !mem_cat.\n      case/orP=> Hv; apply/orP; last by right; apply: (mem_sieve Hv).\n      by left; apply: (@mem_sieve _ mr).\n    move=> [||x] //; first by rewrite /invariant eqd_sym.\n    rewrite -[Icp x]/(icpU gc x) /invariant -icpU_edge !Ek'; exact: Hh'E.\n  rewrite cpring_ecpU cpring_ecpH // maps_sieve !maps_adds -!maps_comp.\n  rewrite (@eq_maps _ _ (comp k' (icpU gc)) _ Ek') head_cpring maps_adds Eh Ek'X.\n  rewrite maps_sieve; congr Adds.\n  rewrite (fconnect_invariant HkF (cface_node_ecpH Hgp)) -/(h (node g)).\n  apply: (etrans (esym Ek'eX)); transitivity (h g); apply: eqP.\n    rewrite (eqcP (HhF _)); apply: (etrans (HhE _)).\n    rewrite head_proper_cpring //; do 2 apply: setU1r; exact: setU11.\n  rewrite -{1}[g : g]Enode (eqcP (HhF _)); apply: (etrans (HhE _)).\n  rewrite head_cpring; exact: setU11.\n- move=> HhE HrgE HkE Eh.\n  pose a u x := cface u (icpY gc x).\n  have EaF: a =2 comp a face by move=> u x; exact: cface1.\n  pose k' u := if pick (a u) is Some x then h' x else k (ecpH g).\n  have Hk'F: invariant face k' =1 ecpY gc.\n    by move=> u; apply/eqP; rewrite /k' (eq_pick (EaF u)).\n  have Ek': forall x, k' (icpY _ x) = h' x.\n    move=> x; rewrite /k' -/gc; case: pickP => [y Hy|Hx].\n      by rewrite /a cface_icpY Sface in Hy; apply: (fconnect_invariant Hh'F).\n    case/idP: (Hx x); exact: connect0.\n  have Ek'X: k' (ecpY gc) = k (ecpH g).\n    by rewrite /k'; case: pickP => // y; rewrite /a cface_ecpY.\n  rewrite (head_proper_cpring Hgp) head_cpring /= in Eh; move: Eh => [EhnX Eh].\n  have Ehng: h (node g) = h g.\n    symmetry; rewrite -{1}[g : g]Enode (eqcP (HhF _)); apply: eqP.\n    apply: (etrans (HhE _)); rewrite head_cpring; exact: setU11.\n  have Ek'nX: k' (node (ecpY _)) = k (node (ecpH _)).\n    rewrite (fconnect_invariant Hk'F (cface_node_ecpY _)) Ek' EhnX -Ehng.\n    by rewrite (fconnect_invariant HkF (cface_node_ecpH Hgp)).\n  have Eh'X: h' gc = h (face (edge g)).\n    rewrite head_proper_cpring //= in Eh; move: HrgN HrgE {HhE HkE}.\n    rewrite head_proper_cpring //=.\n    case/andP=> [_ H]; case/andP=> [_ H']; move: H H'.\n    elim: (mr) {-2}(g : g) (drop 2 (cpring g)) Eh => [|b m Hrec] x [|y p] //= Eh.\n    case/andP; move/eqP=> Dy Hp; rewrite -(finv_eq_monic (Enode g) x) {}Dy.\n    case: b Eh => [|] /= Eh; last by case: Eh.\n    by case/andP; move/eqcP=> <-; rewrite -(eqcP (HhF _)); eauto.\n  exists k'; first split=> //.\n    have Hk'EX: forall u, cface u (ecpY _) -> invariant edge k' u = false.\n      move=> u HuX; rewrite /invariant (fconnect_invariant Hk'F HuX) Ek'X.\n      have HeuX: adj (ecpY _) (edge u) by rewrite -(adjF HuX) adjE.\n      rewrite (adj_ecpY Hgcp) /fband in HeuX; case/hasP: HeuX {HuX} => v.\n      case/mapsP=> [y Hy <-] {v} H; rewrite {u H}(fconnect_invariant Hk'F H) Ek'.\n      move: HkE (uniq_ctrenum Hcp') {x Hx}.\n      rewrite /cpmap -/cpmap -/g cpring_ecpH // => HkE.\n      rewrite -!cat1s -!catA catA insertE_cat uniq_cat has_sym.\n      case/and3P=> [_ Ug _].\n      rewrite mem_seq2 in Hy; case/orP: Hy; move/eqP=> <- {y}.\n        rewrite EhnX -Ehng /h -(fconnect_invariant HkF (cface_node_ecpH Hgp)).\n        rewrite eqd_sym -{1}[ecpH g : ecpH g]Enode (eqcP (HkF _)).\n        apply: (etrans (HkE _)); rewrite mem_insertE // has_cat !has_sieve_adds.\n        rewrite !andFb !orFb -has_cat; apply/hasP => [] [u Hu HuX].\n        move: (hasPn Ug _ (setU11 _ _)); rewrite mem_insertE //; case/hasP.\n        exists u; last done; rewrite mem_cat; apply/orP.\n        by rewrite mem_cat in Hu; case/orP: Hu => Hu; move: (mem_sieve Hu); auto.\n      rewrite Eh'X; have <-: k (edge (ecpH g)) = h (face (edge g)).\n        rewrite (eqcP (HhF _)); symmetry; apply: (fconnect_invariant HkF).\n        by apply: connect1; apply/eqP; rewrite /= Enode (negbE Hgp) /= set11.\n      apply: (etrans (HkE _)); rewrite mem_insertE // has_cat !has_sieve_adds.\n      rewrite !andFb !orFb -has_cat; apply/hasP => [[u Hu HuX]].\n      move: (hasPn Ug _ (setU1r _ (setU1r _ (setU11 _ _)))).\n      rewrite mem_insertE //; case/hasP.\n      exists u; last done; rewrite mem_cat; apply/orP.\n      by rewrite mem_cat in Hu; case/orP: Hu => Hu; move: (mem_sieve Hu); auto.\n    move=> u; case: (@fband_icpY _ gc u) => [[x Hx]|Hu].\n      case: (@fband_icpY _ gc (edge u)) => [[y Hy]|Heu].\n        rewrite /invariant (fconnect_invariant Hk'F Hx).\n        rewrite (fconnect_invariant Hk'F Hy) !Ek'.\n        have Hxy: adj x y.\n          by rewrite -(adj_icpY gc); apply/adjP; exists u; rewrite // Sface.\n        case/adjP: Hxy => [z Hxz Hzy]; rewrite (fconnect_invariant Hh'F Hxz).\n        rewrite -(fconnect_invariant Hh'F Hzy); exact: Hh'E.\n      have Deeu: edge (edge u) = u.\n        by move: Heu {Hx}; rewrite cface_ecpY; case: u => [||[||z]].\n      by rewrite /invariant eqd_sym -{1}Deeu; apply: Hk'EX; rewrite Sface.\n    by apply: Hk'EX; rewrite Sface.\n  rewrite /cpmap -/cpmap cpring_ecpY cpring_ecpH // !maps_sieve !maps_adds.\n  rewrite Ek'nX Ek'X -!maps_comp (@eq_maps _ _ (comp k' (icpY gc)) _ Ek') Eh.\n  by rewrite maps_sieve.\n- move=> HhE HrgE HkE Eh.\n  pose a u x := cface u (icpY gc x).\n  have EaF: a =2 comp a face by move=> u x; exact: cface1.\n  pose k' u := if pick (a u) is Some x then h' x else k (ecpH g).\n  have Hk'F: invariant face k' =1 ecpY gc.\n    by move=> u; apply/eqP; rewrite /k' (eq_pick (EaF u)).\n  have Ek': forall x, k' (icpY gc x) = h' x.\n    move=> x; rewrite /k' -/gc; case: pickP => [y Hy|Hx].\n      by rewrite /a cface_icpY Sface in Hy; apply: (fconnect_invariant Hh'F).\n    by case/idP: (Hx x); exact: connect0.\n  have Ek'X: k' (ecpY gc) = k (ecpH g).\n    by rewrite /k'; case: pickP => // y; rewrite /a cface_ecpY.\n  rewrite (head_proper_cpring Hgp) head_cpring /= in Eh; move: Eh => [EhnX Eh].\n  have Ehfeg: h (face (edge g)) = h g.\n    rewrite (eqcP (HhF _)); apply: eqP.\n    by apply: (etrans (HhE _)); rewrite head_proper_cpring //; apply: setU11.\n  have Ek'nX: k' (node (ecpY gc)) = k (node (ecpH g)).\n    rewrite (fconnect_invariant Hk'F (cface_node_ecpY _)) Ek' EhnX.\n    by rewrite (fconnect_invariant HkF (cface_node_ecpH Hgp)).\n  have Eh'X: h' gc = h (face (edge g)).\n    rewrite head_proper_cpring //= in Eh; move: HrgN HrgE {HhE HkE}.\n    rewrite head_proper_cpring //=.\n    case/andP=> [_ H]; case/andP=> [_ H']; move: H H'.\n    elim: (mr) {-2}(g : g) (drop 2 (cpring g)) Eh => [|b m Hrec] x [|y p] //= Eh.\n    case/andP; move/eqP=> Dy Hp; rewrite -(finv_eq_monic (Enode g) x) {}Dy.\n    case: b Eh => [|] /= Eh; last by case: Eh.\n    by case/andP; move/eqcP=> <-; rewrite -(eqcP (HhF _)); eauto.\n  exists k'; first split=> //.\n    have Hk'EX: forall u, cface u (ecpY gc) -> invariant edge k' u = false.\n      move=> u HuX; rewrite /invariant (fconnect_invariant Hk'F HuX) Ek'X.\n      have HeuX: adj (ecpY gc) (edge u) by rewrite -(adjF HuX) adjE.\n      rewrite (adj_ecpY Hgcp) /fband in HeuX; case/hasP: HeuX {HuX} => v.\n      case/mapsP=> [y Hy <-] {v} H; rewrite {u H}(fconnect_invariant Hk'F H) Ek'.\n      move: HkE (uniq_ctrenum Hcp') {x Hx}.\n      rewrite /cpmap -/cpmap -/g cpring_ecpH // => HkE.\n      rewrite -!cat1s -!catA catA insertE_cat uniq_cat has_sym.\n      case/and3P=> [_ Ug _].\n      rewrite mem_seq2 in Hy; case/orP: Hy; move/eqP=> <- {y}.\n        rewrite EhnX /h -(fconnect_invariant HkF (cface_node_ecpH Hgp)).\n        rewrite eqd_sym -{1}[ecpH g : ecpH g]Enode (eqcP (HkF _)).\n        apply: (etrans (HkE _)); rewrite mem_insertE // has_cat !has_sieve_adds.\n        rewrite !andFb !orFb -has_cat; apply/hasP => [] [u Hu HuX].\n        move: (hasPn Ug _ (setU11 _ _)); rewrite mem_insertE //; case/hasP.\n        exists u; last done; rewrite mem_cat; apply/orP.\n        by rewrite mem_cat in Hu; case/orP: Hu => Hu; move: (mem_sieve Hu); auto.\n      rewrite Eh'X; have <-: k (edge (ecpH g)) = h (face (edge g)).\n        rewrite (eqcP (HhF _)); symmetry; apply: (fconnect_invariant HkF).\n        by apply: connect1; apply/eqP; rewrite /= Enode (negbE Hgp) /= set11.\n      apply: (etrans (HkE _)); rewrite mem_insertE // has_cat !has_sieve_adds.\n      rewrite !andFb !orFb -has_cat; apply/hasP => [[u Hu HuX]].\n      move: (hasPn Ug _ (setU1r _ (setU1r _ (setU11 _ _)))).\n      rewrite mem_insertE //.\n      case/hasP; exists u; last done; rewrite mem_cat; apply/orP.\n      by rewrite mem_cat in Hu; case/orP: Hu => Hu; move: (mem_sieve Hu); auto.\n    move=> u; case: (@fband_icpY _ gc u) => [[x Hx]|Hu].\n      case: (@fband_icpY _ gc (edge u)) => [[y Hy]|Heu].\n        rewrite /invariant (fconnect_invariant Hk'F Hx).\n        rewrite (fconnect_invariant Hk'F Hy) !Ek'.\n        have Hxy: adj x y.\n          by rewrite -(adj_icpY gc); apply/adjP; exists u; rewrite // Sface.\n        case/adjP: Hxy => [z Hxz Hzy]; rewrite (fconnect_invariant Hh'F Hxz).\n        by rewrite -(fconnect_invariant Hh'F Hzy); apply: Hh'E.\n      have Deeu: edge (edge u) = u.\n        by move: Heu {Hx}; rewrite cface_ecpY; case: u => [||[||z]].\n      by rewrite /invariant eqd_sym -{1}Deeu; apply: Hk'EX; rewrite Sface.\n    by apply: Hk'EX; rewrite Sface.\n  rewrite /cpmap -/cpmap cpring_ecpY cpring_ecpH // !maps_sieve !maps_adds Ek'nX.\n  by rewrite Ek'X -!maps_comp (@eq_maps _ _ (comp k' _) _ Ek') Eh maps_sieve.\nmove=> HhE HrgE HkE Eh.\npose a u x := cface u (icpH gc x).\nhave EaF: a =2 comp a face by move=> u x; exact: cface1.\npose k' u := if pick (a u) is Some x then h' x else k (ecpH g).\nhave Hk'F: invariant face k' =1 ecpH gc.\n  by move=> u; apply/eqP; rewrite /k' (eq_pick (EaF u)).\nhave Ek': forall x, k' (icpH _ x) = h' x.\n  move=> x; rewrite /k' -/gc; case: pickP => [y Hy|Hx].\n    by rewrite /a cface_icpH Sface in Hy; apply: (fconnect_invariant Hh'F).\n  by case/idP: (Hx x); exact: connect0.\nhave Ek'X: k' (ecpH gc) = k (ecpH g).\n  by rewrite /k'; case: pickP => // y; rewrite /a cface_ecpH.\nrewrite (head_proper_cpring Hgp) head_proper_cpring //= in Eh.\nmove: Eh => [EhnX EhX Eh].\nhave Ek'nX: k' (node (ecpH gc)) = k (node (ecpH g)).\n  rewrite (fconnect_invariant Hk'F (cface_node_ecpH Hgcp)) Ek' EhnX.\n  by rewrite (fconnect_invariant HkF (cface_node_ecpH Hgp)).\nhave Eh'feX: h' (face (edge gc)) = h (face (edge g)).\nmove: HrgN HrgE (introT eqP Emr) {HhE HkE}; rewrite -size_ring_cpmap -/g.\n  rewrite head_proper_cpring //= !eqdSS; case/andP=> _.\n  elim: (mr) {-2}(g : g) (drop 2 (cpring g)) Eh => [|b m Hrec] x [|y p] //= Eh;\n    case/andP; move/eqP=> Dy Hp; rewrite -(finv_eq_monic (Enode g) x) {}Dy.\n    have Hgcl: long_cpring gc = false.\n      by rewrite size_long_cpring -(size_maps h') head_proper_cpring //= Eh.\n    by rewrite -EhnX; move/eqP: Hgcl => <-.\n  case: b Eh => [|] /= Eh.\n    by case/andP; move/eqcP=> <-; rewrite -(eqcP (HhF _)); eauto.\n  have Hgcl: long_cpring gc.\n    by rewrite size_long_cpring -(size_maps h') head_proper_cpring //= Eh.\n  by rewrite (head_long_cpring Hgcl) in Eh; case: Eh.\nexists k'; first split=> //.\n  have Hk'EX: forall u, cface u (ecpH gc) -> invariant edge k' u = false .\n    move=> u HuX; rewrite /invariant (fconnect_invariant Hk'F HuX) Ek'X.\n    have HeuX: (adj (ecpH _) (edge u)) by rewrite -(adjF HuX) adjE.\n    rewrite (adj_ecpH Hgcp) /fband in HeuX; case/hasP: HeuX {HuX} => v.\n    case/mapsP=> [y Hy <-] {v} H; rewrite {u H}(fconnect_invariant Hk'F H) Ek'.\n    move: HkE (uniq_ctrenum Hcp') {x Hx}.\n    rewrite /cpmap -/cpmap -/g cpring_ecpH //; move=> HkE.\n    rewrite -!cat1s -!catA catA insertE_cat uniq_cat has_sym.\n    case/and3P=> [_ Ug Ug']; rewrite insertE_cat uniq_catC -insertE_cat in Ug'.\n    simpl in Ug'; case/andP: Ug' => [Ug' _]; rewrite /= /setU1 in Ug'.\n    move: Ug'; repeat case/norP => _; move=> Ug'.\n    rewrite mem_seq3 in Hy; case/or3P: Hy; move/eqP=> <-{y}.\n    - rewrite EhnX /h -(fconnect_invariant HkF (cface_node_ecpH Hgp)).\n      rewrite eqd_sym -{1}[ecpH g : ecpH g]Enode (eqcP (HkF _)).\n      apply: (etrans (HkE _)); rewrite mem_insertE // has_cat !has_sieve_adds.\n      rewrite !andFb !orFb -has_cat; apply/hasP => [] [u Hu HuX].\n      move: (hasPn Ug _ (setU11 _ _)); rewrite mem_insertE //; case/hasP.\n      exists u; last done; rewrite mem_cat; apply/orP.\n      by rewrite mem_cat in Hu; case/orP: Hu => Hu; move: (mem_sieve Hu); auto.\n    - rewrite EhX -(eqcP (HkF _)).\n      have <-: k (edge (face (ecpH g))) = h g.\n        apply: (fconnect_invariant HkF); apply: connect1; apply/eqP.\n        by rewrite /= Enode (negbE Hgp).\n      apply: (etrans (HkE _)); rewrite mem_insertE //=.\n      apply/hasP => [[u Hu HuX]]; move: Ug'; rewrite (mem_insertE Hg'E).\n      case/hasP; exists u; last done; rewrite mem_cat; apply/orP.\n      by rewrite mem_cat in Hu; case/orP: Hu; move/mem_sieve; auto.\n    rewrite Eh'feX; have <-: k (edge (ecpH g)) = h (face (edge g)).\n      rewrite (eqcP (HhF _)); symmetry; apply: (fconnect_invariant HkF).\n      by apply: connect1; apply/eqP; rewrite /= Enode (negbE Hgp) /= set11.\n    apply: (etrans (HkE _)); rewrite mem_insertE // has_cat !has_sieve_adds.\n    rewrite !andFb !orFb -has_cat; apply/hasP => [] [u Hu HuX].\n    move: (hasPn Ug _ (setU1r _ (setU1r _ (setU11 _ _)))).\n    rewrite mem_insertE //.\n    case/hasP; exists u; last done; rewrite mem_cat; apply/orP.\n    by rewrite mem_cat in Hu; case/orP: Hu; move/mem_sieve; auto.\n  move=> u; case: (@fband_icpH _ gc u) => [[x Hx]|Hu].\n    case: (@fband_icpH _ gc (edge u)) => [[y Hy]|Heu].\n      rewrite /invariant (fconnect_invariant Hk'F Hx).\n      rewrite (fconnect_invariant Hk'F Hy) !Ek'.\n      have Hxy: adj x y.\n        by rewrite -(adj_icpH gc); apply/adjP; exists u; rewrite // Sface.\n      case/adjP: Hxy => [z Hxz Hzy]; rewrite (fconnect_invariant Hh'F Hxz).\n      by rewrite -(fconnect_invariant Hh'F Hzy); apply: Hh'E.\n    have Deeu: edge (edge u) = u.\n      by move: Heu {Hx}; rewrite cface_ecpH; case: u => [||[||[||z]]].\n    by rewrite /invariant eqd_sym -{1}Deeu; apply: Hk'EX; rewrite Sface.\n  by apply: Hk'EX; rewrite Sface.\nrewrite /cpmap -/cpmap !cpring_ecpH // !maps_sieve !maps_adds.\nby rewrite Ek'nX Ek'X -!maps_comp (@eq_maps _ _ (comp k' _) _ Ek') Eh maps_sieve.\nQed.\n\nLemma sparse_cfctr : forall mr mc cp,\n  size mr = cprsize cp -> size mc = ctrmsize cp ->\n  let g := cpmap cp in let r := cpring g in\n  let cc := cat (maps edge (sieve mr r)) (insertE (sieve mc (ctrenum cp))) in\n  if cfctr mr mc cp is Some _ then sparse (Adds g cc) else true.\nProof.\nmove=> /= mr mc cp; elim: cp mr mc => [|s cp Hrec] mr mc //.\nmove: (cfctr_config_prog mr mc (Adds s cp)).\ncase Dcpc: (cfctr mr mc (Adds s cp)) => // [cpc].\ncase: s Dcpc => // [n||] Dcpc Hcp' Emr Emc;\n  have Hcp := config_prog_cubic Hcp'; rewrite /= in Dcpc Hcp Emr Emc;\n  move: Hrec (cpmap_plain Hcp) (cpmap_cubic Hcp) (cpmap_proper Hcp);\n  rewrite /cpmap -/cpmap; set g := cpmap cp => Hrec HgE HgN Hgp.\n- rewrite cpring_ecpR /= -(rot_rotr n mr).\n  rewrite -(size_rotr n mr) in Emr; move: Dcpc (Hrec _ _ Emr Emc).\n  case: (cfctr (rotr n mr) mc cp) => //= _ _ {cpc}; apply: etrans.\n  apply: simple_perm.\n    move=> y; congr orb.\n      rewrite !(Sface (permF g) y); symmetry; apply: (@same_cnode g).\n      exact: fconnect_iter.\n    apply: eq_has_r => x {y}; rewrite !mem_cat; congr orb.\n    rewrite -(Eface g x) !(mem_maps (Iedge g)).\n    by apply: mem_sieve_rot; rewrite /g size_ring_cpmap.\n  rewrite /= !size_cat !size_maps; congr S; congr addn; rewrite /rot sieve_cat.\n    rewrite -rot_size_cat size_rot -sieve_cat ?cat_take_drop //.\n    by rewrite !size_take Emr -size_ring_cpmap.\n  by rewrite !size_drop Emr -size_ring_cpmap.\n- rewrite /g.\n  case Dcp: cp mc mr Emc Emr Dcpc => [|s cp'] [|b3 mc] // [|b1 [|b2 mr]] //.\n    case: mr {cp Dcp g Hrec Hcp Hcp' HgE HgN Hgp} => [|b3 [|b4 mr]] //.\n    by case: b1 b2 b3 => [|] [|] [|].\n  rewrite -Dcp -/g; have Hg'E: plain (ecpY g) by apply: plain_ecpY.\n  case Hb123: (nsp b1 b2 b3) => //.\n  rewrite [size _]/= [size _ = _]/= => [] [Emc] [Emr].\n  move: {Hrec}(Hrec (Adds b3 mr) mc Emr Emc).\n  case: (cfctr (Adds b3 mr) mc cp) => // _ Hrec _ {cpc}.\n  have <-: (maps (icpY g) (Adds (node g) (ctrenum cp)) = ctrenum (Adds CpY cp)).\n    by rewrite /= /g Dcp.\n  pose p := cat (maps edge (sieve (Adds b3 mr) (cpring (cpmap cp))))\n                (insertE (sieve mc (ctrenum cp))).\n  move: Hrec; rewrite /g -/p; rewrite -/g in p |- *.\n  rewrite sparse_adds -(eq_has (mem_cpring g)); move/andP=> [Up Hp].\n  have HpY: sparse (Adds (ecpY g) (maps (icpY g) (Adds (node g) p))).\n    rewrite maps_adds !sparse_adds; apply/and3P; split.\n    - rewrite -(eq_has (mem_cpring (ecpY g))) cpring_ecpY -maps_adds.\n      apply/hasP => [] [u]; case/mapsP=> /= [y Hy <-] {u} Hry.\n      rewrite /setU1 /= (mem_maps (@icpY_inj _ g)) in Hry.\n        case/setU1P: Hy => [Dy|Hy].\n          by move: (uniq_cpring g); rewrite head_cpring Dy /= Hry.\n        by case/hasP: Up; exists y; last exact: mem_behead.\n      apply/hasP => [] [u]; case/mapsP=> [y Hy <-] {u} Hry; rewrite Snode in Hry.\n      have Hy' := hasPn Up y Hy; case/idP: (Hy').\n      by rewrite mem_cpring cnode1 Snode -(@cnode_injcp (seq1 CpY) _ y).\n    elim: p Up Hp => [|x p Hrec] //=; move/norP=> [Hx Up].\n    rewrite sparse_adds (@sparse_adds (ecpY g)).\n    move/andP=> [Hpx Hp]; apply/andP; split; last exact: Hrec.\n    apply/hasP => [] [u]; case/mapsP=> [y Hy <- {u}] Hxy.\n    case/hasP: Hpx; exists y; first done.\n    by rewrite -(@cnode_injcp (seq1 CpY) _ x).\n  move: HpY; rewrite -maps_sieve /p head_cpring cpring_ecpY -!cat1s !sieve_cat //.\n  rewrite !maps_cat !insertE_cat -maps_sieve -!maps_comp -!catA.\n  rewrite -rot_size_cat sparse_rot -!catA -/g => HpY.\n  rewrite -rot_size_cat sparse_rot -!catA 2!catA sparse_catCA -!catA.\n  move: (sieve mr (behead (cpring g))) (@sieve g mc (ctrenum cp)) HpY => r1 r2.\n  set r1' := maps _ r1; set r2' := insertE (maps _ r2).\n  have <-: r1' = maps (comp edge (icpY g)) r1 by done.\n  have <-: r2' = maps (icpY g) (insertE r2).\n    by rewrite {}/r2'; elim: r2 => // *; repeat congr Adds.\n  move: {r1 r2 r1' r2'}(cat r1' (cat r2' (seq1 (ecpY g)))) => r Hrec.\n  rewrite {1}[cat]lock catA -lock sparse_catCA -!catA {p Up Hp Emc Emr}.\n(* Staging the identities avoids spurrious dependent type expansion *)\n  move: r Hrec; set h := icpY g; set g' := ecpY g in h |- *.\n  have: forall x, h (edge x) = edge (h x) by done.\n  have: node (h (node g)) = edge (node g') by rewrite /= set11.\n  have: node (edge (node g')) = edge g' by done.\n  case: b1 b2 b3 Hb123 g' h => [|] [|] [|] //= _ g' h EhN2 EhN1 EhE r;\n    rewrite !sparse_adds /comp ?EhE -?EhN2 -?EhN1 -?(eq_has (cnode1 _)) //.\n  by case/andP.\ncase: mc mr Emc Emr Dcpc => [|b3 [|b4 [|b5 mc]]] [|b1 [|b2 mr]] //.\nrewrite [size _]/= [size _ = _]/= => [] [Emc] [Emr].\ncase Hb: (nsp b3 b1 b4 || nsp b3 b2 b5); first done.\ncase: (and3b _ _ _); first done.\nmove: {Hrec}(Hrec (Seq b4 b5 & mr) mc Emr Emc).\ncase: (cfctr _ _ _) => // [_] Hrec _ {cpc}.\nhave Hg'E := plain_ecpH g HgE.\nhave <-: Adds (face (ecpH g)) (maps (icpH g) (Seq (node g) g & (ctrenum cp))) =\n          ctrenum (Adds CpH cp) by done.\npose p := cat (maps edge (sieve (Seq b4 b5 & mr) (cpring (cpmap cp))))\n              (insertE (sieve mc (ctrenum cp))).\nmove: Hrec; rewrite /g -/p; rewrite -/g in p |- *.\nrewrite sparse_adds -(eq_has (mem_cpring g)); move/andP=> [Up Hp].\nhave Dng': node (ecpH g) = icpN _ (icpN _ (edge (ecpU g))).\n  by rewrite /= /long_cpring /= Enode (negbE Hgp).\nhave Dn'g: node (icpH g g) = icpN _ (ecpY g).\n  by rewrite /= (negbE Hgp) /eqd /= set11.\nhave Erg': forall x, cpring (ecpH g) (icpH g x) = drop 2 (cpring g) x.\n  move=> x; rewrite cpring_ecpH // mem_adds /setU1 Dng'.\n  by rewrite -(mem_maps (@icpH_inj _ g)).\nhave HpH: sparse (Adds (ecpH g) (maps (icpH g) (Seq (node g) g & p))).\n  rewrite !maps_adds !sparse_adds; apply/and4P; split.\n  - rewrite -(eq_has (mem_cpring (ecpH g))) -!maps_adds.\n    apply/hasP; case=> u; case/mapsP=> y Hy <- {u}; rewrite Erg' => Hry.\n    move: (uniq_cpring g); rewrite head_proper_cpring //=.\n    case/setU1P: Hy => [Dy|Hy]; first by rewrite Dy /setU1 Hry orbT.\n    case/setU1P: Hy => [Dy|Hy]; first by rewrite {5}Dy Hry /= andbF.\n    by case/hasP: Up; exists y; last exact: (mem_drop Hry).\n  - rewrite -maps_adds.\n    apply/hasP; case=> u; case/mapsP=> y Hy <- {u} Hry; rewrite Snode in Hry.\n    simpl in Hy; case/setU1P: Hy => [Dy|Hy].\n      move: Hry; rewrite fconnect_orbit /orbit.\n      have HyN: setC (rev (cpring (ecpH g))) (icpH g y).\n        rewrite /setC mem_rev Erg' -Dy.\n        move: (uniq_cpring g); rewrite head_proper_cpring //= drop0.\n        by case/andP=> _; case/andP.\n      (* staging computation prevents divergence on Qed. *)\n      have ->: order node (icpH g y) = 3.\n        apply: eqP; move: (ecpH g) (cubic_ecpH HgN) (icpH g y) HyN => g'.\n        exact: subsetP.\n      rewrite -Dy /traject /mem /setU1 Dn'g orbF; exact: negP.\n    have Hy' := hasPn Up y Hy; case/idP: (Hy').\n      by rewrite mem_cpring cnode1 Snode -(@cnode_injcp (seq1 CpH) _ y).\n    apply/hasP => [] [u]; case/mapsP=> [y Hy <- {u}] Hry; rewrite Snode in Hry.\n    have Hy' := hasPn Up y Hy; case/idP: (Hy').\n    by rewrite mem_cpring Snode -(@cnode_injcp (seq1 CpH) _ y).\n  elim: p Up Hp => [|x p Hrec] //=; move/norP=> [Hx Up].\n  rewrite (@sparse_adds g) (@sparse_adds (ecpH g)).\n  move/andP=> [Hpx Hp]; apply/andP; split; last exact: Hrec.\n  apply/hasP => [] [u]; case/mapsP=> [y Hy <- {u}] Hxy.\n  by case/hasP: Hpx; exists y; last by rewrite -(@cnode_injcp (seq1 CpH) _ x).\nmove: HpH {Up Hp}; rewrite {}/p head_proper_cpring // cpring_ecpH // -!cat1s.\nrewrite !maps_cat !sieve_cat // -!maps_sieve -/g !sieve1 !maps_cat !maps_seqn.\nmove: (sieve mr (drop 2 (cpring g))) (@sieve g mc (ctrenum cp)) => r1 r2.\nrewrite !insertE_cat !insertE_seqb -!maps_comp -!catA !icpH_edge.\nset r1' := maps _ r1; set r2' := insertE (maps _ r2).\nset r0 := seq1 (ecpH g); set x1 := icpH g (node g); set x2 := icpH g g.\nset x5 := icpH g (edge g); set x4 := icpH g (edge (node g)).\nhave <-: r1' = maps (comp edge (icpH g)) r1 by done.\nhave <-: r2' = maps (icpH g) (insertE r2).\n  by rewrite {}/r2'; elim: r2 => // *; repeat congr Adds.\nrewrite /seq1 /maps !seq1I -/x1 -/x2; simpl in b1, b2, b3, b4, b5.\nrewrite {1}[cat]lock catA -lock sparse_catCA -!catA; set r := cat r0 _ => HpH.\nhave Hrec: (sparse (cat (seqn b1 x1) (cat (seqn b3 x1) (cat (seqn b4 x1)\n                   (cat (seqn b2 x2) (cat (seqn b3 x2) (cat (seqn b5 x2) r))))))).\n  move: HpH; rewrite [sparse]lock; clearbody r.\n  case: b3 b1 b2 b4 b5 Hb => [|] [|] [|] [|] [|] // _ /=.\n  - rewrite -lock -!cat1s (@sparse_catCA (ecpH g)) /seq1 /cat.\n    by rewrite (@sparse_adds (ecpH g)); case/andP.\n  - by rewrite -lock (@sparse_adds (ecpH g)); case/andP.\n  - rewrite -lock -!cat1s (@sparse_catCA (ecpH g)) /seq1 /cat.\n    by rewrite (@sparse_adds (ecpH g)); case/andP.\n  - by rewrite -lock (@sparse_adds (ecpH g)); case/andP.\n  by rewrite -lock 2!(@sparse_adds (ecpH g)); case/and3P.\napply: etrans Hrec {HpH}; apply: simple_perm.\n  move=> u; rewrite /r !(@fband_cat (permF (ecpH g))).\n  set fb := @fband (permF (ecpH g)); case (fb r2' u); first by rewrite !orbT.\n  case (fb r1' u); first by rewrite !orbT.\n  case (fb r0 u); first by rewrite !orbT.\n  case (fb (seqn b5 x5) u); first by rewrite !orbT.\n  case (fb (seqn b4 x4) u); first by rewrite !orbT.\n  case (fb (seqn b4 x1) u); first by rewrite !orbT.\n  case (fb (seqn b5 x2) u); first by rewrite !orbT.\n  rewrite !orbF !orFb; congr orb.\n    case b1; rewrite // /nat_of_bool /seqn /addsn /iter /fb /fband /has.\n    by rewrite 2!cface1r Dng' /= set11.\n  rewrite orbA orbC; repeat congr orb.\n  - case b3;  rewrite // /nat_of_bool /seqn /addsn /iter /fb /fband /has.\n    by rewrite cface1r /= set11.\n  - case b2; rewrite // /nat_of_bool /seqn /addsn /iter /fb /fband /has.\n    by rewrite cface1r /= Enode (negbE Hgp) /=.\n  case b3;  rewrite // /nat_of_bool /seqn /addsn /iter /fb /fband /has.\n  by rewrite 2!cface1r /= Enode (negbE Hgp) /=.\nby rewrite /r !size_cat !size_seqn; repeat NatCongr.\nQed.\n\nFixpoint ctrband (cm : bitseq) (cp : cprog) {struct cp} : cpmask :=\n  match cp, cm with\n  | Adds (CpR n) cp', _ =>\n    let (mr, mk) := ctrband cm cp' in Cpmask (rot n mr) mk\n  | Adds CpY seq0, _ =>\n    Cpmask (seqn 3 false) seq0\n  | Adds CpY cp', (Seq b1 & cm') =>\n    if ctrband cm' cp' is Cpmask (Seq a0 a1 & mr) mk then\n      Cpmask (cat (seq3 (b1 || a0) false (b1 || a1)) mr) mk\n    else Cpmask seq0 seq0\n  | Adds CpH cp', (Seq b1 b0 b2 & cm') =>\n    if ctrband cm' cp' is Cpmask (Seq a0 a1 a2 & mr) mk then\n      Cpmask (cat (seq3 (b0 || a0) b1 (b2 || a2)) mr)\n             (Adds (b0 || (b1 || (b2 || a1))) mk)\n    else Cpmask seq0 seq0\n  | _, _ => Cpmask seq0 seq0\n  end.\n\n\nLemma ctrband_correct : forall cm cp, size cm = ctrmsize cp -> config_prog cp ->\n    proper_cpmask cp (ctrband cm cp)\n /\\ fband (insertE (sieve cm (ctrenum cp))) =1 fband (cpsieve (ctrband cm cp) cp).\nProof.\nmove=> cm cp Ecm Hcp; elim: cp Hcp cm Ecm => // [s cp Hrec] Hcp.\nmove: Hcp (config_prog_cubic Hcp) Hrec => /=.\ncase: s => // [n||] Hcp Hcpq; move: (cpmap_plain Hcpq) (cpmap_proper Hcpq);\n  rewrite /cpmap -/cpmap; set g := cpmap cp => HgE Hgp Hrec cm Ecm.\n- case: (ctrband cm cp) {Hrec Ecm Hcp}(Hrec Hcp _ Ecm) => [mr mk].\n  case; move/andP=> [Emr Emc] Erec.\n  split; first by rewrite /= size_rot Emr.\n  rewrite /cpsieve /cpmap -/cpmap -/g cpring_ecpR /=.\n  move=> x; rewrite Erec -/g /= !fband_cat /=; congr orb.\n  by rewrite sieve_rot ?fband_rot // (eqP Emr) -size_ring_cpmap.\n- rewrite /g; case Dcp: cp cm Hcp Ecm => [|s cp'] // [|b1 cm] //.\n  rewrite -Dcp -/g [size _]/= => Hcp [Ecm].\n  case: (ctrband cm cp) {Hrec}(Hrec Hcp _ Ecm) => [mr mk].\n  case; move/andP=> [Emr Emk].\n  have Hmr: 1 < size mr by rewrite (eqP Emr) -size_ring_cpmap -size_proper_cpring.\n  case: mr Hmr Emr => [|a0 [|a1 mr]] // _ Emr Erec.\n  split; first by rewrite /= -(eqP Emr) /= set11.\n  move=> u; rewrite -maps_adds /cpsieve /cpmap -/cpmap -/g.\n  rewrite cpring_ecpY /behead (head_proper_cpring Hgp).\n  rewrite /cpker -/cpker -!maps_sieve (insertE_icpY g) maps_adds.\n  rewrite !sieve_adds insertE_cat insertE_seqb -!catA !fband_cat orFb /fband.\n  rewrite !has_seqb -maps_sieve !has_maps -/g.\n  case: (fband_icpY u) => [[x Hx]|Hu].\n    have Eu: comp (cface u) (icpY g) =1 cface x.\n      by move=> y; rewrite /comp (same_cface Hx) cface_icpY.\n    rewrite !(eq_has Eu) !(same_cface Hx) cface_icpY !has_cat !has_seqb.\n    rewrite orbCA cface1r Enode; symmetry.\n    rewrite Sface (same_cface (cface_node_ecpY g)) cface_icpY Sface.\n    rewrite /fband in Erec; rewrite Erec /cpsieve -/g has_cat.\n    rewrite {2}(head_proper_cpring Hgp) !has_sieve_adds !orbA.\n    by do 2 congr orb; rewrite !demorgan2 -!orbA; repeat BoolCongr.\n  have Eu: comp (cface u) (icpY g) =1 set0.\n    by move=> y; rewrite /comp -(same_cface Hu) (@cface_ecpY _ g).\n  by rewrite !(eq_has Eu) !has_set0 -!(same_cface Hu) !(@cface_ecpY _ g) !andbF.\ncase: cm Ecm => [|b1 [|b0 [|b2 cm]]] //; rewrite [size _]/= => [] [Ecm].\ncase: (ctrband cm cp) {Hrec}(Hrec Hcp _ Ecm) => [mr mk].\ncase; move/andP=> [Emr Emk].\nhave Hgl: long_cpring g by apply: cfmap_long.\nhave Hmr: 2 < size mr by rewrite (eqP Emr) -size_ring_cpmap -size_long_cpring.\ncase: mr Hmr Emr => [|a0 [|a1 [|a2 mr]]] // _ Emr Erec; simpl in Emr.\nsplit; first by rewrite /= -(eqP Emr) /= set11.\nmove=> u; rewrite /cpsieve /cpmap -/cpmap -/g.\nrewrite cpring_ecpH // /drop /cpker -/cpker -/g (head_long_cpring Hgl).\nrewrite sieve_adds -!maps_adds -!maps_sieve (@insertE_cat (ecpH g)).\nrewrite (@insertE_seqb (ecpH g)) (insertE_icpH g).\nset fX := face (ecpH g); have EfX := erefl fX; rewrite {2}/fX /= in EfX.\nrewrite -EfX; have <-: face (icpH g (edge (node g))) = edge fX.\n  rewrite /= Enode (negbE Hgp) /=; rewrite /eqd /= set11 /eqd /=.\n  by rewrite (inj_eqd (Iedge g)) eqd_sym (negbE Hgp).\nrewrite !sieve_adds -!catA -maps_sieve -maps_cat /fband !has_cat !has_seqb.\nrewrite /fX -!cface1r !has_maps; symmetry; rewrite orbCA; congr orb.\nrewrite Sface (same_cface (cface_node_ecpH Hgp)) Sface.\ncase: (fband_icpH u) => [[x Hx]|Hu].\n  have Eu: comp (cface u) (icpH g) =1 cface x.\n    by move=> y; rewrite /comp (same_cface Hx) cface_icpH.\n  rewrite !(same_cface Hx) !cface_icpH !(eq_has Eu); rewrite /fband in Erec.\n  rewrite !insertE_cat !insertE_seqb !has_cat !has_seqb Erec.\n  rewrite /cpsieve -/g {2}(head_long_cpring Hgl) has_cat.\n  rewrite !has_sieve_adds -cface1r (cface1r (edge (node g))) Enode.\n  by rewrite !demorgan2 -!orbA; repeat BoolCongr.\nhave Eu: comp (cface u) (icpH g) =1 set0.\n  by move=> y; rewrite /comp -(same_cface Hu) cface_ecpH.\nby rewrite !(eq_has Eu) !has_set0; rewrite /comp in Eu; rewrite !Eu !andbF.\nQed.\n\nDefinition cfcontract_mask cf := ctrmask (cfprog cf) (cfcontract_ref cf).\n\nDefinition cfcontract cf := sieve (cfcontract_mask cf) (ctrenum (cfprog cf)).\n\nFixpoint cptriad (ccm : cpmask) (cp : cprog) (i : nat) {struct i} : bool :=\n  if i is S i' then\n    let (mrt, mkt) := cpadj (cpmask1 cp i') cp in\n    let (mrc, mkc) := ccm in\n    let mct := cat (sieve mrc mrt) (sieve mkc mkt) in\n    if has negb mct && (2 < count id mct) then true else cptriad ccm cp i'\n  else false.\n\nDefinition valid_ctrm (cm : bitseq) cp :=\n  let n := count id cm in\n  if n =d 4 then cptriad (ctrband cm cp) cp (cpksize cp) else set3 1 2 3 n.\n\nDefinition contract_ctree cf :=\n  let cp := cfprog cf in\n  let cm := cfcontract_mask cf in\n  if cfctr (seqn (cprsize cp) false) cm cp is Some cpc then\n    if valid_ctrm cm cp then Some (cpcolor cpc) else None\n  else None.\n\nLemma contract_ctreeP : forall cf,\n if contract_ctree cf is Some ct then\n   let r := cfring cf in let cc := cfcontract cf in\n      valid_contract r cc\n   /\\ (forall et, cc_ring_trace cc (rev r) et -> ctree_mem ct (etrace (behead et)))\n else True.\nProof.\nmove=> [sym ccr cp]; rewrite /contract_ctree /cfcontract /cfcontract_mask /=.\nrewrite /cfring rev_rev /cfmap {sym}/= -size_ring_cpmap.\nset g := cpmap cp; set r := cpring g.\nset cm := ctrmask cp ccr; set mr0 := seqn (size r) false.\nhave Emr0: size mr0 = cprsize cp by rewrite -size_ring_cpmap /mr0 size_seqn.\nhave Ecm: size cm = ctrmsize cp by apply: size_ctrmask.\nmove: (sparse_cfctr Emr0 Ecm) (cfctr_correct Emr0 Ecm).\ncase: (cfctr mr0 cm cp) (cfctr_config_prog mr0 cm cp) => //= [cpc] Hcp.\nhave HgE := cpmap_plain (config_prog_cubic Hcp).\nset cc := sieve cm (ctrenum cp); rewrite -/g -/r in cc |- * => UccN Hcc.\ncase Hcm: (valid_ctrm cm cp); last done.\nrewrite /mr0 sieve_false /= in UccN; split.\n  move: Hcm; rewrite /valid_ctrm eqd_sym.\n  have <-: size cc = count id cm.\n  apply: eqP; move: (introT eqP Ecm); rewrite -size_ctrenum /cc.\n  elim: (cm) (ctrenum cp) => [|[|] m Hrec] [|x p] //; apply: Hrec.\n  move=> Hcm; split; try by case/andP: UccN.\n  move: (uniq_ctrenum Hcp); rewrite -/g -/r insertE_cat uniq_cat disjoint_has.\n  - move/and3P=> [_ Ur _]; apply/hasP => [[x Hxc Hxr]]; case/hasP: Ur.\n    exists x; rewrite !mem_insertE // in Hxr |- *; apply/hasP.\n      by case/hasP: Hxr => [y Hy Hxy]; exists y; first exact (mem_sieve Hy).\n    by exists x; [ rewrite -mem_rev | exact: connect0 ].\n  - by rewrite -/cc /set4; case: (4 =d size cc) Hcm; rewrite ?orbT ?orbF.\n  rewrite -/cc; move=> Dcc; move: Hcm; rewrite Dcc /=.\n  move=> H; apply/set0P => [Hccr]; case/negPf: H; move: Hccr.\n  elim: {-2}(cpksize cp) (leqnn (cpksize cp)) => //= [i Hrec] Hi.\n  move: (cpsieve1 Hi Hcp) (proper_cpmask1 cp i).\n  set x := sub (cpmap cp) (cpker cp) i.\n  move: (cpmask1 cp i) => cmx Hx Hcmx.\n  case: (cpadj cmx cp) (cpadj_proper Hcmx) (cpsieve_adj Hcp Hcmx) => [mrt mkt].\n  case: {-4}(ctrband cm cp) (ctrband_correct Ecm Hcp) => [mrc mkc].\n  rewrite -/cc /= -/g -/r; case; move/andP=> [Emrc Emkc] Hmc.\n  move/andP=> [Emrt Emkt] Hmt Hccr.\n  apply: cases_of_if; last by clear; apply: Hrec => //; apply ltnW.\n  move/andP=> [Hmtc Hmtc']; rewrite -size_ring_cpmap -/g -/r in Emrc Emrt.\n  set mt := cat mrt mkt; set mc := cat mrc mkc; set q := cat r (cpker cp).\n  have Emtq: size mt =d size q.\n    by rewrite /mt /q !size_cat (eqP Emrt) (eqP Emkt) /g (size_cpker Hcp) set11.\n  have Emcq: size mc =d size q.\n    by rewrite /mc /q !size_cat (eqP Emrc) (eqP Emkc) /g (size_cpker Hcp) set11.\n  have Uq: simple q by apply: cpmap_simple.\n  rewrite -sieve_cat -/mt -/q ?(eqP Emrt) // {}Hx in Hmt.\n  rewrite -sieve_cat -/mc -/q ?(eqP Emrc) // in Hmc.\n  rewrite -sieve_cat -/mt -/mc ?(eqP Emrt) ?(eqP Emrc) // in Hmtc Hmtc'.\n  case/andP: {Hccr}(Hccr x) {Hrec}; split.\n    apply/hasP => [] [y Hy Hyx].\n    rewrite /q simple_cat in Uq; case/and3P: Uq; clear; case/hasP; exists x.\n      by apply: mem_sub; rewrite /g (size_cpker Hcp).\n    by apply/hasP; exists y; first by rewrite -mem_rev.\n  apply/andP; split.\n    apply: {Hmtc'}(leq_trans Hmtc').\n    apply: (@leq_trans (fcard face (setI (adj x) (fband (insertE cc))))).\n      rewrite leq_eqVlt; apply/orP; left; apply/eqP.\n      transitivity (fcard face (fband (filter (fband (sieve mt q)) (sieve mc q)))).\n        rewrite simple_fcard_fband.\n          move: (mc) (mt) Emcq Emtq Uq; rewrite simple_recI.\n          elim: (q) => [|y q' Hrec] [|b m] // [|b' m'] //= Emq Em'q.\n          move/andP=> [Hy Uq']; set q1 := sieve m q'; set q2 := sieve m' q'.\n          have Hy': forall m'', fband (sieve m'' q') y = false.\n            move=> m''; apply/hasP => [] [z Hz Hyz].\n            by case/hasP: Hy; exists z; first exact (mem_sieve Hz).\n          have Ebq': filter (fband (Adds y q2)) q1 = filter (fband q2) q1.\n            move/idPn: (Hy' m); rewrite -/q1.\n            elim: q1 {Hrec} => [|z q1 Hrec] //=; move/norP=> [Hz Hq1].\n            by rewrite Sface (negbE Hz) Hrec.\n          case: b; rewrite /= Hrec //; case: b';\n            by rewrite //= ?connect0 ?Ebq' // /q2 Hy'.\n        have Uq1: simple (sieve mc q).\n          elim: (mc) (q) Uq => [|[|] m Hrec] [|y q'] //=;\n            rewrite !simple_adds; move/andP=> [Hy Uq']; auto.\n          rewrite Hrec // andbT; apply/hasP => [[z Hz Hyz]].\n          by case/hasP: Hy; exists z; first exact (mem_sieve Hz).\n        elim: (sieve mc q) Uq1 => [|y q1 Hrec] //=.\n        rewrite !simple_adds; move/andP=> [Hy Uq'].\n        case: (fband (sieve mt q) y); auto.\n        rewrite simple_adds Hrec // andbT; apply/hasP => [] [z Hz Hyz].\n        by rewrite mem_filter in Hz; case/hasP: Hy; case/andP: Hz; exists z.\n      apply: eq_n_comp_r => y; apply/idP/idP.\n        move/hasP=> [z Hz Hyz]; rewrite mem_filter in Hz; case/andP: Hz.\n        rewrite Hmt /= orbF -(adjF Hyz) Sadj //; move=> Hxy Hccz.\n        by rewrite /setI -/g Hxy Hmc; apply/hasP; exists z.\n      move/andP=> [Hxy Hccy]; rewrite Hmc in Hccy.\n      case/hasP: Hccy => [z Hz Hyz]; apply/hasP; exists z; auto.\n      by rewrite mem_filter /setI Hz andbT Hmt /= orbF -(adjF Hyz) Sadj.\n    rewrite count_filter -(size_maps (fun y => froot face (edge y))).\n    apply: leq_trans (card_size _); apply: subset_leq_card.\n    apply/subsetP => y; move/and3P=> [Dy Hxy Hyc]; case/adjP: Hxy => [z Hxz Hzy].\n    rewrite -(eqP Dy) -/g -((rootP (Sface g)) Hzy); apply: maps_f.\n    rewrite mem_filter /setI -fconnect_orbit /g Hxz andbT.\n    by move: (closed_connect (fbandF (insertE cc)) Hzy); rewrite -/g => ->.\n  apply/subsetP => Hccx.\n  have Hct: sub_set (fband (sieve mc q)) (fband (sieve mt q)).\n    move=> y Hy; rewrite -Hmc in Hy; case/hasP: Hy => [z Hz Hyz].\n    rewrite (closed_connect (fbandF (sieve mt q)) Hyz) Hmt /= orbF Sadj //; auto.\n  move: (mc) (mt) Emcq Emtq Uq Hct Hmtc; rewrite simple_recI.\n  elim: (q) => [|y q' Hrec] [|b m] // [|b' m'] //= Emq Em'q; move/andP=> [Hy Uq'].\n  have Hy': forall m'', fband (sieve m'' q') y = false.\n    move=> m''; apply/hasP => [] [z Hz Hyz]; case/hasP: Hy.\n    by exists z; first exact (mem_sieve Hz).\n  case: b; case: b'; move=> Hct; try apply: (Hrec m m'); auto.\n  move=> z Hz; move: (Hct z) => /=.\n  case Hzy: (cface z y) => /=; auto.\n  - by rewrite (closed_connect (fbandF (sieve m q')) Hzy) Hy' in Hz.\n  - by move: (Hct y); rewrite /= connect0 !Hy' => H; move: (H (erefl _)).\n  move=> z Hz; move: (Hct z) => /=; case Hzy: (cface z y) => /=; auto.\n  by rewrite (closed_connect (fbandF (sieve m q')) Hzy) Hy' in Hz.\nmove=> et [k Hk Det]; rewrite {et}Det.\nrewrite {1}/mr0 sieve_false in Hcc; case: {Hk Hcc}(Hcc _ Hk).\nhave <-: r = sieve (maps negb mr0) r.\n  by rewrite /mr0; elim: (r) => [|x r' Hrec] //=; congr Adds.\nmove: k => _ k Hk <-; apply/(ctree_mem_cpcolor _ _).\nsplit; first exact: even_etrace.\nset et := trace (maps k (cpring (cpmap cpc))).\nrewrite /etrace; pose h := etrace_perm (behead et).\nexists (comp h k); first by apply: coloring_inj => //; apply permc_inj.\nrewrite sumt_permt (maps_comp h k) -/(permt h) trace_permt -/et.\nrewrite /permt -maps_adds; congr (maps h).\nhave Het: sumt et = Color0 by apply: sumt_trace.\ncase Det: et (introT eqP Het) {h} => [|e et'] /=.\n  by move: (congr1 size Det); rewrite /et size_trace size_maps head_cpring.\nby rewrite -eq_addc0; move/eqcP=> <-.\nQed.\n\nEnd ConfigContract.\n\nSet Strict Implicit.\nUnset Implicit Arguments.\n\n", "meta": {"author": "tangentforks", "repo": "FourColorTheorem", "sha": "eb30720f9e773fdcbf13dc6c61fdb245587cf401", "save_path": "github-repos/coq/tangentforks-FourColorTheorem", "path": "github-repos/coq/tangentforks-FourColorTheorem/FourColorTheorem-eb30720f9e773fdcbf13dc6c61fdb245587cf401/cfcontract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2499306426252682}}
{"text": "Require Import Coq.Program.Basics. \nRequire Import Coq.Strings.String.\nRequire Import Setoid. \nRequire Import ZArith.\nRequire Import Coq.Program.Equality.\nRequire Import Lia.\nRequire Import Ascii.\n\nRequire Import FinProof.All.\n\nRequire Import UMLang.All. \nRequire Import UMLang.LocalClassGenerator.ClassGenerator.\nRequire Import UMLang.GlobalClassGenerator.ClassGenerator.\n\nRequire Import UrsusStdLib.Solidity.All.\nRequire Import UrsusStdLib.Solidity.unitsNotations.\nRequire Import UrsusTVM.Solidity.All.\n\nImport UrsusNotations.\nLocal Open Scope xlist_scope.\nLocal Open Scope record.\nLocal Open Scope program_scope.\nLocal Open Scope glist_scope.\nLocal Open Scope ursus_scope.\nLocal Open Scope usolidity_scope.\n\nFrom elpi Require Import elpi.\n\n\nLocal Open Scope struct_scope.\nLocal Open Scope N_scope.\nLocal Open Scope string_scope.\nRequire Import SetcodeMultisig. \n\nRequire Import UMLang.ExecGenerator.\nRequire Import UMLang.ExecGen.GenFlags.\nRequire Import UMLang.ExecGen.ExecGenDefs.\nRequire Import FinProof.CommonInstances.\n\nRequire Import CommonQCEnvironment.\nRequire Import SetcodeMultisig_LocalState. \nRequire Import CommonForProps.\n\nDefinition INT_1 l (owners : listArray uint256) (reqConfirms :  uint8) (lifetime :  uint32): Prop := \n  isError (eval_state (Uinterpreter (constructor rec def owners reqConfirms lifetime)) l) = false ->\n  length_ owners > 0.\n\nDefinition INT_2 l (owners : listArray uint256) (reqConfirms : uint8)  lifetime: Prop := \n  let MAX_CUSTODIANS := toValue (eval_state (sRReader (MAX_CUSTODIAN_COUNT_right rec def) ) l) in\n  isError (eval_state (Uinterpreter (constructor rec def owners reqConfirms lifetime)) l) = false ->\n  length_ owners <= uint2N MAX_CUSTODIANS.\n\n(* --constructor--\n   --executeUpdate--\n   1: confirmUpdate\n   2: submitUpdate\n   3: confirmTransaction\n   4: submitTransaction\n   5: sendTransaction \n*)\n\nDefinition INT_3_common l l': Prop :=\n  toValue (eval_state (sRReader (m_custodians_right rec def) ) l) =\n    toValue (eval_state (sRReader (m_custodians_right rec def) ) l') /\\\n  toValue (eval_state (sRReader (m_custodianCount_right rec def) ) l) =\n    toValue (eval_state (sRReader (m_custodianCount_right rec def) ) l') /\\\n  toValue (eval_state (sRReader (m_ownerKey_right rec def) ) l) =\n    toValue (eval_state (sRReader (m_ownerKey_right rec def) ) l') /\\\n  (* INT_4_2 *)\n  toValue (eval_state (sRReader (m_defaultRequiredConfirmations_right rec def) ) l) =\n    toValue (eval_state (sRReader (m_defaultRequiredConfirmations_right rec def) ) l') /\\\n  (* INT_5 *)\n  toValue (eval_state (sRReader (m_lifetime_right rec def) ) l) =\n    toValue (eval_state (sRReader (m_lifetime_right rec def) ) l').\n\nDefinition INT_3_1 l (updateId :  uint64) : Prop :=\n  let l' := exec_state (Uinterpreter (confirmUpdate rec def updateId)) l in \n  correctState l ->\n  INT_3_common l l'.\n\nDefinition INT_3_2 l (codeHash : optional uint256) (owners : optional (listArray uint256)) (reqConfirms : optional uint8) (lifetime : optional uint32) : Prop :=\n  let l' := exec_state (Uinterpreter (submitUpdate rec def codeHash owners reqConfirms lifetime)) l in \n  correctState l ->\n  INT_3_common l l'.\n\nDefinition INT_3_3 l (transactionId :  uint64) : Prop :=\n  let l' := exec_state (Uinterpreter (confirmTransaction rec def transactionId)) l in \n  correctState l ->\n  INT_3_common l l'.\n\nDefinition INT_3_4 l (dest :  address) (value :  uint128) (bounce :  boolean) (allBalance :  boolean) (payload :  cell_) (stateInit :  optional  ( TvmCell )): Prop :=\n  let l' := exec_state (Uinterpreter (submitTransaction rec def dest value bounce allBalance payload stateInit)) l in \n  correctState l ->\n  INT_3_common l l'.\n\nDefinition INT_3_5 l (dest :  address) (value :  uint128) (bounce :  boolean) (flags :  uint8) (payload :  cell_) : Prop :=\n  let l' := exec_state (Uinterpreter (sendTransaction rec def dest value bounce flags payload)) l in \n  correctState l ->\n  INT_3_common l l'.\n\n(* INT_4_1 is checked as part of INT_8_2 *)\n\n(* INT_4_2 is checked as part of INT_3_x *)\n\n(* INT_5 is checked as part of INT_3_x *)\n\nDefinition INT_6 l (owners : listArray uint256) (reqConfirms :  uint8) (lifetime :  uint32) : Prop := \n  let msgPubkey := toValue (eval_state (sRReader || msg->pubkey() || ) l) in\n  let tvmPubkey := toValue (eval_state (sRReader || tvm->pubkey() ||) l) in\n  isError (eval_state (Uinterpreter (constructor rec def owners reqConfirms lifetime)) l) = false ->\n  msgPubkey = tvmPubkey.\n\nDefinition equalExceptLocal (l l': LedgerLRecord rec) := \n  ledgerEqb {$$ l with Ledger_LocalState := getPruvendoRecord Ledger_LocalState l' \n$$} l'.\n\nDefinition INT_7 (l: LedgerLRecord rec) (owners : listArray uint256) (reqConfirms :  uint8) (lifetime :  uint32) : Prop := \n  let l' := exec_state (Uinterpreter (constructor rec def owners reqConfirms lifetime)) l in \n  isError (eval_state (Uinterpreter (constructor rec def owners reqConfirms lifetime)) l) = true ->\n  equalExceptLocal l l' = true. \n\nDefinition INT_8_1 l (owners : listArray uint256) (reqConfirms :  uint8) (lifetime :  uint32) : Prop := \n  let MAX_CUSTODIANS := toValue (eval_state (sRReader (MAX_CUSTODIAN_COUNT_right rec def) ) l) in\n  let msgPubkey := toValue (eval_state (sRReader || msg->pubkey() ||) l) in\n  let tvmPubkey := toValue (eval_state (sRReader || tvm->pubkey() ||) l) in\n  length_ owners > 0 ->\n  length_ owners <= uint2N MAX_CUSTODIANS ->\n  msgPubkey = tvmPubkey ->\n  uint2N lifetime > 0 -> (* NOT IN SPEC *)\n  isError (eval_state (Uinterpreter (constructor rec def owners reqConfirms lifetime)) l) = false.\n\nDefinition INT_8_2 l (owners : listArray uint256) (reqConfirms :  uint8) (lifetime :  uint32) : Prop := \n  let l' := exec_state (Uinterpreter (constructor rec def owners reqConfirms lifetime)) l in\n  let owners_sz := length_ owners in\n  let custodians := toValue (eval_state (sRReader (m_custodians_right rec def) ) l') in\n  let custodians_sz := length_ custodians in\n  let reqConfirms' := if N.ltb custodians_sz (uint2N reqConfirms) then (Build_XUBInteger custodians_sz) else reqConfirms in\n  let ownerKey := toValue (eval_state (sRReader (m_ownerKey_right rec def) ) l') in\n  let _lifetime := uint2N (toValue (eval_state (sRReader (m_lifetime_right rec def) ) l')) in\n  let MIN_LIFETIME := uint2N (toValue (eval_state (sRReader (MIN_LIFETIME_right rec def) ) l)) in\n  let DEFAULT_LIFETIME := uint2N (toValue (eval_state (sRReader (DEFAULT_LIFETIME_right rec def) ) l)) in\n  let tvm_now := uint2N (toValue (eval_state (sRReader || now ||) l)) in\n  let lifetime_lower := MIN_LIFETIME * custodians_sz in\n  let lifetime_upper := N.land tvm_now 0xFFFFFFFF in\n  isError (eval_state (Uinterpreter (constructor rec def owners reqConfirms lifetime)) l) = false ->\n  (* result.m_custodians.size <= params.owners.size *)\n  custodians_sz <= owners_sz /\\\n  (* (∀ i : i ≥ 0 ⟶ i < result.m_custodians.size ⟶ (exists c : c In result.m_custodians.keys ⋀ result.m_custodians[c] = Some(i))) /\\\n     (∀ c1, c2, v : ⟶ result.m_custodians[c1] = result.m_custodians[c2] ⟶ result.m_custodians[c1] = Some(v) ⟶ c1 = c2 )*)\n  checkMap1 custodians = true /\\\n  (* (∀ i : i ≥ 0 ⟶ i < params.owners.size ⟶ (exists j : result.m_custodians[params.owners[i]] = Some(j))) *)\n  checkMap2 custodians (N.to_nat owners_sz) owners = true /\\\n  (* INT 4_1 *)\n  (* result.m_defaultRequiredConfirmations = min (result.this.m_custodians.size, params.reqConfirms) *)\n  toValue (eval_state (sRReader (m_defaultRequiredConfirmations_right rec def) ) l') = reqConfirms' /\\\n  (* result.m_ownerKey = params.this.owners[0] *)\n  Some ownerKey = arrLookup 0 owners /\\\n  (* (∀ i : i ≥ 0 ⟶ i < 32 ⟶ result.m_requestsMask[i] = false) *)\n  N.land \n    (uint2N (toValue (eval_state (sRReader (m_requestsMask_right rec def) ) l')))\n     0xFFFFFFFF = 0 /\\\n  (* result.m_transactions = {} *)\n  length_ (toValue (eval_state (sRReader (m_transactions_right rec def) ) l')) = 0 /\\\n  (* result.m_updateRequests = {} *)\n  length_ (toValue (eval_state (sRReader (m_updateRequests_right rec def) ) l')) = 0 /\\\n  (* (∀ i : i ≥ 0 ⟶ i < 32 ⟶ result.m_updateRequestsMask[i] = false) *)\n  N.land \n    (uint2N (toValue (eval_state (sRReader (m_updateRequestsMask_right rec def) ) l')))\n     0xFFFFFFFF = 0 /\\\n  (* result.m_lifetime = params.this.lifetime *)\n  ((uint2N lifetime > 0) ->\n  (uint2N lifetime >= lifetime_lower -> uint2N lifetime <= lifetime_upper -> _lifetime = uint2N lifetime) /\\\n  (uint2N lifetime < lifetime_lower -> _lifetime = lifetime_lower) /\\\n  (uint2N lifetime > lifetime_upper -> _lifetime = lifetime_upper)) /\\\n  (uint2N lifetime = 0 -> _lifetime = DEFAULT_LIFETIME).\n", "meta": {"author": "Pruvendo", "repo": "multisig2", "sha": "d4f8242ecfb79b9f8f61dcbc9d19f889c7051d6c", "save_path": "github-repos/coq/Pruvendo-multisig2", "path": "github-repos/coq/Pruvendo-multisig2/multisig2-d4f8242ecfb79b9f8f61dcbc9d19f889c7051d6c/src/ursus/INT/Props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24993064262526818}}
{"text": "(***************************************************************************\n* Preservation and Progress for mini-ML (CBV) - Proofs                     *\n* Arthur Chargueraud, March 2007, Coq v8.1                                 *\n* Extension to structural polymorphism                                     *\n* Jacques Garrigue, October 2007 - June 2008                               *\n***************************************************************************)\n\nSet Implicit Arguments.\nRequire Import Arith List Metatheory \n  ML_SP_Definitions ML_SP_Infrastructure.\nRequire Omega.\n\nModule MkSound(Cstr:CstrIntf)(Const:CstIntf).\n\nModule Infra := MkInfra(Cstr)(Const).\nImport Infra.\nImport Defs.\n\nModule Mk2(Delta:DeltaIntf).\nModule JudgInfra := MkJudgInfra(Delta).\nImport JudgInfra.\nImport Judge.\n\nLemma kenv_ok_concat : forall K1 K2,\n  kenv_ok K1 -> kenv_ok K2 -> disjoint (dom K1) (dom K2) -> kenv_ok (K1 & K2).\nProof. auto. Qed.\n\nLemma ok_kinds_open_vars : forall K Ks Xs,\n  ok K -> fresh (dom K) (length Ks) Xs ->\n  ok (K & kinds_open_vars Ks Xs).\nProof.\n  intros.\n  unfold kinds_open_vars.\n  apply* disjoint_ok.\n  apply* ok_combine_fresh.\nQed.\n\nHint Resolve ok_kinds_open_vars : core.\n\n(* ********************************************************************** *)\n(** Typing is preserved by weakening *)\n\nLemma typing_weaken : forall gc G E F K t T,\n   K ; (E & G) |gc|= t ~: T -> \n   env_ok (E & F & G) ->\n   K ; (E & F & G) |gc|= t ~: T.\nProof.\n  introv Typ. gen_eq (E & G) as H. gen G.\n  induction Typ; introv EQ Ok; subst.\n  apply* typing_var. apply* binds_weaken.\n  apply_fresh* (@typing_abs gc) as y. apply_ih_bind* H1.\n    forward~ (H0 y) as Q.\n  apply_fresh* (@typing_let gc M L1) as y. apply_ih_bind* H2.\n    forward~ (H1 y) as Q.\n  auto*.\n  auto.\n  apply_fresh* (@typing_gc gc Ks) as y.\nQed.\n\nLemma proper_instance_weaken : forall K K' K'' Ks Us,\n  ok (K & K' & K'') ->\n  proper_instance (K & K'') Ks Us ->\n  proper_instance (K & K' & K'') Ks Us.\nProof.\n  intros.\n  destruct* H0 as [TM FM]; split2*.\nQed.\n\nLemma typing_weaken_kinds : forall gc K K' K'' E t T,\n  K & K''; E |gc|= t ~: T ->\n  kenv_ok (K & K' & K'') ->\n  K & K' & K''; E |gc|= t ~: T.\nProof.\n  introv Typ. gen_eq (K & K'') as H. gen K''.\n  induction Typ; introv EQ Ok; subst.\n  apply* typing_var. apply* proper_instance_weaken.\n  apply_fresh* (@typing_abs gc) as y.\n  apply_fresh* (@typing_let gc M (L1 \\u dom(K&K'&K''))) as y.\n    intros. clear H1 H2.\n    rewrite concat_assoc.\n    apply* H0; clear H0. rewrite* concat_assoc.\n    forward~ (H Xs) as Typ.\n  apply* typing_app.\n  apply* typing_cst. apply* proper_instance_weaken.\n  apply_fresh* (@typing_gc gc Ks) as y.\n  intros.\n  rewrite concat_assoc.\n  apply* (H1 Xs); clear H1.\n    rewrite* concat_assoc.\n  forward~ (H0 Xs) as Typ; clear H0.\nQed.\n\nLemma typing_weaken_kinds' : forall gc K K' E t T,\n  kenv_ok (K & K') ->\n  K ; E |gc|= t ~: T -> K & K' ; E |gc|= t ~: T.\nProof.\n  intros.\n  replace (K & K') with (K & K' & empty) by simpl*.\n  apply* typing_weaken_kinds.\nQed.\n\nLemma proper_instance_subst : forall K K' K'' Ks Us S,\n  env_prop type S ->\n  proper_instance (K & K' & K'') Ks Us ->\n  well_subst (K & K' & K'') (K & map (kind_subst S) K'') S ->\n  proper_instance (K & map (kind_subst S) K'') (List.map (kind_subst S) Ks)\n    (List.map (typ_subst S) Us).\nProof.\n  introv TS PI WS.\n  destruct* PI.\n  split. rewrite map_length. apply* typ_subst_type_list.\n  rewrite* <- kinds_subst_open.\nQed.\n\nLemma well_subst_fresh : forall K K' K'' S Ys Ks,\n  well_subst (K & K' & K'') (K & map (kind_subst S) K'') S ->\n  fresh (dom S \\u dom K \\u dom K'') (length Ks) Ys ->\n  well_subst (K & K' & K'' & kinds_open_vars Ks Ys)\n    (K & map (kind_subst S) (K'' & kinds_open_vars Ks Ys)) S.\nProof.\n  introv WS Fr.\n  assert (KxYs: disjoint (dom K \\u dom K'')\n                         (dom (kinds_open_vars Ks Ys))) by auto.\n  intro x; intros.\n  rewrite map_concat. rewrite <- concat_assoc.\n  destruct* (binds_concat_inv H) as [[N B]|B]; clear H.\n  destruct k; try constructor.\n  simpl. rewrite get_notin_dom by auto.\n  puts (binds_map (kind_subst S) B).\n  apply* wk_kind.\nQed.\n\nLemma All_kind_types_subst : forall k S,\n  All_kind_types type k ->\n  env_prop type S -> All_kind_types type (kind_subst S k).\nProof.\n  intros; unfold kind_subst; apply All_kind_types_map.\n  apply* All_kind_types_imp.\nQed.\n\nHint Resolve All_kind_types_subst : core.\n\nLemma kenv_ok_subst : forall K K' K'' S,\n  env_prop type S ->\n  kenv_ok (K & K' & K'') -> kenv_ok (K & map (kind_subst S) K'').\nProof.\n  introv HS H.\n  kenv_ok_solve. auto.\n  intro; intros.\n  destruct (in_map_inv _ _ _ _ H1) as [b [Hb B]].\n  subst*.\nQed.\n\nLemma env_ok_subst : forall E E' S,\n  env_prop type S ->\n  env_ok (E & E') -> env_ok (E & map (sch_subst S) E').\nProof.\n  introv HS H.\n  env_ok_solve. auto.\n  intro; intros.\n  destruct (in_map_inv _ _ _ _ H0) as [b [Hb B]].\n  subst*.\nQed.\n\nHint Resolve kenv_ok_subst env_ok_subst : core.\n\n(* ********************************************************************** *)\n(** Type substitution preserves typing *)\n\nLemma typing_typ_subst : forall gc F K'' S K K' E t T,\n  disjoint (dom S) (env_fv E \\u fv_in kind_fv K) ->\n  env_prop type S ->\n  well_subst (K & K' & K'') (K & map (kind_subst S) K'') S ->\n  K & K' & K''; E & F |gc|= t ~: T -> \n  K & map (kind_subst S) K''; E & (map (sch_subst S) F) |gc|=\n    t ~: (typ_subst S T).\nProof.\n  introv. intros Dis TS WS Typ.\n  gen_eq (K & K' & K'') as GK; gen_eq (E & F) as G; gen K''; gen F.\n  induction Typ; introv WS EQ EQ'; subst; simpls typ_subst.\n  (* Var *)\n  rewrite~ sch_subst_open. apply* typing_var.\n    binds_cases H1.\n      apply* binds_concat_fresh.\n      rewrite* sch_subst_fresh.\n      use (fv_in_spec sch_fv _ _ _ (binds_in B)).\n     auto*.\n    destruct M as [T Ks]. simpl.\n    apply* proper_instance_subst.\n  (* Abs *)\n  apply_fresh* (@typing_abs gc) as y.\n   replace (Sch (typ_subst S U) nil) with (sch_subst S (Sch U nil)) by auto.\n   apply_ih_map_bind* H1.\n  (* Let *)\n  apply_fresh* (@typing_let gc (sch_subst S M)\n                            (L1 \\u dom S \\u dom K \\u dom K'')) as y.\n   clear H H1 H2. clear L2 T2 t2 Dis.\n   simpl. intros Ys Fr. \n   rewrite* <- sch_subst_open_vars.\n   rewrite* <- kinds_subst_open_vars.\n   rewrite concat_assoc. rewrite <- map_concat.\n   rewrite map_length in Fr.\n   apply* H0; clear H0.\n     apply* well_subst_fresh.\n   rewrite* concat_assoc.\n   apply_ih_map_bind* H2.\n  (* App *)\n  auto*.\n  (* Cst *)\n  rewrite* sch_subst_open.\n  assert (disjoint (dom S) (sch_fv (Delta.type c))).\n    intro x. rewrite* Delta.closed.\n  rewrite* sch_subst_fresh.\n  apply* typing_cst.\n  rewrite* <- (sch_subst_fresh S H2).\n  destruct (Delta.type c) as [T Ks]; simpl.\n  apply* proper_instance_subst.\n  (* GC *)\n  apply* (@typing_gc gc (List.map (kind_subst S) Ks)\n                     (L \\u dom S \\u dom K \\u dom K'')).\n   rewrite map_length; intros.\n   rewrite* <- kinds_subst_open_vars.\n   rewrite concat_assoc. rewrite <- map_concat.\n   apply* (H1 Xs); clear H1.\n     apply* well_subst_fresh.\n   rewrite* concat_assoc.\nQed.\n\nLemma typing_typ_substs : forall gc K' S K E t T,\n  disjoint (dom S) (env_fv E \\u fv_in kind_fv K \\u dom K) -> \n  env_prop type S ->\n  well_subst (K & K') K S ->\n  K & K'; E |gc|= t ~: T -> \n  K ; E |gc|= t ~: (typ_subst S T).\nProof.\n  intros.\n  generalize (@typing_typ_subst gc empty empty); intro TTS.\n  simpl in TTS.\n  apply* TTS.\nQed.\n  \n(* ********************************************************************** *)\n(** Typing schemes for expressions *)\n\nDefinition has_scheme_vars gc L (K:kenv) E t M := forall Xs,\n  fresh L (sch_arity M) Xs ->\n  K & kinds_open_vars (sch_kinds M) Xs; E |gc|= t ~: (M ^ Xs).\n\nDefinition has_scheme gc K E t M := forall Vs,\n  types (sch_arity M) Vs ->\n  list_forall2 (well_kinded K) (kinds_open (sch_kinds M) Vs) Vs ->\n  K ; E |gc|= t ~: (M ^^ Vs).\n\n(* ********************************************************************** *)\n(** Type schemes of terms can be instanciated *)\n\nLemma kind_subst_open_combine : forall Xs Vs Ks,\n  fresh (kind_fv_list Ks) (length Xs) Xs ->\n  types (length Xs) Vs ->\n  forall k : kind,\n    In k Ks ->\n    kind_open k Vs = kind_subst (combine Xs Vs) (kind_open k (typ_fvars Xs)).\nProof.\n  introv Fr. intros.\n  destruct H.\n  rewrite* kind_subst_open.\n  rewrite* kind_subst_fresh.\n    rewrite* (fresh_subst {}).\n    rewrite* <- H.\n  rewrite* dom_combine.\n  use (kind_fv_fresh _ _ _ _ H0 Fr).\nQed.\n\nLemma well_subst_open_vars : forall (K:kenv) Vs (Ks:list kind) Xs,\n  fresh (fv_in kind_fv K) (length Ks) Xs ->\n  fresh (kind_fv_list Ks) (length Xs) Xs ->\n  types (length Xs) Vs ->\n  list_forall2 (well_kinded K) (kinds_open Ks Vs) Vs ->\n  well_subst (K & kinds_open_vars Ks Xs) K (combine Xs Vs).\nProof.\n  introv Fr Fr' TV WK.\n  intro x; intros.\n  destruct* (binds_concat_inv H) as [[N B]|B]; clear H.\n    unfold kinds_open_vars in N.\n    rewrite* kind_subst_fresh.\n      simpl.\n      rewrite* get_notin_dom.\n      destruct* k.\n    use (fv_in_spec kind_fv _ _ _ (binds_in B)).\n  unfold kinds_open_vars, kinds_open in *.\n  rewrite <- map_combine in B.\n  destruct (binds_map_inv _ _ B) as [k0 [Hk0 Bk0]]. subst.\n  puts (binds_map (kind_subst (combine Xs Vs)) B).\n  simpl in H; do 2 rewrite map_combine in H.\n  rewrite list_map_comp in H.\n  refine (list_forall2_get (P:=well_kinded K) Xs _ H _).\n    instantiate (1:=Vs).\n    rewrite* <- (list_map_ext Ks _ _ (kind_subst_open_combine _ _ Fr' TV)).\n  simpl; case_eq (get x (combine Xs Vs)); intros. auto.\n  elim (get_contradicts _ _ _ _ Bk0 H0); auto.\nQed.\n\nLemma has_scheme_from_vars : forall gc L K E t M,\n  has_scheme_vars gc L K E t M ->\n  has_scheme gc K E t M.\nProof.\n  intros gc L K E t [T Ks] H Vs TV. unfold sch_open. simpls.\n  fold kind in K. fold kenv in K.\n  pick_freshes (length Ks) Xs.\n  rewrite (fresh_length _ _ _ Fr) in TV.\n  rewrite~ (@typ_subst_intro Xs Vs T).\n  unfolds has_scheme_vars sch_open_vars. simpls.\n  intro WK.\n  apply* (@typing_typ_substs gc (kinds_open_vars Ks Xs)).\n    apply list_forall_env_prop. destruct* TV.\n  apply* well_subst_open_vars.\nQed.\n\n(* ********************************************************************** *)\n(** Typing is preserved by term substitution *)\n\nLemma typing_trm_subst : forall gc F M K E t T z u, \n  K ; E & z ~ M & F |(gc,GcAny)|= t ~: T ->\n  (exists L:vars, has_scheme_vars (gc,GcAny) L K E u M) -> \n  term u ->\n  K ; E & F |(gc,GcAny)|= (trm_subst z u t) ~: T.\nProof.\n  introv Typt. intros Typu Wu. \n  gen_eq (E & z ~ M & F) as G. gen_eq (gc, GcAny) as gc0. gen F.\n  induction Typt; introv EQ1 EQ2; subst; simpl trm_subst;\n    destruct Typu as [Lu Typu].\n  case_var.\n    binds_get H1. apply_empty* (@typing_weaken (gc,GcAny)).\n      destruct H2; apply* (has_scheme_from_vars Typu).\n    binds_cases H1; apply* typing_var.\n  apply_fresh* (@typing_abs (gc,GcAny)) as y. \n   rewrite* trm_subst_open_var. \n   apply_ih_bind* H1. \n  apply_fresh* (@typing_let (gc,GcAny) M0 L1) as y. \n   intros; apply* H0.\n     exists (Lu \\u mkset Xs); intros Ys TypM.\n     forward~ (Typu Ys) as Typu'; clear Typu.\n     apply* typing_weaken_kinds.\n     forward~ (H Xs).\n   rewrite* trm_subst_open_var.\n   apply_ih_bind* H2.\n  assert (exists L : vars, has_scheme_vars (gc,GcAny) L K E u M). exists* Lu.\n  auto*.\n  auto*.\n  apply_fresh* (@typing_gc (gc,GcAny) Ks) as y.\n   intros Xs Fr.\n   apply* H1; clear H1.\n   exists (Lu \\u dom K \\u mkset Xs); intros Ys Fr'.\n   forward~ (Typu Ys) as Typu'; clear Typu.\n   apply* typing_weaken_kinds.\n   forward~ (H0 Xs).\nQed.\n\n(* ********************************************************************** *)\n(** Canonical derivations *)\n\n(* less than 100 lines! *)\n\nLemma typing_gc_any : forall gc K E t T,\n  K ; E |gc|= t ~: T -> K ; E |(true,GcAny)|= t ~: T.\nProof.\n  induction 1; auto*.\n  apply* typing_gc. simpl; auto.\nQed.\n\nLemma typing_gc_raise : forall gc K E t T,\n  K ; E |gc|= t ~: T -> K ; E |gc_raise gc|= t ~: T.\nProof.\n  induction 1; destruct gc; destruct g; simpl; auto*.\n  apply* typing_gc. simpl; auto.\nQed.\n\nDefinition typing_gc_let K E t T := K; E |(true,GcLet)|= t ~: T.\n  \nLemma typing_gc_ind : forall (P: kenv -> env -> trm -> typ -> Prop),\n  (forall K E t T, K; E |(false,GcLet)|= t ~: T -> P K E t T) ->\n  (forall Ks L K E t T,\n    (forall Xs : list var,\n      fresh L (length Ks) Xs -> P (K & kinds_open_vars Ks Xs) E t T) ->\n    P K E t T) ->\n  forall K E t T, typing_gc_let K E t T -> P K E t T.\nProof.\n  intros.\n  unfold typing_gc_let in H1.\n  gen_eq (true,GcLet) as gc.\n  induction H1; intros; subst; try solve [apply* H].\n  apply* H0.\nQed.\n\nLemma typing_canonize : forall gc K E t T,\n  K ; E |gc|= t ~: T -> K ; E |(true,GcLet)|= t ~: T.\nProof.\n  induction 1; auto*.\n  (* App *)\n  clear H H0.\n  gen IHtyping1.\n  fold (typing_gc_let K E t2 S) in IHtyping2.\n  apply (proj2 (A:=kenv_ok K)).\n  induction IHtyping2 using typing_gc_ind.\n    split2*; intros; subst.\n    gen H. gen_eq (typ_arrow T0 T) as S.\n    fold (typing_gc_let K E t1 S) in IHtyping1.\n    apply (proj2 (A:=kenv_ok K)).\n    induction IHtyping1 using typing_gc_ind.\n      split2*; intros; subst.\n      apply* typing_app.\n    split.\n      destruct (var_freshes L (length Ks)) as [Xs HXs].\n      destruct* (H Xs HXs).\n    intros; subst.\n    apply* (@typing_gc (true,GcLet) Ks L).\n      simpl; auto.\n    intros.\n    destruct (H Xs H0); clear H.\n    apply* H3; clear H3.\n    apply* typing_weaken_kinds'.\n  split.\n    destruct (var_freshes L (length Ks)) as [Xs HXs].\n    destruct* (H Xs HXs).\n\n  intros.\n  apply* (@typing_gc (true,GcLet) Ks L).\n    simpl; auto.\n  intros.\n  destruct (H Xs H0); clear H.\n  apply* H2; clear H2.\n  apply* typing_weaken_kinds'.\n  (* GC *)\n  apply* typing_gc.\n  simpl; auto.\nQed.\n\n(* End of canonical derivations *)\n\n(* ********************************************************************** *)\n(** Extra hypotheses for main results *)\n\nModule Type SndHypIntf.\n  Parameter delta_typed : forall c tl vl K E gc T,\n    K ; E |(false,gc)|= const_app c tl ~: T ->\n    K ; E |(false,gc)|= @Delta.reduce c tl vl ~: T.\nEnd SndHypIntf.\n\nModule Mk3(SH:SndHypIntf).\nImport SH.\n\n(* ********************************************************************** *)\n(** Preservation: typing is preserved by reduction *)\n\nLemma typ_open_vars_nil : forall T,\n  type T -> typ_open_vars T nil = T.\nProof.\n  induction T; unfold typ_open_vars; simpl; intros; auto*.\n    inversion H.\n  unfold typ_open_vars in *; simpls.\n  rewrite IHT1. rewrite* IHT2. inversion* H. inversion* H.\nQed.\n\nLemma typing_abs_inv : forall gc K E t1 t2 T1 T2,\n  K ; E |(gc,GcAny)|= trm_abs t1 ~: typ_arrow T1 T2 ->\n  K ; E |(gc,GcAny)|= t2 ~: T1 ->\n  K ; E |(gc,GcAny)|= t1 ^^ t2 ~: T2.\nProof.\n  introv Typ1 Typ2.\n  gen_eq (gc,GcAny) as gcs.\n  gen_eq (trm_abs t1) as t.\n  gen_eq (typ_arrow T1 T2) as T.\n  induction Typ1; intros; subst; try discriminate.\n    inversions H2; inversions H3; clear H2 H3.\n    pick_fresh x. \n    rewrite* (@trm_subst_intro x). \n    apply_empty* (@typing_trm_subst gc).\n    exists {}. intro. unfold kinds_open_vars, sch_open_vars; simpl.\n    destruct Xs; simpl*. rewrite* typ_open_vars_nil.\n  apply* (@typing_gc (gc,GcAny) Ks L).\n  intros.\n  puts (H0 Xs H2); clear H0.\n  apply* H1.\n  apply* typing_weaken_kinds'.\nQed.\n\nLemma preservation_result : preservation.\nProof.\n  introv Typ. gen_eq (true, GcAny) as gc. gen t'.\n  induction Typ; introv EQ Red; subst; inversions Red;\n    try solve [apply* typing_gc];\n    try (destruct (const_app_inv c tl) as [eq | [T1' [T2' eq]]];\n         rewrite eq in *; discriminate).\n  (* Let *)\n  pick_fresh x. rewrite* (@trm_subst_intro x).\n   simpl in H1.\n   apply_empty* (@typing_trm_subst true).\n   apply* H1.\n  (* Let *)\n  apply* (@typing_let (true,GcAny) M L1).\n  (* Beta *)\n  apply* typing_abs_inv.\n  (* Delta *)\n  assert (K;E |(true,GcAny)|= trm_app t1 t2 ~: T) by auto*.\n  use (typing_canonize H).\n  fold (typing_gc_let K E (trm_app t1 t2) T) in H1.\n  rewrite <- H0 in *.\n  clear -H1.\n  gen_eq (const_app c tl) as t1.\n  induction H1 using typing_gc_ind; intros; subst.\n    apply* typing_gc_any.\n    apply* delta_typed.\n  apply* typing_gc. simpl*.\n  (* App1 *)\n  auto*.\n  (* App2 *)\n  auto*.\n  (* Delta/cst *)\n  apply* (@typing_gc_any (false,GcAny)).\n  apply* delta_typed.\n  rewrite* H3.\nQed.\n\n(* ********************************************************************** *)\n(** Progress: typed terms are values or can reduce *)\n\nLemma value_app_const : forall t1 t2 n,\n  valu n (trm_app t1 t2) ->\n  exists c:Const.const, exists vl:list trm,\n    length vl + n = Const.arity c /\\ trm_app t1 t2 = const_app c vl /\\\n    list_forall value vl.\nProof.\n  induction t1; intros; inversions H; try (inversion H3; fail).\n    clear IHt1_2.\n    destruct (IHt1_1 _ _ H3) as [c [vl [Hlen [Heq Hv]]]].\n    exists c. exists (vl ++ t2 :: nil).\n    split. rewrite app_length. rewrite <- Hlen. simpl. ring.\n    split. rewrite Heq. unfold const_app.\n      rewrite fold_left_app. simpl. auto.\n    apply* list_forall_concat.\n    constructor; auto. exists* n2.\n  exists c. exists (t2 :: nil).\n  inversions H3. rewrite H1.\n  unfold const_app. simpl; auto.\n  split3*. constructor; auto. exists* n2.\nQed.\n\nLemma progress_delta : forall K t0 t3 t2 T,\n  K; empty |(false,GcLet)|= trm_app (trm_app t0 t3) t2 ~: T ->\n  valu 0 (trm_app t0 t3) ->\n  value t2 ->\n  exists t' : trm, trm_app (trm_app t0 t3) t2 --> t'.\nProof.\n  intros.\n  destruct (value_app_const H0) as [c [vl [Hlen [Heq Hv]]]].\n  unfold const_app in *.\n  rewrite Heq in *.\n  change (exists t', fold_left trm_app (t2::nil) (const_app c vl) --> t').\n  unfold const_app; rewrite <- fold_left_app.\n  assert (list_for_n value (S(Const.arity c)) (vl ++ t2 :: nil)).\n    split2*. apply* list_forall_app.\n  exists (Delta.reduce H2).\n  apply red_delta.\nQed.\n\nLemma progress_result : progress.\nProof.\n  introv Typ. gen_eq (empty:env) as E. gen_eq (true,GcAny) as gc.\n  poses Typ' Typ.\n  induction Typ; intros; subst;\n    try (pick_freshes (length Ks) Xs; apply* (H0 Xs)).\n  inversions H1.\n  left*. exists* 0.\n  right*. pick_freshes (sch_arity M) Ys.\n    destructi~ (@H0 Ys) as [[n Val1] | [t1' Red1]].\n      assert (value t1). exists* n.\n      exists* (t2 ^^ t1).\n      exists* (trm_let t1' t2).\n  destruct~ IHTyp2 as [Val2 | [t2' Red2]].\n    destruct~ IHTyp1 as [Val1 | [t1' Red1]]. \n      use (typing_canonize Typ').\n      remember (empty(A:=sch)) as E.\n      remember (trm_app t1 t2) as t.\n      clear Typ1 Typ2 Typ'.\n      fold (typing_gc_let K E t T) in H.\n      apply (proj2 (A:=kenv_ok K)).\n      induction H using typing_gc_ind.\n        split2*; intros; subst.\n        destruct Val1 as [n Val1]; inversions Val1.\n        right*; exists* (t0 ^^ t2).\n        case_eq (Const.arity c); intros.\n          right*. rewrite H0 in Val1.\n          assert (list_for_n value 1 (t2 :: nil)) by split2*.\n          rewrite <- H0 in H1.\n          exists (Delta.reduce H1).\n          apply (red_delta H1).\n        left*. exists n. rewrite H0 in Val1. destruct* Val2.\n        destruct n.\n          right*; apply* progress_delta.\n        left*. destruct Val2. exists* n.\n      destruct (var_freshes L (length Ks)) as [Xs HXs].\n      destruct* (H Xs); clear H.\n      right*; exists* (trm_app t1' t2).\n    right*; exists* (trm_app t1 t2').\n  left*; exists* (Const.arity c).\n  destruct (var_freshes L (length Ks)) as [Xs HXs].\n  apply* (H1 Xs).\nQed.\n\nLemma value_irreducible : forall t t',\n  value t -> ~(t --> t').\nProof.\n  induction t; introv HV; destruct HV as [k HV']; inversions HV';\n    intro R; inversions R.\n       destruct (const_app_inv c tl) as [eq | [t1' [t2' eq]]];\n         rewrite eq in *; discriminate.\n      inversions H2.\n     destruct (value_app_const HV').\n     destruct H as [vl' [Hl [He Hv]]].\n     rewrite He in H0; clear He.\n     destruct (const_app_eq _ _ _ _ H0). subst.\n     clear -vl Hl; destruct vl.\n     Omega.omega.\n    elim (IHt1 t1'). exists* (S k). auto.\n   elim (IHt2 t2'). exists* n2. auto.\n  clear -vl H0.\n  destruct vl.\n  destruct (const_app_inv c0 tl) as [eq | [t1' [t2' eq]]];\n    rewrite eq in *; discriminate.\nQed.\n\nEnd Mk3.\n\nEnd Mk2.\n\nEnd MkSound.\n", "meta": {"author": "garrigue", "repo": "certint", "sha": "ca94fba3e87f843ee1b7666e3bdbf7900029e0ec", "save_path": "github-repos/coq/garrigue-certint", "path": "github-repos/coq/garrigue-certint/certint-ca94fba3e87f843ee1b7666e3bdbf7900029e0ec/ML_SP_Soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.24986272117420633}}
{"text": "(** * Generation of informations regarding the elements of an SITPN model *)\n\nRequire Import common.CoqLib.\nRequire Import common.GlobalFacts.\nRequire Import common.ListPlus.\nRequire Import sitpn.Sitpn.\nRequire Import sitpn.SitpnTypes.\n\nRequire Import common.ListDep.\nRequire Import common.GlobalTypes.\nRequire Import String.\nRequire Import common.StateAndErrorMonad.\nRequire Import common.ListMonad.\nRequire Import transformation.Sitpn2HVhdlTypes.\nRequire Import FunInd.\n\nSection GenSitpnInfos.\n\n  Variable sitpn : Sitpn.\n\n  (* The instantiated state type is [SitpnInfo sitpn] *)\n\n  Definition CompileTimeState := @Mon (Sitpn2HVhdlState sitpn).\n\n  (** ** Informations about transitions. *)\n\n  Section TransitionInfos.\n\n    (** Returns the list of input places of transition [t].\n\n        Correctness: Correct iff all input places of [t] are in the\n        returned list, and the returned list has no duplicates. *)\n\n    Definition get_inputs_of_t (t : T sitpn) : CompileTimeState (list (P sitpn)) :=    \n      (* Tests if a place is an input of t. *)\n      let is_input_of_t := (fun p => if (pre p t) then true else false) in\n      do Plist <- get_lofPs; Ret (filter is_input_of_t Plist).\n\n    (** Returns the list of output places of transition [t].\n\n        Correctness: Correct iff all output places of [p] are in the\n        returned list, and the returned list has no duplicates.\n\n        Does not raise an error if the returned list is nil because it\n        doesn't mean that [t] is an isolated transition; however [t] is a\n        \"source\" transition (without input). *)\n\n    Definition get_outputs_of_t (t : T sitpn) : CompileTimeState (list (P sitpn)) :=    \n      (* Tests if a place is an input of t. *)\n      let is_output_of_t := (fun p => if (post t p) then true else false) in\n      do Plist <- get_lofPs; Ret (filter is_output_of_t Plist).\n\n    (** Returns the list of conditions associated to transition [t].\n    \n    Correctness: Correct iff all conditions associated to [t] are in the\n    returned list, and the returned has no duplicates.  *)\n\n    Definition get_conds_of_t (t : T sitpn) : CompileTimeState (list (C sitpn)) :=\n      (* Tests if a condition is associated to t. *)\n      let is_cond_of_t := (fun c => (match has_C t c with one | mone => true | zero => false end)) in\n      do Clist <- get_lofCs; Ret (filter is_cond_of_t Clist).\n    \n    (** Computes the information about transition t, and adds it to\n        the current state. *)\n\n    Definition add_tinfo (t : T sitpn) : CompileTimeState unit :=\n      do inputs_of_t <- get_inputs_of_t t;\n      do outputs_of_t <- get_outputs_of_t t;\n      if (inputs_of_t ++ outputs_of_t)%list then\n        Err (\"add_tinfo: Transition \" ++ $$t ++ \" is an isolated transition.\")\n      else\n        do conds_of_t <- get_conds_of_t t;\n        set_tinfo (t, MkTransInfo _ inputs_of_t conds_of_t).\n\n    (** Calls the function [add_tinfo] for each transition of [sitpn], thus\n        modifying the current state. *)\n\n    Definition generate_trans_infos : CompileTimeState unit :=\n      do Tlist <- get_lofTs; iter add_tinfo Tlist.\n\n  End TransitionInfos.\n\n  (** ** Informations about places. *)\n\n  Section PlaceInfos.\n    \n    (** Returns a triplet of lists [(tin, tc, tout)] where [tin] is\n        the list of input transitions of [p], [tc] is the list of\n        output transitions of [p] that are in conflict, and [tout] is\n        the list of output transitions of [p] that are not in\n        conflict.\n\n        Correctness: Correct iff all input transitions of [p] are in\n        [tin], and [tin] has no duplicate, and all output transitions\n        of [p] are in [tc] and [tout], and [tout] and [tc] has no\n        duplicate.  *)\n\n    Definition get_neighbors_of_p (p : P sitpn) :\n      CompileTimeState (list (T sitpn) * list (T sitpn) * list (T sitpn)) :=\n      \n      (* Adds the transition t to the list of input and/or output\n         transitions of p. The list of output transitions of p is\n         divided between the transitions in conflict [tc], and\n         transitions without conflict [tout]. [tc] and [tout] are\n         disjoint lists. *)\n      \n      let get_neighbor_of_p :=\n          (fun (tin_tc_tout : (list (T sitpn) * list (T sitpn) * list (T sitpn))) t =>\n             let '(tin, tc, tout) := tin_tc_tout in\n             match post t p with\n             | Some _ =>\n               match pre p t with\n               | Some (basic, _) => ((tin ++ [t])%list, (tc ++ [t])%list, tout)\n               | Some ((inhibitor|test), _) => ((tin ++ [t])%list, tc, (tout ++ [t])%list)\n               | None => ((tin ++ [t])%list, tc, tout)\n               end\n             | None =>\n               match pre p t with\n               | Some (basic, _) => (tin, (tc ++ [t])%list, tout)\n               | Some ((inhibitor|test), _) => (tin, tc, (tout ++ [t])%list)\n               | None => (tin, tc, tout)\n               end\n             end) in\n\n      (* Iterates over the list of transitions, and builds the couple of\n         lists (tinputs, touputs) of p along the way by applying\n         function [is_neighbor_of_p].  *)\n      do Tlist <- get_lofTs;\n      match List.fold_left get_neighbor_of_p Tlist (nil, nil, nil) with\n      | (nil, nil, nil) => Err (\"get_neighbors_of_p: Place \" ++ $$p ++ \" is an isolated place.\")\n      | tin_tc_tout => Ret tin_tc_tout \n      end.\n\n    (** Returns the set of actions associated with place [p]. *)\n\n    Definition get_acts_of_p (p : P sitpn) : CompileTimeState (list (A sitpn)) :=\n      \n      (* Filters the list of actions of [sitpn]. Keeps only the\n         actions associated with place [p].  *)\n      do Alist <- get_lofAs; Ret (filter (fun a => has_A p a) Alist).\n    \n    (** Functions to solve conflicts in a given conflict group, i.e, a\n        set of transitions. *)\n    \n    Section ConflictResolution.\n\n      (** Returns [true] if there exists a condition [c] in [conds]\n          s.t. [c] is associated [t] and [not c] to [t'], or the other\n          way around. Returns [false] otherwise.  *)\n      \n      Definition exists_ccond (t t' : T sitpn) (conds : list (C sitpn)) : bool :=\n        let check_ccond_of_tt' := (fun c => match has_C t c, has_C t' c with\n                                              one, mone | mone, one => true\n                                            | _, _ => false\n                                            end) in\n        if (List.find check_ccond_of_tt' conds) then true else false.\n      \n      (** Returns [true] if there exists a condition [c] in the\n          intersection of the list of conditions of [t] and [t'] that\n          verify [C(c,t) = 1 and C(c,t') = -1] or [C(c,t) = -1 and\n          C(c,t') = 1] (i.e, complementary conditions are associated\n          to [t] and [t']). *)\n\n      Definition mutex_by_cconds (t t' : T sitpn) : CompileTimeState bool :=\n        do tinfo <- get_tinfo t;\n        do tinfo' <- get_tinfo t';\n        Ret (exists_ccond t t' (inter P1SigEq (P1SigEqdec Nat.eq_dec) (conds tinfo) (conds tinfo'))).      \n      \n      (** Returns [true] if there exists a place [p] in [places]\n          s.t. there exists a [basic] or [test] arc between [p] and\n          [t], and an [inhib] arc between [p] and [t'], or the other\n          way around. If such arcs exist, the weight of the inhib arc\n          must be lower or equal to the weight of the basic or test\n          arc. Returns [false] otherwise. *)\n\n      Definition exists_inhib (t t' : T sitpn) (pls : list (P sitpn)) : bool :=\n        let check_inhib_mutex :=\n            (fun p => match pre p t, pre p t' with\n                      | Some ((basic|test), ω), Some (inhibitor, ω')\n                      | Some (inhibitor, ω'), Some ((basic|test), ω) =>\n                        ω' <=? ω\n                      | _, _ => false\n                      end)\n        in if (List.find check_inhib_mutex pls) then true else false.\n\n      (** Returns [true] if there exists a place [p] in the\n         intersection of the list of input places of [t] and [t']\n         that mutually exclude [t] and [t'] by mean of an inhibitor\n         arc. *)\n\n      Definition mutex_by_inhib (t t' : T sitpn) : CompileTimeState bool :=\n        do tinfo <- get_tinfo t;\n        do tinfo' <- get_tinfo t';\n        Ret (exists_inhib t t' (inter P1SigEq (P1SigEqdec Nat.eq_dec) (pinputs tinfo) (pinputs tinfo'))).\n\n      (** Returns [true] is there exists no means of mutual exclusion\n         between transitions [t] and [t']. Returns [false]\n         otherwise.  *)\n      \n      Definition not_exists_mutex (t t' : T sitpn) : CompileTimeState bool :=\n        do mbyinhib <- mutex_by_inhib t t';\n        do mbycconds <- mutex_by_cconds t t';\n        Ret (negb (mbyinhib || mbycconds)).\n\n      (** Returns [true] if there exists at least one mean of mutual\n         exclusion between [t] and all transitions in [cgoft]\n         (conflict group of [t]). Returns [false] otherwise.  *)\n\n      Definition all_conflicts_of_t_solved (t : T sitpn) (cgoft : list (T sitpn)) : CompileTimeState bool :=\n        do res <- find (not_exists_mutex t) cgoft;\n        if res then Ret false else Ret true.\n\n      (** Returns [true] if all conflicts in the conflict group [cg]\n          are solved by means of mutual exclusion, or if the conflict\n          group is empty and has only one element. Returns [false]\n          otherwise.  *)\n      \n      Definition all_conflicts_solved_by_mutex (cg : list (T sitpn)) : CompileTimeState bool :=\n        do bl <- ListMonad.fold_left\n                   (fun '(bprod, l) t => do b <- all_conflicts_of_t_solved t (tl l); Ret (bprod && b, (tl l)))\n                   cg (true, cg);\n        Ret (fst bl).\n\n      Fixpoint all_conflicts_solved_by_mutex_without_foldl (cg : list (T sitpn)) {struct cg} : CompileTimeState bool :=\n        match cg with\n        | nil => Ret true\n        | t :: tl =>\n            (* If all conflicts of [t] are solved, then we can safely\n           withdraw it from the conflict group. Indeed, it means\n           that all the transitions of the tail are not in conflict\n           with [t]. Therefore, [t] is not needed anymore. *)\n            do b <- all_conflicts_of_t_solved t tl;\n            if b then all_conflicts_solved_by_mutex_without_foldl tl else Ret false\n        end.      \n      \n      (** Injects transition [t] in the list [stranss] depending on\n          the level of priority of [t] compared to the elements of the\n          list [stranss].\n    \n        Returns the new priority-sorted list where [c] has been\n        injected.\n      \n        Correctness hypotheses: (1) ~In t stranss, (2) NoDup stranss,\n        (3) Elements of stranss are ordered by decreasing level of\n        priority.\n\n        Correct iff the returned list has no duplicate and its elements\n        are ordered by decreasing level of priority. *)\n\n      Fixpoint inject_t (t : T sitpn) (stranss : list (T sitpn)) {struct stranss} :\n        CompileTimeState (list (T sitpn)) :=\n        match stranss with\n        (* If the list of priority-ordered transitions is empty, then\n           returns a singleton list where [t] is the element with the\n           highest priority. *)\n        | [] => Ret [t]\n\n        (* If there is a head element, compares the head element with t\n           priority-wise. *)\n        | x :: tl =>\n            (* If [t] has a higher priority than [x], then puts [t] as the\n               head element of [stranss], and returns the list. *)\n            if pr_dec t x then Ret (t :: stranss)\n            (* If [x] has a higher priority than [t], then tries to\n               inject [t] in the list's tail.  *)\n            else\n                if pr_dec x t then\n                  do stranss' <- inject_t t tl; Ret (x :: stranss')\n                else\n                  (* If [x ⊁ t] and [t ⊁ x] then error because the two\n                     elements not comparable, and the priority\n                     relation is not a total order over [t ∪ stranss]. *)\n                  Err (\"inject_t: transitions \"\n                         ++ $$t ++ \" and \"\n                         ++ $$x ++ \" are not comparable with the priority relation.\")\n        end.\n      \n      Functional Scheme inject_t_ind := Induction for inject_t Sort Prop.\n      \n      (** Takes a list of transitions [cgroup] (conflict group), and\n          returns a new list of transitions where the elements of the\n          confict group are ordered by level of firing priority.\n\n          Raises an error if the priority relation is not a strict\n          total order over the elements of [cgroup].  *)\n\n      Definition sort_by_priority (cgroup : list (T sitpn)) :\n        CompileTimeState (list (T sitpn)) :=\n        (* [scgroup] stands for sorted conflict group *)\n        fold_left (fun scgroup t => inject_t t scgroup) cgroup [].\n\n    End ConflictResolution.\n\n    (** Returns a PlaceInfo structure containing the information related\n      to place [p], a place of [sitpn].\n\n      Error cases :\n      \n      - p is an isolated place, i.e it doesn't have neither input nor\n        output transitions.\n\n      - the priority relation is not a strict total order over the\n        output transitions of t. \n     *)\n\n    Definition add_pinfo (p : P sitpn) : CompileTimeState unit :=\n\n      (* Gets the input, conflicting, and output transitions of place p. \n         Error: p is an isolated place.\n       *)\n      do tin_tc_tout <- get_neighbors_of_p p;\n      \n      (* Gets the set of actions associated with [p]. *)\n      do acts_of_p <- get_acts_of_p p;\n\n      (* If all conflicts in [tc] are not solved by means of mutual\n         exclusion, then transitions in [tc] must be sorted out by\n         increasing order of priority before setting the PlaceInfo\n         structure for place [p].\n         \n         Error: the priority relation is not a strict total order over\n         the output transitions of p.  *)\n      let '(tin, tc, tout) := tin_tc_tout in\n      do b <- all_conflicts_solved_by_mutex tc;\n      if b then\n        set_pinfo (p, MkPlaceInfo _ tin [] (tc ++ tout) acts_of_p)\n      else\n        do stc <- sort_by_priority tc;\n        set_pinfo (p, MkPlaceInfo _ tin stc tout acts_of_p).\n    \n    (** Computes information for all p ∈ P, and adds the infos to the\n        current state. *)\n    \n    Definition generate_place_infos : CompileTimeState unit :=\n      do Plist <- get_lofPs; iter add_pinfo Plist.\n    \n  End PlaceInfos.\n  \n  (** ** Informations about conditions, actions and functions *)\n\n  Section InterpretationInfos.\n\n    (** Returns the list of transitions associated to condition [c]. *)\n\n    Definition get_transs_of_c (c : C sitpn) : CompileTimeState (list (T sitpn)) :=\n      let is_trans_of_c := (fun t => (match has_C t c with one | mone => true | zero => false end)) in\n      do Tlist <- get_lofTs; Ret (filter is_trans_of_c Tlist).\n\n    (** Computes the information about transition c, and adds it to\n        the current state. *)\n\n    Definition add_cinfo (c : C sitpn) : CompileTimeState unit :=\n      do transs_of_c <- get_transs_of_c c;\n      set_cinfo (c, transs_of_c).\n\n    (** Calls the function [add_cinfo] for each condition of [sitpn], thus\n        modifying the current state. *)\n\n    Definition generate_cond_infos : CompileTimeState unit :=\n      do Clist <- get_lofCs; iter add_cinfo Clist.\n    \n    (** Returns the list of transitions associated to function [f]. *)\n\n    Definition get_transs_of_f (f : F sitpn) : CompileTimeState (list (T sitpn)) :=\n      do Tlist <- get_lofTs; Ret (filter (fun t => has_F t f) Tlist).\n\n    (** Computes the information about function f, and adds it to\n        the current state. *)\n\n    Definition add_finfo (f : F sitpn) : CompileTimeState unit :=\n      do transs_of_f <- get_transs_of_f f;\n      set_finfo (f, transs_of_f).\n    \n    (** Calls the function [add_finfo] for each function of [sitpn];\n        thus modifying the current state. *)\n    \n    Definition generate_fun_infos : CompileTimeState unit :=\n      do Flist <- get_lofFs; iter add_finfo Flist.\n    \n    (** Returns the list of places associated to action [a]. *)\n\n    Definition get_places_of_a (a : A sitpn) : CompileTimeState (list (P sitpn)) :=\n      do Plist <- get_lofPs; Ret (filter (fun p => has_A p a) Plist).    \n\n    (** Computes the information about action a, and adds it to the\n        current state. *)\n\n    Definition add_ainfo (a : A sitpn) : CompileTimeState unit :=\n      do places_of_a <- get_places_of_a a;\n      set_ainfo (a, places_of_a).\n    \n    (** Calls the function [add_ainfo] for each action of\n      [sitpn], thus modifying the current state. *)\n    \n    Definition generate_action_infos : CompileTimeState unit :=\n      do Alist <- get_lofAs; iter add_ainfo Alist.\n    \n  End InterpretationInfos.\n\n  (** ** Well-definition of an [Sitpn] *)\n\n  Section CheckWellDefinedSitpn.\n\n    (** Mostly checks that the priority relation is a strict\n        order. However, now that the property is a part of the Sitpn\n        record type, the check_wd_sitpn is no longer useful. Will\n        probably delete it in versions to come. *)\n    \n    (** Assuming that x ≻ y, checks that x ≻ z if y ≻ z.  Returns an\n        error if x ≻ y and y ≻ z but x ⊁ z.  *)\n    \n    Let check_trans (x y z : T sitpn) : CompileTimeState unit :=\n      match pr_dec y z, pr_dec x z with\n      | left _, right _ => Err (\"check_trans: priority relation is not transitive. \"\n                                  ++ $$x ++ \" ≻ \" ++ $$y\n                                  ++ \" and \" ++ $$y ++ \" ≻ \" ++ $$z\n                                  ++ \" but \" ++ $$x ++ \" ⊁ \" ++ $$z)\n      | _, _ => Ret tt\n      end.\n\n    (** Assuming that [x ≻ y], checks that if [y ≻ z] then [x ≻ z]\n        holds for each [z ∈ trs].  *)\n    \n    Definition iter_xy_check_trans (x y : T sitpn) (trs : list (T sitpn)) :\n      CompileTimeState unit :=\n      iter (check_trans x y) trs.\n\n    (** For each transition [y] in [trs], if [x ≻ y] then calls\n        [iter_xy_check_trans] on [x], [y] and [trs∖{y}].  *)\n    \n    Definition foreach_x_check_trans (x : T sitpn) (trs : list (T sitpn)) :\n      CompileTimeState unit :=\n      let f := fun y trs' =>\n                 if pr_dec x y\n                 then iter_xy_check_trans x y trs'\n                 else Ret tt\n      in foreach f trs.\n\n    (** Checks that the priority relation is transitive; returns an\n        error if not. *)\n    \n    Definition check_pr_is_trans :=\n      do Tlist <- get_lofTs; foreach foreach_x_check_trans Tlist.\n\n    (** Checks that the priority relation is irreflexive; returns\n        an error if not. *)\n    \n    Definition check_pr_is_irrefl : CompileTimeState unit :=\n      let check_irrefl :=\n          (fun t =>\n             if pr_dec t t\n             then Err (\"pr_rel_is_strict_order: priority relation is reflexive for transition \"\n                         ++ $$t ++ \".\")\n             else Ret tt) in\n      do Tlist <- get_lofTs; iter check_irrefl Tlist.\n\n    (** Checks that the priority relation is a strict order, i.e,\n        irreflexive and transitive. *)\n    \n    Definition pr_rel_is_strict_order : CompileTimeState unit :=\n      do _ <- check_pr_is_irrefl; check_pr_is_trans.\n    \n    (** Returns an error if the list of places or transitions of\n        [sitpn] are empty, or if the priority relation is not a strict\n        order.\n        \n        This is a partial checking of the well-definition of an SITPN\n        model. The other properties of the well-definition will\n        checked all along the transformation (e.g. the SITPN model is\n        conflict-free during the generation of place infos, etc.). *)\n    \n    Definition check_wd_sitpn : CompileTimeState unit :=\n      (* Raises an error if sitpn has an empty set of places or transitions. *)\n      if (places sitpn) then Err (\"Found an empty set of places.\")\n      else\n        if (transitions sitpn) then Err (\"Found an empty set of transitions.\")\n        else pr_rel_is_strict_order.\n\n    (** *** Well-definition of an [Sitpn] with nodup lists *)\n    \n    Definition Innodup2In {A}\n               (decA : forall x y : A, {x = y} + {x <> y})\n               {l : list A}\n               (a : { a : A | In a (nodup decA l) }) : {a : A | In a l}.\n      specialize (proj2_sig a) as pf;\n        rewrite (nodup_In decA) in pf;\n        exact (exist _ (proj1_sig a) pf). \n    Defined.\n\n    Definition pre2nodup (pre : P sitpn -> T sitpn -> option (ArcT * natstar)) := \n      fun p t => pre (Innodup2In Nat.eq_dec p) (Innodup2In Nat.eq_dec t).\n\n    Definition post2nodup (post : T sitpn -> P sitpn -> option natstar) :=\n      fun t p => post (Innodup2In Nat.eq_dec t) (Innodup2In Nat.eq_dec p).\n\n    Definition M02nodup (M0 : P sitpn -> nat) :=\n      fun p => M0 (Innodup2In Nat.eq_dec p).\n\n    Definition Is2nodup (Is : T sitpn -> option TimeInterval) :=\n      fun t => Is (Innodup2In Nat.eq_dec t).\n\n    Definition hasCtonodup (has_C : T sitpn -> C sitpn -> MOneZeroOne) :=\n      fun t c => has_C (Innodup2In Nat.eq_dec t) (Innodup2In Nat.eq_dec c).\n\n    Definition hasAtonodup (has_A : P sitpn -> A sitpn -> bool) :=\n      fun p a => has_A (Innodup2In Nat.eq_dec p) (Innodup2In Nat.eq_dec a).\n\n    Definition hasFtonodup (has_F : T sitpn -> F sitpn -> bool) :=\n      fun t f => has_F (Innodup2In Nat.eq_dec t) (Innodup2In Nat.eq_dec f).\n\n    Definition pr2nodup (pr : T sitpn -> T sitpn -> Prop) :=\n      fun x y => pr (Innodup2In Nat.eq_dec x) (Innodup2In Nat.eq_dec y).\n    \n    (* Definition check_wd_sitpn_nodup : CompileTimeState Sitpn := *)\n    (*   (* Raises an error if sitpn has an empty set of places or transitions. *) *)\n    (*   if (places sitpn) then Err (\"Found an empty set of places.\") *)\n    (*   else *)\n    (*     if (transitions sitpn) then Err (\"Found an empty set of transitions.\") *)\n    (*     else *)\n    (*       (* Builds a new [sitpn] where the list of places, transitions, *)\n    (*          actions, functions and conditions have no duplicate *)\n    (*          element. *) *)\n    (*       let sitpn_nodup := *)\n    (*           BuildSitpn (nodup Nat.eq_dec (places sitpn)) *)\n    (*                      (nodup Nat.eq_dec (transitions sitpn)) *)\n    (*                      (pre2nodup (@pre sitpn)) (post2nodup (@post sitpn)) *)\n    (*                      (M02nodup (@M0 sitpn)) (Is2nodup (@Is sitpn)) *)\n    (*                      (nodup Nat.eq_dec (conditions sitpn)) *)\n    (*                      (nodup Nat.eq_dec (actions sitpn)) *)\n    (*                      (nodup Nat.eq_dec (functions sitpn)) *)\n    (*                      (hasCtonodup (@has_C sitpn)) *)\n    (*                      (hasAtonodup (@has_A sitpn)) *)\n    (*                      (hasFtonodup (@has_F sitpn)) *)\n    (*                      (pr2nodup (@pr sitpn)) *)\n    (*       in *)\n    (*       (* do _ <- pr_rel_is_strict_order sitpn_nodup; *) *)\n    (*       Ret sitpn_nodup. *)\n    \n  End CheckWellDefinedSitpn.\n    \nEnd GenSitpnInfos.\n\n(** ** Informations about an [Sitpn] *)\n\n(** Returns an SitpnInfo instance computed from [sitpn]. *)\n\nDefinition generate_sitpn_infos (sitpn : Sitpn) :=\n\n  (* Turns the list of places, transitions, conditions, actions and\n     functions of [sitpn], into dependently-typed lists, and sets them\n     in the compile-time state. *)\n  do Plist <- tmap (fun p s => Ret p s) (places sitpn) nat_to_P;\n  do Tlist <- tmap (fun t s => Ret t s) (transitions sitpn) nat_to_T;\n  do Clist <- tmap (fun c s => Ret c s) (conditions sitpn) nat_to_C;\n  do Alist <- tmap (fun a s => Ret a s) (actions sitpn) nat_to_A;\n  do Flist <- tmap (fun f s => Ret f s) (functions sitpn) nat_to_F;\n  do _ <- set_lofPs Plist;\n  do _ <- set_lofTs Tlist;\n  do _ <- set_lofCs Clist;\n  do _ <- set_lofAs Alist;\n  do _ <- set_lofFs Flist;\n  \n  (* Call to [generate_trans_infos] must precede the call to\n     [generate_place_infos] because the latter uses transition\n     informations.  *)\n  (* do _ <- check_wd_sitpn sitpn; *)\n  do _ <- generate_trans_infos sitpn;\n  do _ <- generate_place_infos sitpn;\n  do _ <- generate_cond_infos sitpn; \n  do _ <- generate_action_infos sitpn;\n  generate_fun_infos sitpn.\n\n", "meta": {"author": "viampietro", "repo": "ver-hilecop", "sha": "cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4", "save_path": "github-repos/coq/viampietro-ver-hilecop", "path": "github-repos/coq/viampietro-ver-hilecop/ver-hilecop-cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4/transformation/GenerateInfos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199306096343, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.24975602544358752}}
{"text": "\nRequire Import List.\nFrom mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq tuple ssrfun.\nFrom mathcomp Require Import choice path bigop fintype.\nRequire Import Lib.Base Ipdl.Exp Ipdl.Core String Ipdl.Lems Lib.TupleLems Ipdl.Tacs Lib.Dist Big Pars Lib.Set.\nRequire Import CoinFlip CFold CFSimComp CFReal.\n\nLemma pars_replace {chan : Type -> Type} (r2 : @ipdl chan) r1 rs :\n  pars [:: r1 & rs] =p pars [:: r2 & rs] ->\n  pars [:: r1 & rs] =p pars [:: r2 & rs].\n  done.\nQed.\n\nLemma new_pars_replace_elim {chan : Type -> Type} t r1 r2 rs rs' :\n  (forall c, @pars chan [:: Out c r1 & rs c] =p pars [:: Out c r1 & rs']) ->\n  (forall c, pars [:: Out c r2 & rs c] =p pars [:: Out c r2 & rs']) ->\n  (x <- new t ;; pars [:: Out x r1 & rs x]) =p (x <- new t ;; pars [:: Out x r2 & rs x]).\n  intros.\n  etransitivity.\n  apply EqCongNew => c_.\n  rewrite H.\n  apply EqRefl.\n  symmetry.\n  etransitivity.\n  apply EqCongNew => c.\n  rewrite H0.\n  apply EqRefl.\n  rewrite new_pars_remove; rewrite //=.\n  rewrite new_pars_remove; rewrite //=.\nQed.\nOpen Scope bool_scope.\n\nLemma CFRealIdealE {chan : Type -> Type} (k : nat) {n}\n           (honest : pred 'I_(n.+2))\n           (out advCommit : (n.+2).-tuple (chan k.-bv)) \n           (advOpen : (n.+2).-tuple (chan unit))\n           (advCommitted : (n.+2).-tuple ((n.+2).-tuple (chan unit)))\n           (advOpened : (n.+2).-tuple ((n.+2).-tuple (chan k.-bv))) :\n  ~~ honest ord0 ->\n  honest ord_max ->\n  CFRealSimpl k honest out advCommit advOpen advCommitted advOpened =p\n  SimComp_simpl7 k honest advCommit advOpen advCommitted advOpened out.\n  intros.\n  rewrite /CFRealSimpl.\n  rewrite /SimComp_simpl7.\n\n  setoid_rewrite (@newvec_newvec _ _ _ unit unit) at 1.\n  rewrite newvec_newvec.\n  apply EqCongNew_vec => open .\n  rewrite newvec_newvec.\n  apply EqCongNew_vec => committed .\n  rewrite newvec_newvec.\n  apply EqCongNew_vec => opened .\n  rotate_news.\n  apply EqCongNew_vec => sum_commits .\n  apply EqCongNew_vec => sum_open .\n  apply EqCongNew_vec => commit .\n  swap_tac 0 2.\n  apply pars_cons_cong; rewrite //=.\n  apply EqProt_big_r; intros; apply EqCongReact; r_swap 0 1; done.\n  swap_tac 0 3.\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 3.\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 2.\n  apply pars_cons_cong; rewrite //=.\n  rewrite bigpar_mkcond.\n  swap_tac 0 1.\n  rewrite bigpar_mkcond.\n  rewrite -par_in_pars.\n  rewrite -bigpar_par.\n  apply pars_cons_cong; rewrite //=.\n  apply EqProt_big_r; intros.\n  rewrite /Sim_CFParty.\n  destruct (honest x); simpl.\n  rewrite -eq_0par.\n  apply EqCongNew_vec => v1 .\n  apply EqCongNew_vec => v2 .\n  align.\n  rewrite -eq_par0.\n  done.\nQed.\n\nLemma CoinFlip_main {chan : Type -> Type} (k : nat) {n}\n           (honest : pred 'I_(n.+2))\n           (out advCommit : (n.+2).-tuple (chan k.-bv)) \n           (advOpen : (n.+2).-tuple (chan unit))\n           (advCommitted : (n.+2).-tuple ((n.+2).-tuple (chan unit)))\n           (advOpened : (n.+2).-tuple ((n.+2).-tuple (chan k.-bv))) :\n  ~~ honest ord0 ->\n  honest ord_max ->\n  CFReal k _ honest out advCommit advOpen advCommitted advOpened =p\n    leak <- new k.-bv ;; \n    ok <- new unit ;; \n    pars [::\n            Sim k honest leak ok advCommit advOpen advCommitted advOpened;\n            CFIdeal k _ honest leak ok out\n                 ].\n  intros.\n  rewrite CFRealSimplE.\n  symmetry.\n  etransitivity.\n  instantiate (1 := SimComp k honest advCommit advOpen advCommitted advOpened out).\n  done.\n\n  rewrite SimComp_E1.\n  rewrite SimComp_simpl2E //=.\n  rewrite SimComp_simpl3E //=.\n  rewrite SimComp_simpl4E //=.\n  rewrite SimComp_simpl5E //=.\n  rewrite SimComp_simpl6E //=.\n  rewrite SimComp_simpl7E //=.\n  rewrite CFRealIdealE //=.\nQed.\n", "meta": {"author": "ipdl", "repo": "ipdl", "sha": "d41b022c9a216acfefaefcbd0ede9e52e350ab8a", "save_path": "github-repos/coq/ipdl-ipdl", "path": "github-repos/coq/ipdl-ipdl/ipdl-d41b022c9a216acfefaefcbd0ede9e52e350ab8a/theories/protocols/CoinFlip/Proof/CTRealIdeal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.24972472098527979}}
{"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import Tactics.\nRequire Import Axioms.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Sequence.\nRequire Import Relation.\nRequire Import Ordinal.\nRequire Import Syntax.\nRequire Import SimpSub.\nRequire Import Dynamic.\nRequire Import Ofe.\nRequire Import Uniform.\nRequire Import Intensional.\nRequire Import Candidate.\nRequire Import System.\nRequire Import Semantics.\nRequire Import SemanticsKnot.\nRequire Import Judgement.\nRequire Import Hygiene.\nRequire Import ProperClosed.\nRequire Import ProperFun.\nRequire Import Shut.\n\nRequire Import ContextHygiene.\nRequire Import MapTerm.\n\n\nLemma cloctx_index :\n  forall object i G (h : @hyp object),\n    index i G h\n    -> cloctx G\n    -> hygieneh (fun j => j < length G - i - 1) h.\nProof.\nintros object i G h Hindex.\ninduct Hindex.\n\n(* 0 *)\n{\nintros h G Hcl.\ncbn.\ninvertc Hcl.\nintros _ Hcl.\nrewrite -> ctxpred_length in Hcl.\neapply hygieneh_weaken; eauto.\nintros j Hj.\nomega.\n}\n\n(* S *)\n{\nintros j h' G h _ IH Hcl.\ninvertc Hcl.\nintros Hcl _.\ncbn.\napply IH; auto.\n}\nQed.\n\n\nLemma seqctx_index :\n  forall i s s' G j h,\n    seqctx i s s' G\n    -> index j G h\n    -> seqhyp i (project s j) (project s' j) (substh (compose (sh (S j)) s) h) (substh (compose (sh (S j)) s') h).\nProof.\nintros i s s' G j h Hseq Hindex.\nrevert s s' Hseq.\ninduct Hindex.\n\n(* 0 *)\n{\nintros h G s1 s2 Hseq.\ninvert Hseq; [].\nintros m1 m2 s1' s2' Hss Hm <- <-.\nsimpsub.\nauto.\n}\n\n(* S *)\n{\nintros j h' G h Hindex IH s s' Hss.\ninvertc Hss; [].\nintros m1 m2 s1' s2' Hss' _ <- <-.\nsimpsub.\nauto.\n}\nQed.\n\n\nLemma sound_hyp_tm_pre :\n  forall G i a,\n    index i G (hyp_tm a)\n    -> seq G (deq (var i) (var i) (subst (sh (S i)) a)).\nProof.\nintros G j a Hindex.\napply seq_i.\nintros i s s' Hs.\nso (seqctx_index _#6 (pwctx_impl_seqctx _#4 Hs) Hindex) as H.\nsimpsubin H.\n(* For some reason, inversion is fouling up (sh (S j)), so we'll hide the ball. *)\nremember (sh (S j)) as shsj eqn:Heqshsj.\ninvertc H.\nintros R Hal Har Hm.\nsubst shsj.\nexists R.\nsimpsub.\ndo2 4 split; auto.\nQed.\n\n\nLemma sound_hyp_tm :\n  forall G i a,\n    index i G (hyp_tm a)\n    -> pseq G (deq (var i) (var i) (subst (sh (S i)) a)).\nProof.\nintros G i a Hindex.\nexists 0.\nintros j _.\napply sound_hyp_tm_pre.\napply index_app_left; auto.\nQed.\n\n\nLemma sound_hyp_tp_pre :\n  forall G i,\n    index i G hyp_tp\n    -> seq G (deqtype (var i) (var i)).\nProof.\nintros G j Hindex.\nrewrite -> seq_eqtype.\nintros i s s' Hs.\nso (seqctx_index _#6 (pwctx_impl_seqctx _#4 Hs) Hindex) as H.\nsimpsubin H.\ninvertc H.\nintros R Hal Har.\nexists R.\nsimpsub.\ndo2 3 split; auto.\nQed.\n\n\nLemma sound_hyp_tp :\n  forall G i,\n    index i G hyp_tp\n    -> pseq G (deqtype (var i) (var i)).\nProof.\nintros G i Hindex.\nexists 0.\nintros j _.\napply sound_hyp_tp_pre.\napply index_app_left; auto.\nQed.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/SoundHyp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438502, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24971927279901598}}
{"text": "Require Import Coq.Init.Wf Coq.Numbers.BinNums.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.FSets.FMapPositive.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Carriers.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Export Fiat.Parsers.ContextFreeGrammar.Fix.Definitions.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Fix.Properties.\nRequire Import Fiat.Common.FMapExtensions.Wf.\nRequire Import Fiat.Common.\nRequire Import Fiat.Common.OptionFacts.\nModule PositiveMapExtensions := FMapExtensionsWf PositiveMap.\nRequire Import Fiat.Common.SetoidInstances. (* must come after the above for instance priority *)\n\nSet Implicit Arguments.\nLocal Open Scope grammar_fixedpoint_scope.\n\nSection grammar_fixedpoint.\n  Context {Char : Type}.\n\n  Context (gdata : grammar_fixedpoint_data).\n\n  Definition aggregate_state := PositiveMap.t (state gdata).\n\n  Local Notation default_value := ⊤ (only parsing).\n\n  Definition lookup_state (st : aggregate_state) (nt : default_nonterminal_carrierT)\n    : state gdata\n    := PositiveMapExtensions.find_default default_value (nonterminal_to_positive nt) st.\n\n  Notation from_aggregate_state := lookup_state (only parsing).\n\n  Definition aggregate_state_le : aggregate_state -> aggregate_state -> bool\n    := PositiveMapExtensions.lift_leb state_le default_value.\n  Definition aggregate_state_eq : aggregate_state -> aggregate_state -> bool\n    := PositiveMapExtensions.lift_eqb state_beq default_value.\n  Definition aggregate_state_lt (v1 v2 : aggregate_state) : bool\n    := PositiveMapExtensions.lift_ltb state_beq state_le default_value v1 v2.\n\n  Lemma PositiveMap_elements_iff {A m k v}\n    : @PositiveMap.find A k m = Some v <-> In (k, v) (PositiveMap.elements m).\n  Proof.\n    rewrite PositiveMapExtensions.elements_iff_find.\n    rewrite InA_alt; unfold PositiveMap.eq_key_elt, PositiveMap.E.eq; simpl.\n    split; [ intros [[? ?] [[? ?] ?]] | intro H; exists (k, v) ];\n      subst; repeat split; assumption.\n  Qed.\n\n  Lemma PositiveMap_elements_iff' {A m kv}\n    : @PositiveMap.find A (fst kv) m = Some (snd kv) <-> In kv (PositiveMap.elements m).\n  Proof.\n    destruct kv; apply PositiveMap_elements_iff.\n  Qed.\n\n  Create HintDb aggregate_step_db discriminated.\n  Hint Rewrite PositiveMap.fold_1 PositiveMap.gmapi nonterminal_to_positive_to_nonterminal positive_to_nonterminal_to_positive PositiveMap.gempty PositiveMapAdditionalFacts.gsspec (@state_beq_refl _ gdata) orb_true_iff orb_true_r orb_false_iff (@state_le_bottom_eq_bottom _ gdata) (@no_state_lt_bottom _ gdata) (@state_le_bottom_eq_bottom _ gdata) (@state_ge_top_eq_top _ gdata) (@bottom_lub_r _ gdata) (@bottom_lub_l _ gdata) (@top_lub_r _ gdata) (@top_lub_l _ gdata) (fun a b => @least_upper_bound_correct_l _ gdata a b : _ = true) (fun a b => @least_upper_bound_correct_r _ gdata a b : _ = true) (fun s => @bottom_bottom _ gdata s : _ = true) (fun s => @top_top _ gdata s : _ = true) beq_nat_true_iff @PositiveMapExtensions.lift_brelation_iff : aggregate_step_db.\n  Hint Rewrite <- beq_nat_refl : aggregate_step_db.\n  Hint Rewrite PositiveMapExtensions.map2_1bis_for_rewrite using reflexivity : aggregate_step_db.\n  Hint Rewrite PositiveMapExtensions.fold_andb_true : aggregate_step_db.\n\n  Local Ltac fold_andb_t_step :=\n    idtac;\n    match goal with\n    | _ => progress intros\n    | _ => progress subst\n    | _ => congruence\n    | _ => progress unfold PositiveMap.key in *\n    | [ H : Some _ = Some _ |- _ ] => inversion H; clear H\n    | [ H : Some ?b <> Some false |- _ ] => destruct b eqn:?; [ clear H | congruence ]\n    | [ H : (⊥ =b ?s) = false, H' : (⊥ < ?s) = false |- _ ]\n      => let H'' := fresh in\n         pose proof (bottom_bottom s) as H''; setoid_rewrite orb_true_iff in H''; destruct H''; congruence\n    | [ H : context[PositiveMap.fold _ _ _ = true] |- _ ]\n      => setoid_rewrite PositiveMapExtensions.fold_andb_true in H\n    | [ |- context[PositiveMap.fold _ _ _ = true] ]\n      => setoid_rewrite PositiveMapExtensions.fold_andb_true\n    | [ |- true = false ] => symmetry\n    | [ H : PositiveMap.fold _ _ _ = false |- false = true ]\n      => rewrite <- H; clear H\n    | [ H : context[PositiveMap.find _ (PositiveMap.map2 ?f _ _)] |- _ ]\n      => setoid_rewrite (@PositiveMapExtensions.map2_1bis_for_rewrite _ _ _ f eq_refl) in H\n    | [ |- context[PositiveMap.find _ (PositiveMap.map2 ?f _ _)] ]\n      => setoid_rewrite (@PositiveMapExtensions.map2_1bis_for_rewrite _ _ _ f eq_refl)\n    | [ H : context[PositiveMapExtensions.lift_brelation] |- _ ]\n      => setoid_rewrite PositiveMapExtensions.lift_brelation_iff in H\n    | [ |- context[PositiveMapExtensions.lift_brelation] ]\n      => setoid_rewrite PositiveMapExtensions.lift_brelation_iff\n    | [ H : ?x = _, H' : context[?x] |- _ ] => setoid_rewrite H in H'\n    | [ H : ?x = _ |- context[?x] ] => setoid_rewrite H\n    | [ H : and _ _ |- _ ] => destruct H\n    | [ H : pointwise_relation _ eq ?x ?y, H' : context[step_constraints _ ?x] |- _ ]\n      => rewrite H in H'\n    | _ => progress autorewrite with aggregate_step_db in *\n    | [ H : forall k : positive, _ |- _ ]\n      => repeat match goal with\n                | [ k' : positive |- _ ]\n                  => unique pose proof (H k')\n                | [ |- context[PositiveMap.find ?k' _] ]\n                  => unique pose proof (H k')\n                | [ _ : context[PositiveMap.find ?k' _] |- _ ]\n                  => unique pose proof (H k')\n                end;\n         clear H\n    | _ => progress simpl in *\n    | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n    | [ H : context[match ?e with _ => _ end] |- _ ] => destruct e eqn:?\n    | [ |- _ <> _ ] => intro\n    | [ H : or _ _ |- _ ] => destruct H\n    | [ |- and _ _ ] => split\n    | [ H : (?x < ?y) = true, H' : (?y < ?z) = true |- _ ]\n      => unique pose proof (state_lt_Transitive H H' : (x < z) = true)\n    | [ H : is_true (?x =b ?y) |- _ ]\n      => rewrite H in *; clear x H\n    | [ H : is_true (?x =b ?y) |- _ ]\n      => rewrite <- H in *; clear x H\n    | [ H : ?R ?x ?y |- _ ]\n      => is_var x; rewrite H in *; clear x H\n    | [ H : ?R ?x ?y |- _ ]\n      => is_var y; rewrite <- H in *; clear y H\n    end.\n  Local Ltac fold_andb_t := repeat fold_andb_t_step.\n\n  Global Instance aggregate_state_eq_Reflexive : Reflexive aggregate_state_eq | 1 := _.\n  Global Instance aggregate_state_eq_Symmetric : Symmetric aggregate_state_eq | 1 := _.\n  Global Instance aggregate_state_eq_Transitive : Transitive aggregate_state_eq | 1 := _.\n  Global Instance aggregate_state_le_Reflexive : Reflexive aggregate_state_le | 1 := _.\n  Global Instance aggregate_state_le_Transitive : Transitive aggregate_state_le | 1 := _.\n  Global Instance aggregate_state_eq_Proper_Equal\n    : Proper (@PositiveMap.Equal _ ==> @PositiveMap.Equal _ ==> eq) aggregate_state_eq | 100\n    := _.\n  Global Instance aggregate_state_le_Proper_Equal\n    : Proper (@PositiveMap.Equal _ ==> @PositiveMap.Equal _ ==> eq) aggregate_state_le | 100\n    := _.\n  Global Instance aggregate_state_lt_Proper_Equal\n    : Proper (@PositiveMap.Equal _ ==> @PositiveMap.Equal _ ==> eq) aggregate_state_lt | 100\n    := _.\n  Global Instance aggregate_state_le_Proper\n    : Proper (aggregate_state_eq ==> aggregate_state_eq ==> eq) aggregate_state_le | 1\n    := _.\n  Global Instance aggregate_state_lt_Proper\n    : Proper (aggregate_state_eq ==> aggregate_state_eq ==> eq) aggregate_state_lt | 1\n    := _.\n\n  Definition aggregate_state_lub_f : option (state gdata) -> option (state gdata) -> option (state gdata)\n      := PositiveMapExtensions.defaulted_f default_value default_value least_upper_bound.\n\n  Definition aggregate_state_lub (v1 v2 : aggregate_state) : aggregate_state\n    := PositiveMap.map2 aggregate_state_lub_f v1 v2.\n\n  Definition aggregate_prestep (v : aggregate_state) : aggregate_state\n    := let helper := step_constraints gdata (from_aggregate_state v) in\n       PositiveMap.mapi (fun nt => helper (positive_to_nonterminal nt)) v.\n\n  Definition aggregate_step (v : aggregate_state) : aggregate_state\n    := aggregate_state_lub v (aggregate_prestep v).\n\n  Definition aggregate_state_lub_correct (v1 v2 : aggregate_state)\n    : aggregate_state_le v1 (aggregate_state_lub v1 v2)\n      /\\ aggregate_state_le v2 (aggregate_state_lub v1 v2).\n  Proof.\n    unfold aggregate_state_le, aggregate_state_lub, aggregate_state_lub_f.\n    setoid_rewrite PositiveMapExtensions.lift_brelation_iff.\n    unfold PositiveMapExtensions.defaulted_f.\n    repeat match goal with\n           | [ |- and _ _ ] => split\n           | _ => intro\n           | _ => progress subst\n           | [ H : ?x = _ |- context[?x] ] => setoid_rewrite H\n           | [ H : ?x = _, H' : context[?x] |- _ ] => setoid_rewrite H in H'\n           | [ H : Some _ = Some _ |- _ ] => inversion H; clear H\n           | [ H : context[match ?e with _ => _ end] |- _ ] => destruct e eqn:?\n           | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n           | [ |- is_true (?R ?x ?x) ] => reflexivity\n           | _ => apply top_top\n           | _ => apply least_upper_bound_correct_l\n           | _ => apply least_upper_bound_correct_r\n           | _ => congruence\n           | [ H : _ |- _ ] => setoid_rewrite PositiveMapExtensions.map2_1bis_for_rewrite in H; [ | reflexivity.. ]\n           end.\n  Qed.\n\n  Lemma find_aggregate_state_lub a b k\n    : PositiveMap.find k (aggregate_state_lub a b)\n      = aggregate_state_lub_f (PositiveMap.find k a) (PositiveMap.find k b).\n  Proof.\n    unfold aggregate_state_lub.\n    fold_andb_t.\n  Qed.\n\n  Lemma nothing_empty_lt v : ~aggregate_state_lt (PositiveMap.empty _) v.\n  Proof.\n    setoid_rewrite PositiveMapExtensions.empty_ltb_nothing; [ congruence | ].\n    setoid_rewrite state_ge_top_eq_top.\n    intros; symmetry; assumption.\n  Qed.\n\n  Lemma aggregate_state_lt_wf : well_founded (Basics.flip aggregate_state_lt).\n  Proof.\n    apply PositiveMapExtensions.well_founded_lift_gtb.\n    { eapply Wf.well_founded_subrelation; [ | eexact (@state_gt_wf _ gdata) ].\n      unfold flip, state_le; intros x y H.\n      destruct (y < x); [ reflexivity | simpl in * ].\n      destruct (y =b x) eqn:Heqb; simpl in *; assumption. }\n    { apply top_top. }\n    { exact _. }\n    { exact _. }\n    { exact _. }\n    { exact _. }\n  Defined.\n\n  Section wrap_wf.\n    Context {A R} (Rwf : @well_founded A R).\n\n    Definition lt_wf_idx_step\n               (lt_wf_idx : nat -> well_founded R)\n               (n : nat)\n      : well_founded R.\n    Proof.\n      destruct n.\n      { clear -Rwf; abstract apply Rwf. }\n      { constructor; intros; apply lt_wf_idx; assumption. }\n    Defined.\n\n    Fixpoint lt_wf_idx (n : nat) : well_founded R\n      := lt_wf_idx_step (@lt_wf_idx) n.\n  End wrap_wf.\n\n  Definition aggregate_state_lt_wf_idx (n : nat) : well_founded (Basics.flip aggregate_state_lt)\n    := lt_wf_idx aggregate_state_lt_wf n.\n\n  Definition step_lt {st}\n    : aggregate_state_eq st (aggregate_step st) = false -> Basics.flip aggregate_state_lt (aggregate_step st) st.\n  Proof.\n    unfold Basics.flip.\n    intros pf.\n    destruct (aggregate_state_lt st (aggregate_step st)) eqn:H; [ reflexivity | exfalso ].\n    unfold aggregate_step in *.\n    pose proof (proj1 (aggregate_state_lub_correct st (aggregate_prestep st))) as H'.\n    unfold aggregate_state_lt, PositiveMapExtensions.lift_ltb in *.\n    fold aggregate_state_le in *.\n    fold aggregate_state_eq in *.\n    generalize dependent (aggregate_state_le st (aggregate_state_lub st (aggregate_prestep st))).\n    generalize dependent (aggregate_state_eq st (aggregate_state_lub st (aggregate_prestep st))).\n    clear.\n    abstract (\n        intros [] ? []; simpl; intros; congruence\n      ).\n  Defined.\n\n  Global Instance aggregate_state_lub_Proper\n    : Proper (aggregate_state_eq ==> aggregate_state_eq ==> aggregate_state_eq) aggregate_state_lub | 1.\n  Proof.\n    unfold aggregate_state_eq, aggregate_state_lub, aggregate_state_lub_f.\n    refine PositiveMapExtensions.map2_defaulted_Proper_lift_brelation.\n  Qed.\n\n  Global Instance from_aggregate_state_Proper\n    : Proper (aggregate_state_eq ==> eq ==> state_beq) from_aggregate_state | 1.\n  Proof.\n    unfold aggregate_state_eq, PositiveMapExtensions.lift_eqb, from_aggregate_state, PositiveMapExtensions.find_default, option_rect; repeat intro; fold_andb_t.\n  Qed.\n\n  Global Instance aggregate_step_Proper\n    : Proper (aggregate_state_eq ==> aggregate_state_eq) aggregate_step | 1.\n  Proof.\n    intros x y H.\n    assert (H' : pointwise_relation _ state_beq (from_aggregate_state x) (from_aggregate_state y)) by (intro; setoid_rewrite H; reflexivity).\n    unfold aggregate_state_eq, PositiveMapExtensions.lift_eqb, aggregate_step, aggregate_state_lub, aggregate_prestep in *.\n    setoid_rewrite PositiveMapExtensions.lift_brelation_iff in H.\n    setoid_rewrite PositiveMapExtensions.lift_brelation_iff.\n    repeat setoid_rewrite fold_option_rect_nodep.\n    first [ setoid_rewrite (PositiveMapExtensions.map2_1bis_for_rewrite _ _ _ _ eq_refl)\n          | setoid_rewrite (PositiveMapExtensions.map2_1bis_for_rewrite _ _ _ _ _); [ | reflexivity.. ] ].\n    setoid_rewrite PositiveMap.gmapi.\n    unfold option_rect_nodep, option_map.\n    intro k; specialize (H k).\n    generalize dependent (lookup_state x); generalize dependent (lookup_state y); intros;\n      do 2 edestruct PositiveMap.find;\n      fold_andb_t.\n  Qed.\n\n  Lemma lookup_state_aggregate_state_lub a b nt\n    : lookup_state (aggregate_state_lub a b) nt = (lookup_state a nt ⊔ lookup_state b nt).\n  Proof.\n    unfold lookup_state, PositiveMapExtensions.find_default.\n    rewrite find_aggregate_state_lub.\n    unfold option_rect, aggregate_state_lub_f.\n    fold_andb_t.\n  Qed.\n\n  Global Instance lookup_state_Proper\n    : Proper (aggregate_state_eq ==> eq ==> state_beq) lookup_state | 1.\n  Proof.\n    unfold aggregate_state_eq, PositiveMapExtensions.lift_eqb, lookup_state, PositiveMapExtensions.find_default, option_rect; repeat intro; fold_andb_t.\n  Qed.\n\n  Lemma find_aggregate_prestep st nt\n    : PositiveMap.find nt (aggregate_prestep st)\n      = option_map (step_constraints gdata (lookup_state st) (positive_to_nonterminal nt))\n                   (PositiveMap.find nt st).\n  Proof.\n    unfold aggregate_prestep.\n    autorewrite with aggregate_step_db.\n    unfold from_aggregate_state, option_rect, option_map.\n    edestruct PositiveMap.find; reflexivity.\n  Qed.\n\n  Lemma find_aggregate_step st nt\n    : PositiveMap.find nt (aggregate_step st)\n      = option_map (fun v => v ⊔ step_constraints gdata (lookup_state st) (positive_to_nonterminal nt) v)\n                   (PositiveMap.find nt st).\n  Proof.\n    unfold aggregate_step.\n    rewrite find_aggregate_state_lub, find_aggregate_prestep.\n    edestruct PositiveMap.find; reflexivity.\n  Qed.\n\n  Lemma lookup_state_aggregate_prestep st nt\n    : lookup_state (aggregate_prestep st) nt\n      = option_rect (fun _ => _)\n                    (fun _ => step_constraints gdata (lookup_state st) nt (lookup_state st nt))\n                    default_value\n                    (PositiveMap.find (nonterminal_to_positive nt) st).\n  Proof.\n    unfold lookup_state.\n    unfold PositiveMapExtensions.find_default.\n    rewrite find_aggregate_prestep.\n    unfold lookup_state.\n    rewrite nonterminal_to_positive_to_nonterminal.\n    unfold PositiveMapExtensions.find_default.\n    unfold state in *; simpl in *.\n    edestruct PositiveMap.find; reflexivity.\n  Qed.\n\n  Lemma lookup_state_aggregate_step st nt\n    : lookup_state (aggregate_step st) nt\n      = option_rect (fun _ => _)\n                    (fun s => s ⊔ step_constraints gdata (lookup_state st) nt (lookup_state st nt))\n                    default_value\n                    (PositiveMap.find (nonterminal_to_positive nt) st).\n  Proof.\n    unfold lookup_state, PositiveMapExtensions.find_default.\n    rewrite find_aggregate_step.\n    unfold lookup_state, PositiveMapExtensions.find_default.\n    rewrite nonterminal_to_positive_to_nonterminal.\n    unfold state in *; simpl in *.\n    edestruct PositiveMap.find; reflexivity.\n  Qed.\n\n  Section with_initial.\n    Context (initial_nonterminals_data : list default_nonterminal_carrierT).\n\n    Definition aggregate_state_max : aggregate_state\n      := List.fold_right\n           (fun nt st => PositiveMap.add (nonterminal_to_positive nt) ⊥ st)\n           (PositiveMap.empty _)\n           initial_nonterminals_data.\n\n    Definition pre_Fix_grammar_helper : aggregate_state -> aggregate_state\n      := Fix\n           (aggregate_state_lt_wf_idx (10 * List.length initial_nonterminals_data))\n           (fun _ => aggregate_state)\n           (fun st Fix_grammar_internal\n            => let st' := aggregate_step st in\n               match Sumbool.sumbool_of_bool (aggregate_state_eq st st') with\n               | left pf => st\n               | right pf => Fix_grammar_internal st' (step_lt pf)\n               end).\n\n    Definition pre_Fix_grammar : aggregate_state\n      := pre_Fix_grammar_helper aggregate_state_max.\n\n    Lemma pre_Fix_grammar_helper_fixed st (H : aggregate_state_eq st (aggregate_step st))\n      : aggregate_state_eq st (pre_Fix_grammar_helper st).\n    Proof.\n      unfold pre_Fix_grammar_helper.\n      rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n      edestruct dec; [ | congruence ].\n      reflexivity.\n    Qed.\n\n    Lemma pre_Fix_grammar_helper_commute v\n      : aggregate_state_eq (pre_Fix_grammar_helper (aggregate_step v))\n                           (aggregate_step (pre_Fix_grammar_helper v)).\n    Proof.\n      unfold pre_Fix_grammar_helper.\n      induction (aggregate_state_lt_wf v) as [v H IHv].\n      rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial);\n        symmetry;\n        rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial);\n        symmetry.\n      do 2 edestruct dec; try reflexivity;\n        repeat match goal with\n               | [ H : ?x = true |- _ ] => change (is_true x) in H\n               end.\n      { fold @pre_Fix_grammar_helper in *.\n        rewrite <- pre_Fix_grammar_helper_fixed by assumption.\n        assumption. }\n      { match goal with\n        | [ H : is_true (aggregate_state_eq ?x ?y), H' : context[?x] |- _ ]\n          => rewrite <- H in H'\n        end.\n        congruence. }\n      { apply IHv.\n        apply step_lt; assumption. }\n    Qed.\n\n    Global Instance aggregate_state_eq_Proper_eq\n      : Proper (eq ==> eq ==> eq) aggregate_state_eq\n      := _.\n    Global Instance aggregate_step_Proper_eq\n      : Proper (eq ==> eq) aggregate_step\n      := _.\n\n    Lemma pre_Fix_grammar_fixedpoint\n      : aggregate_state_eq pre_Fix_grammar (aggregate_step pre_Fix_grammar).\n    Proof.\n      unfold pre_Fix_grammar, pre_Fix_grammar_helper.\n      generalize aggregate_state_max; intro a.\n      rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n      edestruct dec as [pf|pf].\n      { rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n        edestruct dec; [ | congruence ].\n        assumption. }\n      { induction (aggregate_state_lt_wf a) as [?? IH].\n        rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n        symmetry;\n          rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial);\n          symmetry.\n        rewrite pf; simpl.\n        edestruct dec as [pf'|pf'].\n        { rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n          rewrite pf'; simpl.\n          assumption. }\n        { apply IH; try assumption; []; clear IH.\n          unfold Basics.flip, aggregate_state_lt, PositiveMapExtensions.lift_ltb.\n          setoid_rewrite pf; simpl; rewrite andb_true_r.\n          pose proof (fun x => aggregate_state_lub_correct x (aggregate_prestep x)) as H'.\n          unfold aggregate_step in *.\n          edestruct H'; eassumption. } }\n    Qed.\n\n    Lemma find_aggregate_state_max_rdp_spec k v\n      : PositiveMap.find k aggregate_state_max = Some v\n        <-> (v = ⊥ /\\ rdp_list_is_valid_nonterminal initial_nonterminals_data (positive_to_nonterminal k)).\n    Proof.\n      unfold aggregate_state_max in *.\n      generalize dependent initial_nonterminals_data; intros ls.\n      induction ls as [|x xs IHxs].\n      { simpl in *.\n        autorewrite with aggregate_step_db in *.\n        intuition (tauto || congruence || eauto). }\n      { simpl in *.\n        autorewrite with aggregate_step_db in *.\n        edestruct PositiveMap.E.eq_dec; subst;\n          autorewrite with aggregate_step_db in *;\n          auto using eq_refl with nocore.\n        { repeat intuition (congruence || subst || eauto). }\n        { intuition (congruence || subst || eauto).\n          { apply orb_true_iff; intuition. }\n          { do 2 match goal with\n                 | [ H : is_true (orb _ _) |- _ ] => apply orb_true_iff in H\n                 | [ H : _ |- _ ] => setoid_rewrite beq_nat_true_iff in H\n                 end.\n            repeat intuition (congruence || subst || (autorewrite with aggregate_step_db in * ) || eauto). } } }\n    Qed.\n\n    Lemma find_aggregate_state_max k v\n      : PositiveMap.find k aggregate_state_max = Some v\n        -> PositiveMap.find k aggregate_state_max = Some ⊥.\n    Proof.\n      setoid_rewrite find_aggregate_state_max_rdp_spec.\n      tauto.\n    Qed.\n\n    Lemma find_aggregate_state_max_exact k\n      : PositiveMap.find k aggregate_state_max\n        = if rdp_list_is_valid_nonterminal initial_nonterminals_data (positive_to_nonterminal k)\n          then Some ⊥\n          else None.\n    Proof.\n      pose proof (find_aggregate_state_max_rdp_spec k) as H;\n        unfold is_true in *; split_iff; break_match.\n      { intuition eauto. }\n      { edestruct PositiveMap.find; [ | reflexivity ].\n        specialize_all_ways; specialize_by (exact eq_refl).\n        intuition congruence. }\n    Qed.\n  End with_initial.\n\n  Section with_grammar.\n    Context (G : pregrammar' Char).\n\n    Let predata := @rdp_list_predata _ G.\n    Local Existing Instance predata.\n\n    Definition find_aggregate_state_max_spec k v\n      : PositiveMap.find k (aggregate_state_max initial_nonterminals_data) = Some v\n        <-> (v = ⊥ /\\ is_valid_nonterminal initial_nonterminals_data (positive_to_nonterminal k))\n      := find_aggregate_state_max_rdp_spec initial_nonterminals_data k v.\n\n    Hint Rewrite find_aggregate_state_max_spec : aggregate_step_db.\n\n    Lemma lookup_state_aggregate_state_max nt\n      : lookup_state (aggregate_state_max initial_nonterminals_data) nt\n        = if is_valid_nonterminal initial_nonterminals_data nt\n          then ⊥\n          else default_value.\n    Proof.\n      unfold lookup_state, PositiveMapExtensions.find_default, option_rect.\n      destruct (PositiveMap.find (nonterminal_to_positive nt) (aggregate_state_max (@initial_nonterminals_data _ predata))) eqn:H; [ | ];\n        setoid_rewrite H.\n      { simpl in *.\n        apply find_aggregate_state_max_spec in H.\n        rewrite nonterminal_to_positive_to_nonterminal in H.\n        destruct H as [? H']; subst; simpl in *; rewrite H'; intuition. }\n      { match goal with |- context[if ?e then _ else _] => destruct e eqn:H' end;\n        [ | reflexivity ].\n        pose proof (find_aggregate_state_max_spec (nonterminal_to_positive nt) ⊥) as H''.\n        rewrite nonterminal_to_positive_to_nonterminal, H' in H''.\n        destruct H'' as [_ H''].\n        rewrite H'' in H by intuition.\n        congruence. }\n    Qed.\n\n    Lemma find_pre_Fix_grammar (nt : default_nonterminal_carrierT)\n      : is_valid_nonterminal initial_nonterminals_data nt\n        <-> PositiveMap.find (nonterminal_to_positive nt) (pre_Fix_grammar initial_nonterminals_data) <> None.\n    Proof.\n      unfold pre_Fix_grammar, pre_Fix_grammar_helper.\n      assert (H : PositiveMap.find (nonterminal_to_positive nt) (aggregate_state_max initial_nonterminals_data) <> None\n                  <-> is_valid_nonterminal initial_nonterminals_data nt).\n      { pose proof (find_aggregate_state_max_spec (nonterminal_to_positive nt)) as H.\n        rewrite nonterminal_to_positive_to_nonterminal in H.\n        edestruct PositiveMap.find.\n        { edestruct H as [H0 H1]; clear H.\n          intuition congruence. }\n        { specialize (H ⊥).\n          intuition congruence. } }\n      rewrite <- H; clear H.\n      generalize dependent (aggregate_state_max initial_nonterminals_data); intro a; intros.\n      induction (aggregate_state_lt_wf a) as [?? IH].\n      rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n      edestruct dec as [pf|pf]; [ reflexivity | ].\n      rewrite <- IH by (apply step_lt; assumption).\n      rewrite find_aggregate_step.\n      unfold option_map; split; fold_andb_t.\n    Qed.\n\n    Lemma find_pre_Fix_grammar_to_lookup_state (nt : default_nonterminal_carrierT)\n      : PositiveMap.find (nonterminal_to_positive nt) (pre_Fix_grammar initial_nonterminals_data)\n        = if is_valid_nonterminal initial_nonterminals_data nt\n          then Some (lookup_state (pre_Fix_grammar initial_nonterminals_data) nt)\n          else None.\n    Proof.\n      let v := match goal with |- context[if ?v then _ else _] => v end in\n      destruct v eqn:Hvalid.\n      { apply find_pre_Fix_grammar in Hvalid.\n        unfold lookup_state, PositiveMapExtensions.find_default, state in *; simpl in *.\n        edestruct PositiveMap.find;\n          [ reflexivity | congruence ]. }\n      { destruct (PositiveMap.find (nonterminal_to_positive nt) (pre_Fix_grammar (@initial_nonterminals_data _ predata))) eqn:H; [ | reflexivity ].\n        rewrite (proj2 (find_pre_Fix_grammar _)) in Hvalid; congruence. }\n    Qed.\n\n    Lemma find_pre_Fix_grammar_to_lookup_state' nt\n      : PositiveMap.find nt (pre_Fix_grammar initial_nonterminals_data)\n        = if is_valid_nonterminal initial_nonterminals_data (positive_to_nonterminal nt)\n          then Some (lookup_state (pre_Fix_grammar initial_nonterminals_data) (positive_to_nonterminal nt))\n          else None.\n    Proof.\n      rewrite <- find_pre_Fix_grammar_to_lookup_state, positive_to_nonterminal_to_positive.\n      reflexivity.\n    Qed.\n\n    Lemma lookup_state_invalid_pre_Fix_grammar (nt : default_nonterminal_carrierT)\n          (Hinvalid : is_valid_nonterminal initial_nonterminals_data nt = false)\n      : lookup_state (pre_Fix_grammar initial_nonterminals_data) nt = default_value.\n    Proof.\n      unfold lookup_state, PositiveMapExtensions.find_default.\n      pose proof (find_pre_Fix_grammar nt).\n      rewrite Hinvalid in H; destruct H.\n      unfold state in *; simpl in *.\n      edestruct PositiveMap.find.\n      { intuition congruence. }\n      { reflexivity. }\n    Qed.\n  End with_grammar.\nEnd grammar_fixedpoint.\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/Parsers/ContextFreeGrammar/Fix/Fix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.3812195592260441, "lm_q1q2_score": 0.24965868508034778}}
{"text": "(* This file is generated by Why3's Coq 8.4 driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\nRequire list.List.\nRequire list.Length.\nRequire list.Mem.\nRequire map.Map.\nRequire list.Nth.\nRequire option.Option.\nRequire list.NthLength.\nRequire list.Append.\nRequire list.NthLengthAppend.\n\n(* Why3 assumption *)\nDefinition unit := unit.\n\n(* Why3 assumption *)\nInductive array\n  (a:Type) {a_WT:WhyType a} :=\n  | mk_array : Z -> (@map.Map.map Z _ a a_WT) -> array a.\nAxiom array_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (array a).\nExisting Instance array_WhyType.\nImplicit Arguments mk_array [[a] [a_WT]].\n\n(* Why3 assumption *)\nDefinition elts {a:Type} {a_WT:WhyType a} (v:(@array a a_WT)): (@map.Map.map\n  Z _ a a_WT) := match v with\n  | (mk_array x x1) => x1\n  end.\n\n(* Why3 assumption *)\nDefinition length {a:Type} {a_WT:WhyType a} (v:(@array a a_WT)): Z :=\n  match v with\n  | (mk_array x x1) => x\n  end.\n\n(* Why3 assumption *)\nDefinition get {a:Type} {a_WT:WhyType a} (a1:(@array a a_WT)) (i:Z): a :=\n  (map.Map.get (elts a1) i).\n\n(* Why3 assumption *)\nDefinition set {a:Type} {a_WT:WhyType a} (a1:(@array a a_WT)) (i:Z)\n  (v:a): (@array a a_WT) := (mk_array (length a1) (map.Map.set (elts a1) i\n  v)).\n\n(* Why3 assumption *)\nDefinition make {a:Type} {a_WT:WhyType a} (n:Z) (v:a): (@array a a_WT) :=\n  (mk_array n (map.Map.const v:(@map.Map.map Z _ a a_WT))).\n\n(* Why3 assumption *)\nInductive buffer\n  (a:Type) {a_WT:WhyType a} :=\n  | mk_buffer : Z -> Z -> (@array a a_WT) -> (list a) -> buffer a.\nAxiom buffer_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (buffer a).\nExisting Instance buffer_WhyType.\nImplicit Arguments mk_buffer [[a] [a_WT]].\n\n(* Why3 assumption *)\nDefinition sequence {a:Type} {a_WT:WhyType a} (v:(@buffer\n  a a_WT)): (list a) := match v with\n  | (mk_buffer x x1 x2 x3) => x3\n  end.\n\n(* Why3 assumption *)\nDefinition data {a:Type} {a_WT:WhyType a} (v:(@buffer a a_WT)): (@array\n  a a_WT) := match v with\n  | (mk_buffer x x1 x2 x3) => x2\n  end.\n\n(* Why3 assumption *)\nDefinition len {a:Type} {a_WT:WhyType a} (v:(@buffer a a_WT)): Z :=\n  match v with\n  | (mk_buffer x x1 x2 x3) => x1\n  end.\n\n(* Why3 assumption *)\nDefinition first {a:Type} {a_WT:WhyType a} (v:(@buffer a a_WT)): Z :=\n  match v with\n  | (mk_buffer x x1 x2 x3) => x\n  end.\n\n(* Why3 assumption *)\nDefinition size {a:Type} {a_WT:WhyType a} (b:(@buffer a a_WT)): Z :=\n  (length (data b)).\n\nRequire Import Why3. Ltac ae := why3 \"alt-ergo\" timelimit 3.\n\n(* Why3 goal *)\nTheorem WP_parameter_pop : forall {a:Type} {a_WT:WhyType a}, forall (b:Z)\n  (b1:Z) (b2:Z) (b3:(@map.Map.map Z _ a a_WT)) (b4:(list a)),\n  (((((0%Z <= b)%Z /\\ (b < b2)%Z) /\\ (((0%Z <= b1)%Z /\\ (b1 <= b2)%Z) /\\\n  ((b1 = (list.Length.length b4)) /\\ forall (i:Z), ((0%Z <= i)%Z /\\\n  (i < b1)%Z) -> ((((b + i)%Z < b2)%Z -> ((list.Nth.nth i\n  b4) = (Some (map.Map.get b3 (b + i)%Z)))) /\\\n  ((0%Z <= ((b + i)%Z - b2)%Z)%Z -> ((list.Nth.nth i\n  b4) = (Some (map.Map.get b3 ((b + i)%Z - b2)%Z)))))))) /\\ (0%Z <= b2)%Z) /\\\n  (0%Z < b1)%Z) ->\n  match b4 with\n  | nil => True\n  | (cons _ s) => forall (rho:(list a)), (rho = s) -> (((0%Z <= b)%Z /\\\n      (b < b2)%Z) -> forall (rho1:Z), (rho1 = (b1 - 1%Z)%Z) ->\n      forall (rho2:Z), (rho2 = (b + 1%Z)%Z) -> ((rho2 = b2) ->\n      forall (rho3:Z), (rho3 = 0%Z) -> ((((0%Z <= rho3)%Z /\\\n      (rho3 < b2)%Z) /\\ (((0%Z <= rho1)%Z /\\ (rho1 <= b2)%Z) /\\\n      ((rho1 = (list.Length.length rho)) /\\ forall (i:Z), ((0%Z <= i)%Z /\\\n      (i < rho1)%Z) -> ((((rho3 + i)%Z < b2)%Z -> ((list.Nth.nth i\n      rho) = (Some (map.Map.get b3 (rho3 + i)%Z)))) /\\\n      ((0%Z <= ((rho3 + i)%Z - b2)%Z)%Z -> ((list.Nth.nth i\n      rho) = (Some (map.Map.get b3 ((rho3 + i)%Z - b2)%Z)))))))) ->\n      match b4 with\n      | nil => True\n      | (cons x l) => ((map.Map.get b3 b) = x)\n      end)))\n  end.\n(* Why3 intros a a_WT b b1 b2 b3 b4 ((((h1,h2),((h3,h4),(h5,h6))),h7),h8). *)\nunfold get; simpl.\nintros a _a b rho rho1 rho2 rho3.\nintros ((((h1,h2),(h3,(h4,h5))),_),h6).\ndestruct rho3; auto.\nintros; subst.\nintuition.\ngeneralize (h5 (0%Z)).\nae.\nQed.\n\n\n", "meta": {"author": "kit-ty-kate", "repo": "why3", "sha": "553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3", "save_path": "github-repos/coq/kit-ty-kate-why3", "path": "github-repos/coq/kit-ty-kate-why3/why3-553cbabbffeb8116d9e7a3b4e95d2a2a5f9332f3/examples/vstte12_ring_buffer/vstte12_ring_buffer_2_RingBuffer_WP_parameter_pop_4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.24961891798924274}}
{"text": "Require Import Thread Arrays8 MoreArrays.\n\nLocal Hint Extern 1 (@eq W _ _) => words.\n\n\nModule Type S.\n  Variables globalSched globalSock : W.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nModule M'''.\n  Definition globalSched := M.globalSched.\n\n  Open Scope Sep_scope.\n\n  Definition globalInv (fs : files) : HProp := Ex fr, globalSock =*> fr * [| fr %in fs |].\nEnd M'''.\n\nLtac unf := unfold M'''.globalSched, M'''.globalInv in *.\n\nModule T := Thread.Make(M''').\n\nImport T M'''.\nExport T M'''.\n\nDefinition hints : TacPackage.\n  prepare (materialize_buffer, buffer_split_tagged) buffer_join_tagged.\nDefined.\n\nLtac sep := T.sep unf hints.\n\nDefinition handlerS := SPEC reserving 49\n  Al fs, PREmain[_] sched fs * globalInv fs * mallocHeap 0.\n\nDefinition mainS := SPEC reserving 49\n  PREmain[_] globalSched =?> 1 * globalSock =?> 1 * mallocHeap 0.\n\nDefinition writeSomeS := SPEC(\"fr\", \"buf\", \"len\") reserving 36\n  Al fs, Al len,\n  PRE[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 len * [| (wordToNat (V \"len\") <= len)%nat |]\n    * sched fs * globalInv fs * mallocHeap 0\n  POST[_] Ex fs', [| fs %<= fs' |] * V \"buf\" =?>8 len * sched fs' * globalInv fs' * mallocHeap 0.\n\nDefinition m := bimport [[ \"malloc\"!\"malloc\" @ [mallocS],\n                           \"scheduler\"!\"init\" @ [initS], \"scheduler\"!\"exit\" @ [exitS],\n                           \"scheduler\"!\"spawn\" @ [spawnS], \"scheduler\"!\"listen\" @ [listenS],\n                           \"scheduler\"!\"accept\" @ [acceptS], \"scheduler\"!\"read\" @ [readS],\n                           \"scheduler\"!\"write\" @ [writeS], \"scheduler\"!\"close\" @ [closeS] ]]\n  bmodule \"test\" {{\n    bfunction \"writeSome\"(\"fr\", \"buf\", \"len\") [writeSomeS]\n      Assert [Al fs, Al len,\n        PRE[V] [| V \"fr\" %in fs |] * buffer_splitAt (wordToNat (V \"len\")) (V \"buf\") len\n          * [| (wordToNat (V \"len\") <= len)%nat |] * sched fs * globalInv fs * mallocHeap 0\n        POST[_] Ex fs', [| fs %<= fs' |] * buffer_joinAt (wordToNat (V \"len\")) (V \"buf\") len\n          * sched fs' * globalInv fs' * mallocHeap 0];;\n\n      Call \"scheduler\"!\"write\"(\"fr\", \"buf\", \"len\")\n      [PRE[_] Emp POST[_] Emp];;\n      Return 0\n    end with bfunctionNoRet \"handler\"(\"buf\", \"fr\", \"n\") [handlerS]\n      \"buf\" <-- Call \"malloc\"!\"malloc\"(0, 10)\n      [Al fs, PREmain[_, R] R =?> 10 * sched fs * globalInv fs * mallocHeap 0];;\n\n      Note [please_materialize_buffer 10];;\n\n      [Al fs, PREmain[V] V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0]\n      While (0 = 0) {\n        \"fr\" <-- Call \"scheduler\"!\"accept\"($[globalSock])\n        [Al fs, PREmain[V, R] [| R %in fs |] * V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0];;\n\n        \"n\" <-- Call \"scheduler\"!\"read\"(\"fr\", \"buf\", 40)\n        [Al fs, PREmain[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0];;\n\n        [Al fs, PREmain[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0]\n        While (\"n\" <> 0) {\n          If (\"n\" <= 40) {\n            Call \"test\"!\"writeSome\"(\"fr\", \"buf\", \"n\")\n            [Al fs, PREmain[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0]\n          } else {\n            Skip\n          };;\n\n          \"n\" <-- Call \"scheduler\"!\"read\"(\"fr\", \"buf\", 40)\n          [Al fs, PREmain[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0]\n        };;\n\n        Call \"scheduler\"!\"close\"(\"fr\")\n        [Al fs, PREmain[V] V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0]\n      }\n    end with bfunctionNoRet \"main\"(\"fr\", \"x\") [mainS]\n      Init\n      [Al fs, Al v, PREmain[_] sched fs * globalSock =*> v * mallocHeap 0];;\n\n      \"fr\" <-- Call \"scheduler\"!\"listen\"(8080%N)\n      [Al fs, Al v, PREmain[_, R] [| R %in fs |] * sched fs * globalSock =*> v * mallocHeap 0];;\n\n      globalSock *<- \"fr\";;\n\n      Spawn(\"test\"!\"handler\", 50)\n      [Al fs, PREmain[_] sched fs * globalInv fs * mallocHeap 0];;\n\n      Spawn(\"test\"!\"handler\", 50)\n      [Al fs, PREmain[_] sched fs * globalInv fs * mallocHeap 0];;\n\n      Exit 50\n    end\n  }}.\n\nOpaque allocated.\n\nLemma single_cell : forall p,\n  (p =?> 1 = (Ex v, p =*> v) * Emp)%Sep.\n  auto.\nQed.\n\nLemma le_40 : forall w : W,\n  w <= natToW 40\n  -> (wordToNat w <= 40)%nat.\n  intros; pre_nomega.\n  rewrite wordToNat_natToWord_idempotent in * by reflexivity; omega.\nQed.\n\nHint Immediate le_40.\n\nLtac t' := try rewrite (single_cell globalSock); sep; auto.\nLtac t := solve [ t'\n  | post; evaluate hints; descend; try match_locals; t' ].\n\nTheorem ok : moduleOk m.\n  vcgen; abstract t.\nQed.\n\nEnd Make.\n", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/tests/Echo3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24956931203338628}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\nRequire Import Setoid.\nRequire Import ZArith.\nRequire Import Psatz.\n\n\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith. \n\nLocal Open Scope struct_scope.\n\nRequire Import FinProof.CommonProofs.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolClass.\nRequire Import depoolContract.SolidityNotations.\n\nRequire Import depoolContract.NewProofs.ProofHelpers.\nRequire Import depoolContract.DePoolFunc.\n\n(* Set Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100. *)\n\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\nRequire Import depoolContract.Lib.CommonCommon.\n\n(* Require Import MultiSigWallet.Proofs.tvmFunctionsProofs. *)\n\nImport DePoolSpec.LedgerClass.SolidityNotations. \n\nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope solidity_scope.\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\n\nRequire Import depoolContract.DePoolConsts.\nModule ConfigParamsBaseProofs (dc : DePoolConstsTypesSig XTypesSig StateMonadSig).\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig dc.\nModule ProofHelpers := ProofHelpers dc.\n\nImport dc.\nImport ProofHelpers.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\n\n(* ConfigParamsBase_Ф_getCurValidatorData *)\n\nLemma ConfigParamsBase_Ф_getCurValidatorData_exec : forall (l: Ledger), \n    exec_state ( ↓ ConfigParamsBase_Ф_getCurValidatorData ) l = l. \nProof. \n  intros. destruct l. compute. auto.\nQed. \n\n Lemma ConfigParamsBase_Ф_getCurValidatorData_eval : forall (l: Ledger) ,\n let (Л_cell, Л_ok) := eval_state (tvm_rawConfigParam_34) l in\n let hash := tvm_hash Л_cell in \n let sliceRaw := toSlice Л_cell in\n let res := decode_uint8_uint32_uint32 sliceRaw in\n\n eval_state ( ↓ ConfigParamsBase_Ф_getCurValidatorData ) l =\n  if Л_ok then Value (hash , snd (fst (fst res)) , snd (fst res))\n          else Error InternalErrors_ι_ERROR508.\n Proof. \n   intros. destruct l. compute.  auto. \n Qed. \n\nAxiom tvm_rawConfigParam_34_evalAx: forall  (l: Ledger) ,\nlet (raw34, b) := eval_state (tvm_rawConfigParam_34) l in \nlet unknown34 := eval_state (↑16 ε VMState_ι_unknown34) l in\nlet utime_since := eval_state (↑16 ε VMState_ι_utime_since ) l in\nlet utime_until := eval_state (↑16 ε VMState_ι_utime_until ) l in \nfst (decode_uint8_uint32_uint32 (toSlice raw34)) = (unknown34, utime_since, utime_until).\n\n\n Lemma ConfigParamsBase_Ф_getCurValidatorData_eval2 : forall (l: Ledger) ,\n(*  let (_, Л_ok) := eval_state (tvm_rawConfigParam_34) l in *)\n let сurValidatorDataCell := eval_state (↑16 ε VMState_ι_curValidatorData) l in\n let utime_since := eval_state (↑16 ε VMState_ι_utime_since ) l in\n let utime_until := eval_state (↑16 ε VMState_ι_utime_until ) l in \n let hash := tvm_hash сurValidatorDataCell in \n let sliceRaw := toSlice сurValidatorDataCell in\n let res := decode_uint8_uint32_uint32 sliceRaw in\n\n  eval_state ( ↓ ConfigParamsBase_Ф_getCurValidatorData ) l =\n  (* if Л_ok then  *)Value (hash , utime_since , utime_until )\n         (*  else Error (eval_state ( ↑8 ε InternalErrors_ι_ERROR508) l) *).\n Proof.\n   intros.\n   remember (tvm_rawConfigParam_34_evalAx l) as A.\n   rewrite ConfigParamsBase_Ф_getCurValidatorData_eval.\n   destruct l.\n   destruct Ledger_ι_VMState.\n   compute. compute in A.\n   clear HeqA.\n   rewrite A.\n   auto. \n Qed.\n \n\n(* ConfigParamsBase_Ф_getPrevValidatorHash *) \n \nLemma ConfigParamsBase_Ф_getPrevValidatorHash_exec : forall (l: Ledger) , \n \t exec_state ( ↓ ConfigParamsBase_Ф_getPrevValidatorHash ) l = l .  \n Proof. \n   intros. destruct l. auto. \n Qed. \n \nLemma ConfigParamsBase_Ф_getPrevValidatorHash_eval : forall (l: Ledger)  ,\nlet (_, Л_ok) := eval_state tvm_rawConfigParam_32 l in\nlet Л_cell := eval_state (↑ε16 VMState_ι_prevValidatorData) l in\nlet hash := tvm_hash Л_cell in\n\n    eval_state ( ↓ ConfigParamsBase_Ф_getPrevValidatorHash ) l = \n    if Л_ok then Value hash\n            else Error InternalErrors_ι_ERROR507 .\n Proof. \n   intros. compute. auto.\n Qed. \n\nLemma ConfigParamsBase_Ф_getPrevValidatorHash_eval2 : forall (l: Ledger)  ,\n(* let (_, Л_ok) := eval_state tvm_rawConfigParam_32 l in *)\nlet Л_cell := eval_state (↑ε16 VMState_ι_prevValidatorData) l in\nlet hash := tvm_hash Л_cell in\n\n    eval_state ( ↓ ConfigParamsBase_Ф_getPrevValidatorHash ) l = \n    (* if Л_ok then  *)Value hash\n            (* else Error InternalErrors_ι_ERROR507 *) .\n Proof. \n   intros. compute. auto.\n Qed. \n\n\n (* ConfigParamsBase_Ф_roundTimeParams *)\n\n Lemma ConfigParamsBase_Ф_roundTimeParams_exec : forall (l: Ledger) , \n \t exec_state (↓ ConfigParamsBase_Ф_roundTimeParams ) l = l .  \n Proof. \n   intros. destruct l. auto. \n Qed. \n \nLemma ConfigParamsBase_Ф_roundTimeParams_eval : forall (l: Ledger) ,\nlet (_ , ок) := eval_state (tvm_configParam_15) l in\n\nlet validatorsElectedFor := eval_state (↑16 ε VMState_ι_validatorsElectedFor) l in\nlet electionsStartBefore := eval_state (↑16 ε VMState_ι_electionsStartBefore) l in\nlet electionsEndBefore := eval_state (↑16 ε VMState_ι_electionsEndBefore) l in\nlet stakeHeldFor := eval_state (↑16 ε VMState_ι_stakeHeldFor) l in\n\n   eval_state (↓ ConfigParamsBase_Ф_roundTimeParams) l = \n   if ок then Value (validatorsElectedFor, electionsStartBefore, electionsEndBefore, stakeHeldFor)\n         else Error InternalErrors_ι_ERROR509 . \n Proof. \n   intros. destruct l.  compute. auto.\n Qed.\n \n \nLemma ConfigParamsBase_Ф_roundTimeParams_eval2 : forall (l: Ledger) ,\n(* let (_ , ок) := eval_state (tvm_configParam_15) l in\n *)\nlet validatorsElectedFor := eval_state (↑16 ε VMState_ι_validatorsElectedFor) l in\nlet electionsStartBefore := eval_state (↑16 ε VMState_ι_electionsStartBefore) l in\nlet electionsEndBefore := eval_state (↑16 ε VMState_ι_electionsEndBefore) l in\nlet stakeHeldFor := eval_state (↑16 ε VMState_ι_stakeHeldFor) l in\n\n   eval_state (↓ ConfigParamsBase_Ф_roundTimeParams) l = \n   (* if ок then  *)Value (validatorsElectedFor, electionsStartBefore, electionsEndBefore, stakeHeldFor)\n         (* else Error InternalErrors_ι_ERROR509 *). \n Proof. \n   intros. destruct l.  compute. auto.\n Qed.\n\n\n (* ConfigParamsBase_Ф_getMaxStakeFactor *)\n\nLemma ConfigParamsBase_Ф_getMaxStakeFactor_exec : forall (l: Ledger) , \n  exec_state (↓ ConfigParamsBase_Ф_getMaxStakeFactor) l = l .  \nProof. \n  intros. destruct l. auto. \nQed. \n \nLemma ConfigParamsBase_Ф_getMaxStakeFactor_eval : forall (l: Ledger)  ,\nlet (Л_cell, Л_ok) := eval_state tvm_rawConfigParam_17 l in \nlet sliceRaw := toSlice Л_cell in\nlet t1 := tvm_loadTons (tvm_loadTons (tvm_loadTons sliceRaw)) in\nlet res := fst (decode_uint32 t1) in \n    eval_state (↓ ConfigParamsBase_Ф_getMaxStakeFactor ) l = \n    if Л_ok then Value res\n            else Error InternalErrors_ι_ERROR516 . \nProof. \n  intros. destruct l. \n  compute. auto.\nQed. \n\n(* VMState_ι_unknown17_1 : I8 ; (*check the type*)\n\t\tVMState_ι_unknown17_2 : I8 ; \n\t\tVMState_ι_unknown17_3 : I8 ; \n\t\tVMState_ι_maxStakeFactor : I32; *)\n\nAxiom tvm_rawConfigParam_17_evalAx: forall  (l: Ledger) ,\nlet (raw17, b) := eval_state tvm_rawConfigParam_17 l in \n(* let unknown17_1 := eval_state (↑16 ε VMState_ι_unknown17_1) l in\nlet unknown17_2 := eval_state (↑16 ε VMState_ι_unknown17_2 ) l in\nlet unknown17_3 := eval_state (↑16 ε VMState_ι_unknown17_3 ) l in  *)\nlet maxStakeFactor := eval_state (↑16 ε VMState_ι_maxStakeFactor ) l in \n\nfst (decode_uint32 (tvm_loadTons (tvm_loadTons (tvm_loadTons (toSlice raw17))))) = maxStakeFactor.\n\nLemma ConfigParamsBase_Ф_getMaxStakeFactor_eval2 : forall (l: Ledger)  ,\nlet maxStakeFactor := eval_state (↑16 ε VMState_ι_maxStakeFactor ) l in \n    eval_state (↓ ConfigParamsBase_Ф_getMaxStakeFactor ) l =  Value maxStakeFactor. \nProof. \n  intros.\n  remember (tvm_rawConfigParam_17_evalAx l) as A.\n  rewrite ConfigParamsBase_Ф_getMaxStakeFactor_eval.\n  destruct l.\n  destruct Ledger_ι_VMState.\n  compute. compute in A.\n  clear HeqA.\n  rewrite A.\n  auto. \nQed.\n\n\n(* ConfigParamsBase_Ф_getElector *)\n\n\nLemma ConfigParamsBase_Ф_getElector_exec : forall (l: Ledger) , \n  exec_state (↓ ConfigParamsBase_Ф_getElector) l = l .  \nProof. \n  intros. destruct l. auto. \nQed. \n \nLemma ConfigParamsBase_Ф_getElector_eval : forall (l: Ledger) ,\nlet (Л_cell, Л_ok) := eval_state (tvm_rawConfigParam_1) l in\nlet sliceRaw := toSlice Л_cell in      \nlet v := fst (decode_uint256 sliceRaw) in\nlet res := address_makeAddrStd (-1)%Z v in\n\neval_state (↓ ConfigParamsBase_Ф_getElector) l =\nif Л_ok then Value res\n        else Error InternalErrors_ι_ERROR517 .\nProof. \n  intros. destruct l.\n  compute. auto.\nQed. \n\nAxiom tvm_rawConfigParam_1_evalAx: forall  (l: Ledger) ,\nlet (raw1, b) := eval_state tvm_rawConfigParam_1 l in \nlet electorRawAddress := eval_state (↑16 ε VMState_ι_electorRawAddress ) l in \n\nfst (decode_uint256 (toSlice raw1)) = electorRawAddress.\n\nLemma ConfigParamsBase_Ф_getElector_eval2 : forall (l: Ledger) ,\nlet electorRawAddress := eval_state (↑16 ε VMState_ι_electorRawAddress ) l in \nlet res := address_makeAddrStd (-1)%Z electorRawAddress in\n  eval_state (↓ ConfigParamsBase_Ф_getElector) l = Value res.\nProof. \n  intros.\n  remember (tvm_rawConfigParam_1_evalAx l) as A.\n  rewrite ConfigParamsBase_Ф_getElector_eval.\n  destruct l.\n  destruct Ledger_ι_VMState.\n  compute. compute in A.\n  clear HeqA.\n  rewrite A.\n  auto. \nQed. \n\n \nEnd ConfigParamsBaseProofs.", "meta": {"author": "Pruvendo", "repo": "depool_contract", "sha": "6afe23011d62f65921ac2493df691ab888ffeb95", "save_path": "github-repos/coq/Pruvendo-depool_contract", "path": "github-repos/coq/Pruvendo-depool_contract/depool_contract-6afe23011d62f65921ac2493df691ab888ffeb95/src/NewProofs/ConfigParamsBaseProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2495693120333862}}
{"text": "Require Import Bool List String PeanoNat.\nRequire Import Common FMap Syntax.\n\nRequire Export MessagePool.\n\nSet Implicit Arguments.\n\nLocal Open Scope list.\nLocal Open Scope fmap.\n\nDefinition extRqsOf `{DecValue} `{OStateIfc}\n           (sys: System) (mp: MessagePool Msg) :=\n  qsOf (sys_merqs sys) mp.\n\nDefinition extRssOf `{DecValue} `{OStateIfc}\n           (sys: System) (mp: MessagePool Msg) :=\n  qsOf (sys_merss sys) mp.\n\nSection Validness.\n  Context `{DecValue} `{OStateIfc}.\n\n  (* A set of messages are \"well-distributed\" iff the sources of\n   * all messages are different from each others.\n   *)\n  Definition WellDistrMsgs (msgs: list (Id Msg)) :=\n    NoDup (idsOf msgs).\n\n  (* A set of messages are \"valid internal inputs\" iff\n   * 1) each source is internal and\n   * 2) they are well-distributed.\n   *)\n  Definition ValidMsgsIn (sys: System) (msgs: list (Id Msg)) :=\n    SubList (idsOf msgs) (sys_minds sys ++ sys_merqs sys) /\\\n    WellDistrMsgs msgs.\n\n  (* A set of messages are \"valid outputs\" iff\n   * 1) each message is using either an internal or\n   *    an external-response queue.\n   * 2) they are well-distributed.\n   *)\n  Definition ValidMsgsOut (sys: System) (msgs: list (Id Msg)) :=\n    SubList (idsOf msgs) (sys_minds sys ++ sys_merss sys) /\\\n    WellDistrMsgs msgs.\n\n  (* A set of messages are \"valid external inputs\" iff\n   * 1) each message uses an external request queue and\n   * 2) they are well-distributed.\n   *)\n  Definition ValidMsgsExtIn (sys: System) (msgs: list (Id Msg)) :=\n    SubList (idsOf msgs) (sys_merqs sys) /\\\n    WellDistrMsgs msgs.\n\n  (* A set of messages are \"valid external outputs\" iff\n   * 1) each message uses an external response queue and\n   * 2) they are well-distributed.\n   *)\n  Definition ValidMsgsExtOut (sys: System) (msgs: list (Id Msg)) :=\n    SubList (idsOf msgs) (sys_merss sys) /\\\n    WellDistrMsgs msgs.\n\nEnd Validness.\n\nSection HasLabel.\n  Context `{DecValue}.\n\n  Inductive Label :=\n  | LblIns (mins: list (Id Msg)): Label\n  | LblOuts (mouts: list (Id Msg)): Label.\n\n  Class HasLabel (LabelT: Type) :=\n    { getLabel: LabelT -> option Label }.\n\nEnd HasLabel.\n\nSection Transition.\n  Variables (SystemT StateT LabelT: Type).\n\n  Definition Step := SystemT -> StateT -> LabelT -> StateT -> Prop.\n  Definition Steps := SystemT -> StateT -> list LabelT -> StateT -> Prop.\n\n  (* NOTE: the head is the youngest *)\n  Inductive steps (step: Step) (sys: SystemT): StateT -> list LabelT -> StateT -> Prop :=\n  | StepsNil: forall st, steps step sys st nil st\n  | StepsCons:\n      forall st1 ll st2,\n        steps step sys st1 ll st2 ->\n        forall lbl st3,\n          step sys st2 lbl st3 ->\n          steps step sys st1 (lbl :: ll) st3.\n\n  Definition psteps (step: Step)\n             (P: StateT -> list LabelT -> StateT -> Prop)\n             (sys: SystemT) (st1: StateT) (ll: list LabelT) (st2: StateT) :=\n    steps step sys st1 ll st2 /\\\n    P st1 ll st2.\n\nEnd Transition.\n\nSection Behavior.\n\n  Section Labeled.\n    Context {LabelT} `{HasLabel LabelT}.\n\n    Definition Trace := list Label.\n\n    Definition Reachable {SystemT StateT} `{HasInit SystemT StateT}\n               (ss: Steps SystemT StateT LabelT) (sys: SystemT) (st: StateT): Prop :=\n      exists ll, ss sys (initsOf sys) ll st.\n\n    Fixpoint behaviorOf  (ll: list LabelT): Trace :=\n      match ll with\n      | nil => nil\n      | l :: ll' => (getLabel l) ::> (behaviorOf ll')\n      end.\n\n    Inductive Behavior {SystemT StateT} `{HasInit SystemT StateT}\n              (ss: Steps SystemT StateT LabelT) : SystemT -> Trace -> Prop :=\n    | Behv: forall sys ll st,\n        ss sys (initsOf sys) ll st ->\n        forall tr,\n          tr = behaviorOf ll ->\n          Behavior ss sys tr.\n\n  End Labeled.\n\n  Definition Refines `{dv: DecValue} {SystemI StateI LabelI SystemS StateS LabelS}\n             `{HasInit SystemI StateI} `{HasInit SystemS StateS}\n             `{@HasLabel dv LabelI} `{@HasLabel dv LabelS}\n             (ssI: Steps SystemI StateI LabelI) (ssS: Steps SystemS StateS LabelS)\n             (impl: SystemI) (spec: SystemS) :=\n    forall tr, Behavior ssI impl tr ->\n               Behavior ssS spec tr.\n\nEnd Behavior.\n\nNotation \"StI # StS |-- I <= S\" := (Refines StI StS I S) (at level 30).\nNotation \"StI # StS |-- I ⊑ S\" := (Refines StI StS I S) (at level 30).\n\n(** Some concrete state and label definitions *)\n\nRecord State `{DecValue} `{OStateIfc} :=\n  { st_oss: OStates;\n    st_orqs: ORqs Msg;\n    st_msgs: MessagePool Msg\n  }.\n\nDefinition getStateInit `{DecValue} `{OStateIfc} (sys: System): State :=\n  {| st_oss := initsOf sys;\n     st_orqs := initsOf sys;\n     st_msgs := emptyMP _ |}.\n\nGlobal Instance State_HasInit `{DecValue} `{OStateIfc}: HasInit System State :=\n  {| initsOf := getStateInit |}.\n\nDefinition GoodORqsInit `{DecValue} (iorqs: ORqs Msg): Prop :=\n  forall oidx,\n    iorqs@[oidx] >>=[True] (fun orq => orq = []).\n\nDefinition IntMsgsEmpty `{DecValue} `{OStateIfc}\n           (sys: System) (msgs: MessagePool Msg) :=\n  forall midx,\n    In midx sys.(sys_minds) ->\n    findQ midx msgs = nil.\n\n(* [RLabel] represents \"internal rule-driven labels\" that reveal which message\n * is being handled now.\n *)\nSection RLabel.\n  Context `{DecValue}.\n\n  Inductive RLabel :=\n  | RlblEmpty\n  | RlblIns (mins: list (Id Msg)): RLabel\n  | RlblInt (oidx ridx: IdxT) (mins: list (Id Msg)) (mouts: list (Id Msg)): RLabel\n  | RlblOuts (mouts: list (Id Msg)): RLabel.\n\n  Definition rToLabel (l: RLabel): option Label :=\n    match l with\n    | RlblEmpty => None\n    | RlblIns mins => Some (LblIns mins)\n    | RlblInt _ _ _ _ => None\n    | RlblOuts mouts => Some (LblOuts mouts)\n    end.\n\n  Global Instance RLabel_HasLabel: HasLabel RLabel :=\n    { getLabel := rToLabel }.\n\nEnd RLabel.\n\nDefinition History `{DecValue} := list RLabel.\n", "meta": {"author": "mit-plv", "repo": "hemiola", "sha": "1984b4de903259ce2d7abda737e76e16e6436dee", "save_path": "github-repos/coq/mit-plv-hemiola", "path": "github-repos/coq/mit-plv-hemiola/hemiola-1984b4de903259ce2d7abda737e76e16e6436dee/src/System/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24949488821839616}}
{"text": "(** * Parallelization of the Maximum Prefix Sum Application *)\n\nRequire Import SyDPaCC.Core.Bmf SyDPaCC.Core.Parallelization.\nRequire Import SyDPaCC.Applications.Count.\n\nRequire Import SyDPaCC.Bsml.Model.Core SyDPaCC.Bsml.Model.Pid \n        SyDPaCC.Bsml.DataStructures.DistributedList\n        SyDPaCC.Bsml.DataStructures.ReplicatedValue\n        SyDPaCC.Bsml.Skeletons.StdLib\n        SyDPaCC.Bsml.Skeletons.MapReduce.\n\nSet Implicit Arguments.\n\nOpen Scope sydpacc_scope.\n\nModule Make (Import Bsml: Core.BSML).\n\n  Module Pid       := Pid.Make Bsml.Bsp.\n  Module StdLib    := StdLib.Make Bsml Pid.\n  Module Import ParList   := DistributedList.C Bsml Pid.\n  Module Import ReplPar   := ReplicatedValue.C Bsml Pid.\n  Module Import MapReduce := MapReduce.Make Bsml Pid StdLib ParList ReplPar.\n\n  Section Count.\n\n    Variable A : Type.\n    Variable predicate : { pred: A -> bool & { a : A | pred a = true} }.\n\n    (** ** Version where the result is a scalar *)\n\n    Definition par_count_img : par(list A) -> img (count_spec predicate) :=\n      Eval sydpacc in \n        parallel (hom_to_map_reduce (count_spec predicate)).\n\n    Definition par_count : par(list A) -> nat :=\n      Eval sydpacc in\n        of_img ∘ par_count_img.\n\n    (** ** Version where the result is a parallel vector *)\n    Definition par_count_img' :=\n      Eval sydpacc in \n        parallel (hom_to_map_reduce (count_spec predicate)).\n\n    Definition par_count' : par(list A) -> par nat :=\n      Eval sydpacc in\n        (StdLib.parfun of_img) ∘ (@proj1_sig _ _) ∘ par_count_img'.   \n    \n  End Count.\n\nEnd Make.\n\nClose Scope sydpacc_scope.\n", "meta": {"author": "SyDPaCC", "repo": "sydpacc", "sha": "640f0f74f21524ee203b192255ecfa9e456fb7d1", "save_path": "github-repos/coq/SyDPaCC-sydpacc", "path": "github-repos/coq/SyDPaCC-sydpacc/sydpacc-640f0f74f21524ee203b192255ecfa9e456fb7d1/Bsml/Applications/BsmlCount.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24949488182165183}}
{"text": "Require Import Rupicola.Lib.Api.\nRequire Import Crypto.Bedrock.Specs.ScalarField.\nRequire Import Crypto.Arithmetic.PrimeFieldTheorems.\nLocal Open Scope Z_scope.\n\nSection Compile.\n  Context {semantics : Semantics.parameters}\n          {semantics_ok : Semantics.parameters_ok semantics}.\n  Context {scalar_field_parameters : ScalarFieldParameters}.\n  Context {scalar_representaton : ScalarRepresentation}.\n  Existing Instance spec_of_sctestbit.\n\n  Lemma compile_sctestbit :\n    forall (locals: Semantics.locals) (mem: Semantics.mem)\n           (locals_ok : Semantics.locals -> Prop)\n           tr retvars R R' functions\n           T (pred: T -> list word -> Semantics.mem -> Prop)\n      x x_ptr x_var i wi i_var k k_impl var,\n      spec_of_sctestbit functions ->\n      (Scalar x_ptr x * R')%sep mem ->\n      map.get locals x_var = Some x_ptr ->\n      map.get locals i_var = Some wi ->\n      word.unsigned wi = Z.of_nat i ->\n      let v := Z.testbit (F.to_Z (sceval x)) (Z.of_nat i) in\n      (let head := v in\n       forall m,\n         (Scalar x_ptr x * R')%sep m ->\n         (find k_impl\n          implementing (pred (k head))\n          and-returning retvars\n          and-locals-post locals_ok\n          with-locals (map.put locals var (word.of_Z (Z.b2z head)))\n          and-memory m and-trace tr and-rest R\n          and-functions functions)) ->\n      (let head := v in\n       find (cmd.seq\n               (cmd.call [var] sctestbit [expr.var x_var; expr.var i_var])\n               k_impl)\n       implementing (pred (dlet head k))\n       and-returning retvars\n       and-locals-post locals_ok\n       with-locals locals and-memory mem and-trace tr and-rest R\n       and-functions functions).\n  Proof.\n    repeat straightline'.\n    handle_call; [ solve [eauto] ..\n                 | cbv [dlet.dlet] in *|-; sepsimpl ].\n    cbn [length] in *. destruct_lists_of_known_length.\n    subst_lets_in_goal. subst.\n    match goal with H : word.unsigned _ = Z.of_nat _ |- _ =>\n                    rewrite H in *\n    end.\n    repeat straightline'; eauto.\n  Qed.\nEnd Compile.\n\nLtac scfield_compile_step := simple eapply compile_sctestbit.\n", "meta": {"author": "dip-proto", "repo": "fiat-crypto", "sha": "fc3a9280c51f413943c167cc9292e953b8e42c02", "save_path": "github-repos/coq/dip-proto-fiat-crypto", "path": "github-repos/coq/dip-proto-fiat-crypto/fiat-crypto-fc3a9280c51f413943c167cc9292e953b8e42c02/src/Bedrock/ScalarField/Interface/Compilation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2494948818216518}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of CFGV project.\n\n  CFGV is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  CFGV is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with CFGV.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/CFGVLFMTP2014/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\nSet Implicit Arguments.\nRequire Export AlphaEqProps.\n\n\n\nLtac EqDecRefl :=\n  let dec:= fresh \"dec\" in\n  let HH:= fresh \"Hrefl\" in\nrepeat match goal with\n[pp : @eq ?T ?ta ?tb |- _ ] => \n  assert (Deq T) as dec by eauto with Deq;\n  pose proof (UIPReflDeq dec _ pp) as HH;\n  try rewrite HH; clear HH dec\nend.\n\nLtac EqDec ta tb :=\n  let dec:= fresh \"dec\" in\n  let Heq:= fresh \"Heq\" ta tb in\n  let Hneq:= fresh \"Hneq\" ta tb in\n  let T := type of ta in\n  assert (Deq T) as dec by eauto with Deq;\n  destruct (dec ta tb) as [Heq| Hneq]; clear dec.\n\n\nDefinition tAlphaEqG {G} (sa sb : GSym G) \n  (vc: VarSym G ) (ta : Term sa) (tb : Term sb):=\nmatch (deqGSym sa sb) with\n| left eqq => tAlphaEq vc (transport eqq ta) tb\n| right eqq => False\nend.\n\nDefinition pAlphaEqG {G} (sa sb : GSym G) \n  (vc: VarSym G ) (ta : Pattern sa) (tb : Pattern sb):=\nmatch (deqGSym sa sb) with\n| left eqq => pAlphaEq vc (transport eqq ta) tb\n| right eqq => False\nend.\n\nLtac notAlpha :=\n  let Halc := fresh \"Halc\" in\n  let AlphaTac := introv Halc;\n    inverts Halc;\n    EqDecSndEq;\n    subst;\n    contradiction in\n  let Hseq := fresh  \"Hseq\" in\n  let Hseqd := fresh  \"Hseqd\" in\n  try(AlphaTac);\n  unfold  tAlphaEqG; unfold  pAlphaEqG;\n  match goal with\n  [|- context [deqGSym ?l ?l]] =>\n    rewrite DeqTrue; simpl; AlphaTac\n  | [|- context [deqGSym ?l ?r]] =>\n    destruct (deqGSym l r) as [Hseq |?]; cpx;\n    duplicate Hseq as Hseqd;\n    inverts Hseq; cpx ; try subst; cpx\n  end.\n\nLemma decideAbsT {G} (vc : VarSym G) \n  (sa : GSym G) (ta: Term sa)\n(Hdt : forall phnew : Term sa,\n      tSize phnew <= tSize ta ->\n      forall (sb : GSym G) (tb : Term sb), \n     decidable (tAlphaEqG vc phnew tb))\n(sb : GSym G) (tb: Term sa)\n(la lb :(list (vType vc))) :\ndecidable (AlphaEqAbs (termAbs vc la ta) (termAbs vc lb tb)).\nProof.\n  remember (beq_nat (length la) (length lb)) as blen.\n  destruct blen;\n    [\n        applysym beq_nat_true in Heqblen\n      | \n        right ;\n        applysym beq_nat_false in Heqblen;\n        introv Hal; inverts Hal;\n        EqDecSndEq; omega\n    ].\n  remember (GFreshVars (la++lb\n              ++ tAllVars ta++tAllVars tb) la) as lvn.\n  remember (tSwap ta (combine la lvn)) as phnew.\n  pose proof (tcase \n        (@swapPreservesSize G vc (combine la lvn)) _ ta) as Hs.\n  specialize (Hdt (tSwap ta (combine la lvn))).\n  rewrite Hs in Hdt.\n  dimp Hdt. apply Hdt with \n        (tb:= (tSwap tb (combine lb lvn))) in hyp.\n  unfold tAlphaEqG in hyp.\n  rewrite DeqTrue in hyp. allsimpl.\n  clear Hs  Hdt.\n  clear dependent phnew.\n  destruct hyp as [? | Hnal];[left| right];\n  pose proof (FreshDistVarsSpec \n      (la ++ lb ++ tAllVars ta ++ tAllVars tb) la ) as XX;\n  rewrite <- Heqlvn in XX;\n  simpl in XX; repnd; dands;\n  symmetry in XX.\n  - apply alAbT with (lbnew:=lvn); \n        cpx; try congruence;\n    unfold tFresh; allsimpl; repeat(disjoint_reasoning).\n  - introv Hal. apply Hnal. clear Hnal. clear Heqlvn.\n    apply betterAbsTElim \n    with (lvAvoid:= lvn) in Hal.\n     allsimpl. exrepnd.\n    apply tAlphaEqEquivariantRev with \n    (sw := combine lvn lbnew).\n    autorewrite with SwapAppR.\n    unfold tFresh in Hal3.\n    allsimpl. repnd.\n    symmetry in XX.\n    autorewrite with slow; try congruence;\n    cpx; repeat (disjoint_reasoning);\n    repeat match goal with\n    [ H : disjoint _ _ |- _ ] => clear H\n    | [ H : no_repeats _ _ |- _ ] => clear H\n    end.\nDefined.\n\n\nLemma decideAbsP {G} (vc : VarSym G) \n  (sa : GSym G) (ta: Pattern sa)\n(Hdt : forall phnew : Pattern sa,\n      pSize phnew <= pSize ta ->\n      forall (sb : GSym G) (tb : Pattern sb),\n        decidable (pAlphaEqG vc phnew tb))\n(sb : GSym G) (tb: Pattern sa)\n(la lb :(list (vType vc))) :\ndecidable (AlphaEqAbs (patAbs vc la ta) (patAbs vc lb tb)).\nProof.\n  remember (beq_nat (length la) (length lb)) as blen.\n  destruct blen;\n    [\n        applysym beq_nat_true in Heqblen\n      | \n        right ;\n        applysym beq_nat_false in Heqblen;\n        introv Hal; inverts Hal;\n        EqDecSndEq; omega\n    ].\n  remember (GFreshVars (la++lb\n              ++ pAllVars ta++pAllVars tb) la) as lvn.\n  remember (pSwap ta (combine la lvn)) as phnew.\n  pose proof (pcase \n        (@swapPreservesSize G vc (combine la lvn)) _ ta) as Hs.\n  specialize (Hdt (pSwap ta (combine la lvn))).\n  rewrite Hs in Hdt.\n  dimp Hdt. apply Hdt with \n        (tb:= (pSwap tb (combine lb lvn))) in hyp.\n  unfold pAlphaEqG in hyp.\n  rewrite DeqTrue in hyp. allsimpl.\n  clear Hs  Hdt.\n  clear dependent phnew.\n  destruct hyp as [? | Hnal];[left| right];\n  pose proof (FreshDistVarsSpec \n      (la ++ lb ++ pAllVars ta ++ pAllVars tb) la ) as XX;\n  rewrite <- Heqlvn in XX;\n  simpl in XX; repnd; dands;\n  symmetry in XX.\n  - apply alAbP with (lbnew:=lvn); \n        cpx; try congruence;\n    unfold pFresh; allsimpl; repeat(disjoint_reasoning).\n  - introv Hal. apply Hnal. clear Hnal. clear Heqlvn.\n    apply betterAbsPElim \n    with (lvAvoid:= lvn) in Hal.\n     allsimpl. exrepnd.\n    apply pAlphaEqEquivariantRev with \n    (sw := combine lvn lbnew).\n    autorewrite with SwapAppR.\n    unfold pFresh in Hal3.\n    allsimpl. repnd.\n    symmetry in XX.\n    autorewrite with slow; try congruence;\n    cpx; repeat (disjoint_reasoning);\n    repeat match goal with\n    [ H : disjoint _ _ |- _ ] => clear H\n    | [ H : no_repeats _ _ |- _ ] => clear H\n    end.\nDefined.\n\nDefinition diffVarClasses{G} {sa : GSym G} (ta: Term sa)\n            {sb: GSym G} (tb : Term sb) :=\nmatch (ta, tb) with\n| (vleaf vca va, vleaf vcb vb) \n    => match (DeqVarSym vca vcb) with\n      |left _ => False\n      |right _ => True\n      end\n| _ => False\nend.\n\nDefinition diffPVarClasses{G} \n        {sa : GSym G} (ta: Pattern sa)\n        {sb: GSym G} (tb : Pattern sb) :=\nmatch (ta, tb) with\n| (pvleaf vca va, pvleaf vcb vb) \n    => match (DeqVarSym vca vcb) with\n      |left _ => False\n      |right _ => True\n      end\n| _ => False\nend.\n\n\nDefinition diffTProdsNode {G} {sa : GSym G} (ta: Term sa)\n            {sb: GSym G} (tb : Term sb) :=\nmatch (ta, tb) with\n| (tnode pa va, tnode pb vb) \n    => match (deqPr G pa pb) with\n      |left _ => False\n      |right _ => True\n      end\n| _ => False\nend.\n\nDefinition diffPProdsNode {G} {sa : GSym G} \n        (ta: Pattern sa)\n            {sb: GSym G} (tb : Pattern sb) :=\nmatch (ta, tb) with\n| (pnode pa va, pnode pb vb) \n    => match (deqPPr G pa pb) with\n      |left _ => False\n      |right _ => True\n      end\n| _ => False\nend.\n\nDefinition diffEmbedNode {G} {sa : GSym G} \n        (ta: Pattern sa)\n            {sb: GSym G} (tb : Pattern sb) :=\nmatch (ta, tb) with\n| (embed pa va, embed pb vb) \n    => match (deqEm G pa pb) with\n      |left _ => False\n      |right _ => True\n      end\n| _ => False\nend.\n\n\nDefinition isVLeaf {G} {sa : GSym G} (ta: Term sa) :=\nmatch ta with\n| vleaf vca va \n    => True\n| _ => False\nend.\n\nDefinition isPNode {G} {sa : GSym G} \n  (ta: Pattern sa) :=\nmatch ta with\n| pnode vca va \n    => True\n| _ => False\nend.\n\nDefinition isEmbed {G} {sa : GSym G} \n  (ta: Pattern sa) :=\nmatch ta with\n| embed vca va \n    => True\n| _ => False\nend.\n\n\nLemma alphaEqDecidable : forall {G} (vc : VarSym G),\n     (  (forall (sa : GSym G) (ta: Term sa)\n            (sb: GSym G) (tb : Term sb),\n           decidable (tAlphaEqG vc ta tb))\n         *\n        (forall (sa : GSym G) (ta: Pattern sa)\n            (sb: GSym G) (tb : Pattern sb),\n            decidable (pAlphaEqG vc ta tb))\n         *\n        (forall (l : MixtureParam) (ma mb : Mixture l) \n        (lbva : list (list (vType vc)))\n        (lbvb : list (list (vType vc))),\n           decidable \n              (lAlphaEqAbs (MakeAbstractions vc ma lbva) \n                           (MakeAbstractions vc mb lbvb)))).\nProof.\n  intros.\n  GInductionS; introns Hyp; intros;  allsimpl.\n- Case \"tleaf\".\n  destruct tb;[ | right; notAlpha | right; notAlpha];[].\n  \n  EqDec T T0; [| right; notAlpha]; subst.\n  EqDec t t0; [left|right]; subst;\n  unfold tAlphaEqG; try rewrite DeqTrue; allsimpl;\n  eauto with Alpha;[]; notAlpha.\n\n- Case \"vleaf\".\n  destruct tb; [right; notAlpha | |].\n  + EqDec vc0 vc1;[| right]; subst; try EqDecRefl; simpl.\n    * EqDec v v0; [left|right]; subst; unfolds_base;\n      try rewrite DeqTrue;\n      eauto with Alpha.\n      notAlpha.\n\n    * notAlpha.\n      revert Hseqd0.\n      remember (vleaf vc0 v) as vvl.\n      remember (vleaf vc1 v0) as vvr.\n      assert ( diffVarClasses vvl vvr) as Hdd\n       by (subst; unfold diffVarClasses;\n          cases_if; cpx).\n      clear Heqvvr Heqvvl.\n      remember (vSubstType G vc0).\n      remember (vSubstType G vc1).\n      generalize dependent vvl.\n      generalize dependent vvr.\n      rewrite H0.\n      intros. allsimpl.\n      EqDecRefl. simpl.\n      clear dependent t.\n      clear Hneqvc0vc1.\n      clear v0 v vc0 Heqt0 Hseqd0 vc1. introv Hc; inverts Hc;\n      EqDecSndEq; subst vvl; subst vvr; repnud Hdd; allsimpl; cpx.\n      rewrite DeqTrue in Hdd.\n      trivial.\n  + right. notAlpha.\n    introv Hal. inverts Hal.\n    EqDecSndEq.\n    GC. clear H6. clear X. clear H0.\n    generalize dependent H3. \n    remember (vleaf vc0 v) as xx.\n    assert (isVLeaf xx) as Hxx by (subst;simpl; auto).\n    clear Heqxx.\n    generalize dependent xx.\n    rewrite Hseqd0. \n    allsimpl.\n    introv Hisv Heq.\n    inverts Heq.\n    cpx.\n- Case \"tnode\".\n  destruct tb; [right; notAlpha;fail | |].\n\n    right. notAlpha;\n    remember (vleaf vc0 v) as xx.\n    assert (isVLeaf xx) as Hxx by (subst;simpl; auto).\n    clear Heqxx.\n    generalize dependent xx.\n    rewrite <- Hseqd0. \n    allsimpl.\n    introv Hisv Heq.\n    inverts Heq. EqDecSndEq. subst xx.\n    cpx; fail.\n\n    EqDec p p0;[| right].\n    Focus 2. notAlpha.\n    introv Hal.\n\n    remember (tnode p m) as vvl.\n    remember (tnode p0 m0) as vvr.\n    assert (diffTProdsNode vvl vvr) as Hdd\n     by (subst; unfold diffTProdsNode;\n        cases_if; cpx).\n    clear Heqvvr Heqvvl.\n    remember (tpLhs G p).\n    remember (tpLhs G p0).\n    generalize dependent vvl.\n    generalize dependent vvr.\n    generalize Hseqd0.\n    rewrite H0.\n    introv. allsimpl.\n    EqDecRefl. simpl.\n    clear dependent t.\n    introv Hta Hdd.\n    clear Hseqd1 Heqt0  Hneqpp0 m0 Hyp m.\n    inverts Hta;\n    EqDecSndEq;\n    subst vvl; subst vvr; repnud Hdd; allsimpl; cpx.\n    rewrite DeqTrue in Hdd;\n    trivial; fail.\n\n\n  (* back to the real business *)\n  subst p0. unfold tAlphaEqG.\n  rewrite DeqTrue.\n  simpl. rename m0 into mb.\n  destruct (Hyp mb (allBndngVars vc p m) (allBndngVars vc p mb)) as\n    [Hleq | Hnleq];[left; constructor;auto | right; notAlpha].\n      \n- Case \"ptleaf\".\n  destruct tb;[ | right; notAlpha \n                | right; notAlpha \n                | right; notAlpha]; [].\n  \n  EqDec T T0; [| right; notAlpha]; subst;[].\n  EqDec t t0; [left|right]; subst;\n  unfold pAlphaEqG; try rewrite DeqTrue; allsimpl;\n  eauto with Alpha;[]; notAlpha.\n    \n- Case \"pvleaf\".\n  destruct tb;[ right; notAlpha | \n                | right; notAlpha \n                | right; notAlpha]; [].\n  EqDec vc0 vc1;[ left;subst; try EqDecRefl; simpl;\n                  unfold pAlphaEqG; rewrite DeqTrue\n                  ; constructor; fail\n                | right; notAlpha].\n    \n- Case \"pembed\".\n  destruct tb;[ right; notAlpha \n                | right; notAlpha |\n                | right; notAlpha].\n\n  Focus 2.\n    introv Hal. inverts Hal.\n    EqDecSndEq.\n    GC. clear H6. clear X. clear H0.\n    generalize dependent H3.\n    remember (embed p t) as xx.\n    assert (isEmbed xx) as Hxx by (subst;simpl; auto).\n    clear Heqxx.\n    generalize dependent xx.\n    rewrite Hseqd0. \n    allsimpl.\n    introv Hisv Heq.\n    inverts Heq.\n    cpx; fail.\n\n\n  EqDec p p0;[ subst p0; unfold pAlphaEqG; rewrite DeqTrue\n               | right; notAlpha].\n  Focus 2.\n    remember (embed p t) as vvl.\n    remember (embed p0 t0) as vvr.\n    assert (diffEmbedNode vvl vvr) as Hdd\n     by (subst; unfold diffEmbedNode;\n        cases_if; cpx).\n    clear Heqvvr Heqvvl.\n    remember (epLhs G p).\n    remember (epLhs G p0).\n    generalize dependent vvl.\n    generalize dependent vvr.\n    generalize Hseqd0.\n    rewrite H0.\n    introv. allsimpl.\n    EqDecRefl. simpl.\n    clear dependent p.\n    introv Hta Hdd.\n    clear H0 Hseqd1 Hseqd0 Heqp2 p1 t0 p0.\n    inverts Hdd;\n    EqDecSndEq;\n    subst vvl; subst vvr; repnud Hta; allsimpl; cpx.\n    rewrite DeqTrue in Hta;\n    trivial; fail.\n\n\n\n  (* back to the real business *)\n  simpl.\n  pose proof (Hyp _ t0) as Hd.\n  unfold tAlphaEqG in Hd.\n  rewrite DeqTrue in Hd.\n  simpl in Hd.\n  destruct Hd;[left; constructor; trivial | right; notAlpha].\n  \n- Case \"pnode\".\n  destruct tb;[ right; notAlpha \n                | right; notAlpha \n                | right; notAlpha| ].\n\n    introv Hal. inverts Hal.\n    EqDecSndEq.\n    GC. clear H6. clear X. clear H0.\n    generalize dependent H3.\n    remember (pnode p m) as xx.\n    assert (isPNode xx) as Hxx by (subst;simpl; auto).\n    clear Heqxx.\n    generalize dependent xx.\n    rewrite Hseqd0. \n    allsimpl.\n    introv Hisv Heq.\n    inverts Heq.\n    cpx; fail.\n\n    EqDec p p0;[| right].\n    Focus 2. notAlpha.\n    remember (pnode p m) as vvl.\n    remember (pnode p0 m0) as vvr.\n    assert (diffPProdsNode vvl vvr) as Hdd\n     by (subst; unfold diffPProdsNode;\n        cases_if; cpx).\n    clear Heqvvr Heqvvl.\n    remember (ppLhs G p).\n    remember (ppLhs G p0).\n    generalize dependent vvl.\n    generalize dependent vvr.\n    generalize Hseqd0.\n    rewrite H0.\n    introv. allsimpl.\n    EqDecRefl. simpl.\n    clear dependent p.\n    introv Hta Hdd.\n    clear H0 Hseqd1 Hseqd0 Heqp2 p1 m0 p0.\n    inverts Hdd;\n    EqDecSndEq;\n    subst vvl; subst vvr; repnud Hta; allsimpl; cpx.\n    rewrite DeqTrue in Hta;\n    trivial; fail.\n\n    (* back to the real business *)\n  subst p0. unfold pAlphaEqG.\n  rewrite DeqTrue.\n  simpl. rename m0 into mb.\n  destruct (Hyp mb [] []) as\n  [Hleq | Hnleq];[left; constructor;auto | right; notAlpha].\n\n- Case \"mnil\".\n  dependent inversion mb. simpl. left.\n  constructor.\n\n  \n- Case \"mtcons\".\n  dependent inversion mb. simpl.\n  subst. \n  remember (lhead lbva) as lha.\n  remember (lhead lbvb) as lhb.\n  remember (tail lbva) as lta.\n  remember (tail lbvb) as ltb.\n  clear Heqlha Heqlhb Heqlta Heqltb.\n  specialize (Hyp0 m lta ltb).\n  destruct (Hyp0); [| right ; notAlpha].\n  destruct (decideAbsT vc ph Hyp h t lha lhb);\n    [left; constructor; auto| right; notAlpha].\n  \n- Case \"mpcons\".\n  dependent inversion mb. simpl.\n  subst. \n  remember (lhead lbva) as lha.\n  remember (lhead lbvb) as lhb.\n  remember (tail lbva) as lta.\n  remember (tail lbvb) as ltb.\n  clear Heqlha Heqlhb Heqlta Heqltb.\n  specialize (Hyp0 m lta ltb).\n  destruct (Hyp0); [| right ; notAlpha].\n  destruct (decideAbsP vc ph Hyp h p lha lhb);\n    [left; constructor; auto| right; notAlpha].\nDefined.\n\nLemma tAlphaEqDecidable : forall {G} (vc : VarSym G)\n     {s : GSym G} (ta: Term s) (tb : Term s),\n          decidable (tAlphaEqG vc ta tb).\nProof.\n  intros. apply (tcase (alphaEqDecidable vc)).\nDefined.\n\n(** need (cnstructive) finiteness of [VarSym G] for [tAlphaEqual]\n    to be decidable *)\n    \n", "meta": {"author": "aa755", "repo": "CFGV", "sha": "440965e85e0d7107a8f0cfef5d14b895979716e5", "save_path": "github-repos/coq/aa755-CFGV", "path": "github-repos/coq/aa755-CFGV/CFGV-440965e85e0d7107a8f0cfef5d14b895979716e5/AlphaDecider.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24945149434170974}}
{"text": "Require Import Bool List String Peano_dec.\nRequire Import Common FMap IndexSupport HVector Syntax Topology Semantics SemFacts StepM.\nRequire Import Invariant TrsInv Simulation Serial SerialFacts.\nRequire Import RqRsLang RqRsCorrect.\n\nRequire Import Ex.Spec Ex.SpecInds Ex.Template.\nRequire Import Ex.Mesi Ex.Mesi.Mesi Ex.Mesi.MesiTopo.\nRequire Import Ex.Mesi.MesiInvOk.\n\nSet Implicit Arguments.\n\nImport PropMonadNotations.\nImport CaseNotations.\n\nLocal Open Scope list.\nLocal Open Scope hvec.\nLocal Open Scope fmap.\n\nLemma InvExcl_excl_invalid:\n  forall topo cifc st (He: InvExcl topo cifc st) msgs eidx eost,\n    st_msgs st = msgs ->\n    (st_oss st)@[eidx] = Some eost ->\n    NoRsI eidx msgs ->\n    mesiE <= eost#[status] ->\n    forall oidx ost,\n      eidx <> oidx ->\n      (st_oss st)@[oidx] = Some ost ->\n      ObjInvalid oidx ost msgs.\nProof.\n  intros; subst.\n  specialize (He eidx).\n  disc_rule_conds_ex.\n  red in H.\n  unfold ObjExcl0 in H; simpl in H.\n  specialize (H (conj H2 H1)); dest.\n  specialize (H _ H3).\n  rewrite H4 in H; auto.\nQed.\n\nSection Sim.\n  Variable (tr: tree).\n  Hypothesis (Htr: tr <> Node nil).\n\n  Let topo := fst (tree2Topo tr 0).\n  Let cifc := snd (tree2Topo tr 0).\n  Let impl := Mesi.impl Htr.\n\n  Local Definition spec :=\n    @SpecInds.spec (c_l1_indices cifc) (tree2Topo_l1_NoPrefix tr 0).\n\n  Existing Instance Mesi.ImplOStateIfc.\n\n  (** NOTE: simulation only states about coherent values.\n   * Exclusiveness is stated and proven as an invariant. *)\n\n  Section ObjCoh.\n    Variables (cv: nat)\n              (cidx: IdxT)\n              (cost: OState)\n              (msgs: MessagePool Msg).\n\n    Definition cohMsgs: list (MSig * (Id Msg -> Prop)) :=\n      (| (downTo cidx, (MRs, mesiRsS)): fun idm => (valOf idm).(msg_value) = cv\n       | (downTo cidx, (MRs, mesiRsE)): fun idm => (valOf idm).(msg_value) = cv\n       | (rsUpFrom cidx, (MRs, mesiDownRsS)): fun idm => (valOf idm).(msg_value) = cv)%cases.\n\n    Definition MsgCoh := MsgP cohMsgs.\n    Definition MsgsCoh := MsgsP cohMsgs msgs.\n\n    Definition ObjCoh :=\n      ImplOStateMESI cidx cost msgs cv /\\ MsgsCoh.\n\n  End ObjCoh.\n\n  Section ObjCohFacts.\n\n    Lemma ObjInvalid_ObjCoh:\n      forall oidx orq ost msgs\n             (Hrsi: RsDownConflicts oidx orq msgs),\n        ObjInvalid oidx ost msgs ->\n        forall cv, ObjCoh cv oidx ost msgs.\n    Proof.\n      unfold ObjInvalid, ObjCoh; intros.\n      destruct H.\n      - red in H; dest; repeat ssplit.\n        + red; intros; solve_mesi.\n        + do 2 red; intros.\n          specialize (H1 _ H2); red in H1.\n          red; unfold cohMsgs, map, caseDec, fst in *.\n          repeat (find_if_inside; [exfalso; auto; fail|]).\n          destruct (sig_dec _ (_, (MRs, mesiRsM))); [exfalso; auto|].\n          repeat (find_if_inside; [exfalso; auto; fail|]).\n          auto.\n\n      - repeat ssplit.\n        + red; intros.\n          exfalso; eapply NoRsI_MsgExistsSig_InvRs_false; eauto.\n        + destruct H as [idm [? ?]].\n          red; intros.\n          specialize (Hrsi idm ltac:(rewrite H0; reflexivity)\n                                      ltac:(rewrite H0; reflexivity) H); dest.\n          red; intros.\n          red; unfold cohMsgs, map, caseDec, fst.\n          repeat find_if_inside; [..|auto].\n          * exfalso; eapply (H3 idm0); try rewrite H0; try rewrite e; auto.\n            destruct idm as [midx msg], idm0 as [midx0 msg0].\n            simpl in *; inv H0; inv e.\n            intro; subst; rewrite H11 in H12; discriminate.\n          * exfalso; eapply (H3 idm0); try rewrite H0; try rewrite e; auto.\n            destruct idm as [midx msg], idm0 as [midx0 msg0].\n            simpl in *; inv H0; inv e.\n            intro; subst; rewrite H11 in H12; discriminate.\n          * exfalso; eapply H6; try rewrite e; eauto.\n    Qed.\n\n    Lemma NoCohMsgs_MsgsCoh:\n      forall oidx msgs,\n        NoCohMsgs oidx msgs ->\n        forall cv, MsgsCoh cv oidx msgs.\n    Proof.\n      intros.\n      do 2 red; intros.\n      specialize (H _ H0); red in H.\n      red; unfold cohMsgs, map, caseDec, fst in *.\n      repeat (find_if_inside; [exfalso; auto; fail|]).\n      destruct (sig_dec _ (_, (MRs, mesiRsM))); [exfalso; auto|].\n      repeat (find_if_inside; [exfalso; auto; fail|]).\n      auto.\n    Qed.\n\n    Lemma ObjExcl0_ObjCoh:\n      forall oidx ost oss msgs,\n        InvObjExcl0 oidx ost oss msgs ->\n        ObjExcl0 oidx ost msgs ->\n        ObjCoh ost#[val] oidx ost msgs.\n    Proof.\n      intros.\n      specialize (H H0); dest.\n      repeat split.\n      apply NoCohMsgs_MsgsCoh; assumption.\n    Qed.\n\n    Lemma MsgsCoh_enqMP:\n      forall cv cidx msgs,\n        MsgsCoh cv cidx msgs ->\n        forall midx msg,\n          MsgCoh cv cidx (midx, msg) ->\n          MsgsCoh cv cidx (enqMP midx msg msgs).\n    Proof.\n      intros; apply MsgsP_enqMP; auto.\n    Qed.\n\n    Lemma MsgsCoh_other_midx_enqMP:\n      forall cv cidx msgs,\n        MsgsCoh cv cidx msgs ->\n        forall midx msg,\n          ~ In midx [rqUpFrom cidx; rsUpFrom cidx; downTo cidx] ->\n          MsgsCoh cv cidx (enqMP midx msg msgs).\n    Proof.\n      intros.\n      apply MsgsP_other_midx_enqMP; auto.\n      intro Hx; elim H0; dest_in; simpl; tauto.\n    Qed.\n\n    Lemma MsgsCoh_other_midx_enqMsgs:\n      forall cv cidx msgs,\n        MsgsCoh cv cidx msgs ->\n        forall eins,\n          DisjList (idsOf eins) [rqUpFrom cidx; rsUpFrom cidx; downTo cidx] ->\n          MsgsCoh cv cidx (enqMsgs eins msgs).\n    Proof.\n      intros.\n      apply MsgsP_other_midx_enqMsgs; auto.\n      simpl.\n      eapply DisjList_comm, DisjList_SubList;\n        [|apply DisjList_comm; eassumption].\n      solve_SubList.\n    Qed.\n\n    Lemma MsgsCoh_other_msg_id_enqMP:\n      forall cv cidx msgs,\n        MsgsCoh cv cidx msgs ->\n        forall midx msg,\n          ~ In (msg_id msg) [mesiRsS; mesiRsE; mesiDownRsS] ->\n          MsgsCoh cv cidx (enqMP midx msg msgs).\n    Proof.\n      intros; apply MsgsP_other_msg_id_enqMP; auto.\n    Qed.\n\n    Lemma MsgsCoh_other_msg_id_enqMsgs:\n      forall cv cidx msgs,\n        MsgsCoh cv cidx msgs ->\n        forall eins,\n          DisjList (map (fun idm => msg_id (valOf idm)) eins)\n                   [mesiRsS; mesiRsE; mesiDownRsS] ->\n          MsgsCoh cv cidx (enqMsgs eins msgs).\n    Proof.\n      intros; apply MsgsP_other_msg_id_enqMsgs; auto.\n    Qed.\n\n    Lemma MsgsCoh_deqMP:\n      forall cv cidx msgs,\n        MsgsCoh cv cidx msgs ->\n        forall midx,\n          MsgsCoh cv cidx (deqMP midx msgs).\n    Proof.\n      intros; apply MsgsP_deqMP; auto.\n    Qed.\n\n    Lemma MsgsCoh_deqMsgs:\n      forall cv cidx msgs,\n        MsgsCoh cv cidx msgs ->\n        forall minds,\n          MsgsCoh cv cidx (deqMsgs minds msgs).\n    Proof.\n      intros; apply MsgsP_deqMsgs; auto.\n    Qed.\n\n  End ObjCohFacts.\n\n  Definition ImplStateCoh (cv: nat) (st: State): Prop :=\n    Forall (fun oidx =>\n              ost <-- (st_oss st)@[oidx];\n                _ <-- (st_orqs st)@[oidx];\n                ObjCoh cv oidx ost (st_msgs st))\n           (c_li_indices cifc ++ c_l1_indices cifc).\n\n  Definition SpecStateCoh (cv: nat) (st: @State SpecInds.NatDecValue SpecOStateIfc): Prop :=\n    sost <-- (st_oss st)@[specIdx];\n      sorq <-- (st_orqs st)@[specIdx];\n      sost#[specValueIdx] = cv.\n\n  Inductive SimState: State -> @State SpecInds.NatDecValue SpecOStateIfc -> Prop :=\n  | SimStateIntro:\n      forall cv ist sst,\n        SpecStateCoh cv sst ->\n        ImplStateCoh cv ist ->\n        SimState ist sst.\n\n  Definition SimMESI (ist: State) (sst: @State SpecInds.NatDecValue SpecOStateIfc): Prop :=\n    SimState ist sst /\\\n    SimExtMP (c_l1_indices cifc) ist.(st_msgs) ist.(st_orqs) sst.(st_msgs).\n\n  Hint Unfold ObjCoh ImplStateCoh: RuleConds.\n\n  Lemma mesi_sim_init:\n    SimMESI (initsOf impl) (initsOf spec).\n  Proof.\n    split.\n    - apply SimStateIntro with (cv:= 0).\n      + reflexivity.\n      + apply Forall_forall; intros oidx ?.\n        subst cifc; rewrite c_li_indices_head_rootOf in H by assumption.\n        simpl in H; icase oidx.\n        * simpl; rewrite implOStatesInit_value_root by assumption.\n          unfold implORqsInit; simpl.\n          rewrite initORqs_value\n            by (rewrite c_li_indices_head_rootOf by assumption; left; reflexivity).\n          simpl; repeat split.\n          do 3 red; intros.\n          do 2 red in H0; dest_in.\n        * simpl; rewrite implOStatesInit_value_non_root by assumption.\n          unfold implORqsInit; simpl.\n          rewrite initORqs_value\n            by (rewrite c_li_indices_head_rootOf by assumption; right; assumption).\n          simpl; repeat split.\n          do 3 red; intros.\n          do 2 red in H0; dest_in.\n    - red; apply Forall_forall; intros oidx ?.\n      repeat split.\n      simpl; unfold implORqsInit.\n      rewrite initORqs_value; [|apply in_or_app; auto].\n      simpl; mred.\n  Qed.\n\n  Lemma mesi_sim_silent:\n    forall ist sst1,\n      SimMESI ist sst1 ->\n      exists slbl sst2,\n        getLabel RlblEmpty = getLabel slbl /\\\n        step_m spec sst1 slbl sst2 /\\ SimMESI ist sst2.\n  Proof.\n    simpl; intros.\n    exists RlblEmpty; eexists.\n    repeat ssplit; eauto.\n    constructor.\n  Qed.\n\n  Lemma mesi_sim_ext_in:\n    forall oss orqs msgs sst1,\n      SimMESI {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} sst1 ->\n      forall eins,\n        eins <> nil -> ValidMsgsExtIn impl eins ->\n        exists slbl sst2,\n          getLabel (RlblIns eins) = getLabel slbl /\\\n          step_m spec sst1 slbl sst2 /\\\n          SimMESI {| st_oss := oss;\n                     st_orqs := orqs;\n                     st_msgs := enqMsgs eins msgs |} sst2.\n  Proof.\n    destruct sst1 as [soss1 sorqs1 smsgs1]; simpl; intros.\n    red in H; simpl in *; dest.\n    exists (RlblIns eins); eexists.\n    repeat ssplit.\n    + reflexivity.\n    + eapply SmIns; eauto.\n      destruct H1; split; [|assumption].\n      simpl in *; rewrite c_merqs_l1_rqUpFrom in H1.\n      assumption.\n    + split.\n      * inv H.\n        apply SimStateIntro with (cv:= cv); [assumption|].\n        red in H4; simpl in H4.\n        apply Forall_forall; intros oidx ?.\n        rewrite Forall_forall in H4; specialize (H4 _ H).\n        disc_rule_conds_ex.\n        repeat split.\n        { intros; apply H4; auto.\n          eapply MsgsP_enqMsgs_inv; eauto.\n        }\n        { apply MsgsCoh_other_midx_enqMsgs; [assumption|].\n          destruct H1; simpl in H1.\n          eapply DisjList_SubList; [eassumption|].\n          apply DisjList_comm, DisjList_SubList with (l1:= c_minds (snd (tree2Topo tr 0))).\n          { apply tree2Topo_obj_chns_minds_SubList; auto. }\n          { apply tree2Topo_minds_merqs_disj. }\n        }\n      * apply SimExtMP_enqMsgs; auto.\n        apply H1.\n  Qed.\n\n  Lemma mesi_sim_ext_out:\n    forall oss orqs msgs sst1,\n      SimMESI {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} sst1 ->\n      forall eouts: list (Id Msg),\n        eouts <> nil ->\n        Forall (FirstMPI msgs) eouts ->\n        ValidMsgsExtOut impl eouts ->\n        exists slbl sst2,\n          getLabel (RlblOuts eouts) = getLabel slbl /\\\n          step_m spec sst1 slbl sst2 /\\\n          SimMESI {| st_oss := oss;\n                     st_orqs := orqs;\n                     st_msgs := deqMsgs (idsOf eouts) msgs |} sst2.\n  Proof.\n    destruct sst1 as [soss1 sorqs1 smsgs1]; simpl; intros.\n    red in H; simpl in *; dest.\n    destruct H2; unfold impl in H2; simpl in H2.\n    exists (RlblOuts eouts); eexists.\n    repeat ssplit.\n    - reflexivity.\n    - rewrite c_merss_l1_downTo in H2.\n      eapply SmOuts with (msgs0:= smsgs1); eauto.\n      + eapply SimExtMP_ext_outs_FirstMPI; eauto.\n      + split; assumption.\n    - split.\n      + inv H.\n        apply SimStateIntro with (cv:= cv); [assumption|].\n        red in H6; simpl in H6.\n        apply Forall_forall; intros oidx ?.\n        rewrite Forall_forall in H6; specialize (H6 _ H).\n        disc_rule_conds_ex.\n        repeat split.\n        { intros; apply H6; auto.\n          eapply MsgsP_other_midx_deqMsgs_inv; [eassumption|].\n          simpl.\n          apply DisjList_comm, DisjList_SubList with (l1:= c_minds (snd (tree2Topo tr 0))).\n          { eapply SubList_trans;\n              [|apply tree2Topo_obj_chns_minds_SubList; eauto].\n            solve_SubList.\n          }\n          { eapply DisjList_comm, DisjList_SubList; [eassumption|].\n            apply DisjList_comm, tree2Topo_minds_merss_disj.\n          }\n        }\n        { apply MsgsCoh_deqMsgs; assumption. }\n      + rewrite c_merss_l1_downTo in H2.\n        apply SimExtMP_ext_outs_deqMsgs; auto.\n  Qed.\n\n  Ltac disc_MsgsCoh_by_FirstMP Hd Hf :=\n    specialize (Hd _ (FirstMP_InMP Hf));\n    red in Hd;\n    cbv [map cohMsgs] in Hd;\n    cbv [sigOf idOf valOf fst snd] in Hd;\n    match type of Hf with\n    | FirstMPI _ (_, ?msg) =>\n      match goal with\n      | [H1: msg_id ?msg = _, H2: msg_type ?msg = _ |- _] =>\n        rewrite H1, H2 in Hd\n      end\n    end;\n    disc_caseDec Hd.\n\n  Ltac disc_rule_custom ::=\n    repeat\n      match goal with\n      (* get simulation propositions for the current impl. state *)\n      | [Hf: Forall _ (c_li_indices ?cifc ++ c_l1_indices ?cifc),\n             Hin: In ?oidx (c_li_indices ?cifc)\n         |- context[SimMESI {| st_oss := _ +[?oidx <- _] |} _]] =>\n        rewrite Forall_forall in Hf;\n        pose proof (Hf _ (in_or_app _ _ _ (or_introl Hin)))\n      | [Hf: Forall _ (c_li_indices ?cifc ++ c_l1_indices ?cifc),\n             Hin: In ?oidx (tl (c_li_indices ?cifc))\n         |- context[SimMESI {| st_oss := _ +[?oidx <- _] |} _]] =>\n        rewrite Forall_forall in Hf;\n        pose proof (Hf _ (in_or_app _ _ _ (or_introl (tl_In _ _ Hin))))\n      | [Hf: Forall _ (c_li_indices ?cifc ++ c_l1_indices ?cifc),\n             Hin: In ?oidx (c_l1_indices ?cifc)\n         |- context[SimMESI {| st_oss := _ +[?oidx <- _] |} _]] =>\n        rewrite Forall_forall in Hf;\n        pose proof (Hf _ (in_or_app _ _ _ (or_intror Hin)))\n      (* rewrite a coherent value *)\n      | [H: fst ?ost = fst _ |- context[fst ?ost] ] => rewrite H in *\n      (* rewrite inputs/outputs message ids *)\n      | [H: msg_id ?rmsg = _ |- context[msg_id ?rmsg] ] => rewrite H\n      end.\n\n  (*! Prove [SimMESI] for internal steps *)\n\n  Ltac solve_ImplStateCoh :=\n    idtac.\n\n  Ltac solve_SpecStateCoh :=\n    eapply SimStateIntro; [solve_rule_conds_ex|].\n\n  Ltac solve_sim_mesi_ext_mp :=\n    red; simpl; split; [|solve_sim_ext_mp].\n\n  Ltac solve_sim_mesi :=\n    solve_sim_mesi_ext_mp;\n    solve_SpecStateCoh;\n    solve_ImplStateCoh.\n\n  Ltac solve_ImplOStateMESI :=\n    intros;\n    try match goal with\n        | [H: context [invalidate ?st] |- _] =>\n          pose proof (invalidate_sound st)\n        | |- context [invalidate ?st] =>\n          pose proof (invalidate_sound st)\n        end;\n    auto; try solve_mesi; (* check if the goal is solved automatically *)\n    match goal with\n    | [H: _ -> ?P |- ?P] => apply H; auto\n    | [H: _ -> _ -> ?P |- ?P] => apply H; auto\n    end;\n    try match goal with\n        | H:MsgsP ?P _ |- MsgsP ?P _ => disc_MsgsP H; assumption\n        end;\n    try solve_mesi.\n\n  Ltac solve_MsgsCoh :=\n    repeat\n      (try match goal with\n           | |- MsgsCoh _ _ (enqMP _ _ _) =>\n             apply MsgsCoh_other_midx_enqMP;\n             [|solve_chn_not_in; auto; fail]\n           | |- MsgsCoh _ _ (enqMP _ _ _) =>\n             apply MsgsCoh_other_msg_id_enqMP; [|solve_not_in]\n           | |- MsgsCoh _ _ (enqMP _ _ _) =>\n             apply MsgsCoh_enqMP;\n             [|do 2 red; cbv [map cohMsgs]; solve_caseDec; reflexivity]\n           | |- MsgsCoh _ _ (enqMsgs _ _) =>\n             apply MsgsCoh_other_msg_id_enqMsgs; [|solve_DisjList_ex idx_dec]\n           | |- MsgsCoh _ _ (deqMP _ _) => apply MsgsCoh_deqMP\n           | |- MsgsCoh _ _ (deqMsgs _ _) => apply MsgsCoh_deqMsgs\n           end; try eassumption).\n\n  Ltac derive_input_msg_coherent :=\n    match goal with\n    | [Hcoh: MsgsCoh ?cv _ _, Hfmp: FirstMPI _ (_, ?cmsg) |- _] =>\n      let Ha := fresh \"H\" in\n      assert (msg_value cmsg = cv)\n        as Ha by (disc_MsgsCoh_by_FirstMP Hcoh Hfmp; assumption);\n      rewrite Ha in *\n    end.\n\n  Ltac derive_obj_coherent oidx :=\n    match goal with\n    | [Hcoh: _ -> _ -> fst ?ost = ?cv, Host: ?oss@[oidx] = Some ?ost |- _] =>\n      let Ha := fresh \"H\" in\n      assert (fst ost = cv) as Ha by (apply Hcoh; auto; solve_mesi);\n      rewrite Ha in *\n    end.\n\n  Ltac derive_coherence_of oidx :=\n    match goal with\n    | [Hf: forall _, In _ ?l -> _, He: In oidx ?l |- _] =>\n      pose proof (Hf _ He); disc_rule_conds_ex\n    end.\n\n  Theorem mesi_sim_ok:\n    InvSim step_m step_m (MesiInvOk.InvForSim tr) SimMESI impl spec.\n  Proof. (* SKIP_PROOF_ON\n    red; intros.\n\n    pose proof (footprints_ok\n                  (mesi_GoodORqsInit Htr)\n                  (mesi_GoodRqRsSys Htr) H) as Hftinv.\n    pose proof (upLockInv_ok\n                  (mesi_GoodORqsInit Htr)\n                  (mesi_GoodRqRsSys Htr)\n                  (mesi_RqRsDTree Htr) H) as Hpulinv.\n    pose proof (upLockInv_ok\n                  (mesi_GoodORqsInit Htr)\n                  (mesi_GoodRqRsSys Htr)\n                  (mesi_RqRsDTree Htr)\n                  (reachable_steps H (steps_singleton H2))) as Hnulinv.\n    pose proof (mesi_RootChnInv_ok H) as Hprc.\n    pose proof (mesi_MsgConflictsInv\n                  (@mesi_RootChnInv_ok _ Htr) H) as Hpmcf.\n    pose proof (mesi_MsgConflictsInv\n                  (@mesi_RootChnInv_ok _ Htr)\n                  (reachable_steps H (steps_singleton H2))) as Hnmcf.\n\n    inv H2;\n      [apply mesi_sim_silent; assumption\n      |apply mesi_sim_ext_in; assumption\n      |apply mesi_sim_ext_out; assumption\n      |].\n\n    destruct sst1 as [soss1 sorqs1 smsgs1].\n    destruct H0; simpl in H0, H2; simpl.\n    inv H0.\n    red in H15; simpl in H15.\n    red in H6; simpl in H6.\n    destruct (soss1@[specIdx]) as [sost|] eqn:Hsost; simpl in *; [|exfalso; auto].\n    destruct (sorqs1@[specIdx]) as [sorq|] eqn:Hsorq; simpl in *; [|exfalso; auto].\n    subst.\n    simpl in H4; destruct H4; [subst|apply in_app_or in H0; destruct H0].\n\n    - (*! Cases for the main memory *)\n      Ltac solve_ImplStateCoh_mem_me :=\n        disc_rule_conds_ex;\n        split; [solve_ImplOStateMESI|solve_MsgsCoh].\n\n      Ltac solve_ImplStateCoh_mem_others lidx :=\n        match goal with\n        | [Hf: forall _, In _ ?l -> _, He: In lidx ?l |- _] =>\n          specialize (Hf _ He); disc_rule_conds_ex\n        end;\n        split; [solve_ImplOStateMESI|solve_MsgsCoh].\n\n      Ltac case_ImplStateCoh_mem_me_others lidx :=\n        match goal with\n        | |- ImplStateCoh _ {| st_oss := _ +[?oidx <- _] |} =>\n          red; simpl;\n          apply Forall_forall;\n          intros lidx ?; destruct (idx_dec lidx oidx); subst\n        end.\n\n      Ltac solve_ImplStateCoh ::=\n        let lidx := fresh \"lidx\" in\n        case_ImplStateCoh_mem_me_others lidx;\n        [solve_ImplStateCoh_mem_me|solve_ImplStateCoh_mem_others lidx].\n\n      (** Derive some properties of the root *)\n      pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n\n      assert (In (rootOf (fst (tree2Topo tr 0))) (c_li_indices (snd (tree2Topo tr 0)))).\n      { rewrite c_li_indices_head_rootOf by assumption.\n        left; reflexivity.\n      }\n\n      assert (~ In (rootOf (fst (tree2Topo tr 0))) (c_l1_indices (snd (tree2Topo tr 0)))).\n      { pose proof (tree2Topo_WfCIfc tr 0) as [? _].\n        apply (DisjList_NoDup idx_dec) in H4.\n        eapply DisjList_In_2; eassumption.\n      }\n\n      disc_rule_conds_ex.\n      pose proof (RootChnInv_root_NoRsI Hprc) as Hnrsi.\n      pose proof (RootChnInv_root_NoRqI Hprc) as Hnrqi.\n      unfold topo in Hnrsi, Hnrqi; simpl in Hnrsi, Hnrqi.\n\n      assert (rsEdgeUpFrom topo (rootOf (fst (tree2Topo tr 0))) = None).\n      { destruct (rsEdgeUpFrom _ _) eqn:Hrs; [|reflexivity].\n        exfalso.\n        apply rsEdgeUpFrom_Some in Hrs; [|apply mesi_RqRsChnsOnDTree].\n        destruct Hrs as [rqUp [down [pidx ?]]]; dest.\n        apply parentIdxOf_child_not_root in H29; [|subst topo; auto].\n        auto.\n      }\n\n      (** Abstract the root. *)\n      remember (rootOf (fst (tree2Topo tr 0))) as oidx; clear Heqoidx.\n      disc_rule_conds_ex.\n\n      (** Do case analysis per a rule. *)\n      apply concat_In in H5; destruct H5 as [crls [? ?]].\n      apply in_map_iff in H5; destruct H5 as [cidx [? ?]]; subst.\n\n      (** Derive that the child has the parent. *)\n      assert (parentIdxOf (fst (tree2Topo tr 0)) cidx = Some oidx)\n        by (apply subtreeChildrenIndsOf_parentIdxOf; auto).\n\n      dest_in.\n\n      { (* [liGetSImmME] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_child_chns cidx.\n        derive_child_idx_in cidx.\n        derive_obj_coherent oidx.\n        solve_sim_mesi.\n        destruct (idx_dec lidx cidx); subst; solve_MsgsCoh.\n      }\n\n      { (* [liGetMImm] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_child_chns cidx.\n        derive_child_idx_in cidx.\n        solve_sim_mesi.\n      }\n\n      { (* [liInvImmE] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_child_chns cidx.\n        derive_child_idx_in cidx.\n\n        solve_sim_mesi_ext_mp.\n        solve_SpecStateCoh.\n        case_ImplStateCoh_mem_me_others lidx.\n        { disc_rule_conds_ex; split.\n          { intros.\n            derive_coherence_of cidx.\n            disc_getDir.\n            derive_ObjDirE oidx cidx.\n            derive_ObjInvRq cidx.\n            match goal with | [H: _ = cidx |- _] => clear H end.\n            disc_InvNWB cidx H23.\n            congruence.\n          }\n          { solve_MsgsCoh. }\n        }\n        { solve_ImplStateCoh_mem_others lidx. }\n      }\n\n      { (* [liInvImmWBME] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_child_chns cidx.\n        derive_child_idx_in cidx.\n\n        solve_sim_mesi_ext_mp.\n        solve_SpecStateCoh.\n        case_ImplStateCoh_mem_me_others lidx.\n        { disc_rule_conds_ex; split.\n          { intros.\n            derive_coherence_of cidx.\n            disc_getDir.\n            derive_ObjDirME oidx cidx.\n            derive_ObjInvWRq cidx.\n            match goal with | [H: _ = cidx |- _] => clear H end.\n            assert (NoRsI cidx msgs)\n              by (solve_NoRsI_base; solve_NoRsI_by_rqUp cidx).\n            disc_InvWB cidx H22.\n            disc_InvWBCoh_inv cidx H21.\n            congruence.\n          }\n          { solve_MsgsCoh. }\n        }\n        { solve_ImplStateCoh_mem_others lidx. }\n      }\n\n    - (*! Cases for Li caches *)\n      Ltac solve_ImplStateCoh_li_me :=\n        disc_rule_conds_ex;\n        split; [solve_ImplOStateMESI|solve_MsgsCoh].\n\n      Ltac solve_ImplStateCoh_li_others lidx :=\n        match goal with\n        | [Hf: forall _, In _ ?l -> _, He: In lidx ?l |- _] =>\n          specialize (Hf _ He); disc_rule_conds_ex\n        end;\n        split; [solve_ImplOStateMESI|solve_MsgsCoh].\n\n      Ltac case_ImplStateCoh_li_me_others lidx :=\n        match goal with\n        | |- ImplStateCoh _ {| st_oss := _ +[?oidx <- _] |} =>\n          red; simpl;\n          apply Forall_forall;\n          intros lidx ?; destruct (idx_dec lidx oidx); subst\n        end.\n\n      Ltac solve_ImplStateCoh ::=\n        let lidx := fresh \"lidx\" in\n        case_ImplStateCoh_li_me_others lidx;\n        [solve_ImplStateCoh_li_me|solve_ImplStateCoh_li_others lidx].\n\n      apply in_map_iff in H0; destruct H0 as [oidx [? ?]]; subst; simpl in *.\n\n      (** Derive some necessary information: 1) each Li has a parent. *)\n      pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n      pose proof (c_li_indices_tail_has_parent Htr _ _ H4).\n      destruct H0 as [pidx [? ?]].\n      pose proof (Htn _ _ H6); dest.\n\n      (** 2) The object index does not belong to [c_l1_indices]. *)\n      assert (~ In oidx (c_l1_indices (snd (tree2Topo tr 0)))).\n      { pose proof (tree2Topo_WfCIfc tr 0) as [? _].\n        apply (DisjList_NoDup idx_dec) in H19.\n        eapply DisjList_In_2; [eassumption|].\n        apply tl_In; assumption.\n      }\n\n      disc_rule_conds_ex.\n      (** Do case analysis per a rule. *)\n      apply in_app_or in H5; destruct H5.\n\n      1: { (** Rules per a child *)\n        apply concat_In in H5; destruct H5 as [crls [? ?]].\n        apply in_map_iff in H5; destruct H5 as [cidx [? ?]]; subst.\n\n        (** 3) The child has the parent. *)\n        assert (parentIdxOf (fst (tree2Topo tr 0)) cidx = Some oidx)\n          by (apply subtreeChildrenIndsOf_parentIdxOf; auto).\n\n        dest_in.\n\n        { (* [liGetSImmS] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          assert (NoRsI oidx msgs)\n            by (solve_NoRsI_base; solve_NoRsI_by_no_uplock oidx).\n          derive_obj_coherent oidx.\n          solve_sim_mesi.\n          destruct (idx_dec lidx cidx); subst; solve_MsgsCoh.\n        }\n\n        { (* [liGetSImmME] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          assert (NoRsI oidx msgs)\n            by (solve_NoRsI_base; solve_NoRsI_by_no_uplock oidx).\n          derive_obj_coherent oidx.\n          solve_sim_mesi.\n          destruct (idx_dec lidx cidx); subst; solve_MsgsCoh.\n        }\n\n        { (* [liGetSRqUpUp] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          solve_sim_mesi.\n        }\n\n        { (* [liGetSRqUpDownME] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          derive_child_idx_in (dir_excl (fst (snd (snd (snd pos))))).\n          solve_sim_mesi.\n        }\n\n        { (* [liGetMImm] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          solve_sim_mesi.\n        }\n\n        { (* [liGetMRqUpUp] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          solve_sim_mesi.\n        }\n\n        { (* [liGetMRqUpDownME] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          derive_child_idx_in (dir_excl (fst (snd (snd (snd pos))))).\n          solve_sim_mesi.\n        }\n\n        { (* [liGetMRqUpDownS] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          solve_sim_mesi.\n        }\n\n        { (* [liInvImmI] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          solve_sim_mesi.\n        }\n\n        { (* [liInvImmS00] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          solve_sim_mesi.\n        }\n\n        { (* [liInvImmS01] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          solve_sim_mesi.\n        }\n\n        { (* [liInvImmS1] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          solve_sim_mesi.\n        }\n\n        { (* [liInvImmE] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n\n          solve_sim_mesi_ext_mp.\n          solve_SpecStateCoh.\n          case_ImplStateCoh_li_me_others lidx.\n          { disc_rule_conds_ex; split.\n            { intros.\n              derive_coherence_of cidx.\n              disc_getDir.\n              derive_ObjDirE oidx cidx.\n              derive_ObjInvRq cidx.\n              match goal with | [H: _ = cidx |- _] => clear H end.\n              disc_InvNWB cidx H28.\n              congruence.\n            }\n            { solve_MsgsCoh. }\n          }\n          { solve_ImplStateCoh_li_others lidx. }\n        }\n\n        { (* [liInvImmWBI] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          solve_sim_mesi.\n        }\n\n        { (* [liInvImmWBS0] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          solve_sim_mesi.\n        }\n\n        { (* [liInvImmWBS1] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          solve_sim_mesi.\n        }\n\n        { (* [liInvImmWBS] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          solve_sim_mesi.\n        }\n\n        { (* [liInvImmWBME] *)\n          disc_rule_conds_ex; spec_case_silent.\n          derive_child_chns cidx.\n          derive_child_idx_in cidx.\n          assert (NoRqI oidx msgs)\n            by (solve_NoRqI_base; solve_NoRqI_by_no_locks oidx).\n\n          solve_sim_mesi_ext_mp.\n          solve_SpecStateCoh.\n          case_ImplStateCoh_li_me_others lidx.\n          { disc_rule_conds_ex; split.\n            { intros.\n              derive_coherence_of cidx.\n              disc_getDir.\n              derive_ObjDirME oidx cidx.\n              derive_ObjInvWRq cidx.\n              match goal with | [H: _ = cidx |- _] => clear H end.\n              assert (NoRsI cidx msgs)\n                by (solve_NoRsI_base; solve_NoRsI_by_rqUp cidx).\n              disc_InvWB cidx H27.\n              disc_InvWBCoh_inv cidx H26.\n              congruence.\n            }\n            { solve_MsgsCoh. }\n          }\n          { solve_ImplStateCoh_li_others lidx. }\n        }\n      }\n\n      dest_in.\n\n      { (* [liGetSRsDownDownS] *)\n        disc_rule_conds_ex; spec_case_silent.\n\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        derive_child_idx_in cidx.\n        derive_input_msg_coherent.\n        disc_rule_conds_ex.\n        assert (NoRqI oidx msgs)\n          by (solve_NoRqI_base; solve_NoRqI_by_rsDown oidx).\n\n        solve_sim_mesi.\n        destruct (idx_dec lidx cidx); subst; solve_MsgsCoh.\n      }\n\n      { (* [liGetSRsDownDownE] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        derive_child_idx_in cidx.\n        derive_input_msg_coherent.\n        disc_rule_conds_ex.\n        assert (NoRqI oidx msgs)\n          by (solve_NoRqI_base; solve_NoRqI_by_rsDown oidx).\n\n        solve_sim_mesi.\n        destruct (idx_dec lidx cidx); subst; solve_MsgsCoh.\n      }\n\n      { (* [liDownSRsUpDownME] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_footprint_info_basis oidx;\n          [|disc_MesiDownLockInv oidx H29].\n        derive_child_chns upCIdx.\n        derive_child_idx_in upCIdx.\n        disc_responses_from.\n        derive_child_chns cidx.\n        derive_child_idx_in cidx.\n        derive_coherence_of cidx.\n        derive_input_msg_coherent.\n\n        solve_sim_mesi.\n        destruct (idx_dec lidx (obj_idx upCObj)); subst; solve_MsgsCoh.\n      }\n\n      { (* [liDownSImm] *)\n        disc_rule_conds_ex.\n        spec_case_silent.\n        assert (NoRsI oidx msgs)\n          by (solve_NoRsI_base; solve_NoRsI_by_rqDown oidx).\n        disc_rule_conds_ex.\n        solve_sim_mesi.\n      }\n\n      { (* [liDownSRqDownDownME] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_child_idx_in (dir_excl (fst (snd (snd (snd pos))))).\n        solve_sim_mesi.\n      }\n\n      { (* [liDownSRsUpUp] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_footprint_info_basis oidx;\n          [disc_MesiDownLockInv oidx H29|].\n        disc_responses_from.\n        derive_child_chns cidx.\n        derive_child_idx_in cidx.\n        derive_coherence_of cidx.\n        derive_input_msg_coherent.\n        solve_sim_mesi.\n      }\n\n      { (* [liGetMRsDownDownDirI] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        derive_child_idx_in cidx.\n        disc_rule_conds_ex.\n        assert (NoRqI oidx msgs)\n          by (solve_NoRqI_base; solve_NoRqI_by_rsDown oidx).\n        solve_sim_mesi.\n      }\n\n      { (* [liGetMRsDownRqDownDirS] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_footprint_info_basis oidx.\n        solve_sim_mesi.\n      }\n\n      { (* [liDownIRsUpDownS] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_footprint_info_basis oidx;\n          [|disc_MesiDownLockInv oidx H29].\n        derive_child_chns upCIdx.\n        derive_child_idx_in upCIdx.\n        disc_responses_from.\n        disc_rule_conds_ex.\n        solve_sim_mesi.\n      }\n\n      { (* [liDownIRsUpDownME] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_footprint_info_basis oidx;\n          [|disc_MesiDownLockInv oidx H29].\n        derive_child_chns upCIdx.\n        derive_child_idx_in upCIdx.\n        disc_responses_from.\n        disc_rule_conds_ex.\n        solve_sim_mesi.\n      }\n\n      { (* [liDownIImmS] *)\n        disc_rule_conds_ex.\n        spec_case_silent.\n        assert (NoRsI oidx msgs)\n          by (solve_NoRsI_base; solve_NoRsI_by_rqDown oidx).\n        disc_rule_conds_ex.\n        solve_sim_mesi.\n      }\n\n      { (* [liDownIImmME] *)\n        disc_rule_conds_ex.\n        spec_case_silent.\n        assert (NoRsI oidx msgs)\n          by (solve_NoRsI_base; solve_NoRsI_by_rqDown oidx).\n        disc_rule_conds_ex.\n        solve_sim_mesi.\n      }\n\n      { (* [liDownIRqDownDownDirS] *)\n        disc_rule_conds_ex; spec_case_silent.\n        solve_sim_mesi.\n      }\n\n      { (* [liDownIRqDownDownDirME] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_child_idx_in (dir_excl (fst (snd (snd (snd pos))))).\n        solve_sim_mesi.\n      }\n\n      { (* [liDownIRqDownDownDirMES] *)\n        disc_rule_conds_ex; spec_case_silent.\n        solve_sim_mesi.\n      }\n\n      { (* [liDownIRsUpUpS] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_footprint_info_basis oidx;\n          [disc_MesiDownLockInv oidx H29|].\n        disc_responses_from.\n        solve_sim_mesi.\n      }\n\n      { (* [liDownIRsUpUpME] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_footprint_info_basis oidx;\n          [disc_MesiDownLockInv oidx H29|].\n        disc_responses_from.\n        solve_sim_mesi.\n      }\n\n      { (* [liDownIRsUpUpMES] *)\n        disc_rule_conds_ex; spec_case_silent.\n        derive_footprint_info_basis oidx;\n          [disc_MesiDownLockInv oidx H29|].\n        disc_responses_from.\n        solve_sim_mesi.\n      }\n\n      { (* [liInvRqUpUp] *)\n        disc_rule_conds_ex; spec_case_silent.\n        solve_sim_mesi.\n      }\n\n      { (* [liInvRqUpUpWB] *)\n        disc_rule_conds_ex; spec_case_silent.\n        solve_sim_mesi.\n      }\n\n      { (* [liInvRsDownDown] *)\n        disc_rule_conds_ex.\n        spec_case_silent.\n        derive_footprint_info_basis oidx.\n        disc_rule_conds_ex.\n        solve_sim_mesi.\n      }\n\n      { (* [liDropImm] *)\n        disc_rule_conds_ex; spec_case_silent.\n        solve_sim_mesi_ext_mp.\n        solve_SpecStateCoh.\n        case_ImplStateCoh_li_me_others lidx.\n        { solve_ImplStateCoh_li_me. }\n        { specialize (H15 _ H12); disc_rule_conds_ex. }\n      }\n\n    - (*! Cases for L1 caches *)\n      apply in_map_iff in H0; destruct H0 as [oidx [? ?]]; subst.\n\n      Ltac solve_ImplStateCoh_l1_me :=\n        disc_rule_conds_ex;\n        split; [solve_ImplOStateMESI|solve_MsgsCoh].\n\n      Ltac solve_ImplStateCoh_l1_others :=\n        try match goal with\n            | [H: MsgsCoh _ ?oidx _, Hin: In ?oidx _ |- _] => clear Hin\n            end;\n        match goal with\n        | [Hf: forall _, In _ ?l -> _, He: In _ ?l |- _] =>\n          specialize (Hf _ He); disc_rule_conds_ex\n        end;\n        split; [solve_ImplOStateMESI|solve_MsgsCoh].\n\n      Ltac case_ImplStateCoh_l1_me_others :=\n        red; simpl;\n        match goal with\n        | [H: MsgsCoh _ ?oidx _ |- Forall _ _] =>\n          let lidx := fresh \"lidx\" in\n          apply Forall_forall;\n          intros lidx ?; destruct (idx_dec lidx oidx); subst\n        end.\n\n      Ltac solve_ImplStateCoh ::=\n        case_ImplStateCoh_l1_me_others;\n        [solve_ImplStateCoh_l1_me|solve_ImplStateCoh_l1_others].\n\n      (** Derive some necessary information: each L1 has a parent. *)\n      pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n      pose proof (c_l1_indices_has_parent Htr _ _ H4).\n      destruct H0 as [pidx [? ?]].\n      pose proof (Htn _ _ H6); dest.\n\n      Opaque In.\n      disc_rule_conds_ex.\n      Transparent In.\n      (** Do case analysis per a rule. *)\n      dest_in.\n\n      + (* [l1GetSImm] *)\n        disc_rule_conds_ex.\n        spec_case_get oidx.\n        assert (NoRsI oidx msgs)\n          by (solve_NoRsI_base; solve_NoRsI_by_no_uplock oidx).\n        disc_rule_conds_ex.\n        solve_sim_mesi.\n\n      + (* [l1GetSRqUpUp] *)\n        disc_rule_conds_ex.\n        spec_case_silent.\n        assert (NoRsI oidx msgs)\n          by (solve_NoRsI_base; solve_NoRsI_by_no_uplock oidx).\n        disc_rule_conds_ex.\n        solve_sim_mesi.\n\n      + (* [l1GetSRsDownDownS] *)\n        disc_rule_conds_ex.\n        spec_case_get oidx.\n\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        derive_input_msg_coherent.\n        disc_rule_conds_ex.\n        assert (NoRqI oidx msgs)\n          by (solve_NoRqI_base; solve_NoRqI_by_rsDown oidx).\n\n        solve_sim_mesi.\n\n      + (* [l1GetSRsDownDownE] *)\n        disc_rule_conds_ex.\n        spec_case_get oidx.\n\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        derive_input_msg_coherent.\n        disc_rule_conds_ex.\n        assert (NoRqI oidx msgs)\n          by (solve_NoRqI_base; solve_NoRqI_by_rsDown oidx).\n\n        solve_sim_mesi.\n\n      + (* [l1DownSImm] *)\n        disc_rule_conds_ex.\n        spec_case_silent.\n        assert (NoRsI oidx msgs)\n          by (solve_NoRsI_base; solve_NoRsI_by_rqDown oidx).\n        disc_rule_conds_ex.\n        solve_sim_mesi.\n\n      + (* [l1GetMImmE] *)\n        disc_rule_conds_ex.\n        spec_case_set oidx.\n        assert (NoRsI oidx msgs)\n          by (solve_NoRsI_base; solve_NoRsI_by_no_uplock oidx).\n        disc_rule_conds_ex.\n\n        solve_sim_mesi_ext_mp.\n        solve_SpecStateCoh.\n        case_ImplStateCoh_l1_me_others.\n        * mred; simpl.\n          eapply ObjExcl0_ObjCoh.\n          { specialize (H3 oidx); repeat (simpl in H3; mred); dest.\n            eassumption.\n          }\n          { split; [simpl; solve_mesi|solve_MsgsP]. }\n\n        * clear H4. (* In oidx .. *)\n          mred; simpl.\n          assert (exists lost lorq, oss@[lidx] = Some lost /\\\n                                    orqs@[lidx] = Some lorq).\n          { specialize (H15 _ H11).\n            solve_rule_conds_ex.\n          }\n          destruct H4 as [lost [lorq [? ?]]]; rewrite H4, H12; simpl.\n          eapply ObjInvalid_ObjCoh.\n          { apply Hnmcf; [|simpl; mred].\n            assumption.\n          }\n          { eapply InvExcl_excl_invalid with (eidx:= oidx); [eapply H3|..];\n              try eassumption; try reflexivity; try (simpl; mred); try solve_mesi; auto.\n            solve_MsgsP.\n          }\n\n      + (* [l1GetMImmM] *)\n        disc_rule_conds_ex.\n        spec_case_set oidx.\n        assert (NoRsI oidx msgs)\n          by (solve_NoRsI_base; solve_NoRsI_by_no_uplock oidx).\n        disc_rule_conds_ex.\n\n        solve_sim_mesi_ext_mp.\n        solve_SpecStateCoh.\n        case_ImplStateCoh_l1_me_others.\n        * mred; simpl.\n          eapply ObjExcl0_ObjCoh.\n          { specialize (H3 oidx); repeat (simpl in H3; mred); dest.\n            eassumption.\n          }\n          { split; [simpl; solve_mesi|solve_MsgsP]. }\n\n        * clear H4. (* In oidx .. *)\n          mred; simpl.\n          assert (exists lost lorq, oss@[lidx] = Some lost /\\\n                                    orqs@[lidx] = Some lorq).\n          { specialize (H15 _ H11).\n            solve_rule_conds_ex.\n          }\n          destruct H4 as [lost [lorq [? ?]]]; rewrite H4, H12; simpl.\n          eapply ObjInvalid_ObjCoh.\n          { apply Hnmcf; [|simpl; mred].\n            assumption.\n          }\n          { eapply InvExcl_excl_invalid with (eidx:= oidx); [eapply H3|..];\n              try eassumption; try reflexivity; try (simpl; mred); try solve_mesi; auto.\n            solve_MsgsP.\n          }\n\n      + (* [l1GetMRqUpUp] *)\n        disc_rule_conds_ex.\n        spec_case_silent.\n        solve_sim_mesi.\n\n      + (* [l1GetMRsDownDown] *)\n        disc_rule_conds_ex.\n        spec_case_set oidx.\n\n        derive_footprint_info_basis oidx.\n        derive_child_chns cidx.\n        disc_rule_conds_ex.\n\n        assert (NoRsI oidx msgs)\n          by (solve_NoRsI_base; solve_NoRsI_by_rsDown oidx).\n        disc_rule_conds_ex.\n\n        solve_sim_mesi_ext_mp.\n        solve_SpecStateCoh.\n        case_ImplStateCoh_l1_me_others.\n        * mred; simpl.\n          eapply ObjExcl0_ObjCoh.\n          { specialize (H3 oidx); repeat (simpl in H3; mred); dest.\n            eassumption.\n          }\n          { split; [simpl; solve_mesi|solve_MsgsP]. }\n\n        * clear H4. (* In oidx .. *)\n          mred; simpl.\n          assert (exists lost lorq, oss@[lidx] = Some lost /\\\n                                    orqs@[lidx] = Some lorq).\n          { specialize (H15 _ H33).\n            solve_rule_conds_ex.\n          }\n          destruct H4 as [lost [lorq [? ?]]]; rewrite H4, H42; simpl.\n          eapply ObjInvalid_ObjCoh.\n          { apply Hnmcf; [assumption|simpl; mred]. }\n          { eapply InvExcl_excl_invalid with (eidx:= oidx); [eapply H3|..];\n              try eassumption; try reflexivity; try (simpl; mred); try solve_mesi; auto.\n            solve_MsgsP.\n          }\n\n      + (* [l1DownIImmS] *)\n        disc_rule_conds_ex.\n        spec_case_silent.\n        solve_sim_mesi.\n\n      + (* [l1DownIImmME] *)\n        disc_rule_conds_ex.\n        spec_case_silent.\n        solve_sim_mesi.\n\n      + (* [l1InvRqUpUp] *)\n        disc_rule_conds_ex.\n        spec_case_silent.\n        solve_sim_mesi.\n\n      + (* [l1InvRqUpUpM] *)\n        disc_rule_conds_ex.\n        spec_case_silent.\n        solve_sim_mesi.\n\n      + (* [l1InvRsDownDown] *)\n        disc_rule_conds_ex.\n        spec_case_silent.\n        derive_footprint_info_basis oidx.\n        disc_rule_conds_ex.\n        solve_sim_mesi.\n\n        Unshelve.\n        all: eassumption.\n\n        END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Theorem mesi_ok:\n    (steps step_m) # (steps step_m) |-- impl ⊑ spec.\n  Proof.\n    apply invRSim_implies_refinement\n      with (ginv:= MesiInvOk.InvForSim tr) (sim:= SimMESI).\n    - apply mesi_InvForSim_ok.\n    - apply mesi_sim_init.\n    - apply mesi_sim_ok.\n  Qed.\n\nEnd Sim.\n", "meta": {"author": "mit-plv", "repo": "hemiola", "sha": "1984b4de903259ce2d7abda737e76e16e6436dee", "save_path": "github-repos/coq/mit-plv-hemiola", "path": "github-repos/coq/mit-plv-hemiola/hemiola-1984b4de903259ce2d7abda737e76e16e6436dee/src/Ex/Mesi/MesiSim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24943367392062057}}
{"text": "From RecordUpdate Require Import RecordSet.\nImport RecordSetNotations.\n\nFrom Perennial.algebra Require Import liftable auth_map.\nFrom Perennial.Helpers Require Import Transitions.\nFrom Perennial.program_proof Require Import disk_prelude.\n\nFrom Goose.github_com.mit_pdos.go_nfsd Require Import simple.\nFrom Perennial.program_proof Require Import obj.obj_proof marshal_proof addr_proof crash_lockmap_proof addr.addr_proof buf.buf_proof.\nFrom Perennial.program_proof Require Import jrnl.sep_jrnl_proof.\nFrom Perennial.program_proof Require Import disk_prelude.\nFrom Perennial.program_proof Require Import disk_lib.\nFrom Perennial.Helpers Require Import NamedProps Map List range_set.\nFrom Perennial.program_logic Require Import spec_assert.\nFrom Perennial.goose_lang.lib Require Import slice.typed_slice into_val.\nFrom Perennial.program_proof Require Import simple.spec simple.invariant.\n\nSection heap.\nContext `{!heapGS Σ}.\nContext `{!simpleG Σ}.\nImplicit Types (stk:stuckness) (E: coPset).\n\nTheorem wp_inum2Addr (inum : u64) :\n  {{{ ⌜ int.nat inum < NumInodes ⌝ }}}\n    inum2Addr #inum\n  {{{ RET (addr2val (inum2addr inum)); True }}}.\nProof.\n  iIntros (Φ) \"% HΦ\".\n  wp_call.\n  wp_call.\n  rewrite /addr2val /inum2addr /=.\n  rewrite /LogSz /InodeSz.\n\n  rewrite /NumInodes /InodeSz in H.\n  replace (4096 `div` 128) with (32) in H by reflexivity.\n\n  replace (word.add (word.divu (word.sub 4096 8) 8) 2)%Z with (U64 513) by reflexivity.\n  replace (word.mul (word.mul inum 128) 8)%Z with (U64 (int.nat inum * 128 * 8)%nat).\n  { iApply \"HΦ\". done. }\n\n  assert (int.Z (word.mul (word.mul inum 128) 8) = int.Z inum * 1024)%Z.\n  { rewrite word.unsigned_mul.\n    rewrite word.unsigned_mul. word. }\n\n  word.\nQed.\n\nTheorem wp_block2addr bn :\n  {{{ True }}}\n    block2addr #bn\n  {{{ RET (addr2val (blk2addr bn)); True }}}.\nProof.\n  iIntros (Φ) \"% HΦ\".\n  wp_call.\n  wp_call.\n  iApply \"HΦ\". done.\nQed.\n\nOpaque slice_val.\n\nTheorem wp_fh2ino s i :\n  {{{ is_fh s i }}}\n    fh2ino (slice_val s, #())%V\n  {{{ RET #i; True }}}.\nProof.\n  iIntros (Φ) \"Hfh HΦ\".\n  iNamed \"Hfh\".\n  iMod (readonly_load with \"Hfh_slice\") as (q) \"Hslice\".\n  wp_call.\n  wp_call.\n  wp_apply (wp_new_dec with \"Hslice\"); first by eauto.\n  iIntros (dec) \"Hdec\".\n  wp_apply (wp_Dec__GetInt with \"Hdec\").\n  iIntros \"Hdec\".\n  wp_pures.\n  iApply \"HΦ\".\n  done.\nQed.\n\nTheorem wp_Fh__MakeFh3 inum :\n  {{{ True }}}\n    Fh__MakeFh3 (#inum, #())%V\n  {{{ s, RET (slice_val s, #()); is_fh s inum }}}.\nProof.\n  iIntros (Φ) \"_ HΦ\".\n  wp_pures.\n  wp_call.\n  wp_apply wp_new_enc.\n  iIntros (enc) \"Henc\".\n  wp_apply (wp_Enc__PutInt with \"Henc\"); first by word.\n  iIntros \"Henc\".\n  wp_apply (wp_Enc__Finish with \"Henc\").\n  iIntros (s data) \"(%Henc & %Hlen & Hs)\".\n  iDestruct (is_slice_to_small with \"Hs\") as \"Hs\".\n  iMod (readonly_alloc_1 with \"Hs\") as \"Hs\".\n  wp_pures.\n  iApply \"HΦ\".\n  iExists _. iFrame. done.\nQed.\n\nLemma elem_of_covered_inodes (x:u64) :\n  x ∈ covered_inodes ↔ (2 ≤ int.Z x < 32)%Z.\nProof.\n  rewrite /covered_inodes.\n  rewrite rangeSet_lookup //.\nQed.\n\nTheorem wp_validInum (i : u64) :\n  {{{ True }}}\n    validInum #i\n  {{{ (valid : bool), RET #valid; ⌜ valid = true <-> i ∈ covered_inodes ⌝ }}}.\nProof.\n  iIntros (Φ) \"_ HΦ\".\n  wp_call.\n  wp_if_destruct.\n  { iApply \"HΦ\". rewrite elem_of_covered_inodes.\n    iPureIntro.\n    split; [ inversion 1 | intros ].\n    move: H; word. }\n  wp_if_destruct.\n  { iApply \"HΦ\". rewrite elem_of_covered_inodes.\n    iPureIntro.\n    split; [ inversion 1 | intros ].\n    move: H; word. }\n  wp_call.\n  change (int.Z (word.divu _ _)) with 32%Z.\n  wp_if_destruct.\n  { iApply \"HΦ\". rewrite elem_of_covered_inodes.\n    iPureIntro.\n    split; [ inversion 1 | intros ].\n    word. }\n  iApply \"HΦ\".\n  iPureIntro. intuition.\n  rewrite elem_of_covered_inodes.\n  split; [ | word ].\n  assert (i ≠ U64 0) as Hnot_0%(not_inj (f:=int.Z)) by congruence.\n  assert (i ≠ U64 1) as Hnot_1%(not_inj (f:=int.Z)) by congruence.\n  change (int.Z 0%Z) with 0%Z in *.\n  change (int.Z 1%Z) with 1%Z in *.\n  word.\nQed.\n\nLemma is_inode_crash_next γsrc γnext fh state blk :\n  fh [[γsrc]]↦ state ∗\n  ( is_inode fh state (durable_mapsto_own γnext)\n    ∨ is_inode_enc fh (length state) blk (durable_mapsto_own γnext)\n    ∗ is_inode_data (length state) blk state (durable_mapsto_own γnext) )\n  -∗ is_inode_stable γsrc γnext fh.\nProof.\n  iIntros \"[Hfh Hi]\".\n  iExists _. iFrame.\n  iDestruct \"Hi\" as \"[$|[He Hd]]\".\n  iExists _. iFrame.\nQed.\n\nLemma is_inode_crash_prev γsrc γprev γnext fh state blk :\n  txn_cinv Njrnl γprev γnext -∗\n  fh [[γsrc]]↦ state ∗\n  ( is_inode fh state (durable_mapsto γprev)\n    ∨ is_inode_enc fh (length state) blk (durable_mapsto γprev)\n    ∗ is_inode_data (length state) blk state (durable_mapsto γprev) )\n  -∗\n  |C={⊤}=>\n  is_inode_stable γsrc γnext fh.\nProof.\n  iIntros \"#Hcinv [Hfh H]\".\n\n  iDestruct (@liftable _ _ _ _ _ (λ m, is_inode fh state m ∨ is_inode_enc fh (length state) blk m ∗ is_inode_data (length state) blk state m)%I with \"H\") as (mlift) \"[H #Hrestore]\".\n\n  iMod (exchange_durable_mapsto with \"[$Hcinv $H]\") as \"H\".\n  iDestruct (\"Hrestore\" with \"H\") as \"H\".\n\n  iModIntro.\n  iApply is_inode_crash_next; iFrame.\nQed.\n\nLemma is_inode_crash_prev_own γsrc γprev γnext fh state blk :\n  txn_cinv Njrnl γprev γnext -∗\n  fh [[γsrc]]↦ state ∗\n  ( is_inode fh state (durable_mapsto_own γprev)\n    ∨ is_inode_enc fh (length state) blk (durable_mapsto_own γprev)\n    ∗ is_inode_data (length state) blk state (durable_mapsto_own γprev) )\n  -∗\n  |C={⊤}=>\n  is_inode_stable γsrc γnext fh.\nProof.\n  iIntros \"#Hcinv [Hfh H]\".\n\n  iDestruct (liftable_mono (Φ := λ m, is_inode fh state m\n      ∨ is_inode_enc fh (length state) blk m\n        ∗ is_inode_data (length state) blk state m)%I\n    _ (durable_mapsto γprev) with \"H\") as \"H\".\n  { iIntros (??) \"[_ $]\". }\n\n  iApply (is_inode_crash_prev with \"Hcinv\"). iFrame.\nQed.\n\nLemma is_inode_stable_crash γsrc γprev γnext fh :\n  txn_cinv Njrnl γprev γnext -∗\n  is_inode_stable γsrc γprev fh\n  -∗\n  |C={⊤}=>\n  is_inode_stable γsrc γnext fh.\nProof.\n  iIntros \"#Hcinv\".\n  rewrite /is_inode_stable.\n  iDestruct 1 as (?) \"(H1&H2)\".\n  iApply is_inode_crash_prev_own; iFrame \"∗#\".\n  Unshelve.\n  exact (U64 0).\nQed.\n\nEnd heap.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/simple/common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24943367392062052}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition find_lock_rec_spec0 (g_rd: Pointer) (rec_list: Pointer) (rec_idx: Z64) (adt: RData) : option (RData * Pointer) :=\n    match g_rd, rec_list, rec_idx with\n    | (_g_rd_base, _g_rd_ofst), (_rec_list_base, _rec_list_ofst), VZ64 _rec_idx =>\n      rely is_int64 _rec_idx;\n      when'' _g_rec_base, _g_rec_ofst, adt == realm_get_rec_entry_spec (VZ64 _rec_idx) (_rec_list_base, _rec_list_ofst) adt;\n      rely is_int _g_rec_ofst;\n      when _t'10 == is_null_spec (_g_rec_base, _g_rec_ofst) adt;\n      rely is_int _t'10;\n      if (_t'10 =? 1) then\n        Some (adt, (_g_rec_base, _g_rec_ofst))\n      else\n        when adt == granule_lock_spec (_g_rec_base, _g_rec_ofst) adt;\n        when _t'9, adt == granule_get_state_spec (_g_rec_base, _g_rec_ofst) adt;\n        rely is_int _t'9;\n        if (_t'9 =? 3) then\n          when'' _t'3_base, _t'3_ofst == get_g_rec_rd_spec (_g_rec_base, _g_rec_ofst) adt;\n          rely is_int _t'3_ofst;\n          when _t'4 == ptr_eq_spec (_t'3_base, _t'3_ofst) (_g_rd_base, _g_rd_ofst) adt;\n          rely is_int _t'4;\n          if (_t'4 =? 1) then\n            when'' _t'6_base, _t'6_ofst, adt == realm_get_rec_entry_spec (VZ64 _rec_idx) (_rec_list_base, _rec_list_ofst) adt;\n            rely is_int _t'6_ofst;\n            when _t'7 == ptr_eq_spec (_t'6_base, _t'6_ofst) (_g_rec_base, _g_rec_ofst) adt;\n            rely is_int _t'7;\n            let _t'5 := (_t'7 =? 1) in\n            if _t'5 then\n              Some (adt, (_g_rec_base, _g_rec_ofst))\n            else\n              when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt;\n              when'' _t'2_base, _t'2_ofst == null_ptr_spec  adt;\n              rely is_int _t'2_ofst;\n              Some (adt, (_t'2_base, _t'2_ofst))\n          else\n            let _t'5 := 0 in\n            when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt;\n            when'' _t'2_base, _t'2_ofst == null_ptr_spec  adt;\n            rely is_int _t'2_ofst;\n            Some (adt, (_t'2_base, _t'2_ofst))\n        else\n          when adt == granule_unlock_spec (_g_rec_base, _g_rec_ofst) adt;\n          when'' _t'8_base, _t'8_ofst == null_ptr_spec  adt;\n          rely is_int _t'8_ofst;\n          Some (adt, (_t'8_base, _t'8_ofst))\n     end\n    .\n\nEnd SpecLow.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/PSCIAux/LowSpecs/find_lock_rec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.24934540126481736}}
{"text": "Require Import CertiGraph.lib.Ensembles_ext.\nRequire Import Coq.Lists.List.\nRequire Import VST.msl.seplog.\nRequire Import VST.msl.log_normalize.\nRequire Import VST.msl.Coqlib2.\nRequire Import CertiGraph.lib.Coqlib.\nRequire Import CertiGraph.lib.EquivDec_ext.\nRequire Import CertiGraph.lib.relation_list.\nRequire Import CertiGraph.msl_ext.log_normalize.\nRequire Import CertiGraph.msl_ext.iter_sepcon.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.path_lemmas.\nRequire Import CertiGraph.graph.reachable_computable.\nRequire Import CertiGraph.graph.reachable_ind.\nRequire Import CertiGraph.graph.subgraph2.\nRequire Import CertiGraph.graph.graph_gen.\nRequire Import CertiGraph.graph.dag.\nRequire Import CertiGraph.graph.weak_mark_lemmas.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import CertiGraph.msl_application.Graph_Mark.\nRequire Import CertiGraph.msl_application.GraphBi.\nRequire Import Coq.Logic.Classical.\n\nOpen Scope logic.\n\nSection PointwiseGraph_Mark_Bi.\n\nContext {pSGG_Bi: pPointwiseGraph_Graph_Bi}.\nContext {sSGG_Bi: sPointwiseGraph_Graph_Bi bool unit}.\n\nLocal Coercion Graph_LGraph: Graph >-> LGraph.\nLocal Coercion LGraph_SGraph: LGraph >-> SGraph.\nLocal Identity Coercion Graph_GeneralGraph: Graph >-> GeneralGraph.\nLocal Identity Coercion LGraph_LabeledGraph: LGraph >-> LabeledGraph.\nLocal Identity Coercion SGraph_PointwiseGraph: SGraph >-> PointwiseGraph.\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nNotation Graph := (@Graph pSGG_Bi bool unit unit).\n\n(* TODO: move this lemma into Graph_Mark.v. *)\nLemma vlabel_eq: forall (g1 g2: Graph) x1 x2, (WeakMarkGraph.marked g1 x1 <-> WeakMarkGraph.marked g2 x2) -> vlabel g1 x1 = vlabel g2 x2.\nProof.\n  intros.\n  simpl in H.\n  destruct H.\n  destruct (vlabel g1 x1), (vlabel g2 x2); try congruence.\n  + tauto.\n  + symmetry; tauto.\nQed.\n\nLemma mark_null_refl: forall (g: Graph), mark null g g.\nProof. intros. apply mark_invalid_refl, invalid_null. Qed.\n\nLemma mark_vgamma_true_refl: forall (g: Graph) root d l r, vgamma g root = (d, l, r) -> d = true -> mark root g g.\nProof.\n  intros.\n  apply mark_marked_root_refl.\n  inversion H.\n  simpl; congruence.\nQed.\n\nLemma Graph_vgen_true_mark1: forall (G: Graph) (x: addr) l r,\n  vgamma G x = (false, l, r) ->\n  vvalid G x ->\n  mark1 x (G: LabeledGraph _ _ _ _ _) (Graph_vgen G x true: LabeledGraph _ _ _ _ _).\nProof.\n  intros.\n  apply WeakMarkGraph.vertex_update_mark1.\n  inversion H; simpl; auto.\nQed.\n\nLemma left_weak_valid: forall (G G1: Graph) (x l r: addr),\n  vgamma G x = (false, l, r) ->\n  vvalid G x ->\n  mark1 x G G1 ->\n  @weak_valid _ _ _ _ G1 _ (maGraph _) l.\nProof.\n  intros.\n  destruct H1 as [? _].\n  eapply weak_valid_si; [symmetry; exact H1 |].\n  eapply gamma_left_weak_valid; eauto.\nQed.\n\nLemma right_weak_valid: forall (G G1 G2: Graph) (x l r: addr),\n  vgamma G x = (false, l, r) ->\n  vvalid G x ->\n  mark1 x G G1 ->\n  mark l G1 G2 ->\n  @weak_valid _ _ _ _ G2 _ (maGraph _) r.\nProof.\n  intros.\n  destruct H1 as [? _].\n  destruct H2 as [_ ?].\n  eapply weak_valid_si; [symmetry; transitivity G1; [exact H1 | exact H2] |].\n  eapply gamma_right_weak_valid; eauto.\nQed.\n\nLemma root_stable_ramify: forall (g: Graph) (x: addr) (gx: bool * addr * addr),\n  vgamma g x = gx ->\n  vvalid g x ->\n  @derives pred _\n    (reachable_vertices_at x g)\n    (vertex_at x gx *\n      (vertex_at x gx -* reachable_vertices_at x g)).\nProof. intros; apply va_reachable_root_stable_ramify; auto. Qed.\n\nLemma root_update_ramify: forall (g: Graph) (x: addr) (lx: bool) (gx gx': bool * addr * addr),\n  vgamma g x = gx ->\n  vgamma (Graph_vgen g x lx) x = gx' ->\n  vvalid g x ->\n  @derives pred _\n    (reachable_vertices_at x g)\n    (vertex_at x gx *\n      (vertex_at x gx' -* reachable_vertices_at x (Graph_vgen g x lx))).\nProof. intros; apply va_reachable_root_update_ramify; auto. Qed.\n\nLemma graph_ramify_left: forall (g g1: Graph) x l r,\n  vvalid g x ->\n  vgamma g x = (false, l, r) ->\n  mark1 x g g1 ->\n  @derives pred _\n    (reachable_vertices_at x g1)\n    (reachable_vertices_at l g1 *\n      (ALL g': Graph,\n        !! (mark l g1 g') -->\n        (reachable_vertices_at l g' -* reachable_vertices_at x g'))).\nProof.\n  intros.\n  apply (mark_list_mark_ramify g g1 _ _ nil _ (r :: nil)); auto.\n  + intros; apply classic.\n  + simpl.\n    eapply gamma_step_list; eauto.\n  + split_relation_list ((lg_gg g1) :: nil); auto.\n    reflexivity.\n  + unfold Included, Ensembles.In; intros.\n    apply vvalid_vguard.\n    rewrite Intersection_spec in H2; destruct H2.\n    apply reachable_foot_valid in H2; auto.\n  + unfold Included, Ensembles.In; intros.\n    apply vvalid_vguard.\n    rewrite Intersection_spec in H3; destruct H3.\n    apply reachable_foot_valid in H3.\n    destruct H2 as [_ [? _]].\n    rewrite <- H2; auto.\nQed.\n\nLemma graph_ramify_right: forall (g g1 g2: Graph) x l r,\n  vvalid g x ->\n  vgamma g x = (false, l, r) ->\n  mark1 x g g1 ->\n  mark l g1 g2 ->\n  (reachable_vertices_at x g2: pred) |-- reachable_vertices_at r g2 *\n   (ALL g': Graph,\n     !! (mark r g2 g') -->\n     (reachable_vertices_at r g' -* reachable_vertices_at x g')).\nProof.\n  intros.\n  apply (mark_list_mark_ramify g g2 _ _ (l :: nil) _ nil); auto.\n  + intros; apply classic.\n  + simpl.\n    eapply gamma_step_list; eauto.\n  + split_relation_list ((lg_gg g1) :: nil); auto.\n    unfold mark_list. simpl map.\n    split_relation_list (@nil (LabeledGraph _ _ bool unit unit)); auto.\n  + unfold Included, Ensembles.In; intros.\n    apply vvalid_vguard.\n    rewrite Intersection_spec in H3; destruct H3.\n    apply reachable_foot_valid in H3; auto.\n  + unfold Included, Ensembles.In; intros.\n    apply vvalid_vguard.\n    rewrite Intersection_spec in H4; destruct H4.\n    apply reachable_foot_valid in H4.\n    destruct H3 as [_ [? _]].\n    rewrite <- H3; auto.\nQed.\n\nLemma mark1_mark_left_mark_right: forall (g1 g2 g3 g4: Graph) root l r,\n  vvalid g1 root ->\n  vgamma g1 root = (false, l, r) ->\n  mark1 root g1 g2 ->\n  mark l g2 g3 ->\n  mark r g3 g4 ->\n  mark root g1 g4.\nProof.\n  intros.\n  apply (mark1_mark_list_mark root (l :: r :: nil)); auto.\n  + intros; simpl.\n    inversion H0.\n    unfold Complement, Ensembles.In.\n    rewrite H5; congruence.\n  + hnf; intros.\n    apply gamma_step with (y := n') in H0; auto.\n    rewrite H0; simpl.\n    pose proof eq_sym_iff n' l.\n    pose proof eq_sym_iff n' r.\n    tauto.\n  + split_relation_list ((lg_gg g2) :: nil); eauto.\n    unfold mark_list.\n    simpl map.\n    split_relation_list ((lg_gg g3) :: nil); eauto.\nQed.\n\nEnd PointwiseGraph_Mark_Bi.\n\n\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/msl_application/GraphBi_Mark.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.24934539603034367}}
{"text": "Require Import Coqlib.\nRequire Import Maps.\n\nRequire Import Integers.\nRequire Import LibTactics.\nOpen Scope Z_scope.\nImport ListNotations.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n(* Word *)\nDefinition Word := int.\n\n(* Address *)\nDefinition Address := prod Z int.\n\n(* Val *)\nInductive Val: Type := W: Word -> Val | Ptr: Address -> Val.\n\n(*** Definition of Registers **)\n(* General Registers *)\nInductive GenReg: Type := \n  | r0: GenReg  | r1: GenReg  | r2: GenReg  | r3: GenReg  | r4: GenReg  | r5: GenReg  | r6: GenReg  | r7: GenReg\n  | r8: GenReg  | r9: GenReg  | r10: GenReg | r11: GenReg | r12: GenReg | r13: GenReg | r14: GenReg | r15: GenReg\n  | r16: GenReg | r17: GenReg | r18: GenReg | r19: GenReg | r20: GenReg | r21: GenReg | r22: GenReg | r23: GenReg\n  | r24: GenReg | r25: GenReg | r26: GenReg | r27: GenReg | r28: GenReg | r29: GenReg | r30: GenReg | r31: GenReg.\n\n(* Auxiliary Registers *)\nInductive AsReg: Type :=\n  | asr0: AsReg  | asr1: AsReg  | asr2: AsReg  | asr3: AsReg  | asr4: AsReg  | asr5: AsReg  | asr6: AsReg  | asr7: AsReg\n  | asr8: AsReg  | asr9: AsReg  | asr10: AsReg | asr11: AsReg | asr12: AsReg | asr13: AsReg | asr14: AsReg | asr15: AsReg\n  | asr16: AsReg | asr17: AsReg | asr18: AsReg | asr19: AsReg | asr20: AsReg | asr21: AsReg | asr22: AsReg | asr23: AsReg\n  | asr24: AsReg | asr25: AsReg | asr26: AsReg | asr27: AsReg | asr28: AsReg | asr29: AsReg | asr30: AsReg | asr31: AsReg.\n\n(* PSR *)\nInductive PsrReg: Type :=\n| n : PsrReg\n| z : PsrReg\n| cwp : PsrReg.\n\n(* Special Registers *)\nInductive SpReg: Type :=\n| Rwim : SpReg\n| Ry : SpReg\n| Rasr : AsReg -> SpReg.\nCoercion Rasr : AsReg >-> SpReg.\n\n(* Register Name *)\nInductive RegName: Type :=\n| Rr : GenReg -> RegName\n| Rpsr : PsrReg -> RegName\n| Rsp : SpReg -> RegName.\nCoercion Rr : GenReg >-> RegName.\nCoercion Rpsr : PsrReg >-> RegName.\nCoercion Rsp : SpReg >-> RegName.\n\nLemma RegName_eq: forall (x y : RegName),\n    {x = y} + {x <> y}.\nProof.\n  repeat decide equality.\nQed.\n\nModule RegNameEq.\n  Definition t := RegName.\n  Definition eq := RegName_eq.\nEnd RegNameEq.\n\nModule RegMap := EMap(RegNameEq).\nDefinition RegFile := RegMap.t (option Val).\n\n(*** Window Register  **)\n(* Frame *)\nInductive Frame : Type :=\n  consfm : Val -> Val -> Val -> Val -> Val -> Val -> Val -> Val -> Frame.\nNotation \" '[[' v0 , v1 , v2 , v3 , v4 , v5 , v6 , v7 ']]'\" :=\n  (consfm v0 v1 v2 v3 v4 v5 v6 v7) (at level 200): code_scope.\n\n(* Frame List *)\nDefinition FrameList : Type := list Frame.\n\n(* RState *)\nDefinition RState : Type := RegFile * FrameList.\n\n(*** Delay List **)\n(* DelayCycle *)\nDefinition DelayCycle := nat.\n\n(* DelayItem *)\nDefinition DelayItem : Type := DelayCycle * SpReg * Word.\n\n(* DelayList *)\nDefinition DelayList : Type := list DelayItem.\n\n(* DelayTime *)\nDefinition X := 3%nat.\n\n(* set_delay *)\nDefinition set_delay (rsp : SpReg) (w : Word) (D : DelayList) :=\n  (X, rsp, w) :: D.\n\n(* getRegs *)\nFixpoint getRegs (D : DelayList) :=\n  match D with\n  | (_, rsp, _) :: D' => rsp :: (getRegs D')\n  | _ => nil\n  end.\n\n(*** Program State **)\n(* Operation Expression *)  \nInductive OpExp : Type :=\n| Or : GenReg -> OpExp\n| Ow : Word -> OpExp.\n\n(* Address Expression *)\nInductive AddrExp : Type :=\n| Ao : OpExp -> AddrExp\n| Aro : GenReg -> OpExp -> AddrExp.\n\nLemma Address_eq: forall (x y : Address),\n    {x = y} + {x <> y}.\nProof. \n  intros; destruct x, y.\n  destruct (Z.eq_dec z0 z1); destruct (Int.eq_dec i i0); subst; eauto; \n    try solve [right; intro; tryfalse].\nQed.\n\n(* memory *)\nModule AddrEq.\n  Definition t := Address.\n  Definition eq := Address_eq.\nEnd AddrEq.\n\nModule MemMap := EMap(AddrEq).\nDefinition Memory := MemMap.t (option Val).\n\n(* Some Operations for memory *)\n(* disjoint *)\nDefinition disjoint {tp tp': Type} (M1 : tp -> option tp') (M2 : tp -> option tp') : Prop :=\n  forall (x : tp),\n    match M1 x, M2 x with\n    | Some _, Some _ => False\n    | Some _, None => True\n    | None, Some _ => True\n    | None, None => True\n    end.\nNotation \"M1 '⊥' M2\" := (disjoint M1 M2) (at level 39) : mem_scope.\n\n(* in dom *)\nDefinition indom {tp tp': Type} (x : tp) (M : tp -> option tp') :=\n  exists v, M x = Some v.\n\n(* is in dom *)\nDefinition is_indom {tp tp' : Type} (x : tp) (M : tp -> option tp') :=\n  match M x with\n  | Some _ => true\n  | None => false\n  end.\n \n(* merge *)\nDefinition merge {tp tp': Type} (M1 : tp -> option tp') (M2 : tp -> option tp') :=\n  fun x => match M1 x with\n        | None => M2 x\n        | Some b => Some b\n        end.\nNotation \"M1 '⊎' M2\" := (merge M1 M2) (at level 39) : mem_scope.\n\n(* emp memory *)\nDefinition empM : Memory := fun (x : Address) => None. \n(* emp register *)\nDefinition empR : RegFile := fun (rn : RegName) => None.\n\n(* Label f *)\nDefinition Label: Type := Word.\n\n(* Program State *)\nDefinition State: Type := Memory * RState * DelayList.\n\n(*** Expression Evalution *)\nNotation \"$ n\" := (Int.repr n)(at level 1) : code_scope.\nNotation \"a <<ᵢ b\" := (Int.shl a b)(at level 1) : code_scope.\nNotation \"a >>ᵢ b\" := (Int.shru a b)(at level 1) : code_scope.\nNotation \"a &ᵢ b\" := (Int.and a b)(at level 1) : code_scope.\nNotation \"a |ᵢ b\" := (Int.or a b)(at level 1) : code_scope.\nNotation \"a +ᵢ b\" := (Int.add a b)(at level 1) : code_scope.\nNotation \"a -ᵢ b\" := (Int.sub a b)(at level 1) : code_scope.\nNotation \"a =ᵢ b\" := (Int.eq a b)(at level 1) : code_scope.\nNotation \"a <ᵢ b\" := (Int.lt a b)(at level 1) : code_scope.\nNotation \"a >ᵢ b\" := (Int.lt b a)(at level 1) : code_scope.\nNotation \"a <=ᵢ b\" := (orb(Int.lt a b)(Int.eq a b))(at level 1) : code_scope.\nNotation \"a >=ᵢ b\" := (orb(Int.lt b a)(Int.eq a b))(at level 1) : code_scope.\nNotation \"a !=ᵢ b\" := (negb(Int.eq a b))(at level 1) : code_scope.\nNotation \"a 'modu' b\" := (Int.modu a b)(at level 1) : code_scope.\nNotation \"a 'xor' b\" := (Int.xor a b)(at level 1) : code_scope.\n\nDefinition int_le a b :=\n  Int.lt a b || Int.eq a b.\nNotation \"A <ᵢ B <ᵢ C\" := (Int.lt A B && Int.lt B C = true)\n                            (at level 2, B at next level) : code_scope. \nNotation \"A <ᵢ B <=ᵢ C\" := (Int.lt A B && int_le B C = true)\n                             (at level 2, B at next level) : code_scope.\nNotation \"A <=ᵢ B <ᵢ C\" := (int_le A B && Int.lt B C = true)\n                             (at level 2, B at next level) : code_scope.        \nNotation \"A <=ᵢ B <=ᵢ C\" := (int_le A B && int_le B C = true)\n                              (at level 2, B at next level) : code_scope.\n\nDefinition int_leu a b :=\n  Int.ltu a b || Int.eq a b.\n\nNotation \"A <ᵤᵢ B <ᵤᵢ C\" := (Int.ltu A B && Int.ltu B C = true)\n                              (at level 2, B at next level) : code_scope.\nNotation \"A <ᵤᵢ B <=ᵤᵢ C\" := (Int.ltu A B && int_leu B C = true)\n                               (at level 2, B at next level) : code_scope.\nNotation \"A <=ᵤᵢ B <ᵤᵢ C\" := (int_leu A B && Int.ltu B C = true)\n                               (at level 2, B at next level) : code_scope.        \nNotation \"A <=ᵤᵢ B <=ᵤᵢ C\" := (int_leu A B && int_leu B C = true)\n                                (at level 2, B at next level) : code_scope.\nNotation \"A <ᵤᵢ B\" := (Int.ltu A B = true)\n                        (at level 2, no associativity) : code_scope.\nNotation \"A <=ᵤᵢ B\" := (int_leu A B = true)\n                         (at level 2, no associativity) : code_scope.\n\nOpen Scope code_scope.\n\nDefinition get_R (R : RegFile) (rn : RegName) :=\n  match (R rn) with\n  | Some v => match rn with\n             | Rr r0 => Some (W ($ 0))\n             | _ => Some v\n             end\n  | None => None\n  end.\n\nDefinition eval_opexp (R : RegFile) (o : OpExp) :=\n  match o with\n  | Or r => get_R R r\n  | Ow w =>\n    if andb (($-4096) <=ᵢ w) (w <=ᵢ ($4095)) then\n      Some (W w)\n    else\n      None\n  end.\n\nDefinition val_add (v1 v2 : Val) :=\n  match v1, v2 with\n  | W w1, W w2 => Some (W (w1 +ᵢ w2))\n  | Ptr (b, ofs), W w => Some (Ptr (b, ofs +ᵢ w))\n  | _, _ => None\n  end.\n\nDefinition val_sub (v1 v2 : Val) :=\n  match v1, v2 with\n  | W w1, W w2 => Some (W (w1 -ᵢ w2))\n  | Ptr (b, ofs), W w => Some (Ptr (b, ofs -ᵢ w))\n  | _, _ => None\n  end.\n\nDefinition eval_addrexp (R : RegFile) (a : AddrExp) :=\n  match a with\n  | Ao o => eval_opexp R o\n  | Aro r o =>\n    match get_R R r with\n    | Some v1 =>\n      match (eval_opexp R o) with\n      | Some v2 => val_add v1 v2\n      | None => None\n      end \n    | None => None\n    end\n  end.\n\n(* set_R set a value in Register *)\nDefinition set_R (R : RegFile) (rn : RegName) (v : Val) :=\n  if is_indom rn R then\n    RegMap.set rn (Some v) R\n  else\n    R.\n\n(* fetch *)\nDefinition fetch_frame {tp} (R : tp -> option Val) (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : tp) :\n  option Frame :=\n  match (R rr0), (R rr1), (R rr2),\n        (R rr3), (R rr4), (R rr5), (R rr6), (R rr7) with\n  | Some v0, Some v1, Some v2, Some v3, Some v4, Some v5, Some v6, Some v7 =>\n    Some ([[v0, v1, v2, v3, v4, v5, v6, v7]])\n  | _, _, _, _, _, _, _, _ => None\n  end.\n\nDefinition fetch (R : RegFile) :=\n  match (fetch_frame R r8 r9 r10 r11 r12 r13 r14 r15),\n        (fetch_frame R r16 r17 r18 r19 r20 r21 r22 r23),\n        (fetch_frame R r24 r25 r26 r27 r28 r29 r30 r31) with\n  | Some fmo, Some fml, Some fmi =>\n    Some (fmo :: fml :: fmi :: nil)\n  | _, _, _ => None\n  end.\n\n(* exe_delay *)\nFixpoint exe_delay (R : RegFile) (D : DelayList) : RegFile * DelayList :=\n  match D with\n  | (0%nat, rsp, w) :: D =>\n    let (R', D') := exe_delay R D in\n    (set_R R' rsp (W w), D')\n  | (S k, rsp, w) :: D =>\n    let (R', D') := exe_delay R D in\n    (R', (k, rsp, w) :: D')\n  | nil => (R, D)\n  end.\n", "meta": {"author": "jpzha", "repo": "VeriSparc", "sha": "7fc60fbc4b4357b93836d1b461d7d27c669e9f58", "save_path": "github-repos/coq/jpzha-VeriSparc", "path": "github-repos/coq/jpzha-VeriSparc/VeriSparc-7fc60fbc4b4357b93836d1b461d7d27c669e9f58/coqimp/framework/models/state.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.24925380755045362}}
{"text": "(** This file collects facts on proof irrelevant types/propositions. *)\nFrom stdpp Require Export base.\nFrom stdpp Require Import options.\n\nGlobal Hint Extern 200 (ProofIrrel _) => progress (lazy beta) : typeclass_instances.\n\nInstance True_pi: ProofIrrel True.\nProof. intros [] []; reflexivity. Qed.\nInstance False_pi: ProofIrrel False.\nProof. intros []. Qed.\nInstance unit_pi: ProofIrrel ().\nProof. intros [] []; reflexivity. Qed.\nInstance and_pi (A B : Prop) :\n  ProofIrrel A → ProofIrrel B → ProofIrrel (A ∧ B).\nProof. intros ?? [??] [??]. f_equal; trivial. Qed.\nInstance prod_pi (A B : Type) :\n  ProofIrrel A → ProofIrrel B → ProofIrrel (A * B).\nProof. intros ?? [??] [??]. f_equal; trivial. Qed.\nInstance eq_pi {A} (x : A) `{∀ z, Decision (x = z)} (y : A) :\n  ProofIrrel (x = y).\nProof.\n  set (f z (H : x = z) :=\n    match decide (x = z) return x = z with\n    | left H => H | right H' => False_rect _ (H' H)\n    end).\n  assert (∀ z (H : x = z),\n    eq_trans (eq_sym (f x (eq_refl x))) (f z H) = H) as help.\n  { intros ? []. destruct (f x eq_refl); tauto. }\n  intros p q. rewrite <-(help _ p), <-(help _ q).\n  unfold f at 2 4. destruct (decide _); [reflexivity|]. exfalso; tauto.\nQed.\nInstance Is_true_pi (b : bool) : ProofIrrel (Is_true b).\nProof. destruct b; simpl; apply _. Qed.\nLemma sig_eq_pi `(P : A → Prop) `{∀ x, ProofIrrel (P x)}\n  (x y : sig P) : x = y ↔ `x = `y.\nProof.\n  split; [intros <-; reflexivity|].\n  destruct x as [x Hx], y as [y Hy]; simpl; intros; subst.\n  f_equal. apply proof_irrel.\nQed.\nInstance proj1_sig_inj `(P : A → Prop) `{∀ x, ProofIrrel (P x)} :\n  Inj (=) (=) (proj1_sig (P:=P)).\nProof. intros ??. apply (sig_eq_pi P). Qed.\nLemma exists_proj1_pi `(P : A → Prop) `{∀ x, ProofIrrel (P x)}\n  (x : sig P) p : `x ↾ p = x.\nProof. apply (sig_eq_pi _); reflexivity. Qed.\n", "meta": {"author": "ybertot", "repo": "stdpp", "sha": "eacf774cff761d815f42e24619f801c4b3aad38a", "save_path": "github-repos/coq/ybertot-stdpp", "path": "github-repos/coq/ybertot-stdpp/stdpp-eacf774cff761d815f42e24619f801c4b3aad38a/theories/proof_irrel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.24925380755045357}}
{"text": "Require Export Iron.Language.SystemF2Effect.Step.Frame.\nRequire Export Iron.Language.SystemF2Effect.Store.Bind.\n\n(********************************************************************)\n(* All region handles in this effect have corresponding\n   FUse frames in the frame stack. *)\nDefinition LiveEs (fs : stack) (es : list ty)\n := Forall (fun e1 => forall p2,  handleOfEffect e1 = Some p2\n                   -> (exists m1, In (FPriv m1 p2) fs))\n           es.\n\n\nDefinition LiveE  (fs : stack) (e : ty)\n := LiveEs fs (flattenT e).\n\n\n(*******************************************************************)\nLemma liveEs_equivTs\n :  forall  ke sp es1 es2 fs\n ,  EquivTs ke sp es1 es2 KEffect\n -> LiveEs  fs es1\n -> LiveEs  fs es2.\nProof.\n intros. inverts H.\n unfold LiveEs in *.\n snorm.\n apply  H4 in H.\n eapply H0 in H; eauto.\nQed.\n\n\nLemma liveE_equivT_left\n :  forall ke sp e1 e2 fs\n ,  EquivT ke sp e1 e2 KEffect\n -> LiveE  fs e2\n -> LiveE  fs e1.\nProof.\n intros.\n unfold LiveE in *.\n eapply liveEs_equivTs.\n - eapply equivT_equivTs; auto.\n   eapply EqSym.\n   + eauto.\n   + have (KindT ke sp e2 KEffect).\n     eauto.\n   + auto.\n - auto.\nQed.\n\n\nLemma liveE_equivT_right\n :  forall ke sp e1 e2 fs\n ,  EquivT ke sp e1 e2 KEffect\n -> LiveE  fs e1\n -> LiveE  fs e2.\nProof.\n intros.\n unfold LiveE in *.\n eapply liveEs_equivTs.\n - eapply equivT_equivTs; eauto.\n - auto.\nQed.\n\n\n(*******************************************************************)\nLemma liveEs_subsTs\n :  forall ke sp es1 es2 fs\n ,  SubsTs ke sp es1 es2 KEffect\n -> LiveEs fs es1\n -> LiveEs fs es2.\nProof.\n intros. inverts H.\n unfold LiveEs in *.\n snorm.\n eapply H0; eauto.\nQed.\n\n\nLemma liveE_subsT\n :  forall ke sp e1 e2 fs\n ,  SubsT ke sp e1 e2 KEffect\n -> LiveE fs e1\n -> LiveE fs e2.\nProof.\n intros.\n unfold LiveE in *.\n eapply liveEs_subsTs.\n - eapply subsT_subsTs in H; eauto.\n - auto.\nQed.\nHint Resolve liveE_subsT.\n\n\n(********************************************************************)\nLemma liveE_sum_above\n :  forall e1 e2 fs\n ,  LiveE  fs e1 -> LiveE fs e2\n -> LiveE  fs (TSum e1 e2).\nProof.\n intros.\n unfold LiveE. simpl.\n unfold LiveEs.\n eapply Forall_app; eauto.\nQed.\nHint Resolve liveE_sum_above.\n\n\nLemma liveE_sum_above_left\n :  forall fs e1 e2\n ,  LiveE fs (TSum e1 e2)\n -> LiveE fs e1.\nProof.\n intros.\n unfold LiveE  in *.\n unfold LiveEs in *.\n snorm. eauto.\nQed.\nHint Resolve liveE_sum_above_left.\n\n\nLemma liveE_sum_above_right\n :  forall fs e1 e2\n ,  LiveE fs (TSum e1 e2)\n -> LiveE fs e2.\nProof.\n intros.\n unfold LiveE  in *.\n unfold LiveEs in *.\n snorm. eauto.\nQed.\n\n\n(********************************************************************)\nLemma liveE_frame_cons\n :  forall fs f e\n ,  LiveE  fs        e\n -> LiveE  (fs :> f) e.\nProof.\n intros.\n unfold LiveE in *.\n unfold LiveEs in *.\n snorm. firstorder.\nQed.\nHint Resolve liveE_frame_cons.\n\n\nLemma liveE_pop_flet\n :  forall fs t x e\n ,  LiveE  (fs :> FLet t x) e\n -> LiveE  fs e.\nProof.\n intros.\n unfold LiveE in *.\n unfold LiveEs in *.\n snorm.\n spec H x0. rip.\n spec H p2. rip.\n firstorder. nope.\nQed.\n\n\nLemma liveE_maskOnVarT\n :  forall fs e n\n ,  LiveE  fs (maskOnVarT n e)\n -> LiveE  fs e.\nProof.\n intros.\n unfold LiveE in *.\n unfold LiveEs in *.\n snorm.\n spec H x.\n apply handleOfEffect_form_some in H1.\n destruct H1 as [tc]. rip.\n eapply maskOnVar_effect_remains in H0.\n - eapply H in H0; eauto.\n   snorm. nope.\n - eauto.\nQed.\n\n\nLemma liveE_phase_change\n :  forall fs m1 p e\n ,  LiveE (fs :> FPriv m1 p) e\n -> LiveE (fs :> FPriv m1 p) (substTT 0 (TRgn p) e).\nProof.\n intros.\n induction e; snorm;\n  try (solve [unfold LiveE in *;\n              unfold LiveEs in *;\n              snorm; inverts H0; nope]).\n\n - Case \"TSum\".\n   eapply liveE_sum_above.\n   + eapply liveE_sum_above_left  in H; eauto.\n   + eapply liveE_sum_above_right in H; eauto.\n\n - Case \"TCon1\".\n   destruct e;\n    unfold LiveE; unfold LiveEs; snorm;\n    try (solve [inverts H0; snorm; nope]).\n   exists m1.\n   inverts H0.\n   + snorm.\n   + nope.\nQed.\n\n\nLemma liveE_fpriv_in\n :  forall e p2 fs\n ,  LiveE fs e\n -> handleOfEffect e = Some p2\n -> (exists m1, In (FPriv m1 p2) fs).\nProof.\n intros.\n unfold LiveE  in *.\n unfold LiveEs in *.\n snorm.\n eapply handleOfEffect_form_some in H0.\n destruct H0 as [tc]. rip.\n snorm.\n lets D: H (TCon1 tc (TRgn p2)). clear H.\n eapply D. snorm. snorm. nope.\nQed.\n\n\nGlobal Opaque LiveE.\n", "meta": {"author": "DonaldKellett", "repo": "iron-lambda", "sha": "0ce17223c4ff2c65549ead3f9905f60adfd6a40a", "save_path": "github-repos/coq/DonaldKellett-iron-lambda", "path": "github-repos/coq/DonaldKellett-iron-lambda/iron-lambda-0ce17223c4ff2c65549ead3f9905f60adfd6a40a/done/Iron/Language/SystemF2Effect/Store/LiveE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.24925380755045354}}
{"text": "Require Import oeuf.Common.\nRequire Import oeuf.HList.\nRequire Import oeuf.Utopia.\n\nRequire oeuf.SourceValues.\nInclude oeuf.SourceValues.\n\nRequire Import oeuf.OpaqueOps.\n\n\n(* an eliminator that takes cases with types given by the first index,\n   eliminates a target with type given by the second index,\n   and produces a result with type given by the third index *)\n(* Extend this if you want to extend Oeuf *)\nInductive elim : list type -> type -> type -> Type :=\n| ENat : forall ty, elim [ty; Arrow (ADT Tnat) (Arrow ty ty)] (ADT Tnat) ty\n| EBool : forall ty, elim [ty; ty] (ADT Tbool) ty\n| EList : forall tyA ty, elim [ty; Arrow (ADT tyA) (Arrow (ADT (Tlist tyA)) (Arrow ty ty))] (ADT (Tlist tyA)) ty\n| EUnit : forall ty, elim [ty] (ADT Tunit) ty\n| EPair : forall ty1 ty2 ty, elim [Arrow (ADT ty1) (Arrow (ADT ty2) ty)] (ADT (Tpair ty1 ty2)) ty\n| EOption : forall tyA ty, elim [Arrow (ADT tyA) ty; ty] (ADT (Toption tyA)) ty\n| EPositive : forall ty, elim [Arrow (ADT Tpositive) (Arrow ty ty);\n                          Arrow (ADT Tpositive) (Arrow ty ty);\n                          ty] (ADT Tpositive) ty\n| EN : forall ty, elim\n        [ ty\n        ; Arrow (ADT Tpositive) ty\n        ] (ADT TN) ty\n| EZ : forall ty, elim\n        [ ty\n        ; Arrow (ADT Tpositive) ty\n        ; Arrow (ADT Tpositive) ty\n        ] (ADT TZ) ty\n(*| EAscii : forall ty, elim [ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty;\n                            ty; ty; ty; ty; ty; ty; ty; ty]\n                           (ADT Tascii) ty*)\n| EAscii : forall ty, elim [Arrow (ADT Tbool)\n                               (Arrow (ADT Tbool)\n                                  (Arrow (ADT Tbool)\n                                     (Arrow (ADT Tbool)\n                                        (Arrow (ADT Tbool)\n                                           (Arrow (ADT Tbool)\n                                              (Arrow (ADT Tbool)\n                                                 (Arrow (ADT Tbool)\n                                                    ty)))))))]\n                            (ADT Tascii) ty\n                                                        \n                                                                                            \n.\n\nSection expr.\n(* since these types make hlists of recursive calls, the auto-generated schemes are garbage. *)\nLocal Unset Elimination Schemes.\n\nInductive expr {G : list (type * list type * type)} {L : list type} : type -> Type :=\n| Value : forall {ty}, @value G ty -> expr ty\n| Var : forall {ty}, member ty L -> expr ty\n| App : forall {ty1 ty2}, expr (Arrow ty1 ty2) -> expr ty1 -> expr ty2\n| Constr : forall {ty ctor arg_tys} (ct : constr_type ctor arg_tys ty),\n        hlist (expr) arg_tys ->\n        expr (ADT ty)\n| Close : forall {arg_ty free_tys ret_ty},\n        member (arg_ty, free_tys, ret_ty) G ->\n        hlist (expr) free_tys ->\n        expr (Arrow arg_ty ret_ty)\n| Elim : forall {case_tys target_tyn ty} (e : elim case_tys (ADT target_tyn) ty),\n    hlist (expr) case_tys ->\n    expr (ADT target_tyn) ->\n    expr ty\n| OpaqueOp : forall {arg_tys ret_ty},\n        opaque_oper arg_tys ret_ty ->\n        hlist expr arg_tys ->\n        expr ret_ty\n.\n\nEnd expr.\nImplicit Arguments expr.\n\nInductive is_value {G L ty} : expr G L ty -> Prop :=\n| IsValue : forall v, is_value (Value v).\n\nDefinition is_value_dec {G L ty} : forall (e : expr G L ty), { is_value e } + { ~ is_value e }.\ndestruct e.\n1: left; constructor.\nall: right; hide; inversion 1.\nDefined.\n\nDefinition body_expr G fn_sig :=\n    let '(arg_ty, free_tys, ret_ty) := fn_sig in\n    expr G (arg_ty :: free_tys) ret_ty.\n\n\n(* weakening: convert an expr in `G` into an expr in an extension of `G` *)\n\nDefinition weaken_value {G} fn_sig :\n        forall {ty}, value G ty -> value (fn_sig :: G) ty :=\n    let fix go {ty} (v : value G ty) : value (fn_sig :: G) ty :=\n        let fix go_hlist {tys} (vs : hlist (value G) tys) : hlist (value (fn_sig :: G)) tys :=\n            match vs with\n            | hnil => hnil\n            | hcons v vs => hcons (go v) (go_hlist vs)\n            end in\n        match v with\n        | VConstr ct args => VConstr ct (go_hlist args)\n        | VClose mb free => VClose (There mb) (go_hlist free)\n        | VOpaque v => VOpaque v\n        end in @go.\n\nDefinition weaken_value_hlist {G} fn_sig :\n        forall {tys}, hlist (value G) tys -> hlist (value (fn_sig :: G)) tys :=\n    let go := @weaken_value G fn_sig in\n    let fix go_hlist {tys} (vs : hlist (value G) tys) : hlist (value (fn_sig :: G)) tys :=\n        match vs with\n        | hnil => hnil\n        | hcons v vs => hcons (go _ v) (go_hlist vs)\n        end in @go_hlist.\n\nDefinition weaken_expr {G L} fn_sig :\n        forall {ty}, expr G L ty -> expr (fn_sig :: G) L ty :=\n    let fix go {ty} (e : expr G L ty) : expr (fn_sig :: G) L ty :=\n        let fix go_hlist {tys} (es : hlist (expr G L) tys) : hlist (expr (fn_sig :: G) L) tys :=\n            match es with\n            | hnil => hnil\n            | hcons e es => hcons (go e) (go_hlist es)\n            end in\n        match e with\n        | Value v => Value (weaken_value fn_sig v)\n        | Var mb => Var mb\n        | App f a => App (go f) (go a)\n        | Constr ctor args => Constr ctor (go_hlist args)\n        | Close mb free => Close (There mb) (go_hlist free)\n        | Elim e cases target => Elim e (go_hlist cases) (go target)\n        | OpaqueOp op args => OpaqueOp op (go_hlist args)\n        end\n    in @go.\n\nDefinition weaken_expr_hlist {G L} fn_sig :\n        forall {tys}, hlist (expr G L) tys -> hlist (expr (fn_sig :: G) L) tys :=\n    let go := @weaken_expr G L fn_sig in\n    let fix go_hlist {tys} (es : hlist (expr G L) tys) : hlist (expr (fn_sig :: G) L) tys :=\n        match es with\n        | hnil => hnil\n        | hcons e es => hcons (go _ e) (go_hlist es)\n        end in @go_hlist.\n\nDefinition weaken_body {G} fn_sig :\n        forall {sig}, body_expr G sig -> body_expr (fn_sig :: G) sig :=\n    fun sig =>\n        match sig as sig_ return body_expr _ sig_ -> body_expr _ sig_ with\n        | (arg_ty, free_tys, fn_ty) => fun e => weaken_expr fn_sig e\n        end.\n\n\n\n(* (static) global environments.  Similar to an hlist, but each value can refer\n   to the tail that comes after it. *)\n\nInductive genv : list (type * list type * type) -> Type :=\n| GenvNil : genv []\n| GenvCons : forall {fn_sig rest},\n        body_expr rest fn_sig ->\n        genv rest ->\n        genv (fn_sig :: rest).\n\nDefinition mtail {A x} l : @member A x l -> list A.\ninduction 1.\n- exact l.\n- exact IHX.\nDefined.\n\n(* retrieve a value from a genv *)\nFixpoint gget {G} (g : genv G) {fn_sig} (mb : member fn_sig G) {struct g} :\n        body_expr (mtail G mb) fn_sig * genv (mtail G mb).\nrename G into ixs. rename g into vals.\nrename fn_sig into ix.\n\npattern ixs, vals, mb.\nrefine (\n    match vals as vals_ in genv ixs_\n        return\n            forall (mb_ : member ix ixs_), _ ixs_ vals_ mb_ with\n    | GenvNil => fun mb => _\n    | @GenvCons ix' ixs val vals => fun mb => _\n    end mb\n).\n\n  { exfalso.\n    refine (\n        match mb in member _ [] with\n        | Here => idProp\n        | There _ => idProp\n        end). }\n\nspecialize (gget ixs vals).\npattern ix', ixs, mb.\npattern ix', ixs, mb in gget.\nrefine (\n    match mb as mb_ in member _ (ix'_ :: ixs_)\n        return\n            forall (val_ : body_expr ixs_ ix'_) (vals_ : genv ixs_)\n                (gget_ : _ ix'_ ixs_ mb_),\n            _ ix'_ ixs_ mb_ with\n    | @Here _ _ ixs => fun val vals gget => _\n    | @There _ _ ix ixs mb' => fun val vals gget => _\n    end val vals gget).\n\n- simpl. exact (val, vals).\n- simpl. eapply gget.\nDefined.\n\n(* retrieve a value from a genv, and weaken it to be valid in the whole genv *)\nFixpoint gget_weaken {G} (g : genv G) {fn_sig} (mb : member fn_sig G) {struct g} :\n        body_expr G fn_sig.\nrename G into ixs. rename g into vals.\nrename fn_sig into ix.\n\npattern ixs, vals, mb.\nrefine (\n    match vals as vals_ in genv ixs_\n        return\n            forall (mb_ : member ix ixs_), _ ixs_ vals_ mb_ with\n    | GenvNil => fun mb => _\n    | @GenvCons ix' ixs val vals => fun mb => _\n    end mb\n).\n\n  { exfalso.\n    refine (\n        match mb in member _ [] with\n        | Here => idProp\n        | There _ => idProp\n        end). }\n\nspecialize (gget_weaken ixs vals).\npattern ix', ixs, mb.\npattern ix', ixs, mb in gget_weaken.\nrefine (\n    match mb as mb_ in member _ (ix'_ :: ixs_)\n        return\n            forall (val_ : body_expr ixs_ ix'_) (vals_ : genv ixs_)\n                (gget_ : _ ix'_ ixs_ mb_),\n            _ ix'_ ixs_ mb_ with\n    | @Here _ _ ixs => fun val vals gget_weaken => _\n    | @There _ _ ix ixs mb' => fun val vals gget_weaken => _\n    end val vals gget_weaken).\n\n- simpl. exact (weaken_body _ val).\n- simpl. exact (weaken_body _ (gget_weaken _ mb')).\nDefined.\n\n(* denotation functions *)\n(* Extend this if you want to extend Oeuf *)\nDefinition elim_denote {case_tys target_ty ty} (e : elim case_tys target_ty ty) :\n  hlist type_denote case_tys -> type_denote target_ty -> type_denote ty :=\n  match e with\n  | EBool _ => fun cases target => (bool_rect _ (hhead cases) (hhead (htail cases)) target)\n  | ENat _ => fun cases target => (nat_rect _ (hhead cases) (hhead (htail cases)) target)\n  | EList _ _ => fun cases target => (list_rect _ (hhead cases) (hhead (htail cases)) target)\n  | EUnit _ => fun cases target => unit_rect _ (hhead cases) target\n  | EPair _ _ _ => fun cases target => prod_rect _ (hhead cases) target\n  | EOption _ _ => fun cases target => option_rect _ (hhead cases) (hhead (htail cases)) target\n  | EPositive _ => fun cases target => positive_rect _ (hhead cases) (hhead (htail cases))\n                                                 (hhead (htail (htail cases))) target\n  | EN _ => fun cases target =>\n          N_rect _\n              (hhead cases)\n              (hhead (htail cases))\n              target\n  | EZ _ => fun cases target =>\n          Z_rect _\n              (hhead cases)\n              (hhead (htail cases))\n              (hhead (htail (htail cases)))\n              target\n  | EAscii _ => fun cases target =>\n          Ascii.ascii_rect _\n              (hhead cases)\n              target\n              \n  (*  | EAscii _ => fun cases target =>\n          @ascii_rect _\n              (hhead cases)                     \n              (hhead (htail cases))\n              (hhead (htail (htail cases)))\n              (hhead (htail (htail (htail cases))))\n              (hhead (htail (htail (htail (htail cases)))))\n              (hhead (htail (htail (htail (htail (htail cases))))))\n              (hhead (htail (htail (htail (htail (htail (htail cases)))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail cases))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              (hhead (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail (htail cases))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))\n              target*)\n  end.\n\nDefinition expr_denote {G L} (g : hlist func_type_denote G) (l : hlist type_denote L) :\n        forall {ty}, expr G L ty -> type_denote ty :=\n    let fix go {ty} (e : expr G L ty) {struct e} : type_denote ty :=\n        let fix go_hlist {tys} (es : hlist (expr G L) tys) {struct es} : hlist type_denote tys :=\n            match es with\n            | hnil => hnil\n            | hcons e es => hcons (go e) (go_hlist es)\n            end in\n        match e with\n        | Value v => value_denote g v\n        | Var mb => hget l mb\n        | App f a => (go f) (go a)\n        | Constr ct args => constr_denote ct (go_hlist args)\n        | Close mb free =>\n            let func := hget g mb in\n            let free' := go_hlist free in\n            fun x => func free' x\n        | Elim e cases target => elim_denote e (go_hlist cases) (go target)\n        | OpaqueOp op args => opaque_oper_denote op (go_hlist args)\n        end in @go.\n\nDefinition expr_hlist_denote {G L} (g : hlist func_type_denote G) (l : hlist type_denote L) :\n        forall {tys}, hlist (expr G L) tys -> hlist type_denote tys :=\n    let go := @expr_denote G L g l in\n    let fix go_hlist {tys} (vs : hlist (expr G L) tys) : hlist type_denote tys :=\n        match vs with\n        | hnil => hnil\n        | hcons v vs => hcons (go _ v) (go_hlist vs)\n        end in @go_hlist.\n\nDefinition body_expr_denote\n        {G} (g : hlist func_type_denote G)\n        {fn_sig} (e : body_expr G fn_sig) :\n        func_type_denote fn_sig :=\n    match fn_sig as fn_sig_ return body_expr G fn_sig_ -> func_type_denote fn_sig_ with\n    | (arg_ty, free_tys, ret_ty) => fun e =>\n            fun l x => expr_denote g (hcons x l) e\n    end e.\n\nDefinition genv_denote {G} (g : genv G) : hlist func_type_denote G :=\n    let fix go {G} (g : genv G) : hlist func_type_denote G :=\n        match g with\n        | GenvNil => hnil\n        | GenvCons e g' =>\n                let g'_den := go g' in\n                hcons (body_expr_denote g'_den e) g'_den\n        end in go g.\n\n\n(* program states *)\n\n(* `cont G rty ty`: a continuation, valid in global environment `G`, that\n   requires a value of type `ty`, and eventually proceeds to a `Stop` state\n   containing a result value of type `rty` (assuming termination). *)\nInductive cont {G} {rty : type} : type -> Type :=\n| KAppL {L ty1 ty2}\n        (e2 : expr G L ty1)\n        (l : hlist (value G) L)\n        (k : cont ty2)\n        : cont (Arrow ty1 ty2)\n| KAppR {L ty1 ty2}\n        (e1 : expr G L (Arrow ty1 ty2))\n        (l : hlist (value G) L)\n        (k : cont ty2)\n        : cont ty1\n| KConstr {L vtys ety etys ctor ty}\n        (ct : constr_type ctor (vtys ++ [ety] ++ etys) ty)\n        (vs : hlist (expr G L) vtys)\n        (es : hlist (expr G L) etys)\n        (l : hlist (value G) L)\n        (k : cont (ADT ty))\n        : cont ety\n| KClose {L vtys ety etys arg_ty ret_ty}\n        (mb : member (arg_ty, vtys ++ [ety] ++ etys, ret_ty) G)\n        (vs : hlist (expr G L) vtys)\n        (es : hlist (expr G L) etys)\n        (l : hlist (value G) L)\n        (k : cont (Arrow arg_ty ret_ty))\n        : cont ety\n| KElim {L case_tys target_tyn ty}\n        (e : elim case_tys (ADT target_tyn) ty)\n        (cases : hlist (expr G L) case_tys)\n        (l : hlist (value G) L)\n        (k : cont ty)\n        : cont (ADT target_tyn)\n| KOpaqueOp {L vtys ety etys ret_ty}\n        (op : opaque_oper (vtys ++ [ety] ++ etys) ret_ty)\n        (vs : hlist (expr G L) vtys)\n        (es : hlist (expr G L) etys)\n        (l : hlist (value G) L)\n        (k : cont ret_ty)\n        : cont ety\n| KStop : cont rty\n.\nImplicit Arguments cont [].\n\n(* `state G rty`: a state, valid in global environment `G`, that will\n   eventually proceed to a `Stop` state containing a result value of type `rty`\n   (assuming termination). *)\nInductive state {G rty} :=\n| Run {L ty}\n        (e : expr G L ty)\n        (l : hlist (value G) L)\n        (k : cont G rty ty)\n| Stop (v : value G rty).\nImplicit Arguments state [].\n\n(* denotation of program states *)\n\nDefinition cont_denote {G rty ty} (g : hlist func_type_denote G) (k : cont G rty ty) :\n        type_denote ty -> type_denote rty :=\n    let locals_denote {tys} (l : hlist _ tys) := value_hlist_denote g l in\n    let fix go {ty} (k : cont G rty ty) :=\n        match k in cont _ _ ty_ return type_denote ty_ -> type_denote rty with\n        | KAppL e2 l k => fun x => go k (x (expr_denote g (locals_denote l) e2))\n        | KAppR e1 l k => fun x => go k ((expr_denote g (locals_denote l) e1) x)\n        | KConstr ct vs es l k => fun x =>\n                let l' := locals_denote l in\n                let vs' := expr_hlist_denote g l' vs in\n                let es' := expr_hlist_denote g l' es in\n                go k (constr_denote ct (happ vs' (hcons x es')))\n        | KClose mb vs es l k => fun x =>\n                let l' := locals_denote l in\n                let vs' := expr_hlist_denote g l' vs in\n                let es' := expr_hlist_denote g l' es in\n                let func := hget g mb in\n                go k (fun arg => func (happ vs' (hcons x es')) arg)\n        | KElim e cases l k => fun x =>\n                let l' := locals_denote l in\n                let cases' := expr_hlist_denote g l' cases in\n                go k (elim_denote e cases' x)\n        | KOpaqueOp op vs es l k => fun x =>\n                let l' := locals_denote l in\n                let vs' := expr_hlist_denote g l' vs in\n                let es' := expr_hlist_denote g l' es in\n                go k (opaque_oper_denote op (happ vs' (hcons x es')))\n        | KStop => fun x => x\n        end in go k.\n\nDefinition state_denote {G rty} (g : hlist func_type_denote G) (s : state G rty) :\n        type_denote rty :=\n    match s with\n    | Run e l k =>\n            let e' := expr_denote g (value_hlist_denote g l) e in\n            let k' := cont_denote g k in\n            k' e'\n    | Stop v => value_denote g v\n    end.\n\n\n(* operational semantics - step relation *)\n\n(* helper function for proceeding into a continuation *)\nDefinition run_cont {G rty ty} (k : cont G rty ty) : value G ty -> state G rty :=\n    match k in cont _ _ ty_ return value G ty_ -> state G rty with\n    | KAppL e2 l k => fun v => Run (App (Value v) e2) l k\n    | KAppR e1 l k => fun v => Run (App e1 (Value v)) l k\n    | KConstr ct vs es l k =>\n            fun v => Run (Constr ct (happ vs (hcons (Value v) es))) l k\n    | KClose mb vs es l k =>\n            fun v => Run (Close mb (happ vs (hcons (Value v) es))) l k\n    | KElim e cases l k =>\n            fun v => Run (Elim e cases (Value v)) l k\n    | KOpaqueOp op vs es l k =>\n            fun v => Run (OpaqueOp op (happ vs (hcons (Value v) es))) l k\n    | KStop => fun v => Stop v\n    end.\n\n(* helper function for the \"eliminate\" step.  Analogous to `unroll_elim` in\n   later passes. *)\nSection run_elim.\n\n(* some useful notations for building the resulting terms *)\nLocal Notation \"f $ a\" := (App f a) (at level 50, left associativity, only parsing).\n\nLocal Notation \"'h0' x\" := (hhead x) (only parsing, at level 0).\nLocal Notation \"'h1' x\" := (hhead (htail x)) (only parsing, at level 0).\nLocal Notation \"'h2' x\" := (hhead (htail (htail x))) (only parsing, at level 0).\nLocal Notation \"'h3' x\" := (hhead (htail (htail (htail x)))) (only parsing, at level 0).\nLocal Notation \"'h4' x\" := (hhead (htail (htail (htail (htail x))))) (only parsing, at level 0).\nLocal Notation \"'h5' x\" := (hhead (htail (htail (htail (htail (htail x)))))) (only parsing, at level 0).\nLocal Notation \"'h6' x\" := (hhead (htail (htail (htail (htail (htail (htail x))))))) (only parsing, at level 0).\nLocal Notation \"'h7' x\" := (hhead (htail (htail (htail (htail (htail (htail (htail x)))))))) (only parsing, at level 0).\nLocal Notation \"'h8' x\" := (hhead (htail (htail (htail (htail (htail (htail (htail (htail x))))))))) (only parsing, at level 0).\n\nDefinition run_elim {G L case_tys target_tyn ret_ty}\n        (e : elim case_tys (ADT target_tyn) ret_ty)\n        (cases : hlist (expr G L) case_tys)\n        (target : value G (ADT target_tyn))\n        : expr G L ret_ty.\nrevert e. pattern target_tyn, target.\nlet f := match goal with [ |- ?f target_tyn target ] => f end in\nrefine match target as target_ in value _ (ADT target_tyn_)\n        return f target_tyn_ target_ with\n    | @VConstr _  target_tyn ctor arg_tys  ct args => _\n    | VOpaque _ => _\n    end; intros; cycle 1.\n  { inversion e. }\nclear target target_tyn0.\n\n(* note: if you add any new cases here, you must also add cases to\n   run_elim_denote in SourceLiftedProofs.v *)\nrevert cases ct. pattern case_tys, target_tyn, ret_ty.\nrefine match e in elim case_tys_ (ADT target_tyn_) ret_ty_\n        return _ case_tys_ target_tyn_ ret_ty_ with\n    | ENat ret_ty => _\n    | EBool ret_ty => _\n    | EList item_ty ret_ty => _\n    | EUnit ret_ty => _\n    | EPair ty1 ty2 ret_ty => _\n    | EOption item_ty ret_ty => _\n    | EPositive ret_ty => _\n    | EN ret_ty => _\n    | EZ ret_ty => _\n    | EAscii ret_ty => _\n    (*| EAscii ret_ty => _*)\n    end; intros;\nclear e target_tyn ret_ty0 case_tys.\n\n\n- revert args cases. pattern ctor, arg_tys.\n  refine match ct in constr_type ctor_ arg_tys_ (Tnat) return _ ctor_ arg_tys_ with\n      | CTS => _\n      | CTO => _\n      end; intros; clear ct arg_tys ctor.\n  + exact (h0 cases).\n  + refine (h1 cases $ Value (h0 args) $ _).\n    exact (Elim (ENat _) cases (Value (h0 args))).\n\n- revert args cases. pattern ctor, arg_tys.\n  refine match ct in constr_type ctor_ arg_tys_ (Tbool) return _ ctor_ arg_tys_ with\n      | CTtrue => _\n      | CTfalse => _\n      end; intros; clear ct arg_tys ctor.\n  + exact (h0 cases).\n  + exact (h1 cases).\n\n- revert args cases. pattern ctor, arg_tys, item_ty.\n  refine match ct in constr_type ctor_ arg_tys_ (Tlist item_ty_)\n          return _ ctor_ arg_tys_ item_ty_ with\n      | CTnil item_ty => _\n      | CTcons item_ty => _\n      end; intros; clear ct arg_tys ctor  item_ty0.\n  + exact (h0 cases).\n  + refine (h1 cases $ Value (h0 args) $ Value (h1 args) $ _).\n    exact (Elim (EList _ _) cases (Value (h1 args))).\n\n- revert args cases. pattern ctor, arg_tys.\n  refine match ct in constr_type ctor_ arg_tys_ (Tunit)\n          return _ ctor_ arg_tys_ with\n      | CTtt => _\n      end; intros; clear ct arg_tys ctor.\n  + exact (h0 cases).\n\n- revert args cases. pattern ctor, arg_tys, ty1, ty2.\n  refine match ct in constr_type ctor_ arg_tys_ (Tpair ty1_ ty2_)\n          return _ ctor_ arg_tys_ ty1_ ty2_ with\n      | CTpair ty1 ty2 => _\n      end; intros; clear ct arg_tys ctor  ty0 ty3.\n  + exact (h0 cases $ Value (h0 args) $ Value (h1 args)).\n\n- revert args cases. pattern ctor, arg_tys, item_ty.\n  refine match ct in constr_type ctor_ arg_tys_ (Toption item_ty_)\n          return _ ctor_ arg_tys_ item_ty_ with\n      | CTsome item_ty => _\n      | CTnone item_ty => _\n      end; intros; clear ct arg_tys ctor  item_ty0.\n  + exact (h0 cases $ Value (h0 args)).\n  + exact (h1 cases).\n\n- revert args cases. pattern ctor, arg_tys.\n  refine match ct in constr_type ctor_ arg_tys_ (Tpositive)\n          return _ ctor_ arg_tys_ with\n      | CTxI => _\n      | CTxO => _\n      | CTxH => _\n      end; intros; clear ct arg_tys ctor.\n  + refine (h0 cases $ Value (h0 args) $ _).\n    exact (Elim (EPositive _) cases (Value (h0 args))).\n  + refine (h1 cases $ Value (h0 args) $ _).\n    exact (Elim (EPositive _) cases (Value (h0 args))).\n  + exact (h2 cases).\n\n- revert args cases. pattern ctor, arg_tys.\n  refine match ct in constr_type ctor_ arg_tys_ (TN)\n          return _ ctor_ arg_tys_ with\n      | CTN0 => _\n      | CTNpos => _\n      end; intros; clear ct arg_tys ctor.\n  + exact (h0 cases).\n  + exact (h1 cases $ Value (h0 args)).\n\n- revert args cases. pattern ctor, arg_tys.\n  refine match ct in constr_type ctor_ arg_tys_ (TZ)\n          return _ ctor_ arg_tys_ with\n      | CTZ0 => _\n      | CTZpos => _\n      | CTZneg => _\n      end; intros; clear ct arg_tys ctor.\n  + exact (h0 cases).\n  + exact (h1 cases $ Value (h0 args)).\n  + exact (h2 cases $ Value (h0 args)).\n\n- revert args cases. pattern ctor, arg_tys.\n  refine match ct in constr_type ctor_ arg_tys_ (Tascii)\n          return _ ctor_ arg_tys_ with\n      | CTAscii => _\n      end; intros; clear ct arg_tys ctor.\n  + exact (h0 cases $ Value (h0 args) $ Value (h1 args) $ Value (h2 args) $ Value (h3 args)\n              $ Value (h4 args) $ Value (h5 args) $ Value (h6 args) $ Value (h7 args)).\n\n\n(*    \n- revert args cases. pattern ctor, arg_tys.\n  refine match ct in constr_type ctor_ arg_tys_ (Tascii) return _ ctor_ arg_tys_ with\n         | CTascii_0 => _\n         | CTascii_1 => _\n         | CTascii_2 => _\n         | CTascii_3 => _\n         | CTascii_4 => _\n         | CTascii_5 => _\n         | CTascii_6 => _\n         | CTascii_7 => _\n         | CTascii_8 => _\n         | CTascii_9 => _\n         | CTascii_10 => _\n         | CTascii_11 => _\n         | CTascii_12 => _\n         | CTascii_13 => _\n         | CTascii_14 => _\n         | CTascii_15 => _\n         | CTascii_16 => _\n         | CTascii_17 => _\n         | CTascii_18 => _\n         | CTascii_19 => _\n         | CTascii_20 => _\n         | CTascii_21 => _\n         | CTascii_22 => _\n         | CTascii_23 => _\n         | CTascii_24 => _\n         | CTascii_25 => _\n         | CTascii_26 => _\n         | CTascii_27 => _\n         | CTascii_28 => _\n         | CTascii_29 => _\n         | CTascii_30 => _\n         | CTascii_31 => _\n         | CTascii_32 => _\n         | CTascii_33 => _\n         | CTascii_34 => _\n         | CTascii_35 => _\n         | CTascii_36 => _\n         | CTascii_37 => _\n         | CTascii_38 => _\n         | CTascii_39 => _\n         | CTascii_40 => _\n         | CTascii_41 => _\n         | CTascii_42 => _\n         | CTascii_43 => _\n         | CTascii_44 => _\n         | CTascii_45 => _\n         | CTascii_46 => _\n         | CTascii_47 => _\n         | CTascii_48 => _\n         | CTascii_49 => _\n         | CTascii_50 => _\n         | CTascii_51 => _\n         | CTascii_52 => _\n         | CTascii_53 => _\n         | CTascii_54 => _\n         | CTascii_55 => _\n         | CTascii_56 => _\n         | CTascii_57 => _\n         | CTascii_58 => _\n         | CTascii_59 => _\n         | CTascii_60 => _\n         | CTascii_61 => _\n         | CTascii_62 => _\n         | CTascii_63 => _\n         | CTascii_64 => _\n         | CTascii_65 => _\n         | CTascii_66 => _\n         | CTascii_67 => _\n         | CTascii_68 => _\n         | CTascii_69 => _\n         | CTascii_70 => _\n         | CTascii_71 => _\n         | CTascii_72 => _\n         | CTascii_73 => _\n         | CTascii_74 => _\n         | CTascii_75 => _\n         | CTascii_76 => _\n         | CTascii_77 => _\n         | CTascii_78 => _\n         | CTascii_79 => _\n         | CTascii_80 => _\n         | CTascii_81 => _\n         | CTascii_82 => _\n         | CTascii_83 => _\n         | CTascii_84 => _\n         | CTascii_85 => _\n         | CTascii_86 => _\n         | CTascii_87 => _\n         | CTascii_88 => _\n         | CTascii_89 => _\n         | CTascii_90 => _\n         | CTascii_91 => _\n         | CTascii_92 => _\n         | CTascii_93 => _\n         | CTascii_94 => _\n         | CTascii_95 => _\n         | CTascii_96 => _\n         | CTascii_97 => _\n         | CTascii_98 => _\n         | CTascii_99 => _\n         | CTascii_100 => _\n         | CTascii_101 => _\n         | CTascii_102 => _\n         | CTascii_103 => _\n         | CTascii_104 => _\n         | CTascii_105 => _\n         | CTascii_106 => _\n         | CTascii_107 => _\n         | CTascii_108 => _\n         | CTascii_109 => _\n         | CTascii_110 => _\n         | CTascii_111 => _\n         | CTascii_112 => _\n         | CTascii_113 => _\n         | CTascii_114 => _\n         | CTascii_115 => _\n         | CTascii_116 => _\n         | CTascii_117 => _\n         | CTascii_118 => _\n         | CTascii_119 => _\n         | CTascii_120 => _\n         | CTascii_121 => _\n         | CTascii_122 => _\n         | CTascii_123 => _\n         | CTascii_124 => _\n         | CTascii_125 => _\n         | CTascii_126 => _\n         | CTascii_127 => _\n      end; intros; clear ct arg_tys ctor.\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).\n  + exact (h0 cases).*)\nDefined.\n\nEnd run_elim.\n\n(* the actual step relation *)\nInductive sstep {G rty} (g : genv G) : state G rty -> state G rty -> Prop :=\n| SValue : forall {L ty} v (l : hlist (value G) L) (k : cont G rty ty),\n        sstep g (Run (Value v) l k)\n                (run_cont k v)\n\n| SVar : forall {L ty} mb (l : hlist (value G) L) (k : cont G rty ty),\n        sstep g (Run (Var mb) l k)\n                (Run (Value (hget l mb)) l k)\n\n| SAppL : forall {L ty1 ty2} (e1 : expr G L (Arrow ty1 ty2)) (e2 : expr G L ty1) l k,\n        ~ is_value e1 ->\n        sstep g (Run (App e1 e2) l k)\n                (Run e1 l (KAppL e2 l k))\n\n| SAppR : forall {L ty1 ty2} (e1 : expr G L (Arrow ty1 ty2)) (e2 : expr G L ty1) l k,\n        is_value e1 ->\n        ~ is_value e2 ->\n        sstep g (Run (App e1 e2) l k)\n                (Run e2 l (KAppR e1 l k))\n\n| SMakeCall : forall {L arg_ty free_tys ret_ty}\n            (mb : member (arg_ty, free_tys, ret_ty) G) free arg\n            (l : hlist _ L) k,\n        sstep g (Run (App (Value (VClose mb free)) (Value arg)) l k)\n                (Run (gget_weaken g mb) (hcons arg free) k)\n\n| SConstrStep : forall {L vtys ety etys ctor ty}\n            (ct : constr_type ctor (vtys ++ [ety] ++ etys) ty)\n            (vs : hlist (expr G L) vtys)\n            (e : expr G L ety)\n            (es : hlist (expr G L) etys)\n            (l : hlist _ L) k,\n        HForall (@is_value G L) vs ->\n        ~ is_value e ->\n        sstep g (Run (Constr ct (happ vs (hcons e es))) l k)\n                (Run e l (KConstr ct vs es l k))\n\n| SConstrDone : forall {L vtys ctor ty}\n            (ct : constr_type ctor vtys ty)\n            (vs : hlist (value G) vtys)\n            (l : hlist _ L) k,\n        let es := hmap (@Value G L) vs in\n        sstep g (Run (Constr ct es) l k)\n                (Run (Value (VConstr ct vs)) l k)\n\n| SCloseStep : forall {L vtys ety etys arg_ty ret_ty}\n            (mb : member (arg_ty, vtys ++ [ety] ++ etys, ret_ty) G)\n            (vs : hlist (expr G L) vtys)\n            (e : expr G L ety)\n            (es : hlist (expr G L) etys)\n            (l : hlist _ L) k,\n        HForall (@is_value G L) vs ->\n        ~ is_value e ->\n        sstep g (Run (Close mb (happ vs (hcons e es))) l k)\n                (Run e l (KClose mb vs es l k))\n\n| SCloseDone : forall {L vtys arg_ty ret_ty}\n            (mb : member (arg_ty, vtys, ret_ty) G)\n            (vs : hlist (value G) vtys)\n            (l : hlist _ L) k,\n        let es := hmap (@Value G L) vs in\n        sstep g (Run (Close mb es) l k)\n                (Run (Value (VClose mb vs)) l k)\n\n| SElimTarget : forall {L case_tys target_tyn ty}\n            (e : elim case_tys (ADT target_tyn) ty)\n            (cases : hlist (expr G L) case_tys)\n            (target : expr G L (ADT target_tyn))\n            (l : hlist _ L) k,\n        ~ is_value target ->\n        sstep g (Run (Elim e cases target) l k)\n                (Run target l (KElim e cases l k))\n\n| SEliminate : forall {L case_tys target_tyn ty}\n            (e : elim case_tys (ADT target_tyn) ty)\n            (cases : hlist (expr G L) case_tys)\n            (target : value G (ADT target_tyn))\n            (l : hlist _ L) k,\n        sstep g (Run (Elim e cases (Value target)) l k)\n                (Run (run_elim e cases target) l k)\n\n| SOpaqueOpStep : forall {L vtys ety etys ret_ty}\n            (op : opaque_oper (vtys ++ [ety] ++ etys) ret_ty)\n            (vs : hlist (expr G L) vtys)\n            (e : expr G L ety)\n            (es : hlist (expr G L) etys)\n            (l : hlist _ L) k,\n        HForall (@is_value G L) vs ->\n        ~ is_value e ->\n        sstep g (Run (OpaqueOp op (happ vs (hcons e es))) l k)\n                (Run e l (KOpaqueOp op vs es l k))\n\n| SOpaqueOpDone : forall {L vtys ret_ty}\n            (op : opaque_oper vtys ret_ty)\n            (vs : hlist (value G) vtys)\n            (l : hlist _ L) k,\n        let es := hmap (@Value G L) vs in\n        sstep g (Run (OpaqueOp op es) l k)\n                (Run (Value (opaque_oper_denote_source op vs)) l k)\n.\n\n\n\n\n(* example program *)\n\nSection add.\n\nDefinition add_elim a b :=\n    @nat_rect (fun _ => nat -> nat)     (* this is `add` *)\n        (fun b => b)\n        (fun a IHa b => IHa (S b))\n        a b.\n\nDefinition add_lifted :=\n    let Hzero := fun b => b in\n    let Hsucc_2 := fun a IHa => fun b => IHa (S b) in\n    let Hsucc_1 := fun a => fun IHa => Hsucc_2 a IHa in\n    let Hsucc := fun a => Hsucc_1 a in\n    let add_1 := fun a => fun b => @nat_rect (fun _ => nat -> nat) Hzero Hsucc a b in\n    let add := fun a => add_1 a in\n    add.\n\nLemma add_lifted_eq : add_elim = add_lifted.\nreflexivity.\nQed.\n\nLocal Notation \"t1 '~>' t2\" := (Arrow t1 t2) (right associativity, at level 100, only parsing).\nLocal Notation \"'N'\" := (ADT Tnat) (only parsing).\n\nDefinition add_G' :=\n    [ (* Hzero *) (N, [], N)\n    ; (* Hsucc_2 *) (N, [N ~> N; N], N)\n    ; (* Hsucc_1 *) (N ~> N, [N], N ~> N)\n    ; (* Hsucc   *) (N, [], (N ~> N) ~> N ~> N)\n    ; (* add_1 *) (N, [N], N)\n    ; (* add   *) (N, [], N ~> N)\n    ].\n\nDefinition add_G := rev add_G'.\n\nTactic Notation \"member_num\" int_or_var(i) :=\n    do i eapply There; eapply Here.\n\nDefinition add_Hzero : body_expr (skipn 6 add_G) (N, [], N).\nsimpl.\neapply Var. member_num 0.\nDefined.\n\nDefinition add_Hsucc_2 : body_expr (skipn 5 add_G) (N, [N ~> N; N], N).\nsimpl.\neapply App.\n- eapply Var. member_num 1.\n- eapply Constr.\n  + eapply CTS.\n  + eapply hcons. { eapply Var. member_num 0. }\n    eapply hnil.\nDefined.\n\nDefinition add_Hsucc_1 : body_expr (skipn 4 add_G) (N ~> N, [N], N ~> N).\nsimpl.\neapply Close.\n- member_num 0.\n- eapply hcons. { eapply Var. member_num 0. }\n  eapply hcons. { eapply Var. member_num 1. }\n  eapply hnil.\nDefined.\n\nDefinition add_Hsucc : body_expr (skipn 3 add_G) (N, [], (N ~> N) ~> N ~> N).\nsimpl.\neapply Close.\n- member_num 0.\n- eapply hcons. { eapply Var. member_num 0. }\n  eapply hnil.\nDefined.\n\nDefinition add_add_1 : body_expr (skipn 2 add_G) (N, [N], N).\nsimpl.\neapply App. eapply Elim.\n- eapply ENat.\n- eapply hcons. { eapply Close.  member_num 3.  eapply hnil. }\n  eapply hcons. { eapply Close.  member_num 0.  eapply hnil. }\n  eapply hnil.\n- eapply Var. member_num 1.\n- eapply Var. member_num 0.\nDefined.\n\nDefinition add_add : body_expr (skipn 1 add_G) (N, [], N ~> N).\nsimpl.\neapply Close.\n- member_num 0.\n- eapply hcons. { eapply Var.  member_num 0. }\n  eapply hnil.\nDefined.\n\nDefinition add_genv : genv add_G :=\n    (GenvCons add_add\n    (GenvCons add_add_1\n    (GenvCons add_Hsucc\n    (GenvCons add_Hsucc_1\n    (GenvCons add_Hsucc_2\n    (GenvCons add_Hzero\n    (GenvNil))))))).\n\n(* Eval compute -[type_denote] in genv_denote add_genv. *)\n\nDefinition add_denoted := hhead (genv_denote add_genv) hnil.\n(* Eval compute in add_denoted 1 2. *)\n\nLemma add_denoted_eq : add_denoted = add_elim.\nreflexivity.\nQed.\n\nDefinition zero : value add_G N := VConstr CTO hnil.\nDefinition one : value add_G N := VConstr CTS (hcons zero hnil).\nDefinition two : value add_G N := VConstr CTS (hcons one hnil).\nDefinition three : value add_G N := VConstr CTS (hcons two hnil).\n(* Eval compute in value_denote (genv_denote add_genv) three. *)\n\nEnd add.\n\n\n\n(* induction schemes for expr *)\n\nDefinition expr_rect_mut_comb G L\n        (P : forall {ty}, expr G L ty -> Type)\n        (Pl : forall {tys}, hlist (expr G L) tys -> Type)\n    (HValue : forall {ty} (v : value G ty), P (Value v))\n    (HVar : forall {ty} (mb : member ty L), P (Var mb))\n    (HApp : forall {ty1 ty2} (f : expr G L (Arrow ty1 ty2)) (a : expr G L ty1),\n        P f -> P a -> P (App f a))\n    (HConstr : forall {ty ctor arg_tys} (ct : constr_type ctor arg_tys ty) args,\n        Pl args -> P (Constr ct args))\n    (HClose : forall {arg_ty free_tys ret_ty} (mb : member (arg_ty, free_tys, ret_ty) G) free,\n        Pl free -> P (Close mb free))\n    (HElim : forall {case_tys target_tyn ty} (e : elim case_tys (ADT target_tyn) ty) cases target,\n        Pl cases -> P target -> P (Elim e cases target))\n    (HOpaqueOp : forall {arg_tys ret_ty} (op : opaque_oper arg_tys ret_ty) args,\n        Pl args -> P (OpaqueOp op args))\n    (Hhnil : Pl hnil)\n    (Hhcons : forall {ty tys} (e : expr G L ty) (es : hlist (expr G L) tys),\n        P e -> Pl es -> Pl (hcons e es)) :\n    (forall {ty} (e : expr G L ty), P e) *\n    (forall {tys} (e : hlist (expr G L) tys), Pl e) :=\n    let fix go {ty} (e : expr G L ty) :=\n        let fix go_hlist {tys} (es : hlist (expr G L) tys) :=\n            match es as es_ return Pl es_ with\n            | hnil => Hhnil\n            | hcons e es => Hhcons e es (go e) (go_hlist es)\n            end in\n        match e as e_ return P e_ with\n        | Value v => HValue v\n        | Var mb => HVar mb\n        | App f a => HApp f a (go f) (go a)\n        | Constr ct args => HConstr ct args (go_hlist args)\n        | Close mb free => HClose mb free (go_hlist free)\n        | Elim e cases target => HElim e cases target (go_hlist cases) (go target)\n        | OpaqueOp op args => HOpaqueOp op args (go_hlist args)\n        end in\n    let fix go_hlist {tys} (es : hlist (expr G L) tys) :=\n        match es as es_ return Pl es_ with\n        | hnil => Hhnil\n        | hcons e es => Hhcons e es (go e) (go_hlist es)\n        end in\n    (@go, @go_hlist).\n\nDefinition expr_rect_mut G L P Pl HValue HVar HApp HConstr HClose HElim HOpaqueOp Hhnil Hhcons :=\n    fst (expr_rect_mut_comb G L P Pl HValue HVar HApp HConstr HClose HElim HOpaqueOp Hhnil Hhcons).\n\n\n\n(* induction schemes for glist * member *)\n\nLemma genv_member_rect ix\n        (P : forall ixs, genv ixs -> member ix ixs -> Type)\n    (HHere : forall ixs val vals,\n        P (ix :: ixs) (GenvCons val vals) Here)\n    (HThere : forall ix' ixs val vals mb\n        (IHmb : P ixs vals mb),\n        P (ix' :: ixs) (GenvCons val vals) (There mb))\n    : forall G g mb, P G g mb.\ninduction g using genv_rect; intros.\n\n- exfalso.\n  refine (\n    match mb in member _ [] with\n    | Here => idProp\n    | There mb' => idProp\n    end).\n\n- rename fn_sig into ix'. rename rest into ixs.\n  rename b into val. rename g into vals.\n  rename IHg into IHvals.\n\n  refine (\n    match mb as mb_ in member _ (ix'_ :: ixs_)\n        return (\n            forall (val_ : body_expr ixs_ ix'_) (vals_ : genv ixs_)\n                (IHvals_ : forall mb, P ixs_ vals_ mb),\n            P (ix'_ :: ixs_) (GenvCons val_ vals_) mb_) with\n    | Here => _\n    | There mb' => _\n    end val vals IHvals); intros.\n\n  + eapply HHere.\n  + eapply HThere. eapply IHvals_.\nDefined.\n\nLemma genv_member_ind ix\n        (P : forall ixs, genv ixs -> member ix ixs -> Prop)\n    (HHere : forall ixs val vals,\n        P (ix :: ixs) (GenvCons val vals) Here)\n    (HThere : forall ix' ixs val vals mb\n        (IHmb : P ixs vals mb),\n        P (ix' :: ixs) (GenvCons val vals) (There mb))\n    : forall G g mb, P G g mb.\napply genv_member_rect; assumption.\nQed.\n\n\n\n(* semantics *)\n\nInductive is_callstate {G} (g : genv G) : forall {ty1 ty2},\n        value G (Arrow ty1 ty2) -> value G ty1 -> state G ty2 -> Prop :=\n| IsCallstate : forall arg_ty free_tys ret_ty\n            (mb : member (arg_ty, free_tys, ret_ty) G) free av,\n        let fv := VClose mb free in\n        is_callstate g fv av\n            (Run (gget_weaken g mb) (hcons av free) KStop).\n\nInductive final_state {G} : forall {ty}, state G ty -> value G ty -> Prop :=\n| FinalState : forall ty (v : value G ty),\n        final_state (Stop v) v.\n\n\n(* misc *)\n\nDefinition g_nfree (g : type * list type * type) : nat :=\n    let '(_, free_tys, _) := g in\n    length free_tys.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/SourceLifted.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.24917494959846412}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n  Copyright 2018 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Export Simulator.\nRequire Export PBFT.\nRequire Export PBFTcollision_resistant.\nRequire Import Ascii String.\n(*Require Import SHA256.*)\n\n\n(*\n    We'll define here an instance of PBFT so that we can simulate it.\n *)\n\n\n\n(* ================== INSTANCE OF PBFT ================== *)\n\nSection PBFTinstance.\n\n(*  Class NumNodes := MkNumNodes { total_num_faults : nat; total_num_clients : nat }.\n  Context { p_num_nodes : NumNodes }.*)\n\n\n  (* ============================================ *)\n  (* total_num_faults *)\n  Definition F := 1.\n\n  (* total_num_clients is C+1 *)\n  Definition C := 0.\n\n  (* max requests in progress *)\n  Definition MIP := 2.\n\n  (* water-mark range *)\n  Definition WMR := 200.\n\n  (* checkpoint period *)\n  Definition CP := 100.\n  (* ============================================ *)\n\n\n  Definition pbft_digest : Set := list nat.\n\n  Lemma pbft_digest_deq : Deq pbft_digest.\n  Proof.\n    introv; apply list_eq_dec.\n    apply deq_nat.\n  Defined.\n\n  Inductive sending_key_stub : Set :=\n  | pbft_sending_key_stub.\n\n  Inductive receiving_key_stub : Set :=\n  | pbft_receiving_key_stub.\n\n  Definition pbft_sending_key   : Set := sending_key_stub.\n  Definition pbft_receiving_key : Set := receiving_key_stub.\n\n  (*Definition F : nat := 1.*)\n  Definition nreps (F : nat) : nat := 3 * F + 1.\n\n  Definition replica (F : nat) : Set := nat_n (nreps F).\n\n  Lemma replica_deq (F : nat) : Deq (replica F).\n  Proof.\n    apply nat_n_deq.\n  Defined.\n\n  Definition reps2nat (F : nat) : replica F -> nat_n (nreps F) := fun n => n.\n\n  Lemma bijective_reps2nat (F : nat) : bijective (reps2nat F).\n  Proof.\n    exists (fun n : nat_n (nreps F) => n); introv; unfold reps2nat; auto.\n  Defined.\n\n  Definition nclients (C : nat) : nat := S C.\n\n  Definition client (C : nat) : Set := nat_n (nclients C).\n\n  Definition client0 (C : nat) : client C.\n  Proof.\n    exists 0.\n    apply leb_correct.\n    unfold nclients.\n    omega.\n  Defined.\n\n  Lemma client_deq (C : nat) : Deq (client C).\n  Proof.\n    apply nat_n_deq.\n  Defined.\n\n  Definition clients2nat (C : nat) : client C -> nat_n (nclients C) := fun n => n.\n\n  Lemma bijective_clients2nat (C : nat) : bijective (clients2nat C).\n  Proof.\n    exists (fun n : nat_n (nclients C) => n); introv; unfold clients2nat; auto.\n  Defined.\n\n  Inductive operation :=\n  | opr_add (n : nat)\n  | opr_sub (n : nat).\n\n  Lemma operation_deq : Deq operation.\n  Proof.\n    introv; destruct x as [n|n], y as [m|m]; prove_dec;\n      destruct (deq_nat n m); subst; prove_dec.\n  Defined.\n\n  Definition smState : Set := nat.\n  Definition result : Set := nat.\n\n  Definition operation_upd (C : nat) (c : client C) (state : smState) (opr : operation) : result * smState :=\n    match opr with\n    | opr_add m => let k := state + m in (k,k)\n    | opr_sub m => let k := state - m in (k,k)\n    end.\n\n  Inductive PBFTtoken_stub : Set :=\n  | pbft_token_stub.\n\n  Definition pbft_token : Set := PBFTtoken_stub.\n\n  Lemma pbft_token_deq : Deq pbft_token.\n  Proof.\n    introv; destruct x, y; simpl; prove_dec.\n  Defined.\n\n  Global Instance PBFT_I_context : PBFTcontext :=\n    MkPBFTcontext\n      (* max in progress *)\n      MIP\n\n      (* water mark range *)\n      WMR\n\n      (* checkpoint period *)\n      CP\n\n      (* digest type *)\n      pbft_digest\n\n      (* digest decider *)\n      pbft_digest_deq\n\n      (* token type *)\n      pbft_token\n\n      (* token decider *)\n      pbft_token_deq\n\n      (* sending key type *)\n      pbft_sending_key\n\n      (* receiving key type *)\n      pbft_receiving_key\n\n      (* number of faults *)\n      F\n\n      (* replica type *)\n      (replica F)\n\n      (* Replica decider *)\n      (replica_deq F)\n\n      (* replica 2 nat *)\n      (reps2nat F)\n\n      (* proof that reps2nat is bijective *)\n      (bijective_reps2nat F)\n\n      (* number of clients *)\n      (nclients C)\n\n      (* client type *)\n      (client C)\n\n      (* client decider *)\n      (client_deq C)\n\n      (* client 2 nat *)\n      (clients2nat C)\n\n      (* proof that clients2nat is bijective *)\n      (bijective_clients2nat C)\n\n      (* operation type *)\n      operation\n\n      (* operation decider *)\n      operation_deq\n\n      (* result type *)\n      result\n\n      (* result decider *)\n      deq_nat\n\n      (* state type *)\n      smState\n\n      (* initial state *)\n      0\n\n      (* update function *)\n      (operation_upd C)\n\n      (* delay in ms *)\n      1000.\n\n\n  Definition pbft_create_signature\n             (m  : PBFTBare_Msg)\n             (ks : sending_keys) : PBFTtokens := [pbft_token_stub].\n\n  Definition pbft_verify_signature\n             (m : PBFTBare_Msg)\n             (n : name)\n             (k : receiving_key)\n             (a : pbft_token) : bool := true.\n\n  Global Instance PBFT_I_auth : PBFTauth :=\n    MkPBFTauth pbft_create_signature pbft_verify_signature.\n\n\n  Definition pbft_lookup_replica_sending_key   (src : Rep)    : pbft_sending_key   := pbft_sending_key_stub.\n  Definition pbft_lookup_replica_receiving_key (dst : Rep)    : pbft_receiving_key := pbft_receiving_key_stub.\n  Definition pbft_lookup_client_receiving_key  (c   : Client) : pbft_receiving_key := pbft_receiving_key_stub.\n\n  Definition initial_pbft_local_key_map_replicas (src : name) : local_key_map :=\n    match src with\n    | PBFTreplica i =>\n      MkLocalKeyMap\n        [MkDSKey (map PBFTreplica reps) (pbft_lookup_replica_sending_key i)]\n        (List.app\n           (map (fun c => MkDRKey [PBFTclient  c] (pbft_lookup_client_receiving_key  c)) clients)\n           (map (fun m => MkDRKey [PBFTreplica m] (pbft_lookup_replica_receiving_key m)) reps))\n    | PBFTclient _ => MkLocalKeyMap [] []\n    end.\n\n  Global Instance PBFT_I_keys : PBFTinitial_keys :=\n    MkPBFTinitial_keys initial_pbft_local_key_map_replicas.\n\n  Definition pbft_simple_create_hash_messages (msgs : list PBFTmsg) : PBFTdigest := [].\n  Definition pbft_simple_verify_hash_messages (msgs : list PBFTmsg) (d : PBFTdigest) := true.\n  Definition pbft_simple_create_hash_state_last_reply (smst : PBFTsm_state) (lastr : LastReplyState) : PBFTdigest := [].\n  Definition pbft_simple_verify_hash_state_last_reply (smst : PBFTsm_state) (lastr : LastReplyState) (d : PBFTdigest) := true.\n\n  Global Instance PBFT_I_hash : PBFThash :=\n    MkPBFThash\n      pbft_simple_create_hash_messages\n      pbft_simple_verify_hash_messages\n      pbft_simple_create_hash_state_last_reply\n      pbft_simple_verify_hash_state_last_reply.\n\n\n  (*Lemma simple_create_hash_messages_collision_resistant :\n  forall msgs1 msgs2,\n    simple_create_hash_messages msgs1 = simple_create_hash_messages msgs2\n    -> msgs1 = msgs2.\nProof.\n  introv h.\n  unfold simple_create_hash_messages in *.\nAdmitted.\n\nLemma simple_create_hash_state_last_reply_collision_resistant :\n  forall sm1 sm2 last1 last2,\n    simple_create_hash_state_last_reply sm1 last1 = simple_create_hash_state_last_reply sm2 last2\n    -> sm1 = sm2 /\\ last1 = last2.\nProof.\n  introv h.\nAdmitted.\n\nGlobal Instance PBFT_I_hash_axioms : PBFThash_axioms.\nProof.\n  exact (Build_PBFThash_axioms\n           (* create_hash_message is collision resistant *)\n           simple_create_hash_messages_collision_resistant\n\n           (* create_hash_state_last_reply is collision resistant *)\n           simple_create_hash_state_last_reply_collision_resistant\n        ).\nDefined.\n   *)\n\n\n  (* ================== TIME ================== *)\n\n\n  Definition time_I_type : Set := unit.\n\n  Definition time_I_get_time : unit -> time_I_type := fun _ => tt.\n\n  Definition time_I_sub : time_I_type -> time_I_type -> time_I_type := fun _ _ => tt.\n\n  Definition time_I_2string : time_I_type -> string := fun _ => \"\".\n\n  Global Instance TIME_I : Time.\n  Proof.\n    exists time_I_type.\n    { exact time_I_get_time. }\n    { exact time_I_sub. }\n    { exact time_I_2string. }\n  Defined.\n\n\n\n  (* ================== PRETTY PRINTING ================== *)\n\n\n  (* FIX: to replace when extracting *)\n  Definition print_endline : string -> unit := fun _ => tt.\n  Definition nat2string (n : nat) : string := \"-\".\n\n  Definition CR : string := String (ascii_of_nat 13) \"\".\n\n  (* Fix: to finish *)\n  Definition tokens2string (toks : Tokens) : string := \"-\".\n\n  (* Fix: to finish *)\n  Definition digest2string (d : pbft_digest) : string := \"-\".\n\n  (* Fix: to finish *)\n  Definition result2string (r : result) : string := \"-\".\n\n  (* Fix: there's only one client anyway *)\n  Definition client2string (c : client C) : string := \"-\".\n\n  Definition timestamp2string (ts : Timestamp) : string :=\n    match ts with\n    | time_stamp n => nat2string n\n    end.\n\n  Definition view2string (v : View) : string :=\n    match v with\n    | view n => nat2string n\n    end.\n\n  Definition seq2string (s : SeqNum) : string :=\n    match s with\n    | seq_num n => nat2string n\n    end.\n\n  Definition operation2string (opr : operation) : string :=\n    match opr with\n    | opr_add n => str_concat [\"+\", nat2string n]\n    | opr_sub n => str_concat [\"-\", nat2string n]\n    end.\n\n  Definition nat_n2string {m} (n : nat_n m) : string := nat2string (proj1_sig n).\n\n  Definition replica2string (r : replica F) : string := nat_n2string r.\n\n  Definition bare_request2string (br : Bare_Request) : string :=\n    match br with\n    | null_req => str_concat [ \"null_req\"]\n    | bare_req opr ts c => str_concat [operation2string opr, \",\", timestamp2string ts, \",\", client2string c]\n    end.\n\n  Definition request2string (r : Request) : string :=\n    match r with\n    | req br a => str_concat [\"REQUEST(\", bare_request2string br, \",\", tokens2string a, \")\"]\n    end.\n\n  Fixpoint requests2string (rs : list Request) : string :=\n    match rs with\n    | [] => \"\"\n    | [r] => request2string r\n    | r :: rs => str_concat [request2string r, \",\", requests2string rs]\n    end.\n\n  Definition bare_pre_prepare2string (bpp : Bare_Pre_prepare) : string :=\n    match bpp with\n    | bare_pre_prepare v s reqs => str_concat [view2string v, \",\", seq2string s, \",\", requests2string reqs]\n    end.\n\n  Definition bare_prepare2string (bp : Bare_Prepare) : string :=\n    match bp with\n    | bare_prepare v s d i => str_concat [view2string v, \",\", seq2string s, \",\", digest2string d, \",\", replica2string i]\n    end.\n\n  Definition bare_commit2string (bc : Bare_Commit) : string :=\n    match bc with\n    | bare_commit v s d i => str_concat [view2string v, \",\", seq2string s, \",\", digest2string d, \",\", replica2string i]\n    end.\n\n  Definition bare_reply2string (br : Bare_Reply) : string :=\n    match br with\n    | bare_reply v ts c i res => str_concat [view2string v, \",\", timestamp2string ts, \",\", client2string c, \",\", replica2string i, \",\", result2string res]\n    end.\n\n  Definition pre_prepare2string (pp : Pre_prepare) : string :=\n    match pp with\n    | pre_prepare b a => str_concat [\"PRE_PREPARE(\",bare_pre_prepare2string b, \",\", tokens2string a, \")\"]\n    end.\n\n  Definition prepare2string (p : Prepare) : string :=\n    match p with\n    | prepare bp a => str_concat [\"PREPARE(\", bare_prepare2string bp, \",\", tokens2string a, \")\"]\n    end.\n\n  Definition commit2string (c : Commit) : string :=\n    match c with\n    | commit bc a => str_concat [\"COMMIT(\", bare_commit2string bc, \",\", tokens2string a, \")\"]\n    end.\n\n  Definition reply2string (r : Reply) : string :=\n    match r with\n    | reply br a => str_concat [\"REPLY(\", bare_reply2string br, \",\", tokens2string a, \")\"]\n    end.\n\n  Definition debug2string (d : Debug) : string :=\n    match d with\n    | debug r s => str_concat [\"DEBUG(\", replica2string r, \",\", s, \")\"]\n    end.\n\n  Definition bare_checkpoint2string (bc : Bare_Checkpoint) : string :=\n    match bc with\n    | bare_checkpoint v n d i => str_concat [view2string v, \",\", seq2string n, \",\", digest2string d, \",\", replica2string i]\n    end.\n\n  Definition checkpoint2string (c : Checkpoint) : string :=\n    match c with\n    | checkpoint bc a => str_concat [\"CHECKPOINT(\", bare_checkpoint2string bc, \",\", tokens2string a, \")\"]\n    end.\n\n  Definition check_ready2string (c : CheckReady) : string := \"CHECK-READY()\".\n\n  Definition check_stable2string (c : CheckStableChkPt) : string := \"CHECK-STABLE()\".\n\n  Definition start_timer2string (t : StartTimer) : string :=\n    match t with\n    | start_timer r v => str_concat [\"START-TIMER(\", bare_request2string r, \",\" , view2string v, \")\"]\n    end.\n\n  Definition expired_timer2string (t : ExpiredTimer) : string :=\n    match t with\n    | expired_timer r v => str_concat [\"EXPIRED-TIMER(\", bare_request2string r, \",\" , view2string v, \")\"]\n    end.\n\n  (* FIX *)\n  Definition stable_chkpt2string (stable : StableChkPt) : string := \"-\".\n\n  (* FIX *)\n  Definition checkpoint_cert2string (cert : CheckpointCert) : string := \"-\".\n\n  (* FIX *)\n  Definition prepared_infos2string (l : list PreparedInfo) : string := \"-\".\n\n  Definition bare_view_change2string (bvc : Bare_ViewChange) : string :=\n    match bvc with\n    | bare_view_change v n stable cert preps i =>\n      str_concat\n        [view2string v,\n         \",\",\n         seq2string n,\n         \",\",\n         stable_chkpt2string stable,\n         \",\",\n         checkpoint_cert2string cert,\n         \",\",\n         prepared_infos2string preps,\n         \",\",\n         replica2string i\n        ]\n    end.\n\n  Definition view_change2string (vc : ViewChange) : string :=\n    match vc with\n    | view_change bvc a => str_concat [\"VIEW-CHANGE(\", bare_view_change2string bvc, \",\", tokens2string a, \")\"]\n    end.\n\n  (* FIX *)\n  Definition view_change_cert2string (V : ViewChangeCert) : string := \"-\".\n\n  Fixpoint pre_prepares2string (l : list Pre_prepare) : string :=\n    match l with\n    | [] => \"\"\n    | [r] => pre_prepare2string r\n    | r :: rs => str_concat [pre_prepare2string r, \",\", pre_prepares2string rs]\n    end.\n\n  Definition bare_new_view2string (bnv : Bare_NewView) : string :=\n    match bnv with\n    | bare_new_view v V OP NP =>\n      str_concat\n        [\n          view2string v,\n          \",\",\n          view_change_cert2string V,\n          \",\",\n          pre_prepares2string OP,\n          \",\",\n          pre_prepares2string NP\n        ]\n    end.\n\n  Definition new_view2string (nv : NewView) : string :=\n    match nv with\n    | new_view bnv a => str_concat [\"NEW-VIEW(\", bare_new_view2string bnv, \",\", tokens2string a, \")\"]\n    end.\n\n  Definition check_bcast_new_view2string (c : CheckBCastNewView) : string :=\n    match c with\n    | check_bcast_new_view i => str_concat [\"CHECK-BCAST-NEW-VIEW(\", nat2string i, \")\"]\n    end.\n\n  Definition msg2string (m : PBFTmsg) : string :=\n    match m with\n    | PBFTrequest r              => request2string r\n    | PBFTpre_prepare pp         => pre_prepare2string pp\n    | PBFTprepare p              => prepare2string p\n    | PBFTcommit c               => commit2string c\n    | PBFTcheckpoint c           => checkpoint2string c\n    | PBFTcheck_ready c          => check_ready2string c\n    | PBFTcheck_stable c         => check_stable2string c\n    | PBFTcheck_bcast_new_view c => check_bcast_new_view2string c\n    | PBFTstart_timer t          => start_timer2string t\n    | PBFTexpired_timer t        => expired_timer2string t\n    | PBFTview_change v          => view_change2string v\n    | PBFTnew_view v             => new_view2string v\n    | PBFTdebug d                => debug2string d\n    | PBFTreply r                => reply2string r\n    end.\n\n  Definition name2string (n : name) : string :=\n    match n with\n    | PBFTreplica r => replica2string r\n    | PBFTclient c => client2string c\n    end.\n\n  Fixpoint names2string (l : list name) : string :=\n    match l with\n    | [] => \"\"\n    | [n] => name2string n\n    | n :: ns => str_concat [name2string n, \",\", names2string ns]\n    end.\n\n  Definition delay2string (delay : PosDTime) : string := \"-\".\n\n  Definition DirectedMsg2string (dm : DirectedMsg) : string :=\n    match dm with\n    | MkDMsg msg dst delay =>\n      str_concat [msg2string msg, \":\", \"[\", names2string dst, \"]\", \":\", delay2string delay]\n    end.\n\n  Fixpoint DirectedMsgs2string (l : DirectedMsgs) : string :=\n    match l with\n    | [] => \"\"\n    | [dm] => DirectedMsg2string dm\n    | dm :: dmsgs => str_concat [DirectedMsg2string dm, CR, DirectedMsgs2string dmsgs]\n    end.\n\n  Definition TimedDirectedMsg2string (m : TimedDirectedMsg) : string :=\n    match m with\n    | MkTimedDMsg dm time => str_concat [DirectedMsg2string dm, \":\", time_I_2string time]\n    end.\n\n  Fixpoint TimedDirectedMsgs2string (l : TimedDirectedMsgs) : string :=\n    match l with\n    | [] => \"\"\n    | [dm] => TimedDirectedMsg2string dm\n    | dm :: dmsgs => str_concat [TimedDirectedMsg2string dm, CR, TimedDirectedMsgs2string dmsgs]\n    end.\n\n  Definition MonoSimulationState2string (s : MonoSimulationState) : string :=\n    match s with\n    | MkMonoSimState ty sys step out_inflight in_inflight delivered =>\n      str_concat\n        [CR,\n         \"====== STEP ======\",\n         CR,\n         nat2string step,\n         CR,\n         \"====== IN FLIGHT (from outside the system) ======\",\n         CR,\n         DirectedMsgs2string out_inflight,\n         CR,\n         \"====== IN FLIGHT (from inside the system) ======\",\n         CR,\n         DirectedMsgs2string in_inflight,\n         CR,\n         \"====== DELIVERED ======\",\n         CR,\n         TimedDirectedMsgs2string delivered,\n         CR]\n    end.\n\n  Definition pbft_state2string (s : PBFTstate) :=\n      str_concat\n        [\"(checkpoint state size:\"\n         , nat2string (List.length (chk_state_others (cp_state s)))\n         ,\")\"\n         ,\"(ready size:\"\n         , nat2string (List.length (ready s))\n         ,\")\"\n         ,\"(buffered requests:\"\n         , nat2string (List.length (request_buffer (primary_state s)))\n         ,\")\"\n         ,\"(log size:\"\n         , nat2string (List.length (log s))\n         ,\")\"\n        ].\n\n  (* ================== SYSTEM ================== *)\n\n\n  Definition dummy_initial_state : PBFTstate :=\n    Build_State\n      (MkLocalKeyMap [] [])\n      initial_view\n      []\n      initial_checkpoint_state\n      PBFTsm_initial_state\n      initial_next_to_execute\n      initial_ready\n      initial_last_reply\n      initial_view_change_state\n      initial_primary_state.\n\n  Definition PBFTdummySM : MStateMachine PBFTstate :=\n    MhaltedSM dummy_initial_state.\n\n  Definition PBFTmono_sys : NMStateMachine PBFTstate := PBFTreplicaSM.\n\n  Definition mk_request_to (rep : Rep) (ts : nat) (opr : nat) : DirectedMsg :=\n    let ts   := time_stamp ts in\n    let breq := bare_req (opr_add opr) ts (client0 C) in\n    let dst  := PBFTreplica rep in (* the leader *)\n    let toks := [ pbft_token_stub ] : Tokens in (* we just send empty lists here to authenticate messages *)\n    let req  := req breq toks in\n    let msg  := PBFTrequest req in\n    MkDMsg msg [dst] ('0).\n\n  Definition mk_request (ts : nat) (opr : nat) : DirectedMsg :=\n    mk_request_to (PBFTprimary initial_view) ts opr.\n\n  (* n request starting with number start *)\n  Fixpoint mk_requests_start (n start opr : nat) : DirectedMsgs :=\n    match n with\n    | 0 => []\n    | S m => List.app (mk_requests_start m start opr) [mk_request (n + start) opr]\n    end.\n\n  Definition mk_requests (n opr : nat) : DirectedMsgs :=\n    mk_requests_start n 0 opr.\n\n  Record InitRequests :=\n    MkInitRequests\n      {\n        num_requests     : nat;\n        starting_seq_num : nat;\n        req_operation    : nat;\n      }.\n\n  Definition PBFTinit_msgs (msgs : DirectedMsgs) : MonoSimulationState :=\n    MkInitMonoSimState PBFTmono_sys msgs.\n\n  Definition PBFTinit (init : InitRequests) : MonoSimulationState :=\n    PBFTinit_msgs\n      (mk_requests_start\n         (num_requests init)\n         (starting_seq_num init)\n         (req_operation init)).\n\n  Definition PBFTsimul_list (init : InitRequests) (L : list nat) : MonoSimulationState :=\n    mono_run_n_steps L (PBFTinit init).\n\n  Definition PBFTsimul_list_msgs (msgs : DirectedMsgs) (L : list nat) : MonoSimulationState :=\n    mono_run_n_steps L (PBFTinit_msgs msgs).\n\n  (* [switch] is the list of steps at which we want to switch to sending messages\n   coming from the outside (from clients) instead of keeping on sending messages\n   coming from the inside (from replicas). *)\n  Definition PBFTsimul_n\n             (init     : InitRequests) (* This is to generate an initial list of requests *)\n             (rounds   : Rounds)\n             (switches : Switches) : MonoSimulationState :=\n    mono_iterate_n_steps rounds switches (PBFTinit init).\n\n  Definition PBFTsimul_n_msgs\n             (msgs     : DirectedMsgs)\n             (rounds   : Rounds)\n             (switches : Switches) : MonoSimulationState :=\n    mono_iterate_n_steps rounds switches (PBFTinit_msgs msgs).\n\nEnd PBFTinstance.\n\n\n\n(* ================== EXTRACTION ================== *)\n\n\nExtraction Language Ocaml.\n\n(* printing stuff *)\nExtract Inlined Constant print_endline => \"Prelude.print_coq_endline\".\nExtract Inlined Constant nat2string    => \"Prelude.char_list_of_int\".\nExtract Inlined Constant CR            => \"['\\n']\".\n\n(* numbers *)\nExtract Inlined Constant Nat.modulo    => \"(mod)\".\n\n(* lists *)\nExtract Inlined Constant forallb => \"List.for_all\".\nExtract Inlined Constant existsb => \"List.exists\".\nExtract Inlined Constant length  => \"List.length\".\nExtract Inlined Constant app     => \"List.append\".\nExtract Inlined Constant map     => \"List.map\".\nExtract Inlined Constant filter  => \"List.filter\".\n\n(* timing stuff *)\nExtract Inlined Constant time_I_type     => \"float\".\nExtract Inlined Constant time_I_get_time => \"Prelude.Time.get_time\".\nExtract Inlined Constant time_I_sub      => \"Prelude.Time.sub_time\".\nExtract Inlined Constant time_I_2string  => \"Prelude.Time.time2string\".\n\n\n(* == crypto stuff == *)\n(* === COMMENT OUT THIS PART IF YOU DON'T WANT TO USE KEYS === *)\nExtract Inlined Constant pbft_sending_key   => \"Nocrypto.Rsa.priv\".\nExtract Inlined Constant pbft_receiving_key => \"Nocrypto.Rsa.pub\".\nExtract Inlined Constant pbft_lookup_replica_sending_key   => \"RsaKeyFun.lookup_replica_sending_key\".\nExtract Inlined Constant pbft_lookup_replica_receiving_key => \"RsaKeyFun.lookup_replica_receiving_key\".\nExtract Inlined Constant pbft_lookup_client_receiving_key  => \"RsaKeyFun.lookup_client_receiving_key\".\n\nExtract Inlined Constant pbft_create_signature => \"RsaKeyFun.sign_list\".\nExtract Inlined Constant pbft_verify_signature => \"RsaKeyFun.verify_one\".\nExtract Inlined Constant pbft_token => \"Cstruct.t\".\nExtract Inlined Constant pbft_token_deq => \"(=)\".\n(* === --- === *)\n\n\n(* == hashing stuff == *)\nExtract Inlined Constant pbft_digest => \"Cstruct.t\".\nExtract Inlined Constant pbft_digest_deq => \"(=)\".\nExtract Inlined Constant pbft_simple_create_hash_messages => \"Obj.magic (Hash.create_hash_objects)\".\nExtract Inlined Constant pbft_simple_verify_hash_messages => \"Obj.magic (Hash.verify_hash_objects)\".\nExtract Inlined Constant pbft_simple_create_hash_state_last_reply => \"Obj.magic (Hash.create_hash_pair)\".\nExtract Inlined Constant pbft_simple_verify_hash_state_last_reply => \"Obj.magic (Hash.verify_hash_pair)\".\n(* === --- === *)\n\n\nRequire Export ExtrOcamlBasic.\nRequire Export ExtrOcamlNatInt.\nRequire Export ExtrOcamlString.\n\n\nDefinition local_replica (*(F C : nat)*) :=\n  @PBFTreplicaSM\n    (@PBFT_I_context (*(MkNumNodes F C)*))\n    PBFT_I_auth\n    PBFT_I_keys\n    PBFT_I_hash.\n\nExtraction \"PbftReplica.ml\" pbft_state2string lrun_sm MonoSimulationState2string PBFTdummySM local_replica.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/runtime/PBFTsim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2491749363644691}}
{"text": "Require Import Reals Psatz.\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.base_logic.lib Require Export invariants sts.\nFrom iris.heap_lang Require Export lang.\nFrom iris.proofmode Require Import tactics.\nFrom iris.heap_lang Require Import proofmode notation spawn.\nFrom iris.algebra Require Import excl agree csum frac.\nFrom discprob.idxval Require Import pival\n     pival_dist ival_dist irrel_equiv idist_pidist_pair extrema.\n\nProgram Definition flip_half := pidist_plus (1/2)%R _ (mret true) (mret false).\nNext Obligation.\n  abstract (nra).\nQed.\n\nDefinition one_shotR := csumR (fracR) (agreeR boolC).\nClass one_shotG Σ := { one_shot_inG :> inG Σ one_shotR }.\n\nSection proof.\nContext `{!heapG Σ, !spawnG Σ, !probG Σ, !one_shotG Σ}.\n\nDefinition Pending q : one_shotR := (Cinl q : one_shotR).\nDefinition Shot (b: bool) : one_shotR := (Cinr (to_agree b) : one_shotR).\n\nGlobal Instance shot_persistent γ b : Persistent (own γ (Shot b)).\nProof. apply _. Qed.\n\n(* TODO: there's no need to have the starting thread wrap up their ownership into\n   this one shot inv; and the flip_inv should not hold \"one_shot_inv\" but rather \n   just the status of the shot. *)\nDefinition one_shot_inv (γ : gname) (l : loc) : iProp Σ :=\n  (l ↦ NONEV ∨ ∃ b : bool, (l ↦  NONEV ∨ l ↦ SOMEV #b ∗ own γ (Shot b)))%I.\n\nDefinition mapsto_shot l (ob : option bool) : iProp Σ :=\n  match ob with\n    | None => (∃ N γ, inv N (one_shot_inv γ l))%I\n    | Some b => (∃ N γ, inv N (one_shot_inv γ l) ∗ own γ (Shot b))%I\n  end.\n\nDefinition flip_inv (γ : gname) (γ1 γ2: gname) : iProp Σ :=\n  ((ownProb flip_half ∗ own γ1 (Pending (1/2)%Qp) ∗ own γ2 (Pending (1/2)%Qp)) ∨\n   (∃ b, ownProb flip_half ∗ own γ1 (Shot b) ∗ own γ2 (Pending (1/2)%Qp)) ∨\n   (∃ b, ownProb flip_half ∗ own γ1 (Pending (1/2)%Qp) ∗ own γ2 (Shot b)) ∨\n   (∃ b1 b2, (own γ (Excl ()) ∨ ownProb (mret (eqb b1 b2)))\n                     ∗ own γ1 (Shot b1) ∗ own γ2 (Shot b2)))%I.\n\n\nLemma mapsto_shot_load N γ l:\n  {{{ inv N (one_shot_inv γ l) }}} Load (Lit (LitLoc l))\n  {{{ v, RET v;\n      match v with\n      | NONEV => True\n      | SOMEV #b => ∃ b', ⌜ (LitBool b') = b ⌝ ∗ own γ (Shot b')\n      | _  => False\n      end}}}.  \nProof.\n  iIntros (Φ) \"#Hinv Hwand\". \n  iInv N as \">[Hnone|Hsome]\" \"Hclose\".\n  - wp_load. iApply \"Hwand\". iMod (\"Hclose\" with \"[Hnone]\").\n    { iNext. iRight. iExists true. iLeft. iFrame. }\n    done.\n  - iDestruct \"Hsome\" as (b') \"[Hnone|(Hsome&#Hshot')]\".\n    * wp_load. iApply \"Hwand\". iMod (\"Hclose\" with \"[Hnone]\").\n      { iNext. iRight. iExists true. iLeft. iFrame. }\n      iModIntro. done.\n    * wp_load. iApply \"Hwand\".\n      iMod (\"Hclose\" with \"[Hsome]\").\n      { iNext. iRight. iExists b'. iRight. iFrame. done. }\n      iModIntro; iExists b'; iSplitR; done.\nQed.\n\n\nLemma mapsto_shot_load_some N γ l b:\n  {{{ inv N (one_shot_inv γ l) ∗ own γ (Shot b) }}} Load (Lit (LitLoc l))\n  {{{ v, RET v;\n      match v with\n      | NONEV => own γ (Shot b)\n      | SOMEV #b' => ⌜ (LitBool b) = b' ⌝ ∗ own γ (Shot b)\n      | _  => False\n      end}}}.  \nProof.\n  iIntros (Φ) \"(#Hinv&Hshot) Hwand\". \n  iInv N as \">[Hnone|Hsome]\" \"Hclose\".\n  - wp_load. iApply \"Hwand\". iMod (\"Hclose\" with \"[Hnone]\").\n    { iNext. iRight. iExists true. iLeft. iFrame. }\n    done.\n  - iDestruct \"Hsome\" as (b') \"[Hnone|(Hsome&Hshot')]\".\n    * wp_load. iApply \"Hwand\". iMod (\"Hclose\" with \"[Hnone]\").\n      { iNext. iRight. iExists true. iLeft. iFrame. }\n      iModIntro. done.\n    * wp_load. iApply \"Hwand\".\n      iDestruct (own_valid_2 with \"Hshot Hshot'\") as %?%agree_op_invL'; subst.\n      iMod (\"Hclose\" with \"[Hshot' Hsome]\").\n      { iNext. iRight. iExists b'. iRight. iFrame. }\n      iModIntro; iSplitR; done.\nQed.\n\nLemma mapsto_shot_store_some N γ l b:\n  {{{ inv N (one_shot_inv γ l) ∗ own γ (Shot b) }}}\n    Store (Lit (LitLoc l)) (SOMEV (LitV $ LitBool b))\n  {{{ RET #(); own γ (Shot b) }}}.\nProof.\n  iIntros (Φ) \"(#Hinv&Hshot) Hwand\". \n  iInv N as \">[Hnone|Hsome]\" \"Hclose\".\n  - wp_store. iApply \"Hwand\".\n      iAssert (own γ (Shot b) ∗ own γ (Shot b))%I with \"[Hshot]\" as \"(Hshot1&Hshot2)\".\n      { rewrite -own_op Cinr_op //=\n        -(proj1 (agree_included (to_agree b) (to_agree b))); last reflexivity.\n        iFrame. }\n      iMod (\"Hclose\" with \"[Hshot1 Hnone]\").\n      { iNext. iRight. iExists b. iRight. iFrame. }\n      iModIntro. done.\n  - iDestruct \"Hsome\" as (b') \"[Hnone|(Hsome&Hshot')]\".\n    * wp_store. iApply \"Hwand\".\n      iAssert (own γ (Shot b) ∗ own γ (Shot b))%I with \"[Hshot]\" as \"(Hshot1&Hshot2)\".\n      { rewrite -own_op Cinr_op //=\n        -(proj1 (agree_included (to_agree b) (to_agree b))); last reflexivity.\n        iFrame. }\n      iMod (\"Hclose\" with \"[Hshot1 Hnone]\").\n      { iNext. iRight. iExists b. iRight. iFrame. }\n      iModIntro. done.\n    * wp_store. iApply \"Hwand\".\n      iDestruct (own_valid_2 with \"Hshot Hshot'\") as %?%agree_op_invL'; subst.\n      iMod (\"Hclose\" with \"[Hshot' Hsome]\").\n      { iNext. iRight. iExists b'. iRight. iFrame. }\n      iModIntro. done.\nQed.\n\nLemma flip_inv_commit N γ γ1 γ2 γ':\n  γ' = γ1 ∨ γ' = γ2 →\n  {{{ inv N (flip_inv γ γ1 γ2) ∗ own γ' (Pending (1/2)%Qp) }}}\n    flip #1 #2\n  {{{ b, RET (LitV $ LitBool b); own γ' (Shot b) }}}.\nProof.\n  intros Heq.\n  iIntros (Φ) \"(#Hinv&Hγ') Hwand\". \n  iInv N as \">[Hprob|[Hprob|[Hprob|Hprob]]]\" \"Hclose\".\n  * iDestruct \"Hprob\" as \"(Hprob&Hγ1&Hγ2)\".\n    setoid_rewrite <-(pidist_left_id tt (λ x, flip_half)) at 1.\n    unshelve (wp_flip (mret tt) (λ x y, True) b t HR); first by abstract (nra).\n    { apply irrel_coupling_trivial. }\n    destruct Heq as [Heq|Heq]; subst.\n    ** iMod (own_update γ1 (Pending 1%Qp) with \"[Hγ' Hγ1]\") as \"#Hγ'\".\n       { by apply cmra_update_exclusive with (y:=Shot b). }\n       { iCombine \"Hγ'\" \"Hγ1\" as \"H\".\n         rewrite //=. rewrite Cinl_op frac_op'. rewrite /Pending.\n         by rewrite Qp_div_2. }\n       iMod (\"Hclose\" with \"[Hprob Hγ2]\").\n       { iNext. iRight. iLeft. iExists b. iFrame. done. }\n       iModIntro.\n       iApply \"Hwand\"; done.\n    ** iMod (own_update γ2 (Pending 1%Qp) with \"[Hγ' Hγ2]\") as \"#Hγ'\".\n       { by apply cmra_update_exclusive with (y:=Shot b). }\n       { iCombine \"Hγ'\" \"Hγ2\" as \"H\".\n         rewrite //=. rewrite Cinl_op frac_op'. rewrite /Pending.\n         by rewrite Qp_div_2. }\n       iMod (\"Hclose\" with \"[Hprob Hγ1]\").\n       { iNext. iRight. iRight. iLeft. iExists b. iFrame. done. }\n       iModIntro.\n       iApply \"Hwand\"; done.\n  * destruct Heq as [Heq1|Heq2]; subst.\n    { iDestruct \"Hprob\" as (b) \"(Hprob&Hshot&?)\".\n      iDestruct (own_valid_2 with \"Hγ' Hshot\") as \"%\".\n      exfalso; auto. }\n    \n    iDestruct \"Hprob\" as (b) \"(Hprob&Hshot1&Hshot2)\".\n    setoid_rewrite <-pidist_right_id.\n    unshelve (wp_flip flip_half (λ x y, match b, x with\n                                               | true, true => y = true\n                                               | false, false => y = true\n                                               | _, _ => y = false\n                                               end) c c' HRc); first by abstract (nra).\n    { apply ip_irrel_coupling.\n      destruct b.\n      * eapply ip_coupling_plus; first (by reflexivity);\n          apply ip_coupling_mret; auto.\n      * assert (0 <= 1 - (IZR 1 /IZR 2) <= 1)%R by nra.\n        eapply (ip_coupling_proper (ivdplus _ H (mret false) (mret true))).\n        { symmetry. eapply ivdplus_comm. } \n        { reflexivity.  }\n        assert (1 - (IZR 1 / IZR 2) = IZR 1 / IZR 2)%R as Hzeq.\n        { nra.  }\n        generalize H.\n        rewrite Hzeq => ?.\n        eapply ip_coupling_plus; first (by reflexivity);\n          apply ip_coupling_mret; auto.\n    }\n    iMod (own_update _ (Pending 1%Qp) with \"[Hγ' Hshot2]\") as \"#Hγ'\".\n    { by apply cmra_update_exclusive with (y:=Shot c). }\n    { iCombine \"Hγ'\" \"Hshot2\" as \"H\".\n         rewrite //=. rewrite Cinl_op frac_op'. rewrite /Pending.\n         by rewrite Qp_div_2. }\n    iMod (\"Hclose\" with \"[Hprob Hshot1]\").\n    { iNext. iRight. iRight. iRight.\n      iExists b, c. iFrame. iFrame \"Hγ'\".\n      iRight. iFrame.\n      destruct b, c, c' => //=.\n    }\n    iModIntro.\n    iApply \"Hwand\". done.\n  * destruct Heq as [Heq1|Heq2]; subst; last first.\n    { iDestruct \"Hprob\" as (b) \"(Hprob&_&Hshot)\".\n      iDestruct (own_valid_2 with \"Hγ' Hshot\") as \"%\".\n      exfalso; auto. }\n    iDestruct \"Hprob\" as (b) \"(Hprob&Hshot1&Hshot2)\".\n    setoid_rewrite <-pidist_right_id.\n    unshelve (wp_flip flip_half (λ x y, match b, x with\n                                               | true, true => y = true\n                                               | false, false => y = true\n                                               | _, _ => y = false\n                                               end) c c' HRc); first by abstract (nra).\n    { apply ip_irrel_coupling.\n      destruct b.\n      * eapply ip_coupling_plus; first (by reflexivity);\n          apply ip_coupling_mret; auto.\n      * assert (0 <= 1 - (IZR 1 /IZR 2) <= 1)%R by nra.\n        eapply (ip_coupling_proper (ivdplus _ H (mret false) (mret true))).\n        { symmetry. eapply ivdplus_comm. } \n        { reflexivity.  }\n        assert (1 - (IZR 1 / IZR 2) = IZR 1 / IZR 2)%R as Hzeq.\n        { nra.  }\n        generalize H.\n        rewrite Hzeq => ?.\n        eapply ip_coupling_plus; first (by reflexivity);\n          apply ip_coupling_mret; auto.\n    }\n    iMod (own_update _ (Pending 1%Qp) with \"[Hγ' Hshot1]\") as \"#Hγ'\".\n    { by apply cmra_update_exclusive with (y:=Shot c). }\n    { iCombine \"Hγ'\" \"Hshot1\" as \"H\".\n         rewrite //=. rewrite Cinl_op frac_op'. rewrite /Pending.\n         by rewrite Qp_div_2. }\n    iMod (\"Hclose\" with \"[Hprob Hshot2]\").\n    { iNext. iRight. iRight. iRight.\n      iExists c, b. iFrame. iFrame \"Hγ'\".\n      iRight. iFrame.\n      destruct b, c, c' => //=.\n    }\n    iModIntro.\n    iApply \"Hwand\". done.\n  * iDestruct \"Hprob\" as (b1 b2) \"(Hprob&Hshot1&Hshot2)\".\n    destruct Heq as [Heq1|Heq2]; subst.\n    ** iDestruct (own_valid_2 with \"Hγ' Hshot1\") as \"%\".\n       exfalso; auto.\n    ** iDestruct (own_valid_2 with \"Hγ' Hshot2\") as \"%\".\n       exfalso; auto.\nQed.\n                 \nLemma join_spec N γ l :\n  {{{ inv N (one_shot_inv γ l) }}} join #l {{{ b, RET (LitV $ LitBool b); own γ (Shot b) }}}.\nProof.\n  iIntros (Φ) \"#Hinv Hwand\". \n  iLöb as \"IH\". wp_rec. wp_bind (! _)%E.\n  wp_apply mapsto_shot_load; eauto.\n  iIntros (v) \"Hret\". destruct v; eauto.\n  * wp_match. wp_apply \"IH\"; auto.\n  * wp_match. destruct v; eauto.\n    iDestruct \"Hret\" as (b) \"(%&Hshot)\"; subst.\n    iApply \"Hwand\". done.\nQed.\n\nDefinition join : val :=\n  rec: \"join\" \"c\" :=\n    match: !\"c\" with\n      SOME \"x\" => \"x\"\n    | NONE => \"join\" \"c\"\n    end.\n\nDefinition concurrent_flip : expr :=\n  let: \"l\" := ref NONE in\n  Fork (\"l\" <- SOME (flip #1 #2)) ;; \n  let: \"b\" := flip #1 #2 in\n  let: \"ret\" := App join \"l\" in\n  \"b\" = \"ret\".\n\nLemma cflip_spec  :\n  ownProb flip_half ⊢\n          WP concurrent_flip {{ v, ∃ v', ownProb (mret v') ∗\n                                                 ⌜ v = LitV $ LitBool v' ⌝ }}%I.\nProof.\n  iIntros \"Hprob\". rewrite /concurrent_flip.\n  wp_alloc l2 as \"Hl2\". wp_let.\n  iMod (own_alloc (Pending 1%Qp)) as (γ1) \"Hγ1\"; first done.\n  rewrite -[a in Pending a](Qp_div_2 1). rewrite /Pending -frac_op' -Cinl_op.\n  iDestruct \"Hγ1\" as \"(Hγ1a&Hγ1b)\".\n\n  iMod (own_alloc (Pending 1%Qp)) as (γ2) \"Hγ2\"; first done.\n  rewrite -[a in Pending a](Qp_div_2 1). rewrite /Pending -frac_op' -Cinl_op.\n  iDestruct \"Hγ2\" as \"(Hγ2a&Hγ2b)\".\n\n\n  pose proof (nroot .@ \"N1\") as N1.\n  pose proof (nroot .@ \"N2\") as N2.\n  iMod (inv_alloc N1 _ (one_shot_inv γ2 l2) with \"[Hl2]\") as \"#HN1\".\n  { iNext. rewrite /one_shot_inv. iLeft. iFrame. }\n  \n  iMod (own_alloc (Excl ())) as (γ) \"Hγ\"; first done.\n  iMod (inv_alloc N2 _ (flip_inv γ γ1 γ2) with \"[Hprob Hγ1b Hγ2b]\") as \"#HN2\".\n  { iNext. rewrite /flip_inv. iLeft. iFrame. } \n\n  wp_apply wp_fork.\n  iSplitR \"Hγ2a\"; last first.\n  - wp_bind (flip #1 #2). \n    wp_apply (flip_inv_commit N2 γ γ1 γ2 γ2 with \"[Hγ2a]\"); auto.\n    iIntros (b) \"#Hγ2\".\n    wp_apply (mapsto_shot_store_some with \"[Hγ2]\"); eauto.\n  - wp_let. wp_bind (flip #1 #2).\n    wp_apply (flip_inv_commit N2 γ γ1 γ2 γ1 with \"[Hγ1a]\"); auto.\n    iIntros (b) \"#Hγ1\".\n    wp_let. wp_apply join_spec; eauto.\n    iIntros (b') \"#Hγ2\".\n    wp_let.\n    iInv N2 as \">[(_&Hγ1'&_)|[Hprob|[Hprob|Hprob]]]\" \"Hclose\".\n    { iDestruct (own_valid_2 with \"Hγ1 Hγ1'\") as \"%\".\n      exfalso; auto. }\n    { iDestruct \"Hprob\" as (?) \"(_&_&Hγ2')\".\n      iDestruct (own_valid_2 with \"Hγ2 Hγ2'\") as \"%\".\n      exfalso; auto. }\n    { iDestruct \"Hprob\" as (?) \"(_&Hγ1'&_)\".\n      iDestruct (own_valid_2 with \"Hγ1 Hγ1'\") as \"%\".\n      exfalso; auto. }\n    iDestruct \"Hprob\" as (b1 b2) \"(Hprob&Hγ1'&Hγ2')\".\n    iDestruct (own_valid_2 with \"Hγ1 Hγ1'\") as %?%agree_op_invL'; subst.\n    iDestruct (own_valid_2 with \"Hγ2 Hγ2'\") as %?%agree_op_invL'; subst.\n    iDestruct \"Hprob\" as \"[Htok|Hprob]\".\n    { iDestruct (own_valid_2 with \"Hγ Htok\") as \"%\".\n      exfalso; auto. }\n    wp_op.\n    iMod (\"Hclose\" with \"[Hγ]\").\n    { iNext.  iRight. iRight. iRight. iExists b1, b2. iFrame \"Hγ1 Hγ2\".\n      iLeft. done. }\n    iModIntro. iExists (eqb b1 b2). iFrame.\n    iPureIntro. destruct b1, b2 => //=.\nQed.\nEnd proof.", "meta": {"author": "jtassarotti", "repo": "polaris", "sha": "c7873f05214351d54cacf3d8482625ee33ad3288", "save_path": "github-repos/coq/jtassarotti-polaris", "path": "github-repos/coq/jtassarotti-polaris/polaris-c7873f05214351d54cacf3d8482625ee33ad3288/theories/tests/prob_fork_flip.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7217432182679956, "lm_q2_score": 0.34510527769342453, "lm_q1q2_score": 0.24907739376372254}}
{"text": "From Perennial.program_proof.lockservice Require Import lockservice_nocrash.\nFrom Perennial.program_logic Require Export weakestpre.\nFrom Perennial.goose_lang Require Import prelude.\nFrom Perennial.goose_lang Require Import ffi.disk_prelude.\nFrom Perennial.goose_lang Require Import notation.\nFrom Perennial.program_proof Require Import disk_prelude.\nFrom stdpp Require Import gmap.\nFrom RecordUpdate Require Import RecordUpdate.\nFrom Perennial.algebra Require Import auth_map.\nFrom Perennial.goose_lang.lib Require Import lock.\nFrom Perennial.Helpers Require Import NamedProps.\nFrom iris.algebra Require Import numbers.\n\nSection lockservice_proof.\nContext `{!heapGS Σ}.\nContext `{!mapG Σ u64 bool}.\nContext `{!mapG Σ u64 unit}.\nContext `{!ghost_varG Σ bool}.\n\nDefinition Nclient := nroot .@ \"client\".\nDefinition Nserver := nroot .@ \"server\".\nParameter (P : iProp Σ).\nInstance tp : Timeless P. Admitted.\n\nDefinition server_inner γi γp γc : iProp Σ :=\n  ∃ (issued : gmap u64 unit) (processed : gmap u64 bool) (claimed : gmap u64 bool) (locked : bool),\n    \"Hissued\" ∷ ([∗ map] _ ↦ _; _ ∈ issued; processed, True) ∗\n    \"Hprocessed\" ∷ ([∗ map] _ ↦ proc; claim ∈ processed; claimed, ⌜proc = false \\/ claim = true⌝ ∨ P) ∗\n    \"Hctxi\" ∷ map_ctx γi 1 issued ∗\n    \"Hctxp\" ∷ map_ctx γp 1 processed ∗\n    \"Hctxc\" ∷ map_ctx γc 1 claimed ∗\n    \"Hprocro\" ∷ ([∗ map] reqid ↦ proc ∈ processed, reqid [[γp]]↦ false ∨ reqid [[γp]]↦ro true) ∗\n    \"Havail\" ∷ (⌜locked=true⌝ ∨ P).\n\nDefinition client_req_inner γi γc returned reqid : iProp Σ :=\n  \"#Hissue\" ∷ reqid [[γi]]↦ro () ∗\n  \"Hreply\" ∷ ( ghost_var returned (1/2) false ∗ reqid [[γc]]↦ false ∨\n               ghost_var returned (1/2) false ∗ reqid [[γc]]↦ro true ∗ P ∨\n               ghost_var returned (1/2) true ∗ reqid [[γc]]↦ro true ).\n\nDefinition request_token γi reqid : iProp Σ :=\n  \"Hreq_tok\" ∷ reqid [[γi]]↦ro ().\n\nDefinition response_token γp reqid acquired : iProp Σ :=\n  \"Hresp_tok\" ∷ ⌜acquired=false⌝ ∨ reqid [[γp]]↦ro true.\n\nTheorem client_allocates_reqid γi γp γc reqid :\n  inv Nserver (server_inner γi γp γc)\n  ={⊤}=∗\n  ∃ returned,\n    inv Nclient (client_req_inner γi γc returned reqid) ∗\n    ghost_var returned (1/2) false.\nProof.\n  iIntros \"#H\".\n  iInv \"H\" as \">Hinner\" \"Hclose\".\n  iNamed \"Hinner\".\n  destruct (issued !! reqid) eqn:Hissue.\n  { (* Need some kind of assumption that this reqid has not been used yet. *)\n    admit.\n  }\n\n  iDestruct (big_sepM2_lookup_l_none with \"Hissued\") as %Hproc; eauto.\n  iDestruct (big_sepM2_lookup_l_none with \"Hprocessed\") as %Hclaim; eauto.\n\n  iMod (map_alloc_ro _ tt with \"Hctxi\") as \"[Hctxi #Hissue]\"; eauto.\n  iMod (map_alloc _ false with \"Hctxp\") as \"[Hctxp Hproc]\"; eauto.\n  iMod (map_alloc _ false with \"Hctxc\") as \"[Hctxc Hclaim]\"; eauto.\n\n  iDestruct (big_sepM2_insert _ _ _ _ tt false with \"[$Hissued]\") as \"Hissued\"; eauto.\n  iDestruct (big_sepM2_insert _ _ _ _ false false with \"[$Hprocessed]\") as \"Hprocessed\"; eauto.\n  iDestruct (big_sepM_insert with \"[$Hprocro $Hproc]\") as \"Hprocro\"; eauto.\n\n  iMod (ghost_var_alloc false) as (returned) \"[Hret1 Hret2]\".\n\n  iMod (\"Hclose\" with \"[-Hclaim Hret1 Hret2]\") as \"_\".\n  { iExists _, _, _, _. iFrame. }\n\n  iMod (inv_alloc with \"[Hclaim Hret1]\") as \"Hc\".\n  2: { iModIntro. iExists returned. iFrame. }\n\n  iFrame \"#\".\n  iLeft. iFrame.\nAdmitted.\n\nTheorem client_generates_request γi γc returned reqid :\n  inv Nclient (client_req_inner γi γc returned reqid)\n  ={⊤}=∗\n  request_token γi reqid.\nProof.\n  iIntros \"#H\".\n  iInv \"H\" as \">Hinner\" \"Hclose\".\n  iNamed \"Hinner\".\n  iFrame \"Hissue\".\n  iApply \"Hclose\".\n  iFrame. iFrame \"#\".\nQed.\n\nTheorem server_processes_request γi γp γc reqid :\n  inv Nserver (server_inner γi γp γc) -∗\n  request_token γi reqid\n  ={⊤}=∗\n  ∃ acquired, response_token γp reqid acquired.\nProof.\n  iIntros \"#H #Hreq\".\n  iInv \"H\" as \">Hinner\" \"Hclose\".\n  iNamed \"Hinner\".\n  iDestruct (map_valid with \"Hctxi Hreq\") as %Hreq.\n  iDestruct (big_sepM2_lookup_l_some with \"Hissued\") as (proc) \"%\"; eauto.\n  destruct proc.\n  - iDestruct (big_sepM_lookup_acc with \"Hprocro\") as \"[Hdupreply Hprocro]\"; eauto.\n    iDestruct \"Hdupreply\" as \"[Hdupreply|#Hdupreply]\".\n    { iDestruct (map_valid with \"Hctxp Hdupreply\") as \"%\". congruence. }\n    iFrame \"Hdupreply\".\n    iDestruct (\"Hprocro\" with \"[$Hdupreply]\") as \"Hprocro\".\n    iExists true.\n    iApply \"Hclose\". iExists _, _, _, _. iFrame.\n  - destruct locked.\n    + iExists false.\n      iMod (\"Hclose\" with \"[-]\") as \"_\".\n      { iExists _, _, _, _. iFrame. }\n      iModIntro. iLeft. done.\n    + iDestruct (big_sepM2_delete with \"Hissued\") as \"[_ Hissued]\"; eauto.\n      iDestruct (big_sepM2_insert_delete with \"[$Hissued]\") as \"Hissued\".\n      iDestruct (big_sepM2_lookup_l_some with \"Hprocessed\") as (claim) \"%\"; eauto.\n      iDestruct (big_sepM2_delete with \"Hprocessed\") as \"[_ Hprocessed]\"; eauto.\n      iDestruct (big_sepM2_insert_delete with \"[$Hprocessed Havail]\") as \"Hprocessed\".\n      { iDestruct \"Havail\" as \"[%|Havail]\"; first by congruence. iFrame. }\n      iDestruct (big_sepM_insert_acc with \"Hprocro\") as \"[Hproc Hprocro]\"; eauto.\n      iDestruct \"Hproc\" as \"[Hproc|Hproc]\".\n      2: { iDestruct (map_valid with \"Hctxp Hproc\") as \"%\". congruence. }\n      iMod (map_update _ _ true with \"Hctxp Hproc\") as \"[Hctxp Hproc]\".\n      iMod (map_freeze with \"Hctxp Hproc\") as \"[Hctxp #Hproc]\".\n      iDestruct (\"Hprocro\" with \"[$Hproc]\") as \"Hprocro\".\n      iExists true. iFrame \"Hproc\".\n      iApply \"Hclose\". iExists _, _, _, true. iFrame.\n      rewrite insert_id; eauto. rewrite insert_id; eauto. iFrame.\n      iLeft. done.\nQed.\n\nTheorem client_accepts_reply γi γp γc returned reqid :\n  ghost_var returned (1/2) false -∗\n  inv Nserver (server_inner γi γp γc) -∗\n  inv Nclient (client_req_inner γi γc returned reqid) -∗\n  response_token γp reqid true\n  ={⊤}=∗\n  P.\nProof.\n  iIntros \"Hret #Hs #Hc #Htok\".\n  iInv \"Hc\" as \">Hinner_c\" \"Hclose_c\".\n  iNamed \"Hinner_c\".\n  iDestruct \"Hreply\" as \"[Hnotclaimed|Hclaimed]\".\n  2: {\n    iDestruct \"Hclaimed\" as \"[(Hret2 & Hclaim & HP)|(Hret2 & HP)]\".\n    2: { iDestruct (ghost_var_agree with \"Hret Hret2\") as %Heq. congruence. }\n    iCombine \"Hret Hret2\" as \"Hret\".\n    iMod (ghost_var_update true with \"Hret\") as \"[Hret1 Hret2]\".\n    iFrame.\n    iApply \"Hclose_c\". iFrame \"#\". iRight. iRight. iFrame.\n  }\n\n  iDestruct \"Hnotclaimed\" as \"[Hret2 Hnotclaimed]\".\n\n  iInv \"Hs\" as \">Hinner_s\" \"Hclose_s\".\n  iNamed \"Hinner_s\".\n  iDestruct (map_valid with \"Hctxc Hnotclaimed\") as %Hnotclaimed.\n\n  iMod (map_update _ _ true with \"Hctxc Hnotclaimed\") as \"[Hctxc Hclaimed]\".\n  iMod (map_freeze with \"Hctxc Hclaimed\") as \"[Hctxc #Hclaimed]\".\n\n  iDestruct (map_ro_valid with \"Hctxp [Htok]\") as %Hproc.\n  { iDestruct \"Htok\" as \"[%|Htok]\"; first by congruence. iFrame \"Htok\". }\n\n  iDestruct (big_sepM2_delete with \"Hprocessed\") as \"[Hproc Hprocessed]\"; eauto.\n  iDestruct \"Hproc\" as \"[%|Hproc]\"; first by intuition congruence.\n\n  iDestruct (big_sepM2_insert_delete _ _ _ _ true true with \"[$Hprocessed]\") as \"Hprocessed\".\n  { iLeft. iRight. done. }\n\n  iCombine \"Hret Hret2\" as \"Hret\".\n  iMod (ghost_var_update true with \"Hret\") as \"[Hret Hret2]\".\n\n  iMod (\"Hclose_s\" with \"[-Hclose_c Hproc Hret Hret2]\") as \"_\".\n  { iExists _, _, _, _. iFrame.\n    rewrite insert_id; eauto. iFrame. }\n\n  iFrame.\n  iMod (\"Hclose_c\" with \"[-]\") as \"_\".\n  { iFrame \"#\". iFrame. }\n\n  done.\nQed.\n\nEnd lockservice_proof.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/lockservice/scratch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2490363036772338}}
{"text": "(*===========================================================================\n    Predicates over system state: actually predicates over a subset of\n    processor state, in order to define separating conjunction nicely.\n  ===========================================================================*)\nRequire Import Ssreflect.ssreflect Ssreflect.ssrfun Ssreflect.ssrbool Ssreflect.eqtype Ssreflect.fintype Ssreflect.finfun Ssreflect.seq Ssreflect.tuple.\nRequire Import x86proved.bitsrep x86proved.pfun x86proved.x86.reg x86proved.x86.mem x86proved.x86.flags.\nRequire Import x86proved.pmap x86proved.pmapprops.\nRequire Import Coq.Setoids.Setoid x86proved.charge.csetoid Coq.Classes.Morphisms.\n\n\n(* Importing this file really only makes sense if you also import ilogic, so we\n   force that. *)\nRequire Export x86proved.charge.ilogic x86proved.charge.bilogic x86proved.ilogicss x86proved.charge.sepalg.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n(*---------------------------------------------------------------------------\n    Define partial states and lift definitions and lemmas from partial functions\n\n    A partial state consists of\n    - a partial register file\n    - a partial memory map\n    - a partial flag file\n  ---------------------------------------------------------------------------*)\n\nInductive Frag := Registers | Memory | Flags.\nDefinition fragDom d :=\n  match d with\n  | Registers => RegPiece\n  | Memory => PTR\n  | Flags => Flag\n  end.\n\nDefinition fragTgt d :=\n  match d with\n  | Registers => BYTE\n    (* None = \"memory not mapped\" or \"memory inaccessible\".\n       Access to such memory should cause a trap handler to be executed *)\n  | Memory => option BYTE\n\n    (* FlagUnspecified = \"unspecified\", and might not even be stable\n       (e.g. two reads of the flag won't necessarily be consistent) *)\n  | Flags => FlagVal\n  end.\n\n(* None = \"not described\" for the purposes of separation logic *)\nDefinition PState := forall f: Frag, fragDom f -> option (fragTgt f).\n\nStructure StateFrag : Type := {frag:Frag; carrier:>Type}.\nCanonical Structure AnyRegStateFrag := @Build_StateFrag Registers AnyReg.\nCanonical Structure RegStateFrag := @Build_StateFrag Registers Reg.\nCanonical Structure NonSPRegStateFrag := @Build_StateFrag Registers NonSPReg.\nCanonical Structure FlagStateFrag := Build_StateFrag Flags Flag.\n\nDefinition fragOf {sf: StateFrag} (x: carrier sf) := frag sf.\n\nDefinition emptyPState : PState := fun _ => empFun _.\n\nDefinition addRegPieceToPState (s:PState) (rp:RegPiece) (v:BYTE) : PState :=\n  fun (f:Frag) =>\n  match f as f in Frag return fragDom f -> option (fragTgt f) with\n  | Registers => fun rp' => if rp == rp' then Some v else s Registers rp'\n  | Flags => s Flags\n  | Memory => s Memory\n  end.\n\nDefinition addFlagToPState (s:PState) f v : PState :=\n  fun (fr:Frag) =>\n  match fr as fr in Frag return fragDom fr -> option (fragTgt fr) with\n  | Registers => s Registers\n  | Flags => fun f' => if f == f' then Some v else s Flags f'\n  | Memory => s Memory\n  end.\n\nDefinition addBYTEToPState (s:PState) (p:PTR) b : PState :=\n  fun (fr:Frag) =>\n  match fr as fr in Frag return fragDom fr -> option (fragTgt fr) with\n  | Memory => fun p' => if p == p' then Some (Some b) else s Memory p'\n  | Registers => s Registers\n  | Flags => s Flags\n  end.\n\n(*\nDefinition addToPState (f:Frag) (s: PState) : fragDom f -> fragTgt f -> PState :=\n  match f with (* as f in Frag return fragDom f -> option (fragTgt f) with *)\n  | Registers => fun r v => addRegToPState s r v\n  | Flags => fun f v => addFlagToPState s f v\n  | Memory => fun p v => addBYTEToPState s p v\n  end.\n\nDefinition genericAddToPState (f:StateFrag) (s: PState) (x: carrier f) (v: fragTgt (frag f)) := @addToPState (frag f) s x v.\n\nCheck (fun s => genericAddToPState s EAX #0).\nDefinition undefRegToPState s r :=\n  mkPState (fun r' => if r==r' then None else pregisters s r') (pmemory s) (pflags s) (ptrace s).\n*)\n\n(*\nDefinition addGenRegToPState s r v :=\n  mkPState (fun r' => if r==r' then v else pregisters s r') (pmemory s) (pflags s) (ptrace s).\n*)\n\n\nDefinition extendState (s1 s2: PState) : PState := fun f => extend (s1 f) (s2 f).\nDefinition stateIncludedIn (s1 s2: PState) := forall f, includedIn (s1 f) (s2 f).\n\nLemma stateIncludedIn_trans (s1 s2 s3:PState) :\n  stateIncludedIn s1 s2 -> stateIncludedIn s2 s3 -> stateIncludedIn s1 s3.\nProof. move => H1 H2 f. by apply: includedIn_trans. Qed.\n\n(*\nLemma stateIncludedIn_modReg : forall (s1 s2:PState) (r:AnyReg) x, stateIncludedIn s1 s2 ->\nstateIncludedIn (addRegToPState s1 r x) (addRegToPState s2 r x).\nProof.\nrewrite /stateIncludedIn /addRegToPState /includedIn; simpl; move => s1 s2 r v Hincl.\ndestruct Hincl.\nsplit. move => r0 y.\nassert (r === r0 \\/ r != r0).\ndestruct r; destruct r0; auto.\ndestruct r; destruct r0; auto.\ndestruct n; destruct n0; auto.\ndestruct H1 as [H1 | H1].\nrewrite H1; auto.\nrewrite (negPf H1). auto.\nauto.\nQed.\n\nLemma stateIncludedIn_modGenReg : forall (s1 s2:PState) (r:AnyReg) v, stateIncludedIn s1 s2 ->\nstateIncludedIn (addGenRegToPState s1 r v) (addGenRegToPState s2 r v).\nProof.\nrewrite /stateIncludedIn /addGenRegToPState /includedIn; simpl; move => s1 s2 r v Hincl.\ndestruct Hincl.\nsplit. move => r0.\nassert (r === r0 \\/ r != r0).\ndestruct r; destruct r0; auto.\ndestruct r; destruct r0; auto.\ndestruct n; destruct n0; auto.\ndestruct H1 as [H1 | H1].\nrewrite H1; auto.\nrewrite (negPf H1). auto.\nauto.\nQed.\n*)\n\nDefinition stateSplitsAs (s s1 s2: PState) := forall f, splitsAs (s f) (s1 f) (s2 f).\n\nLemma stateSplitsAsIncludes s s1 s2 :\n  stateSplitsAs s s1 s2 -> stateIncludedIn s1 s /\\ stateIncludedIn s2 s.\nProof. move => H.\nsplit => f. apply (proj1 (splitsAsIncludes (H f))). apply (proj2 (splitsAsIncludes (H f))).\nQed.\n\nLemma stateSplitsAsExtendL s s1 s2 s3 s4 : stateSplitsAs s s1 s2 -> stateSplitsAs s2 s3 s4 ->\n  stateSplitsAs s (extendState s1 s3) s4.\nProof. move => H1 H2 f. by apply: splitsAsExtendL. Qed.\n\nLemma stateSplitsAsExtends s s1 s2 : stateSplitsAs s s1 s2 -> s = extendState s1 s2.\nProof.\n  move => H.\n  extensionality f.\n  extensionality x.\n  exact: splitsAsExtend.\nQed.\n\nLemma stateSplitsAs_s_emp_s s : stateSplitsAs s emptyPState s.\nProof. move => f. apply: splitsAs_f_emp_f. Qed.\n\nLemma stateSplitsAs_s_s_emp s : stateSplitsAs s s emptyPState.\nProof. move => f. apply: splitsAs_f_f_emp. Qed.\n\nLemma stateSplitsAs_s_emp_t s t : stateSplitsAs s emptyPState t -> s = t.\nProof. move => H. extensionality f.\napply: functional_extensionality. apply: splitsAs_f_emp_g. apply: H.\nQed.\n\nLemma stateSplitsAs_s_t_emp s t : stateSplitsAs s t emptyPState -> s = t.\nProof. move => H. extensionality f.\napply: functional_extensionality. apply: splitsAs_f_g_emp. apply: H.\nQed.\n\nLemma stateSplitsAs_s_t_s s t: stateSplitsAs s t s -> t = emptyPState.\nProof. move => H. extensionality f.\napply: functional_extensionality. apply: splitsAs_f_g_f. apply H.\nQed.\n\nLemma stateSplitsAs_s_s_t s t: stateSplitsAs s s t -> t = emptyPState.\nProof. move => H. extensionality f.\napply: functional_extensionality. apply: splitsAs_f_f_g. apply H.\nQed.\n\nLemma stateSplitsAsIncludedInSplitsAs f f1 f2 g :\n    stateSplitsAs f f1 f2 -> stateIncludedIn f g -> exists g1, exists g2,\n    stateSplitsAs g g1 g2 /\\ stateIncludedIn f1 g1 /\\ stateIncludedIn f2 g2.\nProof. move => H1 H2.\nexists f1.\nset g2 := fun fr => fun x => if f1 fr x is Some _ then None else if f2 fr x is Some y then Some y else g fr x.\nexists g2.\nsplit => //.\nmove => fr. apply (splitsAsIncludedInSplitsAs (H1 fr) (H2 fr)).\nsplit => //.\nmove => fr. apply (splitsAsIncludedInSplitsAs (H1 fr) (H2 fr)).\nQed.\n\n(* a version more faithful to [splitsAsIncludedInSplitsAs] *)\nLemma stateSplitsAsIncludedInSplitsAs' (f f1 f2 g: PState) :\n  stateSplitsAs f f1 f2 -> stateIncludedIn f g ->\n  exists g2,\n  stateSplitsAs g f1 g2 /\\ stateIncludedIn f2 g2.\nProof.\n  move=> Hsplit Hinc.\n  exists (fun fr => fun x => if f1 fr x is Some _ then None else if f2 fr x is Some y then Some y else g fr x).\n  split => fr; by have [? ?] := splitsAsIncludedInSplitsAs (Hsplit fr) (Hinc fr).\nQed.\n\nLemma stateSplitsAs_functional s1 s2 h i : stateSplitsAs h s1 s2 -> stateSplitsAs i s1 s2 -> h = i.\nProof. move => H1 H2.\nextensionality f.\nspecialize (H1 f). specialize (H2 f).\nhave H:= splitsAs_functional H1 H2.\napply: functional_extensionality.\nmove => x. by specialize (H x).\nQed.\n\nLemma stateSplitsAs_functionalArg s s1 s2 s3 : stateSplitsAs s s2 s1 -> stateSplitsAs s s3 s1 -> s2 = s3.\nProof. move => H1 H2.\nextensionality f.\nspecialize (H1 f). specialize (H2 f).\nhave H := splitsAs_functionalArg H1 H2.\napply: functional_extensionality.\nmove => x. by specialize (H x).\nQed.\n\nLemma stateSplitsAs_commutative s s1 s2 :\n  stateSplitsAs s s1 s2 -> stateSplitsAs s s2 s1.\nProof. move => H f. by apply: splitsAs_commutative. Qed.\n\nLemma stateSplitsAs_associative s s1 s2 s3 s4 :\n  stateSplitsAs s s1 s2 ->\n  stateSplitsAs s2 s3 s4 ->\n  exists s5,\n  stateSplitsAs s s3 s5 /\\\n  stateSplitsAs s5 s1 s4.\nProof. move => H1 H2.\nset s5 := fun fr => fun x => if s4 fr x is Some y then Some y else s1 fr x.\nexists s5.\nsplit; move => fr; apply (splitsAs_associative (H1 fr) (H2 fr)).\nQed.\n\nDefinition restrictState (s: PState) (p: forall f:Frag, fragDom f -> bool) : PState :=\n  fun f => fun x => if p f x then s f x else None.\n\nLemma stateSplitsOn (s: PState) p :\nstateSplitsAs s (restrictState s p)\n                (restrictState s (fun f => fun x => ~~p f x)).\nProof. move => f x.\ncase E: (s f x) => [a |] => //. rewrite /restrictState.\ncase E': (p f x). rewrite E. left; done. right. by rewrite E.\nrewrite /restrictState.  rewrite E.\nby case (p f x).\nQed.\n\n(* Builds a total memory with the same mappings as the partial memory s.\n   Locations that are not in s will be unmapped in the result. *)\nDefinition memComplete (s: PState) : Mem :=\n  pmap_of (fun p =>\n    match s Memory p with\n    | Some (Some v) => Some v\n    | _ => None\n    end).\n\nLemma memComplete_inverse (s: PState) p v:\n  s Memory p = Some v -> (memComplete s) p = v.\nProof.\n  move=> Hsp. rewrite /memComplete. rewrite pmap_of_lookup.\n  rewrite Hsp. by destruct v.\nQed.\n\n\n(*---------------------------------------------------------------------------\n    State predicates, and logical connectives\n    We start without restrictions on predicates, roughly the \"assertions\" of\n    Reynolds' \"Introduction to Separation Logic\", 2009.\n  ---------------------------------------------------------------------------*)\n\nInstance PStateEquiv : Equiv PState := {\n   equiv s1 s2 := forall f, s1 f =1 s2 f\n}.\n\nInstance PStateType : type PState.\nProof.\n  split.\n  move => s f x; reflexivity.\n  move => s1 s2 Hs f x; specialize (Hs f x); symmetry; assumption.\n  move => s1 s2 s3 H12 H23 f x; specialize (H12 f x); specialize (H23 f x).\n  transitivity (s2 f x); assumption.\nQed.\n\nInstance addRegPieceToPStateEquiv_m :\n  Proper (equiv ==> eq ==> eq ==> equiv) addRegPieceToPState.\nProof.\n  move => p q Hpeq r1 r2 Hr1eqr2 w1 w2 Hw1eqw2 f x; subst.\n  destruct f; simpl; rewrite Hpeq; reflexivity.\nQed.\n\nInstance addFlagToPStateEquiv_m :\n  Proper (equiv ==> eq ==> eq ==> equiv) addFlagToPState.\nProof.\n  move => p q Hpeq r1 r2 Hr1eqr2 w1 w2 Hw1eqw2 f x; subst.\n  destruct f; simpl; rewrite Hpeq; reflexivity.\nQed.\n\nInstance addBYTEToPStateEquiv_m :\n  Proper (equiv ==> eq ==> eq ==> equiv) addBYTEToPState.\nProof.\n  move => p q Hpeq r1 r2 Hr1eqr2 w1 w2 Hw1eqw2 f x; subst.\n  destruct f; simpl; rewrite Hpeq; reflexivity.\nQed.\n\nInstance extendStateEquiv_m :\n  Proper (equiv ==> equiv ==> equiv) extendState.\nProof.\n  move => p q Hpeqq r1 r2 Hr1eqr2 f d.\n  unfold extendState, extend.\n  rewrite Hr1eqr2. destruct (r2 f d); [|rewrite Hpeqq]; reflexivity.\nQed.\n\nInstance stateIncludeInEquiv_m :\n  Proper (equiv ==> equiv ==> iff) stateIncludedIn.\nProof.\n  move => p q Hpeqq r1 r2 Hr1eqr2.\n  split; move => H f d y Heq; specialize (H f d y);\n  [rewrite <- Hpeqq in Heq | rewrite Hpeqq in Heq];\n  specialize (H Heq); [rewrite <- Hr1eqr2| rewrite Hr1eqr2];\n  assumption.\nQed.\n\nLemma state_extensional (s1 s2: PState) : (forall f, s1 f =1 s2 f) -> s1 === s2.\nProof. unfold equiv, PStateEquiv; move => H f; apply H. Qed.\n\nProgram Definition my_sa_mul : (PState -s> PState -s> PState -s> Prop) :=\n  lift3s (fun s1 s2 s => forall f, splitsAs (s f) (s1 f) (s2 f)) _ _ _.\nNext Obligation.\n  intros t1 t2 HEqt; unfold equiv, PStateEquiv in HEqt.\n  split; intros; [rewrite <- HEqt | rewrite HEqt]; apply H.\nQed.\nNext Obligation.\n  intros t1 t2 HEqt; unfold equiv, PStateEquiv in HEqt;\n  split; simpl; intros; [rewrite <- HEqt | rewrite HEqt]; apply H.\nQed.\nNext Obligation.\n  intros t1 t2 HEqt; unfold equiv, PStateEquiv in HEqt.\n  split; simpl; intros; [rewrite <- HEqt | rewrite HEqt]; apply H.\nQed.\n\nInstance PStateSepAlgOps: SepAlgOps PState := {\n  sa_unit := emptyPState;\n  sa_mul s1 s2 s := stateSplitsAs s s1 s2\n}.\n\nInstance PStateSepAlg : SepAlg PState.\nProof.\n  split.\n  + move => a b c d Habc Hceqd f; specialize (Hceqd f); rewrite <- Hceqd.\n    apply Habc.\n  + move => a b c d Habc Habd f.\n    eapply splitsAs_functional; [apply Habc | apply Habd].\n  + move => a b c Hbc d. split.\n    - move => Habd f; specialize (Hbc f); rewrite <- Hbc; apply Habd.\n    - move => Hacd f; specialize (Hbc f); rewrite Hbc; apply Hacd.\n  + split; intros; by apply stateSplitsAs_commutative.\n  + move => a b c bc abc H1 H2. eapply stateSplitsAs_associative. apply H1. apply H2.\n  + intros; apply stateSplitsAs_s_s_emp.\nQed.\n\nDefinition SPred := ILFunFrm PState Prop.\n\nLocal Existing Instance ILFun_Ops.\nLocal Existing Instance ILFun_ILogic.\nLocal Existing Instance SABIOps.\nLocal Existing Instance SABILogic.\n\n(* Giving these cost 1 ensures that they are preferred over spec/Prop instances *)\nInstance sepILogicOps : ILogicOps SPred | 1 := _.\nInstance sepLogicOps : BILOperators SPred | 1 := _.\nInstance sepLogic : BILogic SPred | 1 := _.\nGlobal Opaque sepILogicOps sepLogicOps sepLogic.\n\nImplicit Arguments mkILFunFrm [[e] [ILOps]].\n\nDefinition mkSPred (P : PState -> Prop)\n        (f : forall t t' : PState, t === t' -> P t |-- P t') : SPred :=\n  mkILFunFrm PState Prop P f.\n\nImplicit Arguments mkSPred [].\n\nLocal Transparent lentails sepILogicOps.\nProgram Definition eq_pred s := mkSPred (fun s' => s === s') _.\nNext Obligation.\n  rewrite <- H; assumption.\nQed.\n\nLocal Transparent ILFun_Ops.\nInstance eq_pred_equiv_lentails :\n  Proper (equiv ==> lentails) eq_pred.\nProof.\n  move => s t Hseqt u Hsequ; simpl in *.\n  rewrite <- Hseqt. assumption.\nQed.\n\nInstance eq_pred_equiv_lequiv :\n  Proper (equiv ==> lequiv) eq_pred.\nProof.\n  split; apply eq_pred_equiv_lentails; [|symmetry]; assumption.\nQed.\n\nInstance eq_pred_eq_pred_lentails :\n  Proper (eq_pred ==> lentails) eq_pred.\nProof.\n  move => s t Hseqt u Hsequ; simpl in *.\n  rewrite <- Hseqt. assumption.\nQed.\n\nInstance eq_pred_eq_pred_lequiv :\n  Proper (eq_pred ==> lequiv) eq_pred.\nProof.\n  split; apply eq_pred_equiv_lentails; [|symmetry]; assumption.\nQed.\n\nLemma lentails_eq (P : SPred) t :\n  P t <-> eq_pred t |-- P.\nProof.\n  split.\n  - simpl. intros H x H1.\n    assert (P t |-- P x) as H2 by (eapply ILFunFrm_closed; assumption).\n    apply H2; assumption.\n  - simpl; intros; firstorder.\nQed.\n\n\n(* Need lemma about splitting involving a total (e.g. toPState) \"partial\" store.\n   e.g. sa_mul (toPState s) s0 s1 -> s1 = s /\\ s0 = emptyPState *)\nDefinition isTotal T U (f: T -> option U) := forall x, f x <> None.\nDefinition isTotalPState (s: PState) := forall f:Frag, isTotal (s f).\n\nLemma splitsTotal T U (s s0 s1: T -> option U) : isTotal s0 -> splitsAs s s0 s1 -> s =1 s0.\nProof. move => TOT SPLITS. rewrite /splitsAs in SPLITS.\nmove => x. unfold isTotal in TOT.\nspecialize (SPLITS x). specialize (TOT x).\ndestruct (s0 x) => //. destruct (s x) => //.\nelim SPLITS => [[H1 H2] | [H1 H2]]. done. done. by destruct SPLITS.\nQed.\n\nLemma stateSplitsTotal (s s0 s1: PState) : isTotalPState s0 -> stateSplitsAs s s0 s1 -> s === s0.\nProof. move => TOT SPLITS. unfold stateSplitsAs in SPLITS. unfold isTotalPState in TOT.\nmove => f. apply: splitsTotal => //. Qed.\n\nInstance stateSplitsAs_m :\n  Proper (csetoid.equiv ==> csetoid.equiv ==> csetoid.equiv ==> iff) stateSplitsAs.\nProof. move => s1 s2 EQ s1' s2' EQ' s1'' s2'' EQ''.\nsplit => SPLIT f x.\nspecialize (SPLIT f x). specialize (EQ f x). specialize (EQ' f x). specialize (EQ'' f x).\ndestruct (s1 f x); destruct (s2 f x); congruence.\nspecialize (SPLIT f x). specialize (EQ f x). specialize (EQ' f x). specialize (EQ'' f x).\ndestruct (s1 f x); destruct (s2 f x); congruence.\nQed.\n\nLocal Transparent ILFun_Ops SABIOps ltrue.\n\nLemma emp_unit : empSP -|- eq_pred sa_unit.\n  split; simpl; move => x H.\n  + destruct H as [H _]; assumption.\n  + exists H; constructor.\nQed.\n\nLemma eqPredTotal_sepSP_trueR s :\n  isTotalPState s ->\n  eq_pred s -|- eq_pred s ** ltrue.\nProof.\nmove => TOT.\nsplit => s'.\n- apply lentails_eq. exists s, emptyPState. split => //; first apply stateSplitsAs_s_s_emp.\n- move => /= [s1 [s2 [H1 [H2 H3]]]]. hnf in H2, H1. setoid_rewrite <- H2 in H1.\n  apply (stateSplitsTotal TOT) in H1. by rewrite H1.\nQed.\n\nLemma eqPredTotal_sepSP s1 s2 R:\n  isTotalPState s2 ->\n  eq_pred s1 |-- eq_pred s2 ** R ->\n  empSP |-- R.\nProof. move => TOT H.\napply lentails_eq in H. destruct H as [s3 [s4 [H1 [H2 H3]]]].\nsimpl in H2. rewrite <-H2 in H1.\nsimpl in H1.\nrewrite -> (stateSplitsTotal TOT H1) in H1.\napply stateSplitsAs_s_s_t in H1.\nsubst. rewrite emp_unit. by apply lentails_eq.\nQed.\n\nLocal Opaque SABIOps.\n\nGlobal Coercion lbool (b:bool) := lpropand b ltrue.\n\n(*===========================================================================\n    \"is\" predicates on registers and flags\n  ===========================================================================*)\n\nDefinition regPieceIs r v : SPred := eq_pred (addRegPieceToPState emptyPState r v).\nDefinition flagIs f b : SPred := eq_pred (addFlagToPState emptyPState f b).\nDefinition BYTEregIs (r:VRegAny OpSize1) v : SPred := regPieceIs (BYTERegToRegPiece r) v.\n\nDefinition regIs (r:AnyReg) (v:DWORD) : SPred :=\n   regPieceIs (AnyRegPiece r RegIx0) (getRegPiece v RegIx0)\n** regPieceIs (AnyRegPiece r RegIx1) (getRegPiece v RegIx1)\n** regPieceIs (AnyRegPiece r RegIx2) (getRegPiece v RegIx2)\n** regPieceIs (AnyRegPiece r RegIx3) (getRegPiece v RegIx3).\n\nDefinition WORDregIs (r:VRegAny OpSize2) (v:WORD) : SPred :=\n   regPieceIs (AnyRegPiece (WORDRegToReg r) RegIx0) (slice 0 8 8 v)\n** regPieceIs (AnyRegPiece (WORDRegToReg r) RegIx1) (slice 8 8 0 v).\n\nInductive RegOrFlag :=\n| RegOrFlagR s :> VRegAny s -> RegOrFlag\n| RegOrFlagF :> Flag -> RegOrFlag.\n\nDefinition RegOrFlag_target rf :=\nmatch rf with\n| RegOrFlagR s _   => VWORD s\n| RegOrFlagF _     => FlagVal\nend.\n\nDefinition stateIs (x: RegOrFlag) : RegOrFlag_target x -> SPred :=\nmatch x with\n| RegOrFlagR OpSize4 r => regIs r\n| RegOrFlagR OpSize2 r => WORDregIs r\n| RegOrFlagR OpSize1 r => BYTEregIs r\n| RegOrFlagF f => flagIs f\nend.\n\nImplicit Arguments stateIs [].\n\nDefinition stateIsAny x := lexists (stateIs x).\n\nNotation \"x '~=' v\" := (stateIs x v) (at level 70, no associativity, format \"x '~=' v\") : spred_scope.\nNotation \"x '?'\" := (stateIsAny x) (at level 2, format \"x '?'\"): spred_scope.\n\nHint Unfold VWORD RegOrFlag_target : spred.\n(** When dealing with logic, we want to reduce [stateIsAny] and similar to basic building blocks. *)\nHint Unfold stateIsAny : finish_logic_unfolder.\n\n(*---------------------------------------------------------------------------\n     Byte-is predicate\n  ---------------------------------------------------------------------------*)\nProgram Definition byteIs p b : SPred := eq_pred (addBYTEToPState emptyPState p b).\n\nDefinition byteAny p : SPred := lexists (byteIs p).\n\nInstance flagIsEquiv_m :\n  Proper (eq ==> eq ==> csetoid.equiv ==> iff) flagIs.\nProof.\n  intros n m Hneqm f g Hbeqc p q Hpeqq; subst.\n  split; simpl; rewrite <- Hpeqq; tauto.\nQed.\n\nInstance byteIsEquiv_m :\n  Proper (eq ==> eq ==> csetoid.equiv ==> iff) byteIs.\nProof.\n  intros n m Hneqm b c Hbeqc p q Hpeqq; subst.\n  split; simpl; rewrite <- Hpeqq; tauto.\nQed.\n\n(*---------------------------------------------------------------------------\n    Iterated separating conjunction\n  ---------------------------------------------------------------------------*)\nFixpoint isc {A} (I: seq A) (F: A -> SPred) :=\n  match I with\n  | nil => empSP\n  | i :: I' => F i ** isc I' F\n  end.\n\nLemma isc_cat {A} (I J: seq A) F :\n  isc (I ++ J) F -|- isc I F ** isc J F.\nProof.\n  elim: I.\n  - simpl; rewrite sepSPC. rewrite empSPR. reflexivity.\n  - move=> i I IH /=. by rewrite IH sepSPA.\nQed.\n\nLemma isc_snoc {A} (I: seq A) i F :\n  isc (I ++ [:: i]) F -|- isc I F ** F i.\nProof. rewrite isc_cat /=. by rewrite empSPR. Qed.\n\n(*---------------------------------------------------------------------------\n    Strictly exact assertions\n\n    See Section 2.3.2 In Reynolds's \"Introduction to Separation Logic\" online\n    lecture notes.\n    http://www.cs.cmu.edu/afs/cs.cmu.edu/project/fox-19/member/jcr/www15818As2011/cs818A3-11.html\n  ---------------------------------------------------------------------------*)\n\nClass StrictlyExact (P: SPred) := strictly_exact:\n  forall s s', P s -> P s' -> s === s'.\n\nInstance StrictlyExactRegPieceIs r v: StrictlyExact (regPieceIs r v).\nProof. move => s s'. simpl. by move ->. Qed.\n\nInstance StrictlyExactFlagIs f v: StrictlyExact (flagIs f v).\nProof. move => s s'. simpl. by move ->. Qed.\n\nInstance StrictlyExactByteIs p v: StrictlyExact (byteIs p v).\nProof. move => s s'. simpl. by move ->. Qed.\n\nInstance StrictlyExactSep P Q `{PH: StrictlyExact P} `{QH: StrictlyExact Q}\n  : StrictlyExact (P**Q).\nProof. move => s s' [s1 [s2 [H1 [H2 H3]]]] [s1' [s2' [H1' [H2' H3']]]].\nspecialize (PH s1 s1' H2 H2').\nspecialize (QH s2 s2' H3 H3').\nrewrite -> PH, QH in H1.\nby rewrite (stateSplitsAsExtends H1) (stateSplitsAsExtends H1').\nQed.\n\nInstance StrictlyExactRegIs r v: StrictlyExact (regIs r v).\nProof. rewrite /regIs. do 3 (apply StrictlyExactSep; first apply StrictlyExactRegPieceIs).\napply StrictlyExactRegPieceIs. Qed.\n\nInstance StrictlyExactEmpSP : StrictlyExact empSP.\nProof. move => s s' H H'.\ndestruct H as [H _]. destruct H' as [H' _].\nby rewrite -H -H'.\nQed.\n\nInstance StrictlyExactConj P Q `{PH: StrictlyExact P} `{QH: StrictlyExact Q}\n  : StrictlyExact (P //\\\\ Q).\nProof. move => s s' [H1 H2] [H1' H2'].\nby apply (PH s s' H1 H1').\nQed.\n\nClass Precise (P: SPred) := precise:\n  forall s s1 s2, stateIncludedIn s1 s -> stateIncludedIn s2 s -> P s1 -> P s2 -> s1 === s2.\n\nInstance PreciseStrictlyExact P `{PH: StrictlyExact P} : Precise P.\nProof. move => s s1 s2 H1 H2. intuition. Qed.\n\nCorollary Distributive P0 P1 Q `{QH: Precise Q} :\n  (P0 ** Q) //\\\\ (P1 ** Q) |-- (P0 //\\\\ P1) ** Q.\nProof.\nunfold \"|--\". rewrite /sepILogicOps/ILFun_Ops. move => s [H0 H1].\ndestruct H0 as [s0 [s0' [H0a [H0b H0c]]]].\ndestruct H1 as [s1 [s1' [H1a [H1b H1c]]]].\nhave SSI0 := stateSplitsAsIncludes H0a.\nhave SSI1 := stateSplitsAsIncludes H1a.\ndestruct SSI0 as [SSI0a SSI0b].\ndestruct SSI1 as [SSI1a SSI1b].\nhave QH1 := (QH _ _ _ SSI0b SSI1b H0c H1c).\nexists s0. exists s1'.\nsplit. rewrite -> QH1 in H0a.\n\nexact H0a.\nsplit. split. exact H0b. rewrite -> QH1 in SSI0b.\nrewrite -> QH1 in H0a.\nrewrite <- (stateSplitsAs_functionalArg H1a H0a). exact H1b.\nexact H1c.\nQed.\n\n(*---------------------------------------------------------------------------\n    A partial application of [eq] is a predicate\n  ---------------------------------------------------------------------------*)\n\nLemma stateSplitsAs_eq s s1 s2:\n  sa_mul s1 s2 s ->\n  eq_pred s1 ** eq_pred s2 -|- eq_pred s.\nProof.\n  split.\n  - move=> s' [s1' [s2' [Hs' [Hs1' Hs2']]]].\n    Opaque sa_mul.\n    simpl in *.\n    rewrite <- Hs1', <- Hs2' in Hs'.\n    eapply sa_mul_eqR; eassumption.\n  - simpl. move=> s' H1.\n    rewrite -> H1 in H.\n    exists s1; exists s2; done.\nQed.\n\nLemma ILFun_exists_eq (P : SPred) :\n  P -|- Exists s, P s /\\\\ eq_pred s.\nProof.\n  split; intros s Hs.\n  - exists s. constructor; simpl; intuition.\n  - simpl in *; destruct Hs as [x [Hp Hs]].\n    assert (P x |-- P s) as H by (eapply ILFunFrm_closed; assumption).\n    by apply H.\nQed.\n\nGlobal Opaque PStateSepAlgOps.\n\n(*---------------------------------------------------------------------------\n    Some lemmas about the domains of primitive points-to-like predicates\n  ---------------------------------------------------------------------------*)\nOpen Scope spred_scope.\n\nLemma regPieceIs_same (r:RegPiece) v1 v2 : regPieceIs r v1 ** regPieceIs r v2 |-- lfalse.\nProof.  move => s [s1 [s2 [H1 [H1a H1b]]]].\nsimpl in H1a, H1b. rewrite <-H1a in H1. rewrite <-H1b in H1.\nrewrite /sa_mul/PStateSepAlgOps/= in H1.\nspecialize (H1 Registers r). simpl in H1.\ndestruct (s Registers r); rewrite eq_refl in H1.\ndestruct H1; by destruct H.\nby destruct H1.\nQed.\n\nLemma sepRev4 P Q R S : P ** Q ** R ** S -|- S ** R ** Q ** P.\nProof. rewrite (sepSPC P). rewrite (sepSPC Q). rewrite (sepSPC R).\nby rewrite !sepSPA. Qed.\n\nLemma regIs_same s (r:VRegAny s) (v1 v2:VWORD s) : r ~= v1 ** r ~= v2 |-- lfalse.\nProof. destruct s. \n- apply regPieceIs_same. \n- destruct r. admit. \n- rewrite /stateIs/regIs. \n  rewrite sepRev4. rewrite sepSPA.\n  rewrite sepRev4. rewrite -!sepSPA. rewrite -> (@regPieceIs_same (AnyRegPiece r RegIx0)).\n  by rewrite !sepSP_falseL. \nQed.\n\nLemma flagIs_same (f:Flag) v1 v2 : f ~= v1 ** f ~= v2 |-- lfalse.\nProof.  move => s [s1 [s2 [H1 [H1a H1b]]]].\nsimpl in H1a, H1b. rewrite <-H1a in H1. rewrite <-H1b in H1.\nrewrite /sa_mul/PStateSepAlgOps/= in H1.\nspecialize (H1 Flags f). simpl in H1.\ndestruct (s Flags f); rewrite eq_refl in H1.\ndestruct H1; by destruct H.\nby destruct H1.\nQed.\n\nLemma byteIs_same p v1 v2 : byteIs p v1 ** byteIs p v2 |-- lfalse.\nProof.  move => s [s1 [s2 [H1 [H1a H1b]]]].\nsimpl in H1a, H1b. rewrite <-H1a in H1. rewrite <-H1b in H1.\nrewrite /sa_mul/PStateSepAlgOps/= in H1.\nspecialize (H1 Memory p). simpl in H1.\ndestruct (s Memory p); rewrite eq_refl in H1.\ndestruct H1; by destruct H.\nby destruct H1.\nQed.\n\n(* We don't want simpl to unfold this *)\nGlobal Opaque stateIs.\n\n", "meta": {"author": "nbenton", "repo": "x86proved", "sha": "7a58960f6456ee09dd46c990204a30c2fdd7fa1a", "save_path": "github-repos/coq/nbenton-x86proved", "path": "github-repos/coq/nbenton-x86proved/x86proved-7a58960f6456ee09dd46c990204a30c2fdd7fa1a/src/spred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2490362979086967}}
{"text": "(* This file defines a simple escrow contract based on the \"safe remote\npurchase\" example in Solidity's docs. This contract allows a seller to sell an\nitem in a trustless setting assuming economically rational actors. With the\npremise that the seller wants to sell an item for 1 ETH, the contract works in\nthe following way:\n\n1. The seller deploys the contract and commits 2 ETH.\n2. The buyer commits 2 ETH before the deadline.\n3. The seller hands over the item (outside of the smart contract).\n4. The buyer confirms he has received the item. He gets 1 ETH back\nwhile the seller gets 3 ETH back.\n\nIf the buyer does not commit the funds, the seller gets his money back after the\ndeadline. The economic rationality shows up in our assumption that the seller\nwill confirm he has received the item to get his own funds back. *)\n\nFrom Coq Require Import List.\nFrom Coq Require Import Morphisms.\nFrom Coq Require Import ZArith.\nFrom Coq Require Import Permutation.\nFrom Coq Require Import Psatz.\nRequire Import Automation.\nRequire Import Blockchain.\nRequire Import Extras.\nRequire Import Monads.\nRequire Import Serializable.\nFrom RecordUpdate Require Import RecordUpdate.\n\nImport ListNotations.\nImport RecordSetNotations.\n\nSection Escrow.\nContext `{Base : ChainBase}.\n\nSet Nonrecursive Elimination Schemes.\n\nRecord Setup :=\n  build_setup {\n      setup_buyer : Address;\n    }.\n\nInductive NextStep :=\n(* Waiting for buyer to commit itemvalue * 2 *)\n| buyer_commit\n(* Waiting for buyer to confirm item received *)\n| buyer_confirm\n(* Waiting for buyer and seller to withdraw their funds. *)\n| withdrawals\n(* No next step, sale is done. *)\n| none.\n\nRecord State :=\n  build_state {\n      last_action : nat;\n      next_step : NextStep;\n      seller : Address;\n      buyer : Address;\n      seller_withdrawable : Amount;\n      buyer_withdrawable : Amount;\n    }.\n\nInductive Msg :=\n| commit_money\n| confirm_item_received\n| withdraw.\n\nGlobal Instance State_settable : Settable _ :=\n  settable! build_state <last_action; next_step; seller; buyer;\n                         seller_withdrawable; buyer_withdrawable>.\n\nGlobal Instance Setup_serializable : Serializable Setup :=\n  Derive Serializable Setup_rect<build_setup>.\n\nGlobal Instance NextStep_serializable : Serializable NextStep :=\n  Derive Serializable NextStep_rect<buyer_commit, buyer_confirm, withdrawals, none>.\n\nGlobal Instance State_serializable : Serializable State :=\n  Derive Serializable State_rect<build_state>.\n\nGlobal Instance Msg_serializable : Serializable Msg :=\n  Derive Serializable Msg_rect<commit_money, confirm_item_received, withdraw>.\n\nOpen Scope Z.\nDefinition init (chain : Chain) (ctx : ContractCallContext) (setup : Setup)\n  : option State :=\n  let seller := ctx_from ctx in\n  let buyer := setup_buyer setup in\n  do if (buyer =? seller)%address then None else Some tt;\n  do if ctx_amount ctx =? 0 then None else Some tt;\n  do if Z.even (ctx_amount ctx) then Some tt else None;\n  Some (build_state (current_slot chain) buyer_commit seller buyer 0 0).\n\nDefinition receive\n           (chain : Chain) (ctx : ContractCallContext)\n           (state : State) (msg : option Msg)\n  : option (State * list ActionBody) :=\n  match msg, next_step state with\n  | Some commit_money, buyer_commit =>\n    let item_price := (account_balance chain (ctx_contract_address ctx)\n                       - ctx_amount ctx) / 2 in\n    let expected := item_price * 2 in\n    do if (ctx_from ctx =? buyer state)%address then Some tt else None;\n    do if ctx_amount ctx =? expected then Some tt else None;\n    Some (state<|next_step := buyer_confirm|>\n               <|last_action := current_slot chain|>, [])\n\n  | Some confirm_item_received, buyer_confirm =>\n    let item_price := account_balance chain (ctx_contract_address ctx) / 4 in\n    do if (ctx_from ctx =? buyer state)%address then Some tt else None;\n    do if ctx_amount ctx =? 0 then Some tt else None;\n    let new_state :=\n        state<|next_step := withdrawals|>\n             <|buyer_withdrawable := item_price|>\n             <|seller_withdrawable := item_price * 3|> in\n    Some (new_state, [])\n\n  | Some withdraw, withdrawals =>\n    do if ctx_amount ctx =? 0 then Some tt else None;\n    let from := ctx_from ctx in\n    do '(to_pay, new_state) <-\n       match from =? buyer state, from =? seller state with\n       | true, _ => Some (buyer_withdrawable state, state<|buyer_withdrawable := 0|>)\n       | _, true => Some (seller_withdrawable state, state<|seller_withdrawable := 0|>)\n       | _, _ => None\n       end%address;\n    do if to_pay >? 0 then Some tt else None;\n    let new_state :=\n        match buyer_withdrawable new_state, seller_withdrawable new_state with\n        | 0, 0 => new_state<|next_step := none|>\n        | _, _ => new_state\n        end in\n    Some (new_state, [act_transfer (ctx_from ctx) to_pay])\n\n  | Some withdraw, buyer_commit =>\n    do if ctx_amount ctx =? 0 then Some tt else None;\n    do if (last_action state + 50 <? current_slot chain)%nat then None else Some tt;\n    do if (ctx_from ctx =? seller state)%address then Some tt else None;\n    let balance := account_balance chain (ctx_contract_address ctx) in\n    Some (state<|next_step := none|>, [act_transfer (seller state) balance])\n\n  | _, _ => None\n  end.\n\nLtac solve_contract_proper :=\n  repeat\n    match goal with\n    | [|- @bind _ ?m _ _ _ _ = @bind _ ?m _ _ _ _] => unfold bind, m\n    | [|- ?x _  = ?x _] => unfold x\n    | [|- ?x _ _ = ?x _ _] => unfold x\n    | [|- ?x _ _ _ = ?x _ _ _] => unfold x\n    | [|- ?x _ _ _ _ = ?x _ _ _ _] => unfold x\n    | [|- ?x _ _ _ _ = ?x _ _ _ _] => unfold x\n    | [|- ?x _ _ _ _ _ = ?x _ _ _ _ _] => unfold x\n    | [|- Some _ = Some _] => f_equal\n    | [|- pair _ _ = pair _ _] => f_equal\n    | [|- (if ?x then _ else _) = (if ?x then _ else _)] => destruct x\n    | [|- match ?x with | _ => _ end = match ?x with | _ => _ end ] => destruct x\n    | [H: ChainEquiv _ _ |- _] => rewrite H in *\n    | _ => subst; auto\n    end.\n\nProgram Definition contract : Contract Setup Msg State :=\n  build_contract init _ receive _.\nNext Obligation. repeat intro; solve_contract_proper. Qed.\nNext Obligation. repeat intro; solve_contract_proper. Qed.\n\nSection Theories.\n  Lemma no_self_calls bstate caddr :\n    reachable bstate ->\n    env_contracts bstate caddr = Some (Escrow.contract : WeakContract) ->\n    Forall (fun abody => match abody with\n                         | act_transfer to _ => (to =? caddr)%address = false\n                         | _ => False\n                         end) (outgoing_acts bstate caddr).\n  Proof.\n    contract_induction; intros; cbn in *; auto.\n    - now inversion IH.\n    - apply Forall_app; split; try tauto.\n      clear IH.\n      unfold receive in receive_some.\n      destruct_match as [[]|] in receive_some; try congruence.\n      + destruct_match in receive_some; try congruence.\n        destruct_match in receive_some; cbn in *; try congruence.\n        destruct_match in receive_some; cbn in *; try congruence.\n        inversion_clear receive_some; auto.\n      + destruct_match in receive_some; try congruence.\n        destruct_match in receive_some; cbn in *; try congruence.\n        destruct_match in receive_some; cbn in *; try congruence.\n        inversion_clear receive_some; auto.\n      + destruct_match in receive_some; try congruence.\n        * destruct_match in receive_some; cbn in *; try congruence.\n          destruct_match in receive_some; cbn in *; try congruence.\n          destruct (address_eqb_spec (ctx_from ctx) (seller prev_state)) as\n              [<-|]; cbn in *; try congruence.\n          inversion_clear receive_some.\n          constructor; try constructor.\n          apply address_eq_ne; auto.\n        * destruct_match in receive_some; cbn in *; try congruence.\n          destruct_match in receive_some; cbn in *; try congruence.\n          destruct_match in receive_some.\n          destruct_match in receive_some; cbn in *; try congruence.\n          inversion_clear receive_some.\n          constructor; try constructor.\n          apply address_eq_ne; auto.\n    - inversion_clear IH as [|? ? head_not_me tail_not_me].\n      apply Forall_app; split; auto; clear tail_not_me.\n      destruct head; try contradiction.\n      destruct action_facts as [? [? ?]].\n      destruct_address_eq; congruence.\n    - now rewrite <- perm.\n    - instantiate (DeployFacts := fun _ _ => True).\n      instantiate (CallFacts := fun _ _ _ => True).\n      instantiate (AddBlockFacts := fun _ _ _ _ _ _ => True).\n      unset_all; subst; cbn in *.\n      destruct_chain_step; auto.\n      destruct_action_eval; auto.\n  Qed.\n\n  Definition txs_to (to : Address) (txs : list Tx) : list Tx :=\n    filter (fun tx => (tx_to tx =? to)%address) txs.\n\n  Arguments txs_to : simpl never.\n\n  Lemma txs_to_cons addr tx txs :\n    txs_to addr (tx :: txs) =\n    if (tx_to tx =? addr)%address then\n      tx :: txs_to addr txs\n    else\n      txs_to addr txs.\n  Proof. reflexivity. Qed.\n\n  Definition txs_from (from : Address) (txs : list Tx) : list Tx :=\n    filter (fun tx => (tx_from tx =? from)%address) txs.\n\n  Arguments txs_from : simpl never.\n\n  Lemma txs_from_cons addr tx txs :\n    txs_from addr (tx :: txs) =\n    if (tx_from tx =? addr)%address then\n      tx :: txs_from addr txs\n    else\n      txs_from addr txs.\n  Proof. reflexivity. Qed.\n\n  Local Open Scope bool.\n  Definition buyer_confirmed (inc_calls : list (ContractCallInfo Msg)) buyer :=\n    existsb (fun call => (call_from call =? buyer)%address &&\n                         match call_msg call with\n                         | Some confirm_item_received => true\n                         | _ => false\n                         end) inc_calls.\n\n  Definition transfer_acts_to addr acts :=\n    filter (fun a => match a with\n                     | act_transfer to _ => (to =? addr)%address\n                     | _ => false\n                     end) acts.\n\n  Arguments transfer_acts_to : simpl never.\n\n  Lemma transfer_acts_to_cons addr act acts :\n    transfer_acts_to addr (act :: acts) =\n    if match act with\n       | act_transfer to _ => (to =? addr)%address\n       | _ => false\n       end\n    then\n      act :: transfer_acts_to addr acts\n    else\n      transfer_acts_to addr acts.\n  Proof. reflexivity. Qed.\n\n  Definition money_to\n             {bstate_from bstate_to}\n             (trace : ChainTrace bstate_from bstate_to)\n             caddr addr :=\n    sumZ tx_amount (txs_to addr (outgoing_txs trace caddr)) +\n    sumZ act_body_amount (transfer_acts_to addr (outgoing_acts bstate_to caddr)).\n\n  Lemma escrow_correct_strong bstate caddr (trace : ChainTrace empty_state bstate) :\n    env_contracts bstate caddr = Some (Escrow.contract : WeakContract) ->\n    exists (cstate : State)\n           (depinfo : DeploymentInfo Setup)\n           (inc_calls : list (ContractCallInfo Msg)),\n      deployment_info Setup trace caddr = Some depinfo /\\\n      contract_state bstate caddr = Some cstate /\\\n      incoming_calls Msg trace caddr = Some inc_calls /\\\n      let item_worth := deployment_amount depinfo / 2 in\n      let seller_addr := deployment_from depinfo in\n      let buyer_addr := setup_buyer (deployment_setup depinfo) in\n      deployment_amount depinfo = 2 * item_worth /\\\n      item_worth > 0 /\\\n      seller cstate = seller_addr /\\\n      buyer cstate = buyer_addr /\\\n      buyer_addr <> seller_addr /\\\n      forallb (fun act => match act with\n                         | act_transfer _ _ => true\n                         | _ => false\n                         end) (outgoing_acts bstate caddr) = true /\\\n      match next_step cstate with\n      | buyer_commit =>\n        account_balance bstate caddr = 2 * item_worth /\\\n        outgoing_acts bstate caddr = [] /\\\n        outgoing_txs trace caddr = [] /\\\n        inc_calls = []\n\n      | buyer_confirm =>\n        account_balance bstate caddr = 4 * item_worth /\\\n        outgoing_acts bstate caddr = [] /\\\n        outgoing_txs trace caddr = [] /\\\n        inc_calls = [build_call_info buyer_addr (2 * item_worth) (Some commit_money)]\n\n      | withdrawals =>\n        buyer_confirmed inc_calls buyer_addr = true /\\\n        filter (fun c => negb (call_amount c =? 0)%Z ) inc_calls =\n        [build_call_info buyer_addr (2 * item_worth) (Some commit_money)] /\\\n        money_to trace caddr seller_addr + seller_withdrawable cstate = 3 * item_worth /\\\n        money_to trace caddr buyer_addr + buyer_withdrawable cstate = 1 * item_worth\n\n      | none =>\n        buyer_confirmed inc_calls buyer_addr = true /\\\n        filter (fun c => negb (call_amount c =? 0)%Z) inc_calls =\n        [build_call_info buyer_addr (2 * item_worth) (Some commit_money)] /\\\n        money_to trace caddr seller_addr = 3 * item_worth /\\\n        money_to trace caddr buyer_addr = 1 * item_worth \\/\n\n        inc_calls = [build_call_info seller_addr 0 (Some withdraw)] /\\\n        money_to trace caddr seller_addr = 2 * item_worth /\\\n        money_to trace caddr buyer_addr = 0\n      end.\n  Proof.\n    unfold money_to.\n    contract_induction; cbn in *; intros.\n    - (* New block *)\n      auto.\n    - (* Deployment *)\n      unfold Escrow.init in *.\n      destruct (address_eqb_spec (setup_buyer setup) (ctx_from ctx));\n        cbn in *; try congruence.\n      destruct (ctx_amount ctx =? 0) eqn:amount_some; cbn in *; try congruence.\n      destruct (Z.even (ctx_amount ctx)) eqn:amount_even; cbn in *; try congruence.\n      inversion init_some; subst; clear init_some.\n      cbn.\n      assert (2 * (ctx_amount ctx / 2) > 0 -> ctx_amount ctx / 2 > 0) by lia.\n      enough (2 * (ctx_amount ctx / 2) > 0 /\\\n              ctx_amount ctx = 2 * (ctx_amount ctx / 2)) by tauto.\n      assert (ctx_amount ctx mod 2 = 0).\n      {\n        rewrite Zeven_mod in amount_even.\n        unfold Zeq_bool in *.\n        destruct_match eqn:amount_mod_2 in amount_even; try congruence; auto.\n        destruct (Z.compare_spec (ctx_amount ctx mod 2) 0); auto; try congruence.\n      }\n      rewrite <- (Z_div_exact_2 (ctx_amount ctx) 2) by (auto; lia).\n      split; auto.\n      instantiate (DeployFacts := fun _ ctx => ctx_amount ctx >= 0);\n        subst DeployFacts; cbn in *.\n      apply Z.eqb_neq in amount_some.\n      lia.\n    - (* Transfer from contract to someone *)\n      repeat rewrite txs_to_cons.\n      do 5 (split; try tauto).\n      destruct IH as [_ [_ [_ [<- [_ [only_transfers IH]]]]]].\n      apply andb_prop in only_transfers.\n      split; try tauto.\n      destruct only_transfers as [is_transfer _].\n      destruct out_act; try congruence.\n      destruct tx_act_match as [<- [<- _]].\n      repeat rewrite transfer_acts_to_cons in *.\n      destruct (next_step cstate).\n      + intuition congruence.\n      + intuition congruence.\n      + (* Transfer while next_step is withdraw; so seller or buyer withdrew *)\n        do 2 (split; try tauto).\n        destruct IH as [_ [_ [? ?]]].\n        destruct_address_eq; cbn in *; lia.\n      + (* Transfer while next_step is none; action moved from queue to txs *)\n        destruct IH as [IH | IH]; [left|right].\n        * do 2 (split; try tauto).\n          destruct IH as [_ [? ?]].\n          destruct_address_eq; cbn in *; lia.\n        * split; try tauto.\n          destruct IH as [_ ?].\n          destruct_address_eq; cbn in *; lia.\n    - (* Call from someone else *)\n      do 2 (split; try tauto).\n      unfold Escrow.receive in *.\n      set (item_worth := deployment_amount dep_info / 2) in *.\n      destruct msg as [[| |]|].\n      + (* Some commit_money *)\n        destruct (next_step prev_state); try congruence.\n        destruct (address_eqb_spec (ctx_from ctx) (buyer prev_state)) as [->|];\n          cbn in *; try congruence.\n        destruct (ctx_amount ctx =? _) eqn:proper_amount in receive_some;\n          cbn in *; try congruence.\n        inversion_clear receive_some.\n        cbn.\n        do 4 (split; try tauto).\n        destruct IH as [deployed_even [_ [_ [-> [_ [_ [balance_eq [-> [-> ->]]]]]]]]].\n        apply Z.eqb_eq in proper_amount.\n        rewrite balance_eq in proper_amount.\n        rewrite proper_amount.\n        replace (account_balance _ _) with (2 * item_worth + 2 * item_worth / 2 * 2) by lia.\n        rewrite <- Z.mul_comm.\n        rewrite Z.div_mul by lia.\n        repeat split; auto.\n        lia.\n      + (* Some confirm_item_received *)\n        destruct_match in receive_some; cbn in *; try congruence.\n        destruct (address_eqb_spec (ctx_from ctx) (buyer prev_state)) as [->|];\n          cbn in *; try congruence.\n        destruct (ctx_amount ctx =? 0) eqn:zero_amount in receive_some;\n          cbn in *; try congruence.\n        inversion_clear receive_some.\n        cbn.\n        do 4 (split; try tauto).\n        destruct IH as [deployed_even [? [<- [<- [_ [_ [balance_eq [-> [-> ->]]]]]]]]].\n        rewrite address_eq_refl.\n        cbn.\n        split; auto.\n        unfold txs_to, transfer_acts_to; cbn.\n        apply Z.eqb_eq in zero_amount.\n        rewrite zero_amount in *.\n        replace (account_balance _ _) with (4 * item_worth) in * by lia.\n        rewrite (Z.mul_comm 4).\n        rewrite Z.div_mul by lia.\n        destruct (Z.eqb_spec (2 * item_worth) 0); cbn in *; try lia.\n        repeat split; lia.\n      + (* Some withdraw. Can be sent while next_step is either\n           commit_money or withdrawals. *)\n        destruct_match eqn:prev_next_step in receive_some;\n          cbn -[Nat.ltb] in *; try congruence.\n        * (* next_step was commit_money, so seller is withdrawing money\n          because buyer did not commit anything. *)\n          destruct (ctx_amount ctx =? 0) eqn:zero_amount in receive_some;\n            cbn -[Nat.ltb] in *; try congruence.\n          apply Z.eqb_eq in zero_amount.\n          rewrite zero_amount in *.\n          destruct_match in receive_some; cbn in *; try congruence.\n          destruct (address_eqb_spec (ctx_from ctx) (seller prev_state))\n            as [->|]; cbn in *; try congruence.\n          inversion_clear receive_some; cbn.\n          do 4 (split; try tauto).\n          (* In this case we go to none state without buyer having confirmed anything *)\n          right.\n          destruct IH as [_ [_ [<- [_ [? [_ [? [-> [-> ->]]]]]]]]].\n          unfold txs_to, transfer_acts_to.\n          cbn.\n          rewrite address_eq_refl, address_eq_ne by auto.\n          cbn.\n          split; auto; lia.\n        * (* next_step was withdrawals, so either seller or buyer is withdrawing money.\n             This might put us into next_step = none. *)\n          destruct (ctx_amount ctx =? 0) eqn:zero_amount in receive_some;\n            cbn -[Nat.ltb] in *; try congruence.\n          apply Z.eqb_eq in zero_amount.\n          rewrite zero_amount in *.\n          destruct (address_eqb_spec (ctx_from ctx) (buyer prev_state))\n            as [->|]; [|destruct (address_eqb_spec (ctx_from ctx) (seller prev_state))\n                         as [->|]; cbn in *; try congruence].\n          -- (* Buyer withdrawing *)\n            cbn in *.\n            destruct_match in receive_some; cbn in *; try congruence.\n            inversion_clear receive_some; cbn.\n            apply and_assoc; split; [destruct_match; tauto|].\n            do 2 (split; try tauto).\n            destruct (Z.eqb_spec (seller_withdrawable prev_state) 0) as [seller_done|].\n            ++ (* No one has more to withdrew, next_step is none now, so establish\n                  final IH. Since we got here from withdrawal we will be in left case. *)\n              rewrite seller_done in *.\n              left.\n              repeat rewrite transfer_acts_to_cons.\n              fold (buyer_confirmed prev_inc_calls\n                                    (setup_buyer (deployment_setup dep_info))).\n              destruct IH as [_ [_ [<- [-> [? [_ [-> [-> [? ?]]]]]]]]].\n              rewrite address_eq_refl.\n              rewrite address_eq_ne by assumption.\n              cbn.\n              do 2 (split; [tauto|]).\n              lia.\n            ++ (* Seller still has more to withdraw, next_step is still withdrawals *)\n              replace (match seller_withdrawable prev_state with _ => _ end)\n                with (prev_state <| buyer_withdrawable := 0 |>)\n                by (destruct_match; cbn in *; try congruence).\n              cbn.\n              rewrite prev_next_step.\n              repeat rewrite transfer_acts_to_cons.\n              fold (buyer_confirmed prev_inc_calls\n                                    (setup_buyer (deployment_setup dep_info))).\n              destruct IH as [_ [_ [<- [-> [? [_ [-> [-> [? ?]]]]]]]]].\n              rewrite address_eq_refl.\n              rewrite address_eq_ne by assumption.\n              cbn.\n              do 2 (split; try tauto).\n              lia.\n          -- (* Seller withdrawing. Todo: generalize and clean up. *)\n            cbn in *.\n            destruct_match in receive_some; cbn in *; try congruence.\n            inversion_clear receive_some; cbn.\n            apply and_assoc; split; [destruct_match; tauto|].\n            do 2 (split; try tauto).\n            destruct (Z.eqb_spec (buyer_withdrawable prev_state) 0) as [buyer_done|].\n            ++ (* No one has more to withdrew, next_step is none now, so establish\n                  final IH. Since we got here from withdrawal we will be in left case. *)\n              rewrite buyer_done in *.\n              left.\n              repeat rewrite transfer_acts_to_cons.\n              fold (buyer_confirmed prev_inc_calls\n                                    (setup_buyer (deployment_setup dep_info))).\n              destruct IH as [_ [_ [<- [<- [? [_ [-> [-> [? ?]]]]]]]]].\n              rewrite address_eq_refl.\n              rewrite address_eq_ne by auto.\n              cbn.\n              do 2 (split; [tauto|]).\n              lia.\n            ++ (* Buyer still has more to withdraw, next_step is still withdrawals *)\n              replace (match buyer_withdrawable prev_state with _ => _ end)\n                with (prev_state <| seller_withdrawable := 0 |>)\n                by (destruct_match; cbn in *; try congruence).\n              cbn.\n              rewrite prev_next_step.\n              repeat rewrite transfer_acts_to_cons.\n              fold (buyer_confirmed prev_inc_calls\n                                    (setup_buyer (deployment_setup dep_info))).\n              destruct IH as [_ [_ [<- [<- [? [_ [-> [-> [? ?]]]]]]]]].\n              rewrite address_eq_refl.\n              rewrite address_eq_ne by auto.\n              cbn.\n              do 2 (split; [tauto|]).\n              lia.\n      + (* None *)\n        congruence.\n    - (* Self call *)\n      instantiate (CallFacts := fun _ ctx _ => ctx_from ctx <> ctx_contract_address ctx);\n        subst CallFacts; cbn in *; congruence.\n    - (* Permuting queue *)\n      do 5 (split; try tauto).\n      split.\n      + now rewrite <- perm.\n      + assert (out_queue = [] -> out_queue' = [])\n          by (intros ->; now apply Permutation_nil).\n        unfold transfer_acts_to in *.\n        repeat rewrite sumZ_filter in *.\n        destruct (next_step cstate); try tauto.\n        * now rewrite <- perm.\n        * destruct IH as [_ [_ [_ [_ [_ [_ [IH | IH]]]]]]];\n            [left|right]; rewrite <- perm; auto.\n    - instantiate (AddBlockFacts := fun _ _ _ _ _ _ => True).\n      unset_all; subst; cbn in *.\n      destruct_chain_step; auto.\n      destruct_action_eval; auto.\n      intros.\n      pose proof (no_self_calls bstate_from to_addr ltac:(assumption) ltac:(assumption))\n           as all.\n      unfold outgoing_acts in *.\n      rewrite queue_prev in *.\n      subst act; cbn in all.\n      destruct_address_eq; cbn in *; auto.\n      inversion_clear all as [|? ? hd _].\n      destruct msg.\n      + contradiction.\n      + rewrite address_eq_refl in hd.\n        congruence.\n  Qed.\n\n  Definition net_balance_effect\n             {bstate_from bstate_to : ChainState}\n             (trace : ChainTrace bstate_from bstate_to)\n             (caddr addr : Address) : Amount :=\n    sumZ tx_amount (txs_to addr (outgoing_txs trace caddr))\n    - sumZ tx_amount (txs_from addr (incoming_txs trace caddr)).\n\n  (* Our main assumption is that the escrow will always finish due to\n  economically rational actors. We do not formalize this. *)\n  Definition is_escrow_finished cstate :=\n    match next_step cstate with\n    | none => true\n    | _ => false\n    end.\n\n  (* The functional correctness of the Escrow, under the assumption that the\n  escrow finishes due to rational actors. *)\n  Corollary escrow_correct\n            {ChainBuilder : ChainBuilderType}\n            prev new header acts :\n    builder_add_block prev header acts = Some new ->\n    let trace := builder_trace new in\n    forall caddr,\n      env_contracts new caddr = Some (Escrow.contract : WeakContract) ->\n      exists (depinfo : DeploymentInfo Setup)\n             (cstate : State)\n             (inc_calls : list (ContractCallInfo Msg)),\n        deployment_info Setup trace caddr = Some depinfo /\\\n        contract_state new caddr = Some cstate /\\\n        incoming_calls Msg trace caddr = Some inc_calls /\\\n        let item_worth := deployment_amount depinfo / 2 in\n        let seller := deployment_from depinfo in\n        let buyer := setup_buyer (deployment_setup depinfo) in\n        is_escrow_finished cstate = true ->\n        (buyer_confirmed inc_calls buyer = true /\\\n         net_balance_effect trace caddr seller = item_worth /\\\n         net_balance_effect trace caddr buyer = -item_worth \\/\n\n         buyer_confirmed inc_calls buyer = false /\\\n         net_balance_effect trace caddr seller = 0 /\\\n         net_balance_effect trace caddr buyer = 0).\n  Proof.\n    intros after_add trace caddr escrow_at_caddr.\n    cbn in *.\n    pose proof (escrow_correct_strong _ caddr trace escrow_at_caddr) as general.\n    cbn in general.\n    destruct general as\n        [cstate [depinfo [inc_calls [? [? [? [? [? [? [? [? [_ IH]]]]]]]]]]]].\n    exists depinfo, cstate, inc_calls.\n    do 3 (split; [tauto|]).\n    intros is_finished.\n    unfold is_escrow_finished in *.\n    destruct (next_step cstate); try congruence; clear is_finished.\n    unfold net_balance_effect, money_to.\n    assert (inc_txs:\n              forall addr,\n                sumZ tx_amount (txs_from addr (incoming_txs trace caddr)) =\n                sumZ (fun '(a, b, c) => c)\n                     (filter (fun '(from, _, _) => (from =? addr)%address)\n                             (map (fun tx => (tx_from tx, tx_to tx, tx_amount tx))\n                                  (incoming_txs trace caddr)))).\n    {\n      intros addr.\n      induction (incoming_txs trace caddr) as [|hd tl IH'].\n      - reflexivity.\n      - rewrite txs_from_cons.\n        cbn.\n        destruct_address_eq; cbn in *; rewrite IH'; reflexivity.\n    }\n\n    repeat rewrite inc_txs; clear inc_txs.\n    rewrite (incoming_txs_contract caddr _ trace _ depinfo _ inc_calls) by assumption.\n    repeat rewrite filter_app, sumZ_app.\n    cbn.\n    rewrite address_eq_refl.\n    rewrite address_eq_ne by auto.\n    cbn.\n    rewrite 2!filter_map, 2!sumZ_map.\n\n    set (buyer_addr := setup_buyer (deployment_setup depinfo)) in *.\n    set (seller_addr := deployment_from depinfo) in *.\n\n    unfold money_to, transfer_acts_to in IH.\n    cbn in IH.\n\n    change (fun a => call_amount a) with (@call_amount _ Msg).\n\n    destruct IH as [IH | IH]; [left|right].\n    - split; [tauto|].\n      remember (build_call_info _ _ (Some commit_money)) as commitment.\n      assert (Hsum :\n                forall f,\n                  sumZ call_amount (filter f inc_calls) =\n                  sumZ call_amount (filter f [commitment])).\n      {\n        intros f.\n        destruct IH as [_ [<- ?]].\n        clear -inc_calls.\n        induction inc_calls as [|hd tl IH']; auto.\n        cbn.\n        destruct (Z.eqb_spec (call_amount hd) 0) as [zero_amount|].\n        - cbn.\n          destruct (f hd); cbn; try rewrite zero_amount; rewrite IH'; auto.\n        - cbn.\n          destruct (f hd); cbn; rewrite IH'; auto.\n      }\n\n      rewrite 2!Hsum; clear Hsum; subst commitment; cbn in *.\n      rewrite address_eq_refl, address_eq_ne by auto.\n      cbn.\n      destruct IH as [_ [_ [? ?]]].\n      split; lia.\n    - destruct IH as [-> IH].\n      cbn.\n      rewrite address_eq_refl, address_eq_ne by auto.\n      cbn.\n      split; [auto|].\n      split; lia.\n  Qed.\n\nEnd Theories.\n\nEnd Escrow.\n", "meta": {"author": "malthelange", "repo": "CLVM", "sha": "e80aef02c3112b5b62db79bc2b233020367b0bde", "save_path": "github-repos/coq/malthelange-CLVM", "path": "github-repos/coq/malthelange-CLVM/CLVM-e80aef02c3112b5b62db79bc2b233020367b0bde/execution/theories/Examples/Escrow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.24903629214015943}}
{"text": "(* ************************************************************************** *)\n(*                                                                            *)\n(* Verified Flash Translation Layer                                           *)\n(*                                                                            *)\n(* ************************************************************************** *)\n\nRequire Import List.\nRequire Import ListEx.\nRequire Import LibEx.\nRequire Import Monad.\nRequire Import Data.\n\nRequire Import Params.\nRequire Import Nand.\nRequire Import NandLems.\n\nRequire Import Bast0.\nRequire Import FTLProp.\nRequire Import FTLLems.\n\nRequire Import Inv.\n\n(* == I_inv == lemmas =========================== *)\n\nLemma I_pbn_bit_valid_preserv_bit_update :\n  forall pbn bit bi bit',\n    valid_block_no pbn\n    -> I_pbn_bit_valid bit \n    -> bit_update bit pbn bi = Some bit'\n    -> I_pbn_bit_valid bit'.\nProof.\n  intros pbn bit bi bit' Hv HI1 Hup.\n  unfold I_pbn_bit_valid in * .\n  intros pbn'.\n  destruct (block_no_eq_dec pbn pbn').\n    subst pbn'.\n    destruct (HI1 pbn) as [H1 H2].\n    split.\n      intro Hx.\n      exists bi.\n      rewrite (bit_update_bit_get_eq _ _ _ _ Hup).\n      trivial.\n    intros [bi' Hget'].\n    trivial.\n  destruct (HI1 pbn') as [H1 H2].\n  split.\n    intro Hx.\n    destruct (H1 Hx) as [bi' Hg'].\n    exists bi'.\n    rewrite (bit_update_bit_get_neq _ _ _ _ _ Hup (neq_sym H)).\n    trivial.\n  intros [bi' Hg'].\n  apply H2.\n  exists bi'.\n  rewrite <- (bit_update_bit_get_neq _ _ _ _ _ Hup (neq_sym H)).\n  trivial.\nQed.\n\nLemma I_pbn_fbq_valid_preserv_fbq_deq :\n  forall fbq pbn fbq',\n    I_pbn_fbq_valid fbq\n    -> fbq_deq fbq = Some (pbn, fbq')\n    -> I_pbn_fbq_valid fbq'.\nProof.\n  induction fbq.\n    intros.\n    discriminate.\n  intros pbn' fbq' Hv.\n  simpl.\n  intros H.\n  injection H.\n  intros.\n  subst fbq' a.\n  unfold I_pbn_fbq_valid in Hv.\n  unfold I_pbn_fbq_valid.\n  intros pbn Hin.\n  apply Hv.\n  unfold fbq_in.\n  simpl.\n  destruct (beq_nat pbn pbn').\n  trivial.\n  trivial.\nQed.\n\nLemma I_pbn_fbq_state_preserv_fbq_deq : \n  forall bit fbq pbn fbq',\n    I_pbn_fbq_state bit fbq\n    -> fbq_deq fbq = Some (pbn, fbq')\n    -> I_pbn_fbq_state bit fbq'.\nProof.\n  induction fbq.\n    intros.\n    discriminate.\n  intros pbn' fbq' HI4.\n  simpl.\n  intros H.\n  injection H.\n  intros.\n  subst fbq' a.\n  unfold I_pbn_fbq_state in HI4.\n  unfold I_pbn_fbq_state.\n  intros pbn bi Hin Hg.\n  apply HI4 with pbn. \n  unfold fbq_in.\n  simpl.\n  destruct (beq_nat pbn pbn').\n  trivial.\n  trivial.\n  trivial.\nQed.\n\nLemma I_pbn_fbq_state_preserv_bit_update : \n  forall bit fbq pbn bi bit',\n    I_pbn_fbq_state bit fbq\n    -> bit_update bit pbn bi = Some bit'\n    -> fbq_in fbq pbn = false\n    -> I_pbn_fbq_state bit' fbq.\nProof.\n  intros. unfold I_pbn_fbq_state. unfold I_pbn_fbq_state in H.\n  intros pbn' bi' Hin' Hg'.\n  apply (H pbn' bi'); trivial.\n  destruct (block_no_eq_dec pbn pbn').\n    subst pbn'.\n    rewrite H1 in Hin'.\n    discriminate.\n  rewrite <- (bit_update_bit_get_neq _ _ _ _ _ H0); auto.\nQed.\n\nLemma allocated_pbn_not_in_fbq : \n  forall fbq pbn fbq',\n    I_pbn_fbq_distinguishable fbq\n    -> fbq_deq fbq = Some (pbn, fbq')\n    -> fbq_in fbq' pbn = false.\nProof.\n  intros fbq pbn fbq' HI8 Hdeq.\n  assert (Hin : fbq_in fbq pbn = true).\n    unfold fbq_deq, fbq_in in * .\n    destruct fbq.\n      discriminate.\n    injection Hdeq.\n    intros; subst fbq' b.\n    simpl.\n    simplbnat.\n    trivial.\n  destruct (fbq_in fbq' pbn) eqn:Hin'.\n  destruct (fbq_in_fbq_get _ _ Hin') as [i Hg].\n  assert (Hx:=fbq_get_fbq_rdeq_fbq_get _ _ _ _ _ Hg Hdeq).\n  assert (Hy : fbq_get fbq 0 = Some pbn).\n    eapply fbq_deq_fbq_get; eauto.\n  assert (Hm : 0 <> S i).\n    auto with arith.\n  assert (HF:= HI8 0 (S i) pbn pbn Hm Hy Hx).\n  destruct (HF (refl_equal)).\n  trivial.\nQed.\n\nLemma I_pbn_habitation_in_fbq_implies_not_in_bmt :\n  forall pbn bmt fbq,\n    valid_block_no pbn\n    -> I_pbn_habitation bmt fbq\n    -> fbq_in fbq pbn = true\n    -> ~ pbn_in_bmt bmt pbn.\nProof.\n  intros.\n  destruct (H0 pbn H).\n    destruct H2 as [[lbn H3] H4].\n    rewrite H1 in H4.\n    discriminate.\n  unfold pbn_in_bmt.\n  intro Hx.\n  destruct Hx as [lbn Hx].\n  destruct H2 as [H3 H4].\n  apply (H3 lbn Hx); trivial.\nQed.\n\nLemma I_pbn_habitation_in_bmt_implies_not_in_fbq :\n  forall pbn bmt fbq,\n    valid_block_no pbn\n    -> I_pbn_habitation bmt fbq\n    -> pbn_in_bmt bmt pbn\n    -> fbq_in fbq pbn = false.\nProof.\n  intros.\n  destruct (H0 pbn H).\n    destruct H2 as [[lbn H3] H4].\n    trivial.\n  unfold pbn_in_bmt in H1.\n  destruct H1 as [lbn H1].\n  destruct H2 as [H3 H4].\n  destruct (H3 _ H1).\nQed.\n\nLemma I_pbn_bmt_valid_preserv_bmt_update_data_none : \n  forall bmt lbn pbn bmt',\n    valid_block_no pbn\n    -> I_pbn_bmt_valid bmt\n    -> bmt_update bmt lbn (Some pbn, None) = Some bmt' \n    -> I_pbn_bmt_valid bmt'.\nProof.\n  unfold I_pbn_bmt_valid.\n  intros bmt lbn pbn bmt' Hv HI2 Hup.\n  intros lbn' pbn' Hin.\n  destruct (block_no_eq_dec lbn lbn') as [Hlbn | Hlbn].\n    subst lbn'.\n    assert (Hx:= bmt_update_bmt_get_eq _ _ _ _  Hup).\n    destruct Hin as [Hin | Hin].\n      destruct Hin as [x Hin].\n      rewrite Hin in Hx.\n      injection Hx.\n      intros; subst x pbn'.\n      trivial.\n    destruct Hin as [x Hin].\n    rewrite Hin in Hx.\n    discriminate.\n  assert (Hx := bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hup Hlbn Hin).\n  apply HI2 with lbn'; trivial.\nQed.\n\n(* Lemma I_pbn_bmt_valid_preserv_bmt_update :  *)\n(*   forall bmt lbn pbn bmt', *)\n(*     valid_block_no pbn *)\n(*     -> I_pbn_bmt_valid bmt *)\n(*     -> (bmt_update bmt lbn (Some pbn, None) = Some bmt'  *)\n(*         \\/  bmt_update bmt lbn (None, Some pbn) = Some bmt') *)\n(*     -> I_pbn_bmt_valid bmt'. *)\n(* Proof. *)\n(*   intros bmt lbn pbn bmt' Hv HI2 H *)\n(* Qed. *)\n\nLemma I_pbn_bmt_valid_preserv_bmt_update_log : \n  forall bmt lbn pbn bmt',\n    valid_block_no pbn\n    -> I_pbn_bmt_valid bmt\n    -> bmt_update_log bmt lbn pbn = Some bmt' \n    -> I_pbn_bmt_valid bmt'.\nProof.\n  unfold bmt_update_log.\n  intros bmt lbn pbn bmt' Hv HI2 Hul.\n  destruct (bmt_get bmt lbn) as [[bmrdata bmrlog] | ] eqn:Hget; try discriminate.\n  destruct (bmt_update bmt lbn (bmrdata, Some pbn)) as [bmt'' | ] eqn:Hu; try discriminate.\n  injection Hul; intro; subst bmt''.\n  unfold I_pbn_bmt_valid in * .\n  intros lbn' pbn' Hin.\n  destruct (block_no_eq_dec lbn lbn') as [Heq | Hneq].\n    subst lbn'; trivial.\n    unfold pbn_in_bmt_lbn in Hin.\n    destruct Hin as [Hin | Hin].\n      destruct Hin as [x Hin].\n      rewrite (bmt_update_bmt_get_eq _ _ _ _ Hu) in Hin.\n      injection Hin; intros; subst bmrdata x.\n      assert (pbn_in_bmt_lbn bmt lbn pbn').\n        left.\n        exists bmrlog.\n        trivial.\n      eapply HI2; eauto.\n    destruct Hin as [x Hin].\n    rewrite (bmt_update_bmt_get_eq _ _ _ _ Hu) in Hin.\n    injection Hin; intros; subst x pbn'.\n    trivial.\n  apply HI2 with lbn'.\n  unfold pbn_in_bmt_lbn in Hin |- * .\n  destruct Hin as [Hin | Hin].\n    left.\n    unfold pbn_in_bmt_data in Hin.\n    destruct Hin as [x Hin].\n    exists x.\n    rewrite <- (bmt_update_bmt_get_neq _ _ _ _ _ Hu Hneq).\n    trivial.\n  right.\n  unfold pbn_in_bmt_log in Hin.\n  destruct Hin as [x Hin].\n  exists x.\n  rewrite <- (bmt_update_bmt_get_neq _ _ _ _ _ Hu Hneq).\n  trivial.\nQed.\n\nLemma I_pbn_bmt_valid_preserv_bmt_update_data : \n  forall bmt lbn pbn bmt',\n    valid_block_no pbn\n    -> I_pbn_bmt_valid bmt\n    -> bmt_update_data bmt lbn pbn = Some bmt' \n    -> I_pbn_bmt_valid bmt'.\nProof.\n  unfold bmt_update_data.\n  intros bmt lbn pbn bmt' Hv HI2 Hud.\n  destruct (bmt_get bmt lbn) as [[bmrdata bmrlog] | ] eqn:Hget; try discriminate.\n  destruct (bmt_update bmt lbn (Some pbn, bmrlog)) as [bmt'' | ] eqn:Hu; try discriminate.\n  injection Hud; intro; subst bmt''.\n  unfold I_pbn_bmt_valid in * .\n  intros lbn' pbn' Hin.\n  destruct (block_no_eq_dec lbn lbn') as [Heq | Hneq].\n    subst lbn'; trivial.\n    unfold pbn_in_bmt_lbn in Hin.\n    destruct Hin as [Hin | Hin].\n      destruct Hin as [x Hin].\n      rewrite (bmt_update_bmt_get_eq _ _ _ _ Hu) in Hin.\n      injection Hin; intros; subst pbn' x.\n      trivial.\n    destruct Hin as [x Hin].\n    rewrite (bmt_update_bmt_get_eq _ _ _ _ Hu) in Hin.\n    injection Hin; intros; subst bmrlog x.\n    assert (pbn_in_bmt_lbn bmt lbn pbn').\n      right.\n      exists bmrdata.\n      trivial.\n    eapply HI2; eauto.\n  apply HI2 with lbn'.\n  unfold pbn_in_bmt_lbn in Hin |- * .\n  destruct Hin as [Hin | Hin].\n    left.\n    unfold pbn_in_bmt_data in Hin.\n    destruct Hin as [x Hin].\n    exists x.\n    rewrite <- (bmt_update_bmt_get_neq _ _ _ _ _ Hu Hneq).\n    trivial.\n  right.\n  unfold pbn_in_bmt_log in Hin.\n  destruct Hin as [x Hin].\n  exists x.\n  rewrite <- (bmt_update_bmt_get_neq _ _ _ _ _ Hu Hneq).\n  trivial.\nQed.\n\nLemma I_pbn_freebq_valid_preserv_fbq_enq : \n  forall fbq pbn fbq',\n    valid_block_no pbn\n    -> I_pbn_fbq_valid fbq\n    -> fbq_enq fbq pbn = Some fbq'\n    -> I_pbn_fbq_valid fbq'.\nProof.\n  unfold I_pbn_fbq_valid.\n  intros fbq pbn fbq' Hv HI3 Hen.\n  intros pbn' Hin'.\n  destruct (block_no_eq_dec pbn pbn') as [Heq | Hneq].\n    subst pbn'.\n    trivial.\n  apply HI3.\n  rewrite <- (fbq_in_preserv_fbq_enq pbn' fbq pbn fbq'); eauto.\nQed.\n\nLemma I_pbn_freebq_state_preserv_fbq_enq : \n  forall bit fbq pbn bi bit' fbq',\n    valid_block_no pbn\n    -> bit_update bit pbn bi = Some bit'\n    -> bi_state bi = bs_invalid\n    -> I_pbn_fbq_state bit fbq\n    -> fbq_enq fbq pbn = Some fbq'\n    -> I_pbn_fbq_state bit' fbq'.\nProof.\n  intros bit fbq pbn bi bit' fbq' Hv Hu Hbi HI4 Hen.\n  unfold I_pbn_fbq_state in * .\n  intros pbn' bi' Hin' Hget'.\n  destruct (block_no_eq_dec pbn pbn') as [Heq | Hneq].\n    subst pbn'.\n    rewrite (bit_update_bit_get_eq _ _ _ _ Hu) in Hget'.\n    injection Hget'; intro; subst bi'.\n    left; trivial.\n  assert (fbq_in fbq pbn' = true).\n    rewrite <- (fbq_in_preserv_fbq_enq _ _ _ _ (neq_sym Hneq) Hen) .\n    trivial.\n  assert (bit_get bit pbn' = Some bi').\n    rewrite <- (bit_update_bit_get_neq _ _ _ _ _ Hu (neq_sym Hneq)).\n    trivial.\n  eapply HI4; eauto.\nQed.\n\nLemma pbn_not_in_bmt_bmt_update :\n  forall bmt lbn pbn (bmr: bmt_record) bmt',\n    pbn_in_bmt_lbn bmt lbn pbn\n    -> I_pbn_bmt_distinguishable bmt\n    -> I_pbn_bmt_distinguishable_2 bmt\n    -> bmt_update bmt lbn bmr = Some bmt'\n    -> pbn_not_in_bmr pbn bmr\n    -> pbn_not_in_bmt bmt' pbn.\nProof.\n  intros bmt lbn pbn bmr bmt'.\n  intros Hin HI71 HI72 Hup Hnot.\n  unfold pbn_not_in_bmt.\n  intro HF.\n  unfold pbn_in_bmt in HF.\n  destruct HF as [lbn' Hlbn'in].\n  assert (Hx: lbn' = lbn \\/ lbn' <> lbn).\n    destruct (block_no_eq_dec lbn lbn').\n      left; auto.\n    right; auto.\n  destruct Hx as [Heq | Hneq].\n    subst lbn'.\n    unfold I_pbn_bmt_distinguishable in HI71.\n    unfold I_pbn_bmt_distinguishable_2 in HI72.\n    unfold pbn_in_bmt_lbn in Hlbn'in.\n    assert (H1 := bmt_update_bmt_get_eq _ _ _ _ Hup).\n    destruct Hlbn'in as [H2 | H3].\n      unfold pbn_in_bmt_data in H2.\n      destruct H2 as [x Hx].\n      unfold pbn_not_in_bmr in Hnot.\n      destruct bmr as [bmr1 bmr2].\n      destruct bmr1 as [b1 | ].\n      rewrite H1 in Hx.    \n      injection Hx.\n      intros.\n      subst pbn.\n      destruct bmr2.\n      destruct Hnot.\n      apply H0; trivial.\n      apply Hnot; trivial.\n      rewrite H1 in Hx.    \n      discriminate.\n    unfold pbn_in_bmt_log in H3.\n    destruct H3 as [x Hx].\n    unfold pbn_not_in_bmr in Hnot.\n    destruct bmr as [bmr1 bmr2].\n    destruct bmr1 as [b1 | ].\n    destruct bmr2 as [b2 | ].\n    rewrite H1 in Hx.    \n    injection Hx.\n    intros.\n    subst pbn.\n    destruct Hnot.\n    apply H2; trivial.\n    rewrite H1 in Hx.    \n    discriminate.\n    destruct bmr2 as [b2 | ].\n    rewrite H1 in Hx.    \n    injection Hx.\n    intros.\n    subst pbn.\n    apply Hnot; trivial.\n    rewrite H1 in Hx.\n    discriminate.\n  unfold I_pbn_bmt_distinguishable in HI71.\n  unfold pbn_in_bmt_lbn in Hlbn'in.\n  destruct Hlbn'in.\n  unfold pbn_in_bmt_data in H.\n  destruct H as [x Hx].\n  rewrite (bmt_update_bmt_get_neq _ _ _ _ _ Hup (neq_sym Hneq)) in Hx.\n  assert (H1 : pbn_in_bmt_lbn bmt lbn' pbn).\n    unfold pbn_in_bmt_lbn.\n    left.\n    unfold pbn_in_bmt_data.\n    exists x; trivial.\n  assert (Hy:= HI71 lbn lbn' pbn pbn (neq_sym Hneq) Hin H1).\n  apply Hy; trivial.\n  unfold pbn_in_bmt_log in H.\n  destruct H as [x Hx].\n  rewrite (bmt_update_bmt_get_neq _ _ _ _ _ Hup (neq_sym Hneq)) in Hx.\n  assert (H1 : pbn_in_bmt_lbn bmt lbn' pbn).\n    unfold pbn_in_bmt_lbn.\n    right.\n    unfold pbn_in_bmt_log.\n    exists x; trivial.\n  assert (Hy:= HI71 lbn lbn' pbn pbn (neq_sym Hneq) Hin H1).\n  apply Hy; trivial.\nQed.\n\nLemma pbn_in_bmt_implies_pbn_in_bmt_again :\n  forall bmt lbn pbn lbn',\n    I_pbn_bmt_distinguishable bmt\n    -> pbn_in_bmt_lbn bmt lbn pbn\n    -> lbn' <> lbn\n    -> ~ pbn_in_bmt_lbn bmt lbn' pbn.\nProof.\n  intros bmt lbn pbn lbn'.\n  intros HI71 Hin Hneq.\n  unfold I_pbn_bmt_distinguishable in HI71.\n  intro Hin2.\n  apply (HI71 lbn' lbn pbn pbn Hneq Hin2 Hin); trivial.\nQed.\n\n(* \n Lemmas for I7\n\n *)\n\nLemma I_pbn_bmt_distinguishable_preserv_bmt_update_data_none: \n  forall bmt lbn pbn bmt', \n  I_pbn_bmt_distinguishable bmt\n  -> bmt_update bmt lbn (Some pbn, None) = Some bmt'\n  -> ~ pbn_in_bmt bmt pbn\n  -> I_pbn_bmt_distinguishable bmt'.\nProof.\n  intros bmt lbn pbn bmt'.\n  intros HI71 Hup Hnin.\n  unfold I_pbn_bmt_distinguishable in * .\n  intros lbn1 lbn2 pbn1 pbn2 Hneq12 Hin11 Hin22.\n  destruct (pbn_eq_dec lbn lbn1) as [Heq1 | Hneq1].\n  destruct (pbn_eq_dec lbn lbn2) as [Heq2 | Hneq2].\n\n  subst lbn1.\n  destruct (Hneq12 Heq2).\n  subst lbn1.\n  assert (pbn1 = pbn).\n    assert (bmt_get bmt' lbn = Some (Some pbn, None)).\n      rewrite (bmt_update_bmt_get_eq _ _ _ _ Hup); trivial.\n    unfold pbn_in_bmt_lbn in Hin11.\n    unfold pbn_in_bmt_data, pbn_in_bmt_log in Hin11.\n    destruct Hin11 as [Hin11 | Hin11].\n    destruct Hin11 as [x Hin11].\n    rewrite Hin11 in H .\n    injection H; intros; subst; trivial.\n    destruct Hin11 as [x Hin11].\n    rewrite Hin11 in H .\n    discriminate.\n  subst pbn1.\n  apply (bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hup Hneq2) in Hin22.\n  intro HF.\n  subst pbn2.\n  unfold pbn_in_bmt in Hnin.\n  apply Hnin.\n  exists lbn2; trivial.\n\n  destruct (pbn_eq_dec lbn lbn2) as [Heq2 | Hneq2].\n  subst lbn2.\n  assert (pbn2 = pbn).\n    assert (bmt_get bmt' lbn = Some (Some pbn, None)).\n      rewrite (bmt_update_bmt_get_eq _ _ _ _ Hup); trivial.\n    unfold pbn_in_bmt_lbn in Hin22.\n    unfold pbn_in_bmt_data, pbn_in_bmt_log in Hin22.\n    destruct Hin22 as [Hin22 | Hin22].\n    destruct Hin22 as [x Hin22].\n    rewrite Hin22 in H .\n    injection H; intros; subst; trivial.\n    destruct Hin22 as [x Hin22].\n    rewrite Hin22 in H .\n    discriminate.\n  subst pbn2.\n  apply (bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hup Hneq1) in Hin11.\n  intro HF.\n  subst pbn1.\n  unfold pbn_in_bmt in Hnin.\n  apply Hnin.\n  exists lbn1; trivial.\n  \n  apply (bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hup Hneq2) in Hin22.\n  apply (bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hup Hneq1) in Hin11.\n  apply (HI71 lbn1 lbn2); eauto.\nQed.\n\nLemma I_pbn_bmt_distinguishable_preserv_bmt_update_log: \n  forall bmt lbn pbn bmt', \n  I_pbn_bmt_distinguishable bmt\n  -> bmt_update_log bmt lbn pbn = Some bmt'\n  -> ~ pbn_in_bmt bmt pbn\n  -> I_pbn_bmt_distinguishable bmt'.\nProof.\n  intros bmt lbn pbn bmt'.\n  unfold bmt_update_log, I_pbn_bmt_distinguishable, pbn_in_bmt.\n  intros HI71 Hul Hnin.\n  intros lbn1 lbn2 pbn1 pbn2 Hlbn12 Hpbn1 Hpbn2.\n  destruct (bmt_get bmt lbn) as [bmr | ] eqn:Hbmt; try discriminate.\n  destruct bmr as [bmrd bmrl].\n  destruct (bmt_update bmt lbn (bmrd, Some pbn)) as [bmt'' | ] eqn:Hu; try discriminate.\n  injection Hul; intros; subst bmt''.\n  destruct (block_no_eq_dec lbn lbn1) as [Heq | Hneq ].\n    subst lbn1.\n    destruct Hpbn1 as [Hin1 | Hin1].\n      destruct Hin1 as [x Hin1].\n      assert (Hx := bmt_update_bmt_get_eq _ _ _ _ Hu).\n      rewrite Hin1 in Hx.\n      injection Hx.\n      intros.\n      subst x bmrd.\n      assert (Hy := bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hu Hlbn12 Hpbn2).\n      eapply HI71; eauto.\n      left.\n      exists bmrl.\n      trivial.\n    destruct Hin1 as [x Hin1].\n    rewrite (bmt_update_bmt_get_eq _ _ _ _ Hu) in Hin1.\n    injection Hin1; intros; subst x pbn.\n    clear Hin1.\n    intro Hx.\n    subst pbn2.\n    assert (Hy := bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hu Hlbn12 Hpbn2).\n    apply Hnin.    \n    exists lbn2; trivial.\n  destruct (block_no_eq_dec lbn lbn2) as [Heq | Hneq2 ].\n    subst lbn2.\n    destruct Hpbn2 as [Hin2 | Hin2].\n      destruct Hin2 as [x Hin2].\n      assert (Hx := bmt_update_bmt_get_eq _ _ _ _ Hu).\n      rewrite Hin2 in Hx.\n      injection Hx.\n      intros.\n      subst x bmrd.\n      assert (Hy := bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hu (neq_sym Hlbn12) Hpbn1).\n      eapply HI71; eauto.\n      left.\n      exists bmrl.\n      trivial.\n    destruct Hin2 as [x Hin2].\n    rewrite (bmt_update_bmt_get_eq _ _ _ _ Hu) in Hin2.\n    injection Hin2; intros; subst x pbn.\n    clear Hin2.\n    intro Hx.\n    subst pbn1.\n    assert (Hy := bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hu (neq_sym Hlbn12) Hpbn1).\n    apply Hnin.    \n    exists lbn1; trivial.\n  assert (Hx := bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hu Hneq Hpbn1).\n  assert (Hy := bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hu Hneq2 Hpbn2).\n  apply (HI71 _ _ _ _ Hlbn12); eauto.\nQed.\n      \nLemma I_pbn_bmt_distinguishable_2_preserv_bmt_update_data_none: \n  forall bmt lbn pbn bmt', \n  I_pbn_bmt_distinguishable_2 bmt\n  -> bmt_update bmt lbn (Some pbn, None) = Some bmt'\n  -> I_pbn_bmt_distinguishable_2 bmt'.\nProof.\n  intros bmt lbn pbn bmt' HI72 Hu.\n  unfold I_pbn_bmt_distinguishable_2 in * .\n  intros lbn' pbn1 pbn2 Hget.\n  destruct (block_no_eq_dec lbn lbn') as [Heq | Hneq ].\n    subst lbn'.\n    rewrite (bmt_update_bmt_get_eq _ _ _ _ Hu) in Hget.\n    discriminate Hget.\n  rewrite (bmt_update_bmt_get_neq _ _ _ _ _ Hu Hneq) in Hget.\n  eapply HI72; eauto.\nQed.\n\nLemma I_pbn_bmt_distinguishable_2_preserv_bmt_update_log: \n  forall bmt lbn pbn bmt', \n  I_pbn_bmt_distinguishable_2 bmt\n  -> bmt_update_log bmt lbn pbn = Some bmt'\n  -> ~ pbn_in_bmt bmt pbn\n  -> I_pbn_bmt_distinguishable_2 bmt'.\nProof.\n  intros bmt lbn pbn bmt' HI72 Hu Hnin.\n  unfold I_pbn_bmt_distinguishable_2 in * .\n  intros lbn' pbn1 pbn2 Hget.\n  unfold bmt_update_log in Hu.\n  destruct (bmt_get bmt lbn) as [[bmrd bmrl] | ] eqn:Hg; [ | try discriminate].\n  destruct (bmt_update bmt lbn (bmrd, Some pbn)) as [bmt'x | ] eqn:Hbu ; [ | try discriminate].\n  injection Hu; intros; subst bmt'x.\n  clear Hu.\n  destruct (block_no_eq_dec lbn lbn') as [Heq | Hneq ].\n    subst lbn'.\n    rewrite (bmt_update_bmt_get_eq _ _ _ _ Hbu) in Hget.\n    injection Hget; intros; subst bmrd pbn.\n    clear Hget.\n    intros He.\n    subst pbn2.\n    apply Hnin.\n    exists lbn.\n    left.\n    exists bmrl.\n    trivial.\n  rewrite (bmt_update_bmt_get_neq _ _ _ _ _ Hbu Hneq) in Hget.\n  eapply HI72; eauto.\nQed.\n\n(* \n Lemmas for I5\n\n *)\n\nLemma I_pbn_bmt_used_preserv_bit_update_irre : \n  forall bit bmt pbn bi bit',\n    I_pbn_bmt_used bit bmt\n    -> bit_update bit pbn bi = Some bit'\n    -> (~ pbn_in_bmt bmt pbn)\n    -> I_pbn_bmt_used bit' bmt.\nProof.\n  intros bit bmt pbn bi bit' HI5 Hup Hnin.\n  unfold I_pbn_bmt_used in * .\n  intros lbn pbn' bi' Hget'. \n  destruct (pbn_eq_dec pbn pbn') as [Heq | Hneq].\n    subst pbn'.\n    rewrite (bit_update_bit_get_eq _ _ _ _ Hup) in Hget'.\n    injection Hget'.\n    intro H; subst bi'; clear Hget'.\n    split.\n      intros H.\n      unfold pbn_in_bmt in Hnin.\n      apply False_ind.\n      apply Hnin.\n      exists lbn.\n      unfold pbn_in_bmt_lbn.\n      left; trivial.\n    intros H.\n    unfold pbn_in_bmt in Hnin.\n    apply False_ind.\n    apply Hnin.\n    exists lbn.\n    unfold pbn_in_bmt_lbn.\n    right; trivial.\n  rewrite (bit_update_bit_get_neq _ _ _ _ _ Hup (neq_sym Hneq)) in Hget'.\n  apply HI5; auto.\nQed.\n\nLemma I_pbn_bmt_used_preserv_bmt_update_data_none :\n  forall bit bmt pbn lbn bi bit' bmt',\n    I_pbn_bmt_used bit bmt \n    -> I_pbn_bmt_distinguishable bmt\n    -> pbn_not_in_bmt bmt pbn\n    -> bmt_update bmt lbn (Some pbn, None) = Some bmt' \n    -> bit_update bit pbn bi = Some bit'\n    -> bi_state bi = bs_data lbn\n    -> I_pbn_bmt_used bit' bmt'.\nProof.\n  intros bit bmt pbn lbn bi bit' bmt'.\n  intros HI5 HI71 Hnin Hbmtup Hup Hbs.\n  assert (HI71' : I_pbn_bmt_distinguishable bmt').\n    eapply I_pbn_bmt_distinguishable_preserv_bmt_update_data_none; eauto.\n  unfold I_pbn_bmt_used in * .\n  intros lbn' pbn' bi' Hget'.\n  destruct (pbn_eq_dec pbn pbn') as [Heq | Hneq].\n    subst pbn'.\n    rewrite (bit_update_bit_get_eq _ _ _ _ Hup) in Hget'.\n    injection Hget'.\n    intro H; subst bi'; clear Hget'.\n    split.\n      intros H.\n      assert (H1: pbn_in_bmt_lbn bmt' lbn' pbn).\n        left; trivial.\n      assert (H2: pbn_in_bmt_lbn bmt' lbn pbn).\n        eapply (bmt_update_pbn_in_bmt_lbn_eq _ _ _ _ _ Hbmtup); eauto.\n        simpl; trivial.\n      assert (lbn' = lbn).\n        destruct (pbn_eq_dec lbn' lbn) as [Hx | Hx]; trivial.\n        apply False_ind.\n        eapply HI71'; eauto.\n      subst lbn'.\n      trivial.\n    intro H.\n    assert (H1: pbn_in_bmt_lbn bmt' lbn' pbn).\n      right; trivial.\n    assert (H2: pbn_in_bmt_lbn bmt' lbn pbn).\n      eapply (bmt_update_pbn_in_bmt_lbn_eq _ _ _ _ _ Hbmtup); eauto.\n      simpl; trivial.\n    assert (lbn' = lbn).\n      destruct (pbn_eq_dec lbn' lbn) as [Hx | Hx]; trivial.\n      apply False_ind.\n      eapply HI71'; eauto.\n    subst lbn'.\n    unfold pbn_in_bmt_log in H.\n    assert (H3: bmt_get bmt' lbn = Some (Some pbn, None)).\n      eapply bmt_update_bmt_get_eq; eauto.\n    destruct H as [x H].\n    rewrite H in H3.\n    discriminate.\n  (* pbn <> pbn' *)\n  assert (bit_get bit pbn' = Some bi').\n    rewrite (bit_update_bit_get_neq _ _ _ _ _ Hup (neq_sym Hneq)) in Hget'.\n    trivial.\n  destruct (HI5 lbn' pbn' bi' H) as [H1 H2].\n  split.\n    intro Hx.\n    apply H1.\n    destruct (pbn_eq_dec lbn lbn') as [Heq1 | Hneq1].\n      subst lbn'.\n      assert (pbn_in_bmt_data bmt' lbn pbn).\n        exists None.\n        apply (bmt_update_bmt_get_eq _ _ _ _ Hbmtup).\n      assert (pbn = pbn').\n        eapply pbn_in_bmt_data_inj; eauto.\n      destruct (Hneq H3).\n\n    unfold pbn_in_bmt_data in Hx |- * .\n    destruct Hx as [x Hx].\n    exists x.\n    rewrite <- (bmt_update_bmt_get_neq _ _ _ _ _ Hbmtup Hneq1).\n    trivial.\n  intro Hx.\n  apply H2.\n  destruct (pbn_eq_dec lbn lbn') as [Heq1 | Hneq1].\n    subst lbn'.\n    unfold pbn_in_bmt_log in Hx.\n    destruct Hx as [x Hx].\n    assert (bmt_get bmt' lbn = Some (Some pbn, None)).\n      eapply bmt_update_bmt_get_eq; eauto.\n    rewrite H0 in Hx.\n    discriminate. \n  unfold pbn_in_bmt_log in Hx |- * .\n  destruct Hx as [x Hx].\n  exists x.\n  rewrite <- (bmt_update_bmt_get_neq _ _ _ _ _ Hbmtup Hneq1).\n  trivial.\nQed.\n\nLemma I_pbn_bmt_used_preserv_bmt_update_log :\n  forall bit bmt pbn lbn bi pmt bit' bmt',\n    I_pbn_bmt_used bit bmt \n    -> ~ pbn_in_bmt bmt pbn\n    -> bmt_update_log bmt lbn pbn = Some bmt'\n    -> bit_update bit pbn bi = Some bit'\n    -> bi_state bi = bs_log lbn pmt\n    -> I_pbn_bmt_used bit' bmt'.\nProof.\n  unfold I_pbn_bmt_used.\n  intros bit bmt pbn lbn bi pmt bit' bmt' HI5 Hnin Hbmtul Hbitu Hbi.\n  intros lbn' pbn' bi' Hget'.\n  split.\n    intros Hin'.\n    destruct (pbn_eq_dec pbn pbn') as [Heq | Hneq].\n      subst pbn'.\n      assert (Hin'x := bmt_update_log_pbn_in_bmt_data_preserv_rev _ _ _ _ _ _ Hbmtul Hin').\n      apply False_ind.\n      apply Hnin.\n      exists lbn'.\n      left; trivial.\n    rewrite (bit_update_bit_get_neq _ _ _ _ _ Hbitu (neq_sym Hneq)) in Hget'.\n    assert (Hin'x := bmt_update_log_pbn_in_bmt_data_preserv_rev _ _ _ _ _ _ Hbmtul Hin').\n    destruct (HI5 lbn' _ _ Hget') as [HI5_1 HI5_2].\n    apply HI5_1; trivial.\n  intro Hin'.\n  destruct (pbn_eq_dec pbn pbn') as [Heq | Hneq].\n    subst pbn'.\n    destruct (pbn_eq_dec lbn lbn') as [Heq2 | Hneq2].\n      subst lbn'.\n      rewrite (bit_update_bit_get_eq _ _ _ _ Hbitu) in Hget'.\n      injection Hget'; intro; subst bi'; clear Hget'.\n      exists pmt; trivial.\n    assert (Hin'x := bmt_update_log_pbn_in_bmt_log_preserv_rev _ _ _ _ _ _ Hbmtul Hneq2 Hin').\n    apply False_ind.\n    apply Hnin.\n    exists lbn'.\n    right.\n    trivial.\n  rewrite (bit_update_bit_get_neq _ _ _ _ _ Hbitu (neq_sym Hneq)) in Hget'.\n  destruct (pbn_eq_dec lbn lbn') as [Heq2 | Hneq2].\n    subst lbn'.\n    assert (Hin'' := bmt_update_log_pbn_in_bmt_log_eq _ _ _ _ Hbmtul).\n    assert (pbn = pbn').\n      unfold pbn_in_bmt_log in Hin', Hin''.\n      destruct Hin' as [x1 Hin'].\n      destruct Hin'' as [x2 Hin''].\n      rewrite Hin' in Hin''.\n      injection Hin''; intro; subst pbn'; trivial.\n    subst pbn'.\n    destruct (Hneq (refl_equal _)).\n  destruct (HI5 lbn' pbn' bi' Hget') as [Hx Hy].\n  apply Hy.\n  eapply bmt_update_log_pbn_in_bmt_log_preserv_rev; eauto.\nQed.\n\nLemma I_pbn_bmt_used_preserv_bmt_update_none_log :\n  forall bit bmt pbn lbn bi pmt bit' bmt',\n    I_pbn_bmt_used bit bmt \n    -> ~ pbn_in_bmt bmt pbn\n    -> bmt_update bmt lbn (None, Some pbn) = Some bmt'\n    -> bit_update bit pbn bi = Some bit'\n    -> bi_state bi = bs_log lbn pmt\n    -> I_pbn_bmt_used bit' bmt'.\nProof.\n  unfold I_pbn_bmt_used.\n  intros bit bmt pbn lbn bi pmt bit' bmt' HI5 Hnin Hbmtu Hbitu Hbi.\n  intros lbn' pbn' bi' Hget'.\n  split.\n    intros Hin'.\n    destruct (pbn_eq_dec pbn pbn') as [Heq | Hneq].\n      subst pbn'.\n      destruct (pbn_eq_dec lbn lbn') as [Heq2 | Hneq2].\n        subst lbn'.\n        destruct Hin' as [x Hbmtget'].\n        rewrite (bmt_update_bmt_get_eq _ _ _ _ Hbmtu) in Hbmtget'.\n        discriminate Hbmtget'.\n      assert (Hin'x := bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ pbn _ Hbmtu Hneq2).\n      assert (Hinl : pbn_in_bmt_lbn bmt' lbn' pbn).\n        left; trivial.\n      apply Hin'x in Hinl.\n      apply False_ind.\n      apply Hnin.\n      exists lbn'.\n      trivial.\n    rewrite (bit_update_bit_get_neq _ _ _ _ _ Hbitu (neq_sym Hneq)) in Hget'.\n      destruct (pbn_eq_dec lbn lbn') as [Heq2 | Hneq2].\n        subst lbn'.\n        destruct Hin' as [x Hbmtget'].\n        rewrite (bmt_update_bmt_get_eq _ _ _ _ Hbmtu) in Hbmtget'.\n        discriminate Hbmtget'.\n    assert (Hin'2: pbn_in_bmt_lbn bmt' lbn' pbn').\n      left; trivial.\n    assert (Hin'x := bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hbmtu Hneq2 Hin'2).\n    destruct (HI5 lbn' _ _ Hget') as [HI5_1 HI5_2].\n    apply HI5_1; trivial.\n    unfold pbn_in_bmt_data in Hin' .\n    destruct Hin' as [x Hin'].\n    rewrite (bmt_update_bmt_get_neq _ _ _ _ _ Hbmtu Hneq2) in Hin'.\n    exists x; trivial.\n  intro Hinl'.\n  destruct (pbn_eq_dec pbn pbn') as [Heq | Hneq].\n    subst pbn'.\n    destruct (pbn_eq_dec lbn lbn') as [Heq2 | Hneq2].\n      subst lbn'.\n      rewrite (bit_update_bit_get_eq _ _ _ _ Hbitu) in Hget'.\n      injection Hget'; intro; subst bi'; clear Hget'.\n      exists pmt; trivial.\n    assert (Hin'x := bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ pbn _ Hbmtu Hneq2).\n    assert (Hin' : pbn_in_bmt_lbn bmt' lbn' pbn).\n      right; trivial.\n    apply Hin'x in Hin'.\n    apply False_ind.\n    apply Hnin.\n    exists lbn'.\n    trivial.\n  rewrite (bit_update_bit_get_neq _ _ _ _ _ Hbitu (neq_sym Hneq)) in Hget'.\n  destruct (pbn_eq_dec lbn lbn') as [Heq2 | Hneq2].\n    subst lbn'.\n    destruct Hinl' as [x Hinl'].\n    rewrite (bmt_update_bmt_get_eq _ _ _ _ Hbmtu) in Hinl'.\n    injection Hinl'; intros; subst pbn'; clear Hinl'.\n    destruct (Hneq (refl_equal _)).\n  destruct (HI5 lbn' pbn' bi' Hget') as [Hx Hy].\n  apply Hy.\n  destruct Hinl' as [x Hinl'].\n  rewrite (bmt_update_bmt_get_neq _ _ _ _ _ Hbmtu Hneq2) in Hinl'.\n  exists x; trivial.\nQed.\n\nLemma I_pbn_bmt_used_preserv_write_log_block: \n  forall bit bmt pbn lbn bi bit',\n    I_pbn_bmt_used bit bmt\n    -> I_pbn_bmt_distinguishable bmt\n    -> I_pbn_bmt_distinguishable_2 bmt\n    -> bit_update bit pbn bi = Some bit'\n    -> pbn_in_bmt_log bmt lbn pbn\n    -> (exists pmt, bi_state bi = bs_log lbn pmt)\n    -> I_pbn_bmt_used bit' bmt.\nProof.\n  intros bit bmt pbn lbn bi bit' HI5 HI7_1 HI7_2 Hup Hin Hbs.\n  unfold I_pbn_bmt_used in * .\n  intros lbn' pbn' bi' Hget'.\n  assert (pbn' = pbn \\/ pbn' <> pbn).\n    destruct (block_no_eq_dec pbn pbn').\n      left; auto.\n    right; auto.\n  destruct H.\n    subst pbn'.\n    split.\n      destruct (block_no_eq_dec lbn lbn').\n        subst lbn'.\n        intro Hx.\n        unfold pbn_in_bmt_data in Hx.\n        destruct Hx as [x Hx].\n        destruct Hin as [y Hy].\n        rewrite Hy in Hx.\n        injection Hx.\n        intros; subst x y.\n        destruct (HI7_2 lbn pbn pbn Hy (refl_equal _)). \n      intros Hx.\n      destruct (HI7_1 lbn lbn' pbn pbn H (or_intror Hin) (or_introl Hx) (refl_equal _)).\n    intros Hx.\n    assert (bi = bi').\n      rewrite (bit_update_bit_get_eq _ _ _ _ Hup) in Hget'.\n      injection Hget'; auto.\n    subst bi'.\n    assert (lbn' = lbn \\/ lbn <> lbn').\n      destruct (block_no_eq_dec lbn lbn'); auto.\n    destruct H.\n      subst lbn'.\n      trivial.\n    assert (HF := HI7_1 lbn lbn' pbn pbn H). \n    apply False_ind.\n    apply HF.\n    right; trivial.\n    right; trivial.\n    trivial.\n  apply HI5.\n  erewrite <- bit_update_bit_get_neq; eauto.\nQed.\n\n(* Lemma lbn_pbn_in_bmt_after_bmt_update_lbn : *)\nLemma pbn_in_bmt_after_bmt_update_lbn :\n  forall bmt lbn pbn bmr bmt',\n    pbn_in_bmt_lbn bmt lbn pbn\n    -> I_pbn_bmt_distinguishable bmt\n    -> bmt_update bmt lbn bmr = Some bmt'\n    -> ~ pbn_in_bmr pbn bmr \n    -> ~ pbn_in_bmt bmt' pbn.\nProof.\n  intros bmt lbn pbn bmr bmt' Hin HI71 Hu Hnin.\n  intro Hnin'.\n  unfold pbn_in_bmt in * .\n  destruct Hnin' as [lbn' Hnin'].\n  destruct (pbn_eq_dec lbn lbn') as [Heq | Hneq].\n  subst lbn'. \n    apply Hnin.\n    destruct (pbn_in_bmt_lbn_bmt_get _ _ _ Hnin') as [bmrx [Hget' Hxin]].\n    rewrite (bmt_update_bmt_get_eq _ _ _ _ Hu) in Hget'.\n    injection Hget'; intro; subst bmrx; clear Hget'.\n    trivial.\n  assert (Hin':= bmt_update_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hu Hneq Hnin').\n  assert (Hx := HI71  _ _ _ _ Hneq Hin Hin').\n  apply Hx; trivial.\nQed.\n\n(* ---------------------------------------------------------------- *)\n\nLemma I_pbn_habitation_implies_I_bmt_fbq_distinguiable:  (* Derivable Invariant *)\n  forall bmt fbq ,\n    I_pbn_habitation bmt fbq\n    -> I_bmt_fbq_distinguiable bmt fbq.\nProof.\n  intros bmt fbq HI6 pbn pbn' lbn Hpbn Hpbn' Hinbmt Hinfbq.\n  assert (Hx := I_pbn_habitation_in_fbq_implies_not_in_bmt pbn' bmt fbq Hpbn' HI6 Hinfbq); trivial.\n  intro Heq.\n  subst pbn'.\n  apply Hx.\n  exists lbn.\n  destruct Hinbmt.\n  left; trivial.\n  right; trivial.\nQed.\n\n(* ---------------------------------------------------------------- *)\n(* I8 Lemmas *)\n\nLemma I_pbn_fbq_distinguishable_implies_fbq_deq_fbq_not_in : \n  forall fbq pbn fbq',\n    I_pbn_fbq_distinguishable fbq\n    -> fbq_deq fbq = Some (pbn, fbq') \n    -> fbq_in fbq' pbn = false.\nProof.\n  unfold I_pbn_fbq_distinguishable.\n  intros fbq pbn fbq' HI8 Hdeq.\n  assert (Hg1 : fbq_get fbq 0 = Some pbn).\n    apply fbq_deq_fbq_get with fbq'; trivial.\n  destruct (fbq_in fbq' pbn) eqn:HF; trivial.\n  destruct (fbq_in_fbq_get _ _ HF) as [i Hgi].\n  assert (Hg2:= fbq_get_fbq_rdeq_fbq_get _ _ _ _ _ Hgi Hdeq).\n  apply False_ind.\n  apply (HI8 0 (S i) pbn pbn); trivial.\nQed.\n\nLemma I_pbn_fbq_distinguishable_preserv_fbq_enq :\n  forall fbq pbn fbq',\n    I_pbn_fbq_distinguishable fbq\n    -> fbq_in fbq pbn = false\n    -> fbq_enq fbq pbn = Some fbq'\n    -> I_pbn_fbq_distinguishable fbq'.\nProof.\n  unfold I_pbn_fbq_distinguishable.\n  intros fbq pbn fbq' HI8 Hin Henq.\n  intros i1 i2 pbn1 pbn2 Hi1i2  Hg1 Hg2.\n\n  destruct (fbq_get_fbq_enq_fbq_get_rev fbq fbq' i1 pbn1 pbn Henq Hg1) as [[Hpbn1  Hi1] | Hg1' ].\n    destruct (fbq_get_fbq_enq_fbq_get_rev fbq fbq' i2 pbn2 pbn Henq Hg2) as [[Hpbn2  Hi2] | Hg2' ].\n      subst i1 i2.\n      destruct (Hi1i2 (refl_equal _)).\n    subst pbn1.\n    intro HF.\n    subst pbn2.\n    apply (fbq_not_in_fbq_get_some_implies_false _ _ Hin _ Hg2').\n  destruct (fbq_get_fbq_enq_fbq_get_rev fbq fbq' i2 pbn2 pbn Henq Hg2) as [[Hpbn2  Hi2] | Hg2' ].\n    subst pbn2.\n    intro HF.\n    subst pbn1.\n    apply (fbq_not_in_fbq_get_some_implies_false _ _ Hin _ Hg1').\n  apply (HI8 i1 i2); trivial.\nQed.\n\nLemma I_pbn_fbq_distinguishable_preserv_fbq_deq: \n  forall fbq pbn fbq',\n    I_pbn_fbq_distinguishable fbq\n    -> fbq_deq fbq = Some (pbn, fbq')\n    -> I_pbn_fbq_distinguishable fbq'.\nProof.\n  unfold I_pbn_fbq_distinguishable.\n  intros fbq pbn fbq' HI8 Hdeq.\n  intros i1 i2 pbn1 pbn2 Hi1i2  Hg1 Hg2.\n  apply (HI8 (S i1) (S i2) pbn1 pbn2).\n    auto with arith.\n    apply (fbq_get_fbq_deq_fbq_get_rev _ _ _ _ _ Hdeq); trivial.\n  apply (fbq_get_fbq_deq_fbq_get_rev _ _ _ _ _ Hdeq); trivial.\nQed.\n\n(* ---------------------------------------------------------------- *)\n(* I6 Lemmas *)\nLemma I_pbn_habitation_alloc_merge : (* an ad hoc lemma *)\n  forall bmt fbq lbn pbnx pbn1 pbn2 bmt' fbq' fbq'' fbq''',\n    I_pbn_habitation bmt fbq\n    -> I_pbn_bmt_distinguishable bmt\n    -> I_pbn_bmt_distinguishable_2 bmt\n    -> I_pbn_fbq_distinguishable fbq\n    -> valid_block_no pbn1\n    -> valid_block_no pbn2\n    -> valid_block_no pbnx\n    -> bmt_get bmt lbn = Some (Some pbn1, Some pbn2)\n    -> fbq_deq fbq = Some (pbnx, fbq')\n    -> bmt_update bmt lbn (Some pbnx, None) = Some bmt'\n    -> fbq_enq fbq' pbn2 = Some fbq''\n    -> fbq_enq fbq'' pbn1 = Some fbq'''\n    -> I_pbn_habitation bmt' fbq'''.\nProof.\n  intros bmt fbq lbn pbnx pbn1 pbn2 bmt' fbq' fbq'' fbq'''.\n  intros HI6 HI7_1 HI7_2 HI8 Hpbn1 Hpbn2 Hpbnx Hlbn Hdeq Hbmtup Henq1 Henq2.\n  unfold I_pbn_habitation in * .\n  intros pbn Hpbnv.\n  assert (Hn12 : pbn1<>pbn2).\n     apply (HI7_2 lbn pbn1 pbn2); trivial.\n  assert (Hn1x : pbn1<>pbnx).\n    intro HF.\n    subst pbnx.\n    destruct (HI6 pbn1 Hpbn1) as [Hx | Hx].\n      destruct Hx as [[lbn' Hy1] Hy2].\n      rewrite (fbq_deq_fbq_in fbq pbn1 fbq') in Hy2; trivial.\n      discriminate.\n    destruct Hx as [Hx1 Hx2].\n    apply (Hx1 lbn).\n    left.\n    exists (Some pbn2).\n    trivial.\n  assert (Hn2x : pbn2<>pbnx).\n    intro HF.\n    subst pbnx.\n    destruct (HI6 pbn2 Hpbn2) as [Hx | Hx].\n      destruct Hx as [[lbn' Hy1] Hy2].\n      rewrite (fbq_deq_fbq_in fbq pbn2 fbq') in Hy2; trivial.\n      discriminate.\n    destruct Hx as [Hx1 Hx2].\n    apply (Hx1 lbn).\n    right.\n    exists (Some pbn1).\n    trivial.\n  destruct (block_no_eq_dec pbn pbn1)  as [H1 | H2].\n    subst pbn.\n    right.\n    assert (Hx : pbn_not_in_bmt bmt' pbn1).\n      assert (Hin : pbn_in_bmt_lbn bmt lbn pbn1).\n        left.\n        exists (Some pbn2).\n        trivial.\n      assert (Hnin: ~ pbn_in_bmr pbn1 (Some pbnx, None)).\n        unfold pbn_in_bmr.\n        trivial.\n      apply (pbn_in_bmt_after_bmt_update_lbn _ _ _ _ _ Hin HI7_1 Hbmtup Hnin).\n    split.\n      intro lbn'.\n      unfold pbn_not_in_bmt in Hx.\n      unfold pbn_in_bmt in Hx.\n      intro HF.\n      apply Hx.      \n      exists lbn'; trivial. \n      apply fbq_enq_fbq_in with fbq''; trivial.\n  destruct (pbn_eq_dec pbn pbn2) as [H21 | H22].\n    subst pbn.\n    right.\n    assert (Hx : pbn_not_in_bmt bmt' pbn2).\n      assert (Hin : pbn_in_bmt_lbn bmt lbn pbn2).\n        right.\n        exists (Some pbn1).\n        trivial.\n      assert (Hnin: ~ pbn_in_bmr pbn2 (Some pbnx, None)).\n        unfold pbn_in_bmr.\n        trivial.\n      apply (pbn_in_bmt_after_bmt_update_lbn _ _ _ _ _ Hin HI7_1 Hbmtup Hnin).\n    split.\n      intro lbn'.\n      unfold pbn_not_in_bmt in Hx.\n      unfold pbn_in_bmt in Hx.\n      intro HF.\n      apply Hx.      \n      exists lbn'; trivial.\n      rewrite (fbq_in_preserv_fbq_enq pbn2 fbq'' pbn1 fbq'''); eauto.\n      apply fbq_enq_fbq_in with fbq'; trivial.\n  assert (Hdec : pbn = pbnx \\/ pbn <> pbnx).\n    apply (pbn_eq_dec pbn pbnx); trivial.\n  destruct Hdec as [H31 | H32].\n    subst pbnx.\n    left.\n    split.\n      exists lbn.\n      unfold pbn_in_bmt_lbn.\n      left.\n      exists None.\n      apply bmt_update_bmt_get_eq with bmt; trivial.\n    apply (fbq_not_in_preserv_fbq_enq fbq'' pbn fbq''' pbn1); auto.\n    apply (fbq_not_in_preserv_fbq_enq fbq' pbn fbq'' pbn2); auto.\n    apply (I_pbn_fbq_distinguishable_implies_fbq_deq_fbq_not_in fbq pbn fbq'); trivial.\n    \n  destruct (HI6 pbn Hpbnv) as [H | H].\n    destruct H as [[lbn' Hlbn'] Hqnin].\n    assert (lbn' <> lbn).\n      intro HF.\n      subst lbn'.\n      unfold pbn_in_bmt_lbn in Hlbn'.\n      destruct Hlbn' as [Hlbn' | Hlbn'].\n        destruct Hlbn' as [x Hlbn'].\n        rewrite Hlbn in Hlbn'.\n        injection Hlbn'.\n        intros Hx1 Hx2.\n        apply H2.\n        auto.\n      destruct Hlbn' as [x Hlbn'].\n      rewrite Hlbn in Hlbn'.\n      injection Hlbn'.\n      intros Hx1 Hx2.\n      apply H22.\n      subst pbn2.\n      trivial.\n    left.\n    split.\n      exists lbn'.\n      apply (bmt_update_pbn_in_bmt_lbn_neq bmt lbn _ bmt' lbn' pbn Hbmtup H) in Hlbn'; eauto.\n    apply (fbq_not_in_preserv_fbq_enq fbq'' pbn fbq''' pbn1); auto.\n    apply (fbq_not_in_preserv_fbq_enq fbq' pbn fbq'' pbn2); auto.\n    apply (fbq_not_in_preserv_fbq_deq fbq pbn fbq' pbnx); auto.\n  right.\n  destruct H as [Hx1 Hx2].\n  split.    \n    intros lbn'.\n    intro HF.\n    apply (Hx1 lbn').\n    assert (lbn' <> lbn).\n      intros Hy.\n      subst lbn'.\n      assert (bmt_get bmt' lbn = Some (Some pbnx, None)).\n        apply (bmt_update_bmt_get_eq bmt lbn _ bmt' Hbmtup); trivial.\n      unfold pbn_in_bmt_lbn in HF.\n      destruct HF as [HF | HF].\n        unfold pbn_in_bmt_data in HF.\n        destruct HF as [x Hg].\n        rewrite Hg in H.\n        injection H.\n        intros.\n        apply H32.\n        trivial.\n      unfold pbn_in_bmt_log in HF.\n      destruct HF as [x Hg].\n      rewrite Hg in H.\n      discriminate.\n    apply (bmt_update_pbn_in_bmt_lbn_neq_rev bmt bmt' lbn lbn' pbn _ Hbmtup) in HF; eauto.\n\n  rewrite (fbq_in_preserv_fbq_enq pbn fbq'' pbn1 fbq'''); auto.\n  rewrite (fbq_in_preserv_fbq_enq pbn fbq' pbn2 fbq''); auto.\n  rewrite (fbq_in_preserv_fbq_deq fbq pbn fbq' pbnx ); auto.\nQed.    \n\nLemma I_pbn_habitation_alloc_merge_2 : (* an ad hoc lemma *)\n  forall bmt fbq lbn pbnx pbn2 bmt' fbq' fbq'',\n    I_pbn_habitation bmt fbq\n    -> I_pbn_bmt_distinguishable bmt\n    -> I_pbn_bmt_distinguishable_2 bmt\n    -> I_pbn_fbq_distinguishable fbq\n    -> valid_block_no pbn2\n    -> valid_block_no pbnx\n    -> bmt_get bmt lbn = Some (None, Some pbn2)\n    -> fbq_deq fbq = Some (pbnx, fbq')\n    -> bmt_update bmt lbn (Some pbnx, None) = Some bmt'\n    -> fbq_enq fbq' pbn2 = Some fbq''\n    -> I_pbn_habitation bmt' fbq''.\nProof.\n  intros bmt fbq lbn pbnx pbn2 bmt' fbq' fbq''.\n  intros HI6 HI7_1 HI7_2 HI8 Hpbn2 Hpbnx Hlbn Hdeq Hbmtup Henq.\n  unfold I_pbn_habitation in * .\n  intros pbn Hpbnv.\n  assert (Hn2x : pbn2<>pbnx).\n    intro HF.\n    subst pbnx.\n    destruct (HI6 pbn2 Hpbn2) as [Hx | Hx].\n      destruct Hx as [[lbn' Hy1] Hy2].\n      rewrite (fbq_deq_fbq_in fbq pbn2 fbq') in Hy2; trivial.\n      discriminate.\n    destruct Hx as [Hx1 Hx2].\n    apply (Hx1 lbn).\n    right.\n    exists (None).\n    trivial.\n  destruct (pbn_eq_dec pbn pbn2) as [H21 | H22].\n    subst pbn.\n    right.\n    assert (Hx : pbn_not_in_bmt bmt' pbn2).\n      assert (Hin : pbn_in_bmt_lbn bmt lbn pbn2).\n        right.\n        exists None.\n        trivial.\n      assert (Hnin: ~ pbn_in_bmr pbn2 (Some pbnx, None)).\n        unfold pbn_in_bmr.\n        trivial.\n      apply (pbn_in_bmt_after_bmt_update_lbn _ _ _ _ _ Hin HI7_1 Hbmtup Hnin).\n    split.\n      intro lbn'.\n      unfold pbn_not_in_bmt in Hx.\n      unfold pbn_in_bmt in Hx.\n      intro HF.\n      apply Hx.      \n      exists lbn'; trivial.\n      apply fbq_enq_fbq_in with fbq'; trivial.\n  assert (Hdec : pbn = pbnx \\/ pbn <> pbnx).\n    apply (pbn_eq_dec pbn pbnx); trivial.\n  destruct Hdec as [H31 | H32].\n    subst pbnx.\n    left.\n    split.\n      exists lbn.\n      unfold pbn_in_bmt_lbn.\n      left.\n      exists None.\n      apply bmt_update_bmt_get_eq with bmt; trivial.\n    apply (fbq_not_in_preserv_fbq_enq fbq' pbn fbq'' pbn2); auto.\n\n    apply (I_pbn_fbq_distinguishable_implies_fbq_deq_fbq_not_in fbq pbn fbq'); trivial.\n\n  destruct (HI6 pbn Hpbnv) as [H | H].\n    destruct H as [[lbn' Hlbn'] Hqnin].\n    assert (lbn' <> lbn).\n      intro HF.\n      subst lbn'.\n      unfold pbn_in_bmt_lbn in Hlbn'.\n      destruct Hlbn' as [Hlbn' | Hlbn'].\n        destruct Hlbn' as [x Hlbn'].\n        rewrite Hlbn in Hlbn'.\n        discriminate.\n      destruct Hlbn' as [x Hlbn'].\n      rewrite Hlbn in Hlbn'.\n      injection Hlbn'.\n      intros Hx1 Hx2.\n      apply H22.\n      subst pbn2.\n      trivial.\n    left.\n    split.\n      exists lbn'.\n      apply (bmt_update_pbn_in_bmt_lbn_neq bmt lbn _ bmt' lbn' pbn Hbmtup H) in Hlbn'; eauto.\n    apply (fbq_not_in_preserv_fbq_enq fbq' pbn fbq'' pbn2); auto.\n    apply (fbq_not_in_preserv_fbq_deq fbq pbn fbq' pbnx); auto.\n  right.\n  destruct H as [Hx1 Hx2].\n  split.    \n    intros lbn'.\n    intro HF.\n    apply (Hx1 lbn').\n    assert (lbn' <> lbn).\n      intros Hy.\n      subst lbn'.\n      assert (bmt_get bmt' lbn = Some (Some pbnx, None)).\n        apply (bmt_update_bmt_get_eq bmt lbn _ bmt' Hbmtup); trivial.\n      unfold pbn_in_bmt_lbn in HF.\n      destruct HF as [HF | HF].\n        unfold pbn_in_bmt_data in HF.\n        destruct HF as [x Hg].\n        rewrite Hg in H.\n        injection H.\n        intros.\n        apply H32.\n        trivial.\n      unfold pbn_in_bmt_log in HF.\n      destruct HF as [x Hg].\n      rewrite Hg in H.\n      discriminate.\n    apply (bmt_update_pbn_in_bmt_lbn_neq_rev bmt bmt' lbn lbn' pbn _ Hbmtup) in HF; eauto.\n\n  rewrite (fbq_in_preserv_fbq_enq pbn fbq' pbn2 fbq''); auto.\n  rewrite (fbq_in_preserv_fbq_deq fbq pbn fbq' pbnx ); auto.\nQed.\n\nLemma I_pbn_habitation_preserv_bmt_update_log: \n  forall bmt fbq lbn pbn1 pbn2 bmt' fbq',\n    I_pbn_habitation bmt fbq\n    -> I_pbn_bmt_distinguishable bmt\n    -> I_pbn_bmt_distinguishable_2 bmt\n    -> I_pbn_fbq_distinguishable fbq\n    -> valid_block_no pbn1\n    -> valid_block_no pbn2\n    -> bmt_get bmt lbn = Some (Some pbn1, None)\n    -> fbq_deq fbq = Some (pbn2, fbq')\n    -> bmt_update_log bmt lbn pbn2 = Some bmt'\n    -> I_pbn_habitation bmt' fbq'.\nProof.\n  intros bmt fbq lbn pbn1 pbn2 bmt' fbq'. \n  intros HI6 HI7_1 HI7_2 HI8 Hpbn1 Hpbn2 Hget Hdeq Hul.\n  unfold I_pbn_habitation in * .\n  intros pbn Hpbnv.\n  assert (Hn1x : pbn1<>pbn2).\n    intro HF.\n    subst pbn2.\n    destruct (HI6 pbn1 Hpbn1) as [Hx | Hx].\n      destruct Hx as [[lbn' Hy1] Hy2].\n      rewrite (fbq_deq_fbq_in fbq pbn1 fbq') in Hy2; trivial.\n      discriminate.\n    destruct Hx as [Hx1 Hx2].\n    apply (Hx1 lbn).\n    left.\n    exists (None).\n    trivial.\n  destruct (pbn_eq_dec pbn pbn1) as [H11 | H12].\n    subst pbn.\n    left.\n    split.\n      exists lbn.\n      left.\n      apply (bmt_update_log_pbn_in_bmt_data_preserv _ _ _ _ _ _ Hul).\n      exists None; trivial.\n    apply (fbq_not_in_preserv_fbq_deq fbq pbn1 fbq' pbn2); auto.\n    destruct (HI6 pbn1 Hpbn1).\n      destruct H as [[lbn' H1] H2]; trivial.\n    destruct H as [H1 H2].\n    apply False_ind.\n    apply (H1 lbn).\n    left; exists (None); trivial.\n  destruct (pbn_eq_dec pbn pbn2) as [H21 | H22].\n    subst pbn.\n    left.\n    split.\n      exists lbn.\n      right.\n      apply (bmt_update_log_pbn_in_bmt_log_eq _ _ _ _ Hul).\n    apply (I_pbn_fbq_distinguishable_implies_fbq_deq_fbq_not_in fbq pbn2 fbq'); trivial.\n    \n  destruct (HI6 pbn Hpbnv) as [H | H].\n    destruct H as [[lbn' Hlbn'] Hqnin].\n    assert (lbn' <> lbn).\n      intro HF.\n      subst lbn'.\n      unfold pbn_in_bmt_lbn in Hlbn'.\n      destruct Hlbn' as [Hlbn' | Hlbn'].\n        destruct Hlbn' as [x Hlbn'].\n        rewrite Hget in Hlbn'.\n        apply H12.\n        injection Hlbn'; auto.\n      destruct Hlbn' as [x Hlbn'].\n      rewrite Hget in Hlbn'.\n      discriminate.\n    left.\n    split.\n      exists lbn'.\n      apply (bmt_update_log_pbn_in_bmt_lbn_neq bmt lbn _ bmt' lbn' pbn Hul (neq_sym H)) in Hlbn'; eauto.\n    apply (fbq_not_in_preserv_fbq_deq fbq pbn fbq' pbn2); auto.\n  right.\n  destruct H as [Hx1 Hx2].\n  split.    \n    intros lbn'.\n    intro HF.\n    apply (Hx1 lbn').\n    assert (lbn' <> lbn).\n      intros Hy.\n      subst lbn'.\n      destruct HF.\n        apply (Hx1 lbn).\n        left.\n        apply (bmt_update_log_pbn_in_bmt_data_preserv_rev _ _ _ _ _ _ Hul H); auto.\n      apply H22.\n      apply pbn_in_bmt_log_inj with bmt' lbn; trivial.\n      apply bmt_update_log_pbn_in_bmt_log_eq with bmt; auto.\n    apply (bmt_update_log_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hul (neq_sym H)) in HF; eauto.\n  rewrite (fbq_in_preserv_fbq_deq fbq pbn fbq' pbn2 ); auto.\nQed.\n\nLemma I_pbn_habitation_preserv_bmt_update_log_case2: \n  forall bmt fbq lbn pbn2 bmt' fbq',\n    I_pbn_habitation bmt fbq\n    -> I_pbn_bmt_distinguishable bmt\n    -> I_pbn_bmt_distinguishable_2 bmt\n    -> I_pbn_fbq_distinguishable fbq\n    -> valid_block_no pbn2\n    -> bmt_get bmt lbn = Some (None, None)\n    -> fbq_deq fbq = Some (pbn2, fbq')\n    -> bmt_update_log bmt lbn pbn2 = Some bmt'\n    -> I_pbn_habitation bmt' fbq'.\nProof.\n  intros bmt fbq lbn pbn2 bmt' fbq'. \n  intros HI6 HI7_1 HI7_2 HI8 Hpbn2 Hget Hdeq Hul.\n  unfold I_pbn_habitation in * .\n  intros pbn Hpbnv.\n  destruct (pbn_eq_dec pbn pbn2) as [H21 | H22].\n    subst pbn.\n    left.\n    split.\n      exists lbn.\n      right.\n      apply (bmt_update_log_pbn_in_bmt_log_eq _ _ _ _ Hul).\n    apply (I_pbn_fbq_distinguishable_implies_fbq_deq_fbq_not_in fbq pbn2 fbq'); trivial.\n    \n  destruct (HI6 pbn Hpbnv) as [H | H].\n    destruct H as [[lbn' Hlbn'] Hqnin].\n    assert (lbn' <> lbn).\n      intro HF.\n      subst lbn'.\n      unfold pbn_in_bmt_lbn in Hlbn'.\n      destruct Hlbn' as [Hlbn' | Hlbn'].\n        destruct Hlbn' as [x Hlbn'].\n        rewrite Hget in Hlbn'.\n        discriminate.\n      destruct Hlbn' as [x Hlbn'].\n      rewrite Hget in Hlbn'.\n      discriminate.\n    left.\n    split.\n      exists lbn'.\n      apply (bmt_update_log_pbn_in_bmt_lbn_neq bmt lbn _ bmt' lbn' pbn Hul (neq_sym H)) in Hlbn'; eauto.\n    apply (fbq_not_in_preserv_fbq_deq fbq pbn fbq' pbn2); auto.\n  right.\n  destruct H as [Hx1 Hx2].\n  split.    \n    intros lbn'.\n    intro HF.\n    apply (Hx1 lbn').\n    assert (lbn' <> lbn).\n      intros Hy.\n      subst lbn'.\n      destruct HF.\n        apply (Hx1 lbn).\n        left.\n        apply (bmt_update_log_pbn_in_bmt_data_preserv_rev _ _ _ _ _ _ Hul H); auto.\n      apply H22.\n      apply pbn_in_bmt_log_inj with bmt' lbn; trivial.\n      apply bmt_update_log_pbn_in_bmt_log_eq with bmt; auto.\n    apply (bmt_update_log_pbn_in_bmt_lbn_neq_rev _ _ _ _ _ _ Hul (neq_sym H)) in HF; eauto.\n  rewrite (fbq_in_preserv_fbq_deq fbq pbn fbq' pbn2 ); auto.\nQed.\n\nLemma I_valid_lbn_has_entry_in_bmt_preserv_bmt_update : \n  forall bmt lbn bmr bmt',\n    I_valid_lbn_has_entry_in_bmt bmt\n    -> bmt_update bmt lbn bmr = Some bmt'\n    -> I_valid_lbn_has_entry_in_bmt bmt'.\nProof.\n  unfold I_valid_lbn_has_entry_in_bmt.\n  intros bmt lbn bmr bmt' HI10 Hu.\n  intros lbn'.\n  destruct (pbn_eq_dec lbn lbn') as [Heq | Hneq ].\n    subst lbn'.\n    destruct (HI10 lbn) as [H1 H2].\n    split.\n      intro Hlbn.\n      rewrite (bmt_update_bmt_get_eq _ _ _ _ Hu).\n      exists bmr; trivial.\n    intros [bme Hlbn].\n    apply H2; trivial.\n    apply (bmt_update_bmt_get_eq_rev _ _ _ _ Hu); trivial.\n  split.\n    intro Hlbn'.\n    destruct (HI10 lbn') as [H1 H2].\n    rewrite (bmt_update_bmt_get_neq _ _ _ _ _ Hu Hneq).\n    apply H1; trivial.\n  intros [bmr' H'].\n  destruct (HI10 lbn') as [H1 H2].\n  apply H2.\n  rewrite (bmt_update_bmt_get_neq _ _ _ _ _ Hu Hneq) in H'.\n  exists bmr'; trivial.\nQed.\n\nLemma I_valid_lbn_has_entry_in_bmt_preserv_bmt_update_log : \n  forall bmt lbn pbn bmt',\n    I_valid_lbn_has_entry_in_bmt bmt\n    -> bmt_update_log bmt lbn pbn = Some bmt'\n    -> I_valid_lbn_has_entry_in_bmt bmt'.\nProof.\n  unfold I_valid_lbn_has_entry_in_bmt.\n  intros bmt lbn pbn bmt' HI10 Hul.\n  intros lbn'.\n  destruct (pbn_eq_dec lbn lbn') as [Heq | Hneq ].\n    subst lbn'.\n    destruct (HI10 lbn) as [H1 H2].\n    split.\n      intro Hlbn.\n      assert (Hx := bmt_update_log_pbn_in_bmt_log_eq _ _ _ _ Hul).\n      destruct Hx as [x Hl].\n      rewrite Hl.\n      eexists; eauto.\n    intros [bme Hlbn].\n    apply H2; trivial.\n    apply (bmt_update_log_bmt_get_eq_rev _ _ _ _ Hul); trivial.\n  split.\n    intro Hlbn'.\n    destruct (HI10 lbn') as [H1 H2].\n    rewrite (bmt_update_log_bmt_get_neq _ _ _ _ _ Hul Hneq).\n    apply H1; trivial.\n  intros [bmr' H'].\n  destruct (HI10 lbn') as [H1 H2].\n  apply H2.\n  rewrite (bmt_update_log_bmt_get_neq _ _ _ _ _ Hul Hneq) in H'.\n  exists bmr'; trivial.\nQed.\n\n(* ---------------------------------------------------------------- *)\n\nLemma I_pbn_bmt_used_implies_pbn_is_used :\n  forall bit bmt pbn lbn bi,\n  I_pbn_bmt_used bit bmt\n  -> bit_get bit pbn = Some bi\n  -> pbn_in_bmt_lbn bmt lbn pbn \n  -> check_used_block bi = true.\nProof.\n  intros.\n  unfold I_pbn_bmt_used in H.\n  destruct (H lbn pbn bi H0) as [Hx Hy].\n  unfold pbn_in_bmt_lbn in H1.\n  destruct H1.\n    unfold check_used_block.\n    rewrite (Hx H1). trivial.\n  destruct (Hy H1) as [pmt Hbs].\n  unfold check_used_block.\n  rewrite Hbs; trivial.\nQed.\n\nLemma J_bi_block_coherent_preserv_used_set_invalid : \n  forall bit c pbn bi bit',\n    J_bi_block_coherent c bit\n    -> bit_get bit pbn = Some bi\n    -> check_used_block bi = true\n    -> bit_update bit pbn (bi_set_state bi bs_invalid) = Some bit'\n    -> J_bi_block_coherent c bit'.\nProof.\n  intros bit c pbn bi bit' HJ Hget Hck Hup.\n  unfold J_bi_block_coherent in * .\n  intros pbn' bi' Hget'.\n  unfold chip_bi_coherent.\n  assert (Hdec: pbn = pbn' \\/ pbn <> pbn').\n    apply (pbn_eq_dec pbn pbn'); trivial.\n  destruct Hdec as [Heq | Hneq].\n    subst pbn'.\n    assert (bi' = bi_set_state bi bs_invalid).\n      rewrite (bit_update_bit_get_eq bit pbn (bi_set_state bi bs_invalid) bit') in Hget'; trivial.\n      injection Hget'.\n      intros; auto.\n    assert (Hx := HJ pbn bi Hget).\n    unfold chip_bi_coherent in Hx.\n    destruct Hx as [b [Hb Hx]].\n    exists b.\n    split; trivial.\n    rewrite H.\n    unfold bi_set_state.\n    simpl.\n    destruct (check_used_implies_check_data_log Hck) as [Hck1 | Hck2].\n      unfold check_data_block in Hck1.\n      destruct (bi_state bi); try discriminate.\n      unfold block_coherent_data in Hx.\n      destruct Hx as [lbn' [_ [_ [Hx _]]]].\n      trivial.\n    unfold check_log_block in Hck2.\n    destruct (bi_state bi); try discriminate.\n    unfold block_coherent_log in Hx.\n    destruct Hx as [pmt' [lbn' [_ [_ [Hx _]]]]].\n    trivial.\n  apply HJ.\n  rewrite <- (bit_update_bit_get_neq bit pbn' bit' (bi_set_state bi bs_invalid) pbn) ; eauto.\nQed.\n\nLemma J_bi_block_coherent_preserv_write_block_log :\n  forall c bit pbn bi b' c' bit',\n    J_bi_block_coherent c bit\n    -> bit_update bit pbn bi = Some bit'\n    -> chip_get_block c' pbn = Some b'\n    -> (forall pbn' : block_no,\n          pbn' <> pbn -> chip_get_block c' pbn' = chip_get_block c pbn')\n    -> block_coherent_log bi b'\n    -> J_bi_block_coherent c' bit'.\nProof.\n  intros.\n  unfold J_bi_block_coherent in * .\n  intros pbn'  bi' Hgetbi'.\n  unfold chip_bi_coherent in * .\n  assert (Hdec: pbn' = pbn \\/ pbn' <> pbn).\n    destruct (nat_eq_dec pbn' pbn).\n    left; trivial.\n    right; trivial.\n  destruct Hdec as [Heq | Hneq].\n    subst pbn'.\n    assert (bi = bi').\n      erewrite bit_update_bit_get_eq in Hgetbi'; eauto.\n      injection Hgetbi'.\n      trivial.\n    subst bi'.\n    exists b'.\n    split; trivial.\n    unfold block_coherent_log in H3.\n    destruct ((fun x => x) H3) as [pmt [lbn [H4 [H5 H6]]]].\n    rewrite H4.\n    trivial.\n  assert (H4: bit_get bit pbn' = Some bi').\n    erewrite <- (bit_update_bit_get_neq bit pbn' bit' bi pbn); eauto.\n  destruct (H pbn' bi' H4) as [b [Hb Hx]].\n  exists b.\n  split; trivial.\n  erewrite H2; eauto.\nQed.  \n\nLemma J_bi_block_coherent_preserv_bit_update_merge :\n  forall c' bit' pbn_free bi' c'' bit'' lbn,\n    J_bi_block_coherent c' bit'\n    -> (exists b' : block,\n          chip_get_block c'' pbn_free = Some b' /\\\n          block_coherent_data_partial PAGES_PER_BLOCK b')\n    -> (forall pbn' : block_no,\n        pbn' <> pbn_free -> chip_get_block c'' pbn' = chip_get_block c' pbn')\n    -> bit_get bit' pbn_free = Some bi'\n    -> bit_update bit' pbn_free (mk_bi (bs_data lbn) PAGES_PER_BLOCK (bi_erase_count bi')) = Some bit''\n    -> J_bi_block_coherent c'' bit''.\nProof.\n  intros c bit pbn bi c' bit' lbn.  \n  intros HJ Hm1 Hm2 Hget Hup.  \n  unfold J_bi_block_coherent in * .\n  intros pbn' bi' Hget'.\n  destruct (nat_eq_dec pbn pbn') as [Heq | Hneq].\n  subst pbn'.\n  rewrite (bit_update_bit_get_eq bit pbn _ bit' Hup) in Hget'.\n  inversion Hget'.\n  subst bi'.\n  unfold chip_bi_coherent.\n  simpl.\n  destruct Hm1 as [b [Hb Hco]].\n  exists b.\n  split; trivial.\n  unfold block_coherent_data.\n  simpl.\n  exists lbn.\n  split; trivial.\n  unfold block_coherent_data_partial in Hco.\n  destruct Hco as [Hnb [Hbs Hco]].\n  split; auto.\n  split; auto.\n  split; auto.\n  intros loc Hloc.\n  destruct (Hco loc Hloc) as [Hco1 Hco2].\n  apply Hco1.\n  unfold valid_page_off in Hloc.\n  exact Hloc.\n  \n  assert (pbn' <> pbn).\n    auto.\n  unfold chip_bi_coherent.\n  rewrite (bit_update_bit_get_neq bit pbn' bit' _ pbn Hup H) in Hget'.\n  assert (chip_bi_coherent c pbn' bi').\n    apply HJ; trivial.\n  unfold chip_bi_coherent in H0.\n  destruct H0 as [b [Hb Hx]].\n  exists b.\n  split; trivial.\n  rewrite Hm2; trivial.\nQed.\n\n(* used in the 2nd case of alloc_block *)\nLemma J_bi_block_coherent_preserv_erased_set_erased: \n  forall c bit pbn bi bit' bi',\n    J_bi_block_coherent c bit\n    -> bit_get bit pbn = Some bi\n    -> bi_state bi = bs_erased\n    -> bi' = mk_bi bs_erased 0 (bi_erase_count bi)\n    -> bit_update bit pbn bi' = Some bit'\n    -> J_bi_block_coherent c bit'.\nProof.\n  intros c bit pbn bi bit' bi' HJ Hget Hbis Hbi' Hup.\n  unfold J_bi_block_coherent in * .\n  rename bi' into bix.\n  intros pbn' bi' Hget'.\n  destruct (pbn_eq_dec pbn pbn') as [Heq | Hneq].\n    subst pbn'.\n    rewrite (bit_update_bit_get_eq _ _ _ _ Hup) in Hget'.\n    injection Hget'.\n    intro; subst bix.\n    subst bi'.\n    unfold chip_bi_coherent.\n    simpl.\n    clear Hget'.\n    assert (Hx := HJ pbn bi Hget).\n    unfold chip_bi_coherent in Hx.\n    destruct Hx as [b [Hb Hx]].\n    exists b.\n    split; trivial.\n    rewrite Hbis in Hx.\n    unfold block_coherent_erased in * .\n    simpl.\n    destruct Hx as [H1 [H2 [H3 [H4 H5]]]].\n    rewrite H4.\n    rewrite H3.\n    split; trivial.\n    split; trivial.\n    split; trivial.\n    split; trivial.\n  rewrite (bit_update_bit_get_neq bit pbn' bit' _ pbn Hup (neq_sym Hneq)) in Hget'.\n  apply HJ; trivial.\nQed.\n\nLemma J_bi_block_coherent_preserv_bit_update_chip_erase: \n  forall c bit pbn bi b c' bit' bi',\n    J_bi_block_coherent c bit\n    -> bit_get bit pbn = Some bi\n    -> bi' = mk_bi bs_erased 0 (S (bi_erase_count bi))\n    -> bit_update bit pbn bi' = Some bit'\n    -> chip_get_block c pbn = Some b\n    -> chip_set_block c pbn (erased_block (block_erase_count b)) = Some c'\n    -> J_bi_block_coherent c' bit'.\nProof.\n  intros c bit pbn bi b c' bit' bix.\n  unfold J_bi_block_coherent.\n  intros HJ Hget Hbi' Hup Hgetc Hsetc.\n  intros pbn' bi' Hget'.\n  destruct (chip_set_block_elim c pbn _ c' Hsetc) as [Hbv [Hgetc'1 Hgetc'2]].\n  destruct (pbn_eq_dec pbn pbn') as [Heq | Hneq].\n    subst pbn'.\n    rewrite (bit_update_bit_get_eq _ _ _ _ Hup) in Hget'.\n    injection Hget'.\n    intro H; subst bi'; clear Hget'.\n    unfold chip_bi_coherent.\n    exists (erased_block (block_erase_count b)).\n    split; trivial.\n    subst bix; simpl.\n    unfold block_coherent_erased.\n    simpl.\n    split; trivial.\n    split; trivial.\n    split; trivial.\n    split; trivial.\n    intros loc Hloc.\n    unfold erased_block.\n    unfold block_get_page.\n    rewrite Hloc.\n    unfold block_pages.\n    exists init_page.\n    split.\n    assert (Hx: loc < PAGES_PER_BLOCK).\n      unfold valid_page_off in Hloc.\n      unfold bvalid_page_off in Hloc.\n      desbnat.\n      trivial.\n    rewrite (@list_get_list_repeat_list _ _ _ _ Hx).\n    trivial.\n    unfold init_page.\n    simpl; trivial.\n  rewrite (bit_update_bit_get_neq bit pbn' bit' _ pbn Hup (neq_sym Hneq)) in Hget'.\n  unfold chip_bi_coherent.\n  destruct (HJ pbn' bi' Hget') as [bx [Hbx Hx]].\n  exists bx.\n  split; trivial.\n  rewrite (Hgetc'2 pbn' Hneq).\n  trivial.\nQed.\n\nLemma blank_pmt_shape:\n  forall loc,\n    (bvalid_page_off loc = true\n    -> pmt_get blank_pmt loc = Some pmte_empty)\n    /\\ (bvalid_page_off loc = false \n        -> pmt_get blank_pmt loc = None). \nProof.\n  intros.\n  split.\n    intros.\n    unfold bvalid_page_off in H.\n    unfold pmt_get.\n    unfold blank_pmt.\n    desbnat.\n    rewrite (@list_get_list_repeat_list _ loc pmte_empty PAGES_PER_BLOCK H).\n    trivial.\n  intros.\n  unfold bvalid_page_off in H.\n  unfold pmt_get, blank_pmt.\n  desbnat.\n  rewrite (@list_get_list_repeat_list_none _ loc pmte_empty PAGES_PER_BLOCK H).\n  trivial.\nQed.\n\nLemma blank_pmt_shape':\n  pmt_shape blank_pmt 0.\nProof.\n  unfold pmt_shape.\n  intros.\n  destruct (blank_pmt_shape loc) as [H1 H2].\n  split.\n    intro Hloc.\n    simplbnat.\n  intro Hloc.\n  rewrite (H1 H).\n  trivial.\nQed.\n\nLemma blank_pmt_is_domain_complete : \n  pmt_domain_is_complete blank_pmt.\nProof.\n  unfold pmt_domain_is_complete.\n  intros.\n  unfold pmt_len.\n  simpl.\n  trivial.\nQed.\n\n\nLemma pmt_update_pmt_find_rev :\n  forall pmt loc off pmt',\n  pmt_domain_is_complete pmt\n  -> pmt_shape pmt loc \n  -> pmt_update pmt loc off = Some pmt'\n  -> pmt_find_rev pmt' (pmte_log off) = Some loc.\nProof.\n  intros pmt loc off pmt' Hpd Hps Hu.\n  unfold pmt_find_rev.\n  assert (Hg:= pmt_update_pmt_get_eq _ _ _ _ Hu).\n  unfold pmt_shape in Hps.\n  assert (Hlen: pmt_len pmt' = PAGES_PER_BLOCK).\n    unfold pmt_domain_is_complete in Hpd.\n    rewrite (pmt_update_pmt_len _ _ _ _ Hu).\n    trivial.\n  assert (forall loc' pmte,\n            loc' > loc\n            -> pmt_get pmt' loc' = Some pmte\n            -> pmte_log off <> pmte).\n    intros loc' pmte Hneq Hgloc'.\n    intros HF.\n    subst pmte.\n    assert (valid_page_off loc').\n      unfold valid_page_off.\n      unfold bvalid_page_off.\n      destruct (blt_nat loc' PAGES_PER_BLOCK) eqn:Hloc'b; trivial.\n      destruct (pmt_len_pmt_get _ _ Hlen loc') as [H1 H2].\n      rewrite (H2 Hloc'b) in Hgloc'.\n      discriminate.\n    destruct (Hps loc' H) as [H1 H2].\n    assert (Hx : blt_nat loc' loc = false).    \n      clear - Hneq.\n      solvebnat.\n    apply H2 in Hx.\n    assert (Hy : loc' <> loc).\n      clear - Hneq.\n      omega.\n    rewrite (pmt_update_pmt_get_neq _ _ _ _ _ Hu Hy) in Hgloc'.\n    rewrite Hgloc' in Hx.\n    discriminate.\n  apply list_get_list_find_rev; trivial.\n  apply beq_pmt_entry_eq_true; trivial.\n  apply beq_pmt_entry_true_eq; trivial.\nQed.\n", "meta": {"author": "vittayang", "repo": "coqnand", "sha": "dd538809cf926e04d8de9912521d4e2dfc32189e", "save_path": "github-repos/coq/vittayang-coqnand", "path": "github-repos/coq/vittayang-coqnand/coqnand-dd538809cf926e04d8de9912521d4e2dfc32189e/InvLems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2490362921401594}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import fac3.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nRequire Import fac_facts.\n\nDefinition fac_spec :=\n DECLARE _fac\n  WITH n: Z\n  PRE  [ tint ] \n     PROP(0 <= n <= 12)\n     PARAMS (Vint (Int.repr n)) GLOBALS()\n     SEP ()\n  POST [ tint ]  \n     PROP() \n     LOCAL (temp ret_temp (Vint (Int.repr (fac n))))\n     SEP().\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre prog tt gv\n  POST [ tint ]  \n     PROP() \n     LOCAL (temp ret_temp (Vint (Int.repr (fac 5))))\n     SEP(TT).\n\nDefinition Gprog : funspecs :=\n        ltac:(with_library prog [fac_spec; main_spec]).\n\nLemma body_fac:  semax_body Vprog Gprog f_fac fac_spec.\nProof.\nstart_function.\nforward.\nforward_while (EX i:Z, EX f: Z,\n          PROP(0 <= i <= n; 1 <= f; (fac i * f = fac n)%Z) \n          LOCAL (temp _n (Vint (Int.repr i)); temp _f (Vint (Int.repr f)))\n          SEP()).\nExists n 1. entailer!.\nentailer!.\nforward.\nforward.\nforward.\nentailer!. {\nrewrite Int.signed_repr.\n2:{\npose proof (fac_in_range n H).\nsplit.\nrep_lia.\nassert (f <= fac n); [ | rep_lia].\nrewrite <- (Z.mul_1_l f).\nrewrite <- H2.\napply Z.mul_le_mono_nonneg_r; try rep_lia.\nchange 1 with (fac 1).\napply fac_mono. lia.\n}\nrewrite Int.signed_repr by rep_lia.\npose proof (fac_in_range n H).\nsplit.\napply Z.le_trans with 0. rep_lia.\napply Z.mul_nonneg_nonneg; lia.\napply Z.le_trans with (f * fac i)%Z.\napply Z.mul_le_mono_nonneg_l; try rep_lia.\nrewrite fac_equation. rewrite if_true by lia.\napply Z.le_trans with (i * 1)%Z. lia.\napply Z.mul_le_mono_nonneg_l; try rep_lia.\nchange (fac 0 <= fac (i-1)).\napply fac_mono. lia.\nrewrite Z.mul_comm. rewrite H2. lia.\n}\n\nExists (i-1, f*i)%Z.\nentailer!.\nsplit. lia.\nsplit.\napply Z.le_trans with (f * 1)%Z.\nlia.\napply Z.mul_le_mono_nonneg_l; try rep_lia.\nrewrite fac_equation in H2. rewrite if_true in H2 by lia.\nrewrite <- H2.\nrewrite (Z.mul_comm i).\nrewrite (Z.mul_comm f).\nrewrite Z.mul_assoc.\nauto.\nrewrite <- (Int.repr_signed (Int.repr i)) in HRE.\napply repr_inj_signed in HRE; try rep_lia.\nrewrite Int.signed_repr in HRE by rep_lia. subst.\nchange (fac 0) with 1 in H2.\nrewrite Z.mul_1_l in H2.\nsubst.\nforward.\nQed.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nforward_call.\nlia.\nforward.\nQed.\n\nExisting Instance NullExtension.Espec.\n\nLemma prog_correct: semax_prog prog tt Vprog Gprog.\nProof.\nprove_semax_prog.\nsemax_func_cons body_fac.\nsemax_func_cons body_main.\nQed.", "meta": {"author": "cverified", "repo": "cbench-vst", "sha": "b3119729b39c4f5439dee78c633a9d2e3257df41", "save_path": "github-repos/coq/cverified-cbench-vst", "path": "github-repos/coq/cverified-cbench-vst/cbench-vst-b3119729b39c4f5439dee78c633a9d2e3257df41/fac/verif_fac3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2490259750136175}}
{"text": "From iris.algebra Require Import gmap auth agree gset coPset list.\nFrom iris.bi Require Import big_op fixpoint.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.program_logic Require Export total_weakestpre adequacy.\nFrom iris.prelude Require Import options.\nImport uPred.\n\nSection adequacy.\nContext `{!irisGS_gen HasNoLc Λ Σ}.\nImplicit Types e : expr Λ.\n\nDefinition twptp_pre (twptp : list (expr Λ) → iProp Σ)\n    (t1 : list (expr Λ)) : iProp Σ :=\n  ∀ t2 σ1 ns κ κs σ2 nt, ⌜step (t1,σ1) κ (t2,σ2)⌝ -∗\n    state_interp σ1 ns κs nt ={⊤}=∗\n              ∃ nt', ⌜κ = []⌝ ∗ state_interp σ2 (S ns) κs nt' ∗ twptp t2.\n\nLemma twptp_pre_mono (twptp1 twptp2 : list (expr Λ) → iProp Σ) :\n  □ (∀ t, twptp1 t -∗ twptp2 t) -∗\n  ∀ t, twptp_pre twptp1 t -∗ twptp_pre twptp2 t.\nProof.\n  iIntros \"#H\"; iIntros (t) \"Hwp\". rewrite /twptp_pre.\n  iIntros (t2 σ1 ns κ κs σ2 nt1) \"Hstep Hσ\".\n  iMod (\"Hwp\" with \"[$] [$]\") as (n2) \"($ & Hσ & ?)\".\n  iModIntro. iExists n2. iFrame \"Hσ\". by iApply \"H\".\nQed.\n\nLocal Instance twptp_pre_mono' : BiMonoPred twptp_pre.\nProof.\n  constructor; first (intros ????; apply twptp_pre_mono).\n  intros wp Hwp n t1 t2 ?%(discrete_iff _ _)%leibniz_equiv; solve_proper.\nQed.\n\nDefinition twptp (t : list (expr Λ)) : iProp Σ :=\n  bi_least_fixpoint twptp_pre t.\n\nLemma twptp_unfold t : twptp t ⊣⊢ twptp_pre twptp t.\nProof. by rewrite /twptp least_fixpoint_unfold. Qed.\n\nLemma twptp_ind Ψ :\n  ⊢ (□ ∀ t, twptp_pre (λ t, Ψ t ∧ twptp t) t -∗ Ψ t) → ∀ t, twptp t -∗ Ψ t.\nProof.\n  iIntros \"#IH\" (t) \"H\".\n  assert (NonExpansive Ψ).\n  { by intros n ?? ->%(discrete_iff _ _)%leibniz_equiv. }\n  iApply (least_fixpoint_ind _ Ψ with \"[] H\").\n  iIntros \"!>\" (t') \"H\". by iApply \"IH\".\nQed.\n\nLocal Instance twptp_Permutation : Proper ((≡ₚ) ==> (⊢)) twptp.\nProof.\n  iIntros (t1 t1' Ht) \"Ht1\". iRevert (t1' Ht); iRevert (t1) \"Ht1\".\n  iApply twptp_ind; iIntros \"!>\" (t1) \"IH\"; iIntros (t1' Ht).\n  rewrite twptp_unfold /twptp_pre. iIntros (t2 σ1 ns κ κs σ2 nt Hstep) \"Hσ\".\n  destruct (step_Permutation t1' t1 t2 κ σ1 σ2) as (t2'&?&?); [done..|].\n  iMod (\"IH\" $! t2' with \"[% //] Hσ\") as (n2) \"($ & Hσ & IH & _)\".\n  iModIntro. iExists n2. iFrame \"Hσ\". by iApply \"IH\".\nQed.\n\nLemma twptp_app t1 t2 : twptp t1 -∗ twptp t2 -∗ twptp (t1 ++ t2).\nProof.\n  iIntros \"H1\". iRevert (t2). iRevert (t1) \"H1\".\n  iApply twptp_ind; iIntros \"!>\" (t1) \"IH1\". iIntros (t2) \"H2\".\n  iRevert (t1) \"IH1\"; iRevert (t2) \"H2\".\n  iApply twptp_ind; iIntros \"!>\" (t2) \"IH2\". iIntros (t1) \"IH1\".\n  rewrite twptp_unfold /twptp_pre. iIntros (t1'' σ1 ns κ κs σ2 nt Hstep) \"Hσ1\".\n  destruct Hstep as [e1 σ1' e2 σ2' efs' t1' t2' [=Ht ?] ? Hstep]; simplify_eq/=.\n  apply app_eq_inv in Ht as [(t&?&?)|(t&?&?)]; subst.\n  - destruct t as [|e1' ?]; simplify_eq/=.\n    + iMod (\"IH2\" with \"[%] Hσ1\") as (n2) \"($ & Hσ & IH2 & _)\".\n      { by eapply (step_atomic _ _ _ _ _ []). }\n      iModIntro. iExists n2. iFrame \"Hσ\".\n      rewrite -{2}(left_id_L [] (++) (e2 :: _)). iApply \"IH2\".\n      by setoid_rewrite (right_id_L [] (++)).\n    + iMod (\"IH1\" with \"[%] Hσ1\") as (n2) \"($ & Hσ & IH1 & _)\"; first by econstructor.\n      iAssert (twptp t2) with \"[IH2]\" as \"Ht2\".\n      { rewrite twptp_unfold. iApply (twptp_pre_mono with \"[] IH2\").\n        iIntros \"!> * [_ ?] //\". }\n      iModIntro. iExists n2. iFrame \"Hσ\".\n      rewrite -assoc_L (comm _ t2) !cons_middle !assoc_L. by iApply \"IH1\".\n  - iMod (\"IH2\" with \"[%] Hσ1\") as (n2) \"($ & Hσ & IH2 & _)\"; first by econstructor.\n    iModIntro. iExists n2. iFrame \"Hσ\". rewrite -assoc_L. by iApply \"IH2\".\nQed.\n\nLemma twp_twptp s Φ e : WP e @ s; ⊤ [{ Φ }] -∗ twptp [e].\nProof.\n  iIntros \"He\". remember (⊤ : coPset) as E eqn:HE.\n  iRevert (HE). iRevert (e E Φ) \"He\". iApply twp_ind.\n  iIntros \"!>\" (e E Φ); iIntros \"IH\" (->).\n  rewrite twptp_unfold /twptp_pre /twp_pre.\n  iIntros (t1' σ1' ns κ κs σ2' nt Hstep) \"Hσ1\".\n  destruct Hstep as [e1 σ1 e2 σ2 efs [|? t1] t2 ?? Hstep];\n    simplify_eq/=; try discriminate_list.\n  destruct (to_val e1) as [v|] eqn:He1.\n  { apply val_stuck in Hstep; naive_solver. }\n  iMod (\"IH\" with \"Hσ1\") as \"[_ IH]\".\n  iMod (\"IH\" with \"[% //]\") as \"($ & Hσ & [IH _] & IHfork)\".\n  iModIntro. iExists (length efs + nt). iFrame \"Hσ\".\n  iApply (twptp_app [_] with \"(IH [//])\").\n  clear. iInduction efs as [|e efs] \"IH\"; simpl.\n  { rewrite twptp_unfold /twptp_pre. iIntros (t2 σ1 ns κ κs σ2 nt1 Hstep).\n    destruct Hstep; simplify_eq/=; discriminate_list. }\n  iDestruct \"IHfork\" as \"[[IH' _] IHfork]\".\n  iApply (twptp_app [_] with \"(IH' [//])\"). by iApply \"IH\".\nQed.\n\nLemma twptp_total σ ns nt t :\n  state_interp σ ns [] nt -∗ twptp t ={⊤}=∗ ▷ ⌜sn erased_step (t, σ)⌝.\nProof.\n  iIntros \"Hσ Ht\". iRevert (σ ns nt) \"Hσ\". iRevert (t) \"Ht\".\n  iApply twptp_ind; iIntros \"!>\" (t) \"IH\"; iIntros (σ ns nt) \"Hσ\".\n  iApply (pure_mono _ _ (Acc_intro _)). iIntros ([t' σ'] [κ Hstep]).\n  rewrite /twptp_pre.\n  iMod (\"IH\" with \"[% //] Hσ\") as (n' ->) \"[Hσ [H _]]\".\n  by iApply \"H\".\nQed.\nEnd adequacy.\n\nTheorem twp_total Σ Λ `{!invGpreS Σ} s e σ Φ n :\n  (∀ `{Hinv : !invGS_gen HasNoLc Σ},\n     ⊢ |={⊤}=> ∃\n         (stateI : state Λ → nat → list (observation Λ) → nat → iProp Σ)\n         (** We abstract over any instance of [irisG], and thus any value of\n             the field [num_laters_per_step]. This is needed because instances\n             of [irisG] (e.g., the one of HeapLang) are shared between WP and\n             TWP, where TWP simply ignores [num_laters_per_step]. *)\n         (num_laters_per_step : nat → nat)\n         (fork_post : val Λ → iProp Σ)\n         state_interp_mono,\n       let _ : irisGS_gen HasNoLc Λ Σ :=\n           IrisG Hinv stateI fork_post num_laters_per_step state_interp_mono\n       in\n       stateI σ n [] 0 ∗ WP e @ s; ⊤ [{ Φ }]) →\n  sn erased_step ([e], σ). (* i.e. ([e], σ) is strongly normalizing *)\nProof.\n  intros Hwp. eapply pure_soundness. apply (laterN_soundness _  1); simpl.\n  apply (fupd_soundness_no_lc ⊤ ⊤ _ 0)=> Hinv. iIntros \"_\".\n  iMod (Hwp) as (stateI num_laters_per_step fork_post stateI_mono) \"[Hσ H]\".\n  set (iG := IrisG Hinv stateI fork_post num_laters_per_step stateI_mono).\n  iApply (@twptp_total _ _ iG _ n with \"Hσ\").\n  by iApply (@twp_twptp _ _ (IrisG Hinv _ fork_post _ _)).\nQed.\n", "meta": {"author": "amintimany", "repo": "iris", "sha": "03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1", "save_path": "github-repos/coq/amintimany-iris", "path": "github-repos/coq/amintimany-iris/iris-03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1/iris/program_logic/total_adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.24902597501361748}}
{"text": "(** The Rtac tactic that is used to invoke the rewriter\n **)\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.HList.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.Util.Compat.\nRequire Import MirrorCore.RTac.Core.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.Lambda.Rewrite.Core.\nRequire Import MirrorCore.Lambda.Rewrite.BottomUp.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSet Suggest Proof Using.\n\nSection setoid.\n  Context {typ : Set}.\n  Context {func : Set}.\n  Context {RType_typD : RType typ}.\n  Context {Typ2_Fun : Typ2 RType_typD RFun}.\n  Context {RSym_func : RSym func}.\n\n  (** Reasoning principles **)\n  Context {RTypeOk_typD : RTypeOk}.\n  Context {Typ2Ok_Fun : Typ2Ok Typ2_Fun}.\n  Context {RSymOk_func : RSymOk RSym_func}.\n  Context {Typ0_Prop : Typ0 _ Prop}.\n\n  (** TODO(gmalecha): This is not necessary *)\n  Context {RelDec_eq_typ : RelDec (@eq typ)}.\n  Context {RelDec_Correct_eq_typ : RelDec_Correct RelDec_eq_typ}.\n\n  (* TODO(gmalecha): Wrap all of this up in a type class?\n   * Why should it be different than Expr?\n   *)\n  Variable Rbase : Set.\n  Variable Rbase_eq : Rbase -> Rbase -> bool.\n  Hypothesis Rbase_eq_ok : forall a b, Rbase_eq a b = true -> a = b.\n\n  Local Notation \"'R'\" := (R typ Rbase).\n\n  Variable RbaseD : Rbase -> forall t : typ, option (typD t -> typD t -> Prop).\n\n  Hypothesis RbaseD_single_type\n  : forall r t1 t2 rD1 rD2,\n      RbaseD r t1 = Some rD1 ->\n      RbaseD r t2 = Some rD2 ->\n      t1 = t2.\n\n  Local Existing Instance Subst_ctx_subst.\n  Local Existing Instance SubstOk_ctx_subst.\n  Local Existing Instance SubstUpdate_ctx_subst.\n  Local Existing Instance SubstUpdateOk_ctx_subst.\n  Local Existing Instance Expr_expr.\n  Local Existing Instance ExprOk_expr.\n\n  Definition auto_setoid_rewrite_bu\n             (r : R)\n             (reflexive : refl_dec R)\n             (transitive : trans_dec R)\n             (rewriter : RwAction typ func Rbase)\n             (respectful : ResolveProper typ func Rbase)\n  : rtac typ (expr typ func) :=\n    let rw := bottom_up reflexive transitive rewriter respectful in\n    fun ctx cs g =>\n      match @rw g r nil ctx cs with\n      | None => Fail\n      | Some (Progress g', cs') => More_ cs' (GGoal g')\n      | Some (NoProgress, cs') => Fail\n      end.\n\n  Variable R_impl : R.\n\n  Hypothesis R_impl_is_impl\n    : RD RbaseD R_impl (typ0 (F:=Prop)) =\n      Some match eq_sym (typ0_cast (F:=Prop)) in _ = t return t -> t -> Prop with\n           | eq_refl => Basics.impl\n           end.\n\n  Theorem auto_setoid_rewrite_bu_sound\n  : forall is_refl is_trans rw proper\n           (His_reflOk : refl_dec_ok (RD RbaseD) is_refl)\n           (His_transOk : trans_dec_ok (RD RbaseD) is_trans),\n      setoid_rewrite_spec RbaseD rw ->\n      respectful_spec RbaseD  proper ->\n      rtac_sound (auto_setoid_rewrite_bu (Rflip R_impl)\n                                         is_refl is_trans rw proper).\n  Proof using RSymOk_func RTypeOk_typD R_impl_is_impl\n        RbaseD_single_type Typ2Ok_Fun.\n    intros. unfold auto_setoid_rewrite_bu. red.\n    intros.\n    generalize (@bottom_up_sound _ _ _ _ _ _ _ _ _ _ _\n                                 RbaseD_single_type is_refl is_trans rw proper\n                                 His_reflOk His_transOk H H0 g (Rflip R_impl) ctx s nil).\n    simpl.\n    destruct (bottom_up is_refl is_trans rw proper g (Rflip R_impl) nil s).\n    { destruct p. destruct p; subst; eauto using rtac_spec_Fail.\n      red. intros Hbus ? ?.\n      specialize (Hbus _ _ eq_refl H2).\n      forward_reason.\n      split; try assumption.\n      split; [ constructor | ].\n      specialize (H4 (typ0 (F:=Prop))).\n      rewrite R_impl_is_impl in H4.\n      specialize (H4 _ eq_refl).\n      revert H4.\n      destruct (pctxD s) eqn:HpctxDs; try (clear; tauto).\n      simpl. unfold propD. unfold exprD_typ0.\n      simpl.\n      destruct (lambda_exprD (getUVars ctx) (getVars ctx) (typ0 (F:=Prop)) g);\n        try solve [ tauto ].\n      destruct (pctxD c) eqn:HpctxDc; try solve [ tauto ].\n      destruct (lambda_exprD (getUVars ctx) (getVars ctx) (typ0 (F:=Prop)) new_val);\n        try solve [ tauto ].\n      destruct 1; split; try assumption.\n      intros.\n      gather_facts.\n      eapply Pure_pctxD; eauto.\n      intros.\n      specialize (H5 Hnil). simpl in *.\n      revert H6 H5. autorewrite_with_eq_rw.\n      clear. generalize (typ0_cast (F:=Prop)).\n      generalize dependent (typD (typ0 (F:=Prop))).\n      do 4 intro. subst. simpl.\n      unfold flip, Basics.impl. tauto. }\n    { subst. intro. clear.\n      eapply rtac_spec_Fail. }\n  Qed.\n\nEnd setoid.\n", "meta": {"author": "gmalecha", "repo": "mirror-core", "sha": "b962fbca15b0b5a4653f66d29d7115bb04ebd4f3", "save_path": "github-repos/coq/gmalecha-mirror-core", "path": "github-repos/coq/gmalecha-mirror-core/mirror-core-b962fbca15b0b5a4653f66d29d7115bb04ebd4f3/theories/Lambda/Rewrite/Tactic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.24902597501361748}}
{"text": "Require Import Verdi.Verdi.\nRequire Import Verdi.DynamicNetLemmas.\nRequire Import Verdi.TotalMapSimulations.\nRequire Import Verdi.PartialMapSimulations.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import FunctionalExtensionality.\nRequire Import Sumbool.\nRequire Import Sorting.Permutation.\n\nRequire Import Verdi.Ssrexport.\n\nSet Implicit Arguments.\n\nClass MultiParamsPartialExtendedMap\n (B0 : BaseParams) (B1 : BaseParams) \n (P0 : MultiParams B0) (P1 : MultiParams B1) :=\n{\n  pt_ext_map_data : @data B0 -> @name B0 P0 -> @data B1 ;\n  pt_ext_map_input : @input B0 -> @name B0 P0 -> @data B0 -> option (@input B1) \n}.\n\nSection PartialExtendedMapDefs.\n\nContext {base_fst : BaseParams}.\nContext {base_snd : BaseParams}.\nContext {multi_fst : MultiParams base_fst}.\nContext {multi_snd : MultiParams base_snd}.\nContext {name_map : MultiParamsNameTotalMap multi_fst multi_snd}.\nContext {msg_map : MultiParamsMsgPartialMap multi_fst multi_snd}.\nContext {multi_map : MultiParamsPartialExtendedMap multi_fst multi_snd}.\n\nDefinition pt_ext_mapped_net_handlers me src m st :=\n  let '(_, st', ps) := net_handlers me src m st in\n  (pt_ext_map_data st' me, filterMap (pt_map_name_msg (name_map := name_map) (msg_map := msg_map)) ps).\n\nDefinition pt_ext_mapped_input_handlers me inp st :=\n  let '(_, st', ps) := input_handlers me inp st in\n  (pt_ext_map_data st' me, filterMap (pt_map_name_msg (name_map := name_map) (msg_map := msg_map)) ps).\n\nEnd PartialExtendedMapDefs.\n\nClass MultiParamsPartialExtendedMapCongruency\n  (B0 : BaseParams) (B1 : BaseParams)\n  (P0 : MultiParams B0) (P1 : MultiParams B1)\n  (N : MultiParamsNameTotalMap P0 P1)\n  (P : MultiParamsMsgPartialMap P0 P1)\n  (P : MultiParamsPartialExtendedMap P0 P1) : Prop :=\n  {\n    pt_ext_init_handlers_eq : forall n,\n      pt_ext_map_data (init_handlers n) n = init_handlers (tot_map_name n) ;\n    pt_ext_net_handlers_some : forall me src m st m' out st' ps,\n      pt_map_msg m = Some m' ->\n      net_handlers (tot_map_name me) (tot_map_name src) m' (pt_ext_map_data st me) = (out, st', ps) ->\n      pt_ext_mapped_net_handlers me src m st = (st', ps) ;\n    pt_ext_net_handlers_none : forall me src m st out st' ps,\n      pt_map_msg m = None ->\n      net_handlers me src m st = (out, st', ps) ->\n      pt_ext_map_data st' me = pt_ext_map_data st me /\\ filterMap pt_map_name_msg ps = [] ;\n    pt_ext_input_handlers_some : forall me inp st inp' out st' ps,\n      pt_ext_map_input inp me st = Some inp' ->\n      input_handlers (tot_map_name me) inp' (pt_ext_map_data st me) = (out, st', ps) ->\n      pt_ext_mapped_input_handlers me inp st = (st', ps) ;\n    pt_ext_input_handlers_none : forall me inp st out st' ps,\n      pt_ext_map_input inp me st = None ->\n      input_handlers me inp st = (out, st', ps) ->\n      pt_ext_map_data st' me = pt_ext_map_data st me /\\ filterMap pt_map_name_msg ps = []\n  }.\n\nClass FailureParamsPartialExtendedMapCongruency\n  (B0 : BaseParams) (B1 : BaseParams)\n  (P0 : MultiParams B0) (P1 : MultiParams B1)\n  (F0 : FailureParams P0) (F1 : FailureParams P1)\n  (P : MultiParamsPartialExtendedMap P0 P1) : Prop :=\n  {\n    pt_ext_reboot_eq : forall d me,\n      pt_ext_map_data (reboot d) me = reboot (pt_ext_map_data d me)\n  }.\n\nSection PartialExtendedMapSimulations.\n\nContext {base_fst : BaseParams}.\nContext {base_snd : BaseParams}.\nContext {multi_fst : MultiParams base_fst}.\nContext {multi_snd : MultiParams base_snd}.\nContext {name_map : MultiParamsNameTotalMap multi_fst multi_snd}.\nContext {msg_map : MultiParamsMsgPartialMap multi_fst multi_snd}.\nContext {multi_map : MultiParamsPartialExtendedMap multi_fst multi_snd}.\nContext {name_map_bijective : MultiParamsNameTotalMapBijective name_map}.\nContext {multi_map_congr : MultiParamsPartialExtendedMapCongruency name_map msg_map multi_map}.\n\nLemma pt_ext_init_handlers_fun_eq : \n  init_handlers = fun n : name => pt_ext_map_data (init_handlers (tot_map_name_inv n)) (tot_map_name_inv n).\nProof using name_map_bijective multi_map_congr msg_map.\napply functional_extensionality => n.\nhave H_eq := pt_ext_init_handlers_eq.\nrewrite H_eq {H_eq}.\nby rewrite tot_map_name_inverse_inv.\nQed.\n\nDefinition pt_ext_map_net (net : @network  _ multi_fst) : @network _ multi_snd :=\n  {| nwPackets := filterMap pt_map_packet net.(nwPackets) ;\n     nwState := fun n => pt_ext_map_data (net.(nwState) (tot_map_name_inv n)) (tot_map_name_inv n) |}.\n\nLemma pt_ext_map_update_eq :\nforall f h d,\n  (fun n : name => pt_ext_map_data (update name_eq_dec f h d (tot_map_name_inv n)) (tot_map_name_inv n)) =\n  update name_eq_dec (fun n : name => pt_ext_map_data (f (tot_map_name_inv n)) (tot_map_name_inv n)) (tot_map_name h) (pt_ext_map_data d h).\nProof using name_map_bijective.\nmove => f h d.\napply functional_extensionality => n.\nrewrite /update /=.\ncase (name_eq_dec _ _) => H_dec; case (name_eq_dec _ _) => H_dec' //.\n- rewrite -H_dec in H_dec'.\n  by rewrite H_dec.\n- case: H_dec'.\n  rewrite -H_dec.\n  by rewrite tot_map_name_inverse_inv.\n- rewrite H_dec' in H_dec.\n  by rewrite tot_map_name_inv_inverse in H_dec.\nQed.\n\nLemma pt_ext_map_update_eq_some :\n  forall net d p p',\n    pt_map_packet p = Some p' ->\n    (fun n : name => pt_ext_map_data (update name_eq_dec (nwState net) (pDst p) d (tot_map_name_inv n)) (tot_map_name_inv n)) =\n    update name_eq_dec (fun n : name => pt_ext_map_data (nwState net (tot_map_name_inv n)) (tot_map_name_inv n)) (pDst p') (pt_ext_map_data d (pDst p)).\nProof using name_map_bijective.\nmove => net d p p'.\ncase: p => src dst m.\ncase: p' => src' dst' m' /=.\ncase H_eq: (pt_map_msg _) => [m0|] // H_eq'.\ninversion H_eq'; subst.\nmove {H_eq H_eq'}.\nexact: pt_ext_map_update_eq.\nQed.\n\nTheorem step_async_pt_ext_mapped_simulation_1 :\n  forall net net' tr,\n    @step_async _ multi_fst net net' tr ->\n    (exists tr, @step_async _ multi_snd (pt_ext_map_net net) (pt_ext_map_net net') tr) \\/ pt_ext_map_net net' = pt_ext_map_net net.\nProof using name_map_bijective multi_map_congr.\nmove => net net' tr.\ncase => {net net' tr}.\n- move => net net' p ms ms' out d l H_eq H_hnd H_eq'.\n  destruct (pt_map_packet p) eqn:?.\n    left.\n    rewrite H_eq' /= /pt_ext_map_net /=.\n    have H_eq_dst: tot_map_name (pDst p) = pDst p0.\n      case: p H_eq H_hnd H_eq' Heqo => /= src dst m H_eq H_hnd H_eq'.\n      case (pt_map_msg m) => //= m' H_m.\n      by inversion H_m.\n    destruct (net_handlers (pDst p0) (pSrc p0) (pBody p0) (pt_ext_map_data (nwState net (pDst p)) (pDst p))) eqn:?.\n    destruct p1 as [out' d'].\n    exists [(pDst p0, inr out')].\n    apply @StepAsync_deliver with (xs := filterMap pt_map_packet ms) (ys := filterMap pt_map_packet ms') (d := pt_ext_map_data d (pDst p)) (l := filterMap pt_map_name_msg l).\n    * rewrite /= H_eq filterMap_app /=.\n      case H_p: (pt_map_packet _) => [p1|]; last by rewrite H_p in Heqo.\n      by rewrite H_p in Heqo; injection Heqo => H_eq_p; rewrite H_eq_p.\n    * rewrite /=.\n      rewrite -{2}H_eq_dst tot_map_name_inv_inverse.\n      case: p H_eq H_hnd H_eq' Heqo H_eq_dst Heqp1 => /= src dst mg H_eq H_hnd H_eq'.\n      case H_m: (pt_map_msg mg) => [mg'|] //.\n      case: p0 H_eq' => src' dst' m0 H_eq' H_eq_p.\n      inversion H_eq_p; subst.\n      move => H_eq_dst H_eq_n {H_eq_p H_eq_dst}.\n      simpl in *.\n      have H_q := @pt_ext_net_handlers_some _ _ _ _ _ _ _ multi_map_congr dst src mg (nwState net dst) _ _ _ _ H_m H_eq_n.\n      rewrite /pt_ext_mapped_net_handlers in H_q.\n      rewrite H_hnd in H_q.\n      find_inversion.\n      by rewrite tot_map_name_inv_inverse.\n    * rewrite /= /pt_ext_map_net /= 2!filterMap_app.\n      rewrite (filterMap_pt_map_packet_map_eq_some _ _ Heqo).\n      by rewrite (pt_ext_map_update_eq_some _ _ _ Heqo).\n  right.\n  rewrite H_eq' /= {H_eq'}.\n  rewrite /pt_ext_map_net /=.\n  case: p H_eq H_hnd Heqo => /= src dst m H_eq H_hnd.\n  case H_m: (pt_map_msg _) => [m'|] // H_eq' {H_eq'}.\n  rewrite 2!filterMap_app H_eq filterMap_app /=.\n  case H_m': (pt_map_msg _) => [m'|]; first by rewrite H_m' in H_m.\n  have [H_d H_l] := pt_ext_net_handlers_none _ _ _ _ H_m H_hnd.\n  rewrite (filterMap_pt_map_name_msg_empty_eq _ dst H_l) /=.\n  set nwS1 := fun _ => _.\n  set nwS2 := fun _ => _.\n  have H_eq_s: nwS1 = nwS2.\n    rewrite /nwS1 /nwS2 /=.\n    apply functional_extensionality => n.\n    rewrite /update /=.\n      case name_eq_dec => H_dec //.\n      by rewrite H_dec H_d.\n    by rewrite H_eq_s.\n- move => h net net' out inp d l H_hnd H_eq.  \n  destruct (pt_ext_map_input inp h (nwState net h)) eqn:?.\n    left.\n    destruct (input_handlers (tot_map_name h) i (pt_ext_map_data (nwState net h) h)) eqn:?.\n    destruct p  as [out' d'].\n    exists [(tot_map_name h, inl i); (tot_map_name h, inr out')].\n    apply (@StepAsync_input _ _ _ _ _ _ _ (pt_ext_map_data d h) (filterMap pt_map_name_msg l)).\n      rewrite /=.\n      have H_q := @pt_ext_input_handlers_some _ _ _ _ _ _ _ multi_map_congr h inp (nwState net h) _ _ _ _ Heqo Heqp.\n      rewrite /pt_ext_mapped_input_handlers /= in H_q.\n      rewrite H_hnd in H_q.\n      find_inversion.\n      by rewrite tot_map_name_inv_inverse.\n    rewrite /= H_eq /= /pt_ext_map_net /= filterMap_app filterMap_pt_map_packet_map_eq.\n    by rewrite -pt_ext_map_update_eq.\n  right.\n  rewrite H_eq /pt_ext_map_net /=.\n  have [H_d H_l] := pt_ext_input_handlers_none _ _ _ Heqo H_hnd.\n  rewrite filterMap_app.\n  rewrite (filterMap_pt_map_name_msg_empty_eq _ h H_l) /=.\n  set nwS1 := fun _ => _.\n  set nwS2 := fun _ => _.\n  have H_eq_s: nwS1 = nwS2.\n      rewrite /nwS1 /nwS2 /=.\n      apply functional_extensionality => n.\n      rewrite /update /=.\n      case name_eq_dec => H_dec //.\n      by rewrite H_dec H_d.\n    by rewrite H_eq_s.\nQed.\n\nCorollary step_async_pt_ext_mapped_simulation_star_1 :\n  forall net tr,\n    @step_async_star _ multi_fst step_async_init net tr ->\n    exists tr', @step_async_star _ multi_snd step_async_init (pt_ext_map_net net) tr'.\nProof using name_map_bijective multi_map_congr.\nmove => net tr H_step.\nremember step_async_init as y in *.\nmove: Heqy.\ninduction H_step using refl_trans_1n_trace_n1_ind => H_init /=.\n  rewrite H_init.\n  rewrite /step_async_init /= /pt_ext_map_net /=.\n  rewrite pt_ext_init_handlers_fun_eq.\n  exists [].\n  exact: RT1nTBase.\nconcludes.\nrewrite H_init in H_step2 H_step1.\napply step_async_pt_ext_mapped_simulation_1 in H.\ncase: H => H.\n  move: IHH_step1 => [tr' H_star].\n  move: H => [tr'' H].\n  exists (tr' ++ tr'').\n  have H_trans := refl_trans_1n_trace_trans H_star.\n  apply: H_trans.\n  have ->: tr'' = tr'' ++ [] by rewrite -app_nil_end.\n  apply: (@RT1nTStep _ _ _ _ (pt_ext_map_net x'')) => //.\n  exact: RT1nTBase.\nmove: H => [H_eq H_eq'].\nmove: IHH_step1 => [tr' H_star].\nexists tr'.\nrewrite /pt_ext_map_net.\nby rewrite H_eq H_eq'.\nQed.\n\nDefinition pt_ext_map_onet (onet : @ordered_network _ multi_fst) : @ordered_network _ multi_snd :=\nmkONetwork (fun src dst => filterMap pt_map_msg (onet.(onwPackets) (tot_map_name_inv src) (tot_map_name_inv dst)))\n           (fun n => pt_ext_map_data (onet.(onwState) (tot_map_name_inv n)) (tot_map_name_inv n)).\n\nTheorem step_ordered_pt_ext_mapped_simulation_1 :\n  forall net net' tr,\n    @step_ordered _ multi_fst net net' tr ->\n    (exists tr', @step_ordered _ multi_snd (pt_ext_map_onet net) (pt_ext_map_onet net') tr') \\/ pt_ext_map_onet net' = pt_ext_map_onet net.\nProof using name_map_bijective multi_map_congr.\nmove => net net' tr.\ncase => {net net' tr}.\n- move => net net' tr m ms out d l from to H_eq H_hnd H_eq' H_eq_tr.\n  destruct (pt_map_msg m) eqn:?.\n    left.\n    destruct (net_handlers (tot_map_name to) (tot_map_name from) m0 (pt_ext_map_data (onwState net to) to)) eqn:?.\n    destruct p as [out' d'].\n    exists (map2fst (tot_map_name to) (map inr out')).\n    rewrite H_eq' /= /pt_ext_map_onet /=.\n    apply (@StepOrdered_deliver _ _ _ _ _ m0 (filterMap pt_map_msg ms) out' (pt_ext_map_data d to) (filterMap pt_map_name_msg l) (tot_map_name from) (tot_map_name to)) => //=.\n    * rewrite 2!tot_map_name_inv_inverse H_eq /=.\n      case H_m1: pt_map_msg => [m1|]; last by rewrite Heqo in H_m1.\n      rewrite H_m1 in Heqo.\n      by inversion Heqo.\n    * rewrite tot_map_name_inv_inverse.\n      have H_q := @pt_ext_net_handlers_some _ _ _ _ _ _ _ multi_map_congr _ _ _ _ _ _ _ _ Heqo Heqp.\n      rewrite /pt_ext_mapped_net_handlers /= in H_q.\n      by repeat break_let; repeat tuple_inversion.\n    * by rewrite /= pt_ext_map_update_eq collate_pt_map_update2_eq.\n  right.\n  have [H_eq_d H_ms] := pt_ext_net_handlers_none _ _ _ _ Heqo H_hnd.\n  rewrite H_eq' /pt_ext_map_onet /=.\n  rewrite pt_ext_map_update_eq /= H_eq_d.\n  rewrite collate_pt_map_eq H_ms /=.\n  set nwS1 := update _ _ _ _.\n  set nwS2 := fun n => pt_ext_map_data _ _.\n  set nwP1 := fun _ _ => _. \n  set nwP2 := fun _ _ => _. \n  have H_eq_s: nwS1 = nwS2.\n    rewrite /nwS1 /nwS2 {nwS1 nwS2}.\n    apply functional_extensionality => n.\n    rewrite /update /=.\n    case (name_eq_dec _ _) => H_dec //.\n    by rewrite H_dec tot_map_name_inv_inverse.\n  have H_eq_p: nwP1 = nwP2.\n    rewrite /nwP1 /nwP2 /=.\n    apply functional_extensionality => src.\n    apply functional_extensionality => dst.\n    rewrite /update2 /=.\n    case (sumbool_and _ _ _ _) => H_dec //.\n    move: H_dec => [H_eq_from H_eq_to].\n    rewrite -H_eq_from -H_eq_to H_eq /=.\n    case H_m': (pt_map_msg _) => [m'|] //.\n    by rewrite H_m' in Heqo.\n  by rewrite H_eq_s H_eq_p.\n- move => h net net' tr out inp d l H_hnd H_eq H_eq_tr.\n  destruct (pt_ext_map_input inp h (onwState net h)) eqn:?.\n    left.\n    destruct (input_handlers (tot_map_name h) i (pt_ext_map_data (onwState net h) h)) eqn:?.\n    destruct p as [out' d'].\n    exists ((tot_map_name h, inl i) :: map2fst (tot_map_name h) (map inr out')).\n    apply (@StepOrdered_input _ _ (tot_map_name h) _ _ _ out' i (pt_ext_map_data d h) (filterMap pt_map_name_msg l)) => //=; last by rewrite H_eq /pt_ext_map_onet /= pt_ext_map_update_eq collate_pt_map_eq.\n    have H_q := @pt_ext_input_handlers_some _ _ _ _ _ _ _ multi_map_congr h inp (onwState net h) _ _ _ _ Heqo Heqp.\n    rewrite /pt_ext_mapped_input_handlers /= in H_q.\n    rewrite tot_map_name_inv_inverse.\n    by repeat break_let; repeat tuple_inversion.\n  right.\n  rewrite /=.\n  have [H_d H_l] := pt_ext_input_handlers_none h inp (onwState net h) Heqo H_hnd.\n  rewrite H_eq /= /pt_ext_map_onet /=.\n  rewrite pt_ext_map_update_eq /= H_d.\n  rewrite collate_pt_map_eq H_l /=.\n  set nwS1 := update _ _ _ _.\n  set nwS2 := fun n => pt_ext_map_data _ _.\n  have H_eq_n: nwS1 = nwS2.\n    rewrite /nwS1 /nwS2 /=.\n    apply functional_extensionality => n.\n    rewrite /update /=.\n    case (name_eq_dec _ _) => H_dec //.\n    by rewrite H_dec tot_map_name_inv_inverse.\n  by rewrite H_eq_n.\nQed.\n\nCorollary step_ordered_pt_ext_mapped_simulation_star_1 :\n  forall net tr,\n    @step_ordered_star _ multi_fst step_ordered_init net tr ->\n    exists tr', @step_ordered_star _ multi_snd step_ordered_init (pt_ext_map_onet net) tr'.\nProof using name_map_bijective multi_map_congr.\nmove => net tr H_step.\nremember step_ordered_init as y in *.\nmove: Heqy.\ninduction H_step using refl_trans_1n_trace_n1_ind => H_init /=.\n  rewrite H_init.\n  rewrite /step_ordered_init /= /pt_ext_map_net /=.\n  rewrite pt_ext_init_handlers_fun_eq.\n  exists [].  \n  exact: RT1nTBase.\nconcludes.\nrewrite H_init in H_step2 H_step1.\napply step_ordered_pt_ext_mapped_simulation_1 in H.\ncase: H => H.\n  move: IHH_step1 => [tr' H_star].\n  move: H => [tr'' H].\n  exists (tr' ++ tr'').\n  have H_trans := refl_trans_1n_trace_trans H_star.\n  apply: H_trans.\n  have ->: tr'' = tr'' ++ [] by rewrite -app_nil_end.\n  apply: (@RT1nTStep _ _ _ _ (pt_ext_map_onet x'')) => //.\n  exact: RT1nTBase.\nmove: H => [H_eq H_eq'].\nmove: IHH_step1 => [tr' H_star].\nexists tr'.\nby rewrite /pt_ext_map_onet H_eq H_eq'.\nQed.\n\nContext {overlay_fst : NameOverlayParams multi_fst}.\nContext {overlay_snd : NameOverlayParams multi_snd}.\nContext {overlay_map_congr : NameOverlayParamsTotalMapCongruency overlay_fst overlay_snd name_map}.\n\nContext {fail_msg_fst : FailMsgParams multi_fst}.\nContext {fail_msg_snd : FailMsgParams multi_snd}.\nContext {fail_msg_map_congr : FailMsgParamsPartialMapCongruency fail_msg_fst fail_msg_snd msg_map}.\n\nTheorem step_ordered_failure_pt_ext_mapped_simulation_1 :\n  forall net net' failed failed' tr,\n    @step_ordered_failure _ _ overlay_fst fail_msg_fst (failed, net) (failed', net') tr ->\n    (exists tr', @step_ordered_failure _ _ overlay_snd fail_msg_snd (map tot_map_name failed, pt_ext_map_onet net) (map tot_map_name failed', pt_ext_map_onet net') tr') \\/ pt_ext_map_onet net' = pt_ext_map_onet net /\\ failed = failed'.\nProof using overlay_map_congr name_map_bijective multi_map_congr fail_msg_map_congr.\nmove => net net' failed failed' tr H_step.\ninvcs H_step.\n- destruct (pt_map_msg m) eqn:?.\n    left.\n    destruct (net_handlers (tot_map_name to) (tot_map_name from) m0 (pt_ext_map_data (onwState net to) to)) eqn:?.\n    destruct p as [out' d'].\n    exists (map2fst (tot_map_name to) (map inr out')).\n    rewrite /pt_ext_map_onet /=.\n    apply (@StepOrderedFailure_deliver _ _ _ _ _ _ _ _ m0 (filterMap pt_map_msg ms) out' (pt_ext_map_data d to) (filterMap pt_map_name_msg l) (tot_map_name from) (tot_map_name to)) => //=.\n    * rewrite 2!tot_map_name_inv_inverse /= H3 /=.\n      case H_m1: (pt_map_msg _) => [m1|]; last by rewrite Heqo in H_m1.\n      rewrite Heqo in H_m1.\n      by inversion H_m1.\n    * exact: not_in_failed_not_in.\n    * rewrite /= tot_map_name_inv_inverse.\n      have H_q := @pt_ext_net_handlers_some _ _ _ _ _ _ _ multi_map_congr _ _ _ _ _ _ _ _ Heqo Heqp.\n      rewrite /pt_ext_mapped_net_handlers /= in H_q.\n      by repeat break_let; repeat tuple_inversion.\n    * by rewrite /= pt_ext_map_update_eq collate_pt_map_update2_eq.\n  right.\n  split => //.\n  have [H_eq_d H_ms] := pt_ext_net_handlers_none _ _ _ _ Heqo H5.\n  rewrite /pt_ext_map_onet /= pt_ext_map_update_eq H_eq_d collate_pt_map_update2_eq H_ms /=.\n  set nwP1 := update2 _ _ _ _ _.\n  set nwS1 := update _ _ _ _.\n  set nwP2 := fun _ _ => _.\n  set nwS2 := fun _ => _.\n  have H_eq_s: nwS1 = nwS2.\n    rewrite /nwS1 /nwS2 {nwS1 nwS2}.\n    apply functional_extensionality => n.\n    rewrite /update /=.\n    case (name_eq_dec _ _) => H_dec //.\n    by rewrite H_dec tot_map_name_inv_inverse.\n  have H_eq_p: nwP1 = nwP2.\n    rewrite /nwP1 /nwP2 /=.\n    apply functional_extensionality => src.\n    apply functional_extensionality => dst.\n    rewrite /update2 /=.\n    case (sumbool_and _ _ _ _) => H_dec //.\n    move: H_dec => [H_eq_from H_eq_to].\n    rewrite -H_eq_from -H_eq_to /= 2!tot_map_name_inv_inverse H3 /=.\n    case H_m': (pt_map_msg _) => [m'|] //.\n    by rewrite H_m' in Heqo.\n  by rewrite H_eq_s H_eq_p.\n- destruct (pt_ext_map_input inp h (onwState net h)) eqn:?.\n    left.\n    destruct (input_handlers (tot_map_name h) i (pt_ext_map_data (onwState net h) h)) eqn:?.\n    destruct p as [out' d'].\n    exists ((tot_map_name h, inl i) :: map2fst (tot_map_name h) (map inr out')).\n    apply (@StepOrderedFailure_input _ _ _ _ (tot_map_name h) _ _ _ _ out' i (pt_ext_map_data d h) (filterMap pt_map_name_msg l)) => //=.\n    * exact: not_in_failed_not_in.\n    * rewrite /= tot_map_name_inv_inverse.\n      have H_q := @pt_ext_input_handlers_some _ _ _ _ _ _ _ multi_map_congr h inp (onwState net h) _ _ _ _ Heqo Heqp.\n      rewrite /pt_ext_mapped_input_handlers /= in H_q.\n      by repeat break_let; repeat tuple_inversion.\n    * by rewrite /pt_ext_map_onet /= pt_ext_map_update_eq collate_pt_map_eq.\n  right.\n  rewrite /= /pt_ext_map_onet /=.\n  have [H_d H_l] := pt_ext_input_handlers_none h inp (onwState net h) Heqo H4.\n  split => //.\n  rewrite pt_ext_map_update_eq /= H_d.\n  rewrite collate_pt_map_eq H_l /=.\n  set nwS1 := update _ _ _ _.\n  set nwS2 := fun n => pt_ext_map_data _ _.\n  have H_eq_n: nwS1 = nwS2.\n    rewrite /nwS1 /nwS2 /=.\n    apply functional_extensionality => n.\n    rewrite /update /=.\n    case (name_eq_dec _ _) => H_dec //.\n    by rewrite H_dec tot_map_name_inv_inverse.\n  by rewrite H_eq_n.\n- left.\n  rewrite /pt_ext_map_onet /=.  \n  set l := map2snd _ _.\n  have H_nd: NoDup (map (fun nm => fst nm) (filterMap pt_map_name_msg l)).\n    rewrite /pt_map_name_msg /=.\n    rewrite /l {l}.\n    apply NoDup_map_snd_fst.\n      apply (@nodup_pt_map _ _ _ _ _ _ _ msg_fail); first exact: in_map2snd_snd.\n      apply NoDup_map2snd.\n      apply NoDup_remove_all.\n      exact: no_dup_nodes.\n    move => nm nm' H_in H_in'.\n    by rewrite (pt_map_in_snd _ _ _ _ pt_fail_msg_fst_snd H_in) (pt_map_in_snd _ _ _ _ pt_fail_msg_fst_snd H_in').\n  exists [].\n  apply: StepOrderedFailure_fail => //.\n  * exact: not_in_failed_not_in.\n  * rewrite /=.\n    rewrite /l collate_pt_map_eq /pt_map_name_msg.\n    by rewrite (NoDup_Permutation_collate_eq _ _ _ _ _ _ _ H_nd (pt_map_map_pair_eq msg_fail h failed pt_fail_msg_fst_snd)).\nQed.\n\nCorollary step_ordered_failure_pt_ext_mapped_simulation_star_1 :\n  forall net failed tr,\n    @step_ordered_failure_star _ _ overlay_fst fail_msg_fst step_ordered_failure_init (failed, net) tr ->\n    exists tr', @step_ordered_failure_star _ _ overlay_snd fail_msg_snd step_ordered_failure_init (map tot_map_name failed, pt_ext_map_onet net) tr'.\nProof using overlay_map_congr name_map_bijective multi_map_congr fail_msg_map_congr.\nmove => net failed tr H_step.\nremember step_ordered_failure_init as y in *.\nhave H_eq_f: failed = fst (failed, net) by [].\nhave H_eq_n: net = snd (failed, net) by [].\nrewrite H_eq_f {H_eq_f}.\nrewrite {2}H_eq_n {H_eq_n}.\nmove: Heqy.\ninduction H_step using refl_trans_1n_trace_n1_ind => H_init /=.\n  rewrite H_init.\n  rewrite /step_ordered_failure_init /= /pt_ext_map_onet /=.\n  exists [].\n  rewrite -pt_ext_init_handlers_fun_eq.\n  exact: RT1nTBase.\nconcludes.\nrewrite H_init {H_init x} in H_step2 H_step1.\ncase: x' H IHH_step1 H_step1 => failed' net'.\ncase: x'' H_step2 => failed'' net''.\nrewrite /=.\nmove => H_step2 H IHH_step1 H_step1.\napply step_ordered_failure_pt_ext_mapped_simulation_1 in H.\ncase: H => H.\n  move: IHH_step1 => [tr' H_star].\n  move: H => [tr'' H].\n  exists (tr' ++ tr'').\n  have H_trans := refl_trans_1n_trace_trans H_star.\n  apply: H_trans.\n  have ->: tr'' = tr'' ++ [] by rewrite -app_nil_end.\n  apply: (@RT1nTStep _ _ _ _ (map tot_map_name failed'', pt_ext_map_onet net'')) => //.\n  exact: RT1nTBase.  \nmove: H => [H_eq_n H_eq_f].\nrewrite H_eq_n -H_eq_f.\nmove: IHH_step1 => [tr' H_star].\nby exists tr'.\nQed.\n\nContext {new_msg_fst : NewMsgParams multi_fst}.\nContext {new_msg_snd : NewMsgParams multi_snd}.\nContext {new_msg_map_congr : NewMsgParamsPartialMapCongruency new_msg_fst new_msg_snd msg_map}.\n\nDefinition pt_ext_map_odnet (net : @ordered_dynamic_network _ multi_fst) : @ordered_dynamic_network _ multi_snd :=\n{| odnwNodes := map tot_map_name net.(odnwNodes) ;\n   odnwPackets := fun src dst => filterMap pt_map_msg (net.(odnwPackets) (tot_map_name_inv src) (tot_map_name_inv dst)) ;\n   odnwState := fun n => match net.(odnwState) (tot_map_name_inv n) with\n                         | None => None\n                         | Some d => Some (pt_ext_map_data d (tot_map_name_inv n))\n                         end |}.\n\nTheorem step_ordered_dynamic_failure_pt_ext_mapped_simulation_1 :\n  forall net net' failed failed' tr,\n    NoDup (odnwNodes net) ->\n    @step_ordered_dynamic_failure _ _ overlay_fst new_msg_fst fail_msg_fst (failed, net) (failed', net') tr ->\n    (exists tr', @step_ordered_dynamic_failure _ _ overlay_snd new_msg_snd fail_msg_snd (map tot_map_name failed, pt_ext_map_odnet net) (map tot_map_name failed', pt_ext_map_odnet net') tr') \\/ (pt_ext_map_odnet net' = pt_ext_map_odnet net /\\ failed = failed').\nProof using overlay_map_congr new_msg_map_congr name_map_bijective multi_map_congr fail_msg_map_congr.\nmove => net net' failed failed' tr H_nd H_step.\ninvcs H_step.\n- left.\n  rewrite /pt_ext_map_odnet.\n  exists [].\n  apply (@StepOrderedDynamicFailure_start _ _ _ _ _ _ _ _ (tot_map_name h)) => /=; first exact: not_in_failed_not_in.\n  set p1 := fun _ _ => _.\n  set p2 := collate_ls _ _ _ _ _.\n  set s1 := fun _ => _.\n  set s2 := update _ _ _ _.\n  have H_eq_s: s1 = s2.\n    rewrite /s1 /s2 /update {s1 s2}.\n    apply functional_extensionality => n.\n    rewrite -pt_ext_init_handlers_eq.\n    break_match_goal.\n      break_if; break_if; try by congruence.\n      - by repeat find_rewrite; repeat find_rewrite_lem tot_map_name_inv_inverse.\n      - by find_reverse_rewrite; find_rewrite_lem tot_map_name_inverse_inv.\n      - by find_rewrite.\n    break_if; break_if; (try by congruence); last by find_rewrite.\n    by repeat find_rewrite; repeat find_rewrite_lem tot_map_name_inv_inverse.\n  rewrite H_eq_s /s2 {s1 s2 H_eq_s}.\n  have H_eq_p: p1 = p2.\n    rewrite /p1 /p2 {p1 p2}.\n    rewrite (collate_ls_pt_map_eq _ _ _ _ pt_new_msg_fst_snd) /=.\n    rewrite collate_pt_map_eq.\n    set f1 := fun _ _ => _.    \n    set c1 := collate _ _ _ _.\n    set c2 := collate _ _ _ _.\n    set f'1 := map tot_map_name _.\n    set f'2 := filter_rel _ (tot_map_name h) _.\n    have H_c: c1 = c2.\n      rewrite /c1 /c2 {c1 c2}.\n      apply: NoDup_Permutation_collate_eq; last first.\n        rewrite /pt_map_name_msg.\n        apply: pt_nodup_perm_map_map_pair_perm => //.\n        by rewrite pt_new_msg_fst_snd.\n      rewrite /pt_map_name_msg /=.\n      apply: NoDup_map_snd_fst => //.\n        apply (@nodup_pt_map _ _ _ _  _ _ _ msg_new); first exact: in_map2snd_snd.\n        apply: NoDup_map2snd.\n        exact: NoDup_remove_all.\n      move => nm nm' H_in H_in'.\n      apply (@pt_map_in_snd _ _ _ _ _ _ _ msg_new _ _ _ _ pt_new_msg_fst_snd) in H_in.\n      apply (@pt_map_in_snd _ _ _ _ _ _ _ msg_new _ _ _ _ pt_new_msg_fst_snd) in H_in'.\n      by rewrite H_in H_in'.\n    rewrite H_c {H_c}.\n    suff H_suff: f'1 = f'2 by rewrite H_suff.\n    rewrite /f'1 /f'2.\n    elim (odnwNodes net) => /=; first by rewrite 2!remove_all_nil.\n    move => n ns.\n    set mn := tot_map_name n.\n    set mns := map _ ns.\n    set mfailed' := map _ failed'.\n    move => IH.\n    have H_cn := remove_all_cons name_eq_dec failed' n ns.\n    have H_cn' := remove_all_cons name_eq_dec mfailed' mn mns.\n    unfold mn, mns, mfailed' in *.\n    repeat break_or_hyp; repeat break_and; repeat find_rewrite => //=.\n    * by find_apply_lem_hyp not_in_failed_not_in.\n    * by find_apply_lem_hyp in_failed_in.\n    * case adjacent_to_dec => H_dec; case adjacent_to_dec => H_dec' => //=.\n      + by rewrite IH.\n      + by find_apply_lem_hyp tot_adjacent_to_fst_snd.\n      + by find_apply_lem_hyp tot_adjacent_to_fst_snd.\n  by rewrite H_eq_p.\n- destruct (pt_map_msg m) eqn:?.\n    left.\n    destruct (net_handlers (tot_map_name to) (tot_map_name from) m0 (pt_ext_map_data d to)) eqn:?.\n    destruct p as [out' d''].\n    exists (map2fst (tot_map_name to) (map inr out')).\n    rewrite /pt_ext_map_onet /=.\n    apply (@StepOrderedDynamicFailure_deliver _ _ _ _ _ _ _ _ _ m0 (filterMap pt_map_msg ms) out' (pt_ext_map_data d to) (pt_ext_map_data d' to) (filterMap pt_map_name_msg l) (tot_map_name from) (tot_map_name to)) => //=.\n    * exact: not_in_failed_not_in.\n    * exact: in_failed_in.\n    * by rewrite /= tot_map_name_inv_inverse /= H5.\n    * rewrite /= 2!tot_map_name_inv_inverse /=.\n      find_rewrite.\n      by rewrite /= Heqo.\n    * have H_q := @pt_ext_net_handlers_some _ _ _ _ _ _ _ multi_map_congr _ _ _ _ _ _ _ _ Heqo Heqp.\n      rewrite /pt_ext_mapped_net_handlers /= in H_q.\n      by repeat break_let; repeat tuple_inversion.\n    * rewrite /= /pt_ext_map_odnet /=.\n      set u1 := fun _ => match _ with | _ => _ end.\n      set u2 := update _ _ _ _.\n      rewrite collate_pt_map_update2_eq.\n      suff H_suff: u1 = u2 by rewrite H_suff.\n      rewrite /u1 /u2 /update /=.\n      apply functional_extensionality => n.\n      repeat break_if; try by congruence.\n        rewrite -(tot_map_name_inverse_inv n) in n0.\n        by rewrite e in n0.\n      find_rewrite.\n      by find_rewrite_lem tot_map_name_inv_inverse.\n  right.\n  split => //.\n  have [H_eq_d H_ms] := pt_ext_net_handlers_none _ _ _ _ Heqo H7.\n  rewrite /pt_ext_map_odnet /= collate_pt_map_update2_eq H_ms /=.\n  set nwP1 := update2 _ _ _ _ _.\n  set nwS1 := fun _ => match _ with _ => _ end.\n  set nwP2 := fun _ _ => _.\n  set nwS2 := fun _ => _.\n  have H_eq_s: nwS1 = nwS2.\n    rewrite /nwS1 /nwS2 {nwS1 nwS2}.\n    apply functional_extensionality => n.\n    rewrite /update /=.\n    break_if => //.\n    find_rewrite.\n    rewrite H5.\n    by congruence.\n  have H_eq_p: nwP1 = nwP2.\n    rewrite /nwP1 /nwP2 /=.\n    apply functional_extensionality => src.\n    apply functional_extensionality => dst.\n    rewrite /update2 /=.\n    break_if => //.\n    break_and.\n    by rewrite -H -H0 2!tot_map_name_inv_inverse H6 /= Heqo.\n  by rewrite H_eq_s H_eq_p.\n- destruct (pt_ext_map_input inp h d) eqn:?.\n    left.\n    destruct (input_handlers (tot_map_name h) i (pt_ext_map_data d h)) eqn:?.\n    destruct p as [out' d''].\n    exists ((tot_map_name h, inl i) :: map2fst (tot_map_name h) (map inr out')).\n    apply (@StepOrderedDynamicFailure_input _ _ _ _ _ (tot_map_name h) _ _ _ _ out' i (pt_ext_map_data d h) (pt_ext_map_data d' h) (filterMap pt_map_name_msg l)) => //=.\n    * exact: not_in_failed_not_in.\n    * exact: in_failed_in. \n    * by rewrite /pt_ext_map_odnet /= tot_map_name_inv_inverse H5.\n    * have H_q := @pt_ext_input_handlers_some _ _ _ _ _ _ _ multi_map_congr h inp d _ _ _ _ Heqo Heqp.\n      rewrite /pt_ext_mapped_input_handlers /= in H_q.\n      find_rewrite.\n      by repeat tuple_inversion.\n    * rewrite /= /pt_ext_map_odnet /= collate_pt_map_eq.\n      set u1 := fun _ => match _ with | _ => _ end.\n      set u2 := update _ _ _ _.\n      suff H_suff: u1 = u2 by rewrite H_suff.\n      rewrite /u1 /u2 /update /=.\n      apply functional_extensionality => n.\n      repeat break_if; try by congruence.\n        rewrite -(tot_map_name_inverse_inv n) in n0.\n        by rewrite e in n0.\n      find_rewrite.\n      by find_rewrite_lem tot_map_name_inv_inverse.\n  right.\n  rewrite /= /pt_ext_map_odnet /=.\n  have [H_d H_l] := pt_ext_input_handlers_none h inp d Heqo H6.\n  split => //=.\n  rewrite collate_pt_map_eq H_l /=.\n  set nwS1 := fun n : name => match _ with | _ => _ end.\n  set nwS2 := fun n : name => match _ with | _ => _ end.\n  have H_eq_n: nwS1 = nwS2.\n    rewrite /nwS1 /nwS2 /=.\n    apply functional_extensionality => n.\n    rewrite /update /=.\n    break_if => //.\n    by repeat find_rewrite.\n  by rewrite H_eq_n.\n- left.\n  rewrite /pt_ext_map_odnet /=.\n  set l := map2snd _ _.\n  have H_nd': NoDup (map (fun nm => fst nm) (filterMap pt_map_name_msg l)).\n    rewrite /pt_map_name_msg /=.\n    rewrite /l {l}.\n    apply NoDup_map_snd_fst.\n      apply (@nodup_pt_map _ _ _ _ _  _ _ msg_fail); first exact: in_map2snd_snd.\n      apply NoDup_map2snd.\n      exact: NoDup_remove_all.\n    move => nm nm' H_in H_in'.\n    by rewrite (pt_map_in_snd  _ _ _ _ pt_fail_msg_fst_snd H_in) (pt_map_in_snd _ _ _ _ pt_fail_msg_fst_snd H_in').\n  exists [].\n  apply: StepOrderedDynamicFailure_fail => //.\n  * exact: not_in_failed_not_in.\n  * exact: in_failed_in.\n  * rewrite /=.\n    rewrite /l collate_pt_map_eq.\n    have H_pm := pt_nodup_perm_map_map_pair_perm _ h failed H_nd (Permutation_refl (map tot_map_name (odnwNodes net))) pt_fail_msg_fst_snd.\n    have H_pm' := H_pm _ _ _ _ name_map_bijective _ _ overlay_map_congr _ _ fail_msg_map_congr.\n    have H_eq := NoDup_Permutation_collate_eq _ _ _ _  _ _ _ H_nd' H_pm'.\n    by rewrite H_eq.\nQed.\n\nCorollary step_ordered_dynamic_failure_pt_ext_mapped_simulation_star_1 :\n  forall net failed tr,\n    @step_ordered_dynamic_failure_star _ _ overlay_fst new_msg_fst fail_msg_fst step_ordered_dynamic_failure_init (failed, net) tr ->\n    exists tr', @step_ordered_dynamic_failure_star _ _ overlay_snd new_msg_snd fail_msg_snd step_ordered_dynamic_failure_init (map tot_map_name failed, pt_ext_map_odnet net) tr'.\nProof using overlay_map_congr new_msg_map_congr name_map_bijective multi_map_congr fail_msg_map_congr.\nmove => net failed tr H_step.\nremember step_ordered_dynamic_failure_init as y in *.\nchange failed with (fst (failed, net)).\nchange net with (snd (failed, net)) at 2.\nmove: Heqy.\ninduction H_step using refl_trans_1n_trace_n1_ind => H_init /=.\n  rewrite H_init /step_ordered_dynamic_failure_init /= /step_ordered_failure_init.\n  exists [].\n  exact: RT1nTBase.\nconcludes.\nrewrite H_init {H_init x} in H_step2 H_step1.\ncase: x' H IHH_step1 H_step1 => failed' net'.\ncase: x'' H_step2 => failed'' net''.\nrewrite /=.\nmove => H_step2 H IHH_step1 H_step1.\nfind_apply_lem_hyp step_ordered_dynamic_failure_pt_ext_mapped_simulation_1; last by move: H_step1; apply: ordered_dynamic_nodes_no_dup.\ncase: H => H.\n  move: IHH_step1 => [tr' H_star].\n  move: H => [tr'' H].\n  exists (tr' ++ tr'').\n  have H_trans := refl_trans_1n_trace_trans H_star.\n  apply: H_trans.\n  have ->: tr'' = tr'' ++ [] by rewrite -app_nil_end.\n  apply: (@RT1nTStep _ _ _ _ (map tot_map_name failed'', pt_ext_map_odnet net'')) => //.\n  exact: RT1nTBase.  \nmove: H => [H_eq_n H_eq_f].\nrewrite H_eq_n -H_eq_f.\nmove: IHH_step1 => [tr' H_star].\nby exists tr'.\nQed.\n\nEnd PartialExtendedMapSimulations.\n", "meta": {"author": "uwplse", "repo": "verdi", "sha": "4f1f3ed37e372c05ce0249a93162d0f25e3e20c4", "save_path": "github-repos/coq/uwplse-verdi", "path": "github-repos/coq/uwplse-verdi/verdi-4f1f3ed37e372c05ce0249a93162d0f25e3e20c4/core/PartialExtendedMapSimulations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24901745751771548}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Facade.Facade.\n\nRequire Import Platform.Cito.StringMapFacts.\nRequire Import Coq.Lists.List.\nRequire Import Platform.Cito.ListFacts4.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Notation RunsTo := (@RunsTo ADTValue).\n  Notation State := (@State ADTValue).\n  Notation Env := (@Env ADTValue).\n  Notation Sca := (@SCA ADTValue).\n\n  Section Safe_coind.\n\n    Variable env : Env.\n\n    Variable R : Stmt -> State -> Prop.\n\n    Hypothesis SeqCase : forall a b st, R (Seq a b) st -> R a st /\\ forall st', RunsTo env a st st' -> R b st'.\n\n    Hypothesis IfCase : forall cond t f st, R (If cond t f) st -> (is_true st cond /\\ R t st) \\/ (is_false st cond /\\ R f st).\n\n    Hypothesis WhileCase : \n      forall cond body st, \n        let loop := While cond body in \n        R loop st -> \n        (is_true st cond /\\ R body st /\\ (forall st', RunsTo env body st st' -> R loop st')) \\/ \n        (is_false st cond).\n\n    Hypothesis AssignCase :\n      forall x e st,\n        R (Facade.Assign x e) st ->\n        not_mapsto_adt x st = true /\\\n        exists w, eval st e = Some (Sca w).\n\n    Hypothesis LabelCase : \n      forall x lbl st,\n        R (Label x lbl) st -> \n        not_mapsto_adt x st = true /\\\n        exists w, Label2Word env lbl = Some w.\n\n    Hypothesis CallCase : \n      forall x f args st,\n        R (Call x f args) st ->\n        NoDup args /\\\n        not_mapsto_adt x st = true /\\\n        exists f_w input, \n          eval st f = Some (Sca f_w) /\\\n          mapM (sel st) args = Some input /\\\n          ((exists spec,\n              Word2Spec env f_w = Some (Axiomatic spec) /\\\n              PreCond spec input) \\/\n           (exists spec,\n              Word2Spec env f_w = Some (Operational _ spec) /\\\n              length args = length (ArgVars spec) /\\\n              let callee_st := make_map (ArgVars spec) input in\n              R (Body spec) callee_st /\\\n              (forall callee_st',\n                 RunsTo env (Body spec) callee_st callee_st' ->\n                 sel callee_st' (RetVar spec) <> None /\\\n                 no_adt_leak input (ArgVars spec) (RetVar spec) callee_st'))).\n    \n    Hint Constructors Safe.\n\n    Require Import Platform.Cito.GeneralTactics.\n\n    Theorem Safe_coind : forall c st, R c st -> Safe env c st.\n      cofix; intros; destruct c.\n      - eauto.\n      - eapply SeqCase in H; openhyp; eapply SafeSeq; eauto.\n      - eapply IfCase in H; openhyp; eauto.\n      - eapply WhileCase in H; openhyp; eauto.\n      - eapply CallCase in H; openhyp; simpl in *; intuition eauto.\n      - eapply LabelCase in H; openhyp; eauto.\n      - eapply AssignCase in H; openhyp; eauto.\n    Qed.\n\n  End Safe_coind.\n  \nEnd ADTValue.", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Facade/SafeCoind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24901745751771548}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import CommonTheorems.\nRequire Import SpecLemmas.\n\nRequire Import AppendEntriesRequestsCameFromLeadersInterface.\nRequire Import OneLeaderLogPerTermInterface.\nRequire Import LeaderLogsTermSanityInterface.\nRequire Import OneLeaderPerTermInterface.\n\nRequire Import AppendEntriesLeaderInterface.\n\nSection AppendEntriesLeader.\n\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n\n  Context {aecfli : append_entries_came_from_leaders_interface}.\n  Context {ollpti : one_leaderLog_per_term_interface}.\n  Context {lltsi : leaderLogs_term_sanity_interface}.\n  Context {olpti : one_leader_per_term_interface}.\n\n  Ltac update_destruct :=\n    match goal with\n    | [ H : context [ update _ ?x _ ?y ] |- _ ] =>\n      destruct (name_eq_dec x y); subst; rewrite_update; simpl in *\n    | [ |- context [ update _ ?x _ ?y ] ] =>\n      destruct (name_eq_dec x y); subst; rewrite_update; simpl in *\n    end.\n\n  Lemma appendEntries_leader_init :\n    refined_raft_net_invariant_init appendEntries_leader.\n  Proof using. \n    unfold refined_raft_net_invariant_init, appendEntries_leader.\n    simpl. intuition.\n  Qed.\n\n  Definition type_term_log_monotonic st st' :=\n    type st' = Leader ->\n    type st = Leader /\\\n    currentTerm st' = currentTerm st /\\\n    (forall e, In e (log st) -> In e (log st')).\n\n  Notation appendEntries_leader_predicate ps st :=\n    (forall p t lid pli plt es lci e,\n      In p ps ->\n      pBody p = AppendEntries t lid pli plt es lci ->\n      In e es ->\n      currentTerm st = t ->\n      type st = Leader ->\n      In e (log st)).\n\n  Lemma appendEntries_leader_predicate_TTLM_preserved :\n    forall ps st st',\n      appendEntries_leader_predicate ps st ->\n      type_term_log_monotonic st st' ->\n      appendEntries_leader_predicate ps st'.\n  Proof using. \n    unfold type_term_log_monotonic.\n    intuition.\n    repeat find_rewrite.\n    eauto.\n  Qed.\n\n  Lemma handleClientRequest_TTLM :\n    forall h st client id c out st' l,\n      handleClientRequest h st client id c = (out, st', l) ->\n      type_term_log_monotonic st st'.\n  Proof using. \n    unfold type_term_log_monotonic.\n    intros.\n    find_copy_apply_lem_hyp handleClientRequest_type.\n    find_copy_apply_lem_hyp handleClientRequest_log.\n    intuition; try congruence.\n    break_exists.\n    intuition. subst. repeat find_rewrite. auto with *.\n  Qed.\n\n  Lemma appendEntries_leader_client_request :\n    refined_raft_net_invariant_client_request appendEntries_leader.\n  Proof using. \n    unfold refined_raft_net_invariant_client_request, appendEntries_leader.\n    simpl.\n    intros.\n    find_apply_hyp_hyp. intuition.\n    - repeat find_higher_order_rewrite.\n      update_destruct.\n      + eapply appendEntries_leader_predicate_TTLM_preserved; eauto using handleClientRequest_TTLM.\n        eauto.\n      + eauto.\n    - find_apply_lem_hyp handleClientRequest_packets.\n      subst. simpl in *. intuition.\n  Qed.\n\n  Lemma handleTimeout_TTLM :\n    forall h st out st' l,\n      handleTimeout h st = (out, st', l) ->\n      type_term_log_monotonic st st'.\n  Proof using. \n    unfold type_term_log_monotonic.\n    intros.\n    find_copy_apply_lem_hyp handleTimeout_type.\n    find_apply_lem_hyp handleTimeout_log_same.\n    intuition; try congruence.\n  Qed.\n\n  Lemma appendEntries_leader_timeout :\n    refined_raft_net_invariant_timeout appendEntries_leader.\n  Proof using. \n    unfold refined_raft_net_invariant_timeout, appendEntries_leader.\n    simpl.\n    intros.\n    find_apply_hyp_hyp.\n    intuition.\n    - repeat find_higher_order_rewrite.\n      update_destruct.\n      + eapply appendEntries_leader_predicate_TTLM_preserved; eauto using handleTimeout_TTLM.\n        eauto.\n      + eauto.\n    - do_in_map.\n      find_eapply_lem_hyp handleTimeout_packets; eauto.\n      subst. exfalso. eauto 10.\n  Qed.\n\n  Lemma handleAppendEntries_TTLM :\n    forall h st t n pli plt es ci st' ps,\n      handleAppendEntries h st t n pli plt es ci = (st', ps) ->\n      type_term_log_monotonic st st'.\n  Proof using. \n    unfold type_term_log_monotonic, handleAppendEntries.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto; try congruence.\n  Qed.\n\n  Lemma appendEntries_leader_append_entries :\n    refined_raft_net_invariant_append_entries appendEntries_leader.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries, appendEntries_leader.\n    simpl.\n    intros.\n    find_apply_hyp_hyp.\n    intuition.\n    - repeat find_higher_order_rewrite.\n      update_destruct.\n      + eapply appendEntries_leader_predicate_TTLM_preserved; eauto using handleAppendEntries_TTLM.\n        eauto.\n      + eauto.\n    - find_apply_lem_hyp handleAppendEntries_not_append_entries.\n      subst. exfalso. eauto 10.\n  Qed.\n\n  Lemma handleAppendEntriesReply_TTLM :\n    forall h st h' t es r st' ms,\n      handleAppendEntriesReply h st h' t es r = (st', ms) ->\n      type_term_log_monotonic st st'.\n  Proof using. \n    unfold type_term_log_monotonic, handleAppendEntriesReply, advanceCurrentTerm.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto; try congruence.\n  Qed.\n\n  Lemma appendEntries_leader_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply appendEntries_leader.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries_reply, appendEntries_leader.\n    simpl.\n    intros.\n    find_apply_hyp_hyp.\n    intuition.\n    - repeat find_higher_order_rewrite.\n      update_destruct.\n      + eapply appendEntries_leader_predicate_TTLM_preserved; eauto using handleAppendEntriesReply_TTLM.\n        eauto.\n      + eauto.\n    - find_apply_lem_hyp handleAppendEntriesReply_packets.\n      subst. simpl in *. intuition.\n  Qed.\n\n  Lemma handleRequestVote_TTLM :\n    forall st h h' t lli llt st' m,\n      handleRequestVote h st t h' lli llt = (st', m) ->\n      type_term_log_monotonic st st'.\n  Proof using. \n    unfold type_term_log_monotonic, handleRequestVote, advanceCurrentTerm.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto; try congruence.\n  Qed.\n\n  Lemma appendEntries_leader_request_vote :\n    refined_raft_net_invariant_request_vote appendEntries_leader.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote, appendEntries_leader.\n    simpl.\n    intros.\n    find_apply_hyp_hyp.\n    intuition.\n    - repeat find_higher_order_rewrite.\n      update_destruct.\n      + eapply appendEntries_leader_predicate_TTLM_preserved; eauto using handleRequestVote_TTLM.\n        eauto.\n      + eauto.\n    - find_apply_lem_hyp handleRequestVote_no_append_entries.\n      subst. exfalso. eauto 10.\n  Qed.\n\n(* p0 is AE.\n   by AE_came_from_leaders, there is a ll in pre state at (pSrc p0) for p0's term.\n   claim I am (pSrc p0).\n     I am ascending, so I have ll in post state.\n     pSrc p0 ll still is preserved into post state.\n     finish with one ll per term.\n   thus I had a leaderLog in the pre state.\n   this contradicts leaderLogs_currentTerm_sanity_candidate.\n*)\n\n  Lemma handleRequestVoteReply_spec' :\n    forall h st h' t r st',\n      handleRequestVoteReply h st h' t r = st' ->\n      type st' = Follower \\/\n      st' = st \\/\n      type st' = Candidate \\/\n      (type st' = Leader /\\\n       type st = Candidate /\\\n       log st' = log st /\\\n       r = true /\\\n       t = currentTerm st /\\\n       wonElection (dedup name_eq_dec (h' :: votesReceived st)) = true /\\\n       currentTerm st' = currentTerm st).\n  Proof using. \n    unfold handleRequestVoteReply.\n    intros.\n    repeat break_match; repeat find_inversion; do_bool; subst; simpl; intuition.\n  Qed.\n\n  Lemma update_elections_data_RVR_ascending_leaderLog :\n    forall h src t1 v st,\n      type (snd st) = Candidate ->\n      type (handleRequestVoteReply h (snd st) src t1 v) = Leader ->\n      exists ll,\n        In (currentTerm (snd st), ll) (leaderLogs (update_elections_data_requestVoteReply h src t1 v st)).\n  Proof using. \n    unfold update_elections_data_requestVoteReply, handleRequestVoteReply.\n    intros.\n    repeat find_rewrite. simpl in *.\n    repeat break_match; repeat find_inversion; subst; simpl in *; try congruence; eauto.\n  Qed.\n\n  Lemma appendEntries_leader_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply' appendEntries_leader.\n  Proof using lltsi ollpti aecfli. \n    unfold refined_raft_net_invariant_request_vote_reply', appendEntries_leader.\n    simpl.\n    intros.\n    find_apply_hyp_hyp.\n    find_copy_apply_lem_hyp handleRequestVoteReply_spec'.\n    repeat find_higher_order_rewrite.\n    update_destruct.\n    - rewrite handleRequestVoteReply_same_log.\n      intuition; try congruence.\n      + repeat find_rewrite.\n        eauto using in_middle_insert with *.\n      + subst.\n        match goal with\n        | [ H : pBody _ = AppendEntries _ _ _ _ _ _ |- _ ] =>\n          copy_eapply (append_entries_came_from_leaders_invariant net) H\n        end; eauto.\n        break_exists.\n        assert (pDst p = pSrc p0).\n        {\n          destruct (name_eq_dec (pDst p) (pSrc p0)); auto.\n          find_copy_apply_lem_hyp update_elections_data_RVR_ascending_leaderLog; auto.\n          break_exists.\n          repeat find_rewrite.\n          match goal with\n          | [ H : refined_raft_intermediate_reachable ?the_net,\n              H': In (?the_t, ?the_ll) (leaderLogs (update_elections_data_requestVoteReply _ _ _ _ _)),\n              H'' : In (_, ?the_ll') (leaderLogs (fst _))\n              |- _ ] =>\n            match the_net with\n            | context [ st' ] =>\n              apply one_leaderLog_per_term_host_invariant\n              with (net0 := the_net) (t := the_t) (ll := the_ll) (ll' := the_ll')\n            end\n          end; auto; simpl; repeat find_higher_order_rewrite; rewrite_update; simpl; auto.\n        }\n        exfalso.\n        repeat find_rewrite.\n        eapply lt_irrefl.\n        eapply leaderLogs_currentTerm_sanity_candidate_invariant; [|eauto|]; auto.\n    - eauto.\n  Qed.\n\n  Lemma doLeader_TTLM :\n    forall st h os st' ms,\n      doLeader st h = (os, st', ms) ->\n      type_term_log_monotonic st st'.\n  Proof using. \n    unfold doLeader, type_term_log_monotonic.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto; try congruence.\n  Qed.\n\n  Lemma doLeader_message_entries :\n    forall st h os st' ms m t n pli plt es ci e,\n      doLeader st h = (os, st', ms) ->\n      In m ms ->\n      snd m = AppendEntries t n pli plt es ci ->\n      In e es ->\n      currentTerm st = t /\\\n      type st = Leader /\\\n      In e (log st).\n  Proof using. \n    intros. unfold doLeader, advanceCommitIndex in *.\n    break_match; try solve [find_inversion; simpl in *; intuition].\n    break_if; try solve [find_inversion; simpl in *; intuition].\n    find_inversion. simpl. do_in_map. subst.\n    simpl in *. find_inversion.\n    eauto using findGtIndex_in.\n  Qed.\n\n  Lemma lifted_one_leader_per_term :\n    forall net h h',\n      refined_raft_intermediate_reachable net ->\n      currentTerm (snd (nwState net h)) = currentTerm (snd (nwState net h')) ->\n      type (snd (nwState net h)) = Leader ->\n      type (snd (nwState net h')) = Leader ->\n      h = h'.\n  Proof using olpti rri. \n    intros.\n    eapply (lift_prop _ one_leader_per_term_invariant _ ltac:(eauto));\n      simpl in *; repeat break_match; repeat (find_rewrite; simpl in *);\n      auto; simpl in *; repeat find_rewrite; simpl in *; auto.\n  Qed.\n\n\n  Lemma appendEntries_leader_do_leader :\n    refined_raft_net_invariant_do_leader appendEntries_leader.\n  Proof using olpti rri. \n    unfold refined_raft_net_invariant_do_leader, appendEntries_leader.\n    simpl.\n    intros.\n    find_apply_hyp_hyp.\n    intuition.\n    - repeat find_higher_order_rewrite.\n      update_destruct.\n      + eapply appendEntries_leader_predicate_TTLM_preserved; eauto using doLeader_TTLM.\n        match goal with\n        | [ H : nwState ?net ?h = (?gd, ?d) |- _ ] =>\n          replace d with (snd (nwState net h)) in * by (rewrite H; auto)\n        end.\n        eauto.\n      + eauto.\n    - do_in_map. subst. simpl in *.\n      repeat find_higher_order_rewrite.\n      find_copy_eapply_lem_hyp (doLeader_message_entries d);\n        match goal with\n        | [ H : nwState ?net ?h = (?gd, ?d) |- _ ] =>\n          replace d with (snd (nwState net h)) in * by (rewrite H; auto)\n        end; eauto; break_and.\n      update_destruct.\n      + erewrite doLeader_same_log; eauto.\n      + exfalso. eauto using lifted_one_leader_per_term.\n  Qed.\n\n  Lemma doGenericServer_TTLM :\n    forall h st os st' ps,\n      doGenericServer h st = (os, st', ps) ->\n      type_term_log_monotonic st st'.\n  Proof using. \n    unfold type_term_log_monotonic, doGenericServer.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto; try congruence;\n    use_applyEntries_spec; subst; simpl in *; auto.\n  Qed.\n\n  Lemma appendEntries_leader_do_generic_server :\n    refined_raft_net_invariant_do_generic_server appendEntries_leader.\n  Proof using. \n    unfold refined_raft_net_invariant_do_generic_server, appendEntries_leader.\n    simpl.\n    intros.\n    find_apply_hyp_hyp.\n    intuition.\n    - repeat find_higher_order_rewrite.\n      update_destruct.\n      + eapply appendEntries_leader_predicate_TTLM_preserved; eauto using doGenericServer_TTLM.\n        match goal with\n        | [ H : nwState ?net ?h = (?gd, ?d) |- _ ] =>\n          replace d with (snd (nwState net h)) in * by (rewrite H; auto)\n        end.\n        eauto.\n      + eauto.\n    - find_apply_lem_hyp doGenericServer_packets. subst. simpl in *. intuition.\n  Qed.\n\n  Lemma appendEntries_leader_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset appendEntries_leader.\n  Proof using. \n    unfold refined_raft_net_invariant_state_same_packet_subset, appendEntries_leader.\n    simpl. intros.\n    repeat find_reverse_higher_order_rewrite.\n    eauto.\n  Qed.\n\n  Lemma appendEntries_leader_reboot :\n    refined_raft_net_invariant_reboot appendEntries_leader.\n  Proof using. \n    unfold refined_raft_net_invariant_reboot, appendEntries_leader, reboot.\n    simpl.\n    intros.\n    repeat find_higher_order_rewrite.\n    update_destruct.\n    - discriminate.\n    - eauto.\n  Qed.\n\n  Lemma appendEntries_leader_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      appendEntries_leader net.\n  Proof using olpti lltsi ollpti aecfli rri. \n    intros.\n    apply refined_raft_net_invariant'; auto.\n    - apply appendEntries_leader_init.\n    - apply refined_raft_net_invariant_client_request'_weak.\n      apply appendEntries_leader_client_request.\n    - apply refined_raft_net_invariant_timeout'_weak.\n      apply appendEntries_leader_timeout.\n    - apply refined_raft_net_invariant_append_entries'_weak.\n      apply appendEntries_leader_append_entries.\n    - apply refined_raft_net_invariant_append_entries_reply'_weak.\n      apply appendEntries_leader_append_entries_reply.\n    - apply refined_raft_net_invariant_request_vote'_weak.\n      apply appendEntries_leader_request_vote.\n    - apply appendEntries_leader_request_vote_reply.\n    - apply refined_raft_net_invariant_do_leader'_weak.\n      apply appendEntries_leader_do_leader.\n    - apply refined_raft_net_invariant_do_generic_server'_weak.\n      apply appendEntries_leader_do_generic_server.\n    - apply appendEntries_leader_state_same_packet_subset.\n    - apply refined_raft_net_invariant_reboot'_weak.\n      apply appendEntries_leader_reboot.\n  Qed.\n\n  Instance appendeli : append_entries_leader_interface.\n  Proof.\n    split.\n    exact appendEntries_leader_invariant.\n  Qed.\nEnd AppendEntriesLeader.", "meta": {"author": "ahmet-celik", "repo": "pverdi", "sha": "dc88c4a5fd7d90b5bb48e583bd8286097f983f81", "save_path": "github-repos/coq/ahmet-celik-pverdi", "path": "github-repos/coq/ahmet-celik-pverdi/pverdi-dc88c4a5fd7d90b5bb48e583bd8286097f983f81/raft-proofs/AppendEntriesLeaderProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.24901745751771545}}
{"text": "Require Import List.\nRequire Import String.\nRequire Import ZArith.\n\nOpen Scope list_scope.\nOpen Scope string_scope.\nOpen Scope Z_scope.\n\nRequire Import StructTactics.\nRequire Import ImpSyntax.\nRequire Import ImpCommon.\nRequire Import ImpExprTransf.\nRequire Import ImpInterpNock.\nRequire Import ImpConstFold.\n\nRequire Import ImpEval.\nRequire Import ImpStep.\nRequire Import ImpSemanticsFacts.\nRequire Import ImpInterpProof.\nRequire Import ImpInterpNockProof.\nRequire Import ImpExprTransfProof.\n\nLemma cfold_aux_fwd :\n  forall s h e v,\n    ImpEval.eval_e s h e v ->\n    ImpEval.eval_e s h (cfold_aux e) v.\nProof.\n  induction e; simpl; intros; auto.\n  - break_match; auto.\n    find_apply_lem_hyp eval_e_interp_e.\n    find_apply_lem_hyp nock_e_ok.\n    simpl in *. find_rewrite.\n    ee.\n  - repeat break_match; auto.\n    repeat find_apply_lem_hyp eval_e_interp_e.\n    repeat find_apply_lem_hyp nock_e_ok.\n    simpl in *. find_rewrite.\n    ee.\nQed.\n\nLemma cfold_aux_bwd' :\n  forall s h e v,\n    I.interp_e s h (cfold_aux e) = Some v ->\n    I.interp_e s h e = Some v \\/\n    (forall v', ~ ImpEval.eval_e s h e v').\nProof.\n  induction e; simpl; intros; auto.\n  - break_match_hyp; simpl; auto.\n    find_apply_lem_hyp nock_e_ok.\n    simpl in *.\n    destruct o; destruct v0;\n      simpl in *; subst; auto;\n      right; unfold not in *; intros;\n      repeat on (eval_e _ _ _ _), invc;\n      on (eval_unop _ _ _), inv.\n  - repeat break_match_hyp; simpl; auto.\n    repeat find_apply_lem_hyp nock_e_ok.\n    simpl in *.\n    destruct o; destruct v0; destruct v1;\n    simpl in *; subst; auto; try (\n      right; unfold not in *; intros;\n      repeat on (eval_e _ _ _ _), invc;\n      on (eval_binop _ _ _ _), inv;\n      fail).\n    + break_match; subst; auto.\n      right; unfold not in *; intros.\n      repeat on (eval_e _ _ _ _), invc.\n      on (eval_binop _ _ _ _), inv.\n      congruence.\n    + break_match; subst; auto.\n      right; unfold not in *; intros.\n      repeat on (eval_e _ _ _ _), invc.\n      on (eval_binop _ _ _ _), inv.\n      congruence.\nQed.\n\nLemma cfold_aux_bwd :\n  forall s h e v,\n    eval_e s h (cfold_aux e) v ->\n    eval_e s h e v \\/\n    (forall v', ~ eval_e s h e v').\nProof.\n  intros.\n  find_apply_lem_hyp eval_e_interp_e.\n  find_apply_lem_hyp cfold_aux_bwd'.\n  on (or _ _), invc.\n  + left. apply interp_e_eval_e; auto.\n  + right; auto.\nQed.\n\nLemma cfold_p_fwd :\n  forall p v,\n    steps_p p v ->\n    steps_p (cfold p) v.\nProof.\n  apply transf_p_fwd.\n  apply transf_e_fwd.\n  apply cfold_aux_fwd.\nQed.\n\nLemma cfold_p_bwd :\n  forall p v,\n    steps_p (cfold p) v ->\n    steps_p p v \\/ can_get_stuck_prog p.\nProof.\n  apply transf_p_bwd.\n  apply transf_e_bwd.\n  apply cfold_aux_fwd.\n  apply cfold_aux_bwd.\nQed.", "meta": {"author": "palmskog", "repo": "street-fighting-proof-assistants", "sha": "f89660fab17a8c1a6c9cd9c14484ed8d72fb0088", "save_path": "github-repos/coq/palmskog-street-fighting-proof-assistants", "path": "github-repos/coq/palmskog-street-fighting-proof-assistants/street-fighting-proof-assistants-f89660fab17a8c1a6c9cd9c14484ed8d72fb0088/IMP/coq/ImpConstFoldProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.2490174515834723}}
{"text": "Require Import Lia.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\n\nRequire Import FulfillStep.\n\nSet Implicit Arguments.\n\n\nLemma promise_step_promise_consistent\n      lc1 mem1 loc from to msg lc2 mem2 kind\n      (STEP: Local.promise_step lc1 mem1 loc from to msg lc2 mem2 kind)\n      (CONS: Local.promise_consistent lc2):\n  Local.promise_consistent lc1.\nProof.\n  inv STEP. ii.\n  destruct (Memory.op_kind_is_cancel kind) eqn:KIND.\n  - destruct kind; ss. inv PROMISE.\n    destruct (Memory.get loc0 ts promises2) as [[]|] eqn:GET2.\n    + dup GET2. revert GET0.\n      erewrite Memory.remove_o; eauto. condtac; ss. i.\n      rewrite PROMISE0 in *. inv GET0. eauto.\n    + revert GET2. erewrite Memory.remove_o; eauto.\n      condtac; ss; i; try congr.\n      des. subst. exploit Memory.remove_get0; eauto. i. des.\n      rewrite GET in *. inv PROMISE0. ss.\n  - exploit Memory.promise_get1_promise; eauto. i. des.\n    inv MSG_LE; ss; eauto. eapply CONS; eauto. ss.\nQed.\n\nLemma read_step_promise_consistent\n      lc1 mem1 loc to val released ord lc2\n      (STEP: Local.read_step lc1 mem1 loc to val released ord lc2)\n      (CONS: Local.promise_consistent lc2):\n  Local.promise_consistent lc1.\nProof.\n  inv STEP. ii. exploit CONS; eauto. i.\n  eapply TimeFacts.le_lt_lt; eauto. ss.\n  etrans; [|apply Time.join_l]. etrans; [|apply Time.join_l]. refl.\nQed.\n\nLemma fulfill_unset_promises\n      loc from ts msg\n      promises1 promises2\n      l t f m\n      (FULFILL: Memory.remove promises1 loc from ts msg promises2)\n      (TH1: Memory.get l t promises1 = Some (f, m))\n      (TH2: Memory.get l t promises2 = None):\n  l = loc /\\ t = ts /\\ f = from /\\ Message.le msg m.\nProof.\n  revert TH2. erewrite Memory.remove_o; eauto. condtac; ss; [|congr].\n  des. subst. exploit Memory.remove_get0; eauto. i. des.\n  rewrite GET in TH1. inv TH1.\n  esplits; eauto. refl.\nQed.\n\nLemma fulfill_step_promise_consistent\n      lc1 sc1 loc from to val releasedm released ord lc2 sc2\n      (STEP: fulfill_step lc1 sc1 loc from to val releasedm released ord lc2 sc2)\n      (CONS: Local.promise_consistent lc2):\n  Local.promise_consistent lc1.\nProof.\n  inv STEP. ii.\n  destruct (Memory.get loc0 ts promises2) as [[]|] eqn:X.\n  - dup X. revert X.\n    erewrite Memory.remove_o; eauto. condtac; ss. i.\n    rewrite X in *. inv PROMISE.\n    exploit CONS; eauto. s. i.\n    eapply TimeFacts.le_lt_lt; eauto.\n    unfold TimeMap.join. apply Time.join_l.\n  - exploit fulfill_unset_promises; eauto. i. des. subst.\n    apply WRITABLE.\nQed.\n\nLemma write_step_promise_consistent\n      lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n      (STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n      (CONS: Local.promise_consistent lc2):\n  Local.promise_consistent lc1.\nProof.\n  inv STEP. inv WRITE. ii.\n  exploit Memory.promise_get1_promise; eauto.\n  { inv PROMISE; ss. }\n  i. des.\n  destruct (Memory.get loc0 ts promises2) as [[]|] eqn:X.\n  - dup X. revert X0.\n    erewrite Memory.remove_o; eauto. condtac; ss; i.\n    rewrite GET in *. inv X0.\n    apply CONS in X. ss. exploit X; try by (inv MSG_LE; ss). i.\n    eapply TimeFacts.le_lt_lt; eauto.\n    etrans; [|apply Time.join_l]. refl.\n  - exploit fulfill_unset_promises; eauto. i. des. subst.\n    apply WRITABLE.\nQed.\n\nLemma memory_write_promise_consistent\n      ts promises1 mem1 loc from to msg promises2 mem2 kind\n      (TO: Time.lt ts to)\n      (STEP: Memory.write promises1 mem1 loc from to msg promises2 mem2 kind)\n      (CONS: forall to' from' msg'\n               (PROMISE: Memory.get loc to' promises2 = Some (from', msg'))\n               (MSG: msg' <> Message.reserve),\n          Time.lt ts to'):\n  forall to' from' msg'\n    (PROMISE: Memory.get loc to' promises1 = Some (from', msg'))\n    (MSG: msg' <> Message.reserve),\n    Time.lt ts to'.\nProof.\n  i. inv STEP.\n  exploit Memory.promise_get1_promise; eauto.\n  { inv PROMISE0; ss.\n    exploit Memory.remove_get0; try exact PROMISES. i. des.\n    exploit Memory.remove_get0; try exact REMOVE. i. des. congr.\n  }\n  i. des.\n  destruct (Memory.get loc to' promises2) as [[]|] eqn:X.\n  - dup X. revert X0.\n    erewrite Memory.remove_o; eauto. condtac; ss; i.\n    rewrite GET in *. inv X0.\n    apply CONS in X; ss.\n    ii. subst. inv MSG_LE. ss.\n  - exploit fulfill_unset_promises; eauto. i. des. subst. ss.\nQed.\n\nLemma write_na_promise_consistent\n      ts' ts promises1 mem1 loc from to val promises2 mem2 msgs kinds kind\n      (TS: Time.le ts' ts)\n      (STEP: Memory.write_na ts promises1 mem1 loc from to val promises2 mem2 msgs kinds kind)\n      (CONS: forall to' from' msg\n               (PROMISE: Memory.get loc to' promises2 = Some (from', msg))\n               (MSG: msg <> Message.reserve),\n          Time.lt ts' to'):\n  forall to' from' msg\n    (PROMISE: Memory.get loc to' promises1 = Some (from', msg))\n    (MSG: msg <> Message.reserve),\n    Time.lt ts' to'.\nProof.\n  induction STEP; i.\n  { hexploit memory_write_promise_consistent; try exact CONS; eauto.\n    eapply TimeFacts.le_lt_lt; eauto.\n  }\n  eapply memory_write_promise_consistent; try exact WRITE_EX; eauto.\n  { eapply TimeFacts.le_lt_lt; eauto. }\n  eapply IHSTEP; eauto.\n  econs. eapply TimeFacts.le_lt_lt; eauto.\nQed.\n\nLemma write_na_step_promise_consistent\n      lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind\n      (STEP: Local.write_na_step lc1 sc1 mem1 loc from to val ord lc2 sc2 mem2 msgs kinds kind)\n      (CONS: Local.promise_consistent lc2):\n  Local.promise_consistent lc1.\nProof.\n  inv STEP. ii.\n  destruct (classic (loc0 = loc)); cycle 1.\n  - hexploit Memory.write_na_get_diff_promise; try exact WRITE; eauto.\n    i. rewrite <- H0 in PROMISE.\n    exploit CONS; eauto. s.\n    unfold TimeMap.join, TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n    condtac; ss.\n    rewrite TimeFacts.le_join_l; try apply Time.bot_spec. ss.\n  - subst.\n    eapply write_na_promise_consistent; try exact WRITE; eauto; try refl.\n    i. eapply TimeFacts.le_lt_lt; cycle 1.\n    { eapply CONS; eauto. }\n    s. unfold TimeMap.join. apply Time.join_l.\nQed.\n\nLemma fence_step_promise_consistent\n      lc1 sc1 mem1 ordr ordw lc2 sc2\n      (STEP: Local.fence_step lc1 sc1 ordr ordw lc2 sc2)\n      (WF: Local.wf lc1 mem1)\n      (CONS: Local.promise_consistent lc2):\n  Local.promise_consistent lc1.\nProof.\n  inv STEP. ii.\n  exploit CONS; eauto. i.\n  eapply TimeFacts.le_lt_lt; eauto.\n  cut (TView.le (Local.tview lc1)\n                (TView.write_fence_tview (TView.read_fence_tview (Local.tview lc1) ordr) sc1 ordw)).\n  { i. inv H. apply CUR. }\n  etrans.\n  - eapply TViewFacts.write_fence_tview_incr. apply WF.\n  - eapply TViewFacts.write_fence_tview_mon; try refl; try apply WF.\n    eapply TViewFacts.read_fence_tview_incr. apply WF.\nQed.\n\nLemma ordering_relaxed_dec\n      ord:\n  Ordering.le ord Ordering.relaxed \\/ Ordering.le Ordering.strong_relaxed ord.\nProof. destruct ord; auto. Qed.\n\nLemma step_promise_consistent\n      lang pf e th1 th2\n      (STEP: @Thread.step lang pf e th1 th2)\n      (CONS: Local.promise_consistent (Thread.local th2))\n      (WF1: Local.wf (Thread.local th1) (Thread.memory th1))\n      (SC1: Memory.closed_timemap (Thread.sc th1) (Thread.memory th1))\n      (MEM1: Memory.closed (Thread.memory th1)):\n  Local.promise_consistent (Thread.local th1).\nProof.\n  inv STEP; [inv STEP0|inv STEP0; inv LOCAL]; ss.\n  - eapply promise_step_promise_consistent; eauto.\n  - eapply read_step_promise_consistent; eauto.\n  - eapply write_step_promise_consistent; eauto.\n  - eapply read_step_promise_consistent; eauto.\n    eapply write_step_promise_consistent; eauto.\n  - eapply fence_step_promise_consistent; eauto.\n  - eapply fence_step_promise_consistent; eauto.\n  - eapply write_na_step_promise_consistent; eauto.\nQed.\n\nLemma opt_step_promise_consistent\n      lang e th1 th2\n      (STEP: @Thread.opt_step lang e th1 th2)\n      (CONS: Local.promise_consistent (Thread.local th2))\n      (WF1: Local.wf (Thread.local th1) (Thread.memory th1))\n      (SC1: Memory.closed_timemap (Thread.sc th1) (Thread.memory th1))\n      (MEM1: Memory.closed (Thread.memory th1)):\n  Local.promise_consistent (Thread.local th1).\nProof.\n  inv STEP; eauto using step_promise_consistent.\nQed.\n\nLemma rtc_all_step_promise_consistent\n      lang th1 th2\n      (STEP: rtc (@Thread.all_step lang) th1 th2)\n      (CONS: Local.promise_consistent (Thread.local th2))\n      (WF1: Local.wf (Thread.local th1) (Thread.memory th1))\n      (SC1: Memory.closed_timemap (Thread.sc th1) (Thread.memory th1))\n      (MEM1: Memory.closed (Thread.memory th1)):\n  Local.promise_consistent (Thread.local th1).\nProof.\n  revert_until STEP. induction STEP; auto. i.\n  inv H. inv USTEP. exploit Thread.step_future; eauto. i. des.\n  eapply step_promise_consistent; eauto.\nQed.\n\nLemma rtc_tau_step_promise_consistent\n      lang th1 th2\n      (STEP: rtc (@Thread.tau_step lang) th1 th2)\n      (CONS: Local.promise_consistent (Thread.local th2))\n      (WF1: Local.wf (Thread.local th1) (Thread.memory th1))\n      (SC1: Memory.closed_timemap (Thread.sc th1) (Thread.memory th1))\n      (MEM1: Memory.closed (Thread.memory th1)):\n  Local.promise_consistent (Thread.local th1).\nProof.\n  eapply rtc_all_step_promise_consistent; cycle 1; eauto.\n  eapply rtc_implies; [|eauto].\n  apply tau_union.\nQed.\n\nLemma rtc_reserve_step_promise_consistent\n      lang th1 th2\n      (STEPS: rtc (@Thread.reserve_step lang) th1 th2)\n      (CONS: Local.promise_consistent (Thread.local th2)):\n  Local.promise_consistent (Thread.local th1).\nProof.\n  ginduction STEPS; eauto. i. eapply IHSTEPS in CONS.\n  inv H. inv STEP; inv STEP0; inv LOCAL. inv PROMISE. ss.\n  ii. eapply Memory.add_get1 in PROMISE; eauto.\nQed.\n\nLemma rtc_cancel_step_promise_consistent\n      lang th1 th2\n      (STEPS: rtc (@Thread.cancel_step lang) th1 th2)\n      (CONS: Local.promise_consistent (Thread.local th2)):\n  Local.promise_consistent (Thread.local th1).\nProof.\n  ginduction STEPS; eauto. i. eapply IHSTEPS in CONS.\n  inv H. inv STEP; inv STEP0; inv LOCAL. inv PROMISE. ss.\n  ii. dup PROMISE. eapply Memory.remove_get1 in PROMISE; eauto. des; eauto.\n  clarify. eapply Memory.remove_get0 in PROMISES. des. clarify.\nQed.\n\nLemma rtc_reserve_step_promise_consistent2\n      lang (th1 th2: Thread.t lang)\n      (CONS: Local.promise_consistent (Thread.local th1))\n      (STEPS: rtc (@Thread.reserve_step lang) th1 th2)\n  :\n    Local.promise_consistent (Thread.local th2).\nProof.\n  ginduction STEPS; eauto.  i. eapply IHSTEPS.\n  inv H. inv STEP; inv STEP0; inv LOCAL. inv PROMISE. ss.\n  ii. erewrite Memory.add_o in PROMISE; eauto. des_ifs.\n  eapply CONS; eauto.\nQed.\n\nLemma rtc_cancel_step_promise_consistent2\n      lang (th1 th2: Thread.t lang)\n      (CONS: Local.promise_consistent (Thread.local th1))\n      (STEPS: rtc (@Thread.cancel_step lang) th1 th2)\n  :\n    Local.promise_consistent (Thread.local th2).\nProof.\n  ginduction STEPS; eauto.  i. eapply IHSTEPS.\n  inv H. inv STEP; inv STEP0; inv LOCAL. inv PROMISE. ss.\n  ii. erewrite Memory.remove_o in PROMISE; eauto. des_ifs.\n  eapply CONS; eauto.\nQed.\n\nLemma consistent_promise_consistent\n      lang th\n      (CONS: @Thread.consistent lang th)\n      (WF: Local.wf (Thread.local th) (Thread.memory th))\n      (SC: Memory.closed_timemap (Thread.sc th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th)):\n  Local.promise_consistent (Thread.local th).\nProof.\n  destruct th. ss.\n  exploit Memory.cap_exists; eauto. i. des.\n  exploit Memory.cap_closed; eauto. i.\n  exploit Local.cap_wf; eauto. i.\n  hexploit Memory.cap_closed_timemap; eauto. i. des.\n  exploit CONS; eauto. s. i. des.\n  - inv FAILURE. des. inv STEP_FAILURE; inv STEP; ss.\n    inv LOCAL; ss; inv LOCAL0;\n      hexploit rtc_tau_step_promise_consistent; try exact STEPS; eauto.\n  - hexploit rtc_tau_step_promise_consistent; try exact STEPS; eauto.\n    ii. rewrite PROMISES, Memory.bot_get in *. congr.\nQed.\n\nLemma promise_consistent_promise_read\n      lc1 mem1 loc to val ord released lc2\n      f t v r\n      (STEP: Local.read_step lc1 mem1 loc to val released ord lc2)\n      (PROMISE: Memory.get loc t (Local.promises lc1) = Some (f, Message.concrete v r))\n      (CONS: Local.promise_consistent lc2):\n  Time.lt to t.\nProof.\n  inv STEP. exploit CONS; eauto; ss. intros x.\n  apply TimeFacts.join_lt_des in x. des.\n  apply TimeFacts.join_lt_des in AC. des.\n  revert BC0. unfold View.singleton_ur_if. condtac; ss.\n  - unfold TimeMap.singleton, LocFun.add. condtac; ss.\n  - unfold TimeMap.singleton, LocFun.add. condtac; ss.\nQed.\n\nLemma promise_consistent_promise_write\n      lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n      f t m\n      (STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n      (PROMISE: Memory.get loc t (Local.promises lc1) = Some (f, m))\n      (MSG: m <> Message.reserve)\n      (CONS: Local.promise_consistent lc2):\n  Time.le to t.\nProof.\n  destruct (Memory.get loc t (Local.promises lc2)) as [[]|] eqn:X.\n  - inv STEP. inv WRITE. ss.\n    dup X. revert X0.\n    erewrite Memory.remove_o; eauto. condtac; ss. i. guardH o.\n    exploit Memory.promise_get1_promise; try exact PROMISE; eauto.\n    { inv PROMISE0; ss. }\n    i. des.\n    rewrite X0 in *. inv GET.\n    exploit CONS; eauto; try by (inv MSG_LE; ss). s. intros x.\n    apply TimeFacts.join_lt_des in x. des.\n    revert BC. unfold TimeMap.singleton, LocFun.add. condtac; ss. i.\n    econs. ss.\n  - inv STEP. inv WRITE.\n    exploit Memory.promise_get1_promise; eauto.\n    { inv PROMISE0; ss. }\n    i. des.\n    exploit fulfill_unset_promises; eauto. i. des. subst. refl.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/prop/PromiseConsistent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.24897853809839152}}
{"text": "Require Import Verdi.Verdi.\nRequire Import Verdi.HandlerMonad.\nRequire Import Verdi.NameOverlay.\nRequire Import Verdi.LabeledNet.\n\nRequire Import Sumbool.\n\nRequire Import mathcomp.ssreflect.ssreflect.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nSet Implicit Arguments.\n\nModule FailureRecorder (Import NT : NameType) \n (NOT : NameOrderedType NT) (NSet : MSetInterface.S with Module E := NOT) \n (Import ANT : AdjacentNameType NT).\n\nInductive Msg : Set := \n| Fail : Msg\n| New : Msg.\n\nDefinition Msg_eq_dec : forall x y : Msg, {x = y} + {x <> y}.\ndecide equality.\nDefined.\n\nInductive Input : Set := .\n\nDefinition Input_eq_dec : forall x y : Input, {x = y} + {x <> y}.\ndecide equality.\nDefined.\n\nInductive Output : Set := .\n\nDefinition Output_eq_dec : forall x y : Output, {x = y} + {x <> y}.\ndecide equality.\nDefined.\n\nDefinition NS := NSet.t.\n\nRecord Data := mkData { adjacent : NS }.\n\nDefinition InitData (n : name) := mkData NSet.empty.\n\nInductive Label : Type :=\n| Tau : Label\n| RecvFail : name -> name -> Label\n| RecvNew : name -> name -> Label.\n\nDefinition Label_eq_dec : forall x y : Label, {x = y} + {x <> y}.\ndecide equality; exact: name_eq_dec.\nDefined.\n\nDefinition Handler (S : Type) := GenHandler (name * Msg) S Output Label.\n\nDefinition NetHandler (me src: name) (msg : Msg) : Handler Data :=\nst <- get ;;\nmatch msg with\n| New =>\n  put {| adjacent := NSet.add src st.(adjacent) |} ;;\n  ret (RecvNew me src)\n| Fail => \n  put {| adjacent := NSet.remove src st.(adjacent) |} ;;\n  ret (RecvFail me src)\nend.\n\nDefinition IOHandler (me : name) (i : Input) : Handler Data := ret Tau.\n\nInstance FailureRecorder_BaseParams : BaseParams :=\n  {\n    data := Data;\n    input := Input;\n    output := Output\n  }.\n\nInstance FailureRecorder_LabeledMultiParams : LabeledMultiParams FailureRecorder_BaseParams :=\n  {\n    lb_name := name ;\n    lb_msg := Msg ;\n    lb_msg_eq_dec := Msg_eq_dec ;\n    lb_name_eq_dec := name_eq_dec ;\n    lb_nodes := nodes ;\n    lb_all_names_nodes := all_names_nodes ;\n    lb_no_dup_nodes := no_dup_nodes ;\n    label := Label ;\n    label_silent := Tau ;\n    lb_init_handlers := InitData ;\n    lb_net_handlers := (fun dst src msg s => runGenHandler s (NetHandler dst src msg)) ;\n    lb_input_handlers := fun nm msg s => runGenHandler s (IOHandler nm msg) ;\n  }.\n\nInstance FailureRecorder_MultiParams : MultiParams FailureRecorder_BaseParams := unlabeled_multi_params.\n\nInstance FailureRecorder_NameOverlayParams : NameOverlayParams FailureRecorder_MultiParams :=\n  {\n    adjacent_to := adjacent_to ;\n    adjacent_to_dec := adjacent_to_dec ;\n    adjacent_to_symmetric := adjacent_to_symmetric ;\n    adjacent_to_irreflexive := adjacent_to_irreflexive\n  }.\n\nInstance FailureRecorder_FailMsgParams : FailMsgParams FailureRecorder_MultiParams :=\n  {\n    msg_fail := Fail\n  }.\n\nInstance FailureRecorder_NewMsgParams : NewMsgParams FailureRecorder_MultiParams :=\n  {\n    msg_new := New\n  }.\n\nLemma net_handlers_NetHandler :\n  forall dst src m st os st' ms,\n    net_handlers dst src m st = (os, st', ms) ->\n    exists lb, NetHandler dst src m st = (lb, os, st', ms).\nProof.\nintros.\nsimpl in *.\nunfold unlabeled_net_handlers, lb_net_handlers in *.\nsimpl in *.\nmonad_unfold.\nrepeat break_let.\nfind_inversion.\nby exists l0; auto.\nQed.\n\nLemma input_handlers_IOHandler :\n  forall h i d os d' ms,\n    input_handlers h i d = (os, d', ms) ->\n    exists lb, IOHandler h i d = (lb, os, d', ms).\nProof. by []. Qed.\n\nLemma IOHandler_cases :\n  forall h i st u out st' ms,\n      IOHandler h i st = (u, out, st', ms) -> False.\nProof. by move => h; case. Qed.\n\nLemma NetHandler_cases : \n  forall dst src msg st lb out st' ms,\n    NetHandler dst src msg st = (lb, out, st', ms) ->\n    (msg = Fail /\\ lb = RecvFail dst src /\\ out = [] /\\ ms = [] /\\ st'.(adjacent) = NSet.remove src st.(adjacent)) \\/\n    (msg = New /\\ lb = RecvNew dst src /\\ out = [] /\\ ms = [] /\\ st'.(adjacent) = NSet.add src st.(adjacent)).\nProof.\nmove => dst src msg st out st' ms.\nrewrite /NetHandler.\ncase: msg; monad_unfold => /= H_eq.\n- by left; find_inversion.\n- by right; find_inversion.\nQed.\n\nLtac net_handler_cases := \n  find_apply_lem_hyp NetHandler_cases; \n  intuition idtac; subst; \n  repeat find_rewrite.\n\nLtac io_handler_cases := \n  find_apply_lem_hyp IOHandler_cases.\n\nEnd FailureRecorder.\n", "meta": {"author": "DistributedComponents", "repo": "verdi-aggregation", "sha": "c81681555d63d4a3db225119600833868caf4607", "save_path": "github-repos/coq/DistributedComponents-verdi-aggregation", "path": "github-repos/coq/DistributedComponents-verdi-aggregation/verdi-aggregation-c81681555d63d4a3db225119600833868caf4607/systems/FailureRecorderDynamicLabeled.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24896579559260787}}
{"text": "Require Import TM.TM.\n\n(** * Basic 1-Tape Machines *)\n\n\n(** ** Helper functions *)\nSection Mk_Mono.\n  Variable (sig states : finType).\n  Variable mono_trans : states -> option sig -> states * (option sig * move).\n  Variable (init : states) (fin : states -> bool).\n\n  Definition Mk_Mono_TM : mTM sig 1.\n  Proof.\n    split with (states := states).\n    - intros (q&tape).\n      pose proof (mono_trans q (tape[@Fin0])) as (q', act).\n      apply (q', [| act |]).\n    - apply init.\n    - apply fin.\n  Defined.\n\n  Variable (F : finType) (R : Rel (tape sig) (F * tape sig)).\n\n  Definition Mk_R_p : Rel (tapes sig 1) (F * tapes sig 1) :=\n      fun tps1 '(p, tps2) => R (tps1[@Fin0]) (p, tps2[@Fin0]).\n\nEnd Mk_Mono.\n\nArguments Mk_R_p { sig F } ( R ) x y /.\n\n\n\n(** ** Do a single action *)\nSection DoAct.\n  Variable sig : finType.\n  Variable c : sig.\n\n  Variable act : option sig * move.\n\n  Definition DoAct_TM :=\n    {|\n      trans := fun '(q, sym) => (true, [| act |]);\n      start := false;\n      halt x := x;\n    |}.\n\n  Definition DoAct : pTM sig unit 1 := (DoAct_TM; fun _ => tt).\n\n  Definition DoAct_Rel : pRel sig unit 1 :=\n    Mk_R_p (ignoreParam (fun t t' => t' = doAct t act)).\n\n  Lemma DoAct_Sem : DoAct ⊨c(1) DoAct_Rel.\n  Proof. intros t. destruct_tapes. cbn. unfold initc; cbn. eexists (mk_mconfig _ _); cbn; eauto. Qed.\n\nEnd DoAct.\n\nArguments DoAct : simpl never.\nArguments DoAct_Rel { sig } act x y /.\n\n\n(** *** Derived Machines *)\n\nSection DoAct_Derived.\n  Variable sig : finType.\n  Variable c : sig. (* for Write *)\n  Variable (D : move). (* for Move *)\n\n  Definition Write : pTM sig unit 1 := DoAct (Some c, N).\n\n  Definition Write_Rel : pRel sig unit 1 :=\n    Mk_R_p (ignoreParam (fun t t' => t' = midtape (left t) c (right t))).\n\n  Lemma Write_Sem :\n    Write ⊨c(1) Write_Rel.\n  Proof.\n    eapply RealiseIn_monotone.\n    - apply DoAct_Sem.\n    - reflexivity.\n    - hnf. firstorder.\n  Qed.\n\n  Definition Move : pTM sig unit 1 := DoAct (None, D).\n\n  Definition Move_Rel : pRel sig unit 1 :=\n    Mk_R_p (ignoreParam (fun t t' => t' = tape_move (sig := sig) t D)).\n\n  Lemma Move_Sem :\n    Move ⊨c(1) Move_Rel.\n  Proof.\n    eapply RealiseIn_monotone.\n    - apply DoAct_Sem.\n    - reflexivity.\n    - hnf. firstorder.\n  Qed.\n\n  Definition WriteMove : pTM sig unit 1 := DoAct (Some c, D).\n\n  Definition WriteMove_Rel : pRel sig unit 1 :=\n    Mk_R_p (ignoreParam (fun t t' => t' = tape_move (tape_write t (Some c)) D)).\n\n  Lemma WriteMove_Sem :\n    WriteMove ⊨c(1) WriteMove_Rel.\n  Proof.\n    eapply RealiseIn_monotone.\n    - apply DoAct_Sem.\n    - reflexivity.\n    - hnf. firstorder.\n  Qed.\n\nEnd DoAct_Derived.\n\nArguments Write : simpl never.\nArguments Write_Rel { sig } c x y / : rename.\n\nArguments Move : simpl never.\nArguments Move { sig } D.\nArguments Move_Rel { sig } ( D ) x y /.\n\nArguments WriteMove : simpl never.\nArguments WriteMove_Rel { sig } (w D) x y / : rename.\n\n\n(** ** Read a symbol *)\n\nSection ReadChar.\n\n  Variable sig : finType.\n\n  Definition ReadChar_TM : mTM sig 1 :=\n    {|\n      trans := fun '(_, sym) =>\n                 match sym[@Fin0] with\n                 | None => (inl true, [|(None, N)|])\n                 | Some c => (inr c, [|(None, N)|])\n                 end;\n      start := inl false;\n      halt := fun s => match s with\n                    | inl b => b\n                    | inr _ => true\n                    end;\n    |}.\n\n  Definition ReadChar := (ReadChar_TM; fun s => match s with inl _ => None | inr s => Some s end).\n\n  Definition ReadChar_Rel : pRel sig (option sig) 1 :=\n    fun t '(y, t') =>\n      y = current t[@Fin0] /\\\n      t' = t.\n\n  Definition ReadChar_Sem : ReadChar ⊨c(1) ReadChar_Rel.\n  Proof.\n    intros t. destruct_tapes. cbn. unfold initc; cbn. cbv [step]; cbn. unfold current_chars; cbn.\n    destruct (current h) eqn:E.\n    - eexists (mk_mconfig _ _); cbv [step]; cbn. split; eauto.\n    - eexists (mk_mconfig _ _); cbv [step]; cbn. split; eauto.\n  Qed.\n\nEnd ReadChar.\n\nArguments ReadChar : simpl never.\nArguments ReadChar {sig}.\nArguments ReadChar_Rel sig x y /.\n\n\n(** ** Tactic Support *)\n\nLtac smpl_TM_Mono :=\n  lazymatch goal with\n  | [ |- DoAct _ ⊨ _] => eapply RealiseIn_Realise; eapply DoAct_Sem\n  | [ |- DoAct _ ⊨c(_) _] => eapply DoAct_Sem\n  | [ |- projT1 (DoAct _) ↓ _] => eapply RealiseIn_TerminatesIn; eapply DoAct_Sem\n  | [ |- Write _ ⊨ _] => eapply RealiseIn_Realise; eapply Write_Sem\n  | [ |- Write _ ⊨c(_) _] => eapply Write_Sem\n  | [ |- projT1 (Write _) ↓ _] => eapply RealiseIn_TerminatesIn; eapply Write_Sem\n  | [ |- Move _ ⊨ _] => eapply RealiseIn_Realise; eapply Move_Sem\n  | [ |- Move _ ⊨c(_) _] => eapply Move_Sem\n  | [ |- projT1 (Move _) ↓ _] => eapply RealiseIn_TerminatesIn; eapply Move_Sem\n  | [ |- WriteMove _ _ ⊨ _] => eapply RealiseIn_Realise; eapply WriteMove_Sem\n  | [ |- WriteMove _ _ ⊨c(_) _] => eapply WriteMove_Sem\n  | [ |- projT1 (WriteMove _ _) ↓ _] => eapply RealiseIn_TerminatesIn; eapply WriteMove_Sem\n  | [ |- ReadChar ⊨ _] => eapply RealiseIn_Realise; eapply ReadChar_Sem\n  | [ |- ReadChar ⊨c(_) _] => eapply ReadChar_Sem\n  | [ |- projT1 (ReadChar) ↓ _] => eapply RealiseIn_TerminatesIn; eapply ReadChar_Sem\n  end.\n\nSmpl Add smpl_TM_Mono : TM_Correct.", "meta": {"author": "uds-psl", "repo": "CoqTM", "sha": "f4d2aab2008e2158e2c7ca88ebb53b42808a0778", "save_path": "github-repos/coq/uds-psl-CoqTM", "path": "github-repos/coq/uds-psl-CoqTM/CoqTM-f4d2aab2008e2158e2c7ca88ebb53b42808a0778/theories/TM/Basic/Mono.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24896578926620103}}
{"text": "From Tweetnacl.Libs Require Import Export.\nFrom Tweetnacl.ListsOp Require Import Export.\nFrom stdpp Require Import list.\nRequire Import ssreflect.\n\nFrom Tweetnacl.Gen Require Import AMZubSqSel.\nFrom Tweetnacl.Gen Require Import AMZubSqSel_Prop.\nFrom Tweetnacl.Gen Require Import AMZubSqSel_List.\nFrom Tweetnacl.Gen Require Import Get_abcdef.\nFrom Tweetnacl.Gen Require Import abstract_fn_rev.\nFrom Tweetnacl.Gen Require Import ABCDEF.\nFrom Tweetnacl.Low Require Import List16.\nFrom Tweetnacl.Low Require Import AMZubSqSel_Correct.\nFrom Tweetnacl.Gen Require Import abstract_fn_rev_eq.\nFrom Tweetnacl.Gen Require Import abstract_fn_rev_abcdef.\nFrom Tweetnacl.Low Require Import Constant.\n\nOpen Scope Z.\n\nSection Crypto_Scalarmult_Eq_ac_List16_Z.\n\nContext (Mod : Z -> Z).\nContext (Z_Ops : (Ops Z Z) Mod).\nContext (List_Z_Ops : Ops (list Z) (list Z) id).\nContext (List_Z_Ops_Prop : @Ops_List List_Z_Ops).\nContext (List_Z_Ops_Prop_Correct : @Ops_Prop_List_Z Mod List_Z_Ops Z_Ops).\nLocal Instance List16_Ops : (Ops (@List16 Z) (List32B) id) := {}.\nProof.\napply A_List16.\napply M_List16.\napply Zub_List16.\napply Sq_List16.\napply C_0_List16.\napply C_1_List16.\napply C_121665_List16.\napply Sel25519_List16.\napply getbit_List32B.\nsimpl ; reflexivity.\nsimpl ; reflexivity.\nsimpl ; reflexivity.\nsimpl ; reflexivity.\nsimpl ; reflexivity.\nsimpl ; reflexivity.\nDefined.\nLocal Instance List16_Z_Eq : @Ops_Mod_P (@List16 Z) (List32B) Z Mod id List16_Ops Z_Ops := {\nP l := (ZofList 16 (List16_to_List l));\nP' l := (ZofList 8 (List32_to_List l));\n}.\nProof.\n- intros [a Ha] [b Hb] ; simpl ; f_equal; apply A_correct.\n- intros [a Ha] [b Hb] ; simpl List16_to_List.\n  apply mult_GF_Zlengh ; assumption.\n- intros [a Ha] [b Hb] ; simpl ; f_equal ; apply Zub_correct.\n- intros [a Ha] ; simpl List16_to_List ; apply Sq_GF_Zlengh ; assumption.\n- simpl List16_to_List ; f_equal; apply C_121665_correct.\n- simpl List16_to_List ; f_equal; apply C_0_correct.\n- simpl List16_to_List ; f_equal; apply C_1_correct.\n- intros b [p Hp] [q Hq] ; simpl List16_to_List ; f_equal ; apply Sel25519_correct.\n- intros b [p Hp] ; simpl ; symmetry ; apply GetBit_correct ; assumption.\nDefined.\n\nLemma abstract_fn_rev_eq_a_Z : ∀ (m p : ℤ) (CN : List32B) (L16ONE L16NUL L16UP : List16 ℤ) (Cn Up:list Z) (n u:Z),\n  0 ≤ m →\n  List16_to_List L16ONE = Low.C_1 ->\n  List16_to_List L16NUL = Low.C_0 ->\n  List16_to_List L16UP = Up ->\n  List32_to_List CN = Cn ->\n  ZofList 16 Up = u ->\n  ZofList 8 Cn = n ->\n  Mod (P (get_a (abstract_fn_rev m p CN L16ONE L16UP L16NUL L16ONE L16NUL L16NUL L16UP))) =\n  Mod (get_a (abstract_fn_rev m p n 1 u 0 1 0 0 u)).\nProof.\n  intros m p CN L16ONE L16NUL L16UP Cn Up n u.\n  intros Hm.\n  intros HL16ONE HL16NUL HL16UP HL32CN.\n  intros Hu Hn.\n  assert(Heq1:= @abstract_fn_rev_eq_a (List16 Z) List32B Z id Mod List16_Ops Z_Ops List16_Z_Eq m p).\n  specialize Heq1 with CN L16ONE L16UP L16NUL L16ONE L16NUL L16NUL L16UP.\n  apply Heq1 in Hm.\n  clear Heq1.\n  move:Hm.\n  rewrite /P /P' /List16_Z_Eq ?HL16ONE ?HL16NUL ?HL16UP ?HL32CN ?Hu ?Hn.\n  change (ℤ16.lst Low.C_0) with 0.\n  change (ℤ16.lst Low.C_1) with 1.\n  trivial.\nQed.\n\nLemma abstract_fn_rev_eq_c_Z : ∀ (m p : ℤ) (CN : List32B) (L16ONE L16NUL L16UP : List16 ℤ) (Cn Up:list Z) (n u:Z),\n  0 ≤ m →\n  List16_to_List L16ONE = Low.C_1 ->\n  List16_to_List L16NUL = Low.C_0 ->\n  List16_to_List L16UP = Up ->\n  List32_to_List CN = Cn ->\n  ZofList 16 Up = u ->\n  ZofList 8 Cn = n ->\n  Mod (P (get_c (abstract_fn_rev m p CN L16ONE L16UP L16NUL L16ONE L16NUL L16NUL L16UP))) =\n  Mod (get_c (abstract_fn_rev m p n 1 u 0 1 0 0 u)).\nProof.\n  intros m p CN L16ONE L16NUL L16UP Cn Up n u.\n  intros Hm.\n  intros HL16ONE HL16NUL HL16UP HL32CN.\n  intros Hu Hn.\n  assert(Heq1:= @abstract_fn_rev_eq_c (List16 Z) List32B Z id Mod List16_Ops Z_Ops List16_Z_Eq m p).\n  specialize Heq1 with CN L16ONE L16UP L16NUL L16ONE L16NUL L16NUL L16UP.\n  apply Heq1 in Hm.\n  clear Heq1.\n  move:Hm.\n  rewrite /P /P' /List16_Z_Eq ?HL16ONE ?HL16NUL ?HL16UP ?HL32CN ?Hu ?Hn.\n  change (ℤ16.lst Low.C_0) with 0.\n  change (ℤ16.lst Low.C_1) with 1.\n  trivial.\nQed.\n\nEnd Crypto_Scalarmult_Eq_ac_List16_Z.\n\nClose Scope Z.", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/proofs/spec/Low/Crypto_Scalarmult_lemmas_Z_List16.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2489626470776189}}
{"text": "Require Export VST.concurrency.paco.src.paconotation VST.concurrency.paco.src.pacotac VST.concurrency.paco.src.pacodef VST.concurrency.paco.src.pacotacuser.\nSet Implicit Arguments.\n\n(** ** Predicates of Arity 4\n*)\n\n(** 1 Mutual Coinduction *)\n\nSection Arg4_1.\n\nDefinition monotone4 T0 T1 T2 T3 (gf: rel4 T0 T1 T2 T3 -> rel4 T0 T1 T2 T3) :=\n  forall x0 x1 x2 x3 r r' (IN: gf r x0 x1 x2 x3) (LE: r <4= r'), gf r' x0 x1 x2 x3.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.\nVariable gf : rel4 T0 T1 T2 T3 -> rel4 T0 T1 T2 T3.\nArguments gf : clear implicits.\n\nTheorem paco4_acc: forall\n  l r (OBG: forall rr (INC: r <4= rr) (CIH: l <_paco_4= rr), l <_paco_4= paco4 gf rr),\n  l <4= paco4 gf r.\nProof.\n  intros; assert (SIM: paco4 gf (r \\4/ l) x0 x1 x2 x3) by eauto.\n  clear PR; repeat (try left; do 5 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco4_mon: monotone4 (paco4 gf).\nProof. paco_cofix_auto; repeat (left; do 5 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco4_mult_strong: forall r,\n  paco4 gf (upaco4 gf r) <4= paco4 gf r.\nProof. paco_cofix_auto; repeat (left; do 5 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco4_mult: forall r,\n  paco4 gf (paco4 gf r) <4= paco4 gf r.\nProof. intros; eapply paco4_mult_strong, paco4_mon; eauto. Qed.\n\nTheorem paco4_fold: forall r,\n  gf (upaco4 gf r) <4= paco4 gf r.\nProof. intros; econstructor; [ |eauto]; eauto. Qed.\n\nTheorem paco4_unfold: forall (MON: monotone4 gf) r,\n  paco4 gf r <4= gf (upaco4 gf r).\nProof. unfold monotone4; intros; destruct PR; eauto. Qed.\n\nEnd Arg4_1.\n\nHint Unfold monotone4.\nHint Resolve paco4_fold.\n\nArguments paco4_acc            [ T0 T1 T2 T3 ].\nArguments paco4_mon            [ T0 T1 T2 T3 ].\nArguments paco4_mult_strong    [ T0 T1 T2 T3 ].\nArguments paco4_mult           [ T0 T1 T2 T3 ].\nArguments paco4_fold           [ T0 T1 T2 T3 ].\nArguments paco4_unfold         [ T0 T1 T2 T3 ].\n\nInstance paco4_inst  T0 T1 T2 T3 (gf : rel4 T0 T1 T2 T3->_) r x0 x1 x2 x3 : paco_class (paco4 gf r x0 x1 x2 x3) :=\n{ pacoacc    := paco4_acc gf;\n  pacomult   := paco4_mult gf;\n  pacofold   := paco4_fold gf;\n  pacounfold := paco4_unfold gf }.\n\n(** 2 Mutual Coinduction *)\n\nSection Arg4_2.\n\nDefinition monotone4_2 T0 T1 T2 T3 (gf: rel4 T0 T1 T2 T3 -> rel4 T0 T1 T2 T3 -> rel4 T0 T1 T2 T3) :=\n  forall x0 x1 x2 x3 r_0 r_1 r'_0 r'_1 (IN: gf r_0 r_1 x0 x1 x2 x3) (LE_0: r_0 <4= r'_0)(LE_1: r_1 <4= r'_1), gf r'_0 r'_1 x0 x1 x2 x3.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.\nVariable gf_0 gf_1 : rel4 T0 T1 T2 T3 -> rel4 T0 T1 T2 T3 -> rel4 T0 T1 T2 T3.\nArguments gf_0 : clear implicits.\nArguments gf_1 : clear implicits.\n\nTheorem paco4_2_0_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_0 <4= rr) (CIH: l <_paco_4= rr), l <_paco_4= paco4_2_0 gf_0 gf_1 rr r_1),\n  l <4= paco4_2_0 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco4_2_0 gf_0 gf_1 (r_0 \\4/ l) r_1 x0 x1 x2 x3) by eauto.\n  clear PR; repeat (try left; do 5 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco4_2_1_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_1 <4= rr) (CIH: l <_paco_4= rr), l <_paco_4= paco4_2_1 gf_0 gf_1 r_0 rr),\n  l <4= paco4_2_1 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco4_2_1 gf_0 gf_1 r_0 (r_1 \\4/ l) x0 x1 x2 x3) by eauto.\n  clear PR; repeat (try left; do 5 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco4_2_0_mon: monotone4_2 (paco4_2_0 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 5 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco4_2_1_mon: monotone4_2 (paco4_2_1 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 5 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco4_2_0_mult_strong: forall r_0 r_1,\n  paco4_2_0 gf_0 gf_1 (upaco4_2_0 gf_0 gf_1 r_0 r_1) (upaco4_2_1 gf_0 gf_1 r_0 r_1) <4= paco4_2_0 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 5 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco4_2_1_mult_strong: forall r_0 r_1,\n  paco4_2_1 gf_0 gf_1 (upaco4_2_0 gf_0 gf_1 r_0 r_1) (upaco4_2_1 gf_0 gf_1 r_0 r_1) <4= paco4_2_1 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 5 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco4_2_0_mult: forall r_0 r_1,\n  paco4_2_0 gf_0 gf_1 (paco4_2_0 gf_0 gf_1 r_0 r_1) (paco4_2_1 gf_0 gf_1 r_0 r_1) <4= paco4_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco4_2_0_mult_strong, paco4_2_0_mon; eauto. Qed.\n\nCorollary paco4_2_1_mult: forall r_0 r_1,\n  paco4_2_1 gf_0 gf_1 (paco4_2_0 gf_0 gf_1 r_0 r_1) (paco4_2_1 gf_0 gf_1 r_0 r_1) <4= paco4_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco4_2_1_mult_strong, paco4_2_1_mon; eauto. Qed.\n\nTheorem paco4_2_0_fold: forall r_0 r_1,\n  gf_0 (upaco4_2_0 gf_0 gf_1 r_0 r_1) (upaco4_2_1 gf_0 gf_1 r_0 r_1) <4= paco4_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco4_2_1_fold: forall r_0 r_1,\n  gf_1 (upaco4_2_0 gf_0 gf_1 r_0 r_1) (upaco4_2_1 gf_0 gf_1 r_0 r_1) <4= paco4_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco4_2_0_unfold: forall (MON: monotone4_2 gf_0) (MON: monotone4_2 gf_1) r_0 r_1,\n  paco4_2_0 gf_0 gf_1 r_0 r_1 <4= gf_0 (upaco4_2_0 gf_0 gf_1 r_0 r_1) (upaco4_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone4_2; intros; destruct PR; eauto. Qed.\n\nTheorem paco4_2_1_unfold: forall (MON: monotone4_2 gf_0) (MON: monotone4_2 gf_1) r_0 r_1,\n  paco4_2_1 gf_0 gf_1 r_0 r_1 <4= gf_1 (upaco4_2_0 gf_0 gf_1 r_0 r_1) (upaco4_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone4_2; intros; destruct PR; eauto. Qed.\n\nEnd Arg4_2.\n\nHint Unfold monotone4_2.\nHint Resolve paco4_2_0_fold.\nHint Resolve paco4_2_1_fold.\n\nArguments paco4_2_0_acc            [ T0 T1 T2 T3 ].\nArguments paco4_2_1_acc            [ T0 T1 T2 T3 ].\nArguments paco4_2_0_mon            [ T0 T1 T2 T3 ].\nArguments paco4_2_1_mon            [ T0 T1 T2 T3 ].\nArguments paco4_2_0_mult_strong    [ T0 T1 T2 T3 ].\nArguments paco4_2_1_mult_strong    [ T0 T1 T2 T3 ].\nArguments paco4_2_0_mult           [ T0 T1 T2 T3 ].\nArguments paco4_2_1_mult           [ T0 T1 T2 T3 ].\nArguments paco4_2_0_fold           [ T0 T1 T2 T3 ].\nArguments paco4_2_1_fold           [ T0 T1 T2 T3 ].\nArguments paco4_2_0_unfold         [ T0 T1 T2 T3 ].\nArguments paco4_2_1_unfold         [ T0 T1 T2 T3 ].\n\nInstance paco4_2_0_inst  T0 T1 T2 T3 (gf_0 gf_1 : rel4 T0 T1 T2 T3->_) r_0 r_1 x0 x1 x2 x3 : paco_class (paco4_2_0 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3) :=\n{ pacoacc    := paco4_2_0_acc gf_0 gf_1;\n  pacomult   := paco4_2_0_mult gf_0 gf_1;\n  pacofold   := paco4_2_0_fold gf_0 gf_1;\n  pacounfold := paco4_2_0_unfold gf_0 gf_1 }.\n\nInstance paco4_2_1_inst  T0 T1 T2 T3 (gf_0 gf_1 : rel4 T0 T1 T2 T3->_) r_0 r_1 x0 x1 x2 x3 : paco_class (paco4_2_1 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3) :=\n{ pacoacc    := paco4_2_1_acc gf_0 gf_1;\n  pacomult   := paco4_2_1_mult gf_0 gf_1;\n  pacofold   := paco4_2_1_fold gf_0 gf_1;\n  pacounfold := paco4_2_1_unfold gf_0 gf_1 }.\n\n(** 3 Mutual Coinduction *)\n\nSection Arg4_3.\n\nDefinition monotone4_3 T0 T1 T2 T3 (gf: rel4 T0 T1 T2 T3 -> rel4 T0 T1 T2 T3 -> rel4 T0 T1 T2 T3 -> rel4 T0 T1 T2 T3) :=\n  forall x0 x1 x2 x3 r_0 r_1 r_2 r'_0 r'_1 r'_2 (IN: gf r_0 r_1 r_2 x0 x1 x2 x3) (LE_0: r_0 <4= r'_0)(LE_1: r_1 <4= r'_1)(LE_2: r_2 <4= r'_2), gf r'_0 r'_1 r'_2 x0 x1 x2 x3.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.\nVariable gf_0 gf_1 gf_2 : rel4 T0 T1 T2 T3 -> rel4 T0 T1 T2 T3 -> rel4 T0 T1 T2 T3 -> rel4 T0 T1 T2 T3.\nArguments gf_0 : clear implicits.\nArguments gf_1 : clear implicits.\nArguments gf_2 : clear implicits.\n\nTheorem paco4_3_0_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_0 <4= rr) (CIH: l <_paco_4= rr), l <_paco_4= paco4_3_0 gf_0 gf_1 gf_2 rr r_1 r_2),\n  l <4= paco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco4_3_0 gf_0 gf_1 gf_2 (r_0 \\4/ l) r_1 r_2 x0 x1 x2 x3) by eauto.\n  clear PR; repeat (try left; do 5 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco4_3_1_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_1 <4= rr) (CIH: l <_paco_4= rr), l <_paco_4= paco4_3_1 gf_0 gf_1 gf_2 r_0 rr r_2),\n  l <4= paco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco4_3_1 gf_0 gf_1 gf_2 r_0 (r_1 \\4/ l) r_2 x0 x1 x2 x3) by eauto.\n  clear PR; repeat (try left; do 5 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco4_3_2_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_2 <4= rr) (CIH: l <_paco_4= rr), l <_paco_4= paco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 rr),\n  l <4= paco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 (r_2 \\4/ l) x0 x1 x2 x3) by eauto.\n  clear PR; repeat (try left; do 5 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco4_3_0_mon: monotone4_3 (paco4_3_0 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 5 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco4_3_1_mon: monotone4_3 (paco4_3_1 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 5 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco4_3_2_mon: monotone4_3 (paco4_3_2 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 5 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco4_3_0_mult_strong: forall r_0 r_1 r_2,\n  paco4_3_0 gf_0 gf_1 gf_2 (upaco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <4= paco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 5 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco4_3_1_mult_strong: forall r_0 r_1 r_2,\n  paco4_3_1 gf_0 gf_1 gf_2 (upaco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <4= paco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 5 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco4_3_2_mult_strong: forall r_0 r_1 r_2,\n  paco4_3_2 gf_0 gf_1 gf_2 (upaco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <4= paco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 5 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco4_3_0_mult: forall r_0 r_1 r_2,\n  paco4_3_0 gf_0 gf_1 gf_2 (paco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <4= paco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco4_3_0_mult_strong, paco4_3_0_mon; eauto. Qed.\n\nCorollary paco4_3_1_mult: forall r_0 r_1 r_2,\n  paco4_3_1 gf_0 gf_1 gf_2 (paco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <4= paco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco4_3_1_mult_strong, paco4_3_1_mon; eauto. Qed.\n\nCorollary paco4_3_2_mult: forall r_0 r_1 r_2,\n  paco4_3_2 gf_0 gf_1 gf_2 (paco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <4= paco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco4_3_2_mult_strong, paco4_3_2_mon; eauto. Qed.\n\nTheorem paco4_3_0_fold: forall r_0 r_1 r_2,\n  gf_0 (upaco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <4= paco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco4_3_1_fold: forall r_0 r_1 r_2,\n  gf_1 (upaco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <4= paco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco4_3_2_fold: forall r_0 r_1 r_2,\n  gf_2 (upaco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <4= paco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco4_3_0_unfold: forall (MON: monotone4_3 gf_0) (MON: monotone4_3 gf_1) (MON: monotone4_3 gf_2) r_0 r_1 r_2,\n  paco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 <4= gf_0 (upaco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone4_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco4_3_1_unfold: forall (MON: monotone4_3 gf_0) (MON: monotone4_3 gf_1) (MON: monotone4_3 gf_2) r_0 r_1 r_2,\n  paco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 <4= gf_1 (upaco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone4_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco4_3_2_unfold: forall (MON: monotone4_3 gf_0) (MON: monotone4_3 gf_1) (MON: monotone4_3 gf_2) r_0 r_1 r_2,\n  paco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 <4= gf_2 (upaco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone4_3; intros; destruct PR; eauto. Qed.\n\nEnd Arg4_3.\n\nHint Unfold monotone4_3.\nHint Resolve paco4_3_0_fold.\nHint Resolve paco4_3_1_fold.\nHint Resolve paco4_3_2_fold.\n\nArguments paco4_3_0_acc            [ T0 T1 T2 T3 ].\nArguments paco4_3_1_acc            [ T0 T1 T2 T3 ].\nArguments paco4_3_2_acc            [ T0 T1 T2 T3 ].\nArguments paco4_3_0_mon            [ T0 T1 T2 T3 ].\nArguments paco4_3_1_mon            [ T0 T1 T2 T3 ].\nArguments paco4_3_2_mon            [ T0 T1 T2 T3 ].\nArguments paco4_3_0_mult_strong    [ T0 T1 T2 T3 ].\nArguments paco4_3_1_mult_strong    [ T0 T1 T2 T3 ].\nArguments paco4_3_2_mult_strong    [ T0 T1 T2 T3 ].\nArguments paco4_3_0_mult           [ T0 T1 T2 T3 ].\nArguments paco4_3_1_mult           [ T0 T1 T2 T3 ].\nArguments paco4_3_2_mult           [ T0 T1 T2 T3 ].\nArguments paco4_3_0_fold           [ T0 T1 T2 T3 ].\nArguments paco4_3_1_fold           [ T0 T1 T2 T3 ].\nArguments paco4_3_2_fold           [ T0 T1 T2 T3 ].\nArguments paco4_3_0_unfold         [ T0 T1 T2 T3 ].\nArguments paco4_3_1_unfold         [ T0 T1 T2 T3 ].\nArguments paco4_3_2_unfold         [ T0 T1 T2 T3 ].\n\nInstance paco4_3_0_inst  T0 T1 T2 T3 (gf_0 gf_1 gf_2 : rel4 T0 T1 T2 T3->_) r_0 r_1 r_2 x0 x1 x2 x3 : paco_class (paco4_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3) :=\n{ pacoacc    := paco4_3_0_acc gf_0 gf_1 gf_2;\n  pacomult   := paco4_3_0_mult gf_0 gf_1 gf_2;\n  pacofold   := paco4_3_0_fold gf_0 gf_1 gf_2;\n  pacounfold := paco4_3_0_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco4_3_1_inst  T0 T1 T2 T3 (gf_0 gf_1 gf_2 : rel4 T0 T1 T2 T3->_) r_0 r_1 r_2 x0 x1 x2 x3 : paco_class (paco4_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3) :=\n{ pacoacc    := paco4_3_1_acc gf_0 gf_1 gf_2;\n  pacomult   := paco4_3_1_mult gf_0 gf_1 gf_2;\n  pacofold   := paco4_3_1_fold gf_0 gf_1 gf_2;\n  pacounfold := paco4_3_1_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco4_3_2_inst  T0 T1 T2 T3 (gf_0 gf_1 gf_2 : rel4 T0 T1 T2 T3->_) r_0 r_1 r_2 x0 x1 x2 x3 : paco_class (paco4_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3) :=\n{ pacoacc    := paco4_3_2_acc gf_0 gf_1 gf_2;\n  pacomult   := paco4_3_2_mult gf_0 gf_1 gf_2;\n  pacofold   := paco4_3_2_fold gf_0 gf_1 gf_2;\n  pacounfold := paco4_3_2_unfold gf_0 gf_1 gf_2 }.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/concurrency/paco_old/src/paco4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.24896264174489585}}
{"text": "Require Import AbstractLogic.\nRequire Import BasicMachineTypes.\nRequire Import Certificates.\nRequire Import StoreIface.\nRequire Import GenericAnnotationIface.\nRequire Import AnnotationIface.\nRequire Import ResourceAlgebra.\nRequire Import List.\nRequire FMapInterface.\n\nModule Type VERIFIER_ANNOTATIONS\n  (VA_B    : BASICS)\n  (VA_AL   : ABSTRACT_LOGIC VA_B)\n  (VA_CERT : CERTIFICATE with Definition asn := VA_AL.formula).\n\nInductive constantpool_additional : Set :=\n| cpae_static_method : VA_AL.formula -> VA_AL.formula -> VA_AL.formula -> constantpool_additional\n| cpae_static_field\n| cpae_instantiable_class\n| cpae_instance_field\n| cpae_instance_method : VA_AL.formula -> VA_AL.formula -> VA_AL.formula -> constantpool_additional\n| cpae_instance_special_method : VA_AL.formula -> VA_AL.formula -> VA_AL.formula -> constantpool_additional\n| cpae_interface_method : VA_AL.formula -> VA_AL.formula -> VA_AL.formula -> constantpool_additional\n| cpae_classref.\n\nDeclare Module ConstantPoolAdditional : STORE with Definition key := VA_B.ConstantPoolRef.t\n                                              with Definition Key.eq := VA_B.ConstantPoolRef.eq\n                                              with Definition object := constantpool_additional.\n\nDeclare Module ProofTable : STORE with Definition key := (VA_AL.formula * VA_AL.formula)%type\n                                  with Definition object := VA_AL.prf_term.\n\n\nDefinition method_specification' := (VA_AL.formula * VA_AL.formula * VA_AL.formula)%type.\nDefinition method_specification := method_specification'.\nRecord method_annotation' : Set := {\n  method_spec : method_specification'\n; grants : option (res_expr VA_B.Classname.t)\n}.\n\nDefinition code_annotation := VA_CERT.Cert.t.\nDefinition method_annotation := method_annotation'.\nDefinition class_annotation := (ProofTable.t * ConstantPoolAdditional.t)%type.\n\nParameter method_annotation_eqdec : forall (a1 a2:method_annotation), {a1 = a2} + {a1 <> a2}.\n\nDefinition trivial_method_annotation := Build_method_annotation' \n  (VA_AL.trivial, VA_AL.trivial, VA_AL.trivial)\n  None.\n\nModule GA <: GENERIC_ANNOTATION VA_B.\n  Module A <: ANNOTATION VA_B.\n\n    Definition code_annotation := VA_CERT.Cert.t.\n    Definition method_annotation := method_annotation'.\n    Definition grants := grants.\n    Definition class_annotation := (ProofTable.t * ConstantPoolAdditional.t)%type.\n\n    Definition trivial_method_annotation := trivial_method_annotation.\n  End A.\n\n  Definition method_specification := method_specification'.\n  Definition method_spec := method_spec.\nEnd GA.\n\nEnd VERIFIER_ANNOTATIONS.\n\n(*\n   Local Variables:\n   coq-prog-args: (\"-emacs-U\" \"-I\" \"..\" \"-R\" \"../ill\" \"ILL\" \"-R\" \".\" \"Verifier\")\n   End:\n   *)\n", "meta": {"author": "bacam", "repo": "coqjvm", "sha": "cabb813e3ad8263685b4198eea68f1505ff92947", "save_path": "github-repos/coq/bacam-coqjvm", "path": "github-repos/coq/bacam-coqjvm/coqjvm-cabb813e3ad8263685b4198eea68f1505ff92947/coqjvm/verifier/VerifierAnnotationsIface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.24896264174489582}}
{"text": "Require Import msl.msl_standard.\nRequire Import msl.Coqlib2.\nRequire Import veric.shares.\n\nSection UNPROVABLE.\n\nVariable wishes_eq_horses : False.\n\nLemma unrel_glb:\n forall a b,\n    Share.unrel a b = Share.unrel a (Share.glb a b).\ncontradiction wishes_eq_horses.\nQed.\n\nLemma share_rel_unrel':\n  forall r sh,\n    Share.rel r (Share.unrel r sh) = Share.glb r sh.\nProof.\ncontradiction wishes_eq_horses.\nQed.\n\nLemma share_sub_Lsh:\nforall sh, identity (Share.unrel Share.Rsh sh) -> join_sub sh Share.Lsh.\nProof.\n intros.\n rewrite (Share.decompose_Rsh sh) in H.\n remember (decompose sh).\n symmetry in Heqp. destruct p as [sh1 sh2].\n simpl in H.\n apply identity_share_bot in H. subst.\n generalize (top_correct' sh1);intro.\n destruct H.\n exists (Share.recompose (x, Share.bot)).\n rewrite Share.Lsh_recompose.\n assert (sh = Share.recompose (sh1, Share.bot)).\n  rewrite <- Heqp. rewrite Share.recompose_decompose. trivial.\n rewrite H0.\n eapply Share.decompose_join.\n rewrite Share.decompose_recompose. f_equal.\n rewrite Share.decompose_recompose. f_equal.\n rewrite Share.decompose_recompose. f_equal.\n split. trivial.\n split. apply Share.glb_bot. apply Share.lub_bot.\nQed.\n\nLemma join_splice2_aux:\nforall a1 a2 a3 b1 b2 b3,\nShare.lub (Share.rel Share.Lsh (Share.lub a1 a2)) (Share.rel Share.Rsh (Share.lub b1 b2))\n= Share.lub (Share.rel Share.Lsh a3) (Share.rel Share.Rsh b3) ->\nShare.lub a1 a2 = a3 /\\ Share.lub b1 b2 = b3.\nProof with try tauto.\n intros. rewrite Share.lub_rel_recompose in H.\n generalize (Share.decompose_recompose (Share.lub a1 a2, Share.lub b1 b2));intro.\n rewrite H in H0.\n rewrite Share.lub_rel_recompose in H0.\n rewrite Share.decompose_recompose in H0.\n split;congruence.\nQed.\n\nLemma share_rel_unrel:\n  forall r sh,\n    join_sub sh r ->\n    Share.rel r (Share.unrel r sh) = sh.\nProof.\nintros.\nrewrite share_rel_unrel'.\ndestruct H as [a [H H0]].\nsubst r.\nrewrite Share.glb_commute.\nrewrite Share.distrib1.\nrewrite H.\nrewrite Share.lub_bot.\napply Share.glb_idem.\nQed.\n\nLemma glb_rel_Lsh_Rsh:\n forall a b, Share.glb (Share.rel Share.Lsh a) (Share.rel Share.Rsh b) = Share.bot.\nProof.\nintros.\nassert (H := rel_leq Share.Lsh a).\nassert (H0 := rel_leq Share.Rsh b).\napply leq_join_sub in H.\napply leq_join_sub in H0.\nforget (Share.rel Share.Lsh a) as aL.\nforget (Share.rel Share.Rsh b) as bR.\napply Share.ord_antisym; [ | apply Share.bot_correct].\nrewrite <- glb_Lsh_Rsh.\nforget Share.Lsh as L.\nforget Share.Rsh as R.\napply glb_less_both; auto.\nQed.\n\nLemma glb_Rsh_rel_Lsh_sh:\n forall sh,\n  Share.glb Share.Rsh (Share.rel Share.Lsh sh) = Share.bot.\nProof.\nintros.\ndestruct (Share.split Share.top) eqn:?.\nunfold Share.Rsh, Share.Lsh. rewrite Heqp; simpl.\nrewrite Share.glb_commute.\ndestruct (rel_join t t t0 _ (split_join _ _ _ Heqp)).\nclear - H Heqp.\npose proof (rel_leq t t0).\nrewrite <- leq_join_sub in H0.\nrewrite Share.ord_spec1 in H0.\nrewrite H0 in H.\nrewrite <- Share.glb_assoc in H.\nrewrite <- Share.rel_preserves_glb in H.\npose proof (rel_leq t (Share.glb t t0)).\napply leq_join_sub in H1.\napply Share.ord_spec1 in H1. rewrite <- H1 in H.\nclear H1.\npose proof bot_identity. rewrite <- H in H1.\napply (rel_nontrivial) in H1.\ndestruct H1.\napply split_nontrivial' in Heqp; auto.\napply identity_share_bot in Heqp.\napply Share.nontrivial in Heqp; contradiction.\nclear H.\napply identity_share_bot in H1.\nclear - H1.\npose proof (rel_leq t sh).\nforget (Share.rel t sh) as b.\ndestruct H as [a [? ?]].\nsubst t.\nrewrite Share.glb_commute in H1; rewrite Share.distrib1 in H1.\nrewrite Share.glb_commute in H1.\npose proof (Share.lub_upper1 (Share.glb b t0) (Share.glb t0 a)).\nrewrite H1 in H0.\napply Share.ord_antisym; auto.\napply Share.bot_correct.\nQed.\n\nLemma right_nonempty_readable:\n  forall rsh sh, sepalg.nonidentity sh <->\n     readable_share (Share.splice rsh sh).\nProof.\nintros.\nunfold readable_share, Share.splice.\nunfold nonempty_share,nonidentity.\nassert (identity sh <-> identity (Share.glb Share.Rsh (Share.lub (Share.rel Share.Lsh rsh) (Share.rel Share.Rsh sh))));\n  [ | intuition].\nsplit; intro.\n*\napply identity_share_bot in H. subst.\nrewrite Share.rel_bot1.\nrewrite Share.lub_bot.\nrewrite glb_Rsh_rel_Lsh_sh.\napply bot_identity.\n*\nrewrite Share.distrib1 in H.\nrewrite glb_Rsh_rel_Lsh_sh in H.\nrewrite Share.lub_commute, Share.lub_bot in H.\nassert (identity (Share.glb (Share.rel Share.Rsh Share.top) (Share.rel Share.Rsh sh)))\n  by (rewrite Share.rel_top1; auto).\nclear H.\nrewrite <- Share.rel_preserves_glb in H0.\nrewrite Share.glb_commute, Share.glb_top in H0.\napply rel_nontrivial in H0.\ndestruct H0; auto.\nunfold Share.Rsh in H.\ndestruct (Share.split Share.top) eqn:?; simpl in *.\napply split_nontrivial' in Heqp; auto.\napply top_share_nonidentity in Heqp.\ncontradiction.\nQed.\n\nLemma writable_share_right: forall sh, writable_share sh -> Share.unrel Share.Rsh sh = Share.top.\nProof.\n intros.\n apply Share.contains_Rsh_e.\n apply H.\nQed.\n\nLemma unrel_bot:\n forall sh, nonidentity sh -> Share.unrel sh Share.bot = Share.bot.\nProof.\nintros.\nrewrite <- (Share.rel_bot1 sh) at 1.\nrewrite Share.unrel_rel; auto.\nQed.\n\nLemma join_splice2_aux1:\n  forall a1 a2 b1 b2,\n  Share.lub (Share.rel Share.Lsh (Share.glb a1 a2)) (Share.rel Share.Rsh (Share.glb b1 b2)) = Share.bot ->\n  Share.glb a1 a2 = Share.bot /\\ Share.glb b1 b2 = Share.bot.\nProof. intros.\n  rewrite !Share.rel_preserves_glb in H.\n  apply lub_bot_e in H; destruct H.\n  rewrite <- Share.rel_preserves_glb in H, H0.\n  pose proof (rel_nontrivial Share.Lsh (Share.glb a1 a2)).\n  rewrite H in H1. specialize (H1 bot_identity). clear H.\n  pose proof (rel_nontrivial Share.Rsh (Share.glb b1 b2)).\n  rewrite H0 in H. specialize (H bot_identity). clear H0.\n  destruct H1. contradiction (Lsh_nonidentity H0).\n  destruct H. contradiction (Rsh_nonidentity H).\n  apply identity_share_bot in H.\n  apply identity_share_bot in H0.\n  auto.\nQed.\n\nLemma join_splice:\n  forall a1 a2 a3 b1 b2 b3,\n sepalg.join a1 a2 a3 ->\n sepalg.join b1 b2 b3 ->\n sepalg.join (Share.splice a1 b1)  (Share.splice a2 b2)  (Share.splice a3 b3).\nProof.\nintros.\nunfold Share.splice.\ndestruct H, H0.\nsplit.\n*\nrewrite Share.distrib1.\ndo 2 rewrite (Share.glb_commute (Share.lub _ _)).\nrewrite Share.distrib1.\nrewrite Share.distrib1.\nrewrite !(Share.glb_commute (Share.rel _ a2)).\nrewrite !(Share.glb_commute (Share.rel _ b2)).\nrewrite <- !Share.rel_preserves_glb.\nrewrite H,H0.\nrewrite !Share.rel_bot1.\nrewrite (Share.lub_commute Share.bot).\nrewrite !Share.lub_bot.\nrewrite Share.glb_commute.\nrewrite !glb_rel_Lsh_Rsh.\napply Share.lub_bot.\n*\nsubst a3 b3.\nrewrite !Share.rel_preserves_lub.\nforget (Share.rel Share.Lsh a1) as La1.\nforget (Share.rel Share.Rsh b1) as Rb1.\nforget (Share.rel Share.Lsh a2) as La2.\nforget (Share.rel Share.Rsh b2) as Rb2.\nrewrite !Share.lub_assoc.\nf_equal.\nrewrite Share.lub_commute.\nrewrite !Share.lub_assoc.\nf_equal.\napply Share.lub_commute.\nQed.\n\nLemma splice_bot2:\n forall sh, Share.splice sh Share.bot = Share.rel Share.Lsh sh.\nProof.\nintros.\nunfold Share.splice.\nrewrite Share.rel_bot1.\nrewrite Share.lub_bot.\nauto.\nQed.\n\nLemma splice_unrel_unrel:\n  forall sh,\n   Share.splice (Share.unrel Share.Lsh sh) (Share.unrel Share.Rsh sh) = sh.\nProof.\nintros.\nunfold Share.splice.\nrewrite !share_rel_unrel'.\nrewrite share_distrib2'.\nrewrite Share.lub_idem.\nrewrite lub_Lsh_Rsh.\nrewrite (Share.glb_commute Share.top).\nrewrite Share.glb_top.\nrewrite <- Share.glb_assoc.\nrewrite (Share.lub_commute sh).\nrewrite share_distrib1'.\nrewrite (Share.glb_commute Share.Rsh).\nrewrite glb_Lsh_Rsh.\nrewrite (Share.lub_commute Share.bot), Share.lub_bot.\nrewrite Share.glb_idem.\nrewrite (Share.glb_commute sh).\nrewrite <- Share.lub_assoc.\nrewrite Share.glb_commute.\nrewrite Share.lub_commute.\nrewrite Share.glb_absorb.\nauto.\nQed.\n\nLemma join_splice2:\n  forall a1 a2 a3 b1 b2 b3 : Share.t,\n  join (Share.splice a1 b1) (Share.splice a2 b2) (Share.splice a3 b3) ->\n  join a1 a2 a3 /\\ join b1 b2 b3.\nProof.\nintros.\nunfold Share.splice in H.\ndestruct H.\nunfold join, Share.Join_ba.\nassert ((Share.glb a1 a2 = Share.bot /\\ Share.glb b1 b2 = Share.bot)\n         /\\ (Share.lub a1 a2 = a3 /\\ Share.lub b1 b2 = b3)); [ | intuition].\nsplit.\n*\nclear - H.\nrewrite share_distrib1' in H.\nrewrite (Share.lub_commute (Share.glb _ _)) in H.\nrewrite Share.lub_assoc in H.\nrewrite <- (Share.lub_assoc (Share.glb (Share.rel Share.Lsh _) _)) in H.\nrewrite (Share.lub_commute (Share.lub _ _)) in H.\nrewrite <- Share.lub_assoc in H.\nrewrite <- !Share.rel_preserves_glb in H.\nrewrite (Share.glb_commute (Share.rel Share.Rsh _)) in H.\nrewrite !glb_rel_Lsh_Rsh in H.\nrewrite (Share.lub_commute Share.bot), !Share.lub_bot in H.\nrewrite Share.lub_commute in H.\napply join_splice2_aux1; auto.\n*\nclear - H0.\nrewrite Share.lub_assoc in H0.\nrewrite (Share.lub_commute (Share.rel Share.Rsh _)) in H0.\nrewrite <- !Share.lub_assoc in H0.\nrewrite <- Share.rel_preserves_lub in H0.\nrewrite Share.lub_assoc in H0.\nrewrite <- Share.rel_preserves_lub in H0.\nrewrite (Share.lub_commute b2) in H0.\napply join_splice2_aux; auto.\nQed.\n\nLemma nonidentity_rel_Lsh: forall t, nonidentity (Share.rel Share.Lsh t) -> nonidentity t.\nProof.\n  intros.\n  rewrite <- splice_bot2 in H.\n  intro.\n  apply H; clear H.\n  intros ? ? ?.\n  rewrite <- (splice_unrel_unrel a), <- (splice_unrel_unrel b) in H |- *.\n  forget (Share.unrel Share.Lsh a) as sh0.\n  forget (Share.unrel Share.Rsh a) as sh1.\n  forget (Share.unrel Share.Lsh b) as sh2.\n  forget (Share.unrel Share.Rsh b) as sh3.\n  apply join_splice2 in H.\n  destruct H.\n  apply H0 in H.\n  apply bot_identity in H1.\n  subst.\n  auto.\nQed.\n\nLemma readable_share_unrel_Rsh: forall sh, readable_share sh <-> nonunit (Share.unrel Share.Rsh sh).\nunfold readable_share in *.\nProof.\nintros.\nunfold nonempty_share.\ntransitivity (nonidentity (Share.unrel Share.Rsh sh)).\nunfold nonidentity.\nsplit; intro; contradict H.\napply identity_share_bot in H.\nrewrite <- share_rel_unrel'.\nrewrite H.\nrewrite Share.rel_bot1.\napply bot_identity.\nrewrite <- share_rel_unrel' in H.\napply rel_nontrivial in H.\ndestruct H; auto.\nelimtype False.\napply identity_share_bot in H.\nunfold Share.Rsh in H.\ndestruct (Share.split Share.top) eqn:?. simpl in H. subst.\napply split_nontrivial' in Heqp.\napply identity_share_bot in Heqp.\napply Share.nontrivial; auto.\nright.\napply bot_identity.\nsplit.\napply nonidentity_nonunit.\nintro.\nhnf in H|-*; intro.\napply identity_share_bot in H0.\nrewrite H0 in H.\napply (H Share.top).\nred.\napply bot_join_eq.\nQed.\n\nEnd UNPROVABLE.\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/veric/splice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.24891069873124744}}
{"text": "Require Import Lia.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Event.\nRequire Import Time.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\n\nRequire Import AMemory.\nRequire Import ALocal.\nRequire Import AThread.\n\nSet Implicit Arguments.\n\n\nLemma promise_step_promise_consistent\n      lc1 mem1 loc from to msg lc2 mem2 kind\n      (STEP: ALocal.promise_step lc1 mem1 loc from to msg lc2 mem2 kind)\n      (CONS: Local.promise_consistent lc2):\n  Local.promise_consistent lc1.\nProof.\n  inv STEP. ii.\n  destruct (Memory.op_kind_is_cancel kind) eqn:KIND.\n  - destruct kind; ss. inv PROMISE.\n    destruct (Memory.get loc0 ts promises2) as [[]|] eqn:GET2.\n    + dup GET2. revert GET0.\n      erewrite Memory.remove_o; eauto. condtac; ss. i.\n      rewrite PROMISE0 in *. inv GET0. eauto.\n    + revert GET2. erewrite Memory.remove_o; eauto. condtac; ss; i.\n      * des. subst. exploit Memory.remove_get0; eauto. i. des. congr.\n      * congr.\n  - exploit AMemory.promise_get1_promise; eauto. i. des.\n    inv MSG_LE. exploit CONS; eauto.\nQed.\n\nLemma read_step_promise_consistent\n      lc1 mem1 loc to val released ord lc2\n      (STEP: Local.read_step lc1 mem1 loc to val released ord lc2)\n      (CONS: Local.promise_consistent lc2):\n  Local.promise_consistent lc1.\nProof.\n  inv STEP. ii. exploit CONS; eauto. i.\n  eapply TimeFacts.le_lt_lt; eauto. ss.\n  etrans; [|apply Time.join_l]. etrans; [|apply Time.join_l]. refl.\nQed.\n\nLemma fulfill_unset_promises\n      loc from ts msg\n      promises1 promises2\n      l t f m\n      (FULFILL: Memory.remove promises1 loc from ts msg promises2)\n      (TH1: Memory.get l t promises1 = Some (f, m))\n      (TH2: Memory.get l t promises2 = None):\n  l = loc /\\ t = ts /\\ f = from /\\ Message.le msg m.\nProof.\n  revert TH2. erewrite Memory.remove_o; eauto. condtac; ss; [|congr].\n  des. subst. exploit Memory.remove_get0; eauto. i. des.\n  rewrite GET in TH1. inv TH1.\n  esplits; eauto. refl.\nQed.\n\nLemma write_step_promise_consistent\n      lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n      (STEP: ALocal.write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n      (CONS: Local.promise_consistent lc2):\n  Local.promise_consistent lc1.\nProof.\n  inv STEP. inv WRITE. ii.\n  exploit AMemory.promise_get1_promise; eauto.\n  { inv PROMISE; ss. }\n  i. des. inv MSG_LE.\n  destruct (Memory.get loc0 ts promises2) as [[]|] eqn:X.\n  - dup X. revert X0.\n    erewrite Memory.remove_o; eauto. condtac; ss; i.\n    rewrite GET in *. inv X0.\n    apply CONS in X. eapply TimeFacts.le_lt_lt; eauto.\n    s. etrans; [|apply Time.join_l]. refl.\n  - exploit fulfill_unset_promises; eauto. i. des. subst.\n    apply WRITABLE.\nQed.\n\nLemma fence_step_promise_consistent\n      lc1 sc1 mem1 ordr ordw lc2 sc2\n      (STEP: Local.fence_step lc1 sc1 ordr ordw lc2 sc2)\n      (WF: Local.wf lc1 mem1)\n      (CONS: Local.promise_consistent lc2):\n  Local.promise_consistent lc1.\nProof.\n  inv STEP. ii.\n  exploit CONS; eauto. i.\n  eapply TimeFacts.le_lt_lt; eauto.\n  cut (TView.le (Local.tview lc1)\n                (TView.write_fence_tview (TView.read_fence_tview (Local.tview lc1) ordr) sc1 ordw)).\n  { i. inv H. apply CUR. }\n  etrans.\n  - eapply TViewFacts.write_fence_tview_incr. apply WF.\n  - eapply TViewFacts.write_fence_tview_mon; try refl; try apply WF.\n    eapply TViewFacts.read_fence_tview_incr. apply WF.\nQed.\n\nLemma ordering_relaxed_dec\n      ord:\n  Ordering.le ord Ordering.relaxed \\/ Ordering.le Ordering.strong_relaxed ord.\nProof. destruct ord; auto. Qed.\n\nLemma step_promise_consistent\n      lang pf e th1 th2\n      (STEP: @AThread.step lang pf e th1 th2)\n      (CONS: Local.promise_consistent (Thread.local th2))\n      (WF1: Local.wf (Thread.local th1) (Thread.memory th1))\n      (SC1: Memory.closed_timemap (Thread.sc th1) (Thread.memory th1))\n      (MEM1: Memory.closed (Thread.memory th1)):\n  Local.promise_consistent (Thread.local th1).\nProof.\n  inv STEP; [inv STEP0|inv STEP0; inv LOCAL]; ss.\n  - eapply promise_step_promise_consistent; eauto.\n  - eapply read_step_promise_consistent; eauto.\n  - eapply write_step_promise_consistent; eauto.\n  - eapply read_step_promise_consistent; eauto.\n    eapply write_step_promise_consistent; eauto.\n  - eapply fence_step_promise_consistent; eauto.\n  - eapply fence_step_promise_consistent; eauto.\nQed.\n\nLemma rtc_all_step_promise_consistent\n      lang th1 th2\n      (STEP: rtc (@AThread.all_step lang) th1 th2)\n      (CONS: Local.promise_consistent (Thread.local th2))\n      (WF1: Local.wf (Thread.local th1) (Thread.memory th1))\n      (SC1: Memory.closed_timemap (Thread.sc th1) (Thread.memory th1))\n      (MEM1: Memory.closed (Thread.memory th1)):\n  Local.promise_consistent (Thread.local th1).\nProof.\n  revert_until STEP. induction STEP; auto. i.\n  inv H. inv USTEP. exploit AThread.step_future; eauto. i. des.\n  eapply step_promise_consistent; eauto.\nQed.\n\nLemma rtc_tau_step_promise_consistent\n      lang th1 th2\n      (STEP: rtc (@AThread.tau_step lang) th1 th2)\n      (CONS: Local.promise_consistent (Thread.local th2))\n      (WF1: Local.wf (Thread.local th1) (Thread.memory th1))\n      (SC1: Memory.closed_timemap (Thread.sc th1) (Thread.memory th1))\n      (MEM1: Memory.closed (Thread.memory th1)):\n  Local.promise_consistent (Thread.local th1).\nProof.\n  eapply rtc_all_step_promise_consistent; cycle 1; eauto.\n  eapply rtc_implies; [|eauto].\n  apply tau_union.\nQed.\n\nLemma consistent_promise_consistent\n      lang th\n      (CONS: @AThread.consistent lang th)\n      (WF: Local.wf (Thread.local th) (Thread.memory th))\n      (SC: Memory.closed_timemap (Thread.sc th) (Thread.memory th))\n      (MEM: Memory.closed (Thread.memory th)):\n  Local.promise_consistent (Thread.local th).\nProof.\n  destruct th. ss.\n  exploit Memory.cap_exists; eauto. i. des.\n  exploit Memory.cap_closed; eauto. i.\n  exploit Local.cap_wf; eauto. i.\n  exploit Memory.max_full_timemap_exists; try apply x0. i. des.\n  hexploit Memory.max_full_timemap_closed; eauto. i.\n  exploit CONS; eauto. s. i. des.\n  - inv FAILURE. des. inv FAILURE; inv STEP. inv LOCAL. inv LOCAL0.\n    hexploit rtc_tau_step_promise_consistent; try exact STEPS; eauto.\n  - hexploit rtc_tau_step_promise_consistent; try exact STEPS; eauto.\n    ii. rewrite PROMISES, Memory.bot_get in *. congr.\nQed.\n\nLemma promise_consistent_promise_read\n      lc1 mem1 loc to val ord released lc2\n      f t v r\n      (STEP: Local.read_step lc1 mem1 loc to val released ord lc2)\n      (PROMISE: Memory.get loc t (Local.promises lc1) = Some (f, Message.full v r))\n      (CONS: Local.promise_consistent lc2):\n  Time.lt to t.\nProof.\n  inv STEP. exploit CONS; eauto. s. intro x.\n  apply TimeFacts.join_lt_des in x. des.\n  apply TimeFacts.join_lt_des in AC. des.\n  revert BC0. unfold View.singleton_ur_if. condtac; ss.\n  - unfold TimeMap.singleton, LocFun.add. condtac; ss.\n  - unfold TimeMap.singleton, LocFun.add. condtac; ss.\nQed.\n\nLemma promise_consistent_promise_write\n      lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n      f t v r\n      (STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n      (PROMISE: Memory.get loc t (Local.promises lc1) = Some (f, Message.full v r))\n      (CONS: Local.promise_consistent lc2):\n  Time.le to t.\nProof.\n  destruct (Memory.get loc t (Local.promises lc2)) as [[]|] eqn:X.\n  - inv STEP. inv WRITE. ss.\n    dup X. revert X0.\n    erewrite Memory.remove_o; eauto. condtac; ss. i. guardH o.\n    exploit Memory.promise_get1_promise; try exact PROMISE; eauto.\n    { inv PROMISE0; ss. }\n    i. des. inv MSG_LE.\n    rewrite X0 in *. inv GET.\n    exploit CONS; eauto. intro x. ss.\n    apply TimeFacts.join_lt_des in x. des.\n    left. revert BC. unfold TimeMap.singleton, LocFun.add. condtac; ss.\n  - inv STEP. inv WRITE.\n    exploit Memory.promise_get1_promise; eauto.\n    { inv PROMISE0; ss. }\n    i. des. inv MSG_LE.\n    exploit fulfill_unset_promises; eauto. i. des. subst. refl.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising2-coq", "sha": "52dd46538036a7a69c132e89dd3e7698b5e2f830", "save_path": "github-repos/coq/snu-sf-promising2-coq", "path": "github-repos/coq/snu-sf-promising2-coq/promising2-coq-52dd46538036a7a69c132e89dd3e7698b5e2f830/src/attachable/APromiseConsistent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.24891068466658917}}
{"text": "From compcert Require Export Clightdefs.\nRequire Export VST.veric.base.\nRequire Export VST.veric.SeparationLogic.\nRequire Export VST.msl.Extensionality.\nRequire Export compcert.lib.Coqlib.\nRequire Export VST.msl.Coqlib2 VST.veric.coqlib4 VST.floyd.coqlib3.\nRequire Export VST.floyd.functional_base.\nImport LiftNotation.\n\nLemma force_Vint:  forall i, force_int (Vint i) = i.\nProof.  reflexivity. Qed.\nHint Rewrite force_Vint : norm.\n\nLemma is_int_dec i s v: {is_int i s v} + {~ is_int i s v}.\nProof. destruct v; simpl; try solve [right; intros N; trivial].\ndestruct i.\n+ destruct s.\n    * destruct (zle Byte.min_signed (Int.signed i0)); [| right; lia].\n      destruct (zle (Int.signed i0) Byte.max_signed). left; lia. right; lia.\n    * destruct (zle (Int.unsigned i0) Byte.max_unsigned). left; lia. right; lia.\n+ destruct s.\n    * destruct (zle (-32768) (Int.signed i0)); [| right; lia].\n      destruct (zle (Int.signed i0) 32767). left; lia. right; lia.\n    * destruct (zle (Int.unsigned i0) 65535). left; lia. right; lia.\n+ left; trivial.\n+ destruct (Int.eq_dec i0 Int.zero); subst. left; left; trivial.\n    destruct (Int.eq_dec i0 Int.one); subst. left; right; trivial.\n    right. intros N; destruct N; contradiction.\nDefined.\n\nLemma tc_val_dec t v: {tc_val t v} + {~ tc_val t v}.\nProof. destruct t; simpl.\n+ right; intros N; trivial.\n+ apply is_int_dec.\n+ apply is_long_dec.\n+ destruct f. apply is_single_dec. apply is_float_dec.\n+ destruct ((eqb_type t Ctypes.Tvoid &&\n    eqb_attr a\n      {| attr_volatile := false; attr_alignas := Some log2_sizeof_pointer |})%bool).\n  apply is_pointer_or_integer_dec.\n  apply is_pointer_or_null_dec.\n+ apply is_pointer_or_null_dec.\n+ apply is_pointer_or_null_dec.\n+ apply isptr_dec.\n+ apply isptr_dec.\nDefined.\n\nLemma sem_add_pi_ptr:\n   forall {cs: compspecs}  t p i si,\n    isptr p ->\n    match si with\n    | Signed => Int.min_signed <= i <= Int.max_signed\n    | Unsigned => 0 <= i <= Int.max_unsigned\n    end ->\n    Cop.sem_add_ptr_int cenv_cs t si p (Vint (Int.repr i)) = Some (offset_val (sizeof t * i) p).\nProof.\n  intros. destruct p; try contradiction.\n  unfold offset_val, Cop.sem_add_ptr_int.\n  unfold Cop.ptrofs_of_int, Ptrofs.of_ints, Ptrofs.of_intu, Ptrofs.of_int.\n  f_equal. f_equal. f_equal.\n  destruct si; rewrite <- ptrofs_mul_repr;  f_equal.\n  rewrite Int.signed_repr by lia; auto.\n  rewrite Int.unsigned_repr by lia; auto.\nQed.\nHint Rewrite @sem_add_pi_ptr using (solve [auto with norm]) : norm.\n\nLemma sem_cast_i2i_correct_range: forall sz s v,\n  is_int sz s v -> sem_cast_i2i sz s v = Some v.\nProof.\n  intros.\n  destruct sz, s, v; try solve [inversion H]; simpl;\n  f_equal; f_equal; try apply sign_ext_inrange; try apply zero_ext_inrange; eauto.\n  + simpl in H; destruct H; subst; reflexivity.\n  + simpl in H; destruct H; subst; reflexivity.\nQed.\nHint Rewrite sem_cast_i2i_correct_range using (solve [auto with norm]) : norm.\n\nLemma sem_cast_neutral_ptr:\n  forall p, isptr p -> sem_cast_pointer p = Some p.\nProof. intros. destruct p; try contradiction; reflexivity. Qed.\nHint Rewrite sem_cast_neutral_ptr using (solve [auto with norm]): norm.\n\nLemma sem_cast_neutral_Vint: forall v,\n  sem_cast_pointer (Vint v) = Some (Vint v).\nProof.\n  intros. reflexivity.\nQed.\nHint Rewrite sem_cast_neutral_Vint : norm.\n\nDefinition isVint v := match v with Vint _ => True | _ => False end.\n\nLemma is_int_is_Vint: forall i s v, is_int i s v -> isVint v.\nProof. intros.\n destruct i,s,v; simpl; intros; auto.\nQed.\n\nLemma is_int_I32_Vint: forall s v, is_int I32 s (Vint v).\nProof.\nintros.\nhnf. auto.\nQed.\n#[export] Hint Resolve is_int_I32_Vint : core.\n\nLemma sem_cast_neutral_int: forall v,\n  isVint v ->\n  sem_cast_pointer v = Some v.\nProof.\ndestruct v; simpl; intros; try contradiction; auto.\nQed.\n\nHint Rewrite sem_cast_neutral_int using\n  (auto;\n   match goal with H: is_int ?i ?s ?v |- isVint ?v => apply (is_int_is_Vint i s v H) end) : norm.\n\nLemma sizeof_tuchar: forall {cs: compspecs}, sizeof tuchar = 1%Z.\nProof. reflexivity. Qed.\nHint Rewrite @sizeof_tuchar: norm.\n\nHint Rewrite Z.mul_1_l Z.mul_1_r Z.add_0_l Z.add_0_r Z.sub_0_r : norm.\n\nHint Rewrite eval_id_same : norm.\nHint Rewrite eval_id_other using solve [clear; intro Hx; inversion Hx] : norm.\nHint Rewrite Int.sub_idem Int.sub_zero_l  Int.add_neg_zero : norm.\nHint Rewrite Ptrofs.sub_idem Ptrofs.sub_zero_l  Ptrofs.add_neg_zero : norm.\n\nLemma eval_expr_Etempvar:\n  forall {cs: compspecs}  i t, eval_expr (Etempvar i t) = eval_id i.\nProof. reflexivity.\nQed.\nHint Rewrite @eval_expr_Etempvar : eval.\n\nLemma eval_expr_binop: forall {cs: compspecs}  op a1 a2 t, eval_expr (Ebinop op a1 a2 t) =\n          `(eval_binop op (typeof a1) (typeof a2)) (eval_expr a1) (eval_expr a2).\nProof. reflexivity. Qed.\nHint Rewrite @eval_expr_binop : eval.\n\nLemma eval_expr_unop: forall {cs: compspecs} op a1 t, eval_expr (Eunop op a1 t) =\n          lift1 (eval_unop op (typeof a1)) (eval_expr a1).\nProof. reflexivity. Qed.\nHint Rewrite @eval_expr_unop : eval.\n\n#[export] Hint Resolve  eval_expr_Etempvar : core.\n\nLemma eval_expr_Etempvar' : forall {cs: compspecs}  i t, eval_id i = eval_expr (Etempvar i t).\nProof. intros. symmetry; auto.\nQed.\n#[export] Hint Resolve  eval_expr_Etempvar' : core.\n\nHint Rewrite Int.add_zero  Int.add_zero_l Int.sub_zero_l : norm.\nHint Rewrite Ptrofs.add_zero  Ptrofs.add_zero_l Ptrofs.sub_zero_l : norm.\n\nLemma eval_var_env_set:\n  forall i t j v (rho: environ), eval_var i t (env_set rho j v) = eval_var i t rho.\nProof. reflexivity. Qed.\nHint Rewrite eval_var_env_set : norm.\n\nLemma eval_expropt_Some: forall {cs: compspecs}  e, eval_expropt (Some e) = `Some (eval_expr e).\nProof. reflexivity. Qed.\nLemma eval_expropt_None: forall  {cs: compspecs} , eval_expropt None = `None.\nProof. reflexivity. Qed.\nHint Rewrite @eval_expropt_Some @eval_expropt_None : eval.\n\nLemma deref_noload_tarray:\n  forall ty n, deref_noload (tarray ty n) = (fun v => v).\nProof.\n intros. extensionality v. reflexivity.\nQed.\nHint Rewrite deref_noload_tarray : norm.\n\nLemma deref_noload_Tarray:\n  forall ty n a, deref_noload (Tarray ty n a) = (fun v => v).\nProof.\n intros. extensionality v. reflexivity.\nQed.\nHint Rewrite deref_noload_Tarray : norm.\n\nLemma flip_lifted_eq:\n  forall (v1: environ -> val) (v2: val),\n    `eq v1 `(v2) = `(eq v2) v1.\nProof.\nintros. unfold_lift. extensionality rho. apply prop_ext; split; intro; auto.\nQed.\nHint Rewrite flip_lifted_eq : norm.\n\nLemma isptr_is_pointer_or_null:\n  forall v, isptr v -> is_pointer_or_null v.\nProof. intros. destruct v; inv H; simpl; auto.\nQed.\n#[export] Hint Resolve isptr_is_pointer_or_null : core.\n\nDefinition add_ptr_int  {cs: compspecs}  (ty: type) (v: val) (i: Z) : val :=\n           eval_binop Cop.Oadd (tptr ty) tint v (Vint (Int.repr i)).\n\nLemma add_ptr_int_offset:\n  forall  {cs: compspecs}  t v n,\n  repable_signed (sizeof t) ->\n  repable_signed n ->\n  add_ptr_int t v n = offset_val (sizeof t * n) v.\nAbort. (* broken in CompCert 2.7 *)\n\nLemma typed_false_cmp:\n  forall op i j ,\n   typed_false tint (force_val (sem_cmp op tint tint (Vint i) (Vint j))) ->\n   Int.cmp (negate_comparison op) i j = true.\nProof.\nintros.\nunfold sem_cmp in H.\nunfold Cop.classify_cmp in H. simpl in H.\nrewrite Int.negate_cmp.\nunfold both_int, force_val, typed_false, strict_bool_val, sem_cast, classify_cast, tint in H.\ndestruct Archi.ptr64 eqn:Hp; simpl in H.\ndestruct (Int.cmp op i j); inv H; auto.\ndestruct (Int.cmp op i j); inv H; auto.\nQed.\n\nLemma typed_true_cmp:\n  forall op i j,\n   typed_true tint (force_val (sem_cmp op tint tint (Vint i) (Vint j))) ->\n   Int.cmp op i j = true.\nProof.\nintros.\nunfold sem_cmp in H.\nunfold Cop.classify_cmp in H. simpl in H.\nunfold both_int, force_val, typed_false, strict_bool_val, sem_cast, classify_cast, tint in H.\ndestruct Archi.ptr64 eqn:Hp; simpl in H.\ndestruct (Int.cmp op i j); inv H; auto.\ndestruct (Int.cmp op i j); inv H; auto.\nQed.\n\nDefinition Zcmp (op: comparison) : Z -> Z -> Prop :=\n match op with\n | Ceq => eq\n | Cne => (fun i j => i<>j)\n | Clt => Z.lt\n | Cle => Z.le\n | Cgt => Z.gt\n | Cge => Z.ge\n end.\n\nLemma int_cmp_repr:\n forall op i j, repable_signed i -> repable_signed j ->\n   Int.cmp op (Int.repr i) (Int.repr j) = true ->\n   Zcmp op i j.\nProof.\nintros.\nunfold Int.cmp, Int.eq, Int.lt in H1.\nreplace (if zeq (Int.unsigned (Int.repr i)) (Int.unsigned (Int.repr j))\n             then true else false)\n with (if zeq i j then true else false) in H1.\n2:{\ndestruct (zeq i j); destruct (zeq (Int.unsigned (Int.repr i)) (Int.unsigned (Int.repr j)));\n auto.\nsubst. contradiction n; auto.\nclear - H H0 e n.\napply Int.signed_repr in H. rewrite Int.signed_repr_eq in H.\napply Int.signed_repr in H0; rewrite Int.signed_repr_eq in H0.\ncontradiction n; clear n.\nrepeat rewrite Int.unsigned_repr_eq in e.\n match type of H with\n           | context [if ?a then _ else _] => destruct a\n           end;\n match type of H0 with\n           | context [if ?a then _ else _] => destruct a\n           end; lia.\n}\nunfold Zcmp.\nrewrite (Int.signed_repr _ H) in H1; rewrite (Int.signed_repr _ H0) in H1.\nrepeat match type of H1 with\n           | context [if ?a then _ else _] => destruct a\n           end; try lia;\n destruct op; auto; simpl in *; try discriminate; lia.\nQed.\n\nLemma typed_false_cmp_repr:\n  forall op i j,\n   repable_signed i -> repable_signed j ->\n   typed_false tint (force_val (sem_cmp op tint tint\n                              (Vint (Int.repr i))\n                              (Vint (Int.repr j)) )) ->\n   Zcmp (negate_comparison op) i j.\nProof.\n intros.\n apply typed_false_cmp in H1.\n apply int_cmp_repr; auto.\nQed.\n\nLemma typed_true_cmp_repr:\n  forall op i j,\n   repable_signed i -> repable_signed j ->\n   typed_true tint (force_val (sem_cmp op tint tint\n                              (Vint (Int.repr i))\n                              (Vint (Int.repr j)) )) ->\n   Zcmp op i j.\nProof.\n intros.\n apply typed_true_cmp in H1.\n apply int_cmp_repr; auto.\nQed.\n\nLtac intcompare H :=\n (apply typed_false_cmp_repr in H || apply typed_true_cmp_repr in H);\n   [ simpl in H | auto; unfold repable_signed, Int.min_signed, Int.max_signed in *; lia .. ].\n\n\nLemma isptr_deref_noload:\n forall t p, access_mode t = By_reference -> isptr (deref_noload t p) = isptr p.\nProof.\nintros.\nunfold deref_noload. rewrite H. reflexivity.\nQed.\nHint Rewrite isptr_deref_noload using reflexivity : norm.\n\nDefinition headptr (v: val): Prop :=\n  exists b,  v = Vptr b Ptrofs.zero.\n\nLemma headptr_isptr: forall v,\n  headptr v -> isptr v.\nProof.\n  intros.\n  destruct H as [b ?].\n  subst.\n  hnf; auto.\nQed.\n#[export] Hint Resolve headptr_isptr : core.\n\nLemma headptr_offset_zero: forall v,\n  headptr (offset_val 0 v) <->\n  headptr v.\nProof.\n  split; intros.\n  + destruct H as [b ?]; subst.\n    destruct v; try solve [inv H].\n    simpl in H.\n    remember (Ptrofs.add i (Ptrofs.repr 0)).\n    inversion H; subst.\n    rewrite Ptrofs.add_zero in H2; subst.\n    hnf; eauto.\n  + destruct H as [b ?]; subst.\n    exists b.\n    reflexivity.\nQed.\n\n(* Equality proofs for all constants from the Compcert Int, Int64, Ptrofs modules: *)\n\nLemma typed_false_ptr:\n  forall {t a v},  typed_false (Tpointer t a) v -> v=nullval.\nProof.\nunfold typed_false, strict_bool_val, nullval; simpl; intros.\ndestruct Archi.ptr64 eqn:Hp;\ndestruct v; try discriminate; f_equal.\nfirst [pose proof (Int64.eq_spec i Int64.zero); \n          destruct (Int64.eq i Int64.zero)\n       | pose proof (Int.eq_spec i Int.zero); \n         destruct (Int.eq i Int.zero)]; \n      subst; auto; discriminate.\nQed.\n\nLemma typed_true_ptr:\n  forall {t a v},  typed_true (Tpointer t a) v -> isptr v.\nProof.\nunfold typed_true, strict_bool_val; simpl; intros.\ndestruct v; try discriminate; simpl; auto;\ndestruct Archi.ptr64; try discriminate;\n revert H; simple_if_tac; intros; discriminate.\nQed.\n\nLemma int_cmp_repr':\n forall op i j, repable_signed i -> repable_signed j ->\n   Int.cmp op (Int.repr i) (Int.repr j) = false ->\n   Zcmp (negate_comparison op) i j.\nProof.\nintros.\napply int_cmp_repr; auto.\nrewrite Int.negate_cmp.\nrewrite H1; reflexivity.\nQed.\n\nLemma typed_false_of_bool:\n forall x, typed_false tint (Val.of_bool x) -> (x=false).\nProof.\nunfold typed_false; simpl.\nunfold strict_bool_val, Val.of_bool; simpl.\ndestruct x; simpl; intros; [inversion H | auto].\nQed.\n\nLemma typed_true_of_bool:\n forall x, typed_true tint (Val.of_bool x) -> (x=true).\nProof.\nunfold typed_true; simpl.\nunfold strict_bool_val, Val.of_bool; simpl.\ndestruct x; simpl; intros; [auto | inversion H].\nQed.\n\nLemma typed_false_tint:\n Archi.ptr64=false -> \n forall v, typed_false tint v -> v=nullval.\nProof.\nintros.\n hnf in H0. destruct v; inv H0.\n destruct (Int.eq i Int.zero) eqn:?; inv H2.\n apply int_eq_e in Heqb. subst.\n inv H; reflexivity.\nQed.\n\nLemma typed_false_tlong:\n Archi.ptr64=true -> \n forall v, typed_false tlong v -> v=nullval.\nProof.\nintros. unfold nullval. rewrite H.\n hnf in H0. destruct v; inv H0.\npose proof (Int64.eq_spec i Int64.zero).\n destruct (Int64.eq i Int64.zero); inv H2.\nreflexivity.\nQed.\n\nLemma typed_true_e:\n forall t v, typed_true t v -> v<>nullval.\nProof.\nintros.\n intro Hx. subst.\n hnf in H. unfold nullval, strict_bool_val in H.\n destruct Archi.ptr64, t; discriminate.\nQed.\n\nLemma typed_false_tint_Vint:\n  forall v, typed_false tint (Vint v) -> v = Int.zero.\nProof.\nintros.\nunfold typed_false, strict_bool_val in H. simpl in H.\npose proof (Int.eq_spec v Int.zero).\ndestruct (Int.eq v Int.zero); auto. inv H.\nQed.\n\nLemma typed_true_tint_Vint:\n  forall v, typed_true tint (Vint v) -> v <> Int.zero.\nProof.\nintros.\nunfold typed_true, strict_bool_val in H. simpl in H.\npose proof (Int.eq_spec v Int.zero).\ndestruct (Int.eq v Int.zero); auto. inv H.\nQed.\n\nLemma typed_true_tlong_Vlong:\n  forall v, typed_true tlong (Vlong v) -> v <> Int64.zero.\nProof.\nintros.\nunfold typed_true, strict_bool_val in H. simpl in H.\npose proof (Int64.eq_spec v Int64.zero).\ndestruct (Int64.eq v Int64.zero); auto. inv H.\nQed.\n\nLtac intro_redundant P :=\n match goal with H: P |- _ => idtac end.\n\nLtac fancy_intro_discriminate H := idtac.\n\nLtac fancy_intro aggressive :=\n lazymatch goal with |- ~ _ => red | _ => idtac end;\n lazymatch goal with\n | |- ?P -> _ => match type of P with Prop => idtac end\n end;\n tryif \n lazymatch goal with |- ?P -> _ =>\n     lazymatch P with\n     | ptr_eq ?v1 ?v2 => intro_redundant (v1=v2)\n     | Vint ?x = Vint ?y => constr_eq x y + intro_redundant (x=y)\n     | tc_val ?ty ?v =>\n         lazymatch ty with\n         | Tint ?sz ?sg _ => intro_redundant(is_int sz sg v)\n         | Tlong _ _ => intro_redundant(is_long v)\n         | Tfloat F32 _ => intro_redundant(is_single v)\n         | Tfloat F64 _ => intro_redundant(is_float v)\n         | Tpointer _ _ =>\n           tryif (unify ty int_or_ptr_type) \n           then intro_redundant (is_pointer_or_integer v)\n           else intro_redundant (is_pointer_or_null v)\n         | Tarray _ _ _ =>  intro_redundant (is_pointer_or_null v)\n         | Tfunction _ _ _ =>  intro_redundant (is_pointer_or_null v)\n         | _ =>  intro_redundant (isptr v)\n         end\n     | ?x = ?y => constr_eq x y + intro_redundant P\n     | _ => intro_redundant P + unify P True\n    end\n   end\n   then intros _\n   else \n let H := fresh in\n intro H;\n try simple apply ptr_eq_e in H;\n try simple apply Vint_inj in H;\n try lazymatch type of H with\n | tc_val _ _ => unfold tc_val in H; try change (eqb_type _ _) with false in H; cbv iota in H\n | ?x = ?y => tryif constr_eq aggressive true\n                     then first [subst x | subst y\n                                    | is_var x; rewrite H\n                                    | is_var y; rewrite <- H\n                                    | try fancy_intro_discriminate H]\n                     else (try fancy_intro_discriminate H)\n | headptr (_ ?x) => let Hx1 := fresh \"HP\" x in\n                     let Hx2 := fresh \"P\" x in\n                       rename H into Hx1;\n                       pose proof headptr_isptr _ Hx1 as Hx2\n | headptr ?x => let Hx1 := fresh \"HP\" x in\n                 let Hx2 := fresh \"P\" x in\n                   rename H into Hx1;\n                   pose proof headptr_isptr _ Hx1 as Hx2\n | isptr ?x => let Hx := fresh \"P\" x in rename H into Hx\n | is_pointer_or_null ?x => let Hx := fresh \"PN\" x in rename H into Hx\n | typed_false _ _ =>\n        first [simple apply typed_false_of_bool in H\n               | apply typed_false_tint_Vint in H\n               | apply (typed_false_tint (eq_refl _)) in H\n               | apply (typed_false_tlong (eq_refl _)) in H\n               | apply typed_false_ptr in H\n               | idtac ]\n | typed_true _ _ =>\n        first [simple apply typed_true_of_bool in H\n               | apply typed_true_tint_Vint in H\n               | apply typed_true_tlong_Vlong in H\n               | apply typed_true_ptr in H\n               | idtac ]\n end.\n\nLtac fancy_intros aggressive :=\n repeat lazymatch goal with\n  | |- (_ <= _ < _) -> _ => fancy_intro aggressive\n  | |- (_ < _ <= _) -> _ => fancy_intro aggressive\n  | |- (_ <= _ <= _) -> _ => fancy_intro aggressive\n  | |- (_ < _ < _) -> _ => fancy_intro aggressive\n  | |- (?A /\\ ?B) -> ?C => apply (@and_ind A B C) (* For some reason \"apply and_ind\" doesn't work the same *)\n  | |- _ -> _ => fancy_intro aggressive\n  end.\n\nLtac fold_types :=\n fold noattr tuint tint tschar tuchar;\n repeat match goal with\n | |- context [Tpointer ?t noattr] =>\n      change (Tpointer t noattr) with (tptr t)\n | |- context [Tarray ?t ?n noattr] =>\n      change (Tarray t n noattr) with (tarray t n)\n end.\n\nLtac fold_types1 :=\n  match goal with |- _ -> ?A =>\n  let a := fresh \"H\" in set (a:=A); fold_types; subst a\n  end.\n\nLemma is_int_Vbyte: forall c, is_int I8 Signed (Vbyte c).\nProof.\nintros. simpl. normalize. rewrite Int.signed_repr by rep_lia. rep_lia.\nQed.\n#[export] Hint Resolve is_int_Vbyte : core.\n\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/floyd/val_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24886649210189563}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Recognition of combined operations, addressing modes and conditions\n  during the [CSE] phase. *)\n\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Op.\nRequire Import CSEdomain.\n\nDefinition valnum := positive.\n\nSection COMBINE.\n\nVariable get: valnum -> option rhs.\n\nFunction combine_compimm_ne_0 (x: valnum) : option(condition * list valnum) :=\n  match get x with\n  | Some(Op (Ocmp c) ys) => Some (c, ys)\n  | Some(Op (Oandimm n) ys) => Some (Cmasknotzero n, ys)\n  | _ => None\n  end.\n\nFunction combine_compimm_eq_0 (x: valnum) : option(condition * list valnum) :=\n  match get x with\n  | Some(Op (Ocmp c) ys) => Some (negate_condition c, ys)\n  | Some(Op (Oandimm n) ys) => Some (Cmaskzero n, ys)\n  | _ => None\n  end.\n\nFunction combine_compimm_eq_1 (x: valnum) : option(condition * list valnum) :=\n  match get x with\n  | Some(Op (Ocmp c) ys) => Some (c, ys)\n  | _ => None\n  end.\n\nFunction combine_compimm_ne_1 (x: valnum) : option(condition * list valnum) :=\n  match get x with\n  | Some(Op (Ocmp c) ys) => Some (negate_condition c, ys)\n  | _ => None\n  end.\n\nFunction combine_cond (cond: condition) (args: list valnum) : option(condition * list valnum) :=\n  match cond, args with\n  | Ccompimm Cne n, x::nil =>\n      if Int.eq_dec n Int.zero then combine_compimm_ne_0 x\n      else if Int.eq_dec n Int.one then combine_compimm_ne_1 x\n      else None\n  | Ccompimm Ceq n, x::nil =>\n      if Int.eq_dec n Int.zero then combine_compimm_eq_0 x\n      else if Int.eq_dec n Int.one then combine_compimm_eq_1 x\n      else None\n  | Ccompuimm Cne n, x::nil =>\n      if Int.eq_dec n Int.zero then combine_compimm_ne_0 x\n      else if Int.eq_dec n Int.one then combine_compimm_ne_1 x\n      else None\n  | Ccompuimm Ceq n, x::nil =>\n      if Int.eq_dec n Int.zero then combine_compimm_eq_0 x\n      else if Int.eq_dec n Int.one then combine_compimm_eq_1 x\n      else None\n  | _, _ => None\n  end.\n\nFunction combine_addr (addr: addressing) (args: list valnum) : option(addressing * list valnum) :=\n  match addr, args with\n  | Aindexed n, x::nil =>\n      match get x with\n      | Some(Op (Olea a) ys) => Some(offset_addressing_total a n, ys)\n      | _ => None\n      end\n  | _, _ => None\n  end.\n\nFunction combine_op (op: operation) (args: list valnum) : option(operation * list valnum) :=\n  match op, args with\n  | Olea addr, _ =>\n      match combine_addr addr args with\n      | Some(addr', args') => Some(Olea addr', args')\n      | None => None\n      end\n  | Oandimm n, x :: nil =>\n      match get x with\n      | Some(Op (Oandimm m) ys) => Some(Oandimm (Int.and m n), ys)\n      | _ => None\n      end\n  | Oorimm n, x :: nil =>\n      match get x with\n      | Some(Op (Oorimm m) ys) => Some(Oorimm (Int.or m n), ys)\n      | _ => None\n      end\n  | Oxorimm n, x :: nil =>\n      match get x with\n      | Some(Op (Oxorimm m) ys) => Some(Oxorimm (Int.xor m n), ys)\n      | _ => None\n      end\n  | Ocmp cond, _ =>\n      match combine_cond cond args with\n      | Some(cond', args') => Some(Ocmp cond', args')\n      | None => None\n      end\n  | _, _ => None\n  end.\n\nEnd COMBINE.\n\n\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/compcert/ia32/CombineOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24886648650160897}}
{"text": "From iris.proofmode Require Import tactics monpred.\nFrom iris.base_logic Require Import base_logic.\nFrom iris.base_logic.lib Require Import invariants cancelable_invariants na_invariants.\n\nFrom iris.bi Require Import ascii.\n\nSet Default Proof Using \"Type\".\nUnset Printing Use Implicit Types. (* FIXME: remove once we drop support for Coq <=8.11. *)\n\nSection base_logic_tests.\n  Context {M : ucmraT}.\n  Implicit Types P Q R : uPred M.\n\n  Lemma test_random_stuff (P1 P2 P3 : nat -> uPred M) :\n    |- forall (x y : nat) a b,\n      x ≡ y ->\n      <#> (uPred_ownM (a ⋅ b) -*\n      (exists y1 y2 c, P1 ((x + y1) + y2) /\\ True /\\ <#> uPred_ownM c) -*\n      <#> |> (forall z, P2 z ∨ True -> P2 z) -*\n      |> (forall n m : nat, P1 n -> <#> (True /\\ P2 n -> <#> (⌜n = n⌝ <-> P3 n))) -*\n      |> ⌜x = 0⌝ \\/ exists x z, |> P3 (x + z) ** uPred_ownM b ** uPred_ownM (core b)).\n  Proof.\n    iIntros (i [|j] a b ?) \"!> [Ha Hb] H1 #H2 H3\"; setoid_subst.\n    { iLeft. by iNext. }\n    iRight.\n    iDestruct \"H1\" as (z1 z2 c) \"(H1&_&#Hc)\".\n    iPoseProof \"Hc\" as \"foo\".\n    iRevert (a b) \"Ha Hb\". iIntros (b a) \"Hb {foo} Ha\".\n    iAssert (uPred_ownM (a ⋅ core a)) with \"[Ha]\" as \"[Ha #Hac]\".\n    { by rewrite cmra_core_r. }\n    iIntros \"{$Hac $Ha}\".\n    iExists (S j + z1), z2.\n    iNext.\n    iApply (\"H3\" $! _ 0 with \"[$]\").\n    - iSplit. done. iApply \"H2\". iLeft. iApply \"H2\". by iRight.\n    - done.\n  Qed.\n\n  Lemma test_iFrame_pure (x y z : M) :\n    ✓ x -> ⌜y ≡ z⌝ |-@{uPredI M} ✓ x /\\ ✓ x /\\ y ≡ z.\n  Proof. iIntros (Hv) \"Hxy\". by iFrame (Hv) \"Hxy\". Qed.\n\n  Lemma test_iAssert_modality P : (|==> False) -* |==> P.\n  Proof. iIntros. iAssert False%I with \"[> - //]\" as %[]. Qed.\n\n  Lemma test_iStartProof_1 P : P -* P.\n  Proof. iStartProof. iStartProof. iIntros \"$\". Qed.\n  Lemma test_iStartProof_2 P : P -* P.\n  Proof. iStartProof (uPred _). iStartProof (uPredI _). iIntros \"$\". Qed.\n  Lemma test_iStartProof_3 P : P -* P.\n  Proof. iStartProof (uPredI _). iStartProof (uPredI _). iIntros \"$\". Qed.\n  Lemma test_iStartProof_4 P : P -* P.\n  Proof. iStartProof (uPredI _). iStartProof (uPred _). iIntros \"$\". Qed.\nEnd base_logic_tests.\n\nSection iris_tests.\n  Context `{!invG Σ, !cinvG Σ, !na_invG Σ}.\n  Implicit Types P Q R : iProp Σ.\n\n  Lemma test_masks  N E P Q R :\n    ↑N ⊆ E ->\n    (True -* P -* inv N Q -* True -* R) -* P -* |> Q ={E}=* R.\n  Proof.\n    iIntros (?) \"H HP HQ\".\n    iApply (\"H\" with \"[% //] [$] [> HQ] [> //]\").\n    by iApply inv_alloc.\n  Qed.\n\n  Lemma test_iInv_0 N P: inv N (<pers> P) ={⊤}=* |> P.\n  Proof.\n    iIntros \"#H\".\n    iInv N as \"#H2\". Show.\n    iModIntro. iSplit; auto.\n  Qed.\n\n  Lemma test_iInv_0_with_close N P: inv N (<pers> P) ={⊤}=* |> P.\n  Proof.\n    iIntros \"#H\".\n    iInv N as \"#H2\" \"Hclose\". Show.\n    iMod (\"Hclose\" with \"H2\").\n    iModIntro. by iNext.\n  Qed.\n\n  Lemma test_iInv_1 N E P:\n    ↑N ⊆ E ->\n    inv N (<pers> P) ={E}=* |> P.\n  Proof.\n    iIntros (?) \"#H\".\n    iInv N as \"#H2\".\n    iModIntro. iSplit; auto.\n  Qed.\n\n  Lemma test_iInv_2 γ p N P:\n    cinv N γ (<pers> P) ** cinv_own γ p ={⊤}=* cinv_own γ p ** |> P.\n  Proof.\n    iIntros \"(#?&?)\".\n    iInv N as \"(#HP&Hown)\". Show.\n    iModIntro. iSplit; auto with iFrame.\n  Qed.\n\n  Lemma test_iInv_2_with_close γ p N P:\n    cinv N γ (<pers> P) ** cinv_own γ p ={⊤}=* cinv_own γ p ** |> P.\n  Proof.\n    iIntros \"(#?&?)\".\n    iInv N as \"(#HP&Hown)\" \"Hclose\". Show.\n    iMod (\"Hclose\" with \"HP\").\n    iModIntro. iFrame. by iNext.\n  Qed.\n\n  Lemma test_iInv_3 γ p1 p2 N P:\n    cinv N γ (<pers> P) ** cinv_own γ p1 ** cinv_own γ p2\n      ={⊤}=* cinv_own γ p1 ** cinv_own γ p2  ** |> P.\n  Proof.\n    iIntros \"(#?&Hown1&Hown2)\".\n    iInv N with \"[Hown2 //]\" as \"(#HP&Hown2)\".\n    iModIntro. iSplit; auto with iFrame.\n  Qed.\n\n  Lemma test_iInv_4 t N E1 E2 P:\n    ↑N ⊆ E2 ->\n    na_inv t N (<pers> P) ** na_own t E1 ** na_own t E2\n         |- |={⊤}=> na_own t E1 ** na_own t E2  ** |> P.\n  Proof.\n    iIntros (?) \"(#?&Hown1&Hown2)\".\n    iInv N as \"(#HP&Hown2)\". Show.\n    iModIntro. iSplitL \"Hown2\"; auto with iFrame.\n  Qed.\n\n  Lemma test_iInv_4_with_close t N E1 E2 P:\n    ↑N ⊆ E2 ->\n    na_inv t N (<pers> P) ** na_own t E1 ** na_own t E2\n         |- |={⊤}=> na_own t E1 ** na_own t E2  ** |> P.\n  Proof.\n    iIntros (?) \"(#?&Hown1&Hown2)\".\n    iInv N as \"(#HP&Hown2)\" \"Hclose\". Show.\n    iMod (\"Hclose\" with \"[HP Hown2]\").\n    { iFrame. done. }\n    iModIntro. iFrame. by iNext.\n  Qed.\n\n  (* test named selection of which na_own to use *)\n  Lemma test_iInv_5 t N E1 E2 P:\n    ↑N ⊆ E2 ->\n    na_inv t N (<pers> P) ** na_own t E1 ** na_own t E2\n      ={⊤}=* na_own t E1 ** na_own t E2  ** |> P.\n  Proof.\n    iIntros (?) \"(#?&Hown1&Hown2)\".\n    iInv N with \"Hown2\" as \"(#HP&Hown2)\".\n    iModIntro. iSplitL \"Hown2\"; auto with iFrame.\n  Qed.\n\n  Lemma test_iInv_6 t N E1 E2 P:\n    ↑N ⊆ E1 ->\n    na_inv t N (<pers> P) ** na_own t E1 ** na_own t E2\n      ={⊤}=* na_own t E1 ** na_own t E2  ** |> P.\n  Proof.\n    iIntros (?) \"(#?&Hown1&Hown2)\".\n    iInv N with \"Hown1\" as \"(#HP&Hown1)\".\n    iModIntro. iSplitL \"Hown1\"; auto with iFrame.\n  Qed.\n\n  (* test robustness in presence of other invariants *)\n  Lemma test_iInv_7 t N1 N2 N3 E1 E2 P:\n    ↑N3 ⊆ E1 ->\n    inv N1 P ** na_inv t N3 (<pers> P) ** inv N2 P ** na_own t E1 ** na_own t E2\n      ={⊤}=* na_own t E1 ** na_own t E2 ** |> P.\n  Proof.\n    iIntros (?) \"(#?&#?&#?&Hown1&Hown2)\".\n    iInv N3 with \"Hown1\" as \"(#HP&Hown1)\".\n    iModIntro. iSplitL \"Hown1\"; auto with iFrame.\n  Qed.\n\n  (* iInv should work even where we have \"inv N P\" in which P contains an evar *)\n  Lemma test_iInv_8 N : ∃ P, inv N P ={⊤}=* P ≡ True /\\ inv N P.\n  Proof.\n    eexists. iIntros \"#H\".\n    iInv N as \"HP\". iFrame \"HP\". auto.\n  Qed.\n\n  (* test selection by hypothesis name instead of namespace *)\n  Lemma test_iInv_9 t N1 N2 N3 E1 E2 P:\n    ↑N3 ⊆ E1 ->\n    inv N1 P ** na_inv t N3 (<pers> P) ** inv N2 P ** na_own t E1 ** na_own t E2\n      ={⊤}=* na_own t E1 ** na_own t E2 ** |> P.\n  Proof.\n    iIntros (?) \"(#?&#HInv&#?&Hown1&Hown2)\".\n    iInv \"HInv\" with \"Hown1\" as \"(#HP&Hown1)\".\n    iModIntro. iSplitL \"Hown1\"; auto with iFrame.\n  Qed.\n\n  (* test selection by hypothesis name instead of namespace *)\n  Lemma test_iInv_10 t N1 N2 N3 E1 E2 P:\n    ↑N3 ⊆ E1 ->\n    inv N1 P ** na_inv t N3 (<pers> P) ** inv N2 P ** na_own t E1 ** na_own t E2\n      ={⊤}=* na_own t E1 ** na_own t E2 ** |> P.\n  Proof.\n    iIntros (?) \"(#?&#HInv&#?&Hown1&Hown2)\".\n    iInv \"HInv\" as \"(#HP&Hown1)\".\n    iModIntro. iSplitL \"Hown1\"; auto with iFrame.\n  Qed.\n\n  (* test selection by ident name *)\n  Lemma test_iInv_11 N P: inv N (<pers> P) ={⊤}=* |> P.\n  Proof.\n    let H := iFresh in\n    (iIntros H; iInv H as \"#H2\"). auto.\n  Qed.\n\n  (* error messages *)\n  Check \"test_iInv_12\".\n  Lemma test_iInv_12 N P: inv N (<pers> P) ={⊤}=* True.\n  Proof.\n    iIntros \"H\".\n    Fail iInv 34 as \"#H2\".\n    Fail iInv nroot as \"#H2\".\n    Fail iInv \"H2\" as \"#H2\".\n    done.\n  Qed.\n\n  (* test destruction of existentials when opening an invariant *)\n  Lemma test_iInv_13 N:\n    inv N (∃ (v1 v2 v3 : nat), emp ** emp ** emp) ={⊤}=* |> emp.\n  Proof.\n    iIntros \"H\"; iInv \"H\" as (v1 v2 v3) \"(?&?&_)\".\n    eauto.\n  Qed.\n\n  Theorem test_iApply_inG `{!inG Σ A} γ (x x' : A) :\n    x' ≼ x ->\n    own γ x -* own γ x'.\n  Proof. intros. by iApply own_mono. Qed.\nEnd iris_tests.\n\nSection monpred_tests.\n  Context `{!invG Σ}.\n  Context {I : biIndex}.\n  Local Notation monPred := (monPred I (iPropI Σ)).\n  Local Notation monPredI := (monPredI I (iPropI Σ)).\n  Implicit Types P Q R : monPred.\n  Implicit Types 𝓟 𝓠 𝓡 : iProp Σ.\n\n  Check \"test_iInv\".\n  Lemma test_iInv N E 𝓟 :\n    ↑N ⊆ E ->\n    ⎡inv N 𝓟⎤ |-@{monPredI} |={E}=> emp.\n  Proof.\n    iIntros (?) \"Hinv\".\n    iInv N as \"HP\". Show.\n    iFrame \"HP\". auto.\n  Qed.\n\n  Check \"test_iInv_with_close\".\n  Lemma test_iInv_with_close N E 𝓟 :\n    ↑N ⊆ E ->\n    ⎡inv N 𝓟⎤ |-@{monPredI} |={E}=> emp.\n  Proof.\n    iIntros (?) \"Hinv\".\n    iInv N as \"HP\" \"Hclose\". Show.\n    iMod (\"Hclose\" with \"HP\"). auto.\n  Qed.\n\nEnd monpred_tests.\n\n(** Test specifically if certain things parse correctly. *)\nSection parsing_tests.\nContext {PROP : bi}.\nImplicit Types P : PROP.\n\nLemma test_bi_emp_valid : |-@{PROP} True.\nProof. naive_solver. Qed.\n\nLemma test_bi_emp_valid_parens : (|-@{PROP} True) /\\ ((|-@{PROP} True)).\nProof. naive_solver. Qed.\n\nLemma test_bi_emp_valid_parens_space_open : ( |-@{PROP} True).\nProof. naive_solver. Qed.\n\nLemma test_bi_emp_valid_parens_space_close : (|-@{PROP} True ).\nProof. naive_solver. Qed.\n\nLemma test_entails_annot_sections P :\n  (P |-@{PROP} P) /\\ (|-@{PROP}) P P /\\\n  (P -|-@{PROP} P) /\\ (-|-@{PROP}) P P.\nProof. naive_solver. Qed.\n\nLemma test_entails_annot_sections_parens P :\n  ((P |-@{PROP} P)) /\\ ((|-@{PROP})) P P /\\\n  ((P -|-@{PROP} P)) /\\ ((-|-@{PROP})) P P.\nProof. naive_solver. Qed.\n\nLemma test_entails_annot_sections_space_open P :\n  ( P |-@{PROP} P) /\\\n  ( P -|-@{PROP} P).\nProof. naive_solver. Qed.\n\nLemma test_entails_annot_sections_space_close P :\n  (P |-@{PROP} P ) /\\ (|-@{PROP} ) P P /\\\n  (P -|-@{PROP} P ) /\\ (-|-@{PROP} ) P P.\nProof. naive_solver. Qed.\n\n\nCheck \"p1\".\nLemma p1 : forall P, True -> P |- P.\nProof.\n  Unset Printing Notations. Show. Set Printing Notations.\nAbort.\n\nCheck \"p2\".\nLemma p2 : forall P, True /\\ (P |- P).\nProof.\n  Unset Printing Notations. Show. Set Printing Notations.\nAbort.\n\nCheck \"p3\".\nLemma p3 : exists P, P |- P.\nProof.\n  Unset Printing Notations. Show. Set Printing Notations.\nAbort.\n\nCheck \"p4\".\nLemma p4 : |-@{PROP} exists (x : nat), ⌜x = 0⌝.\nProof.\n  Unset Printing Notations. Show. Set Printing Notations.\nAbort.\n\nCheck \"p5\".\nLemma p5 : |-@{PROP} exists (x : nat), ⌜forall y : nat, y = y⌝.\nProof.\n  Unset Printing Notations. Show. Set Printing Notations.\nAbort.\n\nCheck \"p6\".\nLemma p6 : exists! (z : nat), |-@{PROP} exists (x : nat), ⌜forall y : nat, y = y⌝ ** ⌜z = 0⌝.\nProof.\n  Unset Printing Notations. Show. Set Printing Notations.\nAbort.\n\nCheck \"p7\".\nLemma p7 : forall (a : nat), a = 0 -> forall y, True |-@{PROP} ⌜y >= 0⌝.\nProof.\n  Unset Printing Notations. Show. Set Printing Notations.\nAbort.\n\nCheck \"p8\".\nLemma p8 : forall (a : nat), a = 0 -> forall y, |-@{PROP} ⌜y >= 0⌝.\nProof.\n  Unset Printing Notations. Show. Set Printing Notations.\nAbort.\n\nCheck \"p9\".\nLemma p9 : forall (a : nat), a = 0 -> forall y : nat, |-@{PROP} forall z : nat, ⌜z >= 0⌝.\nProof.\n  Unset Printing Notations. Show. Set Printing Notations.\nAbort.\n\nSet Printing Notations.\n\nEnd parsing_tests.\n", "meta": {"author": "SkySkimmer", "repo": "iris", "sha": "186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5", "save_path": "github-repos/coq/SkySkimmer-iris", "path": "github-repos/coq/SkySkimmer-iris/iris-186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5/tests/proofmode_ascii.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.24880838714110762}}
{"text": "\nRequire Import Infrastructure.\nRequire Import SourceProperty.\nRequire Import LR.\nRequire Import Assumed.\nRequire Import TargetProperty.\nRequire Import Disjoint.\n\n\n\n\n(* ********************************************************************** *)\n(** * Coercion Compatibility *)\n\n\nLemma E_coercion2 : forall A1 A2 A0 c p d d' e1 e2,\n    sub d' A1 A2 c ->\n    same_stctx d d' ->\n    swfte d ->\n    rel_d d p ->\n    E A0 (mtsubst_in_sty p A1) e2 e1 ->\n    E A0 (mtsubst_in_sty p A2) e2 (exp_capp c e1).\nProof with eauto.\n  introv ? ? ? ? EH.\n  apply E_sym in EH.\n  apply E_sym.\n  eapply E_coercion1...\nQed.\n\nLemma coercion_compatibility1 : forall A0 A1 A2 c D G e1 e2,\n    sub D A1 A2 c ->\n    swfte D ->\n    E_open D G e1 e2 A1 A0 ->\n    E_open D G (exp_capp c e1) e2 A2 A0.\nProof with eauto using subtype_well_type, swft_wft, E_coercion1.\n  introv Sub Uniq H.\n  destruct H as (? & ? & ? & ? & EH).\n\n  lets (? & ?): sub_regular Sub.\n\n  splits...\n  introv RelD RelG.\n  specializes EH RelD RelG.\n  autorewrite with lr_rewrite...\nQed.\n\n\nLemma coercion_compatibility2 : forall A0 A1 A2 c D G e1 e2,\n    sub D A1 A2 c ->\n    swfte D ->\n    E_open D G e1 e2 A0 A1 ->\n    E_open D G e1 (exp_capp c e2) A0 A2.\nProof with eauto using subtype_well_type, swft_wft, E_coercion2.\n  introv Sub Uniq H.\n  destruct H as (? & ? & ? & ? & EH).\n\n  lets (? & ?): sub_regular Sub.\n\n  splits...\n  introv RelD RelG.\n  specializes EH RelD RelG.\n  autorewrite with lr_rewrite...\nQed.\n\n\n\n\nHint Extern 1 (swfte ?E) =>\n  match goal with\n  | H: has_type _ _ _ _ _ _ |- _ => apply (proj2 (proj2 (proj2 (styping_regular _ _ _ _ _ _ H))))\n  end.\n\n\nHint Extern 1 (swft ?A ?B) =>\n  match goal with\n  | H: has_type _ _ _ _ _ _ |- _ => apply (proj1 (proj2 (proj2 (styping_regular _ _ _ _ _ _ H))))\n  end.\n\n\nLemma disjoint_compatibility : forall Δ Γ E1 e1 A1 E2 e2 A2 dir dir',\n    has_type Δ Γ E1 dir A1 e1 ->\n    has_type Δ Γ E2 dir' A2 e2 ->\n    disjoint Δ A1 A2 ->\n    E_open Δ Γ e1 e2 A1 A2.\nProof with eauto using swft_wft, swfe_wfe, elaboration_well_type, swft_from_swfe, mtsubst_swft, uniq_from_swfte.\n  introv Ty1 Ty2 Dis.\n  splits...\n  introv RelD RelG.\n  forwards (? & ?): rel_d_uniq RelD.\n  forwards : rel_d_same RelD...\n  forwards Ty3 : elaboration_well_type Ty1...\n  forwards Ty4 : elaboration_well_type Ty2...\n  forwards (Ty5 & ?) : subst_close RelD RelG Ty3.\n  forwards (? & Ty6) : subst_close RelD RelG Ty4.\n  splits...\n  lets (v1 & ? & ?) : normalization Ty5.\n  lets (v2 & ? & ?) : normalization Ty6.\n  exists v1 v2.\n  splits...\n  eapply disjoint_value...\n  apply preservation_multi_step with (e := msubst_in_exp g1 (mtsubst_in_exp p e1))...\n  apply preservation_multi_step with (e := msubst_in_exp g2 (mtsubst_in_exp p e2))...\nQed.\n\n\n(* ********************************************************************** *)\n(** * Pair compatibility *)\n\nLemma pair_compatibility : forall D G e1 e2 e1' e2' A B A' B',\n    E_open D G e1 e1' A A' ->\n    E_open D G e2 e2' B B' ->\n    swfte D ->\n    disjoint D A B' ->\n    disjoint D A' B ->\n    E_open D G (exp_pair e1 e2) (exp_pair e1' e2') (sty_and A B) (sty_and A' B').\nProof with eauto using preservation_multi_step.\n  introv EH1 EH2 Wfte Dis1 Dis2.\n\n  destruct EH1 as (? & ? & ? & ? & EH1).\n  destruct EH2 as (? & ? & ? & ? & EH2).\n\n  splits; simpls...\n  introv RelD RelG.\n  specializes EH1 RelD RelG.\n  specializes EH2 RelD RelG.\n\n  destruct EH1 as (? & ? & ? & ? & v1 & v1' & ? & ? & ? & ? & VH1).\n  destruct EH2 as (? & ? & ? & ? & v2 & v2' & ? & ? & ? & ? & VH2).\n\n  splits; autorewrite with lr_rewrite; simpls...\n\n  exists (exp_pair v1 v2) (exp_pair v1' v2').\n  splits...\n\n  apply V_andl...\n  splits...\n  apply V_andr...\n  splits...\n  eapply disjoint_value...\n  apply V_andr...\n  splits...\n  eapply disjoint_value...\n  eapply disjoint_symmetric...\nQed.\n\n", "meta": {"author": "bixuanzju", "repo": "ESOP2019-artifact", "sha": "b870bfc67175fea01980ee866ce8bae528f4d79f", "save_path": "github-repos/coq/bixuanzju-ESOP2019-artifact", "path": "github-repos/coq/bixuanzju-ESOP2019-artifact/ESOP2019-artifact-b870bfc67175fea01980ee866ce8bae528f4d79f/coq/Compatibility.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.24880838714110762}}
{"text": "(** * Dexter 2 CPMM contract *)\n(** This file contains an implementation of the Dexter2 CPMM contract\n    https://gitlab.com/dexter2tz/dexter2tz/-/blob/1cec9d9333eba756603d6cd90ea9c70d482a5d3d/dexter.mligo\n    In addition this file contains proof of functional correctness w.r.t the\n    informal specification https://gitlab.com/dexter2tz/dexter2tz/-/blob/1cec9d9333eba756603d6cd90ea9c70d482a5d3d/docs/informal-spec/dexter2-cpmm.md\n\n    This contract is an implementation of a Constant Product Market Maker (CPMM).\n    When paired with a FA1.2 or FA2 token contract and a Dexter2 liquidity contract,\n    this contract serves as a decentralized exchange allowing users to trade between\n    XTZ and tokens. Additionally, users can also add or withdraw funds from the\n    exchanges trading reserves. Traders pay a 0.3% fee, the fee goes to the owners\n    of the trading reserves, this way user are incentivized to add funds to the reserves.\n*)\nFrom ConCert.Utils Require Import Automation.\nFrom ConCert.Utils Require Import Extras.\nFrom ConCert.Utils Require Import RecordUpdate.\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Execution Require Import InterContractCommunication.\nFrom ConCert.Execution Require Import ContractCommon.\nFrom ConCert.Execution Require Import ResultMonad.\nFrom ConCert.Examples.FA2 Require Import FA2Token.\nFrom ConCert.Examples.FA2 Require Import FA2LegacyInterface.\nFrom ConCert.Examples.Dexter2 Require Import Dexter2FA12.\nFrom ConCert.Examples.Dexter2 Require Dexter2FA12Correct.\nFrom ConCert.Examples.Dexter2 Require Import Dexter2CPMM. Import DEX2.\nFrom Coq Require Import ZArith_base.\nFrom Coq Require Import List. Import ListNotations.\nFrom Coq Require Import Lia.\n\n\n\n(** * Properties *)\nSection Theories.\n  Existing Instance BaseTypes.\n  Open Scope N_scope.\n  Global Arguments amount_to_N /.\n\n  (* Tactics and facts about helper functions (omitted) *)\n  (* begin hide *)\n  Transparent div.\n  Transparent ceildiv.\n  Transparent ceildiv_.\n  Lemma div_eq : forall n m p,\n      div n m = Ok p ->\n      n / m = p /\\ m <> 0.\n  Proof.\n    intros * div_some.\n    unfold div in div_some.\n    cbn in div_some.\n    destruct_match eqn:m_not_zero in div_some;\n      try congruence.\n    destruct_throw_if m_not_zero.\n    now apply N.eqb_neq in m_not_zero.\n  Qed.\n\n  Lemma div_zero : forall n m e,\n    div n m = Err e ->\n    m = 0.\n  Proof.\n    intros * div_some.\n    cbn in div_some.\n    destruct_match eqn:m_zero in div_some;\n      try congruence.\n    destruct_throw_if m_zero.\n    now apply N.eqb_eq in m_zero.\n  Qed.\n  Opaque div.\n\n  Lemma ceildiv_eq : forall n m p,\n    ceildiv n m = Ok p ->\n    ceildiv_ n m = p /\\ m <> 0.\n  Proof.\n    intros * ceildiv_some.\n    unfold ceildiv_.\n    unfold ceildiv in ceildiv_some.\n    destruct_match eqn:modulo_zero.\n    - now apply div_eq in ceildiv_some.\n    - cbn in ceildiv_some.\n      destruct_match eqn:div_some in ceildiv_some;\n        try congruence.\n      apply div_eq in div_some.\n      now inversion_clear ceildiv_some.\n  Qed.\n\n  Lemma ceildiv_zero : forall n m e,\n    ceildiv n m = Err e ->\n    m = 0.\n  Proof.\n    intros * ceildiv_some.\n    unfold ceildiv in ceildiv_some.\n    destruct_match eqn:modulo_zero in ceildiv_some.\n    - now apply div_zero in ceildiv_some.\n    - cbn in ceildiv_some.\n      destruct_match eqn:div_some in ceildiv_some;\n        try congruence.\n      rewrite ceildiv_some in div_some.\n      now apply div_zero in div_some.\n  Qed.\n  Opaque ceildiv.\n  Opaque ceildiv_.\n\n  Transparent sub.\n  Lemma sub_eq : forall n m p,\n    sub n m = Ok p ->\n    n - m = p /\\ m <= n.\n  Proof.\n    intros * sub_some.\n    cbn in sub_some.\n    destruct_match eqn:m_le_n in sub_some;\n      try congruence.\n    destruct_throw_if m_le_n.\n    now rewrite <- N.ltb_ge.\n  Qed.\n\n  Lemma sub_fail : forall n m e,\n    sub n m = Err e ->\n    n < m.\n  Proof.\n    intros * sub_some.\n    cbn in sub_some.\n    destruct_match eqn:n_lt_m in sub_some;\n      try congruence.\n    destruct_throw_if n_lt_m.\n    now apply N.ltb_lt.\n  Qed.\n  Opaque sub.\n\n  Lemma set_delegate_call_nil : forall (addr : baker_address),\n    set_delegate_call addr = [].\n  Proof.\n    intros.\n    pose proof (delegate_call addr).\n    destruct set_delegate_call; auto.\n    apply Forall_inv in H.\n    now destruct a.\n  Qed.\n\n\n\n  Ltac math_convert_step :=\n    match goal with\n    | H : sub _ _ = Ok _ |- _ => apply sub_eq in H as [<- H]\n    | H : sub _ _ = Err _ |- _ => apply sub_fail in H\n    | H : div _ _ = Ok _ |- _ => apply div_eq in H as [<- H]\n    | H : div _ _ = Err _ |- _ => apply div_zero in H\n    | H : ceildiv _ _ = Ok _ |- _ => apply ceildiv_eq in H as [<- H]\n    | H : ceildiv _ _ = Err _ |- _ => apply ceildiv_zero in H\n    end.\n\n  Tactic Notation \"math_convert\" := repeat math_convert_step.\n\n  Tactic Notation \"contract_simpl\" :=\n    repeat (unfold call_to_token,call_to_other_token; contract_simpl_step @receive_cpmm @init_cpmm).\n\n  Ltac destruct_message :=\n    repeat match goal with\n    | msg : option Msg |- _ => destruct msg\n    | msg : Msg |- _ => destruct msg\n    | msg : DexterMsg |- _ => destruct msg\n    | H : Blockchain.receive _ _ _ _ (Some (receive_total_supply_param _)) = Ok _ |- _ => now contract_simpl\n    | H : receive_cpmm _ _ _ (Some (receive_total_supply_param _)) = Ok _ |- _ => now contract_simpl\n    | H : Blockchain.receive _ _ _ _ (Some (receive_metadata_callback _)) = Ok _ |- _ => now contract_simpl\n    | H : receive_cpmm _ _ _ (Some (receive_metadata_callback _)) = Ok _ |- _ => now contract_simpl\n    | H : Blockchain.receive _ _ _ _ (Some (receive_is_operator _)) = Ok _ |- _ => now contract_simpl\n    | H : receive_cpmm _ _ _ (Some (receive_is_operator _)) = Ok _ |- _ => now contract_simpl\n    | H : Blockchain.receive _ _ _ _ (Some (receive_permissions_descriptor _)) = Ok _ |- _ => now contract_simpl\n    | H : receive_cpmm _ _ _ (Some (receive_permissions_descriptor _)) = Ok _ |- _ => now contract_simpl\n    end.\n  (* end hide *)\n\n\n\n  (** ** Set baker correct *)\n  (** [set_baker] only changes [freezeBaker] in state *)\n  Lemma set_baker_state_eq : forall prev_state new_state chain ctx new_acts param,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (SetBaker param))) = Ok (new_state, new_acts) ->\n      prev_state<| freezeBaker := param.(freezeBaker_) |> = new_state.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n  Qed.\n\n  Lemma set_baker_freeze_baker_correct : forall prev_state new_state chain ctx new_acts param,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (SetBaker param))) = Ok (new_state, new_acts) ->\n      new_state.(freezeBaker) = param.(freezeBaker_).\n  Proof.\n    intros * receive_some.\n    apply set_baker_state_eq in receive_some.\n    now subst.\n  Qed.\n\n  (** [set_baker] produces no new_acts *)\n  Lemma set_baker_new_acts_correct : forall chain ctx prev_state param new_state new_acts,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (SetBaker param))) = Ok (new_state, new_acts) ->\n      new_acts = set_delegate_call param.(baker).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n  Qed.\n\n  (** If the requirements are met then receive on set_baker msg must succeed and\n      if receive on set_baker msg succeeds then requirements must hold *)\n  Lemma set_baker_is_some : forall prev_state chain ctx param,\n    (ctx_amount ctx <= 0)%Z /\\\n    prev_state.(selfIsUpdatingTokenPool) = false /\\\n    ctx.(ctx_from) = prev_state.(manager) /\\\n    prev_state.(freezeBaker) = false\n    <->\n    exists new_state new_acts, receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (SetBaker param))) = Ok (new_state, new_acts).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl;\n      propify;\n      try easy;\n      now destruct_address_eq.\n  Qed.\n\n\n\n  (** ** Set manager correct *)\n  (** [set_manager] only changes [manager] in state *)\n  Lemma set_manager_state_eq : forall prev_state new_state chain ctx new_acts new_manager,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (SetManager new_manager))) = Ok (new_state, new_acts) ->\n      prev_state<| manager := new_manager |> = new_state.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n  Qed.\n\n  Lemma set_manager_manager_correct : forall prev_state new_state chain ctx new_acts new_manager,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (SetManager new_manager))) = Ok (new_state, new_acts) ->\n      new_state.(manager) = new_manager.\n  Proof.\n    intros * receive_some.\n    apply set_manager_state_eq in receive_some.\n    now subst.\n  Qed.\n\n  (** [set_manager] produces no new_acts *)\n  Lemma set_manager_new_acts_correct : forall chain ctx prev_state new_manager new_state new_acts,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (SetManager new_manager))) = Ok (new_state, new_acts) ->\n      new_acts = [].\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n  Qed.\n\n  (** If the requirements are met then receive on set_manager msg must succeed and\n      if receive on set_manager msg succeeds then requirements must hold *)\n  Lemma set_manager_is_some : forall prev_state chain ctx new_manager,\n    (ctx_amount ctx <= 0)%Z /\\\n    prev_state.(selfIsUpdatingTokenPool) = false /\\\n    ctx.(ctx_from) = prev_state.(manager)\n    <->\n    exists new_state new_acts, receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (SetManager new_manager))) = Ok (new_state, new_acts).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl;\n      propify;\n      try easy;\n      now destruct_address_eq.\n  Qed.\n\n\n\n  (** ** Set liquidity address correct *)\n  (** [set_lqt_address] only changes [lqtAddress] in state *)\n  Lemma set_lqt_address_state_eq : forall prev_state new_state chain ctx new_acts new_lqt_address,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (SetLqtAddress new_lqt_address))) = Ok (new_state, new_acts) ->\n      prev_state<| lqtAddress := new_lqt_address |> = new_state.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n  Qed.\n\n  Lemma set_lqt_address_correct : forall prev_state new_state chain ctx new_acts new_lqt_address,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (SetLqtAddress new_lqt_address))) = Ok (new_state, new_acts) ->\n      new_state.(lqtAddress) = new_lqt_address.\n  Proof.\n    intros * receive_some.\n    apply set_lqt_address_state_eq in receive_some.\n    now subst.\n  Qed.\n\n  (** [set_lqt_address] produces no new_acts *)\n  Lemma set_lqt_address_new_acts_correct : forall chain ctx prev_state new_lqt_address new_state new_acts,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (SetLqtAddress new_lqt_address))) = Ok (new_state, new_acts) ->\n      new_acts = [].\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n  Qed.\n\n  (** If the requirements are met then receive on set_lqt_address msg must succeed and\n      if receive on set_lqt_address msg succeeds then requirements must hold *)\n  Lemma set_lqt_address_is_some : forall prev_state chain ctx new_lqt_address,\n    (ctx_amount ctx <= 0)%Z /\\\n    prev_state.(selfIsUpdatingTokenPool) = false /\\\n    ctx.(ctx_from) = prev_state.(manager) /\\\n    prev_state.(lqtAddress) = null_address\n    <->\n    exists new_state new_acts, receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (SetLqtAddress new_lqt_address))) = Ok (new_state, new_acts).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl;\n      propify;\n      try easy;\n      now destruct_address_eq.\n  Qed.\n\n\n\n  (** ** Default entrypoint correct *)\n  (** [default_] only changes [xtzPool] in state *)\n  Lemma default_state_eq : forall prev_state new_state chain ctx new_acts,\n    receive_cpmm chain ctx prev_state None = Ok (new_state, new_acts) ->\n      prev_state<| xtzPool := prev_state.(xtzPool) + amount_to_N ctx.(ctx_amount) |> = new_state.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n  Qed.\n\n  Lemma default_correct : forall prev_state new_state chain ctx new_acts,\n    receive_cpmm chain ctx prev_state None = Ok (new_state, new_acts) ->\n      new_state.(xtzPool) = prev_state.(xtzPool) + amount_to_N ctx.(ctx_amount).\n  Proof.\n    intros * receive_some.\n    apply default_state_eq in receive_some.\n    now subst.\n  Qed.\n\n  (** [default_] produces no new_acts *)\n  Lemma default_new_acts_correct : forall chain ctx prev_state new_state new_acts,\n    receive_cpmm chain ctx prev_state None = Ok (new_state, new_acts) ->\n      new_acts = [].\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n  Qed.\n\n  (** If the requirements are met then receive on None msg must succeed and\n      if receive on None msg succeeds then requirements must hold *)\n  Lemma default_entrypoint_is_some : forall prev_state chain ctx,\n    prev_state.(selfIsUpdatingTokenPool) = false\n    <->\n    exists new_state new_acts, receive_cpmm chain ctx prev_state None = Ok (new_state, new_acts).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      now contract_simpl.\n  Qed.\n\n\n\n  (** ** Update token pool correct *)\n  (** [update_token_pool] only changes [selfIsUpdatingTokenPool] in state *)\n  Lemma update_token_pool_state_eq : forall prev_state new_state chain ctx new_acts,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg UpdateTokenPool)) = Ok (new_state, new_acts) ->\n      prev_state<| selfIsUpdatingTokenPool := true |> = new_state.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n  Qed.\n\n  Lemma update_token_pool_correct : forall prev_state new_state chain ctx new_acts,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg UpdateTokenPool)) = Ok (new_state, new_acts) ->\n      new_state.(selfIsUpdatingTokenPool) = true.\n  Proof.\n    intros * receive_some.\n    apply update_token_pool_state_eq in receive_some.\n    now subst.\n  Qed.\n\n  (** [update_token_pool] produces a call act with amount = 0, calling\n      the token contract with a balance of request *)\n  Lemma update_token_pool_new_acts_correct : forall chain ctx prev_state new_state new_acts,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg UpdateTokenPool)) = Ok (new_state, new_acts) ->\n      new_acts = [\n        act_call prev_state.(tokenAddress) 0%Z (serialize\n          (msg_balance_of (Build_balance_of_param\n            ([Build_balance_of_request ctx.(ctx_contract_address) prev_state.(tokenId)])\n            (FA2LegacyInterface.Build_callback _ None ctx.(ctx_contract_address)))))\n      ].\n  Proof.\n    intros * receive_some.\n    now contract_simpl.\n  Qed.\n\n  (** If the requirements are met then receive on update_token_pool msg must succeed and\n      if receive on update_token_pool msg succeeds then requirements must hold *)\n  Lemma update_token_pool_is_some : forall prev_state chain ctx,\n    (ctx_amount ctx <= 0)%Z /\\\n    prev_state.(selfIsUpdatingTokenPool) = false /\\\n    ctx.(ctx_from) = ctx.(ctx_origin)\n    <->\n    exists new_state new_acts, receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg UpdateTokenPool)) = Ok (new_state, new_acts).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl;\n      propify;\n      try easy;\n      now destruct_address_eq.\n  Qed.\n\n  Tactic Notation \"invert_responses_Some\" :=\n    match goal with\n    | [H : match ?rs with\n           | [] => _\n           | _ => _\n           end = Ok _ |- _] =>\n        match type of rs with\n        | list balance_of_response =>\n            destruct rs; inversion H; clear H\n        | _ => fail \"No match on list of balance_of_response\"\n        end\n    end.\n\n\n\n  (** ** Update token pool internal correct *)\n  (** [update_token_pool_internal] only changes [selfIsUpdatingTokenPool] and [tokenPool] in state *)\n  Lemma update_token_pool_internal_state_eq : forall prev_state new_state chain ctx new_acts responses,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.receive_balance_of_param responses)) = Ok (new_state, new_acts) ->\n      prev_state<| selfIsUpdatingTokenPool := false |>\n                <| tokenPool := match responses with\n                                | [] => 0\n                                | response :: t => response.(balance)\n                                end |> = new_state.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now invert_responses_Some.\n  Qed.\n\n  Lemma update_token_pool_internal_update_correct : forall prev_state new_state chain ctx new_acts responses,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.receive_balance_of_param responses)) = Ok (new_state, new_acts) ->\n      new_state.(selfIsUpdatingTokenPool) = false.\n  Proof.\n    intros * receive_some.\n    apply update_token_pool_internal_state_eq in receive_some.\n    now subst.\n  Qed.\n\n  (** [update_token_pool_internal] produces no new actions *)\n  Lemma update_token_pool_internal_new_acts_correct : forall chain ctx prev_state new_state new_acts responses,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.receive_balance_of_param responses)) = Ok (new_state, new_acts) ->\n      new_acts = [].\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n  Qed.\n\n  (** If the requirements are met then receive on update_token_pool_internal msg must succeed and\n      if receive on update_token_pool_internal msg succeeds then requirements must hold *)\n  Lemma update_token_pool_internal_is_some : forall prev_state chain ctx responses,\n    (ctx_amount ctx <= 0)%Z /\\\n    prev_state.(selfIsUpdatingTokenPool) = true /\\\n    ctx.(ctx_from) = prev_state.(tokenAddress) /\\\n    responses <> []\n    <->\n    exists new_state new_acts, receive_cpmm chain ctx prev_state (Some (FA2Token.receive_balance_of_param responses)) = Ok (new_state, new_acts).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl; eauto;\n      destruct responses;\n      propify;\n      destruct_or_hyps;\n      try easy;\n      now destruct_address_eq.\n  Qed.\n\n\n\n  (** ** Add liquidity correct *)\n  (** [add_liquidity] only changes [lqtTotal], [tokenPool] and [xtzPool] in state *)\n  Lemma add_liquidity_state_eq : forall prev_state new_state chain ctx new_acts param,\n    let lqt_minted := amount_to_N ctx.(ctx_amount) * prev_state.(lqtTotal) / prev_state.(xtzPool) in\n    let tokens_deposited := ceildiv_ (amount_to_N ctx.(ctx_amount) * prev_state.(tokenPool)) prev_state.(xtzPool) in\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (AddLiquidity param))) = Ok (new_state, new_acts) ->\n      prev_state<| lqtTotal := prev_state.(lqtTotal) + lqt_minted |>\n                <| tokenPool := prev_state.(tokenPool) + tokens_deposited |>\n                <| xtzPool := prev_state.(xtzPool) + amount_to_N ctx.(ctx_amount) |> = new_state.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now math_convert.\n  Qed.\n\n  Lemma add_liquidity_correct : forall prev_state new_state chain ctx new_acts param,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (AddLiquidity param))) = Ok (new_state, new_acts) ->\n      new_state.(lqtTotal) = prev_state.(lqtTotal) + amount_to_N ctx.(ctx_amount) * prev_state.(lqtTotal) / prev_state.(xtzPool) /\\\n      new_state.(tokenPool) = prev_state.(tokenPool) + ceildiv_ (amount_to_N ctx.(ctx_amount) * prev_state.(tokenPool)) prev_state.(xtzPool) /\\\n      new_state.(xtzPool) = prev_state.(xtzPool) + amount_to_N ctx.(ctx_amount).\n  Proof.\n    intros * receive_some.\n    apply add_liquidity_state_eq in receive_some.\n    now subst.\n  Qed.\n\n  (** In the informal specification it is stated that tokens should be trasnferred from owner,\n      but in the implementation it is trasnferred from the sender.\n      For this we assume that the implementation is correct over the informal specification since\n      that is what other formalizations seem to have assumed *)\n  Lemma add_liquidity_new_acts_correct : forall chain ctx prev_state new_state new_acts param,\n    let lqt_minted := amount_to_N ctx.(ctx_amount) * prev_state.(lqtTotal) / prev_state.(xtzPool) in\n    let tokens_deposited := ceildiv_ (amount_to_N ctx.(ctx_amount) * prev_state.(tokenPool)) prev_state.(xtzPool) in\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (AddLiquidity param))) = Ok (new_state, new_acts) ->\n      new_acts =\n      [\n        (act_call prev_state.(tokenAddress) 0%Z\n          (serialize (FA2Token.msg_transfer\n          [build_transfer ctx.(ctx_from) [build_transfer_destination ctx.(ctx_contract_address) prev_state.(tokenId) tokens_deposited] None])));\n        (act_call prev_state.(lqtAddress) 0%Z\n          (serialize (Dexter2FA12.msg_mint_or_burn {| target := param.(owner); quantity := Z.of_N lqt_minted|})))\n      ].\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now math_convert.\n  Qed.\n\n  (** If the requirements are met then receive on add_liquidity msg must succeed and\n      if receive on add_liquidity msg succeeds then requirements must hold *)\n  Lemma add_liquidity_is_some : forall prev_state chain ctx param,\n    let lqt_minted := amount_to_N ctx.(ctx_amount) * prev_state.(lqtTotal) / prev_state.(xtzPool) in\n    let tokens_deposited := ceildiv_ (amount_to_N ctx.(ctx_amount) * prev_state.(tokenPool)) prev_state.(xtzPool) in\n    prev_state.(selfIsUpdatingTokenPool) = false /\\\n    (current_slot chain < param.(add_deadline))%nat /\\\n    tokens_deposited <= param.(maxTokensDeposited) /\\\n    param.(minLqtMinted) <= lqt_minted /\\\n    prev_state.(xtzPool) <> 0 /\\\n    prev_state.(lqtAddress) <> null_address\n    <->\n    exists new_state new_acts, receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (AddLiquidity param))) = Ok (new_state, new_acts).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl;\n      propify;\n      math_convert;\n      unfold amount_to_N in *;\n      try easy;\n      try now destruct_address_eq.\n\n  Qed.\n\n\n\n  (** ** Remove liquidity correct *)\n  (** [remove_liquidity] only changes [lqtTotal], [tokenPool] and [xtzPool] in state *)\n  Lemma remove_liquidity_state_eq : forall prev_state new_state chain ctx new_acts param,\n    let xtz_withdrawn := (param.(lqtBurned) * prev_state.(xtzPool)) / prev_state.(lqtTotal) in\n    let tokens_withdrawn := (param.(lqtBurned) * prev_state.(tokenPool)) / prev_state.(lqtTotal) in\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (RemoveLiquidity param))) = Ok (new_state, new_acts) ->\n      prev_state<| lqtTotal := prev_state.(lqtTotal) - param.(lqtBurned) |>\n                <| tokenPool := prev_state.(tokenPool) - tokens_withdrawn |>\n                <| xtzPool := prev_state.(xtzPool) - xtz_withdrawn |> = new_state.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now math_convert; cbv.\n  Qed.\n\n  Lemma remove_liquidity_correct : forall prev_state new_state chain ctx new_acts param,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (RemoveLiquidity param))) = Ok (new_state, new_acts) ->\n      new_state.(lqtTotal) = prev_state.(lqtTotal) - param.(lqtBurned) /\\\n      new_state.(tokenPool) = prev_state.(tokenPool) - (param.(lqtBurned) * prev_state.(tokenPool)) / prev_state.(lqtTotal) /\\\n      new_state.(xtzPool) = prev_state.(xtzPool) - (param.(lqtBurned) * prev_state.(xtzPool)) / prev_state.(lqtTotal).\n  Proof.\n    intros * receive_some.\n    apply remove_liquidity_state_eq in receive_some.\n    now subst.\n  Qed.\n\n  (** [remove_liquidity] should produce three acts\n  - A call action to LQT contract burning [lqtBurned] from [sender]\n  - A call action to token contract transferring [tokens_withdrawn] from this contract to [liquidity_to]\n  - A transfer action transferring [xtz_withdrawn] from this contract to [liquidity_to]\n   *)\n  Lemma remove_liquidity_new_acts_correct : forall chain ctx prev_state new_state new_acts param,\n    let xtz_withdrawn := (param.(lqtBurned) * prev_state.(xtzPool)) / prev_state.(lqtTotal) in\n    let tokens_withdrawn := (param.(lqtBurned) * prev_state.(tokenPool)) / prev_state.(lqtTotal) in\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (RemoveLiquidity param))) = Ok (new_state, new_acts) ->\n      new_acts =\n      [\n        (act_call prev_state.(lqtAddress) 0%Z\n          (serialize (Dexter2FA12.msg_mint_or_burn {| target := ctx.(ctx_from); quantity := - Z.of_N param.(lqtBurned)|})));\n        (act_call prev_state.(tokenAddress) 0%Z\n          (serialize (FA2Token.msg_transfer\n          [build_transfer ctx.(ctx_contract_address) [build_transfer_destination param.(liquidity_to) prev_state.(tokenId) tokens_withdrawn] None])));\n        (act_transfer param.(liquidity_to) (N_to_amount xtz_withdrawn))\n      ].\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    math_convert.\n    unfold xtz_transfer in *.\n    destruct_match in *; try congruence.\n    match goal with\n      [ H : Ok _ = Ok _ |- _ ] => now inversion H\n    end.\n  Qed.\n\n  (** If the requirements are met then receive on remove_liquidity msg must succeed and\n      if receive on remove_liquidity msg succeeds then requirements must hold *)\n  Lemma remove_liquidity_is_some : forall prev_state chain ctx param,\n    let xtz_withdrawn := (param.(lqtBurned) * prev_state.(xtzPool)) / prev_state.(lqtTotal) in\n    let tokens_withdrawn := (param.(lqtBurned) * prev_state.(tokenPool)) / prev_state.(lqtTotal) in\n    prev_state.(selfIsUpdatingTokenPool) = false /\\\n    (current_slot chain < param.(remove_deadline))%nat /\\\n    (ctx.(ctx_amount) <= 0)%Z /\\\n    prev_state.(lqtTotal) <> 0 /\\\n    param.(minXtzWithdrawn) <= xtz_withdrawn /\\\n    param.(minTokensWithdrawn) <= tokens_withdrawn /\\\n    tokens_withdrawn <= prev_state.(tokenPool) /\\\n    xtz_withdrawn <= prev_state.(xtzPool) /\\\n    param.(lqtBurned) <= prev_state.(lqtTotal) /\\\n    address_is_contract param.(liquidity_to) = false /\\\n    prev_state.(lqtAddress) <> null_address\n    <->\n    exists new_state new_acts, receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (RemoveLiquidity param))) = Ok (new_state, new_acts).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl;\n      propify;\n      math_convert;\n      try easy;\n      try now destruct_address_eq.\n    all :\n      unfold xtz_transfer in *;\n      destruct_match in *;\n      now destruct_address_eq.\n  Qed.\n\n\n  (** ** XTZ to token correct *)\n  (** [xtz_to_token] only changes [tokenPool] and [xtzPool] in state *)\n  Lemma xtz_to_token_state_eq : forall prev_state new_state chain ctx new_acts param,\n    let tokens_bought := ((amount_to_N ctx.(ctx_amount)) * 997 * prev_state.(tokenPool)) /\n                            (prev_state.(xtzPool) * 1000 + ((amount_to_N ctx.(ctx_amount)) * 997)) in\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (XtzToToken param))) = Ok (new_state, new_acts) ->\n      prev_state<| tokenPool := prev_state.(tokenPool) - tokens_bought |>\n                <| xtzPool := prev_state.(xtzPool) + amount_to_N ctx.(ctx_amount) |> = new_state.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now math_convert.\n  Qed.\n\n  Lemma xtz_to_token_correct : forall prev_state new_state chain ctx new_acts param,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (XtzToToken param))) = Ok (new_state, new_acts) ->\n      new_state.(tokenPool) = prev_state.(tokenPool) - (((amount_to_N ctx.(ctx_amount)) * 997 * prev_state.(tokenPool)) /\n                            (prev_state.(xtzPool) * 1000 + ((amount_to_N ctx.(ctx_amount)) * 997))) /\\\n      new_state.(xtzPool) = prev_state.(xtzPool) + amount_to_N ctx.(ctx_amount).\n  Proof.\n    intros * receive_some.\n    apply xtz_to_token_state_eq in receive_some.\n    now subst.\n  Qed.\n\n  (** [xtz_to_token] should produce one action\n  - A call action to token contract transferring [tokens_bought] from this contract to [tokens_to]\n  *)\n  Lemma xtz_to_token_new_acts_correct : forall chain ctx prev_state new_state new_acts param,\n    let tokens_bought := ((amount_to_N ctx.(ctx_amount)) * 997 * prev_state.(tokenPool)) /\n                            (prev_state.(xtzPool) * 1000 + ((amount_to_N ctx.(ctx_amount)) * 997)) in\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (XtzToToken param))) = Ok (new_state, new_acts) ->\n      new_acts =\n      [\n        (act_call prev_state.(tokenAddress) 0%Z\n          (serialize (FA2Token.msg_transfer\n          [build_transfer ctx.(ctx_contract_address) [build_transfer_destination param.(tokens_to) prev_state.(tokenId) tokens_bought] None])))\n      ].\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now math_convert.\n  Qed.\n\n  (** If the requirements are met then receive on xtz_to_token msg must succeed and\n      if receive on xtz_to_token msg succeeds then requirements must hold *)\n  Lemma xtz_to_token_is_some : forall prev_state chain ctx param,\n    let tokens_bought := ((amount_to_N ctx.(ctx_amount)) * 997 * prev_state.(tokenPool)) /\n                            (prev_state.(xtzPool) * 1000 + ((amount_to_N ctx.(ctx_amount)) * 997)) in\n    prev_state.(selfIsUpdatingTokenPool) = false /\\\n    (current_slot chain < param.(xtt_deadline))%nat /\\\n    (prev_state.(xtzPool) <> 0 \\/ (0 < ctx.(ctx_amount))%Z) /\\\n    param.(minTokensBought) <= tokens_bought /\\\n    tokens_bought <= prev_state.(tokenPool)\n    <->\n    exists new_state new_acts, receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (XtzToToken param))) = Ok (new_state, new_acts).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl;\n      propify;\n      math_convert;\n      unfold amount_to_N in *;\n      try easy;\n      now destruct_address_eq.\n  Qed.\n\n\n  (** ** Token to xtz correct *)\n  (** [token_to_xtz] only changes [tokenPool] and [xtzPool] in state *)\n  Lemma token_to_xtz_state_eq : forall prev_state new_state chain ctx new_acts param,\n    let xtz_bought := (param.(tokensSold) * 997 * prev_state.(xtzPool)) /\n                            (prev_state.(tokenPool) * 1000 + (param.(tokensSold) * 997)) in\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (TokenToXtz param))) = Ok (new_state, new_acts) ->\n      prev_state<| tokenPool := prev_state.(tokenPool) + param.(tokensSold) |>\n                <| xtzPool := prev_state.(xtzPool) - xtz_bought |> = new_state.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now math_convert.\n  Qed.\n\n  Lemma token_to_xtz_correct : forall prev_state new_state chain ctx new_acts param,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (TokenToXtz param))) = Ok (new_state, new_acts) ->\n      new_state.(tokenPool) = prev_state.(tokenPool) + param.(tokensSold) /\\\n      new_state.(xtzPool) = prev_state.(xtzPool) - ((param.(tokensSold) * 997 * prev_state.(xtzPool)) /\n                            (prev_state.(tokenPool) * 1000 + (param.(tokensSold) * 997))).\n  Proof.\n    intros * receive_some.\n    apply token_to_xtz_state_eq in receive_some.\n    now subst.\n  Qed.\n\n  (** token_to_xtz should produce two actions\n  - A call action to token contract transferring [tokens_sold] from [sender] to this contract\n  - A transfer action transferring [xtz_bought] from this contract to [xtz_to]\n   *)\n  Lemma token_to_xtz_new_acts_correct : forall chain ctx prev_state new_state new_acts param,\n    let xtz_bought := (param.(tokensSold) * 997 * prev_state.(xtzPool)) /\n                            (prev_state.(tokenPool) * 1000 + (param.(tokensSold) * 997)) in\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (TokenToXtz param))) = Ok (new_state, new_acts) ->\n      new_acts =\n      [\n        (act_call prev_state.(tokenAddress) 0%Z\n          (serialize (FA2Token.msg_transfer\n          [build_transfer ctx.(ctx_from) [build_transfer_destination ctx.(ctx_contract_address) prev_state.(tokenId) param.(tokensSold)] None])));\n        (act_transfer param.(xtz_to) (N_to_amount xtz_bought))\n      ].\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    math_convert.\n    unfold xtz_transfer in *.\n    destruct_match in *; try congruence.\n    match goal with\n      [H : Ok _ = Ok _ |- _] => now inversion H\n    end.\n  Qed.\n\n  (** If the requirements are met then receive on token_to_xtz msg must succeed and\n      if receive on token_to_xtz msg succeeds then requirements must hold *)\n  Lemma token_to_xtz_is_some : forall prev_state chain ctx param,\n    let xtz_bought := (param.(tokensSold) * 997 * prev_state.(xtzPool)) /\n                            (prev_state.(tokenPool) * 1000 + (param.(tokensSold) * 997)) in\n    prev_state.(selfIsUpdatingTokenPool) = false /\\\n    (current_slot chain < param.(ttx_deadline))%nat /\\\n    (ctx.(ctx_amount) <= 0)%Z /\\\n    param.(minXtzBought) <= xtz_bought /\\\n    (prev_state.(tokenPool) <> 0 \\/ param.(tokensSold) <> 0) /\\\n    address_is_contract param.(xtz_to) = false /\\\n    xtz_bought <= prev_state.(xtzPool)\n    <->\n    exists new_state new_acts, receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (TokenToXtz param))) = Ok (new_state, new_acts).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl;\n      propify;\n      math_convert;\n      try easy;\n      try now destruct_address_eq.\n    all :\n      unfold xtz_transfer in *;\n      destruct_match in *;\n      now destruct_address_eq.\n  Qed.\n\n\n\n  (** ** Token to token correct *)\n  (** [token_to_token] only changes [tokenPool] and [xtzPool] in state *)\n  Lemma token_to_token_state_eq : forall prev_state new_state chain ctx new_acts param,\n    let xtz_bought := (param.(tokensSold_) * 997 * prev_state.(xtzPool)) /\n                            (prev_state.(tokenPool) * 1000 + (param.(tokensSold_) * 997)) in\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (TokenToToken param))) = Ok (new_state, new_acts) ->\n      prev_state<| tokenPool := prev_state.(tokenPool) + param.(tokensSold_) |>\n                <| xtzPool := prev_state.(xtzPool) - xtz_bought |> = new_state.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now math_convert.\n  Qed.\n\n  Lemma token_to_token_correct : forall prev_state new_state chain ctx new_acts param,\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (TokenToToken param))) = Ok (new_state, new_acts) ->\n      new_state.(tokenPool) = prev_state.(tokenPool) + param.(tokensSold_) /\\\n      new_state.(xtzPool) = prev_state.(xtzPool) - ((param.(tokensSold_) * 997 * prev_state.(xtzPool)) /\n                            (prev_state.(tokenPool) * 1000 + (param.(tokensSold_) * 997))).\n  Proof.\n    intros * receive_some.\n    apply token_to_token_state_eq in receive_some.\n    now subst.\n  Qed.\n\n  (** token_to_token should produce two actions\n  - A call action to token contract transferring [tokens_sold] from [sender] to this contract\n  - A call action to [outputDexterContract] [xtz_to_token] entrypoint with [xtz_bought] amount attached\n   *)\n  Lemma token_to_token_new_acts_correct : forall chain ctx prev_state new_state new_acts param,\n    let xtz_bought := (param.(tokensSold_) * 997 * prev_state.(xtzPool)) /\n                            (prev_state.(tokenPool) * 1000 + (param.(tokensSold_) * 997)) in\n    receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (TokenToToken param))) = Ok (new_state, new_acts) ->\n      new_acts =\n      [\n        (act_call prev_state.(tokenAddress) 0%Z\n          (serialize (FA2Token.msg_transfer\n          [build_transfer ctx.(ctx_from) [build_transfer_destination ctx.(ctx_contract_address) prev_state.(tokenId) param.(tokensSold_)] None])));\n        (act_call param.(outputDexterContract) (N_to_amount xtz_bought)\n          (serialize ((FA2Token.other_msg (XtzToToken\n          {| tokens_to := param.(to_);\n             minTokensBought := param.(minTokensBought_);\n             xtt_deadline := param.(ttt_deadline) |})))))\n      ].\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now math_convert.\n  Qed.\n\n  (** If the requirements are met then receive on token_to_token msg must succeed and\n      if receive on token_to_token msg succeeds then requirements must hold *)\n  Lemma token_to_token_is_some : forall prev_state chain ctx param,\n    let xtz_bought := (param.(tokensSold_) * 997 * prev_state.(xtzPool)) /\n                            (prev_state.(tokenPool) * 1000 + (param.(tokensSold_) * 997)) in\n    prev_state.(selfIsUpdatingTokenPool) = false /\\\n    (current_slot chain < param.(ttt_deadline))%nat /\\\n    (ctx.(ctx_amount) <= 0)%Z /\\\n    xtz_bought <= prev_state.(xtzPool) /\\\n    (prev_state.(tokenPool) <> 0 \\/ param.(tokensSold_) <> 0)\n    <->\n    exists new_state new_acts, receive_cpmm chain ctx prev_state (Some (FA2Token.other_msg (TokenToToken param))) = Ok (new_state, new_acts).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl;\n      propify;\n      math_convert;\n      try easy;\n      now destruct_address_eq.\n  Qed.\n\n\n\n  (** ** Init correct *)\n  Lemma init_state_eq : forall chain ctx setup state,\n    init_cpmm chain ctx setup = Ok state ->\n      state = {|\n        tokenPool := 0;\n        xtzPool := 0;\n        lqtTotal := setup.(lqtTotal_);\n        selfIsUpdatingTokenPool := false;\n        freezeBaker := false;\n        manager := setup.(manager_);\n        tokenAddress := setup.(tokenAddress_);\n        lqtAddress := null_address;\n        tokenId := setup.(tokenId_)\n      |}.\n  Proof.\n    intros * init_some.\n    now contract_simpl.\n  Qed.\n\n  Lemma init_correct : forall chain ctx setup state,\n    init_cpmm chain ctx setup = Ok state ->\n      tokenPool state = 0 /\\\n      xtzPool state = 0 /\\\n      lqtTotal state = setup.(lqtTotal_) /\\\n      selfIsUpdatingTokenPool state = false /\\\n      freezeBaker state = false /\\\n      manager state = setup.(manager_) /\\\n      tokenAddress state = setup.(tokenAddress_) /\\\n      lqtAddress state = null_address /\\\n      tokenId state = setup.(tokenId_).\n  Proof.\n    intros * init_some.\n    apply init_state_eq in init_some.\n    now subst.\n  Qed.\n\n  (** Initialization should always succeed *)\n  Lemma init_is_some : forall chain ctx setup,\n    exists state, init_cpmm chain ctx setup = state.\n  Proof.\n    eauto.\n  Qed.\n\n\n\n  (* begin hide *)\n  Ltac rewrite_acts_correct :=\n    match goal with\n    | [ H : receive_cpmm _ _ _ _ = Ok _ |- _ ] =>\n      first [apply set_baker_new_acts_correct in H as new_acts_eq;\n              rewrite set_delegate_call_nil in new_acts_eq\n            |apply set_manager_new_acts_correct in H as new_acts_eq\n            |apply set_lqt_address_new_acts_correct in H as new_acts_eq\n            |apply default_new_acts_correct in H as new_acts_eq\n            |apply update_token_pool_new_acts_correct in H as new_acts_eq\n            |apply update_token_pool_internal_new_acts_correct in H as new_acts_eq\n            |apply add_liquidity_new_acts_correct in H as new_acts_eq\n            |apply remove_liquidity_new_acts_correct in H as new_acts_eq\n            |apply xtz_to_token_new_acts_correct in H as new_acts_eq\n            |apply token_to_xtz_new_acts_correct in H as new_acts_eq\n            |apply token_to_token_new_acts_correct in H as new_acts_eq];\n      subst\n    end.\n\n  Ltac rewrite_state_eq :=\n    match goal with\n    | [ H : receive_cpmm _ _ _ _ = Ok _ |- _ ] =>\n      first [apply set_baker_state_eq in H as new_acts_eq\n            |apply set_manager_state_eq in H as new_acts_eq\n            |apply set_lqt_address_state_eq in H as new_acts_eq\n            |apply default_state_eq in H as new_acts_eq\n            |apply update_token_pool_state_eq in H as new_acts_eq\n            |apply update_token_pool_internal_state_eq in H as new_acts_eq\n            |apply add_liquidity_state_eq in H as new_acts_eq\n            |apply remove_liquidity_state_eq in H as new_acts_eq\n            |apply xtz_to_token_state_eq in H as new_acts_eq\n            |apply token_to_xtz_state_eq in H as new_acts_eq\n            |apply token_to_token_state_eq in H as new_acts_eq ];\n      subst\n    end.\n\n  Ltac rewrite_receive_is_some :=\n    match goal with\n    | [ H : receive_cpmm _ _ _ _ = Ok _ |- _ ] =>\n      first [specialize set_baker_is_some as (_ & []); [now (do 2 eexists; apply H) |]\n            |specialize set_manager_is_some as (_ & []); [now (do 2 eexists; apply H) |]\n            |specialize set_lqt_address_is_some as (_ & []); [now (do 2 eexists; apply H) |]\n            |specialize default_entrypoint_is_some as (_ & []); [now (do 2 eexists; apply H) |]\n            |specialize update_token_pool_is_some as (_ & []); [now (do 2 eexists; apply H) |]\n            |specialize update_token_pool_internal_is_some as (_ & []); [now (do 2 eexists; apply H) |]\n            |specialize add_liquidity_is_some as (_ & []); [now (do 2 eexists; apply H) |]\n            |specialize remove_liquidity_is_some as (_ & []); [now (do 2 eexists; apply H) |]\n            |specialize xtz_to_token_is_some as (_ & []); [now (do 2 eexists; apply H) |]\n            |specialize token_to_xtz_is_some as (_ & []); [now (do 2 eexists; apply H) |]\n            |specialize token_to_token_is_some as (_ & []); [now (do 2 eexists; apply H) |] ];\n      destruct_hyps; subst\n    end.\n  (* end hide *)\n\n\n\n  (** ** Outgoing acts facts *)\n  (** If contract emits self calls then they are for the XtzToToken entrypoint or default entrypoint *)\n  Lemma self_calls' bstate caddr :\n    reachable bstate ->\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate,\n      contract_state bstate caddr = Some cstate /\\\n      (tokenAddress cstate <> caddr ->\n      Forall (fun act_body =>\n        match act_body with\n        | act_transfer to _ => True\n        | act_call to _ msg => to = caddr ->\n            (exists p, msg = serialize (FA2Token.other_msg (XtzToToken p))) \\/\n            (exists p, msg = serialize (msg_mint_or_burn p))\n        | _ => False\n        end) (outgoing_acts bstate caddr)).\n  Proof.\n    contract_induction; intros; cbn in *; auto.\n    - now apply list.Forall_cons in IH as [_ IH].\n    - destruct_message;\n        rewrite_acts_correct;\n        rewrite_state_eq;\n        try (apply Forall_app; split);\n        try apply IH; auto;\n        rewrite ?list.Forall_cons, ?list.Forall_nil;\n        try easy.\n    - destruct_message;\n        rewrite_acts_correct;\n        rewrite_state_eq;\n        try (apply Forall_app; split);\n        apply list.Forall_cons in IH as [? IH];\n        try apply IH; auto;\n        rewrite ?list.Forall_cons, ?list.Forall_nil;\n        try easy.\n    - now rewrite <- perm.\n    - solve_facts.\n  Qed.\n\n  Local Open Scope Z_scope.\n  Lemma call_amount_zero bstate caddr :\n    reachable bstate ->\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n      Forall (fun act_body =>\n        match act_body with\n        | act_transfer _ amount => True\n        | act_call _ amount msg => amount = 0 \\/ exists p, msg = serialize (FA2Token.other_msg (XtzToToken p))\n        | act_deploy amount _ _ => amount = 0\n        end) (outgoing_acts bstate caddr).\n  Proof.\n    intros.\n    apply (lift_outgoing_acts_prop contract); auto.\n    intros * receive_some.\n    cbn in receive_some.\n    destruct_message;\n      rewrite_acts_correct;\n      rewrite ?list.Forall_cons, list.Forall_nil;\n      easy.\n  Qed.\n\n  Lemma no_contract_deployment bstate caddr :\n    reachable bstate ->\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n      Forall (fun act_body =>\n        match act_body with\n        | act_deploy amount _ _ => False\n        | _ => True\n        end) (outgoing_acts bstate caddr).\n  Proof.\n    intros.\n    apply (lift_outgoing_acts_prop contract); auto.\n    intros * receive_some.\n    cbn in receive_some.\n    destruct_message;\n      rewrite_acts_correct; auto.\n  Qed.\n\n\n\n  (** ** Contract balance facts *)\n  Lemma contract_balance_correct' : forall bstate caddr (trace : ChainTrace empty_state bstate),\n    let effective_balance := (env_account_balances bstate caddr - (sumZ (fun act => act_body_amount act) (outgoing_acts bstate caddr)))%Z in\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate deploy_info,\n      contract_state bstate caddr = Some cstate /\\\n      deployment_info Setup trace caddr = Some deploy_info /\\\n       (deploy_info.(deployment_amount) = 0%Z -> Z.of_N (xtzPool cstate) = effective_balance).\n  Proof.\n    intros.\n    subst effective_balance.\n    contract_induction; intros; auto.\n    - cbn in *.\n      apply init_correct in init_some as (_ & ? & _).\n      lia.\n    - cbn in IH.\n      lia.\n    - instantiate (CallFacts := fun _ ctx _ _ _ =>\n        (0 <= ctx_amount ctx)%Z).\n      unfold CallFacts in facts.\n      cbn in receive_some.\n      destruct_message;\n        rewrite_acts_correct;\n        rewrite_state_eq;\n        rewrite_receive_is_some;\n        unfold N_to_amount in *;\n        try match goal with\n        | H : (?x <= ?y)%Z, G : (?y <= ?x)%Z |- _ => apply Z.le_antisymm in H; auto; rewrite H in *\n        end;\n        cbn;\n        try lia.\n    - unfold CallFacts in facts.\n      cbn in receive_some.\n      destruct head;\n        auto;\n        cbn in IH;\n        destruct action_facts as (? & ? & ?);\n        subst;\n      destruct_message;\n        rewrite_acts_correct;\n        rewrite_state_eq;\n        rewrite_receive_is_some;\n        unfold N_to_amount in *;\n        try match goal with\n        | H : (?x <= ?y)%Z, G : (?y <= ?x)%Z |- _ => apply Z.le_antisymm in H; auto; rewrite H in *\n        end;\n        cbn;\n        try lia.\n    - now erewrite sumZ_permutation in IH by eauto.\n    - solve_facts.\n      now apply Z.ge_le.\n  Qed.\n\n  Definition no_transfers (queue : list ActionBody) :=\n    Forall (fun act_body =>\n      match act_body with\n      | act_transfer to _ => False\n      | act_call to _ msg => forall p, msg <> serialize (FA2Token.other_msg (XtzToToken p))\n      | _ => True\n      end) queue.\n\n  Lemma contract_balance_correct : forall bstate caddr (trace : ChainTrace empty_state bstate),\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate deploy_info,\n      contract_state bstate caddr = Some cstate /\\\n      deployment_info Setup trace caddr = Some deploy_info /\\\n       (deploy_info.(deployment_amount) = 0%Z ->\n        no_transfers (outgoing_acts bstate caddr) ->\n          Z.of_N (xtzPool cstate) = env_account_balances bstate caddr).\n  Proof.\n    intros * deployed.\n    eapply contract_balance_correct' in deployed as balance_correct.\n    destruct balance_correct as (cstate & deploy_info & deployed_state & ? & balance_correct).\n    eapply call_amount_zero in deployed as amount_zero; try now constructor.\n    do 2 eexists.\n    intuition.\n    rewrite balance_correct by auto.\n    clear balance_correct.\n    rename H1 into no_transfer.\n    unfold no_transfers in no_transfer.\n    assert (sum_zero : sumZ (fun act : ActionBody => act_body_amount act) (outgoing_acts bstate caddr) = 0%Z).\n    - induction outgoing_acts; auto.\n      apply list.Forall_cons in no_transfer as (no_transfer & no_transfers).\n      apply list.Forall_cons in amount_zero as (amount_zero & amounts_zero).\n      destruct a; auto; cbn; rewrite IHl by auto;\n        clear IHl no_transfers amounts_zero.\n      + now destruct amount_zero as [-> | []].\n      + now subst.\n    - lia.\n  Qed.\n\n  Lemma xtz_pool_bound : forall bstate caddr (trace : ChainTrace empty_state bstate),\n    let effective_balance := (env_account_balances bstate caddr - (sumZ (fun act => act_body_amount act) (outgoing_acts bstate caddr)))%Z in\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate,\n      contract_state bstate caddr = Some cstate /\\\n       Z.of_N (xtzPool cstate) <= effective_balance.\n  Proof.\n    intros.\n    subst effective_balance.\n    contract_induction; intros; auto.\n    - instantiate (DeployFacts := fun _ ctx =>\n        (0 <= ctx_amount ctx)%Z).\n      unfold DeployFacts in facts.\n      cbn in *.\n      apply init_correct in init_some as (_ & -> & _).\n      lia.\n    - cbn in IH.\n      lia.\n    - instantiate (CallFacts := fun _ ctx _ _ _ =>\n        (0 <= ctx_amount ctx)%Z).\n      unfold CallFacts in facts.\n      cbn in receive_some.\n      destruct_message;\n        rewrite_acts_correct;\n        rewrite_state_eq;\n        rewrite_receive_is_some;\n        unfold N_to_amount in *;\n        try match goal with\n        | H : (?x <= ?y)%Z, G : (?y <= ?x)%Z |- _ => apply Z.le_antisymm in H; auto; rewrite H in *\n        end;\n        cbn;\n        try lia.\n    - unfold CallFacts in facts.\n      cbn in receive_some.\n      destruct head;\n        auto;\n        cbn in IH;\n        destruct action_facts as (? & ? & ?);\n        subst;\n      destruct_message;\n        rewrite_acts_correct;\n        rewrite_state_eq;\n        rewrite_receive_is_some;\n        unfold N_to_amount in *;\n        try match goal with\n        | H : (?x <= ?y)%Z, G : (?y <= ?x)%Z |- _ => apply Z.le_antisymm in H; auto; rewrite H in *\n        end;\n        cbn;\n        try lia.\n    - now erewrite sumZ_permutation in IH by eauto.\n    - solve_facts.\n      + cbn.\n        lia.\n      + now apply Z.ge_le.\n  Qed.\n\n  Lemma transfer_bound bstate caddr :\n    let transfered_balance := sumZ (fun act => act_body_amount act) (outgoing_acts bstate caddr) in\n    reachable bstate ->\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate : State,\n      contract_state bstate caddr = Some cstate /\\\n      transfered_balance <= env_account_balances bstate caddr.\n  Proof.\n    intros.\n    subst transfered_balance.\n    contract_induction; intros; cbn in *; auto.\n    - instantiate (DeployFacts := fun _ ctx =>\n        (0 <= ctx_amount ctx)%Z).\n      auto.\n    - lia.\n    - instantiate (CallFacts := fun _ ctx state out_acts _ =>\n        (0 <= ctx_amount ctx)%Z /\\\n        Z.of_N (xtzPool state) <= ctx_contract_balance ctx- sumZ (fun act => act_body_amount act) out_acts).\n      destruct facts.\n      destruct_message;\n        rewrite_acts_correct;\n        rewrite_receive_is_some;\n        unfold N_to_amount in *;\n        try match goal with\n        | H : (?x <= ?y)%Z, G : (?y <= ?x)%Z |- _ => apply Z.le_antisymm in H; auto; rewrite H in *\n        end;\n        cbn;\n        try lia.\n    - destruct facts.\n      destruct head;\n        auto;\n        cbn in IH;\n        destruct action_facts as (? & ? & ?);\n        subst.\n      + contract_simpl.\n        cbn in *.\n        lia.\n      + destruct_message;\n          rewrite_acts_correct;\n          rewrite_receive_is_some;\n          unfold N_to_amount in *;\n          try match goal with\n          | H : (?x <= ?y)%Z, G : (?y <= ?x)%Z |- _ => apply Z.le_antisymm in H; auto; rewrite H in *\n          end;\n          cbn in *;\n          try lia.\n    - now rewrite <- perm.\n    - solve_facts.\n      + cbn.\n        lia.\n      + split.\n        * now apply Z.ge_le.\n        * specialize (account_balance_nonnegative bstate_from to_addr) as ?H.\n          specialize xtz_pool_bound as (? & deployed_state' & ?); eauto.\n          cbn in *.\n          rewrite deployed_state in deployed_state'.\n          rewrite deployed_state in deployed_state0.\n          rewrite deployed_state0 in deployed_state'.\n          inversion deployed_state'.\n          subst.\n          destruct_address_eq; try easy; lia.\n  Qed.\n\n\n\n  (** ** Total supply correct *)\n  Definition mintedOrBurnedTokens_acts (act_body : ActionBody) : Z :=\n    match act_body with\n    | act_call _ _ msg_serialized =>\n      match @deserialize Dexter2FA12.Msg D2LqtSInstances.msg_serializable msg_serialized with\n      | Some msg => mintedOrBurnedTokens (Some msg)\n      | _ => 0\n      end\n    | _ => 0\n    end.\n\n  Definition mintedOrBurnedTokens_tx (tx : Tx) : Z :=\n    match tx.(tx_body) with\n    | tx_call (Some msg_serialized) =>\n      match @deserialize Dexter2FA12.Msg D2LqtSInstances.msg_serializable msg_serialized with\n      | Some msg => mintedOrBurnedTokens (Some msg)\n      | _ => 0\n      end\n    | _ => 0\n    end.\n\n  Lemma deserialize_balance_of_ne_mint_or_burn : forall n m,\n    @deserialize Dexter2FA12.Msg D2LqtSInstances.msg_serializable (serialize (FA2Token.msg_balance_of n)) <>\n    Some (Dexter2FA12.msg_mint_or_burn m).\n  Proof.\n    intros.\n    Transparent serialize deserialize.\n    cbn.\n    rewrite !Nat2Z.id.\n    destruct (Z.of_nat 3 <? 0); auto.\n    cbn.\n    destruct_match; try discriminate.\n    destruct p.\n    now destruct_match.\n    Opaque serialize deserialize.\n  Qed.\n\n  Lemma forall_filter_cons : forall P (Q : Action -> ActionBody) R x l,\n    Forall P (map Q (filter R (x :: l))) -> Forall P (map Q (filter R l)).\n  Proof.\n    intros * forall_l. cbn in forall_l.\n    destruct_match in forall_l; auto.\n    now eapply Forall_inv_tail.\n  Qed.\n\n  Lemma outgoing_acts_no_mint_before_set_lqt_addr : forall bstate caddr (trace : ChainTrace empty_state bstate),\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate,\n      contract_state bstate caddr = Some cstate /\\\n        (cstate.(lqtAddress) = null_address ->\n          Forall (fun act_body =>\n            match act_body with\n            | act_call _ _ msg =>\n              match @deserialize Dexter2FA12.Msg D2LqtSInstances.msg_serializable msg with\n              | Some (msg_mint_or_burn _) => False\n              | _ => True\n              end\n            | _ => True\n            end) (outgoing_acts bstate caddr)).\n  Proof.\n    intros * trace deployed.\n    trace_induction; cbn in *.\n    - (* Step block *)\n      destruct IH as (state & deployed_state & IH).\n      rewrite outgoing_acts_after_block_nil; eauto.\n      eapply contract_addr_format; eauto.\n      now constructor.\n    - (* Action transfer *)\n      destruct IH as (state & deployed_state & sum_eq).\n      eexists.\n      split; eauto.\n      intros lqtAddr.\n      subst.\n      apply sum_eq in lqtAddr.\n      clear sum_eq.\n      unfold outgoing_acts in *.\n      rewrite queue_prev, queue_new in *.\n      now apply forall_filter_cons in lqtAddr.\n    - (* Action deploy *)\n      destruct (address_eqb_spec caddr to_addr) as [<-|].\n      + (* Deploy this contract *)\n        inversion deployed.\n        subst. clear deployed IH.\n        apply wc_init_strong in init_some as (setup' & state' & _ & deployed_state' & init_some).\n        subst.\n        rewrite deserialize_serialize.\n        eexists.\n        split; eauto.\n        intros lqtAddr.\n        rewrite outgoing_acts_after_deploy_nil; auto.\n        rewrite queue_new.\n        apply undeployed_contract_no_out_queue in not_deployed; auto.\n        * rewrite queue_prev in not_deployed.\n          now apply list.Forall_cons in not_deployed.\n        * now constructor.\n      + (* Deploy other contract *)\n        destruct IH as (state' & deployed_state' & sum_eq); auto.\n        eexists.\n        split; eauto.\n        subst.\n        intros lqtAddr.\n        apply sum_eq in lqtAddr.\n        clear sum_eq.\n        unfold outgoing_acts in *.\n        rewrite queue_prev, queue_new in *.\n        now apply forall_filter_cons in lqtAddr.\n    - (* Action call *)\n      destruct IH as (state & deployed_state' & sum_eq).\n      destruct (address_eqb_spec caddr to_addr) as [<-|].\n      + (* Call this contract *)\n        rewrite deployed in deployed0.\n        inversion deployed0.\n        subst. clear deployed0.\n        apply wc_receive_strong in receive_some as\n          (prev_state' & msg' & new_state' & serialize_prev_state & _ & serialize_new_state & receive_some).\n        cbn in receive_some.\n        rewrite <- serialize_new_state, deserialize_serialize.\n        rewrite deployed_state, serialize_prev_state in deployed_state'.\n        inversion deployed_state'. subst.\n        clear deployed_state' serialize_prev_state.\n        eexists.\n        split; eauto.\n        intros lqtAddr.\n        destruct_message;\n          rewrite_acts_correct;\n          rewrite_state_eq;\n          try (apply sum_eq in lqtAddr as lqtAddr'; clear sum_eq);\n          unfold outgoing_acts in *;\n          rewrite queue_prev, queue_new in *;\n          try apply forall_filter_cons in lqtAddr';\n          auto;\n          cbn;\n          rewrite ?address_eq_refl;\n          cbn;\n          rewrite ?list.Forall_cons;\n          repeat split; try easy;\n          rewrite_receive_is_some;\n          try easy.\n        * subst.\n          now eapply forall_filter_cons.\n        * destruct_match eqn:match_deser; auto.\n          destruct m; auto.\n          now apply deserialize_balance_of_ne_mint_or_burn in match_deser.\n      + (* Call other contract *)\n        eexists.\n        split; eauto.\n        intros lqtAddr.\n        apply sum_eq in lqtAddr.\n        clear sum_eq.\n        unfold outgoing_acts in *.\n        rewrite queue_prev, queue_new in *.\n        apply forall_filter_cons in lqtAddr.\n        subst.\n        rewrite filter_app, map_app, Forall_app.\n        split; auto.\n        rewrite Extras.filter_map.\n        cbn.\n        rewrite address_eq_ne, filter_false by auto.\n        now cbn.\n    - (* Invalid action *)\n      destruct IH as (state & deployed_state & sum_eq).\n      eexists.\n      split; eauto.\n      intros lqtAddr.\n      unfold outgoing_acts in *.\n      rewrite queue_prev, <- queue_new in *.\n      apply sum_eq in lqtAddr.\n      clear sum_eq.\n      now apply forall_filter_cons in lqtAddr.\n    - (* Permutation *)\n      destruct IH as (state & deployed_state & sum_eq).\n      eexists.\n      split; eauto.\n      intros lqtAddr.\n      apply sum_eq in lqtAddr.\n      clear sum_eq.\n      eapply Permutation_filter in perm.\n      eapply Permutation.Permutation_map in perm.\n      eapply forall_respects_permutation; eauto.\n  Qed.\n\n  Lemma outgoing_acts_all_mint_same_dest : forall bstate caddr (trace : ChainTrace empty_state bstate),\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate,\n      contract_state bstate caddr = Some cstate /\\\n        Forall (fun act_body =>\n          match act_body with\n          | act_call to _ msg_serialized =>\n            match @deserialize Dexter2FA12.Msg D2LqtSInstances.msg_serializable msg_serialized with\n            | Some (msg_mint_or_burn _) => to = lqtAddress cstate\n            | _ => True\n            end\n          | _ => True\n          end\n        ) (outgoing_acts bstate caddr).\n  Proof.\n    contract_induction;\n      intros; auto.\n    - cbn.\n      now apply list.Forall_cons in IH as [].\n    - instantiate (CallFacts := fun _ _ state out_acts _ =>\n        state.(lqtAddress) = null_address ->\n          Forall (fun act_body =>\n            match act_body with\n            | act_call _ _ msg =>\n              match @deserialize Dexter2FA12.Msg D2LqtSInstances.msg_serializable msg with\n              | Some (msg_mint_or_burn _) => False\n              | _ => True\n              end\n            | _ => True\n            end) out_acts).\n      unfold CallFacts in facts.\n      cbn in receive_some.\n      destruct_message;\n        rewrite_acts_correct;\n        rewrite_state_eq;\n        apply Forall_app;\n        split; auto;\n        rewrite ?list.Forall_cons, ?list.Forall_nil;\n        try easy.\n      + cbn.\n        repeat split; auto.\n        now rewrite deserialize_serialize.\n      + cbn.\n        repeat split; auto.\n        now rewrite deserialize_serialize.\n      + rewrite_receive_is_some.\n        apply facts in H2.\n        apply All_Forall.In_Forall.\n        intros act act_in.\n        eapply Forall_forall in H2; eauto.\n        destruct act; auto.\n        destruct_match; auto.\n        destruct m; auto.\n      + cbn.\n        destruct_match eqn:contradiction; auto.\n        destruct m; auto.\n        now apply deserialize_balance_of_ne_mint_or_burn in contradiction.\n    - apply list.Forall_cons in IH as [].\n      unfold CallFacts in facts.\n      cbn in receive_some.\n      destruct_message;\n        rewrite_acts_correct;\n        rewrite_state_eq;\n        apply Forall_app;\n        split; auto;\n        rewrite ?list.Forall_cons, ?list.Forall_nil;\n        try easy.\n      + cbn.\n        repeat split; auto.\n        now rewrite deserialize_serialize.\n      + cbn.\n        repeat split; auto.\n        now rewrite deserialize_serialize.\n      + rewrite_receive_is_some.\n        apply facts, Forall_inv_tail in H4.\n        apply All_Forall.In_Forall.\n        intros act act_in.\n        eapply Forall_forall in H4; eauto.\n        destruct act; auto.\n        destruct_match; auto.\n        destruct m; auto.\n      + cbn.\n        destruct_match eqn:contradiction; auto.\n        destruct m; auto.\n        now apply deserialize_balance_of_ne_mint_or_burn in contradiction.\n    - now rewrite <- perm.\n    - solve_facts.\n      rewrite deployed in deployed0.\n      inversion deployed0.\n      subst.\n      clear deployed0.\n      specialize outgoing_acts_no_mint_before_set_lqt_addr as (state & state_deployed & ?); eauto.\n      rewrite deployed_state0 in state_deployed.\n      now inversion state_deployed.\n  Qed.\n\n  Lemma outgoing_acts_sum_filter_eq : forall bstate caddr,\n    reachable bstate ->\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate,\n      contract_state bstate caddr = Some cstate /\\\n        sumZ mintedOrBurnedTokens_acts (filter (actTo cstate.(lqtAddress)) (outgoing_acts bstate caddr)) =\n        sumZ mintedOrBurnedTokens_acts (outgoing_acts bstate caddr).\n  Proof.\n    intros * [trace] deployed.\n    apply outgoing_acts_all_mint_same_dest in deployed as mint_or_burn_to_lqt_addr; auto.\n    destruct mint_or_burn_to_lqt_addr as (cstate & deployed_state & mint_or_burn_to_lqt_addr).\n    exists cstate.\n    split; auto.\n    clear trace deployed deployed_state.\n    induction outgoing_acts.\n    - reflexivity.\n    - apply list.Forall_cons in mint_or_burn_to_lqt_addr as [mint_or_burn_to_lqt_addr IH%IHl].\n      clear IHl.\n      cbn.\n      rewrite <- IH. clear IH.\n      destruct a eqn:H; cbn; destruct_address_eq; auto.\n      destruct_match; auto.\n      now destruct_match.\n  Qed.\n\n  Lemma outgoing_txs_no_mint_before_set_lqt_addr : forall bstate caddr (trace : ChainTrace empty_state bstate),\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate,\n      contract_state bstate caddr = Some cstate /\\\n        (cstate.(lqtAddress) = null_address ->\n          Forall (fun tx =>\n            match tx.(tx_body) with\n            | tx_call (Some msg) =>\n              match @deserialize Dexter2FA12.Msg D2LqtSInstances.msg_serializable msg with\n              | Some (msg_mint_or_burn _) => False\n              | _ => True\n              end\n            | _ => True\n            end) (outgoing_txs trace caddr)).\n  Proof.\n    intros * deployed.\n    remember empty_state.\n    induction trace.\n    - now subst.\n    - subst.\n      apply deployed_contract_state_typed in deployed as deployed_state.\n      + destruct deployed_state as (state & deployed_state).\n        exists state.\n        split; auto.\n        assert (reach : reachable to) by (constructor; now econstructor).\n        destruct_chain_step.\n        * (* Step block *)\n          intros.\n          destruct IHtrace as (state' & deployed_state' & sum_eq);\n              try rewrite_environment_equiv; auto.\n          cbn in *.\n          rewrite deployed_state in deployed_state'.\n          inversion deployed_state'.\n          now subst.\n        * destruct_action_eval.\n         -- (* Action transfer *)\n            destruct IHtrace as (state' & deployed_state' & sum_eq);\n              try rewrite_environment_equiv; auto.\n            cbn in *.\n            rewrite deployed_state in deployed_state'.\n            inversion deployed_state'.\n            intros lqtAddr.\n            subst.\n            destruct_address_eq; auto.\n            apply sum_eq in lqtAddr.\n            apply Forall_cons; auto.\n            now inversion lqtAddr.\n         -- (* Action deploy *)\n            rewrite_environment_equiv.\n            cbn in *.\n            intros lqtAddr.\n            destruct (address_eqb_spec caddr to_addr) as [<-|]; auto.\n          --- (* Deploy contract *)\n              specialize undeployed_contract_no_out_txs as H; auto.\n              unfold outgoing_txs in H.\n              destruct_address_eq;\n                try apply Forall_cons; cbn; auto;\n                rewrite H; auto.\n          --- (* Deploy other contract *)\n              destruct IHtrace as (state' & deployed_state' & sum_eq); auto.\n              rewrite deployed_state in deployed_state'.\n              inversion deployed_state'.\n              subst.\n              destruct_address_eq; auto.\n              apply sum_eq in lqtAddr.\n              apply Forall_cons; auto.\n              now inversion lqtAddr.\n         -- (* Action call *)\n            destruct IHtrace as (state' & deployed_state' & sum_eq);\n              try rewrite_environment_equiv; auto.\n            cbn in *.\n            intros lqtAddr.\n            destruct (address_eqb_spec caddr to_addr) as [<-|]; auto.\n          --- (* Call contract *)\n              rewrite deployed in deployed0.\n              inversion deployed0.\n              subst.\n              apply wc_receive_strong in receive_some as\n                (prev_state' & msg' & new_state' & serialize_prev_state & msg_ser & serialize_new_state & receive_some).\n              cbn in receive_some.\n              rewrite <- serialize_new_state, deserialize_serialize in deployed_state.\n              inversion deployed_state.\n              rewrite deployed_state0, serialize_prev_state in deployed_state'.\n              inversion deployed_state'.\n              subst.\n              clear deployed0 deployed_state deployed_state'.\n              assert (lqt_addr_preserved : lqtAddress state' = lqtAddress state \\/ exists a, msg' = Some (FA2Token.other_msg (SetLqtAddress a))).\n              { destruct_message; now rewrite_state_eq. }\n              destruct (address_eqb_spec caddr from_addr) as [<-|]; auto.\n          ---- (* Self call *)\n                rewrite address_eq_refl.\n                edestruct outgoing_acts_no_mint_before_set_lqt_addr as (cstate & deployed_state' & out_acts_forall); eauto.\n                cbn in deployed_state'.\n                rewrite deployed_state0, serialize_prev_state in deployed_state'.\n                inversion deployed_state'.\n                subst. clear deployed_state'.\n                unfold outgoing_acts in out_acts_forall.\n                rewrite queue_prev in out_acts_forall.\n                cbn in out_acts_forall.\n                rewrite address_eq_refl in out_acts_forall.\n                cbn in out_acts_forall.\n                apply Forall_cons. cbn.\n                { destruct lqt_addr_preserved as [lqt_addr_preserved | lqt_addr_preserved]; auto.\n                  - rewrite <- lqt_addr_preserved in lqtAddr.\n                    apply Forall_inv in out_acts_forall; auto.\n                    destruct msg; auto.\n                  - destruct lqt_addr_preserved as [? lqt_addr_preserved].\n                    rewrite lqt_addr_preserved in receive_some.\n                    rewrite_receive_is_some.\n                    apply Forall_inv in out_acts_forall; auto.\n                    destruct msg; auto.\n                }\n                destruct lqt_addr_preserved as [lqt_addr_preserved | lqt_addr_preserved];\n                  try now rewrite <- lqt_addr_preserved in lqtAddr.\n                destruct lqt_addr_preserved as [? lqt_addr_preserved].\n                rewrite lqt_addr_preserved in receive_some.\n                now rewrite_receive_is_some.\n          ---- (* Call by other contract *)\n              rewrite address_eq_ne by auto.\n              destruct lqt_addr_preserved as [lqt_addr_preserved | lqt_addr_preserved];\n                try now rewrite <- lqt_addr_preserved in lqtAddr.\n              destruct lqt_addr_preserved as [? lqt_addr_preserved].\n              rewrite lqt_addr_preserved in receive_some.\n              now rewrite_receive_is_some.\n          --- (* Call other contract *)\n              rewrite deployed_state in deployed_state'.\n              inversion deployed_state'.\n              subst. clear deployed_state'.\n              destruct_address_eq; auto.\n              subst.\n              apply Forall_cons; auto.\n              edestruct outgoing_acts_no_mint_before_set_lqt_addr as (cstate & deployed_state' & out_acts_forall); eauto.\n              cbn in deployed_state'.\n              rewrite deployed_state in deployed_state'.\n              inversion deployed_state'.\n              subst. clear deployed_state'.\n              unfold outgoing_acts in out_acts_forall.\n              rewrite queue_prev in out_acts_forall.\n              cbn in out_acts_forall.\n              rewrite address_eq_refl in out_acts_forall.\n              cbn in out_acts_forall.\n              apply Forall_inv in out_acts_forall; auto.\n              destruct msg; auto.\n        * (* Invalid action *)\n          intros lqtAddr.\n          destruct IHtrace as (state' & deployed_state' & sum_eq);\n            try rewrite_environment_equiv; auto.\n          cbn in *.\n          rewrite deployed_state in deployed_state'.\n          inversion deployed_state'.\n          now subst.\n        * (* Permutation *)\n          intros lqtAddr.\n          destruct IHtrace as (state' & deployed_state' & sum_eq);\n            rewrite env_eq in *; auto.\n          cbn in *.\n          rewrite deployed_state in deployed_state'.\n          inversion deployed_state'.\n          now subst.\n    + constructor.\n      now econstructor.\n  Qed.\n\n  Lemma outgoing_txs_all_mint_same_dest : forall bstate caddr (trace : ChainTrace empty_state bstate),\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate,\n      contract_state bstate caddr = Some cstate /\\\n        Forall (fun tx =>\n          match tx.(tx_body) with\n          | tx_call (Some msg) =>\n            match @deserialize Dexter2FA12.Msg D2LqtSInstances.msg_serializable msg with\n            | Some (msg_mint_or_burn _) => tx.(tx_to) = lqtAddress cstate\n            | _ => True\n            end\n          | _ => True\n          end\n        ) (outgoing_txs trace caddr).\n  Proof.\n    intros * deployed.\n    remember empty_state.\n    induction trace.\n    - now subst.\n    - subst.\n      apply deployed_contract_state_typed in deployed as deployed_state.\n      + destruct deployed_state as (state & deployed_state).\n        exists state.\n        split; auto.\n        destruct_chain_step.\n        * (* Step block *)\n          rewrite_environment_equiv.\n          destruct IHtrace as (state' & deployed_state' & sum_eq); auto.\n          cbn in *.\n          rewrite deployed_state in deployed_state'.\n          now inversion deployed_state'.\n        * destruct_action_eval.\n         -- (* Action transfer *)\n            destruct IHtrace as (state' & deployed_state' & sum_eq);\n              try rewrite_environment_equiv; auto.\n            cbn in *.\n            rewrite deployed_state in deployed_state'.\n            inversion deployed_state'.\n            clear deployed_state'.\n            subst.\n            destruct_address_eq; auto.\n            apply list.Forall_cons.\n            now split.\n         -- (* Action deploy *)\n            rewrite_environment_equiv.\n            cbn in *.\n            destruct (address_eqb_spec caddr to_addr) as [<-|]; auto.\n          --- (* Deploy contract *)\n              eapply undeployed_contract_no_out_txs in not_deployed; auto.\n              unfold outgoing_txs in not_deployed.\n              rewrite not_deployed.\n              destruct_address_eq; auto.\n              now apply list.Forall_cons.\n          --- (* Deploy other contract *)\n              destruct IHtrace as (state' & deployed_state' & sum_eq); auto.\n              rewrite deployed_state in deployed_state'.\n              inversion deployed_state'.\n              clear deployed_state'.\n              subst.\n              destruct_address_eq; auto.\n              now apply list.Forall_cons.\n         -- (* Action call *)\n            destruct IHtrace as (state' & deployed_state' & sum_eq);\n              try rewrite_environment_equiv; auto.\n            cbn in *.\n            destruct (address_eqb_spec caddr to_addr) as [<-|]; auto.\n          --- (* Call contract *)\n              rewrite deployed in deployed0.\n              inversion deployed0.\n              subst.\n              apply wc_receive_strong in receive_some as\n                (prev_state' & msg' & new_state' & serialize_prev_state & msg_ser & serialize_new_state & receive_some).\n              cbn in receive_some.\n              rewrite <- serialize_new_state, deserialize_serialize in deployed_state.\n              inversion deployed_state.\n              rewrite deployed_state0, serialize_prev_state in deployed_state'.\n              inversion deployed_state'.\n              subst.\n              clear deployed0 deployed_state deployed_state'.\n              assert (lqt_addr_preserved : lqtAddress state' = lqtAddress state \\/ exists a, msg' = Some (FA2Token.other_msg (SetLqtAddress a))).\n              { destruct_message; now rewrite_state_eq. }\n              destruct (address_eqb_spec caddr from_addr) as [<-|]; auto.\n          ---- (* Self call *)\n                rewrite address_eq_refl.\n                apply Forall_cons. cbn.\n                { destruct lqt_addr_preserved as [<- | lqt_addr_preserved]; auto.\n                  - edestruct outgoing_acts_all_mint_same_dest as (cstate & deployed_state' & out_acts_forall); eauto.\n                    cbn in deployed_state'.\n                    rewrite deployed_state0, serialize_prev_state in deployed_state'.\n                    inversion deployed_state'.\n                    subst. clear deployed_state'.\n                    unfold outgoing_acts in out_acts_forall.\n                    rewrite queue_prev in out_acts_forall.\n                    cbn in out_acts_forall.\n                    rewrite address_eq_refl in out_acts_forall.\n                    cbn in out_acts_forall.\n                    apply Forall_inv in out_acts_forall.\n                    now destruct msg.\n                  - edestruct outgoing_acts_no_mint_before_set_lqt_addr as (cstate & deployed_state' & out_acts_forall); eauto.\n                    cbn in deployed_state'.\n                    rewrite deployed_state0, serialize_prev_state in deployed_state'.\n                    inversion deployed_state'.\n                    subst. clear deployed_state'.\n                    unfold outgoing_acts in out_acts_forall.\n                    rewrite queue_prev in out_acts_forall.\n                    cbn in out_acts_forall.\n                    rewrite address_eq_refl in out_acts_forall.\n                    cbn in out_acts_forall.\n                    destruct lqt_addr_preserved as [? lqt_addr_preserved].\n                    rewrite lqt_addr_preserved in receive_some.\n                    rewrite_receive_is_some.\n                    apply Forall_inv in out_acts_forall; auto.\n                    destruct msg; auto.\n                    destruct_match; auto.\n                    now destruct m.\n                }\n                destruct lqt_addr_preserved as [<- | lqt_addr_preserved]; auto.\n                destruct lqt_addr_preserved as [? lqt_addr_preserved].\n                rewrite lqt_addr_preserved in receive_some.\n                rewrite_receive_is_some.\n                edestruct outgoing_txs_no_mint_before_set_lqt_addr as (cstate & deployed_state' & out_acts_forall); eauto.\n                cbn in deployed_state'.\n                rewrite deployed_state0, serialize_prev_state in deployed_state'.\n                inversion deployed_state'.\n                subst. clear deployed_state'.\n                apply out_acts_forall in H2.\n                clear out_acts_forall.\n                apply All_Forall.In_Forall.\n                intros act act_in.\n                eapply Forall_forall in H2; eauto.\n                destruct_match; auto.\n                destruct msg0; auto.\n                destruct_match; auto.\n                now destruct_match.\n          ---- (* Call by other contract *)\n              rewrite address_eq_ne by auto.\n              destruct lqt_addr_preserved as [<- | lqt_addr_preserved]; auto.\n              destruct lqt_addr_preserved as [? lqt_addr_preserved].\n              rewrite lqt_addr_preserved in receive_some.\n              rewrite_receive_is_some.\n              edestruct outgoing_txs_no_mint_before_set_lqt_addr as (cstate & deployed_state' & out_acts_forall); eauto.\n              cbn in deployed_state'.\n              rewrite deployed_state0, serialize_prev_state in deployed_state'.\n              inversion deployed_state'.\n              subst. clear deployed_state'.\n              apply out_acts_forall in H2.\n              clear out_acts_forall.\n              apply All_Forall.In_Forall.\n              intros act act_in.\n              eapply Forall_forall in H2; eauto.\n              destruct_match; auto.\n              destruct msg0; auto.\n              destruct_match; auto.\n              now destruct_match.\n          --- (* Call other contract *)\n              rewrite deployed_state in deployed_state'.\n              inversion deployed_state'.\n              clear deployed_state'.\n              subst.\n              destruct_address_eq; auto.\n              apply list.Forall_cons.\n              split; auto.\n              cbn.\n              edestruct outgoing_acts_all_mint_same_dest as (cstate & deployed_state' & out_acts_forall); eauto.\n              cbn in deployed_state'.\n              rewrite deployed_state in deployed_state'.\n              inversion deployed_state'.\n              subst. clear deployed_state'.\n              unfold outgoing_acts in out_acts_forall.\n              rewrite queue_prev in out_acts_forall.\n              cbn in out_acts_forall.\n              rewrite address_eq_refl in out_acts_forall.\n              cbn in out_acts_forall.\n              apply Forall_inv in out_acts_forall.\n              now destruct msg.\n        * (* Invalid action *)\n          destruct IHtrace as (state' & deployed_state' & sum_eq);\n            try rewrite_environment_equiv; auto.\n          cbn in *.\n          rewrite deployed_state in deployed_state'.\n          now inversion deployed_state'.\n        * (* Permutation *)\n          destruct IHtrace as (state' & deployed_state' & sum_eq);\n            rewrite env_eq in *; auto.\n          cbn in *.\n          rewrite deployed_state in deployed_state'.\n          now inversion deployed_state'.\n    + constructor.\n      now econstructor.\n  Qed.\n\n  Lemma outgoing_txs_sum_filter_eq : forall bstate caddr (trace : ChainTrace empty_state bstate),\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate,\n      contract_state bstate caddr = Some cstate /\\\n        sumZ mintedOrBurnedTokens_tx (filter (txCallTo cstate.(lqtAddress)) (outgoing_txs trace caddr)) =\n        sumZ mintedOrBurnedTokens_tx (outgoing_txs trace caddr).\n  Proof.\n    intros * deployed.\n    apply (outgoing_txs_all_mint_same_dest _ _ trace) in deployed as mint_or_burn_to_lqt_addr; auto.\n    destruct mint_or_burn_to_lqt_addr as (cstate & deployed_state & mint_or_burn_to_lqt_addr).\n    exists cstate.\n    split; auto.\n    clear deployed deployed_state.\n    induction (outgoing_txs trace caddr).\n    - reflexivity.\n    - apply list.Forall_cons in mint_or_burn_to_lqt_addr as [mint_or_burn_to_lqt_addr IH%IHl].\n      clear IHl.\n      cbn.\n      rewrite <- IH. clear IH.\n      destruct a eqn:H.\n      destruct tx_body eqn:H1;\n        auto.\n      destruct_match eqn:H2; auto.\n      cbn in *.\n      do 3 (destruct_match; auto).\n      now destruct_address_eq.\n  Qed.\n\n  (** [lqtTotal] is equal to the initial tokens + minted tokens - burned tokens *)\n  Lemma lqt_total_correct' : forall bstate caddr (trace : ChainTrace empty_state bstate),\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate depinfo,\n      contract_state bstate caddr = Some cstate /\\\n      deployment_info Setup trace caddr = Some depinfo /\\\n      let initial_tokens := lqtTotal_ (deployment_setup depinfo) in\n      Z.of_N cstate.(lqtTotal) = (Z.of_N initial_tokens) + sumZ mintedOrBurnedTokens_acts (outgoing_acts bstate caddr)\n        + sumZ mintedOrBurnedTokens_tx (outgoing_txs trace caddr).\n  Proof.\n    contract_induction;\n      intros; auto.\n    - cbn in *.\n      now apply init_correct in init_some.\n    - rewrite IH.\n      cbn.\n      rewrite <- 3!Z.add_assoc.\n      rewrite Z.add_cancel_l.\n      rewrite Z.add_shuffle3.\n      rewrite Z.add_cancel_l.\n      rewrite Z.add_cancel_r.\n      unfold mintedOrBurnedTokens_tx.\n      destruct out_act.\n      + now destruct tx_act_match as [_ [_ [-> | ->]]].\n      + now destruct tx_act_match as [_ [_ ->]].\n      + now destruct tx_act_match as [_ ->].\n    - cbn in receive_some.\n      destruct_message;\n        try (now contract_simpl);\n        rewrite_acts_correct;\n        rewrite_state_eq; auto;\n        rewrite_receive_is_some;\n        cbn;\n        try rewrite deserialize_serialize;\n        destruct_match eqn:msg_deserialized;\n          try now inversion msg_deserialized;\n          cbn;\n          try lia.\n      destruct_match; try lia.\n      now apply deserialize_balance_of_ne_mint_or_burn in msg_deserialized.\n    - destruct head;\n        auto;\n        cbn in IH;\n        destruct action_facts as (? & ? & ?);\n        subst.\n      + now contract_simpl.\n      + cbn in receive_some.\n        destruct_message;\n          try (now contract_simpl);\n          rewrite_acts_correct;\n          rewrite_state_eq; auto;\n          rewrite_receive_is_some;\n          cbn;\n          try rewrite deserialize_serialize;\n          destruct_match eqn:msg_deserialized;\n            try now inversion msg_deserialized;\n            cbn;\n            try lia.\n        * destruct_match; try lia.\n          now apply deserialize_balance_of_ne_mint_or_burn in msg_deserialized.\n        * destruct_match eqn:msg_deserialized0;\n            try now inversion msg_deserialized0.\n    - now rewrite <- perm.\n    - solve_facts.\n  Qed.\n\n  (** [lqtTotal] is equal to the initial tokens + minted tokens - burned tokens *)\n  Lemma lqt_total_correct : forall bstate caddr (trace : ChainTrace empty_state bstate),\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate depinfo,\n      contract_state bstate caddr = Some cstate /\\\n      deployment_info Setup trace caddr = Some depinfo /\\\n      let initial_tokens := lqtTotal_ (deployment_setup depinfo) in\n      Z.of_N cstate.(lqtTotal) = (Z.of_N initial_tokens) + sumZ mintedOrBurnedTokens_acts (filter (actTo cstate.(lqtAddress)) (outgoing_acts bstate caddr))\n        + sumZ mintedOrBurnedTokens_tx (filter (txCallTo cstate.(lqtAddress)) (outgoing_txs trace caddr)).\n  Proof.\n    intros * deployed.\n    eapply lqt_total_correct' in deployed as lqt_correct.\n    apply outgoing_acts_sum_filter_eq in deployed as act_filter_eq; try easy.\n    destruct lqt_correct as (cstate & depinfo & deployed_state & deployment_info & lqt_correct).\n    destruct act_filter_eq as (cstate' & deployed_state' & act_filter_eq).\n    rewrite deployed_state in deployed_state'.\n    inversion deployed_state'.\n    clear deployed_state'. subst.\n    do 2 eexists.\n    intuition.\n    rewrite act_filter_eq.\n    apply (outgoing_txs_sum_filter_eq _ _ trace) in deployed as tx_filter_eq.\n    destruct tx_filter_eq as (cstate & deployed_state' & tx_filter_eq).\n    rewrite deployed_state in deployed_state'.\n    inversion deployed_state'.\n    clear deployed_state'. subst.\n    rewrite tx_filter_eq.\n    apply lqt_correct.\n  Qed.\n  Local Close Scope Z_scope.\n\n  Lemma mintedOrBurnedTokens_call_eq_tx : forall call_info addr,\n    (fun callInfo => mintedOrBurnedTokens callInfo.(call_msg)) call_info =\n    (fun callInfo => mintedOrBurnedTokens_tx (contract_call_info_to_tx addr callInfo)) call_info.\n  Proof.\n    intros.\n    destruct call_info.\n    destruct call_msg.\n    - cbn.\n      now rewrite deserialize_serialize.\n    - reflexivity.\n  Qed.\n\n  Lemma deserialize_lqt_token_msg_right_inverse : forall x (y : Dexter2FA12.Msg),\n    (forall x' (y' : Address), deserialize x' = Some y' -> x' = serialize y') ->\n    deserialize x = Some y ->\n    x = serialize y.\n  Proof.\n    intros * address_right_inverse deser_some.\n    Transparent deserialize serialize.\n    cbn in *.\n    Local Hint Resolve deserialize_nat_right_inverse\n                       deserialize_N_right_inverse\n                       deserialize_int_right_inverse\n                       deserialize_unit_right_inverse\n                       deserialize_serialized_value_right_inverse : deser.\n    repeat (try match goal with\n    | H : match _ with Some _ => _ | None => _ end = Some _ |- _ = _ => let H2 := fresh \"H\" in destruct_match eqn:H2 in H; [| discriminate]\n    | H : match ?x with 0%nat => _ | S _ => _ end = Some _ |- _ = _ => destruct x; [| try discriminate]\n    | H : (let (_, _) := ?p in _) = Some _ |- _ = _ => destruct p\n    | H : Some _ = Some _ |- _ = _ => inversion_clear H\n    | H : extract_ser_value _ _ = @Some (interp_type ser_unit) ?i |- _ = _ => apply deserialize_unit_right_inverse in H as ->; destruct i\n    | H : @deserialize_product _ _ _ _ _ = Some _ |- _ = _ => apply deserialize_product_right_inverse in H as ->; try clear H\n    | |- forall _ _, _ -> _ => intros * deser_some; cbn in *\n    end; auto with deser).\n    Opaque deserialize serialize.\n  Qed.\n\n\n  (** ** lqtTotal/total_supply invariant *)\n  Section LqtPoolCorrect.\n\n    Arguments lqt_contract {_ _ _ _} _.\n    Arguments lqt_total_supply_correct {_ _ _ _} _.\n\n    (** [lqtTotal] of the main contract is equal to [total_supply] of the liquidity token *)\n    (** We define the statement for the liquidity token interface contract interface.\n        [LqtTokenInterface]. That is, for any contract with correct signature satisfying\n        an additional correctness property, namely [total_supply] is equal to the initial\n        tokens + minted tokens - burned tokens *)\n    Definition lqtTotal_total_supply_invariant (i_lqt_contract : LqtTokenInterface) : Prop :=\n      forall bstate caddr_main caddr_lqt (trace : ChainTrace empty_state bstate),\n      env_contracts bstate caddr_main = Some (contract : WeakContract) ->\n      env_contracts bstate caddr_lqt = Some (i_lqt_contract.(lqt_contract) : WeakContract) ->\n      exists state_main state_lqt depinfo_main depinfo_lqt,\n        contract_state bstate caddr_main = Some state_main /\\\n        contract_state bstate caddr_lqt = Some state_lqt /\\\n        deployment_info Setup trace caddr_main = Some depinfo_main /\\\n        deployment_info Dexter2FA12.Setup trace caddr_lqt = Some depinfo_lqt /\\\n        let initial_tokens_main := lqtTotal_ (deployment_setup depinfo_main) in\n        let initial_tokens_lqt := initial_pool (deployment_setup depinfo_lqt) in\n        (state_main.(lqtAddress) = caddr_lqt ->\n         state_lqt.(admin) = caddr_main ->\n        initial_tokens_main = initial_tokens_lqt ->\n        filter (actTo state_main.(lqtAddress)) (outgoing_acts bstate caddr_main) = [] ->\n          state_main.(lqtTotal) = state_lqt.(total_supply)).\n\n    (** We prove that the invariant hold for any contract satisfying the interface *)\n    Lemma lqt_pool_correct_interface :\n      forall (i_lqt_contract : LqtTokenInterface), (* for any correct liquidity token *)\n         (forall x (y : Address), deserialize x = Some y -> x = serialize y) -> (* a technical condition for serialization *)\n        lqtTotal_total_supply_invariant i_lqt_contract.\n    Proof.\n      intros ? ? ? ? ? ? deployed_main deployed_lqt.\n      apply (lqt_total_correct _ _ trace) in deployed_main as main_correct.\n      destruct main_correct as (state_main & depinfo_main & deployed_state_main & deploy_info_main & main_correct).\n      apply (lqt_total_supply_correct _ _ _ trace) in deployed_lqt as lqt_correct.\n      destruct lqt_correct as (state_lqt & depinfo_lqt & inc_calls_lqt & deployed_state_lqt & deploy_info_lqt & inc_acts_lqt & lqt_correct).\n      specialize incomming_eq_outgoing as incoming_eq.\n      edestruct incoming_eq as (? & inc_acts_lqt' & calls_eq);\n        [| apply deployed_main | apply deployed_lqt |].\n      - intros. eapply deserialize_lqt_token_msg_right_inverse; auto.\n      - setoid_rewrite inc_acts_lqt in inc_acts_lqt'.\n        inversion inc_acts_lqt'.\n        subst. clear inc_acts_lqt'.\n        do 4 eexists.\n        repeat split; eauto.\n        cbn.\n        intros addr_main_eq addr_lqt_eq init_pool_eq no_waiting_mint_acts.\n        apply N2Z.inj.\n        rewrite main_correct, lqt_correct, init_pool_eq, no_waiting_mint_acts, addr_main_eq, addr_lqt_eq.\n        rewrite Z.add_0_r, Z.add_cancel_l.\n        rewrite calls_eq, sumZ_map.\n        apply sumZ_eq.\n        intros.\n        now rewrite <- mintedOrBurnedTokens_call_eq_tx.\n    Qed.\n  End LqtPoolCorrect.\n\n  (** Now, we prove that the concrete implementation of the liquidity token satisfies the\n      inter-contract invariant *)\n  Theorem lqt_pool_correct_lqt_fa12 :\n    (forall x (y : Address), deserialize x = Some y -> x = serialize y) ->\n    lqtTotal_total_supply_invariant Dexter2FA12Correct.LqtFA12Token.\n  Proof.\n    apply lqt_pool_correct_interface.\n  Qed.\n\nEnd Theories.\n", "meta": {"author": "AU-COBRA", "repo": "ConCert", "sha": "55ffd996fe89d41677a2ff368d3a5e4be1e997b7", "save_path": "github-repos/coq/AU-COBRA-ConCert", "path": "github-repos/coq/AU-COBRA-ConCert/ConCert-55ffd996fe89d41677a2ff368d3a5e4be1e997b7/examples/dexter2/Dexter2CPMMCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.24880838714110762}}
{"text": "Require Import List.\nRequire Import Bool.\nRequire Import BinNat.\nRequire Import Omega.\nRequire Import sflib.\n\nRequire Import Common.\nRequire Import Memory.\nRequire Import Value.\nRequire Import Lang.\nRequire Import State.\nRequire Import LoadStore.\nRequire Import Behaviors.\n\n\nModule Ir.\n\nModule SmallStep.\n\nSection SMALLSTEP.\n\nImport Ir.Inst.\nVariable md:Ir.IRModule.t.\n\n(* Returns basic block id of pc *)\nDefinition pc_bbid (p:Ir.IRFunction.pc): nat :=\n  match p with\n  | Ir.IRFunction.pc_phi bbid _ => bbid\n  | Ir.IRFunction.pc_inst bbid _ => bbid\n  end.\n\n(* Increment pc of the config. *)\nDefinition incrpc (c:Ir.Config.t) :=\n  match (Ir.Config.cur_fdef_pc md c) with\n  | Some (fdef, pc0) =>\n    match (Ir.IRFunction.next_trivial_pc pc0 fdef) with\n    | Some pc' =>\n      Ir.Config.update_pc c pc'\n    | None => c (* Cannot happen..! *)\n    end\n  | None => c (* Cannot happen *)\n  end.\n\n(* Updates register & Increments PC. *)\nDefinition update_reg_and_incrpc (c:Ir.Config.t) (r:Ir.reg) (v:Ir.val) :=\n  incrpc (Ir.Config.update_rval c r v).\n\n\n(* Helper functions *)\nDefinition twos_compl (n:nat) (sz:nat):nat :=\n  Nat.modulo n (Nat.shiftl 2 (sz - 1)).\n\nDefinition twos_compl_add (x y:nat) (sz:nat):nat :=\n  twos_compl (x + y) sz.\n\nDefinition twos_compl_sub (x y:nat) (sz:nat):nat :=\n  twos_compl (x + (Nat.shiftl 2 (sz - 1)) - y) sz.\n\nDefinition to_num (b:bool): Ir.val :=\n  Ir.num (if b then 1 else 0).\n\n\n(* Definition of the result after a step. *)\nInductive step_res :=\n| sr_success: Ir.event -> Ir.Config.t -> step_res\n| sr_goes_wrong: step_res (* went wrong. *)\n| sr_oom: step_res (* out-of-memory *)\n| sr_prog_finish: Ir.val -> step_res (* program has finished (with a return value). *)\n.\n\n\n(****************************************************\n             Semantics of instructions.\n ****************************************************)\n\n(* Convert a pointer into nat. *)\nDefinition p2N (p:Ir.ptrval) (m:Ir.Memory.t) (sz:nat):nat :=\n  let sz := Nat.min Ir.PTRSZ sz in\n  match p with\n  | Ir.plog l o =>\n    match Ir.log_to_phy m l o with\n    | Some (Ir.pphy o' _ _) =>\n      twos_compl o' sz\n    | _ => twos_compl o sz (* unreachable in well-typed program *)\n    end\n  | Ir.pphy o _ _ =>\n    twos_compl o sz\n  end.\n\n(* Pointer subtraction. *)\nDefinition psub p1 p2 m bsz :=\n  match (p1, p2) with\n  | (Ir.plog l1 o1, Ir.plog l2 o2) =>\n    if Nat.eqb l1 l2 then\n      (* psub on two same block *)\n      Ir.num (twos_compl (twos_compl_sub o1 o2 Ir.PTRSZ) bsz)\n    else\n      (* psub on two different blocks *)\n      Ir.poison\n  (* In all other cases, returns concrete number *)\n  | (Ir.pphy o1 _ _, Ir.plog _ _) =>\n    Ir.num (twos_compl (twos_compl_sub o1 (p2N p2 m Ir.PTRSZ) Ir.PTRSZ) bsz)\n  | (Ir.plog _ _, Ir.pphy o2 _ _) =>\n    Ir.num (twos_compl (twos_compl_sub (p2N p1 m Ir.PTRSZ) o2 Ir.PTRSZ) bsz)\n  | (Ir.pphy o1 _ _, Ir.pphy o2 _ _) =>\n    Ir.num (twos_compl (twos_compl_sub o1 o2 Ir.PTRSZ) bsz)\n  end.\n\n(* getelementptr with/without inbounds tag. *)\nDefinition gep (p:Ir.ptrval) (idx0:nat) (t:Ir.ty) (m:Ir.Memory.t) (inb:bool): Ir.val :=\n  let idx := idx0 * (Ir.ty_bytesz t) in\n  match p with\n  | Ir.plog l o =>\n    let o' := twos_compl_add o idx Ir.PTRSZ in\n    if inb then\n      (* In case of inbounds: check whether input/output pointer is\n         within bounds. *)\n      match (Ir.Memory.get m l) with\n      | Some blk =>\n        if Ir.MemBlock.inbounds o blk &&\n           Ir.MemBlock.inbounds o' blk then Ir.ptr (Ir.plog l o')\n        else Ir.poison (* out of bounds *)\n      | None => Ir.poison (* unreachable *)\n      end\n    else\n      (* otherwise: just returns the pointer with updated offset. *)\n      Ir.ptr (Ir.plog l o')\n  | Ir.pphy o Is cid =>\n    let o' := twos_compl_add o idx Ir.PTRSZ in\n    if inb then\n      if Nat.ltb idx (Nat.shiftl 1 (Ir.PTRSZ - 1)) then\n        (* idx is positive. *)\n        if Nat.ltb (o + idx) Ir.MEMSZ then\n          (* Should not overflow Ir.MEMSZ *)\n          Ir.ptr (Ir.pphy o' (o::o'::Is) cid)\n        else Ir.poison\n      else\n        (* idx is negative. *)\n        if Nat.leb Ir.MEMSZ (o + idx) then\n          (* Should not underflow 0 (= Ir.MEMSZ). *)\n          Ir.ptr (Ir.pphy o' (o::o'::Is) cid)\n        else Ir.poison\n    else\n      (* if no inbounds tag, don't update Is. *)\n      Ir.ptr (Ir.pphy o' Is cid)\n  end.\n\n(* free operation. *)\nDefinition free p m: option (Ir.Memory.t) :=\n  match p with\n  | Ir.plog l 0 => Ir.Memory.free m l\n  | Ir.pphy o Is cid =>\n    (* find a block which corresponds to o. *)\n    match (Ir.Memory.zeroofs_block m o) with\n    | None => None\n    | Some (bid, mb) =>\n      if Ir.deref m p 1 then (* to use Is, cid info *)\n        Ir.Memory.free m bid\n      else None\n    end\n  | _ => None\n  end.\n\n(* Returns true if `icmp eq` on two poiners will return nondeterministic\n   value, false otherwise. *)\nDefinition icmp_eq_ptr_nondet_cond (p1 p2:Ir.ptrval) (m:Ir.Memory.t): bool :=\n  match (p1, p2) with\n  | (Ir.plog l1 o1, Ir.plog l2 o2) =>\n    match (Ir.Memory.get m l1, Ir.Memory.get m l2) with\n    | (Some mb1, Some mb2) =>\n      (negb (Nat.eqb l1 l2)) && (* two pointers should point to diff. blocks *)\n       (* o1 = n /\\ o2 = 0 *)\n      ((Nat.eqb o1 mb1.(Ir.MemBlock.n) && Nat.eqb o2 0) ||\n       (* n < o1 *)\n       (mb1.(Ir.MemBlock.n) <? o1) ||\n       (* o1 = 0 /\\ o2 = n *)\n       (Nat.eqb o1 0 && Nat.eqb o2 mb2.(Ir.MemBlock.n)) ||\n       (* n < o2 *)\n       (mb2.(Ir.MemBlock.n) <? o2) ||\n       (* even if offsets are inbounds, comparison result is nondeterministic\n          if lifetimes are disjoint.\n          Note that using <= is fine because no two blocks can have\n          same birth time or end time. *)\n       (match (mb1.(Ir.MemBlock.r), mb2.(Ir.MemBlock.r)) with\n        | ((b1, None), (b2, None)) => false\n        | ((b1, None), (b2, Some e2)) => e2 <=? b1\n        | ((b1, Some e1), (b2, None)) => e1 <=? b2\n        | ((b1, Some e1), (b2, Some e2)) => (e1 <=? b2) || (e2 <=? b1)\n        end))\n    | (_, _) => false\n    end\n  | (_, _) => false\n  end.\n\n(* p1 == p2 *)\nDefinition icmp_eq_ptr (p1 p2:Ir.ptrval) (m:Ir.Memory.t): option bool :=\n  match (p1, p2) with\n  | (Ir.plog l1 o1, Ir.plog l2 o2) =>\n    if Nat.eqb l1 l2 then\n      (* ICMP-PTR-LOGICAL *)\n      Some (Nat.eqb o1 o2)\n    else\n      if icmp_eq_ptr_nondet_cond p1 p2 m then None\n      else Some false\n  | (Ir.pphy o1 Is1 cid1, _) =>\n    Some (Nat.eqb o1 (p2N p2 m Ir.PTRSZ))\n  | (_, Ir.pphy o2 Is2 cid2) =>\n    Some (Nat.eqb (p2N p1 m Ir.PTRSZ) o2)\n  end.\n\n(* Returns true if `icmp ule` on two poiners will return nondeterministic\n   value, false otherwise. *)\nDefinition icmp_ule_ptr_nondet_cond (p1 p2:Ir.ptrval) (m:Ir.Memory.t): bool :=\n  match (p1, p2) with\n  | (Ir.plog l1 o1, Ir.plog l2 o2) =>\n    negb (Nat.eqb l1 l2) || (* they point to different blocks, or *)\n    match Ir.Memory.get m l1 with\n    | Some mb1 =>\n      (* ~ (o1 <= n /\\ o2 <= n) *)\n      (negb (Nat.leb o1 (Ir.MemBlock.n mb1))) ||\n      (negb (Nat.leb o2 (Ir.MemBlock.n mb1)))\n    | None => false\n    end\n  | _ => false\n  end.\n\n(* p1 <= p2 *)\nDefinition icmp_ule_ptr (p1 p2:Ir.ptrval) (m:Ir.Memory.t): option bool :=\n  if icmp_ule_ptr_nondet_cond p1 p2 m then None\n  else Some\n    match (p1, p2) with\n    | (Ir.plog l1 o1, Ir.plog l2 o2) =>\n      (* always l1 = l2 *)\n      match (Ir.Memory.get m l1) with\n      | Some mb1 => Nat.leb o1 o2\n      | None => false (* unreachable *)\n      end\n    | (Ir.pphy o1 Is1 cid1, _) =>\n      Nat.leb o1 (p2N p2 m Ir.PTRSZ)\n    | (_, Ir.pphy o2 Is2 cid2) =>\n      Nat.leb (p2N p1 m Ir.PTRSZ) o2\n    end.\n\nDefinition binop (bopc:Ir.Inst.bopcode) (i1 i2:nat) (bsz:nat):nat :=\n  match bopc with\n  | Ir.Inst.bop_add => twos_compl_add i1 i2 bsz\n  | Ir.Inst.bop_sub => twos_compl_sub i1 i2 bsz\n  end.\n\n(* Semantics of an instruction which behaves deterministically.\n   If IR module of c is well-typed, and this function returns Some (result),\n   there is no possible execution other than the result.\n   If running the instruction raises nondeterministic result,\n   this function returns None. *)\nDefinition inst_det_step (c:Ir.Config.t): option step_res :=\n  match (Ir.Config.cur_inst md c) with\n  | Some i =>\n    match i with\n    | ibinop r opty bopc op1 op2 =>\n      Some (sr_success Ir.e_none (update_reg_and_incrpc c r\n        match opty with\n        | Ir.ity bsz =>\n          match (Ir.Config.get_val c op1, Ir.Config.get_val c op2) with\n          | (Some (Ir.num i1), Some (Ir.num i2)) => Ir.num (binop bopc i1 i2 bsz)\n          | (_, _) => Ir.poison\n          end\n        | _ => Ir.poison\n        end))\n\n    | ifreeze r op retty =>\n      match (Ir.Config.get_val c op) with\n      | (Some (Ir.num i1)) =>\n        Some (sr_success Ir.e_none (update_reg_and_incrpc c r (Ir.num i1)))\n      | _ => None\n      end\n\n    | iselect r opcond condty op1 op2 opty =>\n      Some (sr_success Ir.e_none (update_reg_and_incrpc c r\n        match (Ir.Config.get_val c opcond,\n               Ir.Config.get_val c op1,\n               Ir.Config.get_val c op2) with\n        | (Some Ir.poison, _, _) => Ir.poison\n        | (Some (Ir.num icond), Some v1, Some v2) =>\n           if Nat.eqb icond 1 then v1 else v2\n        | (_, _, _) => Ir.poison\n        end))\n\n    | ipsub r retty ptrty op1 op2 =>\n      Some (sr_success Ir.e_none (update_reg_and_incrpc c r\n        match retty with\n        | Ir.ity bsz =>\n          match (Ir.Config.get_val c op1, Ir.Config.get_val c op2) with\n          | (Some (Ir.ptr p1), Some (Ir.ptr p2)) => psub p1 p2 (Ir.Config.m c) bsz\n          | (_, _) => Ir.poison\n          end\n        | _ => Ir.poison\n        end))\n\n    | igep r ptrty opptr opidx inb =>\n      Some (sr_success Ir.e_none (update_reg_and_incrpc c r\n        match ptrty with\n        | Ir.ptrty retty =>\n          match (Ir.Config.get_val c opptr, Ir.Config.get_val c opidx) with\n          | (Some (Ir.ptr p), Some (Ir.num idx)) => gep p idx retty (Ir.Config.m c) inb\n          | (_, _) => Ir.poison\n          end\n        | _ => Ir.poison\n        end))\n\n    | iload r retty opptr =>\n      match (Ir.Config.get_val c opptr) with\n      | (Some (Ir.ptr p)) =>\n        if Ir.deref (Ir.Config.m c) p (Ir.ty_bytesz retty) then\n          Some (sr_success Ir.e_none (update_reg_and_incrpc c r (Ir.load_val (Ir.Config.m c) p retty)))\n        else Some sr_goes_wrong\n      | (Some Ir.poison) => Some sr_goes_wrong\n      | _ => (* type check fail *)\n        Some (sr_success Ir.e_none (update_reg_and_incrpc c r Ir.poison))\n      end\n\n    | istore valty opptr opval =>\n      match (Ir.Config.get_val c opptr, Ir.Config.get_val c opval) with\n      | (Some (Ir.ptr p), Some v) =>\n        if Ir.deref (Ir.Config.m c) p (Ir.ty_bytesz valty) then\n          Some (sr_success Ir.e_none\n                           (incrpc (Ir.Config.update_m c (Ir.store_val (Ir.Config.m c) p v valty))))\n        else Some sr_goes_wrong\n      | (Some Ir.poison, Some v) => Some sr_goes_wrong\n      | (_, _) => (* type check fail *)\n        Some (sr_success Ir.e_none (incrpc c))\n      end\n\n    | imalloc r opty opval =>\n      (* malloc is not determinstic! *)\n      None\n\n    | ifree opptr =>\n      match (Ir.Config.get_val c opptr) with\n      | Some (Ir.ptr p) =>\n        match (free p (Ir.Config.m c)) with\n        | Some m => Some (sr_success Ir.e_none (incrpc (Ir.Config.update_m c m)))\n        | None => Some sr_goes_wrong\n        end\n      | _ => Some sr_goes_wrong\n      end\n\n    | ibitcast r opval retty =>\n      Some (sr_success Ir.e_none (update_reg_and_incrpc c r\n        match (Ir.Config.get_val c opval) with\n        | Some (Ir.ptr p) =>\n          match retty with\n          | Ir.ptrty _ => Ir.ptr p\n          | _ => Ir.poison (* ex: `bitcast i8* to i64' is invalid. *)\n          end\n        | Some (Ir.num n) =>\n          match retty with\n          | Ir.ity _ => Ir.num n\n          | _ => Ir.poison (* ex: `bitcast i64 to i8*' is invaild. *)\n          end\n        | _ => Ir.poison\n        end))\n\n    | iptrtoint r opptr retty =>\n      Some (sr_success Ir.e_none (update_reg_and_incrpc c r\n        match retty with\n        | Ir.ity retty =>\n          match (Ir.Config.get_val c opptr) with\n          | Some (Ir.ptr p) => Ir.num (p2N p (Ir.Config.m c) retty)\n          | _ => Ir.poison\n          end\n        | _ => Ir.poison\n        end))\n\n    | iinttoptr r opint retty =>\n      Some (sr_success Ir.e_none (update_reg_and_incrpc c r\n        match retty with\n        | Ir.ptrty retty =>\n          match (Ir.Config.get_val c opint) with\n          | Some (Ir.num n) => Ir.ptr (Ir.pphy (twos_compl n Ir.PTRSZ) nil None)\n          | _ => Ir.poison\n          end\n        | _ => Ir.poison\n        end))\n\n    | ievent opval =>\n      match (Ir.Config.get_val c opval) with\n      | Some (Ir.num n) => Some (sr_success (Ir.e_some n) (incrpc c))\n      | _ => Some sr_goes_wrong\n      end\n\n    | iicmp_eq r opty op1 op2 =>\n      match (Ir.Config.get_val c op1, Ir.Config.get_val c op2) with\n      (* Integer comparison *)\n      | (Some (Ir.num n1), Some (Ir.num n2)) =>\n        Some (sr_success Ir.e_none (update_reg_and_incrpc c r (to_num (Nat.eqb n1 n2))))\n      (* Pointer comparison *)\n      | (Some (Ir.ptr p1), Some (Ir.ptr p2)) =>\n        match (icmp_eq_ptr p1 p2 (Ir.Config.m c)) with\n        | Some b => Some (sr_success Ir.e_none (update_reg_and_incrpc c r (to_num b)))\n        | None => None (* nondet. result *)\n        end\n      | (_, _) => (* In other cases, it is untyped. *)\n        Some (sr_success Ir.e_none (update_reg_and_incrpc c r Ir.poison))\n      end\n\n    | iicmp_ule r opty opptr1 opptr2 =>\n      match (Ir.Config.get_val c opptr1, Ir.Config.get_val c opptr2) with\n      (* Integer comparison *)\n      | (Some (Ir.num n1), Some (Ir.num n2)) =>\n        Some (sr_success Ir.e_none (update_reg_and_incrpc c r (to_num (Nat.leb n1 n2))))\n      (* Comparison with pointer *)\n      | (Some (Ir.ptr p1), Some (Ir.ptr p2)) =>\n        match (icmp_ule_ptr p1 p2 (Ir.Config.m c)) with\n        | Some b => Some (sr_success Ir.e_none (update_reg_and_incrpc c r (to_num b)))\n        | None => None\n        end\n      | (_, _) => (* In other cases, it is untyped. *)\n        Some (sr_success Ir.e_none (update_reg_and_incrpc c r Ir.poison))\n      end\n    end\n\n  | None => Some sr_goes_wrong\n  end.\n\n(* Inductive definition of small-step semantics of instruction. *)\nInductive inst_step: Ir.Config.t -> step_res -> Prop :=\n(* small-step with deterministic semantics. *)\n| s_det: forall c sr\n      (HNEXT:Some sr = inst_det_step c), inst_step c sr\n\n(* freeze, with poison value given as operand *)\n| s_freeze: forall c i r op1 isz j\n      (HCUR:Some i = Ir.Config.cur_inst md c)\n      (HINST:i = Ir.Inst.ifreeze r op1 (Ir.ity isz))\n      (HPOISON:Some Ir.poison = Ir.Config.get_val c op1),\n    inst_step c (sr_success Ir.e_none\n                            (update_reg_and_incrpc c r (Ir.num (twos_compl j isz))))\n\n(* a case where malloc nondeterministically returns NULL.\n   This is required because we really cannot expect when\n   malloc will return NULL in assembly code. *)\n| s_malloc_null: forall c i r szty opsz\n      (HCUR:Some i = Ir.Config.cur_inst md c)\n      (HINST:i = Ir.Inst.imalloc r szty opsz),\n    inst_step c (sr_success Ir.e_none (update_reg_and_incrpc c r (Ir.ptr Ir.NULL)))\n\n(* a case where malloc returned oom. *)\n| s_malloc_oom: forall c i r szty opsz nsz\n      (HCUR:Some i = Ir.Config.cur_inst md c)\n      (HINST:i = Ir.Inst.imalloc r szty opsz)\n      (HSZ:Some (Ir.num nsz) = Ir.Config.get_val c opsz)\n      (HNOSPACE:~exists (P:list nat),\n            Ir.Memory.allocatable (Ir.Config.m c) (List.map (fun addr => (addr, nsz)) P) = true),\n    inst_step c sr_oom\n\n(* Malloc which does twin memory allocation.\n   P is the list of beginning offsets.\n   l is the returned block id. *)\n| s_malloc: forall c i r szty opsz nsz (P:list nat) m' l contents\n      (HCUR:Some i = Ir.Config.cur_inst md c)\n      (HINST:i = Ir.Inst.imalloc r szty opsz)\n      (HSZ:Some (Ir.num nsz) = Ir.Config.get_val c opsz)\n      (HSZ2:nsz > 0)\n      (HC:contents = List.repeat (Ir.Byte.poison) nsz)\n      (HMBWF:forall begt, Ir.MemBlock.wf (Ir.MemBlock.mk\n                                            (Ir.heap) (begt, None) nsz\n                                            (Ir.SYSALIGN) contents P))\n      (HDISJ:Ir.Memory.allocatable (Ir.Config.m c)\n                       (List.map (fun addr => (addr, nsz)) P) = true)\n      (HNEW: (m', l) = Ir.Memory.new (Ir.Config.m c) (Ir.heap) nsz\n                                     (Ir.SYSALIGN) contents P),\n    inst_step c (sr_success Ir.e_none (update_reg_and_incrpc\n                                           (Ir.Config.update_m c m') r\n                    (Ir.ptr (Ir.plog l 0))))\n\n(* a case when icmp eq returns value nondeterminstically *)\n| s_icmp_eq_nondet: forall c i r opty op1 op2 p1 p2 res\n      (HCUR:Some i = Ir.Config.cur_inst md c)\n      (HINST:i = Ir.Inst.iicmp_eq r opty op1 op2)\n      (HOP1:Some (Ir.ptr p1) = Ir.Config.get_val c op1)\n      (HOP2:Some (Ir.ptr p2) = Ir.Config.get_val c op2)\n      (HNONDET:icmp_eq_ptr_nondet_cond p1 p2 (Ir.Config.m c) = true),\n    inst_step c (sr_success Ir.e_none (update_reg_and_incrpc c r (Ir.num res)))\n\n(* a case when icmp ule returns value nondeterminstically *)\n| s_icmp_ule_nondet: forall c i r opty op1 op2 p1 p2 res\n      (HCUR:Some i = Ir.Config.cur_inst md c)\n      (HINST:i = Ir.Inst.iicmp_ule r opty op1 op2)\n      (HOP1:Some (Ir.ptr p1) = Ir.Config.get_val c op1)\n      (HOP2:Some (Ir.ptr p2) = Ir.Config.get_val c op2)\n      (HNONDET:icmp_ule_ptr_nondet_cond p1 p2 (Ir.Config.m c) = true),\n    inst_step c (sr_success Ir.e_none (update_reg_and_incrpc c r (Ir.num res)))\n\n.\n\n(* Result of N small steps on instructions. *)\nInductive inst_nstep: Ir.Config.t -> nat -> Ir.trace * step_res -> Prop :=\n| ns_one: forall c sr (HSINGLE:inst_step c sr),\n    inst_nstep c 1 (nil, sr)\n| ns_success: forall c n c' tr e sr\n           (HSUCC: inst_nstep c n (tr, sr_success e c'))\n           (HSINGLE: inst_step c' sr),\n      inst_nstep c (S n) (e::tr, sr)\n| ns_oom: forall c n tr (HOOM: inst_nstep c n (tr, sr_oom)),\n    inst_nstep c (S n) (tr, sr_oom)\n| ns_goes_wrong: forall c n tr (HGW: inst_nstep c n (tr, sr_goes_wrong)),\n    inst_nstep c (S n) (tr, sr_goes_wrong).\n\n\n\n(* Categorization of instructions. *)\nDefinition changes_mem (i:Ir.Inst.t): bool :=\n  match i with\n  | ibinop _ _ _ _ _ => false\n  | ifreeze _ _ _ => false\n  | iselect _ _ _ _ _ _ => false\n  | ipsub _ _ _ _ _ => false\n  | igep _ _ _ _ _ => false\n  | iload _ _ _ => false\n  | istore _ _ _ => true\n  | imalloc _ _ _ => true\n  | ifree _ => true\n  | ibitcast _ _ _ => false\n  | iptrtoint _ _ _ => false\n  | iinttoptr _ _ _ => false\n  | ievent _ => false\n  | iicmp_eq _ _ _ _ => false\n  | iicmp_ule _ _ _ _ => false\n  end.\nDefinition never_goes_wrong (i:Ir.Inst.t): bool :=\n  match i with\n  | ibinop _ _ _ _ _ => true\n  | ifreeze _ _ _ => true\n  | iselect _ _ _ _ _ _ => true\n  | ipsub _ _ _ _ _ => true\n  | igep _ _ _ _ _ => true\n  | iload _ _ _ => false\n  | istore _ _ _ => false\n  | imalloc _ _ _ => true\n  | ifree _ => false\n  | ibitcast _ _ _ => true\n  | iptrtoint _ _ _ => true\n  | iinttoptr _ _ _ => true\n  | ievent _ => false\n  | iicmp_eq _ _ _ _ => true\n  | iicmp_ule _ _ _ _ => true\n  end.\nDefinition allocates_mem (i:Ir.Inst.t): bool :=\n  match i with\n  | imalloc _ _ _ => true\n  | _ => false\n  end.\nDefinition raises_event (i:Ir.Inst.t): bool :=\n  match i with\n  | ibinop _ _ _ _ _ => false\n  | ifreeze _ _ _ => false\n  | iselect _ _ _ _ _ _ => false\n  | ipsub _ _ _ _ _ => false\n  | igep _ _ _ _ _ => false\n  | iload _ _ _ => false\n  | istore _ _ _ => false\n  | imalloc _ _ _ => false\n  | ifree _ => false\n  | ibitcast _ _ _ => false\n  | iptrtoint _ _ _ => false\n  | iinttoptr _ _ _ => false\n  | ievent _ => true\n  | iicmp_eq _ _ _ _ => false\n  | iicmp_ule _ _ _ _ => false\n  end.\n\n(****************************************************\n             Semantics of terminator.\n ****************************************************)\nDefinition br (c:Ir.Config.t) (bbid:nat): step_res :=\n  match (Ir.Config.cur_fdef_pc md c) with\n  | Some (fdef, pc0) =>\n    let bbid_old := pc_bbid pc0 in\n    match (Ir.IRFunction.get_begin_pc_bb bbid fdef) with\n    | Some pc_next =>\n      sr_success Ir.e_none (Ir.Config.update_pc c pc_next)\n    | None => sr_goes_wrong\n    end\n  | None => sr_goes_wrong\n  end.\n\nDefinition t_step (c:Ir.Config.t) : step_res :=\n  match (Ir.Config.cur_terminator md c) with\n  | Some t =>\n    match t with\n    | Ir.Terminator.tbr bbid =>\n      (* Unconditional branch. *)\n      br c bbid\n         \n    | Ir.Terminator.tbr_cond condop bbid_t bbid_f =>\n      (* Conditional branch. *)\n      let tgt :=\n          match (Ir.Config.get_val c condop) with\n          | Some (Ir.num cond) =>\n            if Nat.eqb cond 0 then Some bbid_f\n            else Some bbid_t\n          | _ => None (* note that 'br poison' is UB. *)\n          end in\n      match tgt with\n      | None => sr_goes_wrong\n      | Some bbid => br c bbid\n      end\n\n    | Ir.Terminator.tret retop =>\n      match (Ir.Config.get_val c retop) with\n      | Some v =>\n        if Ir.Config.has_nestedcall c then\n          (* TODO: Will be revisited later, after 'call' instruction is added. *)\n          sr_goes_wrong\n        else\n          sr_prog_finish v\n      (* is there only one activation record in a call stack? *)\n      | None => sr_goes_wrong\n      end\n    end\n  | _ => sr_goes_wrong\n  end.\n\n(****************************************************\n             Semantics of phi node.\n ****************************************************)\nDefinition phi_step (bef_bbid:nat) (c:Ir.Config.t)\n: option Ir.Config.t :=\n  match (Ir.Config.cur_phi md c) with\n  | Some p =>\n    match list_find_key p.(snd) bef_bbid with\n    | (_, op0)::_ =>\n      match Ir.Config.get_val c op0 with\n      | Some v => Some (update_reg_and_incrpc c p.(fst).(fst) v)\n      | None => None\n      end\n    | nil => None\n    end\n  | _ => None\n  end.\n\nInductive phi_bigstep: nat -> Ir.Config.t -> Ir.Config.t -> Prop :=\n| pbs_one:\n    forall c c' bef_bbid (HSTEP:phi_step bef_bbid c = Some c'),\n    phi_bigstep bef_bbid c c'\n| pbs_succ:\n    forall c c' c'' bef_bbid\n           (HNSTEP:phi_bigstep bef_bbid c c')\n           (HSTEP:phi_step bef_bbid c' = Some c''),\n    phi_bigstep bef_bbid c c''.\n\n\n(****************************************************\n        Semantics of a general small step.\n ****************************************************)\n\nDefinition is_pc_phi (pc0:Ir.IRFunction.pc): bool :=\n  match pc0 with\n  | Ir.IRFunction.pc_phi _ _ => true\n  | _ => false\n  end.\n\nInductive sstep: Ir.Config.t -> step_res -> Prop :=\n| ss_inst:\n    forall st sr (HISTEP:inst_step st sr),\n      sstep st sr\n| ss_br_goes_wrong:\n    forall st t\n           (HCUR:Some t = Ir.Config.cur_terminator md st)\n           (HTSTEP:t_step st = sr_goes_wrong),\n      sstep st sr_goes_wrong\n| ss_br_success:\n    (* It is assumed that phi is executed continuously\n       after br is executed. This follows Vellvm's style. *)\n    forall st0 fdef0 pc0 st' st'' fdef'' pc''\n           (HTSTEP:t_step st0 = sr_success Ir.e_none st')\n           (HCURPC:Some (fdef0, pc0) = Ir.Config.cur_fdef_pc md st0)\n           (HPSTEP:phi_bigstep (pc_bbid pc0) st' st'')\n           (HCURPC':Some (fdef'', pc'') = Ir.Config.cur_fdef_pc md st'')\n           (HNOT_PHI_ANYMORE:is_pc_phi pc'' = false),\n      sstep st0 (sr_success Ir.e_none st'').\n\nEnd SMALLSTEP.\n\nEnd SmallStep.\n\nEnd Ir.", "meta": {"author": "aqjune", "repo": "twinsem", "sha": "c9cc45994bbc7545d32cad0a918492666e6bb69f", "save_path": "github-repos/coq/aqjune-twinsem", "path": "github-repos/coq/aqjune-twinsem/twinsem-c9cc45994bbc7545d32cad0a918492666e6bb69f/SmallStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.2487809158094169}}
{"text": "From Tweetnacl.Gen Require Import AMZubSqSel.\n\nModule Gen.\n\nSection ABCDEF.\n\nContext {T : Type}.\nContext {T' : Type}.\nContext {Mod : T -> T}.\nContext {O : @Ops T T' Mod}.\n\nDefinition fa r (a b c d e f x:T) :=\n  Sel25519 r\n     (M (Sq (A (Sel25519 r a b) (Sel25519 r c d)))\n        (Sq (Zub (Sel25519 r a b) (Sel25519 r c d))))\n     (Sq\n        (A\n           (M (A (Sel25519 r b a) (Sel25519 r d c))\n              (Zub (Sel25519 r a b) (Sel25519 r c d)))\n           (M (Zub (Sel25519 r b a) (Sel25519 r d c))\n              (A (Sel25519 r a b) (Sel25519 r c d))))).\nDefinition fb r (a b c d e f x:T) :=\n  Sel25519 r\n     (Sq\n        (A\n           (M (A (Sel25519 r b a) (Sel25519 r d c))\n              (Zub (Sel25519 r a b) (Sel25519 r c d)))\n           (M (Zub (Sel25519 r b a) (Sel25519 r d c))\n              (A (Sel25519 r a b) (Sel25519 r c d)))))\n     (M (Sq (A (Sel25519 r a b) (Sel25519 r c d)))\n        (Sq (Zub (Sel25519 r a b) (Sel25519 r c d)))).\nDefinition fc r (a b c d e f x:T) :=\nSel25519 r\n  (M\n     (Zub (Sq (A (Sel25519 r a b) (Sel25519 r c d)))\n        (Sq (Zub (Sel25519 r a b) (Sel25519 r c d))))\n     (A\n        (M\n           (Zub (Sq (A (Sel25519 r a b) (Sel25519 r c d)))\n              (Sq (Zub (Sel25519 r a b) (Sel25519 r c d)))) C_121665)\n        (Sq (A (Sel25519 r a b) (Sel25519 r c d)))))\n  (M\n     (Sq\n        (Zub\n           (M (A (Sel25519 r b a) (Sel25519 r d c))\n              (Zub (Sel25519 r a b) (Sel25519 r c d)))\n           (M (Zub (Sel25519 r b a) (Sel25519 r d c))\n              (A (Sel25519 r a b) (Sel25519 r c d))))) x).\nDefinition fd r (a b c d e f x:T) :=\nSel25519 r\n  (M\n     (Sq\n        (Zub\n           (M (A (Sel25519 r b a) (Sel25519 r d c))\n              (Zub (Sel25519 r a b) (Sel25519 r c d)))\n           (M (Zub (Sel25519 r b a) (Sel25519 r d c))\n              (A (Sel25519 r a b) (Sel25519 r c d))))) x)\n  (M\n     (Zub (Sq (A (Sel25519 r a b) (Sel25519 r c d)))\n        (Sq (Zub (Sel25519 r a b) (Sel25519 r c d))))\n     (A\n        (M\n           (Zub (Sq (A (Sel25519 r a b) (Sel25519 r c d)))\n              (Sq (Zub (Sel25519 r a b) (Sel25519 r c d)))) C_121665)\n        (Sq (A (Sel25519 r a b) (Sel25519 r c d))))).\nDefinition fe r (a b c d e f x:T) :=\nA\n  (M (A (Sel25519 r b a) (Sel25519 r d c))\n     (Zub (Sel25519 r a b) (Sel25519 r c d)))\n  (M (Zub (Sel25519 r b a) (Sel25519 r d c))\n     (A (Sel25519 r a b) (Sel25519 r c d))).\nDefinition ff r (a b c d e f x:T) :=\n  Sq (Zub (Sel25519 r a b) (Sel25519 r c d)).\n\nEnd ABCDEF.\n\nEnd Gen.", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/proofs/spec/Gen/ABCDEF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.24877717674386193}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import List.\nRequire Export DistributedReferenceCounting.machine3.invariant0.\nRequire Export DistributedReferenceCounting.machine3.invariant1.\nRequire Export DistributedReferenceCounting.machine3.invariant2.\n\nUnset Standard Proposition Elimination Names.\n\n(* Where properties of rooted_fun are derived --> this\n   should obviously be abstracted and given decent names *)\n\n\nSection INVARIANT3.\nLemma sigma_rooted_fun2 :\n forall (s s1 s2 : Site) (d : Message),\n s2 <> owner -> s1 <> s -> s2 <> s -> rooted_fun s s1 s2 d = 0%Z.\nProof.\n  intros.\n  unfold rooted_fun in |- *.\n  elim d.\n  rewrite case_ineq.\n  auto.\n  auto.\n  intro.\n  case (eq_site_dec s0 s).\n  intro; rewrite case_ineq.\n  auto.\n  auto.\n  auto.\n  rewrite case_ineq.\n  auto.\n  auto.\nQed.\n\nLemma sigma_rooted_fun3 :\n forall s1 : Site,\n sigma_but Site owner eq_site_dec LS\n   (fun s : Site => rooted_fun s s1 owner dec) = 0%Z.\nProof.\n  intro.\n  apply sigma_but_null.\n  intros.\n  unfold rooted_fun in |- *.\n  rewrite case_ineq.\n  auto.\n  auto.\nQed.\n\n\n\nLemma sigma_rooted_fun4 :\n forall (s s1 : Site) (l : list Site),\n ~ In s l ->\n sigma_but Site owner eq_site_dec l\n   (fun s0 : Site => rooted_fun s0 s1 owner (inc_dec s)) = 0%Z.\nProof.\n  intro; intro; intro.\n  elim l.\n  simpl in |- *.\n  auto.\n  \n  simpl in |- *.\n  intros.\n  rewrite H.\n  case (eq_site_dec a owner).\n  auto.\n  \n  intro.\n  case (eq_site_dec s a).\n  intro.\n  elim H0.\n  left; auto.\n  \n  auto.\n  \n  generalize H0.\n  intuition.\nQed.\n\nLemma sigma_rooted_fun6 :\n forall (s s1 : Site) (l : list Site),\n ~ In s l ->\n sigma_but Site owner eq_site_dec l\n   (fun s0 : Site => rooted_fun s0 s owner copy) = 0%Z.\nProof.\n  intro; intro; intro.\n  elim l.\n  simpl in |- *.\n  auto.\n  \n  simpl in |- *.\n  intros.\n  case (eq_site_dec a owner).\n  intro.\n  rewrite H.\n  auto.\n  generalize H0; intuition.\n  intro.\n  case (eq_site_dec s a).\n  intro.\n  elim H0.\n  left; auto.\n  intro.\n  rewrite H.\n  auto.\n  generalize H0; intuition.\nQed.\n\nLemma sigma_rooted_fun7 :\n forall (s : Site) (l : list Site),\n only_once Site eq_site_dec s l ->\n s <> owner ->\n sigma_but Site owner eq_site_dec l\n   (fun s0 : Site => rooted_fun s0 s owner copy) = 1%Z.\n\nProof.\n  simple induction l.\n  simpl in |- *; intuition.\n  \n  intros.\n  generalize H.\n  generalize (sigma_rooted_fun6 s a l0).\n  simpl in |- *.\n  intros.\n  case (eq_site_dec a owner).\n  intro.\n  rewrite H3.\n  auto.\n  \n  generalize H0; simpl in |- *.\n  case (eq_site_dec s a).\n  rewrite e.\n  intuition.\n  \n  auto.\n  \n  auto.\n  \n  intro.\n  case (eq_site_dec s a).\n  intro.\n  rewrite H2.\n  auto.\n  \n  generalize H0; simpl in |- *.\n  case (eq_site_dec s a).\n  auto.\n  \n  intuition.\n  \n  intro.\n  rewrite H3.\n  auto.\n  \n  generalize H0.\n  simpl in |- *.\n  case (eq_site_dec s a).\n  intuition.\n  \n  auto.\n  \n  auto.\nQed.\n\nLemma sigma_rooted_fun8 :\n forall (s2 : Site) (l : list Site),\n ~ In s2 l ->\n sigma_but Site owner eq_site_dec l\n   (fun s : Site => rooted_fun s owner s2 dec) = 0%Z.\nProof.\n  intro; intro.\n  elim l.\n  simpl in |- *.\n  auto.\n  simpl in |- *.\n  intros.\n  case (eq_site_dec a owner).\n  intro.\n  rewrite H.\n  auto.\n  generalize H0; intuition.\n  intro.\n  case (eq_site_dec s2 a).\n  intro; elim H0.\n  left; auto.\n  intro.\n  rewrite H.\n  auto.\n  generalize H0; intuition.\nQed.\n\n\n\nLemma sigma_rooted_fun9 :\n forall (s2 : Site) (l : list Site),\n only_once Site eq_site_dec s2 l ->\n s2 <> owner ->\n sigma_but Site owner eq_site_dec l\n   (fun s : Site => rooted_fun s owner s2 dec) = 1%Z.\nProof.\n  simple induction l.\n  simpl in |- *; intuition.\n  intros.\n  generalize H.\n  generalize (sigma_rooted_fun8 s2 l0).\n  simpl in |- *.\n  intros.\n  case (eq_site_dec a owner).\n  intros.\n  apply H3.\n  generalize H0; simpl in |- *.\n  case (eq_site_dec s2 a).\n  rewrite e.\n  intuition.\n  auto.\n  auto.\n  intro.\n  case (eq_site_dec s2 a).\n  auto.\n  intro.\n  rewrite H2.\n  auto.\n  \n  generalize H0.\n  rewrite e; simpl in |- *.\n  case (eq_site_dec a a).\n  auto.\n  \n  intuition.\n  \n  intro.\n  rewrite H3.\n  auto.\n  \n  generalize H0.\n  simpl in |- *.\n  case (eq_site_dec s2 a).\n  intuition.\n  \n  auto.\n  \n  auto.\nQed.\n\n\nLemma sigma_rooted_fun10 :\n forall s2 : Site,\n sigma_but Site owner eq_site_dec LS\n   (fun s : Site => rooted_fun s owner s2 copy) = 0%Z.\nProof.\n  intros.\n  apply sigma_but_null.\n  intros.\n  simpl in |- *.\n  rewrite case_ineq.\n  auto.\n  auto.\nQed.\n\n\n\nLemma sigma_rooted_fun11 :\n forall (s1 s2 : Site) (l : list Site),\n s2 <> owner ->\n s1 <> owner ->\n ~ In s2 l ->\n sigma_but Site owner eq_site_dec l (fun s : Site => rooted_fun s s1 s2 dec) =\n 0%Z.\nProof.\n  intro; intro.\n  intro; intro.\n  intro.\n  simpl in |- *.\n  elim l.\n  simpl in |- *.\n  auto.\n  simpl in |- *.\n  intros.\n  case (eq_site_dec a owner).\n  intro.\n  rewrite H1.\n  auto.\n  generalize H2; intuition.\n  intro.\n  case (eq_site_dec s2 a).\n  intro.\n  elim H2.\n  left; auto.\n  intro.\n  rewrite H1.\n  auto.\n  generalize H2; intuition.\nQed.\n\n\nLemma sigma_rooted_fun12 :\n forall s1 s2 : Site,\n s2 <> owner ->\n s1 <> owner ->\n only_once Site eq_site_dec s2 LS ->\n sigma_but Site owner eq_site_dec LS (fun s : Site => rooted_fun s s1 s2 dec) =\n 1%Z.\nProof.\n  intros.\n  generalize H1.\n  elim LS.\n  simpl in |- *.\n  intuition.\n  \n  simpl in |- *.\n  intros.\n  case (eq_site_dec a owner).\n  intro.\n  rewrite H2.\n  auto.\n  \n  generalize H3.\n  case (eq_site_dec s2 a).\n  rewrite e.\n  intro; elim H; auto.\n  \n  auto.\n  \n  generalize (sigma_rooted_fun11 s1 s2 l H H0).\n  simpl in |- *.\n  intros.\n  case (eq_site_dec s2 a).\n  intro; rewrite H4.\n  auto.\n  \n  generalize H3.\n  case (eq_site_dec s2 a).\n  auto.\n  \n  intro.\n  elim n0; auto.\n  \n  intro.\n  rewrite H2.\n  auto.\n  \n  generalize H3.\n  case (eq_site_dec s2 a).\n  intro; elim n0; auto.\n  \n  auto.\nQed.\n\n\nLemma sigma_rooted_fun13 :\n forall (s1 s2 : Site) (l : list Site),\n s2 <> owner ->\n s1 <> owner ->\n ~ In s1 l ->\n sigma_but Site owner eq_site_dec l (fun s : Site => rooted_fun s s1 s2 copy) =\n 0%Z.\nProof.\n   intro; intro.\n   intro; intro.\n   intro.\n   elim l.\n   simpl in |- *; auto.\n   simpl in |- *.\n   intros.\n   case (eq_site_dec a owner).\n   intro.\n   rewrite H1.\n   auto.\n   generalize H2; intuition.\n   intro.\n   case (eq_site_dec s1 a).\n   intro.\n   elim H2.\n   left; auto.\n   intro.\n   rewrite H1.\n   auto.\n   generalize H2; intuition.\nQed.\n\nLemma sigma_rooted_fun14 :\n forall (s1 s2 : Site) (l : list Site),\n s2 <> owner ->\n s1 <> owner ->\n only_once Site eq_site_dec s1 l ->\n sigma_but Site owner eq_site_dec l (fun s : Site => rooted_fun s s1 s2 copy) =\n 1%Z.\nProof.\n  intro; intro; intro; intro; intro.\n  elim l.\n  simpl in |- *.\n  intuition.\n  \n  simpl in |- *.\n  intros.\n  case (eq_site_dec a owner).\n  intro.\n  rewrite H1.\n  auto.\n  \n  generalize H2.\n  case (eq_site_dec s1 a).\n  intro.\n  elim H0.\n  rewrite e0; rewrite e.\n  auto.\n  \n  auto.\n  \n  intro.\n  case (eq_site_dec s1 a).\n  intro.\n  generalize (sigma_rooted_fun13 s1 s2 l0 H H0).\n  simpl in |- *.\n  intros.\n  rewrite H3.\n  auto.\n  \n  generalize H2.\n  case (eq_site_dec s1 a).\n  auto.\n  \n  intro.\n  elim n0; auto.\n  \n  intro.\n  rewrite H1.\n  auto.\n  \n  generalize H2.\n  case (eq_site_dec s1 a).\n  intro; elim n0; auto.\n  \n  auto.\nQed.\n\n\n\nLemma sigma_rooted_fun5 :\n forall s s1 : Site,\n only_once Site eq_site_dec s LS ->\n s <> owner ->\n sigma_but Site owner eq_site_dec LS\n   (fun s0 : Site => rooted_fun s0 s1 owner (inc_dec s)) = 1%Z.\nProof.\n  intro; intro.\n  elim LS.\n  simpl in |- *.\n  intuition.\n  \n  intros.\n  case (eq_site_dec a owner).\n  intro.\n  generalize H0.\n  case (eq_site_dec s a).\n  rewrite e.\n  intuition.\n  \n  generalize H.\n  simpl in |- *.\n  intros.\n  rewrite H2.\n  case (eq_site_dec a owner).\n  auto.\n  \n  intuition.\n  \n  generalize H3.\n  case (eq_site_dec s a).\n  intuition.\n  \n  auto.\n  \n  auto.\n  \n  intros.\n  generalize H.\n  generalize (sigma_rooted_fun4 s s1 l).\n  simpl in |- *.\n  intros.\n  rewrite case_ineq.\n  case (eq_site_dec s a).\n  intro.\n  rewrite H2.\n  rewrite case_eq.\n  auto.\n  \n  generalize H0; simpl in |- *.\n  case (eq_site_dec s a).\n  auto.\n  \n  intuition.\n  \n  intros.\n  rewrite H3.\n  auto.\n  \n  generalize H0; simpl in |- *.\n  case (eq_site_dec s a).\n  intuition.\n  \n  auto.\n  \n  auto.\n  \n  auto.\nQed.\n\n\n\n\nLemma sigma_rooted_fun1 :\n forall (s s1 s2 : Site) (d : Message),\n s2 <> owner ->\n ~ In s1 LS ->\n ~ In s2 LS ->\n sigma_but Site owner eq_site_dec LS (fun s : Site => rooted_fun s s1 s2 d) =\n 0%Z.\nProof.\n  intros s s1 s2 d H.\n  elim LS.\n  simpl in |- *.\n  auto.\n  intros.\n  simpl in |- *.\n  case (eq_site_dec a owner).\n  intro.\n  apply H0.\n  generalize H1; simpl in |- *.\n  intuition.\n  generalize H2; simpl in |- *; intuition.\n  intro.\n  rewrite H0.\n  case (eq_site_dec s1 a).\n  generalize H1; simpl in |- *.\n  intro.\n  intro.\n  elim H3.\n  left; auto.\n  intro.\n  case (eq_site_dec s2 a).\n  generalize H2; simpl in |- *; intro; intro.\n  elim H3.\n  left; auto.\n  intro.\n  rewrite sigma_rooted_fun2.\n  omega.\n  auto.\n  auto.\n  auto.\n  generalize H1; simpl in |- *; intuition.\n  generalize H2; simpl in |- *; intuition.\nQed.\n\nLemma add_reduce4 :\n forall x y z a : Z, (x + y)%Z = (z + a)%Z -> (x - a)%Z = (z - y)%Z.\nProof.\nintros; omega.\nQed.\n\nLemma add_reduce5 :\n forall x y z a : Z, (x - a)%Z = (z - y)%Z -> x = (a + z - y)%Z.\nProof.\nintros; omega.\nQed.\n\nLemma add_reduce6 : forall x y z : Z, x = (z + y)%Z -> (x - z)%Z = y.\nProof.\nintros; omega.\nQed.\n\n\n\nEnd INVARIANT3.\n", "meta": {"author": "coq-contribs", "repo": "distributed-reference-counting", "sha": "6552f14cce0ea374c98adcbee0476ae268d64a7e", "save_path": "github-repos/coq/coq-contribs-distributed-reference-counting", "path": "github-repos/coq/coq-contribs-distributed-reference-counting/distributed-reference-counting-6552f14cce0ea374c98adcbee0476ae268d64a7e/machine3/invariant3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2487681003079427}}
{"text": "(*\n * Copyright (c) 2009-2011, Andrew Appel, Robert Dockins and Aquinas Hobor.\n *\n *)\n\nRequire Import VST.msl.base.\nRequire Import VST.msl.sepalg.\nRequire Import VST.msl.psepalg.\nRequire Import VST.msl.eq_dec.\nRequire Import VST.msl.shares.\n\n(** The prototypical example of a psepalg is the positive shares, which\n    are just the lifted basic shares. *)\nDefinition pshare : Type := lifted Share.Join_ba.\nInstance Join_pshare: Join pshare := @Join_lift _ _.\nInstance Perm_pshare : Perm_alg pshare := Perm_lift Share.pa.\nInstance Canc_pshare : Canc_alg pshare := @Canc_lift _ _ Share.ca.\nInstance Disj_pshare : Disj_alg pshare := @Disj_lift _ _ Share.da.\nInstance Pos_pshare : Pos_alg pshare := @Pos_lift _ _.\n\nDefinition pshare_sh : pshare -> share := @lifted_obj share Share.Join_ba.\nCoercion pshare_sh : pshare >-> share.\n\nLemma pshare_eq_dec: forall sh1 sh2: pshare, {sh1=sh2}+{sh1<>sh2}.\nProof.\n  intros.\n  destruct sh1; destruct sh2.\n  destruct (eq_dec x x0); [left|right].\n  subst x0.\n  rewrite (proof_irr n n0); auto.\n  intro.\n  inv H.\n  contradiction n1; auto.\nQed.\n\nInstance EqDec_pshare : EqDec pshare := pshare_eq_dec.\n\nDefinition pfullshare : pshare :=\n  mk_lifted fullshare top_share_nonunit.\n\nLemma pfullshare_pfull : full pfullshare.\nProof with auto.\n  unfold pshare.\n  apply lifted_full. auto with typeclass_instances.\n  apply fullshare_full.\nQed.\n\nLemma join_sub_pfullshare: forall (p: pshare),\n  @join_sub share Share.Join_ba pfullshare p ->\n  p = pfullshare.\nProof.\n  intros. apply join_sub_fullshare in H. apply lifted_eq. trivial.\nQed.\n\nLemma pjoin_sub_pfullshare: forall (p : pshare),\n  join_sub pfullshare p -> False.\nProof.\n  intros.\n  generalize pfullshare_pfull; intro.\n  rewrite pfull_pmaximal in H0.\n  generalize (H0 _ H); intro.\n  destruct H. subst p.\n  apply join_comm in H.\n  contradiction (no_units x pfullshare).\nQed.\n\nLemma pshare_join_full_false1 : forall (p:pshare),\n   joins pfullshare p -> False.\nProof.\n  intros.\n  destruct H. inv H. simpl in *. unfold fullshare in H0.\n  rewrite Share.glb_commute in H0. rewrite Share.glb_top in H0.\n  destruct p; simpl in *. subst. contradiction (n Share.bot). auto.\nQed.\n\nLemma pshare_join_full_false2 : forall (p:pshare),\n   joins p pfullshare -> False.\nProof.\n  intros. apply joins_comm in H. apply pshare_join_full_false1 with p; auto.\nQed.\n\nLemma pshare_join_full_false3: forall (p1: pshare) sh3,\n  join (lifted_obj p1) Share.top sh3 -> False.\nProof.\n  intros.\n  destruct p1. unfold lifted_obj, pfullshare, mk_lifted, proj1_sig in H.\n  destruct H. rewrite Share.glb_top in H. subst. contradiction (n Share.bot); auto.\nQed.\n\nLemma pshare_join_full_false4: forall (p1: pshare) sh3,\n  join Share.top (lifted_obj p1) sh3 -> False.\nProof.\n  intros.\n  eapply pshare_join_full_false3. apply join_comm in H. eauto.\nQed.\n\nLemma pshare_pjoin_full_false3: forall (p1: pshare) pp sh3,\n   join p1 (mk_lifted Share.top pp) sh3 -> False.\nProof.\n  intros. destruct sh3.\n  do 2 red in H. simpl lifted_obj in *.\n apply pshare_join_full_false3 in H. trivial.\nQed.\n\nLemma pshare_pjoin_full_false4: forall (p1: pshare) pp sh3,\n   join (mk_lifted Share.top pp) p1 sh3 -> False.\nProof.\n  intros. destruct sh3.\n  do 2 red in H. simpl lifted_obj in *.\n  apply pshare_join_full_false4 in H. trivial.\nQed.\n\nLtac pfullshare_join :=\n  elimtype False;\n  solve [ eapply pshare_join_full_false1; eauto\n    | eapply pshare_join_full_false2; eauto\n    | eapply pshare_join_full_false3; eauto\n    | eapply pshare_join_full_false4; eauto\n    | eapply pshare_pjoin_full_false3; eauto\n    | eapply pshare_pjoin_full_false4; eauto\n  ].\n\nProgram Definition split_pshare (sh: pshare) : pshare * pshare :=\n  (mk_lifted (fst (Share.split sh)) _, mk_lifted (snd (Share.split sh)) _).\nNext Obligation.\nProof.\n  intros.\n  case_eq (Share.split (proj1_sig sh)); simpl.\n  intros.\n  generalize (split_nontrivial' _ _ _ H); intro.\n  intros ? ?. apply unit_identity in H1. destruct sh; simpl in H0.\n  assert (identity x0) by auto. contradiction (n x0).\n  apply identity_unit_equiv in H2; auto.\nQed.\nNext Obligation.\nProof.\n  intros.\n  case_eq (Share.split (proj1_sig sh)); simpl.\n  intros.\n  generalize (split_nontrivial' _ _ _ H); intro.\n  intros ? ?. apply unit_identity in H1. destruct sh; simpl in H0.\n  assert (identity x0) by auto. contradiction (n x0).\n  apply identity_unit_equiv in H2; auto.\nQed.\n\nLemma psplit_split: forall psh psha pshb,\n  (split_pshare psh = (psha, pshb)) =\n  (Share.split (lifted_obj psh) = (lifted_obj psha, lifted_obj pshb)).\nProof.\n  unfold split_pshare, lifted_obj.\n  intros. apply prop_ext. split; intro.\n  inversion H.\n  apply injective_projections; auto.\n  apply injective_projections; apply lifted_eq; simpl; rewrite H; auto.\nQed.\n\nLemma psplit_pjoin: forall psh psha pshb,\n  split_pshare psh = (psha, pshb) ->\n   join psha pshb psh.\nProof.\n  intros.\n  rewrite psplit_split in H.\n  apply split_join in H.\n  trivial.\nQed.\n\nLemma pshare_split_neq1: forall psh psh1 psh2, split_pshare psh = (psh1, psh2) -> psh1 <> psh.\nProof.\n  intros.\n  apply psplit_pjoin in H.\n  intro contra. subst psh1.\n  apply  join_comm in H.\n  apply pjoin_unit in H. trivial.\nQed.\n\nLemma pshare_split_neq2: forall psh psh1 psh2, split_pshare psh = (psh1, psh2) -> psh2 <> psh.\nProof.\n  intros.\n  apply psplit_pjoin in H.\n  intro contra. subst psh2.\n  apply pjoin_unit in H. trivial.\nQed.\n\nDefinition pLhalf : pshare := fst (split_pshare pfullshare).\nDefinition pRhalf : pshare := snd (split_pshare pfullshare).\n\nLemma pleftright :  join pLhalf pRhalf pfullshare.\nProof.\n  apply psplit_pjoin.\n  trivial.\nQed.\n\nLemma pshare_nonunit: forall sh: pshare, nonunit (pshare_sh sh).\nProof. repeat intro. destruct sh; simpl in *. apply n in H. auto.\nQed.\n\nLemma pshare_not_identity: forall sh: pshare, ~ identity (pshare_sh sh).\nProof. intros. apply nonunit_nonidentity. apply pshare_nonunit.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/msl/pshares.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.24876810030794266}}
{"text": "Require Import ExtLib.Core.RelDec.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.Lambda.AppN.\nRequire Import MirrorCharge.ILogicFunc.\nRequire Import MirrorCharge.Imp.Syntax.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nLocal Existing Instance SS.\nLocal Existing Instance SU.\nLocal Existing Instance RSym_ilfunc.\nLocal Existing Instance RS.\nLocal Existing Instance Expr_expr.\n\nLocal Notation \"a @ b\" := (@App typ _ a b) (at level 30).\nLocal Notation \"\\ t -> e\" := (@Abs typ _ t e) (at level 40).\nLocal Notation \"'Ap' '[' x , y ']'\" := (Inj (inl (inr (pAp x y)))) (at level 0).\nLocal Notation \"'Pure' '[' x ']'\" := (Inj (inl (inr (pPure x)))) (at level 0).\nLocal Notation \"x '|-' y\" :=\n  (App (App (Inj (inr (ilf_entails (tyArr tyLocals tyHProp)))) x) y) (at level 10).\nLocal Notation \"'{{'  P  '}}'  c  '{{'  Q  '}}'\" :=\n  (Inj (inl (inl 1%positive)) @ P @ c @ Q) (at level 20).\nLocal Notation \"c1 ;; c2\" := (Inj (inl (inl 2%positive)) @ c1 @ c2) (at level 30).\n\nFixpoint expr_eq (a b : expr typ func) : option bool :=\n  match a , b with\n    | Var a , Var b => if a ?[ eq ] b then Some true else None\n    | UVar a , UVar b => if a ?[ eq ] b then Some true else None\n    | Inj a , Inj b => SymI.sym_eqb a b\n    | App a b , App c d =>\n      match expr_eq a c with\n        | Some true => expr_eq b d\n        | _ => None\n      end\n    | Abs t a , Abs t' b => expr_eq a b\n    | _ , _ => None\n  end.\n\nSection interp_get.\n  Variable v : expr typ func.\n\n  Definition compare_expr (e1 e2 : expr typ func) : option bool :=\n    expr_eq e1 e2.\n\n  Fixpoint interp_get (updf : expr typ func)\n  : expr typ func :=\n    match updf with\n      | App (App (Inj (inl (inr pLocals_upd))) v') val =>\n        match compare_expr v v' with\n          | Some true =>\n            lpure tyNat val\n          | Some false =>\n            App flocals_get v\n          | None =>\n            App (App (Inj (inl (inr (pUpdate tyNat)))) updf) (App flocals_get v)\n        end\n      | _ =>\n        App (App (Inj (inl (inr (pUpdate tyNat)))) updf) (App flocals_get v)\n    end.\nEnd interp_get.\n\nSection pushUpdates.\n  Variable f : expr typ func.\n\n  Fixpoint pushUpdates (e : expr typ func) (t : typ)\n  : expr typ func :=\n    match e with\n      | App (App (Inj (inl (inr (pStar t)))) L) R =>\n        lstar t (pushUpdates L t) (pushUpdates R t)\n      | Inj (inr (ilf_true t)) => Inj (inr (ilf_true t))\n      | Inj (inr (ilf_false t)) => Inj (inr (ilf_false t))\n      | App (App (Inj (inr (ilf_and t))) L) R =>\n        App (App (Inj (inr (ilf_and t))) (pushUpdates L t)) (pushUpdates R t)\n      | App (App (Inj (inr (ilf_or t))) L) R =>\n        App (App (Inj (inr (ilf_or t))) (pushUpdates L t)) (pushUpdates R t)\n      | App (App (Inj (inr (ilf_impl t))) L) R =>\n        App (App (Inj (inr (ilf_impl t))) (pushUpdates L t)) (pushUpdates R t)\n      | App (Inj (inr (ilf_exists X t))) (Abs t' e) =>\n        App (Inj (inr (ilf_exists X t))) (Abs t' (pushUpdates e t))\n      | App (Inj (inr (ilf_forall X t))) (Abs t' e) =>\n        App (Inj (inr (ilf_forall X t))) (Abs t' (pushUpdates e t))\n      | App (Pure [t]) e =>\n        App (Pure [t]) e\n      | App (App (Ap [t1,t2]) e1) e2 =>\n        App (App (Ap [t1,t2]) (pushUpdates e1 (tyArr t1 t2))) (pushUpdates e2 t1)\n      | App (Inj (inl (inr pLocals_get))) v =>\n        interp_get v f\n      | _ => App (App (Inj (inl (inr (pUpdate t)))) f) e\n    end.\nEnd pushUpdates.\n\nDefinition simplify (e : expr typ func) (args : list (expr typ func))\n: expr typ func :=\n  match e with\n    | Inj (inl (inr pEval_expri)) =>\n      match args with\n        | App (Inj (inl (inr eVar))) X :: xs =>\n          apps (App flocals_get X) xs\n        | _ => apps e args\n      end\n    | Inj (inl (inr (pUpdate t))) =>\n      match args with\n        | f :: e :: nil =>\n          pushUpdates f e t\n        | _ => apps e args\n      end\n    | _ => apps e args\n  end.\n", "meta": {"author": "jesper-bengtson", "repo": "MirrorCharge", "sha": "cb0fe1da80be70ba4b744d4178a4e6e3afa38e62", "save_path": "github-repos/coq/jesper-bengtson-MirrorCharge", "path": "github-repos/coq/jesper-bengtson-MirrorCharge/MirrorCharge-cb0fe1da80be70ba4b744d4178a4e6e3afa38e62/MirrorCharge!/src/MirrorCharge/Imp/STacSimplify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24876810030794264}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\n(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(****************************************************************)\n(*           The Calculus of Inductive Constructions            *)\n(*                       COQ v5.10                              *)\n(*                                                              *)\n(* Laurent Arditi.  Laboratoire I3S. CNRS ura 1376.             *)\n(* Universite de Nice - Sophia Antipolis                        *)\n(* arditi@unice.fr, http://wwwi3s.unice.fr/~arditi/lolo.html    *)\n(*                                                              *)\n(* date: november 1995                                          *)\n(* file: Fill_spec.v                                            *)\n(* contents: proof of a memory block instruction: Fills cx words*)\n(* in memory starting at address di with value al.              *)\n(* Specification level                                          *)\n(****************************************************************)\n\nRequire Export Fill_defs.\n\n(* Specification:\n\ncx: register a_size\ndi: register a_size\nal: register d_size\nmem: memory of d_size bit words, addresses of a_size bits\n\nwhile not(cx=0) do begin\n  mem[di] <- al\n  di <- di+1\n  cx <- cx-1\nend\n*)\n\n(****************************************************************)\n\nFixpoint di (st : nat) : BV -> BV -> BV -> Memo -> BV :=\n  fun (di0 cx0 al0 : BV) (mem0 : Memo) =>\n  match st return BV with\n  | O => di0\n  | S t =>\n      match IsNull (cx t di0 cx0 al0 mem0) return BV with\n      | true => di t di0 cx0 al0 mem0\n      | false => BV_increment (di t di0 cx0 al0 mem0)\n      end\n  end\n \n with cx (st : nat) : BV -> BV -> BV -> Memo -> BV :=\n  fun (di0 cx0 al0 : BV) (mem0 : Memo) =>\n  match st return BV with\n  | O => cx0\n  | S t =>\n      match IsNull (cx t di0 cx0 al0 mem0) return BV with\n      | true => cx t di0 cx0 al0 mem0\n      | false => BV_decrement (cx t di0 cx0 al0 mem0)\n      end\n  end\n \n with al (st : nat) : BV -> BV -> BV -> Memo -> BV :=\n  fun (di0 cx0 al0 : BV) (mem0 : Memo) =>\n  match st return BV with\n  | O => al0\n  | S t =>\n      match IsNull (cx t di0 cx0 al0 mem0) return BV with\n      | true => al t di0 cx0 al0 mem0\n      | false => al t di0 cx0 al0 mem0\n      end\n  end\n \n with mem (st : nat) : BV -> BV -> BV -> Memo -> Memo :=\n  fun (di0 cx0 al0 : BV) (mem0 : Memo) =>\n  match st return Memo with\n  | O => mem0\n  | S t =>\n      match IsNull (cx t di0 cx0 al0 mem0) return Memo with\n      | true => mem t di0 cx0 al0 mem0\n      | false =>\n          MemoWrite (mem t di0 cx0 al0 mem0)\n            (BV_to_nat (di t di0 cx0 al0 mem0)) (al t di0 cx0 al0 mem0)\n      end\n  end.\n\n(****************************************************************)\n(* Valeurs generales des registres *)\n\nLemma di_t :\n forall (t : nat) (di0 cx0 al0 : BV) (mem0 : Memo),\n di (S t) di0 cx0 al0 mem0 =\n match IsNull (cx t di0 cx0 al0 mem0) return BV with\n | true => di t di0 cx0 al0 mem0\n | false => BV_increment (di t di0 cx0 al0 mem0)\n end.\nauto.\nQed.\n\nLemma cx_t :\n forall (t : nat) (di0 cx0 al0 : BV) (mem0 : Memo),\n cx (S t) di0 cx0 al0 mem0 =\n match IsNull (cx t di0 cx0 al0 mem0) return BV with\n | true => cx t di0 cx0 al0 mem0\n | false => BV_decrement (cx t di0 cx0 al0 mem0)\n end.\nauto.\nQed.\n\nLemma al_t :\n forall (t : nat) (di0 cx0 al0 : BV) (mem0 : Memo),\n al (S t) di0 cx0 al0 mem0 =\n match IsNull (cx t di0 cx0 al0 mem0) return BV with\n | true => al t di0 cx0 al0 mem0\n | false => al t di0 cx0 al0 mem0\n end.\nauto.\nQed.\n\nLemma al_constant :\n forall (t : nat) (di0 cx0 al0 : BV) (mem0 : Memo),\n al t di0 cx0 al0 mem0 = al0.\nsimple induction t. auto.\nintros. rewrite al_t. elim (IsNull (cx n di0 cx0 al0 mem0)). apply H. apply H.\nQed.\n\nLemma mem_t :\n forall (t : nat) (di0 cx0 al0 : BV) (mem0 : Memo),\n mem (S t) di0 cx0 al0 mem0 =\n match IsNull (cx t di0 cx0 al0 mem0) return Memo with\n | true => mem t di0 cx0 al0 mem0\n | false =>\n     MemoWrite (mem t di0 cx0 al0 mem0) (BV_to_nat (di t di0 cx0 al0 mem0))\n       (al t di0 cx0 al0 mem0)\n end.\nauto.\nQed.\n(****************************************************************)\n(* Longueurs des registres *)\n\nLemma length_di :\n forall t : nat, lengthbv (di t di_init cx_init al_init mem_init) = a_size.\nsimple induction t. simpl in |- *. exact di_initsize.\nintros.\nrewrite di_t. elim (IsNull (cx n di_init cx_init al_init mem_init)). exact H.\nrewrite length_BV_increment. exact H.\nQed.\n\nLemma length_cx :\n forall t : nat, lengthbv (cx t di_init cx_init al_init mem_init) = a_size.\nsimple induction t. simpl in |- *. exact cx_initsize.\nintros.\nrewrite cx_t. elim (IsNull (cx n di_init cx_init al_init mem_init)). exact H.\nrewrite length_BV_decrement. exact H.\nQed.\n\nLemma length_al :\n forall t : nat, lengthbv (al t di_init cx_init al_init mem_init) = d_size.\nintro. rewrite al_constant. exact al_initsize.\nQed.", "meta": {"author": "coq-contribs", "repo": "circuits", "sha": "f2cec6067f2c58e280c5b460e113d738b387be15", "save_path": "github-repos/coq/coq-contribs-circuits", "path": "github-repos/coq/coq-contribs-circuits/circuits-f2cec6067f2c58e280c5b460e113d738b387be15/BLOCK/Fill_spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24875116618628154}}
{"text": "(* Copyright (c) 2011. Greg Morrisett, Gang Tan, Joseph Tassarotti, \n   Jean-Baptiste Tristan, and Edward Gan.\n\n   This file is part of RockSalt.\n\n   This file is free software; you can redistribute it and/or\n   modify it under the terms of the GNU General Public License as\n   published by the Free Software Foundation; either version 2 of\n   the License, or (at your option) any later version.\n*)\n\nRequire Coqlib.\nRequire Import Parser.\nRequire Import Ascii.\nRequire Import String.\nRequire Import List.\nUnset Automatic Introduction.\nSet Implicit Arguments.\nOpen Scope char_scope.\n\n\nRequire ExtrOcamlString.\nRequire ExtrOcamlNatBigInt.\n(*Require ExtrOcamlNatInt.*)\n\nModule TEST_PARSER_ARG.\n  Definition char_p := bool.\n  Definition char_eq := Bool.bool_dec.\n\n  Inductive type : Set := \n  | Int_t : type.\n\n  Definition tipe := type.\n  Definition tipe_eq : forall (t1 t2:tipe), {t1=t2} + {t1<>t2}.\n    intros ; decide equality.\n  Defined.\n  Definition tipe_m (t:tipe) := \n    match t with \n      | Int_t => nat\n    end.\nEnd TEST_PARSER_ARG.\n\nModule TEST_PARSER.\nModule T := Parser.Parser(TEST_PARSER_ARG).\nImport TEST_PARSER_ARG.\nImport T.\nInfix \"|+|\" := Alt_p (right associativity, at level 80).\nInfix \"$\" := Cat_p (right associativity, at level 70).\nDefinition map_p t1 t2 (p:parser t1) (f:result_m t1 -> result_m t2) := @Map_p t1 t2 f p.\nImplicit Arguments map_p [t1 t2].\nInfix \"@\" := map_p (right associativity, at level 75).\nDefinition Plus_p t (p:parser t) := \n  (Cat_p p (Star_p p)) @ (fun p => ((fst p)::(snd p)): result_m (list_t t)).\nDefinition Alts_p t (ps:list (parser t)) := \n  List.fold_right (@Alt_p t) (Zero_p t) ps.\nDefinition int_t := tipe_t Int_t.\nNotation \"e %% t\" := (e : result_m t) (at level 80).\n\nDefinition one := Char_p true @ (fun _ => 1 %% int_t).\nDefinition zero := Char_p false @ (fun _ => 0 %% int_t).\nDefinition bit' := zero |+| one.\nDefinition bit := Any_p @ (fun c => (if c then 1 else 0) %% int_t).\nDefinition nibble := \n  bit $ bit $ bit $ bit @ \n  (fun x => match x with \n              | (b3,(b2,(b1,b0))) => b0 + 2*b1 + 4*b2 + 8*b3\n            end %% int_t).\nDefinition byte := \n  nibble $ nibble @ (fun p => (snd p + (fst p)*256) %% int_t).\n\n(* is a parser deterministic for strings up to length n? *)\nDefinition is_deterministic t (p:parser t) n := \n  is_determ (snd (parser2regexp p)) 2 (fun n => (match n with 0 => false | _ => true end)::nil) n\n  (fst (parser2regexp p)) (p2r_wf p _).\n\nLemma is_deterministic_byte : is_deterministic byte 8 = true.\nProof.\n  auto.\nQed.\n\nDefinition ambiguous_p := nibble |+| nibble.\n\nLemma is_deterministic_ambiguous_p : is_deterministic ambiguous_p 4 = false.\nProof.\n  auto.\nQed.\n\nFixpoint explode(s:string) : list bool := \n  match s with \n    | \"\"%string => nil\n    | String \"0\" t => false::(explode t)\n    | String _ t => true::(explode t)\n  end.\n\nDefinition lex t (p:parser t) s := parse p (explode s).\n\n(*\nOpaque result_m.\nOpaque p2r_wf.\nOpaque wf_derivs.\nEval compute in lex (nibble) \"0101\". *)\nEnd TEST_PARSER.\n\n  \n\n", "meta": {"author": "mpettersson", "repo": "reins-verifier-proof", "sha": "44d0b8e0c29b07eb71b1d6d44b020648783409fb", "save_path": "github-repos/coq/mpettersson-reins-verifier-proof", "path": "github-repos/coq/mpettersson-reins-verifier-proof/reins-verifier-proof-44d0b8e0c29b07eb71b1d6d44b020648783409fb/Model/ParserTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.2487511596377174}}
{"text": "(*\n * Strong Normalization for Nested Relational Calculus.\n * Copyright Ezra Cooper, 2008-2020.\n *)\n\nAdd Rec LoadPath \"Listkit\" as Listkit.\n\nRequire Import List.\nRequire Import Term.\n\nLoad \"eztactics.v\".\n\nRequire Import Listkit.NthError.\n\nHint Rewrite app_comm_cons : list.\n\n(** Weaken a typing derivation by extending its environment\n    and it still holds. *)\nLemma Weakening :\n  forall env' tm ty env, Typing env tm ty ->\n    Typing (env++env') tm ty.\nProof.\n induction tm; intros ty env tp; inversion tp; eauto with NthError.\n  apply TAbs.\n  autorewrite with list.\n  seauto.\n apply TBind with s.\n  apply IHtm1; sauto.\n autorewrite with list.\n apply IHtm2; sauto.\nQed.\n\n(** Special case of weakening for closed terms. *)\nLemma Weakening_closed :\n  forall tm ty env, Typing nil tm ty -> Typing env tm ty.\nProof.\n intros tm ty env H.\n replace env with (nil ++ env); auto using Weakening.\nQed.\n\n#[export]\nHint Resolve Weakening_closed.\n", "meta": {"author": "ezrakilty", "repo": "nrc-sql", "sha": "132a4c2e91bd90e7cead57099f5e72a39b061b3e", "save_path": "github-repos/coq/ezrakilty-nrc-sql", "path": "github-repos/coq/ezrakilty-nrc-sql/nrc-sql-132a4c2e91bd90e7cead57099f5e72a39b061b3e/Typing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24875115963771738}}
{"text": "Require Import Coq.Logic.ProofIrrelevance.\nRequire Import Coq.Sets.Ensembles.\nRequire Import Coq.Sets.Finite_sets.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Classes.Morphisms.\nRequire Import CertiGraph.lib.Coqlib.\nRequire Import CertiGraph.lib.List_ext.\nRequire Import CertiGraph.lib.EquivDec_ext.\nRequire Import VST.msl.Coqlib2.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.path_lemmas. Import CertiGraph.graph.path_lemmas.PathNotation.\nRequire Import CertiGraph.graph.reachable_computable.\nRequire Import CertiGraph.graph.reachable_ind.\nRequire Import CertiGraph.graph.subgraph2.\n\nSection Dag.\n\nContext {V : Type}.\nContext {E : Type}.\nContext {EV: EqDec V eq}.\nContext {EE: EqDec E eq}.\n\nNotation Graph := (PreGraph V E).\n\nDefinition not_in_circle (g: Graph) (x: V) := forall y: V, edge g x y -> reachable g y x -> False.\n\nDefinition localDag (g: Graph) (x: V) := forall y, reachable g x y -> not_in_circle g y.\n\nDefinition Dag (g: Graph) := forall x, not_in_circle g x.\n\nLemma local_dag_step: forall (g: Graph) x y, localDag g x -> vvalid g x -> step g x y -> localDag g y.\nProof.\n  intros.\n  unfold localDag in *.\n  intros z ?.\n  apply (H z).\n  apply step_reachable with y; auto.\nQed.\n\nLemma dag_local_dag: forall (g: Graph) x, Dag g -> localDag g x.\nProof.\n  intros.\n  intro; intros.\n  apply H.\nQed.\n\nLemma si_local_dag: forall (g1 g2: Graph) x, g1 ~=~ g2 -> (localDag g1 x <-> localDag g2 x).\nProof.\n  cut (forall (g1 g2: Graph) x, g1 ~=~ g2 -> localDag g1 x -> localDag g2 x).\n  1: intros; split; apply H; [| symmetry]; auto.\n  intros.\n  hnf; intros.\n  rewrite <- H in H1.\n  specialize (H0 _ H1); clear H1.\n  hnf; intros.\n  pose proof edge_si _ _ y y0 H.\n  rewrite <- H3 in H1.\n  rewrite <- H in H2.\n  specialize (H0 _ H1 H2).\n  auto.\nQed.\n\nLemma si_dag: forall (g1 g2: Graph), g1 ~=~ g2 -> (Dag g1 <-> Dag g2).\nProof.\n  cut (forall (g1 g2: Graph), g1 ~=~ g2 -> Dag g1 -> Dag g2).\n  1: intros; split; apply H; [| symmetry]; auto.\n  intros.\n  hnf; intros.\n  hnf; intros.\n  pose proof edge_si _ _ x y H.\n  rewrite <- H in H2.\n  rewrite <- H3 in H1.\n  specialize (H0 _ _ H1 H2).\n  auto.\nQed.\n\n#[export] Instance local_dag_proper: Proper (structurally_identical ==> eq ==> iff) localDag.\nProof.\n  do 2 (hnf; intros).\n  subst.\n  apply si_local_dag; auto.\nDefined.\n\n#[export] Instance dag_proper: Proper (structurally_identical ==> iff) Dag.\nProof.\n  hnf; intros.\n  apply si_dag; auto.\nDefined.\n\nLemma localDag_reachable_spec: forall g x S,\n  vvalid g x ->\n  localDag g x ->\n  step_list g x S ->\n  (forall y, reachable g x y <-> reachable_through_set g S y \\/ y = x) /\\\n  (forall y, reachable_through_set g S y -> y <> x).\nProof.\n  intros.\n  split; intros.\n  + rewrite (reachable_ind' g x S y H H1).\n    assert (x = y <-> y = x) by (split; congruence).\n    tauto.\n  + destruct H2 as [x0 [? ?]].\n    rewrite (H1 x0) in H2.\n    specialize (H0 x).\n    spec H0; [apply reachable_refl; auto |].\n    specialize (H0 x0).\n    assert (vvalid g x0) by (apply reachable_head_valid in H3; auto).\n    assert (edge g x x0) by (split; [| split]; auto).\n    spec H0; [auto |].\n    intro; subst; tauto.\nQed.\n\nLemma localDag_reachable_spec': forall g x S,\n  vvalid g x ->\n  localDag g x ->\n  step_list g x S ->\n  Prop_join (reachable_through_set g S) (eq x) (reachable g x).\nProof.\n  intros.\n  destruct (localDag_reachable_spec _ _ _ H H0 H1).\n  split.\n  + intros y; specialize (H2 y).\n    rewrite H2; clear.\n    firstorder.\n  + intros y; specialize (H3 y).\n    firstorder.\nQed.\n\nLemma localDag_reachable_list_spec: forall g x S l,\n  vvalid g x ->\n  localDag g x ->\n  step_list g x S ->\n  reachable_list g x l ->\n  reachable_set_list g S (remove equiv_dec x l).\nProof.\n  intros.\n  intro y.\n  specialize (H2 y).\n  rewrite remove_In_iff.\n  rewrite H2.\n  rewrite (reachable_ind' g x S y H H1).\n  assert (x = y <-> y = x) by (split; intros; congruence).\n  assert (reachable_through_set g S y -> y <> x); [| tauto].\n  specialize (H0 x).\n  spec H0; [apply reachable_refl; auto |].\n  intros [z [? ?]] ?.\n  subst.\n  specialize (H0 z).\n  rewrite (H1 z) in H4.\n  apply H0; auto.\n  split; [| split]; auto.\n  apply reachable_head_valid in H5; auto.\nQed.\n\nLemma localDag_step_rev: forall g x S,\n  vvalid g x ->\n  step_list g x S ->\n  ~ reachable_through_set g S x ->\n  Forall (localDag g) S ->\n  localDag g x.\nProof.\n  intros.\n  intros y ?; simpl.\n  rewrite (reachable_ind' g x S y H H0) in H3.\n  destruct H3.\n  + subst y.\n    intros y ? ?.\n    apply H1; exists y; split; auto.\n    rewrite (H0 y).\n    destruct H3 as [? [? ?]]; auto.\n  + destruct H3 as [s [? ?]].\n    rewrite Forall_forall in H2; specialize (H2 s H3).\n    apply H2; auto.\nQed.\n\nEnd Dag.\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/graph/dag.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24875115963771738}}
{"text": "Require Import RelationClasses.\nRequire Import List.\nRequire Import Omega.\nRequire Import sflib.\nFrom Paco Require Import paco.\nRequire Import Basics.\n\nRequire Import Basic.\nRequire Import Axioms.\nRequire Import Loc.\nRequire Import Language.\nRequire Import ZArith.\nRequire Import Maps.\nRequire Import Iteration.\n\nRequire Import FSets.\nRequire Import FSetInterface.\nRequire Import Lattice.\nRequire Import Event.\nRequire Import Syntax.\nRequire Import Semantics.\nRequire Import Kildall.\nRequire Import Coqlib.\n\nRequire Import Integers.\nRequire Import LibTactics.\nRequire Import CorrectOpt.\nRequire Import Lib_Ordering.\nSet Implicit Arguments.\n\n(** * Loop Invariant Detecting *)\n\n(** This file defines the analysis to detect loop invariants. *)\n\n(** ** Evaluation of the Dominator *)\n(** For each block labelled f, its NDominators returns whether a node f' is\n    its dominators.\n    If f' maps to true, it means that f' is not the dominator of f;\n    if f' maps to false, it means that f' is the dominator of f. *)\nModule NDominators := LPMap(LBoolean).\nModule NDomDS := Dataflow_Solver(NDominators)(NodeSetForward).\n\n(** [dominator] justifies that whether the block labelled f' is the\n    dominator of the block that we focus on. *) \nDefinition dominator (ndom: NDominators.t) (f': positive) :=\n  if NDominators.get f' ndom then false else true.\n\n(** ** Back Edge *)\n(** After evaluating the dominators of each block, we can find the loop.\n    l_entry and l_exit are entry and exit of a loop,\n    if l_exit points to l_entry and l_entry dominates l_exit. *) \nDefinition back_edge (l_exit l_entry: positive)\n           (ndom: NDominators.t) (cdhp: CodeHeap) :=\n  match PTree.get l_exit cdhp with\n  | Some BB =>\n    In l_entry (succ BB) /\\ dominator ndom l_entry = true\n  | None => False\n  end.\n\nLemma back_edge_eq_dec\n      l_exit l_entry ndom cdhp:\n  {back_edge l_exit l_entry ndom cdhp} + {~ back_edge l_exit l_entry ndom cdhp}.\nProof.\n  unfold back_edge.\n  destruct (cdhp ! l_exit) eqn:EXIT; ss.\n  2: { right. ii; eauto. }\n  pose proof in_dec as LIST_IN_EQ_DEC.\n  specialize (LIST_IN_EQ_DEC Language.fid).\n  assert (forall x y: positive, {x = y} + {x <> y}).\n  {\n    ii. eapply Pos.eq_dec; eauto.\n  } \n  eapply LIST_IN_EQ_DEC with (l := succ t) (a := l_entry) in H.\n  destruct H.\n  {\n    destruct (dominator ndom l_entry) eqn:IS_IN_DOM; ss.\n    eauto.\n    right. ii. des. ss.\n  }\n  {\n    right. ii. des. eapply n in H. tryfalse.\n  }\nQed.\n\n(** Finding the back edge, whose exit node is l_exit. *)\nFixpoint back_edge' (l_exit: positive) (ls: list (positive * BBlock.t))\n         (ndom: NDominators.t) (cdhp: CodeHeap) :=\n  match ls with\n  | nil => nil\n  | (l, _) :: ls' =>\n    if back_edge_eq_dec l_exit l ndom cdhp then\n      (l_exit, l) :: back_edge' l_exit ls' ndom cdhp\n    else\n      back_edge' l_exit ls' ndom cdhp\n  end.\n\n(** Finding all the back edges in the code heap. *) \nFixpoint back_edges' (ls: list (positive * BBlock.t))\n         (ndoms: PMap.t NDomDS.L.t) (cdhp: CodeHeap) :=\n  match ls with\n  | nil => nil\n  | (l_exit, _) :: ls' =>\n    match ((snd ndoms) ! l_exit) with\n    | None => back_edges' ls' ndoms cdhp\n    | Some ndom =>\n      (back_edge' l_exit (PTree.elements cdhp) ndom cdhp)\n        ++ back_edges' ls' ndoms cdhp\n    end\n  end.\n                                                         \nDefinition back_edges (ndoms: PMap.t NDomDS.L.t) (cdhp: CodeHeap):\n  list (Language.fid * Language.fid) :=\n  back_edges' (PTree.elements cdhp) ndoms cdhp.  \n\n(** ** Detecting Loops *)\n(** We define [Reach](l, l', cdhp, l_entry) to determinate\n    whether l can reach l' and does not pass l_entry *)     \nFixpoint Reach'(l l': positive) (cdhp: CodeHeap) (l_entry: positive)\n         (ls: list positive) (n: nat) : bool :=\n  match n with\n  | 0%nat => false\n  | S n' =>\n    match ls with\n    | nil => false\n    | l0 :: ls' =>\n      if Ident.eq_dec l0 l' then true else\n        if Ident.eq_dec l0 l_entry then\n          Reach' l l' cdhp l_entry ls' n'\n        else\n          match (PTree.get l0 cdhp) with\n          | None => Reach' l l' cdhp l_entry ls' n'\n          | Some BB =>\n            match (Reach' l0 l' cdhp l_entry (succ BB) n') with\n            | true => true\n            | false => \n              Reach' l l' cdhp l_entry ls' n'\n            end\n          end\n    end\n  end. \n\nDefinition Reach (l l': Language.fid) (cdhp: CodeHeap) (l_entry: positive) : bool :=\n  if Ident.eq_dec l l_entry then false else\n    match (PTree.get l cdhp) with\n    | None => false\n    | Some BB =>\n      Reach' l l' cdhp l_entry (succ BB) (Pos.to_nat PrimIter.num_iterations)\n    end.\n\n(** ** Natural Loop *)\n(** [natural_loop] returns the list of nodes that belong to the loop,\n    where l_exit and l_entry construct the back edge of the loop. *)\nDefinition in_loop (l l_exit l_entry: positive) (cdhp: CodeHeap) (ndom: NDominators.t) :=\n  dominator ndom l_entry && Reach l l_exit cdhp l_entry.\nFixpoint natural_loop' \n         (l_exit l_entry: Language.fid) (cdhp: CodeHeap) (ndoms: PMap.t NDomDS.L.t)\n         (ls: list (Language.fid * BBlock.t)) :=\n  match ls with\n  | nil => IdentSet.empty\n  | (l, _) :: ls' =>\n    match ((snd ndoms) ! l) with\n    | None => IdentSet.empty\n    | Some ndom => if in_loop l l_exit l_entry cdhp ndom then\n                    IdentSet.add l (natural_loop' l_exit l_entry cdhp ndoms ls')\n                  else\n                    natural_loop' l_exit l_entry cdhp ndoms ls'\n    end\n  end. \n  \nDefinition natural_loop (l_exit l_entry: positive) (cdhp: CodeHeap) (ndoms: PMap.t NDomDS.L.t) :=\n  natural_loop' l_exit l_entry cdhp ndoms (PTree.elements cdhp).\n\n(** ** Detecting Loops  *)\n(** [det_loops] returns the list of loops.\n    The loop is represented as a tuple:\n    - l_entry: entry point;\n    - l_exit: exit point;\n    - ls: list of nodes in the loop. *)\nFixpoint det_loops' (cdhp: CodeHeap) (ndoms: PMap.t NDomDS.L.t)\n         (bk_edges: list (positive * positive)) :=\n  match bk_edges with\n  | nil => nil\n  | (l_exit, l_entry) :: bk_edges' =>\n    match (PTree.get l_exit cdhp), (PTree.get l_entry cdhp) with\n    | Some BB_exit, Some BB_entry => \n      (l_entry, l_exit, natural_loop l_exit l_entry cdhp ndoms) :: det_loops' cdhp ndoms bk_edges'\n    | _, _ => det_loops' cdhp ndoms bk_edges'\n    end\n  end. \n\nDefinition transf (p: positive) (ndom: NDomDS.L.t) :=\n  NDominators.set p false ndom. \n\nDefinition det_loops (cdhp: CodeHeap) (ep: positive) :=\n  match NDomDS.fixpoint cdhp succ transf ep NDominators.top with\n  | Some ndoms =>\n    det_loops' cdhp ndoms (back_edges ndoms cdhp)\n  | None => nil\n  end.\n\n(** ** Loop Invariants *)\nInductive LOOP_INV : Set :=\n| LINV_EXPR (r: Reg.t) (e: Inst.expr)\n| LINV_LOC (r: Reg.t) (loc: Loc.t). \n\nFixpoint expr_is_loop_inv (e: Inst.expr) (loop_invs: list LOOP_INV) :=\n  match loop_invs with\n  | nil => False\n  | (LINV_EXPR r' e') :: loop_invs =>\n    if Inst.expr_eq_dec e e' then True\n    else  expr_is_loop_inv e loop_invs\n  | _ :: loop_invs => expr_is_loop_inv e loop_invs\n  end.\n\nLemma in_expr_linv_eq_dec:\n  forall(loop_invs: list LOOP_INV) e,\n    {expr_is_loop_inv e loop_invs} + {~ expr_is_loop_inv e loop_invs}.\nProof.\n  induction loop_invs; ss; ii.\n  - right. ii; ss.\n  - destruct a; ss.\n    des_if; eauto.\nQed. \n\n(** [not_write_regs](rs, RS_W) returns true,\n    if all the registers in rs have not been written. *)\nFixpoint not_write_regs (rs: list Reg.t) (RS_W: RegSet.t) :=\n  match rs with\n  | r :: rs' => if RegSet.mem r RS_W then false\n               else not_write_regs rs' RS_W\n  | nil => true\n  end. \n\n(** An expression e is an loop invariant, if\n    - all its registers have not been written;\n    - it has not been detected as a loop invariant.\n\n    Reading from a location loc is an loop invariant, if\n    - it is a non-atomic location;\n    - it has not been written by other instrucitons.\n *) \nFixpoint loop_invB (BB: BBlock.t) (RS_W: RegSet.t) (LS_W: LocSet.t)\n         (max_reg: Reg.t) (loop_invs: list LOOP_INV) (lo: Ordering.LocOrdMap) := \n  match BB with\n  | (Inst.assign r e) ## BB' =>\n    if (not_write_regs (RegSet.elements (Inst.regs_of_expr e)) RS_W) then\n      if in_expr_linv_eq_dec loop_invs e then\n        loop_invB BB' RS_W LS_W max_reg loop_invs lo\n      else\n        loop_invB BB' RS_W LS_W (Pos.succ max_reg) ((LINV_EXPR max_reg e) :: loop_invs) lo\n    else\n      loop_invB BB' RS_W LS_W max_reg loop_invs lo\n  | (Inst.load r loc Ordering.plain) ## BB' =>\n    match (lo loc) with\n    | Ordering.nonatomic =>\n      if LocSet.mem loc LS_W then\n        loop_invB BB' RS_W LS_W max_reg loop_invs lo\n      else\n        loop_invB BB' RS_W LS_W (Pos.succ max_reg) ((LINV_LOC max_reg loc) :: loop_invs) lo\n    | Ordering.atomic =>\n      loop_invB BB' RS_W LS_W max_reg loop_invs lo\n    end\n  | _ ## BB' =>\n    loop_invB BB' RS_W LS_W max_reg loop_invs lo\n  | _ => (loop_invs, max_reg)\n  end.\n\nFixpoint loop_invBS (BS: list BBlock.t) (RS_W: RegSet.t) (LS_W: LocSet.t)\n         (max_reg: Reg.t) (loop_invs: list LOOP_INV) (lo: Ordering.LocOrdMap) :=\n  match BS with\n  | BB :: BS' =>\n    match loop_invB BB RS_W LS_W max_reg loop_invs lo with\n    | (loop_invs', max_reg') =>\n      loop_invBS BS' RS_W LS_W max_reg' loop_invs' lo\n    end\n  | nil => (loop_invs, max_reg)\n  end.\n\n(** [loop_invC] returns the loop invariants in the code heap. *)\nDefinition RS_W_instr (c: Inst.t) :=\n  match c with\n  | Inst.skip => RegSet.empty\n  | Inst.assign reg rhs => RegSet.singleton reg\n  | Inst.load reg loc _ => RegSet.singleton reg\n  | Inst.store loc rhs _ => RegSet.empty\n  | Inst.cas reg loc er ew _ _ => RegSet.singleton reg\n  | Inst.print e => RegSet.empty \n  | _ => RegSet.empty\n  end.\n\nDefinition LS_W_instr (c: Inst.t) :=\n  match c with\n  | Inst.skip => LocSet.empty\n  | Inst.assign reg rhs => LocSet.empty\n  | Inst.load reg loc _ => LocSet.empty\n  | Inst.store loc rhs _ => LocSet.singleton loc\n  | Inst.cas reg loc er ew _ _ => LocSet.empty\n  | Inst.print e => LocSet.empty \n  | _ => LocSet.empty\n  end.\n\nFixpoint RS_LS_W_evalB (BB: BBlock.t) :=\n  match BB with\n  | c ## BB' => match RS_LS_W_evalB BB' with\n               | (rsw, lsw) =>\n                 (RegSet.union (RS_W_instr c) rsw, LocSet.union (LS_W_instr c) lsw)\n               end\n  | _ => (RegSet.empty, LocSet.empty)\n  end.\n\nFixpoint RS_LS_W_eval (ls: list Language.fid) (cdhp: CodeHeap) :=\n  match ls with\n  | l :: ls' =>\n    match (PTree.get l cdhp) with\n    | Some BB =>\n      let (rsw1, lsw1) := RS_LS_W_evalB BB in\n      let (rsw2, lsw2) := RS_LS_W_eval ls' cdhp in \n      (RegSet.union rsw1 rsw2, LocSet.union lsw1 lsw2)\n    | None => RS_LS_W_eval ls' cdhp\n    end\n  | nil => (RegSet.empty, LocSet.empty)\n  end.\n\nFixpoint BS_in_loops (ls: list Language.fid) (cdhp: CodeHeap) :=\n  match ls with\n  | l :: ls' =>\n    match (PTree.get l cdhp) with\n    | Some BB => BB :: (BS_in_loops ls' cdhp)\n    | None => BS_in_loops ls' cdhp\n    end\n  | nil => nil\n  end. \n\nFixpoint loop_invC' (loops: list (positive * positive * IdentSet.t))\n         (max_reg0: Reg.t) (cdhp: CodeHeap) (lo: Ordering.LocOrdMap) :=\n  match loops with\n  | (l_entry, l_exit, iset) :: loops' =>\n    let ls := IdentSet.elements iset in\n    let (rsw, lsw) := RS_LS_W_eval ls cdhp in \n    let BS := BS_in_loops ls cdhp in\n    let (loop_invs, max_reg) :=\n        loop_invBS BS rsw lsw max_reg0 nil lo in\n    (l_entry, l_exit, loop_invs) :: loop_invC' loops' max_reg cdhp lo\n  | nil => nil\n  end.\n\nDefinition loop_invC (lo: Ordering.LocOrdMap) (func: Func) :=\n  let (cdhp, ep) := func in\n  let loops := det_loops cdhp ep in\n  let rs := regs_of_cdhp cdhp in\n  match (RegSet.max_elt rs) with\n  | None => loop_invC' loops 1%positive cdhp lo\n  | Some max_reg => loop_invC' loops (Pos.succ max_reg) cdhp lo\n  end.\n\nLemma loopinv_det_prop1:\n  forall loops max_reg cdhp lo l_entry l_exit loopinvs\n    (IN: In (l_entry, l_exit, loopinvs) (loop_invC' loops max_reg cdhp lo)),\n  exists ls, In (l_entry, l_exit, ls) loops.\nProof.\n  induction loops; ii; ss.\n  destruct a. destruct p.\n  destruct (RS_LS_W_eval (IdentSet.elements t) cdhp) eqn:Heqe1; ss.\n  destruct (loop_invBS (BS_in_loops (IdentSet.elements t) cdhp) t0 t1 max_reg nil lo) eqn:Heqe2; ss.\n  des1. inv IN; ss. eexists. left. eauto.\n  eapply IHloops in IN; eauto. des1.\n  exists ls. right; eauto.\nQed.\n\nLemma loopinv_det_prop2':\n    forall bk_edges cdhp ndoms l_entry l_exit ls\n      (IN: In (l_entry, l_exit, ls) (det_loops' cdhp ndoms bk_edges)),\n      <<ENTRY_IN: exists BB, PTree.get l_entry cdhp = Some BB>> /\\\n      <<EXIT_IN: exists BB, PTree.get l_exit cdhp = Some BB>>.\nProof.\n  induction bk_edges; ii; ss.\n  destruct a; ss.\n  destruct (cdhp ! p) eqn:GET_FID1; ss;\n    destruct (cdhp ! p0) eqn:GET_FID2; ss;\n      try solve [eapply IHbk_edges in IN; eauto].\n  des1. inv IN; ss. split; eauto.\n  eapply IHbk_edges in IN; eauto.\nQed.\n\nLemma loopinv_det_prop2\n          cdhp ep l_entry l_exit ls\n          (IN: In (l_entry, l_exit, ls) (det_loops cdhp ep)):\n  <<ENTRY_IN: exists BB, PTree.get l_entry cdhp = Some BB>> /\\\n  <<EXIT_IN: exists BB, PTree.get l_exit cdhp = Some BB>>.\nProof.\n  unfold det_loops in *.\n  destruct (NDomDS.fixpoint cdhp succ transf ep NDominators.top) eqn:Heqe; ss.\n  eapply loopinv_det_prop2'; eauto.\nQed.\n  \nLemma wf_loop_invC1\n      cdhp l_entry l_exit loopinvs lo ep\n      (LOOP_INV: In (l_entry, l_exit, loopinvs) (loop_invC lo (cdhp, ep))):\n  <<ENTRY_IN: exists BB, PTree.get l_entry cdhp = Some BB>> /\\\n  <<EXIT_IN: exists BB, PTree.get l_exit cdhp = Some BB>>.\nProof.\n  unfold loop_invC in *.\n  destruct (RegSet.max_elt (regs_of_cdhp cdhp)) eqn: MAX_REG.\n  - renames e to max_reg.\n    eapply loopinv_det_prop1 in LOOP_INV; eauto. des1.\n    eapply loopinv_det_prop2; eauto.\n  - eapply loopinv_det_prop1 in LOOP_INV; eauto. des1.\n    eapply loopinv_det_prop2; eauto.\nQed.\n\nLemma loop_invB_reg_prop:\n  forall BB rsw lsw max_reg loopinvs lo loopinvs' t\n    (LOOP_INVB: loop_invB BB rsw lsw max_reg loopinvs lo = (loopinvs', t)),\n    (max_reg <= t)%positive.\nProof.\n  induction BB; ii; ss; eauto;\n    try solve [inv LOOP_INVB; rewrite Pos.compare_refl in H; ss].\n  destruct c; ss; eauto; try solve [eapply IHBB in LOOP_INVB; eauto].\n  des_ifH LOOP_INVB; ss;\n    try solve [eapply IHBB in LOOP_INVB; eauto].\n  des_ifH LOOP_INVB; ss;\n    try solve [eapply IHBB in LOOP_INVB; eauto].\n  eapply IHBB in LOOP_INVB; eauto.\n  assert (SUCC_LT: (max_reg < Pos.succ max_reg)%positive).\n  {\n    eapply Pos.lt_succ_diag_r; eauto.\n  }\n  assert (SUCC_LT': (max_reg < t)%positive).\n  {\n    eapply Pos.lt_le_trans; eauto.\n  }\n  rewrite SUCC_LT' in H. ss.\n  pose proof (nonatomic_or_atomic or). des1.\n  - subst.\n    destruct (lo loc) eqn:LOC_AT_OR_NA; ss.\n    eapply IHBB in LOOP_INVB; eauto.\n    des_ifH LOOP_INVB; ss.\n    {\n      eapply IHBB in LOOP_INVB; eauto.\n    }\n    {\n      eapply IHBB in LOOP_INVB; eauto.\n      assert (SUCC_LT: (max_reg < Pos.succ max_reg)%positive).\n      {\n        eapply Pos.lt_succ_diag_r; eauto.\n      }\n      assert (SUCC_LT': (max_reg < t)%positive).\n      {\n        eapply Pos.lt_le_trans; eauto.\n      }\n      rewrite SUCC_LT' in H. ss.\n    }\n  - assert (match or with\n              | Ordering.plain =>\n                  match lo loc with\n                  | Ordering.atomic => loop_invB BB rsw lsw max_reg loopinvs lo\n                  | Ordering.nonatomic =>\n                      if LocSet.mem loc lsw\n                      then loop_invB BB rsw lsw max_reg loopinvs lo\n                      else loop_invB BB rsw lsw (Pos.succ max_reg) (LINV_LOC max_reg loc :: loopinvs) lo\n                  end\n              | _ => loop_invB BB rsw lsw max_reg loopinvs lo\n            end =\n            loop_invB BB rsw lsw max_reg loopinvs lo).\n    {\n      destruct or; ss; eauto.\n    }\n    rewrite H1 in LOOP_INVB. clear H1.\n    eapply IHBB in LOOP_INVB; eauto.\nQed.\n\nLemma loop_invB_reg_prop':\n  forall BB rsw lsw max_reg loopinvs loopinvs' lo max_reg' r\n    (LOOP_INVB: loop_invB BB rsw lsw max_reg loopinvs lo = (loopinvs', max_reg'))\n    (IN: (exists e, In (LINV_EXPR r e) loopinvs') \\/ (exists loc, In (LINV_LOC r loc) loopinvs')),\n    ((exists e, In (LINV_EXPR r e) loopinvs) \\/ (exists loc, In (LINV_LOC r loc) loopinvs)) \\/\n    (max_reg <= r)%positive.\nProof.\n  induction BB; ii; ss; eauto;\n    try solve [inv LOOP_INVB; eauto].\n  destruct c; ss; eauto.\n  - des_ifH LOOP_INVB; ss.\n    des_ifH LOOP_INVB; ss;\n      try solve [eapply IHBB in LOOP_INVB; eauto].\n    eapply IHBB in LOOP_INVB; eauto.\n    des1.\n    {\n      des1; ss. des1; ss. des1. inv LOOP_INVB. right.\n      eapply POrderedType.Positive_as_DT.le_refl; eauto.\n      left. eauto.\n      des1. des1. inv LOOP_INVB. eauto.\n    }\n    {\n      assert (SUCC_LT: (max_reg < Pos.succ max_reg)%positive).\n      {\n        eapply Pos.lt_succ_diag_r; eauto.\n      }\n      assert (SUCC_LT': (max_reg < r)%positive).\n      {\n        eapply Pos.lt_le_trans; eauto.\n      }\n      right. eapply POrderedType.Positive_as_DT.lt_le_incl; eauto.\n    }\n    eapply IHBB in LOOP_INVB; eauto.\n  - pose proof (nonatomic_or_atomic or). des1.\n    {\n      subst.\n      destruct (lo loc) eqn:LOC; ss.\n      eapply IHBB in LOOP_INVB; eauto.\n      des_ifH LOOP_INVB; ss; eauto.\n      eapply IHBB in LOOP_INVB; eauto.\n      des1.\n      des1.\n      des1; ss. des1. inv LOOP_INVB. eauto.\n      des1; ss. des1. inv LOOP_INVB.\n      right. eapply POrderedType.Positive_as_DT.le_refl; eauto.\n      eauto.\n      assert (SUCC_LT: (max_reg < Pos.succ max_reg)%positive).\n      {\n        eapply Pos.lt_succ_diag_r; eauto.\n      }\n      assert (SUCC_LT': (max_reg < r)%positive).\n      {\n        eapply Pos.lt_le_trans; eauto.\n      }\n      right. eapply POrderedType.Positive_as_DT.lt_le_incl; eauto.\n    }\n    {\n      assert (match or with\n              | Ordering.plain =>\n                  match lo loc with\n                  | Ordering.atomic => loop_invB BB rsw lsw max_reg loopinvs lo\n                  | Ordering.nonatomic =>\n                      if LocSet.mem loc lsw\n                      then loop_invB BB rsw lsw max_reg loopinvs lo\n                      else loop_invB BB rsw lsw (Pos.succ max_reg) (LINV_LOC max_reg loc :: loopinvs) lo\n                  end\n              | _ => loop_invB BB rsw lsw max_reg loopinvs lo\n              end = loop_invB BB rsw lsw max_reg loopinvs lo).\n      {\n        destruct or; ss.\n      }\n      rewrite H0 in LOOP_INVB; clear H0; ss.\n      eapply IHBB in LOOP_INVB; eauto.\n    }\nQed.\n  \nLemma loop_invBS_reg_prop:\n  forall BS rsw lsw max_reg max_reg' loopinvs0 loopinvs max_reg'' lo r\n    (LOOP_INVBS: loop_invBS BS rsw lsw max_reg' loopinvs0 lo = (loopinvs, max_reg''))\n    (REG: (exists e, In (LINV_EXPR r e) loopinvs) \\/ (exists loc, In (LINV_LOC r loc) loopinvs))\n    (GT: (max_reg < max_reg')%positive),\n    ((exists e, In (LINV_EXPR r e) loopinvs0) \\/ (exists loc, In (LINV_LOC r loc) loopinvs0)) \\/ \n    (max_reg' <= r)%positive.\nProof.\n  induction BS; ii; ss.\n  - inv LOOP_INVBS.\n    left. eauto.\n  - destruct (loop_invB a rsw lsw max_reg' loopinvs0 lo) eqn:Heqe; ss. \n    eapply IHBS in LOOP_INVBS; eauto.\n    2: {  \n      instantiate (1 := max_reg). renames a to BB.\n      eapply loop_invB_reg_prop in Heqe; eauto. \n      eapply Pos.lt_le_trans; eauto. }\n    renames a to BB. des1.\n    {\n      eapply loop_invB_reg_prop'; eauto.\n    }\n    {\n      eapply loop_invB_reg_prop in Heqe; eauto.\n      right. eapply Pos.le_trans; eauto.\n    }\nQed.\n\nLemma loop_invBS_reg_prop2:\n  forall BS rsw lsw max_reg max_reg' loopinvs0 loopinvs lo\n    (LOOP_INVBS: loop_invBS BS rsw lsw max_reg loopinvs0 lo = (loopinvs, max_reg')),\n    (max_reg <= max_reg')%positive.\nProof.\n  induction BS; ii; ss; eauto.\n  - inv LOOP_INVBS. rewrite Pos.compare_refl in H; ss.\n  - destruct (loop_invB a rsw lsw max_reg loopinvs0 lo) eqn:Heqe; ss.\n    eapply IHBS in LOOP_INVBS; eauto.\n    eapply loop_invB_reg_prop in Heqe; eauto.\n    assert ((max_reg <= max_reg')%positive).\n    eapply Pos.le_trans; eauto. tryfalse.\nQed.\n    \nLemma wf_loop_invC2':\n  forall loops max_reg max_reg' l_entry l_exit loopinvs lo cdhp r\n    (MAX_REG: RegSet.max_elt (regs_of_cdhp cdhp) = Some max_reg)\n    (IN: In (l_entry, l_exit, loopinvs) (loop_invC' loops max_reg' cdhp lo))\n    (REG: (exists e, In (LINV_EXPR r e) loopinvs) \\/ (exists loc, In (LINV_LOC r loc) loopinvs))\n    (GT: (max_reg < max_reg')%positive),\n    ~ (RegSet.In r (regs_of_cdhp cdhp)).\nProof.\n  induction loops; ii; ss.\n  destruct a; ss. destruct p; ss.\n  destruct (RS_LS_W_eval (IdentSet.elements t) cdhp) eqn:Heqe1; ss.\n  destruct (loop_invBS (BS_in_loops (IdentSet.elements t) cdhp) t0 t1 max_reg' nil lo) eqn:Heqe2; ss.\n  destruct IN as [IN1 | IN2]; ss; eauto.\n  - inv IN1.\n    renames t0 to rsw, t1 to lsw.\n    eapply loop_invBS_reg_prop in Heqe2; eauto.\n    des1. simpl in Heqe2. des1; des1; ss.\n    eapply RegSet.max_elt_spec2 in MAX_REG.\n    2: { eapply H. }\n    contradiction MAX_REG.\n    assert ((max_reg < r)%positive).\n    {\n      eapply Pos.lt_le_trans; eauto.\n    }\n    eauto.\n  - renames t0 to rsw, t1 to lsw.\n    eapply IHloops in MAX_REG; eauto.\n    eapply loop_invBS_reg_prop2 in Heqe2; eauto.\n    eapply Pos.lt_le_trans; eauto.\nQed.\n    \nLemma wf_loop_invC2\n      cdhp l_entry l_exit loopinvs lo ep r\n      (LOOP_INV: In (l_entry, l_exit, loopinvs) (loop_invC lo (cdhp, ep)))\n      (REG: (exists e, In (LINV_EXPR r e) loopinvs) \\/ (exists loc, In (LINV_LOC r loc) loopinvs)):\n  <<NEW_REG: ~ (RegSet.In r (regs_of_cdhp cdhp))>>.\nProof.\n  unfold loop_invC in *.\n  destruct (RegSet.max_elt (regs_of_cdhp cdhp)) eqn:Heqe; ss.\n  - renames e to max_reg.\n    eapply wf_loop_invC2'; eauto.\n    eapply Pos.lt_succ_diag_r; eauto.\n  - eapply RegSet.max_elt_spec3 in Heqe.\n    unfold RegSet.Empty in *. specialize (Heqe r). eauto.\nQed.\n\nLemma loop_invB_loc_prop:\n  forall BB rsw lsw max_reg loopinvs0 lo loopinvs max_reg' r loc\n    (LOOP_INVB: loop_invB BB rsw lsw max_reg loopinvs0 lo = (loopinvs, max_reg'))\n    (IN: In (LINV_LOC r loc) loopinvs),\n    In (LINV_LOC r loc) loopinvs0 \\/ lo loc = Ordering.nonatomic.\nProof.\n  induction BB; ii; ss;\n    try solve [inv LOOP_INVB; eauto].\n  destruct c; ss; eauto.\n  - des_ifH LOOP_INVB; ss; eauto.\n    des_ifH LOOP_INVB; ss; eauto.\n    eapply IHBB in LOOP_INVB; eauto.\n    des1; eauto.\n    simpl in LOOP_INVB.\n    des1; eauto.\n    inv LOOP_INVB.\n  - pose proof (nonatomic_or_atomic or); ss.\n    des1; subst.\n    {\n      destruct (lo loc0) eqn:Heqe; ss; eauto.\n      des_ifH LOOP_INVB; ss; eauto.\n      eapply IHBB in LOOP_INVB; eauto.\n      des1; eauto.\n      simpl in LOOP_INVB. des1; eauto.\n      inv LOOP_INVB. eauto.\n    }\n    {\n      assert (match or with\n              | Ordering.plain =>\n                match lo loc0 with\n                | Ordering.atomic => loop_invB BB rsw lsw max_reg loopinvs0 lo\n                | Ordering.nonatomic =>\n                  if LocSet.mem loc0 lsw\n                  then loop_invB BB rsw lsw max_reg loopinvs0 lo\n                  else loop_invB BB rsw lsw (Pos.succ max_reg) (LINV_LOC max_reg loc0 :: loopinvs0) lo\n                end\n              | _ => loop_invB BB rsw lsw max_reg loopinvs0 lo\n              end =\n              loop_invB BB rsw lsw max_reg loopinvs0 lo).\n      {\n        destruct or; ss; eauto.\n      }\n      rewrite H0 in LOOP_INVB. clear H0.\n      eapply IHBB in LOOP_INVB; eauto.\n    }\nQed.\n\nLemma loop_invBS_loc_prop:\n  forall BS rsw lsw max_reg loopinvs0 lo loopinvs max_reg' r loc\n    (LOOP_INVBS: loop_invBS BS rsw lsw max_reg loopinvs0 lo = (loopinvs, max_reg'))\n    (LOC: In (LINV_LOC r loc) loopinvs),\n    In (LINV_LOC r loc) loopinvs0 \\/ lo loc = Ordering.nonatomic.\nProof.\n  induction BS; ii; ss.\n  - inv LOOP_INVBS. eauto.\n  - destruct (loop_invB a rsw lsw max_reg loopinvs0 lo) eqn:Heqe; ss.\n    eapply IHBS in LOOP_INVBS; eauto. des1; eauto.\n    eapply loop_invB_loc_prop in Heqe; eauto.\nQed.\n\nLemma wf_loop_invC3':\n  forall loops max_reg cdhp lo l_entry l_exit loopinvs r loc\n    (IN: In (l_entry, l_exit, loopinvs) (loop_invC' loops max_reg cdhp lo))\n    (LOC: In (LINV_LOC r loc) loopinvs),\n    lo loc = Ordering.nonatomic.\nProof.\n  induction loops; ii; ss; eauto.\n  destruct a; ss. destruct p; ss.\n  destruct (RS_LS_W_eval (IdentSet.elements t) cdhp) eqn:Heqe1; ss.\n  destruct (loop_invBS (BS_in_loops (IdentSet.elements t) cdhp) t0 t1 max_reg nil lo) eqn:Heqe2; ss.\n  des1.\n  {\n    inv IN.\n    eapply loop_invBS_loc_prop in Heqe2; eauto. ss.\n    des1; ss.\n  }\n  {\n    eapply IHloops in IN; eauto.\n  }\nQed.\n\nLemma wf_loop_invC3\n      cdhp l_entry l_exit loopinvs lo ep loc\n      (LOOP_INV: In (l_entry, l_exit, loopinvs) (loop_invC lo (cdhp, ep)))\n      (LOC: exists r, In (LINV_LOC r loc) loopinvs):\n  <<NA_LOC: lo loc = Ordering.nonatomic>>.\nProof.\n  des1. unfold loop_invC in *; ss.\n  destruct (RegSet.max_elt (regs_of_cdhp cdhp)) eqn:Heqe; ss.\n  - eapply wf_loop_invC3'; eauto.\n  - eapply wf_loop_invC3'; eauto.\nQed.\n\n(** ** Detecting Loop Invariant in Code Heap *)\nDefinition det_loop_invs (prog: Code) (lo: Ordering.LocOrdMap) :=\n  PTree.map (fun l (func: Func) =>\n               let (cdhp, ep) := func in\n               match (cdhp ! ep) with\n               | Some BB => loop_invC lo (cdhp, ep)\n               | None => nil\n               end\n            ) prog.\n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/rtl/optimizer/DetLoop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24851016961661665}}
{"text": "From iris.algebra Require Export cmra.\nFrom stdpp Require Export list.\nFrom iris.base_logic Require Import base_logic.\nFrom iris.algebra Require Import updates local_updates.\nSet Default Proof Using \"Type\".\n\nSection cofe.\nContext {A : ofeT}.\nImplicit Types l : list A.\n\nInstance list_dist : Dist (list A) := λ n, Forall2 (dist n).\n\nLemma list_dist_lookup n l1 l2 : l1 ≡{n}≡ l2 ↔ ∀ i, l1 !! i ≡{n}≡ l2 !! i.\nProof. setoid_rewrite dist_option_Forall2. apply Forall2_lookup. Qed.\n\nGlobal Instance cons_ne : NonExpansive2 (@cons A) := _.\nGlobal Instance app_ne : NonExpansive2 (@app A) := _.\nGlobal Instance length_ne n : Proper (dist n ==> (=)) (@length A) := _.\nGlobal Instance tail_ne : NonExpansive (@tail A) := _.\nGlobal Instance take_ne : NonExpansive (@take A n) := _.\nGlobal Instance drop_ne : NonExpansive (@drop A n) := _.\nGlobal Instance list_lookup_ne i :\n  NonExpansive (lookup (M:=list A) i).\nProof. intros ????. by apply dist_option_Forall2, Forall2_lookup. Qed.\nGlobal Instance list_alter_ne n f i :\n  Proper (dist n ==> dist n) f →\n  Proper (dist n ==> dist n) (alter (M:=list A) f i) := _.\nGlobal Instance list_insert_ne i :\n  NonExpansive2 (insert (M:=list A) i) := _.\nGlobal Instance list_inserts_ne i :\n  NonExpansive2 (@list_inserts A i) := _.\nGlobal Instance list_delete_ne i :\n  NonExpansive (delete (M:=list A) i) := _.\nGlobal Instance option_list_ne : NonExpansive (@option_list A).\nProof. intros ????; by apply Forall2_option_list, dist_option_Forall2. Qed.\nGlobal Instance list_filter_ne n P `{∀ x, Decision (P x)} :\n  Proper (dist n ==> iff) P →\n  Proper (dist n ==> dist n) (filter (B:=list A) P) := _.\nGlobal Instance replicate_ne :\n  NonExpansive (@replicate A n) := _.\nGlobal Instance reverse_ne : NonExpansive (@reverse A) := _.\nGlobal Instance last_ne : NonExpansive (@last A).\nProof. intros ????; by apply dist_option_Forall2, Forall2_last. Qed.\nGlobal Instance resize_ne n :\n  NonExpansive2 (@resize A n) := _.\n\nDefinition list_ofe_mixin : OfeMixin (list A).\nProof.\n  split.\n  - intros l k. rewrite equiv_Forall2 -Forall2_forall.\n    split; induction 1; constructor; intros; try apply equiv_dist; auto.\n  - apply _.\n  - rewrite /dist /list_dist. eauto using Forall2_impl, dist_S.\nQed.\nCanonical Structure listC := OfeT (list A) list_ofe_mixin.\n\nProgram Definition list_chain\n    (c : chain listC) (x : A) (k : nat) : chain A :=\n  {| chain_car n := default x (c n !! k) |}.\nNext Obligation. intros c x k n i ?. by rewrite /= (chain_cauchy c n i). Qed.\nDefinition list_compl `{Cofe A} : Compl listC := λ c,\n  match c 0 with\n  | [] => []\n  | x :: _ => compl ∘ list_chain c x <$> seq 0 (length (c 0))\n  end.\nGlobal Program Instance list_cofe `{Cofe A} : Cofe listC :=\n  {| compl := list_compl |}.\nNext Obligation.\n  intros ? n c; rewrite /compl /list_compl.\n  destruct (c 0) as [|x l] eqn:Hc0 at 1.\n  { by destruct (chain_cauchy c 0 n); auto with lia. }\n  rewrite -(λ H, length_ne _ _ _ (chain_cauchy c 0 n H)); last lia.\n  apply Forall2_lookup=> i. rewrite -dist_option_Forall2 list_lookup_fmap.\n  destruct (decide (i < length (c n))); last first.\n  { rewrite lookup_seq_ge ?lookup_ge_None_2; auto with lia. }\n  rewrite lookup_seq //= (conv_compl n (list_chain c _ _)) /=.\n  destruct (lookup_lt_is_Some_2 (c n) i) as [? Hcn]; first done.\n  by rewrite Hcn.\nQed.\n\nGlobal Instance list_ofe_discrete : OfeDiscrete A → OfeDiscrete listC.\nProof. induction 2; constructor; try apply (discrete _); auto. Qed.\n\nGlobal Instance nil_discrete : Discrete (@nil A).\nProof. inversion_clear 1; constructor. Qed.\nGlobal Instance cons_discrete x l : Discrete x → Discrete l → Discrete (x :: l).\nProof. intros ??; inversion_clear 1; constructor; by apply discrete. Qed.\nEnd cofe.\n\nArguments listC : clear implicits.\n\n(** Functor *)\nLemma list_fmap_ext_ne {A} {B : ofeT} (f g : A → B) (l : list A) n :\n  (∀ x, f x ≡{n}≡ g x) → f <$> l ≡{n}≡ g <$> l.\nProof. intros Hf. by apply Forall2_fmap, Forall_Forall2, Forall_true. Qed.\nInstance list_fmap_ne {A B : ofeT} (f : A → B) n:\n  Proper (dist n ==> dist n) f → Proper (dist n ==> dist n) (fmap (M:=list) f).\nProof. intros Hf l k ?; by eapply Forall2_fmap, Forall2_impl; eauto. Qed.\nDefinition listC_map {A B} (f : A -n> B) : listC A -n> listC B :=\n  CofeMor (fmap f : listC A → listC B).\nInstance listC_map_ne A B : NonExpansive (@listC_map A B).\nProof. intros n f g ? l. by apply list_fmap_ext_ne. Qed.\n\nProgram Definition listCF (F : cFunctor) : cFunctor := {|\n  cFunctor_car A B := listC (cFunctor_car F A B);\n  cFunctor_map A1 A2 B1 B2 fg := listC_map (cFunctor_map F fg)\n|}.\nNext Obligation.\n  by intros F A1 A2 B1 B2 n f g Hfg; apply listC_map_ne, cFunctor_ne.\nQed.\nNext Obligation.\n  intros F A B x. rewrite /= -{2}(list_fmap_id x).\n  apply list_fmap_equiv_ext=>y. apply cFunctor_id.\nQed.\nNext Obligation.\n  intros F A1 A2 A3 B1 B2 B3 f g f' g' x. rewrite /= -list_fmap_compose.\n  apply list_fmap_equiv_ext=>y; apply cFunctor_compose.\nQed.\n\nInstance listCF_contractive F :\n  cFunctorContractive F → cFunctorContractive (listCF F).\nProof.\n  by intros ? A1 A2 B1 B2 n f g Hfg; apply listC_map_ne, cFunctor_contractive.\nQed.\n\n(* CMRA *)\nSection cmra.\n  Context {A : ucmraT}.\n  Implicit Types l : list A.\n  Local Arguments op _ _ !_ !_ / : simpl nomatch.\n\n  Instance list_op : Op (list A) :=\n    fix go l1 l2 := let _ : Op _ := @go in\n    match l1, l2 with\n    | [], _ => l2\n    | _, [] => l1\n    | x :: l1, y :: l2 => x ⋅ y :: l1 ⋅ l2\n    end.\n  Instance list_pcore : PCore (list A) := λ l, Some (core <$> l).\n\n  Instance list_valid : Valid (list A) := Forall (λ x, ✓ x).\n  Instance list_validN : ValidN (list A) := λ n, Forall (λ x, ✓{n} x).\n\n  Lemma cons_valid l x : ✓ (x :: l) ↔ ✓ x ∧ ✓ l.\n  Proof. apply Forall_cons. Qed.\n  Lemma cons_validN n l x : ✓{n} (x :: l) ↔ ✓{n} x ∧ ✓{n} l.\n  Proof. apply Forall_cons. Qed.\n  Lemma app_valid l1 l2 : ✓ (l1 ++ l2) ↔ ✓ l1 ∧ ✓ l2.\n  Proof. apply Forall_app. Qed.\n  Lemma app_validN n l1 l2 : ✓{n} (l1 ++ l2) ↔ ✓{n} l1 ∧ ✓{n} l2.\n  Proof. apply Forall_app. Qed.\n\n  Lemma list_lookup_valid l : ✓ l ↔ ∀ i, ✓ (l !! i).\n  Proof.\n    rewrite {1}/valid /list_valid Forall_lookup; split.\n    - intros Hl i. by destruct (l !! i) as [x|] eqn:?; [apply (Hl i)|].\n    - intros Hl i x Hi. move: (Hl i); by rewrite Hi.\n  Qed.\n  Lemma list_lookup_validN n l : ✓{n} l ↔ ∀ i, ✓{n} (l !! i).\n  Proof.\n    rewrite {1}/validN /list_validN Forall_lookup; split.\n    - intros Hl i. by destruct (l !! i) as [x|] eqn:?; [apply (Hl i)|].\n    - intros Hl i x Hi. move: (Hl i); by rewrite Hi.\n  Qed.\n  Lemma list_lookup_op l1 l2 i : (l1 ⋅ l2) !! i = l1 !! i ⋅ l2 !! i.\n  Proof.\n    revert i l2. induction l1 as [|x l1]; intros [|i] [|y l2];\n      by rewrite /= ?left_id_L ?right_id_L.\n  Qed.\n  Lemma list_lookup_core l i : core l !! i = core (l !! i).\n  Proof.\n    rewrite /core /= list_lookup_fmap.\n    destruct (l !! i); by rewrite /= ?Some_core.\n  Qed.\n\n  Lemma list_lookup_included l1 l2 : l1 ≼ l2 ↔ ∀ i, l1 !! i ≼ l2 !! i.\n  Proof.\n    split.\n    { intros [l Hl] i. exists (l !! i). by rewrite Hl list_lookup_op. }\n    revert l1. induction l2 as [|y l2 IH]=>-[|x l1] Hl.\n    - by exists [].\n    - destruct (Hl 0) as [[z|] Hz]; inversion Hz.\n    - by exists (y :: l2).\n    - destruct (IH l1) as [l3 ?]; first (intros i; apply (Hl (S i))).\n      destruct (Hl 0) as [[z|] Hz]; inversion_clear Hz; simplify_eq/=.\n      + exists (z :: l3); by constructor.\n      + exists (core x :: l3); constructor; by rewrite ?cmra_core_r.\n  Qed.\n\n  Definition list_cmra_mixin : CmraMixin (list A).\n  Proof.\n    apply cmra_total_mixin.\n    - eauto.\n    - intros n l l1 l2; rewrite !list_dist_lookup=> Hl i.\n      by rewrite !list_lookup_op Hl.\n    - intros n l1 l2 Hl; by rewrite /core /= Hl.\n    - intros n l1 l2; rewrite !list_dist_lookup !list_lookup_validN=> Hl ? i.\n      by rewrite -Hl.\n    - intros l. rewrite list_lookup_valid. setoid_rewrite list_lookup_validN.\n      setoid_rewrite cmra_valid_validN. naive_solver.\n    - intros n x. rewrite !list_lookup_validN. auto using cmra_validN_S.\n    - intros l1 l2 l3; rewrite list_equiv_lookup=> i.\n      by rewrite !list_lookup_op assoc.\n    - intros l1 l2; rewrite list_equiv_lookup=> i.\n      by rewrite !list_lookup_op comm.\n    - intros l; rewrite list_equiv_lookup=> i.\n      by rewrite list_lookup_op list_lookup_core cmra_core_l.\n    - intros l; rewrite list_equiv_lookup=> i.\n      by rewrite !list_lookup_core cmra_core_idemp.\n    - intros l1 l2; rewrite !list_lookup_included=> Hl i.\n      rewrite !list_lookup_core. by apply cmra_core_mono.\n    - intros n l1 l2. rewrite !list_lookup_validN.\n      setoid_rewrite list_lookup_op. eauto using cmra_validN_op_l.\n    - intros n l.\n      induction l as [|x l IH]=> -[|y1 l1] [|y2 l2] Hl Heq;\n        (try by exfalso; inversion Heq).\n      + by exists [], [].\n      + exists [], (x :: l); inversion Heq; by repeat constructor.\n      + exists (x :: l), []; inversion Heq; by repeat constructor.\n      + destruct (IH l1 l2) as (l1'&l2'&?&?&?),\n          (cmra_extend n x y1 y2) as (y1'&y2'&?&?&?);\n          [by inversion_clear Heq; inversion_clear Hl..|].\n        exists (y1' :: l1'), (y2' :: l2'); repeat constructor; auto.\n  Qed.\n  Canonical Structure listR := CmraT (list A) list_cmra_mixin.\n\n  Global Instance list_unit : Unit (list A) := [].\n  Definition list_ucmra_mixin : UcmraMixin (list A).\n  Proof.\n    split.\n    - constructor.\n    - by intros l.\n    - by constructor.\n  Qed.\n  Canonical Structure listUR := UcmraT (list A) list_ucmra_mixin.\n\n  Global Instance list_cmra_discrete : CmraDiscrete A → CmraDiscrete listR.\n  Proof.\n    split; [apply _|]=> l; rewrite list_lookup_valid list_lookup_validN=> Hl i.\n    by apply cmra_discrete_valid.\n  Qed.\n\n  Global Instance list_core_id l : (∀ x : A, CoreId x) → CoreId l.\n  Proof.\n    intros ?; constructor; apply list_equiv_lookup=> i.\n    by rewrite list_lookup_core (core_id_core (l !! i)).\n  Qed.\n\n  (** Internalized properties *)\n  Lemma list_equivI {M} l1 l2 : l1 ≡ l2 ⊣⊢ (∀ i, l1 !! i ≡ l2 !! i : uPred M).\n  Proof. uPred.unseal; constructor=> n x ?. apply list_dist_lookup. Qed.\n  Lemma list_validI {M} l : ✓ l ⊣⊢ (∀ i, ✓ (l !! i) : uPred M).\n  Proof. uPred.unseal; constructor=> n x ?. apply list_lookup_validN. Qed.\nEnd cmra.\n\nArguments listR : clear implicits.\nArguments listUR : clear implicits.\n\nInstance list_singletonM {A : ucmraT} : SingletonM nat A (list A) := λ n x,\n  replicate n ε ++ [x].\n\nSection properties.\n  Context {A : ucmraT}.\n  Implicit Types l : list A.\n  Implicit Types x y z : A.\n  Local Arguments op _ _ !_ !_ / : simpl nomatch.\n  Local Arguments cmra_op _ !_ !_ / : simpl nomatch.\n  Local Arguments ucmra_op _ !_ !_ / : simpl nomatch.\n\n  Lemma list_lookup_opM l mk i : (l ⋅? mk) !! i = l !! i ⋅ (mk ≫= (!! i)).\n  Proof. destruct mk; by rewrite /= ?list_lookup_op ?right_id_L. Qed.\n\n  Global Instance list_op_nil_l : LeftId (=) (@nil A) op.\n  Proof. done. Qed.\n  Global Instance list_op_nil_r : RightId (=) (@nil A) op.\n  Proof. by intros []. Qed.\n\n  Lemma list_op_app l1 l2 l3 :\n    (l1 ++ l3) ⋅ l2 = (l1 ⋅ take (length l1) l2) ++ (l3 ⋅ drop (length l1) l2).\n  Proof.\n    revert l2 l3.\n    induction l1 as [|x1 l1]=> -[|x2 l2] [|x3 l3]; f_equal/=; auto.\n  Qed.\n  Lemma list_op_app_le l1 l2 l3 :\n    length l2 ≤ length l1 → (l1 ++ l3) ⋅ l2 = (l1 ⋅ l2) ++ l3.\n  Proof. intros ?. by rewrite list_op_app take_ge // drop_ge // right_id_L. Qed.\n\n  Lemma list_lookup_validN_Some n l i x : ✓{n} l → l !! i ≡{n}≡ Some x → ✓{n} x.\n  Proof. move=> /list_lookup_validN /(_ i)=> Hl Hi; move: Hl. by rewrite Hi. Qed.\n  Lemma list_lookup_valid_Some l i x : ✓ l → l !! i ≡ Some x → ✓ x.\n  Proof. move=> /list_lookup_valid /(_ i)=> Hl Hi; move: Hl. by rewrite Hi. Qed.\n\n  Lemma list_op_length l1 l2 : length (l1 ⋅ l2) = max (length l1) (length l2).\n  Proof. revert l2. induction l1; intros [|??]; f_equal/=; auto. Qed.\n\n  Lemma replicate_valid n (x : A) : ✓ x → ✓ replicate n x.\n  Proof. apply Forall_replicate. Qed.\n  Global Instance list_singletonM_ne i :\n    NonExpansive (@list_singletonM A i).\n  Proof. intros n l1 l2 ?. apply Forall2_app; by repeat constructor. Qed.\n  Global Instance list_singletonM_proper i :\n    Proper ((≡) ==> (≡)) (list_singletonM i) := ne_proper _.\n\n  Lemma elem_of_list_singletonM i z x : z ∈ ({[i := x]} : list A) → z = ε ∨ z = x.\n  Proof.\n    rewrite elem_of_app elem_of_list_singleton elem_of_replicate. naive_solver.\n  Qed.\n  Lemma list_lookup_singletonM i x : ({[ i := x ]} : list A) !! i = Some x.\n  Proof. induction i; by f_equal/=. Qed.\n  Lemma list_lookup_singletonM_ne i j x :\n    i ≠ j →\n    ({[ i := x ]} : list A) !! j = None ∨ ({[ i := x ]} : list A) !! j = Some ε.\n  Proof. revert j; induction i; intros [|j]; naive_solver auto with lia. Qed.\n  Lemma list_singletonM_validN n i x : ✓{n} ({[ i := x ]} : list A) ↔ ✓{n} x.\n  Proof.\n    rewrite list_lookup_validN. split.\n    { move=> /(_ i). by rewrite list_lookup_singletonM. }\n    intros Hx j; destruct (decide (i = j)); subst.\n    - by rewrite list_lookup_singletonM.\n    - destruct (list_lookup_singletonM_ne i j x) as [Hi|Hi]; first done;\n        rewrite Hi; by try apply (ucmra_unit_validN (A:=A)).\n  Qed.\n  Lemma list_singleton_valid  i x : ✓ ({[ i := x ]} : list A) ↔ ✓ x.\n  Proof.\n    rewrite !cmra_valid_validN. by setoid_rewrite list_singletonM_validN.\n  Qed.\n  Lemma list_singletonM_length i x : length {[ i := x ]} = S i.\n  Proof.\n    rewrite /singletonM /list_singletonM app_length replicate_length /=; lia.\n  Qed.\n\n  Lemma list_core_singletonM i (x : A) : core {[ i := x ]} ≡ {[ i := core x ]}.\n  Proof.\n    rewrite /singletonM /list_singletonM.\n    by rewrite {1}/core /= fmap_app fmap_replicate (core_id_core ∅).\n  Qed.\n  Lemma list_op_singletonM i (x y : A) :\n    {[ i := x ]} ⋅ {[ i := y ]} ≡ {[ i := x ⋅ y ]}.\n  Proof.\n    rewrite /singletonM /list_singletonM /=.\n    induction i; constructor; rewrite ?left_id; auto.\n  Qed.\n  Lemma list_alter_singletonM f i x :\n    alter f i ({[i := x]} : list A) = {[i := f x]}.\n  Proof.\n    rewrite /singletonM /list_singletonM /=. induction i; f_equal/=; auto.\n  Qed.\n  Global Instance list_singleton_core_id i (x : A) :\n    CoreId x → CoreId {[ i := x ]}.\n  Proof. by rewrite !core_id_total list_core_singletonM=> ->. Qed.\n\n  (* Update *)\n  Lemma list_singleton_updateP (P : A → Prop) (Q : list A → Prop) x :\n    x ~~>: P → (∀ y, P y → Q [y]) → [x] ~~>: Q.\n  Proof.\n    rewrite !cmra_total_updateP=> Hup HQ n lf /list_lookup_validN Hv.\n    destruct (Hup n (default ε (lf !! 0))) as (y&?&Hv').\n    { move: (Hv 0). by destruct lf; rewrite /= ?right_id. }\n    exists [y]; split; first by auto.\n    apply list_lookup_validN=> i.\n    move: (Hv i) Hv'. by destruct i, lf; rewrite /= ?right_id.\n  Qed.\n  Lemma list_singleton_updateP' (P : A → Prop) x :\n    x ~~>: P → [x] ~~>: λ k, ∃ y, k = [y] ∧ P y.\n  Proof. eauto using list_singleton_updateP. Qed.\n  Lemma list_singleton_update x y : x ~~> y → [x] ~~> [y].\n  Proof.\n    rewrite !cmra_update_updateP; eauto using list_singleton_updateP with subst.\n  Qed.\n\n  Lemma app_updateP (P1 P2 Q : list A → Prop) l1 l2 :\n    l1 ~~>: P1 → l2 ~~>: P2 →\n    (∀ k1 k2, P1 k1 → P2 k2 → length l1 = length k1 ∧ Q (k1 ++ k2)) →\n    l1 ++ l2 ~~>: Q.\n  Proof.\n    rewrite !cmra_total_updateP=> Hup1 Hup2 HQ n lf.\n    rewrite list_op_app app_validN=> -[??].\n    destruct (Hup1 n (take (length l1) lf)) as (k1&?&?); auto.\n    destruct (Hup2 n (drop (length l1) lf)) as (k2&?&?); auto.\n    exists (k1 ++ k2). rewrite list_op_app app_validN.\n    by destruct (HQ k1 k2) as [<- ?].\n  Qed.\n  Lemma app_update l1 l2 k1 k2 :\n    length l1 = length k1 →\n    l1 ~~> k1 → l2 ~~> k2 → l1 ++ l2 ~~> k1 ++ k2.\n  Proof. rewrite !cmra_update_updateP; eauto using app_updateP with subst. Qed.\n\n  Lemma cons_updateP (P1 : A → Prop) (P2 Q : list A → Prop) x l :\n    x ~~>: P1 → l ~~>: P2 → (∀ y k, P1 y → P2 k → Q (y :: k)) → x :: l ~~>: Q.\n  Proof.\n    intros. eapply (app_updateP _ _ _ [x]);\n      naive_solver eauto using list_singleton_updateP'.\n  Qed.\n  Lemma cons_updateP' (P1 : A → Prop) (P2 : list A → Prop) x l :\n    x ~~>: P1 → l ~~>: P2 → x :: l ~~>: λ k, ∃ y k', k = y :: k' ∧ P1 y ∧ P2 k'.\n  Proof. eauto 10 using cons_updateP. Qed.\n  Lemma cons_update x y l k : x ~~> y → l ~~> k → x :: l ~~> y :: k.\n  Proof. rewrite !cmra_update_updateP; eauto using cons_updateP with subst. Qed.\n\n  Lemma list_middle_updateP (P : A → Prop) (Q : list A → Prop) l1 x l2 :\n    x ~~>: P → (∀ y, P y → Q (l1 ++ y :: l2)) → l1 ++ x :: l2 ~~>: Q.\n  Proof.\n    intros. eapply app_updateP.\n    - by apply cmra_update_updateP.\n    - by eapply cons_updateP', cmra_update_updateP.\n    - naive_solver.\n  Qed.\n  Lemma list_middle_update l1 l2 x y : x ~~> y → l1 ++ x :: l2 ~~> l1 ++ y :: l2.\n  Proof.\n    rewrite !cmra_update_updateP=> ?; eauto using list_middle_updateP with subst.\n  Qed.\n\n(* FIXME\n  Lemma list_middle_local_update l1 l2 x y ml :\n    x ~l~> y @ ml ≫= (!! length l1) →\n    l1 ++ x :: l2 ~l~> l1 ++ y :: l2 @ ml.\n  Proof.\n    intros [Hxy Hxy']; split.\n    - intros n; rewrite !list_lookup_validN=> Hl i; move: (Hl i).\n      destruct (lt_eq_lt_dec i (length l1)) as [[?|?]|?]; subst.\n      + by rewrite !list_lookup_opM !lookup_app_l.\n      + rewrite !list_lookup_opM !list_lookup_middle // !Some_op_opM; apply (Hxy n).\n      + rewrite !(cons_middle _ l1 l2) !assoc.\n        rewrite !list_lookup_opM !lookup_app_r !app_length //=; lia.\n    - intros n mk; rewrite !list_lookup_validN !list_dist_lookup => Hl Hl' i.\n      move: (Hl i) (Hl' i).\n      destruct (lt_eq_lt_dec i (length l1)) as [[?|?]|?]; subst.\n      + by rewrite !list_lookup_opM !lookup_app_l.\n      + rewrite !list_lookup_opM !list_lookup_middle // !Some_op_opM !inj_iff.\n        apply (Hxy' n).\n      + rewrite !(cons_middle _ l1 l2) !assoc.\n        rewrite !list_lookup_opM !lookup_app_r !app_length //=; lia.\n  Qed.\n  Lemma list_singleton_local_update i x y ml :\n    x ~l~> y @ ml ≫= (!! i) → {[ i := x ]} ~l~> {[ i := y ]} @ ml.\n  Proof. intros; apply list_middle_local_update. by rewrite replicate_length. Qed.\n*)\nEnd properties.\n\n(** Functor *)\nInstance list_fmap_cmra_morphism {A B : ucmraT} (f : A → B)\n  `{!CmraMorphism f} : CmraMorphism (fmap f : list A → list B).\nProof.\n  split; try apply _.\n  - intros n l. rewrite !list_lookup_validN=> Hl i. rewrite list_lookup_fmap.\n    by apply (cmra_morphism_validN (fmap f : option A → option B)).\n  - intros l. apply Some_proper. rewrite -!list_fmap_compose.\n    apply list_fmap_equiv_ext, cmra_morphism_core, _.\n  - intros l1 l2. apply list_equiv_lookup=>i.\n    by rewrite list_lookup_op !list_lookup_fmap list_lookup_op cmra_morphism_op.\nQed.\n\nProgram Definition listURF (F : urFunctor) : urFunctor := {|\n  urFunctor_car A B := listUR (urFunctor_car F A B);\n  urFunctor_map A1 A2 B1 B2 fg := listC_map (urFunctor_map F fg)\n|}.\nNext Obligation.\n  by intros F ???? n f g Hfg; apply listC_map_ne, urFunctor_ne.\nQed.\nNext Obligation.\n  intros F A B x. rewrite /= -{2}(list_fmap_id x).\n  apply list_fmap_equiv_ext=>y. apply urFunctor_id.\nQed.\nNext Obligation.\n  intros F A1 A2 A3 B1 B2 B3 f g f' g' x. rewrite /= -list_fmap_compose.\n  apply list_fmap_equiv_ext=>y; apply urFunctor_compose.\nQed.\n\nInstance listURF_contractive F :\n  urFunctorContractive F → urFunctorContractive (listURF F).\nProof.\n  by intros ? A1 A2 B1 B2 n f g Hfg; apply listC_map_ne, urFunctor_contractive.\nQed.\n", "meta": {"author": "izgzhen", "repo": "iris-coq", "sha": "4a1eb8a3d20789af6265b9011939be8274da042c", "save_path": "github-repos/coq/izgzhen-iris-coq", "path": "github-repos/coq/izgzhen-iris-coq/iris-coq-4a1eb8a3d20789af6265b9011939be8274da042c/theories/algebra/list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2484803085048153}}
{"text": "(** * Theorems for [ITree.Basics.Function] *)\n\n(* begin hide *)\nFrom Coq Require Import\n     Morphisms.\n\nFrom ITree Require Import\n     Basics.Basics\n     Basics.Category\n     Basics.Function.\n\nImport CatNotations.\nLocal Open Scope cat_scope.\n(* end hide *)\n\n#[global]\n Instance subrelation_eeq_eqeq {A B} :\n  @subrelation (A -> B) eq2 (@eq A ==> @eq B)%signature.\nProof. congruence. Qed.\n\n#[global]\n Instance Equivalence_eeq {A B} : @Equivalence (Fun A B) eq2.\nProof. constructor; congruence. Qed.\n\n#[global]\n Instance Proper_cat {A B C : Type} :\n  @Proper (Fun A B -> Fun B C -> Fun A C) (eq2 ==> eq2 ==> eq2) cat.\nProof. cbv; congruence. Qed.\n\n#[global]\n Instance cat_Fun_CatIdL : CatIdL Fun.\nProof. red; reflexivity. Qed.\n\n#[global]\n Instance cat_Fun_CatIdR : CatIdR Fun.\nProof. red; reflexivity. Qed.\n\n#[global]\n Instance cat_Fun_assoc : CatAssoc Fun.\nProof. red; reflexivity. Qed.\n\n#[global]\n Instance InitialObject_void : InitialObject Fun void :=\n  fun _ _ v => match v : void with end.\n\n#[global]\n Instance eeq_case_sum {A B C} :\n  @Proper (Fun A C -> Fun B C -> Fun (A + B) C)\n          (eq2 ==> eq2 ==> eq2) case_.\nProof. cbv; intros; subst; destruct _; auto. Qed.\n\n#[global]\n Instance Category_Fun : Category Fun.\nProof.\n  constructor; typeclasses eauto.\nQed.\n\n#[global]\n Instance Coproduct_Fun : Coproduct Fun sum.\nProof.\n  constructor.\n  - intros a b c f g.\n    cbv; reflexivity.\n  - intros a b c f g.\n    cbv; reflexivity.\n  - intros a b c f g fg Hf Hg [x | y]; cbv in *; auto.\n  - typeclasses eauto.\nQed.\n", "meta": {"author": "euisuny", "repo": "icfp22-layered-monadic-interpreters", "sha": "c3998f90613d1213585aaddf265fd463b77e4f8a", "save_path": "github-repos/coq/euisuny-icfp22-layered-monadic-interpreters", "path": "github-repos/coq/euisuny-icfp22-layered-monadic-interpreters/icfp22-layered-monadic-interpreters-c3998f90613d1213585aaddf265fd463b77e4f8a/src/theories/Basics/FunctionFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24840810015529005}}
{"text": "Require Import VST.veric.rmaps.\nRequire Import VST.concurrency.conclib.\nRequire Import VST.progs.conc_queue.\nRequire Import SetoidList.\nRequire Import VST.floyd.library.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nRequire Export VST.floyd.Funspec_old_Notation.\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition tqueue := Tstruct _queue noattr.\nDefinition tqueue_t := Tstruct _queue_t noattr.\n\nDefinition MAX := 10.\n\n(* Ghost histories in the style of\n   History-based Verification of Functional Behaviour of Concurrent Programs,\n   Blom, Huisman, and Zharieva-Stojanovski (VerCors)\n   Twente tech report, 2015 *)\n\nInductive hist_el {A} := QAdd (p : val) (v : A) | QRem (p : val) (v : A).\nNotation hist A := (list (@hist_el A)).\nFixpoint consistent {A} (h : hist A) a b :=\n  match h with\n  | [] => a = b\n  | QAdd p v :: h' => consistent h' (a ++ [(p, v)]) b\n  | QRem p v :: h' => match a with [] => False | v' :: q' => v' = (p, v) /\\ consistent h' q' b end\n  end.\nNotation feasible h := (exists b, consistent h [] b).\n\nParameter ghost : forall (sh : share) {t} (f : share * hist t) (p : val), mpred.\n(*Parameter ghost_factory : mpred.\n\nAxiom ghost_alloc : forall Espec D P Q R C P',\n  semax(Espec := Espec) D (PROPx P (LOCALx Q (SEPx (ghost_factory :: R)))) C P' ->\n  semax D (PROPx P (LOCALx Q (SEPx R))) C P'.\nAxiom new_ghost : forall Espec D P Q R C P' t v,\n  semax(Espec := Espec) D (PROPx P (LOCALx Q (SEPx (ghost_factory ::\n    (EX p : val, ghost Tsh t v p) :: R)))) C P' ->\n  semax D (PROPx P (LOCALx Q (SEPx (ghost_factory :: R)))) C P'.\nAxiom alloc_conflict : ghost_factory * ghost_factory |-- FF.*)\n\n(* In effect, we want two different ways of splitting/combining history shares.\n   One combines the histories as well; the other guarantees injectivity on histories. *)\n\n(* This is definitely unsound, since we can repeat it. *)\nAxiom new_ghost : forall {CS : compspecs} {Espec : OracleKind} D P Q R C P' t' t v p,\n  semax D (PROPx P (LOCALx Q (SEPx (ghost Tsh (Tsh, ([] : hist t')) p :: data_at Tsh t v p :: R)))) C P' ->\n  semax D (PROPx P (LOCALx Q (SEPx (data_at Tsh t v p :: R)))) C P'.\n\nInductive list_incl {A} : list A -> list A -> Prop :=\n| incl_nil l : list_incl [] l\n| incl_skip l1 a l2 (Hincl : list_incl l1 l2) : list_incl l1 (a :: l2)\n| incl_cons a l1 l2 (Hincl : list_incl l1 l2) : list_incl (a :: l1) (a :: l2).\nHint Constructors list_incl.\n\nInductive interleave {A} : list (list A) -> list A -> Prop :=\n| interleave_nil ls (Hnil : Forall (fun l => l = []) ls) : interleave ls []\n| interleave_cons ls i a l l' (Hcons : Znth i ls [] = a :: l) (Hrest : interleave (upd_Znth i ls l) l') :\n    interleave ls (a :: l').\n\nAxiom ghost_share_join : forall sh1 sh2 sh t (h1 h2 : hist t) p, sepalg.join sh1 sh2 Tsh -> list_incl h1 h2 ->\n  ghost sh1 (sh, h1) p * ghost sh2 (Tsh, h2) p = ghost Tsh (Tsh, h2) p.\nAxiom hist_share_join : forall sh sh1 sh2 sh' t (h1 h2 : hist t) p, sepalg.join sh1 sh2 sh' ->\n  ghost sh (sh1, h1) p * ghost sh (sh2, h2) p = EX h' : hist t, !!(interleave [h1; h2] h') && ghost sh (sh', h') p.\nAxiom hist_add : forall {CS : compspecs} {Espec : OracleKind} D P Q R C P' t (h : hist t) e p,\n  feasible (h ++ [e]) ->\n  semax D (PROPx P (LOCALx Q (SEPx (ghost Tsh (Tsh, h ++ [e]) p :: R)))) C P' ->\n  semax D (PROPx P (LOCALx Q (SEPx (ghost Tsh (Tsh, h) p :: R)))) C P'.\nAxiom ghost_inj : forall sh1 sh2 sh t (h1 h2 : hist t) p, ghost sh1 (sh, h1) p * ghost sh2 (Tsh, h2) p\n  |-- !!(list_incl h1 h2).\nAxiom ghost_inj_Tsh : forall sh1 sh2 t (h1 h2 : hist t) p, ghost sh1 (Tsh, h1) p * ghost sh2 (Tsh, h2) p\n  |-- !!(h1 = h2).\n(* Should this be an axiom? *)\nAxiom ghost_feasible : forall sh t (h : hist t) p, ghost sh (Tsh, h) p |-- !!(feasible h).\n\nAxiom ghost_conflict : forall sh1 sh2 t (v1 v2 : share * hist t) p,\n  ghost sh1 v1 p * ghost sh2 v2 p |-- !!sepalg.joins sh1 sh2.\n\n(* We would prefer to let the queue hold arbitrarily complex data, not necessarily associated with a C type.\n   For now, the mpred embedding can't handle type application, so we have to default to data_at instead of\n   taking a general predicate for the queue, and that means the data is always of a C type. *)\nDefinition q_lock_pred' (t : type) P p (vals : list (val * reptype t)) head (addc remc : val) lock gsh h :=\n  !!(Zlength vals <= MAX /\\ 0 <= head < MAX /\\ consistent h [] vals) &&\n  (data_at Tsh tqueue (rotate (complete MAX (map fst vals)) head MAX, (vint (Zlength vals),\n                      (vint head, (vint ((head + Zlength vals) mod MAX), (addc, remc))))) p *\n   cond_var Tsh addc * cond_var Tsh remc * malloc_token Tsh (sizeof tqueue_t) p *\n   malloc_token Tsh (sizeof tcond) addc * malloc_token Tsh (sizeof tcond) remc *\n   malloc_token Tsh (sizeof tlock) lock * ghost gsh (Tsh, h) p *\n   fold_right sepcon emp (map (fun x => let '(p, v) := x in\n     !!(P v) && (data_at Tsh t v p * malloc_token Tsh (sizeof t) p)) vals)).\n\nDefinition q_lock_pred A P p lock gsh := EX vals : list (val * reptype A), EX head : Z,\n  EX addc : val, EX remc : val, EX h : hist _, q_lock_pred' A P p vals head addc remc lock gsh h.\n\nDefinition lqueue lsh t P p lock gsh1 gsh2 (h : hist (reptype t)) :=\n  !!(sepalg.join gsh1 gsh2 Tsh /\\ field_compatible tqueue_t [] p) &&\n  (field_at lsh tqueue_t [StructField _lock] lock p *\n   lock_inv lsh lock (q_lock_pred t P p lock gsh2) * ghost gsh1 (lsh, h) p).\n\nLemma lqueue_feasible : forall A P p lock gsh1 gsh2 (h : hist (reptype A)),\n  lqueue Tsh A P p lock gsh1 gsh2 h = !!(feasible h) && lqueue Tsh A P p lock gsh1 gsh2 h.\nProof.\n  intros; rewrite andp_comm; apply add_andp.\n  unfold lqueue; Intros.\n  setoid_rewrite add_andp with (P0 := ghost gsh1 (Tsh, h) p); [|apply ghost_feasible].\n  Intros; apply prop_right; auto.\nQed.\n\n(*Definition PredType := ArrowType (ConstType val) (ArrowType (DependentType 0) Mpred).\nDefinition q_new_type := ProdType (ConstType (share * share)) PredType.\n\nProgram Definition q_new_spec' := mk_funspec (nil, tptr tqueue_t) cc_default q_new_type\n  (fun (ts: list Type) (x: share * share * (val -> nth 0 ts unit -> mpred)) => let '(gsh1, gsh2, P) := x in\n    PROP (sepalg.join gsh1 gsh2 Tsh)\n    LOCAL ()\n    SEP ())\n  (fun (ts: list Type) (x: share * share * (val -> nth 0 ts unit -> mpred)) => let '(gsh1, gsh2, P) := x in\n    EX newq : val, EX lock : val,\n    PROP ()\n    LOCAL (temp ret_temp newq)\n    SEP (lqueue Tsh (nth 0 ts unit) P newq lock gsh1 gsh2 [])) _ _.\nNext Obligation.\nProof.\n  replace _ with (fun (ts : list Type) (x : share * share * (val -> nth 0 ts unit -> mpred)) rho =>\n    PROP (let '(gsh1, gsh2, P) := x in sepalg.join gsh1 gsh2 Tsh) LOCAL () SEP () rho).\n  apply (PROP_LOCAL_SEP_super_non_expansive q_new_type [fun _ => _] [] []); repeat constructor.\n  hnf; intros.\n  destruct x as ((?, ?), ?); auto.\n  { repeat extensionality.\n    destruct x0 as ((?, ?), ?); auto. }\nQed.\nNext Obligation.\nProof.\n\n(* How do we prove super_non_expansive of an existential? Use exp_approx from veric/seplog / veric/Clight_seplog. *)\nAdmitted.*)\n\nDefinition surely_malloc_spec' :=\n   WITH n:Z\n   PRE [ _n OF tuint ]\n       PROP (0 <= n <= Int.max_unsigned)\n       LOCAL (temp _n (Vint (Int.repr n)))\n       SEP ()\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (malloc_token Tsh n p * memory_block Tsh n p).\nDefinition surely_malloc_spec prog := DECLARE (ext_link_prog prog \"surely_malloc\") surely_malloc_spec'.\n\nDefinition q_new_spec' :=\n  WITH Q : {t : type & reptype t -> Prop}, gsh1 : share, gsh2 : share\n  PRE [ ]\n   PROP (sepalg.join gsh1 gsh2 Tsh)\n   LOCAL ()\n   SEP ()\n  POST [ tptr tqueue_t ]\n   let (t, P) := Q in\n   EX newq : val, EX lock : val,\n   PROP () LOCAL (temp ret_temp newq)\n   SEP (lqueue Tsh t P newq lock gsh1 gsh2 []).\nDefinition q_new_spec prog := DECLARE (ext_link_prog prog \"q_new\") q_new_spec'.\n\nNotation q_new_args t P := (existT (fun t => @reptype CompSpecs t -> Prop) t P).\n\nDefinition q_del_spec' :=\n  WITH Q : {t : type & ((reptype t -> Prop) * hist (reptype t))%type}, p : val, lock : val, gsh1 : share, gsh2 : share\n  PRE [ _tgt OF (tptr tqueue_t) ]\n   let (t, R) := Q in let (P, h) := R in\n   PROP (consistent h [] [])\n   LOCAL (temp _tgt p)\n   SEP (lqueue Tsh t P p lock gsh1 gsh2 h)\n  POST [ tvoid ]\n   PROP ()\n   LOCAL ()\n   SEP ().\nDefinition q_del_spec prog := DECLARE (ext_link_prog prog \"q_del\") q_del_spec'.\n\nNotation q_rem_args t P h := (existT (fun t => ((@reptype CompSpecs t -> Prop) * hist (@reptype CompSpecs t))%type) t (P, h)).\n\nDefinition q_add_spec' :=\n  WITH sh : share, Q : {t : type & ((reptype t -> Prop) * hist (reptype t) * reptype t)%type}, p : val, lock : val,\n       e : val, gsh1 : share, gsh2 : share\n  PRE [ _tgt OF (tptr tqueue_t), _r OF (tptr tvoid) ]\n   let (t, R) := Q in let (S, v) := R in let (P, h) := S in\n   PROP (readable_share sh; P v)\n   LOCAL (temp _tgt p; temp _r e)\n   SEP (lqueue sh t P p lock gsh1 gsh2 h; data_at Tsh t v e; malloc_token Tsh (sizeof t) e)\n  POST [ tvoid ]\n   let (t, R) := Q in let (S, v) := R in let (P, h) := S in\n   PROP ()\n   LOCAL ()\n   SEP (lqueue sh t P p lock gsh1 gsh2 (h ++ [QAdd e v])).\nDefinition q_add_spec prog := DECLARE (ext_link_prog prog \"q_add\") q_add_spec'.\n\nNotation q_add_args t P h v := (existT (fun t =>\n  ((@reptype CompSpecs t -> Prop) * hist (@reptype CompSpecs t) * @reptype CompSpecs t)%type) t (P, h, v)).\n\nDefinition q_remove_spec' :=\n  WITH sh : share, Q : {t : type & ((reptype t -> Prop) * hist (reptype t))%type}, p : val, lock : val, gsh1 : share, gsh2 : share\n  PRE [ _tgt OF (tptr tqueue_t) ]\n   let (t, R) := Q in let (P, h) := R in\n   PROP (readable_share sh)\n   LOCAL (temp _tgt p)\n   SEP (lqueue sh t P p lock gsh1 gsh2 h)\n  POST [ tptr tvoid ]\n   let (t, R) := Q in let (P, h) := R in\n   EX e : val, EX v : reptype t,\n   PROP (P v)\n   LOCAL (temp ret_temp e)\n   SEP (lqueue sh t P p lock gsh1 gsh2 (h ++ [QRem e v]); data_at Tsh t v e; malloc_token Tsh (sizeof t) e).\nDefinition q_remove_spec prog := DECLARE (ext_link_prog prog \"q_remove\") q_remove_spec'.\n\nDefinition q_tryremove_spec' :=\n  WITH sh : share, Q : {t : type & ((reptype t -> Prop) * hist (reptype t))%type}, p : val, lock : val, gsh1 : share, gsh2 : share\n  PRE [ _tgt OF (tptr tqueue_t) ]\n   let (t, R) := Q in let (P, h) := R in\n   PROP (readable_share sh)\n   LOCAL (temp _tgt p)\n   SEP (lqueue sh t P p lock gsh1 gsh2 h)\n  POST [ tptr tvoid ]\n   let (t, R) := Q in let (P, h) := R in\n   EX e : val,\n   PROP ()\n   LOCAL (temp ret_temp e)\n   SEP (if eq_dec e nullval then lqueue sh t P p lock gsh1 gsh2 h else\n        (EX v : reptype t, !!(P v) &&\n         (lqueue sh t P p lock gsh1 gsh2 (h ++ [QRem e v]) * data_at Tsh t v e * malloc_token Tsh (sizeof t) e))).\nDefinition q_tryremove_spec prog := DECLARE (ext_link_prog prog \"q_tryremove\") q_tryremove_spec'.\n\nLemma lock_precise : forall sh p lock (Hsh : readable_share sh),\n  precise (field_at sh tqueue_t [StructField _lock] lock p).\nProof.\n  intros.\n  unfold field_at, at_offset; apply precise_andp2.\n  rewrite data_at_rec_eq; simpl; auto.\nQed.\n\nLemma interleave_single : forall {A} (l l' : list A), interleave [l] l' = (l' = l).\nProof.\n  intros; apply prop_ext; split; intro; subst.\n  - remember [l] as l0; revert dependent l; induction H; intros; subst.\n    + inv Hnil; auto.\n    + exploit (Znth_inbounds i [l0] []).\n      { rewrite Hcons; discriminate. }\n      intro; assert (i = 0) by (rewrite Zlength_cons, Zlength_nil in *; lia).\n      subst; rewrite Znth_0_cons in Hcons; subst.\n      rewrite upd_Znth0, sublist_nil in IHinterleave; specialize (IHinterleave _ eq_refl); subst; auto.\n  - induction l; econstructor; auto.\n    + instantiate (2 := 0); rewrite Znth_0_cons; eauto.\n    + rewrite upd_Znth0, sublist_nil; auto.\nQed.\n\nLemma interleave_remove_nil : forall {A} ls (l' : list A),\n  interleave ([] :: ls) l' <-> interleave ls l'.\nProof.\n  split; intro.\n  - remember ([] :: ls) as l0; revert dependent ls; induction H; intros; subst.\n    + inv Hnil; constructor; auto.\n    + destruct (Z_le_dec i 0).\n      { destruct (eq_dec i 0); [subst; rewrite Znth_0_cons in Hcons | rewrite Znth_underflow in Hcons];\n          try discriminate; try lia. }\n      rewrite Znth_pos_cons in Hcons; [econstructor; eauto | lia].\n      apply IHinterleave.\n      setoid_rewrite upd_Znth_app2 with (l1 := [[]]); auto.\n      rewrite Zlength_cons, Zlength_nil.\n      destruct (Z_le_dec (i - 1) (Zlength ls0)); [lia | rewrite Znth_overflow in Hcons; [discriminate | lia]].\n  - induction H.\n    + constructor; auto.\n    + destruct (zlt i 0); [rewrite Znth_underflow in Hcons; [discriminate | auto]|].\n      econstructor.\n      * rewrite Znth_pos_cons, Z.add_simpl_r; eauto; lia.\n      * setoid_rewrite upd_Znth_app2 with (l1 := [[]]); rewrite Zlength_cons, Zlength_nil.\n        rewrite Z.add_simpl_r; auto.\n        { destruct (Z_le_dec i (Zlength ls)); [lia | rewrite Znth_overflow in Hcons; [discriminate | lia]]. }\nQed.\n\nCorollary interleave_remove_nils : forall {A} ls0 ls (l' : list A), Forall (fun l => l = []) ls0 ->\n  interleave (ls0 ++ ls) l' <-> interleave ls l'.\nProof.\n  induction ls0; [reflexivity | intros].\n  inv H; simpl; rewrite interleave_remove_nil; auto.\nQed.\n\nLemma interleave_trans : forall {A} ls1 ls2 (l' l'' : list A)\n  (Hl' : interleave ls1 l') (Hl'' : interleave (l' :: ls2) l''), interleave (ls1 ++ ls2) l''.\nProof.\n  intros until 1; revert ls2 l''; induction Hl'; intros.\n  - rewrite interleave_remove_nil in Hl''; rewrite interleave_remove_nils; auto.\n  - remember ((a :: l') :: ls2) as ls0; revert dependent ls2; revert dependent l'; revert dependent a;\n      induction Hl''; intros; subst.\n    { inv Hnil; discriminate. }\n    exploit (Znth_inbounds i ls []).\n    { rewrite Hcons0; discriminate. }\n    intro; destruct (eq_dec i0 0).\n    + subst; rewrite Znth_0_cons in Hcons; inv Hcons.\n      econstructor.\n      * rewrite app_Znth1; eauto; lia.\n      * rewrite upd_Znth_app1; auto.\n        rewrite upd_Znth0, sublist_1_cons, sublist_same in Hl''; auto.\n        rewrite Zlength_cons; lia.\n    + exploit (Znth_inbounds i0 ((a0 :: l'0) :: ls2) []).\n      { rewrite Hcons; discriminate. }\n      intro; rewrite Znth_pos_cons in Hcons; [|lia].\n      econstructor.\n      * rewrite app_Znth2, Z.add_simpl_r; eauto; lia.\n      * rewrite Zlength_cons in *; rewrite upd_Znth_app2, Z.add_simpl_r; [|lia].\n        eapply IHHl''; eauto.\n        rewrite upd_Znth_cons; auto; lia.\nQed.\n\nLemma lqueue_share_join : forall t P sh1 sh2 sh p lock gsh1 gsh2 h1 h2\n  (Hsh1 : readable_share sh1) (Hsh2 : readable_share sh2) (Hjoin : sepalg.join sh1 sh2 sh),\n  lqueue sh1 t P p lock gsh1 gsh2 h1 * lqueue sh2 t P p lock gsh1 gsh2 h2 =\n  EX h' : hist _, !!(interleave [h1; h2] h') && lqueue sh t P p lock gsh1 gsh2 h'.\nProof.\n  intros; unfold lqueue; normalize.\n  rewrite sepcon_comm, (sepcon_comm _ (ghost _ _ _)), <- !sepcon_assoc, (sepcon_comm _ (ghost _ _ _)).\n  erewrite hist_share_join; eauto.\n  rewrite !sepcon_assoc, (sepcon_comm _ (lock_inv sh2 _ _)), <- (sepcon_assoc (lock_inv _ _ _)).\n  erewrite lock_inv_share_join; eauto.\n  rewrite (sepcon_comm _ (field_at _ _ _ _ _)), <- (sepcon_assoc (field_at _ _ _ _ _)).\n  erewrite field_at_share_join; eauto.\n  normalize.\n  f_equal; extensionality.\n  normalize.\n  rewrite sepcon_assoc, sepcon_comm; f_equal; f_equal.\n  apply prop_ext; tauto.\nQed.\n\nCorollary lqueue_share_join_nil : forall t P sh1 sh2 sh p lock gsh1 gsh2\n  (Hsh1 : readable_share sh1) (Hsh2 : readable_share sh2) (Hjoin : sepalg.join sh1 sh2 sh),\n  lqueue sh t P p lock gsh1 gsh2 [] |--\n  lqueue sh1 t P p lock gsh1 gsh2 [] * lqueue sh2 t P p lock gsh1 gsh2 [].\nProof.\n  intros; erewrite lqueue_share_join; eauto.\n  Exists ([] : hist (reptype t)); entailer!; constructor; auto.\nQed.\n\nCorollary lqueue_shares_join : forall t P p lock sh1 sh2 sh shs h hs\n  (Hlen : length shs = length hs)\n  (Hsplit : forall i, 0 <= i < Zlength shs ->\n    let '(a, b) := Znth i shs (sh, sh) in\n    readable_share a /\\ readable_share b /\\ sepalg.join a b (fst (Znth (i + 1) shs (sh, sh)))),\n  lqueue (fst (Znth 0 shs (sh, sh))) t P p lock sh1 sh2 h *\n  fold_right sepcon emp (map (fun x => let '(sh, h) := x in lqueue sh t P p lock sh1 sh2 h)\n    (combine (map snd shs) hs)) |--\n  EX h' : hist _, !!(interleave (h :: hs) h') && lqueue sh t P p lock sh1 sh2 h'.\nProof.\n  induction shs; destruct hs; try discriminate; simpl; intros.\n  - Exists h; rewrite interleave_single; entailer!.\n  - rewrite Znth_0_cons; simpl.\n    rewrite Zlength_cons in Hsplit.\n    exploit (Hsplit 0).\n    { rewrite Zlength_correct; lia. }\n    rewrite !Znth_0_cons; destruct a; intros (? & ? & ?).\n    erewrite <- sepcon_assoc, lqueue_share_join; eauto.\n    simpl; rewrite Znth_pos_cons, Zminus_diag; [|lia].\n    Intros h'.\n    eapply derives_trans; [apply IHshs; auto|].\n    { intros; specialize (Hsplit (i + 1)).\n      rewrite !Znth_pos_cons, !Z.add_simpl_r in Hsplit; try lia.\n      apply Hsplit; lia. }\n    Intros h''.\n    Exists h''; entailer!.\n    eapply interleave_trans with (ls1 := [h; l]); eauto.\nQed.\n\nLemma all_ptrs : forall t P vals, fold_right sepcon emp (map (fun x => let '(p, v) := x in\n  !!(P v) && (data_at Tsh t v p * malloc_token Tsh (sizeof t) p)) vals) |--\n  !!(Forall isptr (map fst vals)).\nProof.\n  induction vals; simpl; intros; entailer.\n  destruct a.\n  rewrite data_at_isptr.\n  eapply derives_trans; [apply saturate_aux20 with (P' := isptr v)|].\n  { Intros; apply prop_right; auto. }\n  { apply IHvals; auto. }\n  normalize.\nQed.\n\nLemma vals_precise : forall r t P vals1 vals2 r1 r2\n  (Hvals : map fst vals1 = map fst vals2)\n  (Hvals1 : predicates_hered.app_pred(A := compcert_rmaps.R.rmap) (fold_right sepcon emp\n    (map (fun x => let '(p, v) := x in !!(P v) && (data_at Tsh t v p * malloc_token Tsh (sizeof t) p)) vals1)) r1)\n  (Hvals2 : predicates_hered.app_pred(A := compcert_rmaps.R.rmap) (fold_right sepcon emp\n    (map (fun x => let '(p, v) := x in !!(P v) && (data_at Tsh t v p * malloc_token Tsh (sizeof t) p)) vals2)) r2)\n  (Hr1 : sepalg.join_sub r1 r) (Hr2 : sepalg.join_sub r2 r), r1 = r2.\nProof.\n  induction vals1; simpl; intros; destruct vals2; inversion Hvals.\n  - apply sepalg.same_identity with (a := r); auto.\n    { destruct Hr1 as (? & H); specialize (Hvals1 _ _ H); subst; auto. }\n    { destruct Hr2 as (? & H); specialize (Hvals2 _ _ H); subst; auto. }\n  - destruct a, p; simpl in *; subst.\n    destruct Hvals1 as (? & r1b & ? & (? & r1a & ? & ? & Hh1 & Hm1) & ?),\n      Hvals2 as (? & r2b & ? & (? & r2a & ? & ? & Hh2 & Hm2) & ?).\n    exploit malloc_token_precise.\n    { apply Hm1. }\n    { apply Hm2. }\n    { join_sub. }\n    { join_sub. }\n    assert (r1a = r2a); [|intros; subst].\n    { apply data_at_data_at_ in Hh1; apply data_at_data_at_ in Hh2.\n      eapply data_at__precise with (sh := Tsh); auto; eauto; join_sub. }\n    assert (r1b = r2b); [|subst].\n    { eapply IHvals1; eauto; join_sub. }\n    join_inj.\nQed.\n\nAxiom ghost_precise : forall sh {t} p, precise (EX f : share * hist (reptype t), ghost sh f p).\n\nLemma tqueue_inj : forall r (buf1 buf2 : list val) len1 len2 head1 head2 tail1 tail2\n  (addc1 addc2 remc1 remc2 : val) p r1 r2\n  (Hp1 : predicates_hered.app_pred(A := compcert_rmaps.R.rmap)\n     (data_at Tsh tqueue (buf1, (vint len1, (vint head1, (vint tail1, (addc1, remc1))))) p) r1)\n  (Hp2 : predicates_hered.app_pred(A := compcert_rmaps.R.rmap)\n     (data_at Tsh tqueue (buf2, (vint len2, (vint head2, (vint tail2, (addc2, remc2))))) p) r2)\n  (Hr1 : sepalg.join_sub r1 r) (Hr2 : sepalg.join_sub r2 r)\n  (Hbuf1 : Forall (fun v => v <> Vundef) buf1) (Hl1 : Zlength buf1 = MAX)\n  (Hbuf2 : Forall (fun v => v <> Vundef) buf2) (Hl2 : Zlength buf2 = MAX)\n  (Haddc1 : addc1 <> Vundef) (Haddc2 : addc2 <> Vundef) (Hremc1 : remc1 <> Vundef) (Hremc2 : remc2 <> Vundef),\n  r1 = r2 /\\ buf1 = buf2 /\\ Int.repr len1 = Int.repr len2 /\\ Int.repr head1 = Int.repr head2 /\\\n  Int.repr tail1 = Int.repr tail2 /\\ addc1 = addc2 /\\ remc1 = remc2.\nProof.\n  intros.\n  unfold data_at in Hp1, Hp2; erewrite field_at_Tstruct in Hp1, Hp2; try reflexivity; try apply JMeq_refl.\n  simpl in Hp1, Hp2; unfold withspacer in Hp1, Hp2; simpl in Hp1, Hp2.\n  destruct Hp1 as (? & ? & ? & (? & Hb1) & ? & ? & ? & (? & Hlen1) & ? & ? & ? & (? & Hhead1) & ? & ? & ? &\n    (? & Htail1) & ? & ? & ? & (? & Hadd1) & ? & Hrem1).\n  destruct Hp2 as (? & ? & ? & (? & Hb2) & ? & ? & ? & (? & Hlen2) & ? & ? & ? & (? & Hhead2) & ? & ? & ? &\n    (? & Htail2) & ? & ? & ? & (? & Hadd2) & ? & Hrem2); unfold at_offset in *.\n  assert (readable_share Tsh) as Hread by auto.\n  exploit (mapsto_inj _ _ _ _ _ _ _ r Hread Hrem1 Hrem2); auto; try join_sub.\n  exploit (mapsto_inj _ _ _ _ _ _ _ r Hread Hadd1 Hadd2); auto; try join_sub.\n  exploit (mapsto_inj _ _ _ _ _ _ _ r Hread Htail1 Htail2); auto; try join_sub; try discriminate.\n  exploit (mapsto_inj _ _ _ _ _ _ _ r Hread Hhead1 Hhead2); auto; try join_sub; try discriminate.\n  exploit (mapsto_inj _ _ _ _ _ _ _ r Hread Hlen1 Hlen2); auto; try join_sub; try discriminate.\n  exploit (data_at_ptr_array_inj _ _ _ _ _ _ _ _ r Hread Hb1 Hb2); auto; try join_sub.\n  unfold repinject.\n  intros (? & ?) (? & ?) (? & ?) (? & ?) (? & ?) (? & ?); subst; join_inj.\n  repeat split; auto; congruence.\nQed.\n\nLemma q_inv_precise : forall t P p lock gsh2, precise (q_lock_pred t P p lock gsh2).\nProof.\n  unfold q_lock_pred, q_lock_pred'; intros ???????? H1 H2 Hw1 Hw2.\n  destruct H1 as (vals1 & head1 & addc1 & remc1 & h1 & (? & ? & ?) & ? & ? & ? & (? & ? & ? & (? & ? & ? &\n    (? & ? & ? & (? & ? & ? & (? & ? & ? & (? & ? & ? & (? & ? & ? & (Hq1 & Haddc1)) & Hremc1) & Htv1) & Hta1) &\n    Htr1) & Htl1) & Hghost1) & Hvals1),\n  H2 as (vals2 & head2 & addc2 & remc2 & h2 & (? & ? & ?) & ? & ? & ? & (? & ? & ? & (? & ? & ? &\n    (? & ? & ? & (? & ? & ? & (? & ? & ? & (? & ? & ? & (? & ? & ? & (Hq2 & Haddc2)) & Hremc2) & Htv2) & Hta2) &\n    Htr2) & Htl2) & Hghost2) & Hvals2).\n  pose proof (all_ptrs _ _ _ _ Hvals1) as Hptrs1.\n  pose proof (all_ptrs _ _ _ _ Hvals2) as Hptrs2.\n  exploit (tqueue_inj w _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Hq1 Hq2); try join_sub.\n  { apply Forall_rotate, Forall_complete; auto; [|discriminate].\n    eapply Forall_impl; [|apply Hptrs1]; destruct a; try contradiction; discriminate. }\n  { rewrite Zlength_rotate; try rewrite Zlength_complete; try lia; rewrite Zlength_map; auto. }\n  { apply Forall_rotate, Forall_complete; auto; [|discriminate].\n    eapply Forall_impl; [|apply Hptrs2]; destruct a; try contradiction; discriminate. }\n  { rewrite Zlength_rotate; try rewrite Zlength_complete; try lia; rewrite Zlength_map; auto. }\n  { rewrite cond_var_isptr in Haddc1; destruct Haddc1, addc1; try contradiction; discriminate. }\n  { rewrite cond_var_isptr in Haddc2; destruct Haddc2, addc2; try contradiction; discriminate. }\n  { rewrite cond_var_isptr in Hremc1; destruct Hremc1, remc1; try contradiction; discriminate. }\n  { rewrite cond_var_isptr in Hremc2; destruct Hremc2, remc2; try contradiction; discriminate. }\n  intros (? & ? & Hlen & ? & ? & ? & ?); subst.\n  exploit (ghost_precise(t := t) gsh2 p w).\n  { eexists; apply Hghost1. }\n  { eexists; apply Hghost2. }\n  { join_sub. }\n  { join_sub. }\n  intro; subst.\n  assert (head1 = head2) as ->.\n  { apply repr_inj_unsigned; auto; split; try lia; transitivity MAX; try lia; unfold MAX; computable. }\n  assert (length vals1 = length vals2).\n  { apply repr_inj_unsigned in Hlen; rewrite Zlength_correct in Hlen.\n    rewrite Zlength_correct in Hlen; Omega0.\n    - split; [rewrite Zlength_correct; lia|]; transitivity MAX; try lia; unfold MAX; computable.\n    - split; [rewrite Zlength_correct; lia|]; transitivity MAX; try lia; unfold MAX; computable. }\n  assert (map fst vals1 = map fst vals2) as Heq.\n  { eapply complete_inj; [|rewrite !map_length; auto].\n    eapply rotate_inj; eauto; try lia.\n    repeat rewrite length_complete; try rewrite Zlength_map; auto.\n    rewrite Zlength_complete; try rewrite Zlength_map; lia. }\n  rewrite Heq in *.\n  exploit (vals_precise w _ _ _ _ _ _ Heq Hvals1 Hvals2); auto; try join_sub.\n  assert (readable_share Tsh) as Hread by auto.\n  exploit (cond_var_precise _ _ Hread w _ _ Haddc1 Haddc2); try join_sub.\n  exploit (cond_var_precise _ _ Hread w _ _ Hremc1 Hremc2); try join_sub.\n  exploit (malloc_token_precise _ _ _ w _ _ Hta1 Hta2); try join_sub.\n  exploit (malloc_token_precise _ _ _ w _ _ Htr1 Htr2); try join_sub.\n  exploit (malloc_token_precise _ _ _ w _ _ Htv1 Htv2); try join_sub.\n  exploit (malloc_token_precise _ _ _ w _ _ Htl1 Htl2); try join_sub.\n  intros; subst; join_inj.\nQed.\n\nLemma q_inv_positive : forall t P p lock gsh2, positive_mpred (q_lock_pred t P p lock gsh2).\nProof.\n  intros; simpl.\n  repeat (apply ex_positive; intro).\n  apply positive_andp2.\n  do 7 apply positive_sepcon1; apply positive_sepcon2; auto.\nQed.\n#[export] Hint Resolve q_inv_precise q_inv_positive.\n\nLemma lqueue_precise : forall lsh t P p lock gsh1 gsh2,\n  precise (EX h : hist (reptype t), lqueue lsh t P p lock gsh1 gsh2 h).\nProof.\n  intros; unfold lqueue.\n  apply derives_precise' with (Q := field_at lsh tqueue_t [StructField conc_queue._lock] lock p *\n    lock_inv lsh lock (q_lock_pred t P p lock gsh2) * EX f : share * hist (reptype t), ghost gsh1 f p).\n  - entailer!.\n    Exists (lsh, h); auto.\n  - repeat apply precise_sepcon; auto.\n    apply ghost_precise.\nQed.\n#[export] Hint Resolve lqueue_precise.\n\nLemma lqueue_isptr : forall lsh t P p lock gsh1 gsh2 h, lqueue lsh t P p lock gsh1 gsh2 h =\n  !!isptr p && lqueue lsh t P p lock gsh1 gsh2 h.\nProof.\n  intros; eapply local_facts_isptr with (P := fun p => lqueue lsh t P p lock gsh1 gsh2 h); eauto.\n  unfold lqueue; rewrite field_at_isptr; Intros; apply prop_right; auto.\nQed.\n\nLemma list_incl_refl : forall {A} (l : list A), list_incl l l.\nProof.\n  induction l; auto.\nQed.\n#[export] Hint Resolve list_incl_refl.\n\nLemma consistent_inj : forall {t} (h : hist t) a b b' (Hb : consistent h a b) (Hb' : consistent h a b'), b = b'.\nProof.\n  induction h; simpl; intros.\n  - subst; auto.\n  - destruct a; eauto.\n    destruct a0; [contradiction|].\n    destruct Hb, Hb'; eauto.\nQed.\n\nLemma consistent_trans : forall {t} (h1 h2 : hist t) a b c, consistent h1 a b -> consistent h2 b c ->\n  consistent (h1 ++ h2) a c.\nProof.\n  induction h1; simpl; intros; subst; auto.\n  destruct a; eauto.\n  destruct a0; [contradiction | destruct H; eauto].\nQed.\n\nCorollary consistent_snoc_add : forall {t} (h : hist t) a b e v, consistent h a b ->\n  consistent (h ++ [QAdd e v]) a (b ++ [(e, v)]).\nProof.\n  intros; eapply consistent_trans; simpl; eauto.\nQed.\n\nCorollary consistent_cons_rem : forall {t} (h : hist t) a b e v, consistent h a ((e, v) :: b) ->\n  consistent (h ++ [QRem e v]) a b.\nProof.\n  intros; eapply consistent_trans; eauto; simpl; auto.\nQed.\n\nLemma list_incl_app2 : forall {A} (l l1 l2 : list A), list_incl l l2 -> list_incl l (l1 ++ l2).\nProof.\n  induction l1; auto; intros.\n  simpl; constructor; auto.\nQed.\n\nLemma list_incl_app : forall {A} (l1 l2 l1' l2' : list A), list_incl l1 l2 -> list_incl l1' l2' ->\n  list_incl (l1 ++ l1') (l2 ++ l2').\nProof.\n  induction 1; intros.\n  - simpl; apply list_incl_app2; auto.\n  - simpl; constructor; auto.\n  - simpl; constructor 3; auto.\nQed.\n\nDefinition is_add {A} (a : @hist_el A):= match a with QAdd _ _ => true | _ => false end.\n\nLemma consistent_adds : forall {A} (h : hist A) (Hadds : forallb is_add h = true),\n  exists l, h = map (fun x => let '(p, v) := x in QAdd p v) l /\\\n    forall h2 a b, consistent (h ++ h2) a b <-> consistent h2 (a ++ l) b.\nProof.\n  induction h; simpl; intros.\n  - exists []; split; auto; intros; rewrite app_nil_r; reflexivity.\n  - rewrite andb_true_iff in Hadds; destruct Hadds, a; try discriminate.\n    destruct IHh as (l & ? & IH); auto; subst.\n    exists ((p, v) :: l); split; auto; intros; rewrite IH, <- app_assoc; reflexivity.\nQed.\n\nCorollary consistent_insert_rem : forall {A} (h1 h2 : hist A) a b p v (Hadds : forallb is_add h1 = true),\n  consistent (h1 ++ h2) a b -> consistent (h1 ++ QRem p v :: h2) ((p, v) :: a) b.\nProof.\n  intros.\n  destruct (consistent_adds _ Hadds) as (l & ? & Hh1).\n  rewrite Hh1 in *; simpl; auto.\nQed.\n\nLemma interleave_In : forall {A} ls (l' : list A) x (Hinter : interleave ls l'),\n  In x l' <-> exists l, In l ls /\\ In x l.\nProof.\n  induction 1.\n  - split; intro; [contradiction|].\n    destruct H as (? & ? & ?).\n    rewrite Forall_forall in Hnil; exploit Hnil; eauto; intro; subst; auto.\n  - simpl; rewrite IHHinter.\n    exploit (Znth_inbounds i ls []); [rewrite Hcons; discriminate | intro Hi].\n    split; intro.\n    + destruct H.\n      * subst; exists (x :: l); split; simpl; auto.\n        rewrite <- Hcons; apply Znth_In; auto.\n      * destruct H as (l1 & Hl1 & ?).\n        apply In_upd_Znth in Hl1; destruct Hl1; eauto.\n        subst; exists (a :: l); split; simpl; auto.\n        rewrite <- Hcons; apply Znth_In; auto.\n    + destruct H as (l1 & Hl1 & ?).\n      destruct (In_Znth _ _ [] Hl1) as (i' & ? & Hi').\n      destruct (eq_dec i' i).\n      * subst; rewrite Hcons in *; subst.\n        destruct H; auto.\n        right; exists l; split; auto.\n        apply upd_Znth_In.\n      * right; eexists; erewrite <- upd_Znth_diff in Hi'; [split; eauto; rewrite <- Hi'; apply Znth_In | | |];\n          rewrite ?upd_Znth_Zlength; auto.\nQed.\n\nLemma add_first : forall {A} ls (h : hist A) a b\n  (Hinter : interleave ls h) (Hcon : consistent h a b),\n  exists h1 h2, interleave (map (filter is_add) ls) h1 /\\\n                interleave (map (filter (fun a => negb (is_add a))) ls) h2 /\\ consistent (h1 ++ h2) a b.\nProof.\n  intros until 1; revert a b; induction Hinter; intros.\n  - exists [], []; simpl; repeat split; auto; constructor.\n    + rewrite Forall_forall in *; intros.\n      rewrite in_map_iff in H; destruct H as (? & ? & ?); subst.\n      exploit Hnil; eauto; intro; subst; auto.\n    + rewrite Forall_forall in *; intros.\n      rewrite in_map_iff in H; destruct H as (? & ? & ?); subst.\n      exploit Hnil; eauto; intro; subst; auto.\n  - simpl in Hcon.\n    exploit (Znth_inbounds i ls []); [rewrite Hcons; discriminate | intro].\n    destruct a.\n    + specialize (IHHinter _ _ Hcon); destruct IHHinter as (h1 & h2 & Hh1 & Hh2 & ?).\n      exists (QAdd p v :: h1), h2; repeat split; auto.\n      * econstructor.\n        { rewrite Znth_map with (d' := []), Hcons; simpl; eauto. }\n        rewrite upd_Znth_map; auto.\n      * erewrite <- upd_Znth_map, upd_Znth_triv in Hh2; auto.\n        { rewrite Zlength_map; auto. }\n        rewrite Znth_map', Hcons; auto.\n    + destruct a0; [contradiction | destruct Hcon as (? & Hcon); subst].\n      specialize (IHHinter _ _ Hcon); destruct IHHinter as (h1 & h2 & Hh1 & Hh2 & ?).\n      exists h1, (QRem p v :: h2); repeat split.\n      * erewrite <- upd_Znth_map, upd_Znth_triv in Hh1; auto.\n        { rewrite Zlength_map; auto. }\n        rewrite Znth_map', Hcons; auto.\n      * econstructor.\n        { rewrite Znth_map with (d' := []), Hcons; simpl; eauto. }\n        rewrite upd_Znth_map; auto.\n      * apply consistent_insert_rem; auto.\n        rewrite forallb_forall; intros ? Hin.\n        rewrite interleave_In in Hin; [|eauto].\n        destruct Hin as (? & Hin & Hin'); rewrite in_map_iff in Hin.\n        destruct Hin as (? & ? & Hin); subst.\n        rewrite filter_In in Hin'; destruct Hin'; auto.\nQed.\n\nLemma interleave_reorder : forall {A} ls1 ls2 (l l' : list A),\n  interleave (ls1 ++ l :: ls2) l' <-> interleave (l :: ls1 ++ ls2) l'.\nProof.\n  split; intro.\n  - remember (ls1 ++ l :: ls2) as l0; revert dependent ls2; revert l ls1; induction H; intros; subst.\n    + constructor; rewrite Forall_app in Hnil.\n      destruct Hnil as (? & Hnil); inv Hnil; constructor; auto; rewrite Forall_app; auto.\n    + exploit (Znth_inbounds i (ls1 ++ l0 :: ls2) []); [rewrite Hcons; discriminate | intro].\n      destruct (zlt i (Zlength ls1)); [|rewrite app_Znth2 in Hcons; auto; destruct (eq_dec (i - Zlength ls1) 0)].\n      * rewrite app_Znth1 in Hcons; auto.\n        econstructor; [rewrite Znth_pos_cons, app_Znth1, Z.add_simpl_r; eauto; lia|].\n        rewrite upd_Znth_cons, upd_Znth_app1; try lia.\n        apply IHinterleave.\n        rewrite upd_Znth_app1, Z.add_simpl_r; [auto | lia].\n      * rewrite e, Znth_0_cons in Hcons; subst.\n        econstructor; [rewrite Znth_0_cons; eauto|].\n        rewrite upd_Znth0, sublist_1_cons, sublist_same; auto; [|rewrite Zlength_cons; lia].\n        apply IHinterleave.\n        rewrite upd_Znth_app2, e, upd_Znth0, sublist_1_cons, sublist_same; auto;\n          rewrite Zlength_app, Zlength_cons in *; lia.\n      * rewrite Znth_pos_cons in Hcons; [|lia].\n        replace (i - Zlength ls1 - 1) with ((i - 1) - Zlength ls1) in Hcons by lia.\n        assert (i > 0) by (rewrite Zlength_correct in *; lia).\n        econstructor; [rewrite Znth_pos_cons, app_Znth2; eauto; lia|].\n        rewrite Zlength_app, Zlength_cons in *.\n        rewrite upd_Znth_cons, upd_Znth_app2; auto; try lia.\n        apply IHinterleave.\n        rewrite upd_Znth_app2, upd_Znth_cons; rewrite ?Zlength_cons; try lia.\n        replace (i - Zlength ls1 - 1) with (i - 1 - Zlength ls1); Omega0.\n  - remember (l :: ls1 ++ ls2) as l0; revert dependent ls2; revert l ls1; induction H; intros; subst.\n    + inv Hnil; constructor.\n      rewrite Forall_app in H2; destruct H2; rewrite Forall_app; split; auto.\n    + exploit (Znth_inbounds i (l0 :: ls1 ++ ls2) []); [rewrite Hcons; discriminate | intro].\n      destruct (eq_dec i 0); [|rewrite Znth_pos_cons in Hcons; [destruct (zlt (i - 1) (Zlength ls1)) | lia]].\n      * subst; rewrite Znth_0_cons in Hcons; subst.\n        econstructor; [rewrite app_Znth2, Zminus_diag, Znth_0_cons; eauto; lia|].\n        rewrite upd_Znth_app2, Zminus_diag, upd_Znth0, sublist_1_cons, sublist_same; auto;\n          try rewrite Zlength_cons, !Zlength_correct; try lia.\n        apply IHinterleave.\n        rewrite upd_Znth0, sublist_1_cons, sublist_same; auto; rewrite Zlength_cons; lia.\n      * rewrite app_Znth1 in Hcons; auto.\n        econstructor; [rewrite app_Znth1; eauto|].\n        rewrite upd_Znth_app1; [|lia].\n        apply IHinterleave.\n        rewrite upd_Znth_cons, upd_Znth_app1; auto; lia.\n      * rewrite app_Znth2 in Hcons; auto.\n        replace (i - 1 - Zlength ls1) with (i - Zlength ls1 - 1) in Hcons by lia.\n        econstructor; [rewrite app_Znth2, Znth_pos_cons; eauto; lia|].\n        rewrite upd_Znth_app2, upd_Znth_cons; try rewrite Zlength_cons, Zlength_app in *; try lia.\n        apply IHinterleave.\n        rewrite upd_Znth_cons, upd_Znth_app2; try lia.\n        replace (i - 1 - Zlength ls1) with (i - Zlength ls1 - 1); auto; lia.\nQed.\n\nCorollary interleave_remove_nil' : forall {A} ls1 ls2 (l' : list A),\n  interleave (ls1 ++ [] :: ls2) l' <-> interleave (ls1 ++ ls2) l'.\nProof.\n  intros; rewrite interleave_reorder, interleave_remove_nil; reflexivity.\nQed.\n\nLemma consistent_rems : forall {A} (h : hist A) a b (Hrems : forallb (fun x => negb (is_add x)) h = true),\n  consistent h a b ->\n  exists l, a = l ++ b /\\ h = map (fun x => let '(p, v) := x in QRem p v) l.\nProof.\n  induction h; simpl; intros.\n  - subst; exists []; auto.\n  - rewrite andb_true_iff in Hrems; destruct Hrems.\n    destruct a; [discriminate|].\n    destruct a0; [contradiction | destruct H as (? & Hcon); subst].\n    exploit IHh; eauto; intros (l & ? & ?); subst.\n    exists ((p, v) :: l); auto.\nQed.\n\nLemma interleave_map_inj : forall {A B} (f : A -> B) ls l' (Hinj : forall x y, f x = f y -> x = y),\n  interleave (map (map f) ls) (map f l') -> interleave ls l'.\nProof.\n  intros.\n  remember (map (map f) ls) as ls0; remember (map f l') as l1; revert dependent l'; revert dependent ls;\n    induction H; intros; subst.\n  - destruct l'; [|discriminate].\n    constructor.\n    rewrite Forall_forall in *; intros l Hin.\n    exploit (Hnil (map f l)).\n    { rewrite in_map_iff; eauto. }\n    destruct l; auto; discriminate.\n  - destruct l'0; [discriminate | inv Heql1].\n    change [] with (map f []) in Hcons; rewrite Znth_map' in Hcons.\n    destruct (Znth i ls0 []) eqn: Hi; [discriminate | inv Hcons].\n    exploit Hinj; [eassumption | intro; subst].\n    econstructor; eauto.\n    apply IHinterleave; auto.\n    apply upd_Znth_map.\nQed.\n\nLemma interleave_combine : forall {A B} ls1 ls2 (l1 : list A) (l2 : list B)\n  (Hls : Forall2 (fun la lb => length la = length lb) ls1 ls2)\n  (Hlen : length l1 = length l2),\n  interleave (map (fun x => let '(la, lb) := x in combine la lb) (combine ls1 ls2)) (combine l1 l2) ->\n  interleave ls1 l1 /\\ interleave ls2 l2.\nProof.\n  intros.\n  remember (map (fun x => let '(la, lb) := x in combine la lb) (combine ls1 ls2)) as ls0;\n    remember (combine l1 l2) as l0; revert dependent l2; revert l1; revert dependent ls2; revert ls1;\n    induction H; intros; subst.\n  - destruct l1, l2; try discriminate.\n    pose proof (mem_lemmas.Forall2_Zlength Hls).\n    split; constructor.\n    + rewrite Forall_forall in *; intros l1 Hin.\n      destruct (In_Znth _ _ [] Hin) as (i & ? & ?).\n      exploit (Hnil (combine l1 (Znth i ls2 []))).\n      { rewrite in_map_iff; eexists (_, _); split; eauto.\n        subst; rewrite <- Znth_combine; auto.\n        apply Znth_In; rewrite Zlength_combine, Z.min_l; auto; lia. }\n      exploit (Forall2_Znth _ _ _ [] [] Hls); eauto.\n      intros; subst.\n      destruct (Znth i ls1 []); auto.\n      destruct (Znth i ls2 []); discriminate.\n    + rewrite Forall_forall in *; intros l2 Hin.\n      destruct (In_Znth _ _ [] Hin) as (i & ? & ?).\n      exploit (Hnil (combine (Znth i ls1 []) l2)).\n      { rewrite in_map_iff; eexists (_, _); split; eauto.\n        subst; rewrite <- Znth_combine; auto.\n        apply Znth_In; rewrite Zlength_combine, Z.min_l; auto; lia. }\n      exploit (Forall2_Znth _ _ _ [] [] Hls); [rewrite H; eauto|].\n      intros; subst.\n      destruct (Znth i ls2 []); auto.\n      destruct (Znth i ls1 []); discriminate.\n  - destruct l1, l2; try discriminate.\n    pose proof (mem_lemmas.Forall2_Zlength Hls).\n    inv Heql0; inv Hlen.\n    change [] with ((fun x : list A * list B => let '(la, lb) := x in combine la lb) ([], [])) in Hcons.\n    rewrite Znth_map', Znth_combine in Hcons; auto.\n    destruct (Znth i ls1 []) as [|? la] eqn: Ha1; [discriminate|].\n    destruct (Znth i ls2 []) as [|? lb] eqn: Ha2; [discriminate|].\n    inv Hcons.\n    exploit (Znth_inbounds i ls1 []); [rewrite Ha1; discriminate | intro].\n    exploit (IHinterleave (upd_Znth i ls1 la) (upd_Znth i ls2 lb)); eauto.\n    { apply Forall2_upd_Znth; auto; [|lia].\n      exploit (Forall2_Znth _ _ _ [] [] Hls); eauto.\n      rewrite Ha1, Ha2; intro Hlen; inv Hlen; auto. }\n    { change (combine la lb) with ((fun x : list A * list B => let '(la, lb) := x in combine la lb) (la, lb)).\n      rewrite upd_Znth_map, combine_upd_Znth; auto. }\n    intros (? & ?); split; econstructor; eauto.\nQed.\n\nFixpoint total_length {A} (l : list (list A)) :=\n  match l with\n  | [] => 0\n  | l :: rest => Zlength l + total_length rest\n  end.\n\nLemma total_length_app : forall {A} (l1 l2 : list (list A)),\n  total_length (l1 ++ l2) = total_length l1 + total_length l2.\nProof.\n  induction l1; auto; intros; simpl.\n  rewrite IHl1; lia.\nQed.\n\nLemma total_length_upd : forall {A} ls i (l : list A), 0 <= i < Zlength ls ->\n  total_length (upd_Znth i ls l) = total_length ls - Zlength (Znth i ls []) + Zlength l.\nProof.\n  intros; unfold upd_Znth.\n  replace ls with (sublist 0 i ls ++ sublist i (Zlength ls) ls) at 4.\n  rewrite !total_length_app; simpl.\n  rewrite sublist_next with (i0 := i)(d := []); auto; try lia.\n  simpl; lia.\n  { rewrite <- sublist_split, sublist_same; auto; lia. }\nQed.\n\nLemma Zlength_interleave : forall {A} ls (l : list A), interleave ls l ->\n  Zlength l = total_length ls.\nProof.\n  induction 1.\n  - rewrite Zlength_nil.\n    induction ls; auto; simpl.\n    inv Hnil.\n    rewrite Zlength_nil, <- IHls; auto.\n  - exploit (Znth_inbounds i ls []); [rewrite Hcons; discriminate | intro].\n    rewrite total_length_upd, Hcons in IHinterleave; auto.\n    rewrite Zlength_cons in *; lia.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/conc_queue_specs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24840810015529}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import coqutil.Word.Interface coqutil.Word.Bitwidth.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Tactics.ltac_list_ops.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import bedrock2.Map.Separation.\nRequire Import bedrock2.SepLib.\nRequire Export bedrock2.sepapp.\n\nInductive record_field_description{width: Z}{BW: Bitwidth width}{word: word.word width}\n  {mem: map.map word Byte.byte}(R: Type): Type :=\n| mk_record_field_description(F: Type)(getter: R -> F)(pred: F -> word -> mem -> Prop).\n\nArguments mk_record_field_description{width}{BW}{word}{mem}{R}{F}.\n\n(* Given a record_field_description for some type R and a variable r of type R,\n   looks up the size of that record field (might depend on r) using typeclass search,\n   and returns it as a sized_predicate *)\nLtac infer_size r descr :=\n  lazymatch descr with\n  | mk_record_field_description ?getter ?pred =>\n      constr:(mk_sized_predicate (pred (getter r)) _)\n  end.\n\nLtac create_predicate fields :=\n  lazymatch type of fields with\n  | list (record_field_description ?R) =>\n      lazymatch goal with\n      | r: R |- @word.rep _ _ -> @map.rep _ _ _ -> Prop =>\n          let res := map_with_ltac ltac:(infer_size r) fields in\n          exact (sepapps res)\n      end\n  end.\n\n#[export] Hint Extern 20 (PredicateSize ?p) =>\n  let h := head p in unfold h; typeclasses eauto\n: typeclass_instances.\n\nNotation \"'record!' fields\" := ltac:(create_predicate fields)\n  (at level 10, only parsing).\n\n(* The user can decide whether to put the array size between /**# #**/ or not.\n   C compilers will not accept arbitrary Coq expressions in uncommented sizes,\n   but we do not attempt to check that in Coq, because it seems that\n   there is no way to distinguish whether the user wrote `3` or `(Zpos (xI xH))`. *)\nDeclare Custom Entry c_array_size.\nNotation \"x\" := x (in custom c_array_size at level 2, x constr at level 0).\nNotation \"/* *# x #* */\" := x (in custom c_array_size at level 2, x constr at level 100).\n\nDeclare Custom Entry c_type_as_predicate.\nNotation \"'uintptr_t'\" := uintptr (in custom c_type_as_predicate).\nNotation \"'uint32_t'\" := (uint 32) (in custom c_type_as_predicate).\nNotation \"'uint16_t'\" := (uint 16) (in custom c_type_as_predicate).\nNotation \"'uint8_t'\" := (uint 8) (in custom c_type_as_predicate).\nNotation \"'NOT_C!(' x )\" := x (in custom c_type_as_predicate, x constr).\n\nDeclare Custom Entry c_struct_field.\nDeclare Scope c_struct_field_scope.\nOpen Scope c_struct_field_scope.\nNotation \"'c_struct_field:(' x ')'\" := x\n  (at level 0, x custom c_struct_field at level 2, format \"c_struct_field:( x )\")\n  : c_struct_field_scope.\nNotation \"pred fieldname ;\" := (mk_record_field_description fieldname pred)\n  (in custom c_struct_field at level 2,\n   pred custom c_type_as_predicate at level 0,\n   fieldname constr at level 0)\n  : c_struct_field_scope.\nNotation \"pred fieldname [ sz ] ;\" :=\n  (mk_record_field_description fieldname (array pred sz))\n  (in custom c_struct_field at level 2,\n   pred custom c_type_as_predicate at level 0,\n   fieldname constr at level 0,\n   sz custom c_array_size at level 2)\n  : c_struct_field_scope.\n\nDeclare Custom Entry c_struct_field_list.\nNotation \"'c_struct_field_list:(' x ')'\" := x (x custom c_struct_field_list)\n  : c_struct_field_scope.\nNotation \"{ x1 .. xN }\" := (cons x1 .. (cons xN nil) ..)\n  (in custom c_struct_field_list at level 2,\n   x1 custom c_struct_field, xN custom c_struct_field).\n\nNotation \".* */ 'typedef' 'struct' '__attribute__' '((__packed__))' fs name ; /* *\" :=\n  (match fs with (* <-- typechecking x before passing it to Ltac improves error messages *)\n   | name => (* <-- name given to record in C is ignored by Coq *)\n       ltac:(create_predicate fs)\n   end)\n  (at level 200, fs custom c_struct_field_list at level 2, only parsing).\n\nModule Examples_TODO_move.\n\n  Definition ARPOperationRequest: Z := 1.\n  Definition ARPOperationReply: Z := 2.\n\n  Record ARPPacket := mkARPPacket {\n    htype: Z; (* hardware type *)\n    ptype: Z; (* protocol type *)\n    hlen: Z;  (* hardware address length (6 for MAC addresses) *)\n    plen: Z;  (* protocol address length (4 for IPv4 addresses) *)\n    oper: Z;\n    sha: list Z; (* sender hardware address *)\n    spa: list Z; (* sender protocol address *)\n    tha: list Z; (* target hardware address *)\n    tpa: list Z; (* target protocol address *)\n  }.\n\n  Record EthernetHeader := mkEthernetHeader {\n    dstMAC: list Z;\n    srcMAC: list Z;\n    etherType: Z;\n  }.\n\n  Record var_size_foo := {\n    foo_size: Z;\n    foo_stuff: Z;\n    foo_payload: list Z;\n  }.\n\n  Section WithMem.\n    Local Open Scope Z_scope.\n    Context {width: Z} {BW: Bitwidth width}\n            {word: word.word width} {word_ok: word.ok word}\n            {mem: map.map word Byte.byte} {mem_ok: map.ok mem}.\n\n    Goal c_struct_field:(uint32_t foo_size;) =\n         mk_record_field_description foo_size (uint 32).\n    Proof. reflexivity. Abort.\n\n    Goal forall l, c_struct_field:(uint16_t foo_payload[/**# Z.of_nat (S l) #**/];) =\n             mk_record_field_description foo_payload (array (uint 16) (Z.of_nat (S l))).\n    Proof. reflexivity. Abort.\n\n    Goal c_struct_field:(uint16_t foo_payload[4];) =\n         mk_record_field_description foo_payload (array (uint 16) 4).\n    Proof. reflexivity. Abort.\n\n    Goal forall r, c_struct_field_list:({\n      uint32_t foo_size;\n      uint32_t foo_stuff;\n      uint32_t foo_payload[/**# foo_size r #**/];\n    }) =\n    (cons (mk_record_field_description foo_size (uint 32))\n    (cons (mk_record_field_description foo_stuff (uint 32))\n    (cons (mk_record_field_description foo_payload (array (uint 32) (foo_size r))) nil))).\n    Proof. reflexivity. Abort.\n\n    Definition var_size_foo_t(r: var_size_foo): word -> mem -> Prop := .**/\n      typedef struct __attribute__ ((__packed__)) {\n        uint32_t foo_size;\n        uint32_t foo_stuff;\n        uint8_t foo_payload[/**# foo_size r #**/];\n      } var_size_foo_t;\n    /**.\n\n    Goal forall p, (_ : PredicateSize (var_size_foo_t p)) = 8 + (foo_size p * 1).\n    Proof. intros. reflexivity. Abort.\n\n    Definition ARPPacket_t(r: ARPPacket): word -> mem -> Prop := .**/\n      typedef struct __attribute__ ((__packed__)) {\n        uint16_t htype;\n        uint16_t ptype;\n        uint8_t hlen;\n        uint8_t plen;\n        uint16_t oper;\n        uint8_t sha[6];\n        uint8_t spa[4];\n        uint8_t tha[6];\n        uint8_t tpa[4];\n      } ARPPacket_t;\n    /**.\n\n    Goal forall p, (_ : PredicateSize (ARPPacket_t p)) = 28.\n    Proof. intros. reflexivity. Abort.\n\n    Definition EthernetHeader_t(r: EthernetHeader): word -> mem -> Prop := .**/\n      typedef struct __attribute__ ((__packed__)) {\n        uint8_t dstMAC[6];\n        uint8_t srcMAC[6];\n        uint16_t etherType;\n      } EthernetHeader_t;\n    /**.\n\n    Goal forall p, (_ : PredicateSize (EthernetHeader_t p)) = 14.\n    Proof. intros. reflexivity. Abort.\n\n    (* not a Lemma because this kind of goal will be solved inline by sepcalls canceler *)\n    Goal forall (bs: list Z) (R: mem -> Prop) a m (Rest: EthernetHeader -> Prop),\n        sep (array (uint 8) 14 bs a) R m ->\n        exists h, sep (EthernetHeader_t h a) R m /\\ Rest h.\n    Proof.\n      intros.\n      eexists (mkEthernetHeader _ _ _).\n      unfold EthernetHeader_t.\n      cbn.\n    Abort.\n  End WithMem.\nEnd Examples_TODO_move.\n", "meta": {"author": "mit-plv", "repo": "bedrock2", "sha": "7f2d764ed79f394fe715505a04301d0fb502407f", "save_path": "github-repos/coq/mit-plv-bedrock2", "path": "github-repos/coq/mit-plv-bedrock2/bedrock2-7f2d764ed79f394fe715505a04301d0fb502407f/bedrock2/src/bedrock2/RecordPredicates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24840810015529}}
{"text": "Require Import VST.sepcomp.semantics.\n\nRequire Import VST.compcert.lib.Coqlib.\nRequire Import VST.compcert.lib.Maps.\nRequire Import VST.compcert.lib.Integers.\nRequire Import VST.compcert.lib.Axioms.\n\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import VST.sepcomp.mem_lemmas.\n\n\n(** *I'm overloading the definition of coresemantics. **)\n(* Bellow, I produce a way of lifting the old coresemantics to the new one. *)\n(* This is bad design and should be changed. *)\nRecord ThreadSemantics {G C M : Type} : Type :=\n  { (*nat is thread id. It should not be seen by the code.*)\n    initial_core : nat -> G -> val -> list val -> option C \n  ; at_external : C -> option (external_function * list val)\n  ; after_external : option val -> C -> option C\n  ; halted : C -> option val\n  ; corestep : G -> C -> M -> C -> M -> Prop\n\n  ; corestep_not_at_external:\n      forall ge m q m' q', corestep ge q m q' m' -> at_external q = None\n  ; corestep_not_halted:\n      forall ge m q m' q', corestep ge q m q' m' -> halted q = None\n  ; at_external_halted_excl:\n      forall q, at_external q = None \\/ halted q = None }.\n\nArguments CoreSemantics : clear implicits.\n\nInductive mem_step m m' : Prop :=\n    mem_step_storebytes: forall b ofs bytes,\n       Mem.storebytes m b ofs bytes = Some m' -> mem_step m m'\n  | mem_step_alloc: forall lo hi b',\n       Mem.alloc m lo hi = (m',b') -> mem_step m m'\n  | mem_step_freelist: forall l,\n       Mem.free_list m l = Some m' -> mem_step m m'\n  (*Some non-observable external calls are not a single alloc/free/store-step*)\n  | mem_step_trans: forall m'',\n       mem_step m m'' -> mem_step m'' m' -> mem_step m m'.\n\nLocal Notation \"a # b\" := (PMap.get b a) (at level 1).\nRecord perm_lesseq (m m': mem):= {\n  perm_le_Cur:\n    forall b ofs, Mem.perm_order'' ((Mem.mem_access m')#b ofs Cur) ((Mem.mem_access m)#b ofs Cur)\n; perm_le_Max:\n    forall b ofs, Mem.perm_order'' ((Mem.mem_access m')#b ofs Max) ((Mem.mem_access m)#b ofs Max)\n; perm_le_cont:\n    forall b ofs, Mem.perm m b ofs Cur Readable ->\n     ZMap.get ofs (Mem.mem_contents m') !! b= ZMap.get ofs (Mem.mem_contents m) !! b\n; perm_le_nb: Mem.nextblock m = Mem.nextblock m'\n}.\n\n\n(* Memory semantics are CoreSemantics that are specialized to CompCert memories\n   and evolve memory according to mem_step. Previous notion CoopCoreSem is deprecated,\n   but for now retained in file CoopCoreSem.v *)\nRecord MemSem {G C} :=\n  { csem :> @CoreSemantics G C mem\n\n  ; corestep_mem : forall g c m c' m' (CS: corestep csem g c m c' m'), mem_step m m'\n  (*later, we'll want to add the following constraint\n  ; corestep_incr_perm: forall g c m c' m' (CS: corestep csem g c m c' m')  m1 (PLE: perm_lesseq m m1),\n         exists m1', corestep csem g c m1 c' m1' /\\ perm_lesseq m' m1'*)\n  }.\n\nArguments MemSem : clear implicits.", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/concurrency/ThreadSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.24830921898682642}}
{"text": "\nRequire Import null_wind2_spec.\n\n\n\nDefinition type_LF_156 :=  PLAN ->  OBJ ->  nat ->  nat ->  nat ->  nat ->  nat ->  nat ->  nat -> (Prop * (List.list term)).\n\nDefinition F_156 : type_LF_156:= (fun  u5 u3 u1 u2 u4 _ _ _ _ => ((le u1 u2) = false -> (le (plus (time u3) u2) u4) = true -> (wind u5 u4 u1 u2) = Nil -> (sortedT (Cons u3 u5)) = true -> u5 = Nil, (Term id_le ((model_nat u1):: (model_nat u2)::nil))::(Term id_false nil)::(Term id_le ((Term id_plus ((Term id_time ((model_OBJ u3)::nil)):: (model_nat u2)::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_wind ((model_PLAN u5):: (model_nat u4):: (model_nat u1):: (model_nat u2)::nil))::(Term id_Nil nil)::(Term id_sortedT ((Term id_Cons ((model_OBJ u3):: (model_PLAN u5)::nil))::nil))::(Term id_true nil)::(model_PLAN u5)::(Term id_Nil nil)::nil)).\nDefinition F_170 : type_LF_156:= (fun   _ u3 u1 u2 u4 _ _ _ _ => ((le u1 u2) = false -> (le (plus (time u3) u2) u4) = true -> (wind Nil u4 u1 u2) = Nil -> true = true -> Nil = Nil, (Term id_le ((model_nat u1):: (model_nat u2)::nil))::(Term id_false nil)::(Term id_le ((Term id_plus ((Term id_time ((model_OBJ u3)::nil)):: (model_nat u2)::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_wind ((Term id_Nil nil):: (model_nat u4):: (model_nat u1):: (model_nat u2)::nil))::(Term id_Nil nil)::(Term id_true nil)::(Term id_true nil)::(Term id_Nil nil)::(Term id_Nil nil)::nil)).\nDefinition F_182 : type_LF_156:= (fun  u10  _ u1 u2 u4 u6 u7 u8 u9 => ((le u1 u2) = false -> (le (plus (time (C u7 u8)) u2) u4) = true -> (wind (Cons (C u6 u9) u10) u4 u1 u2) = Nil -> false = true -> (le u6 u7) = false -> (Cons (C u6 u9) u10) = Nil, (Term id_le ((model_nat u1):: (model_nat u2)::nil))::(Term id_false nil)::(Term id_le ((Term id_plus ((Term id_time ((Term id_C ((model_nat u7):: (model_nat u8)::nil))::nil)):: (model_nat u2)::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_wind ((Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil)):: (model_nat u4):: (model_nat u1):: (model_nat u2)::nil))::(Term id_Nil nil)::(Term id_false nil)::(Term id_true nil)::(Term id_le ((model_nat u6):: (model_nat u7)::nil))::(Term id_false nil)::(Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil))::(Term id_Nil nil)::nil)).\nDefinition F_176 : type_LF_156:= (fun  u10  _ u1 u2 u4 u6 u7 u8 u9 => ((le u1 u2) = false -> (le (plus (time (C u7 u8)) u2) u4) = true -> (wind (Cons (C u6 u9) u10) u4 u1 u2) = Nil -> (sortedT (Cons (C u6 u9) u10)) = true -> (le u6 u7) = true -> (Cons (C u6 u9) u10) = Nil, (Term id_le ((model_nat u1):: (model_nat u2)::nil))::(Term id_false nil)::(Term id_le ((Term id_plus ((Term id_time ((Term id_C ((model_nat u7):: (model_nat u8)::nil))::nil)):: (model_nat u2)::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_wind ((Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil)):: (model_nat u4):: (model_nat u1):: (model_nat u2)::nil))::(Term id_Nil nil)::(Term id_sortedT ((Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil))::nil))::(Term id_true nil)::(Term id_le ((model_nat u6):: (model_nat u7)::nil))::(Term id_true nil)::(Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil))::(Term id_Nil nil)::nil)).\nDefinition F_185 : type_LF_156:= (fun  u10  _ u1 u2 u4 u6 u7 u9 _ => ((le u1 u2) = false -> (le (plus u7 u2) u4) = true -> (wind (Cons (C u6 u9) u10) u4 u1 u2) = Nil -> (sortedT (Cons (C u6 u9) u10)) = true -> (le u6 u7) = true -> (Cons (C u6 u9) u10) = Nil, (Term id_le ((model_nat u1):: (model_nat u2)::nil))::(Term id_false nil)::(Term id_le ((Term id_plus ((model_nat u7):: (model_nat u2)::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_wind ((Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil)):: (model_nat u4):: (model_nat u1):: (model_nat u2)::nil))::(Term id_Nil nil)::(Term id_sortedT ((Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil))::nil))::(Term id_true nil)::(Term id_le ((model_nat u6):: (model_nat u7)::nil))::(Term id_true nil)::(Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil))::(Term id_Nil nil)::nil)).\nDefinition F_194 : type_LF_156:= (fun  u10  _ u1 u2 u4 u6 u7 u9 _ => ((le u1 u2) = false -> (le (plus u7 u2) u4) = true -> (Cons (C u6 u9) (wind u10 u4 u1 u2)) = Nil -> (sortedT (Cons (C u6 u9) u10)) = true -> (le u6 u7) = true -> (le (plus u6 u2) u4) = true -> (le (plus u6 u1) u4) = false -> (Cons (C u6 u9) u10) = Nil, (Term id_le ((model_nat u1):: (model_nat u2)::nil))::(Term id_false nil)::(Term id_le ((Term id_plus ((model_nat u7):: (model_nat u2)::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (Term id_wind ((model_PLAN u10):: (model_nat u4):: (model_nat u1):: (model_nat u2)::nil))::nil))::(Term id_Nil nil)::(Term id_sortedT ((Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil))::nil))::(Term id_true nil)::(Term id_le ((model_nat u6):: (model_nat u7)::nil))::(Term id_true nil)::(Term id_le ((Term id_plus ((model_nat u6):: (model_nat u2)::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_le ((Term id_plus ((model_nat u6):: (model_nat u1)::nil)):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil))::(Term id_Nil nil)::nil)).\nDefinition F_202 : type_LF_156:= (fun  u10  _ u1 u2 u4 u6 u7 u9 _ => ((le u1 u2) = false -> (le (plus u7 u2) u4) = true -> (Cons (C u6 u9) Nil) = Nil -> (sortedT (Cons (C u6 u9) u10)) = true -> (le u6 u7) = true -> (le (plus u6 u2) u4) = true -> (le (plus u6 u1) u4) = true -> (Cons (C u6 u9) u10) = Nil, (Term id_le ((model_nat u1):: (model_nat u2)::nil))::(Term id_false nil)::(Term id_le ((Term id_plus ((model_nat u7):: (model_nat u2)::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (Term id_Nil nil)::nil))::(Term id_Nil nil)::(Term id_sortedT ((Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil))::nil))::(Term id_true nil)::(Term id_le ((model_nat u6):: (model_nat u7)::nil))::(Term id_true nil)::(Term id_le ((Term id_plus ((model_nat u6):: (model_nat u2)::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_le ((Term id_plus ((model_nat u6):: (model_nat u1)::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil))::(Term id_Nil nil)::nil)).\nDefinition F_198 : type_LF_156:= (fun  u10  _ u1 u2 u4 u6 u7 u9 _ => ((le u1 u2) = false -> (le (plus u7 u2) u4) = true -> (wind u10 u4 u1 u2) = Nil -> (sortedT (Cons (C u6 u9) u10)) = true -> (le u6 u7) = true -> (le (plus u6 u2) u4) = false -> (Cons (C u6 u9) u10) = Nil, (Term id_le ((model_nat u1):: (model_nat u2)::nil))::(Term id_false nil)::(Term id_le ((Term id_plus ((model_nat u7):: (model_nat u2)::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_wind ((model_PLAN u10):: (model_nat u4):: (model_nat u1):: (model_nat u2)::nil))::(Term id_Nil nil)::(Term id_sortedT ((Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil))::nil))::(Term id_true nil)::(Term id_le ((model_nat u6):: (model_nat u7)::nil))::(Term id_true nil)::(Term id_le ((Term id_plus ((model_nat u6):: (model_nat u2)::nil)):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_Cons ((Term id_C ((model_nat u6):: (model_nat u9)::nil)):: (model_PLAN u10)::nil))::(Term id_Nil nil)::nil)).\n\nDefinition LF_156 := [F_156, F_170, F_182, F_176, F_185, F_194, F_202, F_198].\n\n\nFunction f_156 (u5: PLAN) (u3: OBJ) {struct u5} : bool :=\n match u5, u3 with\n| Nil, _ => true\n| (Cons (C u6 u9) u10), (C u7 u8) => true\nend.\n\n\nHypothesis true_154: forall u1 u2 u3 u4, (le (plus u1 u2) u3) = true -> (le u4 u1) = true -> (le (plus u4 u2) u3) = false -> False.\n\nLemma main_156 : forall F, In F LF_156 -> forall u1, forall u2, forall u3, forall u4, forall u5, forall u6, forall u7, forall u8, forall u9, (forall F', In F' LF_156 -> forall e1, forall e2, forall e3, forall e4, forall e5, forall e6, forall e7, forall e8, forall e9, less (snd (F' e1 e2 e3 e4 e5 e6 e7 e8 e9)) (snd (F u1 u2 u3 u4 u5 u6 u7 u8 u9)) -> fst (F' e1 e2 e3 e4 e5 e6 e7 e8 e9)) -> fst (F u1 u2 u3 u4 u5 u6 u7 u8 u9).\nProof.\nintros F HF u1 u2 u3 u4 u5 u6 u7 u8 u9; case_In HF; intro Hind.\n\n\t(* GENERATE on [ 156 ] *)\n\nrename u1 into _u5. rename u2 into _u3. rename u3 into _u1. rename u4 into _u2. rename u5 into _u4. rename u6 into d_u6. rename u7 into d_u7. rename u8 into d_u8. rename u9 into d_u9. \nrename _u5 into u5. rename _u3 into u3. rename _u1 into u1. rename _u2 into u2. rename _u4 into u4. \n\nrevert Hind.\n\npattern u5, u3, (f_156 u5 u3). apply f_156_ind.\n\n(* case [ 170 ] *)\n\nintros _u5 _u3.  intro eq_1. intro. intro Heq3. rewrite <- Heq3.  intro HFabs0.\nassert (Hind := HFabs0 F_170). clear HFabs0.\nassert (HFabs0 : fst (F_170 Nil _u3 u1 u2 u4 0 0 0 0)).\napply Hind. trivial_in 1. unfold snd. unfold F_170. unfold F_156. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_156. unfold F_170.\nauto.\n\n\n\nintros _u5 _u3. intro u6. intro u9. intro u10.  intro eq_1. intro u7. intro u8.  intro eq_2.  intro HFabs0.\ncase_eq (le u6 u7); [intro H | intro H].\n\n(* case [ 176 ] *)\n\nassert (Hind := HFabs0 F_176). clear HFabs0.\nassert (HFabs0 : fst (F_176 u10 (C 0 0 ) u1 u2 u4 u6 u7 u8 u9)).\napply Hind. trivial_in 3. unfold snd. unfold F_176. unfold F_156. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_156. unfold F_176. simpl in H. repeat(simpl; rewrite H). repeat(simpl in HFabs0; rewrite H in HFabs0). try (auto || (intro H0; contradict H0)). \nauto.\n\n\n(* case [ 182 ] *)\n\nassert (Hind := HFabs0 F_182). clear HFabs0.\nassert (HFabs0 : fst (F_182 u10 (C 0 0 ) u1 u2 u4 u6 u7 u8 u9)).\napply Hind. trivial_in 2. unfold snd. unfold F_182. unfold F_156. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_156. unfold F_182. simpl in H. repeat(simpl; rewrite H). repeat(simpl in HFabs0; rewrite H in HFabs0). try (auto || (intro H0; contradict H0)). \nauto.\n\n\n\n\n\n\t(* TAUTOLOGY on [ 170 ] *)\n\nunfold fst. unfold F_170.\nauto.\n\n\n\n\t(* NEGATIVE CLASH on [ 182 ] *)\n\nunfold fst. unfold F_182. intros. try discriminate.\n\n\n\n\t(* REWRITING on [ 176 ] *)\n\nrename u1 into _u10. rename u2 into d_u2. rename u3 into _u1. rename u4 into _u2. rename u5 into _u4. rename u6 into _u6. rename u7 into _u7. rename u8 into _u8. rename u9 into _u9. \nrename _u10 into u10. rename _u1 into u1. rename _u2 into u2. rename _u4 into u4. rename _u6 into u6. rename _u7 into u7. rename _u8 into u8. rename _u9 into u9. \nassert (Res := Hind F_185). clear Hind.\nassert (HFabs1 : fst (F_185 u10 (C 0 0 ) u1 u2 u4 u6 u7 u9 0)).\napply Res. trivial_in 4. unfold snd. unfold F_185. unfold F_176. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_176. unfold fst in HFabs1. unfold F_185 in HFabs1.   \npattern u7, u8. simpl (time _). cbv beta.\n simpl. auto.\n\n\n\n\t(* TOTAL CASE REWRITING on [ 185 ] *)\n\nrename u1 into _u10. rename u2 into d_u2. rename u3 into _u1. rename u4 into _u2. rename u5 into _u4. rename u6 into _u6. rename u7 into _u7. rename u8 into _u9. rename u9 into d_u9. \nrename _u10 into u10. rename _u1 into u1. rename _u2 into u2. rename _u4 into u4. rename _u6 into u6. rename _u7 into u7. rename _u9 into u9. \nassert (H: ((le (plus u6 u2) u4) = true) /\\ ((le (plus u6 u1) u4) = false) \\/ ((le (plus u6 u2) u4) = false) \\/ ((le (plus u6 u2) u4) = true) /\\ ((le (plus u6 u1) u4) = true)). \n\ndestruct ((le (plus u6 u1) u4)); destruct ((le (plus u6 u2) u4)); auto.\n\ndestruct H as [[H H0]|[H|[H H0]]].\n\n(* rewriting with the axiom [ 119 ] *)\n\nassert (H1 := Hind F_194). clear Hind.\nassert (HFabs0 : fst (F_194 u10 (C 0 0 ) u1 u2 u4 u6 u7 u9 0)).\napply H1. trivial_in 5. unfold snd. unfold F_194. unfold F_185. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_185. unfold F_194. unfold fst in HFabs0. unfold F_194 in HFabs0. simpl in HFabs0. \npattern u6.\npattern u2.\npattern u4.\npattern u1.\npattern u9.\npattern u10.\nsimpl (wind _ _ _ _). cbv beta. try unfold wind. try rewrite H. try rewrite H0. try unfold wind in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 120 ] *)\n\nassert (H1 := Hind F_198). clear Hind.\nassert (HFabs0 : fst (F_198 u10 (C 0 0 ) u1 u2 u4 u6 u7 u9 0)).\napply H1. trivial_in 7. unfold snd. unfold F_198. unfold F_185. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_185. unfold F_198. unfold fst in HFabs0. unfold F_198 in HFabs0. simpl in HFabs0. \npattern u6.\npattern u2.\npattern u4.\npattern u9.\npattern u10.\npattern u1.\nsimpl (wind _ _ _ _). cbv beta. try unfold wind. try rewrite H. try rewrite H0. try unfold wind in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 121 ] *)\n\nassert (H1 := Hind F_202). clear Hind.\nassert (HFabs0 : fst (F_202 u10 (C 0 0 ) u1 u2 u4 u6 u7 u9 0)).\napply H1. trivial_in 6. unfold snd. unfold F_202. unfold F_185. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_185. unfold F_202. unfold fst in HFabs0. unfold F_202 in HFabs0. simpl in HFabs0. \npattern u6.\npattern u2.\npattern u4.\npattern u1.\npattern u9.\npattern u10.\nsimpl (wind _ _ _ _). cbv beta. try unfold wind. try rewrite H. try rewrite H0. try unfold wind in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n\n\t(* NEGATIVE CLASH on [ 194 ] *)\n\nunfold fst. unfold F_194. intros. try discriminate.\n\n\n\n\t(* NEGATIVE CLASH on [ 202 ] *)\n\nunfold fst. unfold F_202. intros. try discriminate.\n\n\n\n\t(* SUBSUMPTION on [ 198 ] *)\n\nrename u1 into _u10. rename u2 into d_u2. rename u3 into _u1. rename u4 into _u2. rename u5 into _u4. rename u6 into _u6. rename u7 into _u7. rename u8 into _u9. rename u9 into d_u9. \nrename _u10 into u10. rename _u1 into u1. rename _u2 into u2. rename _u4 into u4. rename _u6 into u6. rename _u7 into u7. rename _u9 into u9. \nunfold fst. unfold F_198. specialize true_154 with (u1 := u7) (u2 := u2) (u3 := u4) (u4 := u6). intro L. intros. contradict L. (auto || symmetry; auto).\n\n\n\nQed.\n\n\n\n(* the set of all formula instances from the proof *)\nDefinition S_156 := fun f => exists F, In F LF_156 /\\ exists e1, exists e2, exists e3, exists e4, exists e5, exists e6, exists e7, exists e8, exists e9, f = F e1 e2 e3 e4 e5 e6 e7 e8 e9.\n\nTheorem all_true_156: forall F, In F LF_156 -> forall u1: PLAN, forall u2: OBJ, forall u3: nat, forall u4: nat, forall u5: nat, forall u6: nat, forall u7: nat, forall u8: nat, forall u9: nat, fst (F u1 u2 u3  u4  u5  u6  u7  u8  u9).\nProof.\nlet n := constr:(9) in\nlet p := constr:(S(S(n))) in\nintros;\nlet G := fresh \"G\" in\nlet x := fresh \"x\" in\napply wf_subset with (R:=@snd_rpo_mul P Prop max_size) (S:=S_156);\n[(* 1 *) apply wf_snd_rpo_mul, prec_wf\n|(* 2 *) idtac\n|(* 3 *) eexists; split; [ eassumption | idtac]; do_nat n ltac:(eexists); reflexivity\n];\n\nintros x G;\ndo_nat p ltac:(elim G; intro; clear G; intro G);\nrewrite G in * |- *; clear G; clear x;\nintro G;\napply main_156;\n [assumption | idtac];\nintros;\napply G;\n [ idtac | assumption ];\neexists; split;\n [idtac | do_nat n ltac:(eexists); reflexivity];\nassumption.\nQed.\n\n\nTheorem true_156: forall (u5: PLAN) (u3: OBJ) (u1: nat) (u2: nat) (u4: nat), (le u1 u2) = false -> (le (plus (time u3) u2) u4) = true -> (wind u5 u4 u1 u2) = Nil -> (sortedT (Cons u3 u5)) = true -> u5 = Nil.\nProof.\ndo 5 intro.\napply (all_true_156 F_156);\n (trivial_in 0) ||\n (repeat constructor).\nQed.\n", "meta": {"author": "sorinica", "repo": "spike-prover", "sha": "f2d6dd0bcebb647e09dd23048753075551da27eb", "save_path": "github-repos/coq/sorinica-spike-prover", "path": "github-repos/coq/sorinica-spike-prover/spike-prover-f2d6dd0bcebb647e09dd23048753075551da27eb/specs/ABR/certified/null_wind2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.24830921382674492}}
{"text": "Definition UU := Type.\n\nDefinition dirprodpair {X Y : UU} := existT (fun x : X => Y).\n\nDefinition funtoprodtoprod {X Y Z : UU} : { a : X -> Y & X -> Z }.\nProof.\n  refine (dirprodpair _ (fun x => _)).\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/closed/4234.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24829818486025249}}
{"text": "From iris.algebra Require Import auth excl csum gmap.\nFrom iris_monotone Require Import monotone.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic Require Import invariants.\nFrom aneris.prelude Require Import gset_map.\nFrom aneris.prelude Require Import time.\nFrom aneris.aneris_lang Require Import network lang resources events.\nFrom aneris.aneris_lang.lib.vector_clock Require Import vector_clock_proof.\nFrom aneris_examples.crdt.gcounter_convergence Require Import crdt_code crdt_model vc.\n\nRecord GCData : Type := {\n  gcd_addr_list : list socket_address;\n  gcd_addr_list_NoDup_ips : NoDup (ip_of_address <$> gcd_addr_list);\n  gcd_addr_list_nonSys : ∀ i sa, gcd_addr_list !! i = Some sa → ip_of_address sa ≠ \"system\";\n}.\n\nLemma gcd_addr_list_NoDup gcdata : NoDup (gcd_addr_list gcdata).\nProof. eapply NoDup_fmap_1; apply gcdata. Qed.\n\nNotation GClen gcdata := (length (gcd_addr_list gcdata)).\n\nCanonical Structure vector_clockO n := leibnizO (vector_clock n).\nCanonical Structure crdt_stateO n := leibnizO (crdt_state n).\n\nDefinition GCounterM gcdata : Model := model _ (λ x y, CrdtNext x tt y) (initial_crdt_state (GClen gcdata)).\n\nNotation PrinGC c := (principal vc_le c).\n\nNotation crdt_stateUR gcdata :=\n  (authUR (gmapUR nat (@monotoneUR (vector_clockO (GClen gcdata)) vc_le))).\nNotation crdt_locsUR := (authUR (gmapUR nat (csumR (exclR unitO) (agreeR (leibnizO loc))))).\nNotation sendevO gcdata :=\n  (prodO natO (prodO (vector_clockO (GClen gcdata)) (vector_clockO (GClen gcdata)))).\nNotation crdt_sendEVUR gcdata := (authUR (gmapUR nat (exclR (listO (sendevO gcdata))))).\nNotation crdt_recEVUR gcdata :=\n  (authUR (gmapUR nat (exclR (listO (vector_clockO (GClen gcdata)))))).\n\nClass GCounterG Σ (gcdata : GCData) := {\n  GCG_view_monoΣ :> inG Σ (crdt_stateUR gcdata);\n  GCG_locΣ :> inG Σ crdt_locsUR;\n  GCG_sendEVΣ :> inG Σ (crdt_sendEVUR gcdata);\n  GCG_recEVΣ :> inG Σ (crdt_recEVUR gcdata);\n  GCG_vcs_name : gname;\n  GCG_locs_name : gname;\n  GCG_sendevs_name : gname;\n  GCG_recevs_name : gname;\n}.\n\nClass GCounterPreG Σ (gcdata : GCData) := {\n  GCPG_view_monoΣ :> inG Σ (crdt_stateUR gcdata);\n  GCPG_locΣ :> inG Σ crdt_locsUR;\n  GCPG_sendEVΣ :> inG Σ (crdt_sendEVUR gcdata);\n  GCPG_recEVΣ :> inG Σ (crdt_recEVUR gcdata);\n}.\n\nDefinition GCounterΣ (gcdata : GCData) :=\n  #[GFunctor (crdt_stateUR gcdata); GFunctor crdt_locsUR;\n   GFunctor (crdt_sendEVUR gcdata); GFunctor (crdt_recEVUR gcdata)].\n\nGlobal Instance subG_GCounterPreG Σ gcdata : subG (GCounterΣ gcdata) Σ → GCounterPreG Σ gcdata.\nProof. constructor; solve_inG. Qed.\n\nSection Resources.\n  Context `{!anerisG (GCounterM gcdata) Σ, !GCounterG Σ gcdata}.\n\n  Notation vector_clock := (vector_clock (GClen gcdata)).\n  Notation crdt_state := (crdt_state (GClen gcdata)).\n\n  Definition GCounters (st : crdt_state) : iProp Σ :=\n    own (A := crdt_stateUR gcdata) GCG_vcs_name (● ((λ c, PrinGC c) <$> list_to_gmap id st)).\n\n  Definition GCounterSnapShot (i : nat) (c : vector_clock) : iProp Σ :=\n    own (A := crdt_stateUR gcdata) GCG_vcs_name (◯ {[i := PrinGC c]}).\n\n  Definition oloc_to_one_shot (ol : option loc) : csum (excl unit) (agree loc) :=\n    from_option (λ l, Cinr (to_agree l)) (Cinl (Excl ())) ol.\n\n  Definition locations (l : list (option loc)) :=\n    own (A:= crdt_locsUR) GCG_locs_name (● (list_to_gmap oloc_to_one_shot l)).\n\n  Definition unallocated (i : nat) := own GCG_locs_name (◯ {[ i := Cinl (Excl ())]}).\n\n  Definition allocated (i : nat) (l : loc) := own GCG_locs_name (◯ {[ i := Cinr (to_agree l)]}).\n\n  Definition loc_coherence (i : nat) (ol : option loc) (vc : vector_clock) : iProp Σ :=\n    match ol with\n    | None => alloc_evs (StringOfZ i) [] ∗\n              ⌜vc = (vreplicate (GClen gcdata) 0)⌝\n    | Some l =>\n        ∃ a,\n          ⌜gcd_addr_list gcdata !! i = Some a⌝ ∗\n          (∃ σ h, ⌜valid_allocObs (ip_of_address a) l σ h⌝ ∗\n                   alloc_evs (StringOfZ i)\n                   [allocObs (ip_of_address a) (StringOfZ i) l\n                             (vector_clock_to_val (vreplicate (GClen gcdata) 0)) σ h]) ∗\n          l ↦[ip_of_address a] (vector_clock_to_val vc)\n    end.\n\n  Definition locations_coherence (locs : list (option loc)) (st : crdt_state) : iProp Σ :=\n    [∗ list] i ↦ ol; vc ∈ locs; st, loc_coherence i ol vc.\n\n  Definition sendevs_auth (sevss : list (list (nat * (vector_clock * vector_clock)))) : iProp Σ :=\n    own GCG_sendevs_name (● list_to_gmap Excl sevss).\n\n  Definition sendevs_frag (i : nat) (sevs : list (nat * (vector_clock * vector_clock))) : iProp Σ :=\n    own GCG_sendevs_name (◯ {[ i := Excl sevs ]}).\n\n  Definition send_events_correspond (sa : socket_address) (l : loc)\n             (ev : EventObservation aneris_lang)\n             (sev : nat * (vector_clock * vector_clock)) : Prop :=\n    ∃ sa' σ h sh skts skt r s,\n      gcd_addr_list gcdata !! sev.1 = Some sa' ∧\n      vc_is_ser (vector_clock_to_val sev.2.2) s ∧\n      valid_sendonObs sa σ sh skts skt r ∧\n      ev = sendonObs sa σ sh s sa' skt ∧\n      σ.(state_heaps) !! (ip_of_address sa) = Some h ∧\n      h !! l = Some (vector_clock_to_val sev.2.1).\n\n  Definition sendevs_valid (sevss : list (nat * (vector_clock * vector_clock))) : Prop :=\n    ∀ i j sev sev',\n      sevss !! i = Some sev →\n      j < i →\n      sevss !! j = Some sev' →\n      sev'.1 = sev.1 →\n      vc_le sev'.2.1 sev.2.2.\n\n  Definition sendev_coh (i : nat) (ol : option loc)\n             (sevs : list (nat * (vector_clock * vector_clock))) : iProp Σ :=\n    ∃ sa,\n      ⌜gcd_addr_list gcdata !! i = Some sa⌝ ∧ ⌜sendevs_valid sevs⌝ ∧\n      ([∗ list] sev ∈ sevs, GCounterSnapShot i sev.2.1) ∗\n      match ol with\n      | Some l => ∃ evs, sendon_evs sa evs ∗ ⌜Forall2 (send_events_correspond sa l) evs sevs⌝\n      | None => sendon_evs sa [] ∧ ⌜sevs = []⌝\n      end.\n\n  Definition sendevs_coherence (locs : list (option loc))\n             (sevss : list (list (nat * (vector_clock * vector_clock)))) : iProp Σ :=\n    [∗ list] i ↦ ol; sevs ∈ locs; sevss, sendev_coh i ol sevs.\n\n  Definition recevs_auth (evss : list (list vector_clock)) : iProp Σ :=\n    own GCG_recevs_name (● list_to_gmap Excl evss).\n\n  Definition recevs_frag (i : nat) (evs : list vector_clock) : iProp Σ :=\n    own GCG_recevs_name (◯ {[ i := Excl evs ]}).\n\n  Definition rec_events_correspond (sa : socket_address)\n             (ev : EventObservation aneris_lang)\n             (rev : vector_clock) : Prop :=\n    ∃ σ sh skts skt msg r,\n      vc_is_ser (vector_clock_to_val rev) (m_body msg) ∧\n      valid_receiveonObs sa σ sh msg skts skt r ∧\n      ev = receiveonObs sa σ sh msg skts skt r.\n\n  Definition recev_coh (i : nat) (revs : list vector_clock) : iProp Σ :=\n    ∃ sa evs, ⌜gcd_addr_list gcdata !! i = Some sa⌝ ∧\n      (∀ rev j, ⌜S j < length revs⌝ → ⌜revs !! j = Some rev⌝ → GCounterSnapShot i rev) ∗\n      (⌜evs ≠ []⌝ → ∃ l, allocated i l) ∗\n      receiveon_evs sa evs ∗ ⌜Forall2 (rec_events_correspond sa) evs revs⌝.\n\n  Definition recevs_coherence (revss : list (list vector_clock)) : iProp Σ :=\n    [∗ list] i ↦ sa; revs ∈ gcd_addr_list gcdata; revss,\n       (∀ rev j, ⌜S j < length revs⌝ → ⌜revs !! j = Some rev⌝ → GCounterSnapShot i rev) ∗\n       ∃ evs,\n         (⌜evs ≠ []⌝ → ∃ l, allocated i l) ∗\n         receiveon_evs sa evs ∗ ⌜Forall2 (rec_events_correspond sa) evs revs⌝.\n\n  (* Properties *)\n\n  Lemma GCounterSnapShot_le (i : fin (GClen gcdata)) vc st :\n    GCounterSnapShot i vc -∗ GCounters st -∗ ⌜vc_le vc (st !!! i)⌝.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct (own_valid_2 with \"H2 H1\") as %[Hv1 Hv2]%auth_both_valid_discrete.\n    apply singleton_included_l in Hv1 as (vc' & Hvc'1 & Hvc'2).\n    rewrite /= lookup_fmap list_to_gmap_lookup in Hvc'1.\n    destruct ((vec_to_list st) !! (fin_to_nat i)) as [vc''|] eqn:Heq; last by inversion Hvc'1.\n    apply vlookup_lookup in Heq as ->.\n    apply Some_equiv_inj in Hvc'1.\n    revert Hvc'2; rewrite -Hvc'1 Some_included_total principal_included; done.\n  Qed.\n\n  Lemma GCounters_update (i : fin (GClen gcdata)) vc' (st : crdt_state):\n    vc_le (st !!! i) vc' → GCounters st ==∗ GCounters (vinsert i vc' st) ∗ GCounterSnapShot i vc'.\n  Proof.\n    iIntros (Hle) \"Ho\".\n    rewrite /GCounterSnapShot /GCounters.\n    iMod (own_update _ _ (● _ ⋅ ◯ _) with \"Ho\") as \"[$ $]\"; last done.\n    apply auth_update_alloc.\n    rewrite vec_to_list_insert -list_to_gmap_insert;\n      last by rewrite vec_to_list_length; apply fin_to_nat_lt.\n    rewrite fmap_insert.\n    eapply insert_alloc_local_update; [|done|].\n    { rewrite lookup_fmap list_to_gmap_lookup.\n      pose proof (eq_refl : st !!! i = st !!! i) as Hlu.\n      apply vlookup_lookup in Hlu as ->; done. }\n    apply monotone_local_update_grow; done.\n  Qed.\n\n  Lemma get_GCounterSnapShot_weaken (i : fin (GClen gcdata)) st vc :\n    vc_le vc (st !!! i) →\n     GCounters st ==∗ GCounters st ∗ GCounterSnapShot i vc.\n  Proof.\n    iIntros (Hle) \"Ho\".\n    rewrite /GCounterSnapShot /GCounters.\n    iMod (own_update _ _ (● _ ⋅ ◯ _) with \"Ho\") as \"[$ $]\"; last done.\n    apply auth_update_alloc.\n    rewrite -{2}(vlookup_insert_self i st).\n    rewrite vec_to_list_insert -list_to_gmap_insert;\n      last by rewrite vec_to_list_length; apply fin_to_nat_lt.\n    rewrite fmap_insert.\n    eapply insert_alloc_local_update; [|done|].\n    { rewrite lookup_fmap list_to_gmap_lookup.\n      pose proof (eq_refl : st !!! i = st !!! i) as Hlu.\n      apply vlookup_lookup in Hlu as ->; done. }\n    apply monotone_local_update_get_frag; done.\n  Qed.\n\n  Lemma get_GCounterSnapShot (i : fin (GClen gcdata)) st :\n     GCounters st ==∗ GCounters st ∗ GCounterSnapShot i (st !!! i).\n  Proof. rewrite -{2}(vlookup_insert_self i st); apply GCounters_update; done. Qed.\n\n  Lemma locations_is_unallocated i locs :\n    locations locs -∗ unallocated i -∗ ⌜locs !! i = Some None⌝.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct (own_valid_2 with \"H1 H2\")\n      as %[(z & Hz1 & Hz2)%singleton_included_l ?]%auth_both_valid_discrete.\n    rewrite list_to_gmap_lookup in Hz1.\n    destruct (locs !! i) as [[]|]; simpl in *; [|done|by inversion Hz1].\n    revert Hz2; rewrite -Hz1 Some_included; intros [Hinc|Hinc]; first by inversion Hinc.\n    apply csum_included in Hinc as [|[(?&?&?&?&?&?)|(?&?&?&?&?)]]; done.\n  Qed.\n\n  Lemma locations_is_allocated i locs l :\n    locations locs -∗ allocated i l -∗ ⌜locs !! i = Some (Some l)⌝.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct (own_valid_2 with \"H1 H2\")\n      as %[(z & Hz1 & Hz2)%singleton_included_l ?]%auth_both_valid_discrete.\n    rewrite list_to_gmap_lookup in Hz1.\n    destruct (locs !! i) as [[]|]; simpl in *; [| |by inversion Hz1].\n    - revert Hz2; rewrite -Hz1 Some_included; intros [Hinc|Hinc].\n      + apply Cinr_inj, to_agree_inj, leibniz_equiv in Hinc as <-; done.\n      + apply Cinr_included, to_agree_included, leibniz_equiv in Hinc as <-; done.\n    - revert Hz2; rewrite -Hz1 Some_included; intros [Hinc|Hinc]; first by inversion Hinc.\n      apply csum_included in Hinc as [|[(?&?&?&?&?&?)|(?&?&?&?&?)]]; done.\n  Qed.\n\n  Lemma locations_alloc i locs l :\n    locations locs -∗ unallocated i ==∗ locations (<[i := Some l]> locs) ∗ allocated i l.\n  Proof.\n    iIntros \"Hlocs Hua\".\n    iDestruct (locations_is_unallocated with \"Hlocs Hua\") as %Hlu.\n    iMod (own_update_2 _ _ _ (● _ ⋅ ◯ _) with \"Hlocs Hua\") as \"[$ $]\"; last done.\n    apply auth_update.\n    rewrite -list_to_gmap_insert; last by apply lookup_lt_is_Some_1; eauto.\n    apply: singleton_local_update; first by rewrite list_to_gmap_lookup Hlu.\n    apply exclusive_local_update; done.\n  Qed.\n\n  Lemma locations_coherence_length locs st :\n    locations_coherence locs st -∗ ⌜length locs = GClen gcdata⌝.\n  Proof.\n    iIntros \"H\".\n    iDestruct (big_sepL2_length with \"H\") as %Hlen.\n    rewrite vec_to_list_length in Hlen; done.\n  Qed.\n\n  Lemma locations_coherence_insert_acc (i : fin (GClen gcdata)) locs ol st :\n    locs !! (fin_to_nat i) = Some ol →\n    locations_coherence locs st -∗\n    loc_coherence i ol (st !!! i) ∗\n    (∀ ol' vc,\n        loc_coherence i ol' vc -∗\n        locations_coherence (<[fin_to_nat i := ol']> locs) (vinsert i vc st)).\n  Proof.\n    iIntros (Hiol) \"Hlc\"; rewrite /locations_coherence.\n    iDestruct (big_sepL2_insert_acc with \"Hlc\") as \"[$ Hlc]\";\n      [apply Hiol|by apply vlookup_lookup|].\n    setoid_rewrite vec_to_list_insert; done.\n  Qed.\n\n  Lemma sendevs_agree sevss i sevs :\n    sendevs_auth sevss -∗ sendevs_frag i sevs -∗ ⌜sevss !! i = Some sevs⌝.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct (own_valid_2 with \"H1 H2\") as %[Hv1 Hv2]%auth_both_valid_discrete.\n    apply singleton_included_l in Hv1 as (vc' & Hvc'1 & Hvc'2).\n    rewrite /= list_to_gmap_lookup in Hvc'1.\n    apply leibniz_equiv in Hvc'1.\n    specialize (Hv2 i); rewrite /= list_to_gmap_lookup in Hv2.\n    destruct (sevss !! i) as [vc''|] eqn:Heq; last by inversion Hvc'1.\n    destruct vc'; last by simplify_eq/=.\n    simplify_eq/=.\n    apply Excl_included, leibniz_equiv in Hvc'2; simplify_eq; done.\n  Qed.\n\n  Lemma sendevs_update sevss i sevs sevs' :\n    sendevs_auth sevss -∗\n    sendevs_frag i sevs ==∗\n    sendevs_auth (<[i := sevs']>sevss) ∗ sendevs_frag i sevs'.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct (sendevs_agree with \"H1 H2\") as %Hlu.\n    rewrite /sendevs_auth /sendevs_frag.\n    iMod (own_update_2 _ _ _ (● _ ⋅ ◯ _) with \"H1 H2\") as \"[$ $]\"; last done.\n    apply auth_update.\n    rewrite -list_to_gmap_insert; last by apply lookup_lt_Some in Hlu.\n    eapply singleton_local_update; first by rewrite list_to_gmap_lookup Hlu.\n    apply exclusive_local_update; done.\n  Qed.\n\n  Lemma recevs_agree revss i revs :\n    recevs_auth revss -∗ recevs_frag i revs -∗ ⌜revss !! i = Some revs⌝.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct (own_valid_2 with \"H1 H2\") as %[Hv1 Hv2]%auth_both_valid_discrete.\n    apply singleton_included_l in Hv1 as (vc' & Hvc'1 & Hvc'2).\n    rewrite /= list_to_gmap_lookup in Hvc'1.\n    apply leibniz_equiv in Hvc'1.\n    specialize (Hv2 i); rewrite /= list_to_gmap_lookup in Hv2.\n    destruct (revss !! i) as [vc''|] eqn:Heq; last by inversion Hvc'1.\n    destruct vc'; last by simplify_eq/=.\n    simplify_eq/=.\n    apply Excl_included, leibniz_equiv in Hvc'2; simplify_eq; done.\n  Qed.\n\n  Lemma recevs_update revss i revs revs' :\n    recevs_auth revss -∗\n    recevs_frag i revs ==∗\n    recevs_auth (<[i := revs']>revss) ∗ recevs_frag i revs'.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct (recevs_agree with \"H1 H2\") as %Hlu.\n    rewrite /recevs_auth /recevs_frag.\n    iMod (own_update_2 _ _ _ (● _ ⋅ ◯ _) with \"H1 H2\") as \"[$ $]\"; last done.\n    apply auth_update.\n    rewrite -list_to_gmap_insert; last by apply lookup_lt_Some in Hlu.\n    eapply singleton_local_update; first by rewrite list_to_gmap_lookup Hlu.\n    apply exclusive_local_update; done.\n  Qed.\n\n  Lemma sendevs_coherence_length locs sevss :\n    sendevs_coherence locs sevss -∗ ⌜length locs = length sevss⌝.\n  Proof. iApply big_sepL2_length. Qed.\n\n  Lemma sendevs_coherence_insert_acc i locs ol sevss sevs :\n    locs !! i = Some ol →\n    sevss !! i = Some sevs →\n    sendevs_coherence locs sevss -∗\n    sendev_coh i ol sevs ∗\n    (∀ ol' sevs',\n        sendev_coh i ol' sevs' -∗\n        sendevs_coherence (<[i := ol']> locs) (<[i := sevs']>sevss)).\n  Proof.\n    iIntros (Hiol Hsevs) \"Hsc\"; rewrite /sendevs_coherence.\n    iDestruct (big_sepL2_insert_acc with \"Hsc\") as \"[$ Hsc]\";\n      [apply Hiol|apply Hsevs|]; done.\n  Qed.\n\n  Lemma recevs_coherence_length revss :\n    recevs_coherence revss -∗ ⌜length revss = GClen gcdata⌝.\n  Proof.\n    iIntros \"H\".\n    iDestruct (big_sepL2_length with \"H\") as %?; done.\n  Qed.\n\n  Lemma recevs_coherence_insert_acc i revss revs :\n    revss !! i = Some revs →\n    recevs_coherence revss -∗\n    recev_coh i revs ∗\n    (∀ revs',\n        recev_coh i revs' -∗\n        recevs_coherence (<[i := revs']>revss)).\n  Proof.\n    iIntros (Hrevs) \"Hrc\"; rewrite /recevs_coherence.\n    iDestruct (recevs_coherence_length with \"Hrc\") as %Hlen.\n    destruct (lookup_lt_is_Some_2 (gcd_addr_list gcdata) i) as [sa Hsa].\n    { rewrite -Hlen; apply lookup_lt_is_Some_1; eauto. }\n    iDestruct (big_sepL2_insert_acc with \"Hrc\") as \"[[Hi1 Hi2] Hrc]\";\n      [apply Hsa|apply Hrevs|].\n    iSplitL \"Hi1 Hi2\".\n    - iDestruct \"Hi2\" as (?) \"Hi2\".\n      iExists _, _; iSplit; first done.\n      iFrame.\n    - iIntros (revs').\n      iSpecialize (\"Hrc\" $! sa revs').\n      rewrite (list_insert_id (gcd_addr_list gcdata) i sa); last done.\n      iDestruct 1 as (sa' ? Hsa') \"(H1 & H2 & H3)\".\n      rewrite Hsa' in Hsa; simplify_eq.\n      iApply \"Hrc\".\n      iFrame; iExists _; iFrame.\n  Qed.\n\n  Lemma sendevs_valid_extend sevs sevs' trpl :\n    (∀ sev, sev ∈ sevs → vc_le sev.2.1 trpl.2.2) →\n    (∀ sev, sev ∈ sevs' → sev.1 ≠ trpl.1) →\n    sendevs_valid (sevs ++ sevs') → sendevs_valid (sevs ++ sevs' ++ [trpl]).\n  Proof.\n    intros Hsevs Hsevs' Hvl.\n    intros i j sev sev' Hisev Hij Hjsev' Hfst.\n    destruct (decide (i < length (sevs ++ sevs'))) as [|Hnlt].\n    - eapply Hvl; [|apply Hij| |done].\n      + rewrite assoc_L lookup_app_l in Hisev; done.\n      + rewrite assoc_L lookup_app_l in Hjsev'; [done|lia].\n    - assert (i = length (sevs ++ sevs')) as ->.\n      { eapply lookup_lt_Some in Hisev.\n        rewrite !app_length in Hisev, Hnlt.\n        rewrite !app_length; simpl in *;lia. }\n      rewrite assoc_L lookup_app_r in Hisev; last lia.\n      rewrite Nat.sub_diag in Hisev; simplify_eq/=.\n      rewrite assoc_L lookup_app_l in Hjsev'; last lia.\n      destruct (decide (j < length sevs)).\n      + rewrite lookup_app_l in Hjsev'; last done.\n        apply Hsevs; apply elem_of_list_lookup; eauto.\n      + rewrite lookup_app_r in Hjsev'; last lia.\n        exfalso; eapply Hsevs'; last by apply Hfst.\n        apply elem_of_list_lookup; eauto.\n  Qed.\n\nEnd Resources.\n\nSection Resources_alloc.\n  Context `{!anerisG (GCounterM gcdata) Σ, !GCounterPreG Σ gcdata}.\n\n  Notation vector_clock := (vector_clock (GClen gcdata)).\n  Notation crdt_state := (crdt_state (GClen gcdata)).\n\n  Lemma Gcounter_init :\n    ⊢ |==> ∃ γ, own (A := crdt_stateUR gcdata) γ\n                    (● ((λ c, PrinGC c) <$> list_to_gmap id (initial_crdt_state (GClen gcdata)))).\n  Proof.\n    apply own_alloc.\n    apply auth_auth_valid; intros ?.\n    rewrite lookup_fmap list_to_gmap_lookup.\n    destruct (vec_to_list (initial_crdt_state (GClen gcdata)) !! i) eqn:Heq; done.\n  Qed.\n\n  Lemma locations_init :\n    ⊢ |==> ∃ γ, own γ (● list_to_gmap oloc_to_one_shot (replicate (GClen gcdata) None)) ∗\n            [∗ list] i ∈ (seq 0 (GClen gcdata)), own γ (◯ {[i := Cinl (Excl ())]}).\n  Proof.\n    iIntros \"\".\n    iMod (own_alloc (● list_to_gmap oloc_to_one_shot (replicate (GClen gcdata) None) ⋅\n                     ◯ list_to_gmap oloc_to_one_shot (replicate (GClen gcdata) None)))\n      as (γ) \"[Hlocs Hua]\".\n    { apply auth_both_valid_2; last done.\n      intros ?; rewrite list_to_gmap_lookup.\n      destruct (replicate (GClen gcdata) None !! i) as [[]|]; done. }\n    iModIntro; iExists _; iFrame \"Hlocs\".\n    generalize 0; intros n.\n    iInduction (GClen gcdata) as [|k IHk] \"IH\" forall (n); simpl; first done.\n    rewrite list_to_gmap_go_cons insert_singleton_op; last by apply list_to_gmap_go_lookup_lt; lia.\n    iDestruct \"Hua\" as \"[$ Hua]\".\n    iApply \"IH\"; done.\n  Qed.\n\n  Lemma sendevs_init k :\n    ⊢ |==> ∃ γ, own γ (● list_to_gmap_go 0 Excl\n                        (replicate k (@nil (nat * (vector_clock * vector_clock))))) ∗\n             [∗ list] i ∈ (seq 0 k),\n               own γ (◯ {[i := Excl (@nil (nat * (vector_clock * vector_clock))) ]}).\n  Proof.\n    iIntros \"\".\n    iMod (own_alloc (● list_to_gmap Excl (replicate k\n                                            (@nil (nat * (vector_clock * vector_clock)))) ⋅\n                     ◯ list_to_gmap Excl (replicate k\n                                            (@nil (nat * (vector_clock * vector_clock))))))\n      as (γ) \"[Hevs Hua]\".\n    { apply auth_both_valid_2; last done.\n      intros ?; rewrite list_to_gmap_lookup.\n      destruct (replicate k [] !! i) as [[]|]; done. }\n    iModIntro; iExists _; iFrame \"Hevs\".\n    generalize 0; intros n.\n    iInduction k as [|k IHk] \"IH\" forall (n); simpl; first done.\n    rewrite list_to_gmap_go_cons insert_singleton_op; last by apply list_to_gmap_go_lookup_lt; lia.\n    iDestruct \"Hua\" as \"[$ Hua]\".\n    iApply \"IH\"; done.\n  Qed.\n\n  Lemma recevs_init k :\n    ⊢ |==> ∃ γ, own γ (● list_to_gmap_go 0 Excl (replicate k (@nil vector_clock))) ∗\n             [∗ list] i ∈ (seq 0 k), own γ (◯ {[i := Excl (@nil vector_clock) ]}).\n  Proof.\n    iIntros \"\".\n    iMod (own_alloc (● list_to_gmap Excl (replicate k (@nil vector_clock)) ⋅\n                     ◯ list_to_gmap Excl (replicate k (@nil vector_clock))))\n      as (γ) \"[Hevs Hua]\".\n    { apply auth_both_valid_2; last done.\n      intros ?; rewrite list_to_gmap_lookup.\n      destruct (replicate k [] !! i) as [[]|]; done. }\n    iModIntro; iExists _; iFrame \"Hevs\".\n    generalize 0; intros n.\n    iInduction k as [|k IHk] \"IH\" forall (n); simpl; first done.\n    rewrite list_to_gmap_go_cons insert_singleton_op; last by apply list_to_gmap_go_lookup_lt; lia.\n    iDestruct \"Hua\" as \"[$ Hua]\".\n    iApply \"IH\"; done.\n  Qed.\n\nEnd Resources_alloc.\n\nSection Resources_alloc.\n  Context `{!anerisG (GCounterM gcdata) Σ, !GCounterG Σ gcdata}.\n\n  Lemma locations_coh_init_helper k n :\n    ([∗ list] i ∈ seq k n, alloc_evs (StringOfZ (i : nat)) []) -∗\n    [∗ list] i↦ol;vc ∈ (replicate n None); (vreplicate n (vreplicate (GClen gcdata) 0)),\n      loc_coherence (k + i) ol vc.\n  Proof.\n    iIntros \"H\".\n    rewrite big_sepL2_replicate_l /=; last by rewrite vec_to_list_length.\n    rewrite vec_to_list_replicate.\n    iInduction n as [|n] \"IH\" forall (k); simpl; first done.\n    rewrite Nat.add_0_r.\n    iDestruct \"H\" as \"[$ H]\".\n    iSplit; first done.\n    iSpecialize (\"IH\" with \"H\").\n    iApply (big_sepL_impl with \"IH\").\n    iIntros \"!#\" (??) \"? ?\".\n    rewrite plus_Snm_nSm; iFrame.\n  Qed.\n\n  Lemma locations_coh_init :\n    ([∗ list] i ∈ seq 0 (GClen gcdata), alloc_evs (StringOfZ (i : nat)) []) -∗\n    locations_coherence (replicate (GClen gcdata) None) (initial_crdt_state (GClen gcdata)).\n  Proof. iApply locations_coh_init_helper. Qed.\n\n  Lemma sendevs_coh_init :\n    ([∗ list] a ∈ gcd_addr_list gcdata, sendon_evs a []) -∗\n    sendevs_coherence (replicate (GClen gcdata) None) (replicate (GClen gcdata) []).\n  Proof.\n    iIntros \"H\".\n    rewrite /sendevs_coherence.\n    rewrite big_sepL2_replicate_l /=; last by rewrite replicate_length.\n    rewrite -(const_fmap (λ _, [])); last done.\n    rewrite big_sepL_fmap.\n    iApply (big_sepL_impl with \"H\").\n    iIntros \"!#\" (?? ?) \"H\".\n    iExists _; simpl; iFrame; done.\n  Qed.\n\n  Lemma recevs_coh_init :\n    ([∗ list] a ∈ gcd_addr_list gcdata, receiveon_evs a []) -∗\n    recevs_coherence (replicate (GClen gcdata) []).\n  Proof.\n    iIntros \"H\".\n    rewrite /recevs_coherence.\n    rewrite big_sepL2_replicate_r; last done.\n    iApply (big_sepL_impl with \"H\").\n    iIntros \"!#\" (?? ?) \"H\"; simpl.\n    iSplit.\n    { iIntros (? ? ?); lia. }\n    iExists _; simpl; iFrame.\n    iSplit; [by iIntros (?)|done].\n  Qed.\n\nEnd Resources_alloc.\n\nSection Sockets.\n  Context `{!anerisG (crdt_model gcdata) Σ, !GCounterG Σ gcdata}.\n  Context (GCG_vcs_name : gname).\n\n  Notation vector_clock := (vector_clock (GClen gcdata)).\n  Notation crdt_state := (crdt_state (GClen gcdata)).\n\n  Definition GCounter_socket_proto : socket_interp Σ :=\n    (λ m,\n     let mb := m_body m in\n     ∃ (t : vector_clock) (i j : nat),\n       ⌜vc_is_ser (vector_clock_to_val t) mb⌝\n       ∧ ⌜gcd_addr_list gcdata !! i = Some (m_sender m)⌝\n       ∧ ⌜gcd_addr_list gcdata !! j = Some (m_destination m)⌝\n       ∧ ⌜i ≠ j⌝\n       ∧ ⌜length t = GClen gcdata⌝\n       ∧ GCounterSnapShot i t)%I.\n\nEnd Sockets.\n\nSection Global_invariant.\n  Context `{!anerisG (GCounterM gcdata) Σ, !GCounterG Σ gcdata}.\n  Context (GCG_locs_name GCG_vcs_name : gname).\n\n  Notation vector_clock := (vector_clock (GClen gcdata)).\n  Notation crdt_state := (crdt_state (GClen gcdata)).\n\n  Definition CvRDT_InvName := nroot .@ \"CRDT\".\n\n  Definition Global_Inv :=\n    inv CvRDT_InvName\n        (∃ st locs sevss revss,\n            frag_st st ∗ GCounters st ∗ locations locs ∗ sendevs_auth sevss ∗ recevs_auth revss ∗\n            locations_coherence locs st ∗\n            sendevs_coherence locs sevss ∗ recevs_coherence revss ∗\n            ([∗ list] a ∈ gcd_addr_list gcdata,\n                ∃ R T, a ⤳[true, true] (R, T) ∗ [∗ set] m ∈ R, GCounter_socket_proto m)).\n\nEnd Global_invariant.\n", "meta": {"author": "fresheed", "repo": "trillium-experiments", "sha": "a9c38a9e9566fb8057ae97ecb8d1a0c09c799aef", "save_path": "github-repos/coq/fresheed-trillium-experiments", "path": "github-repos/coq/fresheed-trillium-experiments/trillium-experiments-a9c38a9e9566fb8057ae97ecb8d1a0c09c799aef/theories/crdt/gcounter_convergence/crdt_resources.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.24828294698139602}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition get_realm_params_spec (realm_params_addr: Z64) (adt: RData) : option (RData * Z) :=\n    match realm_params_addr with\n    | VZ64 addr =>\n      rely is_int64 addr;\n      let gidx := __addr_to_gidx addr in\n      if (GRANULE_ALIGNED addr) && (is_gidx gidx) then\n        rely prop_dec ((buffer (priv adt)) @ SLOT_NS = None);\n        let e := EVT CPU_ID (COPY_NS gidx READ_REALM_PARAMS) in\n        let gn := (gs (share adt)) @ gidx in\n        if (g_tag (ginfo gn) =? GRANULE_STATE_NS) then\n          let ns_data := g_data (gnorm gn) in\n          Some (adt {log: e :: (log adt)} {priv: (priv adt) {realm_params: ns_data}}, 0)\n        else\n          Some (adt {log: e :: (log adt)}, 1)\n      else\n        Some (adt, 1)\n    end.\n\nEnd Spec.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RmiAux/Specs/get_realm_params.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24828294112005586}}
{"text": "Require Import VST.floyd.base.\nRequire Import VST.floyd.find_nth_tactic.\nRequire Import VST.floyd.seplog_tactics.\nLocal Open Scope logic.\n\nLtac backtrack_find_nth_rec tac :=\n  first [ simple eapply find_nth_preds_rec_nil\n        | (simple eapply find_nth_preds_rec_cons_head; tac) +\n          (simple eapply find_nth_preds_rec_cons_tail; backtrack_find_nth_rec tac)].\n\nLtac backtrack_find_nth tac :=\n  eapply find_nth_preds_constr; backtrack_find_nth_rec tac.\n\nInductive syntactic_cancel: list mpred -> list mpred -> list mpred -> list mpred -> Prop :=\n| syntactic_cancel_nil: forall R, syntactic_cancel R nil R nil\n| syntactic_cancel_free: forall R L0 L F Res,\n    emp |-- L0 ->\n    syntactic_cancel R L F Res ->\n    syntactic_cancel R (L0 :: L) F Res\n| syntactic_cancel_cons_succeed_full: forall n R0 R L0 L F Res,\n    nth_error R n = Some R0 ->\n    R0 |-- L0 ->\n    syntactic_cancel (delete_nth n R) L F Res ->\n    syntactic_cancel R (L0 :: L) F Res\n| syntactic_cancel_cons_succeed_partial: forall n R0 R L0 L F0 F Res,\n    nth_error R n = Some R0 ->\n    R0 * F0 |-- L0 ->\n    syntactic_cancel (delete_nth n R) (F0 :: L) F Res ->\n    syntactic_cancel R (L0 :: L) F Res\n| syntactic_cancel_cons_fail: forall R L0 L F Res,\n    syntactic_cancel R L F Res ->\n    syntactic_cancel R (L0 :: L) F (L0 :: Res).\n\nLemma syntactic_cancel_cons: forall nR0 R L0 L F0 F Res,\n  find_nth_preds (fun R0 => R0 * F0 |-- L0) R nR0 ->\n  syntactic_cancel match nR0 with\n                   | Some (n, _) => delete_nth n R\n                   | None => R\n                   end\n                   L F Res /\\ (F0 = emp \\/ nR0 = None) \\/\n  syntactic_cancel match nR0 with\n                   | Some (n, _) => delete_nth n R\n                   | None => R\n                   end\n                   (F0 :: L) F Res /\\ isSome nR0 ->\n  syntactic_cancel R (L0 :: L) F (let Res' := Res in\n                                 match nR0 with\n                                 | Some _ => Res'\n                                 | None => L0 :: Res'\n                                 end).\nProof.\n  intros.\n  destruct nR0 as [[? ?]|]; [destruct H0 |].\n  + destruct H0.\n    destruct H1; [| congruence].\n    subst F0.\n    apply find_nth_preds_Some in H.\n    destruct H.\n    rewrite sepcon_emp in H1.\n    eapply syntactic_cancel_cons_succeed_full; eauto.\n  + apply find_nth_preds_Some in H.\n    destruct H0.\n    destruct H.\n    eapply syntactic_cancel_cons_succeed_partial; eauto.\n  + destruct H0 as [[? _] | [? ?]]; [| tauto].\n    eapply syntactic_cancel_cons_fail; eauto.\nQed.\n\nLemma delete_nth_SEP: forall R n R0,\n  nth_error R n = Some R0 ->\n  fold_right_sepcon R |-- R0 * fold_right_sepcon (delete_nth n R).\nProof.\n  intros.\n  revert R H; induction n; intros; destruct R; try solve [inv H].\n  + inv H.\n    simpl.\n    auto.\n  + simpl in H.\n    apply IHn in H.\n    simpl.\n    rewrite <- sepcon_assoc, (sepcon_comm _ m), sepcon_assoc.\n    apply sepcon_derives; auto.\nQed.\n\nLemma syntactic_cancel_spec1: forall G1 L1 G2 L2 F,\n  syntactic_cancel G1 L1 G2 L2 ->\n  fold_right_sepcon G2 |-- fold_right_sepcon L2 * F ->\n  fold_right_sepcon G1 |-- fold_right_sepcon L1 * F.\nProof.\n  intros.\n  revert F H0; induction H; intros.\n  + auto.\n  + apply IHsyntactic_cancel in H1.\n    simpl.\n    rewrite sepcon_assoc.\n    eapply derives_trans; [| apply sepcon_derives; [apply H | apply H1]].\n    rewrite emp_sepcon; auto.\n  + apply IHsyntactic_cancel in H2.\n    simpl.\n    rewrite sepcon_assoc.\n    eapply derives_trans; [| apply sepcon_derives; [apply derives_refl | apply H2]].\n    clear IHsyntactic_cancel H2.\n    eapply derives_trans; [apply delete_nth_SEP; eauto |].\n    apply sepcon_derives; auto.\n  + apply IHsyntactic_cancel in H2.\n    simpl.\n    rewrite sepcon_assoc.\n    simpl in H2.\n    eapply derives_trans; [| apply sepcon_derives; [apply H0 | apply derives_refl]].\n    rewrite sepcon_assoc.\n    rewrite <- (sepcon_assoc F0).\n    eapply derives_trans; [| apply sepcon_derives; [apply derives_refl | apply H2]].\n    clear IHsyntactic_cancel H2.\n    eapply derives_trans; [apply delete_nth_SEP; eauto |].\n    apply derives_refl.\n  + simpl in H0.\n    rewrite (sepcon_comm L0), sepcon_assoc in H0.\n    apply (IHsyntactic_cancel (L0*F0)) in H0.\n    eapply derives_trans; [exact H0 |].\n    simpl.\n    rewrite <- sepcon_assoc.\n    apply sepcon_derives; auto.\n    rewrite sepcon_comm; auto.\nQed.\n\nLemma syntactic_cancel_solve3:\n  fold_right_sepcon nil |-- fold_right_sepcon nil.\nProof.\n  auto.\nQed.\n\nLemma syntactic_cancel_spec3: forall G1 L1 G2 L2,\n  syntactic_cancel G1 L1 G2 L2 ->\n  fold_right_sepcon G2 |-- fold_right_sepcon L2 ->\n  fold_right_sepcon G1 |-- fold_right_sepcon L1.\nProof.\n  intros.\n  rewrite <- (sepcon_emp (fold_right_sepcon L1)).\n  eapply syntactic_cancel_spec1; eauto.\n  rewrite sepcon_emp; auto.\nQed.\n\nLtac advanced_syntactic_cancel local_tac :=\n  repeat first\n         [ simple apply syntactic_cancel_nil\n         | simple apply syntactic_cancel_free;\n           [ local_tac\n           | ]\n         | simple eapply syntactic_cancel_cons;\n           [ find_nth local_tac\n           | match goal with\n             | |- _ /\\ (emp = emp \\/ _) \\/ _ =>\n                    left;\n                    split; [| left; reflexivity]\n             | |- _ /\\ (_ \\/ None = None) \\/ _ =>\n                    left;\n                    split; [| left; reflexivity]\n                  (* This is intensional \"left\".\n                     This is used to instantiate the unused F0 *)\n             | |- _ \\/ (_ /\\ isSome (Some _)) =>\n                    right;\n                    split; [| exact I]\n             end;\n             cbv iota; unfold delete_nth; cbv zeta iota\n           ]\n         ].\n\nLtac try_one_syntactic_cancel local_tac :=\n          (simple apply syntactic_cancel_free;\n           [ local_tac\n           | ])\n          +\n          (simple eapply syntactic_cancel_cons;\n           [ backtrack_find_nth local_tac\n           | match goal with\n             | |- _ /\\ (emp = emp \\/ _) \\/ _ =>\n                    left;\n                    split; [| left; reflexivity]\n             | |- _ /\\ (_ \\/ None = None) \\/ _ =>\n                    left;\n                    split; [| left; reflexivity]\n                  (* This is intensional \"left\".\n                     This is used to instantiate the unused F0 *)\n             | |- _ \\/ (_ /\\ isSome (Some _)) =>\n                    right;\n                    split; [| exact I]\n             end;\n             cbv iota; unfold delete_nth; cbv zeta iota\n           ]).\n\nLtac conservative_syntactic_cancel local_ctac :=\n  repeat progress\n    (eapply syntactic_cancel_spec3;\n     [advanced_syntactic_cancel local_ctac |\n      cbv iota; cbv zeta beta ]).\n\nLtac aggresive_syntactic_cancel local_atac local_ctac :=\n  once repeat\n   (conservative_syntactic_cancel local_ctac;\n    first [ apply derives_refl\n          | eapply syntactic_cancel_spec3;\n            [ try_one_syntactic_cancel local_atac;\n              advanced_syntactic_cancel local_ctac\n            | cbv iota; cbv zeta beta ]]).\n(*\nModule Test.\nSection Test.\n\nParameters A B C D E F: mpred.\nAxiom Foo1: A * B |-- C.\nAxiom Foo2: C * D |-- E.\n\nLtac foo :=\n  idtac;\n  match goal with\n  | |- ?P * _ |-- ?P => rewrite <- (sepcon_emp P) at 2; apply derives_refl\n  | |- D * _ |-- E => eapply derives_trans; [| apply Foo2];\n                      rewrite (sepcon_comm C D); apply derives_refl\n  | |- A * _ |-- C => eapply derives_trans; [| apply Foo1];\n                      apply derives_refl\n  end.\n\nGoal A * B * F * D |-- E * F.\neapply symbolic_cancel_setup;\n  [ construct_fold_right_sepcon\n  | construct_fold_right_sepcon\n  | fold_abnormal_mpred\n  | cbv iota beta delta [before_symbol_cancel];\n    conservative_syntactic_cancel foo].\n\n\n  auto.\nQed.\n\nEnd Test.\nEnd Test.\n\nModule Test2.\nSection Test2.\n\nParameter A: nat -> nat -> mpred.\nParameter B: nat -> mpred.\nAxiom Foo: forall x y, A x y * B y |-- B x.\n\nLtac cfoo :=\n  idtac;\n  match goal with\n  | |- ?P * _ |-- ?P => rewrite <- (sepcon_emp P) at 2; apply derives_refl\n  | |- A ?x _ * _ |-- B ?x => apply (Foo x)\n  end.\n\nLtac afoo :=\n  idtac;\n  match goal with\n  | |- ?P * _ |-- ?P => rewrite <- (sepcon_emp P) at 2; apply derives_refl\n  | |- A ?x _ * _ |-- B _ => apply (Foo x)\n  | |- B ?x * _ |-- B _ => rewrite (sepcon_emp (B x)); apply derives_refl\n  end.\n\nGoal forall x y, exists z, A x y * B y |-- B z.\n  intros.\n  eexists.\n  eapply symbolic_cancel_setup;\n  [ construct_fold_right_sepcon\n  | construct_fold_right_sepcon\n  | fold_abnormal_mpred\n  | cbv iota beta delta [before_symbol_cancel]].\n  aggresive_syntactic_cancel afoo cfoo.\nQed.\nEnd Test2.\nEnd Test2.\n*)", "meta": {"author": "QinxiangCao", "repo": "VST-A-VSTpart", "sha": "fd8e5b0846a121c20b267fef7ca36e33dd24fae6", "save_path": "github-repos/coq/QinxiangCao-VST-A-VSTpart", "path": "github-repos/coq/QinxiangCao-VST-A-VSTpart/VST-A-VSTpart-fd8e5b0846a121c20b267fef7ca36e33dd24fae6/legacy/AClight/advanced_cancel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24822907631646585}}
{"text": "(** Start of prelude for coq translation of .cat files *)\nFrom Coq Require Import Ensembles List String RelationClasses.\n(** This prelude uses definitions from RelationAlgebra *)\nFrom RelationAlgebra Require Import all.\n\nDefinition set := Ensemble.\nDefinition relation A := hrel A A.\n\nClass SetLike A :=\n  { union : A -> A -> A;\n    intersection : A -> A -> A;\n    diff : A -> A -> A;\n    universal : A;\n    incl : A -> A -> Prop }.\n\nInstance SetLike_set (A : Type) : SetLike (set A) :=\n  {| union := Union A;\n     intersection := Intersection A;\n     diff := Setminus A;\n     universal := Full_set A;\n     incl := Included A |}.\n\nInstance SetLike_relation (A : Type) : SetLike (relation A) :=\n  {| union := cup;\n     intersection := cap;\n     diff := fun R S => cap R (neg S);\n     universal := top;\n     incl := leq |}.\n\nDefinition complement {A} `{SetLike A} (x : A) := diff universal x.\n\nDefinition empty {A} `{SetLike A} : A := diff universal universal.\n\nDefinition is_empty {A} `{SetLike A} (x : A) : Prop := incl x (diff universal universal).\n\nDefinition rel_seq {A} : relation A -> relation A -> relation A := dot A A A.\n\nDefinition rel_inv {A} : relation A -> relation A := cnv A A.\n\nDefinition cartesian {A} : set A -> set A -> relation A := fun X Y x y => X x /\\ Y y.\n\nDefinition id {A} : relation A := eq.\n\nDefinition domain {A} : relation A -> set A := fun R x => exists y, R x y.\n\nDefinition range {A} : relation A -> set A := fun R y => exists x, R x y.\n\nDefinition irreflexive {A} (R : relation A) := forall x, ~R x x.\n\nNotation refl_clos := (fun R => union R id) (only parsing).\n\nNotation trans_clos := (hrel_str _) (only parsing).\n\nNotation refl_trans_clos := (hrel_itr _) (only parsing).\n\nDefinition acyclic {A} (R : relation A) := incl (intersection (trans_clos R) id) empty.\n\nClass StrictTotalOrder {A} (R : relation A) :=\n  { StrictTotalOrder_Strict :> StrictOrder R;\n    StrictTotalOrder_Total : forall a b, a <> b -> (R a b \\/ R b a) }.\n\nDefinition linearisations {A} (X : set A) (R : relation A) : set (relation A) :=\n  fun S => StrictTotalOrder S /\\ incl R S.\n\nDefinition set_flatten {A} : set (set A) -> set A := fun xss x => exists xs, xss xs /\\ xs x.\n\nDefinition map {A B} (f : A -> B) (X : set A) : set B := fun y => exists x, X x /\\ y = f x.\n\nDefinition co_locs {A} (pco : relation A) (wss : set (set A)) : set (set (relation A)) :=\n  map (fun ws => linearisations ws pco) wss.\n\nDefinition cross {A} (Si : set (set (relation A))) : set (relation A) :=\n  fun ei : relation A => exists (l : list (relation A)) (L : list (set (relation A))),\n      (forall x y, ei x y <-> exists e, In e l /\\ e x y) /\\\n      (forall X, Si X <-> In X L) /\\\n      Forall2 (fun ei Si => Si ei) l L.\n\nDefinition diagonal {A} : set A -> relation A := fun X x y => X x /\\ x = y.\n\nDeclare Scope cat_scope.\nNotation \" [ x ] \" := (diagonal x) : cat_scope.\n\n(* Execution given as an argument to the model *)\n\nRecord candidate :=\n  {\n    (* Documentation for names:\n       http://diy.inria.fr/doc/herd.html#language:identifier *)\n    events : Set;\n    W   : set events; (* read events *)\n    R   : set events; (* write events *)\n    IW  : set events; (* initial writes *)\n    FW  : set events; (* final writes *)\n    B   : set events; (* branch events *)\n    RMW : set events; (* read-modify-write events *)\n    F   : set events; (* fence events *)\n    \n    po  : relation events; (* program order *)\n    addr: relation events; (* address dependency *)\n    data: relation events; (* data dependency *)\n    ctrl: relation events; (* control dependency *)\n    rmw : relation events; (* read-exclusive write-exclusive pair *)\n    amo : relation events; (* atomic modify *)\n    \n    rf  : relation events; (* read-from *)\n    loc : relation events; (* same location *)\n    ext : relation events; (* external *)\n    int : relation events; (* internal *)\n    \n    (* Two functions for unknown sets or relations that are found in\n    .cat files. cat2coq uses [unknown_set \"ACQ\"] when translating\n    some parts of cat files about C11 *)\n    unknown_set : string -> set events;\n    unknown_relation : string -> relation events;\n  }.\n\nHint Unfold events W R IW FW B RMW F po addr data ctrl rmw amo rf loc ext int unknown_set unknown_relation : cat_record.\nHint Unfold union intersection diff universal incl SetLike_set SetLike_relation rel_seq rel_inv : cat_defs.\n\n(** End of prelude *)\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/easy_tso_sc/Cat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.24822906492644928}}
{"text": "From isla Require Import opsem.\n\nDefinition a7430 : isla_trace :=\n  Smt (DeclareConst 0%Z (Ty_BitVec 16%N)) Mk_annot :t:\n  Smt (DeclareConst 92%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"R6\" [] (RegVal_Base (Val_Symbolic 92%Z)) Mk_annot :t:\n  Smt (DefineConst 95%Z (Manyop (Bvmanyarith Bvor) [Manyop (Bvmanyarith Bvand) [Val (Val_Symbolic 92%Z) Mk_annot; Val (Val_Bits (BV 64%N 0xffff0000ffffffff%Z)) Mk_annot] Mk_annot; Binop ((Bvarith Bvshl)) (Unop (ZeroExtend 48%N) (Val (Val_Symbolic 0%Z) Mk_annot) Mk_annot) (Val (Val_Bits (BV 64%N 0x20%Z)) Mk_annot) Mk_annot] Mk_annot)) Mk_annot :t:\n  WriteReg \"R6\" [] (RegVal_Base (Val_Symbolic 95%Z)) Mk_annot :t:\n  Smt (DeclareConst 96%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 96%Z)) Mk_annot :t:\n  Smt (DefineConst 97%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 96%Z) Mk_annot; Val (Val_Bits (BV 64%N 0x4%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n  WriteReg \"_PC\" [] (RegVal_Base (Val_Symbolic 97%Z)) Mk_annot :t:\n  tnil\n.\n", "meta": {"author": "rems-project", "repo": "islaris", "sha": "fcc5791c74a2f791dee9080263cd64e42e73bc39", "save_path": "github-repos/coq/rems-project-islaris", "path": "github-repos/coq/rems-project-islaris/islaris-fcc5791c74a2f791dee9080263cd64e42e73bc39/pkvm_handler/a7430.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24822906492644925}}
{"text": "Require Import CertiGraph.CertiGC.gc_spec.\n\nLocal Open Scope Z_scope.\n\nLemma body_create_space: semax_body Vprog Gprog f_create_space create_space_spec.\nProof.\n  start_function.\n  forward_if True.\n  - exfalso. rewrite MSS_eq_unsigned, Int.unsigned_repr in H0;\n               [lia | apply MSS_max_unsigned_range; assumption].\n  - forward. entailer!.\n  - forward_call (Tarray int_or_ptr_type n noattr, gv).\n    + entailer!. simpl. rewrite Z.max_r by lia. now rewrite Z.mul_comm.\n    + split; [|split].\n      * simpl. replace (Z.max 0 n) with n. 1: apply MSS_max_4_unsigned_range, H.\n        rewrite Z.max_r; [reflexivity | destruct H; assumption].\n      * simpl; tauto.\n      * compute; tauto.\n    + Intros p. if_tac.\n      * subst p. forward_if False.\n        -- unfold all_string_constants. Intros.\n           forward_call ((gv ___stringlit_7),\n                         (map init_data2byte (gvar_init v___stringlit_7)), rsh).\n           exfalso; assumption.\n        -- inversion H0.\n      * Intros. forward_if (\n                    PROP ( )\n                    LOCAL (temp _p p; temp _s s; temp _n (Vint (Int.repr n)))\n                    SEP (mem_mgr gv; all_string_constants rsh gv;\n                         malloc_token Ews (Tarray int_or_ptr_type n noattr) p;\n                         data_at_ Ews (Tarray int_or_ptr_type n noattr) p;\n                         data_at_ sh space_type s)).\n        -- contradiction.\n        -- forward. entailer!.\n        -- do 3 forward. Exists p. unfold tarray. entailer!.\nQed.\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/CertiGC/verif_create_space.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24816273895567365}}
{"text": "Require Import ExtLib_Any.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nPolymorphic Class Functor@{d c} (F : Type@{d} -> Type@{c}) : Type :=\n{ fmap : forall {A B : Type@{d}}, (A -> B) -> F A -> F B }.\n\nPolymorphic Definition ID@{d} {T : Type@{d}} (f : T -> T) : Prop :=\n  forall x : T, f x = x.\n\nModule FunctorNotation.\n  Notation \"f <$> x\" := (@fmap _ _ _ _ f x) (at level 52, left associativity).\nEnd FunctorNotation.\n", "meta": {"author": "ku-sldg", "repo": "copland-avm", "sha": "6c08b0e3df96a22cc675bcea309fe99ea7deca65", "save_path": "github-repos/coq/ku-sldg-copland-avm", "path": "github-repos/coq/ku-sldg-copland-avm/copland-avm-6c08b0e3df96a22cc675bcea309fe99ea7deca65/src/extra/ExtLib_Functor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2481476736791122}}
{"text": "(*Generated by Sail from cheri128.*)\nRequire Import Sail.Base.\nRequire Import Sail.Real.\nRequire Import cheri128_types.\nRequire Import mips_extras.\nImport ListNotations.\nOpen Scope string.\nOpen Scope bool.\nOpen Scope Z.\n\n\nDefinition trace : bool := false.\nHint Unfold trace : sail.\nDefinition eq_unit (_ : unit) (_ : unit) : {_bool : bool & ArithFact (_bool)} := build_ex (true).\n\nDefinition neq_int (x : Z) (y : Z) : {_bool : bool & ArithFact (Bool.eqb (negb (x =? y)) _bool)} :=\n   build_ex (negb (Z.eqb x y)).\n\nDefinition neq_bool (x : bool) (y : bool) : bool := negb (Bool.eqb x y).\n\nDefinition __id (x : Z) : {_retval : Z & ArithFact (_retval =? x)} := build_ex (x).\n\nDefinition _shl_int_general (m : Z) (n : Z) : Z :=\n   if sumbool_of_bool (Z.geb n 0) then shl_int m n else shr_int m (Z.opp n).\n\nDefinition _shr_int_general (m : Z) (n : Z) : Z :=\n   if sumbool_of_bool (Z.geb n 0) then shr_int m n else shl_int m (Z.opp n).\n\nDefinition fdiv_int (n : Z) (m : Z) : Z :=\n   if sumbool_of_bool (andb (Z.ltb n 0) (Z.gtb m 0)) then Z.sub (Z.quot (Z.add n 1) m) 1\n   else if sumbool_of_bool (andb (Z.gtb n 0) (Z.ltb m 0)) then Z.sub (Z.quot (Z.sub n 1) m) 1\n   else Z.quot n m.\n\nDefinition fmod_int (n : Z) (m : Z) : Z := Z.sub n (Z.mul m (fdiv_int n m)).\n\nDefinition undefined_option {a : Type} (typ_a : a) : M (option a) :=\n   (undefined_unit tt) >>= fun u_0 : unit =>\n   let u_1 : a := typ_a in\n   (internal_pick [Some u_1; None])\n    : M (option a).\n\nDefinition is_none {a : Type} (opt : option a) : bool :=\n   match opt with | Some _ => false | None => true end.\n\nDefinition is_some {a : Type} (opt : option a) : bool :=\n   match opt with | Some _ => true | None => false end.\n\n\n\nDefinition sail_mask {v0 : Z} (len : Z) (v : mword v0) `{ArithFact ((len >=? 0) && (v0 >=? 0))}\n: mword len :=\n   if sumbool_of_bool (Z.leb len (length_mword v)) then vector_truncate v len else zero_extend v len.\n\nDefinition sail_ones (n : Z) `{ArithFact (n >=? 0)} : mword n := not_vec (zeros n).\n\nDefinition slice_mask (n : Z) (i : Z) (l : Z) `{ArithFact (n >=? 0)} : mword n :=\n   if sumbool_of_bool (Z.geb l n) then shiftl (sail_ones n) i\n   else\n     let one : bits n := sail_mask n ('b\"1\"  : bits 1) in\n     shiftl (sub_vec (shiftl one l) one) i.\n\nDefinition concat_str_bits {n : Z} (str : string) (x : mword n) : string :=\n   String.append str (string_of_bits x).\n\nDefinition concat_str_dec (str : string) (x : Z) : string := String.append str (dec_str x).\n\n\n\nDefinition cast_unit_vec (b : bitU) : mword 1 :=\n   match b with | B0 => 'b\"0\"  : mword 1 | _ => 'b\"1\"  : mword 1 end.\n\nDefinition __MIPS_write (addr : mword 64) (width : Z) (data : mword (8 * width)) : M (unit) :=\n   (write_ram 64 width (Ox\"0000000000000000\"  : mword 64) addr data) >> returnm tt.\n\nDefinition __MIPS_read (addr : mword 64) (width : Z) `{ArithFact (width >=? 0)}\n: M (mword (8 * width)) :=\n   (read_ram 64 width (Ox\"0000000000000000\"  : mword 64) addr)  : M (mword (8 * width)).\n\nDefinition zopz0zQzQ {n0 : Z} (bs : mword n0) (n : Z) `{ArithFact (n >=? 0)} : mword (n0 * n) :=\n   replicate_bits bs n.\n\nDefinition undefined_exception '(tt : unit) : M (exception) :=\n   (undefined_string tt) >>= fun u_0 : string =>\n   (undefined_unit tt) >>= fun u_1 : unit =>\n   (internal_pick\n      [ISAException u_1;\n      Error_not_implemented u_0;\n      Error_misaligned_access u_1;\n      Error_EBREAK u_1;\n      Error_internal_error u_1])\n    : M (exception).\n\nDefinition mips_sign_extend {n : Z} (m : Z) (v : mword n) `{ArithFact (m >=? n)} : mword m :=\n   sign_extend v m.\n\nDefinition mips_zero_extend {n : Z} (m : Z) (v : mword n) `{ArithFact (m >=? n)} : mword m :=\n   zero_extend v m.\n\nDefinition zeros_implicit (n : Z) (_ : unit) `{ArithFact (n >=? 0)} : mword n := zeros n.\n\nDefinition ones_implicit (n : Z) (_ : unit) `{ArithFact (n >=? 0)} : mword n := sail_ones n.\n\nDefinition zopz0zI_s {n : Z} (x : mword n) (y : mword n) `{ArithFact (n >? 0)} : bool :=\n   Z.ltb (projT1 (sint x)) (projT1 (sint y)).\n\nDefinition zopz0zKzJ_s {n : Z} (x : mword n) (y : mword n) `{ArithFact (n >? 0)} : bool :=\n   Z.geb (projT1 (sint x)) (projT1 (sint y)).\n\nDefinition zopz0zI_u {n : Z} (x : mword n) (y : mword n) `{ArithFact (n >=? 0)} : bool :=\n   Z.ltb (projT1 (uint x)) (projT1 (uint y)).\n\nDefinition zopz0zKzJ_u {n : Z} (x : mword n) (y : mword n) `{ArithFact (n >=? 0)} : bool :=\n   Z.geb (projT1 (uint x)) (projT1 (uint y)).\n\nDefinition bool_to_bits (x : bool) : mword 1 :=\n   if sumbool_of_bool x then 'b\"1\"  : mword 1 else 'b\"0\"  : mword 1.\n\nDefinition bool_to_bit (x : bool) : bitU := if sumbool_of_bool x then B1 else B0.\n\nDefinition bit_to_bool (b : bitU) : bool := match b with | B1 => true | _ => false end.\n\nDefinition bits_to_bool (x : mword 1) : bool := bit_to_bool (access_vec_dec x 0).\n\nDefinition to_bits (l : Z) (n : Z) `{ArithFact (l >=? 0)} : mword l := get_slice_int l n 0.\n\nDefinition mask {m : Z} (n : Z) (bs : mword m) `{ArithFact ((m >=? n) && (n >? 0))} : mword n :=\n   autocast (subrange_vec_dec bs (Z.sub n 1) 0).\n\nDefinition undefined_CauseReg '(tt : unit) : M (CauseReg) :=\n   (undefined_bitvector 32) >>= fun w__0 : mword 32 =>\n   returnm ({| CauseReg_CauseReg_chunk_0 := w__0 |}).\n\nDefinition Mk_CauseReg (v : mword 32) : CauseReg :=\n   {| CauseReg_CauseReg_chunk_0 := (subrange_vec_dec v 31 0) |}.\n\nDefinition _get_CauseReg_bits (v : CauseReg) : mword 32 :=\n   subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 31 0.\n\nDefinition _set_CauseReg_bits (r_ref : register_ref regstate register_value CauseReg) (v : mword 32)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       CauseReg_CauseReg_chunk_0 :=\n         (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 31 0 (subrange_vec_dec v 31 0)) ]}\n      : CauseReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_CauseReg_bits (v : CauseReg) (x : mword 32) : CauseReg :=\n   {[ v with\n     CauseReg_CauseReg_chunk_0 :=\n       (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 31 0 (subrange_vec_dec x 31 0)) ]}.\n\nDefinition _get_CauseReg_BD (v : CauseReg) : mword 1 :=\n   subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 31 31.\n\nDefinition _set_CauseReg_BD (r_ref : register_ref regstate register_value CauseReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       CauseReg_CauseReg_chunk_0 :=\n         (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 31 31 (subrange_vec_dec v 0 0)) ]}\n      : CauseReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_CauseReg_BD (v : CauseReg) (x : mword 1) : CauseReg :=\n   {[ v with\n     CauseReg_CauseReg_chunk_0 :=\n       (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 31 31 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_CauseReg_CE (v : CauseReg) : mword 2 :=\n   subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 29 28.\n\nDefinition _set_CauseReg_CE (r_ref : register_ref regstate register_value CauseReg) (v : mword 2)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       CauseReg_CauseReg_chunk_0 :=\n         (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 29 28 (subrange_vec_dec v 1 0)) ]}\n      : CauseReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_CauseReg_CE (v : CauseReg) (x : mword 2) : CauseReg :=\n   {[ v with\n     CauseReg_CauseReg_chunk_0 :=\n       (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 29 28 (subrange_vec_dec x 1 0)) ]}.\n\nDefinition _get_CauseReg_IV (v : CauseReg) : mword 1 :=\n   subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 23 23.\n\nDefinition _set_CauseReg_IV (r_ref : register_ref regstate register_value CauseReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       CauseReg_CauseReg_chunk_0 :=\n         (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 23 23 (subrange_vec_dec v 0 0)) ]}\n      : CauseReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_CauseReg_IV (v : CauseReg) (x : mword 1) : CauseReg :=\n   {[ v with\n     CauseReg_CauseReg_chunk_0 :=\n       (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 23 23 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_CauseReg_WP (v : CauseReg) : mword 1 :=\n   subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 22 22.\n\nDefinition _set_CauseReg_WP (r_ref : register_ref regstate register_value CauseReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       CauseReg_CauseReg_chunk_0 :=\n         (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 22 22 (subrange_vec_dec v 0 0)) ]}\n      : CauseReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_CauseReg_WP (v : CauseReg) (x : mword 1) : CauseReg :=\n   {[ v with\n     CauseReg_CauseReg_chunk_0 :=\n       (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 22 22 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_CauseReg_IP (v : CauseReg) : mword 8 :=\n   subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 15 8.\n\nDefinition _set_CauseReg_IP (r_ref : register_ref regstate register_value CauseReg) (v : mword 8)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       CauseReg_CauseReg_chunk_0 :=\n         (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 15 8 (subrange_vec_dec v 7 0)) ]}\n      : CauseReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_CauseReg_IP (v : CauseReg) (x : mword 8) : CauseReg :=\n   {[ v with\n     CauseReg_CauseReg_chunk_0 :=\n       (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 15 8 (subrange_vec_dec x 7 0)) ]}.\n\nDefinition _get_CauseReg_ExcCode (v : CauseReg) : mword 5 :=\n   subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 6 2.\n\nDefinition _set_CauseReg_ExcCode\n(r_ref : register_ref regstate register_value CauseReg) (v : mword 5)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       CauseReg_CauseReg_chunk_0 :=\n         (update_subrange_vec_dec r.(CauseReg_CauseReg_chunk_0) 6 2 (subrange_vec_dec v 4 0)) ]}\n      : CauseReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_CauseReg_ExcCode (v : CauseReg) (x : mword 5) : CauseReg :=\n   {[ v with\n     CauseReg_CauseReg_chunk_0 :=\n       (update_subrange_vec_dec v.(CauseReg_CauseReg_chunk_0) 6 2 (subrange_vec_dec x 4 0)) ]}.\n\nDefinition undefined_TLBEntryLoReg '(tt : unit) : M (TLBEntryLoReg) :=\n   (undefined_bitvector 64) >>= fun w__0 : mword 64 =>\n   returnm ({| TLBEntryLoReg_TLBEntryLoReg_chunk_0 := w__0 |}).\n\nDefinition Mk_TLBEntryLoReg (v : mword 64) : TLBEntryLoReg :=\n   {| TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (subrange_vec_dec v 63 0) |}.\n\nDefinition _get_TLBEntryLoReg_bits (v : TLBEntryLoReg) : mword 64 :=\n   subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 63 0.\n\nDefinition _set_TLBEntryLoReg_bits\n(r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 64)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 63 0\n            (subrange_vec_dec v 63 0)) ]}\n      : TLBEntryLoReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryLoReg_bits (v : TLBEntryLoReg) (x : mword 64) : TLBEntryLoReg :=\n   {[ v with\n     TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 63 0\n          (subrange_vec_dec x 63 0)) ]}.\n\nDefinition _get_TLBEntryLoReg_CapS (v : TLBEntryLoReg) : mword 1 :=\n   subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 63 63.\n\nDefinition _set_TLBEntryLoReg_CapS\n(r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 63 63\n            (subrange_vec_dec v 0 0)) ]}\n      : TLBEntryLoReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryLoReg_CapS (v : TLBEntryLoReg) (x : mword 1) : TLBEntryLoReg :=\n   {[ v with\n     TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 63 63\n          (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntryLoReg_CapL (v : TLBEntryLoReg) : mword 1 :=\n   subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 62 62.\n\nDefinition _set_TLBEntryLoReg_CapL\n(r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 62 62\n            (subrange_vec_dec v 0 0)) ]}\n      : TLBEntryLoReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryLoReg_CapL (v : TLBEntryLoReg) (x : mword 1) : TLBEntryLoReg :=\n   {[ v with\n     TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 62 62\n          (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntryLoReg_CapLG (v : TLBEntryLoReg) : mword 1 :=\n   subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 61 61.\n\nDefinition _set_TLBEntryLoReg_CapLG\n(r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 61 61\n            (subrange_vec_dec v 0 0)) ]}\n      : TLBEntryLoReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryLoReg_CapLG (v : TLBEntryLoReg) (x : mword 1) : TLBEntryLoReg :=\n   {[ v with\n     TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 61 61\n          (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntryLoReg_PFN (v : TLBEntryLoReg) : mword 24 :=\n   subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 29 6.\n\nDefinition _set_TLBEntryLoReg_PFN\n(r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 24)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 29 6\n            (subrange_vec_dec v 23 0)) ]}\n      : TLBEntryLoReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryLoReg_PFN (v : TLBEntryLoReg) (x : mword 24) : TLBEntryLoReg :=\n   {[ v with\n     TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 29 6\n          (subrange_vec_dec x 23 0)) ]}.\n\nDefinition _get_TLBEntryLoReg_C (v : TLBEntryLoReg) : mword 3 :=\n   subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 5 3.\n\nDefinition _set_TLBEntryLoReg_C\n(r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 3)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 5 3\n            (subrange_vec_dec v 2 0)) ]}\n      : TLBEntryLoReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryLoReg_C (v : TLBEntryLoReg) (x : mword 3) : TLBEntryLoReg :=\n   {[ v with\n     TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 5 3 (subrange_vec_dec x 2 0)) ]}.\n\nDefinition _get_TLBEntryLoReg_D (v : TLBEntryLoReg) : mword 1 :=\n   subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 2 2.\n\nDefinition _set_TLBEntryLoReg_D\n(r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 2 2\n            (subrange_vec_dec v 0 0)) ]}\n      : TLBEntryLoReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryLoReg_D (v : TLBEntryLoReg) (x : mword 1) : TLBEntryLoReg :=\n   {[ v with\n     TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 2 2 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntryLoReg_V (v : TLBEntryLoReg) : mword 1 :=\n   subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 1 1.\n\nDefinition _set_TLBEntryLoReg_V\n(r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 1 1\n            (subrange_vec_dec v 0 0)) ]}\n      : TLBEntryLoReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryLoReg_V (v : TLBEntryLoReg) (x : mword 1) : TLBEntryLoReg :=\n   {[ v with\n     TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 1 1 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntryLoReg_G (v : TLBEntryLoReg) : mword 1 :=\n   subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 0 0.\n\nDefinition _set_TLBEntryLoReg_G\n(r_ref : register_ref regstate register_value TLBEntryLoReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 0 0\n            (subrange_vec_dec v 0 0)) ]}\n      : TLBEntryLoReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryLoReg_G (v : TLBEntryLoReg) (x : mword 1) : TLBEntryLoReg :=\n   {[ v with\n     TLBEntryLoReg_TLBEntryLoReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryLoReg_TLBEntryLoReg_chunk_0) 0 0 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition undefined_TLBEntryHiReg '(tt : unit) : M (TLBEntryHiReg) :=\n   (undefined_bitvector 64) >>= fun w__0 : mword 64 =>\n   returnm ({| TLBEntryHiReg_TLBEntryHiReg_chunk_0 := w__0 |}).\n\nDefinition Mk_TLBEntryHiReg (v : mword 64) : TLBEntryHiReg :=\n   {| TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (subrange_vec_dec v 63 0) |}.\n\nDefinition _get_TLBEntryHiReg_bits (v : TLBEntryHiReg) : mword 64 :=\n   subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 63 0.\n\nDefinition _set_TLBEntryHiReg_bits\n(r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 64)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 63 0\n            (subrange_vec_dec v 63 0)) ]}\n      : TLBEntryHiReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryHiReg_bits (v : TLBEntryHiReg) (x : mword 64) : TLBEntryHiReg :=\n   {[ v with\n     TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 63 0\n          (subrange_vec_dec x 63 0)) ]}.\n\nDefinition _get_TLBEntryHiReg_R (v : TLBEntryHiReg) : mword 2 :=\n   subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 63 62.\n\nDefinition _set_TLBEntryHiReg_R\n(r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 2)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 63 62\n            (subrange_vec_dec v 1 0)) ]}\n      : TLBEntryHiReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryHiReg_R (v : TLBEntryHiReg) (x : mword 2) : TLBEntryHiReg :=\n   {[ v with\n     TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 63 62\n          (subrange_vec_dec x 1 0)) ]}.\n\nDefinition _get_TLBEntryHiReg_CLGK (v : TLBEntryHiReg) : mword 1 :=\n   subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 61 61.\n\nDefinition _set_TLBEntryHiReg_CLGK\n(r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 61 61\n            (subrange_vec_dec v 0 0)) ]}\n      : TLBEntryHiReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryHiReg_CLGK (v : TLBEntryHiReg) (x : mword 1) : TLBEntryHiReg :=\n   {[ v with\n     TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 61 61\n          (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntryHiReg_CLGS (v : TLBEntryHiReg) : mword 1 :=\n   subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 60 60.\n\nDefinition _set_TLBEntryHiReg_CLGS\n(r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 60 60\n            (subrange_vec_dec v 0 0)) ]}\n      : TLBEntryHiReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryHiReg_CLGS (v : TLBEntryHiReg) (x : mword 1) : TLBEntryHiReg :=\n   {[ v with\n     TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 60 60\n          (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntryHiReg_CLGU (v : TLBEntryHiReg) : mword 1 :=\n   subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 59 59.\n\nDefinition _set_TLBEntryHiReg_CLGU\n(r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 59 59\n            (subrange_vec_dec v 0 0)) ]}\n      : TLBEntryHiReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryHiReg_CLGU (v : TLBEntryHiReg) (x : mword 1) : TLBEntryHiReg :=\n   {[ v with\n     TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 59 59\n          (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntryHiReg_VPN2 (v : TLBEntryHiReg) : mword 27 :=\n   subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 39 13.\n\nDefinition _set_TLBEntryHiReg_VPN2\n(r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 27)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 39 13\n            (subrange_vec_dec v 26 0)) ]}\n      : TLBEntryHiReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryHiReg_VPN2 (v : TLBEntryHiReg) (x : mword 27) : TLBEntryHiReg :=\n   {[ v with\n     TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 39 13\n          (subrange_vec_dec x 26 0)) ]}.\n\nDefinition _get_TLBEntryHiReg_ASID (v : TLBEntryHiReg) : mword 8 :=\n   subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 7 0.\n\nDefinition _set_TLBEntryHiReg_ASID\n(r_ref : register_ref regstate register_value TLBEntryHiReg) (v : mword 8)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 7 0\n            (subrange_vec_dec v 7 0)) ]}\n      : TLBEntryHiReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntryHiReg_ASID (v : TLBEntryHiReg) (x : mword 8) : TLBEntryHiReg :=\n   {[ v with\n     TLBEntryHiReg_TLBEntryHiReg_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntryHiReg_TLBEntryHiReg_chunk_0) 7 0 (subrange_vec_dec x 7 0)) ]}.\n\nDefinition undefined_ContextReg '(tt : unit) : M (ContextReg) :=\n   (undefined_bitvector 64) >>= fun w__0 : mword 64 =>\n   returnm ({| ContextReg_ContextReg_chunk_0 := w__0 |}).\n\nDefinition Mk_ContextReg (v : mword 64) : ContextReg :=\n   {| ContextReg_ContextReg_chunk_0 := (subrange_vec_dec v 63 0) |}.\n\nDefinition _get_ContextReg_bits (v : ContextReg) : mword 64 :=\n   subrange_vec_dec v.(ContextReg_ContextReg_chunk_0) 63 0.\n\nDefinition _set_ContextReg_bits\n(r_ref : register_ref regstate register_value ContextReg) (v : mword 64)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       ContextReg_ContextReg_chunk_0 :=\n         (update_subrange_vec_dec r.(ContextReg_ContextReg_chunk_0) 63 0 (subrange_vec_dec v 63 0)) ]}\n      : ContextReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_ContextReg_bits (v : ContextReg) (x : mword 64) : ContextReg :=\n   {[ v with\n     ContextReg_ContextReg_chunk_0 :=\n       (update_subrange_vec_dec v.(ContextReg_ContextReg_chunk_0) 63 0 (subrange_vec_dec x 63 0)) ]}.\n\nDefinition _get_ContextReg_PTEBase (v : ContextReg) : mword 41 :=\n   subrange_vec_dec v.(ContextReg_ContextReg_chunk_0) 63 23.\n\nDefinition _set_ContextReg_PTEBase\n(r_ref : register_ref regstate register_value ContextReg) (v : mword 41)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       ContextReg_ContextReg_chunk_0 :=\n         (update_subrange_vec_dec r.(ContextReg_ContextReg_chunk_0) 63 23 (subrange_vec_dec v 40 0)) ]}\n      : ContextReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_ContextReg_PTEBase (v : ContextReg) (x : mword 41) : ContextReg :=\n   {[ v with\n     ContextReg_ContextReg_chunk_0 :=\n       (update_subrange_vec_dec v.(ContextReg_ContextReg_chunk_0) 63 23 (subrange_vec_dec x 40 0)) ]}.\n\nDefinition _get_ContextReg_BadVPN2 (v : ContextReg) : mword 19 :=\n   subrange_vec_dec v.(ContextReg_ContextReg_chunk_0) 22 4.\n\nDefinition _set_ContextReg_BadVPN2\n(r_ref : register_ref regstate register_value ContextReg) (v : mword 19)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       ContextReg_ContextReg_chunk_0 :=\n         (update_subrange_vec_dec r.(ContextReg_ContextReg_chunk_0) 22 4 (subrange_vec_dec v 18 0)) ]}\n      : ContextReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_ContextReg_BadVPN2 (v : ContextReg) (x : mword 19) : ContextReg :=\n   {[ v with\n     ContextReg_ContextReg_chunk_0 :=\n       (update_subrange_vec_dec v.(ContextReg_ContextReg_chunk_0) 22 4 (subrange_vec_dec x 18 0)) ]}.\n\nDefinition undefined_XContextReg '(tt : unit) : M (XContextReg) :=\n   (undefined_bitvector 64) >>= fun w__0 : mword 64 =>\n   returnm ({| XContextReg_XContextReg_chunk_0 := w__0 |}).\n\nDefinition Mk_XContextReg (v : mword 64) : XContextReg :=\n   {| XContextReg_XContextReg_chunk_0 := (subrange_vec_dec v 63 0) |}.\n\nDefinition _get_XContextReg_bits (v : XContextReg) : mword 64 :=\n   subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 63 0.\n\nDefinition _set_XContextReg_bits\n(r_ref : register_ref regstate register_value XContextReg) (v : mword 64)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       XContextReg_XContextReg_chunk_0 :=\n         (update_subrange_vec_dec r.(XContextReg_XContextReg_chunk_0) 63 0 (subrange_vec_dec v 63 0)) ]}\n      : XContextReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_XContextReg_bits (v : XContextReg) (x : mword 64) : XContextReg :=\n   {[ v with\n     XContextReg_XContextReg_chunk_0 :=\n       (update_subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 63 0 (subrange_vec_dec x 63 0)) ]}.\n\nDefinition _get_XContextReg_XPTEBase (v : XContextReg) : mword 31 :=\n   subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 63 33.\n\nDefinition _set_XContextReg_XPTEBase\n(r_ref : register_ref regstate register_value XContextReg) (v : mword 31)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       XContextReg_XContextReg_chunk_0 :=\n         (update_subrange_vec_dec r.(XContextReg_XContextReg_chunk_0) 63 33\n            (subrange_vec_dec v 30 0)) ]}\n      : XContextReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_XContextReg_XPTEBase (v : XContextReg) (x : mword 31) : XContextReg :=\n   {[ v with\n     XContextReg_XContextReg_chunk_0 :=\n       (update_subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 63 33 (subrange_vec_dec x 30 0)) ]}.\n\nDefinition _get_XContextReg_XR (v : XContextReg) : mword 2 :=\n   subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 32 31.\n\nDefinition _set_XContextReg_XR\n(r_ref : register_ref regstate register_value XContextReg) (v : mword 2)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       XContextReg_XContextReg_chunk_0 :=\n         (update_subrange_vec_dec r.(XContextReg_XContextReg_chunk_0) 32 31 (subrange_vec_dec v 1 0)) ]}\n      : XContextReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_XContextReg_XR (v : XContextReg) (x : mword 2) : XContextReg :=\n   {[ v with\n     XContextReg_XContextReg_chunk_0 :=\n       (update_subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 32 31 (subrange_vec_dec x 1 0)) ]}.\n\nDefinition _get_XContextReg_XBadVPN2 (v : XContextReg) : mword 27 :=\n   subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 30 4.\n\nDefinition _set_XContextReg_XBadVPN2\n(r_ref : register_ref regstate register_value XContextReg) (v : mword 27)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       XContextReg_XContextReg_chunk_0 :=\n         (update_subrange_vec_dec r.(XContextReg_XContextReg_chunk_0) 30 4 (subrange_vec_dec v 26 0)) ]}\n      : XContextReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_XContextReg_XBadVPN2 (v : XContextReg) (x : mword 27) : XContextReg :=\n   {[ v with\n     XContextReg_XContextReg_chunk_0 :=\n       (update_subrange_vec_dec v.(XContextReg_XContextReg_chunk_0) 30 4 (subrange_vec_dec x 26 0)) ]}.\n\nDefinition TLBNumEntries := 64.\nHint Unfold TLBNumEntries : sail.\nDefinition TLBIndexMax : TLBIndexT := 'b\"111111\"  : mword 6.\nHint Unfold TLBIndexMax : sail.\nDefinition MAX (n : Z) `{ArithFact (n >=? 0)} : {_retval : Z & ArithFact (_retval =? (2 ^ n - 1))} :=\n   build_ex (Z.sub (projT1 (pow2 n)) 1).\n\nDefinition MAX_U64 := projT1 (MAX 64).\nHint Unfold MAX_U64 : sail.\nDefinition MAX_VA := projT1 (MAX 40).\nHint Unfold MAX_VA : sail.\nDefinition MAX_PA := projT1 (MAX 36).\nHint Unfold MAX_PA : sail.\nDefinition undefined_TLBEntry '(tt : unit) : M (TLBEntry) :=\n   (undefined_bitvector 55) >>= fun w__0 : mword 55 =>\n   (undefined_bitvector 64) >>= fun w__1 : mword 64 =>\n   returnm ({| TLBEntry_TLBEntry_chunk_1 := w__0;  TLBEntry_TLBEntry_chunk_0 := w__1 |}).\n\nDefinition Mk_TLBEntry (v : mword 119) : TLBEntry :=\n   {| TLBEntry_TLBEntry_chunk_1 := (subrange_vec_dec v 118 64); \n      TLBEntry_TLBEntry_chunk_0 := (subrange_vec_dec v 63 0) |}.\n\nDefinition _get_TLBEntry_bits (v : TLBEntry) : mword 119 :=\n   concat_vec (subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 54 0)\n     (subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 63 0).\n\nDefinition _set_TLBEntry_bits\n(r_ref : register_ref regstate register_value TLBEntry) (v : mword 119)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_1 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 54 0 (subrange_vec_dec v 118 64)) ]}\n      : TLBEntry in\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 63 0 (subrange_vec_dec v 63 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_bits (v : TLBEntry) (x : mword 119) : TLBEntry :=\n   let v :=\n     {[ v with\n       TLBEntry_TLBEntry_chunk_1 :=\n         (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 54 0 (subrange_vec_dec x 118 64)) ]} in\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 63 0 (subrange_vec_dec x 63 0)) ]}.\n\nDefinition _get_TLBEntry_pagemask (v : TLBEntry) : mword 16 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 54 39.\n\nDefinition _set_TLBEntry_pagemask\n(r_ref : register_ref regstate register_value TLBEntry) (v : mword 16)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_1 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 54 39 (subrange_vec_dec v 15 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_pagemask (v : TLBEntry) (x : mword 16) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_1 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 54 39 (subrange_vec_dec x 15 0)) ]}.\n\nDefinition _get_TLBEntry_r (v : TLBEntry) : mword 2 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 38 37.\n\nDefinition _set_TLBEntry_r (r_ref : register_ref regstate register_value TLBEntry) (v : mword 2)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_1 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 38 37 (subrange_vec_dec v 1 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_r (v : TLBEntry) (x : mword 2) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_1 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 38 37 (subrange_vec_dec x 1 0)) ]}.\n\nDefinition _get_TLBEntry_vpn2 (v : TLBEntry) : mword 27 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 36 10.\n\nDefinition _set_TLBEntry_vpn2 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 27)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_1 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 36 10 (subrange_vec_dec v 26 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_vpn2 (v : TLBEntry) (x : mword 27) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_1 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 36 10 (subrange_vec_dec x 26 0)) ]}.\n\nDefinition _get_TLBEntry_asid (v : TLBEntry) : mword 8 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 9 2.\n\nDefinition _set_TLBEntry_asid (r_ref : register_ref regstate register_value TLBEntry) (v : mword 8)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_1 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 9 2 (subrange_vec_dec v 7 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_asid (v : TLBEntry) (x : mword 8) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_1 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 9 2 (subrange_vec_dec x 7 0)) ]}.\n\nDefinition _get_TLBEntry_g (v : TLBEntry) : mword 1 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 1 1.\n\nDefinition _set_TLBEntry_g (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_1 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 1 1 (subrange_vec_dec v 0 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_g (v : TLBEntry) (x : mword 1) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_1 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 1 1 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntry_valid (v : TLBEntry) : mword 1 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 0 0.\n\nDefinition _set_TLBEntry_valid (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_1 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_1) 0 0 (subrange_vec_dec v 0 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_valid (v : TLBEntry) (x : mword 1) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_1 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_1) 0 0 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntry_caplg1 (v : TLBEntry) : mword 1 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 63 63.\n\nDefinition _set_TLBEntry_caplg1\n(r_ref : register_ref regstate register_value TLBEntry) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 63 63 (subrange_vec_dec v 0 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_caplg1 (v : TLBEntry) (x : mword 1) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 63 63 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntry_caps1 (v : TLBEntry) : mword 1 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 62 62.\n\nDefinition _set_TLBEntry_caps1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 62 62 (subrange_vec_dec v 0 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_caps1 (v : TLBEntry) (x : mword 1) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 62 62 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntry_capl1 (v : TLBEntry) : mword 1 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 61 61.\n\nDefinition _set_TLBEntry_capl1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 61 61 (subrange_vec_dec v 0 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_capl1 (v : TLBEntry) (x : mword 1) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 61 61 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntry_pfn1 (v : TLBEntry) : mword 24 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 60 37.\n\nDefinition _set_TLBEntry_pfn1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 24)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 60 37 (subrange_vec_dec v 23 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_pfn1 (v : TLBEntry) (x : mword 24) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 60 37 (subrange_vec_dec x 23 0)) ]}.\n\nDefinition _get_TLBEntry_c1 (v : TLBEntry) : mword 3 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 36 34.\n\nDefinition _set_TLBEntry_c1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 3)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 36 34 (subrange_vec_dec v 2 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_c1 (v : TLBEntry) (x : mword 3) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 36 34 (subrange_vec_dec x 2 0)) ]}.\n\nDefinition _get_TLBEntry_d1 (v : TLBEntry) : mword 1 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 33 33.\n\nDefinition _set_TLBEntry_d1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 33 33 (subrange_vec_dec v 0 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_d1 (v : TLBEntry) (x : mword 1) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 33 33 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntry_v1 (v : TLBEntry) : mword 1 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 32 32.\n\nDefinition _set_TLBEntry_v1 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 32 32 (subrange_vec_dec v 0 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_v1 (v : TLBEntry) (x : mword 1) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 32 32 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntry_caplg0 (v : TLBEntry) : mword 1 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 31 31.\n\nDefinition _set_TLBEntry_caplg0\n(r_ref : register_ref regstate register_value TLBEntry) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 31 31 (subrange_vec_dec v 0 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_caplg0 (v : TLBEntry) (x : mword 1) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 31 31 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntry_caps0 (v : TLBEntry) : mword 1 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 30 30.\n\nDefinition _set_TLBEntry_caps0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 30 30 (subrange_vec_dec v 0 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_caps0 (v : TLBEntry) (x : mword 1) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 30 30 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntry_capl0 (v : TLBEntry) : mword 1 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 29 29.\n\nDefinition _set_TLBEntry_capl0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 29 29 (subrange_vec_dec v 0 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_capl0 (v : TLBEntry) (x : mword 1) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 29 29 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntry_pfn0 (v : TLBEntry) : mword 24 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 28 5.\n\nDefinition _set_TLBEntry_pfn0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 24)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 28 5 (subrange_vec_dec v 23 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_pfn0 (v : TLBEntry) (x : mword 24) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 28 5 (subrange_vec_dec x 23 0)) ]}.\n\nDefinition _get_TLBEntry_c0 (v : TLBEntry) : mword 3 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 4 2.\n\nDefinition _set_TLBEntry_c0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 3)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 4 2 (subrange_vec_dec v 2 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_c0 (v : TLBEntry) (x : mword 3) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 4 2 (subrange_vec_dec x 2 0)) ]}.\n\nDefinition _get_TLBEntry_d0 (v : TLBEntry) : mword 1 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 1 1.\n\nDefinition _set_TLBEntry_d0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 1 1 (subrange_vec_dec v 0 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_d0 (v : TLBEntry) (x : mword 1) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 1 1 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_TLBEntry_v0 (v : TLBEntry) : mword 1 :=\n   subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 0 0.\n\nDefinition _set_TLBEntry_v0 (r_ref : register_ref regstate register_value TLBEntry) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       TLBEntry_TLBEntry_chunk_0 :=\n         (update_subrange_vec_dec r.(TLBEntry_TLBEntry_chunk_0) 0 0 (subrange_vec_dec v 0 0)) ]}\n      : TLBEntry in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_TLBEntry_v0 (v : TLBEntry) (x : mword 1) : TLBEntry :=\n   {[ v with\n     TLBEntry_TLBEntry_chunk_0 :=\n       (update_subrange_vec_dec v.(TLBEntry_TLBEntry_chunk_0) 0 0 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition TLBEntries : vec (register_ref regstate register_value TLBEntry) 64 :=\nvec_of_list_len [TLBEntry63_ref;TLBEntry62_ref;TLBEntry61_ref;TLBEntry60_ref;TLBEntry59_ref;\n                 TLBEntry58_ref;TLBEntry57_ref;TLBEntry56_ref;TLBEntry55_ref;TLBEntry54_ref;\n                 TLBEntry53_ref;TLBEntry52_ref;TLBEntry51_ref;TLBEntry50_ref;TLBEntry49_ref;\n                 TLBEntry48_ref;TLBEntry47_ref;TLBEntry46_ref;TLBEntry45_ref;TLBEntry44_ref;\n                 TLBEntry43_ref;TLBEntry42_ref;TLBEntry41_ref;TLBEntry40_ref;TLBEntry39_ref;\n                 TLBEntry38_ref;TLBEntry37_ref;TLBEntry36_ref;TLBEntry35_ref;TLBEntry34_ref;\n                 TLBEntry33_ref;TLBEntry32_ref;TLBEntry31_ref;TLBEntry30_ref;TLBEntry29_ref;\n                 TLBEntry28_ref;TLBEntry27_ref;TLBEntry26_ref;TLBEntry25_ref;TLBEntry24_ref;\n                 TLBEntry23_ref;TLBEntry22_ref;TLBEntry21_ref;TLBEntry20_ref;TLBEntry19_ref;\n                 TLBEntry18_ref;TLBEntry17_ref;TLBEntry16_ref;TLBEntry15_ref;TLBEntry14_ref;\n                 TLBEntry13_ref;TLBEntry12_ref;TLBEntry11_ref;TLBEntry10_ref;TLBEntry09_ref;\n                 TLBEntry08_ref;TLBEntry07_ref;TLBEntry06_ref;TLBEntry05_ref;TLBEntry04_ref;\n                 TLBEntry03_ref;TLBEntry02_ref;TLBEntry01_ref;TLBEntry00_ref].\nHint Unfold TLBEntries : sail.\nDefinition undefined_StatusReg '(tt : unit) : M (StatusReg) :=\n   (undefined_bitvector 32) >>= fun w__0 : mword 32 =>\n   returnm ({| StatusReg_StatusReg_chunk_0 := w__0 |}).\n\nDefinition Mk_StatusReg (v : mword 32) : StatusReg :=\n   {| StatusReg_StatusReg_chunk_0 := (subrange_vec_dec v 31 0) |}.\n\nDefinition _get_StatusReg_bits (v : StatusReg) : mword 32 :=\n   subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 31 0.\n\nDefinition _set_StatusReg_bits\n(r_ref : register_ref regstate register_value StatusReg) (v : mword 32)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       StatusReg_StatusReg_chunk_0 :=\n         (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 31 0 (subrange_vec_dec v 31 0)) ]}\n      : StatusReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_StatusReg_bits (v : StatusReg) (x : mword 32) : StatusReg :=\n   {[ v with\n     StatusReg_StatusReg_chunk_0 :=\n       (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 31 0 (subrange_vec_dec x 31 0)) ]}.\n\nDefinition _get_StatusReg_CU (v : StatusReg) : mword 4 :=\n   subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 31 28.\n\nDefinition _set_StatusReg_CU (r_ref : register_ref regstate register_value StatusReg) (v : mword 4)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       StatusReg_StatusReg_chunk_0 :=\n         (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 31 28 (subrange_vec_dec v 3 0)) ]}\n      : StatusReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_StatusReg_CU (v : StatusReg) (x : mword 4) : StatusReg :=\n   {[ v with\n     StatusReg_StatusReg_chunk_0 :=\n       (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 31 28 (subrange_vec_dec x 3 0)) ]}.\n\nDefinition _get_StatusReg_BEV (v : StatusReg) : mword 1 :=\n   subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 22 22.\n\nDefinition _set_StatusReg_BEV (r_ref : register_ref regstate register_value StatusReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       StatusReg_StatusReg_chunk_0 :=\n         (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 22 22 (subrange_vec_dec v 0 0)) ]}\n      : StatusReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_StatusReg_BEV (v : StatusReg) (x : mword 1) : StatusReg :=\n   {[ v with\n     StatusReg_StatusReg_chunk_0 :=\n       (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 22 22 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_StatusReg_IM (v : StatusReg) : mword 8 :=\n   subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 15 8.\n\nDefinition _set_StatusReg_IM (r_ref : register_ref regstate register_value StatusReg) (v : mword 8)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       StatusReg_StatusReg_chunk_0 :=\n         (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 15 8 (subrange_vec_dec v 7 0)) ]}\n      : StatusReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_StatusReg_IM (v : StatusReg) (x : mword 8) : StatusReg :=\n   {[ v with\n     StatusReg_StatusReg_chunk_0 :=\n       (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 15 8 (subrange_vec_dec x 7 0)) ]}.\n\nDefinition _get_StatusReg_KX (v : StatusReg) : mword 1 :=\n   subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 7 7.\n\nDefinition _set_StatusReg_KX (r_ref : register_ref regstate register_value StatusReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       StatusReg_StatusReg_chunk_0 :=\n         (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 7 7 (subrange_vec_dec v 0 0)) ]}\n      : StatusReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_StatusReg_KX (v : StatusReg) (x : mword 1) : StatusReg :=\n   {[ v with\n     StatusReg_StatusReg_chunk_0 :=\n       (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 7 7 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_StatusReg_SX (v : StatusReg) : mword 1 :=\n   subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 6 6.\n\nDefinition _set_StatusReg_SX (r_ref : register_ref regstate register_value StatusReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       StatusReg_StatusReg_chunk_0 :=\n         (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 6 6 (subrange_vec_dec v 0 0)) ]}\n      : StatusReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_StatusReg_SX (v : StatusReg) (x : mword 1) : StatusReg :=\n   {[ v with\n     StatusReg_StatusReg_chunk_0 :=\n       (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 6 6 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_StatusReg_UX (v : StatusReg) : mword 1 :=\n   subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 5 5.\n\nDefinition _set_StatusReg_UX (r_ref : register_ref regstate register_value StatusReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       StatusReg_StatusReg_chunk_0 :=\n         (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 5 5 (subrange_vec_dec v 0 0)) ]}\n      : StatusReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_StatusReg_UX (v : StatusReg) (x : mword 1) : StatusReg :=\n   {[ v with\n     StatusReg_StatusReg_chunk_0 :=\n       (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 5 5 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_StatusReg_KSU (v : StatusReg) : mword 2 :=\n   subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 4 3.\n\nDefinition _set_StatusReg_KSU (r_ref : register_ref regstate register_value StatusReg) (v : mword 2)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       StatusReg_StatusReg_chunk_0 :=\n         (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 4 3 (subrange_vec_dec v 1 0)) ]}\n      : StatusReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_StatusReg_KSU (v : StatusReg) (x : mword 2) : StatusReg :=\n   {[ v with\n     StatusReg_StatusReg_chunk_0 :=\n       (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 4 3 (subrange_vec_dec x 1 0)) ]}.\n\nDefinition _get_StatusReg_ERL (v : StatusReg) : mword 1 :=\n   subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 2 2.\n\nDefinition _set_StatusReg_ERL (r_ref : register_ref regstate register_value StatusReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       StatusReg_StatusReg_chunk_0 :=\n         (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 2 2 (subrange_vec_dec v 0 0)) ]}\n      : StatusReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_StatusReg_ERL (v : StatusReg) (x : mword 1) : StatusReg :=\n   {[ v with\n     StatusReg_StatusReg_chunk_0 :=\n       (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 2 2 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_StatusReg_EXL (v : StatusReg) : mword 1 :=\n   subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 1 1.\n\nDefinition _set_StatusReg_EXL (r_ref : register_ref regstate register_value StatusReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       StatusReg_StatusReg_chunk_0 :=\n         (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 1 1 (subrange_vec_dec v 0 0)) ]}\n      : StatusReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_StatusReg_EXL (v : StatusReg) (x : mword 1) : StatusReg :=\n   {[ v with\n     StatusReg_StatusReg_chunk_0 :=\n       (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 1 1 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition _get_StatusReg_IE (v : StatusReg) : mword 1 :=\n   subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 0 0.\n\nDefinition _set_StatusReg_IE (r_ref : register_ref regstate register_value StatusReg) (v : mword 1)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       StatusReg_StatusReg_chunk_0 :=\n         (update_subrange_vec_dec r.(StatusReg_StatusReg_chunk_0) 0 0 (subrange_vec_dec v 0 0)) ]}\n      : StatusReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_StatusReg_IE (v : StatusReg) (x : mword 1) : StatusReg :=\n   {[ v with\n     StatusReg_StatusReg_chunk_0 :=\n       (update_subrange_vec_dec v.(StatusReg_StatusReg_chunk_0) 0 0 (subrange_vec_dec x 0 0)) ]}.\n\nDefinition execute_branch_mips (pc : mword 64) : M (unit) :=\n   write_reg DelayedPC_ref pc >>\n   write_reg BranchPending_ref ('b\"1\"  : mword 1) >>\n   write_reg NextInBranchDelay_ref ('b\"1\"  : mword 1)\n    : M (unit).\n\nDefinition NotWordVal (word : mword 64) : bool :=\n   neq_vec (zopz0zQzQ (cast_unit_vec (access_vec_dec word 31)) 32) (subrange_vec_dec word 63 32).\n\nDefinition rGPR (idx : mword 5) : M (mword 64) :=\n   let i := projT1 (uint idx) in\n   (if sumbool_of_bool (Z.eqb i 0) then returnm (Ox\"0000000000000000\"  : mword 64)\n    else read_reg GPR_ref >>= fun w__0 : vec (mword 64) 32 => returnm (vec_access_dec w__0 i))\n    : M (mword 64).\n\nDefinition wGPR (idx : mword 5) (v : mword 64) : M (unit) :=\n   let i := projT1 (uint idx) in\n   (if sumbool_of_bool (projT1 (neq_int i 0)) then\n      let '_ :=\n        (if sumbool_of_bool trace then\n           let '_ := (prerr (string_of_int i))  : unit in\n           prerr_bits \" <- \" v\n         else tt)\n         : unit in\n      read_reg GPR_ref >>= fun w__0 : vec (mword 64) 32 =>\n      write_reg GPR_ref (vec_update_dec w__0 i v)\n       : M (unit)\n    else returnm tt)\n    : M (unit).\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nDefinition Exception_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 18))} : Exception :=\n   let l__140 := arg_ in\n   if sumbool_of_bool (Z.eqb l__140 0) then Interrupt\n   else if sumbool_of_bool (Z.eqb l__140 1) then TLBMod\n   else if sumbool_of_bool (Z.eqb l__140 2) then TLBL\n   else if sumbool_of_bool (Z.eqb l__140 3) then TLBS\n   else if sumbool_of_bool (Z.eqb l__140 4) then AdEL\n   else if sumbool_of_bool (Z.eqb l__140 5) then AdES\n   else if sumbool_of_bool (Z.eqb l__140 6) then Sys\n   else if sumbool_of_bool (Z.eqb l__140 7) then Bp\n   else if sumbool_of_bool (Z.eqb l__140 8) then ResI\n   else if sumbool_of_bool (Z.eqb l__140 9) then CpU\n   else if sumbool_of_bool (Z.eqb l__140 10) then Ov\n   else if sumbool_of_bool (Z.eqb l__140 11) then Tr\n   else if sumbool_of_bool (Z.eqb l__140 12) then C2E\n   else if sumbool_of_bool (Z.eqb l__140 13) then C2Trap\n   else if sumbool_of_bool (Z.eqb l__140 14) then XTLBRefillL\n   else if sumbool_of_bool (Z.eqb l__140 15) then XTLBRefillS\n   else if sumbool_of_bool (Z.eqb l__140 16) then XTLBInvL\n   else if sumbool_of_bool (Z.eqb l__140 17) then XTLBInvS\n   else MCheck.\n\nDefinition num_of_Exception (arg_ : Exception) : {e : Z & ArithFact ((0 <=? e) && (e <=? 18))} :=\n   build_ex (\n      match arg_ with\n      | Interrupt => 0\n      | TLBMod => 1\n      | TLBL => 2\n      | TLBS => 3\n      | AdEL => 4\n      | AdES => 5\n      | Sys => 6\n      | Bp => 7\n      | ResI => 8\n      | CpU => 9\n      | Ov => 10\n      | Tr => 11\n      | C2E => 12\n      | C2Trap => 13\n      | XTLBRefillL => 14\n      | XTLBRefillS => 15\n      | XTLBInvL => 16\n      | XTLBInvS => 17\n      | MCheck => 18\n      end\n   ).\n\nDefinition undefined_Exception '(tt : unit) : M (Exception) :=\n   (internal_pick\n      [Interrupt;\n      TLBMod;\n      TLBL;\n      TLBS;\n      AdEL;\n      AdES;\n      Sys;\n      Bp;\n      ResI;\n      CpU;\n      Ov;\n      Tr;\n      C2E;\n      C2Trap;\n      XTLBRefillL;\n      XTLBRefillS;\n      XTLBInvL;\n      XTLBInvS;\n      MCheck])\n    : M (Exception).\n\nDefinition ExceptionCode (ex : Exception) : mword 5 :=\n   let x : bits 8 :=\n     match ex with\n     | Interrupt => Ox\"00\"  : mword 8\n     | TLBMod => Ox\"01\"  : mword 8\n     | TLBL => Ox\"02\"  : mword 8\n     | TLBS => Ox\"03\"  : mword 8\n     | AdEL => Ox\"04\"  : mword 8\n     | AdES => Ox\"05\"  : mword 8\n     | Sys => Ox\"08\"  : mword 8\n     | Bp => Ox\"09\"  : mword 8\n     | ResI => Ox\"0A\"  : mword 8\n     | CpU => Ox\"0B\"  : mword 8\n     | Ov => Ox\"0C\"  : mword 8\n     | Tr => Ox\"0D\"  : mword 8\n     | C2E => Ox\"12\"  : mword 8\n     | C2Trap => Ox\"12\"  : mword 8\n     | XTLBRefillL => Ox\"02\"  : mword 8\n     | XTLBRefillS => Ox\"03\"  : mword 8\n     | XTLBInvL => Ox\"02\"  : mword 8\n     | XTLBInvS => Ox\"03\"  : mword 8\n     | MCheck => Ox\"18\"  : mword 8\n     end in\n   subrange_vec_dec x 4 0.\n\nDefinition string_of_exception (ex : Exception) : string :=\n   match ex with\n   | Interrupt => \"Interrupt\"\n   | TLBMod => \"TLBMod\"\n   | TLBL => \"TLBL\"\n   | TLBS => \"TLBS\"\n   | AdEL => \"AdEL\"\n   | AdES => \"AdES\"\n   | Sys => \"Sys\"\n   | Bp => \"Bp  \"\n   | ResI => \"ResI\"\n   | CpU => \"CpU\"\n   | Ov => \"Ov\"\n   | Tr => \"Tr\"\n   | C2E => \"C2E\"\n   | C2Trap => \"C2Trap\"\n   | XTLBRefillL => \"XTLBRefillL\"\n   | XTLBRefillS => \"XTLBRefillS\"\n   | XTLBInvL => \"XTLBInvL\"\n   | XTLBInvS => \"XTLBInvS\"\n   | MCheck => \"MCheck\"\n   end.\n\nDefinition traceException (ex : Exception) : unit :=\n   if sumbool_of_bool trace then\n     let '_ := (prerr \" EXCEPTION \")  : unit in\n     prerr_endline (string_of_exception ex)\n   else tt.\n\nDefinition exceptionVectorOffset (ex : Exception) : M (mword 12) :=\n   read_reg CP0Status_ref >>= fun w__0 : StatusReg =>\n   returnm (if (bits_to_bool (_get_StatusReg_EXL w__0))  : bool then Ox\"180\"  : mword 12\n            else if orb (generic_eq ex XTLBRefillL) (generic_eq ex XTLBRefillS) then\n              Ox\"080\"\n               : mword 12\n            else if generic_eq ex C2Trap then Ox\"280\"  : mword 12\n            else Ox\"180\"  : mword 12).\n\nDefinition exceptionVectorBase '(tt : unit) : M (mword 64) :=\n   read_reg CP0Status_ref >>= fun w__0 : StatusReg =>\n   returnm (if (bits_to_bool (_get_StatusReg_BEV w__0))  : bool then\n              Ox\"FFFFFFFFBFC00200\"\n               : mword 64\n            else Ox\"FFFFFFFF80000000\"  : mword 64).\n\nDefinition updateBadInstr '(tt : unit) : M (unit) :=\n   ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n   (if (bit_to_bool (access_vec_dec w__0 0))  : bool then\n      ((read_reg LastInstrBits_ref)  : M (mword 32)) >>= fun w__1 : mword 32 =>\n      write_reg CP0BadInstrP_ref w__1\n       : M (unit)\n    else returnm tt) >>\n   ((read_reg CurrentInstrBits_ref)  : M (mword 32)) >>= fun w__2 : mword 32 =>\n   write_reg CP0BadInstr_ref w__2\n    : M (unit).\n\nDefinition undefined_Capability '(tt : unit) : M (Capability) :=\n   (undefined_bool tt) >>= fun w__0 : bool =>\n   (undefined_bitvector 4) >>= fun w__1 : mword 4 =>\n   (undefined_bool tt) >>= fun w__2 : bool =>\n   (undefined_bool tt) >>= fun w__3 : bool =>\n   (undefined_bool tt) >>= fun w__4 : bool =>\n   (undefined_bool tt) >>= fun w__5 : bool =>\n   (undefined_bool tt) >>= fun w__6 : bool =>\n   (undefined_bool tt) >>= fun w__7 : bool =>\n   (undefined_bool tt) >>= fun w__8 : bool =>\n   (undefined_bool tt) >>= fun w__9 : bool =>\n   (undefined_bool tt) >>= fun w__10 : bool =>\n   (undefined_bool tt) >>= fun w__11 : bool =>\n   (undefined_bool tt) >>= fun w__12 : bool =>\n   (undefined_bool tt) >>= fun w__13 : bool =>\n   (undefined_bitvector 3) >>= fun w__14 : mword 3 =>\n   (undefined_bool tt) >>= fun w__15 : bool =>\n   (undefined_bitvector 6) >>= fun w__16 : mword 6 =>\n   (undefined_bool tt) >>= fun w__17 : bool =>\n   (undefined_bitvector 14) >>= fun w__18 : mword 14 =>\n   (undefined_bitvector 14) >>= fun w__19 : mword 14 =>\n   (undefined_bitvector 18) >>= fun w__20 : mword 18 =>\n   (undefined_bitvector 64) >>= fun w__21 : mword 64 =>\n   returnm ({| Capability_tag := w__0; \n               Capability_uperms := w__1; \n               Capability_permit_set_CID := w__2; \n               Capability_access_system_regs := w__3; \n               Capability_permit_unseal := w__4; \n               Capability_permit_ccall := w__5; \n               Capability_permit_seal := w__6; \n               Capability_permit_store_local_cap := w__7; \n               Capability_permit_store_cap := w__8; \n               Capability_permit_load_cap := w__9; \n               Capability_permit_store := w__10; \n               Capability_permit_load := w__11; \n               Capability_permit_execute := w__12; \n               Capability_global := w__13; \n               Capability_reserved := w__14; \n               Capability_internal_e := w__15; \n               Capability_E := w__16; \n               Capability_sealed := w__17; \n               Capability_B := w__18; \n               Capability_T := w__19; \n               Capability_otype := w__20; \n               Capability_address := w__21 |}).\n\nDefinition getCapBounds (c : Capability)\n:\n({rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 64 - 1)))} * {rangevar : Z & ArithFact ((0 <=?\n  rangevar) &&\n  (rangevar <=? (2 ^ 65)))}) :=\n   let E := projT1 (uint c.(Capability_E)) in\n   let a : bits 64 := c.(Capability_address) in\n   let a3 := vector_truncate (shiftr a (Z.add E 11)) 3 in\n   let B3 := vector_truncateLSB c.(Capability_B) 3 in\n   let T3 := vector_truncateLSB c.(Capability_T) 3 in\n   let R3 := sub_vec B3 ('b\"001\"  : mword 3) in\n   let aHi := if zopz0zI_u a3 R3 then 1 else 0 in\n   let bHi := if zopz0zI_u B3 R3 then 1 else 0 in\n   let tHi := if zopz0zI_u T3 R3 then 1 else 0 in\n   let correction_base := Z.sub bHi aHi in\n   let correction_top := Z.sub tHi aHi in\n   let a_top := shiftr a (Z.add E 14) in\n   let base : bits 65 :=\n     vector_truncate\n       (concat_vec (add_vec_int a_top correction_base) (concat_vec c.(Capability_B) (zeros E))) 65 in\n   let top : bits 65 :=\n     vector_truncate\n       (concat_vec (add_vec_int a_top correction_top) (concat_vec c.(Capability_T) (zeros E))) 65 in\n   let top : mword 65 :=\n     if eq_bit (access_vec_dec base 64) B1 then\n       update_vec_dec top 64 (if sumbool_of_bool (andb (Z.eqb aHi 1) (Z.eqb tHi 1)) then B1 else B0)\n     else top in\n   (build_ex\n   (projT1\n    (uint (subrange_vec_dec base 63 0))), build_ex\n   (projT1\n    (uint top))).\n\nDefinition getCapBase (c : Capability)\n: {rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 64 - 1)))} :=\n   build_ex (\n      let '(existT _ base _, existT _ _ _) := getCapBounds c in\n      base\n   ).\n\nDefinition capBoundsEqual (c1 : Capability) (c2 : Capability) : bool :=\n   let '(existT _ base1 _, existT _ top1 _) := getCapBounds c1 in\n   let '(existT _ base2 _, existT _ top2 _) := getCapBounds c2 in\n   andb (Z.eqb base1 base2) (Z.eqb top1 top2).\n\nDefinition setCapOffset (c : Capability) (offset : mword 64) : (bool * Capability) :=\n   let base64 : bits 64 := to_bits 64 (projT1 (getCapBase c)) in\n   let newAddress : bits 64 := add_vec base64 offset in\n   let newCap := {[ c with Capability_address := newAddress ]} in\n   let representable := capBoundsEqual c newCap in\n   (representable, newCap).\n\nDefinition set_next_pcc (newPCC : Capability) : M (unit) :=\n   write_reg NextPCC_ref newPCC >> write_reg DelayedPCC_ref newPCC  : M (unit).\n\nDefinition unrepCap (cap : Capability) : Capability := {[ cap with Capability_tag := false ]}.\n\nDefinition SignalException {o : Type} (ex : Exception) : M (o) :=\n   let '_ := (traceException ex)  : unit in\n   read_reg CP0Status_ref >>= fun w__0 : StatusReg =>\n   (if negb (bits_to_bool (_get_StatusReg_EXL w__0)) then\n      ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__1 : mword 1 =>\n      (if (bit_to_bool (access_vec_dec w__1 0))  : bool then\n         (_set_CauseReg_BD CP0Cause_ref ('b\"1\"  : mword 1)) >>\n         ((read_reg PC_ref)  : M (mword 64)) >>= fun w__2 : mword 64 => returnm (sub_vec_int w__2 4)\n       else\n         (_set_CauseReg_BD CP0Cause_ref ('b\"0\"  : mword 1)) >>\n         ((read_reg PC_ref)  : M (mword 64))\n          : M (mword 64)) >>= fun epc : bits 64 =>\n      read_reg PCC_ref >>= fun w__4 : Capability =>\n      let '(representable, newEPCC) := setCapOffset w__4 epc in\n      let '_ :=\n        (if sumbool_of_bool (negb representable) then print_endline \"UNREPRESENTABLE EPCC!\"\n         else tt)\n         : unit in\n      let '_ := (if newEPCC.(Capability_sealed) then print_endline \"SEALED PCC!\" else tt)  : unit in\n      write_reg\n        EPCC_ref\n        (if sumbool_of_bool (andb representable (negb newEPCC.(Capability_sealed))) then newEPCC\n         else unrepCap newEPCC)\n       : M (unit)\n    else returnm tt) >>\n   (updateBadInstr tt) >>\n   (exceptionVectorOffset ex) >>= fun vectorOffset =>\n   (exceptionVectorBase tt) >>= fun vectorBase =>\n   read_reg KCC_ref >>= fun w__5 : Capability =>\n   let kccBase := projT1 (getCapBase w__5) in\n   write_reg\n     NextPC_ref\n     (sub_vec (add_vec vectorBase (mips_zero_extend 64 vectorOffset)) (to_bits 64 kccBase)) >>\n   read_reg KCC_ref >>= fun w__6 : Capability =>\n   (set_next_pcc w__6) >>\n   (_set_CauseReg_ExcCode CP0Cause_ref (ExceptionCode ex)) >>\n   (_set_StatusReg_EXL CP0Status_ref ('b\"1\"  : mword 1)) >> throw (ISAException tt).\n\nDefinition SignalExceptionBadAddr {o : Type} (ex : Exception) (badAddr : mword 64) : M (o) :=\n   write_reg CP0BadVAddr_ref badAddr >> (SignalException ex)  : M (o).\n\nDefinition SignalExceptionTLB {o : Type} (ex : Exception) (badAddr : mword 64) : M (o) :=\n   write_reg CP0BadVAddr_ref badAddr >>\n   (_set_ContextReg_BadVPN2 TLBContext_ref (subrange_vec_dec badAddr 31 13)) >>\n   (_set_XContextReg_XBadVPN2 TLBXContext_ref (subrange_vec_dec badAddr 39 13)) >>\n   (_set_XContextReg_XR TLBXContext_ref (subrange_vec_dec badAddr 63 62)) >>\n   (_set_TLBEntryHiReg_R TLBEntryHi_ref (subrange_vec_dec badAddr 63 62)) >>\n   (_set_TLBEntryHiReg_VPN2 TLBEntryHi_ref (subrange_vec_dec badAddr 39 13)) >>\n   (SignalException ex)\n    : M (o).\n\nDefinition MemAccessType_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 2))}\n: MemAccessType :=\n   let l__138 := arg_ in\n   if sumbool_of_bool (Z.eqb l__138 0) then Instruction\n   else if sumbool_of_bool (Z.eqb l__138 1) then LoadData\n   else StoreData.\n\nDefinition num_of_MemAccessType (arg_ : MemAccessType)\n: {e : Z & ArithFact ((0 <=? e) && (e <=? 2))} :=\n   build_ex (match arg_ with | Instruction => 0 | LoadData => 1 | StoreData => 2 end).\n\nDefinition undefined_MemAccessType '(tt : unit) : M (MemAccessType) :=\n   (internal_pick [Instruction; LoadData; StoreData])  : M (MemAccessType).\n\nDefinition MemAccessCapRestriction_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 2))}\n: MemAccessCapRestriction :=\n   let l__136 := arg_ in\n   if sumbool_of_bool (Z.eqb l__136 0) then Unrestricted\n   else if sumbool_of_bool (Z.eqb l__136 1) then Trap\n   else Clear.\n\nDefinition num_of_MemAccessCapRestriction (arg_ : MemAccessCapRestriction)\n: {e : Z & ArithFact ((0 <=? e) && (e <=? 2))} :=\n   build_ex (match arg_ with | Unrestricted => 0 | Trap => 1 | Clear => 2 end).\n\nDefinition undefined_MemAccessCapRestriction '(tt : unit) : M (MemAccessCapRestriction) :=\n   (internal_pick [Unrestricted; Trap; Clear])  : M (MemAccessCapRestriction).\n\nDefinition AccessLevel_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 2))} : AccessLevel :=\n   let l__134 := arg_ in\n   if sumbool_of_bool (Z.eqb l__134 0) then User\n   else if sumbool_of_bool (Z.eqb l__134 1) then Supervisor\n   else Kernel.\n\nDefinition num_of_AccessLevel (arg_ : AccessLevel) : {e : Z & ArithFact ((0 <=? e) && (e <=? 2))} :=\n   build_ex (match arg_ with | User => 0 | Supervisor => 1 | Kernel => 2 end).\n\nDefinition undefined_AccessLevel '(tt : unit) : M (AccessLevel) :=\n   (internal_pick [User; Supervisor; Kernel])  : M (AccessLevel).\n\nDefinition int_of_AccessLevel (level : AccessLevel)\n: {n : Z & ArithFact (member_Z_list n [0; 1; 2])} :=\n   build_ex (match level with | User => 0 | Supervisor => 1 | Kernel => 2 end).\n\nDefinition grantsAccess (currentLevel : AccessLevel) (requiredLevel : AccessLevel) : bool :=\n   Z.geb (projT1 (int_of_AccessLevel currentLevel)) (projT1 (int_of_AccessLevel requiredLevel)).\n\nDefinition getAccessLevel '(tt : unit) : M (AccessLevel) :=\n   (or_boolM\n      (read_reg CP0Status_ref >>= fun w__0 : StatusReg =>\n       returnm ((bits_to_bool (_get_StatusReg_EXL w__0))  : bool))\n      (read_reg CP0Status_ref >>= fun w__1 : StatusReg =>\n       returnm ((bits_to_bool (_get_StatusReg_ERL w__1))  : bool))) >>= fun w__2 : bool =>\n   (if sumbool_of_bool w__2 then returnm Kernel\n    else\n      read_reg CP0Status_ref >>= fun w__3 : StatusReg =>\n      let p__158 := _get_StatusReg_KSU w__3 in\n      let b__0 := p__158 in\n      returnm (if eq_vec b__0 ('b\"00\"  : mword 2) then Kernel\n               else if eq_vec b__0 ('b\"01\"  : mword 2) then Supervisor\n               else if eq_vec b__0 ('b\"10\"  : mword 2) then User\n               else User))\n    : M (AccessLevel).\n\nDefinition pcc_access_system_regs '(tt : unit) : M (bool) :=\n   read_reg PCC_ref >>= fun w__0 : Capability => returnm w__0.(Capability_access_system_regs).\n\nDefinition undefined_CapCauseReg '(tt : unit) : M (CapCauseReg) :=\n   (undefined_bitvector 16) >>= fun w__0 : mword 16 =>\n   returnm ({| CapCauseReg_CapCauseReg_chunk_0 := w__0 |}).\n\nDefinition CapExCode (ex : CapEx) : mword 8 :=\n   match ex with\n   | CapEx_None => Ox\"00\"  : mword 8\n   | CapEx_LengthViolation => Ox\"01\"  : mword 8\n   | CapEx_TagViolation => Ox\"02\"  : mword 8\n   | CapEx_SealViolation => Ox\"03\"  : mword 8\n   | CapEx_TypeViolation => Ox\"04\"  : mword 8\n   | CapEx_CallTrap => Ox\"05\"  : mword 8\n   | CapEx_ReturnTrap => Ox\"06\"  : mword 8\n   | CapEx_TSSUnderFlow => Ox\"07\"  : mword 8\n   | CapEx_UserDefViolation => Ox\"08\"  : mword 8\n   | CapEx_TLBNoStoreCap => Ox\"09\"  : mword 8\n   | CapEx_InexactBounds => Ox\"0A\"  : mword 8\n   | CapEx_TLBLoadCap => Ox\"0C\"  : mword 8\n   | CapEx_GlobalViolation => Ox\"10\"  : mword 8\n   | CapEx_PermitExecuteViolation => Ox\"11\"  : mword 8\n   | CapEx_PermitLoadViolation => Ox\"12\"  : mword 8\n   | CapEx_PermitStoreViolation => Ox\"13\"  : mword 8\n   | CapEx_PermitLoadCapViolation => Ox\"14\"  : mword 8\n   | CapEx_PermitStoreCapViolation => Ox\"15\"  : mword 8\n   | CapEx_PermitStoreLocalCapViolation => Ox\"16\"  : mword 8\n   | CapEx_PermitSealViolation => Ox\"17\"  : mword 8\n   | CapEx_AccessSystemRegsViolation => Ox\"18\"  : mword 8\n   | CapEx_PermitCCallViolation => Ox\"19\"  : mword 8\n   | CapEx_AccessCCallIDCViolation => Ox\"1A\"  : mword 8\n   | CapEx_PermitUnsealViolation => Ox\"1B\"  : mword 8\n   | CapEx_PermitSetCIDViolation => Ox\"1C\"  : mword 8\n   end.\n\nDefinition _set_CapCauseReg_ExcCode\n(r_ref : register_ref regstate register_value CapCauseReg) (v : mword 8)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       CapCauseReg_CapCauseReg_chunk_0 :=\n         (update_subrange_vec_dec r.(CapCauseReg_CapCauseReg_chunk_0) 15 8 (subrange_vec_dec v 7 0)) ]}\n      : CapCauseReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _set_CapCauseReg_RegNum\n(r_ref : register_ref regstate register_value CapCauseReg) (v : mword 8)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       CapCauseReg_CapCauseReg_chunk_0 :=\n         (update_subrange_vec_dec r.(CapCauseReg_CapCauseReg_chunk_0) 7 0 (subrange_vec_dec v 7 0)) ]}\n      : CapCauseReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition string_of_capex (ex : CapEx) : string :=\n   match ex with\n   | CapEx_None => \"None\"\n   | CapEx_LengthViolation => \"LengthViolation\"\n   | CapEx_TagViolation => \"TagViolation\"\n   | CapEx_SealViolation => \"SealViolation\"\n   | CapEx_TypeViolation => \"TypeViolation\"\n   | CapEx_CallTrap => \"CallTrap\"\n   | CapEx_ReturnTrap => \"ReturnTrap\"\n   | CapEx_TSSUnderFlow => \"TSSUnderFlow\"\n   | CapEx_UserDefViolation => \"UserDefViolation\"\n   | CapEx_TLBNoStoreCap => \"TLBNoStoreCap\"\n   | CapEx_InexactBounds => \"InexactBounds\"\n   | CapEx_GlobalViolation => \"GlobalViolation\"\n   | CapEx_PermitExecuteViolation => \"PermitExecuteViolation\"\n   | CapEx_PermitLoadViolation => \"PermitLoadViolation\"\n   | CapEx_PermitStoreViolation => \"PermitStoreViolation\"\n   | CapEx_PermitLoadCapViolation => \"PermitLoadCapViolation\"\n   | CapEx_PermitStoreCapViolation => \"PermitStoreCapViolation\"\n   | CapEx_PermitStoreLocalCapViolation => \"PermitStoreLocalCapViolation\"\n   | CapEx_PermitSealViolation => \"PermitSealViolation\"\n   | CapEx_AccessSystemRegsViolation => \"AccessSystemRegsViolation\"\n   | CapEx_PermitCCallViolation => \"PermitCCallViolation\"\n   | CapEx_AccessCCallIDCViolation => \"AccessCCallIDCViolation\"\n   | CapEx_PermitUnsealViolation => \"PermitUnsealViolation\"\n   | CapEx_PermitSetCIDViolation => \"PermitSetCIDViolation\"\n   | CapEx_TLBLoadCap => \"TLBLoadCap\"\n   end.\n\nDefinition raise_c2_exception8 {o : Type} (capEx : CapEx) (regnum : mword 8) : M (o) :=\n   let '_ :=\n     (if sumbool_of_bool trace then\n        let '_ := (prerr \" C2Ex \")  : unit in\n        let '_ := (prerr (string_of_capex capEx))  : unit in\n        let '_ := (prerr \" reg: \")  : unit in\n        prerr_endline (string_of_bits regnum)\n      else tt)\n      : unit in\n   (_set_CapCauseReg_ExcCode CapCause_ref (CapExCode capEx)) >>\n   (_set_CapCauseReg_RegNum CapCause_ref regnum) >>\n   let mipsEx :=\n     if orb (generic_eq capEx CapEx_CallTrap) (generic_eq capEx CapEx_ReturnTrap) then C2Trap\n     else C2E in\n   (SignalException mipsEx)\n    : M (o).\n\nDefinition raise_c2_exception_noreg {o : Type} (capEx : CapEx) : M (o) :=\n   (raise_c2_exception8 capEx (Ox\"FF\"  : mword 8))  : M (o).\n\nDefinition checkCP0AccessHook '(tt : unit) : M (unit) :=\n   (pcc_access_system_regs tt) >>= fun w__0 : bool =>\n   (if sumbool_of_bool (negb w__0) then\n      (raise_c2_exception_noreg CapEx_AccessSystemRegsViolation)\n       : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition checkCP0Access '(tt : unit) : M (unit) :=\n   (getAccessLevel tt) >>= fun accessLevel =>\n   (and_boolM (returnm ((generic_neq accessLevel Kernel)  : bool))\n      (read_reg CP0Status_ref >>= fun w__0 : StatusReg =>\n       returnm ((negb (bit_to_bool (access_vec_dec (_get_StatusReg_CU w__0) 0)))  : bool))) >>= fun w__1 : bool =>\n   (if sumbool_of_bool w__1 then\n      (_set_CauseReg_CE CP0Cause_ref ('b\"00\"  : mword 2)) >> (SignalException CpU)  : M (unit)\n    else returnm tt) >>\n   (checkCP0AccessHook tt)\n    : M (unit).\n\nDefinition incrementCP0Count '(tt : unit) : M (unit) :=\n   ((read_reg TLBRandom_ref)  : M (mword 6)) >>= fun w__0 : mword 6 =>\n   ((read_reg TLBWired_ref)  : M (mword 6)) >>= fun w__1 : mword 6 =>\n   (if eq_vec w__0 w__1 then returnm TLBIndexMax\n    else\n      ((read_reg TLBRandom_ref)  : M (mword 6)) >>= fun w__2 : mword 6 =>\n      returnm (sub_vec_int w__2 1)) >>= fun w__3 : mword 6 =>\n   write_reg TLBRandom_ref w__3 >>\n   ((read_reg CP0Count_ref)  : M (mword 32)) >>= fun w__4 : mword 32 =>\n   write_reg CP0Count_ref (add_vec_int w__4 1) >>\n   ((read_reg CP0Count_ref)  : M (mword 32)) >>= fun w__5 : mword 32 =>\n   ((read_reg CP0Compare_ref)  : M (mword 32)) >>= fun w__6 : mword 32 =>\n   (if eq_vec w__5 w__6 then\n      read_reg CP0Cause_ref >>= fun w__7 : CauseReg =>\n      (_set_CauseReg_IP CP0Cause_ref (or_vec (_get_CauseReg_IP w__7) (Ox\"80\"  : mword 8)))\n       : M (unit)\n    else returnm tt) >>\n   read_reg CP0Status_ref >>= fun w__8 : StatusReg =>\n   let ims := _get_StatusReg_IM w__8 in\n   read_reg CP0Cause_ref >>= fun w__9 : CauseReg =>\n   let ips := _get_CauseReg_IP w__9 in\n   read_reg CP0Status_ref >>= fun w__10 : StatusReg =>\n   let ie := _get_StatusReg_IE w__10 in\n   read_reg CP0Status_ref >>= fun w__11 : StatusReg =>\n   let exl := _get_StatusReg_EXL w__11 in\n   read_reg CP0Status_ref >>= fun w__12 : StatusReg =>\n   let erl := _get_StatusReg_ERL w__12 in\n   (if andb (negb (bits_to_bool exl))\n         (andb (negb (bits_to_bool erl))\n            (andb (bits_to_bool ie) (neq_vec (and_vec ips ims) (Ox\"00\"  : mword 8)))) then\n      (SignalException Interrupt)\n       : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition strReg (r : mword 5) : string := concat_str_dec \"$\" (projT1 (uint r)).\n\nDefinition strRRRArgs (r2 : mword 5) (r1 : mword 5) (rd : mword 5) : string :=\n   String.append (strReg rd)\n     (String.append \", \" (String.append (strReg r1) (String.append \", \" (strReg r2)))).\n\nDefinition strRRIArgs {n : Z} (rs : mword 5) (rd : mword 5) (imm : mword n) `{ArithFact (n >? 0)}\n: string :=\n   String.append (strReg rd)\n     (String.append \", \"\n        (String.append (strReg rs) (String.append \", \" (dec_str (projT1 (sint imm)))))).\n\nDefinition strRRIUArgs {n : Z} (rs : mword 5) (rd : mword 5) (imm : mword n) `{ArithFact (n >? 0)}\n: string :=\n   String.append (strReg rd)\n     (String.append \", \"\n        (String.append (strReg rs) (String.append \", \" (hex_str (projT1 (uint imm)))))).\n\nDefinition strRIArgs {n : Z} (rd : mword 5) (imm : mword n) `{ArithFact (n >? 0)} : string :=\n   String.append (strReg rd) (String.append \", \" (hex_str (projT1 (uint imm)))).\n\nDefinition strMemArgs {n : Z} (base : mword 5) (rt : mword 5) (offset : mword n)\n`{ArithFact (n >? 0)}\n: string :=\n   String.append (strReg rt)\n     (String.append \", \"\n        (String.append (dec_str (projT1 (sint offset)))\n           (String.append \"(\" (String.append (strReg base) \")\")))).\n\nDefinition decode_failure_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 3))}\n: decode_failure :=\n   let l__131 := arg_ in\n   if sumbool_of_bool (Z.eqb l__131 0) then no_matching_pattern\n   else if sumbool_of_bool (Z.eqb l__131 1) then unsupported_instruction\n   else if sumbool_of_bool (Z.eqb l__131 2) then illegal_instruction\n   else internal_error.\n\nDefinition num_of_decode_failure (arg_ : decode_failure)\n: {e : Z & ArithFact ((0 <=? e) && (e <=? 3))} :=\n   build_ex (\n      match arg_ with\n      | no_matching_pattern => 0\n      | unsupported_instruction => 1\n      | illegal_instruction => 2\n      | internal_error => 3\n      end\n   ).\n\nDefinition undefined_decode_failure '(tt : unit) : M (decode_failure) :=\n   (internal_pick\n      [no_matching_pattern;\n      unsupported_instruction;\n      illegal_instruction;\n      internal_error])\n    : M (decode_failure).\n\nDefinition Comparison_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 7))} : Comparison :=\n   let l__124 := arg_ in\n   if sumbool_of_bool (Z.eqb l__124 0) then EQ'\n   else if sumbool_of_bool (Z.eqb l__124 1) then NE\n   else if sumbool_of_bool (Z.eqb l__124 2) then GE\n   else if sumbool_of_bool (Z.eqb l__124 3) then GEU\n   else if sumbool_of_bool (Z.eqb l__124 4) then GT'\n   else if sumbool_of_bool (Z.eqb l__124 5) then LE\n   else if sumbool_of_bool (Z.eqb l__124 6) then LT'\n   else LTU.\n\nDefinition num_of_Comparison (arg_ : Comparison) : {e : Z & ArithFact ((0 <=? e) && (e <=? 7))} :=\n   build_ex (\n      match arg_ with\n      | EQ' => 0\n      | NE => 1\n      | GE => 2\n      | GEU => 3\n      | GT' => 4\n      | LE => 5\n      | LT' => 6\n      | LTU => 7\n      end\n   ).\n\nDefinition undefined_Comparison '(tt : unit) : M (Comparison) :=\n   (internal_pick [EQ'; NE; GE; GEU; GT'; LE; LT'; LTU])  : M (Comparison).\n\nDefinition strCmp (cmp : Comparison) : string :=\n   match cmp with\n   | EQ' => \"eq\"\n   | NE => \"ne\"\n   | GE => \"ge\"\n   | GEU => \"geu\"\n   | GT' => \"gt\"\n   | LE => \"le\"\n   | LT' => \"lt\"\n   | LTU => \"ltu\"\n   end.\n\nDefinition compare (cmp : Comparison) (valA : mword 64) (valB : mword 64) : bool :=\n   match cmp with\n   | EQ' => eq_vec valA valB\n   | NE => neq_vec valA valB\n   | GE => zopz0zKzJ_s valA valB\n   | GEU => zopz0zKzJ_u valA valB\n   | GT' => zopz0zI_s valB valA\n   | LE => zopz0zKzJ_s valB valA\n   | LT' => zopz0zI_s valA valB\n   | LTU => zopz0zI_u valA valB\n   end.\n\nDefinition WordType_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 3))} : WordType :=\n   let l__121 := arg_ in\n   if sumbool_of_bool (Z.eqb l__121 0) then B\n   else if sumbool_of_bool (Z.eqb l__121 1) then H\n   else if sumbool_of_bool (Z.eqb l__121 2) then W\n   else D.\n\nDefinition num_of_WordType (arg_ : WordType) : {e : Z & ArithFact ((0 <=? e) && (e <=? 3))} :=\n   build_ex (match arg_ with | B => 0 | H => 1 | W => 2 | D => 3 end).\n\nDefinition undefined_WordType '(tt : unit) : M (WordType) :=\n   (internal_pick [B; H; W; D])  : M (WordType).\n\nDefinition WordTypeUnaligned_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 3))}\n: WordTypeUnaligned :=\n   let l__118 := arg_ in\n   if sumbool_of_bool (Z.eqb l__118 0) then WL\n   else if sumbool_of_bool (Z.eqb l__118 1) then WR\n   else if sumbool_of_bool (Z.eqb l__118 2) then DL\n   else DR.\n\nDefinition num_of_WordTypeUnaligned (arg_ : WordTypeUnaligned)\n: {e : Z & ArithFact ((0 <=? e) && (e <=? 3))} :=\n   build_ex (match arg_ with | WL => 0 | WR => 1 | DL => 2 | DR => 3 end).\n\nDefinition undefined_WordTypeUnaligned '(tt : unit) : M (WordTypeUnaligned) :=\n   (internal_pick [WL; WR; DL; DR])  : M (WordTypeUnaligned).\n\nDefinition strWordType (w : WordType) : string :=\n   match w with | B => \"b\" | H => \"h\" | W => \"w\" | D => \"d\" end.\n\nDefinition unalignedBytesTouched (vAddr : Z) (width : WordTypeUnaligned) : (Z * Z) :=\n   let woffset := projT1 (emod_with_eq vAddr 4) in\n   let doffset := projT1 (emod_with_eq vAddr 8) in\n   match width with\n   | WL => (vAddr, Z.sub 4 woffset)\n   | WR => (Z.sub vAddr woffset, Z.add woffset 1)\n   | DL => (vAddr, Z.sub 8 doffset)\n   | DR => (Z.sub vAddr doffset, Z.add doffset 1)\n   end.\n\nDefinition wordWidthBytes (w : WordType)\n: {rangevar : Z & ArithFact ((1 <=? rangevar) && (rangevar <=? 8))} :=\n   build_ex (match w with | B => 1 | H => 2 | W => 4 | D => 8 end).\n\nDefinition alignment_width := 16.\nHint Unfold alignment_width : sail.\nDefinition isAddressAligned (addr : mword 64) (wordType : WordType) : bool :=\n   let a := projT1 (uint addr) in\n   Z.eqb (projT1 (ediv_with_eq a alignment_width))\n     (projT1\n      (ediv_with_eq (Z.sub (Z.add a (projT1 (wordWidthBytes wordType))) 1) alignment_width)).\n\nDefinition extendLoad {sz : Z} (memResult : mword sz) (sign : bool) `{ArithFact (sz <=? 64)}\n: mword 64 :=\n   if sumbool_of_bool sign then mips_sign_extend 64 memResult else mips_zero_extend 64 memResult.\n\nDefinition MEMr_wrapper (addr : mword 64) (size : Z) `{ArithFact ((1 <=? size) && (size <=? 8))}\n: M (mword (8 * size)) :=\n   (if eq_vec addr (Ox\"000000007F000000\"  : mword 64) then\n      ((read_reg UART_RVALID_ref)  : M (mword 1)) >>= fun rvalid =>\n      write_reg UART_RVALID_ref ('b\"0\"  : mword 1) >>\n      ((read_reg UART_RDATA_ref)  : M (mword 8)) >>= fun w__0 : mword 8 =>\n      returnm (mask (Z.mul 8 (projT1 (__id size)))\n                 (concat_vec (Ox\"00000000\"  : mword 32)\n                    (concat_vec w__0\n                       (concat_vec rvalid\n                          (concat_vec ('b\"0000000\"  : mword 7) (Ox\"0000\"  : mword 16))))))\n    else if eq_vec addr (Ox\"000000007F000004\"  : mword 64) then\n      returnm (mask (Z.mul 8 (projT1 (__id size))) (Ox\"000000000004FFFF\"  : mword 64))\n    else (MEMr addr size) >>= fun w__1 : mword (8 * size) => returnm (reverse_endianness w__1))\n    : M (mword (8 * size)).\n\nDefinition MEMr_reserve_wrapper (addr : mword 64) (size : Z)\n`{ArithFact ((1 <=? size) && (size <=? 8))}\n: M (mword (8 * size)) :=\n   (MEMr_reserve addr size) >>= fun w__0 : mword (8 * size) => returnm (reverse_endianness w__0).\n\nDefinition init_cp0_state '(tt : unit) : M (unit) :=\n   (_set_StatusReg_BEV CP0Status_ref ((cast_unit_vec B1)  : mword 1))  : M (unit).\n\nDefinition tlbEntryMatch (r : mword 2) (vpn2 : mword 27) (asid : mword 8) (entry : TLBEntry) : bool :=\n   let entryValid := _get_TLBEntry_valid entry in\n   let entryR := _get_TLBEntry_r entry in\n   let entryMask := _get_TLBEntry_pagemask entry in\n   let entryVPN := _get_TLBEntry_vpn2 entry in\n   let entryASID := _get_TLBEntry_asid entry in\n   let entryG := _get_TLBEntry_g entry in\n   let vpnMask : bits 27 := not_vec (mips_zero_extend 27 entryMask) in\n   andb (bits_to_bool entryValid)\n     (andb (eq_vec r entryR)\n        (andb (eq_vec (and_vec vpn2 vpnMask) (and_vec entryVPN vpnMask))\n           (orb (eq_vec asid entryASID) (bits_to_bool entryG)))).\n\nDefinition tlbSearch (VAddr : mword 64) : M (option (mword 6)) :=\n   catch_early_return\n     (let r := subrange_vec_dec VAddr 63 62 in\n     let vpn2 := subrange_vec_dec VAddr 39 13 in\n     liftR (read_reg TLBEntryHi_ref) >>= fun w__0 : TLBEntryHiReg =>\n     let asid := _get_TLBEntryHiReg_ASID w__0 in\n     (let loop_idx_lower := 0 in\n     let loop_idx_upper := 63 in\n     (foreach_ZM_up loop_idx_lower loop_idx_upper 1 tt\n       (fun idx _ _ =>\n         liftR ((reg_deref (vec_access_dec TLBEntries idx))) >>= fun w__1 : TLBEntry =>\n         (if tlbEntryMatch r vpn2 asid w__1 then\n            (early_return ((Some (to_bits 6 idx))  : option (mword 6)) : MR unit (option (mword 6)))\n             : MR (unit) _\n          else returnm tt)\n          : MR (unit) _))) >>\n     returnm None).\n\nDefinition MIPSSegmentOf (vAddr : mword 64) : M ((AccessLevel * option (mword 64))) :=\n   let compat32 :=\n     eq_vec (subrange_vec_dec vAddr 61 31)\n       ('b\"1111111111111111111111111111111\"\n        : mword (61 - 31 + 1)) in\n   let b__0 := subrange_vec_dec vAddr 63 62 in\n   (if eq_vec b__0 ('b\"11\"  : mword (63 - 62 + 1)) then\n      returnm (match (compat32, subrange_vec_dec vAddr 30 29) with\n               | (true, b__1) =>\n                  if eq_vec b__1 ('b\"11\"  : mword (30 - 29 + 1)) then\n                    (Kernel, None\n                     : option (bits 64))\n                  else if eq_vec b__1 ('b\"10\"  : mword (30 - 29 + 1)) then\n                    (Supervisor, None\n                     : option (bits 64))\n                  else if eq_vec b__1 ('b\"01\"  : mword (30 - 29 + 1)) then\n                    (Kernel, Some\n                               (concat_vec (Ox\"00000000\"  : mword 32)\n                                  (concat_vec ('b\"000\"  : mword 3) (subrange_vec_dec vAddr 28 0))))\n                  else if eq_vec b__1 ('b\"00\"  : mword (30 - 29 + 1)) then\n                    (Kernel, Some\n                               (concat_vec (Ox\"00000000\"  : mword 32)\n                                  (concat_vec ('b\"000\"  : mword 3) (subrange_vec_dec vAddr 28 0))))\n                  else match (true, b__1) with | (_, _) => (Kernel, None  : option (bits 64)) end\n               | (_, _) => (Kernel, None  : option (bits 64))\n               end)\n    else if eq_vec b__0 ('b\"10\"  : mword (63 - 62 + 1)) then\n      returnm (Kernel, Some (concat_vec ('b\"00000\"  : mword 5) (subrange_vec_dec vAddr 58 0)))\n    else if eq_vec b__0 ('b\"01\"  : mword (63 - 62 + 1)) then\n      returnm (Supervisor, None  : option (bits 64))\n    else if eq_vec b__0 ('b\"00\"  : mword (63 - 62 + 1)) then\n      returnm (User, None  : option (bits 64))\n    else\n      assert_exp' false \"Pattern match failure at ../mips/mips_tlb.sail 64:1 - 75:2\" >>= fun _ =>\n      exit tt)\n    : M ((AccessLevel * option (mword 64))).\n\nDefinition TLBTranslate2 (vAddr : mword 64) (accessType : MemAccessType) (accessLevel : AccessLevel)\n: M ((mword 64 * MemAccessCapRestriction)) :=\n   (tlbSearch vAddr) >>= fun idx =>\n   (match idx with\n    | Some idx =>\n       let i := projT1 (uint idx) in\n       (reg_deref (vec_access_dec TLBEntries i)) >>= fun entry =>\n       let entryMask := _get_TLBEntry_pagemask entry in\n       let b__0 := entryMask in\n       (if eq_vec b__0 (Ox\"0000\"  : mword 16) then returnm (build_ex 12)\n        else if eq_vec b__0 (Ox\"0003\"  : mword 16) then returnm (build_ex 14)\n        else if eq_vec b__0 (Ox\"000F\"  : mword 16) then returnm (build_ex 16)\n        else if eq_vec b__0 (Ox\"003F\"  : mword 16) then returnm (build_ex 18)\n        else if eq_vec b__0 (Ox\"00FF\"  : mword 16) then returnm (build_ex 20)\n        else if eq_vec b__0 (Ox\"03FF\"  : mword 16) then returnm (build_ex 22)\n        else if eq_vec b__0 (Ox\"0FFF\"  : mword 16) then returnm (build_ex 24)\n        else if eq_vec b__0 (Ox\"3FFF\"  : mword 16) then returnm (build_ex 26)\n        else if eq_vec b__0 (Ox\"FFFF\"  : mword 16) then returnm (build_ex 28)\n        else\n          (undefined_range 12 28)\n           : M ({rangevar : Z & ArithFact ((12 <=? rangevar) && (rangevar <=? 28))})) >>= fun '(existT _ evenOddBit _ : {rangevar : Z & ArithFact ((12 <=?\n         rangevar) &&\n         (rangevar <=? 28))}) =>\n       let isOdd := access_vec_dec vAddr evenOddBit in\n       let '(caps, caplg, capl, pfn, d, v) :=\n         if (bit_to_bool isOdd)  : bool then\n           (_get_TLBEntry_caps1 entry, _get_TLBEntry_caplg1 entry, _get_TLBEntry_capl1 entry, _get_TLBEntry_pfn1\n                                                                                                entry, _get_TLBEntry_d1\n                                                                                                         entry, _get_TLBEntry_v1\n                                                                                                                  entry)\n         else\n           (_get_TLBEntry_caps0 entry, _get_TLBEntry_caplg0 entry, _get_TLBEntry_capl0 entry, _get_TLBEntry_pfn0\n                                                                                                entry, _get_TLBEntry_d0\n                                                                                                         entry, _get_TLBEntry_v0\n                                                                                                                  entry) in\n       (if negb (bits_to_bool v) then\n          (SignalExceptionTLB (if generic_eq accessType StoreData then XTLBInvS else XTLBInvL) vAddr)\n           : M ((mword 64 * MemAccessCapRestriction))\n        else if andb (generic_eq accessType StoreData) (negb (bits_to_bool d)) then\n          (SignalExceptionTLB TLBMod vAddr)\n           : M ((mword 64 * MemAccessCapRestriction))\n        else\n          let res : bits 64 :=\n            mips_zero_extend 64\n              (concat_vec (subrange_vec_dec pfn 23 (Z.sub evenOddBit 12))\n                 (subrange_vec_dec vAddr (Z.sub evenOddBit 1) 0)) in\n          (if generic_eq accessType StoreData then\n             returnm (if (bits_to_bool caps)  : bool then Trap else Unrestricted)\n           else if (bits_to_bool capl)  : bool then returnm Clear\n           else\n             (match accessLevel with\n              | User =>\n                 read_reg TLBEntryHi_ref >>= fun w__11 : TLBEntryHiReg =>\n                 returnm (_get_TLBEntryHiReg_CLGU w__11)\n              | Supervisor =>\n                 read_reg TLBEntryHi_ref >>= fun w__12 : TLBEntryHiReg =>\n                 returnm (_get_TLBEntryHiReg_CLGS w__12)\n              | Kernel =>\n                 read_reg TLBEntryHi_ref >>= fun w__13 : TLBEntryHiReg =>\n                 returnm (_get_TLBEntryHiReg_CLGK w__13)\n              end) >>= fun gclg : bits 1 =>\n             returnm (if neq_bool (bits_to_bool gclg) (bits_to_bool caplg) then Trap\n                      else Unrestricted)) >>= fun macr =>\n          returnm (res, macr))\n        : M ((mword 64 * MemAccessCapRestriction))\n    | None =>\n       (SignalExceptionTLB (if generic_eq accessType StoreData then XTLBRefillS else XTLBRefillL)\n          vAddr)\n        : M ((mword 64 * MemAccessCapRestriction))\n    end)\n    : M ((mword 64 * MemAccessCapRestriction)).\n\nDefinition TLBTranslateC (vAddr : mword 64) (accessType : MemAccessType)\n: M ((mword 64 * MemAccessCapRestriction)) :=\n   (getAccessLevel tt) >>= fun currentAccessLevel =>\n   let compat32 :=\n     eq_vec (subrange_vec_dec vAddr 61 31)\n       ('b\"1111111111111111111111111111111\"\n        : mword (61 - 31 + 1)) in\n   (MIPSSegmentOf vAddr) >>= fun '((requiredLevel, addr)\n   : (AccessLevel * option (bits 64))) =>\n   (if negb (grantsAccess currentAccessLevel requiredLevel) then\n      (SignalExceptionBadAddr (if generic_eq accessType StoreData then AdES else AdEL) vAddr)\n       : M ((mword 64 * MemAccessCapRestriction))\n    else\n      (match addr with\n       | Some a => returnm (a, Unrestricted)\n       | None =>\n          (if sumbool_of_bool\n             (andb (negb compat32)\n                ((Z.gtb (projT1 (uint (subrange_vec_dec vAddr 61 0))) MAX_VA)\n                 : bool)) then\n             (SignalExceptionBadAddr (if generic_eq accessType StoreData then AdES else AdEL) vAddr)\n              : M ((mword 64 * MemAccessCapRestriction))\n           else\n             (TLBTranslate2 vAddr accessType requiredLevel)\n              : M ((mword 64 * MemAccessCapRestriction)))\n           : M ((mword 64 * MemAccessCapRestriction))\n       end) >>= fun '((pa, c)\n      : (bits 64 * MemAccessCapRestriction)) =>\n      (if sumbool_of_bool (Z.gtb (projT1 (uint pa)) MAX_PA) then\n         (SignalExceptionBadAddr (if generic_eq accessType StoreData then AdES else AdEL) vAddr)\n          : M ((mword 64 * MemAccessCapRestriction))\n       else returnm (pa, c))\n       : M ((mword 64 * MemAccessCapRestriction)))\n    : M ((mword 64 * MemAccessCapRestriction)).\n\nDefinition TLBTranslate (vAddr : mword 64) (accessType : MemAccessType) : M (mword 64) :=\n   (TLBTranslateC vAddr accessType) >>= fun '(addr, c) => returnm addr.\n\nDefinition CPtrCmpOp_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 7))} : CPtrCmpOp :=\n   let l__111 := arg_ in\n   if sumbool_of_bool (Z.eqb l__111 0) then CEQ\n   else if sumbool_of_bool (Z.eqb l__111 1) then CNE\n   else if sumbool_of_bool (Z.eqb l__111 2) then CLT\n   else if sumbool_of_bool (Z.eqb l__111 3) then CLE\n   else if sumbool_of_bool (Z.eqb l__111 4) then CLTU\n   else if sumbool_of_bool (Z.eqb l__111 5) then CLEU\n   else if sumbool_of_bool (Z.eqb l__111 6) then CEXEQ\n   else CNEXEQ.\n\nDefinition num_of_CPtrCmpOp (arg_ : CPtrCmpOp) : {e : Z & ArithFact ((0 <=? e) && (e <=? 7))} :=\n   build_ex (\n      match arg_ with\n      | CEQ => 0\n      | CNE => 1\n      | CLT => 2\n      | CLE => 3\n      | CLTU => 4\n      | CLEU => 5\n      | CEXEQ => 6\n      | CNEXEQ => 7\n      end\n   ).\n\nDefinition undefined_CPtrCmpOp '(tt : unit) : M (CPtrCmpOp) :=\n   (internal_pick [CEQ; CNE; CLT; CLE; CLTU; CLEU; CEXEQ; CNEXEQ])  : M (CPtrCmpOp).\n\nDefinition ClearRegSet_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 3))} : ClearRegSet :=\n   let l__108 := arg_ in\n   if sumbool_of_bool (Z.eqb l__108 0) then GPLo\n   else if sumbool_of_bool (Z.eqb l__108 1) then GPHi\n   else if sumbool_of_bool (Z.eqb l__108 2) then CLo\n   else CHi.\n\nDefinition num_of_ClearRegSet (arg_ : ClearRegSet) : {e : Z & ArithFact ((0 <=? e) && (e <=? 3))} :=\n   build_ex (match arg_ with | GPLo => 0 | GPHi => 1 | CLo => 2 | CHi => 3 end).\n\nDefinition undefined_ClearRegSet '(tt : unit) : M (ClearRegSet) :=\n   (internal_pick [GPLo; GPHi; CLo; CHi])  : M (ClearRegSet).\n\nDefinition num_flags := 1.\nHint Unfold num_flags : sail.\nDefinition reserved_otypes := 16.\nHint Unfold reserved_otypes : sail.\nDefinition otype_unsealed := (-1).\nHint Unfold otype_unsealed : sail.\nDefinition otype_sentry := (-2).\nHint Unfold otype_sentry : sail.\nDefinition otype_unsealed_bits := to_bits 64 otype_unsealed.\nHint Unfold otype_unsealed_bits : sail.\nDefinition otype_sentry_bits := to_bits 64 otype_sentry.\nHint Unfold otype_sentry_bits : sail.\nDefinition max_otype := Z.sub (projT1 (MAX 18)) reserved_otypes.\nHint Unfold max_otype : sail.\nDefinition resetE := to_bits 6 52.\nHint Unfold resetE : sail.\nDefinition resetT := concat_vec ('b\"01\"  : mword 2) (Ox\"000\"  : mword 12).\nHint Unfold resetT : sail.\nDefinition null_cap : Capability :=\n{| Capability_tag := false; \n   Capability_uperms := (zeros_implicit 4 tt); \n   Capability_permit_set_CID := false; \n   Capability_access_system_regs := false; \n   Capability_permit_unseal := false; \n   Capability_permit_ccall := false; \n   Capability_permit_seal := false; \n   Capability_permit_store_local_cap := false; \n   Capability_permit_store_cap := false; \n   Capability_permit_load_cap := false; \n   Capability_permit_store := false; \n   Capability_permit_load := false; \n   Capability_permit_execute := false; \n   Capability_global := false; \n   Capability_reserved := (zeros_implicit 3 tt); \n   Capability_internal_e := true; \n   Capability_E := resetE; \n   Capability_sealed := false; \n   Capability_B := (zeros_implicit 14 tt); \n   Capability_T := resetT; \n   Capability_otype := (ones_implicit 18 tt); \n   Capability_address := (zeros_implicit 64 tt) |}.\nHint Unfold null_cap : sail.\nDefinition default_cap : Capability :=\n{| Capability_tag := true; \n   Capability_uperms := (ones_implicit 4 tt); \n   Capability_permit_set_CID := true; \n   Capability_access_system_regs := true; \n   Capability_permit_unseal := true; \n   Capability_permit_ccall := true; \n   Capability_permit_seal := true; \n   Capability_permit_store_local_cap := true; \n   Capability_permit_store_cap := true; \n   Capability_permit_load_cap := true; \n   Capability_permit_store := true; \n   Capability_permit_load := true; \n   Capability_permit_execute := true; \n   Capability_global := true; \n   Capability_reserved := (zeros_implicit 3 tt); \n   Capability_internal_e := true; \n   Capability_E := resetE; \n   Capability_sealed := false; \n   Capability_B := (zeros_implicit 14 tt); \n   Capability_T := resetT; \n   Capability_otype := (ones_implicit 18 tt); \n   Capability_address := (zeros_implicit 64 tt) |}.\nHint Unfold default_cap : sail.\nDefinition cap_size := 16.\nHint Unfold cap_size : sail.\nDefinition caps_per_cacheline := 8.\nHint Unfold caps_per_cacheline : sail.\nDefinition capBitsToCapability (t : bool) (c : mword 128) : Capability :=\n   let internal_exponent : bool := (bit_to_bool (access_vec_dec c 90))  : bool in\n   let otype : bits 18 := subrange_vec_dec c 108 91 in\n   let sealed : bool := neq_vec otype (ones_implicit 18 tt) in\n   let E : bits 6 := zeros_implicit 6 tt in\n   let Bs : bits 14 := zeros_implicit 14 tt in\n   let T : bits 12 := zeros_implicit 12 tt in\n   let lenMSBs : bits 2 := zeros_implicit 2 tt in\n   let '(Bs, E, T, lenMSBs) :=\n     (if sumbool_of_bool internal_exponent then\n        let E : bits 6 := concat_vec (subrange_vec_dec c 80 78) (subrange_vec_dec c 66 64) in\n        let lenMSBs : bits 2 := 'b\"01\"  : mword 2 in\n        let T : bits 12 := concat_vec (subrange_vec_dec c 89 81) ('b\"000\"  : mword 3) in\n        let Bs : bits 14 := concat_vec (subrange_vec_dec c 77 67) ('b\"000\"  : mword 3) in\n        (Bs, E, T, lenMSBs)\n      else\n        let lenMSBs : bits 2 := 'b\"00\"  : mword 2 in\n        let T : bits 12 := subrange_vec_dec c 89 78 in\n        let Bs : bits 14 := subrange_vec_dec c 77 64 in\n        (Bs, E, T, lenMSBs))\n      : (mword 14 * mword 6 * mword 12 * mword 2) in\n   let carry_out :=\n     if zopz0zI_u T (subrange_vec_dec Bs 11 0) then 'b\"01\"  : mword 2\n     else 'b\"00\"  : mword 2 in\n   let Ttop2 := add_vec (add_vec (subrange_vec_dec Bs 13 12) lenMSBs) carry_out in\n   {| Capability_tag := t; \n      Capability_uperms := (subrange_vec_dec c 127 124); \n      Capability_permit_set_CID := ((bit_to_bool (access_vec_dec c 123))  : bool); \n      Capability_access_system_regs := ((bit_to_bool (access_vec_dec c 122))  : bool); \n      Capability_permit_unseal := ((bit_to_bool (access_vec_dec c 121))  : bool); \n      Capability_permit_ccall := ((bit_to_bool (access_vec_dec c 120))  : bool); \n      Capability_permit_seal := ((bit_to_bool (access_vec_dec c 119))  : bool); \n      Capability_permit_store_local_cap := ((bit_to_bool (access_vec_dec c 118))  : bool); \n      Capability_permit_store_cap := ((bit_to_bool (access_vec_dec c 117))  : bool); \n      Capability_permit_load_cap := ((bit_to_bool (access_vec_dec c 116))  : bool); \n      Capability_permit_store := ((bit_to_bool (access_vec_dec c 115))  : bool); \n      Capability_permit_load := ((bit_to_bool (access_vec_dec c 114))  : bool); \n      Capability_permit_execute := ((bit_to_bool (access_vec_dec c 113))  : bool); \n      Capability_global := ((bit_to_bool (access_vec_dec c 112))  : bool); \n      Capability_reserved := (subrange_vec_dec c 111 109); \n      Capability_internal_e := internal_exponent; \n      Capability_E := E; \n      Capability_sealed := sealed; \n      Capability_B := Bs; \n      Capability_T := (concat_vec Ttop2 T); \n      Capability_otype := otype; \n      Capability_address := (subrange_vec_dec c 63 0) |}.\n\nDefinition getCapHardPerms (cap : Capability) : mword 12 :=\n   concat_vec (bool_to_bits cap.(Capability_permit_set_CID))\n     (concat_vec (bool_to_bits cap.(Capability_access_system_regs))\n        (concat_vec (bool_to_bits cap.(Capability_permit_unseal))\n           (concat_vec (bool_to_bits cap.(Capability_permit_ccall))\n              (concat_vec (bool_to_bits cap.(Capability_permit_seal))\n                 (concat_vec (bool_to_bits cap.(Capability_permit_store_local_cap))\n                    (concat_vec (bool_to_bits cap.(Capability_permit_store_cap))\n                       (concat_vec (bool_to_bits cap.(Capability_permit_load_cap))\n                          (concat_vec (bool_to_bits cap.(Capability_permit_store))\n                             (concat_vec (bool_to_bits cap.(Capability_permit_load))\n                                (concat_vec (bool_to_bits cap.(Capability_permit_execute))\n                                   (bool_to_bits cap.(Capability_global)))))))))))).\n\nDefinition capToBits (cap : Capability) : mword 128 :=\n   let t_hi : bits 9 := subrange_vec_dec cap.(Capability_T) 11 3 in\n   let t_lo : bits 3 := subrange_vec_dec cap.(Capability_T) 2 0 in\n   let b_hi : bits 11 := subrange_vec_dec cap.(Capability_B) 13 3 in\n   let b_lo : bits 3 := subrange_vec_dec cap.(Capability_B) 2 0 in\n   let '(b_lo, t_lo) :=\n     (if cap.(Capability_internal_e) then\n        let t_lo : bits 3 := subrange_vec_dec cap.(Capability_E) 5 3 in\n        let b_lo : bits 3 := subrange_vec_dec cap.(Capability_E) 2 0 in\n        (b_lo, t_lo)\n      else (b_lo, t_lo))\n      : (mword 3 * mword 3) in\n   concat_vec cap.(Capability_uperms)\n     (concat_vec (getCapHardPerms cap)\n        (concat_vec cap.(Capability_reserved)\n           (concat_vec cap.(Capability_otype)\n              (concat_vec (bool_to_bits cap.(Capability_internal_e))\n                 (concat_vec t_hi\n                    (concat_vec t_lo (concat_vec b_hi (concat_vec b_lo cap.(Capability_address))))))))).\n\nDefinition null_cap_bits : bits 128 := capToBits null_cap.\nHint Unfold null_cap_bits : sail.\nDefinition capToMemBits (cap : Capability) : mword 128 := xor_vec (capToBits cap) null_cap_bits.\n\nDefinition memBitsToCapability (tag : bool) (b : mword 128) : Capability :=\n   capBitsToCapability tag (xor_vec b null_cap_bits).\n\nDefinition getCapPerms (cap : Capability) : mword 31 :=\n   let perms : bits 15 := mips_zero_extend 15 (getCapHardPerms cap) in\n   concat_vec (Ox\"000\"  : mword 12) (concat_vec cap.(Capability_uperms) perms).\n\nDefinition setCapPerms (cap : Capability) (perms : mword 31) : Capability :=\n   {| Capability_tag := cap.(Capability_tag); \n      Capability_uperms := (subrange_vec_dec perms 18 15); \n      Capability_permit_set_CID := ((bit_to_bool (access_vec_dec perms 11))  : bool); \n      Capability_access_system_regs := ((bit_to_bool (access_vec_dec perms 10))  : bool); \n      Capability_permit_unseal := ((bit_to_bool (access_vec_dec perms 9))  : bool); \n      Capability_permit_ccall := ((bit_to_bool (access_vec_dec perms 8))  : bool); \n      Capability_permit_seal := ((bit_to_bool (access_vec_dec perms 7))  : bool); \n      Capability_permit_store_local_cap := ((bit_to_bool (access_vec_dec perms 6))  : bool); \n      Capability_permit_store_cap := ((bit_to_bool (access_vec_dec perms 5))  : bool); \n      Capability_permit_load_cap := ((bit_to_bool (access_vec_dec perms 4))  : bool); \n      Capability_permit_store := ((bit_to_bool (access_vec_dec perms 3))  : bool); \n      Capability_permit_load := ((bit_to_bool (access_vec_dec perms 2))  : bool); \n      Capability_permit_execute := ((bit_to_bool (access_vec_dec perms 1))  : bool); \n      Capability_global := ((bit_to_bool (access_vec_dec perms 0))  : bool); \n      Capability_reserved := cap.(Capability_reserved); \n      Capability_internal_e := cap.(Capability_internal_e); \n      Capability_E := cap.(Capability_E); \n      Capability_sealed := cap.(Capability_sealed); \n      Capability_B := cap.(Capability_B); \n      Capability_T := cap.(Capability_T); \n      Capability_otype := cap.(Capability_otype); \n      Capability_address := cap.(Capability_address) |}.\n\nDefinition sealCap (cap : Capability) (otyp : mword 24) : (bool * Capability) :=\n   (true, {| Capability_tag := cap.(Capability_tag); \n             Capability_uperms := cap.(Capability_uperms); \n             Capability_permit_set_CID := cap.(Capability_permit_set_CID); \n             Capability_access_system_regs := cap.(Capability_access_system_regs); \n             Capability_permit_unseal := cap.(Capability_permit_unseal); \n             Capability_permit_ccall := cap.(Capability_permit_ccall); \n             Capability_permit_seal := cap.(Capability_permit_seal); \n             Capability_permit_store_local_cap := cap.(Capability_permit_store_local_cap); \n             Capability_permit_store_cap := cap.(Capability_permit_store_cap); \n             Capability_permit_load_cap := cap.(Capability_permit_load_cap); \n             Capability_permit_store := cap.(Capability_permit_store); \n             Capability_permit_load := cap.(Capability_permit_load); \n             Capability_permit_execute := cap.(Capability_permit_execute); \n             Capability_global := cap.(Capability_global); \n             Capability_reserved := cap.(Capability_reserved); \n             Capability_internal_e := cap.(Capability_internal_e); \n             Capability_E := cap.(Capability_E); \n             Capability_sealed := true; \n             Capability_B := cap.(Capability_B); \n             Capability_T := cap.(Capability_T); \n             Capability_otype := (subrange_vec_dec otyp 17 0); \n             Capability_address := cap.(Capability_address) |}).\n\nDefinition unsealCap (cap : Capability) : Capability :=\n   {| Capability_tag := cap.(Capability_tag); \n      Capability_uperms := cap.(Capability_uperms); \n      Capability_permit_set_CID := cap.(Capability_permit_set_CID); \n      Capability_access_system_regs := cap.(Capability_access_system_regs); \n      Capability_permit_unseal := cap.(Capability_permit_unseal); \n      Capability_permit_ccall := cap.(Capability_permit_ccall); \n      Capability_permit_seal := cap.(Capability_permit_seal); \n      Capability_permit_store_local_cap := cap.(Capability_permit_store_local_cap); \n      Capability_permit_store_cap := cap.(Capability_permit_store_cap); \n      Capability_permit_load_cap := cap.(Capability_permit_load_cap); \n      Capability_permit_store := cap.(Capability_permit_store); \n      Capability_permit_load := cap.(Capability_permit_load); \n      Capability_permit_execute := cap.(Capability_permit_execute); \n      Capability_global := cap.(Capability_global); \n      Capability_reserved := cap.(Capability_reserved); \n      Capability_internal_e := cap.(Capability_internal_e); \n      Capability_E := cap.(Capability_E); \n      Capability_sealed := false; \n      Capability_B := cap.(Capability_B); \n      Capability_T := cap.(Capability_T); \n      Capability_otype := (ones_implicit 18 tt); \n      Capability_address := cap.(Capability_address) |}.\n\nDefinition getCapTop (c : Capability)\n: {rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 65)))} :=\n   build_ex (\n      let '(existT _ _ _, existT _ top _) := getCapBounds c in\n      top\n   ).\n\nDefinition getCapOffset (c : Capability)\n: {rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 64 - 1)))} :=\n   build_ex (\n      let base := projT1 (getCapBase c) in\n      projT1\n      (emod_with_eq (Z.sub (projT1 (uint c.(Capability_address))) base) (projT1 (pow2 64)))\n   ).\n\nDefinition getCapLength (c : Capability)\n: M ({rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 65)))}) :=\n   let '(existT _ base _, existT _ top _) := getCapBounds c in\n   assert_exp (orb (negb c.(Capability_tag)) (Z.geb top base)) \"cheri_prelude_128.sail 318:40 - 318:41\" >>\n   returnm (build_ex (projT1 (emod_with_eq (Z.sub top base) (projT1 (pow2 65))))).\n\nDefinition getCapCursor (cap : Capability)\n: {rangevar : Z & ArithFact ((0 <=? rangevar) && (rangevar <=? (2 ^ 64 - 1)))} :=\n   build_ex (projT1 (uint cap.(Capability_address))).\n\nDefinition setCapAddr (c : Capability) (addr : mword 64) : (bool * Capability) :=\n   let newCap := {[ c with Capability_address := addr ]} in\n   let representable := capBoundsEqual c newCap in\n   (representable, newCap).\n\nDefinition incCapOffset (c : Capability) (delta : mword 64) : (bool * Capability) :=\n   let newAddress : bits 64 := add_vec c.(Capability_address) delta in\n   let newCap := {[ c with Capability_address := newAddress ]} in\n   let representable := capBoundsEqual c newCap in\n   (representable, newCap).\n\nDefinition setCapBounds (cap : Capability) (base : mword 64) (top : mword 65) : (bool * Capability) :=\n   let base65 := concat_vec ('b\"0\"  : mword 1) base in\n   let length := sub_vec top base65 in\n   let e := Z.sub 52 (projT1 (count_leading_zeros (subrange_vec_dec length 64 13))) in\n   let ie := orb (projT1 (neq_int e 0)) (bit_to_bool (access_vec_dec length 12)) in\n   let Bbits := vector_truncate base 14 in\n   let Tbits := vector_truncate top 14 in\n   let lostSignificantTop : bool := false in\n   let lostSignificantBase : bool := false in\n   let incE : bool := false in\n   let '(Bbits, Tbits, incE, lostSignificantBase, lostSignificantTop) :=\n     (if sumbool_of_bool ie then\n        let B_ie := vector_truncate (shiftr base (Z.add e 3)) 11 in\n        let T_ie := vector_truncate (shiftr top (Z.add e 3)) 11 in\n        let maskLo : bits 65 := mips_zero_extend 65 (sail_ones (Z.add e 3)) in\n        let z65 : bits 65 := zeros_implicit 65 tt in\n        let lostSignificantBase : bool := neq_vec (and_vec base65 maskLo) z65 in\n        let lostSignificantTop : bool := neq_vec (and_vec top maskLo) z65 in\n        let T_ie : mword 11 :=\n          if sumbool_of_bool lostSignificantTop then add_vec_int T_ie 1\n          else T_ie in\n        let len_ie := sub_vec T_ie B_ie in\n        let '(B_ie, T_ie, incE, lostSignificantBase, lostSignificantTop) :=\n          (if (bit_to_bool (access_vec_dec len_ie 10))  : bool then\n             let incE : bool := true in\n             let lostSignificantBase : bool :=\n               orb lostSignificantBase (bit_to_bool (access_vec_dec B_ie 0)) in\n             let lostSignificantTop : bool :=\n               orb lostSignificantTop (bit_to_bool (access_vec_dec T_ie 0)) in\n             let B_ie : mword 11 := vector_truncate (shiftr base (Z.add e 4)) 11 in\n             let incT := if sumbool_of_bool lostSignificantTop then 1 else 0 in\n             let T_ie : mword 11 := add_vec_int (vector_truncate (shiftr top (Z.add e 4)) 11) incT in\n             (B_ie, T_ie, incE, lostSignificantBase, lostSignificantTop)\n           else (B_ie, T_ie, incE, lostSignificantBase, lostSignificantTop))\n           : (mword 11 * mword 11 * bool * bool * bool) in\n        let Bbits : mword 14 := concat_vec B_ie ('b\"000\"  : mword 3) in\n        let Tbits : mword 14 := concat_vec T_ie ('b\"000\"  : mword 3) in\n        (Bbits, Tbits, incE, lostSignificantBase, lostSignificantTop)\n      else (Bbits, Tbits, incE, lostSignificantBase, lostSignificantTop))\n      : (mword 14 * mword 14 * bool * bool * bool) in\n   let newCap :=\n     {| Capability_tag := cap.(Capability_tag); \n        Capability_uperms := cap.(Capability_uperms); \n        Capability_permit_set_CID := cap.(Capability_permit_set_CID); \n        Capability_access_system_regs := cap.(Capability_access_system_regs); \n        Capability_permit_unseal := cap.(Capability_permit_unseal); \n        Capability_permit_ccall := cap.(Capability_permit_ccall); \n        Capability_permit_seal := cap.(Capability_permit_seal); \n        Capability_permit_store_local_cap := cap.(Capability_permit_store_local_cap); \n        Capability_permit_store_cap := cap.(Capability_permit_store_cap); \n        Capability_permit_load_cap := cap.(Capability_permit_load_cap); \n        Capability_permit_store := cap.(Capability_permit_store); \n        Capability_permit_load := cap.(Capability_permit_load); \n        Capability_permit_execute := cap.(Capability_permit_execute); \n        Capability_global := cap.(Capability_global); \n        Capability_reserved := cap.(Capability_reserved); \n        Capability_internal_e := ie; \n        Capability_E := (to_bits 6 (if sumbool_of_bool incE then Z.add e 1 else e)); \n        Capability_sealed := cap.(Capability_sealed); \n        Capability_B := Bbits; \n        Capability_T := Tbits; \n        Capability_otype := cap.(Capability_otype); \n        Capability_address := base |} in\n   let exact := negb (orb lostSignificantBase lostSignificantTop) in\n   (exact, newCap).\n\nDefinition getRepresentableAlignmentMask (len : mword 64) : mword 64 :=\n   let '(exact, c) :=\n     setCapBounds default_cap (sub_vec (ones_implicit 64 tt) len)\n       (concat_vec ('b\"0\"  : mword 1) (Ox\"FFFFFFFFFFFFFFFF\"  : mword 64)) in\n   let e := projT1 (min_atom (projT1 (uint c.(Capability_E))) 52) in\n   let e' := if c.(Capability_internal_e) then Z.add e 3 else 0 in\n   autocast (concat_vec (sail_ones (Z.sub 64 e')) (zeros e')).\n\nDefinition getRepresentableLength (len : mword 64) : mword 64 :=\n   let m := getRepresentableAlignmentMask len in\n   and_vec (add_vec len (not_vec m)) m.\n\nDefinition CapRegs : vec (register_ref regstate register_value Capability) 32 :=\nvec_of_list_len [C31_ref;C30_ref;C29_ref;C28_ref;C27_ref;C26_ref;C25_ref;C24_ref;C23_ref;C22_ref;\n                 C21_ref;C20_ref;C19_ref;C18_ref;C17_ref;C16_ref;C15_ref;C14_ref;C13_ref;C12_ref;\n                 C11_ref;C10_ref;C09_ref;C08_ref;C07_ref;C06_ref;C05_ref;C04_ref;C03_ref;C02_ref;\n                 C01_ref;DDC_ref].\nHint Unfold CapRegs : sail.\nDefinition have_cp2 := true.\nHint Unfold have_cp2 : sail.\nDefinition readCapReg (n : mword 5) : M (Capability) :=\n   (if eq_vec n ('b\"00000\"  : mword 5) then returnm null_cap\n    else\n      let i := projT1 (uint n) in\n      (reg_deref (vec_access_dec CapRegs i))\n       : M (Capability))\n    : M (Capability).\n\nDefinition readCapRegDDC (n : mword 5) : M (Capability) :=\n   let i := projT1 (uint n) in\n   (reg_deref (vec_access_dec CapRegs i))\n    : M (Capability).\n\nDefinition hasReservedOType (cap : Capability) : bool :=\n   Z.gtb (projT1 (uint cap.(Capability_otype))) max_otype.\n\nDefinition capToString (cap : Capability) (fixlen : bool) : M (string) :=\n   (skip tt) >>\n   (getCapLength cap) >>= fun '(existT _ len _) =>\n   let len_str :=\n     if sumbool_of_bool fixlen then\n       string_of_bits (to_bits 64 (projT1 (min_atom len (projT1 (MAX 64)))))\n     else string_of_bits (to_bits 68 len) in\n   let otype64 : bits 64 :=\n     if hasReservedOType cap then mips_sign_extend 64 cap.(Capability_otype)\n     else mips_zero_extend 64 cap.(Capability_otype) in\n   returnm (String.append \" t:\"\n              (String.append (if cap.(Capability_tag) then \"1\" else \"0\")\n                 (String.append \" s:\"\n                    (String.append (if cap.(Capability_sealed) then \"1\" else \"0\")\n                       (String.append \" perms:\"\n                          (String.append\n                             (string_of_bits (concat_vec ('b\"0\"  : mword 1) (getCapPerms cap)))\n                             (String.append \" type:\"\n                                (String.append (string_of_bits otype64)\n                                   (String.append \" offset:\"\n                                      (String.append\n                                         (string_of_bits (to_bits 64 (projT1 (getCapOffset cap))))\n                                         (String.append \" base:\"\n                                            (String.append\n                                               (string_of_bits\n                                                  (to_bits 64 (projT1 (getCapBase cap))))\n                                               (String.append \" length:\" len_str))))))))))))).\n\nDefinition writeCapReg (n : mword 5) (cap : Capability) : M (unit) :=\n   (if eq_vec n ('b\"00000\"  : mword 5) then returnm tt\n    else\n      let i := projT1 (uint n) in\n      (if sumbool_of_bool trace then\n         let '_ := (prerr (string_of_int i))  : unit in\n         let '_ := (prerr \" <- \")  : unit in\n         (capToString cap false) >>= fun w__0 : string =>\n         let '_ := (prerr_endline w__0)  : unit in\n         let cap2 := capBitsToCapability cap.(Capability_tag) (capToBits cap) in\n         (if generic_neq cap cap2 then\n            let '_ := (prerr_endline \"Wrote non-normal cap:\")  : unit in\n            (capToString cap false) >>= fun w__1 : string =>\n            let '_ := (prerr_endline w__1)  : unit in\n            (capToString cap2 false) >>= fun w__2 : string =>\n            let '_ := (prerr_endline w__2)  : unit in\n            assert_exp' false \"wrote non-normal capability\" >>= fun _ => exit tt\n          else returnm tt)\n          : M (unit)\n       else (skip tt)  : M (unit)) >>\n      write_reg (vec_access_dec CapRegs i) cap\n       : M (unit))\n    : M (unit).\n\nDefinition CapEx_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 24))} : CapEx :=\n   let l__84 := arg_ in\n   if sumbool_of_bool (Z.eqb l__84 0) then CapEx_None\n   else if sumbool_of_bool (Z.eqb l__84 1) then CapEx_LengthViolation\n   else if sumbool_of_bool (Z.eqb l__84 2) then CapEx_TagViolation\n   else if sumbool_of_bool (Z.eqb l__84 3) then CapEx_SealViolation\n   else if sumbool_of_bool (Z.eqb l__84 4) then CapEx_TypeViolation\n   else if sumbool_of_bool (Z.eqb l__84 5) then CapEx_CallTrap\n   else if sumbool_of_bool (Z.eqb l__84 6) then CapEx_ReturnTrap\n   else if sumbool_of_bool (Z.eqb l__84 7) then CapEx_TSSUnderFlow\n   else if sumbool_of_bool (Z.eqb l__84 8) then CapEx_UserDefViolation\n   else if sumbool_of_bool (Z.eqb l__84 9) then CapEx_TLBNoStoreCap\n   else if sumbool_of_bool (Z.eqb l__84 10) then CapEx_InexactBounds\n   else if sumbool_of_bool (Z.eqb l__84 11) then CapEx_GlobalViolation\n   else if sumbool_of_bool (Z.eqb l__84 12) then CapEx_PermitExecuteViolation\n   else if sumbool_of_bool (Z.eqb l__84 13) then CapEx_PermitLoadViolation\n   else if sumbool_of_bool (Z.eqb l__84 14) then CapEx_PermitStoreViolation\n   else if sumbool_of_bool (Z.eqb l__84 15) then CapEx_PermitLoadCapViolation\n   else if sumbool_of_bool (Z.eqb l__84 16) then CapEx_PermitStoreCapViolation\n   else if sumbool_of_bool (Z.eqb l__84 17) then CapEx_PermitStoreLocalCapViolation\n   else if sumbool_of_bool (Z.eqb l__84 18) then CapEx_PermitSealViolation\n   else if sumbool_of_bool (Z.eqb l__84 19) then CapEx_AccessSystemRegsViolation\n   else if sumbool_of_bool (Z.eqb l__84 20) then CapEx_PermitCCallViolation\n   else if sumbool_of_bool (Z.eqb l__84 21) then CapEx_AccessCCallIDCViolation\n   else if sumbool_of_bool (Z.eqb l__84 22) then CapEx_PermitUnsealViolation\n   else if sumbool_of_bool (Z.eqb l__84 23) then CapEx_PermitSetCIDViolation\n   else CapEx_TLBLoadCap.\n\nDefinition num_of_CapEx (arg_ : CapEx) : {e : Z & ArithFact ((0 <=? e) && (e <=? 24))} :=\n   build_ex (\n      match arg_ with\n      | CapEx_None => 0\n      | CapEx_LengthViolation => 1\n      | CapEx_TagViolation => 2\n      | CapEx_SealViolation => 3\n      | CapEx_TypeViolation => 4\n      | CapEx_CallTrap => 5\n      | CapEx_ReturnTrap => 6\n      | CapEx_TSSUnderFlow => 7\n      | CapEx_UserDefViolation => 8\n      | CapEx_TLBNoStoreCap => 9\n      | CapEx_InexactBounds => 10\n      | CapEx_GlobalViolation => 11\n      | CapEx_PermitExecuteViolation => 12\n      | CapEx_PermitLoadViolation => 13\n      | CapEx_PermitStoreViolation => 14\n      | CapEx_PermitLoadCapViolation => 15\n      | CapEx_PermitStoreCapViolation => 16\n      | CapEx_PermitStoreLocalCapViolation => 17\n      | CapEx_PermitSealViolation => 18\n      | CapEx_AccessSystemRegsViolation => 19\n      | CapEx_PermitCCallViolation => 20\n      | CapEx_AccessCCallIDCViolation => 21\n      | CapEx_PermitUnsealViolation => 22\n      | CapEx_PermitSetCIDViolation => 23\n      | CapEx_TLBLoadCap => 24\n      end\n   ).\n\nDefinition undefined_CapEx '(tt : unit) : M (CapEx) :=\n   (internal_pick\n      [CapEx_None;\n      CapEx_LengthViolation;\n      CapEx_TagViolation;\n      CapEx_SealViolation;\n      CapEx_TypeViolation;\n      CapEx_CallTrap;\n      CapEx_ReturnTrap;\n      CapEx_TSSUnderFlow;\n      CapEx_UserDefViolation;\n      CapEx_TLBNoStoreCap;\n      CapEx_InexactBounds;\n      CapEx_GlobalViolation;\n      CapEx_PermitExecuteViolation;\n      CapEx_PermitLoadViolation;\n      CapEx_PermitStoreViolation;\n      CapEx_PermitLoadCapViolation;\n      CapEx_PermitStoreCapViolation;\n      CapEx_PermitStoreLocalCapViolation;\n      CapEx_PermitSealViolation;\n      CapEx_AccessSystemRegsViolation;\n      CapEx_PermitCCallViolation;\n      CapEx_AccessCCallIDCViolation;\n      CapEx_PermitUnsealViolation;\n      CapEx_PermitSetCIDViolation;\n      CapEx_TLBLoadCap])\n    : M (CapEx).\n\nDefinition Mk_CapCauseReg (v : mword 16) : CapCauseReg :=\n   {| CapCauseReg_CapCauseReg_chunk_0 := (subrange_vec_dec v 15 0) |}.\n\nDefinition _get_CapCauseReg_bits (v : CapCauseReg) : mword 16 :=\n   subrange_vec_dec v.(CapCauseReg_CapCauseReg_chunk_0) 15 0.\n\nDefinition _set_CapCauseReg_bits\n(r_ref : register_ref regstate register_value CapCauseReg) (v : mword 16)\n: M (unit) :=\n   (reg_deref r_ref) >>= fun r =>\n   let r :=\n     {[ r with\n       CapCauseReg_CapCauseReg_chunk_0 :=\n         (update_subrange_vec_dec r.(CapCauseReg_CapCauseReg_chunk_0) 15 0 (subrange_vec_dec v 15 0)) ]}\n      : CapCauseReg in\n   write_reg r_ref r\n    : M (unit).\n\nDefinition _update_CapCauseReg_bits (v : CapCauseReg) (x : mword 16) : CapCauseReg :=\n   {[ v with\n     CapCauseReg_CapCauseReg_chunk_0 :=\n       (update_subrange_vec_dec v.(CapCauseReg_CapCauseReg_chunk_0) 15 0 (subrange_vec_dec x 15 0)) ]}.\n\nDefinition _get_CapCauseReg_ExcCode (v : CapCauseReg) : mword 8 :=\n   subrange_vec_dec v.(CapCauseReg_CapCauseReg_chunk_0) 15 8.\n\nDefinition _update_CapCauseReg_ExcCode (v : CapCauseReg) (x : mword 8) : CapCauseReg :=\n   {[ v with\n     CapCauseReg_CapCauseReg_chunk_0 :=\n       (update_subrange_vec_dec v.(CapCauseReg_CapCauseReg_chunk_0) 15 8 (subrange_vec_dec x 7 0)) ]}.\n\nDefinition _get_CapCauseReg_RegNum (v : CapCauseReg) : mword 8 :=\n   subrange_vec_dec v.(CapCauseReg_CapCauseReg_chunk_0) 7 0.\n\nDefinition _update_CapCauseReg_RegNum (v : CapCauseReg) (x : mword 8) : CapCauseReg :=\n   {[ v with\n     CapCauseReg_CapCauseReg_chunk_0 :=\n       (update_subrange_vec_dec v.(CapCauseReg_CapCauseReg_chunk_0) 7 0 (subrange_vec_dec x 7 0)) ]}.\n\nDefinition execute_branch_pcc (newPCC : Capability) : M (unit) :=\n   write_reg DelayedPC_ref (to_bits 64 (projT1 (getCapOffset newPCC))) >>\n   write_reg DelayedPCC_ref newPCC >>\n   write_reg BranchPending_ref ('b\"1\"  : mword 1) >>\n   write_reg NextInBranchDelay_ref ('b\"1\"  : mword 1)\n    : M (unit).\n\nDefinition raise_c2_exception {o : Type} (capEx : CapEx) (regnum : mword 5) : M (o) :=\n   let reg8 := concat_vec ('b\"000\"  : mword 3) regnum in\n   (raise_c2_exception8 capEx reg8)\n    : M (o).\n\nDefinition raise_c2_exception_badaddr {o : Type}\n(capEx : CapEx) (regnum : mword 5) (badAddr : mword 64)\n: M (o) :=\n   write_reg CP0BadVAddr_ref badAddr >> (raise_c2_exception capEx regnum)  : M (o).\n\nDefinition cap_addr_mask := to_bits 64 (Z.sub (projT1 (pow2 64)) cap_size).\nHint Unfold cap_addr_mask : sail.\n\n\n\n\n\n\n\n\nDefinition MEMw_wrapper (addr : mword 64) (size : Z) (data : mword (8 * size))\n`{ArithFact (size >=? 1)}\n: M (unit) :=\n   (if eq_vec addr (Ox\"000000007F000000\"  : mword 64) then\n      let ledata := reverse_endianness data in\n      write_reg UART_WDATA_ref (subrange_vec_dec ledata 7 0) >>\n      write_reg UART_WRITTEN_ref ('b\"1\"  : mword 1)\n       : M (unit)\n    else\n      assert_exp (eq_vec (and_vec addr cap_addr_mask)\n                    (and_vec (add_vec addr (to_bits 64 (Z.sub size 1))) cap_addr_mask)) \"cheri_prelude_common.sail 460:85 - 460:86\" >>\n      (MEMw_tagged addr size false (autocast (autocast data)))\n       : M (unit))\n    : M (unit).\n\nDefinition MEMw_conditional_wrapper (addr : mword 64) (size : Z) (data : mword (8 * size))\n`{ArithFact (size >=? 1)}\n: M (bool) :=\n   assert_exp (eq_vec (and_vec addr cap_addr_mask)\n                 (and_vec (add_vec addr (to_bits 64 (Z.sub size 1))) cap_addr_mask)) \"cheri_prelude_common.sail 472:85 - 472:86\" >>\n   (MEMw_tagged_conditional addr size false (autocast (autocast data)))\n    : M (bool).\n\nDefinition checkDDCPerms (ddc : Capability) (accessType : MemAccessType) : M (unit) :=\n   (if negb ddc.(Capability_tag) then\n      (raise_c2_exception CapEx_TagViolation ('b\"00000\"  : mword 5))\n       : M (unit)\n    else if ddc.(Capability_sealed) then\n      (raise_c2_exception CapEx_SealViolation ('b\"00000\"  : mword 5))\n       : M (unit)\n    else returnm tt) >>\n   (match accessType with\n    | Instruction =>\n       assert_exp' false \"cheri_prelude_common.sail 485:34 - 485:35\" >>= fun _ => exit tt\n    | LoadData =>\n       (if negb ddc.(Capability_permit_load) then\n          (raise_c2_exception CapEx_PermitLoadViolation ('b\"00000\"  : mword 5))\n           : M (unit)\n        else returnm tt)\n        : M (unit)\n    | StoreData =>\n       (if negb ddc.(Capability_permit_store) then\n          (raise_c2_exception CapEx_PermitStoreViolation ('b\"00000\"  : mword 5))\n           : M (unit)\n        else returnm tt)\n        : M (unit)\n    end)\n    : M (unit).\n\nDefinition addrWrapper (addr : mword 64) (accessType : MemAccessType) (width : WordType)\n: M (mword 64) :=\n   read_reg DDC_ref >>= fun ddc =>\n   (checkDDCPerms ddc accessType) >>\n   let cursor := projT1 (getCapCursor ddc) in\n   let vAddr := projT1 (emod_with_eq (Z.add cursor (projT1 (uint addr))) (projT1 (pow2 64))) in\n   let size := projT1 (wordWidthBytes width) in\n   let '(existT _ base _, existT _ top _) := getCapBounds ddc in\n   (if sumbool_of_bool (Z.gtb (Z.add vAddr size) top) then\n      (raise_c2_exception CapEx_LengthViolation ('b\"00000\"  : mword 5))\n       : M (mword 64)\n    else if sumbool_of_bool (Z.ltb vAddr base) then\n      (raise_c2_exception CapEx_LengthViolation ('b\"00000\"  : mword 5))\n       : M (mword 64)\n    else returnm (to_bits 64 vAddr))\n    : M (mword 64).\n\nDefinition addrWrapperUnaligned\n(addr : mword 64) (accessType : MemAccessType) (width : WordTypeUnaligned)\n: M ((mword 64 * Z)) :=\n   read_reg DDC_ref >>= fun ddc =>\n   (checkDDCPerms ddc accessType) >>\n   let cursor := projT1 (getCapCursor ddc) in\n   let vAddr := projT1 (emod_with_eq (Z.add cursor (projT1 (uint addr))) (projT1 (pow2 64))) in\n   let '(waddr, size) := unalignedBytesTouched vAddr width in\n   let '(existT _ base _, existT _ top _) := getCapBounds ddc in\n   (if sumbool_of_bool (Z.gtb (Z.add waddr size) top) then\n      (raise_c2_exception CapEx_LengthViolation ('b\"00000\"  : mword 5))\n       : M ((mword 64 * Z))\n    else if sumbool_of_bool (Z.ltb waddr base) then\n      (raise_c2_exception CapEx_LengthViolation ('b\"00000\"  : mword 5))\n       : M ((mword 64 * Z))\n    else returnm (to_bits 64 waddr, size))\n    : M ((mword 64 * Z)).\n\nDefinition execute_branch (pc : mword 64) : M (unit) :=\n   read_reg PCC_ref >>= fun w__0 : Capability =>\n   (getCapLength w__0) >>= fun '(existT _ len _) =>\n   (if sumbool_of_bool (Z.gtb (Z.add (projT1 (uint pc)) 4) len) then\n      (raise_c2_exception_noreg CapEx_LengthViolation)\n       : M (unit)\n    else returnm tt) >>\n   (execute_branch_mips pc)\n    : M (unit).\n\nDefinition TranslatePC (vAddr : mword 64) : M (mword 64) :=\n   (incrementCP0Count tt) >>\n   read_reg PCC_ref >>= fun pcc =>\n   let '(existT _ base _, existT _ top _) := getCapBounds pcc in\n   let absPC := Z.add base (projT1 (uint vAddr)) in\n   (if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq absPC 4)) 0)) then\n      (SignalExceptionBadAddr AdEL (to_bits 64 absPC))\n       : M (mword 64)\n    else if negb pcc.(Capability_tag) then\n      (raise_c2_exception_noreg CapEx_TagViolation)\n       : M (mword 64)\n    else if pcc.(Capability_sealed) then\n      (raise_c2_exception_noreg CapEx_SealViolation)\n       : M (mword 64)\n    else if negb pcc.(Capability_permit_execute) then\n      (raise_c2_exception_noreg CapEx_PermitExecuteViolation)\n       : M (mword 64)\n    else if sumbool_of_bool (Z.gtb (Z.add absPC 4) top) then\n      (raise_c2_exception_noreg CapEx_LengthViolation)\n       : M (mword 64)\n    else (TLBTranslate (to_bits 64 absPC) Instruction)  : M (mword 64))\n    : M (mword 64).\n\nDefinition checkCP2usable '(tt : unit) : M (unit) :=\n   read_reg CP0Status_ref >>= fun w__0 : StatusReg =>\n   (if negb (bit_to_bool (access_vec_dec (_get_StatusReg_CU w__0) 2)) then\n      (_set_CauseReg_CE CP0Cause_ref ('b\"10\"  : mword 2)) >> (SignalException CpU)  : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition init_cp2_state '(tt : unit) : M (unit) :=\n   write_reg PCC_ref default_cap >>\n   write_reg NextPCC_ref default_cap >>\n   write_reg DelayedPCC_ref default_cap >>\n   write_reg DDC_ref default_cap >>\n   write_reg KCC_ref default_cap >>\n   write_reg EPCC_ref default_cap >>\n   write_reg ErrorEPCC_ref default_cap >>\n   write_reg KDC_ref null_cap >>\n   write_reg KR1C_ref null_cap >>\n   write_reg KR2C_ref null_cap >>\n   write_reg CPLR_ref null_cap >>\n   write_reg CULR_ref null_cap >>\n   let loop_i_lower := 1 in\n   let loop_i_upper := 31 in\n   (foreach_ZM_up loop_i_lower loop_i_upper 1 tt\n     (fun i _ _ =>\n       let idx := to_bits 5 i in\n       (writeCapReg idx null_cap)\n        : M (unit))).\n\nDefinition cp2_next_pc '(tt : unit) : M (unit) :=\n   read_reg NextPCC_ref >>= fun w__0 : Capability =>\n   write_reg PCC_ref w__0 >>\n   ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__1 : mword 1 =>\n   (if (bits_to_bool w__1)  : bool then\n      read_reg DelayedPCC_ref >>= fun w__2 : Capability => write_reg NextPCC_ref w__2  : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition get_CP0EPC '(tt : unit) : M (mword 64) :=\n   read_reg EPCC_ref >>= fun w__0 : Capability => returnm (to_bits 64 (projT1 (getCapOffset w__0))).\n\nDefinition set_CP0EPC (newEPC : mword 64) : M (unit) :=\n   read_reg EPCC_ref >>= fun w__0 : Capability =>\n   let '(representable, newEPCC) := setCapOffset w__0 newEPC in\n   write_reg\n     EPCC_ref\n     (if sumbool_of_bool representable then\n        {[ newEPCC with\n          Capability_tag := (andb newEPCC.(Capability_tag) (negb newEPCC.(Capability_sealed))) ]}\n      else unrepCap newEPCC)\n    : M (unit).\n\nDefinition get_CP0ErrorEPC '(tt : unit) : M (mword 64) :=\n   read_reg ErrorEPCC_ref >>= fun w__0 : Capability =>\n   returnm (to_bits 64 (projT1 (getCapOffset w__0))).\n\nDefinition set_CP0ErrorEPC (v : mword 64) : M (unit) :=\n   read_reg ErrorEPCC_ref >>= fun w__0 : Capability =>\n   let '(representable, newErrorEPCC) := setCapOffset w__0 v in\n   write_reg\n     ErrorEPCC_ref\n     (if sumbool_of_bool representable then\n        {[ newErrorEPCC with\n          Capability_tag :=\n            (andb newErrorEPCC.(Capability_tag) (negb newErrorEPCC.(Capability_sealed))) ]}\n      else unrepCap newErrorEPCC)\n    : M (unit).\n\nDefinition dump_cp2_state '(tt : unit) : M (unit) :=\n   read_reg PCC_ref >>= fun w__0 : Capability =>\n   (capToString w__0 true) >>= fun w__1 : string =>\n   let '_ := (print_endline (String.append \"DEBUG CAP PCC\" w__1))  : unit in\n   (let loop_i_lower := 0 in\n   let loop_i_upper := 31 in\n   (foreach_ZM_up loop_i_lower loop_i_upper 1 tt\n     (fun i _ _ =>\n       (readCapReg (to_bits 5 i)) >>= fun w__2 : Capability =>\n       (capToString w__2 true) >>= fun w__3 : string =>\n       returnm (let '_ :=\n         (print_endline (String.append \"DEBUG CAP REG \" (String.append (string_of_int i) w__3)))\n          : unit in\n       tt)))) >>\n   read_reg DDC_ref >>= fun w__4 : Capability =>\n   (capToString w__4 true) >>= fun w__5 : string =>\n   let '_ := (print_endline (String.append \"DEBUG CAP HWREG 00\" w__5))  : unit in\n   read_reg CULR_ref >>= fun w__6 : Capability =>\n   (capToString w__6 true) >>= fun w__7 : string =>\n   let '_ := (print_endline (String.append \"DEBUG CAP HWREG 01\" w__7))  : unit in\n   read_reg CPLR_ref >>= fun w__8 : Capability =>\n   (capToString w__8 true) >>= fun w__9 : string =>\n   let '_ := (print_endline (String.append \"DEBUG CAP HWREG 08\" w__9))  : unit in\n   read_reg KR1C_ref >>= fun w__10 : Capability =>\n   (capToString w__10 true) >>= fun w__11 : string =>\n   let '_ := (print_endline (String.append \"DEBUG CAP HWREG 22\" w__11))  : unit in\n   read_reg KR2C_ref >>= fun w__12 : Capability =>\n   (capToString w__12 true) >>= fun w__13 : string =>\n   let '_ := (print_endline (String.append \"DEBUG CAP HWREG 23\" w__13))  : unit in\n   read_reg ErrorEPCC_ref >>= fun w__14 : Capability =>\n   (capToString w__14 true) >>= fun w__15 : string =>\n   let '_ := (print_endline (String.append \"DEBUG CAP HWREG 28\" w__15))  : unit in\n   read_reg KCC_ref >>= fun w__16 : Capability =>\n   (capToString w__16 true) >>= fun w__17 : string =>\n   let '_ := (print_endline (String.append \"DEBUG CAP HWREG 29\" w__17))  : unit in\n   read_reg KDC_ref >>= fun w__18 : Capability =>\n   (capToString w__18 true) >>= fun w__19 : string =>\n   let '_ := (print_endline (String.append \"DEBUG CAP HWREG 30\" w__19))  : unit in\n   read_reg EPCC_ref >>= fun w__20 : Capability =>\n   (capToString w__20 true) >>= fun w__21 : string =>\n   returnm (print_endline (String.append \"DEBUG CAP HWREG 31\" w__21)).\n\nDefinition getCapFlags (cap : Capability) : mword 1 := 'b\"0\"  : mword 1.\n\nDefinition setCapFlags (cap : Capability) (flags : mword 1) : Capability := cap.\n\nDefinition isSentryCap (cap : Capability) : bool :=\n   Z.eqb (projT1 (sint cap.(Capability_otype))) otype_sentry.\n\nDefinition ERETHook '(tt : unit) : M (unit) :=\n   read_reg CP0Status_ref >>= fun w__0 : StatusReg =>\n   (if Bool.eqb (bits_to_bool (_get_StatusReg_ERL w__0)) (bit_to_bool B1) then\n      read_reg ErrorEPCC_ref\n       : M (Capability)\n    else read_reg EPCC_ref  : M (Capability)) >>= fun epcc_val =>\n   let new_pcc := if isSentryCap epcc_val then unsealCap epcc_val else epcc_val in\n   (set_next_pcc new_pcc)\n    : M (unit).\n\nDefinition TLBWriteEntry (idx : mword 6) : M (unit) :=\n   ((read_reg TLBPageMask_ref)  : M (mword 16)) >>= fun pagemask =>\n   let b__0 := pagemask in\n   (if eq_vec b__0 (Ox\"0000\"  : mword 16) then returnm tt\n    else if eq_vec b__0 (Ox\"0003\"  : mword 16) then returnm tt\n    else if eq_vec b__0 (Ox\"000F\"  : mword 16) then returnm tt\n    else if eq_vec b__0 (Ox\"003F\"  : mword 16) then returnm tt\n    else if eq_vec b__0 (Ox\"00FF\"  : mword 16) then returnm tt\n    else if eq_vec b__0 (Ox\"03FF\"  : mword 16) then returnm tt\n    else if eq_vec b__0 (Ox\"0FFF\"  : mword 16) then returnm tt\n    else if eq_vec b__0 (Ox\"3FFF\"  : mword 16) then returnm tt\n    else if eq_vec b__0 (Ox\"FFFF\"  : mword 16) then returnm tt\n    else (SignalException MCheck)  : M (unit)) >>\n   let i := projT1 (uint idx) in\n   let entry := vec_access_dec TLBEntries i in\n   (_set_TLBEntry_pagemask entry pagemask) >>\n   read_reg TLBEntryHi_ref >>= fun w__0 : TLBEntryHiReg =>\n   (_set_TLBEntry_r entry (_get_TLBEntryHiReg_R w__0)) >>\n   read_reg TLBEntryHi_ref >>= fun w__1 : TLBEntryHiReg =>\n   (_set_TLBEntry_vpn2 entry (_get_TLBEntryHiReg_VPN2 w__1)) >>\n   read_reg TLBEntryHi_ref >>= fun w__2 : TLBEntryHiReg =>\n   (_set_TLBEntry_asid entry (_get_TLBEntryHiReg_ASID w__2)) >>\n   (and_boolM\n      (read_reg TLBEntryLo0_ref >>= fun w__3 : TLBEntryLoReg =>\n       returnm ((bits_to_bool (_get_TLBEntryLoReg_G w__3))  : bool))\n      (read_reg TLBEntryLo1_ref >>= fun w__4 : TLBEntryLoReg =>\n       returnm ((bits_to_bool (_get_TLBEntryLoReg_G w__4))  : bool))) >>= fun w__5 : bool =>\n   (_set_TLBEntry_g entry ((bool_to_bits w__5)  : mword 1)) >>\n   (_set_TLBEntry_valid entry ((cast_unit_vec B1)  : mword 1)) >>\n   read_reg TLBEntryLo0_ref >>= fun w__6 : TLBEntryLoReg =>\n   (_set_TLBEntry_caps0 entry (_get_TLBEntryLoReg_CapS w__6)) >>\n   read_reg TLBEntryLo0_ref >>= fun w__7 : TLBEntryLoReg =>\n   (_set_TLBEntry_capl0 entry (_get_TLBEntryLoReg_CapL w__7)) >>\n   read_reg TLBEntryLo0_ref >>= fun w__8 : TLBEntryLoReg =>\n   (_set_TLBEntry_caplg0 entry (_get_TLBEntryLoReg_CapLG w__8)) >>\n   read_reg TLBEntryLo0_ref >>= fun w__9 : TLBEntryLoReg =>\n   (_set_TLBEntry_pfn0 entry (_get_TLBEntryLoReg_PFN w__9)) >>\n   read_reg TLBEntryLo0_ref >>= fun w__10 : TLBEntryLoReg =>\n   (_set_TLBEntry_c0 entry (_get_TLBEntryLoReg_C w__10)) >>\n   read_reg TLBEntryLo0_ref >>= fun w__11 : TLBEntryLoReg =>\n   (_set_TLBEntry_d0 entry (_get_TLBEntryLoReg_D w__11)) >>\n   read_reg TLBEntryLo0_ref >>= fun w__12 : TLBEntryLoReg =>\n   (_set_TLBEntry_v0 entry (_get_TLBEntryLoReg_V w__12)) >>\n   read_reg TLBEntryLo1_ref >>= fun w__13 : TLBEntryLoReg =>\n   (_set_TLBEntry_caps1 entry (_get_TLBEntryLoReg_CapS w__13)) >>\n   read_reg TLBEntryLo1_ref >>= fun w__14 : TLBEntryLoReg =>\n   (_set_TLBEntry_capl1 entry (_get_TLBEntryLoReg_CapL w__14)) >>\n   read_reg TLBEntryLo1_ref >>= fun w__15 : TLBEntryLoReg =>\n   (_set_TLBEntry_caplg1 entry (_get_TLBEntryLoReg_CapLG w__15)) >>\n   read_reg TLBEntryLo1_ref >>= fun w__16 : TLBEntryLoReg =>\n   (_set_TLBEntry_pfn1 entry (_get_TLBEntryLoReg_PFN w__16)) >>\n   read_reg TLBEntryLo1_ref >>= fun w__17 : TLBEntryLoReg =>\n   (_set_TLBEntry_c1 entry (_get_TLBEntryLoReg_C w__17)) >>\n   read_reg TLBEntryLo1_ref >>= fun w__18 : TLBEntryLoReg =>\n   (_set_TLBEntry_d1 entry (_get_TLBEntryLoReg_D w__18)) >>\n   read_reg TLBEntryLo1_ref >>= fun w__19 : TLBEntryLoReg =>\n   (_set_TLBEntry_v1 entry (_get_TLBEntryLoReg_V w__19))\n    : M (unit).\n\nDefinition strCReg (r : mword 5) : string := concat_str_dec \"$c\" (projT1 (uint r)).\n\nDefinition strRRArgs (rd : mword 5) (r1 : mword 5) : string :=\n   String.append (strReg rd) (String.append \", \" (strReg r1)).\n\nDefinition strRCArgs (rd : mword 5) (c1 : mword 5) : string :=\n   String.append (strReg rd) (String.append \", \" (strCReg c1)).\n\nDefinition strCRArgs (cd : mword 5) (r1 : mword 5) : string :=\n   String.append (strCReg cd) (String.append \", \" (strReg r1)).\n\nDefinition strCCArgs (cd : mword 5) (c1 : mword 5) : string :=\n   String.append (strCReg cd) (String.append \", \" (strCReg c1)).\n\nDefinition strCCCArgs (cd : mword 5) (c1 : mword 5) (c2 : mword 5) : string :=\n   String.append (strCReg cd)\n     (String.append \", \" (String.append (strCReg c1) (String.append \", \" (strCReg c2)))).\n\nDefinition strCCRArgs (cd : mword 5) (c1 : mword 5) (r2 : mword 5) : string :=\n   String.append (strCReg cd)\n     (String.append \", \" (String.append (strCReg c1) (String.append \", \" (strReg r2)))).\n\nDefinition strRCCArgs (rd : mword 5) (c1 : mword 5) (c2 : mword 5) : string :=\n   String.append (strReg rd)\n     (String.append \", \" (String.append (strCReg c1) (String.append \", \" (strCReg c2)))).\n\nDefinition strRCRArgs (rd : mword 5) (c1 : mword 5) (r2 : mword 5) : string :=\n   String.append (strReg rd)\n     (String.append \", \" (String.append (strCReg c1) (String.append \", \" (strReg r2)))).\n\nDefinition strCCIArgs {n : Z} (cd : mword 5) (cs : mword 5) (imm : mword n) `{ArithFact (n >? 0)}\n: string :=\n   String.append (strCReg cd)\n     (String.append \", \"\n        (String.append (strCReg cs) (String.append \", \" (dec_str (projT1 (sint imm)))))).\n\nDefinition strCCIUArgs {n : Z} (cd : mword 5) (cs : mword 5) (imm : mword n) `{ArithFact (n >? 0)}\n: string :=\n   String.append (strCReg cd)\n     (String.append \", \"\n        (String.append (strCReg cs) (String.append \", \" (hex_str (projT1 (uint imm)))))).\n\nDefinition decode (v__0 : mword 32) : option ast :=\n   if eq_vec (subrange_vec_dec v__0 31 26) ('b\"011001\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (DADDIU (rs, rt, imm))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000101101\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DADDU (rs, rt, rd))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"011000\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (DADDI (rs, rt, imm))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000101100\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DADD (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000100000\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (ADD (rs, rt, rd))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"001000\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (ADDI (rs, rt, imm))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000100001\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (ADDU (rs, rt, rd))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"001001\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (ADDIU (rs, rt, imm))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000101111\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DSUBU (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000101110\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DSUB (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000100010\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (SUB (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000100011\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (SUBU (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000100100\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (AND (rs, rt, rd))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"001100\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (ANDI (rs, rt, imm))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000100101\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (OR (rs, rt, rd))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"001101\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (ORI (rs, rt, imm))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000100111\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (NOR (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000100110\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (XOR (rs, rt, rd))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"001110\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (XORI (rs, rt, imm))\n   else if eq_vec (subrange_vec_dec v__0 31 21) ('b\"00111100000\"  : mword (31 - 21 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (LUI (rt, imm))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"00000000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"111000\"  : mword (5 - 0 + 1))) then\n     let sa : bits 5 := subrange_vec_dec v__0 10 6 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DSLL (rt, rd, sa))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"00000000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"111100\"  : mword (5 - 0 + 1))) then\n     let sa : bits 5 := subrange_vec_dec v__0 10 6 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DSLL32 (rt, rd, sa))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000010100\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DSLLV (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"00000000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"111011\"  : mword (5 - 0 + 1))) then\n     let sa : bits 5 := subrange_vec_dec v__0 10 6 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DSRA (rt, rd, sa))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"00000000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"111111\"  : mword (5 - 0 + 1))) then\n     let sa : bits 5 := subrange_vec_dec v__0 10 6 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DSRA32 (rt, rd, sa))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000010111\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DSRAV (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"00000000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"111010\"  : mword (5 - 0 + 1))) then\n     let sa : bits 5 := subrange_vec_dec v__0 10 6 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DSRL (rt, rd, sa))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"00000000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"111110\"  : mword (5 - 0 + 1))) then\n     let sa : bits 5 := subrange_vec_dec v__0 10 6 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DSRL32 (rt, rd, sa))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000010110\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (DSRLV (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"00000000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000000\"  : mword (5 - 0 + 1))) then\n     let sa : regno := subrange_vec_dec v__0 10 6 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (SLL (rt, rd, sa))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000100\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (SLLV (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"00000000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000011\"  : mword (5 - 0 + 1))) then\n     let sa : regno := subrange_vec_dec v__0 10 6 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (SRA (rt, rd, sa))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000111\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (SRAV (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"00000000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000010\"  : mword (5 - 0 + 1))) then\n     let sa : regno := subrange_vec_dec v__0 10 6 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (SRL (rt, rd, sa))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000110\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (SRLV (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000101010\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (SLT (rs, rt, rd))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"001010\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (SLTI (rs, rt, imm))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000101011\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (SLTU (rs, rt, rd))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"001011\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (SLTIU (rs, rt, imm))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000001011\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (MOVN (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000001010\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (MOVZ (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 16) (Ox\"0000\"  : mword (31 - 16 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000010000\"  : mword (10 - 0 + 1))) then\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (MFHI rd)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 16) (Ox\"0000\"  : mword (31 - 16 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000010010\"  : mword (10 - 0 + 1))) then\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (MFLO rd)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 0) ('b\"000000000000000010001\"  : mword (20 - 0 + 1)))\n   then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (MTHI rs)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 0) ('b\"000000000000000010011\"  : mword (20 - 0 + 1)))\n   then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (MTLO rs)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"011100\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000010\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (MUL (rs, rt, rd))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"0018\"  : mword (15 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (MULT (rs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"0019\"  : mword (15 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (MULTU (rs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"001C\"  : mword (15 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (DMULT (rs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"001D\"  : mword (15 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (DMULTU (rs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"011100\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"0000\"  : mword (15 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (MADD (rs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"011100\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"0001\"  : mword (15 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (MADDU (rs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"011100\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"0004\"  : mword (15 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (MSUB (rs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"011100\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"0005\"  : mword (15 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (MSUBU (rs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"001A\"  : mword (15 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (DIV (rs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"001B\"  : mword (15 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (DIVU (rs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"001E\"  : mword (15 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (DDIV (rs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"001F\"  : mword (15 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (DDIVU (rs, rt))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"000010\"  : mword (31 - 26 + 1)) then\n     let offset : bits 26 := subrange_vec_dec v__0 25 0 in\n     Some (J offset)\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"000011\"  : mword (31 - 26 + 1)) then\n     let offset : bits 26 := subrange_vec_dec v__0 25 0 in\n     Some (JAL offset)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (andb (eq_vec (subrange_vec_dec v__0 20 11) ('b\"0000000000\"  : mword (20 - 11 + 1)))\n                (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001000\"  : mword (5 - 0 + 1)))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (JR rs)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (andb (eq_vec (subrange_vec_dec v__0 20 16) ('b\"00000\"  : mword (20 - 16 + 1)))\n                (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001001\"  : mword (5 - 0 + 1)))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (JALR (rs, rd))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"000100\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BEQ (rs, rt, imm, false, false))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"010100\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BEQ (rs, rt, imm, false, true))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"000101\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BEQ (rs, rt, imm, true, false))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"010101\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BEQ (rs, rt, imm, true, true))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"00000\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BCMPZ (rs, imm, LT', false, false))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"10000\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BCMPZ (rs, imm, LT', true, false))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"00010\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BCMPZ (rs, imm, LT', false, true))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"10010\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BCMPZ (rs, imm, LT', true, true))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"00001\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BCMPZ (rs, imm, GE, false, false))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"10001\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BCMPZ (rs, imm, GE, true, false))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"00011\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BCMPZ (rs, imm, GE, false, true))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"10011\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BCMPZ (rs, imm, GE, true, true))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000111\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"00000\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BCMPZ (rs, imm, GT', false, false))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"010111\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"00000\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BCMPZ (rs, imm, GT', false, true))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000110\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"00000\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BCMPZ (rs, imm, LE, false, false))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"010110\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"00000\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (BCMPZ (rs, imm, LE, false, true))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001100\"  : mword (5 - 0 + 1))) then\n     Some (SYSCALL tt)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001101\"  : mword (5 - 0 + 1))) then\n     Some (BREAK tt)\n   else if eq_vec v__0 (Ox\"42000020\"  : mword 32) then Some (WAIT tt)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"110000\"  : mword (5 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (TRAPREG (rs, rt, GE))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"110001\"  : mword (5 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (TRAPREG (rs, rt, GEU))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"110010\"  : mword (5 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (TRAPREG (rs, rt, LT'))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"110011\"  : mword (5 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (TRAPREG (rs, rt, LTU))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"110100\"  : mword (5 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (TRAPREG (rs, rt, EQ'))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000000\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"110110\"  : mword (5 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     Some (TRAPREG (rs, rt, NE))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"01100\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (TRAPIMM (rs, imm, EQ'))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"01110\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (TRAPIMM (rs, imm, NE))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"01000\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (TRAPIMM (rs, imm, GE))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"01001\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (TRAPIMM (rs, imm, GEU))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"01010\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (TRAPIMM (rs, imm, LT'))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"000001\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 20 16) ('b\"01011\"  : mword (20 - 16 + 1))) then\n     let rs : regno := subrange_vec_dec v__0 25 21 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     Some (TRAPIMM (rs, imm, LTU))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"100000\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Load (B, true, false, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"100100\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Load (B, false, false, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"100001\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Load (H, true, false, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"100101\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Load (H, false, false, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"100011\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Load (W, true, false, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"100111\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Load (W, false, false, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"110111\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Load (D, false, false, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"110000\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Load (W, true, true, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"110100\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Load (D, false, true, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"101000\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Store (B, false, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"101001\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Store (H, false, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"101011\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Store (W, false, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"111111\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Store (D, false, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"111000\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Store (W, true, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"111100\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (Store (D, true, base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"100010\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (LWL (base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"100110\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (LWR (base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"101010\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (SWL (base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"101110\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (SWR (base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"011010\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (LDL (base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"011011\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (LDR (base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"101100\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (SDL (base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"101101\"  : mword (31 - 26 + 1)) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let offset : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (SDR (base, rt, offset))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"101111\"  : mword (31 - 26 + 1)) then\n     let op : regno := subrange_vec_dec v__0 20 16 in\n     let imm : imm16 := subrange_vec_dec v__0 15 0 in\n     let base : regno := subrange_vec_dec v__0 25 21 in\n     Some (CACHE (base, op, imm))\n   else if andb\n             (eq_vec (subrange_vec_dec v__0 31 11)\n                ('b\"000000000000000000000\"\n                 : mword (31 - 11 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001111\"  : mword (5 - 0 + 1))) then\n     Some (SYNC tt)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01000000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 3) (Ox\"00\"  : mword (10 - 3 + 1))) then\n     let sel : bits 3 := subrange_vec_dec v__0 2 0 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (MFC0 (rt, rd, sel, false))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01000000001\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 3) (Ox\"00\"  : mword (10 - 3 + 1))) then\n     let sel : bits 3 := subrange_vec_dec v__0 2 0 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (MFC0 (rt, rd, sel, true))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01000000100\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"B800\"  : mword (15 - 0 + 1))) then\n     Some (HCF tt)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01000000100\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"D000\"  : mword (15 - 0 + 1))) then\n     Some (HCF tt)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01000000100\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 3) (Ox\"00\"  : mword (10 - 3 + 1))) then\n     let sel : bits 3 := subrange_vec_dec v__0 2 0 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (MTC0 (rt, rd, sel, false))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01000000101\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 3) (Ox\"00\"  : mword (10 - 3 + 1))) then\n     let sel : bits 3 := subrange_vec_dec v__0 2 0 in\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (MTC0 (rt, rd, sel, true))\n   else if eq_vec v__0 (Ox\"42000002\"  : mword 32) then Some ((TLBWI tt)  : ast)\n   else if eq_vec v__0 (Ox\"42000006\"  : mword 32) then Some ((TLBWR tt)  : ast)\n   else if eq_vec v__0 (Ox\"42000001\"  : mword 32) then Some ((TLBR tt)  : ast)\n   else if eq_vec v__0 (Ox\"42000008\"  : mword 32) then Some ((TLBP tt)  : ast)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01111100000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000111011\"  : mword (10 - 0 + 1))) then\n     let rt : regno := subrange_vec_dec v__0 20 16 in\n     let rd : regno := subrange_vec_dec v__0 15 11 in\n     Some (RDHWR (rt, rd))\n   else if eq_vec v__0 (Ox\"42000018\"  : mword 32) then Some (ERET tt)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000000\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetPerm (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000001\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetType (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000010\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetBase (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000011\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetLen (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000101\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetTag (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000110\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetSealed (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"0004\"  : mword (15 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CGetCause rd)\n   else if eq_vec v__0 (Ox\"48C00000\"  : mword 32) then Some (CReturn tt)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001101\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000010\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetOffset (rd, cb))\n   else if andb\n             (eq_vec (subrange_vec_dec v__0 31 11)\n                ('b\"010010001000000000000\"\n                 : mword (31 - 11 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000100\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     Some (CSetCause rt)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000100\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000000\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CAndPerm (cd, cb, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001100\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000000\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let ct : CapRegOrDDCEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CToPtr (rd, cb, ct))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001110\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000000\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, ct, CEQ))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001110\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000001\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, ct, CNE))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001110\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000010\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, ct, CLT))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001110\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000011\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, ct, CLE))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001110\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000100\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, ct, CLTU))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001110\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000101\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, ct, CLEU))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001110\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000110\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, ct, CEXEQ))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001110\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000111\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, ct, CNEXEQ))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001101\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000000\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CIncOffset (cd, cb, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001101\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000001\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CSetOffset (cd, cb, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000001\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000000\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CSetBounds (cd, cb, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000100\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000101\"  : mword (10 - 0 + 1))) then\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CClearTag (cd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000100\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000111\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CFromPtr (cd, cb, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001011\"  : mword (31 - 21 + 1)))\n             (andb (eq_vec (subrange_vec_dec v__0 15 11) ('b\"00000\"  : mword (15 - 11 + 1)))\n                (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000000\"  : mword (5 - 0 + 1)))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CCheckPerm (cs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001011\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000001\"  : mword (10 - 0 + 1))) then\n     let cs : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CCheckType (cs, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000010\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000000\"  : mword (5 - 0 + 1))) then\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CSeal (cd, cs, ct))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000011\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000000\"  : mword (5 - 0 + 1))) then\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CUnseal (cd, cs, ct))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000111\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000000\"  : mword (10 - 0 + 1))) then\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CJALR (cd, cb, true))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 16) (Ox\"4900\"  : mword (31 - 16 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000000000\"  : mword (10 - 0 + 1))) then\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CJALR ('b\"00000\"  : mword 5, cb, false))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"0FFF\"  : mword (15 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CGetCause rd)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"17FF\"  : mword (15 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CSetCause rs)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"07FF\"  : mword (15 - 0 + 1))) then\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CGetPCC cd)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"1FFF\"  : mword (15 - 0 + 1))) then\n     let cb : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CJALR ('b\"00000\"  : mword 5, cb, false))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"27FF\"  : mword (15 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CGetCID rd)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"2FFF\"  : mword (15 - 0 + 1))) then\n     let cb : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CSetCID cb)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"C7FF\"  : mword (15 - 0 + 1))) then\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CClearTags cb)\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"01000111111\"  : mword (10 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CCheckPerm (cs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"01001111111\"  : mword (10 - 0 + 1))) then\n     let cs : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CCheckType (cs, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"01011111111\"  : mword (10 - 0 + 1))) then\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CClearTag (cd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"01010111111\"  : mword (10 - 0 + 1))) then\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CMove (cd, cs))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"01100111111\"  : mword (10 - 0 + 1))) then\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CJALR (cd, cb, true))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"11101111111\"  : mword (10 - 0 + 1))) then\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CSealEntry (cd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"11110111111\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CLoadTags (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000111111\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetPerm (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00001111111\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetType (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00010111111\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetBase (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00011111111\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetLen (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00100111111\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetTag (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00101111111\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetSealed (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00110111111\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetOffset (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00111111111\"  : mword (10 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CGetPCCSetOffset (cd, rs))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"01101111111\"  : mword (10 - 0 + 1))) then\n     let sel : CapHwrEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CReadHwr (cd, sel))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"01110111111\"  : mword (10 - 0 + 1))) then\n     let sel : CapHwrEnc := subrange_vec_dec v__0 15 11 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CWriteHwr (cb, sel))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"01111111111\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetAddr (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"10010111111\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetFlags (rd, cb))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"10011111111\"  : mword (10 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CGetPCCIncOffset (cd, rs))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"10100111111\"  : mword (10 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CGetPCCSetAddr (cd, rs))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"10000111111\"  : mword (10 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let rs : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CRAP (rt, rs))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"10001111111\"  : mword (10 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let rs : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CRAM (rt, rs))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001011\"  : mword (5 - 0 + 1))) then\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CSeal (cd, cs, ct))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001100\"  : mword (5 - 0 + 1))) then\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CUnseal (cd, cs, ct))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001101\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CAndPerm (cd, cs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001111\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CSetOffset (cd, cs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001000\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CSetBounds (cd, cs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001001\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CSetBoundsExact (cd, cs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001110\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CSetFlags (cd, cs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"010001\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CIncOffset (cd, cb, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"011101\"  : mword (5 - 0 + 1))) then\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CBuildCap (cd, cb, ct))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"011110\"  : mword (5 - 0 + 1))) then\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CCopyType (cd, cb, ct))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"011111\"  : mword (5 - 0 + 1))) then\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CCSeal (cd, cs, ct))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"010010\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CToPtr (rd, cb, ct))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"010011\"  : mword (5 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CFromPtr (cd, cb, rs))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"001010\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CSub (rt, cb, cs))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"011011\"  : mword (5 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CMOVX (cd, cs, rs, false))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"011100\"  : mword (5 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CMOVX (cd, cs, rs, true))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"100010\"  : mword (5 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CSetAddr (cd, cs, rs))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"100011\"  : mword (5 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CGetAndAddr (rd, cs, rs))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"100100\"  : mword (5 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CAndAddr (cd, cs, rt))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"010100\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, cs, CEQ))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"010101\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, cs, CNE))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"010110\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, cs, CLT))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"010111\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, cs, CLE))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"011000\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, cs, CLTU))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"011001\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, cs, CLEU))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"011010\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, cs, CEXEQ))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"100001\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CPtrCmp (rd, cb, cs, CNEXEQ))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"100000\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let ct : CapRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CTestSubset (rd, cb, ct))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"111000\"  : mword (5 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CLCNT (cd, cs, rs))\n   else if eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001001\"  : mword (31 - 21 + 1)) then\n     let imm : bits 16 := subrange_vec_dec v__0 15 0 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CBX (cd, imm, true))\n   else if eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001001010\"  : mword (31 - 21 + 1)) then\n     let imm : bits 16 := subrange_vec_dec v__0 15 0 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CBX (cd, imm, false))\n   else if eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010001\"  : mword (31 - 21 + 1)) then\n     let imm : bits 16 := subrange_vec_dec v__0 15 0 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CBZ (cd, imm, false))\n   else if eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010010\"  : mword (31 - 21 + 1)) then\n     let imm : bits 16 := subrange_vec_dec v__0 15 0 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (CBZ (cd, imm, true))\n   else if eq_vec v__0 (Ox\"48A007FF\"  : mword 32) then Some (CReturn tt)\n   else if eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000101\"  : mword (31 - 21 + 1)) then\n     let selector : bits 11 := subrange_vec_dec v__0 10 0 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CCall (cs, cb, selector))\n   else if eq_vec (subrange_vec_dec v__0 31 16) (Ox\"49E0\"  : mword (31 - 16 + 1)) then\n     let imm : bits 16 := subrange_vec_dec v__0 15 0 in\n     Some (ClearRegs (GPLo, imm))\n   else if eq_vec (subrange_vec_dec v__0 31 16) (Ox\"49E1\"  : mword (31 - 16 + 1)) then\n     let imm : bits 16 := subrange_vec_dec v__0 15 0 in\n     Some (ClearRegs (GPHi, imm))\n   else if eq_vec (subrange_vec_dec v__0 31 16) (Ox\"49E2\"  : mword (31 - 16 + 1)) then\n     let imm : bits 16 := subrange_vec_dec v__0 15 0 in\n     Some (ClearRegs (CLo, imm))\n   else if eq_vec (subrange_vec_dec v__0 31 16) (Ox\"49E3\"  : mword (31 - 16 + 1)) then\n     let imm : bits 16 := subrange_vec_dec v__0 15 0 in\n     Some (ClearRegs (CHi, imm))\n   else if eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010011\"  : mword (31 - 21 + 1)) then\n     let imm : bits 11 := subrange_vec_dec v__0 10 0 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CIncOffsetImmediate (cd, cb, imm))\n   else if eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010100\"  : mword (31 - 21 + 1)) then\n     let imm : bits 11 := subrange_vec_dec v__0 10 0 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegEnc := subrange_vec_dec v__0 15 11 in\n     Some (CSetBoundsImmediate (cd, cb, imm))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"110010\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 2 0) ('b\"000\"  : mword (2 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in\n     let offset : bits 8 := subrange_vec_dec v__0 10 3 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CLoad (rd, cb, rt, offset, false, B))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"110010\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 2 0) ('b\"100\"  : mword (2 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in\n     let offset : bits 8 := subrange_vec_dec v__0 10 3 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CLoad (rd, cb, rt, offset, true, B))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"110010\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 2 0) ('b\"001\"  : mword (2 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in\n     let offset : bits 8 := subrange_vec_dec v__0 10 3 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CLoad (rd, cb, rt, offset, false, H))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"110010\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 2 0) ('b\"101\"  : mword (2 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in\n     let offset : bits 8 := subrange_vec_dec v__0 10 3 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CLoad (rd, cb, rt, offset, true, H))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"110010\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 2 0) ('b\"010\"  : mword (2 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in\n     let offset : bits 8 := subrange_vec_dec v__0 10 3 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CLoad (rd, cb, rt, offset, false, W))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"110010\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 2 0) ('b\"110\"  : mword (2 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in\n     let offset : bits 8 := subrange_vec_dec v__0 10 3 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CLoad (rd, cb, rt, offset, true, W))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"110010\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 2 0) ('b\"011\"  : mword (2 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let rd : IntRegEnc := subrange_vec_dec v__0 25 21 in\n     let offset : bits 8 := subrange_vec_dec v__0 10 3 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CLoad (rd, cb, rt, offset, false, D))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000001000\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CLoadLinked (rd, cb, false, B))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000001100\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CLoadLinked (rd, cb, true, B))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000001001\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CLoadLinked (rd, cb, false, H))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000001101\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CLoadLinked (rd, cb, true, H))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000001010\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CLoadLinked (rd, cb, false, W))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000001110\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CLoadLinked (rd, cb, true, W))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000001011\"  : mword (10 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CLoadLinked (rd, cb, false, D))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"111010\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 2 0) ('b\"000\"  : mword (2 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let rs : IntRegEnc := subrange_vec_dec v__0 25 21 in\n     let offset : bits 8 := subrange_vec_dec v__0 10 3 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CStore (rs, cb, rt, offset, B))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"111010\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 2 0) ('b\"001\"  : mword (2 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let rs : IntRegEnc := subrange_vec_dec v__0 25 21 in\n     let offset : bits 8 := subrange_vec_dec v__0 10 3 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CStore (rs, cb, rt, offset, H))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"111010\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 2 0) ('b\"010\"  : mword (2 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let rs : IntRegEnc := subrange_vec_dec v__0 25 21 in\n     let offset : bits 8 := subrange_vec_dec v__0 10 3 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CStore (rs, cb, rt, offset, W))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 26) ('b\"111010\"  : mword (31 - 26 + 1)))\n             (eq_vec (subrange_vec_dec v__0 2 0) ('b\"011\"  : mword (2 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let rs : IntRegEnc := subrange_vec_dec v__0 25 21 in\n     let offset : bits 8 := subrange_vec_dec v__0 10 3 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CStore (rs, cb, rt, offset, D))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000000\"  : mword (5 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let rd : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CStoreConditional (rs, cb, rd, B))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000001\"  : mword (5 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let rd : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CStoreConditional (rs, cb, rd, H))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000010\"  : mword (5 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let rd : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CStoreConditional (rs, cb, rd, W))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000011\"  : mword (5 - 0 + 1))) then\n     let rs : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     let rd : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CStoreConditional (rs, cb, rd, D))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"111110\"  : mword (31 - 26 + 1)) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let offset : bits 11 := subrange_vec_dec v__0 10 0 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 25 21 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CSC (cs, cb, rt, offset))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 5 0) ('b\"000111\"  : mword (5 - 0 + 1))) then\n     let rd : IntRegEnc := subrange_vec_dec v__0 10 6 in\n     let cs : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CSCC (cs, cb, rd))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"110110\"  : mword (31 - 26 + 1)) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 15 11 in\n     let offset : bits 11 := subrange_vec_dec v__0 10 0 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 25 21 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CLC (cd, cb, rt, offset))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001010000\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 10 0) ('b\"00000001111\"  : mword (10 - 0 + 1))) then\n     let cd : CapRegEnc := subrange_vec_dec v__0 20 16 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 15 11 in\n     Some (CLLC (cd, cb))\n   else if eq_vec (subrange_vec_dec v__0 31 26) ('b\"011101\"  : mword (31 - 26 + 1)) then\n     let offset : bits 16 := subrange_vec_dec v__0 15 0 in\n     let cd : CapRegEnc := subrange_vec_dec v__0 25 21 in\n     let cb : CapRegOrDDCEnc := subrange_vec_dec v__0 20 16 in\n     Some (CLCBI (cd, cb, offset))\n   else if andb (eq_vec (subrange_vec_dec v__0 31 21) ('b\"01001000100\"  : mword (31 - 21 + 1)))\n             (eq_vec (subrange_vec_dec v__0 15 0) (Ox\"0006\"  : mword (15 - 0 + 1))) then\n     let rt : IntRegEnc := subrange_vec_dec v__0 20 16 in\n     Some (C2Dump rt)\n   else Some (RI tt).\n\nDefinition execute_XORI (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (wGPR rt (xor_vec w__0 (mips_zero_extend 64 imm)))\n    : M (unit).\n\nDefinition execute_XOR (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (xor_vec w__0 w__1))  : M (unit).\n\nDefinition execute_WAIT '(tt : unit) : M (unit) :=\n   ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n   (if (bits_to_bool w__0)  : bool then (SignalException ResI)  : M (unit)\n    else returnm tt) >>\n   ((read_reg PC_ref)  : M (mword 64)) >>= fun w__1 : mword 64 =>\n   write_reg NextPC_ref w__1\n    : M (unit).\n\nDefinition execute_TRAPREG (rs : mword 5) (rt : mword 5) (cmp : Comparison) : M (unit) :=\n   (rGPR rs) >>= fun rs_val =>\n   (rGPR rt) >>= fun rt_val =>\n   let condition := compare cmp rs_val rt_val in\n   (if sumbool_of_bool condition then (SignalException Tr)  : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition execute_TRAPIMM (rs : mword 5) (imm : mword 16) (cmp : Comparison) : M (unit) :=\n   (rGPR rs) >>= fun rs_val =>\n   let imm_val : bits 64 := mips_sign_extend 64 imm in\n   let condition := compare cmp rs_val imm_val in\n   (if sumbool_of_bool condition then (SignalException Tr)  : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition execute_TLBWR '(tt : unit) : M (unit) :=\n   (checkCP0Access tt) >>\n   ((read_reg TLBRandom_ref)  : M (mword 6)) >>= fun w__0 : mword 6 =>\n   (TLBWriteEntry w__0)\n    : M (unit).\n\nDefinition execute_TLBWI '(tt : unit) : M (unit) :=\n   (checkCP0Access tt) >>\n   ((read_reg TLBIndex_ref)  : M (mword 6)) >>= fun w__0 : mword 6 =>\n   (TLBWriteEntry w__0)\n    : M (unit).\n\nDefinition execute_TLBR '(tt : unit) : M (unit) :=\n   (checkCP0Access tt) >>\n   ((read_reg TLBIndex_ref)  : M (mword 6)) >>= fun w__0 : mword 6 =>\n   let i := projT1 (uint w__0) in\n   (reg_deref (vec_access_dec TLBEntries i)) >>= fun entry =>\n   write_reg TLBPageMask_ref (_get_TLBEntry_pagemask entry) >>\n   (_set_TLBEntryHiReg_R TLBEntryHi_ref (_get_TLBEntry_r entry)) >>\n   (_set_TLBEntryHiReg_CLGK TLBEntryHi_ref ((cast_unit_vec B0)  : mword 1)) >>\n   (_set_TLBEntryHiReg_CLGS TLBEntryHi_ref ((cast_unit_vec B0)  : mword 1)) >>\n   (_set_TLBEntryHiReg_CLGU TLBEntryHi_ref ((cast_unit_vec B0)  : mword 1)) >>\n   (_set_TLBEntryHiReg_VPN2 TLBEntryHi_ref (_get_TLBEntry_vpn2 entry)) >>\n   (_set_TLBEntryHiReg_ASID TLBEntryHi_ref (_get_TLBEntry_asid entry)) >>\n   (_set_TLBEntryLoReg_CapS TLBEntryLo0_ref (_get_TLBEntry_caps0 entry)) >>\n   (_set_TLBEntryLoReg_CapL TLBEntryLo0_ref (_get_TLBEntry_capl0 entry)) >>\n   (_set_TLBEntryLoReg_CapLG TLBEntryLo0_ref (_get_TLBEntry_caplg0 entry)) >>\n   (_set_TLBEntryLoReg_PFN TLBEntryLo0_ref (_get_TLBEntry_pfn0 entry)) >>\n   (_set_TLBEntryLoReg_C TLBEntryLo0_ref (_get_TLBEntry_c0 entry)) >>\n   (_set_TLBEntryLoReg_D TLBEntryLo0_ref (_get_TLBEntry_d0 entry)) >>\n   (_set_TLBEntryLoReg_V TLBEntryLo0_ref (_get_TLBEntry_v0 entry)) >>\n   (_set_TLBEntryLoReg_G TLBEntryLo0_ref (_get_TLBEntry_g entry)) >>\n   (_set_TLBEntryLoReg_CapS TLBEntryLo1_ref (_get_TLBEntry_caps1 entry)) >>\n   (_set_TLBEntryLoReg_CapL TLBEntryLo1_ref (_get_TLBEntry_capl1 entry)) >>\n   (_set_TLBEntryLoReg_CapLG TLBEntryLo1_ref (_get_TLBEntry_caplg1 entry)) >>\n   (_set_TLBEntryLoReg_PFN TLBEntryLo1_ref (_get_TLBEntry_pfn1 entry)) >>\n   (_set_TLBEntryLoReg_C TLBEntryLo1_ref (_get_TLBEntry_c1 entry)) >>\n   (_set_TLBEntryLoReg_D TLBEntryLo1_ref (_get_TLBEntry_d1 entry)) >>\n   (_set_TLBEntryLoReg_V TLBEntryLo1_ref (_get_TLBEntry_v1 entry)) >>\n   (_set_TLBEntryLoReg_G TLBEntryLo1_ref (_get_TLBEntry_g entry))\n    : M (unit).\n\nDefinition execute_TLBP '(tt : unit) : M (unit) :=\n   (checkCP0Access tt) >>\n   read_reg TLBEntryHi_ref >>= fun w__0 : TLBEntryHiReg =>\n   (tlbSearch (_get_TLBEntryHiReg_bits w__0)) >>= fun result =>\n   (match result with\n    | Some idx =>\n       write_reg TLBProbe_ref ('b\"0\"  : mword 1) >> write_reg TLBIndex_ref idx  : M (unit)\n    | None =>\n       write_reg TLBProbe_ref ('b\"1\"  : mword 1) >>\n       write_reg TLBIndex_ref ('b\"000000\"  : mword 6)\n        : M (unit)\n    end)\n    : M (unit).\n\nDefinition execute_Store\n(width : WordType) (conditional : bool) (base : mword 5) (rt : mword 5) (offset : mword 16)\n: M (unit) :=\n   (rGPR base) >>= fun w__0 : mword 64 =>\n   (addrWrapper (add_vec (mips_sign_extend 64 offset) w__0) StoreData width) >>= fun vAddr : bits 64 =>\n   (rGPR rt) >>= fun rt_val =>\n   (if negb (isAddressAligned vAddr width) then (SignalExceptionBadAddr AdES vAddr)  : M (unit)\n    else\n    (TLBTranslate vAddr StoreData) >>= fun pAddr =>\n    if sumbool_of_bool conditional then\n      (and_boolM\n         (((read_reg CP0LLBit_ref)  : M (mword 1)) >>= fun w__1 : mword 1 =>\n          returnm ((bit_to_bool (access_vec_dec w__1 0))  : bool))\n         (((read_reg CP0LLAddr_ref)  : M (mword 64)) >>= fun w__2 : mword 64 =>\n          returnm ((eq_vec w__2 pAddr)  : bool))) >>= fun w__3 : bool =>\n      (if sumbool_of_bool w__3 then\n         (match width with\n          | W => (MEMw_conditional_wrapper pAddr 4 (subrange_vec_dec rt_val 31 0))  : M (bool)\n          | D => (MEMw_conditional_wrapper pAddr 8 rt_val)  : M (bool)\n          | _ => throw (Error_internal_error tt)\n          end)\n          : M (bool)\n       else returnm false) >>= fun success : bool =>\n      (wGPR rt (mips_zero_extend 64 (bool_to_bits success)))\n       : M (unit)\n    else\n      (match width with\n       | B => (MEMw_wrapper pAddr 1 (subrange_vec_dec rt_val 7 0))  : M (unit)\n       | H => (MEMw_wrapper pAddr 2 (subrange_vec_dec rt_val 15 0))  : M (unit)\n       | W => (MEMw_wrapper pAddr 4 (subrange_vec_dec rt_val 31 0))  : M (unit)\n       | D => (MEMw_wrapper pAddr 8 rt_val)  : M (unit)\n       end)\n       : M (unit))\n    : M (unit).\n\nDefinition execute_SYSCALL '(tt : unit) : M (unit) := (SignalException Sys)  : M (unit).\n\nDefinition execute_SYNC '(tt : unit) : M (unit) := (MEM_sync tt)  : M (unit).\n\nDefinition execute_SWR (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) :=\n   (rGPR base) >>= fun w__0 : mword 64 =>\n   (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) StoreData WR) >>= fun '(vAddr, size) =>\n   (TLBTranslate vAddr StoreData) >>= fun pAddr =>\n   (rGPR rt) >>= fun reg_val =>\n   let l__12 := size in\n   (if sumbool_of_bool (Z.eqb l__12 1) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 7 0))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__12 2) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 15 0))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__12 3) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 23 0))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__12 4) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 31 0))))\n       : M (unit)\n    else assert_exp' false \"../mips/mips_insts.sail 1404:26 - 1404:27\" >>= fun _ => exit tt)\n    : M (unit).\n\nDefinition execute_SWL (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) :=\n   (rGPR base) >>= fun w__0 : mword 64 =>\n   (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) StoreData WL) >>= fun '(vAddr, size) =>\n   (TLBTranslate vAddr StoreData) >>= fun pAddr =>\n   (rGPR rt) >>= fun reg_val =>\n   let l__8 := size in\n   (if sumbool_of_bool (Z.eqb l__8 4) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 31 0))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__8 3) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 31 8))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__8 2) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 31 16))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__8 1) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 31 24))))\n       : M (unit)\n    else assert_exp' false \"../mips/mips_insts.sail 1383:24 - 1383:25\" >>= fun _ => exit tt)\n    : M (unit).\n\nDefinition execute_SUBU (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun opA =>\n   (rGPR rt) >>= fun opB =>\n   (if orb (NotWordVal opA) (NotWordVal opB) then\n      (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit)\n    else\n      (wGPR rd\n         (mips_sign_extend 64 (sub_vec (subrange_vec_dec opA 31 0) (subrange_vec_dec opB 31 0))))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_SUB (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun opA =>\n   (rGPR rt) >>= fun opB =>\n   (if orb (NotWordVal opA) (NotWordVal opB) then\n      (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit)\n    else\n      let temp33 : bits 33 :=\n        sub_vec (mips_sign_extend 33 (subrange_vec_dec opA 31 0))\n          (mips_sign_extend 33 (subrange_vec_dec opB 31 0)) in\n      (if neq_bool (bit_to_bool (access_vec_dec temp33 32)) (bit_to_bool (access_vec_dec temp33 31))\n       then\n         (SignalException Ov)\n          : M (unit)\n       else (wGPR rd (mips_sign_extend 64 (subrange_vec_dec temp33 31 0)))  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_SRLV (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun temp =>\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   let sa := subrange_vec_dec w__0 4 0 in\n   (if NotWordVal temp then\n      (undefined_bitvector 64) >>= fun w__1 : mword 64 => (wGPR rd w__1)  : M (unit)\n    else\n      let rt32 := subrange_vec_dec temp 31 0 in\n      (shift_bits_right rt32 sa) >>= fun w__2 : mword (31 - 0 + 1) =>\n      (wGPR rd (mips_sign_extend 64 w__2))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_SRL (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun temp =>\n   (if NotWordVal temp then\n      (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit)\n    else\n      let rt32 := subrange_vec_dec temp 31 0 in\n      (shift_bits_right rt32 sa) >>= fun w__1 : mword (31 - 0 + 1) =>\n      (wGPR rd (mips_sign_extend 64 w__1))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_SRAV (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun temp =>\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   let sa := subrange_vec_dec w__0 4 0 in\n   (if NotWordVal temp then\n      (undefined_bitvector 64) >>= fun w__1 : mword 64 => (wGPR rd w__1)  : M (unit)\n    else\n      let rt32 := subrange_vec_dec temp 31 0 in\n      (shift_bits_right_arith rt32 sa) >>= fun w__2 : mword (31 - 0 + 1) =>\n      (wGPR rd (mips_sign_extend 64 w__2))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_SRA (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun temp =>\n   (if NotWordVal temp then\n      (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit)\n    else\n      let rt32 := subrange_vec_dec temp 31 0 in\n      (shift_bits_right_arith rt32 sa) >>= fun w__1 : mword (31 - 0 + 1) =>\n      (wGPR rd (mips_sign_extend 64 w__1))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_SLTU (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun rs_val =>\n   (rGPR rt) >>= fun rt_val =>\n   (wGPR rd\n      (mips_zero_extend 64 (if zopz0zI_u rs_val rt_val then 'b\"1\"  : mword 1 else 'b\"0\"  : mword 1)))\n    : M (unit).\n\nDefinition execute_SLTIU (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) :=\n   (rGPR rs) >>= fun rs_val =>\n   let immext : bits 64 := mips_sign_extend 64 imm in\n   (wGPR rt\n      (mips_zero_extend 64 (if zopz0zI_u rs_val immext then 'b\"1\"  : mword 1 else 'b\"0\"  : mword 1)))\n    : M (unit).\n\nDefinition execute_SLTI (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) :=\n   let imm_val := projT1 (sint imm) in\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   let rs_val := projT1 (sint w__0) in\n   (wGPR rt\n      (mips_zero_extend 64\n         (if sumbool_of_bool (Z.ltb rs_val imm_val) then 'b\"1\"  : mword 1\n          else 'b\"0\"  : mword 1)))\n    : M (unit).\n\nDefinition execute_SLT (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (rGPR rt) >>= fun w__1 : mword 64 =>\n   (wGPR rd\n      (mips_zero_extend 64 (if zopz0zI_s w__0 w__1 then 'b\"1\"  : mword 1 else 'b\"0\"  : mword 1)))\n    : M (unit).\n\nDefinition execute_SLLV (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   let sa := subrange_vec_dec w__0 4 0 in\n   (rGPR rt) >>= fun w__1 : mword 64 =>\n   let rt32 := subrange_vec_dec w__1 31 0 in\n   (shift_bits_left rt32 sa) >>= fun w__2 : mword (31 - 0 + 1) =>\n   (wGPR rd (mips_sign_extend 64 w__2))\n    : M (unit).\n\nDefinition execute_SLL (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun w__0 : mword 64 =>\n   let rt32 := subrange_vec_dec w__0 31 0 in\n   (shift_bits_left rt32 sa) >>= fun w__1 : mword (31 - 0 + 1) =>\n   (wGPR rd (mips_sign_extend 64 w__1))\n    : M (unit).\n\nDefinition execute_SDR (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) :=\n   (rGPR base) >>= fun w__0 : mword 64 =>\n   (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) StoreData DR) >>= fun '(vAddr, size) =>\n   (TLBTranslate vAddr StoreData) >>= fun pAddr =>\n   (rGPR rt) >>= fun reg_val =>\n   let l__40 := size in\n   (if sumbool_of_bool (Z.eqb l__40 1) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 7 0))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__40 2) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 15 0))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__40 3) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 23 0))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__40 4) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 31 0))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__40 5) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 39 0))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__40 6) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 47 0))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__40 7) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 55 0))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__40 8) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 0))))\n       : M (unit)\n    else assert_exp' false \"../mips/mips_insts.sail 1509:24 - 1509:25\" >>= fun _ => exit tt)\n    : M (unit).\n\nDefinition execute_SDL (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) :=\n   (rGPR base) >>= fun w__0 : mword 64 =>\n   (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) StoreData DL) >>= fun '(vAddr, size) =>\n   (TLBTranslate vAddr StoreData) >>= fun pAddr =>\n   (rGPR rt) >>= fun reg_val =>\n   let l__32 := size in\n   (if sumbool_of_bool (Z.eqb l__32 8) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 0))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__32 7) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 8))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__32 6) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 16))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__32 5) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 24))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__32 4) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 32))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__32 3) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 40))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__32 2) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 48))))\n       : M (unit)\n    else if sumbool_of_bool (Z.eqb l__32 1) then\n      (MEMw_wrapper pAddr size (autocast (autocast (subrange_vec_dec reg_val 63 56))))\n       : M (unit)\n    else assert_exp' false \"../mips/mips_insts.sail 1482:24 - 1482:25\" >>= fun _ => exit tt)\n    : M (unit).\n\nDefinition execute_RI '(tt : unit) : M (unit) := (skip tt) >> (SignalException ResI)  : M (unit).\n\nDefinition execute_RDHWR (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (getAccessLevel tt) >>= fun accessLevel =>\n   let haveAccessLevel : bool := generic_eq accessLevel Kernel in\n   read_reg CP0Status_ref >>= fun w__0 : StatusReg =>\n   let haveCU0 : bool := eq_bit B1 (access_vec_dec (_get_StatusReg_CU w__0) 0) in\n   let rdi := projT1 (uint rd) in\n   ((read_reg CP0HWREna_ref)  : M (mword 32)) >>= fun w__1 : mword 32 =>\n   let haveHWREna : bool := eq_bit B1 (access_vec_dec w__1 rdi) in\n   (if sumbool_of_bool (negb (orb haveAccessLevel (orb haveCU0 haveHWREna))) then\n      (SignalException ResI)\n       : M (unit)\n    else returnm tt) >>\n   let b__102 := rd in\n   (if eq_vec b__102 ('b\"00000\"  : mword 5) then returnm (mips_zero_extend 64 ('b\"0\"  : mword 1))\n    else if eq_vec b__102 ('b\"00001\"  : mword 5) then\n      returnm (mips_zero_extend 64 ('b\"0\"  : mword 1))\n    else if eq_vec b__102 ('b\"00010\"  : mword 5) then\n      ((read_reg CP0Count_ref)  : M (mword 32)) >>= fun w__2 : mword 32 =>\n      returnm (mips_zero_extend 64 w__2)\n    else if eq_vec b__102 ('b\"00011\"  : mword 5) then\n      returnm (mips_zero_extend 64 ('b\"1\"  : mword 1))\n    else if eq_vec b__102 ('b\"11101\"  : mword 5) then\n      ((read_reg CP0UserLocal_ref)  : M (mword 64))\n       : M (mword 64)\n    else (SignalException ResI)  : M (mword 64)) >>= fun temp : bits 64 =>\n   (wGPR rt temp)\n    : M (unit).\n\nDefinition execute_ORI (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (wGPR rt (or_vec w__0 (mips_zero_extend 64 imm)))\n    : M (unit).\n\nDefinition execute_OR (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (or_vec w__0 w__1))  : M (unit).\n\nDefinition execute_NOR (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (not_vec (or_vec w__0 w__1)))  : M (unit).\n\nDefinition execute_MULTU (rs : mword 5) (rt : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun rsVal =>\n   (rGPR rt) >>= fun rtVal =>\n   (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64)  : M (mword 64)\n    else returnm (mult_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0))) >>= fun result : bits 64 =>\n   write_reg HI_ref (mips_sign_extend 64 (subrange_vec_dec result 63 32)) >>\n   write_reg LO_ref (mips_sign_extend 64 (subrange_vec_dec result 31 0))\n    : M (unit).\n\nDefinition execute_MULT (rs : mword 5) (rt : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun rsVal =>\n   (rGPR rt) >>= fun rtVal =>\n   (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64)  : M (mword 64)\n    else returnm (mults_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0))) >>= fun result : bits 64 =>\n   write_reg HI_ref (mips_sign_extend 64 (subrange_vec_dec result 63 32)) >>\n   write_reg LO_ref (mips_sign_extend 64 (subrange_vec_dec result 31 0))\n    : M (unit).\n\nDefinition execute_MUL (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun rsVal =>\n   (rGPR rt) >>= fun rtVal =>\n   let result : bits 64 :=\n     mips_sign_extend 64 (mults_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0)) in\n   (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64)  : M (mword 64)\n    else returnm (mips_sign_extend 64 (subrange_vec_dec result 31 0))) >>= fun w__1 : mword 64 =>\n   (wGPR rd w__1)\n    : M (unit).\n\nDefinition execute_MTLO (rs : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 => write_reg LO_ref w__0  : M (unit).\n\nDefinition execute_MTHI (rs : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 => write_reg HI_ref w__0  : M (unit).\n\nDefinition execute_MTC0 (rt : mword 5) (rd : mword 5) (sel : mword 3) (double : bool) : M (unit) :=\n   (checkCP0Access tt) >>\n   (rGPR rt) >>= fun reg_val =>\n   (match (rd, sel) with\n    | (b__64, b__65) =>\n       (if andb (eq_vec b__64 ('b\"00000\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          write_reg TLBIndex_ref (mask 6 reg_val)\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"00001\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          returnm tt\n        else if andb (eq_vec b__64 ('b\"00010\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          (_set_TLBEntryLoReg_bits TLBEntryLo0_ref reg_val)\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"00011\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          (_set_TLBEntryLoReg_bits TLBEntryLo1_ref reg_val)\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"00100\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          (_set_ContextReg_PTEBase TLBContext_ref (subrange_vec_dec reg_val 63 23))\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"00100\"  : mword 5)) (eq_vec b__65 ('b\"010\"  : mword 3)) then\n          write_reg CP0UserLocal_ref reg_val\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"00101\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          write_reg TLBPageMask_ref (subrange_vec_dec reg_val 28 13)\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"00110\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          write_reg TLBWired_ref (mask 6 reg_val) >> write_reg TLBRandom_ref TLBIndexMax  : M (unit)\n        else if andb (eq_vec b__64 ('b\"00111\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          write_reg\n            CP0HWREna_ref\n            (concat_vec (subrange_vec_dec reg_val 31 29)\n               (concat_vec ('b\"0000000000000000000000000\"  : mword 25)\n                  (subrange_vec_dec reg_val 3 0)))\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"01000\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          returnm tt\n        else if andb (eq_vec b__64 ('b\"01001\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          write_reg CP0Count_ref (subrange_vec_dec reg_val 31 0)\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"01010\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          (_set_TLBEntryHiReg_R TLBEntryHi_ref (subrange_vec_dec reg_val 63 62)) >>\n          (_set_TLBEntryHiReg_CLGK TLBEntryHi_ref\n             ((cast_unit_vec (access_vec_dec reg_val 61))\n              : mword 1)) >>\n          (_set_TLBEntryHiReg_CLGS TLBEntryHi_ref\n             ((cast_unit_vec (access_vec_dec reg_val 60))\n              : mword 1)) >>\n          (_set_TLBEntryHiReg_CLGU TLBEntryHi_ref\n             ((cast_unit_vec (access_vec_dec reg_val 59))\n              : mword 1)) >>\n          (_set_TLBEntryHiReg_VPN2 TLBEntryHi_ref (subrange_vec_dec reg_val 39 13)) >>\n          (_set_TLBEntryHiReg_ASID TLBEntryHi_ref (subrange_vec_dec reg_val 7 0))\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"01011\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          write_reg CP0Compare_ref (subrange_vec_dec reg_val 31 0) >>\n          read_reg CP0Cause_ref >>= fun w__0 : CauseReg =>\n          (_set_CauseReg_IP CP0Cause_ref (and_vec (_get_CauseReg_IP w__0) (Ox\"7F\"  : mword 8)))\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"01100\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          (_set_StatusReg_CU CP0Status_ref\n             (and_vec (subrange_vec_dec reg_val 31 28)\n                (concat_vec ('b\"0\"  : mword 1)\n                   (concat_vec (bool_to_bits have_cp2) ('b\"01\"  : mword 2))))) >>\n          (_set_StatusReg_BEV CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 22))  : mword 1)) >>\n          (_set_StatusReg_IM CP0Status_ref (subrange_vec_dec reg_val 15 8)) >>\n          (_set_StatusReg_KX CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 7))  : mword 1)) >>\n          (_set_StatusReg_SX CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 6))  : mword 1)) >>\n          (_set_StatusReg_UX CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 5))  : mword 1)) >>\n          (_set_StatusReg_KSU CP0Status_ref (subrange_vec_dec reg_val 4 3)) >>\n          (_set_StatusReg_ERL CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 2))  : mword 1)) >>\n          (_set_StatusReg_EXL CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 1))  : mword 1)) >>\n          (_set_StatusReg_IE CP0Status_ref ((cast_unit_vec (access_vec_dec reg_val 0))  : mword 1))\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"01101\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          (_set_CauseReg_IV CP0Cause_ref ((cast_unit_vec (access_vec_dec reg_val 23))  : mword 1)) >>\n          read_reg CP0Cause_ref >>= fun w__1 : CauseReg =>\n          let ip := _get_CauseReg_IP w__1 in\n          (_set_CauseReg_IP CP0Cause_ref\n             (concat_vec (subrange_vec_dec ip 7 2) (subrange_vec_dec reg_val 9 8)))\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"01110\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          (set_CP0EPC reg_val)\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"10000\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          write_reg CP0ConfigK0_ref (subrange_vec_dec reg_val 2 0)\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"10100\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          (_set_XContextReg_XPTEBase TLBXContext_ref (subrange_vec_dec reg_val 63 33))\n           : M (unit)\n        else if andb (eq_vec b__64 ('b\"11110\"  : mword 5)) (eq_vec b__65 ('b\"000\"  : mword 3)) then\n          (set_CP0ErrorEPC reg_val)\n           : M (unit)\n        else (SignalException ResI)  : M (unit))\n        : M (unit)\n    end)\n    : M (unit).\n\nDefinition execute_MSUBU (rs : mword 5) (rt : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun rsVal =>\n   (rGPR rt) >>= fun rtVal =>\n   (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64)  : M (mword 64)\n    else returnm (mult_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0))) >>= fun mul_result : bits 64 =>\n   ((read_reg HI_ref)  : M (mword 64)) >>= fun w__1 : mword 64 =>\n   ((read_reg LO_ref)  : M (mword 64)) >>= fun w__2 : mword 64 =>\n   let result :=\n     sub_vec (concat_vec (subrange_vec_dec w__1 31 0) (subrange_vec_dec w__2 31 0)) mul_result in\n   write_reg HI_ref (mips_sign_extend 64 (subrange_vec_dec result 63 32)) >>\n   write_reg LO_ref (mips_sign_extend 64 (subrange_vec_dec result 31 0))\n    : M (unit).\n\nDefinition execute_MSUB (rs : mword 5) (rt : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun rsVal =>\n   (rGPR rt) >>= fun rtVal =>\n   (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64)  : M (mword 64)\n    else returnm (mults_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0))) >>= fun mul_result : bits 64 =>\n   ((read_reg HI_ref)  : M (mword 64)) >>= fun w__1 : mword 64 =>\n   ((read_reg LO_ref)  : M (mword 64)) >>= fun w__2 : mword 64 =>\n   let result :=\n     sub_vec (concat_vec (subrange_vec_dec w__1 31 0) (subrange_vec_dec w__2 31 0)) mul_result in\n   write_reg HI_ref (mips_sign_extend 64 (subrange_vec_dec result 63 32)) >>\n   write_reg LO_ref (mips_sign_extend 64 (subrange_vec_dec result 31 0))\n    : M (unit).\n\nDefinition execute_MOVZ (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun w__0 : mword 64 =>\n   (if eq_vec w__0 (Ox\"0000000000000000\"  : mword 64) then\n      (rGPR rs) >>= fun w__1 : mword 64 => (wGPR rd w__1)  : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition execute_MOVN (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun w__0 : mword 64 =>\n   (if neq_vec w__0 (Ox\"0000000000000000\"  : mword 64) then\n      (rGPR rs) >>= fun w__1 : mword 64 => (wGPR rd w__1)  : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition execute_MFLO (rd : mword 5) : M (unit) :=\n   ((read_reg LO_ref)  : M (mword 64)) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit).\n\nDefinition execute_MFHI (rd : mword 5) : M (unit) :=\n   ((read_reg HI_ref)  : M (mword 64)) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit).\n\nDefinition execute_MFC0 (rt : mword 5) (rd : mword 5) (sel : mword 3) (double : bool) : M (unit) :=\n   (checkCP0Access tt) >>\n   (match (rd, sel) with\n    | (b__0, b__1) =>\n       (if andb (eq_vec b__0 ('b\"00000\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          ((read_reg TLBIndex_ref)  : M (mword 6)) >>= fun w__0 : mword 6 =>\n          let idx : bits 31 := mips_zero_extend 31 w__0 in\n          ((read_reg TLBProbe_ref)  : M (mword 1)) >>= fun w__1 : mword 1 =>\n          returnm (concat_vec (Ox\"00000000\"  : mword 32) (concat_vec w__1 idx))\n        else if andb (eq_vec b__0 ('b\"00001\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          ((read_reg TLBRandom_ref)  : M (mword 6)) >>= fun w__2 : mword 6 =>\n          returnm (mips_zero_extend 64 w__2)\n        else if andb (eq_vec b__0 ('b\"00010\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          read_reg TLBEntryLo0_ref >>= fun w__3 : TLBEntryLoReg =>\n          returnm (_get_TLBEntryLoReg_bits w__3)\n        else if andb (eq_vec b__0 ('b\"00011\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          read_reg TLBEntryLo1_ref >>= fun w__4 : TLBEntryLoReg =>\n          returnm (_get_TLBEntryLoReg_bits w__4)\n        else if andb (eq_vec b__0 ('b\"00100\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          read_reg TLBContext_ref >>= fun w__5 : ContextReg => returnm (_get_ContextReg_bits w__5)\n        else if andb (eq_vec b__0 ('b\"00100\"  : mword 5)) (eq_vec b__1 ('b\"010\"  : mword 3)) then\n          ((read_reg CP0UserLocal_ref)  : M (mword 64))\n           : M (mword 64)\n        else if andb (eq_vec b__0 ('b\"00101\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          ((read_reg TLBPageMask_ref)  : M (mword 16)) >>= fun w__7 : mword 16 =>\n          returnm (mips_zero_extend 64 (concat_vec w__7 (Ox\"000\"  : mword 12)))\n        else if andb (eq_vec b__0 ('b\"00110\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          ((read_reg TLBWired_ref)  : M (mword 6)) >>= fun w__8 : mword 6 =>\n          returnm (mips_zero_extend 64 w__8)\n        else if andb (eq_vec b__0 ('b\"00111\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          ((read_reg CP0HWREna_ref)  : M (mword 32)) >>= fun w__9 : mword 32 =>\n          returnm (mips_zero_extend 64 w__9)\n        else if andb (eq_vec b__0 ('b\"01000\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          ((read_reg CP0BadVAddr_ref)  : M (mword 64))\n           : M (mword 64)\n        else if andb (eq_vec b__0 ('b\"01000\"  : mword 5)) (eq_vec b__1 ('b\"001\"  : mword 3)) then\n          ((read_reg CP0BadInstr_ref)  : M (mword 32)) >>= fun w__11 : mword 32 =>\n          returnm (mips_zero_extend 64 w__11)\n        else if andb (eq_vec b__0 ('b\"01000\"  : mword 5)) (eq_vec b__1 ('b\"010\"  : mword 3)) then\n          ((read_reg CP0BadInstrP_ref)  : M (mword 32)) >>= fun w__12 : mword 32 =>\n          returnm (mips_zero_extend 64 w__12)\n        else if andb (eq_vec b__0 ('b\"01001\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          ((read_reg CP0Count_ref)  : M (mword 32)) >>= fun w__13 : mword 32 =>\n          returnm (mips_zero_extend 64 w__13)\n        else if andb (eq_vec b__0 ('b\"01010\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          read_reg TLBEntryHi_ref >>= fun w__14 : TLBEntryHiReg =>\n          returnm (_get_TLBEntryHiReg_bits w__14)\n        else if andb (eq_vec b__0 ('b\"01011\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          ((read_reg CP0Compare_ref)  : M (mword 32)) >>= fun w__15 : mword 32 =>\n          returnm (mips_zero_extend 64 w__15)\n        else if andb (eq_vec b__0 ('b\"01100\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          read_reg CP0Status_ref >>= fun w__16 : StatusReg =>\n          returnm (mips_zero_extend 64 (_get_StatusReg_bits w__16))\n        else if andb (eq_vec b__0 ('b\"01101\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          read_reg CP0Cause_ref >>= fun w__17 : CauseReg =>\n          returnm (mips_zero_extend 64 (_get_CauseReg_bits w__17))\n        else if andb (eq_vec b__0 ('b\"01110\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          (get_CP0EPC tt)\n           : M (mword 64)\n        else if andb (eq_vec b__0 ('b\"01111\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          returnm (mips_zero_extend 64 (Ox\"00000405\"  : mword 32))\n        else if andb (eq_vec b__0 ('b\"01111\"  : mword 5)) (eq_vec b__1 ('b\"110\"  : mword 3)) then\n          returnm (mips_zero_extend 64 ('b\"0\"  : mword 1))\n        else if andb (eq_vec b__0 ('b\"01111\"  : mword 5)) (eq_vec b__1 ('b\"111\"  : mword 3)) then\n          returnm (mips_zero_extend 64 ('b\"0\"  : mword 1))\n        else if andb (eq_vec b__0 ('b\"10000\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          ((read_reg CP0ConfigK0_ref)  : M (mword 3)) >>= fun w__19 : mword 3 =>\n          returnm (mips_zero_extend 64\n                     (concat_vec ('b\"1\"  : mword 1)\n                        (concat_vec ('b\"000000000000000\"  : mword 15)\n                           (concat_vec ('b\"1\"  : mword 1)\n                              (concat_vec ('b\"10\"  : mword 2)\n                                 (concat_vec ('b\"000\"  : mword 3)\n                                    (concat_vec ('b\"001\"  : mword 3)\n                                       (concat_vec (Ox\"0\"  : mword 4) w__19))))))))\n        else if andb (eq_vec b__0 ('b\"10000\"  : mword 5)) (eq_vec b__1 ('b\"001\"  : mword 3)) then\n          returnm (mips_zero_extend 64\n                     (concat_vec ('b\"1\"  : mword 1)\n                        (concat_vec TLBIndexMax\n                           (concat_vec ('b\"000\"  : mword 3)\n                              (concat_vec ('b\"000\"  : mword 3)\n                                 (concat_vec ('b\"000\"  : mword 3)\n                                    (concat_vec ('b\"000\"  : mword 3)\n                                       (concat_vec ('b\"000\"  : mword 3)\n                                          (concat_vec ('b\"000\"  : mword 3)\n                                             (concat_vec (bool_to_bits have_cp2)\n                                                (concat_vec ('b\"0\"  : mword 1)\n                                                   (concat_vec ('b\"0\"  : mword 1)\n                                                      (concat_vec ('b\"0\"  : mword 1)\n                                                         (concat_vec ('b\"0\"  : mword 1)\n                                                            (concat_vec ('b\"0\"  : mword 1)\n                                                               ('b\"0\"\n                                                                : mword 1))))))))))))))))\n        else if andb (eq_vec b__0 ('b\"10000\"  : mword 5)) (eq_vec b__1 ('b\"010\"  : mword 3)) then\n          returnm (mips_zero_extend 64\n                     (concat_vec ('b\"1\"  : mword 1)\n                        (concat_vec ('b\"000\"  : mword 3)\n                           (concat_vec (Ox\"0\"  : mword 4)\n                              (concat_vec (Ox\"0\"  : mword 4)\n                                 (concat_vec (Ox\"0\"  : mword 4)\n                                    (concat_vec (Ox\"0\"  : mword 4)\n                                       (concat_vec (Ox\"0\"  : mword 4)\n                                          (concat_vec (Ox\"0\"  : mword 4) (Ox\"0\"  : mword 4))))))))))\n        else if andb (eq_vec b__0 ('b\"10000\"  : mword 5)) (eq_vec b__1 ('b\"011\"  : mword 3)) then\n          returnm (Ox\"000000000C002000\"  : mword 64)\n        else if andb (eq_vec b__0 ('b\"10000\"  : mword 5)) (eq_vec b__1 ('b\"101\"  : mword 3)) then\n          returnm (Ox\"0000000000000000\"  : mword 64)\n        else if andb (eq_vec b__0 ('b\"10000\"  : mword 5)) (eq_vec b__1 ('b\"110\"  : mword 3)) then\n          returnm (Ox\"0000000000000000\"  : mword 64)\n        else if andb (eq_vec b__0 ('b\"10001\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          ((read_reg CP0LLAddr_ref)  : M (mword 64))\n           : M (mword 64)\n        else if andb (eq_vec b__0 ('b\"10010\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          returnm (mips_zero_extend 64 ('b\"0\"  : mword 1))\n        else if andb (eq_vec b__0 ('b\"10011\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          returnm (mips_zero_extend 64 ('b\"0\"  : mword 1))\n        else if andb (eq_vec b__0 ('b\"10100\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          read_reg TLBXContext_ref >>= fun w__21 : XContextReg =>\n          returnm (_get_XContextReg_bits w__21)\n        else if andb (eq_vec b__0 ('b\"11110\"  : mword 5)) (eq_vec b__1 ('b\"000\"  : mword 3)) then\n          (get_CP0ErrorEPC tt)\n           : M (mword 64)\n        else (SignalException ResI)  : M (mword 64))\n        : M (mword 64)\n    end) >>= fun result : bits 64 =>\n   (wGPR rt\n      (if sumbool_of_bool double then result\n       else mips_sign_extend 64 (subrange_vec_dec result 31 0)))\n    : M (unit).\n\nDefinition execute_MADDU (rs : mword 5) (rt : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun rsVal =>\n   (rGPR rt) >>= fun rtVal =>\n   (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64)  : M (mword 64)\n    else returnm (mult_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0))) >>= fun mul_result : bits 64 =>\n   ((read_reg HI_ref)  : M (mword 64)) >>= fun w__1 : mword 64 =>\n   ((read_reg LO_ref)  : M (mword 64)) >>= fun w__2 : mword 64 =>\n   let result :=\n     add_vec mul_result (concat_vec (subrange_vec_dec w__1 31 0) (subrange_vec_dec w__2 31 0)) in\n   write_reg HI_ref (mips_sign_extend 64 (subrange_vec_dec result 63 32)) >>\n   write_reg LO_ref (mips_sign_extend 64 (subrange_vec_dec result 31 0))\n    : M (unit).\n\nDefinition execute_MADD (rs : mword 5) (rt : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun rsVal =>\n   (rGPR rt) >>= fun rtVal =>\n   (if orb (NotWordVal rsVal) (NotWordVal rtVal) then (undefined_bitvector 64)  : M (mword 64)\n    else returnm (mults_vec (subrange_vec_dec rsVal 31 0) (subrange_vec_dec rtVal 31 0))) >>= fun mul_result : bits 64 =>\n   ((read_reg HI_ref)  : M (mword 64)) >>= fun w__1 : mword 64 =>\n   ((read_reg LO_ref)  : M (mword 64)) >>= fun w__2 : mword 64 =>\n   let result :=\n     add_vec mul_result (concat_vec (subrange_vec_dec w__1 31 0) (subrange_vec_dec w__2 31 0)) in\n   write_reg HI_ref (mips_sign_extend 64 (subrange_vec_dec result 63 32)) >>\n   write_reg LO_ref (mips_sign_extend 64 (subrange_vec_dec result 31 0))\n    : M (unit).\n\nDefinition execute_Load\n(width : WordType) (sign : bool) (linked : bool) (base : mword 5) (rt : mword 5) (offset : mword 16)\n: M (unit) :=\n   (rGPR base) >>= fun w__0 : mword 64 =>\n   (addrWrapper (add_vec (mips_sign_extend 64 offset) w__0) LoadData width) >>= fun vAddr : bits 64 =>\n   (if negb (isAddressAligned vAddr width) then (SignalExceptionBadAddr AdEL vAddr)  : M (unit)\n    else\n      (TLBTranslate vAddr LoadData) >>= fun pAddr =>\n      (if sumbool_of_bool linked then\n         write_reg CP0LLBit_ref ('b\"1\"  : mword 1) >>\n         write_reg CP0LLAddr_ref pAddr >>\n         (match width with\n          | W =>\n             (MEMr_reserve_wrapper pAddr 4) >>= fun w__1 : mword (8 * 4) =>\n             returnm (extendLoad w__1 sign)\n          | D =>\n             (MEMr_reserve_wrapper pAddr 8) >>= fun w__2 : mword (8 * 8) =>\n             returnm (extendLoad w__2 sign)\n          | _ => throw (Error_internal_error tt)\n          end)\n          : M (mword 64)\n       else\n         (match width with\n          | B =>\n             (MEMr_wrapper pAddr 1) >>= fun w__5 : mword (8 * 1) => returnm (extendLoad w__5 sign)\n          | H =>\n             (MEMr_wrapper pAddr 2) >>= fun w__6 : mword (8 * 2) => returnm (extendLoad w__6 sign)\n          | W =>\n             (MEMr_wrapper pAddr 4) >>= fun w__7 : mword (8 * 4) => returnm (extendLoad w__7 sign)\n          | D =>\n             (MEMr_wrapper pAddr 8) >>= fun w__8 : mword (8 * 8) => returnm (extendLoad w__8 sign)\n          end)\n          : M (mword 64)) >>= fun memResult : bits 64 =>\n      (wGPR rt memResult)\n       : M (unit))\n    : M (unit).\n\nDefinition execute_LWR (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) :=\n   (rGPR base) >>= fun w__0 : mword 64 =>\n   (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) LoadData WR) >>= fun '(vAddr, size) =>\n   (TLBTranslate vAddr LoadData) >>= fun pAddr =>\n   (rGPR rt) >>= fun reg_val =>\n   let l__4 := size in\n   (if sumbool_of_bool (Z.eqb l__4 1) then\n      (MEMr_wrapper pAddr size) >>= fun w__1 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 31 8) w__1)))\n    else if sumbool_of_bool (Z.eqb l__4 2) then\n      (MEMr_wrapper pAddr size) >>= fun w__2 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 31 16) w__2)))\n    else if sumbool_of_bool (Z.eqb l__4 3) then\n      (MEMr_wrapper pAddr size) >>= fun w__3 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 31 24) w__3)))\n    else if sumbool_of_bool (Z.eqb l__4 4) then (MEMr_wrapper pAddr _)  : M (mword (8 * 4))\n    else assert_exp' false \"../mips/mips_insts.sail 1360:21 - 1360:22\" >>= fun _ => exit tt) >>= fun result : bits 32 =>\n   (wGPR rt (mips_sign_extend 64 result))\n    : M (unit).\n\nDefinition execute_LWL (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) :=\n   (rGPR base) >>= fun w__0 : mword 64 =>\n   (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) LoadData WL) >>= fun '(vAddr, size) =>\n   (TLBTranslate vAddr LoadData) >>= fun pAddr =>\n   (rGPR rt) >>= fun reg_val =>\n   let l__0 := size in\n   (if sumbool_of_bool (Z.eqb l__0 4) then (MEMr_wrapper pAddr _)  : M (mword (8 * 4))\n    else if sumbool_of_bool (Z.eqb l__0 3) then\n      (MEMr_wrapper pAddr size) >>= fun w__2 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec w__2 (subrange_vec_dec reg_val 7 0))))\n    else if sumbool_of_bool (Z.eqb l__0 2) then\n      (MEMr_wrapper pAddr size) >>= fun w__3 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec w__3 (subrange_vec_dec reg_val 15 0))))\n    else if sumbool_of_bool (Z.eqb l__0 1) then\n      (MEMr_wrapper pAddr size) >>= fun w__4 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec w__4 (subrange_vec_dec reg_val 23 0))))\n    else assert_exp' false \"../mips/mips_insts.sail 1339:21 - 1339:22\" >>= fun _ => exit tt) >>= fun result : bits 32 =>\n   (wGPR rt (mips_sign_extend 64 result))\n    : M (unit).\n\nDefinition execute_LUI (rt : mword 5) (imm : mword 16) : M (unit) :=\n   (wGPR rt (mips_sign_extend 64 (concat_vec imm (Ox\"0000\"  : mword 16))))  : M (unit).\n\nDefinition execute_LDR (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) :=\n   (rGPR base) >>= fun w__0 : mword 64 =>\n   (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) LoadData DR) >>= fun '(vAddr, size) =>\n   (TLBTranslate vAddr LoadData) >>= fun pAddr =>\n   (rGPR rt) >>= fun reg_val =>\n   let l__24 := size in\n   (if sumbool_of_bool (Z.eqb l__24 1) then\n      (MEMr_wrapper pAddr size) >>= fun w__1 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 8) w__1)))\n    else if sumbool_of_bool (Z.eqb l__24 2) then\n      (MEMr_wrapper pAddr size) >>= fun w__2 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 16) w__2)))\n    else if sumbool_of_bool (Z.eqb l__24 3) then\n      (MEMr_wrapper pAddr size) >>= fun w__3 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 24) w__3)))\n    else if sumbool_of_bool (Z.eqb l__24 4) then\n      (MEMr_wrapper pAddr size) >>= fun w__4 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 32) w__4)))\n    else if sumbool_of_bool (Z.eqb l__24 5) then\n      (MEMr_wrapper pAddr size) >>= fun w__5 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 40) w__5)))\n    else if sumbool_of_bool (Z.eqb l__24 6) then\n      (MEMr_wrapper pAddr size) >>= fun w__6 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 48) w__6)))\n    else if sumbool_of_bool (Z.eqb l__24 7) then\n      (MEMr_wrapper pAddr size) >>= fun w__7 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec (subrange_vec_dec reg_val 63 56) w__7)))\n    else if sumbool_of_bool (Z.eqb l__24 8) then (MEMr_wrapper pAddr _)  : M (mword (8 * 8))\n    else assert_exp' false \"../mips/mips_insts.sail 1456:21 - 1456:22\" >>= fun _ => exit tt) >>= fun w__16 : mword 64 =>\n   (wGPR rt w__16)\n    : M (unit).\n\nDefinition execute_LDL (base : mword 5) (rt : mword 5) (offset : mword 16) : M (unit) :=\n   (rGPR base) >>= fun w__0 : mword 64 =>\n   (addrWrapperUnaligned (add_vec (mips_sign_extend 64 offset) w__0) LoadData DL) >>= fun '(vAddr, size) =>\n   (TLBTranslate vAddr LoadData) >>= fun pAddr =>\n   (rGPR rt) >>= fun reg_val =>\n   let l__16 := size in\n   (if sumbool_of_bool (Z.eqb l__16 8) then (MEMr_wrapper pAddr _)  : M (mword (8 * 8))\n    else if sumbool_of_bool (Z.eqb l__16 7) then\n      (MEMr_wrapper pAddr size) >>= fun w__2 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec w__2 (subrange_vec_dec reg_val 7 0))))\n    else if sumbool_of_bool (Z.eqb l__16 6) then\n      (MEMr_wrapper pAddr size) >>= fun w__3 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec w__3 (subrange_vec_dec reg_val 15 0))))\n    else if sumbool_of_bool (Z.eqb l__16 5) then\n      (MEMr_wrapper pAddr size) >>= fun w__4 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec w__4 (subrange_vec_dec reg_val 23 0))))\n    else if sumbool_of_bool (Z.eqb l__16 4) then\n      (MEMr_wrapper pAddr size) >>= fun w__5 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec w__5 (subrange_vec_dec reg_val 31 0))))\n    else if sumbool_of_bool (Z.eqb l__16 3) then\n      (MEMr_wrapper pAddr size) >>= fun w__6 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec w__6 (subrange_vec_dec reg_val 39 0))))\n    else if sumbool_of_bool (Z.eqb l__16 2) then\n      (MEMr_wrapper pAddr size) >>= fun w__7 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec w__7 (subrange_vec_dec reg_val 47 0))))\n    else if sumbool_of_bool (Z.eqb l__16 1) then\n      (MEMr_wrapper pAddr size) >>= fun w__8 : mword (8 * size) =>\n      returnm (autocast (autocast (concat_vec w__8 (subrange_vec_dec reg_val 55 0))))\n    else assert_exp' false \"../mips/mips_insts.sail 1430:21 - 1430:22\" >>= fun _ => exit tt) >>= fun w__16 : mword 64 =>\n   (wGPR rt w__16)\n    : M (unit).\n\nDefinition execute_JR (rs : mword 5) : M (unit) :=\n   ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n   (if (bits_to_bool w__0)  : bool then (SignalException ResI)  : M (unit)\n    else returnm tt) >>\n   (rGPR rs) >>= fun w__1 : mword 64 => (execute_branch w__1)  : M (unit).\n\nDefinition execute_JALR (rs : mword 5) (rd : mword 5) : M (unit) :=\n   ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n   (if (bits_to_bool w__0)  : bool then (SignalException ResI)  : M (unit)\n    else returnm tt) >>\n   (rGPR rs) >>= fun w__1 : mword 64 =>\n   (execute_branch w__1) >>\n   ((read_reg PC_ref)  : M (mword 64)) >>= fun w__2 : mword 64 =>\n   (wGPR rd (add_vec_int w__2 8))\n    : M (unit).\n\nDefinition execute_JAL (offset : mword 26) : M (unit) :=\n   ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n   (if (bits_to_bool w__0)  : bool then (SignalException ResI)  : M (unit)\n    else returnm tt) >>\n   ((read_reg PC_ref)  : M (mword 64)) >>= fun w__1 : mword 64 =>\n   (execute_branch\n      (concat_vec (subrange_vec_dec (add_vec_int w__1 4) 63 28)\n         (concat_vec offset ('b\"00\"  : mword 2)))) >>\n   ((read_reg PC_ref)  : M (mword 64)) >>= fun w__2 : mword 64 =>\n   (wGPR ('b\"11111\"  : mword 5) (add_vec_int w__2 8))\n    : M (unit).\n\nDefinition execute_J (offset : mword 26) : M (unit) :=\n   ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n   (if (bits_to_bool w__0)  : bool then (SignalException ResI)  : M (unit)\n    else returnm tt) >>\n   ((read_reg PC_ref)  : M (mword 64)) >>= fun w__1 : mword 64 =>\n   (execute_branch\n      (concat_vec (subrange_vec_dec (add_vec_int w__1 4) 63 28)\n         (concat_vec offset ('b\"00\"  : mword 2))))\n    : M (unit).\n\nDefinition execute_HCF '(tt : unit) : unit := tt.\n\nDefinition execute_ERET '(tt : unit) : M (unit) :=\n   (checkCP0Access tt) >>\n   (ERETHook tt) >>\n   write_reg CP0LLBit_ref ('b\"0\"  : mword 1) >>\n   read_reg CP0Status_ref >>= fun w__0 : StatusReg =>\n   (if Bool.eqb (bits_to_bool (_get_StatusReg_ERL w__0)) (bit_to_bool B1) then\n      (get_CP0ErrorEPC tt) >>= fun w__1 : mword 64 =>\n      write_reg NextPC_ref w__1 >> (_set_StatusReg_ERL CP0Status_ref ('b\"0\"  : mword 1))  : M (unit)\n    else\n      (get_CP0EPC tt) >>= fun w__2 : mword 64 =>\n      write_reg NextPC_ref w__2 >> (_set_StatusReg_EXL CP0Status_ref ('b\"0\"  : mword 1))  : M (unit))\n    : M (unit).\n\nDefinition execute_DSUBU (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (sub_vec w__0 w__1))  : M (unit).\n\nDefinition execute_DSUB (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (rGPR rt) >>= fun w__1 : mword 64 =>\n   let temp65 : bits 65 := sub_vec (mips_sign_extend 65 w__0) (mips_sign_extend 65 w__1) in\n   (if neq_bool (bit_to_bool (access_vec_dec temp65 64)) (bit_to_bool (access_vec_dec temp65 63))\n    then\n      (SignalException Ov)\n       : M (unit)\n    else (wGPR rd (subrange_vec_dec temp65 63 0))  : M (unit))\n    : M (unit).\n\nDefinition execute_DSRLV (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun temp =>\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   let sa := subrange_vec_dec w__0 5 0 in\n   (shift_bits_right temp sa) >>= fun w__1 : mword 64 => (wGPR rd w__1)  : M (unit).\n\nDefinition execute_DSRL32 (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun temp =>\n   let sa32 := concat_vec ('b\"1\"  : mword 1) sa in\n   (shift_bits_right temp sa32) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit).\n\nDefinition execute_DSRL (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun temp =>\n   (shift_bits_right temp sa) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit).\n\nDefinition execute_DSRAV (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun temp =>\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   let sa := subrange_vec_dec w__0 5 0 in\n   (shift_bits_right_arith temp sa) >>= fun w__1 : mword 64 => (wGPR rd w__1)  : M (unit).\n\nDefinition execute_DSRA32 (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun temp =>\n   let sa32 := concat_vec ('b\"1\"  : mword 1) sa in\n   (shift_bits_right_arith temp sa32) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit).\n\nDefinition execute_DSRA (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun temp =>\n   (shift_bits_right_arith temp sa) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit).\n\nDefinition execute_DSLLV (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun w__0 : mword 64 =>\n   (rGPR rs) >>= fun w__1 : mword 64 =>\n   (shift_bits_left w__0 (subrange_vec_dec w__1 5 0)) >>= fun w__2 : mword 64 =>\n   (wGPR rd w__2)\n    : M (unit).\n\nDefinition execute_DSLL32 (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun w__0 : mword 64 =>\n   (shift_bits_left w__0 (concat_vec ('b\"1\"  : mword 1) sa)) >>= fun w__1 : mword 64 =>\n   (wGPR rd w__1)\n    : M (unit).\n\nDefinition execute_DSLL (rt : mword 5) (rd : mword 5) (sa : mword 5) : M (unit) :=\n   (rGPR rt) >>= fun w__0 : mword 64 =>\n   (shift_bits_left w__0 sa) >>= fun w__1 : mword 64 => (wGPR rd w__1)  : M (unit).\n\nDefinition execute_DMULTU (rs : mword 5) (rt : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (rGPR rt) >>= fun w__1 : mword 64 =>\n   let result := mult_vec w__0 w__1 in\n   write_reg HI_ref (subrange_vec_dec result 127 64) >>\n   write_reg LO_ref (subrange_vec_dec result 63 0)\n    : M (unit).\n\nDefinition execute_DMULT (rs : mword 5) (rt : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (rGPR rt) >>= fun w__1 : mword 64 =>\n   let result := mults_vec w__0 w__1 in\n   write_reg HI_ref (subrange_vec_dec result 127 64) >>\n   write_reg LO_ref (subrange_vec_dec result 63 0)\n    : M (unit).\n\nDefinition execute_DIVU (rs : mword 5) (rt : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun rsVal =>\n   (rGPR rt) >>= fun rtVal =>\n   (if orb (NotWordVal rsVal)\n         (orb (NotWordVal rtVal) (eq_vec rtVal (Ox\"0000000000000000\"  : mword 64))) then\n      (undefined_bitvector 32) >>= fun w__0 : mword 32 =>\n      (undefined_bitvector 32) >>= fun w__1 : mword 32 => returnm (w__0  : bits 32, w__1  : bits 32)\n    else\n      let si := projT1 (uint (subrange_vec_dec rsVal 31 0)) in\n      let ti := projT1 (uint (subrange_vec_dec rtVal 31 0)) in\n      let qi := Z.quot si ti in\n      let ri := Z.rem si ti in\n      returnm (to_bits 32 qi, to_bits 32 ri)) >>= fun '(q, r) =>\n   write_reg HI_ref (mips_sign_extend 64 r) >> write_reg LO_ref (mips_sign_extend 64 q)  : M (unit).\n\nDefinition execute_DIV (rs : mword 5) (rt : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun rsVal =>\n   (rGPR rt) >>= fun rtVal =>\n   (if orb (NotWordVal rsVal)\n         (orb (NotWordVal rtVal) (eq_vec rtVal (Ox\"0000000000000000\"  : mword 64))) then\n      (undefined_bitvector 32) >>= fun w__0 : mword 32 =>\n      (undefined_bitvector 32) >>= fun w__1 : mword 32 => returnm (w__0  : bits 32, w__1  : bits 32)\n    else\n      let si := projT1 (sint (subrange_vec_dec rsVal 31 0)) in\n      let ti := projT1 (sint (subrange_vec_dec rtVal 31 0)) in\n      let qi := Z.quot si ti in\n      let ri := Z.sub si (Z.mul ti qi) in\n      returnm (to_bits 32 qi, to_bits 32 ri)) >>= fun '(q, r) =>\n   write_reg HI_ref (mips_sign_extend 64 r) >> write_reg LO_ref (mips_sign_extend 64 q)  : M (unit).\n\nDefinition execute_DDIVU (rs : mword 5) (rt : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   let rsVal := projT1 (uint w__0) in\n   (rGPR rt) >>= fun w__1 : mword 64 =>\n   let rtVal := projT1 (uint w__1) in\n   (if sumbool_of_bool (Z.eqb rtVal 0) then\n      (undefined_bitvector 64) >>= fun w__2 : mword 64 =>\n      (undefined_bitvector 64) >>= fun w__3 : mword 64 => returnm (w__2  : bits 64, w__3  : bits 64)\n    else\n      let qi := Z.quot rsVal rtVal in\n      let ri := Z.rem rsVal rtVal in\n      returnm (to_bits 64 qi, to_bits 64 ri)) >>= fun '(q, r) =>\n   write_reg LO_ref q >> write_reg HI_ref r  : M (unit).\n\nDefinition execute_DDIV (rs : mword 5) (rt : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   let rsVal := projT1 (sint w__0) in\n   (rGPR rt) >>= fun w__1 : mword 64 =>\n   let rtVal := projT1 (sint w__1) in\n   (if sumbool_of_bool (Z.eqb rtVal 0) then\n      (undefined_bitvector 64) >>= fun w__2 : mword 64 =>\n      (undefined_bitvector 64) >>= fun w__3 : mword 64 => returnm (w__2  : bits 64, w__3  : bits 64)\n    else\n      let qi := Z.quot rsVal rtVal in\n      let ri := Z.sub rsVal (Z.mul qi rtVal) in\n      returnm (to_bits 64 qi, to_bits 64 ri)) >>= fun '(q, r) =>\n   write_reg LO_ref q >> write_reg HI_ref r  : M (unit).\n\nDefinition execute_DADDU (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (add_vec w__0 w__1))  : M (unit).\n\nDefinition execute_DADDIU (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (wGPR rt (add_vec w__0 (mips_sign_extend 64 imm)))\n    : M (unit).\n\nDefinition execute_DADDI (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   let sum65 : bits 65 := add_vec (mips_sign_extend 65 w__0) (mips_sign_extend 65 imm) in\n   (if neq_bool (bit_to_bool (access_vec_dec sum65 64)) (bit_to_bool (access_vec_dec sum65 63)) then\n      (SignalException Ov)\n       : M (unit)\n    else (wGPR rt (subrange_vec_dec sum65 63 0))  : M (unit))\n    : M (unit).\n\nDefinition execute_DADD (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (rGPR rt) >>= fun w__1 : mword 64 =>\n   let sum65 : bits 65 := add_vec (mips_sign_extend 65 w__0) (mips_sign_extend 65 w__1) in\n   (if neq_bool (bit_to_bool (access_vec_dec sum65 64)) (bit_to_bool (access_vec_dec sum65 63)) then\n      (SignalException Ov)\n       : M (unit)\n    else (wGPR rd (subrange_vec_dec sum65 63 0))  : M (unit))\n    : M (unit).\n\nDefinition execute_ClearRegs (regset : ClearRegSet) (m : mword 16) : M (unit) :=\n   (if orb (generic_eq regset CLo) (generic_eq regset CHi) then (checkCP2usable tt)  : M (unit)\n    else returnm tt) >>\n   let loop_i_lower := 0 in\n   let loop_i_upper := 15 in\n   (foreach_ZM_up loop_i_lower loop_i_upper 1 tt\n     (fun i _ _ =>\n       (if (bit_to_bool (access_vec_dec m i))  : bool then\n          (match regset with\n           | GPLo => (wGPR (to_bits 5 i) (zeros_implicit 64 tt))  : M (unit)\n           | GPHi => (wGPR (to_bits 5 (Z.add i 16)) (zeros_implicit 64 tt))  : M (unit)\n           | CLo =>\n              (if sumbool_of_bool (Z.eqb i 0) then write_reg DDC_ref null_cap  : M (unit)\n               else (writeCapReg (to_bits 5 i) null_cap)  : M (unit))\n               : M (unit)\n           | CHi => (writeCapReg (to_bits 5 (Z.add i 16)) null_cap)  : M (unit)\n           end)\n           : M (unit)\n        else returnm tt)\n        : M (unit))).\n\nDefinition execute_CWriteHwr (cb : mword 5) (sel : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   let l__75 := projT1 (uint sel) in\n   (if sumbool_of_bool (Z.eqb l__75 0) then returnm (false, false)\n    else if sumbool_of_bool (Z.eqb l__75 1) then returnm (false, false)\n    else if sumbool_of_bool (Z.eqb l__75 8) then returnm (false, true)\n    else if sumbool_of_bool (Z.eqb l__75 22) then returnm (true, true)\n    else if sumbool_of_bool (Z.eqb l__75 23) then returnm (true, true)\n    else if sumbool_of_bool (Z.eqb l__75 28) then returnm (true, true)\n    else if sumbool_of_bool (Z.eqb l__75 29) then returnm (true, true)\n    else if sumbool_of_bool (Z.eqb l__75 30) then returnm (true, true)\n    else if sumbool_of_bool (Z.eqb l__75 31) then returnm (true, true)\n    else (SignalException ResI)  : M ((bool * bool))) >>= fun '((needSup, needAccessSys)\n   : (bool * bool)) =>\n   (and_boolMP\n      ((returnm (build_ex needAccessSys)) : M ({_bool : bool & ArithFact (Bool.eqb needAccessSys _bool)}))\n      (build_trivial_ex\n      ((pcc_access_system_regs tt) >>= fun w__9 : bool => returnm ((negb w__9)  : bool))) : M ({_bool : bool & ArithFactP (exists simp_1 , Bool.eqb (needAccessSys &&\n     simp_1) _bool = true)})) >>= fun '(existT _ w__10 _) =>\n   (if sumbool_of_bool w__10 then\n      (raise_c2_exception CapEx_AccessSystemRegsViolation sel)\n       : M (unit)\n    else\n    (and_boolMP\n       ((returnm (build_ex needSup)) : M ({_bool : bool & ArithFact (Bool.eqb needSup _bool)}))\n       (build_trivial_ex\n       ((getAccessLevel tt) >>= fun w__11 : AccessLevel =>\n        returnm ((negb (grantsAccess w__11 Supervisor))  : bool))) : M ({_bool : bool & ArithFactP (exists simp_1 , Bool.eqb (needSup &&\n      simp_1) _bool = true)})) >>= fun '(existT _ w__12 _) =>\n    if sumbool_of_bool w__12 then\n      (raise_c2_exception CapEx_AccessSystemRegsViolation sel)\n       : M (unit)\n    else\n      (readCapReg cb) >>= fun capVal =>\n      let l__66 := projT1 (uint sel) in\n      (if sumbool_of_bool (Z.eqb l__66 0) then write_reg DDC_ref capVal  : M (unit)\n       else if sumbool_of_bool (Z.eqb l__66 1) then write_reg CULR_ref capVal  : M (unit)\n       else if sumbool_of_bool (Z.eqb l__66 8) then write_reg CPLR_ref capVal  : M (unit)\n       else if sumbool_of_bool (Z.eqb l__66 22) then write_reg KR1C_ref capVal  : M (unit)\n       else if sumbool_of_bool (Z.eqb l__66 23) then write_reg KR2C_ref capVal  : M (unit)\n       else if sumbool_of_bool (Z.eqb l__66 28) then write_reg ErrorEPCC_ref capVal  : M (unit)\n       else if sumbool_of_bool (Z.eqb l__66 29) then write_reg KCC_ref capVal  : M (unit)\n       else if sumbool_of_bool (Z.eqb l__66 30) then write_reg KDC_ref capVal  : M (unit)\n       else if sumbool_of_bool (Z.eqb l__66 31) then write_reg EPCC_ref capVal  : M (unit)\n       else assert_exp' false \"CWriteHwr: should be unreachable code\" >>= fun _ => exit tt)\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CUnseal (cd : mword 5) (cs : mword 5) (ct : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cs) >>= fun cs_val =>\n   let cs_otype := projT1 (uint cs_val.(Capability_otype)) in\n   (readCapReg ct) >>= fun ct_val =>\n   let ct_cursor := projT1 (getCapCursor ct_val) in\n   (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs)  : M (unit)\n    else if negb ct_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation ct)  : M (unit)\n    else if negb cs_val.(Capability_sealed) then\n      (raise_c2_exception CapEx_SealViolation cs)\n       : M (unit)\n    else if ct_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation ct)  : M (unit)\n    else if hasReservedOType cs_val then (raise_c2_exception CapEx_TypeViolation cs)  : M (unit)\n    else if sumbool_of_bool (projT1 (neq_int ct_cursor cs_otype)) then\n      (raise_c2_exception CapEx_TypeViolation ct)\n       : M (unit)\n    else if negb ct_val.(Capability_permit_unseal) then\n      (raise_c2_exception CapEx_PermitUnsealViolation ct)\n       : M (unit)\n    else if sumbool_of_bool (Z.ltb ct_cursor (projT1 (getCapBase ct_val))) then\n      (raise_c2_exception CapEx_LengthViolation ct)\n       : M (unit)\n    else if sumbool_of_bool (Z.geb ct_cursor (projT1 (getCapTop ct_val))) then\n      (raise_c2_exception CapEx_LengthViolation ct)\n       : M (unit)\n    else\n      (writeCapReg cd\n         {[ (unsealCap cs_val) with\n           Capability_global := (andb cs_val.(Capability_global) ct_val.(Capability_global)) ]})\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CToPtr (rd : mword 5) (cb : mword 5) (ct : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC ct) >>= fun ct_val =>\n   (readCapReg cb) >>= fun cb_val =>\n   (if negb ct_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation ct)  : M (unit)\n    else if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then\n      (raise_c2_exception CapEx_SealViolation cb)\n       : M (unit)\n    else\n      let ctBase := projT1 (getCapBase ct_val) in\n      (wGPR rd\n         (if negb cb_val.(Capability_tag) then zeros_implicit 64 tt\n          else to_bits 64 (Z.sub (projT1 (getCapCursor cb_val)) ctBase)))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CTestSubset (rd : mword 5) (cb : mword 5) (ct : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (readCapReg ct) >>= fun ct_val =>\n   let ct_top := projT1 (getCapTop ct_val) in\n   let ct_base := projT1 (getCapBase ct_val) in\n   let ct_perms := getCapPerms ct_val in\n   let cb_top := projT1 (getCapTop cb_val) in\n   let cb_base := projT1 (getCapBase cb_val) in\n   let cb_perms := getCapPerms cb_val in\n   let result :=\n     if neq_bool cb_val.(Capability_tag) ct_val.(Capability_tag) then 'b\"0\"  : mword 1\n     else if sumbool_of_bool (Z.ltb ct_base cb_base) then 'b\"0\"  : mword 1\n     else if sumbool_of_bool (Z.gtb ct_top cb_top) then 'b\"0\"  : mword 1\n     else if neq_vec (and_vec ct_perms cb_perms) ct_perms then 'b\"0\"  : mword 1\n     else 'b\"1\"  : mword 1 in\n   (wGPR rd (mips_zero_extend 64 result))\n    : M (unit).\n\nDefinition execute_CSub (rd : mword 5) (cb : mword 5) (ct : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg ct) >>= fun ct_val =>\n   (readCapReg cb) >>= fun cb_val =>\n   (wGPR rd (to_bits 64 (Z.sub (projT1 (getCapCursor cb_val)) (projT1 (getCapCursor ct_val)))))\n    : M (unit).\n\nDefinition execute_CStoreConditional (rs : mword 5) (cb : mword 5) (rd : mword 5) (width : WordType)\n: M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if negb cb_val.(Capability_permit_store) then\n      (raise_c2_exception CapEx_PermitStoreViolation cb)\n       : M (unit)\n    else\n      let size := projT1 (wordWidthBytes width) in\n      let vAddr := projT1 (getCapCursor cb_val) in\n      let vAddr64 := to_bits 64 vAddr in\n      (if sumbool_of_bool (Z.gtb (Z.add vAddr size) (projT1 (getCapTop cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if negb (isAddressAligned vAddr64 width) then\n         (SignalExceptionBadAddr AdES vAddr64)\n          : M (unit)\n       else\n         (TLBTranslate vAddr64 StoreData) >>= fun pAddr =>\n         (rGPR rs) >>= fun rs_val =>\n         ((read_reg CP0LLBit_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n         (if (bit_to_bool (access_vec_dec w__0 0))  : bool then\n            (match width with\n             | B => (MEMw_conditional_wrapper pAddr 1 (subrange_vec_dec rs_val 7 0))  : M (bool)\n             | H => (MEMw_conditional_wrapper pAddr 2 (subrange_vec_dec rs_val 15 0))  : M (bool)\n             | W => (MEMw_conditional_wrapper pAddr 4 (subrange_vec_dec rs_val 31 0))  : M (bool)\n             | D => (MEMw_conditional_wrapper pAddr 8 rs_val)  : M (bool)\n             end)\n             : M (bool)\n          else returnm false) >>= fun success : bool =>\n         (wGPR rd (mips_zero_extend 64 (bool_to_bits success)))\n          : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CStore\n(rs : mword 5) (cb : mword 5) (rt : mword 5) (offset : mword 8) (width : WordType)\n: M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if negb cb_val.(Capability_permit_store) then\n      (raise_c2_exception CapEx_PermitStoreViolation cb)\n       : M (unit)\n    else\n      let size := projT1 (wordWidthBytes width) in\n      let cursor := projT1 (getCapCursor cb_val) in\n      (rGPR rt) >>= fun w__0 : mword 64 =>\n      let vAddr :=\n        projT1\n        (emod_with_eq\n           (Z.add (Z.add cursor (projT1 (uint w__0))) (Z.mul size (projT1 (sint offset))))\n           (projT1\n            (pow2 64))) in\n      let vAddr64 := to_bits 64 vAddr in\n      (if sumbool_of_bool (Z.gtb (Z.add vAddr size) (projT1 (getCapTop cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if negb (isAddressAligned vAddr64 width) then\n         (SignalExceptionBadAddr AdES vAddr64)\n          : M (unit)\n       else\n         (TLBTranslate vAddr64 StoreData) >>= fun pAddr =>\n         (rGPR rs) >>= fun rs_val =>\n         (match width with\n          | B => (MEMw_wrapper pAddr 1 (subrange_vec_dec rs_val 7 0))  : M (unit)\n          | H => (MEMw_wrapper pAddr 2 (subrange_vec_dec rs_val 15 0))  : M (unit)\n          | W => (MEMw_wrapper pAddr 4 (subrange_vec_dec rs_val 31 0))  : M (unit)\n          | D => (MEMw_wrapper pAddr 8 rs_val)  : M (unit)\n          end)\n          : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CSetOffset (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (rGPR rt) >>= fun rt_val =>\n   (if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then\n      (raise_c2_exception CapEx_SealViolation cb)\n       : M (unit)\n    else\n      let '(success, newCap) := setCapOffset cb_val rt_val in\n      (if sumbool_of_bool success then (writeCapReg cd newCap)  : M (unit)\n       else (writeCapReg cd (unrepCap newCap))  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CSetFlags (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (rGPR rt) >>= fun rt_val =>\n   (if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then\n      (raise_c2_exception CapEx_SealViolation cb)\n       : M (unit)\n    else\n      let newCap := setCapFlags cb_val (vector_truncate rt_val num_flags) in\n      (writeCapReg cd newCap)\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CSetCause (rt : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (pcc_access_system_regs tt) >>= fun w__0 : bool =>\n   (if sumbool_of_bool (negb w__0) then\n      (raise_c2_exception_noreg CapEx_AccessSystemRegsViolation)\n       : M (unit)\n    else\n      (rGPR rt) >>= fun rt_val =>\n      (_set_CapCauseReg_ExcCode CapCause_ref (subrange_vec_dec rt_val 15 8)) >>\n      (_set_CapCauseReg_RegNum CapCause_ref (subrange_vec_dec rt_val 7 0))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CSetCID (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if negb cb_val.(Capability_permit_set_CID) then\n      (raise_c2_exception CapEx_PermitSetCIDViolation cb)\n       : M (unit)\n    else\n      let addr := projT1 (getCapCursor cb_val) in\n      (if sumbool_of_bool (Z.ltb addr (projT1 (getCapBase cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.geb addr (projT1 (getCapTop cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else write_reg CID_ref (to_bits 64 addr)  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CSetBoundsImmediate (cd : mword 5) (cb : mword 5) (imm : mword 11) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   let immU := projT1 (uint imm) in\n   let cursor := projT1 (getCapCursor cb_val) in\n   let base := projT1 (getCapBase cb_val) in\n   let top := projT1 (getCapTop cb_val) in\n   let newTop := Z.add cursor immU in\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if sumbool_of_bool (Z.ltb cursor base) then\n      (raise_c2_exception CapEx_LengthViolation cb)\n       : M (unit)\n    else if sumbool_of_bool (Z.gtb newTop top) then\n      (raise_c2_exception CapEx_LengthViolation cb)\n       : M (unit)\n    else\n      let '(_, newCap) := setCapBounds cb_val (to_bits 64 cursor) (to_bits 65 newTop) in\n      (writeCapReg cd newCap)\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CSetBoundsExact (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (rGPR rt) >>= fun w__0 : mword 64 =>\n   let rt_val := projT1 (uint w__0) in\n   let cursor := projT1 (getCapCursor cb_val) in\n   let base := projT1 (getCapBase cb_val) in\n   let top := projT1 (getCapTop cb_val) in\n   let newTop := Z.add cursor rt_val in\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if sumbool_of_bool (Z.ltb cursor base) then\n      (raise_c2_exception CapEx_LengthViolation cb)\n       : M (unit)\n    else if sumbool_of_bool (Z.gtb newTop top) then\n      (raise_c2_exception CapEx_LengthViolation cb)\n       : M (unit)\n    else\n      let '(exact, newCap) := setCapBounds cb_val (to_bits 64 cursor) (to_bits 65 newTop) in\n      (if sumbool_of_bool (negb exact) then (raise_c2_exception CapEx_InexactBounds cb)  : M (unit)\n       else (writeCapReg cd newCap)  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CSetBounds (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (rGPR rt) >>= fun w__0 : mword 64 =>\n   let rt_val := projT1 (uint w__0) in\n   let cursor := projT1 (getCapCursor cb_val) in\n   let base := projT1 (getCapBase cb_val) in\n   let top := projT1 (getCapTop cb_val) in\n   let newTop := Z.add cursor rt_val in\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if sumbool_of_bool (Z.ltb cursor base) then\n      (raise_c2_exception CapEx_LengthViolation cb)\n       : M (unit)\n    else if sumbool_of_bool (Z.gtb newTop top) then\n      (raise_c2_exception CapEx_LengthViolation cb)\n       : M (unit)\n    else\n      let '(_, newCap) := setCapBounds cb_val (to_bits 64 cursor) (to_bits 65 newTop) in\n      (writeCapReg cd newCap)\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CSetAddr (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (rGPR rt) >>= fun rt_val =>\n   (if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then\n      (raise_c2_exception CapEx_SealViolation cb)\n       : M (unit)\n    else\n      let '(representable, newCap) := setCapAddr cb_val rt_val in\n      (if sumbool_of_bool representable then (writeCapReg cd newCap)  : M (unit)\n       else (writeCapReg cd (unrepCap newCap))  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CSealEntry (cd : mword 5) (cs : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cs) >>= fun cs_val =>\n   let cs_cursor := projT1 (getCapCursor cs_val) in\n   let cs_top := projT1 (getCapTop cs_val) in\n   let cs_base := projT1 (getCapBase cs_val) in\n   (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs)  : M (unit)\n    else if cs_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cs)  : M (unit)\n    else if negb cs_val.(Capability_permit_execute) then\n      (raise_c2_exception CapEx_PermitExecuteViolation cs)\n       : M (unit)\n    else\n      let '(success, newCap) := sealCap cs_val (to_bits 24 otype_sentry) in\n      (if sumbool_of_bool (negb success) then\n         (raise_c2_exception CapEx_InexactBounds cs)\n          : M (unit)\n       else (writeCapReg cd newCap)  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CSeal (cd : mword 5) (cs : mword 5) (ct : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cs) >>= fun cs_val =>\n   (readCapReg ct) >>= fun ct_val =>\n   let ct_cursor := projT1 (getCapCursor ct_val) in\n   let ct_top := projT1 (getCapTop ct_val) in\n   let ct_base := projT1 (getCapBase ct_val) in\n   (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs)  : M (unit)\n    else if negb ct_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation ct)  : M (unit)\n    else if cs_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cs)  : M (unit)\n    else if ct_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation ct)  : M (unit)\n    else if negb ct_val.(Capability_permit_seal) then\n      (raise_c2_exception CapEx_PermitSealViolation ct)\n       : M (unit)\n    else if sumbool_of_bool (Z.ltb ct_cursor ct_base) then\n      (raise_c2_exception CapEx_LengthViolation ct)\n       : M (unit)\n    else if sumbool_of_bool (Z.geb ct_cursor ct_top) then\n      (raise_c2_exception CapEx_LengthViolation ct)\n       : M (unit)\n    else if sumbool_of_bool (Z.gtb ct_cursor max_otype) then\n      (raise_c2_exception CapEx_LengthViolation ct)\n       : M (unit)\n    else\n      let '(success, newCap) := sealCap cs_val (to_bits 24 ct_cursor) in\n      (if sumbool_of_bool (negb success) then\n         (raise_c2_exception CapEx_InexactBounds cs)\n          : M (unit)\n       else (writeCapReg cd newCap)  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CSCC (cs : mword 5) (cb : mword 5) (rd : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cs) >>= fun cs_val =>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if negb cb_val.(Capability_permit_store) then\n      (raise_c2_exception CapEx_PermitStoreViolation cb)\n       : M (unit)\n    else if andb (negb cb_val.(Capability_permit_store_cap)) cs_val.(Capability_tag) then\n      (raise_c2_exception CapEx_PermitStoreCapViolation cb)\n       : M (unit)\n    else if andb (negb cb_val.(Capability_permit_store_local_cap))\n              (andb cs_val.(Capability_tag) (negb cs_val.(Capability_global))) then\n      (raise_c2_exception CapEx_PermitStoreLocalCapViolation cb)\n       : M (unit)\n    else\n      let vAddr := projT1 (getCapCursor cb_val) in\n      let vAddr64 := to_bits 64 vAddr in\n      (if sumbool_of_bool (Z.gtb (Z.add vAddr cap_size) (projT1 (getCapTop cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq vAddr cap_size)) 0)) then\n         (SignalExceptionBadAddr AdES vAddr64)\n          : M (unit)\n       else\n         (TLBTranslateC vAddr64 StoreData) >>= fun '(pAddr, macr) =>\n         (match (if eq_bit ((bool_to_bit cs_val.(Capability_tag))  : bitU)\n                      ((bool_to_bit false)\n                       : bitU) then\n                   Unrestricted\n                 else macr) with\n          | Trap => (raise_c2_exception_badaddr CapEx_TLBNoStoreCap cs vAddr64)  : M (bool)\n          | Clear => returnm false\n          | Unrestricted => returnm cs_val.(Capability_tag)\n          end) >>= fun mtag : bool =>\n         ((read_reg CP0LLBit_ref)  : M (mword 1)) >>= fun w__1 : mword 1 =>\n         (if (bit_to_bool (access_vec_dec w__1 0))  : bool then\n            (MEMw_tagged_conditional pAddr cap_size mtag (capToMemBits cs_val))\n             : M (bool)\n          else returnm false) >>= fun success =>\n         (wGPR rd (mips_zero_extend 64 (bool_to_bits success)))\n          : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CSC (cs : mword 5) (cb : mword 5) (rt : mword 5) (offset : mword 11) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cs) >>= fun cs_val =>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if negb cb_val.(Capability_permit_store) then\n      (raise_c2_exception CapEx_PermitStoreViolation cb)\n       : M (unit)\n    else if andb (negb cb_val.(Capability_permit_store_cap)) cs_val.(Capability_tag) then\n      (raise_c2_exception CapEx_PermitStoreCapViolation cb)\n       : M (unit)\n    else if andb (negb cb_val.(Capability_permit_store_local_cap))\n              (andb cs_val.(Capability_tag) (negb cs_val.(Capability_global))) then\n      (raise_c2_exception CapEx_PermitStoreLocalCapViolation cb)\n       : M (unit)\n    else\n      let cursor := projT1 (getCapCursor cb_val) in\n      (rGPR rt) >>= fun w__0 : mword 64 =>\n      let vAddr :=\n        projT1\n        (emod_with_eq (Z.add (Z.add cursor (projT1 (uint w__0))) (Z.mul 16 (projT1 (sint offset))))\n           (projT1\n            (pow2 64))) in\n      let vAddr64 := to_bits 64 vAddr in\n      (if sumbool_of_bool (Z.gtb (Z.add vAddr cap_size) (projT1 (getCapTop cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq vAddr cap_size)) 0)) then\n         (SignalExceptionBadAddr AdES vAddr64)\n          : M (unit)\n       else\n         (TLBTranslateC vAddr64 StoreData) >>= fun '(pAddr, macr) =>\n         (match (if eq_bit ((bool_to_bit cs_val.(Capability_tag))  : bitU)\n                      ((bool_to_bit false)\n                       : bitU) then\n                   Unrestricted\n                 else macr) with\n          | Unrestricted => returnm cs_val.(Capability_tag)\n          | Clear => returnm false\n          | Trap => (raise_c2_exception_badaddr CapEx_TLBNoStoreCap cs vAddr64)  : M (bool)\n          end) >>= fun mtag : bool =>\n         (MEMw_tagged pAddr cap_size mtag (capToMemBits cs_val))\n          : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CReturn '(tt : unit) : M (unit) :=\n   (checkCP2usable tt) >> (raise_c2_exception_noreg CapEx_ReturnTrap)  : M (unit).\n\nDefinition execute_CReadHwr (cd : mword 5) (sel : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   let l__57 := projT1 (uint sel) in\n   (if sumbool_of_bool (Z.eqb l__57 0) then returnm (false, false)\n    else if sumbool_of_bool (Z.eqb l__57 1) then returnm (false, false)\n    else if sumbool_of_bool (Z.eqb l__57 8) then returnm (false, true)\n    else if sumbool_of_bool (Z.eqb l__57 22) then returnm (true, true)\n    else if sumbool_of_bool (Z.eqb l__57 23) then returnm (true, true)\n    else if sumbool_of_bool (Z.eqb l__57 28) then returnm (true, true)\n    else if sumbool_of_bool (Z.eqb l__57 29) then returnm (true, true)\n    else if sumbool_of_bool (Z.eqb l__57 30) then returnm (true, true)\n    else if sumbool_of_bool (Z.eqb l__57 31) then returnm (true, true)\n    else (SignalException ResI)  : M ((bool * bool))) >>= fun '((needSup, needAccessSys)\n   : (bool * bool)) =>\n   (and_boolMP\n      ((returnm (build_ex needAccessSys)) : M ({_bool : bool & ArithFact (Bool.eqb needAccessSys _bool)}))\n      (build_trivial_ex\n      ((pcc_access_system_regs tt) >>= fun w__9 : bool => returnm ((negb w__9)  : bool))) : M ({_bool : bool & ArithFactP (exists simp_1 , Bool.eqb (needAccessSys &&\n     simp_1) _bool = true)})) >>= fun '(existT _ w__10 _) =>\n   (if sumbool_of_bool w__10 then\n      (raise_c2_exception CapEx_AccessSystemRegsViolation sel)\n       : M (unit)\n    else\n    (and_boolMP\n       ((returnm (build_ex needSup)) : M ({_bool : bool & ArithFact (Bool.eqb needSup _bool)}))\n       (build_trivial_ex\n       ((getAccessLevel tt) >>= fun w__11 : AccessLevel =>\n        returnm ((negb (grantsAccess w__11 Supervisor))  : bool))) : M ({_bool : bool & ArithFactP (exists simp_1 , Bool.eqb (needSup &&\n      simp_1) _bool = true)})) >>= fun '(existT _ w__12 _) =>\n    if sumbool_of_bool w__12 then\n      (raise_c2_exception CapEx_AccessSystemRegsViolation sel)\n       : M (unit)\n    else\n      let l__48 := projT1 (uint sel) in\n      (if sumbool_of_bool (Z.eqb l__48 0) then read_reg DDC_ref  : M (Capability)\n       else if sumbool_of_bool (Z.eqb l__48 1) then read_reg CULR_ref  : M (Capability)\n       else if sumbool_of_bool (Z.eqb l__48 8) then read_reg CPLR_ref  : M (Capability)\n       else if sumbool_of_bool (Z.eqb l__48 22) then read_reg KR1C_ref  : M (Capability)\n       else if sumbool_of_bool (Z.eqb l__48 23) then read_reg KR2C_ref  : M (Capability)\n       else if sumbool_of_bool (Z.eqb l__48 28) then read_reg ErrorEPCC_ref  : M (Capability)\n       else if sumbool_of_bool (Z.eqb l__48 29) then read_reg KCC_ref  : M (Capability)\n       else if sumbool_of_bool (Z.eqb l__48 30) then read_reg KDC_ref  : M (Capability)\n       else if sumbool_of_bool (Z.eqb l__48 31) then read_reg EPCC_ref  : M (Capability)\n       else assert_exp' false \"CReadHwr: should be unreachable code\" >>= fun _ => exit tt) >>= fun capVal : Capability =>\n      (writeCapReg cd capVal)\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CRAP (rt : mword 5) (rs : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (rGPR rs) >>= fun len => (wGPR rt (getRepresentableLength len))  : M (unit).\n\nDefinition execute_CRAM (rt : mword 5) (rs : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (rGPR rs) >>= fun len => (wGPR rt (getRepresentableAlignmentMask len))  : M (unit).\n\nDefinition execute_CPtrCmp (rd : mword 5) (cb : mword 5) (ct : mword 5) (op : CPtrCmpOp) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (readCapReg ct) >>= fun ct_val =>\n   let equal : bool := eq_vec cb_val.(Capability_address) ct_val.(Capability_address) in\n   let ltu : bool := zopz0zI_u cb_val.(Capability_address) ct_val.(Capability_address) in\n   let lts : bool := zopz0zI_s cb_val.(Capability_address) ct_val.(Capability_address) in\n   let cmp : bool :=\n     match op with\n     | CEQ => equal\n     | CNE => negb equal\n     | CLT => lts\n     | CLE => orb lts equal\n     | CLTU => ltu\n     | CLEU => orb ltu equal\n     | CEXEQ => generic_eq cb_val ct_val\n     | CNEXEQ => generic_neq cb_val ct_val\n     end in\n   (wGPR rd (mips_zero_extend 64 (bool_to_bits cmp)))\n    : M (unit).\n\nDefinition execute_CMove (cd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun w__0 : Capability => (writeCapReg cd w__0)  : M (unit).\n\nDefinition execute_CMOVX (cd : mword 5) (cb : mword 5) (rt : mword 5) (ismovn : bool) : M (unit) :=\n   (checkCP2usable tt) >>\n   (rGPR rt) >>= fun w__0 : mword 64 =>\n   (if (bits_to_bool\n          (xor_vec (bool_to_bits (eq_vec w__0 (zeros_implicit 64 tt)))\n             ((bool_to_bits ismovn)\n              : mword 1)))\n       : bool then\n      (readCapReg cb) >>= fun w__1 : Capability => (writeCapReg cd w__1)  : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition execute_CLoadTags (rd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if negb cb_val.(Capability_permit_load) then\n      (raise_c2_exception CapEx_PermitLoadViolation cb)\n       : M (unit)\n    else if negb cb_val.(Capability_permit_load_cap) then\n      (raise_c2_exception CapEx_PermitLoadCapViolation cb)\n       : M (unit)\n    else\n      let vAddr := projT1 (getCapCursor cb_val) in\n      let vAddr64 := to_bits 64 (projT1 (getCapCursor cb_val)) in\n      (if sumbool_of_bool\n         (Z.gtb (Z.add vAddr (Z.mul caps_per_cacheline cap_size)) (projT1 (getCapTop cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool\n         (negb (Z.eqb (projT1 (emod_with_eq vAddr (Z.mul cap_size caps_per_cacheline))) 0)) then\n         (SignalExceptionBadAddr AdEL vAddr64)\n          : M (unit)\n       else\n         (TLBTranslateC vAddr64 LoadData) >>= fun '(pAddr, macr) =>\n         (match macr with\n          | Clear => (raise_c2_exception_badaddr CapEx_TLBLoadCap cb vAddr64)  : M (unit)\n          | Trap => (raise_c2_exception_badaddr CapEx_TLBLoadCap cb vAddr64)  : M (unit)\n          | Unrestricted =>\n             let x : bits 64 := zeros_implicit 64 tt in\n             (let loop_i_lower := 0 in\n             let loop_i_upper := Z.sub caps_per_cacheline 1 in\n             (foreach_ZM_up loop_i_lower loop_i_upper 1 x\n               (fun i _ x =>\n                 (MEMr_tagged (add_vec_int pAddr (Z.mul i cap_size)) cap_size true) >>= fun '(tag, _) =>\n                 let x : bits 64 := update_vec_dec x i ((bool_to_bit tag)  : bitU) in\n                 returnm x))) >>= fun x : mword 64 =>\n             (wGPR rd x)\n              : M (unit)\n          end)\n          : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CLoadLinked (rd : mword 5) (cb : mword 5) (signext : bool) (width : WordType)\n: M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if negb cb_val.(Capability_permit_load) then\n      (raise_c2_exception CapEx_PermitLoadViolation cb)\n       : M (unit)\n    else\n      let size := projT1 (wordWidthBytes width) in\n      let vAddr := projT1 (getCapCursor cb_val) in\n      let vAddr64 := to_bits 64 vAddr in\n      (if sumbool_of_bool (Z.gtb (Z.add vAddr size) (projT1 (getCapTop cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if negb (isAddressAligned vAddr64 width) then\n         (SignalExceptionBadAddr AdEL vAddr64)\n          : M (unit)\n       else\n         (TLBTranslate vAddr64 LoadData) >>= fun pAddr =>\n         (MEMr_reserve_wrapper pAddr size) >>= fun w__0 : mword (8 * size) =>\n         let memResult : bits 64 := extendLoad w__0 signext in\n         write_reg CP0LLBit_ref ('b\"1\"  : mword 1) >>\n         write_reg CP0LLAddr_ref pAddr >> (wGPR rd memResult)  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CLoad\n(rd : mword 5) (cb : mword 5) (rt : mword 5) (offset : mword 8) (signext : bool) (width : WordType)\n: M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if negb cb_val.(Capability_permit_load) then\n      (raise_c2_exception CapEx_PermitLoadViolation cb)\n       : M (unit)\n    else\n      let size := projT1 (wordWidthBytes width) in\n      let cursor := projT1 (getCapCursor cb_val) in\n      (rGPR rt) >>= fun w__0 : mword 64 =>\n      let vAddr :=\n        projT1\n        (emod_with_eq\n           (Z.add (Z.add cursor (projT1 (uint w__0))) (Z.mul size (projT1 (sint offset))))\n           (projT1\n            (pow2 64))) in\n      let vAddr64 := to_bits 64 vAddr in\n      (if sumbool_of_bool (Z.gtb (Z.add vAddr size) (projT1 (getCapTop cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if negb (isAddressAligned vAddr64 width) then\n         (SignalExceptionBadAddr AdEL vAddr64)\n          : M (unit)\n       else\n         (TLBTranslate vAddr64 LoadData) >>= fun pAddr =>\n         (MEMr_wrapper pAddr size) >>= fun w__1 : mword (8 * size) =>\n         let memResult : bits 64 := extendLoad w__1 signext in\n         (wGPR rd memResult)\n          : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CLLC (cd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if negb cb_val.(Capability_permit_load) then\n      (raise_c2_exception CapEx_PermitLoadViolation cb)\n       : M (unit)\n    else\n      let vAddr := projT1 (getCapCursor cb_val) in\n      let vAddr64 := to_bits 64 vAddr in\n      (if sumbool_of_bool (Z.gtb (Z.add vAddr cap_size) (projT1 (getCapTop cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq vAddr cap_size)) 0)) then\n         (SignalExceptionBadAddr AdEL vAddr64)\n          : M (unit)\n       else\n         (TLBTranslateC vAddr64 LoadData) >>= fun '(pAddr, macr) =>\n         (MEMr_tagged_reserve pAddr cap_size\n            (andb cb_val.(Capability_permit_load_cap) (negb (generic_eq macr Clear)))) >>= fun '(tag, mem) =>\n         (if sumbool_of_bool (andb tag (generic_eq macr Trap)) then\n            (raise_c2_exception_badaddr CapEx_TLBLoadCap cb vAddr64)\n             : M (unit)\n          else\n            let cap := memBitsToCapability tag mem in\n            (writeCapReg cd cap) >>\n            write_reg CP0LLBit_ref ('b\"1\"  : mword 1) >> write_reg CP0LLAddr_ref pAddr  : M (unit))\n          : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CLCBI (cd : mword 5) (cb : mword 5) (offset : mword 16) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if negb cb_val.(Capability_permit_load) then\n      (raise_c2_exception CapEx_PermitLoadViolation cb)\n       : M (unit)\n    else\n      let cursor := projT1 (getCapCursor cb_val) in\n      let vAddr :=\n        projT1\n        (emod_with_eq (Z.add cursor (Z.mul 16 (projT1 (sint offset)))) (projT1 (pow2 64))) in\n      let vAddr64 := to_bits 64 vAddr in\n      (if sumbool_of_bool (Z.gtb (Z.add vAddr cap_size) (projT1 (getCapTop cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq vAddr cap_size)) 0)) then\n         (SignalExceptionBadAddr AdEL vAddr64)\n          : M (unit)\n       else\n         (TLBTranslateC vAddr64 LoadData) >>= fun '(pAddr, macr) =>\n         (MEMr_tagged pAddr cap_size\n            (andb cb_val.(Capability_permit_load_cap) (negb (generic_eq macr Clear)))) >>= fun '(tag, mem) =>\n         (if sumbool_of_bool (andb tag (generic_eq macr Trap)) then\n            (raise_c2_exception_badaddr CapEx_TLBLoadCap cb vAddr64)\n             : M (unit)\n          else\n            let cap := memBitsToCapability tag mem in\n            (writeCapReg cd cap)\n             : M (unit))\n          : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CLC (cd : mword 5) (cb : mword 5) (rt : mword 5) (offset : mword 11) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if negb cb_val.(Capability_permit_load) then\n      (raise_c2_exception CapEx_PermitLoadViolation cb)\n       : M (unit)\n    else\n      let cursor := projT1 (getCapCursor cb_val) in\n      (rGPR rt) >>= fun w__0 : mword 64 =>\n      let vAddr :=\n        projT1\n        (emod_with_eq (Z.add (Z.add cursor (projT1 (uint w__0))) (Z.mul 16 (projT1 (sint offset))))\n           (projT1\n            (pow2 64))) in\n      let vAddr64 := to_bits 64 vAddr in\n      (if sumbool_of_bool (Z.gtb (Z.add vAddr cap_size) (projT1 (getCapTop cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq vAddr cap_size)) 0)) then\n         (SignalExceptionBadAddr AdEL vAddr64)\n          : M (unit)\n       else\n         (TLBTranslateC vAddr64 LoadData) >>= fun '(pAddr, macr) =>\n         (MEMr_tagged pAddr cap_size\n            (andb cb_val.(Capability_permit_load_cap) (negb (generic_eq macr Clear)))) >>= fun '(tag, mem) =>\n         (if sumbool_of_bool (andb tag (generic_eq macr Trap)) then\n            (raise_c2_exception_badaddr CapEx_TLBLoadCap cb vAddr64)\n             : M (unit)\n          else\n            let cap := memBitsToCapability tag mem in\n            (writeCapReg cd cap)\n             : M (unit))\n          : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CJALR (cd : mword 5) (cb : mword 5) (link : bool) : M (unit) :=\n   (checkCP2usable tt) >>\n   ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n   (if (bits_to_bool w__0)  : bool then (SignalException ResI)  : M (unit)\n    else returnm tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   let cb_ptr := projT1 (getCapCursor cb_val) in\n   let cb_top := projT1 (getCapTop cb_val) in\n   let cb_base := projT1 (getCapBase cb_val) in\n   let sentry := isSentryCap cb_val in\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if sumbool_of_bool (andb cb_val.(Capability_sealed) (negb sentry)) then\n      (raise_c2_exception CapEx_SealViolation cb)\n       : M (unit)\n    else if negb cb_val.(Capability_permit_execute) then\n      (raise_c2_exception CapEx_PermitExecuteViolation cb)\n       : M (unit)\n    else if sumbool_of_bool (Z.ltb cb_ptr cb_base) then\n      (raise_c2_exception CapEx_LengthViolation cb)\n       : M (unit)\n    else if sumbool_of_bool (Z.gtb (Z.add cb_ptr 4) cb_top) then\n      (raise_c2_exception CapEx_LengthViolation cb)\n       : M (unit)\n    else if sumbool_of_bool (projT1 (neq_int (projT1 (emod_with_eq cb_ptr 4)) 0)) then\n      (SignalException AdEL)\n       : M (unit)\n    else\n      let cb_val : Capability := if sumbool_of_bool sentry then unsealCap cb_val else cb_val in\n      (if sumbool_of_bool link then\n         read_reg PCC_ref >>= fun w__1 : Capability =>\n         ((read_reg PC_ref)  : M (mword 64)) >>= fun w__2 : mword 64 =>\n         let '(success, linkCap) := setCapOffset w__1 (add_vec_int w__2 8) in\n         assert_exp' success \"Link cap should always be representable.\" >>= fun _ =>\n         let '(success2, sealedLink) := sealCap linkCap (to_bits 24 otype_sentry) in\n         assert_exp' success2 \"Sealing should always be possible with current format.\" >>= fun _ =>\n         (writeCapReg cd sealedLink)\n          : M (unit)\n       else returnm tt) >>\n      (execute_branch_pcc cb_val)\n       : M (unit)) >>\n   write_reg NextInBranchDelay_ref ('b\"1\"  : mword 1)\n    : M (unit).\n\nDefinition execute_CIncOffsetImmediate (cd : mword 5) (cb : mword 5) (imm : mword 11) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   let imm64 : bits 64 := mips_sign_extend 64 imm in\n   (if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then\n      (raise_c2_exception CapEx_SealViolation cb)\n       : M (unit)\n    else\n      let '(success, newCap) := incCapOffset cb_val imm64 in\n      (if sumbool_of_bool success then (writeCapReg cd newCap)  : M (unit)\n       else (writeCapReg cd (unrepCap newCap))  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CIncOffset (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (rGPR rt) >>= fun rt_val =>\n   (if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then\n      (raise_c2_exception CapEx_SealViolation cb)\n       : M (unit)\n    else\n      let '(success, newCap) := incCapOffset cb_val rt_val in\n      (if sumbool_of_bool success then (writeCapReg cd newCap)  : M (unit)\n       else (writeCapReg cd (unrepCap newCap))  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CGetType (rd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun capVal =>\n   (wGPR rd\n      (if hasReservedOType capVal then mips_sign_extend 64 capVal.(Capability_otype)\n       else mips_zero_extend 64 capVal.(Capability_otype)))\n    : M (unit).\n\nDefinition execute_CGetTag (rd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun capVal =>\n   (wGPR rd (mips_zero_extend 64 (bool_to_bits capVal.(Capability_tag))))\n    : M (unit).\n\nDefinition execute_CGetSealed (rd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun capVal =>\n   (wGPR rd (mips_zero_extend 64 (bool_to_bits capVal.(Capability_sealed))))\n    : M (unit).\n\nDefinition execute_CGetPerm (rd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun capVal =>\n   (wGPR rd (mips_zero_extend 64 (getCapPerms capVal)))\n    : M (unit).\n\nDefinition execute_CGetPCCSetOffset (cd : mword 5) (rs : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (rGPR rs) >>= fun rs_val =>\n   read_reg PCC_ref >>= fun w__0 : Capability =>\n   let '(success, newPCC) := setCapOffset w__0 rs_val in\n   (if sumbool_of_bool success then (writeCapReg cd newPCC)  : M (unit)\n    else (writeCapReg cd (unrepCap newPCC))  : M (unit))\n    : M (unit).\n\nDefinition execute_CGetPCCSetAddr (cd : mword 5) (rs : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (rGPR rs) >>= fun rs_val =>\n   read_reg PCC_ref >>= fun w__0 : Capability =>\n   let '(success, newCap) := setCapAddr w__0 rs_val in\n   (if sumbool_of_bool success then (writeCapReg cd newCap)  : M (unit)\n    else (writeCapReg cd (unrepCap newCap))  : M (unit))\n    : M (unit).\n\nDefinition execute_CGetPCCIncOffset (cd : mword 5) (rs : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (rGPR rs) >>= fun rs_val =>\n   read_reg PCC_ref >>= fun w__0 : Capability =>\n   ((read_reg PC_ref)  : M (mword 64)) >>= fun w__1 : mword 64 =>\n   let '(success, newCap) := setCapOffset w__0 (add_vec w__1 rs_val) in\n   (if sumbool_of_bool success then (writeCapReg cd newCap)  : M (unit)\n    else (writeCapReg cd (unrepCap newCap))  : M (unit))\n    : M (unit).\n\nDefinition execute_CGetPCC (cd : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   read_reg PCC_ref >>= fun w__0 : Capability =>\n   ((read_reg PC_ref)  : M (mword 64)) >>= fun w__1 : mword 64 =>\n   let '(success, pcc) := setCapOffset w__0 w__1 in\n   assert_exp' success \"PCC with offset PC should always be representable\" >>= fun _ =>\n   (writeCapReg cd pcc)\n    : M (unit).\n\nDefinition execute_CGetOffset (rd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun capVal =>\n   (wGPR rd (to_bits 64 (projT1 (getCapOffset capVal))))\n    : M (unit).\n\nDefinition execute_CGetLen (rd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun capVal =>\n   (getCapLength capVal) >>= fun '(existT _ len65 _) =>\n   (wGPR rd (to_bits 64 (if sumbool_of_bool (Z.gtb len65 MAX_U64) then MAX_U64 else len65)))\n    : M (unit).\n\nDefinition execute_CGetFlags (rd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun capVal =>\n   (wGPR rd (mips_zero_extend 64 (getCapFlags capVal)))\n    : M (unit).\n\nDefinition execute_CGetCause (rd : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (pcc_access_system_regs tt) >>= fun w__0 : bool =>\n   (if sumbool_of_bool (negb w__0) then\n      (raise_c2_exception_noreg CapEx_AccessSystemRegsViolation)\n       : M (unit)\n    else\n      read_reg CapCause_ref >>= fun w__1 : CapCauseReg =>\n      (wGPR rd (mips_zero_extend 64 (_get_CapCauseReg_bits w__1)))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CGetCID (rd : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   ((read_reg CID_ref)  : M (mword 64)) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit).\n\nDefinition execute_CGetBase (rd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun capVal => (wGPR rd (to_bits 64 (projT1 (getCapBase capVal))))  : M (unit).\n\nDefinition execute_CGetAndAddr (rd : mword 5) (cb : mword 5) (rs : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun capVal =>\n   (rGPR rs) >>= fun rs_val => (wGPR rd (and_vec capVal.(Capability_address) rs_val))  : M (unit).\n\nDefinition execute_CGetAddr (rd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun capVal => (wGPR rd capVal.(Capability_address))  : M (unit).\n\nDefinition execute_CFromPtr (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (rGPR rt) >>= fun rt_val =>\n   (if eq_vec rt_val (Ox\"0000000000000000\"  : mword 64) then (writeCapReg cd null_cap)  : M (unit)\n    else if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else\n      let '(success, newCap) := setCapOffset cb_val rt_val in\n      (if sumbool_of_bool success then (writeCapReg cd newCap)  : M (unit)\n       else (writeCapReg cd (unrepCap newCap))  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CCopyType (cd : mword 5) (cb : mword 5) (ct : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (readCapReg ct) >>= fun ct_val =>\n   let cb_base := projT1 (getCapBase cb_val) in\n   let cb_top := projT1 (getCapTop cb_val) in\n   let ct_otype := projT1 (uint ct_val.(Capability_otype)) in\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if orb (negb ct_val.(Capability_sealed)) (hasReservedOType ct_val) then\n      (writeCapReg cd\n         {[ null_cap with Capability_address := (mips_sign_extend 64 ct_val.(Capability_otype)) ]})\n       : M (unit)\n    else if sumbool_of_bool (Z.ltb ct_otype cb_base) then\n      (raise_c2_exception CapEx_LengthViolation cb)\n       : M (unit)\n    else if sumbool_of_bool (Z.geb ct_otype cb_top) then\n      (raise_c2_exception CapEx_LengthViolation cb)\n       : M (unit)\n    else\n      let '(success, cap) := setCapOffset cb_val (to_bits 64 (Z.sub ct_otype cb_base)) in\n      assert_exp' success \"CopyType: offset is in bounds so should be representable\" >>= fun _ =>\n      (writeCapReg cd cap)\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CClearTags (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if negb cb_val.(Capability_permit_store) then\n      (raise_c2_exception CapEx_PermitStoreViolation cb)\n       : M (unit)\n    else\n      let vAddr := projT1 (getCapCursor cb_val) in\n      let vAddr64 := to_bits 64 (projT1 (getCapCursor cb_val)) in\n      (if sumbool_of_bool\n         (Z.gtb (Z.add vAddr (Z.mul caps_per_cacheline cap_size)) (projT1 (getCapTop cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb vAddr (projT1 (getCapBase cb_val))) then\n         (raise_c2_exception CapEx_LengthViolation cb)\n          : M (unit)\n       else if sumbool_of_bool\n         (negb (Z.eqb (projT1 (emod_with_eq vAddr (Z.mul cap_size caps_per_cacheline))) 0)) then\n         (SignalExceptionBadAddr AdEL vAddr64)\n          : M (unit)\n       else\n         (TLBTranslate vAddr64 StoreData) >>= fun pAddr =>\n         let loop_i_lower := 0 in\n         let loop_i_upper := Z.sub caps_per_cacheline 1 in\n         (foreach_ZM_up loop_i_lower loop_i_upper 1 tt\n           (fun i _ _ =>\n             (MEMr_tagged (add_vec_int pAddr (Z.mul i cap_size)) cap_size false) >>= fun '(_, mem) =>\n             (MEMw_tagged (add_vec_int pAddr (Z.mul i cap_size)) cap_size false mem)\n              : M (unit))))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CClearTag (cd : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (writeCapReg cd {[ cb_val with Capability_tag := false ]})\n    : M (unit).\n\nDefinition execute_CCheckType (cs : mword 5) (cb : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cs) >>= fun cs_val =>\n   (readCapReg cb) >>= fun cb_val =>\n   (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs)  : M (unit)\n    else if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if orb (negb cs_val.(Capability_sealed)) (hasReservedOType cs_val) then\n      (raise_c2_exception CapEx_SealViolation cs)\n       : M (unit)\n    else if orb (negb cb_val.(Capability_sealed)) (hasReservedOType cb_val) then\n      (raise_c2_exception CapEx_SealViolation cb)\n       : M (unit)\n    else if neq_vec cs_val.(Capability_otype) cb_val.(Capability_otype) then\n      (raise_c2_exception CapEx_TypeViolation cs)\n       : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition execute_CCheckTag (cs : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cs) >>= fun cs_val =>\n   (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs)  : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition execute_CCheckPerm (cs : mword 5) (rt : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cs) >>= fun cs_val =>\n   let cs_perms : bits 64 := mips_zero_extend 64 (getCapPerms cs_val) in\n   (rGPR rt) >>= fun rt_perms =>\n   (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs)  : M (unit)\n    else if neq_vec (and_vec cs_perms rt_perms) rt_perms then\n      (raise_c2_exception CapEx_UserDefViolation cs)\n       : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition execute_CCall (cs : mword 5) (cb : mword 5) (b__107 : mword 11) : M (unit) :=\n   (if eq_vec b__107 ('b\"00000000000\"  : mword 11) then\n      (checkCP2usable tt) >>\n      ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n      (if (bits_to_bool w__0)  : bool then (SignalException ResI)  : M (unit)\n       else returnm tt) >>\n      (readCapReg cs) >>= fun cs_val =>\n      (readCapReg cb) >>= fun cb_val =>\n      let cs_cursor := projT1 (getCapCursor cs_val) in\n      (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs)  : M (unit)\n       else if negb cb_val.(Capability_tag) then\n         (raise_c2_exception CapEx_TagViolation cb)\n          : M (unit)\n       else if orb (negb cs_val.(Capability_sealed)) (hasReservedOType cs_val) then\n         (raise_c2_exception CapEx_SealViolation cs)\n          : M (unit)\n       else if orb (negb cb_val.(Capability_sealed)) (hasReservedOType cb_val) then\n         (raise_c2_exception CapEx_SealViolation cb)\n          : M (unit)\n       else if neq_vec cs_val.(Capability_otype) cb_val.(Capability_otype) then\n         (raise_c2_exception CapEx_TypeViolation cs)\n          : M (unit)\n       else if negb cs_val.(Capability_permit_execute) then\n         (raise_c2_exception CapEx_PermitExecuteViolation cs)\n          : M (unit)\n       else if cb_val.(Capability_permit_execute) then\n         (raise_c2_exception CapEx_PermitExecuteViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb cs_cursor (projT1 (getCapBase cs_val))) then\n         (raise_c2_exception CapEx_LengthViolation cs)\n          : M (unit)\n       else if sumbool_of_bool (Z.geb cs_cursor (projT1 (getCapTop cs_val))) then\n         (raise_c2_exception CapEx_LengthViolation cs)\n          : M (unit)\n       else (raise_c2_exception CapEx_CallTrap cs)  : M (unit))\n       : M (unit)\n    else if eq_vec b__107 ('b\"00000000001\"  : mword 11) then\n      (checkCP2usable tt) >>\n      ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__1 : mword 1 =>\n      (if (bits_to_bool w__1)  : bool then (SignalException ResI)  : M (unit)\n       else returnm tt) >>\n      (readCapReg cs) >>= fun cs_val =>\n      (readCapReg cb) >>= fun cb_val =>\n      let cs_cursor := projT1 (getCapCursor cs_val) in\n      (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs)  : M (unit)\n       else if negb cb_val.(Capability_tag) then\n         (raise_c2_exception CapEx_TagViolation cb)\n          : M (unit)\n       else if hasReservedOType cs_val then (raise_c2_exception CapEx_SealViolation cs)  : M (unit)\n       else if hasReservedOType cb_val then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n       else if neq_vec cs_val.(Capability_otype) cb_val.(Capability_otype) then\n         (raise_c2_exception CapEx_TypeViolation cs)\n          : M (unit)\n       else if negb cs_val.(Capability_permit_ccall) then\n         (raise_c2_exception CapEx_PermitCCallViolation cs)\n          : M (unit)\n       else if negb cb_val.(Capability_permit_ccall) then\n         (raise_c2_exception CapEx_PermitCCallViolation cb)\n          : M (unit)\n       else if negb cs_val.(Capability_permit_execute) then\n         (raise_c2_exception CapEx_PermitExecuteViolation cs)\n          : M (unit)\n       else if cb_val.(Capability_permit_execute) then\n         (raise_c2_exception CapEx_PermitExecuteViolation cb)\n          : M (unit)\n       else if sumbool_of_bool (Z.ltb cs_cursor (projT1 (getCapBase cs_val))) then\n         (raise_c2_exception CapEx_LengthViolation cs)\n          : M (unit)\n       else if sumbool_of_bool (Z.geb cs_cursor (projT1 (getCapTop cs_val))) then\n         (raise_c2_exception CapEx_LengthViolation cs)\n          : M (unit)\n       else\n         (set_next_pcc (unsealCap cs_val)) >>\n         write_reg C26_ref (unsealCap cb_val) >>\n         write_reg NextPC_ref (to_bits 64 (projT1 (getCapOffset cs_val)))\n          : M (unit))\n       : M (unit)\n    else\n      assert_exp' false \"Pattern match failure at ../mips/mips_ri.sail 41:16 - 45:1\" >>= fun _ =>\n      exit tt)\n    : M (unit).\n\nDefinition execute_CCSeal (cd : mword 5) (cs : mword 5) (ct : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cs) >>= fun cs_val =>\n   (readCapReg ct) >>= fun ct_val =>\n   let ct_cursor := projT1 (getCapCursor ct_val) in\n   let ct_top := projT1 (getCapTop ct_val) in\n   let ct_base := projT1 (getCapBase ct_val) in\n   (if negb cs_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cs)  : M (unit)\n    else if eq_vec ct_val.(Capability_address) otype_sentry_bits then\n      (if cs_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cs)  : M (unit)\n       else if negb cs_val.(Capability_permit_execute) then\n         (raise_c2_exception CapEx_PermitExecuteViolation cs)\n          : M (unit)\n       else\n         let '(success, newCap) := sealCap cs_val (to_bits 24 otype_sentry) in\n         (if sumbool_of_bool (negb success) then\n            (raise_c2_exception CapEx_InexactBounds cs)\n             : M (unit)\n          else (writeCapReg cd newCap)  : M (unit))\n          : M (unit))\n       : M (unit)\n    else if orb (negb ct_val.(Capability_tag))\n              (eq_vec ct_val.(Capability_address) otype_unsealed_bits) then\n      (writeCapReg cd cs_val)\n       : M (unit)\n    else if cs_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cs)  : M (unit)\n    else if ct_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation ct)  : M (unit)\n    else if negb ct_val.(Capability_permit_seal) then\n      (raise_c2_exception CapEx_PermitSealViolation ct)\n       : M (unit)\n    else if sumbool_of_bool (Z.ltb ct_cursor ct_base) then\n      (raise_c2_exception CapEx_LengthViolation ct)\n       : M (unit)\n    else if sumbool_of_bool (Z.geb ct_cursor ct_top) then\n      (raise_c2_exception CapEx_LengthViolation ct)\n       : M (unit)\n    else if sumbool_of_bool (Z.gtb ct_cursor max_otype) then\n      (raise_c2_exception CapEx_TypeViolation ct)\n       : M (unit)\n    else\n      let '(success, newCap) := sealCap cs_val (to_bits 24 ct_cursor) in\n      (if sumbool_of_bool (negb success) then\n         (raise_c2_exception CapEx_InexactBounds cs)\n          : M (unit)\n       else (writeCapReg cd newCap)  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CBuildCap (cd : mword 5) (cb : mword 5) (ct : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapRegDDC cb) >>= fun cb_val =>\n   (readCapReg ct) >>= fun ct_val =>\n   let cb_base := projT1 (getCapBase cb_val) in\n   let ct_base := projT1 (getCapBase ct_val) in\n   let cb_top := projT1 (getCapTop cb_val) in\n   let ct_top := projT1 (getCapTop ct_val) in\n   let cb_perms := getCapPerms cb_val in\n   let ct_perms := getCapPerms ct_val in\n   let ct_offset := projT1 (getCapOffset ct_val) in\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else if sumbool_of_bool (Z.ltb ct_base cb_base) then\n      (raise_c2_exception CapEx_LengthViolation cb)\n       : M (unit)\n    else if sumbool_of_bool (Z.gtb ct_top cb_top) then\n      (raise_c2_exception CapEx_LengthViolation cb)\n       : M (unit)\n    else if sumbool_of_bool (Z.gtb ct_base ct_top) then\n      (raise_c2_exception CapEx_LengthViolation ct)\n       : M (unit)\n    else if neq_vec (and_vec ct_perms cb_perms) ct_perms then\n      (raise_c2_exception CapEx_UserDefViolation cb)\n       : M (unit)\n    else\n      let '(exact, cd1) := setCapBounds cb_val (to_bits 64 ct_base) (to_bits 65 ct_top) in\n      let '(representable, cd2) := setCapOffset cd1 (to_bits 64 ct_offset) in\n      let cd3 := setCapPerms cd2 ct_perms in\n      assert_exp' exact \"CBuildCap: setCapBounds was not exact\" >>= fun _ =>\n      assert_exp' representable \"CBuildCap: offset was not representable\" >>= fun _ =>\n      (writeCapReg cd cd3)\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CBZ (cb : mword 5) (imm : mword 16) (notzero : bool) : M (unit) :=\n   (checkCP2usable tt) >>\n   ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n   (if (bits_to_bool w__0)  : bool then (SignalException ResI)  : M (unit)\n    else returnm tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (if (bits_to_bool\n          (xor_vec (bool_to_bits (eq_vec cb_val.(Capability_address) (zeros_implicit 64 tt)))\n             ((bool_to_bits notzero)\n              : mword 1)))\n       : bool then\n      let offset : bits 64 :=\n        add_vec_int (mips_sign_extend 64 (concat_vec imm ('b\"00\"  : mword 2))) 4 in\n      ((read_reg PC_ref)  : M (mword 64)) >>= fun w__1 : mword 64 =>\n      (execute_branch (add_vec w__1 offset))\n       : M (unit)\n    else returnm tt) >>\n   write_reg NextInBranchDelay_ref ('b\"1\"  : mword 1)\n    : M (unit).\n\nDefinition execute_CBX (cb : mword 5) (imm : mword 16) (notset : bool) : M (unit) :=\n   (checkCP2usable tt) >>\n   ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n   (if (bits_to_bool w__0)  : bool then (SignalException ResI)  : M (unit)\n    else returnm tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (if (bits_to_bool\n          (xor_vec (bool_to_bits cb_val.(Capability_tag)) ((bool_to_bits notset)  : mword 1)))\n       : bool then\n      let offset : bits 64 :=\n        add_vec_int (mips_sign_extend 64 (concat_vec imm ('b\"00\"  : mword 2))) 4 in\n      ((read_reg PC_ref)  : M (mword 64)) >>= fun w__1 : mword 64 =>\n      (execute_branch (add_vec w__1 offset))\n       : M (unit)\n    else returnm tt) >>\n   write_reg NextInBranchDelay_ref ('b\"1\"  : mword 1)\n    : M (unit).\n\nDefinition execute_CAndPerm (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (rGPR rt) >>= fun rt_val =>\n   (if negb cb_val.(Capability_tag) then (raise_c2_exception CapEx_TagViolation cb)  : M (unit)\n    else if cb_val.(Capability_sealed) then (raise_c2_exception CapEx_SealViolation cb)  : M (unit)\n    else\n      let perms := getCapPerms cb_val in\n      let newCap := setCapPerms cb_val (and_vec perms (subrange_vec_dec rt_val 30 0)) in\n      (writeCapReg cd newCap)\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CAndAddr (cd : mword 5) (cb : mword 5) (rt : mword 5) : M (unit) :=\n   (checkCP2usable tt) >>\n   (readCapReg cb) >>= fun cb_val =>\n   (rGPR rt) >>= fun rt_val =>\n   (if andb cb_val.(Capability_tag) cb_val.(Capability_sealed) then\n      (raise_c2_exception CapEx_SealViolation cb)\n       : M (unit)\n    else\n      let newAddr := and_vec cb_val.(Capability_address) rt_val in\n      let '(representable, newCap) := setCapAddr cb_val newAddr in\n      (if sumbool_of_bool representable then (writeCapReg cd newCap)  : M (unit)\n       else (writeCapReg cd (unrepCap newCap))  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_CACHE (base : mword 5) (op : mword 5) (imm : mword 16) : M (unit) :=\n   (checkCP0Access tt)  : M (unit).\n\nDefinition execute_C2Dump (rt : mword 5) : unit := tt.\n\nDefinition execute_BREAK '(tt : unit) : M (unit) := (SignalException Bp)  : M (unit).\n\nDefinition execute_BEQ (rs : mword 5) (rd : mword 5) (imm : mword 16) (ne : bool) (likely : bool)\n: M (unit) :=\n   ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n   (if (bits_to_bool w__0)  : bool then (SignalException ResI)  : M (unit)\n    else returnm tt) >>\n   (rGPR rs) >>= fun w__1 : mword 64 =>\n   (rGPR rd) >>= fun w__2 : mword 64 =>\n   (if (bits_to_bool (xor_vec (bool_to_bits (eq_vec w__1 w__2)) ((bool_to_bits ne)  : mword 1)))\n       : bool then\n      let offset : bits 64 :=\n        add_vec_int (mips_sign_extend 64 (concat_vec imm ('b\"00\"  : mword 2))) 4 in\n      ((read_reg PC_ref)  : M (mword 64)) >>= fun w__3 : mword 64 =>\n      (execute_branch (add_vec w__3 offset))\n       : M (unit)\n    else if sumbool_of_bool likely then\n      ((read_reg PC_ref)  : M (mword 64)) >>= fun w__4 : mword 64 =>\n      write_reg NextPC_ref (add_vec_int w__4 8)\n       : M (unit)\n    else write_reg NextInBranchDelay_ref ('b\"1\"  : mword 1)  : M (unit))\n    : M (unit).\n\nDefinition execute_BCMPZ\n(rs : mword 5) (imm : mword 16) (cmp : Comparison) (link : bool) (likely : bool)\n: M (unit) :=\n   ((read_reg InBranchDelay_ref)  : M (mword 1)) >>= fun w__0 : mword 1 =>\n   (if (bits_to_bool w__0)  : bool then (SignalException ResI)  : M (unit)\n    else returnm tt) >>\n   ((read_reg PC_ref)  : M (mword 64)) >>= fun w__1 : mword 64 =>\n   let linkVal := add_vec_int w__1 8 in\n   (rGPR rs) >>= fun regVal =>\n   let condition := compare cmp regVal (mips_zero_extend 64 ('b\"0\"  : mword 1)) in\n   (if sumbool_of_bool condition then\n      let offset : bits 64 :=\n        add_vec_int (mips_sign_extend 64 (concat_vec imm ('b\"00\"  : mword 2))) 4 in\n      ((read_reg PC_ref)  : M (mword 64)) >>= fun w__2 : mword 64 =>\n      (execute_branch (add_vec w__2 offset))\n       : M (unit)\n    else if sumbool_of_bool likely then\n      ((read_reg PC_ref)  : M (mword 64)) >>= fun w__3 : mword 64 =>\n      write_reg NextPC_ref (add_vec_int w__3 8)\n       : M (unit)\n    else write_reg NextInBranchDelay_ref ('b\"1\"  : mword 1)  : M (unit)) >>\n   (if sumbool_of_bool link then (wGPR ('b\"11111\"  : mword 5) linkVal)  : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition execute_ANDI (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (wGPR rt (and_vec w__0 (mips_zero_extend 64 imm)))\n    : M (unit).\n\nDefinition execute_AND (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun w__0 : mword 64 =>\n   (rGPR rt) >>= fun w__1 : mword 64 => (wGPR rd (and_vec w__0 w__1))  : M (unit).\n\nDefinition execute_ADDU (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun opA =>\n   (rGPR rt) >>= fun opB =>\n   (if orb (NotWordVal opA) (NotWordVal opB) then\n      (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit)\n    else\n      (wGPR rd\n         (mips_sign_extend 64 (add_vec (subrange_vec_dec opA 31 0) (subrange_vec_dec opB 31 0))))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_ADDIU (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) :=\n   (rGPR rs) >>= fun opA =>\n   (if NotWordVal opA then\n      (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rt w__0)  : M (unit)\n    else\n      (wGPR rt\n         (mips_sign_extend 64\n            (add_vec (subrange_vec_dec opA 31 0) (mips_sign_extend (Z.add (Z.sub 31 0) 1) imm))))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_ADDI (rs : mword 5) (rt : mword 5) (imm : mword 16) : M (unit) :=\n   (rGPR rs) >>= fun opA =>\n   (if NotWordVal opA then\n      (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rt w__0)  : M (unit)\n    else\n      let sum33 : bits 33 :=\n        add_vec (mips_sign_extend 33 (subrange_vec_dec opA 31 0)) (mips_sign_extend 33 imm) in\n      (if neq_bool (bit_to_bool (access_vec_dec sum33 32)) (bit_to_bool (access_vec_dec sum33 31))\n       then\n         (SignalException Ov)\n          : M (unit)\n       else (wGPR rt (mips_sign_extend 64 (subrange_vec_dec sum33 31 0)))  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_ADD (rs : mword 5) (rt : mword 5) (rd : mword 5) : M (unit) :=\n   (rGPR rs) >>= fun opA : bits 64 =>\n   (rGPR rt) >>= fun opB : bits 64 =>\n   (if orb (NotWordVal opA) (NotWordVal opB) then\n      (undefined_bitvector 64) >>= fun w__0 : mword 64 => (wGPR rd w__0)  : M (unit)\n    else\n      let sum33 : bits 33 :=\n        add_vec (mips_sign_extend 33 (subrange_vec_dec opA 31 0))\n          (mips_sign_extend 33 (subrange_vec_dec opB 31 0)) in\n      (if neq_bool (bit_to_bool (access_vec_dec sum33 32)) (bit_to_bool (access_vec_dec sum33 31))\n       then\n         (SignalException Ov)\n          : M (unit)\n       else (wGPR rd (mips_sign_extend 64 (subrange_vec_dec sum33 31 0)))  : M (unit))\n       : M (unit))\n    : M (unit).\n\nDefinition execute_measure (instr : ast) : Z :=\n   match instr with | CLCNT (cd, cb, rt) => 1 | _ => 0 end.\n\nFixpoint _rec_execute (merge_var : ast) (_reclimit : Z) (_acc : Acc (Zwf 0) _reclimit)\n{struct _acc} : M (unit).\nexact (\n   assert_exp' (Z.geb _reclimit 0) \"recursion limit reached\" >>= fun _ =>\n   (match merge_var with\n    | CLCNT (cd, cb, rt) =>\n       (_rec_execute (CLC (cd, cb, rt, to_bits 11 0)) (Z.sub _reclimit 1) (_limit_reduces _acc))\n        : M (unit)\n    | DADDIU (rs, rt, imm) => (execute_DADDIU rs rt imm)  : M (unit)\n    | DADDU (rs, rt, rd) => (execute_DADDU rs rt rd)  : M (unit)\n    | DADDI (rs, rt, imm) => (execute_DADDI rs rt imm)  : M (unit)\n    | DADD (rs, rt, rd) => (execute_DADD rs rt rd)  : M (unit)\n    | ADD (rs, rt, rd) => (execute_ADD rs rt rd)  : M (unit)\n    | ADDI (rs, rt, imm) => (execute_ADDI rs rt imm)  : M (unit)\n    | ADDU (rs, rt, rd) => (execute_ADDU rs rt rd)  : M (unit)\n    | ADDIU (rs, rt, imm) => (execute_ADDIU rs rt imm)  : M (unit)\n    | DSUBU (rs, rt, rd) => (execute_DSUBU rs rt rd)  : M (unit)\n    | DSUB (rs, rt, rd) => (execute_DSUB rs rt rd)  : M (unit)\n    | SUB (rs, rt, rd) => (execute_SUB rs rt rd)  : M (unit)\n    | SUBU (rs, rt, rd) => (execute_SUBU rs rt rd)  : M (unit)\n    | AND (rs, rt, rd) => (execute_AND rs rt rd)  : M (unit)\n    | ANDI (rs, rt, imm) => (execute_ANDI rs rt imm)  : M (unit)\n    | OR (rs, rt, rd) => (execute_OR rs rt rd)  : M (unit)\n    | ORI (rs, rt, imm) => (execute_ORI rs rt imm)  : M (unit)\n    | NOR (rs, rt, rd) => (execute_NOR rs rt rd)  : M (unit)\n    | XOR (rs, rt, rd) => (execute_XOR rs rt rd)  : M (unit)\n    | XORI (rs, rt, imm) => (execute_XORI rs rt imm)  : M (unit)\n    | LUI (rt, imm) => (execute_LUI rt imm)  : M (unit)\n    | DSLL (rt, rd, sa) => (execute_DSLL rt rd sa)  : M (unit)\n    | DSLL32 (rt, rd, sa) => (execute_DSLL32 rt rd sa)  : M (unit)\n    | DSLLV (rs, rt, rd) => (execute_DSLLV rs rt rd)  : M (unit)\n    | DSRA (rt, rd, sa) => (execute_DSRA rt rd sa)  : M (unit)\n    | DSRA32 (rt, rd, sa) => (execute_DSRA32 rt rd sa)  : M (unit)\n    | DSRAV (rs, rt, rd) => (execute_DSRAV rs rt rd)  : M (unit)\n    | DSRL (rt, rd, sa) => (execute_DSRL rt rd sa)  : M (unit)\n    | DSRL32 (rt, rd, sa) => (execute_DSRL32 rt rd sa)  : M (unit)\n    | DSRLV (rs, rt, rd) => (execute_DSRLV rs rt rd)  : M (unit)\n    | SLL (rt, rd, sa) => (execute_SLL rt rd sa)  : M (unit)\n    | SLLV (rs, rt, rd) => (execute_SLLV rs rt rd)  : M (unit)\n    | SRA (rt, rd, sa) => (execute_SRA rt rd sa)  : M (unit)\n    | SRAV (rs, rt, rd) => (execute_SRAV rs rt rd)  : M (unit)\n    | SRL (rt, rd, sa) => (execute_SRL rt rd sa)  : M (unit)\n    | SRLV (rs, rt, rd) => (execute_SRLV rs rt rd)  : M (unit)\n    | SLT (rs, rt, rd) => (execute_SLT rs rt rd)  : M (unit)\n    | SLTI (rs, rt, imm) => (execute_SLTI rs rt imm)  : M (unit)\n    | SLTU (rs, rt, rd) => (execute_SLTU rs rt rd)  : M (unit)\n    | SLTIU (rs, rt, imm) => (execute_SLTIU rs rt imm)  : M (unit)\n    | MOVN (rs, rt, rd) => (execute_MOVN rs rt rd)  : M (unit)\n    | MOVZ (rs, rt, rd) => (execute_MOVZ rs rt rd)  : M (unit)\n    | MFHI rd => (execute_MFHI rd)  : M (unit)\n    | MFLO rd => (execute_MFLO rd)  : M (unit)\n    | MTHI rs => (execute_MTHI rs)  : M (unit)\n    | MTLO rs => (execute_MTLO rs)  : M (unit)\n    | MUL (rs, rt, rd) => (execute_MUL rs rt rd)  : M (unit)\n    | MULT (rs, rt) => (execute_MULT rs rt)  : M (unit)\n    | MULTU (rs, rt) => (execute_MULTU rs rt)  : M (unit)\n    | DMULT (rs, rt) => (execute_DMULT rs rt)  : M (unit)\n    | DMULTU (rs, rt) => (execute_DMULTU rs rt)  : M (unit)\n    | MADD (rs, rt) => (execute_MADD rs rt)  : M (unit)\n    | MADDU (rs, rt) => (execute_MADDU rs rt)  : M (unit)\n    | MSUB (rs, rt) => (execute_MSUB rs rt)  : M (unit)\n    | MSUBU (rs, rt) => (execute_MSUBU rs rt)  : M (unit)\n    | DIV (rs, rt) => (execute_DIV rs rt)  : M (unit)\n    | DIVU (rs, rt) => (execute_DIVU rs rt)  : M (unit)\n    | DDIV (rs, rt) => (execute_DDIV rs rt)  : M (unit)\n    | DDIVU (rs, rt) => (execute_DDIVU rs rt)  : M (unit)\n    | J offset => (execute_J offset)  : M (unit)\n    | JAL offset => (execute_JAL offset)  : M (unit)\n    | JR rs => (execute_JR rs)  : M (unit)\n    | JALR (rs, rd) => (execute_JALR rs rd)  : M (unit)\n    | BEQ (rs, rd, imm, ne, likely) => (execute_BEQ rs rd imm ne likely)  : M (unit)\n    | BCMPZ (rs, imm, cmp, link, likely) => (execute_BCMPZ rs imm cmp link likely)  : M (unit)\n    | SYSCALL arg0 => (execute_SYSCALL arg0)  : M (unit)\n    | BREAK arg0 => (execute_BREAK arg0)  : M (unit)\n    | WAIT arg0 => (execute_WAIT arg0)  : M (unit)\n    | TRAPREG (rs, rt, cmp) => (execute_TRAPREG rs rt cmp)  : M (unit)\n    | TRAPIMM (rs, imm, cmp) => (execute_TRAPIMM rs imm cmp)  : M (unit)\n    | Load (width, sign, linked, base, rt, offset) =>\n       (execute_Load width sign linked base rt offset)  : M (unit)\n    | Store (width, conditional, base, rt, offset) =>\n       (execute_Store width conditional base rt offset)  : M (unit)\n    | LWL (base, rt, offset) => (execute_LWL base rt offset)  : M (unit)\n    | LWR (base, rt, offset) => (execute_LWR base rt offset)  : M (unit)\n    | SWL (base, rt, offset) => (execute_SWL base rt offset)  : M (unit)\n    | SWR (base, rt, offset) => (execute_SWR base rt offset)  : M (unit)\n    | LDL (base, rt, offset) => (execute_LDL base rt offset)  : M (unit)\n    | LDR (base, rt, offset) => (execute_LDR base rt offset)  : M (unit)\n    | SDL (base, rt, offset) => (execute_SDL base rt offset)  : M (unit)\n    | SDR (base, rt, offset) => (execute_SDR base rt offset)  : M (unit)\n    | CACHE (base, op, imm) => (execute_CACHE base op imm)  : M (unit)\n    | SYNC arg0 => (execute_SYNC arg0)  : M (unit)\n    | MFC0 (rt, rd, sel, double) => (execute_MFC0 rt rd sel double)  : M (unit)\n    | HCF arg0 => returnm (execute_HCF arg0)\n    | MTC0 (rt, rd, sel, double) => (execute_MTC0 rt rd sel double)  : M (unit)\n    | TLBWI arg0 => (execute_TLBWI arg0)  : M (unit)\n    | TLBWR arg0 => (execute_TLBWR arg0)  : M (unit)\n    | TLBR arg0 => (execute_TLBR arg0)  : M (unit)\n    | TLBP arg0 => (execute_TLBP arg0)  : M (unit)\n    | RDHWR (rt, rd) => (execute_RDHWR rt rd)  : M (unit)\n    | ERET arg0 => (execute_ERET arg0)  : M (unit)\n    | CGetPerm (rd, cb) => (execute_CGetPerm rd cb)  : M (unit)\n    | CGetFlags (rd, cb) => (execute_CGetFlags rd cb)  : M (unit)\n    | CGetType (rd, cb) => (execute_CGetType rd cb)  : M (unit)\n    | CGetBase (rd, cb) => (execute_CGetBase rd cb)  : M (unit)\n    | CGetOffset (rd, cb) => (execute_CGetOffset rd cb)  : M (unit)\n    | CGetLen (rd, cb) => (execute_CGetLen rd cb)  : M (unit)\n    | CGetTag (rd, cb) => (execute_CGetTag rd cb)  : M (unit)\n    | CGetSealed (rd, cb) => (execute_CGetSealed rd cb)  : M (unit)\n    | CGetAddr (rd, cb) => (execute_CGetAddr rd cb)  : M (unit)\n    | CGetAndAddr (rd, cb, rs) => (execute_CGetAndAddr rd cb rs)  : M (unit)\n    | CGetPCC cd => (execute_CGetPCC cd)  : M (unit)\n    | CGetPCCSetOffset (cd, rs) => (execute_CGetPCCSetOffset cd rs)  : M (unit)\n    | CGetPCCIncOffset (cd, rs) => (execute_CGetPCCIncOffset cd rs)  : M (unit)\n    | CGetPCCSetAddr (cd, rs) => (execute_CGetPCCSetAddr cd rs)  : M (unit)\n    | CGetCause rd => (execute_CGetCause rd)  : M (unit)\n    | CSetCause rt => (execute_CSetCause rt)  : M (unit)\n    | CGetCID rd => (execute_CGetCID rd)  : M (unit)\n    | CSetCID cb => (execute_CSetCID cb)  : M (unit)\n    | CRAP (rt, rs) => (execute_CRAP rt rs)  : M (unit)\n    | CRAM (rt, rs) => (execute_CRAM rt rs)  : M (unit)\n    | CReadHwr (cd, sel) => (execute_CReadHwr cd sel)  : M (unit)\n    | CWriteHwr (cb, sel) => (execute_CWriteHwr cb sel)  : M (unit)\n    | CAndPerm (cd, cb, rt) => (execute_CAndPerm cd cb rt)  : M (unit)\n    | CSetFlags (cd, cb, rt) => (execute_CSetFlags cd cb rt)  : M (unit)\n    | CToPtr (rd, cb, ct) => (execute_CToPtr rd cb ct)  : M (unit)\n    | CSub (rd, cb, ct) => (execute_CSub rd cb ct)  : M (unit)\n    | CPtrCmp (rd, cb, ct, op) => (execute_CPtrCmp rd cb ct op)  : M (unit)\n    | CIncOffset (cd, cb, rt) => (execute_CIncOffset cd cb rt)  : M (unit)\n    | CIncOffsetImmediate (cd, cb, imm) => (execute_CIncOffsetImmediate cd cb imm)  : M (unit)\n    | CSetOffset (cd, cb, rt) => (execute_CSetOffset cd cb rt)  : M (unit)\n    | CSetAddr (cd, cb, rt) => (execute_CSetAddr cd cb rt)  : M (unit)\n    | CAndAddr (cd, cb, rt) => (execute_CAndAddr cd cb rt)  : M (unit)\n    | CSetBounds (cd, cb, rt) => (execute_CSetBounds cd cb rt)  : M (unit)\n    | CSetBoundsImmediate (cd, cb, imm) => (execute_CSetBoundsImmediate cd cb imm)  : M (unit)\n    | CSetBoundsExact (cd, cb, rt) => (execute_CSetBoundsExact cd cb rt)  : M (unit)\n    | CClearTag (cd, cb) => (execute_CClearTag cd cb)  : M (unit)\n    | CMOVX (cd, cb, rt, ismovn) => (execute_CMOVX cd cb rt ismovn)  : M (unit)\n    | CMove (cd, cb) => (execute_CMove cd cb)  : M (unit)\n    | ClearRegs (regset, m) => (execute_ClearRegs regset m)  : M (unit)\n    | CFromPtr (cd, cb, rt) => (execute_CFromPtr cd cb rt)  : M (unit)\n    | CBuildCap (cd, cb, ct) => (execute_CBuildCap cd cb ct)  : M (unit)\n    | CCopyType (cd, cb, ct) => (execute_CCopyType cd cb ct)  : M (unit)\n    | CCheckPerm (cs, rt) => (execute_CCheckPerm cs rt)  : M (unit)\n    | CCheckType (cs, cb) => (execute_CCheckType cs cb)  : M (unit)\n    | CCheckTag cs => (execute_CCheckTag cs)  : M (unit)\n    | CTestSubset (rd, cb, ct) => (execute_CTestSubset rd cb ct)  : M (unit)\n    | CSeal (cd, cs, ct) => (execute_CSeal cd cs ct)  : M (unit)\n    | CCSeal (cd, cs, ct) => (execute_CCSeal cd cs ct)  : M (unit)\n    | CSealEntry (cd, cs) => (execute_CSealEntry cd cs)  : M (unit)\n    | CUnseal (cd, cs, ct) => (execute_CUnseal cd cs ct)  : M (unit)\n    | CCall (cs, cb, b__107) => (execute_CCall cs cb b__107)  : M (unit)\n    | CReturn arg0 => (execute_CReturn arg0)  : M (unit)\n    | CBX (cb, imm, notset) => (execute_CBX cb imm notset)  : M (unit)\n    | CBZ (cb, imm, notzero) => (execute_CBZ cb imm notzero)  : M (unit)\n    | CJALR (cd, cb, link) => (execute_CJALR cd cb link)  : M (unit)\n    | CLoad (rd, cb, rt, offset, signext, width) =>\n       (execute_CLoad rd cb rt offset signext width)  : M (unit)\n    | CLoadLinked (rd, cb, signext, width) => (execute_CLoadLinked rd cb signext width)  : M (unit)\n    | CLoadTags (rd, cb) => (execute_CLoadTags rd cb)  : M (unit)\n    | CStore (rs, cb, rt, offset, width) => (execute_CStore rs cb rt offset width)  : M (unit)\n    | CStoreConditional (rs, cb, rd, width) =>\n       (execute_CStoreConditional rs cb rd width)  : M (unit)\n    | CSC (cs, cb, rt, offset) => (execute_CSC cs cb rt offset)  : M (unit)\n    | CSCC (cs, cb, rd) => (execute_CSCC cs cb rd)  : M (unit)\n    | CLC (cd, cb, rt, offset) => (execute_CLC cd cb rt offset)  : M (unit)\n    | CLCBI (cd, cb, offset) => (execute_CLCBI cd cb offset)  : M (unit)\n    | CLLC (cd, cb) => (execute_CLLC cd cb)  : M (unit)\n    | CClearTags cb => (execute_CClearTags cb)  : M (unit)\n    | C2Dump rt => returnm (execute_C2Dump rt)\n    | RI arg0 => (execute_RI arg0)  : M (unit)\n    end)\n    : M (unit)\n).\nDefined.\n\n\nDefinition execute (i : ast) : M (unit) :=\n   (_rec_execute i ((execute_measure i)  : Z) (Zwf_guarded _))  : M (unit).\n\nDefinition assembly (merge_var : ast) : string :=\n   match merge_var with\n   | DADDIU (rs, rt, imm) => String.append \"daddiu \" (strRRIArgs rs rt imm)\n   | DADDU (rs, rt, rd) => String.append \"daddu \" (strRRRArgs rs rt rd)\n   | DADDI (rs, rt, imm) => String.append \"daddi \" (strRRIArgs rs rt imm)\n   | DADD (rs, rt, rd) => String.append \"dadd \" (strRRRArgs rs rt rd)\n   | ADD (rs, rt, rd) => String.append \"add \" (strRRRArgs rs rt rd)\n   | ADDI (rs, rt, imm) => String.append \"addi \" (strRRIArgs rs rt imm)\n   | ADDU (rs, rt, rd) => String.append \"addu \" (strRRRArgs rs rt rd)\n   | ADDIU (rs, rt, imm) => String.append \"addiu \" (strRRIArgs rs rt imm)\n   | DSUBU (rs, rt, rd) => String.append \"dsubu \" (strRRRArgs rs rt rd)\n   | DSUB (rs, rt, rd) => String.append \"dsub \" (strRRRArgs rs rt rd)\n   | SUB (rs, rt, rd) => String.append \"sub \" (strRRRArgs rs rt rd)\n   | SUBU (rs, rt, rd) => String.append \"subu \" (strRRRArgs rs rt rd)\n   | AND (rs, rt, rd) => String.append \"and \" (strRRRArgs rs rt rd)\n   | ANDI (rs, rt, imm) => String.append \"andi \" (strRRIUArgs rs rt imm)\n   | OR (rs, rt, rd) => String.append \"or \" (strRRRArgs rs rt rd)\n   | ORI (rs, rt, imm) => String.append \"ori \" (strRRIUArgs rs rt imm)\n   | NOR (rs, rt, rd) => String.append \"nor \" (strRRRArgs rs rt rd)\n   | XOR (rs, rt, rd) => String.append \"xor \" (strRRRArgs rs rt rd)\n   | XORI (rs, rt, imm) => String.append \"xori \" (strRRIUArgs rs rt imm)\n   | LUI (rt, imm) => String.append \"lui \" (strRIArgs rt imm)\n   | DSLL (rs, rd, sa) => String.append \"dsll \" (strRRIUArgs rs rd sa)\n   | DSLL32 (rs, rd, sa) => String.append \"dsll32 \" (strRRIUArgs rs rd sa)\n   | DSLLV (rs, rt, rd) => String.append \"dsllv \" (strRRRArgs rs rt rd)\n   | DSRA (rt, rd, sa) => String.append \"dsra \" (strRRIUArgs rt rd sa)\n   | DSRA32 (rt, rd, sa) => String.append \"dsra32 \" (strRRIUArgs rt rd sa)\n   | DSRAV (rs, rt, rd) => String.append \"dsrav \" (strRRRArgs rs rt rd)\n   | DSRL (rt, rd, sa) => String.append \"dsrl \" (strRRIUArgs rt rd sa)\n   | DSRL32 (rt, rd, sa) => String.append \"dsrl32 \" (strRRIUArgs rt rd sa)\n   | DSRLV (rs, rt, rd) => String.append \"dsrlv \" (strRRRArgs rs rt rd)\n   | SLL (rt, rd, sa) => String.append \"sll \" (strRRIUArgs rt rd sa)\n   | SLLV (rs, rt, rd) => String.append \"sllv \" (strRRRArgs rs rt rd)\n   | SRA (rt, rd, sa) => String.append \"sra \" (strRRIUArgs rt rd sa)\n   | SRAV (rs, rt, rd) => String.append \"srav \" (strRRRArgs rs rt rd)\n   | SRL (rt, rd, sa) => String.append \"srl \" (strRRIUArgs rt rd sa)\n   | SRLV (rs, rt, rd) => String.append \"srlv \" (strRRRArgs rs rt rd)\n   | SLT (rs, rt, rd) => String.append \"slt \" (strRRRArgs rs rt rd)\n   | SLTI (rs, rd, imm) => String.append \"slti \" (strRRIArgs rs rd imm)\n   | SLTU (rs, rt, rd) => String.append \"sltu \" (strRRRArgs rs rt rd)\n   | SLTIU (rs, rd, imm) => String.append \"sltiu \" (strRRIUArgs rs rd imm)\n   | MOVN (rs, rt, rd) => String.append \"movn \" (strRRRArgs rs rt rd)\n   | MOVZ (rs, rt, rd) => String.append \"movz \" (strRRRArgs rs rt rd)\n   | MFHI rd => String.append \"mfhi \" (strReg rd)\n   | MFLO rd => String.append \"mflo \" (strReg rd)\n   | MTHI rs => String.append \"mthi \" (strReg rs)\n   | MTLO rs => String.append \"mtlo \" (strReg rs)\n   | MUL (rs, rt, rd) => String.append \"mul \" (strRRRArgs rs rt rd)\n   | MULT (rs, rt) =>\n      String.append \"mult \" (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | MULTU (rs, rt) =>\n      String.append \"multu \" (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | DMULT (rs, rt) =>\n      String.append \"dmult \" (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | DMULTU (rs, rt) =>\n      String.append \"dmultu \" (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | MADD (rs, rt) =>\n      String.append \"madd \" (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | MADDU (rs, rt) =>\n      String.append \"maddu \" (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | MSUB (rs, rt) =>\n      String.append \"msub \" (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | MSUBU (rs, rt) =>\n      String.append \"msubu \" (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | DIV (rs, rt) =>\n      String.append \"div \" (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | DIVU (rs, rt) =>\n      String.append \"divu \" (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | DDIV (rs, rt) =>\n      String.append \"ddiv \" (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | DDIVU (rs, rt) =>\n      String.append \"ddivu \" (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | J offset => String.append \"j \" (hex_str (projT1 (uint offset)))\n   | JAL offset => String.append \"jal \" (hex_str (projT1 (uint offset)))\n   | JR rs => String.append \"jr \" (strReg rs)\n   | JALR (rs, rd) =>\n      String.append \"jalr \" (String.append (strReg rd) (String.append \", \" (strReg rs)))\n   | BEQ (rs, rt, imm, ne, likely) =>\n      let op := if sumbool_of_bool ne then \"bne\" else \"beq\" in\n      let l := if sumbool_of_bool likely then \"l \" else \" \" in\n      String.append op\n        (String.append l\n           (String.append (strReg rs)\n              (String.append \", \"\n                 (String.append (strReg rt) (String.append \", \" (hex_str (projT1 (sint imm))))))))\n   | BCMPZ (rs, imm, cmp, link, likely) =>\n      let op := String.append \"b\" (String.append (strCmp cmp) \"z\") in\n      let al := if sumbool_of_bool link then \"al\" else \"\" in\n      let l := if sumbool_of_bool likely then \"l \" else \" \" in\n      String.append op\n        (String.append al\n           (String.append l\n              (String.append (strReg rs) (String.append \", \" (hex_str (projT1 (sint imm)))))))\n   | SYSCALL tt => \"syscall\"\n   | BREAK tt => \"break\"\n   | WAIT tt => \"wait\"\n   | TRAPREG (rs, rt, cmp) =>\n      let op := String.append \"t\" (String.append (strCmp cmp) \" \") in\n      String.append op (String.append (strReg rs) (String.append \", \" (strReg rt)))\n   | TRAPIMM (rs, imm, cmp) =>\n      let op := String.append \"t\" (String.append (strCmp cmp) \"i \") in\n      String.append op\n        (String.append (strReg rs) (String.append \", \" (hex_str (projT1 (uint imm)))))\n   | Load (width, sign, linked, base, rt, offset) =>\n      let op : string :=\n        match (width, sign, linked) with\n        | (B, true, false) => \"lb \"\n        | (B, false, false) => \"lbu \"\n        | (H, true, false) => \"lh \"\n        | (H, false, false) => \"lhu \"\n        | (W, true, false) => \"lw \"\n        | (W, false, false) => \"lwu \"\n        | (D, false, false) => \"ld \"\n        | (W, true, true) => \"ll \"\n        | (D, false, true) => \"lld \"\n        | _ => \"invalid load\"\n        end in\n      String.append op (strMemArgs base rt offset)\n   | Store (width, conditional, base, rt, offset) =>\n      let op : string :=\n        if sumbool_of_bool conditional then\n          match width with | W => \"sc\" | D => \"scd\" | _ => \"invalid sc\" end\n        else String.append \"s\" (strWordType width) in\n      String.append op (String.append \" \" (strMemArgs base rt offset))\n   | LWL (base, rt, offset) => String.append \"lwl \" (strMemArgs base rt offset)\n   | LWR (base, rt, offset) => String.append \"lwr \" (strMemArgs base rt offset)\n   | SWL (base, rt, offset) => String.append \"swl \" (strMemArgs base rt offset)\n   | SWR (base, rt, offset) => String.append \"swr \" (strMemArgs base rt offset)\n   | LDL (base, rt, offset) => String.append \"ldl \" (strMemArgs base rt offset)\n   | LDR (base, rt, offset) => String.append \"ldr \" (strMemArgs base rt offset)\n   | SDL (base, rt, offset) => String.append \"sdl \" (strMemArgs base rt offset)\n   | SDR (base, rt, offset) => String.append \"sdr \" (strMemArgs base rt offset)\n   | CACHE (base, op, imm) => String.append \"cache \" (strMemArgs base op imm)\n   | SYNC tt => \"sync\"\n   | MFC0 (rt, rd, sel, double) =>\n      let op := if sumbool_of_bool double then \"dmfc0 \" else \"mfc0 \" in\n      String.append op\n        (String.append (strReg rt)\n           (String.append \", \"\n              (String.append (strReg rd) (String.append \", $\" (dec_str (projT1 (uint sel)))))))\n   | MTC0 (rt, rd, sel, double) =>\n      let op := if sumbool_of_bool double then \"dmtc0 \" else \"mtc0 \" in\n      String.append op\n        (String.append (strReg rt)\n           (String.append \", \"\n              (String.append (strReg rd) (String.append \", $\" (dec_str (projT1 (uint sel)))))))\n   | TLBWI tt => \"tlbwi\"\n   | TLBWR tt => \"tlbwr\"\n   | TLBR tt => \"tlbr\"\n   | TLBP tt => \"tlbp\"\n   | RDHWR (rt, rd) =>\n      String.append \"rdhwr\" (String.append (strReg rt) (String.append \", \" (strReg rd)))\n   | ERET tt => \"eret\"\n   | CGetCause rd => String.append \"cgetcause \" (strReg rd)\n   | CSetCause rs => String.append \"csetcause \" (strReg rs)\n   | CGetPCC cd => String.append \"cgetpcc \" (strCReg cd)\n   | CJALR (b__0, cb, false) =>\n      if eq_vec b__0 ('b\"00000\"  : mword 5) then String.append \"cjr \" (strCReg cb)\n      else \"assembly unimplemented\"\n   | CGetCID rd => String.append \"cgetcid \" (strReg rd)\n   | CSetCID cb => String.append \"csetcid \" (strCReg cb)\n   | CClearTags cb => String.append \"ccleartags \" (strCReg cb)\n   | CCheckPerm (cs, rt) => String.append \"ccheckperm \" (strCRArgs cs rt)\n   | CCheckType (cs, cb) => String.append \"cchecktype \" (strCCArgs cs cb)\n   | CClearTag (cd, cb) => String.append \"ccleartag \" (strCCArgs cd cb)\n   | CMove (cd, cs) => String.append \"cmove \" (strCCArgs cd cs)\n   | CJALR (cd, cb, true) => String.append \"cjalr \" (strCCArgs cd cb)\n   | CSealEntry (cd, cb) => String.append \"csealentry \" (strCCArgs cd cb)\n   | CLoadTags (rd, cb) => String.append \"cloadtags \" (strRCArgs rd cb)\n   | CGetPerm (rd, cb) => String.append \"cgetperm \" (strRCArgs rd cb)\n   | CGetType (rd, cb) => String.append \"cgettype \" (strRCArgs rd cb)\n   | CGetBase (rd, cb) => String.append \"cgetbase \" (strRCArgs rd cb)\n   | CGetLen (rd, cb) => String.append \"cgetlen \" (strRCArgs rd cb)\n   | CGetTag (rd, cb) => String.append \"cgettag \" (strRCArgs rd cb)\n   | CGetSealed (rd, cb) => String.append \"cgetsealed \" (strRCArgs rd cb)\n   | CGetOffset (rd, cb) => String.append \"cgetoffset \" (strRCArgs rd cb)\n   | CGetPCCSetOffset (cd, rs) => String.append \"cgetpccsetoffset \" (strCRArgs cd rs)\n   | CReadHwr (cd, sel) => String.append \"creadhwr \" (strCRArgs cd sel)\n   | CWriteHwr (cb, sel) => String.append \"cwritehwr \" (strCRArgs cb sel)\n   | CGetAddr (rd, cb) => String.append \"cgetaddr \" (strRCArgs rd cb)\n   | CGetFlags (rd, cb) => String.append \"cgetflags \" (strRCArgs rd cb)\n   | CGetPCCIncOffset (cd, rs) => String.append \"cgetpccincoffset \" (strCRArgs cd rs)\n   | CGetPCCSetAddr (cd, rs) => String.append \"cgetpccsetaddr \" (strCRArgs cd rs)\n   | CRAP (rt, rs) => String.append \"crrl \" (strRRArgs rt rs)\n   | CRAM (rt, rs) => String.append \"cram \" (strRRArgs rt rs)\n   | CSeal (cd, cs, ct) => String.append \"cseal \" (strCCCArgs cd cs ct)\n   | CUnseal (cd, cs, ct) => String.append \"cunseal \" (strCCCArgs cd cs ct)\n   | CAndPerm (cd, cs, rt) => String.append \"candperm \" (strCCRArgs cd cs rt)\n   | CSetOffset (cd, cs, rt) => String.append \"csetoffset \" (strCCRArgs cd cs rt)\n   | CSetBounds (cd, cs, rt) => String.append \"csetbounds \" (strCCRArgs cd cs rt)\n   | CSetBoundsExact (cd, cs, rt) => String.append \"csetboundsexact \" (strCCRArgs cd cs rt)\n   | CSetFlags (cd, cs, rt) => String.append \"csetflags \" (strCCRArgs cd cs rt)\n   | CIncOffset (cd, cs, rt) => String.append \"cincoffset \" (strCCRArgs cd cs rt)\n   | CBuildCap (cd, cs, ct) => String.append \"cbuildcap \" (strCCCArgs cd cs ct)\n   | CCopyType (cd, cs, ct) => String.append \"ccopytype \" (strCCCArgs cd cs ct)\n   | CCSeal (cd, cs, ct) => String.append \"ccseal \" (strCCCArgs cd cs ct)\n   | CToPtr (rd, cb, ct) => String.append \"ctoptr \" (strRCRArgs rd cb ct)\n   | CFromPtr (cd, cb, rs) => String.append \"cfromptr \" (strCCRArgs cd cb rs)\n   | CSub (rt, cb, cs) => String.append \"csub \" (strRCCArgs rt cb cs)\n   | CMOVX (cd, cs, rs, false) => String.append \"cmovz \" (strCCRArgs cd cs rs)\n   | CMOVX (cd, cs, rs, true) => String.append \"cmovn \" (strCCRArgs cd cs rs)\n   | CSetAddr (cd, cs, rt) => String.append \"csetaddr \" (strCCRArgs cd cs rt)\n   | CGetAndAddr (rd, cs, rs) => String.append \"cgetandaddr \" (strRCRArgs rd cs rs)\n   | CAndAddr (cd, cs, rt) => String.append \"candaddr \" (strCCRArgs cd cs rt)\n   | CReturn tt => \"creturn\"\n   | CCall (cs, cb, selector) => String.append \"ccall \" (strCCIUArgs cs cb selector)\n   | CIncOffsetImmediate (cd, cb, imm) => String.append \"cincoffsetimm \" (strCCIArgs cd cb imm)\n   | CSetBoundsImmediate (cd, cb, imm) => String.append \"csetboundsimm \" (strCCIUArgs cd cb imm)\n   | RI tt => \"reserved instruction\"\n   | _ => \"assembly unimplemented\"\n   end.\n\nDefinition supported_instructions (instr : ast) : option ast := Some instr.\n\nDefinition initialize_registers '(tt : unit) : M (unit) :=\n   (undefined_bitvector 64) >>= fun w__0 : mword 64 =>\n   write_reg PC_ref w__0 >>\n   (undefined_bitvector 64) >>= fun w__1 : mword 64 =>\n   write_reg NextPC_ref w__1 >>\n   (undefined_bitvector 1) >>= fun w__2 : mword 1 =>\n   write_reg TLBProbe_ref w__2 >>\n   (undefined_bitvector 6) >>= fun w__3 : mword 6 =>\n   write_reg TLBIndex_ref w__3 >>\n   (undefined_bitvector 6) >>= fun w__4 : mword 6 =>\n   write_reg TLBRandom_ref w__4 >>\n   (undefined_TLBEntryLoReg tt) >>= fun w__5 : TLBEntryLoReg =>\n   write_reg TLBEntryLo0_ref w__5 >>\n   (undefined_TLBEntryLoReg tt) >>= fun w__6 : TLBEntryLoReg =>\n   write_reg TLBEntryLo1_ref w__6 >>\n   (undefined_ContextReg tt) >>= fun w__7 : ContextReg =>\n   write_reg TLBContext_ref w__7 >>\n   (undefined_bitvector 16) >>= fun w__8 : mword 16 =>\n   write_reg TLBPageMask_ref w__8 >>\n   (undefined_bitvector 6) >>= fun w__9 : mword 6 =>\n   write_reg TLBWired_ref w__9 >>\n   (undefined_TLBEntryHiReg tt) >>= fun w__10 : TLBEntryHiReg =>\n   write_reg TLBEntryHi_ref w__10 >>\n   (undefined_XContextReg tt) >>= fun w__11 : XContextReg =>\n   write_reg TLBXContext_ref w__11 >>\n   (undefined_TLBEntry tt) >>= fun w__12 : TLBEntry =>\n   write_reg TLBEntry00_ref w__12 >>\n   (undefined_TLBEntry tt) >>= fun w__13 : TLBEntry =>\n   write_reg TLBEntry01_ref w__13 >>\n   (undefined_TLBEntry tt) >>= fun w__14 : TLBEntry =>\n   write_reg TLBEntry02_ref w__14 >>\n   (undefined_TLBEntry tt) >>= fun w__15 : TLBEntry =>\n   write_reg TLBEntry03_ref w__15 >>\n   (undefined_TLBEntry tt) >>= fun w__16 : TLBEntry =>\n   write_reg TLBEntry04_ref w__16 >>\n   (undefined_TLBEntry tt) >>= fun w__17 : TLBEntry =>\n   write_reg TLBEntry05_ref w__17 >>\n   (undefined_TLBEntry tt) >>= fun w__18 : TLBEntry =>\n   write_reg TLBEntry06_ref w__18 >>\n   (undefined_TLBEntry tt) >>= fun w__19 : TLBEntry =>\n   write_reg TLBEntry07_ref w__19 >>\n   (undefined_TLBEntry tt) >>= fun w__20 : TLBEntry =>\n   write_reg TLBEntry08_ref w__20 >>\n   (undefined_TLBEntry tt) >>= fun w__21 : TLBEntry =>\n   write_reg TLBEntry09_ref w__21 >>\n   (undefined_TLBEntry tt) >>= fun w__22 : TLBEntry =>\n   write_reg TLBEntry10_ref w__22 >>\n   (undefined_TLBEntry tt) >>= fun w__23 : TLBEntry =>\n   write_reg TLBEntry11_ref w__23 >>\n   (undefined_TLBEntry tt) >>= fun w__24 : TLBEntry =>\n   write_reg TLBEntry12_ref w__24 >>\n   (undefined_TLBEntry tt) >>= fun w__25 : TLBEntry =>\n   write_reg TLBEntry13_ref w__25 >>\n   (undefined_TLBEntry tt) >>= fun w__26 : TLBEntry =>\n   write_reg TLBEntry14_ref w__26 >>\n   (undefined_TLBEntry tt) >>= fun w__27 : TLBEntry =>\n   write_reg TLBEntry15_ref w__27 >>\n   (undefined_TLBEntry tt) >>= fun w__28 : TLBEntry =>\n   write_reg TLBEntry16_ref w__28 >>\n   (undefined_TLBEntry tt) >>= fun w__29 : TLBEntry =>\n   write_reg TLBEntry17_ref w__29 >>\n   (undefined_TLBEntry tt) >>= fun w__30 : TLBEntry =>\n   write_reg TLBEntry18_ref w__30 >>\n   (undefined_TLBEntry tt) >>= fun w__31 : TLBEntry =>\n   write_reg TLBEntry19_ref w__31 >>\n   (undefined_TLBEntry tt) >>= fun w__32 : TLBEntry =>\n   write_reg TLBEntry20_ref w__32 >>\n   (undefined_TLBEntry tt) >>= fun w__33 : TLBEntry =>\n   write_reg TLBEntry21_ref w__33 >>\n   (undefined_TLBEntry tt) >>= fun w__34 : TLBEntry =>\n   write_reg TLBEntry22_ref w__34 >>\n   (undefined_TLBEntry tt) >>= fun w__35 : TLBEntry =>\n   write_reg TLBEntry23_ref w__35 >>\n   (undefined_TLBEntry tt) >>= fun w__36 : TLBEntry =>\n   write_reg TLBEntry24_ref w__36 >>\n   (undefined_TLBEntry tt) >>= fun w__37 : TLBEntry =>\n   write_reg TLBEntry25_ref w__37 >>\n   (undefined_TLBEntry tt) >>= fun w__38 : TLBEntry =>\n   write_reg TLBEntry26_ref w__38 >>\n   (undefined_TLBEntry tt) >>= fun w__39 : TLBEntry =>\n   write_reg TLBEntry27_ref w__39 >>\n   (undefined_TLBEntry tt) >>= fun w__40 : TLBEntry =>\n   write_reg TLBEntry28_ref w__40 >>\n   (undefined_TLBEntry tt) >>= fun w__41 : TLBEntry =>\n   write_reg TLBEntry29_ref w__41 >>\n   (undefined_TLBEntry tt) >>= fun w__42 : TLBEntry =>\n   write_reg TLBEntry30_ref w__42 >>\n   (undefined_TLBEntry tt) >>= fun w__43 : TLBEntry =>\n   write_reg TLBEntry31_ref w__43 >>\n   (undefined_TLBEntry tt) >>= fun w__44 : TLBEntry =>\n   write_reg TLBEntry32_ref w__44 >>\n   (undefined_TLBEntry tt) >>= fun w__45 : TLBEntry =>\n   write_reg TLBEntry33_ref w__45 >>\n   (undefined_TLBEntry tt) >>= fun w__46 : TLBEntry =>\n   write_reg TLBEntry34_ref w__46 >>\n   (undefined_TLBEntry tt) >>= fun w__47 : TLBEntry =>\n   write_reg TLBEntry35_ref w__47 >>\n   (undefined_TLBEntry tt) >>= fun w__48 : TLBEntry =>\n   write_reg TLBEntry36_ref w__48 >>\n   (undefined_TLBEntry tt) >>= fun w__49 : TLBEntry =>\n   write_reg TLBEntry37_ref w__49 >>\n   (undefined_TLBEntry tt) >>= fun w__50 : TLBEntry =>\n   write_reg TLBEntry38_ref w__50 >>\n   (undefined_TLBEntry tt) >>= fun w__51 : TLBEntry =>\n   write_reg TLBEntry39_ref w__51 >>\n   (undefined_TLBEntry tt) >>= fun w__52 : TLBEntry =>\n   write_reg TLBEntry40_ref w__52 >>\n   (undefined_TLBEntry tt) >>= fun w__53 : TLBEntry =>\n   write_reg TLBEntry41_ref w__53 >>\n   (undefined_TLBEntry tt) >>= fun w__54 : TLBEntry =>\n   write_reg TLBEntry42_ref w__54 >>\n   (undefined_TLBEntry tt) >>= fun w__55 : TLBEntry =>\n   write_reg TLBEntry43_ref w__55 >>\n   (undefined_TLBEntry tt) >>= fun w__56 : TLBEntry =>\n   write_reg TLBEntry44_ref w__56 >>\n   (undefined_TLBEntry tt) >>= fun w__57 : TLBEntry =>\n   write_reg TLBEntry45_ref w__57 >>\n   (undefined_TLBEntry tt) >>= fun w__58 : TLBEntry =>\n   write_reg TLBEntry46_ref w__58 >>\n   (undefined_TLBEntry tt) >>= fun w__59 : TLBEntry =>\n   write_reg TLBEntry47_ref w__59 >>\n   (undefined_TLBEntry tt) >>= fun w__60 : TLBEntry =>\n   write_reg TLBEntry48_ref w__60 >>\n   (undefined_TLBEntry tt) >>= fun w__61 : TLBEntry =>\n   write_reg TLBEntry49_ref w__61 >>\n   (undefined_TLBEntry tt) >>= fun w__62 : TLBEntry =>\n   write_reg TLBEntry50_ref w__62 >>\n   (undefined_TLBEntry tt) >>= fun w__63 : TLBEntry =>\n   write_reg TLBEntry51_ref w__63 >>\n   (undefined_TLBEntry tt) >>= fun w__64 : TLBEntry =>\n   write_reg TLBEntry52_ref w__64 >>\n   (undefined_TLBEntry tt) >>= fun w__65 : TLBEntry =>\n   write_reg TLBEntry53_ref w__65 >>\n   (undefined_TLBEntry tt) >>= fun w__66 : TLBEntry =>\n   write_reg TLBEntry54_ref w__66 >>\n   (undefined_TLBEntry tt) >>= fun w__67 : TLBEntry =>\n   write_reg TLBEntry55_ref w__67 >>\n   (undefined_TLBEntry tt) >>= fun w__68 : TLBEntry =>\n   write_reg TLBEntry56_ref w__68 >>\n   (undefined_TLBEntry tt) >>= fun w__69 : TLBEntry =>\n   write_reg TLBEntry57_ref w__69 >>\n   (undefined_TLBEntry tt) >>= fun w__70 : TLBEntry =>\n   write_reg TLBEntry58_ref w__70 >>\n   (undefined_TLBEntry tt) >>= fun w__71 : TLBEntry =>\n   write_reg TLBEntry59_ref w__71 >>\n   (undefined_TLBEntry tt) >>= fun w__72 : TLBEntry =>\n   write_reg TLBEntry60_ref w__72 >>\n   (undefined_TLBEntry tt) >>= fun w__73 : TLBEntry =>\n   write_reg TLBEntry61_ref w__73 >>\n   (undefined_TLBEntry tt) >>= fun w__74 : TLBEntry =>\n   write_reg TLBEntry62_ref w__74 >>\n   (undefined_TLBEntry tt) >>= fun w__75 : TLBEntry =>\n   write_reg TLBEntry63_ref w__75 >>\n   (undefined_bitvector 32) >>= fun w__76 : mword 32 =>\n   write_reg CP0Compare_ref w__76 >>\n   (undefined_CauseReg tt) >>= fun w__77 : CauseReg =>\n   write_reg CP0Cause_ref w__77 >>\n   (undefined_bitvector 1) >>= fun w__78 : mword 1 =>\n   write_reg CP0LLBit_ref w__78 >>\n   (undefined_bitvector 64) >>= fun w__79 : mword 64 =>\n   write_reg CP0LLAddr_ref w__79 >>\n   (undefined_bitvector 64) >>= fun w__80 : mword 64 =>\n   write_reg CP0BadVAddr_ref w__80 >>\n   (undefined_bitvector 32) >>= fun w__81 : mword 32 =>\n   write_reg CurrentInstrBits_ref w__81 >>\n   (undefined_bitvector 32) >>= fun w__82 : mword 32 =>\n   write_reg LastInstrBits_ref w__82 >>\n   (undefined_bitvector 32) >>= fun w__83 : mword 32 =>\n   write_reg CP0BadInstr_ref w__83 >>\n   (undefined_bitvector 32) >>= fun w__84 : mword 32 =>\n   write_reg CP0BadInstrP_ref w__84 >>\n   (undefined_bitvector 32) >>= fun w__85 : mword 32 =>\n   write_reg CP0Count_ref w__85 >>\n   (undefined_bitvector 32) >>= fun w__86 : mword 32 =>\n   write_reg CP0HWREna_ref w__86 >>\n   (undefined_bitvector 64) >>= fun w__87 : mword 64 =>\n   write_reg CP0UserLocal_ref w__87 >>\n   (undefined_bitvector 3) >>= fun w__88 : mword 3 =>\n   write_reg CP0ConfigK0_ref w__88 >>\n   (undefined_StatusReg tt) >>= fun w__89 : StatusReg =>\n   write_reg CP0Status_ref w__89 >>\n   (undefined_bitvector 1) >>= fun w__90 : mword 1 =>\n   write_reg NextInBranchDelay_ref w__90 >>\n   (undefined_bitvector 1) >>= fun w__91 : mword 1 =>\n   write_reg InBranchDelay_ref w__91 >>\n   (undefined_bitvector 1) >>= fun w__92 : mword 1 =>\n   write_reg BranchPending_ref w__92 >>\n   (undefined_bitvector 64) >>= fun w__93 : mword 64 =>\n   write_reg DelayedPC_ref w__93 >>\n   (undefined_bitvector 64) >>= fun w__94 : mword 64 =>\n   write_reg HI_ref w__94 >>\n   (undefined_bitvector 64) >>= fun w__95 : mword 64 =>\n   write_reg LO_ref w__95 >>\n   (undefined_bitvector 64) >>= fun w__96 : mword 64 =>\n   (undefined_vector 32 w__96) >>= fun w__97 : vec (mword 64) 32 =>\n   write_reg GPR_ref w__97 >>\n   (undefined_bitvector 8) >>= fun w__98 : mword 8 =>\n   write_reg UART_WDATA_ref w__98 >>\n   (undefined_bitvector 1) >>= fun w__99 : mword 1 =>\n   write_reg UART_WRITTEN_ref w__99 >>\n   (undefined_bitvector 8) >>= fun w__100 : mword 8 =>\n   write_reg UART_RDATA_ref w__100 >>\n   (undefined_bitvector 1) >>= fun w__101 : mword 1 =>\n   write_reg UART_RVALID_ref w__101 >>\n   (undefined_Capability tt) >>= fun w__102 : Capability =>\n   write_reg PCC_ref w__102 >>\n   (undefined_Capability tt) >>= fun w__103 : Capability =>\n   write_reg NextPCC_ref w__103 >>\n   (undefined_Capability tt) >>= fun w__104 : Capability =>\n   write_reg DelayedPCC_ref w__104 >>\n   (undefined_Capability tt) >>= fun w__105 : Capability =>\n   write_reg DDC_ref w__105 >>\n   (undefined_Capability tt) >>= fun w__106 : Capability =>\n   write_reg C01_ref w__106 >>\n   (undefined_Capability tt) >>= fun w__107 : Capability =>\n   write_reg C02_ref w__107 >>\n   (undefined_Capability tt) >>= fun w__108 : Capability =>\n   write_reg C03_ref w__108 >>\n   (undefined_Capability tt) >>= fun w__109 : Capability =>\n   write_reg C04_ref w__109 >>\n   (undefined_Capability tt) >>= fun w__110 : Capability =>\n   write_reg C05_ref w__110 >>\n   (undefined_Capability tt) >>= fun w__111 : Capability =>\n   write_reg C06_ref w__111 >>\n   (undefined_Capability tt) >>= fun w__112 : Capability =>\n   write_reg C07_ref w__112 >>\n   (undefined_Capability tt) >>= fun w__113 : Capability =>\n   write_reg C08_ref w__113 >>\n   (undefined_Capability tt) >>= fun w__114 : Capability =>\n   write_reg C09_ref w__114 >>\n   (undefined_Capability tt) >>= fun w__115 : Capability =>\n   write_reg C10_ref w__115 >>\n   (undefined_Capability tt) >>= fun w__116 : Capability =>\n   write_reg C11_ref w__116 >>\n   (undefined_Capability tt) >>= fun w__117 : Capability =>\n   write_reg C12_ref w__117 >>\n   (undefined_Capability tt) >>= fun w__118 : Capability =>\n   write_reg C13_ref w__118 >>\n   (undefined_Capability tt) >>= fun w__119 : Capability =>\n   write_reg C14_ref w__119 >>\n   (undefined_Capability tt) >>= fun w__120 : Capability =>\n   write_reg C15_ref w__120 >>\n   (undefined_Capability tt) >>= fun w__121 : Capability =>\n   write_reg C16_ref w__121 >>\n   (undefined_Capability tt) >>= fun w__122 : Capability =>\n   write_reg C17_ref w__122 >>\n   (undefined_Capability tt) >>= fun w__123 : Capability =>\n   write_reg C18_ref w__123 >>\n   (undefined_Capability tt) >>= fun w__124 : Capability =>\n   write_reg C19_ref w__124 >>\n   (undefined_Capability tt) >>= fun w__125 : Capability =>\n   write_reg C20_ref w__125 >>\n   (undefined_Capability tt) >>= fun w__126 : Capability =>\n   write_reg C21_ref w__126 >>\n   (undefined_Capability tt) >>= fun w__127 : Capability =>\n   write_reg C22_ref w__127 >>\n   (undefined_Capability tt) >>= fun w__128 : Capability =>\n   write_reg C23_ref w__128 >>\n   (undefined_Capability tt) >>= fun w__129 : Capability =>\n   write_reg C24_ref w__129 >>\n   (undefined_Capability tt) >>= fun w__130 : Capability =>\n   write_reg C25_ref w__130 >>\n   (undefined_Capability tt) >>= fun w__131 : Capability =>\n   write_reg C26_ref w__131 >>\n   (undefined_Capability tt) >>= fun w__132 : Capability =>\n   write_reg C27_ref w__132 >>\n   (undefined_Capability tt) >>= fun w__133 : Capability =>\n   write_reg C28_ref w__133 >>\n   (undefined_Capability tt) >>= fun w__134 : Capability =>\n   write_reg C29_ref w__134 >>\n   (undefined_Capability tt) >>= fun w__135 : Capability =>\n   write_reg C30_ref w__135 >>\n   (undefined_Capability tt) >>= fun w__136 : Capability =>\n   write_reg C31_ref w__136 >>\n   (undefined_Capability tt) >>= fun w__137 : Capability =>\n   write_reg CULR_ref w__137 >>\n   (undefined_Capability tt) >>= fun w__138 : Capability =>\n   write_reg CPLR_ref w__138 >>\n   (undefined_Capability tt) >>= fun w__139 : Capability =>\n   write_reg KR1C_ref w__139 >>\n   (undefined_Capability tt) >>= fun w__140 : Capability =>\n   write_reg KR2C_ref w__140 >>\n   (undefined_Capability tt) >>= fun w__141 : Capability =>\n   write_reg KCC_ref w__141 >>\n   (undefined_Capability tt) >>= fun w__142 : Capability =>\n   write_reg KDC_ref w__142 >>\n   (undefined_Capability tt) >>= fun w__143 : Capability =>\n   write_reg EPCC_ref w__143 >>\n   (undefined_Capability tt) >>= fun w__144 : Capability =>\n   write_reg ErrorEPCC_ref w__144 >>\n   (undefined_CapCauseReg tt) >>= fun w__145 : CapCauseReg =>\n   write_reg CapCause_ref w__145 >>\n   (undefined_bitvector 64) >>= fun w__146 : mword 64 => write_reg CID_ref w__146  : M (unit).\n\nDefinition initial_CauseReg : CauseReg :=\n{| CauseReg_CauseReg_chunk_0 := (Ox\"00000000\"  : mword 32) |}.\nHint Unfold initial_CauseReg : sail.\nDefinition initial_TLBEntryLoReg : TLBEntryLoReg :=\n{| TLBEntryLoReg_TLBEntryLoReg_chunk_0 := (Ox\"0000000000000000\"  : mword 64) |}.\nHint Unfold initial_TLBEntryLoReg : sail.\nDefinition initial_TLBEntryHiReg : TLBEntryHiReg :=\n{| TLBEntryHiReg_TLBEntryHiReg_chunk_0 := (Ox\"0000000000000000\"  : mword 64) |}.\nHint Unfold initial_TLBEntryHiReg : sail.\nDefinition initial_ContextReg : ContextReg :=\n{| ContextReg_ContextReg_chunk_0 := (Ox\"0000000000000000\"  : mword 64) |}.\nHint Unfold initial_ContextReg : sail.\nDefinition initial_XContextReg : XContextReg :=\n{| XContextReg_XContextReg_chunk_0 := (Ox\"0000000000000000\"  : mword 64) |}.\nHint Unfold initial_XContextReg : sail.\nDefinition initial_TLBEntry : TLBEntry :=\n{| TLBEntry_TLBEntry_chunk_1 :=\n     ('b\"0000000000000000000000000000000000000000000000000000000\"\n      : mword 55); \n   TLBEntry_TLBEntry_chunk_0 := (Ox\"0000000000000000\"  : mword 64) |}.\nHint Unfold initial_TLBEntry : sail.\nDefinition initial_StatusReg : StatusReg :=\n{| StatusReg_StatusReg_chunk_0 := (Ox\"00000000\"  : mword 32) |}.\nHint Unfold initial_StatusReg : sail.\nDefinition initial_Capability : Capability :=\n{| Capability_tag := false; \n   Capability_uperms := (Ox\"0\"  : mword 4); \n   Capability_permit_set_CID := false; \n   Capability_access_system_regs := false; \n   Capability_permit_unseal := false; \n   Capability_permit_ccall := false; \n   Capability_permit_seal := false; \n   Capability_permit_store_local_cap := false; \n   Capability_permit_store_cap := false; \n   Capability_permit_load_cap := false; \n   Capability_permit_store := false; \n   Capability_permit_load := false; \n   Capability_permit_execute := false; \n   Capability_global := false; \n   Capability_reserved := ('b\"000\"  : mword 3); \n   Capability_internal_e := false; \n   Capability_E := ('b\"000000\"  : mword 6); \n   Capability_sealed := false; \n   Capability_B := ('b\"00000000000000\"  : mword 14); \n   Capability_T := ('b\"00000000000000\"  : mword 14); \n   Capability_otype := ('b\"000000000000000000\"  : mword 18); \n   Capability_address := (Ox\"0000000000000000\"  : mword 64) |}.\nHint Unfold initial_Capability : sail.\nDefinition initial_CapCauseReg : CapCauseReg :=\n{| CapCauseReg_CapCauseReg_chunk_0 := (Ox\"0000\"  : mword 16) |}.\nHint Unfold initial_CapCauseReg : sail.\nDefinition initial_regstate : regstate :=\n{| CID := (Ox\"0000000000000000\"  : mword 64); \n   CapCause := initial_CapCauseReg; \n   ErrorEPCC := initial_Capability; \n   EPCC := initial_Capability; \n   KDC := initial_Capability; \n   KCC := initial_Capability; \n   KR2C := initial_Capability; \n   KR1C := initial_Capability; \n   CPLR := initial_Capability; \n   CULR := initial_Capability; \n   C31 := initial_Capability; \n   C30 := initial_Capability; \n   C29 := initial_Capability; \n   C28 := initial_Capability; \n   C27 := initial_Capability; \n   C26 := initial_Capability; \n   C25 := initial_Capability; \n   C24 := initial_Capability; \n   C23 := initial_Capability; \n   C22 := initial_Capability; \n   C21 := initial_Capability; \n   C20 := initial_Capability; \n   C19 := initial_Capability; \n   C18 := initial_Capability; \n   C17 := initial_Capability; \n   C16 := initial_Capability; \n   C15 := initial_Capability; \n   C14 := initial_Capability; \n   C13 := initial_Capability; \n   C12 := initial_Capability; \n   C11 := initial_Capability; \n   C10 := initial_Capability; \n   C09 := initial_Capability; \n   C08 := initial_Capability; \n   C07 := initial_Capability; \n   C06 := initial_Capability; \n   C05 := initial_Capability; \n   C04 := initial_Capability; \n   C03 := initial_Capability; \n   C02 := initial_Capability; \n   C01 := initial_Capability; \n   DDC := initial_Capability; \n   DelayedPCC := initial_Capability; \n   NextPCC := initial_Capability; \n   PCC := initial_Capability; \n   UART_RVALID := ('b\"0\"  : mword 1); \n   UART_RDATA := (Ox\"00\"  : mword 8); \n   UART_WRITTEN := ('b\"0\"  : mword 1); \n   UART_WDATA := (Ox\"00\"  : mword 8); \n   GPR :=\n     (vec_of_list_len [Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64]); \n   LO := (Ox\"0000000000000000\"  : mword 64); \n   HI := (Ox\"0000000000000000\"  : mword 64); \n   DelayedPC := (Ox\"0000000000000000\"  : mword 64); \n   BranchPending := ('b\"0\"  : mword 1); \n   InBranchDelay := ('b\"0\"  : mword 1); \n   NextInBranchDelay := ('b\"0\"  : mword 1); \n   CP0Status := initial_StatusReg; \n   CP0ConfigK0 := ('b\"000\"  : mword 3); \n   CP0UserLocal := (Ox\"0000000000000000\"  : mword 64); \n   CP0HWREna := (Ox\"00000000\"  : mword 32); \n   CP0Count := (Ox\"00000000\"  : mword 32); \n   CP0BadInstrP := (Ox\"00000000\"  : mword 32); \n   CP0BadInstr := (Ox\"00000000\"  : mword 32); \n   LastInstrBits := (Ox\"00000000\"  : mword 32); \n   CurrentInstrBits := (Ox\"00000000\"  : mword 32); \n   CP0BadVAddr := (Ox\"0000000000000000\"  : mword 64); \n   CP0LLAddr := (Ox\"0000000000000000\"  : mword 64); \n   CP0LLBit := ('b\"0\"  : mword 1); \n   CP0Cause := initial_CauseReg; \n   CP0Compare := (Ox\"00000000\"  : mword 32); \n   TLBEntry63 := initial_TLBEntry; \n   TLBEntry62 := initial_TLBEntry; \n   TLBEntry61 := initial_TLBEntry; \n   TLBEntry60 := initial_TLBEntry; \n   TLBEntry59 := initial_TLBEntry; \n   TLBEntry58 := initial_TLBEntry; \n   TLBEntry57 := initial_TLBEntry; \n   TLBEntry56 := initial_TLBEntry; \n   TLBEntry55 := initial_TLBEntry; \n   TLBEntry54 := initial_TLBEntry; \n   TLBEntry53 := initial_TLBEntry; \n   TLBEntry52 := initial_TLBEntry; \n   TLBEntry51 := initial_TLBEntry; \n   TLBEntry50 := initial_TLBEntry; \n   TLBEntry49 := initial_TLBEntry; \n   TLBEntry48 := initial_TLBEntry; \n   TLBEntry47 := initial_TLBEntry; \n   TLBEntry46 := initial_TLBEntry; \n   TLBEntry45 := initial_TLBEntry; \n   TLBEntry44 := initial_TLBEntry; \n   TLBEntry43 := initial_TLBEntry; \n   TLBEntry42 := initial_TLBEntry; \n   TLBEntry41 := initial_TLBEntry; \n   TLBEntry40 := initial_TLBEntry; \n   TLBEntry39 := initial_TLBEntry; \n   TLBEntry38 := initial_TLBEntry; \n   TLBEntry37 := initial_TLBEntry; \n   TLBEntry36 := initial_TLBEntry; \n   TLBEntry35 := initial_TLBEntry; \n   TLBEntry34 := initial_TLBEntry; \n   TLBEntry33 := initial_TLBEntry; \n   TLBEntry32 := initial_TLBEntry; \n   TLBEntry31 := initial_TLBEntry; \n   TLBEntry30 := initial_TLBEntry; \n   TLBEntry29 := initial_TLBEntry; \n   TLBEntry28 := initial_TLBEntry; \n   TLBEntry27 := initial_TLBEntry; \n   TLBEntry26 := initial_TLBEntry; \n   TLBEntry25 := initial_TLBEntry; \n   TLBEntry24 := initial_TLBEntry; \n   TLBEntry23 := initial_TLBEntry; \n   TLBEntry22 := initial_TLBEntry; \n   TLBEntry21 := initial_TLBEntry; \n   TLBEntry20 := initial_TLBEntry; \n   TLBEntry19 := initial_TLBEntry; \n   TLBEntry18 := initial_TLBEntry; \n   TLBEntry17 := initial_TLBEntry; \n   TLBEntry16 := initial_TLBEntry; \n   TLBEntry15 := initial_TLBEntry; \n   TLBEntry14 := initial_TLBEntry; \n   TLBEntry13 := initial_TLBEntry; \n   TLBEntry12 := initial_TLBEntry; \n   TLBEntry11 := initial_TLBEntry; \n   TLBEntry10 := initial_TLBEntry; \n   TLBEntry09 := initial_TLBEntry; \n   TLBEntry08 := initial_TLBEntry; \n   TLBEntry07 := initial_TLBEntry; \n   TLBEntry06 := initial_TLBEntry; \n   TLBEntry05 := initial_TLBEntry; \n   TLBEntry04 := initial_TLBEntry; \n   TLBEntry03 := initial_TLBEntry; \n   TLBEntry02 := initial_TLBEntry; \n   TLBEntry01 := initial_TLBEntry; \n   TLBEntry00 := initial_TLBEntry; \n   TLBXContext := initial_XContextReg; \n   TLBEntryHi := initial_TLBEntryHiReg; \n   TLBWired := ('b\"000000\"  : mword 6); \n   TLBPageMask := (Ox\"0000\"  : mword 16); \n   TLBContext := initial_ContextReg; \n   TLBEntryLo1 := initial_TLBEntryLoReg; \n   TLBEntryLo0 := initial_TLBEntryLoReg; \n   TLBRandom := ('b\"000000\"  : mword 6); \n   TLBIndex := ('b\"000000\"  : mword 6); \n   TLBProbe := ('b\"0\"  : mword 1); \n   NextPC := (Ox\"0000000000000000\"  : mword 64); \n   PC := (Ox\"0000000000000000\"  : mword 64) |}.\nHint Unfold initial_regstate : sail.\n\n\n", "meta": {"author": "CTSRD-CHERI", "repo": "sail-cheri-mips", "sha": "13a9c3fb0c3f8d320d4f4650a63d23d3a8b12724", "save_path": "github-repos/coq/CTSRD-CHERI-sail-cheri-mips", "path": "github-repos/coq/CTSRD-CHERI-sail-cheri-mips/sail-cheri-mips-13a9c3fb0c3f8d320d4f4650a63d23d3a8b12724/prover_snapshots/coq/cheri-mips-snapshot/cheri128.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24814767367911217}}
{"text": "Require Import Strings.String.\nLocal Open Scope string_scope.\nLocal Open Scope list_scope.\nScheme Equality for string.\n\n(*--------------- TIPURI DE DATE ---------------*)\n\nInductive ErrorNat :=\n  | error_nat : ErrorNat\n  | num : nat -> ErrorNat.\n\nCoercion num: nat >-> ErrorNat.\n\nCheck num 3.\n\nInductive ErrorBool :=\n  | error_bool : ErrorBool\n  | boolean : bool -> ErrorBool.\n\nCoercion boolean: bool >-> ErrorBool.\n\nCheck boolean true.\n\nInductive ErrorString :=\n  | error_string : ErrorString\n  | Sstring : string -> ErrorString.\n\nCoercion Sstring: string >-> ErrorString.\n\nCheck Sstring \"PLP\".\n\nInductive ErrorPtr :=\n  | error_ptr : ErrorPtr\n  | ptr : string -> ErrorPtr.\n\nCheck ptr \"x\".\n\nInductive ErrorRef :=\n  | error_ref : ErrorRef\n  | ref : string -> ErrorRef.\n\nCheck ref \"y\".\n\n(*--------------- END TIPURI DE DATE ---------------*)\n\n(*Cele 2 tipuri de date, semantic, vor prelua offset-ul variabilelor asignate*)\n\n(*--------------- STRUCT-URI ---------------*)\n\nInductive FieldValues :=\n| nat_value : ErrorNat -> FieldValues\n| bool_value : ErrorBool -> FieldValues\n| ptr_value : ErrorPtr -> FieldValues\n| ref_value : ErrorRef -> FieldValues\n| string_value : ErrorString -> FieldValues.\n\nCoercion nat_value: ErrorNat >-> FieldValues.\nCoercion bool_value: ErrorBool >-> FieldValues.\nCoercion ptr_value: ErrorPtr >-> FieldValues.\nCoercion ref_value: ErrorRef >-> FieldValues.\nCoercion string_value: ErrorString >-> FieldValues.\n\nInductive Field :=\n| field : string -> FieldValues -> Field.\n\nCheck (field \"field1\" \"x\").\nCheck (field \"field1\" (ptr \"x\")).\n\nInductive Struct :=\n| struct: (list Field) -> Struct.\n\nCheck (struct ((field \"camp1\" 10) :: (field \"camp2\" \"text\") :: nil)).\n\nNotation \"'[[' L ']]'\" := (struct L) (at level 95).\n\nCheck ([[(field \"field1\" 2) :: (field \"field2\" \"txt\") :: nil]]).\n\n(*--------------- END STRUCT-URI ---------------*)\n\nInductive AExp :=\n  | avar: string -> AExp\n  | anum: ErrorNat -> AExp\n  | aplus: AExp -> AExp -> AExp\n  | asub: AExp -> AExp -> AExp\n  | amul: AExp -> AExp -> AExp\n  | adiv: AExp -> AExp -> AExp\n  | amod: AExp -> AExp -> AExp.\n\nCoercion avar: string >-> AExp.\nCoercion anum: ErrorNat >-> AExp.\n\nNotation \"A +' B\" := (aplus A B)(at level 50, left associativity).\nNotation \"A -' B\" := (asub A B)(at level 50, left associativity).\nNotation \"A *' B\" := (amul A B)(at level 48, left associativity).\nNotation \"A /' B\" := (adiv A B)(at level 48, left associativity).\nNotation \"A %' B\" := (amod A B)(at level 45, left associativity).\n\nInductive BExp :=\n  | berror\n  | btrue\n  | bfalse\n  | bvar: string -> BExp\n  | blt : AExp -> AExp -> BExp\n  | bnot : BExp -> BExp\n  | band : BExp -> BExp -> BExp\n  | bor : BExp -> BExp -> BExp.\n\nCoercion bvar: string >-> BExp.\n\nNotation \"A <' B\" := (blt A B) (at level 70).\nNotation \"!' A\" := (bnot A)(at level 51, left associativity).\nNotation \"A &&' B\" := (band A B)(at level 52, left associativity).\nNotation \"A ||' B\" := (bor A B)(at level 53, left associativity).\n\nInductive SExp :=\n  | svar : string -> SExp\n  | scat : SExp -> SExp -> SExp\n  | scpy : SExp -> SExp -> SExp\n  | slength : SExp -> nat -> SExp.\n\nCoercion svar: string >-> SExp.\n\nNotation \"A +s B\" := (scat A B) (at level 54,left associativity).\nNotation \"A +c B\" := (scpy A B) (at level 56, left associativity).\nNotation \"'len' A\" := (slength A) (at level 55).\n\n(* VALORILE DE RETURN ALE FUNCTIILOR*)\n\nInductive ReturnType :=\n  | void : ReturnType\n  | nat_return : ReturnType\n  | bool_return : ReturnType\n  | string_return : ReturnType.\n\n(* PAIR PENTRU SWITCH *)\n\nInductive Pair (T1 T2 : Type) :=\n  | pair (t1 : T1) (t2 : T2).\n\nInductive Stmt :=\n| int_decl: string -> Stmt\n| boolean_decl: string -> Stmt\n| ptr_decl: string -> Stmt\n| str_decl : string -> Stmt\n| structure_decl : string -> Stmt\n| assgn_ptr: string -> string -> Stmt\n| assgn_ref: string -> string -> Stmt\n| assgn_int : string -> AExp -> Stmt\n| assgn_bool : string -> BExp -> Stmt\n| assgn_string : string -> SExp -> Stmt\n| assgn_func : ReturnType -> string -> (list AExp) -> Stmt -> Stmt\n| assgn_struct : string -> Struct -> Stmt\n| getStructField : string -> string -> Stmt\n| setStructField : string -> string -> FieldValues -> Stmt\n| break : Stmt\n| continue : Stmt\n| switch_int : string -> list (Pair ErrorNat Stmt) -> Stmt\n| switch_bool : string -> list (Pair ErrorBool Stmt) -> Stmt\n| sequence : Stmt -> Stmt -> Stmt\n| while : BExp -> Stmt -> Stmt\n| ifthenelse : BExp -> Stmt -> Stmt -> Stmt\n| ifthen : BExp -> Stmt -> Stmt\n| forr : Stmt -> BExp -> Stmt -> Stmt -> Stmt.\n\n(*Un pointer poate fi declarat inainte de a fi initializat, insa o referinta nu*)\n\nNotation \"'int' X\" := (int_decl X) (at level 90).\nNotation \"'boolean' X\" := (boolean_decl X) (at level 90).\nNotation \"'str' X\" := (str_decl X) (at level 90).\nNotation \"'structure' X\" := (structure_decl X) (at level 90).\nNotation \"'*' X\" := (ptr_decl X) (at level 90).\nNotation \"X :n= A\" := (assgn_int X A) (at level 90).\nNotation \"X :b= A\" := (assgn_bool X A) (at level 90).\nNotation \"X :p= A\" := (assgn_ptr X A) (at level 90).\nNotation \"X :r= A\" := (assgn_ref X A) (at level 90).\nNotation \"X :s= A\" := (assgn_string X A) (at level 90).\nNotation \"X :struct= A\" := (assgn_struct X A) (at level 90).\nNotation \"S1 ;; S2\" := (sequence S1 S2) (at level 93, right associativity).\n\nReserved Notation \"A =[ S ]=> N\" (at level 60).\nReserved Notation \"B ={ S }=> B'\" (at level 70).\nReserved Notation \"B ={ S }=> B'\" (at level 70).\nReserved Notation \"S -{ Sigma }-> Sigma'\" (at level 60).\n\n(* --------------- RESULT ---------------*)\n\nInductive Result :=\n  | undecl : Result\n  | err_assign : Result\n  | nat_decl : Result\n  | bool_decl : Result\n  | func_decl : Result\n  | pointer_decl : Result\n  | string_decl : Result\n  | struct_decl : Result\n  | nat_val : ErrorNat -> Result\n  | bool_val : ErrorBool -> Result\n  | pointer_val : ErrorPtr -> Result\n  | ref_val : ErrorRef -> Result\n  | string_val : ErrorString -> Result\n  | struct_val : Struct -> Result\n  | func_val : Stmt -> Result.\n\nCoercion nat_val: ErrorNat >-> Result.\nCoercion bool_val: ErrorBool >-> Result.\nCoercion pointer_val: ErrorPtr >-> Result.\nCoercion ref_val: ErrorRef >-> Result.\nCoercion string_val: ErrorString >-> Result.\nCoercion struct_val : Struct >-> Result.\n\nDefinition check_eq_over_types (t1 : Result)(t2 : Result) : bool :=\n  match t1 with\n  | err_assign => match t2 with \n                   | err_assign => true\n                   | _ => false\n                   end\n  | undecl => match t2 with \n                   | undecl => true\n                   | _ => false\n                   end\n  | nat_decl => match t2 with \n                | nat_decl => true\n                | _ => false\n                end\n  | struct_decl => match t2 with \n                | struct_decl => true\n                | _ => false\n                end\n  | bool_decl => match t2 with \n                   | bool_decl => true\n                   | _ => false\n                   end\n  | func_decl => match t2 with \n                   | func_decl => true\n                   | _ => false\n                   end\n  | string_decl => match t2 with \n                   | string_decl => true\n                   | _ => false\n                   end\n  | pointer_decl => match t2 with \n                   | pointer_decl => true\n                   | _ => false\n                   end\n  | nat_val a => match t2 with \n                    | nat_val b => true\n                    | _ => false\n                    end\n  | bool_val a => match t2 with \n                    | bool_val b => true\n                    | _ => false\n                    end\n  | pointer_val a => match t2 with \n                    | pointer_val b => true\n                    | _ => false\n                    end\n  | ref_val a => match t2 with \n                    | ref_val b => true\n                    | _ => false\n                    end\n  | func_val a => match t2 with\n                | func_val b => true\n                | _ => false\n                end\n  | struct_val a => match t2 with\n                | struct_val b => true\n                | _ => false\n                end\n  | string_val a => match t2 with\n                | string_val b => true\n                | _ => false\n                end\n  end.\n\n(* --------------- END RESULT ---------------*)\n(* --------------- MEM + MEMLAYER (GLOBAL + BLANK) + ENV (GLOBAL + BLANK) + STACK(OF ENV) + CONFIG ---------------*)\n\nInductive Mem :=\n  | mem_default : Mem\n  | offset : nat -> Mem.\n\nScheme Equality for Mem.\n\nDefinition Env := string -> Mem.\n\nDefinition MemLayer := Mem -> Result.\n\nDefinition Stack := list Env.\n\nInductive Config :=\n  | config : nat -> Env -> MemLayer -> Stack -> Config.\n\nDefinition update_env (env: Env) (x: string) (n: Mem) : Env :=\n  fun y =>\n      if (andb (string_beq x y ) (Mem_beq (env y) mem_default))\n      then\n        n\n      else\n        (env y).\n\nDefinition env_global : Env :=\n  fun s =>\n    if(string_beq s \"x\")\n    then (offset 1)\n    else if(string_beq s \"y\") then (offset 2)\n      else mem_default.\n\nDefinition env_blank : Env :=\n  fun s => mem_default.\n\nCompute (env_global \"z\").\n\nCompute (update_env env_global \"z\" (offset 3)) \"z\".\n\nCompute (update_env env_global \"x\" (offset 3)) \"x\".\n\nDefinition update_mem (mem : MemLayer) (env : Env) (x : string) (type : Mem) (v : Result) : MemLayer :=\n  fun y =>\n    if (Mem_beq ((update_env env x type) x) y) then\n      match v with\n            | nat_decl => if(check_eq_over_types (mem type) undecl) then v else err_assign\n            | bool_decl => if(check_eq_over_types (mem type) undecl) then v else err_assign\n            | func_decl => if(check_eq_over_types (mem type) undecl) then v else err_assign\n            | pointer_decl => if(check_eq_over_types (mem type) undecl) then v else err_assign\n            | struct_decl => if(check_eq_over_types (mem type) undecl) then v else err_assign\n            | string_decl => if(check_eq_over_types (mem type) undecl) then v else err_assign\n            | nat_val a => match (mem type) with\n                            | nat_decl => v\n                            | nat_val b => v\n                            | _ => err_assign\n                           end\n            | ref_val a => match (mem type) with\n                            | undecl => v\n                            | _ => err_assign\n                           end\n            | bool_val a => match (mem type) with\n                            | bool_decl => v\n                            | bool_val b => v\n                            | _ => err_assign\n                           end\n            | func_val a => match (mem type) with\n                            | func_decl => v\n                            | func_val b => v\n                            | _ => err_assign\n                           end\n            | struct_val a => match (mem type) with\n                            | struct_decl => v\n                            | struct_val b => v\n                            | _ => err_assign\n                           end\n            | pointer_val a => match (mem type) with\n                            | pointer_decl => v\n                            | pointer_val b => v\n                            | _ => err_assign\n                           end\n            | string_val a => match (mem type) with\n                            | string_decl => v\n                            | string_val b => v\n                            | _ => err_assign\n                           end\n            | undecl => err_assign\n            | err_assign => v\n          end\n    else\n      (mem y).\n\nDefinition mem_global : MemLayer :=\n  fun s =>\n    if(Mem_beq s (offset 1)) then nat_decl\n    else if (Mem_beq s (offset 2)) then bool_decl\n      else undecl.\n\nDefinition mem_blank : MemLayer :=\n  fun s =>\n    if(Mem_beq s (offset 1)) then nat_decl\n    else if (Mem_beq s (offset 2)) then bool_decl\n      else undecl.\n\nCompute (mem_global (env_global \"x\")).\nCompute (mem_global (env_global \"y\")).\nCompute (mem_global (env_global \"z\")).\nCompute (update_mem mem_global env_global \"x\" (offset 1) (nat_val 3)) (offset 1).\nCompute (update_mem mem_global env_global \"y\" (offset 2) (bool_val true)) (offset 2).\nCompute (update_mem (update_mem mem_global env_global \"z\" (offset 3) bool_decl) env_global \"z\" (offset 3) (bool_val true)) (offset 3).\n\nDefinition update_conf (s : string) (conf : Config) (r : Result) : Config :=\nmatch conf with\n  | config nbr env mem stack =>\n      match r with\n        | func_val a => (config (nbr) (update_env env s (offset (nbr))) (update_mem mem (update_env env s (offset (nbr))) s (offset (nbr)) r) (env :: stack))\n        | nat_val a => (config (nbr) (update_env env s (offset (nbr))) (update_mem mem (update_env env s (offset (nbr))) s (offset (nbr)) r) stack)\n        | bool_val a => (config (nbr) (update_env env s (offset (nbr))) (update_mem mem (update_env env s (offset (nbr))) s (offset (nbr)) r) stack)\n        | struct_val a => (config (nbr) (update_env env s (offset (nbr))) (update_mem mem (update_env env s (offset (nbr))) s (offset (nbr)) r) stack)\n        | pointer_val a => (config (nbr) (update_env env s (offset (nbr))) (update_mem mem (update_env env s (offset (nbr))) s (offset (nbr)) r) stack)\n        | ref_val a => (config (nbr) (update_env env s (offset (nbr))) (update_mem mem (update_env env s (offset (nbr))) s (offset (nbr)) r) stack)\n        | _ => (config (nbr+1) (update_env env s (offset (nbr+1))) (update_mem mem (update_env env s (offset (nbr+1))) s (offset (nbr+1)) r) stack)\n    end\n      end.\nDefinition stack : Stack := nil.\nDefinition conf_global : Config := (config 2 env_global mem_global stack).\nCompute (update_conf \"z\" conf_global undecl).\n\nDefinition getConfigElementOffset (conf : Config) (s : string) :=\nmatch conf with\n| config nat env memlayer stack => (env s)\nend.\n\nCompute (getConfigElementOffset conf_global \"x\").\nCompute (getConfigElementOffset conf_global \"y\").\nCompute (getConfigElementOffset conf_global \"z\").\n\nDefinition getConfigMemzoneResult (conf : Config) (mem : Mem) :=\nmatch conf with\n| config nat env memlayer stack => (memlayer mem)\nend.\n\nCompute (getConfigMemzoneResult conf_global (offset 1)).\nCompute (getConfigMemzoneResult conf_global (offset 2)).\nCompute (getConfigMemzoneResult conf_global (offset 3)).\nCompute (getConfigMemzoneResult conf_global mem_default).\n\nDefinition getConfigLastMemzone (conf : Config) :=\nmatch conf with\n| config nat env memlayer stack => nat\nend.\n\nCompute (getConfigLastMemzone conf_global).\n\nDefinition getConfigLastEnvStack (conf : Config) : Env :=\nmatch conf with\n| config nat env memlayer stack => match stack with\n                                  | nil => env_blank\n                                  | (c :: stack') => c\n                                  end\nend.\n\nCompute (getConfigElementOffset (update_conf \"z\" conf_global func_decl) \"z\").\nCompute (getConfigElementOffset (update_conf \"z\" (update_conf \"z\" conf_global func_decl) (func_val (int_decl \"k\"))) \"z\").\nCompute (getConfigMemzoneResult (update_conf \"z\" (update_conf \"z\" conf_global nat_decl) (nat_val 6)) (offset 3)).\nCompute (getConfigMemzoneResult (update_conf \"z\" conf_global func_decl) (offset 3)).\nCompute (getConfigLastMemzone (update_conf \"z\" conf_global func_decl)).\nCompute getConfigMemzoneResult (update_conf \"z\" (update_conf \"z\" conf_global func_decl) (func_val (int_decl \"k\"))) (offset 3).\n\n(* --------------- END MEM + MEMLAYER (GLOBAL + BLANK) + ENV (GLOBAL + BLANK) + STACK(OF ENV) + CONFIG ---------------*)\n(* --------------- GLOBAL VARIABLES LIST ---------------*)\n\nDefinition string_list := list string.\n\nDefinition global_vars : string_list := (\"x\" :: \"y\" :: nil).\n\n(* --------------- END GLOBAL VARIABLES LIST ---------------*)\n\n(*TO DO : SEMANTICA + GET,SET PENTRU STRUCT*)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "AdrianSmau", "repo": "ProiectPLP", "sha": "b473f4c2bfa9402746df746b68f775d3dbe3aa6e", "save_path": "github-repos/coq/AdrianSmau-ProiectPLP", "path": "github-repos/coq/AdrianSmau-ProiectPLP/ProiectPLP-b473f4c2bfa9402746df746b68f775d3dbe3aa6e/proiect_v2_21.12.2020.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.24801663865091342}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Vincent Rahli\n\n*)\n\n\nRequire Export sequents_lib.\nRequire Export sequents_tacs2.\n\n\nDefinition renaming : Type := opname * opname.\n\nDefinition rename_opname (r : renaming) (n : opname) : opname :=\n  let (n1,n2) := r in\n  if String.string_dec n n1 then n2\n  else if String.string_dec n n2 then n1\n       else n.\n\nDefinition rename_opabs (r : renaming) (a : opabs) : opabs :=\n  match a with\n  | Build_opabs name params sign => Build_opabs (rename_opname r name) params sign\n  end.\n\nDefinition rename_op {o} (r : renaming) (op : @Opid o) : Opid :=\n  match op with\n  | Abs abs => Abs (rename_opabs r abs)\n  | _ => op\n  end.\n\nFixpoint rename_term {o} (r : renaming) (t : @NTerm o) : NTerm :=\n  match t with\n  | vterm v => vterm v\n  | sterm s => sterm (fun n => rename_term r (s n))\n  | oterm op bs => oterm (rename_op r op) (map (rename_bterm r) bs)\n  end\nwith rename_bterm {o} (r : renaming) (bt : @BTerm o) : BTerm :=\n       match bt with\n       | bterm vs t => bterm vs (rename_term r t)\n       end.\n\nFixpoint rename_soterm {o} (r : renaming) (t : @SOTerm o) : SOTerm :=\n  match t with\n  | sovar v ts => sovar v (map (rename_soterm r) ts)\n  | soseq s => soseq (fun n => rename_term r (s n))\n  | soterm op bs => soterm (rename_op r op) (map (rename_sobterm r) bs)\n  end\nwith rename_sobterm {o} (r : renaming) (bt : @SOBTerm o) : SOBTerm :=\n       match bt with\n       | sobterm vs t => sobterm vs (rename_soterm r t)\n       end.\n\nLemma rename_term_apply_list {o} :\n  forall (r : renaming) ts (t : @NTerm o),\n    rename_term r (apply_list t ts)\n    = apply_list (rename_term r t) (map (rename_term r) ts).\nProof.\n  induction ts; introv; simpl; tcsp.\n  rewrite IHts; simpl; auto.\nQed.\n\nLemma soterm2nterm_rename_soterm {o} :\n  forall (r : renaming) (t : @SOTerm o),\n    soterm2nterm (rename_soterm r t)\n    = rename_term r (soterm2nterm t).\nProof.\n  soterm_ind t as [v ts ind|f|op bs ind] Case; introv; simpl in *; tcsp.\n\n  - Case \"sovar\".\n    rewrite rename_term_apply_list; simpl.\n    allrw map_map; unfold compose; simpl.\n    f_equal.\n    apply eq_maps; tcsp.\n\n  - Case \"soterm\".\n    f_equal.\n    allrw map_map; unfold compose; simpl.\n    apply eq_maps; introv i; simpl.\n    destruct x; simpl.\n    apply ind in i; f_equal; auto.\nQed.\n\nLemma free_vars_rename_term {o} :\n  forall (r : renaming) (t : @NTerm o),\n    free_vars (rename_term r t) = free_vars t.\nProof.\n  sp_nterm_ind1 t as [v|f ind|op bs ind] Case; introv; simpl; tcsp;[].\n  induction bs; simpl; auto.\n  rewrite IHbs; clear IHbs; simpl in *; tcsp;[|introv i; eapply ind; eauto].\n  destruct a; simpl.\n  erewrite ind; eauto.\nDefined.\nHint Rewrite @free_vars_rename_term : slow.\n\nLemma closed_rename_term {o} :\n  forall (r : renaming) (t : @NTerm o),\n    closed t\n    -> closed (rename_term r t).\nProof.\n  introv cl.\n  unfold closed in *; autorewrite with slow in *; auto.\nQed.\nHint Resolve closed_rename_term : slow.\n\nLemma get_utokens_o_rename_op {o} :\n  forall (r : renaming) (op : @Opid o),\n    get_utokens_o (rename_op r op) = get_utokens_o op.\nProof.\n  destruct op; simpl; tcsp.\nQed.\nHint Rewrite @get_utokens_o_rename_op : slow.\n\nLemma get_utokens_rename_term {o} :\n  forall (r : renaming) (t : @NTerm o),\n    get_utokens (rename_term r t) = get_utokens t.\nProof.\n  sp_nterm_ind1 t as [v|f ind|op bs ind] Case; introv; simpl; tcsp;[].\n  autorewrite with slow; f_equal.\n  induction bs; simpl in *; auto.\n  rewrite IHbs; auto;[|introv xx; eapply ind;eauto].\n  destruct a; simpl; f_equal.\n  eapply ind; eauto.\nQed.\nHint Rewrite @get_utokens_rename_term : slow.\n\nLemma implies_noutokens_rename_term {o} :\n  forall r (t : @NTerm o),\n    noutokens t\n    -> noutokens (rename_term r t).\nProof.\n  introv n.\n  unfold noutokens in *; autorewrite with slow in *; auto.\nQed.\nHint Resolve implies_noutokens_rename_term : slow.\n\nLemma OpBindings_rename_op {o} :\n  forall r (op : @Opid o),\n    OpBindings (rename_op r op) = OpBindings op.\nProof.\n  destruct op as [| | |abs]; simpl; tcsp.\n  destruct abs; simpl; auto.\nQed.\nHint Rewrite @OpBindings_rename_op : slow.\n\nLemma implies_wf_term_rename_term {o} :\n  forall (r : renaming) (t : @NTerm o),\n    wf_term t\n    -> wf_term (rename_term r t).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv wf; simpl; tcsp.\n\n  - Case \"sterm\".\n    allrw @wf_sterm_iff.\n    introv.\n    pose proof (ind n) as q; clear ind.\n    pose proof (wf n) as h; clear wf.\n    allrw @computation_seq.isprog_nout_iff.\n    repnd.\n    allrw @nt_wf_eq.\n    dands; eauto 3 with slow.\n\n  - Case \"oterm\".\n    allrw @wf_oterm_iff.\n    allrw map_map; unfold compose.\n    autorewrite with slow.\n    repnd; dands; auto.\n\n    + rewrite <- wf0.\n      apply eq_maps; introv i.\n      destruct x; unfold num_bvars; simpl; auto.\n\n    + introv i.\n      allrw in_map_iff; exrepnd; subst.\n      destruct a; simpl in *.\n      apply wf_bterm_iff.\n      eapply ind; eauto.\n      apply wf in i1.\n      allrw @wf_bterm_iff; tcsp.\nQed.\nHint Resolve implies_wf_term_rename_term : slow.\n\nLemma implies_wf_soterm_rename_soterm {o} :\n  forall (r : renaming) (t : @SOTerm o),\n    wf_soterm t\n    -> wf_soterm (rename_soterm r t).\nProof.\n  introv wf.\n  unfold wf_soterm in *; simpl in *.\n  rewrite soterm2nterm_rename_soterm.\n  eauto 3 with slow.\nQed.\nHint Resolve implies_wf_soterm_rename_soterm : slow.\n\nLemma so_free_vars_rename_soterm {o} :\n  forall (r : renaming) (t : @SOTerm o),\n    so_free_vars (rename_soterm r t) = so_free_vars t.\nProof.\n  soterm_ind t as [v ts ind|f ind|op bs ind] Case; introv; simpl; tcsp.\n\n  - Case \"sovar\".\n    autorewrite with list; f_equal.\n    allrw flat_map_map; unfold compose.\n    apply eq_flat_maps; introv i; tcsp.\n\n  - Case \"soterm\".\n    allrw flat_map_map; unfold compose.\n    apply eq_flat_maps; introv i; tcsp.\n    destruct x; simpl.\n    apply ind in i.\n    rewrite i; auto.\nQed.\nHint Rewrite @so_free_vars_rename_soterm : slow.\n\nLemma implies_socovered_rename_soterm {o} :\n  forall r (t : @SOTerm o) vars,\n    socovered t vars\n    -> socovered (rename_soterm r t) vars.\nProof.\n  introv cov.\n  unfold socovered in *; autorewrite with slow in *; auto.\nQed.\nHint Resolve implies_socovered_rename_soterm : slow.\n\nLemma get_utokens_so_rename_soterm {o} :\n  forall (r : renaming) (t : @SOTerm o),\n    get_utokens_so (rename_soterm r t) = get_utokens_so t.\nProof.\n  soterm_ind t as [v ts ind|f ind|op bs ind] Case; introv; simpl; tcsp.\n\n  - Case \"sovar\".\n    allrw flat_map_map; unfold compose; autorewrite with slow in *.\n    apply eq_flat_maps; introv i; tcsp.\n\n  - Case \"soterm\".\n    allrw flat_map_map; unfold compose; autorewrite with slow in *.\n    f_equal.\n    apply eq_flat_maps; introv i; tcsp.\n    destruct x; simpl.\n    apply ind in i.\n    rewrite i; auto.\nQed.\nHint Rewrite @get_utokens_so_rename_soterm : slow.\n\nLemma implies_no_utokens_rename_soterm {o} :\n  forall r (t : @SOTerm o),\n    no_utokens t\n    -> no_utokens (rename_soterm r t).\nProof.\n  introv.\n  unfold no_utokens in *; autorewrite with slow; auto.\nQed.\nHint Resolve implies_no_utokens_rename_soterm : slow.\n\nLemma opabs_params_rename_opabs :\n  forall r (opabs : opabs),\n    opabs_params (rename_opabs r opabs) = opabs_params opabs.\nProof.\n  destruct opabs; simpl; auto.\nQed.\nHint Rewrite opabs_params_rename_opabs : slow.\n\nLemma opabs_sign_rename_opabs :\n  forall r (opabs : opabs),\n    opabs_sign (rename_opabs r opabs) = opabs_sign opabs.\nProof.\n  destruct opabs; simpl; auto.\nQed.\nHint Rewrite opabs_sign_rename_opabs : slow.\n\nLemma rename_correct {o} :\n  forall {opabs vars rhs} (r : renaming) (correct : @correct_abs o opabs vars rhs),\n    correct_abs (rename_opabs r opabs) vars (rename_soterm r rhs).\nProof.\n  introv cor.\n  unfold correct_abs in *; simpl in *; repnd; dands; eauto 3 with slow;\n    autorewrite with slow in *; auto.\nQed.\nHint Resolve rename_correct : slow.\n\nDefinition rename_library_entry {o} (r : renaming) (e : @library_entry o) : library_entry :=\n  match e with\n  | lib_abs opabs vars rhs correct =>\n    lib_abs (rename_opabs r opabs) vars (rename_soterm r rhs) (rename_correct r correct)\n  end.\n\nDefinition rename_lib {o} (r : renaming) (l : @library o) : library :=\n  map (rename_library_entry r) l.\n\nDefinition rename_conclusion {o} (r : renaming) (c : @conclusion o) : conclusion :=\n  match c with\n  | concl_ext t e => concl_ext (rename_term r t) (rename_term r e)\n  | concl_typ t => concl_typ (rename_term r t)\n  end.\n\nDefinition rename_hypothesis {o} (r : renaming) (h : @hypothesis o) : hypothesis :=\n  match h with\n  | Build_hypothesis _ n h t l => Build_hypothesis _ n h (rename_term r t) l\n  end.\n\nDefinition rename_barehypotheses {o} (r : renaming) (H : @barehypotheses o) : barehypotheses :=\n  map (rename_hypothesis r) H.\n\nDefinition rename_baresequent {o} (r : renaming) (s : @baresequent o) : baresequent :=\n  match s with\n  | Build_baresequent _ hyps concl =>\n    Build_baresequent _ (rename_barehypotheses r hyps) (rename_conclusion r concl)\n  end.\n\nLemma rename_barehypotheses_snoc {o} :\n  forall r (H : @bhyps o) h,\n    rename_barehypotheses r (snoc H h)\n    = snoc (rename_barehypotheses r H) (rename_hypothesis r h).\nProof.\n  induction H; introv; simpl; auto.\n  rewrite IHlist; auto.\nDefined.\n\nLemma vars_hyps_rename_barehypotheses {o} :\n  forall r (H : @bhyps o),\n    vars_hyps (rename_barehypotheses r H)\n    = vars_hyps H.\nProof.\n  induction H; introv; simpl; tcsp.\n  allrw.\n  destruct a; simpl; auto.\nQed.\nHint Rewrite @vars_hyps_rename_barehypotheses : slow.\n\nLemma nh_vars_hyps_rename_barehypotheses {o} :\n  forall r (H : @bhyps o),\n    nh_vars_hyps (rename_barehypotheses r H)\n    = nh_vars_hyps H.\nProof.\n  introv; unfold nh_vars_hyps; simpl.\n  induction H; simpl; tcsp.\n  destruct a; simpl in *; unfold is_nh in *; simpl.\n  destruct (negb hidden); simpl; tcsp.\n  rewrite IHlist; auto.\nQed.\nHint Rewrite @nh_vars_hyps_rename_barehypotheses : slow.\n\nLemma htyp_rename_hypothesis {o} :\n  forall r (h : @hypothesis o),\n    htyp (rename_hypothesis r h)\n    = rename_term r (htyp h).\nProof.\n  destruct h; simpl; tcsp.\nQed.\nHint Rewrite @htyp_rename_hypothesis : slow.\n\nLemma hvar_rename_hypothesis {o} :\n  forall r (h : @hypothesis o),\n    hvar (rename_hypothesis r h)\n    = hvar h.\nProof.\n  destruct h; simpl; tcsp.\nQed.\nHint Rewrite @hvar_rename_hypothesis : slow.\n\nLemma implies_isprog_vars_rename_term {o} :\n  forall vs r (t : @NTerm o),\n    isprog_vars vs t\n    -> isprog_vars vs (rename_term r t).\nProof.\n  introv isp.\n  unfold isprog_vars in *; autorewrite with slow; repnd; dands; eauto 3 with slow.\nQed.\nHint Resolve implies_isprog_vars_rename_term : slow.\n\nLemma wf_hypotheses_rename_barehypotheses {o} :\n  forall r (H : @barehypotheses o),\n    wf_hypotheses H\n    -> wf_hypotheses (rename_barehypotheses r H).\nProof.\n  induction H using rev_list_indT; simpl; introv wf; auto.\n  inversion wf as [|? ? isp ni wf1 e]; ginv; clear wf.\n  apply snoc_inj in e; repnd; subst; simpl.\n  rewrite rename_barehypotheses_snoc.\n  constructor; simpl; auto; eauto 3 with slow;\n    autorewrite with slow in *; eauto 3 with slow.\nQed.\nHint Resolve wf_hypotheses_rename_barehypotheses : slow.\n\nLemma wf_concl_rename_conclusion {o} :\n  forall r (concl : @conclusion o),\n    wf_concl concl\n    -> wf_concl (rename_conclusion r concl).\nProof.\n  destruct concl; introv wf; simpl in *;\n    unfold wf_concl in *; simpl in *; repnd; dands; eauto 3 with slow.\nQed.\nHint Resolve wf_concl_rename_conclusion : slow.\n\nLemma wf_sequent_rename {o} :\n  forall r (s : @baresequent o),\n    wf_sequent s -> wf_sequent (rename_baresequent r s).\nProof.\n  introv wf.\n  destruct s; simpl in *.\n  unfold wf_sequent in *; simpl in *.\n  allrw @vswf_hypotheses_nil_eq.\n  repnd; dands; eauto 3 with slow.\nQed.\nHint Resolve wf_sequent_rename : slow.\n\nDefinition rename_sequent {o} (r : renaming) (cs : @sequent o) : sequent :=\n  let (s,wf) := cs in\n  existT wf_sequent (rename_baresequent r s) (wf_sequent_rename r s wf).\n\nLemma closed_type_sequent_rename {o} :\n  forall r (s : @sequent o),\n    closed_type_sequent s -> closed_type_sequent (rename_sequent r s).\nProof.\n  introv cl.\n  unfold closed_type_sequent in *; simpl in *.\n  unfold closed_type_baresequent in *; simpl in *.\n  destruct s; simpl in *; autorewrite with slow in *.\n  unfold closed_type in *; simpl in *; autorewrite with slow in *.\n  destruct x; simpl in *; autorewrite with slow in *.\n  unfold covered in *; simpl in *.\n  destruct concl in *; simpl in *; autorewrite with slow in *; auto.\nQed.\nHint Resolve closed_type_sequent_rename : slow.\n\nDefinition rename_ctsequent {o} (r : renaming) (cs : @ctsequent o) : ctsequent :=\n  let (s,c) := cs in\n  existT closed_type_sequent (rename_sequent r s) (closed_type_sequent_rename r s c).\n\nLemma closed_extract_ctsequent_rename {o} :\n  forall r (s : @ctsequent o),\n    closed_extract_ctsequent s -> closed_extract_ctsequent (rename_ctsequent r s).\nProof.\n  introv cl.\n  unfold closed_extract_ctsequent in *; simpl in *.\n  destruct s; simpl in *.\n  unfold closed_extract_sequent in *; simpl in *.\n  destruct x; simpl in *.\n  destruct x; simpl in *.\n  unfold closed_extract_baresequent in *; simpl in *.\n  unfold closed_extract in *; simpl in *.\n  destruct concl in *; simpl in *; tcsp; autorewrite with slow in *.\n  unfold covered in *; simpl in *; autorewrite with slow in *; auto.\nQed.\nHint Resolve closed_extract_ctsequent_rename : slow.\n\nDefinition rename_csequent {o} (r : renaming) (cs : @csequent o) : csequent :=\n  let (s,c) := cs in\n  existT closed_extract_ctsequent (rename_ctsequent r s) (closed_extract_ctsequent_rename r s c).\n\nLemma rename_opname_idem :\n  forall r (n : opname),\n    rename_opname r (rename_opname r n) = n.\nProof.\n  introv; unfold rename_opname; destruct r; boolvar; subst; tcsp.\nQed.\nHint Rewrite rename_opname_idem : slow.\n\nLemma rename_opabs_idem :\n  forall r (a : opabs),\n    rename_opabs r (rename_opabs r a) = a.\nProof.\n  introv; destruct a; simpl; autorewrite with slow; auto.\nQed.\nHint Rewrite rename_opabs_idem : slow.\n\nLemma rename_opid_idem {o} :\n  forall r (op : @Opid o),\n    rename_op r (rename_op r op) = op.\nProof.\n  introv; destruct op; simpl; autorewrite with slow; auto.\nQed.\nHint Rewrite @rename_opid_idem : slow.\n\nLemma rename_term_idem {o} :\n  forall r (t : @NTerm o),\n    rename_term r (rename_term r t) = t.\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv; simpl; tcsp.\n\n  - Case \"sterm\".\n    f_equal.\n    apply functional_extensionality; tcsp.\n\n  - Case \"oterm\".\n    autorewrite with slow in *; allrw map_map; unfold compose.\n    f_equal.\n    apply eq_map_l; introv i.\n    destruct x; simpl.\n    erewrite ind; eauto.\nQed.\nHint Rewrite @rename_term_idem : slow.\n\n(*Eval compute in (rename_term_idem\n                   (\"member\", \"MEMBER\")\n                   (mk_uall (vterm nvarT) nvart mk_axiom)).*)\n\nLemma rename_soterm_idem {o} :\n  forall r (t : @SOTerm o),\n    rename_soterm r (rename_soterm r t) = t.\nProof.\n  soterm_ind t as [v ts ind|f ind|op bs ind] Case; introv; simpl; tcsp.\n\n  - Case \"sovar\".\n    f_equal.\n    allrw map_map; unfold compose.\n    apply eq_map_l; tcsp.\n\n  - Case \"soseq\".\n    f_equal.\n    apply functional_extensionality; introv; autorewrite with slow; auto.\n\n  - Case \"soterm\".\n    autorewrite with slow; allrw map_map; unfold compose.\n    f_equal.\n    apply eq_map_l; introv i; destruct x; simpl.\n    erewrite ind; eauto.\nQed.\nHint Rewrite @rename_soterm_idem : slow.\n\nLemma rename_library_entry_idem {o} :\n  forall r (e : @library_entry o),\n    rename_library_entry r (rename_library_entry r e) = e.\nProof.\n  introv; destruct e; simpl.\n\n  remember (rename_correct r (rename_correct r correct)) as cor; clear Heqcor.\n  revert cor.\n  autorewrite with slow; introv.\n  f_equal; eauto with pi.\nQed.\nHint Rewrite @rename_library_entry_idem : slow.\n\nLemma rename_lib_idem {o} :\n  forall r (lib : @library o),\n    rename_lib r (rename_lib r lib) = lib.\nProof.\n  induction lib; introv; simpl; auto; allrw; f_equal; autorewrite with slow; auto.\nQed.\nHint Rewrite @rename_lib_idem : slow.\n\nLemma eq_rename_opname_implies :\n  forall r n m,\n    rename_opname r n = rename_opname r m\n    -> n = m.\nProof.\n  introv h.\n  unfold rename_opname in *.\n  destruct r; boolvar; subst; tcsp.\nQed.\nHint Resolve eq_rename_opname_implies : slow.\n\nLemma eq_opabs_name_rename_implies :\n  forall r a1 a2,\n    opabs_name (rename_opabs r a1) = opabs_name (rename_opabs r a2)\n    -> opabs_name a1 = opabs_name a2.\nProof.\n  introv h; destruct a1, a2; simpl in *; eauto 3 with slow.\nQed.\nHint Resolve eq_opabs_name_rename_implies : slow.\n\nLemma implies_not_matching_entries_rename {o} :\n  forall r (e a : @library_entry o),\n    ~ matching_entries e a\n    -> ~ matching_entries (rename_library_entry r e) (rename_library_entry r a).\nProof.\n  introv n m; destruct n.\n  unfold matching_entries in *; simpl in *.\n  destruct e, a; simpl in *.\n  unfold matching_entry_sign in *; simpl in *; autorewrite with slow in *.\n  repnd; dands; auto; eauto 3 with slow.\nQed.\nHint Resolve implies_not_matching_entries_rename : slow.\n\nLemma implies_entry_in_library_rename {o} :\n  forall r e (lib : @library o),\n    entry_in_library e lib\n    -> entry_in_library (rename_library_entry r e) (rename_lib r lib).\nProof.\n  induction lib; introv i; simpl in *; tcsp.\n  repndors; repnd; subst; tcsp.\n  right.\n  dands; tcsp; eauto 3 with slow.\nQed.\nHint Resolve implies_entry_in_library_rename : slow.\n\nLemma implies_lib_extends_rename_lib {o} :\n  forall r (lib1 lib2 : @library o),\n    lib_extends lib1 lib2\n    -> lib_extends (rename_lib r lib1) (rename_lib r lib2).\nProof.\n  introv ext i.\n  apply (implies_entry_in_library_rename r) in i; autorewrite with slow in *.\n  apply ext in i.\n  apply (implies_entry_in_library_rename r) in i; autorewrite with slow in *; auto.\nQed.\nHint Resolve implies_lib_extends_rename_lib : slow.\n\nLemma implies_isprog_rename_term {o} :\n  forall r (t : @NTerm o),\n    isprog t\n    -> isprog (rename_term r t).\nProof.\n  introv isp.\n  allrw @isprog_eq.\n  destruct isp.\n  split; dands; allrw @nt_wf_eq; eauto 3 with slow.\nQed.\nHint Resolve implies_isprog_rename_term : slow.\n\nDefinition rename_cterm {o} r (ct : @CTerm o) : CTerm :=\n  let (t,isp) := ct in\n  mk_ct (rename_term r t) (implies_isprog_rename_term r t isp).\n\nDefinition rename_var_cterm {o} r (p : NVar * @CTerm o) : NVar * CTerm :=\n  let (v,t) := p in (v,rename_cterm r t).\n\nDefinition rename_csub {o} r (s : @CSub o) : @CSub o :=\n  map (rename_var_cterm r) s.\n\nLemma rename_csub_snoc {o} :\n  forall r (s : @CSub o) v t,\n    rename_csub r (snoc s (v,t))\n    = snoc (rename_csub r s) (v, rename_cterm r t).\nProof.\n  induction s; introv; simpl; tcsp.\n  f_equal; tcsp.\nQed.\n\nLtac sim_snoc3 :=\n  match goal with\n  | [ |- similarity _ (snoc ?s1 (?x,?t1)) (snoc ?s2 (?x,?t2)) (snoc _ ?h) ] =>\n    let w := fresh \"w\" in\n    let c := fresh \"c\" in\n    assert (wf_term (htyp h)) as w;\n    [ auto\n    | assert (cover_vars (htyp h) s1) as c;\n      [ auto\n      | apply similarity_snoc; simpl;\n        exists s1 s2 t1 t2 w c\n      ]\n    ]\n  end.\n\nLemma dom_csub_rename_csub {o} :\n  forall r (s : @CSub o),\n    dom_csub (rename_csub r s) = dom_csub s.\nProof.\n  unfold dom_csub, rename_csub; introv.\n  allrw map_map; unfold compose.\n  apply eq_maps; introv i.\n  destruct x; simpl; auto.\nQed.\nHint Rewrite @dom_csub_rename_csub : slow.\n\nLemma implies_covered_rename {o} :\n  forall r (t : @NTerm o) vars,\n    covered t vars\n    -> covered (rename_term r t) vars.\nProof.\n  introv cov.\n  unfold covered in *; autorewrite with slow in *; auto.\nQed.\nHint Resolve implies_covered_rename : slow.\n\nLemma implies_cover_vars_rename {o} :\n  forall r (t : @NTerm o) s,\n    cover_vars t s\n    -> cover_vars (rename_term r t) (rename_csub r s).\nProof.\n  introv cov.\n  allrw @cover_vars_covered; autorewrite with slow.\n  eauto 3 with slow.\nQed.\nHint Resolve implies_cover_vars_rename : slow.\n\nLemma rename_cterm_idem {o} :\n  forall r (t : @CTerm o),\n    rename_cterm r (rename_cterm r t) = t.\nProof.\n  introv; destruct t; simpl.\n  apply cterm_eq; simpl; autorewrite with slow; auto.\nQed.\nHint Rewrite @rename_cterm_idem : slow.\n\nLemma implies_isnoncan_like_rename_term {o} :\n  forall r (t : @NTerm o),\n    isnoncan_like t\n    -> isnoncan_like (rename_term r t).\nProof.\n  introv isn.\n  unfold isnoncan_like in *; repndors;[left|right].\n\n  - unfold isnoncan in *.\n    destruct t as [|f|op bs]; simpl in *; auto.\n    destruct op; simpl; auto.\n\n  - unfold isabs in *.\n    destruct t as [|f|op bs]; simpl in *; auto.\n    destruct op; simpl; auto.\nQed.\nHint Resolve implies_isnoncan_like_rename_term : slow.\n\nLemma implies_iscan_rename_term {o} :\n  forall r (t : @NTerm o),\n    iscan t\n    -> iscan (rename_term r t).\nProof.\n  introv isc.\n  unfold iscan in *.\n  destruct t as [|f|op bs]; simpl in *; auto.\n  destruct op; simpl; auto.\nQed.\nHint Resolve implies_iscan_rename_term : slow.\n\nLemma implies_isexc_rename_term {o} :\n  forall r (t : @NTerm o),\n    isexc t\n    -> isexc (rename_term r t).\nProof.\n  introv ise.\n  unfold isexc in *.\n  destruct t as [|f|op bs]; simpl in *; auto.\n  destruct op; simpl; auto.\nQed.\nHint Resolve implies_isexc_rename_term : slow.\n\nLemma implies_isvalue_like_rename_term {o} :\n  forall r (t : @NTerm o),\n    isvalue_like t\n    -> isvalue_like (rename_term r t).\nProof.\n  introv isv.\n  unfold isvalue_like in *; repndors;[left|right]; eauto 3 with slow.\nQed.\nHint Resolve implies_isvalue_like_rename_term : slow.\n\nDefinition rename_var_term {o} r (p : NVar * @NTerm o) : NVar * NTerm :=\n  let (v,t) := p in (v,rename_term r t).\n\nDefinition rename_sub {o} r (s : @Sub o) : @Sub o :=\n  map (rename_var_term r) s.\n\nLemma sub_find_rename_sub {o} :\n  forall r (s : @Sub o) v,\n    sub_find (rename_sub r s) v\n    = match sub_find s v with\n      | Some t => Some (rename_term r t)\n      | None => None\n      end.\nProof.\n  induction s; introv; simpl; tcsp; repnd; simpl; boolvar; auto.\nDefined.\n\nLemma rename_sub_sub_filter {o} :\n  forall r (s : @Sub o) l,\n    rename_sub r (sub_filter s l)\n    = sub_filter (rename_sub r s) l.\nProof.\n  induction s; introv; simpl; tcsp.\n  repnd; simpl; boolvar; tcsp.\n  simpl; rewrite IHs; auto.\nDefined.\n\nLemma rename_term_lsubst_aux {o} :\n  forall r (t : @NTerm o) s,\n    rename_term r (lsubst_aux t s) = lsubst_aux (rename_term r t) (rename_sub r s).\nProof.\n  sp_nterm_ind1 t as [v|f ind|op bs ind] Case; introv; simpl; tcsp.\n\n  - Case \"vterm\".\n\n    rewrite sub_find_rename_sub.\n    remember (sub_find s v) as sf; symmetry in Heqsf; destruct sf; auto.\n\n  - Case \"oterm\".\n    f_equal.\n    induction bs; simpl; auto.\n    rewrite IHbs; simpl in *; tcsp;[|introv xx; eapply ind; eauto].\n    destruct a; simpl.\n    erewrite ind; eauto.\n    rewrite rename_sub_sub_filter; auto.\nDefined.\n\nLemma bound_vars_rename_term {o} :\n  forall (r : renaming) (t : @NTerm o),\n    bound_vars (rename_term r t) = bound_vars t.\nProof.\n  sp_nterm_ind1 t as [v|f ind|op bs ind] Case; introv; simpl; tcsp;[].\n  induction bs; simpl; auto.\n  rewrite IHbs; clear IHbs; simpl in *; tcsp;[|introv i; eapply ind; eauto].\n  destruct a; simpl.\n  erewrite ind; eauto.\nDefined.\nHint Rewrite @bound_vars_rename_term : slow.\n\nLemma all_vars_rename_term {o} :\n  forall r (t : @NTerm o),\n    all_vars (rename_term r t) = all_vars t.\nProof.\n  introv; unfold all_vars; autorewrite with slow; auto.\nQed.\nHint Rewrite @all_vars_rename_term : slow.\n\nLemma rename_sub_var_ren {o} :\n  forall r l1 l2, @rename_sub o r (var_ren l1 l2) = var_ren l1 l2.\nProof.\n  unfold var_ren.\n  induction l1; introv; simpl; auto.\n  destruct l2; simpl; auto.\n  rewrite IHl1; auto.\nQed.\nHint Rewrite @rename_sub_var_ren : slow.\n\nLemma rename_term_change_bvars_alpha {o} :\n  forall r vs (t : @NTerm o),\n    rename_term r (change_bvars_alpha vs t)\n    = change_bvars_alpha vs (rename_term r t).\nProof.\n  sp_nterm_ind1 t as [v|f|op bs ind] Case; introv; simpl in *; tcsp.\n  f_equal.\n  allrw map_map; unfold compose.\n  apply eq_maps; introv i.\n  destruct x; simpl.\n  erewrite <- ind; eauto 3 with slow;[].\n  autorewrite with slow; f_equal.\n  rewrite rename_term_lsubst_aux; autorewrite with slow; auto.\nDefined.\n\nLemma flat_map_free_vars_range_rename_sub {o} :\n  forall r (s : @Sub o),\n    flat_map free_vars (range (rename_sub r s))\n    = flat_map free_vars (range s).\nProof.\n  induction s; simpl; auto.\n  rewrite IHs; repnd; simpl; clear IHs.\n  autorewrite with slow; auto.\nDefined.\nHint Rewrite @flat_map_free_vars_range_rename_sub : slow.\n\nLemma rename_term_lsubst {o} :\n  forall r (t : @NTerm o) s,\n    rename_term r (lsubst t s) = lsubst (rename_term r t) (rename_sub r s).\nProof.\n  introv.\n  unfold lsubst.\n  autorewrite with slow.\n  boolvar; auto; rewrite rename_term_lsubst_aux; auto.\n  rewrite rename_term_change_bvars_alpha; auto.\nDefined.\n\nLemma rename_term_subst {o} :\n  forall r (t : @NTerm o) v u,\n    rename_term r (subst t v u) = subst (rename_term r t) v (rename_term r u).\nProof.\n  introv; unfold subst.\n  rewrite rename_term_lsubst; auto.\nDefined.\n\nLemma eapply_wf_def_rename_term {o} :\n  forall r (t : @NTerm o),\n    eapply_wf_def t\n    -> eapply_wf_def (rename_term r t).\nProof.\n  introv wf.\n  unfold eapply_wf_def in *; repndors; exrepnd; subst; simpl in *; tcsp.\n  - left; eexists; eauto.\n  - unfold mk_nseq; right; left; eexists; eauto.\n  - unfold mk_lam; right; right; eexists; eexists; eauto.\nQed.\nHint Resolve eapply_wf_def_rename_term : slow.\n\nLemma maybe_new_var_rename_term {o} :\n  forall v l r (t : @NTerm o),\n    maybe_new_var v l (rename_term r t)\n    = maybe_new_var v l t.\nProof.\n  introv; unfold maybe_new_var, newvar; autorewrite with slow; auto.\nQed.\nHint Rewrite @maybe_new_var_rename_term : slow.\n\nLemma pushdown_fresh_rename_term {o} :\n  forall v r (t : @NTerm o),\n    pushdown_fresh v (rename_term r t)\n    = rename_term r (pushdown_fresh v t).\nProof.\n  introv; unfold pushdown_fresh.\n  destruct t as [z|f|op bs]; simpl; auto.\n  f_equal.\n  unfold mk_fresh_bterms; allrw map_map; unfold compose.\n  apply eq_maps; introv i.\n  destruct x; simpl; autorewrite with slow; auto.\nQed.\n\nLemma get_fresh_atom_rename_term {o} :\n  forall r (t : @NTerm o),\n    get_fresh_atom (rename_term r t) = get_fresh_atom t.\nProof.\n  introv; unfold get_fresh_atom; autorewrite with slow; auto.\nQed.\nHint Rewrite @get_fresh_atom_rename_term : slow.\n\nDefinition rename_name_term {o} r (p : get_patom_set o * @NTerm o) : get_patom_set o * NTerm :=\n  let (v,t) := p in (v,rename_term r t).\n\nDefinition rename_utok_sub {o} r (s : @utok_sub o) : @utok_sub o :=\n  map (rename_name_term r) s.\n\nLemma rename_term_oterm {o} :\n  forall r op (bs : list (@BTerm o)),\n    rename_term r (oterm op bs)\n    = oterm (rename_op r op) (map (rename_bterm r) bs).\nProof.\n  tcsp.\nQed.\n\nLemma get_utok_rename_op {o} :\n  forall r (op : @Opid o),\n    get_utok (rename_op r op) = get_utok op.\nProof.\n  introv; destruct op; simpl; tcsp.\nQed.\nHint Rewrite @get_utok_rename_op : slow.\n\nLemma utok_sub_find_rename_utok_sub {o} :\n  forall r (s : @utok_sub o) a,\n    utok_sub_find (rename_utok_sub r s) a\n    = match utok_sub_find s a with\n      | Some t => Some (rename_term r t)\n      | None => None\n      end.\nProof.\n  induction s; introv; simpl; tcsp.\n  repnd; simpl; boolvar; subst; tcsp.\nQed.\n\nLemma rename_term_subst_utok {o} :\n  forall r (a : get_patom_set o) bs s,\n    rename_term r (subst_utok a bs s)\n    = subst_utok a (map (rename_bterm r) bs) (rename_utok_sub r s).\nProof.\n  introv.\n  unfold subst_utok; autorewrite with slow.\n  rewrite utok_sub_find_rename_utok_sub.\n  remember (utok_sub_find s a) as f; symmetry in Heqf; destruct f; auto.\nQed.\n\nLemma rename_term_subst_utokens_aux {o} :\n  forall r (t : @NTerm o) (s : utok_sub),\n    rename_term r (subst_utokens_aux t s)\n    = subst_utokens_aux (rename_term r t) (rename_utok_sub r s).\nProof.\n  sp_nterm_ind1 t as [v|f|op bs ind] Case; introv; tcsp;[].\n  rewrite rename_term_oterm.\n  repeat (rewrite subst_utokens_aux_oterm).\n  autorewrite with slow in *.\n  remember (get_utok op) as guo; symmetry in Heqguo; destruct guo; simpl in *; tcsp.\n\n  - rewrite rename_term_subst_utok; allrw map_map; unfold compose.\n    f_equal.\n    apply eq_maps; introv i.\n    destruct x; simpl; f_equal.\n    eapply ind; eauto.\n\n  - f_equal.\n    allrw map_map; unfold compose.\n    apply eq_maps; introv i.\n    destruct x; simpl; f_equal.\n    eapply ind; eauto.\nQed.\n\nLemma free_vars_utok_sub_rename_utok_sub {o} :\n  forall r (s : @utok_sub o),\n    free_vars_utok_sub (rename_utok_sub r s)\n    = free_vars_utok_sub s.\nProof.\n  induction s; introv; simpl; tcsp.\n  repnd; simpl; autorewrite with slow; allrw; auto.\nQed.\nHint Rewrite @free_vars_utok_sub_rename_utok_sub : slow.\n\nLemma rename_term_subst_utokens {o} :\n  forall r (t : @NTerm o) (s : utok_sub),\n    rename_term r (subst_utokens t s)\n    = subst_utokens (rename_term r t) (rename_utok_sub r s).\nProof.\n  introv; unfold subst_utokens; autorewrite with slow in *.\n  boolvar.\n\n  - apply rename_term_subst_utokens_aux.\n\n  - rewrite rename_term_subst_utokens_aux; autorewrite with slow.\n    rewrite rename_term_change_bvars_alpha; auto.\nQed.\n\nDefinition rename_sosub_kind {o} r (s : @sosub_kind o) : sosub_kind :=\n  match s with\n  | sosk l t => sosk l (rename_term r t)\n  end.\n\nDefinition rename_var_sk {o} r (p : NVar * @sosub_kind o) : NVar * sosub_kind :=\n  let (v,t) := p in (v,rename_sosub_kind r t).\n\nDefinition rename_sosub {o} r (s : @SOSub o) : @SOSub o :=\n  map (rename_var_sk r) s.\n\nLemma sosub_find_rename_sosub {o} :\n  forall r (s : @SOSub o) v,\n    sosub_find (rename_sosub r s) v\n    = match sosub_find s v with\n      | Some t => Some (rename_sosub_kind r t)\n      | None => None\n      end.\nProof.\n  induction s; introv; simpl; tcsp; repnd; simpl; boolvar; auto;\n    destruct a; simpl; boolvar; auto.\nQed.\n\nLemma rename_sub_combine {o} :\n  forall r l (ts : list (@NTerm o)),\n    length l = length ts\n    -> rename_sub r (combine l ts)\n       = combine l (map (rename_term r) ts).\nProof.\n  induction l; introv len; simpl in *; tcsp.\n  destruct ts; simpl in *; ginv.\n  rewrite IHl; auto.\nQed.\n\nLemma rename_sosub_ossub_filter {o} :\n  forall r (s : @SOSub o) l,\n    rename_sosub r (sosub_filter s l)\n    = sosub_filter (rename_sosub r s) l.\nProof.\n  induction s; introv; simpl; tcsp.\n  repnd; simpl; boolvar; tcsp.\n  destruct a; simpl; boolvar; tcsp.\n  simpl; rewrite IHs; auto.\nQed.\n\nLemma rename_term_sosub_aux {o} :\n  forall r (t : @SOTerm o) s,\n    rename_term r (sosub_aux s t)\n    = sosub_aux (rename_sosub r s) (rename_soterm r t).\nProof.\n  soterm_ind t as [v ts ind|f ind|op bs ind] Case ; introv; simpl in *; tcsp.\n\n  - Case \"sovar\".\n\n    rewrite sosub_find_rename_sosub.\n    autorewrite with list.\n    remember (sosub_find s (v,length ts)) as sf; symmetry in Heqsf; destruct sf; simpl; auto.\n\n    + destruct s0; simpl.\n      rewrite rename_term_lsubst_aux; simpl.\n      apply sosub_find_some in Heqsf; repnd.\n      rewrite rename_sub_combine; autorewrite with list; auto.\n      allrw map_map; unfold compose.\n      f_equal; f_equal.\n      apply eq_maps; introv i; tcsp.\n\n    + rewrite rename_term_apply_list; simpl; f_equal.\n      allrw map_map; unfold compose.\n      apply eq_maps; introv i; tcsp.\n\n  - Case \"soterm\".\n    f_equal; allrw map_map; unfold compose.\n    apply eq_maps; introv i.\n    destruct x; simpl; f_equal.\n    erewrite ind;eauto.\n    rewrite rename_sosub_ossub_filter; auto.\nQed.\n\nLemma fo_bound_vars_rename_soterm {o} :\n  forall r (t : @SOTerm o),\n    fo_bound_vars (rename_soterm r t)\n    = fo_bound_vars t.\nProof.\n  soterm_ind t as [v ts ind|f ind|op bs ind] Case; introv; simpl; tcsp.\n\n  - Case \"sovar\".\n    allrw flat_map_map; unfold compose.\n    apply eq_flat_maps; auto.\n\n  - Case \"soterm\".\n    allrw flat_map_map; unfold compose.\n    apply eq_flat_maps; auto.\n    introv i; destruct x; simpl; f_equal.\n    eapply ind; eauto.\nQed.\nHint Rewrite @fo_bound_vars_rename_soterm : slow.\n\nLemma free_vars_sosub_rename_sosub {o} :\n  forall r (s : @SOSub o),\n    free_vars_sosub (rename_sosub r s)\n    = free_vars_sosub s.\nProof.\n  unfold free_vars_sosub, rename_sosub; introv.\n  allrw flat_map_map; unfold compose.\n  apply eq_flat_maps; introv i; repnd; simpl.\n  destruct x; simpl; autorewrite with slow; auto.\nQed.\nHint Rewrite @free_vars_sosub_rename_sosub : slow.\n\nLemma all_fo_vars_rename_soterm {o} :\n  forall r (t : @SOTerm o),\n    all_fo_vars (rename_soterm r t)\n    = all_fo_vars t.\nProof.\n  soterm_ind t as [v ts ind|f ind|op bs ind] Case; introv; simpl; tcsp;\n    allrw flat_map_map; unfold compose.\n\n  - f_equal; apply eq_flat_maps; auto.\n\n  - apply eq_flat_maps; introv i; destruct x; simpl; f_equal.\n    eapply ind; eauto.\nQed.\nHint Rewrite @all_fo_vars_rename_soterm : slow.\n\nLemma bound_vars_sosub_rename_sosub {o} :\n  forall r (s : @SOSub o),\n    bound_vars_sosub (rename_sosub r s)\n    = bound_vars_sosub s.\nProof.\n  introv.\n  unfold bound_vars_sosub, rename_sosub.\n  allrw flat_map_map; unfold compose.\n  apply eq_flat_maps; introv i; repnd; simpl.\n  destruct x; simpl; autorewrite with slow; auto.\nQed.\nHint Rewrite @bound_vars_sosub_rename_sosub : slow.\n\nLemma rename_soterm_so_change_bvars_alpha {o} :\n  forall r (t : @SOTerm o) vs k,\n    rename_soterm r (so_change_bvars_alpha vs k t)\n    = so_change_bvars_alpha vs k (rename_soterm r t).\nProof.\n  soterm_ind t as [v ts ind|f|op bs ind] Case; introv; simpl in *; tcsp.\n\n  - Case \"sovar\".\n    autorewrite with list; f_equal.\n    allrw map_map; unfold compose.\n    apply eq_maps; tcsp.\n\n  - Case \"soterm\".\n    f_equal.\n    allrw map_map; unfold compose.\n    apply eq_maps; introv i.\n    destruct x; simpl.\n    erewrite <- ind; eauto 3 with slow;[].\n    autorewrite with slow; f_equal.\nQed.\n\nLemma rename_soterm_fo_change_bvars_alpha {o} :\n  forall r (t : @SOTerm o) vs k,\n    rename_soterm r (fo_change_bvars_alpha vs k t)\n    = fo_change_bvars_alpha vs k (rename_soterm r t).\nProof.\n  soterm_ind t as [v ts ind|f|op bs ind] Case; introv; simpl in *; tcsp.\n\n  - Case \"sovar\".\n    autorewrite with list; f_equal.\n    boolvar; subst; simpl in *; ginv; tcsp;\n      try (complete (destruct ts; simpl in *; tcsp)).\n    f_equal; allrw map_map; unfold compose.\n    apply eq_maps; tcsp.\n\n  - Case \"soterm\".\n    f_equal.\n    allrw map_map; unfold compose.\n    apply eq_maps; introv i.\n    destruct x; simpl.\n    erewrite <- ind; eauto 3 with slow;[].\n    autorewrite with slow; f_equal.\nQed.\n\nLemma all_fo_vars_fo_change_bvars_alpha_rename_soterm {o} :\n  forall r (t : @SOTerm o) l k,\n    all_fo_vars (fo_change_bvars_alpha l k (rename_soterm r t))\n    = all_fo_vars (fo_change_bvars_alpha l k t).\nProof.\n  introv; rewrite <- rename_soterm_fo_change_bvars_alpha; autorewrite with slow; auto.\nQed.\nHint Rewrite @all_fo_vars_fo_change_bvars_alpha_rename_soterm : slow.\n\nLemma allvars_rename_term {o} :\n  forall r (t : @NTerm o),\n    allvars (rename_term r t) = allvars t.\nProof.\n  sp_nterm_ind1 t as [v|f|op bs ind] Case; introv; simpl; tcsp.\n  allrw flat_map_map; unfold compose.\n  apply eq_flat_maps; introv i.\n  destruct x; simpl; f_equal; eapply ind; eauto.\nQed.\nHint Rewrite @allvars_rename_term : slow.\n\nLemma allvars_range_sosub_rename_sosub {o} :\n  forall r (s : @SOSub o),\n    allvars_range_sosub (rename_sosub r s)\n    = allvars_range_sosub s.\nProof.\n  introv; unfold allvars_range_sosub, rename_sosub.\n  allrw flat_map_map; unfold compose.\n  apply eq_flat_maps; introv i; repnd; simpl.\n  destruct x; simpl; f_equal; autorewrite with slow; auto.\nQed.\nHint Rewrite @allvars_range_sosub_rename_sosub : slow.\n\nLemma all_vars_change_bvars_alpha_rename_term {o} :\n  forall l r (t : @NTerm o),\n    all_vars (change_bvars_alpha l (rename_term r t))\n    = all_vars (change_bvars_alpha l t).\nProof.\n  introv.\n  rewrite <- rename_term_change_bvars_alpha.\n  introv; unfold all_vars; autorewrite with slow; auto.\nQed.\nHint Rewrite @all_vars_change_bvars_alpha_rename_term : slow.\n\nLemma rename_sosub_sosub_change_bvars_alpha {o} :\n  forall r l (s : @SOSub o),\n    rename_sosub r (sosub_change_bvars_alpha l s)\n    = sosub_change_bvars_alpha l (rename_sosub r s).\nProof.\n  introv; unfold sosub_change_bvars_alpha, rename_sosub.\n  allrw map_map; unfold compose.\n  apply eq_maps; introv i; repnd; simpl.\n  destruct x; simpl.\n  unfold sk_change_bvars_alpha; simpl; autorewrite with slow.\n  f_equal; f_equal.\n  rewrite rename_term_lsubst_aux; simpl.\n  rewrite <- rename_term_change_bvars_alpha; autorewrite with slow; auto.\nQed.\n\nLemma rename_term_sosub {o} :\n  forall r s (t : @SOTerm o),\n    rename_term r (sosub s t)\n    = sosub (rename_sosub r s) (rename_soterm r t).\nProof.\n  introv; unfold sosub; autorewrite with slow.\n  boolvar; tcsp.\n\n  - rewrite rename_term_sosub_aux; auto.\n\n  - rewrite rename_term_sosub_aux; auto.\n    rewrite rename_sosub_sosub_change_bvars_alpha; auto.\n\n  - rewrite rename_term_sosub_aux; auto.\n    rewrite rename_soterm_fo_change_bvars_alpha; auto.\n\n  - rewrite rename_term_sosub_aux; simpl.\n    rewrite rename_soterm_fo_change_bvars_alpha; auto.\n    rewrite rename_sosub_sosub_change_bvars_alpha; auto.\nQed.\n\nLemma rename_sosub_mk_abs_subst {o} :\n  forall r vars (bs : list (@BTerm o)),\n    rename_sosub r (mk_abs_subst vars bs)\n    = mk_abs_subst vars (map (rename_bterm r) bs).\nProof.\n  induction vars; introv; simpl; auto.\n  destruct a; simpl.\n  destruct bs; simpl; auto.\n  destruct b; simpl.\n  boolvar; simpl; auto.\n  rewrite IHvars; auto.\nQed.\n\nLemma implies_matching_entry_rename {o} :\n  forall r abs1 abs2 vars (bs : list (@BTerm o)),\n    matching_entry abs1 abs2 vars bs\n    -> matching_entry (rename_opabs r abs1) (rename_opabs r abs2) vars (map (rename_bterm r) bs).\nProof.\n  unfold  matching_entry in *; introv h; repnd.\n  destruct abs1, abs2; simpl in *; subst; dands; auto.\n  unfold matching_bterms in *.\n  allrw map_map; unfold compose.\n  rewrite h.\n  apply eq_maps; introv i.\n  destruct x; simpl; unfold num_bvars; simpl; auto.\nQed.\nHint Resolve implies_matching_entry_rename : slow.\n\nLemma implies_found_entry_rename {o} :\n  forall r lib abs bs oa vars (rhs : @SOTerm o) correct,\n    found_entry lib abs bs oa vars rhs correct\n    -> found_entry\n         (rename_lib r lib)\n         (rename_opabs r abs)\n         (map (rename_bterm r) bs)\n         (rename_opabs r oa)\n         vars\n         (rename_soterm r rhs)\n         (rename_correct r correct).\nProof.\n  introv fe; unfold found_entry in *.\n  revert abs bs oa vars rhs correct fe.\n  induction lib; introv fe; simpl in *; ginv.\n  destruct a; simpl in *.\n  boolvar; ginv; tcsp.\n\n  - inversion fe; subst; GC.\n    assert (correct0 = correct) as xx by (eauto 3 with pi).\n    subst; GC; auto.\n\n  - apply (implies_matching_entry_rename r) in m.\n    autorewrite with slow in *.\n    apply not_matching_entry_iff in n; destruct n.\n    allrw map_map; unfold compose in *.\n    assert (map (fun x => rename_bterm r (rename_bterm r x)) bs = bs) as xx; try congruence.\n    apply eq_map_l; introv i; destruct x; simpl; autorewrite with slow; auto.\n\n  - apply (implies_matching_entry_rename r) in m.\n    apply not_matching_entry_iff in n; destruct n; auto.\nQed.\n\nLemma compute_step_rename {o} :\n  forall r lib (a b : @NTerm o),\n    compute_step lib a = csuccess b\n    -> compute_step (rename_lib r lib) (rename_term r a) = csuccess (rename_term r b).\nProof.\n  nterm_ind1s a as [v|f ind|op bs ind] Case; introv comp; simpl in *.\n\n  - Case \"vterm\".\n\n    csunf comp; simpl in *; ginv.\n\n  - Case \"sterm\".\n\n    csunf comp; simpl in *; ginv.\n    simpl in *.\n    csunf; simpl; auto.\n\n  - Case \"oterm\".\n\n    dopid op as [can|ncan|exc|abs] SCase.\n\n    + SCase \"Can\".\n\n      csunf comp; simpl in *; ginv.\n      csunf; simpl; auto.\n\n    + SCase \"NCan\".\n\n      destruct bs as [|w]; try (complete (allsimpl; ginv)).\n      destruct w as [l t]; try (complete (allsimpl; ginv)).\n      destruct l; try (complete (allsimpl; ginv));[|].\n\n      {\n        destruct t as [x|f|op bts]; try (complete (allsimpl; ginv)); [|].\n\n        - csunf comp; allsimpl.\n          dopid_noncan ncan SSCase; allsimpl; ginv.\n\n          + SSCase \"NApply\".\n\n            apply compute_step_seq_apply_success in comp; exrepnd; subst; allsimpl; tcsp.\n\n          + SSCase \"NEApply\".\n\n            apply compute_step_eapply_success in comp; exrepnd; subst; allsimpl; tcsp.\n            repndors; repnd; subst; tcsp.\n\n            * apply compute_step_eapply2_success in comp1; repnd.\n              subst; simpl in *.\n              repndors; exrepnd; ginv.\n              csunf; simpl.\n              unfold compute_step_eapply; simpl; boolvar; try omega.\n              allrw @Znat.Nat2Z.id; auto.\n\n            * csunf; simpl.\n              applydup @isexc_implies2 in comp0; exrepnd; subst.\n              unfold compute_step_eapply; simpl; auto.\n\n            * exrepnd; subst; simpl in *.\n              fold_terms.\n              rewrite compute_step_eapply_iscan_isnoncan_like; eauto 3 with slow;[].\n              pose proof (ind arg2 arg2 []) as q; clear ind.\n              repeat (autodimp q hyp); eauto 3 with slow;[].\n              apply q in comp1; clear q.\n              rewrite comp1; auto.\n\n          + SSCase \"NFix\".\n\n            apply compute_step_fix_success in comp; repnd; subst; simpl in *.\n            csunf; simpl; auto.\n\n          + SSCase \"NCbv\".\n\n            apply compute_step_cbv_success in comp; exrepnd; subst; simpl in *.\n            csunf; simpl.\n            unfold apply_bterm; simpl.\n            rewrite rename_term_subst; auto.\n\n          + SSCase \"NTryCatch\".\n\n            apply compute_step_try_success in comp; exrepnd; subst; tcsp.\n\n          + SSCase \"NCanTest\".\n\n            apply compute_step_seq_can_test_success in comp; exrepnd; subst; tcsp.\n\n        - dopid op as [can2|ncan2|exc2|abs2] SSCase.\n\n          + SSCase \"Can\".\n            dopid_noncan ncan SSSCase.\n\n            {\n              SSSCase \"NApply\".\n\n              csunf comp; simpl in comp.\n              apply compute_step_apply_success in comp; repndors; exrepnd; subst; tcsp.\n              csunf; simpl; unfold apply_bterm; simpl.\n              rewrite rename_term_subst; auto.\n            }\n\n            {\n              SSSCase \"NEApply\".\n\n              csunf comp; simpl in comp.\n\n              apply compute_step_eapply_success in comp; exrepnd; subst; allsimpl; tcsp.\n              repndors; repnd; subst; tcsp.\n\n              - apply compute_step_eapply2_success in comp1; repnd.\n                subst; simpl in *.\n                repndors; exrepnd; subst; ginv; tcsp;[|].\n\n                + unfold mk_lam in *; ginv; simpl.\n                  fold_terms; unfold mk_eapply.\n                  rewrite compute_step_eapply_lam_iscan; eauto 3 with slow;[].\n                  unfold apply_bterm; simpl.\n                  rewrite rename_term_lsubst; auto.\n\n                + unfold mk_nseq in *; ginv; simpl.\n                  fold_terms; unfold mk_eapply.\n                  csunf; simpl.\n                  unfold compute_step_eapply; simpl; boolvar; try omega.\n                  allrw @Znat.Nat2Z.id; auto.\n\n              - fold_terms; unfold mk_eapply.\n                rewrite compute_step_eapply_iscan_isexc; eauto 3 with slow.\n                apply (eapply_wf_def_rename_term r) in comp2; simpl in comp2; auto.\n\n              - exrepnd; subst; simpl in *.\n                fold_terms.\n                apply (eapply_wf_def_rename_term r) in comp2; simpl in comp2; auto.\n                rewrite compute_step_eapply_iscan_isnoncan_like; eauto 3 with slow.\n                pose proof (ind arg2 arg2 []) as q; clear ind.\n                repeat (autodimp q hyp); eauto 3 with slow;[].\n                apply q in comp1; clear q.\n                rewrite comp1; auto.\n            }\n\n            {\n              SSSCase \"NFix\".\n\n              csunf comp; simpl in comp.\n              apply compute_step_fix_success in comp; repnd; subst; simpl; tcsp.\n            }\n\n            {\n              SSSCase \"NSpread\".\n\n              csunf comp; simpl in comp.\n              apply compute_step_spread_success in comp; exrepnd; subst; simpl; tcsp.\n              csunf; simpl; unfold apply_bterm.\n              rewrite rename_term_lsubst; simpl; tcsp.\n            }\n\n            {\n              SSSCase \"NDsup\".\n\n              csunf comp; simpl in comp.\n              apply compute_step_dsup_success in comp; exrepnd; subst; simpl; tcsp.\n              csunf; simpl; unfold apply_bterm.\n              rewrite rename_term_lsubst; simpl; tcsp.\n            }\n\n            {\n              SSSCase \"NDecide\".\n\n              csunf comp; simpl in comp.\n              apply compute_step_decide_success in comp; exrepnd; subst; simpl; tcsp.\n              csunf; simpl; unfold apply_bterm.\n              repndors; exrepnd; subst; simpl; rewrite rename_term_subst; simpl; tcsp.\n            }\n\n            {\n              SSSCase \"NCbv\".\n\n              csunf comp; simpl in comp.\n              apply compute_step_cbv_success in comp; exrepnd; subst; simpl; tcsp.\n              csunf; simpl; unfold apply_bterm.\n              repndors; exrepnd; subst; simpl; rewrite rename_term_subst; simpl; tcsp.\n            }\n\n            {\n              SSSCase \"NSleep\".\n\n              csunf comp; simpl in comp.\n              apply compute_step_sleep_success in comp; exrepnd; subst; simpl; tcsp.\n            }\n\n            {\n              SSSCase \"NTUni\".\n\n              csunf comp; simpl in comp.\n              apply compute_step_tuni_success in comp; exrepnd; subst; simpl; tcsp.\n              csunf; simpl; tcsp.\n              unfold compute_step_tuni; simpl; boolvar; try omega.\n              allrw @Znat.Nat2Z.id; auto.\n            }\n\n            {\n              SSSCase \"NMinus\".\n\n              csunf comp; simpl in comp.\n              apply compute_step_minus_success in comp; exrepnd; subst; simpl; tcsp.\n            }\n\n            {\n              SSSCase \"NFresh\".\n\n              csunf comp; simpl in comp; ginv.\n            }\n\n            {\n              SSSCase \"NTryCatch\".\n\n              csunf comp; simpl in comp.\n              apply compute_step_try_success in comp; exrepnd; subst; simpl; tcsp.\n            }\n\n            {\n              SSSCase \"NParallel\".\n\n              csunf comp; simpl in comp; ginv.\n              apply compute_step_parallel_success in comp; exrepnd; subst; simpl; tcsp.\n            }\n\n            {\n              SSSCase \"NCompOp\".\n\n              apply compute_step_ncompop_can1_success in comp; repnd.\n              repndors; exrepnd; subst; simpl; tcsp.\n\n              - apply compute_step_compop_success_can_can in comp1; exrepnd; subst; GC; ginv.\n                repndors; exrepnd; subst;\n                  csunf; simpl; dcwf h;\n                    unfold compute_step_comp; simpl; allrw; boolvar; auto.\n\n              - rewrite compute_step_ncompop_ncanlike2; eauto 3 with slow;[].\n                simpl in *; dcwf h;[].\n                pose proof (ind t t []) as q; clear ind; repeat (autodimp q hyp); eauto 3 with slow.\n                apply q in comp4; clear q.\n                rewrite comp4; auto.\n\n              - apply isexc_implies2 in comp1; exrepnd; subst; simpl in *.\n                csunf; simpl; dcwf h; auto.\n            }\n\n            {\n              SSSCase \"NArithOp\".\n\n              apply compute_step_narithop_can1_success in comp; repnd.\n              repndors; exrepnd; subst; simpl; tcsp.\n\n              - apply compute_step_arithop_success_can_can in comp1; exrepnd; subst; GC; ginv.\n                repndors; exrepnd; subst;\n                  csunf; simpl; dcwf h;\n                    unfold compute_step_arith; simpl; allrw; boolvar; auto.\n\n              - rewrite compute_step_narithop_ncanlike2; eauto 3 with slow;[].\n                simpl in *; dcwf h;[].\n                pose proof (ind t t []) as q; clear ind; repeat (autodimp q hyp); eauto 3 with slow.\n                apply q in comp4; clear q.\n                rewrite comp4; auto.\n\n              - apply isexc_implies2 in comp1; exrepnd; subst; simpl in *.\n                csunf; simpl; dcwf h; auto.\n            }\n\n            {\n              SSSCase \"NCanTest\".\n\n              csunf comp; simpl in *.\n              apply compute_step_can_test_success in comp; exrepnd; subst; simpl in *.\n              csunf; simpl.\n              destruct (canonical_form_test_for c can2); auto.\n            }\n\n          + SSCase \"NCan\".\n\n            csunf comp; simpl in *.\n            remember (compute_step lib (oterm (NCan ncan2) bts)) as comp'; symmetry in Heqcomp'.\n            destruct comp'; simpl in *; ginv;[].\n            pose proof (ind (oterm (NCan ncan2) bts) (oterm (NCan ncan2) bts) []) as q; clear ind.\n            repeat (autodimp q hyp); eauto 3 with slow.\n            apply q in Heqcomp'; clear q.\n            csunf; simpl in *.\n            rewrite Heqcomp'; simpl; auto.\n\n          + SSCase \"Exc\".\n\n            csunf comp; simpl in *.\n            apply compute_step_catch_success in comp; repndors; exrepnd; subst; simpl in *; tcsp.\n\n            * csunf; simpl.\n              rewrite rename_term_subst; auto.\n\n            * csunf; simpl.\n              rewrite compute_step_catch_if_diff; auto.\n\n          + SSCase \"Abs\".\n\n            csunf comp; simpl in *.\n            remember (compute_step lib (oterm (Abs abs2) bts)) as comp'; symmetry in Heqcomp'.\n            destruct comp'; simpl in *; ginv;[].\n            pose proof (ind (oterm (Abs abs2) bts) (oterm (Abs abs2) bts) []) as q; clear ind.\n            repeat (autodimp q hyp); eauto 3 with slow.\n            apply q in Heqcomp'; clear q.\n            csunf; simpl in *.\n            rewrite Heqcomp'; simpl; auto.\n      }\n\n      {\n        (* fresh *)\n\n        csunf comp; simpl in comp.\n        apply compute_step_fresh_success in comp; exrepnd; subst; simpl in *.\n        repndors; exrepnd; subst; tcsp.\n\n        - csunf; simpl; boolvar; auto.\n\n        - rewrite compute_step_fresh_if_isvalue_like2; eauto 3 with slow.\n          rewrite pushdown_fresh_rename_term; auto.\n\n        - pose proof (ind t (subst t n (mk_utoken (get_fresh_atom t))) [n]) as q; clear ind.\n          repeat (autodimp q hyp); eauto with slow;\n            try (complete (rewrite simple_osize_subst; simpl; auto; eauto 3 with slow)).\n          apply q in comp2; clear q.\n          rewrite computation3.compute_step_fresh_if_isnoncan_like; eauto 3 with slow.\n          rewrite rename_term_subst in comp2; simpl in *; autorewrite with slow in *.\n          fold_terms; rewrite comp2; simpl; auto.\n          rewrite rename_term_subst_utokens; auto.\n      }\n\n    + SCase \"Exc\".\n\n      csunf comp; simpl in comp; ginv.\n      csunf; simpl; auto.\n\n    + SCase \"Abs\".\n\n      csunf comp; simpl in comp.\n      apply compute_step_lib_success in comp; exrepnd; subst.\n      csunf; simpl.\n\n      apply (implies_found_entry_rename r) in comp0.\n      apply found_entry_implies_compute_step_lib_success in comp0.\n      rewrite comp0; clear comp0.\n      unfold mk_instance; simpl.\n\n      rewrite rename_term_sosub.\n      rewrite rename_sosub_mk_abs_subst; auto.\nQed.\n\nLemma reduces_to_rename {o} :\n  forall r lib (a b : @NTerm o),\n    reduces_to lib a b\n    -> reduces_to (rename_lib r lib) (rename_term r a) (rename_term r b).\nProof.\n  introv h; unfold reduces_to in *; exrepnd; exists k.\n  revert a b h0.\n  induction k; introv h.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst; auto.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    apply (compute_step_rename r) in h1.\n    apply IHk in h0.\n    allrw.\n    eexists; dands; eauto.\nQed.\nHint Resolve reduces_to_rename : slow.\n\nLemma nt_wf_rename_term {o} :\n  forall r (t : @NTerm o),\n    nt_wf t\n    -> nt_wf (rename_term r t).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv wf; simpl in *; auto.\n\n  - Case \"sterm\".\n    inversion wf as [|? imp|]; subst; clear wf.\n    constructor; introv.\n    pose proof (ind n) as q; clear ind.\n    pose proof (imp n) as h; clear imp.\n    repnd.\n    dands; eauto 3 with slow.\n\n  - Case \"oterm\".\n    allrw @nt_wf_oterm_iff; repnd.\n    allrw map_map; unfold compose; simpl in *.\n    autorewrite with slow.\n    rewrite <- wf0.\n    dands.\n\n    + apply eq_maps; introv i; destruct x; simpl; tcsp.\n\n    + introv i.\n      allrw in_map_iff; exrepnd; subst; simpl in *.\n      destruct a; simpl in *.\n      applydup wf in i1.\n      apply ind in i1; auto.\n      allrw @bt_wf_iff; auto.\nQed.\nHint Resolve nt_wf_rename_term : slow.\n\nLemma isprogram_rename_term {o} :\n  forall r (t : @NTerm o),\n    isprogram t\n    -> isprogram (rename_term r t).\nProof.\n  introv isp.\n  unfold isprogram in *; repnd; dands; eauto 3 with slow.\nQed.\nHint Resolve isprogram_rename_term : slow.\n\nLemma isvalue_rename_term {o} :\n  forall r (t : @NTerm o),\n    isvalue t\n    -> isvalue (rename_term r t).\nProof.\n  introv isv.\n  allrw @isvalue_iff; repnd; dands; eauto 3 with slow.\nQed.\nHint Resolve isvalue_rename_term : slow.\n\nLemma computes_to_value_rename {o} :\n  forall r lib (a b : @NTerm o),\n    computes_to_value lib a b\n    -> computes_to_value (rename_lib r lib) (rename_term r a) (rename_term r b).\nProof.\n  introv comp.\n  unfold computes_to_value in *; repnd; dands; eauto 3 with slow.\nQed.\nHint Resolve computes_to_value_rename : slow.\n\nLemma computes_to_valc_rename {o} :\n  forall r lib (a b : @CTerm o),\n    computes_to_valc lib a b\n    -> computes_to_valc (rename_lib r lib) (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; destruct_cterms; unfold computes_to_valc; simpl; eauto 3 with slow.\nQed.\nHint Resolve computes_to_valc_rename : slow.\n\nLemma rename_cterm_mkc_uni {o} :\n  forall r j, @rename_cterm o r (mkc_uni j) = mkc_uni j.\nProof.\n  introv; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_uni : slow.\n\nLemma rename_cterm_mkc_integer {o} :\n  forall r j, @rename_cterm o r (mkc_integer j) = mkc_integer j.\nProof.\n  introv; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_integer : slow.\n\nLemma rename_cterm_mkc_token {o} :\n  forall r j, @rename_cterm o r (mkc_token j) = mkc_token j.\nProof.\n  introv; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_token : slow.\n\nLemma rename_cterm_mkc_utoken {o} :\n  forall r j, @rename_cterm o r (mkc_utoken j) = mkc_utoken j.\nProof.\n  introv; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_utoken : slow.\n\nLemma rename_cterm_mkc_equality {o} :\n  forall r (a b c : @CTerm o),\n    rename_cterm r (mkc_equality a b c)\n    = mkc_equality (rename_cterm r a) (rename_cterm r b) (rename_cterm r c).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_equality : slow.\n\nLemma rename_cterm_mkc_free_from_atom {o} :\n  forall r (a b c : @CTerm o),\n    rename_cterm r (mkc_free_from_atom a b c)\n    = mkc_free_from_atom (rename_cterm r a) (rename_cterm r b) (rename_cterm r c).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_free_from_atom : slow.\n\nLemma rename_cterm_mkc_efree_from_atom {o} :\n  forall r (a b c : @CTerm o),\n    rename_cterm r (mkc_efree_from_atom a b c)\n    = mkc_efree_from_atom (rename_cterm r a) (rename_cterm r b) (rename_cterm r c).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_efree_from_atom : slow.\n\nLemma rename_cterm_mkc_free_from_atoms {o} :\n  forall r (a b : @CTerm o),\n    rename_cterm r (mkc_free_from_atoms a b)\n    = mkc_free_from_atoms (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_free_from_atoms : slow.\n\nLemma rename_cterm_mkc_apply {o} :\n  forall r (a b : @CTerm o),\n    rename_cterm r (mkc_apply a b)\n    = mkc_apply (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_apply : slow.\n\nLemma rename_cterm_mkc_apply2 {o} :\n  forall r (a b c : @CTerm o),\n    rename_cterm r (mkc_apply2 a b c)\n    = mkc_apply2 (rename_cterm r a) (rename_cterm r b) (rename_cterm r c).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_apply2 : slow.\n\nLemma rename_cterm_mkc_sup {o} :\n  forall r (a b : @CTerm o),\n    rename_cterm r (mkc_sup a b)\n    = mkc_sup (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_sup : slow.\n\nLemma rename_cterm_mkc_texc {o} :\n  forall r (a b : @CTerm o),\n    rename_cterm r (mkc_texc a b)\n    = mkc_texc (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_texc : slow.\n\nLemma rename_cterm_mkc_union {o} :\n  forall r (a b : @CTerm o),\n    rename_cterm r (mkc_union a b)\n    = mkc_union (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_union : slow.\n\nLemma rename_cterm_mkc_image {o} :\n  forall r (a b : @CTerm o),\n    rename_cterm r (mkc_image a b)\n    = mkc_image (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_image : slow.\n\nLemma rename_cterm_mkc_exception {o} :\n  forall r (a b : @CTerm o),\n    rename_cterm r (mkc_exception a b)\n    = mkc_exception (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_exception : slow.\n\nLemma rename_cterm_mkc_refl {o} :\n  forall r (a : @CTerm o),\n    rename_cterm r (mkc_refl a)\n    = mkc_refl (rename_cterm r a).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_refl : slow.\n\nLemma rename_cterm_mkc_inl {o} :\n  forall r (a : @CTerm o),\n    rename_cterm r (mkc_inl a)\n    = mkc_inl (rename_cterm r a).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_inl : slow.\n\nLemma rename_cterm_mkc_pertype {o} :\n  forall r (a : @CTerm o),\n    rename_cterm r (mkc_pertype a)\n    = mkc_pertype (rename_cterm r a).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_pertype : slow.\n\nLemma rename_cterm_mkc_ipertype {o} :\n  forall r (a : @CTerm o),\n    rename_cterm r (mkc_ipertype a)\n    = mkc_ipertype (rename_cterm r a).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_ipertype : slow.\n\nLemma rename_cterm_mkc_spertype {o} :\n  forall r (a : @CTerm o),\n    rename_cterm r (mkc_spertype a)\n    = mkc_spertype (rename_cterm r a).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_spertype : slow.\n\nLemma rename_cterm_mkc_inr {o} :\n  forall r (a : @CTerm o),\n    rename_cterm r (mkc_inr a)\n    = mkc_inr (rename_cterm r a).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_inr : slow.\n\nLemma rename_cterm_mkc_partial {o} :\n  forall r (a : @CTerm o),\n    rename_cterm r (mkc_partial a)\n    = mkc_partial (rename_cterm r a).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_partial : slow.\n\nLemma rename_cterm_mkc_mono {o} :\n  forall r (a : @CTerm o),\n    rename_cterm r (mkc_mono a)\n    = mkc_mono (rename_cterm r a).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_mono : slow.\n\nLemma rename_cterm_mkc_admiss {o} :\n  forall r (a : @CTerm o),\n    rename_cterm r (mkc_admiss a)\n    = mkc_admiss (rename_cterm r a).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_admiss : slow.\n\nLemma rename_cterm_mkc_requality {o} :\n  forall r (a b c : @CTerm o),\n    rename_cterm r (mkc_requality a b c)\n    = mkc_requality (rename_cterm r a) (rename_cterm r b) (rename_cterm r c).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_requality : slow.\n\nLemma rename_cterm_mkc_tequality {o} :\n  forall r (a b : @CTerm o),\n    rename_cterm r (mkc_tequality a b)\n    = mkc_tequality (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_tequality : slow.\n\nLemma rename_cterm_mkc_pair {o} :\n  forall r (a b : @CTerm o),\n    rename_cterm r (mkc_pair a b)\n    = mkc_pair (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_pair : slow.\n\nLemma rename_cterm_mkc_int {o} :\n  forall r, @rename_cterm o r mkc_int = mkc_int.\nProof.\n  introv; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_int : slow.\n\nLemma rename_cterm_mkc_base {o} :\n  forall r, @rename_cterm o r mkc_base = mkc_base.\nProof.\n  introv; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_base : slow.\n\nLemma rename_cterm_mkc_atom {o} :\n  forall r, @rename_cterm o r mkc_atom = mkc_atom.\nProof.\n  introv; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_atom : slow.\n\nLemma rename_cterm_mkc_uatom {o} :\n  forall r, @rename_cterm o r mkc_uatom = mkc_uatom.\nProof.\n  introv; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_uatom : slow.\n\nLemma rename_cterm_mkc_axiom {o} :\n  forall r, @rename_cterm o r mkc_axiom = mkc_axiom.\nProof.\n  introv; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_axiom : slow.\n\nLemma implies_alpha_eq_term_rename {o} :\n  forall r (a b : @NTerm o),\n    alpha_eq a b\n    -> alpha_eq (rename_term r a) (rename_term r b).\nProof.\n  nterm_ind1s a as [v|f|op bs ind] Case; introv aeq.\n\n  - Case \"vterm\".\n    inversion aeq; subst; clear aeq; simpl; auto.\n\n  - Case \"sterm\".\n    inversion aeq as [|? ? imp|]; subst; clear aeq; simpl; auto.\n\n  - Case \"oterm\".\n    apply alpha_eq_oterm_implies_combine in aeq; exrepnd; subst; simpl.\n    apply alpha_eq_oterm_combine; repeat (rewrite map_length in * ); dands; auto.\n    introv i.\n    rewrite <- map_combine in i.\n    allrw in_map_iff; exrepnd; ginv.\n    applydup aeq0 in i1; clear aeq0.\n    destruct a0, a; simpl in *.\n    inversion i0 as [? ? ? ? ? disj len1 len2 norep aeq]; subst.\n    applydup in_combine in i1; repnd.\n\n    pose proof (ind n (lsubst n (var_ren l lv)) l) as q; clear ind.\n    rewrite lsubst_allvars_preserves_osize2 in q.\n    repeat (autodimp q hyp); eauto 2 with slow.\n    apply q in aeq; clear q.\n    repeat (rewrite @rename_term_lsubst in * ).\n    autorewrite with slow in *.\n    exists lv; autorewrite with slow in *; auto.\nQed.\nHint Resolve implies_alpha_eq_term_rename : slow.\n\nLemma implies_alpha_eq_bterm_rename {o} :\n  forall r (a b : @BTerm o),\n    alpha_eq_bterm a b\n    -> alpha_eq_bterm (rename_bterm r a) (rename_bterm r b).\nProof.\n  introv aeq.\n    destruct a as [l1 t1], b as [l2 t2]; simpl in *.\n    inversion aeq as [? ? ? ? ? disj len1 len2 norep aeq']; subst; clear aeq.\n    exists lv; autorewrite with slow in *; auto.\n    apply (implies_alpha_eq_term_rename r) in aeq'.\n    repeat (rewrite @rename_term_lsubst in * ); autorewrite with slow in *; auto.\nQed.\nHint Resolve implies_alpha_eq_bterm_rename : slow.\n\nLemma rename_bterm_idem {o} :\n  forall r (b : @BTerm o),\n    rename_bterm r (rename_bterm r b) = b.\nProof.\n  introv; destruct b as [l t]; simpl; autorewrite with slow; auto.\nQed.\nHint Rewrite @rename_bterm_idem : slow.\n\nLemma rename_sub_idem {o} :\n  forall r (s : @Sub o),\n    rename_sub r (rename_sub r s) = s.\nProof.\n  induction s; introv; repnd; simpl; autorewrite with slow; allrw; auto.\nQed.\nHint Rewrite @rename_sub_idem : slow.\n\nLemma implies_wf_sub_rename {o} :\n  forall r (sub : @Sub o),\n    wf_sub sub\n    -> wf_sub (rename_sub r sub).\nProof.\n  induction sub; introv wf; simpl in *; auto; repnd.\n  allrw @wf_sub_cons_iff; repnd; dands; auto; eauto 2 with slow.\nQed.\nHint Resolve implies_wf_sub_rename : slow.\n\nLemma computes_to_exception_rename {o} :\n  forall r lib (a b c : @NTerm o),\n    computes_to_exception lib a b c\n    -> computes_to_exception (rename_lib r lib) (rename_term r a) (rename_term r b) (rename_term r c).\nProof.\n  introv comp.\n  unfold computes_to_exception in *.\n  apply (reduces_to_rename r) in comp; simpl in *; auto.\nQed.\nHint Resolve computes_to_exception_rename : slow.\n\nDefinition rename_seq {o} r (f : @ntseq o) : ntseq :=\n  fun n => rename_term r (f n).\n\nLemma computes_to_seq_rename {o} :\n  forall r lib (a : @NTerm o) f,\n    computes_to_seq lib a f\n    -> computes_to_seq (rename_lib r lib) (rename_term r a) (rename_seq r f).\nProof.\n  introv comp.\n  unfold computes_to_exception in *.\n  apply (reduces_to_rename r) in comp; simpl in *; auto.\nQed.\nHint Resolve computes_to_seq_rename : slow.\n\nLemma implies_approx_rename {o} :\n  forall r lib (a b : @NTerm o),\n    approx lib a b\n    -> approx (rename_lib r lib) (rename_term r a) (rename_term r b).\nProof.\n  cofix IND; introv apr.\n  inversion apr as [cl]; clear apr.\n  constructor.\n  unfold close_comput in *.\n  repnd; dands; eauto 2 with slow.\n\n  - clear cl3 cl4 cl.\n    unfold close_compute_val in *.\n    introv comp.\n    apply (computes_to_value_rename r) in comp; simpl in *.\n    autorewrite with slow in *.\n\n    apply cl2 in comp; clear cl2.\n    exrepnd.\n    apply (computes_to_value_rename r) in comp1; simpl in *.\n    eexists; dands; eauto.\n\n    unfold lblift in *.\n    rewrite map_length in *.\n    repnd; dands; auto.\n    introv h.\n    applydup comp0 in h; clear comp0.\n\n    rewrite selectbt_map; try omega.\n    rewrite selectbt_map in h0; auto.\n\n    remember (tl_subterms {[n]}) as u.\n    remember (tr_subterms {[n]}) as v.\n    clear Hequ Heqv.\n\n    unfold blift in *; exrepnd.\n    exists lv (rename_term r nt1) (rename_term r nt2).\n\n    dands;\n      try (complete (apply (implies_alpha_eq_bterm_rename r) in h2; simpl in *; autorewrite with slow in *; auto));\n      try (complete (apply (implies_alpha_eq_bterm_rename r) in h1; simpl in *; autorewrite with slow in *; auto));[].\n\n    unfold olift in *; repnd; dands; eauto 2 with slow;[].\n\n    introv wf isp1 isp2.\n    pose proof (h0 (rename_sub r sub)) as q.\n    repeat (autodimp q hyp); eauto 2 with slow;\n      try (complete (apply (isprogram_rename_term r) in isp1;rewrite rename_term_lsubst in isp1;autorewrite with slow in isp1;auto));\n      try (complete (apply (isprogram_rename_term r) in isp2;rewrite rename_term_lsubst in isp2;autorewrite with slow in isp2;auto));[].\n\n    repndors; tcsp;[].\n    left.\n    apply (IND r) in q.\n    repeat (rewrite @rename_term_lsubst in * ).\n    autorewrite with slow in *; auto.\n\n  - clear cl2 cl4 cl.\n    unfold close_compute_exc in *.\n    introv comp.\n    apply (computes_to_exception_rename r) in comp; simpl in *.\n    autorewrite with slow in *.\n\n    apply cl3 in comp; clear cl3.\n    exrepnd.\n    apply (computes_to_exception_rename r) in comp0; simpl in *.\n    eexists; eexists; dands; eauto.\n\n    + clear comp1.\n      repndors; tcsp; left.\n      apply (IND r) in comp2.\n      repeat (rewrite @rename_term_lsubst in * ).\n      autorewrite with slow in *; auto.\n\n    + clear comp2.\n      repndors; tcsp; left.\n      apply (IND r) in comp1.\n      repeat (rewrite @rename_term_lsubst in * ).\n      autorewrite with slow in *; auto.\n\n  - clear cl2 cl3 cl.\n    unfold close_compute_exc in *.\n    introv comp.\n    apply (computes_to_seq_rename r) in comp; simpl in *.\n    autorewrite with slow in *.\n\n    apply cl4 in comp; clear cl4.\n    exrepnd.\n    apply (computes_to_seq_rename r) in comp1; simpl in *.\n    eexists; dands; eauto.\n\n    introv.\n    pose proof (comp0 n) as q; clear comp0; repndors; tcsp.\n    left.\n    apply (IND r) in q.\n    unfold rename_seq in *.\n    autorewrite with slow in *.\n    auto.\nQed.\nHint Resolve implies_approx_rename : slow.\n\nLemma implies_approxc_rename {o} :\n  forall r lib (a b : @CTerm o),\n    approxc lib a b\n    -> approxc (rename_lib r lib) (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv ceq; destruct_cterms; unfold approxc in *; simpl in *; eauto 3 with slow.\nQed.\nHint Resolve implies_approxc_rename : slow.\n\nLemma implies_capproxc_rename {o} :\n  forall r lib (a b : @CTerm o),\n    capproxc lib a b\n    -> capproxc (rename_lib r lib) (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv apr; spcast; eauto 3 with slow.\nQed.\nHint Resolve implies_capproxc_rename : slow.\n\nLemma implies_cequivc_rename {o} :\n  forall r lib (a b : @CTerm o),\n    cequivc lib a b\n    -> cequivc (rename_lib r lib) (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv ceq; destruct_cterms; unfold cequivc in *; simpl in *.\n  destruct ceq as [ap1 ap2].\n  split; eauto 2 with slow.\nQed.\nHint Resolve implies_cequivc_rename : slow.\n\nLemma implies_ccequivc_rename {o} :\n  forall r lib (a b : @CTerm o),\n    ccequivc lib a b\n    -> ccequivc (rename_lib r lib) (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv apr; spcast; eauto 3 with slow.\nQed.\nHint Resolve implies_ccequivc_rename : slow.\n\nDefinition rename_cvterm {o} {vs} r (t : @CVTerm o vs) : CVTerm vs :=\n  let (u,isp) := t in\n  mk_cvterm vs (rename_term r u) (implies_isprog_vars_rename_term vs r u isp).\n\nLemma rename_cterm_isect {o} :\n  forall r (A : @CTerm o) v B,\n    rename_cterm r (mkc_isect A v B)\n    = mkc_isect (rename_cterm r A) v (rename_cvterm r B).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_isect : rename.\n\nLemma rename_cterm_disect {o} :\n  forall r (A : @CTerm o) v B,\n    rename_cterm r (mkc_disect A v B)\n    = mkc_disect (rename_cterm r A) v (rename_cvterm r B).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_disect : rename.\n\nLemma rename_cterm_function {o} :\n  forall r (A : @CTerm o) v B,\n    rename_cterm r (mkc_function A v B)\n    = mkc_function (rename_cterm r A) v (rename_cvterm r B).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_function : rename.\n\nLemma rename_cterm_set {o} :\n  forall r (A : @CTerm o) v B,\n    rename_cterm r (mkc_set A v B)\n    = mkc_set (rename_cterm r A) v (rename_cvterm r B).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_set : rename.\n\nLemma rename_cterm_product {o} :\n  forall r (A : @CTerm o) v B,\n    rename_cterm r (mkc_product A v B)\n    = mkc_product (rename_cterm r A) v (rename_cvterm r B).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_product : rename.\n\nLemma rename_cterm_tunion {o} :\n  forall r (A : @CTerm o) v B,\n    rename_cterm r (mkc_tunion A v B)\n    = mkc_tunion (rename_cterm r A) v (rename_cvterm r B).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_tunion : rename.\n\nLemma rename_cterm_w {o} :\n  forall r (A : @CTerm o) v B,\n    rename_cterm r (mkc_w A v B)\n    = mkc_w (rename_cterm r A) v (rename_cvterm r B).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_w : rename.\n\nLemma rename_cterm_m {o} :\n  forall r (A : @CTerm o) v B,\n    rename_cterm r (mkc_m A v B)\n    = mkc_m (rename_cterm r A) v (rename_cvterm r B).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_m : rename.\n\nLemma rename_cterm_substc {o} :\n  forall r (a : @CTerm o) v b,\n    rename_cterm r (substc a v b)\n    = substc (rename_cterm r a) v (rename_cvterm r b).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl.\n  rewrite rename_term_subst; auto.\nQed.\nHint Rewrite @rename_cterm_substc : rename.\n\nDefinition rename_per1 {o} (r : renaming) (e : per(o)) : per :=\n  fun a b =>\n    exists a' b',\n      a = rename_cterm r a'\n      /\\ b = rename_cterm r b'\n      /\\ e a' b'.\n\nDefinition rename_per {o} (r : renaming) (e : per(o)) : per :=\n  fun a b => e (rename_cterm r a) (rename_cterm r b).\n\nLemma rename_per_iff {o} :\n  forall r (e : per(o)), (rename_per r e) <=2=> (rename_per1 r e).\nProof.\n  repeat introv; unfold rename_per, rename_per1; simpl; split; intro h.\n\n  - exists (rename_cterm r t1) (rename_cterm r t2); autorewrite with slow; auto.\n\n  - exrepnd; subst; autorewrite with slow; auto.\nQed.\n\nDefinition rename_cts {o} (r : renaming) (ts : cts(o)) : cts :=\n  fun t1 t2 e => ts (rename_cterm r t1) (rename_cterm r t2) (rename_per r e).\n\nLemma rename_cterm_approx {o} :\n  forall r (a b : @CTerm o),\n    rename_cterm r (mkc_approx a b)\n    = mkc_approx (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_approx : rename.\n\nLemma rename_cterm_cequiv {o} :\n  forall r (a b : @CTerm o),\n    rename_cterm r (mkc_cequiv a b)\n    = mkc_cequiv (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_cequiv : rename.\n\nDefinition rename_per_fam {o} {ea : per(o)} r (eb : forall (a b : @CTerm o) (e : ea a b), per(o)) : per-fam(rename_per r ea) :=\n  fun (a b : @CTerm o) (e : rename_per r ea a b) =>\n    rename_per r (eb (rename_cterm r a) (rename_cterm r b) e).\n\nDefinition rename_fper {o} r (p : @CTerm o -> @CTerm o -> per(o)) :=\n  fun a b => rename_per r (p (rename_cterm r a) (rename_cterm r b)).\n\nLemma inhabited_rename_fper {o} :\n  forall r (p : @CTerm o -> @CTerm o -> per(o)) x y,\n    inhabited (rename_fper r p x y) <=> inhabited (p (rename_cterm r x) (rename_cterm r y)).\nProof.\n  introv; unfold inhabited, rename_fper, rename_per; split; introv h; exrepnd.\n  - eexists; eauto.\n  - exists (rename_cterm r t); autorewrite with slow; auto.\nQed.\n\nLemma is_per_rename_fper {o} :\n  forall r (p : @CTerm o -> @CTerm o -> per(o)),\n    is_per p -> is_per (rename_fper r p).\nProof.\n  introv isp.\n  unfold is_per in *; repnd.\n  dands; introv; repeat (rw @inhabited_rename_fper); tcsp;[].\n  introv inh1 inh2.\n  eapply isp; eauto.\nQed.\nHint Resolve is_per_rename_fper : slow.\n\nLemma implies_rename_per {o} :\n  forall r (e : per(o)) a b,\n    e a b -> rename_per r e (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv h; unfold rename_per; autorewrite with slow; auto.\nDefined.\nHint Resolve implies_rename_per : slow.\n\nLemma implies_weq_rename {o} :\n  forall r lib eqa eqb (t1 t2 : @CTerm o),\n    weq lib eqa eqb t1 t2\n    -> weq (rename_lib r lib) (rename_per r eqa) (rename_per_fam r eqb) (rename_cterm r t1) (rename_cterm r t2).\nProof.\n  introv w; induction w as [? ? ? ? ? ? ea c1 c2 ha hb]; spcast.\n  apply (computes_to_valc_rename r) in c1.\n  apply (computes_to_valc_rename r) in c2.\n  autorewrite with slow rename in *.\n  apply (weq_cons\n           (rename_lib r lib)\n           (rename_per r eqa)\n           (rename_per_fam r eqb)\n           (rename_cterm r t)\n           (rename_cterm r t')\n           (rename_cterm r a)\n           (rename_cterm r f)\n           (rename_cterm r a')\n           (rename_cterm r f')\n           (implies_rename_per r eqa a a' ea)); spcast; auto.\n  introv w.\n  unfold rename_per_fam, rename_per in w; autorewrite with slow rename in w.\n  unfold implies_rename_per in w; simpl in w.\n  rewrite (rename_cterm_idem r a) in w.\n  rewrite (rename_cterm_idem r a') in w.\n  unfold eq_ind_r in w; simpl in w.\n  apply hb in w; autorewrite with slow in *; auto.\nQed.\nHint Resolve implies_weq_rename : slow.\n\nLemma implies_meq_rename {o} :\n  forall r lib eqa eqb (t1 t2 : @CTerm o),\n    meq lib eqa eqb t1 t2\n    -> meq (rename_lib r lib) (rename_per r eqa) (rename_per_fam r eqb) (rename_cterm r t1) (rename_cterm r t2).\nProof.\n  cofix IND.\n  introv m.\n  destruct m as [? ? ? ? ea c1 c2 hb]; spcast.\n  apply (computes_to_valc_rename r) in c1.\n  apply (computes_to_valc_rename r) in c2.\n  autorewrite with slow rename in *.\n  apply (meq_cons\n           (rename_lib r lib)\n           (rename_per r eqa)\n           (rename_per_fam r eqb)\n           (rename_cterm r t1)\n           (rename_cterm r t2)\n           (rename_cterm r a)\n           (rename_cterm r f)\n           (rename_cterm r a')\n           (rename_cterm r f')\n           (implies_rename_per r eqa a a' ea)); spcast; auto.\n  introv w.\n  unfold rename_per_fam, rename_per in w; autorewrite with slow rename in w.\n  unfold implies_rename_per in w; simpl in w.\n  rewrite (rename_cterm_idem r a) in w.\n  rewrite (rename_cterm_idem r a') in w.\n  unfold eq_ind_r in w; simpl in w.\n  apply hb in w; autorewrite with slow in *; auto.\n  apply (IND r) in w; autorewrite with slow in *; auto.\nQed.\nHint Resolve implies_meq_rename : slow.\n\nLemma rename_computes_to_excc {o} :\n  forall r lib (n t e : @CTerm o),\n    computes_to_excc lib n t e\n    -> computes_to_excc (rename_lib r lib) (rename_cterm r n) (rename_cterm r t) (rename_cterm r e).\nProof.\n  introv comp.\n  destruct_cterms; unfold computes_to_excc in *; simpl in *.\n  apply (computes_to_exception_rename r) in comp; auto.\nQed.\n\nLemma rename_per_image_eq {o} :\n  forall r lib eqa (a b c : @CTerm o),\n    per_image_eq (rename_lib r lib) (rename_per r eqa) (rename_cterm r a) (rename_cterm r b) (rename_cterm r c)\n    <=> per_image_eq lib eqa a b c.\nProof.\n  introv; split; introv h.\n\n  - remember (rename_lib r lib) as lib'; revert lib Heqlib'.\n    remember (rename_cterm r a) as a'; revert a Heqa'.\n    remember (rename_cterm r b) as b'; revert b Heqb'.\n    remember (rename_cterm r c) as c'; revert c Heqc'.\n\n    induction h as [|? ? ? ? ? h1 h2]; introv e1 e2 e3 el; subst.\n\n    + pose proof (IHh1 (rename_cterm r t)) as q; autorewrite with slow in q; autodimp q hyp; clear IHh1.\n      pose proof (q b) as q; autodimp q hyp.\n      pose proof (q a) as q; autodimp q hyp.\n      pose proof (q lib) as q; autodimp q hyp.\n\n      pose proof (IHh2 c) as w; autodimp w hyp; clear IHh2.\n      pose proof (w (rename_cterm r t)) as w; autorewrite with slow in w; autodimp w hyp.\n      pose proof (w a) as w; autodimp w hyp.\n      pose proof (w lib) as w; autodimp w hyp.\n      econstructor; eauto.\n\n    + spcast.\n      apply (implies_cequivc_rename r) in h1.\n      apply (implies_cequivc_rename r) in h2.\n      autorewrite with slow in *.\n      eapply image_eq_eq; spcast; eauto.\n\n  - induction h as [|? ? ? ? ? h1 h2].\n\n    + econstructor; eauto.\n\n    + spcast.\n      apply (implies_cequivc_rename r) in h1.\n      apply (implies_cequivc_rename r) in h2.\n      autorewrite with slow in *.\n      eapply image_eq_eq; spcast; eauto.\n      unfold rename_per; autorewrite with slow; auto.\nQed.\nHint Resolve rename_per_image_eq : slow.\n\nLemma implies_rename_hasvaluec {o} :\n  forall r lib (a : @CTerm o),\n    hasvaluec lib a\n    -> hasvaluec (rename_lib r lib) (rename_cterm r a).\nProof.\n  unfold hasvaluec; introv hv; destruct_cterms; unfold hasvalue in *; simpl in *.\n  exrepnd.\n  apply (computes_to_value_rename r) in hv0.\n  eexists; eauto.\nQed.\nHint Resolve implies_rename_hasvaluec : slow.\n\nLemma chaltsc_rename_iff {o} :\n  forall r lib (a : @CTerm o),\n    chaltsc lib a <=> chaltsc (rename_lib r lib) (rename_cterm r a).\nProof.\n  introv; split; introv h; spcast.\n  - apply (implies_rename_hasvaluec r) in h; auto.\n  - apply (implies_rename_hasvaluec r) in h; autorewrite with slow in *; auto.\nQed.\n\nLemma implies_inhabited_rename_per_fam {o} :\n  forall r (ea : per(o)) (eb : per-fam(ea)) a b (e : ea (rename_cterm r a) (rename_cterm r b)),\n    inhabited (eb (rename_cterm r a) (rename_cterm r b) e)\n    -> inhabited (rename_per_fam r eb a b e).\nProof.\n  introv; unfold inhabited, rename_per_fam, rename_per.\n  introv h; exrepnd.\n  exists (rename_cterm r t); autorewrite with slow; auto.\nQed.\n\nLemma inhabited_rename_per_fam_implies {o} :\n  forall r (ea : per(o)) (eb : per-fam(ea)) a b (e : ea (rename_cterm r a) (rename_cterm r b)),\n    inhabited (rename_per_fam r eb a b e)\n    -> inhabited (eb (rename_cterm r a) (rename_cterm r b) e).\nProof.\n  introv; unfold inhabited, rename_per_fam, rename_per.\n  introv h; exrepnd.\n  exists (rename_cterm r t); autorewrite with slow; auto.\nQed.\n\nLemma rename_per_eq {o} :\n  forall r (e : per(o)) a b,\n    e a b = rename_per r e (rename_cterm r a) (rename_cterm r b).\nProof.\n  introv; unfold rename_per.\n  f_equal; rewrite @rename_cterm_idem; auto.\nDefined.\n\nLemma implies_rename_per_fam {o} :\n  forall r (eqa : per(o)) (eqb : per-fam(eqa)) a a' b b' (e : eqa a a'),\n    eqb a a' e b b'\n    -> rename_per_fam\n         r\n         eqb\n         (rename_cterm r a) (rename_cterm r a')\n         (implies_rename_per r eqa a a' e)\n         (rename_cterm r b) (rename_cterm r b').\nProof.\n  introv h.\n  unfold rename_per_fam, rename_per.\n  unfold implies_rename_per, eq_ind_r, eq_ind, eq_rect, eq_sym; simpl.\n  autorewrite with slow.\n\n  remember (rename_cterm_idem r a) as w; clear Heqw.\n  revert w; autorewrite with slow; introv.\n  rewrite (UIP_refl _ _ w); auto; clear w.\n\n  remember (rename_cterm_idem r a') as w; clear Heqw.\n  revert w; autorewrite with slow; introv.\n  rewrite (UIP_refl _ _ w); auto; clear w.\nDefined.\n\nLemma implies_rename_per_tunion_eq {o} :\n  forall r (ea : per(o)) (eb : per-fam(ea)) t1 t2,\n    per_tunion_eq ea eb t1 t2\n    -> per_tunion_eq (rename_per r ea) (rename_per_fam r eb) (rename_cterm r t1) (rename_cterm r t2).\nProof.\n  introv h.\n  induction h as [|? ? ? ? h1 h2].\n\n  - econstructor; eauto.\n\n  - apply (tunion_eq_eq _ _ _ _ (rename_cterm r a1) (rename_cterm r a2) (implies_rename_per r ea a1 a2 h1)).\n    apply implies_rename_per_fam; auto.\nQed.\n\nLemma eq_rename_per_idem {o} :\n  forall r (e : per(o)),\n    (rename_per r (rename_per r e)) <=2=> e.\nProof.\n  repeat introv; unfold rename_per; autorewrite with slow; auto.\nQed.\n\nLemma eq_rename_per_idem2 {o} :\n  forall r (e : per(o)) a b,\n    rename_per r (rename_per r e) a b = e a b.\nProof.\n  repeat introv; unfold rename_per; autorewrite with slow; auto.\nDefined.\n\nLemma eq_term_equals_per_tunion_eq_if2 {o} :\n  forall (eqa1 eqa2 : per(o)) (eqb1 : per-fam(eqa1)) (eqb2 : per-fam(eqa2))\n         (w : forall a b, eqa1 a b = eqa2 a b),\n    (forall (a1 a2 : CTerm) (e1 : eqa1 a1 a2),\n        (eqb1 a1 a2 e1) <=2=> (eqb2 a1 a2 (@eq_ind _ _ (fun x => x) e1 (eqa2 a1 a2) (w a1 a2))))\n    -> (forall (a1 a2 : CTerm) (e1 : eqa2 a1 a2),\n           (eqb2 a1 a2 e1) <=2=> (eqb1 a1 a2 (@eq_ind _ _ (fun x => x) e1 (eqa1 a1 a2) (eq_sym (w a1 a2)))))\n    -> (per_tunion_eq eqa1 eqb1) <=2=> (per_tunion_eq eqa2 eqb2).\nProof.\n  introv imp1 imp2.\n  introv; split; intro k; induction k.\n\n  - apply @tunion_eq_cl with (t := t); sp.\n\n  - apply @tunion_eq_eq with (a1 := a1) (a2 := a2) (e := (eq_ind (eqa1 a1 a2) (fun x : [U] => x) e (eqa2 a1 a2) (w a1 a2))); sp; spcast.\n    apply (imp1 a1 a2 e); auto.\n\n  - apply @tunion_eq_cl with (t := t); sp.\n\n  - apply @tunion_eq_eq with (a1 := a1) (a2 := a2) (e := (eq_ind (eqa2 a1 a2) (fun x : [U] => x) e (eqa1 a1 a2) (eq_sym (w a1 a2)))); sp; spcast.\n    apply (imp2 a1 a2 e); auto.\nQed.\n\nLemma rename_per_tunion_eq_implies {o} :\n  forall r (ea : per(o)) (eb : per-fam(ea)) t1 t2,\n    per_tunion_eq (rename_per r ea) (rename_per_fam r eb) (rename_cterm r t1) (rename_cterm r t2)\n    -> per_tunion_eq ea eb t1 t2.\nProof.\n  introv h.\n  apply (implies_rename_per_tunion_eq r) in h; autorewrite with slow in h.\n\n  eapply (eq_term_equals_per_tunion_eq_if2 _ _ _ _ (eq_rename_per_idem2 r ea));\n    [| |eauto]; repeat introv.\n\n  - unfold rename_per_fam, rename_per.\n    unfold eq_ind, eq_rect; simpl.\n    remember (eq_rename_per_idem2 r ea a1 a2) as w; clear Heqw.\n    revert e1 w.\n    unfold rename_per.\n    autorewrite with slow; introv.\n    rewrite (UIP_refl _ _ w); auto.\n\n  - unfold rename_per_fam, rename_per.\n    unfold eq_ind, eq_rect; simpl.\n    remember (eq_rename_per_idem2 r ea a1 a2) as w; clear Heqw.\n    revert e1 w.\n    unfold rename_per.\n    autorewrite with slow; introv.\n    rewrite (UIP_refl _ _ w); auto.\nQed.\n\nLemma implies_rename_per2 {o} :\n  forall r (e : per(o)) a b,\n    e (rename_cterm r a) (rename_cterm r b) -> rename_per r e a b.\nProof.\n  introv h; unfold rename_per; autorewrite with slow; auto.\nDefined.\n\nLemma weq_eq_term_equals2 {p} :\n  forall lib (eqa1 eqa2 : per(p)) eqb1 eqb2 t1 t2\n         (w : forall a b, eqa1 a b = eqa2 a b),\n    (forall (a1 a2 : CTerm) (e1 : eqa1 a1 a2),\n        (eqb1 a1 a2 e1) <=2=> (eqb2 a1 a2 (@eq_ind _ _ (fun x => x) e1 (eqa2 a1 a2) (w a1 a2))))\n    -> weq lib eqa1 eqb1 t1 t2\n    -> weq lib eqa2 eqb2 t1 t2.\nProof.\n  introv imp1 weqt.\n  induction weqt as [t t' a f a' f' e c c' h h'].\n  apply @weq_cons with (a := a) (a' := a') (f := f) (f' := f') (e := (eq_ind (eqa1 a a') (fun x => x) e (eqa2 a a') (w a a'))); sp.\n  apply h'.\n  apply imp1; auto.\nQed.\n\nLemma weq_rename_implies {o} :\n  forall r lib eqa eqb (t1 t2 : @CTerm o),\n    weq (rename_lib r lib) (rename_per r eqa) (rename_per_fam r eqb) (rename_cterm r t1) (rename_cterm r t2)\n    -> weq lib eqa eqb t1 t2.\nProof.\n  introv w.\n  apply (implies_weq_rename r) in w; autorewrite with slow in *.\n  eapply (weq_eq_term_equals2 _ _ _ _ _ _ _ (eq_rename_per_idem2 r eqa));[|eauto]; clear w.\n\n  repeat introv.\n  unfold rename_per_fam, rename_per.\n  unfold eq_ind, eq_rect; simpl.\n  remember (eq_rename_per_idem2 r eqa a1 a2) as w; clear Heqw.\n  revert e1 w.\n  unfold rename_per.\n  autorewrite with slow; introv.\n  rewrite (UIP_refl _ _ w); auto.\nQed.\nHint Resolve weq_rename_implies : slow.\n\nLemma meq_eq_term_equals2 {p} :\n  forall lib (eqa1 eqa2 : per(p)) eqb1 eqb2 t1 t2\n         (w : forall a b, eqa1 a b = eqa2 a b),\n    (forall (a1 a2 : CTerm) (e1 : eqa1 a1 a2),\n        (eqb1 a1 a2 e1) <=2=> (eqb2 a1 a2 (@eq_ind _ _ (fun x => x) e1 (eqa2 a1 a2) (w a1 a2))))\n    -> meq lib eqa1 eqb1 t1 t2\n    -> meq lib eqa2 eqb2 t1 t2.\nProof.\n  cofix IND.\n  introv imp1 weqt.\n  destruct weqt as [a f a' f' e c c' h].\n  apply @meq_cons with (a := a) (a' := a') (f := f) (f' := f') (e := (eq_ind (eqa1 a a') (fun x => x) e (eqa2 a a') (w a a'))); sp.\n  eapply IND;[|apply h]; auto.\n  apply imp1; auto.\nQed.\n\nLemma meq_rename_implies {o} :\n  forall r lib eqa eqb (t1 t2 : @CTerm o),\n    meq (rename_lib r lib) (rename_per r eqa) (rename_per_fam r eqb) (rename_cterm r t1) (rename_cterm r t2)\n    -> meq lib eqa eqb t1 t2.\nProof.\n  introv w.\n  apply (implies_meq_rename r) in w; autorewrite with slow in *.\n  eapply (meq_eq_term_equals2 _ _ _ _ _ _ _ (eq_rename_per_idem2 r eqa));[|eauto]; clear w.\n\n  repeat introv.\n  unfold rename_per_fam, rename_per.\n  unfold eq_ind, eq_rect; simpl.\n  remember (eq_rename_per_idem2 r eqa a1 a2) as w; clear Heqw.\n  revert e1 w.\n  unfold rename_per.\n  autorewrite with slow; introv.\n  rewrite (UIP_refl _ _ w); auto.\nQed.\nHint Resolve meq_rename_implies : slow.\n\nLemma getc_utokens_rename_cterm {o} :\n  forall (r : renaming) (t : @CTerm o),\n    getc_utokens (rename_cterm r t) = getc_utokens t.\nProof.\n  introv; destruct_cterms; unfold getc_utokens; simpl; autorewrite with slow; auto.\nQed.\nHint Rewrite @getc_utokens_rename_cterm : slow.\n\nLemma rename_name_not_in_upto {o} :\n  forall r lib (a x : @CTerm o) e,\n    name_not_in_upto (rename_lib r lib) (rename_cterm r a) (rename_cterm r x) (rename_per r e)\n                     <=> name_not_in_upto lib a x e.\nProof.\n  introv.\n  unfold name_not_in_upto; split; intro h; exrepnd; spcast.\n\n  - apply (computes_to_valc_rename r) in h0.\n    unfold rename_per in *; autorewrite with slow in *.\n    eexists; eexists; dands; spcast; eauto.\n    autorewrite with slow; auto.\n\n  - apply (computes_to_valc_rename r) in h0.\n    unfold rename_per in *; autorewrite with slow in *.\n    exists u (rename_cterm r y); dands; spcast; eauto; autorewrite with slow; auto.\nQed.\n\nLemma implies_noutokensc_rename_cterm {o} :\n  forall (r : renaming) (t : @CTerm o),\n    noutokensc t -> noutokensc (rename_cterm r t).\nProof.\n  introv nout; destruct_cterms; unfold noutokensc in *; simpl in *; eauto 3 with slow.\nQed.\nHint Resolve implies_noutokensc_rename_cterm : slow.\n\nLemma rename_cterm_fix_approxc {o} :\n  forall r k (f : @CTerm o),\n    rename_cterm r (fix_approxc k f) = fix_approxc k (rename_cterm r f).\nProof.\n  induction k; introv; simpl; auto.\n\n  - apply cterm_eq; simpl; auto.\n\n  - autorewrite with slow in *.\n    rewrite IHk; auto.\nQed.\n\nLemma rename_cterm_subst_fapproxc {o} :\n  forall r v (a : @CVTerm o [v]) f k,\n    rename_cterm r (subst_fapproxc a f k)\n    = subst_fapproxc (rename_cvterm r a) (rename_cterm r f) k.\nProof.\n  introv; unfold subst_fapproxc.\n  rewrite rename_cterm_substc; f_equal.\n  apply rename_cterm_fix_approxc.\nQed.\n\nLemma rename_cvterm_idem {o} :\n  forall r vs (t : @CVTerm o vs),\n    rename_cvterm r (rename_cvterm r t) = t.\nProof.\n  introv; destruct t; simpl.\n  apply cvterm_eq; simpl; autorewrite with slow; auto.\nQed.\nHint Rewrite @rename_cvterm_idem : slow.\n\nLemma cofinite_subst_fapprox_eqc_rename {o} :\n  forall r (e : per(o)) v (a b : @CVTerm o [v]) f,\n    cofinite_subst_fapprox_eqc e a b f\n    -> cofinite_subst_fapprox_eqc (rename_per r e) (rename_cvterm r a) (rename_cvterm r b) (rename_cterm r f).\nProof.\n  introv cof.\n  unfold cofinite_subst_fapprox_eqc in *; exrepnd.\n  exists j; introv h.\n  apply cof0 in h; clear cof0.\n  unfold rename_per.\n  repeat (rewrite rename_cterm_subst_fapproxc).\n  autorewrite with slow; auto.\nQed.\n\nLemma rename_cofinite_subst_fapprox_eqc {o} :\n  forall r (e : per(o)) v (a b : @CVTerm o [v]) f,\n    cofinite_subst_fapprox_eqc (rename_per r e) (rename_cvterm r a) (rename_cvterm r b) (rename_cterm r f)\n    -> cofinite_subst_fapprox_eqc e a b f.\nProof.\n  introv cof.\n  unfold cofinite_subst_fapprox_eqc in *; exrepnd.\n  exists j; introv h.\n  apply cof0 in h; clear cof0.\n  unfold rename_per in *.\n  repeat (rewrite rename_cterm_subst_fapproxc in h).\n  autorewrite with slow in *; auto.\nQed.\n\nLemma rename_cofinite_subst_fapprox_eqc2 {o} :\n  forall r (e : per(o)) v (a b : @CVTerm o [v]) f,\n    cofinite_subst_fapprox_eqc (rename_per r e) a b f\n    -> cofinite_subst_fapprox_eqc e (rename_cvterm r a) (rename_cvterm r b) (rename_cterm r f).\nProof.\n  introv cof.\n  unfold cofinite_subst_fapprox_eqc in *; exrepnd.\n  exists j; introv h.\n  apply cof0 in h; clear cof0.\n  unfold rename_per in *.\n  repeat (rewrite rename_cterm_subst_fapproxc in h).\n  autorewrite with slow in *; auto.\nQed.\n\nLemma rename_cterm_mkc_fix {o} :\n  forall r (a : @CTerm o),\n    rename_cterm r (mkc_fix a)\n    = mkc_fix (rename_cterm r a).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_mkc_fix : slow.\n\nLemma admissible_equality_rename {o} :\n  forall r (e : per(o)),\n    admissible_equality (rename_per r e)\n                        <=> admissible_equality e.\nProof.\n  introv; unfold admissible_equality; split; introv h cof.\n\n  - apply (cofinite_subst_fapprox_eqc_rename r) in cof.\n    apply h in cof; clear h.\n    unfold subst_fix_eqc, rename_per, subst_fixc in *.\n    repeat (rewrite rename_cterm_substc in cof); autorewrite with slow in cof; auto.\n\n  - apply (rename_cofinite_subst_fapprox_eqc2 r) in cof.\n    apply h in cof; clear h.\n    unfold subst_fix_eqc, rename_per, subst_fixc in *.\n    repeat (rewrite rename_cterm_substc); autorewrite with slow; auto.\nQed.\n\nLemma mono_equality_rename {o} :\n  forall r lib (ea : per(o)),\n    mono_equality (rename_lib r lib) (rename_per r ea)\n    <=> mono_equality lib ea.\nProof.\n  introv; split; introv mono e apr; unfold mono_equality in *.\n\n  - apply (implies_approxc_rename r) in apr.\n    apply mono in apr; auto; eauto 3 with slow.\n    unfold rename_per in *; autorewrite with slow in *; auto.\n\n  - apply (implies_approxc_rename r) in apr.\n    autorewrite with slow in *.\n    apply mono in apr; auto; eauto 3 with slow.\nQed.\n\nLemma rename_cterm_pw {o} :\n  forall r (P : @CTerm o) ap A bp ba B cp ca cb C p ,\n    rename_cterm r (mkc_pw P ap A bp ba B cp ca cb C p)\n    = mkc_pw (rename_cterm r P) ap (rename_cvterm r A) bp ba (rename_cvterm r B) cp ca cb (rename_cvterm r C) (rename_cterm r p).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_pw : rename.\n\nLemma rename_cterm_pm {o} :\n  forall r (P : @CTerm o) ap A bp ba B cp ca cb C p ,\n    rename_cterm r (mkc_pm P ap A bp ba B cp ca cb C p)\n    = mkc_pm (rename_cterm r P) ap (rename_cvterm r A) bp ba (rename_cvterm r B) cp ca cb (rename_cvterm r C) (rename_cterm r p).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_pm : rename.\n\nDefinition rename_per_fam_fam\n           {o}\n           r\n           {ep : per(o)}\n           {ea : forall p p', ep p p' -> per(o)}\n           (eb : forall p p' (ep : ep p p') a a', ea p p' ep a a' -> per(o))\n  : per-fam-fam(rename_per r ep,rename_per_fam r ea) :=\n  fun (p p' : @CTerm o)\n      (e : rename_per r ep p p')\n      a a'\n      (f : rename_per r (ea (rename_cterm r p) (rename_cterm r p') e) a a') =>\n    rename_per r (eb (rename_cterm r p) (rename_cterm r p') e (rename_cterm r a) (rename_cterm r a') f).\n\nLemma rename_sub_csub2sub {o} :\n  forall r (s : @CSub o),\n    rename_sub r (csub2sub s) = csub2sub (rename_csub r s).\nProof.\n  introv; unfold rename_sub, rename_csub, csub2sub.\n  allrw map_map; unfold compose; auto.\n  apply eq_maps; introv i; repnd; simpl; auto.\n  destruct_cterms; simpl; auto.\nQed.\n\nLemma rename_csubst {o} :\n  forall r (t : @NTerm o) s,\n    rename_term r (csubst t s) = csubst (rename_term r t) (rename_csub r s).\nProof.\n  introv.\n  unfold csubst.\n  rewrite rename_term_lsubst.\n  rewrite rename_sub_csub2sub; auto.\nQed.\nHint Rewrite @rename_csubst : rename.\n\nLemma rename_cterm_lsubstc2 {o} :\n  forall r a (A : @CTerm o) b B C,\n    rename_cterm r (lsubstc2 a A b B C)\n    = lsubstc2 a (rename_cterm r A) b (rename_cterm r B) (rename_cvterm r C).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl.\n  rewrite rename_csubst; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_lsubstc2 : rename.\n\nLemma rename_cterm_lsubstc3 {o} :\n  forall r a (A : @CTerm o) b B c C D,\n    rename_cterm r (lsubstc3 a A b B c C D)\n    = lsubstc3 a (rename_cterm r A) b (rename_cterm r B) c (rename_cterm r C) (rename_cvterm r D).\nProof.\n  introv; destruct_cterms; apply cterm_eq; simpl.\n  rewrite rename_csubst; simpl; auto.\nQed.\nHint Rewrite @rename_cterm_lsubstc3 : rename.\n\nLemma implies_pweq_rename {o} :\n  forall r lib eqp eqa eqb cp ca cb C p (t1 t2 : @CTerm o),\n    pweq lib eqp eqa eqb cp ca cb C p t1 t2\n    -> pweq\n         (rename_lib r lib)\n         (rename_per r eqp)\n         (rename_per_fam r eqa)\n         (rename_per_fam_fam r eqb)\n         cp ca cb\n         (rename_cvterm r C)\n         (rename_cterm r p)\n         (rename_cterm r t1)\n         (rename_cterm r t2).\nProof.\n  introv w; induction w as [? ? ? ? ? ? ? ? ea c1 c2 ha hb]; spcast.\n  apply (computes_to_valc_rename r) in c1.\n  apply (computes_to_valc_rename r) in c2.\n  autorewrite with slow rename in *.\n  apply (pweq_cons\n           (rename_lib r lib)\n           (rename_per r eqp)\n           (rename_per_fam r eqa)\n           (rename_per_fam_fam r eqb)\n           cp ca cb\n           (rename_cvterm r C)\n           (rename_cterm r p)\n           (rename_cterm r t1)\n           (rename_cterm r t2)\n           (implies_rename_per r eqp p p ep)\n           (rename_cterm r a1)\n           (rename_cterm r f1)\n           (rename_cterm r a2)\n           (rename_cterm r f2)\n           (implies_rename_per_fam r eqp eqa p p a1 a2 ep ea)\n        ); spcast; auto.\n  introv w.\n  unfold rename_per_fam_fam, rename_per_fam, rename_per in w; autorewrite with slow rename in w.\n\n  unfold implies_rename_per, implies_rename_per_fam in w; simpl in w.\n  rewrite (rename_cterm_idem r p) in w.\n  rewrite (rename_cterm_idem r a1) in w.\n  rewrite (rename_cterm_idem r a2) in w.\n  unfold eq_ind_r in w; simpl in w.\n  unfold eq_ind, eq_rect, eq_sym in w.\n  rewrite Equality.UIP_refl_refl in w.\n  apply hb in w; autorewrite with rename slow in *; auto.\nQed.\n\nLemma implies_pmeq_rename {o} :\n  forall r lib eqp eqa eqb cp ca cb C p (t1 t2 : @CTerm o),\n    pmeq lib eqp eqa eqb cp ca cb C p t1 t2\n    -> pmeq\n         (rename_lib r lib)\n         (rename_per r eqp)\n         (rename_per_fam r eqa)\n         (rename_per_fam_fam r eqb)\n         cp ca cb\n         (rename_cvterm r C)\n         (rename_cterm r p)\n         (rename_cterm r t1)\n         (rename_cterm r t2).\nProof.\n  cofix IND.\n  introv w; destruct w as [? ? ? ? ? ea c1 c2 hb]; spcast.\n  apply (computes_to_valc_rename r) in c1.\n  apply (computes_to_valc_rename r) in c2.\n  autorewrite with slow rename in *.\n  apply (pmeq_cons\n           (rename_lib r lib)\n           (rename_per r eqp)\n           (rename_per_fam r eqa)\n           (rename_per_fam_fam r eqb)\n           cp ca cb\n           (rename_cvterm r C)\n           (rename_cterm r p)\n           (rename_cterm r t1)\n           (rename_cterm r t2)\n           (implies_rename_per r eqp p p ep)\n           (rename_cterm r a1)\n           (rename_cterm r f1)\n           (rename_cterm r a2)\n           (rename_cterm r f2)\n           (implies_rename_per_fam r eqp eqa p p a1 a2 ep ea)\n        ); spcast; auto.\n  introv w.\n  unfold rename_per_fam_fam, rename_per_fam, rename_per in w; autorewrite with slow rename in w.\n\n  unfold implies_rename_per, implies_rename_per_fam in w; simpl in w.\n  rewrite (rename_cterm_idem r p) in w.\n  rewrite (rename_cterm_idem r a1) in w.\n  rewrite (rename_cterm_idem r a2) in w.\n  unfold eq_ind_r in w; simpl in w.\n  unfold eq_ind, eq_rect, eq_sym in w.\n  rewrite Equality.UIP_refl_refl in w.\n  apply hb in w; autorewrite with rename slow in *; auto.\n  apply (IND r) in w; autorewrite with slow rename in *; auto.\nQed.\n\nLemma eq_pweq_implies {o} :\n  forall lib\n         (eqp1 eqp2 : per(o))\n         (eqa1 : per-fam(eqp1)) (eqa2 : per-fam(eqp2))\n         (eqb1 : per-fam-fam(eqp1,eqa1)) (eqb2 : per-fam-fam(eqp2,eqa2))\n         cp ca cb C p t1 t2\n         (w1 : forall a b, eqp1 a b = eqp2 a b)\n         (w2 : forall a b (e1 : eqp1 a b) c d,\n             eqa1 a b e1 c d\n             = eqa2 a b (@eq_ind _ _ (fun x => x) e1 (eqp2 a b) (w1 a b)) c d)\n         (w3 : forall a b (e1 : eqp1 a b) c d (e2 : eqa1 a b e1 c d) e f,\n             eqb1 a b e1 c d e2 e f\n             = eqb2\n                 a b (@eq_ind _ _ (fun x => x) e1 (eqp2 a b) (w1 a b))\n                 c d (@eq_ind _ _ (fun x => x) e2 (eqa2 a b (@eq_ind _ _ (fun x => x) e1 (eqp2 a b) (w1 a b)) c d) (w2 a b e1 c d))\n                 e f),\n    pweq lib eqp1 eqa1 eqb1 cp ca cb C p t1 t2\n    -> pweq lib eqp2 eqa2 eqb2 cp ca cb C p t1 t2.\nProof.\n  introv w3 pw.\n  induction pw as [p t1 t2 ep a f a' f' e c c' h h'].\n\n  apply (pweq_cons\n           lib eqp2 eqa2 eqb2 cp ca cb C p t1 t2\n           (@eq_ind _ _ (fun x => x) ep (eqp2 p p) (w1 p p))\n           a f a' f'\n           (@eq_ind _ _ (fun x => x) e (eqa2 p p (@eq_ind _ _ (fun x => x) ep (eqp2 p p) (w1 p p)) a a') (w2 p p ep a a'))); spcast; auto.\n  introv w.\n  apply h'.\n  pose proof (w3 p p ep a a' e b1 b2) as z.\n  rewrite z; auto.\nQed.\n\nLemma pweq_rename_implies {o} :\n  forall r lib eqp eqa eqb cp ca cb C p (t1 t2 : @CTerm o),\n    pweq\n      (rename_lib r lib)\n      (rename_per r eqp)\n      (rename_per_fam r eqa)\n      (rename_per_fam_fam r eqb)\n      cp ca cb\n      (rename_cvterm r C)\n      (rename_cterm r p)\n      (rename_cterm r t1)\n      (rename_cterm r t2)\n    -> pweq lib eqp eqa eqb cp ca cb C p t1 t2.\nProof.\n  introv w.\n  apply (implies_pweq_rename r) in w; autorewrite with slow in *.\n\n  assert (forall a b, rename_per r (rename_per r eqp) a b = eqp a b) as w1.\n  { introv; unfold rename_per; autorewrite with slow; auto. }\n\n  assert (forall a b (e1 : rename_per r (rename_per r eqp) a b) c d,\n             rename_per_fam r (rename_per_fam r eqa) a b e1 c d\n             = eqa a b (@eq_ind _ _ (fun x => x) e1 (eqp a b) (w1 a b)) c d) as w2.\n  {\n    introv.\n    revert e1.\n    remember (w1 a b) as q; clear Heqq.\n    revert q.\n    unfold rename_per_fam, rename_per; autorewrite with slow.\n    introv.\n    unfold eq_ind, eq_rect; simpl.\n    rewrite (UIP_refl _ _ q); auto.\n  }\n\n  eapply (eq_pweq_implies _ _ _ _ _ _ _ _ _ _ _ _ _ _ w1 w2);[|exact w].\n  clear w.\n  introv.\n\n  remember (w2 a b e1 c d) as q; clear Heqq.\n  remember (w1 a b) as z; clear Heqz.\n\n  revert e1 e2 z q.\n  unfold eq_ind, eq_rect; simpl.\n  unfold rename_per_fam_fam, rename_per_fam, rename_per; simpl.\n  autorewrite with slow rename.\n  introv.\n  revert q.\n  rewrite (UIP_refl _ _ z); auto.\n  introv.\n  rewrite (UIP_refl _ _ q); auto.\nQed.\nHint Resolve pweq_rename_implies : slow.\n\nLemma eq_pmeq_implies {o} :\n  forall lib\n         (eqp1 eqp2 : per(o))\n         (eqa1 : per-fam(eqp1)) (eqa2 : per-fam(eqp2))\n         (eqb1 : per-fam-fam(eqp1,eqa1)) (eqb2 : per-fam-fam(eqp2,eqa2))\n         cp ca cb C p t1 t2\n         (w1 : forall a b, eqp1 a b = eqp2 a b)\n         (w2 : forall a b (e1 : eqp1 a b) c d,\n             eqa1 a b e1 c d\n             = eqa2 a b (@eq_ind _ _ (fun x => x) e1 (eqp2 a b) (w1 a b)) c d)\n         (w3 : forall a b (e1 : eqp1 a b) c d (e2 : eqa1 a b e1 c d) e f,\n             eqb1 a b e1 c d e2 e f\n             = eqb2\n                 a b (@eq_ind _ _ (fun x => x) e1 (eqp2 a b) (w1 a b))\n                 c d (@eq_ind _ _ (fun x => x) e2 (eqa2 a b (@eq_ind _ _ (fun x => x) e1 (eqp2 a b) (w1 a b)) c d) (w2 a b e1 c d))\n                 e f),\n    pmeq lib eqp1 eqa1 eqb1 cp ca cb C p t1 t2\n    -> pmeq lib eqp2 eqa2 eqb2 cp ca cb C p t1 t2.\nProof.\n  cofix IND.\n  introv w3 pw.\n  destruct pw as [ ep a f a' f' e c c' h].\n\n  apply (pmeq_cons\n           lib eqp2 eqa2 eqb2 cp ca cb C p t1 t2\n           (@eq_ind _ _ (fun x => x) ep (eqp2 p p) (w1 p p))\n           a f a' f'\n           (@eq_ind _ _ (fun x => x) e (eqa2 p p (@eq_ind _ _ (fun x => x) ep (eqp2 p p) (w1 p p)) a a') (w2 p p ep a a'))); spcast; auto.\n  introv w.\n  eapply IND; eauto.\n  apply h.\n  pose proof (w3 p p ep a a' e b1 b2) as z.\n  rewrite z; auto.\nQed.\n\nLemma pmeq_rename_implies {o} :\n  forall r lib eqp eqa eqb cp ca cb C p (t1 t2 : @CTerm o),\n    pmeq\n      (rename_lib r lib)\n      (rename_per r eqp)\n      (rename_per_fam r eqa)\n      (rename_per_fam_fam r eqb)\n      cp ca cb\n      (rename_cvterm r C)\n      (rename_cterm r p)\n      (rename_cterm r t1)\n      (rename_cterm r t2)\n    -> pmeq lib eqp eqa eqb cp ca cb C p t1 t2.\nProof.\n  introv w.\n  apply (implies_pmeq_rename r) in w; autorewrite with slow in *.\n\n  assert (forall a b, rename_per r (rename_per r eqp) a b = eqp a b) as w1.\n  { introv; unfold rename_per; autorewrite with slow; auto. }\n\n  assert (forall a b (e1 : rename_per r (rename_per r eqp) a b) c d,\n             rename_per_fam r (rename_per_fam r eqa) a b e1 c d\n             = eqa a b (@eq_ind _ _ (fun x => x) e1 (eqp a b) (w1 a b)) c d) as w2.\n  {\n    introv.\n    revert e1.\n    remember (w1 a b) as q; clear Heqq.\n    revert q.\n    unfold rename_per_fam, rename_per; autorewrite with slow.\n    introv.\n    unfold eq_ind, eq_rect; simpl.\n    rewrite (UIP_refl _ _ q); auto.\n  }\n\n  eapply (eq_pmeq_implies _ _ _ _ _ _ _ _ _ _ _ _ _ _ w1 w2);[|exact w].\n  clear w.\n  introv.\n\n  remember (w2 a b e1 c d) as q; clear Heqq.\n  remember (w1 a b) as z; clear Heqz.\n\n  revert e1 e2 z q.\n  unfold eq_ind, eq_rect; simpl.\n  unfold rename_per_fam_fam, rename_per_fam, rename_per; simpl.\n  autorewrite with slow rename.\n  introv.\n  revert q.\n  rewrite (UIP_refl _ _ z); auto.\n  introv.\n  rewrite (UIP_refl _ _ q); auto.\nQed.\nHint Resolve pmeq_rename_implies : slow.\n\nLemma implies_close_rename {o} :\n  forall r (u : library -> cts(o)) lib (t1 t2 : @CTerm o) e,\n    (forall lib t1 t2 e,\n        u lib t1 t2 e\n        -> u (rename_lib r lib) (rename_cterm r t1) (rename_cterm r t2) (rename_per r e))\n    -> close lib (u lib) t1 t2 e\n    -> close\n         (rename_lib r lib)\n         (u (rename_lib r lib))\n         (rename_cterm r t1)\n         (rename_cterm r t2)\n         (rename_per r e).\nProof.\n  introv imp cl.\n  remember (u lib) as ts.\n  revert Heqts.\n  close_cases (induction cl using @close_ind') Case; introv eqts; subst.\n\n  - Case \"CL_init\".\n    apply CL_init.\n    apply imp; auto.\n\n  - Case \"CL_int\".\n    apply CL_int.\n    unfold per_int in *; repnd; spcast.\n    apply (computes_to_valc_rename r) in per0.\n    apply (computes_to_valc_rename r) in per1.\n    autorewrite with slow in *.\n    dands; spcast; auto.\n    unfold rename_per; introv; rw per.\n    unfold equality_of_int; split; introv h; exrepnd; spcast.\n\n    + apply (computes_to_valc_rename r) in h1.\n      apply (computes_to_valc_rename r) in h0.\n      autorewrite with slow in *.\n      exists k; dands; spcast; auto.\n\n    + apply (computes_to_valc_rename r) in h1.\n      apply (computes_to_valc_rename r) in h0.\n      autorewrite with slow in *.\n      exists k; dands; spcast; auto.\n\n  - Case \"CL_atom\".\n    apply CL_atom.\n    unfold per_atom in *; repnd; spcast.\n    apply (computes_to_valc_rename r) in per0.\n    apply (computes_to_valc_rename r) in per1.\n    autorewrite with slow in *.\n    dands; spcast; auto.\n    unfold rename_per; introv; rw per.\n    unfold equality_of_atom; split; introv h; exrepnd; spcast.\n\n    + apply (computes_to_valc_rename r) in h1.\n      apply (computes_to_valc_rename r) in h0.\n      autorewrite with slow in *.\n      exists s; dands; spcast; auto.\n\n    + apply (computes_to_valc_rename r) in h1.\n      apply (computes_to_valc_rename r) in h0.\n      autorewrite with slow in *.\n      exists s; dands; spcast; auto.\n\n  - Case \"CL_uatom\".\n    apply CL_uatom.\n    unfold per_uatom in *; repnd; spcast.\n    apply (computes_to_valc_rename r) in per0.\n    apply (computes_to_valc_rename r) in per1.\n    autorewrite with slow in *.\n    dands; spcast; auto.\n    unfold rename_per; introv; rw per.\n    unfold equality_of_uatom; split; introv h; exrepnd; spcast.\n\n    + apply (computes_to_valc_rename r) in h1.\n      apply (computes_to_valc_rename r) in h0.\n      autorewrite with slow in *.\n      eexists; dands; spcast; eauto.\n\n    + apply (computes_to_valc_rename r) in h1.\n      apply (computes_to_valc_rename r) in h0.\n      autorewrite with slow in *.\n      eexists; dands; spcast; eauto.\n\n  - Case \"CL_base\".\n    apply CL_base.\n    unfold per_base in *; repnd; spcast.\n    apply (computes_to_valc_rename r) in per0.\n    apply (computes_to_valc_rename r) in per1.\n    autorewrite with slow in *.\n    dands; spcast; auto.\n    unfold rename_per; introv; rw per.\n    split; introv h; exrepnd; spcast;\n      apply (implies_cequivc_rename r) in h; autorewrite with slow in *; auto.\n\n  - Case \"CL_approx\".\n    apply CL_approx.\n    unfold per_approx in *; exrepnd; spcast.\n    apply (computes_to_valc_rename r) in per0.\n    apply (computes_to_valc_rename r) in per2.\n    autorewrite with slow rename in *.\n    eexists; eexists; eexists; eexists; dands; spcast; eauto.\n\n    + split; intro h;\n        apply (implies_capproxc_rename r) in h; autorewrite with slow in *;\n          apply per3 in h; apply (implies_capproxc_rename r) in h; auto.\n\n    + introv; unfold rename_per; simpl.\n      rw per1; clear per1.\n      split; intro h; repnd; spcast.\n\n      * apply (computes_to_valc_rename r) in h0.\n        apply (computes_to_valc_rename r) in h1.\n        autorewrite with slow in *.\n        dands; spcast; auto; eauto 3 with slow.\n\n      * apply (computes_to_valc_rename r) in h0.\n        apply (computes_to_valc_rename r) in h1.\n        autorewrite with slow in *.\n        dands; spcast; auto; eauto 3 with slow.\n        apply (implies_approxc_rename r) in h; autorewrite with slow in *; auto.\n\n  - Case \"CL_cequiv\".\n    apply CL_cequiv.\n    unfold per_cequiv in *; exrepnd; spcast.\n    apply (computes_to_valc_rename r) in per0.\n    apply (computes_to_valc_rename r) in per2.\n    autorewrite with slow rename in *.\n    eexists; eexists; eexists; eexists; dands; spcast; eauto.\n\n    + split; intro h;\n        apply (implies_ccequivc_rename r) in h; autorewrite with slow in *;\n          apply per3 in h; apply (implies_ccequivc_rename r) in h; auto.\n\n    + introv; unfold rename_per; simpl.\n      rw per1; clear per1.\n      split; intro h; repnd; spcast.\n\n      * apply (computes_to_valc_rename r) in h0.\n        apply (computes_to_valc_rename r) in h1.\n        autorewrite with slow in *.\n        dands; spcast; auto; eauto 3 with slow.\n\n      * apply (computes_to_valc_rename r) in h0.\n        apply (computes_to_valc_rename r) in h1.\n        autorewrite with slow in *.\n        dands; spcast; auto; eauto 3 with slow.\n        apply (implies_cequivc_rename r) in h; autorewrite with slow in *; auto.\n\n  - Case \"CL_eq\".\n    repeat (autodimp IHcl hyp).\n    apply CL_eq.\n    spcast.\n    unfold per_eq.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow in *.\n    eexists; eexists; eexists; eexists; eexists; eexists.\n    exists (rename_per r eqa).\n    dands; spcast; eauto;[| |].\n\n    + unfold eqindomain. unfold rename_per.\n      autorewrite with slow; tcsp.\n\n    + unfold eqindomain. unfold rename_per.\n      autorewrite with slow; tcsp.\n\n    + introv; unfold rename_per.\n      rw eqiff; autorewrite with slow; tcsp.\n      split; introv h; repnd; dands; tcsp; spcast;\n        try (complete (apply (computes_to_valc_rename r) in h0; autorewrite with slow in *; auto));\n        try (complete (apply (computes_to_valc_rename r) in h1; autorewrite with slow in *; auto)).\n\n  - Case \"CL_req\".\n    repeat (autodimp IHcl hyp).\n    apply CL_req.\n    spcast.\n    unfold per_req.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow rename in *.\n    eexists; eexists; eexists; eexists; eexists; eexists.\n    exists (rename_per r eqa).\n    dands; spcast; eauto;[| |].\n\n    + destruct eo1 as [eos1|eos1];[left|right]; spcast; eauto 3 with slow.\n\n    + destruct eo2 as [eos2|eos2];[left|right]; spcast; eauto 3 with slow.\n\n    + introv; unfold rename_per.\n      rw eqiff; autorewrite with slow; tcsp.\n      unfold per_req_eq; split; introv h; exrepnd; eexists; eexists; dands; tcsp; spcast;\n        try (complete (apply (computes_to_valc_rename r) in h0; autorewrite with slow in *; eauto));\n        try (complete (apply (computes_to_valc_rename r) in h1; autorewrite with slow in *; eauto));\n        try (complete (apply (computes_to_valc_rename r) in h2; autorewrite with slow in *; eauto)).\n\n  - Case \"CL_teq\".\n    repeat (autodimp IHcl hyp).\n    apply CL_teq.\n    spcast.\n    unfold per_teq.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autodimp IHcl1 hyp.\n    autodimp IHcl2 hyp.\n    autodimp IHcl3 hyp.\n    autorewrite with slow rename in *.\n    eexists; eexists; eexists; eexists.\n    exists (rename_per r eqa).\n    dands; spcast; eauto.\n\n    introv; unfold rename_per.\n    rw eqiff; autorewrite with slow; tcsp.\n\n  - Case \"CL_isect\".\n    apply CL_isect.\n    spcast.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow rename in *.\n    repeat (autodimp IHcl hyp).\n\n    exists (rename_per r eqa) (rename_per_fam r eqb).\n    dands.\n\n    + unfold type_family.\n      eexists; eexists; eexists; eexists; eexists; eexists; dands; spcast; eauto.\n      introv.\n\n      dup e as q.\n      apply rename_per_iff in q.\n      unfold rename_per1 in q; exrepnd; subst.\n      revert e; unfold rename_per_fam, rename_per; autorewrite with slow; introv.\n      pose proof (recb a'0 b' e) as q; repeat (autodimp q hyp).\n      unfold rename_per in q; auto.\n      autorewrite with rename in *; auto.\n\n    + introv.\n      split; introv h.\n\n      * introv.\n        dup e as q.\n        apply rename_per_iff in q.\n        unfold rename_per1 in q; exrepnd; subst.\n        revert e; unfold rename_per_fam, rename_per in *; autorewrite with slow; introv.\n        rw eqiff in h; apply h.\n\n      * unfold rename_per.\n        apply eqiff.\n        introv.\n        pose proof (h (rename_cterm r a) (rename_cterm r a')) as q.\n        revert q; unfold rename_per_fam, rename_per; autorewrite with slow.\n        introv; tcsp.\n\n  - Case \"CL_func\".\n    apply CL_func.\n    spcast.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow rename in *.\n    repeat (autodimp IHcl hyp).\n\n    exists (rename_per r eqa) (rename_per_fam r eqb).\n    dands.\n\n    + unfold type_family.\n      eexists; eexists; eexists; eexists; eexists; eexists; dands; spcast; eauto.\n      introv.\n\n      dup e as q.\n      apply rename_per_iff in q.\n      unfold rename_per1 in q; exrepnd; subst.\n      revert e; unfold rename_per_fam, rename_per; autorewrite with slow; introv.\n      pose proof (recb a'0 b' e) as q; repeat (autodimp q hyp).\n      unfold rename_per in q; auto.\n      autorewrite with rename in *; auto.\n\n    + introv.\n      split; introv h.\n\n      * introv.\n        dup e as q.\n        apply rename_per_iff in q.\n        unfold rename_per1 in q; exrepnd; subst.\n        revert e; unfold rename_per_fam, rename_per in *; autorewrite with slow; introv.\n        rw eqiff in h; apply h.\n\n      * unfold rename_per.\n        apply eqiff.\n        introv.\n        pose proof (h (rename_cterm r a) (rename_cterm r a')) as q.\n        revert q; unfold rename_per_fam, rename_per; autorewrite with slow.\n        introv; tcsp.\n\n  - Case \"CL_disect\".\n    apply CL_disect.\n    spcast.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow rename in *.\n    repeat (autodimp IHcl hyp).\n\n    exists (rename_per r eqa) (rename_per_fam r eqb).\n    dands.\n\n    + unfold type_family.\n      eexists; eexists; eexists; eexists; eexists; eexists; dands; spcast; eauto.\n      introv.\n\n      dup e as q.\n      apply rename_per_iff in q.\n      unfold rename_per1 in q; exrepnd; subst.\n      revert e; unfold rename_per_fam, rename_per; autorewrite with slow; introv.\n      pose proof (recb a'0 b' e) as q; repeat (autodimp q hyp).\n      unfold rename_per in q; auto.\n      autorewrite with rename in *; auto.\n\n    + introv.\n      split; introv h.\n\n      * unfold rename_per in h.\n        apply eqiff in h; exrepnd.\n        unfold rename_per_fam, rename_per; simpl.\n        eexists; eauto.\n\n      * exrepnd.\n        unfold rename_per.\n        apply eqiff.\n        eexists; eauto.\n\n  - Case \"CL_pertype\".\n    repeat (autodimp IHcl hyp).\n    apply CL_pertype.\n    spcast.\n    unfold per_pertype.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow in *.\n    eexists; eexists.\n\n    exists (rename_fper r eq1) (rename_fper r eq2).\n    dands; spcast; eauto; eauto 3 with slow.\n\n    + introv.\n      pose proof (rec1 (rename_cterm r x) (rename_cterm r y)) as q; autodimp q hyp.\n      autorewrite with slow in *; auto.\n\n    + introv.\n      pose proof (rec2 (rename_cterm r x) (rename_cterm r y)) as q; autodimp q hyp.\n      autorewrite with slow in *; auto.\n\n    + introv; repeat (rw @inhabited_rename_fper); tcsp.\n\n    + introv; unfold rename_per.\n      rw @inhabited_rename_fper.\n      rw eqiff; tcsp.\n\n  - Case \"CL_ipertype\".\n    repeat (autodimp IHcl hyp).\n    apply CL_ipertype.\n    spcast.\n    unfold per_ipertype.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow in *.\n    eexists; eexists.\n\n    exists (rename_fper r eq1).\n    dands; spcast; eauto; eauto 3 with slow.\n\n    + introv.\n      pose proof (rec1 (rename_cterm r x) (rename_cterm r y)) as q; autodimp q hyp.\n      autorewrite with slow in *; auto.\n\n    + introv; unfold rename_per.\n      rw @inhabited_rename_fper.\n      rw eqiff; tcsp.\n\n  - Case \"CL_spertype\".\n    repeat (autodimp IHcl hyp).\n    apply CL_spertype.\n    spcast.\n    unfold per_spertype.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow in *.\n    eexists; eexists.\n\n    exists (rename_fper r eq1).\n    dands; spcast; eauto; eauto 3 with slow.\n\n    + introv.\n      pose proof (rec1 (rename_cterm r x) (rename_cterm r y)) as q; autodimp q hyp.\n      autorewrite with slow in *; auto.\n\n    + introv inh.\n      apply inhabited_rename_fper in inh.\n      apply (rec2 _ (rename_cterm r y)) in inh; auto.\n      autorewrite with slow in *; auto.\n\n    + introv inh.\n      apply inhabited_rename_fper in inh.\n      apply (rec3 (rename_cterm r x)) in inh; auto.\n      autorewrite with slow in *; auto.\n\n    + introv; unfold rename_per.\n      rw @inhabited_rename_fper.\n      rw eqiff; tcsp.\n\n  - Case \"CL_w\".\n    apply CL_w.\n    spcast.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow rename in *.\n    repeat (autodimp IHcl hyp).\n\n    exists (rename_per r eqa) (rename_per_fam r eqb).\n    dands.\n\n    + unfold type_family.\n      eexists; eexists; eexists; eexists; eexists; eexists; dands; spcast; eauto.\n      introv.\n\n      dup e as q.\n      apply rename_per_iff in q.\n      unfold rename_per1 in q; exrepnd; subst.\n      revert e; unfold rename_per_fam, rename_per; autorewrite with slow; introv.\n      pose proof (recb a'0 b' e) as q; repeat (autodimp q hyp).\n      unfold rename_per in q; auto.\n      autorewrite with rename in *; auto.\n\n    + introv.\n      split; introv h.\n\n      * unfold rename_per in h.\n        apply eqiff in h; exrepnd.\n        apply (implies_weq_rename r) in h; autorewrite with slow in *; auto.\n\n      * unfold rename_per.\n        apply eqiff.\n        apply (weq_rename_implies r); autorewrite with slow; auto.\n\n  - Case \"CL_m\".\n    apply CL_m.\n    spcast.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow rename in *.\n    repeat (autodimp IHcl hyp).\n\n    exists (rename_per r eqa) (rename_per_fam r eqb).\n    dands.\n\n    + unfold type_family.\n      eexists; eexists; eexists; eexists; eexists; eexists; dands; spcast; eauto.\n      introv.\n\n      dup e as q.\n      apply rename_per_iff in q.\n      unfold rename_per1 in q; exrepnd; subst.\n      revert e; unfold rename_per_fam, rename_per; autorewrite with slow; introv.\n      pose proof (recb a'0 b' e) as q; repeat (autodimp q hyp).\n      unfold rename_per in q; auto.\n      autorewrite with rename in *; auto.\n\n    + introv.\n      split; introv h.\n\n      * unfold rename_per in h.\n        apply eqiff in h; exrepnd.\n        apply (implies_meq_rename r) in h; autorewrite with slow in *; auto.\n\n      * unfold rename_per.\n        apply eqiff.\n        apply (meq_rename_implies r); autorewrite with slow; auto.\n\n  - Case \"CL_pw\".\n    apply CL_pw.\n    spcast.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow rename in *.\n\n    repeat (autodimp IHcl hyp).\n\n    exists (rename_per r eqp) (rename_per_fam r eqa) (rename_per_fam_fam r eqb).\n    exists (rename_cterm r p) (rename_cterm r p') cp cp' ca ca' cb cb'.\n    exists (rename_cvterm r C) (rename_cvterm r C').\n    dands;[|].\n\n    + unfold type_pfamily.\n      eexists; eexists; eexists; eexists; eexists; eexists.\n      eexists; eexists; eexists; eexists; eexists; eexists.\n      dands; spcast; eauto;[| | |].\n\n      * introv.\n        dup ep as q.\n        apply rename_per_iff in q.\n        unfold rename_per1 in q; exrepnd; subst.\n        revert ep; unfold rename_per_fam, rename_per; autorewrite with slow; introv.\n        pose proof (reca a' b' ep) as q; repeat (autodimp q hyp).\n        unfold rename_per in q; auto.\n        autorewrite with rename in *; auto.\n\n      * introv.\n        dup ep as q.\n        apply rename_per_iff in q.\n        unfold rename_per1 in q; exrepnd; subst.\n        revert ep ea; unfold rename_per_fam_fam, rename_per_fam, rename_per; autorewrite with slow; introv.\n\n        pose proof (recb a' b' ep (rename_cterm r a1) (rename_cterm r a2) ea) as q; repeat (autodimp q hyp).\n        unfold rename_per in q; auto.\n        autorewrite with rename slow in *; auto.\n\n      * introv eb.\n        dup ep as q.\n        apply rename_per_iff in q.\n        unfold rename_per1 in q; exrepnd; subst.\n        revert ep ea eb; unfold rename_per_fam_fam, rename_per_fam, rename_per; autorewrite with slow rename; introv eb.\n        eapply eqc; eauto.\n\n      * unfold rename_per; autorewrite with slow; auto.\n\n    + introv.\n      split; introv h;[|].\n\n      * unfold rename_per in h.\n        apply eqiff in h; exrepnd.\n        apply (implies_pweq_rename r) in h; autorewrite with slow in *; auto.\n\n      * unfold rename_per.\n        apply eqiff.\n        apply (pweq_rename_implies r); autorewrite with slow; auto.\n\n  - Case \"CL_pm\".\n    apply CL_pm.\n    spcast.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow rename in *.\n\n    repeat (autodimp IHcl hyp).\n\n    exists (rename_per r eqp) (rename_per_fam r eqa) (rename_per_fam_fam r eqb).\n    exists (rename_cterm r p) (rename_cterm r p') cp cp' ca ca' cb cb'.\n    exists (rename_cvterm r C) (rename_cvterm r C').\n    dands;[|].\n\n    + unfold type_pfamily.\n      eexists; eexists; eexists; eexists; eexists; eexists.\n      eexists; eexists; eexists; eexists; eexists; eexists.\n      dands; spcast; eauto;[| | |].\n\n      * introv.\n        dup ep as q.\n        apply rename_per_iff in q.\n        unfold rename_per1 in q; exrepnd; subst.\n        revert ep; unfold rename_per_fam, rename_per; autorewrite with slow; introv.\n        pose proof (reca a' b' ep) as q; repeat (autodimp q hyp).\n        unfold rename_per in q; auto.\n        autorewrite with rename in *; auto.\n\n      * introv.\n        dup ep as q.\n        apply rename_per_iff in q.\n        unfold rename_per1 in q; exrepnd; subst.\n        revert ep ea; unfold rename_per_fam_fam, rename_per_fam, rename_per; autorewrite with slow; introv.\n\n        pose proof (recb a' b' ep (rename_cterm r a1) (rename_cterm r a2) ea) as q; repeat (autodimp q hyp).\n        unfold rename_per in q; auto.\n        autorewrite with rename slow in *; auto.\n\n      * introv eb.\n        dup ep as q.\n        apply rename_per_iff in q.\n        unfold rename_per1 in q; exrepnd; subst.\n        revert ep ea eb; unfold rename_per_fam_fam, rename_per_fam, rename_per; autorewrite with slow rename; introv eb.\n        eapply eqc; eauto.\n\n      * unfold rename_per; autorewrite with slow; auto.\n\n    + introv.\n      split; introv h;[|].\n\n      * unfold rename_per in h.\n        apply eqiff in h; exrepnd.\n        apply (implies_pmeq_rename r) in h; autorewrite with slow in *; auto.\n\n      * unfold rename_per.\n        apply eqiff.\n        apply (pmeq_rename_implies r); autorewrite with slow; auto.\n\n  - Case \"CL_texc\".\n    repeat (autodimp IHcl1 hyp).\n    repeat (autodimp IHcl2 hyp).\n    apply CL_texc.\n    spcast.\n    unfold per_texc.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow in *.\n\n    exists (rename_per r eqn) (rename_per r eqe).\n    eexists; eexists; eexists; eexists.\n    dands; spcast; eauto; eauto 3 with slow.\n\n    introv; unfold rename_per.\n    rw eqiff; tcsp.\n    unfold per_texc_eq.\n    split; introv h; exrepnd; spcast.\n\n    * apply (rename_computes_to_excc r) in h0.\n      apply (rename_computes_to_excc r) in h2.\n      autorewrite with slow in *.\n      eexists; eexists; eexists; eexists; dands; spcast; eauto; autorewrite with slow; auto.\n\n    * apply (rename_computes_to_excc r) in h0.\n      apply (rename_computes_to_excc r) in h2.\n      autorewrite with slow in *.\n      eexists; eexists; eexists; eexists; dands; spcast; eauto; autorewrite with slow; auto.\n\n  - Case \"CL_union\".\n    repeat (autodimp IHcl1 hyp).\n    repeat (autodimp IHcl2 hyp).\n    apply CL_union.\n    spcast.\n    unfold per_union.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow in *.\n\n    exists (rename_per r eqa) (rename_per r eqb).\n    eexists; eexists; eexists; eexists.\n    dands; spcast; eauto; eauto 3 with slow.\n\n    introv; unfold rename_per.\n    rw eqiff; tcsp.\n    unfold per_union_eq.\n    unfold per_union_eq_L, per_union_eq_R.\n    split; introv h; repndors; exrepnd; spcast.\n\n    * apply (computes_to_valc_rename r) in h0.\n      apply (computes_to_valc_rename r) in h2.\n      autorewrite with slow in *.\n      left.\n      eexists; eexists; dands; spcast; eauto; autorewrite with slow; auto.\n\n    * apply (computes_to_valc_rename r) in h0.\n      apply (computes_to_valc_rename r) in h2.\n      autorewrite with slow in *.\n      right.\n      eexists; eexists; dands; spcast; eauto; autorewrite with slow; auto.\n\n    * apply (computes_to_valc_rename r) in h0.\n      apply (computes_to_valc_rename r) in h2.\n      autorewrite with slow in *.\n      left.\n      eexists; eexists; dands; spcast; eauto; autorewrite with slow; auto.\n\n    * apply (computes_to_valc_rename r) in h0.\n      apply (computes_to_valc_rename r) in h2.\n      autorewrite with slow in *.\n      right.\n      eexists; eexists; dands; spcast; eauto; autorewrite with slow; auto.\n\n  - Case \"CL_image\".\n    repeat (autodimp IHcl hyp).\n    apply CL_image.\n    spcast.\n    unfold per_image.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow in *.\n\n    exists (rename_per r eqa).\n    eexists; eexists; eexists; eexists.\n    dands; spcast; eauto; eauto 3 with slow.\n\n    introv; rw eqiff; tcsp.\n    rw <- (rename_per_image_eq r lib); autorewrite with slow; tcsp.\n\n  - Case \"CL_partial\".\n    repeat (autodimp IHcl hyp).\n    apply CL_partial.\n    spcast.\n    unfold per_partial.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow in *.\n\n    eexists; eexists.\n    exists (rename_per r eqa).\n    dands; spcast; eauto; eauto 3 with slow.\n\n    + introv h.\n      unfold rename_per in h.\n      apply hv in h; spcast.\n      apply (implies_rename_hasvaluec r) in h; autorewrite with slow in *; auto.\n\n    + introv; unfold rename_per at 1; simpl.\n      rw eqiff.\n      unfold per_partial_eq.\n\n      repeat (rw (chaltsc_rename_iff r lib)); autorewrite with slow.\n      unfold rename_per; tcsp.\n\n  - Case \"CL_admiss\".\n    repeat (autodimp IHcl hyp).\n    apply CL_admiss.\n    spcast.\n    unfold per_admiss.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow in *.\n\n    eexists; eexists.\n    exists (rename_per r eqa).\n    dands; spcast; eauto; eauto 3 with slow.\n\n    introv; unfold rename_per at 1; simpl.\n    rw eqiff.\n    unfold per_admiss_eq.\n\n    rw @admissible_equality_rename.\n    split; introv h; repnd; spcast; auto.\n\n    + apply (computes_to_valc_rename r) in h0.\n      apply (computes_to_valc_rename r) in h1.\n      autorewrite with slow in *.\n      dands; spcast; auto.\n\n    + apply (computes_to_valc_rename r) in h0.\n      apply (computes_to_valc_rename r) in h1.\n      autorewrite with slow in *.\n      dands; spcast; auto.\n\n  - Case \"CL_mono\".\n    repeat (autodimp IHcl hyp).\n    apply CL_mono.\n    spcast.\n    unfold per_mono.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow in *.\n\n    eexists; eexists.\n    exists (rename_per r eqa).\n    dands; spcast; eauto; eauto 3 with slow.\n\n    introv; unfold rename_per at 1; simpl.\n    rw eqiff.\n    unfold per_mono_eq.\n    rw @mono_equality_rename.\n    split; introv h; repnd; spcast; auto.\n\n    + apply (computes_to_valc_rename r) in h0.\n      apply (computes_to_valc_rename r) in h1.\n      autorewrite with slow in *.\n      dands; spcast; auto.\n\n    + apply (computes_to_valc_rename r) in h0.\n      apply (computes_to_valc_rename r) in h1.\n      autorewrite with slow in *.\n      dands; spcast; auto.\n\n  - Case \"CL_ffatom\".\n    repeat (autodimp IHcl hyp).\n    apply CL_ffatom.\n    spcast.\n    unfold per_ffatom.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    apply (computes_to_valc_rename r) in ca1.\n    apply (computes_to_valc_rename r) in ca2.\n    autorewrite with slow in *.\n\n    eexists; eexists; eexists; eexists; eexists; eexists.\n    exists (rename_per r eqa); eexists.\n    dands; spcast; eauto; eauto 3 with slow.\n\n    introv; unfold rename_per at 1; simpl.\n    rw eqiff.\n    unfold per_ffatom_eq.\n\n    split; introv h; exrepnd; spcast.\n\n    + apply (computes_to_valc_rename r) in h0.\n      apply (computes_to_valc_rename r) in h1.\n      autorewrite with slow in *.\n      dands; spcast; auto.\n      exists (rename_cterm r y); dands; autorewrite with slow; eauto 3 with slow.\n\n    + apply (computes_to_valc_rename r) in h0.\n      apply (computes_to_valc_rename r) in h1.\n      autorewrite with slow in *.\n      dands; spcast; auto.\n      unfold rename_per in *; autorewrite with slow in *.\n      exists (rename_cterm r y); dands; autorewrite with slow; eauto 3 with slow.\n\n  - Case \"CL_effatom\".\n    repeat (autodimp IHcl hyp).\n    apply CL_effatom.\n    spcast.\n    unfold per_effatom.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow in *.\n\n    eexists; eexists; eexists; eexists; eexists; eexists.\n    exists (rename_per r eqa).\n    dands; spcast; eauto; eauto 3 with slow; tcsp.\n\n    + repeat (rw @rename_name_not_in_upto); auto.\n\n    + introv; unfold rename_per at 1; simpl.\n      rw eqiff.\n      unfold per_effatom_eq.\n\n      split; introv h; exrepnd; spcast.\n\n      * apply (computes_to_valc_rename r) in h0.\n        apply (computes_to_valc_rename r) in h1.\n        autorewrite with slow in *.\n        dands; spcast; auto.\n        repeat (rw @rename_name_not_in_upto); auto.\n\n      * apply (computes_to_valc_rename r) in h0.\n        apply (computes_to_valc_rename r) in h1.\n        autorewrite with slow in *.\n        dands; spcast; auto.\n        repeat (rw @rename_name_not_in_upto in h); auto.\n\n  - Case \"CL_ffatoms\".\n    repeat (autodimp IHcl hyp).\n    apply CL_ffatoms.\n    spcast.\n    unfold per_ffatoms.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow in *.\n\n    eexists; eexists; eexists; eexists.\n    exists (rename_per r eqa).\n    dands; spcast; eauto; eauto 3 with slow; tcsp.\n\n    introv; unfold rename_per at 1; simpl.\n    rw eqiff.\n    unfold per_ffatoms_eq.\n\n    split; introv h; exrepnd; spcast.\n\n    + apply (computes_to_valc_rename r) in h0.\n      apply (computes_to_valc_rename r) in h1.\n      autorewrite with slow in *.\n      dands; spcast; auto.\n      exists (rename_cterm r y); dands; eauto 3 with slow.\n\n    + apply (computes_to_valc_rename r) in h0.\n      apply (computes_to_valc_rename r) in h1.\n      autorewrite with slow in *.\n      dands; spcast; auto.\n      unfold rename_per in *; simpl in *; autorewrite with slow in *.\n      exists (rename_cterm r y); dands; eauto 3 with slow.\n\n  - Case \"CL_set\".\n    apply CL_set.\n    spcast.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow rename in *.\n    repeat (autodimp IHcl hyp).\n\n    exists (rename_per r eqa) (rename_per_fam r eqb).\n    dands.\n\n    + unfold type_family.\n      eexists; eexists; eexists; eexists; eexists; eexists; dands; spcast; eauto.\n      introv.\n\n      dup e as q.\n      apply rename_per_iff in q.\n      unfold rename_per1 in q; exrepnd; subst.\n      revert e; unfold rename_per_fam, rename_per; autorewrite with slow; introv.\n      pose proof (recb a'0 b' e) as q; repeat (autodimp q hyp).\n      unfold rename_per in q; auto.\n      autorewrite with rename in *; auto.\n\n    + introv.\n      split; introv h.\n\n      * dup h as q.\n        apply rename_per_iff in q.\n        unfold rename_per1 in q; exrepnd; subst.\n        apply eqiff in h; exrepnd.\n        apply implies_inhabited_rename_per_fam in h0.\n        eexists; eauto.\n\n      * exrepnd.\n        unfold rename_per.\n        apply eqiff.\n        apply inhabited_rename_per_fam_implies in h0.\n        eexists; eauto.\n\n  - Case \"CL_tunion\".\n    apply CL_tunion.\n    spcast.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow rename in *.\n    repeat (autodimp IHcl hyp).\n\n    exists (rename_per r eqa) (rename_per_fam r eqb).\n    dands.\n\n    + unfold type_family.\n      eexists; eexists; eexists; eexists; eexists; eexists; dands; spcast; eauto.\n      introv.\n\n      dup e as q.\n      apply rename_per_iff in q.\n      unfold rename_per1 in q; exrepnd; subst.\n      revert e; unfold rename_per_fam, rename_per; autorewrite with slow; introv.\n      pose proof (recb a'0 b' e) as q; repeat (autodimp q hyp).\n      unfold rename_per in q; auto.\n      autorewrite with rename in *; auto.\n\n    + introv.\n      unfold rename_per at 1.\n      rw eqiff.\n\n      split; intro h.\n\n      * apply (implies_rename_per_tunion_eq r) in h.\n        autorewrite with slow in *; auto.\n\n      * apply (rename_per_tunion_eq_implies r).\n        autorewrite with slow in *; auto.\n\n  - Case \"CL_product\".\n    apply CL_product.\n    spcast.\n    apply (computes_to_valc_rename r) in c1.\n    apply (computes_to_valc_rename r) in c2.\n    autorewrite with slow rename in *.\n    repeat (autodimp IHcl hyp).\n\n    exists (rename_per r eqa) (rename_per_fam r eqb).\n    dands.\n\n    + unfold type_family.\n      eexists; eexists; eexists; eexists; eexists; eexists; dands; spcast; eauto.\n      introv.\n\n      dup e as q.\n      apply rename_per_iff in q.\n      unfold rename_per1 in q; exrepnd; subst.\n      revert e; unfold rename_per_fam, rename_per; autorewrite with slow; introv.\n      pose proof (recb a'0 b' e) as q; repeat (autodimp q hyp).\n      unfold rename_per in q; auto.\n      autorewrite with rename in *; auto.\n\n    + introv.\n      unfold rename_per at 1.\n      rw eqiff.\n      split; intro h.\n\n      * unfold per_product_eq in *; exrepnd; spcast.\n        apply (computes_to_valc_rename r) in h1.\n        apply (computes_to_valc_rename r) in h2.\n        autorewrite with slow in *.\n        eexists; eexists; eexists; eexists.\n        exists (implies_rename_per r eqa a a' e).\n        dands; spcast; eauto.\n\n        { unfold rename_per; autorewrite with slow; auto. }\n\n        apply implies_rename_per_fam; auto.\n\n      * unfold per_product_eq in *; exrepnd; spcast.\n        apply (computes_to_valc_rename r) in h1.\n        apply (computes_to_valc_rename r) in h2.\n        autorewrite with slow in *.\n        clear h3.\n        unfold rename_per_fam, rename_per in *.\n\n        eexists; eexists; eexists; eexists.\n        exists (implies_rename_per2 r eqa a a' e).\n        dands; spcast; eauto.\nQed.\n\nLemma implies_univi_rename {o} :\n  forall i lib r (t1 t2 : @CTerm o) eq,\n    univi lib i t1 t2 eq\n    -> univi (rename_lib r lib) i (rename_cterm r t1) (rename_cterm r t2) (rename_per r eq).\nProof.\n  induction i as [? ind] using comp_ind_type.\n  introv u; simpl in *.\n  allrw @univi_exists_iff.\n  exrepnd; spcast.\n\n  exists j.\n  dands; auto; spcast.\n\n  - apply (computes_to_valc_rename r) in u2; autorewrite with slow in *; auto.\n\n  - apply (computes_to_valc_rename r) in u3; autorewrite with slow in *; auto.\n\n  - introv; simpl.\n    clear u2 u3.\n    unfold rename_per.\n    rw u0; clear u0.\n    split; introv h; exrepnd.\n\n    + pose proof (implies_close_rename r (fun lib => univi lib j) lib (rename_cterm r A) (rename_cterm r A') eqa) as q.\n      simpl in q; autorewrite with slow in q.\n      repeat (autodimp q hyp).\n      eexists; eauto.\n\n    + pose proof (implies_close_rename r (fun lib => univi lib j) (rename_lib r lib) A A' eqa) as q.\n      simpl in q; autorewrite with slow in q.\n      repeat (autodimp q hyp).\n      eexists; eauto.\nQed.\n\nLemma implies_univ_rename {o} :\n  forall lib r (t1 t2 : @CTerm o) eq,\n    univ lib t1 t2 eq\n    -> univ (rename_lib r lib) (rename_cterm r t1) (rename_cterm r t2) (rename_per r eq).\nProof.\n  introv u; unfold univ in *; exrepnd.\n  exists i.\n  apply implies_univi_rename; auto.\nQed.\n\nLemma implies_close_univ_rename {o} :\n  forall r lib (t1 t2 : @CTerm o) e,\n    close lib (univ lib) t1 t2 e\n    -> close\n         (rename_lib r lib)\n         (univ (rename_lib r lib))\n         (rename_cterm r t1)\n         (rename_cterm r t2)\n         (rename_per r e).\nProof.\n  introv cl.\n  apply implies_close_rename; auto.\n  introv u; apply implies_univ_rename; auto.\nQed.\n\nLemma implies_equality_rename {o} :\n  forall r lib (t1 t2 T : @CTerm o),\n    equality lib t1 t2 T\n    -> equality\n         (rename_lib r lib)\n         (rename_cterm r t1)\n         (rename_cterm r t2)\n         (rename_cterm r T).\nProof.\n  introv equ.\n  unfold equality, nuprl in *; exrepnd.\n  exists (rename_per r eq).\n  unfold rename_per; autorewrite with slow in *.\n  dands; auto;[].\n  fold (rename_per r eq).\n  apply implies_close_univ_rename; auto.\nQed.\n\nLemma rename_cterm_lsubstc {o} :\n  forall r (t : @NTerm o) w s c w' c',\n    rename_cterm r (lsubstc t w s c)\n    = lsubstc (rename_term r t) w' (rename_csub r s) c'.\nProof.\n  introv; apply cterm_eq; simpl.\n  apply rename_csubst.\nQed.\n\nLemma implies_similarity_rename {o} :\n  forall r lib (H : @bhyps o) s1 s2,\n    similarity lib s1 s2 H\n    -> similarity\n         (rename_lib r lib)\n         (rename_csub r s1)\n         (rename_csub r s2)\n         (rename_barehypotheses r H).\nProof.\n  induction H using rev_list_indT; simpl; introv sim; auto.\n\n  - inversion sim; subst; simpl in *; ginv;\n      try constructor; try (complete (destruct hs; ginv)).\n\n  - apply similarity_snoc in sim; exrepnd; subst; simpl in *.\n    repeat (rewrite rename_csub_snoc in * ).\n    rewrite rename_barehypotheses_snoc in *.\n\n    sim_snoc3; dands; autorewrite with slow in *; auto; eauto 3 with slow.\n    destruct a; simpl in *.\n    apply (implies_equality_rename r) in sim1.\n    erewrite rename_cterm_lsubstc in sim1; eauto.\nQed.\n\nLemma rename_csub_idem {o} :\n  forall r (s : @CSub o),\n    rename_csub r (rename_csub r s) = s.\nProof.\n  introv; unfold rename_csub; allrw map_map; unfold compose.\n  apply eq_map_l; introv i; repnd; simpl; autorewrite with slow; auto.\nQed.\nHint Rewrite @rename_csub_idem : slow.\n\nLemma rename_hypothesis_idem {o} :\n  forall r (h : @hypothesis o),\n    rename_hypothesis r (rename_hypothesis r h) = h.\nProof.\n  introv; destruct h; simpl; autorewrite with slow; auto.\nQed.\nHint Rewrite @rename_hypothesis_idem : slow.\n\nLemma rename_barehypotheses_idem {o} :\n  forall r (H : @bhyps o),\n    rename_barehypotheses r (rename_barehypotheses r H) = H.\nProof.\n  introv; unfold rename_barehypotheses; allrw map_map; unfold compose.\n  apply eq_map_l; introv i; repnd; simpl; autorewrite with slow; auto.\nQed.\nHint Rewrite @rename_barehypotheses_idem : slow.\n\nLtac eqh_snoc3 :=\n  match goal with\n  | [ |- eq_hyps _ (snoc ?s1 (?x,?t1)) (snoc ?s2 (?x,?t2)) (snoc _ ?h) ] =>\n    let w  := fresh \"w\" in\n    let c1 := fresh \"c1\" in\n    let c2 := fresh \"c2\" in\n    assert (wf_term (htyp h)) as w;\n    [ auto\n    | assert (cover_vars (htyp h) s1) as c1;\n      [ auto\n      | assert (cover_vars (htyp h) s2) as c2;\n        [ auto\n        | apply eq_hyps_snoc; simpl;\n          exists s1 s2 t1 t2 w c1 c2\n        ]\n      ]\n    ]\n  end.\n\nLemma implies_tequality_rename {o} :\n  forall r lib (t1 t2 : @CTerm o),\n    tequality lib t1 t2\n    -> tequality\n         (rename_lib r lib)\n         (rename_cterm r t1)\n         (rename_cterm r t2).\nProof.\n  introv equ.\n  unfold tequality, nuprl in *; exrepnd.\n  exists (rename_per r eq).\n  apply implies_close_univ_rename; auto.\nQed.\n\nLemma implies_tequalityi_rename {o} :\n  forall r lib i (t1 t2 : @CTerm o),\n    tequalityi lib i t1 t2\n    -> tequalityi\n         (rename_lib r lib)\n         i\n         (rename_cterm r t1)\n         (rename_cterm r t2).\nProof.\n  introv equ.\n  unfold tequalityi, nuprl in *; exrepnd.\n  apply (implies_equality_rename r) in equ; autorewrite with slow in *; auto.\nQed.\n\nLemma implies_eqtypes_rename {o} :\n  forall r lib lvl (t1 t2 : @CTerm o),\n    eqtypes lib lvl t1 t2\n    -> eqtypes\n         (rename_lib r lib)\n         lvl\n         (rename_cterm r t1)\n         (rename_cterm r t2).\nProof.\n  introv equ.\n  destruct lvl; simpl in *.\n  - apply implies_tequality_rename; auto.\n  - apply implies_tequalityi_rename; auto.\nQed.\n\nLemma implies_eq_hyps_rename {o} :\n  forall r lib (H : @bhyps o) s1 s2,\n    eq_hyps lib s1 s2 H\n    -> eq_hyps\n         (rename_lib r lib)\n         (rename_csub r s1)\n         (rename_csub r s2)\n         (rename_barehypotheses r H).\nProof.\n  induction H using rev_list_indT; simpl; introv eqh; auto.\n\n  - inversion eqh; subst; simpl in *; ginv;\n      try constructor; try (complete (destruct hs; ginv)).\n\n  - apply eq_hyps_snoc in eqh; exrepnd; subst; simpl in *.\n    repeat (rewrite rename_csub_snoc in * ).\n    rewrite rename_barehypotheses_snoc in *.\n    eqh_snoc3; dands; autorewrite with slow in *; auto; eauto 3 with slow.\n\n    destruct a; simpl in *.\n    apply (implies_eqtypes_rename r) in eqh0.\n    repeat (erewrite rename_cterm_lsubstc in eqh0); eauto.\nQed.\n\nLemma implies_hyps_functionality_rename {o} :\n  forall r lib s (H : @bhyps o),\n    hyps_functionality lib s H\n    -> hyps_functionality\n         (rename_lib r lib)\n         (rename_csub r s)\n         (rename_barehypotheses r H).\nProof.\n  introv hf sim.\n  apply (implies_similarity_rename r) in sim; autorewrite with slow in *.\n  apply hf in sim.\n  apply (implies_eq_hyps_rename r) in sim; autorewrite with slow in *; auto.\nQed.\n\nLtac clear_eq_left x :=\n  match goal with\n  | [ H : x = _ |- _ ] => clear H\n  end.\n\nLemma renaming_preserves_sequent_true_ext_lib {o} :\n  forall r lib (s : @csequent o),\n    sequent_true_ext_lib lib s\n    -> sequent_true_ext_lib (rename_lib r lib) (rename_csequent r s).\nProof.\n  introv strue.\n  apply sequent_true_ext_lib_all.\n  introv ext sim hf.\n\n  apply (implies_lib_extends_rename_lib r) in ext; autorewrite with slow in *.\n  pose proof (strue (rename_lib r lib0)) as q; clear strue.\n  autodimp q hyp;[].\n\n  rw @VR_sequent_true_ex in q; simpl in q.\n\n  destruct s; simpl in *.\n  destruct x; simpl in *.\n  destruct x; simpl in *.\n  destruct x; simpl in *.\n  autorewrite with slow in *.\n\n  apply (implies_similarity_rename r) in sim; autorewrite with slow in *.\n  apply (implies_hyps_functionality_rename r) in hf; autorewrite with slow in *.\n  apply (q _ (rename_csub r s2)) in hf; auto;[]; clear q.\n  exrepnd.\n\n  destruct concl; simpl in *.\n\n  - exrepnd.\n    introv.\n\n    apply (implies_tequality_rename r) in hf0.\n    apply (implies_equality_rename r) in hf1.\n    autorewrite with slow in *.\n\n    dands.\n\n    + match goal with\n      | [ H : tequality ?a ?b ?c |- tequality ?d ?e ?f] =>\n        assert (tequality a b c = tequality d e f) as xx;[|rewrite <- xx; auto]\n      end.\n      f_equal; apply cterm_eq; simpl;\n        rewrite rename_csubst; autorewrite with slow; auto.\n\n    + match goal with\n      | [ H : equality ?a ?b ?c ?d |- equality ?e ?f ?g ?h] =>\n        assert (equality a b c d = equality e f g h) as xx;[|rewrite <- xx; auto]\n      end.\n      f_equal; apply cterm_eq; simpl;\n        rewrite rename_csubst; autorewrite with slow; auto.\n\n  - apply (implies_tequality_rename r) in hf0.\n    autorewrite with slow in *.\n\n    match goal with\n    | [ H : tequality ?a ?b ?c |- tequality ?d ?e ?f] =>\n      assert (tequality a b c = tequality d e f) as xx;[|rewrite <- xx; auto]\n    end.\n    f_equal; apply cterm_eq; simpl;\n      rewrite rename_csubst; autorewrite with slow; auto.\nQed.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/rules/name_invariance.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.24801663865091342}}
{"text": "Require Import Coqlib.\nRequire Import Maps.\n\nRequire Import Classical_Prop.\n\nRequire Import Integers.\nRequire Import LibTactics.\nOpen Scope Z_scope.\nImport ListNotations.\n\nRequire Import state.\nRequire Import language.\nRequire Import highlang.\nRequire Import lowlang.\nRequire Import logic.\nRequire Import reg_lemma.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nOpen Scope code_scope.\nOpen Scope mem_scope.\n\n(*+ The Event Trace Refinement +*)\nCoInductive Etr :=\n| empEtr : Etr\n| abortEtr : Etr\n| outEtr : Val -> Etr -> Etr. \n\nInductive star_tau_step {prog : Type} (step : prog -> msg -> prog -> Prop) :\n  prog -> prog -> Prop :=\n| zero_tau_step : forall p, star_tau_step step p p\n| multi_tau_step : forall (p p' p'' : prog), star_tau_step step p p' -> step p' tau p'' ->\n                                             star_tau_step step p p''.\n\nCoInductive Etrace {tprog} (step : tprog -> msg -> tprog -> Prop): tprog -> Etr -> Prop :=\n| Etr_tau : forall P P' P'',\n    star_tau_step step P P' -> step P' tau P'' ->\n    Etrace step P'' empEtr -> Etrace step P empEtr\n| Etr_abort : forall P P',\n    star_tau_step step P P' -> (~ (exists P'' m, step P' m P'')) -> Etrace step P abortEtr\n| Etr_event : forall P P' P'' v etr,\n    star_tau_step step P P' -> step P' (out v) P'' ->\n    Etrace step P'' etr -> Etrace step P (outEtr v etr).\n\nDefinition Etr_Refinement (LP : LProg) (HP : HProg) :=\n  forall B, Etrace LP__ LP B -> Etrace HP__ HP B.\n\n(*+ State Relation +*)\nDefinition TaskCur := (0%Z, $0).\n\nDefinition ctxfm R (F F' : FrameList) : Prop :=\n  exists w n F2,\n    get_R R cwp = Some (W w) /\\ get_R R Rwim = Some (W (($ 1) <<ᵢ n)) /\\ w <> n /\\\n    F = F' ++ F2 /\\ ($ 0) <=ᵤᵢ w <=ᵤᵢ ($ 7) /\\ ($ 0) <=ᵤᵢ n <=ᵤᵢ ($ 7) /\\\n    length F' = Nat.mul 2%nat (Z.to_nat (Int.unsigned ((N +ᵢ n -ᵢ w -ᵢ ($ 1)) modu N))) /\\ length F = 13.\n\nDefinition Rinj (LR : RegFile) (HR : HRegFile) :=\n  (forall rr : GenReg, exists v, LR rr = Some v /\\ HR rr = Some v) /\\\n  (forall sr : SpReg, exists w, LR sr = Some (W w)) /\\ (exists w, LR cwp = Some (W w)) /\\\n  (exists w, LR n = Some w /\\ HR fn = Some w) /\\ (exists w, LR z = Some w /\\ HR fz = Some w).\n\nParameter ctx_s ctx_e : int.\n\nDefinition DomCtx (l : Address) (t : Tid) (b : Z) :=\n  match l with\n  | (b', o') => if Z.eq_dec t b' then\n                 (* A location marks the name of thread and a set of locations saving context *)\n                 o' = $ 0 \\/ (int_leu ctx_s o' = true /\\ Int.ltu o' ctx_e = true)\n               else\n                 if Z.eq_dec b b' then\n                   int_leu ($ 0) o' = true /\\ Int.ltu o' ($64) = true /\\ Int.eq (o' modu ($ 4)) ($ 0) = true\n                 else\n                   False\n  end.\n\nDefinition set_Mframe' (b : Z) (ofs : Word) (fm : Frame) :=\n  set_Mframe empM (b, ofs) (b, ofs +ᵢ ($ 4)) (b, ofs +ᵢ ($ 8)) (b, ofs +ᵢ ($ 12))\n             (b, ofs +ᵢ ($ 16)) (b, ofs +ᵢ ($ 20)) (b, ofs +ᵢ ($ 24)) (b, ofs +ᵢ ($ 28)) fm.\n\nInductive stkRel : Z * FrameList * Memory -> HFrameList -> Prop :=\n| LFnilHFnil : forall b, stkRel (b, nil, empM) nil\n\n| LFnilHFcons : forall fm1 fm2 HF M M' b b',\n    M = (set_Mframe' b ($ 0) fm1) ⊎ (set_Mframe' b ($ 32) fm2) ⊎ M' ->\n    (set_Mframe' b ($ 0) fm1) ⊥ (set_Mframe' b ($ 32) fm2) ->\n    ((set_Mframe' b ($ 0) fm1) ⊎ (set_Mframe' b ($ 32) fm2)) ⊥ M' ->\n    get_frame_nth fm2 6 = Some (Ptr (b', $ 0)) ->\n    stkRel (b', nil, M') HF ->\n    stkRel (b, nil, M) ((b, fm1, fm2) :: HF)\n           \n| LFconsHFcons : forall fm1 fm2 F HF M M' b b' fm1' fm2',\n    M = (set_Mframe' b ($ 0) fm1') ⊎ (set_Mframe' b ($ 32) fm2') ⊎ M' ->\n    (set_Mframe' b ($ 0) fm1') ⊥ (set_Mframe' b ($ 32) fm2') ->\n    ((set_Mframe' b ($ 0) fm1') ⊎ (set_Mframe' b ($ 32) fm2')) ⊥ M' ->\n    get_frame_nth fm2 6 = Some (Ptr (b', $ 0)) ->\n    stkRel (b', F, M') HF ->\n    stkRel (b, fm1 :: fm2 :: F, M) ((b, fm1, fm2) :: HF).\n\n(** Current Thread State Relation *)\nInductive curTRel : Memory * RState -> Tid * tlocst -> Prop :=\n| Cur_TRel : forall M Mctx Mk R F F' t HR b b' HF pc npc,\n    (M = Mctx ⊎ Mk /\\ Mctx ⊥ Mk) -> (forall l, (indom l Mctx <-> DomCtx l t b) /\\ t <> b) ->\n    ctxfm R F F' -> stkRel (b', F', Mk) HF -> Rinj R HR ->\n    curTRel (M, (R, F)) (t, ((HR, b, HF), pc, npc)).\n\n(** Ready Thread State Relation *)\nInductive rdyTsRel (restoreQ : Memory -> RState -> Prop) : Memory -> ThrdPool -> Prop :=\n| thrdRel : forall t K M Q,\n    restoreQ M Q -> curTRel (M, Q) (t, K) ->\n    rdyTsRel restoreQ M (ThrdMap.set t (Some K) EmpThrdPool)\n\n| thrdsRel : forall T1 T2 T M1 M2 M,\n    rdyTsRel restoreQ M1 T1 -> rdyTsRel restoreQ M2 T1 ->\n    M1 ⊥ M2 -> T1 ⊥ T2 -> M = M1 ⊎ M2 -> T = T1 ⊎ T2 ->\n    rdyTsRel restoreQ M T.\n\n(** Whole Program State Relation *)\nInductive wp_stateRel (restoreQ : Memory -> RState -> Prop) : State -> HState -> Prop :=\n| Wp_stateRel : forall (M Mc MT M' : Memory) Q T t K M',\n    Mc ⊎ MT ⊎ (MemMap.set TaskCur (Some (Ptr (t, $0))) empM) ⊎ M' = M ->\n    Mc ⊥ MT -> (Mc ⊎ MT) ⊥ (MemMap.set TaskCur (Some (Ptr (t, $0))) empM) ->\n    (Mc ⊎ MT ⊎ (MemMap.set TaskCur (Some (Ptr (t, $0))) empM)) ⊥ M' ->\n    curTRel (Mc, Q) (t, K) ->\n    rdyTsRel restoreQ MT (ThrdMap.set t None T) ->\n    wp_stateRel restoreQ (M, Q, nil) (T, t, K, M').\n\nDefinition get_Hs_pcont (HS : HState) :=\n  match HS with\n  | (T, t, K, M) =>\n    match K with\n    | (HQ, pc, npc) => (pc, npc)\n    end\n  end.\n\n(*+ Primitive Correctness +*)\nDefinition correct (Cas : XCodeHeap) (PrimSet : apSet) (restoreQ : Memory -> RState -> Prop) :=\n  forall C S HS pc npc,\n    wp_stateRel restoreQ S HS -> HProgSafe ((C, PrimSet), HS) ->\n    get_Hs_pcont HS = (pc, npc) -> C ⊥ Cas ->\n    Etr_Refinement (C ⊎ Cas, (S, pc, npc)) ((C, PrimSet), HS).\n\n\n  \n\n\n\n    \n", "meta": {"author": "jpzha", "repo": "VeriSparc", "sha": "7fc60fbc4b4357b93836d1b461d7d27c669e9f58", "save_path": "github-repos/coq/jpzha-VeriSparc", "path": "github-repos/coq/jpzha-VeriSparc/VeriSparc-7fc60fbc4b4357b93836d1b461d7d27c669e9f58/coqimp/ext/refinement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2479878547346572}}
{"text": "From cap_machine Require Import rules_base.\nFrom iris.base_logic Require Export invariants gen_heap.\nFrom iris.program_logic Require Export weakestpre ectx_lifting.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import frac.\n\nSection cap_lang_rules.\n  Context `{memG Σ, regG Σ, MonRef: MonRefG (leibnizO _) CapR_rtc Σ}.\n  Context `{MachineParameters}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types σ : ExecConf.\n  Implicit Types c : cap_lang.expr. \n  Implicit Types a b : Addr.\n  Implicit Types r : RegName.\n  Implicit Types v : cap_lang.val. \n  Implicit Types w : Word.\n  Implicit Types reg : gmap RegName Word.\n  Implicit Types ms : gmap Addr Word.\n\n  Lemma wp_jmp_success E pc_p pc_g pc_b pc_e pc_a w r w' pc_p':\n    decodeInstrW w = Jmp r →\n    PermFlows pc_p pc_p' →\n     isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n\n     {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n         ∗ ▷ pc_a ↦ₐ[pc_p'] w\n         ∗ ▷ r ↦ᵣ w' }}}\n       Instr Executable @ E\n       {{{ RET NextIV;\n           PC ↦ᵣ updatePcPerm w'\n           ∗ pc_a ↦ₐ[pc_p'] w\n           ∗ r ↦ᵣ w' }}}.\n  Proof.\n    iIntros (Hinstr Hfl Hvpc ϕ) \"(>HPC & >Hpc_a & >Hr) Hφ\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 l1 l2 n) \"Hσ1 /=\". destruct σ1; simpl.\n    iDestruct \"Hσ1\" as \"[Hr0 Hm]\".\n    assert (pc_p' ≠ O).\n    { destruct pc_p'; auto. destruct pc_p; inversion Hfl. inversion Hvpc; naive_solver. }\n    iDestruct (@gen_heap_valid_cap with \"Hm Hpc_a\") as %?; auto.\n    iDestruct (@gen_heap_valid with \"Hr0 HPC\") as %?.\n    iDestruct (@gen_heap_valid with \"Hr0 Hr\") as %Hr_r0.\n    iModIntro. iSplitR. by iPureIntro; apply normal_always_head_reducible.\n    iNext. iIntros (e2 σ2 efs Hpstep).\n    apply prim_step_exec_inv in Hpstep as (-> & -> & (c & -> & Hstep)).\n    iSplitR; auto. eapply step_exec_inv in Hstep; eauto.\n\n    rewrite /update_reg /= in Hstep. simplify_pair_eq. cbn.\n    iMod (@gen_heap_update with \"Hr0 HPC\") as \"[Hr0 HPC]\". iFrame.\n    iApply \"Hφ\". iFrame. rewrite /RegLocate Hr_r0. eauto.\n  Qed.\n\n  Lemma wp_jmp_successPC E pc_p pc_g pc_b pc_e pc_a w pc_p' :\n    decodeInstrW w = Jmp PC →\n    PermFlows pc_p pc_p' →\n     isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n\n     {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n         ∗ ▷ pc_a ↦ₐ[pc_p'] w }}}\n       Instr Executable @ E\n       {{{ RET NextIV;\n           PC ↦ᵣ updatePcPerm (inr ((pc_p,pc_g),pc_b,pc_e,pc_a))\n           ∗ pc_a ↦ₐ[pc_p'] w }}}.\n  Proof.\n    iIntros (Hinstr Hfl Hvpc ϕ) \"(>HPC & >Hpc_a) Hφ\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 l1 l2 n) \"Hσ1 /=\". destruct σ1; cbn.\n    iDestruct \"Hσ1\" as \"[Hr0 Hm]\".\n    assert (pc_p' ≠ O).\n    { destruct pc_p'; auto. destruct pc_p; inversion Hfl. inversion Hvpc; naive_solver. }\n    iDestruct (@gen_heap_valid_cap with \"Hm Hpc_a\") as %?; auto.\n    iDestruct (@gen_heap_valid with \"Hr0 HPC\") as %Hr_PC.\n    iModIntro. iSplitR. by iPureIntro; apply normal_always_head_reducible.\n    iNext. iIntros (e2 σ2 efs Hpstep).\n    apply prim_step_exec_inv in Hpstep as (-> & -> & (c & -> & Hstep)).\n    iSplitR; auto. eapply step_exec_inv in Hstep; eauto.\n\n    rewrite /update_reg /= in Hstep. simplify_pair_eq. cbn.\n    rewrite /RegLocate Hr_PC.\n    iMod (@gen_heap_update with \"Hr0 HPC\") as \"[Hr0 HPC]\". iFrame.\n    iApply \"Hφ\". by iFrame.\n  Qed.\n\nEnd cap_lang_rules.\n", "meta": {"author": "logsem", "repo": "cerise-stack", "sha": "f68111362730aff998798d63c7d6a0a7176eff44", "save_path": "github-repos/coq/logsem-cerise-stack", "path": "github-repos/coq/logsem-cerise-stack/cerise-stack-f68111362730aff998798d63c7d6a0a7176eff44/theories/rules/rules_Jmp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2479878547346572}}
{"text": "Require Import Framework File FileDiskLayer FileDiskNoninterference FileDiskRefinement.\nRequire Import FunctionalExtensionality Lia Language.\n\nLemma blocks_allocator_rep_upd:\nforall x4 t0 a v1,\nDiskAllocator.block_allocator_rep x4 t0 ->\nnth_error (value_to_bits (t0 DiskAllocatorParams.bitmap_addr)) a =\nSome true ->\na < DiskAllocatorParams.num_of_blocks ->\nDiskAllocator.block_allocator_rep (Mem.upd x4 a v1)\n(upd t0 (DiskAllocatorParams.bitmap_addr + S a) v1).\nProof.\n  unfold DiskAllocator.block_allocator_rep; intros.\n  cleanup.\n  exists (t0 DiskAllocatorParams.bitmap_addr), (updn x0 a v1).\n  intuition eauto.\n  rewrite upd_ne; eauto; lia.\n  erewrite <- seln_eq_updn_eq with (l:= (value_to_bits (t0 DiskAllocatorParams.bitmap_addr))).\n  erewrite <- upd_nop.\n  eapply DiskAllocator.valid_bits_upd.\n  eauto.\n  rewrite value_to_bits_length; eauto.\n  rewrite value_to_bits_length; eauto.\n  pose proof DiskAllocatorParams.num_of_blocks_in_bounds;\n  unfold DiskAllocatorParams.num_of_blocks in *; lia.\n  erewrite seln_eq_updn_eq.\n  rewrite value_to_bits_to_value.\n  rewrite upd_ne; eauto; lia.\n  eapply nth_error_nth in H0.\n  rewrite nth_seln_eq; eauto.\n  eapply nth_error_nth in H0.\n  rewrite nth_seln_eq; eauto.\n  rewrite updn_length; eauto.\n  rewrite Mem.upd_ne; eauto; lia.\n  Unshelve.\n  all: constructor.\nQed.\n\nLemma file_map_rep_upd:\nforall x inum f off v1 x2 x4 a inode,\nfile_map_rep x x2 x4  ->\nnth_error (Inode.block_numbers inode) off = Some a ->\nx inum = Some f ->\nx2 inum = Some inode ->\nInode.inode_map_valid x2 ->\nfile_map_rep (Mem.upd x inum (update_file f off v1)) x2 (Mem.upd x4 a v1).\nProof.\n  unfold file_map_rep in *; intros; cleanup.\n  split; eauto.\n  unfold addrs_match_exactly in *.\n  intros.\n  destruct (addr_dec inum a0); subst.\n  rewrite Mem.upd_eq; eauto.\n  intuition congruence.\n  rewrite Mem.upd_ne; eauto.\n\n  intros.\n  eapply_fresh H4 in H2; eauto.\n  destruct (addr_dec inum inum0); subst.\n  rewrite Mem.upd_eq in H6; eauto.\n  rewrite H2 in H5.\n  cleanup.\n  unfold file_rep, update_file in *; \n  simpl in *; cleanup.\n  intuition eauto.\n  rewrite updn_length; eauto.\n  destruct (addr_dec i off); subst.\n  cleanup.\n  exists v1.\n  erewrite FileInnerSpecs.nth_error_updn_eq; eauto.                \n  rewrite Mem.upd_eq; eauto.\n  eapply_fresh Inode.nth_error_some_lt in H0; lia.\n  eapply_fresh H7 in H8; cleanup.\n  exists x0.\n  erewrite FileInnerSpecs.nth_error_updn_ne; eauto.               \n  rewrite Mem.upd_ne; eauto.\n  destruct (addr_dec block_number a); eauto; subst.\n  unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n  eapply H3 in H2; cleanup.\n  eapply NoDup_nth_error in H2; eauto.\n  eapply nth_error_Some; eauto.\n  congruence.\n  congruence.\n  rewrite Mem.upd_ne in H6; eauto.\n  eapply_fresh H4 in H5; eauto.\n  unfold file_rep in *; cleanup.\n  intuition eauto. \n  eapply_fresh H9 in H13; eauto; cleanup.\n  eexists; intuition eauto.\n  rewrite Mem.upd_ne; eauto.\n\n  destruct (addr_dec block_number a); eauto; subst.\n  unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n  eapply H16 in H2; eauto.\n  eapply NoDup_nth_error in H2.\n  instantiate (1:= i) in H2;\n  instantiate (1:= length (Inode.block_numbers inode0) + off) in H2.\n  eapply_fresh Inode.nth_error_some_lt in H14; lia.\n  \n  rewrite app_length. \n  eapply_fresh Inode.nth_error_some_lt in H0; lia.\n  rewrite nth_error_app2.\n  rewrite nth_error_app1.\n  replace (length (Inode.block_numbers inode0) + off -\n  length (Inode.block_numbers inode0)) with off.\n  congruence.\n  lia.\n  eapply nth_error_Some; eauto.\n  congruence.\n  lia.\nQed.\n\n\n\nLtac econstructor_recovery :=\n  match goal with\n  | [|- recovery_exec _ ?u [?o] _ [] _ _ _ ]=>\n    eapply (@ExecFinished _ _ _ _ u o)\n  | [|- recovery_exec _ ?u (?o :: _) _ (?rf :: _) _ _ _ ]=>\n    eapply (@ExecRecovered _ _ _ _ u o _ _ _ rf)\n  end.\n\n  Ltac invert_exec_lift_no_match :=\n  match goal with\n  | [H: Language.exec' _ _ _ (Op _ (P1 _)) _ |- _ ]=>\n    invert_exec'' H\n  | [H: Language.exec' _ _ _ (Op _ (P2 _)) _ |- _ ]=>\n    invert_exec'' H\n  | [H: Language.exec' _ _ _ (_ <- lift_L1 _ _; _) _ |- _ ]=>\n    invert_exec'' H\n  | [H: Language.exec' _ _ _ (_ <- lift_L2 _ _; _) _ |- _ ]=>\n    invert_exec'' H\n  | [H: Language.exec' _ _ _ (_ <- Op _ (P1 _); _) _ |- _ ]=>\n    invert_exec'' H\n  | [H: Language.exec' _ _ _ (_ <- Op _ (P2 _); _) _ |- _ ]=>\n    invert_exec'' H\n  | _ =>\n    try invert_exec_no_match\n  end.\n\n  Ltac invert_exec_lift :=\n  match goal with\n  | [H: Language.exec' _ _ _ (Op _ (P1 _)) _ |- _ ]=>\n    invert_exec'' H\n  | [H: Language.exec' _ _ _ (Op _ (P2 _)) _ |- _ ]=>\n    invert_exec'' H\n  | [H: Language.exec' _ _ _ (_ <- lift_L1 _ _; _) _ |- _ ]=>\n    invert_exec'' H\n  | [H: Language.exec' _ _ _ (_ <- lift_L2 _ _; _) _ |- _ ]=>\n    invert_exec'' H\n  | [H: Language.exec' _ _ _ (_ <- Op _ (P1 _); _) _ |- _ ]=>\n    invert_exec'' H\n  | [H: Language.exec' _ _ _ (_ <- Op _ (P2 _); _) _ |- _ ]=>\n    invert_exec'' H\n  | _ =>\n    try invert_exec\n  end.\n\nTheorem Termination_Sensitive_recover:\n  forall u u' n ex,\n      Termination_Sensitive u recover recover recover\n          AD_valid_state (AD_related_states u' ex)\n          (authenticated_disk_reboot_list n).\nProof.\n  induction n; simpl;\n  unfold Termination_Sensitive, AD_valid_state,\n  AD_related_states, FD_valid_state, FD_related_states,\n  refines_valid, refines_related,\n  authenticated_disk_reboot_list in *;\n  intros; cleanup; simpl in *.\n  {\n    invert_exec; cleanup.\n    unfold recover in *; repeat invert_exec; simpl in *.\n    simpl in H11.\n    repeat invert_exec_lift_no_match.\n    eexists.    \n    econstructor_recovery.\n    repeat econstructor.\n  }\n  {\n    invert_exec; cleanup.\n    unfold recover in *; repeat invert_exec; simpl in *.\n    repeat invert_exec_lift_no_match.\n    repeat cleanup_pairs.    \n    destruct s2, s1, p; simpl in *.\n    edestruct IHn.\n    3: apply H15.\n    intros; eauto.\n    intros; eauto.\n    instantiate (2:= (s0, (Empty, (t4, t4)))).\n    unfold refines, files_rep in *; simpl in *.\n    cleanup; do 2 eexists; intuition eauto.\n    eexists.\n    econstructor_recovery.\n    repeat econstructor; eauto.\n    simpl; eauto.\n  }\nQed.\n\nLtac invert_bind :=\nmatch goal with\n|[H: exec' _ _ _ (Ret _) _ |- _] =>\ninvert_exec'' H\n|[H: exec' _ _ _ (Op _ (P1 _)) _ |- _] =>\ninvert_exec'' H\n|[H: exec' _ _ _ (Op _ (P2 _)) _ |- _] =>\ninvert_exec'' H\n|[H: exec' _ _ _ (_ <- _ ; _) _ |- _] =>\ninvert_exec'' H\n| _ =>\n  try invert_exec\nend.\n\nLtac invert_bind_no_match :=\nmatch goal with\n|[H: exec' _ _ _ (Ret _) _ |- _] =>\ninvert_exec'' H\n|[H: exec' _ _ _ (Op _ (P1 _)) _ |- _] =>\ninvert_exec'' H\n|[H: exec' _ _ _ (Op _ (P2 _)) _ |- _] =>\ninvert_exec'' H\n|[H: exec' _ _ _ (_ <- _ ; _) _ |- _] =>\ninvert_exec'' H\n| _ =>\n  try invert_exec_no_match\nend.\n\nSet Nested Proofs Allowed.\nLemma lt_le_lt:\n      forall n m p q,\n      n + m < q -> p <= m -> n + p < q.\nProof.  lia. Qed.\n\nLemma nth_error_None_r :\nforall T (l: list T) n,\nn >= length l ->\nnth_error l n = None.\nProof.\n  apply nth_error_None.\nQed.\n\nLemma bind_reorder_l:\n  forall O (L: Language O) T  \n  (p1: prog L T) T' (p2: T -> prog L T') \n  T'' (p3: T' -> prog L T'') \n  u o s r,\n      exec L u o s (Bind p1 (fun t => Bind (p2 t) p3)) r ->\n      exec L u o s (Bind (Bind p1 p2) p3) r.\nProof.  Proof.\neapply bind_reorder.\nQed.\n\nLemma bind_reorder_r:\n  forall O (L: Language O) T  \n  (p1: prog L T) T' (p2: T -> prog L T') \n  T'' (p3: T' -> prog L T'') \n  u o s r,\n  exec L u o s (Bind (Bind p1 p2) p3) r ->\n      exec L u o s (Bind p1 (fun t => Bind (p2 t) p3)) r.\n      \nProof.  Proof.\neapply bind_reorder.\nQed.\n\nLemma inode_allocations_are_same:\nforall u fm1 fm2 s1 s2 t1 t2 inum ex,\nrefines s1 fm1 ->\nrefines s2 fm2 ->\nsame_for_user_except u ex fm1 fm2 ->\ninum < Inode.InodeAllocatorParams.num_of_blocks ->\nt1 = fst (snd (snd s1)) ->\nt2 = fst (snd (snd s2)) ->\nnth_error\n(value_to_bits\n  (t1 Inode.InodeAllocatorParams.bitmap_addr))\ninum =\nnth_error\n  (value_to_bits (t2 \n  Inode.InodeAllocatorParams.bitmap_addr)) inum.\nProof.\n  unfold refines, files_rep, \n  files_inner_rep, same_for_user_except; intros.\n  cleanup; repeat cleanup_pairs.\n  destruct_fresh (x inum).\n  {\n    eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in D; eauto.\n    cleanup.\n    destruct_fresh (fm1 inum).\n    {\n      destruct_fresh (x1 inum).\n      unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H8.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H4, H8 in D; simpl in *; congruence.\n      rewrite nth_seln_eq in H3.\n      repeat erewrite nth_error_nth'.\n\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H17.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H15, H21 in D1; simpl in *; congruence.\n      rewrite nth_seln_eq in H20.\n      rewrite H3, H20; eauto.\n      all: try rewrite value_to_bits_length;\n      unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n      pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n\n      unfold file_map_rep in *; cleanup.\n      edestruct H7; exfalso.\n      apply H11; eauto; congruence.\n    }\n    {\n      edestruct H1; exfalso.\n      apply H3; eauto; congruence.\n    }\n  }\n  {\n    eapply_fresh FileInnerSpecs.inode_missing_then_file_missing in D; eauto.\n    cleanup.\n    destruct_fresh (fm1 inum).\n    {\n      edestruct H1; exfalso.\n      apply H; eauto; congruence.\n    }\n    destruct_fresh (x1 inum).\n    {\n      unfold file_map_rep in *; cleanup.\n      edestruct H3; exfalso.\n      apply H10; eauto; congruence.\n    }\n    {\n      unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H7.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite nth_seln_eq in H0.\n      repeat erewrite nth_error_nth'.\n\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H16.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite nth_seln_eq in H19.\n      rewrite H0, H19; eauto.\n      rewrite H12, H20 in D1; simpl in *; congruence.\n      all: try rewrite value_to_bits_length;\n      unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n      pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n      rewrite H3, H7 in D; simpl in *; congruence.\n    }\n  }\nQed.\n\nLemma inode_owners_are_same:\nforall u fm1 fm2 s1 s2 inum ex,\nrefines s1 fm1 ->\nrefines s2 fm2 ->\nsame_for_user_except u ex fm1 fm2 ->\ninum < Inode.InodeAllocatorParams.num_of_blocks ->\nnth_error\n(value_to_bits\n  (fst (snd (snd s1)) Inode.InodeAllocatorParams.bitmap_addr))\ninum = Some true ->\n  Inode.owner (Inode.decode_inode\n(fst (snd (snd s1)) (Inode.InodeAllocatorParams.bitmap_addr + S inum))) =\n  Inode.owner\n(Inode.decode_inode\n(fst (snd (snd s2)) (Inode.InodeAllocatorParams.bitmap_addr + S inum))).\nProof.\n  unfold refines, files_rep, \n  files_inner_rep, same_for_user_except; intros.\n  cleanup; repeat cleanup_pairs.\n  destruct_fresh (x1 inum).\n  {\n    eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in D; eauto.\n    cleanup.\n    destruct_fresh (fm2 inum).\n    {\n      destruct_fresh (x inum).\n      eapply_fresh H5 in D0; eauto; cleanup.\n      unfold file_map_rep in *; cleanup.\n      eapply_fresh H10 in D0; eauto.\n      eapply_fresh H14 in D; eauto.\n      unfold file_rep in *; cleanup.\n\n      unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H23.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H21, H23 in D1; simpl in *; congruence.\n      rewrite H21, H23 in D1; simpl in *.\n      cleanup.\n\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H28.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H26, H32 in D; simpl in *; congruence.\n      rewrite H26, H32 in D; simpl in *; cleanup.\n      eauto.\n\n      all: try rewrite value_to_bits_length;\n      unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n      pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n\n      unfold file_map_rep in *; cleanup.\n      edestruct H6; exfalso.\n      apply H14; eauto; congruence.\n    }\n    {\n      edestruct H1; exfalso.\n      apply H0; eauto; congruence.\n    }\n  }\n  {\n    unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H17.\n      cleanup; split_ors; cleanup; try congruence.\n      eapply nth_error_nth in H3.\n      rewrite <- nth_seln_eq in H3.\n      rewrite H0 in H3; congruence.\n      rewrite H15, H17 in D; simpl in *; congruence.\n\n      all: try rewrite value_to_bits_length;\n      unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n      pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n  }\nQed.\n\nLemma inode_owners_are_same':\nforall u fm1 fm2 s1 s2 t1 t2 inum ex,\nrefines s1 fm1 ->\nrefines s2 fm2 ->\nsame_for_user_except u ex fm1 fm2 ->\ninum < Inode.InodeAllocatorParams.num_of_blocks ->\nnth_error\n(value_to_bits\n  (t1 Inode.InodeAllocatorParams.bitmap_addr))\ninum = Some true ->\nt1 = fst (snd (snd s1)) ->\nt2 = fst (snd (snd s2)) ->\n  Inode.owner (Inode.decode_inode\n(t1 (Inode.InodeAllocatorParams.bitmap_addr + S inum))) =\n  Inode.owner\n(Inode.decode_inode\n(t2 (Inode.InodeAllocatorParams.bitmap_addr + S inum))).\nProof.\n  unfold refines, files_rep, \n  files_inner_rep, same_for_user_except; intros.\n  cleanup; repeat cleanup_pairs.\n  destruct_fresh (x1 inum).\n  {\n    eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in D; eauto.\n    cleanup.\n    destruct_fresh (fm2 inum).\n    {\n      destruct_fresh (x inum).\n      eapply_fresh H7 in D0; eauto; cleanup.\n      unfold file_map_rep in *; cleanup.\n      eapply_fresh H8 in D0; eauto.\n      eapply_fresh H12 in D; eauto.\n      unfold file_rep in *; cleanup.\n\n      unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H23.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H21, H23 in D1; simpl in *; congruence.\n      rewrite H21, H23 in D1; simpl in *.\n      cleanup.\n\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H28.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H26, H32 in D; simpl in *; congruence.\n      rewrite H26, H32 in D; simpl in *; cleanup.\n      eauto.\n\n      all: try rewrite value_to_bits_length;\n      unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n      pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n\n      unfold file_map_rep in *; cleanup.\n      edestruct H4; exfalso.\n      apply H12; eauto; congruence.\n    }\n    {\n      edestruct H1; exfalso.\n      apply H0; eauto; congruence.\n    }\n  }\n  {\n    unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H17.\n      cleanup; split_ors; cleanup; try congruence.\n      eapply nth_error_nth in H3.\n      rewrite <- nth_seln_eq in H3.\n      rewrite H0 in H3; congruence.\n      rewrite H13, H17 in D; simpl in *; congruence.\n\n      all: try rewrite value_to_bits_length;\n      unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n      pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n  }\nQed.\n\n\nLemma block_numbers_in_length:\nforall inum off a s2 d' x x0 u ex,\nrefines d' x ->\nrefines s2 x0 ->\nsame_for_user_except u ex x x0 ->\ninum < Inode.InodeAllocatorParams.num_of_blocks ->\nnth_error\n(value_to_bits\n  (fst (snd (snd d')) Inode.InodeAllocatorParams.bitmap_addr))\ninum = Some true ->\nnth_error\n (Inode.block_numbers\n    (Inode.decode_inode\n       (fst (snd (snd d')) (Inode.InodeAllocatorParams.bitmap_addr + S inum))))\n off = Some a ->\noff <\nlength\n(Inode.block_numbers\n(Inode.decode_inode\n  (fst (snd (snd s2))\n     (Inode.InodeAllocatorParams.bitmap_addr + S inum)))).\nProof.\n  unfold refines, files_rep, \n  files_inner_rep, same_for_user_except; intros.\n  cleanup; repeat cleanup_pairs.\n  destruct_fresh (x3 inum).\n  {\n    eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in D; eauto.\n    cleanup.\n    destruct_fresh (x0 inum).\n    {\n      destruct_fresh (x1 inum).\n      eapply_fresh H6 in D0; eauto; cleanup.\n      unfold file_map_rep in *; cleanup.\n      eapply_fresh H11 in D0; eauto.\n      eapply_fresh H15 in D; eauto.\n      unfold file_rep in *; cleanup.\n\n      unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H24.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H22, H24 in D1; simpl in *; congruence.\n      rewrite H22, H24 in D1; simpl in *.\n      cleanup.\n\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H29.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H27, H33 in D; simpl in *; congruence.\n      rewrite H27, H33 in D; simpl in *; cleanup.\n      eapply nth_error_Some; eauto; congruence.\n\n      all: try rewrite value_to_bits_length;\n      unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n      pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n\n      unfold file_map_rep in *; cleanup.\n      edestruct H7; exfalso.\n      apply H15; eauto; congruence.\n    }\n    {\n      edestruct H1; exfalso.\n      apply H0; eauto; congruence.\n    }\n  }\n  {\n    unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H18.\n      cleanup; split_ors; cleanup; try congruence.\n      eapply nth_error_nth in H3.\n      rewrite <- nth_seln_eq in H3.\n      rewrite H0 in H3; congruence.\n      rewrite H16, H18 in D; simpl in *; congruence.\n\n      all: try rewrite value_to_bits_length;\n      unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n      pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n  }\nQed.\n\nLemma block_numbers_oob:\nforall inum off s2 d' x x0 u ex,\nrefines d' x ->\nrefines s2 x0 ->\nsame_for_user_except u ex x x0 ->\ninum < Inode.InodeAllocatorParams.num_of_blocks ->\nnth_error\n(value_to_bits\n  (fst (snd (snd d')) Inode.InodeAllocatorParams.bitmap_addr))\ninum = Some true ->\nnth_error\n (Inode.block_numbers\n    (Inode.decode_inode\n       (fst (snd (snd d')) (Inode.InodeAllocatorParams.bitmap_addr + S inum))))\n off = None ->\noff >=\nlength\n(Inode.block_numbers\n(Inode.decode_inode\n  (fst (snd (snd s2))\n     (Inode.InodeAllocatorParams.bitmap_addr + S inum)))).\n     Proof.\n      unfold refines, files_rep, \n      files_inner_rep, same_for_user_except; intros.\n      cleanup; repeat cleanup_pairs.\n      destruct_fresh (x3 inum).\n      {\n        eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in D; eauto.\n        cleanup.\n        destruct_fresh (x0 inum).\n        {\n          destruct_fresh (x1 inum).\n          eapply_fresh H6 in D0; eauto; cleanup.\n          unfold file_map_rep in *; cleanup.\n          eapply_fresh H11 in D0; eauto.\n          eapply_fresh H15 in D; eauto.\n          unfold file_rep in *; cleanup.\n    \n          unfold Inode.inode_rep, \n          Inode.inode_map_rep,\n          Inode.InodeAllocator.block_allocator_rep in *.\n          cleanup.\n          eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H24.\n          cleanup; split_ors; cleanup; try congruence.\n          rewrite H22, H24 in D1; simpl in *; congruence.\n          rewrite H22, H24 in D1; simpl in *.\n          cleanup.\n    \n          eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H29.\n          cleanup; split_ors; cleanup; try congruence.\n          rewrite H27, H33 in D; simpl in *; congruence.\n          rewrite H27, H33 in D; simpl in *; cleanup.\n          eapply nth_error_None; eauto; congruence.\n    \n          all: try rewrite value_to_bits_length;\n          unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n          pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n    \n          unfold file_map_rep in *; cleanup.\n          edestruct H7; exfalso.\n          apply H15; eauto; congruence.\n        }\n        {\n          edestruct H1; exfalso.\n          apply H0; eauto; congruence.\n        }\n      }\n      {\n        unfold Inode.inode_rep, \n          Inode.inode_map_rep,\n          Inode.InodeAllocator.block_allocator_rep in *.\n          cleanup.\n          eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H18.\n          cleanup; split_ors; cleanup; try congruence.\n          eapply nth_error_nth in H3.\n          rewrite <- nth_seln_eq in H3.\n          rewrite H0 in H3; congruence.\n          rewrite H16, H18 in D; simpl in *; congruence.\n    \n          all: try rewrite value_to_bits_length;\n          unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n          pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n      }\n    Qed.\n\nHint Resolve block_numbers_in_length : core.\nHint Resolve block_numbers_oob : core.\n\nLtac exec_step:= \n  repeat eapply bind_reorder_l;\n  rewrite cons_app; econstructor; \n  [solve [repeat econstructor; eauto] \n  | try solve [repeat econstructor; eauto] ].\n\nLtac invert_step :=\n  simpl in *; \n  try match goal with\n  |[A: exec _ _ _ _ _ _ |- _] =>\n   repeat eapply bind_reorder_r in A \n  end;\n  repeat invert_bind; simpl in *; cleanup;\n  try congruence;\n  try solve [unfold Inode.InodeAllocatorParams.bitmap_addr,\n        Inode.InodeAllocatorParams.num_of_blocks,\n        DiskAllocatorParams.bitmap_addr,\n        DiskAllocatorParams.num_of_blocks in *;\n        pose proof Inode.InodeAllocatorParams.blocks_fit_in_disk; \n        pose proof DiskAllocatorParams.blocks_fit_in_disk; \n        lia].\n\n Ltac invert_step_crash :=\n  simpl in *; \n  try match goal with\n  |[A: exec _ _ _ _ _ _ |- _] =>\n   repeat eapply bind_reorder_r in A \n  end;\n  repeat invert_bind_no_match; simpl in *; try split_ors; cleanup_no_match;\n  try congruence;\n  try solve [unfold Inode.InodeAllocatorParams.bitmap_addr,\n        Inode.InodeAllocatorParams.num_of_blocks,\n        DiskAllocatorParams.bitmap_addr,\n        DiskAllocatorParams.num_of_blocks in *;\n        pose proof Inode.InodeAllocatorParams.blocks_fit_in_disk; \n        pose proof DiskAllocatorParams.blocks_fit_in_disk; \n        lia].\n\n\n\n\nLemma block_nums_inbound:\nforall inum off s2 fm,\nrefines s2 fm ->\ninum < Inode.InodeAllocatorParams.num_of_blocks ->\nnth_error\n(value_to_bits\n  (fst (snd (snd s2)) Inode.InodeAllocatorParams.bitmap_addr))\ninum = Some true ->\n(nth off\n    (Inode.block_numbers\n        (Inode.decode_inode\n          (fst (snd (snd s2)) (Inode.InodeAllocatorParams.bitmap_addr + S inum)))) 0)\n  < DiskAllocatorParams.num_of_blocks.\n  Proof.\n    unfold refines, files_rep, \n    files_inner_rep, same_for_user_except; intros.\n    cleanup; repeat cleanup_pairs.\n    destruct_fresh (x inum).\n    {\n      eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in D; eauto.\n      cleanup.\n      \n      unfold file_rep in *; cleanup.\n  \n        unfold Inode.inode_rep, \n        Inode.inode_map_rep,\n        Inode.InodeAllocator.block_allocator_rep in *.\n        cleanup.\n  \n        eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H7.\n        cleanup; split_ors; cleanup; try congruence.\n        rewrite H3, H10 in D; simpl in *; congruence.\n\n        unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n        eapply_fresh H6 in D; eauto.\n        cleanup.\n        unfold file_map_rep, file_rep in *; cleanup.\n        eapply_fresh H14 in D; eauto; cleanup.\n\n        unfold DiskAllocator.block_allocator_rep in *.\n        rewrite H3, H10 in D; simpl in *; cleanup.\n\n        destruct_fresh (nth_error (Inode.block_numbers (Inode.decode_inode (seln x4 inum value0))) off).\n        eapply_fresh H17 in D; cleanup.\n        eapply nth_error_nth with (d:= 0) in D; rewrite <- D in *.\n\n        destruct (Compare_dec.lt_dec (nth off\n        (Inode.block_numbers\n           (Inode.decode_inode (seln x4 inum value0))) 0) DiskAllocatorParams.num_of_blocks); eauto.\n        rewrite H20 in H21; try congruence; try lia.\n\n        apply nth_error_None in D.\n        rewrite <- nth_seln_eq, seln_oob; eauto.\n        unfold DiskAllocatorParams.num_of_blocks.\n        apply FSParameters.file_blocks_count_nonzero.\n        lia.\n        \n        all: try rewrite value_to_bits_length;\n        unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n        pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n    }\n    {\n      unfold file_rep in *; cleanup.\n        unfold Inode.inode_rep, \n        Inode.inode_map_rep,\n        Inode.InodeAllocator.block_allocator_rep in *.\n        cleanup.\n  \n        eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H6.\n        cleanup; split_ors; cleanup; try congruence.\n        eapply nth_error_nth in H1.\n        rewrite nth_seln_eq in H6; rewrite H6 in H1; congruence.\n        rewrite H2, H9 in D; simpl in *; congruence.\n\n        all: try rewrite value_to_bits_length;\n        unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n        pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n    }\n  Qed.\n\nLemma used_blocks_are_allocated:\nforall s2 off inum fm,\nrefines s2 fm ->\ninum < Inode.InodeAllocatorParams.num_of_blocks ->\noff < length (Inode.block_numbers\n(Inode.decode_inode\n    (fst (snd (snd s2))\n      (Inode.InodeAllocatorParams.bitmap_addr + S inum)))) ->\nnth_error\n(value_to_bits\n  (fst (snd (snd s2)) Inode.InodeAllocatorParams.bitmap_addr))\ninum = Some true ->\nnth_error\n    (value_to_bits\n      (fst (snd (snd s2))\n          DiskAllocatorParams.bitmap_addr))\n    (nth off\n      (Inode.block_numbers\n          (Inode.decode_inode\n            (fst (snd (snd s2))\n                (Inode.InodeAllocatorParams.bitmap_addr + S inum)))) 0) = Some true.\nProof.\n  unfold refines, files_rep, \n  files_inner_rep; intros.\n  cleanup; repeat cleanup_pairs.\n  destruct_fresh (x inum).\n  {\n    eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in D; eauto.\n    cleanup.\n    \n    unfold file_rep in *; cleanup.\n\n      unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H8.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H4, H11 in D; simpl in *; congruence.\n\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply_fresh H7 in D; eauto.\n      cleanup.\n      unfold file_map_rep, file_rep in *; cleanup.\n      eapply_fresh H15 in D; eauto; cleanup.\n\n      unfold DiskAllocator.block_allocator_rep in *.\n      rewrite H4, H11 in D; simpl in *; cleanup.\n\n      destruct_fresh (nth_error (Inode.block_numbers (Inode.decode_inode (seln x4 inum value0))) off).\n      eapply_fresh H18 in D; cleanup.\n      eapply nth_error_nth with (d:= 0) in D; rewrite <- D in *.\n\n      eapply DiskAllocator.valid_bits_extract with (n:= (nth off\n      (Inode.block_numbers\n         (Inode.decode_inode (seln x4 inum value0)))\n      0)) in H19.\n      cleanup; split_ors; cleanup; try congruence.\n      erewrite nth_error_nth'; eauto.\n      rewrite <- nth_seln_eq, H23; eauto.\n\n      rewrite value_to_bits_length.\n      eapply Forall_forall in H14.\n      2: eapply nth_In; eauto.\n      instantiate (1:= 0) in H14.\n      pose proof DiskAllocatorParams.num_of_blocks_in_bounds.\n      eapply PeanoNat.Nat.lt_le_trans; eauto.\n      \n      rewrite H20.\n      eapply Forall_forall in H14.\n      2: eapply nth_In; eauto.\n      instantiate (1:= 0) in H14.\n      pose proof DiskAllocatorParams.num_of_blocks_in_bounds.\n      eapply PeanoNat.Nat.lt_le_trans; eauto.\n\n      rewrite H20, value_to_bits_length. \n      apply DiskAllocatorParams.num_of_blocks_in_bounds.\n      \n      apply nth_error_None in D; lia.\n      lia.\n\n      rewrite H9, value_to_bits_length. \n      apply Inode.InodeAllocatorParams.num_of_blocks_in_bounds.\n  }\n  {\n    unfold file_rep in *; cleanup.\n      unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H7.\n      cleanup; split_ors; cleanup; try congruence.\n      eapply nth_error_nth in H2.\n      rewrite nth_seln_eq in H7; rewrite H7 in H2; congruence.\n      rewrite H3, H10 in D; simpl in *; congruence.\n\n      all: try rewrite value_to_bits_length;\n      unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n      pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n  }\nQed.\n\nLemma data_block_inbounds:\nforall inum off s2 fm,\nrefines s2 fm ->\ninum < Inode.InodeAllocatorParams.num_of_blocks ->\noff < length (Inode.block_numbers\n(Inode.decode_inode\n    (fst (snd (snd s2))\n      (Inode.InodeAllocatorParams.bitmap_addr + S inum)))) ->\nnth_error\n(value_to_bits\n  (fst (snd (snd s2)) Inode.InodeAllocatorParams.bitmap_addr))\ninum = Some true ->\nDiskAllocatorParams.bitmap_addr +\nS\n(nth off\n(Inode.block_numbers\n(Inode.decode_inode\n  (fst (snd (snd (fst s2, snd s2)))\n    (Inode.InodeAllocatorParams.bitmap_addr + S inum)))) 0) <\nFSParameters.data_length.\nProof.\n  unfold refines, files_rep, \n  files_inner_rep; intros.\n  cleanup; repeat cleanup_pairs.\n  destruct_fresh (x inum).\n  {\n    eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in D; eauto.\n    cleanup.\n    \n    unfold file_rep in *; cleanup.\n\n      unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H8.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H4, H11 in D; simpl in *; congruence.\n\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply_fresh H7 in D; eauto.\n      cleanup.\n      unfold file_map_rep, file_rep in *; cleanup.\n      eapply_fresh H15 in D; eauto; cleanup.\n\n      unfold DiskAllocator.block_allocator_rep in *.\n      rewrite H4, H11 in D; simpl in *; cleanup.\n\n      destruct_fresh (nth_error (Inode.block_numbers (Inode.decode_inode (seln x4 inum value0))) off).\n      eapply_fresh H18 in D; cleanup.\n      eapply nth_error_nth with (d:= 0) in D; rewrite <- D in *.\n\n      eapply DiskAllocator.valid_bits_extract with (n:= (nth off\n      (Inode.block_numbers\n         (Inode.decode_inode (seln x4 inum value0)))\n      0)) in H19.\n      cleanup; split_ors; cleanup; try congruence.\n      pose proof DiskAllocatorParams.blocks_fit_in_disk.\n      unfold DiskAllocatorParams.bitmap_addr, DiskAllocatorParams.num_of_blocks in *. \n\n      eapply Forall_forall in H14.\n      2: eapply nth_In; eauto.\n      instantiate (1:= 0) in H14.\n      apply PeanoNat.Nat.le_succ_l in H14.\n      eapply lt_le_lt; eauto.\n      \n      rewrite H20.\n      eapply Forall_forall in H14.\n      2: eapply nth_In; eauto.\n      instantiate (1:= 0) in H14.\n      pose proof DiskAllocatorParams.num_of_blocks_in_bounds.\n      eapply PeanoNat.Nat.lt_le_trans; eauto.\n\n      rewrite H20, value_to_bits_length. \n      apply DiskAllocatorParams.num_of_blocks_in_bounds.\n      \n      apply nth_error_None in D; lia.\n      lia.\n\n      rewrite H9, value_to_bits_length. \n      apply Inode.InodeAllocatorParams.num_of_blocks_in_bounds.\n  }\n  {\n    unfold file_rep in *; cleanup.\n      unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H7.\n      cleanup; split_ors; cleanup; try congruence.\n      eapply nth_error_nth in H2.\n      rewrite nth_seln_eq in H7; rewrite H7 in H2; congruence.\n      rewrite H3, H10 in D; simpl in *; congruence.\n\n      all: try rewrite value_to_bits_length;\n      unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n      pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds; try lia.\n  }\nQed.\n\nHint Resolve data_block_inbounds: core.\n\nLtac substitute_facts :=\ntry \n  match goal with\n  |[A: nth_error (value_to_bits (?t Inode.InodeAllocatorParams.bitmap_addr)) ?n = _ \n        |- context [nth_error (value_to_bits (?y Inode.InodeAllocatorParams.bitmap_addr)) ?n] ] =>\n  erewrite <- inode_allocations_are_same with (t1 := t)(t2:= y);\n  [ | | | eauto | | |]; \n  try match goal with\n  | [|- refines _ _ ] =>\n  eauto\n  end; eauto;\n  try solve [repeat cleanup_pairs; simpl; eauto]\n  end;\ntry (match goal with\n  |[A: nth_error ?x ?n = _ |- context [nth_error ?x ?n] ] =>\n  setoid_rewrite A\n  end; simpl);\ntry match goal with\n  |[A: nth_error (Inode.block_numbers _) _ = Some _ \n  |- context [nth_error (Inode.block_numbers _) _] ] =>\n  erewrite nth_error_nth' with (d:= 0)\n  end;\ntry match goal with\n  |[A: nth_error (Inode.block_numbers _) ?n = None \n  |- context [nth_error (Inode.block_numbers _) ?n] ] =>\n  setoid_rewrite nth_error_None_r; eauto\n  end;\ntry match goal with\n  |[ A: refines ?s2 _,\n  A0: ?inum < Inode.InodeAllocatorParams.num_of_blocks,\nA1: nth_error\n(value_to_bits\n  (fst (snd _) Inode.InodeAllocatorParams.bitmap_addr))\n?inum = Some true |- context [Compare_dec.lt_dec \n  (nth ?off (Inode.block_numbers (Inode.decode_inode\n  (fst (snd (snd (fst ?s2, snd ?s2)))\n      (Inode.InodeAllocatorParams.bitmap_addr + S ?inum)))) ?def) ?c] ] =>\n      pose proof A1 as A2;\n      erewrite inode_allocations_are_same in A2;\n      [| | | eauto | | |]; \n      try match goal with\n      | [|- refines _ _ ] =>\n      eauto\n      end; eauto;\n      try solve [repeat cleanup_pairs; simpl; eauto];\n      pose proof (block_nums_inbound inum off s2 _ A A0 A2);\n  cleanup;\n  destruct (Compare_dec.lt_dec \n  (nth off (Inode.block_numbers (Inode.decode_inode\n  (fst (snd s2)\n      (Inode.InodeAllocatorParams.bitmap_addr + S inum)))) def) c) eqn:X; \n      [|simpl in *; lia];\n      setoid_rewrite X\nend;\ntry match goal with\n| [A: refines (_, (_, (?t, _))) ?x,\n  A0: refines ?s2 ?x0,\n  A1: same_for_user_except _ _ ?x ?x0\n  |- exec' (Inode.owner (Inode.decode_inode (?t _))) _ _ _ _ ] =>\n  erewrite inode_owners_are_same';\n  [| | | eauto | | | |];\n  try match goal with\n      | [|- refines _ _ ] =>\n      eauto\n      end; eauto;\n  try solve [repeat cleanup_pairs; simpl; eauto]\n\n|[A: refines ?x4 ?x,\n  A0: refines ?s2 ?x0,\n  A1: same_for_user_except _ _ ?x ?x0\n|- context[Some (Inode.owner (Inode.decode_inode \n(fst (snd (snd (fst ?s2, snd ?s2))) _)))] ] =>\n  erewrite inode_owners_are_same with (s1:= x4)(s2:= s2);\n  [| | | eauto | |];\n  try match goal with\n      | [|- refines _ _ ] =>\n      eauto\n      end; eauto;\n  try solve [repeat cleanup_pairs; simpl; eauto]\nend;\ntry \n  match goal with\n  |[|- context [nth_error (value_to_bits (_ DiskAllocatorParams.bitmap_addr)) \n  (nth _ (Inode.block_numbers _) _)] ] =>\n  erewrite used_blocks_are_allocated; eauto\n  end.\n\nLtac solve_termination :=  \n  match goal with\n  [H: refines ?s1 ?x,\n  H0: refines ?s2 ?x0, \n  H1: same_for_user_except _ _ ?x ?x0,\n  A : recovery_exec' _ _ _ _ _ _ _ |- _] =>  \n    eapply Termination_Sensitive_recover in A;\n    try instantiate (1:= (fst s2, (Empty, (snd (snd (snd s2)), snd (snd (snd s2)))))) in A;\n    unfold AD_valid_state, refines_valid, FD_valid_state; \n    intros; eauto\n  end;\n  repeat match goal with\n  |  [A: fst ?x = fst ?y,\n  A0: snd ?x = snd ?y |- _] =>\n  assert(x = y); [repeat cleanup_pairs; eauto|];\n    subst; clear A A0\n  end;\n  match goal with\n  [A : AD_related_states _ _ _ _ -> \n  exists _, recovery_exec _ _ _ _ _ _ _ _ |- _] =>  \n    edestruct A; clear A\n  end;\n    [ unfold AD_related_states, refines_related, FD_related_states;\n      do 2 eexists; intuition eauto;\n      simpl in *; unfold refines in *;\n      repeat cleanup_pairs;\n      unfold files_rep in *; \n      cleanup; simpl in *; \n      subst; eauto\n    |];\n  try match goal with\n    [A : recovery_exec _ _ _ (fst ?s2, _) _ _ _ ?s2' |- _] =>  \n      exists (Recovered (extract_state_r s2'));\n      econstructor_recovery; [|\n        instantiate (1 := s2); eauto ]\n    end;\n    repeat eapply bind_reorder_l;\n    repeat (\n      repeat eapply bind_reorder_l;\n      repeat exec_step;\n      substitute_facts;\n      repeat eapply bind_reorder_l;\n      repeat exec_step);\n    repeat eapply bind_reorder_l;\n    try solve[\n      eauto;\n    repeat (rewrite cons_app;\n    eapply ExecBindCrash);\n    repeat rewrite app_nil_r;\n    repeat cleanup_pairs;\n    repeat econstructor; eauto].\n\nLtac solve_illegal_state := \ntry match goal with\n|[H: nth_error (Inode.block_numbers _) _ = Some ?a,\nH0: nth_error (value_to_bits (_ DiskAllocatorParams.bitmap_addr)) ?a = Some false |- _] =>\neapply nth_error_nth in H as Htemp; \nrewrite <- Htemp in *;\nerewrite used_blocks_are_allocated in H0; \ntry congruence; eauto;\n[ repeat cleanup_pairs; eauto\n| eapply nth_error_Some; eauto;\nsetoid_rewrite H; congruence]\nend; \ntry match goal with\n|[H: nth_error (Inode.block_numbers _) _ = Some ?a,\nH0: nth_error (value_to_bits (_ DiskAllocatorParams.bitmap_addr)) ?a = None |- _] =>\neapply nth_error_nth in H as Htemp; \nrewrite <- Htemp in *;\nerewrite used_blocks_are_allocated in H0; \ntry congruence; eauto;\n[ repeat cleanup_pairs; eauto\n| eapply nth_error_Some; eauto;\nsetoid_rewrite H; congruence]\nend;\ntry match goal with\n|[H: ~ ?a < _,\nH0: nth_error (Inode.block_numbers _) _ = Some ?a |- _] =>\n    exfalso; apply H;\n    eapply nth_error_nth in H0; \n    rewrite <- H0;\n    eapply block_nums_inbound; eauto;\n    repeat cleanup_pairs; eauto\nend;\nmatch goal with\n|[H: ?inum < Inode.InodeAllocatorParams.num_of_blocks,\nH0: nth_error (value_to_bits (_ Inode.InodeAllocatorParams.bitmap_addr)) ?inum = None |- _] =>\n    apply nth_error_None in H0;\n    rewrite value_to_bits_length in H0;\n    pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds;\n    unfold Inode.InodeAllocatorParams.num_of_blocks in *;\n    lia\nend.\n\nLtac solve_termination_after_commit:=\nmatch goal with\n    [H: refines ?s1 ?x,\n    H0: refines ?s2 ?x0, \n    H1: same_for_user_except _ _ ?x ?x0,\n    A : recovery_exec' _ _ _ _ _ _ _ |- _] =>  \n      eapply Termination_Sensitive_recover in A;\n      try instantiate (1:= (fst s2, (Empty, (fst (snd (snd s2)), fst (snd (snd s2)))))) in A;\n      unfold AD_valid_state, refines_valid, FD_valid_state; \n      intros; eauto\n    end;\n    repeat match goal with\n    |  [A: fst ?x = fst ?y,\n    A0: snd ?x = snd ?y |- _] =>\n    assert(x = y); [repeat cleanup_pairs; eauto|];\n      subst; clear A A0\n    end;\n    match goal with\n    [A : AD_related_states _ _ _ _ -> \n    exists _, recovery_exec _ _ _ _ _ _ _ _ |- _] =>  \n      edestruct A; clear A\n    end;\n      [ unfold AD_related_states, refines_related, FD_related_states;\n        do 2 eexists; intuition eauto;\n        simpl in *; unfold refines in *;\n        repeat cleanup_pairs;\n        unfold files_rep in *; \n        cleanup; simpl in *; \n        subst; repeat cleanup_pairs; eauto\n      |];\n    try match goal with\n      [A : recovery_exec _ _ _ ?s2 _ _ _ ?s2' |- _] =>  \n        exists (Recovered (extract_state_r s2'));\n        econstructor_recovery; [|\n          instantiate (1 := s2); eauto ]\n      end;\n      repeat eapply bind_reorder_l;\n      repeat (\n        repeat eapply bind_reorder_l;\n        repeat exec_step;\n        repeat substitute_facts;\n        repeat eapply bind_reorder_l;\n        repeat exec_step);\n      repeat eapply bind_reorder_l;\n      try solve[\n        eauto;\n      repeat (rewrite cons_app;\n      eapply ExecBindCrash);\n      repeat cleanup_pairs;\n      repeat econstructor; eauto].\n\n\nLtac solve_termination_after_abort :=  \nmatch goal with\n[H: refines ?s1 ?x,\nH0: refines ?s2 ?x0, \nH1: same_for_user_except _ _ ?x ?x0,\nA : recovery_exec' _ _ _ _ _ _ _ |- _] =>  \n  eapply Termination_Sensitive_recover in A;\n  try instantiate (1:= (fst s2, (Empty, (snd (snd (snd s2)), snd (snd (snd s2)))))) in A;\n  unfold AD_valid_state, refines_valid, FD_valid_state; \n  intros; eauto\nend;\nrepeat match goal with\n|  [A: fst ?x = fst ?y,\nA0: snd ?x = snd ?y |- _] =>\nassert(x = y); [repeat cleanup_pairs; eauto|];\n  subst; clear A A0\nend;\nmatch goal with\n[A : AD_related_states _ _ _ _ -> \nexists _, recovery_exec _ _ _ _ _ _ _ _ |- _] =>  \n  edestruct A; clear A\nend;\n  [ unfold AD_related_states, refines_related, FD_related_states;\n    do 2 eexists; intuition eauto;\n    simpl in *; unfold refines in *;\n    repeat cleanup_pairs;\n    unfold files_rep in *; \n    cleanup; simpl in *; \n    subst; eauto\n  |];\ntry match goal with\n  [A : recovery_exec _ _ _ (fst ?s2, _) _ _ _ ?s2' |- _] =>  \n    exists (Recovered (extract_state_r s2'));\n    econstructor_recovery; [|\n      instantiate (1 := (fst s2, (Empty, (snd (snd (snd s2)), snd (snd (snd s2)))))); eauto ]\n  end;\n  repeat eapply bind_reorder_l;\n  repeat (\n    repeat eapply bind_reorder_l;\n    repeat exec_step;\n    repeat substitute_facts;\n    repeat eapply bind_reorder_l;\n    repeat exec_step);\n  repeat eapply bind_reorder_l;\n  try solve[\n    eauto;\n  repeat (rewrite cons_app;\n  eapply ExecBindCrash);\n  repeat cleanup_pairs;\n  repeat econstructor; eauto].\n\n\n  Lemma data_block_inbounds_2:\nforall inum off s fm im dm inode,\nInode.inode_rep im s ->\nFile.DiskAllocator.block_allocator_rep dm s ->\nFile.file_map_rep fm im dm ->\nim inum = Some inode ->\noff < length (Inode.block_numbers inode) ->\nFile.DiskAllocatorParams.bitmap_addr +\nS (seln (Inode.block_numbers inode) off 0) <\nFSParameters.data_length.\nProof.\n  intros.\n  cleanup; repeat cleanup_pairs.\n    eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H2; eauto.\n    cleanup.\n    \n      unfold Inode.inode_rep, \n      Inode.inode_map_rep,\n      Inode.InodeAllocator.block_allocator_rep in *.\n      cleanup.\n\n      eapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H7.\n      cleanup; split_ors; cleanup; try congruence.\n      rewrite H5, H10 in H2; simpl in *; congruence.\n\n      unfold Inode.inode_map_valid, Inode.inode_valid in *; cleanup.\n      eapply_fresh H6 in H2; eauto.\n      cleanup.\n      unfold File.file_map_rep, File.file_rep in *; cleanup.\n      eapply_fresh H14 in H2; eauto; cleanup.\n\n      unfold File.DiskAllocator.block_allocator_rep in *.\n      rewrite H5, H10 in H2; simpl in *; cleanup.\n\n      destruct_fresh (nth_error (Inode.block_numbers (Inode.decode_inode (seln x2 inum value0))) off).\n      eapply_fresh H17 in D; cleanup.\n      eapply nth_error_nth with (d:= 0) in D; rewrite <- D in *.\n\n      eapply File.DiskAllocator.valid_bits_extract with (n:= (nth off\n      (Inode.block_numbers\n         (Inode.decode_inode (seln x2 inum value0)))\n      0)) in H18.\n      cleanup; split_ors; cleanup; try congruence.\n      pose proof File.DiskAllocatorParams.blocks_fit_in_disk.\n      unfold File.DiskAllocatorParams.bitmap_addr, File.DiskAllocatorParams.num_of_blocks in *. \n\n      eapply Forall_forall in H13.\n      2: eapply nth_In; eauto.\n      instantiate (1:= 0) in H13.\n      apply PeanoNat.Nat.le_succ_l in H13.\n      eapply TSCommon.lt_le_lt; eauto.\n      rewrite nth_seln_eq; eauto.\n      \n\n      rewrite H19.\n      eapply Forall_forall in H13.\n      2: eapply nth_In; eauto.\n      instantiate (1:= 0) in H13.\n      pose proof File.DiskAllocatorParams.num_of_blocks_in_bounds.\n      eapply PeanoNat.Nat.lt_le_trans; eauto.\n\n      rewrite H19, value_to_bits_length. \n      apply File.DiskAllocatorParams.num_of_blocks_in_bounds.\n      \n      apply nth_error_None in D; lia.\n      destruct (Compare_dec.lt_dec inum (length x2)); eauto.\n      rewrite H5, H9 in H2; simpl in *; try congruence; try lia.\n\n      rewrite H8, value_to_bits_length. \n      apply Inode.InodeAllocatorParams.num_of_blocks_in_bounds.\nQed.\n\nSet Nested Proofs Allowed.\nLemma used_blocks_are_allocated_2:\nforall s off inum im inode dm fm,\nInode.inode_rep im s ->\nFile.DiskAllocator.block_allocator_rep\n     dm s ->\n     File.file_map_rep fm im dm ->\nim inum = Some inode ->\noff < length (Inode.block_numbers inode) ->\nnth_error\n  (value_to_bits\n    (s File.DiskAllocatorParams.bitmap_addr))\n  (seln (Inode.block_numbers inode) off 0) = Some true.\nProof.\nintros.\neapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H2; eauto.\ncleanup.\nunfold Inode.inode_rep, Inode.inode_map_rep,\nInode.inode_map_valid,\nInode.inode_valid,\nInode.InodeAllocator.block_allocator_rep in *; cleanup.\nmatch goal with\n     | [H: ?x1 ?inum = Some _,\n        H1: forall _ _, \n        ?x1 _ = Some _ -> _ /\\ _|- _] =>\n        eapply_fresh H1 in H; eauto; cleanup\nend.\n     \nmatch goal with\n| [H: Forall _ (Inode.block_numbers _)|- _] =>\n  eapply_fresh Forall_forall in H; [| eapply in_seln; eauto]\nend;\nunfold File.DiskAllocatorParams.num_of_blocks; intuition eauto.\ndestruct (Compare_dec.lt_dec inum Inode.InodeAllocatorParams.num_of_blocks).\n{\n  match goal with\n| [H: Inode.InodeAllocator.valid_bits\n_ _ (value_to_bits\n   (?s1\n      Inode.InodeAllocatorParams.bitmap_addr))\n?s1 |- _] =>\neapply Inode.InodeAllocator.valid_bits_extract with (n:= inum) in H; eauto\nend.\nall: try solve [pose proof Inode.InodeAllocatorParams.num_of_blocks_in_bounds;\ntry rewrite value_to_bits_length;\nunfold Inode.InodeAllocatorParams.num_of_blocks in *; try lia].\ncleanup; split_ors; cleanup; try congruence.\n- rewrite H5, H13 in H2; simpl in *; congruence.\n- unfold File.file_map_rep, File.file_rep in *; cleanup.\neapply_fresh a0 in H2; eauto; cleanup.\n\nunfold File.DiskAllocator.block_allocator_rep in *.\ncleanup.\nrewrite H5, H13 in H2; simpl in *; cleanup.\n\ndestruct_fresh (nth_error (Inode.block_numbers (Inode.decode_inode (seln x2 inum value0))) off).\neapply_fresh H15 in D; cleanup.\neapply nth_error_nth with (d:= 0) in D; rewrite <- D in *.\n\neapply File.DiskAllocator.valid_bits_extract with (n:= (nth off\n(Inode.block_numbers\n   (Inode.decode_inode (seln x2 inum value0)))\n0)) in v.\ncleanup; split_ors; cleanup; try congruence.\nerewrite nth_error_nth'; eauto.\nerewrite <- nth_seln_eq, <- H17; eauto.\nrepeat rewrite nth_seln_eq; eauto.\n\nrewrite value_to_bits_length.\npose proof File.DiskAllocatorParams.num_of_blocks_in_bounds.\neapply PeanoNat.Nat.lt_le_trans; eauto.\n\nrewrite e0.\nrewrite <- nth_seln_eq.\nunfold File.DiskAllocatorParams.num_of_blocks in *;\npose proof File.DiskAllocatorParams.num_of_blocks_in_bounds.\neapply PeanoNat.Nat.lt_le_trans; eauto.\n\nrewrite e0, value_to_bits_length. \napply File.DiskAllocatorParams.num_of_blocks_in_bounds.\n\napply nth_error_None in D; lia.\n}\n{\n  unfold Inode.inode_rep, Inode.inode_map_rep,\n    Inode.inode_map_valid,\n    Inode.inode_valid,\n    Inode.InodeAllocator.block_allocator_rep in *; cleanup.\n    \n    rewrite H5, H10 in *; \n    simpl in *; try lia; try congruence.\n}\nQed.", "meta": {"author": "Atalay-Ileri", "repo": "ConFrm", "sha": "80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf", "save_path": "github-repos/coq/Atalay-Ileri-ConFrm", "path": "github-repos/coq/Atalay-Ileri-ConFrm/ConFrm-80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf/Storage/TerminationSensivitiy/FD_TS/TSCommon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24798784920831338}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\nRequire Import Sequential.\n\nFrom PromisingLib Require Import Event.\n\nSection NOMIX.\n  Variable loc_na: Loc.t -> Prop.\n  Variable loc_at: Loc.t -> Prop.\n\n  Definition _nomix\n             (nomix: forall (lang: language) (st: lang.(Language.state)), Prop)\n             (lang: language) (st: lang.(Language.state)): Prop :=\n    forall st1 e\n           (STEP: lang.(Language.step) e st st1),\n      (<<NA: forall l c (NA: is_atomic_event e = false) (ACC: is_accessing e = Some (l, c)), loc_na l>>) /\\\n        (<<AT: forall l c (AT: is_atomic_event e = true) (ACC: is_accessing e = Some (l, c)), loc_at l>>) /\\\n        (<<CONT: nomix lang st1>>)\n  .\n\n  Definition nomix := paco2 _nomix bot2.\n  Arguments nomix: clear implicits.\n\n  Lemma nomix_mon: monotone2 _nomix.\n  Proof.\n    ii. exploit IN; eauto. i. des. splits.\n    { i. hexploit NA; eauto. }\n    { i. hexploit AT; eauto. }\n    { auto. }\n  Qed.\n  #[local] Hint Resolve nomix_mon: paco.\nEnd NOMIX.\n\n#[export] Hint Resolve nomix_mon: paco.\n#[export] Hint Resolve cpn2_wcompat: paco.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/sequential/NoMix.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.24797007252647155}}
{"text": "Require Import Kami.Syntax Kami.Compiler.Compiler.\nRequire Import Kami.Notations.\n\nSection Simple.\n\n  Variable ty : Kind -> Type.\n  Variable regMapTy : Type.\n\n  Inductive RmeSimple :=\n  | VarRME (v : regMapTy) : RmeSimple\n  | UpdRegRME (r : string)(pred : Bool @# ty)(k : FullKind)(val : Expr ty k)(regMap : RmeSimple) : RmeSimple\n  | WriteRME (idxNum num : nat) (writePort dataArray : string) (idx  : Bit (Nat.log2_up idxNum) @# ty) (Data : Kind)\n             (val : Array num Data @# ty)\n             (mask : option (Array num Bool @# ty)) (pred : Bool @# ty) (writeMap readMap : RmeSimple)\n             (arr : Array idxNum Data @# ty) : RmeSimple\n  | ReadReqRME (idxNum num : nat) (readReq readReg dataArray : string) (idx : Bit (Nat.log2_up idxNum) @# ty) (Data : Kind)\n               (isAddr : bool) (pred : Bool @# ty) (writeMap readMap : RmeSimple)\n               (arr : Array idxNum Data @# ty) : RmeSimple\n  | ReadRespRME (idxNum num : nat) (readResp readReg dataArray writePort : string) (isWriteMask: bool) (Data : Kind)\n               (isAddr : bool) (writeMap readMap : RmeSimple) : RmeSimple\n  | AsyncReadRME (idxNum num : nat) (readPort dataArray writePort : string) (isWriteMask: bool)\n                 (idx : Bit (Nat.log2_up idxNum) @# ty) (pred : Bool @# ty)\n                 (k : Kind)(writeMap readMap : RmeSimple) : RmeSimple\n  | CompactRME (regMap: RmeSimple): RmeSimple.\n\n  Fixpoint RmeSimple_of_RME(x : RegMapExpr ty regMapTy) : RmeSimple :=\n    match x with\n    | VarRegMap v => VarRME v\n    | UpdRegMap r pred k val regMap => UpdRegRME r pred val (RmeSimple_of_RME regMap)\n    | CompactRegMap x' => CompactRME (RmeSimple_of_RME x')\n    end.\n\n  Inductive CompActionSimple : Kind -> Type :=\n  | CompCall_simple (f : string)(argRetK : Kind * Kind)(pred : Bool @# ty)(arg : fst argRetK @# ty)\n                    lret (cont : fullType ty (SyntaxKind (snd argRetK)) -> CompActionSimple lret) : CompActionSimple lret\n  | CompLetExpr_simple k (e : Expr ty k) lret (cont : fullType ty k -> CompActionSimple lret) : CompActionSimple lret\n  | CompNondet_simple k lret (cont : fullType ty k -> CompActionSimple lret) : CompActionSimple lret\n  | CompSys_simple (pred: Bool @# ty) (ls: list (SysT ty)) lret (cont: CompActionSimple lret): CompActionSimple lret\n  | CompReadReg_simple (r: string) (k: FullKind) (readMap : RmeSimple) lret\n                       (cont: fullType ty k -> CompActionSimple lret): CompActionSimple lret\n  | CompRet_simple lret (e: lret @# ty) (newMap: RmeSimple) : CompActionSimple lret\n  | CompLetFull_simple k (a: CompActionSimple k) lret (cont: fullType ty (SyntaxKind k) ->\n                                                      regMapTy -> CompActionSimple lret): CompActionSimple lret\n  | CompWrite_simple (idxNum : nat) (Data : Kind) (writePort dataArray : string) (readMap : RmeSimple) lret\n                     (cont : ty (Array idxNum Data) -> CompActionSimple lret) : CompActionSimple lret\n  | CompSyncReadReq_simple (idxNum num : nat) (Data : Kind) (readReq readReg dataArray : string) (isAddr : bool)\n                           (readMap : RmeSimple) lret\n                           (cont : ty (Array idxNum Data) -> CompActionSimple lret) : CompActionSimple lret\n  | CompSyncReadRes_simple (idxNum num : nat) (readResp readReg dataArray writePort : string) (isWriteMask: bool) (Data : Kind) (isAddr : bool)\n                           (readMap : RmeSimple) lret\n                           (cont : fullType ty (SyntaxKind (Array num Data)) -> CompActionSimple lret) : CompActionSimple lret\n  | CompAsyncRead_simple (idxNum num : nat) (readPort dataArray writePort : string) (isWriteMask: bool) (idx : Bit (Nat.log2_up idxNum) @# ty)\n                         (pred : Bool @# ty)\n                         (k : Kind)\n                         (readMap : RmeSimple) lret\n                         (cont : fullType ty (SyntaxKind (Array num k)) -> CompActionSimple lret) : CompActionSimple lret.\n\n  Fixpoint CompActionSimple_of_CA{k}(a : CompActionT ty regMapTy k) : CompActionSimple k :=\n    match a with\n    | CompCall f argRetK pred arg lret cont => CompCall_simple f argRetK pred arg (fun x => CompActionSimple_of_CA (cont x))\n    | CompLetExpr k e lret cont => CompLetExpr_simple e (fun x => CompActionSimple_of_CA (cont x))\n    | CompNondet k lret cont => CompNondet_simple k (fun x => CompActionSimple_of_CA (cont x))\n    | CompSys pred ls lret cont => CompSys_simple pred ls (CompActionSimple_of_CA cont)\n    | CompRead r k readMap lret cont => CompReadReg_simple r k (RmeSimple_of_RME readMap)\n                                                           (fun x => CompActionSimple_of_CA (cont x))\n    | CompRet lret e newMap => CompRet_simple e (RmeSimple_of_RME newMap)\n    | CompLetFull k a lret cont => CompLetFull_simple (CompActionSimple_of_CA a) (fun x y => CompActionSimple_of_CA (cont x y))\n    | CompWrite idxNum num writePort dataArray idx Data val mask pred writeMap readMap lret cont =>\n      @CompWrite_simple idxNum Data writePort dataArray (RmeSimple_of_RME readMap) lret\n                        (fun arr => \n                           CompLetFull_simple (CompRet_simple (($$ WO)%kami_expr : Void @# ty)\n                                                              (@WriteRME idxNum num writePort dataArray idx Data val mask pred\n                                                                         (RmeSimple_of_RME writeMap)\n                                                                         (RmeSimple_of_RME readMap) (#arr)%kami_expr))\n                                              (fun _ y => CompActionSimple_of_CA (cont y)))\n    | CompSyncReadReq idxNum num readReq readReg dataArray idx Data isAddr pred writeMap readMap lret cont =>\n      @CompSyncReadReq_simple idxNum num Data readReq readReg dataArray isAddr (RmeSimple_of_RME readMap) lret\n                              (fun x => CompLetFull_simple (CompRet_simple (($$ WO)%kami_expr : Void @# ty)\n                                                                           (@ReadReqRME idxNum num readReq readReg dataArray\n                                                                                        idx Data isAddr pred\n                                                                                        (RmeSimple_of_RME writeMap)\n                                                                                        (RmeSimple_of_RME readMap)\n                                                                                        (#x)%kami_expr))\n                                                           (fun _ y => CompActionSimple_of_CA (cont y)))\n    | CompSyncReadRes idxNum num readResp readReg dataArray writePort isWriteMask Data isAddr writeMap readMap lret cont =>\n      CompSyncReadRes_simple idxNum readResp readReg dataArray writePort isWriteMask isAddr (RmeSimple_of_RME readMap)\n                             (fun x => CompLetFull_simple\n                                         (CompRet_simple (($$WO)%kami_expr)\n                                                         (@ReadRespRME idxNum num readResp readReg dataArray writePort\n                                                                       isWriteMask Data isAddr (RmeSimple_of_RME writeMap)\n                                                                       (RmeSimple_of_RME readMap)))\n                                         (fun _ y => CompActionSimple_of_CA (cont x y)))\n    | CompAsyncRead idxNum num readPort dataArray writePort isWriteMask idx pred k writeMap readMap lret cont =>\n      CompAsyncRead_simple idxNum readPort dataArray writePort isWriteMask idx pred (RmeSimple_of_RME readMap)\n                           (fun x =>\n                              CompLetFull_simple (CompRet_simple (($$ WO)%kami_expr : Void @# ty)\n                                                     (AsyncReadRME idxNum num readPort dataArray\n                                                                   writePort isWriteMask idx pred\n                                                                   k (RmeSimple_of_RME writeMap)\n                                                                   (RmeSimple_of_RME readMap)))\n                              (fun _ y => CompActionSimple_of_CA (cont x y)))\n    end.\n\n  Definition CAS_RulesRf(readMap : regMapTy) (rules : list RuleT) (lrf : list RegFileBase) :=\n    CompActionSimple_of_CA (compileRulesRf ty readMap rules lrf).\n\nEnd Simple.\n", "meta": {"author": "sifive", "repo": "Kami", "sha": "ffb77238f27b603dbd42d2622ba911740bf5eadf", "save_path": "github-repos/coq/sifive-Kami", "path": "github-repos/coq/sifive-Kami/Kami-ffb77238f27b603dbd42d2622ba911740bf5eadf/Compiler/CompilerSimple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.24797007252647155}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Crypto.Spec.Curve25519.\nRequire Import bedrock2.Map.Separation.\nRequire Import bedrock2.Syntax.\nRequire Import compiler.Pipeline.\nRequire Import compiler.Symbols.\nRequire Import compiler.MMIO.\nRequire Import coqutil.Word.Bitwidth32.\nRequire Import Crypto.Arithmetic.PrimeFieldTheorems.\nRequire Import Crypto.Bedrock.Field.Interface.Compilation2.\nRequire Import Crypto.Bedrock.Field.Synthesis.New.UnsaturatedSolinas.\nRequire Import Crypto.Bedrock.Group.AdditionChains.\nRequire Import Crypto.Bedrock.Group.ScalarMult.LadderStep.\nRequire Import Crypto.Bedrock.Group.ScalarMult.CSwap.\nRequire Import Crypto.Bedrock.Group.ScalarMult.MontgomeryLadder.\nRequire Import Crypto.Bedrock.End2End.X25519.Field25519.\nRequire Import Crypto.Bedrock.End2End.X25519.MontgomeryLadder.\nRequire Import bedrock2Examples.LAN9250.\nRequire Import bedrock2Examples.lightbulb.\nRequire Import bedrock2Examples.memequal.\nRequire Import bedrock2Examples.memswap.\nRequire Import bedrock2Examples.memconst.\nRequire Import Rupicola.Examples.Net.IPChecksum.IPChecksum.\n\n(******)\n\nRequire Crypto.Bedrock.End2End.RupicolaCrypto.ChaCha20.\n(*\nRequire bedrock2.BasicC32Semantics.\nGoal bedrock2.BasicC32Semantics.ext_spec = bedrock2.FE310CSemantics.ext_spec.\n  reflexivity.\n  cbn.\nRequire bedrock2.FE310CSemantics*)\n\n(******)\n\nLocal Open Scope string_scope.\nImport Syntax Syntax.Coercions NotationsCustomEntry.\nImport ListNotations.\nImport Coq.Init.Byte.\n\nDefinition garageowner : list byte :=\n  [x7b; x06; x18; x0c; x54; x0c; xca; x9f; xa3; x16; x0b; x2f; x2b; x69; x89; x63; x77; x4c; xc1; xef; xdc; x04; x91; x46; x76; x8b; xb2; xbf; x43; x0e; x34; x34].\n\nLocal Notation ST := 0x80000000.\nLocal Notation PK := 0x80000040.\nLocal Notation BUF:= 0x80000060.\n\nDefinition initfn := func! {\n  memconst_pk($PK);\n  output! MMIOWRITE($0x10012038, $(Z.lor (Z.shiftl (0xf) 2) (Z.shiftl 1 9)));\n  output! MMIOWRITE($0x10012008, $(Z.lor (Z.shiftl 1 11) (Z.shiftl 1 12)));\n  output! MMIOWRITE($0x10024010, $2);\n  unpack! err = lan9250_init()\n}.\n\nDefinition loopfn := func! {\n  st=$ST; pk=$PK; buf=$BUF;\n\n  unpack! pktlen, err = recvEthernet(buf);\n  require !err;\n  require ($63 < pktlen);\n\n  ethertype = load1(buf + $12) << $8 | load1(buf + $13);\n  require ($1535 < ethertype);\n  protocol = load1(buf+$23);\n  require (protocol == $0x11);\n\n  if $(14+20+8 +2+32 +4) == pktlen { (* getpk *)\n    memswap(buf, buf+$6, $6); (* ethernet address *)\n    memswap(buf+$(14+12), buf+$(14+16), $4); (* IP address *)\n    memswap(buf+$(14+20+0), buf+$(14+20+2), $2); (* UDP port *)\n    store1(buf+$(14+2), $0); (* ip length *)\n    store1(buf+$(14+3), $(20+ 8+ 32+2)); (* ip length *)\n    store1(buf+$(14+10), $0); (* preliminary ip checksum *)\n    store1(buf+$(14+11), $0); (* preliminary ip checksum *)\n\n    unpack! chk = ip_checksum(buf+$14, $20);\n    store1(buf+$(14+11), chk>>$8);\n    store1(buf+$(14+10), chk);\n\n    store1(buf+$(14+20+4), $0); (* udp length *)\n    store1(buf+$(14+20+5), $(8+ 32+2)); (* udp length *)\n    store1(buf+$(14+20+6), $0); (* udp checksum *)\n    store1(buf+$(14+20+7), $0); (* udp checksum *)\n\n    x25519_base(buf+$(14+20+8 +2), st+$32);\n    unpack! err = lan9250_tx(buf, $(14+20+8 +2+32))\n  } else if $(14+20+8 +2+16 +4) == pktlen { (* operate *)\n    stackalloc 32 as tmp;\n    x25519(tmp, st+$32, pk);\n    unpack! set0 = memequal(tmp, buf+$(14+20+8 +2), $16);\n    unpack! set1 = memequal(tmp+$16, buf+$(14+20+8 +2), $16);\n\n    io! mmio_val = MMIOREAD($0x1001200c);\n    mmio_val = mmio_val & coq:(Z.clearbit (Z.clearbit (2^32-1) 11) 12);\n    output! MMIOWRITE($0x1001200c, mmio_val | (set1<<$1 | set0) << $11);\n\n    if (set0|set1) { (* rekey *)\n        chacha20_block(st, st, (*nonce*)pk) (* NOTE: another impl? *)\n    }\n  }\n}.\n\nImport TracePredicate TracePredicateNotations SPI lightbulb_spec.\nNotation OP := (lightbulb_spec.OP _).\nDefinition iocfg : list OP -> Prop :=\n  one (\"st\", word.of_Z (0x10012038), word.of_Z (Z.lor (Z.shiftl (0xf) 2) (Z.shiftl 1 9))) +++\n  one (\"st\", word.of_Z (0x10012008), word.of_Z (Z.lor (Z.shiftl 1 11) (Z.shiftl 1 12))) +++\n  one (\"st\", word.of_Z (0x10024010), word.of_Z 2).\nDefinition BootSeq : list OP -> Prop :=\n  iocfg +++ (lan9250_init_trace _\n               ||| lan9250_boot_timeout _\n               ||| (any+++spi_timeout _)).\n\nImport WeakestPrecondition ProgramLogic SeparationLogic.\nLocal Notation \"m =* P\" := ((P%sep) m) (at level 70, only parsing) (* experiment*).\nLocal Notation \"xs $@ a\" := (Array.array ptsto (word.of_Z 1) a xs) (at level 10, format \"xs $@ a\").\nGlobal Instance spec_of_initfn : spec_of \"initfn\" :=\n  fnspec! \"initfn\" / bs R,\n  { requires t m := m =* bs $@(word.of_Z PK) * R /\\ length bs = 32%nat;\n    ensures t' m' := m' =* garageowner$@(word.of_Z PK) * R /\\\n      exists iol, t' = iol ++ t /\\\n      exists ioh, mmio_trace_abstraction_relation ioh iol /\\\n      BootSeq ioh }.\n\nLtac fwd :=\n  repeat match goal with\n         | |- _ /\\ _ => split\n         | |- exists _, _ => eexists\n         | _ => straightline\n         end; trivial.\nLtac slv := try solve [ trivial | ecancel_assumption | SepAutoArray.listZnWords | intuition idtac | reflexivity | eassumption].\n\nLocal Instance spec_of_memconst_pk : spec_of \"memconst_pk\" := spec_of_memconst \"memconst_pk\" garageowner.\nLocal Instance WHY_spec_of_lan9250_init : spec_of \"lan9250_init\" := spec_of_lan9250_init.\nLemma initfn_ok : program_logic_goal_for_function! initfn.\nProof.\n  repeat straightline.\n  straightline_call.\n  { ssplit. eassumption. rewrite H2. all : vm_compute; trivial. }\n  repeat straightline.\n  eapply WeakestPreconditionProperties.interact_nomem; repeat straightline.\n  eexists; fwd; slv.\n  { vm_compute. intuition congruence. }\n  eapply WeakestPreconditionProperties.interact_nomem; repeat straightline.\n  eexists; fwd; slv.\n  { vm_compute. intuition congruence. }\n  eapply WeakestPreconditionProperties.interact_nomem; repeat straightline.\n  eexists; fwd; slv.\n  { vm_compute. intuition congruence. }\n  straightline_call; repeat straightline; fwd.\n  { repeat (eapply align_trace_cons || exact (eq_sym (List.app_nil_l _)) || eapply align_trace_app). }\n  { repeat (eapply List.Forall2_cons || eapply List.Forall2_refl || eapply List.Forall2_app; eauto). all: cbv[mmio_event_abstraction_relation]; eauto. }\n  cbv [BootSeq ].\n  eapply TracePredicate.concat_app.\n  2: solve[cbv [choice]; intuition eauto].\n  cbv [iocfg].\n  eapply (TracePredicate.concat_app _ _ [_;_] [_]); [|cbv [one]; trivial].\n  eapply (TracePredicate.concat_app _ _ [_] [_]); cbv [one]; trivial.\nQed.\n\nLocal Open Scope list_scope.\nRequire Crypto.Bedrock.End2End.RupicolaCrypto.Spec.\nImport Tuple LittleEndianList.\nLocal Definition be2 z := rev (le_split 2 z).\nLocal Coercion to_list : tuple >-> list.\nLocal Coercion Z.b2z : bool >-> Z.\n\nDefinition state : Type := list byte * list byte. (* seed, xs25519 secret key *)\n\nDefinition garagedoor_iteration : state -> list (lightbulb_spec.OP _) -> state -> Prop :=\n  fun '(seed, sk) ioh '(SEED, SK) =>\n  (lightbulb_spec.lan9250_recv_no_packet _ ioh \\/\n    lightbulb_spec.lan9250_recv_packet_too_long _ ioh \\/\n    TracePredicate.concat TracePredicate.any (lightbulb_spec.spi_timeout _) ioh) \\/\n  (exists incoming, lightbulb_spec.lan9250_recv _ incoming ioh /\\\n  let ethertype := le_combine (rev (firstn 2 (skipn 12 incoming))) in ethertype < 1536 \\/\n  let ipproto := nth 23 incoming x00 in ipproto <> x11 \\/\n  (length incoming <> 14+20+8 +2+16 +4 /\\ length incoming <> 14+20+8 +2+32 +4)%nat) \\/\n  exists (mac_local mac_remote : tuple byte 6),\n  exists (ethertype : Z) (ih_const : tuple byte 2) (ip_length : Z) (ip_idff : tuple byte 5),\n  exists (ipproto := x11) (ip_checksum : Z) (ip_local ip_remote : tuple byte 4),\n  exists (udp_local udp_remote : tuple byte 2) (udp_length : Z) (udp_checksum : Z),\n  exists (garagedoor_header : tuple byte 2) (garagedoor_payload : list byte),\n  let incoming : list byte :=\n    (mac_local ++ mac_remote ++ be2 ethertype ++\n     ih_const ++ be2 ip_length ++\n     ip_idff ++ [ipproto] ++ le_split 2 ip_checksum ++\n     ip_remote ++ ip_local ++\n     udp_remote ++ udp_local ++\n     be2 udp_length ++ be2 udp_checksum ++\n     garagedoor_header ++ garagedoor_payload) in\n  (exists doorstate action : Naive.word32,\n  TracePredicate.concat\n      (lightbulb_spec.lan9250_recv _ incoming) (TracePredicate.concat\n      (TracePredicate.one (\"ld\", lightbulb_spec.GPIO_DATA_ADDR _, doorstate))\n      (TracePredicate.one (\"st\", lightbulb_spec.GPIO_DATA_ADDR _, action))) ioh\n   /\\ (\n    let m := firstn 16 garagedoor_payload in\n    let v := le_split 32 (F.to_Z (x25519_gallina (le_combine sk) (Field.feval_bytes(FieldRepresentation:=frep25519) garageowner))) in\n    exists set0 set1 : Naive.word32,\n    (word.unsigned set0 = 1 <-> firstn 16 v = m) /\\\n    (word.unsigned set1 = 1 <->  skipn 16 v = m) /\\\n    action = word.or (word.and doorstate (word.of_Z (Z.clearbit (Z.clearbit (2^32-1) 11) 12))) (word.slu (word.or (word.slu set1 (word.of_Z 1)) set0) (word.of_Z 11)) /\\\n    (* /\\ (word.unsigned set0 <> 0 \\/ word.unsigned set1 <> 0 -> SEED++SK = RupicolaCrypto.Spec.chacha20_encrypt k (Z.to_nat (word.unsigned counter)) _ _) *)\n    (word.unsigned set1 = 0 -> word.unsigned set0 = 0 -> SEED=seed /\\ SK=sk))) \\/\n  TracePredicate.concat (lightbulb_spec.lan9250_recv _ incoming)\n  (lightbulb_spec.lan9250_send _\n    (let ip_length := 62 in\n     let udp_length := 42 in\n     mac_remote ++ mac_local ++ be2 ethertype ++\n     let ih C := ih_const ++ be2 ip_length ++\n                 ip_idff ++ [ipproto] ++ le_split 2 C ++\n                 ip_local ++ ip_remote in\n     ih (Spec.ip_checksum (ih 0)) ++\n     udp_local ++ udp_remote ++\n     be2 udp_length ++ be2 0 ++\n     garagedoor_header ++\n     le_split 32 (F.to_Z (x25519_gallina (le_combine sk) (F.of_Z Field.M_pos 9)))))\n  ioh /\\ SEED=seed /\\ SK=sk.\n\nLocal Instance spec_of_recvEthernet : spec_of \"recvEthernet\" := spec_of_recvEthernet.\nLocal Instance spec_of_lan9250_tx : spec_of \"lan9250_tx\" := spec_of_lan9250_tx.\nLocal Instance spec_of_memswap : spec_of \"memswap\" := spec_of_memswap.\nLocal Instance spec_of_memequal : spec_of \"memequal\" := spec_of_memequal.\n\n\nDefinition memrep bs R : state -> map.rep(map:=SortedListWord.map _ _) -> Prop := fun '(seed, sk) m =>\n  m =*\n    seed$@(word.of_Z ST) *\n    sk$@(word.add (word.of_Z ST) (word.of_Z 32)) *\n    garageowner$@(word.of_Z PK) *\n    bs $@(word.of_Z BUF) * R /\\\n  length seed = 32%nat /\\\n  length sk = 32%nat /\\\n  length bs = 1520%nat.\n\nGlobal Instance spec_of_loopfn : spec_of \"loopfn\" :=\n  fnspec! \"loopfn\" / seed sk bs R,\n  { requires t m := memrep bs R (seed, sk) m;\n    ensures T M := exists SEED SK BS, memrep BS R (SEED, SK) M /\\\n    exists iol, T = iol ++ t /\\\n    exists ioh, SPI.mmio_trace_abstraction_relation ioh iol /\\\n    garagedoor_iteration (seed, sk) ioh (SEED, SK) }.\n\nImport ZnWords.\nImport coqutil.Tactics.autoforward.\n\nImport Crypto.Util.FixCoqMistakes.\n\nLocal Existing Instance ChaCha20.spec_of_chacha20.\n\nLemma loopfn_ok : program_logic_goal_for_function! loopfn.\nProof.\n  straightline.\n  cbv [memrep garagedoor_iteration] in *.\n  repeat straightline.\n  rename H11 into Lseed. rename H12 into Lsk. rename H13 into H11.\n  straightline_call; try ecancel_assumption; trivial; repeat straightline.\n  intuition idtac; repeat straightline;\n  eexists; split; repeat straightline; split; intros; try contradiction; [|]; repeat straightline.\n  2: fwd; slv.\n\n  pose proof H12 as Hbuf.\n  seprewrite_in @bytearray_index_merge Hbuf. { ZnWords. }\n\n  eexists; split; repeat straightline.\n  rewrite word.unsigned_ltu, ?word.unsigned_of_Z_nowrap by ZnWords.ZnWords;\n  destr Z.ltb; rewrite ?word.unsigned_of_Z_0, ?word.unsigned_of_Z_1; intuition try discriminate;\n  autoforward with typeclass_instances in E.\n  2: { fwd; slv. right. left. fwd; slv; intuition try ZnWords. }\n\n  repeat straightline.\n  eapply WeakestPreconditionProperties.dexpr_expr.\n  eexists; split; repeat straightline.\n\n  case (SepAutoArray.list_expose_nth x3 12 ltac:(ZnWords)) as (Hpp&Lpp).\n  forget (List.firstn 12 x3) as mac.\n  forget (nth 12 x3 Inhabited.default) as ethertype_hi.\n  forget (List.skipn 13 x3) as pp.\n  subst x3.\n  repeat seprewrite_in @Array.bytearray_append H12; cbn [Array.array] in H12.\n  rewrite ?app_length in *; cbn [length] in *; rewrite ?Lpp in *.\n  change (Z.of_nat 12) with 12 in *.\n\n  repeat straightline.\n\n  destruct pp as [|ethertype_lo pp]; cbn [length app Array.array] in *.\n  { exfalso; ZnWords. }\n  Import SetEvars coqutil.Tactics.eplace Word.Naive LittleEndianList.\n  eplace (word.add (word.add buf _) _) with (word.add buf _) in H12 by (ring_simplify; trivial).\n  repeat straightline.\n\n  let v := match goal with l := map.put _ \"ethertype\" ?v |- _ => v end in\n  remember v as ethertype in *;\n  assert (word.unsigned ethertype = le_combine [ethertype_lo; ethertype_hi]);\n   [ rewrite Heqethertype | ]; clear Heqethertype.\n  { pose proof byte.unsigned_range ethertype_hi.\n    pose proof byte.unsigned_range ethertype_lo.\n    subst_words.\n    cbn [le_combine]. rewrite ?Z.shiftl_0_l, ?Z.lor_0_r.\n    rewrite_strat (bottomup (terms word.unsigned_or_nowrap word.unsigned_and_nowrap word.unsigned_of_Z word.unsigned_slu)).\n    2: ZnWords.\n    cbv [word.wrap]; (rewrite_strat (bottomup (terms (Zmod_small)))); try ZnWords.ZnWords.\n    { rewrite Z.lor_comm; reflexivity. } }\n\n  eexists; split; repeat straightline.\n  rewrite word.unsigned_ltu, ?word.unsigned_of_Z_nowrap by ZnWords.ZnWords;\n  destr Z.ltb; rewrite ?word.unsigned_of_Z_0, ?word.unsigned_of_Z_1; intuition try discriminate;\n  autoforward with typeclass_instances in E0.\n  2: {\n    fwd; slv; [].\n    right. left. eexists. ssplit; try eassumption. left.\n    rewrite skipn_app, skipn_all2, ?Lpp, ?app_nil_l by ZnWords.\n    cbn [List.skipn minus firstn List.firstn List.app rev]. ZnWords. }\n\n  case (SepAutoArray.list_expose_nth pp 9 ltac:(ZnWords)) as (Hppp&Lppp).\n  forget (List.firstn 9 pp) as ih_l.\n  forget (nth 9 pp Inhabited.default) as ipproto.\n  forget (List.skipn 10 pp) as ppp.\n  subst pp.\n  repeat seprewrite_in @Array.bytearray_append H12; cbn [Array.array] in H12.\n  rewrite ?app_length in *; cbn [length] in *; rewrite ?Lppp in *.\n  change (Z.of_nat 9) with 9 in *.\n  change (Z.of_nat 1) with 1 in *.\n\n  repeat eplace (word.add (word.add buf _) _) with (word.add buf _) in H12 by (ring_simplify; trivial).\n\n  repeat straightline.\n  eexists; split; repeat straightline.\n  subst protocol.\n  pose proof byte.unsigned_range ipproto.\n  rewrite word.unsigned_eqb, ?word.unsigned_and_nowrap, ?word.unsigned_of_Z_nowrap by ZnWords.ZnWords.\n  destr Z.eqb; rewrite ?word.unsigned_of_Z_0, ?word.unsigned_of_Z_1; intuition try discriminate; autoforward with typeclass_instances in E1.\n  2: {\n    fwd; slv; [].\n    right. left. eexists. ssplit; try eassumption. right. left.\n    rewrite app_nth2 by ZnWords.\n    rewrite app_comm_cons.\n    rewrite app_nth2 by SepAutoArray.listZnWords.\n    rewrite app_nth2 by SepAutoArray.listZnWords.\n    rewrite app_nth1 by SepAutoArray.listZnWords.\n    match goal with |- context[nth ?x] => replace x with O by SepAutoArray.listZnWords end.\n    cbn. intro. subst. apply E1. reflexivity. }\n\n  repeat straightline.\n  eexists; split; repeat straightline.\n  rewrite word.unsigned_eqb, ?word.unsigned_of_Z_nowrap by ZnWords.ZnWords.\n  destr Z.eqb; rewrite ?word.unsigned_of_Z_0, ?word.unsigned_of_Z_1; intuition try discriminate; autoforward with typeclass_instances in E2.\n\n  2: {\n    repeat straightline.\n    eexists; split; repeat straightline.\n    rewrite word.unsigned_eqb, ?word.unsigned_of_Z_nowrap by ZnWords.ZnWords.\n    destr Z.eqb; rewrite ?word.unsigned_of_Z_0, ?word.unsigned_of_Z_1; intuition try discriminate; autoforward with typeclass_instances in E3.\n    2: {\n      fwd; slv.\n      right. left. eexists. ssplit; try eassumption. right. right. SepAutoArray.listZnWords. }\n    repeat straightline.\n    straightline_call; ssplit; try ecancel_assumption; try trivial; try ZnWords.\n    { cbv. inversion 1. }\n\n    rename Lppp into Lihl; assert (List.length ppp = 40)%nat as Lppp by ZnWords.\n\n    repeat straightline.\n    pose proof (List.firstn_skipn (14+20+8 +2 - 12-2-9-1) ppp) as HH.\n    pose proof (@firstn_length_le _ ppp (14+20+8 +2 - 12-2-9-1) ltac:(ZnWords)).\n    pose proof skipn_length (14+20+8 +2 - 12-2-9-1) ppp; rewrite Lppp in *.\n    forget (List.firstn (14+20+8 +2 - 12-2-9-1) ppp) as pPP.\n    forget (List.skipn (14+20+8 +2 - 12-2-9-1) ppp) as pPPP.\n    simpl minus in H31, H32.\n    subst ppp.\n    repeat rewrite ?(app_assoc _ _ pPPP), ?app_comm_cons in H33.\n    do 3 (seprewrite_in @Array.bytearray_append H33; cbn [Array.array] in H33).\n\n    change (unsigned x) with (@word.unsigned _ word32 x) in H32.\n    repeat straightline.\n    pose proof (List.firstn_skipn 16 pPPP) as HH.\n    pose proof (@firstn_length_le _ pPPP 16 ltac:(ZnWords)).\n    pose proof skipn_length 16 pPPP. rewrite H32 in *.\n    forget (List.firstn 16 pPPP) as cmp1.\n    forget (List.skipn 16 pPPP) as trailer.\n    subst pPPP.\n    seprewrite_in_by (Array.bytearray_append cmp1) H33 SepAutoArray.listZnWords.\n\n    remember (le_split 32 (F.to_Z (x25519_gallina (le_combine sk) (Field.feval_bytes _)))) as vv.\n    repeat straightline.\n    pose proof (List.firstn_skipn 16 vv) as Hvv.\n    pose proof (@firstn_length_le _ vv 16 ltac:(subst vv; rewrite ?length_le_split; ZnWords)).\n    pose proof skipn_length 16 vv.\n    forget (List.firstn 16 vv) as vv0.\n    forget (List.skipn 16 vv) as vv1.\n    subst vv.\n    rewrite <-Hvv in H33.\n    rewrite length_le_split in *.\n    seprewrite_in_by (Array.bytearray_append vv0) H33 SepAutoArray.listZnWords.\n\n    repeat straightline.\n    straightline_call; ssplit.\n    { ecancel_assumption. }\n    { use_sep_assumption. cancel. cancel_seps_at_indices 2%nat 0%nat.\n      { Morphisms.f_equiv. SepAutoArray.listZnWords. }\n      ecancel_done. }\n    { ZnWords. }\n    { ZnWords. }\n    repeat straightline.\n\n    repeat straightline.\n    straightline_call; ssplit.\n    { use_sep_assumption. cancel. cancel_seps_at_indices 1%nat 0%nat.\n      { Morphisms.f_equiv. SepAutoArray.listZnWords. }\n      ecancel_done. }\n    { use_sep_assumption. cancel. cancel_seps_at_indices 2%nat 0%nat.\n      { Morphisms.f_equiv. SepAutoArray.listZnWords. }\n      ecancel_done. }\n    { ZnWords. }\n    { ZnWords. }\n\n    repeat straightline.\n    eexists. split. repeat straightline.\n    eexists _, _; split; [eapply map.split_empty_r; reflexivity|].\n    eexists; ssplit; trivial.\n    { cbv. clear. intuition congruence. }\n\n    repeat straightline.\n    eexists. split. repeat straightline.\n    eexists _, _; split; [eapply map.split_empty_r; reflexivity|].\n    eexists; ssplit; trivial.\n    eexists; ssplit; trivial.\n    { cbv. clear. intuition congruence. }\n    repeat straightline.\n\n    eapply map.split_empty_r in H38; destruct H38.\n    eapply map.split_empty_r in H39; destruct H39.\n    seprewrite_in_by @bytearray_index_merge H33 SepAutoArray.listZnWords.\n    seprewrite_in_by @bytearray_index_merge H33 SepAutoArray.listZnWords.\n    seprewrite_in_by @bytearray_index_merge H33 SepAutoArray.listZnWords.\n    seprewrite_in_by @bytearray_index_merge H33 SepAutoArray.listZnWords.\n    seprewrite_in_by @bytearray_index_merge H33 SepAutoArray.listZnWords.\n    assert (length (vv0 ++ vv1) = 32%nat) by SepAutoArray.listZnWords.\n\n\n    change (word.of_Z 134217728) with st in H33.\n    repeat straightline.\n    eexists; ssplit; repeat straightline.\n    { (* chacha20 *)\n      (* NOTE: viewing the same memory in two different ways, ++ combined and split *)\n      straightline_call; ssplit.\n      { seprewrite_in_by @bytearray_index_merge H33 SepAutoArray.listZnWords.\n        ecancel_assumption. }\n      { SepAutoArray.listZnWords. }\n      { ecancel_assumption. }\n      { SepAutoArray.listZnWords. }\n      { rewrite <-(List.firstn_skipn 12 garageowner) in H33.\n        seprewrite_in_by (Array.bytearray_append (List.firstn 12 garageowner)) H33 SepAutoArray.listZnWords.\n        ecancel_assumption. }\n      { SepAutoArray.listZnWords. }\n      repeat straightline.\n\n      rewrite <-(List.firstn_skipn 32 x6) in H46.\n      seprewrite_in_by (Array.bytearray_append (List.firstn 32 x6)) H46 SepAutoArray.listZnWords.\n      replace (word.of_Z (BinInt.Z.of_nat (Datatypes.length (List.firstn 32 x6)))) with (word.of_Z 32 : word32) in * by SepAutoArray.listZnWords.\n\n      ssplit; trivial.\n      eexists _, _, _; ssplit; try ecancel_assumption; try SepAutoArray.listZnWords.\n\n    eexists; ssplit.\n    { subst a0 a. change (?x::?y::?t) with ([x;y]++t). rewrite app_assoc. trivial. }\n    eexists; ssplit.\n    { eapply Forall2_app; try eassumption.\n      eapply Forall2_cons. 2:eapply Forall2_cons. 3:eapply Forall2_nil.\n      all:[>left|right]; eexists _, _; ssplit; trivial. }\n    right.\n    right.\n    eexists _, _, _, _, _, _, _, _, _, _, _, _, _, _, _. left; ssplit; trivial.\n    eexists _, _.\n    split.\n    {\n    eapply TracePredicate.concat_app.\n    1: match goal with |- _ ?x _ => eplace x with _ end; [|eassumption].\n\n    symmetry. (* NOTE: systematic list cancellation *)\n    rewrite <-(firstn_skipn 6 mac) at 1; rewrite <-?app_assoc.\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    change ([?x]++?y::?z) with ([x;y]++z).\n    eapply (f_equal2 app).\n    { cbv [be2]. progress change 2%nat with (List.length [ethertype_lo; ethertype_hi]).\n      setoid_rewrite split_le_combine; trivial. }\n    rewrite <-(firstn_skipn 2 ih_l) at 1; rewrite <-?app_assoc.\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    rewrite <-(firstn_skipn 2 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app).\n    { cbv [be2]. eplace 2%nat with _ at 3; cycle 1.\n      rewrite split_le_combine, rev_involutive; trivial.\n      rewrite rev_length. SepAutoArray.listZnWords. }\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    eapply (f_equal2 app). { f_equal. eapply byte.unsigned_inj. rewrite E1. trivial. }\n    rewrite <-(firstn_skipn 2 pPP) at 1; rewrite <-?app_assoc.\n    eapply (f_equal2 app).\n    { eplace 2%nat with _ at 2; cycle 1.\n      rewrite split_le_combine; trivial.\n      SepAutoArray.listZnWords. }\n    rewrite <-(firstn_skipn 4 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    rewrite <-(firstn_skipn 4 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    rewrite <-(firstn_skipn 2 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    rewrite <-(firstn_skipn 2 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    rewrite <-(firstn_skipn 2 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app).\n    { cbv [be2]. eplace 2%nat with _ at 7; cycle 1.\n      rewrite split_le_combine, rev_involutive; trivial.\n      rewrite rev_length. SepAutoArray.listZnWords. }\n    rewrite <-(firstn_skipn 2 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app).\n    { cbv [be2]. eplace 2%nat with _ at 8; cycle 1.\n      rewrite split_le_combine, rev_involutive; trivial.\n      rewrite rev_length. SepAutoArray.listZnWords. }\n    eapply (f_equal2 app). { rewrite to_list_from_list; trivial. }\n    reflexivity.\n\n    change [?x;?y] with ([x]++[y]).\n    eapply TracePredicate.concat_app; cbv [TracePredicate.one]; f_equal. }\n\n    rewrite <-Hvv.\n    rewrite !ListUtil.firstn_app_sharp by ZnWords.\n    rewrite !ListUtil.skipn_app_sharp by ZnWords.\n    eexists _, _; ssplit; try eassumption; subst mmio_val; eauto.\n\n    intros; exfalso. apply H39.\n    rewrite word.unsigned_or_nowrap. apply Z.lor_eq_0_iff; auto.\n    (* end chacha20*) }\n\nOptimize Proof. Optimize Heap.\n\n    ssplit; trivial.\n    eexists _, _, _; ssplit; try ecancel_assumption; try SepAutoArray.listZnWords.\n    eexists; ssplit.\n    { subst a. change (?x::?y::?t) with ([x;y]++t). rewrite app_assoc. trivial. }\n    eexists; ssplit.\n    { eapply Forall2_app; try eassumption.\n      eapply Forall2_cons. 2:eapply Forall2_cons. 3:eapply Forall2_nil.\n      all:[>left|right]; eexists _, _; ssplit; trivial. }\n    right.\n    right.\n    eexists _, _, _, _, _, _, _, _, _, _, _, _, _, _, _. left; ssplit; trivial.\n    eexists _, _.\n    split.\n    {\n    eapply TracePredicate.concat_app.\n    1: match goal with |- _ ?x _ => eplace x with _ end; [|eassumption].\n\n    symmetry. (* NOTE: systematic list cancellation *)\n    rewrite <-(firstn_skipn 6 mac) at 1; rewrite <-?app_assoc.\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    change ([?x]++?y::?z) with ([x;y]++z).\n    eapply (f_equal2 app).\n    { cbv [be2]. progress change 2%nat with (List.length [ethertype_lo; ethertype_hi]).\n      setoid_rewrite split_le_combine; trivial. }\n    rewrite <-(firstn_skipn 2 ih_l) at 1; rewrite <-?app_assoc.\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    rewrite <-(firstn_skipn 2 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app).\n    { cbv [be2]. eplace 2%nat with _ at 3; cycle 1.\n      rewrite split_le_combine, rev_involutive; trivial.\n      rewrite rev_length. SepAutoArray.listZnWords. }\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    eapply (f_equal2 app). { f_equal. eapply byte.unsigned_inj. rewrite E1. trivial. }\n    rewrite <-(firstn_skipn 2 pPP) at 1; rewrite <-?app_assoc.\n    eapply (f_equal2 app).\n    { eplace 2%nat with _ at 2; cycle 1.\n      rewrite split_le_combine; trivial.\n      SepAutoArray.listZnWords. }\n    rewrite <-(firstn_skipn 4 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    rewrite <-(firstn_skipn 4 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    rewrite <-(firstn_skipn 2 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    rewrite <-(firstn_skipn 2 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app); [rewrite to_list_from_list; trivial|].\n    rewrite <-(firstn_skipn 2 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app).\n    { cbv [be2]. eplace 2%nat with _ at 7; cycle 1.\n      rewrite split_le_combine, rev_involutive; trivial.\n      rewrite rev_length. SepAutoArray.listZnWords. }\n    rewrite <-(firstn_skipn 2 (List.skipn _ _)) at 1; rewrite <-?app_assoc, ?List.skipn_skipn.\n    eapply (f_equal2 app).\n    { cbv [be2]. eplace 2%nat with _ at 8; cycle 1.\n      rewrite split_le_combine, rev_involutive; trivial.\n      rewrite rev_length. SepAutoArray.listZnWords. }\n    eapply (f_equal2 app). { rewrite to_list_from_list; trivial. }\n    reflexivity.\n\n    change [?x;?y] with ([x]++[y]).\n    eapply TracePredicate.concat_app; cbv [TracePredicate.one]; f_equal. }\n\n    rewrite <-Hvv.\n    rewrite !ListUtil.firstn_app_sharp by ZnWords.\n    rewrite !ListUtil.skipn_app_sharp by ZnWords.\n    eexists _, _; ssplit; try eassumption; subst mmio_val; eauto.\n  }\n\n  {\n    repeat straightline.\n    pose proof (List.firstn_skipn 6 mac) as HH.\n    pose proof (@firstn_length_le _ mac 6 ltac:(ZnWords)).\n    pose proof skipn_length 6 mac; rewrite ?Lpp in *.\n    forget (List.firstn 6 mac) as mac_local.\n    forget (List.skipn 6 mac) as mac_remote.\n    subst mac.\n    repeat seprewrite_in @Array.bytearray_append H12; cbn [Array.array] in H12.\n    rewrite H26 in *.\n    change (Z.of_nat 6) with 6 in *.\n\n    straightline_call; ssplit; try ecancel_assumption; try ZnWords.\n\n    repeat straightline.\n\n    pose proof (List.firstn_skipn 2 ppp) as HH.\n    pose proof (@firstn_length_le _ ppp 2 ltac:(ZnWords)).\n    pose proof skipn_length 2 ppp as Lip_checksum.\n    forget (List.firstn 2 ppp) as ip_checksum.\n    forget (List.skipn 2 ppp) as pppp.\n    subst ppp; rewrite ?app_length in *.\n    repeat seprewrite_in @Array.bytearray_append H29; cbn [Array.array] in H29.\n    rewrite ?H28 in *.\n    change (Z.of_nat 24) with 24 in *.\n    change (Z.of_nat 2) with 2 in *.\n    eplace (word.add (word.add buf _) _) with (word.add buf _) in H29 by (ring_simplify; trivial).\n\n    pose proof (List.firstn_skipn 4 pppp) as HH.\n    pose proof (@firstn_length_le _ pppp 4 ltac:(ZnWords)).\n    forget (List.firstn 4 pppp) as ip_remote.\n    forget (List.skipn 4 pppp) as ppppp.\n    subst pppp; rewrite ?app_length in *.\n    repeat seprewrite_in @Array.bytearray_append H29; cbn [Array.array] in H29.\n    rewrite ?H30 in *.\n    change (Z.of_nat 28) with 28 in *.\n    change (Z.of_nat 4) with 4 in *.\n    eplace (word.add (word.add buf _) _) with (word.add buf _) in H29 by (ring_simplify; trivial).\n\n    pose proof (List.firstn_skipn 4 ppppp) as HH.\n    pose proof (@firstn_length_le _ ppppp 4 ltac:(ZnWords)).\n    forget (List.firstn 4 ppppp) as ip_local.\n    forget(List.skipn 4 ppppp) as pppppp.\n    subst ppppp; rewrite ?app_length in *.\n    repeat seprewrite_in @Array.bytearray_append H29; cbn [Array.array] in H29.\n    rewrite ?H31 in *.\n    change (Z.of_nat 30) with 30 in *.\n    change (Z.of_nat 4) with 4 in *.\n    eplace (word.add (word.add buf _) _) with (word.add buf _) in H29 by (ring_simplify; trivial).\n\n    straightline_call; ssplit; try ecancel_assumption; try ZnWords.\n\n    repeat straightline.\n\n    pose proof (List.firstn_skipn 2 pppppp) as HH.\n    pose proof (@firstn_length_le _ pppppp 2 ltac:(ZnWords)).\n    forget (List.firstn 2 pppppp) as udp_remote.\n    forget(List.skipn 2 pppppp) as pP.\n    subst pppppp; rewrite ?app_length in *.\n    repeat seprewrite_in @Array.bytearray_append H33; cbn [Array.array] in H33.\n    rewrite ?H32 in *.\n    change (Z.of_nat 34) with 34 in *.\n    change (Z.of_nat 4) with 4 in *.\n    eplace (word.add (word.add buf _) _) with (word.add buf _) in H33 by (ring_simplify; trivial).\n\n    pose proof (List.firstn_skipn 2 pP) as HH.\n    pose proof (@firstn_length_le _ pP 2 ltac:(ZnWords)).\n    forget (List.firstn 2 pP) as udp_local.\n    forget(List.skipn 2 pP) as pPP.\n    subst pP; rewrite ?app_length in *.\n    repeat seprewrite_in @Array.bytearray_append H33; cbn [Array.array] in H33.\n    rewrite ?H34 in *.\n    change (Z.of_nat 36) with 36 in *.\n    change (Z.of_nat 4) with 4 in *.\n    eplace (word.add (word.add buf _) _) with (word.add buf _) in H33 by (ring_simplify; trivial).\n\n    straightline_call; ssplit; try ecancel_assumption; try ZnWords.\n\n    repeat straightline.\n\n    case (SepAutoArray.list_expose_nth ih_l 2 ltac:(ZnWords)) as (HH&LL).\n    forget (List.firstn 2 ih_l) as ih_const.\n    forget (nth 2 ih_l Inhabited.default) as ip_length_hi.\n    forget (List.skipn 3 ih_l) as ip_length_lo.\n    subst ih_l.\n    repeat seprewrite_in @Array.bytearray_append H36; cbn [Array.array] in H36.\n    rewrite ?app_length in *; cbn [length] in *; rewrite ?LL in *.\n    change (Z.of_nat 1) with 1 in *.\n    change (Z.of_nat 2) with 2 in *.\n    eplace (word.add (word.add buf _) _) with (word.add buf _) in H36 by (ring_simplify; trivial).\n    eplace (word.add (word.add buf _) _) with (word.add buf _) in H36 by (ring_simplify; trivial).\n\n    repeat straightline.\n\n    destruct ip_length_lo as [|ip_length_lo ip_idff ].\n    { cbn [length] in *. exfalso; Lia.lia. }\n    cbn [Array.array] in *.\n    eplace (word.add (word.add buf _) _) with (word.add buf _) in H35 by (ring_simplify; trivial).\n\n    repeat straightline.\n    destruct ip_checksum as [|ip_checksum_0 [|ip_checksum_1 [|] ] ];\n        try (cbn [length] in *; discriminate); cbn [Array.array] in *.\n    eplace (word.add (word.add buf _) _) with (word.add buf _) in H37 by (ring_simplify; trivial).\n\n    straightline.\n    straightline.\n    straightline.\n    straightline.\n    straightline.\n    straightline.\n    straightline.\n    repeat straightline.\n    assert (ptsto_to_array :\n      forall {width : Z} {word : Interface.word width},\n      word.ok word ->\n      forall mem : map.map (word.rep(word:=word)) Byte.byte,\n      map.ok mem -> forall a b,\n      Lift1Prop.iff1 (ptsto a b) (Array.array(mem:=mem) ptsto (word.of_Z 1) a [b])).\n    { cbn [Array.array]. intros. cancel. }\n\n    assert (bytearray_address_merge :\n  forall {width : Z} {word : Interface.word width},\n  word.ok word ->\n  forall mem : map.map (word.rep(word:=word)) Byte.byte,\n  map.ok mem ->\n  forall (xs ys : list byte) (start b : word.rep),\n  word.unsigned (word.sub b start) = Z.of_nat (Datatypes.length xs) ->\n  Lift1Prop.iff1 (xs$@start ⋆ ys$@b) ((xs ++ ys)$@start : mem -> Prop)).\n  { intros.\n    replace b with (word.add start (word.sub b start)).\n    { eapply Array.bytearray_index_merge; trivial. }\n    eapply word.unsigned_inj. rewrite ?word.unsigned_add, ?word.unsigned_sub.\n    cbv [word.wrap].\n    rewrite Zplus_mod_idemp_r.\n    transitivity (word.unsigned b mod 2^width).\n    { f_equal.  ring. }\n    rewrite Z.mod_small; trivial; eapply word.unsigned_range. }\n\nOptimize Proof. Optimize Heap.\n\n  repeat seprewrite_in @ptsto_to_array H39.\n  rewrite ?word.unsigned_of_Z_nowrap in H39 by ZnWords.\n  seprewrite_in_by (@bytearray_address_merge _ _ _ _ _ ih_const) H39 ZnWords.\n  seprewrite_in_by (fun x=>@bytearray_address_merge _ _ _ _ _ (ih_const++x)%list) H39 SepAutoArray.listZnWords.\n  rewrite <-app_assoc in H39.\n  seprewrite_in_by (fun x=>@bytearray_address_merge _ _ _ _ _ (ih_const++x)%list) H39 SepAutoArray.listZnWords.\n  rewrite <-!app_assoc in H39.\n  cbn [length] in *.\n  seprewrite_in_by (fun x=>@bytearray_address_merge _ _ _ _ _ (ih_const++x)%list) H39 SepAutoArray.listZnWords.\n  rewrite <-!app_assoc in H39.\n  seprewrite_in_by (fun x=>@bytearray_address_merge _ _ _ _ _ (ih_const++x)%list) H39 SepAutoArray.listZnWords.\n  rewrite <-!app_assoc in H39.\n  seprewrite_in_by (fun x=>@bytearray_address_merge _ _ _ _ _ (ih_const++x)%list) H39 SepAutoArray.listZnWords.\n  rewrite <-!app_assoc in H39.\n  seprewrite_in_by (fun x=>@bytearray_address_merge _ _ _ _ _ (ih_const++x)%list) H39 SepAutoArray.listZnWords.\n  rewrite <-!app_assoc in H39.\n  seprewrite_in_by (fun x=>@bytearray_address_merge _ _ _ _ _ (ih_const++x)%list) H39 SepAutoArray.listZnWords.\n\n  straightline_call; [(ssplit; cycle -1)|];\n    cbv [Arrays.listarray_value Arrays.ai_repr Arrays._access_info Arrays.ai_width Arrays.ai_size Arrays.ai_type Memory.bytes_per] in *;\n    change (Z.of_nat 1) with 1%Z in *;\n    try ecancel_assumption;\n    try SepAutoArray.listZnWords.\n\nOptimize Proof. Optimize Heap.\n\n  repeat straightline.\n\n  repeat match goal with x := word.of_Z 0 |- _ => subst x end.\n  repeat match goal with x := word.of_Z 62 |- _ => subst x end.\n  rewrite !word.unsigned_of_Z_nowrap in H43 by Lia.lia.\n  progress replace  ((ih_const ++ [byte.of_Z 0] ++ [byte.of_Z 62] ++ ip_idff ++ [ipproto] ++ [byte.of_Z 0] ++ [byte.of_Z 0] ++ ip_local) ++ ip_remote)%list\n    with ((ih_const ++ [byte.of_Z 0] ++ [byte.of_Z 62] ++ ip_idff ++ [ipproto]) ++ [byte.of_Z 0] ++ [byte.of_Z 0] ++ ip_local ++ ip_remote)%list\n    in * by (rewrite ?app_assoc; trivial).\n  seprewrite_in @Array.bytearray_append H43.\n  seprewrite_in (@Array.bytearray_append _ _ _ _ _ [byte.of_Z 0]) H43.\n  seprewrite_in (@Array.bytearray_append _ _ _ _ _ [byte.of_Z 0]) H43.\n  rewrite ?app_length in H43; cbn [length] in H43; rewrite ?LL in H43.\n  replace (Datatypes.length ip_idff) with 5%nat in H43 by ZnWords.\n  cbn [plus] in H43.\n  repeat eplace (word.add (word.add buf _) _) with (word.add buf _) in H43 by (ring_simplify; trivial).\n\n  Import symmetry.\n  seprewrite_in (symmetry! (fun a=>@ptsto_to_array _ _ _ _ _ a (byte.of_Z 0))) H43.\n  seprewrite_in (symmetry! (fun a=>@ptsto_to_array _ _ _ _ _ a (byte.of_Z 0))) H43.\n\n  repeat straightline.\n  match goal with H : ?P ?m |- store _ ?m _ _ _ => revert H end.\n  repeat match goal with H : sep _ _ _ |- _ => clear H end.\n  repeat straightline.\n\n  do 6 (destruct pPP as [|? pPP]; (cbn [Datatypes.length] in *; try Lia.lia)).\n  set ((b :: b0 :: b1 :: b2 :: b3 :: b4 :: pPP)$@(word.add buf (word.of_Z 38))) as X in H40.\n  cbn [Array.array] in X. subst X.\n  repeat eplace (word.add (word.add buf _) _) with (word.add buf _) in H40 by (ring_simplify; trivial).\n\n  repeat straightline.\n  pose proof (List.firstn_skipn 32 pPP) as HH.\n  pose proof (@firstn_length_le _ pPP 32 ltac:(ZnWords)).\n  forget (List.firstn 32 pPP) as _pkpad.\n  forget(List.skipn 32 pPP) as pPPP.\n  subst pPP; rewrite ?app_length in *.\n  repeat seprewrite_in (@Array.bytearray_append _ _ _ _ _ _pkpad) H29.\n  rewrite ?H33 in *.\n  change (Z.of_nat 32) with 32 in *.\n  repeat eplace (word.add (word.add buf _) _) with (word.add buf _) in H29 by (ring_simplify; trivial).\n  straightline_call; ssplit; try ecancel_assumption; trivial.\n\nOptimize Proof. Optimize Heap.\n\n  repeat straightline.\n\n  revert H37.\n  repeat match goal with H : sep _ _ _ |- _ => clear H end.\n  intros.\n  repeat seprewrite_in @ptsto_to_array H37.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 ZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\nOptimize Proof. Optimize Heap.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\nOptimize Proof. Optimize Heap.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\nOptimize Proof. Optimize Heap.\n\n  rename x3 into ipchk.\n  match goal with x := word.sru ipchk _ |- _ => subst x end.\n  progress rewrite ?word.unsigned_sru_nowrap, ?word.unsigned_of_Z_nowrap in H37 by ZnWords.\n\n  straightline_call; [ssplit; cycle -1|]; try ecancel_assumption.\n  { rewrite ?app_length, ?length_le_split. SepAutoArray.listZnWords. }\n  { ZnWords. }\n\n  pose proof length_le_split 32 (F.to_Z (x25519_gallina (le_combine sk) (F.of_Z Field.M_pos 9))) as Hpkl.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n  seprewrite_in_by (fun xs ys=>@bytearray_address_merge _ _ _ _ _ xs ys buf) H37 SepAutoArray.listZnWords.\n\n  repeat straightline.\n  destruct H35; repeat straightline; [intuition idtac | ].\n  { eexists; ssplit. eexists _, _; ssplit; slv.\n    eexists; ssplit. subst a4. subst a. rewrite app_assoc. reflexivity.\n    eexists; ssplit. eapply Forall2_app; eassumption.\n    eauto using TracePredicate.any_app_more. }\n\n  ssplit; trivial.\n  eexists _, _, _; ssplit; slv.\n  eexists; ssplit. subst a4. subst a. rewrite app_assoc. reflexivity.\n  eexists; ssplit. eapply Forall2_app; eassumption.\n  right. right.\n\n  exists (from_list 6 mac_local ltac:(assumption)); rewrite to_list_from_list.\n  exists (from_list 6 mac_remote ltac:(assumption)); rewrite to_list_from_list.\n  cbv beta delta [be2].\n  exists (le_combine [ethertype_lo; ethertype_hi]); rewrite split_le_combine' by trivial.\n  exists (from_list 2 ih_const ltac:(assumption)); rewrite to_list_from_list.\n  exists (le_combine [ip_length_lo; ip_length_hi]); rewrite split_le_combine' by trivial.\n  exists (from_list 5 ip_idff ltac:(ZnWords)); rewrite to_list_from_list.\n  exists (le_combine [ip_checksum_0; ip_checksum_1]); rewrite split_le_combine' by trivial.\n  exists (from_list 4 ip_local ltac:(assumption)); rewrite to_list_from_list.\n  exists (from_list 4 ip_remote ltac:(assumption)); rewrite to_list_from_list.\n  exists (from_list 2 udp_local ltac:(assumption)); rewrite to_list_from_list.\n  exists (from_list 2 udp_remote ltac:(assumption)); rewrite to_list_from_list.\n  exists (le_combine [b0; b]); rewrite split_le_combine' by trivial.\n  exists (le_combine [b2; b1]); rewrite split_le_combine' by trivial.\n  exists (from_list 2 [b3;b4] eq_refl); rewrite to_list_from_list.\n  exists (_pkpad ++ pPPP).\n\n  assert (x11 = ipproto) as Hp. { eapply byte.unsigned_inj. rewrite E1. trivial. }\n  destruct Hp.\n\n  right.\n  ssplit; trivial.\n  eapply TracePredicate.concat_app.\n  all : match goal with |- _ ?x _ => eplace x with _; try eassumption; [] end.\n  assert (app_singleton_l : forall {A} (x:A) xs, [x] ++ xs = x :: xs) by (intros; reflexivity).\n  2 : simpl le_split at 1.\n  all : cbn [rev].\n  all : repeat (rewrite <-?app_assoc, ?app_nil_l, ?app_singleton_l, <-?app_comm_cons).\n  all : trivial; repeat (f_equal; []).\n\n  match goal with c := Impl.ip_checksum_impl ?y |- context[Spec.ip_checksum ?x] =>\n    progress rewrite <-(Impl.ip_checksum_impl_ok' y : _ = word.unsigned c) in *;\n    progress replace x with y in * end.\n  2: {\n    repeat (rewrite <-?app_assoc, ?app_nil_l, ?app_singleton_l, <-?app_comm_cons).\n    trivial. }\n  remember (Spec.ip_checksum _) as chk.\n  unfold le_split at 1.\n  repeat (rewrite <-?app_assoc, ?app_nil_l, ?app_singleton_l, <-?app_comm_cons).\n  trivial. }\n\n  Unshelve.\n  all : try SepAutoArray.listZnWords.\nQed.\n\nRequire Import Crypto.Bedrock.End2End.X25519.MontgomeryLadderProperties.\nImport bedrock2.Syntax.\nImport coqutil.Macros.WithBaseName.\n\n(* these wrappers exist because CompilerInvariant requires execution proofs with arbitrary locals in the starting state, which ProgramLogic does not support *)\nDefinition init := func! { initfn() } .\nDefinition loop := func! { loopfn() } .\nDefinition memconst_pk := memconst garageowner.\nDefinition ip_checksum := ip_checksum_br2fn.\n\nDefinition funcs :=\n  &[, init; loop;\n    initfn; loopfn;\n    memswap; memequal; memconst_pk;\n    ip_checksum;\n    ChaCha20.chacha20_block; ChaCha20.quarter;\n    lan9250_tx ]\n    ++lightbulb.function_impls\n    ++MontgomeryLadder.funcs.\n\n\nLemma chacha20_ok: forall functions, ChaCha20.spec_of_chacha20 (&,ChaCha20.chacha20_block::&,ChaCha20.quarter::functions).\n  intros.\n  simple eapply ChaCha20.chacha20_block_body_correct.\n  constructor.\n  eapply ChaCha20.quarter_body_correct.\n  constructor.\nQed.\n\nImport SPI.\nLemma link_loopfn : spec_of_loopfn funcs.\nProof.\n  eapply loopfn_ok; try eapply memswap.memswap_ok; try eapply memequal_ok.\n    repeat (eapply recvEthernet_ok || eapply lightbulb_handle_ok);\n        eapply lan9250_readword_ok; eapply spi_xchg_ok;\n        (eapply spi_write_ok || eapply spi_read_ok).\n    eapply ip_checksum_br2fn_ok; exact I.\n    eapply x25519_base_ok; try eapply fe25519_from_word_correct; try eapply link_montladder; try eapply fe25519_to_bytes_correct.\n    eapply lan9250_tx_ok; try eapply lan9250_writeword_ok; try eapply spi_xchg_ok; (eapply spi_write_ok || eapply spi_read_ok).\n    eapply x25519_ok; try eapply fe25519_from_bytes_correct; try eapply link_montladder; try eapply fe25519_to_bytes_correct.\n    eapply chacha20_ok.\nQed. Optimize Heap.\n\nRequire compiler.ToplevelLoop.\nDefinition ml: MemoryLayout.MemoryLayout(word:=Naive.word32) := {|\n  MemoryLayout.code_start    := word.of_Z 0x20400000;\n  MemoryLayout.code_pastend  := word.of_Z 0x21400000;\n  MemoryLayout.heap_start    := word.of_Z 0x80000000;\n  MemoryLayout.heap_pastend  := word.of_Z 0x80002000;\n  MemoryLayout.stack_start   := word.of_Z 0x80002000;\n  MemoryLayout.stack_pastend := word.of_Z 0x80004000;\n|}.\n\nLemma ml_ok : MemoryLayout.MemoryLayoutOk ml. Proof. split; cbv; trivial; inversion 1. Qed.\n\nLocal Instance : FlatToRiscvCommon.bitwidth_iset 32 Decode.RV32IM := eq_refl.\nDerive garagedoor_compiler_result SuchThat\n  (ToplevelLoop.compile_prog (string_keyed_map:=@SortedListString.map) MMIO.compile_ext_call ml funcs\n  = Success garagedoor_compiler_result)\n  As garagedoor_compiler_result_ok.\nProof.\n  match goal with x := _ |- _ => cbv delta [x]; clear x end.\n  vm_compute.\n  match goal with |- @Success ?A ?x = Success ?e => is_evar e;\n    exact (@eq_refl (result A) (@Success A x)) end.\nQed. Optimize Heap.\n\nDefinition garagedoor_stack_size := snd garagedoor_compiler_result.\nDefinition garagedoor_finfo := snd (fst garagedoor_compiler_result).\nDefinition garagedoor_insns := fst (fst garagedoor_compiler_result).\nDefinition garagedoor_bytes := Pipeline.instrencode garagedoor_insns.\nDefinition garagedoor_symbols : list byte := Symbols.symbols garagedoor_finfo.\n\nRequire Import compiler.CompilerInvariant.\nRequire Import compiler.NaiveRiscvWordProperties.\nLocal Existing Instance SortedListString.map.\n\nLemma compiler_emitted_valid_instructions :\n  bverify.bvalidInstructions Decode.RV32IM garagedoor_insns = true.\nProof. vm_cast_no_check (eq_refl true). Qed.\n\nDefinition good_trace s t s' :=\n  exists ioh, SPI.mmio_trace_abstraction_relation ioh t /\\\n  (BootSeq +++ stateful garagedoor_iteration s s') ioh.\nImport ExprImpEventLoopSpec.\nDefinition garagedoor_spec : ProgramSpec := {|\n  datamem_start := MemoryLayout.heap_start ml;\n  datamem_pastend := MemoryLayout.heap_pastend ml;\n  goodTrace t := exists s0 s, good_trace s0 t s;\n  isReady t m := exists s0 s, good_trace s0 t s /\\ exists bs R, memrep bs R s m |}.\n\nLemma good_trace_from_isRead a a0 : isReady garagedoor_spec a a0 ->\n  isReady garagedoor_spec a a0 /\\\n  ExprImpEventLoopSpec.goodTrace garagedoor_spec a.\nProof.\n  cbv [isReady goodTrace garagedoor_spec]; intuition eauto.\n  case H as (?&?&?&?&?&H); eauto.\nQed.\n\nLemma link_initfn : spec_of_initfn funcs.\nProof.\n  eapply initfn_ok.\n  eapply memconst_ok.\n  eapply lan9250_init_ok;\n    try (eapply lan9250_wait_for_boot_ok || eapply lan9250_mac_write_ok);\n    (eapply lan9250_readword_ok || eapply lan9250_writeword_ok);\n        eapply spi_xchg_ok;\n        (eapply spi_write_ok || eapply spi_read_ok).\nQed. Optimize Heap.\n\nImport ToplevelLoop GoFlatToRiscv .\nLocal Notation invariant := (ll_inv compile_ext_call ml garagedoor_spec).\nLemma invariant_proof :\n  forall initial : MetricRiscvMachine,\n    getPc (getMachine initial) = MemoryLayout.code_start ml ->\n    getNextPc (getMachine initial) = word.add (getPc (getMachine initial)) (word.of_Z 4)->\n    regs_initialized.regs_initialized (getRegs (getMachine initial)) ->\n    getLog (getMachine initial) = [] ->\n    (forall a, word.unsigned (MemoryLayout.code_start ml) <= word.unsigned a < word.unsigned (MemoryLayout.code_pastend ml) -> In a (getXAddrs (getMachine initial))) ->\n    valid_machine initial ->\n    (imem (MemoryLayout.code_start ml) (MemoryLayout.code_pastend ml) garagedoor_insns *\n     LowerPipeline.mem_available (MemoryLayout.heap_start ml) (MemoryLayout.heap_pastend ml) *\n     LowerPipeline.mem_available (MemoryLayout.stack_start ml) (MemoryLayout.stack_pastend ml))%sep (getMem (getMachine initial)) ->\n\n     invariant initial /\\\n     (forall st, invariant st -> mcomp_sat (run1 Decode.RV32IM) st invariant /\\\n       exists extend s0 s1, good_trace s0 (extend ++ getLog (getMachine st)) s1).\nProof.\n  intros.\n\n  unshelve epose proof compiler_invariant_proofs _ _ _ _ _ garagedoor_spec as HCI; shelve_unifiable; try exact _.\n  { exact (naive_word_riscv_ok 5%nat). }\n  { eapply SortedListString.ok. }\n  { eapply compile_ext_call_correct. }\n  { intros. cbv [compile_ext_call compile_interact]; BreakMatch.break_match; trivial. }\n  { exact ml_ok. }\n  ssplit; intros; ssplit; eapply HCI; eauto; [].\n\n  econstructor.\n  eexists garagedoor_insns.\n  eexists garagedoor_finfo.\n  eexists garagedoor_stack_size.\n  rewrite garagedoor_compiler_result_ok; ssplit; trivial using compiler_emitted_valid_instructions.\n  2,3:vm_compute; inversion 1.\n  econstructor (* ProgramSatisfiesSpec *).\n  1: vm_compute; reflexivity.\n  1: instantiate (1:=snd init).\n  3: instantiate (1:=snd loop).\n  1,3: exact eq_refl.\n  1,2: cbv [hl_inv]; intros; eapply WeakestPreconditionProperties.sound_cmd.\n  1,3: eapply Crypto.Util.Bool.Reflect.reflect_bool; vm_compute; reflexivity.\n\n  all : repeat straightline; subst args.\n  { repeat straightline.\n    cbv [LowerPipeline.mem_available LowerPipeline.ptsto_bytes] in *.\n    cbv [datamem_pastend datamem_start garagedoor_spec heap_start heap_pastend ml] in H6.\n    SeparationLogic.extract_ex1_and_emp_in H6.\n    change (BinIntDef.Z.of_nat (Datatypes.length anybytes) = 0x2000) in H6_emp0.\n    Tactics.rapply WeakestPreconditionProperties.Proper_call;\n      [|eapply link_initfn]; try eassumption.\n    2: {\n      rewrite <-(List.firstn_skipn 0x40 anybytes) in H6.\n      rewrite <-(List.firstn_skipn 0x20 (List.skipn _ anybytes)) in H6.\n      do 2 seprewrite_in @Array.bytearray_append H6.\n      rewrite 2firstn_length, skipn_length, 2Nat2Z.inj_min, Nat2Z.inj_sub, H6_emp0 in H6.\n      split.\n      { use_sep_assumption. cancel. cancel_seps_at_indices 0%nat 0%nat; [|ecancel_done].\n        Morphisms.f_equiv. }\n      { rewrite firstn_length, skipn_length. Lia.lia. }\n      { Lia.lia. } }\n    intros ? ? ? ?; repeat straightline; eapply good_trace_from_isRead.\n    subst a; rewrite app_nil_r.\n    rewrite <-(List.firstn_skipn 0x20 (List.firstn _ anybytes)) in H11.\n    rewrite <-(List.firstn_skipn 1520 (skipn 32 (skipn 64 anybytes))) in H11.\n    do 2 seprewrite_in @Array.bytearray_append H11.\n    rewrite ?firstn_length, ?skipn_length, ?Nat2Z.inj_min, ?Nat2Z.inj_sub, H6_emp0 in H11.\n    cbv [isReady garagedoor_spec good_trace]. eexists (_,_), (_,_); fwd. eauto.\n    { rewrite <-app_nil_l. eapply TracePredicate.concat_app; eauto. econstructor. }\n    cbv [memrep]. ssplit.\n    { use_sep_assumption. cancel.\n      cancel_seps_at_indices 0%nat 0%nat; [reflexivity|].\n      cancel_seps_at_indices 0%nat 0%nat; [reflexivity|].\n      cancel_seps_at_indices 0%nat 0%nat; [reflexivity|].\n      ecancel_done. }\n    all : repeat rewrite ?firstn_length, ?skipn_length; try Lia.lia. }\n\n  {  match goal with H : goodTrace _ _ |- _ => clear H end.\n    cbv [isReady goodTrace good_trace garagedoor_spec] in *; repeat straightline.\n    DestructHead.destruct_head' state.\n    Tactics.rapply WeakestPreconditionProperties.Proper_call;\n      [|eapply link_loopfn]; try eassumption.\n    intros ? ? ? ?; repeat straightline; eapply good_trace_from_isRead.\n    eexists; fwd; try eassumption.\n    cbv [good_trace] in *; repeat straightline.\n    { subst a.  (eexists; split; [eapply Forall2_app; eauto|]).\n      eapply stateful_app_r, stateful_singleton; eauto. } }\n\n  Unshelve.\n  all : trivial using SortedListString.ok.\nQed.\n\n(*\nPrint Assumptions link_loopfn. (* Closed under the global context *)\nPrint Assumptions invariant_proof. (* propositional_extensionality, functional_extensionality_dep *)\n*)\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Bedrock/End2End/X25519/GarageDoor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.24797006726805898}}
{"text": "Require Import Coq.Classes.Morphisms.\nRequire Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Tuple.\nRequire Import Crypto.Util.Tactics.RewriteHyp.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Notations.\n\nSection homogenous_type.\n  Context {base_type_code : Type}\n          {op : flat_type base_type_code -> flat_type base_type_code -> Type}\n          {var : base_type_code -> Type}.\n\n  Local Notation flat_type := (flat_type base_type_code).\n  Local Notation type := (type base_type_code).\n  Local Notation interp_flat_type := (@interp_flat_type base_type_code).\n  Local Notation exprf := (@exprf base_type_code op var).\n  Local Notation expr := (@expr base_type_code op var).\n\n  (** Sometimes, we want to deal with partially-interpreted\n      expressions, things like [prod (exprf A) (exprf B)] rather than\n      [exprf (Prod A B)], or like [prod (var A) (var B)] when we start\n      with the type [Prod A B].  These convenience functions let us\n      recurse on the type in only one place, and replace one kind of\n      pairing operator (be it [pair] or [Pair] or anything else) with\n      another kind, and simultaneously mapping a function over the\n      base values (e.g., [Var] (for turning [var] into [exprf]) or\n      [Const] (for turning [interp_base_type] into [exprf])). *)\n  Fixpoint smart_interp_flat_map {f g}\n           (h : forall x, f x -> g (Tbase x))\n           (tt : g Unit)\n           (pair : forall A B, g A -> g B -> g (Prod A B))\n           {t}\n    : interp_flat_type f t -> g t\n    := match t return interp_flat_type f t -> g t with\n       | Syntax.Tbase _ => h _\n       | Unit => fun _ => tt\n       | Prod A B => fun v : interp_flat_type _ A * interp_flat_type _ B\n                     => pair _ _\n                             (@smart_interp_flat_map f g h tt pair A (fst v))\n                             (@smart_interp_flat_map f g h tt pair B (snd v))\n       end.\n  Fixpoint smart_interp_flat_map2 {f1 f2 g}\n           (h : forall x, f1 x -> f2 x -> g (Tbase x))\n           (tt : g Unit)\n           (pair : forall A B, g A -> g B -> g (Prod A B))\n           {t}\n    : interp_flat_type f1 t -> interp_flat_type f2 t -> g t\n    := match t return interp_flat_type f1 t -> interp_flat_type f2 t -> g t with\n       | Syntax.Tbase _ => h _\n       | Unit => fun _ _ => tt\n       | Prod A B => fun (v1 : interp_flat_type _ A * interp_flat_type _ B)\n                         (v2 : interp_flat_type _ A * interp_flat_type _ B)\n                     => pair _ _\n                             (@smart_interp_flat_map2 f1 f2 g h tt pair A (fst v1) (fst v2))\n                             (@smart_interp_flat_map2 f1 f2 g h tt pair B (snd v1) (snd v2))\n       end.\n  Fixpoint smart_interp_flat_map3 {f1 f2 f3 g}\n           (h : forall x, f1 x -> f2 x -> f3 x -> g (Tbase x))\n           (tt : g Unit)\n           (pair : forall A B, g A -> g B -> g (Prod A B))\n           {t}\n    : interp_flat_type f1 t -> interp_flat_type f2 t -> interp_flat_type f3 t -> g t\n    := match t return interp_flat_type f1 t -> interp_flat_type f2 t -> interp_flat_type f3 t -> g t with\n       | Syntax.Tbase _ => h _\n       | Unit => fun _ _ _ => tt\n       | Prod A B => fun (v1 : interp_flat_type _ A * interp_flat_type _ B)\n                         (v2 : interp_flat_type _ A * interp_flat_type _ B)\n                         (v3 : interp_flat_type _ A * interp_flat_type _ B)\n                     => pair _ _\n                             (@smart_interp_flat_map3 f1 f2 f3 g h tt pair A (fst v1) (fst v2) (fst v3))\n                             (@smart_interp_flat_map3 f1 f2 f3 g h tt pair B (snd v1) (snd v2) (snd v3))\n       end.\n  Definition smart_interp_map_hetero {f g g'}\n             (h : forall x, f x -> g (Tbase x))\n             (tt : g Unit)\n             (pair : forall A B, g A -> g B -> g (Prod A B))\n             (abs : forall A B, (g A -> g B) -> g' (Arrow A B))\n             {t}\n    : interp_type_gen_hetero g (interp_flat_type f) t -> g' t\n    := match t return interp_type_gen_hetero g (interp_flat_type f) t -> g' t with\n       | Arrow A B => fun v => abs _ _\n                                   (fun x => @smart_interp_flat_map f g h tt pair _ (v x))\n       end.\n  Fixpoint SmartValf {T} (val : forall t : base_type_code, T t) t : interp_flat_type T t\n    := match t return interp_flat_type T t with\n       | Syntax.Tbase _ => val _\n       | Unit => tt\n       | Prod A B => (@SmartValf T val A, @SmartValf T val B)\n       end.\n  Section SmartValf_monad.\n    Context (M : Type -> Type) (ret : forall T, T -> M T)\n            (bind : forall A B, M A -> (A -> M B) -> M B).\n    Fixpoint SmartValfM\n             {T} (val : forall t : base_type_code, M (T t)) t : M (interp_flat_type T t)\n      := match t return M (interp_flat_type T t) with\n         | Syntax.Tbase _ => val _\n         | Unit => ret _ tt\n         | Prod A B => bind _ _ (@SmartValfM T val A)\n                            (fun a => bind _ _ (@SmartValfM T val B)\n                                           (fun b => ret _ (a, b)))\n         end.\n  End SmartValf_monad.\n\n  (** [SmartVar] is like [Var], except that it inserts\n      pair-projections and [Pair] as necessary to handle [flat_type],\n      and not just [base_type_code] *)\n  Local Notation exprfb := (fun t => exprf (Tbase t)).\n  Definition SmartValf_option {T} (val : forall t, option (T t)) t\n    : option (interp_flat_type T t)\n    := @SmartValfM\n         (fun t => option t) (fun t v => @Some t v)\n         (fun _ _ x f => match x with\n                         | Some x => f x\n                         | None => None\n                         end)\n         T val t.\n  Definition SmartPairf {t} : interp_flat_type exprfb t -> exprf t\n    := @smart_interp_flat_map exprfb exprf (fun t x => x) TT (fun A B x y => Pair x y) t.\n  Lemma SmartPairf_Pair {A B} (e1 : interp_flat_type _ A) (e2 : interp_flat_type _ B)\n    : SmartPairf (t:=Prod A B) (e1, e2)%core = Pair (SmartPairf e1) (SmartPairf e2).\n  Proof using Type. reflexivity. Qed.\n  Definition SmartVarf {t} : interp_flat_type var t -> exprf t\n    := @smart_interp_flat_map var exprf (fun t => Var) TT (fun A B x y => Pair x y) t.\n  Definition SmartVarf_Pair {A B v}\n    : @SmartVarf (Prod A B) v = Pair (SmartVarf (fst v)) (SmartVarf (snd v))\n    := eq_refl.\n  Definition SmartVarfMap {var var'} (f : forall t, var t -> var' t) {t}\n    : interp_flat_type var t -> interp_flat_type var' t\n    := @smart_interp_flat_map var (interp_flat_type var') f tt (fun A B x y => pair x y) t.\n  Lemma SmartVarfMap_compose {var' var'' var''' t} f g x\n    : @SmartVarfMap var'' var''' g t (@SmartVarfMap var' var'' f t x)\n      = @SmartVarfMap _ _ (fun t v => g t (f t v)) t x.\n  Proof using Type.\n    unfold SmartVarfMap; clear; induction t; simpl; destruct_head_hnf unit; destruct_head_hnf prod;\n      rewrite_hyp ?*; congruence.\n  Qed.\n  Lemma SmartVarfMap_id {var' t} x : @SmartVarfMap var' var' (fun _ x => x) t x = x.\n  Proof using Type.\n    unfold SmartVarfMap; clear; induction t; simpl; destruct_head_hnf unit; destruct_head_hnf prod;\n      rewrite_hyp ?*; congruence.\n  Qed.\n  Definition SmartVarfMap_Pair {var' var''} {f' : forall t, var' t -> var'' t} {A B}\n             v\n    : @SmartVarfMap var' var'' f' (Prod A B) v\n      = (SmartVarfMap f' (fst v), SmartVarfMap f' (snd v))\n    := eq_refl.\n  Lemma SmartVarfMap_tuple' {var' var''} {f' : forall t, var' t -> var'' t} {T n}\n             v\n    : @SmartVarfMap var' var'' f' (tuple' T n) v\n      = flat_interp_untuple' (Tuple.map' (@SmartVarfMap var' var'' f' _) (flat_interp_tuple' v)).\n  Proof.\n    induction n as [|n IHn]; [ reflexivity | destruct v as [v0 v1] ].\n    simpl; rewrite SmartVarfMap_Pair, IHn; simpl.\n    reflexivity.\n  Qed.\n  Definition SmartVarfMap_tuple {var' var''} {f' : forall t, var' t -> var'' t} {T n}\n             v\n    : @SmartVarfMap var' var'' f' (tuple T n) v\n      = tuple_map (@SmartVarfMap var' var'' f' _) v.\n  Proof.\n    destruct n as [|n]; [ destruct v; reflexivity | ].\n    apply SmartVarfMap_tuple'.\n  Qed.\n  Global Instance smart_interp_flat_map_Proper {f g}\n    : Proper ((forall_relation (fun t => pointwise_relation _ eq))\n                ==> eq\n                ==> (forall_relation (fun A => forall_relation (fun B => pointwise_relation _ (pointwise_relation _ eq))))\n                ==> forall_relation (fun t => eq ==> eq))\n             (@smart_interp_flat_map f g).\n  Proof using Type.\n    unfold forall_relation, pointwise_relation, respectful.\n    intros F G HFG x y ? Q R HQR t a b ?; subst y b.\n    induction t; simpl in *; auto.\n    rewrite_hyp !*; reflexivity.\n  Qed.\n  Global Instance SmartVarfMap_Proper {var' var''}\n    : Proper (forall_relation (fun t => pointwise_relation _ eq) ==> forall_relation (fun t => eq ==> eq))\n             (@SmartVarfMap var' var'').\n  Proof using Type.\n    repeat intro; eapply smart_interp_flat_map_Proper; trivial; repeat intro; reflexivity.\n  Qed.\n  Definition SmartVarfMap2 {var var' var''} (f : forall t, var t -> var' t -> var'' t) {t}\n    : interp_flat_type var t -> interp_flat_type var' t -> interp_flat_type var'' t\n    := @smart_interp_flat_map2 var var' (interp_flat_type var'') f tt (fun A B x y => pair x y) t.\n  Lemma SmartVarfMap2_fst_arg {var' var''} {t}\n        (x : interp_flat_type var' t)\n        (y : interp_flat_type var'' t)\n    : SmartVarfMap2 (fun _ a b => a) x y = x.\n  Proof using Type.\n    unfold SmartVarfMap2; clear; induction t; simpl; destruct_head_hnf unit; destruct_head_hnf prod;\n      rewrite_hyp ?*; congruence.\n  Qed.\n  Lemma SmartVarfMap2_snd_arg {var' var''} {t}\n        (x : interp_flat_type var' t)\n        (y : interp_flat_type var'' t)\n    : SmartVarfMap2 (fun _ a b => b) x y = y.\n  Proof using Type.\n    unfold SmartVarfMap2; clear; induction t; simpl; destruct_head_hnf unit; destruct_head_hnf prod;\n      rewrite_hyp ?*; congruence.\n  Qed.\n  Definition SmartVarfMap3 {var var' var'' var'''} (f : forall t, var t -> var' t -> var'' t -> var''' t) {t}\n    : interp_flat_type var t -> interp_flat_type var' t -> interp_flat_type var'' t -> interp_flat_type var''' t\n    := @smart_interp_flat_map3 var var' var'' (interp_flat_type var''') f tt (fun A B x y => pair x y) t.\n  Definition SmartVarfTypeMap {var} (f : forall t, var t -> Type) {t}\n    : interp_flat_type var t -> Type\n    := @smart_interp_flat_map var (fun _ => Type) f unit (fun _ _ P Q => P * Q)%type t.\n  Definition SmartVarfPropMap {var} (f : forall t, var t -> Prop) {t}\n    : interp_flat_type var t -> Prop\n    := @smart_interp_flat_map var (fun _ => Prop) f True (fun _ _ P Q => P /\\ Q)%type t.\n  Definition SmartVarfTypeMap2 {var var'} (f : forall t, var t -> var' t -> Type) {t}\n    : interp_flat_type var t -> interp_flat_type var' t -> Type\n    := @smart_interp_flat_map2 var var' (fun _ => Type) f unit (fun _ _ P Q => P * Q)%type t.\n  Definition SmartVarfPropMap2 {var var'} (f : forall t, var t -> var' t -> Prop) {t}\n    : interp_flat_type var t -> interp_flat_type var' t -> Prop\n    := @smart_interp_flat_map2 var var' (fun _ => Prop) f True (fun _ _ P Q => P /\\ Q)%type t.\n  Definition SmartFlatTypeMap {var'} (f : forall t, var' t -> base_type_code) {t}\n    : interp_flat_type var' t -> flat_type\n    := @smart_interp_flat_map var' (fun _ => flat_type) (fun t v => Tbase (f t v)) Unit (fun _ _ => Prod) t.\n  Definition SmartFlatTypeMap_Pair {var'} (f : forall t, var' t -> base_type_code) {A B}\n        (x : interp_flat_type var' (A * B))\n    : SmartFlatTypeMap f x\n      = (SmartFlatTypeMap f (@fst (interp_flat_type _ _) (interp_flat_type _ _) x)\n         * SmartFlatTypeMap f (@snd (interp_flat_type _ _) (interp_flat_type _ _) x))%ctype\n    := eq_refl.\n  Definition SmartFlatTypeUnMap (t : flat_type)\n    : interp_flat_type (fun _ => base_type_code) t\n    := SmartValf (fun t => t) t.\n  Fixpoint SmartFlatTypeMapInterp {var' var''} (f : forall t, var' t -> base_type_code)\n           (fv : forall t v, var'' (f t v)) t {struct t}\n    : forall v, interp_flat_type var'' (SmartFlatTypeMap f (t:=t) v)\n    := match t return forall v, interp_flat_type var'' (SmartFlatTypeMap f (t:=t) v) with\n       | Syntax.Tbase x => fv _\n       | Unit => fun v => v\n       | Prod A B => fun xy : interp_flat_type _ A * interp_flat_type _ B\n                     => (@SmartFlatTypeMapInterp _ _ f fv A (fst xy),\n                         @SmartFlatTypeMapInterp _ _ f fv B (snd xy))\n       end.\n  Fixpoint SmartFlatTypeMapInterp2 {var' var'' var'''} (f : forall t, var' t -> base_type_code)\n           (fv : forall t v, var'' t -> var''' (f t v)) t {struct t}\n    : forall v, interp_flat_type var'' t -> interp_flat_type var''' (SmartFlatTypeMap f (t:=t) v)\n    := match t return forall v, interp_flat_type var'' t -> interp_flat_type var''' (SmartFlatTypeMap f (t:=t) v) with\n       | Syntax.Tbase x => fv _\n       | Unit => fun v _ => v\n       | Prod A B => fun (xy : interp_flat_type _ A * interp_flat_type _ B)\n                         (x'y' : interp_flat_type _ A * interp_flat_type _ B)\n                     => (@SmartFlatTypeMapInterp2 _ _ _ f fv A (fst xy) (fst x'y'),\n                         @SmartFlatTypeMapInterp2 _ _ _ f fv B (snd xy) (snd x'y'))\n       end.\n  Fixpoint SmartFlatTypeMapUnInterp var' var'' var''' (f : forall t, var' t -> base_type_code)\n           (fv : forall t (v : var' t), var'' (f t v) -> var''' t)\n           {t} {struct t}\n    : forall v, interp_flat_type var'' (SmartFlatTypeMap f (t:=t) v)\n                -> interp_flat_type var''' t\n    := match t return forall v, interp_flat_type var'' (SmartFlatTypeMap f (t:=t) v)\n                                -> interp_flat_type var''' t with\n       | Syntax.Tbase x => fv _\n       | Unit => fun _ v => v\n       | Prod A B => fun (v : interp_flat_type _ A * interp_flat_type _ B)\n                         (xy : interp_flat_type _ (SmartFlatTypeMap _ (fst v)) * interp_flat_type _ (SmartFlatTypeMap _ (snd v)))\n                     => (@SmartFlatTypeMapUnInterp _ _ _ f fv A _ (fst xy),\n                         @SmartFlatTypeMapUnInterp _ _ _ f fv B _ (snd xy))\n       end.\n  Definition SmartVarMap {var' var''} (f : forall t, var' t -> var'' t) (f' : forall t, var'' t -> var' t) {t}\n    : interp_type_gen (interp_flat_type var') t -> interp_type_gen (interp_flat_type var'') t\n    := match t return interp_type_gen (interp_flat_type var') t -> interp_type_gen (interp_flat_type var'') t with\n       | Arrow src dst => fun F x => SmartVarfMap f (F (SmartVarfMap f' x))\n       end.\n  Lemma SmartVarMap_id {var' t} x v : @SmartVarMap var' var' (fun _ x => x) (fun _ x => x) t x v = x v.\n  Proof using Type. destruct t; simpl; rewrite !SmartVarfMap_id; reflexivity. Qed.\n  Definition SmartVarVarf {t} : interp_flat_type var t -> interp_flat_type exprfb t\n    := SmartVarfMap (fun t => Var).\n  Definition SmartVarVarf_Pair {A B} (v : interp_flat_type _ _ * interp_flat_type _ _)\n    : @SmartVarVarf (Prod A B) v\n      = (SmartVarVarf (fst v), SmartVarVarf (snd v))\n    := eq_refl.\n  Lemma SmartPairfSmartVarVarf_SmartVarf {t} v\n    : SmartPairf (SmartVarVarf v) = SmartVarf (t:=t) v.\n  Proof.\n    induction t; try reflexivity; simpl.\n    rewrite SmartVarf_Pair, SmartVarVarf_Pair, SmartPairf_Pair; f_equal;\n      auto.\n  Qed.\nEnd homogenous_type.\n\nGlobal Arguments SmartVarf {_ _ _ _} _.\nGlobal Arguments SmartPairf {_ _ _ t} _.\nGlobal Arguments SmartValf {_} T _ t.\nGlobal Arguments SmartVarVarf {_ _ _ _} _.\nGlobal Arguments SmartVarfMap {_ _ _} _ {!_} _ / .\nGlobal Arguments SmartVarfMap2 {_ _ _ _} _ {!t} _ _ / .\nGlobal Arguments SmartVarfMap3 {_ _ _ _ _} _ {!t} _ _ _ / .\nGlobal Arguments SmartVarfTypeMap {_ _} _ {_} _.\nGlobal Arguments SmartVarfPropMap {_ _} _ {_} _.\nGlobal Arguments SmartVarfTypeMap2 {_ _ _} _ {t} _ _.\nGlobal Arguments SmartVarfPropMap2 {_ _ _} _ {t} _ _.\nGlobal Arguments SmartFlatTypeMap {_ _} _ {_} _.\nGlobal Arguments SmartFlatTypeUnMap {_} _.\nGlobal Arguments SmartFlatTypeMapInterp {_ _ _ _} _ {_} _.\nGlobal Arguments SmartFlatTypeMapInterp2 {_ _ _ _ f} fv {t} _ _.\nGlobal Arguments SmartFlatTypeMapUnInterp {_ _ _ _ _} fv {_ _} _.\nGlobal Arguments SmartVarMap {_ _ _} _ _ {!_} _ / _.\n\nSection hetero_type.\n  Fixpoint flatten_flat_type {base_type_code} (t : flat_type (flat_type base_type_code)) : flat_type base_type_code\n    := match t with\n       | Tbase T => T\n       | Unit => Unit\n       | Prod A B => Prod (@flatten_flat_type _ A) (@flatten_flat_type _ B)\n       end.\n\n  Section smart_flat_type_map2.\n    Context {base_type_code1 base_type_code2 : Type}.\n\n    Definition SmartFlatTypeMap2 {var' : base_type_code1 -> Type} (f : forall t, var' t -> flat_type base_type_code2) {t}\n      : interp_flat_type var' t -> flat_type base_type_code2\n      := @smart_interp_flat_map base_type_code1 var' (fun _ => flat_type base_type_code2) f Unit (fun _ _ => Prod) t.\n    Fixpoint SmartFlatTypeMap2Interp {var' var''} (f : forall t, var' t -> flat_type base_type_code2)\n             (fv : forall t v, interp_flat_type var'' (f t v)) t {struct t}\n      : forall v, interp_flat_type var'' (SmartFlatTypeMap2 f (t:=t) v)\n      := match t return forall v, interp_flat_type var'' (SmartFlatTypeMap2 f (t:=t) v) with\n         | Tbase x => fv _\n         | Unit => fun v => v\n         | Prod A B => fun xy : interp_flat_type _ A * interp_flat_type _ B\n                       => (@SmartFlatTypeMap2Interp _ _ f fv A (fst xy),\n                           @SmartFlatTypeMap2Interp _ _ f fv B (snd xy))\n         end.\n    Fixpoint SmartFlatTypeMapUnInterp2 var' var'' var''' (f : forall t, var' t -> flat_type base_type_code2)\n             (fv : forall t (v : var' t), interp_flat_type var'' (f t v) -> var''' t)\n             {t} {struct t}\n      : forall v, interp_flat_type var'' (SmartFlatTypeMap2 f (t:=t) v)\n                  -> interp_flat_type var''' t\n      := match t return forall v, interp_flat_type var'' (SmartFlatTypeMap2 f (t:=t) v)\n                                  -> interp_flat_type var''' t with\n         | Tbase x => fv _\n         | Unit => fun _ v => v\n         | Prod A B => fun (v : interp_flat_type _ A * interp_flat_type _ B)\n                           (xy : interp_flat_type _ (SmartFlatTypeMap2 _ (fst v)) * interp_flat_type _ (SmartFlatTypeMap2 _ (snd v)))\n                       => (@SmartFlatTypeMapUnInterp2 _ _ _ f fv A _ (fst xy),\n                           @SmartFlatTypeMapUnInterp2 _ _ _ f fv B _ (snd xy))\n         end.\n    Fixpoint SmartFlatTypeMap2Interp2 {var' var'' var'''} (f : forall t, var' t -> flat_type base_type_code2)\n             (fv : forall t v, var'' t -> interp_flat_type var''' (f t v)) t {struct t}\n      : forall v, interp_flat_type var'' t -> interp_flat_type var''' (SmartFlatTypeMap2 f (t:=t) v)\n      := match t return forall v, interp_flat_type var'' t -> interp_flat_type var''' (SmartFlatTypeMap2 f (t:=t) v) with\n         | Tbase x => fv _\n         | Unit => fun v _ => v\n         | Prod A B => fun (xy : interp_flat_type _ A * interp_flat_type _ B)\n                           (x'y' : interp_flat_type _ A * interp_flat_type _ B)\n                       => (@SmartFlatTypeMap2Interp2 _ _ _ f fv A (fst xy) (fst x'y'),\n                           @SmartFlatTypeMap2Interp2 _ _ _ f fv B (snd xy) (snd x'y'))\n         end.\n\n    Lemma SmartFlatTypeMapUnInterp2_SmartFlatTypeMap2Interp2\n          var' var'' var'''\n          (f : forall t, var' t -> flat_type base_type_code2)\n          (fv : forall t (v : var' t), interp_flat_type var'' (f t v) -> var''' t)\n          (gv : forall t v, var''' t -> interp_flat_type var'' (f t v))\n          {t} v\n          (e : interp_flat_type var''' t)\n      : @SmartFlatTypeMapUnInterp2\n          _ _ _ f fv t v\n          (@SmartFlatTypeMap2Interp2\n             _ _ _ f gv t v e)\n        = SmartVarfMap2 (fun t v e => fv t v (gv t v e)) v e.\n    Proof using Type.\n      induction t; simpl in *; destruct_head' unit;\n        rewrite_hyp ?*; reflexivity.\n    Qed.\n  End smart_flat_type_map2.\n\n  Section smart_flat_type.\n    Context {base_type_code1 base_type_code2 : Type}\n            (f : base_type_code1 -> base_type_code2).\n    Fixpoint lift_flat_type (t : flat_type base_type_code1)\n      : flat_type base_type_code2\n      := match t with\n         | Tbase T => Tbase (f T)\n         | Unit => Unit\n         | Prod A B => Prod (lift_flat_type A) (lift_flat_type B)\n         end.\n\n    Section with_var.\n      Context {var1 : base_type_code1 -> Type}\n              {var2 : base_type_code2 -> Type}\n              (fvar : forall t, var1 t -> var2 (f t))\n              (fvar' : forall t, var2 (f t) -> var1 t).\n\n      Fixpoint transfer_interp_flat_type {t}\n        : interp_flat_type var1 t\n          -> interp_flat_type var2 (lift_flat_type t)\n        := match t with\n           | Tbase T => fvar _\n           | Unit => fun v => v\n           | Prod A B => fun ab : interp_flat_type _ A * interp_flat_type _ B\n                         => (@transfer_interp_flat_type _ (fst ab),\n                             @transfer_interp_flat_type _ (snd ab))%core\n           end.\n\n      Fixpoint untransfer_interp_flat_type {t}\n        : interp_flat_type var2 (lift_flat_type t)\n          -> interp_flat_type var1 t\n        := match t with\n           | Tbase T => fvar' _\n           | Unit => fun v => v\n           | Prod A B => fun ab : interp_flat_type _ (lift_flat_type A)\n                                  * interp_flat_type _ (lift_flat_type B)\n                         => (@untransfer_interp_flat_type _ (fst ab),\n                             @untransfer_interp_flat_type _ (snd ab))%core\n           end.\n    End with_var.\n  End smart_flat_type.\nEnd hetero_type.\n\nGlobal Arguments SmartFlatTypeMap2 {_ _ _} _ {!_} _ / .\nGlobal Arguments SmartFlatTypeMap2Interp {_ _ _ _ _} fv {_} _.\nGlobal Arguments SmartFlatTypeMap2Interp2 {_ _ _ _ _ _} fv {t} v _.\nGlobal Arguments SmartFlatTypeMapUnInterp2 {_ _ _ _ _ _} fv {_ _} _.\n\nSection interp_lemmas.\n  Context {base_type_code : Type}\n          {op : flat_type base_type_code -> flat_type base_type_code -> Type}\n          {interp_base_type : base_type_code -> Type}\n          {interp_op : forall s d, op s d -> interp_flat_type interp_base_type s -> interp_flat_type interp_base_type d}.\n\n  Local Notation exprfb := (fun t => exprf _ op (Tbase t)).\n\n  Lemma interpf_SmartVarf\n        {t} (e : interp_flat_type _ t)\n  : @interpf _ interp_base_type _ interp_op _ (SmartVarf (var:=interp_base_type) e)\n    = e.\n  Proof.\n    induction t as [ t | | A IHA B IHB ]; try destruct e; try reflexivity.\n    rewrite !SmartVarf_Pair; cbn; rewrite IHA, IHB.\n    reflexivity.\n  Qed.\n\n  Lemma interpf_SmartPairf'\n        {t} (e : interp_flat_type exprfb t)\n  : @interpf _ interp_base_type _ interp_op _ (SmartPairf e)\n    = SmartVarfMap (fun t => interpf interp_op) e.\n  Proof.\n    induction t as [ t | | A IHA B IHB ]; try reflexivity.\n    { destruct e.\n      rewrite !SmartPairf_Pair, !SmartVarfMap_Pair, <- !IHA, <- !IHB.\n      reflexivity. }\n  Qed.\n\n  Lemma interpf_SmartPairf\n        {t} (e : interp_flat_type exprfb t)\n  : @interpf _ interp_base_type _ interp_op _ (SmartPairf (var:=interp_base_type) e)\n    = SmartVarfMap (fun t => interpf interp_op) e.\n  Proof. apply interpf_SmartPairf'. Qed.\nEnd interp_lemmas.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Compilers/SmartMap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.24795610126175752}}
{"text": "(** * Definition of Context Free Grammars *)\nRequire Import Coq.Strings.String Coq.Lists.List.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Common.\n\nSet Implicit Arguments.\n\nLocal Open Scope string_like_scope.\nLocal Open Scope type_scope.\n\nSection cfg.\n  Context {Char} {HSL : StringLikeMin Char} {predata : @parser_computational_predataT Char} (G : grammar Char).\n\n  Context (valid : nonterminals_listT).\n\n  (** Relation defining if a productions is maybe empty *)\n  Inductive maybe_empty_productions : productions Char -> Type :=\n  | MaybeEmptyHead : forall pat pats, maybe_empty_production pat\n                                      -> maybe_empty_productions (pat::pats)\n  | MaybeEmptyTail : forall pat pats, maybe_empty_productions pats\n                                      -> maybe_empty_productions (pat::pats)\n  with maybe_empty_production : production Char -> Type :=\n  | MaybeEmptyProductionNil : maybe_empty_production nil\n  | MaybeEmptyProductionCons : forall it its, maybe_empty_item it\n                                              -> maybe_empty_production its\n                                              -> maybe_empty_production (it::its)\n  with maybe_empty_item : item Char -> Type :=\n  | MaybeEmptyNonTerminal : forall nt, is_valid_nonterminal valid (of_nonterminal nt)\n                                      -> maybe_empty_productions (Lookup G nt)\n                                      -> maybe_empty_item (NonTerminal nt).\nEnd cfg.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/Reachable/MaybeEmpty/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.24786533211253592}}
{"text": "(* Copyright © 1998-2006\n * Henk Barendregt\n * Luís Cruz-Filipe\n * Herman Geuvers\n * Mariusz Giero\n * Rik van Ginneken\n * Dimitri Hendriks\n * Sébastien Hinderer\n * Bart Kirkels\n * Pierre Letouzey\n * Iris Loeb\n * Lionel Mamane\n * Milad Niqui\n * Russell O’Connor\n * Randy Pollack\n * Nickolay V. Shmyrev\n * Bas Spitters\n * Dan Synek\n * Freek Wiedijk\n * Jan Zwanenburg\n *\n * This work is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This work is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this work; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *)\n\n(** printing two_n %\\ensuremath{2n}% #2n# *)\n(** printing Small %\\ensuremath{\\frac13^n}% *)\n(** printing Smaller %\\ensuremath{\\frac13^{2n^2}}% *)\n\nRequire Export CoRN.reals.CSumsReals.\nRequire Export CoRN.fta.KeyLemma.\nRequire Import CoRN.algebra.CRing_as_Ring.\nFrom Coq Require Import Lia.\n\n(**\n** Main Lemma\n*)\n\nSection Main_Lemma.\n\n(**\n%\\begin{convention}%\nLet [a : nat->IR], [n : nat], [a_0 : IR]  and [eps : IR] such that [0 < n],\n[([0] [<] eps)], [forall (k : nat)([0] [<=] (a k))], [(a n) [=] [1]], and\n[(eps [<=] a_0)].\n%\\end{convention}%\n*)\n\nVariable a : nat -> IR.\nVariable n : nat.\nHypothesis gt_n_0 : 0 < n.\nVariable eps : IR.\nHypothesis eps_pos : [0] [<] eps.\nHypothesis a_nonneg : forall k : nat, [0] [<=] a k.\nHypothesis a_n_1 : a n [=] [1].\nVariable a_0 : IR.\nHypothesis eps_le_a_0 : eps [<=] a_0.\n\nLemma a_0_pos : [0] [<] a_0.\nProof.\n apply less_leEq_trans with eps; auto.\nQed.\n\n(**\n%\\begin{convention}% We define the following local abbreviations:\n - [two_n := 2 * n]\n - [Small := p3m n]\n - [Smaller := p3m (two_n * n)]\n\n%\\end{convention}%\n*)\n\n(* begin hide *)\nLet two_n := 2 * n.\nLet Small := p3m n.\nLet Smaller := p3m (two_n * n).\n(* end hide *)\n\nLemma Main_1a' : forall (t : IR) (j k : nat),\n let r' := t[*]p3m (S (S j)) in let r := t[*]p3m (S j) in\n (forall i, 1 <= i -> i <= n -> a i[*]r'[^]i[-]eps [<=] a k[*]r'[^]k) ->\n forall i : nat, 1 <= i -> i <= n -> a i[*] (r [/]ThreeNZ) [^]i[-]eps [<=] a k[*] (r [/]ThreeNZ) [^]k.\nProof.\n (* begin hide *)\n intros.\n cut ((t[*]p3m (S j)) [/]ThreeNZ [=] t[*]p3m (S (S j))). intro.\n  astepl (a i[*] (t[*]p3m (S (S j))) [^]i[-]eps).\n  astepr (a k[*] (t[*]p3m (S (S j))) [^]k).\n  auto.\n Step_final (t[*]p3m (S j) [/]ThreeNZ).\nQed.\n(* end hide *)\n\nLemma Main_1b' : forall (t : IR) (j k : nat),\n let r' := t[*]p3m j in let r := t[*]p3m (S j) in\n (forall i, 1 <= i -> i <= n -> a i[*]r'[^]i[-]eps [<=] a k[*]r'[^]k) ->\n forall i, 1 <= i -> i <= n -> a i[*] (r[*]Three) [^]i[-]eps [<=] a k[*] (r[*]Three) [^]k.\nProof.\n (* begin hide *)\n intros.\n cut (t[*]p3m (S j) [*]Three [=] t[*]p3m j). intro.\n  astepl (a i[*] (t[*]p3m j) [^]i[-]eps).\n  astepr (a k[*] (t[*]p3m j) [^]k).\n  auto.\n Step_final (t[*] (p3m (S j) [*]Three)).\nQed.\n(* end hide *)\n\nLemma Main_1a : forall (r : IR) (k : nat), [0] [<=] r -> 1 <= k -> k <= n ->\n (forall i, 1 <= i -> i <= n -> a i[*] (r [/]ThreeNZ) [^]i[-]eps [<=] a k[*] (r [/]ThreeNZ) [^]k) ->\n let p_ := fun i : nat => a i[*]r[^]i in let p_k := a k[*]r[^]k in\n Sum 1 (pred k) p_ [<=] Half[*] ([1][-]Small) [*]p_k[+]Half[*]Three[^]n[*]eps.\nProof.\n (* begin hide *)\n intros r k H H0 H1 H2 p_ p_k.\n unfold p_, p_k in |- *.\n apply leEq_transitive with (Sum 1 (pred k)\n   (fun i : nat => Three[^]i[*] (a k[*] (r [/]ThreeNZ) [^]k[+]eps))).\n  apply Sum_resp_leEq.\n   auto with arith.\n  intros i H3 H4.\n  cut (Three[^]i [#] ZeroR).\n   intro H5.\n   apply shift_leEq_mult' with H5.\n    apply nexp_resp_pos.\n    apply pos_three.\n   astepl (a i[*] (r[^]i[/] Three[^]i[//]H5)).\n   astepl (a i[*] (r [/]ThreeNZ) [^]i).\n   astepr (eps[+]a k[*] (r [/]ThreeNZ) [^]k).\n   apply shift_leEq_plus'.\n   apply H2.\n    assumption.\n   lia.\n  apply nexp_resp_ap_zero.\n  apply three_ap_zero.\n apply leEq_wdl with (Sum 1 (pred k) (fun i : nat => Three[^]i) [*]\n   (a k[*] (r [/]ThreeNZ) [^]k[+]eps)).\n  cut (Three[-][1] [#] ZeroR).\n   intro H3.\n   astepl ((Three[^]S (pred k) [-]Three[^]1[/] Three[-][1][//]H3) [*]\n     (a k[*] (r [/]ThreeNZ) [^]k[+]eps)).\n   rewrite <- (S_pred _ _ H0).\n   astepl ((Three[^]k[-]Three[/] Three[-][1][//]H3) [*] (a k[*] (r [/]ThreeNZ) [^]k[+]eps)).\n   rstepl ([1] [/]TwoNZ[*] (Three[^]k[-]Three) [*] (a k[*] (r [/]ThreeNZ) [^]k) [+]\n     [1] [/]TwoNZ[*] (Three[^]k[-]Three) [*]eps).\n   apply leEq_transitive with (Half[*] ([1][-]Small) [*] (a k[*]r[^]k) [+]\n     [1] [/]TwoNZ[*] (Three[^]k[-]Three) [*]eps).\n    apply plus_resp_leEq.\n    cut (Three[^]k [#] ZeroR).\n     intro H4.\n     astepl ([1] [/]TwoNZ[*] (Three[^]k[-]Three) [*] (a k[*] (r[^]k[/] Three[^]k[//]H4))).\n     rstepl ([1] [/]TwoNZ[*]a k[*]r[^]k[*] ([1][-] (Three[/] Three[^]k[//]H4))).\n     rstepr (Half[*]a k[*]r[^]k[*] ([1][-]Small)).\n     unfold Half in |- *.\n     apply mult_resp_leEq_lft.\n      apply minus_resp_leEq_both.\n       apply leEq_reflexive.\n      unfold Small in |- *.\n      unfold p3m in |- *.\n      cut (Three[^]pred k [#] ZeroR).\n       intro H5.\n       apply leEq_wdr with ([1][/] Three[^]pred k[//]H5).\n        cut (Three[^]n [#] ZeroR).\n         intro H6.\n         astepl ([1][/] Three[^]n[//]H6).\n         apply recip_resp_leEq.\n          apply nexp_resp_pos.\n          apply pos_three.\n         apply great_nexp_resp_le.\n          apply less_leEq; apply one_less_three.\n         lia.\n        apply nexp_resp_ap_zero.\n        apply three_ap_zero.\n       apply eq_div.\n       pattern k at 1 in |- *.\n       rewrite (S_pred _ _ H0).\n       astepl ([1][*] (Three[*]Three[^]pred k):IR).\n       clear H3 H4 H5.\n       astepl ((Three[*]Three[^]pred k):IR). reflexivity.\n       apply nexp_resp_ap_zero.\n      apply three_ap_zero.\n     apply mult_resp_nonneg.\n      apply mult_resp_nonneg.\n       apply less_leEq.\n       astepr (Half:IR).\n       apply pos_half.\n      apply a_nonneg.\n     apply nexp_resp_nonneg; auto.\n    apply nexp_resp_ap_zero.\n    apply three_ap_zero.\n   apply plus_resp_leEq_lft.\n   rstepl ([1] [/]TwoNZ[*]eps[*] (Three[^]k[-]Three)).\n   rstepr (Half[*]eps[*]Three[^]n).\n   unfold Half in |- *.\n   apply mult_resp_leEq_lft.\n    apply leEq_transitive with (Three[^]k:IR).\n     astepr (Three[^]k[-]ZeroR).\n     apply minus_resp_leEq_rht.\n     apply less_leEq; apply pos_three.\n    apply great_nexp_resp_le; auto.\n    apply less_leEq; apply one_less_three.\n   apply less_leEq; apply mult_resp_pos; auto.\n   astepr (Half:IR); apply pos_half.\n  rstepl (Two:IR).\n  apply two_ap_zero.\n apply eq_symmetric_unfolded.\n apply mult_distr_sum_rht with (f := fun i : nat => (Three:IR) [^]i).\nQed.\n(* end hide *)\n\nLemma Main_1b : forall (r : IR) (k : nat), [0] [<=] r -> 1 <= k -> k <= n ->\n (forall i,  1 <= i -> i <= n -> a i[*] (r[*]Three) [^]i[-]eps [<=] a k[*] (r[*]Three) [^]k) ->\n let p_ := fun i => a i[*]r[^]i in let p_k := a k[*]r[^]k in\n Sum (S k) n p_ [<=] Half[*] ([1][-]Small) [*]p_k[+]Half[*]Three[^]n[*]eps.\nProof.\n (* begin hide *)\n intros r k H H0 H1 H2 p_ p_k.\n unfold p_, p_k in |- *.\n cut (forall i : nat, Three[^]i [#] ZeroR).\n  intro H3.\n  2: intro i; apply pos_ap_zero.\n  2: apply nexp_resp_pos.\n  2: apply pos_three.\n apply leEq_transitive with (Sum (S k) n\n   (fun i : nat => a k[*] (r[*]Three) [^]k[+]eps[/] Three[^]i[//]H3 i)).\n  apply Sum_resp_leEq.\n   auto with arith.\n  intros i H4 H5.\n  apply shift_leEq_div.\n   apply nexp_resp_pos; apply pos_three.\n  rstepr (eps[+]a k[*] (r[*]Three) [^]k).\n  apply shift_leEq_plus'.\n  rstepl (a i[*] (r[^]i[*]Three[^]i) [-]eps).\n  astepl (a i[*] (r[*]Three) [^]i[-]eps).\n  apply H2; auto with arith.\n  apply le_trans with (S k); auto.\n astepl (Sum (S k) n (fun i : nat => (a k[*] (r[*]Three) [^]k[+]eps) [*][1][/] Three[^]i[//]H3 i)).\n astepl (Sum (S k) n (fun i : nat => (a k[*] (r[*]Three) [^]k[+]eps) [*] ([1][/] Three[^]i[//]H3 i))).\n apply leEq_wdl with ((a k[*] (r[*]Three) [^]k[+]eps) [*]\n   Sum (S k) n (fun i : nat => [1][/] Three[^]i[//]H3 i)).\n  2: apply eq_symmetric_unfolded.\n  2: apply mult_distr_sum_lft with (f := fun i : nat => [1][/] Three[^]i[//]H3 i).\n astepl ((a k[*] (r[*]Three) [^]k[+]eps) [*] Sum (S k) n (fun i : nat => ([1] [/]ThreeNZ) [^]i)).\n cut ([1][-][1] [/]ThreeNZ [#] ZeroR).\n  2: rstepl ((Two:IR) [/]ThreeNZ).\n  2: apply div_resp_ap_zero_rev.\n  2: apply two_ap_zero.\n intro H4.\n astepl ((a k[*] (r[*]Three) [^]k[+]eps) [*] (([1] [/]ThreeNZ) [^]S k[-] ([1] [/]ThreeNZ) [^]S n[/]\n   [1][-][1] [/]ThreeNZ[//]H4)).\n astepl ((a k[*] (r[*]Three) [^]k[+]eps) [*] ([1] [/]ThreeNZ[*] ([1] [/]ThreeNZ) [^]k[-]\n   [1] [/]ThreeNZ[*] ([1] [/]ThreeNZ) [^]n[/] [1][-][1] [/]ThreeNZ[//]H4)).\n rstepl ([1] [/]TwoNZ[*] (a k[*] (r[*]Three) [^]k) [*]\n   (([1] [/]ThreeNZ) [^]k[-] ([1] [/]ThreeNZ) [^]n) [+]\n     [1] [/]TwoNZ[*]eps[*] (([1] [/]ThreeNZ) [^]k[-] ([1] [/]ThreeNZ) [^]n)).\n apply leEq_transitive with (Half[*] ([1][-]Small) [*] (a k[*]r[^]k) [+]\n   [1] [/]TwoNZ[*]eps[*] (([1] [/]ThreeNZ) [^]k[-] ([1] [/]ThreeNZ) [^]n)).\n  apply plus_resp_leEq.\n  astepl ([1] [/]TwoNZ[*] (a k[*] (r[^]k[*]Three[^]k)) [*]\n    (([1] [/]ThreeNZ) [^]k[-] ([1] [/]ThreeNZ) [^]n)).\n  rstepl ([1] [/]TwoNZ[*]a k[*]r[^]k[*]\n    (Three[^]k[*] ([1] [/]ThreeNZ) [^]k[-]Three[^]k[*] ([1] [/]ThreeNZ) [^]n)).\n  unfold Half in |- *.\n  rstepr ([1] [/]TwoNZ[*]a k[*]r[^]k[*] ([1][-]Small)).\n  apply mult_resp_leEq_lft.\n   astepl (((Three:IR) [*][1] [/]ThreeNZ) [^]k[-]Three[^]k[*] ([1] [/]ThreeNZ) [^]n).\n   astepl ((((Three:IR) [*][1]) [/]ThreeNZ) [^]k[-]Three[^]k[*] ([1] [/]ThreeNZ) [^]n).\n   astepl (((Three:IR) [/]ThreeNZ) [^]k[-]Three[^]k[*] ([1] [/]ThreeNZ) [^]n).\n   astepl (OneR[^]k[-]Three[^]k[*] ([1] [/]ThreeNZ) [^]n).\n   astepl (OneR[-]Three[^]k[*] ([1] [/]ThreeNZ) [^]n).\n   apply less_leEq.\n   apply minus_resp_less_rht.\n   unfold Small in |- *.\n   unfold p3m in |- *.\n   rstepl (OneR[*] ([1] [/]ThreeNZ) [^]n).\n   apply mult_resp_less.\n    astepl (OneR[^]k).\n    apply nexp_resp_less; auto.\n     apply less_leEq; apply pos_one.\n    apply one_less_three.\n   apply nexp_resp_pos.\n   apply pos_div_three; apply pos_one.\n  apply mult_resp_nonneg.\n   apply mult_resp_nonneg.\n    apply less_leEq.\n    apply pos_div_two; apply pos_one.\n   apply a_nonneg.\n  apply nexp_resp_nonneg; assumption.\n apply plus_resp_leEq_lft.\n rstepr (Half[*]eps[*]Three[^]n).\n unfold Half in |- *.\n apply mult_resp_leEq_lft.\n  apply leEq_transitive with OneR.\n   apply leEq_transitive with ((OneR [/]ThreeNZ) [^]k).\n    astepr ((OneR [/]ThreeNZ) [^]k[-][0]).\n    apply less_leEq.\n    apply minus_resp_less_rht.\n    apply nexp_resp_pos.\n    apply pos_div_three; apply pos_one.\n   astepr ([1][^]k:IR).\n   apply nexp_resp_leEq.\n    apply less_leEq; apply pos_div_three; apply pos_one.\n   astepr (OneR [/]OneNZ).\n   apply less_leEq; apply recip_resp_less.\n    apply pos_one.\n   apply one_less_three.\n  astepl (OneR[^]n).\n  apply nexp_resp_leEq; apply less_leEq.\n   apply pos_one.\n  apply one_less_three.\n apply less_leEq.\n apply mult_resp_pos; auto.\n apply pos_div_two; apply pos_one.\nQed.\n(* end hide *)\n\nLemma Main_1 : forall (r : IR) (k : nat), [0] [<=] r -> 1 <= k -> k <= n ->\n (forall i,  1 <= i ->  i <= n -> a i[*] (r [/]ThreeNZ) [^]i[-]eps [<=] a k[*] (r [/]ThreeNZ) [^]k) ->\n (forall i,  1 <= i -> i <= n -> a i[*] (r[*]Three) [^]i[-]eps [<=] a k[*] (r[*]Three) [^]k) ->\n let p_ := fun i => a i[*]r[^]i in let p_k := a k[*]r[^]k in\n Sum 1 (pred k) p_[+]Sum (S k) n p_ [<=] ([1][-]Small) [*]p_k[+]Three[^]n[*]eps.\nProof.\n (* begin hide *)\n intros r k H H0 H1 H2 H3 p_ p_k.\n unfold p_, p_k in |- *.\n set (h := Half[*] ([1][-]Small) [*]p_k[+]Half[*]Three[^]n[*]eps) in *.\n apply leEq_wdr with (h[+]h); unfold h, p_k in |- *.\n  apply plus_resp_leEq_both.\n   apply Main_1a; auto.\n  apply Main_1b; auto.\n unfold Half in |- *; rational.\nQed.\n(* end hide *)\n\nLemma Main_2' : forall (t : IR) (i k : nat),\n a i[*] (t[*]p3m 0) [^]i[-]eps [<=] a k[*] (t[*]p3m 0) [^]k -> a i[*]t[^]i[-]eps [<=] a k[*]t[^]k.\nProof.\n intros.\n cut (t[*]p3m 0 [=] t). intro.\n  astepl (a i[*] (t[*]p3m 0) [^]i[-]eps).\n  astepr (a k[*] (t[*]p3m 0) [^]k).\n  auto.\n Step_final (t[*][1]).\nQed.\n\nLemma Main_2 : forall (t : IR) (j k : nat), let r := t[*]p3m j in\n [0] [<=] t -> a k[*]t[^]k [=] a_0[-]eps -> (forall i, 1 <= i -> i <= n -> a i[*]t[^]i[-]eps [<=] a k[*]t[^]k) ->\n forall i, 1 <= i -> i <= n -> a i[*]r[^]i [<=] a_0.\nProof.\n (* begin hide *)\n intros.\n unfold r in |- *.\n apply leEq_transitive with (a i[*]t[^]i).\n  astepl (a i[*] (t[^]i[*]p3m j[^]i)).\n  rstepl (p3m j[^]i[*] (a i[*]t[^]i)).\n  astepr ([1][*] (a i[*]t[^]i)).\n  apply mult_resp_leEq_rht.\n   astepr ([1][^]i:IR).\n   apply nexp_resp_leEq.\n    apply less_leEq; apply p3m_pos.\n   apply p3m_small.\n  astepl ([0][*]t[^]i).\n  apply mult_resp_leEq_rht; auto.\n  astepl ([0][^]i:IR).\n  apply nexp_resp_leEq; auto.\n  apply leEq_reflexive.\n apply leEq_wdr with (eps[+]a k[*]t[^]k).\n  apply shift_leEq_plus'; auto.\n astepl (eps[+] (a_0[-]eps)); rational.\nQed.\n(* end hide *)\n\nLemma Main_3a : forall (t : IR) (j k k_0 : nat), let r := t[*]p3m j in\n k_0 <= n -> a k_0[*]t[^]k_0 [=] a_0[-]eps -> a k_0[*]r[^]k_0[-]eps [<=] a k[*]r[^]k ->\n p3m (j * n) [*]a_0[-]Two[*]eps [<=] a k[*]r[^]k.\nProof.\n (* begin hide *)\n intros.\n unfold r in |- *.\n rstepl (p3m (j * n) [*]a_0[-]eps[-]eps).\n apply leEq_transitive with (a k_0[*] (t[*]p3m j) [^]k_0[-]eps); auto.\n apply minus_resp_leEq.\n astepr (a k_0[*] (t[^]k_0[*]p3m j[^]k_0)).\n astepr (a k_0[*] (t[^]k_0[*]p3m (j * k_0))).\n rstepr (p3m (j * k_0) [*] (a k_0[*]t[^]k_0)).\n astepr (p3m (j * k_0) [*] (a_0[-]eps)).\n astepr (p3m (j * k_0) [*]a_0[-]p3m (j * k_0) [*]eps).\n apply minus_resp_leEq_both.\n  apply mult_resp_leEq_rht.\n   apply p3m_mon'; auto with arith.\n  apply less_leEq; apply a_0_pos.\n astepr ([1][*]eps).\n apply mult_resp_leEq_rht.\n  apply p3m_small.\n apply less_leEq; auto.\nQed.\n(* end hide *)\n\nLemma Main_3 : forall (t : IR) (j k k_0 : nat), let r := t[*]p3m j in\n j < two_n -> k_0 <= n -> a k_0[*]t[^]k_0 [=] a_0[-]eps -> a k_0[*]r[^]k_0[-]eps [<=] a k[*]r[^]k ->\n Smaller[*]a_0[-]Two[*]eps [<=] a k[*]r[^]k.\nProof.\n (* begin hide *)\n intros t j k k_0 r H H0 H1 H2.\n unfold r in |- *.\n apply leEq_transitive with (p3m (j * n) [*]a_0[-]Two[*]eps).\n  apply minus_resp_leEq.\n  apply mult_resp_leEq_rht.\n   unfold Smaller in |- *.\n   apply p3m_mon'.\n   apply mult_le_compat_r; auto with arith.\n  apply less_leEq; apply a_0_pos.\n apply Main_3a with k_0; auto.\nQed.\n(* end hide *)\n\nLemma Main : {r : IR | [0] [<=] r | {k : nat | 1 <= k /\\ k <= n /\\\n (let p_ := fun i => a i[*]r[^]i in let p_k := a k[*]r[^]k in\n  Sum 1 (pred k) p_[+]Sum (S k) n p_ [<=] ([1][-]Small) [*]p_k[+]Three[^]n[*]eps /\\\n  r[^]n [<=] a_0 /\\ Smaller[*]a_0[-]Two[*]eps [<=] p_k /\\ p_k [<=] a_0)}}.\nProof.\n (* begin hide *)\nProof.\n elim (Key a n gt_n_0 eps eps_pos a_nonneg a_n_1 a_0 eps_le_a_0).\n intro t. intros H0 H1.\n elim (H1 two_n). intro k. intros H2.\n elim H2. intros H3 H4.\n elim H4. intros H5 H6.\n elim H6. intros H7 H8.\n elim (kseq_prop k n H3 H5). intro j. intros H9.\n elim H9. intros H10 H11. elim H11. intros H12 H13.\n clear H9 H6 H4 H2 H1.\n cut ([0] [<=] t[*]p3m (S j)). intro H14.\n  2: apply mult_resp_nonneg; auto.\n  2: apply less_leEq; apply p3m_pos.\n exists (t[*]p3m (S j)).\n  auto.\n exists (k (S j)).\n elim (H3 (S j)); intros H3' H3''.\n split. auto.\n  split. auto.\n  intros p_ p_k. (* patch *)\n split; unfold p_, p_k in |- *.\n  apply Main_1; auto.\n   intros i H15 H16.\n   apply Main_1a'; auto.\n   intros i0 H17 H18.\n   rewrite H13.\n   apply H8; auto with arith.\n  intros i H15 H16.\n  apply Main_1b'; auto.\n  intros i0 H17 H18.\n  rewrite <- H12.\n  apply H8; auto with arith.\n  apply le_trans with (S j); auto with arith.\n split.\n  astepl ([1][*] (t[*]p3m (S j)) [^]n).\n  astepl (a n[*] (t[*]p3m (S j)) [^]n).\n  apply Main_2 with (k 0); auto.\n  intros i H15 H16.\n  apply Main_2'.\n  apply H8; auto with arith.\n elim (H3 0); intros H3''' H3''''.\n split.\n  apply Main_3 with (k 0); auto.\n  apply H8; auto with arith.\n apply Main_2 with (k 0); auto.\n intros i H15 H16.\n apply Main_2'; auto with arith.\nQed.\n(* end hide *)\n\nEnd Main_Lemma.\n", "meta": {"author": "coq-community", "repo": "corn", "sha": "cfbf6b297643935f0fe7e22d2b14b462bf7e3095", "save_path": "github-repos/coq/coq-community-corn", "path": "github-repos/coq/coq-community-corn/corn-cfbf6b297643935f0fe7e22d2b14b462bf7e3095/fta/MainLemma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.24786533211253592}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Abhishek Anand & Vincent Rahli\n\n *)\n\n\nRequire Export rules_useful.\n\n\nHint Resolve wf_term_subst : slow.\n\nLemma subset_free_vars_csub_app3 {o} :\n  forall (t : @NTerm o) sub1 sub2,\n    disjoint (remove_nvars (dom_csub sub1) (free_vars t)) (dom_csub sub2)\n    -> csubst t (sub1 ++ sub2) = csubst t sub1.\nProof.\n  unfold csubst; introv disj.\n  rw <- @csub2sub_app.\n  apply simple_lsubst_app2.\n  - introv i j k.\n    assert (cl_sub (csub2sub sub1)) as cl by eauto 3 with slow.\n    apply in_sub_eta in i; repnd.\n    pose proof (flat_map_free_vars_range_cl_sub (csub2sub sub1) cl) as h.\n    assert (LIn t0 (flat_map free_vars (range (csub2sub sub1)))) as it.\n    { rw lin_flat_map; eexists; dands; eauto. }\n    rw h in it; simpl in it; tcsp.\n  - introv i.\n    assert (prog_sub (csub2sub sub2)) as prog by eauto 3 with slow.\n    rw <- @prog_sub_eq in prog; apply prog.\n    apply in_sub_eta in i; tcsp.\n  - introv i j k.\n    allrw @dom_csub_eq.\n    pose proof (disj v) as xx.\n    rw in_remove_nvars in xx.\n    autodimp xx hyp; tcsp.\nQed.\n\nLemma lsubstc_app_weak_r {o} :\n  forall (t : @NTerm o) w x u s1 s2 c,\n    disjoint (remove_nvars [x] (free_vars t)) (dom_csub s2)\n    -> {c' : cover_vars t ((x,u) :: s1)\n        & lsubstc\n            t\n            w\n            ((x,u) :: s1 ++ s2)\n            c\n          = lsubstc t w ((x,u) :: s1) c'}.\nProof.\n  introv disj.\n\n  assert (cover_vars t ((x,u) :: s1)) as cov.\n  {\n    allrw @cover_vars_eq.\n    allrw subvars_eq.\n    introv i; applydup c in i; allsimpl; clear c.\n    allrw @dom_csub_app.\n    allrw in_app_iff.\n    repndors; tcsp.\n    apply disjoint_sym in disj.\n    apply disj in i0.\n    rw in_remove_nvars in i0; simpl in i0.\n    destruct (deq_nvar x x0); auto.\n    destruct i0; tcsp.\n  }\n\n  exists cov.\n\n  apply lsubstc_eq_if_csubst.\n  rewrite @app_comm_cons.\n  apply subset_free_vars_csub_app3; simpl.\n  introv i.\n  apply disj.\n  allrw in_remove_nvars; repnd; dands; auto.\n  allsimpl.\n  intro j; destruct i; tcsp.\nQed.\n\nLemma lsubstc_snoc_weak_r {o} :\n  forall (t : @NTerm o) w x u s y v c,\n    (x <> y -> !LIn y (free_vars t))\n    -> {c' : cover_vars t ((x,u) :: s)\n        & lsubstc\n            t\n            w\n            ((x,u) :: snoc s (y,v))\n            c\n          = lsubstc t w ((x,u) :: s) c'}.\nProof.\n  introv disj.\n\n  assert (cover_vars t ((x,u) :: s)) as cov.\n  {\n    allrw @cover_vars_eq.\n    allrw subvars_eq.\n    introv i; applydup c in i; allsimpl; clear c.\n    allrw @dom_csub_snoc; allsimpl.\n    allrw in_snoc.\n    repndors; subst; tcsp.\n    destruct (deq_nvar x y); tcsp.\n  }\n\n  exists cov.\n\n  apply lsubstc_eq_if_csubst.\n  rewrite snoc_as_append.\n  rewrite @app_comm_cons.\n  apply subset_free_vars_csub_app3; simpl.\n  introv i j; allsimpl; repndors; subst; tcsp.\n  allrw in_remove_nvars; repnd; allsimpl.\n  allrw not_over_or; repnd; tcsp.\nQed.\n\nLtac lsubstc_weak :=\n  match goal with\n  | [ |- context[lsubstc ?t ?w ((?x,?u) :: ?s1 ++ ?s2) ?c] ] =>\n    let disj := fresh \"disj\" in\n    let h    := fresh \"h\" in\n    let cov  := fresh \"cov\" in\n    assert (disjoint (remove_nvars [x] (free_vars t)) (dom_csub s2)) as disj;\n      [ auto\n      | pose proof (lsubstc_app_weak_r t w x u s1 s2 c disj) as h;\n        destruct h as [ cov h ];\n        rewrite h; clear h\n      ]\n\n  | [ |- context[lsubstc ?t ?w ((?x,?u) :: snoc ?s (?y,?v)) ?c] ] =>\n    let disj := fresh \"disj\" in\n    let h    := fresh \"h\" in\n    let cov  := fresh \"cov\" in\n    assert (x <> y -> !LIn y (free_vars t)) as disj;\n      [ auto\n      | pose proof (lsubstc_snoc_weak_r t w x u s y v c disj) as h;\n        destruct h as [ cov h ];\n        rewrite h; clear h\n      ]\n  end.\n\n(* !!MOVE *)\nLemma isprog_vars_equality {p} :\n  forall (a b c : @NTerm p) vs,\n    isprog_vars vs (mk_equality a b c)\n                <=> (isprog_vars vs a # isprog_vars vs b # isprog_vars vs c).\nProof.\n  introv.\n  repeat (rw @isprog_vars_eq; simpl).\n  autorewrite with slow.\n  allrw subvars_app_l.\n  allrw <- @wf_term_eq.\n  allrw <- @wf_equality_iff; split; sp.\nQed.\n\n(* !!MOVE *)\nLemma isprog_vars_member {p} :\n  forall (a b : @NTerm p) vs,\n    isprog_vars vs (mk_member a b)\n                <=> (isprog_vars vs a # isprog_vars vs b).\nProof.\n  introv.\n  repeat (rw @isprog_vars_eq; simpl).\n  autorewrite with slow.\n  allrw subvars_app_l.\n  allrw <- @wf_term_eq.\n  allrw <- @wf_equality_iff; split; sp.\nQed.\n\n(* !!MOVE *)\nLemma isprog_vars_iff_covered {o} :\n  forall (t : @NTerm o) (vs : list NVar),\n    isprog_vars vs t <=> (covered t vs # wf_term t).\nProof.\n  tcsp.\nQed.\n\n(* !!MOVE *)\nLemma isprog_vars_lsubst2 {o} :\n  forall (t : @NTerm o) vs sub,\n    wf_term t\n    -> (forall v u, LIn (v, u) sub -> isprog_vars vs u)\n    -> isprog_vars (vs ++ dom_sub sub) t\n    -> isprog_vars vs (lsubst t sub).\nProof.\n  introv w k1 k2.\n  allrw @isprog_vars_eq; repnd.\n  dands.\n\n  {\n    eapply subvars_eqvars;[|apply eqvars_sym; apply eqvars_free_vars_disjoint].\n    rw subvars_app_l; dands.\n\n    - rw subvars_remove_nvars; auto.\n\n    - eapply subvars_trans;[apply sub_free_vars_sub_keep_first_subvars|].\n      rw subvars_eq; introv i.\n      apply in_sub_free_vars in i; exrepnd.\n      apply k1 in i0.\n      apply isprog_vars_eq in i0; repnd.\n      rw subvars_eq in i2; apply i2 in i1; auto.\n  }\n\n  { apply nt_wf_lsubst_iff; dands; auto.\n    introv i j.\n    apply sub_find_some in j.\n    apply k1 in j; eauto 3 with slow.\n  }\nQed.\n\n(* !!MOVE *)\nLemma isprog_vars_comm {o} :\n  forall (t : @NTerm o) vs1 vs2,\n    isprog_vars (vs1 ++ vs2) t\n    -> isprog_vars (vs2 ++ vs1) t.\nProof.\n  introv isp.\n  allrw @isprog_vars_eq; repnd; dands; auto.\n  apply subvars_comm_r; auto.\nQed.\n\n(* !!MOVE *)\nLemma isprog_vars_subst2 {o} :\n  forall (t : @NTerm o) v u vs,\n    wf_term t\n    -> isprog_vars vs u\n    -> isprog_vars (v :: vs) t\n    -> isprog_vars vs (subst t v u).\nProof.\n  introv w k1 k2.\n  apply isprog_vars_lsubst2; simpl; auto.\n\n  - introv i; repndors; cpx.\n\n  - apply isprog_vars_comm; simpl; auto.\nQed.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/rules/lsubstc_weak.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.2478653321125359}}
{"text": "(* \n This is the definition of formal syntax for Dan Grossman's Thesis, \n  \"SAFE PROGRAMMING AT THE C LEVEL OF ABSTRACTION\". \n\n   Lemmas about static semantics context well formedness.\n*)\nSet Implicit Arguments.\nRequire Export LanguageModuleDef.\nRequire Export CpdtTactics.\nRequire Export TacticNotations.\nRequire Export Tacticals.\nRequire Export AlphaConversion.\nRequire Export StaticSemanticsKindingAndContextWellFormednessLemmas.\nRequire Export StaticSemanticsKindingLemmas.\n\nLemma WFU_t_implies_K_nil_A:\n  forall (t : Tau) (e : EVP.E.Var) (p : Path)  (u' : Upsilon),\n    WFU (U.ctxt (e, p) t u') -> \n    K ddot t A.\nProof.\n  destruct t; intros; try solve[inversion H; try assumption].\nQed.\n\nLemma WFU_strengthening:\n forall (u u' : Upsilon),\n   U.extends u u' = true ->\n   WFU u' ->\n   WFU u.\nProof.\n(*\n  intros u u' ext WFUu'.\n  induction WFUu'; intros; try solve[crush].\n  apply U.empty_extends_only_empty in ext; subst.\n  constructor.\n\n  apply U.extends_r_weak in ext; try assumption.\n  pose proof ext as ext'.\n  apply IHWFUu' in ext; try assumption.\n  assert (Z: WFU (U.ctxt (x, p) tau u0)).\n  constructor; try assumption.\n  apply WFU_implies_nodup in Z; try assumption.\n  (* almost but no cigar I'd say. *)\n  case_eq(U.map u (x, p)); intros.\n  admit.\n  reflexivity.\n*)\n  intros u.\n  induction u; intros; try solve[crush].\nAdmitted.\n\nLemma WFD_WFDG_implies_K_d_t_A:\n  forall d g x tau,\n    WFD d ->\n    WFDG d g ->\n    G.map g x = Some tau ->\n    K d tau A.\nProof.\n intros d g x tau WFDder WFDGder.\n induction WFDGder; intros; try solve[crush].\n unfold G.map in H1.\n fold G.map in H1.\n case_eq(G.K_eq x x0); intros; rewrite H2 in H1.\n inversion H1; subst; try assumption.\n apply IHWFDGder in WFDder; try assumption.\n inversion WFDder; subst. \n apply IHWFDGder in H0; try assumption.\n apply K_weakening with (d:= d); try assumption.\n pose proof H5 as H5'.\n apply WFD_implies_nodup in H5'.\n apply D.extends_r_str; try assumption.\n apply D.extends_refl; try assumption.\n unfold D.nodup.\n fold D.nodup.\n rewrite H3.\n assumption.\nQed.\n\nLemma WFDG_g_strengthening:\n  forall (g g' : Gamma),\n    G.extends g g' = true ->\n    forall (d : Delta), \n      WFD d ->\n      WFDG d g' ->\n      WFDG d g.\nProof.\n  (* closer no cigar. *)\n  intros g.\n  induction g; intros; try solve[crush].\n\n  pose proof H as H'.\n  apply G.extends_l_str in H.\n  apply IHg with (d:= d) in H; try assumption.\n  constructor; try assumption.\n  admit. (* H' WFDG g' should imply k is not in there. *)\n  apply WFD_WFDG_implies_K_d_t_A with (g:= (G.ctxt k t g)) (x:= k); try assumption.\n  constructor; try assumption.\n  admit.\n  admit.\n  unfold G.map.\n  fold G.map.\n  rewrite G.K.beq_t_refl.\n  reflexivity.\nAdmitted.\n\n(* by extends induction\n  intros g g'.\n  functional induction (G.extends g g'); intros; try solve[crush].\n  apply IHb with (d:= d) in H; try assumption.\n  constructor; try assumption.\n  admit. (* Stuck dang it. *)\n  apply WFD_WFDG_implies_K_d_t_A with (g:= c') (x:= k); try assumption.\n  apply G.T.beq_t_eq in e1; subst; try assumption.\n*)\n\n(* By  WFDG induction\n\n  intros d g' WFDGder g ext.\n  induction WFDGder; try solve[crush]; intros.\n\n  apply G.empty_extends_only_empty in ext.\n  subst.\n  constructor; try assumption.\n\n  apply G.extends_r_weak in ext; try assumption.\n  apply IHwfdgdg' in ext; try assumption.\n  apply WFDG_implies_nodup in wfdgdg'.\n  unfold G.nodup.\n  fold G.nodup.\n  rewrite H; try assumption.\n  admit. (* perhaps stuck. *)\n  apply IHwfdgdg' in ext.\n  constructor; try assumption.\nQed.\n\n*)\n\n\n\nLemma WFD_strengthening:\n forall (d d' : Delta),\n   WFD (d ++ d') ->\n   WFD d.\nProof.\n   intros.\n   induction d.\n  Case \"d=[]\".\n   constructor.\n  Case \"a :: d'\".\n   inversion H.\n   apply IHd in H3.\n   constructor. \n   AdmitAlphaConversion.\n   assumption.\nQed.\n\n(* used. *)\nLemma WFDG_d_strengthening:\n  forall (d d' : Delta) (g  : Gamma),\n    WFDG (d ++ d') g ->\n    WFDG d g.\nProof.\n  intros d d' g WFDGder.\n  induction WFDGder.\n  Case \"g = []\".\n   constructor.\n  Case \"[(x,tau] ++ g\".\n   constructor.\n   AdmitAlphaConversion.\n   admit. (* induction wrong, d0 instead of d. *)\n   assumption.\n   admit.\nQed.\n\nLemma WFDG_strengthening:\n  forall (d d' : Delta) (g g' : Gamma),\n    WFDG (d ++ d') (g ++ g') ->\n    WFDG d g.\nProof.\n  intros.\n  apply WFDG_d_strengthening in H.\n  apply WFDG_g_strengthening in H.\n  assumption.\nQed.\n\n(* Is this really true? *)\nLemma WFC_strengthening:\n  forall (d d': Delta) (u u' : Upsilon) (g g': Gamma),\n    WFC (d ++ d') (u ++ u') (g ++ g') ->\n    WFC d u g.\nProof.\n  intros d d' u u' g g' WFCder.\n  apply (WFC_ind\n           (fun (d : Delta) (u : Upsilon) (g : Gamma) =>\n              WFC (d ++ d') (u ++ u') (g ++ g') ->\n              WFC d u g)).\n  intros.\n  Case \"WFC d0 u0 g0\".\n   constructor; try assumption.\n  Case \"WFC d u g\".\n   inversion WFCder.\n   crush.\n   apply WFD_strengthening in H; try assumption.\n   apply WFU_strengthening in H1; try assumption.\n   apply WFDG_strengthening in H0; try assumption.\n   constructor; try assumption.\n   assumption.\nQed.\n\n(* Too much work to do it this way. *)\nLemma WFC_strengthening_right:\n  forall (d d': Delta) (u u' : Upsilon) (g g': Gamma),\n    WFC (d ++ d') (u ++ u') (g ++ g') ->\n    WFC d' u' g'.\nProof.\nAdmitted.\n\n(* This one might be true and needed. Might needs extendedbyG. \n  Heck might need both extended bys. *)\nLemma WFDG_g_weakening:\n  forall (d : Delta) (g: Gamma),\n    WFDG d g -> \n    forall (g' : Gamma),\n      WFDG d g' -> \n      WFDG d (g ++ g').\nProof.\n  intros d g WFDGder.\n  induction g.\n  Case \"g = []\".\n   intros.\n   rewrite app_nil_l.\n   assumption.\n  Case \"a :: g\".\n   intros.\n   SCase \"((x, tau) :: g) ++ g'\".\n    destruct a.\n    rewrite cons_is_append_singleton.\n    rewrite <- app_assoc.\n    constructor; try assumption.\n    AdmitAlphaConversion.\n    inversion WFDGder; try assumption.\n    crush.\n    inversion WFDGder; try assumption.\n    inversion WFDGder; try assumption.\n    inversion WFDGder; try assumption.\n    inversion WFDGder; try assumption.\n    crush.\n    (* in a loop so good sign I need to strengthen the theorem. *)\n Admitted.\n\nLemma WFDG_g_weakening_2:\n  forall (g : Gamma) (x : EVar) (t : Tau),\n    ExtendedByG g ([(x,t)] ++ g) ->\n    forall (d : Delta),\n      WFDG d g -> \n      WFDG d ([(x,t)] ++ g).\nProof.\n  (* Lost on all induction and all cases. *)\nAdmitted.\n\nLemma WFU_weakening:\n  forall (u : Upsilon),\n    WFU u ->\n    forall (u' : Upsilon),\n      WFU u' ->\n      WFU (u ++ u').\nAdmitted.\n\n", "meta": {"author": "briangmilnes", "repo": "CycloneCoqSemantics", "sha": "190c0fc57d5aebfde244efb06a119f108de7a150", "save_path": "github-repos/coq/briangmilnes-CycloneCoqSemantics", "path": "github-repos/coq/briangmilnes-CycloneCoqSemantics/CycloneCoqSemantics-190c0fc57d5aebfde244efb06a119f108de7a150/3.1/StaticSemanticsWellFormednessLemmas2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24782206554097855}}
{"text": "From stdpp Require Import prelude.\nFrom sets Require Import Ensemble.\nFrom AML Require Import Signature.\nFrom AML.Syntax Require Import Pattern.\nFrom AML.Proofs Require Import ProofSystem Theorems.\nFrom AML.Semantics Require Import Validity Tautology GlobalSemanticConsequence.\nFrom AML.Semantics Require Import StrongSemanticConsequence.\n\nSection sec_strong_soundness.\n\nContext\n  `{signature}\n  `{Set_ Pattern PatternSet}\n  .\n\nLemma strong_soundness (Γ : PatternSet) (ϕ : Pattern) :\n  Γ ⊢ₛ ϕ -> Γ ⊧ₛ ϕ.\nProof.\n  induction 1 as [| | ϕ Hax | | ? ? Hpremise].\n  - intros A e a Ha.\n    unfold PatternValuation.set_pattern_valuation,\n      PropositionalPatternValuation.set_propositional_pattern_valuation in Ha.\n    rewrite elem_of_filtered_intersection in Ha.\n    by apply Ha.\n  - by apply valid_set_strong_semantic_consequence_any,\n      tautology_valid.\n  - inversion Hax as [| | | | | ? ? ? Hx | ? ? ? Hx | ? ? Hpos Hfree | |].\n    + apply valid_set_strong_semantic_consequence_any.\n      by apply valid_evar_sub0_rename_ex.\n    + apply valid_set_strong_semantic_consequence_any.\n      pose proof (Hiff := valid_iff_app_bot_l ϕ0).\n      by apply valid_iff_alt_classic in Hiff as [].\n    + apply valid_set_strong_semantic_consequence_any.\n      pose proof (Hiff := valid_iff_app_bot_r ϕ0).\n      by apply valid_iff_alt_classic in Hiff as [].\n    + apply valid_set_strong_semantic_consequence_any.\n      pose proof (Hiff := valid_iff_app_or_l ϕ0 ψ χ).\n      by apply valid_iff_alt_classic in Hiff as [].\n    + apply valid_set_strong_semantic_consequence_any.\n      pose proof (Hiff := valid_iff_app_or_r ϕ0 ψ χ).\n      by apply valid_iff_alt_classic in Hiff as [].\n    + apply valid_set_strong_semantic_consequence_any.\n      pose proof (Hiff := valid_iff_app_ex_l x ϕ0 ψ Hx).\n      by apply valid_iff_alt_classic in Hiff as [].\n    + apply valid_set_strong_semantic_consequence_any.\n      pose proof (Hiff := valid_iff_app_ex_r x ϕ0 ψ Hx).\n      by apply valid_iff_alt_classic in Hiff as [].\n    + apply valid_set_strong_semantic_consequence_any.\n      pose proof (Hiff := valid_iff_svar_sub0_mu X ϕ0 Hpos Hfree).\n      by apply valid_iff_alt_classic in Hiff as [].\n    + apply valid_set_strong_semantic_consequence_any.\n      by apply valid_ex_x.\n    + apply valid_set_strong_semantic_consequence_any.\n      by unshelve eapply singleton_valiable_rule.\n  - inversion X; subst.\n    by apply set_strong_mp with ϕ.\n  - by inversion Hpremise.\nQed.\n\nEnd sec_strong_soundness.\n", "meta": {"author": "traiansf", "repo": "aml-in-coq", "sha": "3bb9bb35242618abf875de6082016c5d89949825", "save_path": "github-repos/coq/traiansf-aml-in-coq", "path": "github-repos/coq/traiansf-aml-in-coq/aml-in-coq-3bb9bb35242618abf875de6082016c5d89949825/theories/AML/Soundness/StrongSoundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.24782205935626178}}
{"text": "Require Import ExtLib.Core.Type.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Structures.Proper.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nGlobal Instance RelDec_eq_unit : RelDec (@eq unit) :=\n{ rel_dec := fun _ _ => true }.\nGlobal Instance RelDec_Correct_eq_unit : RelDec_Correct RelDec_eq_unit.\n  constructor. destruct x; destruct y; auto; simpl. intuition.\nQed.\n\nGlobal Instance type_unit : type unit :=\n{ equal := fun _ _ => True \n; proper := fun _ => True\n}.\n\nGlobal Instance typeOk_N : typeOk type_unit.\nProof.\n  constructor; compute; auto.\nQed.\n\nGlobal Instance proper_tt (x : unit) : proper x.\nProof.\n  exact I.\nQed.", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/coq-ext-lib/theories/Data/Unit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24782205935626175}}
{"text": "Require Import Bool.\nRequire Import RelationClasses.\nRequire Import List.\nRequire Import Program.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Loc.\n\nFrom PromisingLib Require Import Event.\n\nRequire Import Sequential.\nRequire Import SeqLib.\n\nSet Implicit Arguments.\n\n\n#[export] Hint Resolve Oracle.wf_mon: paco.\n\nLtac existT_elim1 :=\n  match goal with\n  | H: existT _ ?T1 ?v1 = existT _ ?T2 ?v2 |- _ =>\n    match T1 with\n    | T2 => apply EqdepTheory.inj_pair2 in H\n    | _ => assert (T1 = T2) by (apply EqdepFacts.eq_sigT_fst in H; ss);\n          subst T2\n    end\n  end.\n\nLtac existT_elim := repeat existT_elim1.\n\nLtac splitsH :=\n  repeat match goal with\n         | [H: ?a /\\ ?b |- _] => inv H\n         end; unnw.\n\n\n(* TODO: move to simple.v *)\n\nLemma wf_input_oracle_wf_input\n      e i\n      (WF: SeqEvent.wf_input e i):\n  Oracle.wf_input e (SeqEvent.get_oracle_input i).\nProof.\n  unfold SeqEvent.wf_input, Oracle.wf_input in *. splitsH.\n  destruct i. ss. splits.\n  - split; i; des.\n    + destruct in_access; ss. destruct p as [[[]]]. inv H0.\n      specialize (H loc t2). des. eauto.\n    + specialize (H loc v_new). des.\n      exploit H5; eauto. intros x. des. rewrite x. ss. eauto.\n  - rewrite <- H1. destruct in_acquire; ss.\n  - rewrite <- H2. destruct in_release; ss.\nQed.\n\n\n(** oracle_le *)\n\nVariant _oracle_le (oracle_le: Oracle.t -> Oracle.t -> Prop): Oracle.t -> Oracle.t -> Prop :=\n| oracle_le_intro\n    lhs rhs\n    (LE: forall e i o lhs1 (STEP: Oracle.step e i o lhs lhs1),\n      exists rhs1, (<<STEP: Oracle.step e i o rhs rhs1>>) /\\\n              (<<LE1: oracle_le lhs1 rhs1>>)):\n  _oracle_le oracle_le lhs rhs.\n\nLemma oracle_le_mon: monotone2 _oracle_le.\nProof.\n  ii. inv IN. econs. i. exploit LE0; eauto. i. des. eauto.\nQed.\n#[export] Hint Resolve oracle_le_mon: paco.\n\nDefinition oracle_le := paco2 _oracle_le bot2.\nArguments oracle_le: clear implicits.\n\nLemma oracle_le_refl orc: oracle_le orc orc.\nProof.\n  revert orc. pcofix CIH. i.\n  pfold. econs. i. esplits; eauto.\nQed.\n\nLemma oracle_le_trans\n      orc1 orc2 orc3\n      (LE1: oracle_le orc1 orc2)\n      (LE2: oracle_le orc2 orc3):\n  oracle_le orc1 orc3.\nProof.\n  revert orc1 orc2 orc3 LE1 LE2. pcofix CIH. i.\n  pfold. econs. i.\n  punfold LE1. inv LE1. punfold LE2. inv LE2.\n  exploit LE; eauto. i. des.\n  exploit LE0; eauto. i. des.\n  esplits; eauto.\n  inv LE1; try done. inv LE2; try done.\n  right. eapply CIH; eauto.\nQed.\n\nGlobal Program Instance oracle_le_PreOrder: PreOrder oracle_le.\nNext Obligation.\n  ii. revert x. pcofix CIH. i.\n  pfold. econs. i. esplits; eauto.\nQed.\nNext Obligation.\n  ii. revert x y z H H0. pcofix CIH. i.\n  pfold. econs. i.\n  punfold H0. inv H0. punfold H1. inv H1.\n  exploit LE; eauto. i. des.\n  exploit LE0; eauto. i. des.\n  esplits; eauto.\n  inv LE1; try done. inv LE2; try done.\n  right. eapply CIH; eauto.\nQed.\n\nLemma oracle_le_steps\n      lang step tr (st1: SeqState.t lang) p1 orc1 orc1' st2 p2 orc2\n      (ORACLE: oracle_le orc1 orc1')\n      (STEPS: SeqThread.steps step tr\n                              (SeqThread.mk st1 p1 orc1)\n                              (SeqThread.mk st2 p2 orc2)):\n  exists orc2',\n    SeqThread.steps step tr\n                    (SeqThread.mk st1 p1 orc1')\n                    (SeqThread.mk st2 p2 orc2').\nProof.\n  remember (SeqThread.mk st1 p1 orc1) as th1.\n  remember (SeqThread.mk st2 p2 orc2) as th2.\n  revert st1 p1 orc1 orc1' st2 p2 orc2 ORACLE Heqth1 Heqth2.\n  dependent induction STEPS; i; subst.\n  { inv Heqth2. esplits. econs 1. }\n  { inv STEP. exploit IHSTEPS; eauto. i. des.\n    esplits. econs 2; eauto. econs. ss.\n  }\n  { inv STEP. punfold ORACLE. inv ORACLE.\n    exploit LE; eauto. i. des. inv LE1; try done.\n    exploit IHSTEPS; try eapply H; eauto. intros x. des.\n    esplits. econs 3; try exact x. econs; eauto.\n  }\nQed.\n\nLemma wf_in_access_some\n      (i: option (Loc.t * Const.t * Flag.t * Const.t)) e\n      (WF: forall loc v_new,\n          ((exists v_old f_old, i = Some (loc, v_old, f_old, v_new)) <->\n             (is_accessing e = Some (loc, v_new)))):\n  i <-> is_accessing e.\nProof.\n  destruct i; ss.\n  - destruct p as [[[]]]. destruct (WF t t2).\n    exploit H; eauto. intros x. rewrite x. ss.\n  - destruct e; ss.\n    + destruct (WF loc val). exploit H0; eauto. i. des. ss.\n    + destruct (WF loc val). exploit H0; eauto. i. des. ss.\n    + destruct (WF loc valw). exploit H0; eauto. i. des. ss.\nQed.\n\nLemma oracle_wf_in_access_some\n      (i: option (Loc.t * Const.t * Flag.t)) e\n      (WF: forall loc, (exists v_old f_old, i = Some (loc, v_old, f_old)) <->\n                    (exists v_new, is_accessing e = Some (loc, v_new))):\n  i <-> is_accessing e.\nProof.\n  destruct i; ss.\n  - destruct p as [[]]. destruct (WF t).\n    exploit H; eauto. intros x. des. rewrite x. ss.\n  - destruct e; ss.\n    + destruct (WF loc). exploit H0; eauto. i. des. ss.\n    + destruct (WF loc). exploit H0; eauto. i. des. ss.\n    + destruct (WF loc). exploit H0; eauto. i. des. ss.\nQed.\n\nDefinition oracle_simple_output (i: Oracle.input): Oracle.output :=\n  let 'Oracle.mk_input acc acq rel := i in\n  Oracle.mk_output\n    (if is_some acc then Some Perm.low else None)\n    (if is_some acq then Some (fun _ => Perm.low, fun _ => Const.undef) else None)\n    (if is_some rel then Some (fun _ => Perm.low) else None).\n\nLemma oracle_simple_output_wf\n      pe i\n      (WF: Oracle.wf_input pe i):\n  Oracle.wf_output pe (oracle_simple_output i).\nProof.\n  unfold Oracle.wf_input, Oracle.wf_output in *. splitsH.\n  apply oracle_wf_in_access_some in H.\n  rewrite <- H, <- H1, <- H2.\n  destruct i. ss. splits.\n  - destruct in_access; ss.\n  - destruct in_acquire; ss.\n  - destruct in_release; ss.\nQed.\n\n\n(** dummy_oracle *)\n\nDefinition dummy_oracle_step\n           (_t: Type) (pe: ProgramEvent.t) (i: Oracle.input) (o: Oracle.output) (orc0 orc1: _t): Prop :=\n  Oracle.wf_input pe i /\\ o = oracle_simple_output i.\n\nDefinition dummy_oracle: Oracle.t := Oracle.mk (@dummy_oracle_step unit) tt.\n\nLemma dummy_oracle_wf: Oracle.wf dummy_oracle.\nProof.\n  pcofix CIH. pfold. econs; ii.\n  - inv STEP. existT_elim. subst. inv STEP0. splits; ss.\n    + apply oracle_simple_output_wf; ss.\n    + right. destruct x2. ss.\n  - exists Const.undef. split; ii.\n    + esplits; try eapply oracle_simple_output_wf; eauto.\n      econs. econs; eauto.\n    + esplits; try eapply oracle_simple_output_wf; eauto.\n      econs. econs; eauto.\n  - esplits; try eapply oracle_simple_output_wf; eauto.\n    econs. econs; eauto.\n  - esplits; try eapply oracle_simple_output_wf; eauto.\n    econs. econs; eauto.\n  - esplits; try eapply oracle_simple_output_wf; eauto.\n    econs. econs; eauto.\n    Unshelve.\n    all: ss.\nQed.\n\n\n(** oracle_of_trace *)\n\nDefinition oracle_similar_input_access (i1 i2: option (Loc.t * Const.t * Flag.t)): bool :=\n  match i1, i2 with\n  | Some (loc1, _, _), Some (loc2, _, _) => Loc.eqb loc1 loc2\n  | None, None => true\n  | _, _ => false\n  end.\n\nDefinition oracle_similar_input (i1 i2: Oracle.input): bool :=\n  andb (oracle_similar_input_access i1.(Oracle.in_access) i2.(Oracle.in_access))\n       (andb (eqb (is_some i1.(Oracle.in_acquire)) (is_some i2.(Oracle.in_acquire)))\n             (eqb (is_some i1.(Oracle.in_release)) (is_some i2.(Oracle.in_release)))).\n\nGlobal Program Instance oracle_similar_input_Equivalence: Equivalence oracle_similar_input.\nNext Obligation.\n  ii. destruct x. destruct in_access.\n  - destruct p as [[]]. unfold oracle_similar_input, oracle_similar_input_access. ss.\n    rewrite Loc.eqb_refl. destruct in_acquire, in_release; ss.\n  - destruct in_acquire, in_release; ss.\nQed.\nNext Obligation.\n  ii. destruct x, y. unfold oracle_similar_input in *. ss.\n  inv H. etrans; eauto.\n  repeat rewrite andb_true_iff in *. des. splits.\n  - destruct in_access0, in_access; ss.\n    + destruct p as [[]], p0 as [[]].\n      rewrite Loc.eqb_eq in *. congr.\n    + destruct p as [[]]. ss.\n  - destruct in_acquire, in_acquire0; ss.\n  - destruct in_release, in_release0; ss.\nQed.\nNext Obligation.\n  ii. destruct x, y, z. unfold oracle_similar_input in *. ss.\n  inv H. inv H0. etrans; eauto.\n  repeat rewrite andb_true_iff in *. des. splits.\n  - destruct in_access, in_access0, in_access1; ss.\n    + destruct p as [[]], p1 as [[]], p0 as [[]].\n      rewrite Loc.eqb_eq in *. congr.\n    + destruct p0 as [[]]. ss.\n  - destruct in_acquire, in_acquire0; ss.\n  - destruct in_release, in_release0; ss.\nQed.\n\nLemma input_match_similar\n      d0 d1 i_src i_tgt\n      (MATCH: SeqEvent.input_match d0 d1 i_src i_tgt):\n  oracle_similar_input (SeqEvent.get_oracle_input i_src) (SeqEvent.get_oracle_input i_tgt).\nProof.\n  inv MATCH. unfold oracle_similar_input in *.\n  destruct i_src, i_tgt. ss.\n  inv ACCESS; inv ACQUIRE; inv RELEASE; ss; rewrite Loc.eqb_refl; ss.\nQed.\n\nLemma input_le_similar\n      i0 i1\n      (LE: Oracle.input_le i0 i1):\n  oracle_similar_input i0 i1.\nProof.\n  destruct i0, i1.\n  unfold Oracle.input_le, oracle_similar_input in *. ss. des.\n  etrans; eauto.\n  repeat rewrite andb_true_iff. splits.\n  - destruct in_access, in_access0; ss.\n    destruct p as [[]], p0 as [[]]; ss. des. subst. apply Loc.eqb_refl.\n  - destruct in_acquire, in_acquire0; ss.\n  - destruct in_release, in_release0; ss.\nQed.\n\nLemma oracle_similar_input_loc\n      i1 i2\n      loc1 v1 f1\n      loc2 v2 f2\n      (SIMILAR: oracle_similar_input i1 i2)\n      (IN1: i1.(Oracle.in_access) = Some (loc1, v1, f1))\n      (IN2: i2.(Oracle.in_access) = Some (loc2, v2, f2)):\n  loc1 = loc2.\nProof.\n  destruct i1, i2; ss. subst.\n  unfold oracle_similar_input, oracle_similar_input_access in *. ss.\n  inv SIMILAR. apply andb_prop in H0. des.\n  rewrite Loc.eqb_eq in H0. ss.\nQed.\n\nDefinition oracle_output_of_event\n           (i: Oracle.input) (o: Oracle.output) (i_src: Oracle.input): Oracle.output :=\n  if oracle_similar_input i i_src\n  then o\n  else oracle_simple_output i_src.\n\nDefinition reading_value_of (e: ProgramEvent.t): option Const.t :=\n  match e with\n  | ProgramEvent.read _ v _\n  | ProgramEvent.update _ v _ _ _ => Some v\n  | _ => None\n  end.\n\nDefinition eq_reading_value (e1 e2: ProgramEvent.t): Prop :=\n  match reading_value_of e1, reading_value_of e2 with\n  | Some v1, Some v2 => v1 = v2\n  | _, _ => True\n  end.\n\nGlobal Program Instance eq_reading_value_Reflexive: Reflexive eq_reading_value.\nNext Obligation.\n  ii. destruct x; ss.\nQed.\n\nGlobal Program Instance eq_reading_value_Symmetric: Symmetric eq_reading_value.\nNext Obligation.\n  ii. destruct x, y; ss; inv H; ss.\nQed.\n\nVariant oracle_step_of_event (e: ProgramEvent.t) (i: Oracle.input) (o: Oracle.output) (orc: Oracle.t):\n  forall (pe: ProgramEvent.t) (i: Oracle.input) (o: Oracle.output) (orc0 orc1: option orc.(Oracle._t)), Prop :=\n| oracle_step_of_event_None\n    e' i' o'\n    (EVENT: eq_reading_value e e')\n    (INPUT: Oracle.wf_input e' i')\n    (OUT: o' = oracle_output_of_event i o i'):\n    oracle_step_of_event e i o orc e' i' o' None (Some orc.(Oracle._o))\n| oracle_step_of_event_Some\n    e' i' o' orc0 orc1\n    (STEP: orc.(Oracle._step) e' i' o' orc0 orc1):\n    oracle_step_of_event e i o orc e' i' o' (Some orc0) (Some orc1)\n.\n\nDefinition oracle_of_event\n           (e: ProgramEvent.t) (i: Oracle.input) (o: Oracle.output) (orc: Oracle.t): Oracle.t :=\n  Oracle.mk (oracle_step_of_event e i o orc) None.\n\nFixpoint oracle_of_trace_aux\n         (tr: list (ProgramEvent.t * SeqEvent.input * Oracle.output)) (orc: Oracle.t): Oracle.t :=\n  match tr with\n  | [] => orc\n  | (e, i, o) :: tr =>\n    oracle_of_event e (SeqEvent.get_oracle_input i) o (oracle_of_trace_aux tr orc)\n  end.\n\nDefinition oracle_of_trace tr orc_init := oracle_of_trace_aux tr orc_init.\n\nInductive oracle_follows_trace (orc0: Oracle.t):\n  forall (tr: list (ProgramEvent.t * SeqEvent.input * Oracle.output)) (orc: Oracle.t), Prop :=\n| oracle_follows_trace_nil\n    orc\n    (LE1: oracle_le orc orc0)\n    (LE2: oracle_le orc0 orc):\n    oracle_follows_trace orc0 [] orc\n| oracle_follows_trace_cons\n    e i o tr orc1\n    (SOUND: forall e' i' o' orc2\n              (STEP: Oracle.step e' i' o' orc1 orc2),\n        (<<EVENT: eq_reading_value e e'>>) /\\\n        (oracle_similar_input (SeqEvent.get_oracle_input i) i' ->\n         (<<OUTPUT: o' = o>>) /\\\n         (<<FOLLOWS: oracle_follows_trace orc0 tr orc2>>)))\n    (COMPLETE: forall e' i'\n                 (EVENT: eq_reading_value e e')\n                 (INPUT: oracle_similar_input (SeqEvent.get_oracle_input i) i')\n                 (WF_INPUT: Oracle.wf_input e' i'),\n        exists orc2,\n          (<<STEP: Oracle.step e' i' o orc1 orc2>>)):\n    oracle_follows_trace orc0 ((e, i, o) :: tr) orc1\n.\n\nLemma option_oracle_follows\n      orc0 tr orc e i o\n      (FOLLOWS: oracle_follows_trace orc0 tr orc):\n  oracle_follows_trace\n    orc0 tr (Oracle.mk (oracle_step_of_event e i o orc) (Some orc.(Oracle._o))).\nProof.\n  destruct orc. ss.\n  generalize _o at 1.\n  revert _o i o FOLLOWS.\n  induction tr; i.\n  { inv FOLLOWS. econs.\n    - clear LE2. revert orc0 _o _o0 LE1.\n      pcofix CIH. i. pfold. econs. i.\n      inv STEP. existT_elim. subst. inv STEP0. ss.\n      punfold LE1. inv LE1. exploit LE.\n      { econs. eauto. }\n      i. des. inv LE1; try done.\n      exploit CIH; eauto. i.\n      esplits; eauto.\n    - clear LE1. revert orc0 _o _o0 LE2.\n      pcofix CIH. i. pfold. econs. i.\n      punfold LE2. inv LE2. exploit LE; eauto. i. des.\n      inv LE1; try done.\n      inv STEP0. existT_elim. subst.\n      exploit CIH; eauto. i.\n      esplits.\n      { econs. econs. eauto. }\n      right. eauto.\n  }\n  inv FOLLOWS. econs; i.\n  - inv STEP. existT_elim. subst. inv STEP0.\n    exploit SOUND.\n    { econs; eauto. }\n    intros x. des. split; ss. i.\n    exploit x0; eauto. i. des. subst. splits; ss.\n    eapply IHtr; eauto.\n  - exploit COMPLETE; eauto. i. des. inv STEP. existT_elim. subst.\n    esplits. econs. econs. eauto.\nQed.\n\nLemma oracle_of_trace_follows tr orc_init:\n  oracle_follows_trace orc_init tr (oracle_of_trace tr orc_init).\nProof.\n  induction tr.\n  { econs; ss; apply oracle_le_refl. }\n  destruct a as [[e i] o]. econs; i.\n  - inv STEP. existT_elim. subst. inv STEP0.\n    unfold oracle_output_of_event. condtac; ss. splits; ss. i.\n    split; ss. eapply option_oracle_follows. auto.\n  - esplits. unfold oracle_of_trace. ss. econs. econs; eauto.\n    unfold oracle_output_of_event. condtac; ss.\nQed.\n\nDefinition wf_trace tr: Prop :=\n  Forall (fun x => match x with\n                | (e, i, o) => SeqEvent.wf_input e i /\\ Oracle.wf_output e o\n                end) tr.\n\nLemma oracle_similar_input_fields\n      i1 i2\n      (SIMILAR: oracle_similar_input i1 i2):\n  (i1.(Oracle.in_access) <-> i2.(Oracle.in_access)) /\\\n  (i1.(Oracle.in_acquire) <-> i2.(Oracle.in_acquire)) /\\\n  (i1.(Oracle.in_release) <-> i2.(Oracle.in_release)).\nProof.\n  destruct i1, i2. ss.\n  unfold oracle_similar_input in *. inv SIMILAR.\n  repeat rewrite andb_true_iff in *. des.\n  apply eqb_prop in H1, H2. rewrite H1, H2. splits; ss.\n  destruct in_access, in_access0; ss.\n  destruct p as [[]]. ss.\nQed.\n\nLemma oracle_output_of_event_wf\n      e i o e' i'\n      (WF_INPUT: Oracle.wf_input e i)\n      (WF_OUTPUT: Oracle.wf_output e o)\n      (WF: Oracle.wf_input e' i'):\n  Oracle.wf_output e' (oracle_output_of_event i o i').\nProof.\n  unfold oracle_output_of_event. condtac; cycle 1.\n  { apply oracle_simple_output_wf. ss. }\n  unfold Oracle.wf_input, Oracle.wf_output in *.\n  exploit oracle_similar_input_fields; eauto. i. splitsH.\n  splits; cycle 1.\n  { rewrite H7. rewrite <- H10. rewrite H1. ss. }\n  { rewrite H8. rewrite <- H11. rewrite H2. ss. }\n  apply oracle_wf_in_access_some in H0, H6.\n  rewrite H3. rewrite <- H6. rewrite H. ss.\nQed.\n\nLemma option_oracle_wf\n      orc e i o\n      (WF: Oracle.wf orc):\n  Oracle.wf (Oracle.mk (oracle_step_of_event e i o orc) (Some orc.(Oracle._o))).\nProof.\n  destruct orc. ss.\n  generalize _o at 1. revert _o WF.\n  pcofix CIH. i. punfold WF. inv WF.\n  pfold. econs; i.\n  { inv STEP. existT_elim. subst. inv STEP0. ss.\n    exploit WF0; [econs; eauto|]. i. des. splits; ss.\n    inv ORACLE; try done. right. eauto.\n  }\n  { clear - LOAD.\n    specialize (LOAD loc ord). des. exists val. split; ii.\n    - exploit LOAD; eauto. i. des.\n      inv STEP. existT_elim. subst.\n      esplits; eauto. econs. econs. eauto.\n    - exploit LOAD0; eauto. i. des.\n      inv STEP. existT_elim. subst.\n      esplits; eauto. econs. econs. eauto.\n  }\n  { clear - STORE.\n    ii. exploit STORE; eauto. i. des.\n    inv STEP. existT_elim. subst.\n    esplits; eauto. econs. econs. eauto.\n  }\n  { clear - FENCE.\n    ii. exploit FENCE; eauto. i. des.\n    inv STEP. existT_elim. subst.\n    esplits; eauto. econs. econs. eauto.\n  }\n  { clear - SYSCALL.\n    ii. exploit SYSCALL; eauto. i. des.\n    inv STEP. existT_elim. subst.\n    esplits; eauto. econs. econs. eauto.\n  }\nQed.\n\nLemma oracle_of_trace_wf\n      tr orc_init\n      (TRACE: wf_trace tr)\n      (INIT: Oracle.wf orc_init):\n  Oracle.wf (oracle_of_trace tr orc_init).\nProof.\n  revert TRACE. induction tr; i; ss.\n  destruct a as [[e i] o]. inv TRACE. des.\n  exploit IHtr; eauto. i. clear IHtr.\n  pfold. econs; i.\n  { unfold oracle_of_trace in *. ss.\n    inv STEP. existT_elim. subst. inv STEP0. splits; ss.\n    { eapply oracle_output_of_event_wf; eauto.\n      apply wf_input_oracle_wf_input; eauto.\n    }\n    left. apply option_oracle_wf. auto.\n  }\n  { destruct (reading_value_of e) as [v|] eqn:READING.\n    - exists v. split; ii.\n      + esplits.\n        * econs. econs; eauto. destruct e; ss; inv READING; ss.\n        * eapply oracle_output_of_event_wf; eauto.\n          apply wf_input_oracle_wf_input. ss.\n      + esplits.\n        * econs. econs; eauto. destruct e; ss; inv READING; ss.\n        * eapply oracle_output_of_event_wf; eauto.\n          apply wf_input_oracle_wf_input. ss.\n    - exists Const.undef. split; ii.\n      + esplits.\n        * econs. econs; eauto. destruct e; ss.\n        * eapply oracle_output_of_event_wf; eauto.\n          apply wf_input_oracle_wf_input. ss.\n      + esplits.\n        * econs. econs; eauto. destruct e; ss.\n        * eapply oracle_output_of_event_wf; eauto.\n          apply wf_input_oracle_wf_input. ss.\n  }\n  { ii. esplits.\n    - econs. econs; eauto. destruct e; ss.\n    - eapply oracle_output_of_event_wf; eauto.\n      apply wf_input_oracle_wf_input. ss.\n  }\n  { ii. esplits.\n    - econs. econs; eauto. destruct e; ss.\n    - eapply oracle_output_of_event_wf; eauto.\n      apply wf_input_oracle_wf_input. ss.\n  }\n  { ii. esplits.\n    - econs. econs; eauto. destruct e; ss.\n    - eapply oracle_output_of_event_wf; eauto.\n      apply wf_input_oracle_wf_input. ss.\n  }\nQed.\n\n\n(** add_oracle *)\n\nInductive add_oracle_t (_t: Type): Type :=\n| add_oracle_init (orc: _t)\n| add_oracle_orc (orc: _t)\n.\n\nVariant add_oracle_step (e: ProgramEvent.t) (i: Oracle.input) (o: Oracle.output)\n        (_t: Type) (step: ProgramEvent.t -> Oracle.input -> Oracle.output -> _t -> _t -> Prop):\n  forall (e: ProgramEvent.t) (i: Oracle.input) (o: Oracle.output)\n    (orc0 orc1: add_oracle_t _t), Prop :=\n| add_oracle_step_init_event\n    orc0:\n    add_oracle_step e i o step e i o (add_oracle_init orc0) (add_oracle_orc orc0)\n| add_oracle_step_init_orc\n    e' i' o' orc0 orc1\n    (STEP: step e' i' o' orc0 orc1):\n    add_oracle_step e i o step e' i' o' (add_oracle_init orc0) (add_oracle_orc orc1)\n| add_oracle_step_orc\n    e' i' o' orc0 orc1\n    (STEP: step e' i' o' orc0 orc1):\n    add_oracle_step e i o step e' i' o' (add_oracle_orc orc0) (add_oracle_orc orc1)\n.\n\nDefinition add_oracle\n           (e: ProgramEvent.t) (i: Oracle.input) (o: Oracle.output) (orc: Oracle.t): Oracle.t :=\n  Oracle.mk (add_oracle_step e i o orc.(Oracle._step)) (add_oracle_init orc.(Oracle._o)).\n\nLemma add_oracle_orc_le e i o _t step orc:\n  oracle_le (Oracle.mk (@add_oracle_step e i o _t step) (add_oracle_orc orc)) (Oracle.mk step orc).\nProof.\n  revert orc. pcofix CIH. i. pfold. econs. i.\n  inv STEP. existT_elim. subst. inv STEP0. esplits.\n  - econs. eauto.\n  - right. ss.\nQed.\n\nLemma add_oracle_spec\n      e i o orc_init\n      e' i' o' orc0 orc1\n      (ORACLE: orc0 = add_oracle e i o orc_init)\n      (STEP: Oracle.step e' i' o' orc0 orc1):\n  (e' = e /\\ i' = i /\\ o' = o /\\ oracle_le orc1 orc_init) \\/\n  (exists orc_init1,\n      (<<STEP: Oracle.step e' i' o' orc_init orc_init1>>) /\\\n      (<<LE: oracle_le orc1 orc_init1>>)).\nProof.\n  subst. inv STEP. existT_elim. subst. inv STEP0.\n  - left. splits; ss.\n    destruct orc_init. ss. eapply add_oracle_orc_le; eauto.\n  - right. destruct orc_init. ss. esplits.\n    + econs. eauto.\n    + eapply add_oracle_orc_le; eauto.\nQed.\n\nLemma add_oracle_init_progress\n      e i o _t step orc\n      e'\n      (PROGRESS: Oracle.progress e' (Oracle.mk step orc)):\n  Oracle.progress e' (Oracle.mk (@add_oracle_step e i o _t step) (add_oracle_init orc)).\nProof.\n  unfold Oracle.progress in *. i.\n  exploit PROGRESS; eauto. i. des.\n  inv STEP. existT_elim. subst.\n  esplits; eauto. econs. econs. eauto.\nQed.\n\nLemma add_oracle_orc_progress\n      e i o _t step orc\n      e'\n      (PROGRESS: Oracle.progress e' (Oracle.mk step orc)):\n  Oracle.progress e' (Oracle.mk (@add_oracle_step e i o _t step) (add_oracle_orc orc)).\nProof.\n  unfold Oracle.progress in *. i.\n  exploit PROGRESS; eauto. i. des.\n  inv STEP. existT_elim. subst.\n  esplits; eauto. econs. econs. eauto.\nQed.\n\nLemma add_oracle_orc_wf\n      e i o _t step orc\n      (WF: Oracle.wf (Oracle.mk step orc)):\n  Oracle.wf (Oracle.mk (@add_oracle_step e i o _t step) (add_oracle_orc orc)).\nProof.\n  revert orc WF. pcofix CIH. i.\n  punfold WF. inv WF.\n  pfold. econs; i; eauto using add_oracle_orc_progress.\n  - inv STEP. existT_elim. subst. inv STEP0.\n    exploit WF0; [econs; eauto|]. i. des.\n    inv ORACLE; try done. splits; auto.\n  - specialize (LOAD loc ord). des. exists val.\n    split; i; apply add_oracle_orc_progress; ss.\nQed.\n\nLemma add_oracle_wf\n      e i o orc_init\n      (WF_INPUT: Oracle.wf_input e i)\n      (WF_OUTPUT: Oracle.wf_output e o)\n      (WF: Oracle.wf orc_init):\n  Oracle.wf (add_oracle e i o orc_init).\nProof.\n  destruct orc_init.\n  dup WF. punfold WF. inv WF.\n  pfold. econs; i; eauto using add_oracle_init_progress.\n  { inv STEP. existT_elim. subst. inv STEP0.\n    - splits; auto. left. apply add_oracle_orc_wf. ss.\n    - exploit WF1; [econs; eauto|]. i. des.\n      inv ORACLE; try done. splits; ss.\n      left. eapply add_oracle_orc_wf. ss.\n  }\n  { specialize (LOAD loc ord). des. exists val.\n    split; i; eapply add_oracle_init_progress; ss.\n  }\nQed.\n\nLemma nil_steps_any_oracle\n      lang step st1 p1 orc1 st2 p2 orc2 orc\n      (STEPS: SeqThread.steps step [] (@SeqThread.mk lang st1 p1 orc1) (SeqThread.mk st2 p2 orc2)):\n  orc1 = orc2 /\\\n  SeqThread.steps step [] (SeqThread.mk st1 p1 orc) (SeqThread.mk st2 p2 orc).\nProof.\n  dependent induction STEPS; ss.\n  - split; ss. econs.\n  - destruct th1.\n    exploit IHSTEPS; eauto. i. des.\n    inv STEP. splits; ss.\n    econs 2; eauto. econs. ss.\nQed.\n\nLemma steps_cons_inv\n      lang step e i o tr st1 p1 orc1 th4\n      (STEPS: SeqThread.steps step ((e, i, o) :: tr)\n                              (@SeqThread.mk lang st1 p1 orc1) th4):\n  exists st2 th3,\n    (<<NASTEPS: SeqThread.steps step [] (SeqThread.mk st1 p1 orc1) (SeqThread.mk st2 p1 orc1)>>) /\\\n    (<<ATSTEP: SeqThread.at_step e i o (SeqThread.mk st2 p1 orc1) th3>>) /\\\n    (<<STEPS: SeqThread.steps step tr th3 th4>>).\nProof.\n  dependent induction STEPS; ss.\n  - destruct th1. inv STEP.\n    exploit IHSTEPS; eauto. i. des.\n    esplits; eauto. econs 2; eauto. econs. ss.\n  - esplits; eauto. econs 1.\nQed.\n\nLemma steps_app\n      lang step tr1 tr2 (th1 th2 th3: SeqThread.t lang)\n      (STEPS1: SeqThread.steps step tr1 th1 th2)\n      (STEPS2: SeqThread.steps step tr2 th2 th3):\n  SeqThread.steps step (tr1 ++ tr2) th1 th3.\nProof.\n  induction STEPS1; ss.\n  - econs 2; eauto.\n  - econs 3; eauto.\nQed.\n\nLemma add_oracle_steps_inv\n      lang step e i o orc tr st1 p1 orc1 st2 p2 orc2\n      (ORACLE: oracle_le orc1 (add_oracle e i o orc))\n      (STEPS: SeqThread.steps step tr\n                              (@SeqThread.mk lang st1 p1 orc1)\n                              (SeqThread.mk st2 p2 orc2)):\n  (exists orc2',\n      SeqThread.steps step tr\n                      (SeqThread.mk st1 p1 orc)\n                      (SeqThread.mk st2 p2 orc2')) \\/\n  (exists e' i' o' tr',\n      (<<TRACE: tr = (e', i', o') :: tr'>>) /\\\n      (<<EVENT: ProgramEvent.le e e'>>) /\\\n      (<<INPUT: Oracle.input_le i (SeqEvent.get_oracle_input i')>>) /\\\n      (<<OUTPUT: o' = o>>)).\nProof.\n  destruct tr.\n  { left. exploit nil_steps_any_oracle; eauto. i. des. esplits; eauto. }\n  destruct p as [[e' i'] o'].\n  exploit steps_cons_inv; eauto. i. des. clear STEPS.\n  inv ATSTEP.\n  punfold ORACLE. inv ORACLE. exploit LE; eauto. i. des. inv LE1; ss.\n  exploit add_oracle_spec; eauto. i. des; subst.\n  { right. esplits; eauto. }\n  left.\n  exploit oracle_le_steps; try exact STEPS0.\n  { eapply oracle_le_trans; eauto. }\n  i. des. exists orc2'.\n  replace ((e', i', o') :: tr) with ([] ++ (e', i', o') :: tr).\n  eapply steps_app.\n  { eapply nil_steps_any_oracle; eauto. }\n  econs 3; eauto; ss.\n  econs; eauto. ss.\nQed.\n\nDefinition oracle_input_of_event (e: ProgramEvent.t) (m: SeqMemory.t): Oracle.input :=\n  Oracle.mk_input\n    (match is_accessing e with\n     | Some (loc, _) => Some (loc, m.(SeqMemory.value_map) loc, m.(SeqMemory.flags) loc)\n     | None => None\n     end)\n    (if is_acquire e then Some () else None)\n    (if is_release e then Some () else None)\n.\n\nLemma oracle_input_of_event_wf e m:\n  Oracle.wf_input e (oracle_input_of_event e m).\nProof.\n  unfold Oracle.wf_input. splits; ss; try by des_ifs.\n  ss. des_ifs; split; i; des; inv H; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/sequential/OracleFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371502, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2478220531715449}}
{"text": "Require Export sem_lab.\nRequire Export absop_rules.\nImport os_ucos_h.\n\nOpen Scope code_scope.\n\nLemma sem_H_get_none:\n  forall els eid,\n    EcbMod.get els eid = None ->\n    ~(exists n wls, EcbMod.get els eid = Some (abssem n, wls)).\n  intros.\n  unfold not.\n  intros.\n  destruct H0.\n  destruct H0.\n  rewrite H in H0.\n  tryfalse.\nQed.\n\nLtac mytac :=\n  heat; jeauto2.\n  \nLemma eventsearch_after_get_H:\n  forall p ectrl1 a b ectrl2 msgqls1 msgq msgqls2 mqls tcbls  qid mqls1 mqls' mq mqls2,\n    length ectrl1 = length msgqls1 ->\n    ECBList_P p Vnull \n              (ectrl1 ++ ((a,b)::nil) ++ ectrl2)\n              (msgqls1 ++ (msgq::nil) ++ msgqls2)\n              mqls tcbls ->\n    ECBList_P p (Vptr qid) ectrl1 msgqls1 mqls1 tcbls ->\n    EcbMod.join mqls1 mqls' mqls ->\n    EcbMod.joinsig qid mq mqls2 mqls' ->\n    EcbMod.get mqls qid = Some mq.\n  intros.\n  apply ecblist_p_decompose in H0; auto.\n  mytac.\n  \n  assert (x1 = Vptr qid /\\ x = mqls1).\n    eapply ecblist_p_eqh with (ecbls:=mqls); eauto.\n    EcbMod.solve_map.\n    EcbMod.solve_map.\n\n  mytac.\n  lets Hx:EcbMod.join_joinsig_get H2 H3.\n  auto.\nQed.\n\nLemma semacc_eventtype_neq_sem:\n  forall s P p ectrl1 a b ectrl2 msgqls1 msgq msgqls2 mqls tcbls  qid mqls1 mqls' mq mqls2 t,\n    s |= AEventData a msgq ** P ->\n    RLH_ECBData_P msgq mq ->\n    length ectrl1 = length msgqls1 ->\n    ECBList_P p Vnull \n              (ectrl1 ++ ((a,b)::nil) ++ ectrl2)\n              (msgqls1 ++ (msgq::nil) ++ msgqls2)\n              mqls tcbls ->\n    ECBList_P p (Vptr qid) ectrl1 msgqls1 mqls1 tcbls ->\n    EcbMod.join mqls1 mqls' mqls ->\n    EcbMod.joinsig qid mq mqls2 mqls' ->\n    V_OSEventType a = Some (Vint32 t) ->\n    Int.eq t ($ OS_EVENT_TYPE_SEM) = false ->\n    s |= AEventData a msgq ** \n         [| ~ exists n wls, EcbMod.get mqls qid = Some (abssem n, wls)|] ** P.\n  intros.\n  assert (EcbMod.get mqls qid = Some mq).\n    eapply eventsearch_after_get_H; eauto.\n  \n  unfold AEventData in *.\n  destruct msgq eqn:Hmsgq.\n  sep split in H.\n  sep auto.\n  unfold RLH_ECBData_P in H0.\n  destruct mq; destruct e eqn:Hmq; tryfalse.\n  unfold not; intros; mytac; tryfalse.\n  \n  sep split in H.\n  rewrite H9 in H6.\n  inverts H6.\n  rewrite Int.eq_true in H7.\n  tryfalse.\n\n  sep split in H.\n  sep auto.\n  unfold RLH_ECBData_P in H0.\n  destruct mq; destruct e eqn:Hmq; tryfalse.\n  unfold not; intros; mytac; tryfalse.\n\n  sep split in H.\n  sep auto.\n  unfold RLH_ECBData_P in H0.\n  destruct mq; destruct e eqn:Hmq; tryfalse.\n  unfold not; intros; mytac; tryfalse.\nQed.\n\nLemma semacc_triangle_sem:\n  forall s P a msgq mq n,\n    s |= AEventData a msgq ** P ->\n    RLH_ECBData_P msgq mq ->\n    V_OSEventType a = Some (V$OS_EVENT_TYPE_SEM) ->\n    V_OSEventCnt a = Some (Vint32 n) ->\n    s |= AEventData a msgq ** \n         [| exists wls, msgq = DSem n /\\ mq = (abssem n, wls) |] ** P.\n  intros.\n  sep pauto.\n  unfold AEventData in *.\n  destruct msgq eqn:Hmsgq; sep split in H. \n  rewrite H1 in H4; tryfalse.\n\n  unfold RLH_ECBData_P in H0.\n  destruct mq; destruct e eqn:Hmq; tryfalse.\n  rewrite H2 in H4. inverts H4.\n  inverts H0.\n  exists w.\n  auto.\n\n  rewrite H1 in H3; tryfalse.\n  \n  rewrite H1 in H3; tryfalse.\nQed.  \n\nLemma semacc_ltu_trans: \n  forall x y,\n    Int.ltu Int.zero x = true ->\n    Int.ltu x y = true ->\n    Int.ltu (Int.sub x Int.one) y = true.\n  int auto.\n  int auto.\nQed.\n\nLemma semacc_compose_EcbList_P:\n  forall p qid a b tcbls i n x2 x3 vn msgq mq ectrl1 msgqls1 mqls1 ectrl2 msgqls2 mqls2 mqls' mqls,\n    R_ECB_ETbl_P qid (a,b) tcbls ->\n    a = (V$OS_EVENT_TYPE_SEM :: Vint32 i :: Vint32 n :: x2 :: x3 :: vn :: nil) ->\n    RLH_ECBData_P msgq mq ->\n    ECBList_P p (Vptr qid) ectrl1 msgqls1 mqls1 tcbls ->\n    ECBList_P vn Vnull ectrl2 msgqls2 mqls2 tcbls ->\n    EcbMod.joinsig qid mq mqls2 mqls' ->\n    EcbMod.join mqls1 mqls' mqls ->\n    ECBList_P p Vnull (ectrl1 ++ ((a,b)::nil) ++ ectrl2) \n              (msgqls1 ++ (msgq::nil) ++ msgqls2)\n              mqls tcbls.\n  intros.\n  subst.\n  eapply ecblist_p_compose; eauto.\n  simpl.\n  eexists; splits; eauto.\n  do 3 eexists; splits; eauto.\n  unfolds; simpl; auto.\nQed.\n\n(************************************** from post *****************************)\n\nLemma sem_eventtype_neq_sem:\n   forall s P a msgq mq t,\n    s |= AEventData a msgq ** P ->\n    RLH_ECBData_P msgq mq ->\n    V_OSEventType a = Some (Vint32 t) ->\n    Int.eq t ($ OS_EVENT_TYPE_SEM) = false ->\n    s |= AEventData a msgq **\n         [| (~ exists n wls, mq = (abssem n, wls)) |] ** P.\n  intros.\n\n  unfold AEventData in *.\n  destruct msgq eqn:Hmsgq.\n  sep split in H.\n  sep auto.\n  unfold RLH_ECBData_P in H0.\n  destruct mq; destruct e eqn:Hmq; tryfalse.\n  unfold not; intros; mytac; tryfalse.\n  \n  sep split in H.\n  rewrite H3 in H1.\n  inverts H1.\n  rewrite Int.eq_true in H2.\n  tryfalse.\n\n  sep split in H.\n  sep auto.\n  unfold RLH_ECBData_P in H0.\n  destruct mq; destruct e eqn:Hmq; tryfalse.\n  unfold not; intros; mytac; tryfalse.\n\n  sep split in H.\n  sep auto.\n  unfold RLH_ECBData_P in H0.\n  destruct mq; destruct e eqn:Hmq; tryfalse.\n  unfold not; intros; mytac; tryfalse.\nQed.\n\nLemma  Mutex_owner_set: forall x y z t, (~exists aa bb cc, t = (absmutexsem aa bb, cc))->   RH_TCBList_ECBList_MUTEX_OWNER x y ->  RH_TCBList_ECBList_MUTEX_OWNER (EcbMod.set x z t) y.\nProof.\n    intros.\n    unfold RH_TCBList_ECBList_MUTEX_OWNER in *.\n    intros.\n    assert ( eid = z \\/ eid <> z).\n    tauto.\n    elim H2; intros.\n    subst eid.\n    rewrite EcbMod.set_a_get_a in H1.\n    inverts H1.\n    false.\n    apply H.\n    eauto.\n    go.\n\n    rewrite EcbMod.set_a_get_a' in H1.\n    eapply H0; eauto.\n    go.\nQed.\n  \nLemma  Mutex_owner_hold_for_set_tcb: forall x y pcur a b c,  RH_TCBList_ECBList_MUTEX_OWNER x y ->  RH_TCBList_ECBList_MUTEX_OWNER x (TcbMod.set y pcur (a, b, c)).\nProof.\n    intros.\n    unfold   RH_TCBList_ECBList_MUTEX_OWNER  in *.\n    intros.\n    assert ( pcur = tid  \\/ pcur <> tid ) by tauto.\n    elim H1; intros.\n    subst pcur.\n    rewrite TcbMod.set_a_get_a; auto.\n    eauto.\n    go.\n    rewrite TcbMod.set_a_get_a'; auto.\n    eapply H; eauto.\n    go.\nQed.\n\n\nDefinition semcre_RL_Tbl_init_prop:\n  RL_Tbl_Grp_P INIT_EVENT_TBL (Vint32 Int.zero).\nProof.\n  unfolds.\n  intros.\n  splits.\n  intros.\n  inverts H1.\n  split.\n  simpl in H0.\n  intros.\n  destruct H.\n  lets Hex : nat8_des H2 H0.\n  auto.\n  intros.\n  rewrite Int.and_zero_l.\n  auto.\n  inverts H1.\n  split.\n  rewrite Int.and_zero_l.\n  intros.\n  apply leftmoven in H.\n  unfold Int.zero in H1.\n  tryfalse.\n  simpl in H0.\n  lets Hesx : nat8_des H H0.\n  intros.\n  unfold Int.zero in Hesx.\n  int auto.\n  remember (zlt 0 (Int.unsigned v)) as Hb.\n  destruct Hb; \n  tryfalse.\n  assert (Int.unsigned v = 0).\n  subst v.\n  apply unsigned_zero.\n  omega.\nQed.\n\nLemma semcre_ECBList_P:\n  forall mqls tcbls ct sid ecbls p l i v1,\n    RH_TCBList_ECBList_P mqls tcbls ct ->\n    get mqls sid = None ->\n    ECBList_P p Vnull l ecbls mqls tcbls ->\n    ECBList_P (Vptr sid) Vnull\n              ((V$OS_EVENT_TYPE_SEM\n                 :: Vint32 Int.zero :: Vint32 i :: Vnull :: v1 :: p :: nil,\n                INIT_EVENT_TBL) :: l) (DSem i :: ecbls)\n               (set mqls sid (abssem i, nil))\n               tcbls.\nProof.\n  intros.\n  unfolds.\n  fold ECBList_P.\n  eexists.\n  split; eauto.\n  split.\n  unfolds.\n  split.\n  unfolds.\n  destruct H as (Ha1 & Ha2 & Ha3 & Ha4).\n  splits.\n  unfolds.\n  intros.\n  usimpl H2.\n\n  unfolds.\n  intros.\n  unfolds in H.\n  mytac.\n  simpl in H5.\n  lets Hres : prio_prop  H H7; eauto.\n  assert (∘(Int.unsigned (Int.shru ($ prio) ($ 3))) < 8)%nat.\n  eapply Z_le_nat; eauto.\n  split; auto.\n  apply Int.unsigned_range_2.\n  remember (∘(Int.unsigned (Int.shru ($ prio) ($ 3)))) as  Heq.\n  assert (x1=Int.zero) by (eapply nat8_des;eauto).\n  subst x1.\n  apply int_land_zero in H6; tryfalse.\n\n  unfolds.\n  intros.\n  usimpl H2.\n\n  unfolds.\n  intros.\n  usimpl H2.\n\n  destruct H as (Ha1 & Ha2 & Ha3 & Ha4).\n  split.\n  unfolds.\n  splits.\n  unfolds.\n  intros.\n  destruct Ha1 as (Hab & Hac).\n  lets Hre : Hac H.\n  destruct Hre as (xx & yy & wt & Hec & Hin).\n  change ((fun x => x = None) (get mqls sid)) in H0.\n  rewrite Hec in H0.\n  tryfalse.\n\n  unfolds.\n  intros.\n  destruct Ha2 as (Hab & Hac).\n  lets Hre : Hac H.\n  destruct Hre as (xx  & wt & Hec & Hin).\n  change ((fun x => x = None) (get mqls sid)) in H0.\n  rewrite Hec in H0.\n  tryfalse.\n\n  unfolds.\n  intros.\n  destruct Ha3 as (Hab & Hac).\n  lets Hre : Hac H.\n  destruct Hre as (xx  & wt & Hec & Hin).\n  change ((fun x => x = None) (get mqls sid)) in H0.\n  rewrite Hec in H0.\n  tryfalse.\n\n  unfolds.\n  intros.\n  destruct Ha4 as (Hab & Hac).\n  apply Hac in H.\n  destruct H as (n1 & n2  & wt & Hec & Hed).\n  change ((fun x => x = None) (get mqls sid)) in H0.\n  rewrite Hec in H0.\n  tryfalse.\n\n  unfolds.\n  branch 2.\n  simpl;auto.\n  do 3 eexists.\n  unfold V_OSEventListPtr.\n  simpl nth_val .\n  splits; eauto.\n  instantiate (1:= (abssem i, nil)).\n  eapply ecbmod_get_sig_set; eauto.\n  unfolds.\n  splits.\n  auto.\n  unfolds.\n  split; intros; [reflexivity | tryfalse].\nQed.\n\nLtac tryfalse' :=\n  repeat match goal with\n           | H1: get ?x ?t = None, H2: get ?x ?t = Some _ |- _ =>\n             change ((fun y => y = None) (get x t)) in H1;\n             rewrite H2 in H1\n           | H1: get ?x ?t = Some ?v1, H2: get ?x ?t = Some ?v2 |- _ =>\n             change ((fun y => y = Some v1) (get x t)) in H1;\n             rewrite H2 in H1\n         end;\n  tryfalse.\n                                          \nLemma semcre_RH_TCBList_ECBList_P:\n  forall v'37 x i v'38 v'40,\n    get v'37 x = None ->\n    RH_TCBList_ECBList_P v'37 v'38 v'40 ->\n    RH_TCBList_ECBList_P\n      (set v'37 x (abssem i, nil))\n      v'38 v'40.\nProof.\n  intros.\n  unfolds.\n  unfolds in H0.\n  destruct H0 as (Ha1 & Ha2 & Ha3 & Ha4).\n  split.\n\n  destruct Ha1.\n  unfolds.\n  split.\n  intros.\n  rewrite set_sem in H2.\n  destruct (dec x eid).\n  destruct H2.\n  inverts H2.\n  lets Hres : H0 H2.\n  eauto.\n  intros.\n  lets Hres : H1 H2.\n  mytac.\n  assert (eid = x \\/ eid <> x) by tauto.\n  destruct H5.\n  subst.\n  tryfalse'.\n  rewrite set_sem.\n  destruct (dec x eid); tryfalse.\n  destruct (dec x x); tryfalse.\n  eauto.\n  \n  split.\n  destruct Ha2.\n  unfolds.\n  split.\n  intros.\n  rewrite set_sem in H2.\n  destruct (dec x eid).\n  destruct H2.\n  inverts H2.\n  simpl in H3; tryfalse.\n  eapply H0; eauto.\n  intros.\n  rewrite set_sem.\n  lets Hres : H1 H2.\n  destruct Hres as (n&wls& Hec & Hin).\n  remember (dec x eid) as Hbool.\n  destruct Hbool.\n  apply eq_sym in HeqHbool.\n  subst x.\n  tryfalse'.\n  do 2 eexists; splits; eauto.\n\n  split.\n  destruct Ha3.\n  unfolds.\n  split.\n  intros.\n  rewrite set_sem in H2.\n  destruct (dec x eid).\n  destruct H2.\n  inverts H2.\n  lets Hres : H0 H2.\n  eauto.\n  intros.\n  lets Hres : H1 H2.\n  mytac.\n  assert (eid = x \\/ eid <> x) by tauto.\n  destruct H5.\n  subst.\n  tryfalse'.\n  rewrite set_sem.\n  destruct (dec x eid); tryfalse.\n  eauto.\n\n  destruct Ha4.\n  unfolds.\n  split.\n  intros.\n  rewrite set_sem in H2.\n  destruct (dec x eid).\n  destruct H2.\n  inverts H2.\n  lets Hres : H0 H2.\n  eauto.\n\n  split; intros.\n\n  destruct H1 as (H1 & H1').\n  lets Hres : H1 H2.\n  mytac.\n  assert (eid = x \\/ eid <> x) by tauto.\n  destruct H5.\n  subst.\n  tryfalse'.\n  rewrite set_sem.\n  destruct (dec x eid); tryfalse; eauto.\n  \n  destruct H1 as (H1 & H1').\n  eapply Mutex_owner_set.\n  unfold not.\n  intros.\n  mytac.\n  tryfalse'.\n  auto.\nQed.\n\n(** move to join_lib **)\nLemma map_join_get_none':\n  forall (A B T : Type) (PermMap : PermMap A B T) \n    (x y z : T) (t : A) v,\n    join x y z ->\n    get x t = None ->\n    get y t = v ->\n    get z t = v.\n  intros.\n  assert (get z t = get y t) by jeauto2.\n  subst.\n  auto.\nQed.\n\nLemma semcre_ecblist_star_not_inh :\n    forall v'28 v'24  eid  v'27 v'37 v'38 s vl P,\n      ECBList_P v'24 Vnull v'28 v'27 v'37 v'38 ->\n      s |= Astruct eid OS_EVENT vl  **\n        evsllseg v'24 Vnull v'28 v'27  ** P ->\n      get v'37 eid = None.\nProof.\n  inductions v'28;intros.\n  simpl in H; mytac.\n  unfold ECBList_P in H.\n  fold ECBList_P in H.\n  mytac.\n  destruct v'27.\n  tryfalse.\n  destruct a.\n  mytac.\n  unfold evsllseg in H0.\n  fold evsllseg in H0.\n  sep normal in H0.\n  sep destruct H0.\n  sep split in H0.\n  rewrite H in H5.\n  inverts H5.\n  sep lower 2%nat in H0. \n  sep lower 3%nat in H0.\n  sep lower 1%nat in H0.\n  lets Hrs : IHv'28 H4 H0.\n  unfold AEventNode in H0.\n  unfold AOSEvent in H0.\n  unfold node in H0.\n  sep normal in H0.\n  sep destruct H0.\n  sep split in H0.\n  mytac.\n  inverts H5.\n  sep lift 3%nat in H0.\n  lets Hs : astruct_neq_ptr H0.\n  intro Hf.\n  unfolds in Hf.\n  destruct Hf as [Hx | Hf].\n  mytac.\n  tryfalse.\n  destruct Hf.\n  mytac.\n  tryfalse.\n  tryfalse.\n  intro Hf.\n  unfolds in Hf.\n  destruct Hf as [Hx | Hf].\n  mytac.\n  tryfalse.\n  destruct Hf.\n  mytac.\n  tryfalse.\n  tryfalse.\n  unfold TcbJoin in H2.\n  eapply map_join_get_none'; jeauto2.\nQed.  \n  \nLemma sempend_ltu_ass1:\n  forall x, Int.ltu x x = false.\n  int auto.\nQed.\n\nLemma sempend_ltu_ass2:\n  Int.ltu Int.zero Int.one = true.\n  int auto.\nQed.\n\nLemma join_prop2_my':\n  forall m1 m2 m12 b1 prio st msg m3 ma3 m4 msg',\n    join m1 m2 m12 ->\n    TcbJoin (b1, Int.zero) (prio, st, msg) m3 ma3 ->\n    join m4 ma3 m2 ->\n    join m1 \n         (set m2 (b1, Int.zero) (prio, rdy, msg'))\n         (set m12 (b1, Int.zero) (prio, rdy, msg')).\nProof.\n  unfold TcbJoin.\n  intros.\n  eapply my_join_sig_abc.\n  unfold usePerm; simpl; auto.\n  eapply H1.\n  trivial.\n  unfold joinsig.\n  eapply H0.\nQed.\n\nLemma statsem_and_not_statsem_eq_rdy : Int.eq ($ OS_STAT_SEM&ᵢInt.not ($ OS_STAT_SEM)) ($ OS_STAT_RDY) = true.\nProof.\n  unfold OS_STAT_SEM, OS_STAT_RDY.\n  unfold Int.not.\n  unfold Int.xor.\n  unfold Z.lxor.\n  int auto.\n  compute.\n  split; intros; tryfalse.\n  int auto.\n  compute.\n  intro; tryfalse.\n  compute.\n  intro; tryfalse.\n  compute.\n  split; intros; tryfalse.\nQed.\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/ucos_lib/sem_common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24781621564305223}}
{"text": "Require Import Coqlib.\nRequire Import Asm.\nRequire Import Integers.\nRequire Import PeekTactics.\nRequire Import PeepsLib.\nRequire Import PregTactics.\nRequire Import StepIn.\nRequire Import AsmBits.\nRequire Import Values.\nRequire Import ValEq.\nRequire Import Integers.\nRequire Import PeepsTactics.\n\n(*TODO: Replace with newer version*)\nLtac prep_r :=\n  T0 _destruct state_bits;      \n    NP0 app_new step_fwd_exec step_fwd; eauto;    \n  repeat break_and;      \n  P0 _clear step_through;\n  P0 _clear step_fwd;\n  P0 _clear current_fn;\n  NP app_new mem_eq_match_metadata_r MemEq.mem_eq.\n\nLtac step_l :=\n    NP1 app_new step_through_current_instr step_through;\n    NP1 app_new step_through_current_fn step_through; [ | simpl; eauto ];\n    (step_l_str || step_l_jmp);\n    break_and; compute_skipz; P1 _simpl step_through; try break_and;\n    NP1 app_new step_fwd_transf_block step_fwd.\n\n(*\nmovl  %eax, %ecx\nleal  -1(%ecx), %eax\ntestl %ecx, %ecx\n=>\ntestl %eax, %eax\nleal  -1(%eax), %eax\n*)\nDefinition neg_one := (Int.repr (-1)).\nDefinition peep_test_then_lea_example :=\n  Pmov_rr ECX EAX ::\n  Plea EAX (Addrmode (Some ECX) None (inl neg_one)) ::\n  Ptest_rr ECX ECX ::\n  nil.\n\nSection TEST_THEN_LEA.\n\n  Variable concrete : code.\n  Variable r1 r2 : ireg.\n  Hypothesis r1_r2_neq : r1 <> r2.\n  \n  Definition peep_test_then_lea_defs : rewrite_defs :=\n    {|\n      fnd :=\n        Pmov_rr r2 r1 ::\n                Plea r1 (Addrmode (Some r2) None (inl neg_one)) ::\n                Ptest_rr r2 r2 ::\n                nil\n      ; rpl :=\n        Ptest_rr r1 r1 ::\n                 Plea r1 (Addrmode (Some r1) None (inl neg_one)) ::\n                 Pnop ::\n                 nil\n      ; lv_in := PC :: IR r1 :: nil\n      ; lv_out := PC :: IR r1 :: flags\n      ; clobbered := IR r2 :: nil\n    |}.\n\n    Lemma peep_test_then_lea_selr :\n    StepEquiv.step_through_equiv_live (fnd peep_test_then_lea_defs) (rpl peep_test_then_lea_defs) (lv_in peep_test_then_lea_defs) (lv_out peep_test_then_lea_defs).\n  Proof.\n    prep_l.\n    step_l.\n    step_l.\n    step_l.\n    prep_r.\n    step_r.\n    step_r.\n    step_r.\n    finish_r.\n    prep_eq.\n    split.\n    2: eq_mem_tac.\n    intros.\n    P0 _clear current_block.\n    P0 _clear MemoryAxioms.match_metadata.\n    P0 _clear no_ptr_mem.\n    P0 _clear no_ptr_regs.\n    break_or.\n    repeat find_rewrite_goal.\n    simpl.\n    repeat (simpl_exec; try break_match; try congruence);      \n            repeat (state_inv); try opt_inv; preg_simpl.\n    unfold Val.add.\n    simpl.\n    repeat find_rewrite_goal.\n    f_equal.    \n    break_or.\n    repeat (simpl_and_clear; try break_match; try congruence);      \n            repeat (state_inv); try opt_inv; preg_simpl.\n    unfold Val.add.    \n    subst m0 m1 a1 a0 m.\n    clear_taut.    \n    subst r0.\n    preg_simpl.\n    unfold Val.add.\n    subst.\n    preg_simpl.\n    break_match_sm; simpl; intros;\n    try break_match; try congruence.\n    f_equal.\n    P0 _simpl val_eq.\n    inv_vint.\n    f_equal.\n    P0 _simpl val_eq.\n    assumption.    \n\n    simpl_and_clear.\n    \n    assert (In reg flags) by (simpl; auto).    \n\n    repeat rewrite nextinstr_flags by assumption.\n    rewrite Pregmap.gso.\n    repeat rewrite nextinstr_flags by assumption.\n    \n    eapply val_eq_compare_ints; eauto.\n    eapply val_eq_and; eauto.\n    3: simpl; auto.\n    subst_max.\n    preg_simpl.\n    assumption.\n    subst_max.\n    preg_simpl.\n    assumption.\n    subst m m1 m0.\n    eauto.\n    simpl in *.\n    repeat break_or_reg; congruence.    \n  Qed.\n\n  Definition peep_test_then_lea_proofs : rewrite_proofs :=\n    {|\n      defs := peep_test_then_lea_defs\n      ; selr := peep_test_then_lea_selr\n    |}.\n\n  Definition peep_test_then_lea : \n    concrete = fnd peep_test_then_lea_defs ->\n    StepEquiv.rewrite.\n  Proof.\n    intros.\n    peep_tac_mk_rewrite peep_test_then_lea_defs peep_test_then_lea_proofs.\n  Qed.\n\nEnd TEST_THEN_LEA.\n\nDefinition peep_test_then_lea_rewrite (c : code) : option StepEquiv.rewrite.\n  name peep_test_then_lea p.\n  unfold peep_test_then_lea_defs in p.\n  simpl in p. \n  specialize (p c).\n  do 3 set_code_cons c.\n  set_code_nil c.  \n  set_instr_eq i 0%nat peep_test_then_lea_example.\n  set_instr_eq i0 1%nat peep_test_then_lea_example.\n  set_instr_eq i1 2%nat peep_test_then_lea_example.  \n  set_ireg_eq rd0 r1.\n  set_ireg_eq r0 r2.\n  set_ireg_eq r2 rd.\n  set_ireg_neq r1 rd.  \n  set_addrmode_eq a (Addrmode (Some rd) None (inl neg_one)).\n  specialize (p _ _ n eq_refl). exact (Some p).\nDefined.\n\nDefinition test_then_lea (c : code) : list StepEquiv.rewrite :=\n  collect (map peep_test_then_lea_rewrite (ParamSplit.matched_pat peep_test_then_lea_example c)).\n                \n", "meta": {"author": "uwplse", "repo": "peek", "sha": "4943735ed39fd5ddadf2c28fc2ada31504228561", "save_path": "github-repos/coq/uwplse-peek", "path": "github-repos/coq/uwplse-peek/peek-4943735ed39fd5ddadf2c28fc2ada31504228561/compcert/peeps/Peep_TestThenLea.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2478162156430522}}
{"text": "Set Warnings \"-notation-overridden,-parsing,-deprecated-hint-without-locality\".\nFrom Coq Require Import Bool.Bool.\nFrom Coq Require Import Strings.String.\nFrom Coq Require Import Arith.Arith.\nFrom Coq Require Import Arith.EqNat. Import Nat.\nFrom Coq Require Import Arith.PeanoNat.\nFrom Coq Require Import Strings.String.\nFrom Coq Require Import Logic.Eqdep_dec.\nFrom PFPL Require Import PartialMap_Set.\nFrom PFPL Require Import Definitions.\nFrom PFPL Require Import Lemmas_Vars.\nFrom PFPL Require Import Lemmas_Rename.\nFrom PFPL Require Import Lemmas_Same_Structure.\nFrom PFPL Require Import Lemmas_AlphaEquiv.\nFrom PFPL Require Import Lemmas_Rename.\nFrom PFPL Require Import Lemmas_FreshRename.\nFrom PFPL Require Import Lemmas_Rename_FreshRename.\nFrom PFPL Require Import Lemmas_FreshRename_AlphaEquiv.\nFrom PFPL Require Import Lemmas_Subst.\n\nLemma rename_vs_subst : forall e e' x y z,\n  (x =? y) = false ->\n  (x =? z) = false ->\n  free_vars e' y = false ->\n  rename (subst' e' x e) y z = subst' e' x (rename e y z).\nProof.\n  induction e; intros; simpl.\n  - reflexivity.\n  - reflexivity.\n  - case_eq (x0 =? x); intro X0X.\n    + apply Nat.eqb_eq in X0X. subst.\n      rewrite Nat.eqb_sym. rewrite H.\n      simpl. rewrite Nat.eqb_refl.\n      symmetry.\n      apply rename_non_existant_free. assumption.\n    + simpl. case_eq (y =? x); intro YX.\n      * apply Nat.eqb_eq in YX. subst.\n        simpl. rewrite H0. reflexivity.\n      * simpl. rewrite X0X. reflexivity.\n  - f_equal.\n    apply IHe1. assumption. assumption. assumption.\n    apply IHe2. assumption. assumption. assumption.\n  - f_equal.\n    apply IHe1. assumption. assumption. assumption.\n    apply IHe2. assumption. assumption. assumption.\n  - f_equal.\n    apply IHe1. assumption. assumption. assumption.\n    apply IHe2. assumption. assumption. assumption.\n  - f_equal.\n    apply IHe. assumption. assumption. assumption.\n  - case_eq (x0 =? x); intro X0X.\n    + apply Nat.eqb_eq in X0X. subst.\n      rewrite Nat.eqb_sym. rewrite H.\n      simpl. rewrite Nat.eqb_refl.\n      rewrite Nat.eqb_sym. rewrite H.\n      f_equal.\n      apply IHe1. assumption. assumption. assumption.\n    + simpl. case_eq (y =? x); intro YX.\n      * apply Nat.eqb_eq in YX. subst.\n        simpl. rewrite H.\n        f_equal.\n        apply IHe1. assumption. assumption. assumption.\n      * simpl. rewrite X0X. f_equal.\n        apply IHe1. assumption. assumption. assumption.\n        apply IHe2. assumption. assumption. assumption.\nQed.\n\nLemma subst'_vs_rename : forall e e' x x',\n  all_vars e x' = false ->\n  (subst' e' x e) = (subst' e' x' (rename e x x')).\nProof.\n  induction e; intros e' z z' A; simpl.\n  - reflexivity.\n  - reflexivity.\n  - destruct (z =? x); simpl.\n    rewrite Nat.eqb_refl. reflexivity.\n    simpl in A. unfold singletonSet in A.\n    rewrite Nat.eqb_sym. destruct (x =? z').\n    discriminate. reflexivity.\n  - simpl in A. unfold unionSet in A.\n    apply orb_false_iff in A. destruct A as [A A'].\n    f_equal; [apply IHe1 | apply IHe2]; auto.\n  - simpl in A. unfold unionSet in A.\n    apply orb_false_iff in A. destruct A as [A A'].\n    f_equal; [apply IHe1 | apply IHe2]; auto.\n  - simpl in A. unfold unionSet in A.\n    apply orb_false_iff in A. destruct A as [A A'].\n    f_equal; [apply IHe1 | apply IHe2]; auto.\n  - simpl in A. f_equal. apply IHe. auto.\n  - simpl in A. unfold unionSet in A.\n    apply orb_false_iff in A. destruct A as [A A'].\n    unfold updateSet in A'.\n    case_eq (x =? z'); intro XZ'; rewrite XZ' in A'.\n    discriminate.\n    case_eq (z =? x); intro ZX.\n    + apply Nat.eqb_eq in ZX. subst z.\n      simpl. rewrite Nat.eqb_sym. rewrite XZ'.\n      f_equal. auto.\n      apply subst_non_free_var.\n      apply not_in_expr_not_free. auto.\n    + simpl. rewrite Nat.eqb_sym. rewrite XZ'.\n      f_equal. auto. apply IHe2. auto.\nQed.\n", "meta": {"author": "jdmota", "repo": "Harpers-E-Language-in-Coq", "sha": "d09313908aa2c4503301e276e7ca8eb6b3d56897", "save_path": "github-repos/coq/jdmota-Harpers-E-Language-in-Coq", "path": "github-repos/coq/jdmota-Harpers-E-Language-in-Coq/Harpers-E-Language-in-Coq-d09313908aa2c4503301e276e7ca8eb6b3d56897/coq/Lemmas_Rename_Subst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.24781554514906315}}
{"text": "Require Import Lia.\nRequire Import RelationClasses.\n\nFrom Paco Require Import paco.\nFrom sflib Require Import sflib.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nRequire Import Time.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\nRequire Import Behavior.\n\nRequire Import AMemory.\nRequire Import ALocal.\nRequire Import AThread.\n\nRequire Import APF.\nRequire Import PF.\n\n\nLemma promise_apromise\n  :\n    Memory.promise <9= AMemory.promise.\nProof.\n  i. inv PR; econs; eauto.\nQed.\n\nLemma write_awrite\n  :\n    Memory.write <10= AMemory.write.\nProof.\n  i. inv PR; econs; eauto.\n  eapply promise_apromise; eauto.\nQed.\n\nLemma program_step_aprogram_step\n  :\n    Thread.program_step <4= AThread.program_step.\nProof.\n  i. inv PR. inv LOCAL.\n  - econs; eauto.\n  - econs; eauto.\n  - inv LOCAL0. econs; eauto. econs; eauto.\n    econs; eauto. eapply write_awrite; eauto.\n  - inv LOCAL2. econs; eauto. econs; eauto.\n    econs; eauto. eapply write_awrite; eauto.\n  - econs; eauto.\n  - econs; eauto.\n  - econs; eauto.\nQed.\n\nLemma thread_step_athread_step\n  :\n    Thread.step_allpf <4= AThread.step_allpf.\nProof.\n  i. inv PR. inv STEP.\n  - inv STEP0. inv LOCAL. econs; eauto. econs; eauto.\n    econs; eauto. econs; eauto. eapply promise_apromise; eauto.\n  - econs. econs 2. eapply program_step_aprogram_step; eauto.\nQed.\n\nLemma thread_steps_athread_steps lang\n  :\n    rtc (tau (@Thread.step_allpf lang)) <2= rtc (tau (@AThread.step_allpf lang)).\nProof.\n  eapply rtc_implies. i. inv H. econs; eauto.\n  eapply thread_step_athread_step; eauto.\nQed.\n\nLemma program_steps_aprogram_steps lang\n  :\n    rtc (tau (@Thread.program_step lang)) <2= rtc (tau (@AThread.program_step lang)).\nProof.\n  eapply rtc_implies. i. inv H. econs; eauto.\n  eapply program_step_aprogram_step; eauto.\nQed.\n\nLemma pfstep_apfstep:\n  PFConfiguration.step <4= APFConfiguration.step.\nProof.\n  ii. inv PR.\n  eapply program_steps_aprogram_steps in STEPS.\n  eapply program_step_aprogram_step in STEP.\n  econs; eauto.\nQed.\n\nRecord shorter (mem_src mem_tgt: Memory.t): Prop :=\n  shorter_intro\n    {\n      shorter_get: forall loc to from msg (GET: Memory.get loc to mem_tgt = Some (from, msg)),\n        exists from', (<<GET: Memory.get loc to mem_src = Some (from', msg)>>);\n\n      shorter_get_iff: forall loc to from' msg (GET: Memory.get loc to mem_src = Some (from', msg)),\n          exists from msg, (<<GET: Memory.get loc to mem_tgt = Some (from, msg)>>) /\\\n                           (<<TS: Time.le from from'>>) /\\\n                           (<<ATTATCH:\n                              forall (BLANK: Memory.get loc from' mem_src = None),\n                                Time.lt from from'>>);\n    }\n.\n\nLemma shorter_write mem_src0 mem_tgt0 loc from to val released prom1 mem_tgt1 kind\n      (WRITE: AMemory.write Memory.bot mem_tgt0 loc from to val released prom1 mem_tgt1 kind)\n      (SHORT: shorter mem_src0 mem_tgt0)\n  :\n    exists from' mem_src1,\n      (<<WRITE: Memory.write Memory.bot mem_src0 loc from' to val released prom1 mem_src1 kind>>) /\\\n      (<<SHORT: shorter mem_src1 mem_tgt1>>).\nProof.\n  exploit APFConfiguration.write_no_promise; eauto. i. des. clarify.\n  inv WRITE. inv PROMISE. exists (Time.middle from to).\n  assert (WF: (<<MSG_WF: Message.wf (Message.full val released)>>) /\\\n              (<<TO: Time.lt from to>>) /\\\n              (<<DISJOINT: forall to2 from2 msg2\n                                  (GET: Memory.get loc to2 mem_tgt0 = Some (from2, msg2)),\n                  Interval.disjoint (from, to) (from2, to2)>>)).\n  { inv MEM. inv ADD. splits; auto. } des.\n  exploit (@Memory.add_exists mem_src0 loc (Time.middle from to) to (Message.full val released)).\n  { ii. inv LHS. inv RHS. ss.\n    eapply shorter_get_iff in GET2; eauto. des.\n    eapply DISJOINT; eauto.\n    - instantiate (1:=x). econs; ss. etrans.\n      + eapply Time.middle_spec; eauto.\n      + eauto.\n    - econs; ss. eapply TimeFacts.le_lt_lt; eauto.\n  }\n  { eapply Time.middle_spec; eauto. }\n  { ss. }\n  intros [mem_src1 ADD].\n  exploit (Memory.add_exists_le).\n  { eapply Memory.bot_le. }\n  { eapply ADD. } intros [prom0' ADDPROM].\n  exploit Memory.remove_exists.\n  { eapply Memory.add_get0. eapply ADDPROM. } intros [prom1 REMOVEPROM].\n\n  exists mem_src1. split.\n  - econs.\n    + econs; eauto; i; clarify.\n      dup GET. eapply shorter_get_iff in GET; eauto. des.\n      dup GET1. eapply shorter_get in GET1; eauto. des. clarify.\n      eapply DISJOINT; eauto.\n      * instantiate (1:=to). econs; ss. refl.\n      * econs; ss.\n        { eapply ATTATCH; eauto.\n          eapply Memory.add_get0 in ADD. des. clarify. }\n        { eapply Memory.get_ts in GET. des; auto.\n          - clarify. refl.\n          - left. auto. }\n    + exploit MemoryFacts.add_remove_eq; eauto. i. clarify.\n\n  - econs.\n    + i. dup GET. erewrite Memory.add_o in GET; eauto. des_ifs.\n      * ss. des. clarify. esplits. eapply Memory.add_get0; eauto.\n      * guardH o. dup GET. eapply shorter_get in GET; cycle 1; eauto. des.\n        eapply Memory.add_get1 in GET2; eauto.\n    + i. dup GET. erewrite Memory.add_o in GET; eauto. des_ifs.\n      * ss. des. clarify. esplits.\n        { eapply Memory.add_get0; eauto. }\n        { left. eapply Time.middle_spec; eauto. }\n        { i. eapply Time.middle_spec; eauto. }\n      * guardH o. dup GET. eapply shorter_get_iff in GET; cycle 1; eauto. des.\n        eapply Memory.add_get1 in GET2; eauto.\n        esplits; eauto.\n        i. eapply ATTATCH. destruct (Memory.get loc0 from' mem_src0) eqn:GET3; auto.\n        destruct p. eapply Memory.add_get1 in GET3; eauto. clarify.\nQed.\n\n\nLemma shorter_update mem_src0 mem_tgt0 loc from to val released prom1 mem_tgt1 kind\n      (WRITE: AMemory.write Memory.bot mem_tgt0 loc from to val released prom1 mem_tgt1 kind)\n      ts msg\n      (READ: Memory.get loc from mem_tgt0 = Some (ts, msg))\n      (SHORT: shorter mem_src0 mem_tgt0)\n  :\n    exists mem_src1,\n      (<<WRITE: Memory.write Memory.bot mem_src0 loc from to val released prom1 mem_src1 kind>>) /\\\n      (<<SHORT: shorter mem_src1 mem_tgt1>>).\nProof.\n  exploit APFConfiguration.write_no_promise; eauto. i. des. clarify.\n  inv WRITE. inv PROMISE.\n  assert (WF: (<<MSG_WF: Message.wf (Message.full val released)>>) /\\\n              (<<TO: Time.lt from to>>) /\\\n              (<<DISJOINT: forall to2 from2 msg2\n                                  (GET: Memory.get loc to2 mem_tgt0 = Some (from2, msg2)),\n                  Interval.disjoint (from, to) (from2, to2)>>)).\n  { inv MEM. inv ADD. splits; auto. } des.\n  exploit (@Memory.add_exists mem_src0 loc from to (Message.full val released)).\n  { ii. inv LHS. inv RHS. ss.\n    eapply shorter_get_iff in GET2; eauto. des.\n    eapply DISJOINT; eauto.\n    - instantiate (1:=x). econs; ss.\n    - econs; ss. eapply TimeFacts.le_lt_lt; eauto.\n  }\n  { ss. }\n  { ss. }\n  intros [mem_src1 ADD].\n  exploit (Memory.add_exists_le).\n  { eapply Memory.bot_le. }\n  { eapply ADD. } intros [prom0' ADDPROM].\n  exploit Memory.remove_exists.\n  { eapply Memory.add_get0. eapply ADDPROM. } intros [prom1 REMOVEPROM].\n\n  exists mem_src1. split.\n  - econs.\n    + econs; eauto; i; clarify.\n      dup GET. eapply shorter_get_iff in GET; eauto. des.\n      dup GET1. eapply shorter_get in GET1; eauto. des. clarify.\n      eapply DISJOINT; eauto.\n      * instantiate (1:=to). econs; ss. refl.\n      * econs; ss.\n        { eapply ATTATCH; eauto.\n          eapply Memory.add_get0 in ADD. des. clarify. }\n        { eapply Memory.get_ts in GET. des; auto.\n          - clarify. refl.\n          - left. auto. }\n    + exploit MemoryFacts.add_remove_eq; eauto. i. clarify.\n  - econs.\n    + i. dup GET. erewrite Memory.add_o in GET; eauto. des_ifs.\n      * ss. des. clarify. esplits. eapply Memory.add_get0; eauto.\n      * guardH o. dup GET. eapply shorter_get in GET; cycle 1; eauto. des.\n        eapply Memory.add_get1 in GET2; eauto.\n    + i. dup GET. erewrite Memory.add_o in GET; eauto. des_ifs.\n      * ss. des. clarify. esplits.\n        { eapply Memory.add_get0; eauto. }\n        { refl. }\n        { i. eapply shorter_get in READ; eauto. des.\n          eapply Memory.add_get1 in GET; eauto. clarify. }\n      * guardH o. dup GET. eapply shorter_get_iff in GET; cycle 1; eauto. des.\n        eapply Memory.add_get1 in GET2; eauto.\n        esplits; eauto.\n        i. eapply ATTATCH. destruct (Memory.get loc0 from' mem_src0) eqn:GET3; auto.\n        destruct p. eapply Memory.add_get1 in GET3; eauto. clarify.\nQed.\n\nLemma shorter_program_step lang th_src th_tgt th_tgt' st st' v v' prom' sc sc'\n      mem_tgt mem_tgt' mem_src e_tgt\n      (STEP: AThread.program_step e_tgt th_tgt th_tgt')\n      (SHORT: shorter mem_src mem_tgt)\n      (TH_SRC: th_src = Thread.mk lang st (Local.mk v Memory.bot) sc mem_src)\n      (TH_TGT0: th_tgt = Thread.mk lang st (Local.mk v Memory.bot) sc mem_tgt)\n      (TH_TGT1: th_tgt' = Thread.mk lang st' (Local.mk v' prom') sc' mem_tgt')\n  :\n    exists mem_src' e_src,\n      (<<STEP: Thread.program_step\n                 e_src th_src\n                 (Thread.mk lang st' (Local.mk v' prom') sc' mem_src')>>) /\\\n      (<<SHORT: shorter mem_src' mem_tgt'>>) /\\\n      (<<EVENT: ThreadEvent.get_machine_event e_tgt = ThreadEvent.get_machine_event e_src>>)\n.\nProof.\n  inv STEP. clarify. inv LOCAL.\n  - esplits; eauto. econs; eauto.\n  - esplits; eauto. inv LOCAL0. ss. clarify. econs; eauto. econs; eauto.\n    eapply shorter_get in GET; eauto. des. econs; eauto.\n  - inv LOCAL0. ss. clarify.\n    exploit shorter_write; eauto. i. des. exists mem_src1.\n    esplits; eauto.\n    + econs; eauto; ss.\n    + ss.\n  - inv LOCAL1. inv LOCAL2. clarify.\n    dup GET. eapply shorter_get in GET; eauto. des.\n    exploit shorter_update; eauto. i. des. exists mem_src1.\n    esplits; eauto. econs; eauto.\n  - esplits; eauto. inv LOCAL0. ss. clarify. econs; eauto.\n  - esplits; eauto. inv LOCAL0. ss. clarify. econs; eauto.\n  - esplits; eauto. inv LOCAL0. ss. clarify. econs; eauto.\nQed.\n\nLemma shorter_program_steps lang th_src th_tgt th_tgt' st st' v v' prom' sc sc'\n      mem_tgt mem_tgt' mem_src\n      (STEPS: rtc (tau (@AThread.program_step lang)) th_tgt th_tgt')\n      (SHORT: shorter mem_src mem_tgt)\n      (TH_SRC: th_src = Thread.mk lang st (Local.mk v Memory.bot) sc mem_src)\n      (TH_TGT0: th_tgt = Thread.mk lang st (Local.mk v Memory.bot) sc mem_tgt)\n      (TH_TGT1: th_tgt' = Thread.mk lang st' (Local.mk v' prom') sc' mem_tgt')\n  :\n    exists mem_src',\n      (<<STEPS: rtc (tau (@Thread.program_step lang))\n                    th_src\n                    (Thread.mk lang st' (Local.mk v' prom') sc' mem_src')>>) /\\\n      (<<SHORT: shorter mem_src' mem_tgt'>>)\n.\nProof.\n  ginduction STEPS.\n  - i. clarify. esplits; eauto.\n  - i. clarify. inv H. destruct y. destruct local.\n    exploit shorter_program_step; eauto. i. des.\n    exploit PFConfiguration.program_step_no_promise; eauto. i. ss. clarify.\n    exploit IHSTEPS; eauto. i. des. esplits; eauto.\n    econs; eauto. econs; eauto. rewrite <- EVENT. auto.\nQed.\n\nInductive sim_apf_pf: Configuration.t -> Configuration.t -> Prop :=\n| sim_apf_pf_intro\n    c_src c_tgt\n    ths sc mem_src mem_tgt\n    (SRC: c_src = Configuration.mk ths sc mem_src)\n    (TGT: c_tgt = Configuration.mk ths sc mem_tgt)\n    (PROMISESRC: ~ Configuration.has_promise c_src)\n    (PROMISETGT: ~ Configuration.has_promise c_tgt)\n    (MEMORY: shorter mem_src mem_tgt)\n  :\n    sim_apf_pf c_src c_tgt\n.\n\nLemma sim_apf_pf_step c_tgt0 c_tgt1 c_src0 tid e\n      (SIM: sim_apf_pf c_src0 c_tgt0)\n      (STEP: APFConfiguration.step tid e c_tgt0 c_tgt1)\n  :\n    exists c_src1,\n      (<<STEP: PFConfiguration.step tid e c_src0 c_src1>>) /\\\n      (<<SIM: sim_apf_pf c_src1 c_tgt1>>).\nProof.\n  inv SIM. dup STEP. inv STEP. ss. destruct e2. destruct lc1, local, lc3.\n  exploit APFConfiguration.no_promise_spec; eauto. i. ss. clarify.\n  exploit shorter_program_steps; eauto. i. des.\n  exploit APFConfiguration.program_steps_no_promise; eauto. i. ss. clarify.\n  exploit shorter_program_step; eauto. i. des.\n  assert (STEPSRC: PFConfiguration.step\n                     (ThreadEvent.get_machine_event e_src) e\n                     (Configuration.mk ths sc mem_src)\n                     (Configuration.mk (IdentMap.add e (existT _ lang st3, Local.mk tview1 promises1) ths) sc3 mem_src'0)).\n  { econs; eauto. }\n  rewrite EVENT. esplits; eauto. econs; eauto.\n  - eapply PFConfiguration.configuration_step_no_promise in STEPSRC; eauto.\n  - eapply APFConfiguration.configuration_step_no_promise in STEP0; eauto.\nQed.\n\nLemma sim_apf_pf_init s\n  :\n    sim_apf_pf (Configuration.init s) (Configuration.init s).\nProof.\n  econs; ss.\n  - ii. inv H. ss. unfold Threads.init in FIND.\n    erewrite IdentMap.Properties.F.map_o in *.\n    unfold option_map, Local.init in *. des_ifs. ss. erewrite Memory.bot_get in GET. clarify.\n  - ii. inv H. ss. unfold Threads.init in FIND.\n    erewrite IdentMap.Properties.F.map_o in *.\n    unfold option_map, Local.init in *. des_ifs. ss. erewrite Memory.bot_get in GET. clarify.\n  - econs; i.\n    + unfold Memory.init, Memory.get in *. erewrite Cell.init_get in *.\n      des_ifs. esplits; eauto.\n    + unfold Memory.init, Memory.get in *. erewrite Cell.init_get in *.\n      des_ifs. esplits; eauto.\n      * refl.\n      * i. erewrite Cell.init_get in *. des_ifs.\nQed.\n\nLemma sim_apf_pf_terminal c_src c_tgt\n      (SIM: sim_apf_pf c_src c_tgt)\n      (TERMINAL: Configuration.is_terminal c_tgt)\n  :\n    Configuration.is_terminal c_src.\nProof.\n  inv SIM. ii. eauto.\nQed.\n\nLemma sim_apf_pf_adequacy c_src c_tgt\n      (SIM: sim_apf_pf c_src c_tgt)\n  :\n    behaviors APFConfiguration.step c_tgt <1=\n    behaviors PFConfiguration.step c_src.\nProof.\n  i. ginduction PR; i.\n  - econs 1. eapply sim_apf_pf_terminal; eauto.\n  - exploit sim_apf_pf_step; eauto. i. des. econs 2; eauto.\n  - exploit sim_apf_pf_step; eauto. i. des. econs 3; eauto.\n  - exploit sim_apf_pf_step; eauto. i. des. econs 4; eauto.\nQed.\n\nTheorem apf_pf_equiv s\n  :\n    behaviors APFConfiguration.step (Configuration.init s) <1=\n    behaviors PFConfiguration.step (Configuration.init s).\nProof.\n  eapply sim_apf_pf_adequacy.\n  eapply sim_apf_pf_init; auto.\nQed.\n\nTheorem apf_pf_equiv2 c\n  :\n    behaviors PFConfiguration.step c <1=\n    behaviors APFConfiguration.step c.\nProof.\n  eapply le_step_behavior_improve; eauto.\n  i. eapply pfstep_apfstep; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising2-coq", "sha": "52dd46538036a7a69c132e89dd3e7698b5e2f830", "save_path": "github-repos/coq/snu-sf-promising2-coq", "path": "github-repos/coq/snu-sf-promising2-coq/promising2-coq-52dd46538036a7a69c132e89dd3e7698b5e2f830/src/attachable/APFPF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6893056040203135, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.24771172387224796}}
{"text": "From iris.program_logic Require Import language ectxi_language ectx_language lifting.\nFrom iris Require Import program_logic.weakestpre.\nFrom iris.proofmode Require Import tactics.\nFrom st.STLCmuST Require Import lang.\n\nSection wkpre_lemmas.\n\n  Context `{Σ : !gFunctors}.\n  Context `{irisGS_inst : !irisGS STLCmuST_lang Σ}.\n\n  Lemma wp_bind' (K : list ectx_item) s E e Φ :\n    WP e @ s; E {{ v, WP fill K (of_val v) @ s; E {{ Φ }} }} ⊢ WP fill K e @ s; E {{ Φ }}.\n  Proof. iApply wp_bind. Qed.\n\n  Lemma wp_pure_step_later {s : stuckness} {E : coPset} e1 e2 Φ (H : pure_step e1 e2) :\n    ▷ WP e2 @ s ; E {{Φ}} ⊢ WP e1 @ s ; E {{Φ}}.\n  Proof. iIntros \"He2\". iApply (wp_pure_step_later _ _ _ _ True 1). intros t. by apply nsteps_once. auto. auto. Qed.\n\nEnd wkpre_lemmas.\n", "meta": {"author": "scaup", "repo": "sem_backs_st", "sha": "e14aa7f421de94df5c1369d2b4b44d8644243cec", "save_path": "github-repos/coq/scaup-sem_backs_st", "path": "github-repos/coq/scaup-sem_backs_st/sem_backs_st-e14aa7f421de94df5c1369d2b4b44d8644243cec/theories/STLCmuST/wkpre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.3702253925955867, "lm_q1q2_score": 0.2476364618827159}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\nRequire Import omega.Omega.\nRequire Import Setoid.\nRequire Import ZArith.\n\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith. \n\nLocal Open Scope struct_scope.\n\nRequire Import FinProof.CommonProofs.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolClass.\nRequire Import depoolContract.SolidityNotations.\n\nRequire Import depoolContract.DePoolFunc.\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\n\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\n(*Require Import depoolContract.Lib.CommonCommon.*)\n(* Require Import depoolContract.Lib.tvmFunctionsProofs. *)\n\nImport DePoolSpec.LedgerClass.SolidityNotations. \n\nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope solidity_scope.\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\n\nSet Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100.\n\nRequire Export depoolContract.Scenarios.Projections.Round_Steps.States.\nRequire Export depoolContract.Scenarios.Common.RotateRoundsCondition.\nRequire Export depoolContract.Scenarios.Common.RoundDefinitions.\nRequire Export depoolContract.Scenarios.Common.unfreezeCondition.\n\nSection Round_Steps_conditions.\n\nVariable ticktockCalled : Prop.\nVariable constructorCalled : Prop.\nVariable terminatorCalled : Prop.\nVariable onSuccessToRecoverStakeCalled : Prop.\nVariable onFailToRecoverStakeCalled : Prop.\nVariable onStakeRejectCalled : Prop.\nVariable onStakeAcceptCalled : Prop.\nVariable participateInElectionsCalled : Prop.\nVariable completeRoundWithChunkCalled : Prop.\nVariable queryId elector stakeAt chunkSize : Z.\nVariable bounceExternal : Prop.\nVariable functionId process_new_stakeId recover_stakeId decodedRoundId : Z.\n\nDefinition generateRoundCalled (l : Ledger) :=\n    constructorCalled \\/ rotate_round_conditions_full l ticktockCalled.\n\n\nDefinition projection_round_steps_constructor_condition\n(l : Ledger) (r : RoundsBase_ι_Round) :=\n    generateRoundCalled l.\n\nDefinition projection_round_steps_constructor_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    roundIn nl nr /\\\n    ~ roundIn ol nr /\\\n    projection_round_steps_constructor_condition ol or /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_PrePooling.\n\nDefinition projection_round_steps_constructor_fake0_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n        constructorCalled.\n\nDefinition projection_round_steps_constructor_fake0_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    roundIn nl nr /\\\n    ~ roundIn ol nr /\\\n    projection_round_steps_constructor_fake0_condition ol or /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Pooling.\n\nDefinition projection_round_steps_constructor_fake1_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n        constructorCalled.\n\nDefinition projection_round_steps_constructor_fake1_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    roundIn nl nr /\\\n    ~ roundIn ol nr /\\\n    projection_round_steps_constructor_fake1_condition ol or /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze.\n\nDefinition projection_round_steps_constructor_fake2_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n        constructorCalled.\n\nDefinition projection_round_steps_constructor_fake2_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    roundIn nl nr /\\\n    ~ roundIn ol nr /\\\n    projection_round_steps_constructor_fake2_condition ol or /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completed.\n\nDefinition projection_round_steps_prepool_completing_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    terminatorCalled /\\\n    r = roundPre0 l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_PrePooling /\\\n    ownerOrSelfCall l /\\\n    poolClosed l = false /\\\n    0 < RoundsBase_ι_Round_ι_participantQty r.\n\nDefinition projection_round_steps_prepool_completing_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_prepool_completing_condition ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completing.\n\nDefinition projection_round_steps_prepool_completed_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    terminatorCalled /\\\n    r = roundPre0 l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_PrePooling /\\\n    ownerOrSelfCall l /\\\n    poolClosed l = false /\\\n    0 = RoundsBase_ι_Round_ι_participantQty r.\n\nDefinition projection_round_steps_prepool_completed_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_prepool_completed_condition ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completed.\n\nDefinition projection_round_steps_prepool_pooling_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    rotate_round_conditions_full l ticktockCalled /\\\n    r = roundPre0 l /\\\n    poolClosed l = false /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_PrePooling.\n\nDefinition projection_round_steps_prepool_pooling_move\n    (ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n        projection_round_steps_prepool_pooling_condition ol or /\\\n        roundIn nl nr /\\\n        getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Pooling.\n\nDefinition projection_round_steps_pooling_completing_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    terminatorCalled /\\\n    r = roundPre0 l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_Pooling /\\\n    ownerOrSelfCall l /\\\n    poolClosed l = false /\\\n    0 < RoundsBase_ι_Round_ι_participantQty r.\n\nDefinition projection_round_steps_pooling_completing_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_pooling_completing_condition ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completing.\n\nDefinition projection_round_steps_pooling_completed_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    terminatorCalled /\\\n    r = roundPre0 l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_Pooling /\\\n    ownerOrSelfCall l /\\\n    poolClosed l = false /\\\n    0 = RoundsBase_ι_Round_ι_participantQty r.\n\nDefinition projection_round_steps_pooling_completed_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_pooling_completed_condition ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completed.\n\nDefinition projection_round_steps_pooling_waiting_unfreeze_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    rotate_round_conditions_full l ticktockCalled /\\\n    r = round0 l /\\\n    poolClosed l = false /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_Pooling /\\\n    stakeSum (validatorStake l r) < m_validatorAssurance l.\n\nDefinition projection_round_steps_pooling_waiting_unfreeze_move\n    (ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_pooling_waiting_unfreeze_condition ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze.\n\nDefinition projection_round_steps_pooling_waiting_validator_request_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    rotate_round_conditions_full l ticktockCalled /\\\n    r = round0 l /\\\n    poolClosed l = false /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_Pooling /\\\n    m_validatorAssurance l <= stakeSum (validatorStake l r).\n\nDefinition projection_round_steps_pooling_waiting_validator_request_move\n    (ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_pooling_waiting_validator_request_condition ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest.\n\nDefinition projection_round_steps_waiting_validator_request_completing1_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    terminatorCalled /\\\n    r = round1 l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest /\\\n    ownerOrSelfCall l /\\\n    poolClosed l = false.\n\nDefinition projection_round_steps_waiting_validator_request_completing1_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_validator_request_completing1_condition ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completing.\n\nDefinition projection_round_steps_waiting_validator_request_completing2_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    rotate_round_conditions_full l ticktockCalled /\\\n    r = round1 l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest.\n\nDefinition projection_round_steps_waiting_validator_request_completing2_move\n    (ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_validator_request_completing2_condition ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completing.\n\nDefinition projection_round_steps_waiting_validator_request_waiting_if_stake_accepted_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    participateInElectionsCalled /\\\n    onlyValidatorContract l /\\\n    poolClosed l = false /\\\n    checkDePoolBalance l (msgValue l) (balance l) /\\\n    stakeAt = RoundsBase_ι_Round_ι_supposedElectedAt r /\\\n    r = round1 l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest.\n\nDefinition projection_round_steps_waiting_validator_request_waiting_if_stake_accepted_move\n    (ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_validator_request_waiting_if_stake_accepted_condition\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingIfStakeAccepted.\n\nDefinition projection_round_steps_waiting_if_stake_accepted_waiting_validator_request0_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    bounceExternal /\\\n    functionId = process_new_stakeId /\\\n    RoundsBase_ι_Round_ι_id r = decodedRoundId /\\\n    r = round1 l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingIfStakeAccepted.\n\nDefinition projection_round_steps_waiting_if_stake_accepted_waiting_validator_request0_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_if_stake_accepted_waiting_validator_request0_condition\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest.\n\nDefinition projection_round_steps_waiting_if_stake_accepted_waiting_validator_request1_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    onStakeRejectCalled /\\\n    RoundsBase_ι_Round_ι_id r = queryId /\\\n    r = round1 l /\\\n    msgSender l = RoundsBase_ι_Round_ι_proxy r /\\\n    elector = RoundsBase_ι_Round_ι_elector r /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingIfStakeAccepted.\n\nDefinition projection_round_steps_waiting_if_stake_accepted_waiting_validator_request1_move\n    (ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_if_stake_accepted_waiting_validator_request1_condition\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest.\n\nDefinition projection_round_steps_waiting_if_stake_accepted_waiting_validator_start_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    onStakeAcceptCalled /\\\n    RoundsBase_ι_Round_ι_id r = queryId /\\\n    r = round1 l /\\\n    msgSender l = RoundsBase_ι_Round_ι_proxy r /\\\n    elector = RoundsBase_ι_Round_ι_elector r /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingIfStakeAccepted.\n\nDefinition projection_round_steps_waiting_if_stake_accepted_waiting_validator_start_move\n    (ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_if_stake_accepted_waiting_validator_start_condition\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingValidationStart.\n\nDefinition projection_round_steps_waiting_validator_start_waiting_reward1_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    rotate_round_conditions_full l ticktockCalled /\\\n    r = round1 l /\\\n    RoundsBase_ι_Round_ι_vsetHashInElectionPhase r <> currentValidator l /\\\n    RoundsBase_ι_Round_ι_vsetHashInElectionPhase r <> prevValidator l /\\\n    validationStart l + RoundsBase_ι_Round_ι_stakeHeldFor r + ELECTOR_UNFREEZE_LAG l <= now l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingValidationStart.\n\nDefinition projection_round_steps_waiting_validator_start_waiting_reward1_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_validator_start_waiting_reward1_condition\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingReward.\n\nDefinition projection_round_steps_waiting_validator_start_waiting_reward2_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    updateRoundsCalled l ticktockCalled /\\\n    r = round2 l /\\\n    RoundsBase_ι_Round_ι_vsetHashInElectionPhase r <> currentValidator l /\\\n    RoundsBase_ι_Round_ι_vsetHashInElectionPhase r <> prevValidator l /\\\n    validationStart l + RoundsBase_ι_Round_ι_stakeHeldFor r + ELECTOR_UNFREEZE_LAG l <= now l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingValidationStart.\n\nDefinition projection_round_steps_waiting_validator_start_waiting_reward2_move\n    (ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_validator_start_waiting_reward2_condition\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingReward.\n\nDefinition projection_round_steps_waiting_validator_start_waiting_if_validator_win_elections_condition\n(l : Ledger) (r : RoundsBase_ι_Round) :=\n    updateRoundsCalled l ticktockCalled /\\\n    r = round1 l /\\\n    RoundsBase_ι_Round_ι_vsetHashInElectionPhase r = prevValidator l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingValidationStart.\n\nDefinition projection_round_steps_waiting_validator_start_waiting_if_validator_win_elections_move\n    (ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_validator_start_waiting_if_validator_win_elections_condition\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingReward.\n\nDefinition projection_round_steps_waiting_if_validator_win_elections_waiting_validator_start_condition\n(l : Ledger) (r : RoundsBase_ι_Round) :=\n    bounceExternal /\\\n    functionId = recover_stakeId /\\\n    RoundsBase_ι_Round_ι_id r = decodedRoundId /\\\n    r = round1 l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingIfValidatorWinElections.\n\nDefinition projection_round_steps_waiting_if_validator_win_elections_waiting_validator_start_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_if_validator_win_elections_waiting_validator_start_condition\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingValidationStart.\n\nDefinition projection_round_steps_waiting_if_validator_win_elections_waiting_unfreeze_condition\n(l : Ledger) (r : RoundsBase_ι_Round) :=\n    (onSuccessToRecoverStakeCalled \\/ onFailToRecoverStakeCalled) /\\\n    RoundsBase_ι_Round_ι_id r = queryId /\\\n    roundIn l r /\\\n    msgSender l = RoundsBase_ι_Round_ι_proxy r /\\\n    elector = RoundsBase_ι_Round_ι_elector r /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingIfValidatorWinElections.\n\nDefinition projection_round_steps_waiting_if_validator_win_elections_waiting_unfreeze_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_if_validator_win_elections_waiting_unfreeze_condition\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze.\n\nDefinition projection_round_steps_waiting_unfreeze_waiting_reward_condition1\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    rotate_round_conditions_full l ticktockCalled /\\\n    r = round1 l /\\\n    shouldBeUnfrozen l r /\\\n    RoundsBase_ι_Round_ι_completionReason r = RoundsBase_ι_CompletionReasonP_ι_Undefined /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze.\n\nDefinition projection_round_steps_waiting_unfreeze_waiting_reward_move1\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_unfreeze_waiting_reward_condition1\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingReward.\n\nDefinition projection_round_steps_waiting_unfreeze_waiting_reward_condition2\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    updateRoundsCalled l ticktockCalled /\\\n    r = round2 l /\\\n    shouldBeUnfrozen l r /\\\n    RoundsBase_ι_Round_ι_completionReason r = RoundsBase_ι_CompletionReasonP_ι_Undefined /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze.\n\nDefinition projection_round_steps_waiting_unfreeze_waiting_reward_move2\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_unfreeze_waiting_reward_condition2\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingReward.\n\nDefinition projection_round_steps_waiting_unfreeze_completing_condition1\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    rotate_round_conditions_full l ticktockCalled /\\\n    r = round1 l /\\\n    shouldBeUnfrozen l r /\\\n    RoundsBase_ι_Round_ι_completionReason r <> RoundsBase_ι_CompletionReasonP_ι_Undefined /\\\n    0 < RoundsBase_ι_Round_ι_participantQty r /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze.\n\nDefinition projection_round_steps_waiting_unfreeze_completing_move1\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_unfreeze_completing_condition1\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completing.\n\nDefinition projection_round_steps_waiting_unfreeze_completing_condition2\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    updateRoundsCalled l ticktockCalled /\\\n    r = round2 l /\\\n    shouldBeUnfrozen l r /\\\n    RoundsBase_ι_Round_ι_completionReason r <> RoundsBase_ι_CompletionReasonP_ι_Undefined /\\\n    0 < RoundsBase_ι_Round_ι_participantQty r /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze.\n\nDefinition projection_round_steps_waiting_unfreeze_completing_move2\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_unfreeze_completing_condition2\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completing.\n\nDefinition projection_round_steps_waiting_unfreeze_completed_condition1\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    rotate_round_conditions_full l ticktockCalled /\\\n    r = round1 l /\\\n    shouldBeUnfrozen l r /\\\n    RoundsBase_ι_Round_ι_completionReason r <> RoundsBase_ι_CompletionReasonP_ι_Undefined /\\\n    0 = RoundsBase_ι_Round_ι_participantQty r /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze.\n\nDefinition projection_round_steps_waiting_unfreeze_completed_move1\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_unfreeze_completed_condition1\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completed.\n\nDefinition projection_round_steps_waiting_unfreeze_completed_condition2\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    updateRoundsCalled l ticktockCalled /\\\n    r = round2 l /\\\n    shouldBeUnfrozen l r /\\\n    RoundsBase_ι_Round_ι_completionReason r <> RoundsBase_ι_CompletionReasonP_ι_Undefined /\\\n    0 = RoundsBase_ι_Round_ι_participantQty r /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze.\n\nDefinition projection_round_steps_waiting_unfreeze_completed_move2\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_unfreeze_completed_condition2\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completed.\n\nDefinition projection_round_steps_waiting_rewards_waiting_unfreeze_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    bounceExternal /\\\n    functionId = recover_stakeId /\\\n    RoundsBase_ι_Round_ι_id r = decodedRoundId /\\\n    r = round2 l /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingReward.\n\nDefinition projection_round_steps_waiting_rewards_waiting_unfreeze_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_rewards_waiting_unfreeze_condition\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze.\n\nDefinition projection_round_steps_waiting_rewards_completing_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    (onSuccessToRecoverStakeCalled \\/ onFailToRecoverStakeCalled) /\\\n    RoundsBase_ι_Round_ι_id r = queryId /\\\n    roundIn l r /\\\n    msgSender l = RoundsBase_ι_Round_ι_proxy r /\\\n    elector = RoundsBase_ι_Round_ι_elector r /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_WaitingReward.\n\nDefinition projection_round_steps_waiting_rewards_completing_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_waiting_rewards_completing_condition\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completing.\n\nDefinition projection_round_steps_completing_completed_condition\n    (l : Ledger) (r : RoundsBase_ι_Round) :=\n    completeRoundWithChunkCalled /\\\n    selfCall l /\\\n    RoundsBase_ι_Round_ι_id r = queryId /\\\n    r = round2 l /\\\n    Z.of_nat (length (RoundsBase_ι_Round_ι_stakes r)) <= chunkSize /\\\n    getProjectionRoundStepState r = RoundsBase_ι_RoundStepP_ι_Completing.\n\nDefinition projection_round_steps_completing_completed_move\n(ol nl : Ledger) (or nr : RoundsBase_ι_Round) :=\n    projection_round_steps_completing_completed_condition\n        ol or /\\\n    roundIn nl nr /\\\n    getProjectionRoundStepState nr = RoundsBase_ι_RoundStepP_ι_Completed.\n\nEnd Round_Steps_conditions.", "meta": {"author": "Pruvendo", "repo": "depool_contract_scenarios", "sha": "f0146bda676f3a1a35a7695b9598c7d2e337bbc2", "save_path": "github-repos/coq/Pruvendo-depool_contract_scenarios", "path": "github-repos/coq/Pruvendo-depool_contract_scenarios/depool_contract_scenarios-f0146bda676f3a1a35a7695b9598c7d2e337bbc2/src/Scenarios/Projections/Round_Steps/Conditions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.24763646188271587}}
{"text": "Require Import UFO.Rel.Definitions.\nRequire Import UFO.Rel.BasicFacts.\nRequire Import UFO.Rel.Monotone.\nRequire Import UFO.Util.Subset.\nRequire Import UFO.Util.Postfix.\nRequire Import UFO.Lang.Sig.\nRequire Import UFO.Lang.BindingsFacts.\nRequire Import UFO.Lang.Static.\nRequire Import UFO.Lang.StaticFacts.\nSet Implicit Arguments.\n\nSection section_ccompat_tm_op.\n\nContext (EV LV : Set).\nContext (Ξ : XEnv EV LV).\nContext (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig).\nContext (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig).\nContext (N : it ∅ EV LV ∅ 𝕄) (E : eff ∅ EV LV ∅) (ℓ : lbl LV ∅).\n\nLemma ccompat_tm_op n ξ₁ ξ₂ t₁ t₂ :\nn ⊨ 𝓣⟦ Ξ ⊢ (ty_it N ℓ) # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ →\nn ⊨ 𝓣⟦ Ξ ⊢ (ty_ms (it_msig N) ℓ) # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ (tm_op t₁) (tm_op t₂).\nProof.\nintro H.\nchange (tm_op t₁) with (ktx_plug (ktx_op ktx_hole) t₁).\nchange (tm_op t₂) with (ktx_plug (ktx_op ktx_hole) t₂).\neapply plug0 with (Ta := ty_it N ℓ).\n+ intro ; simpl ; auto.\n+ intro ; simpl ; auto.\n+ iintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂' ;\n  iintro v₁ ; iintro v₂ ; iintro Hv.\n  simpl ktx_plug.\n  simpl 𝓥_Fun in Hv.\n  idestruct Hv as m₁ Hv ; idestruct Hv as m₂ Hv.\n  idestruct Hv as X₁ Hv ; idestruct Hv as X₂ Hv.\n  idestruct Hv as Hv Hm ; idestruct Hm as HX Hm.\n  ielim_prop Hv ; destruct Hv ; subst v₁ v₂.\n\n  eapply 𝓣_step_r.\n  { apply step_op. }\n  eapply 𝓣_step_l.\n  { apply step_op. }\n  later_shift.\n  \n  apply 𝓥_unroll in Hm.\n  apply 𝓥_in_𝓣.\n  apply Hm.\n+ apply postfix_refl.\n+ apply postfix_refl.\n+ apply H.\nQed.\n\nEnd section_ccompat_tm_op.\n\n\nSection section_compat_tm_op.\nContext (n : nat).\nContext (EV LV V : Set).\nContext (Ξ : XEnv EV LV).\nContext (Γ : V → ty ∅ EV LV ∅).\nContext (N : it ∅ EV LV ∅ 𝕄) (E : eff ∅ EV LV ∅) (ℓ : lbl LV ∅).\n\nLemma compat_tm_op t₁ t₂ :\nn ⊨ ⟦ Ξ Γ ⊢ t₁ ≼ˡᵒᵍ t₂ : (ty_it N ℓ) # E ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ (tm_op t₁) ≼ˡᵒᵍ (tm_op t₂) : (ty_ms (it_msig N) ℓ) # E ⟧.\nProof.\nintro Ht.\niintro ξ₁ ; iintro ξ₂ ;\niintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ;\niintro γ₁ ; iintro γ₂.\niintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.\nsimpl subst_tm.\napply ccompat_tm_op.\niespecialize Ht.\nispecialize Ht ; [ eassumption | ].\nispecialize Ht ; [ eassumption | ].\nispecialize Ht ; [ eassumption | ].\nispecialize Ht ; [ eassumption | ].\napply Ht.\nQed.\n\nLemma compat_ktx_op T' E' K₁ K₂ :\nn ⊨ ⟦ Ξ Γ ⊢ K₁ ≼ˡᵒᵍ K₂ : T' # E' ⇢ (ty_it N ℓ) # E ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ (ktx_op K₁) ≼ˡᵒᵍ (ktx_op K₂) : T' # E' ⇢ (ty_ms (it_msig N) ℓ) # E⟧.\nProof.\nintro HK.\niintro ξ₁ ; iintro ξ₂ ;\niintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ;\niintro γ₁ ; iintro γ₂.\niintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.\niintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂' ;\niintro t₁ ; iintro t₂ ; iintro Ht.\niespecialize HK.\nispecialize HK ; [ eassumption | ].\nispecialize HK ; [ eassumption | ].\nispecialize HK ; [ eassumption | ].\nispecialize HK ; [ eassumption | ].\nielim_vars HK ; [ | eassumption | eassumption ].\niespecialize HK.\nispecialize HK ; [ eassumption | ].\nsimpl ktx_plug.\napply ccompat_tm_op.\napply HK.\nQed.\n\nEnd section_compat_tm_op.", "meta": {"author": "yizhouzhang", "repo": "olaf-coq", "sha": "03090a5e60e739dfa45ad60322d848c18faad48d", "save_path": "github-repos/coq/yizhouzhang-olaf-coq", "path": "github-repos/coq/yizhouzhang-olaf-coq/olaf-coq-03090a5e60e739dfa45ad60322d848c18faad48d/coq-src/UFO/Rel/Compat_tm_op.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.2476364476996434}}
{"text": "Set Universe Polymorphism.\nModule Foo.\n  Definition T : sigT (fun x => x).\n  Proof.\n    exists Set.\n    abstract exact nat.\n  Defined.\nEnd Foo.\nModule Bar.\n  Include Foo.\nEnd Bar.\nDefinition foo := eq_refl : Foo.T = Bar.T.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/closed/3804.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2475616503018257}}
{"text": "Add Search Blacklist \"Private_\" \"_subproof\".\nSet Printing Depth 50.\nRemove Search Blacklist \"Private_\" \"_subproof\".\nAdd Search Blacklist \"Private_\" \"_subproof\".\nAdd LoadPath \"../..\".\nRequire Import BetaJulia.BasicPLDefs.Identifier.\nRequire Import BetaJulia.Sub0250a.BaseDefs.\nRequire Import BetaJulia.Sub0250a.BaseProps.\nRequire Import BetaJulia.Sub0250a.MatchProps.\nRequire Import BetaJulia.Sub0250a.SemSubProps.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nOpen Scope btjt_scope.\nOpen Scope btjm_scope.\nOpen Scope btjnf_scope.\nOpen Scope btjd_scope.\nLemma sub_d__inv_depth_le : forall t t' : ty, |- t << t' -> | t | <= | t' |.\nProof.\n(intros t t' Hsub).\n(induction Hsub).\n-\nconstructor.\n-\n(apply Nat.le_trans with (| t2 |); assumption).\n-\n(simpl).\n(apply Nat.max_le_compat; assumption).\n-\n(simpl).\n(apply Nat.max_lub; assumption).\n-\n(simpl).\n(apply Nat.le_max_l).\n-\n(simpl).\n(apply Nat.le_max_r).\n-\n(simpl).\n(rewrite max_baca_eq_bca).\nconstructor.\n-\n(simpl).\n(rewrite max_abac_eq_abc).\nconstructor.\n-\n(simpl).\n(apply le_n_S).\nassumption.\nQed.\nLemma sub_d_eq__inv_depth_eq : forall t t' : ty, |- t << t' -> |- t' << t -> | t | = | t' |.\nProof.\n(intros t t' Hsub1 Hsub2).\n(apply Nat.le_antisymm; apply sub_d__inv_depth_le; assumption).\nQed.\nLemma unite_pairs__preserves_sub_d_l :\n  forall t1 t2 t1' t2' : ty, |- t1 << t1' -> |- t2 << t2' -> |- unite_pairs t1 t2 << TPair t1' t2'.\nProof.\n(intros ta; induction ta; intros tb;\n  try (solve\n   [ induction tb; intros ta' tb' Hsub1 Hsub2; try (solve [ simpl; constructor; assumption ]);\n      destruct (sub_d_union_l__inv _ _ _ Hsub2) as [Hsub21 Hsub22]; rewrite unite_pairs_t_union; try resolve_not_union; constructor;\n      [ apply IHtb1 | apply IHtb2 ]; assumption ])).\n-\n(intros ta' tb' Hsub1 Hsub2).\n(apply sub_d_union_l__inv in Hsub1).\n(destruct Hsub1 as [Hsub11 Hsub12]).\n(rewrite unite_pairs_union_t).\n(constructor; [ apply IHta1 | apply IHta2 ]; assumption).\nQed.\nLemma unite_pairs__preserves_sub_d_r :\n  forall t1' t2' t1 t2 : ty, |- t1 << t1' -> |- t2 << t2' -> |- TPair t1 t2 << unite_pairs t1' t2'.\nProof.\n(intros ta'; induction ta'; intros tb';\n  try (solve\n   [ induction tb'; intros ta tb Hsub1 Hsub2; try (solve [ simpl; constructor; assumption ]); rewrite unite_pairs_t_union;\n      try resolve_not_union; apply SD_Trans with (TPair ta (TUnion tb'1 tb'2));\n      [ constructor; constructor || assumption\n      | apply SD_Trans with (TUnion (TPair ta tb'1) (TPair ta tb'2)); apply SD_Distr2 || apply SD_UnionL;\n         [ apply union_right_1; apply IHtb'1 | apply union_right_2; apply IHtb'2 ]; assumption || constructor ] ])).\n-\n(intros ta tb Hsub1 Hsub2).\n(rewrite unite_pairs_union_t).\n(apply SD_Trans with (TPair (TUnion ta'1 ta'2) tb)).\n+\n(constructor; constructor || assumption).\n+\n(apply SD_Trans with (TUnion (TPair ta'1 tb) (TPair ta'2 tb))).\n(apply SD_Distr1).\n(apply SD_UnionL).\n(apply union_right_1; apply IHta'1; assumption || constructor).\n(apply union_right_2; apply IHta'2; assumption || constructor).\nQed.\nTheorem mk_nf__sub_d_eq : forall t : ty, |- MkNF( t) << t /\\ |- t << MkNF( t).\nProof.\n(induction t).\n-\n(split; simpl; constructor).\n-\n(destruct IHt1; destruct IHt2).\n(split; simpl).\n(apply unite_pairs__preserves_sub_d_l; assumption).\n(apply unite_pairs__preserves_sub_d_r; assumption).\n-\n(destruct IHt1; destruct IHt2).\n(split; simpl; constructor; (apply union_right_1; assumption) || (apply union_right_2; assumption)).\n-\n(simpl).\n(destruct IHt).\n(split; constructor; assumption).\nQed.\nLemma mk_nf__sub_d_l : forall t : ty, |- MkNF( t) << t.\nProof.\n(apply mk_nf__sub_d_eq).\nQed.\nLemma mk_nf__sub_d_r : forall t : ty, |- t << MkNF( t).\nProof.\n(apply mk_nf__sub_d_eq).\nQed.\nLemma cname_sem_sub_k__sub_d :\n  forall (k : nat) (c : cname), | TCName c | <= k -> forall t2 : ty, ||-[ k][TCName c]<= [t2] -> |- TCName c << t2.\nProof.\n(intros k c Hdep t2).\n(assert (Hva : value_type (TCName c)) by constructor).\n(assert (Hma : |-[ k] TCName c <$ TCName c) by (apply match_ty_value_type__reflexive; assumption)).\n(induction t2; intros Hsem; try (solve [ specialize (Hsem _ Hma); destruct k; simpl in Hsem; subst; constructor || contradiction ])).\n-\n(apply value_sem_sub_k_union__inv in Hsem; try assumption).\n(destruct Hsem as [Hsem| Hsem]; [ apply union_right_1 | apply union_right_2 ]; tauto).\nQed.\nLemma pair_sem_sub_k__sub_d :\n  forall (k : nat) (ta1 ta2 : ty),\n  atom_type (TPair ta1 ta2) ->\n  | TPair ta1 ta2 | <= k ->\n  (forall tb1 : ty, ||-[ k][ta1]<= [tb1] -> |- ta1 << tb1) ->\n  (forall tb2 : ty, ||-[ k][ta2]<= [tb2] -> |- ta2 << tb2) -> forall t2 : ty, ||-[ k][TPair ta1 ta2]<= [t2] -> |- TPair ta1 ta2 << t2.\nProof.\n(intros k ta1 ta2 Hat Hdep IH1 IH2).\n(assert (Hva : value_type (TPair ta1 ta2)) by (apply atom_type__value_type; assumption)).\n(assert (Hma : |-[ k] TPair ta1 ta2 <$ TPair ta1 ta2) by (apply match_ty_value_type__reflexive; assumption)).\n(induction t2; intros Hsem; try (solve [ specialize (Hsem _ Hma); destruct k; simpl in Hsem; subst; constructor || contradiction ])).\n-\nclear IHt2_1 IHt2_2.\n(destruct (sem_sub_k_pair__inv _ _ _ _ _ Hdep Hsem) as [Hsem1 Hsem2]).\n(constructor; [ apply IH1 | apply IH2 ]; tauto).\n-\n(apply value_sem_sub_k_union__inv in Hsem; try assumption).\n(destruct Hsem as [Hsem| Hsem]; [ apply union_right_1 | apply union_right_2 ]; tauto).\nQed.\nLemma nf_sem_sub_k__sub_d : forall (k : nat) (t1 : ty), InNF( t1) -> | t1 | <= k -> forall t2 : ty, ||-[ k][t1]<= [t2] -> |- t1 << t2.\nProof.\n(induction k;\n  match goal with\n  | |- forall t1 : ty, InNF( t1) -> | t1 | <= ?k -> forall t2 : ty, ||-[ ?k][t1]<= [t2] -> |- t1 << t2 =>\n        apply\n         (in_nf_mut (fun (t1 : ty) (_ : atom_type t1) => | t1 | <= k -> forall t2 : ty, ||-[ k][t1]<= [t2] -> |- t1 << t2)\n            (fun (t1 : ty) (_ : in_nf t1) => | t1 | <= k -> forall t2 : ty, ||-[ k][t1]<= [t2] -> |- t1 << t2))\n  end;\n  try\n   match goal with\n   | |- context [ |- TCName _ << _ ] => apply cname_sem_sub_k__sub_d\n   | |- context [ |- TPair _ _ << _ ] =>\n         intros ta1 ta2 Hat1 IH1 Hat2 IH2 Hdep; assert (Hatp : atom_type (TPair ta1 ta2)) by (constructor; assumption);\n          destruct (max_inv_depth_le__inv _ _ _ Hdep) as [Hdep1 Hdep2]; specialize (IH1 Hdep1); specialize \n          (IH2 Hdep2); apply pair_sem_sub_k__sub_d; assumption\n   | |- context [ |- TUnion _ _ << _ ] =>\n         intros t1 t2 Hnf1 IH1 Hnf2 IH2 Hdep; destruct (max_inv_depth_le__inv _ _ _ Hdep) as [Hdep1 Hdep2]; intros t' Hsem;\n          apply sem_sub_k_union_l__inv in Hsem; destruct Hsem as [Hsem1 Hsem2]; constructor; auto\n   | |- forall ta : ty, atom_type ta -> _ => tauto\n   end).\n-\n(intros t Hnft IHt Hdep).\n(inversion Hdep).\n-\n(intros t Hnft IH).\n(intros Hdep t2).\n(assert (Hva : value_type (TRef t)) by constructor).\n(assert (Hma : |-[ S k] TRef t <$ TRef t) by (apply match_ty_value_type__reflexive; assumption)).\n(induction t2; intros Hsem; try (solve [ specialize (Hsem _ Hma); contradiction ])).\n+\n(apply value_sem_sub_k_union__inv in Hsem; try assumption).\n(destruct Hsem as [Hsem| Hsem]; [ apply union_right_1 | apply union_right_2 ]; tauto).\n+\nclear IHt2.\n(simpl in Hdep).\n(pose proof (le_S_n _ _ Hdep) as Hdep').\n(unfold sem_sub_k in Hsem).\nspecialize (Hsem _ Hma).\n(apply match_ty_ref__inv in Hsem).\n(destruct Hsem as [t' [Heqt' [[Hk Hdt't2] Href]]]).\n(* Auto-generated comment: Succeeded. *)\n\n", "meta": {"author": "uwplse", "repo": "analytics-data", "sha": "64d3fccac3a25230d1adb59fcf1aded3f375029a", "save_path": "github-repos/coq/uwplse-analytics-data", "path": "github-repos/coq/uwplse-analytics-data/analytics-data-64d3fccac3a25230d1adb59fcf1aded3f375029a/diffs-annotated-fixed-2/7/user-7-session-84.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.24756164494591587}}
{"text": "(** Authors: Jianzhou Zhao. *)\n\nRequire Import LinF_PreLib.\nRequire Import LinF_Renaming.\nRequire Export LinF_OParametricity.\nRequire Import LinF_OParametricity_Macro.\nRequire Export LinF_ContextualEq_Def.\nRequire Import LinF_ContextualEq_Infrastructure.\nRequire Export LinF_ContextualEq_Lemmas.\nRequire Export LinF_ContextualEq_Sound.\nRequire Export LinF_OContextualEq_Lemmas.\n\nExport OParametricity.\n\nDefinition F_ological_related E lE e e' t : Prop :=\n  typing E lE e t /\\\n  typing E lE e' t /\\\n  exists L,\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n   disjdom L (fv_env Env) ->\n   disjdom L (fv_lenv lEnv) ->\n   F_Related_osubst E lE gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n   F_Rosubst E rsubst dsubst dsubst' Env ->\n   F_Related_oterms t rsubst dsubst dsubst'\n                                 (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n                                 (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e'))) Env lEnv.\n\nLemma F_ological_related_congruence__abs_free :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  forall L0,\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n   disjdom L0 (fv_env Env) ->\n   disjdom L0 (fv_lenv lEnv) ->\n   F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n   F_Rosubst E rsubst dsubst dsubst' Env ->\n   F_Related_oterms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n     Env lEnv\n  ) ->\n  forall L K T1' C1 T2' E' D',\n  wf_typ E' T1' kn_nonlin ->\n  (forall x,\n    x `notin` L ->\n    contexting E D T (open_ec C1 x) ((x, bind_typ T1')::E') D' T2'\n  ) ->\n  (forall x,\n    x `notin` L ->\n   typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom L0 (fv_env Env) ->\n     disjdom L0 (fv_lenv lEnv) ->\n     F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E rsubst dsubst dsubst' Env ->\n     F_Related_oterms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n      Env lEnv\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom (L0 `union` cv_ec (open_ec C1 x) `union` fv_ec (open_ec C1 x) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` (add x (dom E')) `union` dom D') (fv_env Env) ->\n     disjdom (L0 `union` cv_ec (open_ec C1 x) `union` fv_ec (open_ec C1 x) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` (add x (dom E')) `union` dom D') (fv_lenv lEnv) ->\n     F_Related_osubst ((x, bind_typ T1')::E') D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst ((x, bind_typ T1')::E') rsubst dsubst dsubst' Env ->\n     F_Related_oterms T2' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug (open_ec C1 x) e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug (open_ec C1 x) e'))))\n      Env lEnv\n  ) ->\n  (K = kn_nonlin -> D' = lempty) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n  disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D') (fv_env Env) ->\n  disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D') (fv_lenv lEnv) ->\n  F_Related_osubst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n  F_Rosubst E' rsubst dsubst dsubst' Env  ->\n  F_Related_oterms (typ_arrow K T1' T2') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug C1 (shift_ee e))))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug C1 (shift_ee e'))))))\n      Env lEnv.\nProof.\n    intros e e' E D T Htyp Htyp' L0 Hlr L K T1' C1 T2' E' D' H H1 H2 H3 dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv Disj00 Disj01 Hrel_sub HRsub.\n    assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J. \n    destruct J as [[[[[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe] Hwfe'] HwfEnv] HwflEnv].\n\n    rename H into WFTV.\n    \n    assert (value (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug C1 (shift_ee e))))))) as Value.\n      clear Disj00 Disj01.\n      apply delta_gamma_lgamma_osubst_value with (E:=E') (D:=D') (Env:=Env) (lEnv:=lEnv); auto.\n        apply FrTyping__absvalue with (L:=L `union` cv_ec C1) (E:=E') (D:=D') (T1:=T2') (K:=kn_nonlin); auto.\n          intros x xn.\n          assert (x `notin` L) as xnFv. auto.\n          apply H1 in xnFv.\n          apply contexting_plug_typing with (e:=e) in xnFv; auto.\n          simpl_env in xnFv.\n          rewrite open_ee_expr with (e:=e) (u:=x) in xnFv; auto.\n          assert (disjdom ((fv_ee x) `union` (fv_te x)) (cv_ec C1)) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite <- open_ee_plug in xnFv; auto. \n          rewrite shift_ee_expr with (e:=e) in xnFv; auto.\n    assert (value (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug C1 (shift_ee e'))))))) as Value'.\n      clear Disj00 Disj01.\n      apply delta_gamma_lgamma_osubst_value with (E:=E') (D:=D') (Env:=Env) (lEnv:=lEnv); auto.\n        apply FrTyping__absvalue with (L:=L `union` cv_ec C1) (E:=E') (D:=D') (T1:=T2') (K:=kn_nonlin); auto.\n          intros x xn.\n          assert (x `notin` L) as xnFv. auto.\n          apply H1 in xnFv.\n          apply contexting_plug_typing with (e:=e') in xnFv; auto.\n          simpl_env in xnFv.\n          rewrite open_ee_expr with (e:=e') (u:=x) in xnFv; auto.\n          assert (disjdom ((fv_ee x) `union` (fv_te x)) (cv_ec C1)) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite <- open_ee_plug in xnFv; auto. \n          rewrite shift_ee_expr with (e:=e') in xnFv; auto.\n    exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug C1 (shift_ee e)))))).\n    exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug C1 (shift_ee e')))))).\n    split.\n      clear Disj00 Disj01.\n      assert (typing E' D' (plug (ctx_abs_free K T1' C1) e) (typ_arrow K T1' T2')) as Hptyp.\n        apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n           apply contexting_abs_free with (L:=L); auto.\n      apply typing_osubst with (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst) (Env:=Env) (lEnv:=lEnv) in Hptyp; auto.\n    split. \n      clear Disj00 Disj01.\n      assert (typing E' D' (plug (ctx_abs_free K T1' C1) e') (typ_arrow K T1' T2')) as Hptyp'.\n        apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n           apply contexting_abs_free with (L:=L); auto.\n      apply typing_osubst with (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst') (Env:=Env) (lEnv:=lEnv) in Hptyp'; auto.\n    split. split; auto.\n    split. split; auto.\n      SCase \"Frel\".\n      apply F_Related_ovalues_arrow_req.\n      split; auto.\n      split; auto.\n      SSCase \"arrow\".\n        exists {}.\n        intros lEnv1 x x' Htyping Htyping' Hwfle Disj Harrow_left.\n        pick fresh z.\n        assert (z `notin` L) as Fry. auto.\n        assert (wf_typ ([(z, bind_typ T1')]++E') T2' kn_lin) as WFT'. \n          apply H1 in Fry.\n          apply contexting_regular in Fry.\n          decompose [and] Fry; auto.\n        assert (lEnv1 = nil) as EQ.\n          apply value_nonlin_inversion in Htyping; subst; auto.\n            apply F_Related_ovalues_inversion in Harrow_left.\n            decompose [prod] Harrow_left; auto.\n\n            apply wft_osubst with (E:=E') (dsubst:=dsubst); auto.\n        subst.\n        assert (F_Related_osubst ([(z, bind_typ T1')]++E') D' ([(z,x)]++gsubst) ([(z,x')]++gsubst') lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv) as Hrel_sub'.           \n          apply F_Related_osubst_typ; auto.\n        assert (F_Rosubst ([(z, bind_typ T1')]++E') rsubst dsubst dsubst' Env) as HRsub'. \n          apply F_Rosubst_typ; auto.\n        apply H2 with (dsubst:=dsubst) (gsubst:=[(z,x)]++gsubst) (lgsubst:=lgsubst) (dsubst':=dsubst') (gsubst':=[(z,x')]++gsubst') (lgsubst':=lgsubst') (rsubst:=rsubst) (Env:=Env) (lEnv:=lEnv) in Fry; auto.\n        clear Disj00 Disj01.\n        simpl_env in Fry.\n        assert (\n            apply_delta_subst dsubst (apply_gamma_subst ([(z,x)]++gsubst) (apply_gamma_subst lgsubst (plug (open_ec C1 z) e))) =\n            apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (subst_ee z x (plug (open_ec C1 z) e))))\n                  ) as Heq1. simpl. \n           rewrite swap_subst_ee_olgsubst with (E:=E')(D:=D') (Env:=Env) (lEnv:=lEnv) (lEnv':=nil) (dsubst:=dsubst)(lgsubst:=lgsubst)(gsubst:=gsubst)(t:=apply_delta_subst_typ dsubst T1'); auto.\n             apply wf_lgamma_osubst__nfv with (x:=z) in Hwflg; auto.\n         assert (\n            apply_delta_subst dsubst' (apply_gamma_subst ([(z,x')]++gsubst') (apply_gamma_subst lgsubst' (plug (open_ec C1 z) e'))) =\n            apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (subst_ee z x' (plug (open_ec C1 z) e'))))\n                  ) as Heq2.  simpl.\n           rewrite swap_subst_ee_olgsubst with (E:=E')(D:=D')(Env:=Env) (lEnv:=lEnv) (lEnv':=nil) (dsubst:=dsubst')(lgsubst:=lgsubst')(gsubst:=gsubst')(t:=apply_delta_subst_typ dsubst' T1'); auto.\n             apply wf_lgamma_osubst__nfv with (x:=z) in Hwflg'; auto.\n         rewrite Heq1 in Fry. rewrite Heq2 in Fry. clear Heq1 Heq2.\n         destruct Fry as [v [v' [Ht [Ht' [[Hbrc Hv] [[Hbrc' Hv'] Hrel]]]]]].\n         exists (v). exists (v').\n         split.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst dsubst (apply_gamma_subst gsubst  (apply_gamma_subst lgsubst (subst_ee z x (plug (open_ec C1 z) e)))))); auto.\n              rewrite <- shift_ee_expr; auto.\n             assert (plug (open_ec C1 z) e = open_ee (plug C1 e) z) as EQ.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n                eapply disjdom_app_l.\n                split.\n                  apply disjdom_one_2; auto.\n                  simpl. apply disjdom_nil_1.\n             rewrite EQ.\n             eapply m_red_abs_osubst with (T1:=T2') (L:=L `union` cv_ec C1); eauto.\n               apply F_Related_ovalues_inversion in Harrow_left.\n               decompose [prod] Harrow_left; auto.\n\n               assert (typing E' D' (plug (ctx_abs_free K T1' C1) e) (typ_arrow K T1' T2')) as Hptyp.\n                 apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n                   apply contexting_abs_free with (L:=L); auto.\n               apply notin_fv_ee_typing with (y:=z) in Hptyp; auto.\n               simpl in Hptyp.\n               rewrite <- shift_ee_expr in Hptyp; auto.\n\n               intros x0 x0dom.\n               assert (x0 `notin` L) as x0n. auto.\n               apply H1 in x0n.\n               assert (disjdom ((fv_ee x0) `union` fv_te x0) (cv_ec C1)) as Disj'.\n                 eapply disjdom_app_l.\n                 split.\n                   apply disjdom_one_2; auto.\n                   simpl. apply disjdom_nil_1.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n               apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.       \n         split; auto.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (subst_ee z x' (plug (open_ec C1 z) e')))))); auto.\n              rewrite <- shift_ee_expr; auto.\n             assert (plug (open_ec C1 z) e' = open_ee (plug C1 e') z) as EQ.\n               assert (disjdom (fv_ee z `union` fv_te z) (cv_ec C1)) as Disj'.\n                 eapply disjdom_app_l.\n                 split.\n                   apply disjdom_one_2; auto.\n                   simpl. apply disjdom_nil_1.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n             rewrite EQ.\n             eapply m_red_abs_osubst with (T1:=T2') (L:=L `union` cv_ec C1); eauto.\n               apply F_Related_ovalues_inversion in Harrow_left.\n               decompose [prod] Harrow_left; auto.\n\n               assert (typing E' D' (plug (ctx_abs_free K T1' C1) e') (typ_arrow K T1' T2')) as Hptyp.\n                 apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n                   apply contexting_abs_free with (L:=L); auto.\n               apply notin_fv_ee_typing with (y:=z) in Hptyp; auto.\n               simpl in Hptyp.\n               rewrite <- shift_ee_expr in Hptyp; auto.\n\n               intros x0 x0dom.\n               assert (x0 `notin` L) as x0n. auto.\n               apply H1 in x0n.\n               assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec C1)) as Disj'.\n                 eapply disjdom_app_l.\n                 split.\n                   apply disjdom_one_2; auto.\n                   simpl. apply disjdom_nil_1.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n               apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.       \n\n        clear - Fr Disj00.\n        assert (J:=@open_ec_fv_ec_upper C1 z).\n        assert (J':=@cv_ec_open_ec_rec C1 0 z).\n        unfold open_ec in *.\n        apply disjdom_sym_1.\n        apply disjdom_sub with (D1:={{z}} `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D').\n          eapply disjdom_app_r.\n          split; auto.\n            destruct_notin.\n            clear - NotInTac16.\n            apply disjdom_one_2; auto.\n           \n            rewrite J'.\n            clear - J. simpl in J. fsetdec.\n\n        clear - Fr Disj01.\n        assert (J:=@open_ec_fv_ec_upper C1 z).\n        assert (J':=@cv_ec_open_ec_rec C1 0 z).\n        unfold open_ec in *.\n        apply disjdom_sym_1.\n        apply disjdom_sub with (D1:={{z}} `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D').\n          eapply disjdom_app_r.\n          split; auto.\n            destruct_notin.\n            clear - NotInTac23.\n            apply disjdom_one_2; auto.\n           \n            rewrite J'.\n            clear - J. simpl in J. fsetdec.\nQed.\n\nLemma F_ological_related_congruence__labs_free :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  forall L0,\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n   disjdom L0 (fv_env Env) ->\n   disjdom L0 (fv_lenv lEnv) ->\n   F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n   F_Rosubst E rsubst dsubst dsubst' Env ->\n   F_Related_oterms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n     Env lEnv\n  ) ->\n  forall L K T1' C1 T2' E' D',\n  wf_typ E' T1' kn_lin ->\n  (forall x,\n    x `notin` L ->\n    contexting E D T (open_ec C1 x) E' ((x, lbind_typ T1')::D') T2'\n  ) ->\n  (forall x,\n    x `notin` L ->\n   typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom L0 (fv_env Env) ->\n     disjdom L0 (fv_lenv lEnv) ->\n     F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E rsubst dsubst dsubst' Env ->\n     F_Related_oterms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n      Env lEnv\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom (L0 `union` cv_ec (open_ec C1 x) `union` fv_ec (open_ec C1 x) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` (add x (dom D'))) (fv_env Env) ->\n     disjdom (L0 `union` cv_ec (open_ec C1 x) `union` fv_ec (open_ec C1 x) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` (add x (dom D'))) (fv_lenv lEnv) ->\n     F_Related_osubst E' ((x, lbind_typ T1')::D') gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E' rsubst dsubst dsubst' Env ->\n     F_Related_oterms T2' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug (open_ec C1 x) e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug (open_ec C1 x) e'))))\n      Env lEnv\n  ) ->\n  (K = kn_nonlin -> D' = lempty) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n  disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D') (fv_env Env) ->\n  disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D') (fv_lenv lEnv) ->\n  F_Related_osubst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n  F_Rosubst E' rsubst dsubst dsubst' Env  ->\n  F_Related_oterms (typ_arrow K T1' T2') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug C1 (shift_ee e))))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug C1 (shift_ee e'))))))\n      Env lEnv.\nProof.\n    intros e e' E D T Htyp Htyp' L0 Hlr L K T1' C1 T2' E' D' H H1 H2 H3 dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv Disj00 Disj01 Hrel_sub HRsub.\n    assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J. \n    destruct J as [[[[[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe] Hwfe'] HwfEnv] HwflEnv].\n\n    rename H into WFTV.\n\n    assert (value (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug C1 (shift_ee e))))))) as Value.\n      clear Disj00 Disj01.\n      apply delta_gamma_lgamma_osubst_value with (E:=E') (D:=D') (Env:=Env) (lEnv:=lEnv); auto.\n        apply FrTyping__labsvalue with (L:=L `union` cv_ec C1) (E:=E') (D:=D') (T1:=T2') (K:=kn_lin); auto.\n          intros x xn.\n          assert (x `notin` L) as xnFv. auto.\n          apply H1 in xnFv.\n          apply contexting_plug_typing with (e:=e) in xnFv; auto.\n          simpl_env in xnFv.\n          rewrite open_ee_expr with (e:=e) (u:=x) in xnFv; auto.\n          assert (disjdom (fv_ee x `union` fv_te x) (cv_ec C1)) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite <- open_ee_plug in xnFv; auto. \n          rewrite shift_ee_expr with (e:=e) in xnFv; auto.\n    assert (value (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug C1 (shift_ee e'))))))) as Value'.\n      clear Disj00 Disj01.\n      apply delta_gamma_lgamma_osubst_value with (E:=E') (D:=D') (Env:=Env) (lEnv:=lEnv); auto.\n        apply FrTyping__labsvalue with (L:=L `union` cv_ec C1) (E:=E') (D:=D') (T1:=T2') (K:=kn_lin); auto.\n          intros x xn.\n          assert (x `notin` L) as xnFv. auto.\n          apply H1 in xnFv.\n          apply contexting_plug_typing with (e:=e') in xnFv; auto.\n          simpl_env in xnFv.\n          rewrite open_ee_expr with (e:=e') (u:=x) in xnFv; auto.\n          assert (disjdom (fv_ee x `union` fv_te x) (cv_ec C1)) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite <- open_ee_plug in xnFv; auto. \n          rewrite shift_ee_expr with (e:=e') in xnFv; auto.\n    \n    exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug C1 (shift_ee e)))))).\n    exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug C1 (shift_ee e')))))).\n    split.\n      clear Disj00 Disj01.\n      assert (typing E' D' (plug (ctx_abs_free K T1' C1) e) (typ_arrow K T1' T2')) as Hptyp.\n        apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n           apply contexting_labs_free with (L:=L); auto.\n      apply typing_osubst with (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst) (Env:=Env) (lEnv:=lEnv) in Hptyp; auto.\n    split.\n      clear Disj00 Disj01.\n      assert (typing E' D' (plug (ctx_abs_free K T1' C1) e') (typ_arrow K T1' T2')) as Hptyp'.\n        apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n           apply contexting_labs_free with (L:=L); auto.\n      apply typing_osubst with (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst')  (Env:=Env) (lEnv:=lEnv) in Hptyp'; auto.\n    split. split; auto.\n    split. split; auto.\n      SCase \"Frel\".\n      apply F_Related_ovalues_arrow_req.\n      split; auto.\n      split; auto.\n      SSCase \"arrow\".\n        exists (dom gsubst `union` dom lgsubst `union` dom gsubst' `union` dom lgsubst' `union` dom E `union` dom D `union` dom E' `union` dom D' `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2')).\n        intros lEnv1 x x' Htyping Htyping' Hwfle Disj' Harrow_left.\n\n        assert (disjoint lEnv1 gsubst /\\ disjoint lEnv1 lgsubst /\\ disjoint lEnv1 gsubst' /\\ disjoint lEnv1 lgsubst' /\\ disjoint lEnv1 E /\\ disjoint lEnv1 D /\\ disjoint lEnv1 E' /\\ disjoint lEnv1 D') as Disj.\n          apply disjdom_sym_1 in Disj'.\n          split.\n            apply disjdom__disjoint.\n            apply disjdom_sub with (D1:=dom gsubst `union` dom lgsubst `union` dom gsubst' `union` dom lgsubst' `union` dom E `union` dom D `union` dom E' `union` dom D' `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2')); auto.\n               fsetdec.\n          split.\n            apply disjdom__disjoint.\n            apply disjdom_sub with (D1:=dom gsubst `union` dom lgsubst `union` dom gsubst' `union` dom lgsubst' `union` dom E `union` dom D `union` dom E' `union` dom D' `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2')); auto.\n               fsetdec.\n          split.\n            apply disjdom__disjoint.\n            apply disjdom_sub with (D1:=dom gsubst `union` dom lgsubst `union` dom gsubst' `union` dom lgsubst' `union` dom E `union` dom D `union` dom E' `union` dom D' `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2')); auto.\n               fsetdec.\n          split.\n            apply disjdom__disjoint.\n            apply disjdom_sub with (D1:=dom gsubst `union` dom lgsubst `union` dom gsubst' `union` dom lgsubst' `union` dom E `union` dom D `union` dom E' `union` dom D' `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2')); auto.\n               fsetdec.\n          split.\n            apply disjdom__disjoint.\n            apply disjdom_sub with (D1:=dom gsubst `union` dom lgsubst `union` dom gsubst' `union` dom lgsubst' `union` dom E `union` dom D `union` dom E' `union` dom D' `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2')); auto.\n               fsetdec.\n          split.\n            apply disjdom__disjoint.\n            apply disjdom_sub with (D1:=dom gsubst `union` dom lgsubst `union` dom gsubst' `union` dom lgsubst' `union` dom E `union` dom D `union` dom E' `union` dom D' `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2')); auto.\n               fsetdec.\n          split.\n            apply disjdom__disjoint.\n            apply disjdom_sub with (D1:=dom gsubst `union` dom lgsubst `union` dom gsubst' `union` dom lgsubst' `union` dom E `union` dom D `union` dom E' `union` dom D' `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2')); auto.\n               fsetdec.\n            apply disjdom__disjoint.\n            apply disjdom_sub with (D1:=dom gsubst `union` dom lgsubst `union` dom gsubst' `union` dom lgsubst' `union` dom E `union` dom D `union` dom E' `union` dom D' `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2')); auto.\n               fsetdec.\n\n        pick fresh z.\n        assert (z `notin` L) as Fry. auto.\n        assert (wf_typ E' T2' kn_lin) as WFT'. \n          apply H1 in Fry.\n          apply contexting_regular in Fry.\n          decompose [and] Fry; auto.\n        assert (F_Related_osubst E' ([(z, lbind_typ T1')]++D') gsubst gsubst' ([(z,x)]++lgsubst) ([(z,x')]++lgsubst') rsubst dsubst dsubst' Env (lEnv1++lEnv)) as Hrel_sub'.        \n          apply F_Related_osubst_ltyp; auto.\n             decompose [and] Disj. split; auto.\n        apply H2 with (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=[(z,x)]++lgsubst) (dsubst':=dsubst') (gsubst':=gsubst') (lgsubst':=[(z,x')]++lgsubst') (rsubst:=rsubst) (Env:=Env) (lEnv:=lEnv1++lEnv) in Fry; auto.\n        clear Disj00 Disj01.\n        simpl_env in Fry.\n        assert (\n            apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst ([(z,x)]++lgsubst) (plug (open_ec C1 z) e))) =\n            apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (subst_ee z x (plug (open_ec C1 z) e))))\n                  ) as Heq1. simpl. reflexivity.\n         assert (\n            apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst ([(z,x')]++lgsubst') (plug (open_ec C1 z) e'))) =\n            apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (subst_ee z x' (plug (open_ec C1 z) e'))))\n                  ) as Heq2.  simpl. reflexivity.\n         rewrite Heq1 in Fry. rewrite Heq2 in Fry. clear Heq1 Heq2.\n         destruct Fry as [v [v' [Ht [Ht' [[Hbrc Hv] [[Hbrc' Hv'] Hrel]]]]]].\n         exists (v). exists (v').\n         split.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst dsubst (apply_gamma_subst gsubst  (apply_gamma_subst lgsubst (subst_ee z x (plug (open_ec C1 z) e)))))); auto.\n              rewrite <- shift_ee_expr; auto.\n             assert (plug (open_ec C1 z) e = open_ee (plug C1 e) z) as EQ.\n              assert (disjdom (fv_ee z `union` fv_te z) (cv_ec C1)) as Disj0.\n                eapply disjdom_app_l.\n                split.\n                  apply disjdom_one_2; auto.\n                  simpl. apply disjdom_nil_1.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n             rewrite EQ.\n             eapply m_red_labs_osubst with (T1:=T2') (L:=L `union` cv_ec C1) (lEnv':=lEnv1); eauto.\n               apply F_Related_ovalues_inversion in Harrow_left.\n               decompose [prod] Harrow_left; auto.\n\n               decompose [and] Disj. split; auto.\n\n               assert (typing E' D' (plug (ctx_abs_free K T1' C1) e) (typ_arrow K T1' T2')) as Hptyp.\n                 apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n                   apply contexting_labs_free with (L:=L); auto.\n               apply notin_fv_ee_typing with (y:=z) in Hptyp; auto.\n               simpl in Hptyp.\n               rewrite <- shift_ee_expr in Hptyp; auto.\n\n               intros x0 x0dom.\n               assert (x0 `notin` L) as x0n. auto.\n               apply H1 in x0n.\n               assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec C1)) as Disj0.\n                 eapply disjdom_app_l.\n                 split.\n                   apply disjdom_one_2; auto.\n                   simpl. apply disjdom_nil_1.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n               apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.       \n         split; auto.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (subst_ee z x' (plug (open_ec C1 z) e')))))); auto.\n              rewrite <- shift_ee_expr; auto.\n             assert (plug (open_ec C1 z) e' = open_ee (plug C1 e') z) as EQ.\n               assert (disjdom (fv_ee z `union` fv_te z) (cv_ec C1)) as Disj0.\n                 eapply disjdom_app_l.\n                 split.\n                   apply disjdom_one_2; auto.\n                   simpl. apply disjdom_nil_1.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n             rewrite EQ.\n             eapply m_red_labs_osubst with (T1:=T2') (L:=L `union` cv_ec C1) (lEnv':=lEnv1); eauto.\n               apply F_Related_ovalues_inversion in Harrow_left.\n               decompose [prod] Harrow_left; auto.\n\n               decompose [and] Disj. split; auto.\n\n               assert (typing E' D' (plug (ctx_abs_free K T1' C1) e') (typ_arrow K T1' T2')) as Hptyp.\n                 apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n                   apply contexting_labs_free with (L:=L); auto.\n               apply notin_fv_ee_typing with (y:=z) in Hptyp; auto.\n               simpl in Hptyp.\n               rewrite <- shift_ee_expr in Hptyp; auto.\n\n               intros x0 x0dom.\n               assert (x0 `notin` L) as x0n. auto.\n               apply H1 in x0n.\n               assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec C1)) as Disj0.\n                 eapply disjdom_app_l.\n                 split.\n                   apply disjdom_one_2; auto.\n                   simpl. apply disjdom_nil_1.\n             rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n               apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.       \n\n        clear - Fr Disj00.\n        assert (J:=@open_ec_fv_ec_upper C1 z).\n        assert (J':=@cv_ec_open_ec_rec C1 0 z).\n        unfold open_ec in *.\n        apply disjdom_sym_1.\n        apply disjdom_sub with (D1:={{z}} `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D').\n          eapply disjdom_app_r.\n          split; auto.\n            destruct_notin.\n            clear - NotInTac16.\n            apply disjdom_one_2; auto.\n           \n            rewrite J'.\n            clear - J. simpl in J. fsetdec.\n\n        clear - Fr Disj01 Disj' Disj00 Htyping Hrel_sub'.\n        assert (J:=@open_ec_fv_ec_upper C1 z).\n        assert (J':=@cv_ec_open_ec_rec C1 0 z).\n        unfold open_ec in *.\n        apply disjdom_sym_1.\n        apply disjdom_sub with (D1:={{z}} `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D').\n          eapply disjdom_app_r.\n          split; auto.\n            destruct_notin.\n            clear - NotInTac23  NotInTac24.\n            apply disjdom_one_2; simpl_env; auto.\n           \n            apply disjdom_sym_1.\n            apply disjdom_eq with (D1:=fv_lenv lEnv1 `union` fv_lenv lEnv).\n              eapply disjdom_app_l.\n              split; auto.\n                 apply disjdom_sub with (D1:=dom gsubst `union` dom lgsubst `union` dom gsubst' `union` dom lgsubst' `union` dom E `union` dom D `union` dom E' `union` dom D' `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2')); auto.\n                   apply disjdom_sym_1. \n                   apply disjdom_fv_lenv_wfle with (Env:=Env); auto.\n                     apply F_Related_osubst__inversion in Hrel_sub'; auto.\n                     decompose [prod] Hrel_sub'. clear Hrel_sub'.\n                     apply disjoint_lgamma_osubst in b4.                    \n                     decompose [and] b4. clear b4.\n                     apply disjoint_lgamma_osubst in b5.                    \n                     decompose [and] b5. clear b5.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjoint__disjdom. assumption.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjoint__disjdom.\n                       clear - H13. solve_uniq.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjoint__disjdom. assumption.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjoint__disjdom.\n                       clear - H3. solve_uniq.\n\n                       clear - Disj00.\n                       apply disjdom_sym_1.         \n                       apply disjdom_sub with (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D').\n                         apply disjdom_sym_1.         \n                         apply disjdom_sub with (fv_env Env); auto.\n                           apply fv_env__includes__dom.\n                           clear. fsetdec.\n           \n                   clear. fsetdec.\n\n                 clear - Disj01.\n                 apply disjdom_sym_1; auto.\n               simpl_env. clear. fsetdec.\n             rewrite J'. clear - J. simpl in J. fsetdec.\nQed.\n\nLemma F_ological_related_congruence__abs_capture :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  forall L0,\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n   disjdom L0 (fv_env Env) ->\n   disjdom L0 (fv_lenv lEnv) ->\n   F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n   F_Rosubst E rsubst dsubst dsubst' Env ->\n   F_Related_oterms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n     Env lEnv\n  ) ->\n  forall K y T1' C1 T2' E' D',\n  wf_typ (env_remove (y, bind_typ T1') E') T1' kn_nonlin ->\n  binds y (bind_typ T1') E' ->\n  y `notin` dom D `union` cv_ec C1 ->\n  contexting E D T C1 E' D' T2' ->\n  (K = kn_nonlin -> D' = lempty) ->\n  (typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom L0 (fv_env Env) ->\n     disjdom L0 (fv_lenv lEnv) ->\n     F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E rsubst dsubst dsubst' Env ->\n     F_Related_oterms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n      Env lEnv\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` dom D') (fv_env Env) ->\n     disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` dom D') (fv_lenv lEnv) ->\n     F_Related_osubst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E' rsubst dsubst dsubst' Env ->\n     F_Related_oterms T2' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n      Env lEnv\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n  disjdom (L0 `union` ({{y}} `union` cv_ec (close_ec C1 y)) `union` fv_ec (close_ec C1 y) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom (env_remove (y, bind_typ T1') E') `union` dom D') (fv_env Env) ->\n  disjdom (L0 `union` ({{y}} `union` cv_ec (close_ec C1 y)) `union` fv_ec (close_ec C1 y) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom (env_remove (y, bind_typ T1') E') `union` dom D') (fv_lenv lEnv) ->\n  F_Related_osubst (env_remove (y, bind_typ T1') E') D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n  F_Rosubst (env_remove (y, bind_typ T1') E') rsubst dsubst dsubst' Env  ->\n  F_Related_oterms (typ_arrow K T1' T2') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e) y))))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e') y))))))\n      Env lEnv.\nProof.\n    intros e e' E D T Htyp Htyp' L0 Hlr K y T1' C1 T2' E' D' H H0 H1 Hcontexting H2 IHHcontexting dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv Disj00 Disj01 Hrel_sub HRsub. \n    assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J. \n    destruct J as [[[[[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe] Hwfe'] HwfEnv] HwflEnv].\n\n    rename H into WFTV.\n    \n    assert (wf_typ E' T2' kn_lin) as WFT'. \n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (Fry := @IHHcontexting Htyp Htyp' Hlr).\n    assert (wf_env E') as Wfe'.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (EQ1:=@env_remove_typ_inv E' y T1'  Wfe' H0).\n    destruct EQ1 as [E1' [E2' [EQ1' [EQ2' Sub]]]]; subst.\n    rewrite EQ1' in *.\n\n    assert (EQ:=Hwflg).\n    apply wf_olgsubst_app_inv in EQ.\n    destruct EQ as [dsubst1 [dsubst2 [gsubst1 [gsubst2 [dEQ1 [dEQ2 [dEQ3 [gEQ1 [gEQ2 gEQ3]]]]]]]]]; subst.\n\n    assert (EQ:=Hwflg').\n    apply wf_olgsubst_app_inv in EQ.\n    destruct EQ as [dsubst1' [dsubst2' [gsubst1' [gsubst2' [dEQ1' [dEQ2' [dEQ3' [gEQ1' [gEQ2' gEQ3']]]]]]]]]; subst.\n       \n    assert (EQ:=Hwfr).\n    apply wf_rsubst_app_inv in EQ.\n    destruct EQ as [rsubst1 [rsubst2 [rEQ1 [rEQ2 rEQ3]]]]; subst.\n\n    assert (wf_typ E2' T1' kn_nonlin) as WFTV'.\n    apply wft_strengthen_sub with (F:=E1'); auto.\n\n    assert (value (apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e) y))))))) as Value.\n      clear Disj00 Disj01.\n      apply delta_gamma_lgamma_osubst_value with (Env:=Env) (lEnv:=lEnv) (E:=E1'++E2') (D:=D'); auto.\n        apply FrTyping__absvalue with (L:=dom (E1'++E2') `union` dom D' `union` cv_ec (close_ec C1 y) `union` cv_ec C1 `union` dom Env `union` dom lEnv) (E:=E1'++E2') (D:=D') (T1:=T2') (K:=kn_nonlin); auto.\n          intros x xnFv.\n          rewrite <- shift_ee_expr with (e:=e); auto.\n          assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite open_ee_plug; auto. \n          rewrite close_open_ee__subst_ee; auto.\n          assert (context C1) as Ctx1.\n            apply contexting__context in Hcontexting; auto.\n          rewrite close_open_ec__subst_ec; auto.\n          assert (disjdom (union {{y}} (fv_ee x `union` fv_te x)) (cv_ec C1)) as Disj'.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n            eapply disjdom_app_l.\n            split.\n               apply disjdom_one_2; auto.\n               simpl. apply disjdom_nil_1.\n          rewrite <- subst_ee_plug; auto. \n          assert (typing (E1'++[(y, bind_typ T1')]++E2') D' (plug C1 e) T2') as Htyp2.\n            apply contexting_plug_typing with (e:=e) in Hcontexting; auto.\n          apply typing_nonlin_renaming_permute with (x:=y); auto.\n    assert (value (apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (exp_abs K T1' (plug (close_ec C1 y)  (close_ee (shift_ee e') y))))))) as Value'.\n      clear Disj00 Disj01.\n      apply delta_gamma_lgamma_osubst_value with (E:=E1'++E2') (D:=D') (Env:=Env) (lEnv:=lEnv); auto.\n        apply FrTyping__absvalue with (L:=dom (E1'++E2') `union` dom D' `union` cv_ec (close_ec C1 y) `union` cv_ec C1 `union` dom Env `union` dom lEnv) (E:=E1'++E2') (D:=D') (T1:=T2') (K:=kn_nonlin); auto.\n          intros x xnFv.\n          rewrite <- shift_ee_expr with (e:=e'); auto.\n          assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite open_ee_plug; auto. \n          rewrite close_open_ee__subst_ee; auto.\n          assert (context C1) as Ctx1.\n            apply contexting__context in Hcontexting; auto.\n          rewrite close_open_ec__subst_ec; auto.\n          assert (disjdom (union {{y}} (fv_ee x `union` fv_te x)) (cv_ec C1)) as Disj'.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite <- subst_ee_plug; auto. \n          assert (typing (E1'++[(y, bind_typ T1')]++E2') D' (plug C1 e') T2') as Htyp2'.\n            apply contexting_plug_typing with (e:=e') in Hcontexting; auto.\n          apply typing_nonlin_renaming_permute with (x:=y); auto.\n    exists (apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e) y)))))).\n    exists (apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e') y)))))).\n    split.\n      assert (typing (E1'++E2') D' (plug (ctx_abs_capture K y T1' (close_ec C1 y)) e) (typ_arrow K T1' T2')) as Hptyp.\n        clear Disj00 Disj01.\n        destruct (in_dec y (fv_ee e)) as [yine | ynine].\n          simpl.\n          apply typing_abs with (L:=dom (E1'++E2') `union` dom D' `union` dom E `union` dom D `union` {{y}} `union` cv_ec C1 `union` cv_ec (close_ec C1 y) `union` dom Env `union` dom lEnv); auto.\n            intros x xn.\n            rewrite <- shift_ee_expr; auto.\n            assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n              eapply disjdom_app_l.\n              split.\n                apply disjdom_one_2; auto.\n                simpl. apply disjdom_nil_1.\n            rewrite open_ee_plug; auto.\n            assert (y `in` gdom_env E \\/ y `in` dom D) as yED.\n              assert (y `in` gdom_env E `union` dom D) as J.\n                apply in_fv_ee_typing' with (x:=y) in Htyp; auto.\n              fsetdec.\n            rewrite close_open_ee__subst_ee; auto.\n            assert (context C1) as Ctx1.\n              apply contexting__context in Hcontexting; auto.\n            rewrite close_open_ec__subst_ec; auto.\n            destruct yED as [yE | yD].\n              apply gbinds_In_inv in yE.\n              destruct yE as [t Binds].\n              assert (wf_env E) as Wfe. auto.\n              assert (J:=@env_remove_inv E y (bind_typ t) Wfe Binds).\n              destruct J as [E1 [E2 [EQ1 EQ2]]]; subst.\n\n              apply typing_nonlin_permute; auto. \n              apply contexting_plug_typing with (E:=E1++[(x, bind_typ t)]++E2) (D:=D) (T:=T); auto.\n\n                apply contexting_nonlin_renaming_one; auto.\n\n                simpl_env in xn.\n                apply typing_nonlin_renaming_one with (x:=y); auto.\n\n              contradict yD; auto.\n          rewrite <- EQ1'.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n            apply contexting_abs_capture; auto.\n              rewrite EQ1'. auto.\n      apply typing_osubst with (dsubst:=dsubst1++dsubst2) (gsubst:=gsubst1++gsubst2) (lgsubst:=lgsubst) (Env:=Env) (lEnv:=lEnv) in Hptyp; auto.\n    split.\n      assert (typing (E1'++E2') D' (plug (ctx_abs_capture K y T1' (close_ec C1 y)) e') (typ_arrow K T1' T2')) as Hptyp'.\n        clear Disj00 Disj01.\n        destruct (in_dec y (fv_ee e')) as [yine | ynine'].\n          simpl.\n          apply typing_abs with (L:=dom (E1'++E2') `union` dom D' `union` dom E `union` dom D `union` cv_ec C1 `union` cv_ec (close_ec C1 y) `union` dom Env `union` dom lEnv); auto.\n            intros x xn.\n            rewrite <- shift_ee_expr; auto.\n            assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n              eapply disjdom_app_l.\n              split.\n                apply disjdom_one_2; auto.\n                simpl. apply disjdom_nil_1.\n            rewrite open_ee_plug; auto.\n            assert (y `in` gdom_env E \\/ y `in` dom D) as yED.\n              assert (y `in` gdom_env E `union` dom D) as J.\n                apply in_fv_ee_typing' with (x:=y) in Htyp'; auto.\n              fsetdec.\n            rewrite close_open_ee__subst_ee; auto.\n            assert (context C1) as Ctx1.\n              apply contexting__context in Hcontexting; auto.\n            rewrite close_open_ec__subst_ec; auto.\n            destruct yED as [yE | yD].\n              apply gbinds_In_inv in yE.\n              destruct yE as [t Binds].\n              assert (wf_env E) as Wfe. auto.\n              assert (J:=@env_remove_inv E y (bind_typ t) Wfe Binds).\n              destruct J as [E1 [E2 [EQ1 EQ2]]]; subst.\n              apply typing_nonlin_permute; auto. \n              apply contexting_plug_typing with (E:=E1++[(x, bind_typ t)]++E2) (D:=D) (T:=T); auto.\n                apply contexting_nonlin_renaming_one; auto.\n\n                simpl_env in xn.\n                apply typing_nonlin_renaming_one with (x:=y); auto.\n\n              contradict yD; auto.\n          rewrite <- EQ1'.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n            apply contexting_abs_capture; auto.\n              rewrite EQ1'. auto.\n      apply typing_osubst with (dsubst:=dsubst1'++dsubst2') (gsubst:=gsubst1'++gsubst2') (lgsubst:=lgsubst') (Env:=Env) (lEnv:=lEnv) in Hptyp'; auto.\n    split. split; auto.\n    split. split; auto.\n      SCase \"Frel\".\n      apply F_Related_ovalues_arrow_req.\n      split; auto.\n      split; auto.\n      SSCase \"arrow\".\n        exists {}.\n        intros lEnv1 x x' Htyping Htyping' Hwfle Disj Harrow_left.\n\n        assert (lEnv1 = nil) as EQ.\n          apply value_nonlin_inversion in Htyping; subst; auto.\n            apply F_Related_ovalues_inversion in Harrow_left.\n            decompose [prod] Harrow_left; auto.\n\n            apply wft_osubst with (E:=E1'++E2') (dsubst:=dsubst1++dsubst2); auto.\n        subst.\n        assert (F_Related_ovalues T1' rsubst2 dsubst2 dsubst2' x x' Env nil) as Harrow_left'.\n          apply Forel_stronger_heads with (E:=E2') (E':=E1') in Harrow_left; auto.       \n            simpl. apply disjdom_sym_1. apply disjdom_nil_1.\n        assert (F_Related_osubst (E1'++[(y, bind_typ T1')]++E2') D' (gsubst1++[(y,x)]++gsubst2) (gsubst1'++[(y,x')]++gsubst2') lgsubst lgsubst' (rsubst1++rsubst2) (dsubst1++dsubst2) (dsubst1'++dsubst2') Env lEnv) as Hrel_sub'.\n          assert (y `notin` fv_env Env) as ynEnv.\n            clear Disj01 Sub H1 Hcontexting IHHcontexting Fry dEQ3 dEQ2 dEQ3 gEQ2 gEQ3 rEQ2 rEQ3 Value Value' Disj Htyping Htyping'.\n            apply disjdom_app_2 in Disj00.\n            apply disjdom_app_1 in Disj00.\n            apply disjdom_app_1 in Disj00.\n            destruct Disj00 as [J1 J2].\n            apply J1; auto.\n          assert (y `notin` fv_lenv lEnv) as ynlEnv.\n            clear Disj00 Sub H1 Hcontexting IHHcontexting Fry dEQ3 dEQ2 dEQ3 gEQ2 gEQ3 rEQ2 rEQ3 Value Value' Disj Htyping Htyping'.\n            apply disjdom_app_2 in Disj01.\n            apply disjdom_app_1 in Disj01.\n            apply disjdom_app_1 in Disj01.\n            destruct Disj01 as [J1 J2].\n            apply J1; auto.\n          clear Disj00 Disj01.\n          assert (y `notin` dom E1') as ynE1'.\n             apply fresh_mid_head with (E:=E2') (a:=bind_typ T1'); auto.\n          assert (y `notin` dom E2') as ynE2'.\n             apply fresh_mid_tail with (F:=E1') (a:=bind_typ T1'); auto.\n          assert (y `notin` dom D') as ynD'.\n             apply contexting_regular in Hcontexting.\n             decompose [and] Hcontexting.\n             apply wf_lenv_notin_fv_lenv with (x:=y) (T:=T1') in H6; auto.\n          apply F_Related_osubst_gweaken; auto.\n             rewrite apply_delta_osubst_typ_strenghen with (E1:=E1') (E2:=E2') (Env:=Env) in Htyping; auto.\n             rewrite apply_delta_osubst_typ_strenghen with (E1:=E1') (E2:=E2') (Env:=Env) in Htyping'; auto.\n\n        assert (F_Rosubst (E1'++[(y, bind_typ T1')] ++E2') (rsubst1++rsubst2) (dsubst1++dsubst2) (dsubst1'++dsubst2') Env) as HRsub'. \n          assert (y `notin` fv_env Env) as ynEnv.\n            clear Disj01 Sub H1 Hcontexting IHHcontexting Fry dEQ3 dEQ2 dEQ3 gEQ2 gEQ3 rEQ2 rEQ3 Value Value' Disj Htyping Htyping'.\n            apply disjdom_app_2 in Disj00.\n            apply disjdom_app_1 in Disj00.\n            apply disjdom_app_1 in Disj00.\n            destruct Disj00 as [J1 J2].\n            apply J1; auto.\n          assert (y `notin` fv_lenv lEnv) as ynlEnv.\n            clear Disj00 Sub H1 Hcontexting IHHcontexting Fry dEQ3 dEQ2 dEQ3 gEQ2 gEQ3 rEQ2 rEQ3 Value Value' Disj Htyping Htyping'.\n            apply disjdom_app_2 in Disj01.\n            apply disjdom_app_1 in Disj01.\n            apply disjdom_app_1 in Disj01.\n            destruct Disj01 as [J1 J2].\n            apply J1; auto.\n          clear Disj00 Disj01.\n          assert (y `notin` dom E1') as ynE1'.\n             apply fresh_mid_head with (E:=E2') (a:=bind_typ T1'); auto.\n          assert (y `notin` dom E2') as ynE2'.\n             apply fresh_mid_tail with (F:=E1') (a:=bind_typ T1'); auto.\n          apply F_Rosubst_gweaken; auto.       \n       assert (\n       disjdom\n         (union L0\n            (union (cv_ec C1)\n               (union (fv_ec C1)\n                  (union (dom E)\n                     (union (dom D)\n                        (union (fv_tt T)\n                           (union (fv_tt T2')\n                              (union (dom (E1' ++ [(y, bind_typ T1')] ++ E2')) (dom D')))))))))\n         (fv_env Env)) as Disj00'.\n\n           clear - Disj00.\n           assert (J:=@close_ec_fv_ec_eq C1 y).\n           assert (J':=@close_ec_fv_ec_lower C1 y).\n           apply disjdom_sym_1.\n           apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom (E1'++E2')) `union` dom D').\n             apply disjdom_sym_1; auto.\n             simpl_env. rewrite J. clear - J'. fsetdec.\n       assert (\n       disjdom\n         (union L0\n            (union (cv_ec C1)\n               (union (fv_ec C1)\n                  (union (dom E)\n                     (union (dom D)\n                        (union (fv_tt T)\n                           (union (fv_tt T2')\n                              (union (dom (E1' ++ [(y, bind_typ T1')] ++ E2')) (dom D')))))))))\n         (fv_lenv lEnv)) as Disj01'.\n           clear - Disj01.\n           assert (J:=@close_ec_fv_ec_eq C1 y).\n           assert (J':=@close_ec_fv_ec_lower C1 y).\n           apply disjdom_sym_1.\n           apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom (E1'++E2')) `union` dom D').\n             apply disjdom_sym_1; auto.\n             simpl_env. rewrite J. clear - J'. fsetdec.\n        assert (J:=@Fry (dsubst1++dsubst2) (dsubst1'++dsubst2') (gsubst1++[(y,x)]++gsubst2) (gsubst1'++[(y,x')]++gsubst2') lgsubst lgsubst' (rsubst1++rsubst2) Env lEnv Disj00' Disj01' Hrel_sub' HRsub').\n        clear Disj00' Disj01'.\n        assert (\n            apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++[(y,x)]++gsubst2) (apply_gamma_subst lgsubst (plug C1 e))) =\n            apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (subst_ee y x (plug C1 e))))\n                  ) as Heq1. simpl.\n           simpl_env.\n           rewrite gamma_osubst_opt with (E':=E1') (E:=E2') (D:=D') (dsubst:=dsubst1++dsubst2) (t:=T1') (lgsubst:=lgsubst) (Env:=Env) (lEnv:=lEnv); auto.\n            assert (y `notin` fv_env Env) as ynEnv.\n              clear Disj01 Sub H1 Hcontexting IHHcontexting Fry dEQ3 dEQ2 dEQ3 gEQ2 gEQ3 rEQ2 rEQ3 Value Value' Disj Htyping Htyping'.\n              apply disjdom_app_2 in Disj00.\n              apply disjdom_app_1 in Disj00.\n              apply disjdom_app_1 in Disj00.\n              destruct Disj00 as [J1 J2].\n              apply J1; auto.\n            assert (y `notin` fv_lenv lEnv) as ynlEnv.\n              clear Disj00 Sub H1 Hcontexting IHHcontexting Fry dEQ3 dEQ2 dEQ3 gEQ2 gEQ3 rEQ2 rEQ3 Value Value' Disj Htyping Htyping'.\n              apply disjdom_app_2 in Disj01.\n              apply disjdom_app_1 in Disj01.\n              apply disjdom_app_1 in Disj01.\n              destruct Disj01 as [J1 J2].\n              apply J1; auto.\n             clear Disj00 Disj01.\n             assert (y `notin` dom (E1'++E2')) as ynE'.\n               apply contexting_regular in Hcontexting.\n               decompose [and] Hcontexting.\n               apply uniq_from_wf_env in H5.\n               simpl_env. solve_uniq.\n             assert (y `notin` dom D') as ynD'.\n               apply contexting_regular in Hcontexting.\n               decompose [and] Hcontexting.\n               apply wf_lenv_notin_fv_lenv with (x:=y) (T:=T1') in H6; auto.\n             assert (JJ:=Hwflg).\n             apply wf_lgamma_osubst__nfv with (x:=y) in JJ; auto.\n             rewrite swap_subst_ee_olgsubst with  (D:=D') (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (t:=apply_delta_subst_typ (dsubst1++dsubst2) T1') (gsubst:=gsubst1++gsubst2) (Env:=Env) (lEnv:=lEnv) (lEnv':=nil); auto.\n\n             apply F_Related_osubst__inversion in Hrel_sub'.\n             decompose [prod] Hrel_sub'; auto.\n         assert (\n            apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++[(y,x')]++gsubst2') (apply_gamma_subst lgsubst' (plug C1 e'))) =\n            apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (subst_ee y x' (plug C1 e'))))\n                  ) as Heq2.  simpl.\n           simpl_env.\n           rewrite gamma_osubst_opt with (E':=E1') (E:=E2') (D:=D') (dsubst:=dsubst1'++dsubst2') (t:=T1') (lgsubst:=lgsubst') (Env:=Env) (lEnv:=lEnv); auto.\n            assert (y `notin` fv_env Env) as ynEnv.\n              clear Disj01 Sub H1 Hcontexting IHHcontexting Fry dEQ3 dEQ2 dEQ3 gEQ2 gEQ3 rEQ2 rEQ3 Value Value' Disj Htyping Htyping'.\n              apply disjdom_app_2 in Disj00.\n              apply disjdom_app_1 in Disj00.\n              apply disjdom_app_1 in Disj00.\n              destruct Disj00 as [J1 J2].\n              apply J1; auto.\n            assert (y `notin` fv_lenv lEnv) as ynlEnv.\n              clear Disj00 Sub H1 Hcontexting IHHcontexting Fry dEQ3 dEQ2 dEQ3 gEQ2 gEQ3 rEQ2 rEQ3 Value Value' Disj Htyping Htyping'.\n              apply disjdom_app_2 in Disj01.\n              apply disjdom_app_1 in Disj01.\n              apply disjdom_app_1 in Disj01.\n              destruct Disj01 as [J1 J2].\n              apply J1; auto.\n             clear Disj00 Disj01.\n             assert (y `notin` dom (E1'++E2')) as ynE'.\n               apply contexting_regular in Hcontexting.\n               decompose [and] Hcontexting.\n               apply uniq_from_wf_env in H5.\n               simpl_env. solve_uniq.\n             assert (y `notin` dom D') as ynD'.\n               apply contexting_regular in Hcontexting.\n               decompose [and] Hcontexting.\n               apply wf_lenv_notin_fv_lenv with (x:=y) (T:=T1') in H6; auto.\n             assert (JJ:=Hwflg').\n             apply wf_lgamma_osubst__nfv with (x:=y) in JJ; auto.\n             rewrite swap_subst_ee_olgsubst with  (D:=D') (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (t:=apply_delta_subst_typ (dsubst1'++dsubst2') T1') (gsubst:=gsubst1'++gsubst2') (Env:=Env) (lEnv:=lEnv) (lEnv':=nil); auto.\n\n             apply F_Related_osubst__inversion in Hrel_sub'.\n             decompose [prod] Hrel_sub'; auto.\n         rewrite Heq1 in J. rewrite Heq2 in J. clear Heq1 Heq2.\n         destruct J as [v [v' [Ht [Ht' [[Hbrc Hv] [[Hbrc' Hv'] Hrel]]]]]].\n         exists (v). exists (v').\n         split.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2)  (apply_gamma_subst lgsubst (subst_ee y x (plug C1 e)))))); auto.\n              assert (apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst x)) =x) as Heq1.\n                 assert (disjdom (fv_te x) (dom (dsubst1 ++ dsubst2))) as Disj03.\n                   assert (disjdom (dom (E1'++E2')) (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom (E1'++E2')) in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     simpl_env. rewrite <- dEQ2. rewrite <- dEQ3.\n                     clear - Htyping x0notin Disj001.\n                     apply in_fv_te_typing with (X:=x0) in Htyping; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply free_dom__free_env in Htyping.\n                       apply J2 in Htyping; auto.\n\n                     simpl_env in x0notin. rewrite <- dEQ2 in x0notin. rewrite <- dEQ3 in x0notin.\n                     clear - Htyping x0notin Disj001.\n                     apply notin_fv_te_typing with (X:=x0) in Htyping; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply free_env__free_dom.\n                       apply J1.\n                       apply ddom__dom; simpl_env; auto.\n                 assert (disjdom (fv_ee x) (dom lgsubst)) as Disj04.\n                   assert (disjdom (dom (D')) (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom (D')) in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     apply dom_lgamma_osubst in Hwflg.\n                     decompose [and] Hwflg.\n                     rewrite <- H5.\n                     clear - Htyping x0notin Disj001.\n                     apply in_fv_ee_typing with (x:=x0) in Htyping; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply J2.\n                       apply free_dom__free_env. fsetdec.\n\n                     apply dom_lgamma_osubst in Hwflg.\n                     decompose [and] Hwflg.\n                     rewrite <- H5 in x0notin. \n                     clear - Htyping x0notin Disj001.\n                     apply notin_fv_ee_typing with (y:=x0) in Htyping; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply J1 in x0notin.\n                       apply free_env__free_dom in x0notin; auto.\n                 assert (disjdom (fv_ee x) (dom (gsubst1 ++ gsubst2))) as Disj05.\n                   assert (disjdom (dom (E1'++E2')) (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom (E1'++E2')) in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     simpl_env. rewrite <- gEQ2. rewrite <- gEQ3.\n                     clear - Htyping x0notin Disj001.\n                     apply in_fv_ee_typing with (x:=x0) in Htyping; auto.\n                       destruct Disj001 as [J1 J2].\n                       assert (x0 `in` dom Env) as J. fsetdec.\n                       apply free_dom__free_env in J.\n                       apply J2 in J.\n                       apply dom__gdom in J.\n                       simpl_env in J; auto.\n\n                     simpl_env in x0notin. rewrite <- gEQ2 in x0notin. rewrite <- gEQ3 in x0notin.\n                     clear - Htyping x0notin Disj001.\n                     apply notin_fv_ee_typing with (y:=x0) in Htyping; auto.\n                       destruct Disj001 as [J1 J2].\n                       assert (x0 `in` gdom_env (E1'++E2')) as J. simpl_env. assumption.\n                       apply gdom__dom in J.                \n                       apply J1 in J.\n                       apply free_env__free_dom in J. auto.\n                 clear Disj00 Disj01.\n                 rewrite gamma_osubst_closed_exp; auto.\n                 rewrite gamma_osubst_closed_exp; auto.\n                 rewrite delta_osubst_closed_exp; auto.                   \n                 rewrite gamma_osubst_closed_exp; auto.\n              rewrite <- Heq1.\n              rewrite commut_gamma_subst_abs.\n              rewrite commut_gamma_subst_abs.\n              assert (subst_ee y (apply_delta_subst  (dsubst1++dsubst2) (apply_gamma_subst  (gsubst1++gsubst2) (apply_gamma_subst lgsubst x))) (plug C1 e) = subst_ee y x (plug C1 e)) as Heq2. \n                 rewrite Heq1. auto. \n              rewrite Heq2.\n              assert (typing (E1'++[(y, bind_typ T1')]++E2') D' (plug C1 e) T2') as Typinge.\n                apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n\n             assert (disjdom (union {{y}} (fv_ee x `union` fv_te x)) (cv_ec C1)) as Disj0.\n               eapply disjdom_app_l.\n               split.\n                 clear Disj00 Disj01.\n                 apply disjdom_one_2; auto.\n               eapply disjdom_app_l.\n               split.\n                  clear - Htyping Disj00.\n                  apply typing_fv_ee_upper in Htyping.\n                  apply disjdom_sym_1.\n                  simpl in Htyping.\n                  apply disjdom_sub with (D1:= dom Env `union` {}); auto.\n                  apply disjdom_sub with (D1:= fv_env Env).\n                    assert (J:=@close_ec_fv_ec_eq C1 y).\n                    apply disjdom_sym_1.\n                    apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom (E1'++E2')) `union` dom D').\n                      apply disjdom_sym_1; auto.\n                      simpl_env. rewrite J. clear. fsetdec.                                       \n                    assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n\n                  clear - Htyping Disj00.\n                  apply typing_fv_te_upper in Htyping.\n                  apply disjdom_sym_1.\n                  apply disjdom_sub with (D1:= dom Env `union` {}); auto.\n                    apply disjdom_sub with (D1:= fv_env Env).\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sym_1.\n                      apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom (E1'++E2')) `union` dom D').\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite J. clear. fsetdec.                                       \n                      assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n                    simpl_env. fsetdec.\n\n              rewrite subst_ee_plug; auto.\n              rewrite <- close_open_ee__subst_ee; auto.\n              assert (context C1) as Context1.\n                apply contexting__context in Hcontexting; auto.    \n              rewrite <- close_open_ec__subst_ec; auto.\n              assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj1.\n                eapply disjdom_app_l.\n                split.\n                  clear - Htyping Disj00.\n                  apply typing_fv_ee_upper in Htyping.\n                  apply disjdom_sym_1.\n                  simpl in Htyping.\n                  apply disjdom_sub with (D1:= dom Env `union` {}); auto.\n                  apply disjdom_sub with (D1:= fv_env Env).\n                    assert (J:=@close_ec_fv_ec_eq C1 y).\n                    apply disjdom_sym_1.\n                    apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom (E1'++E2')) `union` dom D').\n                      apply disjdom_sym_1; auto.\n                      simpl_env. rewrite J. clear. fsetdec.                                       \n                    assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n\n                  clear - Htyping Disj00.\n                  apply typing_fv_te_upper in Htyping.\n                  apply disjdom_sym_1.\n                  apply disjdom_sub with (D1:= dom Env `union` {}); auto.\n                    apply disjdom_sub with (D1:= fv_env Env).\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sym_1.\n                      apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom (E1'++E2')) `union` dom D').\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite J. clear. fsetdec.                                       \n                      assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n                    simpl_env. fsetdec.\n\n              rewrite <- open_ee_plug; auto.\n              rewrite commut_lgamma_osubst_open_ee with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(gsubst:=gsubst1++gsubst2) (Env:=Env) (lEnv:=lEnv); auto.\n              rewrite commut_gamma_osubst_open_ee with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(lgsubst:=lgsubst) (Env:=Env) (lEnv:=lEnv); auto.\n              rewrite <- shift_ee_expr; auto.\n              apply red_abs_preserved_under_delta_osubst with (dE:=E1'++E2') (Env:=Env); auto.\n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_gamma_osubst_open_ee with (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (D:=D') (lgsubst:=lgsubst) (Env:=Env) (lEnv:=lEnv); auto.\n              apply red_abs_preserved_under_gamma_osubst with (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (D:=D') (lgsubst:=lgsubst) (Env:=Env) (lEnv:=lEnv); auto. \n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_lgamma_osubst_open_ee with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(gsubst:=gsubst1++gsubst2) (Env:=Env) (lEnv:=lEnv); auto.\n              apply red_abs_preserved_under_lgamma_osubst with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(gsubst:=gsubst1++gsubst2) (Env:=Env) (lEnv:=lEnv); auto. \n\n              apply red_abs.\n                apply expr_abs with (L:=(cv_ec (close_ec C1 y)) `union` cv_ec C1).\n                   apply type_from_wf_typ in WFTV; assumption.\n\n                   intros.\n                   assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec (close_ec C1 y))) as Disj'.\n                     eapply disjdom_app_l.\n                     split.\n                       clear Disj00 Disj01.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite open_ee_plug; auto.\n                   rewrite close_open_ec__subst_ec; auto.\n                   rewrite close_open_ee__subst_ee; auto.\n                  assert (disjdom (union {{y}} (fv_ee x0 `union` fv_te x0)) (cv_ec C1)) as Disj0'.\n                     eapply disjdom_app_l.\n                     split.\n                       clear Disj00 Disj01.\n                       apply disjdom_one_2; auto.\n                     eapply disjdom_app_l.\n                     split.\n                       clear Disj00 Disj01.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite <- subst_ee_plug; auto.\n\n               apply F_Related_ovalues_inversion in Harrow_left'.\n               decompose [prod] Harrow_left'; auto.\n         split; auto.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (subst_ee y x' (plug C1 e')))))); auto.\n              assert (apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' x')) =x') as Heq1'.\n                 assert (disjdom (fv_te x') (dom (dsubst1' ++ dsubst2'))) as Disj03.\n                   assert (disjdom (dom (E1'++E2')) (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom (E1'++E2')) in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     simpl_env. rewrite <- dEQ2'. rewrite <- dEQ3'.\n                     clear - Htyping' x0notin Disj001.\n                     apply in_fv_te_typing with (X:=x0) in Htyping'; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply free_dom__free_env in Htyping'.\n                       apply J2 in Htyping'; auto.\n\n                     simpl_env in x0notin. rewrite <- dEQ2' in x0notin. rewrite <- dEQ3' in x0notin.\n                     clear - Htyping' x0notin Disj001.\n                     apply notin_fv_te_typing with (X:=x0) in Htyping'; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply free_env__free_dom.\n                       apply J1.\n                       apply ddom__dom; simpl_env; auto.\n                 assert (disjdom (fv_ee x') (dom lgsubst')) as Disj04.\n                   assert (disjdom (dom (D')) (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom (D')) in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     apply dom_lgamma_osubst in Hwflg'.\n                     decompose [and] Hwflg'.\n                     rewrite <- H5.\n                     clear - Htyping' x0notin Disj001.\n                     apply in_fv_ee_typing with (x:=x0) in Htyping'; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply J2.\n                       apply free_dom__free_env. fsetdec.\n\n                     apply dom_lgamma_osubst in Hwflg'.\n                     decompose [and] Hwflg'.\n                     rewrite <- H5 in x0notin. \n                     clear - Htyping' x0notin Disj001.\n                     apply notin_fv_ee_typing with (y:=x0) in Htyping'; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply J1 in x0notin.\n                       apply free_env__free_dom in x0notin; auto.\n                 assert (disjdom (fv_ee x') (dom (gsubst1' ++ gsubst2'))) as Disj05.\n                   assert (disjdom (dom (E1'++E2')) (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom (E1'++E2')) in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     simpl_env. rewrite <- gEQ2'. rewrite <- gEQ3'.\n                     clear - Htyping' x0notin Disj001.\n                     apply in_fv_ee_typing with (x:=x0) in Htyping'; auto.\n                       destruct Disj001 as [J1 J2].\n                       assert (x0 `in` dom Env) as J. fsetdec.\n                       apply free_dom__free_env in J.\n                       apply J2 in J.\n                       apply dom__gdom in J.\n                       simpl_env in J; auto.\n\n                     simpl_env in x0notin. rewrite <- gEQ2' in x0notin. rewrite <- gEQ3' in x0notin.\n                     clear - Htyping' x0notin Disj001.\n                     apply notin_fv_ee_typing with (y:=x0) in Htyping'; auto.\n                       destruct Disj001 as [J1 J2].\n                       assert (x0 `in` gdom_env (E1'++E2')) as J. simpl_env. assumption.\n                       apply gdom__dom in J.                \n                       apply J1 in J.\n                       apply free_env__free_dom in J. auto.\n                 clear Disj00 Disj01.\n                 rewrite gamma_osubst_closed_exp; auto.\n                 rewrite gamma_osubst_closed_exp; auto.\n                 rewrite delta_osubst_closed_exp; auto.                   \n                 rewrite gamma_osubst_closed_exp; auto.\n              rewrite <- Heq1'.\n              rewrite commut_gamma_subst_abs.\n              rewrite commut_gamma_subst_abs.\n              assert (subst_ee y (apply_delta_subst  (dsubst1'++dsubst2') (apply_gamma_subst  (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' x'))) (plug C1 e') = subst_ee y x' (plug C1 e')) as Heq2'. \n                 rewrite Heq1'. auto. \n              rewrite Heq2'.\n              assert (typing (E1'++[(y, bind_typ T1')]++E2') D' (plug C1 e') T2') as Typinge'.\n                apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n             assert (disjdom (union {{y}} (fv_ee x' `union` fv_te x')) (cv_ec C1)) as Disj0.\n               eapply disjdom_app_l.\n               split.\n                 clear Disj00 Disj01.\n                 apply disjdom_one_2; auto.\n               eapply disjdom_app_l.\n               split.\n                  clear - Htyping' Disj00.\n                  apply typing_fv_ee_upper in Htyping'.\n                  apply disjdom_sym_1.\n                  simpl in Htyping'.\n                  apply disjdom_sub with (D1:= dom Env `union` {}); auto.\n                  apply disjdom_sub with (D1:= fv_env Env).\n                    assert (J:=@close_ec_fv_ec_eq C1 y).\n                    apply disjdom_sym_1.\n                    apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom (E1'++E2')) `union` dom D').\n                      apply disjdom_sym_1; auto.\n                      simpl_env. rewrite J. clear. fsetdec.                                       \n                    assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n\n                  clear - Htyping' Disj00.\n                  apply typing_fv_te_upper in Htyping'.\n                  apply disjdom_sym_1.\n                  apply disjdom_sub with (D1:= dom Env `union` {}); auto.\n                    apply disjdom_sub with (D1:= fv_env Env).\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sym_1.\n                      apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom (E1'++E2')) `union` dom D').\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite J. clear. fsetdec.                                       \n                      assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n                    simpl_env. fsetdec.\n\n              rewrite subst_ee_plug; auto.\n              rewrite <- close_open_ee__subst_ee; auto.\n              assert (context C1) as Context1.\n                apply contexting__context in Hcontexting; auto.    \n              rewrite <- close_open_ec__subst_ec; auto.\n              assert (disjdom (fv_ee x' `union` fv_te x') (cv_ec (close_ec C1 y))) as Disj1.\n                eapply disjdom_app_l.\n                split.\n                  clear - Htyping' Disj00.\n                  apply typing_fv_ee_upper in Htyping'.\n                  apply disjdom_sym_1.\n                  simpl in Htyping'.\n                  apply disjdom_sub with (D1:= dom Env `union` {}); auto.\n                  apply disjdom_sub with (D1:= fv_env Env).\n                    assert (J:=@close_ec_fv_ec_eq C1 y).\n                    apply disjdom_sym_1.\n                    apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom (E1'++E2')) `union` dom D').\n                      apply disjdom_sym_1; auto.\n                      simpl_env. rewrite J. clear. fsetdec.                                       \n                    assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n\n                  clear - Htyping' Disj00.\n                  apply typing_fv_te_upper in Htyping'.\n                  apply disjdom_sym_1.\n                  apply disjdom_sub with (D1:= dom Env `union` {}); auto.\n                    apply disjdom_sub with (D1:= fv_env Env).\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sym_1.\n                      apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom (E1'++E2')) `union` dom D').\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite J. clear. fsetdec.                                       \n                      assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n                    simpl_env. fsetdec.\n\n              rewrite <- open_ee_plug; auto.\n              rewrite commut_lgamma_osubst_open_ee with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(gsubst:=gsubst1'++gsubst2') (Env:=Env) (lEnv:=lEnv); auto.\n              rewrite commut_gamma_osubst_open_ee with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(lgsubst:=lgsubst') (Env:=Env) (lEnv:=lEnv); auto.\n              rewrite <- shift_ee_expr; auto.\n              apply red_abs_preserved_under_delta_osubst with (dE:=E1'++E2') (Env:=Env); auto.\n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_gamma_osubst_open_ee with (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (D:=D') (lgsubst:=lgsubst') (Env:=Env) (lEnv:=lEnv); auto.\n              apply red_abs_preserved_under_gamma_osubst with (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (D:=D') (lgsubst:=lgsubst') (Env:=Env) (lEnv:=lEnv); auto. \n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_lgamma_osubst_open_ee with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(gsubst:=gsubst1'++gsubst2') (Env:=Env) (lEnv:=lEnv); auto.\n              apply red_abs_preserved_under_lgamma_osubst with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(gsubst:=gsubst1'++gsubst2') (Env:=Env) (lEnv:=lEnv); auto. \n\n              apply red_abs.\n                apply expr_abs with (L:=cv_ec (close_ec C1 y) `union` cv_ec C1).\n                   apply type_from_wf_typ in WFTV; assumption.\n\n                   intros.\n                   assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec (close_ec C1 y))) as Disj'.\n                     eapply disjdom_app_l.\n                     split.\n                       clear Disj00 Disj01.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite open_ee_plug; auto.\n                   rewrite close_open_ec__subst_ec; auto.\n                   rewrite close_open_ee__subst_ee; auto.\n                  assert (disjdom (union {{y}} (fv_ee x0 `union` fv_te x0)) (cv_ec C1)) as Disj0'.\n                    eapply disjdom_app_l.\n                    split.\n                      clear Disj00 Disj01.\n                      apply disjdom_one_2; auto.\n                    eapply disjdom_app_l.\n                    split.\n                      clear Disj00 Disj01.\n                      apply disjdom_one_2; auto.\n                      simpl. apply disjdom_nil_1.\n                   rewrite <- subst_ee_plug; auto.\n\n               apply F_Related_ovalues_inversion in Harrow_left'.\n               decompose [prod] Harrow_left'; auto.\nQed.\n\nLemma F_ological_related_congruence__labs_capture :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  forall L0,\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n   disjdom L0 (fv_env Env) ->\n   disjdom L0 (fv_lenv lEnv) ->\n   F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n   F_Rosubst E rsubst dsubst dsubst' Env ->\n   F_Related_oterms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n     Env lEnv\n  ) ->\n  forall K y T1' C1 T2' E' D',\n  wf_typ E' T1' kn_lin ->\n  binds y (lbind_typ T1') D' ->\n  y `notin` gdom_env E `union` cv_ec C1 ->\n  contexting E D T C1 E' D' T2' ->\n  (K = kn_nonlin -> lenv_remove (y, lbind_typ T1') D' = lempty) ->\n  (typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom L0 (fv_env Env) ->\n     disjdom L0 (fv_lenv lEnv) ->\n     F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E rsubst dsubst dsubst' Env ->\n     F_Related_oterms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n      Env lEnv\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` dom D') (fv_env Env) ->\n     disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` dom D') (fv_lenv lEnv) ->\n     F_Related_osubst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E' rsubst dsubst dsubst' Env ->\n     F_Related_oterms T2' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n      Env lEnv\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n  disjdom (L0 `union` ({{y}} `union` cv_ec (close_ec C1 y)) `union` fv_ec (close_ec C1 y) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom (lenv_remove (y, lbind_typ T1') D')) (fv_env Env) ->\n  disjdom (L0 `union` ({{y}} `union` cv_ec (close_ec C1 y)) `union` fv_ec (close_ec C1 y) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom (lenv_remove (y, lbind_typ T1') D')) (fv_lenv lEnv) ->\n  F_Related_osubst E' (lenv_remove (y, lbind_typ T1') D') gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n  F_Rosubst E' rsubst dsubst dsubst' Env  ->\n  F_Related_oterms (typ_arrow K T1' T2') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e) y))))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e') y))))))\n      Env lEnv.\nProof.\n    intros e e' E D T Htyp Htyp' L0 Hlr K y T1' C1 T2' E' D' H H0 H1 Hcontexting H2 IHHcontexting dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv Disj00 Disj01 Hrel_sub HRsub.  \n    assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J. \n    destruct J as [[[[[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe] Hwfe'] HwfEnv] HwflEnv].\n\n    rename H into WFTV.\n    \n    assert (wf_typ E' T2' kn_lin) as WFT'. \n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (Fry := @IHHcontexting Htyp Htyp' Hlr).\n    assert (wf_lenv E' D') as Wfle'.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (EQ1:=@lenv_remove_inv E' D' y (lbind_typ T1')  Wfle' H0).\n    destruct EQ1 as [D1' [D2' [EQ1' EQ2']]]; subst.\n    rewrite EQ1' in *.\n\n    assert (EQ:=Hrel_sub).\n    apply F_Related_olgsubst_lapp_inv in EQ.\n    destruct EQ as [lgsubst1 [lgsubst2 [lgsubst1' [lgsubst2' [lEnv1 [lEnv2 [gEQ1 [gEQ2 [gEQ3 [gEQ4 [gEQ5 [gEQ6 [gEQ7 [Hrel_sub1 Hrel_sub2]]]]]]]]]]]]]]; subst.\n\n    assert (value (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst (lgsubst1++lgsubst2) (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e) y))))))) as Value.\n      clear Disj00 Disj01.\n      apply delta_gamma_lgamma_osubst_value with (E:=E') (D:=D1'++D2') (Env:=Env) (lEnv:=lEnv1++lEnv2); auto.\n        apply FrTyping__labsvalue with (L:=dom E' `union` dom (D1'++D2') `union` cv_ec (close_ec C1 y) `union` cv_ec C1) (D:=D1'++D2') (E:=E') (T1:=T2') (K:=kn_lin); auto.\n          intros x xnFv.\n          rewrite <- shift_ee_expr with (e:=e); auto.\n          assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite open_ee_plug; auto. \n          rewrite <- EQ1'.\n          rewrite close_open_ee__subst_ee; auto.\n          assert (context C1) as Ctx1.\n            apply contexting__context in Hcontexting; auto.\n          rewrite close_open_ec__subst_ec; auto.\n          assert (disjdom (union {{y}} (fv_ee x `union` fv_te x)) (cv_ec C1)) as Disj'.\n             eapply disjdom_app_l.\n             split.\n               apply disjdom_one_2; auto.\n             eapply disjdom_app_l.\n             split.\n               apply disjdom_one_2; auto.\n               simpl. apply disjdom_nil_1.\n          rewrite <- subst_ee_plug; auto. \n          assert (typing E' (D1'++[(y, lbind_typ T1')]++D2') (plug C1 e) T2') as Htyp2.\n            apply contexting_plug_typing with (e:=e) in Hcontexting; auto.\n              rewrite EQ1'. auto.\n         apply typing_lin_renaming_permute with (x:=y); auto.\n    assert (value (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst (lgsubst1'++lgsubst2') (exp_abs K T1' (plug (close_ec C1 y)  (close_ee (shift_ee e') y))))))) as Value'.\n      clear Disj00 Disj01.\n      apply delta_gamma_lgamma_osubst_value with (E:=E') (D:=D1'++D2') (Env:=Env) (lEnv:=lEnv1++lEnv2); auto.\n        apply FrTyping__labsvalue with (L:=dom E' `union` dom (D1'++D2') `union` cv_ec (close_ec C1 y) `union` cv_ec C1) (D:=D1'++D2') (E:=E') (T1:=T2') (K:=kn_lin); auto.\n          intros x xnFv.\n          rewrite <- shift_ee_expr with (e:=e'); auto.\n          assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite open_ee_plug; auto. \n          rewrite <- EQ1'.\n          rewrite close_open_ee__subst_ee; auto.\n          assert (context C1) as Ctx1.\n            apply contexting__context in Hcontexting; auto.\n          rewrite close_open_ec__subst_ec; auto.\n          assert (disjdom (union {{y}} (fv_ee x `union` fv_te x)) (cv_ec C1)) as Disj'.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite <- subst_ee_plug; auto. \n          assert (typing E' (D1'++[(y, lbind_typ T1')]++D2') (plug C1 e') T2') as Htyp2'.\n            apply contexting_plug_typing with (e:=e') in Hcontexting; auto.\n              rewrite EQ1'. auto.\n         apply typing_lin_renaming_permute with (x:=y); auto.\n    exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst (lgsubst1++lgsubst2) (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e) y)))))).\n    exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst (lgsubst1'++lgsubst2') (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e') y)))))).\n    split. \n      clear Disj00 Disj01.\n      assert (typing E' (D1'++D2') (plug (ctx_abs_capture K y T1' (close_ec C1 y)) e) (typ_arrow K T1' T2')) as Hptyp.\n        destruct (in_dec y (fv_ee e)) as [yine | ynine].\n          simpl.\n          apply typing_labs with (L:=dom (D1'++D2') `union` dom E' `union` dom E `union` dom D `union` cv_ec C1 `union` cv_ec (close_ec C1 y) `union` dom Env `union` dom lEnv1 `union` dom lEnv2); auto.\n            intros x xn.\n            rewrite <- shift_ee_expr; auto.\n            assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n              eapply disjdom_app_l.\n              split.\n                apply disjdom_one_2; auto.\n                simpl. apply disjdom_nil_1.\n            rewrite open_ee_plug; auto.\n            assert (y `in` gdom_env E \\/ y `in` dom D) as yED.\n              assert (y `in` gdom_env E `union` dom D) as J.\n                apply in_fv_ee_typing' with (x:=y) in Htyp; auto.\n              clear - J. fsetdec.\n            rewrite close_open_ee__subst_ee; auto.\n            assert (context C1) as Ctx1.\n              apply contexting__context in Hcontexting; auto.\n            rewrite close_open_ec__subst_ec; auto.\n            destruct yED as [yE | yD].\n              contradict H1; auto.\n\n              apply binds_In_inv in yD.\n              destruct yD as [b Binds]. destruct b.\n              assert (wf_lenv E D) as Wfle. auto.\n              assert (J:=@lenv_remove_inv E D y (lbind_typ t) Wfle Binds).\n              destruct J as [D1 [D2 [dEQ1 dEQ2]]]; subst.\n              apply typing_lin_permute.\n              simpl_env in xn.\n              apply contexting_plug_typing with (E:=E) (D:=D1++[(x, lbind_typ t)]++D2) (T:=T); auto.\n                apply contexting_lin_renaming_one; auto.\n\n                apply typing_lin_renaming_one with (x:=y); auto.\n\n          rewrite <- EQ1'.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n            apply contexting_labs_capture; auto.\n              intros J. apply H2 in J.\n              rewrite lenv_remove_opt; auto.\n              apply uniq_from_wf_lenv in Wfle'. assumption.\n               \n      apply typing_osubst with (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst1++lgsubst2) (Env:=Env) (lEnv:=lEnv1++lEnv2) in Hptyp; auto.\n    split.\n      clear Disj00 Disj01.\n      assert (typing E' (D1'++D2') (plug (ctx_abs_capture K y T1' (close_ec C1 y)) e') (typ_arrow K T1' T2')) as Hptyp'.\n        destruct (in_dec y (fv_ee e')) as [yine' | ynine'].\n          simpl.\n          apply typing_labs with (L:=dom (D1'++D2') `union` dom E' `union` dom D `union` dom E `union` cv_ec C1 `union` cv_ec (close_ec C1 y) `union` dom Env `union` dom lEnv1 `union` dom lEnv2); auto.\n            intros x xn.\n            rewrite <- shift_ee_expr; auto.\n            assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n              eapply disjdom_app_l.\n              split.\n                apply disjdom_one_2; auto.\n                simpl. apply disjdom_nil_1.\n            rewrite open_ee_plug; auto.\n            assert (y `in` gdom_env E \\/ y `in` dom D) as yED.\n              assert (y `in` gdom_env E `union` dom D) as J.\n                apply in_fv_ee_typing' with (x:=y) in Htyp'; auto.\n              clear - J.\n              fsetdec.\n            rewrite close_open_ee__subst_ee; auto.\n            assert (context C1) as Ctx1.\n              apply contexting__context in Hcontexting; auto.\n            rewrite close_open_ec__subst_ec; auto.\n            destruct yED as [yE | yD].\n              contradict H1; auto.\n\n              apply binds_In_inv in yD.\n              destruct yD as [b Binds]. destruct b.\n              assert (wf_lenv E D) as Wfle. auto.\n              assert (J:=@lenv_remove_inv E D y (lbind_typ t) Wfle Binds).\n              destruct J as [D1 [D2 [dEQ1 dEQ2]]]; subst.\n              apply typing_lin_permute.\n              simpl_env in xn.\n              apply contexting_plug_typing with (E:=E) (D:=D1++[(x, lbind_typ t)]++D2) (T:=T); auto.\n                apply contexting_lin_renaming_one; auto.\n\n                apply typing_lin_renaming_one with (x:=y); auto.\n\n          rewrite <- EQ1'.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n            apply contexting_labs_capture; auto.\n              intros J. apply H2 in J.\n              rewrite lenv_remove_opt; auto.\n              apply uniq_from_wf_lenv in Wfle'. assumption.\n      apply typing_osubst with (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst1'++lgsubst2') (Env:=Env) (lEnv:=lEnv1++lEnv2) in Hptyp'; auto.\n    split. split; auto.\n    split. split; auto.\n      SCase \"Frel\".\n      apply F_Related_ovalues_arrow_req.\n      split; auto.\n      split; auto.\n      SSCase \"arrow\".\n        exists (L0 `union` (cv_ec C1) `union` (fv_ec C1) `union` (fv_tt T) `union` (fv_tt T1') `union` (fv_tt T2') `union`  \n                       dom gsubst `union` dom lgsubst1 `union` dom lgsubst2  `union` dom gsubst' `union` dom lgsubst1' `union` dom lgsubst2'  `union` dom E `union` dom D `union` dom Env `union` dom lEnv1 `union` dom lEnv2 `union` {{y}} `union` dom E' `union` dom D1' `union` dom D2').\n        intros lEnv x x' Htyping Htyping' Hwfle Disj' Harrow_left.\n\n        assert (F_Related_osubst E' (D1'++[(y, lbind_typ T1')]++D2') gsubst gsubst' (lgsubst1++[(y,x)]++lgsubst2) (lgsubst1'++[(y,x')]++lgsubst2') rsubst dsubst dsubst' Env (lEnv1++lEnv++lEnv2)) as Hrel_sub'.        \n          assert (y `notin` fv_env Env) as ynEnv.\n            clear - Disj00.\n            apply disjdom_app_2 in Disj00.\n            apply disjdom_app_1 in Disj00.\n            apply disjdom_app_1 in Disj00.\n            destruct Disj00 as [J1 J2].\n            apply J1; auto.\n          assert (y `notin` fv_lenv (lEnv1++lEnv2)) as ynlEnv12.\n            clear - Disj01.\n            apply disjdom_app_2 in Disj01.\n            apply disjdom_app_1 in Disj01.\n            apply disjdom_app_1 in Disj01.\n            destruct Disj01 as [J1 J2].\n            apply J1; auto.\n          assert (y `notin` dom lEnv) as ynlEnv.\n            clear - Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_2 in Disj'.\n            apply disjdom_app_1 in Disj'.\n            destruct Disj' as [J1 J2]. auto.\n          clear Disj00 Disj01.\n          assert (y `notin` dom D1') as ynD1'.\n            apply fresh_mid_head with (E:=D2') (a:=lbind_typ T1'); auto.\n              apply contexting_regular in Hcontexting.\n              decompose [and] Hcontexting. eauto.\n          assert (y `notin` dom D2') as ynD2'.\n            apply fresh_mid_tail with (F:=D1') (a:=lbind_typ T1'); auto.\n              apply contexting_regular in Hcontexting.\n              decompose [and] Hcontexting. eauto.\n         assert (y `notin` dom E') as ynE'.\n           apply contexting_regular in Hcontexting.\n           decompose [and] Hcontexting.\n           apply wf_lenv_notin_dom with (x:=y) (T:=T1') in H6; auto.\n         simpl_env in ynlEnv12.\n         apply F_Related_osubst_lgweaken; auto.\n           apply disjdom__disjoint.\n           apply disjdom_sym_1 in Disj'.           \n           apply disjdom_sub with (D2:=dom E') in Disj'; auto.\n             clear. fsetdec.\n\n           apply disjdom__disjoint.\n           apply disjdom_sym_1 in Disj'.           \n           apply disjdom_sub with (D2:=dom (D1'++D2')) in Disj'; auto.\n             clear. simpl_env. fsetdec.\n\n          apply wf_lenv_merge.\n            rewrite_env (nil ++ lEnv++(lEnv1++lEnv2)) in Hwfle.\n            apply wf_lenv_lin_strengthening' in Hwfle.\n            rewrite_env (lEnv1++lEnv2++nil) in Hwfle.\n            apply wf_lenv_lin_strengthening' in Hwfle.\n            simpl_env in Hwfle. assumption.\n\n            apply wf_lenv_lin_strengthening' in Hwfle; auto.\n\n            apply uniq_from_wf_lenv in Hwfle.\n            clear - Hwfle.\n            solve_uniq.\n     \n          apply F_Related_osubst__inversion in Hrel_sub1.  \n          decompose [prod] Hrel_sub1; auto.\n\n          apply F_Related_osubst__inversion in Hrel_sub2.  \n          decompose [prod] Hrel_sub2; auto.\n\n       assert (\n       disjdom\n         (union L0\n            (union (cv_ec C1)\n               (union (fv_ec C1)\n                  (union (dom E)\n                     (union (dom D)\n                        (union (fv_tt T)\n                           (union (fv_tt T2')\n                              (union (dom E') (dom (D1' ++ [(y, lbind_typ T1')] ++ D2'))))))))))\n         (fv_env Env)) as Disj00'.\n           clear - Disj00.\n           assert (J:=@close_ec_fv_ec_eq C1 y).\n           assert (J':=@close_ec_fv_ec_lower C1 y).\n           apply disjdom_sym_1.\n           apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom (D1'++D2')).\n             apply disjdom_sym_1; auto.\n             simpl_env. rewrite J. clear - J'. fsetdec.\n       assert (\n       disjdom\n         (union L0\n            (union (cv_ec C1)\n               (union (fv_ec C1)\n                  (union (dom E)\n                     (union (dom D)\n                        (union (fv_tt T)\n                           (union (fv_tt T2')\n                              (union (dom E') (dom (D1' ++ [(y, lbind_typ T1')] ++ D2'))))))))))\n         (fv_lenv (lEnv1++lEnv++lEnv2))) as Disj01'.\n           clear - Disj01 Disj' Disj00 Htyping WFTV.\n           assert (J:=@close_ec_fv_ec_eq C1 y).\n           assert (J':=@close_ec_fv_ec_lower C1 y).\n           apply disjdom_sym_1.\n           apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` (dom (D1'++D2'))).\n             apply disjdom_eq with (D1:=fv_lenv (lEnv1++lEnv2) `union` fv_lenv lEnv).\n               eapply disjdom_app_l.\n               split.\n                 apply disjdom_sym_1; auto.\n                 apply disjdom_sym_1.\n                   apply disjdom_fv_lenv_wfle with (Env:=Env); auto.\n                     clear - Disj00.\n                     apply disjdom_sub with (D1:=fv_env Env); auto.\n                        apply fv_env__includes__dom.\n\n                     clear - Disj'.\n                     assert (J:=@close_ec_fv_ec_eq C1 y).\n                     assert (J':=@close_ec_fv_ec_upper C1 y).\n                     apply disjdom_sym_1 in Disj'.\n                     apply disjdom_sub with (D2:=L0 `union` ({{y}} `union` cv_ec (close_ec C1 y)) `union` fv_ec (close_ec C1 y) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom (D1'++D2')) in Disj'.\n                       apply disjdom_sym_1; auto. \n                       rewrite J. clear - J'. simpl_env. fsetdec.\n               simpl_env. clear. fsetdec.\n             simpl_env. rewrite J. clear - J'. fsetdec.\n        assert (J:=@Fry dsubst dsubst' gsubst gsubst' (lgsubst1++[(y,x)]++lgsubst2) (lgsubst1'++[(y,x')]++lgsubst2') rsubst Env (lEnv1++lEnv++lEnv2) Disj00' Disj01' Hrel_sub' HRsub).\n        assert (\n            apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst (lgsubst1++[(y,x)]++lgsubst2) (plug C1 e))) =\n            apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst (lgsubst1++lgsubst2) (subst_ee y x (plug C1 e))))\n                  ) as Heq1.\n           simpl_env.\n           rewrite lgamma_osubst_opt with (D':=D1') (D:=D2') (E:=E') (dsubst:=dsubst) (t:=T1') (gsubst:=gsubst) (Env:=Env) (lEnv':=lEnv1) (lEnv0:=lEnv) (lEnv:=lEnv2); auto.\n             apply F_Related_osubst__inversion in Hrel_sub'.\n             decompose [prod] Hrel_sub'; auto.\n\n             apply F_Related_osubst__inversion in Hrel_sub2.\n             decompose [prod] Hrel_sub2; auto.\n\n             apply F_Related_osubst__inversion in Hrel_sub1.\n             decompose [prod] Hrel_sub1; auto.\n         assert (\n            apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst  (lgsubst1'++[(y,x')]++lgsubst2') (plug C1 e'))) =\n            apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst  (lgsubst1'++lgsubst2') (subst_ee y x' (plug C1 e'))))\n                  ) as Heq2.\n           simpl_env.\n           rewrite lgamma_osubst_opt with (D':=D1') (D:=D2') (E:=E') (dsubst:=dsubst') (t:=T1') (gsubst:=gsubst') (Env:=Env) (lEnv':=lEnv1) (lEnv0:=lEnv) (lEnv:=lEnv2); auto.\n             apply F_Related_osubst__inversion in Hrel_sub'.\n             decompose [prod] Hrel_sub'; auto.\n\n             apply F_Related_osubst__inversion in Hrel_sub2.\n             decompose [prod] Hrel_sub2; auto.\n\n             apply F_Related_osubst__inversion in Hrel_sub1.\n             decompose [prod] Hrel_sub1; auto.\n         rewrite Heq1 in J. rewrite Heq2 in J. clear Heq1 Heq2.\n         destruct J as [v [v' [Ht [Ht' [[Hbrc Hv] [[Hbrc' Hv'] Hrel]]]]]].\n         exists (v). exists (v').\n         split.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst dsubst (apply_gamma_subst gsubst  (apply_gamma_subst (lgsubst1++lgsubst2) (subst_ee y x (plug C1 e)))))); auto.\n              assert (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst (lgsubst1++lgsubst2) x)) =x) as Heq1.\n                 assert (disjdom (fv_te x) (dom dsubst)) as Disj03.\n                   assert (disjdom (dom E') (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom E') in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     apply dom_delta_osubst in Hwfd.\n                     rewrite <- Hwfd.\n                     clear - Htyping x0notin Disj001.\n                     apply in_fv_te_typing with (X:=x0) in Htyping; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply free_dom__free_env in Htyping.\n                       apply J2 in Htyping; auto.\n\n                     apply dom_delta_osubst in Hwfd.\n                     rewrite <- Hwfd in x0notin. \n                     clear - Htyping x0notin Disj001.\n                     apply notin_fv_te_typing with (X:=x0) in Htyping; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply free_env__free_dom.\n                       apply J1.\n                       apply ddom__dom; simpl_env; auto.\n                 assert (disjdom (fv_ee x) (dom (lgsubst1++lgsubst2))) as Disj04.\n                   assert (disjdom (dom (D1'++D2')) (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom (D1'++D2')) in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   assert (disjdom (dom (D1'++D2')) (dom lEnv)) as Disj002.\n                     apply disjdom_sym_1 in Disj'.\n                     apply disjdom_sub with (D2:=dom (D1'++D2')) in Disj'.\n                       apply disjdom_sym_1 in Disj'; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     simpl_env. rewrite <- gEQ3. rewrite <- gEQ4.\n                     clear - Htyping x0notin Disj001 Disj002.\n                     apply in_fv_ee_typing with (x:=x0) in Htyping; auto.\n                     assert (x0 `in` dom Env \\/ x0 `in` dom lEnv) as J.\n                       clear - Htyping.  fsetdec.\n                     destruct J as [J | J].\n                       destruct Disj001 as [J1 J2].\n                       apply free_dom__free_env in J.\n                       apply J2 in J. simpl_env in J. auto.\n\n                       destruct Disj002 as [J1 J2].\n                       apply J2 in J. simpl_env in J. auto.\n\n                     simpl_env in x0notin. rewrite <- gEQ3 in x0notin. rewrite <- gEQ4 in x0notin.\n                     clear - Htyping x0notin Disj001 Disj002.\n                     apply notin_fv_ee_typing with (y:=x0) in Htyping; auto.\n                     assert (x0 `in` dom (D1'++D2')) as J. \n                       clear - x0notin. simpl_env. fsetdec.\n                     assert (J':=J).\n                     destruct Disj001 as [J1 J2].\n                     apply J1 in J.\n                     apply free_env__free_dom in J.\n\n                     destruct Disj002 as [J3 J4].\n                     apply J3 in J'.\n                     auto.\n                 assert (disjdom (fv_ee x) (dom gsubst)) as Disj05.\n                   assert (disjdom (dom E') (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom E') in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   assert (disjdom (dom E') (dom lEnv)) as Disj002.\n                     apply disjdom_sym_1 in Disj'.\n                     apply disjdom_sub with (D2:=dom E') in Disj'.\n                       apply disjdom_sym_1 in Disj'; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     apply dom_lgamma_osubst in Hwflg.\n                     decompose [and] Hwflg.\n                     rewrite <- H4.\n                     clear - Htyping x0notin Disj001 Disj002.\n                     apply in_fv_ee_typing with (x:=x0) in Htyping; auto.\n                     assert (x0 `in` dom Env \\/ x0 `in` dom lEnv) as J.\n                       clear - Htyping.  fsetdec.\n                     destruct J as [J | J].\n                       destruct Disj001 as [J1 J2].\n                       apply free_dom__free_env in J.\n                       apply J2 in J.\n                       apply dom__gdom in J; auto.\n\n                       destruct Disj002 as [J1 J2].\n                       apply J2 in J.\n                       apply dom__gdom in J; auto.\n\n                     apply dom_lgamma_osubst in Hwflg.\n                     decompose [and] Hwflg.\n                     rewrite <- H4 in x0notin.\n                     clear - Htyping x0notin Disj001 Disj002.\n                     apply notin_fv_ee_typing with (y:=x0) in Htyping; auto.\n                     assert (J:=x0notin).\n                     destruct Disj001 as [J1 J2].\n                     apply gdom__dom in J.                \n                     apply J1 in J.\n                     apply free_env__free_dom in J.\n                     destruct Disj002 as [J3 J4].\n                     apply gdom__dom in x0notin.                \n                     apply J3 in x0notin. auto.\n                 clear Disj00 Disj01.\n                 rewrite gamma_osubst_closed_exp; auto.\n                 rewrite gamma_osubst_closed_exp; auto.\n                 rewrite delta_osubst_closed_exp; auto.\n                 rewrite gamma_osubst_closed_exp; auto.\n              rewrite <- Heq1.\n              rewrite commut_gamma_subst_abs.\n              rewrite commut_gamma_subst_abs.\n              assert (subst_ee y (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst (lgsubst1++lgsubst2) x))) (plug C1 e) = subst_ee y x (plug C1 e)) as Heq2. \n                 rewrite Heq1. auto. \n              rewrite Heq2.\n              assert (typing E' (D1'++[(y, lbind_typ T1')]++D2') (plug C1 e) T2') as Typinge.\n                apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n             assert (disjdom (union {{y}} (fv_ee x `union` fv_te x)) (cv_ec C1)) as Disj0.\n               eapply disjdom_app_l.\n               split.\n                 clear - H1.\n                 apply disjdom_one_2; auto.\n               eapply disjdom_app_l.\n               split.\n                  clear - Htyping Disj00 Disj'.\n                  apply typing_fv_ee_upper in Htyping.\n                  apply disjdom_sym_1.\n                  simpl in Htyping.\n                  apply disjdom_sub with (D1:= dom Env `union` dom lEnv); auto.\n                  apply disjdom_sub with (D1:= fv_env Env `union` dom lEnv).\n                    eapply disjdom_app_r.\n                    split.\n                      clear - Disj00.\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom E') `union` dom ((D1'++D2'))).\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite J. clear. fsetdec.                                       \n\n                      clear - Disj'.\n                      apply disjdom_sym_1 in Disj'.\n                      apply disjdom_sub with (D2:=cv_ec C1) in Disj'; auto.\n                        clear. fsetdec.                                       \n                    assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n\n                  clear - Htyping Disj00.\n                  apply typing_fv_te_upper in Htyping.\n                  apply disjdom_sym_1.\n                  apply disjdom_sub with (D1:= dom Env `union` {}); auto.\n                    apply disjdom_sub with (D1:= fv_env Env).\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sym_1.\n                      apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom E') `union` dom (D1'++D2')).\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite J. clear. fsetdec.                                       \n                      assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n                    simpl_env. fsetdec.\n\n              rewrite subst_ee_plug; auto.\n              rewrite <- close_open_ee__subst_ee; auto.\n              assert (context C1) as Context1.\n                apply contexting__context in Hcontexting; auto.    \n              rewrite <- close_open_ec__subst_ec; auto.\n              assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n               eapply disjdom_app_l.\n               split.\n                  clear - Htyping Disj00 Disj'.\n                  apply typing_fv_ee_upper in Htyping.\n                  apply disjdom_sym_1.\n                  simpl in Htyping.\n                  apply disjdom_sub with (D1:= dom Env `union` dom lEnv); auto.\n                  apply disjdom_sub with (D1:= fv_env Env `union` dom lEnv).\n                    eapply disjdom_app_r.\n                    split.\n                      clear - Disj00.\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom E') `union` dom ((D1'++D2'))).\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite J. clear. fsetdec.                                       \n\n                      clear - Disj'.\n                      apply disjdom_sym_1 in Disj'.\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sub with (D2:=cv_ec (close_ec C1 y)) in Disj'; auto.\n                        rewrite J. clear. fsetdec.                                       \n                    assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n\n                  clear - Htyping Disj00.\n                  apply typing_fv_te_upper in Htyping.\n                  apply disjdom_sym_1.\n                  apply disjdom_sub with (D1:= dom Env `union` {}); auto.\n                    apply disjdom_sub with (D1:= fv_env Env).\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sym_1.\n                      apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom E') `union` dom (D1'++D2')).\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite J. clear. fsetdec.                                       \n                      assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n                    simpl_env. fsetdec.\n\n              rewrite <- open_ee_plug; auto.\n              rewrite commut_lgamma_osubst_open_ee with (D:=D1'++D2')(E:=E')(dsubst:=dsubst)(gsubst:=gsubst) (Env:=Env) (lEnv:=lEnv1++lEnv2); auto.\n              rewrite commut_gamma_osubst_open_ee with (D:=D1'++D2')(E:=E')(dsubst:=dsubst)(lgsubst:=lgsubst1++lgsubst2) (Env:=Env) (lEnv:=lEnv1++lEnv2); auto.\n              rewrite <- shift_ee_expr; auto.\n              apply red_abs_preserved_under_delta_osubst with (dE:=E') (Env:=Env); auto.\n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_gamma_osubst_open_ee with (D:=D1'++D2') (dsubst:=dsubst) (E:=E') (lgsubst:=lgsubst1++lgsubst2) (Env:=Env) (lEnv:=lEnv1++lEnv2); auto.\n              apply red_abs_preserved_under_gamma_osubst with (D:=D1'++D2') (dsubst:=dsubst) (E:=E')(lgsubst:=lgsubst1++lgsubst2) (Env:=Env) (lEnv:=lEnv1++lEnv2); auto.\n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_lgamma_osubst_open_ee with (D:=D1'++D2')(E:=E')(dsubst:=dsubst)(gsubst:=gsubst) (Env:=Env) (lEnv:=lEnv1++lEnv2); auto.\n              apply red_abs_preserved_under_lgamma_osubst with (D:=D1'++D2')(E:=E')(dsubst:=dsubst)(gsubst:=gsubst) (Env:=Env) (lEnv:=lEnv1++lEnv2); auto. \n\n              apply red_abs.\n                apply expr_abs with (L:=cv_ec (close_ec C1 y) `union` cv_ec C1).\n                   apply type_from_wf_typ in WFTV; assumption.\n\n                   intros.\n                   assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec (close_ec C1 y))) as Disj0'.\n                     eapply disjdom_app_l.\n                     split.\n                       clear - H.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite open_ee_plug; auto.\n                   rewrite close_open_ec__subst_ec; auto.\n                   rewrite close_open_ee__subst_ee; auto.\n                  assert (disjdom (union {{y}} (fv_ee x0 `union` fv_te x0)) (cv_ec C1)) as Disj1'.\n                     eapply disjdom_app_l.\n                     split.\n                       clear - H1.\n                       apply disjdom_one_2; auto.\n                     eapply disjdom_app_l.\n                     split.\n                       clear - H.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite <- subst_ee_plug; auto.\n               apply F_Related_ovalues_inversion in Harrow_left.\n               decompose [prod] Harrow_left; auto.\n         split; auto.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst (lgsubst1'++lgsubst2') (subst_ee y x' (plug C1 e')))))); auto.\n              assert (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst (lgsubst1'++lgsubst2') x')) =x') as Heq1'.\n                 assert (disjdom (fv_te x') (dom dsubst')) as Disj03.\n                   assert (disjdom (dom E') (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom E') in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     apply dom_delta_osubst in Hwfd'.\n                     rewrite <- Hwfd'.\n                     clear - Htyping' x0notin Disj001.\n                     apply in_fv_te_typing with (X:=x0) in Htyping'; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply free_dom__free_env in Htyping'.\n                       apply J2 in Htyping'; auto.\n\n                     apply dom_delta_osubst in Hwfd'.\n                     rewrite <- Hwfd' in x0notin. \n                     clear - Htyping' x0notin Disj001.\n                     apply notin_fv_te_typing with (X:=x0) in Htyping'; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply free_env__free_dom.\n                       apply J1.\n                       apply ddom__dom; simpl_env; auto.\n                 assert (disjdom (fv_ee x') (dom (lgsubst1'++lgsubst2'))) as Disj04.\n                   assert (disjdom (dom (D1'++D2')) (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom (D1'++D2')) in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   assert (disjdom (dom (D1'++D2')) (dom lEnv)) as Disj002.\n                     apply disjdom_sym_1 in Disj'.\n                     apply disjdom_sub with (D2:=dom (D1'++D2')) in Disj'.\n                       apply disjdom_sym_1 in Disj'; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     simpl_env. rewrite <- gEQ5. rewrite <- gEQ6.\n                     clear - Htyping' x0notin Disj001 Disj002.\n                     apply in_fv_ee_typing with (x:=x0) in Htyping'; auto.\n                     assert (x0 `in` dom Env \\/ x0 `in` dom lEnv) as J.\n                       clear - Htyping'.  fsetdec.\n                     destruct J as [J | J].\n                       destruct Disj001 as [J1 J2].\n                       apply free_dom__free_env in J.\n                       apply J2 in J. simpl_env in J. auto.\n\n                       destruct Disj002 as [J1 J2].\n                       apply J2 in J. simpl_env in J. auto.\n\n                     simpl_env in x0notin. rewrite <- gEQ5 in x0notin. rewrite <- gEQ6 in x0notin.\n                     clear - Htyping' x0notin Disj001 Disj002.\n                     apply notin_fv_ee_typing with (y:=x0) in Htyping'; auto.\n                     assert (x0 `in` dom (D1'++D2')) as J. \n                       clear - x0notin. simpl_env. fsetdec.\n                     assert (J':=J).\n                     destruct Disj001 as [J1 J2].\n                     apply J1 in J.\n                     apply free_env__free_dom in J.\n\n                     destruct Disj002 as [J3 J4].\n                     apply J3 in J'.\n                     auto.\n                 assert (disjdom (fv_ee x') (dom gsubst')) as Disj05.\n                   assert (disjdom (dom E') (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom E') in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   assert (disjdom (dom E') (dom lEnv)) as Disj002.\n                     apply disjdom_sym_1 in Disj'.\n                     apply disjdom_sub with (D2:=dom E') in Disj'.\n                       apply disjdom_sym_1 in Disj'; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     apply dom_lgamma_osubst in Hwflg'.\n                     decompose [and] Hwflg'.\n                     rewrite <- H4.\n                     clear - Htyping' x0notin Disj001 Disj002.\n                     apply in_fv_ee_typing with (x:=x0) in Htyping'; auto.\n                     assert (x0 `in` dom Env \\/ x0 `in` dom lEnv) as J.\n                       clear - Htyping'.  fsetdec.\n                     destruct J as [J | J].\n                       destruct Disj001 as [J1 J2].\n                       apply free_dom__free_env in J.\n                       apply J2 in J.\n                       apply dom__gdom in J; auto.\n\n                       destruct Disj002 as [J1 J2].\n                       apply J2 in J.\n                       apply dom__gdom in J; auto.\n\n                     apply dom_lgamma_osubst in Hwflg'.\n                     decompose [and] Hwflg'.\n                     rewrite <- H4 in x0notin.\n                     clear - Htyping' x0notin Disj001 Disj002.\n                     apply notin_fv_ee_typing with (y:=x0) in Htyping'; auto.\n                     assert (J:=x0notin).\n                     destruct Disj001 as [J1 J2].\n                     apply gdom__dom in J.                \n                     apply J1 in J.\n                     apply free_env__free_dom in J.\n                     destruct Disj002 as [J3 J4].\n                     apply gdom__dom in x0notin.                \n                     apply J3 in x0notin. auto.\n                 clear Disj00 Disj01.\n                 rewrite gamma_osubst_closed_exp; auto.\n                 rewrite gamma_osubst_closed_exp; auto.\n                 rewrite delta_osubst_closed_exp; auto.\n                 rewrite gamma_osubst_closed_exp; auto.\n              rewrite <- Heq1'.\n              rewrite commut_gamma_subst_abs.\n              rewrite commut_gamma_subst_abs.\n              assert (subst_ee y (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst (lgsubst1'++lgsubst2') x'))) (plug C1 e') = subst_ee y x' (plug C1 e')) as Heq2'. \n                 rewrite Heq1'. auto. \n              rewrite Heq2'.\n              assert (typing E' (D1'++[(y, lbind_typ T1')]++D2') (plug C1 e') T2') as Typinge'.\n                apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n             assert (disjdom (union {{y}} (fv_ee x' `union` fv_te x')) (cv_ec C1)) as Disj0'.\n               eapply disjdom_app_l.\n               split.\n                 clear - H1.\n                 apply disjdom_one_2; auto.\n               eapply disjdom_app_l.\n               split.\n                  clear - Htyping' Disj00 Disj'.\n                  apply typing_fv_ee_upper in Htyping'.\n                  apply disjdom_sym_1.\n                  simpl in Htyping'.\n                  apply disjdom_sub with (D1:= dom Env `union` dom lEnv); auto.\n                  apply disjdom_sub with (D1:= fv_env Env `union` dom lEnv).\n                    eapply disjdom_app_r.\n                    split.\n                      clear - Disj00.\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom E') `union` dom ((D1'++D2'))).\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite J. clear. fsetdec.                                       \n\n                      clear - Disj'.\n                      apply disjdom_sym_1 in Disj'.\n                      apply disjdom_sub with (D2:=cv_ec C1) in Disj'; auto.\n                        clear. fsetdec.                                       \n                    assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n\n                  clear - Htyping' Disj00.\n                  apply typing_fv_te_upper in Htyping'.\n                  apply disjdom_sym_1.\n                  apply disjdom_sub with (D1:= dom Env `union` {}); auto.\n                    apply disjdom_sub with (D1:= fv_env Env).\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sym_1.\n                      apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom E') `union` dom (D1'++D2')).\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite J. clear. fsetdec.                                       \n                      assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n                    simpl_env. fsetdec.\n\n              rewrite subst_ee_plug; auto.\n              rewrite <- close_open_ee__subst_ee; auto.\n              assert (context C1) as Context1.\n                apply contexting__context in Hcontexting; auto.    \n              rewrite <- close_open_ec__subst_ec; auto.\n              assert (disjdom (fv_ee x' `union` fv_te x') (cv_ec (close_ec C1 y))) as Disj.\n                eapply disjdom_app_l.\n                split.\n                  clear - Htyping' Disj00 Disj'.\n                  apply typing_fv_ee_upper in Htyping'.\n                  apply disjdom_sym_1.\n                  simpl in Htyping'.\n                  apply disjdom_sub with (D1:= dom Env `union` dom lEnv); auto.\n                  apply disjdom_sub with (D1:= fv_env Env `union` dom lEnv).\n                    eapply disjdom_app_r.\n                    split.\n                      clear - Disj00.\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom E') `union` dom ((D1'++D2'))).\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite J. clear. fsetdec.                                       \n\n                      clear - Disj'.\n                      apply disjdom_sym_1 in Disj'.\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sub with (D2:=cv_ec (close_ec C1 y)) in Disj'; auto.\n                        rewrite J. clear. fsetdec.                                       \n                    assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n\n                  clear - Htyping' Disj00.\n                  apply typing_fv_te_upper in Htyping'.\n                  apply disjdom_sym_1.\n                  apply disjdom_sub with (D1:= dom Env `union` {}); auto.\n                    apply disjdom_sub with (D1:= fv_env Env).\n                      assert (J:=@close_ec_fv_ec_eq C1 y).\n                      apply disjdom_sym_1.\n                      apply disjdom_sub with (D1:=L0 `union` ({{y}} `union` (cv_ec (close_ec C1 y))) `union` (fv_ec (close_ec C1 y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` (dom E') `union` dom (D1'++D2')).\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite J. clear. fsetdec.                                       \n                      assert (J:=@fv_env__includes__dom Env). clear - J. fsetdec.\n                    simpl_env. fsetdec.\n\n              rewrite <- open_ee_plug; auto.\n              rewrite commut_lgamma_osubst_open_ee with (D:=D1'++D2')(E:=E')(dsubst:=dsubst')(gsubst:=gsubst') (Env:=Env) (lEnv:=lEnv1++lEnv2); auto.\n              rewrite commut_gamma_osubst_open_ee with (D:=D1'++D2')(E:=E')(dsubst:=dsubst')(lgsubst:=lgsubst1'++lgsubst2') (Env:=Env) (lEnv:=lEnv1++lEnv2); auto.\n              rewrite <- shift_ee_expr; auto.\n              apply red_abs_preserved_under_delta_osubst with (dE:=E') (Env:=Env); auto.\n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_gamma_osubst_open_ee with (D:=D1'++D2') (dsubst:=dsubst') (E:=E') (lgsubst:=lgsubst1'++lgsubst2') (Env:=Env) (lEnv:=lEnv1++lEnv2); auto.\n              apply red_abs_preserved_under_gamma_osubst with (D:=D1'++D2') (dsubst:=dsubst') (E:=E')(lgsubst:=lgsubst1'++lgsubst2') (Env:=Env) (lEnv:=lEnv1++lEnv2); auto.\n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_lgamma_osubst_open_ee with (D:=D1'++D2')(E:=E')(dsubst:=dsubst')(gsubst:=gsubst') (Env:=Env) (lEnv:=lEnv1++lEnv2); auto.\n              apply red_abs_preserved_under_lgamma_osubst with (D:=D1'++D2')(E:=E')(dsubst:=dsubst')(gsubst:=gsubst') (Env:=Env) (lEnv:=lEnv1++lEnv2); auto. \n\n              apply red_abs.\n                apply expr_abs with (L:=cv_ec (close_ec C1 y) `union` cv_ec C1).\n                   apply type_from_wf_typ in WFTV; assumption.\n\n                   intros.\n                   assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec (close_ec C1 y))) as Disj0.\n                     eapply disjdom_app_l.\n                     split.\n                       clear - H.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite open_ee_plug; auto.\n                   rewrite close_open_ec__subst_ec; auto.\n                   rewrite close_open_ee__subst_ee; auto.\n                  assert (disjdom (union {{y}} (fv_ee x0 `union` fv_te x0)) (cv_ec C1)) as Disj1'.\n                     eapply disjdom_app_l.\n                     split.\n                       clear - H1.\n                       apply disjdom_one_2; auto.\n                     eapply disjdom_app_l.\n                     split.\n                       clear - H.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite <- subst_ee_plug; auto.\n               apply F_Related_ovalues_inversion in Harrow_left.\n               decompose [prod] Harrow_left; auto.\n           SSSCase \"Rel\".\n             apply Forel_lin_domeq with (lEnv:=lEnv1++lEnv++lEnv2); auto.\n               clear. simpl_env. fsetdec.\nQed.\n\nLemma F_ological_related_congruence__app1 :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  forall L0,\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n   disjdom L0 (fv_env Env) ->\n   disjdom L0 (fv_lenv lEnv) ->\n   F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n   F_Rosubst E rsubst dsubst dsubst' Env ->\n   F_Related_oterms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n     Env lEnv\n  ) ->\n  forall T1' K  E' D1' D2' D3' C1 e2 T2',\n  contexting E D T C1 E' D1' (typ_arrow K T1' T2') ->\n  typing E' D2' e2 T1' ->\n  lenv_split E' D1' D2' D3' ->\n  disjdom (fv_ee e2) (dom D) ->\n  (typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom L0 (fv_env Env) ->\n     disjdom L0 (fv_lenv lEnv) ->\n     F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E rsubst dsubst dsubst' Env ->\n     F_Related_oterms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n      Env lEnv\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D1') (fv_env Env) ->\n     disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt T1' `union` fv_tt T2')  `union` dom E' `union` dom D1') (fv_lenv lEnv) ->\n     F_Related_osubst E' D1' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E' rsubst dsubst dsubst' Env ->\n     F_Related_oterms (typ_arrow K T1' T2') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n      Env lEnv\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n  disjdom (L0 `union` cv_ec C1 `union` (fv_ec C1 `union` fv_ee e2) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` dom D3') (fv_env Env) ->\n  disjdom (L0 `union` cv_ec C1 `union` (fv_ec C1 `union` fv_ee e2) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` dom D3') (fv_lenv lEnv) ->\n  F_Related_osubst E' D3' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n  F_Rosubst E' rsubst dsubst dsubst' Env  ->\n  F_Related_oterms T2' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_app (plug C1 e) e2))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_app (plug C1 e') e2))))\n      Env lEnv.\nProof.\n    intros e e' E D T Htyp Htyp' L0 Hlr T1' K E' D1' D2' D3' C1 e2 T2' Hcontexting H H0 H1 IHHcontexting dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv Disj00 Disj01 Hrel_sub HRsub.  \n   assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J. \n   destruct J as [[[[[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe] Hwfe'] HwfEnv] HwflEnv].\n   apply F_Related_osubst_split with (lE1:=D1') (lE2:=D2') in Hrel_sub; auto.\n   destruct Hrel_sub as [lgsubst1 [lgsubst1' [lgsubst2 [lgsubst2' [lEnv1 [lEnv2 [J1 [J2 [J3 J4]]]]]]]]].\n\n   assert (\n      F_Related_oterms (typ_arrow K T1' T2') rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst1 (plug C1 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst1' (plug C1 e'))))\n         Env lEnv1\n     ) as FR_ArrowType.\n    apply IHHcontexting; auto.\n      clear - Disj00 H0 H.\n      apply dom_lenv_split in H0.\n      apply typing_regular in H.\n      destruct H as [_ [_ [_ H]]].\n      apply wft_fv_tt_sub in H.\n      apply disjdom_sym_1.\n      apply disjdom_sub with (D1:=L0 `union` cv_ec C1 `union` (fv_ec C1 `union` fv_ee e2) `union` dom E `union` dom D `union` fv_tt T  `union` fv_tt T2' `union` dom E' `union` dom D3').\n        apply disjdom_sym_1; auto.\n        clear Disj00. rewrite H0. clear H0. fsetdec.        \n\n      clear - Disj01 H0 J1 H.\n      apply dom_lenv_split in H0.\n      apply lgamma_osubst_split__lenv_split in J1.\n      apply fv_lenv_split in J1.\n      apply typing_regular in H.\n      destruct H as [_ [_ [_ H]]].\n      apply wft_fv_tt_sub in H.\n      apply disjdom_sym_1.\n      apply disjdom_sub with (D1:=L0 `union` cv_ec C1 `union` (fv_ec C1 `union` fv_ee e2) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` dom D3').\n        apply disjdom_sym_1.\n        apply disjdom_sub with (D1:=fv_lenv lEnv); auto.\n          rewrite J1. clear. fsetdec.\n        clear Disj01. rewrite H0. clear H0 J1. fsetdec.        \n   destruct FR_ArrowType as [v [v' [Ht [Ht' [Hn [Hn' Hrel]]]]]].\n\n   clear Disj00 Disj01.\n\n   apply F_Related_ovalues_arrow_leq in Hrel.\n   destruct Hrel as [Hv [Hv' [L Harrow]]]; subst.\n\n   assert (\n      F_Related_oterms T1' rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst2 e2)))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst'(apply_gamma_subst lgsubst2' e2)))\n         Env lEnv2\n     ) as FR_T1.\n    apply oparametricity with (E:=E') (lE:=D2'); auto.\n   destruct FR_T1 as [v0 [v'0 [Ht1 [Ht1' [Hn1 [Hn1' Hrel_wft1]]]]]].\n\n   assert (lenv_split Env lEnv1 lEnv2 lEnv) as Split.\n     apply lgamma_osubst_split__lenv_split in J1. auto.\n\n   assert (uniq lEnv2) as Uniq2.\n     apply typing_regular in Ht1. destruct Ht1 as [JJ1 [JJ2 [JJ3 JJ4]]].\n     apply uniq_from_wf_lenv in JJ2; auto.\n   assert (JJ:=@pick_lenv (L `union` dom lEnv2 `union` dom lEnv `union` dom lEnv1 `union` dom Env `union` dom E' `union` dom D1' `union` dom D2' `union` dom D3' `union` dom E `union` dom D) lEnv2 Uniq2).\n   destruct JJ as [asubst [Wfa [lEnv2_eq_asubst Disj]]].\n   assert (disjoint asubst Env) as Disj1.\n     apply disjoint_split_right in Split.\n     apply disjoint_eq with (D1:=lEnv2); auto.\n   assert (disjdom (atom_subst_codom asubst) (union (dom Env) (dom lEnv2))) as Disj2.\n     apply disjdom_sym_1 in Disj.\n     apply disjdom_sub with (D2:=union (dom Env) (dom lEnv2)) in Disj; try solve [assumption].\n     clear. fsetdec.\n   destruct (@Harrow (subst_atoms_lenv asubst lEnv2) (subst_atoms_exp asubst v0) (subst_atoms_exp asubst v'0)) as [u [u' [Hnorm_vxu [Hnorm_v'x'u' Hrel_wft2]]]]; auto.\n     apply typing_lin_renamings; auto.\n       eapply preservation_normalization; eauto.\n     apply typing_lin_renamings; auto.\n       eapply preservation_normalization; eauto.\n     apply wf_lenv_merge; auto.\n       apply wf_lenv_renamings; auto.\n\n       assert (disjdom (atom_subst_codom asubst) (dom lEnv2)) as Disj3.\n         apply disjdom_app_r in Disj2. destruct Disj2.\n         apply disjdom_sym_1; auto.\n       assert (J:=@subst_atoms_lenv__dom_upper asubst lEnv2 Wfa Uniq2 Disj3).\n       apply disjdom__disjoint.\n       apply disjdom_sym_1.\n       apply disjdom_sub with (D1:=union (dom lEnv2) (atom_subst_codom asubst)); auto.\n       eapply disjdom_app_r.\n         split.\n           apply disjoint__disjdom.\n           apply disjoint_lenv_split' in Split.\n           apply disjoint_sym_1; auto.\n            \n           apply disjdom_sym_1 in Disj.\n           apply disjdom_sub with (D2:=(dom lEnv1)) in Disj; auto.\n             clear. fsetdec.\n\n     assert (J:=@subst_atoms_lenv__dom_eq asubst lEnv2 Wfa Uniq2 lEnv2_eq_asubst).\n     apply disjdom_sym_1 in Disj.\n     apply disjdom_sub with (D2:=L) in Disj; auto.\n       apply disjdom_sym_1.\n       apply disjdom_eq with (D1:=atom_subst_codom asubst); auto.\n          rewrite J. clear. fsetdec.       \n       clear. fsetdec.\n     apply Forel_lin_renamings with (E:=E'); auto.\n       eapply preservation_normalization; eauto.\n       eapply preservation_normalization; eauto.\n\n   assert (F_Related_ovalues T2' rsubst dsubst dsubst' (rev_subst_atoms_exp asubst u) (rev_subst_atoms_exp asubst u') Env (lEnv2++lEnv1)) as Hrel_wft2'.\n     assert (lEnv2++lEnv1 = rev_subst_atoms_lenv asubst ((subst_atoms_lenv asubst lEnv2)++ lEnv1)) as Eq1.\n       rewrite rev_subst_atoms_lenv_app.\n       rewrite <- id_rev_subst_atoms_lenv; auto.\n         rewrite <- rev_subst_atoms_lenv_notin_inv; auto.\n           apply disjdom_sym_1 in Disj.\n           apply disjdom_sub with (D2:=dom lEnv1) in Disj; auto.\n             clear. fsetdec.\n         rewrite lEnv2_eq_asubst. clear. fsetdec.\n\n         apply disjdom_sym_1 in Disj.\n         apply disjdom_sub with (D2:=dom lEnv2) in Disj; auto.\n           clear. fsetdec.\n     rewrite Eq1.\n     apply Forel_lin_rev_renamings with (E:=E'); auto.\n       apply preservation_normalization with (e:=exp_app v (subst_atoms_exp asubst v0)); auto.\n         apply typing_app with (T1:=apply_delta_subst_typ dsubst T1') (K:=K) (D1:=lEnv1) (D2:=subst_atoms_lenv asubst lEnv2).\n           simpl_commut_subst in Ht.\n           apply preservation_normalization with (v:=v) in Ht; auto.\n\n           apply preservation_normalization with (v:=v0) in Ht1; auto.\n           apply typing_lin_renamings; auto.\n\n           apply lenv_split_commute.\n           apply disjoint__lenv_split; auto.\n             apply wf_lenv_renamings; auto.\n\n             assert (J:=@subst_atoms_lenv__dom_eq asubst lEnv2 Wfa Uniq2 lEnv2_eq_asubst).\n             apply disjdom_sym_1 in Disj.\n             apply disjdom_sub with (D2:=dom lEnv1) in Disj; auto.\n               apply disjdom__disjoint.\n               apply disjdom_eq with (D1:=atom_subst_codom asubst); auto.\n                 rewrite J. clear. fsetdec.             \n               clear. fsetdec.\n\n       apply preservation_normalization with (e:=exp_app v' (subst_atoms_exp asubst v'0)); auto.\n         apply typing_app with (T1:=apply_delta_subst_typ dsubst' T1') (K:=K) (D1:=lEnv1) (D2:=subst_atoms_lenv asubst lEnv2).\n           simpl_commut_subst in Ht'.\n           apply preservation_normalization with (v:=v') in Ht'; auto.\n\n           apply preservation_normalization with (v:=v'0) in Ht1'; auto.\n           apply typing_lin_renamings; auto.\n\n           apply lenv_split_commute.\n           apply disjoint__lenv_split; auto.\n             apply wf_lenv_renamings; auto.\n\n             assert (J:=@subst_atoms_lenv__dom_eq asubst lEnv2 Wfa Uniq2 lEnv2_eq_asubst).\n             apply disjdom_sym_1 in Disj.\n             apply disjdom_sub with (D2:=dom lEnv1) in Disj; auto.\n               apply disjdom__disjoint.\n               apply disjdom_eq with (D1:=atom_subst_codom asubst); auto.\n                 rewrite J. clear. fsetdec.             \n               clear. fsetdec.\n\n       apply disjdom_sym_1 in Disj.\n       apply disjdom_sub with (D2:=dom Env) in Disj; auto.\n         clear. fsetdec.\n\n       apply disjdom_eq with (D1:=dom lEnv2); auto.\n       eapply disjdom_app_r.\n       split.\n         apply disjoint__disjdom.\n         apply disjoint_split_right in Split; auto.\n       \n         apply disjoint__disjdom.\n         eapply disjoint_app_l.\n         split.\n           assert (J:=@subst_atoms_lenv__dom_eq asubst lEnv2 Wfa Uniq2 lEnv2_eq_asubst).\n           apply disjdom__disjoint.\n           apply disjdom_eq with (D1:=atom_subst_codom asubst); auto.\n             apply disjdom_sym_1 in Disj.\n             apply disjdom_sub with (D2:=dom lEnv2) in Disj; auto.\n               clear. fsetdec.             \n             rewrite J. clear. fsetdec.\n\n           apply disjoint_lenv_split' in Split; auto.\n   assert (normalize (exp_app v v0) (rev_subst_atoms_exp asubst u)) as Hnorm'_vxu.\n     apply normalize_rev_renamings with (asubst:=asubst) in Hnorm_vxu; auto.\n     rewrite rev_subst_atoms_exp__app in Hnorm_vxu.\n     rewrite <- id_rev_subst_atoms_exp with (asubst:=asubst) in Hnorm_vxu; auto.\n       rewrite <- rev_wf_asubst_id with (asubst:=asubst) (e:=v) in Hnorm_vxu; auto.\n       apply disjdom_sub with (D1:=dom Env `union` dom lEnv1).\n         eapply disjdom_app_r.\n         split.\n           apply disjdom_sym_1.\n           apply disjdom_sym_1 in Disj.\n           apply disjdom_sub with (D2:=dom Env) in Disj; auto.\n             clear. fsetdec.             \n           apply disjdom_sym_1.\n           apply disjdom_sym_1 in Disj.\n           apply disjdom_sub with (D2:=dom lEnv1) in Disj; auto.\n             clear. fsetdec.             \n         apply preservation_normalization with (v:=v) in Ht; auto.\n         apply typing_fv_ee_upper in Ht; auto.\n      apply preservation_normalization with (v:=v0) in Ht1; auto.      \n      apply typing_fv_ee_lower in Ht1; auto.\n      rewrite <- lEnv2_eq_asubst. assumption.\n\n      apply preservation_normalization with (v:=v0) in Ht1; auto.\n      apply typing_fv_ee_upper in Ht1; auto.\n      apply disjdom_sub with (D1:=union (dom Env) (dom lEnv2)); auto.  \n\n   assert (normalize (exp_app v' v'0) (rev_subst_atoms_exp asubst u')) as Hnorm'_v'x'u'.\n     apply normalize_rev_renamings with (asubst:=asubst) in Hnorm_v'x'u'; auto.\n     rewrite rev_subst_atoms_exp__app in Hnorm_v'x'u'.\n     rewrite <- id_rev_subst_atoms_exp with (asubst:=asubst) in Hnorm_v'x'u'; auto.\n       rewrite <- rev_wf_asubst_id with (asubst:=asubst) (e:=v') in Hnorm_v'x'u'; auto.\n       apply disjdom_sub with (D1:=dom Env `union` dom lEnv1).\n         eapply disjdom_app_r.\n         split.\n           apply disjdom_sym_1.\n           apply disjdom_sym_1 in Disj.\n           apply disjdom_sub with (D2:=dom Env) in Disj; auto.\n             clear.  fsetdec.             \n           apply disjdom_sym_1.\n           apply disjdom_sym_1 in Disj.\n           apply disjdom_sub with (D2:=dom lEnv1) in Disj; auto.\n             clear.  fsetdec.             \n         apply preservation_normalization with (v:=v') in Ht'; auto.\n         apply typing_fv_ee_upper in Ht'; auto.\n      apply preservation_normalization with (v:=v'0) in Ht1'; auto.\n      apply typing_fv_ee_lower in Ht1'; auto.\n      rewrite <- lEnv2_eq_asubst. assumption.\n\n      apply preservation_normalization with (v:=v'0) in Ht1'; auto.\n      apply typing_fv_ee_upper in Ht1'; auto.\n      apply disjdom_sub with (D1:=union (dom Env) (dom lEnv2)); auto.  \n\n   exists(rev_subst_atoms_exp asubst u). exists(rev_subst_atoms_exp asubst u').\n   assert (apply_delta_subst dsubst\n            (apply_gamma_subst gsubst\n              (apply_gamma_subst lgsubst (exp_app (plug C1 e) e2)) \n            ) =\n            apply_delta_subst dsubst\n            (apply_gamma_subst gsubst\n              (exp_app \n                (apply_gamma_subst lgsubst1 (plug C1 e))\n                (apply_gamma_subst lgsubst2 e2)\n              )               \n            )\n          ) as EQ.\n     simpl_commut_subst in *.\n     rewrite lgamma_subst_split_osubst' with (lgsubst1:=lgsubst1) (lgsubst2:=lgsubst2) (E:=E') (lE:=D3') (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst) (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv); auto.\n     rewrite lgamma_subst_split_osubst with (lgsubst1:=lgsubst1) (lgsubst2:=lgsubst2) (E:=E') (lE:=D3') (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst) (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv); auto.\n     apply F_Related_osubst__inversion in J3.\n     decompose [prod] J3; auto.\n     apply F_Related_osubst__inversion in J4.\n     decompose [prod] J4; auto.\n     rewrite lgamma_osubst_split_shuffle2 with (lgsubst:=lgsubst) (lgsubst1:=lgsubst1) (E:=E') (lE:=D3') (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv) ; auto.\n     erewrite gamma_osubst_closed_exp; eauto.\n       rewrite lgamma_osubst_split_shuffle1 with (lgsubst:=lgsubst) (lgsubst2:=lgsubst2) (E:=E') (lE:=D3') (e:=apply_gamma_subst lgsubst2 e2) (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv) ; auto.\n       erewrite gamma_osubst_closed_exp with \n         (e:=apply_delta_subst dsubst\n            (apply_gamma_subst gsubst\n              (apply_gamma_subst lgsubst2 e2))\n          ); eauto.\n         unfold disjdom.\n         split; intros x xnotin.\n           apply in_fv_ee_typing with (x:=x) in Ht1; try solve [assumption].\n           assert (x `in` dom Env \\/ x `in` dom lEnv2) as J. \n             clear - Ht1. fsetdec.\n           destruct J as [J | J].\n             apply disjoint_lgamma_osubst in b5.\n             decompose [and] b5. clear b5.\n             clear - J H6.\n             apply disjoint_innotin2 with (x:=x) in H6; auto.\n\n             assert (x `in` dom lEnv)as J'.\n               apply dom_lenv_split in Split.\n               rewrite Split. auto.\n             assert (dom D1' [=] dom lgsubst1) as DomEq.\n               apply dom_lgamma_osubst in b5.\n               decompose [and] b5; auto.\n             rewrite <- DomEq.\n             assert (x `notin` dom D3')as J''.            \n               apply lgamma_osubst_split__wf_lgamma_osubst in J1.\n               apply disjoint_lgamma_osubst in J1.\n               decompose [and] J1. clear J1.       \n             clear - J' H8.\n             apply disjoint_innotin2 with (x:=x) in H8; auto.\n             apply dom_lenv_split in H0.\n             rewrite H0 in J''. auto.\n\n           apply notin_fv_ee_typing with (y:=x) in Ht1; try solve [assumption].\n           assert (x `notin` dom Env) as J'.\n             apply disjoint_lgamma_osubst in b5.\n             decompose [and] b5. clear b5.\n             clear - xnotin H6.\n             apply disjoint_innotin1 with (x:=x) in H6; auto.\n\n           assert ( x `notin` dom lEnv2) as J''.\n             assert (dom D1' [=] dom lgsubst1) as DomEq.\n               apply dom_lgamma_osubst in b5.\n               decompose [and] b5; auto.\n             rewrite <- DomEq in xnotin.\n             assert (x `in` dom D3')as J'''.            \n               apply dom_lenv_split in H0.\n               rewrite H0. auto.\n             assert (x `notin` dom lEnv)as JJ'.\n               apply lgamma_osubst_split__wf_lgamma_osubst in J1.\n               apply disjoint_lgamma_osubst in J1.\n               decompose [and] J1. clear J1.\n             clear - J''' H8.\n             apply disjoint_innotin1 with (x:=x) in H8; auto.\n             apply dom_lenv_split in Split.\n             rewrite Split in JJ'. auto.\n           clear - J' J''. auto.\n\n       unfold disjdom.\n       split; intros x xnotin.\n         apply in_fv_ee_typing with (x:=x) in Ht; try solve [assumption].\n         assert (x `in` dom Env \\/ x `in` dom lEnv1) as J. clear - Ht. fsetdec.\n         destruct J as [J | J].\n           apply disjoint_lgamma_osubst in b13.\n           decompose [and] b13. clear b13.\n           clear - J H6.\n           apply disjoint_innotin2 with (x:=x) in H6; auto.\n\n           assert (x `in` dom lEnv)as J'.\n             apply dom_lenv_split in Split.\n             rewrite Split. auto.\n           assert (dom D2' [=] dom lgsubst2) as DomEq.\n             apply dom_lgamma_osubst in b13.\n             decompose [and] b13; auto.\n           rewrite <- DomEq.\n           assert (x `notin` dom D3')as J''.            \n             apply lgamma_osubst_split__wf_lgamma_osubst in J1.\n             apply disjoint_lgamma_osubst in J1.\n             decompose [and] J1. clear J1.             \n             clear - J' H8.\n             apply disjoint_innotin2 with (x:=x) in H8; auto.\n           apply dom_lenv_split in H0.\n           rewrite H0 in J''. auto.\n         apply notin_fv_ee_typing with (y:=x) in Ht; try solve [assumption].\n         assert (x `notin` dom Env) as J'.\n           apply disjoint_lgamma_osubst in b13.\n           decompose [and] b13. clear b13.\n           clear - xnotin H6.\n           apply disjoint_innotin1 with (x:=x) in H6; auto.\n\n         assert ( x `notin` dom lEnv1) as J''.\n           assert (dom D2' [=] dom lgsubst2) as DomEq.\n             apply dom_lgamma_osubst in b13.\n             decompose [and] b13; auto.\n           rewrite <- DomEq in xnotin.\n           assert (x `in` dom D3')as J'''.            \n             apply dom_lenv_split in H0.\n             rewrite H0. auto.\n           assert (x `notin` dom lEnv)as JJ'.\n             apply lgamma_osubst_split__wf_lgamma_osubst in J1.\n             apply disjoint_lgamma_osubst in J1.\n             decompose [and] J1. clear J1.             \n           clear - J''' H8.\n           apply disjoint_innotin1 with (x:=x) in H8; auto.\n           apply dom_lenv_split in Split.\n           rewrite Split in JJ'. auto.\n         clear - J' J''. auto.   \n   repeat(rewrite EQ). clear EQ.\n   assert (apply_delta_subst dsubst'\n            (apply_gamma_subst gsubst'\n              (apply_gamma_subst lgsubst' (exp_app (plug C1 e') e2)) \n            ) =\n            apply_delta_subst dsubst'\n            (apply_gamma_subst gsubst'\n              (exp_app \n                (apply_gamma_subst lgsubst1' (plug C1 e'))\n                (apply_gamma_subst lgsubst2' e2)\n              )               \n            )\n          ) as EQ.\n     simpl_commut_subst in *.\n     rewrite lgamma_subst_split_osubst' with (lgsubst1:=lgsubst1') (lgsubst2:=lgsubst2') (E:=E') (lE:=D3') (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst') (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv); auto.\n     rewrite lgamma_subst_split_osubst with (lgsubst1:=lgsubst1') (lgsubst2:=lgsubst2') (E:=E') (lE:=D3') (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst') (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv); auto.\n     apply F_Related_osubst__inversion in J3.\n     decompose [prod] J3; auto.\n     apply F_Related_osubst__inversion in J4.\n     decompose [prod] J4; auto.\n     rewrite lgamma_osubst_split_shuffle2 with (lgsubst:=lgsubst') (lgsubst1:=lgsubst1') (E:=E') (lE:=D3')  (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv); auto.\n     erewrite gamma_osubst_closed_exp; eauto.\n       rewrite lgamma_osubst_split_shuffle1 with (lgsubst:=lgsubst') (lgsubst2:=lgsubst2') (E:=E') (lE:=D3') (e:=apply_gamma_subst lgsubst2' e2)  (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv); auto.\n       erewrite gamma_osubst_closed_exp with \n         (e:=apply_delta_subst dsubst'\n            (apply_gamma_subst gsubst'\n              (apply_gamma_subst lgsubst2' e2))\n          ); eauto.\n         unfold disjdom.\n         split; intros x xnotin.\n           apply in_fv_ee_typing with (x:=x) in Ht1'; try solve [assumption].\n           assert (x `in` dom Env \\/ x `in` dom lEnv2) as J. clear - Ht1'. fsetdec.\n           destruct J as [J | J].\n             apply disjoint_lgamma_osubst in b4.\n             decompose [and] b4. clear b4.\n             clear - J H6.\n             apply disjoint_innotin2 with (x:=x) in H6; auto.\n\n             assert (x `in` dom lEnv)as J'.\n               apply dom_lenv_split in Split.\n               rewrite Split. auto.\n             assert (dom D1' [=] dom lgsubst1') as DomEq.\n               apply dom_lgamma_osubst in b4.\n               decompose [and] b4; auto.\n             rewrite <- DomEq.\n             assert (x `notin` dom D3')as J''.            \n               apply lgamma_osubst_split__wf_lgamma_osubst in J2.\n               apply disjoint_lgamma_osubst in J2.\n               decompose [and] J2. clear J2.             \n             clear - J' H8.\n             apply disjoint_innotin2 with (x:=x) in H8; auto.\n             apply dom_lenv_split in H0.\n             rewrite H0 in J''. auto.\n\n           apply notin_fv_ee_typing with (y:=x) in Ht1'; try solve [assumption].\n           assert (x `notin` dom Env) as J'.\n             apply disjoint_lgamma_osubst in b4.\n             decompose [and] b4. clear b4.\n             clear - xnotin H6.\n             apply disjoint_innotin1 with (x:=x) in H6; auto.\n\n           assert ( x `notin` dom lEnv2) as J''.\n             assert (dom D1' [=] dom lgsubst1') as DomEq.\n               apply dom_lgamma_osubst in b4.\n               decompose [and] b4; auto.\n             rewrite <- DomEq in xnotin.\n             assert (x `in` dom D3')as J'''.            \n               apply dom_lenv_split in H0.\n               rewrite H0. auto.\n             assert (x `notin` dom lEnv)as JJ'.\n               apply lgamma_osubst_split__wf_lgamma_osubst in J2.\n               apply disjoint_lgamma_osubst in J2.\n               decompose [and] J2. clear J2.             \n               clear - J''' H8.\n               apply disjoint_innotin1 with (x:=x) in H8; auto.\n             apply dom_lenv_split in Split.\n             rewrite Split in JJ'. auto.\n           clear - J' J''. auto.\n\n       unfold disjdom.\n       split; intros x xnotin.\n         apply in_fv_ee_typing with (x:=x) in Ht'; try solve [assumption].\n         assert (x `in` dom Env \\/ x `in` dom lEnv1) as J. clear - Ht'. fsetdec.\n         destruct J as [J | J].\n           apply disjoint_lgamma_osubst in b12.\n           decompose [and] b12. clear b12.\n           clear - J H6.\n           apply disjoint_innotin2 with (x:=x) in H6; auto.\n\n           assert (x `in` dom lEnv)as J'.\n             apply dom_lenv_split in Split.\n             rewrite Split. auto.\n           assert (dom D2' [=] dom lgsubst2') as DomEq.\n             apply dom_lgamma_osubst in b12.\n             decompose [and] b12; auto.\n           rewrite <- DomEq.\n           assert (x `notin` dom D3')as J''.            \n             apply lgamma_osubst_split__wf_lgamma_osubst in J2.\n             apply disjoint_lgamma_osubst in J2.\n             decompose [and] J2. clear J2.           \n             clear - H8 J'.\n             apply disjoint_innotin2 with (x:=x) in H8; auto.\n           apply dom_lenv_split in H0.\n           rewrite H0 in J''. auto.\n         apply notin_fv_ee_typing with (y:=x) in Ht'; try solve [assumption].\n         assert (x `notin` dom Env) as J'.\n           apply disjoint_lgamma_osubst in b12.\n           decompose [and] b12. clear b12.\n           clear - xnotin H6.\n           apply disjoint_innotin1 with (x:=x) in H6; auto.\n         assert ( x `notin` dom lEnv1) as J''.\n           assert (dom D2' [=] dom lgsubst2') as DomEq.\n             apply dom_lgamma_osubst in b12.\n             decompose [and] b12; auto.\n           rewrite <- DomEq in xnotin.\n           assert (x `in` dom D3')as J'''.            \n             apply dom_lenv_split in H0.\n             rewrite H0. auto.\n           assert (x `notin` dom lEnv)as JJ'.\n             apply lgamma_osubst_split__wf_lgamma_osubst in J2.\n             apply disjoint_lgamma_osubst in J2.\n             decompose [and] J2. clear J2.             \n             clear - J''' H8.\n             apply disjoint_innotin1 with (x:=x) in H8; auto.\n           apply dom_lenv_split in Split.\n           rewrite Split in JJ'. auto.\n         clear - J' J''. auto.   \n   repeat(rewrite EQ). clear EQ.\n   repeat(split; try solve [simpl_commut_subst in *; eauto |\n                                              simpl_commut_subst; apply congr_app with (v1:=v) (v2:=v0); auto |\n                                              simpl_commut_subst; apply congr_app with (v1:=v') (v2:=v'0); auto]).\n    apply Forel_lin_domeq with (lEnv:=lEnv2++lEnv1); auto.\n      apply wf_lenv_merge; auto.\n        apply disjoint_lenv_split' in Split; auto.\n      apply dom_lenv_split in Split.\n        rewrite Split. simpl_env. clear. fsetdec.\nQed.\n\nLemma F_ological_related_congruence__app2 :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  forall L0,\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n   disjdom L0 (fv_env Env) ->\n   disjdom L0 (fv_lenv lEnv) ->\n   F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n   F_Rosubst E rsubst dsubst dsubst' Env ->\n   F_Related_oterms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n     Env lEnv\n  ) ->\n  forall T1' K  E' D1' D2' D3' e1 C2 T2',\n  typing E' D1' e1 (typ_arrow K T1' T2') ->\n  contexting E D T C2 E' D2' T1' ->\n  disjdom (fv_ee e1) (dom D) ->\n  lenv_split E' D1' D2' D3' ->\n  (typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom L0 (fv_env Env) ->\n     disjdom L0 (fv_lenv lEnv) ->\n     F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E rsubst dsubst dsubst' Env ->\n     F_Related_oterms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n      Env lEnv\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom (L0 `union` cv_ec C2 `union` fv_ec C2 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T1' `union` dom E' `union` dom D2') (fv_env Env) ->\n     disjdom (L0 `union` cv_ec C2 `union` fv_ec C2 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T1'  `union` dom E' `union` dom D2') (fv_lenv lEnv) ->\n     F_Related_osubst E' D2' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E' rsubst dsubst dsubst' Env ->\n     F_Related_oterms T1' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C2 e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C2 e'))))\n      Env lEnv\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n  disjdom (L0 `union` cv_ec C2 `union` (fv_ee e1 `union` fv_ec C2) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` dom D3') (fv_env Env) ->\n  disjdom (L0 `union` cv_ec C2 `union` (fv_ee e1 `union` fv_ec C2) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` dom D3') (fv_lenv lEnv) ->\n  F_Related_osubst E' D3' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n  F_Rosubst E' rsubst dsubst dsubst' Env  ->\n  F_Related_oterms T2' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_app e1 (plug C2 e)))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_app e1 (plug C2 e')))))\n      Env lEnv.\nProof.\n   intros e e' E D T Htyp Htyp' L0 Hlr T1' K E' D1' D2' D3' e1 C2 T2' H Hcontexting H0 H1 IHHcontexting dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv Disj00 Disj01 Hrel_sub HRsub.  \n   assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J. \n   destruct J as [[[[[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe] Hwfe'] HwfEnv] HwflEnv].\n   apply F_Related_osubst_split with (lE1:=D1') (lE2:=D2') in Hrel_sub; auto.\n   destruct Hrel_sub as [lgsubst1 [lgsubst1' [lgsubst2 [lgsubst2' [lEnv1 [lEnv2 [J1 [J2 [J3 J4]]]]]]]]].\n\n   assert (\n      F_Related_oterms (typ_arrow K T1' T2') rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst1 e1)))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst1' e1)))\n         Env lEnv1\n     ) as FR_ArrowType.\n    apply oparametricity with (E:=E') (lE:=D1'); auto.\n   destruct FR_ArrowType as [v [v' [Ht [Ht' [Hn [Hn' Hrel]]]]]].\n\n   apply F_Related_ovalues_arrow_leq in Hrel.\n   destruct Hrel as [Hv [Hv' [L Harrow]]]; subst.\n\n   assert (\n      F_Related_oterms T1' rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst2 (plug C2 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst'(apply_gamma_subst lgsubst2' (plug C2 e'))))\n         Env lEnv2\n     ) as FR_T1.\n    apply IHHcontexting; auto.\n      clear - Disj00 H1 H.\n      apply dom_lenv_split in H1.\n      apply typing_regular in H.\n      destruct H as [_ [_ [_ H]]].\n      apply wft_fv_tt_sub in H.\n      apply disjdom_sym_1.\n      apply disjdom_sub with (D1:=L0 `union` cv_ec C2 `union` (fv_ee e1 `union` fv_ec C2) `union` dom E `union` dom D `union` fv_tt T  `union` fv_tt T2' `union` dom E' `union` dom D3').\n        apply disjdom_sym_1; auto.\n        clear Disj00. rewrite H1. clear H1. simpl in H. fsetdec.        \n\n      clear - Disj01 H1 J1 H.\n      apply dom_lenv_split in H1.\n      apply lgamma_osubst_split__lenv_split in J1.\n      apply fv_lenv_split in J1.\n      apply typing_regular in H.\n      destruct H as [_ [_ [_ H]]].\n      apply wft_fv_tt_sub in H.\n      apply disjdom_sym_1.\n      apply disjdom_sub with (D1:=L0 `union` cv_ec C2 `union` (fv_ee e1 `union` fv_ec C2) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` dom D3').\n        apply disjdom_sym_1.\n        apply disjdom_sub with (D1:=fv_lenv lEnv); auto.\n          rewrite J1. clear. fsetdec.\n        clear Disj01. rewrite H1. clear H1 J1. simpl in H. fsetdec.        \n   destruct FR_T1 as [v0 [v'0 [Ht1 [Ht1' [Hn1 [Hn1' Hrel_wft1]]]]]].\n\n   clear Disj00 Disj01.\n\n   assert (lenv_split Env lEnv1 lEnv2 lEnv) as Split.\n     apply lgamma_osubst_split__lenv_split in J1. auto.\n\n   assert (uniq lEnv2) as Uniq2.\n     apply typing_regular in Ht1. destruct Ht1 as [JJ1 [JJ2 [JJ3 JJ4]]].\n     apply uniq_from_wf_lenv in JJ2; auto.\n   assert (JJ:=@pick_lenv (L `union` dom lEnv2 `union` dom lEnv `union` dom lEnv1 `union` dom Env `union` dom E' `union` dom D1' `union` dom D2' `union` dom D3' `union` dom E `union` dom D) lEnv2 Uniq2).\n   destruct JJ as [asubst [Wfa [lEnv2_eq_asubst Disj]]].\n   assert (disjoint asubst Env) as Disj1.\n     apply disjoint_split_right in Split.\n     apply disjoint_eq with (D1:=lEnv2); auto.\n   assert (disjdom (atom_subst_codom asubst) (union (dom Env) (dom lEnv2))) as Disj2.\n     apply disjdom_sym_1 in Disj.\n     apply disjdom_sub with (D2:=union (dom Env) (dom lEnv2)) in Disj; try solve [assumption].\n     clear. fsetdec.\n   destruct (@Harrow (subst_atoms_lenv asubst lEnv2) (subst_atoms_exp asubst v0) (subst_atoms_exp asubst v'0)) as [u [u' [Hnorm_vxu [Hnorm_v'x'u' Hrel_wft2]]]]; auto.\n     apply typing_lin_renamings; auto.\n       eapply preservation_normalization; eauto.\n     apply typing_lin_renamings; auto.\n       eapply preservation_normalization; eauto.\n     apply wf_lenv_merge; auto.\n       apply wf_lenv_renamings; auto.\n\n       assert (disjdom (atom_subst_codom asubst) (dom lEnv2)) as Disj3.\n         apply disjdom_app_r in Disj2. destruct Disj2.\n         apply disjdom_sym_1; auto.\n       assert (J:=@subst_atoms_lenv__dom_upper asubst lEnv2 Wfa Uniq2 Disj3).\n       apply disjdom__disjoint.\n       apply disjdom_sym_1.\n       apply disjdom_sub with (D1:=union (dom lEnv2) (atom_subst_codom asubst)); auto.\n       eapply disjdom_app_r.\n         split.\n           apply disjoint__disjdom.\n           apply disjoint_lenv_split' in Split.\n           apply disjoint_sym_1; auto.\n            \n           apply disjdom_sym_1 in Disj.\n           apply disjdom_sub with (D2:=(dom lEnv1)) in Disj; auto.\n             clear. fsetdec.\n\n     assert (J:=@subst_atoms_lenv__dom_eq asubst lEnv2 Wfa Uniq2 lEnv2_eq_asubst).\n     apply disjdom_sym_1 in Disj.\n     apply disjdom_sub with (D2:=L) in Disj; auto.\n       apply disjdom_sym_1.\n       apply disjdom_eq with (D1:=atom_subst_codom asubst); auto.\n          rewrite J. clear. fsetdec.       \n       clear. fsetdec.\n     apply Forel_lin_renamings with (E:=E'); auto.\n       eapply preservation_normalization; eauto.\n       eapply preservation_normalization; eauto.\n\n   assert (F_Related_ovalues T2' rsubst dsubst dsubst' (rev_subst_atoms_exp asubst u) (rev_subst_atoms_exp asubst u') Env (lEnv2++lEnv1)) as Hrel_wft2'.\n     assert (lEnv2++lEnv1 = rev_subst_atoms_lenv asubst ((subst_atoms_lenv asubst lEnv2)++ lEnv1)) as Eq1.\n       rewrite rev_subst_atoms_lenv_app.\n       rewrite <- id_rev_subst_atoms_lenv; auto.\n         rewrite <- rev_subst_atoms_lenv_notin_inv; auto.\n           apply disjdom_sym_1 in Disj.\n           apply disjdom_sub with (D2:=dom lEnv1) in Disj; auto.\n             clear. fsetdec.\n         rewrite lEnv2_eq_asubst. clear. fsetdec.\n\n         apply disjdom_sym_1 in Disj.\n         apply disjdom_sub with (D2:=dom lEnv2) in Disj; auto.\n           clear. fsetdec.\n     rewrite Eq1.\n     apply Forel_lin_rev_renamings with (E:=E'); auto.\n       apply preservation_normalization with (e:=exp_app v (subst_atoms_exp asubst v0)); auto.\n         apply typing_app with (T1:=apply_delta_subst_typ dsubst T1') (K:=K) (D1:=lEnv1) (D2:=subst_atoms_lenv asubst lEnv2).\n           simpl_commut_subst in Ht.\n           apply preservation_normalization with (v:=v) in Ht; auto.\n\n           apply preservation_normalization with (v:=v0) in Ht1; auto.\n           apply typing_lin_renamings; auto.\n\n           apply lenv_split_commute.\n           apply disjoint__lenv_split; auto.\n             apply wf_lenv_renamings; auto.\n\n             assert (J:=@subst_atoms_lenv__dom_eq asubst lEnv2 Wfa Uniq2 lEnv2_eq_asubst).\n             apply disjdom_sym_1 in Disj.\n             apply disjdom_sub with (D2:=dom lEnv1) in Disj; auto.\n               apply disjdom__disjoint.\n               apply disjdom_eq with (D1:=atom_subst_codom asubst); auto.\n                 rewrite J. clear. fsetdec.             \n               clear. fsetdec.\n\n       apply preservation_normalization with (e:=exp_app v' (subst_atoms_exp asubst v'0)); auto.\n         apply typing_app with (T1:=apply_delta_subst_typ dsubst' T1') (K:=K) (D1:=lEnv1) (D2:=subst_atoms_lenv asubst lEnv2).\n           simpl_commut_subst in Ht'.\n           apply preservation_normalization with (v:=v') in Ht'; auto.\n\n           apply preservation_normalization with (v:=v'0) in Ht1'; auto.\n           apply typing_lin_renamings; auto.\n\n           apply lenv_split_commute.\n           apply disjoint__lenv_split; auto.\n             apply wf_lenv_renamings; auto.\n\n             assert (J:=@subst_atoms_lenv__dom_eq asubst lEnv2 Wfa Uniq2 lEnv2_eq_asubst).\n             apply disjdom_sym_1 in Disj.\n             apply disjdom_sub with (D2:=dom lEnv1) in Disj; auto.\n               apply disjdom__disjoint.\n               apply disjdom_eq with (D1:=atom_subst_codom asubst); auto.\n                 rewrite J. clear. fsetdec.             \n               clear. fsetdec.\n\n       apply disjdom_sym_1 in Disj.\n       apply disjdom_sub with (D2:=dom Env) in Disj; auto.\n         clear. fsetdec.\n\n       apply disjdom_eq with (D1:=dom lEnv2); auto.\n       eapply disjdom_app_r.\n       split.\n         apply disjoint__disjdom.\n         apply disjoint_split_right in Split; auto.\n       \n         apply disjoint__disjdom.\n         eapply disjoint_app_l.\n         split.\n           assert (J:=@subst_atoms_lenv__dom_eq asubst lEnv2 Wfa Uniq2 lEnv2_eq_asubst).\n           apply disjdom__disjoint.\n           apply disjdom_eq with (D1:=atom_subst_codom asubst); auto.\n             apply disjdom_sym_1 in Disj.\n             apply disjdom_sub with (D2:=dom lEnv2) in Disj; auto.\n               clear. fsetdec.             \n             rewrite J. clear. fsetdec.\n\n           apply disjoint_lenv_split' in Split; auto.\n   assert (normalize (exp_app v v0) (rev_subst_atoms_exp asubst u)) as Hnorm'_vxu.\n     apply normalize_rev_renamings with (asubst:=asubst) in Hnorm_vxu; auto.\n     rewrite rev_subst_atoms_exp__app in Hnorm_vxu.\n     rewrite <- id_rev_subst_atoms_exp with (asubst:=asubst) in Hnorm_vxu; auto.\n       rewrite <- rev_wf_asubst_id with (asubst:=asubst) (e:=v) in Hnorm_vxu; auto.\n       apply disjdom_sub with (D1:=dom Env `union` dom lEnv1).\n         eapply disjdom_app_r.\n         split.\n           apply disjdom_sym_1.\n           apply disjdom_sym_1 in Disj.\n           apply disjdom_sub with (D2:=dom Env) in Disj; auto.\n             clear. fsetdec.             \n           apply disjdom_sym_1.\n           apply disjdom_sym_1 in Disj.\n           apply disjdom_sub with (D2:=dom lEnv1) in Disj; auto.\n             clear. fsetdec.             \n         apply preservation_normalization with (v:=v) in Ht; auto.\n         apply typing_fv_ee_upper in Ht; auto.\n      apply preservation_normalization with (v:=v0) in Ht1; auto.      \n      apply typing_fv_ee_lower in Ht1; auto.\n      rewrite <- lEnv2_eq_asubst. assumption.\n\n      apply preservation_normalization with (v:=v0) in Ht1; auto.\n      apply typing_fv_ee_upper in Ht1; auto.\n      apply disjdom_sub with (D1:=union (dom Env) (dom lEnv2)); auto.  \n\n   assert (normalize (exp_app v' v'0) (rev_subst_atoms_exp asubst u')) as Hnorm'_v'x'u'.\n     apply normalize_rev_renamings with (asubst:=asubst) in Hnorm_v'x'u'; auto.\n     rewrite rev_subst_atoms_exp__app in Hnorm_v'x'u'.\n     rewrite <- id_rev_subst_atoms_exp with (asubst:=asubst) in Hnorm_v'x'u'; auto.\n       rewrite <- rev_wf_asubst_id with (asubst:=asubst) (e:=v') in Hnorm_v'x'u'; auto.\n       apply disjdom_sub with (D1:=dom Env `union` dom lEnv1).\n         eapply disjdom_app_r.\n         split.\n           apply disjdom_sym_1.\n           apply disjdom_sym_1 in Disj.\n           apply disjdom_sub with (D2:=dom Env) in Disj; auto.\n             clear. fsetdec.             \n           apply disjdom_sym_1.\n           apply disjdom_sym_1 in Disj.\n           apply disjdom_sub with (D2:=dom lEnv1) in Disj; auto.\n             clear. fsetdec.             \n         apply preservation_normalization with (v:=v') in Ht'; auto.\n         apply typing_fv_ee_upper in Ht'; auto.\n      apply preservation_normalization with (v:=v'0) in Ht1'; auto.\n      apply typing_fv_ee_lower in Ht1'; auto.\n      rewrite <- lEnv2_eq_asubst. assumption.\n\n      apply preservation_normalization with (v:=v'0) in Ht1'; auto.\n      apply typing_fv_ee_upper in Ht1'; auto.\n      apply disjdom_sub with (D1:=union (dom Env) (dom lEnv2)); auto.  \n\n   exists(rev_subst_atoms_exp asubst u). exists(rev_subst_atoms_exp asubst u').\n   assert (apply_delta_subst dsubst\n            (apply_gamma_subst gsubst\n              (apply_gamma_subst lgsubst (exp_app e1 (plug C2 e))) \n            ) =\n            apply_delta_subst dsubst\n            (apply_gamma_subst gsubst\n              (exp_app \n                (apply_gamma_subst lgsubst1 e1)\n                (apply_gamma_subst lgsubst2 (plug C2 e))\n              )               \n            )\n          ) as EQ.\n     simpl_commut_subst in *.\n     rewrite lgamma_subst_split_osubst' with (lgsubst1:=lgsubst1) (lgsubst2:=lgsubst2) (E:=E') (lE:=D3') (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst) (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv); auto.\n     rewrite lgamma_subst_split_osubst with (lgsubst1:=lgsubst1) (lgsubst2:=lgsubst2) (E:=E') (lE:=D3') (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst) (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv); auto.\n     apply F_Related_osubst__inversion in J3.\n     decompose [prod] J3; auto.\n     apply F_Related_osubst__inversion in J4.\n     decompose [prod] J4; auto.\n     rewrite lgamma_osubst_split_shuffle2 with (lgsubst:=lgsubst) (lgsubst1:=lgsubst1) (E:=E') (lE:=D3') (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv) ; auto.\n     erewrite gamma_osubst_closed_exp; eauto.\n     rewrite lgamma_osubst_split_shuffle1 with (lgsubst:=lgsubst) (lgsubst2:=lgsubst2) (E:=E') (lE:=D3') (e:=apply_gamma_subst lgsubst2 (plug C2 e)) (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv) ; auto.\n     erewrite gamma_osubst_closed_exp with \n         (e:=apply_delta_subst dsubst\n            (apply_gamma_subst gsubst\n              (apply_gamma_subst lgsubst2 (plug C2 e)))\n          ); eauto.\n         unfold disjdom.\n         split; intros x xnotin.\n           apply in_fv_ee_typing with (x:=x) in Ht1; try solve [assumption].\n           assert (x `in` dom Env \\/ x `in` dom lEnv2) as J. clear - Ht1. fsetdec.\n           destruct J as [J | J].\n             apply disjoint_lgamma_osubst in b5.\n             decompose [and] b5. clear b5.\n             clear - J H6.\n             apply disjoint_innotin2 with (x:=x) in H6; auto.\n\n             assert (x `in` dom lEnv)as J'.\n               apply dom_lenv_split in Split.\n               rewrite Split. auto.\n             assert (dom D1' [=] dom lgsubst1) as DomEq.\n               apply dom_lgamma_osubst in b5.\n               decompose [and] b5; auto.\n             rewrite <- DomEq.\n             assert (x `notin` dom D3')as J''.            \n               apply lgamma_osubst_split__wf_lgamma_osubst in J1.\n               apply disjoint_lgamma_osubst in J1.\n               decompose [and] J1. clear J1.             \n               clear - J' H8.\n               apply disjoint_innotin2 with (x:=x) in H8; auto.\n             apply dom_lenv_split in H1.\n             rewrite H1 in J''. auto.\n\n           assert (x `notin` dom Env) as J'.\n             apply disjoint_lgamma_osubst in b5.\n             decompose [and] b5. clear b5.\n             clear - xnotin H6.\n             apply disjoint_innotin1 with (x:=x) in H6; auto.\n\n           assert ( x `notin` dom lEnv2) as J''.\n             assert (dom D1' [=] dom lgsubst1) as DomEq.\n               apply dom_lgamma_osubst in b5.\n               decompose [and] b5; auto.\n             rewrite <- DomEq in xnotin.\n             assert (x `in` dom D3')as J'''.            \n               apply dom_lenv_split in H1.\n               rewrite H1. auto.\n             assert (x `notin` dom lEnv)as JJ'.\n               apply lgamma_osubst_split__wf_lgamma_osubst in J1.\n               apply disjoint_lgamma_osubst in J1.\n               decompose [and] J1. clear J1.             \n               clear - J''' H8.\n               apply disjoint_innotin1 with (x:=x) in H8; auto.\n           apply dom_lenv_split in Split.\n             rewrite Split in JJ'. auto.\n           apply notin_fv_ee_typing with (y:=x) in Ht1; auto.\n\n       unfold disjdom.\n       split; intros x xnotin.\n         apply in_fv_ee_typing with (x:=x) in Ht; try solve [assumption].\n         assert (x `in` dom Env \\/ x `in` dom lEnv1) as J. \n           clear - Ht.\n           fsetdec.\n         destruct J as [J | J].\n           apply disjoint_lgamma_osubst in b13.\n           decompose [and] b13. clear b13.\n           clear - J H6.\n           apply disjoint_innotin2 with (x:=x) in H6; auto.\n\n           assert (x `in` dom lEnv)as J'.\n             apply dom_lenv_split in Split.\n             rewrite Split. auto.\n           assert (dom D2' [=] dom lgsubst2) as DomEq.\n             apply dom_lgamma_osubst in b13.\n             decompose [and] b13; auto.\n           rewrite <- DomEq.\n           assert (x `notin` dom D3')as J''.            \n             apply lgamma_osubst_split__wf_lgamma_osubst in J1.\n             apply disjoint_lgamma_osubst in J1.\n             decompose [and] J1. clear J1.             \n             clear - J' H8.\n             apply disjoint_innotin2 with (x:=x) in H8; auto.\n           apply dom_lenv_split in H1.\n           rewrite H1 in J''. auto.\n         assert (x `notin` dom Env) as J'.\n           apply disjoint_lgamma_osubst in b13.\n           decompose [and] b13. clear b13.\n           clear - xnotin H6.\n           apply disjoint_innotin1 with (x:=x) in H6; auto.\n         assert ( x `notin` dom lEnv1) as J''.\n           assert (dom D2' [=] dom lgsubst2) as DomEq.\n             apply dom_lgamma_osubst in b13.\n             decompose [and] b13; auto.\n           rewrite <- DomEq in xnotin.\n           assert (x `in` dom D3')as J'''.            \n             apply dom_lenv_split in H1.\n             rewrite H1. auto.\n           assert (x `notin` dom lEnv)as JJ'.\n             apply lgamma_osubst_split__wf_lgamma_osubst in J1.\n             apply disjoint_lgamma_osubst in J1.\n             decompose [and] J1. clear J1.             \n             clear - J''' H8.\n             apply disjoint_innotin1 with (x:=x) in H8; auto.\n           apply dom_lenv_split in Split.\n           rewrite Split in JJ'. auto.\n         apply notin_fv_ee_typing with (y:=x) in Ht; auto.\n   repeat(rewrite EQ). clear EQ.\n   assert (apply_delta_subst dsubst'\n            (apply_gamma_subst gsubst'\n              (apply_gamma_subst lgsubst' (exp_app e1 (plug C2 e'))) \n            ) =\n            apply_delta_subst dsubst'\n            (apply_gamma_subst gsubst'\n              (exp_app \n                (apply_gamma_subst lgsubst1' e1)\n                (apply_gamma_subst lgsubst2' (plug C2 e'))\n              )               \n            )\n          ) as EQ.\n     simpl_commut_subst in *.\n     rewrite lgamma_subst_split_osubst' with (lgsubst1:=lgsubst1') (lgsubst2:=lgsubst2') (E:=E') (lE:=D3') (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst') (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv); auto.\n     rewrite lgamma_subst_split_osubst with (lgsubst1:=lgsubst1') (lgsubst2:=lgsubst2') (E:=E') (lE:=D3') (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst') (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv); auto.\n     apply F_Related_osubst__inversion in J3.\n     decompose [prod] J3; auto.\n     apply F_Related_osubst__inversion in J4.\n     decompose [prod] J4; auto.\n     rewrite lgamma_osubst_split_shuffle2 with (lgsubst:=lgsubst') (lgsubst1:=lgsubst1') (E:=E') (lE:=D3')  (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv); auto.\n     erewrite gamma_osubst_closed_exp; eauto.\n     rewrite lgamma_osubst_split_shuffle1 with (lgsubst:=lgsubst') (lgsubst2:=lgsubst2') (E:=E') (lE:=D3') (e:=apply_gamma_subst lgsubst2' (plug C2 e'))  (Env:=Env) (lEnv1:=lEnv1) (lEnv2:=lEnv2) (lEnv:=lEnv); auto.\n     erewrite gamma_osubst_closed_exp with \n         (e:=apply_delta_subst dsubst'\n            (apply_gamma_subst gsubst'\n              (apply_gamma_subst lgsubst2' (plug C2 e')))\n          ); eauto.\n         unfold disjdom.\n         split; intros x xnotin.\n           apply in_fv_ee_typing with (x:=x) in Ht1'; try solve [assumption].\n           assert (x `in` dom Env \\/ x `in` dom lEnv2) as J. \n             clear - Ht1'.\n             fsetdec.\n           destruct J as [J | J].\n             apply disjoint_lgamma_osubst in b4.\n             decompose [and] b4. clear b4.\n             clear - J H6.\n             apply disjoint_innotin2 with (x:=x) in H6; auto.\n\n             assert (x `in` dom lEnv)as J'.\n               apply dom_lenv_split in Split.\n               rewrite Split. auto.\n             assert (dom D1' [=] dom lgsubst1') as DomEq.\n               apply dom_lgamma_osubst in b4.\n               decompose [and] b4; auto.\n             rewrite <- DomEq.\n             assert (x `notin` dom D3')as J''.            \n               apply lgamma_osubst_split__wf_lgamma_osubst in J2.\n               apply disjoint_lgamma_osubst in J2.\n               decompose [and] J2. clear J2.             \n               clear - J' H8.\n               apply disjoint_innotin2 with (x:=x) in H8; auto.\n           apply dom_lenv_split in H1.\n             rewrite H1 in J''. auto.\n\n           assert (x `notin` dom Env) as J'.\n             apply disjoint_lgamma_osubst in b4.\n             decompose [and] b4. clear b4.\n             clear - xnotin H6.\n             apply disjoint_innotin1 with (x:=x) in H6; auto.\n\n           assert ( x `notin` dom lEnv2) as J''.\n             assert (dom D1' [=] dom lgsubst1') as DomEq.\n               apply dom_lgamma_osubst in b4.\n               decompose [and] b4; auto.\n             rewrite <- DomEq in xnotin.\n             assert (x `in` dom D3')as J'''.            \n               apply dom_lenv_split in H1.\n               rewrite H1. auto.\n             assert (x `notin` dom lEnv)as JJ'.\n               apply lgamma_osubst_split__wf_lgamma_osubst in J2.\n               apply disjoint_lgamma_osubst in J2.\n               decompose [and] J2. clear J2.             \n               clear - J''' H8.\n               apply disjoint_innotin1 with (x:=x) in H8; auto.\n           apply dom_lenv_split in Split.\n             rewrite Split in JJ'. auto.\n           apply notin_fv_ee_typing with (y:=x) in Ht1'; auto.\n\n       unfold disjdom.\n       split; intros x xnotin.\n         apply in_fv_ee_typing with (x:=x) in Ht'; try solve [assumption].\n         assert (x `in` dom Env \\/ x `in` dom lEnv1) as J. \n           clear - Ht'.\n           fsetdec.\n         destruct J as [J | J].\n           apply disjoint_lgamma_osubst in b12.\n           decompose [and] b12. clear b12.\n           clear - J H6.\n           apply disjoint_innotin2 with (x:=x) in H6; auto.\n\n           assert (x `in` dom lEnv)as J'.\n             apply dom_lenv_split in Split.\n             rewrite Split. auto.\n           assert (dom D2' [=] dom lgsubst2') as DomEq.\n             apply dom_lgamma_osubst in b12.\n             decompose [and] b12; auto.\n           rewrite <- DomEq.\n           assert (x `notin` dom D3')as J''.            \n             apply lgamma_osubst_split__wf_lgamma_osubst in J2.\n             apply disjoint_lgamma_osubst in J2.\n             decompose [and] J2. clear J2.             \n             clear - J' H8.\n             apply disjoint_innotin2 with (x:=x) in H8; auto.\n           apply dom_lenv_split in H1.\n           rewrite H1 in J''. auto.\n         assert (x `notin` dom Env) as J'.\n           apply disjoint_lgamma_osubst in b12.\n           decompose [and] b12. clear b12.\n           clear - xnotin H6.\n           apply disjoint_innotin1 with (x:=x) in H6; auto.\n        assert ( x `notin` dom lEnv1) as J''.\n           assert (dom D2' [=] dom lgsubst2') as DomEq.\n             apply dom_lgamma_osubst in b12.\n             decompose [and] b12; auto.\n           rewrite <- DomEq in xnotin.\n           assert (x `in` dom D3')as J'''.            \n             apply dom_lenv_split in H1.\n             rewrite H1. auto.\n           assert (x `notin` dom lEnv)as JJ'.\n             apply lgamma_osubst_split__wf_lgamma_osubst in J2.\n             apply disjoint_lgamma_osubst in J2.\n             decompose [and] J2. clear J2.             \n             clear - J''' H8.\n             apply disjoint_innotin1 with (x:=x) in H8; auto.\n           apply dom_lenv_split in Split.\n           rewrite Split in JJ'. auto.\n         apply notin_fv_ee_typing with (y:=x) in Ht'; auto.\n   repeat(rewrite EQ). clear EQ.\n   repeat(split; try solve [simpl_commut_subst in *; eauto |\n                                              simpl_commut_subst; apply congr_app with (v1:=v) (v2:=v0); auto |\n                                              simpl_commut_subst; apply congr_app with (v1:=v') (v2:=v'0); auto]).\n    apply Forel_lin_domeq with (lEnv:=lEnv2++lEnv1); auto.\n      apply wf_lenv_merge; auto.\n        apply disjoint_lenv_split' in Split; auto.\n      apply dom_lenv_split in Split.\n        rewrite Split. simpl_env. clear. fsetdec.\nQed.\n\nLemma F_ological_related_congruence__tabs_free :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  forall L0,\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n   disjdom L0 (fv_env Env) ->\n   disjdom L0 (fv_lenv lEnv) ->\n   F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n   F_Rosubst E rsubst dsubst dsubst' Env ->\n   F_Related_oterms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n     Env lEnv\n  ) ->\n  forall L K C1 T1' E' D',\n  (forall X, X `notin` L -> vcontext (open_tc C1 X)) ->\n  (forall X,\n    X `notin` L ->\n    contexting E D T (open_tc C1 X) ((X, bind_kn K)::E') D' (open_tt T1' X)\n  ) ->\n  (forall X,\n   X `notin` L ->\n   typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom L0 (fv_env Env) ->\n     disjdom L0 (fv_lenv lEnv) ->\n     F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E rsubst dsubst dsubst' Env ->\n     F_Related_oterms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n      Env lEnv\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom (L0 `union` cv_ec (open_tc C1 X) `union` fv_ec (open_tc C1 X) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt (open_tt T1' X) `union` (add X (dom E')) `union` dom D') (fv_env Env) ->\n     disjdom (L0 `union` cv_ec (open_tc C1 X) `union` fv_ec (open_tc C1 X) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt (open_tt T1' X) `union` (add X (dom E')) `union` dom D') (fv_lenv lEnv) ->\n     F_Related_osubst ((X, bind_kn K)::E') D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst ((X, bind_kn K)::E') rsubst dsubst dsubst' Env ->\n     F_Related_oterms (open_tt T1' X) rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug (open_tc C1 X) e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug (open_tc C1 X) e'))))\n      Env lEnv\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n  disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T1'  `union` dom E' `union` dom D') (fv_env Env) ->\n  disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T1'  `union` dom E' `union` dom D') (fv_lenv lEnv) ->\n  F_Related_osubst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n  F_Rosubst E' rsubst dsubst dsubst' Env  ->\n  F_Related_oterms (typ_all K T1') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_tabs K (plug C1 (shift_te e))))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_tabs K (plug C1 (shift_te e'))))))\n      Env lEnv.\nProof.\n  intros e e' E D T Htyp Htyp' L0 Hlr L K C1 T1' E' D' H0 H1 H2 dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv Disj00 Disj01 Hrel_sub HRsub.\n  assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J.\n  destruct J as [[[[[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe] Hwfe'] HwfEnv] HwflEnv].\n  assert (value (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_tabs K (plug C1 (shift_te e))))))) as Value.\n    clear Disj00 Disj01.\n    apply delta_gamma_lgamma_osubst_value with (E:=E') (D:=D') (Env:=Env) (lEnv:=lEnv); auto.\n      apply value_tabs; auto.\n        apply expr_tabs with (L:=L `union` cv_ec C1); auto.\n          intros X Xn.\n          assert (X `notin` L) as XnFv. auto.\n          apply H1 in XnFv.\n          apply contexting_plug_typing with (e:=e) in XnFv; auto.\n          simpl_env in XnFv.\n          rewrite open_te_expr' with (e:=e) (u:=X) in XnFv; auto.\n          assert (disjdom (fv_tt X) (cv_ec C1)) as Disj.\n            apply disjdom_one_2; auto.\n          rewrite <- open_te_plug in XnFv; auto. \n          rewrite shift_te_expr with (e:=e) in XnFv; auto.\n  assert (value (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_tabs K (plug C1 (shift_te e'))))))) as Value'.\n    clear Disj00 Disj01.\n    apply delta_gamma_lgamma_osubst_value with (E:=E') (D:=D')(Env:=Env) (lEnv:=lEnv); auto.\n      apply value_tabs; auto.\n        apply expr_tabs with (L:=L `union` cv_ec C1); auto.\n          intros X Xn.\n          assert (X `notin` L) as XnFv. auto.\n          apply H1 in XnFv.\n          apply contexting_plug_typing with (e:=e') in XnFv; auto.\n          simpl_env in XnFv.\n          rewrite open_te_expr' with (e:=e') (u:=X) in XnFv; auto.\n          assert (disjdom (fv_tt X) (cv_ec C1)) as Disj.\n            apply disjdom_one_2; auto.\n          rewrite <- open_te_plug in XnFv; auto. \n          rewrite shift_te_expr with (e:=e') in XnFv; auto.\n    \n  exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_tabs K (plug C1 (shift_te e)))))).\n  exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_tabs K (plug C1 (shift_te e')))))).\n    split.\n      assert (typing E' D' (plug (ctx_tabs_free K C1) e) (typ_all K T1')) as Hptyp.\n        apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n           apply contexting_tabs_free with (L:=L); auto.\n      apply typing_osubst with (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst) (Env:=Env) (lEnv:=lEnv)in Hptyp; auto.\n    split.\n      assert (typing E' D' (plug (ctx_tabs_free K C1) e') (typ_all K T1')) as Hptyp'.\n        apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n           apply contexting_tabs_free with (L:=L); auto.\n      apply typing_osubst with (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst')(Env:=Env) (lEnv:=lEnv) in Hptyp'; auto.\n    split. split; auto.\n    split. split; auto.\n      SCase \"Frel\".\n      apply F_Related_ovalues_all_req.\n      split; auto.\n      split; auto.\n        SSCase \"Frel\".\n        exists (L `union` fv_te e `union` dom E `union` fv_env E `union` fv_lenv D `union` fv_env E' `union` fv_lenv D' `union` cv_ec C1 `union` fv_te (plug C1 e) `union` fv_te (plug C1 e') `union` fv_env Env `union` fv_lenv lEnv).\n        intros X t2 t2' R Fr HwfR Hfv.\n        assert (X `notin` L) as FryL. auto.\n        assert (wf_typ ([(X,bind_kn K)]++E') (open_tt T1' X) kn_lin) as WFT'.\n          apply H1 in FryL.\n          apply contexting_regular in FryL.\n          decompose [and] FryL; auto.\n        apply H2 with (dsubst:=[(X, t2)]++dsubst) \n                         (dsubst':=[(X, t2')]++dsubst') \n                         (gsubst:=gsubst)\n                         (gsubst':=gsubst') \n                         (lgsubst:=lgsubst)\n                         (lgsubst':=lgsubst') (Env:=Env) (lEnv:=lEnv)\n                         (rsubst:=[(X,R)]++rsubst)in FryL; auto.\n        simpl in FryL. simpl_env in FryL.\n        clear Disj00 Disj01.\n        erewrite swap_subst_te_ogsubst with (E:=E') (dsubst:=dsubst) (Env:=Env) (lEnv:=lEnv)in FryL; eauto using wfor_left_inv. \n        erewrite swap_subst_te_olgsubst with (E:=E') (dsubst:=dsubst) (Env:=Env) (lEnv:=lEnv)in FryL; eauto using wfor_left_inv. \n        erewrite swap_subst_te_ogsubst with  (E:=E')  (dsubst:=dsubst') (Env:=Env) (lEnv:=lEnv)in FryL; eauto using wfor_right_inv.\n        erewrite swap_subst_te_olgsubst with  (E:=E')  (dsubst:=dsubst') (Env:=Env) (lEnv:=lEnv)in FryL; eauto using wfor_right_inv.\n        destruct FryL as [v [v' [Ht [Ht' [[Hbrc Hv] [[Hbrc' Hv'] Hrel]]]]]].\n        exists (v). exists (v').\n        split.\n          SSSCase \"norm\".\n          split; auto.\n          apply bigstep_red_trans with (e':=(apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (subst_te X t2 (plug (open_tc C1 X) e)))))); auto.\n              rewrite <- shift_te_expr; auto.\n             assert (plug (open_tc C1 X) e = open_te (plug C1 e) X) as EQ.\n               rewrite open_te_plug; auto.\n                 rewrite <- open_te_expr'; auto.\n                 apply disjdom_one_2; auto.\n             rewrite EQ.\n             eapply m_red_tabs_osubst with (T1:=T1') (L:=L `union` cv_ec C1); eauto.\n               apply wfor_left_inv in HwfR; auto.\n\n               intros X0 X0dom.\n               assert (X0 `notin` L) as X0n. auto.\n               apply H1 in X0n.\n               assert (disjdom (fv_tt X0) (cv_ec C1)) as Disj.\n                 apply disjdom_one_2; auto.\n               rewrite open_te_plug; auto.\n               rewrite <- open_te_expr'; auto.\n               apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.       \n\n        split; auto.\n          SSSCase \"norm\".\n          split; auto.\n          apply bigstep_red_trans with (e':=(apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (subst_te X t2' (plug (open_tc C1 X) e')))))); auto.\n              rewrite <- shift_te_expr; auto.\n             assert (plug (open_tc C1 X) e' = open_te (plug C1 e') X) as EQ.\n               rewrite open_te_plug; auto.\n                 rewrite <- open_te_expr'; auto.\n                 apply disjdom_one_2; auto.\n             rewrite EQ.\n             eapply m_red_tabs_osubst with (T1:=T1') (L:=L `union` cv_ec C1); eauto.\n               apply wfor_right_inv in HwfR; auto.\n\n               intros X0 X0dom.\n               assert (X0 `notin` L) as X0n. auto.\n               apply H1 in X0n.\n               assert (disjdom (fv_tt X0) (cv_ec C1)) as Disj.\n                 apply disjdom_one_2; auto.\n               rewrite open_te_plug; auto.\n               rewrite <- open_te_expr'; auto.\n               apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.       \n\n          clear - Fr Disj00.\n          assert (J:=@open_tc_fv_ec_eq C1 X).\n          assert (J':=@cv_ec_open_tc_rec C1 0 X).\n          assert (J'':=@open_tt_fv_tt_upper T1' X).\n          unfold open_tc in *.\n          apply disjdom_sym_1.\n          apply disjdom_sub with (D1:={{X}} `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T1' `union` dom E' `union` dom D').\n          eapply disjdom_app_r.\n          split; auto.\n            destruct_notin.\n            clear - NotInTac8.\n            apply disjdom_one_2; auto.\n           \n            rewrite J'. rewrite J.\n            clear - J''.  simpl in J''.  fsetdec.\n\n          clear - Fr Disj01.\n          assert (J:=@open_tc_fv_ec_eq C1 X).\n          assert (J':=@cv_ec_open_tc_rec C1 0 X).\n          assert (J'':=@open_tt_fv_tt_upper T1' X).\n          unfold open_tc in *.\n          apply disjdom_sym_1.\n          apply disjdom_sub with (D1:={{X}} `union` L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T1' `union` dom E' `union` dom D').\n          eapply disjdom_app_r.\n          split; auto.\n            destruct_notin.\n            clear - NotInTac9.\n            apply disjdom_one_2; auto.\n           \n            rewrite J'. rewrite J.\n            clear - J''.  simpl in J''.  fsetdec.\n\n          SSSCase \"Fsubst\".\n          simpl_env.\n          apply F_Related_osubst_kind; auto.\n          SSSCase \"FRsubst\".\n          simpl_env.\n          apply F_Rosubst_rel; auto.\nQed.\n\nLemma F_ological_related_congruence__tabs_capture :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  forall L0,\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n   disjdom L0 (fv_env Env) ->\n   disjdom L0 (fv_lenv lEnv) ->\n   F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n   F_Rosubst E rsubst dsubst dsubst' Env ->\n   F_Related_oterms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n     Env lEnv\n  ) ->\n  forall Y K C1 T1' E' D',\n  binds Y (bind_kn K) E' ->\n  Y `notin` cv_ec C1 ->\n  vcontext C1 ->\n  contexting E D T C1 E' D' T1' ->\n  wf_lenv (env_remove (Y, bind_kn K) E') D' ->\n  (typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom L0 (fv_env Env) ->\n     disjdom L0 (fv_lenv lEnv) ->\n     F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E rsubst dsubst dsubst' Env ->\n     F_Related_oterms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n      Env lEnv\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T1' `union` dom E' `union` dom D') (fv_env Env) ->\n     disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T1' `union` dom E' `union` dom D') (fv_lenv lEnv) ->\n     F_Related_osubst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E' rsubst dsubst dsubst' Env ->\n     F_Related_oterms T1' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n      Env lEnv\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n  disjdom (L0 `union` ({{Y}} `union` cv_ec (close_tc C1 Y)) `union` fv_ec  (close_tc C1 Y) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt (close_tt T1' Y)  `union` dom (env_remove (Y, bind_kn K) E') `union` dom D') (fv_env Env) ->\n  disjdom (L0 `union` ({{Y}} `union` cv_ec  (close_tc C1 Y)) `union` fv_ec  (close_tc C1 Y) `union` dom E `union` dom D `union` fv_tt T `union` fv_tt (close_tt T1' Y)  `union` dom (env_remove (Y, bind_kn K) E')  `union` dom D') (fv_lenv lEnv) ->\n  F_Related_osubst (env_remove (Y, bind_kn K) E') D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n  F_Rosubst (env_remove (Y, bind_kn K) E') rsubst dsubst dsubst' Env  ->\n  F_Related_oterms (typ_all K (close_tt T1' Y)) rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_tabs K (plug (close_tc C1 Y) (close_te (shift_te e) Y))))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_tabs K (plug (close_tc C1 Y) (close_te (shift_te e') Y))))))\n      Env lEnv.\nProof.\n    intros e e' E D T Htyp Htyp' L0 Hlr Y K C1 T1' E' D' H H0 H1 Hcontexting H2 IHHcontexting dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv Disj00 Disj01 Hrel_sub HRsub.\n    assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J. \n    destruct J as [[[[[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe] Hwfe'] HwfEnv] HwflEnv].\n\n    assert (Fry := @IHHcontexting Htyp Htyp' Hlr).\n    assert (wf_env E') as Wfe'.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (EQ1:=@env_remove_inv E' Y (bind_kn K)  Wfe' H).\n    destruct EQ1 as [E1' [E2' [EQ1' EQ2']]]; subst.\n    rewrite EQ1' in *.\n\n    assert (EQ:=Hwflg).\n    apply wf_olgsubst_app_inv in EQ.\n    destruct EQ as [dsubst1 [dsubst2 [gsubst1 [gsubst2 [dEQ1 [dEQ2 [dEQ3 [gEQ1 [gEQ2 gEQ3]]]]]]]]]; subst.\n\n    assert (EQ:=Hwflg').\n    apply wf_olgsubst_app_inv in EQ.\n    destruct EQ as [dsubst1' [dsubst2' [gsubst1' [gsubst2' [dEQ1' [dEQ2' [dEQ3' [gEQ1' [gEQ2' gEQ3']]]]]]]]]; subst.\n       \n    assert (EQ:=Hwfr).\n    apply wf_rsubst_app_inv in EQ.\n    destruct EQ as [rsubst1 [rsubst2 [rEQ1 [rEQ2 rEQ3]]]]; subst.\n\n    assert (value (apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (exp_tabs K (plug (close_tc C1 Y) (close_te (shift_te e) Y))))))) as Value.\n      clear Disj00 Disj01.\n      apply delta_gamma_lgamma_osubst_value with (E:=E1'++E2') (D:=D')(Env:=Env)(lEnv:=lEnv); auto.\n        apply value_tabs.\n        apply expr_tabs with (L:=dom (E1'++E2') `union` dom D' `union` cv_ec (close_tc C1 Y) `union` cv_ec C1); auto.\n          intros X XnFv.\n          rewrite <- shift_te_expr with (e:=e); auto.\n          assert (disjdom (fv_tt X) (cv_ec (close_tc C1 Y))) as Disj.\n            apply disjdom_one_2; auto.\n          rewrite open_te_plug; auto. \n          rewrite close_open_te__subst_te; auto.\n          assert (context C1) as Ctx1.\n            apply contexting__context in Hcontexting; auto.\n          rewrite close_open_tc__subst_tc; auto.\n          assert (disjdom (union {{Y}} (fv_tt X)) (cv_ec C1)) as Disj'.\n            eapply disjdom_app_l.\n            split.\n              clear - H0.\n              apply disjdom_one_2; auto.\n              clear - XnFv.\n              apply disjdom_one_2; auto.\n          rewrite <- subst_te_plug; auto. \n          assert (typing (E1'++[(Y, bind_kn K)]++E2') D' (plug C1 e) T1') as Htyp2.\n            apply contexting_plug_typing with (e:=e) in Hcontexting; auto.\n          apply subst_te_expr; auto.\n\n    assert (value (apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (exp_tabs K (plug (close_tc C1 Y)  (close_te (shift_te e') Y))))))) as Value'.\n      clear Disj00 Disj01.\n      apply delta_gamma_lgamma_osubst_value with (E:=E1'++E2') (D:=D')(Env:=Env)(lEnv:=lEnv); auto.\n        apply value_tabs.\n        apply expr_tabs with (L:=dom (E1'++E2') `union` dom D' `union` cv_ec (close_tc C1 Y) `union` cv_ec C1); auto.\n          intros X XnFv.\n          rewrite <- shift_te_expr with (e:=e'); auto.\n          assert (disjdom (fv_tt X) (cv_ec (close_tc C1 Y))) as Disj.\n            apply disjdom_one_2; auto.\n          rewrite open_te_plug; auto. \n          rewrite close_open_te__subst_te; auto.\n          assert (context C1) as Ctx1.\n            apply contexting__context in Hcontexting; auto.\n          rewrite close_open_tc__subst_tc; auto.\n          assert (disjdom (union {{Y}} (fv_tt X)) (cv_ec C1)) as Disj'.\n            eapply disjdom_app_l.\n            split.\n              clear - H0.\n              apply disjdom_one_2; auto.\n              clear - XnFv.\n              apply disjdom_one_2; auto.\n          rewrite <- subst_te_plug; auto. \n          assert (typing (E1'++[(Y, bind_kn K)]++E2') D' (plug C1 e') T1') as Htyp2'.\n            apply contexting_plug_typing with (e:=e') in Hcontexting; auto.\n          apply subst_te_expr; auto.\n\n    exists (apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (exp_tabs K (plug (close_tc C1 Y) (close_te (shift_te e) Y)))))).\n    exists (apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (exp_tabs K (plug (close_tc C1 Y) (close_te (shift_te e') Y)))))).\n    split.\n      assert (typing (E1'++E2') D' (plug (ctx_tabs_capture Y K (close_tc C1 Y)) e) (typ_all K (close_tt T1' Y))) as Hptyp.\n        clear Disj00 Disj01.\n        destruct (in_dec Y (fv_te e)) as [yine | ynine].\n          simpl.\n          apply typing_tabs with (L:=dom (E1'++E2') `union` dom D' `union` dom E `union` dom D `union` {{Y}} `union` cv_ec C1 `union` cv_ec (close_tc C1 Y)); auto.\n            intros X Xn.\n            rewrite <- shift_te_expr; auto.\n            rewrite open_te_plug; auto.\n              rewrite close_open_te__subst_te; auto.\n              rewrite close_open_tc__subst_tc; auto.\n                apply plug_vcontext__value.\n                  apply vcontext_through_subst_tc; auto.\n                  apply plug_context__expr.\n                    apply context_through_subst_tc; auto.\n                      apply vcontext__context in H1; auto.\n                    apply subst_te_expr; auto.             \n                apply vcontext__context in H1; auto.\n              clear - Xn.\n              apply disjdom_one_2; auto.        \n\n            intros X Xn.\n            rewrite <- shift_te_expr; auto.\n            assert (disjdom (fv_tt X) (cv_ec (close_tc C1 Y))) as Disj.\n              apply disjdom_one_2; auto.\n            rewrite open_te_plug; auto.\n            assert (Y `in` ddom_env E) as J.\n              apply in_fv_te_typing' with (X:=Y) in Htyp; auto.\n            rewrite close_open_te__subst_te; auto.\n            assert (context C1) as Ctx1.\n              apply contexting__context in Hcontexting; auto.\n            rewrite close_open_tc__subst_tc; auto.\n            apply dbinds_In_inv in J.\n            destruct J as [k Binds].\n            assert (wf_env E) as Wfe. auto.\n            assert (J:=@env_remove2_inv E Y (bind_kn k) Wfe Binds).\n            destruct J as [E1 [E2 [EQ1 EQ2]]]; subst.\n\n            apply typing_typ_permute; auto. \n            assert (J:=Hcontexting).\n            apply contexting_typ_renaming_one with (Y:=X) in Hcontexting; auto.\n            assert (Y `notin` fv_env E1' `union` fv_env E2' `union` fv_lenv D') as YnE1'E2'D'.\n              apply wf_lenv_notin_fv_env with (K:=K); auto.          \n                 apply contexting_regular in J.\n                 decompose [and] J; auto.\n            assert (Y `notin` dom (E1' ++ E2')) as YndE1'E2'D'.\n              clear Xn.\n              destruct_notin.\n              apply free_env__free_dom in YnE1'E2'D'.\n              apply free_env__free_dom in NotInTac.\n              auto.\n            rewrite <- map_subst_tlb_id with (G:=E1'++E2') (D:=D') in Hcontexting; try solve [assumption].\n            rewrite <- map_subst_tb_id' with (G:=E1') (G':=E2') in Hcontexting; try solve [assumption].\n            apply contexting_plug_typing with (E:=map (subst_tb Y X) E1++[(X, bind_kn k)]++E2) (D:=map (subst_tlb Y X) D) (T:=subst_tt Y X T); auto.\n              rewrite close_open_tt__subst_tt; auto.\n                apply contexting_regular in J.\n                decompose [and] J.\n                apply type_from_wf_typ in H9; auto.\n\n              simpl_env in Xn.\n              apply typing_typ_renaming_one with (Y:=X) in Htyp; auto.\n\n          rewrite <- EQ1'.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n            apply contexting_tabs_capture; auto.\n              rewrite EQ1'. auto.\n      apply typing_osubst with (dsubst:=dsubst1++dsubst2) (gsubst:=gsubst1++gsubst2) (lgsubst:=lgsubst)(Env:=Env)(lEnv:=lEnv) in Hptyp; auto.\n    split.\n      assert (typing (E1'++E2') D' (plug (ctx_tabs_capture Y K (close_tc C1 Y)) e') (typ_all K (close_tt T1' Y))) as Hptyp'.\n        clear Disj00 Disj01.\n        destruct (in_dec Y (fv_te e')) as [yine' | ynine'].\n          simpl.\n          apply typing_tabs with (L:=dom (E1'++E2') `union` dom D' `union` dom E `union` dom D `union` {{Y}} `union` cv_ec C1 `union` cv_ec (close_tc C1 Y)); auto.\n            intros X Xn.\n            rewrite <- shift_te_expr; auto.\n            rewrite open_te_plug; auto.\n              rewrite close_open_te__subst_te; auto.\n              rewrite close_open_tc__subst_tc; auto.\n                apply plug_vcontext__value.\n                  apply vcontext_through_subst_tc; auto.\n                  apply plug_context__expr.\n                    apply context_through_subst_tc; auto.\n                      apply vcontext__context in H1; auto.\n                    apply subst_te_expr; auto.             \n                apply vcontext__context in H1; auto.\n              apply disjdom_one_2; auto.        \n\n            intros X Xn.\n            rewrite <- shift_te_expr; auto.\n            assert (disjdom (fv_tt X) (cv_ec (close_tc C1 Y))) as Disj.\n              apply disjdom_one_2; auto.\n            rewrite open_te_plug; auto.\n            assert (Y `in` ddom_env E) as J.\n              apply in_fv_te_typing' with (X:=Y) in Htyp'; auto.\n            rewrite close_open_te__subst_te; auto.\n            assert (context C1) as Ctx1.\n              apply contexting__context in Hcontexting; auto.\n            rewrite close_open_tc__subst_tc; auto.\n            apply dbinds_In_inv in J.\n            destruct J as [k Binds].\n            assert (wf_env E) as Wfe. auto.\n            assert (J:=@env_remove2_inv E Y (bind_kn k) Wfe Binds).\n            destruct J as [E1 [E2 [EQ1 EQ2]]]; subst.\n\n            apply typing_typ_permute; auto. \n            assert (J:=Hcontexting).\n            apply contexting_typ_renaming_one with (Y:=X) in Hcontexting; auto.\n            assert (Y `notin` fv_env E1' `union` fv_env E2' `union` fv_lenv D') as YnE1'E2'D'.\n              apply wf_lenv_notin_fv_env with (K:=K); auto.          \n                 apply contexting_regular in J.\n                 decompose [and] J; auto.\n            assert (Y `notin` dom (E1' ++ E2')) as YndE1'E2'D'.\n              clear Xn.\n              destruct_notin.\n              apply free_env__free_dom in YnE1'E2'D'.\n              apply free_env__free_dom in NotInTac.\n              auto.\n            rewrite <- map_subst_tlb_id with (G:=E1'++E2') (D:=D') in Hcontexting; try solve [assumption].\n            rewrite <- map_subst_tb_id' with (G:=E1') (G':=E2') in Hcontexting; try solve [assumption].\n            apply contexting_plug_typing with (E:=map (subst_tb Y X) E1++[(X, bind_kn k)]++E2) (D:=map (subst_tlb Y X) D) (T:=subst_tt Y X T); auto.\n              rewrite close_open_tt__subst_tt; auto.\n                apply contexting_regular in J.\n                decompose [and] J.\n                apply type_from_wf_typ in H9; auto.\n\n              simpl_env in Xn.\n              apply typing_typ_renaming_one with (Y:=X) in Htyp'; auto.\n\n          rewrite <- EQ1'.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n            apply contexting_tabs_capture; auto.\n              rewrite EQ1'. auto.\n      apply typing_osubst with (dsubst:=dsubst1'++dsubst2') (gsubst:=gsubst1'++gsubst2') (lgsubst:=lgsubst')(Env:=Env)(lEnv:=lEnv) in Hptyp'; auto.\n    split. split; auto.\n    split. split; auto.\n      SCase \"Frel\".\n      apply F_Related_ovalues_all_req.\n      split; auto.\n      split; auto.\n\n        SSCase \"Frel\".\n        exists (fv_te e `union` dom E `union` fv_env E `union` fv_lenv D `union` {{Y}} `union` fv_env E1' `union` fv_lenv D' `union` cv_ec C1 `union` fv_te (plug C1 e) `union` fv_te (plug C1 e') `union` dom E1' `union` dom E2' `union` fv_tt T1' `union` fv_env Env `union` fv_lenv lEnv).\n        intros X t2 t2' R Fr HwfR Hfv.\n\n        assert (F_Related_osubst (E1'++[(Y, bind_kn K)]++E2') D' (gsubst1++gsubst2) (gsubst1'++gsubst2') lgsubst lgsubst' (rsubst1++[(Y,R)]++rsubst2) (dsubst1++[(Y,t2)]++dsubst2) (dsubst1'++[(Y,t2')]++dsubst2') Env lEnv) as Hrel_sub'.\n          assert (Y `notin` dom E1') as YnE1'.\n            apply fresh_mid_head with (E:=E2') (a:=bind_kn K); auto.\n          assert (Y `notin` dom E2') as YnE2'.\n             apply fresh_mid_tail with (F:=E1') (a:=bind_kn K); auto.\n          assert (Y `notin` dom D') as YnD'.\n            apply contexting_regular in Hcontexting.\n            decompose [and] Hcontexting.\n            clear - H7 Hwfe'.\n            apply wf_lenv_notin_fv_env with (E1:=E1') (E2:=E2') (X:=Y) (K:=K) in H7; auto.\n          assert (Y `notin` fv_env Env) as YnEnv.\n            clear - Disj00.\n            apply disjdom_app_2 in Disj00.\n            apply disjdom_app_1 in Disj00.\n            apply disjdom_app_1 in Disj00.\n            destruct Disj00 as [J1 J2].\n            apply J1; auto.\n          assert (Y `notin` fv_lenv lEnv) as YnlEnv.\n            clear - Disj01.\n            apply disjdom_app_2 in Disj01.\n            apply disjdom_app_1 in Disj01.\n            apply disjdom_app_1 in Disj01.\n            destruct Disj01 as [J1 J2].\n            apply J1; auto.\n          clear Disj00 Disj01.\n          apply F_Related_osubst_dweaken; auto.\n\n        assert (F_Rosubst (E1'++[(Y, bind_kn K)] ++E2') (rsubst1++[(Y, R)]++rsubst2) (dsubst1++[(Y, t2)] ++dsubst2) (dsubst1'++[(Y, t2')] ++dsubst2') Env) as HRsub'. \n          assert (Y `notin` dom E1') as ynE1'.\n             apply fresh_mid_head with (E:=E2') (a:=bind_kn K); auto.\n          assert (Y `notin` dom E2') as ynE2'.\n             apply fresh_mid_tail with (F:=E1') (a:=bind_kn K); auto.\n          assert (Y `notin` fv_env Env) as YnEnv.\n            clear - Disj00.\n            apply disjdom_app_2 in Disj00.\n            apply disjdom_app_1 in Disj00.\n            apply disjdom_app_1 in Disj00.\n            destruct Disj00 as [J1 J2].\n            apply J1; auto.\n          clear Disj00 Disj01.\n          apply F_Rosubst_dweaken; auto.       \n\n       assert (\n       disjdom\n         (union L0\n            (union (cv_ec C1)\n               (union (fv_ec C1)\n                  (union (dom E)\n                     (union (dom D)\n                        (union (fv_tt T)\n                           (union (fv_tt T1')\n                              (union (dom (E1' ++ [(Y, bind_kn K)] ++ E2')) (dom D')))))))))\n         (fv_env Env)) as Disj00'.\n\n           clear - Disj00.\n           assert (J:=@close_tc_fv_ec_eq C1 Y).\n           assert (J':=@close_tc_cv_ec_eq C1 Y).\n           assert (J'':=@close_tt_fv_tt_lower T1' Y).\n           apply disjdom_sym_1.\n           apply disjdom_sub with (D1:=L0 `union` ({{Y}} `union` (cv_ec (close_tc C1 Y))) `union` (fv_ec (close_tc C1 Y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt (close_tt T1' Y)) `union` (dom (E1'++E2')) `union` dom D').\n             apply disjdom_sym_1; auto.\n             simpl_env. rewrite <- J.  rewrite <- J'.  clear - J''. fsetdec.\n\n       assert (\n       disjdom\n         (union L0\n            (union (cv_ec C1)\n               (union (fv_ec C1)\n                  (union (dom E)\n                     (union (dom D)\n                        (union (fv_tt T)\n                           (union (fv_tt T1')\n                              (union (dom (E1' ++ [(Y, bind_kn K)] ++ E2')) (dom D')))))))))\n         (fv_lenv lEnv)) as Disj01'.\n           clear - Disj01.\n           assert (J:=@close_tc_fv_ec_eq C1 Y).\n           assert (J':=@close_tc_cv_ec_eq C1 Y).\n           assert (J'':=@close_tt_fv_tt_lower T1' Y).\n           apply disjdom_sym_1.\n           apply disjdom_sub with (D1:=L0 `union` ({{Y}} `union` (cv_ec (close_tc C1 Y))) `union` (fv_ec (close_tc C1 Y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt (close_tt T1' Y)) `union` (dom (E1'++E2')) `union` dom D').\n             apply disjdom_sym_1; auto.\n             simpl_env. rewrite <- J.  rewrite <- J'.  clear - J''. fsetdec.\n\n        assert (J:=@Fry (dsubst1++[(Y, t2)]++dsubst2) (dsubst1'++[(Y, t2')]++dsubst2') (gsubst1++gsubst2) (gsubst1'++gsubst2') lgsubst lgsubst' (rsubst1++[(Y, R)]++rsubst2) Env lEnv Disj00' Disj01' Hrel_sub' HRsub').\n\n        assert (\n            apply_delta_subst (dsubst1++[(Y, t2)]++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (plug C1 e))) =\n            apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (subst_te Y t2 (plug C1 e))))\n                  ) as Heq1. simpl.\n           simpl_env.\n           assert (wf_typ Env t2 K) as Wft2. apply wfor_left_inv in HwfR; auto.\n           apply F_Related_osubst__inversion in Hrel_sub'.\n           decompose [prod] Hrel_sub'; auto.\n           apply F_Related_osubst__inversion in Hrel_sub.\n           decompose [prod] Hrel_sub; auto.\n           rewrite delta_osubst_opt' with (Env:=Env) (E':=E1') (E:=E2') (k:=K); auto.\n           assert (Y `notin` dom Env) as YnE. \n             clear - Disj00.\n             apply disjdom_app_2 in Disj00.\n             apply disjdom_app_1 in Disj00.\n             apply disjdom_app_1 in Disj00.\n             destruct Disj00 as [J1 J2].\n             apply free_env__free_dom.\n             apply J1; auto.\n           rewrite swap_subst_te_ogsubst with (Env:=Env) (lEnv:=lEnv) (D:=D') (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (K:=K) (lgsubst:=lgsubst); auto.\n           rewrite swap_subst_te_olgsubst with (Env:=Env) (lEnv:=lEnv) (D:=D') (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (K:=K) (gsubst:=gsubst1++gsubst2); auto.\n\n         assert (\n            apply_delta_subst (dsubst1'++[(Y,t2')]++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (plug C1 e'))) =\n            apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (subst_te Y t2' (plug C1 e'))))\n                  ) as Heq2.  simpl.\n           simpl_env.\n           assert (wf_typ Env t2' K) as Wft2. apply wfor_right_inv in HwfR; auto.\n           apply F_Related_osubst__inversion in Hrel_sub'.\n           decompose [prod] Hrel_sub'; auto.\n           apply F_Related_osubst__inversion in Hrel_sub.\n           decompose [prod] Hrel_sub; auto.\n           rewrite delta_osubst_opt' with (E':=E1') (E:=E2') (k:=K)  (Env:=Env); auto.\n           assert (Y `notin` dom Env) as YnE. \n             clear - Disj00.\n             apply disjdom_app_2 in Disj00.\n             apply disjdom_app_1 in Disj00.\n             apply disjdom_app_1 in Disj00.\n             destruct Disj00 as [J1 J2].\n             apply free_env__free_dom.\n             apply J1; auto.\n           rewrite swap_subst_te_ogsubst with  (Env:=Env) (lEnv:=lEnv)  (D:=D') (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (K:=K) (lgsubst:=lgsubst'); auto.\n           rewrite swap_subst_te_olgsubst with  (Env:=Env) (lEnv:=lEnv)  (D:=D') (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (K:=K) (gsubst:=gsubst1'++gsubst2'); auto.\n\n         rewrite Heq1 in J. rewrite Heq2 in J. clear Heq1 Heq2.\n         destruct J as [v [v' [Ht [Ht' [[Hbrc Hv] [[Hbrc' Hv'] Hrel]]]]]].\n         exists (v). exists (v').\n         split.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2)  (apply_gamma_subst lgsubst (subst_te Y t2 (plug C1 e)))))); auto.\n              assert (apply_delta_subst_typ (dsubst1++dsubst2) t2 = t2) as Heq1.\n                 rewrite delta_osubst_closed_typ; auto.\n                   assert (disjdom (dom (E1'++E2')) (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom (E1'++E2')) in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     simpl_env. rewrite <- dEQ2. rewrite <- dEQ3.\n                     clear - HwfR x0notin Disj001.\n                     apply wfor_left_inv in HwfR.\n                     apply in_fv_wf with (X:=x0) in HwfR; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply free_dom__free_env in HwfR.\n                       apply J2 in HwfR; auto.\n\n                     simpl_env in x0notin. rewrite <- dEQ2 in x0notin. rewrite <- dEQ3 in x0notin.\n                     clear - HwfR x0notin Disj001.\n                     apply wfor_left_inv in HwfR.\n                     apply notin_fv_wf with (X:=x0) in HwfR; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply free_env__free_dom.\n                       apply J1.\n                       apply ddom__dom; simpl_env; auto.\n              rewrite <- Heq1.\n              rewrite commut_gamma_subst_tabs.\n              rewrite commut_gamma_subst_tabs.\n              assert (subst_te Y (apply_delta_subst_typ  (dsubst1++dsubst2) t2) (plug C1 e) = subst_te Y t2 (plug C1 e)) as Heq2. \n                 rewrite Heq1. auto. \n              rewrite Heq2.\n              assert (typing (E1'++[(Y, bind_kn K)]++E2') D' (plug C1 e) T1') as Typinge.\n                apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n             assert (disjdom (union {{Y}} (fv_tt t2)) (cv_ec C1)) as Disj0.\n               eapply disjdom_app_l.\n               split.\n                 clear - H0.\n                 apply disjdom_one_2; auto.\n\n                  clear - HwfR Disj00.\n                  apply wfor_left_inv in HwfR.\n                  apply wft_fv_tt_sub in HwfR.\n                  apply disjdom_sym_1.\n                  apply disjdom_sub with (D1:= dom Env); auto.\n                  apply disjdom_sub with (D1:= fv_env Env).\n                      clear - Disj00.\n                      assert (J:=@close_tc_cv_ec_eq C1 Y).\n                      apply disjdom_sym_1.\n                      apply disjdom_sub with (D1:=L0 `union` ({{Y}} `union` (cv_ec (close_tc C1 Y))) `union` (fv_ec (close_tc C1 Y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt (close_tt T1' Y)) `union` (dom (E1'++E2')) `union` dom D').\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite <- J. clear. fsetdec.                                       \n\n                    apply fv_env__includes__dom.\n\n             assert (type t2) as Type2.\n               apply wfor_left_inv in HwfR.\n               apply type_from_wf_typ in HwfR; auto. \n              rewrite subst_te_plug; auto.\n              rewrite <- close_open_te__subst_te; auto.\n              assert (context C1) as Context1.\n                apply contexting__context in Hcontexting; auto.    \n              rewrite <- close_open_tc__subst_tc; auto.\n              assert (disjdom (fv_tt t2) (cv_ec (close_tc C1 Y))) as Disj.\n                clear - Disj00 HwfR.\n                apply disjdom_sym_1 in Disj00.\n                apply disjdom_sub with (D2:=cv_ec (close_tc C1 Y)) in Disj00.\n                  apply disjdom_sym_1.\n                  apply disjdom_sub with (D1:=dom Env).\n                    apply disjdom_sub with (D1:=fv_env Env).\n                      apply disjdom_sym_1; auto.\n                        apply fv_env__includes__dom.\n                      apply wft_fv_tt_sub with (K:=K).\n                        apply wfor_left_inv in HwfR; auto.\n                    clear. fsetdec.\n              rewrite <- open_te_plug; auto.\n              rewrite commut_lgamma_osubst_open_te with (Env:=Env) (lEnv:=lEnv) (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(gsubst:=gsubst1++gsubst2); auto.\n              rewrite commut_gamma_osubst_open_te with (Env:=Env) (lEnv:=lEnv) (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(lgsubst:=lgsubst); auto.\n              rewrite <- shift_te_expr; auto.\n              apply red_tabs_preserved_under_delta_osubst with (Env:=Env) (dE:=E1'++E2'); auto.\n\n              rewrite <- commut_gamma_subst_tabs; auto.\n              rewrite <- commut_gamma_osubst_open_te with (Env:=Env) (lEnv:=lEnv) (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (D:=D') (lgsubst:=lgsubst); auto.\n              apply red_tabs_preserved_under_gamma_osubst with(Env:=Env) (lEnv:=lEnv)  (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (D:=D') (lgsubst:=lgsubst); auto. \n\n              rewrite <- commut_gamma_subst_tabs; auto.\n              rewrite <- commut_lgamma_osubst_open_te with (Env:=Env) (lEnv:=lEnv) (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(gsubst:=gsubst1++gsubst2); auto.\n              apply red_tabs_preserved_under_lgamma_osubst with (Env:=Env) (lEnv:=lEnv) (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(gsubst:=gsubst1++gsubst2); auto. \n\n              apply red_tabs; auto.\n                apply expr_tabs with (L:=(cv_ec (close_tc C1 Y)) `union` cv_ec C1).\n                   intros.\n                   assert (disjdom (fv_tt X0) (cv_ec (close_tc C1 Y))) as Disj'.\n                     simpl. clear - H3.\n                     apply disjdom_one_2; auto.\n                   rewrite open_te_plug; auto.\n                   rewrite close_open_tc__subst_tc; auto.\n                   rewrite close_open_te__subst_te; auto.\n                  assert (disjdom (union {{Y}} (fv_tt X0)) (cv_ec C1)) as Disj0'.\n                     eapply disjdom_app_l.\n                     split.\n                       clear - H0.\n                       apply disjdom_one_2; auto.\n\n                       clear - H3.\n                       apply disjdom_one_2; auto.\n                   rewrite <- subst_te_plug; auto.\n\n         split; auto.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2')  (apply_gamma_subst lgsubst' (subst_te Y t2' (plug C1 e')))))); auto.\n              assert (apply_delta_subst_typ (dsubst1'++dsubst2') t2' = t2') as Heq1.\n                 rewrite delta_osubst_closed_typ; auto.\n                   assert (disjdom (dom (E1'++E2')) (fv_env Env)) as Disj001.\n                     apply disjdom_sym_1 in Disj00.\n                     apply disjdom_sub with (D2:=dom (E1'++E2')) in Disj00.\n                       apply disjdom_sym_1 in Disj00; auto.\n                       clear. simpl_env. fsetdec.\n                   clear Disj00 Disj01.\n                   split; intros x0 x0notin.\n                     simpl_env. rewrite <- dEQ2'. rewrite <- dEQ3'.\n                     clear - HwfR x0notin Disj001.\n                     apply wfor_right_inv in HwfR.\n                     apply in_fv_wf with (X:=x0) in HwfR; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply free_dom__free_env in HwfR.\n                       apply J2 in HwfR; auto.\n\n                     simpl_env in x0notin. rewrite <- dEQ2' in x0notin. rewrite <- dEQ3' in x0notin.\n                     clear - HwfR x0notin Disj001.\n                     apply wfor_right_inv in HwfR.\n                     apply notin_fv_wf with (X:=x0) in HwfR; auto.\n                       destruct Disj001 as [J1 J2].\n                       apply free_env__free_dom.\n                       apply J1.\n                       apply ddom__dom; simpl_env; auto.\n              rewrite <- Heq1.\n              rewrite commut_gamma_subst_tabs.\n              rewrite commut_gamma_subst_tabs.\n              assert (subst_te Y (apply_delta_subst_typ  (dsubst1'++dsubst2') t2') (plug C1 e') = subst_te Y t2' (plug C1 e')) as Heq2. \n                 rewrite Heq1. auto. \n              rewrite Heq2.\n              assert (typing (E1'++[(Y, bind_kn K)]++E2') D' (plug C1 e') T1') as Typinge'.\n                apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n             assert (disjdom (union {{Y}} (fv_tt t2')) (cv_ec C1)) as Disj0.\n               eapply disjdom_app_l.\n               split.\n                 clear - H0.\n                 apply disjdom_one_2; auto.\n\n                  clear - HwfR Disj00.\n                  apply wfor_right_inv in HwfR.\n                  apply wft_fv_tt_sub in HwfR.\n                  apply disjdom_sym_1.\n                  apply disjdom_sub with (D1:= dom Env); auto.\n                  apply disjdom_sub with (D1:= fv_env Env).\n                      clear - Disj00.\n                      assert (J:=@close_tc_cv_ec_eq C1 Y).\n                      apply disjdom_sym_1.\n                      apply disjdom_sub with (D1:=L0 `union` ({{Y}} `union` (cv_ec (close_tc C1 Y))) `union` (fv_ec (close_tc C1 Y)) `union` dom E `union` dom D `union` fv_tt T `union` (fv_tt (close_tt T1' Y)) `union` (dom (E1'++E2')) `union` dom D').\n                        apply disjdom_sym_1; auto.\n                        simpl_env. rewrite <- J. clear. fsetdec.                                       \n\n                    apply fv_env__includes__dom.\n             assert (type t2') as Type2'.\n               apply wfor_right_inv in HwfR.\n               apply type_from_wf_typ in HwfR; auto. \n              rewrite subst_te_plug; auto.\n              rewrite <- close_open_te__subst_te; auto.\n              assert (context C1) as Context1.\n                apply contexting__context in Hcontexting; auto.    \n              rewrite <- close_open_tc__subst_tc; auto.\n              assert (disjdom (fv_tt t2') (cv_ec (close_tc C1 Y))) as Disj.\n                clear - Disj00 HwfR.\n                apply disjdom_sym_1 in Disj00.\n                apply disjdom_sub with (D2:=cv_ec (close_tc C1 Y)) in Disj00.\n                  apply disjdom_sym_1.\n                  apply disjdom_sub with (D1:=dom Env).\n                    apply disjdom_sub with (D1:=fv_env Env).\n                      apply disjdom_sym_1; auto.\n                        apply fv_env__includes__dom.\n                      apply wft_fv_tt_sub with (K:=K).\n                        apply wfor_right_inv in HwfR; auto.\n                    clear. fsetdec.\n              rewrite <- open_te_plug; auto.\n              rewrite commut_lgamma_osubst_open_te with (Env:=Env) (lEnv:=lEnv) (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(gsubst:=gsubst1'++gsubst2'); auto.\n              rewrite commut_gamma_osubst_open_te with (Env:=Env) (lEnv:=lEnv) (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(lgsubst:=lgsubst'); auto.\n              rewrite <- shift_te_expr; auto.\n              apply red_tabs_preserved_under_delta_osubst with(Env:=Env) (dE:=E1'++E2'); auto.\n\n              rewrite <- commut_gamma_subst_tabs; auto.\n              rewrite <- commut_gamma_osubst_open_te with(Env:=Env) (lEnv:=lEnv)  (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (D:=D') (lgsubst:=lgsubst'); auto.\n              apply red_tabs_preserved_under_gamma_osubst with (Env:=Env) (lEnv:=lEnv) (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (D:=D') (lgsubst:=lgsubst'); auto. \n\n              rewrite <- commut_gamma_subst_tabs; auto.\n              rewrite <- commut_lgamma_osubst_open_te with (Env:=Env) (lEnv:=lEnv) (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(gsubst:=gsubst1'++gsubst2'); auto.\n              apply red_tabs_preserved_under_lgamma_osubst with (Env:=Env) (lEnv:=lEnv) (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(gsubst:=gsubst1'++gsubst2'); auto. \n\n              apply red_tabs; auto.\n                apply expr_tabs with (L:=(cv_ec (close_tc C1 Y)) `union` cv_ec C1).\n                   intros.\n                   assert (disjdom (fv_tt X0) (cv_ec (close_tc C1 Y))) as Disj'.\n                     clear - H3.\n                     apply disjdom_one_2; auto.\n                   rewrite open_te_plug; auto.\n                   rewrite close_open_tc__subst_tc; auto.\n                   rewrite close_open_te__subst_te; auto.\n                  assert (disjdom (union {{Y}} (fv_tt X0)) (cv_ec C1)) as Disj0'.\n                     eapply disjdom_app_l.\n                     split.\n                       clear - H0.\n                       apply disjdom_one_2; auto.\n\n                       clear - H3.  \n                       apply disjdom_one_2; auto.\n                   rewrite <- subst_te_plug; auto.\n\n               simpl_env.\n               rewrite close_open_tt__subst_tt; auto.\n                 assert (wf_delta_osubst ([(X, bind_kn K)]++E1'++E2') ([(X, t2)]++dsubst1++dsubst2) Env) as Wfd.\n                   apply F_Rosubst__wf_osubst in HRsub.\n                   decompose [prod] HRsub.\n                   clear - a0 HwfR Fr dEQ2 dEQ3.\n                   eapply odsubst_weaken_head; simpl_env; eauto using wfor_left_inv.\n\n                 assert (wf_delta_osubst ([(X, bind_kn K)]++E1'++E2') ([(X, t2')]++dsubst1'++dsubst2') Env) as Wfd'.\n                   apply F_Rosubst__wf_osubst in HRsub.\n                   decompose [prod] HRsub.\n                   clear - b0 HwfR Fr dEQ2' dEQ3'.\n                   eapply odsubst_weaken_head; simpl_env; eauto using wfor_right_inv.\n\n                 apply F_Rosubst__wf_osubst in HRsub'.\n                 decompose [prod] HRsub'; auto.\n                 clear - Hrel Wfd Wfd' b a0 b0 Hwfd Hwfd' Fr rEQ2 rEQ3 dEQ2 dEQ3 dEQ2' dEQ3' HwfR.\n                 apply Forel_typ_permute_renaming_one with (E1:=E1')(E2:=E2')(K:=K) (X:=Y); auto.\n               \n                 apply contexting_regular in Hcontexting.\n                 decompose [and] Hcontexting.\n                 apply type_from_wf_typ in H9; auto.\nQed.\n\nLemma F_ological_related_congruence__tapp :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  forall L0,\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n   disjdom L0 (fv_env Env) ->\n   disjdom L0 (fv_lenv lEnv) ->\n   F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n   F_Rosubst E rsubst dsubst dsubst' Env ->\n   F_Related_oterms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n     Env lEnv\n  ) ->\n  forall K  C1 T' T2' E' D',\n  contexting E D T C1 E' D' (typ_all K T2') ->\n  wf_typ E' T' K ->\n  (typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom L0 (fv_env Env) ->\n     disjdom L0 (fv_lenv lEnv) ->\n     F_Related_osubst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E rsubst dsubst dsubst' Env ->\n     F_Related_oterms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n      Env lEnv\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n     disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2' `union` dom E' `union` dom D') (fv_env Env) ->\n     disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt T2'  `union` dom E' `union` dom D') (fv_lenv lEnv) ->\n     F_Related_osubst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n     F_Rosubst E' rsubst dsubst dsubst' Env ->\n     F_Related_oterms (typ_all K T2') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n      Env lEnv\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv,\n  disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt (open_tt T2' T') `union` dom E' `union` dom D') (fv_env Env) ->\n  disjdom (L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T `union` fv_tt (open_tt T2' T') `union` dom E' `union` dom D') (fv_lenv lEnv) ->\n  F_Related_osubst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' Env lEnv ->\n  F_Rosubst E' rsubst dsubst dsubst' Env  ->\n  F_Related_oterms (open_tt T2' T') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_tapp (plug C1 e) T'))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_tapp (plug C1 e') T'))))\n      Env lEnv.\nProof.\n   intros e e' E D T Htyp Htyp' L0 Hlr K C1 T' T2' E' D' Hcontexting H IHHcontexting dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv Disj00 Disj01 Hrel_sub HRsub.  \n   assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J. \n   destruct J as [[[[[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe] Hwfe'] HwfEnv] HwflEnv].\n   assert (\n      F_Related_oterms (typ_all K T2') rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n         Env lEnv\n     ) as FR_AllType.\n      apply IHHcontexting; auto.\n        clear - Disj00.\n        apply disjdom_sym_1.\n        apply disjdom_sub with (D1:=L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T  `union` fv_tt (open_tt T2' T') `union` dom E' `union` dom D').\n          apply disjdom_sym_1; auto.\n\n          assert (J:=@open_tt_fv_tt_lower T2' T').\n          clear Disj00.  fsetdec.        \n\n        clear - Disj01.\n        apply disjdom_sym_1.\n        apply disjdom_sub with (D1:=L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T  `union` fv_tt (open_tt T2' T') `union` dom E' `union` dom D').\n          apply disjdom_sym_1; auto.\n\n          assert (J:=@open_tt_fv_tt_lower T2' T').\n          clear Disj01.  fsetdec.        \n   destruct FR_AllType as [v [v' [Ht [Ht' [Hn [Hn' Hrel]]]]]].\n\n   clear Disj00 Disj01.\n\n   apply F_Related_ovalues_all_leq in Hrel.\n   destruct Hrel as [Hv [Hv' [L Hall]]]; subst.\n   unfold open_tt in Hall.\n\n   assert (forall X,\n     X `notin` dom (E') `union` fv_tt T2' ->\n     wf_typ ([(X, bind_kn K)]++E') (open_tt T2' X) kn_lin) as w.\n     apply contexting_regular in Hcontexting.\n     destruct Hcontexting as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n     eapply wft_all_inv; eauto.\n\n   pick fresh y.\n   assert (y `notin` L) as Fr'. auto.\n   destruct (@Hall y (apply_delta_subst_typ dsubst T') (apply_delta_subst_typ dsubst' T') \n                                (F_FORel T' (rho_nil++rsubst) (delta_nil++dsubst) (delta_nil++dsubst') Env)\n                                Fr'\n                   ) as [u [u' [Hn_vt2u [Hn_v't2'u' Hrel_wft]]]]; auto.\n          apply F_FORel__R__wfor with (E:=E') (rsubst:=rsubst); auto.\n             simpl_env. split; auto.  \n\n              assert (ddom_env E' [=] dom rsubst) as EQ.\n                apply dom_rho_subst; auto.\n              assert (y `notin` ddom_env E') as Fv.\n                 apply dom__ddom; auto.\n              rewrite EQ in Fv. auto.\n\n   exists(u). exists (u').\n       split. simpl_commut_subst in *; rewrite commut_delta_osubst_open_tt with (dE:=E') (Env:=Env); auto.\n                eapply typing_tapp; eauto using wft_osubst.\n       split. simpl_commut_subst in *; rewrite commut_delta_osubst_open_tt with (dE:=E') (Env:=Env); auto.\n                eapply typing_tapp; eauto using wft_osubst.\n       split.\n       SCase \"Norm\".\n       simpl_commut_subst.\n       eapply m_ocongr_tapp; eauto.\n\n      split.\n      SCase \"Norm\".\n      simpl_commut_subst.\n      eapply m_ocongr_tapp; eauto.\n\n      SCase \"Frel\".\n      unfold open_tt.\n      assert (F_Related_ovalues (open_tt_rec 0 T' T2') (rho_nil++rsubst) (delta_nil++dsubst) (delta_nil++dsubst') u u' Env lEnv =\n                  F_Related_ovalues (open_tt_rec 0 T' T2') rsubst dsubst dsubst' u u' Env lEnv).\n         simpl. reflexivity.\n      rewrite <- H0.\n      apply oparametricity_subst_value with\n                (E:=E') (E':=@nil (atom*binding))\n                (rsubst:=rsubst) (rsubst':=rho_nil)\n                (k:=0) (Env:=Env) (lEnv:=lEnv)\n                (t:=T2') (t2:=T') (K:=kn_lin) (Q:=K)\n                (X:=y) (R:=(F_FORel T' (rho_nil++rsubst) (delta_nil++dsubst) (delta_nil++dsubst') Env))\n                ; auto.\n        SSCase \"wft\".\n          simpl_env. unfold open_tt in w. apply w; auto.\n\n        SSCase \"wft\".\n          simpl_env. rewrite subst_tt_intro_rec with (X:=y); auto.\n          rewrite_env (map (subst_tb y T') nil ++ E').\n          eapply wf_typ_subst_tb with (Q:=K); auto.\n          apply w; auto.\n\n        SSCase \"Rel__R\".\n        unfold F_FORel__R. split; auto.\n\n        SSCase \"fv\".\n        eapply m_tapp_ofv with (dsubst:=dsubst) (dsubst':=dsubst') (v:=v) (v':=v'); \n           eauto using notin_fv_te_typing.\n\n        SSCase \"eq\".\n        apply dom_delta_osubst with (Env:=Env); auto.\n        apply dom_delta_osubst with (Env:=Env); auto.\n        apply dom_rho_subst; auto.\n\n        SSCase \"typing\".\n        simpl_env. simpl.\n        apply preservation_normalization with (e:=(exp_tapp (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n                                                            (apply_delta_subst_typ dsubst (apply_gamma_subst_typ gsubst (apply_gamma_subst_typ lgsubst T'))))); auto.\n          rewrite swap_subst_tt_odsubst with (E:=E')(Env:=Env)(K:=K); auto.\n          rewrite subst_tt_open_tt_rec; eauto using type_from_wf_typ.\n            rewrite <- subst_tt_fresh with (T:=T2'); auto.\n            simpl. destruct (y == y); subst; try solve [contradict n; auto].\n              rewrite commut_delta_osubst_open_tt_rec with (dE:=E')(Env:=Env); auto.\n              apply typing_tapp with (K:=K); eauto using wft_osubst.\n                simpl_commut_subst in Ht. auto.\n\n          apply m_ocongr_tapp with(E:=E')(lE:=D')(Env:=Env)(lEnv:=lEnv)(v:=v)(K:=K); auto.\n\n        SSCase \"typing\".\n        simpl_env. simpl.\n        apply preservation_normalization with (e:=(exp_tapp (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n                                                            (apply_delta_subst_typ dsubst' (apply_gamma_subst_typ gsubst' (apply_gamma_subst_typ lgsubst' T'))))); auto.\n          rewrite swap_subst_tt_odsubst with (E:=E')(Env:=Env)(K:=K); auto.\n          rewrite subst_tt_open_tt_rec; eauto using type_from_wf_typ.\n            rewrite <- subst_tt_fresh with (T:=T2'); auto.\n            simpl. destruct (y == y); subst; try solve [contradict n; auto].\n              rewrite commut_delta_osubst_open_tt_rec with (dE:=E')(Env:=Env); auto.\n              apply typing_tapp with (K:=K); eauto using wft_osubst.\n                simpl_commut_subst in Ht'. auto.\n\n          apply m_ocongr_tapp with(E:=E')(lE:=D')(Env:=Env)(lEnv:=lEnv)(v:=v')(K:=K); auto.\n\n        SSCase \"rsubst\".\n        eapply rsubst_weaken with (X:=y) (rsubst:=rsubst) (rsubst':=rho_nil); eauto.\n          apply dom_rho_subst; auto.\n        SSCase \"dsubst\".   \n        apply odsubst_weaken with (X:=y) (K:=K) (dsubst:=dsubst) (dsubst':=delta_nil) (t:=(apply_delta_subst_typ dsubst T')); auto.\n          apply wft_osubst_closed with (E:=E') (E':=@nil (atom*binding)) (dsubst:=dsubst) (Env:=Env) ; auto.\n          apply dom_delta_osubst in Hwfd; auto.\n        SSCase \"dsubst'\".\n        apply odsubst_weaken with (X:=y) (K:=K) (dsubst:=dsubst') (dsubst':=delta_nil) (t:=(apply_delta_subst_typ dsubst' T')); auto.\n          apply wft_osubst_closed with (E:=E') (E':=@nil (atom*binding)) (dsubst:=dsubst') (Env:=Env); auto.\n          apply dom_delta_osubst in Hwfd'; auto.\nQed.\n\nLemma F_ological_related_congruence : forall E lE e e' t C E' lE' t',\n  F_ological_related E lE e e' t ->\n  contexting E lE t C E' lE' t' ->\n  F_ological_related E' lE' (plug C e) (plug C e') t'.\nProof.\n  intros E lE e e' t C E' lE' t' Hlr Hcontexting.\n  destruct Hlr as [Htyp [Htyp' [L0 Hlr]]]. \n  split. apply contexting_plug_typing with (e:=e) in Hcontexting; auto.\n  split. apply contexting_plug_typing with (e:=e') in Hcontexting; auto.\n  exists (L0 `union` \n                 cv_ec C `union` fv_ec C `union` \n                 dom E `union` dom lE `union` \n                 fv_tt t `union`  fv_tt t' `union` \n                dom E' `union` dom lE').\n  (contexting_cases (induction Hcontexting) Case); \n    intros dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Env lEnv Disj00 Disj01 Hrel_sub HRsub; simpl in *; auto.\n  Case \"contexting_hole\".\n    remember (L0 `union` \n                 {} `union` {} `union` \n                 dom E `union` dom D `union` \n                 fv_tt T `union`  fv_tt T `union` \n                dom E `union` dom D) as L1.\n    apply Hlr; auto.\n      apply disjdom_sym_1.\n      apply disjdom_sub with (D1:=L1); subst.\n        apply disjdom_sym_1; auto.\n        clear. fsetdec.\n\n      apply disjdom_sym_1.\n      apply disjdom_sub with (D1:=L1); subst.\n        apply disjdom_sym_1; auto.\n        clear. fsetdec.\n\n  Case \"contexting_abs_free\".\n    apply F_ological_related_congruence__abs_free with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (L0:=L0) (L:=L) (K:=K) (T1':=T1') (C1:=C1) (T2':=T2') (E':=E') (D':=D') \n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst) (Env:=Env) (lEnv:=lEnv); assumption.\n\n  Case \"contexting_labs_free\". \n    apply F_ological_related_congruence__labs_free with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (L0:=L0) (L:=L) (K:=K) (T1':=T1') (C1:=C1) (T2':=T2') (E':=E') (D':=D') \n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst) (Env:=Env) (lEnv:=lEnv); assumption.\n\n  Case \"contexting_abs_capture\".\n    apply F_ological_related_congruence__abs_capture with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (L0:=L0) (K:=K) (y:=y) (T1':=T1') (C1:=C1) (T2':=T2') (E':=E') (D':=D') \n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst) (Env:=Env) (lEnv:=lEnv); assumption.\n\n  Case \"contexting_labs_capture\".\n    apply F_ological_related_congruence__labs_capture with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (L0:=L0) (K:=K) (y:=y) (T1':=T1') (C1:=C1) (T2':=T2') (E':=E') (D':=D') \n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst) (Env:=Env) (lEnv:=lEnv); assumption.\n\n  Case \"contexting_app1\". \n    apply F_ological_related_congruence__app1 with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (L0:=L0) (K:=K) (T1':=T1') (C1:=C1) (T2':=T2') (E':=E') (D1':=D1')  (D2':=D2')  (D3':=D3') \n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst) (Env:=Env) (lEnv:=lEnv); assumption.\n\n  Case \"contexting_app2\". \n    apply F_ological_related_congruence__app2 with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (L0:=L0) (K:=K) (T1':=T1') (C2:=C2) (T2':=T2') (E':=E') (D1':=D1')  (D2':=D2')  (D3':=D3') \n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst) (Env:=Env) (lEnv:=lEnv); assumption.\n\n   Case \"contexting_tabs_free\".\n    apply F_ological_related_congruence__tabs_free with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (L0:=L0) (K:=K) (L:=L) (T1':=T1') (C1:=C1) (E':=E') (D':=D')\n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst) (Env:=Env) (lEnv:=lEnv); assumption.\n\n   Case \"contexting_tabs_capture\".\n    apply F_ological_related_congruence__tabs_capture with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (L0:=L0) (K:=K) (T1':=T1') (C1:=C1) (E':=E') (D':=D')\n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst) (Env:=Env) (lEnv:=lEnv); assumption.\n\n   Case \"contexting_tapp\".\n    apply F_ological_related_congruence__tapp with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (L0:=L0) (K:=K) (T':=T') (C1:=C1) (E':=E') (D':=D')\n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst) (Env:=Env) (lEnv:=lEnv); assumption.\n\n    Case \"contexting_apair1\".\n    assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J. decompose [prod] J. clear J.\n\n    assert (\n      F_Related_oterms T1' rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n         Env lEnv\n     ) as FR_T1.\n     apply IHHcontexting; auto.\n      clear - Disj00.\n      apply disjdom_sym_1.\n      apply disjdom_sub with (D1:=L0 `union` cv_ec C1 `union` (fv_ec C1 `union` fv_ee e2) `union` dom E `union` dom D `union` fv_tt T  `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D').\n        apply disjdom_sym_1; auto.\n        clear Disj00. fsetdec.        \n\n      clear - Disj01.\n      apply disjdom_sym_1.\n      apply disjdom_sub with (D1:=L0 `union` cv_ec C1 `union` (fv_ec C1 `union` fv_ee e2) `union` dom E `union` dom D `union` fv_tt T  `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D').\n        apply disjdom_sym_1; auto.\n        clear Disj01. fsetdec.        \n    destruct FR_T1 as [v [v' [Ht1 [Ht1' [Hn1 [Hn1' Hrel1]]]]]].\n\n    clear Disj00 Disj01.\n\n    assert (\n      F_Related_oterms T2' rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e2)))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e2)))\n         Env lEnv\n     ) as FR_T2.\n       apply oparametricity with (E:=E') (lE:=D'); auto.\n    destruct FR_T2 as [v0 [v'0 [Ht2 [Ht2' [Hn2 [Hn2' Hrel2]]]]]].\n\n    exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_apair (plug C1 e)  e2)))).\n    exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_apair (plug C1 e') e2)))).\n    split; simpl_commut_subst; auto.\n    split; simpl_commut_subst; auto.\n    split. split; simpl_commut_subst; auto.\n    split. split; simpl_commut_subst; auto.\n      SCase \"Frel\".\n        SSCase \"Frel\".\n        apply F_Related_ovalues_with_req.\n        repeat (split; simpl_commut_subst; auto).\n        exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e)))).\n        exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e2))).\n        exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e')))).\n        exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e2))).\n        repeat(split; auto).\n          exists (v). exists (v'). split; auto.\n          exists (v0). exists (v'0). split; auto.\n\n    Case \"contexting_apair2\".\n    assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J. decompose [prod] J. clear J.\n\n    assert (\n      F_Related_oterms T1' rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e1)))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e1)))\n         Env lEnv\n     ) as FR_T1.\n       apply oparametricity with (E:=E') (lE:=D'); auto.\n    destruct FR_T1 as [v [v' [Ht1 [Ht1' [Hn1 [Hn1' Hrel1]]]]]].\n\n    assert (\n      F_Related_oterms T2' rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C2 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C2 e'))))\n         Env lEnv\n     ) as FR_T2.\n     apply IHHcontexting; auto.\n      clear - Disj00.\n      apply disjdom_sym_1.\n      apply disjdom_sub with (D1:=L0 `union` cv_ec C2 `union` (fv_ee e1 `union` fv_ec C2) `union` dom E `union` dom D `union` fv_tt T  `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D').\n        apply disjdom_sym_1; auto.\n        clear Disj00. fsetdec.        \n\n      clear - Disj01.\n      apply disjdom_sym_1.\n      apply disjdom_sub with (D1:=L0 `union` cv_ec C2 `union` (fv_ee e1 `union` fv_ec C2) `union` dom E `union` dom D `union` fv_tt T  `union` (fv_tt T1' `union` fv_tt T2') `union` dom E' `union` dom D').\n        apply disjdom_sym_1; auto.\n        clear Disj01. fsetdec.        \n    destruct FR_T2 as [v0 [v'0 [Ht2 [Ht2' [Hn2 [Hn2' Hrel2]]]]]].\n\n    clear Disj00 Disj01.\n\n    exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_apair e1 (plug C2 e))))).\n    exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_apair e1 (plug C2 e'))))).\n    split; simpl_commut_subst; auto.\n    split; simpl_commut_subst; auto.\n    split. split; simpl_commut_subst; auto.\n    split. split; simpl_commut_subst; auto.\n      SCase \"Frel\".\n        SSCase \"Frel\".\n        apply F_Related_ovalues_with_req.\n        repeat (split; simpl_commut_subst; auto).\n        exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e1))).\n        exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C2 e)))).\n        exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e1))).\n        exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C2 e')))).\n        repeat(split; auto).\n          exists (v). exists (v'). split; auto.\n          exists (v0). exists (v'0). split; auto.\n\n    Case \"contexting_fst\".\n    assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J.\n    destruct J as [[[[[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe] Hwfe'] HwfEnv] HwflEnv].\n    assert (wf_typ E' (typ_with T1' T2') kn_lin) as WFTwith.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (\n      F_Related_oterms (typ_with T1' T2') rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n         Env lEnv\n     ) as FR_With.\n      apply IHHcontexting; auto.\n       clear - Disj00 WFTwith.\n       apply disjdom_sym_1.\n       apply disjdom_sub with (D1:=L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T  `union` fv_tt T1' `union` dom E' `union` dom D').\n         apply disjdom_sym_1; auto.\n\n         apply wft_fv_tt_sub in WFTwith.\n         clear Disj00. simpl in WFTwith. fsetdec.        \n\n       clear - Disj01 WFTwith.\n       apply disjdom_sym_1.\n       apply disjdom_sub with (D1:=L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T  `union` fv_tt T1' `union` dom E' `union` dom D').\n         apply disjdom_sym_1; auto.\n\n         apply wft_fv_tt_sub in WFTwith.\n         clear Disj01. simpl in WFTwith. fsetdec.        \n    destruct FR_With as [ee1 [ee1' [Ht [Ht' [Hn [Hn' FR_With]]]]]].\n\n    clear Disj00 Disj01.\n\n    simpl_commut_subst in Ht. simpl_commut_subst in Ht'. \n    apply congr_fst with (T1:=apply_delta_subst_typ dsubst T1') (T2:=apply_delta_subst_typ dsubst T2') (Env:=Env) (lEnv:=lEnv) in Hn; auto.\n    apply congr_fst with (T1:=apply_delta_subst_typ dsubst' T1') (T2:=apply_delta_subst_typ dsubst' T2') (Env:=Env) (lEnv:=lEnv) in Hn'; auto.\n    destruct Hn as [e1 [e2 [Hbrc Heq]]].\n    destruct Hn' as [e1' [e2' [Hbrc' Heq']]].\n    apply F_Related_ovalues_with_leq in FR_With.\n    subst.\n    destruct FR_With as [Hv [Hv' [ee1 [ee2 [ee1' [ee2' [Heq [Heq' \n                                [[u1 [u1' [[Hbrc_e1u1 Hu1][[Hbrc_e1'u1' Hu1'] Hrel_wft1]]]] \n                                 [u2 [u2' [[Hbrc_e2u2 Hu2][[Hbrc_e2'u2' Hu2'] Hrel_wft2]]]]]\n                              ]]]]]]]]; subst.\n    inversion Heq. inversion Heq'. subst. clear Heq Heq'.\n    exists(u1). exists(u1').\n        repeat(split; simpl_commut_subst; auto; try solve [\n          apply typing_fst with (T2:=apply_delta_subst_typ dsubst T2'); auto |\n          apply typing_fst with (T2:=apply_delta_subst_typ dsubst' T2');auto |\n          split; auto; apply bigstep_red__trans with (e':=ee1); auto |\n          split; auto; apply bigstep_red__trans with (e':=ee1'); auto]).\n\n    Case \"contexting_snd\".\n    assert (J:=Hrel_sub). apply F_Related_osubst__inversion in J.\n    destruct J as [[[[[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe] Hwfe'] HwfEnv] HwflEnv].\n    assert (wf_typ E' (typ_with T1' T2') kn_lin) as WFTwith.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (\n      F_Related_oterms (typ_with T1' T2') rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n         Env lEnv\n     ) as FR_With.\n      apply IHHcontexting; auto.\n       clear - Disj00 WFTwith.\n       apply disjdom_sym_1.\n       apply disjdom_sub with (D1:=L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T  `union` fv_tt T2' `union` dom E' `union` dom D').\n         apply disjdom_sym_1; auto.\n\n         apply wft_fv_tt_sub in WFTwith.\n         clear Disj00. simpl in WFTwith. fsetdec.        \n\n       clear - Disj01 WFTwith.\n       apply disjdom_sym_1.\n       apply disjdom_sub with (D1:=L0 `union` cv_ec C1 `union` fv_ec C1 `union` dom E `union` dom D `union` fv_tt T  `union` fv_tt T2' `union` dom E' `union` dom D').\n         apply disjdom_sym_1; auto.\n\n         apply wft_fv_tt_sub in WFTwith.\n         clear Disj01. simpl in WFTwith. fsetdec.        \n    destruct FR_With as [ee2 [ee2' [Ht [Ht' [Hn [Hn' FR_With]]]]]].\n\n    clear Disj00 Disj01.\n\n    simpl_commut_subst in Ht. simpl_commut_subst in Ht'. \n    apply congr_snd with (T1:=apply_delta_subst_typ dsubst T1') (T2:=apply_delta_subst_typ dsubst T2') (Env:=Env) (lEnv:=lEnv) in Hn; auto.\n    apply congr_snd with (T1:=apply_delta_subst_typ dsubst' T1') (T2:=apply_delta_subst_typ dsubst' T2') (Env:=Env) (lEnv:=lEnv) in Hn'; auto.\n    destruct Hn as [e1 [e2 [Hbrc Heq]]].\n    destruct Hn' as [e1' [e2' [Hbrc' Heq']]].\n    apply F_Related_ovalues_with_leq in FR_With.\n    subst.\n    destruct FR_With as [Hv [Hv' [ee1 [ee2 [ee1' [ee2' [Heq [Heq' \n                                [[u1 [u1' [[Hbrc_e1u1 Hu1][[Hbrc_e1'u1' Hu1'] Hrel_wft1]]]] \n                                 [u2 [u2' [[Hbrc_e2u2 Hu2][[Hbrc_e2'u2' Hu2'] Hrel_wft2]]]]]\n                              ]]]]]]]]; subst.\n    inversion Heq. inversion Heq'. subst. clear Heq Heq'.\n    exists (u2). exists (u2').\n        repeat(split; simpl_commut_subst; auto; try solve [\n          apply typing_snd with (T1:=apply_delta_subst_typ dsubst T1'); auto |\n          apply typing_snd with (T1:=apply_delta_subst_typ dsubst' T1'); auto |\n          split; auto; apply bigstep_red__trans with (e':=ee2); auto |\n          split; auto; apply bigstep_red__trans with (e':=ee2'); auto]).\nQed.\n\nAxiom F_Related_ovalues__consistent : forall v v',\n  F_Related_ovalues Two nil nil nil v v' nil nil->\n  ((v = tt /\\ v' =tt) \\/ (v = ff /\\ v' =ff)).\n\nLemma F_ological_related__sound : forall E lE e e' t,\n  F_ological_related E lE e e' t ->\n  F_observational_eq E lE e e' t.\nProof.\n  intros E lE e e' t Hlr.\n  assert (J:=Hlr).\n  destruct J as [Htyp [Htyp' [L J]]].\n  split; auto.\n  split; auto.\n    intros C Hcontext.\n    apply F_ological_related_congruence with (C:=C) (E':=nil) (lE':=nil) (t':=Two) in Hlr; auto.\n    split. eapply contexting_plug_typing; eauto.\n    split. eapply contexting_plug_typing; eauto.\n      assert (F_Rosubst nil nil nil nil nil) as J1. auto.\n      assert (F_Related_osubst nil nil nil nil nil nil nil nil nil nil nil) as J2. auto.\n      destruct Hlr as [Htyp1 [Htyp1' [L' Hlr]]].\n      assert (disjdom L' (dom (@nil (atom*binding)))) as Disj1.\n        simpl. apply disjdom_sym_1. apply disjdom_nil_1.\n      assert (disjdom L' (dom (@nil (atom*lbinding)))) as Disj2.\n        simpl. apply disjdom_sym_1. apply disjdom_nil_1.\n      assert (Hrel:=@Hlr nil nil nil nil nil nil nil nil nil Disj1 Disj2 J2 J1).\n      destruct Hrel as [v [v' [Htypv [Htypv' [Hn [Hn' Hrel]]]]]].\n      simpl in *.\n      assert (JJ:=@F_Related_ovalues__consistent v v' Hrel).\n      destruct JJ as [[EQ EQ'] | [EQ EQ']]; subst; auto.\nQed.\n", "meta": {"author": "Zdancewic", "repo": "linearity", "sha": "b2662939b2e8fb8fbe34f7ec0d3c69ef1bdff916", "save_path": "github-repos/coq/Zdancewic-linearity", "path": "github-repos/coq/Zdancewic-linearity/linearity-b2662939b2e8fb8fbe34f7ec0d3c69ef1bdff916/parametricity/LinF_OContextualEq_Sound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2475215050507193}}
{"text": "Require Import compcert.lib.Axioms.\nRequire Import compcert.lib.Maps.\n\nRequire Import VST.concurrency.sepcomp.\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\n\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import VST.concurrency.permissions.\nRequire Import compcert.common.Memory. (*for Mem.perm_order'' *)\nRequire Import VST.concurrency.bounded_maps.\nRequire Import VST.concurrency.permissions.\n\nRequire Import VST.sepcomp.semantics_lemmas.\nRequire Import Coqlib.\nRequire Import VST.veric.Clight_new.\nRequire Import VST.veric.Clightnew_coop.\n\nLemma CLight_Deterministic: forall ge c m c1 m1 c2 m2,\n    veric.Clight_new.cl_step ge c m c2 m2 ->\n    veric.Clight_new.cl_step ge c m c1 m1 ->\n    c1 = c2 /\\ m1 = m2.\nProof. intros.\n       specialize (cl_corestep_fun _ _ _ _ _ _ _ H H0); intros X; inversion X; subst. split; trivial.\nQed.\n\nDefinition bnd_from_init m := bounded_maps.bounded_map (snd (getMaxPerm m)) /\\ (Mem.mem_access m).1 = fun z k => None.\n\nLemma mem_storebytes_counded_init:\n  forall m m' b ofs bytes,\n    bnd_from_init m ->\n    Mem.storebytes m b ofs bytes = Some m' ->\n    bnd_from_init m'.\nProof.\n  intros ? ? ? ? ? H0 H.\n  destruct H0; split.\n  unfold getMaxPerm in *. erewrite Mem.storebytes_access; eauto.\n  erewrite Mem.storebytes_access; eauto.\nQed.\n\nLemma mem_alloc_bounded_init:\n  forall m lo hi m1 b,\n    bnd_from_init m ->\n    Mem.alloc m lo hi = (m1, b) ->\n    bnd_from_init m1.\nProof.\n  { intros ? ? ? ? ? H0 H.\n    Transparent Mem.alloc. unfold Mem.alloc in H. Opaque Mem.alloc.\n    inversion H; clear H; subst.\n    destruct H0; split; simpl in *; trivial.\n    red; intros. red in H.\n    rewrite (PTree.gmap1 (fun f : Z -> perm_kind -> option permission => f^~ Max)\n                         p (PTree.set (Mem.nextblock m)\n                                      (fun (ofs : Z) (_ : perm_kind) => if zle lo ofs && zlt ofs hi then Some Freeable else None)\n                                      (Mem.mem_access m).2)) in H1.\n    unfold option_map in H1.\n    rewrite PTree.gsspec in H1.\n    destruct (peq p (Mem.nextblock m)); subst.\n    { inversion H1; clear H1; subst. clear H0 H. red.\n      exists hi, lo; split; intros.\n      { destruct (zle lo p); destruct (zlt p hi); simpl; trivial; omega. }\n      { destruct (zle lo p); destruct (zlt p hi); simpl; trivial; omega. } }\n    { apply (H p); clear H0. rewrite PTree.gmap1. apply H1. } }\nQed.\n\n\nLemma mem_free_bounded_init:\n  forall m lo hi m' b,\n    bnd_from_init m ->\n    Mem.free m b lo hi = Some m' ->\n    bnd_from_init m'.\nProof.\n  intros ? ? ? ? ? H0 Heqq.\n  Transparent Mem.free. unfold Mem.free in Heqq. Opaque Mem.free.\n  destruct (Mem.range_perm_dec m b lo hi Cur Freeable); try discriminate.\n  inversion Heqq; clear Heqq; subst.\n  destruct H0 as [? INI]; split.\n  intros p f F.  simpl.\n  destruct (peq p b); subst.\n  { simpl in F. rewrite PTree.gmap1 in F. unfold option_map in F. rewrite PTree.gss in F. inversion F; clear F; subst.\n    specialize (H b).\n    remember (((getMaxPerm m).2) ! b) as g. destruct g; symmetry in Heqg.\n    { assert (Some o = Some o) by trivial. specialize (H _ H0); clear H0. rename o into g.\n      destruct H as [HI [LO [HHi HLo]]]. unfold getMaxPerm in Heqg. unfold PMap.get. simpl in *.\n      rewrite PTree.gmap1 in Heqg. unfold option_map in Heqg. rewrite INI.\n      destruct (((Mem.mem_access m).2) ! b); try discriminate. inversion Heqg; clear Heqg; subst.\n      exists  HI, LO; split; intros.\n      { destruct (zle lo p); destruct (zlt p hi); simpl; trivial; eauto. }\n      { destruct (zle lo p); destruct (zlt p hi); simpl; trivial; eauto. } }\n    { clear H. unfold getMaxPerm in Heqg.\n      destruct (zlt lo hi).\n      { assert (A: lo <= lo < hi) by omega. specialize (r _ A).\n        apply Mem.perm_max in r. unfold Mem.perm, PMap.get in r.\n        rewrite PTree.gmap1 in Heqg. unfold option_map in Heqg.\n        remember (((Mem.mem_access m).2) ! b) as q. destruct q; simpl in *. discriminate.\n        rewrite INI in r. inversion r. }\n      { simpl in Heqg. rewrite PTree.gmap1 in Heqg. unfold option_map in Heqg. unfold PMap.get.\n        remember (((Mem.mem_access m).2) ! b) as w. destruct w; try discriminate. clear Heqg.\n        rewrite INI.\n        exists lo, lo; split; intros.\n        { destruct (zle lo p); destruct (zlt p hi); simpl; trivial. }\n        { destruct (zle lo p); destruct (zlt p hi); simpl; trivial. } } } }\n  { apply (H p). unfold getMaxPerm in *; simpl in *.\n    rewrite PTree.gmap1 in F. rewrite PTree.gmap1. unfold option_map in *.\n    rewrite PTree.gso in F; trivial. }\n  simpl; trivial.\nQed.\n\nLemma mem_drop_perm_bounded_init:\n  forall m b lo hi P m',\n    bnd_from_init m ->\n    Mem.drop_perm m b lo hi P = Some m' ->\n    bnd_from_init m'.\nProof.\n  intros ? ? ? ? ? ? H0 Heqq.\n  Transparent Mem.drop_perm. unfold Mem.drop_perm in Heqq. Opaque Mem.drop_perm.\n  destruct (Mem.range_perm_dec m b lo hi Cur Freeable); try discriminate.\n  inversion Heqq; clear Heqq; subst.\n  destruct H0 as [? INI]; split.\n  - intros p f F.  simpl.\n    destruct (peq p b); subst.\n    { simpl in F.\n      rewrite PTree.gmap1 in F.\n      unfold option_map in F.\n      rewrite PTree.gss in F.\n      inversion F; clear F; subst.\n      specialize (H b).\n      remember (((getMaxPerm m).2) ! b) as g. destruct g; symmetry in Heqg.\n      { assert (Some o = Some o) by trivial. specialize (H _ H0); clear H0. rename o into g.\n      destruct H as [HI [LO [HHi HLo]]]. unfold getMaxPerm in Heqg. unfold PMap.get. simpl in *.\n      rewrite PTree.gmap1 in Heqg. unfold option_map in Heqg. rewrite INI.\n      destruct (((Mem.mem_access m).2) ! b); try discriminate. inversion Heqg; clear Heqg; subst.\n      exists  (Z.max HI hi), (Z.min LO lo); split; intros.\n      { destruct (zle lo p); destruct (zlt p hi); simpl; trivial; eauto.\n        - move : H=> /Z.gt_lt_iff /Z.max_lub_lt_iff [] ? ?.\n          xomega.\n        - move : H=> /Z.gt_lt_iff /Z.max_lub_lt_iff [] /Z.gt_lt_iff /HHi //.\n        - move : H=> /Z.gt_lt_iff /Z.max_lub_lt_iff [] /Z.gt_lt_iff /HHi //.\n        - move : H=> /Z.gt_lt_iff /Z.max_lub_lt_iff [] /Z.gt_lt_iff /HHi //.\n      }\n      { destruct (zle lo p); destruct (zlt p hi); simpl; trivial; eauto.\n        - move : H=> /Z.min_glb_lt_iff [] ? ?.\n          xomega.\n        - move : H=> /Z.min_glb_lt_iff [] ? ?.\n          omega.\n        - move : H=> /Z.min_glb_lt_iff [] /HLo //.\n        - move : H=> /Z.min_glb_lt_iff [] /HLo //.\n      } }\n    { clear H. unfold getMaxPerm in Heqg.\n      destruct (zlt lo hi).\n      { assert (A: lo <= lo < hi) by omega. specialize (r _ A).\n        apply Mem.perm_max in r. unfold Mem.perm, PMap.get in r.\n        rewrite PTree.gmap1 in Heqg. unfold option_map in Heqg.\n        remember (((Mem.mem_access m).2) ! b) as q. destruct q; simpl in *. discriminate.\n        rewrite INI in r. inversion r. }\n      { simpl in Heqg. rewrite PTree.gmap1 in Heqg. unfold option_map in Heqg. unfold PMap.get.\n        remember (((Mem.mem_access m).2) ! b) as w. destruct w; try discriminate. clear Heqg.\n        rewrite INI.\n        exists lo, lo; split; intros.\n        { destruct (zle lo p); destruct (zlt p hi); simpl; trivial. xomega. }\n        { destruct (zle lo p); destruct (zlt p hi); simpl; trivial. xomega.  } } } }\n  { apply (H p). unfold getMaxPerm in *; simpl in *.\n    rewrite PTree.gmap1 in F. rewrite PTree.gmap1. unfold option_map in *.\n    rewrite PTree.gso in F; trivial. }\n  simpl; trivial.\nQed.\n\nLemma mem_free_list_bounded_init:\n  forall m l m',\n    bnd_from_init m ->\n    Mem.free_list m l = Some m' ->\n    bnd_from_init m'.\nProof.\n  intros ? ? ? H0 H.\n  { generalize dependent m'. generalize dependent m. induction l; intros.\n    { inversion H; clear H; subst. trivial. }\n    { destruct a as [[b lo] hi]. simpl in H. remember (Mem.free m b lo hi) as q; symmetry in Heqq.\n      destruct q; try discriminate. apply (IHl m0); trivial. clear H IHl m'.\n      rename m0 into m'.\n      eapply mem_free_bounded_init; eauto.\n  } }\nQed.\n\nLemma preserve_bnd: memstep_preserve (fun m m' => bnd_from_init m -> bnd_from_init m').\nProof.\n  econstructor; intros; eauto.\n  induction H; intros.\n  - eapply mem_storebytes_counded_init; eauto.\n  - eapply mem_alloc_bounded_init; eauto.\n  - eapply mem_free_list_bounded_init; eauto.\n  - eauto.\nQed.\n\nLemma CLight_step_mem_bound' ge c m c' m':\n  veric.Clight_new.cl_step ge c m c' m' -> bnd_from_init m -> bnd_from_init m'.\nProof.\n  intros.\n  apply (memsem_preserves CLN_memsem _ preserve_bnd _ _ _ _ _ H H0).\nQed.\n\n(*This proof is already in juicy_machine.\n * move it to a more general position.*)\nLemma Mem_canonical_useful: forall m loc k,\n    fst (Mem.mem_access m) loc k = None.\nProof. intros. destruct m; simpl in *.\n       unfold PMap.get in nextblock_noaccess.\n       pose (b:= Pos.max (TreeMaxIndex (snd mem_access) + 1 )  nextblock).\n       assert (H1:  ~ Plt b nextblock).\n       { intros H. assert (HH:= Pos.le_max_r (TreeMaxIndex (snd mem_access) + 1) nextblock).\n         clear - H HH. unfold Pos.le in HH. unfold Plt in H.\n         apply HH. eapply Pos.compare_gt_iff.\n         auto. }\n       assert (H2 :( b > (TreeMaxIndex (snd mem_access)))%positive ).\n       { assert (HH:= Pos.le_max_l (TreeMaxIndex (snd mem_access) + 1) nextblock).\n         apply Pos.lt_gt. eapply Pos.lt_le_trans; eauto.\n         xomega. }\n       specialize (nextblock_noaccess b loc k H1).\n       apply max_works in H2. rewrite H2 in nextblock_noaccess.\n       assumption.\nQed.\n\nLemma mem_bound_init_mem_bound:\n  forall m,\n    bounded_maps.bounded_map (snd (getMaxPerm m)) <->\n    bnd_from_init m.\nProof.\n  repeat (split; intros) ; eauto.\n  - extensionality x;\n    extensionality y;\n    eapply Mem_canonical_useful.\n  - destruct H; auto.\nQed.\n\nLemma CLight_step_mem_bound ge c m c' m':\n  veric.Clight_new.cl_step ge c m c' m' ->\n  bounded_maps.bounded_map (snd (getMaxPerm m)) ->\n  bounded_maps.bounded_map (snd (getMaxPerm m')).\nProof.\n  intros.\n  eapply CLight_step_mem_bound' in H;\n  apply mem_bound_init_mem_bound; eauto.\nQed.\n\n\nDefinition bounded_mem (m: mem) := bounded_maps.bounded_map (snd (getMaxPerm m)) .\n\n\nLemma mem_alloc_bounded:\n  forall m lo hi m1 b,\n    bounded_mem m ->\n    Mem.alloc m lo hi = (m1, b) ->\n    bounded_mem m1.\nProof.\n  intros m lo hi m1 b H H0.\n  apply mem_bound_init_mem_bound; eauto.\n  eapply mem_alloc_bounded_init; eauto.\n  apply mem_bound_init_mem_bound; eauto.\nQed.\n\nLemma drop_perm_bounded:\n  forall m b lo hi P m',\n    bounded_mem m ->\n    Mem.drop_perm m b lo hi P = Some m' ->\n    bounded_mem m'.\nProof.\n  intros m b lo hi P m' H H0.\n  apply mem_bound_init_mem_bound; eauto.\n  eapply mem_drop_perm_bounded_init ; eauto.\n  apply mem_bound_init_mem_bound; eauto.\nQed.\n\nLemma store_bounded:\n  forall Mint32 m b ofs v m',\n    bounded_mem m ->\n    Mem.store Mint32 m b ofs v = Some m' ->\n    bounded_mem m'.\nProof.\n  intros Mint m b ofs v m' H H0.\n  eapply mem_bound_init_mem_bound; eauto.\n  eapply mem_storebytes_counded_init; eauto.\n  - eapply mem_bound_init_mem_bound; eauto.\n  - eapply Mem.store_storebytes; eauto.\nQed.\n\nLemma bounded_getMaxPerm:\n  forall m p Hlt,\n    @bounded_mem m ->\n    @bounded_mem (@restrPermMap p m Hlt).\nProof.\n  intros ? ? ? H b f.\n  rewrite /restrPermMap /= PTree.gmap1 PTree.gmap.\n  move: (H b f).\n  rewrite /getMaxPerm /= PTree.gmap1.\n  destruct (((Mem.mem_access m).2) ! b)=> //.\nQed.\n\nLemma store_init_data_bounded:\n  forall F V ge m b ofs data m',\n    bounded_mem m ->\n    @Globalenvs.Genv.store_init_data F V ge m b ofs data = Some m' ->\n    bounded_mem m'.\nProof.\n  intros.\n  move: H0.\n  destruct data; simpl;\n  try eapply store_bounded; eauto.\n  - intros HH; inversion HH.\n    subst; auto.\n  - destruct ( Globalenvs.Genv.find_symbol ge i);\n    try solve[intros HH; inversion HH];\n    eapply store_bounded; eauto.\nQed.\n\nLemma store_init_data_list_bounded:\n  forall F V ge m b ofs B m',\n    bounded_mem m ->\n    @Globalenvs.Genv.store_init_data_list F V ge m b ofs B = Some m' ->\n    bounded_mem m'.\nProof.\n  intros.\n  move: m' ofs b m H H0.\n  induction B.\n  - intros; inversion H0; subst; auto.\n  - intros; simpl in H0.\n    destruct (Globalenvs.Genv.store_init_data ge m b ofs a) eqn:STORE_INIT;\n      try solve[inversion H0].\n    eapply IHB; try apply H0.\n    eapply store_init_data_bounded; eauto.\nQed.\n\nLemma store_zeros_init_data_bounded:\n  forall m b ofs a m',\n    bounded_mem m ->\n    Globalenvs.store_zeros m b ofs a = Some m' ->\n    bounded_mem m'.\nProof.\n  intros.\n  destruct (zle a 0) eqn:AA.\n  - rewrite Globalenvs.store_zeros_equation in H0.\n    rewrite AA in H0; inversion H0; subst; auto.\n  - assert (exists n, Z.of_nat n = a).\n    { exists (nat_of_Z a).\n      apply nat_of_Z_eq. omega. }\n    destruct H1 as [n H1].\n    subst a.\n    clear g AA.\n    move: n m b ofs m' H H0.\n    induction n.\n    + intros.\n      rewrite Globalenvs.store_zeros_equation in H0.\n      rewrite Nat2Z.inj_0 in H0.\n      destruct (zle 0 0); try omega.\n      inversion H0; subst; assumption.\n    + intros.\n      rewrite Globalenvs.store_zeros_equation in H0.\n      destruct (zle (Z.of_nat n.+1) 0).\n      { rewrite Nat2Z.inj_succ in l.\n        assert (HH:=coqlib4.Z_of_nat_ge_O n).\n        clear - l HH.\n        xomega.\n      }\n      destruct ( Mem.store AST.Mint8unsigned m b ofs Values.Vzero) eqn:STORE';\n        try solve[inversion H0].\n      replace (Z.of_nat n.+1 - 1) with (Z.of_nat n) in H0 by xomega.\n      eapply IHn; try eapply H0.\n      eapply store_bounded; eauto.\nQed.\n\nLemma alloc_global_bounded:\n  forall F V ge m m' a,\n    @bounded_mem m ->\n    @Globalenvs.Genv.alloc_global F V ge m a = Some m' ->\n    @bounded_mem m'.\nProof.\n  move => ? ? ge m m' [] ? a BND.\n  rewrite /Globalenvs.Genv.alloc_global.\n  destruct a.\n  - destruct (Mem.alloc m 0 1) eqn:ALLOC; intros DROP;\n    try solve[inversion DROP].\n    eapply drop_perm_bounded; try eapply DROP.\n    eapply mem_alloc_bounded; eauto.\n  - remember (AST.init_data_list_size (AST.gvar_init v)) as  A; clear HeqA.\n    destruct (Mem.alloc m 0 A) eqn:ALLOC.\n    destruct (Globalenvs.store_zeros m0 b 0 ) eqn:STORE;\n      try solve[intros HH; inversion HH ].\n    remember ((AST.gvar_init v)) as  B; clear HeqB.\n    destruct (Globalenvs.Genv.store_init_data_list ge m1 b 0 B) eqn:STORE_INIT;\n      try solve[intros HH; inversion HH ].\n    intros DROP.\n    eapply drop_perm_bounded; try eapply DROP. clear DROP.\n    eapply store_init_data_list_bounded;\n      try eapply STORE_INIT.\n    eapply store_zeros_init_data_bounded; try eapply STORE.\n    eapply mem_alloc_bounded; eauto.\nQed.\n\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/concurrency/Clight_bounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.24747696480672415}}
{"text": "\nRequire Import member_t_insin_spec.\n\n\n\nDefinition type_LF_157 :=  nat ->  nat -> (Prop * (List.list term)).\n\nDefinition F_157 : type_LF_157:= (fun    u1 u2 => ((nat_eq u1 u2) = true -> (nat_eq u1 u2) = false -> False, (Term id_nat_eq ((model_nat u1):: (model_nat u2)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u2)::nil))::(Term id_false nil)::nil)).\nDefinition F_177 : type_LF_157:= (fun    u3 _ => (false = true -> (nat_eq 0 (S u3)) = false -> False, (Term id_false nil)::(Term id_true nil)::(Term id_nat_eq ((Term id_0 nil):: (Term id_S ((model_nat u3)::nil))::nil))::(Term id_false nil)::nil)).\nDefinition F_183 : type_LF_157:= (fun    u3 _ => (false = true -> (nat_eq (S u3) 0) = false -> False, (Term id_false nil)::(Term id_true nil)::(Term id_nat_eq ((Term id_S ((model_nat u3)::nil)):: (Term id_0 nil)::nil))::(Term id_false nil)::nil)).\nDefinition F_171 : type_LF_157:= (fun     _ _ => (true = true -> (nat_eq 0 0) = false -> False, (Term id_true nil)::(Term id_true nil)::(Term id_nat_eq ((Term id_0 nil):: (Term id_0 nil)::nil))::(Term id_false nil)::nil)).\nDefinition F_189 : type_LF_157:= (fun    u3 u4 => ((nat_eq u3 u4) = true -> (nat_eq (S u3) (S u4)) = false -> False, (Term id_nat_eq ((model_nat u3):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((Term id_S ((model_nat u3)::nil)):: (Term id_S ((model_nat u4)::nil))::nil))::(Term id_false nil)::nil)).\nDefinition F_190 : type_LF_157:= (fun     _ _ => ((nat_eq 0 0) = false -> False, (Term id_nat_eq ((Term id_0 nil):: (Term id_0 nil)::nil))::(Term id_false nil)::nil)).\nDefinition F_196 : type_LF_157:= (fun     _ _ => (true = false -> False, (Term id_true nil)::(Term id_false nil)::nil)).\n\nDefinition LF_157 := [F_157, F_177, F_183, F_171, F_189, F_190, F_196].\n\n\nFunction f_157 (u1: nat) (u2: nat) {struct u2} : bool :=\n match u1, u2 with\n| 0, 0 => true\n| 0, (S u3) => true\n| (S u3), 0 => true\n| (S u3), (S u4) => true\nend.\n\nLemma main_157 : forall F, In F LF_157 -> forall u1, forall u2, (forall F', In F' LF_157 -> forall e1, forall e2, less (snd (F' e1 e2)) (snd (F u1 u2)) -> fst (F' e1 e2)) -> fst (F u1 u2).\nProof.\nintros F HF u1 u2; case_In HF; intro Hind.\n\n\t(* GENERATE on [ 157 ] *)\n\nrename u1 into _u1. rename u2 into _u2. \nrename _u1 into u1. rename _u2 into u2. \n\nrevert Hind.\n\npattern u1, u2, (f_157 u1 u2). apply f_157_ind.\n\n(* case [ 171 ] *)\n\nintros _u1 _u2.  intro eq_1.  intro eq_2.  intro HFabs0.\nassert (Hind := HFabs0 F_171). clear HFabs0.\nassert (HFabs0 : fst (F_171 0 0)).\napply Hind. trivial_in 3. unfold snd. unfold F_171. unfold F_157. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_157. unfold F_171.\nauto.\n\n\n(* case [ 177 ] *)\n\nintros _u1 _u2.  intro eq_1. intro u3.  intro eq_2.  intro HFabs0.\nassert (Hind := HFabs0 F_177). clear HFabs0.\nassert (HFabs0 : fst (F_177 u3 0)).\napply Hind. trivial_in 1. unfold snd. unfold F_177. unfold F_157. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_157. unfold F_177.\nauto.\n\n\n(* case [ 183 ] *)\n\nintros _u1 _u2. intro u3.  intro eq_1.  intro eq_2.  intro HFabs0.\nassert (Hind := HFabs0 F_183). clear HFabs0.\nassert (HFabs0 : fst (F_183 u3 0)).\napply Hind. trivial_in 2. unfold snd. unfold F_183. unfold F_157. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_157. unfold F_183.\nauto.\n\n\n(* case [ 189 ] *)\n\nintros _u1 _u2. intro u3.  intro eq_1. intro u4.  intro eq_2.  intro HFabs0.\nassert (Hind := HFabs0 F_189). clear HFabs0.\nassert (HFabs0 : fst (F_189 u3 u4)).\napply Hind. trivial_in 4. unfold snd. unfold F_189. unfold F_157. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_157. unfold F_189.\nauto.\n\n\n\n\n\n\t(* NEGATIVE CLASH on [ 177 ] *)\n\nunfold fst. unfold F_177. intros. try discriminate.\n\n\n\n\t(* NEGATIVE CLASH on [ 183 ] *)\n\nunfold fst. unfold F_183. intros. try discriminate.\n\n\n\n\t(* NEGATIVE DECOMPOSITION on [ 171 ] *)\n\nrename u1 into d_u1. rename u2 into d_u2. \n\nassert (H := Hind F_190). \nassert (HFabs0 : fst (F_190 0 0)).\napply H. trivial_in 5. unfold snd. unfold F_190. unfold F_171. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_171. unfold F_190.\n\nunfold fst in HFabs0. unfold F_190 in HFabs0.\nauto.\n\n\n\n\t(* REWRITING on [ 189 ] *)\n\nrename u1 into _u3. rename u2 into _u4. \nrename _u3 into u3. rename _u4 into u4. \nassert (Res := Hind F_157). clear Hind.\nassert (HFabs1 : fst (F_157 u3 u4)).\napply Res. trivial_in 0. unfold snd. unfold F_157. unfold F_189. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_189. unfold fst in HFabs1. unfold F_157 in HFabs1.   \npattern u3, u4. simpl (nat_eq _ _). cbv beta.\n simpl. auto.\n\n\n\n\t(* REWRITING on [ 190 ] *)\n\nrename u1 into d_u1. rename u2 into d_u2. \n\nassert (Res := Hind F_196). clear Hind.\nassert (HFabs1 : fst (F_196 0 0)).\napply Res. trivial_in 6. unfold snd. unfold F_196. unfold F_190. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_190. unfold fst in HFabs1. unfold F_196 in HFabs1.    simpl. auto.\n\n\n\n\t(* NEGATIVE CLASH on [ 196 ] *)\n\nunfold fst. unfold F_196. intros. try discriminate.\n\n\n\nQed.\n\n\n\n(* the set of all formula instances from the proof *)\nDefinition S_157 := fun f => exists F, In F LF_157 /\\ exists e1, exists e2, f = F e1 e2.\n\nTheorem all_true_157: forall F, In F LF_157 -> forall u1: nat, forall u2: nat, fst (F u1  u2).\nProof.\nlet n := constr:(2) in\nlet p := constr:(S(S(n))) in\nintros;\nlet G := fresh \"G\" in\nlet x := fresh \"x\" in\napply wf_subset with (R:=@snd_rpo_mul P Prop max_size) (S:=S_157);\n[(* 1 *) apply wf_snd_rpo_mul, prec_wf\n|(* 2 *) idtac\n|(* 3 *) eexists; split; [ eassumption | idtac]; do_nat n ltac:(eexists); reflexivity\n];\n\nintros x G;\ndo_nat p ltac:(elim G; intro; clear G; intro G);\nrewrite G in * |- *; clear G; clear x;\nintro G;\napply main_157;\n [assumption | idtac];\nintros;\napply G;\n [ idtac | assumption ];\neexists; split;\n [idtac | do_nat n ltac:(eexists); reflexivity];\nassumption.\nQed.\n\n\nTheorem true_157: forall (u1: nat) (u2: nat), (nat_eq u1 u2) = true -> (nat_eq u1 u2) = false -> False.\nProof.\ndo 2 intro.\napply (all_true_157 F_157);\n (trivial_in 0) ||\n (repeat constructor).\nQed.\n\n\nDefinition type_LF_200 :=  PLAN ->  nat ->  nat ->  nat -> (Prop * (List.list term)).\n\nDefinition F_200 : type_LF_200:= (fun   u2 u1 _ _ => ((memberT u1 u2) = true -> (memberT u1 u2) = false -> False, (Term id_memberT ((model_nat u1):: (model_PLAN u2)::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u2)::nil))::(Term id_false nil)::nil)).\nDefinition F_213 : type_LF_200:= (fun    _ u1 _ _ => (false = true -> (memberT u1 Nil) = false -> False, (Term id_false nil)::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Nil nil)::nil))::(Term id_false nil)::nil)).\nDefinition F_219 : type_LF_200:= (fun   u6 u1 u4 u5 => (true = true -> (memberT u1 (Cons (C u4 u5) u6)) = false -> (nat_eq u1 u4) = true -> False, (Term id_true nil)::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u4):: (model_nat u5)::nil)):: (model_PLAN u6)::nil))::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u4)::nil))::(Term id_true nil)::nil)).\nDefinition F_225 : type_LF_200:= (fun   u6 u1 u4 u5 => ((memberT u1 u6) = true -> (memberT u1 (Cons (C u4 u5) u6)) = false -> (nat_eq u1 u4) = false -> False, (Term id_memberT ((model_nat u1):: (model_PLAN u6)::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u4):: (model_nat u5)::nil)):: (model_PLAN u6)::nil))::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u4)::nil))::(Term id_false nil)::nil)).\nDefinition F_240 : type_LF_200:= (fun   u6 u1 u4 _ => ((memberT u1 u6) = true -> true = false -> (nat_eq u1 u4) = false -> (nat_eq u1 u4) = true -> False, (Term id_memberT ((model_nat u1):: (model_PLAN u6)::nil))::(Term id_true nil)::(Term id_true nil)::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u4)::nil))::(Term id_true nil)::nil)).\nDefinition F_226 : type_LF_200:= (fun   u6 u1 u4 u5 => ((memberT u1 (Cons (C u4 u5) u6)) = false -> (nat_eq u1 u4) = true -> False, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u4):: (model_nat u5)::nil)):: (model_PLAN u6)::nil))::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u4)::nil))::(Term id_true nil)::nil)).\nDefinition F_256 : type_LF_200:= (fun    _ u1 u4 _ => (true = false -> (nat_eq u1 u4) = true -> (nat_eq u1 u4) = true -> False, (Term id_true nil)::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u4)::nil))::(Term id_true nil)::nil)).\nDefinition F_260 : type_LF_200:= (fun   u6 u1 u4 _ => ((memberT u1 u6) = false -> (nat_eq u1 u4) = true -> (nat_eq u1 u4) = false -> False, (Term id_memberT ((model_nat u1):: (model_PLAN u6)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u4)::nil))::(Term id_false nil)::nil)).\n\nDefinition LF_200 := [F_200, F_213, F_219, F_225, F_240, F_226, F_256, F_260].\n\n\nFunction f_200 (u2: PLAN) (u1: nat) {struct u2} : bool :=\n match u2, u1 with\n| Nil, _ => true\n| (Cons (C u4 u5) u6), _ => true\nend.\n\nLemma main_200 : forall F, In F LF_200 -> forall u1, forall u2, forall u3, forall u4, (forall F', In F' LF_200 -> forall e1, forall e2, forall e3, forall e4, less (snd (F' e1 e2 e3 e4)) (snd (F u1 u2 u3 u4)) -> fst (F' e1 e2 e3 e4)) -> fst (F u1 u2 u3 u4).\nProof.\nintros F HF u1 u2 u3 u4; case_In HF; intro Hind.\n\n\t(* GENERATE on [ 200 ] *)\n\nrename u1 into _u2. rename u2 into _u1. rename u3 into d_u3. rename u4 into d_u4. \nrename _u2 into u2. rename _u1 into u1. \n\nrevert Hind.\n\npattern u2, u1, (f_200 u2 u1). apply f_200_ind.\n\n(* case [ 213 ] *)\n\nintros _u2 _u1.  intro eq_1. intro. intro Heq1. rewrite <- Heq1.  intro HFabs0.\nassert (Hind := HFabs0 F_213). clear HFabs0.\nassert (HFabs0 : fst (F_213 Nil _u1 0 0)).\napply Hind. trivial_in 1. unfold snd. unfold F_213. unfold F_200. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_200. unfold F_213.\nauto.\n\n\n\nintros _u2 _u1. intro u4. intro u5. intro u6.  intro eq_1. intro. intro Heq1. rewrite <- Heq1.  intro HFabs0.\ncase_eq (nat_eq _u1 u4); [intro H | intro H].\n\n(* case [ 219 ] *)\n\nassert (Hind := HFabs0 F_219). clear HFabs0.\nassert (HFabs0 : fst (F_219 u6 _u1 u4 u5)).\napply Hind. trivial_in 2. unfold snd. unfold F_219. unfold F_200. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_200. unfold F_219. simpl in H. repeat(simpl; rewrite H). repeat(simpl in HFabs0; rewrite H in HFabs0). try (auto || (intro H0; contradict H0)). \nauto.\n\n\n(* case [ 225 ] *)\n\nassert (Hind := HFabs0 F_225). clear HFabs0.\nassert (HFabs0 : fst (F_225 u6 _u1 u4 u5)).\napply Hind. trivial_in 3. unfold snd. unfold F_225. unfold F_200. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_200. unfold F_225. simpl in H. repeat(simpl; rewrite H). repeat(simpl in HFabs0; rewrite H in HFabs0). try (auto || (intro H0; contradict H0)). \nauto.\n\n\n\n\n\n\t(* NEGATIVE CLASH on [ 213 ] *)\n\nunfold fst. unfold F_213. intros. try discriminate.\n\n\n\n\t(* NEGATIVE DECOMPOSITION on [ 219 ] *)\n\nrename u1 into _u6. rename u2 into _u1. rename u3 into _u4. rename u4 into _u5. \nrename _u6 into u6. rename _u1 into u1. rename _u4 into u4. rename _u5 into u5. \nassert (H := Hind F_226). \nassert (HFabs0 : fst (F_226 u6 u1 u4 u5)).\napply H. trivial_in 5. unfold snd. unfold F_226. unfold F_219. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_219. unfold F_226.\n\nunfold fst in HFabs0. unfold F_226 in HFabs0.\nauto.\n\n\n\n\t(* TOTAL CASE REWRITING on [ 225 ] *)\n\nrename u1 into _u6. rename u2 into _u1. rename u3 into _u4. rename u4 into _u5. \nrename _u6 into u6. rename _u1 into u1. rename _u4 into u4. rename _u5 into u5. \nassert (H: ((nat_eq u1 u4) = true) \\/ ((nat_eq u1 u4) = false)). \n\ndestruct ((nat_eq u1 u4)); auto.\n\ndestruct H as [H|H].\n\n(* rewriting with the axiom [ 93 ] *)\n\nassert (H1 := Hind F_240). clear Hind.\nassert (HFabs0 : fst (F_240 u6 u1 u4 0)).\napply H1. trivial_in 4. unfold snd. unfold F_240. unfold F_225. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_225. unfold F_240. unfold fst in HFabs0. unfold F_240 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u4.\npattern u5.\npattern u6.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 94 ] *)\n\nassert (H1 := Hind F_200). clear Hind.\nassert (HFabs0 : fst (F_200 u6 u1 0 0)).\napply H1. trivial_in 0. unfold snd. unfold F_200. unfold F_225. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_225. unfold F_200. unfold fst in HFabs0. unfold F_200 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u4.\npattern u5.\npattern u6.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n\n\t(* NEGATIVE CLASH on [ 240 ] *)\n\nunfold fst. unfold F_240. intros. try discriminate.\n\n\n\n\t(* TOTAL CASE REWRITING on [ 226 ] *)\n\nrename u1 into _u6. rename u2 into _u1. rename u3 into _u4. rename u4 into _u5. \nrename _u6 into u6. rename _u1 into u1. rename _u4 into u4. rename _u5 into u5. \nassert (H: ((nat_eq u1 u4) = true) \\/ ((nat_eq u1 u4) = false)). \n\ndestruct ((nat_eq u1 u4)); auto.\n\ndestruct H as [H|H].\n\n(* rewriting with the axiom [ 93 ] *)\n\nassert (H1 := Hind F_256). clear Hind.\nassert (HFabs0 : fst (F_256 Nil u1 u4 0)).\napply H1. trivial_in 6. unfold snd. unfold F_256. unfold F_226. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_226. unfold F_256. unfold fst in HFabs0. unfold F_256 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u4.\npattern u5.\npattern u6.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 94 ] *)\n\nassert (H1 := Hind F_260). clear Hind.\nassert (HFabs0 : fst (F_260 u6 u1 u4 0)).\napply H1. trivial_in 7. unfold snd. unfold F_260. unfold F_226. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_226. unfold F_260. unfold fst in HFabs0. unfold F_260 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u4.\npattern u5.\npattern u6.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n\n\t(* NEGATIVE CLASH on [ 256 ] *)\n\nunfold fst. unfold F_256. intros. try discriminate.\n\n\n\n\t(* SUBSUMPTION on [ 260 ] *)\n\nrename u1 into _u6. rename u2 into _u1. rename u3 into _u4. rename u4 into d_u4. \nrename _u6 into u6. rename _u1 into u1. rename _u4 into u4. \nunfold fst. unfold F_260. specialize true_157 with (u1 := u1) (u2 := u4). intro L. intros. contradict L. (auto || symmetry; auto).\n\n\n\nQed.\n\n\n\n(* the set of all formula instances from the proof *)\nDefinition S_200 := fun f => exists F, In F LF_200 /\\ exists e1, exists e2, exists e3, exists e4, f = F e1 e2 e3 e4.\n\nTheorem all_true_200: forall F, In F LF_200 -> forall u1: PLAN, forall u2: nat, forall u3: nat, forall u4: nat, fst (F u1 u2  u3  u4).\nProof.\nlet n := constr:(4) in\nlet p := constr:(S(S(n))) in\nintros;\nlet G := fresh \"G\" in\nlet x := fresh \"x\" in\napply wf_subset with (R:=@snd_rpo_mul P Prop max_size) (S:=S_200);\n[(* 1 *) apply wf_snd_rpo_mul, prec_wf\n|(* 2 *) idtac\n|(* 3 *) eexists; split; [ eassumption | idtac]; do_nat n ltac:(eexists); reflexivity\n];\n\nintros x G;\ndo_nat p ltac:(elim G; intro; clear G; intro G);\nrewrite G in * |- *; clear G; clear x;\nintro G;\napply main_200;\n [assumption | idtac];\nintros;\napply G;\n [ idtac | assumption ];\neexists; split;\n [idtac | do_nat n ltac:(eexists); reflexivity];\nassumption.\nQed.\n\n\nTheorem true_200: forall (u2: PLAN) (u1: nat), (memberT u1 u2) = true -> (memberT u1 u2) = false -> False.\nProof.\ndo 2 intro.\napply (all_true_200 F_200);\n (trivial_in 0) ||\n (repeat constructor).\nQed.\n\n\nDefinition type_LF_263 :=  PLAN ->  nat ->  nat ->  nat ->  nat ->  nat ->  nat ->  nat -> (Prop * (List.list term)).\n\nDefinition F_263 : type_LF_263:= (fun   u2 u1 u3 u4 _ _ _ _ => ((memberT u1 (insIn u2 u3 u4)) = true -> (memberT u1 u2) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_insIn ((model_PLAN u2):: (model_nat u3):: (model_nat u4)::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u2)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_277 : type_LF_263:= (fun    _ u1 u3 u4 _ _ _ _ => ((memberT u1 (Cons (C u3 u4) Nil)) = true -> (memberT u1 Nil) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u3):: (model_nat u4)::nil)):: (Term id_Nil nil)::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Nil nil)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_292 : type_LF_263:= (fun    _ u1 u3 u4 _ _ _ _ => ((memberT u1 (Cons (C u3 u4) Nil)) = true -> false = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u3):: (model_nat u4)::nil)):: (Term id_Nil nil)::nil))::nil))::(Term id_true nil)::(Term id_false nil)::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_283 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 (insIn u7 (time (C u9 u10)) u4)) = true -> (memberT u1 (Cons (C u9 u10) u7)) = false -> (le (er (C u9 u10)) u4) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_insIn ((model_PLAN u7):: (Term id_time ((Term id_C ((model_nat u9):: (model_nat u10)::nil))::nil)):: (model_nat u4)::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u10)::nil)):: (model_PLAN u7)::nil))::nil))::(Term id_false nil)::(Term id_le ((Term id_er ((Term id_C ((model_nat u9):: (model_nat u10)::nil))::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_289 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 (Cons (C u3 u4) (Cons (C u9 u10) u7))) = true -> (memberT u1 (Cons (C u9 u10) u7)) = false -> (le (er (C u9 u10)) u4) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u3):: (model_nat u4)::nil)):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u10)::nil)):: (model_PLAN u7)::nil))::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u10)::nil)):: (model_PLAN u7)::nil))::nil))::(Term id_false nil)::(Term id_le ((Term id_er ((Term id_C ((model_nat u9):: (model_nat u10)::nil))::nil)):: (model_nat u4)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_296 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 (insIn u7 u9 u4)) = true -> (memberT u1 (Cons (C u9 u10) u7)) = false -> (le (er (C u9 u10)) u4) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_insIn ((model_PLAN u7):: (model_nat u9):: (model_nat u4)::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u10)::nil)):: (model_PLAN u7)::nil))::nil))::(Term id_false nil)::(Term id_le ((Term id_er ((Term id_C ((model_nat u9):: (model_nat u10)::nil))::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_299 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 (Cons (C u3 u4) (Cons (C u9 u10) u7))) = true -> (memberT u1 (Cons (C u9 u10) u7)) = false -> (le u10 u4) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u3):: (model_nat u4)::nil)):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u10)::nil)):: (model_PLAN u7)::nil))::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u10)::nil)):: (model_PLAN u7)::nil))::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_330 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 (Cons (C u3 u4) (Cons (C u9 u10) u7))) = true -> true = false -> (le u10 u4) = false -> (nat_eq u1 u9) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u3):: (model_nat u4)::nil)):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u10)::nil)):: (model_PLAN u7)::nil))::nil))::nil))::(Term id_true nil)::(Term id_true nil)::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_334 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 (Cons (C u3 u4) (Cons (C u9 u10) u7))) = true -> (memberT u1 u7) = false -> (le u10 u4) = false -> (nat_eq u1 u9) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u3):: (model_nat u4)::nil)):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u10)::nil)):: (model_PLAN u7)::nil))::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u7)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_354 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => (true = true -> (memberT u1 u7) = false -> (le u10 u4) = false -> (nat_eq u1 u9) = false -> (nat_eq u1 u3) = true -> u3 = u1, (Term id_true nil)::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u7)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u3)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_358 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 (Cons (C u9 u10) u7)) = true -> (memberT u1 u7) = false -> (le u10 u4) = false -> (nat_eq u1 u9) = false -> (nat_eq u1 u3) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u10)::nil)):: (model_PLAN u7)::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u7)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u3)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_391 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => (true = true -> (memberT u1 u7) = false -> (le u10 u4) = false -> (nat_eq u1 u9) = false -> (nat_eq u1 u3) = false -> (nat_eq u1 u9) = true -> u3 = u1, (Term id_true nil)::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u7)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u3)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_395 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 u7) = true -> (memberT u1 u7) = false -> (le u10 u4) = false -> (nat_eq u1 u9) = false -> (nat_eq u1 u3) = false -> (nat_eq u1 u9) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (model_PLAN u7)::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u7)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u3)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_396 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 u7) = false -> (le u10 u4) = false -> (nat_eq u1 u9) = false -> (nat_eq u1 u3) = false -> (nat_eq u1 u9) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (model_PLAN u7)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u3)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_293 : type_LF_263:= (fun    _ u1 u3 u4 _ _ _ _ => ((memberT u1 (Cons (C u3 u4) Nil)) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u3):: (model_nat u4)::nil)):: (Term id_Nil nil)::nil))::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_418 : type_LF_263:= (fun    _ u1 u3 _ _ _ _ _ => (true = true -> (nat_eq u1 u3) = true -> u3 = u1, (Term id_true nil)::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u3)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_422 : type_LF_263:= (fun    _ u1 u3 _ _ _ _ _ => ((memberT u1 Nil) = true -> (nat_eq u1 u3) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Nil nil)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u3)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_426 : type_LF_263:= (fun    _ u1 u3 _ _ _ _ _ => (false = true -> (nat_eq u1 u3) = false -> u3 = u1, (Term id_false nil)::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u3)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_302 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 (insIn u7 u9 u4)) = true -> (memberT u1 (Cons (C u9 u10) u7)) = false -> (le u10 u4) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_insIn ((model_PLAN u7):: (model_nat u9):: (model_nat u4)::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u10)::nil)):: (model_PLAN u7)::nil))::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_448 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 (insIn u7 u9 u4)) = true -> true = false -> (le u10 u4) = true -> (nat_eq u1 u9) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_insIn ((model_PLAN u7):: (model_nat u9):: (model_nat u4)::nil))::nil))::(Term id_true nil)::(Term id_true nil)::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_452 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 (insIn u7 u9 u4)) = true -> (memberT u1 u7) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_insIn ((model_PLAN u7):: (model_nat u9):: (model_nat u4)::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u7)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_487 : type_LF_263:= (fun    _ u1 u3 u4 u9 u10 _ _ => ((memberT u1 (Cons (C u9 u4) Nil)) = true -> (memberT u1 Nil) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u4)::nil)):: (Term id_Nil nil)::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Nil nil)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_502 : type_LF_263:= (fun    _ u1 u3 u4 u9 u10 _ _ => ((memberT u1 (Cons (C u9 u4) Nil)) = true -> false = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u4)::nil)):: (Term id_Nil nil)::nil))::nil))::(Term id_true nil)::(Term id_false nil)::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_493 : type_LF_263:= (fun   u13 u1 u3 u4 u9 u10 u15 u16 => ((memberT u1 (insIn u13 (time (C u15 u16)) u4)) = true -> (memberT u1 (Cons (C u15 u16) u13)) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (le (er (C u15 u16)) u4) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_insIn ((model_PLAN u13):: (Term id_time ((Term id_C ((model_nat u15):: (model_nat u16)::nil))::nil)):: (model_nat u4)::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u15):: (model_nat u16)::nil)):: (model_PLAN u13)::nil))::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_le ((Term id_er ((Term id_C ((model_nat u15):: (model_nat u16)::nil))::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_499 : type_LF_263:= (fun   u13 u1 u3 u4 u9 u10 u15 u16 => ((memberT u1 (Cons (C u9 u4) (Cons (C u15 u16) u13))) = true -> (memberT u1 (Cons (C u15 u16) u13)) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (le (er (C u15 u16)) u4) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u4)::nil)):: (Term id_Cons ((Term id_C ((model_nat u15):: (model_nat u16)::nil)):: (model_PLAN u13)::nil))::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u15):: (model_nat u16)::nil)):: (model_PLAN u13)::nil))::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_le ((Term id_er ((Term id_C ((model_nat u15):: (model_nat u16)::nil))::nil)):: (model_nat u4)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_506 : type_LF_263:= (fun   u13 u1 u3 u4 u9 u10 u15 u16 => ((memberT u1 (insIn u13 u15 u4)) = true -> (memberT u1 (Cons (C u15 u16) u13)) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (le (er (C u15 u16)) u4) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_insIn ((model_PLAN u13):: (model_nat u15):: (model_nat u4)::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u15):: (model_nat u16)::nil)):: (model_PLAN u13)::nil))::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_le ((Term id_er ((Term id_C ((model_nat u15):: (model_nat u16)::nil))::nil)):: (model_nat u4)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_509 : type_LF_263:= (fun   u13 u1 u3 u4 u9 u10 u15 u16 => ((memberT u1 (Cons (C u9 u4) (Cons (C u15 u16) u13))) = true -> (memberT u1 (Cons (C u15 u16) u13)) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (le u16 u4) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u4)::nil)):: (Term id_Cons ((Term id_C ((model_nat u15):: (model_nat u16)::nil)):: (model_PLAN u13)::nil))::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u15):: (model_nat u16)::nil)):: (model_PLAN u13)::nil))::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_le ((model_nat u16):: (model_nat u4)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_577 : type_LF_263:= (fun   u13 u1 u3 u4 u9 u10 u15 u16 => ((memberT u1 (Cons (C u9 u4) (Cons (C u15 u16) u13))) = true -> true = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (le u16 u4) = false -> (nat_eq u1 u15) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u4)::nil)):: (Term id_Cons ((Term id_C ((model_nat u15):: (model_nat u16)::nil)):: (model_PLAN u13)::nil))::nil))::nil))::(Term id_true nil)::(Term id_true nil)::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_le ((model_nat u16):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u15)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_581 : type_LF_263:= (fun   u13 u1 u3 u4 u9 u10 u15 u16 => ((memberT u1 (Cons (C u9 u4) (Cons (C u15 u16) u13))) = true -> (memberT u1 u13) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (le u16 u4) = false -> (nat_eq u1 u15) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u4)::nil)):: (Term id_Cons ((Term id_C ((model_nat u15):: (model_nat u16)::nil)):: (model_PLAN u13)::nil))::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u13)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_le ((model_nat u16):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u15)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_625 : type_LF_263:= (fun   u13 u1 u3 u4 u9 u10 u15 u16 => (true = true -> (memberT u1 u13) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (le u16 u4) = false -> (nat_eq u1 u15) = false -> (nat_eq u1 u9) = true -> u3 = u1, (Term id_true nil)::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u13)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_le ((model_nat u16):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u15)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_630 : type_LF_263:= (fun   u13 u1 u3 u4 u9 u10 u15 u16 => ((memberT u1 u13) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (le u16 u4) = false -> (nat_eq u1 u15) = false -> (nat_eq u1 u9) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (model_PLAN u13)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_le ((model_nat u16):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u15)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_629 : type_LF_263:= (fun   u13 u1 u3 u4 u9 u10 u15 u16 => ((memberT u1 (Cons (C u15 u16) u13)) = true -> (memberT u1 u13) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (le u16 u4) = false -> (nat_eq u1 u15) = false -> (nat_eq u1 u9) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u15):: (model_nat u16)::nil)):: (model_PLAN u13)::nil))::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u13)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_le ((model_nat u16):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u15)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_678 : type_LF_263:= (fun   u13 u1 u3 u4 u9 u10 u15 u16 => (true = true -> (memberT u1 u13) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (le u16 u4) = false -> (nat_eq u1 u15) = false -> (nat_eq u1 u9) = false -> (nat_eq u1 u15) = true -> u3 = u1, (Term id_true nil)::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u13)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_le ((model_nat u16):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u15)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u15)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_682 : type_LF_263:= (fun   u13 u1 u3 u4 u9 u10 u15 u16 => ((memberT u1 u13) = true -> (memberT u1 u13) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (le u16 u4) = false -> (nat_eq u1 u15) = false -> (nat_eq u1 u9) = false -> (nat_eq u1 u15) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (model_PLAN u13)::nil))::(Term id_true nil)::(Term id_memberT ((model_nat u1):: (model_PLAN u13)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_le ((model_nat u16):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u15)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u15)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_683 : type_LF_263:= (fun   u13 u1 u3 u4 u9 u10 u15 u16 => ((memberT u1 u13) = false -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (le u16 u4) = false -> (nat_eq u1 u15) = false -> (nat_eq u1 u9) = false -> (nat_eq u1 u15) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (model_PLAN u13)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_le ((model_nat u16):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u15)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u15)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_503 : type_LF_263:= (fun    _ u1 u3 u4 u9 u10 _ _ => ((memberT u1 (Cons (C u9 u4) Nil)) = true -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Cons ((Term id_C ((model_nat u9):: (model_nat u4)::nil)):: (Term id_Nil nil)::nil))::nil))::(Term id_true nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_711 : type_LF_263:= (fun    _ u1 u3 u4 u9 u10 _ _ => (true = true -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (nat_eq u1 u9) = true -> u3 = u1, (Term id_true nil)::(Term id_true nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_715 : type_LF_263:= (fun    _ u1 u3 u4 u9 u10 _ _ => ((memberT u1 Nil) = true -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (nat_eq u1 u9) = false -> u3 = u1, (Term id_memberT ((model_nat u1):: (Term id_Nil nil)::nil))::(Term id_true nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_719 : type_LF_263:= (fun    _ u1 u3 u4 u9 u10 _ _ => (false = true -> (le u10 u4) = true -> (nat_eq u1 u9) = false -> (nat_eq u1 u9) = false -> u3 = u1, (Term id_false nil)::(Term id_true nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_716 : type_LF_263:= (fun    _ u1 u3 u4 u9 u10 _ _ => ((le u10 u4) = true -> (nat_eq u1 u9) = false -> (nat_eq u1 u9) = true -> u3 = u1, (Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_359 : type_LF_263:= (fun   u7 u1 u3 u4 u9 u10 _ _ => ((memberT u1 u7) = false -> (le u10 u4) = false -> (nat_eq u1 u9) = false -> (nat_eq u1 u3) = true -> u3 = u1, (Term id_memberT ((model_nat u1):: (model_PLAN u7)::nil))::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u3)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_749 : type_LF_263:= (fun    _ u1 u3 u4 u9 u10 u12 _ => (true = false -> (le u10 u4) = false -> (nat_eq u1 u9) = false -> (nat_eq u1 u3) = true -> (nat_eq u1 u12) = true -> u3 = u1, (Term id_true nil)::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u3)::nil))::(Term id_true nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u12)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_743 : type_LF_263:= (fun    _ u1 u3 u4 u9 u10 _ _ => (false = false -> (le u10 u4) = false -> (nat_eq u1 u9) = false -> (nat_eq u1 u3) = true -> u3 = u1, (Term id_false nil)::(Term id_false nil)::(Term id_le ((model_nat u10):: (model_nat u4)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u9)::nil))::(Term id_false nil)::(Term id_nat_eq ((model_nat u1):: (model_nat u3)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_423 : type_LF_263:= (fun    _ u1 u3 _ _ _ _ _ => ((nat_eq u1 u3) = true -> u3 = u1, (Term id_nat_eq ((model_nat u1):: (model_nat u3)::nil))::(Term id_true nil)::(model_nat u3)::(model_nat u1)::nil)).\nDefinition F_804 : type_LF_263:= (fun    _  _ _ _ _ _ _ _ => (true = true -> 0 = 0, (Term id_true nil)::(Term id_true nil)::(Term id_0 nil)::(Term id_0 nil)::nil)).\nDefinition F_810 : type_LF_263:= (fun    _ u5 _ _ _ _ _ _ => (false = true -> (S u5) = 0, (Term id_false nil)::(Term id_true nil)::(Term id_S ((model_nat u5)::nil))::(Term id_0 nil)::nil)).\nDefinition F_816 : type_LF_263:= (fun    _ u5 _ _ _ _ _ _ => (false = true -> 0 = (S u5), (Term id_false nil)::(Term id_true nil)::(Term id_0 nil)::(Term id_S ((model_nat u5)::nil))::nil)).\nDefinition F_822 : type_LF_263:= (fun    _ u5 u6 _ _ _ _ _ => ((nat_eq u5 u6) = true -> (S u6) = (S u5), (Term id_nat_eq ((model_nat u5):: (model_nat u6)::nil))::(Term id_true nil)::(Term id_S ((model_nat u6)::nil))::(Term id_S ((model_nat u5)::nil))::nil)).\n\nDefinition LF_263 := [F_263, F_277, F_292, F_283, F_289, F_296, F_299, F_330, F_334, F_354, F_358, F_391, F_395, F_396, F_293, F_418, F_422, F_426, F_302, F_448, F_452, F_487, F_502, F_493, F_499, F_506, F_509, F_577, F_581, F_625, F_630, F_629, F_678, F_682, F_683, F_503, F_711, F_715, F_719, F_716, F_359, F_749, F_743, F_423, F_804, F_810, F_816, F_822].\n\n\nFunction f_263 (u2: PLAN) (u3: nat) (u4: nat) {struct u2} : PLAN :=\n match u2, u3, u4 with\n| Nil, _, _ => Nil\n| (Cons (C u9 u10) u7), _, _ => Nil\nend.\n\nFunction f_452 (u7: PLAN) (u4: nat) (u9: nat) {struct u7} : PLAN :=\n match u7, u4, u9 with\n| Nil, _, _ => Nil\n| (Cons (C u15 u16) u13), _, _ => Nil\nend.\n\nFunction f_359 (u7: PLAN) (u1: nat) {struct u7} : bool :=\n match u7, u1 with\n| Nil, _ => true\n| (Cons (C u12 u13) u14), _ => true\nend.\n\nFunction f_423 (u1: nat) (u3: nat) {struct u3} : bool :=\n match u1, u3 with\n| 0, 0 => true\n| 0, (S u5) => true\n| (S u5), 0 => true\n| (S u5), (S u6) => true\nend.\n\nLemma main_263 : forall F, In F LF_263 -> forall u1, forall u2, forall u3, forall u4, forall u5, forall u6, forall u7, forall u8, (forall F', In F' LF_263 -> forall e1, forall e2, forall e3, forall e4, forall e5, forall e6, forall e7, forall e8, less (snd (F' e1 e2 e3 e4 e5 e6 e7 e8)) (snd (F u1 u2 u3 u4 u5 u6 u7 u8)) -> fst (F' e1 e2 e3 e4 e5 e6 e7 e8)) -> fst (F u1 u2 u3 u4 u5 u6 u7 u8).\nProof.\nintros F HF u1 u2 u3 u4 u5 u6 u7 u8; case_In HF; intro Hind.\n\n\t(* GENERATE on [ 263 ] *)\n\nrename u1 into _u2. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into d_u5. rename u6 into d_u6. rename u7 into d_u7. rename u8 into d_u8. \nrename _u2 into u2. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. \n\nrevert Hind.\n\npattern u2, u3, u4, (f_263 u2 u3 u4). apply f_263_ind.\n\n(* case [ 277 ] *)\n\nintros _u2 _u3 _u4.  intro eq_1. intro. intro Heq3. rewrite <- Heq3. intro. intro Heq4. rewrite <- Heq4.  intro HFabs0.\nassert (Hind := HFabs0 F_277). clear HFabs0.\nassert (HFabs0 : fst (F_277 Nil u1 _u3 _u4 0 0 0 0)).\napply Hind. trivial_in 1. unfold snd. unfold F_277. unfold F_263. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_263. unfold F_277.\nauto.\n\n\n\nintros _u2 _u3 _u4. intro u9. intro u10. intro u7.  intro eq_1. intro. intro Heq3. rewrite <- Heq3. intro. intro Heq4. rewrite <- Heq4.  intro HFabs0.\ncase_eq (le (er (C u9 u10)) _u4); [intro H | intro H].\n\n(* case [ 283 ] *)\n\nassert (Hind := HFabs0 F_283). clear HFabs0.\nassert (HFabs0 : fst (F_283 u7 u1 _u3 _u4 u9 u10 0 0)).\napply Hind. trivial_in 3. unfold snd. unfold F_283. unfold F_263. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_263. unfold F_283. simpl in H. repeat(simpl; rewrite H). repeat(simpl in HFabs0; rewrite H in HFabs0). try (auto || (intro H0; contradict H0)). \nauto.\n\n\n(* case [ 289 ] *)\n\nassert (Hind := HFabs0 F_289). clear HFabs0.\nassert (HFabs0 : fst (F_289 u7 u1 _u3 _u4 u9 u10 0 0)).\napply Hind. trivial_in 4. unfold snd. unfold F_289. unfold F_263. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_263. unfold F_289. simpl in H. repeat(simpl; rewrite H). repeat(simpl in HFabs0; rewrite H in HFabs0). try (auto || (intro H0; contradict H0)). \nauto.\n\n\n\n\n\n\t(* REWRITING on [ 277 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into d_u5. rename u6 into d_u6. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. rename _u4 into u4. \nassert (Res := Hind F_292). clear Hind.\nassert (HFabs1 : fst (F_292 Nil u1 u3 u4 0 0 0 0)).\napply Res. trivial_in 2. unfold snd. unfold F_292. unfold F_277. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_277. unfold fst in HFabs1. unfold F_292 in HFabs1.   \npattern u1. simpl (memberT _ _). cbv beta.\n simpl. auto.\n\n\n\n\t(* NEGATIVE DECOMPOSITION on [ 292 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into d_u5. rename u6 into d_u6. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. rename _u4 into u4. \nassert (H := Hind F_293). \nassert (HFabs0 : fst (F_293 Nil u1 u3 u4 0 0 0 0)).\napply H. trivial_in 14. unfold snd. unfold F_293. unfold F_292. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_292. unfold F_293.\n\nunfold fst in HFabs0. unfold F_293 in HFabs0.\nauto.\n\n\n\n\t(* REWRITING on [ 283 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (Res := Hind F_296). clear Hind.\nassert (HFabs1 : fst (F_296 u7 u1 u3 u4 u9 u10 0 0)).\napply Res. trivial_in 5. unfold snd. unfold F_296. unfold F_283. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_283. unfold fst in HFabs1. unfold F_296 in HFabs1.   \npattern u9, u10. simpl (time _). cbv beta.\n simpl. auto.\n\n\n\n\t(* REWRITING on [ 289 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (Res := Hind F_299). clear Hind.\nassert (HFabs1 : fst (F_299 u7 u1 u3 u4 u9 u10 0 0)).\napply Res. trivial_in 6. unfold snd. unfold F_299. unfold F_289. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_289. unfold fst in HFabs1. unfold F_299 in HFabs1.   \npattern u9, u10. simpl (er _). cbv beta.\n simpl. auto.\n\n\n\n\t(* REWRITING on [ 296 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (Res := Hind F_302). clear Hind.\nassert (HFabs1 : fst (F_302 u7 u1 u3 u4 u9 u10 0 0)).\napply Res. trivial_in 18. unfold snd. unfold F_302. unfold F_296. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_296. unfold fst in HFabs1. unfold F_302 in HFabs1.   \npattern u9, u10. simpl (er _). cbv beta.\n simpl. auto.\n\n\n\n\t(* TOTAL CASE REWRITING on [ 299 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (H: ((nat_eq u1 u9) = true) \\/ ((nat_eq u1 u9) = false)). \n\ndestruct ((nat_eq u1 u9)); auto.\n\ndestruct H as [H|H].\n\n(* rewriting with the axiom [ 93 ] *)\n\nassert (H1 := Hind F_330). clear Hind.\nassert (HFabs0 : fst (F_330 u7 u1 u3 u4 u9 u10 0 0)).\napply H1. trivial_in 7. unfold snd. unfold F_330. unfold F_299. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_299. unfold F_330. unfold fst in HFabs0. unfold F_330 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u9.\npattern u10.\npattern u7.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 94 ] *)\n\nassert (H1 := Hind F_334). clear Hind.\nassert (HFabs0 : fst (F_334 u7 u1 u3 u4 u9 u10 0 0)).\napply H1. trivial_in 8. unfold snd. unfold F_334. unfold F_299. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_299. unfold F_334. unfold fst in HFabs0. unfold F_334 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u9.\npattern u10.\npattern u7.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n\n\t(* NEGATIVE CLASH on [ 330 ] *)\n\nunfold fst. unfold F_330. intros. try discriminate.\n\n\n\n\t(* TOTAL CASE REWRITING on [ 334 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (H: ((nat_eq u1 u3) = true) \\/ ((nat_eq u1 u3) = false)). \n\ndestruct ((nat_eq u1 u3)); auto.\n\ndestruct H as [H|H].\n\n(* rewriting with the axiom [ 93 ] *)\n\nassert (H1 := Hind F_354). clear Hind.\nassert (HFabs0 : fst (F_354 u7 u1 u3 u4 u9 u10 0 0)).\napply H1. trivial_in 9. unfold snd. unfold F_354. unfold F_334. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_334. unfold F_354. unfold fst in HFabs0. unfold F_354 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u3.\npattern u4.\npattern (Cons (C u9 u10) u7).\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 94 ] *)\n\nassert (H1 := Hind F_358). clear Hind.\nassert (HFabs0 : fst (F_358 u7 u1 u3 u4 u9 u10 0 0)).\napply H1. trivial_in 10. unfold snd. unfold F_358. unfold F_334. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_334. unfold F_358. unfold fst in HFabs0. unfold F_358 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u3.\npattern u4.\npattern (Cons (C u9 u10) u7).\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n\n\t(* NEGATIVE DECOMPOSITION on [ 354 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (H := Hind F_359). \nassert (HFabs0 : fst (F_359 u7 u1 u3 u4 u9 u10 0 0)).\napply H. trivial_in 40. unfold snd. unfold F_359. unfold F_354. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_354. unfold F_359.\n\nunfold fst in HFabs0. unfold F_359 in HFabs0.\nauto.\n\n\n\n\t(* TOTAL CASE REWRITING on [ 358 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (H: ((nat_eq u1 u9) = true) \\/ ((nat_eq u1 u9) = false)). \n\ndestruct ((nat_eq u1 u9)); auto.\n\ndestruct H as [H|H].\n\n(* rewriting with the axiom [ 93 ] *)\n\nassert (H1 := Hind F_391). clear Hind.\nassert (HFabs0 : fst (F_391 u7 u1 u3 u4 u9 u10 0 0)).\napply H1. trivial_in 11. unfold snd. unfold F_391. unfold F_358. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_358. unfold F_391. unfold fst in HFabs0. unfold F_391 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u9.\npattern u10.\npattern u7.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 94 ] *)\n\nassert (H1 := Hind F_395). clear Hind.\nassert (HFabs0 : fst (F_395 u7 u1 u3 u4 u9 u10 0 0)).\napply H1. trivial_in 12. unfold snd. unfold F_395. unfold F_358. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_358. unfold F_395. unfold fst in HFabs0. unfold F_395 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u9.\npattern u10.\npattern u7.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n\n\t(* NEGATIVE DECOMPOSITION on [ 391 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (H := Hind F_396). \nassert (HFabs0 : fst (F_396 u7 u1 u3 u4 u9 u10 0 0)).\napply H. trivial_in 13. unfold snd. unfold F_396. unfold F_391. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_391. unfold F_396.\n\nunfold fst in HFabs0. unfold F_396 in HFabs0.\nauto.\n\n\n\n\t(* SUBSUMPTION on [ 395 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nunfold fst. unfold F_395. specialize true_200 with (u1 := u1) (u2 := u7). intro L. intros. contradict L. (auto || symmetry; auto).\n\n\n\n\t(* SUBSUMPTION on [ 396 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nunfold fst. unfold F_396. specialize true_157 with (u1 := u1) (u2 := u9). intro L. intros. contradict L. (auto || symmetry; auto).\n\n\n\n\t(* TOTAL CASE REWRITING on [ 293 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into d_u5. rename u6 into d_u6. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. rename _u4 into u4. \nassert (H: ((nat_eq u1 u3) = true) \\/ ((nat_eq u1 u3) = false)). \n\ndestruct ((nat_eq u1 u3)); auto.\n\ndestruct H as [H|H].\n\n(* rewriting with the axiom [ 93 ] *)\n\nassert (H1 := Hind F_418). clear Hind.\nassert (HFabs0 : fst (F_418 Nil u1 u3 0 0 0 0 0)).\napply H1. trivial_in 15. unfold snd. unfold F_418. unfold F_293. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_293. unfold F_418. unfold fst in HFabs0. unfold F_418 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u3.\npattern u4.\npattern Nil.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 94 ] *)\n\nassert (H1 := Hind F_422). clear Hind.\nassert (HFabs0 : fst (F_422 Nil u1 u3 0 0 0 0 0)).\napply H1. trivial_in 16. unfold snd. unfold F_422. unfold F_293. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_293. unfold F_422. unfold fst in HFabs0. unfold F_422 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u3.\npattern u4.\npattern Nil.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n\n\t(* NEGATIVE DECOMPOSITION on [ 418 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into d_u4. rename u5 into d_u5. rename u6 into d_u6. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. \nassert (H := Hind F_423). \nassert (HFabs0 : fst (F_423 Nil u1 u3 0 0 0 0 0)).\napply H. trivial_in 43. unfold snd. unfold F_423. unfold F_418. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_418. unfold F_423.\n\nunfold fst in HFabs0. unfold F_423 in HFabs0.\nauto.\n\n\n\n\t(* REWRITING on [ 422 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into d_u4. rename u5 into d_u5. rename u6 into d_u6. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. \nassert (Res := Hind F_426). clear Hind.\nassert (HFabs1 : fst (F_426 Nil u1 u3 0 0 0 0 0)).\napply Res. trivial_in 17. unfold snd. unfold F_426. unfold F_422. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_422. unfold fst in HFabs1. unfold F_426 in HFabs1.   \npattern u1. simpl (memberT _ _). cbv beta.\n simpl. auto.\n\n\n\n\t(* NEGATIVE CLASH on [ 426 ] *)\n\nunfold fst. unfold F_426. intros. try discriminate.\n\n\n\n\t(* TOTAL CASE REWRITING on [ 302 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (H: ((nat_eq u1 u9) = true) \\/ ((nat_eq u1 u9) = false)). \n\ndestruct ((nat_eq u1 u9)); auto.\n\ndestruct H as [H|H].\n\n(* rewriting with the axiom [ 93 ] *)\n\nassert (H1 := Hind F_448). clear Hind.\nassert (HFabs0 : fst (F_448 u7 u1 u3 u4 u9 u10 0 0)).\napply H1. trivial_in 19. unfold snd. unfold F_448. unfold F_302. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_302. unfold F_448. unfold fst in HFabs0. unfold F_448 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u9.\npattern u10.\npattern u7.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 94 ] *)\n\nassert (H1 := Hind F_452). clear Hind.\nassert (HFabs0 : fst (F_452 u7 u1 u3 u4 u9 u10 0 0)).\napply H1. trivial_in 20. unfold snd. unfold F_452. unfold F_302. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_302. unfold F_452. unfold fst in HFabs0. unfold F_452 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u9.\npattern u10.\npattern u7.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n\n\t(* NEGATIVE CLASH on [ 448 ] *)\n\nunfold fst. unfold F_448. intros. try discriminate.\n\n\n\n\t(* GENERATE on [ 452 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \n\nrevert Hind.\n\npattern u7, u4, u9, (f_452 u7 u4 u9). apply f_452_ind.\n\n(* case [ 487 ] *)\n\nintros _u7 _u4 _u9.  intro eq_1. intro. intro Heq4. rewrite <- Heq4. intro. intro Heq9. rewrite <- Heq9.  intro HFabs0.\nassert (Hind := HFabs0 F_487). clear HFabs0.\nassert (HFabs0 : fst (F_487 Nil u1 u3 _u4 _u9 u10 0 0)).\napply Hind. trivial_in 21. unfold snd. unfold F_487. unfold F_452. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_452. unfold F_487.\nauto.\n\n\n\nintros _u7 _u4 _u9. intro u15. intro u16. intro u13.  intro eq_1. intro. intro Heq4. rewrite <- Heq4. intro. intro Heq9. rewrite <- Heq9.  intro HFabs0.\ncase_eq (le (er (C u15 u16)) _u4); [intro H | intro H].\n\n(* case [ 493 ] *)\n\nassert (Hind := HFabs0 F_493). clear HFabs0.\nassert (HFabs0 : fst (F_493 u13 u1 u3 _u4 _u9 u10 u15 u16)).\napply Hind. trivial_in 23. unfold snd. unfold F_493. unfold F_452. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_452. unfold F_493. simpl in H. repeat(simpl; rewrite H). repeat(simpl in HFabs0; rewrite H in HFabs0). try (auto || (intro H0; contradict H0)). \nauto.\n\n\n(* case [ 499 ] *)\n\nassert (Hind := HFabs0 F_499). clear HFabs0.\nassert (HFabs0 : fst (F_499 u13 u1 u3 _u4 _u9 u10 u15 u16)).\napply Hind. trivial_in 24. unfold snd. unfold F_499. unfold F_452. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_452. unfold F_499. simpl in H. repeat(simpl; rewrite H). repeat(simpl in HFabs0; rewrite H in HFabs0). try (auto || (intro H0; contradict H0)). \nauto.\n\n\n\n\n\n\t(* REWRITING on [ 487 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (Res := Hind F_502). clear Hind.\nassert (HFabs1 : fst (F_502 Nil u1 u3 u4 u9 u10 0 0)).\napply Res. trivial_in 22. unfold snd. unfold F_502. unfold F_487. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_487. unfold fst in HFabs1. unfold F_502 in HFabs1.   \npattern u1. simpl (memberT _ _). cbv beta.\n simpl. auto.\n\n\n\n\t(* NEGATIVE DECOMPOSITION on [ 502 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (H := Hind F_503). \nassert (HFabs0 : fst (F_503 Nil u1 u3 u4 u9 u10 0 0)).\napply H. trivial_in 35. unfold snd. unfold F_503. unfold F_502. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_502. unfold F_503.\n\nunfold fst in HFabs0. unfold F_503 in HFabs0.\nauto.\n\n\n\n\t(* REWRITING on [ 493 ] *)\n\nrename u1 into _u13. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into _u15. rename u8 into _u16. \nrename _u13 into u13. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. rename _u15 into u15. rename _u16 into u16. \nassert (Res := Hind F_506). clear Hind.\nassert (HFabs1 : fst (F_506 u13 u1 u3 u4 u9 u10 u15 u16)).\napply Res. trivial_in 25. unfold snd. unfold F_506. unfold F_493. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_493. unfold fst in HFabs1. unfold F_506 in HFabs1.   \npattern u15, u16. simpl (time _). cbv beta.\n simpl. auto.\n\n\n\n\t(* REWRITING on [ 499 ] *)\n\nrename u1 into _u13. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into _u15. rename u8 into _u16. \nrename _u13 into u13. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. rename _u15 into u15. rename _u16 into u16. \nassert (Res := Hind F_509). clear Hind.\nassert (HFabs1 : fst (F_509 u13 u1 u3 u4 u9 u10 u15 u16)).\napply Res. trivial_in 26. unfold snd. unfold F_509. unfold F_499. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_499. unfold fst in HFabs1. unfold F_509 in HFabs1.   \npattern u15, u16. simpl (er _). cbv beta.\n simpl. auto.\n\n\n\n\t(* REWRITING on [ 506 ] *)\n\nrename u1 into _u13. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into _u15. rename u8 into _u16. \nrename _u13 into u13. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. rename _u15 into u15. rename _u16 into u16. \nassert (Res := Hind F_302). clear Hind.\nassert (HFabs1 : fst (F_302 u13 u1 u3 u4 u15 u16 0 0)).\napply Res. trivial_in 18. unfold snd. unfold F_302. unfold F_506. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_506. unfold fst in HFabs1. unfold F_302 in HFabs1.   \npattern u15, u16. simpl (er _). cbv beta.\n simpl. auto.\n\n\n\n\t(* TOTAL CASE REWRITING on [ 509 ] *)\n\nrename u1 into _u13. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into _u15. rename u8 into _u16. \nrename _u13 into u13. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. rename _u15 into u15. rename _u16 into u16. \nassert (H: ((nat_eq u1 u15) = true) \\/ ((nat_eq u1 u15) = false)). \n\ndestruct ((nat_eq u1 u15)); auto.\n\ndestruct H as [H|H].\n\n(* rewriting with the axiom [ 93 ] *)\n\nassert (H1 := Hind F_577). clear Hind.\nassert (HFabs0 : fst (F_577 u13 u1 u3 u4 u9 u10 u15 u16)).\napply H1. trivial_in 27. unfold snd. unfold F_577. unfold F_509. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_509. unfold F_577. unfold fst in HFabs0. unfold F_577 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u15.\npattern u16.\npattern u13.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 94 ] *)\n\nassert (H1 := Hind F_581). clear Hind.\nassert (HFabs0 : fst (F_581 u13 u1 u3 u4 u9 u10 u15 u16)).\napply H1. trivial_in 28. unfold snd. unfold F_581. unfold F_509. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_509. unfold F_581. unfold fst in HFabs0. unfold F_581 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u15.\npattern u16.\npattern u13.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n\n\t(* NEGATIVE CLASH on [ 577 ] *)\n\nunfold fst. unfold F_577. intros. try discriminate.\n\n\n\n\t(* TOTAL CASE REWRITING on [ 581 ] *)\n\nrename u1 into _u13. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into _u15. rename u8 into _u16. \nrename _u13 into u13. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. rename _u15 into u15. rename _u16 into u16. \nassert (H: ((nat_eq u1 u9) = true) \\/ ((nat_eq u1 u9) = false)). \n\ndestruct ((nat_eq u1 u9)); auto.\n\ndestruct H as [H|H].\n\n(* rewriting with the axiom [ 93 ] *)\n\nassert (H1 := Hind F_625). clear Hind.\nassert (HFabs0 : fst (F_625 u13 u1 u3 u4 u9 u10 u15 u16)).\napply H1. trivial_in 29. unfold snd. unfold F_625. unfold F_581. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_581. unfold F_625. unfold fst in HFabs0. unfold F_625 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u9.\npattern u4.\npattern (Cons (C u15 u16) u13).\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 94 ] *)\n\nassert (H1 := Hind F_629). clear Hind.\nassert (HFabs0 : fst (F_629 u13 u1 u3 u4 u9 u10 u15 u16)).\napply H1. trivial_in 31. unfold snd. unfold F_629. unfold F_581. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_581. unfold F_629. unfold fst in HFabs0. unfold F_629 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u9.\npattern u4.\npattern (Cons (C u15 u16) u13).\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n\n\t(* NEGATIVE DECOMPOSITION on [ 625 ] *)\n\nrename u1 into _u13. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into _u15. rename u8 into _u16. \nrename _u13 into u13. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. rename _u15 into u15. rename _u16 into u16. \nassert (H := Hind F_630). \nassert (HFabs0 : fst (F_630 u13 u1 u3 u4 u9 u10 u15 u16)).\napply H. trivial_in 30. unfold snd. unfold F_630. unfold F_625. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_625. unfold F_630.\n\nunfold fst in HFabs0. unfold F_630 in HFabs0.\nauto.\n\n\n\n\t(* SUBSUMPTION on [ 630 ] *)\n\nrename u1 into _u13. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into _u15. rename u8 into _u16. \nrename _u13 into u13. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. rename _u15 into u15. rename _u16 into u16. \nunfold fst. unfold F_630. specialize true_157 with (u1 := u1) (u2 := u9). intro L. intros. contradict L. (auto || symmetry; auto).\n\n\n\n\t(* TOTAL CASE REWRITING on [ 629 ] *)\n\nrename u1 into _u13. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into _u15. rename u8 into _u16. \nrename _u13 into u13. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. rename _u15 into u15. rename _u16 into u16. \nassert (H: ((nat_eq u1 u15) = true) \\/ ((nat_eq u1 u15) = false)). \n\ndestruct ((nat_eq u1 u15)); auto.\n\ndestruct H as [H|H].\n\n(* rewriting with the axiom [ 93 ] *)\n\nassert (H1 := Hind F_678). clear Hind.\nassert (HFabs0 : fst (F_678 u13 u1 u3 u4 u9 u10 u15 u16)).\napply H1. trivial_in 32. unfold snd. unfold F_678. unfold F_629. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_629. unfold F_678. unfold fst in HFabs0. unfold F_678 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u15.\npattern u16.\npattern u13.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 94 ] *)\n\nassert (H1 := Hind F_682). clear Hind.\nassert (HFabs0 : fst (F_682 u13 u1 u3 u4 u9 u10 u15 u16)).\napply H1. trivial_in 33. unfold snd. unfold F_682. unfold F_629. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_629. unfold F_682. unfold fst in HFabs0. unfold F_682 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u15.\npattern u16.\npattern u13.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n\n\t(* NEGATIVE DECOMPOSITION on [ 678 ] *)\n\nrename u1 into _u13. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into _u15. rename u8 into _u16. \nrename _u13 into u13. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. rename _u15 into u15. rename _u16 into u16. \nassert (H := Hind F_683). \nassert (HFabs0 : fst (F_683 u13 u1 u3 u4 u9 u10 u15 u16)).\napply H. trivial_in 34. unfold snd. unfold F_683. unfold F_678. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_678. unfold F_683.\n\nunfold fst in HFabs0. unfold F_683 in HFabs0.\nauto.\n\n\n\n\t(* SUBSUMPTION on [ 682 ] *)\n\nrename u1 into _u13. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into _u15. rename u8 into _u16. \nrename _u13 into u13. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. rename _u15 into u15. rename _u16 into u16. \nunfold fst. unfold F_682. specialize true_200 with (u1 := u1) (u2 := u13). intro L. intros. contradict L. (auto || symmetry; auto).\n\n\n\n\t(* SUBSUMPTION on [ 683 ] *)\n\nrename u1 into _u13. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into _u15. rename u8 into _u16. \nrename _u13 into u13. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. rename _u15 into u15. rename _u16 into u16. \nunfold fst. unfold F_683. specialize true_157 with (u1 := u1) (u2 := u15). intro L. intros. contradict L. (auto || symmetry; auto).\n\n\n\n\t(* TOTAL CASE REWRITING on [ 503 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (H: ((nat_eq u1 u9) = true) \\/ ((nat_eq u1 u9) = false)). \n\ndestruct ((nat_eq u1 u9)); auto.\n\ndestruct H as [H|H].\n\n(* rewriting with the axiom [ 93 ] *)\n\nassert (H1 := Hind F_711). clear Hind.\nassert (HFabs0 : fst (F_711 Nil u1 u3 u4 u9 u10 0 0)).\napply H1. trivial_in 36. unfold snd. unfold F_711. unfold F_503. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_503. unfold F_711. unfold fst in HFabs0. unfold F_711 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u9.\npattern u4.\npattern Nil.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n(* rewriting with the axiom [ 94 ] *)\n\nassert (H1 := Hind F_715). clear Hind.\nassert (HFabs0 : fst (F_715 Nil u1 u3 u4 u9 u10 0 0)).\napply H1. trivial_in 37. unfold snd. unfold F_715. unfold F_503. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_503. unfold F_715. unfold fst in HFabs0. unfold F_715 in HFabs0. simpl in HFabs0. \npattern u1.\npattern u9.\npattern u4.\npattern Nil.\nsimpl (memberT _ _). cbv beta. try unfold memberT. try rewrite H. try rewrite H0. try unfold memberT in HFabs0. try rewrite H in HFabs0. try rewrite H0 in HFabs0. auto.\n\n\n\n\t(* NEGATIVE DECOMPOSITION on [ 711 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (H := Hind F_716). \nassert (HFabs0 : fst (F_716 Nil u1 u3 u4 u9 u10 0 0)).\napply H. trivial_in 39. unfold snd. unfold F_716. unfold F_711. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_711. unfold F_716.\n\nunfold fst in HFabs0. unfold F_716 in HFabs0.\nauto.\n\n\n\n\t(* REWRITING on [ 715 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (Res := Hind F_719). clear Hind.\nassert (HFabs1 : fst (F_719 Nil u1 u3 u4 u9 u10 0 0)).\napply Res. trivial_in 38. unfold snd. unfold F_719. unfold F_715. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_715. unfold fst in HFabs1. unfold F_719 in HFabs1.   \npattern u1. simpl (memberT _ _). cbv beta.\n simpl. auto.\n\n\n\n\t(* NEGATIVE CLASH on [ 719 ] *)\n\nunfold fst. unfold F_719. intros. try discriminate.\n\n\n\n\t(* SUBSUMPTION on [ 716 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nunfold fst. unfold F_716. specialize true_157 with (u1 := u1) (u2 := u9). intro L. intros. contradict L. (auto || symmetry; auto).\n\n\n\n\t(* GENERATE on [ 359 ] *)\n\nrename u1 into _u7. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u7 into u7. rename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \n\nrevert Hind.\n\npattern u7, u1, (f_359 u7 u1). apply f_359_ind.\n\n(* case [ 743 ] *)\n\nintros _u7 _u1.  intro eq_1. intro. intro Heq1. rewrite <- Heq1.  intro HFabs0.\nassert (Hind := HFabs0 F_743). clear HFabs0.\nassert (HFabs0 : fst (F_743 Nil _u1 u3 u4 u9 u10 0 0)).\napply Hind. trivial_in 42. unfold snd. unfold F_743. unfold F_359. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_359. unfold F_743.\nauto.\n\n\n\nintros _u7 _u1. intro u12. intro u13. intro u14.  intro eq_1. intro. intro Heq1. rewrite <- Heq1.  intro HFabs0.\ncase_eq (nat_eq _u1 u12); [intro H | intro H].\n\n(* case [ 749 ] *)\n\nassert (Hind := HFabs0 F_749). clear HFabs0.\nassert (HFabs0 : fst (F_749 Nil _u1 u3 u4 u9 u10 u12 0)).\napply Hind. trivial_in 41. unfold snd. unfold F_749. unfold F_359. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_359. unfold F_749. simpl in H. repeat(simpl; rewrite H). repeat(simpl in HFabs0; rewrite H in HFabs0). try (auto || (intro H0; contradict H0)). \nauto.\n\n\n(* case [ 755 ] *)\n\nassert (Hind := HFabs0 F_359). clear HFabs0.\nassert (HFabs0 : fst (F_359 u14 _u1 u3 u4 u9 u10 0 0)).\napply Hind. trivial_in 40. unfold snd. unfold F_359. unfold F_359. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_359. unfold F_359. simpl in H. repeat(simpl; rewrite H). repeat(simpl in HFabs0; rewrite H in HFabs0). try (auto || (intro H0; contradict H0)). \nauto.\n\n\n\n\n\n\t(* NEGATIVE CLASH on [ 749 ] *)\n\nunfold fst. unfold F_749. intros. try discriminate.\n\n\n\n\t(* NEGATIVE DECOMPOSITION on [ 743 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into _u4. rename u5 into _u9. rename u6 into _u10. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. rename _u4 into u4. rename _u9 into u9. rename _u10 into u10. \nassert (H := Hind F_423). \nassert (HFabs0 : fst (F_423 Nil u1 u3 0 0 0 0 0)).\napply H. trivial_in 43. unfold snd. unfold F_423. unfold F_743. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_743. unfold F_423.\n\nunfold fst in HFabs0. unfold F_423 in HFabs0.\nauto.\n\n\n\n\t(* GENERATE on [ 423 ] *)\n\nrename u1 into d_u1. rename u2 into _u1. rename u3 into _u3. rename u4 into d_u4. rename u5 into d_u5. rename u6 into d_u6. rename u7 into d_u7. rename u8 into d_u8. \nrename _u1 into u1. rename _u3 into u3. \n\nrevert Hind.\n\npattern u1, u3, (f_423 u1 u3). apply f_423_ind.\n\n(* case [ 804 ] *)\n\nintros _u1 _u3.  intro eq_1.  intro eq_2.  intro HFabs0.\nassert (Hind := HFabs0 F_804). clear HFabs0.\nassert (HFabs0 : fst (F_804 Nil 0 0 0 0 0 0 0)).\napply Hind. trivial_in 44. unfold snd. unfold F_804. unfold F_423. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_423. unfold F_804.\nauto.\n\n\n(* case [ 810 ] *)\n\nintros _u1 _u3.  intro eq_1. intro u5.  intro eq_2.  intro HFabs0.\nassert (Hind := HFabs0 F_810). clear HFabs0.\nassert (HFabs0 : fst (F_810 Nil u5 0 0 0 0 0 0)).\napply Hind. trivial_in 45. unfold snd. unfold F_810. unfold F_423. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_423. unfold F_810.\nauto.\n\n\n(* case [ 816 ] *)\n\nintros _u1 _u3. intro u5.  intro eq_1.  intro eq_2.  intro HFabs0.\nassert (Hind := HFabs0 F_816). clear HFabs0.\nassert (HFabs0 : fst (F_816 Nil u5 0 0 0 0 0 0)).\napply Hind. trivial_in 46. unfold snd. unfold F_816. unfold F_423. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_423. unfold F_816.\nauto.\n\n\n(* case [ 822 ] *)\n\nintros _u1 _u3. intro u5.  intro eq_1. intro u6.  intro eq_2.  intro HFabs0.\nassert (Hind := HFabs0 F_822). clear HFabs0.\nassert (HFabs0 : fst (F_822 Nil u5 u6 0 0 0 0 0)).\napply Hind. trivial_in 47. unfold snd. unfold F_822. unfold F_423. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_423. unfold F_822.\nauto.\n\n\n\n\n\n\t(* TAUTOLOGY on [ 804 ] *)\n\nunfold fst. unfold F_804.\nauto.\n\n\n\n\t(* NEGATIVE CLASH on [ 810 ] *)\n\nunfold fst. unfold F_810. intros. try discriminate.\n\n\n\n\t(* NEGATIVE CLASH on [ 816 ] *)\n\nunfold fst. unfold F_816. intros. try discriminate.\n\n\n\n\t(* POSITIVE DECOMPOSITION on [ 822 ] *)\n\nrename u1 into d_u1. rename u2 into _u5. rename u3 into _u6. rename u4 into d_u4. rename u5 into d_u5. rename u6 into d_u6. rename u7 into d_u7. rename u8 into d_u8. \nrename _u5 into u5. rename _u6 into u6. \nassert (H1 := Hind F_423). \nassert (HFabs1 : fst (F_423 Nil u5 u6 0 0 0 0 0)).\napply H1. trivial_in 43. unfold snd. unfold F_423. unfold F_822. rewrite_model. abstract solve_rpo_mul.\nunfold fst. unfold F_822. unfold F_423.\n\nunfold fst in HFabs1. unfold F_423 in HFabs1.\n\nrepeat (auto || (rewrite HFabs1||  auto)).\n\n\nQed.\n\n\n\n(* the set of all formula instances from the proof *)\nDefinition S_263 := fun f => exists F, In F LF_263 /\\ exists e1, exists e2, exists e3, exists e4, exists e5, exists e6, exists e7, exists e8, f = F e1 e2 e3 e4 e5 e6 e7 e8.\n\nTheorem all_true_263: forall F, In F LF_263 -> forall u1: PLAN, forall u2: nat, forall u3: nat, forall u4: nat, forall u5: nat, forall u6: nat, forall u7: nat, forall u8: nat, fst (F u1 u2  u3  u4  u5  u6  u7  u8).\nProof.\nlet n := constr:(8) in\nlet p := constr:(S(S(n))) in\nintros;\nlet G := fresh \"G\" in\nlet x := fresh \"x\" in\napply wf_subset with (R:=@snd_rpo_mul P Prop max_size) (S:=S_263);\n[(* 1 *) apply wf_snd_rpo_mul, prec_wf\n|(* 2 *) idtac\n|(* 3 *) eexists; split; [ eassumption | idtac]; do_nat n ltac:(eexists); reflexivity\n];\n\nintros x G;\ndo_nat p ltac:(elim G; intro; clear G; intro G);\nrewrite G in * |- *; clear G; clear x;\nintro G;\napply main_263;\n [assumption | idtac];\nintros;\napply G;\n [ idtac | assumption ];\neexists; split;\n [idtac | do_nat n ltac:(eexists); reflexivity];\nassumption.\nQed.\n\n\nTheorem true_263: forall (u2: PLAN) (u1: nat) (u3: nat) (u4: nat), (memberT u1 (insIn u2 u3 u4)) = true -> (memberT u1 u2) = false -> u3 = u1.\nProof.\ndo 4 intro.\napply (all_true_263 F_263);\n (trivial_in 0) ||\n (repeat constructor).\nQed.\n", "meta": {"author": "sorinica", "repo": "spike-prover", "sha": "f2d6dd0bcebb647e09dd23048753075551da27eb", "save_path": "github-repos/coq/sorinica-spike-prover", "path": "github-repos/coq/sorinica-spike-prover/spike-prover-f2d6dd0bcebb647e09dd23048753075551da27eb/specs/ABR/certified/member_t_insin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2474594239801285}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.lib.Axioms.\n\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import VST.msl.Extensionality.\n\nRequire Import VST.sepcomp.mem_lemmas.\nRequire Import VST.sepcomp.semantics.\nRequire Import VST.sepcomp.effect_semantics.\nRequire Import VST.sepcomp.structured_injections.\n\nDefinition vis mu := fun b => locBlocksSrc mu b || frgnBlocksSrc mu b.\nDefinition visTgt mu := fun b => locBlocksTgt mu b || frgnBlocksTgt mu b.\n\nInductive reach (m:mem) (B:block -> Prop): list (block * Z) -> block -> Prop :=\n  reach_nil: forall b, B b -> reach m B nil b\n| reach_cons: forall b L b' z off n q,\n                     reach m B L b' ->\n                     Mem.perm m b' z Cur Readable ->\n                     ZMap.get z (PMap.get b' (Mem.mem_contents m)) =\n                     Fragment (Vptr b off) q n ->\n              reach m B ((b',z)::L) b.\n\nFixpoint reach' (m:mem) (B:block -> Prop) (L:list (block * Z)): block -> Prop:=\n  match L with\n    nil => B\n  | l::L => match l with\n             (b',z) => match ZMap.get z (PMap.get b' (Mem.mem_contents m))\n                       with Fragment (Vptr b off) q  n => fun bb => bb = b /\\\n                                               Mem.perm m b' z Cur Readable /\\\n                                               reach' m B L b'\n                           | _ => fun bb => False\n                       end\n            end\n  end.\n\nLemma reach_reach': forall m B L b1, reach m B L b1 <-> reach' m B L b1.\nProof. intros m B L.\n  induction L; simpl; split; intros.\n    inv H. trivial. constructor. trivial.\n  destruct a as [b' z]. destruct (IHL b') as [IHa IHb]; clear IHL.\n    inv H. rewrite H6.\n    destruct (Mem.perm_dec m b' z Cur Readable); try contradiction; simpl.\n    split; trivial. eauto.\n  destruct a as [b' z].\n    remember (ZMap.get z (Mem.mem_contents m) !! b') as v.\n    destruct v; try inv H; destruct v; try inv H. apply eq_sym in Heqv.\n    destruct H1. apply IHL in H0.\n      econstructor; try eassumption.\nQed.\n\nFixpoint reach'' (m:mem) (B:block -> bool) (L:list (block * Z)): block -> bool:=\n  match L with\n    nil => B\n  | l::L => match l with\n             (b',z) => match ZMap.get z (PMap.get b' (Mem.mem_contents m))\n                       with Fragment (Vptr b off) q  n => fun bb => eq_block bb b &&\n                                               Mem.perm_dec m b' z Cur Readable  &&\n                                               reach'' m B L b'\n                           | _ => fun bb => false\n                       end\n            end\n  end.\n\nLemma reach_reach'' m B L b1 :\n  reach m (fun b => B b=true) L b1 <-> reach'' m B L b1=true.\nProof.\n  revert b1. induction L; simpl; split; intros.\n    inv H. trivial. constructor. trivial.\n  destruct a as [b' z]. destruct (IHL b') as [IHa IHb]; clear IHL.\n    inv H. rewrite H6.\n    destruct (Mem.perm_dec m b' z Cur Readable); try contradiction; simpl.\n    rewrite !andb_true_iff. split; auto. split; auto.\n    case (eq_block b1 b1); auto.\n  destruct a as [b' z].\n    remember (ZMap.get z (Mem.mem_contents m) !! b') as v.\n    destruct v; try solve[inv H]; destruct v; try solve[inv H]. apply eq_sym in Heqv.\n    rewrite !andb_true_iff in H. destruct H as [[H1 X] H0].\n    apply IHL in H0. econstructor; try eassumption.\n    revert X.\n    case_eq (Mem.perm_dec m b' z Cur Readable); auto.\n    simpl. intros. congruence.\n    revert H1.\n    case_eq (eq_block b1 b).\n    intros ->. simpl. eauto.\n    simpl; intros. congruence.\nQed.\n\nLemma reach_inject: forall m1 m2 j (J: Mem.inject j m1 m2)\n                 L1 b1 B1 (R: reach m1 B1 L1 b1) B2\n                 (HB: forall b, B1 b -> exists jb d, j b = Some(jb,d) /\\ B2 jb),\n                 exists b2 L2 d2, j b1 = Some(b2,d2) /\\ reach m2 B2 L2 b2.\nProof. intros.\n  induction R.\n    destruct (HB _ H) as [jb [d [Jb B]]].\n    exists jb, nil, d. split; trivial. constructor. assumption.\n  destruct IHR as [b2' [L2' [d2' [J' R2']]]].\n    clear R HB.\n    specialize (Mem.mi_memval _ _ _ (Mem.mi_inj _ _ _ J) _ _ _ _ J' H).\n    intros. rewrite H0 in H1.\n    inv H1.\n    inv H3.\n    exists b2, ((b2',(z + d2'))::L2'), delta.\n    split. assumption.\n    eapply reach_cons. apply R2'.\n       eapply Mem.perm_inject. apply J'. apply J. apply H.\n       apply eq_sym. apply H6.\nQed.\n\nLemma reach_mono: forall B1 B2 (HB : forall b, B1 b = true -> B2 b = true)\n                         m b L1 (R : reach m (fun bb : block => B1 bb = true) L1 b),\n                  exists L, reach m (fun bb : block => B2 bb = true) L b.\nProof. intros.\n  induction R; simpl in *.\n    exists nil. constructor.  eauto.\n  destruct IHR as [L2 R2].\n    eexists. eapply reach_cons; eassumption.\nQed.\n\nParameter REACH : mem -> (block -> bool) -> block -> bool.\nAxiom REACHAX : (* Constructible via FiniteMaps.v, relying on finiteness of memories *)\n  forall m B b, REACH m B b = true\n  <-> exists L, reach m (fun bb => B bb = true) L b.\n\nLemma REACH_nil: forall m B b, B b = true -> REACH m B b = true.\nProof. intros. apply REACHAX.\n exists nil. constructor. assumption.\nQed.\n\nLemma REACH_cons: forall m B b b' z off n q,\n                     REACH m B b' = true ->\n                     Mem.perm m b' z Cur Readable ->\n                     ZMap.get z (PMap.get b' (Mem.mem_contents m)) =\n                        Fragment (Vptr b off) q  n ->\n                  REACH m B b = true.\nProof. intros.\n  apply REACHAX in H. destruct H as [L HL].\n  apply REACHAX. eexists.\n  eapply reach_cons; eassumption.\nQed.\n\nLemma REACH_inject: forall m1 m2 j (J: Mem.inject j m1 m2) B1 B2\n                 (HB: forall b, B1 b = true -> exists jb d, j b = Some(jb,d) /\\ B2 jb = true)\n                 b1 (R: REACH m1 B1 b1 = true),\n                 exists b2 d, j b1 = Some(b2,d) /\\ REACH m2 B2 b2 = true.\nProof.\n  intros. apply REACHAX in R. destruct R as [L1 R].\n  destruct (reach_inject _ _ _ J _ _ _ R _ HB) as [b2 [L2 [off [J2 R2]]]].\n  exists b2, off. split; trivial.\n    apply REACHAX. exists L2; assumption.\nQed.\n\nLemma REACH_mono: forall B1 B2 (HB: forall b, B1 b = true -> B2 b = true) m b\n                  (R: REACH m B1 b = true), REACH m B2 b = true.\nProof. intros. rewrite REACHAX in *.\n  destruct R as [L1 R].\n  apply (reach_mono _ _ HB _ _ _ R).\nQed.\n\nDefinition replace_locals (mu:SM_Injection) pSrc' pTgt': SM_Injection :=\n  match mu with\n    Build_SM_Injection locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern =>\n    Build_SM_Injection locBSrc locBTgt pSrc' pTgt' local extBSrc extBTgt fSrc fTgt extern\n  end.\n(*typically, we have forall b, pSrc b -> pSrc' b and forall b, pTgt b -> pTgt' b,\n  i.e. only reclassify private entries as public*)\n\nLemma replace_locals_wd: forall mu (WD: SM_wd mu) pSrc' pTgt'\n         (SRC: forall b1, pSrc' b1 = true ->\n               exists b2 d, local_of mu b1 = Some(b2,d) /\\ pTgt' b2=true)\n         (TGT: forall b, pTgt' b = true -> locBlocksTgt mu b = true),\n      SM_wd (replace_locals mu pSrc' pTgt').\nProof. intros.\n  destruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\n  constructor; simpl; try apply WD.\n    intros. apply (SRC _ H).\n    assumption.\nQed.\n\nLemma replace_locals_extern: forall mu pubSrc' pubTgt',\n      extern_of (replace_locals mu pubSrc' pubTgt') = extern_of mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_local: forall mu pubSrc' pubTgt',\n      local_of (replace_locals mu pubSrc' pubTgt') = local_of mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_unknown: forall mu pubSrc' pubTgt',\n      unknown_of (replace_locals mu pubSrc' pubTgt') = unknown_of mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_foreign: forall mu pubSrc' pubTgt',\n      foreign_of (replace_locals mu pubSrc' pubTgt') = foreign_of mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_pub: forall mu pubSrc' pubTgt',\n      pub_of (replace_locals mu pubSrc' pubTgt') =\n          (fun b => if pubSrc' b then local_of mu b else None).\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_pub': forall mu pubSrc' pubTgt'\n      (P: forall b, pubBlocksSrc mu b = true -> pubSrc' b = true)\n      b (B: pubBlocksSrc mu b = true),\n      pub_of (replace_locals mu pubSrc' pubTgt') b = pub_of mu b.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nrewrite B, (P _ B). trivial.\nQed.\n\nLemma replace_locals_as_inj: forall mu pubSrc' pubTgt',\n      as_inj (replace_locals mu pubSrc' pubTgt') = as_inj mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_shared: forall mu pubSrc' pubTgt',\n      shared_of (replace_locals mu pubSrc' pubTgt') =\n      join (foreign_of mu) (fun b => if pubSrc' b then local_of mu b else None).\nProof. intros. unfold shared_of, join; simpl.\nrewrite replace_locals_foreign.\nrewrite replace_locals_pub.\ntrivial.\nQed.\n\nLemma replace_locals_DOM: forall mu pubSrc' pubTgt',\n      DOM (replace_locals mu pubSrc' pubTgt') = DOM mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_RNG: forall mu pubSrc' pubTgt',\n      RNG (replace_locals mu pubSrc' pubTgt') = RNG mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_DomSrc: forall mu pubSrc' pubTgt',\n      DomSrc (replace_locals mu pubSrc' pubTgt') = DomSrc mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_DomTgt: forall mu pubSrc' pubTgt',\n      DomTgt (replace_locals mu pubSrc' pubTgt') = DomTgt mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_locBlocksSrc: forall mu pubSrc' pubTgt',\n      locBlocksSrc (replace_locals mu pubSrc' pubTgt') = locBlocksSrc mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_extBlocksTgt: forall mu pubSrc' pubTgt',\n      extBlocksTgt (replace_locals mu pubSrc' pubTgt') = extBlocksTgt mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_extBlocksSrc: forall mu pubSrc' pubTgt',\n      extBlocksSrc (replace_locals mu pubSrc' pubTgt') = extBlocksSrc mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_locBlocksTgt: forall mu pubSrc' pubTgt',\n      locBlocksTgt (replace_locals mu pubSrc' pubTgt') = locBlocksTgt mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_frgnBlocksSrc: forall mu pubSrc' pubTgt',\n      frgnBlocksSrc (replace_locals mu pubSrc' pubTgt') = frgnBlocksSrc mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_frgnBlocksTgt: forall mu pubSrc' pubTgt',\n      frgnBlocksTgt (replace_locals mu pubSrc' pubTgt') = frgnBlocksTgt mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_pubBlocksSrc: forall mu pubSrc' pubTgt',\n      pubBlocksSrc (replace_locals mu pubSrc' pubTgt') = pubSrc'.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_pubBlocksTgt: forall mu pubSrc' pubTgt',\n      pubBlocksTgt (replace_locals mu pubSrc' pubTgt') = pubTgt'.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_locals_sharedTgt:\n  forall (mu : SM_Injection) (pubSrc' pubTgt' : block -> bool),\n  sharedTgt (replace_locals mu pubSrc' pubTgt') =\n  (fun b : block => frgnBlocksTgt mu b || pubTgt' b).\nProof. intros. unfold sharedTgt. extensionality b.\n  rewrite replace_locals_frgnBlocksTgt, replace_locals_pubBlocksTgt.\n  trivial.\nQed.\n\nLemma replace_locals_visTgt:\n  forall (mu : SM_Injection) (pubSrc' pubTgt' : block -> bool),\n  visTgt (replace_locals mu pubSrc' pubTgt') = visTgt mu.\nProof. intros. unfold visTgt. extensionality b.\n  rewrite replace_locals_frgnBlocksTgt, replace_locals_locBlocksTgt.\n  trivial.\nQed.\n\nDefinition replace_externs (mu:SM_Injection) fSrc' fTgt': SM_Injection :=\n  match mu with\n    Build_SM_Injection locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern =>\n    Build_SM_Injection locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc' fTgt' extern\n  end.\n(*typically, we have forall b, fSrc b -> fSrc' b and forall b, fTgt b -> fTgt' b,\n  i.e. only reclassify unknown entries as foreign*)\n\nLemma replace_externs_wd: forall mu (WD: SM_wd mu) fSrc' fTgt'\n         (SRC: forall b1, fSrc' b1 = true ->\n               exists b2 d, extern_of mu b1 = Some(b2,d) /\\ fTgt' b2=true)\n         (TGT: forall b, fTgt' b = true -> extBlocksTgt mu b = true),\n      SM_wd (replace_externs mu fSrc' fTgt').\nProof. intros.\n  destruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\n  constructor; simpl; try apply WD.\n    intros. apply (SRC _ H).\n    assumption.\nQed.\n\nLemma replace_externs_extern: forall mu frgSrc' frgTgt',\n      extern_of (replace_externs mu frgSrc' frgTgt') = extern_of mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_foreign: forall mu frgSrc' frgTgt',\n      foreign_of (replace_externs mu frgSrc' frgTgt') =\n      fun b : block => if frgSrc' b then extern_of mu b else None.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_local: forall mu frgSrc' frgTgt',\n      local_of (replace_externs mu frgSrc' frgTgt') = local_of mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_priv: forall mu frgSrc' frgTgt',\n      priv_of (replace_externs mu frgSrc' frgTgt') = priv_of mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_pub: forall mu frgSrc' frgTgt',\n      pub_of (replace_externs mu frgSrc' frgTgt') = pub_of mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_as_inj: forall mu frgSrc' frgTgt',\n      as_inj (replace_externs mu frgSrc' frgTgt') = as_inj mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_DOM: forall mu frgSrc' frgTgt',\n      DOM (replace_externs mu frgSrc' frgTgt') = DOM mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_RNG: forall mu frgSrc' frgTgt',\n      RNG (replace_externs mu frgSrc' frgTgt') = RNG mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_DomSrc: forall mu frgSrc' frgTgt',\n      DomSrc (replace_externs mu frgSrc' frgTgt') = DomSrc mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_DomTgt: forall mu frgSrc' frgTgt',\n      DomTgt (replace_externs mu frgSrc' frgTgt') = DomTgt mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_locBlocksSrc: forall mu frgSrc' frgTgt',\n      locBlocksSrc (replace_externs mu frgSrc' frgTgt') = locBlocksSrc mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_locBlocksTgt: forall mu frgSrc' frgTgt',\n      locBlocksTgt (replace_externs mu frgSrc' frgTgt') = locBlocksTgt mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_extBlocksSrc: forall mu frgSrc' frgTgt',\n      extBlocksSrc (replace_externs mu frgSrc' frgTgt') = extBlocksSrc mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_extBlocksTgt: forall mu frgSrc' frgTgt',\n      extBlocksTgt (replace_externs mu frgSrc' frgTgt') = extBlocksTgt mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_frgnBlocksSrc: forall mu fSrc' fTgt',\n      frgnBlocksSrc (replace_externs mu fSrc' fTgt') = fSrc'.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_frgnBlocksTgt: forall mu fSrc' fTgt',\n      frgnBlocksTgt (replace_externs mu fSrc' fTgt') = fTgt'.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_pubBlocksSrc: forall mu frgSrc' frgTgt',\n      pubBlocksSrc (replace_externs mu frgSrc' frgTgt') = pubBlocksSrc mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\nLemma replace_externs_pubBlocksTgt: forall mu frgSrc' frgTgt',\n      pubBlocksTgt (replace_externs mu frgSrc' frgTgt') = pubBlocksTgt mu.\nProof. intros.\ndestruct mu as [locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern]; simpl in *.\nreflexivity.\nQed.\n\n\nLemma replace_locals_sharedSrc mu pubSrc' pubTgt': forall\n      (HPUB1: forall b,  pubSrc' b = true -> local_of mu b <> None)\n      (HPUB2: forall b,  pubBlocksSrc mu b = true -> pubSrc' b = true),\n      sharedSrc (replace_locals mu pubSrc' pubTgt') =\n      fun b => pubSrc' b || sharedSrc mu b.\nProof. intros. unfold sharedSrc. rewrite replace_locals_shared.\nextensionality b. unfold  shared_of, join.\nremember (foreign_of mu b) as d.\ndestruct d; simpl; trivial.\n  destruct p. intuition auto with bool.\nremember (pubSrc' b) as q. symmetry in Heqq.\ndestruct q; simpl. apply HPUB1 in Heqq.\n  destruct (local_of mu b); trivial. congruence.\nunfold pub_of. destruct mu; simpl in *.\nspecialize (HPUB2 b).\ndestruct (pubBlocksSrc b); trivial. rewrite Heqq in HPUB2. intuition congruence.\nQed.\n\nDefinition getBlocks (V:list val) (b: block): bool :=\n   in_dec eq_block b\n    (fold_right (fun v L => match v with Vptr b' z => b'::L | _ => L end) nil V).\n\nLemma getBlocksD: forall v V b,\n  getBlocks (v:: V) b =\n    match v with\n      Vptr b' _  => orb (eq_block b' b) (getBlocks V b)\n    | _ => getBlocks V b\n   end.\nProof. intros.\n  destruct v; simpl; try reflexivity.\n  unfold getBlocks. simpl.\n  destruct (eq_block b0 b); simpl. trivial.\n  destruct (in_dec eq_block b\n    (fold_right\n       (fun (v : val) (L : list block) =>\n        match v with\n        | Vundef => L\n        | Vint _ => L\n        | Vlong _ => L\n        | Vfloat _ => L\n        | Vsingle _ => L\n        | Vptr b' _ => b' :: L\n        end) nil V)). trivial. trivial.\nQed.\n\nLemma getBlocksD_nil: forall b,\n  getBlocks nil b = false.\nProof. intros.\n  reflexivity.\nQed.\n\nLemma getBlocks_char: forall V b, getBlocks V b = true <->\n   exists off, In (Vptr b off) V.\nProof.\n  intros V. induction V; simpl; intros.\n     unfold getBlocks; simpl. split; intros. inv H. destruct H. contradiction.\n  rewrite getBlocksD.\n  destruct a; simpl in *; destruct (IHV b); clear IHV.\n      split; intros. destruct (H H1). exists x; right; trivial.\n         apply H0. destruct H1 as [n [X | X]]. inv X. exists n; trivial.\n      split; intros. destruct (H H1). exists x; right; trivial.\n         apply H0. destruct H1 as [n [X | X]]. inv X. exists n; trivial.\n      split; intros. destruct (H H1). exists x; right; trivial.\n         apply H0. destruct H1 as [n [X | X]]. inv X. exists n; trivial.\n      split; intros. destruct (H H1). exists x; right; trivial.\n         apply H0. destruct H1 as [n [X | X]]. inv X. exists n; trivial.\n      split; intros. destruct (H H1). exists x; right; trivial.\n         apply H0. destruct H1 as [n [X | X]]. inv X. exists n; trivial.\n      split; intros.\n         apply orb_true_iff in H1.\n           destruct H1. exists i; left. clear H H0.\n             destruct (eq_block b0 b); subst. trivial. inv H1.\n           destruct (H H1). exists x; right; trivial.\n         apply orb_true_iff. destruct H1 as [n [X | X]].\n            left. inv X. destruct (eq_block b b); subst. trivial. exfalso. apply n0; trivial.\n            right. apply H0. exists n; trivial.\nQed.\n\nLemma getBlocks_inject: forall j vals1 vals2\n                       (ValInjMu : Forall2 (val_inject j) vals1 vals2)\n                       b (B: getBlocks vals1 b = true),\n      exists jb d, j b = Some (jb, d) /\\ getBlocks vals2 jb = true.\nProof. intros. apply getBlocks_char in B. destruct B as [off INN].\n   destruct (forall2_val_inject_D _ _ _ ValInjMu _ INN) as [v2 [ValInj INN2]].\n   inv ValInj.\n   exists b2, delta. split; trivial.\n   apply getBlocks_char. eexists. apply INN2.\nQed.\n\nDefinition REACH_closed m (X: Values.block -> bool) : Prop :=\n  (forall b, REACH m X b = true -> X b = true).\n\nDefinition mapped (j:meminj) b : bool :=\n  match j b with None => false | Some _ => true end.\n\nLemma mappedD_true : forall j b (M: mapped j b = true),\n                     exists p, j b = Some p.\nProof. intros.\n  unfold mapped in M.\n  remember (j b) as d. destruct d; inv M. exists p; trivial.\nQed.\nLemma mappedD_false : forall j b (M: mapped j b = false),\n                      j b = None.\nProof. intros.\n  unfold mapped in M.\n  remember (j b) as d. destruct d; inv M. trivial.\nQed.\nLemma mappedI_true : forall j b p (J: j b = Some p),\n                      mapped j b = true.\nProof. intros.\n  unfold mapped; rewrite J; trivial.\nQed.\nLemma mappedI_false : forall j b (J:j b = None),\n                       mapped j b = false.\nProof. intros.\n  unfold mapped; rewrite J; trivial.\nQed.\nLemma mapped_charT: forall j b, (mapped j b = true) <-> (exists p, j b = Some p).\nProof. intros.\n  split; intros.\n    apply mappedD_true; assumption.\n  destruct H. eapply mappedI_true; eassumption.\nQed.\nLemma mapped_charF: forall j b, (mapped j b = false) <-> (j b = None).\nProof. intros.\n  split; intros.\n    apply mappedD_false; assumption.\n    apply mappedI_false; assumption.\nQed.\n\nLemma inject_mapped: forall j m1 m2 (Inj12: Mem.inject j m1 m2) k\n          (RC: REACH_closed m1 (mapped k))\n          (INC: inject_incr k j),\n      Mem.inject k m1 m2.\nProof. intros.\nsplit; intros.\n  split; intros.\n     eapply Inj12; try eassumption. eapply INC; eassumption.\n     eapply Inj12; try eassumption. eapply INC; eassumption.\n     specialize (Mem.mi_memval _ _ _ (Mem.mi_inj _ _ _ Inj12) b1).\n        rewrite (INC _ _ _ H). intros.\n        specialize (H1 _ _ _ (eq_refl _) H0).\n        inv H1; constructor.\n        inv H4; try constructor.\n        assert (R: REACH m1 (mapped k) b0 = true).\n           apply eq_sym in H2.\n           eapply REACH_cons; try eassumption.\n           apply REACH_nil. eapply mappedI_true; eassumption.\n        specialize (RC _ R).\n          destruct (mappedD_true _ _ RC) as [[bb dd] RR]; clear RC.\n          rewrite (INC _ _ _ RR) in H1; inv H1.\n        econstructor; try eassumption. trivial.\n   remember (k b) as d.\n     destruct d; apply eq_sym in Heqd; trivial.\n     destruct p. apply INC in Heqd.\n     exfalso. apply H. apply (Mem.valid_block_inject_1 _ _ _ _ _ _ Heqd Inj12).\n   apply INC in H. eapply Inj12; eauto.\n   intros b1 b1'; intros.\n     apply INC in H0; apply INC in H1.\n     eapply Inj12; eassumption.\n   apply INC in H.\n     eapply Inj12; eassumption.\n(*perm_inv*)\n  eapply Inj12; eauto.\nQed.\n\nLemma restrict_val_inject: forall j val1 val2\n     (Inj : val_inject j val1 val2)\n     X (HR: forall b, getBlocks (val1::nil) b = true -> X b = true),\n   val_inject (restrict j X) val1 val2.\nProof. intros.\n  inv Inj; try constructor.\n      econstructor; trivial.\n        eapply restrictI_Some; try eassumption.\n         apply HR; simpl. rewrite getBlocksD.\n         remember (eq_block b1 b1) .\n         destruct s. trivial. exfalso. apply n; trivial.\nQed.\n\nLemma restrict_forall_vals_inject: forall j vals1 vals2\n     (Inj : Forall2 (val_inject j) vals1 vals2)\n     X (HR: forall b, getBlocks vals1 b = true -> X b = true),\n Forall2 (val_inject (restrict j X)) vals1 vals2.\nProof. intros.\n  induction Inj. constructor.\n  constructor.\n    apply restrict_val_inject. assumption.\n       intros. apply HR.\n         rewrite getBlocksD in H0.\n         rewrite getBlocksD_nil in H0.\n         rewrite getBlocksD.\n         destruct x; try congruence.\n         apply orb_true_iff in H0. destruct H0; intuition auto with bool.\n   apply IHInj. intros. apply HR.\n      rewrite getBlocksD. rewrite H0.\n      destruct x; trivial. intuition auto with bool.\nQed.\n\nLemma restrict_mapped_closed: forall j m X\n      (RC: REACH_closed m (mapped j))\n      (RX: REACH_closed m X),\n      REACH_closed m (mapped (restrict j X)).\nProof. intros.\n  intros b Hb.\n  apply REACHAX in Hb.\n  destruct Hb as [L HL].\n  generalize dependent b.\n  induction L; simpl; intros; inv HL.\n     assumption.\n  specialize (IHL _ H1); clear H1.\n    destruct (mappedD_true _ _ IHL) as [[bb' dd'] M']; clear IHL.\n    unfold restrict in M'.\n    remember (X b') as d; destruct d; inv M'.\n    assert (Rb: REACH m (mapped j) b = true).\n      eapply REACH_cons; try eassumption.\n      apply REACH_nil. eapply mappedI_true; eassumption.\n    specialize (RC _ Rb).\n      destruct (mappedD_true _ _ RC) as [[bb dd] M]; clear RC.\n    assert (Xb: REACH m X b = true).\n      eapply REACH_cons; try eassumption.\n      apply REACH_nil. rewrite Heqd; trivial.\n    specialize (RX _ Xb).\n    eapply mappedI_true. unfold restrict. rewrite M, RX. reflexivity.\nQed.\n\nLemma restrict_mapped_closed_triv: forall j m X,\n      REACH_closed m (fun b => mapped j b && X b) =\n      REACH_closed m (mapped (restrict j X)).\nProof. intros.\n  assert ((fun b => mapped j b && X b) = (mapped (restrict j X))).\n    extensionality b. unfold mapped, restrict.\n    destruct (j b); simpl; destruct (X b); trivial.\n  rewrite H. trivial.\nQed.\n\nLemma REACH_closed_intersection: forall m X Y\n        (HX: REACH_closed m X) (HY: REACH_closed m Y),\n      REACH_closed m (fun b => X b && Y b).\nProof. intros. intros b Hb.\n  rewrite REACHAX in Hb.\n  destruct Hb as [L HL].\n  generalize dependent b.\n  induction L; simpl; intros; inv HL; trivial.\n  specialize (IHL _ H1); clear H1.\n  apply andb_true_iff in IHL. destruct IHL.\n  apply andb_true_iff.\n  split.\n    apply HX. eapply REACH_cons; try eassumption.\n      apply REACH_nil; eassumption.\n    apply HY. eapply REACH_cons; try eassumption.\n      apply REACH_nil; eassumption.\nQed.\n\nLemma REACH_closed_union: forall m X Y\n        (HX: REACH_closed m X) (HY: REACH_closed m Y),\n      REACH_closed m (fun b => X b || Y b).\nProof. intros. intros b Hb.\n  rewrite REACHAX in Hb.\n  destruct Hb as [L HL].\n  generalize dependent b.\n  induction L; simpl; intros; inv HL; trivial.\n  specialize (IHL _ H1); clear H1.\n  apply orb_true_iff in IHL.\n  apply orb_true_iff.\n  destruct IHL.\n    left.\n    apply HX. eapply REACH_cons; try eassumption.\n      apply REACH_nil; eassumption.\n  right. apply HY. eapply REACH_cons; try eassumption.\n      apply REACH_nil; eassumption.\nQed.\n\nLemma inject_REACH_closed: forall j m1 m2 (Inj: Mem.inject j m1 m2),\n      REACH_closed m1 (mapped j).\nProof. intros. intros b Hb.\n  destruct (REACH_inject _ _ _ Inj (mapped j)  (fun b => true))\n    with (b1:=b) as [b2 [dd [ZZ _]]].\n    intros; simpl.\n      destruct (mappedD_true _ _ H) as [[bb d] J]; clear H.\n      exists bb, d; split; trivial.\n    assumption.\n  eapply mappedI_true; eassumption.\nQed.\n\nLemma inject_restrict: forall j m1 m2 X\n        (INJ : Mem.inject j m1 m2)\n        (RC : REACH_closed m1 X),\n      Mem.inject (restrict j X) m1 m2.\nProof. intros.\n  eapply inject_mapped; try eassumption.\n    eapply restrict_mapped_closed; try eassumption.\n    eapply inject_REACH_closed; try eassumption.\n  apply restrict_incr.\nQed.\n\n(*The blocks explicitly exported via call arguments, plus the already shared blocks*)\nDefinition exportedSrc mu vals b := orb (getBlocks vals b) (sharedSrc mu b).\nDefinition exportedTgt mu vals b := orb (getBlocks vals b) (sharedTgt mu b).\n\nLemma exported_inject: forall mu (WD: SM_wd mu) vals1 vals2\n          (ValInjMu : Forall2 (val_inject (as_inj mu)) vals1 vals2) b\n          (SRC: exportedSrc mu vals1 b = true ),\n        exists jb d, as_inj mu b = Some (jb, d)\n                  /\\ exportedTgt mu vals2 jb = true.\nProof. intros. unfold exportedSrc in SRC. unfold exportedTgt.\n  apply orb_true_iff in SRC.\n  destruct SRC as [SRC | SRC].\n   destruct (getBlocks_inject _ _ _ ValInjMu _ SRC) as [b2 [d [J G]]].\n   exists b2, d. rewrite J, G. intuition.\n  destruct (shared_SrcTgt _ WD _ SRC) as [b2 [d [J G]]].\n   exists b2, d. rewrite (shared_in_all _ WD _ _ _ J).\n      rewrite G. intuition auto with bool.\nQed.\n\nLemma val_inject_sub_on j k: forall v1 v2\n        (V:  val_inject j v1 v2)\n        (HK: forall b, getBlocks (v1::nil) b = true -> j b = k b),\n      val_inject k v1 v2.\nProof. intros.\n  inv V; eauto.\n    econstructor; trivial. rewrite <- HK; trivial.\n    rewrite getBlocks_char. eexists; left. reflexivity.\nQed.\n\nLemma val_inject_sub_on' j k: forall v1 v2\n        (V:  val_inject j v1 v2)\n        (HK: forall b b2 d, getBlocks (v1::nil) b = true ->\n              j b = Some(b2,d) -> k b = Some(b2,d)),\n      val_inject k v1 v2.\nProof. intros.\n  inv V; eauto.\n    econstructor; trivial. eapply HK; trivial.\n    rewrite getBlocks_char. eexists; left. reflexivity.\nQed.\n\nLemma val_list_inject_sub_on j k: forall vals1 vals2\n        (V:  Val.inject_list j vals1 vals2)\n        (HK: forall b, getBlocks vals1 b = true -> j b = k b),\n      Val.inject_list k vals1 vals2.\nProof. intros.\n  induction V; try econstructor.\n  clear IHV. eapply val_inject_sub_on; try eassumption.\n    intros. eapply HK.\n    rewrite getBlocks_char. rewrite getBlocks_char in H0.\n    destruct H0. destruct H0. eexists; left. eassumption.\n     inv H0.\n apply IHV. intros. apply HK.\n    rewrite getBlocks_char. rewrite getBlocks_char in H0.\n    destruct H0. eexists; right. eassumption.\nQed.\nLemma val_list_inject_sub_on' j k: forall vals1 vals2\n        (V:  Val.inject_list j vals1 vals2)\n        (HK: forall b b2 d, getBlocks vals1 b = true ->\n              j b = Some(b2,d) -> k b = Some(b2,d)),\n      Val.inject_list k vals1 vals2.\nProof. intros.\n  induction V; try econstructor.\n  clear IHV. eapply val_inject_sub_on'; try eassumption.\n    intros. eapply HK; trivial.\n    rewrite getBlocks_char. rewrite getBlocks_char in H0.\n    destruct H0. destruct H0. eexists; left. eassumption.\n     inv H0.\n  apply IHV; clear IHV.\n    intros. apply HK; trivial.\n    rewrite getBlocks_char. rewrite getBlocks_char in H0.\n    destruct H0. eexists; right. eassumption.\nQed.\n\nLemma REACH_shared_of: forall mu (WD: SM_wd mu) m1 m2 vals1 vals2\n        (MemInjMu : Mem.inject (shared_of mu) m1 m2)\n        (ValInjMu : Forall2 (val_inject (shared_of mu)) vals1 vals2) b1\n        (R : REACH m1 (exportedSrc mu vals1) b1 = true)\n        B (HB: forall b b2 d, shared_of mu b = Some(b2,d) -> B b2 = true),\n      exists b2 d, shared_of mu b1 = Some (b2, d) /\\\n                   REACH m2 (fun b => orb (getBlocks vals2 b) (B b)) b2 = true.\nProof. intros.\n eapply (REACH_inject _ _ _ MemInjMu); try eassumption.\n clear R. simpl; intros.\n apply orb_true_iff in H.\n destruct H.\n   destruct (getBlocks_inject _ _ _ ValInjMu _ H) as [b2 [d [J G]]].\n   exists b2, d. rewrite J, G. intuition.\n apply sharedSrc_iff in H. destruct H as [jb [delta SH]].\n   specialize (HB _ _ _ SH).\n   exists jb, delta.\n   intuition auto with bool.\nQed.\n\nLemma REACH_as_inj: forall mu (WD: SM_wd mu) m1 m2 vals1 vals2\n        (MemInjMu : Mem.inject (as_inj mu) m1 m2)\n        (ValInjMu : Forall2 (val_inject (as_inj mu)) vals1 vals2) b1\n        (R : REACH m1 (exportedSrc mu vals1) b1 = true)\n        B (HB: forall b b2 d, shared_of mu b = Some(b2,d) -> B b2 = true),\n      exists b2 d, as_inj mu b1 = Some (b2, d) /\\\n                   REACH m2 (fun b => orb (getBlocks vals2 b) (B b)) b2 = true.\nProof. intros.\n eapply (REACH_inject _ _ _ MemInjMu); try eassumption.\n clear R. simpl; intros.\n apply orb_true_iff in H.\n destruct H.\n   destruct (getBlocks_inject _ _ _ ValInjMu _ H) as [b2 [d [J G]]].\n   exists b2, d. rewrite J, G. intuition.\n apply sharedSrc_iff in H. destruct H as [jb [delta SH]].\n   specialize (HB _ _ _ SH).\n   apply shared_in_all in SH; trivial.\n   exists jb, delta.\n   intuition auto with bool.\nQed.\n\nLemma REACH_local: forall mu (WD: SM_wd mu) m1 m2 vals1 vals2\n        (MemInjMu : Mem.inject (as_inj mu) m1 m2)\n        (ValInjMu : Forall2 (val_inject (as_inj mu)) vals1 vals2) b1\n        (R : REACH m1 (exportedSrc mu vals1) b1 = true)\n         (locBSrc : locBlocksSrc mu b1 = true),\n      exists b2 d, local_of mu b1 = Some (b2, d).\nProof. intros.\n  destruct (REACH_as_inj _ WD _ _ _ _ MemInjMu ValInjMu\n            _ R (fun b => true)) as [b2 [d [ASINJ RR]]].\n    trivial.\n  exists b2, d.\n  assert (noExt:= locBlocksSrc_externNone _ WD _ locBSrc).\n  destruct (joinD_Some _ _ _ _ _ ASINJ). congruence.\n  apply H.\nQed.\n\nLemma REACH_extern: forall mu (WD: SM_wd mu) m1 m2 vals1 vals2\n        (MemInjMu : Mem.inject (as_inj mu) m1 m2)\n        (ValInjMu : Forall2 (val_inject (as_inj mu)) vals1 vals2) b1\n        (R : REACH m1 (exportedSrc mu vals1) b1 = true)\n         (locBSrc : locBlocksSrc mu b1 = false),\n      exists b2 d, extern_of mu b1 = Some (b2, d).\nProof. intros.\n  destruct (REACH_as_inj _ WD _ _ _ _ MemInjMu ValInjMu\n            _ R (fun b => true)) as [b2 [d [ASINJ RR]]].\n    trivial.\n  exists b2, d.\n  destruct (joinD_Some _ _ _ _ _ ASINJ). assumption.\n  destruct H.\n  destruct (local_DomRng _ WD _ _ _ H0) as [ZZ _]; rewrite ZZ in locBSrc.\n  discriminate.\nQed.\n\n(*The following six or so results are key lemmas about REACH - they say\n  that blocks exported in SRC are injected, to blocks exported by TGT,\n  preserving the locBlocks-structure, ie distinction betwene public and\n  foreign*)\nLemma REACH_as_inj_REACH: forall mu (WD: SM_wd mu) m1 m2 vals1 vals2\n        (MemInjMu : Mem.inject (as_inj mu) m1 m2)\n        (ValInjMu : Forall2 (val_inject (as_inj mu)) vals1 vals2) b1\n        (R : REACH m1 (exportedSrc mu vals1) b1 = true),\n      exists b2 d, as_inj mu b1 = Some (b2, d) /\\\n                   REACH m2 (exportedTgt mu vals2) b2 = true.\nProof. intros.\n  destruct (REACH_as_inj _ WD _ _ _ _ MemInjMu ValInjMu _ R (fun b => true))\n       as [b2 [d [ASI _]]]. trivial.\n  exists b2, d. split; trivial.\n  destruct (REACH_inject _ _ _ MemInjMu _ _\n      (exported_inject _ WD _ _ ValInjMu) _ R)\n   as [bb2 [dd [ASI' RR]]].\n  rewrite ASI' in ASI. inv ASI.\n  assumption.\nQed.\n\nLemma REACH_local_REACH: forall mu (WD: SM_wd mu) m1 m2 vals1 vals2\n        (MemInjMu : Mem.inject (as_inj mu) m1 m2)\n        (ValInjMu : Forall2 (val_inject (as_inj mu)) vals1 vals2) b1\n        (R : REACH m1 (exportedSrc mu vals1) b1 = true)\n         (locBSrc : locBlocksSrc mu b1 = true),\n      exists b2 d, local_of mu b1 = Some (b2, d) /\\\n                   REACH m2 (exportedTgt mu vals2) b2 = true.\nProof. intros.\n  destruct (REACH_as_inj_REACH _ WD _ _ _ _ MemInjMu ValInjMu\n            _ R) as [b2 [d [ASINJ RR]]].\n  exists b2, d. split; trivial.\n  assert (noExt:= locBlocksSrc_externNone _ WD _ locBSrc).\n  destruct (joinD_Some _ _ _ _ _ ASINJ). congruence.\n  apply H.\nQed.\n\nLemma REACH_local_REACH': forall mu m1 vals1  b1\n        (R : REACH m1 (exportedSrc mu vals1) b1 = true)\n        (WD: SM_wd mu) m2 vals2\n        (MemInjMu : Mem.inject (as_inj mu) m1 m2)\n        (ValInjMu : Forall2 (val_inject (as_inj mu)) vals1 vals2)\n        (locBSrc : locBlocksSrc mu b1 = true) b2 d\n        (LOC: local_of mu b1 = Some (b2, d)),\n     REACH m2 (exportedTgt mu vals2) b2 = true.\nProof. intros.\n  destruct (REACH_local_REACH _ WD _ _ _ _ MemInjMu ValInjMu _ R locBSrc)\n  as [bb [dd [LL RR]]]. rewrite LL in LOC. inv LOC. trivial.\nQed.\n\nLemma REACH_extern_REACH: forall mu (WD: SM_wd mu) m1 m2 vals1 vals2\n        (MemInjMu : Mem.inject (as_inj mu) m1 m2)\n        (ValInjMu : Forall2 (val_inject (as_inj mu)) vals1 vals2) b1\n        (R : REACH m1 (exportedSrc mu vals1) b1 = true)\n         (locBSrc : locBlocksSrc mu b1 = false),\n      exists b2 d, extern_of mu b1 = Some (b2, d) /\\\n                   REACH m2 (exportedTgt mu vals2) b2 = true.\nProof. intros.\n  destruct (REACH_as_inj_REACH _ WD _ _ _ _ MemInjMu ValInjMu\n            _ R) as [b2 [d [ASINJ RR]]].\n  exists b2, d. split; trivial.\n  destruct (joinD_Some _ _ _ _ _ ASINJ).\n    apply H.\n  destruct H as [_ H].\n    destruct (local_DomRng _ WD _ _ _ H) as [ZZ _]; rewrite ZZ in locBSrc.\n    discriminate.\nQed.\n\nLemma pubBlocksSrc_REACH: forall m1 mu (WD: SM_wd mu) vals b, pubBlocksSrc mu b = true ->\n           REACH m1 (exportedSrc mu vals) b = true.\nProof. intros. apply REACH_nil.\n  apply orb_true_iff. right. apply pubSrc_shared; trivial.\nQed.\n\nLemma getBlocks_REACH_exportedSrc m mu vals b: forall\n         (GB: getBlocks vals b = true),\n      REACH m (exportedSrc mu vals) b = true.\nProof. intros. eapply REACH_nil.\n unfold exportedSrc. rewrite GB; trivial.\nQed.\n\nDefinition local_out_of_reach mu (m : mem) (b : block) (ofs : Z): Prop :=\n  locBlocksTgt mu b = true /\\\n  forall b0 delta, local_of mu b0 = Some (b, delta) ->\n                  (~ Mem.perm m b0 (ofs - delta) Max Nonempty \\/\n                   pubBlocksSrc mu b0 = false).\n\nLemma genvs_domain_eq_match_genvsB: forall {F1 V1 F2 V2:Type}\n  (ge1: Genv.t F1 V1) (ge2: Genv.t F2 V2),\n  genvs_domain_eq ge1 ge2 -> genv2blocksBool ge1 = genv2blocksBool ge2.\nProof. intros F1 V1 F2 V2 ge1 ge2.\n  unfold genvs_domain_eq, genv2blocksBool. simpl; intros.\n  destruct H.\n  f_equal; extensionality b.\n    destruct (H b); clear H.\n    remember (Genv.invert_symbol ge1 b) as d.\n      destruct d; apply eq_sym in Heqd.\n      apply Genv.invert_find_symbol in Heqd.\n        destruct H1. eexists; eassumption.\n        apply Genv.find_invert_symbol in H.\n        rewrite H. trivial.\n    remember (Genv.invert_symbol ge2 b) as q.\n     destruct q; trivial; apply eq_sym in Heqq.\n      apply Genv.invert_find_symbol in Heqq.\n        destruct H2. eexists; eassumption.\n        apply Genv.find_invert_symbol in H.\n        rewrite H in Heqd. discriminate.\n   destruct H0 as [H0 X].\n   destruct (H0 b); clear H0.\n     remember (Genv.find_var_info ge1 b) as d.\n       destruct d; apply eq_sym in Heqd.\n         destruct H1. eexists; reflexivity.\n         rewrite H0. trivial.\n       remember (Genv.find_var_info ge2 b) as q.\n         destruct q; apply eq_sym in Heqq; trivial.\n           destruct H2. eexists; reflexivity.\n           discriminate.\nQed.\n\nLemma genv2blocksBool_char1: forall F V (ge : Genv.t F V) b,\n     (fst (genv2blocksBool ge)) b = true <-> fst (genv2blocks ge) b.\nProof. intros.\n  remember (genv2blocksBool ge) as X.\n  destruct X as [f g]; simpl.\n  remember (genv2blocks ge) as Y.\n  destruct Y as [f' g']; simpl.\n  unfold genv2blocksBool in HeqX. inv HeqX.\n  unfold genv2blocks in HeqY. inv HeqY.\n  remember (Genv.invert_symbol ge b) as d.\n  destruct d; apply eq_sym in Heqd.\n    split; intros; trivial.\n    exists i. rewrite (Genv.invert_find_symbol _ _ Heqd). trivial.\n  split; intros; try congruence.\n    destruct H.\n    apply Genv.find_invert_symbol in H. congruence.\nQed.\n\nLemma genv2blocksBool_char2: forall F V (ge : Genv.t F V) b,\n     (snd (genv2blocksBool ge)) b = true <-> snd (genv2blocks ge) b.\nProof. intros.\n  remember (genv2blocksBool ge) as X.\n  destruct X as [f g]; simpl.\n  remember (genv2blocks ge) as Y.\n  destruct Y as [f' g']; simpl.\n  unfold genv2blocksBool in HeqX. inv HeqX.\n  unfold genv2blocks in HeqY. inv HeqY.\n  remember (Genv.find_var_info ge b) as d.\n  destruct d; apply eq_sym in Heqd.\n    split; intros; trivial.\n    exists g; trivial.\n  split; intros; try congruence.\n    destruct H. congruence.\nQed.\n\nLemma genv2blocksBool_char1': forall F V (ge : Genv.t F V) b,\n     (fst (genv2blocksBool ge)) b = false <-> ~ fst (genv2blocks ge) b.\nProof. intros.\n  split; intros.\n    intros N. apply genv2blocksBool_char1 in N. congruence.\n  remember (fst (genv2blocksBool ge) b) as d.\n  destruct d; trivial. apply eq_sym in Heqd.\n    apply genv2blocksBool_char1 in Heqd. congruence.\nQed.\n\nLemma genv2blocksBool_char2': forall F V (ge : Genv.t F V) b,\n     (snd (genv2blocksBool ge)) b = false <-> ~ snd (genv2blocks ge) b.\nProof. intros.\n  split; intros.\n    intros N. apply genv2blocksBool_char2 in N. congruence.\n  remember (snd (genv2blocksBool ge) b) as d.\n  destruct d; trivial. apply eq_sym in Heqd.\n    apply genv2blocksBool_char2 in Heqd. congruence.\nQed.\n\nLemma restrict_preserves_globals: forall {F V} (ge:Genv.t F V) j X\n  (PG : meminj_preserves_globals ge j)\n  (Glob : forall b, isGlobalBlock ge b = true -> X b = true),\nmeminj_preserves_globals ge (restrict j X).\nProof. intros.\n  apply meminj_preserves_genv2blocks in PG.\n  destruct PG as [PGa [PGb PGc]].\n  apply meminj_preserves_genv2blocks.\n  split; intros.\n    specialize (PGa _ H).\n    apply restrictI_Some. assumption.\n    apply Glob.\n    unfold isGlobalBlock.\n      apply genv2blocksBool_char1 in H. rewrite H. intuition.\n  split; intros.\n    specialize (PGb _ H).\n    apply restrictI_Some. assumption.\n    apply Glob.\n    unfold isGlobalBlock.\n      apply genv2blocksBool_char2 in H. rewrite H. intuition auto with bool.\n  destruct (restrictD_Some _ _ _ _ _ H0) as [AU XX]; clear H0.\n     apply (PGc _ _ _ H AU).\nQed.\n\nLemma genvs_domain_eq_isGlobal: forall {F1 V1 F2 V2} ge1 ge2\n                       (DomainEQ: @genvs_domain_eq F1 V1 F2 V2 ge1 ge2),\n       isGlobalBlock ge1 = isGlobalBlock ge2.\nProof. intros.\n  destruct DomainEQ.\n  extensionality b. unfold isGlobalBlock.\n  remember (fst (genv2blocksBool ge1) b) as d.\n  destruct d; apply eq_sym in Heqd.\n    apply genv2blocksBool_char1 in Heqd.\n    apply H in Heqd.\n    apply genv2blocksBool_char1 in Heqd.\n    rewrite Heqd. trivial.\n  apply genv2blocksBool_char1' in Heqd.\n    remember (fst (genv2blocksBool ge2) b) as q.\n    destruct q; apply eq_sym in Heqq.\n      apply genv2blocksBool_char1 in Heqq.\n      apply H in Heqq. contradiction.\n  clear Heqd Heqq.\n  remember (snd (genv2blocksBool ge1) b) as d.\n  destruct d; apply eq_sym in Heqd.\n    apply genv2blocksBool_char2 in Heqd.\n    apply H0 in Heqd.\n    apply genv2blocksBool_char2 in Heqd.\n    rewrite Heqd. trivial.\n  apply genv2blocksBool_char2' in Heqd.\n    remember (snd (genv2blocksBool ge2) b) as q.\n    destruct q; apply eq_sym in Heqq.\n      apply genv2blocksBool_char2 in Heqq.\n      apply H0 in Heqq. contradiction.\n   trivial.\nQed.\n\nLemma meminj_preserves_globals_isGlobalBlock: forall {F V} (g: Genv.t F V)\n               j (PG: meminj_preserves_globals g j)\n               b (GB: isGlobalBlock g b = true),\n      j b = Some (b, 0).\nProof. intros.\n  unfold isGlobalBlock in GB.\n  apply meminj_preserves_genv2blocks in PG.\n  destruct PG as [PGa [PGb PGc]].\n  apply orb_true_iff in GB.\n  destruct GB.\n    apply genv2blocksBool_char1 in H. apply (PGa _ H).\n    apply genv2blocksBool_char2 in H. apply (PGb _ H).\nQed.\n\nLemma meminj_preserves_globals_initSM: forall {F1 V1} (ge: Genv.t F1 V1) j\n                  (PG : meminj_preserves_globals ge j) DomS DomT X Y,\n      meminj_preserves_globals ge (extern_of (initial_SM DomS DomT X Y j)).\nProof. intros. apply PG. Qed.\n\nLemma meminj_preserves_globals_init_REACH_frgn:\n      forall {F1 V1} (ge: Genv.t F1 V1) j\n             (PG : meminj_preserves_globals ge j) DomS DomT m R Y\n             (HR: forall b, isGlobalBlock ge b = true -> R b = true),\n      (forall b, isGlobalBlock ge b = true ->\n                 frgnBlocksSrc (initial_SM DomS DomT (REACH m R) Y j) b = true).\nProof. intros.\n  unfold initial_SM; simpl.\n  apply REACH_nil. apply (HR _ H).\nQed.\n\nLemma REACH_is_closed: forall R m1,\n  REACH_closed m1 (fun b : block => REACH m1 R b).\nProof. intros. unfold REACH_closed. intros.\n  apply REACHAX. apply REACHAX in H. destruct H as [L HL].\n  generalize dependent b.\n  induction L; intros; simpl in *; inv HL.\n     apply REACHAX in H. apply H.\n  specialize (IHL _ H1). destruct IHL as [LL HLL].\n    eexists. eapply reach_cons; eassumption.\nQed.\n\n\n(*Generic proof that the inital structured injection satisfies\n  the match_genv, match_wd and match_valid conditions of the LSR*)\nLemma core_initial_wd : forall {F1 V1 F2 V2} (ge1: Genv.t F1 V1) (ge2: Genv.t F2 V2)\n                               vals1 m1 j vals2 m2 DomS DomT\n          (MInj: Mem.inject j m1 m2)\n          (VInj: Forall2 (val_inject j) vals1 vals2)\n          (HypJ: forall b1 b2 d, j b1 = Some (b2, d) -> DomS b1 = true /\\ DomT b2 = true)\n          (R: forall b, REACH m2 (fun b' => isGlobalBlock ge2 b' || getBlocks vals2 b') b = true ->\n                        DomT b = true)\n          (PG: meminj_preserves_globals ge1 j)\n          (GenvsDomEQ: genvs_domain_eq ge1 ge2)\n          (HS: forall b, DomS b = true -> Mem.valid_block m1 b)\n          (HT: forall b, DomT b = true -> Mem.valid_block m2 b)\n          mu (Hmu: mu = initial_SM DomS DomT\n                         (REACH m1 (fun b => isGlobalBlock ge1 b || getBlocks vals1 b))\n                         (REACH m2 (fun b => isGlobalBlock ge2 b || getBlocks vals2 b)) j),\n       (forall b, REACH m1 (fun b' => isGlobalBlock ge1 b' || getBlocks vals1 b') b = true ->\n                  DomS b = true) /\\\n       SM_wd mu /\\ sm_valid mu m1 m2 /\\\n       meminj_preserves_globals ge1 (extern_of mu) /\\\n       (forall b, isGlobalBlock ge1 b = true -> frgnBlocksSrc mu b = true) /\\\n       REACH_closed m1 (vis mu) /\\\n       REACH_closed m1 (mapped (as_inj mu)).\nProof. intros.\n  specialize (getBlocks_inject _ _ _ VInj); intros.\n  assert (HR: forall b1, REACH m1 (fun b : block => isGlobalBlock ge1 b || getBlocks vals1 b) b1 = true ->\n            exists b2 z, j b1 = Some (b2, z) /\\\n                         REACH m2 (fun b : block => isGlobalBlock ge2 b || getBlocks vals2 b) b2 = true).\n         eapply (REACH_inject _ _ _ MInj).\n              intros. clear R mu Hmu HS HT.\n              apply orb_true_iff in H0.\n              destruct H0.\n                rewrite (meminj_preserves_globals_isGlobalBlock _ _ PG _ H0).\n                exists b, 0. rewrite <- (genvs_domain_eq_isGlobal _ _ GenvsDomEQ).\n                intuition auto with bool.\n              destruct (H _ H0) as [b2 [d [J GB2]]]. exists b2, d; intuition auto with bool.\n  split. intros.\n         destruct (HR _ H0) as [b2 [d [J R2]]].\n         apply (HypJ _ _ _ J).\n  subst.\n  split. eapply initial_SM_wd; try eassumption.\n           intros. destruct (HR _ H0) as [b2 [d [J R2]]].\n             apply (HypJ _ _ _ J).\n  split. split; intros. apply (HS _ H0). apply (HT _ H0).\n  split. eapply meminj_preserves_globals_initSM; intuition.\n  split. apply meminj_preserves_globals_init_REACH_frgn; try eassumption.\n    intuition auto with bool.\n  split. simpl. apply REACH_is_closed.\n  rewrite initial_SM_as_inj.\n    apply (inject_REACH_closed _ _ _ MInj).\nQed.\n\n(*Proof the match_genv is preserved by callsteps*)\nLemma intern_incr_meminj_preserves_globals:\n      forall {F V} (ge: Genv.t F V) mu\n             (PG: meminj_preserves_globals ge (extern_of mu) /\\\n                  (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true))\n             mu' (Inc: intern_incr mu mu'),\n      meminj_preserves_globals ge (extern_of mu') /\\\n      (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu' b = true).\nProof. intros.\n  assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by apply Inc.\n  rewrite (intern_incr_extern _ _ Inc), FF in PG.\n  assumption.\nQed.\n\nLemma replace_externs_meminj_preserves_globals:\n      forall {F V} (ge: Genv.t F V) nu\n          (PG: meminj_preserves_globals ge (extern_of nu) /\\\n               (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc nu b = true))\n          mu  fSrc fTgt (Hyp: mu = replace_externs nu fSrc fTgt)\n          (FRG: forall b, frgnBlocksSrc nu b = true -> fSrc b = true),\n      meminj_preserves_globals ge (extern_of mu) /\\\n      (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true).\nProof. intros. destruct PG as [PG FF]; subst.\nsplit.\n    rewrite replace_externs_extern.\n    apply PG.\nintros. destruct nu; simpl in *.\n  apply (FRG _ (FF _ H)).\nQed.\n\n(*Proof the match_genv is preserved by callsteps*)\nLemma after_external_meminj_preserves_globals:\n      forall {F V} (ge: Genv.t F V) mu (WDmu : SM_wd mu)\n             (PG: meminj_preserves_globals ge (extern_of mu) /\\\n                 (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true))\n             nu pubSrc' pubTgt' vals1 m1\n             (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                (REACH m1 (exportedSrc mu vals1) b))\n\n\n             (Hnu: nu = replace_locals mu pubSrc' pubTgt')\n             nu' (WDnu' : SM_wd nu') (INC: extern_incr nu nu')\n             m2 (SMV: sm_valid mu m1 m2) (SEP: sm_inject_separated nu nu' m1 m2)\n             frgnSrc' ret1 m1'\n             (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n             frgnTgt' ret2 m2'\n             (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n             mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt'),\n      meminj_preserves_globals ge (extern_of mu') /\\\n     (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu' b = true).\nProof. intros. subst.\ndestruct PG as [PG FF].\nassert (Fincr:= extern_incr_extern _ _ INC).\nrewrite replace_locals_extern in Fincr.\nsplit.\n  rewrite replace_externs_extern.\n  apply meminj_preserves_genv2blocks.\n  apply meminj_preserves_genv2blocks in PG.\n  destruct PG as [PGa [PGb PGc]].\n  split; intros.\n    specialize (PGa _ H). clear PGb PGc.\n    apply (Fincr _ _ _ PGa).\n  split; intros.\n    specialize (PGb _ H). clear PGa PGc.\n    apply (Fincr _ _ _ PGb).\n  remember (extern_of mu b1) as d.\n    destruct d; apply eq_sym in Heqd.\n      destruct p.\n      rewrite (Fincr _ _ _ Heqd) in H0.\n      inv H0. apply (PGc _ _ _ H Heqd).\n    destruct SEP as [SEPa [SEPb SEPc]].\n      rewrite replace_locals_as_inj, replace_locals_DomSrc, replace_locals_DomTgt in *.\n      remember (local_of mu b1) as q.\n      destruct q; apply eq_sym in Heqq.\n        destruct p. destruct INC as [_ [? _]].\n        rewrite replace_locals_local in H1. rewrite H1 in Heqq.\n        destruct (disjoint_extern_local _ WDnu' b1); congruence.\n      assert (as_inj mu b1 = None).\n        apply joinI_None; assumption.\n      destruct (SEPa b1 b2 delta H1 (extern_in_all _ _ _ _ H0)).\n      specialize (PGb _ H).\n         destruct (extern_DomRng' _ WDmu _ _ _ PGb) as [? [? [? [? [? [? [? ?]]]]]]].\n         congruence.\nintros.\n  specialize (FF _ H).\n  rewrite replace_externs_frgnBlocksSrc.\n  assert (F': frgnBlocksSrc nu' b = true).\n    destruct INC as [_ [_ [_ [_ [_ [_ [_ [_ [FRG _]]]]]]]]].\n    rewrite replace_locals_frgnBlocksSrc in FRG. rewrite <- FRG; trivial.\n  assert (L' := frgnBlocksSrc_locBlocksSrc _ WDnu' _ F').\n  unfold DomSrc.\n  rewrite L', (frgnBlocksSrc_extBlocksSrc _ WDnu' _ F'); simpl.\n  apply (frgnSrc_shared _ WDnu') in F'.\n  apply REACH_nil. unfold exportedSrc. intuition auto with bool.\nQed.\n\nLemma restrict_SharedSrc mu: SM_wd mu ->\n  restrict (as_inj mu) (sharedSrc mu) = shared_of mu.\nProof. unfold sharedSrc, restrict. intros.\n  extensionality b.\n  remember (shared_of mu b) as d.\n  destruct d; simpl; trivial.\n  destruct p; apply eq_sym in Heqd.\n  apply shared_in_all in Heqd; trivial.\nQed.\n\nLemma restrict_vis_foreign_local mu: forall (WD: SM_wd mu),\n      restrict (as_inj mu) (vis mu) = join (foreign_of mu) (local_of mu).\nProof. intros.\n  extensionality b.\n  unfold restrict, join, vis.\n  remember (frgnBlocksSrc mu b) as f.\n  destruct f; apply eq_sym in Heqf.\n    rewrite orb_true_r.\n    destruct (frgnSrc _ WD _ Heqf) as [b2 [d [F FT]]].\n    rewrite F. apply foreign_in_all; trivial.\n  rewrite orb_false_r.\n    rewrite (frgnBlocksSrc_false_foreign_None _ _ Heqf).\n    remember (locBlocksSrc mu b) as l.\n    destruct l; apply eq_sym in Heql.\n      eapply locBlocksSrc_as_inj_local; eassumption.\n    rewrite (locBlocksSrc_false_local_None _ _ WD Heql); trivial.\nQed.\n\nDefinition restrict_sm mu (X:block -> bool) :=\nmatch mu with\n  Build_SM_Injection locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern =>\n  Build_SM_Injection locBSrc locBTgt pSrc pTgt (restrict local X)\n                     extBSrc extBTgt fSrc fTgt (restrict extern X)\nend.\n\nLemma restrict_sm_com: forall mu X Y,\n      restrict_sm (restrict_sm mu X) Y = restrict_sm (restrict_sm mu Y) X.\nProof. intros. unfold restrict_sm.\n  destruct mu.\n  f_equal; apply restrict_com.\nQed.\n\nLemma restrict_sm_nest: forall mu X Y\n         (HXY: forall b, Y b = true -> X b = true),\n      restrict_sm (restrict_sm mu X) Y = restrict_sm mu Y.\nProof. intros. unfold restrict_sm.\n  destruct mu; simpl in *.\n  f_equal; apply restrict_nest; assumption.\nQed.\n\nLemma restrict_sm_nest': forall mu X Y\n         (HXY: forall b, Y b = true -> X b = true),\n      restrict_sm (restrict_sm mu Y) X = restrict_sm mu Y.\nProof. intros. rewrite restrict_sm_com.\n  apply restrict_sm_nest; assumption.\nQed.\n\nLemma restrict_sm_local: forall mu X,\n      local_of (restrict_sm mu X) = restrict (local_of mu) X.\nProof. intros. destruct mu; reflexivity. Qed.\nLemma restrict_sm_pub: forall mu X,\n      pub_of (restrict_sm mu X) = restrict (pub_of mu) X.\nProof. intros. unfold pub_of.\n       extensionality b. destruct mu; simpl.\n       unfold restrict.\n       remember (pubBlocksSrc b) as d.\n       destruct d; trivial.\n       destruct (X b); trivial.\nQed.\n\nLemma restrict_sm_extern: forall mu X,\n      extern_of (restrict_sm mu X) = restrict (extern_of mu) X.\nProof. intros. destruct mu; reflexivity. Qed.\nLemma restrict_sm_foreign: forall mu X,\n      foreign_of (restrict_sm mu X) = restrict (foreign_of mu) X.\nProof. intros. unfold foreign_of.\n       extensionality b. destruct mu; simpl.\n       unfold restrict.\n       remember (frgnBlocksSrc b) as d.\n       destruct d; trivial.\n       destruct (X b); trivial.\nQed.\n\nLemma restrict_sm_all: forall mu X,\n       as_inj (restrict_sm mu X) = restrict (as_inj mu) X.\nProof. intros. unfold as_inj.\n   rewrite restrict_sm_local, restrict_sm_extern.\n   apply join_restrict.\nQed.\n\nLemma restrict_sm_local': forall mu (WD: SM_wd mu) X\n      (HX: forall b, vis mu b = true -> X b = true),\n      local_of (restrict_sm mu X) = local_of mu.\nProof. intros. rewrite restrict_sm_local.\n apply restrict_outside. intros.\n apply HX.\n destruct (local_DomRng _ WD _ _ _ H). unfold vis. intuition auto with bool.\nQed.\n\nLemma restrict_sm_pub': forall mu (WD: SM_wd mu) X\n      (HX: forall b, vis mu b = true ->\n                     X b = true),\n      pub_of (restrict_sm mu X) = pub_of mu.\nProof. intros. rewrite restrict_sm_pub.\n apply restrict_outside. intros.\n apply HX. apply pub_in_local in H.\n destruct (local_DomRng _ WD _ _ _ H). unfold vis. intuition auto with bool.\nQed.\n\nLemma restrict_sm_foreign': forall mu (WD: SM_wd mu) X\n      (HX: forall b, vis mu b = true -> X b = true),\n      foreign_of (restrict_sm mu X) = foreign_of mu.\nProof. intros. rewrite restrict_sm_foreign.\n apply restrict_outside. intros.\n apply HX. unfold vis. rewrite orb_true_iff.\n right. eapply (foreign_DomRng _ WD _ _ _ H).\nQed.\n\nLemma restrict_sm_locBlocksSrc: forall mu X,\n      locBlocksSrc (restrict_sm mu X) = locBlocksSrc mu.\nProof. intros. destruct mu; reflexivity. Qed.\nLemma restrict_sm_extBlocksSrc: forall mu X,\n      extBlocksSrc (restrict_sm mu X) = extBlocksSrc mu.\nProof. intros. destruct mu; reflexivity. Qed.\nLemma restrict_sm_pubBlocksSrc: forall mu X,\n      pubBlocksSrc (restrict_sm mu X) = pubBlocksSrc mu.\nProof. intros. destruct mu; reflexivity. Qed.\nLemma restrict_sm_frgnBlocksSrc: forall mu X,\n      frgnBlocksSrc (restrict_sm mu X) = frgnBlocksSrc mu.\nProof. intros. destruct mu; reflexivity. Qed.\nLemma restrict_sm_DomSrc: forall mu X,\n      DomSrc (restrict_sm mu X) = DomSrc mu.\nProof. intros. destruct mu; reflexivity. Qed.\nLemma restrict_sm_DOM: forall mu X,\n      DOM (restrict_sm mu X) = DOM mu.\nProof. intros. destruct mu; reflexivity. Qed.\n\nLemma restrict_sm_locBlocksTgt: forall mu X,\n      locBlocksTgt (restrict_sm mu X) = locBlocksTgt mu.\nProof. intros. destruct mu; reflexivity. Qed.\nLemma restrict_sm_extBlocksTgt: forall mu X,\n      extBlocksTgt (restrict_sm mu X) = extBlocksTgt mu.\nProof. intros. destruct mu; reflexivity. Qed.\nLemma restrict_sm_pubBlocksTgt: forall mu X,\n      pubBlocksTgt (restrict_sm mu X) = pubBlocksTgt mu.\nProof. intros. destruct mu; reflexivity. Qed.\nLemma restrict_sm_frgnBlocksTgt: forall mu X,\n      frgnBlocksTgt (restrict_sm mu X) = frgnBlocksTgt mu.\nProof. intros. destruct mu; reflexivity. Qed.\nLemma restrict_sm_DomTgt: forall mu X,\n      DomTgt (restrict_sm mu X) = DomTgt mu.\nProof. intros. destruct mu; reflexivity. Qed.\nLemma restrict_sm_RNG: forall mu X,\n      RNG (restrict_sm mu X) = RNG mu.\nProof. intros. destruct mu; reflexivity. Qed.\n\nLemma restrict_sm_visTgt mu X: visTgt (restrict_sm mu X) = visTgt mu.\nProof. intros. unfold visTgt.\n  rewrite restrict_sm_locBlocksTgt, restrict_sm_frgnBlocksTgt.\n  trivial.\nQed.\n\nLemma replace_locals_exportedTgt:\n  forall (mu : SM_Injection) (pubSrc' pubTgt' : block -> bool) vals,\n  exportedTgt (replace_locals mu pubSrc' pubTgt') vals =\n  (fun b : block => getBlocks vals b || (frgnBlocksTgt mu b || pubTgt' b)).\nProof. intros. unfold exportedTgt. extensionality b.\n  rewrite replace_locals_sharedTgt. trivial.\nQed.\n\nLemma restrict_sm_WD:\n      forall mu (WD: SM_wd mu) X\n          (HX: forall b, vis mu b = true -> X b = true),\n      SM_wd (restrict_sm mu X).\nProof. intros.\nsplit; intros.\n  rewrite restrict_sm_locBlocksSrc, restrict_sm_extBlocksSrc.\n    apply WD.\n  rewrite restrict_sm_locBlocksTgt, restrict_sm_extBlocksTgt.\n    apply WD.\n  rewrite restrict_sm_locBlocksSrc, restrict_sm_locBlocksTgt.\n    rewrite restrict_sm_local in H.\n    eapply WD. eapply restrictD_Some. apply H.\n  rewrite restrict_sm_extBlocksSrc, restrict_sm_extBlocksTgt.\n    rewrite restrict_sm_extern in H.\n    eapply WD. eapply restrictD_Some. apply H.\n  rewrite restrict_sm_pubBlocksSrc in H.\n    destruct (pubSrcAx _ WD _ H) as [b2 [d1 [PUB1 PT2]]].\n    rewrite restrict_sm_pubBlocksTgt, restrict_sm_local.\n    exists b2, d1. split; trivial.\n    apply restrictI_Some; intuition.\n    apply HX. unfold vis. rewrite (pubBlocksLocalSrc _ WD _ H). intuition.\n  rewrite restrict_sm_frgnBlocksSrc in H.\n    destruct (frgnSrcAx _ WD _ H) as [b2 [d1 [FRG1 FT2]]].\n    rewrite restrict_sm_frgnBlocksTgt, restrict_sm_extern.\n    exists b2, d1. split; trivial.\n    apply restrictI_Some; intuition.\n    apply HX. unfold vis. rewrite H. intuition auto with bool.\n  rewrite restrict_sm_locBlocksTgt.\n    rewrite restrict_sm_pubBlocksTgt in H.\n    apply (pubBlocksLocalTgt _ WD _ H).\n  rewrite restrict_sm_extBlocksTgt.\n    rewrite restrict_sm_frgnBlocksTgt in H.\n    apply (frgnBlocksExternTgt _ WD _ H).\nQed.\n\nLemma restrict_sm_preserves_globals: forall {F V} (ge:Genv.t F V) mu X\n  (PG : meminj_preserves_globals ge (as_inj mu))\n  (Glob : forall b, isGlobalBlock ge b = true -> X b = true),\nmeminj_preserves_globals ge (as_inj (restrict_sm mu X)).\nProof. intros. rewrite restrict_sm_all.\n  eapply restrict_preserves_globals; assumption.\nQed.\n\nLemma restrict_sm_preserves_globals' F V (ge:Genv.t F V) mu X :\n  Events.meminj_preserves_globals ge (extern_of mu) ->\n  (forall b, isGlobalBlock ge b = true -> X b = true) ->\n  Events.meminj_preserves_globals ge (extern_of (restrict_sm mu X)).\nProof.\nintros.\nrewrite restrict_sm_extern.\neapply restrict_preserves_globals; assumption.\nQed.\n\nDefinition mkinitial_SM (mu: SM_Injection) frgnS frgnT :=\n  match mu with\n  Build_SM_Injection locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern =>\n  Build_SM_Injection (fun b => false) (fun b => false) (fun b => false) (fun b => false) (fun b => None)\n                     (DomSrc mu) (DomTgt mu) frgnS frgnT (as_inj mu)\n  end.\n\nLemma mkinitial_SM_as_inj: forall mu S T,\n  as_inj (mkinitial_SM mu S T) = as_inj mu.\nProof. intros. destruct mu; simpl.\n  unfold as_inj; simpl.\n  apply join_None_rightneutral.\nQed.\nLemma mkinitial_SM_local: forall mu S T,\n  local_of (mkinitial_SM mu S T) = fun b => None.\nProof. intros. destruct mu; simpl. trivial. Qed.\nLemma mkinitial_SM_extern: forall mu S T,\n  extern_of (mkinitial_SM mu S T) = as_inj mu.\nProof. intros. destruct mu; simpl. trivial. Qed.\n\nLemma mkinitial_SM_foreign: forall mu S T b1,\n  foreign_of (mkinitial_SM mu S T) b1 =\n  if S b1 then as_inj mu b1 else None.\nProof. intros. destruct mu; simpl. trivial. Qed.\n\nLemma mkinitial_SM_DomSrc: forall mu S T,\n  DomSrc (mkinitial_SM mu S T) = DomSrc mu.\nProof. intros. destruct mu; simpl. trivial. Qed.\nLemma mkinitial_SM_DOM: forall mu S T,\n  DOM (mkinitial_SM mu S T) = DOM mu.\nProof. intros. destruct mu; simpl. trivial. Qed.\nLemma mkinitial_SM_DomTgt: forall mu S T,\n  DomTgt (mkinitial_SM mu S T) = DomTgt mu.\nProof. intros. destruct mu; simpl. trivial. Qed.\nLemma mkinitial_SM_RBG: forall mu S T,\n  RNG (mkinitial_SM mu S T) = RNG mu.\nProof. intros. destruct mu; simpl. trivial. Qed.\n\nLemma mkinitial_SM_equals_initial_SM: forall mu S T,\n  mkinitial_SM mu S T = initial_SM (DomSrc mu) (DomTgt mu) S T (as_inj mu).\nProof. intros.\n  unfold initial_SM, mkinitial_SM.\n  destruct mu; simpl in *.\n  f_equal; trivial.\nQed.\n\nLemma vals_def_inject_getBlock j b2: forall vals1 vals2\n    (INJ: Val.inject_list j vals1 vals2)\n    (DEF : vals_def vals1 = true)\n    (GB: getBlocks vals2 b2 = true),\n    exists b1 d, j b1 = Some(b2,d) /\\ getBlocks vals1 b1 = true.\nProof. intros.\n  induction INJ; simpl; intros.\n     rewrite getBlocksD_nil in GB. inv GB.\n  rewrite getBlocksD in GB.\n  inv H; simpl in *.\n    destruct IHINJ as [b1 [d [J GB1]]]; trivial.\n      exists b1, d; split; trivial.\n    destruct IHINJ as [b1 [d [J GB1]]]; trivial.\n      exists b1, d; split; trivial.\n    destruct IHINJ as [b1 [d [J GB1]]]; trivial.\n      exists b1, d; split; trivial.\n    destruct IHINJ as [b1 [d [J GB1]]]; trivial.\n      exists b1, d; split; trivial.\n    destruct (eq_block b0 b2); subst; simpl in *.\n      exists b1, delta; split; trivial.\n        rewrite getBlocks_char. exists ofs1; left; trivial.\n      destruct IHINJ as [bb1 [d [J GB1]]]; trivial.\n      exists bb1, d; split; trivial. rewrite getBlocks_char in GB1.\n        rewrite getBlocks_char. destruct GB1. eexists; right; eassumption.\n    inv DEF.\nQed.\n\nLemma visTgt_DomTgt mu b: visTgt mu b = true -> SM_wd mu -> DomTgt mu b = true.\nProof. unfold visTgt, DomTgt; intros.\n  destruct (locBlocksTgt mu b); simpl in *; trivial.\n  eapply frgnBlocksExternTgt; assumption.\nQed.\n\nLemma replace_locals_wd_AtExternal: forall mu vals1 vals2 m1 m2\n         (WD : SM_wd mu)\n         (MINJ : Mem.inject (as_inj mu) m1 m2)\n         (AINJ : Forall2 (val_inject (as_inj mu)) vals1 vals2),\n  SM_wd\n  (replace_locals mu\n     (fun b => locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b)\n     (fun b => locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b)).\nProof. intros.\n      apply replace_locals_wd. trivial.\n        intros. apply andb_true_iff in H. destruct H.\n                (*apply val_list_inject_forall_inject in AINJ.\n                apply forall_vals_inject_restrictD in AINJ.*)\n                exploit (REACH_local_REACH mu); try eassumption.\n                intros [b2 [d [LOC RCH2]]].\n                exists b2, d. rewrite LOC, RCH2.\n                destruct (local_DomRng _ WD _ _ _ LOC). rewrite H2; split; trivial.\n  intros. apply andb_true_iff in H; destruct H.\n                rewrite H; trivial.\nQed.\n\nLemma inject_shared_replace_locals m1 m2 mu vals1 vals2:\n      forall (RC : REACH_closed m1 (vis mu))\n             (WD : SM_wd mu)\n             (MINJ : Mem.inject (as_inj mu) m1 m2)\n             pubSrc' pubTgt'\n             (HPS: pubSrc' = (fun b => locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b))\n             (HPT: pubTgt' = (fun b => locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b))\n             nu (Hnu : nu = replace_locals mu pubSrc' pubTgt')\n             (WDnu: SM_wd nu),\n      Mem.inject (shared_of nu) m1 m2.\nProof. intros.\n   eapply inject_mapped; try eassumption.\n                intros. subst nu. rewrite replace_locals_shared. intros b Hb.\n                apply REACHAX in Hb. destruct Hb as [L HL].\n                generalize dependent b.\n                induction L; intros; inv HL; trivial.\n                specialize (IHL _ H1); clear H1.\n                apply mappedD_true in IHL. destruct IHL as [[b1 delta] IHL].\n\n               apply inject_REACH_closed in MINJ.\n                  exploit (MINJ b).\n                    eapply REACH_cons; try eassumption.\n                    eapply REACH_nil.\n                      destruct (joinD_Some _ _ _ _ _ IHL); clear IHL.\n                        eapply mappedI_true. apply foreign_in_all; eassumption.\n                      destruct H as [_ H].\n                        remember (locBlocksSrc mu b' && REACH m1 (exportedSrc mu vals1) b') as qq.\n                        destruct qq; inv H.\n                        eapply mappedI_true. apply local_in_all; eassumption.\n                  intros. apply mappedD_true in H. destruct H as [[b2 dd] AIb].\n                  exploit (RC b). eapply REACH_cons; try eassumption.\n                     eapply REACH_nil. unfold vis.\n                     destruct (joinD_Some _ _ _ _ _ IHL); clear IHL.\n                       apply orb_true_iff; right. eapply foreign_DomRng; eassumption.\n                     destruct H as [_ H].\n                      remember (locBlocksSrc mu b' && REACH m1 (exportedSrc mu vals1) b') as qq.\n                      destruct qq; inv H.\n                      destruct (local_DomRng _ WD _ _ _ H1). rewrite H; trivial.\n                  unfold vis; intros. apply orb_true_iff in H.\n                  destruct H. 2:{ unfold join. destruct (frgnSrc _ WD _ H) as [? [? [? ?]]].\n                       eapply mappedI_true. rewrite H0. reflexivity. }\n                  specialize (locBlocksSrc_externNone _ WD _ H). intros EXT.\n                  destruct (joinD_Some _ _ _ _ _ AIb); clear AIb.\n                    rewrite H0 in EXT; discriminate.\n                  destruct H0. apply extern_ofD_None in H0; destruct H0.\n                    assert (RR: REACH m1 (exportedSrc mu vals1) b = true).\n                       eapply REACH_cons; try eassumption.\n                       destruct (joinD_Some _ _ _ _ _ IHL); clear IHL.\n                         apply REACH_nil. unfold exportedSrc, sharedSrc, shared_of, join.\n                           rewrite H5.  intuition auto with bool.\n                         destruct H5.\n                           remember (locBlocksSrc mu b' && REACH m1 (exportedSrc mu vals1) b') as qq.\n                           destruct qq; inv H6. apply eq_sym in Heqqq. apply andb_true_iff in Heqqq. apply Heqqq.\n                    eapply mappedI_true. unfold join. rewrite H0, H, RR; simpl. eassumption.\n               assert (AI: as_inj mu = as_inj nu).\n                  subst nu. rewrite replace_locals_as_inj; trivial.\n               subst. rewrite AI. apply shared_in_all; eassumption.\nQed.\n\nLemma forall_vals_inject_restrictD' j vals1 vals2 X\n      (Inj : Forall2 (val_inject (restrict j X)) vals1 vals2) :\n  Forall2 (val_inject j) vals1 vals2\n  /\\ (forall b : block, getBlocks vals1 b = true -> X b = true).\nProof.\nintros. induction Inj. constructor.\nconstructor; trivial. unfold getBlocks. simpl. intros; congruence.\ndestruct IHInj as [H0 H1]. split. constructor; auto.\n  eapply val_inject_restrictD in H. eassumption.\nintros b0 GET. rewrite getBlocksD in GET.\nassert (H2: (exists ofs, x=Vptr b0 ofs) \\/ getBlocks l b0=true).\n{ revert GET; case_eq x; auto. intros b1 i ? H2; subst x.\n  rewrite orb_true_iff in H2. destruct H2; auto.\n  destruct (eq_block b1 b0); try (simpl in H2; congruence). subst.\n  left. exists i. auto. }\ndestruct H2 as [[ofs H2]|H2]. subst x.\ninv H. apply restrictD_Some in H4. destruct H4; auto.\napply H1; auto.\nQed.\n\nLemma forall_vals_inject_intern_incr mu mu' vals1 vals2\n      (Inj : Forall2 (val_inject (as_inj mu)) vals1 vals2)\n      (Incr : intern_incr mu mu')\n      (WD : SM_wd mu') :\n  Forall2 (val_inject (as_inj mu')) vals1 vals2.\nProof.\nintros. induction Inj. constructor.\nconstructor; trivial. apply val_inject_incr with (f1 := as_inj mu); auto.\napply intern_incr_as_inj; auto.\nQed.\n\nLemma forall_vals_inject_extern_incr mu mu' vals1 vals2\n      (Inj : Forall2 (val_inject (as_inj mu)) vals1 vals2)\n      (Incr : extern_incr mu mu')\n      (WD : SM_wd mu') :\n  Forall2 (val_inject (as_inj mu')) vals1 vals2.\nProof.\nintros. induction Inj. constructor.\nconstructor; trivial. apply val_inject_incr with (f1 := as_inj mu); auto.\napply extern_incr_as_inj; auto.\nQed.\n\nLemma local_of_vis mu: forall b1 b2 d\n   (LOC: local_of mu b1 = Some (b2,d))\n   (WD: SM_wd mu), vis mu b1 = true.\nProof. intros. unfold vis.\n  destruct (local_DomRng _ WD _ _ _ LOC).\n  intuition auto with bool.\nQed.\n\nLemma incr_local_restrictvis mu: SM_wd mu ->\n      inject_incr (local_of mu) (restrict (as_inj mu)(vis mu)).\nProof. intros; red; intros.\n  apply restrictI_Some.\n  apply local_in_all; assumption.\n  destruct (local_DomRng _ H _ _ _ H0) .\n  unfold vis; intuition auto with bool.\nQed.\n\nLemma local_visTgt mu (WD: SM_wd mu) b1 b2 d:\n      local_of mu b1 = Some(b2,d) -> visTgt mu b2 = true.\nProof. unfold visTgt. intros.\n  destruct (local_DomRng _ WD _ _ _ H); intuition auto with bool.\nQed.\n\nSection globalfunction_ptr_inject.\n\nContext {F V : Type} (ge : Genv.t F V).\n\nDefinition globalfunction_ptr_inject (j:meminj):=\n  forall b f, Genv.find_funct_ptr ge b = Some f ->\n              j b = Some(b,0) /\\ isGlobalBlock ge b = true.\n\nLemma restrict_preserves_globalfun_ptr: forall j X\n  (PG : globalfunction_ptr_inject j)\n  (Glob : forall b, isGlobalBlock ge b = true -> X b = true),\nglobalfunction_ptr_inject (restrict j X).\nProof. intros.\n  red; intros.\n  destruct (PG _ _ H). split; trivial.\n  apply restrictI_Some; try eassumption.\n  apply (Glob _ H1).\nQed.\n\nLemma restrict_GFP_vis: forall mu\n  (GFP : globalfunction_ptr_inject (as_inj mu))\n  (Glob : forall b, isGlobalBlock ge b = true ->\n                    frgnBlocksSrc mu b = true),\n  globalfunction_ptr_inject (restrict (as_inj mu) (vis mu)).\nProof. intros.\n  unfold vis.\n  eapply restrict_preserves_globalfun_ptr. eassumption.\n  intuition auto with bool.\nQed.\n\nRemark val_inject_function_pointer:\n  forall v fd j tv,\n  Genv.find_funct ge v = Some fd ->\n  globalfunction_ptr_inject j ->\n  val_inject j v tv ->\n  tv = v.\nProof.\n  intros. exploit Genv.find_funct_inv; eauto. intros [b EQ]. subst v.\n  inv H1.\n  rewrite Genv.find_funct_find_funct_ptr in H.\n  destruct (H0 _ _ H).\n  rewrite H1 in H4; inv H4.\n  rewrite Ptrofs.add_zero. trivial.\nQed.\n\nEnd globalfunction_ptr_inject.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/sepcomp/reach.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24745941802762592}}
{"text": "(** * Adjunction and Kan extension **)\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nGeneralizable All Variables.\n\nSet Primitive Projections.\nSet Universe Polymorphism.\n\nRequire Import\n        COC.Base.Main\n        COC.Adj.Main\n        COC.KanExt.Lan\n        COC.KanExt.Ran.\n\nClass PreserveLan\n      {C D E E': Category}{F: C --> E}{K: C --> D}\n      (lan: Lan F K)\n      (L: E --> E')\n      (new: forall (S: D --> E'),\n          (L \\o F) ==> (S \\o K) ->\n          (L \\o lanF lan) ==> S) :=\n  preserve_lan:\n    IsLan (lanF:=L \\o lanF lan) (Nassoc \\o (L <o lanN lan)) (@new).\n\n(** left adjoint preserve lan **)\nProgram Instance left_adjoint_preserve_lan\n        (C D E E': Category)\n        (F: C --> E)(K: C --> D)(lan: Lan F K)\n        (L: E --> E')(R: E' --> E)(adj: L -| R)\n  : PreserveLan\n      (fun S e =>\n         [ 1 \\o * ==> * ]\n           \\o (adj_counit adj o> S)\n           \\o Nassoc\n           \\o (L <o (lanU lan\n                           (Nassoc\n                              \\o (R <o e)\n                              \\o Nassoc_inv\n                              \\o (adj_unit adj o> F)\n                              \\o [ * ==> 1 \\o * ])))).\nNext Obligation.\n  - simpl; intros.\n    rewrite !cat_comp_id_cod, !cat_comp_assoc, <- fmap_comp; simpl.\n    generalize (lan_universality\n                  (IsLan:=lan)\n                  (Nassoc \\o (R <o e) \\o Nassoc_inv \\o (adj_unit adj o> F) \\o [ * ==> 1 \\o * ]) X); simpl.\n    intro H; rewrite H; simpl.\n    rewrite cat_comp_id_cod, cat_comp_id_dom.\n    rewrite <- cat_comp_id_cod.\n    rewrite <- adj_rl_naturality.\n    rewrite fmap_id, !cat_comp_id_cod.\n    rewrite <- (cat_comp_id_dom (fmap R _ \\o _)), cat_comp_assoc.\n    rewrite adj_rl_naturality.\n    now rewrite adj_iso_lr_rl, fmap_id, !cat_comp_id_dom.\n  - simpl; intros.\n    symmetry.\n    rewrite !cat_comp_id_cod, <- cat_comp_id_cod.\n    rewrite <- adj_rl_naturality.\n    rewrite fmap_id, !cat_comp_id_cod.\n    generalize (lan_uniqueness\n                  (IsLan:=lan)\n                  (e:=Nassoc \\o (R <o e) \\o Nassoc_inv \\o (adj_unit adj o> F) \\o Natrans_id_cod_inv F)\n                  (u:=(R <o u) \\o Nassoc_inv \\o{Fun _ _} (adj_unit adj o> lanF lan) \\o{Fun _ _} [* ==> 1 \\o * ]));\n      simpl; intros Heq.\n    rewrite <- Heq.\n    + rewrite cat_comp_id_cod.\n      rewrite adj_rl_naturality.\n      now rewrite fmap_id, cat_comp_id_dom, adj_iso_lr_rl, cat_comp_id_dom.\n    + intros c.\n      rewrite !cat_comp_id_cod.\n      rewrite <- adj_lr_naturality.\n      rewrite cat_comp_id_cod.\n      rewrite (fmap_id (F:=L)), cat_comp_id_dom.\n      rewrite <- adj_lr_naturality.\n      rewrite (fmap_id (F:=L)), !cat_comp_id_dom.\n      rewrite <- H.\n      rewrite cat_comp_id_cod.\n      rewrite <- (cat_comp_id_cod (u (K c) \\o _)).\n      rewrite (adj_lr_naturality (IsAdjunction:=adj) _ _ (u (K c))).\n      now rewrite fmap_id, cat_comp_id_cod.\nQed.\n\n(** lan from adjunction **)\nProgram Definition lan_from_adjunction\n        (C D: Category)\n        (F: C --> D)(G: D --> C)(adj: F -| G)\n  : Lan (Id C) F :=\n  [Lan by (fun S e => ([ * \\o 1 ==> *]\n                         \\o (S <o adj_counit adj)\n                         \\o Nassoc_inv\n                         \\o (e o> G)\n                         \\o [* ==> 1 \\o *]))\n   with G, adj_unit adj].\nNext Obligation.\n  rewrite <- !cat_comp_assoc.\n  rewrite <- (fmap_id (F:=S) (F X)), <- fmap_comp.\n  rewrite !cat_comp_id_dom.\n  rewrite cat_comp_assoc.\n  generalize (natrans_naturality (IsNatrans:=e) (adj_lr adj (Id F X))); simpl; intros H; rewrite H; clear H.\n  rewrite <- cat_comp_assoc, <- fmap_comp.\n  rewrite cat_comp_assoc.\n  rewrite <- adj_rl_naturality.\n  rewrite !fmap_id, !cat_comp_id_cod.\n  now rewrite adj_iso_lr_rl, fmap_id, cat_comp_id_cod.\n\n  rewrite !cat_comp_id_cod, cat_comp_id_dom.\n  rewrite <- H.\n  rewrite <- cat_comp_assoc.\n  rewrite <- (natrans_naturality (IsNatrans:=u) ((adj_rl adj) (Id G X))).\n  rewrite cat_comp_assoc.\n  rewrite <- (cat_comp_id_dom (fmap G _ \\o _)), cat_comp_assoc.\n  rewrite <- adj_lr_naturality, fmap_id, !cat_comp_id_dom.\n  now rewrite adj_iso_rl_lr, cat_comp_id_dom.\nQed.\n\n(** ran from adjunction **)\nProgram Definition ran_from_adjunction\n        (C D: Category)\n        (F: C --> D)(G: D --> C)(adj: F -| G)\n  : Ran (Id D) G :=\n  [Ran by (fun S e =>\n             [1 \\o * ==> *]\n               \\o (e o> F)\n               \\o Nassoc\n               \\o (S <o adj_unit adj)\n               \\o  [* ==> * \\o 1])\n   with F, adj_counit adj].\nNext Obligation.\n  rewrite !cat_comp_id_cod, !cat_comp_id_dom.\n  rewrite <- cat_comp_assoc.\n  generalize (natrans_naturality (IsNatrans:=e) (adj_rl adj (Id (G X)))); simpl; intros H; rewrite <- H; clear H.\n  rewrite cat_comp_assoc, <- fmap_comp.\n  rewrite <- (cat_comp_id_dom (_ \\o adj_lr adj _)).\n  rewrite cat_comp_assoc, <- adj_lr_naturality.\n  rewrite !fmap_id, !cat_comp_id_dom.\n  now rewrite adj_iso_rl_lr, fmap_id, cat_comp_id_dom.\n\n  rewrite !cat_comp_id_cod, cat_comp_id_dom.\n  rewrite <- H.\n  rewrite cat_comp_assoc.\n  rewrite (natrans_naturality (IsNatrans:=u) (adj_lr adj (Id (F X)))).\n  rewrite <- cat_comp_assoc.\n  rewrite <- (cat_comp_id_cod (_ \\o fmap F _)), <- !cat_comp_assoc.\n  rewrite (cat_comp_assoc (fmap F _)).\n  rewrite <- adj_rl_naturality, fmap_id, !cat_comp_id_cod.\n  now rewrite adj_iso_lr_rl, cat_comp_id_cod.\nQed.\n\n(** adjunction from lan **)\nProgram Definition counit_from_lan\n        (C D: Category)\n        (F: C --> D)(G: D --> C)\n        (au: (Id C) ==> (G \\o F))\n        (luniv: forall (S: D --> C),\n            (Id C) ==> (S \\o F) -> G ==> S)\n        (Hlan: IsLan (lanF:=G) au luniv)\n        (puniv: forall (S: D --> D),\n            (F \\o Id C) ==> (S \\o F) ->\n            (F \\o G) ==> S)\n        (Hp: PreserveLan (lan:=Build_Lan Hlan)(L:=F) puniv)\n  : (F \\o G) ==> (Id D) :=\n  puniv (Id D) ([* ==> 1 \\o *] \\o Id F \\o [* \\o 1 ==> *]).\n\nLemma counit_from_lan_makes_triangle:\n  forall (C D: Category)\n         (F: C --> D)(G: D --> C)\n         (au: (Id C) ==> (G \\o F))\n         (luniv: forall (S: D --> C),\n             (Id C) ==> (S \\o F) -> G ==> S)\n         (Hlan: IsLan (lanF:=G) au luniv)\n         (puniv: forall (S: D --> D),\n             (F \\o Id C) ==> (S \\o F) ->\n             (F \\o G) ==> S)\n         (Hp: PreserveLan (lan:=Build_Lan Hlan)(L:=F) puniv),\n    adj_triangle au (puniv (Id D) ([* ==> 1 \\o *] \\o Id F \\o [* \\o 1 ==> *])).\nProof.\n  intros; split.\n  - simpl; intros c.\n    rewrite !cat_comp_id_cod, cat_comp_id_dom.\n    generalize (lan_universality (IsLan:=Hp) ([ * ==> 1 \\o * ] \\o Natrans_id F \\o [ * \\o 1 ==> * ]) c); simpl.\n    rewrite cat_comp_id_cod.\n    intros H; rewrite H.\n    now rewrite !cat_comp_id_cod.\n  -\n    generalize (lan_uniqueness (IsLan:=Hlan)(e:=au)(u:=Id G)).\n    intros H'; rewrite H'; clear H'.\n    + apply lan_uniqueness.\n      simpl; intros c.\n      rewrite !cat_comp_id_cod, cat_comp_id_dom.\n      rewrite cat_comp_assoc.\n      rewrite (natrans_naturality (IsNatrans:=au) (au c)); simpl.\n      rewrite <- cat_comp_assoc, <- fmap_comp.\n\n      generalize (lan_universality (IsLan:=Hp) ([ * ==> 1 \\o * ] \\o Natrans_id F \\o [ * \\o 1 ==> * ]) c); simpl.\n      rewrite !cat_comp_id_cod.\n      intros H; rewrite H.\n      now rewrite !fmap_id, !cat_comp_id_cod.\n    + now simpl; intros c; rewrite cat_comp_id_cod.\nQed.\n\nDefinition adjunction_from_lan\n        (C D: Category)\n        (F: C --> D)(G: D --> C)\n        (au: (Id C) ==> (G \\o F))\n        (luniv: forall (S: D --> C),\n            (Id C) ==> (S \\o F) -> G ==> S)\n        (Hlan: IsLan (lanF:=G) au luniv)\n        (puniv: forall (S: D --> D),\n            (F \\o Id C) ==> (S \\o F) ->\n            (F \\o G) ==> S)\n        (Hp: PreserveLan (lan:=Build_Lan Hlan)(L:=F) puniv)\n  : F -| G :=\n  Adjunction_by_unit_and_counit\n    (counit_from_lan_makes_triangle Hp).\n\n(** *** 5.3.2 Lan -| Inverse -| Ran **)\nProgram Definition Inverse_functor\n        (C D: Category)(K: C --> D)\n        (E: Category)\n  : (E^D) --> (E^C) :=\n  [Functor by S :-> [c :=> S (K c)] with F :-> F \\o K].\nNext Obligation.\n  now rewrite <- natrans_naturality.\nQed.\nNext Obligation.\n  rename X into F, Y into G.\n  intros S T Heq c; simpl.\n  now rewrite Heq.\nQed.\n\nProgram Definition Lan_functor\n        (C D: Category)(K: C --> D)\n        (E: Category)\n        (lan: forall (F: C --> E), Lan F K)\n  : (E^C) --> (E^D) :=\n  [Functor by (fun F G S => lanU (lan F) (lanN (lan G) \\o S))\n   with `(lanF (lan F))].\nNext Obligation.\n  - rename X into F, Y into G.\n    intros S T Heq d.\n    apply (lan_uniqueness (IsLan:=lan F)(e:=lanN (lan G) \\o T)).\n    rewrite (lan_universality (IsLan:=lan F)(lanN (lan G) \\o S)).\n    now simpl; intros c; rewrite Heq.\n  - rename X into F, Y into G, Z into H, f into S, g into T, X0 into d.\n    symmetry.\n    apply (lan_uniqueness (IsLan:=lan F)(e:=(lanN (lan H) \\o T \\o S))(u:=(lanU (lan G) (lanN (lan H) \\o T))\\o (lanU (lan F) (lanN (lan G) \\o S)))); simpl; intros c.\n    rewrite cat_comp_assoc.\n    rewrite (lan_universality (IsLan:=lan F)(lanN (lan G) \\o S) c).\n    simpl.\n    rewrite <- cat_comp_assoc.\n    rewrite (lan_universality (IsLan:=lan G)(lanN (lan H) \\o T) c).\n    simpl.\n    now rewrite cat_comp_assoc.\n  - rename X into F, X0 into d.\n    symmetry.\n    apply (lan_uniqueness (IsLan:=lan F)(e:=(lanN (lan F) \\o Natrans_id F))(u:=Natrans_id _)); simpl; intros c.\n    now rewrite cat_comp_id_cod, cat_comp_id_dom.\nQed.\n\nProgram Definition Ran_functor\n        (C D: Category)(K: C --> D)\n        (E: Category)\n        (ran: forall (F: C --> E), Ran F K)\n  : (E^C) --> (E^D) :=\n  [Functor by (fun F G S => ranU (ran G) (S \\o ranN (ran F)))\n   with `(ranF (ran F))].\nNext Obligation.\n  - rename X into F, Y into G.\n    intros S T Heq d.\n    apply (ran_uniqueness (IsRan:=ran G)(e:=T \\o ranN (ran F))).\n    rewrite (ran_universality (IsRan:=ran G)(S \\o ranN (ran F))).\n    now simpl; intros c; rewrite Heq.\n  - rename X into F, Y into G, Z into H, f into S, g into T, X0 into d.\n    symmetry.\n    apply (ran_uniqueness (IsRan:=ran H)(e:=((T \\o S) \\o ranN (ran F)))(u:=(ranU (ran H) (T \\o ranN (ran G))) \\o (ranU (ran G) (S \\o ranN (ran F))))); simpl; intros c.\n    rewrite <- cat_comp_assoc.\n    rewrite (ran_universality (IsRan:=ran H)(T \\o ranN (ran G)) c).\n    simpl.\n    rewrite cat_comp_assoc.\n    rewrite (ran_universality (IsRan:=ran G)(S \\o ranN (ran F)) c).\n    simpl.\n    now rewrite cat_comp_assoc.\n  - rename X into F, X0 into d.\n    symmetry.\n    apply (ran_uniqueness (IsRan:=ran F)(e:=(Natrans_id F \\o ranN (ran F)))(u:=Natrans_id _)); simpl; intros c.\n    now rewrite cat_comp_id_cod, cat_comp_id_dom.\nQed.\n\n(** Lan -| Inverse **)\nProgram Definition lan_inverse_adjunction\n        (C D: Category)(K: C --> D)\n        (E: Category)\n        (lan: forall (F: C --> E), Lan F K)\n  : Lan_functor lan -| Inverse_functor K E :=\n  [Adj by (fun (F: C --> E)(G: D --> E) =>\n             [S in lanF (lan F) ==> G :->\n                        (S o> K) \\o lanN (lan F)]),\n          (fun (F: C --> E)(G: D --> E) =>\n             [S in F ==> (G \\o K) :-> lanU (lan F) S]) ].\nNext Obligation.\n  intros S T Heq c; simpl.\n  now rewrite Heq.\nQed.\nNext Obligation.\n  intros S T Heq d; simpl.\n  apply (lan_uniqueness (IsLan:=lan F)(e:= T)); simpl; intros c.\n  now rewrite (lan_universality (IsLan:=lan F) S c), Heq.\nQed.\nNext Obligation.\n  - rename c into F, d into G, f into S, X into d.\n    symmetry.\n    now apply (lan_uniqueness (IsLan:=lan F)(e:=S o> K \\o lanN (lan F))).\n  - rename c into F, d into G, g into T, X into c.\n    now rewrite (lan_universality (IsLan:=lan F) T c).\n  - rename c into F, c' into F', d into G, d' into G', f into S, g into T, h into U, X into c.\n    rewrite !cat_comp_assoc.\n    now rewrite (lan_universality (IsLan:=lan F') (lanN (lan F) \\o S) c); simpl.\nQed.\n\n(** Inverse -| Ran **)\nProgram Definition ran_inverse_adjunction\n        (C D: Category)(K: C --> D)\n        (E: Category)\n        (ran: forall (F: C --> E), Ran F K)\n  : Inverse_functor K E -| Ran_functor ran :=\n  [Adj by (fun (G: D --> E)(F: C --> E) =>\n             [S in (G \\o K) ==> F :-> ranU (ran F) S]),\n          (fun (G: D --> E)(F: C --> E) =>\n             [S in G ==> ranF (ran F) :-> ranN (ran F) \\o (S o> K)])].\nNext Obligation.\n  intros S T Heq d; simpl.\n  apply (ran_uniqueness (IsRan:=ran F)(e:= T)); simpl; intros c.\n  now rewrite (ran_universality (IsRan:=ran F) S c), Heq.\nQed.\nNext Obligation.\n  intros S T Heq c; simpl.\n  now rewrite Heq.\nQed.\nNext Obligation.\n  - rename c into G, d into F, f into S, X into c.\n    now rewrite (ran_universality (IsRan:=ran F) S c).\n  - rename c into G, d into F, g into S, X into d.\n    symmetry.\n    now apply (ran_uniqueness (IsRan:=ran F)(e:=ranN (ran F) \\o (S o> K))).\n  - rename d into F, d' into F', c into G, c' into G', f into T, g into S, h into U, X into d.\n    symmetry.\n    generalize (ran_uniqueness (IsRan:=ran F')); simpl; intros Huniq.\n    eapply (Huniq _ (S \\o U \\o [c :=> T (K c) from (_ \\o _) to (_ \\o _)])\n                  ((ranU (ran F') (S \\o ranN (ran F))) \\o (ranU (ran F) U) \\o T)); simpl; intros c.\n    rewrite <- !cat_comp_assoc.\n    rewrite (ran_universality (IsRan:=ran F')(S \\o ranN (ran F)) c); simpl.\n    rewrite (cat_comp_assoc _ _ (S c)).\n    now rewrite (ran_universality (IsRan:=ran F) U c).\nQed.\n", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/Cat_on_coq/theories/KanExt/Adj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2474388945535825}}
{"text": "(*\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\nRequire Import String.\nRequire Import Lia.\nRequire Import EquivDec.\nRequire Import Decidable.\nRequire Import Utils.\nRequire Import Imp.\n\nSection ImpSize.\n\n  Context {Model: Set}.\n  Context {Op: Set}.\n  Context {Runtime: Set}.\n\n  Definition imp_expr := @Imp.imp_expr Model Op Runtime.\n  Definition imp_stmt := @Imp.imp_stmt Model Op Runtime.\n  Definition imp_function := @Imp.imp_function Model Op Runtime.\n  Definition imp := @Imp.imp Model Op Runtime.\n\n\n  Fixpoint imp_expr_size (e:imp_expr) : nat\n    := match e with\n       | ImpExprError v => 1\n       | ImpExprVar v => 1\n       | ImpExprConst v => 1\n       | ImpExprOp op l => S (List.fold_left (fun acc e => acc + imp_expr_size e ) l 0)\n       | ImpExprRuntimeCall f args => S (List.fold_left (fun acc e => acc + imp_expr_size e) args 0)\n       end.\n\n    Fixpoint imp_stmt_size (stmt:imp_stmt) : nat\n      := match stmt with\n         | ImpStmtBlock decls stmts =>\n           S (List.fold_left\n                (fun acc (decl: var * option imp_expr) =>\n                   let (x, eopt) := decl in\n                   acc + match eopt with\n                         | None => 1\n                         | Some e => 1 + imp_expr_size e\n                         end)\n                decls\n                (List.fold_left\n                   (fun acc s => acc + imp_stmt_size s)\n                   stmts 0))\n         | ImpStmtAssign x e => 1 + imp_expr_size e\n         | ImpStmtFor i e s => 1 + imp_expr_size e + imp_stmt_size s\n         | ImpStmtForRange i e1 e2 s =>\n           1 + imp_expr_size e1  + imp_expr_size e2  + imp_stmt_size s\n         | ImpStmtIf e s1 s2 =>\n           1 + imp_expr_size e + imp_stmt_size s1 + imp_stmt_size s2\n         end.\n\n    Definition imp_function_size (q:imp_function) : nat :=\n      match q with\n      | ImpFun args s ret => imp_stmt_size s\n      end.\n\n    Definition imp_size (q: imp) : nat :=\n      match q with\n      | ImpLib l =>\n        List.fold_left\n          (fun acc (decl: string * imp_function) =>\n             let (fname, fdef) := decl in acc + imp_function_size fdef)\n          l 0\n      end.\n\n    Lemma imp_expr_size_nzero (e:imp_expr) : imp_expr_size e <> 0.\n    Proof.\n      induction e; simpl; try lia.\n    Qed.\n\n    Lemma imp_stmt_size_nzero (s:imp_stmt) : imp_stmt_size s <> 0.\n    Proof.\n      induction s; simpl; try destruct o; try lia.\n    Qed.\n\n    Corollary imp_function_size_nzero (q:imp_function) : imp_function_size q <> 0.\n    Proof.\n      destruct q.\n      apply imp_stmt_size_nzero.\n    Qed.\n\n    (* Corollary imp_size_nzero (q:imp) : imp_size q <> 0. *)\n    (* Proof. *)\n    (*   induction q; simpl; try destruct o; try lia. *)\n    (*   apply imp_stmt_size_nzero. *)\n    (* Qed. *)\n\nEnd ImpSize.\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/Imp/Lang/ImpSize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.24741215026910174}}
{"text": "(* \n * An encoding of the untyped lambda calculus with numbers.\n *\n * Authors: \n *   Arjun Guha <arjun@cs.brown.edu>\n *   Benjamin Lerner <blerner@cs.brown.edu>\n *)\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.Le.\nRequire Import Coq.Arith.Lt.\nRequire Import Coq.Structures.Orders.\nRequire Import Coq.Structures.OrderedType.\nRequire Import Coq.MSets.MSetList.\nRequire Import Coq.FSets.FMapList.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Logic.Decidable.\nRequire Import Omega.\nRequire Import SfLib.\nSet Implicit Arguments.\nRequire Import ListExt.\n\nModule Type ATOM.\n\n  Parameter atom : Set.\n  Declare Module Atom_as_OT : UsualOrderedType with Definition t := atom.\n  Declare Module Ordered : Coq.Structures.OrderedType.OrderedType \n    with Definition t := atom.\n  Module OrderedTypeFacts := Coq.Structures.OrderedType.OrderedTypeFacts (Ordered).\n  Parameter atom_fresh_for_list : forall (xs : list atom), \n    exists x : atom, ~ List.In x xs.\n  Parameter atom_eq_dec : forall a1 a2 : atom, {a1 = a2} + {~ a1 = a2}.\n  Parameter atom_dec_eq : forall a1 a2 : atom, a1 = a2 \\/ ~ a1 = a2.\n\nEnd ATOM.\n\nModule Type STRING.\n\n Parameter string : Set.\n Declare Module String_as_OT : UsualOrderedType with Definition t := string.\n Declare Module Ordered : Coq.Structures.OrderedType.OrderedType\n   with Definition t := string.\n Module OrderedTypeFacts := Coq.Structures.OrderedType.OrderedTypeFacts (Ordered).\n Parameter string_eq_dec : forall s1 s2 : string, {s1 = s2} + {~ s1 = s2}.\n Parameter string_dec_eq : forall s1 s2 : string, s1 = s2 \\/ ~ s1 = s2.\n\nEnd STRING.\n\nModule LC (Import Atom : ATOM) (Import String : STRING).\n\nModule Atoms := Coq.MSets.MSetList.Make (Atom.Atom_as_OT).\nModule AtomEnv := Coq.FSets.FMapList.Make (Atom.Ordered).\n\nDefinition atom := Atom.atom. (* free variables *)\nDefinition loc := Atom.atom.\nDefinition string := String.string.\n\nParameter __proto__ : string.\n\n\nSection Definitions.\nUnset Elimination Schemes.\nInductive exp : Set :=\n  | exp_fvar  : atom -> exp\n  | exp_bvar  : nat -> exp (* bound variables as de Brujin indices *)\n  | exp_abs   : exp -> exp\n  | exp_app   : exp -> exp -> exp\n  | exp_nat   : nat -> exp\n  | exp_succ  : exp -> exp\n  | exp_bool  : bool -> exp\n  | exp_string : string -> exp\n  | exp_undef : exp\n  | exp_null  : exp\n  | exp_not   : exp -> exp\n  | exp_if    : exp -> exp -> exp -> exp\n  | exp_err   : exp\n  | exp_label : atom -> exp -> exp\n  | exp_break : atom -> exp -> exp\n  | exp_loc   : loc -> exp\n  | exp_deref : exp -> exp\n  | exp_ref   : exp -> exp\n  | exp_set   : exp -> exp -> exp\n  | exp_catch : exp -> exp -> exp (* 2nd exp is a binder *)\n  | exp_throw : exp -> exp\n  | exp_seq   : exp -> exp -> exp\n  | exp_finally : exp -> exp -> exp\n  | exp_obj   : list (string * exp) -> exp\n  | exp_getfield : exp -> exp -> exp\n  | exp_setfield : exp -> exp -> exp -> exp\n  | exp_delfield : exp -> exp -> exp.\nSet Elimination Schemes.\n\nDefinition exp_ind := fun (P : exp -> Prop)\n  (rec_exp_fvar : forall a : atom, P (exp_fvar a))\n  (rec_exp_bvar : forall n : nat, P (exp_bvar n))\n  (rec_exp_abs : forall e : exp, P e -> P (exp_abs e))\n  (rec_exp_app : forall e : exp, P e -> forall e0 : exp, P e0 -> P (exp_app e e0))\n  (rec_exp_nat : forall n : nat, P (exp_nat n))\n  (rec_exp_succ : forall e : exp, P e -> P (exp_succ e))\n  (rec_exp_bool : forall b : bool, P (exp_bool b))\n  (rec_exp_string : forall s : string, P (exp_string s))\n  (rec_exp_undef : P exp_undef)\n  (rec_exp_null : P exp_null)\n  (rec_exp_not : forall e : exp, P e -> P (exp_not e))\n  (rec_exp_if : forall e : exp, P e -> forall e0 : exp, P e0 -> forall e1 : exp, P e1 -> P (exp_if e e0 e1))\n  (rec_exp_err : P exp_err)\n  (rec_exp_label : forall (a : atom) (e : exp), P e -> P (exp_label a e))\n  (rec_exp_break : forall (a : atom) (e : exp), P e -> P (exp_break a e))\n  (rec_exp_loc : forall l : loc, P (exp_loc l))\n  (rec_exp_deref : forall e : exp, P e -> P (exp_deref e))\n  (rec_exp_ref : forall e : exp, P e -> P (exp_ref e))\n  (rec_exp_set : forall e : exp, P e -> forall e0 : exp, P e0 -> P (exp_set e e0))\n  (rec_exp_catch : forall e : exp, P e -> forall e0 : exp, P e0 -> P (exp_catch e e0))\n  (rec_exp_throw : forall e : exp, P e -> P (exp_throw e))\n  (rec_exp_seq : forall e : exp, P e -> forall e0 : exp, P e0 -> P (exp_seq e e0))\n  (rec_exp_finally : forall e : exp, P e -> forall e0 : exp, P e0 -> P (exp_finally e e0))\n  (rec_exp_obj : forall l : list (string * exp), Forall P (map (@snd string exp) l) -> P (exp_obj l))\n  (rec_exp_getfield : forall o : exp, P o -> forall f : exp, P f -> P (exp_getfield o f))\n  (rec_exp_setfield : forall o : exp, P o -> forall f, P f -> forall e, P e -> P (exp_setfield o f e))\n  (rec_exp_delfield : forall o : exp, P o -> forall f : exp, P f -> P (exp_delfield o f))\n  =>\nfix exp_rec' (e : exp) {struct e} : P e :=\n  match e as e0 return (P e0) with\n  | exp_fvar a => rec_exp_fvar a\n  | exp_bvar n => rec_exp_bvar n\n  | exp_abs e0 => rec_exp_abs e0 (exp_rec' e0)\n  | exp_app e0 e1 => rec_exp_app e0 (exp_rec' e0) e1 (exp_rec' e1)\n  | exp_nat n => rec_exp_nat n\n  | exp_succ e0 => rec_exp_succ e0 (exp_rec' e0)\n  | exp_bool b => rec_exp_bool b\n  | exp_string s => rec_exp_string s\n  | exp_undef => rec_exp_undef\n  | exp_null => rec_exp_null\n  | exp_not e0 => rec_exp_not e0 (exp_rec' e0)\n  | exp_if e0 e1 e2 => rec_exp_if e0 (exp_rec' e0) e1 (exp_rec' e1) e2 (exp_rec' e2)\n  | exp_err => rec_exp_err\n  | exp_label a e0 => rec_exp_label a e0 (exp_rec' e0)\n  | exp_break a e0 => rec_exp_break a e0 (exp_rec' e0)\n  | exp_loc l => rec_exp_loc l\n  | exp_deref e0 => rec_exp_deref e0 (exp_rec' e0)\n  | exp_ref e0 => rec_exp_ref e0 (exp_rec' e0)\n  | exp_set e0 e1 => rec_exp_set e0 (exp_rec' e0) e1 (exp_rec' e1)\n  | exp_catch e0 e1 => rec_exp_catch e0 (exp_rec' e0) e1 (exp_rec' e1)\n  | exp_throw e0 => rec_exp_throw e0 (exp_rec' e0)\n  | exp_seq e0 e1 => rec_exp_seq e0 (exp_rec' e0) e1 (exp_rec' e1)\n  | exp_finally e0 e1 => rec_exp_finally e0 (exp_rec' e0) e1 (exp_rec' e1)\n  | exp_obj l =>\n    rec_exp_obj l ((fix forall_rec (ls : list (string * exp)) : Forall P (map (@snd string exp) ls) :=\n      match ls with\n        | nil => Forall_nil P\n        | (_,tr)::rest => Forall_cons tr (exp_rec' tr) (forall_rec rest)\n      end) l)\n  | exp_getfield o f => rec_exp_getfield o (exp_rec' o) f (exp_rec' f)\n  | exp_setfield o f e => rec_exp_setfield o (exp_rec' o) f (exp_rec' f) e (exp_rec' e)\n  | exp_delfield o f => rec_exp_delfield o (exp_rec' o) f (exp_rec' f)\n  end.\n(* Definition exp_rec := fun (P : exp -> Set) => exp_rect (P := P). *)\n(* Definition exp_ind := fun (P : exp -> Prop) => exp_rect (P := P). *)\n\n\nLtac destruct_and_solve' e := destruct e; [idtac | right; intro Neq; inversion Neq; contradiction].\nTactic Notation \"solve\" \"by\" \"destruction\" \"1\" tactic(t) constr(e) := destruct_and_solve' e; left; t; auto.\nTactic Notation \"solve\" \"by\" \"destruction\" \"2\" tactic(t) constr(e1) constr(e2) := \n  destruct_and_solve' e1; solve by destruction 1 (t) e2.\nTactic Notation \"solve\" \"by\" \"destruction\" \"3\" tactic(t) constr(e1) constr(e2) constr (e3) := \n  destruct_and_solve' e1; solve by destruction 2 (t) e2 e3.\n\nLemma exp_eq_dec : forall e1 e2 : exp, e1 = e2 \\/ ~ e1 = e2.\nProof with eauto.\ninduction e1; induction e2; try solve [\n  left; reflexivity | right; congruence\n  | solve by destruction 1 subst (string_dec_eq s s0)\n  | solve by destruction 1 subst (IHe1 e2)\n  | solve by destruction 2 subst (IHe1_1 e2_1) (IHe1_2 e2_2)\n  | solve by destruction 3 subst (IHe1_1 e2_1) (IHe1_2 e2_2) (IHe1_3 e2_3)\n  | solve by destruction 1 subst (Atom.atom_dec_eq a a0)\n  | solve by destruction 1 subst (Atom.atom_dec_eq l l0)\n  | solve by destruction 2 subst (Atom.atom_dec_eq a a0) (IHe1 e2)  \n  | solve by destruction 1 subst (eq_nat_dec n n0) \n  | solve by destruction 2 subst (IHe1 e2) (string_dec_eq f f0)\n  | solve by destruction 3 subst (IHe1_1 e2_1) (IHe1_2 e2_2) (string_dec_eq f f0) ].\nCase \"exp_bool\".\ndestruct b; destruct b0; try solve [left; reflexivity | right; congruence].\nCase \"exp_obj\".\nassert (l = l0 \\/ l <> l0). \n  SCase \"list proof\".\n  apply in_dec_dec_list. intros. rewrite Forall_forall in H. \n  remember a1 as a1'; destruct a1'. remember a2 as a2'; destruct a2'.\n  assert (EqS := string_dec_eq s s0). inversion EqS; [auto | right; congruence].\n  assert (e = e0 \\/ e <> e0). apply H. apply in_split_r in H1. simpl in H1. \n  replace (map (snd (B:=exp)) l) with (snd (split l)). auto. symmetry; apply map_snd_snd_split.\n  inversion H4; [left; subst; auto | right; congruence].\ninversion H1; [left; subst; auto | right; congruence].\nQed.\n\nLemma str_exp_eq_dec : forall (a1 a2 : (string * exp)), a1 = a2 \\/ a1 <> a2.\nProof with auto.\n  destruct a1 as (a1s, a1e); destruct a2 as (a2s, a2e).\n  assert (S := string_dec_eq a1s a2s). assert (E := exp_eq_dec a1e a2e).\n  destruct S; destruct E; subst; solve [left; auto | right; congruence].\nQed.\n\nLemma str_exp_list_eq_dec : forall (l1 l2 : list (string * exp)), l1 = l2 \\/ l1 <> l2.\nProof.\n  induction l1. intros; destruct l2; solve [left; auto | right; congruence].\n  intros. destruct l2. right; congruence.\n  assert (E := str_exp_eq_dec a p). destruct E.\n  destruct (IHl1 l2); subst; solve [left; auto | right; congruence].\n  right; congruence.\nQed.\n\nDefinition fieldnames l := map (@fst string exp) l.\nDefinition values l := map (@snd string exp) l.\nDefinition map_values A (f : exp -> A) l := \n  map (fun kv => ((@fst string exp) kv, f ((@snd string exp) kv))) l.\nHint Unfold values fieldnames map_values.\n\n(* open_rec is the analogue of substitution for de Brujin indices.\n  open_rec k u e replaces index k with u in e. *)\nFixpoint open_rec (k : nat) (u : exp) (e : exp) { struct e } := match e with\n  | exp_fvar a    => e\n  | exp_bvar n    => if beq_nat k n then u else e\n  | exp_abs  e    => exp_abs (open_rec (S k) u e)\n  | exp_app e1 e2 => exp_app (open_rec k u e1) (open_rec k u e2)\n  | exp_nat n     => e\n  | exp_succ e    => exp_succ (open_rec k u e)\n  | exp_bool b     => e\n  | exp_string s   => e\n  | exp_undef      => e\n  | exp_null       => e\n  | exp_not e      => exp_not (open_rec k u e)\n  | exp_if e e1 e2 => exp_if (open_rec k u e) (open_rec k u e1) (open_rec k u e2)\n  | exp_err       => e\n  | exp_label x e => exp_label x (open_rec k u e)\n  | exp_break x e => exp_break x (open_rec k u e)\n  | exp_loc _     => e\n  | exp_deref e   => exp_deref (open_rec k u e)\n  | exp_ref e     => exp_ref (open_rec k u e)\n  | exp_set e1 e2 => exp_set (open_rec k u e1) (open_rec k u e2)\n  | exp_catch e1 e2 => exp_catch (open_rec k u e1) (open_rec (S k) u e2)\n  | exp_throw e     => exp_throw (open_rec k u e)\n  | exp_seq e1 e2   => exp_seq (open_rec k u e1) (open_rec k u e2)\n  | exp_finally e1 e2 => exp_finally (open_rec k u e1) (open_rec k u e2)\n  | exp_obj l     => exp_obj (map_values (open_rec k u) l)\n  | exp_getfield o f => exp_getfield (open_rec k u o) (open_rec k u f)\n  | exp_setfield o f e => exp_setfield (open_rec k u o) (open_rec k u f) (open_rec k u e)\n  | exp_delfield o f => exp_delfield (open_rec k u o) (open_rec k u f)\nend.\n\n\nDefinition open e u := open_rec 0 u e.\n\nUnset Elimination Schemes.\n(* locally closed : all de Brujin indices are bound *)\nInductive lc' : nat -> exp -> Prop :=\n  | lc_fvar : forall n a, lc' n (exp_fvar a)\n  | lc_bvar : forall k n, k < n -> lc' n (exp_bvar k)\n  | lc_abs  : forall n e,\n      lc' (S n) e -> lc' n (exp_abs e)\n  | lc_app  : forall n e1 e2, lc' n e1 -> lc' n e2 -> lc' n (exp_app e1 e2)\n  | lc_nat  : forall n x, lc' n (exp_nat x)\n  | lc_succ : forall n e, lc' n e -> lc' n (exp_succ e)\n  | lc_bool : forall n b, lc' n (exp_bool b)\n  | lc_string : forall n s, lc' n (exp_string s)\n  | lc_undef : forall n, lc' n exp_undef\n  | lc_null : forall n, lc' n exp_null\n  | lc_not  : forall n e, lc' n e -> lc' n (exp_not e)\n  | lc_if   : forall n e e1 e2, \n      lc' n e -> lc' n e1 -> lc' n e2 -> lc' n (exp_if e e1 e2)\n  | lc_err   : forall n, lc' n exp_err\n  | lc_label : forall n x e, lc' n e -> lc' n (exp_label x e)\n  | lc_break : forall n x e, lc' n e -> lc' n (exp_break x e)\n  | lc_loc   : forall n x, lc' n (exp_loc x)\n  | lc_ref   : forall n e, lc' n e -> lc' n (exp_ref e)\n  | lc_deref : forall n e, lc' n e -> lc' n (exp_deref e)\n  | lc_set   : forall n e1 e2, lc' n e1 -> lc' n e2 -> lc' n (exp_set e1 e2)\n  | lc_catch : forall n e1 e2, \n      lc' n e1 -> lc' (S n) e2 -> lc' n (exp_catch e1 e2)\n  | lc_throw : forall n e, lc' n e -> lc' n (exp_throw e)\n  | lc_seq   : forall n e1 e2, lc' n e1 -> lc' n e2 -> lc' n (exp_seq e1 e2)\n  | lc_finally : forall n e1 e2, \n    lc' n e1 ->\n    lc' n e2 ->\n    lc' n (exp_finally e1 e2)\n  | lc_obj   : forall n l, NoDup (fieldnames l) -> Forall (lc' n) (values l) -> lc' n (exp_obj l)\n  | lc_getfield : forall n o f, lc' n o -> lc' n f -> lc' n (exp_getfield o f)\n  | lc_setfield : forall n o f e, lc' n o -> lc' n f -> lc' n e -> lc' n (exp_setfield o f e)\n  | lc_delfield : forall n o f, lc' n o -> lc' n f -> lc' n (exp_delfield o f)\n.\nSet Elimination Schemes.\n\nDefinition lc'_ind := fun (P : nat -> exp -> Prop)\n  (rec_lc_fvar : forall (n : nat) (a : atom), P n (exp_fvar a))\n  (rec_lc_bvar : forall k n : nat, k < n -> P n (exp_bvar k))\n  (rec_lc_abs : forall (n : nat) (e : exp),\n        lc' (S n) e -> P (S n) e -> P n (exp_abs e))\n  (rec_lc_app : forall (n : nat) (e1 e2 : exp),\n        lc' n e1 -> P n e1 -> lc' n e2 -> P n e2 -> P n (exp_app e1 e2))\n  (rec_lc_nat : forall n x : nat, P n (exp_nat x))\n  (rec_lc_succ : forall (n : nat) (e : exp), lc' n e -> P n e -> P n (exp_succ e))\n  (rec_lc_bool : forall (n : nat) (b : bool), P n (exp_bool b))\n  (rec_lc_string : forall (n : nat) (s : string), P n (exp_string s))\n  (rec_lc_undef : forall n : nat, P n exp_undef)\n  (rec_lc_null : forall n : nat, P n exp_null)\n  (rec_lc_not : forall (n : nat) (e : exp), lc' n e -> P n e -> P n (exp_not e))\n  (rec_lc_if : forall (n : nat) (e e1 e2 : exp),\n        lc' n e ->\n        P n e ->\n        lc' n e1 -> P n e1 -> lc' n e2 -> P n e2 -> P n (exp_if e e1 e2))\n  (rec_lc_err : forall n : nat, P n exp_err)\n  (rec_lc_label : forall (n : nat) (x : atom) (e : exp),\n        lc' n e -> P n e -> P n (exp_label x e))\n  (rec_lc_break : forall (n : nat) (x : atom) (e : exp),\n         lc' n e -> P n e -> P n (exp_break x e))\n  (rec_lc_loc : forall (n : nat) (x : loc), P n (exp_loc x))\n  (rec_lc_ref : forall (n : nat) (e : exp), lc' n e -> P n e -> P n (exp_ref e))\n  (rec_lc_deref : forall (n : nat) (e : exp), lc' n e -> P n e -> P n (exp_deref e))\n  (rec_lc_set : forall (n : nat) (e1 e2 : exp),\n         lc' n e1 -> P n e1 -> lc' n e2 -> P n e2 -> P n (exp_set e1 e2))\n  (rec_lc_catch : forall (n : nat) (e1 e2 : exp),\n         lc' n e1 ->\n         P n e1 -> lc' (S n) e2 -> P (S n) e2 -> P n (exp_catch e1 e2))\n  (rec_lc_throw : forall (n : nat) (e : exp), lc' n e -> P n e -> P n (exp_throw e))\n  (rec_lc_seq : forall (n : nat) (e1 e2 : exp),\n         lc' n e1 -> P n e1 -> lc' n e2 -> P n e2 -> P n (exp_seq e1 e2))\n  (rec_lc_finally : forall (n : nat) (e1 e2 : exp),\n         lc' n e1 -> P n e1 -> lc' n e2 -> P n e2 -> P n (exp_finally e1 e2))\n  (rec_lc_obj : forall (n : nat) (l : list (string * exp)),\n         NoDup (fieldnames l) -> Forall (P n) (map (@snd string exp) l) -> P n (exp_obj l)) \n  (rec_lc_getfield : forall (n : nat) o, P n o -> forall f, P n f -> P n (exp_getfield o f))\n  (rec_lc_setfield : forall (n : nat) o, P n o -> forall f, P n f -> forall e, P n e -> P n (exp_setfield o f e))\n  (rec_lc_delfield : forall (n : nat) o, P n o -> forall f, P n f -> P n (exp_delfield o f))\n=>\nfix lc'_ind' (n : nat) (e : exp) (l : lc' n e) {struct l} : P n e :=\n  match l in (lc' n0 e0) return (P n0 e0) with\n  | lc_fvar n0 a => rec_lc_fvar n0 a\n  | lc_bvar k n0 l0 => rec_lc_bvar k n0 l0\n  | lc_abs n0 e0 l0 => rec_lc_abs n0 e0 l0 (lc'_ind' (S n0) e0 l0)\n  | lc_app n0 e1 e2 l0 l1 => rec_lc_app n0 e1 e2 l0 (lc'_ind' n0 e1 l0) l1 (lc'_ind' n0 e2 l1)\n  | lc_nat n0 x => rec_lc_nat n0 x\n  | lc_succ n0 e0 l0 => rec_lc_succ n0 e0 l0 (lc'_ind' n0 e0 l0)\n  | lc_bool n0 b => rec_lc_bool n0 b\n  | lc_string n0 s => rec_lc_string n0 s\n  | lc_undef n0 => rec_lc_undef n0\n  | lc_null n0 => rec_lc_null n0\n  | lc_not n0 e0 l0 => rec_lc_not n0 e0 l0 (lc'_ind' n0 e0 l0)\n  | lc_if n0 e0 e1 e2 l0 l1 l2 =>\n      rec_lc_if  n0 e0 e1 e2 l0 (lc'_ind' n0 e0 l0) l1 (lc'_ind' n0 e1 l1) l2 (lc'_ind' n0 e2 l2)\n  | lc_err n0 => rec_lc_err n0\n  | lc_label n0 x e0 l0 => rec_lc_label n0 x e0 l0 (lc'_ind' n0 e0 l0)\n  | lc_break n0 x e0 l0 => rec_lc_break n0 x e0 l0 (lc'_ind' n0 e0 l0)\n  | lc_loc n0 x => rec_lc_loc n0 x\n  | lc_ref n0 e0 l0 => rec_lc_ref n0 e0 l0 (lc'_ind' n0 e0 l0)\n  | lc_deref n0 e0 l0 => rec_lc_deref n0 e0 l0 (lc'_ind' n0 e0 l0)\n  | lc_set n0 e1 e2 l0 l1 => rec_lc_set n0 e1 e2 l0 (lc'_ind' n0 e1 l0) l1 (lc'_ind' n0 e2 l1)\n  | lc_catch n0 e1 e2 l0 l1 =>\n      rec_lc_catch n0 e1 e2 l0 (lc'_ind' n0 e1 l0) l1 (lc'_ind' (S n0) e2 l1)\n  | lc_throw n0 e0 l0 => rec_lc_throw n0 e0 l0 (lc'_ind' n0 e0 l0)\n  | lc_seq n0 e1 e2 l0 l1 => rec_lc_seq n0 e1 e2 l0 (lc'_ind' n0 e1 l0) l1 (lc'_ind' n0 e2 l1)\n  | lc_finally n0 e1 e2 l0 l1 => rec_lc_finally n0 e1 e2 l0 (lc'_ind' n0 e1 l0) l1 (lc'_ind' n0 e2 l1)\n  | lc_obj n0 l0 n1 pf_lc' => rec_lc_obj n0 l0 n1\n      ((fix forall_lc_ind T (pf_lc : Forall (lc' n0) T) : Forall (P n0) T :=\n        match pf_lc with\n          | Forall_nil => Forall_nil (P n0)\n          | Forall_cons t l' isVal rest => \n            Forall_cons (A:=exp) (P:=P n0) (l:=l') t (lc'_ind' n0 t isVal) (forall_lc_ind l' rest)\n        end) (map (@snd string exp) l0) pf_lc')\n  | lc_getfield n0 o f lc_o lc_f  => rec_lc_getfield n0 o (lc'_ind' n0 o lc_o) f (lc'_ind' n0 f lc_f)\n  | lc_setfield n0 o f e lc_o lc_f lc_e => rec_lc_setfield n0 o (lc'_ind' n0 o lc_o) f (lc'_ind' n0 f lc_f) e (lc'_ind' n0 e lc_e)\n  | lc_delfield n0 o f lc_o lc_f => rec_lc_delfield n0 o (lc'_ind' n0 o lc_o) f (lc'_ind' n0 f lc_f)\n  end.\n\nDefinition lc := lc' 0.\n\nUnset Elimination Schemes.\nInductive val : exp -> Prop :=\n  | val_abs  : forall e, lc (exp_abs e) -> val (exp_abs e)\n  | val_nat  : forall n, val (exp_nat n)\n  | val_fvar : forall a, val (exp_fvar a)\n  | val_bool : forall b, val (exp_bool b)\n  | val_string : forall s, val (exp_string s)\n  | val_undef : val (exp_undef)\n  | val_null : val (exp_null)\n  | val_loc  : forall l, val (exp_loc l)\n  | val_obj  : forall l, Forall val (values l)\n                     -> NoDup (fieldnames l)\n                     -> val (exp_obj l).\nSet Elimination Schemes.\n\nDefinition val_ind := fun (P : exp -> Prop)\n  (rec_val_abs : forall e : exp, lc (exp_abs e) -> P (exp_abs e))\n  (rec_val_nat : forall n : nat, P (exp_nat n))\n  (rec_val_fvar : forall a : atom, P (exp_fvar a))\n  (rec_val_bool : forall b : bool, P (exp_bool b))\n  (rec_val_string : forall s : string, P (exp_string s))\n  (rec_val_undef : P exp_undef)\n  (rec_val_null : P exp_null)\n  (rec_val_loc : forall l : loc, P (exp_loc l))\n  (rec_val_obj : forall l : list (string * exp), Forall P (map (@snd string exp) l) ->\n        NoDup (fieldnames l) -> P (exp_obj l))\n  (e : exp) (v : val e) =>\n  fix val_ind' (e : exp) (v : val e) { struct v } : P e :=\n  match v in (val e0) return (P e0) with\n    | val_abs x x0 => rec_val_abs x x0\n    | val_nat x => rec_val_nat x\n    | val_fvar x => rec_val_fvar x\n    | val_bool x => rec_val_bool x\n    | val_string x => rec_val_string x\n    | val_undef => rec_val_undef\n    | val_null => rec_val_null\n    | val_loc x => rec_val_loc x\n    | val_obj x pf_vals x0 => rec_val_obj x\n      ((fix forall_val_ind T (pf_vals : Forall val T) : Forall P T :=\n        match pf_vals with\n          | Forall_nil => Forall_nil P\n          | Forall_cons t l' isVal rest => \n            Forall_cons (A:=exp) (P:=P) (l:=l') t (val_ind' t isVal) (forall_val_ind l' rest)\n        end) (map (@snd string exp) x) pf_vals) x0\n  end.\n\n\nInductive stored_val : Set :=\n  | val_with_proof : forall (v : exp), val v -> stored_val.\n\nDefinition sto := AtomEnv.t stored_val.\n\nInductive tag : Set :=\n  | TagAbs  : tag\n  | TagNat  : tag\n  | TagVar  : tag\n  | TagBool : tag\n  | TagString : tag\n  | TagUndef : tag\n  | TagNull : tag\n  | TagLoc  : tag\n  | TagObj  : tag.\n\nInductive tagof : exp -> tag -> Prop :=\n  | tag_abs  : forall e, tagof (exp_abs e) TagAbs\n  | tag_nat  : forall n, tagof (exp_nat n) TagNat\n  | tag_var  : forall x, tagof (exp_fvar x) TagVar\n  | tag_bool : forall b, tagof (exp_bool b) TagBool\n  | tag_string : forall s, tagof (exp_string s) TagString\n  | tag_undef : tagof (exp_undef) TagUndef\n  | tag_null : tagof (exp_null) TagNull\n  | tag_loc  : forall l, tagof (exp_loc l) TagLoc\n  | tag_obj  : forall l, tagof (exp_obj l) TagObj.\n\nHint Unfold open lc.\nHint Constructors lc'.\n\nLemma lc_val : forall v,\n  val v -> lc' 0 v.\nProof with auto.\nintros. induction v; try inversion H...\nCase \"exp_obj\".\n  constructor... subst... induction l; simpl... constructor.\n  SCase \"head\".\n  inversion H0. apply H5. subst. inversion H2. auto.  \n  SCase \"tail\". \n  apply IHl. inversion H0... constructor. \n  inversion H2... inversion H2... inversion H3... inversion H2... inversion H3...\nQed.\n\nHint Resolve lc_val.\n\nLemma lc_ascend : forall k k' e, k' >= k -> lc' k e -> lc' k' e.\nProof with auto.\nintros.\ngeneralize dependent k'.\ninduction H0...\nCase \"lc_bvar\".\n  intros. apply lc_bvar. omega.\nCase \"lc_abs\".\n  intros. apply lc_abs. apply IHlc'. omega.\nCase \"lc_catch\".\n  intros. apply lc_catch... apply IHlc'2. omega.\nCase \"lc_obj\".\n  intros. apply lc_obj... unfold values.\n  induction H0; constructor... \nQed.\nHint Resolve lc_ascend.\n\n\nHint Constructors tagof tag.\nLemma decide_tagof : forall e t, tagof e t \\/  ~ tagof e t.\nProof.\n  intros.\n  unfold not.\n  destruct e; destruct t; try solve  [ auto | right; intros; inversion H ].\nQed.\n\nLemma dec_in : forall (l : list string) a, In a l \\/ ~ In a l.\nProof with eauto.\ninduction l. intro; right; intro; inversion H.\nintro. assert (dec := string_dec_eq a a0).\ndestruct dec; auto. inversion H.\n left; constructor...\n assert (H1 := IHl a0). inversion H1. left; right... \n right. intro. apply H0. inversion H2... contradiction.\nQed.\n\nLemma dec_no_dup_strings : forall l : list string, NoDup l \\/ ~ NoDup l. \nProof with eauto.\ninduction l. left. constructor.\ninversion IHl. assert (DecIn := dec_in l a).\ninversion DecIn. right. intro. inversion H1. contradiction. left. constructor...\nright. intro; inversion H0; contradiction.\nQed.\n\nLtac inverting_and_solve' e := \n  let D := fresh \"D\" in let Neq := fresh \"Neq\" in \n    assert (D := e); inversion D; [idtac | right; intro Neq; inversion Neq; contradiction].\nTactic Notation \"solve\" \"by\" \"inverting\" \"1\" tactic(t) constr(e) := inverting_and_solve' e; left; t; auto.\nTactic Notation \"solve\" \"by\" \"inverting\" \"2\" tactic(t) constr(e1) constr(e2) := \n  inverting_and_solve' e1; solve by inverting 1 (t) e2.\nTactic Notation \"solve\" \"by\" \"inverting\" \"3\" tactic(t) constr(e1) constr(e2) constr (e3) := \n  inverting_and_solve' e1; solve by inverting 2 (t) e2 e3.\n\nLemma decide_lc : forall e, forall n, lc' n e \\/  ~ lc' n e.\nProof with eauto.\ninduction e; intro; try solve [ \n  left; auto\n| solve by inverting 1 (constructor) (IHe n)\n| solve by inverting 1 (constructor) (IHe (S n))\n| solve by inverting 2 (constructor) (IHe1 n) (IHe2 n)\n| solve by inverting 2 (constructor) (IHe1 n) (IHe2 (S n))\n| solve by inverting 3 (constructor) (IHe1 n) (IHe2 n) (IHe3 n)\n].\nCase \"exp_bvar\".\n  destruct (dec_le n0 n). \n  right. intro. inversion H0. omega.\n  left. constructor. omega.\nCase \"exp_obj\".\n  assert (Forall (fun e => lc' n e \\/ ~ lc' n e) (map (snd (B:=exp)) l)).\n    induction H. constructor. apply Forall_cons. apply H. apply IHForall.\n  apply forall_dec_dec_forall in H0. inversion H0. \n  SCase \"Everything in l is locally closed\".\n    destruct (dec_no_dup_strings (fieldnames l)).\n    SSCase \"Field names are distinct\". left. constructor. auto. unfold values... \n    SSCase \"Field names are not distinct\". right; intro; apply H2. inversion H3...\n  SCase \"Not everything in l is locally closed\". right. intro. apply H1. inversion H2. apply H6.\nQed.\n\n\nLemma decide_val : forall e, val e \\/ ~ val e.\nProof with eauto.\nunfold not. intro. \ninduction e; try solve [left; constructor | right; intro H; inversion H].\nCase \"exp_abs\". \ninduction IHe. left. constructor. constructor. apply lc_ascend with 0...\nassert (lc' 1 e \\/ ~ lc' 1 e). apply decide_lc.\ninversion H0. left; constructor... right; intro. apply H1. inversion H2. inversion H4. auto.\nCase \"exp_obj\".\napply (forall_dec_dec_forall val (l:=(map (@snd string exp) l))) in H.\ninversion H. assert (H1 := dec_no_dup_strings (fieldnames l)).\ninversion H1. left; constructor; unfold values; auto... right. intro. inversion H3. contradiction.\nright. intro. inversion H1. contradiction.\nQed.\n\n\nInductive E : Set :=\n  | E_hole    : E\n  | E_app_1   : E -> exp -> E\n  | E_app_2   : exp -> E -> E\n  | E_succ    : E -> E\n  | E_not     : E -> E\n  | E_if      : E -> exp -> exp -> E\n  | E_label   : atom -> E -> E\n  | E_break   : atom -> E -> E\n  | E_ref     : E -> E\n  | E_deref   : E -> E\n  | E_setref1 : E -> exp -> E\n  | E_setref2 : exp -> E -> E\n  | E_catch   : E -> exp -> E\n  | E_throw   : E -> E\n  | E_seq   : E -> exp -> E\n  | E_finally  : E -> exp -> E\n  | E_obj     : forall (vs : list (string * exp)) (es : list (string * exp)), \n                  (Forall val (values vs)) -> string -> E -> E\n  | E_getfield1 : E -> exp -> E\n  | E_getfield2 : exp -> E -> E\n  | E_setfield1 : E -> exp -> exp -> E\n  | E_setfield2 : exp -> E -> exp -> E\n  | E_setfield3 : exp -> exp -> E -> E\n  | E_delfield1 : E -> exp -> E\n  | E_delfield2 : exp -> E -> E\n.\n\nInductive E' : exp -> exp -> Prop :=\n  | E'_app_1 : forall e1 e2,\n      lc e1 ->\n      lc e2 ->\n      E' (exp_app e1 e2) e1\n  | E'_app_2 : forall v1 e2,\n      val v1 ->\n      lc e2 ->\n      E' (exp_app v1 e2) e2\n  | E'_succ : forall e,\n      lc e ->\n      E' (exp_succ e) e\n  | E'_not : forall e,\n      lc e ->\n      E' (exp_not e) e\n  | E'_if : forall e1 e2 e3,\n      lc e1 ->\n      lc e2 ->\n      lc e3 ->\n      E' (exp_if e1 e2 e3) e1\n  | E'_break : forall x e,\n      lc e ->\n      E' (exp_break x e) e\n  | E'_ref : forall e,\n      lc e ->\n      E' (exp_ref e) e\n  | E'_deref : forall e,\n      lc e ->\n      E' (exp_deref e) e\n  | E'_setref_1 : forall e1 e2,\n      lc e1 ->\n      lc e2 ->\n      E' (exp_set e1 e2) e1\n  | E'_setref_2 : forall v1 e2,\n      val v1 ->\n      lc e2 ->\n      E' (exp_set v1 e2) e2\n  | E'_throw : forall e,\n      lc e ->\n      E' (exp_throw e) e\n  | E'_seq_1 : forall e1 e2,\n      lc e1 ->\n      lc e2 ->\n      E' (exp_seq e1 e2) e1\n  | E'_seq_2 : forall v1 e2,\n      val v1 ->\n      lc e2 ->\n      E' (exp_seq v1 e2) e2\n  | E'_object : forall vs es k e,\n       Forall val (values vs) ->\n       lc (exp_obj (vs ++ (k, e) :: es)) ->\n       E' (exp_obj (vs ++ (k, e) :: es)) e\n  | E'_getfield_1 : forall e1 e2,\n      lc e1 ->\n      lc e2 ->\n      E' (exp_getfield e1 e2) e1\n  | E_getfield_2 : forall v1 e2,\n      val v1 ->\n      lc e2 ->\n      E' (exp_getfield v1 e2) e2\n  | E'_delfield_1 : forall e1 e2,\n      lc e1 ->\n      lc e2 ->\n      E' (exp_delfield e1 e2) e1\n  | E_delfield_2 : forall v1 e2,\n      val v1 ->\n      lc e2 ->\n      E' (exp_delfield v1 e2) e2\n  | E'_setfield_1 : forall e1 e2 e3,\n      lc e1 ->\n      lc e2 ->\n      lc e3 ->\n      E' (exp_setfield e1 e2 e3) e1\n  | E'_setfield_2 : forall v1 e2 e3,\n      val v1 ->\n      lc e2 ->\n      lc e3 ->\n      E' (exp_setfield v1 e2 e3) e2\n  | E'_setfield_3 : forall v1 v2 e3,\n      val v1 ->\n      val v2 ->\n      lc e3 ->\n      E' (exp_setfield v1 v2 e3) e3.\n\nInductive F : exp -> exp -> Prop :=\n  | F_E' : forall e1 e2,\n      E' e1 e2 ->\n      F e1 e2\n  | F_label : forall x e,\n      lc e ->\n      F (exp_label x e) e.\n\nInductive G : exp -> exp -> Prop :=\n   | G_E' : forall e1 e2,\n       E' e1 e2 ->\n       G e1 e2\n   | G_catch : forall e1 e2,\n       lc e1 ->\n       lc' 1 e2 ->\n       G (exp_catch e1 e2) e1.\n\nInductive ae : exp -> Prop :=\n  | redex_app  : forall e1 e2, val e1 -> val e2 -> ae (exp_app e1 e2)\n  | redex_succ : forall e, val e -> ae (exp_succ e)\n  | redex_not  : forall e, val e -> ae (exp_not e)\n  | redex_if   : forall e e1 e2, \n      val e -> lc e1 -> lc e2 -> ae (exp_if e e1 e2)\n  | redex_label : forall x v, val v -> ae (exp_label x v)\n   | redex_label_match_and_mismatch : forall x y v,\n       val v ->\n       ae (exp_label x (exp_break y v))\n   | redex_break : forall x e v, \n     val v -> \n     G e (exp_break x v) ->\n     ae e\n  | redex_ref   : forall v, val v -> ae (exp_ref v)\n  | redex_deref : forall v, val v -> ae (exp_deref v)\n  | redex_set  : forall v1 v2, val v1 -> val v2 -> ae (exp_set v1 v2)\n  | redex_uncatch : forall v e, val v -> lc' 1 e -> ae (exp_catch v e)\n  | redex_catch : forall e, lc' 1 e -> ae (exp_catch exp_err e)\n  | redex_throw : forall v, val v -> ae (exp_throw v)\n  | redex_seq   : forall v e, val v -> lc e -> ae (exp_seq v e)\n  | redex_finally : forall v e, val v -> lc e -> ae (exp_finally v e)\n  | redex_finally_err : forall e , lc e -> ae (exp_finally exp_err e)\n  | redex_finally_break : forall x v e, \n      val v -> \n      lc e -> \n       ae (exp_finally (exp_break x v) e)\n  | redex_err_bubble : forall e,\n      lc e ->\n      F e exp_err ->\n      ae e\n  | redex_getfield : forall o f, val o -> val f -> ae (exp_getfield o f)\n  | redex_setfield : forall o f e, val o -> val f -> val e -> ae (exp_setfield o f e)\n  | redex_delfield : forall o f, val o -> val f -> ae (exp_delfield o f)\n.\n\nInductive decompose : exp -> E -> exp -> Prop :=\n  | cxt_hole : forall e,\n      ae e ->\n      decompose e E_hole e\n  | cxt_app_1 : forall E e1 e2 e',\n      decompose e1 E e' ->\n      decompose (exp_app e1 e2) (E_app_1 E e2) e'\n  | cxt_app_2 : forall E v e e',\n      val v ->\n      decompose e E e' ->\n      decompose (exp_app v e) (E_app_2 v E) e'\n  | cxt_succ : forall E e e',\n      decompose e E e' ->\n      decompose (exp_succ e) (E_succ E) e'\n  | cxt_not : forall E e e',\n      decompose e E e' ->\n      decompose (exp_not e) (E_not E) e'\n  | cxt_if : forall E e e1 e2 e',\n      decompose e E e' ->\n      decompose (exp_if e e1 e2) (E_if E e1 e2) e'\n  | cxt_break : forall x e E ae,\n      decompose e E ae ->\n      decompose (exp_break x e) (E_break x E) ae\n  | cxt_label : forall x e E ae,\n      decompose e E ae ->\n      decompose (exp_label x e) (E_label x E) ae\n  | cxt_ref : forall e E ae,\n     decompose e E ae ->\n     decompose (exp_ref e) (E_ref E) ae\n  | cxt_deref : forall e E ae,\n     decompose e E ae ->\n     decompose (exp_deref e) (E_deref E) ae\n  | cxt_set1 : forall e1 e2 E ae,\n      decompose e1 E ae ->\n      decompose (exp_set e1 e2) (E_setref1 E e2) ae\n  | cxt_set2 : forall e1 e2 E ae,\n      val e1 ->\n      decompose e2 E ae ->\n      decompose (exp_set e1 e2) (E_setref2 e1 E) ae\n  | cxt_throw : forall e E ae,\n      decompose e E ae ->\n      decompose (exp_throw e) (E_throw E) ae\n  | cxt_catch : forall e1 e2 E ae,\n      decompose e1 E ae ->\n      decompose (exp_catch e1 e2) (E_catch E e2) ae\n  | cxt_seq : forall E e1 e2 ae,\n      decompose e1 E ae ->\n      decompose (exp_seq e1 e2) (E_seq E e2) ae\n  | cxt_finally : forall E e1 e2 ae,\n      decompose e1 E ae ->\n      decompose (exp_finally e1 e2) (E_finally E e2) ae\n  | cxt_obj  : forall vs es k e E e' (are_vals : Forall val (values vs)),\n      decompose e E e' ->\n      decompose (exp_obj (vs++(k,e)::es)) (E_obj vs es are_vals k E) e'\n  | cxt_getfield1 : forall o f E ae,\n      decompose o E ae ->\n      decompose (exp_getfield o f) (E_getfield1 E f) ae\n  | cxt_getfield2 : forall o f E ae,\n      val o ->\n      decompose f E ae ->\n      decompose (exp_getfield o f) (E_getfield2 o E) ae\n  | cxt_setfield1 : forall o f e E ae,\n      decompose o E ae ->\n      decompose (exp_setfield o f e) (E_setfield1 E f e) ae\n  | cxt_setfield2 : forall o f e E ae,\n      val o ->\n      decompose f E ae ->\n      decompose (exp_setfield o f e) (E_setfield2 o E e) ae\n  | cxt_setfield3 : forall o f e E ae,\n      val o -> val f ->\n      decompose e E ae ->\n      decompose (exp_setfield o f e) (E_setfield3 o f E) ae\n  | cxt_delfield1 : forall o f E ae,\n      decompose o E ae ->\n      decompose (exp_delfield o f) (E_delfield1 E f) ae\n  | cxt_delfield2 : forall o f E ae,\n      val o ->\n      decompose f E ae ->\n      decompose (exp_delfield o f) (E_delfield2 o E) ae\n.\n\nFixpoint plug (e : exp) (cxt : E) := match cxt with\n  | E_hole => e\n  | E_app_1 cxt e2 => exp_app (plug e cxt) e2\n  | E_app_2 v cxt => exp_app v (plug e cxt)\n  | E_succ cxt => exp_succ (plug e cxt)\n  | E_not cxt => exp_not (plug e cxt)\n  | E_if cxt e1 e2 => exp_if (plug e cxt) e1 e2\n  | E_label x cxt => exp_label x (plug e cxt)\n  | E_break x cxt => exp_break x (plug e cxt)\n  | E_ref cxt => exp_ref (plug e cxt)\n  | E_deref cxt => exp_deref (plug e cxt)\n  | E_setref1 cxt e2 => exp_set (plug e cxt) e2\n  | E_setref2 v1 cxt => exp_set v1 (plug e cxt)\n  | E_catch cxt e2 => exp_catch (plug e cxt) e2\n  | E_throw cxt    => exp_throw (plug e cxt)\n  | E_seq cxt e2   => exp_seq (plug e cxt) e2\n  | E_finally cxt e2 => exp_finally (plug e cxt) e2\n  | E_obj vs es _ k cxt => exp_obj (vs++(k,plug e cxt)::es)\n  | E_getfield1 cxt f => exp_getfield (plug e cxt) f\n  | E_getfield2 v cxt => exp_getfield v (plug e cxt)\n  | E_setfield1 cxt f e' => exp_setfield (plug e cxt) f e'\n  | E_setfield2 v cxt e' => exp_setfield v (plug e cxt) e'\n  | E_setfield3 v f cxt => exp_setfield v f (plug e cxt)\n  | E_delfield1 cxt f => exp_delfield (plug e cxt) f\n  | E_delfield2 v cxt => exp_delfield v (plug e cxt)\nend.\n\nFixpoint delta exp := match exp with\n  | exp_succ (exp_nat n) => exp_nat (S n)\n  | exp_not (exp_bool b) => exp_bool (negb b)\n  | _                    => exp_err\nend.\n\nInductive red :  exp -> exp -> Prop := \n  | red_succ : forall e, red (exp_succ e) (delta (exp_succ e))\n  | red_not  : forall e, red (exp_not e) (delta (exp_not e))\n  | red_if1  : forall e1 e2, red (exp_if (exp_bool true) e1 e2) e1\n  | red_if2  : forall e1 e2, red (exp_if (exp_bool false) e1 e2) e2\n  | red_app  : forall e v, \n      val v -> red (exp_app (exp_abs e) v) (open e v)\n  | red_app_err : forall v1 v2,\n      val v1 ->\n      val v2 ->\n      ~ tagof v1 TagAbs ->\n      red (exp_app v1 v2) exp_err\n  | red_if_err : forall v1 e2 e3,\n      val v1 ->\n      ~ tagof v1 TagBool ->\n      red (exp_if v1 e2 e3) exp_err\n  | red_label : forall x v,\n      val v -> red (exp_label x v) v\n  | red_break_bubble : forall x v e,\n    G e (exp_break x v) ->\n    red e (exp_break x v)\n  | red_break_match : forall x v,\n    red (exp_label x (exp_break x v)) v\n  | red_break_mismatch : forall x y v,\n    x <> y ->\n    red (exp_label x (exp_break y v)) (exp_break y v)\n  | red_set_err : forall v1 v2,\n      val v1 ->\n      val v2 ->\n      ~ tagof v1 TagLoc ->\n      red (exp_set v1 v2) exp_err\n  | red_deref_err : forall v,\n      val v ->\n      ~ tagof v TagLoc ->\n      red (exp_deref v) exp_err\n  | red_err_bubble : forall e,\n      F e exp_err ->\n      red e exp_err\n  | red_throw : forall v,\n      val v ->\n      red (exp_throw v) exp_err (* TODO: errors need carry values *)\n  | red_catch_normal : forall v e,\n      val v ->\n      red (exp_catch v e) v\n  | red_catch_catch : forall e,\n      red (exp_catch exp_err e) (open e (exp_nat 0)) (* TODO: err vals *)\n  | red_seq : forall e v,\n      val v ->\n      red (exp_seq v e) e\n  | red_finally_normal : forall v e,\n      val v ->\n      red (exp_finally v e) (exp_seq e v)\n  | red_finally_propagate_err : forall e ,\n      red (exp_finally exp_err e) (exp_seq e exp_err)\n  | red_finally_propagate_break : forall x v e,\n      val v ->\n      red (exp_finally (exp_break x v) e) (exp_seq e (exp_break x v))\n  | red_getfield : forall l f,\n      val (exp_obj l) ->\n      In f (fieldnames l) ->\n      red (exp_getfield (exp_obj l) (exp_string f)) (lookup_assoc l f exp_err string_eq_dec)\n  | red_getfield_notfound : forall l f,\n      val (exp_obj l) ->\n      ~ In f (fieldnames l) -> ~ In __proto__ (fieldnames l) ->\n      red (exp_getfield (exp_obj l) (exp_string f)) exp_undef\n  | red_getfield_proto : forall l f,\n      val (exp_obj l) ->\n      ~ In f (fieldnames l) ->\n      In __proto__ (fieldnames l) ->\n      red (exp_getfield (exp_obj l) (exp_string f)) \n        (exp_getfield (exp_deref (exp_getfield (exp_obj l) (exp_string __proto__))) (exp_string f))\n  | red_getfield_err_notobj : forall v f,\n      val v -> ~ tagof v TagObj -> red (exp_getfield v f) exp_err\n  | red_getfield_err_notstr : forall v f,\n      val v -> val f -> ~ tagof f TagString -> red (exp_getfield v f) exp_err\n  | red_setfield_update : forall l f v,\n      val (exp_obj l) ->\n      val v ->\n      In f (fieldnames l) ->\n      red (exp_setfield (exp_obj l) (exp_string f) v) (exp_obj (update_assoc l f v string_eq_dec))\n  | red_setfield_add : forall l f v,\n      val (exp_obj l) ->\n      val v ->\n      ~ In f (fieldnames l) ->\n      red (exp_setfield (exp_obj l) (exp_string f) v) (exp_obj ((f,v)::l))\n  | red_setfield_err_notobj : forall v f e,\n      val v -> ~ tagof v TagObj -> red (exp_setfield v f e) exp_err\n  | red_setfield_err_notstr : forall v f e,\n      val v -> val f -> ~ tagof f TagString -> red (exp_setfield v f e) exp_err\n  | red_delfield : forall l f,\n      val (exp_obj l) ->\n      In f (fieldnames l) ->\n      red (exp_delfield (exp_obj l) (exp_string f)) \n        (exp_obj (remove_fst f l string_eq_dec))\n  | red_delfield_notfound : forall l f,\n      val (exp_obj l) ->\n      ~ In f (fieldnames l) ->\n      red (exp_delfield (exp_obj l) (exp_string f)) (exp_obj l)\n  | red_delfield_err_notobj : forall v f,\n      val v -> ~ tagof v TagObj -> red (exp_delfield v f) exp_err\n  | red_delfield_err_notstr : forall v f,\n      val v -> val f -> ~ tagof f TagString -> red (exp_delfield v f) exp_err\n.\n\nInductive step : sto -> exp -> sto -> exp -> Prop :=\n  | step_red : forall s e E ae e',\n    lc e ->\n    decompose e E ae ->\n    red ae e' ->\n    step s e s (plug e' E)\n  | step_ref : forall E e v l s (pf : val v),\n    lc e ->\n    decompose e E (exp_ref v) ->\n    ~ In l (map (@fst AtomEnv.key stored_val) (AtomEnv.elements s)) ->\n    step s e (AtomEnv.add l (val_with_proof pf) s) (plug (exp_loc l) E)\n  | step_deref : forall e s E l v (pf : val v),\n    lc e ->\n    decompose e E (exp_deref (exp_loc l)) ->\n    AtomEnv.find l s = Some (val_with_proof pf) ->\n    step s e s (plug v E)\n  | step_deref_err : forall e s E l,\n    lc e ->\n    decompose e E (exp_deref (exp_loc l)) ->\n    AtomEnv.find l s = None ->\n    step s e s (plug exp_err E)\n  | step_setref : forall s e E l v v_old (pf_v : val v) (pf_v_old : val v_old),\n    lc e ->\n    decompose e E (exp_set (exp_loc l) v) ->\n    AtomEnv.find l s = Some (val_with_proof pf_v_old) ->\n    step s e (AtomEnv.add l (val_with_proof pf_v) s) (plug (exp_loc l) E)\n  | step_setref_err : forall s e E l v,\n    lc e ->\n    decompose e E (exp_set (exp_loc l) v) ->\n    AtomEnv.find l s = None ->\n    step s e s (plug exp_err E)\n  | step_err : forall x v s,\n      val v ->\n      step s (exp_break x v) s exp_err\n.\n\nEnd Definitions.\n\nTactic Notation \"exp_cases\" tactic(first) ident(c) :=\n  first;\n    [ Case_aux c \"exp_fvar\"\n    | Case_aux c \"exp_bvar\"\n    | Case_aux c \"exp_abs\"\n    | Case_aux c \"exp_app\"\n    | Case_aux c \"exp_nat\"\n    | Case_aux c \"exp_succ\"\n    | Case_aux c \"exp_bool\"\n    | Case_aux c \"exp_string\"\n    | Case_aux c \"exp_undef\"\n    | Case_aux c \"exp_null\"\n    | Case_aux c \"exp_not\"\n    | Case_aux c \"exp_if\"\n    | Case_aux c \"exp_err\"\n    | Case_aux c \"exp_label\"\n    | Case_aux c \"exp_break\"\n    | Case_aux c \"exp_loc\"\n    | Case_aux c \"exp_ref\"\n    | Case_aux c \"exp_deref\"\n    | Case_aux c \"exp_set\"\n    | Case_aux c \"exp_catch\"\n    | Case_aux c \"exp_throw\"\n    | Case_aux c \"exp_seq\"\n    | Case_aux c \"exp_finally\"\n    | Case_aux c \"exp_obj\"\n    | Case_aux c \"exp_getfield\"\n    | Case_aux c \"exp_setfield\"\n    | Case_aux c \"exp_delfield\"\n ].\nTactic Notation \"lc_cases\" tactic(first) ident(c) :=\n  first;\n    [ Case_aux c \"lc_fvar\"\n    | Case_aux c \"lc_bvar\"\n    | Case_aux c \"lc_abs\"\n    | Case_aux c \"lc_app\"\n    | Case_aux c \"lc_nat\"\n    | Case_aux c \"lc_succ\"\n    | Case_aux c \"lc_bool\"\n    | Case_aux c \"lc_string\"\n    | Case_aux c \"lc_undef\"\n    | Case_aux c \"lc_null\"\n    | Case_aux c \"lc_not\"\n    | Case_aux c \"lc_if\"\n    | Case_aux c \"lc_err\"\n    | Case_aux c \"lc_label\"\n    | Case_aux c \"lc_break\"\n    | Case_aux c \"lc_loc\"\n    | Case_aux c \"lc_ref\"\n    | Case_aux c \"lc_deref\"\n    | Case_aux c \"lc_set\"\n    | Case_aux c \"lc_catch\"\n    | Case_aux c \"lc_throw\"\n    | Case_aux c \"lc_seq\"\n    | Case_aux c \"lc_finally\"\n    | Case_aux c \"lc_obj\" \n    | Case_aux c \"lc_getfield\"\n    | Case_aux c \"lc_setfield\"\n    | Case_aux c \"lc_delfield\"\n].\nTactic Notation \"val_cases\" tactic(first) ident(c) :=\n  first;\n    [ Case_aux c \"val_abs\"\n    | Case_aux c \"val_nat\"\n    | Case_aux c \"val_fvar\"\n    | Case_aux c \"val_bool\"\n    | Case_aux c \"val_string\"\n    | Case_aux c \"val_undef\"\n    | Case_aux c \"val_null\"\n    | Case_aux c \"val_loc\"\n    | Case_aux c \"val_obj\" ].\nTactic Notation \"E_cases\" tactic(first) ident(c) :=\n  first;\n    [ Case_aux c \"E_hole\"\n    | Case_aux c \"E_app_1\"\n    | Case_aux c \"E_app_2\"\n    | Case_aux c \"E_succ\"\n    | Case_aux c \"E_not\"\n    | Case_aux c \"E_if\"\n    | Case_aux c \"E_label\"\n    | Case_aux c \"E_break\"\n    | Case_aux c \"E_ref\"\n    | Case_aux c \"E_deref\"\n    | Case_aux c \"E_setref1\"\n    | Case_aux c \"E_setref2\"\n    | Case_aux c \"E_seq\"\n    | Case_aux c \"E_finally\"\n    | Case_aux c \"E_obj\"\n    | Case_aux c \"E_getfield1\"\n    | Case_aux c \"E_getfield2\"\n    | Case_aux c \"E_setfield1\"\n    | Case_aux c \"E_setfield2\"\n    | Case_aux c \"E_setfield3\"\n    | Case_aux c \"E_delfield1\"\n    | Case_aux c \"E_delfield2\"\n ].\nTactic Notation \"redex_cases\" tactic(first) ident(c) :=\n  first;\n    [ Case_aux c \"redex_app\"\n    | Case_aux c \"redex_succ\"\n    | Case_aux c \"redex_not\"\n    | Case_aux c \"redex_if\"\n    | Case_aux c \"redex_label\"\n    | Case_aux c \"redex_break\"\n    | Case_aux c \"redex_ref\"\n    | Case_aux c \"redex_deref\"\n    | Case_aux c \"redex_set\"\n    | Case_aux c \"redex_uncatch\"\n    | Case_aux c \"redex_catch\"\n    | Case_aux c \"redex_throw\"\n    | Case_aux c \"redex_seq\"\n    | Case_aux c \"redex_finally\" \n    | Case_aux c \"redex_finally_err\" \n    | Case_aux c \"redex_err_bubble\" \n    | Case_aux c \"redex_getfield\"\n    | Case_aux c \"redex_setfield\"\n    | Case_aux c \"redex_delfield\"\n].\nTactic Notation \"decompose_cases\" tactic(first) ident(c) :=\n  first;\n    [ Case_aux c \"decompose_hole\"\n    | Case_aux c \"decompose_app_1\"\n    | Case_aux c \"decompose_app_2\"\n    | Case_aux c \"decompose_succ\"\n    | Case_aux c \"decompose_not\"\n    | Case_aux c \"decompose_if\"\n    | Case_aux c \"decompose_break\"\n    | Case_aux c \"decompose_label\"\n    | Case_aux c \"decompose_ref\"\n    | Case_aux c \"decompose_deref\"\n    | Case_aux c \"decompose_set1\"\n    | Case_aux c \"decompose_set2\" \n    | Case_aux c \"decompose_throw\"\n    | Case_aux c \"decompose_catch\"\n    | Case_aux c \"decompose_seq\"\n    | Case_aux c \"decompose_finally\"\n    | Case_aux c \"decompose_obj\"\n    | Case_aux c \"decompose_getfield1\"\n    | Case_aux c \"decompose_getfield2\"\n    | Case_aux c \"decompose_setfield1\"\n    | Case_aux c \"decompose_setfield2\"\n    | Case_aux c \"decompose_setfield3\"\n    | Case_aux c \"decompose_delfield1\" \n    | Case_aux c \"decompose_delfield2\" \n].\nTactic Notation \"decompose1_cases\" tactic(first) ident(c) :=\n  first;\n    [ Case_aux c \"decompose1_hole\"\n    | Case_aux c \"decompose1_app_1\"\n    | Case_aux c \"decompose1_app_2\"\n    | Case_aux c \"decompose1_succ\"\n    | Case_aux c \"decompose1_not\"\n    | Case_aux c \"decompose1_if\"\n    | Case_aux c \"decompose1_break\"\n    | Case_aux c \"decompose1_ref\"\n    | Case_aux c \"decompose1_deref\"\n    | Case_aux c \"decompose1_set1\"\n    | Case_aux c \"decompose1_set2\"\n    | Case_aux c \"decompose1_throw\"\n    | Case_aux c \"decompose1_seq\"\n    | Case_aux c \"decompose1_obj\" \n    | Case_aux c \"decompose1_getfield1\" \n    | Case_aux c \"decompose1_getfield2\" \n    | Case_aux c \"decompose1_setfield1\" \n    | Case_aux c \"decompose1_setfield2\" \n    | Case_aux c \"decompose1_setfield3\" \n    | Case_aux c \"decompose1_delfield1\" \n    | Case_aux c \"decompose1_delfield2\" \n].\nTactic Notation \"red_cases\" tactic(first) ident(c) :=\n  first;\n    [ Case_aux c \"red_succ\"\n    | Case_aux c \"red_not\"\n    | Case_aux c \"red_if1\"\n    | Case_aux c \"red_if2\"\n    | Case_aux c \"red_app\"\n    | Case_aux c \"red_app_err\"\n    | Case_aux c \"red_if_err\"\n    | Case_aux c \"red_label\"\n    | Case_aux c \"red_break_bubble\"\n    | Case_aux c \"red_break_match\"\n    | Case_aux c \"red_break_mismatch\"\n    | Case_aux c \"red_set_err\"\n    | Case_aux c \"red_deref_err\"\n    | Case_aux c \"red_err_bubble\"\n    | Case_aux c \"red_throw\"\n    | Case_aux c \"red_catch_normal\"\n    | Case_aux c \"red_catch_catch\"\n    | Case_aux c \"red_seq\"\n    | Case_aux c \"red_finally_normal\"\n    | Case_aux c \"red_finally_propagate_err\"\n    | Case_aux c \"red_finally_propagate_break\" \n    | Case_aux c \"red_getfield\"\n    | Case_aux c \"red_getfield_notfound\"\n    | Case_aux c \"red_getfield_proto\"\n    | Case_aux c \"red_getfield_err_notobj\"\n    | Case_aux c \"red_getfield_err_notstr\"\n    | Case_aux c \"red_setfield_update\"\n    | Case_aux c \"red_setfield_add\"\n    | Case_aux c \"red_setfield_err_notobj\"\n    | Case_aux c \"red_setfield_err_notstr\"\n    | Case_aux c \"red_delfield\"\n    | Case_aux c \"red_delfield_notfound\"\n    | Case_aux c \"red_delfield_err_notobj\"\n    | Case_aux c \"red_delfield_err_notstr\"\n].\nTactic Notation \"step_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"step_red\"\n  | Case_aux c \"step_ref\"\n  | Case_aux c \"step_deref\"\n  | Case_aux c \"step_deref_err\"\n  | Case_aux c \"step_setref\"\n  | Case_aux c \"step_setref_err\" ].\n\nHint Unfold values fieldnames map_values.\nHint Unfold open lc.\nHint Constructors lc'.\nHint Resolve lc_val.\nHint Resolve lc_ascend.\nHint Constructors tagof tag.\nHint Constructors decompose E val exp ae exp val ae red\n                  step stored_val.\n\nLemma decompose_ae : forall e E e',\n  decompose e E e' -> ae e'.\nProof with auto. intros. induction H... Qed.\n\n\nLemma val_injective : forall e1 e2, e1 = e2 -> (val e1 <-> val e2).\nProof with eauto. intros; subst... tauto. Qed.\n\nLemma plug_ok : forall e E e',\n  decompose e E e' -> plug e' E = e.\nProof.\nintros. Print decompose.\ndecompose_cases (induction H) Case; simpl; try (auto || rewrite -> IHdecompose; auto).\nQed.\n\nLtac destruct_decomp e := match goal with\n  |  [ H : exists E : E, exists ae : exp, decompose e E ae |- _ ] =>\n       destruct H as [E [ae H]]\n  | _ => fail\nend.\n\n\n\nLemma decompose_lc : forall E e ae,\n  lc e ->\n  decompose e E ae ->\n  lc ae.\nProof. intros. decompose_cases (induction H0) Case; try solve [inversion H; eauto | auto].\nCase \"decompose_obj\".\n  apply IHdecompose. \n apply Forall_in with (l := values (vs ++ (k, e) :: es)).\n  unfold lc in H. inversion H.  auto.\n  unfold values; rewrite map_app; simpl; apply in_middle.\nQed.\n\nInductive val' : exp -> Prop :=\n  | val'_err : val' exp_err\n  | val'_val : forall v, val v -> val' v\n  | val'_break : forall x v, val v -> val' (exp_break x v)\n.\n\nLemma lc_val' : forall v, val' v -> lc' 0 v.\nProof with auto. intros. inversion H... Qed.\n\nHint Constructors val' E' F G. \n\nLtac clean_decomp := repeat match goal with\n  | [ H1 : ?cond, IH : ?cond -> ?exp |- _ ] => let H := fresh \"IH\" in\n    (assert exp as H by (apply IH; exact H1); clear IH)\n  | [ IH : 0 = 0 -> ?exp |- _ ]\n    => let H := fresh IH in\n       (assert exp as H by (apply IH; reflexivity); clear IH)\n  | [ IH : 1 = 0 -> _ |- _ ]\n    => clear IH\nend.\n\nLtac invert_val' := repeat match goal with\n  | [ IH : val' ?e |- _ ]\n    => (inversion IH; clear IH)\nend.\n\nLtac solve_break_err H e :=\n  let HV := fresh \"HV\" in \n  let HE := fresh \"HE\" in \n    destruct H as [HV | HE]; [idtac | destruct_decomp e; eauto 7];\n    subst; eauto; inversion HV; clear HV; eauto; \n      [ right; exists E_hole; eapply ex_intro; apply cxt_hole; \n        try solve [apply redex_err_bubble; auto | constructor; auto]\n      | subst\n      | right; exists E_hole; eapply ex_intro; apply cxt_hole; \n        match goal with \n        | [ H: exp_break ?x ?v = _ |- _] => try solve [apply redex_break with x v; auto; constructor; auto| constructor; auto]\n        end]. \n\nLemma decomp : forall e,\n  lc e -> val' e \\/ \n          (exists E, exists ae, decompose e E ae).\nProof with eauto 7.\nintros.\nunfold lc in H.\nremember 0.\nremember H as LC. clear HeqLC.\nmove H after LC.\nlc_cases (induction H) Case; intros; subst; clean_decomp; try solve [inversion LC; subst; repeat match goal with\n|  [ H :  lc' 0 ?e -> val' ?e \\/ _ ,\n          (* should be  val ?e' \\/ (exists (E : E) (ae : exp), decomposition ?e E ae), but coq8.4 chokes on it *)\n     HLC : lc' 0 ?e\n   |- _ ] => let H' := fresh in assert (H' := H HLC); clear H\n| [ LC1 : lc' _ ?e1, H : val' ?e1 \\/ _ |- val' (_ ?e1) \\/ _ ] => solve_break_err H e1\n| [ LC1 : lc' _ ?e1, H : val' ?e1 \\/ _ |- val' (_ ?e1 _) \\/ _ ] => solve_break_err H e1\n| [ LC2 : lc' _ ?e2, H : val' ?e2 \\/ _ |- val' (_ _ ?e2) \\/ _ ] => solve_break_err H e2\n| [ LC1 : lc' _ ?e1, H : val' ?e1 \\/ _ |- val' (_ ?e1 _ _) \\/ _ ] => solve_break_err H e1\n| [ LC2 : lc' _ ?e2, H : val' ?e2 \\/ _ |- val' (_ _ ?e2 _) \\/ _ ] => solve_break_err H e2\n| [ LC3 : lc' _ ?e3, H : val' ?e3 \\/ _ |- val' (_ _ _ ?e3) \\/ _ ] => solve_break_err H e3\nend; eauto 7].\nCase \"lc_bvar\".\n  inversion H.\nCase \"lc_break\".\n  inversion IH. \n    inversion H0. right. exists E_hole. repeat eapply ex_intro. apply cxt_hole. apply redex_err_bubble... left...\n    right. eapply ex_intro; eapply ex_intro; apply cxt_hole. eapply redex_break...\n  destruct_decomp e. right; exists (E_break x E); exists ae; auto.\nCase \"lc_obj\".\n  assert (forall x : string * exp, In x l -> decidable (val (snd x))). intros; apply decide_val.\n  assert (Split := (take_while l (fun kv => val (snd kv)) H1)).\n  inversion Split. \n  SCase \"Everything in (exp_obj l) is already a value\".\n    left. constructor. constructor... unfold values; rewrite map_snd_snd_split. apply forall_snd_comm...\n  SCase \"Something in (exp_obj l) is not yet a value\".\n    inversion_clear H2. inversion_clear H3. \n    inversion_clear H2. inversion_clear H3. inversion_clear H4.\n    remember x1 as x1'; destruct x1'.\n    assert (Forall val (values x)). unfold values; rewrite map_snd_snd_split; apply forall_snd_comm...\n    assert (val' e \\/ (exists E, exists ae, decompose e E ae)).   \n      inversion LC. rewrite H2 in H0. rewrite map_snd_snd_split in H0. rewrite snd_split_comm in H0.\n      simpl in H0. rewrite forall_app in H0. inversion_clear H0. inversion_clear H11.\n      apply H0... rewrite Forall_forall in H9; apply H9. subst. unfold values. \n      rewrite map_snd_snd_split. rewrite snd_split_comm. simpl. apply in_middle. \n    inversion H6. \n      SSCase \"e is a val'\". invert_val'; subst.\n        SSSCase \"e is exp_err\". right.\n          exists E_hole. eapply ex_intro. apply cxt_hole. constructor. apply LC.\n          constructor. constructor; auto.\n        SSSCase \"e is a val\". contradiction. \n        SSSCase \"e is a break\".\n          right.\n          exists E_hole. eapply ex_intro. apply cxt_hole. \n          apply redex_break with (x := x2) (v := v). trivial.\n          constructor. constructor. trivial. auto.\n      SSCase \"e is not a val'\".\n        inversion H7. inversion H8. right. exists (E_obj x x0 H4 s x2). exists x3. \n        rewrite H2. apply cxt_obj...\nQed.\n\nHint Resolve decompose_lc.\nHint Unfold not.\n\n(* Invert tagof *)\nHint Extern 1 ( False ) => match goal with\n  | [ H: tagof _ _ |- False]  => inversion H\nend.\n\nLemma progress : forall sto e,\n  lc e ->\n<<<<<<< HEAD\n  val e \\/ (exists v, exists x, e = exp_break x v) \\/ (exists e', exists sto', step sto e sto' e').\n=======\n  val e \\/ e = exp_err \\/ (exists e', exists sto', step sto e sto' e').\n>>>>>>> a65558cc64374e77716c3e329d6c87553ea7f525\nProof with eauto.\nintros.\nremember H as HLC; clear HeqHLC.\napply decomp in H.\ndestruct H. destruct H...\nright. right. exists exp_err. exists sto0. auto.\ndestruct_decomp e...\nright. right.\nassert (LC.ae ae). apply decompose_ae in H...\n\n\ninversion H0; subst...\n(* redex_cases (inversion H0) Case; subst... *)\nCase \"redex_app\". val_cases (inversion H1) SCase; subst; eauto 6.\nCase \"redex_if\". val_cases (inversion H1) SCase; subst; first [destruct b; eauto 6 | eauto 6]. \nCase \"redex_label_break\".\n  assert ({ x = y } + { ~ x = y }). apply Atom.atom_eq_dec.\n  destruct H2; subst...\nCase \"redex_ref\".\nassert (exists l : atom, \n          ~ In l (map (@fst AtomEnv.key stored_val) (AtomEnv.elements sto0))) \n    as [l HnotInL].\n  apply Atom.atom_fresh_for_list.\nexists (plug (exp_loc l) E).\nexists (AtomEnv.add l (val_with_proof H1) sto0)...\nCase \"redex_deref\".\nval_cases (inversion H1) SCase; subst; try solve [ exists (plug exp_err E); eauto ].\n  SCase \"val_loc\". remember (AtomEnv.find l sto0) as MaybeV.\n  destruct MaybeV...\n  destruct s...\nCase \"redex_set\".\nval_cases (inversion H1) SCase; subst; try solve [ exists (plug exp_err E); eauto ].\n  SCase \"val_loc\". remember (AtomEnv.find l sto0) as MaybeV.\n  destruct MaybeV...\n  destruct s.\n  exists (plug (exp_loc l) E).\n  exists (AtomEnv.add l (val_with_proof H2) sto0)...\nCase \"redex_getfield\".\n  destruct (decide_tagof o TagObj).\n  inversion H3. destruct (decide_tagof f TagString). inversion H5. destruct (dec_in (fieldnames l) s). \n    exists (plug (lookup_assoc l s exp_err string_eq_dec) E); exists sto0. subst; eapply step_red... \n    destruct (dec_in (fieldnames l) __proto__).\n      exists (plug (exp_getfield (exp_deref (exp_getfield o (exp_string __proto__))) f) E); exists sto0. subst; eapply step_red...\n      exists (plug exp_undef E); exists sto0. subst; eapply step_red...\n    exists (plug exp_err E); exists sto0. subst; eapply step_red...\n  exists (plug exp_err E); exists sto0; subst; eapply step_red...\nCase \"redex_setfield\".\n  destruct (decide_tagof o TagObj).\n  inversion H4. destruct (decide_tagof f TagString). inversion H6. \n    destruct (dec_in (fieldnames l) s).\n      exists (plug (exp_obj (update_assoc l s e0 string_eq_dec)) E); exists sto0. subst; eapply step_red...\n      exists (plug (exp_obj ((s,e0)::l)) E); exists sto0. subst; eapply step_red...\n    exists (plug exp_err E); exists sto0. subst; eapply step_red...\n  exists (plug exp_err E); exists sto0; subst; eapply step_red...\nCase \"redex_delfield\".\n  destruct (decide_tagof o TagObj).\n  inversion H3. destruct (decide_tagof f TagString). inversion H5.\n    destruct (dec_in (fieldnames l) s). \n      exists (plug (exp_obj (remove_fst s l string_eq_dec)) E); exists sto0. subst; eapply step_red... \n      exists (plug o E); exists sto0. subst; eapply step_red...\n    exists (plug exp_err E); exists sto0; subst; eapply step_red...\n  exists (plug exp_err E); exists sto0; subst; eapply step_red...\nQed.\n\nLtac solve_lc_plug := match goal with\n  | [ IHdecompose : lc' 0 ?e -> lc' 0 (plug ?e' ?E),\n      H : lc' 0 ?e\n      |- context [plug ?e' ?E] ]\n    => (apply IHdecompose in H; auto)\nend.\n\nLemma lc_plug : forall E ae e e',\n  lc e ->\n  lc e' ->\n  decompose e E ae ->\n  lc (plug e' E).\nProof with auto.\nintros.\ndecompose_cases (induction H1) Case;\n first [ inversion H; subst; simpl; unfold lc in *; constructor ; try solve_lc_plug; auto | auto ]. \nCase \"decompose_obj\".\n  SCase \"Proving NoDup of fieldnames after plugging\".\n  unfold fieldnames in *. rewrite map_fst_fst_split. rewrite fst_split_comm. simpl.\n  rewrite map_fst_fst_split in H3; rewrite fst_split_comm in H3; simpl in H3...\n  SCase \"Proving all are values after plugging\".\n  unfold values in *. rewrite map_snd_snd_split; rewrite snd_split_comm; simpl.\n  rewrite map_snd_snd_split in H5; rewrite snd_split_comm in H5; simpl in H5...\n  rewrite forall_app. rewrite forall_app in H5. inversion H5. split... inversion H4... \nQed.\n\nHint Resolve lc_plug.\n\nLemma lc_active : forall e,\n  ae e -> lc e.\nProof with eauto.\n  intros.\n  remember H.\n  unfold lc.\n  clear Heqa.\n  inversion a; try solve [constructor; eauto using lc_val].\n\n  subst. inversion H1; subst... inversion H2; subst...\n  trivial.\nQed.\n\nHint Resolve lc_active.\n\nLemma lc_open : forall k e u,\n  lc' (S k) e ->\n  lc' 0 u ->\n  lc' k (open_rec k u e).\nProof with auto.\nintros.\ngeneralize dependent k.\nexp_cases (induction e) Case; intros; try solve [simpl; inversion H; subst;  eauto].\nCase \"exp_bvar\".\n  simpl. \n  assert (H1 := Coq.Arith.Compare_dec.lt_eq_lt_dec k n).\n  destruct H1. destruct s.\n  SCase \"k < n\".\n    inversion H. subst. assert (beq_nat k n = false). rewrite -> beq_nat_false_iff. omega. rewrite -> H1. apply lc_ascend with (k := S k). omega. exact H.\n  SCase \"k = n\". \n    rewrite <- beq_nat_true_iff in e.\n    rewrite -> e.  apply lc_ascend with (k := 0) (k' := k)... omega.\n  SCase \"k > n\". Check beq_nat.\n    assert (beq_nat k n = false). rewrite -> beq_nat_false_iff... omega.\n    rewrite -> H1...\nCase \"exp_obj\".\n  simpl. unfold map_values. apply forall_map_comm in H. constructor. \n  SCase \"NoDup\". \n    inversion H1. unfold fieldnames in *. rewrite map_fst_fst_split in *.\n    rewrite fst_split_map_snd...\n  SCase \"values\". \n    unfold values. apply forall_map_comm. apply forall_map_comm. simpl. \n    rewrite Forall_forall. rewrite Forall_forall in H.\n    intros. apply H... inversion H1. rewrite Forall_forall in H6. apply H6. \n    destruct x as (s, e). subst. unfold values. rewrite map_snd_snd_split. apply in_split_r...\nQed.\n\n\nLemma lc_red : forall ae e,\n  lc ae ->\n  red ae e ->\n  lc e.\nProof with auto.\nintros.\nred_cases (destruct H0) Case; try solve [auto | inversion H; auto].\nCase \"red_succ\". simpl. exp_cases (destruct e) SCase; auto.\nCase \"red_not\". simpl. exp_cases (destruct e) SCase; auto.\nCase \"red_app\".\n  unfold lc in *.\n  inversion H; subst.\n  unfold open.\n  inversion H4; subst.\n  apply lc_open. exact H3. exact H5.\nCase \"red_break_bubble\".\n  inversion H0; subst... inversion H1; subst...\n  inversion H3; subst... \n  unfold values in H7.\n  rewrite map_app in H7.\n  rewrite forall_app in H7. \n  destruct H7.\n  inversion H6.\n  trivial.\nCase \"red_break_match\".\n  inversion H; inversion H2; subst...\nCase \"red_catch_catch\".\n  unfold lc in *.\n  inversion H; subst.\n  unfold open.\n  apply lc_open...\nCase \"red_getfield\".\n  induction l. inversion H1.\n  destruct a as (astr, aexp). simpl.\n  destruct (string_eq_dec f astr). inversion H0. simpl in H3. inversion H3. apply lc_val...\n  apply IHl. inversion H. inversion H5. simpl in *. inversion H8. inversion H10. subst.\n  constructor...\n  inversion H0. inversion H3. constructor... inversion H4...\n  inversion H1. simpl in H2. symmetry in H2; contradiction. auto.\nCase \"red_setfield_update\".\n  induction l. inversion H2.\n  destruct a as (astr, aexp). simpl.\n  destruct (string_eq_dec f astr). inversion H. subst. inversion H7. simpl in H6. inversion H6. subst.\n  constructor... constructor...\n  constructor... simpl. \n  unfold fieldnames in *; rewrite <- update_fieldnames_eq. inversion H0. simpl in H5...\n  constructor. inversion H. inversion H7; subst. simpl; simpl in H13; inversion H13...\n  fold (map (@snd string exp) (update_assoc l f v string_eq_dec)); apply update_values_eq. inversion H0. inversion H4. rewrite Forall_forall in *; subst; intros. apply lc_val... apply lc_val...\nCase \"red_setfield_add\".\n  constructor. simpl. constructor... inversion H0... simpl. constructor... inversion H0...\n  rewrite Forall_forall in H4; apply Forall_forall; intros; apply lc_val...\nCase \"red_delfield\".\n  unfold fieldnames in H1; rewrite map_fst_fst_split in H1; apply (in_split_fst f l) in H1. \n  inversion_clear H1; inversion_clear H2; inversion_clear H1. subst.  \n  inversion_clear H; clear H2; inversion_clear H1; subst. unfold fieldnames in H; rewrite map_fst_fst_split in H.  \n  rewrite fst_split_comm in H. assert (ND1 := NoDup_remove_1 (fst (split x)) (fst (split x0)) f H).\n  assert (ND2 := NoDup_remove_2 (fst (split x)) (fst (split x0)) f H).\n  assert (~ (In f (fst (split x)) \\/ In f (fst (split x0)))).\n  intro. apply (in_or_app (fst (split x)) (fst (split x0)) f) in H1. contradiction. \n  assert (~ In f (fst (split x))). intro; apply H1; left...\n  assert (~ In f (fst (split x0))). intro; apply H1; right... clear ND2. clear H1.\n  constructor. \n  rewrite remove_app_comm. unfold fieldnames. rewrite map_fst_fst_split. \n  rewrite fst_split_comm2. rewrite fst_split_comm2. simpl. destruct (string_eq_dec f f). simpl.\n  rewrite (not_in_remove_eq f x string_eq_dec H3) in ND1. \n  rewrite (not_in_remove_eq f x0 string_eq_dec H4) in ND1...\n  rewrite (not_in_remove_eq f x string_eq_dec H3) in H.\n  rewrite (not_in_remove_eq f x0 string_eq_dec H4) in H...\n  rewrite Forall_forall in H2. rewrite Forall_forall; intros. rewrite remove_app_comm in H1.\n  unfold values in H1. rewrite map_snd_snd_split in H1.\n  rewrite snd_split_comm2 in H1; rewrite snd_split_comm2 in H1.\n  apply in_app_or in H1. inversion_clear H1. apply H2. unfold values. rewrite map_snd_snd_split.\n  rewrite snd_split_comm. apply in_or_app. left. rewrite (not_in_remove_eq f x string_eq_dec H3)...\n  apply in_app_or in H5. inversion_clear H5. simpl in H1. destruct (string_eq_dec f f). inversion H1. \n  unfold not in n. assert False. apply n... contradiction.\n  apply H2. unfold values. rewrite map_snd_snd_split. rewrite snd_split_comm. apply in_or_app. right.\n  right. rewrite (not_in_remove_eq f x0 string_eq_dec H4)...\nQed.\n\nLemma preservation : forall sto1 e1 sto2 e2,\n  lc e1 ->\n  step sto1 e1 sto2 e2 ->\n  lc e2.\nProof with auto.\nintros.\nunfold lc in *.\ndestruct H0. (* step_cases (destruct H0) Case.  *)\nCase \"step_red\".\n  apply lc_red in H2... apply lc_plug with (ae := ae0) (e := e)...\n  apply lc_active. apply decompose_ae with (e := e) (E := E0)...\nCase \"step_ref\".\n  apply lc_plug with (e := e) (ae := exp_ref v)...\nCase \"step_deref\".\n  apply lc_plug with (e := e) (ae := exp_deref (exp_loc l))...\nCase \"step_deref_err\".\n  apply lc_plug with (e := e) (ae := exp_deref (exp_loc l))...\nCase \"step_setref\".\n  apply lc_plug with (e := e) (ae := exp_set (exp_loc l) v)...\nCase \"step_setref_err\".\n  apply lc_plug with (e := e) (ae := exp_set (exp_loc l) v)...\nCase \"step_break\".\n  trivial.\nQed.\n\nEnd LC.\n", "meta": {"author": "brownplt", "repo": "lambdajs-coq", "sha": "820abb7b49a8c97b6f5110200d7c6d9040278a80", "save_path": "github-repos/coq/brownplt-lambdajs-coq", "path": "github-repos/coq/brownplt-lambdajs-coq/lambdajs-coq-820abb7b49a8c97b6f5110200d7c6d9040278a80/LambdaJS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2473054883831013}}
{"text": "From Coq Require Export\n     Morphisms\n     Setoid\n     Program.Equality\n     Lists.List\n     Logic.EqdepFacts\n     Eqdep EqdepFacts\n    \n.\nRequire Import  ExtLib.Structures.Monad.\nFrom EnTree Require Import\n     Basics.HeterogeneousRelations\n     Basics.QuantType\n     Core.EnTreeDefinition\n     Core.SubEvent\n     Ref.EnTreeSpecDefinition\n     Ref.EnTreeSpecFacts\n     Ref.EnTreeSpecCombinatorFacts\n     Ref.SpecM\n     Eq.Eqit\n     Ref.MRecSpec\n     Ref.SpecMFacts\n     Ref.Automation\n     Ref.RecSpecFix\n.\nOpen Scope entree_scope.\nImport Monad.\nImport MonadNotation.\nLocal Open Scope monad_scope.\nFrom Paco Require Import paco.\nFixpoint trepeat {E R: Type} `{EncodingType E} (n : nat) (t : entree E R) :=\n  match n with\n  | 0 => ret tt\n  | S n => t;; trepeat n t end.\n\nSection total_spec_fix.\nContext {A B : Type} `{QuantType A} `{QuantType B}.\nContext {E : Type} `{EncodingType E}.\n\nContext (Pre : A -> Prop) (Post : A -> B -> Prop).\n\n\nDefinition total_spec' (a : A) : entree_spec E B :=\n  assume_spec (Pre a);;\n  b <- exists_spec B;;\n  assert_spec (Post a b);;\n  ret b.\n  \n\nContext (Rdec : Rel A A).\nContext (Hwf : well_founded Rdec).\n\nDefinition total_spec_fix : A -> entree_spec E B :=\n  rec_fix_spec \n    (fun rec a =>\n       assume_spec (Pre a);;\n       n <- exists_spec nat;;\n       trepeat n (\n         a' <- exists_spec A;;\n         assert_spec (Pre a' /\\ Rdec a' a);;\n         rec a');;\n       b <- exists_spec B;;\n       assert_spec (Post a b);;\n       ret b\n    ).\nTheorem total_spec_fix_refines_total_spec' (a : A) : strict_refines (total_spec_fix a) (total_spec' a).\nProof.\n  revert a. eapply well_founded_ind; eauto.\n  intros a Hind. unfold total_spec_fix, total_spec'.\n  quantr. intros. quantl. auto.\n  match goal with |- padded_refines eq PostRelEq eq (interp_mrec_spec ?b _ ) _ => set b as body end.\n  quantl. intros n. induction n.\n  - cbn. quantl. intros b. quantr. exists b. quantl. intros. quantr. auto.\n    apply padded_refines_ret. auto.\n  - cbn. do 2 rewrite interp_mrec_spec_bind. repeat apply padded_refines_bind_bind_l.\n    match goal with |- padded_refines eq PostRelEq eq _ ?t => assert (t ≅ Ret tt;; t) end.\n    cbn. \n    (* some rewriting fails here for some reason *)\n    { pstep. red. cbn. rewrite itree_eta' at 1. rewrite itree_eta'. pstep_reverse.\n      apply Reflexive_eqit. auto. }\n    rewrite H3. eapply padded_refines_bind with (RR := fun _ _ => True).\n    + quantl. intros. quantl. intros [Hpre Hdec].\n      eapply padded_refines_weaken_l with (phi2 := total_spec' a0;; Ret tt).\n      * cbn. apply padded_refines_bind_bind_l.\n        quantl. auto. apply padded_refines_bind_bind_l.\n        quantl. intros. apply padded_refines_bind_bind_l. quantl.\n        intros. apply padded_refines_ret. auto.\n      * specialize (Hind a0 Hdec).\n        unfold call_spec. setoid_rewrite interp_mrec_spec_inl. rewrite tau_eutt.\n        rewrite interp_mrec_spec_bind. eapply padded_refines_bind; intros; try apply padded_refines_ret; eauto.\n    + intros b0 [] _. eapply padded_refines_weaken_l; try eapply IHn.\n      setoid_rewrite interp_mrec_spec_bind. \n      eapply padded_refines_bind; intros; subst; try reflexivity.\n      quantl. intros. cbn.  eapply interp_mrec_spec_exists_specr. Unshelve. 2: eauto. \n      quantl. intros. subst. quantr. auto. apply padded_refines_ret. auto.\nQed.\n\nEnd total_spec_fix.\n", "meta": {"author": "GaloisInc", "repo": "entree-specs", "sha": "52c4868f1f65c7ce74e90000214de27e23ba98fb", "save_path": "github-repos/coq/GaloisInc-entree-specs", "path": "github-repos/coq/GaloisInc-entree-specs/entree-specs-52c4868f1f65c7ce74e90000214de27e23ba98fb/theories/Ref/RecFixSpecTotal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2473054883831013}}
{"text": "Require Import Coq.Logic.Classical_Prop.\nRequire Import CompCert.Events.\nRequire Import CompCert.Smallstep.\nRequire Import CompCert.Behaviors.\nRequire Import Common.Definitions.\nRequire Import Common.Util.\nRequire Import Common.Linking.\nRequire Import Common.Memory.\nRequire Import Common.Reachability.\nRequire Import Common.RenamingOption.\nRequire Import Common.Values.\n(** From Renaming, only addr_shared_so_far and some tactics (like find_nil_rcons,\n    and find_rcons_rcons) are used. Consider refactoring them out\n    (into a file called Sharing.v, and into Common.Util)\n    to get rid of the dependency on Renaming.\n    Keep CSInvariants for only unary invariants; hence, do not depend on \"renaming\".\n*)\nRequire Import Common.Traces.\nRequire Import Common.TracesInform.\nRequire Import Common.CompCertExtensions.\nRequire Import Source.Language.\nRequire Import Source.GlobalEnv.\nRequire Import Source.CS.\nRequire Import Lib.Extra.\nRequire Import Lib.Monads.\n\nFrom mathcomp Require Import ssreflect eqtype ssrfun seq.\nFrom mathcomp Require ssrbool ssrnat.\nFrom extructures Require Import fmap fset.\n\nRequire Import Lia.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nSection Util.\n\n  Lemma starR_rcons:\n    forall (sem: semantics event) s1 s2 t1 e1,\n      single_events sem ->\n      starR (step sem) (globalenv sem) s1 (rcons t1 e1) s2 ->\n      exists st1 se1,\n        starR (step sem) (globalenv sem) s1 t1 st1 /\\\n        Step sem st1 [:: e1] se1 /\\\n        starR (step sem) (globalenv sem) se1 E0 s2.\n    intros ? ? ? ? ? Hsingle Hstar.\n    remember (rcons t1 e1) as t1_.\n    revert e1 t1 Heqt1_.\n    induction Hstar; intros; subst; unfold E0 in *; first by find_nil_rcons.\n    induction t1 using last_ind.\n    - unfold Eapp in *. rewrite app_nil_l in Heqt1_; subst.\n      pose proof (Hsingle _ _ _ H) as Hlength.\n      destruct t0; auto; simpl in *; auto.\n      + exists s2, s3; intuition. constructor.\n      + (** TODO: Use a \"length_size\" lemma. Get a contra in Hlength. *)\n        assert (forall (A: Type) l, size l = @length A l) as size_length.\n        {\n          induction l; auto.\n        }\n        rewrite <- size_length, size_rcons in Hlength. lia.\n    - specialize (IHHstar x t1 Logic.eq_refl) as [st1 [se1 [Ht2 [He1 Hnil]]]].\n      pose proof (Hsingle _ _ _ H) as Hlength.\n      destruct t2; auto; simpl in *.\n      + unfold Eapp in *. rewrite app_nil_r in Heqt1_. find_rcons_rcons.\n        do 2 eexists; intuition; eauto.\n        eapply starR_step; eauto.\n      + destruct t2; simpl in *; auto.\n        * unfold Eapp in *.\n          assert (e1 = e /\\ t0 = rcons t1 x) as [rewr1 rewr2]; subst.\n          {\n            rewrite <- cats1, <- catA, cats1, <- rcons_cat in Heqt1_.\n            find_rcons_rcons.\n              by rewrite cats1.\n          }\n          exists s2, s3; intuition. constructor.\n        * lia.\n  Qed.\n\nEnd Util.\n\n\nModule CSInvariants.\n\n(** Unary invariants about the source semantics *)\n\nImport Source.\n\nDefinition is_prefix (s: CS.state) (p: Source.program) t : Prop :=\n  Star (CS.sem p) (CS.initial_machine_state p) t s.\n\n\nInductive wf_ptr_wrt_cid_t (cid: Component.id) (t: trace event) : Pointer.t -> Prop\n  :=\n  | wf_ptr_own:\n      forall p b o,\n        wf_ptr_wrt_cid_t cid t (p, cid, b, o)\n  | wf_ptr_shared:\n      forall p c_other b o,\n      addr_shared_so_far (c_other, b) t -> wf_ptr_wrt_cid_t cid t (p, c_other, b, o)\n.\n\n\nInductive wf_load (pc_comp: Component.id) (t: trace event)\n          : Pointer.t -> Pointer.t -> Prop\n  :=\n  | private_stuff_from_corresp_private_addr:\n      forall load_at ptr,\n        ~ addr_shared_so_far (Pointer.component ptr, Pointer.block ptr) t ->\n        ~ addr_shared_so_far (Pointer.component load_at, Pointer.block load_at) t ->\n        Pointer.component ptr = Pointer.component load_at ->\n        wf_load pc_comp t load_at ptr\n  | shared_stuff_from_anywhere:\n      forall load_at ptr,\n        addr_shared_so_far (Pointer.component ptr, Pointer.block ptr) t ->\n        wf_load pc_comp t load_at ptr\n  | private_stuff_of_current_pc_from_shared_addr:\n      forall load_at ptr,\n        ~ addr_shared_so_far (Pointer.component ptr, Pointer.block ptr) t ->\n        Pointer.component ptr = pc_comp ->\n        addr_shared_so_far (Pointer.component load_at, Pointer.block load_at) t ->\n        wf_load pc_comp t load_at ptr.\n\nDefinition wf_mem_wrt_t_pc (mem: Memory.t) (t: trace event)\n           (pc_comp: Component.id) : Prop :=\nforall load_at ptr,\n  Memory.load mem load_at = Some (Ptr ptr) ->\n  Pointer.permission ptr = Permission.data ->\n  wf_load pc_comp t load_at ptr.\n\n  Fixpoint runtime_expr_struct_invariant\n           (e: expr) (val_test: value -> Prop) : Prop :=\n    match e with\n    | E_val v => val_test v\n    | E_binop _ e1 e2 =>\n      runtime_expr_struct_invariant e1 val_test /\\\n      runtime_expr_struct_invariant e2 val_test\n    | E_seq e1 e2 =>\n      runtime_expr_struct_invariant e1 val_test /\\\n      runtime_expr_struct_invariant e2 val_test\n    | E_if e1 e2 e3 =>\n      runtime_expr_struct_invariant e1 val_test /\\\n      runtime_expr_struct_invariant e2 val_test /\\\n      runtime_expr_struct_invariant e3 val_test\n    | E_alloc e =>\n      runtime_expr_struct_invariant e val_test\n    | E_deref e =>\n      runtime_expr_struct_invariant e val_test\n    | E_assign e1 e2 =>\n      runtime_expr_struct_invariant e1 val_test /\\\n      runtime_expr_struct_invariant e2 val_test\n    | E_call _ _ e =>\n      runtime_expr_struct_invariant e val_test\n    | E_callptr e1 e2 =>\n      runtime_expr_struct_invariant e1 val_test /\\\n      runtime_expr_struct_invariant e2 val_test\n    | E_funptr _\n    | E_arg\n    | E_local\n    | E_exit => true\n    end.\n\n  Fixpoint cont_struct_invariant (k: cont) (val_test: value -> Prop) : Prop :=\n    match k with\n    | Kbinop1 _ e k2 =>\n      runtime_expr_struct_invariant e val_test /\\\n      cont_struct_invariant k2 val_test\n    | Kbinop2 _ v k2 =>\n      val_test v /\\\n      cont_struct_invariant k2 val_test\n    | Kseq e k2 =>\n      runtime_expr_struct_invariant e val_test /\\\n      cont_struct_invariant k2 val_test\n    | Kif e1 e2 k3 =>\n      runtime_expr_struct_invariant e1 val_test /\\\n      runtime_expr_struct_invariant e2 val_test /\\\n      cont_struct_invariant k3 val_test\n    | Kalloc k2 =>\n      cont_struct_invariant k2 val_test\n    | Kderef k2 =>\n      cont_struct_invariant k2 val_test\n    | Kassign1 e k2 =>\n      runtime_expr_struct_invariant e val_test /\\\n      cont_struct_invariant k2 val_test\n    | Kassign2 v k2 =>\n      val_test v /\\\n      cont_struct_invariant k2 val_test\n    | Kcall _ _ k2 =>\n      cont_struct_invariant k2 val_test\n    | Kcallptr1 e k2 =>\n      runtime_expr_struct_invariant e val_test /\\\n      cont_struct_invariant k2 val_test\n    | Kcallptr2 v k2 =>\n      val_test v /\\\n      cont_struct_invariant k2 val_test\n    | Kstop => true\n    end.\n\nDefinition stack_struct_invariant (s: CS.stack) (frame_test: CS.frame -> Prop) : Prop :=\n    List.Forall (fun frm => frame_test frm) s.\n\nDefinition wf_expr_wrt_t_pc (e: expr) (t: trace event)\n           (pc_comp: Component.id): Prop :=\n  runtime_expr_struct_invariant\n    e\n    (fun v => forall ptr,\n         v = Ptr ptr ->\n         Pointer.permission ptr = Permission.data ->\n         wf_ptr_wrt_cid_t pc_comp t ptr).\n\nDefinition wf_cont_wrt_t_pc (k: cont) (t: trace event)\n           (pc_comp: Component.id): Prop :=\n  cont_struct_invariant\n    k\n    (fun v => forall ptr,\n         v = Ptr ptr ->\n         Pointer.permission ptr = Permission.data ->\n         wf_ptr_wrt_cid_t pc_comp t ptr).\n\nDefinition wf_frame_wrt_t t (frm: CS.frame) :=\n  let val_test :=\n      fun v =>\n        forall ptr,\n          v = Ptr ptr ->\n          Pointer.permission ptr = Permission.data ->\n          wf_ptr_wrt_cid_t (CS.f_component frm) t ptr\n  in\n  val_test (CS.f_arg frm)\n  /\\\n  cont_struct_invariant (CS.f_cont frm) val_test.\n\n\nDefinition wf_stack_wrt_t_pc (stk: CS.stack) (t: trace event) : Prop :=\n  stack_struct_invariant stk (wf_frame_wrt_t t).\n\nDefinition wf_state_t (s: CS.state) (t: trace event) : Prop :=\n  wf_expr_wrt_t_pc (CS.s_expr s) t (CS.s_component s) /\\\n  wf_mem_wrt_t_pc (CS.s_memory s) t (CS.s_component s) /\\\n  wf_cont_wrt_t_pc (CS.s_cont s) t (CS.s_component s) /\\\n  wf_stack_wrt_t_pc (CS.s_stack s) t /\\\n  (forall ptr,\n         CS.s_arg s = Ptr ptr ->\n         Pointer.permission ptr = Permission.data ->\n         wf_ptr_wrt_cid_t (CS.s_component s) t ptr).\n\nLemma initial_wf_mem p:\n  well_formed_program p ->\n  wf_mem_wrt_t_pc (prepare_buffers p) E0 Component.main.\nProof.\n  intros Hwf. constructor.\n  - unfold E0. intros contra; inversion contra; by find_nil_rcons.\n  - unfold E0. intros contra; inversion contra; by find_nil_rcons.\n  - unfold prepare_buffers in *. unfold Memory.load in *.\n    find_if_inside_hyp H; [|discriminate].\n    rewrite mapmE in H.\n    destruct (prog_buffers p (Pointer.component load_at)) as [buf|] eqn:ebuf;\n      [|discriminate]; simpl in H.\n    rewrite ComponentMemory.load_prealloc in H.\n    find_if_inside_hyp H; [|discriminate].\n    rewrite setmE in H.\n    find_if_inside_hyp H; [|discriminate].\n    destruct buf as [sz|chunk] eqn:ebuf2.\n    + find_if_inside_hyp H; discriminate.\n    + inversion Hwf.\n      assert (exists x, prog_interface p (Pointer.component load_at) = Some x)\n        as [? Hintf'].\n      {\n        apply/dommP. rewrite wfprog_defined_buffers0. apply/dommP. by eauto.\n      }\n      assert (Hintf: prog_interface p (Pointer.component load_at)). by rewrite Hintf'.\n      specialize (wfprog_well_formed_buffers0 _ Hintf) as [Hbuf1 Hbuf2].\n      rewrite ebuf in Hbuf2. simpl in *.\n      move : Hbuf2 => /andP => [[? G]]. move : G => /allP => G.\n      apply nth_error_In, In_in in H. by apply G in H.\nQed.\n\nLemma values_are_integers_expr_wrt_t_pc cur_comp expr:\n  values_are_integers expr ->\n  forall t,\n    wf_expr_wrt_t_pc expr t cur_comp.\nProof.\n  induction expr; auto; intros Hvalues t; inversion Hvalues; simpl in *; auto.\n  - destruct v; discriminate.\n  - move : Hvalues => /andP => [[G1 G2]].\n    constructor.\n    + apply IHexpr1; by auto.\n    + apply IHexpr2; by auto.\n  - move : Hvalues => /andP => [[G1 G2]].\n    constructor.\n    + apply IHexpr1; by auto.\n    + apply IHexpr2; by auto.\n  - move : Hvalues => /andP => [[G1 G2]].\n    move : G2 => /andP => [[G21 G22]].\n    constructor.\n    + apply IHexpr1; by auto.\n    + split; [apply IHexpr2|apply IHexpr3]; by auto.\n  - move : Hvalues => /andP => [[G1 G2]].\n    constructor.\n    + apply IHexpr1; by auto.\n    + apply IHexpr2; by auto.\n  - move : Hvalues => /andP => [[G1 G2]].\n    constructor.\n    + apply IHexpr1; by auto.\n    + apply IHexpr2; by auto.\nQed.\n\n(**Lemma wf_ptr_wrt_cid_t_rcons ptr t1 e,\n       Pointer.permission ptr = Permission.data -> wf_ptr_wrt_cid_t C t1 ptr\n  wf_ptr_wrt_cid_t C' (t1 ** [:: ECall C P v mem C']) ptr\n*)\nLemma runtime_expr_struct_invariant_rcons re C t1 e:\n  runtime_expr_struct_invariant\n    re\n    (fun v : value =>\n       forall ptr : Pointer.t,\n         v = Ptr ptr ->\n         Pointer.permission ptr = Permission.data -> wf_ptr_wrt_cid_t C t1 ptr) ->\n  runtime_expr_struct_invariant\n    re\n    (fun v0 : value =>\n       forall ptr : Pointer.t,\n         v0 = Ptr ptr ->\n         Pointer.permission ptr = Permission.data ->\n         wf_ptr_wrt_cid_t C (t1 ** [:: e]) ptr).\nProof.\n  intros; induction re; simpl in *; auto; intuition.\n  (* 1 goal remains *)\n  setoid_rewrite cats1.\n  destruct ptr as [[[pptr cptr] bptr] optr]. simpl in *; subst.\n  destruct (classic (addr_shared_so_far\n                       (cptr, bptr)\n                       (rcons t1 e)\n           )) as [ptrshr | ptrnotshr].\n  ** eapply wf_ptr_shared; by auto.\n  ** specialize (H _ Logic.eq_refl Logic.eq_refl).\n     inversion H; [by constructor|subst].\n     exfalso.\n     eapply ptrnotshr, reachable_from_previously_shared; [eassumption|].\n     constructor. by rewrite in_fset1.\nQed.\n\nLemma cont_struct_invariant_rcons k C t1 e:\n  cont_struct_invariant\n    k\n    (fun v : value =>\n       forall ptr : Pointer.t,\n         v = Ptr ptr -> Pointer.permission ptr = Permission.data ->\n         wf_ptr_wrt_cid_t C t1 ptr) ->\n  cont_struct_invariant\n    k\n    (fun v0 : value =>\n       forall ptr : Pointer.t,\n         v0 = Ptr ptr ->\n         Pointer.permission ptr = Permission.data ->\n         wf_ptr_wrt_cid_t C (t1 ** [:: e]) ptr).\nProof.\n  intros; induction k; simpl in *; auto; intuition;\n    try by apply runtime_expr_struct_invariant_rcons.\n  (** Refactor the \"-\" subgoal as a lemma on values *)\n  - setoid_rewrite cats1.\n    destruct ptr as [[[pptr cptr] bptr] optr]. simpl in *; subst.\n    destruct (classic (addr_shared_so_far\n                         (cptr, bptr)\n                         (rcons t1 e)\n             )) as [ptrshr | ptrnotshr].\n    ** eapply wf_ptr_shared; by auto.\n    ** specialize (H0 _ Logic.eq_refl Logic.eq_refl).\n       inversion H0; [by constructor|subst].\n       exfalso.\n       eapply ptrnotshr, reachable_from_previously_shared; [eassumption|].\n       constructor. by rewrite in_fset1.\n  - setoid_rewrite cats1.\n    destruct ptr as [[[pptr cptr] bptr] optr]. simpl in *; subst.\n    destruct (classic (addr_shared_so_far\n                         (cptr, bptr)\n                         (rcons t1 e)\n             )) as [ptrshr | ptrnotshr].\n    ** eapply wf_ptr_shared; by auto.\n    ** specialize (H0 _ Logic.eq_refl Logic.eq_refl).\n       inversion H0; [by constructor|subst].\n       exfalso.\n       eapply ptrnotshr, reachable_from_previously_shared; [eassumption|].\n       constructor. by rewrite in_fset1.\n  - setoid_rewrite cats1.\n    destruct ptr as [[[pptr cptr] bptr] optr]. simpl in *; subst.\n    destruct (classic (addr_shared_so_far\n                         (cptr, bptr)\n                         (rcons t1 e)\n             )) as [ptrshr | ptrnotshr].\n    ** eapply wf_ptr_shared; by auto.\n    ** specialize (H0 _ Logic.eq_refl Logic.eq_refl).\n       inversion H0; [by constructor|subst].\n       exfalso.\n       eapply ptrnotshr, reachable_from_previously_shared; [eassumption|].\n       constructor. by rewrite in_fset1.\nQed.\n\nLemma is_prefix_wf_state_t s p t:\n  closed_program p ->\n  well_formed_program p ->\n  is_prefix s p t ->\n  wf_state_t s t.\nProof.\n  unfold is_prefix. simpl.\n  intros Hclosed Hwf Hstar.\n  remember (prepare_global_env p) as G eqn:HG.\n  remember (CS.initial_machine_state p) as s0 eqn:Hs0.\n  revert HG Hs0.\n  apply star_iff_starR in Hstar.\n  induction Hstar as [| s0 t1 s1 t2 s2 t12 Hstar01 IHstar Hstep12 Ht12];\n    intros; subst.\n  - unfold CS.initial_machine_state.\n    inversion Hclosed. destruct (prog_main p) eqn:emain; [|discriminate].\n    constructor; simpl.\n    + apply values_are_integers_expr_wrt_t_pc. inversion Hwf. \n      specialize (wfprog_well_formed_procedures0 _ _ _ emain).\n      inversion wfprog_well_formed_procedures0. by intuition.\n    + split; [apply initial_wf_mem; assumption | split; by constructor].\n  - assert (IHstar_: wf_state_t s1 t1) by (apply IHstar; auto).\n    clear IHstar. unfold wf_state_t in IHstar_.\n    intuition. (** destructs IHstar_ recursively *)\n    inversion Hstep12; subst; (try rewrite E0_right);\n      unfold wf_state_t; simpl in *; try by intuition. \n    + (** KS_Binop1 *)\n      intuition.\n      (** wf_cont remains *)\n      inversion H.\n      constructor; [assumption|by unfold wf_cont_wrt_t_pc in H0].\n    + (** KS_Binop2 *)\n      intuition.\n      (** wf_cont remains *)\n      constructor; [by unfold wf_expr_wrt_t_pc in H |\n                    unfold wf_cont_wrt_t_pc in H0; by intuition].\n    + (** KS_BinopEval *)\n      intuition.\n      (** wf_expr remains *)\n      simpl in H.\n      unfold wf_cont_wrt_t_pc, wf_expr_wrt_t_pc in *. simpl in *.\n      destruct H0 as [Hv1 Hk].\n      clear -H Hv1.\n      (** TODO: Refactor as a lemma *)\n      intros ? Heval Hperm.\n      destruct op; simpl in *; auto.\n      * destruct v1 as [| [[[[] c1] b1] o1] |] eqn:ev1; try discriminate.\n        -- destruct v2 as [| [[[[] c2] b2] o2] |] eqn:ev2; simpl in *; inversion Heval;\n             simpl in *; subst; try discriminate.\n           specialize (H _ Logic.eq_refl Logic.eq_refl).\n           inversion H; subst; constructor; by auto.\n        -- destruct v2 as [| [[[[] c2] b2] o2] |] eqn:ev2; simpl in *; inversion Heval;\n             simpl in *; subst; discriminate.\n        -- destruct v2 as [| [[[[] c2] b2] o2] |] eqn:ev2; simpl in *; inversion Heval;\n             simpl in *; subst; try discriminate.\n           specialize (Hv1 _ Logic.eq_refl Logic.eq_refl).\n           inversion Hv1; subst; constructor; by auto.\n      * destruct v1 as [| [[[[] c1] b1] o1] |] eqn:ev1; try discriminate.\n        -- destruct v2 as [| [[[[] c2] b2] o2] |] eqn:ev2; simpl in *; inversion Heval;\n             simpl in *; subst; discriminate.\n        -- destruct v2 as [| [[[[] c2] b2] o2] |] eqn:ev2; simpl in *; inversion Heval;\n             simpl in *; subst; try discriminate.\n           find_if_inside_hyp Heval; discriminate.\n        -- destruct v2 as [| [[[[] c2] b2] o2] |] eqn:ev2; simpl in *; inversion Heval;\n             simpl in *; subst.\n           ++ specialize (Hv1 _ Logic.eq_refl Logic.eq_refl).\n              inversion Hv1; subst; constructor; by auto.\n           ++ find_if_inside_hyp Heval; discriminate.\n      * destruct v1 as [| [[[[] c1] b1] o1] |] eqn:ev1; try discriminate.\n        destruct v2 as [| [[[[] c1] b1] o1] |] eqn:ev2; discriminate.\n      * destruct v1 as [| [[[[] c1] b1] o1] |] eqn:ev1; try discriminate;\n          destruct v2 as [| [[[[] c2] b2] o2] |] eqn:ev2; discriminate.\n      * destruct v1 as [| [[[[] c1] b1] o1] |] eqn:ev1; try discriminate;\n          destruct v2 as [| [[[[] c2] b2] o2] |] eqn:ev2; try discriminate.\n        -- destruct (Pointer.leq (Permission.code, c1, b1, o1)\n                                 (Permission.code, c2, b2, o2)); discriminate.\n        -- destruct (Pointer.leq (Permission.data, c1, b1, o1)\n                                 (Permission.data, c2, b2, o2)); discriminate.\n    + (** KS_Seq1 *)\n      intuition.\n      (** wf_cont remains *)\n      inversion H.\n      constructor; assumption.\n    + (** KS_If1 *)\n      intuition.\n      (** wf_cont remains *)\n      inversion H. intuition.\n      constructor; intuition; assumption.\n    + (** KS_If2 *)\n      intuition.\n      (** wf_expr remains *)\n      inversion H0. intuition.\n      find_if_inside_goal; assumption.\n    + (** KS_Arg *)\n      intuition.\n      (** wf_expr remains *)\n      unfold wf_expr_wrt_t_pc. simpl. intros.\n      inversion H3. constructor.\n    + (** KS_AllocEval *)\n      intuition.\n      * (** wf_expr *)\n        apply Memory.component_of_alloc_ptr in H5. subst.\n        unfold wf_expr_wrt_t_pc. simpl. intros.\n        inversion H5; subst.\n        destruct ptr0 as [[[ ?] ?] ?]; simpl.\n        by constructor.\n      * (** wf_mem *)\n        unfold wf_mem_wrt_t_pc in H1.\n        intros ? ? Hload.\n        destruct ((Pointer.component load_at, Pointer.block load_at) ==\n                  (Pointer.component ptr, Pointer.block ptr)) eqn:e.\n        -- erewrite Memory.load_after_alloc_eq in Hload; eauto.\n           ++ repeat (find_if_inside_hyp Hload; [|discriminate]).\n              discriminate.\n           ++ by apply/eqP.\n        -- erewrite Memory.load_after_alloc in Hload; eauto.\n           apply/eqP. by rewrite e.\n    + (** KS_DerefEval *)\n      intuition.\n      (** wf_expr *)\n      unfold wf_expr_wrt_t_pc. simpl. intros ? ? Hperm. subst.\n      destruct ptr as [[[[] cloaded] bloaded] oloaded]; [discriminate|].\n      clear Hperm.\n      specialize (H1 _ _ H3 Logic.eq_refl).\n      unfold wf_expr_wrt_t_pc in H. simpl in H.\n      assert (P' = Permission.data).\n      { by apply Memory.load_some_permission in H3. }\n      subst.\n      specialize (H _ Logic.eq_refl Logic.eq_refl).\n      inversion H1; simpl in *; subst.\n      * inversion H; subst.\n        -- by constructor.\n        -- contradiction.\n      * by constructor.\n      * by constructor.\n    + (** KS_FunPtr *)\n      intuition.\n      unfold wf_expr_wrt_t_pc. simpl. intros ? inv contra. inversion inv. subst.\n      simpl in *. discriminate.\n    + (** KS_Assign1 *)\n      intuition.\n      (** wf_cont *)\n      constructor; simpl; inversion H; assumption.\n    + (** KS_Assign2 *)\n      intuition. inversion H0. constructor; assumption.\n    + (** KS_AssignEval *)\n      intuition.\n      * (** wf_expr *)\n        unfold wf_expr_wrt_t_pc. simpl. inversion H0; assumption.\n      * (** wf_mem *)\n        intros ? ? Hload Hperm.\n        destruct ptr as [[[[] cptr] bptr] optr]; [discriminate|]. clear Hperm.\n        erewrite Memory.load_after_store in Hload; [| by eauto].\n        assert (P' = Permission.data).\n        { by apply Memory.store_some_permission in H3. }\n        subst. unfold wf_expr_wrt_t_pc in H. simpl in H.\n        specialize (H _ Logic.eq_refl Logic.eq_refl). \n        inversion H0 as [Hv ?].\n        find_if_inside_hyp Hload.\n        -- move : e => /Pointer.eqP => ?. inversion Hload. subst.\n           specialize (Hv _ Logic.eq_refl Logic.eq_refl).\n           inversion Hv; subst.\n           ++ destruct (classic (addr_shared_so_far (cptr, bptr) t1))\n               as [ptrshr|ptrnotshr].\n              ** apply shared_stuff_from_anywhere; assumption.\n              ** destruct (classic (addr_shared_so_far (C', b') t1))\n                  as [C'b'shr|C'b'notshr].\n                 --- apply private_stuff_of_current_pc_from_shared_addr; by auto.\n                 --- apply private_stuff_from_corresp_private_addr; auto.\n                     inversion H; [by auto | contradiction].\n           ++ apply shared_stuff_from_anywhere; assumption.\n        -- apply H1; by auto.\n    + (** KS_InitCallPtr1 *)\n      intuition. inversion H.\n      constructor; assumption.\n    + (** KS_InitCallPtr2 *)\n      intuition. unfold wf_expr_wrt_t_pc in H. simpl in *.\n      inversion H0.\n      constructor; assumption.\n    + (** KS_InitCallPtr3 *)\n      intuition. inversion H0. assumption.\n    + (** KS_InternalCall *)\n      intuition.\n      * (** wf_expr *)\n        apply values_are_integers_expr_wrt_t_pc.\n        destruct Hwf.\n          by specialize (wfprog_well_formed_procedures0 _ _ _ H5) as [_ [? _]].\n      * (** wf_cont *)\n          by constructor.\n      * constructor; simpl; by intuition.\n    + (** KS_ExternalCall *)\n      intuition.\n      * (** wf_expr *)\n        apply values_are_integers_expr_wrt_t_pc.\n        destruct Hwf.\n          by specialize (wfprog_well_formed_procedures0 _ _ _ H6) as [_ [? _]].\n      * intros ? ? Hload Hperm.\n        destruct ptr as [[[[] cptr] bptr] optr]; [discriminate|]. clear Hperm.\n        destruct load_at as [[[ploadat cloadat] bloadat] oloadat].\n        assert (ploadat = Permission.data).\n        { by apply Memory.load_some_permission in Hload. }\n        subst.\n        setoid_rewrite cats1.\n        destruct (classic (addr_shared_so_far (cptr, bptr)\n                                              (rcons t1 (ECall C P v mem C'))))\n          as [ptrshr|ptrnotshr].\n        -- apply shared_stuff_from_anywhere; by auto.\n        -- destruct (cptr == C') eqn:ecptr.\n           ++ assert (cptr = C'). by apply/eqP. subst.\n              destruct (classic (addr_shared_so_far (cloadat, bloadat)\n                                                    (rcons t1 (ECall C P v mem C'))))\n                as [loadatshr|loadatnotshr].\n              ** apply private_stuff_of_current_pc_from_shared_addr; auto.\n              ** apply private_stuff_from_corresp_private_addr; auto. simpl.\n                 specialize (H1 _ _ Hload Logic.eq_refl). inversion H1; subst; auto.\n                 --- exfalso. apply ptrnotshr.\n                     eapply reachable_from_previously_shared; eauto. simpl.\n                     constructor. by rewrite in_fset1.\n                 --- exfalso. apply loadatnotshr.\n                     eapply reachable_from_previously_shared; eauto. simpl.\n                     constructor. by rewrite in_fset1.\n           ++ apply private_stuff_from_corresp_private_addr; simpl in *; auto; subst.\n              ** intros Hshraddr.\n                 apply ptrnotshr.\n                 eapply addr_shared_so_far_load_addr_shared_so_far; simpl; eauto.\n              ** specialize (H1 _ _ Hload Logic.eq_refl). inversion H1; subst; auto.\n                 --- exfalso. apply ptrnotshr.\n                     eapply reachable_from_previously_shared; eauto. simpl.\n                     constructor. by rewrite in_fset1.\n               --- exfalso. apply ptrnotshr.\n                   eapply addr_shared_so_far_load_addr_shared_so_far; simpl; eauto.\n                   +++\n                     eapply reachable_from_previously_shared; eauto. simpl.\n                     constructor. by rewrite in_fset1.\n                   +++ eassumption.\n      * (** wf_cont *)\n        constructor.\n      * (** wf_stack *)\n        constructor; intuition.\n        -- constructor; simpl in *.\n           ++ intros ? Hptr Hperm.\n              destruct ptr as [[[pptr cptr] bptr] optr].\n              simpl in *; subst.\n              specialize (H4 _ Logic.eq_refl Logic.eq_refl).\n              destruct (classic (addr_shared_so_far\n                                   (cptr, bptr)\n                                   (t1 ** [:: ECall C P v mem C'])\n                       )) as [ptrshr | ptrnotshr].\n              ** eapply wf_ptr_shared; by auto.\n              ** inversion H4; [by constructor|subst].\n                 setoid_rewrite cats1 in ptrnotshr.\n                 exfalso.\n                 eapply ptrnotshr, reachable_from_previously_shared; [eassumption|].\n                 constructor. by rewrite in_fset1.\n           ++ by apply cont_struct_invariant_rcons.\n        -- unfold wf_stack_wrt_t_pc, stack_struct_invariant in H2.\n           apply Forall_forall. erewrite Forall_forall in H2.\n           intros frm Hin. specialize (H2 frm Hin).\n           destruct H2 as [Hfrm1 Hfrm2].\n           split.\n           ++ intros ? Harg Hperm.\n              specialize (Hfrm1 _ Harg Hperm).\n              setoid_rewrite cats1.\n              destruct ptr as [[[pptr cptr] bptr] optr]. simpl in *; subst.\n              destruct (classic (addr_shared_so_far\n                                   (cptr, bptr)\n                                   (rcons t1 (ECall C P v mem C'))\n                       )) as [ptrshr | ptrnotshr].\n              ** eapply wf_ptr_shared; by auto.\n              ** inversion Hfrm1; [by constructor|subst].\n                 exfalso.\n                 eapply ptrnotshr, reachable_from_previously_shared; [eassumption|].\n                 constructor. by rewrite in_fset1.\n           ++ by apply cont_struct_invariant_rcons.\n      * (** wf_ptr *)\n        setoid_rewrite cats1.\n        destruct ptr as [[[pptr cptr] bptr] optr]. simpl in *; subst.\n        assert (G: addr_shared_so_far\n                     (cptr, bptr)\n                     (rcons t1\n                            (ECall C P (Ptr (Permission.data, cptr, bptr, optr)) mem C'))\n               ).\n        {\n          eapply reachable_from_args_is_shared; simpl.\n          constructor. by rewrite in_fset1.\n        }\n        constructor; by auto.\n    + (** KS_InternalReturn *)\n      intuition.\n      * (** wf_cont *)\n        inversion H2; subst. unfold wf_frame_wrt_t in H6.\n          by intuition.\n      * (** wf_stack *)\n        inversion H2; subst. by intuition.\n      * inversion H2; subst. unfold wf_frame_wrt_t in H8.\n          by intuition.\n    + (** KS_ExternalReturn *)\n      intuition.\n      * (** wf_expr *)\n        unfold wf_expr_wrt_t_pc. simpl. intros ? Hv Hperm.\n        setoid_rewrite cats1.\n        destruct ptr as [[[pptr cptr] bptr] optr]. simpl in *; subst.\n        assert (G: addr_shared_so_far\n                     (cptr, bptr)\n                     (rcons t1\n                            (ERet C (Ptr (Permission.data, cptr, bptr, optr)) mem C'))\n               ).\n        {\n          eapply reachable_from_args_is_shared; simpl.\n          constructor. by rewrite in_fset1.\n        }\n        constructor; by auto.\n      * intros ? ? Hload Hperm.\n        destruct ptr as [[[[] cptr] bptr] optr]; [discriminate|]. clear Hperm.\n        destruct load_at as [[[ploadat cloadat] bloadat] oloadat].\n        assert (ploadat = Permission.data).\n        { by apply Memory.load_some_permission in Hload. }\n        subst.\n        setoid_rewrite cats1.\n        destruct (classic (addr_shared_so_far (cptr, bptr)\n                                              (rcons t1 (ERet C v mem C'))))\n          as [ptrshr|ptrnotshr].\n        -- apply shared_stuff_from_anywhere; by auto.\n        -- destruct (cptr == C') eqn:ecptr.\n           ++ assert (cptr = C'). by apply/eqP. subst.\n              destruct (classic (addr_shared_so_far (cloadat, bloadat)\n                                                    (rcons t1 (ERet C v mem C'))))\n                as [loadatshr|loadatnotshr].\n              ** apply private_stuff_of_current_pc_from_shared_addr; auto.\n              ** apply private_stuff_from_corresp_private_addr; auto. simpl.\n                 specialize (H1 _ _ Hload Logic.eq_refl). inversion H1; subst; auto.\n                 --- exfalso. apply ptrnotshr.\n                     eapply reachable_from_previously_shared; eauto. simpl.\n                     constructor. by rewrite in_fset1.\n                 --- exfalso. apply loadatnotshr.\n                     eapply reachable_from_previously_shared; eauto. simpl.\n                     constructor. by rewrite in_fset1.\n           ++ apply private_stuff_from_corresp_private_addr; simpl in *; auto; subst.\n              ** intros Hshraddr.\n                 apply ptrnotshr.\n                 eapply addr_shared_so_far_load_addr_shared_so_far; simpl; eauto.\n              ** specialize (H1 _ _ Hload Logic.eq_refl). inversion H1; subst; auto.\n                 --- exfalso. apply ptrnotshr.\n                     eapply reachable_from_previously_shared; eauto. simpl.\n                     constructor. by rewrite in_fset1.\n               --- exfalso. apply ptrnotshr.\n                   eapply addr_shared_so_far_load_addr_shared_so_far; simpl; eauto.\n                   +++\n                     eapply reachable_from_previously_shared; eauto. simpl.\n                     constructor. by rewrite in_fset1.\n                   +++ eassumption.\n      * (** wf_cont *)\n        inversion H2; subst. unfold wf_frame_wrt_t in H7.\n        intuition. simpl in *. unfold wf_cont_wrt_t_pc.\n        by apply cont_struct_invariant_rcons.\n      * (** w_stack *)\n        unfold wf_stack_wrt_t_pc, stack_struct_invariant, wf_frame_wrt_t in *.\n        apply Forall_forall. erewrite Forall_forall in H2.\n        intros frm Hin.\n        assert (Hin':\n                  In frm\n                     ({| CS.f_component := C';\n                         CS.f_arg := old_call_arg; CS.f_cont := k |} :: s)).\n        {\n            by apply List.in_cons.\n        }\n        specialize (H2 frm Hin').\n        destruct H2 as [Hfrm1 Hfrm2].\n        split.\n        ++ intros ? Harg Hperm.\n           specialize (Hfrm1 _ Harg Hperm).\n           setoid_rewrite cats1.\n           destruct ptr as [[[pptr cptr] bptr] optr]. simpl in *; subst.\n           destruct (classic (addr_shared_so_far\n                                (cptr, bptr)\n                                (rcons t1 (ERet C v mem C'))\n                    )) as [ptrshr | ptrnotshr].\n           ** eapply wf_ptr_shared; by auto.\n           ** inversion Hfrm1; [by constructor|subst].\n              exfalso.\n              eapply ptrnotshr, reachable_from_previously_shared; [eassumption|].\n              constructor. by rewrite in_fset1.\n        ++ by apply cont_struct_invariant_rcons.\n      * (** wf_ptr *)\n        inversion H2; subst. unfold wf_frame_wrt_t in H9.\n        intuition.\n        simpl in *.\n        specialize (H5 _ Logic.eq_refl H6).\n        destruct ptr as [[[pptr cptr] bptr] optr]. simpl in *. subst.\n        setoid_rewrite cats1.\n        destruct (classic (addr_shared_so_far\n                             (cptr, bptr)\n                             (rcons t1 (ERet C v mem C'))\n                    )) as [ptrshr | ptrnotshr].\n        ** eapply wf_ptr_shared; by auto.\n        ** inversion H5; [by constructor|].\n           subst. exfalso.\n           eapply ptrnotshr, reachable_from_previously_shared; [eassumption|].\n           constructor. by rewrite in_fset1.\nQed.\n\nEnd CSInvariants.\n", "meta": {"author": "secure-compilation", "repo": "SecurePtrs", "sha": "5b4c34eda0b827469a5c73e434a12c6c87773e04", "save_path": "github-repos/coq/secure-compilation-SecurePtrs", "path": "github-repos/coq/secure-compilation-SecurePtrs/SecurePtrs-5b4c34eda0b827469a5c73e434a12c6c87773e04/Source/CSInvariants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2472493990808347}}
{"text": "From Ornamental Require Import Ornaments.\nRequire Import Infrastructure.\n\nSet DEVOID search prove equivalence.\nSet DEVOID lift type.\nSet Nonrecursive Elimination Schemes.\n\n(*\n * This code is a minimized example from @ptival, which I use as a regression test\n * to make sure projections aren't expanded and left as applications of prod_rect,\n * and that projections/accessors lift to accessors/projections.\n *\n * The proofs here are purposely brittle, since they should break if the terms are not _exactly_ syntactically equal.\n *)\n\nModule Pairs.\n\n  Definition profile : Type := (bool * nat).\n\n  Definition page : Type := (nat * (nat * (bool * ((bool * nat) * nat)))).\n\n  Definition visible (pr : profile) (pa : page) : bool :=\n    andb (fst pr) (fst (snd (snd pa))).\n\nEnd Pairs.\n\nPreprocess Module Pairs as Pairs_PP { opaque andb }.\n\nModule Records.\n\n  Record Profile :=\n    {\n      public : bool;\n      age : nat;\n    }.\n\n  Definition is_public (pr : Pairs.profile) : bool := fst pr.\n\n  Definition get_age (pr : Pairs.profile) : nat := snd pr.\n\nEnd Records.\n\nPreprocess Module Records as Records_PP.\n\nLift Records_PP.Profile Pairs_PP.profile in Records_PP.public as is_public.\nLift Pairs_PP.profile Records_PP.Profile in Records_PP.is_public as public.\n\nDefinition is_public_expected (h : Pairs_PP.profile) :=\n  Prod.fst _ _ h.\n\nLemma test_is_public:\n  is_public = is_public_expected.\nProof.\n  unfold is_public, is_public_expected.\n  test_exact_equality.\nQed.\n\nLemma test_public:\n  public = fun h => Records_PP.public h.\nProof.\n  unfold public.\n  test_exact_equality.\nQed.\n\nLift Records_PP.Profile Pairs_PP.profile in Records_PP.age as get_age.\nLift Pairs_PP.profile Records_PP.Profile in Records_PP.get_age as age.\n\nDefinition get_age_expected (h : Pairs_PP.profile) :=\n  Prod.snd _ _ h.\n\nLemma test_get_h_n:\n  get_age = get_age_expected.\nProof.\n  unfold get_age, get_age_expected.\n  test_exact_equality.\nQed.\n\nLemma testGetHN:\n  age = fun (h : Records_PP.Profile) => Records_PP.age h.\nProof.\n  unfold age. \n  test_exact_equality.\nQed.\n\nLift Pairs_PP.profile Records_PP.Profile in Pairs_PP.visible as visible_PP { opaque andb }.\n\nDefinition visible_PP_expected (pr : Records_PP.Profile) (pa : nat * (nat * (bool * (Records_PP.Profile * nat)))) : bool :=\n Records_PP.public pr \n &&\n Pairs_PP.Coq_Init_Datatypes_fst bool (Records_PP.Profile * nat)\n   (Pairs_PP.Coq_Init_Datatypes_snd nat (bool * (Records_PP.Profile * nat))\n      (Pairs_PP.Coq_Init_Datatypes_snd nat (nat * (bool * (Records_PP.Profile * nat))) pa)).\n\nLemma test_visible_PP:\n  visible_PP = visible_PP_expected.\nProof.\n  unfold visible_PP, visible_PP_expected.\n  test_exact_equality.\nQed.\n\nModule MoreRecords.\n\n  Record Page :=\n    {\n      friends : nat;\n      groups : nat;\n      active  : bool;\n      profile  : Records_PP.Profile;\n      photos : nat;\n    }.\n\n  (* We'd like to wrap the ugly access into this: *)\n  Definition is_active (pa : Pairs.page) : bool := fst (snd (snd pa)).\n\nEnd MoreRecords.\n\nPreprocess Module MoreRecords as MoreRecords_PP.\n\nLift Pairs_PP.profile Records_PP.Profile in Pairs_PP.page as page_PP.\n\nLift Pairs_PP.profile Records_PP.Profile in MoreRecords_PP.is_active as active0.\nLift page_PP MoreRecords_PP.Page in active0 as active.\n\nLift Pairs_PP.profile Records_PP.Profile in Pairs_PP.visible as visible0 { opaque andb }.\nLift page_PP MoreRecords_PP.Page in visible0 as visible { opaque andb }.\n\nDefinition visible_expected (pr : Records_PP.Profile) (pa : MoreRecords_PP.Page) : bool :=\n  (Records_PP.public pr && MoreRecords_PP.active pa)%bool.\n\nLemma test_visible :\n  visible = visible_expected.\nProof.\n  unfold visible, visible_expected.\n  test_exact_equality.\nQed.\n", "meta": {"author": "uwplse", "repo": "pumpkin-pi", "sha": "a7743d4665d8c7a0ebfd9d39e1247ee7804d402b", "save_path": "github-repos/coq/uwplse-pumpkin-pi", "path": "github-repos/coq/uwplse-pumpkin-pi/pumpkin-pi-a7743d4665d8c7a0ebfd9d39e1247ee7804d402b/plugin/coq/prod_rect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2472010503901541}}
{"text": "Require Import CertiGraph.msl_application.ArrayGraph.\nRequire Import VST.veric.SeparationLogic.\nRequire Import CertiGraph.unionfind.env_unionfind_arr.\nRequire Import CertiGraph.floyd_ext.share.\n\n(*I suppose this focuses SpatialArrayGraphAssum to specifically the mpred type? Have no idea what it means*)\nInstance SAGA_VST: SpatialArrayGraphAssum mpred. Proof. refine (Build_SpatialArrayGraphAssum _ _ _ _ _). Defined.\n\n(* Translation of a rank-parent pair into the C representation *)\nDefinition vgamma2cdata (rpa : nat * Z) : reptype vertex_type :=\n  match rpa with\n  | (r, pa) => (Vint (Int.repr pa), Vint (Int.repr (Z.of_nat r)))\n  end.\n\n(*Some SpatialGraph wrap over the data_at mpred stated below?*)\nInstance SAG_VST (sh: share): SpatialArrayGraph pointer_val mpred.\nProof.\n(*       pointer_val         mpred *)\n  exact (fun pt lst => data_at sh (tarray vertex_type (Z.of_nat (length lst)))\n                               (map vgamma2cdata lst) (pointer_val_val pt)).\nDefined.\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/unionfind/spatial_array_graph.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24708377864121805}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nRequire Import Coq.Classes.RelationClasses Lia Program.\nFrom Fairness Require Export ITreeLib WFLib FairBeh NatStructs Mod pind.\nFrom PromisingLib Require Import Loc Event.\nFrom PromisingSEQ Require Import Time View TView Cell Memory Local.\n\nSet Implicit Arguments.\n\nModule WMem.\n  Program Definition init_cell: Cell.t :=\n    @Cell.mk (LocMap.singleton Time.bot (Time.bot, Message.concrete (Const.of_Z (BinIntDef.Z.of_nat 0)) None)) _.\n  Next Obligation.\n  Proof.\n    econs.\n    { i. eapply LocMap.singleton_find_inv in GET. des; clarify. auto. }\n    { i. eapply LocMap.singleton_find_inv in GET. des; clarify. auto. }\n    { i. eapply LocMap.singleton_find_inv in GET1.\n      eapply LocMap.singleton_find_inv in GET2. des; clarify.\n    }\n  Qed.\n\n  Definition init_mem: Memory.t := fun _ => init_cell.\n\n  Record t :=\n    mk\n      {\n        memory:> Memory.t;\n        sc: TimeMap.t;\n      }.\n\n  Definition init: t := mk init_mem TimeMap.bot.\n\n  Let ident := (Loc.t * Time.t)%type.\n\n  Definition view_to_local (vw: View.t): Local.t := Local.mk (TView.mk (fun _ => vw) vw vw) Memory.bot.\n\n  Definition missed (m: Memory.t) (loc: Loc.t) (ts: Time.t): fmap ident :=\n    fun '(loc', ts') =>\n      if (Loc.eq_dec loc' loc)\n      then\n        if (Time.le_lt_dec ts' ts)\n        then Flag.emp\n        else match Memory.get loc' ts' m with\n             | Some (_, Message.concrete _ (Some _)) => Flag.fail\n             | _ => Flag.emp\n             end\n      else Flag.emp.\n\n  Definition load_fun:\n    ktree (programE ident t) (View.t * Loc.t * Ordering.t) (View.t * Const.t) :=\n    fun '(vw0, loc, ord) =>\n      msc <- trigger (Get id);;\n      '(exist _ (lc1, val, to) _) <- trigger (Choose (sig (fun '(lc1, val, to) =>\n                                                             exists released,\n                                                               Local.read_step\n                                                                 (view_to_local vw0)\n                                                                 (msc.(memory))\n                                                                 loc\n                                                                 to\n                                                                 val\n                                                                 released\n                                                                 ord\n                                                                 lc1)));;\n      _ <- trigger (Fair (missed msc loc to));;\n      Ret (lc1.(Local.tview).(TView.cur), val)\n  .\n\n  Definition store_fun:\n    ktree (programE ident t) (View.t * Loc.t * Const.t * Ordering.t) (View.t) :=\n    fun '(vw0, loc, val, ord) =>\n      msc <- trigger (Get id);;\n      '(exist _ (lc1, to, sc1, mem1) _) <- trigger (Choose (sig (fun '(lc1, to, sc1, mem1) =>\n                                                                   exists from released kind,\n                                                                     Local.write_step\n                                                                       (view_to_local vw0)\n                                                                       (msc.(sc))\n                                                                       (msc.(memory))\n                                                                       loc\n                                                                       from\n                                                                       to\n                                                                       val\n                                                                       None\n                                                                       released\n                                                                       ord\n                                                                       lc1\n                                                                       sc1\n                                                                       mem1\n                                                                       kind)));;\n      _ <- trigger (Fair (missed msc loc to));;\n      _ <- trigger (Put (mk mem1 sc1));;\n      Ret (lc1.(Local.tview).(TView.cur))\n  .\n\n  Definition faa_fun:\n    ktree (programE ident t) (View.t * Loc.t * Const.t * Ordering.t * Ordering.t) (View.t * Const.t) :=\n    fun '(vw0, loc, addendum, ordr, ordw) =>\n      msc <- trigger (Get id);;\n      '(exist _ (lc2, to, val, sc1, mem1) _) <-\n        trigger (Choose (sig (fun '(lc2, to, val, sc1, mem1) =>\n                                exists lc1 from releasedr releasedw kind,\n                                  (Local.read_step\n                                     (view_to_local vw0)\n                                     (msc.(memory))\n                                     loc\n                                     from\n                                     val\n                                     releasedr\n                                     ordr\n                                     lc1) /\\\n                                    (Local.write_step\n                                       lc1\n                                       (msc.(sc))\n                                       (msc.(memory))\n                                       loc\n                                       from\n                                       to\n                                       (Const.add val addendum)\n                                       releasedr\n                                       releasedw\n                                       ordw\n                                       lc2\n                                       sc1\n                                       mem1\n                                       kind))));;\n      _ <- trigger (Fair (missed msc loc to));;\n      _ <- trigger (Put (mk mem1 sc1));;\n      Ret (lc2.(Local.tview).(TView.cur), val)\n  .\n\n  Definition mod: Mod.t :=\n    Mod.mk\n      init\n      (Mod.get_funs [(\"store\", Mod.wrap_fun store_fun);\n                     (\"load\", Mod.wrap_fun load_fun);\n                     (\"faa\", Mod.wrap_fun faa_fun)\n      ]).\n\nEnd WMem.\n\nFrom Fairness Require Import PCM IProp IPM FairRA StateRA MonotonePCM.\nFrom PromisingSEQ Require Import MemoryProps.\n\nSection MEMRA.\n  Definition wmemRA: URA.t := (Loc.t ==> (Auth.t (Excl.t Cell.t)))%ra.\n\n  Context `{WMEMRA: @GRA.inG wmemRA Σ}.\n\n  Definition memory_resource_black (m: WMem.t): wmemRA :=\n    fun loc =>\n      Auth.black (Excl.just (m.(WMem.memory) loc): Excl.t Cell.t).\n\n  Definition points_to_white (loc: Loc.t) (c: Cell.t): wmemRA :=\n    fun loc' =>\n      if (Loc.eq_dec loc' loc)\n      then Auth.white (Excl.just c: Excl.t Cell.t)\n      else URA.unit\n  .\n\n  Definition points_to (loc: Loc.t) (c: Cell.t): iProp :=\n    OwnM (points_to_white loc c).\n\n  Definition wmemory_black (m: WMem.t): iProp :=\n    OwnM (memory_resource_black m).\n\n  (* TODO: multiple locs *)\n  Definition wmem_init_res (l0 l1: Loc.t): wmemRA :=\n    points_to_white l0 WMem.init_cell ⋅ points_to_white l1 WMem.init_cell ⋅ memory_resource_black WMem.init.\n\n  Lemma wmem_init_res_wf l0 l1\n        (DISJ: l0 <> l1)\n    :\n    URA.wf (wmem_init_res l0 l1).\n  Proof.\n    unfold wmem_init_res, points_to_white, points_to, Auth.white.\n    Local Transparent URA.unit.\n    ur. i. ur. des_ifs.\n    { splits.\n      { eexists (URA.unit). ur. ss. }\n      { ur. ss. }\n    }\n    { splits.\n      { eexists (URA.unit). ur. ss. }\n      { ur. ss. }\n    }\n    { splits.\n      { eexists (Excl.just (WMem.init_mem k)). ur. ss. }\n      { ur. ss. }\n    }\n  Qed.\n\n  Lemma wmem_init_res_prop l0 l1\n    :\n    (OwnM (wmem_init_res l0 l1))\n      -∗\n      (points_to l0 WMem.init_cell ** points_to l1 WMem.init_cell ** wmemory_black WMem.init).\n  Proof.\n    iIntros \"[[H0 H1] H2]\". iFrame.\n  Qed.\n\n  (* normal points-to *)\n  Definition wpoints_to (l: Loc.t) (v: Const.t) (vw: View.t): iProp :=\n    ∃ c,\n      (points_to l c)\n        **\n        (⌜exists from released,\n              (<<GET: Cell.get (Cell.max_ts c) c = Some (from, Message.concrete v released)>>) /\\\n                (<<DEFINED: v <> Const.undef>>) /\\\n                (<<VIEW: View.le (View.singleton_ur l (Cell.max_ts c)) vw >>)⌝)\n  .\n\n  Lemma init_cell_max_ts\n    :\n    Cell.max_ts WMem.init_cell = Time.bot.\n  Proof.\n    auto.\n  Qed.\n\n  Lemma init_cell_get\n    :\n    Cell.get (Cell.max_ts WMem.init_cell) WMem.init_cell =\n      Some (Time.bot, Message.concrete (BinIntDef.Z.of_nat 0) None).\n  Proof.\n    ss.\n  Qed.\n\n  Lemma init_cell_get_if to from msg\n        (GET: Cell.get to WMem.init_cell = Some (from, msg))\n    :\n    (<<TO: to = Time.bot>>) /\\\n      (<<FROM: from = Time.bot>>) /\\\n      (<<MSG: msg = Message.concrete (BinIntDef.Z.of_nat 0) None>>).\n  Proof.\n    hexploit Cell.max_ts_spec; eauto. i. des.\n    rewrite init_cell_max_ts in *. inv MAX.\n    { inv H. }\n    { inv H. setoid_rewrite init_cell_get in GET. clarify. }\n  Qed.\n\n  Lemma init_points_to_wpoints_to l v\n    :\n    (points_to l WMem.init_cell)\n      -∗\n      wpoints_to l (Const.of_Z (BinIntDef.Z.of_nat 0)) v.\n  Proof.\n    iIntros \"H\". iExists _. iFrame. iPureIntro. esplits.\n    { rewrite init_cell_get. eauto. }\n    { ss. }\n    { econs.\n      { ss. eapply TimeMap.singleton_spec.\n        rewrite init_cell_max_ts. eapply Time.bot_spec. }\n      { ss. eapply TimeMap.singleton_spec.\n        rewrite init_cell_max_ts. eapply Time.bot_spec. }\n    }\n  Qed.\n\n  Lemma wpoints_to_view_mon l v vw0 vw1\n        (LE: View.le vw0 vw1)\n    :\n    (wpoints_to l v vw0)\n      ⊢\n      (wpoints_to l v vw1).\n  Proof.\n    unfold wpoints_to.\n    iIntros \"[% [OWN %]]\". des. iExists _. iSplit; [iFrame|].\n    iPureIntro. esplits; eauto.\n  Qed.\n\n  Lemma wmemory_ra_get\n        m l c\n    :\n    (wmemory_black m)\n      -∗\n      (points_to l c)\n      -∗\n      ⌜m.(WMem.memory) l = c⌝.\n  Proof.\n    iIntros \"BLACK WHITE\".\n    unfold wmemory_black, points_to.\n    iCombine \"BLACK WHITE\" as \"OWN\". iOwnWf \"OWN\". iPureIntro.\n    ur in H. specialize (H l).\n    unfold memory_resource_black, points_to_white in H. des_ifs.\n    ur in H. ur in H. des_ifs. des. rr in H. des. ur in H. des_ifs.\n  Qed.\n\n  Lemma pointwise_updatabable M K (a b: URA.pointwise K M)\n        (POINTWISE: forall k, URA.updatable (a k) (b k))\n    :\n    URA.updatable a b.\n  Proof.\n    ii. ur. ur in H. i. eapply POINTWISE; eauto.\n  Qed.\n\n  Lemma wmemory_ra_write\n        m0 m1 l c\n        from to msg\n        (WRITE: Memory.add m0.(WMem.memory) l from to msg m1)\n    :\n    (wmemory_black m0)\n      -∗\n      (points_to l c)\n      -∗\n      (#=> (wmemory_black (WMem.mk m1 m0.(WMem.sc)) ** points_to l (m1 l))).\n  Proof.\n    iIntros \"BLACK WHITE\".\n    unfold wmemory_black, points_to.\n    iCombine \"BLACK WHITE\" as \"OWN\". iOwnWf \"OWN\".\n    ur in H. specialize (H l).\n    unfold memory_resource_black, points_to_white in H. des_ifs.\n    ur in H. ur in H. des_ifs. des. rr in H. des. ur in H. des_ifs.\n    iAssert (#=> OwnM (memory_resource_black (WMem.mk m1 m0.(WMem.sc)) ⋅ points_to_white l (m1 l))) with \"[OWN]\" as \"> [BLACK WHITE]\".\n    { iApply (OwnM_Upd with \"OWN\").\n      ur. apply pointwise_updatabable. i.\n      unfold memory_resource_black, points_to_white. ss.\n      inv WRITE. setoid_rewrite LocFun.add_spec. des_ifs.\n      eapply Auth.auth_update. ii. des. split; ss.\n      { ur. ss. }\n      { ur in FRAME. ur. des_ifs. rr.\n        f_equal. symmetry. apply LocFun.add_spec_eq.\n      }\n    }\n    { iModIntro. iFrame. }\n  Qed.\n\n  Lemma memory_write_max_ts m0 loc from to msg m1\n        (ADD: Memory.add m0 loc from to msg m1)\n        (MAX: Time.le (Memory.max_ts loc m0) to)\n    :\n    Memory.max_ts loc m1 = to.\n  Proof.\n    apply TimeFacts.antisym.\n    { hexploit Memory.max_ts_spec.\n      { eapply Memory.add_get0; eauto. }\n      i. des. erewrite Memory.add_o in GET; eauto. des_ifs.\n      { ss. des; clarify. }\n      { des; ss. eapply Memory.max_ts_spec in GET. des. etrans; eauto. }\n    }\n    { eapply Memory.add_get0 in ADD. des.\n      eapply Memory.max_ts_spec in GET0. des. auto.\n    }\n  Qed.\n\n  Lemma wmemory_ra_load\n        m l v0 v1 vw0 vw1\n        ord lc1 to released\n        (READ: Local.read_step (WMem.view_to_local vw0) m.(WMem.memory) l to v1 released ord lc1)\n        (VIEW: vw1 = lc1.(Local.tview).(TView.cur))\n        (ORD: ord = Ordering.plain)\n    :\n    (wmemory_black m)\n      -∗\n      (wpoints_to l v0 vw0)\n      -∗\n      ((wmemory_black m) ∗ (⌜(View.le vw0 vw1) /\\ (v0 = v1)⌝) ∗ #=>(wpoints_to l v0 vw1)).\n  Proof.\n    iIntros \"BLACK [% [WHITE %]]\". des. subst.\n    iPoseProof (wmemory_ra_get with \"BLACK WHITE\") as \"%\". subst.\n    iSplitL \"BLACK\"; [auto|]. inv READ. ss. iSplit.\n    { iPureIntro. split.\n      { etrans; [|eapply View.join_l]. eapply View.join_l. }\n      { assert (to = (Cell.max_ts (WMem.memory m l))).\n        { eapply TimeFacts.antisym.\n          { eapply Memory.max_ts_spec in GET0. des. clarify. }\n          { inv READABLE. etrans; eauto.\n            inv VIEW0. ss. specialize (PLN0 l).\n            unfold TimeMap.singleton in PLN0.\n            setoid_rewrite LocFun.add_spec_eq in PLN0. auto.\n          }\n        }\n        subst. setoid_rewrite GET in GET0. clarify.\n        inv VAL; ss.\n        destruct v1, val'; ss. apply Z.eqb_eq in H0. subst. auto.\n      }\n    }\n    { iModIntro. iExists _. iFrame. iPureIntro. esplits; eauto.\n      ss. unfold View.singleton_ur_if. des_ifs.\n      etrans; eauto.\n      etrans; [|eapply View.join_l]. eapply View.join_l.\n    }\n  Qed.\n\n  Lemma wmemory_ra_store\n        m0 l v0 vw0 m1 v1 vw1\n        lc1 to sc1 mem1 ord from released kind\n        (WRITE: Local.write_step (WMem.view_to_local vw0) m0.(WMem.sc) m0.(WMem.memory) l from to v1 None released ord lc1 sc1 mem1 kind)\n        (VIEW: vw1 = lc1.(Local.tview).(TView.cur))\n        (MEM: m1 = WMem.mk mem1 sc1)\n        (ORD: ord = Ordering.plain)\n        (DEFINED: v1 <> Const.undef)\n    :\n    (wmemory_black m0)\n      -∗\n      (wpoints_to l v0 vw0)\n      -∗\n      ((⌜View.le vw0 vw1⌝) ∗ #=>((wmemory_black m1) ∗ (wpoints_to l v1 vw1))).\n  Proof.\n    iIntros \"BLACK [% [WHITE %]]\". des. subst.\n    iPoseProof (wmemory_ra_get with \"BLACK WHITE\") as \"%\". subst.\n    inv WRITE. ss. hexploit memory_write_bot_add; eauto. i. subst.\n    inv WRITE0. inv PROMISE. clear REMOVE PROMISES ATTACH TS.\n    assert (MAX: Cell.max_ts (mem1 l) = to).\n    { hexploit Memory.max_ts_spec.\n      { eapply Memory.add_get1; eauto. }\n      i. des. erewrite Memory.add_o in GET0; eauto. des_ifs; ss.\n      { des; clarify. }\n      { des; ss. eapply Memory.max_ts_spec in GET0. des.\n        hexploit Memory.max_ts_spec.\n        { eapply Memory.add_get0; eauto. }\n        i. des. inv WRITABLE.\n        exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n        { eapply TS. }\n        etrans; eauto.\n        etrans; eauto.\n        inv VIEW0. ss. specialize (RLX l).\n        unfold TimeMap.singleton in RLX. setoid_rewrite LocFun.add_spec_eq in RLX. auto.\n      }\n    }\n    subst. iSplit.\n    { iPureIntro. eapply View.join_l. }\n    iPoseProof (wmemory_ra_write with \"BLACK WHITE\") as \"> [BLACK WHITE]\".\n    { eauto. }\n    iModIntro. iSplitL \"BLACK\"; [auto|].\n    iExists _. iSplit; [iFrame|]. iPureIntro. esplits; eauto.\n    { eapply Memory.add_get0; eauto. }\n    { ss. eapply View.join_r. }\n  Qed.\n\n  (* faa points-to *)\n  Definition wpoints_to_faa (l: Loc.t) (v: Const.t): iProp :=\n    ∃ c,\n      (points_to l c)\n        **\n        (⌜exists from released,\n              (<<GET: Cell.get (Cell.max_ts c) c = Some (from, Message.concrete v released)>>) /\\\n                (<<FAA: forall to from msg (GET: Cell.get to c = Some (from, msg)),\n                    ((exists to' msg',\n                         (<<GET: Cell.get to' c = Some (to, msg')>>) /\\ (<<TS: Time.lt to to'>>)) \\/\n                       (<<TS: to = Cell.max_ts c>>))>>) /\\\n                (<<DEFINED: v <> Const.undef>>)⌝)\n  .\n\n  Lemma init_points_to_wpoints_to_faa l\n    :\n    (points_to l WMem.init_cell)\n      -∗\n      wpoints_to_faa l (Const.of_Z (BinIntDef.Z.of_nat 0)).\n  Proof.\n    iIntros \"H\". iExists _. iFrame. iPureIntro. esplits.\n    { rewrite init_cell_get. eauto. }\n    { i. hexploit init_cell_get_if; eauto. i. des; clarify.\n      right. rewrite init_cell_max_ts. auto.\n    }\n    { ss. }\n  Qed.\n\n  Lemma wmemory_ra_faa\n        v msc\n        vw0 loc addendum ordr ordw\n        lc1 from releasedr releasedw kind\n        lc2 to val sc1 mem1\n        (READ: Local.read_step (WMem.view_to_local vw0) (msc.(WMem.memory)) loc from val releasedr ordr lc1)\n        (WRITE: Local.write_step lc1 (msc.(WMem.sc)) (msc.(WMem.memory)) loc from to (Const.add val addendum) releasedr releasedw ordw lc2 sc1 mem1 kind)\n        (ORDR: ordr = Ordering.plain)\n        (ORDW: ordw = Ordering.acqrel)\n        (DEFINED: addendum <> Const.undef)\n    :\n    (wmemory_black msc)\n      -∗\n      (wpoints_to_faa loc v)\n      -∗\n      ((⌜(View.le vw0 lc2.(Local.tview).(TView.cur)) /\\ (v = val)⌝)\n         ∗ #=>((wmemory_black (WMem.mk mem1 sc1)) ∗ wpoints_to_faa loc (Const.add v addendum))).\n  Proof.\n    iIntros \"BLACK [% [WHITE %]]\". des. subst.\n    iPoseProof (wmemory_ra_get with \"BLACK WHITE\") as \"%\". subst.\n    inv READ. inv WRITE. ss.\n    inv WRITE0. ss. hexploit memory_write_bot_add; eauto. i. subst.\n    inv PROMISE. clear REMOVE PROMISES ATTACH TS.\n    hexploit add_succeed_wf; eauto. i. des.\n    assert (MAX0: from = Cell.max_ts (WMem.memory msc loc)).\n    { hexploit FAA; eauto. i. des; auto.\n      hexploit DISJOINT; eauto. i. exfalso. eapply H.\n      { instantiate (1:=Time.meet to to'). econs; ss.\n        { unfold Time.meet. des_ifs. }\n        { eapply Time.meet_l. }\n      }\n      { econs; ss.\n        { unfold Time.meet. des_ifs. }\n        { eapply Time.meet_r. }\n      }\n    }\n    subst. setoid_rewrite GET0 in GET. inv GET.\n    assert (val = v).\n    { inv VAL; ss. destruct val, v; ss. apply Z.eqb_eq in H0. subst. auto. }\n    subst. iSplit.\n    { iPureIntro. split.\n      { etrans; [|eapply View.join_l].\n        etrans; [|eapply View.join_l].\n        eapply View.join_l.\n      }\n      { auto. }\n    }\n    assert (MAX1: to = Cell.max_ts (mem1 loc)).\n    { eapply TimeFacts.antisym.\n      { hexploit Memory.max_ts_spec.\n        { eapply Memory.add_get0; eauto. }\n        { i. des. eauto. }\n      }\n      { hexploit Memory.max_ts_spec.\n        { eapply Memory.add_get1; eauto. }\n        i. des. erewrite Memory.add_o in GET; eauto. des_ifs.\n        { ss. des; subst. reflexivity. }\n        { guardH o. eapply Memory.max_ts_spec in GET. des.\n          etrans ;eauto. left. auto.\n        }\n      }\n    }\n    iPoseProof (wmemory_ra_write with \"BLACK WHITE\") as \"> [BLACK WHITE]\".\n    { eauto. }\n    iModIntro. iSplitL \"BLACK\"; [auto|].\n    iExists _. iSplit; [iFrame|]. iPureIntro. esplits; eauto.\n    { erewrite <- MAX1. eapply Memory.add_get0; eauto. }\n    { i. setoid_rewrite Memory.add_o in GET; [|eauto]. des_ifs.\n      { ss. des; clarify. auto. }\n      { guardH o. hexploit FAA; eauto. i. des.\n        { left. esplits; eauto. eapply Memory.add_get1; eauto. }\n        { subst. left. esplits; eauto.\n          { eapply Memory.add_get0; eauto. }\n        }\n      }\n    }\n    { ii. destruct v, addendum; ss. }\n  Qed.\n\n  (* full points-to *)\n  Definition wProp := Const.t -> View.t -> Prop.\n  Definition wor (P Q: wProp): wProp := fun c vw => ((P c vw) \\/ (Q c vw)).\n  Definition wimpl (P Q: wProp): Prop := (∀ c vw, (P c vw) -> (Q c vw)).\n\n  Definition lift_wProp (P: wProp) (c: Const.t) (vw: View.t): iProp :=\n    ∃ vw', (⌜P c vw'⌝) ∗ (⌜View.le vw' vw⌝).\n\n  Lemma lift_wProp_mon\n        P c vw0 vw1\n        (LE: View.le vw0 vw1)\n    :\n    (lift_wProp P c vw0) -∗ (lift_wProp P c vw1).\n  Proof.\n    unfold lift_wProp. iIntros \"[% [A %B]]\". iExists vw'. iFrame.\n    iPureIntro. etrans. eapply B. auto.\n  Qed.\n\n\n\n\n\n  Context `{OBLGRA: @GRA.inG ObligationRA.t Σ}.\n  Context `{ARROWRA: @GRA.inG (ArrowRA (void + WMem.ident)%type) Σ}.\n  Context `{IDENTTGT: @GRA.inG (identTgtRA (void + WMem.ident)%type) Σ}.\n  Context `{EDGERA: @GRA.inG EdgeRA Σ}.\n  Context `{ONESHOTSRA: @GRA.inG (@FiniteMap.t (OneShot.t unit)) Σ}.\n\n  Definition wmemory_black_strong m: iProp :=\n    wmemory_black m ** (FairRA.blacks (fun id => exists loc to, id = (inr (inr (loc, to))) /\\ Memory.get loc to m.(WMem.memory) = None)).\n\n  Lemma wmemory_ra_write_strong\n        m0 m1 l c\n        from to msg\n        (WRITE: Memory.add m0.(WMem.memory) l from to msg m1)\n    :\n    (wmemory_black_strong m0)\n      -∗\n      (points_to l c)\n      -∗\n      (#=> (wmemory_black_strong (WMem.mk m1 m0.(WMem.sc)) ** points_to l (m1 l) ** FairRA.black_ex (inr (inr (l, to))) 1%Qp)).\n  Proof.\n    iIntros \"[BLACK BLACKS] WHITE\".\n    iPoseProof (wmemory_ra_write with \"BLACK WHITE\") as \"> [BLACK WHITE]\"; [eauto|..].\n    iModIntro. iFrame. iApply (FairRA.blacks_unfold with \"BLACKS\").\n    { i. ss. des; subst.\n      { erewrite Memory.add_o in IN0; eauto. des_ifs. esplits; eauto. }\n      { esplits; eauto. eapply Memory.add_get0. eauto. }\n    }\n    { ii. des. clarify. ss. eapply Memory.add_get0 in WRITE. des; clarify. }\n  Qed.\n\n  Lemma wmemory_ra_faa_strong\n        v msc\n        vw0 loc addendum ordr ordw\n        lc1 from releasedr releasedw kind\n        lc2 to val sc1 mem1\n        (READ: Local.read_step (WMem.view_to_local vw0) (msc.(WMem.memory)) loc from val releasedr ordr lc1)\n        (WRITE: Local.write_step lc1 (msc.(WMem.sc)) (msc.(WMem.memory)) loc from to (Const.add val addendum) releasedr releasedw ordw lc2 sc1 mem1 kind)\n        (ORDR: ordr = Ordering.plain)\n        (ORDW: ordw = Ordering.acqrel)\n        (DEFINED: addendum <> Const.undef)\n    :\n    (wmemory_black_strong msc)\n      -∗\n      (wpoints_to_faa loc v)\n      -∗\n      ((⌜(View.le vw0 lc2.(Local.tview).(TView.cur)) /\\ (v = val)⌝)\n         ∗ #=>((wmemory_black_strong (WMem.mk mem1 sc1)) ∗ wpoints_to_faa loc (Const.add v addendum))).\n  Proof.\n    iIntros \"[BLACK BLACKS] WHITE\".\n    iPoseProof (wmemory_ra_faa with \"BLACK WHITE\") as \"[% H]\"; eauto.\n    iSplitR; [auto|]. iPoseProof (\"H\") as \"> [H0 H1]\".\n    iModIntro. unfold wmemory_black_strong. iFrame.\n    inv READ. inv WRITE. hexploit memory_write_bot_add; eauto. i. subst. ss.\n    inv WRITE0. inv PROMISE. ss.\n    iPoseProof (FairRA.blacks_unfold with \"BLACKS\") as \"[H0 H1]\"; [..|iApply \"H0\"].\n    { i. ss. des; subst.\n      { erewrite Memory.add_o in IN0; eauto. des_ifs. esplits; eauto. }\n      { esplits; eauto. eapply Memory.add_get0. eauto. }\n    }\n    { ii. des. clarify. eapply Memory.add_get0 in MEM. des; clarify. }\n  Qed.\n\n  Definition wpoints_to_full (l: Loc.t) (V: View.t) (k: nat) (P Q: wProp) : iProp :=\n    ∃ c,\n      (points_to l c)\n        **\n        (∃ v released,\n            (⌜Cell.max_ts c = Time.bot⌝ ∨ ObligationRA.duty (inr (inr (l, (Cell.max_ts c)))) [(k,Ord.S Ord.O)])\n              **\n              (ObligationRA.pending k 1%Qp)\n              **\n              (⌜Q v View.bot⌝)\n              **\n              (⌜(<<MSGVIEW: V = View.join (View.unwrap released) (View.singleton_ur l (Cell.max_ts c))>>) /\\\n                 (<<DEFINED: v <> Const.undef>>) /\\\n                 exists from,\n                   (<<GET: Cell.get (Cell.max_ts c) c = Some (from, Message.concrete v released)>>) /\\\n                     (<<DEFINED: v <> Const.undef>>) /\\\n                     (<<RELEASED: Time.lt Time.bot (Cell.max_ts c) -> released <> None>>)⌝)\n              **\n              (⌜forall to from' v' released' (GET: Cell.get to c = Some (from', Message.concrete v' released'))\n                       (LT: Time.lt to (Cell.max_ts c)),\n                    (P v' View.bot) /\\ (<<DEFINED: v' <> Const.undef>>)⌝))\n  .\n\n  Lemma init_points_to_wpoints_to_full l (P Q: wProp)\n        (SAT: Q (Const.of_Z (BinIntDef.Z.of_nat 0)) View.bot)\n    :\n    (points_to l WMem.init_cell)\n      -∗\n      #=>\n      (∃ k, wpoints_to_full l View.bot k P Q ** ObligationRA.black k Ord.O).\n  Proof.\n    iIntros \"H\".\n    iPoseProof (ObligationRA.alloc) as \"> [% [[B W] PENDING]]\".\n    iModIntro. iExists _. iSplitR \"B\"; [|iApply \"B\"]. iExists _.\n    iSplitL \"H\"; [iApply \"H\"|]. iExists _, _. iSplitL.\n    { iSplitL.\n      { iSplit; [|eauto]. iSplitR.\n        { iLeft. iPureIntro. apply init_cell_max_ts. }\n        { iApply \"PENDING\". }\n      }\n      { iPureIntro. esplits; eauto.\n        { eapply View.antisym.\n          { eapply View.bot_spec. }\n          { ss. eapply View.join_spec.\n            { reflexivity. }\n            { rewrite init_cell_max_ts.\n              econs; ss; eapply TimeMap.singleton_spec; eapply Time.bot_spec.\n            }\n          }\n        }\n        { i. rewrite init_cell_max_ts in H. inv H. }\n      }\n    }\n    { iPureIntro. i. apply init_cell_get_if in GET. des. clarify.\n      rewrite init_cell_max_ts in LT. inv LT.\n    }\n  Qed.\n\n  Lemma wpoints_to_full_not_shot\n        l V k P Q\n    :\n    (wpoints_to_full l V k P Q) ∗ (ObligationRA.shot k) -∗ ⌜False⌝.\n  Proof.\n    iIntros \"[[% [? [% [% [[[[? PENDING] ?] ?] H]]]]] SHOT]\".\n    iApply (ObligationRA.pending_not_shot with \"PENDING SHOT\").\n  Qed.\n\n  Lemma wpoints_to_full_impl\n        l V k P P' Q\n    :\n    ((⌜wimpl P P'⌝) ∗ (wpoints_to_full l V k P Q))\n      -∗ (wpoints_to_full l V k P' Q).\n  Proof.\n    iIntros \"[% [% [A [% [% [B %]]]]]]\".\n    iExists _. iSplitL \"A\"; [iFrame|]. iExists _, _. iFrame.\n    iIntros (? ? ? ? ? ?). iPureIntro.\n    hexploit H0; eauto. i. des. split; auto.\n  Qed.\n\n  Lemma wmemory_ra_get_strong\n        m l c\n    :\n    (wmemory_black_strong m)\n      -∗\n      (points_to l c)\n      -∗\n      ⌜m.(WMem.memory) l = c⌝.\n  Proof.\n    iIntros \"[BLACK _] WHITE\". iApply (wmemory_ra_get with \"BLACK WHITE\").\n  Qed.\n\n  Lemma wmemory_ra_load_acq\n        l V k (P Q: wProp)\n        m val vw0 vw1\n        ord lc1 to released\n        (READ: Local.read_step (WMem.view_to_local vw0) m.(WMem.memory) l to val released ord lc1)\n        (VIEW: vw1 = lc1.(Local.tview).(TView.cur))\n        (ORD: ord = Ordering.acqrel)\n    :\n    (wmemory_black_strong m)\n      -∗\n      (wpoints_to_full l V k P Q)\n      -∗\n      ((⌜View.le vw0 vw1⌝)\n         ∗ (wmemory_black_strong m)\n         ∗ (wpoints_to_full l V k P Q)\n         ∗ (((lift_wProp P val vw1)\n               ∗ (∃ ts, (ObligationRA.correl (inr (inr (l, ts))) k (Ord.S Ord.O))\n                          ∗ (⌜WMem.missed m.(WMem.memory) l to (l, ts) = Flag.fail⌝)))\n            ∨ ((lift_wProp Q val vw1) ∗ (⌜View.le V vw1⌝)))\n      ).\n  Proof.\n    iIntros \"BLACK [% [WHITE [% [% [[[[X Y] %] %] %]]]]]\". des. subst.\n    iPoseProof (wmemory_ra_get_strong with \"BLACK WHITE\") as \"%\". subst.\n    inv READ. ss. iSplit.\n    { iPureIntro. aggrtac. }\n    iAssert (⌜Cell.max_ts (WMem.memory m l) = Time.bot⌝\n             ∨ (ObligationRA.correl _ _ _))%I with \"[X]\" as \"#CORREL\".\n    { iPoseProof \"X\" as \"[X|X]\"; [auto|].\n      iRight. iApply (ObligationRA.duty_correl with \"X\"). ss. eauto.\n    }\n    iSplitL \"BLACK\"; [auto|]. iSplitL.\n    { iExists _. iFrame. iExists _, _. iSplit.\n      { iSplit.\n        { auto. }\n        { iPureIntro. esplits; eauto. }\n      }\n      { iPureIntro. auto. }\n    }\n    destruct (Time.eq_dec to (Cell.max_ts (WMem.memory m l))).\n    { iRight. subst. setoid_rewrite GET0 in GET. inv GET.\n      assert (val = v).\n      { inv VAL; ss.\n        destruct v, val; ss. apply Z.eqb_eq in H2. subst. auto.\n      }\n      subst. iSplit.\n      { unfold lift_wProp. iExists _. iSplit.\n        { iPureIntro. eauto. }\n        { iPureIntro. apply View.bot_spec. }\n      }\n      { iPureIntro. unfold View.singleton_ur_if. des_ifs.\n        eapply View.join_spec.\n        { aggrtac. }\n        { etrans; [|eapply View.join_l]. eapply View.join_r. }\n      }\n    }\n    { iLeft. hexploit Memory.max_ts_spec.\n      { eapply GET0. }\n      i. des. dup MAX. inv MAX; ss.\n      hexploit H1; eauto. i. des.\n      assert (val' = val).\n      { inv VAL; ss. destruct val, val'; ss. apply Z.eqb_eq in H4. subst. auto. }\n      subst. iSplitR.\n      { unfold lift_wProp. iExists _. iSplit.\n        { iPureIntro. eapply H1; eauto. }\n        { iPureIntro. apply View.bot_spec. }\n      }\n      iExists _. iSplitR.\n      { iPoseProof \"CORREL\" as \"[%BOT|CORR]\"; [|auto].\n        setoid_rewrite BOT in H0. inv H0.\n      }\n      iPureIntro.\n      destruct (LocSet.Facts.eq_dec l l); ss.\n      destruct (Time.le_lt_dec (Cell.max_ts (WMem.memory m l)) to).\n      { exfalso. eapply Time.lt_strorder.\n        eapply TimeFacts.lt_le_lt; [|apply l0]; eauto.\n      }\n      setoid_rewrite GET. hexploit RELEASED; auto.\n      { eapply TimeFacts.le_lt_lt; eauto. eapply Time.bot_spec. }\n      { i. des_ifs. }\n    }\n  Qed.\n\n  Lemma wmemory_ra_load_rlx\n        l V k (P Q: wProp)\n        m val vw0 vw1\n        ord lc1 to released\n        (READ: Local.read_step (WMem.view_to_local vw0) m.(WMem.memory) l to val released ord lc1)\n        (VIEW: vw1 = lc1.(Local.tview).(TView.cur))\n        (ORD: ord = Ordering.relaxed)\n    :\n    (wmemory_black_strong m)\n      -∗\n      (wpoints_to_full l V k P Q)\n      -∗\n      (⌜View.le V vw0⌝)\n      -∗\n      ((⌜View.le vw0 vw1⌝)\n         ∗ (wmemory_black_strong m)\n         ∗ (wpoints_to_full l V k P Q)\n         ∗ (lift_wProp Q val vw1)\n      ).\n  Proof.\n    iIntros \"BLACK [% [WHITE [% [% [[[X %] %] Z]]]]] %\". des. subst.\n    iPoseProof (wmemory_ra_get_strong with \"BLACK WHITE\") as \"%\". subst.\n    inv READ. ss.\n    assert (TO: to = Cell.max_ts (WMem.memory m l)).\n    { eapply TimeFacts.antisym.\n      { eapply Memory.max_ts_spec in GET0. des. clarify. }\n      { inv READABLE. etrans; eauto.\n        inv H1. ss. specialize (PLN0 l).\n        unfold TimeMap.singleton in PLN0. etrans; [|eauto].\n        unfold TimeMap.join. setoid_rewrite LocFun.add_spec_eq.\n        apply Time.join_r.\n      }\n    }\n    subst. setoid_rewrite GET0 in GET. inv GET.\n    assert (val = v).\n    { inv VAL; ss.\n      destruct v, val; ss. apply Z.eqb_eq in H2. subst. auto.\n    }\n    subst. iSplit.\n    { iPureIntro. aggrtac. }\n    iSplitL \"BLACK\"; [auto|]. iSplitL.\n    { iExists _. iFrame. iExists _, _. iSplit; eauto. iPureIntro. esplits; eauto. }\n    { unfold lift_wProp. iExists _. iPureIntro. splits; eauto. eapply View.bot_spec. }\n  Qed.\n\n  Lemma wmemory_ra_store_rel\n        l V k (P Q R: wProp)\n        m0 vw0 m1 val vw1\n        lc1 to sc1 mem1 ord from released kind\n        (WRITE: Local.write_step (WMem.view_to_local vw0) m0.(WMem.sc) m0.(WMem.memory) l from to val None released ord lc1 sc1 mem1 kind)\n        (VIEW: vw1 = lc1.(Local.tview).(TView.cur))\n        (MEM: m1 = WMem.mk mem1 sc1)\n        (ORD: ord = Ordering.acqrel)\n        (DEFINED: val <> Const.undef)\n    :\n    (wmemory_black_strong m0)\n      -∗\n      (wpoints_to_full l V k P Q)\n      -∗\n      (⌜View.le V vw0⌝)\n      -∗\n      (⌜R val View.bot⌝)\n      -∗\n      ((⌜View.le vw0 vw1⌝)\n         ∗ #=( ObligationRA.arrows_sat (Id:=sum_tid (void + WMem.ident)%type) )=> ((wmemory_black_strong m1))\n         ∗ (∃ V' k' o,\n               (⌜View.le V' vw1⌝)\n                 ∗\n                 (⌜View.le vw0 V'⌝)\n                 ∗\n                 #=>((wpoints_to_full l V' k' (wor P Q) R)\n                       ∗ (ObligationRA.black k' o)\n                    )\n           )\n      ).\n  Proof.\n    iIntros \"BLACK [% [WHITE [% [% [[[[_ Y] %] %] %]]]]] % %\". des. subst.\n    iPoseProof (wmemory_ra_get_strong with \"BLACK WHITE\") as \"%\". subst.\n    inv WRITE. ss. iSplit.\n    { iPureIntro. aggrtac. }\n    hexploit memory_write_bot_add; eauto. i. subst.\n    inv WRITE0. inv PROMISE. clear REMOVE PROMISES ATTACH TS.\n    iPoseProof (wmemory_ra_write_strong with \"BLACK WHITE\") as \"> [[BLACK WHITE] FAIRBLACK]\".\n    { eauto. }\n    assert (TS: Time.lt (Cell.max_ts (WMem.memory m0 l)) to).\n    { inv WRITABLE. eapply TimeFacts.le_lt_lt; [|eauto].\n      inv H2. ss. etrans; [|eapply RLX].\n      unfold TimeMap.join, TimeMap.singleton. setoid_rewrite LocFun.add_spec_eq.\n      eapply Time.join_r.\n    }\n    hexploit memory_write_max_ts.\n    { eauto. }\n    { left. auto. }\n    i. subst.\n    iPoseProof (ObligationRA.alloc) as \"> [% [[B W] PENDING]]\".\n    iPoseProof (ObligationRA.duty_alloc with \"[FAIRBLACK] W\") as \"> DUTY\".\n    { unfold ObligationRA.duty. iExists [], _.  iSplit.\n      { iFrame. iApply ObligationRA.duty_list_nil. }\n      { ss. }\n    }\n    iModIntro. iSplitL \"BLACK\"; [auto|].\n    iExists _, _, _. iSplit; cycle 1.\n    { iSplitR; cycle 1.\n      { iModIntro. iSplitR \"B\"; [|eauto].\n        iExists _. iSplitL \"WHITE\"; [auto|].\n        iExists _, _. iSplitL.\n        { iSplitL.\n          { iSplitL; [|eauto]. iSplitL \"DUTY\". eauto. iFrame. }\n          { iPureIntro. splits; eauto. esplits.\n            { eapply Memory.add_get0. eauto. }\n            { auto. }\n            { i. ss. }\n          }\n        }\n        { iPureIntro. i. setoid_rewrite Memory.add_o in GET0; eauto. des_ifs.\n          { ss. des; clarify. exfalso. eapply Time.lt_strorder. eapply LT. }\n          { des; ss. hexploit Memory.max_ts_spec; eauto. i. des. inv MAX.\n            { hexploit H1; eauto. i. des; ss. splits; auto. rr. auto. }\n            { inv H0. clarify. setoid_rewrite GET1 in GET. clarify.\n              splits; auto. rr. auto.\n            }\n          }\n        }\n      }\n      { iPureIntro. unfold TView.write_released. des_ifs. ss. des_ifs.\n        setoid_rewrite LocFun.add_spec_eq. aggrtac.\n      }\n    }\n    { iPureIntro. unfold TView.write_released. des_ifs. ss. des_ifs.\n      setoid_rewrite LocFun.add_spec_eq. eapply View.join_spec.\n      { eapply View.join_spec.\n        { eapply View.bot_spec. }\n        { reflexivity. }\n      }\n      { eapply View.join_r. }\n    }\n  Qed.\n\nEnd MEMRA.\n\nGlobal Opaque wmemory_black wpoints_to wpoints_to_faa wpoints_to_full.\n", "meta": {"author": "damhiya", "repo": "fairness", "sha": "279dcc679bd18b85666b97d6b540d94299c5d66e", "save_path": "github-repos/coq/damhiya-fairness", "path": "github-repos/coq/damhiya-fairness/fairness-279dcc679bd18b85666b97d6b540d94299c5d66e/src/example/WMM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.24708377318878272}}
{"text": "Require Import Defs Term_Defs Term StructTactics Event_system Term_system.\n\nRequire Import Lia Coq.Program.Tactics Coq.Program.Equality Coq.Arith.EqNat.\n\nRequire Import List.\nImport List.ListNotations.\n\nSet Nested Proofs Allowed.\n\n(* \n(ev_sys_remote t p q) represents (abstractly) the events that occur \nat place q, originated by a request from place p for q to execute t *)\nDefinition ev_sys_remote (t:Term) (p:Plc) (q:Plc): EvSys Ev.\nAdmitted.\n\n\nFixpoint ev_sys (t: AnnoTerm) p: EvSys Ev :=\n  match t with\n  | aasp (i, j) lr x => leaf (i, j) (asp_event i x p)\n  | aatt (i, j) lr (req_loc,rpy_loc) q x =>\n    before (i, j)\n      (leaf (i, S i) (req i req_loc p q (unanno x)))\n      (before (S i, j)\n              (* (ev_sys x q) *)\n              (ev_sys_remote (unanno x) p q)\n              (leaf (pred j, j) (rpy (pred j) rpy_loc p q)))\n  | alseq r lr x y => before r (ev_sys x p)\n                          (ev_sys y p)\n (* | abseq (i, j) lr s x y =>\n    before (i, j)\n           (leaf (i, S i)\n                 (Term_Defs.split i p))\n           (before (S i, j)\n                   (before (S i, (pred j))\n                           (ev_sys x p)\n                           (ev_sys y p))\n                   (leaf ((pred j), j)\n                   (join (pred j) p)))\n  | abpar (i, j) lr (xi,xi') (yi,yi') s x y =>\n    before (i, j)\n           (leaf (i, S i)\n                 (splitp i xi yi p))\n           (before (S i, j)\n                   (merge (S i, (pred j))\n                          (ev_sys x p)\n                          (ev_sys y p))\n                   (leaf ((pred j), j)\n                   (joinp (pred j) xi' yi' p)))\n*)\n  end.\n\n(*\nDefinition remote_event: Term -> Plc -> Ev.\nAdmitted.\n*)\n\n\nInductive events: AnnoTerm -> Plc -> Ev -> Prop :=\n| evtscpy:\n    forall r lr i p,\n      fst r = i ->\n      events (aasp r lr CPY) p (copy i p)\n| evtsusm:\n    forall i id args r lr p,\n      fst r = i ->\n      events (aasp r lr (ASPC id args)) p (umeas i p id args)\n| evtssig:\n    forall r lr i p,\n      fst r = i ->\n      events (aasp r lr SIG) p (sign i p) \n| evtshsh:\n    forall r lr i p,\n      fst r = i ->\n      events (aasp r lr HSH) p (hash i p)\n| evtsattreq:\n    forall r lr q t i p req_loc rpy_loc,\n      fst r = i ->\n      events (aatt r lr (req_loc, rpy_loc) q t) p (req i req_loc p q (unanno t))\n             (*\n| evtsatt:\n    forall r lr q t (*ev*) p locs,\n      events (aatt r lr locs q t) p (remote_event (unanno t) p)\n      (*events t q ev -> \n      events (aatt r lr locs q t) p ev\n       *)\n*)\n      \n| evtsattrpy:\n    forall r lr q t i p req_loc rpy_loc,\n      snd r = S i ->\n      events (aatt r lr (req_loc, rpy_loc) q t) p (rpy i rpy_loc p q)\n| evtslseql:\n    forall r lr t1 t2 ev p,\n      events t1 p ev ->\n      events (alseq r lr t1 t2) p ev\n| evtslseqr:\n    forall r lr t1 t2 ev p,\n      events t2 p ev ->\n      events (alseq r lr t1 t2) p ev\n(* | evtsbseqsplit:\n    forall r lr i s t1 t2 p,\n      fst r = i ->\n      events (abseq r lr s t1 t2) p\n             (Term_Defs.split i p)\n| evtsbseql:\n    forall r lr s t1 t2 ev p,\n      events t1 p ev ->\n      events (abseq r lr s t1 t2) p ev\n| evtsbseqr:\n    forall r lr s t1 t2 ev p,\n      events t2 p ev ->\n      events (abseq r lr s t1 t2) p ev\n| evtsbseqjoin:\n    forall r lr i s t1 t2 p,\n      snd r = S i ->\n      events (abseq r lr s t1 t2) p\n             (join i p)\n\n| evtsbparsplit:\n    forall r lr i s t1 t2 p xi xi' yi yi',\n      fst r = i ->\n      events (abpar r lr (xi,xi') (yi,yi') s t1 t2) p\n             (splitp i xi yi p)\n| evtsbparl:\n    forall r lr s t1 t2 ev p xlocs ylocs,\n      events t1 p ev ->\n      events (abpar r lr xlocs ylocs s t1 t2) p ev\n| evtsbparr:\n    forall r lr s t1 t2 ev p xlocs ylocs,\n      events t2 p ev ->\n      events (abpar r lr xlocs ylocs s t1 t2) p ev\n| evtsbparjoin:\n    forall r lr i s t1 t2 p xi xi' yi yi',\n      snd r = S i ->\n      events (abpar r lr (xi,xi') (yi,yi') s t1 t2) p\n             (joinp i (xi') (yi') p) *) .\nHint Constructors events : core.\n\n\nInductive store_event: Ev -> Plc -> Loc -> Prop :=\n| put_event: forall i x p q t, store_event (req i x p q t) p x\n(*| put_event_spl: forall i xi yi p, store_event (splitp i xi yi p) p xi\n| put_event_spr: forall i xi yi p, store_event (splitp i xi yi p) p yi *)\n| get_event: forall i x p q, store_event (rpy i x p q) p x\n(*| get_event_joinpl: forall i xi yi p, store_event (joinp i xi yi p) p xi\n| get_event_joinpr: forall i xi yi p, store_event (joinp i xi yi p) p yi *) .\n\n(*\nLemma wf_mono_locs: forall t,\n    well_formed t ->\n    fst (lrange t) <= snd (lrange t).\nProof.\n  intros.\n  rewrite Term.well_formed_lrange; eauto.\n  lia.\nDefined.\n*)\n\nLtac inv_wf :=\n  match goal with\n  | [H: well_formed (aasp _ _ _) |- _] =>\n    invc H\n  | [H: well_formed (alseq _ _ _ _) |- _] =>\n    invc H\n  | [H: well_formed (aatt _ _ _ _ ?t) |- _] =>   \n    invc H\n  (*| [H: well_formed (abseq _ _ _ _ _) |- _] =>\n    invc H\n  | [H: well_formed (abpar _ _ _ _ _ _ _) |- _] =>\n    invc H *)\n  end.\n\nLtac inv_ev :=\n  match goal with\n  | [H: events (aasp _ _ _) _ _ |- _] =>\n    invc H\n  | [H: events (alseq _ _ _ _) _ _ |- _] =>\n    invc H\n  | [H: events (aatt _ _ _ _ _) _ _ |- _] =>   \n    invc H\n  (*| [H: events (abseq _ _ _ _ _) _ _ |- _] =>\n    invc H\n  | [H: events (abpar _ _ _ _ _ _ _) _ _ |- _] =>\n    invc H *)\n  end.\n\nLtac inv_ev' :=\n  match goal with\n  | [H: events (aasp _ _ _) _ _ |- _] =>\n    inv H\n  | [H: events (alseq _ _ _ _) _ _ |- _] =>\n    inv H\n  | [H: events (aatt _ _ _ _ _) _ _ |- _] =>   \n    inv H\n  (* | [H: events (abseq _ _ _ _ _) _ _ |- _] =>\n    inv H\n  | [H: events (abpar _ _ _ _ _ _ _) _ _ |- _] =>\n    inv H *)\n  end.\n\nLtac inv_ev2 :=\n  match goal with\n  | [H: events _ _ _,\n     H': events _ _ _ |- _] =>\n    invc H; invc H'\n  end.\n\nLtac inv_ev2' :=\n  match goal with\n  | [H: events _ _ _,\n     H': events _ _ _ |- _] =>\n    inv H; inv H'\n  end.\n\nLtac inv_se :=\n  match goal with\n  | [H: store_event (?C _) (*(req _ _ _ _ _)*) _ _ |- _] =>\n    invc H\n         (*\n  | [H: events (alseq _ _ _ _) _ _ |- _] =>\n    invc H\n  | [H: events (aatt _ _ _ _ _) _ _ |- _] =>   \n    invc H\n  | [H: events (abseq _ _ _ _ _) _ _ |- _] =>\n    invc H\n  | [H: events (abpar _ _ _ _ _ _ _) _ _ |- _] =>\n    invc H *)\n  end.\n\nLtac inv_store_ev2 :=\n  match goal with\n  | [H: store_event _ _ _,\n     H': store_event _ _ _ |- _] =>\n    invc H; invc H'\n  end.\n\nLemma nodup_contra': forall ls ls' (loc:nat),\n    NoDup (ls ++ ls') ->\n    In loc ls ->\n    In loc ls' ->\n    False.\nProof.\n  intros.\n  generalizeEverythingElse ls.\n\n  (*\n  generalize dependent H0.\n  generalize dependent H1.\n  generalize dependent loc.\n  dependent induction H; intros.\n   *)\n  induction ls; destruct ls'; intros.\n  -\n    solve_by_inversion.\n  -\n    solve_by_inversion.\n  -\n    solve_by_inversion.\n  -\n    invc H0;\n      invc H1;\n      try solve_by_inversion.\n    +\n      invc H.\n      unfold not in *.\n      eapply H2.\n      assert (ls ++ loc :: ls' = ls ++ (loc :: ls')).\n      tauto.\n      \n      eapply in_or_app.\n      right.\n      simpl.\n      tauto.\n    +\n      invc H.\n      unfold not in *.\n      eapply H3.\n      eapply in_or_app.\n      right.\n      right.\n      eassumption.\n    +\n      eapply IHls with (ls' := (loc :: ls')).\n\n      invc H.\n      eassumption.\n      eassumption.\n      econstructor.\n      tauto.\n    +\n      invc H.\n      unfold not in *.\n\n      assert (NoDup (ls ++ ls')).\n      {\n        eapply NoDup_remove_1; eauto.\n      }\n\n      eauto.\nDefined.\n\nLemma in_app: forall ls ls' (loc:nat),\n    In loc ls ->\n    In loc (ls ++ ls').\nProof.\n  intros.\n  eapply in_or_app; eauto.\nDefined.\n\nLemma in_app2: forall ls ls' (loc:nat),\n    In loc ls' ->\n    In loc (ls ++ ls').\nProof.\n  intros.\n  eapply in_or_app; eauto.\nDefined.\n\nLtac in_app_facts :=\n  match goal with\n  | [H: In ?loc (lrange ?t1),\n        H': well_formed ?t1,\n            H'': well_formed ?t2 |- _] =>\n    try\n      (assert_new_proof_by\n         (In loc ((lrange t1) ++ (lrange t2)))\n         ltac:(eapply in_app; eauto));\n    try (assert_new_proof_by\n           (In loc ((lrange t2) ++ (lrange t1)))\n           ltac:(eapply in_app2; eauto))\n  end.\n\nLtac nodup_contra_auto :=\n  match goal with\n  | [H: In ?loc ?ls,\n        H': In ?loc ?ls',\n            H'': NoDup (?ls ++ ?ls') |- _] =>\n    exfalso; eapply nodup_contra'; eauto\n  end.\n\n\nLemma event_in_lrange: forall t p ev loc,\n    well_formed t ->\n    events t p ev ->\n    store_event ev p loc ->\n    In loc (lrange t).\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    destruct a;\n      inv_ev;\n      ff.\n  -\n    \n    inv_wf.\n\n    (*\n    clear H12.\n    clear H11.\n     *)\n    \n    \n\n    inv_ev'; ff.\n\n\n    \n\n    (*\n    ff;\n      inv_ev.\n    +\n      ff.\n      (*\n      assert (In req_loc l). admit.\n      ff.\n       *)\n      \n      (*\n      inv H1.\n      admit. *)\n    +\n      ff.\n      (*\n      assert (In rpy_loc l). admit.\n      ff.\n       *)\n      \n      (*\n      ff.\n      inv H1. *)\n     *)\n    \n  -\n    ff.\n    inv_wf.\n    (*\n    clear H11.\n    clear H12. *)\n    inv_ev.\n    +\n\n      assert (In loc (lrange t1)) by eauto.\n\n      (*\n\n      assert (list_subset (lrange t1) l). admit.\n       *)\n      \n      unfold list_subset in *.\n      eauto.\n\n      (*\n\n      assert (l = (lrange t1) ++ (lrange t2)).\n      admit.\n\n      subst;\n      in_app_facts; eauto. *)\n    +\n      assert (In loc (lrange t2)) by eauto.\n\n      (*\n\n      assert (list_subset (lrange t2) l). admit. *)\n      unfold list_subset in *.\n      eauto.\n\n      \n      (*\n\n      assert (l = (lrange t1) ++ (lrange t2)).\n      admit.\n\n      subst;\n        in_app_facts; eauto.\n       *)\n\n      (*\n\n  -\n    ff.\n    inv_wf.\n    (*\n    clear H12. *)\n    inv_ev;\n      try solve_by_inversion.\n    +\n      assert (In loc (lrange t1)) by eauto.\n\n      (*\n\n      assert (list_subset (lrange t1) l). admit. *)\n      unfold list_subset in *.\n      eauto.\n\n      (*\n\n      assert (l = (lrange t1) ++ (lrange t2)).\n      admit.\n\n      subst;\n      in_app_facts; eauto. *)\n    +\n      assert (In loc (lrange t2)) by eauto.\n\n      (*\n\n      assert (list_subset (lrange t2) l). admit.\n       *)\n      \n      unfold list_subset in *.\n      eauto.\n\n      \n      (*\n      assert (l = (lrange t1) ++ (lrange t2)).\n      admit.\n\n      subst;\n        in_app_facts; eauto.\n       *)\n      \n  -\n    ff.\n    inv_wf.\n\n    (*\n    clear H19.\n    clear H15.\n    clear H16.\n    clear H17.\n    clear H18.\n     *)\n    \n    \n\n    \n    inv_ev';\n      try solve_by_inversion;\n      try (eauto; tauto);\n      try (ff; congruence).\n    +\n      ff.\n      unfold list_subset in *.\n      ff.\n      repeat inv_se;\n        ff'.\n        \n      \n      (*\n      \n      assert (list_subset [xi; xi'; yi; yi'] l). admit.\n      unfold list_subset in *.\n\n      ff.\n       *)\n\n      (*\n    +\n      \n      assert (list_subset (lrange t1) l). admit.\n       \n      \n      unfold list_subset in *.\n      eauto.\n\n    +\n      assert (list_subset (lrange t2) l). admit.\n      unfold list_subset in *.\n      eauto.\n*)\n    +\n\n      (*\n      assert (list_subset [xi; xi'; yi; yi'] l). admit.\n       *)\n      \n      unfold list_subset in *.\n      ff.\n\n      repeat inv_se;\n        ff'.\n          \n      ++\n        repeat (find_apply_hyp_hyp').\n        tauto.\n*)\nDefined.\n\nLtac t_in_lrange :=\n  match goal with\n  | [H: events ?t ?p ?ev,\n        H': store_event ?ev ?p ?loc |- _] =>\n    assert_new_proof_by (In loc (lrange t)) ltac:(eapply event_in_lrange; eauto)\n  end.\n\nLemma unique_store_event_locs: forall t p ev ev' loc,\n    well_formed t ->\n    events t p ev ->\n    events t p ev' ->\n    store_event ev p loc ->\n    store_event ev' p loc ->\n    ev = ev'.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    inv_wf;\n      inv_ev2;\n      eauto.\n  -\n    inv_wf;\n      inv_ev2;\n       try (assert (req_loc = rpy_loc) by \n               (repeat inv_se; congruence));\n          repeat inv_se;\n          ff; congruence.\n \n  -\n    inv_wf.\n    (*\n    clear H13.\n    clear H14.\n     *)\n    \n    \n    inv_ev2;\n      try solve_by_inversion;\n      try eauto;\n      try (\n           (* unfold list_subset in *;  *)\n           repeat t_in_lrange;\n           nodup_contra_auto; tauto).\n\n    (*\n  -\n    inv_wf.\n    inv_ev2;\n      try solve_by_inversion;\n      try eauto;\n      try (\n          repeat t_in_lrange;\n          nodup_contra_auto; tauto).\n  -\n          Ltac nodup_inv :=\n        repeat \n        match goal with\n        | [H: NoDup (_::_) |- _] => invc H\n        end.\n    inv_wf.\n    \n    (* clear H21. *)\n    (*clear H17; clear H18; clear H19; clear H20. *)\n    inv_ev2;\n      try solve_by_inversion;\n      try (ff; congruence);\n      try (eauto; tauto);\n      try (repeat inv_se;\n           repeat t_in_lrange;\n           try in_app_facts;\n           ff;\n           nodup_inv;\n           ff;\n           try nodup_contra_auto;\n           tauto).\n*)\nDefined.\n\n(*\nLemma evsys_reps: forall t p ev,\n  ev_in ev (ev_sys t p) ->\n  ev_in ev (Term_system.ev_sys t p).\nProof.\nAdmitted.\n\nLemma events_reps: forall t p ev,\n  events t p ev ->\n  Term.events t p ev.\nProof.\nAdmitted.\n*)\n\nDefinition store_event_evsys es p loc := exists ev, store_event ev p loc /\\ ev_in ev es.\n\nInductive store_conflict: Plc -> EvSys Ev -> Prop :=\n| store_conflict_merge: forall r p es1 es2 loc,\n    store_event_evsys es1 p loc ->\n    store_event_evsys es2 p loc ->\n    store_conflict p (merge r es1 es2)\n| store_conflict_before_l: forall r p es1 es2,\n    store_conflict p es1 ->\n    store_conflict p (before r es1 es2)\n| store_conflict_before_r: forall r p es1 es2,\n    store_conflict p es2 ->\n    store_conflict p (before r es1 es2).\n\n\nAxiom ev_sys_iff_remote: forall t n p0,\n    (ev_sys t n = ev_sys_remote (unanno t) p0 n).\n\nAxiom no_nested_at_store_conflict: forall t p q,\n    not (store_conflict p (ev_sys_remote t p q)).\n\nAxiom events_remote: forall t p q ev n n' l loc loc',\n    ev_in ev (ev_sys_remote (unanno t) p q) ->\n    events (aatt (n, n') l (loc, loc') q t) p ev.\n\nLemma evsys_events:\n  forall t p ev,\n    well_formed_r t ->\n    ev_in ev (ev_sys t p) <-> events t p ev.\nProof.\n    split; revert p; induction t; intros; inv H; simpl in *;\n    repeat break_let; simpl in *.\n  - inv H0; auto; destruct a; simpl; auto.\n  - destruct p.\n    rewrite H8 in H0; simpl in H0.\n    repeat find_inversion.\n    inv H0; auto.\n\n    inv H3; auto. inv H3; auto.\n    +\n      apply events_remote; eauto.\n    +\n      inv H4; auto.\n  - inv H0; auto.\n\n    (*\n    \n  - rewrite H10 in H0; simpl in H0.\n\n    inv H0.\n\n    inv H3.\n    auto.\n\n    inv H3.\n\n    inv H3.\n\n    auto.\n\n    inv H4.\n    auto.\n\n   \n\n    inv H5.\n\n    auto.\n    auto.\n\n    inv H5.\n\n    inv H5.\n\n    auto.\n\n    inv H4.\n    inv H4.\n\n    auto.\n    \n  - destruct p; destruct p0.\n    rewrite H12 in H0; simpl in H0.\n    inv H0; auto. inv H3; auto. inv H3; auto. inv H4; auto. inv H4; auto.\n*)\n  - inv H0; auto.\n  - rewrite H8; simpl.\n    inv H0; auto.\n    simpl in *.\n    (*\n    rewrite H11 in H8. *)\n    assert (snd (range t) = i) by lia.\n    subst.\n    auto.\n    (*\n    apply Nat.succ_inj in H13; subst; auto. *)\n  - inv H0; auto.\n\n    (*\n  - rewrite H10; simpl.\n    inv H0; auto.\n    simpl in H13.\n\n    assert (snd (range t2) = i) by lia.\n    subst.\n    auto.\n\n    \n    (*\n    rewrite H12 in H10. \n    apply Nat.succ_inj in H10; subst; auto. *)\n    \n  - rewrite H12; simpl.\n    inv H0; auto.\n    simpl in *.\n    assert (snd (range t2) = i) by lia.\n    subst.\n    auto.\n\n    (*\n    rewrite H15 in H12.\n    apply Nat.succ_inj in H12; subst; auto. *)\n*)\n\nQed.\n\nLemma wf_implies_wfr: forall t,\n    well_formed t ->\n    well_formed_r t.\nProof.\n  induction t; intros;\n    try destruct a;\n    ff.\nDefined.\n\nLemma unique_store_events': forall t p ev1 ev2 loc,\n    well_formed t ->\n    ev_in ev1 (ev_sys t p) ->\n    ev_in ev2 (ev_sys t p) -> \n    store_event ev1 p loc ->\n    store_event ev2 p loc ->\n    ev1 <> ev2 ->\n    False.\nProof.\n  intros.\n  assert (ev1 = ev2).\n  {\n    eapply unique_store_event_locs;\n      try eassumption.\n    Locate evsys_events.\n    eapply evsys_events; eauto.\n    eapply wf_implies_wfr; eauto.\n    eapply evsys_events; eauto.\n    eapply wf_implies_wfr; eauto.\n  }\n  congruence.\nDefined.\n\nLemma unique_store_events_corollary: forall t p ev1 ev2 loc,\n    well_formed t ->\n    ev_in ev1 (ev_sys t p) -> \n    store_event ev1 p loc ->\n    store_event ev2 p loc ->\n    ev1 <> ev2 ->\n    not (ev_in ev2 (ev_sys t p)).\nProof.\n  intros.\n  unfold not; intros.\n  eapply unique_store_events'.\n  eassumption.\n  apply H0.\n  apply H4.\n  eassumption.\n  eassumption.\n  eassumption.\nDefined.\n\nLemma unique_events': forall r es1 es2 ev1 ev2,\n    well_structured ev (merge r es1 es2) ->\n    ev_in ev1 es1 ->\n    ev_in ev2 es2 ->\n    ev ev1 <> ev ev2.\nProof.\n  intros.\n  inv H.\n  assert (fst (es_range es1) <= ev ev1 < snd (es_range es1)).\n  {\n    eapply ws_evsys_range; eauto.\n  }\n\n  assert (fst (es_range es2) <= ev ev2 < snd (es_range es2)).\n  {\n    eapply ws_evsys_range; eauto.\n  }\n\n  lia.\nDefined.\n\nLemma unqev: forall ev1 ev2,\n  ev ev1 <> ev ev2 ->\n  ev1 <> ev2.\nProof.\n  intros.\n  unfold not; intros.\n  subst.\n  solve_by_inversion.\nDefined.\n\nLemma unique_events: forall r es1 es2 ev1 ev2,\n    well_structured ev (merge r es1 es2) ->\n    ev_in ev1 es1 ->\n    ev_in ev2 es2 ->\n    ev1 <> ev2.\nProof.\n  intros.\n  eapply unqev.\n  eapply unique_events';\n    eauto.\nDefined.\n\nLemma  evsys_range\n  : forall (t : AnnoTerm) (p : nat), es_range (ev_sys t p) = range t.\nProof.\n  induction t; intros; simpl; auto;\n    repeat break_let; simpl; auto.\nQed.\n\n(*\nLemma ws_remote: forall t p0 ev n,\n    well_structured ev (ev_sys t p0) ->\n    well_structured ev (ev_sys_remote (unanno t) p0 n).\nProof.\nAdmitted.\n*)\n\nLemma well_structured_evsys:\n  forall t p,\n    well_formed_r t ->\n    well_structured ev (ev_sys t p).\nProof.\n  induction t; intros; inv H; simpl;\n    repeat break_let; destruct r as [i k];\n      simpl in *; subst; auto.\n  - apply ws_leaf_event; auto;\n      destruct a; simpl; auto.\n  - apply ws_before; simpl; auto.\n    rewrite H6.\n\n    assert (ev_sys t n = ev_sys_remote (unanno t) p0 n) as HH.\n    {\n      eapply ev_sys_iff_remote.\n    }\n    rewrite <- HH.\n\n    apply ws_before; simpl; auto; rewrite evsys_range; auto.\n    \n  - apply ws_before; auto; repeat rewrite evsys_range; auto.\n\n    (*\n    \n  - repeat (apply ws_before; simpl in *; auto; repeat rewrite evsys_range; auto).\n    \n  - repeat (apply ws_before; simpl in *; auto; repeat rewrite evsys_range; auto).\n    repeat (apply ws_merge; simpl in *; auto; repeat rewrite evsys_range; auto).\n*)\nQed.\n\nTheorem no_store_conflicts: forall t p sys,\n    well_formed t ->\n    sys = ev_sys t p ->\n    not (store_conflict p sys).\nProof.\n  unfold not; intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    destruct a;\n      cbn in *;\n      repeat break_let;\n      subst;\n      solve_by_inversion.\n  -\n    destruct p.\n    destruct r.\n\n    (*\n    assert (p0 <> n). admit.\n     *)\n    \n\n    \n\n\n    \n    ff.\n    subst.\n    invc H1; ff.\n    invc H3; ff.\n\n    \n\n    pose\n      no_nested_at_store_conflict.\n    unfold not in *.\n    eauto.\n  -\n    ff.\n    subst.\n    invc H1;\n      do_wf_pieces.\n    (*\n  -\n\n      cbn in *;\n      repeat break_let;\n      subst.\n    inv H1.\n    +\n      solve_by_inversion.\n    +\n      inv H3.\n      ++\n        inv H4;\n          do_wf_pieces.\n      ++\n        solve_by_inversion.\n  - assert (well_structured ev sys).\n    {\n      rewrite H0.\n      eapply well_structured_evsys; eauto.\n      eapply wf_implies_wfr; eauto.\n      (*\n      rewrite H0.\n      eapply well_structured_evsys.\n      eassumption. *)\n    }\n    \n    cbn in *;\n      repeat break_let;\n      subst.\n    inv H1;\n      try solve_by_inversion.\n    +\n      inv H4;\n        try solve_by_inversion.\n      ++       \n        inv H5;\n          try solve_by_inversion.\n        +++\n          unfold store_event_evsys in *.\n          destruct_conjs.\n\n          assert (ev_in H7 (merge (S n, Nat.pred n0) (ev_sys t1 p1) (ev_sys t2 p1))).\n          {\n            eauto.\n          }\n          \n          assert (ev_in H9 (merge (S n, Nat.pred n0) (ev_sys t1 p1) (ev_sys t2 p1))).\n          {\n            eauto.\n          }\n\n          eapply unique_store_events' with (ev1:=H7) (ev2:=H9) (t:=(abpar (n, n0) l (n1,n2) (n3,n4) s t1 t2)) (p:=p1) (loc:=loc);\n            try eassumption;\n            try (simpl; eauto; tauto).\n          ++++  \n            inv H2.\n            inv H16.\n            eapply unique_events; eauto.\n*)\nDefined.\n\nFAILHERE\n\n\n\n    \n\n\n\n\n      \n    \n    \n  \n\n\n(*\n\nCreate HintDb lr.\n\nLemma rpy_events_lrange (t:AnnoTerm) : forall p i p1 q loc,\n    well_formed t ->\n    events t p (rpy i loc p1 q) ->\n    fst (lrange t) <= loc < snd (lrange t).\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n      try (\n        cbn in *;\n        inv_wf;\n        inv_ev;\n        simpl in *; subst;\n        try lia;\n        repeat (find_eapply_hyp_hyp);\n        repeat find_eapply_lem_hyp wf_mono_locs;\n        lia).\nDefined.\nHint Resolve rpy_events_lrange : lr.\n\nLemma req_events_lrange (t:AnnoTerm) : forall p i p1 q t0 loc,\n    well_formed t ->\n    events t p (req i loc p1 q  t0) ->\n    fst (lrange t) <= loc < snd (lrange t).\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    try (\n        cbn in *;\n        inv_wf;\n        inv_ev;\n        simpl in *; subst;\n        try lia;\n        repeat (find_eapply_hyp_hyp);\n        repeat find_eapply_lem_hyp wf_mono_locs;\n        lia).\nDefined.\nHint Resolve req_events_lrange : lr.\n\nLemma splitp_l_events_lrange (t:AnnoTerm) : forall p i p0 yi loc,\n    well_formed t ->\n    events t p (splitp i loc yi p0) ->\n    fst (lrange t) <= loc < snd (lrange t).\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    try (\n        cbn in *;\n        inv_wf;\n        inv_ev;\n        simpl in *; subst;\n        try lia;\n        repeat (find_eapply_hyp_hyp);\n        repeat find_eapply_lem_hyp wf_mono_locs;\n        lia).\nDefined.\nHint Resolve splitp_l_events_lrange : lr.\n\nLemma splitp_r_events_lrange (t:AnnoTerm) : forall p i p0 xi loc,\n    well_formed t ->\n    events t p (splitp i xi loc p0) ->\n    fst (lrange t) <= loc < snd (lrange t).\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    try (\n        cbn in *;\n        inv_wf;\n        inv_ev;\n        simpl in *; subst;\n        try lia;\n        repeat (find_eapply_hyp_hyp);\n        repeat find_eapply_lem_hyp wf_mono_locs;\n        lia).\nDefined.\nHint Resolve splitp_r_events_lrange : lr.\n\nLemma joinp_l_events_lrange (t:AnnoTerm) : forall p p0 i yi loc,\n    well_formed t ->\n    events t p (joinp i loc yi p0) ->\n    fst (lrange t) <= loc < snd (lrange t).\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    try (\n        cbn in *;\n        inv_wf;\n        inv_ev;\n        simpl in *; subst;\n        try lia;\n        repeat (find_eapply_hyp_hyp);\n        repeat find_eapply_lem_hyp wf_mono_locs;\n        lia).\nDefined.\nHint Resolve joinp_l_events_lrange : lr.\n\nLemma joinp_r_events_lrange (t:AnnoTerm) : forall p p0 i xi loc,\n    well_formed t ->\n    events t p (joinp i xi loc p0) ->\n    fst (lrange t) <= loc < snd (lrange t).\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    try (\n        cbn in *;\n        inv_wf;\n        inv_ev;\n        simpl in *; subst;\n        try lia;\n        repeat (find_eapply_hyp_hyp);\n        repeat find_eapply_lem_hyp wf_mono_locs;\n        lia).\nDefined.\nHint Resolve joinp_r_events_lrange : lr.\n\nLemma store_events_lrange (t:AnnoTerm) : forall p ev loc,\n    well_formed t ->\n    events t p ev ->\n    store_event ev loc ->\n    fst (lrange t) <= loc < snd (lrange t).\nProof.\n  intros.\n  inv H1;\n    eauto with lr.\nDefined.\n*)\n\nLtac pose_store_events :=\n  match goal with\n  | [H: events _ _ ?ev,\n        H': Loc |- _] =>\n    assert_new_proof_by (store_event ev H') econstructor\n  end.\n\n(*\nLtac pose_new_lrange :=\n  match goal with\n  | [H: well_formed ?t,\n        H': events ?t ?p ?ev,\n            H'': store_event ?ev ?loc\n     |- _] =>\n    pose_new_proof (store_events_lrange t p ev loc H H' H'')\n  end.\n*)\n\nLtac pose_lrange_facts :=\n  repeat pose_store_events\n  (*repeat pose_new_lrange; \n  repeat find_eapply_lem_hyp wf_mono_locs*) .\n\nLtac dest_lrange :=\n  match goal with\n  | [H: LocRange |- _] => destruct H\n  end.\n\nCreate HintDb rl.\n\nSet Nested Proofs Allowed.\n\nLemma store_event_locs: forall t p ev loc,\n    store_event ev loc ->\n    events t p ev ->\n    well_formed t ->\n    In loc (lrange t).\nProof.\nAdmitted.\n\n(* TODO:  check nodup_contra call sites *)\nLemma nodup_contra: forall (x (*y*): nat) ls ls',\n    In x ls  ->\n    In x (* y *) ls' ->\n    NoDup (ls ++ ls') ->\n    False.\nProof.\nAdmitted.\n\nLemma unique_req_locs: forall t p i i0 loc q q0 t0 t1,\n    well_formed t ->\n    events t p (req i  loc p q t0) ->\n    events t p (req i0 loc p q0 t1) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    inv_wf.\n    inv_ev2.\n  -\n\n    invc H.\n\n    invc H0.\n    invc H1.\n\n    ff.\n  -\n    ff.\n\n    inv H.\n\n    invc H0.\n    +\n      invc H1.\n      ++\n        eauto.\n      ++\n        eauto.\n\n\n\n        assert (In loc (lrange t1)).\n        {\n          eapply store_event_locs; eauto.\n          econstructor.\n        }\n\n        assert (In loc (lrange t2)).\n        {\n          eapply store_event_locs; eauto.\n          econstructor.\n        }\n\n        (* TODO:  NoDup ((lrange t1) ++ (lrange t2)) as part of well_formed? *)\n        assert (NoDup ((lrange t1) ++ (lrange t2))).\n        {\n          admit.\n        }\n\n        eauto.\n\n        exfalso.\n        eapply nodup_contra.\n        apply H0.\n        apply H1.\n        eassumption.\n    +\n      invc H1.\n      ++\n                assert (In loc (lrange t1)).\n        {\n          eapply store_event_locs; eauto.\n          econstructor.\n        }\n\n        assert (In loc (lrange t2)).\n        {\n          eapply store_event_locs; eauto.\n          econstructor.\n        }\n\n        (* TODO:  NoDup ((lrange t1) ++ (lrange t2)) as part of well_formed? *)\n        assert (NoDup ((lrange t1) ++ (lrange t2))).\n        {\n          admit.\n        }\n\n        eauto.\n\n        exfalso.\n        eapply nodup_contra.\n        apply H0.\n        apply H1.\n        eassumption.\n\n      ++\n\n        assert (In loc t2\n        \n        \n        \n        \n      \n      \n          \n        \n        \n        \n        \n\n        ff.\n        \n\n        \n      ff.\n\n    \n    \n\n    \n\n    ff.\n\n    invc H0.\n    ff.\n    +\n      ff.\n      invc H1.\n      ++\n        eauto.\n      ++\n        \n        \n        \n    \n\n\n    \n    inv_wf.\n    inv_ev2; try eauto.\n\n    admit.\n\n    \n    inv_ev2;\n      try eauto.\n\n    ff.\n    \n    \n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_req_locs : rl.\n\nLemma unique_req_splitp_l_locs:\n  forall (t : AnnoTerm) (p i i0 loc p0 p1 q yi : nat) (t0: Term),\n    well_formed t ->\n    events t p (req i loc p0 q t0) ->\n    events t p (splitp i0 loc yi p1) -> i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_req_splitp_l_locs : rl.\n\nLemma unique_req_splitp_r_locs:\n  forall (t : AnnoTerm) (p i i0 loc p0 p1 q xi : nat) (t0: Term),\n    well_formed t ->\n    events t p (req i loc p0 q t0) ->\n    events t p (splitp i0 xi loc p1) -> i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_req_splitp_r_locs: rl.\n\nLemma unique_req_rpy_locs\n  : forall (t : AnnoTerm) (p i i0 loc p0 p1 q q0 : nat) (t0: Term),\n    well_formed t ->\n    events t p (req i loc p0 q t0) ->\n    events t p (rpy i0 loc p1 q0) -> i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_req_rpy_locs: rl.\n\nLemma unique_splitp_splitp_ll_locs:\n  forall (t : AnnoTerm) (p i i0 loc p0 p1 yi yi0 : nat),\n    well_formed t ->\n    events t p (splitp i  loc yi  p0) ->\n    events t p (splitp i0 loc yi0 p1) -> i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_splitp_splitp_ll_locs: rl.\n\nLemma unique_splitp_splitp_rl_locs:\n  forall (t : AnnoTerm) (p i i0 loc p0 p1 yi yi0 : nat),\n    well_formed t ->\n    events t p (splitp i0 loc yi0 p1) ->\n    events t p (splitp i  yi loc  p0) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_splitp_splitp_rl_locs: rl.\n\nLemma unique_rpy_splitp_l_locs:\n  forall (t : AnnoTerm) (p i i0 loc p0 p1 q yi : nat),\n    well_formed t ->\n    events t p (rpy i loc p0 q) ->\n    events t p (splitp i0 loc yi p1) -> i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_rpy_splitp_l_locs: rl.\n\nLemma unique_splitp_splitp_rr_locs:\n  forall (t : AnnoTerm) (p i i0 loc p0 p1 xi xi0 : nat),\n    well_formed t ->\n    events t p (splitp i  xi loc  p0) ->\n    events t p (splitp i0 xi0 loc p1) -> i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_splitp_splitp_rr_locs: rl.\n\nLemma unique_rpy_splitp_r_locs:\n  forall (t : AnnoTerm) (p i i0 loc p0 p1 q xi : nat),\n    well_formed t ->\n    events t p (rpy i loc p0 q) ->\n    events t p (splitp i0 xi loc p1) -> i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_rpy_splitp_r_locs: rl.\n\nLemma unique_rpy_locs\n  : forall (t : AnnoTerm) (p i i0 loc p0 p1 q q0 : nat),\n    well_formed t ->\n    events t p (rpy i  loc p0 q) ->\n    events t p (rpy i0 loc p1 q0) -> i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_rpy_locs: rl.\n\nLemma unique_splitpl_joinpl_locs\n  : forall (t : AnnoTerm) (p i i0 loc p1 q0 yi yi' : nat),\n    well_formed t ->\n    events t p (splitp i loc yi p1) ->\n    events t p (joinp i0 loc yi' q0) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_splitpl_joinpl_locs: rl.\n\nLemma unique_req_joinpl_locs\n  : forall (t : AnnoTerm) (p i i0 loc p0 q q0 yi : nat) t0,\n    well_formed t ->\n    events t p (req i loc p0 q t0) ->\n    events t p (joinp i0 loc yi q0) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_req_joinpl_locs: rl.\n\nLemma unique_splitpr_joinpl_locs\n  : forall (t : AnnoTerm) (p i i0 loc p1 q0 xi yi : nat),\n    well_formed t ->\n    events t p (splitp i xi loc p1) ->\n    events t p (joinp i0 loc yi q0) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_splitpr_joinpl_locs: rl.\n\nLemma unique_rpy_joinpl_locs\n  : forall (t : AnnoTerm) (p i i0 loc p0 q q0 yi : nat),\n    well_formed t ->\n    events t p (rpy i loc p0 q) ->\n    events t p (joinp i0 loc yi q0) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_rpy_joinpl_locs: rl.\n\nLemma unique_joinpl_joinpl_locs\n  : forall (t : AnnoTerm) (p i i0 loc p1 q0 yi yi' : nat),\n    well_formed t ->\n    events t p (joinp i  loc yi p1) ->\n    events t p (joinp i0 loc yi' q0) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_joinpl_joinpl_locs: rl.\n\nLemma unique_req_joinpr_locs\n  : forall (t : AnnoTerm) (p i i0 loc p0 q q0 xi : nat) t0,\n    well_formed t ->\n    events t p (req i loc p0 q t0) ->\n    events t p (joinp i0 xi loc q0) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_req_joinpr_locs: rl.\n\nLemma unique_splitpl_joinpr_locs\n  : forall (t : AnnoTerm) (p i i0 loc p1 q0 yi xi : nat),\n    well_formed t ->\n    events t p (splitp i loc yi p1) ->\n    events t p (joinp i0 xi loc q0) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_splitpl_joinpr_locs: rl.\n\nLemma unique_splitpr_joinpr_locs\n  : forall (t : AnnoTerm) (p i i0 loc p1 q0 xi xi' : nat),\n    well_formed t ->\n    events t p (splitp i xi loc p1) ->\n    events t p (joinp i0 xi' loc q0) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_splitpr_joinpr_locs: rl.\n\nLemma unique_rpy_joinpr_locs\n  : forall (t : AnnoTerm) (p i i0 loc p0 q q0 xi : nat),\n    well_formed t ->\n    events t p (rpy i loc p0 q) ->\n    events t p (joinp i0 xi loc q0) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_rpy_joinpr_locs: rl.\n\nLemma unique_joinpl_joinpr_locs\n  : forall (t : AnnoTerm) (p i i0 loc p1 q0 xi yi : nat),\n    well_formed t ->\n    events t p (joinp i  xi loc p1) ->\n    events t p (joinp i0 loc yi q0) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_joinpl_joinpr_locs: rl.\n\nLemma unique_joinpr_joinpr_locs\n  : forall (t : AnnoTerm) (p i i0 loc p1 q0 xi xi' : nat),\n    well_formed t ->\n    events t p (joinp i  xi  loc p1) ->\n    events t p (joinp i0 xi' loc q0) ->\n    i = i0.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros;\n    inv_wf;\n    inv_ev2;\n    try eauto;\n    dest_lrange; simpl in *;\n      try (pose_lrange_facts;    \n           lia).\nDefined.\nHint Resolve unique_joinpr_joinpr_locs: rl.\n\n\nLtac flip a :=\n  try (eapply a;\n       eauto; tauto);\n  try (symmetry;\n       eapply a;\n       eauto; tauto);\n  tauto.\n\nLtac dorl' a b c d e f g h i j k l m n o p q r s t u :=\n    first\n      [ flip a\n      | flip b\n      | flip c\n      | flip d\n      | flip e\n      | flip f\n      | flip g\n      | flip h\n      | flip i\n      | flip j\n      | flip k\n      | flip l\n      | flip m\n      | flip n\n      | flip o\n      | flip p\n      | flip q\n      | flip r\n      | flip s\n      | flip t\n      | flip u\n      ].\n\nLtac dorl :=\n  dorl'\n    unique_req_locs\n    unique_req_splitp_l_locs\n    unique_req_splitp_r_locs\n    unique_req_rpy_locs\n    unique_req_joinpl_locs\n    unique_splitp_splitp_ll_locs\n    unique_splitp_splitp_rl_locs\n    unique_rpy_splitp_l_locs\n    unique_splitpl_joinpl_locs\n    unique_splitp_splitp_rr_locs\n    unique_rpy_splitp_r_locs\n    unique_splitpr_joinpl_locs\n    unique_rpy_locs\n    unique_rpy_joinpl_locs\n    unique_joinpl_joinpl_locs\n    unique_req_joinpr_locs\n    unique_splitpl_joinpr_locs\n    unique_splitpr_joinpr_locs\n    unique_rpy_joinpr_locs\n    unique_joinpl_joinpr_locs\n    unique_joinpr_joinpr_locs.\n    \nLemma unique_store_events: forall t p ev1 ev2 loc,\n  well_formed t ->\n  events t p ev1 ->\n  events t p ev2 ->\n  store_event ev1 loc ->\n  store_event ev2 loc ->\n  ev1 = ev2.\nProof.\n  intros.\n  eapply events_injective; eauto.\n  invc H2;\n    invc H3;\n    simpl;\n    try dorl.\nDefined.\n\nLemma unique_store_events': forall t p ev1 ev2 loc,\n    well_formed t ->\n    ev_in ev1 (ev_sys t p) ->\n    ev_in ev2 (ev_sys t p) -> \n    store_event ev1 loc ->\n    store_event ev2 loc ->\n    ev1 <> ev2 ->\n    False.\nProof.\n  intros.\n  assert (ev1 = ev2).\n  {\n    eapply unique_store_events;\n      try eassumption.\n    eapply evsys_events; eauto.\n    eapply evsys_events; eauto.\n  }\n  congruence.\nDefined.\n\nDefinition store_event_evsys es loc := exists ev, store_event ev loc /\\ ev_in ev es.\n\nInductive store_conflict: EvSys Ev -> Prop :=\n| store_conflict_merge: forall r es1 es2 loc,\n    store_event_evsys es1 loc ->\n    store_event_evsys es2 loc ->\n    store_conflict (merge r es1 es2)\n| store_conflict_before_l: forall r es1 es2,\n    store_conflict es1 ->\n    store_conflict (before r es1 es2)\n| store_conflict_before_r: forall r es1 es2,\n    store_conflict es2 ->\n    store_conflict (before r es1 es2).\n\nLemma unique_events': forall r es1 es2 ev1 ev2,\n    well_structured ev (merge r es1 es2) ->\n    ev_in ev1 es1 ->\n    ev_in ev2 es2 ->\n    ev ev1 <> ev ev2.\nProof.\n  intros.\n  inv H.\n  assert (fst (es_range es1) <= ev ev1 < snd (es_range es1)).\n  {\n    eapply ws_evsys_range; eauto.\n  }\n\n  assert (fst (es_range es2) <= ev ev2 < snd (es_range es2)).\n  {\n    eapply ws_evsys_range; eauto.\n  }\n\n  lia.\nDefined.\n\nLemma unqev: forall ev1 ev2,\n  ev ev1 <> ev ev2 ->\n  ev1 <> ev2.\nProof.\n  intros.\n  unfold not; intros.\n  subst.\n  solve_by_inversion.\nDefined.\n\nLemma unique_events: forall r es1 es2 ev1 ev2,\n    well_structured ev (merge r es1 es2) ->\n    ev_in ev1 es1 ->\n    ev_in ev2 es2 ->\n    ev1 <> ev2.\nProof.\n  intros.\n  eapply unqev.\n  eapply unique_events';\n    eauto.\nDefined.\n\n\n\nDefinition store_event_evsys es loc := exists ev, store_event ev loc /\\ ev_in ev es.\n\nInductive store_conflict: EvSys Ev -> Prop :=\n| store_conflict_merge: forall r es1 es2 loc,\n    store_event_evsys es1 loc ->\n    store_event_evsys es2 loc ->\n    store_conflict (merge r es1 es2)\n| store_conflict_before_l: forall r es1 es2,\n    store_conflict es1 ->\n    store_conflict (before r es1 es2)\n| store_conflict_before_r: forall r es1 es2,\n    store_conflict es2 ->\n    store_conflict (before r es1 es2).\n\nTheorem no_store_conflicts: forall t p sys,\n    well_formed t ->\n    sys = ev_sys t p ->\n    not (store_conflict sys).\nProof.\n  unfold not; intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    destruct a;\n      cbn in *;\n      repeat break_let;\n      subst;\n      solve_by_inversion.\n  -\n    cbn in *;\n      repeat break_let;\n      subst.\n    inv H1.\n    +\n      solve_by_inversion.\n    +\n      inv H2;\n        try solve_by_inversion;\n        try inv_wf; eauto.\n      \n  -\n    cbn in *;\n      repeat break_let;\n      subst.\n    inv H1;\n      do_wf_pieces.\n  -\n    cbn in *;\n      repeat break_let;\n      subst.\n    inv H1.\n    +\n      solve_by_inversion.\n    +\n      inv H2.\n      ++\n        inv H3;\n          do_wf_pieces.\n      ++\n        solve_by_inversion.\n  -\n    \n    assert (well_structured ev sys).\n    {\n      rewrite H0.\n      eapply well_structured_evsys.\n      eassumption.\n    }\n    \n    cbn in *;\n      repeat break_let;\n      subst.\n    inv H1;\n      try solve_by_inversion.\n    +\n      inv H3;\n        try solve_by_inversion.\n      ++       \n        inv H4;\n          try solve_by_inversion.\n        +++\n          unfold store_event_evsys in *.\n          destruct_conjs.\n\n          assert (ev_in H6 (merge (S n, Nat.pred n0) (ev_sys t1 p1) (ev_sys t2 p1))).\n          {\n            eauto.\n          }\n          \n          assert (ev_in H8 (merge (S n, Nat.pred n0) (ev_sys t1 p1) (ev_sys t2 p1))).\n          {\n            eauto.\n          }\n\n          eapply unique_store_events' with (ev1:=H6) (ev2:=H8) (t:=(abpar (n, n0) l (n1,n2) (n3,n4) s t1 t2)) (p:=p1) (loc:=loc);\n            try eassumption;\n            try (simpl; eauto; tauto).\n          ++++  \n            inv H2.\n            inv H16.\n            eapply unique_events; eauto.\nDefined.\n", "meta": {"author": "ku-sldg", "repo": "copland-avm", "sha": "6c08b0e3df96a22cc675bcea309fe99ea7deca65", "save_path": "github-repos/coq/ku-sldg-copland-avm", "path": "github-repos/coq/ku-sldg-copland-avm/copland-avm-6c08b0e3df96a22cc675bcea309fe99ea7deca65/src/extra/Store_Semantics_alt_Old.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24703296844699485}}
{"text": "(*===========================================================================\n  Auxiliary lemmas for Hoare triples on *programs*\n  ===========================================================================*)\nRequire Import ssreflect ssrbool ssrnat eqtype seq fintype.\nRequire Import procstate procstatemonad bitsops bitsprops bitsopsprops.\nRequire Import SPred septac spec spectac safe pointsto cursor instr reader instrcodec.\nRequire Import Setoid RelationClasses Morphisms.\nRequire Import program basic antiframe.\n\n(* Morphism for program equivalence *)\nGlobal Instance basic_progEq_m:\nProper (lequiv ==> progEq ==> lequiv ==> lequiv) basic.\n  Proof.\n    move => P P' HP c c' Hc Q Q' HQ. rewrite {1}/basic.\n    setoid_rewrite HQ. setoid_rewrite HP. setoid_rewrite Hc. reflexivity.\n  Qed.\n\n(* Skip rule *)\nLemma basic_skip P: |-- basic P prog_skip P.\nProof.\n  rewrite /basic. specintros => i j.\n  unfold_program.\n  specintro => H.\n  rewrite emp_unit spec_reads_eq_at; rewrite <- emp_unit.\n  rewrite spec_at_emp. inversion H. subst. by apply limplValid.\nQed.\n\n(* Sequencing rule *)\nLemma basic_seq (c1 c2: program) S P Q R:\n  S |-- basic P c1 Q ->\n  S |-- basic Q c2 R ->\n  S |-- basic P (c1;; c2) R.\nProof.\n  rewrite /basic. move=> Hc1 Hc2. specintros => i j.\n  unfold_program.\n  specintro => i'. rewrite -> memIsNonTop. specintros => p' EQ. subst.\n  specapply Hc1. by ssimpl.\n  specapply Hc2. by ssimpl.\n  rewrite <-spec_reads_frame. apply: limplAdj. apply: landL2.\n  by rewrite spec_at_emp.\nQed.\n\n(* Scoped label rule *)\nLemma basic_local S P c Q:\n  (forall l, S |-- basic P (c l) Q) ->\n  S |-- basic P (prog_declabel c) Q.\nProof.\n  move=> H. rewrite /basic. rewrite /memIs /=. specintros => i j l.\n  specialize (H l). lforwardR H.\n  - apply lforallL with i. apply lforallL with j. reflexivity.\n  apply H.\nQed.\n\n(* Needed to avoid problems with coercions *)\nLemma basic_instr S P i Q :\n  S |-- basic P i Q ->\n  S |-- basic P (prog_instr i) Q.\nProof. done. Qed.\n\nLemma regMissingIn_program r (i j: DWORD) (c: program):\n  regMissingIn r (i -- j :-> c).\nProof.\n  move: i j.\n  induction c => i j; unfold_program; by eauto with reg_not_in.\nQed.\nHint Resolve regMissingIn_program : reg_not_in.\n\nLemma antiframe_register_basic (r: Reg) P Q c:\n  regNotFree r P ->\n  (forall v, |-- basic (P ** r~=v) c (Q ** r~=v)) ->\n  |-- basic P c Q.\nProof.\n  rewrite /basic /spec_reads => HregNotFree H.\n  specintros => i j s Hs. autorewrite with push_at. apply limplValid.\n  apply antiframe_register with r.\n  - apply regNotFree_sepSP.\n    + apply regNotFree_sepSP; last done. apply regNotFree_reg.\n      by destruct r; first destruct r.\n    + apply regMissingIn_regNotFree. rewrite ->Hs. auto with reg_not_in.\n  - apply _.\n  - move => v. specialize (H v). lforwardR H.\n    { apply lforallL with i. apply lforallL with j. apply lforallL with s.\n      apply lpropimplL; first done. reflexivity. }\n    specapply H; first by ssimpl. autorewrite with push_at.\n    rewrite spec_reads_emp. cancel1. by ssimpl.\nQed.\n\n(* Attempts to apply \"basic\" lemma on a single command (basic_basic) or\n   on the first of a sequence (basic_seq). Note that it attempts to use sbazooka\n   to discharge subgoals, so be careful if existentials are exposed in the goal --\n   they will be instantiated! *)\n  Hint Unfold not : basicapply.\n  Hint Rewrite eq_refl : basicapply.\n  Ltac instRule R H :=\n    move: (R) => H;\n    repeat (autounfold with basicapply in H);\n    eforalls H;\n    autorewrite with push_at in H.\n\n\n  (* This is all very sensitive to use of \"e\" versions of apply/exact. Beware! *)\n  (* We ensure that we leave at most one goal remaining. *)\n  Ltac basicatom R tacfin :=\n  lazymatch goal with\n    | |- |-- basic ?P (prog_instr ?i) ?Q =>\n          (eapply basic_basic; first eapply basic_instr; [ eexact R | tacfin .. | try tacfin ])\n\n    | _ => eapply basic_basic; [ eexact R | tacfin .. | try tacfin ]\n    end.\n\n  Ltac  basicseq R tacfin :=\n  lazymatch goal with\n    | |- |-- basic ?P (prog_seq ?p1 ?p2) ?Q => (eapply basic_seq; first basicatom R tacfin)\n    | _ => basicatom R tacfin\n    end.\n\n  Ltac basicapply R tac tacfin :=\n    let Hlem := fresh \"Hlem\" in\n    instRule R Hlem;\n    tac Hlem;\n    first basicseq Hlem tacfin;\n    clear Hlem.\n\n  Tactic Notation \"basicapply\" open_constr(R) \"using\" tactic3(tac) \"side\" \"conditions\" tactic(tacfin) := basicapply R tac tacfin.\n  Tactic Notation \"basicapply\" open_constr(R) \"using\" tactic3(tac) := basicapply R using (tac) side conditions by autounfold with spred; sbazooka.\n  Tactic Notation \"basicapply\" open_constr(R) \"side\" \"conditions\" tactic(tacfin) := basicapply R using (fun Hlem => autorewrite with basicapply in Hlem) side conditions tacfin.\n  Tactic Notation \"basicapply\" open_constr(R) := basicapply R using (fun Hlem => autorewrite with basicapply in Hlem).\n  (** Variant of [basicapply] that doesn't require that the side conditions be fully solved. *)\n  Tactic Notation \"try_basicapply\" open_constr(R) \"using\" tactic3(tac) := basicapply R using (tac) side conditions autounfold with spred; sbazooka.\n  Tactic Notation \"try_basicapply\" open_constr(R) := try_basicapply R using (fun Hlem => autorewrite with basicapply in Hlem).\n", "meta": {"author": "jbj", "repo": "x86proved", "sha": "d314fa6d23c064a2be4bf686ac7da16a591fda01", "save_path": "github-repos/coq/jbj-x86proved", "path": "github-repos/coq/jbj-x86proved/x86proved-d314fa6d23c064a2be4bf686ac7da16a591fda01/src/x86/basicprog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24703296844699485}}
{"text": "From iris.algebra Require Import frac.\nFrom iris.proofmode Require Import proofmode.\nRequire Import Eqdep_dec List.\nFrom cap_machine Require Import rules logrel fundamental.\nFrom cap_machine.examples Require Import template_adequacy macros_new.\nFrom cap_machine Require Import proofmode.\nOpen Scope Z_scope.\n\nSection counter.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ} {sealg:sealStoreG Σ}\n          {nainv: logrel_na_invs Σ}\n          `{MP: MachineParameters}.\n\n  Definition N : namespace := nroot .@ \"mincounter\".\n\n  (* In this example, we avoid computing offsets by hand, and instead define the\n     code in two steps, computing the labels automatically (mimicking the steps\n     a proper assembler would do). *)\n\n  Definition counter_init0 (init code data end_: Z) : list Word :=\n    (* init: *)\n    encodeInstrsW [\n      Mov r_t1 PC;\n      Lea r_t1 (data-init)%Z;\n      Mov r_t2 r_t1;\n      Lea r_t2 1;\n      Store r_t1 r_t2;\n      Lea r_t1 (code-data)%Z;\n      Subseg r_t1 code end_;\n      Restrict r_t1 (encodePerm E);\n      Mov r_t2 0;\n      Jmp r_t0\n    ].\n  Definition counter_code0 (code data: Z) : list Word :=\n    (* code: *)\n    encodeInstrsW [\n      Mov r_t1 PC;\n      Lea r_t1 (data-code)%Z;\n      Load r_t1 r_t1;\n      Load r_t2 r_t1;\n      Add r_t2 r_t2 1;\n      Store r_t1 r_t2;\n      Mov r_t1 0;\n      Jmp r_t0\n    ].\n  Definition counter_data : list Word :=\n    (* data: *)\n    map WInt [7777 (* placeholder *); 0 (* current value of the counter *)]\n    (* end: *).\n\n  Definition code_off := Eval compute in length (counter_init0 0 0 0 0).\n  Definition data_off := Eval compute in length (counter_code0 0 0).\n  Definition end_off := Eval compute in length counter_data.\n\n  Definition counter_init (init: Z) : list Word :=\n    counter_init0 init (init + code_off) (init + code_off + data_off)\n                  (init + code_off + data_off + end_off).\n\n  Definition counter_code (code: Z) : list Word :=\n    counter_code0 code (code + data_off).\n\n  (* Specification for the init routine *)\n\n  Local Ltac solve_addr' :=\n    repeat match goal with x := _ |- _ => subst x end;\n    unfold code_off, data_off, end_off in *; solve_addr.\n\n  Lemma counter_init_spec (a_init: Addr) wadv w1 w2 wdat φ :\n    let a_code := (a_init ^+ code_off)%a in\n    let a_data := (a_init ^+ (code_off + data_off))%a in\n    let a_end := (a_init ^+ (code_off + data_off + end_off))%a in\n    ContiguousRegion a_init (code_off + data_off + end_off) →\n\n   ⊢ (( PC ↦ᵣ WCap RWX a_init a_end a_init\n      ∗ r_t0 ↦ᵣ wadv\n      ∗ r_t1 ↦ᵣ w1\n      ∗ r_t2 ↦ᵣ w2\n      ∗ a_data ↦ₐ wdat\n      ∗ codefrag a_init (counter_init a_init)\n      ∗ ▷ (  PC ↦ᵣ updatePcPerm wadv\n           ∗ r_t0 ↦ᵣ wadv\n           ∗ r_t1 ↦ᵣ WCap E a_code a_end a_code\n           ∗ r_t2 ↦ᵣ WInt 0\n           ∗ a_data ↦ₐ WCap RWX a_init a_end (a_data ^+ 1)%a\n           ∗ codefrag a_init (counter_init a_init)\n           -∗ WP Seq (Instr Executable) {{ φ }}))\n      -∗ WP Seq (Instr Executable) {{ φ }})%I.\n  Proof.\n    intros a_code a_data a_end.\n    iIntros (Hcont) \"(HPC & Hr0 & Hr1 & Hr2 & Hdat & Hprog & Hφ)\".\n    iGo \"Hprog\".\n    { transitivity (Some a_data); auto. solve_addr'. }\n    iGo \"Hprog\".\n    { transitivity (Some a_code); auto. solve_addr'. }\n    iGo \"Hprog\".\n    { transitivity (Some a_code); auto. solve_addr'. }\n    { transitivity (Some a_end); auto. solve_addr'. }\n    solve_addr'.\n    iGo \"Hprog\"; rewrite decode_encode_perm_inv //.\n    iGo \"Hprog\". iApply \"Hφ\". iFrame.\n    rewrite (_: (a_init ^+ 19) = a_data ^+ 1)%a //. solve_addr'.\n  Qed.\n\n  Lemma counter_code_spec (a_init: Addr) wcont w1 w2 φ :\n    let a_code := (a_init ^+ code_off)%a in\n    let a_data := (a_code ^+ data_off)%a in\n    let a_end := (a_code ^+ (data_off + end_off))%a in\n    ContiguousRegion a_code (data_off + end_off) →\n\n  ⊢ (( inv (N.@\"cap\") (a_data ↦ₐ WCap RWX a_init a_end (a_data ^+ 1)%a)\n     ∗ inv with_adv.invN (∃ n, (a_data ^+ 1)%a ↦ₐ WInt n ∗ ⌜0 ≤ n⌝)\n     ∗ na_inv logrel_nais (N.@\"code\") (codefrag a_code (counter_code a_code))\n     ∗ PC ↦ᵣ WCap RX a_code a_end a_code\n     ∗ r_t0 ↦ᵣ wcont\n     ∗ r_t1 ↦ᵣ w1\n     ∗ r_t2 ↦ᵣ w2\n     ∗ na_own logrel_nais ⊤\n     ∗ ▷ (∀ (n: Z),\n            PC ↦ᵣ updatePcPerm wcont\n          ∗ r_t0 ↦ᵣ wcont\n          ∗ r_t1 ↦ᵣ WInt 0\n          ∗ r_t2 ↦ᵣ WInt n\n          ∗ na_own logrel_nais ⊤\n          -∗ WP Seq (Instr Executable) {{ φ }}))\n     -∗ WP Seq (Instr Executable) {{ φ }})%I.\n  Proof.\n    intros a_code a_data a_end.\n    iIntros (Hcont) \"(#HIcap & #HIv & #HIcode & HPC & Hr0 & Hr1 & Hr2 & Hna & Hφ)\".\n    assert (Ha_code: a_code = (a_init ^+ code_off)%a) by done. clearbody a_code.\n    (* open the invariant containing the code *)\n    iMod (na_inv_acc logrel_nais with \"HIcode Hna\") as \"(>Hcode & Hna & Hclose_code)\".\n    done. done.\n\n    iGo \"Hcode\".\n    { transitivity (Some a_data); auto. solve_addr'. }\n    (* load from a_data *)\n    wp_instr.\n    iMod (inv_acc with \"HIcap\") as \"[>Hcap Hclose]\"; auto.\n    iInstr \"Hcode\".\n    iMod (\"Hclose\" with \"Hcap\") as \"_\". iModIntro. wp_pure.\n    (* load from a_data+1 *)\n    wp_instr.\n    iMod (inv_acc with \"HIv\") as \"[>Hv Hclose]\"; auto.\n    iDestruct \"Hv\" as (n) \"(Hn & %Hn)\".\n    iInstr \"Hcode\".\n    { split. solve_pure. solve_addr'. }\n    iMod (\"Hclose\" with \"[Hn]\") as \"_\". { iNext. iExists _. by iFrame. }\n    iModIntro. wp_pure.\n    (* add *)\n    iInstr \"Hcode\".\n    (* store to a_data+1 *)\n    wp_instr.\n    iMod (inv_acc with \"HIv\") as \"[>Hv Hclose]\"; auto.\n    iDestruct \"Hv\" as (n') \"(Hn' & %Hn')\".\n    iInstr \"Hcode\". solve_addr'.\n    iMod (\"Hclose\" with \"[Hn']\") as \"_\".\n    { iNext. iExists _. iFrame. iPureIntro. lia. }\n    iModIntro. wp_pure.\n    (* cont *)\n    iGo \"Hcode\".\n\n    (* close the invariant with the code *)\n    iMod (\"Hclose_code\" with \"[$Hcode $Hna]\") as \"Hna\".\n    iApply \"Hφ\". iFrame.\n  Qed.\n\n  Lemma counter_full_run_spec (a_init: Addr) b_adv e_adv w1 w2 wdat rmap adv :\n    let a_code := (a_init ^+ code_off)%a in\n    let a_data := (a_code ^+ data_off)%a in\n    let a_end := (a_code ^+ (data_off + end_off))%a in\n    ContiguousRegion a_init (code_off + data_off + end_off) →\n    dom rmap = all_registers_s ∖ {[ PC; r_t0; r_t1; r_t2 ]} →\n    Forall (λ w, is_z w = true) adv →\n    (b_adv + length adv)%a = Some e_adv →\n\n  ⊢ (   inv with_adv.invN (∃ n : Z, (a_data ^+ 1)%a ↦ₐ WInt n ∗ ⌜0 ≤ n⌝)\n      ∗ PC ↦ᵣ WCap RWX a_init a_end a_init\n      ∗ r_t0 ↦ᵣ WCap RWX b_adv e_adv b_adv\n      ∗ r_t1 ↦ᵣ w1\n      ∗ r_t2 ↦ᵣ w2\n      ∗ ([∗ map] r↦w ∈ rmap, r ↦ᵣ w ∗ ⌜is_z w = true⌝)\n      ∗ codefrag a_init (counter_init a_init)\n      ∗ codefrag a_code (counter_code a_code)\n      ∗ a_data ↦ₐ wdat\n      ∗ ([∗ map] a↦w ∈ mkregion b_adv e_adv adv, a ↦ₐ w)\n      ∗ na_own logrel_nais ⊤\n      -∗ WP Seq (Instr Executable) {{ λ _, True }})%I.\n  Proof.\n    iIntros (? ? ? ? Hrdom ? ?) \"(#HI & HPC & Hr0 & Hr1 & Hr2 & Hrmap & Hinit & Hcode & Hdat & Hadv & Hna)\".\n\n    (* The capability to the adversary is safe and we can also jmp to it *)\n    iDestruct (mkregion_sepM_to_sepL2 with \"Hadv\") as \"Hadv\". done.\n    iDestruct (region_integers_alloc' _ _ _ b_adv _ RWX with \"Hadv\") as \">#Hadv\". done.\n    iDestruct (jmp_to_unknown with \"Hadv\") as \"#Hcont\".\n\n    iApply (counter_init_spec a_init with \"[-]\"). solve_addr'. iFrame.\n    simpl. rewrite (_: a_init ^+ (_ + _ + _) = a_end)%a. 2: solve_addr'. iFrame.\n    rewrite (_: a_init ^+ (_ + _) = a_data)%a. 2: solve_addr'. iFrame.\n    iNext. iIntros \"(HPC & Hr0 & Hr1 & Hr2 & Hdat & _)\".\n\n    (* Allocate an invariant for the points-to at a_data containing the capability to a_data+1 *)\n    iMod (inv_alloc (N.@\"cap\") _ (a_data ↦ₐ WCap RWX a_init a_end (a_data ^+ 1)%a)\n            with \"Hdat\") as \"#HIcap\".\n\n    (* Allocate a non-atomic invariant for the code of the code routine *)\n    iMod (na_inv_alloc logrel_nais _ (N.@\"code\") (codefrag a_code (counter_code a_code))\n           with \"Hcode\") as \"#HIcode\".\n\n    (* Show that the E-capability to the code: routine is safe *)\n    iAssert (interp (WCap E a_code a_end a_code)) as \"#Hcode_safe\".\n    { rewrite /interp /= (fixpoint_interp1_eq (WCap E _ _ _)) /=. iIntros (rr).\n      iIntros \"!> !> ([%Hrfull #Hrsafe] & Hrr & Hna)\". rewrite /interp_conf.\n\n      (* unpack the registers *)\n      destruct (Hrfull r_t0) as [w0' Hr0'].\n      destruct (Hrfull r_t1) as [w1' Hr1'].\n      destruct (Hrfull r_t2) as [w2' Hr2'].\n      unfold registers_mapsto.\n      rewrite -insert_delete_insert.\n      iDestruct (big_sepM_insert with \"Hrr\") as \"[HPC Hrr]\".\n        by rewrite lookup_delete.\n      iDestruct (big_sepM_delete _ _ r_t0 with \"Hrr\") as \"[Hr0 Hrr]\".\n        by rewrite lookup_delete_ne //.\n      iDestruct (big_sepM_delete _ _ r_t1 with \"Hrr\") as \"[Hr1 Hrr]\".\n        by rewrite !lookup_delete_ne //.\n      iDestruct (big_sepM_delete _ _ r_t2 with \"Hrr\") as \"[Hr2 Hrr]\".\n        by rewrite !lookup_delete_ne //.\n\n      (* the continuation is safe, and we can jump to it *)\n      iAssert (interp w0') as \"Hv0\". by iApply \"Hrsafe\"; eauto; done.\n      iDestruct (jmp_to_unknown with \"[$Hv0]\") as \"#Hcont_prog\".\n\n      (* apply the spec *)\n      iApply (counter_code_spec a_init with \"[-]\"). solve_addr'.\n      rewrite (_: (a_init ^+ _) ^+ _ = a_data)%a. 2: solve_addr'.\n      rewrite (_: (a_init ^+ _) ^+ (_ + _) = a_end)%a. 2: solve_addr'.\n      iFrame. iFrame \"HIcap HIcode HI\".\n      iIntros \"!>\" (n) \"(HPC & Hr0 & Hr1 & Hr2 & Hcode)\".\n\n      (* put the registers back together *)\n      iDestruct (big_sepM_sep _ (λ k v, interp v)%I with \"[Hrr]\") as \"Hrr\".\n      { iSplitL. by iApply \"Hrr\". iApply big_sepM_intro. iModIntro.\n        iIntros (r' ? HH). repeat eapply lookup_delete_Some in HH as [? HH].\n        iApply (\"Hrsafe\" $! r'); auto. }\n      iDestruct (big_sepM_insert with \"[$Hrr $Hr2]\") as \"Hrr\". by rewrite lookup_delete.\n        by iApply interp_int. rewrite insert_delete_insert.\n      iDestruct (big_sepM_insert with \"[$Hrr $Hr1]\") as \"Hrr\".\n        by rewrite lookup_insert_ne // lookup_delete.\n        by iApply interp_int. rewrite insert_commute // insert_delete_insert.\n      iDestruct (big_sepM_insert with \"[$Hrr $Hr0]\") as \"Hrr\".\n        by rewrite !lookup_insert_ne // lookup_delete.\n        by iApply \"Hv0\". do 2 rewrite (insert_commute _ r_t0) //;[]. rewrite insert_delete_insert.\n\n      (* jmp to continuation *)\n      iApply \"Hcont_prog\". 2: iFrame. iPureIntro.\n      rewrite !dom_insert_L dom_delete_L regmap_full_dom //. set_solver+. }\n\n    (* put the registers back together *)\n    iDestruct (big_sepM_mono _ (λ k v, k ↦ᵣ v ∗ interp v)%I with \"Hrmap\") as \"Hrmap\".\n    { intros ? w ?. cbn. iIntros \"[? %Hw]\". iFrame. destruct w; try inversion Hw.\n      iApply interp_int. }\n    iDestruct (big_sepM_insert _ _ r_t2 with \"[$Hrmap $Hr2]\") as \"Hrmap\".\n      by rewrite -not_elem_of_dom Hrdom; set_solver+.\n      by iApply interp_int.\n    iDestruct (big_sepM_insert _ _ r_t1 with \"[$Hrmap $Hr1]\") as \"Hrmap\".\n      by rewrite lookup_insert_ne // -not_elem_of_dom Hrdom; set_solver+.\n      by iApply \"Hcode_safe\".\n    iDestruct (big_sepM_insert _ _ r_t0 with \"[$Hrmap $Hr0]\") as \"Hrmap\".\n      by rewrite !lookup_insert_ne // -not_elem_of_dom Hrdom; set_solver+.\n      by iApply \"Hadv\".\n\n    iApply (wp_wand with \"[-]\").\n    { iApply \"Hcont\". 2: iFrame. iPureIntro.\n      rewrite !dom_insert_L Hrdom !singleton_union_difference_L !all_registers_union_l. set_solver+. }\n    eauto.\n  Qed.\n\nEnd counter.\n\nLocal Ltac solve_addr' :=\n  repeat match goal with x := _ |- _ => subst x end;\n  unfold code_off, data_off, end_off in *; solve_addr.\n\nProgram Definition counter_inv (a_init: Addr) : memory_inv :=\n  MkMemoryInv\n    (λ m, ∃ n, m !! (a_init ^+ (code_off + data_off + 1))%a = Some (WInt n) ∧ 0 ≤ n)\n    {[ (a_init ^+ (code_off + data_off + 1))%a ]}\n    _.\nNext Obligation.\n  intros a_init m m' H. cbn in *.\n  specialize (H (a_init ^+ (code_off + data_off + 1))%a). feed specialize H. by set_solver.\n  destruct H as [w [? ?] ]. by simplify_map_eq.\nQed.\n\nDefinition counterN : namespace := nroot .@ \"counter\".\n\nLemma adequacy `{MachineParameters} (P Adv: prog) (m m': Mem) (reg reg': Reg) es:\n  prog_instrs P =\n    counter_init (prog_start P) ++\n    counter_code (prog_start P ^+ code_off)%a ++\n    counter_data →\n  with_adv.is_initial_memory P Adv m →\n  with_adv.is_initial_registers P Adv reg r_t0 →\n  Forall (λ w, is_z w = true) (prog_instrs Adv) →\n\n  rtc erased_step ([Seq (Instr Executable)], (reg, m)) (es, (reg', m')) →\n  ∃ n, m' !! (prog_start P ^+ (code_off + data_off + 1))%a = Some (WInt n) ∧ 0 ≤ n.\nProof.\n  intros HP Hm Hr HAdv Hstep.\n  generalize (prog_size P). rewrite HP /=. intros.\n\n  (* Prove the side-conditions over the memory invariant *)\n  eapply (with_adv.template_adequacy P Adv (counter_inv (prog_start P)) r_t0 m m' reg reg' es); auto.\n  { cbn. unfold with_adv.is_initial_memory in Hm. destruct Hm as (Hm & _ & _).\n    exists 0; split; [| done]. eapply lookup_weaken; [| apply Hm]. rewrite /prog_region mkregion_lookup.\n    { exists (Z.to_nat (code_off + data_off + 1)). split. done. rewrite HP; done. }\n    { apply prog_size. } }\n  { cbn. apply elem_of_subseteq_singleton, elem_of_list_to_set, elem_of_finz_seq_between. solve_addr'. }\n\n  intros * Hss * Hrdom. iIntros \"(#HI & Hna & HPC & Hr0 & Hrmap & Hadv & Hprog)\".\n  set (a_init := prog_start P) in *.\n  set (a_code := (a_init ^+ code_off)%a) in *.\n  set (a_data := (a_code ^+ data_off)%a) in *.\n\n  (* Extract the code & data regions from the program resources *)\n  iAssert (codefrag a_init (counter_init a_init) ∗\n           codefrag a_code (counter_code a_code) ∗\n           (∃ w, a_data ↦ₐ w))%I\n    with \"[Hprog]\" as \"(Hinit & Hcode & Hdat)\".\n  { rewrite /codefrag /region_mapsto.\n    set M := filter _ _.\n    set Minit := mkregion a_init a_code (counter_init a_init).\n    set Mcode := mkregion a_code a_data (counter_code a_code).\n    set Mdat := mkregion a_data (a_data ^+ 1)%a [WInt 7777].\n\n    assert (Mcode ##ₘ Mdat).\n    { apply map_disjoint_spec.\n      intros ? ? ? [? [? ?%lookup_lt_Some] ]%mkregion_lookup [? [? ?%lookup_lt_Some] ]%mkregion_lookup.\n      all: solve_addr'. }\n\n    assert (Minit ##ₘ (Mcode ∪ Mdat)).\n    { apply map_disjoint_spec.\n      intros ? ? ? [? [? ?%lookup_lt_Some] ]%mkregion_lookup.\n      2: solve_addr'. intros [HH|HH]%lookup_union_Some; auto.\n      all: apply mkregion_lookup in HH as [? [? ?%lookup_lt_Some] ]; solve_addr'. }\n\n    assert (Minit ∪ (Mcode ∪ Mdat) ⊆ M) as HM.\n    { apply map_subseteq_spec. intros a w. intros [Ha| [Ha|Ha]%lookup_union_Some]%lookup_union_Some.\n      4,5: assumption.\n      all: apply mkregion_lookup in Ha as [i [? HH] ]; [| solve_addr'].\n      all: apply map_filter_lookup_Some_2;\n        [| cbn; apply not_elem_of_singleton; apply lookup_lt_Some in HH; solve_addr'].\n      all: subst; rewrite mkregion_lookup; [| rewrite HP; solve_addr'].\n      { eexists. split; eauto. rewrite HP. by apply lookup_app_l_Some. }\n      { exists (Z.to_nat (i+code_off)). split. solve_addr'. rewrite HP.\n        apply lookup_app_Some. right. split. solve_addr'. apply lookup_app_l_Some.\n        rewrite (_: _ - _ = i)%nat //. solve_addr'. }\n      { exists (Z.to_nat (code_off + data_off)). destruct i; [| by inversion HH]. split. solve_addr'.\n        rewrite HP. apply lookup_app_Some. right. split. solve_addr'.\n        apply lookup_app_Some. right. split. solve_addr'. done. } }\n\n    iDestruct (big_sepM_subseteq with \"Hprog\") as \"Hprog\". apply HM.\n    iDestruct (big_sepM_union with \"Hprog\") as \"[Hinit Hprog]\". assumption.\n    iDestruct (big_sepM_union with \"Hprog\") as \"[Hcode Hdat]\". assumption.\n    iDestruct (mkregion_sepM_to_sepL2 with \"Hinit\") as \"Hinit\". solve_addr'.\n    iDestruct (mkregion_sepM_to_sepL2 with \"Hcode\") as \"Hcode\". solve_addr'.\n    iDestruct (mkregion_sepM_to_sepL2 with \"Hdat\") as \"Hdat\". solve_addr'.\n    iFrame. iExists _. rewrite finz_seq_between_cons. cbn. by iDestruct \"Hdat\" as \"[? ?]\".\n    solve_addr'. }\n  iDestruct \"Hdat\" as (wdat) \"Hdat\".\n\n  assert (is_Some (rmap !! r_t1)) as [w1 Hr1].\n  { rewrite -elem_of_dom Hrdom. set_solver+. }\n  assert (is_Some (rmap !! r_t2)) as [w2 Hr2].\n  { rewrite -elem_of_dom Hrdom. set_solver+. }\n  iDestruct (big_sepM_delete _ _ r_t1 with \"Hrmap\") as \"[[Hr1 _] Hrmap]\"; eauto.\n  iDestruct (big_sepM_delete _ _ r_t2 with \"Hrmap\") as \"[[Hr2 _] Hrmap]\".\n    by rewrite lookup_delete_ne //.\n\n  iApply (counter_full_run_spec with \"[$Hadv $Hr0 $Hr1 $Hr2 $Hinit $Hrmap $Hna $Hdat $Hcode HPC]\"); auto.\n  solve_addr'. by rewrite !dom_delete_L Hrdom; set_solver+. by apply prog_size.\n  rewrite (_: _ ^+ (_ + _) = prog_end P)%a. 2: solve_addr'. iFrame.\n\n  (* Show the invariant for the counter value using the invariant from the adequacy theorem *)\n  iApply (inv_alter with \"HI\").\n  iIntros \"!> !> H\". rewrite /minv_sep. iDestruct \"H\" as (mι) \"(Hm & %Hmιdom & %Hι)\".\n  cbn in Hι. destruct Hι as (n & Hι & Hn).\n  rewrite (_: a_init ^+ _ = (a_data ^+ 1))%a in Hι. 2: solve_addr'.\n  iDestruct (big_sepM_delete _ _ (a_data ^+ 1)%a (WInt n) with \"Hm\") as \"[Hn Hm]\". done.\n  iSplitL \"Hn\". by eauto. iIntros \"Hn'\". iDestruct \"Hn'\" as (n') \"(Hn' & %)\".\n  iExists (<[ (a_data ^+ 1)%a := WInt n' ]> mι). iSplitL \"Hm Hn'\".\n  { iDestruct (big_sepM_insert with \"[$Hm $Hn']\") as \"Hm\". by apply lookup_delete.\n    rewrite insert_delete_insert //. }\n  iPureIntro. split. rewrite dom_insert_L Hmιdom /Hmιdom /=. 2: exists n'.\n  all: rewrite (_: a_init ^+ _ = (a_data ^+ 1))%a; [| solve_addr']. set_solver+.\n  rewrite lookup_insert //.\nQed.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/examples/minimal_counter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.24703296188687882}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nSet Asymmetric Patterns.\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import Transitions.\nRequire Import LList.\n\nSection Trace_DEF.\n\nVariable L : LTS.\n\nLet state := LTS_State L.\nDefinition trace := LList state.\n\nVariable init : state.\n\nCoInductive exec : state -> Type :=\n  | exec_init : exec init\n  | exec_trans :\n      forall (s s' : state) (a : LTS_Act L),\n      exec s -> LTS_Trans s a s' -> exec s'. \n\nCoFixpoint LList_of_exec  : forall s : state, exec s -> trace :=\n  fun s e =>\n  match e with\n  | exec_init => LNil state\n  | exec_trans s s' a e' _ => LCons s' (LList_of_exec e')\n  end.\n\nCoInductive is_trace : trace -> state -> Prop :=\n  | is_trace_LNil : is_trace (LNil state) init\n  | is_trace_LCons :\n      forall (l : trace) (s s' : state) (a : LTS_Act L),\n      is_trace l s -> LTS_Trans s a s' -> is_trace (LCons s' l) s'.\n\n\nEnd Trace_DEF.", "meta": {"author": "coq-contribs", "repo": "pautomata", "sha": "6caf4d6b861004524b531b6e0ed7db8ee5dfc975", "save_path": "github-repos/coq/coq-contribs-pautomata", "path": "github-repos/coq/coq-contribs-pautomata/pautomata-6caf4d6b861004524b531b6e0ed7db8ee5dfc975/Trace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2469600724097323}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Import type_sys_useful.\nRequire Import dest_close.\n\n\nLemma eq_term_equals_per_tunion_eq_if {p} :\n  forall (eqa1 eqa2 : per(p)) (eqb1 : per-fam(eqa1)) (eqb2 : per-fam(eqa2)),\n    eqa1 <=2=> eqa2\n    -> (forall (a1 a2 : CTerm) (e1 : eqa1 a1 a2) (e2 : eqa2 a1 a2),\n          (eqb1 a1 a2 e1) <=2=> (eqb2 a1 a2 e2))\n    -> (per_tunion_eq eqa1 eqb1) <=2=> (per_tunion_eq eqa2 eqb2).\nProof.\n  introv eqt1 eqt2.\n  introv; split; intro k; induction k.\n\n  - apply @tunion_eq_cl with (t := t); sp.\n\n  - dup e as e'; apply eqt1 in e'.\n    apply @tunion_eq_eq with (a1 := a1) (a2 := a2) (e := e'); sp; spcast.\n    apply (eqt2 a1 a2 e e'); auto.\n\n  - apply @tunion_eq_cl with (t := t); sp.\n\n  - dup e as e'; apply eqt1 in e'.\n    apply @tunion_eq_eq with (a1 := a1) (a2 := a2) (e := e'); sp; spcast.\n    apply (eqt2 a1 a2 e' e); auto.\nQed.\n\nLemma per_tunion_eq_sym {p} :\n  forall (eqa : per(p)) eqb t1 t2,\n    (forall (a1 a2 : CTerm) (e : eqa a1 a2),\n       term_equality_symmetric (eqb a1 a2 e))\n    -> per_tunion_eq eqa eqb t1 t2\n    -> per_tunion_eq eqa eqb t2 t1.\nProof.\n  introv tesb per.\n  induction per.\n  apply @tunion_eq_cl with (t := t); sp.\n  apply @tunion_eq_eq with (a1 := a1) (a2 := a2) (e := e); sp.\n  apply tesb; auto.\nQed.\n\nLemma per_tunion_eq_trans {p} :\n  forall (eqa : per(p)) eqb t1 t2 t3,\n    per_tunion_eq eqa eqb t1 t2\n    -> per_tunion_eq eqa eqb t2 t3\n    -> per_tunion_eq eqa eqb t1 t3.\nProof.\n  introv per1 per2.\n  apply tunion_eq_cl with (t := t2); sp.\nQed.\n\nLemma per_tunion_eq_cequiv {p} :\n  forall lib (eqa : per(p)) eqb t t',\n    (forall (a1 a2 : CTerm) (e : eqa a1 a2),\n       term_equality_symmetric (eqb a1 a2 e))\n    -> (forall (a1 a2 : CTerm) (e : eqa a1 a2),\n       term_equality_transitive (eqb a1 a2 e))\n    -> (forall (a1 a2 : CTerm) (e : eqa a1 a2),\n          term_equality_respecting lib (eqb a1 a2 e))\n    -> t ~=~(lib) t'\n    -> per_tunion_eq eqa eqb t t\n    -> per_tunion_eq eqa eqb t t'.\nProof.\n  introv tes tet ter ceq per.\n  revert_dependents t'.\n  induction per; introv ceq.\n  apply IHper2; auto.\n  apply @tunion_eq_eq with (a1 := a1) (a2 := a2) (e := e); sp.\n  apply (ter a1 a2 e t2 t'); auto.\n  apply tet with (t2 := t1); auto.\n  apply tes; auto.\nQed.\n\nLemma close_type_system_tunion {p} :\n  forall lib (ts : cts(p))\n         T T'\n         (eq : per)\n         A A' v v' B B' eqa eqb,\n    type_system lib ts\n    -> defines_only_universes lib ts\n    -> computes_to_valc lib T (mkc_tunion A v B)\n    -> computes_to_valc lib T' (mkc_tunion A' v' B')\n    -> close lib ts A A' eqa\n    -> (forall (a a' : CTerm) (e : eqa a a'),\n          close lib ts (substc a v B) (substc a' v' B') (eqb a a' e))\n    -> (forall (a a' : CTerm) (e : eqa a a'),\n          type_system lib ts ->\n          defines_only_universes lib ts ->\n          type_sys_props lib (close lib ts) (substc a v B) (substc a' v' B')\n                         (eqb a a' e))\n    -> (forall t t' : CTerm,\n          eq t t' <=> per_tunion_eq eqa eqb t t')\n    -> per_tunion lib (close lib ts) T T' eq\n    -> type_sys_props lib (close lib ts) A A' eqa\n    -> type_sys_props lib (close lib ts) T T' eq.\nProof.\n  introv X X0 c1 c2 X1 clb recb eqiff per IHX1.\n\n  rw @type_sys_props_iff_type_sys_props3.\n  prove_type_sys_props3 SCase; intros.\n\n  + SCase \"uniquely_valued\".\n    dclose_lr;\n    try (complete (apply defines_only_universes_tunion_L with (T2 := T3) (eq2 := eq') in per; sp));\n    try (complete (apply defines_only_universes_tunion_R with (T2 := T3) (eq2 := eq') in per; sp)).\n\n    SSCase \"CL_tunion\".\n    allunfold @per_tunion; exrepd.\n    generalize (eq_term_equals_type_family lib T T3 eqa0 eqa eqb0 eqb (close lib ts) A v B A' v' B' mkc_tunion); intro i.\n    repeat (autodimp i hyp; try (complete (introv ee; eqconstr ee; sp))); repnd.\n\n    generalize (eq_term_equals_type_family lib T T' eqa1 eqa eqb1 eqb (close lib ts) A v B A' v' B' mkc_tunion); intro j.\n    repeat (autodimp j hyp; try (complete (introv ee; eqconstr ee; sp))); repnd.\n\n    apply eq_term_equals_trans with (eq2 := per_tunion_eq eqa1 eqb1); auto.\n    apply eq_term_equals_trans with (eq2 := per_tunion_eq eqa0 eqb0); auto;\n    try (complete (apply eq_term_equals_sym; auto)).\n\n    apply eq_term_equals_per_tunion_eq_if; auto.\n\n    apply eq_term_equals_trans with (eq2 := eqa); auto.\n    apply eq_term_equals_sym; auto.\n\n    introv.\n    dup e2 as e3.\n    rw <- i0 in e3.\n    apply eq_term_equals_trans with (eq2 := eqb a1 a2 e3); auto.\n    apply eq_term_equals_sym; auto.\n\n  + SCase \"type_symmetric\"; repdors; subst; dclose_lr;\n    apply CL_tunion;\n    clear per;\n    allunfold @per_tunion; exrepd;\n    unfold per_tunion;\n    exists eqa0 eqb0; sp;\n    allrw <-; sp.\n    apply eq_term_equals_trans with (eq2 := eq); auto.\n    apply eq_term_equals_sym; auto.\n\n  + SCase \"type_value_respecting\"; repdors; subst;\n    apply CL_tunion; unfold per_tunion; exists eqa eqb; sp.\n\n    duplicate c1 as ct.\n    apply @cequivc_mkc_tunion with (T' := T3) in ct; sp.\n\n    apply @type_family_cequivc\n          with\n          (A1 := A)\n          (v1 := v)\n          (B1 := B)\n          (A2 := A'0)\n          (v2 := v'0)\n          (B2 := B'0)\n          (A := A')\n          (v := v')\n          (B := B'); sp.\n\n    duplicate c2 as ct.\n    apply @cequivc_mkc_tunion with (T' := T3) in ct; sp.\n\n    apply @type_family_cequivc2\n          with\n          (A1 := A')\n          (v1 := v')\n          (B1 := B')\n          (A2 := A'0)\n          (v2 := v'0)\n          (B2 := B'0)\n          (A := A)\n          (v := v)\n          (B := B); sp.\n\n  + SCase \"term_symmetric\".\n    unfold term_equality_symmetric; introv eqts.\n    onedtsp e pp p0 p1 c t t0 t3 tygs tygt dum.\n    apply eqiff; apply eqiff in eqts; exrepnd.\n    apply per_tunion_eq_sym; auto.\n    introv.\n    pose proof (recb a1 a2 e0) as h; repeat (autodimp h hyp).\n    onedtsp x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11; auto.\n\n  + SCase \"term_transitive\".\n    unfold term_equality_transitive; sp.\n    apply eqiff; sp.\n    assert (eq t1 t2) as eq12 by auto.\n    assert (eq t2 t3) as eq23 by auto.\n    rw eqiff in eq12; rw eqiff in eq23; exrepnd.\n    apply (per_tunion_eq_trans eqa eqb t1 t2 t3); auto.\n\n  + SCase \"term_value_respecting\".\n    unfold term_equality_respecting; sp.\n    apply eqiff; sp.\n    assert (eq t t) as eqtt by auto.\n    apply eqiff in eqtt; exrepnd.\n    apply (per_tunion_eq_cequiv lib eqa eqb t t'); auto;\n    introv;\n    pose proof (recb a1 a2 e) as h; repeat (autodimp h hyp);\n    onedtsp x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11; auto.\n\n  + SCase \"type_gsymmetric\"; repdors; subst; split; sp; dclose_lr;\n    apply CL_tunion;\n    clear per;\n    allunfold @per_tunion; exrepd.\n\n    (* 1 *)\n    generalize (eq_term_equals_type_family\n                  lib T T3 eqa0 eqa eqb0 eqb (close lib ts)\n                  A v B A' v' B' mkc_tunion); intro i.\n    repeat (autodimp i hyp; try (complete (introv ee; eqconstr ee; sp))).\n    repnd.\n\n    exists eqa eqb; sp.\n\n    apply eq_term_equals_trans with (eq2 := per_tunion_eq eqa0 eqb0); auto.\n    apply eq_term_equals_per_tunion_eq_if; auto.\n    apply eq_term_equals_sym; auto.\n\n    (* 2 *)\n    generalize (eq_term_equals_type_family2\n                  lib T3 T eqa0 eqa eqb0 eqb (close lib ts)\n                  A v B A' v' B' mkc_tunion); intro i;\n    repeat (autodimp i hyp; try (complete (introv ee; eqconstr ee; sp)));\n    repnd.\n\n    exists eqa eqb; sp.\n\n    apply eq_term_equals_trans with (eq2 := per_tunion_eq eqa0 eqb0); auto.\n    apply eq_term_equals_per_tunion_eq_if; auto.\n    apply eq_term_equals_sym; auto.\n\n  + SCase \"type_gtransitive\"; sp.\n\n  + SCase \"type_mtransitive\".\n    repdors; subst; dclose_lr;\n    try (move_term_to_top (per_tunion lib (close lib ts) T T4 eq2));\n    try (move_term_to_top (per_tunion lib (close lib ts) T' T4 eq2)).\n\n    (* 1 *)\n    clear per.\n    allunfold @per_tunion; exrepd.\n\n    generalize (eq_term_equals_type_family2\n                  lib T3 T eqa1 eqa eqb1 eqb (close lib ts)\n                  A v B A' v' B' mkc_tunion); intro i.\n    repeat (autodimp i hyp; try (complete (introv ee; eqconstr ee; sp))).\n    repnd.\n\n    generalize (type_family_trans2\n                  lib mkc_tunion (close lib ts) T3 T T4 eqa eqb eqa0 eqb0 A v B A' v' B'); intro j.\n    repeat (autodimp j hyp; try (complete (introv ee; eqconstr ee; sp))).\n    repnd.\n\n    dands; apply CL_tunion; unfold per_tunion; exists eqa eqb; sp; allrw.\n\n    eapply eq_term_equals_trans; eauto.\n    apply eq_term_equals_per_tunion_eq_if; auto.\n    apply eq_term_equals_sym; auto.\n\n    eapply eq_term_equals_trans; eauto.\n    apply eq_term_equals_per_tunion_eq_if; auto.\n    apply eq_term_equals_sym; auto.\n    introv.\n    apply eq_term_equals_sym; auto.\n\n    (* 2 *)\n    clear per.\n    allunfold @per_tunion; exrepd.\n\n    generalize (eq_term_equals_type_family2\n                  lib T3 T' eqa1 eqa eqb1 eqb (close lib ts)\n                  A' v' B' A v B mkc_tunion); intro i.\n    repeat (autodimp i hyp;\n            try (complete (introv ee; eqconstr ee; sp));\n            try (complete (apply type_sys_props_sym; sp))).\n    onedtsp uv tys tyt tyst tyvr tes tet tevr tygs tygt dum.\n    intros.\n    apply type_sys_props_sym.\n    apply type_sys_props_eqb_comm; sp.\n    apply tet with (t2 := a'); sp.\n    apply tet with (t2 := a); sp.\n    repnd.\n\n    generalize (type_family_trans2\n                  lib mkc_tunion (close lib ts) T3 T' T4 eqa eqb eqa0 eqb0 A' v' B' A v B); intro j.\n    repeat (autodimp j hyp;\n            try (complete (introv ee; eqconstr ee; sp));\n            try (complete (apply type_sys_props_sym; sp))).\n    onedtsp uv tys tyt tyst tyvr tes tet tevr tygs tygt dum.\n    intros.\n    apply type_sys_props_sym.\n    apply type_sys_props_eqb_comm; sp.\n    apply tet with (t2 := a'); sp.\n    apply tet with (t2 := a); sp.\n    repnd.\n\n    dands; apply CL_tunion; unfold per_tunion; exists eqa eqb; sp; allrw.\n\n    eapply eq_term_equals_trans; eauto.\n    apply eq_term_equals_per_tunion_eq_if; auto.\n    apply eq_term_equals_sym; auto.\n\n    eapply eq_term_equals_trans; eauto.\n    apply eq_term_equals_per_tunion_eq_if; auto.\n    apply eq_term_equals_sym; auto.\n    introv.\n    apply eq_term_equals_sym; auto.\nQed.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/close/close_type_sys_per_tunion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24696007240973225}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config Universes.\nFrom MetaCoq.Template Require Import Loader.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICTyping PCUICSN PCUICLiftSubst.\nFrom MetaCoq.SafeChecker Require Import PCUICErrors PCUICWfEnv PCUICWfEnvImpl PCUICTypeChecker PCUICSafeChecker.\nFrom Equations Require Import Equations.\n\nImport MCMonadNotation.\nGlobal Existing Instance default_checker_flags.\nGlobal Existing Instance default_normalizing.\n\n(* ********************************************************* *)\n(* In this file we define a small plugin which proves        *)\n(* the identity theorem for any sort using the safe checker. *)\n(* ********************************************************* *)\n\nDefinition bAnon := {| binder_name := nAnon; binder_relevance := Relevant |}.\nDefinition bNamed s := {| binder_name := nNamed s; binder_relevance := Relevant |}.\n\nDefinition tImpl X Y := tProd bAnon X (lift0 1 Y).\n\nDefinition univ := Level.Level \"s\".\n\n(* TODO move to SafeChecker *)\n\nDefinition gctx : global_env_ext :=\n  ({| universes := (LS.union (LevelSet.singleton Level.lzero) (LevelSet.singleton univ), ConstraintSet.empty);\n      declarations := []; retroknowledge := Retroknowledge.empty |}, Monomorphic_ctx).\n\n(** We use the environment checker to produce the proof that gctx, which is a singleton with only\n    universe \"s\" declared is well-formed. *)\n\nDefinition kername_of_string (s : string) : kername :=\n  (MPfile [], s).\n\nGlobal Program Instance fake_guard_impl : abstract_guard_impl :=\n{| guard_impl := fake_guard_impl |}.\nNext Obligation. Admitted.\n\nGlobal Existing Instance normalization. (* to convert from Normalization to NormalizationIn *)\nGlobal Instance assume_normalization : Normalization.\nAdmitted.\n\nDefinition make_wf_env_ext (Σ : global_env_ext) : EnvCheck wf_env_ext wf_env_ext :=\n  '(exist Σ' pf) <- check_wf_ext optimized_abstract_env_impl Σ ;;\n  ret Σ'.\n\nDefinition gctx_wf_env : wf_env_ext.\nProof.\n  let wf_proof := eval hnf in (make_wf_env_ext gctx) in\n  match wf_proof with\n  | CorrectDecl _ ?x => exact x\n  | _ => fail \"Couldn't prove the global environment is well-formed\"\n  end.\nDefined.\n\n\n\n(** There is always a proof of `forall x : Sort s, x -> x` *)\n\nDefinition inh (Σ : wf_env_ext) Γ T := (∑ t, forall Σ0 : global_env_ext, abstract_env_ext_rel Σ Σ0 -> ∥ typing Σ0 Γ t T ∥).\n\nDefinition check_inh (Σ : wf_env_ext) Γ\n  (wfΓ : forall Σ0 : global_env_ext, abstract_env_ext_rel Σ Σ0 -> ∥ wf_local Σ0 Γ ∥) t {T} : typing_result (inh Σ Γ T) :=\n  prf <- check_type_wf_env_fast optimized_abstract_env_impl Σ Γ wfΓ t (T := T) ;;\n  ret (t; prf).\n\nLtac fill_inh t :=\n  lazymatch goal with\n  [ wfΓ : forall _ _ , ∥ wf_local _ ?Γ ∥ |- inh ?Σ ?Γ ?T ] =>\n    let t := uconstr:(check_inh Σ Γ wfΓ t (T:=T)) in\n    let proof := eval cbn in t in\n    match proof with\n    | Checked ?d => exact_no_check d\n    | TypeError ?e =>\n        let str := eval cbn in (string_of_type_error Σ e) in\n        fail \"Failed to inhabit \" T \" : \" str\n    | _ => fail \"Anomaly: unexpected return value: \" proof\n    end\n  | [ |- inh _ ?Γ _ ] => fail \"Missing local wellformedness assumption for\" Γ\n  end.\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/examples/metacoq_tour_prelude.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24696007240973225}}
{"text": "Require Import Lists.List Lists.ListSet Vector Arith.PeanoNat AbstractRelation Tribool Common Util.\n\nModule Type SQL.\n  Import Db.\n\n  (* I will probably need to declare a canonical structure/type class for Names *)\n\n  Inductive pretm : Type :=\n  | tmconst : BaseConst -> pretm\n  | tmnull  : pretm\n  | tmvar   : FullVar -> pretm    (* refers to FROM tables *)\n  .\n\n  Lemma pretm_dec : forall (x y: pretm), { x = y } + { x <> y }.\n  Proof.\n    decide equality. apply Db.BaseConst_dec. decide equality. apply Db.Name_dec. apply Nat.eq_dec.\n  Qed.\n\n  Inductive prequery : Type :=\n  | select  : bool -> list (pretm * Name) -> list (list (pretb * Scm)) -> precond -> prequery\n  | selstar : bool -> list (list (pretb * Scm)) -> precond -> prequery\n  | qunion  : bool -> prequery -> prequery -> prequery\n  | qinters : bool -> prequery -> prequery -> prequery\n  | qexcept : bool -> prequery -> prequery -> prequery\n\n  with precond : Type :=\n  | cndtrue   : precond\n  | cndfalse  : precond\n  | cndnull   : bool -> pretm -> precond\n  | cndistrue : precond -> precond\n  | cndpred   : forall n, (forall l : list BaseConst, length l = n -> bool) -> list pretm -> precond\n  | cndmemb   : bool -> list pretm -> prequery -> precond\n  | cndex     : prequery -> precond\n  | cndand    : precond -> precond -> precond\n  | cndor     : precond -> precond -> precond\n  | cndnot    : precond -> precond\n\n  with pretb: Type :=\n  | tbbase  : Name -> pretb\n  | tbquery : prequery -> pretb.\n\n  Notation \"'NULL'\" := (tmnull) (at level 45).\n\n  Notation \"'SELECT' btm 'FROM' btb 'WHERE' c\" := (select false btm btb c) (at level 45).\n  Notation \"'SELECT' 'DISTINCT' btm 'FROM' btb 'WHERE' c\" := (select true btm btb c) (at level 45).\n  Notation \"'SELECT' '*' 'FROM' btb 'WHERE' c\" := (selstar false btb c) (at level 45).\n  Notation \"'SELECT' 'DISTINCT' '*' 'FROM' btb 'WHERE' c\" := (selstar true btb c) (at level 45).\n  Notation \"Q1 'UNION' Q2\" := (qunion false Q1 Q2) (at level 45).\n  Notation \"Q1 'INTERSECT' Q2\" := (qinters false Q1 Q2) (at level 45).\n  Notation \"Q1 'EXCEPT' Q2\" := (qexcept false Q1 Q2) (at level 45).\n  Notation \"Q1 'UNION' 'ALL' Q2\" := (qunion true Q1 Q2) (at level 45).\n  Notation \"Q1 'INTERSECT' 'ALL' Q2\" := (qinters true Q1 Q2) (at level 45).\n  Notation \"Q1 'EXCEPT' 'ALL' Q2\" := (qexcept true Q1 Q2) (at level 45).\n\n  Notation \"'FALSE'\" := cndfalse (at level 45).\n  Notation \"'TRUE'\" := cndtrue (at level 45).\n  Notation \"t 'IS' 'NULL'\" := (cndnull true t) (at level 45).\n  Notation \"t 'IS' 'NOT' 'NULL'\" := (cndnull false t) (at level 45).\n  Notation \"tl 'IN' Q\" := (cndmemb true tl Q) (at level 45).\n  Notation \"tl 'NOT' 'IN' Q\" := (cndmemb false tl Q) (at level 45).\n  Notation \"'EXISTS' Q\" := (cndex Q) (at level 45).\n  Notation \"e1 'AND' e2\" := (cndand e1 e2) (at level 45).\n  Notation \"e1 'OR' e2\" := (cndor e1 e2) (at level 45).\n  Notation \"'NOT' e\" := (cndnot e) (at level 45).\n\n  Definition mapi {A B: Type} (f : nat -> A -> B) (l : list A) : list B := \n    (fix aux l0 i : list B :=\n      match l0 with\n      | List.nil => List.nil\n      | a::tl => f i a::aux tl (S i)\n      end) l 0.\n\n  Definition btm_of_ctx (G: Ctx) : list (pretm * Name) := \n    List.concat (mapi (fun i => List.map (fun x => (tmvar (i,x), x))) G).\n\n  Definition tmlist_of_ctx (G: Ctx) : list pretm := \n    List.concat (mapi (fun i => List.map (fun x => tmvar (i,x))) G).\n\n  Lemma length_tmlist c0 : length (tmlist_of_ctx c0) = length (concat c0).\n  Proof.\n    unfold tmlist_of_ctx. unfold mapi. generalize 0.\n    elim c0; intuition. \n    simpl. do 2 rewrite app_length. rewrite cmap_length.\n    f_equal. apply H.\n  Qed.\n\n  Inductive j_var (a : Name) : Scm -> Prop :=\n  | j_varhd   : forall s, ~ List.In a s -> j_var a (a::s)\n  | j_varcons : forall b s, a <> b -> j_var a s -> j_var a (b::s).\n\n  Inductive j_tm  (g : Ctx) : pretm -> Prop := \n  | j_const : forall c, j_tm g (tmconst c)\n  | j_null  : j_tm g tmnull\n  | j_tmvar : forall n a s, List.nth_error g n = Some s -> j_var a s -> j_tm g (tmvar (n,a)).\n\n  (* this was put into place to allow for well-formedness conditions on the DB,\n     but we don't have any *)\n  Inductive j_db (d : Db.D) : Prop := jd_intro : j_db d.\n\n  Definition j_tml (g : Ctx) (tl : list pretm) : Type := forall t, List.In t tl -> j_tm g t.\n\n  Definition dflist : forall A, list A -> Prop := List.NoDup.\n\n  Inductive j_query (d : Db.D) : Ctx -> prequery -> Scm -> Prop :=\n  | j_select :\n      forall s c b btm btbl g g1,\n      j_btbl d g btbl g1 ->     (* btbl is wellformed under Ctx g, producing a context extension g1 *)\n      j_cond d (g1 ++ g) c ->   (* c is defined under Ctx (g1 ++ g) *)\n      j_tml (g1 ++ g) (List.map fst btm) -> (* the attr names given don't matter *)\n      (* j_tm/j_cond needs all of the references to be unambiguous, i.e. if (g1 ++ g) contains duplicate entries,\n          they cannot be used by the terms *)\n      s = List.map snd btm ->   (* the schema is given by the second components of btm *)\n      j_query d g (select b btm btbl c) s\n  | j_selstar :\n      forall g btbl g1 c s b,\n      j_btbl d g btbl g1 ->       (* btb is wellformed under Ctx g, producing a context extension g1 *)\n      j_cond d (g1 ++ g) c ->   (* c is defined under Ctx (g1 ++ g) *)\n      s = List.concat g1 ->     (* merges the schemas in g1 *)\n      j_tml (g1 ++ g) (tmlist_of_ctx g1) ->\n      (* the line above forces the attributes in g1 to be unambiguous *)\n      j_query d g (selstar b btbl c) s\n  (* union etc. allow different schemas for subqueries, and return the schema of the first query *)\n  | j_union   : forall g b q1 q2 s s', length s = length s' -> j_query d g q1 s -> j_query d g q2 s' -> j_query d g (qunion b q1 q2) s\n  | j_inters  : forall g b q1 q2 s s', length s = length s' -> j_query d g q1 s -> j_query d g q2 s' -> j_query d g (qinters b q1 q2) s\n  | j_except  : forall g b q1 q2 s s', length s = length s' -> j_query d g q1 s -> j_query d g q2 s' -> j_query d g (qexcept b q1 q2) s\n\n  with j_tb (d : Db.D) : Ctx -> pretb -> Scm -> Prop :=\n  | j_tbbase  : forall x s g, j_db d -> Db.db_schema d x = Some s -> j_tb d g (tbbase x) s\n  | j_tbquery : forall g q s, j_query d g q s -> j_tb d g (tbquery q) s\n\n  with j_cond (d : Db.D) : Ctx -> precond -> Prop :=\n  | j_cndtrue   : forall g, j_db d -> j_cond d g cndtrue\n  | j_cndfalse  : forall g, j_db d -> j_cond d g cndfalse\n  | j_cndnull   : forall g t b, j_db d -> j_tm g t -> j_cond d g (cndnull b t)\n  | j_cndistrue : forall g c, j_cond d g c -> j_cond d g (cndistrue c)\n  | j_cndpred   : forall g n p tml, j_db d -> j_tml g tml -> length tml = n -> j_cond d g (cndpred n p tml)\n  | j_cndmemb   : forall g q sq tl b, \n                  j_tml g tl -> j_query d g q sq -> \n                  List.length sq = List.length tl -> j_cond d g (cndmemb b tl q)\n  | j_cndex     : forall g q, j_inquery d g q -> j_cond d g (cndex q)\n  | j_cndand    : forall g c1 c2, j_cond d g c1 -> j_cond d g c2 -> j_cond d g (cndand c1 c2)\n  | j_cndor     : forall g c1 c2, j_cond d g c1 -> j_cond d g c2 -> j_cond d g (cndor c1 c2)\n  | j_cndnot    : forall g c, j_cond d g c -> j_cond d g (cndnot c)\n\n  (* the output of j_btb can use any choice of names, avoiding collision *)\n  with j_btb  (d : Db.D) : Ctx -> list (pretb * Scm) -> Ctx -> Prop :=\n  | j_btbnil  : forall g, j_db d -> j_btb d g List.nil List.nil\n  | j_btbcons : forall g T s s' btb g1, length s = length s' -> List.NoDup s' -> \n                j_tb d g T s -> j_btb d g btb g1 -> j_btb d g ((T,s')::btb) (s'::g1)\n\n  with j_btbl (d : Db.D) : Ctx -> list (list (pretb * Scm)) -> Ctx -> Prop :=\n  | j_btblnil : forall g, j_db d -> j_btbl d g List.nil List.nil\n  | j_btblcons : forall g B Bl g1 g2, j_btbl d g Bl g1 -> j_btb d (g1++g) B g2 -> j_btbl d g (B::Bl) (g2++g1)\n \n  with j_inquery (d : Db.D) : Ctx -> prequery -> Prop :=\n  | j_inselect :\n      forall c b btm btbl g g1,\n      j_btbl d g btbl g1 ->       (* btb is wellformed under Ctx g, producing a context extension g1 *)\n      j_cond d (g1 ++ g) c ->  (* c is defined under Ctx (g (+) g1) *)\n      j_tml (g1 ++ g) (List.map fst btm) -> (* btm is wellformed under Ctx (g (+) g1) *)\n      j_inquery d g (select b btm btbl c)\n  | j_inselstar :\n      forall g btbl g1 c b,\n      j_btbl d g btbl g1 ->       (* btb is wellformed under Ctx g, producing a context extension g1 *)\n      j_cond d (g1 ++ g) c ->  (* c is defined under Ctx (g (+) g1) *)\n      (* the different behaviour, compared with j_query, is achieved by omitting the j_tml premise *)\n      j_inquery d g (selstar b btbl c)\n  (* union etc. allow different schemas for subqueries, and return the schema of the first query *)\n  | j_inunion   : forall g b q1 q2 s s', length s = length s' -> j_query d g q1 s -> j_query d g q2 s' -> j_inquery d g (qunion b q1 q2)\n  | j_ininters  : forall g b q1 q2 s s', length s = length s' -> j_query d g q1 s -> j_query d g q2 s' -> j_inquery d g (qinters b q1 q2)\n  | j_inexcept  : forall g b q1 q2 s s', length s = length s' -> j_query d g q1 s -> j_query d g q2 s' -> j_inquery d g (qexcept b q1 q2)\n  .\n\n  Scheme jq_ind_mut := Induction for j_query Sort Prop\n  with jT_ind_mut := Induction for j_tb Sort Prop\n  with jc_ind_mut := Induction for j_cond Sort Prop\n  with jbT_ind_mut := Induction for j_btb Sort Prop\n  with jbTl_ind_mut := Induction for j_btbl Sort Prop\n  with jiq_ind_mut := Induction for j_inquery Sort Prop.\n\n  Combined Scheme j_ind_mut from jq_ind_mut, jT_ind_mut, jc_ind_mut, jbT_ind_mut, jiq_ind_mut.\n\n  Definition tm := fun G => { t : pretm & j_tm G t }.\n  Definition query := fun d G s => { Q : prequery & j_query d G Q s }.\n  Definition tb := fun d G s => { T : pretb & j_tb d G T s }.\n  Definition cond := fun d G => { c : precond & j_cond d G c }.\n  Definition inquery := fun d G => { Q : prequery & j_inquery d G Q }.\n\n  (* a recursive definition of schemas *)\n\n  (* XXX: not entirely sure of the rationale for propagating or erasing the boolean b *)\n  Fixpoint q_schema (d : Db.D) (q : prequery) (b : bool) {struct q} : list Name :=\n    match q with\n    | select _ btm _ _  => List.map snd btm (* XXX: no duplicate-freedom check *)\n    | selstar _ btb _   =>\n        if b then List.nil\n        else List.concat (List.concat ((List.map (List.map snd) btb)))\n     (* bind (monadic_map (tb_schema d) btb) (fun G0 => ret (List.concat G0)) *)\n    | qunion _ q1 _ => q_schema d q1 false\n    | qinters _ q1 q2   => q_schema d q1 false\n    | qexcept _ q1 q2   => q_schema d q1 false\n    end.\n\n  Definition tb_schema (d : Db.D) (T : pretb) : option (list Name) :=\n    match T with\n    | tbbase x  => Db.db_schema d x\n    | tbquery q0 => ret (q_schema d q0 false)\n    end.\n\n(* \n  Fixpoint pred_safe (d : Db.D) (c : precond) {struct c} : bool :=\n    match c with\n    | cndmemb _ tl q0 => List.length (q_schema d q0 false) =? List.length tl\n    | cndex q0 => match q_schema d q0 true with None => false | _ => true end\n    | cndand c1 c2 => pred_safe d c1 && pred_safe d c2\n    | cndor c1 c2 => pred_safe d c1 && pred_safe d c2\n    | cndnot c0 => pred_safe d c0\n    | cndpred n p tml => length tml =? n\n    | _ => true\n    end.\n*)\n\n  Definition btb_schema (d : Db.D) : list (pretb * Scm) -> Ctx :=\n    (* bind (monadic_map (tb_schema d) btb) ret *)\n    List.map snd.\n\n  Definition btbl_schema (d : Db.D) (btbl : list (list (pretb * Scm))) : Ctx :=\n    List.concat (List.map (btb_schema d) btbl).\n\n(* TODO we stop here because we still have to do btbl_schema *)\n\n  Theorem jq_q_schema : forall d G Q s,\n    forall j : j_query d G Q s, q_schema d Q false = s.\n  intros d G Q s HWF.\n  eapply (jq_ind_mut _ \n          (fun G0 Q0 s0 H0 => q_schema d Q0 false = s0)\n          (fun G0 T0 s0 H0 => (* tb_schema d T0 = Some s0 *) True)\n          (fun G0 c0 H0 => (* pred_safe d c0 = true *) True)\n          (fun G0 btb G1 H0 => btb_schema d btb = G1)\n          (fun G0 btbl G1 H0 => btbl_schema d btbl = G1)\n          (fun G0 Q0 H0 => exists s0, q_schema d Q0 true = s0)\n          _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ HWF).\n  Unshelve.\n  + intros s0 c b btm btb G0 G1 Hbtb IHbtb Hc IHc Html. simpl. intro. rewrite e. reflexivity.\n  + intros G0 btbl G1 c s0 b Hbtbl IHbtbl Hc IHc e Html. simpl.\n    simpl in IHbtbl. unfold btbl_schema, btb_schema in IHbtbl.\n    rewrite e. rewrite <- IHbtbl. reflexivity.\n  + intros G0 b Q1 Q2 s0 s1 Hlen HQ1 IHQ1 HQ2 IHQ2; simpl; simpl in IHQ1; exact IHQ1.\n  + intros G0 b Q1 Q2 s0 s1 Hlen HQ1 IHQ1 HQ2 IHQ2; simpl; simpl in IHQ1; exact IHQ1.\n  + intros G0 b Q1 Q2 s0 s1 Hlen HQ1 IHQ1 HQ2 IHQ2; simpl; simpl in IHQ1; exact IHQ1.\n  + intros x s0 G0 Hdb e. simpl. constructor.\n  + intros x s0 G0 Hdb e. simpl. constructor.\n  + intros G0 Hdb. reflexivity.\n  + intros G0 Hdb. reflexivity.\n  + intros G0 t b Hdb Ht. reflexivity.\n  + intros; constructor.\n  + intros; constructor.\n  + intros; constructor.\n  + intros; constructor.\n  + intros; constructor.\n  + intros; constructor.\n  + intros; constructor.\n  + intros; constructor.\n  + intros G0 T s0 s' btb G1 Hlen Hnodup HT IHT Hbtb IHbtb. simpl. unfold btb_schema.\n    simpl in IHbtb. unfold btb_schema, ret in IHbtb.\n    rewrite IHbtb. reflexivity.\n  + intros; reflexivity.\n  + intros G1 btb btbl G2 G3 Hbtbl IHbtbl Hbtb IHbtb. simpl.\n    simpl in IHbtbl, IHbtb. rewrite <- IHbtbl, <- IHbtb. reflexivity.\n  + intros c b btm btb G0 G1 Hbtb IHbtb Hc IHc Html. simpl. eexists. all:auto.\n  + intros G0 btb G1 c b Hbtb IHbtb Hc IHc. simpl. eexists. all:eauto.\n  + intros G0 b Q1 Q2 s0 s1 Hlen HQ1 IHQ1 HQ2 IHQ2; simpl. rewrite IHQ1. exists s0; auto.\n  + intros G0 b Q1 Q2 s0 s1 Hlen HQ1 IHQ1 HQ2 IHQ2; simpl. rewrite IHQ1. exists s0; auto.\n  + intros G0 b Q1 Q2 s0 s1 Hlen HQ1 IHQ1 HQ2 IHQ2; simpl. rewrite IHQ1. exists s0; auto.\n  Qed.\n\n  Definition tm_lift (t : pretm) k :=\n    match t with\n    | tmvar x => let (n,a) := x in tmvar (k+n,a)\n    | _ => t\n    end.\n\n  Lemma j_tm_weak G G' t : j_tm G t -> j_tm (G' ++ G) (tm_lift t (length G')).\n  Proof.\n    intro H. elim H; try (intros; constructor).\n    simpl. intros n a s HG Has. eapply (j_tmvar _ _ _ s); auto.\n    elim G'; auto.\n  Qed.\n\nEnd SQL.", "meta": {"author": "wricciot", "repo": "nullSQL", "sha": "bdc482ca138b2807334c14de2103abb67e03423a", "save_path": "github-repos/coq/wricciot-nullSQL", "path": "github-repos/coq/wricciot-nullSQL/nullSQL-bdc482ca138b2807334c14de2103abb67e03423a/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24696006550914953}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq path.\nFrom Coq Require Import Eqdep Relation_Operators.\nFrom pcm Require Import pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL Require Import Freshness State EqTypeX DepMaps.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection NewSoupPredicates.\n\n(*****************************************************)\n(*        More elaborated message predicates         *)\n(*****************************************************)\n\n\nDefinition msg_in_soup' from to t (cond : seq nat -> bool) (d : soup) :=\n  (exists! i, exists c,\n        find i d = Some (Msg (TMsg t c) from to true)) /\\\n  forall i c, find i d = Some (Msg (TMsg t c) from to true) -> cond c.\n\nDefinition msg_spec' from to tg cnt :=\n  msg_in_soup' from to tg (fun y => (y == cnt)).\n\nDefinition no_msg_from_to' from to\n           (criterion : nat -> seq nat -> bool) (d : soup) :=\n  forall i t c,\n    find i d = Some (Msg (TMsg t c) from to true) -> ~~criterion t c.\n\nLemma no_msg_from_to_consume' from to cond s i:\n  valid s ->\n  no_msg_from_to' from to cond s ->\n  no_msg_from_to' from to cond (consume_msg s i).\nProof.\nmove=>V H m t c .\nrewrite /consume_msg; case: (find i s); last by move=>F; apply: (H m t c F).\nmove=>ms; case B: (m == i).\n- by move/eqP: B=>B; subst m; rewrite findU eqxx/= V.\nby rewrite findU B/==>/(H m t c).\nQed.\n\nLemma no_msg_spec_consume s from to tg cnt cond i :\n  valid s ->\n  find i s = Some {| content := TMsg tg cnt;\n                     from := from; to := to; active := true |} ->\n  msg_in_soup' from to tg cond s ->\n  no_msg_from_to' from to (fun x y => (x == tg)) (consume_msg s i).\nProof.\nmove=>V F[][j][[c]]F' H1 H2.\nmove=>m t' c'; rewrite /consume_msg; move: (find_some F).\ncase: dom_find=>// msg->_ _; case B: (m == i).\n- by move/eqP: B=>B; subst m; rewrite findU eqxx/= V.\nhave X: j = i by apply: (H1 i); exists cnt.\nsubst j; rewrite findU B/==>H.\ncase X: (t' == tg)=>//=.\nmove/eqP: X=>X; subst t'.\nsuff X: i = m by subst i; rewrite eqxx in B.\nby apply: (H1 m); exists c'.\nQed.\n\nLemma msg_spec_consumeE i d from to from' to' t c' t' cond:\n  valid d ->\n  find  i d = Some (Msg (TMsg t' c') from' to' true) ->\n  msg_in_soup' from to t cond d ->\n  [|| (from != from'), (to != to') | (t != t')] ->\n  msg_in_soup' from to t cond (consume_msg d i).\nProof.\nmove=>V E S N.\ncase: S=>[][j][[c]F]H1 H2.\nhave Nij: i != j.\n- case H: (i == j)=>//.\n  move/eqP in H; subst i; move: E; rewrite F=>[][???]; subst.\n  move: N=>/orP []/eqP; first by congruence.\n  move/eqP/orP; case; first by move=>X Z; subst to'; rewrite eqxx in X.\n  by rewrite eqxx.\nsplit.\n- exists j; split; first by exists c; rewrite mark_other// eq_sym; apply/negbTE.\n  move=> x [c1] E'.\n  case H: (x == i).\n  + by move/eqP in H; subst x; rewrite (find_consume _ E) in E'.\n  by apply: H1; exists c1; rewrite mark_other in E'.\nmove=>k c1.\ncase H: (k == i); first by move/eqP in H; subst k; rewrite (find_consume _ E).\nby rewrite mark_other//; apply: H2.\nQed.\n\n\nEnd NewSoupPredicates.\n", "meta": {"author": "DistributedComponents", "repo": "disel", "sha": "88dc15450394a5963f513d220001b49389c6b52f", "save_path": "github-repos/coq/DistributedComponents-disel", "path": "github-repos/coq/DistributedComponents-disel/disel-88dc15450394a5963f513d220001b49389c6b52f/theories/Core/NewStatePredicates.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2469533556692104}}
{"text": "(*! Circuits | Lemmas used in the compiler-correctness proof !*)\nRequire Export Koika.CircuitGeneration Koika.CircuitOptimization.\nRequire Import Koika.Common Koika.Environments Koika.Types Koika.Lowering.\n\nSection Bools.\n  Definition bool_le b1 b2 :=\n    b2 = false ->\n    b1 = false.\n\n  Lemma bool_le_impl b1 b2 :\n    bool_le b1 b2 <-> (orb (negb b1) b2) = true.\n  Proof.\n    destruct b1, b2; unfold bool_le; cbn; intuition.\n  Qed.\n\n  Lemma bool_le_and :\n    forall b1 b1' b2 b2',\n      bool_le b1 b1' ->\n      bool_le b2 b2' ->\n      bool_le (andb b1 b2) (andb b1' b2').\n  Proof.\n    unfold bool_le; intros.\n    destruct b1, b2, b1', b2'; cbn;\n      intuition discriminate.\n  Qed.\n\n  Lemma bool_le_and_l :\n    forall b1 b1' b2,\n      bool_le b1 b1' ->\n      bool_le (andb b1 b2) b1'.\n  Proof.\n    unfold bool_le; intros.\n    destruct b1, b2, b1'; cbn;\n      intuition discriminate.\n  Qed.\n\n  Lemma bool_le_or :\n    forall b1 b1' b2 b2',\n      bool_le b1 b1' ->\n      bool_le b2 b2' ->\n      bool_le (orb b1 b2) (orb b1' b2').\n  Proof.\n    unfold bool_le; intros.\n    destruct b1, b2, b1', b2'; cbn;\n      intuition discriminate.\n  Qed.\n\n  Lemma bool_le_mux :\n    forall (s: bool) b1 b1' b2 b2',\n      bool_le b1 b1' ->\n      bool_le b2 b2' ->\n      bool_le (if s then b1 else b2) (if s then b1' else b2').\n  Proof.\n    unfold bool_le; intros.\n    destruct s; cbn;\n      intuition discriminate.\n  Qed.\n\n  Lemma bool_le_not :\n    forall b1 b2,\n      bool_le b1 b2 ->\n      bool_le (negb b2) (negb b1).\n  Proof.\n    unfold bool_le; intros.\n    destruct b1, b2; cbn;\n      intuition discriminate.\n  Qed.\n\n  Lemma bool_le_true :\n    forall b, bool_le b true.\n  Proof.\n    unfold bool_le; intros;\n      destruct b; intuition discriminate.\n  Qed.\n\n  Lemma bool_le_false :\n    forall b, bool_le false b.\n  Proof.\n    unfold bool_le; intros;\n      destruct b; intuition discriminate.\n  Qed.\nEnd Bools.\n\nSection Circuits.\n  Context {pos_t var_t rule_name_t reg_t ext_fn_t: Type}.\n\n  Context {CR: reg_t -> nat}.\n  Context {CSigma: ext_fn_t -> CExternalSignature}.\n\n  Context {REnv: Env reg_t}.\n  Context (cr: REnv.(env_t) (fun idx => bits (CR idx))).\n\n  Context {Show_rule_name_t : Show rule_name_t}.\n\n  Context (csigma: forall f, CSig_denote (CSigma f)).\n  Context (lco: (@local_circuit_optimizer\n                   rule_name_t reg_t ext_fn_t CR CSigma\n                   (rwdata (rule_name_t := rule_name_t) CR CSigma)\n                   csigma)).\n\n  Notation circuit := (circuit (rule_name_t := rule_name_t)\n                              (rwdata := rwdata (rule_name_t := rule_name_t) CR CSigma)\n                              CR CSigma).\n  Notation interp_circuit := (interp_circuit cr csigma).\n\n  Definition circuit_le (c1 c2: circuit 1) :=\n    bool_le (Bits.single (interp_circuit c1)) (Bits.single (interp_circuit c2)).\n\n  Lemma interp_circuit_circuit_le_helper_false :\n    forall c1 c2,\n      circuit_le c1 c2 ->\n      interp_circuit c2 = Ob~0 ->\n      interp_circuit c1 = Ob~0.\n  Proof.\n    unfold circuit_le; intros * Hlt Heq;\n      destruct (interp_circuit c1) as (? & [ ]), (interp_circuit c2) as (? & []).\n    inversion Heq; cbv; f_equal; apply Hlt; cbn; congruence.\n  Qed.\n\n  Lemma interp_circuit_circuit_le_helper_true :\n    forall c1 c2,\n      circuit_le c1 c2 ->\n      interp_circuit c1 = Ob~1 ->\n      interp_circuit c2 = Ob~1.\n  Proof.\n    unfold circuit_le; intros * Hlt Heq;\n      destruct (interp_circuit c1) as (? & [ ]), (interp_circuit c2) as ([ | ] & []);\n      inversion Heq; subst; cbv; f_equal; symmetry; apply Hlt; cbn; congruence.\n  Qed.\n\n  Lemma circuit_le_CAnnot :\n    forall s c1 c2,\n      circuit_le c1 c2 ->\n      circuit_le (CAnnot s c1) (CAnnot s c2).\n  Proof. firstorder. Qed.\n\n  Lemma circuit_le_CAnnot_l :\n    forall s c1 c2,\n      circuit_le c1 c2 ->\n      circuit_le (CAnnot s c1) c2.\n  Proof. firstorder. Qed.\n\n  Lemma circuit_le_CAnnot_r :\n    forall s c1 c2,\n      circuit_le c1 c2 ->\n      circuit_le c1 (CAnnot s c2).\n  Proof. firstorder. Qed.\n\n  Lemma circuit_le_CBundleRef :\n    forall rl1 rl2 rs1 rs2 b1 b2 field1 field2 c1 c2,\n      circuit_le c1 c2 ->\n      circuit_le (CBundleRef rl1 rs1 b1 field1 c1) (CBundleRef rl2 rs2 b2 field2 c2).\n  Proof. firstorder. Qed.\n\n  Lemma circuit_le_CBundleRef_l :\n    forall rl1 rs1 b1 field1 c1 c2,\n      circuit_le c1 c2 ->\n      circuit_le (CBundleRef rl1 rs1 b1 field1 c1) c2.\n  Proof. firstorder. Qed.\n\n  Lemma circuit_le_CBundleRef_r :\n    forall rl2 rs2 b2 field2 c1 c2,\n      circuit_le c1 c2 ->\n      circuit_le c1 (CBundleRef rl2 rs2 b2 field2 c2).\n  Proof. firstorder. Qed.\n\n  Lemma circuit_le_CAnd :\n    forall c1 c1' c2 c2',\n      circuit_le c1 c1' ->\n      circuit_le c2 c2' ->\n      circuit_le (CAnd c1 c2) (CAnd c1' c2').\n  Proof. unfold circuit_le; cbn; eauto using bool_le_and. Qed.\n\n  Lemma circuit_le_CAnd_l :\n    forall c1 c1' c2,\n      circuit_le c1 c1' ->\n      circuit_le (CAnd c1 c2) c1'.\n  Proof. unfold circuit_le; cbn; eauto using bool_le_and_l. Qed.\n\n  Lemma circuit_le_CAnd_r :\n    forall c1 c1' c2',\n      circuit_le c1 c1' ->\n      interp_circuit c2' = Ob~1 ->\n      circuit_le c1 (CAnd c1' c2').\n  Proof. unfold circuit_le; cbn. intros * ? ->.\n     cbn; rewrite Bool.andb_true_r; eauto. Qed.\n\n  Lemma circuit_le_COr :\n    forall c1 c1' c2 c2',\n      circuit_le c1 c1' ->\n      circuit_le c2 c2' ->\n      circuit_le (COr c1 c2) (COr c1' c2').\n  Proof. unfold circuit_le; cbn; eauto using bool_le_or. Qed.\n\n  Lemma circuit_le_CMux :\n    forall s c1 c1' c2 c2',\n      circuit_le c1 c1' ->\n      circuit_le c2 c2' ->\n      circuit_le (CMux s c1 c2) (CMux s c1' c2').\n  Proof.\n    unfold circuit_le; cbn;\n      intros; destruct (Bits.single (interp_circuit s)); eauto.\n  Qed.\n\n  Lemma circuit_le_CMux_l :\n    forall s c1 c2 c3,\n      (interp_circuit s = Ob~1 -> circuit_le c1 c3) ->\n      (interp_circuit s = Ob~0 -> circuit_le c2 c3) ->\n      circuit_le (CMux s c1 c2) c3.\n  Proof.\n    unfold circuit_le; cbn;\n      intros * Heq1 Heq2; destruct (interp_circuit s) as [ b [] ]; cbn.\n    destruct b; eauto.\n  Qed.\n\n  Lemma circuit_le_CMux_r :\n    forall s c1 c2 c3,\n      (interp_circuit s = Ob~1 -> circuit_le c1 c2) ->\n      (interp_circuit s = Ob~0 -> circuit_le c1 c3) ->\n      circuit_le c1 (CMux s c2 c3).\n  Proof.\n    unfold circuit_le; cbn;\n      intros * Heq1 Heq2; destruct (interp_circuit s) as [ b [] ]; cbn.\n    destruct b; eauto.\n  Qed.\n\n  Lemma circuit_le_CNot :\n    forall c1 c2,\n      circuit_le c1 c2 ->\n      circuit_le (CNot c2) (CNot c1).\n  Proof. unfold circuit_le; cbn; eauto using bool_le_not. Qed.\n\n  Lemma circuit_le_true :\n    forall c, circuit_le c (CConst Ob~1).\n  Proof. unfold circuit_le; cbn; eauto using bool_le_true. Qed.\n\n  Lemma circuit_le_false :\n    forall c, circuit_le (CConst Ob~0) c.\n  Proof. unfold circuit_le; cbn; eauto using bool_le_false. Qed.\n\n  Lemma circuit_le_fold_right {X} :\n    forall (xs: list X) f0 f1 c0 c1,\n      circuit_le c1 c0 ->\n      (forall x acc1 acc0, circuit_le acc1 acc0 -> circuit_le (f1 x acc1) (f0 x acc0)) ->\n      circuit_le (List.fold_right f1 c1 xs) (List.fold_right f0 c0 xs).\n  Proof.\n    induction xs; cbn; intros * Hlt Hxlt; eauto.\n  Qed.\n\n  Lemma circuit_le_refl :\n    forall c, circuit_le c c.\n  Proof. firstorder. Qed.\n\n  Lemma circuit_le_trans :\n    forall c1 c2 c3,\n      circuit_le c1 c2 ->\n      circuit_le c2 c3 ->\n      circuit_le c1 c3.\n  Proof. firstorder. Qed.\n\n  Lemma circuit_le_opt_l :\n    forall c1 c2,\n      circuit_le c1 c2 ->\n      circuit_le (lco.(lco_fn) c1) c2.\n  Proof.\n    unfold circuit_le; intros; rewrite lco.(lco_proof); assumption.\n  Qed.\n\n  Lemma circuit_le_opt_r :\n    forall c1 c2,\n      circuit_le c1 c2 ->\n      circuit_le c1 (lco.(lco_fn) c2).\n  Proof.\n    unfold circuit_le; intros; rewrite lco.(lco_proof); assumption.\n  Qed.\n\n  Lemma circuit_le_willFire_of_canFire_canFire :\n    forall rl_name c1 (cLog: scheduler_circuit (rule_name_t := rule_name_t) CR CSigma REnv) rws,\n      circuit_le (willFire_of_canFire lco rl_name {| canFire := c1; regs := rws |} cLog) c1.\n  Proof.\n    unfold willFire_of_canFire; intros.\n    eapply circuit_le_trans.\n    - eapply circuit_le_fold_right.\n      + apply circuit_le_refl.\n      + intros; rewrite !getenv_zip.\n        eapply circuit_le_opt_l, circuit_le_CAnd.\n        * eassumption.\n        * apply circuit_le_true.\n    - cbn.\n      induction finite_elements; cbn.\n      + apply circuit_le_CAnnot_l, circuit_le_refl.\n      + apply circuit_le_CAnd_l; eassumption.\n  Qed.\nEnd Circuits.\n\nLtac circuit_le_f_equal :=\n  repeat (apply circuit_le_CAnnot_l ||\n          apply circuit_le_CAnnot_r ||\n          apply circuit_le_opt_l ||\n          apply circuit_le_opt_r ||\n          apply circuit_le_CBundleRef_l ||\n          apply circuit_le_CBundleRef_r ||\n          apply circuit_le_CAnd ||\n          apply circuit_le_COr ||\n          apply circuit_le_CNot ||\n          apply circuit_le_true ||\n          apply circuit_le_false ||\n          apply circuit_le_refl).\n", "meta": {"author": "mit-plv", "repo": "koika", "sha": "c758c7b0092186f76ed858f4137366cc62f7a04a", "save_path": "github-repos/coq/mit-plv-koika", "path": "github-repos/coq/mit-plv-koika/koika-c758c7b0092186f76ed858f4137366cc62f7a04a/coq/CircuitProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24676624590664595}}
{"text": "From ExtLib Require Export\n     Extras\n     RelDec.\nFrom Ceres Require Export\n     Ceres.\nFrom ITree Require Export\n     Exception\n     Nondeterminism\n     ITree.\nFrom Coq Require Export\n     String.\nExport\n  FunNotation\n  Monads\n  SumNotations\n  ITreeNotations.\nOpen Scope itree_scope.\nOpen Scope string_scope.\nOpen Scope sum_scope.\n\nSection Server.\n\nVariables Q A S : Type.\n\nHypothesis RelDec__A   : RelDec (@eq A).\nHypothesis Serialize__A: Serialize A.\nHypothesis Serialize__Q: Serialize Q.\n\nVariant serverE : Type -> Type :=\n  Server__Recv : S -> serverE Q\n| Server__Exec : Q -> A -> serverE unit.\n\nDefinition serverOf {E} `{serverE -< E} (step: Q -> state S A) : S -> itree E void :=\n  rec (fun s =>\n         q <- embed Server__Recv s;;\n         let (s', a) := step q s in\n         embed Server__Exec q a;;\n         call s').\n\nClass Is__sE E `{serverE -< E} `{nondetE -< E}.\n\nDefinition serverOfT {E} `{serverE -< E} `{nondetE -< E}\n           (stept: forall {F} `{nondetE -< F}, Q -> stateT S (itree F) A)\n  : S -> itree E void :=\n  rec (fun s =>\n         q <- embed Server__Recv s;;\n         '(s', a) <- stept q s;;\n         embed Server__Exec q a;;\n         call s').\n\nVariant observeE : Type -> Type :=\n  Observe__FromServer : Q -> observeE A\n| Observe__FromClient : S -> observeE Q.\n\nClass Is__oE E `{observeE -< E} `{nondetE -< E} `{exceptE string -< E}.\n\nDefinition observe {E} `{Is__oE E} (m: itree (serverE +' nondetE) void) : itree E void :=\n  interp\n    (fun _ e =>\n       match e with\n       | (se|) =>\n           match se in serverE Y return _ Y with\n           | Server__Recv s => embed Observe__FromClient s\n           | Server__Exec q a =>\n               a' <- embed Observe__FromServer q;;\n               if a' ?[ eq ] a\n               then Ret tt\n               else throw $ \"Upon \" ++ to_string q ++\n                          \", expect \" ++ to_string a ++\n                          \", but observed \" ++ to_string a'\n           end\n       | (|ne) =>\n           match ne in nondetE Y return _ Y with\n           | Or => trigger Or\n           end\n       end) m.\n\nEnd Server.\n\nArguments serverOf {_ _ _ _ _}.\nArguments observe  {_ _ _ _ _ _ _ _ _ _ _}.\nArguments serverOfT {_ _ _ _ _ _}.\n\nNotation failureE := (exceptE string).\nNotation sE Q A S := (serverE Q A S +' nondetE).\nNotation oE Q A S := (observeE Q A S +' nondetE +' failureE).\n#[global]\nInstance oE_Is__oE Q A S : Is__oE Q A S (oE Q A S). Defined.\n#[global]\nInstance sE_Is__sE Q A S : Is__sE Q A S (sE Q A S). Defined.\n", "meta": {"author": "liyishuai", "repo": "file-sync", "sha": "3a270f48eeef26e3d4274c5347c7d45f330b680f", "save_path": "github-repos/coq/liyishuai-file-sync", "path": "github-repos/coq/liyishuai-file-sync/file-sync-3a270f48eeef26e3d4274c5347c7d45f330b680f/theories/Server.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2467662459066459}}
{"text": "(** * Definition of the generic part of the interface of the correctness proof of the CFG parser *)\nRequire Import Coq.Strings.String.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Arith.EqNat.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.GenericBaseTypes.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.StringLike.Core.\n\nSet Implicit Arguments.\n\nSection correctness.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char}\n          {predata : @parser_computational_predataT Char}\n          {gendata : @generic_parser_dataT Char}.\n\n  Class generic_parser_decidable_data {gendata : @generic_parser_dataT Char} :=\n    {\n      parse_nt_T_to_bool : parse_nt_T -> bool;\n      parse_item_T_to_bool : parse_item_T -> bool;\n      parse_production_T_to_bool : parse_production_T -> bool;\n      parse_productions_T_to_bool : parse_productions_T -> bool\n    }.\n\n  Class generic_parser_decidable_correctness_data {gendata : @generic_parser_dataT Char} {gddata : generic_parser_decidable_data} :=\n    {\n      ret_Terminal_true_to_bool\n      : forall ch, parse_item_T_to_bool (ret_Terminal_true ch) = true;\n      ret_Terminal_false_to_bool\n      : forall ch, parse_item_T_to_bool (ret_Terminal_false ch) = false;\n      ret_NonTerminal_true_to_bool\n      : forall nt rv, parse_item_T_to_bool (ret_NonTerminal_true nt rv) = parse_nt_T_to_bool rv;\n      ret_NonTerminal_false_to_bool\n      : forall nt, parse_item_T_to_bool (ret_NonTerminal_false nt) = false;\n      ret_production_nil_true_to_bool\n      : parse_production_T_to_bool ret_production_nil_true = true;\n      ret_production_nil_false_to_bool\n      : parse_production_T_to_bool ret_production_nil_false = false;\n      ret_orb_production_base_to_bool\n      : parse_production_T_to_bool ret_orb_production_base = false;\n      ret_orb_production_to_bool\n      : forall rv1 rv2, parse_production_T_to_bool (ret_orb_production rv1 rv2)\n                        = orb (parse_production_T_to_bool rv1) (parse_production_T_to_bool rv2);\n      ret_production_cons_to_bool\n      : forall rv1 rv2, parse_production_T_to_bool (ret_production_cons rv1 rv2)\n                        = andb (parse_item_T_to_bool rv1) (parse_production_T_to_bool rv2);\n      ret_orb_productions_base_to_bool\n      : parse_productions_T_to_bool ret_orb_productions_base = false;\n      ret_orb_productions_to_bool\n      : forall rv1 rv2, parse_productions_T_to_bool (ret_orb_productions rv1 rv2)\n                        = orb (parse_production_T_to_bool rv1) (parse_productions_T_to_bool rv2);\n      ret_nt_to_bool\n      : forall v, parse_nt_T_to_bool (ret_nt v) = parse_productions_T_to_bool v;\n      ret_nt_invalid_to_bool\n      : parse_nt_T_to_bool ret_nt_invalid = false\n    }.\nEnd correctness.\n\nCreate HintDb generic_parser_decidable_correctness discriminated.\nHint Rewrite @ret_Terminal_true_to_bool @ret_Terminal_false_to_bool @ret_NonTerminal_true_to_bool @ret_NonTerminal_false_to_bool @ret_production_nil_true_to_bool @ret_production_nil_false_to_bool @ret_orb_production_base_to_bool @ret_orb_production_to_bool @ret_production_cons_to_bool @ret_orb_productions_base_to_bool @ret_orb_productions_to_bool @ret_nt_to_bool @ret_nt_invalid_to_bool : generic_parser_decidable_correctness.\n\nLemma fold_right_ret_orb_production_eq\n      {Char}\n      {gendata : @generic_parser_dataT Char}\n      {gddata : generic_parser_decidable_data}\n      {gdcdata : generic_parser_decidable_correctness_data}\n      ls b\n  : parse_production_T_to_bool (List.fold_right ret_orb_production b ls)\n    = List.fold_right orb (parse_production_T_to_bool b) (List.map parse_production_T_to_bool ls).\nProof.\n  revert b; induction ls as [|?? IHls]; simpl; trivial; intros; [].\n  rewrite <- IHls; clear IHls.\n  autorewrite with generic_parser_decidable_correctness; trivial.\nQed.\n\nLemma fold_right_ret_orb_productions_eq\n      {Char}\n      {gendata : @generic_parser_dataT Char}\n      {gddata : generic_parser_decidable_data}\n      {gdcdata : generic_parser_decidable_correctness_data}\n      ls b\n  : parse_productions_T_to_bool (List.fold_right ret_orb_productions b ls)\n    = List.fold_right orb (parse_productions_T_to_bool b) (List.map parse_production_T_to_bool ls).\nProof.\n  revert b; induction ls as [|?? IHls]; simpl; trivial; intros; [].\n  rewrite <- IHls; clear IHls.\n  autorewrite with generic_parser_decidable_correctness; trivial.\nQed.\n\nHint Rewrite @fold_right_ret_orb_production_eq @fold_right_ret_orb_productions_eq : generic_parser_decidable_correctness.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_eapply_example/src/Parsers/GenericBoolCorrectnessBaseTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24676624590664586}}
{"text": "(** * Parallel.v : describing parallel quantum programs *)\n\nFrom Babel Require Import TerminalDogma \n                          ExtraDogma.Extensionality.\n\nFrom Babel Require Import QTheory POrderFacility POrderSet POrderNat\n                            nd_seq.\n\nFrom Babel.Ranko Require Import CentralCharacter.\n\nFrom Coq Require Import Classical Arith Relations Reals.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n\nModule QParallelProg \n\n(** This Module relies on a basic theory of quantum, *)\n                     (QTB : QTheoryBasicType) \n\n(** and a theory to combine sets into quantums. *)\n                     (QTS : QTheorySetType QTB).\n\n(** Get the extended theory of quantum sets *)\nModule Import QTS_ext := QTheorySet QTB QTS.\n\n\n(** use the number order *)\nImport NatLePoset.CanonicalStruct.\nImport SubsetOrder.CanonicalStruct.\n\n\nDeclare Scope QPP_scope.\nOpen Scope QPP_scope.\n\n(** A legal parallel quantum program (after syntax check) *)\nInductive prog (qs : QvarScope): Type :=\n| skip_\n| abort_ \n| init_ (qv : qs) \n| unitary_ (qv : qs) (U : UnitaryOpt qv)\n| if_ (qv_m : qs) (m : MeaOpt qv_m) (S0 S1: prog qs)\n| while_ (qv_m : qs) (m : MeaOpt qv_m) (S0 : prog qs)\n| seq_ (S1 S2 : prog qs)\n| prob_ (p : [0, 1]R) (S1 S2 : prog qs)\n| nondet_ (S1 S2 : prog qs)\n| atom_ (S0 : prog qs)\n| parallel_ (S1 S2 : prog qs).\n\nNotation \" 'Skip' \" := (@skip_ _) : QPP_scope.\nNotation \" 'Abort' \" := (@abort_ _) : QPP_scope.\nNotation \" qv <- '0' \" := (@init_ _ qv) (at level 10) : QPP_scope.\nNotation \" qv *= U \" := (@unitary_ _ qv U) (at level 10) : QPP_scope.\nNotation \" 'If' m [[ qv_m ]] 'Then' S0 'Else' S1 'End' \" := \n    (@if_ _ qv_m m S0 S1) (at level 90) : QPP_scope.\nNotation \" 'While' m [[ qv_m ]] 'Do' S0 'End' \" := \n    (@while_ _ qv_m m S0) (at level 90) : QPP_scope.\nNotation \" S1 ; S2 \" := (@seq_ _ S1 S2) \n    (at level 95, right associativity) : QPP_scope.\nNotation \" S1 [ p ⊕ ] S2 \" := (@prob_ _ p S1 S2) \n    (format \"S1  [ p  ⊕ ]  S2\"): QPP_scope.\nNotation \" S1 □ S2 \" := (@nondet_ _ S1 S2) (at level 3): QPP_scope.\nNotation \" << P >> \" := (@atom_ _ P) : QPP_scope.\nNotation \" [ S1 // S2 ] \" := (@parallel_ _ S1 S2) (at level 0) : QPP_scope.\n\nFixpoint non_parallel {qs : QvarScope} (P : prog qs) : bool :=\n    match P with \n    | [S1 // S2] => false\n    | If m [[ qv_m ]] Then S0 Else S1 End => non_parallel S0 && non_parallel S1\n    | While m [[ qv_m ]] Do S0 End => non_parallel S0\n    | S1 ; S2 => non_parallel S1 && non_parallel S2\n    | _ => true\n    end.\n\n(** Get the quantum variable of the program *)\nFixpoint qvar_of_prog {qs : QvarScope} (S0 : prog qs) : qs :=\n    match S0 with\n    | Skip => em_var _\n    | Abort => em_var _\n    | qv <- 0 => qv\n    | qv *= _ => qv\n    | If _ [[ qv_m ]] Then S0 Else S1 End\n        => qv_m [+] (qvar_of_prog S0) [+] (qvar_of_prog S1)\n    | While _ [[ qv_m ]] Do S0 End\n        => qv_m [+] (qvar_of_prog S0)\n    | S1;S2 => (qvar_of_prog S1) [+] (qvar_of_prog S2)\n    | S1 [ p ⊕ ] S2 => (qvar_of_prog S1) [+] (qvar_of_prog S2)\n    | S1 □ S2 =>(qvar_of_prog S1) [+] (qvar_of_prog S2)\n    | <<S0>> => qvar_of_prog S0\n    | [ S1 // S2 ] => (qvar_of_prog S1) [+] (qvar_of_prog S2)\n    end.\nCoercion qvar_of_prog : prog >-> Qvar.\n\n\nFixpoint seq_Head {qs : QvarScope} (S0 : prog qs) : prog qs :=\n    match S0 with\n    | P0 ; P1 => seq_Head P0\n    | _ => S0\n    end.\nFixpoint seq_Tail {qs : QvarScope} (S0 : prog qs) : option (prog qs) :=\n    match S0 with\n    | P0 ; P1 => match seq_Tail P0 with\n                  | None => Some P1\n                  | Some Q => Some (Q ; P1)\n                  end\n    | _ => None\n    end.\n\n(** Refine the step statement *)\n(** make a choice for the parallel component program *)\nDefinition Step {qs : QvarScope} (S1 S2: prog qs) \n              (b : bool) : prog qs :=\n    if b then\n        match seq_Tail S1 with\n        | None => (* if S1 is not a sequence *)\n            match S1 with\n            | If m [[ qv_m ]] Then P0 Else P1 End => \n                If m [[ qv_m ]] Then [ P0 // S2 ] Else [ P1 // S2 ] End\n            | While m [[ qv_m ]] Do P0 End =>\n                If m [[ qv_m ]] Then [ P0 ; While m [[qv_m]] Do P0 End // S2 ]\n                                Else [ Skip // S2] End\n            | _ => S1 ; [ Skip // S2 ]\n            end \n        (** Note that here we give a different interpretation of \n            nested parallel composition \n            We consider the inner parallel composition as a 'atomic' action\n            performed in parallel *)\n        | Some Q => seq_Head S1 ; [ Q // S2 ]\n        end\n    else\n        match seq_Tail S2 with\n        | None => (* if S2 is not a sequence *)\n            match S2 with\n            | If m [[ qv_m ]] Then P0 Else P1 End => \n                If m [[ qv_m ]] Then [ S1 // P0 ] Else [ S1 // P1 ] End\n            | While m [[ qv_m ]] Do P0 End =>\n                If m [[ qv_m ]] Then [ S1 // P0 ; While m [[qv_m]] Do P0 End ]\n                                Else [ S1 // Skip] End\n            | _ => S2 ; [ S1 // Skip ]\n            end \n        (** Note that here we give a different interpretation of \n            nested parallel composition *)\n        | Some Q => seq_Head S2 ; [ S1 // Q ]\n    end.\nArguments Step : simpl nomatch.\n(* ############################################################ *)\n(** ** Operational Semantics *)\n\n(** The configuration of computation *)\nInductive cfg (qs : QvarScope): Type :=\n| Srho_pair (S0 : prog qs) (rho : 𝒟( qs )⁻ )\n| Terminated (rho : 𝒟( qs )⁻ ).\nNotation \" <{ S0 , rho }> \" := (@Srho_pair _ S0 rho ) : QPP_scope.\nNotation \" <{ '↓' , rho }> \" := (@Terminated _ rho) : QPP_scope.\n\n\n\nReserved Notation \" c1 -=> c2 \" (at level 20).\nReserved Notation \" c1 -=>* c2 \" (at level 20).\n\n\nInductive opSem_trans qs : cfg qs -> cfg qs -> Prop :=\n| skip_step rho : \n    <{ Skip, rho }> -=> <{ ↓, rho }>\n\n| abort_step rho:\n    <{ Abort, rho }> -=> <{ ↓, 𝟎 }>\n\n| init_step qv rho:\n    <{ qv <- 0, rho }> -=> <{ ↓, InitStt qv rho }>\n\n| unitary_step qv U rho:\n    <{ qv *= U, rho }> -=> <{ ↓, Uapply U rho }>\n\n| if_step_Y qv_m m S0 S1 rho:\n    <{ If m [[qv_m]] Then S0 Else S1 End, rho }>\n    -=> <{ S0, Mapply m true rho }>\n\n| if_step_N qv_m m S0 S1 rho:\n    <{ If m [[qv_m]] Then S0 Else S1 End, rho }>\n        -=> <{ S1, Mapply m false rho }>\n\n| while_step_Y qv_m m S0 rho:\n    <{ While m [[qv_m]] Do S0 End, rho }>\n        -=> <{ S0 ; While m [[qv_m]] Do S0 End, Mapply m true rho }>\n\n| while_step_N qv_m m S0 rho:\n    <{ While m [[qv_m]] Do S0 End, rho }>\n        -=> <{ ↓, Mapply m true rho }>\n\n| seq_step_p S0 St S1 rho0 rho1:\n    <{ S0, rho0 }> -=> <{ St, rho1 }>\n    -> <{ S0 ; S1, rho0 }> -=> <{ St ; S1, rho1 }>\n\n| seq_step_t S0 S1 rho0 rho1:\n    <{ S0, rho0 }> -=> <{ ↓, rho1 }>\n        -> <{ S0 ; S1, rho0 }> -=> <{ S1, rho1 }>\n\n| atom_step S0 rho0 rho1 :\n    <{ S0, rho0 }> -=>* <{ ↓, rho1 }>\n        -> <{ <<S0>>, rho0 }> -=> <{ ↓, rho1 }>\n\n| parallel_step_0 S0 S1 rho :\n    <{ [S0 // S1], rho }> -=> <{ Step S0 S1 true, rho }>\n\n| parallel_step_1 S0 S1 rho :\n    <{ [S0 // S1], rho }> -=> <{ Step S0 S1 false, rho }>\n\nwhere \" c1 -=> c2 \" := (opSem_trans c1 c2)\n    and \" c1 -=>* c2 \" := (clos_trans _ (@opSem_trans _) c1 c2).\n\n\n\n(* ############################################################ *)\n(** ** Denotational Semantics *)\n\nReserved Notation \" ⦗ P , n ⦘ ( rho ) \" \n    (at level 10, rho at next level, format \"⦗  P ,  n  ⦘ ( rho )\").\n    \nReserved Notation \" ⦗ P , n ⦘ \" \n    (at level 10, format \"⦗  P ,  n  ⦘\").\n\nReserved Notation \" ⦗ ↓ ⦘ ( rho ) \" \n    (at level 10, rho at next level, only printing, format \"⦗  ↓  ⦘ ( rho )\").\n\nReserved Notation \" ⦗ ↓ ⦘\" \n    (at level 10, only printing, format \"⦗  ↓  ⦘\").\n\n(** Define the denotational semantics of calculating n steps \n    parameter :\n        [P : option (prog qs)], if [P] is [None] then the program is \n            terminated.*)\nFixpoint deSemN_point {qs : QvarScope} (P : option (prog qs)) (n : nat)\n    (rho : 𝒟( qs )⁻) : 𝒫(𝒟( qs )⁻) :=\n    match P with\n    | None => {{ rho }}\n    | Some P => \n        match n with\n        | 0 => ∅\n        | n'.+1 => \n            match P with\n            | Skip => \n                {{ rho }}\n\n            | Abort => \n                𝕌 \n\n            | qv <- 0 => \n                {{ InitStt qv rho }}\n\n            | qv *= U => \n                {{ Uapply U rho }}\n\n            | If m [[ qv_m ]] Then P0 Else P1 End =>\n                (⦗ P0, n' ⦘ ( Mapply m true rho ))\n                + (⦗ P1, n' ⦘ ( Mapply m false rho ))\n\n            | While m [[ qv_m ]] Do P0 End  =>\n                ⦗ P0; While m [[ qv_m ]] Do P0 End, n' ⦘ (Mapply m true rho)\n                + {{ Mapply m false rho }}\n\n            | S1 ; S2 => \n                ⋃ { ⦗ S2, n' ⦘ (rho') , rho' | rho' ∈ ⦗ S1, n' ⦘ (rho) }\n\n            | S1 [ p ⊕ ] S2 =>\n                (⦗ S1, n' ⦘( rho )[ p ⊕ ] ⦗ S2, n' ⦘( rho ))%QTS\n\n            | S1 □ S2 =>\n                ⦗ S1, n' ⦘(rho) ∪ ⦗ S2, n' ⦘(rho)\n\n            | << P >> => \n                ⦗ P, n' ⦘ (rho)\n\n            | [ S1 // S2 ] => \n                (** Note that here we give a different interpretation of \n                    nested parallel composition *)\n                (⦗ Step S1 S2 true, n' ⦘ (rho))\n                ∪ (⦗ Step S1 S2 false, n' ⦘ (rho))\n\n            end\n        end\n    end\n    where \" ⦗ P , n ⦘ \" := (deSemN_point (Some P) n) : QPP_scope and\n    \" ⦗ P , n ⦘ ( rho ) \" := (deSemN_point (Some P) n rho) : QPP_scope.\n\nArguments deSemN_point : simpl nomatch.\n\nNotation \" ⦗ ↓ ⦘ ( rho ) \" := (deSemN_point None _ rho) :QPP_scope.\nNotation \" ⦗ ↓ ⦘ \" := (deSemN_point None _ ) :QPP_scope.\n\n(** lift to set input *)\nDefinition deSemN {qs : QvarScope} (P : prog qs) (n : nat) := ⋃ ◦ ⦗ P, n ⦘ [<].\n\n\nNotation \" ⟦ P , n ⟧ \" := (deSemN P n)\n    (at level 10, format \"⟦  P ,  n  ⟧\") : QPP_scope.\n\nNotation \" ⟦ P , n ⟧ ( rho_s ) \" := (deSemN P n rho_s)\n    (at level 10, rho_s at next level, \n    format \"⟦  P ,  n  ⟧ ( rho_s )\") : QPP_scope.\n\n(*\n(** Prove that [⦗ P , n ⦘ ( rho )] is always nonempty. *)\nLemma deSemN_point_nemMixin {qs : QvarScope} (P : prog qs) (n : nat) rho :\n    NemSet.class_of (⦗ P , n ⦘ (rho)).\nProof.\n    rewrite /NemSet.mixin_of. elim: n P rho.\n    move => P rho //=. apply uni_neq_em.\n    \n    (** induction step *)\n    move => n IHn. case => //=.\n\n    (** skip, abort, init, unitary *)\n    1,2,3,4 : intros; apply NemSet.class.\n\n    (** if *)\n    move => qv_m m S0 S1 rho. \n    by apply add_set_nem; apply IHn.\n\n    (** while *)\n    move => qv_m m S0 rho.\n    apply add_set_nem. by apply IHn. by apply NemSet.class.\n\n    (** sequence *)\n    move => S1 S2 rho.\n    apply bigU_nemP. apply forall_to_exists_nonempty.\n    rewrite mapR_eq_emP. by apply IHn.\n    move => //= A [] x [_ Hx]. rewrite -Hx. by apply IHn.\n\n    (** probability *)\n    move => p S1 S2 rho.\n    apply scalar_convex_combS_nemMixin; by apply IHn.\n\n    (** nondeterministic *)\n    move => S1 S2 rho.\n    apply union_nem_L. by apply IHn.\n\n    (** parallel *)\n    move => S1 S2 rho.\n    apply union_nem_L. by apply IHn.\nQed.\n\n\n\n(** Prove that [⟦ P , n ⟧ (rho_s)] is always nonempty. *)\n\nLemma deSemN_nemMixin {qs : QvarScope} (P : prog qs) (n : nat) \n    (rho_s : 𝒫(𝒟( qs )⁻)) (Hnem : NemSet.class_of rho_s) : \n        NemSet.class_of (⟦ P , n ⟧ (rho_s)).\nProof.\n    rewrite /NemSet.mixin_of /deSemN.\n    apply bigU_nemP. apply forall_to_exists_nonempty.\n    by rewrite mapR_eq_emP.\n    move => A [] x [_ Hx]. rewrite -Hx. by apply deSemN_point_nemMixin.\nQed.\n\nCanonical deSemN_nemType \n    {qs : QvarScope} (P : prog qs) (n : nat) (rho_s : 𝒫(𝒟( qs )⁻)₊) :=\n        NemSet _ (@deSemN_nemMixin _ P n _ (NemSet.class rho_s)).\n*)\n\n\nSection DeSemPointStep.\n\nVariable (qs : QvarScope) (rho : 𝒟( qs )⁻) (n : nat).\n\nLemma deSemN_seq_point_fun (S1 S2 : prog qs):\n\n    ⦗ S1 ; S2, n.+1 ⦘ = ⋃ ◦ ⦗ S2, n ⦘ [<] ◦ ⦗ S1, n ⦘.\n\nProof. by []. Qed.\n\nEnd DeSemPointStep.\n\n\n\nSection DeSemStep.\n\nVariable (qs : QvarScope) (rho_s : 𝒫(𝒟( qs )⁻)₊).\n(*\n\n\nLemma deSemN_skip n:\n\n            ⟦ Skip, n.+1 ⟧(rho_s) = rho_s.\n\nProof. \n    rewrite /deSemN /fun_comp /mapR //=.\n    by rewrite bigU_rei.\nQed.\n\n\n\nLemma deSemN_abort n:\n\n            ⟦ Abort, n ⟧(rho_s) = 𝕌.\n\nProof. \n    rewrite /deSemN /fun_comp /mapR //=.\n    case: n => //=.\n    rewrite bigU_sgt_nem => //. apply NemSet.class.\n    rewrite bigU_sgt_nem => //=. by apply NemSet.class.\nQed.\n\n\nLemma deSemN_init qv n:\n \n            ⟦ qv <-0 , n.+1 ⟧(rho_s) = (InitStt qv) [<] rho_s.\n\nProof. \n    rewrite /deSemN /fun_comp /mapR //=.\n    by rewrite bigU_fun_rei.\nQed.\n\n\nLemma deSemN_unitary qv U n:\n \n            ⟦ qv *= U , n.+1 ⟧(rho_s) = (Uapply U) [<] rho_s.\n\nProof. \n    rewrite /deSemN /mapR //=. \n    by apply bigU_fun_rei.\nQed.\nLemma deSemN_if qv_m m S0 S1 n:\n\n            ⟦ If m [[ qv_m ]] Then S0 Else S1 End, n.+1 ⟧ (rho_s) \n            = ( ⟦ S0 , n ⟧ ((Mapply m true) [<] rho_s)\n            + ⟦ S1 , n ⟧ ((Mapply m false) [<] rho_s) )%QTS.\n\nProof.\n\n    rewrite /deSemN /fun_comp /mapR //=. \n    \n\nAbort.\n\nLemma deSemN_while qv_m m S0 n:\n\n            ⟦ While m [[ qv_m ]] Do S0 End, n.+1 ⟧ (rho_s) \n            = ( ⟦ S0 ; While m [[ qv_m ]] Do S0 End, n ⟧ (MapplyS m true rho_s)\n            + MapplyS m false rho_s )%QTS.\n\nProof.\n    rewrite /deSemN //=.\nAbort.\n\nLemma deSemN_seq S0 S1 n:\n\n            ⟦ S0 ; S1, n.+1 ⟧ (rho_s) = ⟦ S1 , n ⟧ (⟦ S0, n ⟧ (rho_s)).\n\nProof.\n    equal_f_comp rho_s.\n    rewrite /deSemN deSemN_seq_point_fun.\n    \n    rewrite -[RHS]fun_assoc\n        [(⋃ ◦ ⦗ S1, n ⦘ [<]) ◦ ⋃] fun_assoc.\n    rewrite mapR_bigU_swapF.\n    rewrite -bigU_fun_distF.\n    rewrite -[⋃ ◦ ⦗ S1, n ⦘ [<] ◦ ⦗ S0, n ⦘]fun_assoc.\n    rewrite -double_mapRF.\n    by rewrite fun_assoc.\nQed.\n\nLemma deSemN_prob p S1 S2 n:\n\n        ⟦ S1 [p ⊕] S2, n.+1 ⟧(rho_s) \n        = (⟦ S1, n ⟧( rho_s )[ p ⊕ ] ⟦ S2, n ⟧( rho_s ))%QTS.\n\nProof.\nAbort.\n*)\n\nLemma deSemN_nondet S1 S2 n:\n        ⟦ S1 □ S2, n.+1 ⟧(rho_s) = ⟦ S1, n ⟧(rho_s) ∪ ⟦ S2, n ⟧(rho_s).\nProof.\n    rewrite /deSemN /mapR => //=.\n    by rewrite union_bigU_mapR_dist.\nQed.\n\nLemma deSemN_atom P n:\n        ⟦ <<P>>, n.+1 ⟧(rho_s) = ⟦ P, n ⟧(rho_s).\nProof. by []. Qed.\n\n\nLemma deSemN_parallel S1 S2 n:\n        ⟦ [ S1 // S2], n.+1 ⟧(rho_s) \n        =  (⟦ Step S1 S2 true, n ⟧(rho_s)) ∪ (⟦ Step S1 S2 false, n ⟧(rho_s)).\nProof.\n    rewrite /deSemN /mapR.\n    by rewrite union_bigU_mapR_dist.\nQed.\n\nEnd DeSemStep.\n\n\n\nLemma deSem0 (qs : QvarScope) P (rho_s : 𝒫(𝒟( qs )⁻)) :\n        \n        ⟦ P , 0 ⟧ (rho_s) = ∅.\n\nProof.\n    rewrite /deSemN /fun_comp /mapR //=.\n    case (em_classic rho_s).\n    move => ->. by apply bigU_sgt_em.\n    move => ?. by apply bigU_sgt_nem.\nQed.\n\n\nLemma deSem_em (qs : QvarScope) (P : prog qs) n :\n\n        ⟦ P , n ⟧ (∅) = ∅.\n\nProof.\n    rewrite /deSemN /fun_comp => //=.\n    rewrite mapR_em. by apply big_union_em.\nQed.\n    \n\n\nLemma deSemN_monotonicMixin {qs : QvarScope} (P : prog qs) (n : nat) :\n    MonotonicFun.mixin_of (⟦ P, n ⟧).\nProof.\n    rewrite /MonotonicFun.mixin_of => A B HAinB.\n\n    (** prove the special cases *)\n    case: n. by rewrite !deSem0.\n    move => n.\n    case: (em_classic A); case: (em_classic B).\n    move => -> ->. by rewrite deSem_em.\n    move => _ ->. by rewrite deSem_em.\n    move => HB HA. rewrite HB //= in HAinB. \n        rewrite /ord_op //= in HAinB.\n        rewrite subset_emP in HAinB. by destruct (HA HAinB).\n\n    move => HB HA.\n\n    rewrite /deSemN /fun_comp.\n\n    case P; rewrite /mapR //=; intros; apply bigU_mor_sub;\n    by apply mapR_mor_sub.\nQed.\n\nCanonical deSemN_monotonicfun {qs : QvarScope} (P : prog qs) (n : nat) :=\n    MonotonicFun _ (@deSemN_monotonicMixin qs P n).\n\n\nLemma deSemN_continuousMixin {qs : QvarScope} (P : prog qs) (n : nat) :\n    ContinuousFun.mixin_of (MonotonicFun.class (⟦ P, n ⟧)).\nProof.\n    rewrite /ContinuousFun.mixin_of //= => c.\n    rewrite /monotonic_mapR_chain  /CPO.join_op  //=.\n    rewrite /deSemN.\n    equal_f_comp c. \n    (** LHS *)\n    rewrite -fun_assoc.\n    rewrite [((⋃ ◦ ⦗ P, n ⦘ [<]) ◦ ⋃)]fun_assoc. \n    rewrite mapR_bigU_swapF.\n    (** RHS *)\n    rewrite -[in RHS]fun_assoc.\n    rewrite bigU_fun_distF.\n    by [].\nQed.\n\n\n\n(* The strong relation between opSemN and order *)\nLemma deSemN_point_monotonic_strong {qs : QvarScope} :\n    forall (S0 : prog qs) (rho : 𝒟( qs )⁻) n i, \n        (i <= n)%nat -> ⦗ S0, i ⦘ (rho) ⊆ ⦗ S0, n ⦘ (rho).\nProof.\n    move => S0 rho n.\n\n    (* induction on n *)\n    elim: n S0 rho.\n    (* induction basis, n = 0*)\n    move => S0 rho i. by rewrite leqn0 => /eqP ->.\n\n    (* induction step, process i=0 first *)\n    move => n IHn S0 rho i Hi. case: i Hi.\n    by move => _.\n\n    move => i Hi.\n    (* case on programs *)\n    case: S0.\n    (* skip abort, init, unitary *)\n    1,2,3,4: by intros.\n    (* if *)\n    move => qv_m m S0 S1. \n    by apply PDenSetOrder_add_split; apply /IHn.\n    (* while *)\n    move => qv_m m S0 /=. \n    apply PDenSetOrder_add_split; last first => //.\n    by apply IHn.\n    (* sequence *)\n    move => S1 S2 /=.\n    apply bigU_mapR_mor_sub.\n    by apply IHn.\n    move => t. by apply IHn.\n    (* probability *)\n    move => p S1 S2 /=.\n    apply PDensetOrder_cv_comb_split; by apply IHn.\n    (* nondet *)\n    move => S1 S2 /=.\n    apply PDenSetOrder_union_split; by apply IHn.\n    (* atom *)\n    move => S0 /=. by apply IHn => //.\n    (* parallel *)\n    move => S1 S2 /=. \n    apply PDenSetOrder_union_split; by apply IHn.\nQed.\n\nLemma deSemN_point_monotonic_step {qs : QvarScope} (P : prog qs) rho: \n    forall n, ⦗ P, n ⦘ (rho) ⊆ ⦗ P, n.+1 ⦘ (rho).\nProof. move => n. by apply deSemN_point_monotonic_strong. Qed.\nArguments deSemN_point_monotonic_step {qs} P rho.\n\n\n(* The strong relation between deSemN and order *)\nLemma deSemN_monotonic_strong {qs : QvarScope}:\n    forall (S0 : prog qs) (r1 r2 : 𝒫(𝒟( qs )⁻)) (n i : nat), \n        (i <= n)%nat -> r1 ⊆ r2 -> ⟦ S0, i ⟧ (r1) ⊆ ⟦ S0, n ⟧ (r2).\nProof. \n    rewrite /deSemN => S0 r1 r2 n i Hi Hr1r2.\n    apply bigU_mapR_mor_sub => // t.\n    by apply deSemN_point_monotonic_strong.\nQed.\n\n\nLemma deSemN_monotonic_rho {qs : QvarScope} :\n    forall (S0 : prog qs) (r1 r2 : 𝒫(𝒟( qs )⁻)) n, \n        r1 ⊆ r2 -> ⟦ S0, n ⟧ (r1) ⊆ ⟦ S0, n ⟧ (r2).\nProof.\n    move => S0 r1 r2 n.\n    by apply (@deSemN_monotonic_strong qs S0 r1 r2 n n).\nQed.\n\n\n\n(** Prove that [opSemN c i] is increasing when i increases. *)\nLemma deSemN_monotonic_N {qs : QvarScope} (P : prog qs) (rho_s : 𝒫(𝒟( qs )⁻)): \n    forall i n, (i <= n)%nat -> ⟦ P, i ⟧ (rho_s) ⊆ ⟦ P, n ⟧ (rho_s).\nProof. move => i n Hin. \n    by apply deSemN_monotonic_strong.\nQed.\n\nLemma deSemN_monotonic_step {qs : QvarScope} (P : prog qs) (rho_s : 𝒫(𝒟( qs )⁻)): \n    forall n, ⟦ P, n ⟧ (rho_s) ⊆ ⟦ P, n.+1 ⟧ (rho_s).\nProof. move => n. by apply deSemN_monotonic_strong. Qed.\nArguments deSemN_monotonic_step {qs} P rho_s.\n\n\n\n(** Construct the monotonic structure *)\nDefinition deSemN_n {qs : QvarScope} (P : prog qs) rho_s n := deSemN P n rho_s.\n\n\nLemma deSemN_n_monotonicMixin \n    {qs : QvarScope} (P : prog qs) (rho_s : 𝒫(𝒟( qs )⁻)) : \n    MonotonicFun.mixin_of (deSemN_n P rho_s).\nProof.\n    rewrite /MonotonicFun.mixin_of => x y Hxy.\n    rewrite /deSemN_n. apply deSemN_monotonic_N. apply /leP. by apply Hxy.\nDefined.\n\nCanonical deSemN_n_monotonic \n    {qs : QvarScope} (P : prog qs) (rho_s : 𝒫(𝒟( qs )⁻)) := \n    MonotonicFun _ (@deSemN_n_monotonicMixin _ P rho_s).\n\n\n(*\nLemma deSemN_n_continuousMixin\n    {qs : QvarScope} (P : prog qs) (rho_s : 𝒫(𝒟( qs )⁻)) : True.\n    ContinuousFun.mixin_of (MonotonicFun.class (deSemN_n P rho_s)).\n\n\n(** Define the operationa semantics (infinite step) *)\nDefinition chain_deSemN {qs : QvarScope} (P : prog qs) rho_s : chain 𝒟(qs)⁻ :=\n    mk_chain (deSemN_monotonic_step P rho_s).\n(** Note that these two chains are different.\n    One on step number, and another on ch index. *)\n\n\n\n(* TODO we can implement a general lemma for monotonic functions *)\nLemma chain_deSemN_n {qs : QvarScope} (P : prog qs) rho_s n :\n        chain_deSemN P rho_s _[n] = ⟦ P, n ⟧ (rho_s).\nProof. by []. Qed.\n*)\n\n\nDefinition DeSem \n    {qs : QvarScope} (P : prog qs) (rho_s : 𝒫(𝒟( qs )⁻)) : 𝒫(𝒟( qs )⁻) := \n        \n        ⊔ᶜˡ ((deSemN_n P rho_s) [<] 𝕌).\n\nNotation \" ⟦ P ⟧ \" := (@DeSem _ P) \n        (at level 10, format \"⟦  P  ⟧\"): QPP_scope.  \nNotation \" ⟦ P ⟧ ( rho_s ) \" := (@DeSem _ P rho_s) \n    (at level 10, format \"⟦  P  ⟧ ( rho_s )\"): QPP_scope.\n\nLemma DeSem_monotonicMixin {qs : QvarScope} (P : prog qs) : \n    MonotonicFun.mixin_of (⟦ P ⟧).\nProof.\n    rewrite /MonotonicFun.mixin_of //= => A B HAB.\n    rewrite !/DeSem /CLattice.join_op //=.\n    apply bigU_mapR_mor_sub => //=.\n    rewrite /deSemN_n => n.\n    by apply (MonotonicFun.class (⟦ P, n ⟧)).\nQed.\n\nCanonical DeSem_monotonicfun {qs : QvarScope} (P : prog qs) :=\n    MonotonicFun _ (@DeSem_monotonicMixin qs P).\n\n(* \n\nLemma DeSem_continuousMixin {qs : QvarScope} (P : prog qs) :\n    ContinuousFun.mixin_of (MonotonicFun.class (⟦ P ⟧)).\nProof.\n    rewrite /ContinuousFun.mixin_of /CPO.join_op //= => c.\n    rewrite /DeSem /CLattice.join_op //=. apply poset_antisym.\n    rewrite /mapR //=.\n    equal_f_comp c.\n    rewrite -fun_assoc.\n    rewrite \n\n\n\nLemma DeSem_ub : forall {qs : QvarScope} n (P : prog qs) rho_s, \n    ⟦ P, n ⟧ (rho_s) ⊑ ⟦ P ⟧ (rho_s).\nProof.\n    rewrite /DeSem => qs n P rho_s //=.\n    have t := CPO.join_prop (CPO.class _ ) [chain of ((deSemN_n P rho_s) [<] (𝕌))].\n    apply t => //=.\n    exists n. by split.\nQed.\nArguments DeSem_ub {qs} n P rho_s.\n\nLemma DeSem_lub : forall {qs : QvarScope} (P : prog qs) rho_s rho_ub, \n    (forall n, ⟦ P, n ⟧(rho_s) ⊑ rho_ub) -> ⟦ P ⟧ (rho_s) ⊑ rho_ub.\nProof.\n    rewrite /DeSem => qs P rho_s rho_ub H //=.\n    have t := CPO.join_prop (CPO.class _ ) [chain of ((deSemN_n P rho_s) [<] (𝕌))].\n    apply t => //=.\n\nQed.\n\nLemma DeSem_lubP : forall {qs : QvarScope} (P : prog qs) rho_s rho_ub, \n    (forall n, ⟦ P, n ⟧(rho_s) ⊑ rho_ub) <-> ⟦ P ⟧ (rho_s) ⊑ rho_ub.\nProof. split. by apply DeSem_lub.\n    move => HP n. transitivity (⟦ P ⟧ (rho_s)) => //. \n    by apply DeSem_ub.\nQed.\n*)\n\n(*##################################################################*)\n(* tactic *)\n\nLtac deSem_simpl_branch :=\n    (   rewrite /deSemN_n\n        || rewrite /deSemN\n    ) => //=.\n\n\nLtac deSem_move_up_branch := \n    match goal with\n    | H : _ = ⦗ _, _ ⦘(_) |- _ => clear H\n    | H : _ = ⟦ _, _ ⟧(_) |- _ => clear H\n    | n : nat |- _ ∈ ⦗ Skip , ?n ⦘(_) -> _ =>\n        generalize dependent n; case => //=\n    | n : nat |- _ ∈ ⦗ Abort , ?n ⦘(_) -> _ =>\n        generalize dependent n; case => //=\n    | n : nat |- _ ∈ ⦗ _ <- 0, ?n ⦘(_) -> _ =>\n        generalize dependent n; case => //=\n    | n : nat |- _ ∈ ⦗ _ *= _, ?n ⦘(_) -> _ =>\n        generalize dependent n; case => //=\n\n    | n : nat |- _ ∈ ⦗ If _ [[_]] Then _ Else _ End , ?n ⦘(_) -> _ =>\n        generalize dependent n; case => //=\n    \n    | n : nat |- _ ∈ ⦗ While _ [[_]] Do _ End , ?n ⦘(_) -> _ =>\n        generalize dependent n; case => //=\n\n    (** to avoid dead loop *)\n    | n : nat |- _ ∈ ⦗ _; While _ [[_]] Do _ End , ?n ⦘(_) -> _ => intros ?\n\n    | n : nat |- _ ∈ ⦗ _; _ , ?n ⦘(_) -> _ =>\n        generalize dependent n; case => //=\n\n    | n : nat |- _ ∈ ⦗ << _ >>, ?n ⦘(_) -> _ =>\n        generalize dependent n; case => //=\n\n    | n : nat |- _ ∈ ⦗ [_ // _], ?n ⦘(_) -> _ =>\n        generalize dependent n; case => //=\n        \n    end.\n\nLtac deSem_step\n        top_step\n        split_mode \n        general_apply_depth\n        eexists_mode\n        :=\n        match goal with\n        | _ => progress repeat deSem_simpl_branch\n        | _ => progress deSem_move_up_branch\n\n        | _ => set_step top_step split_mode general_apply_depth eexists_mode\n        end.\n    \nLtac deSem_step_sealed \n        split_mode\n        general_apply_depth\n        eexists_mode\n        :=\n    idtac; let rec top := deSem_step_sealed in \n        deSem_step top split_mode general_apply_depth eexists_mode.\n\nLtac deSem_killer := \n    all_move_down;\n    repeat deSem_step_sealed LAZY 100 LAZY.\n\n(*##################################################################*)\n\n\n\n(** Properties of Denotational Semantics *)\n\nLemma DeSem_skip {qs : QvarScope} (rho_s : 𝒫(𝒟( qs )⁻)₊):\n    ⟦ Skip ⟧ (rho_s) = rho_s.\nProof.\n    deSem_killer.\n    instantiate (1:=1%nat). deSem_killer. \n\n    (*\n    rewrite /DeSem /CLattice.join_op //=. apply poset_antisym.\n\n    apply bigU_lub => a [] i [] _ ->.\n    rewrite /deSemN_n /deSemN -fun_compP.\n    case: i.\n    (** n = 0 *)\n    rewrite /deSemN_point. rewrite /mapR.\n    rewrite bigU_sgt_nem //=. by apply NemSet.class.\n    (** n > 0 *)\n    rewrite /mapR //= => n. by rewrite bigU_rei.\n\n    apply bigU_ub => //=. exists 1%nat. split => //=.\n    rewrite /deSemN_n /deSemN /fun_comp /mapR //=.\n    by rewrite bigU_rei.\n    *)\nQed.\n\nLemma DeSem_abort {qs : QvarScope} (rho_s : 𝒫(𝒟( qs )⁻)₊):\n    ⟦ Abort ⟧ (rho_s) = 𝕌.\nProof.\n    deSem_killer.\n    instantiate (1:=1%nat). deSem_killer. \nQed.\n\nLemma DeSem_init {qs : QvarScope} qv (rho_s : 𝒫(𝒟( qs )⁻)₊):\n    ⟦ qv <- 0 ⟧ (rho_s) = (InitStt qv) [<] rho_s.\nProof.\n    deSem_killer.\n    instantiate (1:=1%nat). deSem_killer. \nQed.\n\nLemma DeSem_unitary {qs : QvarScope} qv U (rho_s : 𝒫(𝒟( qs )⁻)₊):\n    ⟦ qv *= U ⟧ (rho_s) = (Uapply U) [<] rho_s.\nProof.\n    deSem_killer.\n    instantiate (1:=1%nat). deSem_killer. \nQed.\n\n\n\n\nLemma DeSem_if {qs : QvarScope} qv_m m S0 S1 (rho_s : 𝒫(𝒟( qs )⁻)):\n    \n    ⟦ If m [[qv_m]] Then S0 Else S1 End ⟧ (rho_s) \n        = ⋃ ((fun rho => \n            (⟦ S0 ⟧ ({{ Mapply m true rho }}) + ⟦ S1 ⟧ ({{ Mapply m false rho}}))) [<] rho_s).\n\nProof.\n    deSem_killer. apply a0. apply a1.\n    instantiate(1:= (Nat.max x11 x5).+1). deSem_killer.\n    apply (set_belong_cut (⦗ S1, x5 ⦘((Mapply m false x1)))) => //.\n    apply deSemN_point_monotonic_strong. apply /leP. apply Nat.le_max_r.\n    apply (set_belong_cut (⦗ S0, x11 ⦘((Mapply m true x1)))) => //.\n    apply deSemN_point_monotonic_strong. apply /leP. apply Nat.le_max_l.\nQed.\n\n\nLemma DeSem_while {qs : QvarScope} qv_m m S0 (rho_s : 𝒫(𝒟( qs )⁻)):\n    ⟦ While m [[qv_m]] Do S0 End ⟧ (rho_s) \n        = ⋃ (( fun rho =>\n            ⟦ S0 ; While m [[qv_m]] Do S0 End ⟧ ({{ Mapply m true rho }}) \n            + {{ Mapply m false rho }}) [<] rho_s).\nProof.\n    deSem_killer.\n    apply a0.\n    instantiate(1 := x7.+1 ).\n    deSem_killer.\nQed.\n\nLemma DeSem_seq {qs : QvarScope} S1 S2 (rho_s : 𝒫(𝒟( qs )⁻)):\n    ⟦ S1 ; S2 ⟧ (rho_s) =  ⟦ S2 ⟧ ( ⟦ S1 ⟧ (rho_s) ).\nProof.\n    deSem_killer. apply a0.\n    instantiate(1 := (max x1 x5).+1). deSem_killer.\n    instantiate(1 := x3). \n    apply (set_belong_cut (⦗ S1, x5 ⦘(x7))) => //.\n    apply deSemN_point_monotonic_strong. apply /leP. apply Nat.le_max_r.\n    apply (set_belong_cut (⦗ S2, x1 ⦘(x3))) => //.\n    apply deSemN_point_monotonic_strong. apply /leP. apply Nat.le_max_l.\nQed.    \n\n\nLemma DeSem_atom {qs : QvarScope} P (rho_s : 𝒫(𝒟( qs )⁻)):\n    ⟦ <<P>> ⟧ (rho_s) =  ⟦ P ⟧ (rho_s).\nProof.\n    deSem_killer.\n    instantiate (1:=x1.+1).\n    deSem_killer.\nQed.\n\n\nLemma DeSem_para {qs : QvarScope} S1 S2 (rho_s : 𝒫(𝒟( qs )⁻)):\n    ⟦ [S1 // S2] ⟧ (rho_s) = \n        ⟦ Step S1 S2 true ⟧ (rho_s) ∪ ⟦ Step S1 S2 false ⟧ (rho_s).\nProof.\n    deSem_killer.\n    all : instantiate (1:=x1.+1); deSem_killer.\nQed.\n\n(*\n(** The chain of chain_deSemN_point *)\n\nDefinition deSemN_point_map_chain \n    {qs : QvarScope} (P : prog qs) ch n : chain (𝒫(𝒟(qs)⁻)) :=\n    fmap_chain (⦗ P, n ⦘) ch.\n\n\n(** The relation between three chains: \n    - bigU chain\n    - deSemN_point chain\n    - deSemN chain\n*)\n\nLemma deSem_chain_decompose \n    {qs : QvarScope} (P : prog qs) rho_s n :\n    deSemN_chain P rho_s n = bigU_chain (deSemN_point_map_chain P rho_s n).\nProof. \n    apply chain_eqP. apply functional_extensionality => i.\n    rewrite /deSemN_chain /deSemN_chain_obj {1}/chain_obj.\n    rewrite /bigU_chain /bigU_chain_obj {2}/chain_obj.\n    rewrite /deSemN_point_map_chain /fmap_chain /fmap_chain_obj {2}/chain_obj.\n    by [].\nQed.\n\n\n(*#########################################################################*)\n\n\n\n\n\n\n\n\n\n(** Here is some dirty work about empty set *)\nLemma lim_ch_em_ex_em (qs : QvarScope) (ch : chain qs) :\n    (lim→∞ (ch)) = ∅ -> exists i, ch _[i] = ∅.\nProof.\n    (** This is not true. *)\nAbort.\n\nLemma lim_ch_em_deSemN_point_em (qs : QvarScope) (S : prog qs) (ch : chain 𝒟(qs)⁻) n:\n    (lim→∞ (ch)) = ∅ -> (lim→∞ (deSemN_point_map_chain S ch n)) = ∅.\nAdmitted.\n\nLemma lim_ch_em_deSemN_em (qs : QvarScope) (S : prog qs) (ch : chain 𝒟(qs)⁻) n:\n    (lim→∞ (ch)) = ∅ -> (lim→∞ (deSemN_chain S ch n)) = ∅.\nProof.\n    move => Hem.\n    rewrite deSem_chain_decompose. rewrite -bigU_continuous. \n    rewrite lim_ch_em_deSemN_point_em //. by apply big_union_em.\nQed.\n\nLemma lim_ch_nem_chi_nem (qs : QvarScope) (ch : chain 𝒟( qs )⁻) i :\n    (lim→∞ (ch)) <> ∅ -> ch _[i] <> ∅.\nProof.\n    move => Hch. have Htemp := (@chain_limit_ub _ ch i).\n    move => Heq. apply /Hch /subset_emP. rewrite -Heq. apply Htemp.\nQed.\n\n\nTheorem deSem0_continuous (qs : QvarScope) (S : prog qs) (ch : chain 𝒟(qs)⁻):\n    ⟦ S, 0 ⟧ (lim→∞ (ch)) = lim→∞ (deSemN_chain S ch 0).\nProof.\n    case (em_classic (lim→∞ (ch))).\n    move => H. rewrite H deSem0_em. rewrite lim_ch_em_deSemN_em //.\n    move => H. rewrite deSem0_nem //. apply poset_antisym => //.\n    apply chain_limit_lub => i. \n    rewrite /deSemN_chain /deSemN_chain_obj {1}/chain_obj. \n    rewrite deSem0_nem //. by apply lim_ch_nem_chi_nem.\nQed.\n\n\nTheorem deSemN_point_continuous \n    (qs : QvarScope) (S : prog qs) (ch : chain 𝒟(qs)⁻) n:\n    ⦗ S, n ⦘ [<] (lim→∞ (ch)) = lim→∞ (deSemN_point_map_chain S ch n).\nProof. \n    apply fmap_continuous.\nQed.\n\n\n\n(** TODO #8 *)\nTheorem deSemN_continuous (qs : QvarScope) (S : prog qs) (ch : chain 𝒟(qs)⁻) n:\n        ⟦ S, n ⟧ (lim→∞ (ch)) = lim→∞ (deSemN_chain S ch n).\nProof.\n    rewrite /deSemN /fun_comp.\n    rewrite deSemN_point_continuous bigU_continuous.\n    by rewrite deSem_chain_decompose.\nQed.\n\n\n\n*)\nEnd QParallelProg.\n\n\n", "meta": {"author": "LucianoXu", "repo": "Project-Babel", "sha": "92a749468a5ab3f3acb5e0bcbf29800df90be651", "save_path": "github-repos/coq/LucianoXu-Project-Babel", "path": "github-repos/coq/LucianoXu-Project-Babel/Project-Babel-92a749468a5ab3f3acb5e0bcbf29800df90be651/Babel/QProg/Parallel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2467439580784916}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\nRequire Import Setoid.\nRequire Import ZArith.\nRequire Import Psatz.\n\n\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith. \n\nLocal Open Scope struct_scope.\n\nRequire Import FinProof.CommonProofs.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolClass.\nRequire Import depoolContract.SolidityNotations.\n\nRequire Import depoolContract.NewProofs.ProofHelpers.\nRequire Import depoolContract.DePoolFunc.\n\n(* Set Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100. *)\n\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\nRequire Import depoolContract.Lib.CommonCommon.\n\n(* Require Import MultiSigWallet.Proofs.tvmFunctionsProofs. *)\n\nImport DePoolSpec.LedgerClass.SolidityNotations. \n\nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope solidity_scope.\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\n\nRequire Import depoolContract.DePoolConsts.\nModule DePoolContract_Ф_updateRounds (dc : DePoolConstsTypesSig XTypesSig StateMonadSig).\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig dc.\nModule ProofHelpers := ProofHelpers dc.\n\nImport dc.\nImport ProofHelpers.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\nOpaque Z.eqb Z.add Z.sub Z.div Z.mul hmapLookup hmapInsert Z.ltb Z.geb Z.leb Z.gtb Z.modulo deleteListPair intInc hmapPush.\n \nOpaque  DePoolContract_Ф_updateRound2 RoundsBase_Ф_stakeSum ProxyBase_Ф__recoverStake (* RoundsBase_Ф_setRound0 *).\n\n(* Notation \"'->selfdestruct' a\" := (do a' ← a; ↓ selfdestruct a') (at level 20). *)\n\n(* Import TVMModel.LedgerClass. *)\n\nDefinition DePoolContract_Ф_updateRounds_tailer (Л_areElectionsStarted: XBool) \n                                                (Л_curValidatorHash Л_prevValidatorHash: XInteger) \n                                                (Л_validationStart Л_validationEnd Л_validatorsElectedFor:  XInteger) \n                                                      : LedgerT (XErrorValue (XValueValue True) XInteger) := \nIf! ( $ Л_areElectionsStarted !& \n\t (↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_vsetHashInElectionPhase ?!= $ Л_curValidatorHash) !& \n\t (↑17 D2! LocalState_ι_updateRounds_Л_round2 ^^ RoundsBase_ι_Round_ι_step ?== ξ$ RoundsBase_ι_RoundStepP_ι_Completed)) then { \n\n\t\t(↑↑11 U2! delete RoundsBase_ι_m_rounds [[ ↑17 D2! LocalState_ι_updateRounds_Л_round2 ^^ RoundsBase_ι_Round_ι_id ]]) >> \n\t\t(↑17 U1! LocalState_ι_updateRounds_Л_round2 := D2! LocalState_ι_updateRounds_Л_round1) >> \n\t\t(↑17 U1! LocalState_ι_updateRounds_Л_round1 := D2! LocalState_ι_updateRounds_Л_round0) >> \n    (↑17 U1! LocalState_ι_updateRounds_Л_round0 := D2! LocalState_ι_updateRounds_Л_roundPre0) >>  \n\t\t(↑↑17 U2! LocalState_ι_updateRounds_Л_roundPre0 := DePoolContract_Ф_generateRound () ) >> \n\n\t\t(↑↑17 U2! LocalState_ι_updateRounds_Л_round2 := DePoolContract_Ф_updateRound2 (! ↑17 D2! LocalState_ι_updateRounds_Л_round2 , \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  $ Л_prevValidatorHash , \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  $ Л_curValidatorHash , \n                                          $ Л_validationStart !) ) >> \n    If! ( !¬ (↑12 D2! DePoolContract_ι_m_poolClosed) ) then { \n      (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_supposedElectedAt := $ \tЛ_validationEnd) >> \n      (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_validatorsElectedFor := $ Л_validatorsElectedFor ) >> \n      ↑↑17 U2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_elector ??:= ConfigParamsBase_Ф_getElector () ; \n      (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_vsetHashInElectionPhase := $ Л_curValidatorHash) >> \ndeclareLocal {( _ :>: _ , _ :>: _ , _ :>: _ , Л_stakeHeldFor :>: XInteger32 )} ?:= ConfigParamsBase_Ф_roundTimeParams () ; \n      (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_stakeHeldFor := $ Л_stakeHeldFor) >> \n      (↑↑17 U2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_validatorStake := \n          RoundsBase_Ф_stakeSum (! D1! (↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_stakes) [[ ↑2 D2! ValidatorBase_ι_m_validatorWallet ]] !)) >> \n      declareLocal Л_isValidatorStakeOk :>: XBool := (↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_validatorStake) ?>= \n                     (↑12 D2! DePoolContract_ι_m_validatorAssurance)\t; \n      (If ( !¬ $ Л_isValidatorStakeOk ) then { \n        (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_step := ξ$ RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze) >> \n        (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_completionReason := ξ$ RoundsBase_ι_CompletionReasonP_ι_ValidatorStakeIsTooSmall) >> \n        (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_unfreeze := $ xInt0) \n      } else { \n        (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_step := ξ$ RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest) >> \n        (->emit StakeSigningRequested (!! ↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_supposedElectedAt , \n                        ↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_proxy  !!)) \n      }) }; \n\n      (If ( !¬ (↑12 D2! DePoolContract_ι_m_poolClosed) ) then { \n        (↑17 U1! LocalState_ι_updateRounds_Л_round0 ^^ RoundsBase_ι_Round_ι_step := ξ$ RoundsBase_ι_RoundStepP_ι_Pooling) \n      })  \n      \n      } ;        \n      ( RoundsBase_Ф_setRoundPre0 (! ↑17 D2! LocalState_ι_updateRounds_Л_roundPre0 !) ) >> \n      ( RoundsBase_Ф_setRound0 (! ↑17 D2! LocalState_ι_updateRounds_Л_round0 !) ) >> \n      ( RoundsBase_Ф_setRound1 (! ↑17 D2! LocalState_ι_updateRounds_Л_round1 !) ) >> \n      ( RoundsBase_Ф_setRound2 (! ↑17 D2! LocalState_ι_updateRounds_Л_round2 !) ) >> \nreturn! (xValue I) . \n \n\n\nDefinition DePoolContract_Ф_updateRounds_header  : LedgerT (XErrorValue (XValueValue True) XInteger) := \ndeclareLocal {( Л_validatorsElectedFor :>: XInteger32 , Л_electionsStartBefore :>: XInteger32 , _ :>: _ , _ :>: _ )} ??:= ConfigParamsBase_Ф_roundTimeParams () ; \ndeclareLocal {( Л_curValidatorHash :>: XInteger256 , Л_validationStart :>: XInteger32 , Л_validationEnd  :>: XInteger32 )} ??:= ConfigParamsBase_Ф_getCurValidatorData () ; \ndeclareLocal Л_prevValidatorHash  :>: XInteger256 ??:= ConfigParamsBase_Ф_getPrevValidatorHash () ; \ndeclareLocal Л_areElectionsStarted :>: XBool := ( tvm_now () ?>=  $ Л_validationEnd !- $ Л_electionsStartBefore ) ; \n( declareGlobal! LocalState_ι_updateRounds_Л_roundPre0 :>: RoundsBase_ι_Round := RoundsBase_Ф_getRoundPre0 () ) >> \n( declareGlobal! LocalState_ι_updateRounds_Л_round0 :>: RoundsBase_ι_Round := RoundsBase_Ф_getRound0 () ) >> \n( declareGlobal! LocalState_ι_updateRounds_Л_round1 :>: RoundsBase_ι_Round := RoundsBase_Ф_getRound1 () ) >> \n( declareGlobal! LocalState_ι_updateRounds_Л_round2 :>: RoundsBase_ι_Round := RoundsBase_Ф_getRound2 () ) >> \nIf2!! ((↑ε12 DePoolContract_ι_m_poolClosed ) !& \n(DePoolContract_Ф_isEmptyRound (! ↑17 D2! LocalState_ι_updateRounds_Л_round2 !) ) !& \n(DePoolContract_Ф_isEmptyRound (! ↑17 D2! LocalState_ι_updateRounds_Л_round1 !) ) !& \n(DePoolContract_Ф_isEmptyRound (! ↑17 D2! LocalState_ι_updateRounds_Л_round0 !) ) !& \n(DePoolContract_Ф_isEmptyRound (! ↑17 D2! LocalState_ι_updateRounds_Л_roundPre0 !))) then { \n  (->selfdestruct ( ↑2 D2! ValidatorBase_ι_m_validatorWallet ) ) >> \n  tvm_exit () \n};          \n(↑↑17 U2! LocalState_ι_updateRounds_Л_round2 := DePoolContract_Ф_updateRound2 (! ↑17 D2! LocalState_ι_updateRounds_Л_round2 , \n                                        $ Л_prevValidatorHash , \n                                        $ Л_curValidatorHash , \n                    $ Л_validationStart !) ) >> \nIf!! ( (↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_step ?== ξ$ RoundsBase_ι_RoundStepP_ι_WaitingValidationStart) !& \n(↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_vsetHashInElectionPhase ?== $ Л_prevValidatorHash)) then { \n\n(↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_step := ξ$ RoundsBase_ι_RoundStepP_ι_WaitingIfValidatorWinElections) >> \nProxyBase_Ф__recoverStake (! ↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_proxy , \n            ↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_id , \n            ↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_elector !) >> $ xValue I \n};  DePoolContract_Ф_updateRounds_tailer Л_areElectionsStarted Л_curValidatorHash Л_prevValidatorHash Л_validationStart Л_validationEnd Л_validatorsElectedFor.\n\n\nLemma DePoolContract_Ф_updateRounds_header_eq: DePoolContract_Ф_updateRounds_header = DePoolContract_Ф_updateRounds.\nProof.\n  auto.\nQed.\n\nOpaque DePoolContract_Ф_updateRounds_tailer.\n\n\nLemma DePoolContract_Ф_updateRounds_header_exec : forall (l: Ledger) ,                            \nlet ertp := eval_state ( ↓ ConfigParamsBase_Ф_roundTimeParams ) l in\nlet ret1 : bool := errorValueIsValue ertp in\nlet rtp := errorMapDefault Datatypes.id ertp (0,0,0,0) in \nlet electionsStartBefore := snd (fst ( fst rtp )) in\nlet validatorsElectedFor := fst (fst ( fst rtp )) in\n\nlet ecvd := eval_state ( ↓ ConfigParamsBase_Ф_getCurValidatorData ) l in\nlet ret2 : bool := errorValueIsValue ecvd in\nlet cvd := errorMapDefault Datatypes.id ecvd (0,0,0) in \nlet curValidatorHash := fst (fst cvd) in\nlet validationStart := snd (fst cvd) in\nlet validationEnd := snd cvd in\n\nlet epvh :=  eval_state ( ↓  ConfigParamsBase_Ф_getPrevValidatorHash ) l  in\nlet ret3 : bool := errorValueIsValue epvh in\nlet prevValidatorHash := errorMapDefault Datatypes.id epvh 0 in \n\nlet areElectionsStarted : bool := ( ( eval_state ( ↓ tvm_now ) l ) >=? ( validationEnd - electionsStartBefore ) ) in\nlet roundPre0 := eval_state ( ↓ RoundsBase_Ф_getRoundPre0 ) l in\nlet round0 := eval_state ( ↓ RoundsBase_Ф_getRound0 ) l in\nlet round1 := eval_state ( ↓ RoundsBase_Ф_getRound1 ) l in\nlet round2 := eval_state ( ↓ RoundsBase_Ф_getRound2 ) l in\nlet if1 : bool := ( ( eval_state ( ↑12 ε DePoolContract_ι_m_poolClosed ) l ) &&\n                    (( eval_state ( ↓     DePoolContract_Ф_isEmptyRound round2 ) l ) && \n                    (( eval_state ( ↓     DePoolContract_Ф_isEmptyRound round1 ) l ) && \n                    (( eval_state ( ↓     DePoolContract_Ф_isEmptyRound round0 ) l ) && \n                    ( eval_state ( ↓     DePoolContract_Ф_isEmptyRound roundPre0 ) l )))) )%bool in  \nlet m_validatorWallet := eval_state ( ↑2 ε ValidatorBase_ι_m_validatorWallet) l in                                       \nlet l' := {$ l With (LocalState_ι_updateRounds_Л_roundPre0, roundPre0) ;\n                         (LocalState_ι_updateRounds_Л_round0, round0) ; \n                         (LocalState_ι_updateRounds_Л_round1, round1) ;\n                         (LocalState_ι_updateRounds_Л_round2, round2) $} in\n\nlet (round2, newl) := run (↓ DePoolContract_Ф_updateRound2 round2 prevValidatorHash curValidatorHash validationStart) l'  in\nlet if2 : bool := ( ( eqb ( round1 ->> RoundsBase_ι_Round_ι_step ) RoundsBase_ι_RoundStepP_ι_WaitingValidationStart ) \n                   &&\n                  ( ( round1 ->> RoundsBase_ι_Round_ι_vsetHashInElectionPhase ) =? prevValidatorHash ) )%bool in\nlet round1 := if if2 then \n              {$ round1 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_WaitingIfValidatorWinElections ) $} \n              else round1 in \nlet newl' :=  {$ newl With (LocalState_ι_updateRounds_Л_round1, round1); (LocalState_ι_updateRounds_Л_round2, round2) $} in                   \nlet newl := if if2 then exec_state ( ↓ ProxyBase_Ф__recoverStake ( round1 ->> RoundsBase_ι_Round_ι_proxy )\n                                                               ( round1 ->> RoundsBase_ι_Round_ι_id )\n                                                               ( round1 ->> RoundsBase_ι_Round_ι_elector ) ) newl'\n                 else newl' in\n\nexec_state ( DePoolContract_Ф_updateRounds_header ) l = \nif ret1 then\n  if ret2 then \n    if ret3 then \n      if if1 then exec_state (↓ selfdestruct m_validatorWallet) l'\n      else exec_state (DePoolContract_Ф_updateRounds_tailer areElectionsStarted curValidatorHash prevValidatorHash validationStart validationEnd validatorsElectedFor) newl  \n    else l\n  else l\nelse l. \n\nProof.\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  case_eq DePoolContract_ι_m_poolClosed; intros. idtac.\n\n  all: repeat destructIf_solve2. idtac.\n  all: try destructFunction4 DePoolContract_Ф_updateRound2; auto. idtac.\n\n\n  all: try destructFunction1 selfdestruct; auto. idtac.\n        \n  all: repeat destructIf_solve2. \n\nQed.  \n\n\nLemma DePoolContract_Ф_updateRounds_header_eval : forall (l: Ledger) ,                            \nlet ertp := eval_state ( ↓ ConfigParamsBase_Ф_roundTimeParams ) l in\nlet ret1 : bool := errorValueIsValue ertp in\nlet rtp := errorMapDefault Datatypes.id ertp (0,0,0,0) in \nlet electionsStartBefore := snd (fst ( fst rtp )) in\nlet validatorsElectedFor := fst (fst ( fst rtp )) in\n\nlet ecvd := eval_state ( ↓ ConfigParamsBase_Ф_getCurValidatorData ) l in\nlet ret2 : bool := errorValueIsValue ecvd in\nlet cvd := errorMapDefault Datatypes.id ecvd (0,0,0) in \nlet curValidatorHash := fst (fst cvd) in\nlet validationStart := snd (fst cvd) in\nlet validationEnd := snd cvd in\n\nlet epvh :=  eval_state ( ↓  ConfigParamsBase_Ф_getPrevValidatorHash ) l  in\nlet ret3 : bool := errorValueIsValue epvh in\nlet prevValidatorHash := errorMapDefault Datatypes.id epvh 0 in \n\nlet areElectionsStarted : bool := ( ( eval_state ( ↓ tvm_now ) l ) >=? ( validationEnd - electionsStartBefore ) ) in\nlet roundPre0 := eval_state ( ↓ RoundsBase_Ф_getRoundPre0 ) l in\nlet round0 := eval_state ( ↓ RoundsBase_Ф_getRound0 ) l in\nlet round1 := eval_state ( ↓ RoundsBase_Ф_getRound1 ) l in\nlet round2 := eval_state ( ↓ RoundsBase_Ф_getRound2 ) l in\nlet if1 : bool := ( ( eval_state ( ↑12 ε DePoolContract_ι_m_poolClosed ) l ) &&\n                    (( eval_state ( ↓     DePoolContract_Ф_isEmptyRound round2 ) l ) && \n                    (( eval_state ( ↓     DePoolContract_Ф_isEmptyRound round1 ) l ) && \n                    (( eval_state ( ↓     DePoolContract_Ф_isEmptyRound round0 ) l ) && \n                    ( eval_state ( ↓     DePoolContract_Ф_isEmptyRound roundPre0 ) l )))) )%bool in  \nlet m_validatorWallet := eval_state ( ↑2 ε ValidatorBase_ι_m_validatorWallet) l in                                       \nlet l' := {$ l With (LocalState_ι_updateRounds_Л_roundPre0, roundPre0) ;\n                         (LocalState_ι_updateRounds_Л_round0, round0) ; \n                         (LocalState_ι_updateRounds_Л_round1, round1) ;\n                         (LocalState_ι_updateRounds_Л_round2, round2) $} in\n\nlet (round2, newl) := run (↓ DePoolContract_Ф_updateRound2 round2 prevValidatorHash curValidatorHash validationStart) l'  in\nlet if2 : bool := ( ( eqb ( round1 ->> RoundsBase_ι_Round_ι_step ) RoundsBase_ι_RoundStepP_ι_WaitingValidationStart ) \n                   &&\n                  ( ( round1 ->> RoundsBase_ι_Round_ι_vsetHashInElectionPhase ) =? prevValidatorHash ) )%bool in\nlet round1 := if if2 then \n              {$ round1 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_WaitingIfValidatorWinElections ) $} \n              else round1 in \nlet newl' :=  {$ newl With (LocalState_ι_updateRounds_Л_round1, round1); (LocalState_ι_updateRounds_Л_round2, round2) $} in                   \nlet newl := if if2 then exec_state ( ↓ ProxyBase_Ф__recoverStake ( round1 ->> RoundsBase_ι_Round_ι_proxy )\n                                                               ( round1 ->> RoundsBase_ι_Round_ι_id )\n                                                               ( round1 ->> RoundsBase_ι_Round_ι_elector ) ) newl'\n                 else newl' in\n\neval_state ( DePoolContract_Ф_updateRounds_header  ) l = \n(* if ret1 then\n  if ret2 then \n    if ret3 then  *)\n      if if1 then Value (Error I)\n      else eval_state (DePoolContract_Ф_updateRounds_tailer areElectionsStarted curValidatorHash prevValidatorHash validationStart validationEnd validatorsElectedFor) newl  .\n(*     else l\n  else l\nelse l *)\n\nProof.\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  case_eq DePoolContract_ι_m_poolClosed; intros. idtac.\n\n  all: repeat destructIf_solve2. idtac.\n  all: try destructFunction4 DePoolContract_Ф_updateRound2; auto. idtac.\n  all: try destructFunction1 selfdestruct; auto. idtac.\n        \n  all: repeat destructIf_solve2. \n\nQed.  \n\nDefinition DePoolContract_Ф_updateRounds_tailer3 (Л_validationEnd Л_validatorsElectedFor Л_curValidatorHash: XInteger) : LedgerT (XErrorValue True XInteger):=\n  (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_supposedElectedAt := $ \tЛ_validationEnd) >> \n  (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_validatorsElectedFor := $ Л_validatorsElectedFor ) >> \n  ↑↑17 U2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_elector ??:= ConfigParamsBase_Ф_getElector () ; \n  (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_vsetHashInElectionPhase := $ Л_curValidatorHash) >> \ndeclareLocal {( _ :>: _ , _ :>: _ , _ :>: _ , Л_stakeHeldFor :>: XInteger32 )} ?:= ConfigParamsBase_Ф_roundTimeParams () ; \n  (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_stakeHeldFor := $ Л_stakeHeldFor) >> \n  (↑↑17 U2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_validatorStake := \n      RoundsBase_Ф_stakeSum (! D1! (↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_stakes) [[ ↑2 D2! ValidatorBase_ι_m_validatorWallet ]] !)) >> \n  declareLocal Л_isValidatorStakeOk :>: XBool := (↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_validatorStake) ?>= \n                 (↑12 D2! DePoolContract_ι_m_validatorAssurance)\t; \n  (If ( !¬ $ Л_isValidatorStakeOk ) then { \n    (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_step := ξ$ RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze) >> \n    (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_completionReason := ξ$ RoundsBase_ι_CompletionReasonP_ι_ValidatorStakeIsTooSmall) >> \n    (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_unfreeze := $ xInt0) \n  } else { \n    (↑17 U1! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_step := ξ$ RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest) >> \n    (->emit StakeSigningRequested (!! ↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_supposedElectedAt , \n                    ↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_proxy  !!)) \n  }).\n\nDefinition DePoolContract_Ф_updateRounds_tailer2 (Л_areElectionsStarted: XBool) \n                                                (Л_curValidatorHash Л_prevValidatorHash: XInteger) \n                                                (Л_validationStart Л_validationEnd Л_validatorsElectedFor: XInteger) \n                                              \n                                                      : LedgerT (XErrorValue (XValueValue True) XInteger) := \nIf! ( $ Л_areElectionsStarted !& \n\t (↑17 D2! LocalState_ι_updateRounds_Л_round1 ^^ RoundsBase_ι_Round_ι_vsetHashInElectionPhase ?!= $ Л_curValidatorHash) !& \n\t (↑17 D2! LocalState_ι_updateRounds_Л_round2 ^^ RoundsBase_ι_Round_ι_step ?== ξ$ RoundsBase_ι_RoundStepP_ι_Completed)) then { \n\n\t\t(↑↑11 U2! delete RoundsBase_ι_m_rounds [[ ↑17 D2! LocalState_ι_updateRounds_Л_round2 ^^ RoundsBase_ι_Round_ι_id ]]) >> \n\t\t(↑17 U1! LocalState_ι_updateRounds_Л_round2 := D2! LocalState_ι_updateRounds_Л_round1) >> \n\t\t(↑17 U1! LocalState_ι_updateRounds_Л_round1 := D2! LocalState_ι_updateRounds_Л_round0) >> \n    (↑17 U1! LocalState_ι_updateRounds_Л_round0 := D2! LocalState_ι_updateRounds_Л_roundPre0) >>  \n\t\t(↑↑17 U2! LocalState_ι_updateRounds_Л_roundPre0 := DePoolContract_Ф_generateRound () ) >> \n\n\t\t(↑↑17 U2! LocalState_ι_updateRounds_Л_round2 := DePoolContract_Ф_updateRound2 (! ↑17 D2! LocalState_ι_updateRounds_Л_round2 , \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  $ Л_prevValidatorHash , \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  $ Л_curValidatorHash , \n                                          $ Л_validationStart !) ) >> \n    If! ( !¬ (↑12 D2! DePoolContract_ι_m_poolClosed) ) then { \n      DePoolContract_Ф_updateRounds_tailer3 Л_validationEnd Л_validatorsElectedFor Л_curValidatorHash\n       }; \n\n      (If ( !¬ (↑12 D2! DePoolContract_ι_m_poolClosed) ) then { \n        (↑17 U1! LocalState_ι_updateRounds_Л_round0 ^^ RoundsBase_ι_Round_ι_step := ξ$ RoundsBase_ι_RoundStepP_ι_Pooling) \n      })  \n      \n      } ;        \n      ( RoundsBase_Ф_setRoundPre0 (! ↑17 D2! LocalState_ι_updateRounds_Л_roundPre0 !) ) >> \n      ( RoundsBase_Ф_setRound0 (! ↑17 D2! LocalState_ι_updateRounds_Л_round0 !) ) >> \n      ( RoundsBase_Ф_setRound1 (! ↑17 D2! LocalState_ι_updateRounds_Л_round1 !) ) >> \n      ( RoundsBase_Ф_setRound2 (! ↑17 D2! LocalState_ι_updateRounds_Л_round2 !) ) >> \nreturn! (xValue I) .\n\n\n\n\n(* Transparent RoundsBase_Ф_stakeSum. *)\n\n(* Transparent RoundsBase_Ф_setRound0. *)\n\nOpaque DePoolContract_Ф_updateRounds_tailer3.\n\nLemma  DePoolContract_Ф_updateRounds_tailer2_exec  (areElectionsStarted: XBool) \n                                                  (curValidatorHash prevValidatorHash: XInteger) \n                                                  (validationStart validationEnd validatorsElectedFor:  XInteger)  (l: Ledger):\nlet _roundPre0 := eval_state ( ↑17 ε LocalState_ι_updateRounds_Л_roundPre0 ) l in\nlet _round0 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round0 ) l in\nlet _round1 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round1) l in\nlet _round2 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round2 ) l in\n\nlet if3 : bool :=  (areElectionsStarted && \n         (( negb ( ( _round1 ->> RoundsBase_ι_Round_ι_vsetHashInElectionPhase ) =? curValidatorHash ) ) && \n         (  ( eqb ( _round2 ->> RoundsBase_ι_Round_ι_step ) RoundsBase_ι_RoundStepP_ι_Completed ) )) )%bool in\n        \nlet newl :=   {$ l With RoundsBase_ι_m_rounds := \n               ( eval_state ( ↑11 ε RoundsBase_ι_m_rounds ) l ) ->delete ( _round2 ->> RoundsBase_ι_Round_ι_id ) $}\n               in  \nlet round2 := _round1 in\nlet round1 := _round0 in\nlet round0 := _roundPre0  in\nlet (roundPre0, newl) :=  run ( ↓ DePoolContract_Ф_generateRound ) newl in\n\nlet newl' := {$ newl With (LocalState_ι_updateRounds_Л_roundPre0, roundPre0) ;\n                         (LocalState_ι_updateRounds_Л_round0, round0) ; \n                         (LocalState_ι_updateRounds_Л_round1, round1) ;\n                         (LocalState_ι_updateRounds_Л_round2, round2) $} in\n\nlet (round2, newl) := run ( ↓ DePoolContract_Ф_updateRound2 round2 prevValidatorHash curValidatorHash validationStart ) newl' in\nlet newl := {$ newl With (LocalState_ι_updateRounds_Л_round2, round2) $} in\n\nlet l2 := newl in \n\nlet if4  : bool := negb ( eval_state (↑12 ε DePoolContract_ι_m_poolClosed) newl )  in \n\nlet (r, newl) := if if4 then run (DePoolContract_Ф_updateRounds_tailer3 validationEnd validatorsElectedFor curValidatorHash) newl else (Value I, newl) in\nlet ml := newl in\n\nlet roundPre0 := eval_state ( ↑17 ε LocalState_ι_updateRounds_Л_roundPre0 ) ml in\nlet round0 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round0 ) ml in\nlet round1 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round1) ml in\nlet round2 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round2 ) ml in\n\nlet if5 : bool := negb ( eval_state (↑12 ε DePoolContract_ι_m_poolClosed) newl )  in  \nlet round0 := if if5 then {$ round0 with ( RoundsBase_ι_Round_ι_step , RoundsBase_ι_RoundStepP_ι_Pooling  ) $} \n                     else round0 in   \nlet newl := {$ newl With (LocalState_ι_updateRounds_Л_round0, round0) $} in             \n\nlet lsetPre0 := exec_state ( ↓ RoundsBase_Ф_setRoundPre0 roundPre0 ) newl in\nlet lset0 := exec_state ( ↓ RoundsBase_Ф_setRound0 round0 ) lsetPre0 in\nlet lset1 := exec_state ( ↓ RoundsBase_Ф_setRound1 round1 ) lset0 in\nlet lset2 := exec_state ( ↓ RoundsBase_Ф_setRound2 round2 ) lset1 in \n\nlet lsetPre0' := exec_state ( ↓ RoundsBase_Ф_setRoundPre0 _roundPre0 ) l in\nlet lset0' := exec_state ( ↓ RoundsBase_Ф_setRound0 _round0 ) lsetPre0' in\nlet lset1' := exec_state ( ↓ RoundsBase_Ф_setRound1 _round1 ) lset0' in\nlet lset2' := exec_state ( ↓ RoundsBase_Ф_setRound2 _round2 ) lset1' in \n\nexec_state ( DePoolContract_Ф_updateRounds_tailer2 areElectionsStarted curValidatorHash prevValidatorHash\n                              validationStart validationEnd validatorsElectedFor ) l = \n(* if ret1 then\n  if ret2 then \n    if ret3 then  *)\n     if if3 then\n        if if4 then  \n            if (errorValueIsValue r) then lset2\n            else ml\n        else lset2\n     else lset2'.\n\nProof.\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n\n  all: repeat destructIf_solve2. idtac.\n  all: try destructFunction4 DePoolContract_Ф_updateRound2; auto. idtac.\n  all: repeat destructIf_solve2. idtac.\n  all: try destructFunction3 DePoolContract_Ф_updateRounds_tailer3; auto. idtac.\n  case_eq x0; intros; auto. idtac.\n  all: repeat destructIf_solve2. idtac.\n\n  Require Import depoolContract.Lib.CommonStateProofs.\n  apply ledgerEq; auto. idtac.\n  simpl. idtac.\n  destructLedger l0; auto. \nQed. \n\n\n\nLemma  DePoolContract_Ф_updateRounds_tailer2_eval  (areElectionsStarted: XBool) \n                                                  (curValidatorHash prevValidatorHash: XInteger) \n                                                  (validationStart validationEnd validatorsElectedFor:  XInteger) (l: Ledger):\nlet _roundPre0 := eval_state ( ↑17 ε LocalState_ι_updateRounds_Л_roundPre0 ) l in\nlet _round0 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round0 ) l in\nlet _round1 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round1) l in\nlet _round2 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round2 ) l in\n\nlet if3 : bool :=  (areElectionsStarted && \n         (( negb ( ( _round1 ->> RoundsBase_ι_Round_ι_vsetHashInElectionPhase ) =? curValidatorHash ) ) && \n         (  ( eqb ( _round2 ->> RoundsBase_ι_Round_ι_step ) RoundsBase_ι_RoundStepP_ι_Completed ) )) )%bool in\n        \nlet newl :=   {$ l With RoundsBase_ι_m_rounds := \n               ( eval_state ( ↑11 ε RoundsBase_ι_m_rounds ) l ) ->delete ( _round2 ->> RoundsBase_ι_Round_ι_id ) $}\n               in  \nlet round2 := _round1 in\nlet round1 := _round0 in\nlet round0 := _roundPre0  in\nlet (roundPre0, newl) :=  run ( ↓ DePoolContract_Ф_generateRound ) newl in\n\nlet newl' := {$ newl With (LocalState_ι_updateRounds_Л_roundPre0, roundPre0) ;\n                         (LocalState_ι_updateRounds_Л_round0, round0) ; \n                         (LocalState_ι_updateRounds_Л_round1, round1) ;\n                         (LocalState_ι_updateRounds_Л_round2, round2) $} in\n\nlet (round2, newl) := run ( ↓ DePoolContract_Ф_updateRound2 round2 prevValidatorHash curValidatorHash validationStart ) newl' in\nlet newl := {$ newl With (LocalState_ι_updateRounds_Л_round2, round2) $} in\n\nlet l2 := newl in \n\nlet if4  : bool := negb ( eval_state (↑12 ε DePoolContract_ι_m_poolClosed) newl )  in \n\nlet (r, newl) := if if4 then run (DePoolContract_Ф_updateRounds_tailer3 validationEnd validatorsElectedFor curValidatorHash) newl else (Value I, newl) in\nlet ml := newl in\n\nlet roundPre0 := eval_state ( ↑17 ε LocalState_ι_updateRounds_Л_roundPre0 ) ml in\nlet round0 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round0 ) ml in\nlet round1 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round1) ml in\nlet round2 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round2 ) ml in\n\nlet if5 : bool := negb ( eval_state (↑12 ε DePoolContract_ι_m_poolClosed) newl )  in  \nlet round0 := if if5 then {$ round0 with ( RoundsBase_ι_Round_ι_step , RoundsBase_ι_RoundStepP_ι_Pooling  ) $} \n                     else round0 in   \nlet newl := {$ newl With (LocalState_ι_updateRounds_Л_round0, round0) $} in             \n\nlet lsetPre0 := exec_state ( ↓ RoundsBase_Ф_setRoundPre0 roundPre0 ) newl in\nlet lset0 := exec_state ( ↓ RoundsBase_Ф_setRound0 round0 ) lsetPre0 in\nlet lset1 := exec_state ( ↓ RoundsBase_Ф_setRound1 round1 ) lset0 in\nlet lset2 := exec_state ( ↓ RoundsBase_Ф_setRound2 round2 ) lset1 in \n\nlet lsetPre0' := exec_state ( ↓ RoundsBase_Ф_setRoundPre0 _roundPre0 ) l in\nlet lset0' := exec_state ( ↓ RoundsBase_Ф_setRound0 _round0 ) lsetPre0' in\nlet lset1' := exec_state ( ↓ RoundsBase_Ф_setRound1 _round1 ) lset0' in\nlet lset2' := exec_state ( ↓ RoundsBase_Ф_setRound2 _round2 ) lset1' in \n\neval_state ( DePoolContract_Ф_updateRounds_tailer2 areElectionsStarted curValidatorHash prevValidatorHash\n                              validationStart validationEnd validatorsElectedFor ) l = \n(* if ret1 then\n  if ret2 then \n    if ret3 then  *)\n     if if3 then\n        if if4 then  \n            if (errorValueIsValue r) then Value (Value I)\n            else errorMapDefaultF (fun _ => Value (Value I)) r (fun e => Error e)\n        else Value (Value I)\n     else Value (Value I).\n\nProof.\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n\n  all: repeat destructIf_solve2. idtac.\n  all: try destructFunction4 DePoolContract_Ф_updateRound2; auto. idtac.\n  all: repeat destructIf_solve2. idtac.\n  all: try destructFunction3 DePoolContract_Ф_updateRounds_tailer3; auto. idtac.\n  case_eq x0; intros; auto. idtac.\n  all: repeat destructIf_solve2. \nQed.\n\n\nTransparent DePoolContract_Ф_updateRounds_tailer3.\n\nLemma DePoolContract_Ф_updateRounds_tailer3_exec : forall (validationEnd validatorsElectedFor curValidatorHash: XInteger) (l: Ledger) ,                            \n\nlet round1 := eval_state (  ↑17 ε LocalState_ι_updateRounds_Л_round1) l in\n\nlet eelector := eval_state ( ↓ ConfigParamsBase_Ф_getElector ) l in \nlet ret4 : bool := errorValueIsValue eelector in\nlet elector := errorMapDefault Datatypes.id eelector 0 in \n\nlet ertp := eval_state ( ↓ ConfigParamsBase_Ф_roundTimeParams ) l in\nlet ret5 : bool := errorValueIsValue ertp in\nlet rtp := errorMapDefault Datatypes.id ertp (0,0,0,0) in \nlet stakeHeldFor := snd rtp in \n\nlet round1 :=  {$ round1 with ( RoundsBase_ι_Round_ι_supposedElectedAt , validationEnd) ;\n                                   ( RoundsBase_ι_Round_ι_validatorsElectedFor , validatorsElectedFor ) ;\n                                   ( RoundsBase_ι_Round_ι_elector , elector) ;\n                                   ( RoundsBase_ι_Round_ι_vsetHashInElectionPhase , curValidatorHash) ;\n                                   ( RoundsBase_ι_Round_ι_stakeHeldFor , stakeHeldFor) $} in\n\nlet newl := {$l With (LocalState_ι_updateRounds_Л_round1, round1) $} in\nlet m_validatorWallet := eval_state ( ↑2 ε ValidatorBase_ι_m_validatorWallet) newl in\nlet (stakeSum, newl) :=  run (↓ RoundsBase_Ф_stakeSum\n               ( ( round1 ->> RoundsBase_ι_Round_ι_stakes ) [m_validatorWallet])) newl  in \nlet round1 :=  {$ round1 with ( RoundsBase_ι_Round_ι_validatorStake , stakeSum) $} in\n\nlet m_validatorAssurance := eval_state ( ↑12 ε DePoolContract_ι_m_validatorAssurance) newl in\nlet isValidatorStakeOk := round1 ->> RoundsBase_ι_Round_ι_validatorStake  >=? m_validatorAssurance in\n\n\nlet round1 := if negb isValidatorStakeOk  then \n{$ round1 with  ( RoundsBase_ι_Round_ι_step , RoundsBase_ι_RoundStepP_ι_WaitingUnfreeze  ) ;\n                ( RoundsBase_ι_Round_ι_completionReason  , RoundsBase_ι_CompletionReasonP_ι_ValidatorStakeIsTooSmall) ;                 \n                ( RoundsBase_ι_Round_ι_unfreeze , 0)  $}\n                                   else\n{$ round1 with ( RoundsBase_ι_Round_ι_step , RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest) $}  in\n\nlet oldEvents := eval_state ( ↑16 ε VMState_ι_events ) newl in \nlet newEvent : LedgerEvent :=  StakeSigningRequested ( round1 ->> RoundsBase_ι_Round_ι_supposedElectedAt )\n                                        ( round1 ->> RoundsBase_ι_Round_ι_proxy ) in\nlet newl := if negb isValidatorStakeOk  then newl else \n             {$ newl With VMState_ι_events := newEvent :: oldEvents  $} in\n\nexec_state ( DePoolContract_Ф_updateRounds_tailer3 validationEnd validatorsElectedFor curValidatorHash) l =\n       {$newl With (LocalState_ι_updateRounds_Л_round1, round1) $}.  \nProof.\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  repeat destructIf_solve2. idtac.           \n  destructFunction1 RoundsBase_Ф_stakeSum; auto. idtac.              \n  repeat destructIf_solve2. \n  \nQed.  \n\n\nLemma DePoolContract_Ф_updateRounds_tailer3_eval : forall (validationEnd validatorsElectedFor curValidatorHash: XInteger) (l: Ledger) ,                            \neval_state ( DePoolContract_Ф_updateRounds_tailer3 validationEnd validatorsElectedFor curValidatorHash) l = Value I.\n       \nProof.\n  intros.\n  destructLedger l. \n  compute. idtac.\n\n  repeat destructIf_solve2. idtac.           \n  destructFunction1 RoundsBase_Ф_stakeSum; auto. idtac.              \n  repeat destructIf_solve2. \n  \nQed.  \n\nLemma DePoolContract_Ф_updateRounds_tailer_eq: DePoolContract_Ф_updateRounds_tailer = DePoolContract_Ф_updateRounds_tailer2.\nProof.\n  auto.\nQed.\n\n\nEnd DePoolContract_Ф_updateRounds.", "meta": {"author": "Pruvendo", "repo": "depool_contract", "sha": "6afe23011d62f65921ac2493df691ab888ffeb95", "save_path": "github-repos/coq/Pruvendo-depool_contract", "path": "github-repos/coq/Pruvendo-depool_contract/depool_contract-6afe23011d62f65921ac2493df691ab888ffeb95/src/NewProofs/DePoolContract_updateRounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2467439580784916}}
{"text": "Require Import RamifyCoq.msl_ext.iter_sepcon.\nRequire Import RamifyCoq.msl_application.Graph.\nRequire Import RamifyCoq.msl_application.GList.\nRequire Import VST.veric.SeparationLogic.\nRequire Import RamifyCoq.sample_mark.env_unionfind_iter.\nRequire Import RamifyCoq.floyd_ext.share.\n\nLocal Open Scope logic.\n\nSection pSGG_VST.\n\nInstance PointerVal_EqDec: EquivDec.EqDec pointer_val eq.\n  hnf; intros.\n  apply PV_eq_dec.\nDefined.\n\nInstance PointerValE_EqDec: EquivDec.EqDec (pointer_val * unit) eq.\n  hnf; intros. destruct x, y. \n  destruct u, u0. destruct (PV_eq_dec p p0); [left | right]; congruence.\nDefined.\n\nInstance SGBA_VST: PointwiseGraphBasicAssum pointer_val (pointer_val * unit).\n  refine (Build_PointwiseGraphBasicAssum pointer_val (pointer_val * unit) _ _).\nDefined.\n\nEnd pSGG_VST.\n\nInstance pSGG_VST: pPointwiseGraph_GList.\n  refine (Build_pPointwiseGraph_GList pointer_val NullPointer SGBA_VST).\nDefined.\n\nDefinition vgamma2cdata (rpa : nat * addr) : reptype node_type :=\n  match rpa with\n  | (r, pa) => (Vint (Int.repr (Z.of_nat r)), pointer_val_val pa)\n  end.\n\nSection sSGG_VST.\n\n  Definition binode (sh: share) (p: addr) (rpa: nat * addr): mpred :=\n    data_at sh node_type (vgamma2cdata rpa) (pointer_val_val p).\n\n  Instance SGP_VST (sh: share) : PointwiseGraphPred addr (addr * unit) (nat * addr) unit mpred.\n  refine (Build_PointwiseGraphPred _ _ _ _ _ (binode sh) (fun _ _ => emp)).\n  Defined.\n\n  (*\n  Instance MSLstandard sh : MapstoSepLog (AAV (SGP_VST sh)) (binode sh).\n  Proof.\n    intros. apply mkMapstoSepLog. intros.\n    apply derives_precise with (memory_block sh (sizeof node_type) (pointer_val_val p)); [| apply memory_block_precise].\n    apply exp_left; intros [? ?]. unfold binode. apply data_at_memory_block.\n  Defined.\n   *)\n\n  Lemma sepcon_unique_vertex_at sh: writable_share sh -> sepcon_unique2 (@vertex_at _ _ _ _ _ (SGP_VST sh)).\n  Proof.\n    intros. hnf; intros. simpl.\n    destruct y1 as [? ?], y2 as [? ?].\n    unfold binode.\n    rewrite data_at_isptr.\n    normalize.\n    apply data_at_conflict.\n    + apply readable_nonidentity, writable_readable. auto.\n    + change (sizeof node_type) with 8. omega.\n  Qed.\n\nInstance SGA_VST (sh: share) : PointwiseGraphAssum (SGP_VST sh).\n  refine (Build_PointwiseGraphAssum _ _ _ _ _ _ _ _ _ _ _).\nDefined.\n\nInstance SGAvs_VST (sh: wshare): PointwiseGraphAssum_vs (SGP_VST sh).\n  apply sepcon_unique_vertex_at; auto.\nDefined.\n\nInstance SGAvn_VST (sh: wshare): PointwiseGraphAssum_vn (SGP_VST sh) NullPointer.\n  intros [? ?].\n  simpl.\n  unfold binode.\n  rewrite data_at_isptr.\n  normalize.\nDefined.\n\nEnd sSGG_VST.\n\nHint Extern 10 (@sepcon_unique2 _ _ _ _ _ (@vertex_at _ _ _ _ _ _)) => apply sepcon_unique_vertex_at; auto.\n\nInstance sSGG_VST (sh: wshare): @sPointwiseGraph_GList pSGG_VST nat unit.\n  refine (Build_sPointwiseGraph_GList pSGG_VST _ _ _ (SGP_VST sh) (SGA_VST sh) (SGAvs_VST sh) (SGAvn_VST sh)).\nDefined.\n\nGlobal Opaque pSGG_VST sSGG_VST.\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/sample_mark/spatial_graph_uf_iter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2467334993928453}}
{"text": "Require Import ssreflect ssrfun ssrbool.\n(*Require Import Generic.lemmas Generic.wlog.\nRequire Import PG32.pg32_inductive PG32.pg32_spreads_packings.*)\nRequire Import List.\nRequire Import PG32.pg32_spreads_packings PG32.pg32_packings.\n\nLemma aux_S31 : statement_packings S31.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S31.\nLemma aux_S32 : statement_packings S32.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S32.\nLemma aux_S33 : statement_packings S33.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S33.\nLemma aux_S34 : statement_packings S34.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S34.\nLemma aux_S35 : statement_packings S35.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S35.\nLemma aux_S36 : statement_packings S36.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S36.\nLemma aux_S37 : statement_packings S37.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S37.\nLemma aux_S38 : statement_packings S38.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S38.\nLemma aux_S39 : statement_packings S39.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S39.\nLemma aux_S40 : statement_packings S40.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S40.\n", "meta": {"author": "magaud", "repo": "PG3q", "sha": "d34bc2a8b4f42610952a65840b724a69f5a926a1", "save_path": "github-repos/coq/magaud-PG3q", "path": "github-repos/coq/magaud-PG3q/PG3q-d34bc2a8b4f42610952a65840b724a69f5a926a1/pg32/pg32_packings_part4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2465979617318012}}
{"text": "(* -------------------------------------------------------------------- *)\nFrom mathcomp Require Import all_ssreflect all_algebra. \nRequire Import global Utf8.\n\nSet   Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nVariant label_kind :=\n  | InternalLabel\n  | ExternalLabel\n.\n\n(* ==================================================================== *)\nDefinition label := positive.\nBind Scope positive_scope with label.\n\nDefinition remote_label := (funname * label)%type.\n\n(* Indirect jumps use labels encoded as pointers: we assume such an encoding exists.\n  The encoding and decoding functions are parameterized by a domain:\n  they are assumed to succeed on this domain only.\n*)\n\nSection WITH_POINTER_DATA.\nContext {pd: PointerData}.\n\nSection  SPEC.\n  Context\n    (enc: seq remote_label → remote_label → option pointer)\n    (dec: seq remote_label → pointer → option remote_label).\n\n  (* The domain should be small enough, otherwise it is not possible to associate\n     a distinct word to each label. *)\n  Definition small_dom (dom : seq remote_label) :=\n    (Z.of_nat (size dom) <=? wbase Uptr)%Z.\n\n  Definition decode_encode_label_t : Prop :=\n    ∀ dom lbl,\n      small_dom dom →\n      lbl \\in dom →\n      obind (dec dom) (enc dom lbl) = Some lbl.\n\nEnd  SPEC.\n\nSection CONSISTENCY.\n  Lemma decode_encode_label_consistent :\n    ∃ enc dec, decode_encode_label_t enc dec.\n  Proof.\n    exists (λ dom lbl,\n             let r := find (pred1 lbl) dom in\n             if r < size dom\n             then Some (wrepr Uptr (Z.of_nat r))\n             else None).\n    exists (λ dom p, oseq.onth dom (Z.to_nat (wunsigned p))).\n    move => dom lbl /ZleP small_dom.\n    rewrite -has_pred1 => /dup[] => lbl_in_dom.\n    rewrite has_find => /= /dup[] /ltP found -> /=.\n    rewrite wunsigned_repr_small; last first.\n    - move: (find _ _) (size _) small_dom found => n m; Lia.lia.\n    rewrite Nat2Z.id oseq.onth_nth.\n    rewrite (nth_map lbl); last exact/ltP.\n    by have /eqP -> := nth_find lbl lbl_in_dom.\n  Qed.\n\nEnd CONSISTENCY.\n\nParameter encode_label : seq remote_label → remote_label → option pointer.\nParameter decode_label : seq remote_label → pointer → option remote_label.\n\nAxiom decode_encode_label : decode_encode_label_t encode_label decode_label.\n\nLemma encode_label_dom :\n  ∀ dom lbl, small_dom dom → lbl \\in dom → encode_label dom lbl ≠ None.\nProof.\n  move=> dom lbl small_dom hmem.\n  have := decode_encode_label small_dom hmem.\n  by case: encode_label.\nQed.\n\nEnd WITH_POINTER_DATA.\n", "meta": {"author": "jasmin-lang", "repo": "jasmin", "sha": "3c783b662000c371ba924a953d444fd80b860d9f", "save_path": "github-repos/coq/jasmin-lang-jasmin", "path": "github-repos/coq/jasmin-lang-jasmin/jasmin-3c783b662000c371ba924a953d444fd80b860d9f/proofs/arch/label.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24659796173180115}}
{"text": "Require Import CertiGraph.prim.prim_env.\nRequire Export CertiGraph.lib.find_lemmas.\nRequire Export CertiGraph.priq.is_empty_lemmas.\nRequire Import CertiGraph.graph.MathUAdjMatGraph. \nRequire Import CertiGraph.graph.SpaceUAdjMatGraph1.\nRequire Import CertiGraph.prim.prim_spec1.\n\nLocal Open Scope Z.\n\n\n(***********************VERIFICATION***********************)\n\nSection PrimProof.\n\nContext {size: Z}.\t\nContext {inf: Z}.\n\n(* Without a find + isEmpty priq file, just leave it IMO *)\nLemma find_min_lt_inf: forall u l,\n    u = find l (fold_right Z.min (hd 0 l) l) 0 -> (@isEmpty inf l) = Vzero ->\n    Zlength l > 0 -> Znth u l < inf + 1.\nProof.\n  intros. rewrite <- isEmpty_in' in H0. destruct H0 as [? [? ?]].\n  rewrite H. rewrite Znth_find.\n  - pose proof (fold_min _ _ H0). lia.\n  - now apply fold_min_in_list.\nQed.\n\n(**Initialisation functions**)\n\nLemma body_getCell: semax_body Vprog (@Gprog size inf) f_getCell (@getCell_spec size inf).\nProof.\n  start_function.\n  rewrite (SpaceAdjMatGraph_unfold' _ _ _ addresses u); trivial.\n  assert ((Zlength (map Int.repr (Znth u (@graph_to_symm_mat size g)))) = size). {\n    unfold graph_to_symm_mat, graph_to_mat, vert_to_list.\n    rewrite Znth_map; repeat rewrite Zlength_map.\n    all: rewrite nat_inc_list_Zlength, Z2Nat.id; lia.\n  }\n  assert (0 <= i < Zlength (map Int.repr (Znth u (@graph_to_symm_mat size g)))) by lia.\n  assert (0 <= i < Zlength (Znth u (@graph_to_symm_mat size g))). {\n    rewrite Zlength_map in H2. lia.\n  }\n\n  Intros.\n  freeze FR := (iter_sepcon _ _) (iter_sepcon _ _).\n  unfold list_rep.\n  forward. forward. forward. thaw FR.\n  rewrite (SpaceAdjMatGraph_unfold'  _ _ _ addresses u); trivial.\t\n  entailer!.\n\n  all: unfold graph_to_symm_mat; rewrite graph_to_mat_Zlength; trivial.\n  apply Zlength_nonneg. lia.\nQed.\n\nLemma body_initialise_list: semax_body Vprog (@Gprog size inf) f_initialise_list (@initialise_list_spec size).\nProof.\nstart_function.\nassert_PROP(Zlength old_list = size). entailer!.\nforward_for_simple_bound size\n    (EX i : Z,\n     PROP ()\n     LOCAL (temp _list arr; temp _size (Vint (Int.repr size)); temp _a (Vint (Int.repr a)))\n     SEP (\n      data_at Tsh (tarray tint size) (repeat (Vint (Int.repr a)) (Z.to_nat i) ++ (sublist i size old_list)) arr\n    ))%assert.\nentailer!. rewrite app_nil_l. rewrite sublist_same by lia. entailer!.\n(*loop*)\nforward. entailer!.\nrewrite (sublist_split i (i+1)) by lia.\nreplace (sublist i (i+1) old_list) with [Znth i old_list]. simpl.\nrewrite upd_Znth_char.\nrewrite <- repeat_app' by lia.\nrewrite <- app_assoc. simpl. auto.\napply Zlength_repeat; lia.\nsymmetry; apply sublist_one; lia.\n(*postcon*)\nentailer!. rewrite sublist_nil. rewrite app_nil_r. entailer!.\nQed.\n\n(******************PRIM'S***************)\n\nLemma body_prim: semax_body Vprog (@Gprog size inf) f_prim (@prim_spec size inf).\nProof.\n  start_function. rename H into Hprecon_1. rename H0 into Hprecon_2.\n  rename H1 into Hprecon_3.\n  pose proof (inf_representable g).\n  rename H into inf_repr.\nassert (inf_repable: repable_signed inf). {\n  rep_lia.\n}\nassert (Hsz: 0 < size <= Int.max_signed). {\n  apply (size_representable g). }\nassert (Hsz2: size <= Int.max_signed). {\n  lia. }\nassert (size_repable: repable_signed size). {\n  unfold repable_signed. rep_lia. }\nassert (H_size4_rep: Int.min_signed <= size * 4 <= Int.max_signed). {\n  split; [rep_lia|].\n  apply Z.le_trans with (m := size * (4 * size)); trivial.\n  rewrite Z.mul_comm, (Z.mul_comm _ (4 * size)).\n  apply Z.le_mul_diag_r; lia.\n}\nassert (H_size4_rep': 4 <= size * 4 <= Int.max_unsigned). {\n  split; [lia|].\n  apply Z.le_trans with (m := Int.max_signed).\n  2: compute; inversion 1.\n  apply Z.le_trans with (m := size * (4 * size)); trivial.\n  rewrite Z.mul_comm, (Z.mul_comm _ (4 * size)).\n  apply Z.le_mul_diag_r; lia.\n} \n  \n(*replace all data_at_ with data_at Vundef*)\nrepeat rewrite data_at__tarray. set (k:=default_val tint); compute in k; subst k.\n(*populate key with inf*)\n\nunfold V in *.\nforward_call (size * 4). (* check that the call is ok *)\n  \nIntros key.\nremember (pointer_val_val key) as v_key.\nrename H into Ha.\n\nforward_call (v_key, (repeat Vundef (Z.to_nat size)), inf).\nsimpl sizeof. rewrite Z_div_mult. \nrewrite data_at__tarray.\nunfold default_val. simpl. entailer!. lia. \n\n\nassert_PROP (Zlength (map (fun x : Z => Vint (Int.repr x)) garbage) = size). entailer!.\nrewrite Zlength_repeat in H5. trivial.\nlia.\n\n\nforward_call (pointer_val_val parent_ptr, (map (fun x : Z => Vint (Int.repr x)) garbage), size).\nclear H garbage.\n\nforward_call (size * 4).\nIntros out.\nremember (pointer_val_val out) as v_out.\nrename H into Hb.\n\nforward_call (v_out, (repeat Vundef (Z.to_nat size)), 0).\nsimpl sizeof. rewrite Z_div_mult. \nrewrite data_at__tarray.\nunfold default_val. simpl. entailer!. lia.\n\nassert (Hrbound: 0 <= r < size). apply vert_bound in Hprecon_1; auto.\nrewrite <- Heqv_key.\nforward.\nassert (Hstarting_keys: forall i, 0 <= i < size -> is_int I32 Signed (Znth i (upd_Znth r (repeat (Vint (Int.repr inf)) (Z.to_nat size)) (Vint (Int.repr 0))))). {\n  intros. unfold is_int. destruct (Z.eq_dec i r).\n  +subst i. rewrite upd_Znth_same. auto. rewrite Zlength_repeat; lia.\n  +rewrite Znth_upd_Znth_diff; auto. rewrite Znth_repeat_inrange by lia. auto.\n}\nreplace (upd_Znth r (repeat (Vint (Int.repr inf)) (Z.to_nat size)) (Vint (Int.repr 0))) with\n  (map (fun x => Vint (Int.repr x)) (upd_Znth r (repeat inf (Z.to_nat size)) 0)) in *.\n2: {\n  rewrite <- upd_Znth_map.\n  f_equal.\n  rewrite map_repeat.\n  reflexivity.\n}\nset (starting_keys:=map (fun x => Vint (Int.repr x)) (upd_Znth r (repeat inf (Z.to_nat size)) 0)) in *.\nassert (HZlength_starting_keys: Zlength starting_keys = size). {\n  unfold starting_keys. rewrite Zlength_map. rewrite Zlength_upd_Znth. rewrite Zlength_repeat; lia.\n}\nunfold repable_signed in inf_repable.\n(*push all vertices into priq*)\nforward_call(tt).\nIntro priq_ptr.\nremember (pointer_val_val priq_ptr) as v_pq.\nrewrite <- Heqv_out.\n\n(*push all vertices into priq*)\nforward_for_simple_bound size\n  (EX i : Z,\n    PROP ()\n    LOCAL (\n      temp _pq v_pq; temp _out v_out;\n      temp _key v_key; temp _graph (pointer_val_val gptr);\n      temp _size (Vint (Int.repr size));\n      temp _inf (Vint (Int.repr inf));\n      temp _r (Vint (Int.repr r)); temp _parent (pointer_val_val parent_ptr)\n    )\n    SEP (\n      data_at Tsh (tarray tint size) (repeat (Vint (Int.repr 0)) (Z.to_nat size)) v_out;\n      data_at Tsh (tarray tint size) (repeat (Vint (Int.repr size)) (Z.to_nat size)) (pointer_val_val parent_ptr);\n      data_at Tsh (tarray tint size) starting_keys v_key;\n      data_at Tsh (tarray tint size) (sublist 0 i starting_keys ++ sublist i size (repeat Vundef (Z.to_nat size))) v_pq;\n      (@SpaceAdjMatGraph' size CompSpecs Tsh (@graph_to_symm_mat size g) (pointer_val_val gptr) addresses);\n      free_tok v_pq (sizeof tint * size);\n      free_tok v_out (size * 4);\n      free_tok v_key (size * 4)\n    )\n  )%assert.\nentailer!.\nrewrite sublist_nil, sublist_same, app_nil_l.\nentailer!.\ntrivial. rewrite Zlength_repeat; lia.\n\n(*precon taken care of*)\n(*loop*)\nTransparent size.\nforward.\nGlobal Opaque size.\n\nassert (Znth i starting_keys = Vint (Int.repr (Znth i (upd_Znth r (repeat inf (Z.to_nat size)) 0)))). {\n  unfold starting_keys. rewrite Znth_map; auto.\n  rewrite Zlength_upd_Znth. rewrite Zlength_repeat; lia.\n}\nforward_call (v_pq, i, Znth i (upd_Znth r (repeat inf (Z.to_nat size)) 0), sublist 0 i starting_keys ++ sublist i size (repeat Vundef (Z.to_nat size))).\nsplit. auto. unfold weight_inrange_priq.\ndestruct (Z.eq_dec i r). subst i. rewrite upd_Znth_same.\npose proof Int.min_signed_neg; lia.\nrewrite Zlength_repeat; lia.\nrewrite upd_Znth_diff, Znth_repeat_inrange. rep_lia.\nlia. rewrite Zlength_repeat; lia. rewrite Zlength_repeat; lia. auto.\ndestruct (Z.eq_dec i r).\nsubst i. rewrite upd_Znth_same. lia.\nrewrite Zlength_repeat; lia.\nrewrite upd_Znth_diff; try rewrite Zlength_repeat; try lia.\nrewrite Znth_repeat_inrange; lia.\nentailer!.\nrewrite upd_Znth_app2. rewrite Zlength_sublist, Z.sub_0_r, Z.sub_diag; try lia.\nrewrite (sublist_split i (i+1) size). rewrite (sublist_one i (i+1)). rewrite upd_Znth_app1.\nrewrite upd_Znth0. rewrite app_assoc.\nrewrite (sublist_split 0 i (i+1)). rewrite (sublist_one i (i+1)). rewrite <- H0. entailer!.\nall: try lia.\nrewrite Zlength_cons, Zlength_nil; lia.\nrewrite Zlength_repeat. lia. lia.\nrewrite Zlength_repeat; lia.\nrewrite Zlength_sublist. rewrite Zlength_sublist. lia. lia. rewrite Zlength_repeat; lia. lia. lia.\nrewrite sublist_nil, app_nil_r, sublist_same; try lia.\n(*one last thing for convenience*)\nrewrite <- (map_repeat (fun x => Vint (Int.repr x))).\nrewrite <- (map_repeat (fun x => Vint (Int.repr x))).\npose proof (finGraph g) as fg.\n(*whew! all setup done!*)\n(*now for the pq loop*)\nforward_loop (\n  EX mst': (@G size inf),\n  EX fmst': FiniteGraph mst',\n  EX parents: list V,\n  EX keys: list Z, (*can give a concrete definition in SEP, but it leads to shenanigans during entailer*)\n  EX pq_state: list V, (*can give a concrete definition in SEP, but it leads to shenanigans during entailer*)\n  EX popped_vertices: list V,\n  EX unpopped_vertices: list V,\n    PROP (\n      (*graph stuff*)\n      is_partial_lgraph mst' g;\n      uforest' mst';\n      (*about the lists*)\n      Permutation (popped_vertices++unpopped_vertices) (VList g);\n      forall v, 0 <= v < size -> 0 <= Znth v parents <= size;\n      forall v, 0 <= v < size -> Znth v keys = if V_EqDec v r then 0 else elabel g (eformat (v, Znth v parents));\n      forall v, 0 <= v < size -> Znth v pq_state = if in_dec V_EqDec v popped_vertices then Z.add inf 1 else Znth v keys;\n      forall v, 0 <= v < size -> 0 <= Znth v parents < size ->\n          (evalid g (eformat (v, Znth v parents)) /\\ (*together you form a valid edge in g*)\n          (exists i, 0<=i<Zlength popped_vertices /\\ Znth i popped_vertices = Znth v parents /\\\n            i < find popped_vertices v 0) /\\ (*your parent has been popped, only time parents is updated, and you weren't in it when it was*)\n          (forall u, In u (sublist 0 (find popped_vertices v 0) popped_vertices) -> elabel g (eformat (v, Znth v parents)) <= elabel g (eformat (u,v))) (*your current parent is the lowest among the popped, until you're popped too*) (*<-used for proving weight invar below*)\n          );\n      forall v, 0 <= v < size -> Znth v parents = size -> forall u, In u (sublist 0 (find popped_vertices v 0) popped_vertices) -> ~adjacent g u v;\n      (*mst specific*)\n      Permutation (EList mst') (map (fun v => eformat (v, Znth v parents)) (filter (fun v => Znth v parents <? size) popped_vertices));\n      forall u v, In u popped_vertices -> In v popped_vertices -> (connected g u v <-> connected mst' u v);\n      (*misc*)\n      forall u v, In u unpopped_vertices -> ~ adjacent mst' u v;\n      (*weight*)\n      (* at the point of being popped, you had the lowest weight of all potential branches *)\n      forall v u1 u2, In v popped_vertices -> 0 <= Znth v parents < size ->\n        vvalid g u2 ->\n        In u1 (sublist 0 (find popped_vertices v 0) popped_vertices) ->\n        ~ In u2 (sublist 0 (find popped_vertices v 0) popped_vertices) ->\n        elabel g (eformat (v, Znth v parents)) <= elabel g (eformat (u1,u2));\n      (*minimality...*)\n      exists M, minimum_spanning_forest M g /\\ is_partial_lgraph mst' M;\n      (*the following two are yuck...*)\n      popped_vertices = nil -> r = find pq_state (fold_right Z.min (hd 0 pq_state) pq_state) 0;\n      popped_vertices <> nil -> hd_error popped_vertices = Some r\n    )\n    LOCAL (\n      temp _v (Vint (Int.repr size));\n      temp _pq v_pq; temp _out v_out;\n      temp _key v_key;\n      temp _graph (pointer_val_val gptr);\n      temp _size (Vint (Int.repr size));\n      temp _inf (Vint (Int.repr inf));\n      temp _r (Vint (Int.repr r));\n      temp _parent (pointer_val_val parent_ptr)\n    )\n    SEP (\n      data_at Tsh (tarray tint size) (map (fun x => if in_dec V_EqDec x popped_vertices\n        then (Vint (Int.repr 1)) else (Vint (Int.repr 0))) (nat_inc_list (Z.to_nat size))) v_out;\n      data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x)) parents) (pointer_val_val parent_ptr);\n      data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x)) keys) v_key;\n      data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x))\n        pq_state) v_pq;\n      (@SpaceAdjMatGraph' size CompSpecs Tsh (@graph_to_symm_mat size g) (pointer_val_val gptr) addresses);\n      free_tok v_pq (sizeof tint * size);\n      free_tok v_out (size * 4);\n      free_tok v_key (size * 4)\n    )\n  )\nbreak: (\n  EX mst: (@G size inf),\n  EX fmst: FiniteGraph mst,\n  EX popped_vertices: list V,\n  EX parents: list V,\n  EX keys: list Z,\n    PROP (\n      is_partial_lgraph mst g;\n      uforest' mst;\n      Permutation popped_vertices (VList mst);\n      forall v, 0 <= v < size -> 0 <= Znth v parents < size ->\n          (evalid g (eformat (v, Znth v parents)) /\\ (*together you form a valid edge in g*)\n          (exists i, 0<=i<Zlength popped_vertices /\\ Znth i popped_vertices = Znth v parents\n            /\\ i < find popped_vertices v 0) /\\ (*your parent has been popped, only time parents is updated, and you weren't in it when it was*)\n          (forall u, In u (sublist 0 (find popped_vertices v 0) popped_vertices) -> elabel g (eformat (v, Znth v parents)) <= elabel g (eformat (u,v))) (*your current parent is the lowest among the popped, until you're popped too*) (*<-used for proving weight invar below*)\n          );\n      forall v, 0 <= v < size -> Znth v parents = size -> forall u, In u (sublist 0 (find popped_vertices v 0) popped_vertices) -> ~adjacent g u v;\n      (*something about weight*)\n      Permutation (EList mst) (map (fun v => eformat (v, Znth v parents)) (filter (fun v => Znth v parents <? size) popped_vertices));\n      spanning mst g;\n      hd_error popped_vertices = Some r; (*<-idk if necessary, just putting it in in case*)\n      (*weight*)\n      forall v u1 u2, In v popped_vertices -> 0 <= Znth v parents < size ->\n        vvalid g u2 ->\n        In u1 (sublist 0 (find popped_vertices v 0) popped_vertices) ->\n        ~ In u2 (sublist 0 (find popped_vertices v 0) popped_vertices) ->\n        elabel g (eformat (v, Znth v parents)) <= elabel g (eformat (u1,u2));\n      forall v, 0 <= v < size -> 0 <= Znth v parents <= size;\n      (*minimality...*)\n      exists M, minimum_spanning_forest M g /\\ is_partial_lgraph mst M\n    )\n    LOCAL (\n      temp _pq v_pq; temp _out v_out;\n      temp _parent (pointer_val_val parent_ptr); temp _key v_key;\n      temp _graph (pointer_val_val gptr); temp _r (Vint (Int.repr r))\n    )\n    SEP (\n      data_at Tsh (tarray tint size) (repeat (Vint (Int.repr 1)) (Z.to_nat size)) v_out;\n      data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x)) parents) (pointer_val_val parent_ptr);\n      data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x)) keys) v_key;\n      data_at Tsh (tarray tint size) (repeat (Vint (Int.repr (inf+1))) (Z.to_nat size)) v_pq;\n      (@SpaceAdjMatGraph' size CompSpecs Tsh (@graph_to_symm_mat size g) (pointer_val_val gptr) addresses);\n      free_tok v_pq (sizeof tint * size);\n      free_tok v_out (size * 4);\n      free_tok v_key (size * 4)\n    )\n  )\n%assert.\n(****PRECON****) {\n  remember (@edgeless_graph'\n            size inf\n            Hsz\n            (inf_representable g)) as elg. \n  Exists elg.\n  pose proof (finGraph elg) as fe. Exists fe.\n  Exists (repeat size (Z.to_nat size)).\n  Exists (upd_Znth r (repeat inf (Z.to_nat size)) 0).\n  Exists (upd_Znth r (repeat inf (Z.to_nat size)) 0).\n  Exists (nil (A:=V)).\n  Exists (VList g). rewrite app_nil_l.\n  assert (Hinv_1: is_partial_lgraph elg g).\n  subst elg. apply edgeless_partial_lgraph.\n  assert (Hinv_2: uforest' elg). subst elg. apply uforest'_edgeless_graph.\n  assert (Hinv_3: Permutation (VList g) (VList g)). apply Permutation_refl; auto.\n  assert (Hinv_4: forall v : Z, 0 <= v < size -> 0 <= Znth v (repeat size (Z.to_nat size)) <= size). {\n    intros. rewrite Znth_repeat_inrange; lia.\n  }\n  assert (Hinv_5: forall v : Z, 0 <= v < size -> Znth v (upd_Znth r (repeat inf (Z.to_nat size)) 0) =\n    (if V_EqDec v r then 0 else elabel g (eformat (v, Znth v (repeat size (Z.to_nat size)))))). {\n    intros. destruct (V_EqDec v r).\n    hnf in e; subst v. rewrite upd_Znth_same. auto. rewrite Zlength_repeat; lia.\n    unfold RelationClasses.complement, Equivalence.equiv in c. rewrite upd_Znth_diff.\n    repeat rewrite Znth_repeat_inrange by lia. symmetry; rewrite <- (invalid_edge_weight g); auto.\n    unfold not; intros. rewrite <- (eformat_adj g) in H0. apply adjacent_requires_vvalid in H0. destruct H0.\n    rewrite vert_bound in H1. lia.\n    rewrite Zlength_repeat; lia. rewrite Zlength_repeat; lia. auto.\n  }\n  assert (Hinv_6: forall v : Z,\n    0 <= v < size ->\n    Znth v (upd_Znth r (repeat inf (Z.to_nat size)) 0) =\n    (if in_dec V_EqDec v (nil (A:=V))\n     then (inf + 1)%Z\n     else Znth v (upd_Znth r (repeat inf (Z.to_nat size)) 0))). {\n    intros. destruct (in_dec V_EqDec v []); [contradiction | auto].\n  }\n  assert (Hinv_7: forall v : Z, 0 <= v < size ->\n    0 <= Znth v (repeat size (Z.to_nat size)) < size ->\n    evalid g (eformat (v, Znth v (repeat size (Z.to_nat size)))) /\\\n    (exists i : Z, 0 <= i < Zlength (nil (A:=V)) /\\\n       Znth i (nil (A:=V)) = Znth v (repeat size (Z.to_nat size)) /\\ i < find (nil (A:=V)) v 0) /\\\n    (forall u : V,\n     In u (sublist 0 (find (nil (A:=V)) v 0) (nil (A:=V))) ->\n     elabel g (eformat (v, Znth v (repeat size (Z.to_nat size)))) <=\n     elabel g (eformat (u, v)))). {\n    intros. rewrite Znth_repeat_inrange in H0; lia. }\n  assert (Hinv_8: forall v : Z, 0 <= v < size ->\n    Znth v (repeat size (Z.to_nat size)) = size ->\n    forall u : V, In u (sublist 0 (find [] v 0) []) -> ~ adjacent g u v). {\n    intros. rewrite sublist_nil in H1. contradiction. }\n  assert (Hinv_9: Permutation (EList elg)\n      (map (fun v : Z => eformat (v, Znth v (repeat size (Z.to_nat size))))\n         (filter (fun v : Z => Znth v (repeat size (Z.to_nat size)) <? size) []))). {\n    simpl.\n    (*because I've trouble using edgeless_graph_EList*) apply NoDup_Permutation. apply NoDup_EList. apply NoDup_nil.\n    intros. rewrite EList_evalid. split; intros.\n    subst elg.\n    pose proof (@edgeless_graph_evalid size inf (inf_representable g) Hsz x); contradiction. contradiction.\n  }\n  assert (Hr1: forall u v : V, In u (nil (A:=V)) -> In v (nil (A:=V)) -> connected g u v <-> connected elg u v). {\n    intros. contradiction.\n  }\n  assert (Hr2: (nil (A:=V)) = (nil (A:=V)) ->\n    r = find (upd_Znth r (repeat inf (Z.to_nat size)) 0)\n      (fold_right Z.min (hd 0 (upd_Znth r (repeat inf (Z.to_nat size)) 0))\n         (upd_Znth r (repeat inf (Z.to_nat size)) 0)) 0). {\n    intros. rewrite find_src; lia. \n  }\n  (*Hinv_12 (nil <> nil) seems to be missing, autoresolved?*)\n  assert (Hinv_13: forall u v : V, In u (VList g) -> ~ adjacent elg u v). {\n    unfold not; intros. destruct H0 as [e [? ?]]. destruct H0.\n    subst elg. pose proof (@edgeless_graph_evalid size inf (inf_representable g) Hsz e); contradiction.\n  }\n  assert (Hinv_14: forall v u1 u2 : V,\n    In v (nil (A:=V)) ->\n    0 <= Znth v (repeat size (Z.to_nat size)) < size ->\n    vvalid g u2 ->\n    In u1 (sublist 0 (find (nil (A:=V)) v 0) (nil (A:=V))) ->\n    ~ In u2 (sublist 0 (find (nil (A:=V)) v 0) (nil (A:=V))) ->\n    elabel g (eformat (v, Znth v (repeat size (Z.to_nat size)))) <=\n    elabel g (eformat (u1, u2))). {\n    intros. contradiction.\n  }\n  assert (Hinv_15: exists M, minimum_spanning_forest M g /\\ is_partial_lgraph elg M). {\n    destruct (exists_msf g) as [M ?]. exists M; split. auto.\n    subst elg. apply edgeless_partial_lgraph.\n  }                                                      (*fix up the SEP*)\n  replace (map (fun x : V => if in_dec V_EqDec x [] then Vint (Int.repr 1) else Vint (Int.repr 0)) (nat_inc_list (Z.to_nat size)))\n    with (map (fun x : Z => Vint (Int.repr x)) (repeat 0 (Z.to_nat size))). 2: {\n    apply list_eq_Znth. repeat rewrite Zlength_map. rewrite Zlength_repeat by lia. rewrite nat_inc_list_Zlength, Z2Nat.id; lia.\n    intros. rewrite Zlength_map, Zlength_repeat in H by lia.\n    rewrite Znth_map. 2: rewrite Zlength_repeat; lia.\n    rewrite Znth_repeat_inrange by lia.\n    rewrite Znth_map. 2: rewrite nat_inc_list_Zlength, Z2Nat.id; lia.\n    rewrite nat_inc_list_i. 2: rewrite Z2Nat.id; lia.\n    destruct (in_dec V_EqDec i []); [contradiction | auto].\n  }\n  unfold starting_keys.\n  time \"main loop precon (originally 446.87s):\" entailer!.\n  \n\n\n}\n(****MAIN LOOP****) {\n  clear Hstarting_keys HZlength_starting_keys starting_keys.\n  Intros mst' fmst' parents keys pq_state popped_vertices unpopped_vertices.\n  (*do a mass renaming for convenience*)\n  rename H into Hinv_1; rename H0 into Hinv_2;\n  rename H1 into Hinv_3; rename H2 into Hinv_4;\n  rename H3 into Hinv_5; rename H4 into Hinv_6;\n  rename H5 into Hinv_7; rename H6 into Hinv_8;\n  rename H7 into Hinv_9; rename H8 into Hinv_10;\n  rename H9 into Hinv_13; rename H10 into Hinv_14;\n  rename H11 into Hinv_15; rename H12 into Hr1;\n  rename H13 into Hr2.\n  assert_PROP (Zlength parents = size /\\\n               Zlength keys = size /\\\n               Zlength pq_state = size\n              ). {\n    entailer!.\n    repeat rewrite Zlength_map in *.\n    rewrite H2 in *.\n    split3; trivial.\n  }\n  destruct H as [HZlength_parents [HZlength_keys HZlength_pq_state]].\n  assert (Hpopped_or_unpopped: forall v, vvalid g v -> In v popped_vertices \\/ In v unpopped_vertices). {\n    intros. apply in_app_or. apply (Permutation_in (l:=VList g)). apply Permutation_sym; auto. apply VList_vvalid; auto.\n  }\n  (*^^significant lag from the three entailers above*)\n  assert (Hpopped_vvalid: forall v, In v popped_vertices -> vvalid g v). {\n    intros. rewrite <- VList_vvalid. apply (Permutation_in (l:=popped_vertices++unpopped_vertices)).\n    apply Hinv_3. apply in_or_app; left; auto.\n  }\n  assert (Hunpopped_vvalid: forall v, In v unpopped_vertices -> vvalid g v). {\n    intros. rewrite <- VList_vvalid. apply (Permutation_in (l:=popped_vertices++unpopped_vertices)).\n    apply Hinv_3. apply in_or_app; right; auto.\n  }\n  assert (@inrange_priq inf pq_state). {\n    unfold inrange_priq. rewrite Forall_forall. intros x Hx.\n    rewrite In_Znth_iff in Hx. destruct Hx as [i [? ?]].\n    unfold V in *.\n    rewrite HZlength_pq_state in H. subst x.\n    rewrite Hinv_6. 2: lia.\n    destruct (@in_dec Z V_EqDec i popped_vertices).    \n    rep_lia.\n    rewrite Hinv_5. 2: lia. destruct (V_EqDec i r).\n    pose proof (inf_representable g); rep_lia.\n    split. apply weight_representable. apply (Z.le_trans _ inf). apply weight_inf_bound. lia.\n  }\n  replace (data_at Tsh (tarray tint size) (map (fun x : Z => Vint (Int.repr x)) pq_state) v_pq)\n    with (data_at Tsh (tarray tint size) (map Vint (map Int.repr pq_state)) v_pq).\n  2: { rewrite list_map_compose. auto. }\n  forward_call (v_pq, pq_state).\n  forward_if.\n\n  (*PROCEED WITH LOOP*) {\n  assert (@isEmpty inf pq_state = Vzero). {\n    destruct (@isEmptyTwoCases inf pq_state);\n    rewrite H1 in H0; simpl in H0; now inversion H0.\n  }\n  forward_call (v_pq, pq_state).\n  Intros u. rename H2 into Hu.\n  assert (0 <= u < size). {\n    rewrite Hu. rewrite <- HZlength_pq_state. apply find_range.\n    apply min_in_list. apply incl_refl. destruct pq_state.\n    rewrite Zlength_nil in HZlength_pq_state. lia.\n    simpl. left; trivial.\n  }\n  assert (Hu_not_popped: ~ In u popped_vertices). { unfold not; intros.\n    assert (Znth u pq_state < inf + 1). apply (find_min_lt_inf u pq_state Hu H1).\n    unfold V in *. rewrite HZlength_pq_state. lia.\n    rewrite Hinv_6 in H4 by lia.\n    destruct (in_dec V_EqDec u popped_vertices). lia. contradiction.\n  }\n  assert (Hu_unpopped: In u unpopped_vertices). { destruct (Hpopped_or_unpopped u).\n    rewrite (vvalid_meaning g). auto. contradiction. auto.\n  }\n  forward.\n  replace (upd_Znth u (map (fun x : V =>\n    if in_dec V_EqDec x popped_vertices then Vint (Int.repr 1) else Vint (Int.repr 0))\n    (nat_inc_list (Z.to_nat size))) (Vint (Int.repr 1))) with (map (fun x : V =>\n    if in_dec V_EqDec x (popped_vertices+::u) then Vint (Int.repr 1) else Vint (Int.repr 0))\n    (nat_inc_list (Z.to_nat size))).\n  2: { apply list_eq_Znth. rewrite Zlength_upd_Znth. do 2 rewrite Zlength_map. auto.\n    intros. rewrite Zlength_map in H3. rewrite nat_inc_list_Zlength in H3.\n    destruct (Z.eq_dec i u). subst i.\n    +rewrite upd_Znth_same. rewrite Znth_map.\n    rewrite nat_inc_list_i. assert (In u (popped_vertices+::u)). apply in_or_app. right; simpl; auto.\n    destruct (in_dec V_EqDec u (popped_vertices+::u)). auto. contradiction.\n    lia. rewrite nat_inc_list_Zlength; lia.\n    rewrite Zlength_map, nat_inc_list_Zlength; lia.\n    +rewrite upd_Znth_diff. rewrite Znth_map. rewrite Znth_map. rewrite nat_inc_list_i.\n    destruct (in_dec V_EqDec i (popped_vertices+::u));\n    destruct (in_dec V_EqDec i popped_vertices). auto.\n    apply in_app_or in i0; destruct i0. contradiction. destruct H4. symmetry in H4; contradiction. contradiction.\n    assert (In i (popped_vertices+::u)). apply in_or_app. left; auto. contradiction.\n    auto. auto. rewrite nat_inc_list_Zlength; auto. rewrite nat_inc_list_Zlength; auto.\n    rewrite Zlength_map, nat_inc_list_Zlength; auto.\n    rewrite Zlength_map, nat_inc_list_Zlength; auto.\n    auto.\n    rewrite Z2Nat.id; lia. trivial.\n  }\n  rewrite upd_Znth_map. rewrite upd_Znth_map. rewrite list_map_compose. (*pq state*)\n  replace (Znth 0 pq_state) with (hd 0 pq_state). rewrite <- Hu. 2: { destruct pq_state. rewrite Zlength_nil in HZlength_pq_state; lia. simpl. rewrite Znth_0_cons. auto. }\n  assert (Hur: popped_vertices = nil -> u = r). {\n    intros. rewrite Hu. symmetry; apply Hr1. auto.\n  }\n  assert (Hu_min: forall v, 0 <= v < size -> Znth u pq_state <= Znth v pq_state). {\n    intros. rewrite Hu. rewrite Znth_find.\n    apply fold_min. apply Znth_In. unfold V in *. lia.\n    apply fold_min_in_list. unfold V in *. lia.\n  }\n  clear Hu. set (upd_pq_state:=upd_Znth u pq_state (inf + 1)).\n  (*for loop to update un-popped vertices' min weight.\n  The result is every vertex who's NOT in popped_vertices and connected, has their weight maintained or lowered*)\n  forward_for_simple_bound size (\n    EX i: Z,\n    EX parents': list Z,\n    EX keys': list Z,\n    EX pq_state': list Z,\n      PROP (\n        (*if you were already popped (out=1) or not adjacent, nothing happens*)\n        forall v, 0<=v<i -> (~adjacent g u v \\/ In v (popped_vertices+::u)) -> (\n          Znth v parents' = Znth v parents /\\\n          Znth v keys' = Znth v keys /\\\n          Znth v pq_state' = Znth v upd_pq_state);\n        (*if you are still in pq and adjacent, you are updated*)\n        forall v, 0<=v<i -> adjacent g u v -> ~ In v (popped_vertices+::u) -> (\n          Znth v parents' = (if Z.ltb (elabel g (eformat (u,v))) (Znth v upd_pq_state) then u else Znth v parents) /\\\n          Znth v keys' = Z.min (elabel g (eformat (u,v))) (Znth v upd_pq_state) /\\\n          Znth v pq_state' = Z.min (elabel g (eformat (u,v))) (Znth v upd_pq_state));\n        (*no change for those that haven't been checked*)\n        forall v, i<=v<size -> (\n          Znth v parents' = Znth v parents /\\\n          Znth v keys' = Znth v keys /\\\n          Znth v pq_state' = Znth v upd_pq_state\n        );\n        forall v, 0 <= v < size -> Int.min_signed <= Znth v keys' <= inf\n      )\n      LOCAL (temp _u (Vint (Int.repr u)); temp _t'4 (@isEmpty inf pq_state);\n             temp _v (Vint (Int.repr size)); temp _pq v_pq; temp _out v_out;\n             temp _key v_key; temp _graph (pointer_val_val gptr);\n             temp _size (Vint (Int.repr size)); temp _inf (Vint (Int.repr inf));\n             temp _r (Vint (Int.repr r)); temp _parent (pointer_val_val parent_ptr))\n      SEP (data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x)) pq_state') v_pq;\n     data_at Tsh (tarray tint size)\n       (map\n          (fun x : V =>\n           if in_dec V_EqDec x (popped_vertices+::u) then Vint (Int.repr 1) else Vint (Int.repr 0))\n          (nat_inc_list (Z.to_nat size))) v_out;\n     data_at Tsh (tarray tint size) (map (fun x : Z => Vint (Int.repr x)) parents') (pointer_val_val parent_ptr);\n     data_at Tsh (tarray tint size) (map (fun x : Z => Vint (Int.repr x)) keys') v_key;\n     (@SpaceAdjMatGraph' size CompSpecs Tsh (@graph_to_symm_mat size g) (pointer_val_val gptr) addresses);\n     free_tok v_pq (sizeof tint * size);\n     free_tok v_out (size * 4);\n     free_tok v_key (size * 4)\n          )\n    )\n  %assert.\n  (*precon*) {\n    Exists parents. Exists keys. Exists upd_pq_state. entailer!.\n    remember (Zlength parents) as size.\n    (*in this case, proving the PROPs beforehand did not improve the timing*)\n    intros. rewrite Hinv_5 by lia. destruct (V_EqDec v r). auto. split; rep_lia.\n    pose proof (weight_representable g (eformat (v, Znth v parents))).\n    split; try rep_lia. apply weight_inf_bound.\n  }\n  (*loop*)\n  assert (is_int I32 Signed (if in_dec V_EqDec (Znth i (nat_inc_list (Z.to_nat size))) (popped_vertices+::u)\n    then Vint (Int.repr 1) else Vint (Int.repr 0))). {\n    unfold is_int. rewrite nat_inc_list_i. 2: rewrite Z2Nat.id; lia.\n    destruct (in_dec V_EqDec i (popped_vertices+::u)); auto.\n  }\n  assert (Hc: 0 <= i < Zlength (nat_inc_list (Z.to_nat size))). {\n    rewrite nat_inc_list_Zlength, Z2Nat.id; trivial. lia. }\n  forward.\n  rename H5 into Hinv2_1; rename H6 into Hinv2_2;\n  rename H7 into Hinv2_3; rename H8 into Hinv2_4.\n  assert_PROP (Zlength (map (fun x : Z => Vint (Int.repr x)) parents') = size /\\\n                Zlength (map (fun x : Z => Vint (Int.repr x)) keys') = size /\\\n                Zlength (map (fun x : Z => Vint (Int.repr x)) pq_state') = size). entailer!.\n  repeat rewrite Zlength_map in H5. destruct H5 as [? [? ?]].\n  rename H5 into HZlength_parents'. rename H6 into HZlength_keys'. rename H7 into HZlength_pq_state'.\n  rewrite nat_inc_list_i. 2: rewrite Z2Nat.id; lia.\n  set (out_i:=if in_dec V_EqDec i (popped_vertices+::u)\n               then Vint (Int.repr 1)\n               else Vint (Int.repr 0)). fold out_i.\n  forward_if.\n  (**In queue**)\n  +assert (~ In i (popped_vertices+::u)). {\n    destruct (in_dec V_EqDec i (popped_vertices +:: u)). simpl in H5. inversion H5. auto.\n   }\n   Transparent size.\n   forward_call (g, gptr, addresses, u, i).\n   Global Opaque size.\n   forward.\n  forward_if.\n    -(*g[u][i] < ..., update*)\n    (*implies adjacency*)\n      rewrite graph_to_mat_eq in H7; try lia. rewrite eformat_symm in H7.\n      rewrite Int.signed_repr in H7. rewrite Int.signed_repr in H7.\n      2: { assert (Int.min_signed <= Znth i keys' <= inf). apply Hinv2_4; lia.\n           pose proof (inf_representable g).\n           rep_lia.\n      }\n    2: { apply weight_representable. }\n    assert (Hadj_ui: adjacent g u i). {\n      rewrite eformat_adj_elabel.\n      assert (Znth i keys' <= inf). apply Hinv2_4. lia.\n      apply (Z.lt_le_trans _ (Znth i keys')); auto.\n    }\n    forward. forward. forward. entailer!.\n    rewrite upd_Znth_same. simpl. auto. rewrite Zlength_map. rewrite HZlength_keys'. auto.\n    rewrite upd_Znth_same. 2: { simpl. auto. rewrite Zlength_map. rewrite HZlength_keys'. auto. }\n    replace (map (fun x : Z => Vint (Int.repr x)) pq_state') with (map Vint (map Int.repr pq_state')).\n    2: rewrite list_map_compose; auto.\n    forward_call (v_pq, i, Znth i (Znth u (@graph_to_symm_mat size g)), pq_state').\n    unfold weight_inrange_priq.\n    rewrite graph_to_mat_eq. split.\n    apply weight_representable. rewrite eformat_adj_elabel, eformat_symm in Hadj_ui.\n    fold V in *. lia. lia. lia.\n    Exists (upd_Znth i parents' u).\n    Exists (upd_Znth i keys' (Znth i (Znth u (@graph_to_symm_mat size g)))).\n    Exists (upd_Znth i pq_state' (Znth i (Znth u (@graph_to_symm_mat size g)))).\n    rewrite list_map_compose. repeat rewrite (upd_Znth_map (fun x => Vint (Int.repr x))). \n    clear H0 H5.\n    assert (Hx1: forall v : Z, 0 <= v < i + 1 ->\n      ~ adjacent g u v \\/ In v (popped_vertices +:: u) ->\n      Znth v (upd_Znth i parents' u) = Znth v parents /\\\n      Znth v (upd_Znth i keys' (Znth i (Znth u (@graph_to_symm_mat size g)))) = Znth v keys /\\\n      Znth v (upd_Znth i pq_state' (Znth i (Znth u (@graph_to_symm_mat size g)))) =\n      Znth v upd_pq_state). {\n      intros. destruct (Z.lt_trichotomy v i). repeat rewrite upd_Znth_diff; try lia. apply Hinv2_1. lia. apply H5.\n      destruct H8. subst v. destruct H5; contradiction. lia.\n    } (*71s to 60s*)\n    assert (Hx2: forall v : Z,\n    0 <= v < i + 1 ->\n    adjacent g u v ->\n    ~ In v (popped_vertices +:: u) ->\n    Znth v (upd_Znth i parents' u) =\n    (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents) /\\\n    Znth v (upd_Znth i keys' (Znth i (Znth u (@graph_to_symm_mat size g)))) =\n    Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state) /\\\n    Znth v (upd_Znth i pq_state' (Znth i (Znth u (@graph_to_symm_mat size g)))) =\n    Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state)). {\n      intros. destruct (Z.lt_trichotomy v i).\n        (*v<i*) repeat rewrite upd_Znth_diff; try lia. apply Hinv2_2. lia. auto. auto.\n        destruct H9.\n        (*v=i*) subst v. repeat rewrite upd_Znth_same; try lia.\n        (*i not in popped, so must be in unpopped, which means upd_pq_state = pq_state = keys*)\n        assert (Znth i upd_pq_state = Znth i keys').\n          unfold upd_pq_state. rewrite upd_Znth_diff. 2: replace (Zlength pq_state) with size; lia. 2: replace (Zlength pq_state) with size; lia.\n          replace (Znth i keys') with (Znth i keys). rewrite Hinv_6.\n          destruct (in_dec V_EqDec i popped_vertices). exfalso; apply H8. apply in_or_app; left; auto. auto. lia.\n          symmetry. apply Hinv2_3. lia. unfold not; intros. apply H8. apply in_or_app; right; subst i; left; auto.\n        rewrite H9. split3.\n        rewrite <- (@graph_to_mat_eq size); try lia. destruct (Znth u (Znth i (@graph_to_symm_mat size g)) <? Znth i keys') eqn:bool.\n        auto. rewrite graph_to_mat_eq in bool; try lia. rewrite Z.ltb_nlt in bool. contradiction.\n        rewrite graph_to_mat_eq; try lia. rewrite eformat_symm. rewrite Zlt_Zmin; auto.\n        rewrite graph_to_mat_eq; try lia. rewrite eformat_symm. rewrite Zlt_Zmin; auto.\n        (*v>i*) lia.\n    } (*60s to 33s*)\n    assert(Hx3: forall v : Z,\n    i + 1 <= v < size ->\n    Znth v (upd_Znth i parents' u) = Znth v parents /\\\n    Znth v (upd_Znth i keys' (Znth i (Znth u (@graph_to_symm_mat size g)))) = Znth v keys /\\\n    Znth v (upd_Znth i pq_state' (Znth i (Znth u (@graph_to_symm_mat size g)))) = Znth v upd_pq_state). {\n      intros. repeat rewrite upd_Znth_diff; try lia. apply Hinv2_3. lia.\n    }\n    (*entailer unable to solve but no change to timing*)\n    assert (Hx4: forall v : Z,\n    0 <= v < size ->\n    Int.min_signed <= Znth v (upd_Znth i keys' (Znth i (Znth u (@graph_to_symm_mat size g)))) <= inf). {\n      intros. destruct (Z.eq_dec v i). subst i. rewrite upd_Znth_same. rewrite graph_to_mat_eq.\n      split. apply (weight_representable g (eformat (v,u))). apply weight_inf_bound. lia. lia. rewrite HZlength_keys'; lia.\n      rewrite upd_Znth_diff. apply Hinv2_4. auto. rewrite HZlength_keys'; lia.\n      rewrite HZlength_keys'; lia. auto.\n    } (*entailer unable to solve but no change to timing*)\n    time \"inner loop update-because-lt-postcon (orig 71 seconds)\" entailer!.\n    -forward. (*nothing changed*)\n    Exists parents'. Exists keys'. Exists pq_state'.\n    assert (Hx1: forall v : Z,\n          0 <= v < i + 1 ->\n          ~ adjacent g u v \\/ In v (popped_vertices +:: u) ->\n          Znth v parents' = Znth v parents /\\\n          Znth v keys' = Znth v keys /\\ Znth v pq_state' = Znth v upd_pq_state). {\n      intros. destruct (Z.lt_trichotomy v i). apply Hinv2_1; auto. lia. destruct H10.\n      subst v. apply Hinv2_3. lia. lia.\n    } (*60s to 53s*)\n    assert (Hx2: forall v : Z,\n      0 <= v < i + 1 ->\n      adjacent g u v ->\n      ~ In v (popped_vertices +:: u) ->\n      Znth v parents' =\n      (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents) /\\\n      Znth v keys' = Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state) /\\\n      Znth v pq_state' = Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state)). {\n      intros. destruct (Z.lt_trichotomy v i).\n      (*v < i*) apply Hinv2_2. lia. auto. auto.\n      destruct H11.\n      (*v = i*) subst v. rewrite <- (@graph_to_mat_eq size); try lia.\n      assert (Znth i upd_pq_state = Znth i keys'). {\n        unfold upd_pq_state. rewrite upd_Znth_diff. 2: replace (Zlength pq_state) with size; lia.  2: replace (Zlength pq_state) with size; lia.\n        replace (Znth i keys') with (Znth i keys). rewrite Hinv_6.\n        destruct (in_dec V_EqDec i popped_vertices). exfalso. apply H10. apply in_or_app; left; auto.\n        auto. lia. symmetry. apply Hinv2_3. lia. unfold not; intros. apply H10. apply in_or_app; right; subst i; left; auto.\n      } rewrite H11.\n      rewrite graph_to_mat_symmetric; try lia.\n      rewrite !Int.signed_repr in H7. split3.\n      destruct (Znth i (Znth u (@graph_to_symm_mat size g)) <? Znth i keys') eqn:bool.\n      rewrite Z.ltb_lt in bool. unfold V in *. lia.\n      apply Hinv2_3. lia.\n      unfold V in *.\n      rewrite Z.min_r; try lia. \n      replace (Znth i pq_state') with (Znth i upd_pq_state). rewrite H11.\n      unfold V in *. rewrite Z.min_r; try lia.\n      symmetry; apply Hinv2_3; lia.\n      assert (Int.min_signed <= Znth i keys' <= inf). apply Hinv2_4. lia. pose proof (inf_repable); unfold repable_signed in H13; lia.\n      rewrite graph_to_mat_eq; try lia. apply weight_representable.\n      (*v > i*) lia.\n    } (*53s to 30s*)\n    assert (Hx3: forall v : Z,\n      i + 1 <= v < size ->\n      Znth v parents' = Znth v parents /\\\n      Znth v keys' = Znth v keys /\\ Znth v pq_state' = Znth v upd_pq_state). {\n      intros. apply Hinv2_3. lia.\n    } (*entailer unable to solve but no change to timing*)\n    time \"inner loop no-update-because-not-lt-postcon (originally 60s)\" entailer!.\n    \n  +(*nothing changed because out of pq*)\n  assert (In i (popped_vertices+::u)). {\n    unfold typed_false in H5. destruct (V_EqDec u i); simpl in H5. unfold Equivalence.equiv in e; subst i. apply in_or_app; right; left; auto.\n    destruct (in_dec V_EqDec i (popped_vertices+::u)); simpl in H5. auto. inversion H5.\n  }\n  forward. (*again nothing changed*)\n  Exists parents'. Exists keys'. Exists pq_state'.\n  rewrite (SpaceAdjMatGraph_unfold' _ _ _ addresses u).\n  unfold list_rep.\n  2: unfold graph_to_symm_mat; rewrite graph_to_mat_Zlength; lia.\n  2: lia.\n  assert (forall v : Z,\n          0 <= v < i + 1 ->\n          ~ adjacent g u v \\/ In v (popped_vertices +:: u) ->\n          Znth v parents' = Znth v parents /\\\n          Znth v keys' = Znth v keys /\\ Znth v pq_state' = Znth v upd_pq_state). {\n    intros. destruct (Z.lt_trichotomy v i). apply Hinv2_1; auto. lia. destruct H9. subst v. apply Hinv2_3. lia. lia.\n  }\n  assert (forall v : Z,\n    0 <= v < i + 1 ->\n    adjacent g u v ->\n    ~ In v (popped_vertices +:: u) ->\n    Znth v parents' =\n    (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents) /\\\n    Znth v keys' = Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state) /\\\n    Znth v pq_state' = Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state)). {\n    intros. destruct (Z.lt_trichotomy v i). apply Hinv2_2. lia. auto. auto.\n    destruct H11. subst v. contradiction. (*i is popped*) lia.\n  }\n  assert (forall v : Z,\n    i + 1 <= v < size ->\n    Znth v parents' = Znth v parents /\\\n    Znth v keys' = Znth v keys /\\ Znth v pq_state' = Znth v upd_pq_state). {\n    intros. apply Hinv2_3. lia.\n  }\n  time \"inner loop no-update-because-out-postcon (originally 92 seconds):\" entailer!.\n  +(*inner loop done, postcon leading to next outer loop iter*)\n  Intros parents' keys' pq_state'.\n  assert (Htmp: Znth u parents' = Znth u parents /\\ Znth u keys' = Znth u keys /\\ Znth u pq_state' = Znth u upd_pq_state). {\n    apply H3. lia. right; apply in_or_app; right; left; auto.\n  } destruct Htmp as [Hu_parents [Hu_keys Hu_pq_state]].\n  (*need to split into two cases: if Znth u keys = inf, then it's a \"starter\" and so the same mst. Else, it's adde(eformat (u, Znth u keys))*)\n  clear H5. rename H3 into Hinv2_1; rename H4 into Hinv2_2; rename H6 into Hinv2_3.\n  assert (0 <= Znth u parents). { apply Hinv_4. auto. }\n  assert (Znth u parents <= size). { apply Hinv_4. auto. }\n  (*****We do as many props as we can here, especially the non-mst ones*****)\n  assert (Hperm_g: Permutation (popped_vertices +:: u ++ remove V_EqDec u unpopped_vertices) (VList g)). {\n    assert (NoDup unpopped_vertices). apply (NoDup_app_r V popped_vertices). apply (Permutation_NoDup (l:=VList g)). apply Permutation_sym; auto.\n    apply NoDup_VList.\n    rewrite <- app_assoc. simpl. apply (Permutation_trans (l':=popped_vertices++unpopped_vertices)).\n    apply Permutation_app_head. apply NoDup_Permutation. apply NoDup_cons. apply remove_In.\n    apply nodup_remove_nodup. auto. auto. intros; split; intros.\n    destruct H6. subst x. auto. rewrite remove_In_iff in H6. apply H6.\n    destruct (V_EqDec x u). unfold Equivalence.equiv in e. subst x. left; auto.\n    unfold RelationClasses.complement, Equivalence.equiv in c. right. rewrite remove_In_iff. split; auto.\n    auto.\n  }\n  assert (Hparents_bound: forall v : Z, 0 <= v < size -> 0 <= Znth v parents' <= size). {\n    intros. destruct (adjacent_dec g u v). destruct (in_dec Z.eq_dec v (popped_vertices +::u)).\n    replace (Znth v parents') with (Znth v parents). 2: symmetry; apply Hinv2_1; auto. apply Hinv_4; auto.\n    replace (Znth v parents') with (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents).\n    2: symmetry; apply (Hinv2_2 v); auto. rewrite <- (@graph_to_mat_eq size); auto.\n    destruct (Znth u (Znth v (@graph_to_symm_mat size g)) <? Znth v upd_pq_state) eqn:bool. lia. apply Hinv_4; auto.\n    replace (Znth v parents') with (Znth v parents). 2: symmetry; apply Hinv2_1; auto. apply Hinv_4; auto.\n  }\n  assert (Hkeys': forall v : Z, 0 <= v < size -> Znth v keys' = (if V_EqDec v r then 0 else elabel g (eformat (v, Znth v parents')))). {\n    intros. destruct (adjacent_dec g u v). destruct (in_dec Z.eq_dec v (popped_vertices +::u)).\n    ****\n    replace (Znth v keys') with (Znth v keys). 2: symmetry; apply Hinv2_1; auto. rewrite Hinv_5.\n    replace (Znth v parents') with (Znth v parents). 2: symmetry; apply Hinv2_1; auto. auto. auto.\n    ****\n    replace (Znth v keys') with (Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state)). 2: symmetry; apply Hinv2_2; auto.\n    replace (Znth v parents') with (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents). 2: symmetry; apply Hinv2_2; auto.\n    destruct (V_EqDec v r). hnf in e.\n    (*v=r*) subst v. destruct popped_vertices. exfalso. apply n. apply in_or_app; right; left. apply Hur; auto.\n    assert (hd_error (v :: popped_vertices) = Some r). apply Hr2. unfold not; intros. inversion H7. inversion H7. subst v.\n    exfalso. apply n. apply in_or_app; left; left; auto.\n    (*v <> r*)\n    rewrite <- (@graph_to_mat_eq size) by lia. destruct (Znth u (Znth v (@graph_to_symm_mat size g)) <? Znth v upd_pq_state) eqn:bool.\n    rewrite graph_to_mat_eq by lia. rewrite graph_to_mat_eq in bool by lia. rewrite Z.ltb_lt in bool. rewrite Zlt_Zmin by auto. rewrite eformat_symm; auto.\n    rewrite graph_to_mat_eq by lia. rewrite graph_to_mat_eq in bool by lia. rewrite Z.ltb_ge in bool. rewrite Z.min_r by auto.\n    unfold upd_pq_state. destruct (Z.eq_dec v u). subst v. exfalso; apply n. apply in_or_app; right; left; auto.\n    rewrite upd_Znth_diff. rewrite Hinv_6 by lia. destruct (in_dec V_EqDec v popped_vertices). exfalso; apply n. apply in_or_app; left; auto.\n    rewrite Hinv_5 by lia. destruct (V_EqDec v r). contradiction. auto.\n    replace (Zlength pq_state) with size by lia. lia.\n    replace (Zlength pq_state) with size by lia. lia. auto.\n    ****\n    replace (Znth v keys') with (Znth v keys). 2: symmetry; apply Hinv2_1; auto. rewrite Hinv_5.\n    replace (Znth v parents') with (Znth v parents). 2: symmetry; apply Hinv2_1; auto. auto. auto.\n  }\n  assert (Hpq_state': forall v : Z, 0 <= v < size -> Znth v pq_state' = (if in_dec V_EqDec v (popped_vertices +:: u) then inf + 1 else Znth v keys')). {\n    intros. destruct (in_dec V_EqDec v (popped_vertices +:: u)).\n    replace (Znth v pq_state') with (Znth v upd_pq_state). 2: symmetry; apply Hinv2_1; auto. unfold upd_pq_state.\n    apply in_app_or in i; destruct i.\n    rewrite upd_Znth_diff. rewrite Hinv_6 by lia. destruct (in_dec V_EqDec v popped_vertices). auto. contradiction.\n    replace (Zlength pq_state) with size; lia. replace (Zlength pq_state) with size; lia.\n    unfold not; intros; subst v. contradiction.\n    destruct H6. subst v. rewrite upd_Znth_same. auto. replace (Zlength pq_state) with size; lia.\n    contradiction.\n    destruct (adjacent_dec g u v).\n    (*second case*)\n    replace (Znth v pq_state') with (Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state)). 2: symmetry; apply Hinv2_2; auto.\n    replace (Znth v keys') with (Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state)). 2: symmetry; apply Hinv2_2; auto.\n    auto.\n    (*third case*)\n    replace (Znth v pq_state') with (Znth v upd_pq_state). 2: symmetry; apply Hinv2_1; auto. unfold upd_pq_state.\n    rewrite upd_Znth_diff. rewrite Hinv_6 by lia. destruct (in_dec V_EqDec v popped_vertices).\n    exfalso; apply n. apply in_or_app; left; auto.\n    symmetry; apply Hinv2_1; auto. unfold upd_pq_state.\n    replace (Zlength pq_state) with size; lia. replace (Zlength pq_state) with size; lia.\n    unfold not; intros. subst v. apply n. apply in_or_app; right; left; auto.\n  }\n  assert (Hpopped_nil: popped_vertices +:: u = [] -> r = find pq_state' (fold_right Z.min (hd 0 pq_state') pq_state') 0). {\n    intros. assert (In u (popped_vertices+::u)). apply in_or_app; right; left; auto.\n    rewrite H5 in H6. contradiction.\n  }\n  assert (Hpopped_unnil: popped_vertices +:: u <> [] -> hd_error (popped_vertices +:: u) = Some r). {\n    intros. destruct popped_vertices. rewrite Hur; auto.\n    apply hd_error_app. rewrite Hr2; auto. unfold not; intros. inversion H6.\n  }\n  assert (Hheavy: forall v : Z, 0 <= v < size -> 0 <= Znth v parents' < size ->\n    evalid g (eformat (v, Znth v parents')) /\\\n    (exists i : Z, 0 <= i < Zlength (popped_vertices +:: u) /\\\n      Znth i (popped_vertices +:: u) = Znth v parents' /\\\n      i < find (popped_vertices+::u) v 0)\n    /\\ (forall u0 : V,\n     In u0 (sublist 0 (find (popped_vertices +:: u) v 0) (popped_vertices +:: u)) ->\n     elabel g (eformat (v, Znth v parents')) <= elabel g (eformat (u0, v)))). {\n    intros. (*the main issue is u and unpopped; popped_vertices is an application of Hinv2_1 and Hinv_7*)\n    destruct (in_dec V_EqDec v (popped_vertices+::u)).\n    (*v in popped_vertices+::u*)\n    replace (Znth v parents') with (Znth v parents). 2: symmetry; apply Hinv2_1; auto.\n    replace (Znth v parents') with (Znth v parents) in H6. 2: symmetry; apply Hinv2_1; auto.\n    destruct (Hinv_7 v H5 H6). destruct H8 as [[j [? ?]] ?].\n    split. auto. split. exists j. split.\n    rewrite Zlength_app. rewrite Zlength_cons, Zlength_nil. lia.\n    split. rewrite app_Znth1 by lia. apply H9.\n    destruct H9. apply (Z.lt_le_trans _ (find popped_vertices v 0)). auto. apply find_app_le.\n    intros.\n    apply H10. rewrite sublist_app1 in H11. auto.\n    2: { split. lia. apply (find_range_gen (popped_vertices+::u) v 0). auto. lia. }\n    2: { assert (0 <= find (popped_vertices +:: u) v 0 < Zlength (popped_vertices +:: u)).\n        apply (find_range (popped_vertices+::u) v). auto. rewrite Zlength_app, Zlength_cons, Zlength_nil in H12. lia. }\n    destruct (V_EqDec v u).\n    (*subcase v = u*) hnf in e. subst v.\n    replace (find (popped_vertices +:: u) u 0) with (Zlength popped_vertices) in H11.\n    replace (find popped_vertices u 0) with (Zlength popped_vertices). auto.\n    rewrite find_notIn_0; auto.\n    rewrite find_app_notIn1. rewrite find_cons. rewrite Z.add_0_r. auto. auto.\n    (*subcase v <> u*) unfold RelationClasses.complement, Equivalence.equiv in c.\n    assert (In v popped_vertices). apply in_app_or in i; destruct i. auto. destruct H12. symmetry in H12; contradiction. contradiction.\n    replace (find (popped_vertices +:: u) v 0) with (find popped_vertices v 0) in H11. auto.\n    symmetry; apply find_app_In1. auto.\n    (*****NOT IN POPPED_VERTICES+::U*****)\n    assert (In v (remove V_EqDec u unpopped_vertices)). destruct (Hpopped_or_unpopped v). rewrite vert_bound; auto.\n    exfalso; apply n; apply in_or_app; left; auto. rewrite remove_In_iff. split. auto. unfold not; intros.\n    subst v. apply n; apply in_or_app; right; left; auto.\n    destruct (adjacent_dec g u v).\n    (*adjacent*)\n    replace (Znth v parents') with (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents).\n    2: symmetry; apply Hinv2_2; auto.\n    replace (Znth v parents') with (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents) in H6.\n    2: symmetry; apply Hinv2_2; auto.\n    rewrite <- ((@graph_to_mat_eq size) g u v) in * by lia.\n    destruct (Znth u (Znth v (@graph_to_symm_mat size g)) <? Znth v upd_pq_state) eqn: bool.\n    (*smaller, updated: u is the new parent*)\n      rewrite Z.ltb_lt in bool. split. rewrite eformat_symm. apply eformat_adj. auto.\n      split. exists (Zlength popped_vertices). split. rewrite Zlength_app, Zlength_cons, Zlength_nil.\n      split. apply Zlength_nonneg. lia. rewrite Znth_app2 by lia. rewrite Z.sub_diag, Znth_0_cons.\n      split. auto. rewrite find_notIn by auto. rewrite Zlength_app, Zlength_cons, Zlength_nil. lia.\n      intros.\n      assert (v <> u). unfold not; intros. subst v. apply n. apply in_or_app; right; left; auto.\n      rewrite sublist_same in H9. 2: auto. 2: { rewrite find_notIn, Z.add_0_r. auto. auto. }\n      apply in_app_or in H9; destruct H9.\n      rewrite eformat_symm, <- (@graph_to_mat_eq size) by lia.\n      unfold upd_pq_state in bool.\n      rewrite upd_Znth_diff in bool. 2: replace (Zlength pq_state) with size; lia.\n      2: replace (Zlength pq_state) with size; lia. 2: auto.\n      rewrite Hinv_6 in bool. 2: lia. destruct (in_dec V_EqDec v popped_vertices).\n      exfalso. apply n. apply in_or_app; left; auto.\n      rewrite Hinv_5 in bool by lia. destruct (V_EqDec v r). hnf in e; subst v.\n      destruct popped_vertices. exfalso; apply H10; symmetry; apply Hur. auto.\n      assert (hd_error (v :: popped_vertices) = Some r). apply Hr2. unfold not; intros; inversion H11.\n      inversion H11. subst v. exfalso; apply n. apply in_or_app; left; left; auto.\n      (*now check whether Znth v parents is size or lower.\n        If < size, use Hinv_7 to show that eformat(u0,v) must be bigger than parents.\n        If size, use Hinv_8 to derive that eformat(u0,v) is invalid.\n        *)\n      assert (Htmp: Znth v parents <= size). apply Hinv_4. lia. apply Z.le_lteq in Htmp; destruct Htmp.\n      assert (elabel g (eformat (v, Znth v parents)) <= elabel g (eformat (u0, v))). { apply (Hinv_7 v). lia.\n        split. apply Hinv_4. lia. lia. rewrite find_notIn, Z.add_0_r, sublist_same. auto. auto. auto.\n        unfold not; intros; apply n; apply in_or_app; left; auto.\n      }\n      apply (Z.le_trans _ (elabel g (eformat (v, Znth v parents)))). lia. lia.\n      (*Znth v parents = size. So elabel = inf, meaning it should not be connected to u0 by Hinv_8*)\n      assert (~ evalid g (eformat (u0, v))). {\n        unfold not; intros. rewrite <- eformat_adj in H12.\n        assert (~ adjacent g u0 v). apply Hinv_8. lia. lia.\n        rewrite find_notIn, Z.add_0_r by auto. rewrite sublist_same by auto. auto.\n        contradiction.\n      }\n      apply (invalid_edge_weight g) in H12.\n      replace (elabel g (eformat (u0, v))) with inf by trivial.\n      rewrite graph_to_mat_eq by lia. apply (weight_inf_bound).\n      (*u0 = u.*)\n      destruct H9. 2: contradiction. subst u0.\n      rewrite eformat_symm. apply Z.eq_le_incl. reflexivity.\n    (*case not smaller, so parent remains the same. Use Hinv_7*)\n    assert (Htmp: 0 <= Znth v parents < size). apply H6.\n    apply Hinv_7 in Htmp. 2: lia. destruct Htmp. destruct H10 as [[j [? ?]] ?].\n    split. auto. split. exists j. split. rewrite Zlength_app, Zlength_cons, Zlength_nil. lia.\n    split. rewrite Znth_app1 by lia. apply H11.\n    destruct H11. apply (Z.lt_le_trans _ (find popped_vertices v 0)). auto. apply find_app_le.\n    intros. rewrite find_notIn in H13 by auto. rewrite sublist_same in H13. 2: auto. 2: rewrite Z.add_0_r; auto.\n    apply in_app_or in H13. destruct H13. apply H12. rewrite find_notIn. rewrite Z.add_0_r, sublist_same by auto.\n    auto. unfold not; intros; apply n. apply in_or_app; left; auto.\n    destruct H13. 2: contradiction. subst u0.\n    (*use bool*)\n    unfold upd_pq_state in bool. rewrite Z.ltb_ge in bool.\n    destruct (V_EqDec u v).\n      (*v=u.*)\n      hnf in e; subst v. rewrite upd_Znth_same in bool.\n      2: replace (Zlength pq_state) with size; lia.\n      pose proof (weight_inf_bound g (eformat (u, u))). rewrite <- (@graph_to_mat_eq size) in H13 by lia.\n      lia.\n      (*v<>u*)\n      unfold RelationClasses.complement, Equivalence.equiv in c. rewrite upd_Znth_diff in bool.\n      2: replace (Zlength pq_state) with size; lia. 2: replace (Zlength pq_state) with size; lia.\n      2: auto.\n      rewrite Hinv_6 in bool by lia. destruct (in_dec V_EqDec v popped_vertices). exfalso; apply n; apply in_or_app; left; auto.\n      rewrite Hinv_5 in bool by lia. destruct (V_EqDec v r).\n      (*v=r*)hnf in e; subst v. (*hm...*)\n      exfalso; apply n. apply hd_error_In. apply Hpopped_unnil. unfold not; intros.\n      assert (In u (popped_vertices+::u)). apply in_or_app; right; left; auto. rewrite H13 in H14; contradiction.\n      (*v<>r*)\n      rewrite graph_to_mat_eq in bool by lia. apply bool.\n    (*finally, non adjacent*)\n    replace (Znth v parents') with (Znth v parents). 2: symmetry; apply Hinv2_1; auto.\n    replace (Znth v parents') with (Znth v parents) in H6. 2: symmetry; apply Hinv2_1; auto.\n    destruct (Hinv_7 v H5 H6). destruct H10 as [[j [? ?]] ?].\n    split. auto. split. exists j. split.\n    rewrite Zlength_app. rewrite Zlength_cons, Zlength_nil. lia.\n    split. rewrite app_Znth1 by lia. apply H11.\n    destruct H11. apply (Z.lt_le_trans _ (find popped_vertices v 0)). auto. apply find_app_le.\n    intros. rewrite find_notIn in H13 by auto. rewrite Z.add_0_r, sublist_same in H13 by auto.\n    apply in_app_or in H13. destruct H13. apply H12.\n    rewrite find_notIn. rewrite Z.add_0_r, sublist_same by auto.\n    auto. unfold not; intros; apply n. apply in_or_app; left; auto.\n    destruct H13. 2: contradiction. subst u0.\n    (*but elabel g (eformat (u,v)) = inf because it's invalid*)\n    assert (~ evalid g (eformat (u,v))). unfold not; intros; apply H8. rewrite eformat_adj; auto.\n    apply (invalid_edge_weight g) in H13.\n    repeat rewrite <- (@graph_to_mat_eq size) by lia.\n    replace (Znth u (Znth v (@graph_to_symm_mat size g))) with inf.\n    rewrite graph_to_mat_eq by lia. apply weight_inf_bound.\n    rewrite <- (@graph_to_mat_eq size) in H13 by lia.\n    symmetry. assumption. \n  }\n  assert (Hheavy2: forall v : Z, 0 <= v < size -> Znth v parents' = size ->\n    forall u0 : V, In u0 (sublist 0 (find (popped_vertices +:: u) v 0) (popped_vertices +:: u)) ->\n    ~ adjacent g u0 v). {\n    intros. destruct (in_dec V_EqDec v (popped_vertices+::u)).\n    apply in_app_or in i; destruct i.\n    rewrite find_app_In1 in H7 by auto. rewrite sublist_app1 in H7.\n    2: pose proof (find_lbound popped_vertices v 0); lia.\n    2: { rewrite find_ubound, Z.add_0_r. apply Z.le_refl. }\n    apply Hinv_8. lia. 2: auto.\n    replace (Znth v parents) with (Znth v parents'). auto. apply Hinv2_1. lia.\n    right; apply in_or_app; left; auto.\n    (*v=u, pretty much same deal*)\n    destruct H8. 2: contradiction. subst v. rewrite find_app_notIn1, find_cons, Z.add_0_r in H7 by auto.\n    rewrite sublist_app1 in H7. 2: { pose proof (Zlength_nonneg popped_vertices). split. lia. auto. }\n    2: apply Z.le_refl.\n    (*rewrite sublist_same in H7 by auto.*)\n    apply Hinv_8. lia. replace (Znth u parents) with (Znth u parents'); auto.\n    rewrite find_notIn_0; auto.\n    (*v unpopped, means u0 in popped or u0=u. Former: Hinv_8. Latter:?*)\n    rewrite find_notIn, Z.add_0_r, sublist_same in H7 by auto.\n    apply in_app_or in H7; destruct H7.\n    destruct (adjacent_dec g u v).\n    replace (Znth v parents') with (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents) in H6.\n    2: { symmetry; apply Hinv2_2; auto. }\n    rewrite <- (@graph_to_mat_eq size) in H6 by lia. destruct (Znth u (Znth v (@graph_to_symm_mat size g)) <? Znth v upd_pq_state).\n    assert (vvalid g u). apply adjacent_requires_vvalid in H8. apply H8. rewrite vert_bound in H9. lia.\n    apply Hinv_8. lia. lia. rewrite find_notIn_0, sublist_same; auto.\n    unfold not; intros; apply n; apply in_or_app; left; auto.\n    (*not adjacent: rewrite parents' into parents*)\n    replace (Znth v parents') with (Znth v parents) in H6. 2: { symmetry; apply Hinv2_1. lia. auto. }\n    apply Hinv_8. lia. lia. rewrite find_notIn_0, sublist_same; auto.\n    unfold not; intros; apply n; apply in_or_app; left; auto.\n    (*u0=u*)\n    destruct H7. 2: contradiction. subst u0.\n    destruct (adjacent_dec g u v). 2: auto.\n    replace (Znth v parents') with (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents) in H6.\n    2: { symmetry; apply Hinv2_2; auto. }\n    rewrite <- (@graph_to_mat_eq size) in H6 by lia. destruct (Znth u (Znth v (@graph_to_symm_mat size g)) <? Znth v upd_pq_state) eqn:bool.\n    assert (vvalid g u). apply adjacent_requires_vvalid in H7. apply H7. rewrite vert_bound in H8. lia.\n    rewrite eformat_adj, evalid_inf_iff, <- (@graph_to_mat_eq size) in H7 by lia.\n    rewrite Z.ltb_ge in bool. unfold upd_pq_state in bool.\n    rewrite upd_Znth_diff in bool. rewrite Hinv_6 in bool by lia.\n    destruct (in_dec V_EqDec v popped_vertices). exfalso; apply n; apply in_or_app; left; auto.\n    rewrite Hinv_5 in bool by lia. destruct (V_EqDec v r).\n    hnf in e; subst v. exfalso; apply n. apply hd_error_In. apply Hpopped_unnil.\n    unfold not; intros. assert (In u (popped_vertices+::u)). apply in_or_app; right; left; auto.\n    rewrite H8 in H9; contradiction.\n    assert (elabel g (eformat (v,Znth v parents)) = inf). apply (invalid_edge_weight g).\n    unfold not; intros. apply eformat_evalid_vvalid in H8. destruct H8. rewrite H6 in H9. rewrite vert_bound in H9. lia.\n    rewrite H8 in bool. lia.\n    replace (Zlength pq_state) with size; lia.\n    replace (Zlength pq_state) with size; lia.\n    unfold not; intros; subst v. apply n; apply in_or_app; right; left; auto.\n  }\n  assert (Hweight: forall v u1 u2 : V,\n          In v (popped_vertices +:: u) ->\n          0 <= Znth v parents' < size ->\n          vvalid g u2 ->\n          In u1 (sublist 0 (find (popped_vertices +:: u) v 0) (popped_vertices +:: u)) ->\n          ~ In u2 (sublist 0 (find (popped_vertices +:: u) v 0) (popped_vertices +:: u)) ->\n          elabel g (eformat (v, Znth v parents')) <= elabel g (eformat (u1, u2))\n  ). { intros.\n    assert (0 <= v < size). {\n      apply in_app_or in H5. destruct H5. rewrite <- (vert_bound g). apply Hpopped_vvalid. auto.\n      destruct H5. 2: contradiction. subst u; auto. }\n    replace (Znth v parents') with (Znth v parents) in *. 2: { symmetry; apply (Hinv2_1 v); auto. }\n    apply in_app_or in H5. destruct H5.\n    (*case was already in popped vertices*)\n    rewrite find_app_In1 in H8, H9 by auto. rewrite sublist_app1 in H8, H9.\n      2: pose proof (find_lbound popped_vertices v 0); lia.\n      2: { pose proof (find_ubound popped_vertices v 0). rewrite Z.add_0_r in H11. auto. }\n      2: pose proof (find_lbound popped_vertices v 0); lia.\n      2: { pose proof (find_ubound popped_vertices v 0). rewrite Z.add_0_r in H11. auto. }\n    apply Hinv_14; auto.\n    (*case v = u*)\n    destruct H5. 2: contradiction. subst v.\n    assert ((sublist 0 (find (popped_vertices +:: u) u 0) (popped_vertices +:: u)) =\n      (popped_vertices)).\n    { rewrite find_app_notIn1, find_cons, Z.add_0_r by auto.\n         rewrite sublist_app1, sublist_same. auto. auto. auto.\n          pose proof (Zlength_nonneg popped_vertices). split. lia. auto.\n          apply Z.le_refl.\n    } rewrite H5 in H9, H8.\n    (*make use of Hu_min\n      case u2 = u: then apply Hheavy, done (guess it wasn't useless after all)\n      case u2 <> u: then by Hu_min, Znth u pq_state <= Znth u2 pq_state\n        u2 is unpopped, so by Hinv_6, Znth u2 pq_state = Znth v keys\n        u2 can't be r, so by Hinv_5, Znth v keys = elabel g (eformat (u2, Znth u2 parents))\n        ===> Znth u pq_state <= elabel g (eformat (u2, Znth u2 parents))\n        using Hheavy again? and Z.le_trans, Znth u pq_state <= elabel g (eformat (u1, u2))\n        subcase u = r a.k.a. popped_vertices = []: then contradiction on u1 being in empty\n        Then Znth u pq_state = Znth v keys = elabel g (eformat (u,Znth u parents)). Apply\n    *)\n    destruct (V_EqDec u2 u). hnf in e. subst u2.\n    assert ((forall u0 : V,\n          In u0 (sublist 0 (find (popped_vertices +:: u) u 0) (popped_vertices +:: u)) ->\n          elabel g (eformat (u, Znth u parents')) <= elabel g (eformat (u0, u)))).\n    apply Hheavy; lia. rewrite Hu_parents in H11. apply H11. rewrite H5. auto.\n    rewrite vert_bound in H7. assert (vvalid g u1). apply Hpopped_vvalid; auto. rewrite vert_bound in H11.\n    assert (0 <= Znth u2 parents <= size). apply Hinv_4; lia. destruct H12.\n    apply Z.le_lteq in H13. destruct H13.\n    2: { assert (~ adjacent g u1 u2). apply Hinv_8. lia. lia.\n          rewrite find_notIn, Z.add_0_r, sublist_same by auto. auto.\n        rewrite eformat_adj in H14. apply (invalid_edge_weight g) in H14.\n        replace (elabel g (eformat (u1, u2))) with inf\n          by trivial.\n        apply weight_inf_bound. }\n    (*u2 <> u*) unfold RelationClasses.complement, Equivalence.equiv in c.\n    assert (Znth u pq_state <= Znth u2 pq_state). apply Hu_min; lia.\n    rewrite (Hinv_6 u2) in H14 by lia. destruct (in_dec V_EqDec u2 popped_vertices). contradiction.\n    clear n. rewrite Hinv_5 in H14. destruct (V_EqDec u2 r).\n    hnf in e. subst u2. destruct popped_vertices. contradiction. exfalso; apply H9.\n    apply hd_error_In. apply Hr2. unfold not; intros. assert (In v (v::popped_vertices)) by (left; auto).\n    rewrite H15 in H16; contradiction.\n    unfold RelationClasses.complement, Equivalence.equiv in c0.\n    assert (elabel g (eformat (u2, Znth u2 parents)) <= elabel g (eformat (u1,u2))).\n      apply Hinv_7. lia. lia. rewrite find_notIn, Z.add_0_r, sublist_same by auto. auto. 2: auto.\n    apply (Z.le_trans _ (elabel g (eformat (u2, Znth u2 parents)))). 2: auto.\n    apply (Z.le_trans _ (Znth u pq_state)). 2: auto.\n    clear H14 H15.\n    rewrite Hinv_6 by lia. destruct (in_dec V_EqDec u popped_vertices). contradiction.\n    rewrite Hinv_5 by lia. destruct (V_EqDec u r).\n    hnf in e; subst u. destruct popped_vertices. contradiction. exfalso; apply n.\n    apply hd_error_In. apply Hr2. unfold not; intros. assert (In v (v::popped_vertices)). left; auto.\n    rewrite H14 in H15; contradiction.\n    apply Z.le_refl.\n  }\n  (*now split into cases*)\n  apply Z.le_lteq in H4. destruct H4.\n  ++ (*adde case*)\n  assert (vvalid mst' u). apply vert_bound. lia.\n  assert (vvalid mst' (Znth u parents)). apply vert_bound. lia.\n  assert (evalid g (eformat (u,(Znth u parents)))). apply Hinv_7; lia.\n  assert (Hfst: vvalid mst' (fst (eformat (u,(Znth u parents))))). {\n    destruct (Z.le_ge_cases u (Znth u parents)). rewrite eformat1; simpl; auto.\n    rewrite eformat2; simpl; auto.\n  }\n  assert (Hsnd: vvalid mst' (snd (eformat (u,(Znth u parents))))). {\n    destruct (Z.le_ge_cases u (Znth u parents)). rewrite eformat1; simpl; auto.\n    rewrite eformat2; simpl; auto.\n  }\n  assert (Hfst_le_snd: (fst (eformat (u,Znth u parents))) <= (snd (eformat (u,Znth u parents)))). {\n    destruct (Z.le_ge_cases u (Znth u parents)). rewrite eformat1; simpl; auto.\n    rewrite eformat2; simpl; auto.\n  }\n  assert (Int.min_signed <= elabel g (eformat (u,(Znth u parents))) < inf). {\n    split. apply weight_representable. apply evalid_inf_iff; auto.\n  }\n  assert (Hu_evalid: ~ evalid mst' (eformat (u,(Znth u parents)))). {\n    unfold not; intros. apply (Hinv_13 u (Znth u parents)).\n    auto. rewrite eformat_adj. auto.\n  }\n  assert (Huparents_popped: In (Znth u parents) popped_vertices). {\n    assert (exists i : Z, 0 <= i < Zlength (popped_vertices) /\\\n      Znth i (popped_vertices) = Znth u parents /\\ i < find popped_vertices u 0).\n    apply Hinv_7; lia. destruct H9 as [i [? [? ?]]]. rewrite <- H10. apply Znth_In. lia.\n  }\n  assert (Huparents_unpopped: ~ In (Znth u parents) unpopped_vertices). {\n    apply (NoDup_app_not_in V popped_vertices). apply (Permutation_NoDup (l:=VList g)).\n    apply Permutation_sym; apply Hinv_3. apply NoDup_VList. auto.\n  }\n  set (adde_u:=adde mst' (fst (eformat (u,Znth u parents))) (snd (eformat (u,Znth u parents))) Hfst Hsnd Hfst_le_snd (elabel g (eformat (u,(Znth u parents)))) H8).\n  Exists (adde_u).\n  Exists (finGraph adde_u).\n  Exists parents' keys' pq_state' (popped_vertices+::u) (remove V_EqDec u unpopped_vertices).\n  assert (HM: exists M : UAdjMatGG, minimum_spanning_forest M g /\\ is_partial_lgraph adde_u M). {\n    destruct Hinv_15 as [M [Hmsf_M Hpartial_M]]. pose proof (finGraph M).\n    destruct (evalid_dec M (eformat (u, Znth u parents))).\n    ****\n      exists M. split. auto. apply adde_partial_lgraph; auto. rewrite <- surjective_pairing; auto.\n      rewrite <- surjective_pairing. symmetry. apply Hmsf_M; auto.\n    ****\n      set (a:=eformat (u, Znth u parents)) in *.\n      (*find a corresponding edge b in M, show that elabel g a <= elabel g b\n        Then do a swap\n      *)\n      assert (connected M (Znth u parents) u). apply Hmsf_M. apply adjacent_connected. exists a.\n        split. apply (evalid_strong_evalid g); auto.\n        rewrite (edge_src_fst g), (edge_dst_snd g); auto.\n        unfold a; destruct (Z.le_ge_cases u (Znth u parents)). rewrite eformat1 by (simpl; auto).\n        simpl. right. auto.\n        rewrite eformat2 by (simpl; auto). simpl. left; auto.\n      destruct H9 as [p ?].\n      (*for convenience's sake, simplify*)\n      apply (connected_by_upath_exists_simple_upath) in H9. clear p. destruct H9 as [p [? ?]].\n      (*since Znth u parents is in popped and u isn't, use the partition to find a v1 v2*)\n      pose proof (finGraph M) as fM.\n      assert (exists l, fits_upath M l p). apply connected_exists_list_edges in H9; auto. destruct H11 as [l Hl].\n      assert (exists v1 v2, In v1 p /\\ In v2 p /\\ In v1 popped_vertices /\\ ~ In v2 popped_vertices /\\ (exists e, adj_edge M e v1 v2 /\\ In e l)).\n        apply (path_partition_checkpoint2 M popped_vertices p l (Znth u parents) u); auto.\n      destruct H11 as [v1 [v2 [? [? [? [? ?]]]]]].\n      destruct H15 as [b [Hc Hbl]]. assert (b = eformat (v1, v2)). {\n        destruct Hmsf_M. destruct H15. destruct H15. destruct H18. destruct H18. destruct H20. apply (H20 v1 v2 b (eformat (v1,v2))).\n        split. auto. apply eformat_adj'. rewrite <- eformat_adj. exists b; auto.\n      } subst b. assert (evalid M (eformat (v1,v2))). apply Hc.\n      assert (In v2 unpopped_vertices).\n        destruct (Hpopped_or_unpopped v2). rewrite vert_bound, <- (vert_bound M).\n        apply eformat_evalid_vvalid in H15; apply H15. contradiction. auto.\n      set (b:= eformat (v1,v2)) in *. clear Hc. assert (Hbl': In b l) by auto.\n      apply (fits_upath_split2 M p l b (Znth u parents) u) in Hbl'; auto.\n      destruct Hbl' as [p1 [p2 [l1 [l2 [Hp [Hp1p2 [Hl1 [Hl2 Hl']]]]]]]].\n      assert ((sublist 0 (find (popped_vertices +:: u) u 0) (popped_vertices +:: u)) = popped_vertices). {\n        rewrite find_app_notIn1, find_cons, Z.add_0_r by auto.\n        rewrite sublist_app1, sublist_same. auto. auto. auto.\n        pose proof (Zlength_nonneg popped_vertices). split. lia. auto.\n        apply Z.le_refl.\n      }\n      assert (elabel g a <= elabel g b). {\n        unfold b; unfold a. rewrite <- Hu_parents. apply Hweight; auto.\n        apply in_or_app; right; left; auto. rewrite Hu_parents; lia.\n        all: rewrite H17; auto.\n      } clear H17.\n      assert (~ evalid mst' b). {\n        unfold not; intros. rewrite <- EList_evalid in H17.\n        apply (Permutation_in (l':=(map (fun v : Z => eformat (v, Znth v parents))\n              (filter (fun v : Z => Znth v parents <? size) popped_vertices)))) in H17.\n        apply list_in_map_inv in H17. destruct H17 as [x [? ?]]. rewrite filter_In in H19. destruct H19.\n        assert (In (Znth x parents) popped_vertices). {\n          rewrite H17 in H15. apply eformat_evalid_vvalid in H15. do 2 rewrite vert_bound in H15.\n          assert ((exists i : Z,\n            0 <= i < Zlength popped_vertices /\\\n            Znth i popped_vertices = Znth x parents /\\ i < find popped_vertices x 0) /\\\n           (forall u : V,\n            In u (sublist 0 (find popped_vertices x 0) popped_vertices) ->\n            elabel g (eformat (x, Znth x parents)) <= elabel g (eformat (u, x)))). apply Hinv_7.\n          apply H15. apply H15. destruct H21. clear H22. destruct H21 as [i [? [? ?]]].\n          rewrite <- H22; apply Znth_In. lia.\n        }\n        (*now compare v1, v2, x, Znth x parents*)\n        unfold b in H17. apply eformat_eq in H17. destruct H17; destruct H17; subst v1; subst v2; contradiction.\n        apply Hinv_9.\n      }\n      clear Hinv_1 Hinv_2 Hinv_3 Hinv_4 Hinv_5 Hinv_6 Hinv_7 Hinv_8 Hinv_9 Hinv_10 Hr1 Hr2 Hinv_13 Hinv_14.\n      clear Hinv2_1 Hinv2_2 Hinv2_3 Hparents_bound Hkeys' Hpq_state' Hheavy Hheavy2 Hweight Hpopped_nil Hpopped_unnil.\n      clear Hpopped_or_unpopped Hpopped_vvalid Hunpopped_vvalid Hu_not_popped Hu_unpopped Hur Hu_min HZlength_parents HZlength_keys HZlength_pq_state Hu_parents Hu_keys Hu_pq_state Huparents_popped Huparents_unpopped.\n      set (remove_b:= eremove M b). (*huh, how come I don't need to provide evalid b?*)\n      assert (Ha_fst_vvalid: vvalid remove_b (fst a)). {\n        unfold a; simpl. destruct (Z.le_ge_cases u (Znth u parents)).\n        rewrite eformat1 by auto; simpl. rewrite vert_bound; lia.\n        rewrite eformat2 by auto; simpl. rewrite vert_bound; lia.\n      }\n      assert (Ha_snd_vvalid: vvalid remove_b (snd a)). {\n        unfold a; simpl. destruct (Z.le_ge_cases u (Znth u parents)).\n        rewrite eformat1 by auto; simpl. rewrite vert_bound; lia.\n        rewrite eformat2 by auto; simpl. rewrite vert_bound; lia.\n      }\n      assert (Ha_fst_le_snd: fst a <= snd a). {\n        unfold a; destruct (Z.le_ge_cases u (Znth u parents)).\n        rewrite eformat1; simpl; auto.\n        rewrite eformat2; simpl; auto.\n      }\n      set (w:=elabel g a).\n      assert (Ha_weight_bound: Int.min_signed <= w < inf). {\n        split. apply weight_representable. apply evalid_inf_iff; auto.\n      }\n      set (swap:=adde remove_b (fst a) (snd a) Ha_fst_vvalid Ha_snd_vvalid Ha_fst_le_snd w Ha_weight_bound).\n      assert (Hadde_partial_swap: is_partial_lgraph adde_u swap). {\n        unfold is_partial_lgraph; split. split. 2: split3.\n        intros. rewrite vert_bound; rewrite vert_bound in H19. lia.\n        intros. simpl. simpl in H19. simpl. unfold graph_gen.addValidFunc, graph_gen.removeValidFunc in *.\n        destruct H19. left. split. apply Hpartial_M. auto. unfold not; intros; subst e. contradiction. right; auto.\n        intros. rewrite (edge_src_fst swap); rewrite (edge_src_fst adde_u); auto.\n        intros. rewrite (edge_dst_snd swap); rewrite (edge_dst_snd adde_u); auto.\n        unfold preserve_vlabel, preserve_elabel; split; intros.\n        destruct vlabel. destruct vlabel. auto.\n        simpl. simpl in H19. unfold graph_gen.addValidFunc in H19. unfold graph_gen.update_elabel.\n        rewrite <- surjective_pairing.\n        unfold EquivDec.equiv_dec. destruct (E_EqDec a e). unfold w. auto.\n        unfold RelationClasses.complement, Equivalence.equiv in c. destruct H19.\n        destruct (E_EqDec e b). hnf in e0; subst e. contradiction.\n        apply Hpartial_M; auto.\n        rewrite <- surjective_pairing in H19; symmetry in H19; contradiction.\n      }\n      assert (NoDup l). apply (simple_upath_list_edges_NoDup M p l); auto.\n      assert (~ In b l1). { rewrite Hl' in H19.\n        assert (forall y, In y l1 -> ~ In y ([b] ++l2)). apply NoDup_app_not_in; auto.\n        unfold not; intros. apply H20 in H21. apply H21. apply in_or_app; left; left; auto.\n      }\n      assert (~ In b l2). { rewrite Hl' in H19. apply NoDup_app_r in H19.\n        unfold not; intros. apply (NoDup_app_not_in E [b] l2) in H21; auto. left; auto.\n      }\n      assert (Hp1l1_remove: fits_upath remove_b l1 p1). { apply (fits_upath_transfer' p1 l1 M).\n        intros. do 2 rewrite vert_bound; split; auto.\n        intros. simpl. unfold graph_gen.removeValidFunc.\n        split. apply (fits_upath_evalid M p1 l1); auto. unfold not; intros; subst e; contradiction.\n        intros. simpl. auto.\n        intros. simpl. auto.\n        auto.\n      }\n      assert (Hp2l2_remove: fits_upath remove_b l2 p2). { apply (fits_upath_transfer' p2 l2 M).\n        intros. do 2 rewrite vert_bound; split; auto.\n        intros. simpl. unfold graph_gen.addValidFunc, graph_gen.removeValidFunc.\n        split. apply (fits_upath_evalid M p2 l2); auto. unfold not; intros; subst e; contradiction.\n        intros. simpl. auto.\n        intros. simpl. auto.\n        auto.\n      }\n      assert (Hp1p2': (connected_by_path remove_b p1 (Znth u parents) (fst b) /\\ connected_by_path remove_b p2 (snd b) u) \\/\n        (connected_by_path remove_b p1 (Znth u parents) (snd b) /\\ connected_by_path remove_b p2 (fst b) u)). {\n        rewrite (edge_src_fst M), (edge_dst_snd M) in Hp1p2.\n        destruct Hp1p2; [left | right].\n        destruct H22. split. split. apply (fits_upath_valid_upath remove_b p1 l1); auto. apply H22.\n        split. apply (fits_upath_valid_upath remove_b p2 l2); auto. apply H23.\n        destruct H22. split. split. apply (fits_upath_valid_upath remove_b p1 l1); auto. apply H22.\n        split. apply (fits_upath_valid_upath remove_b p2 l2); auto. apply H23.\n      }\n      assert (labeled_spanning_uforest swap g). {\n        assert (is_partial_lgraph swap g). {\n          assert (Hedge_valid: forall e, evalid swap e -> evalid g e).\n          intros. simpl in H22. unfold graph_gen.addValidFunc, graph_gen.removeValidFunc in H22. destruct H22.\n          destruct H22. apply Hmsf_M. auto. rewrite <- surjective_pairing in H22. subst e. auto.\n          split. split. 2: split3.\n          intros. rewrite vert_bound; rewrite vert_bound in H22. lia. auto.\n          intros. rewrite (edge_src_fst swap), (edge_src_fst g); auto.\n          intros. rewrite (edge_dst_snd swap), (edge_dst_snd g); auto.\n          unfold preserve_vlabel, preserve_elabel; split; intros. destruct vlabel; destruct vlabel; auto.\n          simpl. unfold graph_gen.update_elabel, EquivDec.equiv_dec. rewrite <- surjective_pairing.\n          simpl in H22. unfold graph_gen.addValidFunc, graph_gen.removeValidFunc in H22.\n          destruct (E_EqDec a e). hnf in e0; subst e. unfold w; auto.\n          unfold RelationClasses.complement, Equivalence.equiv in c. destruct H22.\n          destruct H22. destruct (E_EqDec e b). hnf in e0; subst e. contradiction.\n          apply Hmsf_M; auto.\n          symmetry in H22; rewrite <- surjective_pairing in H22; contradiction.\n        }\n        assert (uforest' swap). {\n          assert (uforest' remove_b /\\ ~ connected remove_b (src M b) (dst M b)). {\n            apply remove_edge_uforest'. apply Hmsf_M. auto. }\n          destruct H23. rewrite (edge_src_fst M), (edge_dst_snd M) in H24.\n          apply add_edge_uforest'; auto.\n          unfold not; intros; destruct H25 as [pa ?]. apply H24. clear H24.\n          destruct Hp1p2'.\n          ++destruct H24. apply (connected_trans _ _ (Znth u parents)). apply connected_symm; exists p1; auto.\n            apply (connected_trans _ _ u). unfold a in H25. destruct (Z.le_ge_cases u (Znth u parents)).\n            rewrite eformat1 in H25 by auto. apply connected_symm; exists pa; apply H25.\n            rewrite eformat2 in H25 by auto. exists pa; apply H25.\n            apply connected_symm; exists p2; apply H26.\n          ++destruct H24. apply (connected_trans _ _ u). exists p2; auto.\n            apply (connected_trans _ _ (Znth u parents)). unfold a in H25. destruct (Z.le_ge_cases u (Znth u parents)).\n            rewrite eformat1 in H25 by auto. exists pa; apply H25.\n            rewrite eformat2 in H25 by auto. apply connected_symm; exists pa; apply H25.\n            exists p1; auto.\n        }\n        assert (Hremove_a: ~ evalid remove_b a). { unfold not; intros. apply n.\n          simpl in H24. unfold graph_gen.removeValidFunc in H24. apply H24. }\n        assert (Hswap_a: evalid swap a). { simpl. rewrite <- surjective_pairing.\n          unfold graph_gen.addValidFunc. right; auto. }\n        assert (Hconnected_b: connected swap (fst b) (snd b)). {\n          destruct Hp1p2'; destruct H24.\n          ++apply (connected_trans _ _ (Znth u parents)).\n          apply connected_symm; exists p1. split. 2: apply H24.\n          apply add_edge_valid_upath. rewrite <- surjective_pairing; auto. apply H24.\n          apply (connected_trans _ _ u). apply adjacent_connected. rewrite eformat_adj, eformat_symm. auto.\n          apply connected_symm; exists p2. split. 2: apply H25.\n          apply add_edge_valid_upath. rewrite <- surjective_pairing; auto. apply H25.\n          ++apply (connected_trans _ _ u).\n          exists p2. split. 2: apply H25.\n          apply add_edge_valid_upath. rewrite <- surjective_pairing; auto. apply H25.\n          apply (connected_trans _ _ (Znth u parents)). apply adjacent_connected. rewrite eformat_adj; auto.\n          exists p1. split. 2: apply H24.\n          apply add_edge_valid_upath. rewrite <- surjective_pairing; auto. apply H24.\n        } clear Hp1p2' Hp1p2.\n        split. split. apply H22. split. auto.\n        (*spanning*) { unfold spanning; intros x y.\n          split; intros. 2: apply (is_partial_lgraph_connected swap); auto.\n          apply Hmsf_M in H24.\n          destruct H24 as [p' ?]. apply (connected_by_upath_exists_simple_upath) in H24.\n          clear p'. destruct H24 as [p' [? ?]].\n          assert (exists l', fits_upath M l' p'). apply valid_upath_exists_list_edges. apply H24.\n          destruct H26 as [l' ?]. assert (NoDup l'). apply (simple_upath_list_edges_NoDup M p'); auto.\n          clear H H0 H1.\n          destruct (in_dec E_EqDec b l').\n          ++ (*b is in l', must take detour*)\n          assert (In b l'); auto. apply (fits_upath_split2 M p' l' b x y) in H; auto.\n          destruct H as [p1x [p2y [l1x [l2y [? [? [? [? ?]]]]]]]]. subst l'; subst p'.\n          rewrite (edge_src_fst M), (edge_dst_snd M) in H0.\n          assert (~ In b l1x). { unfold not; intros. apply (NoDup_app_not_in _ l1x ([b]++l2y) H27 b) in H. apply H. apply in_or_app; left; left; auto. }\n          assert (~ In b l2y). { apply NoDup_app_r in H27. apply (NoDup_app_not_in _ [b] l2y H27 b). left; auto. }\n          destruct H0; destruct H0.\n          ++++\n          apply (connected_trans _ _ (fst b)). exists p1x. split. 2: apply H0. apply add_edge_valid_upath.\n            rewrite <- surjective_pairing; auto. apply (remove_edge_valid_upath _ _ _ l1x); auto. apply H0.\n          apply (connected_trans _ _ (snd b)); auto.\n          exists p2y. split. 2: apply H30. apply add_edge_valid_upath. rewrite <- surjective_pairing; auto.\n          apply (remove_edge_valid_upath _ _ _ l2y); auto. apply H30.\n          ++++\n          apply (connected_trans _ _ (snd b)). exists p1x. split. 2: apply H0. apply add_edge_valid_upath.\n            rewrite <- surjective_pairing; auto. apply (remove_edge_valid_upath _ _ _ l1x); auto. apply H0.\n          apply (connected_trans _ _ (fst b)); apply connected_symm; auto.\n          apply connected_symm. exists p2y. split. 2: apply H30. apply add_edge_valid_upath. rewrite <- surjective_pairing; auto.\n          apply (remove_edge_valid_upath _ _ _ l2y); auto. apply H30.\n          ++ (*b isn't in l', transfer path*)\n          exists p'. split. 2: apply H24. apply add_edge_valid_upath. rewrite <- surjective_pairing; auto.\n          apply (remove_edge_valid_upath _ _ _ l'); auto. apply H24.\n        }\n        (*preserve labels*) unfold preserve_vlabel, preserve_elabel; split; intros.\n        destruct vlabel; destruct vlabel; auto.\n        simpl; simpl in H24. unfold graph_gen.addValidFunc, graph_gen.removeValidFunc in H24.\n        unfold graph_gen.update_elabel, EquivDec.equiv_dec.\n        rewrite <- surjective_pairing. rewrite <- surjective_pairing in H24.\n        destruct (E_EqDec a e). hnf in e0. subst e. unfold w; auto.\n        unfold RelationClasses.complement, Equivalence.equiv in c. destruct H24. 2: symmetry in H24; contradiction.\n        destruct H24. destruct (E_EqDec e b). hnf in e0; contradiction. apply Hmsf_M; auto.\n      }\n      exists swap. split; auto. apply (msf_if_le_msf' swap M g); auto.\n      unfold sum_DE, DEList. pose proof (finGraph swap) as fswap.\n      rewrite (map_ext_in (elabel swap) (elabel g)).\n      rewrite (map_ext_in (elabel M) (elabel g)).\n      rewrite (fold_left_comm _ (map (elabel g) (EList swap)) (map (elabel g) (a::(remove E_EqDec b (EList M))))).\n      simpl.\n      (**) {\n        set (k:=EList M).\n        rewrite fold_left_accum_Zadd.\n        rewrite fold_left_Zadd_map_remove. 2: unfold k; rewrite EList_evalid; auto. 2: unfold k; apply NoDup_EList.\n        apply (Z.le_trans _ (fold_left Z.add (map (elabel g) k) 0 - elabel g b + elabel g b)).\n        apply Zplus_le_compat_l. auto.\n        rewrite Z.sub_add. apply Z.eq_le_incl. (*and... I can't reflexivity!*)\n        apply fold_left_comm. intros; lia.\n        apply Permutation_map. unfold k. apply NoDup_Permutation. apply NoDup_EList. apply NoDup_EList.\n        intros. do 2 rewrite EList_evalid. split; intros; auto.\n      }\n      intros; lia.\n      apply Permutation_map. { apply NoDup_Permutation. apply NoDup_EList.\n        apply NoDup_cons. unfold not; intros. rewrite remove_In_iff in H23. destruct H23.\n        rewrite EList_evalid in H23. contradiction.\n        apply nodup_remove_nodup. apply NoDup_EList.\n        intros. rewrite EList_evalid; simpl; unfold graph_gen.addValidFunc, graph_gen.removeValidFunc.\n        rewrite remove_In_iff, EList_evalid, <- surjective_pairing. split; intros; destruct H23; auto.\n      }\n      { intros. rewrite EList_evalid in H23. apply Hmsf_M; auto. }\n      {  intros. rewrite EList_evalid in H23. apply H22; auto. }\n  }\n  assert (Hpartial: is_partial_lgraph adde_u g). {\n    apply adde_partial_lgraph. auto. rewrite <- surjective_pairing; auto. rewrite <- surjective_pairing; auto. }\n  assert (Huforest_adde: uforest' adde_u). {\n    apply add_edge_uforest'; auto.\n    unfold not; intros. destruct (Z.le_ge_cases u (Znth u parents)).\n      ****\n      rewrite eformat1 in *; try (simpl; lia).\n      destruct H9 as [p [? [? ?]]]. destruct p. inversion H11.\n      destruct p. inversion H11; inversion H12. subst v.\n      rewrite H15 in Hu_unpopped; contradiction.\n      destruct H9. inversion H11. subst v.\n      apply (Hinv_13 u v0). auto. apply H9.\n      ****\n      rewrite eformat2 in *; try (simpl; lia).\n      simpl in H9. apply connected_symm in H9.\n      destruct H9 as [p [? [? ?]]]. destruct p. inversion H11.\n      destruct p. inversion H11; inversion H12. subst v.\n      rewrite H15 in Hu_unpopped; contradiction.\n      destruct H9. inversion H11. subst v.\n      apply (Hinv_13 u v0). auto. apply H9.\n  }\n  assert (Hu_new: evalid adde_u (eformat (u, Znth u parents))). {\n    simpl. unfold graph_gen.addValidFunc. right; rewrite <- surjective_pairing. auto. }\n  assert (Hsrc: src adde_u (eformat (u, Znth u parents)) = fst (eformat (u, Znth u parents))). {\n    apply (edge_src_fst adde_u). }\n  assert (Hdst: dst adde_u (eformat (u, Znth u parents)) = snd (eformat (u, Znth u parents))). {\n    apply (edge_dst_snd adde_u). }\n  assert (Hnot_adj: forall u0 v : V, In u0 (remove V_EqDec u unpopped_vertices) -> ~ adjacent adde_u u0 v). {\n    intros. rewrite remove_In_iff in H9; destruct H9.\n    assert (~ adjacent mst' u0 v). apply Hinv_13. auto.\n    unfold not; intros. destruct H12 as [e ?]. destruct (E_EqDec (eformat (u,Znth u parents)) e).\n    hnf in e0. subst e.\n    destruct H12. rewrite Hsrc, Hdst in H13.\n    destruct (Z.le_ge_cases u (Znth u parents)).\n      rewrite eformat1 in H13 by (simpl; lia). simpl in H13.\n      destruct H13; destruct H13. symmetry in H13; contradiction.\n      subst u0. contradiction.\n      rewrite eformat2 in H13 by (simpl; lia). simpl in H13.\n      destruct H13; destruct H13. subst u0; contradiction.\n      symmetry in H15; contradiction.\n    unfold RelationClasses.complement, Equivalence.equiv in c. apply H11.\n    exists e. apply add_edge_adj_edge2 in H12; auto.\n    rewrite <- surjective_pairing; auto.\n  }\n  assert (Hconnnected: (forall u0 v : V,\n    In u0 (popped_vertices +:: u) ->\n    In v (popped_vertices +:: u) -> connected g u0 v <-> connected adde_u u0 v)). {\n    intros. apply in_app_or in H9; apply in_app_or in H10. destruct H9; destruct H10.\n    ****(*both in popped vertices, reuse invariant*)\n        split; intros.\n        apply Hinv_10 in H11; auto. apply add_edge_connected; auto.\n        rewrite <- surjective_pairing; auto.\n        apply (is_partial_lgraph_connected adde_u); auto.\n    ****(*v=u*) destruct H10. 2: contradiction. subst v.\n        split; intros.\n        (*g -> adde*)\n        (* u0 is popped, so is Znth u parents, thus use invariant on them by adding eformat (u, Znth u parents) to the path\n            Then add it again to go back to u*)\n        apply (connected_trans adde_u u0 (Znth u parents) u).\n        apply add_edge_connected. rewrite <- surjective_pairing. auto.\n        rewrite <- Hinv_10; auto. apply (connected_trans g u0 u).\n        auto. apply adjacent_connected. rewrite eformat_adj. apply H7.\n        apply connected_symm. apply adjacent_connected. rewrite eformat_adj. auto.\n        (*adde -> g*)\n        apply (is_partial_lgraph_connected adde_u); auto.\n    ****(*u0=u, repeat of above*) destruct H9. 2: contradiction. subst u0. rename H10 into H9.\n        split; intros.\n        apply (connected_trans adde_u u (Znth u parents) v).\n        apply adjacent_connected. rewrite eformat_adj. auto.\n        apply add_edge_connected. rewrite <- surjective_pairing; auto.\n        rewrite <- Hinv_10; auto.\n        apply (connected_trans g (Znth u parents) u).\n        apply adjacent_connected. rewrite eformat_adj, eformat_symm. apply H7. auto.\n        apply (is_partial_lgraph_connected adde_u); auto.\n    ****destruct H9. 2: contradiction. destruct H10. 2: contradiction. subst u0. subst v.\n        split; intros; apply connected_refl; rewrite vert_bound; lia.\n  }\n  time \"end of pop loop (adde_u) (did not record original):\" entailer!.\n\n  remember (Zlength parents) as size.\n  clear H9 H10 H11 H12 H13 H14 H15 H16 H17 H18 H19 H20 H21 H22.\n\n  (*permutation of EList*)\n    apply (Permutation_trans (l':=(eformat (u,Znth u parents))::(EList mst'))).\n    apply Permutation_sym.\n    { apply NoDup_Permutation. apply NoDup_cons. rewrite EList_evalid; auto. apply NoDup_EList. apply NoDup_EList.\n      intros; split; intros. rewrite EList_evalid. simpl. unfold graph_gen.addValidFunc. destruct H9.\n      rewrite <- surjective_pairing. right; symmetry; auto. left; rewrite EList_evalid in H9; auto.\n      rewrite EList_evalid in H9; simpl in H9. unfold graph_gen.addValidFunc in H9; destruct H9.\n      right; rewrite EList_evalid; auto. left; symmetry; auto. rewrite <- surjective_pairing in H9; auto.\n    }\n    apply (Permutation_trans (l':=(eformat (u, Znth u parents)) :: (map (fun v : Z => eformat (v, Znth v parents))\n       (filter (fun v : Z => Znth v parents <? size) (popped_vertices))))).\n    { apply Permutation_cons. auto. apply Hinv_9. }\n    apply (Permutation_trans (l':=(map (fun v : Z => eformat (v, Znth v parents))\n       (filter (fun v : Z => Znth v parents <? size) (popped_vertices)))+::(eformat (u, Znth u parents)))).\n    { apply Permutation_cons_append. }\n    replace (map (fun v : Z => eformat (v, Znth v parents))\n       (filter (fun v : Z => Znth v parents <? size) popped_vertices) +:: \n     (eformat (u, Znth u parents))) with (map (fun v : Z => eformat (v, Znth v parents'))\n       (filter (fun v : Z => Znth v parents' <? size) (popped_vertices +:: u))). apply Permutation_refl.\n    replace [eformat (u,Znth u parents)] with (map (fun v : Z => eformat (v, Znth v parents)) [u]). 2: { simpl; auto. }\n    rewrite <- list_append_map.\n    replace (filter (fun v : Z => Znth v parents' <? size) (popped_vertices +:: u)) with (filter (fun v : Z => Znth v parents <? size) (popped_vertices +:: u)).\n    2: {\n      apply filter_ext_in. intros. replace (Znth a parents) with (Znth a parents'). auto.\n      apply Hinv2_1. 2: right; auto. apply in_app_or in H9; destruct H9.\n      rewrite <- (vert_bound g). apply Hpopped_vvalid; auto.\n      destruct H9. 2: contradiction. subst a; lia.\n    }\n    replace (filter (fun v : Z => Znth v parents <? size) popped_vertices +:: u) with (filter (fun v : Z => Znth v parents <? size) (popped_vertices +:: u)).\n    2: { rewrite filter_app. simpl. destruct (Znth u parents <? size) eqn: bool. auto.\n      rewrite Z.ltb_ge in bool; lia. }\n    apply map_ext_in; intros. rewrite filter_In in H9. destruct H9.\n    replace (Znth a parents) with (Znth a parents'). auto.\n    apply Hinv2_1.\n    rewrite <- (vert_bound g). apply in_app_or in H9. destruct H9.\n    apply Hpopped_vvalid; auto.\n    destruct H9. 2: contradiction. subst a. apply Hunpopped_vvalid; auto.\n    right; auto.\n  ++ (*Znth u keys = inf. Implies u has no other vertices from the mst that can connect to it. Thus, no change to graph*)\n  Exists mst' fmst' parents' keys' pq_state' (popped_vertices+::u) (remove V_EqDec u unpopped_vertices).\n  assert (Permutation (EList mst')\n      (map (fun v : Z => eformat (v, Znth v parents'))\n         (filter (fun v : Z => Znth v parents' <? size) (popped_vertices +:: u)))). {\n    replace (filter (fun v : Z => Znth v parents' <? size) (popped_vertices +:: u)) with\n      (filter (fun v : Z => Znth v parents' <? size) (popped_vertices)).\n    2: { rewrite filter_app. simpl. destruct (Znth u parents' <? size) eqn: bool.\n    rewrite Z.ltb_lt in bool; lia.\n    rewrite app_nil_r; auto. }\n    replace (filter (fun v : Z => Znth v parents' <? size) popped_vertices) with\n      (filter (fun v : Z => Znth v parents <? size) popped_vertices).\n    2: { apply filter_ext_in. intros.\n      replace (Znth a parents) with (Znth a parents'). auto.\n      apply Hinv2_1. rewrite <- (vert_bound g). apply Hpopped_vvalid; auto.\n      right; apply in_or_app; left; auto. }\n    replace (map (fun v : Z => eformat (v, Znth v parents'))\n     (filter (fun v : Z => Znth v parents <? size) popped_vertices)) with\n      (map (fun v : Z => eformat (v, Znth v parents))\n     (filter (fun v : Z => Znth v parents <? size) popped_vertices)). apply Hinv_9.\n    apply map_ext_in. intros. rewrite filter_In in H5. destruct H5.\n      replace (Znth a parents) with (Znth a parents'). auto.\n      apply Hinv2_1. rewrite <- (vert_bound g). apply Hpopped_vvalid; auto.\n      right; apply in_or_app; left; auto.\n  }\n  assert (Hconnected: forall u0 v : V,\n    In u0 (popped_vertices +:: u) ->\n    In v (popped_vertices +:: u) -> connected g u0 v <-> connected mst' u0 v). {\n    intros. apply in_app_or in H6; apply in_app_or in H7.\n    destruct H6; destruct H7.\n    ****(*both in popped_vertices*)apply Hinv_10; auto.\n    ****(*v=u*) destruct H7. 2: contradiction. subst v.\n      (*In this case, because Znth u parents = inf, NOTHING in popped_vertices should be connected to it in g or mst*)\n      split; intros.\n      (*get a contradiction about ~connected g u0 u*)\n      destruct H7 as [p ?].\n      apply (path_partition_checkpoint g popped_vertices unpopped_vertices p u0 u) in H7; auto.\n      destruct H7 as [v1 [v2 [? [? [? [? ?]]]]]].\n      (*\n        Znth v2 pq_state = keys, because it is unpopped\n        Znth v2 keys >= Znth u keys = inf, because u is popped first\n        Then Znth v2 parents =size using Hinv_7 and stuff\n        but that violates Hinv_8\n      *)\n      assert (0 <= v2 < size). rewrite <- (vert_bound g); apply Hunpopped_vvalid; auto.\n      assert (Hv2_notin: ~ In v2 popped_vertices). {\n      apply (NoDup_app_not_in V unpopped_vertices). apply (Permutation_NoDup (l:=popped_vertices++unpopped_vertices)).\n      apply Permutation_app_comm. apply (Permutation_NoDup (l:=VList g)). apply Permutation_sym; apply Hinv_3.\n      apply NoDup_VList. auto.\n      }\n      assert (Znth v2 parents = size). {\n        assert (0<=Znth v2 parents <= size). apply Hinv_4; auto.\n        destruct H13. apply Z.le_lteq in H14. destruct H14. 2: auto. exfalso.\n        assert (Znth v2 pq_state = Znth v2 keys). rewrite Hinv_6 by lia.\n          destruct (in_dec V_EqDec v2 popped_vertices). contradiction. auto.\n        assert (Znth u pq_state = Znth u keys). rewrite Hinv_6 by lia.\n          destruct (in_dec V_EqDec u popped_vertices). contradiction. auto.\n        assert (Znth u keys <= Znth v2 keys). rewrite <- H15, <- H16. apply Hu_min; lia.\n        assert (Znth v2 keys < inf). rewrite Hinv_5 by lia. destruct (V_EqDec v2 r).\n        lia.\n        apply (evalid_meaning g). apply Hinv_7; lia.\n        (*now so Znth u keys = inf*)\n        destruct popped_vertices. contradiction.\n        (*case u=r, then Znth v2 pq_state = Znth v2 keys should be = inf, lia. Easiest way to solve this is to hack Hinv_11*)\n        (*edit: ok that was unnecessary, lots of things to kill off u=r*)\n        (*case u<>r, then Znth u keys = elabel g (eformat (u, Znth u parents)), but Znth u parents = inf, so Znth u keys = inf. Then inf < inf*)\n        assert( Znth u keys = elabel g (eformat (u,Znth u parents))). rewrite Hinv_5 by lia.\n        destruct (V_EqDec u r). hnf in e.\n          assert (In r (v::popped_vertices)). apply hd_error_In. apply Hr2.\n          unfold not; intros. assert (In v (v::popped_vertices)). left; auto.\n          rewrite H19 in H20; contradiction. subst u. contradiction.\n          auto.\n        rewrite H19 in H17. replace (elabel g (eformat (u, Znth u parents))) with inf in H17. lia.\n        symmetry; apply (invalid_edge_weight g).\n        unfold not; intros. rewrite H4 in H20. apply eformat_evalid_vvalid in H20. destruct H20.\n        rewrite vert_bound in H21; lia.\n      }\n      exfalso. apply (Hinv_8 v2 H12 H13 v1).\n      rewrite find_notIn, Z.add_0_r, sublist_same. auto. auto. auto.\n      auto. auto.\n      (*mst' -> g*) apply connected_symm in H7. destruct H7 as [p [? [? ?]]]. destruct p. inversion H8.\n      inversion H8. destruct p. inversion H9. subst v. subst u0. apply connected_refl. rewrite vert_bound; lia.\n      subst v. destruct H7. exfalso. apply (Hinv_13 u v0); auto.\n    ****(*u0=u, which is repeat of above*) destruct H6. 2: contradiction. subst u0. rename H7 into H6.\n      split; intros.\n      (*g -> mst'*)\n      apply connected_symm in H7. destruct H7 as [p ?].\n      apply (path_partition_checkpoint g popped_vertices unpopped_vertices p v u) in H7; auto.\n      destruct H7 as [v1 [v2 [? [? [? [? ?]]]]]].\n      (*\n        Znth v2 pq_state = keys, because it is unpopped\n        Znth v2 keys >= Znth u keys = inf, because u is popped first\n        Then Znth v2 parents =size using Hinv_7 and stuff\n        but that violates Hinv_8\n      *)\n      assert (0 <= v2 < size). rewrite <- (vert_bound g); apply Hunpopped_vvalid; auto.\n      assert (Hv2_notin: ~ In v2 popped_vertices). {\n      apply (NoDup_app_not_in V unpopped_vertices). apply (Permutation_NoDup (l:=popped_vertices++unpopped_vertices)).\n      apply Permutation_app_comm. apply (Permutation_NoDup (l:=VList g)). apply Permutation_sym; apply Hinv_3.\n      apply NoDup_VList. auto.\n      }\n      assert (Znth v2 parents = size). {\n        assert (0<=Znth v2 parents <= size). apply Hinv_4; auto.\n        destruct H13. apply Z.le_lteq in H14. destruct H14. 2: auto. exfalso.\n        assert (Znth v2 pq_state = Znth v2 keys). rewrite Hinv_6 by lia.\n          destruct (in_dec V_EqDec v2 popped_vertices). contradiction. auto.\n        assert (Znth u pq_state = Znth u keys). rewrite Hinv_6 by lia.\n          destruct (in_dec V_EqDec u popped_vertices). contradiction. auto.\n        assert (Znth u keys <= Znth v2 keys). rewrite <- H15, <- H16. apply Hu_min; lia.\n        assert (Znth v2 keys < inf). rewrite Hinv_5 by lia. destruct (V_EqDec v2 r).\n        lia.\n        apply (evalid_meaning g). apply Hinv_7; lia.\n        (*now so Znth u keys = inf*)\n        destruct popped_vertices. contradiction.\n        (*case u=r, then Znth v2 pq_state = Znth v2 keys should be = inf, lia. Easiest way to solve this is to hack Hinv_11*)\n        (*edit: ok that was unnecessary, lots of things to kill off u=r*)\n        (*case u<>r, then Znth u keys = elabel g (eformat (u, Znth u parents)), but Znth u parents = inf, so Znth u keys = inf. Then inf < inf*)\n        assert( Znth u keys = elabel g (eformat (u,Znth u parents))). rewrite Hinv_5 by lia.\n        destruct (V_EqDec u r). hnf in e.\n          assert (In r (v0::popped_vertices)). apply hd_error_In. apply Hr2.\n          unfold not; intros. assert (In v0 (v0::popped_vertices)). left; auto.\n          rewrite H19 in H20; contradiction. subst u. contradiction.\n          auto.\n        rewrite H19 in H17. replace (elabel g (eformat (u, Znth u parents))) with inf in H17. lia.\n        symmetry; apply (invalid_edge_weight g).\n        unfold not; intros. rewrite H4 in H20. apply eformat_evalid_vvalid in H20. destruct H20.\n        rewrite vert_bound in H21; lia.\n      }\n      exfalso. apply (Hinv_8 v2 H12 H13 v1).\n      rewrite find_notIn, Z.add_0_r, sublist_same. auto. auto. auto.\n      auto. auto.\n      (*mst' -> g*) destruct H7 as [p [? [? ?]]]. destruct p. inversion H8.\n      inversion H8. destruct p. inversion H9. subst v0. subst v. apply connected_refl. rewrite vert_bound; lia.\n      subst v0. destruct H7. exfalso. apply (Hinv_13 u v1); auto.\n    ****(*both=u*)destruct H6. 2: contradiction. destruct H7. 2: contradiction. subst u0; subst v.\n    split; intros; apply connected_refl; rewrite vert_bound; lia.\n  }\n  assert (Hnot_adj: forall u0 v : V, In u0 (remove V_EqDec u unpopped_vertices) -> ~ adjacent mst' u0 v). {\n    intros. apply Hinv_13. rewrite remove_In_iff in H6; apply H6.\n  }\n  time \"End of pop loop (same msf) (originally 150s):\" entailer!.\n  }\n  { (*break*) forward. (*no more vertices in queue*)\n    assert (Hempty: @isEmpty inf pq_state = Vone). {\n      destruct (@isEmptyTwoCases inf pq_state);\n      rewrite H1 in H0; simpl in H0; now inversion H0.\n    } clear H0.\n    rewrite (@isEmptyMeansInf inf pq_state) in Hempty.\n    rename Hempty into H0. rewrite Forall_forall in H0.\n    assert (Permutation popped_vertices (VList mst')). {\n      apply NoDup_Permutation.\n      apply Permutation_sym, Permutation_NoDup, NoDup_app_l in Hinv_3. auto. apply NoDup_VList.\n      apply NoDup_VList. intros; split; intros.\n      apply VList_vvalid. rewrite vert_bound. rewrite <- (vert_bound g). apply Hpopped_vvalid; auto.\n      rewrite VList_vvalid, vert_bound, <- (vert_bound g), vert_bound in H1.\n      assert (Znth x pq_state = (if in_dec V_EqDec x popped_vertices then inf + 1 else Znth x keys)). apply Hinv_6; auto.\n      destruct (in_dec V_EqDec x popped_vertices). auto. exfalso. rewrite Hinv_5 in H2.\n      assert (Znth x pq_state > inf). apply H0. apply Znth_In. unfold V in *. rewrite HZlength_pq_state. auto. 2: auto.\n      destruct (V_EqDec x r).\n      lia.\n      rewrite H2 in H3. pose proof (weight_inf_bound g (eformat (x, Znth x parents))).\n      apply Zgt_not_le in H3. contradiction.\n    }\n    Exists mst'. Exists fmst'. Exists popped_vertices. Exists parents. Exists keys.\n    (*SEP matters*)\n    replace (map Vint (map Int.repr pq_state)) with (repeat (Vint (Int.repr (inf + 1))) (Z.to_nat size)). 2: {\n      apply list_eq_Znth. do 2 rewrite Zlength_map.\n      unfold V in *. rewrite Zlength_repeat; lia.\n      intros. rewrite Zlength_repeat in H2 by lia.\n      rewrite Znth_repeat_inrange by lia. rewrite Znth_map. 2: unfold V in *; rewrite Zlength_map; lia.\n      unfold V in *. rewrite Znth_map by lia. rewrite Hinv_6 by lia.\n      unfold V in *.\n      destruct (@in_dec Z V_EqDec i popped_vertices). auto.\n      exfalso; apply n. apply (Permutation_in (l:=VList mst')). apply Permutation_sym; auto.\n      rewrite VList_vvalid, vert_bound; auto.\n    }\n    replace (map (fun x : V =>\n      if in_dec V_EqDec x popped_vertices then Vint (Int.repr 1) else Vint (Int.repr 0))\n     (nat_inc_list (Z.to_nat size))) with (repeat (Vint (Int.repr 1)) (Z.to_nat size)). 2: {\n      apply list_eq_Znth. rewrite Zlength_map, Zlength_repeat, nat_inc_list_Zlength, Z2Nat.id by lia; auto.\n      intros. rewrite Zlength_repeat in H2 by lia. rewrite Znth_repeat_inrange by lia.\n      rewrite Znth_map. 2: rewrite nat_inc_list_Zlength, Z2Nat.id; lia.\n      rewrite nat_inc_list_i. 2: rewrite Z2Nat.id; lia.\n      destruct (in_dec V_EqDec i popped_vertices). auto.\n      exfalso; apply n. apply (Permutation_in (l:=VList mst')). apply Permutation_sym; auto.\n      rewrite VList_vvalid, vert_bound; auto.\n    }\n    assert (spanning mst' g). {\n      unfold spanning; intros.\n      split; intros. assert (vvalid g u /\\ vvalid g v). apply connected_vvalid; auto. destruct H3.\n      rewrite vert_bound, <- (vert_bound mst'), <- VList_vvalid in H3, H4.\n      apply Hinv_10; auto.\n      apply (Permutation_in (l:=VList mst')). apply Permutation_sym; auto. apply H3.\n      apply (Permutation_in (l:=VList mst')). apply Permutation_sym; auto. apply H4.\n      assert (vvalid mst' u /\\ vvalid mst' v). apply connected_vvalid; auto. destruct H3.\n      rewrite <- VList_vvalid in H3, H4.\n      apply Hinv_10; auto.\n      apply (Permutation_in (l:=VList mst')). apply Permutation_sym; auto. apply H3.\n      apply (Permutation_in (l:=VList mst')). apply Permutation_sym; auto. apply H4.\n    }\n    assert (hd_error popped_vertices = Some r). {\n      destruct popped_vertices. assert (vvalid mst' 0). rewrite vert_bound; lia.\n      rewrite <- VList_vvalid in H3. apply (Permutation_in (l':=[])) in H3. contradiction.\n      apply Permutation_sym; apply H1.\n      apply Hr2. unfold not; intros. assert (In v (v::popped_vertices)) by (left; auto).\n      rewrite H3 in H4; contradiction.\n    }\n    time entailer!. (*was 55 seconds without PROP*)\n  }\n}\n(*POST-LOOP*) {\nclear Hstarting_keys HZlength_starting_keys starting_keys.\nIntros mst fmst popped_vertices parents keys.\nrename H into Hinv_1; rename H0 into Hinv_2;\nrename H1 into Hinv_3; rename H2 into Hinv_4;\nrename H3 into Hinv_5; rename H4 into Hinv_6;\nrename H5 into Hinv_7; rename H6 into Hinv_8;\nrename H7 into Hinv_9; rename H8 into Hinv_10;\nrename H9 into Hinv_11.\nassert (labeled_spanning_uforest mst g). {\n  split. split. apply Hinv_1. split. apply Hinv_2. apply Hinv_7.\n  split. unfold preserve_vlabel; intros. destruct vlabel. destruct vlabel. auto.\n  unfold preserve_elabel; intros. apply Hinv_1. auto.\n}\nassert (minimum_spanning_forest mst g). {\n  destruct Hinv_11 as [M [? ?]].\n  apply (partial_lgraph_spanning_mst mst M g); auto.\n}\nassert (Permutation (EList mst)\n          (map (fun v : Z => eformat (v, Znth v parents))\n             (filter (fun v : Z => Znth v parents <? size) (nat_inc_list (Z.to_nat size))))). {\napply (Permutation_trans (l':= (map (fun v : Z => eformat (v, Znth v parents))\n              (filter (fun v : Z => Znth v parents <? size) popped_vertices)))).\nauto. apply Permutation_map. apply NoDup_Permutation.\napply NoDup_filter. apply (Permutation_NoDup (l:=VList mst)). apply Permutation_sym; auto. apply NoDup_VList.\napply NoDup_filter. apply nat_inc_list_NoDup.\nintros. do 2 rewrite filter_In. rewrite nat_inc_list_in_iff by auto. rewrite Z2Nat.id by lia.\nsplit; intros; destruct H1; split; auto.\napply (Permutation_in (l':=VList mst)) in H1. 2: auto. rewrite VList_vvalid, vert_bound in H1. lia.\napply (Permutation_in (l:=VList mst)). apply Permutation_sym; auto. rewrite VList_vvalid, vert_bound; lia.\n}\nrepeat rewrite Heqv_pq, Heqv_out, Heqv_key.\nfreeze FR := (data_at _ _ _ (pointer_val_val out))\n               (data_at _ _ _ (pointer_val_val parent_ptr))\n               (data_at _ _ _ (pointer_val_val key))\n               (SpaceAdjMatGraph' _ _ _ _)\n               (free_tok (pointer_val_val out) _)\n               (free_tok (pointer_val_val key) _).\nforward_call (Tsh, priq_ptr, size, (repeat (inf + 1) (Z.to_nat size))).\nrewrite map_map, map_repeat.\nentailer!.\nthaw FR.\nfreeze FR := (data_at _ _ _ (pointer_val_val parent_ptr))\n               (data_at _ _ _ (pointer_val_val key))\n               (SpaceAdjMatGraph' _ _ _ _)\n               (free_tok (pointer_val_val key) _).\nforward_call (Tsh, out, size, (repeat 1 (Z.to_nat size))).\nrewrite map_map, map_repeat, Z.mul_comm. simpl. entailer!.\nthaw FR.\nfreeze FR := (data_at _ _ _ (pointer_val_val parent_ptr))\n               (SpaceAdjMatGraph' _ _ _ _).\nrewrite <- map_map.\nforward_call (Tsh, key, size, keys).\nrewrite Z.mul_comm. simpl. entailer!.\nforward. \nExists mst fmst parents. thaw FR.\nTransparent size.\nentailer!.\nGlobal Opaque size.\n}\nQed.\n\nEnd PrimProof.\n \n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/prim/verif_prim1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24659795523992176}}
{"text": "Set Implicit Arguments.\nSet Maximal Implicit Insertion.\nSet Contextual Implicit.\n\nFrom Coq Require Import\n     Relation_Definitions\n     RelationClasses\n.\n\nRequire Import Fix.\nRequire Import GHC.Base.\n\nRequire Import Adverb.Composable.Repeatedly.\nRequire Import ClassesOfFunctors.AppKleenePlus.\n\nSection RefinesKleenePlusLaws.\n\n    Variable D : (Set -> Set) -> Set -> Set.\n    Context `{ReifiedKleenePlus -≪ D} `{Functor1 D}.\n    Context `{Monad (Fix1 D)}.\n\n    Fixpoint seq {A : Set} (a : Fix1 D A) (n : nat) : Fix1 D A :=\n      match n with\n      | 0 => a\n      | S n => a >> @seq _ a n\n      end.\n\n    Variant RefinesKleenePlusLaws\n            (Kr : forall (A : Set), relation (Fix1 D A))\n            {A : Set} : relation (Fix1 D A) :=\n    | RefinesSeq : forall (a b : Fix1 D A) n,\n        Kr _ a b ->\n        RefinesKleenePlusLaws Kr (@seq _ a n) (@kleenePlus _ _ _ _ _ b)\n    | RefinesKleenePlus : forall (a b : Fix1 D A),\n        Kr _ a (@kleenePlus _ _ _ _ _ b) ->\n        RefinesKleenePlusLaws Kr (@kleenePlus _ _ _ _ _ a) (@kleenePlus _ _ _ _ _ b)\n    (* TODO: move to a separate data type. *)\n    | RefinesKleenePlusCong : forall (a b : Fix1 D A),\n        Kr _ a b ->\n        RefinesKleenePlusLaws Kr (@kleenePlus _ _ _ _ _ a) (@kleenePlus _ _ _ _ _ b).\n\n    Global Instance FunctorRel__RefinesKleenePlusLaws :\n      FunctorRel (F:=Fix1 D) RefinesKleenePlusLaws.\n    constructor. intros. destruct H5.\n    - constructor; auto.\n    - constructor; auto.\n    - apply RefinesKleenePlusCong. auto.\n    Qed.\n\nEnd RefinesKleenePlusLaws.\n\nSection RefinesKleenePlusLaws_SmartConstructors.\n\n  Variable D : (Set -> Set) -> Set -> Set.\n  Context `{ReifiedKleenePlus -≪ D} `{Functor1 D}.\n  Context `{Monad (Fix1 D)}.\n\n  Variable R : (forall (A : Set), relation (Fix1 D A)) ->\n               forall (A : Set), relation (Fix1 D A).\n  Context `{FunctorRel _ R} `{RefinesKleenePlusLaws -⋘ R}.\n\n  Lemma refinesSeq :\n    forall {A : Set} (a b : Fix1 D A) n,\n      FixRel R _ a b ->\n      FixRel R _ (@seq _ _ _ _ _ a n) (@kleenePlus _ _ _ _ _ b).\n  Proof.\n    intros. apply inFRel, injRel.\n    constructor; assumption.\n  Qed.\n\n  Lemma refinesKleenePlus :\n    forall {A : Set} (a b : Fix1 D A),\n      FixRel R _ a (@kleenePlus _ _ _ _ _ b) ->\n      FixRel R _ (@kleenePlus _ _ _ _ _ a) (@kleenePlus _ _ _ _ _ b).\n  Proof.\n    intros. apply inFRel, injRel.\n    constructor; assumption.\n  Qed.\n\n  Lemma refinesKleenePlusCong :\n    forall {A : Set} (a b : Fix1 D A),\n      FixRel R _ a b ->\n      FixRel R _ (@kleenePlus _ _ _ _ _ a) (@kleenePlus _ _ _ _ _ b).\n  Proof.\n    intros. apply inFRel, injRel.\n    constructor; assumption.\n  Qed.\n\nEnd RefinesKleenePlusLaws_SmartConstructors.\n", "meta": {"author": "lastland", "repo": "ProgramAdverbs", "sha": "1f8086d379d1fc0eb896539adae66cd9f7d8ec04", "save_path": "github-repos/coq/lastland-ProgramAdverbs", "path": "github-repos/coq/lastland-ProgramAdverbs/ProgramAdverbs-1f8086d379d1fc0eb896539adae66cd9f7d8ec04/Refines/RefinesStar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24656605900564807}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import PSCIAux.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition psci_cpu_on_target_spec (g_target_rec: Pointer) (target_rec: Pointer) (rec: Pointer) (entry_point_address: Z64) (target_cpu: Z64) (adt: RData) : option RData :=\n    match entry_point_address, target_cpu with\n    | VZ64 ep, VZ64 tc =>\n      rely is_int64 ep; rely is_int64 tc;\n      rely (peq (base g_target_rec) ginfo_loc);\n      rely (peq (base target_rec) buffer_loc);\n      rely (peq (base rec) buffer_loc);\n      when rec_gidx == ((buffer (priv adt)) @ (offset rec));\n      when target_gidx == ((buffer (priv adt)) @ (offset target_rec));\n      rely prop_dec (rec_gidx <> target_gidx);\n      rely is_gidx target_gidx;\n      rely (offset g_target_rec =? target_gidx);\n      let gn_rec := (gs (share adt)) @ rec_gidx in\n      let gn := (gs (share adt)) @ target_gidx in\n      rely (g_tag (ginfo gn_rec) =? GRANULE_STATE_REC);\n      rely (g_tag (ginfo gn) =? GRANULE_STATE_REC);\n      rely prop_dec (glock gn = Some CPU_ID);\n      rely (ref_accessible gn CPU_ID);\n      rely (ref_accessible gn_rec CPU_ID);\n      rely is_int (g_runnable (gnorm gn));\n      if g_runnable (gnorm gn) =? 0 then\n        let sctlr := r_sctlr_el1 (g_regs (grec gn_rec)) in\n        rely is_int64 sctlr;\n        let g' := gn {grec : (grec gn) {g_pstate : 965}\n                                       {g_pc: ep}\n                                       {g_regs : set_reg sctlr_el1 (Z.lor SCTLR_EL1_FLAGS (Z.land sctlr SCTLR_EL1_EE)) (g_regs (grec gn))}}\n                     {gnorm: (gnorm gn) {g_runnable: 1}} in\n        rely (g_tag (ginfo gn) =? gtype gn);\n        let e := EVT CPU_ID (REL target_gidx g') in\n        Some adt {log: e :: log adt}\n             {priv: (priv adt) {buffer: (buffer (priv adt)) # (offset target_rec) == None} {psci_x0: 0}\n                               {psci_forward_psci_call: 1} {psci_forward_x1: tc}}\n             {share: (share adt) {gs: (gs (share adt)) # target_gidx == (g' {glock: None})}}\n      else\n        rely (g_tag (ginfo gn) =? gtype gn);\n        let e := EVT CPU_ID (REL target_gidx gn) in\n        Some adt {log: e :: log adt}\n             {priv: (priv adt) {buffer: (buffer (priv adt)) # (offset target_rec) == None} {psci_x0: PSCI_RETURN_ALREADY_ON}}\n             {share: (share adt) {gs: (gs (share adt)) # target_gidx == (gn {glock: None})}}\n     end.\n\nEnd Spec.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/PSCIAux2/Specs/psci_cpu_on_target.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24653632588928492}}
{"text": "Require Import Coqlib.                                               \nRequire Import Maps.            \nRequire Import LibTactics.   \n        \nRequire Import Integers.  \nOpen Scope Z_scope.        \nImport ListNotations.  \n   \nSet Asymmetric Patterns.  \n        \nRequire Import state.    \nRequire Import language.  \n \nSet Implicit Arguments.    \nUnset Strict Implicit. \n               \nRequire Import logic.\n    \nRequire Import lemmas.\nRequire Import lemmas_ins.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nRequire Import integer_lemma.\n\nRequire Import sep_lemma.\nRequire Import reg_lemma.\nRequire Import derived_rule.\n\nRequire Import tm_dly_lemma.\n\nRequire Import code.\nRequire Import ctxswitch_spec.\n\nRequire Import lemma1.\n\nOpen Scope nat.\nOpen Scope code_scope.\nOpen Scope mem_scope.\n  \n(*+ Proof +*)\nTheorem Ta0AdjustCWPProof :\n  forall vl,\n    spec |- {{ ta0_adjust_cwp_pre vl }}\n             ta0_adjust_cwp\n           {{ ta0_adjust_cwp_post vl }}.\nProof.\n  intros.\n  unfold ta0_adjust_cwp_pre.\n  unfold ta0_adjust_cwp_post.\n  hoare_ex_intro_pre.\n  renames x' to fmg, x'0 to fmo, x'1 to fml, x'2 to fmi.\n  renames x'3 to id, x'6 to vi, x'4 to F, x'5 to vy. \n  renames x'8 to i, x'13 to vz, x'14 to vn.\n  renames x'7 to ll, x'9 to ct, x'10 to nt, x'11 to nctx, x'12 to nstk, x'15 to oid.\n  eapply Pure_intro_rule.\n  introv Hlgvl.\n  hoare_lift_pre 13.\n  eapply Pure_intro_rule.\n  introv Hpure.\n  hoare_lift_pre 13.\n  eapply Pure_intro_rule.\n  introv Hnctx.\n  destruct fmg, fmo, fml, fmi.\n  eapply backward_rule.\n  introv Hs.\n  simpl_sep_liftn_in Hs 2.\n  eapply Regs_Global_combine_GenRegs in Hs; eauto.\n  unfold ta0_adjust_cwp.\n\n  destruct Hpure as [Hg4 [Hrot [Hoid_range [Hvl_g4 [Hg7 Hct] ] ] ] ].\n  simpl in Hg4.\n  inversion Hg4; subst.\n  simpl in Hg7.\n  inversion Hg7; subst.\n\n  (** sll g4 1 g5 *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply sll_rule_reg; eauto.\n  simpl; eauto.\n  rewrite in_range1; eauto.\n  simpl upd_genreg.\n\n  (** srl g4 (OS_WINDOWS - 1) g5 *)\n  unfold OS_WINDOWS.\n  assert (Heq7 : ($ 8) -ᵢ ($ 1) = ($ 7)).\n  eauto.\n  rewrite Heq7.\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply srl_rule_reg; eauto.\n  simpl; eauto.\n  rewrite in_range7; eauto.\n  simpl upd_genreg. \n  rewrite get_range_0_4_stable; eauto.\n  rewrite get_range_0_4_stable; eauto.\n  \n  (** or g4 g5 g4 *)\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply or_rule_reg; eauto.\n  simpl; eauto. \n  simpl upd_genreg.\n\n  eapply hoare_pure_gen' with (pu := $ 0 <=ᵤᵢ id <=ᵤᵢ $ 7 /\\ $ 0 <=ᵤᵢ vi <=ᵤᵢ $ 7).\n  {\n    introv Hs.\n    simpl_sep_liftn_in Hs 2.\n    unfold FrameState in Hs.\n    asrt_to_line_in Hs 3.\n    simpl_sep_liftn_in Hs 4.\n    eapply sep_pure_l_elim in Hs; eauto.\n    simpljoin1; eauto.\n  } \n  eapply Pure_intro_rule.\n  introv Hid_inrange.\n  destruct Hid_inrange as [Hid_inrange Hvi_inrange].\n    \n  (** andcc g4 g7 g0 *)\n  hoare_lift_pre 4.\n  hoare_lift_pre 5.\n  hoare_lift_pre 3.\n  eapply seq_rule.\n  TimReduce_simpl. \n  eapply andcc_rule_reg; eauto.\n  simpl upd_genreg.\n  simpl get_genreg_val.\n  assert (Hiszero : iszero ((i >>ᵢ ($ 7)) |ᵢ (i <<ᵢ ($ 1))) &ᵢ (($ 1) <<ᵢ vi) =\n         iszero (get_range 0 7 ((i >>ᵢ ($ 7)) |ᵢ (i <<ᵢ ($ 1)))) &ᵢ (($ 1) <<ᵢ vi)).\n  {\n    rewrite in_range_0_7_and; eauto.\n  }  \n  rewrite Hiszero.\n  rewrite g4_val_get_range_0_7_equal with (id := id); eauto.\n\n  (** bne Ta0_Switch; nop *)\n  eapply Bne_rule; eauto.\n  {\n    eval_spec.\n  }\n  {\n    TimReduce_simpl.\n    eapply nop_rule; eauto.\n  }\n  {\n    TimReduce_simpl.\n    introv Hs.\n    simpl_sep_liftn_in Hs 3.\n    sep_cancel1 1 1.\n    simpl; eauto.\n  }\n\n  Focus 3.\n  introv Hne.\n  unfold iszero in Hne.\n  destruct (Int.eq_dec (($ 1) <<ᵢ (post_cwp id)) &ᵢ (($ 1) <<ᵢ vi) $ 0); tryfalse.\n  clear Hne.\n  renames n to Hne.\n  eapply and_not_zero_eq in Hne; eauto.\n  2 : eapply in_range_0_7_post_cwp_still; eauto.\n  split.\n \n    introv Hs.\n    unfold ta0_task_switch_newcontext_pre.\n    sep_ex_intro.\n    asrt_to_line 14.\n    eapply sep_pure_l_intro; eauto.\n    simpl_sep_liftn 2.\n    eapply GenRegs_split_Regs_Global; eauto.\n    sep_cancel1 1 1.\n    sep_cancel1 3 1.\n    sep_cancel1 1 3.\n    sep_cancel1 1 2.\n    do 7 sep_cancel1 1 1.\n    instantiate (1 := Aemp).\n    eapply astar_emp_intro_r; eauto.\n    instantiate (1 := Aemp).\n    eapply sep_pure_l_intro; eauto.\n    eapply sep_pure_l_intro; eauto.\n\n    introv Hs. \n    unfold ta0_task_switch_newcontext_post in Hs.\n    sep_ex_elim_in Hs.\n    asrt_to_line_in Hs 13.\n    eapply sep_pure_l_elim in Hs.\n    destruct Hs as [Hlgvl1 Hs].\n    symmetry in Hlgvl1.\n    inversion Hlgvl1; subst.\n    sep_ex_intro.\n    eapply sep_pure_l_intro; eauto.\n    do 12 sep_cancel1 1 1.\n    match goal with\n    | H : _ |= _ |- _ => renames H to Hs\n    end.\n    eapply sep_pure_l_elim in Hs; eauto.\n\n  2 : DlyFrameFree_elim.  \n\n  introv Heq.\n  unfold iszero in Heq.\n  destruct (Int.eq_dec (($ 1) <<ᵢ (post_cwp id)) &ᵢ (($ 1) <<ᵢ vi) $ 0); tryfalse.\n  clear Heq.\n  renames e to Heq.\n  eapply and_zero_not_eq in Heq; eauto.\n  2 : eapply in_range_0_7_post_cwp_still; eauto.\n\n  eapply hoare_pure_gen' with (length F = 13).\n  {\n    introv Hs.\n    simpl_sep_liftn_in Hs 4.\n    unfold FrameState in Hs.\n    asrt_to_line_in Hs 3.\n    simpl_sep_liftn_in Hs 3.\n    eapply sep_pure_l_elim in Hs.\n    simpljoin1; eauto.\n  }\n  eapply Pure_intro_rule.\n  introv Hlen_F.\n\n  destruct F; simpl in Hlen_F; tryfalse.\n  destruct F; simpl in Hlen_F; tryfalse.\n  destruct f, f0.\n  hoare_lift_pre 4. \n  unfold FrameState at 1.\n  eapply backward_rule.\n  introv Hs.\n  asrt_to_line_in Hs 3.\n  simpl_sep_liftn_in Hs 3.\n  eapply sep_pure_l_elim in Hs.\n  destruct Hs as [_ Hs].\n  simpl_sep_liftn_in Hs 3.\n  eapply sep_pure_l_elim in Hs.\n  destruct Hs as [_ Hs].\n  eauto.\n\n  (** restore *)\n  hoare_lift_pre 2.\n  hoare_lift_pre 3.\n  eapply seq_rule; eauto.\n  TimReduce_simpl.\n  eapply restore_rule_reg; eauto.\n  simpl; eauto.\n  unfold win_masked.\n  destruct (((($ 1) <<ᵢ (post_cwp id)) &ᵢ (($ 1) <<ᵢ vi)) !=ᵢ ($ 0)) eqn:Heqe; eauto.\n  unfold negb in Heqe.\n  destruct (((($ 1) <<ᵢ (post_cwp id)) &ᵢ (($ 1) <<ᵢ vi)) =ᵢ ($ 0)) eqn:Heqe1; tryfalse.\n  eapply int_eq_false_neq in Heqe1.\n  eapply and_not_zero_eq in Heqe1; eauto.\n  subst; tryfalse.\n  eapply in_range_0_7_post_cwp_still; eauto.\n  simpl upd_genreg.\n\n  (** jumpl Ta0_adjust_cwp; nop *)\n  eapply J1_rule; eauto.\n  {\n    TimReduce_simpl.\n    introv Hs.\n    simpl. \n    unfold Ta0_adjust_CWP at 1 2.\n    unfold Ta0_adjust_CWP at 1 2.\n    rewrite in_range344; eauto.\n  }\n  {\n    eval_spec.\n  }\n  {\n    TimReduce_simpl.\n    introv Hs.\n    eapply GenRegs_split_one with (rr := g0) in Hs.\n    simpl get_genreg_val' in Hs.\n    eauto.\n  }\n  {\n    TimReduce_simpl.\n    eapply nop_rule; eauto.\n    introv Hs.\n    eapply GenRegs_upd_combine_one in Hs.\n    simpl upd_genreg in Hs.\n    simpl_sep_liftn_in Hs 2.\n    simpl_sep_liftn_in Hs 3.\n    eapply FrameState_combine in Hs; eauto.\n    unfold ta0_adjust_cwp_pre.\n    sep_ex_intro.\n    asrt_to_line 14.\n    eapply sep_pure_l_intro; eauto.\n    simpl_sep_liftn 2.\n    eapply GenRegs_split_Regs_Global; eauto.\n    sep_cancel1 2 1.\n    sep_cancel1 4 2.\n    sep_cancel1 1 1.\n    sep_cancel1 1 2.\n    do 7 sep_cancel1 1 1.\n    instantiate (1 := Aemp).\n    eapply astar_emp_intro_r; eauto.\n    instantiate (1 := Aemp).\n    simpl get_frame_nth.\n    eapply sep_pure_l_intro; eauto.\n    split; eauto.\n    split.\n    {\n      instantiate (1 := oid).\n      eapply rotate_cons; eauto.\n    }\n    repeat (split; eauto).\n    eapply g4_rot_stable with (oid := oid); eauto.\n    eapply sep_pure_l_intro; eauto.\n    clear - Hlen_F.\n    rewrite app_length.\n    simpl; omega.\n    split; eauto.\n    eapply in_range_0_7_post_cwp_still; eauto.\n  }\n\n  introv Hs.\n  unfold ta0_adjust_cwp_post in Hs.\n  sep_ex_elim_in Hs.\n  asrt_to_line_in Hs 13.\n  sep_ex_intro.\n  do 13 sep_cancel1 1 1.\n  match goal with\n  | H : _ |= _ |- _ => rename H into Hs\n  end.\n  eapply sep_pure_l_elim in Hs; eauto.\n\n  DlyFrameFree_elim.\nQed.", "meta": {"author": "luckywangwang", "repo": "CertiSparc", "sha": "b5c4ff0d1b723537a645b6c5578b8749ed1c813e", "save_path": "github-repos/coq/luckywangwang-CertiSparc", "path": "github-repos/coq/luckywangwang-CertiSparc/CertiSparc-b5c4ff0d1b723537a645b6c5578b8749ed1c813e/coqimp/contextswitch/proof/AdjustCWP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.2465363258892849}}
{"text": "Require Import Omega.\nRequire Import Bool.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import PromiseConsistent.\nRequire Import Mapping.\n\nRequire Import PFStep.\n\nSet Implicit Arguments.\n\n\nModule OrdLocal.\n  Section OrdLocal.\n    Variable L: Loc.t -> bool.\n    Variable ordc: Ordering.t.\n\n    Inductive read_step (lc1:Local.t) (mem1:Memory.t) (loc:Loc.t) (to:Time.t) (val:Const.t) (released:option View.t) (ord:Ordering.t) (lc2:Local.t): Prop :=\n    | read_step_intro\n        ord'\n        (ORD: ord' = if L loc then Ordering.join ord ordc else ord)\n        (STEP: Local.read_step lc1 mem1 loc to val released ord' lc2)\n    .\n    Hint Constructors read_step.\n\n    Inductive write_step (lc1:Local.t) (sc1:TimeMap.t) (mem1:Memory.t)\n              (loc:Loc.t) (from to:Time.t)\n              (val:Const.t) (releasedm released:option View.t) (ord:Ordering.t)\n              (lc2:Local.t) (sc2:TimeMap.t) (mem2:Memory.t) (kind:Memory.op_kind): Prop :=\n    | write_step_intro\n        ord'\n        (ORD: ord' = if L loc then Ordering.join ord ordc else ord)\n        (STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord' lc2 sc2 mem2 kind)\n    .\n    Hint Constructors write_step.\n\n    Inductive program_step:\n      forall (e:ThreadEvent.t) (lc1:Local.t) (sc1:TimeMap.t) (mem1:Memory.t) (lc2:Local.t) (sc2:TimeMap.t) (mem2:Memory.t), Prop :=\n    | step_silent\n        lc1 sc1 mem1:\n        program_step ThreadEvent.silent lc1 sc1 mem1 lc1 sc1 mem1\n    | step_read\n        lc1 sc1 mem1\n        loc ts val released ord lc2\n        (LOCAL: read_step lc1 mem1 loc ts val released ord lc2):\n        program_step (ThreadEvent.read loc ts val released ord) lc1 sc1 mem1 lc2 sc1 mem1\n    | step_write\n        lc1 sc1 mem1\n        loc from to val released ord lc2 sc2 mem2 kind\n        (LOCAL: write_step lc1 sc1 mem1 loc from to val None released ord lc2 sc2 mem2 kind):\n        program_step (ThreadEvent.write loc from to val released ord) lc1 sc1 mem1 lc2 sc2 mem2\n    | step_update\n        lc1 sc1 mem1\n        loc ordr ordw\n        tsr valr releasedr releasedw lc2\n        tsw valw lc3 sc3 mem3 kind\n        (LOCAL1: read_step lc1 mem1 loc tsr valr releasedr ordr lc2)\n        (LOCAL2: write_step lc2 sc1 mem1 loc tsr tsw valw releasedr releasedw ordw lc3 sc3 mem3 kind):\n        program_step (ThreadEvent.update loc tsr tsw valr valw releasedr releasedw ordr ordw)\n                     lc1 sc1 mem1 lc3 sc3 mem3\n    | step_fence\n        lc1 sc1 mem1\n        ordr ordw lc2 sc2\n        (LOCAL: Local.fence_step lc1 sc1 ordr ordw lc2 sc2):\n        program_step (ThreadEvent.fence ordr ordw) lc1 sc1 mem1 lc2 sc2 mem1\n    | step_syscall\n        lc1 sc1 mem1\n        e lc2 sc2\n        (LOCAL: Local.fence_step lc1 sc1 Ordering.seqcst Ordering.seqcst lc2 sc2):\n        program_step (ThreadEvent.syscall e) lc1 sc1 mem1 lc2 sc2 mem1\n    | step_failure\n        lc1 sc1 mem1\n        (LOCAL: Local.failure_step lc1):\n        program_step ThreadEvent.failure lc1 sc1 mem1 lc1 sc1 mem1\n    .\n    Hint Constructors program_step.\n\n\n    (* step_future *)\n\n    Lemma write_step_non_cancel\n          lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n          (STEP: write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind):\n      negb (Memory.op_kind_is_cancel kind).\n    Proof.\n      inv STEP. eapply Local.write_step_non_cancel; eauto.\n    Qed.\n\n    Lemma write_step_strong_relaxed\n          lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n          (STEP: write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n          (ORD: Ordering.le Ordering.strong_relaxed ord):\n      negb (Memory.op_kind_is_lower kind).\n    Proof.\n      inv STEP. eapply Local.write_step_strong_relaxed; eauto.\n      etrans; eauto. des_ifs; try refl.\n      eapply Ordering.join_l.\n    Qed.\n\n    Lemma program_step_future\n          e lc1 sc1 mem1 lc2 sc2 mem2\n          (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n          (WF1: Local.wf lc1 mem1)\n          (SC1: Memory.closed_timemap sc1 mem1)\n          (CLOSED1: Memory.closed mem1):\n      <<WF2: Local.wf lc2 mem2>> /\\\n      <<SC2: Memory.closed_timemap sc2 mem2>> /\\\n      <<CLOSED2: Memory.closed mem2>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview lc1) (Local.tview lc2)>> /\\\n      <<SC_FUTURE: TimeMap.le sc1 sc2>> /\\\n      <<MEM_FUTURE: Memory.future mem1 mem2>>.\n    Proof.\n      inv STEP.\n      - esplits; eauto; try refl.\n      - inv LOCAL.\n        exploit Local.read_step_future; eauto. i. des.\n        esplits; eauto; try refl.\n      - inv LOCAL.\n        exploit Local.write_step_future; eauto; try by econs. i. des.\n        esplits; eauto; try refl.\n      - inv LOCAL1. inv LOCAL2.\n        exploit Local.read_step_future; eauto. i. des.\n        exploit Local.write_step_future; eauto; try by econs. i. des.\n        esplits; eauto. etrans; eauto.\n      - exploit Local.fence_step_future; eauto. i. des. esplits; eauto; try refl.\n      - exploit Local.fence_step_future; eauto. i. des. esplits; eauto; try refl.\n      - esplits; eauto; try refl.\n    Qed.\n\n    Lemma program_step_inhabited\n          e lc1 sc1 mem1 lc2 sc2 mem2\n          (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n          (INHABITED1: Memory.inhabited mem1):\n      <<INHABITED2: Memory.inhabited mem2>>.\n    Proof.\n      inv STEP; eauto.\n      - inv LOCAL. inv STEP. inv WRITE.\n        inv PROMISE; eauto using Memory.add_inhabited, Memory.split_inhabited, Memory.lower_inhabited, Memory.cancel_inhabited.\n      - inv LOCAL2. inv STEP. inv WRITE.\n        inv PROMISE; eauto using Memory.add_inhabited, Memory.split_inhabited, Memory.lower_inhabited, Memory.cancel_inhabited.\n    Qed.\n\n\n    (* step_disjoint *)\n\n    Lemma program_step_disjoint\n          e lc1 sc1 mem1 lc2 sc2 mem2 lc\n          (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n          (WF1: Local.wf lc1 mem1)\n          (SC1: Memory.closed_timemap sc1 mem1)\n          (CLOSED1: Memory.closed mem1)\n          (DISJOINT1: Local.disjoint lc1 lc)\n          (WF: Local.wf lc mem1):\n      <<DISJOINT2: Local.disjoint lc2 lc>> /\\\n      <<WF: Local.wf lc mem2>>.\n    Proof.\n      inv STEP.\n      - esplits; eauto.\n      - inv LOCAL. exploit Local.read_step_disjoint; eauto.\n      - inv LOCAL. exploit Local.write_step_disjoint; eauto.\n      - inv LOCAL1. inv LOCAL2.\n        exploit Local.read_step_future; eauto. i. des.\n        exploit Local.read_step_disjoint; eauto. i. des.\n        exploit Local.write_step_disjoint; eauto.\n      - exploit Local.fence_step_disjoint; eauto.\n      - exploit Local.fence_step_disjoint; eauto.\n      - esplits; eauto.\n    Qed.\n\n    Lemma program_step_promises_bot\n          e lc1 sc1 mem1 lc2 sc2 mem2\n          (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n          (PROMISES: (Local.promises lc1) = Memory.bot):\n      (Local.promises lc2) = Memory.bot.\n    Proof.\n      inv STEP; try inv LOCAL; ss; try inv STEP; ss.\n      - eapply Memory.write_promises_bot; eauto.\n      - inv LOCAL1. inv LOCAL2. inv STEP. inv STEP0.\n        eapply Memory.write_promises_bot; eauto.\n    Qed.\n  End OrdLocal.\nEnd OrdLocal.\n\n\nModule OrdThread.\n  Section OrdThread.\n    Variable lang: language.\n    Variable L: Loc.t -> bool.\n    Variable ordc: Ordering.t.\n\n    Inductive program_step (e:ThreadEvent.t): forall (e1 e2:Thread.t lang), Prop :=\n    | program_step_intro\n        st1 lc1 sc1 mem1\n        st2 lc2 sc2 mem2\n        (STATE: (Language.step lang) (ThreadEvent.get_program_event e) st1 st2)\n        (LOCAL: OrdLocal.program_step L ordc e lc1 sc1 mem1 lc2 sc2 mem2):\n        program_step e (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2)\n    .\n    Hint Constructors program_step.\n\n    Inductive step: forall (pf:bool) (e:ThreadEvent.t) (e1 e2:Thread.t lang), Prop :=\n    | step_promise\n        pf e e1 e2\n        (STEP: Thread.promise_step pf e e1 e2)\n        (PF: PF.pf_event L e):\n        step pf e e1 e2\n    | step_program\n        e e1 e2\n        (STEP: program_step e e1 e2):\n        step true e e1 e2\n    .\n    Hint Constructors step.\n\n    Inductive step_allpf (e: ThreadEvent.t) (e1 e2: Thread.t lang): Prop :=\n    | step_nopf_intro\n        pf\n        (STEP: step pf e e1 e2)\n    .\n    Hint Constructors step_allpf.\n\n    Lemma allpf pf: step pf <3= step_allpf.\n    Proof.\n      i. econs. eauto.\n    Qed.\n\n    Definition pf_tau_step := tau (step true).\n    Hint Unfold pf_tau_step.\n\n    Definition tau_step := tau step_allpf.\n    Hint Unfold tau_step.\n\n    Definition all_step := union step_allpf.\n    Hint Unfold all_step.\n\n    Inductive opt_step: forall (e: ThreadEvent.t) (e1 e2: Thread.t lang), Prop :=\n    | step_none\n        e:\n        opt_step ThreadEvent.silent e e\n    | step_some\n        pf e e1 e2\n        (STEP: step pf e e1 e2):\n        opt_step e e1 e2\n    .\n    Hint Constructors opt_step.\n\n    Definition steps_failure (e1: Thread.t lang): Prop :=\n      exists e2 e3,\n        <<STEPS: rtc tau_step e1 e2>> /\\\n        <<FAILURE: step true ThreadEvent.failure e2 e3>>.\n    Hint Unfold steps_failure.\n\n    Definition consistent (e: Thread.t lang): Prop :=\n      forall mem1 sc1\n        (CAP: Memory.cap (Thread.memory e) mem1)\n        (SC_MAX: Memory.max_concrete_timemap mem1 sc1),\n        <<FAILURE: steps_failure (Thread.mk lang (Thread.state e) (Thread.local e) sc1 mem1)>> \\/\n        exists e2,\n          <<STEPS: rtc tau_step (Thread.mk lang (Thread.state e) (Thread.local e) sc1 mem1) e2>> /\\\n          <<PROMISES: (Local.promises (Thread.local e2)) = Memory.bot>>.\n\n\n    (* future *)\n\n    Lemma program_step_future\n          e e1 e2\n          (STEP: program_step e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      inv STEP. ss. eapply OrdLocal.program_step_future; eauto.\n    Qed.\n\n    Lemma step_future\n          pf e e1 e2\n          (STEP: step pf e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      inv STEP.\n      - eapply Thread.promise_step_future; eauto.\n      - eapply program_step_future; eauto.\n    Qed.\n\n    Lemma rtc_all_step_future\n          e1 e2\n          (STEPS: rtc all_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      revert WF1 SC1 CLOSED1. induction STEPS; i.\n      - esplits; eauto; refl.\n      - inv H. inv USTEP. exploit step_future; eauto. i. des.\n        exploit IHSTEPS; eauto. i. des.\n        esplits; eauto; etrans; eauto.\n    Qed.\n\n    Lemma rtc_tau_step_future\n          e1 e2\n          (STEPS: rtc tau_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      eapply rtc_all_step_future; eauto.\n      eapply rtc_implies; try exact STEPS.\n      apply tau_union.\n    Qed.\n\n\n    (* disjoint *)\n\n    Lemma step_disjoint\n          pf e e1 e2 lc\n          (STEP: step pf e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (DISJOINT1: Local.disjoint (Thread.local e1) lc)\n          (WF: Local.wf lc (Thread.memory e1)):\n      <<DISJOINT2: Local.disjoint (Thread.local e2) lc>> /\\\n      <<WF: Local.wf lc (Thread.memory e2)>>.\n    Proof.\n      inv STEP.\n      - eapply Thread.promise_step_disjoint; eauto.\n      - inv STEP0. eapply OrdLocal.program_step_disjoint; eauto.\n    Qed.\n\n    Lemma rtc_all_step_disjoint\n          e1 e2 lc\n          (STEPS: rtc all_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (DISJOINT1: Local.disjoint (Thread.local e1) lc)\n          (WF: Local.wf lc (Thread.memory e1)):\n      <<DISJOINT2: Local.disjoint (Thread.local e2) lc>> /\\\n      <<WF: Local.wf lc (Thread.memory e2)>>.\n    Proof.\n      revert WF1 SC1 CLOSED1 DISJOINT1 WF.\n      induction STEPS; i; eauto.\n      inv H. inv USTEP.\n      exploit step_future; eauto. i. des.\n      exploit step_disjoint; eauto. i. des.\n      eauto.\n    Qed.\n\n    Lemma rtc_tau_step_disjoint\n          e1 e2 lc\n          (STEPS: rtc tau_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (DISJOINT1: Local.disjoint (Thread.local e1) lc)\n          (WF: Local.wf lc (Thread.memory e1)):\n      <<DISJOINT2: Local.disjoint (Thread.local e2) lc>> /\\\n      <<WF: Local.wf lc (Thread.memory e2)>>.\n    Proof.\n      eapply rtc_all_step_disjoint; try exact DISJOINT1; eauto.\n      eapply rtc_implies; try exact STEPS.\n      apply tau_union.\n    Qed.\n\n\n    (* promise_consistent *)\n\n    Lemma step_promise_consistent\n          pf e e1 e2\n          (STEP: step pf e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (CONS: Local.promise_consistent (Thread.local e2)):\n      Local.promise_consistent (Thread.local e1).\n    Proof.\n      inv STEP; ss.\n      - inv STEP0. s.\n        eapply promise_step_promise_consistent; eauto.\n      - inv STEP0. inv LOCAL; ss.\n        + inv LOCAL0. eapply read_step_promise_consistent; eauto.\n        + inv LOCAL0. eapply write_step_promise_consistent; eauto.\n        + inv LOCAL1. inv LOCAL2.\n          exploit Local.read_step_future; eauto. i. des.\n          eapply read_step_promise_consistent; eauto.\n          eapply write_step_promise_consistent; eauto.\n        + eapply fence_step_promise_consistent; eauto.\n        + eapply fence_step_promise_consistent; eauto.\n    Qed.\n\n    Lemma rtc_all_step_promise_consistent\n          e1 e2\n          (STEPS: rtc all_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (CONS: Local.promise_consistent (Thread.local e2)):\n      Local.promise_consistent (Thread.local e1).\n    Proof.\n      revert WF1 SC1 CLOSED1 CONS. induction STEPS; ss. i.\n      inv H. inv USTEP. exploit step_future; eauto. i. des.\n      eapply step_promise_consistent; eauto.\n    Qed.\n\n    Lemma rtc_tau_step_promise_consistent\n          e1 e2\n          (STEPS: rtc tau_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (CONS: Local.promise_consistent (Thread.local e2)):\n      Local.promise_consistent (Thread.local e1).\n    Proof.\n      eapply rtc_all_step_promise_consistent; try exact CONS; eauto.\n      eapply rtc_implies; try exact STEPS.\n      apply tau_union.\n    Qed.\n\n    Lemma cap_step_current_step\n          pf e e0 e1 fe0\n          (THREAD: thread_map ident_map e0 fe0)\n          (STEP: step pf e e0 e1)\n          (LOCAL: Local.wf (Thread.local e0) (Thread.memory e0))\n          (FLOCAL: Local.wf (Thread.local fe0) (Thread.memory fe0))\n          (MEMORY: Memory.closed (Thread.memory e0))\n          (FMEMORY: Memory.closed (Thread.memory fe0))\n          (SC: Memory.closed_timemap (Thread.sc e0) (Thread.memory e0))\n          (FSC: Memory.closed_timemap (Thread.sc fe0) (Thread.memory fe0))\n      :\n        exists fe fe1,\n          (<<THREAD: thread_map ident_map e1 fe1>>) /\\\n          (<<STEP: step pf fe fe0 fe1>>) /\\\n          (<<EVENT: tevent_map ident_map fe e>>).\n    Proof.\n      assert (MAPLT: mapping_map_lt ident_map).\n      { eapply ident_map_lt. }\n      assert (MAPLE: mapping_map_le ident_map).\n      { eapply ident_map_le. }\n      assert (MAPEQ: mapping_map_eq ident_map).\n      { eapply ident_map_eq. }\n\n      inv THREAD. ss. inv STEP.\n      { inv STEP0. inv LOCAL1.\n        exploit promise_map; try apply PROMISE; eauto; ss.\n        { eapply FLOCAL. }\n        { eapply LOCAL0. }\n        { eapply mapping_map_lt_non_collapsable; eauto. }\n        { eapply ident_map_message. }\n        i. des. inv LOCAL0.\n        eexists _, (Thread.mk _ st (Local.mk (Local.tview flc) fprom1) fsc fmem1).\n        esplits; eauto.\n        { econs; eauto.\n          { econs; eauto. }\n          { eapply mapping_map_lt_collapsable_unwritable; eauto. }\n        }\n        { econs 1. econs.\n          { econs; eauto. eapply closed_message_map; eauto.\n            eapply ident_map_message. }\n          { inv KIND; ss. inv MSG; ss. }\n          { unfold PF.pf_event in *. i. inv PROMISE1. eauto. }\n        }\n        { econs; eauto; ss. eapply ident_map_message. }\n      }\n      { inv STEP0. inv LOCAL1.\n        { esplits; eauto.\n          { econs; eauto. }\n          { econs 2; eauto. econs; eauto. econs 1; eauto. }\n          { econs; eauto. }\n        }\n        { inv LOCAL2. exploit read_step_map; eauto.\n          { eapply ident_map_bot. }\n          { eapply FLOCAL. } i. des.\n          exists (ThreadEvent.read loc fto val freleased ord). esplits.\n          { econs; eauto. eapply mapping_map_lt_collapsable_unwritable; eauto. }\n          { econs 2; eauto. econs; eauto. econs 2; eauto. econs; eauto. }\n          { econs; eauto. }\n        }\n        { inv LOCAL2. hexploit write_step_map; try eassumption; eauto.\n          { eapply ident_map_bot. }\n          { eapply FLOCAL. }\n          { eapply FLOCAL. }\n          { econs 2. }\n          { refl. }\n          { refl. }\n          { eapply mapping_map_lt_non_collapsable; eauto. }\n          i. des.\n          exists (ThreadEvent.write loc from to val freleasedw ord). esplits.\n          { econs; eauto. eapply mapping_map_lt_collapsable_unwritable; eauto. }\n          { econs 2; eauto. econs; eauto. econs 3; eauto. econs; eauto. }\n          { econs; eauto; ss. }\n        }\n        { inv LOCAL2. inv LOCAL3. exploit read_step_map; eauto.\n          { eapply ident_map_bot. }\n          { eapply FLOCAL. } i. des.\n          hexploit Local.read_step_future; try apply STEP; eauto. i. des.\n          hexploit Local.read_step_future; try apply READ; eauto. i. des.\n          hexploit write_step_map; try eapply STEP0; try eassumption; eauto.\n          { eapply ident_map_bot. }\n          { eapply WF0. }\n          { eapply WF0. }\n          { eapply mapping_map_lt_collapsable_unwritable; eauto. }\n          { refl. }\n          { eapply mapping_map_lt_non_collapsable; eauto. }\n          i. des.\n          exists (ThreadEvent.update loc fto tsw valr valw freleased freleasedw ordr ordw). esplits.\n          { econs; eauto. eapply mapping_map_lt_collapsable_unwritable; eauto. }\n          { econs 2; eauto. econs; eauto. econs 4; eauto.\n            { econs; eauto. }\n            { econs; eauto. }\n          }\n          { econs; eauto; ss. }\n        }\n        { inv LOCAL2. exploit fence_step_map; try apply FENCE; eauto.\n          { eapply ident_map_bot. }\n          { eapply FLOCAL. } i. des.\n          exists (ThreadEvent.fence ordr ordw). esplits.\n          { econs; eauto. }\n          { econs 2; eauto. econs; eauto. econs 5; eauto. }\n          { econs; eauto; ss. }\n        }\n        { inv LOCAL2. exploit fence_step_map; eauto.\n          { eapply ident_map_bot. }\n          { eapply FLOCAL. } i. des.\n          exists (ThreadEvent.syscall e0). esplits.\n          { econs; eauto. }\n          { econs 2; eauto. econs; eauto. econs 6; eauto. }\n          { econs; eauto; ss. }\n        }\n        { inv LOCAL2. exploit failure_step_map; eauto. i.\n          exists (ThreadEvent.failure). esplits.\n          { econs; eauto. }\n          { econs 2; eauto. econs; eauto. econs 7; eauto. }\n          { econs; eauto; ss. }\n        }\n      }\n    Qed.\n  End OrdThread.\nEnd OrdThread.\n\n\nModule OrdConfiguration.\n  Section OrdConfiguration.\n    Variable L: Loc.t -> bool.\n    Variable ordc: Ordering.t.\n\n    Inductive step: forall (e: ThreadEvent.t) (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n    | step_intro\n        e tid c1 lang st1 lc1 e2 e3 st4 lc4 sc4 memory4\n        (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))\n        (CANCELS: rtc (@Thread.cancel_step _) (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1)) e2)\n        (STEP: OrdThread.opt_step L ordc e e2 e3)\n        (RESERVES: rtc (@Thread.reserve_step _) e3 (Thread.mk _ st4 lc4 sc4 memory4))\n        (CONSISTENT: e <> ThreadEvent.failure ->\n                     OrdThread.consistent L ordc (Thread.mk _ st4 lc4 sc4 memory4)):\n        step e tid c1 (Configuration.mk (IdentMap.add tid (existT _ _ st4, lc4) (Configuration.threads c1)) sc4 memory4)\n    .\n    Hint Constructors step.\n\n    Inductive all_step (c1 c2: Configuration.t): Prop :=\n    | all_step_intro\n        e tid\n        (STEP: step e tid c1 c2)\n    .\n    Hint Constructors all_step.\n\n    Inductive machine_step: forall (e: MachineEvent.t) (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n    | machine_step_instro\n        e tid c1 c2\n        (STEP: step e tid c1 c2):\n        machine_step (ThreadEvent.get_machine_event e) tid c1 c2\n    .\n    Hint Constructors machine_step.\n  End OrdConfiguration.\nEnd OrdConfiguration.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/ldrfra/OrdStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791787121629465, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.24652096223982087}}
{"text": "Require Import VST.veric.juicy_base.\nRequire Import VST.veric.shares.\nImport cjoins.\n\nDefinition dec_share_nonidentity (sh: Share.t) : {~identity sh}+{identity sh} :=\n   (Sumbool.sumbool_not _ _ (dec_share_identity sh)).\n\nDefinition perm_of_sh (sh: Share.t): option permission :=\n  if writable_share_dec sh\n  then if eq_dec sh Share.top\n            then Some Freeable\n            else Some Writable\n    else if readable_share_dec sh\n         then Some Readable\n         else if eq_dec sh Share.bot\n                   then None\n              else Some Nonempty.\nFunctional Scheme perm_of_sh_ind := Induction for perm_of_sh Sort Prop.\n\n\nDefinition contents_at (m: mem) (loc: address) : memval :=\n  ZMap.get (snd loc) (PMap.get (fst loc) (mem_contents m)).\n\nDefinition contents_cohere (m: mem) (phi: rmap) :=\n  forall rsh sh v loc pp, phi @ loc = YES rsh sh (VAL v) pp -> contents_at m loc = v /\\ pp=NoneP.\n\nDefinition valshare (r: resource) : share :=\n    match r with\n      | YES sh rsh _ _ => Share.glb Share.Rsh sh\n      | _ => Share.bot\n    end.\n\nDefinition res_retain' (r: resource) : Share.t :=\n match r with\n  | NO sh _ => sh\n  | YES sh _ _ _ => Share.glb Share.Lsh sh\n  | PURE _ _ => Share.top\n end.\n\nDefinition perm_of_res (r: resource) :=\n  (*  perm_of_sh (res_retain' r) (valshare r). *)\n match r with\n | NO sh _ => if eq_dec sh Share.bot then None else Some Nonempty\n | PURE _ _ => Some Nonempty\n | YES sh rsh (VAL _) _ => perm_of_sh sh\n | YES sh rsh _ _ => Some Nonempty\n end.\n\n(*To do a case analysis over perm_of_res, use:\nfunctional induction (perm_of_res_explicit r1) using perm_of_res_expl_ind \nWe define the induction shceme bellow. *)\nDefinition perm_of_res_lock_explicit\n             (r : compcert_rmaps.RML.R.resource):=\n    match r with\n    | compcert_rmaps.RML.R.NO _ _ => None\n    | compcert_rmaps.RML.R.YES sh _ (compcert_rmaps.VAL _) _ => None\n    | compcert_rmaps.RML.R.YES sh _ (compcert_rmaps.LK _) _ =>\n      if writable_share_dec (Share.glb Share.Rsh sh)\n      then if eq_dec (Share.glb Share.Rsh sh) Share.top then Some Freeable else Some Writable\n      else if readable_share_dec (Share.glb Share.Rsh sh) then Some Readable else\n             if eq_dec  (Share.glb Share.Rsh sh) Share.bot then None else Some Nonempty\n    | compcert_rmaps.RML.R.YES sh _ (compcert_rmaps.CT _) _ => \n      if writable_share_dec (Share.glb Share.Rsh sh)\n      then if eq_dec (Share.glb Share.Rsh sh) Share.top then Some Freeable else Some Writable\n      else if readable_share_dec (Share.glb Share.Rsh sh) then Some Readable else\n             if eq_dec  (Share.glb Share.Rsh sh) Share.bot then None else Some Nonempty\n    | compcert_rmaps.RML.R.YES sh _ (compcert_rmaps.FUN _ _) _ => None\n    | compcert_rmaps.RML.R.PURE _ _ => None\n    end.\n      \n  Functional Scheme perm_of_res_lock_expl_ind := Induction for perm_of_res_lock_explicit Sort Prop.\n\n\n\nDefinition perm_of_res' (r: resource) :=\n  (*  perm_of_sh (res_retain' r) (valshare r). *)\n match r with\n | NO sh _ => if eq_dec sh Share.bot then None else Some Nonempty\n | PURE _ _ => Some Nonempty\n | YES sh _ _ _ => perm_of_sh sh\n end.\n\nDefinition perm_of_res_lock (r: resource) := \n  (*  perm_of_sh (res_retain' r) (valshare r). *)\n match r with\n | YES sh rsh (LK _) _ => perm_of_sh (Share.glb Share.Rsh sh)\n | YES sh rsh (CT _) _ => perm_of_sh (Share.glb Share.Rsh sh)\n | _ => None \n end.\n(*To do a case analysis over perm_of_res_lock, use:\nfunctional induction (perm_of_res_lock_explicit r1) using perm_of_res_lock_expl_ind \nWe define the induction shceme bellow. *)\nDefinition perm_of_res_explicit\n               (r : compcert_rmaps.RML.R.resource):=\n        match r with\n        | compcert_rmaps.RML.R.NO sh _ => if eq_dec sh Share.bot then None else Some Nonempty\n           | compcert_rmaps.RML.R.YES sh _ (compcert_rmaps.VAL _) _ =>\n             if writable_share_dec sh\n             then if eq_dec sh Share.top then Some Freeable else Some Writable\n             else\n               if readable_share_dec sh\n               then Some Readable\n               else if eq_dec sh Share.bot then None else Some Nonempty\n           | compcert_rmaps.RML.R.YES sh _ (compcert_rmaps.LK _) _ => Some Nonempty\n           | compcert_rmaps.RML.R.YES sh _ (compcert_rmaps.CT _) _ => Some Nonempty\n           | compcert_rmaps.RML.R.YES sh _ (compcert_rmaps.FUN _ _) _ => Some Nonempty\n           | compcert_rmaps.RML.R.PURE _ _ => Some Nonempty\n        end.\n      \nFunctional Scheme perm_of_res_expl_ind := Induction for perm_of_res_explicit Sort Prop.\n\n\n\n(*Definition perm_of_res_lock (r: resource) :=\n  (*  perm_of_sh (res_retain' r) (valshare r). *)\n match r with\n | NO sh => if eq_dec sh Share.bot then None else Some Nonempty\n | PURE _ _ => Some Nonempty\n | YES rsh sh (LK _) _ => perm_of_sh rsh (pshare_sh sh)\n | YES rsh sh (CT _) _ => perm_of_sh rsh (pshare_sh sh)\n | YES rsh sh _ _ => Some Nonempty\n end. *)\n\nLemma Rsh_not_top: Share.Rsh <> Share.top.\nProof.\nunfold Share.Rsh.\ncase_eq (Share.split Share.top); intros.\nsimpl; intro. subst.\napply nonemp_split_neq2 in H.\napply H; auto.\napply top_share_nonidentity.\nQed.\n\nLemma nonidentity_Rsh: ~identity Share.Rsh.\nProof.\nunfold Share.Rsh.\ncase_eq (Share.split Share.top); intros.\nsimpl; intro.\napply split_nontrivial' in H.\napply top_share_nonidentity; auto.\nauto.\nQed.\n\nLemma perm_of_sh_fullshare: perm_of_sh fullshare = Some Freeable.\nProof. unfold perm_of_sh.\n  rewrite if_true. rewrite if_true by auto. auto.\n   unfold fullshare.\n   apply writable_share_top.\nQed.\n\nLemma nonreadable_extern_retainer: ~readable_share extern_retainer.\nunfold extern_retainer, readable_share.\nintro H; apply H; clear H.\nassert (Share.glb Share.Rsh\n     (fst (Share.split Share.Lsh)) = Share.bot); [ | rewrite H; auto].\napply sub_glb_bot with Share.Lsh.\ndestruct (Share.split Share.Lsh) eqn:H.\napply Share.split_together in H.\nsimpl.\nrewrite <- H.\napply leq_join_sub.\napply Share.lub_upper1.\napply glb_Rsh_Lsh.\nQed.\n\nLemma Lsh_nonreadable: ~readable_share Share.Lsh.\nProof.\nunfold readable_share; intros.\nrewrite glb_Rsh_Lsh.\nauto.\nQed.\n\nLemma perm_of_res_op1:\n  forall r,\n    perm_order'' (perm_of_res' r) (perm_of_res r).\nProof.\n  destruct r eqn:?; simpl.\n  - if_tac; constructor.\n  - unfold perm_of_sh.\n    if_tac. if_tac; destruct k; constructor.\n    if_tac. destruct k; constructor.\n    rewrite if_false by auto. destruct k; constructor.\n  - constructor.\nQed.\n\nLemma perm_of_res_op2:\n  forall r,\n    perm_order'' (perm_of_res' r) (perm_of_res_lock r).\nProof.\n  destruct r; simpl; auto.\n  - if_tac; constructor.\n  - destruct k; try solve [destruct (perm_of_sh sh); constructor].\n   +\n    unfold perm_of_sh.\n    if_tac. if_tac.\n    repeat if_tac; constructor.\n    rewrite if_true. rewrite if_false. constructor.\n    apply glb_Rsh_not_top.\n    apply writable_share_glb_Rsh; auto.\n    rewrite if_true by auto.\n    rewrite if_false. rewrite if_true. constructor.\n    unfold readable_share. rewrite glb_twice; auto.\n    contradict H. unfold writable_share in *. eapply join_sub_trans; eauto.\n    apply leq_join_sub. apply Share.glb_lower2.\n   +\n    unfold perm_of_sh.\n    if_tac. if_tac.\n    rewrite if_true by apply (writable_share_glb_Rsh H).\n    subst.\n    rewrite if_false by apply glb_Rsh_not_top. constructor.\n    rewrite if_true by (apply writable_share_glb_Rsh; auto).\n    rewrite if_false by apply glb_Rsh_not_top. constructor.\n    rewrite if_true by auto.\n    rewrite if_false.\n    rewrite if_true. constructor.\n    unfold readable_share. rewrite glb_twice; auto.\n    contradict H. unfold writable_share in *. eapply join_sub_trans; eauto.\n    apply leq_join_sub. apply Share.glb_lower2.\nQed.\n\nDefinition access_cohere (m: mem)  (phi: rmap) :=\n  forall loc,  access_at m loc Cur = perm_of_res (phi @ loc).\n\nDefinition max_access_at m loc := access_at m loc Max.\n\nDefinition max_access_cohere (m: mem) (phi: rmap)  :=\n  forall loc,\n    perm_order'' (max_access_at m loc) (perm_of_res' (phi @ loc)).\n\n(*\nDefinition max_access_cohere (m: mem) (phi: rmap)  :=\n  forall loc,\n   match phi @ loc with\n   | YES rsh sh _ _ => perm_order'' (max_access_at m loc) (perm_of_sh rsh (pshare_sh sh))\n   | NO rsh => perm_order'' (max_access_at m loc) (perm_of_sh rsh Share.bot )\n   | PURE _ _ => (fst loc < nextblock m)%positive\n  end. *)\n\nDefinition alloc_cohere (m: mem) (phi: rmap) :=\n forall loc,  (fst loc >= nextblock m)%positive -> phi @ loc = NO Share.bot bot_unreadable.\n\nInductive juicy_mem: Type :=\n  mkJuicyMem: forall (m: mem) (phi: rmap)\n    (JMcontents: contents_cohere m phi)\n    (JMaccess: access_cohere m phi)\n    (JMmax_access: max_access_cohere m phi)\n    (JMalloc: alloc_cohere m phi),\n       juicy_mem.\n\nSection selectors.\nVariable (j: juicy_mem).\nDefinition m_dry := match j with mkJuicyMem m _ _ _ _ _ => m end.\nDefinition m_phi := match j with mkJuicyMem _ phi _ _ _ _ => phi end.\nLemma juicy_mem_contents: contents_cohere m_dry m_phi.\nProof. unfold m_dry, m_phi; destruct j; auto. Qed.\nLemma juicy_mem_access: access_cohere m_dry m_phi.\nProof. unfold m_dry, m_phi; destruct j; auto. Qed.\nLemma juicy_mem_max_access: max_access_cohere m_dry m_phi.\nProof. unfold m_dry, m_phi; destruct j; auto. Qed.\nLemma juicy_mem_alloc_cohere: alloc_cohere m_dry m_phi.\nProof. unfold m_dry, m_phi; destruct j; auto. Qed.\nEnd selectors.\n\nLemma perm_of_empty_inv {s} : perm_of_sh s = None -> s = Share.bot.\nProof.\nintros.\nunfold perm_of_sh in*.\nif_tac in H; subst; auto.\nif_tac in H; subst; auto.\ninv H. inv H.\nif_tac in H; subst; auto.\ninv H.\nif_tac in H; subst; auto. inv H.\nQed.\n\nLemma writable_join_sub: forall loc phi1 phi2,\n  join_sub phi1 phi2 -> writable loc phi1 -> writable loc phi2.\nProof.\nintros.\nhnf in H0|-*.\ndestruct H; generalize (resource_at_join _ _ _ loc H); clear H.\nrevert H0; destruct (phi1 @ loc); intros; try contradiction.\ndestruct H0; subst.\ninv H.\nsplit. eapply join_writable1; eauto. auto.\ncontradiction (join_writable_readable RJ H0 rsh2).\nQed.\n\nLemma writable_inv: forall phi loc, writable loc phi ->\n  exists sh, exists rsh, exists k, exists pp, \n       phi @ loc = YES sh rsh k pp /\\ \n       writable_share sh /\\\n       isVAL k.\nProof.\nsimpl.\nintros phi loc H.\ndestruct (phi @ loc); try solve [inversion H].\ndestruct H.\ndo 4 eexists. split. reflexivity. split; auto.\nQed.\n\nLemma nreadable_inv: forall phi loc, ~readable loc phi \n  -> (exists sh, exists nsh, phi @ loc = NO sh nsh)\n   \\/ (exists sh, exists rsh, exists k, exists pp, phi @ loc = YES sh rsh k pp /\\ ~isVAL k)\n   \\/ (exists k, exists pp, phi @ loc = PURE k pp).\nProof.\nintros.\nsimpl in H.\ndestruct (phi@loc); eauto 50.\nQed.\n\nLemma VAL_valid:\n forall (f: address -> option (rshare*kind)),\n   (forall l sh k, f l = Some (sh,k) -> isVAL k) ->\n   AV.valid f.\nProof.\nintros.\nintros b ofs.\ncase_eq (f (b,ofs)); intros; auto.\ndestruct p.\nspecialize (H _ _ _ H0).\ndestruct k; solve [\n    auto\n  | inversion H ].\nQed.\n\nLemma age1_joinx {A}  {JA: Join A}{PA: Perm_alg A}{agA: ageable A}{AgeA: Age_alg A} : forall phi1 phi2 phi3 phi1' phi2' phi3',\n             age phi1 phi1' -> age phi2 phi2' -> age phi3 phi3' ->\n             join phi1 phi2 phi3 -> join phi1' phi2' phi3'.\nProof.\nintros.\ndestruct (age1_join _ H2 H) as [phi2'' [phi3'' [? [? ?]]]].\nunfold age in *.\ncongruence.\nQed.\n\nLemma constructive_age1_join  {A}  {JA: Join A}{PA: Perm_alg A}{agA: ageable A}{AgeA: Age_alg A} : forall x y z x' : A,\n       join x y z ->\n       age x x' ->\n       { yz' : A*A | join x' (fst yz') (snd yz') /\\ age y (fst yz') /\\ age z (snd yz')}.\nProof.\npose proof I.\nintros.\ncase_eq (age1 y); [intros y' ? | intros].\ncase_eq (age1 z); [intros z' ? | intros].\nexists (y',z').\nsimpl.\nsplit; auto.\napply (age1_joinx x y z x' y' z' H1 H2 H3 H0).\nelimtype False.\ndestruct (age1_join _ H0 H1) as [? [? [? [? ?]]]].\nunfold age in *.\ncongruence.\nelimtype False.\ndestruct (age1_join _ H0 H1) as [? [? [? [? ?]]]].\nunfold age in *.\ncongruence.\nQed.\n\nLemma age1_constructive_joins_eq : forall {A}  {JA: Join A}{PA: Perm_alg A}{agA: ageable A}{AgeA: Age_alg A}  {phi1 phi2},\n  constructive_joins phi1 phi2\n  -> forall {phi1'}, age1 phi1 = Some phi1'\n  -> forall {phi2'}, age1 phi2 = Some phi2'\n  -> constructive_joins phi1' phi2'.\nProof.\nintros.\ndestruct X as [? ?H].\ndestruct (constructive_age1_join _ _ _ _ H1 H) as [[y z] [? [? ?]]].\nsimpl in *.\nunfold age in H3. rewrite H0 in H3; inv H3; econstructor; eauto.\nQed.\n\n\nProgram Definition age1_juicy_mem (j: juicy_mem): option juicy_mem :=\n      match age1 (m_phi j) with\n        | Some phi' => Some (mkJuicyMem (m_dry j) phi' _ _ _ _)\n        | None => None\n      end.\nNext Obligation.  (* contents_cohere *)\n assert (necR (m_phi j) phi')\n   by (constructor 1; symmetry in Heq_anonymous; apply Heq_anonymous).\n destruct j; hnf; simpl in *; intros.\n case_eq (phi @ loc); intros.\n apply (necR_NO _ _ _ _ _ H) in H1. congruence.\n generalize (necR_YES _ _ _ _ _ _ _ H H1); intros.\n rewrite H0 in H2. inv H2.\n destruct (JMcontents sh0 r v loc _ H1). subst; split; auto.\n rewrite (necR_PURE _ _ _ _ _ H H1) in H0. inv H0.\nQed.\nNext Obligation. (* access_cohere *)\n assert (necR (m_phi j) phi')\n   by (constructor 1; symmetry in Heq_anonymous; apply Heq_anonymous).\n destruct j; hnf; simpl in *; intros.\n generalize (JMaccess loc); case_eq (phi @ loc); intros.\n apply (necR_NO _ _ loc _ _ H) in H0. rewrite H0; auto.\n rewrite (necR_YES _ _ _ _ _ _ _ H H0); auto.\n rewrite (necR_PURE _ _ _ _ _ H H0); auto.\nQed.\nNext Obligation. (* max_access_cohere *)\n assert (necR (m_phi j) phi')\n   by (constructor 1; symmetry in Heq_anonymous; apply Heq_anonymous).\n destruct j; hnf; simpl in *; intros.\n generalize (JMmax_access loc); case_eq (phi @ loc); intros.\n apply (necR_NO _ _ loc _ _ H) in H0. rewrite H0; auto.\n rewrite (necR_YES _ _ _ _ _ _ _ H H0); auto.\n rewrite (necR_PURE _ _ _ _ _ H H0); auto.\nQed.\nNext Obligation. (* alloc_cohere *)\n assert (necR (m_phi j) phi')\n   by (constructor 1; symmetry in Heq_anonymous; apply Heq_anonymous).\n destruct j; hnf; simpl in *; intros.\n specialize (JMalloc loc H0).\n apply (necR_NO _ _ loc _ _ H). auto.\nQed.\n\nLemma age1_juicy_mem_unpack: forall j j',\n  age1_juicy_mem j = Some j' ->\n  age (m_phi j)  (m_phi j')\n  /\\ m_dry j = m_dry j'.\nProof.\nintros.\nunfold age1_juicy_mem in H.\ninvSome.\ninv H.\nsplit; simpl; auto.\nsymmetry in H0; apply H0.\nQed.\n\nLemma age1_juicy_mem_unpack': forall j j',\n  age (m_phi j)  (m_phi j')  /\\ m_dry j = m_dry j' ->\n  age1_juicy_mem j = Some j'.\nProof.\n  intuition.\n  unfold age1_juicy_mem.\n  generalize (eq_refl (age1 (m_phi j))).\n  pattern (age1 (m_phi j)) at 1 3.\n  rewrite H0;  clear H0. intros H0.\n  f_equal.\n  destruct j, j'; simpl in *; subst; repeat f_equal; try apply proof_irr.\nQed.\n\nLemma age1_juicy_mem_unpack'': forall j j',\n  age (m_phi j)  (m_phi j')  -> m_dry j = m_dry j' ->\n  age1_juicy_mem j = Some j'.\nProof.\n  intros.\n  apply age1_juicy_mem_unpack'.\n split; auto.\nQed.\n\n(* TODO: move into rmaps_lemmas *)\nLemma rmap_join_eq_level: forall phi1 phi2: rmap, joins phi1 phi2 -> level phi1 = level phi2.\nProof.\nintros until phi2; intro H.\ndestruct H as [? H].\napply join_level in H; destruct H; congruence.\nQed.\n\nLemma rmap_join_sub_eq_level: forall phi1 phi2: rmap,\n          join_sub phi1 phi2 -> level phi1 = level phi2.\nProof.\nintros until phi2; intro H.\ndestruct H; apply join_level in H; destruct H; congruence.\nQed.\n\nLemma age1_juicy_mem_None1:\n  forall j, age1_juicy_mem j = None -> age1 (m_phi j) = None.\nProof.\nintros j H.\ndestruct j.\nsimpl.\nunfold age1_juicy_mem in H; simpl in H.\nrevert H; generalize (refl_equal (age1 phi)); pattern (age1 phi) at 1 3; destruct (age1 phi); intros; auto.\ninv H.\nQed.\n\nLemma age1_juicy_mem_None2:\n  forall j, age1 (m_phi j) = None -> age1_juicy_mem j = None.\nProof.\nintros.\nunfold age1_juicy_mem.\ngeneralize (eq_refl (age1 (m_phi j))).\npattern (age1 (m_phi j)) at 1 3.\nrewrite H.\nauto.\nQed.\n\nLemma age1_juicy_mem_Some:\n  forall j j', age1_juicy_mem j = Some j' -> age1 (m_phi j) = Some (m_phi j').\nProof.\nintros.\napply age1_juicy_mem_unpack in H; intuition.\nQed.\n\n\nLemma unage_juicy_mem: forall j' : juicy_mem,\n   exists j : juicy_mem, age1_juicy_mem j = Some j'.\nProof.\nintros.\ndestruct j' as [m phi'].\ndestruct (af_unage age_facts phi') as [phi ?].\nassert (NEC: necR phi phi')  by (constructor 1; auto).\n rename H into Hage.\nassert (contents_cohere m phi).\n  hnf; intros.\n  generalize (necR_YES phi phi' loc rsh sh (VAL v) pp NEC H); intro.\n  destruct (JMcontents _ _ _ _ _ H0).\n  rewrite H2 in H0.\n  split; auto.\n  generalize (necR_YES' _ _ loc rsh sh (VAL v) NEC); intro.\n  apply H3 in H0. congruence.\nassert (access_cohere m phi).\n  hnf; intros.\n  generalize (JMaccess loc); intros.\n  case_eq (phi @ loc); intros.\n  apply (necR_NO _ _ loc _ _ NEC) in H1. rewrite H1 in H0; auto.\n  apply (necR_YES _ _ _ _ _ _ _ NEC) in H1. rewrite H1 in H0; auto.\n  apply (necR_PURE _ _ _ _ _ NEC) in H1. rewrite H1 in H0; auto.\nassert (max_access_cohere m phi).\n  hnf; intros.\n  generalize (JMmax_access loc); intros.\n  case_eq (phi @ loc); intros.\n  apply (necR_NO _ _ _ _ _ NEC) in H2; rewrite H2 in H1; auto.\n  rewrite (necR_YES _ _ _ _ _ _ _ NEC H2) in H1; auto.\n  rewrite (necR_PURE _ _ _ _ _ NEC H2) in H1; auto.\nassert (alloc_cohere m phi).\n  hnf; intros.\n  generalize (JMalloc loc H2); intros.\n  case_eq (phi @ loc); intros.\n  apply (necR_NO _ _ _ _ _ NEC) in H4; rewrite H4 in H3; auto.\n  rewrite (necR_YES _ _ _ _ _ _ _ NEC H4) in H3; inv H3.\n  rewrite (necR_PURE _ _ _ _ _ NEC H4) in H3; inv H3.\nexists (mkJuicyMem m phi H H0 H1 H2).\napply age1_juicy_mem_unpack''; simpl; auto.\nQed.\n\nLemma level1_juicy_mem: forall j: juicy_mem,\n  age1_juicy_mem j = None <-> level (m_phi j) = 0%nat.\nProof.\nintro x.\nsplit; intro H.\napply age1_level0.\napply age1_juicy_mem_None1; auto.\napply age1_level0 in H.\napply age1_juicy_mem_None2.\nauto.\nQed.\n\nLemma level2_juicy_mem: forall j1 j2: juicy_mem,\n   age1_juicy_mem j1 = Some j2 -> level (m_phi j1) = S (level (m_phi j2)).\nProof.\nintros x y H.\ndestruct (age1_juicy_mem_unpack x y H).\n apply age_level in H0. auto.\nQed.\n\nLemma juicy_mem_ageable_facts: ageable_facts juicy_mem (fun j => level (m_phi j)) age1_juicy_mem.\nProof.\nconstructor.\n(*apply age1_juicy_mem_wf.*)\napply unage_juicy_mem.\napply level1_juicy_mem.\napply level2_juicy_mem.\nQed.\n\nInstance juicy_mem_ageable: ageable juicy_mem :=\n  mkAgeable _ (fun j => level (m_phi j)) age1_juicy_mem juicy_mem_ageable_facts.\n\nLemma level_juice_level_phi: forall (j: juicy_mem), level j = level (m_phi j).\nProof. intuition. Qed.\n\nLemma juicy_mem_ext: forall j1 j2,\n       m_dry j1 = m_dry j2  ->\n       m_phi j1 = m_phi j2 ->\n       j1=j2.\nProof.\nintros.\ndestruct j1; destruct j2; simpl in *.\nsubst.\nf_equal; apply proof_irr.\nQed.\n\nLemma unage_writable: forall (phi phi': rmap) loc,\n  age phi phi' -> writable loc phi' -> writable loc phi.\nProof.\nintros.\nsimpl in *.\napply age1_resource_at with (loc := loc) (r := phi @ loc) in H.\ndestruct (phi' @ loc); try contradiction.\nunfold writable.\ndestruct (phi @ loc); try discriminate.\ninv H. auto.\ndestruct (phi' @ loc); inv H0.\nrewrite resource_at_approx. auto.\nQed.\n\nLemma unage_readable: forall (phi phi': rmap) loc,\n  age phi phi' -> readable loc phi' -> readable loc phi.\nProof.\nintros.\nsimpl in *.\napply age1_resource_at with (loc := loc) (r := phi @ loc) in H.\n 2: symmetry; apply resource_at_approx.\ndestruct (phi' @ loc); try inv H0.\ndestruct (phi @ loc); try inv H.\nauto.\nQed.\n\nLemma readable_inv: forall phi loc, readable loc phi ->\n  exists rsh, exists sh, exists v, exists pp, phi @ loc = YES rsh sh (VAL v) pp.\nProof.\nsimpl.\nintros phi loc H.\ndestruct (phi @ loc); try solve [inversion H].\ndestruct k; try inv H.\neauto.\nQed.\n\n(* resource coherence *)\n\n(* FIXME: put somewhere else. *)\nDefinition fmap_option {A B} (v: option A) (m: B) (f: A -> B): B :=\n  match v with\n    | None => m\n    | Some v' => f v'\n  end.\n\nLemma resource_at_make_rmap: forall f V lev H, resource_at (proj1_sig (make_rmap f V lev H)) = f.\nrefine (fun f V lev H => match proj2_sig (make_rmap f V lev H) with\n                           | conj _ RESOURCE_AT => RESOURCE_AT\n                         end).\nQed.\n\nLemma resource_at_remake_rmap: forall f V lev H, resource_at (proj1_sig (remake_rmap f V lev H)) = f.\nrefine (fun f V lev H => match proj2_sig (remake_rmap f V lev H) with\n                           | conj _ RESOURCE_AT => RESOURCE_AT\n                         end).\nQed.\n\nLemma level_make_rmap: forall f V lev H, @level rmap _ (proj1_sig (make_rmap f V lev H)) = lev.\nrefine (fun f V lev H => match proj2_sig (make_rmap f V lev H) with\n                           | conj LEVEL _ => LEVEL\n                         end).\nQed.\n\nLemma level_remake_rmap: forall f V lev H, @level rmap _ (proj1_sig (remake_rmap f V lev H)) = lev.\nrefine (fun f V lev H => match proj2_sig (remake_rmap f V lev H) with\n                           | conj LEVEL _ => LEVEL\n                         end).\nQed.\n\n(* Here we build the [rmap]s that correspond to [store]s, [alloc]s and [free]s on the dry memory. *)\nSection inflate.\nVariables (m: mem) (phi: rmap).\n\nLemma phi_valid: valid (resource_at phi).\nProof. unfold valid; apply rmap_valid. Qed.\n\nDefinition inflate_initial_mem' (w: rmap) (loc: address) :=\n   match access_at m loc Cur with\n           | Some Freeable => YES Share.top readable_share_top (VAL (contents_at m loc)) NoneP\n           | Some Writable => YES Ews (writable_readable writable_Ews) (VAL (contents_at m loc)) NoneP\n           | Some Readable => YES Ers readable_Ers (VAL (contents_at m loc)) NoneP\n           | Some Nonempty => \n                         match w @ loc with PURE _ _ => w @ loc | _ => NO _ nonreadable_extern_retainer end\n           | None =>  NO Share.bot bot_unreadable\n         end.\n\nLemma inflate_initial_mem'_fmap:\n forall w, resource_fmap (approx (level w)) (approx (level w)) oo inflate_initial_mem' w =\n                inflate_initial_mem' w.\nProof.\nunfold valid, CompCert_AV.valid, compose.\nintros.\nunfold inflate_initial_mem'.\nextensionality loc.\ndestruct (access_at m loc); try destruct p;\n  try solve [unfold resource_fmap; f_equal; try apply preds_fmap_NoneP].\nrewrite <- level_core.\n  case_eq (w @ loc);intros; try reflexivity.\n  rewrite <- H. rewrite level_core. apply resource_at_approx.\nQed.\n\nLemma inflate_initial_mem'_valid:\n  forall lev, CompCert_AV.valid (res_option oo inflate_initial_mem' lev).\nProof.\nunfold valid, CompCert_AV.valid, compose, inflate_initial_mem'.\nintros lev b ofs.\ndestruct (access_at m (b, ofs)); try destruct p; simpl; auto.\n case_eq (lev @ (b,ofs)); intros; simpl; auto.\nQed.\n\nDefinition inflate_initial_mem (w: rmap): rmap :=\n    proj1_sig (make_rmap (inflate_initial_mem' w) (inflate_initial_mem'_valid w) _\n            (inflate_initial_mem'_fmap w)).\n\nLemma inflate_initial_mem_level: forall w, level (inflate_initial_mem w) = level w.\nProof.\nintros; unfold inflate_initial_mem, inflate_initial_mem'.\nrewrite level_make_rmap; auto.\nQed.\n\nDefinition all_VALs (phi: rmap) :=\n  forall l, match phi @ l with\n              | YES _ _ k _ => isVAL k\n              | _ => True\n            end.\n\nLemma inflate_initial_mem_all_VALs: forall lev, all_VALs (inflate_initial_mem lev).\nProof.\nunfold inflate_initial_mem, inflate_initial_mem', all_VALs.\nintros; rewrite resource_at_make_rmap.\ndestruct (access_at m l); try destruct p; auto.\n case (lev @ l); simpl; intros; auto.\nQed.\n\n(* FIXME\n   Build an rmap that's identical to phi except where m has allocated. *)\nDefinition inflate_alloc: rmap.\n refine (proj1_sig (remake_rmap (fun loc =>\n   fmap_option (res_option (phi @ loc))\n\n  (* phi = NO *)\n  (fmap_option (access_at m loc Cur)\n    (NO Share.bot bot_unreadable)\n    (fun p => \n      match p with\n        | Freeable => YES Share.top readable_share_top (VAL (contents_at m loc)) NoneP\n        | _ => NO Share.Lsh Lsh_nonreadable\n      end))\n\n  (* phi = YES *)\n  (fun _ => phi @ loc)) _ (level phi) _)).\nProof.\nassert (VALID: valid (resource_at phi)) by (apply phi_valid).\nunfold valid, CompCert_AV.valid in *.\nunfold compose in *.\nintros b ofs.\nspecialize VALID with b ofs.\nunfold fmap_option.\ndestruct (phi @ (b, ofs)); simpl in *; auto.\ndestruct (access_at m (b, ofs)); simpl in *; auto.\ndestruct p; simpl in *; auto.\ndestruct k; simpl in *; auto.\nintros i H.\nspecialize (VALID i H).\ndestruct (phi @ (b, ofs + i)); simpl in *; auto; try discriminate.\ndestruct VALID as [n [H H0]].\nexists n.\nsplit; auto.\ndestruct (phi @ (b, ofs - z)); simpl in *; auto; try discriminate.\n\n(* NO *)\ndestruct (access_at m (b, ofs)); simpl; auto. destruct p0; simpl; auto.\n\n(* YES *)\nintro.\ncase_eq (phi @ l); simpl; intros; auto.\ncase_eq (access_at m l Cur); simpl; intros; auto.\nright; destruct p; simpl; auto.\nleft; exists phi; split; auto.\nright; destruct  (access_at m l Cur); simpl; auto.\ndestruct p0; simpl; auto.\nDefined.\n\nLemma approx_map_idem: forall n (lp: preds),\n  preds_fmap (approx n) (approx n) (preds_fmap (approx n) (approx n) lp) =\n  preds_fmap (approx n) (approx n) lp.\nProof.\nintros n ls.\nchange (preds_fmap (approx n) (approx n) (preds_fmap (approx n) (approx n) ls))\nwith (((preds_fmap (approx n) (approx n)) oo (preds_fmap (approx n) (approx n))) ls).\nrewrite preds_fmap_comp.\nrewrite (approx_oo_approx n).\nauto.\nQed.\n\n(* Build an [rmap] that's identical to [phi] except where [m] has stored. *)\nDefinition inflate_store: rmap. refine (\nproj1_sig (make_rmap (fun loc =>\n  match phi @ loc with\n    | YES sh rsh (VAL _) _ => YES sh rsh (VAL (contents_at m loc)) NoneP\n    | YES _ _ _ _ => resource_fmap (approx (level phi)) (approx (level phi)) (phi @ loc)\n    | _ => phi @ loc\n  end) _ (level phi) _)).\nProof.\nassert (VALID: valid (resource_at phi)) by (apply phi_valid).\nunfold valid, CompCert_AV.valid in *.\nunfold compose in *.\nintros b ofs.\nspecialize VALID with b ofs.\nremember (phi @ (b, ofs)) as HPHI.\ndestruct HPHI; simpl; auto.\ndestruct k; simpl in *; auto.\nintros i H1.\nspecialize VALID with i.\ndestruct (phi @ (b, ofs + i)); auto.\ndestruct k; simpl; auto.\nsimpl in VALID.\nassert (H2 := VALID H1).\ninv H2.\ndestruct VALID as [n [H1 H0]].\nexists n.\nsplit; auto.\ndestruct (phi @ (b, ofs - z)); simpl in *; auto.\ninversion H0; subst; auto.\n\nunfold compose.\nextensionality l.\ndestruct l as (b, ofs).\nremember (phi @ (b, ofs)) as HPHI.\ndestruct HPHI; auto.\n(* YES *)\ndestruct k; try solve\n  [ unfold resource_fmap; rewrite preds_fmap_NoneP; auto\n  | unfold resource_fmap; rewrite approx_map_idem; auto ].\nrewrite HeqHPHI.\napply resource_at_approx.\nDefined.\n\nEnd inflate.\n\nLemma adr_inv0: forall (b b': block) (ofs ofs': Z) (sz: Z),\n  ~ adr_range (b, ofs) sz (b', ofs') ->\n  b <> b' \\/ ~ ofs <= ofs' < ofs + sz.\nProof.\nintros until sz.\nintro H.\ndestruct (peq b b').\nright; intro Contra.\napply H.\nunfold adr_range.\nauto.\nleft; intro Contra.\napply n; auto.\nQed.\n\nLemma adr_inv: forall (b b': block) (ofs ofs': Z) ch,\n  ~ adr_range (b, ofs) (size_chunk ch) (b', ofs') ->\n  b <> b' \\/ ~ ofs <= ofs' < ofs + size_chunk ch.\nProof. intros until ch; intros H1; eapply adr_inv0; eauto. Qed.\n\nLemma range_inv0: forall ofs ofs' sz,\n  ~ ofs <= ofs' < ofs + sz ->\n  ofs' < ofs \\/ ofs' >= ofs + sz.\nProof.\nintros until sz; intro H.\ndestruct (zle ofs ofs'); destruct (zlt ofs' (ofs + sz)); omega.\nQed.\n\nLemma range_inv: forall ofs ofs' ch,\n  ~ ofs <= ofs' < ofs + size_chunk ch ->\n  ofs' < ofs \\/ ofs' >= ofs + size_chunk ch.\nProof. intros; eapply range_inv0; eauto. Qed.\n\nLemma perm_of_sh_Freeable_top: forall sh, perm_of_sh sh = Some Freeable -> \n     sh = Share.top.\nProof.\nintros sh H.\nunfold perm_of_sh in H.\nrepeat if_tac in H; solve [inversion H | auto].\nQed.\n\nLemma nextblock_access_empty: forall m b ofs k, (b >= nextblock m)%positive\n  -> access_at m (b, ofs) k = None.\nProof.\nintros.\nunfold access_at. simpl.\napply (nextblock_noaccess m b ofs k).\nauto.\nQed.\n\nSection initial_mem.\nVariables (m: mem) (w: rmap).\n\nDefinition initial_rmap_ok := \n   forall loc, ((fst loc >= nextblock m)%positive -> core w @ loc = NO Share.bot bot_unreadable) /\\\n                   (match w @ loc with \n                    | PURE _ _ => (fst loc < nextblock m)%positive /\\ \n                                           access_at m loc Cur = Some Nonempty /\\  \n                                            max_access_at m loc = Some Nonempty \n                    | _ => True end).\nHypothesis IOK: initial_rmap_ok.\nEnd initial_mem.\n\nDefinition empty_retainer (loc: address) := Share.bot.\n\nLemma perm_of_freeable: perm_of_sh Share.top = Some Freeable.\nProof.\nunfold perm_of_sh.\nrewrite if_true. rewrite if_true; auto.\nauto.\nQed.\n\nLemma perm_of_writable: \n   forall sh, writable_share sh -> sh <> Share.top -> perm_of_sh sh = Some Writable.\nProof.\nintros.\nunfold perm_of_sh.\nrewrite if_true by auto. rewrite if_false; auto.\nQed.\n\nLemma perm_of_readable:\n  forall sh (rsh: readable_share sh), ~writable_share sh -> perm_of_sh sh = Some Readable.\nProof.\nintros. unfold perm_of_sh. rewrite if_false by auto. rewrite if_true; auto.\nQed.\n\nLemma perm_of_nonempty:\n  forall sh, sh <> Share.bot -> ~readable_share sh -> perm_of_sh sh = Some Nonempty.\nProof.\nintros. unfold perm_of_sh.\nrewrite if_false by auto.\nrewrite if_false by auto.\nrewrite if_false by auto; auto.\nQed.\n\nLemma perm_of_empty:\n    perm_of_sh Share.bot = None.\nProof.\nintros. unfold perm_of_sh.\nrewrite if_false. rewrite if_false.\nrewrite if_true; auto.\napply bot_unreadable.\nintro.\napply writable_readable_share in H.\napply bot_unreadable in H; auto.\nQed.\n\nLemma perm_of_Ews: perm_of_sh Ews = Some Writable.\nProof.\nunfold perm_of_sh, Ews, extern_retainer.\nrewrite if_true.\n*\nrewrite if_false; auto.\nintro.\nrewrite Share.lub_commute in H.\npose proof lub_Lsh_Rsh. rewrite Share.lub_commute in H0.\nrewrite <- H in H0.\napply Share.distrib_spec in H0.\ndestruct (Share.split Share.Lsh) eqn:?H; simpl in *.\npose proof (nonemp_split_neq1 Share.Lsh t t0).\nspec H2. intro.\napply identity_share_bot in H3. contradiction Lsh_bot_neq.\nsubst t.\napply H2; auto.\nclear.\nrewrite glb_Rsh_Lsh.\nrewrite Share.glb_commute.\nsymmetry.\napply Share.ord_antisym.\nrewrite <- glb_Lsh_Rsh.\napply glb_less_both.\ndestruct (Share.split Share.Lsh) eqn:H.\nsimpl.\napply Share.split_together in H.\nrewrite <- H.\napply Share.lub_upper1.\napply Share.ord_refl.\napply Share.bot_correct.\n*\nunfold writable_share.\napply leq_join_sub.\napply Share.lub_upper2.\nQed.\n\nLemma perm_of_Ers: perm_of_sh Ers = Some Readable.\nProof.\nunfold perm_of_sh, Ers, extern_retainer.\nrewrite if_false.\n*\nrewrite if_true; auto.\napply readable_share_lub.\nunfold readable_share.\nrewrite glb_split_x.\nintro.\napply identity_share_bot in H.\ndestruct (Share.split Share.Rsh) eqn:H0.\napply Share.split_nontrivial in H0.\nunfold Share.Rsh in H0.\ndestruct (Share.split Share.top) eqn:H1.\nsimpl in *. subst.\napply Share.split_nontrivial in H1.\napply Share.nontrivial; auto.\nauto.\nsimpl in H; auto.\n*\nunfold writable_share.\nintro.\napply leq_join_sub in H.\napply Share.ord_spec2 in H.\napply (f_equal (Share.glb Share.Rsh)) in H.\nrewrite Share.distrib1 in H.\nrewrite Share.glb_idem in H.\nrewrite Share.lub_absorb in H.\nrewrite Share.distrib1 in H.\nrewrite (@sub_glb_bot Share.Rsh (fst (Share.split Share.Lsh)) Share.Lsh)\n in H.\nrewrite Share.lub_commute, Share.lub_bot in H.\nrewrite glb_split_x in H.\ndestruct (Share.split Share.Rsh) eqn:H0.\napply nonemp_split_neq1 in H0.\nsimpl in *; subst. congruence.\napply nonidentity_Rsh.\nclear.\nexists (snd (Share.split Share.Lsh)).\ndestruct (Share.split Share.Lsh) eqn:H.\nsimpl.\nsplit.\neapply Share.split_disjoint; eauto.\neapply Share.split_together; eauto.\napply glb_Rsh_Lsh.\nQed.\n\nLemma extern_retainer_neq_bot: extern_retainer <> Share.bot.\nProof.\nunfold extern_retainer.\nintro.\ndestruct (Share.split Share.Lsh) eqn:H0.\nsimpl in *. subst.\npose proof (Share.split_together _ _ _ H0).\nrewrite Share.lub_commute, Share.lub_bot in H.\nsubst.\napply nonemp_split_neq2 in H0.\ncontradiction H0; auto.\nclear.\nunfold Share.Lsh.\nintro.\napply identity_share_bot in H.\ndestruct (Share.split Share.top) eqn:H0.\nsimpl in *; subst.\napply split_nontrivial' in H0.\napply identity_share_bot in H0.\napply Share.nontrivial; auto.\nleft.\napply bot_identity.\nQed.\n\nLemma perm_order''_trans: forall a b c, Mem.perm_order'' a b ->  Mem.perm_order'' b c ->\n                               Mem.perm_order'' a c.\nProof.\n   intros a b c H1 H2; destruct a, b, c; inversion H1; inversion H2; subst; eauto;\n             eapply perm_order_trans; eauto.\nQed.\n\nDefinition initial_mem (m: mem) lev (IOK: initial_rmap_ok m lev) : juicy_mem.\n refine (mkJuicyMem m  (inflate_initial_mem m lev) _ _ _ _);\n  unfold inflate_initial_mem, inflate_initial_mem';\n  hnf; intros;  try rewrite resource_at_make_rmap in *.\n* (* contents_cohere *)\nrevert H; case_eq (access_at m loc Cur); intros.\n destruct p; inv H0; auto.\n revert H2; case_eq (lev @ loc); intros; congruence.\n destruct (max_access_at m loc); try destruct p; try congruence.\n* (* access_cohere *)\n symmetry.\n destruct (access_at m loc) eqn:?; try destruct p; auto; simpl.\n apply perm_of_freeable.\n apply perm_of_Ews.\n apply perm_of_Ers.\n destruct (IOK loc).\n destruct (lev @ loc).\n simpl; rewrite if_false by apply extern_retainer_neq_bot; auto.\n simpl; rewrite if_false by apply extern_retainer_neq_bot; auto.\n reflexivity.\n rewrite if_true; auto.\n* (* max_access_cohere *)\n  { generalize (perm_cur_max m (fst loc) (snd loc)); unfold perm; intros.\n    case_eq (access_at m loc Cur); try destruct p; intros.\n    - unfold perm_order'', perm_order', max_access_at in *.\n    simpl; rewrite perm_of_freeable.\n    apply H.\n    unfold access_at in H0. rewrite H0. constructor.\n    - simpl. rewrite perm_of_Ews.\n    unfold perm_order'', perm_order', max_access_at, access_at in *.\n    rewrite H0 in *.\n    specialize (H Writable). spec H. constructor.\n    apply H.\n     - simpl. rewrite perm_of_Ers.\n    unfold perm_order'', perm_order', max_access_at, access_at in *.\n    rewrite H0 in *.\n    apply H. constructor.\n    - destruct (IOK loc).\n    eapply perm_order''_trans; [apply (access_max m (fst loc) (snd loc))|].\n    unfold access_at in H0; rewrite H0.\n    destruct (lev @ loc) ; simpl;\n    try destruct (@eq_dec Share.t Share.EqDec_share extern_retainer Share.bot); try constructor.\n    - simpl. destruct (eq_dec Share.bot Share.bot) as [e|n]; [| exfalso; apply n; reflexivity].\n      rewrite <- H0.\n      apply (access_max m).\n  }\n* (* alloc_cohere *)\nunfold access_at.\nunfold block; rewrite (nextblock_noaccess m (fst loc) (snd loc) Cur); auto.\nDefined.\n\nDefinition juicy_mem_level (j: juicy_mem) (lev: nat) :=\n  level (m_phi j) = lev.\n\nLemma initial_mem_level: forall lev m j IOK,\n  j = initial_mem m lev IOK -> juicy_mem_level j (level lev).\nProof.\nintros.\ndestruct j; simpl.\nunfold initial_mem in H.\ninversion H; subst.\nunfold juicy_mem_level. simpl.\nerewrite inflate_initial_mem_level; eauto.\nQed.\n\nLemma initial_mem_all_VALs: forall lev m j IOK, j = initial_mem m lev IOK\n  -> all_VALs (m_phi j).\nProof.\nintros until 1; intros (b, ofs).\ndestruct j; unfold initial_mem in H; inversion H; subst.\nsimpl.\nunfold inflate_initial_mem, inflate_initial_mem'; rewrite resource_at_make_rmap.\ndestruct (access_at m (b, ofs)); try destruct p; auto.\ncase_eq (lev @ (b,ofs)); intros; auto.\nQed.\n\nLemma perm_mem_access: forall m b ofs p,\n  perm m b ofs Cur p ->\n  exists p', (perm_order p' p /\\ access_at m (b, ofs) Cur = Some p').\nProof.\nintros.\nrewrite perm_access in H. red in H.\ndestruct (access_at m (b, ofs) Cur); try contradiction; eauto.\nQed.\n\nSection store.\nVariables (jm: juicy_mem) (m': mem)\n          (ch: memory_chunk) (b: block) (ofs: Z) (v: val)\n          (STORE: store ch (m_dry jm) b ofs v = Some m').\n\nLemma store_phi_elsewhere_eq: forall rsh sh mv loc',\n  ~ adr_range (b, ofs) (size_chunk ch) loc'\n  -> (m_phi jm) @ loc' = YES rsh sh (VAL mv) NoneP -> contents_at m' loc' = mv.\nProof.\ndestruct jm. simpl in *. clear jm.\nintros.\nunfold contents_at.\nrewrite store_mem_contents with\n  (chunk := ch) (m1 := m) (b := b) (ofs := ofs) (v := v); auto.\ndestruct loc' as [b' ofs']. simpl.\ndestruct (peq b' b).\n(* b' = b *)\ndestruct (adr_inv b b' ofs ofs' ch H).\nsymmetry in e.\ncontradiction.\n(* b' = b /\\ ~ ofs <= ofs' < ofs + size_chunk ch *)\nsubst.\nrewrite PMap.gss.\nrewrite setN_outside.\ndestruct (JMcontents _ _ _ _ _ H0) as [H5 _].\napply H5.\ndestruct (range_inv _ _ _ H1) as [H1'|H1'].\nleft; auto.\nright.\nrewrite encode_val_length.\nrewrite <- size_chunk_conv.\nauto.\n\n(* b' <> b *)\nrewrite PMap.gso; auto.\ndestruct (JMcontents _ _ _ _ _ H0) as [H1 _].\napply H1.\nQed.\n\nDefinition store_juicy_mem: juicy_mem.\n refine (mkJuicyMem m' (inflate_store m' (m_phi jm)) _ _ _ _).\n(* contents_cohere *)\nintros rsh sh' v' loc' pp H2.\nunfold inflate_store in H2; rewrite resource_at_make_rmap in H2.\ndestruct (m_phi jm @ loc'); try destruct k; try solve [inversion H2].\ninversion H2; auto.\n(* access_cohere *)\nintro loc; generalize (juicy_mem_access jm loc); intro H0.\nunfold inflate_store; rewrite resource_at_make_rmap.\nrewrite <- (Memory.store_access _ _ _ _ _ _ STORE).\ndestruct (m_phi jm @ loc); try destruct k; auto.\n(* max_access_cohere *)\nintro loc; generalize (juicy_mem_max_access jm loc); intro H1.\nunfold inflate_store; rewrite resource_at_make_rmap.\nunfold max_access_at in *.\nrewrite <- (Memory.store_access _ _ _ _ _ _ STORE).\napply nextblock_store in STORE.\ndestruct (m_phi jm @ loc); auto.\ndestruct k; simpl; try assumption.\n(* alloc_cohere *)\nhnf; intros.\nunfold inflate_store. rewrite resource_at_make_rmap.\ngeneralize (juicy_mem_alloc_cohere jm loc); intro.\nrewrite (nextblock_store _ _ _ _ _ _ STORE) in H.\nrewrite (H0 H). auto.\nDefined.\n\nEnd store.\n\nSection storebytes.\nVariables (jm: juicy_mem) (m': mem) (b: block) (ofs: Z) (bytes: list memval)\n  (STOREBYTES: storebytes (m_dry jm) b ofs bytes = Some m').\n\nLemma storebytes_phi_elsewhere_eq: forall rsh sh mv loc',\n  ~ adr_range (b, ofs) (Zlength bytes) loc' ->\n  (m_phi jm) @ loc' = YES rsh sh (VAL mv) NoneP ->\n  contents_at m' loc' = mv.\nProof.\ndestruct jm. simpl in *. clear jm.\nintros.\nunfold contents_at.\nrewrite storebytes_mem_contents with\n  (m1 := m) (b := b) (ofs := ofs) (bytes := bytes); auto.\ndestruct loc' as [b' ofs']. simpl.\ndestruct (peq b' b).\n(* b' = b *)\ndestruct (adr_inv0 b b' ofs ofs' (Zlength bytes) H).\nsymmetry in e.\ncontradiction.\n(* b' = b /\\ ~ ofs <= ofs' < ofs + size_chunk ch *)\nsubst.\nrewrite PMap.gss.\nrewrite setN_outside.\ndestruct (JMcontents _ _ _ _ _ H0) as [H5 _].\napply H5.\ndestruct (range_inv0 _ _ _ H1) as [H1'|H1'].\nleft; auto.\nright.\nrewrite <-Zlength_correct; auto.\n(* b' <> b *)\nrewrite PMap.gso; auto.\ndestruct (JMcontents _ _ _ _ _ H0) as [H1 _].\napply H1.\nQed.\n\nDefinition storebytes_juicy_mem: juicy_mem.\n refine (mkJuicyMem m' (inflate_store m' (m_phi jm)) _ _ _ _).\n(* contents_cohere *)\nintros rsh sh' v' loc' pp H2.\nunfold inflate_store in H2; rewrite resource_at_make_rmap in H2.\ndestruct (m_phi jm @ loc'); try destruct k; try solve [inversion H2].\ninversion H2; auto.\n(* access_cohere *)\nintro loc; generalize (juicy_mem_access jm loc); intro H0.\nunfold inflate_store; rewrite resource_at_make_rmap.\nrewrite <- (Memory.storebytes_access _ _ _ _ _ STOREBYTES).\ndestruct (m_phi jm @ loc); try destruct k; auto.\n(* max_access_cohere *)\nintro loc; generalize (juicy_mem_max_access jm loc); intro H1.\nunfold inflate_store; rewrite resource_at_make_rmap.\nunfold max_access_at in *.\nrewrite <- (Memory.storebytes_access _ _ _ _ _ STOREBYTES).\nassert (H88:=nextblock_storebytes _ _ _ _ _ STOREBYTES).\ndestruct (m_phi jm @ loc); try rewrite H88; auto.\ndestruct k; simpl; try rewrite H88; auto.\n(* alloc_cohere *)\nhnf; intros.\nunfold inflate_store. rewrite resource_at_make_rmap.\ngeneralize (juicy_mem_alloc_cohere jm loc); intro.\nrewrite (nextblock_storebytes _ _ _ _ _ STOREBYTES) in H.\nrewrite (H0 H).\nauto.\nDefined.\n\nEnd storebytes.\n\nLemma free_smaller_None : forall m b b' ofs lo hi m',\n  access_at m (b, ofs) Cur = None\n  -> free m b' lo hi = Some m'\n  -> access_at m' (b, ofs) Cur = None.\nProof.\nintros.\ndestruct (adr_range_dec (b',lo) (hi-lo) (b,ofs)).\ndestruct a; simpl in *.\nsubst b'; apply free_access with (ofs:=ofs) in H0; [ | omega].\ndestruct H0.\npose proof (Memory.access_cur_max m' (b,ofs)).\nrewrite H1 in H3; simpl in H3.\ndestruct (access_at m' (b, ofs) Cur); auto; contradiction.\nrewrite <- H. symmetry.\neapply free_access_other; eauto.\ndestruct (eq_block b b'); auto; right.\nsimpl in n.\nassert (~(lo <= ofs < lo + (hi - lo))) by intuition.\nomega.\nQed.\n\nLemma free_nadr_range_eq : forall m b b' ofs' lo hi m',\n  ~ adr_range (b, lo) (hi - lo) (b', ofs')\n  -> free m b lo hi = Some m'\n  -> access_at m (b', ofs') = access_at m' (b', ofs')\n  /\\  contents_at m (b', ofs') = contents_at m' (b', ofs').\nProof.\nintros.\nsplit.\nextensionality k.\napply (free_access_other _ _ _ _ _ H0 b' ofs' k).\ndestruct (eq_block b b'); auto; right.\nsimpl in H.\nassert (~(lo <= ofs' < lo + (hi - lo))) by intuition.\nomega.\nunfold contents_at.\nsimpl.\nTransparent free.\nunfold free in H0.\nOpaque free.\nif_tac in H0; inv H0.\nunfold unchecked_free.\nsimpl.\nreflexivity.\nQed.\n\nSection free.\nVariables (jm :juicy_mem) (m': mem)\n          (b: block) (lo hi: Z)\n          (FREE: free (m_dry jm) b lo hi = Some m')\n          (PERM: forall ofs, lo <= ofs < hi ->\n                      perm_of_res (m_phi jm @ (b,ofs)) = Some Freeable).\n\nDefinition inflate_free: rmap. refine (\nproj1_sig (make_rmap (fun loc =>\n  if adr_range_dec (b,lo) (hi-lo) loc then NO Share.bot bot_unreadable else m_phi jm @ loc)\n     _ (level (m_phi jm)) _)).\nProof.\n* (* AV.valid *)\nassert (VALID: valid (resource_at (m_phi jm))) by (apply phi_valid).\nintros b' ofs'.\nspecialize (VALID b' ofs').\nunfold compose in *; simpl in *.\nif_tac; [simpl; now auto | ].\ndestruct (m_phi jm @ (b', ofs')) eqn:?; try destruct k; simpl in *; auto.\n +\n intros. specialize (VALID _ H0).\n if_tac; [ | now auto].\n destruct H1; subst b'.\n specialize (PERM (ofs'+i)).  spec PERM; [omega | ].\n destruct (m_phi jm @ (b, ofs' + i)); inv  VALID. inv PERM.\n +\n destruct VALID as [n [? ?]]; exists n; split; auto.\n if_tac; auto.\n destruct H2; subst b'.\n specialize (PERM (ofs'-z)).  spec PERM; [omega | ].\n destruct (m_phi jm @ (b, ofs' -z)); inv  H1. inv PERM.\n*\nunfold compose.\nextensionality l.\ndestruct l as (b', ofs').\nif_tac; try reflexivity.\napply resource_at_approx.\nDefined.\n\n\nDefinition free_juicy_mem: juicy_mem.\n generalize (juicy_mem_contents jm); intro.\n generalize (juicy_mem_access jm); intro.\n generalize (juicy_mem_max_access jm); intro.\n refine (mkJuicyMem m' inflate_free _ _ _ _).\n* (* contents_cohere *)\nunfold contents_cohere in *.\nintros rsh' sh' v' [b' ofs'] pp H2.\nunfold access_cohere in H0.\nspecialize (H0 (b', ofs')).\nunfold inflate_free in H2; rewrite resource_at_make_rmap in H2.\nif_tac in H2; [inv H2 | ]. rename H3 into H8.\nremember (m_phi jm @ (b', ofs')) as HPHI.\ndestruct HPHI; try destruct k; inv H2.\nassert (H3: contents_at (m_dry jm) (b', ofs') = v') by (eapply H; eauto).\nassert (H4: m' = unchecked_free (m_dry jm) b lo hi) by (apply free_result; auto).\nrewrite H4.\nunfold unchecked_free, contents_at; simpl.\nsplit; auto.\nsymmetry in HeqHPHI.\ndestruct (H _ _ _ _ _ HeqHPHI); auto.\n* (* access_cohere *)\nintros [b' ofs']; spec H0 (b', ofs').\nunfold inflate_free; rewrite resource_at_make_rmap.\ndestruct (adr_range_dec (b,lo) (hi-lo) (b',ofs')).\n + (* adr_range *)\ndestruct a as [H2 H3].\nreplace (lo+(hi-lo)) with hi in H3 by omega.\nsubst b'.\nreplace (access_at m' (b, ofs') Cur) with (@None permission).\nsimpl. rewrite if_true by auto. auto.\ndestruct (free_access _ _ _ _ _ FREE ofs' H3).\npose proof (Memory.access_cur_max m' (b,ofs')). rewrite H4 in H5.\nsimpl  in H5.\ndestruct (access_at m' (b, ofs') Cur); auto; contradiction.\n+ (* ~adr_range *)\ndestruct (free_nadr_range_eq _ _ _ _ _ _ _ n FREE) as [H2 H3].\nrewrite H2 in *. clear H2 H3.\ncase_eq (m_phi jm @ (b', ofs')); intros; rewrite H2 in *; auto.\n* (* max_access_cohere *)\n{ intros [b' ofs']. specialize (H1 (b',ofs')).\n  unfold inflate_free. unfold max_access_at. rewrite resource_at_make_rmap.\n  destruct (adr_range_dec (b,lo) (hi-lo) (b',ofs')).\n  - simpl; destruct (eq_dec Share.bot Share.bot) as [e|n]; [| exfalso; apply n; reflexivity].\n    destruct (access_at m' (b', ofs') Max); constructor.\n  - clear PERM.\n    unfold max_access_at.\n    destruct (free_nadr_range_eq _ _ _ _ _ _ _ n FREE) as [H2 H3].\n    rewrite <- H2. assumption. }\n* (* alloc_cohere *)\nhnf; intros.\nunfold inflate_free. rewrite resource_at_make_rmap.\npose proof (juicy_mem_alloc_cohere jm loc).\nrewrite (nextblock_free _ _ _ _ _ FREE) in H2; auto.\nrewrite H3; auto.\nif_tac; auto.\nDefined.\n\nEnd free.\n\nLemma free_not_freeable_eq : forall m b lo hi m' b' ofs',\n  free m b lo hi = Some m'\n  -> access_at m (b', ofs') Cur <> Some Freeable\n  -> access_at m (b', ofs') Cur = access_at m' (b', ofs') Cur.\nProof.\nintros.\ndestruct (adr_range_dec (b,lo) (hi-lo) (b',ofs')).\ndestruct a.\nsubst b'.\ndestruct (free_access _ _ _ _ _ H ofs'); [omega |].\ncontradiction.\napply (free_access_other _ _ _ _ _ H).\ndestruct (eq_block b' b); auto; right.\nsubst b'.\nsimpl in n. assert (~( lo <= ofs' < lo + (hi - lo))) by intuition; omega.\nQed.\n\n(* The empty juicy memory *)\n\nDefinition after_alloc' \n  (lo hi: Z) (b: block) (phi: rmap)(H: forall ofs, phi @ (b,ofs) = NO Share.bot bot_unreadable)\n  : address -> resource := fun loc =>\n    if adr_range_dec (b,lo) (hi-lo) loc \n      then YES Share.top readable_share_top (VAL Undef) NoneP\n      else phi @ loc.\n\nLemma adr_range_eq_block : forall b ofs n b' ofs',\n  adr_range (b,ofs) n (b',ofs') ->\n  b=b'.\nProof.\nunfold adr_range; intros.\ndestruct H; auto.\nQed.\n\nLemma after_alloc'_valid : forall lo hi b phi H,\n  valid (after_alloc' lo hi b phi H).\nProof.\nintros; hnf; intros.\nunfold compose, after_alloc'.\nif_tac; simpl; auto.\ncase_eq (phi @ (b0, ofs)); intros; simpl; auto.\ngeneralize (rmap_valid phi). intro H4.\nunfold AV.valid, compose in H4.\nspec H4 b0 ofs.\nrewrite H1 in H4; simpl in H4.\ndestruct k; auto.\nintros.\nif_tac.\nassert (b = b0) by (eapply adr_range_eq_block; eauto).\nsubst. congruence.\nauto.\ndestruct H4 as [? [? ?]]; eexists; split; eauto.\nif_tac; eauto.\nassert (b = b0) by (eapply adr_range_eq_block; eauto).\nsubst. congruence.\nQed.\n\nLemma after_alloc'_ok : forall lo hi b phi H,\n  resource_fmap (approx (level phi)) (approx (level phi)) oo (after_alloc' lo hi b phi H)\n  = after_alloc' lo hi b phi H.\nProof.\nintros.\nunfold resource_fmap, compose, after_alloc'.\nextensionality loc.\nif_tac.\nrewrite preds_fmap_NoneP; auto.\ncase_eq (phi @ loc); intros; auto.\ngeneralize H1; intros.\napply necR_YES with (phi':=phi) in H1; eauto.\nrewrite <- H1.\nauto.\ngeneralize (resource_at_approx phi loc); rewrite H1; auto.\nQed.\n\nDefinition after_alloc\n  (lo hi: Z) (b: block) (phi: rmap)(H: forall ofs, phi @ (b,ofs) = NO Share.bot bot_unreadable) : rmap :=\n  proj1_sig (make_rmap (after_alloc' lo hi b phi H)\n    (after_alloc'_valid lo hi b phi H)\n    (level phi)\n    (after_alloc'_ok lo hi b phi H)).\n\nDefinition mod_after_alloc' (phi: rmap) (lo hi: Z) (b: block)\n  : address -> resource := fun loc =>\n    if adr_range_dec (b,lo) (hi-lo) loc \n      then YES Share.top readable_share_top (VAL Undef) NoneP\n      else core phi @ loc.\n\nLemma mod_after_alloc'_valid : forall phi lo hi b,\n  valid (mod_after_alloc' phi lo hi b).\nProof.\nintros; hnf; intros.\nunfold compose, mod_after_alloc'.\nif_tac; simpl; auto.\nrewrite <- core_resource_at.\ndestruct (phi @ (b0,ofs)).\nrewrite core_NO; simpl; auto.\nrewrite core_YES; simpl; auto.\nrewrite core_PURE; simpl; auto.\nQed.\n\nLemma mod_after_alloc'_ok : forall phi lo hi b,\n  resource_fmap (approx (level phi)) (approx (level phi)) oo (mod_after_alloc'  phi lo hi b)\n  = mod_after_alloc' phi lo hi b.\nProof.\nintros.\nunfold resource_fmap, compose, mod_after_alloc'.\nextensionality loc.\nif_tac; auto.\ncase_eq (core phi @ loc); intros; auto; f_equal;\nrewrite <- level_core;\ngeneralize (resource_at_approx (core phi) loc); rewrite H0; intro; injection H1; auto.\nQed.\n\nDefinition mod_after_alloc (phi: rmap) (lo hi: Z) (b: block) :=\n  proj1_sig (make_rmap (mod_after_alloc' phi lo hi b)\n    (mod_after_alloc'_valid phi lo hi b)\n    _\n    (mod_after_alloc'_ok phi lo hi b)).\n\nTransparent alloc.\n\nLemma adr_range_inv: forall loc loc' n,\n  ~ adr_range loc n loc' ->\n  fst loc <> fst loc' \\/ (fst loc=fst loc' /\\ ~snd loc <= snd loc' < snd loc + n).\nProof.\nintros until n.\nintro H.\ndestruct (peq (fst loc) (fst loc')).\nright; split; auto; intro Contra.\napply H.\nunfold adr_range.\ndestruct loc,loc'.\nauto.\nleft; intro Contra.\napply n0; auto.\nQed.\n\nLemma dry_noperm_juicy_nonreadable : forall m loc,\n  access_at (m_dry m) loc Cur = None ->   ~readable loc (m_phi m).\nProof.\nintros.\nrewrite (juicy_mem_access m loc) in H.\nintro. hnf in H0.\ndestruct (m_phi m @loc); simpl in *; auto.\ndestruct k as [x | | |]; try inv H.\nunfold perm_of_sh in H2.\nif_tac in H2. if_tac in H2; inv H2.\nrewrite if_true in H2 by auto.\ninv H2.\nQed.\n\nLemma fullempty_after_alloc : forall m1 m2 lo n b ofs,\n  alloc m1 lo n = (m2, b) ->\n  access_at m2 (b, ofs) Cur = None \\/ access_at m2 (b, ofs) Cur = Some Freeable.\nProof.\nintros.\npose proof (alloc_access_same _ _ _ _ _ H ofs Cur).\ndestruct (range_dec lo ofs n). auto.\nleft.\nrewrite <- (alloc_access_other _ _ _ _ _ H b ofs Cur) by (right; omega).\napply alloc_result in H.\nsubst.\napply nextblock_access_empty.\napply Pos.le_ge, Ple_refl.\nQed.\n\nLemma alloc_dry_unchanged_on : forall m1 m2 loc lo hi b0,\n  alloc m1 lo hi = (m2, b0) ->\n  ~adr_range (b0,lo) (hi-lo) loc ->\n  access_at m1 loc = access_at m2 loc /\\\n  (access_at m1 loc Cur <> None -> contents_at m1 loc= contents_at m2 loc).\nProof.\nintros.\ndestruct loc as [b z]; simpl.\nsplit.\nextensionality k.\neapply Memory.alloc_access_other; eauto.\nsimpl in H0.\ndestruct (eq_block b b0); auto. subst. right.\nassert (~(lo <= z < lo + (hi - lo))) by intuition; omega.\nintros.\nunfold alloc in H.\ninv H. unfold contents_at; simpl.\nunfold adr_range in H0.\ndestruct (eq_dec b (nextblock m1)).\nsubst.\nrewrite invalid_noaccess in H1; [ congruence |].\ncontradict H0.\nred in H0. apply Plt_irrefl in H0. contradiction.\nrewrite PMap.gso by auto.\nauto.\nQed.\n\nLemma adr_range_zle_fact : forall b lo hi loc,\n  adr_range (b,lo) (hi-lo) loc ->\n  zle lo (snd loc) && zlt (snd loc) hi = true.\nProof.\nunfold adr_range.\nintros.\ndestruct loc; simpl in *.\ndestruct H.\ndestruct H0.\napply andb_true_iff.\nsplit.\napply zle_true; auto.\napply zlt_true; omega.\nQed.\n\nLemma alloc_dry_updated_on : forall m1 m2 lo hi b loc,\n  alloc m1 lo hi = (m2, b) ->\n  adr_range (b, lo) (hi - lo) loc ->\n  access_at m2 loc Cur=Some Freeable /\\\n  contents_at m2 loc=Undef.\nProof.\nintros.\ndestruct loc as [b' z'].\nsplit.\ndestruct H0. subst b'.\napply (alloc_access_same _ _ _ _ _ H). omega.\nunfold contents_at; unfold alloc in H; inv H. simpl.\ndestruct H0; subst b'.\nrewrite PMap.gss. rewrite ZMap.gi; auto.\nQed.\n\nDefinition resource_decay (nextb: block) (phi1 phi2: rmap) :=\n  (level phi1 >= level phi2)%nat /\\\n forall l: address,\n  ((fst l >= nextb)%positive -> phi1 @ l = NO Share.bot bot_unreadable) /\\\n  (resource_fmap (approx (level phi2)) (approx (level phi2)) (phi1 @ l) = (phi2 @ l) \\/\n  (exists sh, exists (wsh: writable_share sh), exists v, exists v',\n       resource_fmap (approx (level phi2)) (approx (level phi2)) (phi1 @ l) = \n                       YES sh (writable_readable_share wsh) (VAL v) NoneP /\\ \n       phi2 @ l = YES sh (writable_readable_share wsh) (VAL v') NoneP)\n  \\/ ((fst l >= nextb)%positive /\\ exists v, phi2 @ l = YES Share.top readable_share_top (VAL v) NoneP)\n  \\/ (exists v, exists pp, phi1 @ l = YES Share.top readable_share_top (VAL v) pp \n                        /\\ phi2 @ l = NO Share.bot bot_unreadable)).\n\nDefinition resource_nodecay (nextb: block) (phi1 phi2: rmap) :=\n  (level phi1 >= level phi2)%nat /\\\n  forall l: address,\n  ((fst l >= nextb)%positive -> phi1 @ l = NO Share.bot bot_unreadable) /\\\n  (resource_fmap (approx (level phi2)) (approx (level phi2)) (phi1 @ l) = (phi2 @ l) \\/\n  (exists sh, exists (wsh: writable_share sh), exists v, exists v',\n       resource_fmap (approx (level phi2)) (approx (level phi2)) (phi1 @ l) = YES sh (writable_readable_share wsh) (VAL v) NoneP\n      /\\ phi2 @ l = YES sh (writable_readable_share wsh) (VAL v') NoneP)).\n\nLemma resource_nodecay_decay:\n   forall b phi1 phi2, resource_nodecay b phi1 phi2 -> resource_decay b phi1 phi2.\nProof.\n unfold resource_decay, resource_nodecay; intros; destruct H; split; intros; try omega.\nspecialize (H0 l); intuition.\nQed.\n\nLemma resource_decay_refl: forall b phi, \n  (forall l, (fst l >= b)%positive -> phi @ l = NO Share.bot bot_unreadable) ->\n  resource_decay b phi phi.\nProof.\nintros.\nsplit; auto.\nintros; split; auto.\nleft.\napply resource_at_approx.\nQed.\n\nLemma resource_decay_trans: forall b b' m1 m2 m3,\n  (b <= b')%positive ->\n  resource_decay b m1 m2 -> resource_decay b' m2 m3 -> resource_decay b m1 m3.\nProof.\n intros until m3; intro Hbb; intros.\n destruct H as [H' H]; destruct H0 as [H0' H0]; split; [omega |].\n intro l; specialize (H l); specialize (H0 l).\n destruct H,H0.\n split.  auto.\n destruct H1.\n destruct H2.\n left. rewrite <- H2.\n replace (resource_fmap (approx (level m3)) (approx (level m3)) (m1 @ l))\n    with (resource_fmap (approx (level m3)) (approx (level m3))\n              (resource_fmap (approx (level m2)) (approx (level m2)) (m1 @ l)))\n  by (rewrite resource_fmap_fmap; rewrite approx_oo_approx' by auto; rewrite approx'_oo_approx by auto; auto).\nrewrite H1. auto.\n clear - Hbb H H1 H0 H2 H' H0'.\n right.\n destruct H2 as [[sh2 [wsh2 [v2 [v2' [? ?]]]]]|[[? [v ?]] |?]]; subst.\n left; exists sh2, wsh2,v2,v2'; split; auto.\n rewrite <- H1 in H2.\n rewrite resource_fmap_fmap in H2.\n rewrite approx_oo_approx' in H2 by omega.\n rewrite approx'_oo_approx in H2 by omega.\n assumption.\n right; left. split. xomega. exists v; auto.\n right; right; auto.\n destruct H2 as [v [pp [? ?]]].\n rewrite H2 in H1. destruct (m1 @ l); inv H1.\n exists v, p. split; auto. f_equal. apply proof_irr.\n destruct H2.\n destruct H1 as [[sh [wsh [v [v' [? ?]]]]]|[[? [v ?]] |?]].\n right; left; exists sh,wsh,v,v'; split. \n rewrite <- (approx_oo_approx' (level m3) (level m2)) at 1 by auto.\n rewrite <- (approx'_oo_approx (level m3) (level m2)) at 2 by auto.\n rewrite <- resource_fmap_fmap. rewrite H1.\n unfold resource_fmap. rewrite preds_fmap_NoneP. auto.\n rewrite H3 in H2. rewrite <- H2.\n unfold resource_fmap. rewrite preds_fmap_NoneP. auto.\n right; right; left; split; auto. exists v. rewrite <- H2; rewrite <- H3.\n rewrite H3.\n unfold resource_fmap. rewrite preds_fmap_NoneP. auto.\n right; right; right.\n destruct H1 as [v [pp [? ?]]].\n rewrite H3 in H2. simpl in H2. eauto.\n destruct H1 as [[sh [wsh [v [v' [? ?]]]]]|[[? [v ?]] |?]].\n destruct H2 as [[sh2 [wsh2 [v2 [v2' [? ?]]]]]|[[? [v2 ?]] |?]].\n right; left; exists sh,wsh,v,v2'; split.\n rewrite <- (approx_oo_approx' (level m3) (level m2)) at 1 by auto.\n rewrite <- (approx'_oo_approx (level m3) (level m2)) at 2 by auto.\n rewrite <- resource_fmap_fmap. rewrite H1.\n unfold resource_fmap. rewrite preds_fmap_NoneP. auto.\n rewrite H3 in H2. rewrite H4. simpl in H2. inv H2.\n f_equal. apply proof_irr.\n right; right; left. split. xomega. exists v2; auto.\n right; right; right.\n destruct (m1 @ l); inv H1.\n destruct H2 as [vx [pp [? ?]]]. inversion2 H3 H1.\n exists v,p. split; auto. f_equal; apply proof_irr.\n destruct H2 as [[sh2 [wsh2 [v2 [v2' [? ?]]]]]|[[? [v2 ?]] |?]].\n right; right; left; split; auto. exists v2'. rewrite H3 in H2; inv H2.\n rewrite H4; f_equal; apply proof_irr.\n right; right; left; split; auto; exists v2; auto.\n left. destruct H2 as [v' [pp [? ?]]]. rewrite H4; rewrite H; auto.\n destruct H2 as [[sh2 [wsh2 [v2 [v2' [? ?]]]]]|[[? [v2 ?]] |?]].\n destruct H1 as [v' [pp [? ?]]].\n rewrite H4 in H2; inv H2.\n right; right; left; split. xomega. eauto.\n right; right; right.\n destruct H1 as [v1 [pp1 [? ?]]].\n destruct H2 as [v2 [pp2 [? ?]]].\n inversion2 H3 H2.\nQed.\n\nLemma level_store_juicy_mem:\n forall jm m ch b i v H, level (store_juicy_mem jm m ch b i v H) = level jm.\nProof.\nintros.\nunfold store_juicy_mem. simpl.\nunfold inflate_store; simpl. rewrite level_make_rmap. auto.\nQed.\n\nLemma level_storebytes_juicy_mem:\n forall jm m b i bytes H, level (storebytes_juicy_mem jm m b i bytes H) = level jm.\nProof.\nintros.\nunfold storebytes_juicy_mem. simpl.\nunfold inflate_store; simpl. rewrite level_make_rmap. auto.\nQed.\n\nLemma inflate_store_resource_nodecay:\n  forall (jm: juicy_mem) (m': mem)\n          (ch: memory_chunk) (b: block) (ofs: Z) (v: val)\n          (STORE: store ch (m_dry jm) b ofs v = Some m')\n          (PERM: forall z, ofs <= z < ofs + size_chunk ch ->\n                      perm_order'' (perm_of_res (m_phi jm @ (b,z))) (Some Writable))\n          phi',\n  inflate_store m' (m_phi jm) = phi' -> resource_nodecay (nextblock (m_dry jm)) (m_phi jm) phi'.\nProof.\nintros.\nsplit.\nsubst; unfold inflate_store; simpl. rewrite level_make_rmap. auto.\nintro l'.\nsplit.\napply juicy_mem_alloc_cohere.\ndestruct (adr_range_dec (b, ofs) (size_chunk ch) l') as [HA | HA].\n* (* adr_range *)\nright.\nunfold adr_range in HA.\ndestruct l' as (b', ofs').\ndestruct HA as [HA0 HA1].\nsubst b'.\nassert (H0: range_perm (m_dry jm) b ofs (ofs + size_chunk ch) Cur Writable).\n  cut (valid_access (m_dry jm) ch b ofs Writable).\n  intros [? ?]; auto.\n  eapply store_valid_access_3; eauto.\nassert (H1: perm (m_dry jm) b ofs' Cur Writable) by (apply H0; auto).\ngeneralize (juicy_mem_access jm (b, ofs')); intro ACCESS.\nunfold perm, perm_order' in H1.\nunfold access_at in ACCESS.\nsimpl in *.\ndestruct ((mem_access (m_dry jm)) !! b ofs' Cur) eqn:?H; try contradiction.\nspecialize (PERM ofs' HA1).\ndestruct ( m_phi jm @ (b, ofs') ) eqn:?H; try destruct k; simpl in PERM; try if_tac in PERM; try inv PERM.\ndestruct (juicy_mem_contents _ _ _ _ _ _ H3); subst.\nsimpl.\nassert (writable_share sh). {\n clear - PERM.\n unfold perm_of_sh in PERM.\n if_tac in PERM; auto. if_tac_in PERM. inv PERM.\n if_tac in PERM; inv PERM.\n}\n exists sh,H; do 2 econstructor; split; simpl; f_equal.\n apply proof_irr.\nunfold inflate_store;  rewrite resource_at_make_rmap.\nrewrite H3. f_equal; apply proof_irr.\n* (* ~ adr_range *)\nleft.\nassert (H0: level (m_phi jm) = level phi').\n  rewrite <- H; unfold inflate_store; rewrite level_make_rmap; auto.\nrewrite <- H.\nunfold inflate_store; rewrite level_make_rmap; rewrite resource_at_make_rmap.\ncase_eq l'; intros b' ofs' e'; subst.\nremember (m_phi jm @ (b', ofs')) as HPHI; destruct HPHI; try destruct k; auto;\n  try solve [rewrite HeqHPHI; rewrite resource_at_approx; auto].\nrewrite (store_phi_elsewhere_eq jm _ _ _ _ _ STORE _ r m (b', ofs')); auto.\nassert (H: p = NoneP).\n  symmetry in HeqHPHI; \n  destruct  (juicy_mem_contents jm _ _ _ _ _ HeqHPHI); auto.\nrewrite H.\nunfold resource_fmap; f_equal; try reflexivity.\nassert (H: p = NoneP).\n  symmetry in HeqHPHI;\n  destruct  (juicy_mem_contents jm _ _ _ _ _ HeqHPHI); auto.\nrewrite H in HeqHPHI; clear H.\nrewrite HeqHPHI; auto.\nQed.\n\nLemma inflate_free_resource_decay:\n forall (jm :juicy_mem) (m': mem)\n          (b: block) (lo hi: Z)\n          (FREE: free (m_dry jm) b lo hi = Some m')\n          (PERM: forall ofs : Z,\n             lo <= ofs < hi -> perm_of_res (m_phi jm @ (b, ofs)) = Some Freeable),\n   resource_decay (nextblock (m_dry jm)) (m_phi jm) (inflate_free jm b lo hi PERM).\nProof.\nintros.\nsplit.\nunfold inflate_free; rewrite level_make_rmap; auto.\nintros l.\nsplit.\napply juicy_mem_alloc_cohere.\ndestruct (adr_range_dec (b, lo) (hi-lo) l) as [HA | HA].\n* (* adr_range *)\nright. right.\ndestruct l; simpl in HA|-*.\ndestruct HA as [H0 H1]. subst b0.\nassert (lo + (hi - lo) = hi) by omega.\nrewrite H in H1. clear H.\nunfold inflate_free; simpl; rewrite resource_at_make_rmap.\nspecialize (PERM _ H1).\ndestruct (m_phi jm @ (b,z)) eqn:?; try destruct k; inv PERM.\nif_tac in H0; inv H0.\nrewrite if_true by (split; auto; omega).\nright.\nexists m, p.\nunfold perm_of_sh in H0.\nrepeat if_tac in H0; inv H0.\nsplit; try reflexivity. f_equal; apply proof_irr.\n* (* ~adr_range *)\ndestruct l.\ndestruct (free_nadr_range_eq _ _ _ _ _ _ _ HA FREE).\nleft.\nunfold inflate_free; rewrite level_make_rmap; rewrite resource_at_make_rmap.\nrewrite if_false by auto.\ngeneralize (juicy_mem_contents jm); intro Hc.\ngeneralize (juicy_mem_access jm (b0,z)); intro Ha.\nrewrite resource_at_approx.\ncase_eq (m_phi jm @ (b0, z)); intros; rewrite H1 in Ha; auto.\nQed.\n\nLemma juicy_store_nodecay:\n  forall jm m' ch b ofs v\n       (H: store ch (m_dry jm) b ofs v = Some m')\n          (PERM: forall z, ofs <= z < ofs + size_chunk ch ->\n                      perm_order'' (perm_of_res (m_phi jm @ (b,z))) (Some Writable)),\n       resource_nodecay (nextblock (m_dry jm)) (m_phi jm) (m_phi (store_juicy_mem jm _ _ _ _ _ H)).\nProof.\n intros.\n eapply inflate_store_resource_nodecay; eauto.\nQed.\n\nLemma can_age1_juicy_mem: forall j r,\n  age (m_phi j) r -> exists j', age1 j = Some j'.\nProof.\nintros j r H.\nunfold age in H.\ncase_eq (age1_juicy_mem j); intros.\ndestruct (age1_juicy_mem_unpack _ _ H0).\neexists; eauto.\napply age1_juicy_mem_None1 in H0.\nrewrite H0 in H.\nelimtype False; inversion H.\nQed.\n\n\nLemma can_age_jm:\n  forall jm, age1 (m_phi jm) <> None -> exists jm', age jm jm'.\nProof.\n intro jm; case_eq (age1 (m_phi jm)); intros; try congruence.\n apply (can_age1_juicy_mem _ _ H).\nQed.\n\n\nLemma age_jm_dry: forall {jm jm'}, age jm jm' -> m_dry jm = m_dry jm'.\nProof. intros; destruct (age1_juicy_mem_unpack _ _ H); auto.\nQed.\n\nLemma age_jm_phi: forall {jm jm'}, age jm jm' -> age (m_phi jm) (m_phi jm').\nProof. intros; destruct (age1_juicy_mem_unpack _ _ H); auto.\nQed.\n\n(** * Results about aging in juicy memory coherence properties *)\n\nLemma age1_YES'_1 {phi phi' l rsh sh k P} :\n  age1 phi = Some phi' ->\n  phi @ l = YES rsh sh k P ->\n  (exists P, phi' @ l = YES rsh sh k P).\nProof.\n  intros A E.\n  apply (proj1 (age1_YES' phi phi' l rsh sh k A)).\n  eauto.\nQed.\n\nLemma age1_YES'_2 {phi phi' l rsh sh k P} :\n  age1 phi = Some phi' ->\n  phi' @ l = YES rsh sh k P ->\n  (exists P, phi @ l = YES rsh sh k P).\nProof.\n  intros A E.\n  apply (proj2 (age1_YES' phi phi' l rsh sh k A)).\n  eauto.\nQed.\n\nLemma age1_PURE_2 {phi phi' l k P} :\n  age1 phi = Some phi' ->\n  phi' @ l = PURE k P ->\n  (exists P, phi @ l = PURE k P).\nProof.\n  intros A E.\n  apply (proj2 (age1_PURE phi phi' l k A)).\n  eauto.\nQed.\n\nLemma perm_of_res_age x y loc :\n  age x y -> perm_of_res (x @ loc) = perm_of_res (y @ loc).\nProof.\n  intros A.\n  destruct (x @ loc) as [sh | rsh sh k p | k p] eqn:E.\n  - destruct (age1_NO x y loc sh n A) as [[]_]; eauto.\n  - destruct (age1_YES' x y loc rsh sh k A) as [[p' ->] _]; eauto.\n  - destruct (age1_PURE x y loc k A) as [[p' ->] _]; eauto.\nQed.\n\nLemma contents_cohere_age m : hereditary age (contents_cohere m).\nProof.\n  intros x y E A.\n  intros rsh sh v loc pp H.\n  destruct (proj2 (age1_YES' _ _ loc rsh sh (VAL v) E)) as [pp' E'].\n  now eauto.\n  specialize (A rsh sh v loc _ E').\n  destruct A as [A ->]. split; auto.\n  apply (proj1 (age1_YES _ _ loc rsh sh (VAL v) E)) in E'.\n  congruence.\nQed.\n\nLemma access_cohere_age m : hereditary age (access_cohere m).\nProof.\n  intros x y E B.\n  intros addr.\n  destruct (age1_levelS _ _ E) as [n L].\n  rewrite (B addr).\n  apply perm_of_res_age, E.\nQed.\n\nLemma max_access_cohere_age m : hereditary age (max_access_cohere m).\nProof.\n  intros x y E C.\n  intros addr; specialize (C addr).\n  destruct (y @ addr) as [sh | sh p k pp | k p] eqn:AT.\n  - eapply (age1_NO x) in AT; auto.\n    rewrite AT in C; auto.\n  - destruct (age1_YES'_2 E AT) as [P Ex].\n    rewrite Ex in C.\n    auto.\n  - destruct (age1_PURE_2 E AT) as [P Ex].\n    rewrite Ex in C; auto.\nQed.\n\nLemma alloc_cohere_age m : hereditary age (alloc_cohere m).\nProof.\n  intros x y E D.\n  intros loc G; specialize (D loc G).\n  eapply (age1_NO x); eauto.\nQed.\n\n\n(** * Results in the opposite direction *)\n\nDefinition unage {A} {_:ageable A} x y := age y x.\n\nLemma unage_YES'_1 {phi phi' l rsh sh k P} :\n  age1 phi' = Some phi ->\n  phi @ l = YES rsh sh k P ->\n  (exists P, phi' @ l = YES rsh sh k P).\nProof.\n  intros A E.\n  apply (proj2 (age1_YES' phi' phi l rsh sh k A)).\n  eauto.\nQed.\n\nLemma unage_YES'_2 {phi phi' l rsh sh k P} :\n  age1 phi' = Some phi ->\n  phi' @ l = YES rsh sh k P ->\n  (exists P, phi @ l = YES rsh sh k P).\nProof.\n  intros A E.\n  apply (proj1 (age1_YES' phi' phi l rsh sh k A)).\n  eauto.\nQed.\n\nLemma unage_PURE_2 {phi phi' l k P} :\n  age1 phi' = Some phi ->\n  phi' @ l = PURE k P ->\n  (exists P, phi @ l = PURE k P).\nProof.\n  intros A E.\n  apply (proj1 (age1_PURE phi' phi l k A)).\n  eauto.\nQed.\n\nLemma contents_cohere_unage m : hereditary unage (contents_cohere m).\nProof.\n  intros x y E A.\n  intros rsh sh v loc pp H.\n  destruct (proj1 (age1_YES' _ _ loc rsh sh (VAL v) E)) as [pp' E'].\n  eauto.\n  specialize (A rsh sh v loc _ E').\n  destruct A as [A ->]. split; auto.\n  apply (proj2 (age1_YES _ _ loc rsh sh (VAL v) E)) in E'.\n  congruence.\nQed.\n\nLemma access_cohere_unage m : hereditary unage (access_cohere m).\nProof.\n  intros x y E B.\n  intros addr.\n  destruct (age1_levelS _ _ E) as [n L].\n  rewrite (B addr).\n  symmetry.\n  apply perm_of_res_age, E.\nQed.\n\nLemma max_access_cohere_unage m : hereditary unage (max_access_cohere m).\nProof.\n  intros x y E C.\n  intros addr; specialize (C addr).\n  destruct (x @ addr) as [sh | sh p k pp | k p] eqn:AT.\n  - eapply (age1_NO y) in AT; auto.\n    rewrite AT; auto.\n  - destruct (@age1_YES'_2 y x addr sh p k pp E AT) as [P ->].\n    auto.\n  - destruct (age1_PURE_2 E AT) as [P Ex].\n    rewrite Ex; auto.\nQed.\n\nLemma alloc_cohere_unage m : hereditary unage (alloc_cohere m).\nProof.\n  intros x y E D.\n  intros loc G; specialize (D loc G).\n  eapply (age1_NO y); eauto.\nQed.\n\nLemma juicy_mem_unage jm' : { jm | age jm jm' }.\nProof.\n  pose proof (rmap_unage_age (m_phi jm')) as A.\n  remember (rmap_unage (m_phi jm')) as phi.\n  unshelve eexists (mkJuicyMem (m_dry jm') phi _ _ _ _).\n  all: destruct jm' as [m phi' Co Ac Ma N]; simpl.\n  - eapply contents_cohere_unage; eauto.\n  - eapply access_cohere_unage; eauto.\n  - eapply max_access_cohere_unage; eauto.\n  - eapply alloc_cohere_unage; eauto.\n  - apply age1_juicy_mem_unpack''; auto.\nQed.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/veric/juicy_mem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.2465209528455392}}
{"text": "Require Import Recdef.\nRequire Import floyd.proofauto.\nLocal Open Scope logic.\nRequire Import List. Import ListNotations.\n\nRequire Import tweetnacl20140427.split_array_lemmas.\nRequire Import ZArith.\nRequire Import tweetnacl20140427.tweetNaclBase.\nRequire Import tweetnacl20140427.Salsa20.\nRequire Import tweetnacl20140427.tweetnaclVerifiableC.\nRequire Import tweetnacl20140427.verif_salsa_base.\n\nRequire Import tweetnacl20140427.spec_salsa. Opaque Snuffle.Snuffle. Opaque fcore_result.\n\nDefinition X_content (x: SixteenByte * SixteenByte * (SixteenByte * SixteenByte))\n                     (i:Z) (l:list val) : Prop :=\n    l = upd_upto x (Z.to_nat i) (list_repeat 16 Vundef).\n\nLemma XcontUpdate Nonce C Key1 Key2 i l\n      (I: 0 <= i < 4)\n      (L: X_content (Nonce, C, (Key1, Key2)) i l):\nX_content (Nonce, C, (Key1, Key2)) (i + 1)\n  (upd_Znth (11 + i)\n     (upd_Znth (6 + i)\n        (upd_Znth (1 + i)\n           (upd_Znth (5 * i) l\n              (Vint (littleendian (Select16Q C i))))\n           (Vint (littleendian (Select16Q Key1 i))))\n        (Vint (littleendian (Select16Q Nonce i))))\n     (Vint (littleendian (Select16Q Key2 i)))).\nProof. unfold X_content in *.\n  rewrite (Z.add_comm _ 1), Z2Nat.inj_add; try omega. simpl.\n  rewrite Z2Nat.id; try omega. subst l; reflexivity.\nQed.\n\n(*Issue : writing the lemma using the Delta := func_typcontext ...\n  @semax CompSepcs Espec Delta ...\n  leads to failure - but only 40 lines down, in the call to forward_call,\n  where check_Delta now fails since it introduces a Delta0.\n  I think we need to complement the line (\n    Delta := @abbreviate tycontext (mk_tycontext _ _ _ _ _) |- _ => ...\n  in checkDelta (checkDeltaOLD) with a second option,\n  Delta := func_tycontext ... =>.\n  Note that\n  1. rerunning abbreviate_semax at that place (before calling forward_call)\n     does not resolve the situation\n  2. In the master-branch, we actually could write the lemma using Delta :=,\n     so this is really an issue ith the new_compcert branch*)\n\nLemma f_core_loop1 (Espec : OracleKind) FR c k h nonce out w x y t\n(data : SixteenByte * SixteenByte * (SixteenByte * SixteenByte))\n(*(Delta := func_tycontext f_core SalsaVarSpecs SalsaFunSpecs) *):\n@semax CompSpecs Espec\n  (func_tycontext f_core SalsaVarSpecs SalsaFunSpecs) (*Delta*)\n  (PROP  ()\n   LOCAL  (lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n           lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; temp _in nonce;\n           temp _out out; temp _c c; temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FR; data_at_ Tsh (tarray tuint 16) x;\n         CoreInSEP data (nonce, c, k)))\n  \n  (Ssequence\n    (Sset _i (Econst_int (Int.repr 0) tint))\n    (Sloop\n      (Ssequence\n        (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                       (Econst_int (Int.repr 4) tint) tint)\n          Sskip\n          Sbreak)\n        (Ssequence\n          (Ssequence\n            (Scall (Some _t'1)\n              (Evar _ld32 (Tfunction (Tcons (tptr tuchar) Tnil) tuint\n                            cc_default))\n              ((Ebinop Oadd (Etempvar _c (tptr tuchar))\n                 (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                   (Etempvar _i tint) tint) (tptr tuchar)) :: nil))\n            (Sset _aux (Etempvar _t'1 tuint)))\n          (Ssequence\n            (Sassign\n              (Ederef\n                (Ebinop Oadd (Evar _x (tarray tuint 16))\n                  (Ebinop Omul (Econst_int (Int.repr 5) tint)\n                    (Etempvar _i tint) tint) (tptr tuint)) tuint)\n              (Etempvar _aux tuint))\n            (Ssequence\n              (Ssequence\n                (Scall (Some _t'2)\n                  (Evar _ld32 (Tfunction (Tcons (tptr tuchar) Tnil) tuint\n                                cc_default))\n                  ((Ebinop Oadd (Etempvar _k (tptr tuchar))\n                     (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                       (Etempvar _i tint) tint) (tptr tuchar)) :: nil))\n                (Sset _aux (Etempvar _t'2 tuint)))\n              (Ssequence\n                (Sassign\n                  (Ederef\n                    (Ebinop Oadd (Evar _x (tarray tuint 16))\n                      (Ebinop Oadd (Econst_int (Int.repr 1) tint)\n                        (Etempvar _i tint) tint) (tptr tuint)) tuint)\n                  (Etempvar _aux tuint))\n                (Ssequence\n                  (Ssequence\n                    (Scall (Some _t'3)\n                      (Evar _ld32 (Tfunction (Tcons (tptr tuchar) Tnil) tuint\n                                    cc_default))\n                      ((Ebinop Oadd (Etempvar _in (tptr tuchar))\n                         (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                           (Etempvar _i tint) tint) (tptr tuchar)) :: nil))\n                    (Sset _aux (Etempvar _t'3 tuint)))\n                  (Ssequence\n                    (Sassign\n                      (Ederef\n                        (Ebinop Oadd (Evar _x (tarray tuint 16))\n                          (Ebinop Oadd (Econst_int (Int.repr 6) tint)\n                            (Etempvar _i tint) tint) (tptr tuint)) tuint)\n                      (Etempvar _aux tuint))\n                    (Ssequence\n                      (Ssequence\n                        (Scall (Some _t'4)\n                          (Evar _ld32 (Tfunction (Tcons (tptr tuchar) Tnil)\n                                        tuint cc_default))\n                          ((Ebinop Oadd\n                             (Ebinop Oadd (Etempvar _k (tptr tuchar))\n                               (Econst_int (Int.repr 16) tint) (tptr tuchar))\n                             (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                               (Etempvar _i tint) tint) (tptr tuchar)) ::\n                           nil))\n                        (Sset _aux (Etempvar _t'4 tuint)))\n                      (Sassign\n                        (Ederef\n                          (Ebinop Oadd (Evar _x (tarray tuint 16))\n                            (Ebinop Oadd (Econst_int (Int.repr 11) tint)\n                              (Etempvar _i tint) tint) (tptr tuint)) tuint)\n                        (Etempvar _aux tuint))))))))))\n      (Sset _i\n        (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint))))\n  (normal_ret_assert (\nPROP  ()\n   LOCAL  (temp _i (Vint (Int.repr 4)); lvar _t (tarray tuint 4) t;\n   lvar _y (tarray tuint 16) y; lvar _x (tarray tuint 16) x;\n   lvar _w (tarray tuint 16) w; temp _in nonce; temp _out out; temp _c c;\n   temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FR;\n         EX  l : list val, !!X_content data 4 l &&\n                 data_at Tsh (tarray tuint 16) l x;\n         CoreInSEP data (nonce, c, k)))).\nProof. intros. abbreviate_semax.\nTime forward_for_simple_bound 4 (EX i:Z,\n   PROP  ()\n   LOCAL  (\n   lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n   lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; temp _in nonce;\n   temp _out out; temp _c c; temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FR;\n         EX l:_, !!(X_content data i l) && data_at Tsh (tarray tuint 16) l x;\n         CoreInSEP data (nonce, c, k))). (*0.8 versus 2.1*)\n{ Exists (list_repeat 16 Vundef). Time entailer!. (*1.3 versus 4.2*) }\n{ rename H into I.\n\n  destruct data as ((Nonce, C), Key). unfold CoreInSEP.\n  unfold SByte at 2. Intros X0; rename H into X0cont.\n\n  freeze [0;2;4] FR1.\n  freeze [0;1] FR2.\n\n  assert (C16:= SixteenByte2ValList_Zlength C).\n  remember (SplitSelect16Q C i) as FB; destruct FB as (Front, Back).\n  Time assert_PROP (isptr c /\\ field_compatible (Tarray tuchar 16 noattr) [] c) as FCc by entailer!. (*2.1 versus 3.7*)\n  destruct FCc as [Pc FC]; apply isptrD in Pc; destruct Pc as [cb [coff CP]]; rewrite CP in *.\n  destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB I) as [FL _].\n\n  rewrite (split3_data_at_Tarray_tuchar Tsh 16 (Zlength (QuadChunks2ValList Front))\n        (Zlength (QuadChunks2ValList Front) + Zlength (QuadChunks2ValList [Select16Q C i])));\n    repeat rewrite QuadChunk2ValList_ZLength;\n    try rewrite FL; try rewrite <- C1; try rewrite Zlength_cons, Zlength_nil; try solve[simpl; omega].\n  rewrite Zminus_plus. change (Z.succ 0) with 1. repeat rewrite Z.mul_1_r.\n  Time normalize. (*2 versus 2.8*)\n  rewrite (Select_SplitSelect16Q C i _ _ HeqFB) at 2.\n  rewrite field_address0_offset by auto with field_compatible.\n  rewrite field_address0_offset by auto with field_compatible. simpl.\n  autorewrite with sublist.\n  rewrite sublist_app2; (*. (4 * Zlength Front) (4 + 4 * Zlength Front)); *)\n    repeat rewrite QuadChunk2ValList_ZLength; repeat rewrite FL.\n    2: omega.\n  rewrite Zminus_diag. rewrite Z.add_simpl_l. repeat rewrite Z.mul_1_l.\n\n  freeze [0;2;3] FR3.\n  rewrite (sublist0_app1 4), (sublist_same 0 4); try rewrite <- QuadByteValList_ZLength; try omega.\n\n  (*Issue this is where the call fails if we use abbreviation Delta := ... in the statement of the lemma*)\n\n\n  Time forward_call (offset_val (4 * i) (Vptr cb coff), Select16Q C i). (*3.4 versus 15.4*)\n  (*{ goal automatically discharged versus 4.2 }*)\n\n  thaw FR3.\n  apply semax_pre with (P':=\n  (PROP  ()\n   LOCAL  ( temp _aux (Vint (littleendian (Select16Q C i)));\n   temp _i (Vint (Int.repr i));\n   lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n   lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; temp _in nonce;\n   temp _out out; temp _c c; temp _k k; temp _h (Vint (Int.repr h)))\n   SEP\n   (FRZL FR2; data_at Tsh (Tarray tuchar 16 noattr) (SixteenByte2ValList C) c))).\n  { rewrite (Select_SplitSelect16Q C i _ _ HeqFB). unfold QByte.\n    rewrite (split3_data_at_Tarray_tuchar Tsh 16 (Zlength (QuadChunks2ValList Front)) (Zlength (QuadChunks2ValList Front)+4)); trivial;\n    repeat rewrite Zlength_app;\n    repeat rewrite QuadChunk2ValList_ZLength;\n(*    repeat rewrite FL; try rewrite BL; *)\n    try rewrite <- QuadByteValList_ZLength; try rewrite Z.mul_1_r; try omega.\n     2: destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB I) as [_ BL]; rewrite FL, BL; omega.\n    autorewrite with sublist.\n    rewrite CP in *.\n    rewrite field_address0_offset by auto with field_compatible.\n    rewrite field_address0_offset by auto with field_compatible.\n    Time entailer!. (*7.8*)\n    rewrite app_nil_r.\n    apply sepcon_derives. autorewrite with sublist.\n      rewrite sublist_app2; repeat rewrite QuadChunk2ValList_ZLength; repeat rewrite FL; try omega.\n      repeat rewrite Zminus_diag. rewrite Z.add_simpl_l.\n      rewrite sublist_app1; try rewrite <- QuadByteValList_ZLength; try omega.\n      rewrite sublist_same; try rewrite <- QuadByteValList_ZLength; try omega. trivial.\n    rewrite sublist_app2; repeat rewrite QuadChunk2ValList_ZLength; repeat rewrite FL; try omega.\n    repeat rewrite Z.add_simpl_l, app_nil_r in *. trivial. }\n\n  (*Store into x[...]*)\n  thaw FR2.\n  freeze [0;2] FR4.\n  Time forward. (*2.5 versus 5.8*)\n\n  destruct Key as [Key1 Key2].\n  thaw FR4.\n  Opaque ThirtyTwoByte.\n  thaw FR1.\n  freeze [0;1;3;4] FR5. Transparent ThirtyTwoByte.\n  Time assert_PROP (field_compatible (Tarray tuchar 32 noattr) [] k) as FCK32\n    by (unfold ThirtyTwoByte; entailer!). (*1.1 versus 5.1*)\n  erewrite ThirtyTwoByte_split16; trivial. unfold SByte at 1. Opaque ThirtyTwoByte.\n  Time normalize. (*2.2 versus 3.8*)\n  Time assert_PROP (field_compatible (Tarray tuchar 16 noattr) [] k) as FCK16 by entailer!. (*1 versus 4.7*)\n  assert (K1_16:= SixteenByte2ValList_Zlength Key1).\n  remember (SplitSelect16Q Key1 i) as FB_K1. destruct FB_K1 as (Front_K1, Back_K1).\n(*  rewrite (Select_SplitSelect16Q Key1 i _ _ HeqFB_K1).*)\n  erewrite Select_Unselect_Tarray_at. (*; repeat rewrite <- K1_16; trivial.*)\n    2: symmetry; apply (Select_SplitSelect16Q Key1 i _ _ HeqFB_K1).\n    2: assumption.\n    2: rewrite <- (Select_SplitSelect16Q Key1 i _ _ HeqFB_K1), <- K1_16; trivial.\n    2: rewrite <- (Select_SplitSelect16Q Key1 i _ _ HeqFB_K1), <- K1_16; cbv; trivial.\n  unfold Select_at. simpl. rewrite app_nil_r. flatten_sepcon_in_SEP.\n  freeze [1;2;3] FR6.\n  (*assert (FrontBackK1:= (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB_K1 I)) as [FLK BLK].*)\n  rewrite <- QuadByteValList_ZLength. (*rewrite Z.mul_1_l. *)\n  rewrite  QuadChunk2ValList_ZLength.\n  destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB_K1 I) as [FLK _]; rewrite FLK.\n\n  Time forward_call (offset_val (4 * i) k,\n                 Select16Q Key1 i). (*8.9 versus 19.5; both were 3-4 secs faster befor tick elimination etc*)\n\n  thaw  FR6.\n  apply semax_pre with (P':=\n  (PROP  ()\n   LOCAL  (temp _aux (Vint (littleendian (Select16Q Key1 i)));\n   temp _i (Vint (Int.repr i));\n   lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n   lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; temp _in nonce;\n   temp _out out; temp _c c; temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FRZL FR5; ThirtyTwoByte (Key1,Key2) k))).\n  { erewrite ThirtyTwoByte_split16; trivial.\n    repeat rewrite  <- QuadByteValList_ZLength; repeat rewrite QuadChunk2ValList_ZLength.\n    Time entailer!. (*4.4 versus 6.6*)\n    unfold SByte. rewrite (Select_SplitSelect16Q _ _ _ _ HeqFB_K1) in *.\n    erewrite Select_Unselect_Tarray_at with (data:= QuadChunks2ValList Front_K1 ++\n       QuadChunks2ValList [Select16Q Key1 (Zlength Front)(*i*)] ++ QuadChunks2ValList Back_K1); try reflexivity.\n    + unfold QByte, Select_at. simpl. repeat rewrite app_nil_r.\n      unfold Unselect_at.\n      rewrite  QuadChunk2ValList_ZLength.\n      rewrite <- QuadByteValList_ZLength, FLK. cancel.\n    + assumption.\n    + rewrite <- K1_16; assumption.\n    + rewrite <- K1_16. cbv; trivial.\n  }\n\n  (*Store into x[...]*)\n  thaw FR5.\n  freeze [0;1;2;4] FR6.\n  Time forward. (*2.8 versus 7.8*)\n\n  (*Load nonce*)\n  thaw FR6. freeze [0;2;3;4] FR7.\n  unfold SByte at 1; simpl.\n  assert (N16:= SixteenByte2ValList_Zlength Nonce).\n  remember (SplitSelect16Q Nonce i) as FB_N; destruct FB_N as (Front_N, BACK_N).\n    rewrite (Select_SplitSelect16Q _ i _ _ HeqFB_N) in *.\n  Time assert_PROP (field_compatible (Tarray tuchar 16 noattr) [] nonce) as FCN by entailer!. (*1.2 versus 6.8*)\n  erewrite Select_Unselect_Tarray_at with (d:=nonce); try reflexivity; try assumption.\n  2: solve [rewrite <- N16; trivial].\n  2: solve [rewrite <- N16; cbv; trivial].\n  Time normalize. (*2.4 versus 5.2*)\n  freeze [1;2] FR8.\n  unfold Select_at. simpl. rewrite app_nil_r.\n  rewrite <- QuadByteValList_ZLength. (*rewrite Z.mul_1_l.  simpl.*)\n  rewrite  QuadChunk2ValList_ZLength.\n  destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB_N I) as [FrontN _]; rewrite FrontN.\n  (*destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB_N I) as [FrontN BackN].*)\n\n  Time forward_call (offset_val (4 * i) nonce,\n                 Select16Q Nonce i). (*11.7 versus 21*)\n\n  thaw FR8.\n  apply semax_pre with (P':=\n  (PROP  ()\n   LOCAL  (\n   temp _aux (Vint (littleendian (Select16Q Nonce i)));\n   temp _i (Vint (Int.repr i));\n   lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n   lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; temp _in nonce;\n   temp _out out; temp _c c; temp _k k; temp _h (Vint (Int.repr h)))\n   SEP (FRZL FR7; SByte Nonce nonce))).\n  { Time entailer!. (*1.8 versus 9.5*)\n\n    (*Apart from the unfold QByte, the next 9 lines are exactly as above, inside the function call*)\n    unfold SByte. rewrite (Select_SplitSelect16Q _ _ _ _ HeqFB_N) in *.\n    erewrite Select_Unselect_Tarray_at; try reflexivity; try assumption.\n    + unfold QByte, Select_at. simpl. rewrite app_nil_r. cancel.\n      rewrite <- QuadByteValList_ZLength. (*rewrite Z.mul_1_l. simpl.*)\n      rewrite  QuadChunk2ValList_ZLength.\n      (*destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB_N I) as [FrontN _]; rewrite FrontN; cancel.*)\n      rewrite FrontN; cancel.\n    + rewrite <- N16; trivial.\n    + rewrite <- N16; cbv; trivial. }\n\n  (*Store into x[...]*)\n  thaw FR7. freeze [0;1;2;4] FR9.\n  Time forward. (*3.2 versus 15*)\n\n  (*Load Key2*)\n  thaw FR9. freeze [0;1;3;4] FR10.\n  rewrite ThirtyTwoByte_split16; trivial. Time normalize. (*2.2 versus 4.1*)\n  unfold SByte at 2.\n  assert (K2_16:= SixteenByte2ValList_Zlength Key2).\n  Time assert_PROP (isptr k/\\ field_compatible (Tarray tuchar 16 noattr) [] (offset_val 16 k))\n     as Pk_FCK2 by entailer!. (*1.4 versus 6.6*)\n  destruct Pk_FCK2 as [Pk FCK2]; apply isptrD in Pk; destruct Pk as [kb [koff Pk]]; rewrite Pk in *.\n  remember (SplitSelect16Q Key2 i) as FB_K2; destruct FB_K2 as (Front_K2, Back_K2).\n  rewrite (Select_SplitSelect16Q _ i _ _ HeqFB_K2) in *.\n  erewrite Select_Unselect_Tarray_at with (d:=offset_val 16 (Vptr kb koff)); try reflexivity; try assumption.\n  2: solve [rewrite <- K2_16; trivial]. 2: solve [rewrite <- K2_16; cbv; trivial].\n  Time normalize. (*1.4 versus 6.6*)\n  unfold Select_at. simpl. rewrite app_nil_r.\n  repeat rewrite <- QuadByteValList_ZLength.\n  rewrite QuadChunk2ValList_ZLength.\n\n  freeze [1;2;3] FR11.\n  Time forward_call (Vptr kb\n           (Int.add (Int.add koff (Int.repr 16)) (Int.repr (4 * Zlength Front_K2))),\n                 Select16Q Key2 i). (*8.9 versus 20.5 SLOW*)\n  { destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB_K2 I) as [FK2 _]; rewrite FK2.\n     apply prop_right; simpl. rewrite Z.mul_1_l.\n     trivial. }\n\n  thaw FR11.\n  apply semax_pre with (P':=\n  (PROP  ()\n   LOCAL  (\n   temp _aux (Vint (littleendian (Select16Q Key2 i)));\n   temp _i (Vint (Int.repr i));\n   lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n   lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; temp _in nonce;\n   temp _out out; temp _c c; temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FRZL FR10; ThirtyTwoByte (Key1,Key2) k))).\n  { rewrite Pk in *. erewrite ThirtyTwoByte_split16 by assumption.\n    Time entailer!. (*4.6 versus 7.4*)\n\n    (*Apart from the unfold QByte, the next 9 lines are exactly as above, inside the function call*)\n    unfold SByte. rewrite (Select_SplitSelect16Q _ _ _ _ HeqFB_K2) in *.\n    erewrite Select_Unselect_Tarray_at; try reflexivity; try assumption.\n    + unfold QByte, Select_at. simpl. repeat rewrite app_nil_r. cancel.\n      rewrite <- QuadByteValList_ZLength. (*rewrite Z.mul_1_l. simpl.*)\n      rewrite  QuadChunk2ValList_ZLength. rewrite Int.add_assoc. rewrite add_repr. cancel.\n    + rewrite <- K2_16; assumption.\n    + rewrite <- K2_16; cbv; trivial. }\n\n  (*Store into x[...]*)\n  thaw FR10. freeze [0;1;2;4] FR11.\n  Time forward. (*4.3 versus 14.7*) clear FL.\n\n  Time entailer!. (*4.9 versus 16.1*)  remember (Zlength Front_K1) as i.\n  Exists (upd_Znth (11 + i)\n     (upd_Znth (6 + i)\n        (upd_Znth (1 + i)\n           (upd_Znth (5 * i) X0\n              (Vint (littleendian (Select16Q C i))))\n           (Vint (littleendian (Select16Q Key1 i))))\n        (Vint (littleendian (Select16Q Nonce i))))\n     (Vint (littleendian (Select16Q Key2 i)))).\n  Time entailer!. (*2 versus 2.8  - penalty*)\n    clear - X0cont I. apply XcontUpdate; trivial.\n\n  thaw FR11. Time cancel. (*0.3*)\n }\napply andp_left2; apply derives_refl.\nTime Qed. (* 19.046 secs (17.109u,0.015s) (successful)*)\n\nLemma XX data l: X_content data 4 l ->\n  l = match data with ((Nonce, C), (Key1, Key2)) =>\n          match Nonce with (N1, N2, N3, N4) =>\n          match C with (C1, C2, C3, C4) =>\n          match Key1 with (K1, K2, K3, K4) =>\n          match Key2 with (L1, L2, L3, L4) =>\n      map Vint (map littleendian [C1; K1; K2; K3;\n                                  K4; C2; N1; N2;\n                                  N3; N4; C3; L1;\n                                  L2; L3; L4; C4])\n      end end end end end.\nProof.\nintros. red in H. subst l.\napply upd_upto_char. reflexivity.\nQed.", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/tweetnacl20140427/verif_fcore_loop1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6791786991753929, "lm_q2_score": 0.36296919862864757, "lm_q1q2_score": 0.24652094816533965}}
{"text": "Require Import Verdi.Verdi.\nRequire Import Verdi.HandlerMonad.\nRequire Import Verdi.NameOverlay.\nRequire Import Verdi.TotalMapSimulations.\nRequire Import Verdi.PartialMapSimulations.\nRequire Import Verdi.PartialExtendedMapSimulations.\n\nRequire Import NameAdjacency.\nRequire Import AggregationDefinitions.\nRequire Import AggregationAux.\nRequire Import AggregationStaticCorrect.\nRequire Import TreeAux.\nRequire Import TreeStaticCorrect.\nRequire Import TreeAggregationStatic.\n\nRequire Import Sumbool.\nRequire Import Orders.\nRequire Import MSetFacts.\nRequire Import MSetProperties.\n\nRequire Import mathcomp.ssreflect.ssreflect.\nRequire Import mathcomp.ssreflect.ssrbool.\nRequire Import mathcomp.ssreflect.eqtype.\nRequire Import mathcomp.ssreflect.fintype.\nRequire Import mathcomp.ssreflect.finset.\nRequire Import mathcomp.fingroup.fingroup.\n\nRequire Import AAC_tactics.AAC.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nSet Implicit Arguments.\n\nModule TreeAggregationCorrect (Import NT : NameType)  \n (NOT : NameOrderedType NT) (NSet : MSetInterface.S with Module E := NOT) \n (NOTC : NameOrderedTypeCompat NT) (NMap : FMapInterface.S with Module E := NOTC) \n (Import RNT : RootNameType NT) (Import CFG : CommutativeFinGroup) \n (Import ANT : AdjacentNameType NT) (Import A : Adjacency NT NOT NSet ANT)\n (Import TA : TAux NT NOT NSet NOTC NMap)\n (Import AD : ADefs NT NOT NSet NOTC NMap CFG).\n\nModule AGC := AggregationCorrect NT NOT NSet NOTC NMap CFG ANT A AD.\nModule AG := AGC.AG.\n\nModule TRC := TreeCorrect NT NOT NSet NOTC NMap RNT ANT A TA.\nModule TR := TRC.TR.\n\nModule AX := AAux NT NOT NSet NOTC NMap CFG ANT AD.\nImport AX.\n\nModule TG := TreeAggregation NT NOT NSet NOTC NMap RNT CFG ANT A TA AD.\nImport TG.\n\nImport GroupScope.\n\nModule ADCFGAACInstances := CFGAACInstances CFG.\nImport ADCFGAACInstances.\n\nModule NSetFacts := Facts NSet.\nModule NSetProps := Properties NSet.\nModule NSetOrdProps := OrdProperties NSet.\n\nRequire Import FMapFacts.\nModule NMapFacts := Facts NMap.\n\nInstance TreeAggregation_Aggregation_name_tot_map : MultiParamsNameTotalMap TreeAggregation_MultiParams AG.Aggregation_MultiParams :=\n  {\n    tot_map_name := id ;\n    tot_map_name_inv := id ;\n  }.\n\nInstance TreeAggregation_Aggregation_name_tot_map_bijective : MultiParamsNameTotalMapBijective TreeAggregation_Aggregation_name_tot_map :=\n  {\n    tot_map_name_inv_inverse := fun _ => Logic.eq_refl ;\n    tot_map_name_inverse_inv := fun _ => Logic.eq_refl\n  }.\n\nInstance TreeAggregation_Aggregation_params_pt_msg_map : MultiParamsMsgPartialMap TreeAggregation_MultiParams AG.Aggregation_MultiParams :=\n  {\n    pt_map_msg := fun m => \n      match m with \n      | Aggregate m' => Some (AG.Aggregate m')\n      | Fail => Some AG.Fail      \n      | Level _ => None \n      end   \n  }.\n\n\nInstance TreeAggregation_Aggregation_params_pt_ext_map : MultiParamsPartialExtendedMap TreeAggregation_MultiParams AG.Aggregation_MultiParams :=\n  {\n    pt_ext_map_data := fun d _ => \n      AG.mkData d.(local) d.(aggregate) d.(adjacent) d.(balance) ;\n    pt_ext_map_input := fun i n d =>\n      match i with \n      | Local m => Some (AG.Local m)\n      | SendAggregate => \n        if root_dec n then None else\n          match parent d.(adjacent) d.(levels) with\n          | Some p => Some (AG.SendAggregate p)\n          | None => None\n          end\n      | AggregateRequest client_id => Some (AG.AggregateRequest client_id)\n      | _ => None\n      end\n  }.\n\nLemma pt_ext_map_name_msgs_level_adjacent_empty : \n  forall fs lvo,\n  filterMap pt_map_name_msg (level_adjacent lvo fs) = [].\nProof.\nmove => fs lvo.\nrewrite /level_adjacent NSet.fold_spec.\nelim: NSet.elements => //=.\nmove => n ns IH.\nrewrite {2}/level_fold /=.\nrewrite (@fold_left_level_fold_eq TreeAggregation_TreeMsg) /=.\nby rewrite filterMap_app /= -app_nil_end IH.\nQed.\n\nInstance TreeAggregation_Aggregation_multi_params_pt_ext_map_congruency : MultiParamsPartialExtendedMapCongruency TreeAggregation_Aggregation_name_tot_map TreeAggregation_Aggregation_params_pt_msg_map TreeAggregation_Aggregation_params_pt_ext_map :=\n  {\n    pt_ext_init_handlers_eq := _ ;\n    pt_ext_net_handlers_some := _ ;\n    pt_ext_net_handlers_none := _ ;\n    pt_ext_input_handlers_some := _ ;\n    pt_ext_input_handlers_none := _ \n  }.\nProof.\n- by move => n; rewrite /= /InitData /=; break_if.\n- move => me src mg st mg' out st' ps H_eq H_eq'.\n  rewrite /pt_ext_mapped_net_handlers.\n  repeat break_let.\n  rewrite /= /runGenHandler_ignore /= in H_eq'.\n  rewrite /= /runGenHandler_ignore /= in Heqp.\n  repeat break_let.\n  repeat tuple_inversion.\n  destruct u, u0.\n  unfold id in *.\n  destruct st'.\n  by net_handler_cases; AG.net_handler_cases; simpl in *; congruence.\n- move => me src mg st out st' ps H_eq H_eq'.\n  rewrite /= /runGenHandler_ignore /= in H_eq'.\n  repeat break_let.\n  repeat tuple_inversion.\n  destruct u.\n  destruct st'.\n  by net_handler_cases; simpl in *; congruence.\n- move => me inp st inp' out st' ps H_eq H_eq'.\n  rewrite /pt_ext_mapped_input_handlers.\n  repeat break_let.\n  rewrite /= /runGenHandler_ignore /= in H_eq'.\n  rewrite /= /runGenHandler_ignore /= in Heqp.\n  repeat break_let.\n  repeat tuple_inversion.\n  destruct u, u0.\n  unfold id in *.\n  have H_eq_inp: inp = SendAggregate \\/ inp <> SendAggregate by destruct inp; (try by right); left.\n  case: H_eq_inp => H_eq_inp.\n    subst_max.\n    rewrite /= in H_eq.\n    move: H_eq.\n    case H_p: (parent st.(adjacent) st.(levels)) => [dst|].\n      have H_p' := H_p.\n      rewrite /parent in H_p'.\n      break_match_hyp => //.\n      destruct s.\n      simpl in *.\n      find_injection.\n      inversion m0.\n      inversion H.\n      destruct st'.\n      io_handler_cases; AG.io_handler_cases; simpl in *; repeat break_match; repeat find_injection; unfold id in *; try congruence.\n      move: Heqb.\n      by case root_dec.\n    by io_handler_cases; AG.io_handler_cases; simpl in *; repeat break_match; repeat find_injection; congruence.\n  destruct st'.\n  simpl in *.\n  by io_handler_cases; AG.io_handler_cases; simpl in *; repeat break_match; repeat find_injection; congruence.\n- move => me inp st out st' ps H_eq H_eq'.\n  rewrite /= /runGenHandler_ignore /= in H_eq'.\n  repeat break_let.\n  repeat tuple_inversion.\n  destruct u.\n  destruct st'.\n  io_handler_cases; simpl in *; unfold is_left in *; repeat break_if; try break_match; try congruence.\n  * by rewrite pt_ext_map_name_msgs_level_adjacent_empty.\n  * by rewrite pt_ext_map_name_msgs_level_adjacent_empty.\nQed.\n  \nInstance TreeAggregation_Aggregation_fail_msg_params_pt_ext_map_congruency : FailMsgParamsPartialMapCongruency TreeAggregation_FailMsgParams AG.Aggregation_FailMsgParams TreeAggregation_Aggregation_params_pt_msg_map := \n  {\n    pt_fail_msg_fst_snd := Logic.eq_refl\n  }.\n\nInstance TreeAggregation_Aggregation_name_overlay_params_tot_map_congruency : NameOverlayParamsTotalMapCongruency TreeAggregation_NameOverlayParams AG.Aggregation_NameOverlayParams TreeAggregation_Aggregation_name_tot_map := \n  {\n    tot_adjacent_to_fst_snd := fun _ _ => conj (fun H => H) (fun H => H)\n  }.\n\nTheorem TreeAggregation_Aggregation_pt_ext_mapped_simulation_star_1 :\nforall net failed tr,\n    @step_ordered_failure_star _ _ TreeAggregation_NameOverlayParams TreeAggregation_FailMsgParams step_ordered_failure_init (failed, net) tr ->\n    exists tr', @step_ordered_failure_star _ _ AG.Aggregation_NameOverlayParams AG.Aggregation_FailMsgParams step_ordered_failure_init (failed, pt_ext_map_onet net) tr'.\nProof.\nmove => onet failed tr H_st.\napply step_ordered_failure_pt_ext_mapped_simulation_star_1 in H_st.\nmove: H_st => [tr' H_st].\nrewrite map_id in H_st.\nby exists tr'.\nQed.\n\nInstance TreeAggregation_Tree_base_params_pt_map : BaseParamsPartialMap TreeAggregation_BaseParams TR.Tree_BaseParams :=\n  {\n    pt_map_data := fun d => TR.mkData d.(adjacent) d.(broadcast) d.(levels) ;\n    pt_map_input := fun i =>\n                   match i with\n                   | LevelRequest client_id => Some (TR.LevelRequest client_id)\n                   | Broadcast => Some TR.Broadcast\n                   | _ => None\n                   end ;\n    pt_map_output := fun o => \n                    match o with\n                    | LevelResponse client_id olv => Some (TR.LevelResponse client_id olv)\n                    | _ => None\n                    end\n  }.\n\nInstance TreeAggregation_Tree_name_tot_map : MultiParamsNameTotalMap TreeAggregation_MultiParams TR.Tree_MultiParams :=\n  {\n    tot_map_name := id ;\n    tot_map_name_inv := id ;\n  }.\n\nInstance TreeAggregation_Tree_name_tot_map_bijective : MultiParamsNameTotalMapBijective TreeAggregation_Tree_name_tot_map :=\n  {\n    tot_map_name_inv_inverse := fun _ => Logic.eq_refl ;\n    tot_map_name_inverse_inv := fun _ => Logic.eq_refl\n  }.\n\nInstance TreeAggregation_Tree_multi_params_pt_map : MultiParamsMsgPartialMap TreeAggregation_MultiParams TR.Tree_MultiParams :=\n  {\n    pt_map_msg := fun m => match m with \n                        | Fail => Some TR.Fail \n                        | Level lvo => Some (TR.Level lvo)\n                        | _ => None \n                        end ;\n  }.\n\nInstance TreeAggregation_Tree_multi_params_pt_map_congruency : MultiParamsPartialMapCongruency TreeAggregation_Tree_base_params_pt_map TreeAggregation_Tree_name_tot_map TreeAggregation_Tree_multi_params_pt_map :=\n  {\n    pt_init_handlers_eq := _ ;\n    pt_net_handlers_some := _ ;\n    pt_net_handlers_none := _ ;\n    pt_input_handlers_some := _ ;\n    pt_input_handlers_none := _\n  }.\n- by move => n; rewrite /= /InitData /= /TR.InitData /= /id /=; break_if.\n- move => me src mg st mg' H_eq.  \n  rewrite /pt_mapped_net_handlers.\n  repeat break_let.\n  case H_n: net_handlers => [[out st'] ps].\n  rewrite /= /runGenHandler_ignore /= in Heqp H_n.\n  repeat break_let.\n  repeat tuple_inversion.\n  unfold id in *.\n  destruct u, u0.\n  destruct st'.\n  by net_handler_cases; TR.net_handler_cases; simpl in *; congruence.\n- move => me src mg st out st' ps H_eq H_eq'.\n  rewrite /= /runGenHandler_ignore /= in H_eq'.\n  repeat break_let.\n  repeat tuple_inversion.\n  destruct u, st'.\n  by net_handler_cases; simpl in *; congruence.\n- move => me inp st inp' H_eq.\n  rewrite /pt_mapped_input_handlers.\n  repeat break_let.  \n  case H_i: input_handlers => [[out st'] ps].\n  rewrite /= /runGenHandler_ignore /= in Heqp H_i.\n  repeat break_let.\n  repeat tuple_inversion.\n  unfold id in *.\n  destruct u, u0, st, st'.\n  io_handler_cases; TR.io_handler_cases; simpl in *; try congruence.\n    set ptl := filterMap _ _.\n    set ptl' := level_adjacent _ _.\n    suff H_suff: ptl = ptl' by repeat find_rewrite.\n    rewrite /ptl /ptl' /level_adjacent 2!NSet.fold_spec.\n    elim: NSet.elements => //=.\n    move => n ns IH.\n    rewrite (@fold_left_level_fold_eq TreeAggregation_TreeMsg) filterMap_app /= /id /=.\n    by rewrite (@fold_left_level_fold_eq TR.Tree_TreeMsg) /= IH.\n  set ptl := filterMap _ _.\n  set ptl' := level_adjacent _ _.\n  suff H_suff: ptl = ptl' by repeat find_rewrite.\n  rewrite /ptl /ptl' /level_adjacent 2!NSet.fold_spec.\n  elim: NSet.elements => //=.\n  move => n ns IH.\n  rewrite (@fold_left_level_fold_eq TreeAggregation_TreeMsg) filterMap_app /= /id /=.\n  by rewrite (@fold_left_level_fold_eq TR.Tree_TreeMsg) /= IH.\n- move => me inp st out st' ps H_eq H_eq'.\n  rewrite /= /runGenHandler_ignore /= in H_eq'.\n  repeat break_let.  \n  repeat tuple_inversion.\n  destruct u, st'.\n  by io_handler_cases; simpl in *; congruence.\nQed.\n\nInstance TreeAggregation_Tree_fail_msg_params_pt_map_congruency : FailMsgParamsPartialMapCongruency TreeAggregation_FailMsgParams TR.Tree_FailMsgParams TreeAggregation_Tree_multi_params_pt_map := \n  {\n    pt_fail_msg_fst_snd := Logic.eq_refl\n  }.\n\nInstance TreeAggregation_Tree_name_overlay_params_tot_map_congruency : NameOverlayParamsTotalMapCongruency TreeAggregation_NameOverlayParams TR.Tree_NameOverlayParams TreeAggregation_Tree_name_tot_map := \n  {\n    tot_adjacent_to_fst_snd := fun _ _ => conj (fun H => H) (fun H => H)\n  }.\n\nTheorem TreeAggregation_Tree_pt_mapped_simulation_star_1 :\nforall net failed tr,\n    @step_ordered_failure_star _ _ TreeAggregation_NameOverlayParams TreeAggregation_FailMsgParams step_ordered_failure_init (failed, net) tr ->\n    @step_ordered_failure_star _ _ TR.Tree_NameOverlayParams TR.Tree_FailMsgParams step_ordered_failure_init (failed, pt_map_onet net) (filterMap pt_map_trace_ev tr).\nProof.\nmove => onet failed tr H_st.\napply step_ordered_failure_pt_mapped_simulation_star_1 in H_st.\nby rewrite map_id in H_st.\nQed.\n\nInstance AggregationData_Data : AggregationData Data :=\n  {\n    aggr_local := local ;\n    aggr_aggregate := aggregate ;\n    aggr_adjacent := adjacent ;\n    aggr_balance := balance\n  }.\n\nInstance AggregationMsg_TreeAggregation : AggregationMsg :=\n  {\n    aggr_msg := msg ;\n    aggr_msg_eq_dec := msg_eq_dec ;\n    aggr_fail := Fail ;\n    aggr_of := fun mg => match mg with | Aggregate m' => m' | _ => 1 end\n  }.\n\nInstance AggregationMsgMap_Aggregation_TreeAggregation : AggregationMsgMap AggregationMsg_TreeAggregation AGC.AggregationMsg_Aggregation :=\n  {\n    map_msgs := filterMap pt_map_msg ;    \n  }.\nProof.\n- elim => //=.\n  case => [m'||olv] ms IH /=.\n  * by rewrite /aggregate_sum_fold /= IH.\n  * by rewrite /aggregate_sum_fold /= IH.\n  * by rewrite /aggregate_sum_fold /= IH; gsimpl.\n- elim => //=.\n  case => [m'||olv] ms IH /=.\n  * by split => H_in; case: H_in => H_in //; right; apply IH.\n  * by split => H_in; left.\n  * split => H_in; last by right; apply IH.\n    case: H_in => H_in //.\n    by apply IH.\nDefined.\n\nLemma TreeAggregation_conserves_network_mass : \n  forall onet failed tr,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr ->\n  conserves_network_mass (remove_all name_eq_dec failed nodes) nodes onet.(onwPackets) onet.(onwState).\nProof.\nmove => onet failed tr H_st.\nhave [tr' H_st'] := TreeAggregation_Aggregation_pt_ext_mapped_simulation_star_1 H_st.\nhave H_inv := AGC.Aggregation_conserves_network_mass H_st'.\nrewrite /= /id /= /conserves_network_mass in H_inv.\nrewrite /conserves_network_mass.\nmove: H_inv.\nset state := fun n : name => _.\nset packets := fun src dst : name => _.\nrewrite (sum_local_aggr_local_eq _ (onwState onet)) //.\nmove => H_inv.\nrewrite H_inv {H_inv}.\nrewrite (sum_aggregate_aggr_aggregate_eq _ (onwState onet)) //.\nrewrite sum_aggregate_msg_incoming_active_map_msgs_eq /map_msgs /= -/packets.\nby rewrite (sum_fail_balance_incoming_active_map_msgs_eq _ state) /map_msgs /= -/packets //.\nQed.\n\nEnd TreeAggregationCorrect.\n", "meta": {"author": "DistributedComponents", "repo": "verdi-aggregation", "sha": "c81681555d63d4a3db225119600833868caf4607", "save_path": "github-repos/coq/DistributedComponents-verdi-aggregation", "path": "github-repos/coq/DistributedComponents-verdi-aggregation/verdi-aggregation-c81681555d63d4a3db225119600833868caf4607/systems/TreeAggregationStaticCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.24646990513685751}}
{"text": "Inductive Empty : Prop := .\n\nInductive paths {A : Type} (a : A) : A -> Type :=\n  idpath : paths a a.\n\nNotation \"x = y :> A\" := (@paths A x y) : type_scope.\nNotation \"x = y\" := (x = y :>_) : type_scope.\n\nArguments idpath {A a} , [A] a.\n\nDefinition idmap {A : Type} : A -> A := fun x => x.\n\nDefinition path_sum {A B : Type} (z z' : A + B)\n           (pq : match z, z' with\n                   | inl z0, inl z'0 => z0 = z'0\n                   | inr z0, inr z'0 => z0 = z'0\n                   | _, _ => Empty\n                 end)\n: z = z'.\n  destruct z, z', pq; exact idpath.\nDefined.\n\nDefinition ap {A B:Type} (f:A -> B) {x y:A} (p:x = y) : f x = f y\n  := match p with idpath => idpath end.\n\nTheorem ex2_8 {A B A' B' : Type} (g : A -> A') (h : B -> B') (x y : A + B)\n              (* Fortunately, this unifies properly *)\n              (pq : match (x, y) with (inl x', inl y') => x' = y' | (inr x', inr y') => x' = y' | _ => Empty end) :\n  let f z := match z with inl z' => inl (g z') | inr z' => inr (h z') end in\n  ap f (path_sum x y pq) = path_sum (f x) (f y)\n     (* Coq appears to require *ALL* of the annotations *)\n     ((match x as x return match (x, y) with\n              (inl x', inl y') => x' = y'\n            | (inr x', inr y') => x' = y'\n            | _ => Empty\n          end -> match (f x, f y) with\n               | (inl x', inl y') => x' = y'\n               | (inr x', inr y') => x' = y'\n               | _ => Empty end with\n           | inl x' => match y as y return match y with\n                                               inl y' => x' = y'\n                                             | _ => Empty\n                                           end -> match f y with\n                                                    | inl y' => g x' = y'\n                                                    | _ => Empty end with\n                         | inl y' => ap g\n                         | inr y' => idmap\n                       end\n           | inr x' => match y as y return match y return Prop with\n                                               inr y' => x' = y'\n                                             | _ => Empty\n                                           end -> match f y return Prop with\n                                                    | inr y' => h x' = y'\n                                                    | _ => Empty end with\n                         | inl y' => idmap\n                         | inr y' => ap h\n                       end\n       end) pq).\n  destruct x; destruct y; destruct pq; reflexivity.\nQed.\n(* Toplevel input, characters 1367-1374:\nError:\nIn environment\nA : Type\nB : Type\nA' : Type\nB' : Type\ng : A -> A'\nh : B -> B'\nx : A + B\ny : A + B\npq :\nmatch x with\n| inl x' => match y with\n            | inl y' => x' = y'\n            | inr _ => Empty\n            end\n| inr x' => match y with\n            | inl _ => Empty\n            | inr y' => x' = y'\n            end\nend\nf :=\nfun z : A + B =>\nmatch z with\n| inl z' => inl (g z')\n| inr z' => inr (h z')\nend : A + B -> A' + B'\nx' : B\ny0 : A + B\ny' : B\nThe term \"x' = y'\" has type \"Type\" while it is expected to have type\n\"Prop\" (Universe inconsistency). *)\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/closed/HoTT_coq_054.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.2464106822396846}}
{"text": "(*\n * Copyright (c) 2009 Robert Dockins and Aquinas Hobor.\n *\n *)\n\n(* Coq development: using indirection theory to model types in l-calculus *)\n\nRequire Import msl.msl_standard.\n\nRequire Import lam_ref_tcb.\nRequire Import lam_ref_mach_defs.\nRequire Import lam_ref_mach_lemmas.\nRequire Import lam_ref_type_prelim.\nRequire Import lam_ref_type_defs.\nRequire Import lam_ref_type_safety.\n\nLemma exp_to_val_to_exp : forall v H,\n  exp_to_val (val_to_exp v) H = v.\nProof.\n  unfold val_to_exp, exp_to_val.\n  intros.\n  destruct v as [v Hv]; simpl in *.\n  destruct v; simpl in *;\n    (replace Hv with H by (apply proof_irr); auto).\nQed.\n\nLemma forces2exprType: forall w v tau,\n  forces w v (%tau) ->\n  forall v', expr_type (val_to_exp v) tau (w,v').\nProof.\n  intros.\n  rewrite expr_type_eqn.\n  repeat intro.\n  split.\n  repeat intro.\n  simpl in H4.\n  assert (stopped b (val_to_exp v)).\n  apply values_stopped.\n  unfold val_to_exp.\n  destruct v; simpl; auto.\n  elim H6; eauto.\n  repeat intro.\n  simpl in H4.\n  exists (projT2 v).\n  rewrite exp_to_val_to_exp.\n  destruct a'.\n  destruct H0.\n  subst.\n  rewrite <- (box_refl_trans extendM) in H; auto.\n  assert (forces m v (%tau)).\n  apply H.\n  split; auto.\n  assert (forces (fst a'1) v (%tau)).\n  apply pred_nec_hereditary with (m,v).\n  rewrite value_knot_necR; split; auto.\n  assert (necR (m,v0) a'1).\n  apply rt_trans with a'0; auto.\n  destruct a'1.\n  rewrite value_knot_necR in H6.\n  intuition.\n  auto.\n  apply H6.\nQed.\n\nLemma exprType_value : forall w e tau m v\n  (H:isValue e),\n  forces w v (mtype_valid m) ->\n  expr_type e tau (w,v) ->\n  forces w (exp_to_val e H) (%tau).\nProof.\n  intros.\n  rewrite expr_type_eqn in H1.\n  spec H1 (w,v).\n  detach H1.\n  spec H1 m.\n  spec H1 (w,v) (rt_refl _ age (w,v)) H0.\n  destruct H1.\n  spec H2 (w,v) (rt_refl _ age (w,v)).\n  detach H2.\n  destruct H2.\n  replace H with x by (apply proof_irr).\n  auto.\n  simpl; auto.\n  apply values_stopped; auto.\n  apply R_extends_refl.\nQed.\n\nLemma expr_type_search_rule : forall (G Q tau sigma:pred world) (f:expr -> expr),\n  forall e a,\n         closed (f e) ->\n         expr_type e tau a ->\n         (Q) a ->\n         (|>G) a ->\n  forall\n  (HQ: boxy extendM Q)\n  (HG: boxy extendM G)\n  (Hstep : forall m m' x y, step (m,x) (m',y) -> step (m,f x) (m',f y))\n  (Hredex:\n     forall k v e m (H:isValue e),\n         closed (f e) ->\n         (|>G) (k,v) ->\n         Q (k,v) ->\n         mtype_valid m (k,v) ->\n         (%tau) (k,exp_to_val e H) ->\n         expr_type (f e) sigma (k,v))\n  (Hsearch:\n     forall e a,\n         closed (f e) ->\n         G a ->\n         Q a ->\n         expr_type e tau a ->\n         expr_type (f e) sigma a),\n\n  expr_type (f e) sigma a.\nProof.\n  intros G Q tau sigma f e a Hcl H H0 H1; intros.\n  rewrite expr_type_eqn; repeat intro.\n  destruct (stopped_dec e b).\n  destruct s as [[m' e'] Hst].\n  split; repeat intro.\n  simpl in H6.\n  destruct a'2 as [k v].\n  generalize (Hstep _ _ _ _ Hst); intros.\n  assert (m' = b0 /\\ f e' = b1).\n  eapply step_deterministic; eauto.\n  destruct H9; subst b0 b1.\n  clear H8.\n  rewrite expr_type_eqn in H.\n  spec H a' H2.\n  spec H b a'0 H3 H4.\n  destruct H.\n  spec H m' e' a'1 H5.\n  detach H.\n  spec H (k,v) H7.\n  destruct H as [w [? ?]].\n  exists w; split; auto.\n  destruct H9.\n  split; auto.\n  apply Hsearch; auto.\n  change (f e') with (snd (m',f e')).\n  eapply closed_step; eauto.\n  rewrite <- HG in H1.\n  rewrite <- later_commute in H1.\n  spec H1 a' H2.\n  spec H1 (k,v).\n  detach H1.\n  rewrite <- HG in H1.\n  apply H1; auto.\n  simpl; apply Rft_Rt_trans with a'1; auto.\n  apply rt_trans with a'0; auto.\n  rewrite <- HQ in H0.\n  spec H0 a' H2.\n  eapply pred_nec_hereditary in H0.\n  2: instantiate (1:=(k,v)).\n  rewrite <- HQ in H0.\n  apply H0; auto.\n  apply rt_trans with a'0; auto.\n  apply rt_trans with a'1; auto.\n  apply Rt_Rft; auto.\n  simpl; auto.\n  simpl in H6.\n  elim H6.\n  exists m'; exists (f e').\n  apply Hstep; auto.\n\n  rewrite expr_type_eqn in H.\n  spec H a' H2.\n  spec H b a'0 H3 H4.\n  destruct H.\n  spec H5 a'0 (rt_refl _ age a'0).\n  spec H5.\n  simpl; auto.\n  destruct H5.\n  destruct a'0 as [k v].\n  assert (expr_type (f e) sigma (k,v)).\n  spec Hredex k v e b x.\n  apply Hredex; auto.\n  rewrite <- HG in H1.\n  rewrite <- later_commute in H1.\n  spec H1 a' H2.\n  apply pred_nec_hereditary with a'; auto.\n  rewrite <- HQ in H0.\n  spec H0 a' H2.\n  apply pred_nec_hereditary with a'; auto.\n  rewrite expr_type_eqn in H6.\n  spec H6 (k,v).\n  detach H6.\n  eapply H6; eauto.\n  apply R_extends_refl.\nQed.\n\nLemma subst_env_valid_closed :  forall env G e a,\n  closed' (length G) e ->\n  etype_valid env G a ->\n  closed (subst_env env e).\nProof.\n  intros.\n  unfold closed, subst_env.\n  change 0 with (0 + 0).\n  apply closed_subst_env.\n  replace (length env + 0) with (length G); auto.\n  revert H0; clear.\n  revert env a; induction G; destruct env; simpl; intuition.\n  rewrite IHG with env a0; auto.\nQed.\n\nLemma etype_valid_lookup: forall G x tau w env v,\n  nth_error G x = Some tau ->\n  etype_valid env G (w,v) ->\n  exists v,\n    nth_error env x = Some v /\\ forces w v (%tau).\nProof.\n  induction G; intros.\n  destruct x; inversion H.\n  destruct x.\n  simpl in H.\n  inversion H; clear H.\n  subst a.\n  destruct env.\n  inversion H0.\n  simpl in H0.\n  destruct H0.\n  exists v0.\n  simpl.\n  auto.\n  destruct env.\n  inversion H0.\n  simpl in H0.\n  destruct H0.\n  simpl in H.\n  apply (IHG _ _ _ _ _ H H1).\nQed.\n\nLemma etype_valid_val : forall G env m v v',\n  etype_valid env G (m,v) ->\n  etype_valid env G (m,v').\nProof.\n  induction G; destruct env; simpl; intuition.\n  eapply IHG; eauto.\nQed.\n\nLemma expr_type_val' : forall tau,\n  TT |-- ALL v:value, ALL e:expr, %(expr_type e tau --> with_val v (expr_type e tau)).\nProof.\n  intros; apply goedel_loeb.\n  hnf; intros.\n  intro v.\n  destruct H; destruct a.\n  clear H.\n  rename H0 into H.\n  repeat intro.\n  destruct a'; simpl.\n  destruct H0; subst.\n  destruct a'0.\n  rewrite value_knot_necR in H1; destruct H1; subst.\n  rewrite expr_type_eqn.\n  rewrite expr_type_eqn in H2.\n  repeat intro.\n  destruct a'.\n  destruct H3; subst.\n  simpl in H3.\n  destruct a'0.\n  rewrite value_knot_necR in H4; destruct H4; subst.\n  spec H2 (m2,v0).\n  detach H2.\n  spec H2 b0 (m3,v0).\n  detach H2.\n  spec H2 H5.\n  split; destruct H2.\n  repeat intro.\n  spec H2 b1 b2.\n  destruct a'.\n  rewrite value_knot_necR in H7; destruct H7; subst.\n  destruct a'0.\n  simpl in H9.\n  rewrite value_knot_laterR in H9; destruct H9; subst.\n  spec H2 (m4,v0).\n  detach H2.\n  detach H2.\n  spec H2 (m5,v0).\n  detach H2.\n  destruct H2 as [w [? ?]].\n  destruct w.\n  destruct H2.\n  subst.\n  exists (m6,v).\n  split.\n  simpl; split; auto.\n  destruct H10.\n  split.\n  auto.\n  rewrite box_all in H.\n  spec H v.\n  rewrite box_all in H.\n  spec H b2.\n  rewrite <- (box_refl_trans extendM) in H.\n  rewrite <- later_commute in H.\n  spec H (m0,v1).\n  detach H.\n  eapply pred_nec_hereditary in H.\n  2: instantiate (1:=(m1,v1)).\n  rewrite <- (box_refl_trans extendM) in H.\n  rewrite <- later_commute in H.\n  spec H (m2,v1); detach H.\n  spec H (m5,v1).\n  detach H.\n  spec H (m6,v1).\n  detach H.\n  spec H (m6,v1) (rt_refl _ age (m6,v1)).\n  apply H; auto.\n  split; auto.\n  simpl.\n  rewrite value_knot_laterR; split; auto.\n  apply Rft_Rt_trans with m4; auto.\n  apply rt_trans with m3; auto.\n  split; auto.\n  simpl; apply R_extends_refl.\n  simpl; apply R_extends_trans.\n  rewrite value_knot_necR; split; auto.\n  split; auto.\n  simpl; apply R_extends_refl.\n  simpl; apply R_extends_trans.\n  simpl; rewrite value_knot_laterR; split; auto.\n  simpl in H8.\n  simpl; auto.\n  rewrite value_knot_necR; split; auto.\n\n  repeat intro.\n  destruct a'; simpl in H8.\n  spec H6 (m4,v0).\n  detach H6.\n  detach H6.\n  auto.\n  simpl; auto.\n  rewrite value_knot_necR; split; auto.\n  rewrite value_knot_necR in H7; intuition.\n  rewrite value_knot_necR; split; auto.\n  split; auto.\nQed.\n\nLemma expr_type_val : forall e tau k v v',\n  expr_type e tau (k,v) ->\n  expr_type e tau (k,v').\nProof.\n  intros.\n  generalize (expr_type_val' tau); intro H0.\n  spec H0 (k,v) I v' e.\n  spec H0 (k,v) (R_extends_refl (k,v)).\n  spec H0 (k,v) (rt_refl _ age (k,v)).\n  apply H0; auto.\nQed.\n\nLemma openValue_valid_value : forall env G a e,\n  openValue e ->\n  closed' (length G) e ->\n  etype_valid env G a ->\n  isValue (subst_env env e).\nProof.\n  intros env; pattern env.\n  apply rev_ind; clear env; simpl; intros.\n  destruct G; auto.\n  split; auto.\n  elim H1.\n  rewrite <- (rev_involutive G) in H2.\n  case_eq (rev G); intros;\n    rewrite H3 in H2; simpl in H2.\n  destruct l; inv H2.\n  unfold subst_env.\n  rewrite subst_env_split.\n  simpl.\n  assert (etype_valid l (rev l0) a).\n  revert H2; clear.\n  generalize (rev l0); clear.\n  induction l; simpl; intros; auto.\n  destruct l; simpl in *; auto.\n  destruct H2.\n  destruct l; simpl in H0; auto.\n  destruct l0; simpl in H2.\n  destruct H2.\n  destruct l; simpl in H0; auto.\n  destruct H2.\n  split.\n  destruct a; simpl in *.\n  auto.\n  apply IHl; auto.\n\n  eapply H with (rev l0) a.\n  destruct e; simpl in *; auto.\n  elim H0.\n  replace (length l + 0) with (length l0).\n  rewrite rev_length.\n  apply subst_closed'.\n  replace (S (length l0)) with (length G); auto.\n  rewrite <- rev_length.\n  rewrite H3; simpl.\n  auto.\n  rewrite <- (rev_length l0).\n  revert H4; generalize (rev l0); clear.\n  induction l; intros.\n  destruct l; simpl in H4.\n  auto.\n  elim H4.\n  simpl.\n  destruct l0; simpl in H4.\n  elim H4.\n  simpl; f_equal; auto.\n  apply IHl; auto.\n  destruct H4; auto.\n  auto.\nQed.\n\n\n(** Redex rules **)\n\nLemma typ_beta: forall v1 v2 sigma tau w,\n  forces w v1 (ty_lam sigma tau) ->\n  forces w v2 (%sigma) ->\n  forall v', expr_type (App (val_to_exp v1) (val_to_exp v2)) tau (w,v').\nProof.\n  intros.\n  rewrite expr_type_eqn.\n  intros z Hz.\n  destruct z as [z v].\n  destruct Hz as [Hz ?]; subst.\n  repeat intro; split; repeat intro.\n  simpl in H4; inv H4.\n  elim (values_stopped (val_to_exp v1)) with b; eauto.\n  apply (projT2 v1).\n  elim (values_stopped (val_to_exp v2)) with b; eauto.\n  apply (projT2 v2).\n  exists a'1; split.\n  do 5 red; apply R_extends_refl.\n  rewrite exp_to_val_to_exp.\n  split.\n  apply pred_nec_hereditary with a'; auto.\n  apply rt_trans with a'0; auto.\n  apply Rt_Rft; auto.\n  destruct H as [e [He [Hjst ?]]].\n  simpl in Hjst; subst v1.\n  inv H9.\n  rewrite <- later_commute in H.\n  spec H (z,v_Lam e He).\n  detach H.\n  spec H (fst a'1,v_Lam e He).\n  detach H.\n  spec H v2 (fst a'1,v_Lam e He).\n  spec H (rt_refl _ age (fst a'1,v_Lam e He)).\n  detach H.\n  destruct a'1; auto.\n  revert H.\n  apply expr_type_val.\n  simpl; auto.\n  simpl; intros.\n  destruct a'2; destruct H; subst.\n  assert (forces (fst a'1) v0 (%sigma)).\n  apply pred_nec_hereditary with (z,v0).\n  rewrite value_knot_necR; split; auto.\n  assert (necR (z,v) a'1).\n  apply rt_trans with a'; auto.\n  apply rt_trans with a'0; auto.\n  apply Rt_Rft; auto.\n  destruct a'1.\n  rewrite value_knot_necR in H4.\n  intuition.\n  rewrite <- (box_refl_trans extendM) in H0; auto.\n  apply H0.\n  split; auto.\n  apply H4.\n  split; auto.\n  simpl; rewrite value_knot_laterR; split; auto.\n  assert (laterR (z,v) a'1).\n  apply Rft_Rt_trans with a'; auto.\n  apply Rft_Rt_trans with a'0; auto.\n  destruct a'1.\n  rewrite value_knot_laterR in H.\n  intuition.\n  split; auto.\n\n  exfalso.\n  simpl in H4.\n  elim H4.\n  destruct H as [e [He [? ?]]].\n  simpl in H.\n  subst v1.\n  unfold v_Lam.\n  unfold val_to_exp, v_Lam; simpl.\n  exists b.\n  exists (subst 0 (exp_to_val (projT1 v2) (projT2 v2)) e).\n  apply st_App3.\nQed.\n\nLemma expr_ty_new: forall k v tau,\n  forces k v (%tau) ->\n  forall v', expr_type (New (val_to_exp v)) (ty_ref tau) (k,v').\nProof.\n  intros.\n  destruct v; unfold val_to_exp; simpl.\n  rewrite expr_type_eqn.\n  repeat intro.\n  split; repeat intro.\n\n  simpl in H4.\n  inv H4.\n  assert (stopped b x).\n  apply values_stopped; auto.\n  elim H4; eauto.\n  unfold new in H8.\n  destruct b; inv H8.\n  destruct a'2.\n  case_eq (unsquash m); intros.\n  set (f' := fun a => if beq_nat a l then Some tau else f a).\n  assert (R_extends (m,v0) (squash (n,f'),v0)).\n  split; auto.\n  hnf.\n  rewrite H4.\n  rewrite unsquash_squash.\n  split; auto.\n  intros.\n  assert (mtype_valid (l,v) (m,v0)).\n  apply pred_nec_hereditary with a'0; auto.\n  apply rt_trans with a'1; auto.\n  apply Rt_Rft; auto.\n  case_eq (f a); intros; auto.\n  right.\n  unfold fmap, option_map, compose, f'.\n  hnf in H7.\n  rewrite H4 in H7.\n  case_eq (beq_nat a l); intros.\n  apply beq_nat_true in H9.\n  subst a.\n  spec H7 l.\n  cbv beta zeta in H7.\n  rewrite H8 in H7.\n  destruct H7.\n  simpl in H7; omegac.\n  cbv beta zeta in H7.\n  spec H7 a.\n  rewrite H8 in H7.\n  simpl.\n  rewrite H8.\n  generalize H8.\n  rewrite (unsquash_approx H4).\n  simpl.\n  rewrite H8.\n  rewrite H9.\n  auto.\n  assert\n    (mtype_valid\n        (S l, fun a : nat => if beq_nat a l then exp_to_val x H6 else v a)\n        (squash (n,f'),v0)).\n  hnf. unfold f'.\n  rewrite unsquash_squash.\n  intro a.\n  simpl fmap. simpl ffun_fmap.\n  case_eq (beq_nat a l); intros.\n  simpl option_map.\n  unfold fidentity_fmap.\n  apply beq_nat_true in H8.\n  subst a.\n  simpl fst.\n  split; auto.\n\n  unfold deref; simpl snd.\n  case_eq (beq_nat l l); intros.\n  replace H6 with i by apply proof_irr.\n  rewrite later_commute.\n  fold f'.\n  unfold forces.\n  unfold forces in H.\n  cut ((%tau) (squash (n,f'),exp_to_val x i)).\n  repeat intro.\n  red. rewrite approx_spec.\n  split; auto.\n  replace (level a'3) with (level a'2).\n  apply lt_le_trans with (level (fst (squash (n,f'),exp_to_val x i))).\n  simpl in H10.\n  destruct a'2.\n  rewrite value_knot_laterR in H10.\n  simpl.\n  apply laterR_level; auto.\n  destruct H10; auto.\n  rewrite knot_level; simpl.\n  rewrite unsquash_squash; auto.\n  simpl in H11.\n  apply extend_level; auto.\n  eapply pred_nec_hereditary in H9.\n  2: apply Rt_Rft; apply H10.\n  spec H9 a'3 H11.\n  apply pred_nec_hereditary with a'3; auto.\n  destruct a'.\n  assert ((%tau) (m0,exp_to_val x i)).\n  rewrite <- box_refl_trans in H; auto.\n  apply H.\n  split; auto.\n  destruct H0; auto.\n  assert ((%tau) (m,exp_to_val x i)).\n  apply pred_nec_hereditary with (m0,exp_to_val x i).\n  rewrite value_knot_necR; split; auto.\n  assert (necR (m0,v1) (m,v0)).\n  apply rt_trans with a'0; auto.\n  apply rt_trans with a'1; auto.\n  apply Rt_Rft; auto.\n  rewrite value_knot_necR in H10.\n  destruct H10; auto.\n  auto.\n  rewrite <- box_refl_trans in H10; auto.\n  apply H10; auto.\n  split; auto.\n  destruct H7; auto.\n  apply beq_nat_false in H8; elim H8; auto.\n  case_eq (f a); intros.\n  assert (mtype_valid (l,v) (m,v0)).\n  apply pred_nec_hereditary with a'0; auto.\n  apply rt_trans with a'1; auto.\n  apply Rt_Rft; auto.\n  hnf in H10.\n  rewrite H4 in H10.\n  cbv beta zeta in H10.\n  spec H10 a.\n  rewrite H9 in H10.\n  destruct H10.\n  simpl in H10.\n  split.\n  simpl; omega.\n  simpl deref.\n  rewrite H8.\n  unfold deref in H11.\n  simpl snd in H11.\n  rewrite <- box_refl_trans in H11; auto.\n  fold f'.\n  spec H11 (squash (n,f'),v a).\n  spec H11.\n  split; auto.\n  destruct H7; auto.\n  repeat intro.\n  unfold fidentity_fmap. red. rewrite approx_spec.\n  split.\n  apply lt_le_trans with (level a'2).\n  apply laterR_level; auto.\n  destruct a'2; destruct H12; subst.\n  simpl.\n  rewrite knot_level.\n  hnf in H12.\n  rewrite unsquash_squash in H12.\n  case_eq (unsquash m0); intros.\n  rewrite H14 in H12; auto.\n  destruct H12; simpl; subst; auto.\n  eapply H11; eauto.\n  simpl.\n  assert (mtype_valid (l,v) (m,v0)).\n  apply pred_nec_hereditary with a'0; auto.\n  apply rt_trans with a'1; auto.\n  apply Rt_Rft; auto.\n  hnf in H10.\n  rewrite H4 in H10.\n  spec H10 a.\n  cbv beta zeta in H10.\n  rewrite H9 in H10.\n  simpl in H10.\n  apply beq_nat_false in H8.\n  omega.\n\n  exists (squash (n,f'),v0).\n  split; auto.\n  split; auto.\n  change (Loc l) with (val_to_exp (v_Loc l)).\n  apply forces2exprType.\n  rewrite ty_ref_extends.\n  exists l; split.\n  simpl; auto.\n  simpl.\n  rewrite unsquash_squash.\n  unfold f'. simpl.\n  case_eq (beq_nat l l); simpl; intros.\n  hnf.\n  unfold fidentity_fmap.\n  change (approx n (approx n tau)) with ((approx n oo approx n) tau).\n  rewrite <- (approx_approx1 0).\n  auto.\n  apply beq_nat_false in H9; elim H9; auto.\n\n  simpl in H4.\n  elim H4.\n  case_eq (new b (exp_to_val x i)); intros.\n  exists m; exists (Loc a).\n  apply st_New2 with i; auto.\nQed.\n\nLemma expr_type_upd_Update: forall tau sigma w l v e3 v0,\n  forces w (v_Loc l) (ty_ref tau) ->\n  forces w v (%tau) ->\n  expr_type e3 sigma (w,v0) ->\n  expr_type (Update (Loc l) (val_to_exp v) e3) sigma (w,v0).\nProof.\n  intros.\n  rewrite expr_type_eqn; repeat intro.\n  split; repeat intro.\n  simpl in H6.\n  inv H6.\n  inv H9.\n  assert (stopped b (val_to_exp v)).\n  apply values_stopped.\n  destruct v; auto.\n  elim H6; eauto.\n  exists a'2.\n  split.\n  simpl; apply R_extends_refl.\n  split; auto.\n  eapply pred_nec_hereditary in H4.\n  2: instantiate (1:=a'2).\n  2: apply rt_trans with a'1; auto.\n  2: apply Rt_Rft; auto.\n  destruct a'2.\n  simpl in H4.\n  simpl.\n  case_eq (unsquash m); intros.\n  rewrite H6 in H4.\n  spec H4 a.\n  revert H4.\n  generalize (refl_equal (f a)).\n  case_eq (f a); intros.\n  rewrite exp_to_val_to_exp.\n  unfold update.\n  destruct b.\n  simpl.\n  simpl in H9.\n  destruct H9; split; auto.\n  case_eq (beq_nat l a); intro; auto.\n  apply beq_nat_true in H11; subst a.\n  hnf in H.\n  destruct H.\n  destruct H.\n  simpl in H; inv H.\n  cut (type_at x tau (m,v_Loc x)).\n  intro.\n  simpl in H.\n  rewrite H6 in H.\n  rewrite H4 in H.\n  cut ((%tau) (m,v)); intros.\n  spec H12 a'2 H13.\n  eapply pred_nec_hereditary in H12.\n  2: apply rt_trans with a'3; auto.\n  2: apply Rt_Rft; auto.\n  cut (approx n tau a'3).\n  hnf in H.\n  rewrite <- H.\n  intros.\n  red in H15. rewrite approx_spec in H15.\n  destruct H15; auto.\n  red. rewrite approx_spec.\n  split; auto.\n  apply lt_le_trans with (level a'2).\n  apply laterR_level.\n  apply Rt_Rft_trans with a'3; auto.\n  destruct a'2.\n  destruct H13; subst.\n  simpl.\n  rewrite knot_level.\n  case_eq (unsquash m0); intros.\n  hnf in H13.\n  rewrite H6 in H13.\n  rewrite H15 in H13.\n  destruct H13; subst; simpl; auto.\n  red in H0.\n  assert ((%tau) (fst a',v)).\n  rewrite <- box_refl_trans in H0; auto.\n  spec H0 (fst a',v).\n  spec H0.\n  split; auto.\n  destruct a'; destruct H2; auto.\n  auto.\n  apply pred_nec_hereditary with (fst a', v); auto.\n  rewrite value_knot_necR; split; auto.\n  assert (necR a' (m,v1)).\n  apply rt_trans with a'0; auto.\n  apply rt_trans with a'1; auto.\n  apply Rt_Rft; auto.\n  destruct a'.\n  rewrite value_knot_necR in H13.\n  simpl; destruct H13; auto.\n  rewrite <- type_at_extends in H11.\n  spec H11 (fst a', v_Loc x).\n  spec H11.\n  split; auto.\n  destruct a'; destruct H2; auto.\n  eapply pred_nec_hereditary.\n  2: apply H11.\n  rewrite value_knot_necR; split; auto.\n  assert (necR a' (m,v1)).\n  apply rt_trans with a'0; auto.\n  apply rt_trans with a'1; auto.\n  apply Rt_Rft; auto.\n  destruct a'.\n  rewrite value_knot_necR in H.\n  destruct H; simpl; auto.\n  unfold update; destruct b; simpl; auto.\n  rewrite <- expr_type_extends in H1.\n  spec H1 a' H2.\n  eapply pred_nec_hereditary.\n  2: apply H1.\n  apply rt_trans with a'; auto.\n  apply rt_trans with a'0; auto.\n  apply rt_trans with a'1; auto.\n  apply Rt_Rft; auto.\n  simpl in H6.\n  elim H6.\n  exists (update b l v).\n  exists e3.\n  destruct v.\n  apply st_Upd3 with i; auto.\nQed.\n\n\nLemma expr_ty_deref_loc : forall l tau a,\n  expr_type (Loc l) (ty_ref tau) a ->\n  expr_type (Deref (Loc l)) tau a.\nProof.\n  intros.\n  rewrite expr_type_eqn; repeat intro.\n  split; repeat intro.\n  simpl in H4.\n  inv H4.\n  inv H7.\n  exists a'2.\n  split.\n  simpl; apply R_extends_refl.\n  split.\n  apply pred_nec_hereditary with a'0; auto.\n  apply rt_trans with a'1; auto.\n  apply Rt_Rft; auto.\n  rewrite <- expr_type_extends in H.\n  spec H a' H0.\n  eapply pred_nec_hereditary in H.\n  2: instantiate (1:=a'1).\n  2: apply rt_trans with a'0; auto.\n  assert (forces (fst a'1) (exp_to_val (Loc l) (isvLoc l)) (%(ty_ref tau))).\n  destruct a'1.\n  eapply exprType_value.\n  2: apply H.\n  unfold fst.\n  red.\n  apply pred_nec_hereditary with a'0; auto.\n  apply H2.\n  rewrite ty_ref_extends in H4.\n  destruct a'1.\n  destruct H4 as [l' [? ?]].\n  simpl in H4; inv H4.\n  simpl fst in H6.\n  assert (mtype_valid b0 (m,v)).\n  apply pred_nec_hereditary with a'0; auto.\n  simpl in H6.\n  hnf in H4.\n  cbv beta zeta in H4.\n  case_eq (unsquash m); intros;\n    rewrite H7 in H4, H6.\n  spec H4 l'.\n  case_eq (f l'); intros.\n  rewrite H8 in H4, H6.\n  destruct H4.\n  destruct a'2.\n  eapply forces2exprType.\n  rewrite later_commute in H9.\n  spec H9 (m0,deref b0 l').\n  detach H9.\n  repeat intro.\n  spec H9 a'1 H10.\n  cut (approx n p a'1); intros.\n  hnf in H6.\n  rewrite H6 in H11.\n  red in H11. rewrite approx_spec in H11.\n  destruct H11; auto.\n  red. rewrite approx_spec.\n  split; auto.\n  change (level a'1 < n).\n  apply le_lt_trans with (level (m0,v0)).\n  destruct a'1; destruct H10.\n  simpl.\n  hnf in H10.\n  repeat rewrite knot_level.\n  destruct (unsquash m0); destruct (unsquash m1).\n  destruct H10; subst; auto.\n  apply lt_le_trans with (level (m,v)).\n  apply laterR_level; auto.\n  simpl.\n  rewrite knot_level.\n  rewrite H7; simpl; auto.\n  simpl in H5; rewrite value_knot_laterR in H5.\n  destruct H5; subst.\n\n  simpl; rewrite value_knot_laterR; split; auto.\n  rewrite H8 in H6, H4.\n  elim H6.\n  simpl in H4.\n  elim H4.\n  exists b.\n  exists (val_to_exp (deref b l)).\n  apply st_Deref2; auto.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/examples/lam_ref/lam_ref_type_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.24638902670073717}}
{"text": "Require Import Cosa.Lib.Header.\nRequire Import Cosa.Abstract.Valuation.\nRequire Import Cosa.Nominal.Set.\nRequire Import Cosa.Nominal.CompcertInstances.\nRequire Import Coq.Classes.EquivDec.\nRequire Cminor.\n\n(** An abstract notion of expression. The type [expr] is a variant of\n    [Cminor.expr] where the variables are taken to be at an arbitrary\n    type rather than a type of identifier. They will be instantiated\n    with [Graph.node]. Most of the evaluation relation is reused from\n    [Cminor].*)\n\nSection Expr.\n\n  Context {var:Type} {nominal_var:Action var}.\n\n  Inductive expr :=\n  | Avar : var -> expr\n  | Aconst : Cminor.constant -> expr\n  | Aunop : Cminor.unary_operation -> expr -> expr\n  | Abinop : Cminor.binary_operation -> expr -> expr -> expr\n  | Aload : AST.memory_chunk -> expr -> expr\n  .\n\n\n  Global Program Instance action_expr : Action expr := {|\n    act π := (fix act e :=\n      match e return _ with\n      | Avar v => Avar (π·v)\n      | Aconst c => Aconst c\n      | Aunop op e => Aunop op (act e)\n      | Abinop op e₁ e₂ => Abinop op (act e₁) (act e₂)\n      | Aload c e => Aload c (act e)\n      end)\n  |}.\n  Next Obligation.\n    autounfold.\n    intros π₁ π₂ hπ e e' <-.\n    induction e; (congruence||now rewrite hπ).\n  Qed.\n  Next Obligation.\n    (* [x] should not have been introduced *)\n    revert x.\n    (* / *)\n    intros e.\n    induction e; (congruence||now rewrite act_id).\n  Qed.\n  Next Obligation.\n    (* [x] should not have been introduced *)\n    revert x.\n    (* / *)\n    intros e.\n    induction e; (congruence||now rewrite act_comp).\n  Qed.\n\n  (** Evaluation is parametrised by an environment for the\n      variables. And a read relation for loads.\n\n      [reads chunk vaddr v] holds if reading chunk [chunk] at the\n      memory address corresponding to value [vaddr] yields [v]. *)\n  (* spiwack: I use a function [var->Values.val] as my environment\n     because it's what is useful for abstract interpretation. However,\n     we could use a relation [var->Values.val->Prop] and hence be\n     more compatible with [Cminor]'s expressions. *)\n  Variable (env:var -> Values.val)\n           (reads:AST.memory_chunk -> Values.val -> Values.val->Prop).\n\n  Inductive eval_expr : expr -> Values.val -> Prop :=\n  | eval_Avar : forall α, eval_expr (Avar α) (env α)\n  | eval_Aconst : forall cst v sp (ge:Cminor.genv),\n             Cminor.eval_constant ge sp cst = Some v ->\n             eval_expr (Aconst cst) v\n    (** For the moment, we ignore Oaddrsymbol (which calls to the\n        global environment) and Oaddrstack (which points to the top of\n        the local stack-frame). *)\n  | eval_Aunop : forall op a1 v1 v,\n      eval_expr a1 v1 ->\n      Cminor.eval_unop op v1 = Some v ->\n      eval_expr (Aunop op a1) v\n  | eval_Abinop: forall op a1 a2 v1 v2 v m,\n      eval_expr a1 v1 ->\n      eval_expr a2 v2 ->\n      Cminor.eval_binop op v1 v2 m = Some v ->\n      eval_expr (Abinop op a1 a2) v\n    (** For the moment, we ignore unsigned comparison of pointers, which requires\n        some access to memory. *)\n  | eval_Aload: forall chunk addr vaddr v,\n      eval_expr addr vaddr ->\n      reads chunk vaddr v ->\n      eval_expr (Aload chunk addr) v\n  .\n\nEnd Expr.\n\nArguments expr var : clear implicits.\n\nLtac apply_hyps :=\n  repeat match goal with\n  | H:_|-_ => eapply H\n  end\n.\n\nLtac equivariant_eval_expr_tac :=\n  simpl; intros h; inversion_clear h; econstructor; apply_hyps\n.\n\nLemma equivariant_eval_expr var `(Action var) : Equivariant (@eval_expr var).\nProof.\n  apply equivariant_alt₄.\n  intros π env read e v.\n  assert ( forall π env read e v,  eval_expr (π · env) (π · read) (π · e) (π · v) -> eval_expr env read e v ) as h.\n  { clear. intros π env read e.\n    induction e; intros ?; [|equivariant_eval_expr_tac..].\n    intros h; inversion h. simpl in *. simplify_act. subst.\n    econstructor. }\n  apply prop_extensionality.\n  split.\n  + apply h.\n  + intros r.\n    apply (h (op_p π)). simplify_act.\n    exact r.\nQed.\n(* Hint EResolve equivariant_eval_expr : equivariant. *)\nHint Extern 0 (Equivariant eval_expr) => eapply equivariant_eval_expr : equivariant.\n\nLemma eval_expr_increasing var (env:var->Values.val) :\n  forall (reads₁ reads₂:_->_->_->Prop),\n  (forall chunk vaddr v, reads₁ chunk vaddr v -> reads₂ chunk vaddr v) ->\n  forall e v, eval_expr env reads₁ e v -> eval_expr env reads₂ e v.\nProof.\n  intros * h *.\n  induction 1; try (econstructor (solve[eauto])).\nQed.\n\n(** Evaluation of pure expressions: ignores [Aload] expressions. *)\nDefinition eval_pure_expr {var} env e v :=\n  eval_expr (var:=var) env (fun _ _ _ => True) e v\n.\n\nLemma equivariant_eval_pure_expr var `(Action var) :\n  Equivariant (@eval_pure_expr var).\nProof.\n  unfold eval_pure_expr.\n  combinatorize.\n  narrow_equivariant.\n  + easy.\nQed.\n(* Hint EResolve equivariant_eval_pure_expr : equivariant. *)\nHint Extern 0 (Equivariant eval_pure_expr) => eapply equivariant_eval_pure_expr : equivariant.\n\n\n(** Pure expressions as assertions. *)\nDefinition check_pure_expr {var} env e b :=\n  eval_pure_expr (var:=var) env e (Values.Val.of_bool b)\n.\n\nLemma equivariant_check_pure_expr var `(Action var) :\n  Equivariant (@check_pure_expr var).\nProof.\n  unfold check_pure_expr.\n  combinatorize.\n  narrow_equivariant.\n  + easy.\nQed.\n(* Hint EResolve equivariant_check_pure_expr : equivariant. *)\nHint Extern 0 (Equivariant check_pure_expr) => eapply equivariant_check_pure_expr : equivariant.\n\nDefinition valid_pure_expr {var} env e b :=\n  check_pure_expr (var:=var) env e b /\\ ~(check_pure_expr env e (negb b))\n.\n\nLemma equivariant_valid_pure_expr var `(Action var) :\n  Equivariant (@valid_pure_expr var).\nProof.\n  unfold valid_pure_expr.\n  combinatorize.\n  Time narrow_equivariant; easy.\nQed.\n(* Hint EResolve equivariant_valid_pure_expr : equivariant. *)\nHint Extern 0 (Equivariant valid_pure_expr) => eapply equivariant_valid_pure_expr : equivariant.\n\n(** Substitution. *)\nFixpoint subs {A B} (φ:A->B) (e:expr A) : expr B :=\n  match e with\n  | Avar v => Avar (φ v)\n  | Aconst c => Aconst c\n  | Aunop op e => Aunop op (subs φ e)\n  | Abinop op e₁ e₂ => Abinop op (subs φ e₁) (subs φ e₂)\n  | Aload chunk e => Aload chunk (subs φ e)\n  end\n.\n\nFixpoint collect {F} (a:Applicative F) {A} (e:expr (F A)) : F (expr A) :=\n  match e with\n  | Avar v => a.(map) Avar v\n  | Aconst c => pure a (Aconst c)\n  | Aunop op e => a.(map) (Aunop op) (collect a e)\n  | Abinop op e₁ e₂ => map2 a (Abinop op) (collect a e₁) (collect a e₂)\n  | Aload chunk e => a.(map) (Aload chunk) (collect a e)\n  end\n.\n\n(** Partial renaming. *)\nDefinition rename {A B} (φ:A->option B) (e:expr A) : option (expr B) :=\n  collect Option (subs φ e)\n.\n(* arnaud: not needed?\n(* arnaud: belongs_to_expr can actually be defined in term of [collect], using\n   the writer applicative and a list. *)\nFixpoint belongs_to_expr {A} (e:expr A) (x:A) : Prop :=\n  match e with\n  | Avar v => x=v\n  | Aconst _ => False\n  | Aunop _ e => belongs_to_expr e x\n  | Abinop _ e₁ e₂ => belongs_to_expr e₁ x \\/ belongs_to_expr e₂ x\n  | Aload _ e => belongs_to_expr e x\n  end\n.\n\nLemma value_not_fixed_eval_pure_expr A {_:EqDec A eq} (e:expr A) v :\n  central (belongs_to_expr e)\n          (fun ρ => eval_pure_expr ρ e v).\nProof.\n  unfold central; revert v.\n  induction e as [ x | c | op e he | op e₁ he₁ e₂ he₂ | chunk e he ]; simpl.\n  - intros ** ν h.\n    inversion h; subst; clear h.\n    assert (ν x = swap α β ν x) as ->.\n    { unfold swap.\n      rewrite !if_eq_neq; congruence. }\n    constructor.\n  - intros ** h.\n    inversion h; subst; clear h.\n    econstructor; eauto.\n  - intros ** h.\n    inversion h; subst; clear h.\n    econstructor; eauto.\n    now apply he.\n  - intros v α β hα hβ ** h.\n    inversion h; subst; clear h.\n    econstructor; eauto; [apply he₁|apply he₂]; solve[easy|clear -hα hβ; firstorder].\n  - intros ** h.\n    inversion h; subst; clear h.\n    econstructor; eauto.\n    eapply he; eauto.\nQed.\n\nLemma value_not_fixed_check_pure_expr A {_:EqDec A eq} (e:expr A) b :\n  central (belongs_to_expr e)\n          (fun ρ => check_pure_expr ρ e b).\nProof.\n  apply value_not_fixed_eval_pure_expr.\nQed.\n\nLemma value_not_fixed_valid_pure_expr A {_:EqDec A eq} (e:expr A) b :\n  central (belongs_to_expr e)\n          (fun ρ => valid_pure_expr ρ e b).\nProof.\n  unfold central, valid_pure_expr.\n  intros ** [h₁ h₂].\n  split.\n  - apply value_not_fixed_check_pure_expr; eauto.\n  - intros h₃; apply h₂.\n    assert (ν = swap α β (swap α β ν)) as h₄.\n    { extensionality x.\n      now rewrite swap_idempotent. }\n    rewrite h₄.\n    apply value_not_fixed_check_pure_expr; eauto.\nQed. *)", "meta": {"author": "aspiwack", "repo": "cosa", "sha": "2d808236e71f2289033dff6b74a3f57311df9a14", "save_path": "github-repos/coq/aspiwack-cosa", "path": "github-repos/coq/aspiwack-cosa/cosa-2d808236e71f2289033dff6b74a3f57311df9a14/Abstract/Lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.24638902670073712}}
{"text": "(* Singly linked list *)\n\nFrom iris.base_logic.lib Require Export wsat.\nFrom iris_c.clang Require Import logic tactics notations.\nFrom iris_c.lib Require Import gmap_solve int.\n\nSection proof.\n  Context `{clangG Σ}.\n\n  Definition tcell (t: type): type := Tprod t (Tptr Tvoid).\n\n  Fixpoint isList (l: val) (xs: list val) (t: type) :=\n    match xs with\n      | [] => (⌜ l = null ⌝)%I\n      | x::xs' => (∃ p l',\n                     ⌜ l = Vptr p ∧ typeof x t ∧ typeof l' (Tptr (tcell t)) ⌝ ∗\n                     p ↦ Vpair x l' @ tcell t ∗ isList l' xs' t)%I\n    end.\n\n  Fixpoint isListSeg (l lt lt2: val) (x: val) (xs: list val) (t: type) :=\n    match xs with\n      | [] => (∃ p, ⌜ l = Vptr p ∧ l = lt ∧ typeof x t⌝ ∗ p ↦ Vpair x lt2 @ tcell t)%I\n      | x'::xs' => (∃ p l',\n                     ⌜ l = Vptr p ∧ typeof x t ∧ typeof l' (Tptr (tcell t)) ⌝ ∗\n                     p ↦ Vpair x l' @ tcell t ∗ isListSeg l' lt lt2 x' xs' t)%I\n    end.\n\n  Lemma isList_ptr (l: val) (xs: list val) (t: type) :\n    isList l xs t ⊢ ⌜ typeof l (Tptr Tvoid) ⌝.\n  Proof.\n    destruct xs as [|x xs'].\n    - iIntros \"%\". iPureIntro. by subst.\n    - simpl. iIntros \"H\".\n      iDestruct \"H\" as (??) \"(% & ? & _)\".\n      by destruct_ands.\n  Qed.\n\n  Lemma isList_ptr' (l: val) (xs: list val) (t: type) :\n    isList l xs t ⊢ ⌜ typeof l (Tptr (tcell t)) ⌝.\n  Proof.\n    destruct xs as [|x xs'].\n    - iIntros \"%\". iPureIntro. by subst.\n    - simpl. iIntros \"H\".\n      iDestruct \"H\" as (??) \"(% & ? & _)\".\n      by destruct_ands.\n  Qed.\n\n  Notation \"'Tlist'\" := (Tptr (tcell Tint8)).\n\n  Definition rev_list : expr :=\n    while: ( (!\"x\"@Tlist) != null ) (\n      \"t\" <- snd (!(!\"x\"@Tlist)@(tcell Tint8)) ;;\n      (!\"x\"@Tlist) + 1 <- !\"y\"@Tlist ;;\n      \"y\" <- !\"x\"@Tlist ;;\n      \"x\" <- !\"t\"@Tlist\n    ) ;;\n    return: !\"y\"@Tlist.\n\n  Definition traverse_list (lx: val) : expr :=\n    while: (!lx@Tlist != null) ( lx <- snd (!(!lx@Tlist)@(tcell Tint8)) ).\n\n  Lemma traverse_spec Φ lx xs: ∀ l,\n    lx ↦ l @ Tlist ∗ isList l xs Tint8 ∗ (isList l xs Tint8 -∗ Φ void)\n    ⊢ WP (traverse_list lx, ([], semp)) {{ v, Φ v }}.\n  Proof.\n    induction xs as [|x xs' IHxs'].\n    - iIntros (l) \"[? [% HΦ]]\".\n      rewrite /traverse_list. subst.\n      iApply (wp_while [] []).\n      repeat wp_step.\n      iApply (wp_break [] []).\n      simpl. iApply wp_value=>//.\n      by iApply \"HΦ\".\n    - iIntros (l) \"[Hlx [Hl HΦ]]\".\n      simpl. iDestruct \"Hl\" as (p l') \"[% [Hp Hl']]\".\n      destruct_ands.\n      rewrite /traverse_list.\n      iApply (wp_while [] []).\n      do 10 wp_step.\n      iApply (wp_continue [] []).\n      iApply IHxs'. iFrame. iIntros \"?\".\n      iApply \"HΦ\". iExists _, _. by iFrame.\n  Qed.\n\n  Lemma lseg_snoc' v:\n    typeof v Tint8 →\n    ∀ xs x p p' (p'': addr) l'',\n      typeof l'' Tlist →\n      isListSeg p p' p'' x xs Tint8 ∗ p'' ↦ Vpair v l'' @ tcell Tint8\n       ⊢ isListSeg p p'' l'' x (xs ++ [v]) Tint8.\n  Proof.\n    intros ?.\n    induction xs as [|x' xs' IHxs']; iIntros (x p p' p'' l'' ?) \"[Hl Hv]\"; simpl.\n    - iDestruct \"Hl\" as (p''') \"[% ?]\". destruct_ands.\n      iExists p''', p''. iSplit=>//. iFrame.\n      iExists _. iFrame. done.\n    - iDestruct \"Hl\" as (p''' l') \"[% [? ?]]\". destruct_ands.\n      specialize (IHxs' x' l' p' p'' l'').\n      iDestruct (IHxs' with \"[~1 Hv]\") as \"?\"=>//; first iFrame.\n      iExists _, _. iFrame. done.\n  Qed.\n\n  Lemma lseg_snoc v xs x p p' (p'': addr) l'':\n    typeof v Tint8 → typeof l'' Tlist →\n    isListSeg p p' p'' x xs Tint8 ∗ p'' ↦ Vpair v l'' @ tcell Tint8\n    ⊢ isListSeg p p'' l'' x (xs ++ [v]) Tint8.\n  Proof. iIntros (??) \"?\". iApply lseg_snoc'=>//. Qed.\n\n  Lemma lseg_unsnoc: ∀ xs p (p': addr) x,\n    isListSeg p p' null x xs Tint8 ⊢\n    (∃ (x': val) xs' p'', isListSeg p p'' p' x xs' Tint8 ∗\n     p' ↦ Vpair x' null @ tcell Tint8 ∗ ⌜ xs = xs' ++ [x'] ⌝ ) ∨\n    (⌜ p = p' ∧ xs = [] ⌝ ∗ p' ↦ Vpair x null @ tcell Tint8).\n  Proof.\n    induction xs as [|x' xs' IHxs'].\n    - iIntros (???) \"H\". simpl. iDestruct \"H\" as (?) \"[% ?]\". destruct_ands.\n      iRight. simplify_eq. by iFrame.\n    - iIntros (???) \"H\". simpl. iDestruct \"H\" as (??) \"[% [? ?]]\". destruct_ands.\n      iDestruct (IHxs' with \"~1\") as \"[?|[% ?]]\".\n      + iLeft. iDestruct \"~2\" as (???) \"[? [? %]]\". iExists H2. iFrame.\n        subst. iExists (x'::H5). iExists _.\n        iSplit=>//. simpl. iExists _, _.\n        iFrame. done.\n      + destruct_ands. iLeft. iExists x'. iFrame.\n        iExists [], H0. iSplit=>//. simpl. iExists _.\n        iSplit=>//.\n  Qed.\n\n  Lemma lseg_to_list xs: ∀ p p' x,\n    isListSeg p p' null x xs Tint8 ⊢ isList p (x::xs) Tint8.\n  Proof.\n    induction xs as [|x' xs' IHxs'].\n    - iDestruct 1 as (?) \"[% ?]\". destruct_ands.\n      iExists _, _. iFrame. iSplit=>//.\n    - simpl. iDestruct 1 as (??) \"[% [? ?]]\". destruct_ands.\n      iDestruct (IHxs' with \"~\") as \"?\".\n      iExists _, _. iFrame. iSplit=>//.\n  Qed.\n\n  Definition enq_env pt pt': env :=\n    (sset \"lt'\" (Tlist, Vptr pt')\n          (sset \"lt\" (Tptr Tlist, Vptr pt)\n                semp)).\n\n  Lemma enq_spec' lx (p: addr) Φ x xs k: ∀ xs2 xs1 pt pt' (p': addr) l',\n    typeof l' Tlist → typeof p Tlist →\n    lx ↦ p @ Tlist ∗ pt ↦ p' @ Tlist ∗ pt' ↦ l' @ Tlist ∗\n    isListSeg p p' l' x xs1 Tint8 ∗ isList l' xs2 Tint8 ∗ ⌜ xs = xs1 ++ xs2 ⌝ ∗\n    (∀ p': addr, lx ↦ p @ Tlist -∗ pt ↦ p' @ Tlist -∗\n                 isListSeg p p' null x xs Tint8 -∗\n                 pt' ↦ null @ Tlist -∗\n                 WP (fill_ectxs void k, ([], enq_env pt pt')) {{ Φ }})\n    ⊢ WP (fill_ectxs (while: (! \"lt'\" @ Tlist != null) (\n            \"lt\" <- ! \"lt'\" @ Tlist ;; \"lt'\" <- snd ! ! \"lt'\" @ Tlist @ (tcell Tint8)\n          )) k, ([], enq_env pt pt')) {{ Φ }}.\n  Proof.\n    induction xs2 as [|x' xs2' IHxs'];\n      iIntros (???????) \"(Hlx&Hpt&Hpt'&Hxs1&Hxs2&%&HΦ)\".\n    - iDestruct \"Hxs2\" as \"%\". subst.\n      iApply wp_while. iNext. wp_run.\n      rewrite (right_id_L _ (++)).\n      iApply (wp_break _ []). simpl.\n      by iSpecialize (\"HΦ\" $! p' with \"Hlx Hpt Hxs1 Hpt'\").\n    - simpl. iDestruct \"Hxs2\" as (p'' l'') \"[% [? ?]]\". destruct_ands.\n      iApply wp_while. iNext.\n      wp_run. iApply (wp_continue _ []).\n      iApply (IHxs' (xs1 ++ [x'])); last iFrame; auto.\n      iSplitL.\n      { iApply lseg_snoc=>//. iFrame. }\n      { by rewrite -assoc. }\n  Qed.\n\n  Definition enq_list (lx: val) (v: val) : expr :=\n    \"lt\" <- !lx @ Tlist ;;\n    if: ((!\"lt\"@Tlist) != null) then: (\n      \"lt'\" <- snd (!(!\"lt\"@Tlist)@(tcell Tint8)) ;;\n      while: ((!\"lt'\"@Tlist) != null) (\n        \"lt\" <- !\"lt'\"@Tlist;;\n        \"lt'\" <- snd (!(!\"lt'\"@Tlist)@(tcell Tint8))\n      ) ;;\n      (!\"lt\"@Tlist) + 1 <- Ealloc (tcell Tint8) (Vpair v null)\n    ) else: (\n      lx <- Ealloc (tcell Tint8) (Vpair v null)\n    ).\n\n  Lemma enq_spec Φ lx lt lt' xs v: typeof v Tint8 → ∀ l,\n    lt' ↦ null @ Tlist ∗ lt ↦ null @ Tlist ∗\n    lx ↦ l @ Tlist ∗ isList l xs Tint8 ∗\n    (∀ l', (lx ↦ l' @ Tlist) -∗ (isList l' (xs ++ [v]) Tint8) -∗ Φ void)\n    ⊢ WP (enq_list lx v, ([], enq_env lt lt')) {{ v, Φ v }}.\n  Proof.\n    intros ?. rewrite /enq_list. subst.\n    iIntros (l) \"(Ht' & Ht & Hlx & Hl & HΦ)\".\n    iDestruct (mapsto_typeof with \"Hlx\") as \"%\". wp_var.\n    destruct xs as [|x xs'] eqn:?; subst; simpl.\n    - iDestruct \"Hl\" as \"%\". subst. wp_run.\n      wp_alloc x as \"Hx\"=>//.\n      wp_assign. iApply (\"HΦ\" with \"[-Hx]\")=>//.\n      iExists _, _. iFrame. iSplit=>//.\n    - simpl. iDestruct \"Hl\" as (p l') \"[% [? ?]]\".\n      destruct_ands. wp_run.\n      wp_unfill (Ewhile _ _).\n      iApply (enq_spec' lx p _ x _ _ _ [] lt lt' p l'); last iFrame; auto.\n      iSplitL \"~\"=>//.\n      { simpl. iExists _. iSplit=>//. }\n      iSplit=>//. iIntros (?) \"? ? ? ?\". destruct a. simpl.\n      wp_run. rewrite_byte. replace (Z.to_nat 1) with 1%nat=>//.\n      iDestruct (lseg_unsnoc with \"~2\") as \"[H|[% Hp]]\".\n      + iDestruct \"H\" as (???) \"[Hl [Hp %]]\". destruct_ands.\n        iDestruct (mapstoval_split with \"Hp\") as \"[Hp1 Hp2]\". simpl.\n        wp_alloc lp' as \"Hlp'\"=>//.\n        wp_assign. iApply (\"HΦ\" with \"~\").\n        iDestruct (mapsto_typeof with \"Hp1\") as \"%\".\n        iDestruct (mapstoval_join with \"[Hp1 Hp2]\") as \"Hp\"; first by iSplitL \"Hp1\".\n        iDestruct (lseg_snoc with \"[Hl Hp]\") as \"Hl'\"; try iFrame; auto.\n        iDestruct (lseg_snoc with \"[Hl' Hlp']\") as \"Hl''\"; try iFrame; auto.\n        iDestruct (lseg_to_list with \"Hl''\") as \"Hl''\".\n        simpl. iDestruct \"Hl''\" as (??) \"[% [? ?]]\". destruct_ands.\n        iExists _, _. iFrame. done.\n      + destruct_ands.\n        iDestruct (mapstoval_split with \"Hp\") as \"[Hp1 Hp2]\". simpl.\n        wp_alloc lp' as \"Hlp'\"=>//. wp_assign.\n        iApply (\"HΦ\" with \"~\").\n        iDestruct (mapstoval_join with \"[Hp1 Hp2]\") as \"Hp\"; first by iSplitL \"Hp1\".\n        iExists _, _. iFrame. iSplit=>//.\n        iExists _, _. iFrame. iSplit=>//.\n  Qed.\n\n  Definition rev_env px py pt : env :=\n    sset \"x\" (Tptr Tlist, Vptr px)\n         (sset \"y\" (Tptr Tlist, Vptr py)\n               (sset \"t\" (Tptr Tlist, Vptr pt) semp)).\n\n  Lemma rev_spec' (f: ident) k ks Φ px py pt xs:\n    ∀ lx ly ys,\n      isList lx xs Tint8 ∗\n      isList ly ys Tint8 ∗\n      px ↦ lx @ Tlist ∗\n      py ↦ ly @ Tlist ∗\n      pt ↦ - @ Tlist ∗\n      (∀ ly' : val, py ↦ ly' @ Tlist ∗\n                    isList ly' (rev xs ++ ys) Tint8 -∗\n                    WP (fill_ectxs void k, (ks, rev_env px py pt)) {{ Φ }})\n      ⊢ WP (fill_ectxs (while: (! \"x\" @ Tlist != null) (\n             \"t\" <- snd ! ! \"x\" @ Tlist @ (tcell Tint8) ;;\n             ! \"x\" @ Tlist + (Byte.repr 1) <- ! \"y\" @ Tlist ;;\n             \"y\" <- ! \"x\" @ Tlist ;;\n             \"x\" <- ! \"t\" @ Tlist )) k, (ks, rev_env px py pt)) {{ v, Φ v }}.\n  Proof.\n    induction xs as [|x xs' IHxs']; intros ??? ; subst.\n    - iIntros \"(Hlx & Hly & Hpx & Hpy & Hpt & HΦ)\".\n      iDestruct \"Hlx\" as \"%\". subst. \n      iApply wp_while. iNext.\n      wp_run. iApply (wp_break _ []).\n      iApply (\"HΦ\" with \"[-]\")=>//. iFrame.\n    - iIntros \"(Hlx & Hly & Hpx & Hpy & Hpt & HΦ)\".\n      iDestruct \"Hlx\" as (p l') \"(% & Hp & Hl')\".\n      destruct H0 as [? [? ?]]. subst.\n      iDestruct \"Hpt\" as (?) \"Hpt\".\n      destruct p as [pb po].\n      iDestruct (isList_ptr with \"Hly\") as \"%\".\n      iApply wp_while. iNext. wp_run.\n      rewrite_byte. replace (Z.to_nat 1) with 1%nat; last done.\n      iDestruct (mapstoval_split with \"Hp\") as \"[Hp1 Hp2]\". simpl.\n      wp_run. iApply (wp_continue _ []).\n      iApply (IHxs' l' (Vptr (pb, po)) (x::ys)).\n      iFrame. iDestruct (mapstoval_join with \"[Hp1 Hp2]\") as \"Hp\".\n      { iSplitL \"Hp1\"; by simpl. }\n      iSplitL \"Hp Hly\".\n      { iExists (pb, po), ly. iFrame.\n        iPureIntro. split; [|split]=>//. by eapply typeof_any_ptr. }\n      rewrite -app_assoc. iFrame. by iExists _.\n  Qed.\n\n  Definition ps :=\n    [ (\"x\", Tptr Tlist); (\"y\", Tptr Tlist); (\"t\", Tptr Tlist) ].\n\n  Lemma rev_spec pt k ks Φ xs:\n    ∀ lx ly ys,\n      \"rev\" T↦ Function Tvoid ps rev_list ∗\n      isList lx xs Tint8 ∗ isList ly ys Tint8 ∗\n      pt ↦ - @ Tlist ∗\n      (∀ ly', isList ly' (rev xs ++ ys) Tint8 -∗ WP (fill_ectxs ly' k, ks) {{ Φ }})\n      ⊢ WP (fill_ectxs (Ecall Tvoid \"rev\"\n                              (Epair (Ealloc Tlist (Evalue lx))\n                                     (Epair (Ealloc Tlist (Evalue ly))\n                                            (Vpair pt void))))\n                              k, ks) {{ Φ }}.\n   Proof.\n     iIntros (???). iIntros \"(Hf & Hlx & Hly & Hpt & HΦ)\".\n     destruct ks.\n     iDestruct (wp_bind (k ++ [ EKcall Tvoid \"rev\" \n                                ; EKpairl (Epair (Ealloc Tlist ly) (Vpair pt void))])\n                        _ (Ealloc Tlist lx))\n       as \"H\"=>//.\n     assert (fill_ectxs (Ealloc Tlist lx)\n                        (k ++ [ EKcall Tvoid \"rev\";\n                                EKpairl (Epair (Ealloc Tlist ly) (Vpair pt void))]) =\n             fill_ectxs (fill_ectxs (Ealloc Tlist lx)\n                              [ EKcall Tvoid \"rev\";\n                                EKpairl (Epair (Ealloc Tlist ly) (Vpair pt void))]) k).\n     { symmetry. eapply fill_app. }\n     rewrite H0.\n     simpl. iApply \"H\".\n     iDestruct (isList_ptr' with \"Hlx\") as \"%\".\n     iDestruct (isList_ptr' with \"Hly\") as \"%\".\n     wp_alloc x as \"Hx\". iApply wp_value=>//.\n     rewrite -(fill_app x [EKcall Tvoid \"rev\";\n                       EKpairl (Epair (Ealloc Tlist ly) (Vpair pt void))] k).\n     simpl.\n     rewrite (fill_app (Ealloc Tlist ly)\n                       [EKcall Tvoid \"rev\"; EKpairr x; EKpairl (Vpair pt void) ] k).\n     iApply wp_bind=>//.\n     wp_alloc y as \"Hy\".\n     iApply wp_value=>//.\n     rewrite -(fill_app y [ EKcall Tvoid \"rev\";\n                            EKpairr x;\n                            EKpairl (Vpair pt void) ] k).\n     simpl.\n     rewrite (fill_app (Epair y (Vpair pt void))\n                       [EKcall Tvoid \"rev\"; EKpairr x] k).\n     iApply wp_bind=>//.\n     iApply wp_pair.\n     rewrite -(fill_app (Vpair y (Vpair pt void))\n                        [EKcall Tvoid \"rev\"; EKpairr x] k).\n     simpl.\n     rewrite (fill_app (Epair x (Vpair y (Vpair pt void)))\n                       [EKcall Tvoid \"rev\"] k).\n     iApply wp_bind=>//. iApply wp_pair.\n     rewrite -(fill_app (Vpair x (Vpair y (Vpair pt void)))\n                        [EKcall Tvoid \"rev\"] k).\n     simpl.\n     iApply (wp_call (rev_env x y pt) e _\n                     (Vpair x (Vpair y (Vpair pt Vvoid))) ps)=>//.\n     iFrame. iNext.\n     move: (rev_spec' \"rev\" [EKseq (return: ! \"y\" @ Tlist)]\n                      (Kcall k e :: s) Φ x y pt xs lx ly ys) => Hspec.\n     simpl in *.\n     iDestruct (Hspec with \"[-]\") as \"Hspec\"=>//.\n     { iFrame. iIntros (?).\n       iIntros \"[Hy Hl]\".\n       wp_run. by iApply \"HΦ\". }\n   Qed.\nEnd proof.\n", "meta": {"author": "izgzhen", "repo": "iris-c-coq", "sha": "ca4bbc8fd86d8c53406a371eb30d0dda64a0920e", "save_path": "github-repos/coq/izgzhen-iris-c-coq", "path": "github-repos/coq/izgzhen-iris-c-coq/iris-c-coq-ca4bbc8fd86d8c53406a371eb30d0dda64a0920e/theories/clang/lib/list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2463890267007371}}
{"text": "Require Import Coq.Lists.List\n        Coq.Strings.String\n        Coq.Logic.FunctionalExtensionality\n        Coq.Sets.Ensembles\n        Fiat.Common.ilist2\n        Fiat.Common.StringBound\n        Coq.Program.Program\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.Common.Ensembles.IndexedEnsembles\n        Fiat.QueryStructure.Specification.Representation.Notations.\n\n(* A tuple is a heterogeneous list indexed by a heading. *)\nDefinition RawTuple {heading : RawHeading} :=\n  ilist2 (B := id) (AttrList heading).\n\nDefinition Tuple {heading : Heading}\n  := @RawTuple heading.\n\n(* Always parse the heading argument in Heading scope. *)\nArguments Tuple [_%Heading].\n\n(* Notations for tuple field. *)\n\nRecord Component (Heading : Attribute) :=\n  { value : attrType Heading }.\n\nNotation \"id :: value\" :=\n  (Build_Component {| attrName := id;\n                      attrType := _ |}\n                   value) : Component_scope.\n\nBind Scope Component_scope with Component.\n\n(* Notation-friendly tuple definition. *)\nFixpoint BuildTuple\n         {n}\n         (attrs : Vector.t Attribute n)\n  : ilist2 (B := Component) attrs -> @Tuple (BuildHeading attrs) :=\n  match attrs return ilist2 (B := Component) attrs -> @Tuple (BuildHeading attrs) with\n  | Vector.nil => fun components => inil2\n  | Vector.cons attr n' attrs' =>\n    fun components =>\n      icons2 (B := id) (value (ilist2_hd components))\n            (BuildTuple attrs' (ilist2_tl components))\n  end.\n\n(* Notation\nfor tuples built from [BuildTuple]. *)\n\nNotation \"< col1 , .. , coln >\" :=\n  (@BuildTuple _ _ (icons2 col1%Component .. (icons2 coln%Component inil2) ..))\n  : Tuple_scope.\n\nDefinition GetAttributeRaw {heading}\n: @RawTuple heading -> forall attr : Attributes heading, Domain heading attr := ith2.\n\nDefinition GetAttribute {heading}\n  : @Tuple heading ->\n    forall attr : @BoundedString _ (HeadingNames heading),\n      Domain heading (ibound (indexb attr)) :=\n  fun t idx => GetAttributeRaw t (ibound (indexb idx)).\n\nNotation \"t ! R\" :=\n  (GetAttribute t%Tuple (@Build_BoundedIndex _ _ _ R%string _))\n  : Tuple_scope.\n\nDefinition SetAttributeRaw {heading}\n: @RawTuple heading ->\n  forall attr : Attributes heading,\n    Domain heading attr -> @RawTuple heading :=\n  fun tup attr dom => replace_Index2 _ tup attr dom.\n\nDefinition SetAttribute {heading}\n: @Tuple heading ->\n  forall attr : @BoundedString _ (HeadingNames heading),\n    Domain heading (ibound (indexb attr)) -> @Tuple heading :=\n  fun tup attr dom => replace_Index2 _ tup (ibound (indexb attr)) dom.\n\n(*Notation \"tup '!!' attr '<-' v \" := (SetAttribute tup (@Build_BoundedIndex _ _ _ attr%string _) v) : Tuple_scope. *)\n\nDefinition AppendTupleRaw\n           {heading1 heading2}\n           (tup1 : @RawTuple heading1)\n           (tup2 : @RawTuple heading2)\n  : @RawTuple (AppendRawHeading heading1 heading2) :=\n  ilist2_app tup1 tup2.\n\nNotation \"tup1 ++ tup2\" := (AppendTupleRaw tup1 tup2) : Tuple_scope.\n\nDefinition UpdateAttributeRaw\n           {heading}\n           (attr : Attributes heading)\n           (f : Domain heading attr -> Domain heading attr)\n           (tup : @RawTuple heading)\n  : @RawTuple heading := update_Index2 _ tup _ f.\n\nDefinition UpdateAttribute\n           {heading}\n           (tup : @Tuple heading)\n           (attr : @BoundedString _ (HeadingNames heading))\n           (f : Domain heading (ibound (indexb attr))\n                -> Domain heading (ibound (indexb attr)))\n  : @Tuple heading := UpdateAttributeRaw _ f tup.\n\nDefinition UpdateAttributes\n           {heading}\n           (tup : @Tuple heading)\n           (attrs :\n              list (@sigT (@BoundedString _ (HeadingNames heading))\n                          (fun attr => Domain heading (ibound (indexb attr))\n                                       -> Domain heading (ibound (indexb attr)))))\n  : @Tuple heading := fold_left (fun (tup' : @Tuple heading)\n                                     attr => UpdateAttribute tup' (projT1 attr) (projT2 attr)) attrs tup.\n\nClass HeadingHint := { headingHint : Heading }.\n\nNotation \"tup ○ f\" :=\n  (let H := _ in\n   let _ := {| headingHint := H |} in\n   @UpdateAttributes H tup f%Update%list) : Tuple_scope.\n\nNotation \"x !! attr / f\" :=\n  (@existT (@BoundedString _ (HeadingNames headingHint))\n           (fun attr' => Domain _ (ibound (indexb attr'))\n                        -> Domain _ (ibound (indexb attr')))\n           (@Build_BoundedIndex _ _ _ attr%string _)\n           (fun x => f)) : Update_scope.\n\nNotation \"attr ::= v\" :=\n  (@existT (@BoundedString _ (HeadingNames headingHint))\n           (fun attr' => Domain _ (ibound (indexb attr'))\n                        -> Domain _ (ibound (indexb attr')))\n           (@Build_BoundedIndex _ _ _ attr%string _)\n           (fun _ => v)) : Update_scope.\n\n(*Notation \"'UpdateTuple' tup '!' attrs \" :=\n    (UpdateAttribute tup (@Build_BoundedIndex _ _ _ attr%string _) f)\n      (tup at level 0, at level 80, attr at level 0,\n       f at level 0, no associativity) : Tuple_scope.*)\n\nSection TupleNotationExamples.\n  Local Open Scope Tuple_scope.\n\n  Definition MovieHeading : Heading := <\"title\" :: string, \"year\" :: nat>%Heading.\n  Definition GwW : Tuple := <\"title\" :: \"Gone With the Wind\"%string, \"year\" :: 1938>.\n  Definition GwW' := Eval simpl in GwW ○ [\"title\" ::= \"Gone With the Wind Part 2\"%string].\n  Definition DupleMovie : RawTuple := GwW ++ GwW'.\n\n  Definition GwW'' (tup : @Tuple MovieHeading)\n    : @Tuple MovieHeading :=\n    tup ○ [old !! \"title\" / append old \"Gone With the Wind Part 3\"%string;\n           \"year\" ::= 10].\n\nEnd TupleNotationExamples.\n(*\nNotation \"a ++= b\" := (@UpdateTuple _ {|attrName := a; attrType := string|}\n                             (fun o => Build_Component (_::_) (append (value o) b))) (at level 80).\nNotation \"a :+= b\" := (@UpdateTuple _ {|attrName := a; attrType := list _|}\n                             (fun o => Build_Component (_::_) (cons b (value o)))) (at level 80).\nNotation \"[ a ; .. ; c ]\" := (compose a .. (compose c id) ..) : Update_scope.\n\nDelimit Scope Update_scope with Update.\n*)\n\nDefinition IndexedRawTuple {heading} := @IndexedElement (@RawTuple heading).\nDefinition RawTupleIndex {heading} (I : @IndexedRawTuple heading) : nat :=\n  elementIndex I.\nDefinition indexedRawTuple {heading} (I : @IndexedRawTuple heading)\n  : @RawTuple heading := indexedElement I.\n\nDefinition IndexedTuple {heading} := @IndexedElement (@Tuple heading).\nDefinition TupleIndex {heading} (I : @IndexedTuple heading) : nat :=\n  elementIndex I.\nDefinition indexedTuple {heading} (I : @IndexedTuple heading)\n: @Tuple heading := indexedElement I.\n\nDefinition GetAttributeRawBnd {heading : Heading}\n           (tup : @RawTuple heading)\n           (idx : (BoundedIndex (HeadingNames heading)))\n  : Domain heading (ibound (indexb idx)) :=\n  GetAttributeRaw tup (ibound (indexb idx)).\n\n(* Raw tuple field accessor notation *)\nNotation \"tup '!' idx\" := (GetAttributeRaw tup ``idx) : TupleImpl_scope.\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/QueryStructure/Specification/Representation/Tuple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24638901993027698}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\n(*****************************************************************************)\n(*          Projet Coq - Calculus of Inductive Constructions V5.10           *)\n(*****************************************************************************)\n(*                                                                           *)\n(*          Category Theory : Hom (Bi-)Functors (used in Adjunctions)        *)\n(*                                                                           *)\n(*          Amokrane Saibi May 1994                                          *)\n(*                                                                           *)\n(*****************************************************************************)\n\n\nRequire Export SET.\nRequire Export Dual.\nRequire Export PROD.\nRequire Export Functor.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n(* C(-,G-) et D(F-,-) : D^o x C -> SET *)\n\n\n(* C(F-,-) *)\n\nSection FunSet2_r.\n\nVariable C D : Category.\n\n(* pour alle'ger les e'critures *)\n\n Section abrev.\n \n Definition OB_l (dxc : POb (Dual D) C) : D := Ob_l dxc.\n\n Variables (d1xc1 d2xc2 : POb (Dual D) C) (foxg : Pmor d1xc1 d2xc2).\n\n Definition HOM_l : OB_l d2xc2 --> OB_l d1xc1 := Hom_l foxg.\n\n Definition Build_POb1 (d : D) (c : C) := Build_POb (A:=Dual D) (B:=C) d c.\n\n Definition Build_Pmor1 (c c' : C) (d d' : D) (f : d' --> d)\n   (g : c --> c') := Build_Pmor (u:=Build_POb1 d c) (t:=Build_POb1 d' c') f g.\n\n End abrev.\n\n(* *)\n\nVariable F : Functor D C.\n\nDefinition FunSET2_r_ob (dxc : POb (Dual D) C) := F (OB_l dxc) --> Ob_r dxc.\n\n Section funset2_r_map_def.\n\n Variable d1xc1 d2xc2 : POb (Dual D) C.\n\n  Section funset2_r_mor_def.\n\n  Variable foxg : Pmor d1xc1 d2xc2.\n\n  Definition FunSET2_r_mor1 (h : FunSET2_r_ob d1xc1) :=\n    (FMor F (HOM_l foxg) o h) o Hom_r foxg.\n\n  Lemma FunSET2_r_map_law1 : Map_law FunSET2_r_mor1.\n  Proof.\n  unfold Map_law, FunSET2_r_mor1 in |- *; simpl in |- *.\n  intros h1 h2 H.\n  apply Comp_r; apply Comp_l; assumption.\n  Qed.\n\n  Canonical Structure FunSET2_r_mor :\n    Map (FunSET2_r_ob d1xc1) (FunSET2_r_ob d2xc2) := FunSET2_r_map_law1.\n\n  End funset2_r_mor_def.\n  \n Lemma FunSET2_r_map_law : Map_law FunSET2_r_mor.\n Proof.\n unfold Map_law, FunSET2_r_mor in |- *.\n intros f1xg1 f2xg2; elim f1xg1; intros f1 g1. \n elim f2xg2; intros f2 g2; simpl in |- *.\n unfold Ext in |- *; simpl in |- *.\n unfold Equal_Pmor in |- *; simpl in |- *.\n unfold FunSET2_r_mor1 in |- *; simpl in |- *.\n unfold FunSET2_r_ob in |- *.\n intro H; elim H; intros H1 H2 h.\n apply Comp_lr.\n apply Comp_r; trivial.\n apply FPres; assumption.\n assumption.\n Qed.\n\n Canonical Structure FunSET2_r_map := Build_Map FunSET2_r_map_law.\n\n End funset2_r_map_def.\n\nLemma Fun2_r_comp_law : Fcomp_law FunSET2_r_map.\nProof.\nunfold Fcomp_law, FunSET2_r_map in |- *; simpl in |- *.\nunfold FunSET2_r_mor, Ext in |- *; simpl in |- *.\nunfold FunSET2_r_mor1, FunSET2_r_ob in |- *; simpl in |- *.\nintros d1xc1 d2xc2 d3xc3 f1xg1 f2xg2 h.\nelim f1xg1; simpl in |- *; unfold DHom in |- *; intros f1 g1.\nelim f2xg2; simpl in |- *; unfold DHom in |- *; intros f2 g2; simpl in |- *.\n(* *) apply Trans with (((FMor F (f2 o f1) o h) o g1) o g2).\napply Ass.\napply Comp_r.\n(* *) apply Trans with ((FMor F f2 o FMor F f1 o h) o g1).\napply Comp_r.\n(* *) apply Trans with ((FMor F f2 o FMor F f1) o h).\napply Comp_r.\napply FComp.\napply Ass1.\napply Ass1.\nQed.\n\nLemma Fun2_r_id_law : Fid_law FunSET2_r_map.\nProof.\nunfold Fid_law, FunSET2_r_map, FunSET2_r_mor in |- *; simpl in |- *.\nunfold Ext, Id_SET in |- *; simpl in |- *.\nunfold FunSET2_r_mor1 in |- *; simpl in |- *.\nunfold FunSET2_r_ob in |- *; intros dxc f.\nunfold Id_fun in |- *.\n(* *) apply Trans with (FMor F (Id (OB_l dxc)) o f).\napply Idr1.\n(* *) apply Trans with (Id (F (OB_l dxc)) o f).\napply Comp_r.\napply FId.\napply Idl.\nQed.\n\nCanonical Structure FunSET2_r := Build_Functor Fun2_r_comp_law Fun2_r_id_law.\n\nEnd FunSet2_r.\n\n\nSection FunSet2_l.\n\nVariables (C D : Category) (G : Functor C D).\n\n(* D(-,G-) *)\n\nDefinition FunSET2_l_ob (dxc : POb (Dual D) C) := OB_l dxc --> G (Ob_r dxc).\n\n Section funset2_l_map_def.\n\n Variable d1xc1 d2xc2 : POb (Dual D) C.\n\n  Section funset2_l_mor_def.\n\n  Variable foxg : Pmor d1xc1 d2xc2.\n\n  Definition FunSET2_l_mor1 (h : FunSET2_l_ob d1xc1) :=\n    (HOM_l foxg o h) o FMor G (Hom_r foxg).\n\n  Lemma FunSET2_l_map_law1 : Map_law FunSET2_l_mor1.\n  Proof.\n  unfold Map_law, FunSET2_l_mor1 in |- *; simpl in |- *.\n  intros h1 h2 H.\n  apply Comp_r; apply Comp_l; assumption.\n  Qed.\n\n  Canonical Structure FunSET2_l_mor :\n    Map (FunSET2_l_ob d1xc1) (FunSET2_l_ob d2xc2) := FunSET2_l_map_law1.\n\n  End funset2_l_mor_def.\n\n Lemma FunSET2_l_map_law : Map_law FunSET2_l_mor.\n Proof.\n unfold Map_law, FunSET2_l_mor in |- *.\n intros f1xg1 f2xg2; elim f1xg1; intros f1 g1. \n elim f2xg2; intros f2 g2; simpl in |- *.\n unfold Ext in |- *; simpl in |- *.\n unfold Equal_Pmor in |- *; simpl in |- *.\n unfold FunSET2_l_mor1 in |- *; simpl in |- *.\n unfold FunSET2_l_ob in |- *.\n intro H; elim H; intros H1 H2 h.\n apply Comp_lr.\n apply Comp_r; trivial.\n apply FPres. \n assumption.\n Qed.\n\n Canonical Structure FunSET2_l_map := Build_Map FunSET2_l_map_law.\n\n End funset2_l_map_def.\n \nLemma Fun2_l_comp_law : Fcomp_law FunSET2_l_map.\nProof.\nunfold Fcomp_law, FunSET2_l_map in |- *; simpl in |- *.\nunfold FunSET2_l_mor, Ext in |- *; simpl in |- *.\nunfold FunSET2_l_mor1, FunSET2_l_ob in |- *; simpl in |- *.\nintros d1xc1 d2xc2 d3xc3 f1xg1 f2xg2 h.\nelim f1xg1; simpl in |- *; unfold DHom in |- *; intros f1 g1.\nelim f2xg2; simpl in |- *; unfold DHom in |- *; intros f2 g2; simpl in |- *.\n\n(* *) apply Trans with (((f2 o f1) o h) o FMor G g1 o FMor G g2).\napply Comp_l.\napply FComp.\n(* *) apply Trans with ((((f2 o f1) o h) o FMor G g1) o FMor G g2).\napply Ass.\napply Comp_r.\n(* *) apply Trans with ((f2 o f1 o h) o FMor G g1).\napply Comp_r.\napply Ass1.\napply Ass1.\nQed.\n\nLemma Fun2_l_id_law : Fid_law FunSET2_l_map.\nProof.\nunfold Fid_law, FunSET2_l_map, FunSET2_l_mor in |- *; simpl in |- *.\nunfold Ext, Id_SET in |- *; simpl in |- *.\nunfold FunSET2_l_mor1 in |- *; simpl in |- *.\nunfold FunSET2_l_ob in |- *; simpl in |- *; intros dxc f.\nunfold Id_fun in |- *.\n(* *) apply Trans with (Id (OB_l dxc) o f o FMor G (Id (Ob_r dxc))).\napply Ass1.\n(* *) apply Trans with (f o FMor G (Id (Ob_r dxc))).\napply Idl.\n(* *) apply Trans with (f o Id (G (Ob_r dxc))).\napply Comp_l; apply FId.\napply Idr1.\nQed.\n\nCanonical Structure FunSET2_l := Build_Functor Fun2_l_comp_law Fun2_l_id_law.\n\nEnd FunSet2_l.\n\n\n", "meta": {"author": "JasonGross", "repo": "category-coq-experience-tests", "sha": "f9949ede618788fd051fe8327f997ee683388e49", "save_path": "github-repos/coq/JasonGross-category-coq-experience-tests", "path": "github-repos/coq/JasonGross-category-coq-experience-tests/category-coq-experience-tests-f9949ede618788fd051fe8327f997ee683388e49/ConCaT/CATEGORY_THEORY/ADJUNCTION/HomFunctor2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24638901993027698}}
{"text": "Require Import Bool.\nRequire Import String.\nRequire Classical.\nRequire Import Coq.Classes.RelationClasses.\nRequire Coq.Setoids.Setoid.\n\nOpen Scope string_scope.\n\n(* To solve bug 2630. *)\nLtac easy ::=\n  let rec use_hyp H :=\n   (match type of H with\n    | _ /\\ _ => exact H || destruct_hyp H\n    | _ => try (solve [ inversion H ])\n    end)\n  with do_intro := (let H := fresh in\n                    intro H; use_hyp H)\n  with destruct_hyp H := (case H; clear H; do_intro; do_intro) in\n  let rec use_hyps :=\n   (match goal with\n    | H:_ /\\ _ |- _ => exact H || (destruct_hyp H; use_hyps)\n    | H:_ |- _ => solve [ inversion H ]\n    | _ => idtac\n    end) in\n  let rec do_atom :=\n   ((solve [ reflexivity | symmetry; trivial ]) || (* the only modified line *)\n      contradiction || (split; do_atom))\n  with do_ccl := (trivial with eq_true; do_atom || (repeat do_intro; do_atom)) in\n  (use_hyps; do_ccl) || fail \"Cannot solve this goal\".\n\n\n(***************************)\n(** *  Krivine's machine  **)\n(***************************)\n\n\n(** An abstract set of instructions, containing callcc **)\nParameter instruction : Set.\nParameter callcc : instruction.\n\n(** A set of stack constants **)\nParameter stack_const : Set.\n\n(** λ_c terms **)\nInductive term : Set :=\n  | Cst : instruction -> term\n  | Lam : string -> term -> term\n  | Var : string -> term\n  | App : term -> term -> term.\nCoercion Cst : instruction >-> term.\nCoercion Var : string >-> term.\nNotation \"'λ' n t\" := (Lam n t) (at level 16, n at level 0, t at level 41, format \"'λ' n '/  '  t\").\nNotation \"t @ s\" := (App t s) (at level 15, left associativity).\n\n\n(** Closures, stacks and environments **)\nInductive Λ : Set :=\n  | Closed : term -> env -> Λ\n  | Cont : Π -> Λ\nwith Π : Set :=\n  | Scst : stack_const -> Π\n  | Scons : Λ -> Π -> Π\nwith env : Set :=\n  | Enil : env\n  | Econs : string -> Λ -> env -> env.\nCoercion Scst : stack_const >-> Π.\nNotation \"t ↓ e\" := (Closed t e) (at level 45, no associativity, format \"t '/  ' '↓' e\").\nNotation \"k[ π ]\" := (Cont π).\nNotation \"t · s\" := (Scons t s) (at level 47, right associativity).\nNotation \"e ← t ; f\" := (Econs e t f) (at level 49, right associativity, format \"e '←' t ';'  '/' f\").\nNotation \"∅\" := Enil.\n\nBind Scope Env_scope with env.\nBind Scope Stack_scope with Π.\nBind Scope Clos_scope with Λ.\n\nArguments Cont _%Stack_scope.\nArguments Scons _%Clos_scope _%Stack_scope.\nArguments Econs _%Clos_scope _%Env_scope.\n\n(* Extracting a closure from an environment *)\nFixpoint get s (e : env) : Λ :=\n  match e with\n    | c←t;e' => if string_dec s c then t else get s e'\n    | Enil => \"environment too small\"↓Enil (* dummy case *)\n  end.\n\n(** Checking wether a term is closed.\n    Useful for eliminating typos in big λ_c-terms.  **)\nFixpoint closed_aux acc t :=\n  match t with\n    | Cst _ => true\n    | Lam s t' => closed_aux (cons s acc) t'\n    | Var n => if List.in_dec string_dec n acc then true else false\n    | App t₁ t₂ => closed_aux acc t₁ && closed_aux acc t₂\n  end.\n\nDefinition closed := closed_aux nil.\n\n\n(** Processes **)\nInductive process := Process : Λ -> Π -> process.\nNotation \"c '★' s\" := (Process c s) (at level 55).\n\n(** **  Reduction rules  **)\n\nParameter red : process -> process -> Prop.\nNotation \"p₁ ≻ p₂\" := (red p₁ p₂) (at level 70).\nAxiom red_trans : forall p₁ p₂ p₃, p₁ ≻ p₂ -> p₂ ≻ p₃ -> p₁ ≻ p₃.\n\n(** Reduction rules: grab, push, save, restore plus one for variables.\n    \n    The last rule is necessary for native data: we unbox it to expose it to the operators.\n**)\nAxiom red_Lam : forall n t c e π, (λ n t)↓e ★ c·π ≻ t↓(n←c;e) ★ π.\nAxiom red_App : forall t t' e π, t @ t'↓e ★ π ≻ t↓e ★ t'↓e · π.\nAxiom red_cc : forall t e π, callcc↓e ★ t·π ≻ t ★ k[π]·π.\nAxiom red_k : forall t π π', k[π] ★ t·π' ≻ t ★ π.\nAxiom red_Var : forall n e π, Var n↓e ★ π ≻ get n e ★ π.\nAxiom red_AppVar : forall t n e π, t @ Var n↓e ★ π ≻ t↓e ★ get n e·π.\n\n(** Tactics to perform one step of evaluation in the KAM **)\nLtac Kred tac := eapply red_trans; [now apply tac |].\nLtac Kstep := Kred red_Lam || (Kred red_Var; simpl get) || (Kred red_AppVar; simpl get) || Kred red_cc\n             || Kred red_k || (Kred red_App; simpl get).\n\n(** Printing command for λ_c terms. **)\nSection Printing.\n  Variable print_const : instruction -> string.\n  Variable print_sconst : stack_const -> string.\n\n  Fixpoint print_term (t : term) : string :=\n    match t with\n      | Cst c => print_const c\n      | Lam n t => \"λ\" ++ n ++ \" \" ++ print_term t\n      | Var n => n\n      | App t₁ t₂ => print_term t₁ ++ \" \" ++ print_term t₂\n    end.\n  \n  Fixpoint print_clos c :=\n    match c with\n      | Closed t e => (print_term t ++ \"↓\" ++ print_env e)%string\n      | Cont s => \"k[\" ++ print_stack s ++ \"]\"\n    end\n  with print_stack s :=\n    match s with\n      | Scst α => print_sconst α\n      | Scons c s' => print_clos c ++ \"°\" ++ print_stack s'\n    end\n  with print_env e :=\n    match e with\n      | Enil => \"∅\"%string\n      | Econs n c Enil => n ++ \" ↦ \" ++ print_clos c\n      | Econs n c e' => n ++ \" ↦ \" ++ print_clos c ++ \", \" ++ print_env e'\n    end.\nEnd Printing.\n\n(** **  Some usual terms  **)\n\nDefinition Id := λ\"x\" \"x\".\nDefinition nId := λ\"x\" (\"x\" @ \"x\"). (* or any λx. x u *) \nDefinition tt := λ\"x\" λ\"y\" \"x\".\nDefinition ff := λ\"x\" λ\"y\" \"y\".\nDefinition δ := λ\"x\" \"x\" @ \"x\".\nDefinition Ω := δ @ δ.\n(** A universal realizer of excluded middle **)\nDefinition em := λ\"f\" λ\"g\" callcc @ λ\"k\" \"g\" @ λ\"i\" \"k\" @ (\"f\" @ \"i\").\n(** Turing's fixpoint operator **)\nDefinition Y := (λ\"x\" λ\"y\" \"y\" @ (\"x\" @ \"x\" @ \"y\")) @ (λ\"x\" λ\"y\" \"y\" @ (\"x\" @ \"x\" @ \"y\")).\n\nExample Ω_red : forall e π, δ↓e ★ δ↓e·π ≻ δ↓e ★ δ↓e·π.\nProof. unfold δ at 1. intros e π. do 2 Kstep. apply red_Var. Qed.\n\n(** Storage operators for functions.\n    We force the presence of the continuation(s) k (or u and v)\n    to ensure that the reduction can only occur when it is present.\n**)\nDefinition caron1 op := λ\"Mx\" \"Mx\" @ λ\"x\" op @ \"x\".\nDefinition caron2 op := λ\"Mx\" \"Mx\" @ λ\"x\" λ\"My\" \"My\" @ λ\"y\" op @ \"x\" @ \"y\".\nDefinition caron3 op := λ\"Mx\" \"Mx\" @ λ\"x\" λ\"My\" \"My\" @ λ\"y\" λ\"Mz\" \"Mz\" @ λ\"z\" op @ \"x\" @ \"y\" @ \"z\".\nDefinition caron4 op := λ\"Mx\" \"Mx\" @ λ\"x\" λ\"My\" \"My\" @ λ\"y\" λ\"Mz\" \"Mz\" @ λ\"z\"\n  λ\"Mt\" \"Mt\" @ λ\"t\" op @ \"x\" @ \"y\" @ \"z\" @ \"t\".\n\n(** Same thing for relations. **)\nDefinition rel_caron1 rel := λ\"Mx\" \"Mx\" @ λ\"x\" rel @ \"x\".\nDefinition rel_caron2 rel := λ\"Mx\" \"Mx\" @ λ\"x\" λ\"My\" \"My\" @ λ\"y\" rel @ \"x\" @ \"y\".\nDefinition rel_caron3 rel :=\n  λ\"Mx\" \"Mx\" @ λ\"x\" λ\"My\" \"My\" @ λ\"y\" λ\"Mz\" \"Mz\" @ λ\"z\" rel @ \"x\" @ \"y\" @ \"z\".\nDefinition rel_caron4 rel := λ\"Mx\" \"Mx\" @ λ\"x\" λ\"My\" \"My\" @ λ\"y\" λ\"Mz\" \"Mz\" @ λ\"z\" λ\"Mt\" \"Mt\" @ λ\"t\"\n  rel @ \"x\" @ \"y\" @ \"z\" @ \"t\".\n\n\n(***********************)\n(** *  Realizability  **)\n(***********************)\n\n\nParameter pole : process -> Prop.\nNotation \"p ∈ ⫫\" := (pole p) (at level 69, format \"p  '∈'  '⫫'\").\nAxiom anti_evaluation : forall p p', p ≻ p' -> p' ∈ ⫫ -> p ∈ ⫫.\n\nDefinition formula := Π -> Prop.\n\nDefinition Fval (F : formula) (π : Π) := F π.\nNotation \"π '∈' '‖' F '‖'\" := (Fval F π) (at level 70, format \"'[hv' π  '∈' '/'  '‖' F '‖' ']'\").\n\nDefinition realizes t F := forall π, π ∈ ‖F‖ -> t★π ∈ ⫫.\nNotation \"t ⊩ F\" := (realizes t F) (at level 79).\n\nDefinition Impl A B := fun π => match π with Scst _ => False | t·π' => t ⊩ A /\\ π' ∈ ‖B‖ end.\nNotation \"A '→' B\" := (Impl A B) (at level 78, right associativity).\n\n\nLtac clear_realizers :=\n  repeat lazymatch goal with\n    | H : _ ⊩ _ |- _ => clear H\n    | H : _ ∈ ‖_‖ |- _ => clear H\n    | π : Π |- _ => clear π\n    | t : Λ |- _ => clear t\n    | e : env |- _ => clear e\n  end.\n\n(** **  Quantifications  **)\n\n(** There is a lot of boilerplate code here because the notation mecanism of Coq is not powerful enough to handle\n    relativized quantification of arbitrary arity so we have to define it for every fixed arity.\n    In addition, we also take advantage of these definitions to optimize relativization predicates,\n    so that relativzing to [A x ∧ B x] can be defined as [∀x, A x → B x → …].\n    \n    In a nutshell, we can use [∀ x y … z, A] or [∃ x y … z, A] for unrelativized quantifications and\n    [∀₂ x, y ∈ P₁ × P₂, A] or [∃₃ x, y, z ∈ P₁ × P₂ × P₃] for relatized one, where the indices [₂] and [₃] are\n    the number of variables you quantify over.  Currently, it goes from 1 to 5.\n**)\n\n(** *** Without relativization **)\n\nDefinition Forall T f : formula := fun π => exists t : T, π ∈ ‖f t‖.\nGlobal Notation \"'∀' t₁ .. t₂ ',' F\" := (Forall _ (fun t₁ => .. (Forall _ (fun t₂ => F)) .. ))\n  (at level 99, t₁ binder, t₂ binder, right associativity).\nGlobal Notation \"'∃' t₁ .. t₂ ',' F\" :=\n  (Forall formula (fun Z => (Forall _ (fun t₁ => .. (Forall _ (fun t₂ => F → Z)) ..)) → Z))\n  (at level 99, t₁ binder, t₂ binder, right associativity).\n\n(** *** With relativization **)\n\n(** Relativization is defined as an operator of formulæ depending on an argument.\n    The simplest such operator on a predicate [P] is [fun A x => P x -> A x] built by [make_Rel]\n    but in some cases we may want to define optimized ones, using [now_Rel].\n**)\nClass Relativisation {T : Type} (P : T -> formula) := Rel : (T -> formula) -> T -> formula.\nGlobal Instance now_Rel {T} P f : @Relativisation T P := {Rel := f}.\nGlobal Instance make_Rel {T} P : @Relativisation T P := {Rel := fun f t => P t → f t}.\nGlobal Hint Unfold Rel now_Rel make_Rel : Krivine.\n(* Note: We cannot add the equivalence between relativized formula and the formula with the predicate\n         as a precondition because the idea is precisely to modify the number of arguments\n         so that terms cannot be equivalent.\n         We could add the existence of terms performing the translation in both directions as a way to ensure\n         correctness but this could not be used in practice. *)\n\n(** Binding 1 variable **)\nDefinition ForallR {T} P `{@Relativisation T P} (f : T -> formula) : formula :=\n  fun π => exists t : T, π ∈ ‖Rel f t‖.\nGlobal Notation \"'∀₁' t '∈' P ',' F\" := (ForallR P (fun t => F)) (at level 99, right associativity).\nGlobal Notation \"'∃₁' t '∈' P ',' F\" :=\n  (Forall formula (fun Z => (ForallR P (fun t => F → Z)) → Z)) (at level 99, t at next level).\n\n(** Binding 2 variables **)\nDefinition ForallR2 {T₁ T₂} P₁ P₂ `{@Relativisation T₁ P₁, @Relativisation T₂ P₂} (f : T₁ -> T₂ -> formula)\n  : formula := fun π => exists t₁ : T₁, exists t₂ : T₂, π ∈ ‖Rel (fun t => Rel (f t) t₂) t₁‖.\nGlobal Notation \"'∀₂' t₁ ',' t₂ '∈' P₁ '×' P₂ ',' F\" :=\n  (ForallR2 P₁ P₂ (fun t₁ t₂ => F)) (at level 99, right associativity).\nGlobal Notation \"'∃₂' t₁ ',' t₂ '∈' P₁ '×' P₂ ',' F\" :=\n  (Forall formula (fun Z => (ForallR2 P₁ P₂ (fun t₁ t₂ => F → Z)) → Z)) (at level 99, right associativity).\n\n(** Binding 3 variables **)\nDefinition ForallR3 {T₁ T₂ T₃} P₁ P₂ P₃ `{@Relativisation T₁ P₁, @Relativisation T₂ P₂, @Relativisation T₃ P₃}\n                    (f : T₁ -> T₂ -> T₃ -> formula) : formula :=\n  fun π => exists t₁ : T₁, exists t₂ : T₂, exists t₃ : T₃,\n           π ∈ ‖Rel (fun t => Rel (fun t' => Rel (f t t') t₃) t₂) t₁‖.\nGlobal Notation \"'∀₃' t₁ ',' t₂ ',' t₃ '∈' P₁ '×' P₂ '×' P₃ ',' F\" :=\n  (ForallR3 P₁ P₂ P₃ (fun t₁ t₂ t₃ => F)) (at level 99,  right associativity).\nGlobal Notation \"'∃₃' t₁ ',' t₂ ',' t₃ '∈' P₁ '×' P₂ '×' P₃ ',' F\" :=\n  (Forall formula (fun Z => (ForallR3 P₁ P₂ P₃ (fun t₁ t₂ t₃ => F → Z)) → Z))\n  (at level 99, right associativity).\n\n(** Binding 4 variables **)\nDefinition ForallR4 {T₁ T₂ T₃ T₄} P₁ P₂ P₃ P₄\n                    `{@Relativisation T₁ P₁, @Relativisation T₂ P₂, @Relativisation T₃ P₃, @Relativisation T₄ P₄}\n                    (f : T₁ -> T₂ -> T₃ -> T₄ -> formula) : formula :=\n  fun π => exists t₁ : T₁, exists t₂ : T₂, exists t₃ : T₃, exists t₄ : T₄,\n           π ∈ ‖Rel (fun t => Rel (fun t' => Rel (fun t'' => Rel (f t t' t'') t₄) t₃) t₂) t₁‖.\nGlobal Notation \"'∀₄' t₁ ',' t₂ ',' t₃ ',' t₄ '∈' P₁ '×' P₂ '×' P₃ '×' P₄ ',' F\" :=\n  (ForallR4 P₁ P₂ P₃ P₄ (fun t₁ t₂ t₃ t₄ => F)) (at level 99,  right associativity).\nGlobal Notation \"'∃₄' t₁ ',' t₂ ',' t₃ ',' t₄ '∈' P₁ '×' P₂ '×' P₃ '×' P₄ ',' F\" :=\n  (Forall formula (fun Z => (ForallR4 P₁ P₂ P₃ P₄ (fun t₁ t₂ t₃ t₄ => F → Z)) → Z))\n  (at level 99, right associativity).\n\n(** Binding 5 variables **)\nDefinition ForallR5 {T₁ T₂ T₃ T₄ T₅} P₁ P₂ P₃ P₄ P₅\n  `{@Relativisation T₁ P₁, @Relativisation T₂ P₂, @Relativisation T₃ P₃, @Relativisation T₄ P₄,\n    @Relativisation T₅ P₅} (f : T₁ -> T₂ -> T₃ -> T₄ -> T₅ -> formula) : formula :=\n  fun π => exists t₁ : T₁, exists t₂ : T₂, exists t₃ : T₃, exists t₄ : T₄, exists t₅ : T₅,\n    π ∈ ‖Rel (fun t => Rel (fun t' => Rel (fun t'' => Rel (fun t''' => Rel (f t t' t'' t''') t₅) t₄) t₃) t₂) t₁‖.\nGlobal Notation \"'∀₅' t₁ ',' t₂ ',' t₃ ',' t₄ ',' t₅ '∈' P₁ '×' P₂ '×' P₃ '×' P₄ '×' P₅ ',' F\" :=\n  (ForallR5 P₁ P₂ P₃ P₄ P₅ (fun t₁ t₂ t₃ t₄ t₅ => F)) (at level 99,  right associativity).\nGlobal Notation \"'∃₅' t₁ ',' t₂ ',' t₃ ',' t₄ ',' t₅ '∈' P₁ '×' P₂ '×' P₃ '×' P₄ '×' P₅ ',' F\" :=\n  (Forall formula (fun Z => (ForallR5 P₁ P₂ P₃ P₄ P₅ (fun t₁ t₂ t₃ t₄ t₅ => F → Z)) → Z))\n  (at level 99, right associativity).\n\n(** ***  Function relativisation  **)\n\nDefinition fun_Pred {T T'} P P' (f : T -> T') := ∀₁x∈P, P' (f x).\nGlobal Instance fun_Rel {T T'} P P' `{Relativisation T P} : @Relativisation (T -> T') (fun_Pred P P') :=\n  now_Rel (fun_Pred P P') (fun f t => (∀₁x∈P, P'(t x)) → f t).\nNotation \"A '~>' B\" := (fun_Pred A B) (at level 80, right associativity).\n\n\n(** ** Usual connectives **)\n\nDefinition Top : formula := fun _ => False.\nNotation \"⊤\" := Top.\n\nDefinition bot := ∀ Z, Z.\nNotation \"⊥\" := bot.\n\nNotation \"¬ F\" := (F → ⊥) (at level 25, only parsing).\n\nDefinition one := ∀ Z, (Z → Z).\n\n\n(** Semantic implication **)\n\n(** Be careful that the equivalence between c → A and c ↦ A can only be realized when c is realized\n    by the identity. This means that taking c = n <> m does not provide the equivalence.\n    In this case, it is better to take a boolean equality eqb since x <> y then amounts to eqb(x,y) = 0.\n**)\nDefinition mapsto (c : Prop) F := fun π => c /\\ π ∈ ‖F‖.\nNotation \"c '↦' F\" := (mapsto c F) (at level 78, right associativity).\n\n(** Intersection type **)\nDefinition inter A B := fun π => π ∈ ‖A‖ \\/ π ∈ ‖B‖.\nNotation \"A '∩' B\" := (inter A B) (at level 71, right associativity).\n\n\n(** Optimized version for n-ary and **)\nDefinition and2 A B := ∀ Z, (A → B → Z) → Z.\nNotation \"A ∧ B\" := (and2 A B) (at level 80, no associativity).\nDefinition and3 A B C := ∀ Z, (A → B → C → Z) → Z.\nNotation \"A ∧ B ∧ C\" := (and3 A B C) (at level 80, B at next level, no associativity).\nDefinition and4 A B C D := ∀ Z, (A → B → C → D → Z) → Z.\nNotation \"A ∧ B ∧ C ∧ D\" := (and4 A B C D) (at level 80, B at next level, C at next level, no associativity).\nDefinition and5 A B C D E := ∀ Z, (A → B → C → D → E → Z) → Z.\nNotation \"A ∧ B ∧ C ∧ D ∧ E\" := (and5 A B C D E)\n  (at level 80, B at next level, C at next level, D at next level, no associativity).\nDefinition and6 A B C D E F := ∀ Z, (A → B → C → D → E → F → Z) → Z.\nNotation \"A ∧ B ∧ C ∧ D ∧ E ∧ F\" := (and6 A B C D E F)\n  (at level 80, B at next level, C at next level, D at next level, E at next level, no associativity).\n\n(** Optimized versions for n-ary or **)\nDefinition or2 A B := ∀ Z, (A → Z) → (B → Z) → Z.\nNotation \"A ∨ B\" := (or2 A B) (at level 85, no associativity).\nDefinition or3 A B C := ∀ Z, (A → Z) → (B → Z) → (C → Z) → Z.\nNotation \"A ∨ B ∨ C\" := (or3 A B C) (at level 85, B at next level, no associativity).\nDefinition or4 A B C D := ∀ Z, (A → Z) → (B → Z) → (C → Z) → (D → Z) → Z.\nNotation \"A ∨ B ∨ C ∨ D\" := (or4 A B C D) (at level 85, B at next level, C at next level, no associativity).\nDefinition or5 A B C D E := ∀ Z, (A → Z) → (B → Z) → (C → Z) → (D → Z) → (E → Z) → Z.\nNotation \"A ∨ B ∨ C ∨ D ∨ E\" := (or5 A B C D E)\n  (at level 85, B at next level, C at next level, D at next level, no associativity).\nDefinition or6 A B C D E F := ∀ Z, (A → Z) → (B → Z) → (C → Z) → (D → Z) → (E → Z) → (F → Z) → Z.\nNotation \"A ∨ B ∨ C ∨ D ∨ E ∨ F\" := (or6 A B C D E F)\n  (at level 85, B at next level, C at next level, D at next level, E at next level, no associativity).\n\n(** Combining existential quantifiers and conjonction\n    \n    We optimize existential qunatifiers and conjunctions [∃x, A x ∧ B x] into [∀Z, (∀x, A x → B x → Z) → Z]\n    rather than [∀Z, (∀x, (∀Y, (A x → B x → Y) → Y)) → Z].\n\n    We can also use the semantic implication to get [∀Z, (∀x, A x ↦ B x → Z) → Z]. To do so, use [&] instead of [∧].\n    Such semantic conjunctions (at most 2) must be put at the begginning of the conjunct.\n**)\n(* Conflict with the other ∀_/∃_ notation without { } *)\n\n(** Without ↦ **)\nGlobal Notation \"'Ex₁' t '∈' P ',' '{' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR P (fun t => F₁ → .. (F₂ → Z) .. )) → Z))\n  (at level 98, t at next level, F₁ at level 79, F₂ at level 79).\nGlobal Notation \"'Ex₂' t₁ ',' t₂ '∈' P₁ '×' P₂ ',' '{' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR2 P₁ P₂ (fun t₁ t₂ => F₁ → .. (F₂ → Z) ..)) → Z))\n  (at level 98, right associativity, F₁ at level 79, F₂ at level 79).\nGlobal Notation \"'Ex₃' t₁ ',' t₂ ',' t₃ '∈' P₁ '×' P₂ '×' P₃ ',' '{' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR3 P₁ P₂ P₃ (fun t₁ t₂ t₃ => F₁ → .. (F₂ → Z) ..)) → Z))\n  (at level 98, right associativity, F₁ at level 79, F₂ at level 79).\nGlobal Notation \"'Ex₄' t₁ ',' t₂ ',' t₃ ',' t₄ '∈' P₁ '×' P₂ '×' P₃ '×' P₄ ',' '{' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR4 P₁ P₂ P₃ P₄ (fun t₁ t₂ t₃ t₄ => F₁ → .. (F₂ → Z) ..)) → Z))\n  (at level 98, right associativity, F₁ at level 79, F₂ at level 79).\nGlobal Notation\n  \"'Ex₅' t₁ ',' t₂ ',' t₃ ',' t₄ ',' t₅ '∈' P₁ '×' P₂ '×' P₃ '×' P₄ '×' P₅ ',' '{' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR5 P₁ P₂ P₃ P₄ P₅ (fun t₁ t₂ t₃ t₄ t₅ => F₁ → .. (F₂ → Z) ..)) → Z))\n  (at level 98, right associativity, F₁ at level 79, F₂ at level 79).\n\n(** With one ↦ **)\nGlobal Notation \"'Ex₁' t '∈' P ',' '{' F₀ '&' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR P (fun t => F₀ ↦ F₁ → .. (F₂ → Z) .. )) → Z))\n  (at level 98, t at next level, F₀ at level 79, F₁ at level 79, F₂ at level 79).\nGlobal Notation \"'Ex₂' t₁ ',' t₂ '∈' P₁ '×' P₂ ',' '{' F₀ '&' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR2 P₁ P₂ (fun t₁ t₂ => F₀ ↦ F₁ → .. (F₂ → Z) ..)) → Z))\n  (at level 98, right associativity, F₀ at level 79, F₁ at level 79, F₂ at level 79).\nGlobal Notation \"'Ex₃' t₁ ',' t₂ ',' t₃ '∈' P₁ '×' P₂ '×' P₃ ',' '{' F₀ '&' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR3 P₁ P₂ P₃ (fun t₁ t₂ t₃ => F₀ ↦ F₁ → .. (F₂ → Z) ..)) → Z))\n  (at level 98, right associativity, F₀ at level 79, F₁ at level 79, F₂ at level 79).\nGlobal Notation \"'Ex₄' t₁ ',' t₂ ',' t₃ ',' t₄ '∈' P₁ '×' P₂ '×' P₃ '×' P₄ ',' '{' F₀ '&' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR4 P₁ P₂ P₃ P₄ (fun t₁ t₂ t₃ t₄ => F₀ ↦ F₁ → .. (F₂ → Z) ..)) → Z))\n  (at level 98, right associativity, F₀ at level 79, F₁ at level 79, F₂ at level 79).\nGlobal Notation\n  \"'Ex₅' t₁ ',' t₂ ',' t₃ ',' t₄ ',' t₅ '∈' P₁ '×' P₂ '×' P₃ '×' P₄ '×' P₅ ',' '{' F₀ '&' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR5 P₁ P₂ P₃ P₄ P₅ (fun t₁ t₂ t₃ t₄ t₅ => F₀ ↦ F₁ → .. (F₂ → Z) ..)) → Z))\n  (at level 98, right associativity, F₀ at level 79, F₁ at level 79, F₂ at level 79).\n\n(** With two ↦ **)\nGlobal Notation \"'Ex₁' t '∈' P ',' '{' F '&' F₀ '&' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR P (fun t => F ↦ F₀ ↦ F₁ → .. (F₂ → Z) .. )) → Z))\n  (at level 98, t at next level, F at level 79, F₀ at level 79, F₁ at level 79, F₂ at level 79).\nGlobal Notation \"'Ex₂' t₁ ',' t₂ '∈' P₁ '×' P₂ ',' '{' F '&' F₀ '&' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR2 P₁ P₂ (fun t₁ t₂ => F ↦ F₀ ↦ F₁ → .. (F₂ → Z) ..)) → Z))\n  (at level 98, right associativity, F at level 79, F₀ at level 79, F₁ at level 79, F₂ at level 79).\nGlobal Notation \"'Ex₃' t₁ ',' t₂ ',' t₃ '∈' P₁ '×' P₂ '×' P₃ ',' '{' F '&' F₀ '&' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR3 P₁ P₂ P₃ (fun t₁ t₂ t₃ => F ↦ F₀ ↦ F₁ → .. (F₂ → Z) ..)) → Z))\n  (at level 98, right associativity, F at level 79, F₀ at level 79, F₁ at level 79, F₂ at level 79).\nGlobal Notation \"'Ex₄' t₁ ',' t₂ ',' t₃ ',' t₄ '∈' P₁ '×' P₂ '×' P₃ '×' P₄ ',' '{' F '&' F₀ '&' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR4 P₁ P₂ P₃ P₄ (fun t₁ t₂ t₃ t₄ => F ↦ F₀ ↦ F₁ → .. (F₂ → Z) ..)) → Z))\n  (at level 98, right associativity, F at level 79, F₀ at level 79, F₁ at level 79, F₂ at level 79).\nGlobal Notation\n  \"'Ex₅' t₁ ',' t₂ ',' t₃ ',' t₄ ',' t₅ '∈' P₁ '×' P₂ '×' P₃ '×' P₄ '×' P₅ ',' '{' F '&' F₀ '&' F₁ '∧' .. '∧' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR5 P₁ P₂ P₃ P₄ P₅ (fun t₁ t₂ t₃ t₄ t₅ => F ↦ F₀ ↦ F₁ → .. (F₂ → Z) ..)) → Z))\n  (at level 98, right associativity, F at level 79, F₀ at level 79, F₁ at level 79, F₂ at level 79).\n\n(** Combining existential quantifiers and disjonction **)\nGlobal Notation \"'Ex₁' t '∈' P ',' '{' F₁ '∨' .. '∨' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR P (fun t => (F₁ → Z) → .. ((F₂ → Z) → Z) .. )) → Z))\n  (at level 98, t at next level, F₁ at level 79, F₂ at level 79).\nGlobal Notation \"'Ex₂' t₁ ',' t₂ '∈' P₁ '×' P₂ ',' '{' F₁ '∨' .. '∨' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR2 P₁ P₂ (fun t₁ t₂ => (F₁ → Z) → .. ((F₂ → Z) → Z) .. )) → Z))\n  (at level 98, right associativity, F₁ at level 79, F₂ at level 79).\nGlobal Notation \"'Ex₃' t₁ ',' t₂ ',' t₃ '∈' P₁ '×' P₂ '×' P₃ ',' '{' F₁ '∨' .. '∨' F₂ '}'\" :=\n  (Forall formula (fun Z => (ForallR3 P₁ P₂ P₃ (fun t₁ t₂ t₃ => (F₁ → Z) → .. ((F₂ → Z) → Z) .. )) → Z))\n  (at level 98, right associativity, F₁ at level 79, F₂ at level 79).\nGlobal Notation \"'Ex₄' t₁ ',' t₂ ',' t₃ ',' t₄ '∈' P₁ '×' P₂ '×' P₃ '×' P₄ ',' '{' F₁ '∨' .. '∨' F₂ '}'\" :=\n  (Forall formula\n    (fun Z => (ForallR4 P₁ P₂ P₃ P₄ (fun t₁ t₂ t₃ t₄ => (F₁ → Z) → .. ((F₂ → Z) → Z) .. )) → Z))\n  (at level 98, right associativity, F₁ at level 79, F₂ at level 79).\nGlobal Notation\n  \"'Ex₅' t₁ ',' t₂ ',' t₃ ',' t₄ ',' t₅ '∈' P₁ '×' P₂ '×' P₃ '×' P₄ '×' P₅ ',' '{' F₁ '∨' .. '∨' F₂ '}'\" :=\n  (Forall formula\n    (fun Z => (ForallR5 P₁ P₂ P₃ P₄ P₅ (fun t₁ t₂ t₃ t₄ t₅ => (F₁ → Z) → ..((F₂ → Z) → Z)..)) → Z))\n  (at level 98, right associativity, F₁ at level 79, F₂ at level 79).\n", "meta": {"author": "coq-contribs", "repo": "classical-realizability", "sha": "8c6187da3ba58bdbbbdbb9ec091c4aa738820361", "save_path": "github-repos/coq/coq-contribs-classical-realizability", "path": "github-repos/coq/coq-contribs-classical-realizability/classical-realizability-8c6187da3ba58bdbbbdbb9ec091c4aa738820361/ShallowEmbedding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24638901993027698}}
{"text": "From Coq Require Import RelationClasses.\nFrom Mon Require Import SPropBase.\nSet Warnings \"-notation-overridden,-ambiguous-paths\".\nFrom mathcomp Require Import all_ssreflect.\nSet Warnings \"notation-overridden,ambiguous-paths\".\nFrom Relational Require Import OrderEnrichedCategory OrderEnrichedRelativeMonadExamples.\nFrom Crypt Require Import ChoiceAsOrd OrderEnrichedRelativeAdjunctions OrderEnrichedRelativeAdjunctionsExamples TransformingLaxMorph SubDistr Theta_dens LaxFunctorsAndTransf UniversalFreeMap FreeProbProg StateTransformingLaxMorph LaxComp.\n\nImport SPropNotations.\n\n(*\nIn this file we state transform this morphism\nθdens : Frp → Sdistr\ninto\nStT(θdens) : StT(Frp) → StT(SDistr)\n\nWe also subsequently make its domain free\nθFstd : FrStP → StT(Frp) → stT(SDistr)\n*)\n\nSection GetDomainAndCodomain.\n  Context {C D1 D2 : ord_category} {J1 : ord_functor C D1} {J12 : ord_functor D1 D2} {J2 : ord_functor C D2}\n          {phi : natIso J2 (ord_functor_comp J1 J12)} (psi := ni_inv phi)\n          {M1 : ord_relativeMonad J1} {M2: ord_relativeMonad J2}.\n\n\n  Definition rlmm_domain (smTheta :  relativeLaxMonadMorphism J12 phi M1 M2)\n    : ord_relativeMonad J1\n    := M1.\n  Definition rlmm_codomain (smTheta :  relativeLaxMonadMorphism J12 phi M1 M2)\n    : ord_relativeMonad J2\n    := M2.\n\nEnd GetDomainAndCodomain.\n\n\nSection StT_unaryThetaDens.\n  Context {probE : Type -> Type}. (*an interface for probabilistic events*)\n  Context {chUniverse : Type}\n          {chElement : chUniverse -> choiceType}.\n  Context (prob_handler : forall (T:choiceType),\n    probE T -> SDistr T).\n\n  Context {S : choiceType}.\n\n  (*we wish to transform this monad morphism*)\n  Let θdens_filled :=\n  @unary_theta_dens.\n\n  (*domain and codomain*)\n  Let Frp := rlmm_domain θdens_filled.\n  (* Eval hnf in rlmm_codomain θdens_filled. (*SDistr*) *)\n\n\n\n  (*state transform the domain*)\n\n  Program Definition unaryStateTingAdj :\n  leftAdjunctionSituation choice_incl\n         (ord_functor_comp (unaryTimesS1 S) choice_incl)\n         (ToTheS S) :=\n    mkNatIso _ _ _ _ _ _ _.\n  Next Obligation.\n    move=> [A X]. unshelve econstructor.\n      simpl. move=> g a s. exact (g (a,s)).\n      move=> g g'. simpl in g. simpl in g'.\n      move=> Hg. unfold extract_ord. simpl.\n      move=> a.\n      unfold extract_ord in Hg. simpl in Hg.\n      apply boolp.funext. move=> s.\n      apply Hg.\n  Defined.\n  Next Obligation.\n    move=> [A X]. unshelve econstructor.\n      simpl. move=> g. move=> [a s]. exact (g a s).\n      simpl. move => g g'.\n      unfold extract_ord. simpl.\n      move=> Hg. move=> [a s].\n      specialize (Hg a). destruct Hg.\n      reflexivity.\n  Defined.\n  Next Obligation.\n    move=> [A X] [A' X']. move=> [fA fX]. simpl in *.\n    apply sig_eq. simpl. apply boolp.funext. move=> g.\n    apply boolp.funext. move=> a'. apply boolp.funext. move=> s.\n    simpl.\n    rewrite /OrderEnrichedRelativeAdjunctionsExamples.ToTheS_obligation_1.\n    reflexivity.\n  Qed.\n  Next Obligation.\n    move=> [A X].\n    apply sig_eq. simpl. apply boolp.funext. move=> g.\n    simpl. apply boolp.funext. move=> a. reflexivity.\n  Qed.\n  Next Obligation.\n    move=> [A X].\n    apply sig_eq. simpl. apply boolp.funext. move=> g.\n    simpl. apply boolp.funext. move=> [a s]. reflexivity.\n  Qed.\n\n  Program Definition unaryStateBeta' :\n  lnatTrans (lord_functor_comp\n                      (strict2laxFunc (ToTheS S))\n                      (strict2laxFunc (ord_functor_id TypeCat)))\n            (lord_functor_comp\n                      (strict2laxFunc (ord_functor_id TypeCat))\n                      (strict2laxFunc (ToTheS S))) :=\n    mkLnatTrans _ _.\n\n  Program Definition stT_thetaDens_adj :=\n  Transformed_lmla θdens_filled unaryStateTingAdj unaryStateTingAdj unaryStateBeta' _ _.\n  Next Obligation.\n    move=> A Y. move=> g.\n    apply boolp.funext. move=> [ a s]. cbv. reflexivity.\n  Qed.\n\n  Definition stT_thetaDens :=  rlmm_from_lmla stT_thetaDens_adj.\n\nEnd StT_unaryThetaDens.\n\n\n\nSection MakeTheDomainFree.\n  Context {probE : Type -> Type}. (*an interface for probabilistic events*)\n  Context {chUniverse : Type}\n          {chElement : chUniverse -> choiceType}.\n  Context {prob_handler : forall (T:choiceType),\n    probE T -> SDistr T}.\n\n  Context {S : choiceType}.\n\n  Let unaryIntState_filled :=\n  @unaryIntState S.\n\n  Let stT_thetaDens_filled :=\n  @stT_thetaDens S.\n\n\n\n  (*an auxiliary morphism to connect the dots*)\n  Program Definition bridgg :\n  relativeMonadMorphism (ord_functor_id _) (trivialChi)\n     (rlmm_codomain unaryIntState_filled)\n     (rlmm_domain stT_thetaDens_filled) :=\n    mkRelMonMorph _ _ _ _ _ _ _.\n\n  (*now... unaryIntState_filled ; bridgg = ppre*)\n  Let ppre := rlmm_comp _ _ _ _ _ _ _ (unaryIntState_filled) bridgg.\n\n  (*and then ppre ; stT_thetaDens_filled*)\n  Definition thetaFstd := rlmm_comp _ _ _ _ _ _ _ ppre stT_thetaDens_filled.\n\n\nEnd MakeTheDomainFree.\n", "meta": {"author": "Nsidorenco", "repo": "OpenVoteNetwork", "sha": "be771d7b74908c11d83a6cfd66542b51dfb318ab", "save_path": "github-repos/coq/Nsidorenco-OpenVoteNetwork", "path": "github-repos/coq/Nsidorenco-OpenVoteNetwork/OpenVoteNetwork-be771d7b74908c11d83a6cfd66542b51dfb318ab/theories/Crypt/rhl_semantics/state_prob/StateTransfThetaDens.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.24635188072557193}}
{"text": "(******************************************************************************)\n(** * Reasoning with multiple Power executions. *)\n(******************************************************************************)\n\nRequire Import Classical List Relations Peano_dec Omega.\nRequire Import Hahn.\nRequire Import Basic Power_Events  Power_Model Power_Domains Power_Locations\n  Power_Automation Power_Irreflexive Power_Threads Power_Helpers.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\n(* Unfold databases *)\nHint Unfold rb sync lwsync fence prop1 prop2 prop hb : derived_rels.\nHint Unfold Wf WfDEPS WfACTS WfSB WfRF WfMO WfRMW : wf_unfold.\n\n(* Notations *)\nNotation \"G ⟪ r ⟫ G'\" := (G.(r) ≡ G'.(r)) (at level 1).\nNotation \"G [ l ]  G'\" := (G.(l) = G'.(l)) (at level 1).\nNotation \"rel |loc\" := (fun G => (rel G) ∩ (same_loc G)) (at level 1).\n\n(* Tactics *)\nLtac equiv_solver :=\n  let solve_g := (fun g g' => \n    subst; (idtac + destruct g); (idtac + destruct g'); simpl; splits; auto\n  ) in\n  match goal with \n  | |- _ ?g ≡ _ ?g' => solve_g g g'\n  | |- _ ?g = _ ?g' => solve_g g g'\n  end.\n\nTactic Notation \"assert\" \"{\" ident(name) \"}\" uconstr(H) :=\n  assert (name: H) by equiv_solver.\n\nTactic Notation \"unfold_all\" :=\n  autounfold with derived_rels type_unfold.\nTactic Notation \"unfold_all\" \"in\" hyp(H):=\n  autounfold with derived_rels type_unfold in H.\nTactic Notation \"unfold_all\" \"in\" \"*\":=\n  autounfold with derived_rels type_unfold in *.\n\nTactic Notation \"surround\" \"<\" constr(s) \">\" constr(x) \"<\" constr(s') \">\" \"{\" constr(g) \"}\" :=\n  arewrite (x g ⊆ ⦗s g⦘ ⨾ x g ⨾ ⦗s' g⦘) by domain_solver.\nTactic Notation \"surround\" \"<\" constr(s) \">\" constr(x) \"{\" constr(g) \"}\" :=\n  arewrite (x g ⊆ ⦗s g⦘ ⨾ x g) by domain_solver.\nTactic Notation \"surround\" uconstr(x) \"<\" uconstr(s) \">\" \"{\" uconstr(g) \"}\" :=\n  arewrite (x g ⊆ x g ⨾ ⦗s g⦘) by domain_solver.\n\nSection Power_Executions.\n\nVariables G G' : power_execution.\n\n(* Relational equivalence helpers *)\nLemma rb_if_rf_mo (RF: G ⟪rf⟫ G') (MO: G ⟪mo⟫ G') : \n  G ⟪rb⟫ G'.\nProof. by unfold_all in *; rewrite RF, MO. Qed.\n\nLemma sync_if_sb (LAB: G [lab] G') (SB: G ⟪sb⟫ G') : \n  G ⟪sync⟫ G'.\nProof. by unfold_all in *; rewrite SB, LAB. Qed.\n\nLemma lwsync_if_sb (LAB: G [lab] G') (SB: G ⟪sb⟫ G') : \n  G ⟪lwsync⟫ G'.\nProof. by unfold_all in *; rewrite SB, LAB. Qed.\n\nLemma fence_if_sb (LAB: G [lab] G') (SB: G ⟪sb⟫ G') : \n  G ⟪fence⟫ G'.\nProof.\n  unfold fence.\n  arewrite (G ⟪sync⟫ G') by apply sync_if_sb.\n  arewrite (G ⟪lwsync⟫ G') by apply lwsync_if_sb.\nQed.\n\nLemma fence_if_sync_lwsync (S1: G ⟪sync⟫ G') (S2: G ⟪lwsync⟫ G') : \n  G ⟪fence⟫ G'.\nProof. by unfold fence; rewrite S1, S2. Qed.\n\nLemma hb_if_ppo_sb_rf (LAB: G [lab] G')\n  (PPO: G ⟪ppo⟫ G') (SB: G ⟪sb⟫ G') (RF: G ⟪rf⟫ G'):\n  G ⟪hb⟫ G'.\nProof.\n  unfold hb; rewrite PPO, RF.\n  arewrite (G ⟪fence⟫ G') by apply fence_if_sb.\nQed.\n\nLemma hb_if_ppo_fence_rf (LAB: G [lab] G')\n  (PPO: G ⟪ppo⟫ G') (FE: G ⟪fence⟫ G') (RF: G ⟪rf⟫ G'):\n  G ⟪hb⟫ G'.\nProof.\n  by unfold hb; rewrite PPO, RF, FE.\nQed.\n\nLemma prop1_if_rf_sb_ppo (LAB: G [lab] G')\n  (RF: G ⟪rf⟫ G') (SB: G ⟪sb⟫ G') (PPO: G ⟪ppo⟫ G') :\n  G ⟪prop1⟫ G'.\nProof.\n  unfold prop1; rewrite RF.\n  arewrite (G ⟪fence⟫ G') by apply fence_if_sb.\n  arewrite (G ⟪hb⟫ G') by apply hb_if_ppo_sb_rf.\n  by unfold_all in *; rewrite LAB.\nQed.\n\nLemma prop1_if_rf_fence_hb (LAB: G [lab] G')\n  (RF: G ⟪rf⟫ G') (FE: G ⟪fence⟫ G') (HB: G ⟪hb⟫ G') :\n  G ⟪prop1⟫ G'.\nProof.\n  unfold prop1; rewrite RF, FE, HB.\n  by unfold_all in *; rewrite LAB.\nQed.\n\nLemma prop2_if_mo_rf_sb_ppo (LAB: G [lab] G')\n  (MO: G ⟪mo⟫ G') (RF: G ⟪rf⟫ G') (SB: G ⟪sb⟫ G') (PPO: G ⟪ppo⟫ G') :\n  G ⟪prop2⟫ G'.\nProof.\n  unfold prop2; rewrite MO, RF.\n  arewrite (G ⟪rb⟫ G') by apply rb_if_rf_mo.\n  arewrite (G ⟪fence⟫ G') by apply fence_if_sb.\n  arewrite (G ⟪sync⟫ G') by apply sync_if_sb.\n  arewrite (G ⟪hb⟫ G') by apply hb_if_ppo_sb_rf.\nQed.\n\nLemma prop2_if_mo_rf_fence_hb_sync (LAB: G [lab] G')\n  (MO: G ⟪mo⟫ G') (RF: G ⟪rf⟫ G') (FE: G ⟪fence⟫ G') (HB: G ⟪hb⟫ G') \n  (SY: G ⟪sync⟫ G'):\n  G ⟪prop2⟫ G'.\nProof.\n  unfold prop2; rewrite MO, RF, FE, HB, SY.\n  arewrite (G ⟪rb⟫ G') by apply rb_if_rf_mo.\nQed.\n\nLemma prop_if_mo_rf_sb_ppo (LAB: G [lab] G')\n  (MO: G ⟪mo⟫ G') (RF: G ⟪rf⟫ G') (SB: G ⟪sb⟫ G') (PPO: G ⟪ppo⟫ G') :\n  G ⟪prop⟫ G'.\nProof.\n  unfold prop.\n  arewrite (G ⟪prop1⟫ G') by apply prop1_if_rf_sb_ppo.\n  arewrite (G ⟪prop2⟫ G') by apply prop2_if_mo_rf_sb_ppo.\nQed.\n\nLemma prop_if_mo_rf_hb_sync_fence (LAB: G [lab] G')\n  (MO: G ⟪mo⟫ G') (RF: G ⟪rf⟫ G') (HB: G ⟪hb⟫ G')\n  (SY: G ⟪sync⟫ G') (FE: G ⟪fence⟫ G') :\n  G ⟪prop⟫ G'.\nProof.\n  unfold prop.\n  arewrite (G ⟪prop1⟫ G') by apply prop1_if_rf_fence_hb.\n  arewrite (G ⟪prop2⟫ G') by apply prop2_if_mo_rf_fence_hb_sync.\nQed.\n\nLemma prop_if_prop1_prop2 (P1: G ⟪prop1⟫ G') (P2: G ⟪prop2⟫ G'):\n  G ⟪prop⟫ G'.\nProof. by unfold prop; rewrite P1, P2. Qed.\n\nLemma ppo_if_ii_ic (LAB: G [lab] G') (II: G ⟪ii⟫ G') (IC: G ⟪ic⟫ G') :\n  G ⟪ppo⟫ G'.\nProof. by unfold ppo; rewrite II, IC; unfold_all in *; rewrite LAB. Qed.\n\nLemma ii_if_ii0_ci0_cc0 (HII: G ⟪ii0⟫ G') (HCI: G ⟪ci0⟫ G') (HCC: G ⟪cc0⟫ G'):\n  G ⟪ii⟫ G'.\nProof.\n  red; split; red; ins;\n  eapply ii_rec with (P:=ii _) (P0:=ic _) (P1:=ci _) (P2:=cc _);\n  auto; ins; vauto;\n  try (apply HII in H0);\n  try (apply HCI in H0);\n  try (apply HCC in H0);\n  vauto.\nQed.\n\nLemma ic_if_ii0_ci0_cc0 (HII: G ⟪ii0⟫ G') (HCI: G ⟪ci0⟫ G') (HCC: G ⟪cc0⟫ G'):\n  G ⟪ic⟫ G'.\nProof.\n  red; split; red; ins.\n  - apply ic_rec with (G:=G) (P:=ii G') (P0:=ic G') (P1:=ci G') (P2:=cc G');\n    auto; ins; vauto;\n    try (apply HII in H0);\n    try (apply HCI in H0);\n    try (apply HCC in H0);\n    vauto.\n  - apply ic_rec with (G:=G') (P:=ii G) (P0:=ic G) (P1:=ci G) (P2:=cc G);\n    auto; ins; vauto;\n    try (apply HII in H0);\n    try (apply HCI in H0);\n    try (apply HCC in H0);\n    vauto.\nQed.\n\n(* Consistency equivalence helpers *)\nDefinition consistency_iso G G' :=\n  G [lab] G' /\\\n  G ⟪sb⟫ G' /\\\n  G ⟪mo⟫ G' /\\\n  G ⟪rf⟫ G' /\\\n  G ⟪rmw⟫ G' /\\\n  G ⟪ppo⟫ G'.\n\nLemma consistent_alt (WF: Wf G /\\ Wf G'):\n   consistency_iso G G' -> (PowerConsistent G' -> PowerConsistent G).\nProof.\n  unfold consistency_iso, PowerConsistent.\n  ins; desf; unnw.\n  assert (RB: G ⟪rb⟫ G') by (by apply rb_if_rf_mo).\n  assert (PR: G ⟪prop⟫ G') by (by apply prop_if_mo_rf_sb_ppo).\n  assert (HB: G ⟪hb⟫ G') by (by apply hb_if_ppo_sb_rf).\n  assert (SL: G ⟪same_loc⟫ G') by (by unfold Power_Model.same_loc; rewrite H).\n  by splits; auto; rewrite ?H, ?H0, ?H1, ?H2, ?H3, ?H4, ?RB, ?PR, ?HB, ?SL.\nQed.\n\nDefinition consistency_iso2 G G' :=\n  G [lab] G' /\\\n  G ⟪mo⟫ G' /\\\n  G ⟪rf⟫ G' /\\\n  G ⟪rmw⟫ G' /\\\n  G ⟪ii0⟫ G' /\\\n  G ⟪ci0⟫ G' /\\\n  G ⟪cc0⟫ G' /\\\n  G ⟪sync⟫ G' /\\\n  G ⟪fence⟫ G' /\\\n  G ⟪sb|loc⟫ G'.\n\nLemma consistent_alt2 (WF: Wf G /\\ Wf G'):\n   consistency_iso2 G G' -> (PowerConsistent G' -> PowerConsistent G).\nProof.\n  unfold consistency_iso2, PowerConsistent.\n  ins; desf.\n  assert (II: G ⟪ii⟫ G') by (by apply ii_if_ii0_ci0_cc0).\n  assert (IC: G ⟪ic⟫ G') by (by apply ic_if_ii0_ci0_cc0).\n  assert (PPO: G ⟪ppo⟫ G') by (by apply ppo_if_ii_ic).\n  assert (RB: G ⟪rb⟫ G') by (by apply rb_if_rf_mo).\n  assert (HB: G ⟪hb⟫ G') by (by apply hb_if_ppo_fence_rf).\n  assert (PR: G ⟪prop⟫ G') by (by apply prop_if_mo_rf_hb_sync_fence).\n  splits; auto; by rewrite ?H0, ?H1, ?H2, ?H3, ?H4, ?H5, ?H6, ?H7, ?H8,\n                           ?RB, ?ST, ?FE, ?HB, ?PR, ?PPO.\nQed.\n\nDefinition consistency_iso3 G G' :=\n  G [lab] G' /\\\n  G ⟪mo⟫ G' /\\\n  G ⟪rf⟫ G' /\\\n  G ⟪rmw⟫ G' /\\\n  G ⟪prop1⟫ G' /\\\n  G ⟪prop2⟫ G' /\\\n  G ⟪hb⟫ G' /\\\n  G ⟪sb|loc⟫ G'.\n\nLemma consistent_alt3 (WF: Wf G /\\ Wf G'):\n   consistency_iso3 G G' -> (PowerConsistent G' -> PowerConsistent G).\nProof.\n  unfold consistency_iso3, PowerConsistent.\n  ins; desf.\n  assert (RB: G ⟪rb⟫ G') by (by apply rb_if_rf_mo).\n  assert (PR: G ⟪prop⟫ G') by (by apply prop_if_prop1_prop2).\n  splits; auto; by rewrite ?H0, ?H1, ?H2, ?H3, ?H4, ?H5, ?H6, ?RB, ?PR.\nQed.\n\nEnd Power_Executions.\n", "meta": {"author": "personal-practice", "repo": "coq", "sha": "df9a5f44b57323b02ba108126569a22e98b433e2", "save_path": "github-repos/coq/personal-practice-coq", "path": "github-repos/coq/personal-practice-coq/coq-df9a5f44b57323b02ba108126569a22e98b433e2/scfix/Power_Executions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2461987499748915}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef2.Spec.\nRequire Import TableDataOpsRef3.Specs.table_unmap3.\nRequire Import TableDataOpsRef3.LowSpecs.table_unmap3.\nRequire Import TableDataOpsRef3.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       table_unmap_spec\n       table_unmap2_spec\n    .\n\n  Lemma table_unmap3_spec_exists:\n    forall habd habd'  labd g_rd map_addr level res\n           (Hspec: table_unmap3_spec g_rd map_addr level habd = Some (habd', res))\n            (Hrel: relate_RData habd labd),\n    exists labd', table_unmap3_spec0 g_rd map_addr level labd = Some (labd', res) /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque peq ptr_eq.\n    intros. duplicate Hrel. destruct D. clear hrepl lrepl. destruct g_rd.\n    unfold table_unmap3_spec, table_unmap3_spec0 in *.\n    unfold Assertion in *. rm_bind Hspec; rm_bind'. simpl in *.\n    unfold Assertion; rm_bind'; grewrite.\n    repeat simpl_hyp Hspec; extract_prop_dec; simpl_query_oracle; rm_bind'; grewrite.\n    - rewrite_oracle_rel rel_oracle C6.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold unmap_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec; clear H0; grewrite;\n        (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C6.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold unmap_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec; clear H0; grewrite;\n        (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C6.\n      repeat (grewrite; try simpl_htarget; simpl). inversion Hspec.\n      (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C6.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n    - rewrite_oracle_rel rel_oracle C6.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef3/RefProof/table_unmap3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2461987499748915}}
{"text": "Require Import Arith.\nRequire Import List.\nImport ListNotations.\nRequire Import Omega.\n\nRequire Import v1.Util.\nRequire Import v1.ListLemmas.\nRequire Import v1.EpicsTypes.\nRequire Import v1.EpicsRecords.\nRequire Import v1.Step.\nRequire Import v1.NeutronTactics.\n\nSet Default Timeout 10.\nSet Implicit Arguments.\n\n\nDefinition is_db_op op :=\n    match op with\n    | MSetConst _ _ => true\n    | MCopy _ _ _ _ => true\n    | MReadLink _ _ _ _ => true\n    | MWriteLink _ _ _ _ => true\n    | MCalculate _ _ => true\n    | MCalculateStr _ _ _ => true\n    | MHavocUpdate => true\n    | MHavocWrite _ _ => true\n    | _ => false\n    end.\n\nDefinition is_output_op op :=\n    match op with\n    | MHwWrite _ _ _ => true\n    | MScheduleCallback _ _ => true\n    | _ => false\n    end.\n\nDefinition is_special_op op :=\n    match op with\n    | MProcess _ => true\n    | MCalcCond _ _ _ _ => true\n    | MCheckPACT => true\n    | MHavocProcess _ => true\n    | _ => false\n    end.\n\nDefinition micro_rect_g (P : micro -> Type) (Pl : list micro -> Type) :\n    (forall fn val, P (MSetConst fn val)) ->\n    (forall fn_src src_ty fn_dest dest_ty, P (MCopy fn_src src_ty fn_dest dest_ty)) ->\n    (forall il il_ty fn f_ty, P (MReadLink il il_ty fn f_ty)) ->\n    (forall fn f_ty ol ol_ty, P (MWriteLink fn f_ty ol ol_ty)) ->\n    (forall fl, P (MProcess fl)) ->\n    (forall expr fn_out, P (MCalculate expr fn_out)) ->\n    (forall expr fn_out_dbl fn_out_str, P (MCalculateStr expr fn_out_dbl fn_out_str)) ->\n    (forall fn f_ty out_ty, P (MHwWrite fn f_ty out_ty)) ->\n    (forall fn_cur fn_prev oopt body,\n        Pl body ->\n        P (MCalcCond fn_cur fn_prev oopt body)) ->\n    (forall delay code,\n        Pl code ->\n        P (MScheduleCallback delay code)) ->\n    (P (MCheckPACT)) ->\n    (P (MHavocUpdate)) ->\n    (forall ol ol_ty, P (MHavocWrite ol ol_ty)) ->\n    (forall fl, P (MHavocProcess fl)) ->\n    (Pl []) ->\n    (forall op ops,\n        P op ->\n        Pl ops ->\n        Pl (op :: ops)) ->\n    (forall op, P op).\nintros. generalize op. clear op. fix 1.\nsimple refine (\n    let fix micro_list_rect_g ops : Pl ops :=\n        match ops as ops_ return Pl ops_ with\n        | [] => _\n        | op :: ops =>\n                let Hop := micro_rect_g op in\n                let Hops := micro_list_rect_g ops in\n                _\n        end in _\n).\n{ clear micro_rect_g micro_list_rect_g. assumption. }\n{ clearbody Hop Hops. clear micro_rect_g micro_list_rect_g. eauto. }\nclearbody micro_list_rect_g. clear micro_rect_g.\n\ndestruct op; eauto.\nDefined.\n\n\nDefinition micro_list_rect_g (P : micro -> Type) (Pl : list micro -> Type) :\n    (forall fn val, P (MSetConst fn val)) ->\n    (forall fn_src src_ty fn_dest dest_ty, P (MCopy fn_src src_ty fn_dest dest_ty)) ->\n    (forall il il_ty fn f_ty, P (MReadLink il il_ty fn f_ty)) ->\n    (forall fn f_ty ol ol_ty, P (MWriteLink fn f_ty ol ol_ty)) ->\n    (forall fl, P (MProcess fl)) ->\n    (forall expr fn_out, P (MCalculate expr fn_out)) ->\n    (forall expr fn_out_dbl fn_out_str, P (MCalculateStr expr fn_out_dbl fn_out_str)) ->\n    (forall fn f_ty out_ty, P (MHwWrite fn f_ty out_ty)) ->\n    (forall fn_cur fn_prev oopt body,\n        Pl body ->\n        P (MCalcCond fn_cur fn_prev oopt body)) ->\n    (forall delay code,\n        Pl code ->\n        P (MScheduleCallback delay code)) ->\n    (P (MCheckPACT)) ->\n    (P (MHavocUpdate)) ->\n    (forall ol ol_ty, P (MHavocWrite ol ol_ty)) ->\n    (forall fl, P (MHavocProcess fl)) ->\n    (Pl []) ->\n    (forall op ops,\n        P op ->\n        Pl ops ->\n        Pl (op :: ops)) ->\n    (forall ops, Pl ops).\nintros. generalize ops. clear ops. fix 1. intros.\nsimple refine (\n    match ops as ops_ return Pl ops_ with\n    | [] => _\n    | op :: ops =>\n            let Hop : P op := _ in\n            let Hops : Pl ops := micro_list_rect_g ops in\n            _\n    end\n); try clearbody Hops; clear micro_list_rect_g.\n- eassumption.\n- eapply micro_rect_g; eassumption.\n- eauto.\nDefined.\n\nDefinition micro_rec' (P : micro -> Set) (Pl : list micro -> Set) :=\n    micro_rect_g P Pl.\n\nDefinition micro_ind' (P : micro -> Prop) (Pl : list micro -> Prop) :=\n    micro_rect_g P Pl.\n\nDefinition micro_list_ind' (P : micro -> Prop) (Pl : list micro -> Prop) :=\n    micro_list_rect_g P Pl.\n\nDefinition micro_ind'' (P : micro -> Prop) :\n    (forall fn val, P (MSetConst fn val)) ->\n    (forall fn_src src_ty fn_dest dest_ty, P (MCopy fn_src src_ty fn_dest dest_ty)) ->\n    (forall il il_ty fn f_ty, P (MReadLink il il_ty fn f_ty)) ->\n    (forall fn f_ty ol ol_ty, P (MWriteLink fn f_ty ol ol_ty)) ->\n    (forall fl, P (MProcess fl)) ->\n    (forall expr fn_out, P (MCalculate expr fn_out)) ->\n    (forall expr fn_out_dbl fn_out_str, P (MCalculateStr expr fn_out_dbl fn_out_str)) ->\n    (forall fn f_ty out_ty, P (MHwWrite fn f_ty out_ty)) ->\n    (forall fn_cur fn_prev oopt body,\n        Forall P body ->\n        P (MCalcCond fn_cur fn_prev oopt body)) ->\n    (forall delay code,\n        Forall P code ->\n        P (MScheduleCallback delay code)) ->\n    (P (MCheckPACT)) ->\n    (P (MHavocUpdate)) ->\n    (forall ol ol_ty, P (MHavocWrite ol ol_ty)) ->\n    (forall fl, P (MHavocProcess fl)) ->\n    (forall op, P op).\nintros. eapply micro_ind' with (Pl := Forall P); eauto.\nDefined.\n\n\nDefinition umicro_rec' (P : umicro -> Type) (Pl : list umicro -> Type) :\n    (forall fn val, P (USetConst fn val)) ->\n    (forall fn_src fn_dest, P (UCopy fn_src fn_dest)) ->\n    (forall il fn, P (UReadLink il fn)) ->\n    (forall fn ol, P (UWriteLink fn ol)) ->\n    (forall fns ol, P (UWriteLinkTyped fns ol)) ->\n    (forall fl, P (UProcess fl)) ->\n    (forall expr fn_out, P (UCalculate expr fn_out)) ->\n    (forall expr fn_out_dbl fn_out_str, P (UCalculateStr expr fn_out_dbl fn_out_str)) ->\n    (forall fn out_ty, P (UHwWrite fn out_ty)) ->\n    (forall fn_cur fn_prev oopt body,\n        Pl body ->\n        P (UCalcCond fn_cur fn_prev oopt body)) ->\n    (forall delay code,\n        Pl code ->\n        P (UScheduleCallback delay code)) ->\n    (P (UCheckPACT)) ->\n    (P (UHavocUpdate)) ->\n    (forall ol, P (UHavocWrite ol)) ->\n    (forall fl, P (UHavocProcess fl)) ->\n    (Pl []) ->\n    (forall op ops,\n        P op ->\n        Pl ops ->\n        Pl (op :: ops)) ->\n    (forall op, P op).\nintros. generalize op. clear op. fix 1.\nsimple refine (\n    let fix umicro_rec'_list ops : Pl ops :=\n        match ops as ops_ return Pl ops_ with\n        | [] => _\n        | op :: ops =>\n                let Hop := umicro_rec' op in\n                let Hops := umicro_rec'_list ops in\n                _\n        end in _\n).\n{ clear umicro_rec' umicro_rec'_list. assumption. }\n{ clearbody Hop Hops. clear umicro_rec' umicro_rec'_list. eauto. }\nclearbody umicro_rec'_list. clear umicro_rec'.\n\ndestruct op; eauto.\nDefined.\n\n\n\n\nInductive MicroForall (P : micro -> Prop) : micro -> Prop:=\n| MfCalcCond : forall fn_cur fn_prev oopt body,\n        P (MCalcCond fn_cur fn_prev oopt body) ->\n        Forall (MicroForall P) body ->\n        MicroForall P (MCalcCond fn_cur fn_prev oopt body)\n| MfScheduleCallback : forall delay code,\n        P (MScheduleCallback delay code) ->\n        Forall (MicroForall P) code ->\n        MicroForall P (MScheduleCallback delay code)\n| MfOther : forall op,\n        match op with\n        | MCalcCond _ _ _ _ => False\n        | MScheduleCallback _ _ => False\n        | _ => True\n        end ->\n        P op ->\n        MicroForall P op.\n\nLemma forall_one : forall P op,\n    MicroForall P op ->\n    P op.\ninversion 1; auto.\nQed.\n\n\n\nDefinition type_umicro_list dbt rt :=\n    let go := type_umicro dbt rt in\n    let fix go_list uops : option (list micro) :=\n        match uops with\n        | [] => Some []\n        | uop :: uops =>\n                go uop >>= fun uop' =>\n                go_list uops >>= fun uops' =>\n                Some (uop' :: uops')\n        end in go_list.\n\n\n\nInductive type_error_context :=\n| TCtxRecord (rn : record_name)\n| TCtxOpcode (uop : umicro)\n.\n\nInductive type_error :=\n| TyENoSuchRecord (rn : record_name)\n| TyENoTypedField (fns : list (field_type_matcher * field_name)) (ty : field_type)\n| TyEInContext (ctx : type_error_context) (e : type_error)\n| TyEMultipleErrors (e1 e2 : type_error)\n.\n\nDefinition type_umicro_checked (dbt : database_type) (rt : record_type) :\n    umicro -> unit + type_error.\nsimple refine (\n    let fix go (uop : umicro) : unit + type_error :=\n        let fix go_list (uops : list umicro) : unit + type_error :=\n            match uops with\n            | [] => inl tt\n            | uop :: uops =>\n                match go uop, go_list uops with\n                | inl tt, inl tt => inl tt\n                | inr e, inl tt => inr e\n                | inl tt, inr e => inr e\n                | inr e1, inr e2 => inr (TyEMultipleErrors e1 e2)\n                end\n            end in\n        let ctx := TCtxOpcode uop in\n        match uop with\n        | USetConst fn val => inl tt\n        | UCopy fn_src fn_dest => inl tt\n        | UReadLink il fn => _\n        | UWriteLink fn ol => _\n        | UWriteLinkTyped fns ol => _\n        | UProcess fl => inl tt\n        | UCalculate expr fn_out => inl tt\n        | UCalculateStr expr fn_out_dbl fn_out_str => inl tt\n        | UHwWrite fn out_ty => inl tt\n        | UCalcCond fn_cur fn_prev oopt body => go_list body\n        | UScheduleCallback delay code => go_list code\n        | UCheckPACT => inl tt\n        | UHavocUpdate => inl tt\n        | UHavocWrite ol => _\n        | UHavocProcess fl => inl tt\n        end in go\n); try clearbody go; try clearbody go_list.\n\n- (* ReadLink *)\n  destruct (lookup_type dbt (fl_rn il)); [ | right; exact (TyENoSuchRecord (fl_rn il)) ].\n  exact (inl tt).\n\n- (* WriteLink *)\n  destruct (lookup_type dbt (fl_rn ol)); [ | right; exact (TyENoSuchRecord (fl_rn ol)) ].\n  exact (inl tt).\n\n- (* WriteLinkTyped *)\n  destruct (lookup_type dbt (fl_rn ol)) as [ol_rt | ];\n          [ | right; exact (TyENoSuchRecord (fl_rn ol)) ].\n  set (ty := record_field_type ol_rt (fl_fn ol)).\n  destruct (find_match_for_type fns ty);\n        [ | right; exact (TyENoTypedField fns ty) ].\n  exact (inl tt).\n\n- (* HavocWrite *)\n  destruct (lookup_type dbt (fl_rn ol)); [ | right; exact (TyENoSuchRecord (fl_rn ol)) ].\n  exact (inl tt).\nDefined.\n\nDefinition map_checked {A} (f : A -> unit + type_error) : list A -> unit + type_error.\nsimple refine (\n    let go := f in\n    let fix go_list (xs : list A) : unit + type_error :=\n        match xs with\n        | [] => inl tt\n        | x :: xs =>\n                match go x, go_list xs with\n                | inl tt, inl tt => inl tt\n                | inr e, inl tt => inr e\n                | inl tt, inr e => inr e\n                | inr e1, inr e2 => inr (TyEMultipleErrors e1 e2)\n                end\n        end in go_list\n).\nDefined.\n\nDefinition type_record_uprogram_checked dbt urp : unit + type_error :=\n    map_checked (type_umicro_checked dbt (ru_type urp)) (ru_code urp).\n\nDefinition check_numbered_record {A} (f : A -> unit + type_error) (nx : nat * A) :\n        unit + type_error :=\n    let '(n, x) := nx in\n    match f x with\n    | inl tt => inl tt\n    | inr err => inr (TyEInContext (TCtxRecord n) err)\n    end.\n\nDefinition type_database_program'_checked dbt udp :=\n    map_checked (check_numbered_record (type_record_uprogram_checked dbt)) (numbered udp).\n\nDefinition type_database_program_checked udp :=\n    type_database_program'_checked (map ru_type udp) udp.\n\n\nInductive results_match {A : Type} :\n    (option A) ->\n    (unit + type_error) ->\n    Prop :=\n| RmYes : forall x, results_match (Some x) (inl tt)\n| RmNo : forall err, results_match None (inr err).\n\nLemma results_match_chain : forall A B x y\n    (f : option A -> option B)\n    (g : unit + type_error -> unit + type_error),\n    (forall x, exists x', f (Some x) = Some x') ->\n    (f None = None) ->\n    (g (inl tt) = inl tt) ->\n    (forall y, exists y', g (inr y) = inr y') ->\n    results_match x y ->\n    results_match (f x) (g y).\nintros0 Hf Hf' Hg Hg' Hrm.\n\ninvc Hrm.\n- destruct (Hf x0) as [? Hf_x]. rewrite Hf_x, Hg. constructor.\n- destruct (Hg' err) as [? Hg'_y]. rewrite Hf', Hg'_y. constructor.\nQed.\n\nLemma results_match_chain' : forall A B\n        (x1 : option A) (x2 : option B)\n        (y1 y2 : unit + type_error),\n    (forall x, x1 = Some x -> exists x', x2 = Some x') ->\n    (x1 = None -> x2 = None) ->\n    (y1 = inl tt -> y2 = inl tt) ->\n    (forall y, y1 = inr y -> exists y', y2 = inr y') ->\n    results_match x1 y1 ->\n    results_match x2 y2.\nintros0 Hx Hx' Hy Hy' Hrm.\n\ninvc Hrm.\n- destruct (Hx x) as [? Hx_x]; auto. rewrite Hx_x, Hy; auto. constructor.\n- destruct (Hy' err) as [? Hy'_y]; auto. rewrite Hx', Hy'_y; auto. constructor.\nQed.\n\nLemma results_match_chain_l : forall A B x y\n    (f : option A -> option B),\n    (forall x, exists x', f (Some x) = Some x') ->\n    (f None = None) ->\n    results_match x y ->\n    results_match (f x) y.\nintros. change y with (id y). eapply results_match_chain; eauto.\nunfold id. eauto.\nQed.\n\nLemma results_match_chain_r : forall A (x : option A) y\n    (g : unit + type_error -> unit + type_error),\n    (g (inl tt) = inl tt) ->\n    (forall y, exists y', g (inr y) = inr y') ->\n    results_match x y ->\n    results_match x (g y).\nintros. change x with (id x). eapply results_match_chain; eauto.\nunfold id. eauto.\nQed.\n\n(* `remvar` (\"remember as evar\") - replaces a chunk of your goal with an evar,\n   This may make it easier to apply some lemmas.  After solving the main goal,\n   you must also prove that the evar's instantiation is compatible with the\n   original value.\n *)\n\nTactic Notation \"remvar\" uconstr(u) \"as\" ident(x) :=\n    let x' := fresh x \"'\" in\n    let Heq := fresh \"Heq\" x in\n    remember u as x' eqn:Heq in |- *;\n    let T := type of x' in\n    evar (x : T);\n    let H := fresh \"H\" in\n    assert (H : x' = x); cycle 1;\n    unfold x in *; clear x;\n    [ rewrite H in Heq |- *; clear H\n    | rewrite Heq; clear Heq; clear x' ].\n\n\nLtac lift xx :=\n    let T := type of xx in\n    let switch old new_f :=\n        let new_f' := eval cbv beta in new_f in\n        (change old with (new_f' xx)) in\n\n    match goal with\n    | [ |- context [?f (?fx xx) ?b ?c ?d ?e] ] =>\n            switch (f (fx xx) b c d e) (fun x : T => f (fx x) b c d e)\n    | [ |- context [?f ?a (?fx xx) ?c ?d ?e] ] =>\n            switch (f a (fx xx) c d e) (fun x : T => f a (fx x) c d e)\n    | [ |- context [?f ?a ?b (?fx xx) ?d ?e] ] =>\n            switch (f a b (fx xx) d e) (fun x : T => f a b (fx x) d e)\n    | [ |- context [?f ?a ?b ?c (?fx xx) ?e] ] =>\n            switch (f a b c (fx xx) e) (fun x : T => f a b c (fx x) e)\n    | [ |- context [?f ?a ?b ?c ?d (?fx xx)] ] =>\n            switch (f a b c d (fx xx)) (fun x : T => f a b c d (fx x))\n\n    | [ |- context [?f (?fx xx) ?b ?c ?d] ] =>\n            switch (f (fx xx) b c d) (fun x : T => f (fx x) b c d)\n    | [ |- context [?f ?a (?fx xx) ?c ?d] ] =>\n            switch (f a (fx xx) c d) (fun x : T => f a (fx x) c d)\n    | [ |- context [?f ?a ?b (?fx xx) ?d] ] =>\n            switch (f a b (fx xx) d) (fun x : T => f a b (fx x) d)\n    | [ |- context [?f ?a ?b ?c (?fx xx)] ] =>\n            switch (f a b c (fx xx)) (fun x : T => f a b c (fx x))\n\n    | [ |- context [?f (?fx xx) ?b ?c] ] =>\n            switch (f (fx xx) b c) (fun x : T => f (fx x) b c)\n    | [ |- context [?f ?a (?fx xx) ?c] ] =>\n            switch (f a (fx xx) c) (fun x : T => f a (fx x) c)\n    | [ |- context [?f ?a ?b (?fx xx)] ] =>\n            switch (f a b (fx xx)) (fun x : T => f a b (fx x))\n\n    | [ |- context [?f (?fx xx) ?b] ] =>\n            switch (f (fx xx) b) (fun x : T => f (fx x) b)\n    | [ |- context [?f ?a (?fx xx)] ] =>\n            switch (f a (fx xx)) (fun x : T => f a (fx x))\n\n    | [ |- context [?f (?fx xx)] ] =>\n            switch (f (fx xx)) (fun x : T => f (fx x))\n\n    | [ |- context [xx] ] =>\n            switch (xx) (fun x : T => x)\n    end.\n\n\n\nLemma type_umicro_checked_correct : forall dbt rt uop,\n    results_match (type_umicro dbt rt uop) (type_umicro_checked dbt rt uop).\nintros dbt rt.\ninduction uop using umicro_rec' with\n    (Pl := fun uops =>\n        results_match\n            (type_umicro_list dbt rt uops)\n            (map_checked (type_umicro_checked dbt rt) uops));\nsimpl;\nfold (type_umicro_list dbt rt);\nfold (map_checked (type_umicro_checked dbt rt));\ntry solve [constructor; discriminate 1 || eauto].\n\n- destruct (lookup_type _ _); simpl;\n  constructor; discriminate 1 || eauto.\n\n- destruct (lookup_type _ _); simpl;\n  constructor; discriminate 1 || eauto.\n\n- destruct (lookup_type _ _); simpl;\n  [ destruct (find_match_for_type _ _); simpl | ];\n  constructor; discriminate 1 || eauto.\n\n- do 2 lift (type_umicro_list dbt rt body).\n  eapply results_match_chain_l with (3 := IHuop); simpl; eauto.\n\n- do 2 lift (type_umicro_list dbt rt code).\n  eapply results_match_chain_l with (3 := IHuop); simpl; eauto.\n\n- destruct (lookup_type _ _); simpl;\n  constructor; discriminate 1 || eauto.\n\n- unfold bind_option.\n  invc IHuop; invc IHuop0; simpl; constructor.\n\nQed.\n\nLemma map_checked_correct : forall A B (f : A -> option B) f' xs,\n    (forall x, results_match (f x) (f' x)) ->\n    results_match (map_opt f xs) (map_checked f' xs).\ninduction xs; intros0 Hrm.\n- constructor; simpl; intros; discriminate || eauto.\n- specialize (IHxs Hrm). rename a into x. specialize (Hrm x).\n  simpl. unfold bind_option.\n  invc Hrm; invc IHxs; simpl; constructor.\nQed.\n\nLemma type_record_uprogram_checked_correct : forall dbt urp,\n    results_match (type_record_uprogram dbt urp)\n                  (type_record_uprogram_checked dbt urp).\nintros. unfold type_record_uprogram, type_record_uprogram_checked.\ndo 2 lift (map_opt (type_umicro dbt (ru_type urp)) (ru_code urp)).\neapply results_match_chain_l; simpl; eauto.\neapply map_checked_correct. eapply type_umicro_checked_correct.\nQed.\n\n(*\nLemma chain_map_checked_numbered' : forall A B (f : A -> option B) f' xs n,\n    results_match (map_opt f xs) (map_checked f' xs) ->\n    results_match (map_opt f xs) (map_checked (check_numbered_record f') (numbered' n xs)).\ninduction xs; intros0 Hrm.\n- constructor; simpl; intros; discriminate || eauto.\n- simpl in *; unfold bind_option in *.\n  destruct (f a), (map_opt f xs),\n    (f' a), (map_checked f' xs) eqn:?, (map_checked _ (numbered' _ xs)) eqn:?;\n    (repeat on unit, fun H => destruct H); try econstructor; invc Hrm.\n  + specialize (IHxs (S n) ltac:(constructor)). rewrite Heqs0 in IHxs. invc IHxs.\n  + specialize (IHxs (S n) ltac:(constructor)). rewrite Heqs0 in IHxs. invc IHxs.\n  + specialize (IHxs (S n) ltac:(constructor)). rewrite Heqs0 in IHxs. invc IHxs.\n  + \n    try destruct u; try destruct u0; try try discriminate.\n  destruct (f a), (f' a); try destruct u.\n  Focus 2.\n  eapply \n\n  + destruct (f a), (map_opt f xs), (f' a), (map_checked f' xs);\n      try destruct u; try destruct u0; try discriminate.\n    specialize (IHxs (S n) ltac:(constructor)). invc IHxs.\n    econstructor.\n\n  + destruct (f a), (map_opt f xs), (f' a), (map_checked f' xs);\n      try destruct u; try destruct u0; try discriminate.\n    all: try (specialize (IHxs (S n) ltac:(constructor)); invc IHxs; constructor).\n    econstructor.\n\nsimpl in *. unfold bind_option in *.\ndestruct (f a) eqn:?, (f' a) eqn:?; try destruct u.\ndestruct (map_opt f xs), (map_checked _ _); try destruct u.\n  *)\n\nLemma map_checked_numbered'_inl : forall A (f : A -> _) xs n,\n    map_checked f xs = inl tt ->\n    map_checked (check_numbered_record f) (numbered' n xs) = inl tt.\ninduction xs; intros0 Hmap; simpl in *.  { auto. }\ndestruct (f a), (map_checked f xs) eqn:?;\n(repeat on unit, fun H => destruct H); try discriminate.\nrewrite IHxs; eauto.\nQed.\n\nLemma map_checked_numbered_inl : forall A (f : A -> _) xs,\n    map_checked f xs = inl tt ->\n    map_checked (check_numbered_record f) (numbered xs) = inl tt.\nunfold numbered. intros. eapply map_checked_numbered'_inl; eauto.\nQed.\n\nLemma map_checked_numbered'_inr : forall A (f : A -> _) xs n err,\n    map_checked f xs = inr err ->\n    exists err',\n        map_checked (check_numbered_record f) (numbered' n xs) = inr err'.\ninduction xs; intros0 Hmap; simpl in *.  { discriminate. }\ndestruct (f a), (map_checked f xs) eqn:?;\n(repeat on unit, fun H => destruct H); try discriminate.\n- destruct (IHxs (S n) ?? ***) as (? & Heq). rewrite Heq. eauto.\n- break_match; try destruct u; eauto.\n- break_match; try destruct u; eauto.\nQed.\n\nLemma map_checked_numbered_inr : forall A (f : A -> _) xs err,\n    map_checked f xs = inr err ->\n    exists err',\n        map_checked (check_numbered_record f) (numbered xs) = inr err'.\nunfold numbered. intros. eapply map_checked_numbered'_inr; eauto.\nQed.\n\nLemma type_database_program'_checked_correct : forall dbt udp,\n    results_match (type_database_program' dbt udp)\n                  (type_database_program'_checked dbt udp).\nintros. unfold type_database_program', type_database_program'_checked.\nassert (HH : results_match\n        (map_opt (type_record_uprogram dbt) udp)\n        (map_checked (type_record_uprogram_checked dbt) udp)).\n  { eapply map_checked_correct. eapply type_record_uprogram_checked_correct. }\n\neapply results_match_chain' with (5 := HH); eauto.\n- eapply map_checked_numbered_inl.\n- eapply map_checked_numbered_inr.\nQed.\n\nLemma type_database_program_checked_correct : forall udp,\n    results_match (type_database_program udp)\n                  (type_database_program_checked udp).\nintros. unfold type_database_program, type_database_program_checked.\neapply type_database_program'_checked_correct.\nQed.\n\n\nDefinition unwrap_matched_results {A} x y :\n    @results_match A x y ->\n    A + type_error.\nintro Hrm.\nrefine (\n    match x as x_, y as y_ return x = x_ -> y = y_ -> _ with\n    | Some val, inl tt => fun _ _ => inl val\n    | None, inr err => fun _ _ => inr err\n    | _, _ => fun Heq1 Heq2 => _\n    end eq_refl eq_refl\n); hide; exfalso; subst; invc Hrm.\nDefined.\nImplicit Arguments unwrap_matched_results [A].\n\nLemma unwrap_matched_results_inl : forall A x y pf val,\n    @unwrap_matched_results A x y pf = inl val ->\n    x = Some val.\nintros0 Hunwrap.\nunfold unwrap_matched_results in Hunwrap.\ndestruct x, y; (repeat on unit, fun u => destruct u); try solve [discriminate | invc pf].\ncongruence.\nQed.\n\n\nDefinition type_database_program_with_check udp :=\n    unwrap_matched_results\n        (type_database_program udp)\n        (type_database_program_checked udp)\n        ltac:(eauto using type_database_program_checked_correct).\n\nLemma type_database_program_with_check_inl_eq udp dbp :\n    type_database_program_with_check udp = inl dbp ->\n    type_database_program udp = Some dbp.\nunfold type_database_program_with_check. eapply unwrap_matched_results_inl.\nQed.\n", "meta": {"author": "HazardousPeach", "repo": "neutrons-bench", "sha": "447b1066142ceee607ba595d04c43c03089ce6f4", "save_path": "github-repos/coq/HazardousPeach-neutrons-bench", "path": "github-repos/coq/HazardousPeach-neutrons-bench/neutrons-bench-447b1066142ceee607ba595d04c43c03089ce6f4/semantics/v1/StepAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.246198737574728}}
{"text": "(** \n Verified SAR-BP: A verified C implementation of SAR backprojection\n with a certified absolute error bound.\n \n Version 1.0 (2015-12-04)\n \n Copyright (C) 2015 Reservoir Labs Inc.\n All rights reserved.\n \n This file is free software. You can redistribute it and/or modify it\n under the terms of the GNU General Public License as published by the\n Free Software Foundation, either version 3 of the License (GNU GPL\n v3), or (at your option) any later version.  A verbatim copy of the\n GNU GPL v3 is included in gpl-3.0.txt.\n \n This file is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See LICENSE for\n more details about the use and redistribution of this file and the\n whole Verified SAR-BP library.\n \n This work is sponsored in part by DARPA MTO as part of the Power\n Efficiency Revolution for Embedded Computing Technologies (PERFECT)\n program (issued by DARPA/CMO under Contract No: HR0011-12-C-0123). The\n views and conclusions contained in this work are those of the authors\n and should not be interpreted as representing the official policies,\n either expressly or implied, of the DARPA or the\n U.S. Government. Distribution Statement \"A\" (Approved for Public\n Release, Distribution Unlimited.)\n \n \n If you are using or modifying Verified SAR-BP in your work, please\n consider citing the following paper:\n \n Tahina Ramananandro, Paul Mountcastle, Benoit Meister and Richard\n Lethin.\n A Unified Coq Framework for Verifying C Programs with Floating-Point\n Computations.\n In CPP (5th ACM/SIGPLAN conference on Certified Programs and Proofs)\n 2016.\n \n \n Verified SAR-BP derives from prior work listed in ACKS along with\n their copyright and licensing information.\n \n Verified SAR-BP requires third-party libraries listed in ACKS along\n with their copyright information.\n*)\n(**\nAuthor: Tahina Ramananandro <ramananandro@reservoir.com>\n\nBounds for small images. Those bounds have been extracted from the\nDARPA PERFECT suite ( http://hpc.pnl.gov/PERFECT/ )\n*)\n\nRequire Import ZArith RAux.\nRequire Flocq.Core.Fcore_Raux.\nDefinition abs_data_border: R := (16231879/4294967296)%R .\nDefinition abs_data_min: R := (6115167/4503599627370496)%R .\nDefinition abs_data_max: R := (4194091/4194304)%R .\nDefinition abs_data_dist: R := (2873621/16777216)%R .\n\nDefinition platpos_x_min: R := (7227795/1024)%R .\nDefinition platpos_x_max: R := (14481547/2048)%R. \n\nDefinition platpos_y_min: R := (0)%R .\nDefinition platpos_y_max: R := (13866841/32768)%R. \n\nDefinition platpos_z_min: R := (14481547/2048)%R .\nDefinition platpos_z_max: R := (14481547/2048)%R. \n\nDefinition dxdy := Eval compute in (4503599627370496 * / Fcore_Raux.Z2R (2 ^ 54))%R. \nDefinition dR := Eval compute in (4503599627370496 * / Fcore_Raux.Z2R (2 ^ 57))%R.\nDefinition N_PULSES := (512)%nat .\nDefinition N_RANGE := (512)%Z .\nDefinition N_RANGE_UPSAMPLED := (4096)%Z .\nDefinition BP_NPIX_Y := (512)%nat .\nDefinition BP_NPIX_X := (512)%nat .\nDefinition ku := Eval compute in (7368997658362958 * / Fcore_Raux.Z2R (2 ^ 45))%R. \n(*\nDefinition z0 := Eval compute in (0 * / R_of_Z (2 ^ 1074))%R. \n*)\nDefinition z0_low := 0%R.\nDefinition z0_high := 0%R.\nDefinition R0 := Eval compute in (5462373766791168 * / Fcore_Raux.Z2R (2 ^ 39))%R.\n", "meta": {"author": "wuweh", "repo": "vsarbp", "sha": "8e4ca028ec8a73eb7f2fd27892a69971384cada5", "save_path": "github-repos/coq/wuweh-vsarbp", "path": "github-repos/coq/wuweh-vsarbp/vsarbp-8e4ca028ec8a73eb7f2fd27892a69971384cada5/sar_sizes/small/SARBounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.24616638976170704}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import TableWalk.Spec.\nRequire Import AbsAccessor.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition data_destroy_spec0 (g_rd: Pointer) (map_addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match g_rd, map_addr with\n    | (_g_rd_base, _g_rd_ofst), VZ64 _map_addr =>\n      rely is_int (4 - 1);\n      rely is_int64 _map_addr;\n      rely is_int64 (4 - 1);\n      when adt == table_walk_lock_unlock_spec (_g_rd_base, _g_rd_ofst) (VZ64 _map_addr) (VZ64 (4 - 1)) adt;\n      when'' _g_llt_base, _g_llt_ofst == get_wi_g_llt_spec  adt;\n      rely is_int _g_llt_ofst;\n      when' _index == get_wi_index_spec  adt;\n      rely is_int64 _index;\n      when _t'7 == is_null_spec (_g_llt_base, _g_llt_ofst) adt;\n      rely is_int _t'7;\n      if (_t'7 =? 1) then\n        let _ret := 1 in\n        Some (adt, (VZ64 _ret))\n      else\n        when'' _ll_table_base, _ll_table_ofst, adt == granule_map_spec (_g_llt_base, _g_llt_ofst) 5 adt;\n        rely is_int _ll_table_ofst;\n        when' _pte_val == pgte_read_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) adt;\n        rely is_int64 _pte_val;\n        rely is_int64 (Z.land _pte_val 504403158265495552);\n        rely is_int64 ((Z.land _pte_val 504403158265495552) / 72057594037927936);\n        let _ipa_state := ((Z.land _pte_val 504403158265495552) / 72057594037927936) in\n        if (negb (_ipa_state =? 1)) then\n          let _ret := 1 in\n          when adt == buffer_unmap_spec (_ll_table_base, _ll_table_ofst) adt;\n          when adt == granule_unlock_spec (_g_llt_base, _g_llt_ofst) adt;\n          Some (adt, (VZ64 _ret))\n        else\n          rely is_int64 (Z.land _pte_val 281474976706560);\n          let _data_addr := (Z.land _pte_val 281474976706560) in\n          rely is_int64 _data_addr;\n          when'' _g_data_base, _g_data_ofst, adt == find_lock_granule_spec (VZ64 _data_addr) (VZ64 4) adt;\n          rely is_int _g_data_ofst;\n          when _t'6 == is_null_spec (_g_data_base, _g_data_ofst) adt;\n          rely is_int _t'6;\n          if (_t'6 =? 1) then\n            let _ret := 1 in\n            when adt == buffer_unmap_spec (_ll_table_base, _ll_table_ofst) adt;\n            when adt == granule_unlock_spec (_g_llt_base, _g_llt_ofst) adt;\n            Some (adt, (VZ64 _ret))\n          else\n            rely is_int64 (3 * 72057594037927936);\n            let _pte_val := (3 * 72057594037927936) in\n            when adt == pgte_write_spec (_ll_table_base, _ll_table_ofst) (VZ64 _index) (VZ64 _pte_val) adt;\n            when adt == granule_put_spec (_g_llt_base, _g_llt_ofst) adt;\n            when adt == granule_memzero_spec (_g_data_base, _g_data_ofst) 1 adt;\n            when adt == granule_set_state_spec (_g_data_base, _g_data_ofst) 1 adt;\n            when adt == granule_unlock_spec (_g_data_base, _g_data_ofst) adt;\n            let _ret := 0 in\n            when adt == buffer_unmap_spec (_ll_table_base, _ll_table_ofst) adt;\n            when adt == granule_unlock_spec (_g_llt_base, _g_llt_ofst) adt;\n            Some (adt, (VZ64 _ret))\n     end\n    .\n\nEnd SpecLow.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsIntro/LowSpecs/data_destroy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.3738758157951908, "lm_q1q2_score": 0.24616638015632974}}
{"text": "Require Import Target.\nRequire Import Shape.\nRequire Import Compiler.\n\n(* _____________________________________ \n                  SYNTAX\n   _____________________________________ *)\n\nInductive origin : Type :=\n  | ContextOrigin : origin\n  | ProgramOrigin : origin.\n\nInductive external_action : Type :=\n  | ExtCall : component_id -> procedure_id -> registers -> \n    external_action\n  | ExtRet : registers -> external_action\n  | End : external_action.\n\nNotation \"✓\" := (End).\n\nInductive internal_action : Type :=\n  | IntTau : internal_action\n  | IntCall : component_id -> procedure_id -> internal_action\n  | IntRet : internal_action.\n\nInductive action : Type :=\n  | Ext : external_action -> origin -> action\n  | Int : internal_action -> origin -> action.\n\nDefinition trace : Type := list action.\n\n\n(* _____________________________________ \n                  STATES\n   _____________________________________ *)\n\nDefinition sigma :=\n  list (component_id * nat).\n\nDefinition A_sigma :=\n  list (component_id).\n\nInductive alt_list (A B : Type) : Type :=\n  | alt_init : A -> alt_list A B\n  | alt_cons : A -> alt_list B A -> alt_list A B.\n\nDefinition A_SIGMA : Type :=\n  alt_list A_sigma sigma.\n\nDefinition P_SIGMA : Type :=\n  alt_list sigma A_sigma.\n\nDefinition program_state : Type :=\n  (component_id *\n   P_SIGMA *\n   global_memory *\n   registers *\n   address).\n\nDefinition context_state : Type :=\n  (component_id *\n   A_SIGMA *\n   global_memory).\n\nInductive state_partial_view : Type :=\n  | ProgramControl : program_state -> state_partial_view\n  | ContextControl : context_state -> state_partial_view\n  | EXITED.\n\n(* ------- Definitions : Extra notations ------- *)\n\nDefinition Top {A B : Type} (E:alt_list A B) : A :=\n  match E with\n  | alt_init _ _ h => h \n  | alt_cons _ _ h t => h\n  end.\n\nDefinition SetTop {A B : Type} (E:alt_list A B) (new:A)\n  : alt_list A B :=\n  match E with\n  | alt_init _ _ h => alt_init A B new\n  | alt_cons _ _ h t => alt_cons A B new t \n  end.\n\n\n(* _____________________________________ \n                REDUCTIONS\n   _____________________________________ *)\n\nInductive reduction (Is:partial_program_interfaces) (E:entry_points) : \n  state_partial_view -> state_partial_view -> action -> Prop :=\n  (* T_CallRetTau+ *)\n  | T_CallRetTauPlus :\n    forall C C' d d' mem mem' reg reg' pc pc' o o' PE PE',\n    let action := fun cfg =>\n      match cfg with\n      | (C,d,mem,reg,pc) =>\n        match decode (fetch_mem C mem pc) with\n        | Some (Target.Call C0 P0) => Int (IntCall C0 P0) ProgramOrigin\n        | Some Return => Int IntRet ProgramOrigin \n        | _ => Int IntTau ProgramOrigin\n        end\n      end\n    in \n    (Top PE = o) -> (PE' = SetTop PE o') ->\n    step Is E (C,d,mem,reg,pc) (C',d',mem',reg',pc') ->\n    reduction Is E \n      (ProgramControl (C,PE,mem,reg,pc)) \n      (ProgramControl (C',PE',mem',reg',pc'))\n      (action (C,d,mem,reg,pc))\n  (* T_TauMinus- *)\n  | T_TauMinus : forall C AE mem,\n    reduction Is E \n      (ContextControl (C, AE, mem)) \n      (ContextControl (C, AE, mem)) \n      (Int IntTau ContextOrigin)\n  (* T_Call- *)\n  | T_CallMinus : forall C C' P' AE AE' Ao mem,\n    (component_defined C (option interface) Is = true) ->\n    (match (nth C Is None) with\n    | Some i => In (C', P') (get_import i) \n    | None => False\n    end)\n    \\/ (C' = C) ->\n    ~(In (Some C') (dom_entry_points E)) -> (Top AE = Ao) ->\n    (AE' = SetTop AE (C::Ao)) ->\n    reduction Is E \n      (ContextControl (C, AE, mem))\n      (ContextControl (C', AE',mem)) \n      (Int (IntCall C' P') ContextOrigin)\n  (* T_Ret- *)\n  | T_RetMinus : forall C C' AE AE' o mem,\n    (C'::o = Top AE) -> (AE' = SetTop AE o) ->\n    reduction Is E\n      (ContextControl (C, AE, mem))\n      (ContextControl (C', AE', mem))\n      (Int IntRet ContextOrigin)\n  (* T_Call? *)\n  | T_CallCtx : forall C C' P' AE AE' Ao reg mem,\n    (component_defined C (option interface) Is = true) ->\n    (match (nth C Is None) with\n    | Some i => In (C',P') (get_import i)\n    | None => False\n    end)\n    ->\n    (In (Some C') (dom_entry_points E)) -> (Top AE = Ao) ->\n    (AE' = SetTop AE (C::Ao)) ->\n    reduction Is E \n    (ContextControl (C,AE,mem))\n    (ProgramControl (C',(alt_cons sigma A_sigma [] AE'),\n      mem,reg,fetch_entry_points C' P' E))\n        (Ext (ExtCall C' P' reg) ContextOrigin)\n  (* T_Ret? *)\n  | T_RetCtx : forall C C' pc o PE PE' reg mem,\n    (Top PE = (C',pc)::o) -> (PE' = SetTop PE o) ->\n    reduction Is E \n    (ContextControl (C, (alt_cons A_sigma sigma [] PE), mem))\n    (ProgramControl (C',PE',mem,reg,pc))\n      (Ext (ExtRet reg) ContextOrigin)\n  (* T_Call! *)\n  | T_CallPrg : forall C C' P' o PE PE' mem reg pc i,\n    (fetch_mem C mem pc = i) -> (decode i = Some (Target.Call C' P')) ->\n    (component_defined C (option interface) Is = true) ->\n    (match (nth C Is None) with\n    | Some i => (In (C',P') (get_import i))\n    | None => False\n    end)\n    ->\n    ~(In (Some C') (dom_entry_points E)) -> (Top PE = o) ->\n    (PE' = SetTop PE ((C,pc+1)::o)) ->\n    reduction Is E\n    (ProgramControl (C,PE,mem,reg,pc))\n    (ContextControl (C',(alt_cons A_sigma sigma [] PE'),mem))\n      (Ext (ExtCall C' P' reg) ProgramOrigin)\n  (* T_Ret! *)\n  | T_RetPrg : forall C C' Ao AE AE' i pc mem reg,\n    (fetch_mem C mem pc = i) -> (decode i = Some Return) ->\n    (Top AE = C'::Ao) -> (AE' = SetTop AE Ao) ->\n    reduction Is E \n    (ProgramControl (C,(alt_cons sigma A_sigma [] AE),mem,reg,pc))\n    (ContextControl (C',AE',mem))\n      (Ext (ExtRet reg) ProgramOrigin)\n  (* T_Exit? *)\n  | T_ExitCtx : forall C AE mem,\n    reduction Is E\n    (ContextControl (C,AE,mem)) EXITED (Ext End ContextOrigin)\n  (* T_Exit! *)\n  | T_ExitPrg : forall theta C PE mem reg pc,\n    (forall alpha, (alpha <> (Ext End ProgramOrigin) ->\n      reduction Is E (ProgramControl(C,PE,mem,reg,pc)) theta alpha)) ->\n    reduction Is E\n    (ProgramControl (C,PE,mem,reg,pc)) EXITED (Ext End ProgramOrigin).\n\n\n(* _____________________________________ \n          INITIAL TRACE STATES\n   _____________________________________ *)\n\nDefinition initial_trace_state (P:Target.program) : \n  state_partial_view :=\n  match P with\n  | (Is, mem, E) =>\n    let CS_PRG := (alt_init sigma A_sigma []) in\n    let CS_CTX := (alt_init A_sigma sigma []) in\n    let f x :=\n      match x with\n      | Some x' => main_cid =? x'\n      | None => false\n      end\n    in\n    if existsb f (dom_entry_points E) then\n      ProgramControl (main_cid, CS_PRG, mem, g_regs, \n        fetch_entry_points main_cid 0 E)\n    else\n      ContextControl (main_cid, CS_CTX, mem)\n  end.\n\n\n(* _____________________________________ \n            TRACE DUALIZATION\n   _____________________________________ *)\n\nDefinition dual_trace (T:trace) :=\n  let f :=\n    (fun alpha =>\n     match alpha with\n     | Int ia ProgramOrigin => Int ia ContextOrigin\n     | Int ia ContextOrigin => Int ia ProgramOrigin\n     | Ext ea ProgramOrigin => Ext ea ContextOrigin\n     | Ext ea ContextOrigin => Ext ea ProgramOrigin\n     end) in\n  map f T.\n\n\n(* _____________________________________ \n            ACTION COMPOSITION\n   _____________________________________ *)\n\nInductive reduction_multi (Is:partial_program_interfaces) (E:entry_points) :\n  state_partial_view -> state_partial_view -> trace -> Prop :=\n  (* T_Refl *)\n  | T_Refl : forall o o', \n    reduction_multi Is E o o' []\n  (* T_Internal *)\n  | T_Internal : forall o o' Ia origin,\n    reduction Is E o o' (Int Ia origin) ->\n    reduction_multi Is E o o' []\n  (* T_Cross *)\n  | T_Cross : forall o o' Ea origin,\n    reduction Is E o o' (Ext Ea origin) ->\n    reduction_multi Is E o o' [Ext Ea origin]\n  (* T_Trans *)\n  | T_Trans : forall o o' o'' t u,\n    reduction_multi Is E o o' [t] ->\n    reduction_multi Is E o' o'' [u] ->\n    reduction_multi Is E o o'' ([t]++[u]).\n\n\n(* _____________________________________ \n       INFERENCE RULES FOR CONTEXT\n   _____________________________________ *)\n\nInductive reduction_duality (Is:partial_program_interfaces) (E:entry_points) :\n  state_partial_view -> state_partial_view -> trace -> Prop := \n  | T_Dual : forall o o' t,\n    reduction_multi Is E o o' (dual_trace t) ->\n    reduction_duality Is E o o' t.\n\n(* _____________________________________ \n              TRACE SETS\n   _____________________________________ *)\n\n(* Defined as a binary relation *)\n\nDefinition in_Traces_p (t:trace) (p:Target.program) (s:shape) : \n  Prop :=\n  match p with\n  | (_, mem_p, E_p) =>\n    match s with\n    | (Is, _) => exists O, \n    reduction_multi (normalize_Is Is) E_p (initial_trace_state p) O t\n    end \n  end.\n\nDefinition in_Traces_a (t:trace) (a:Target.program) (s:shape) : \n  Prop :=\n  match a with\n  | (_, mem_a, E_a) =>\n    match s with\n    | (Is, _) => exists O, \n    reduction_multi (normalize_Is Is) E_a (initial_trace_state a) O t\n    end \n  end.\n\n\n(* _____________________________________ \n       TRACES WITH INTERNAL ACTIONS\n   _____________________________________ *)\n\nFixpoint erase (t:trace) : trace :=\n  match t with\n  | [] => []\n  | (Int _ _)::t => erase t\n  | (Ext Ea origin)::t =>\n    (Ext Ea origin) :: (erase t)\n  end.\n\n\n(* _____________________________________ \n         TRACE CANONICALIZATION\n   _____________________________________ *)\n\nDefinition zeta_gamma (Ea:external_action) : external_action :=\n  match Ea with\n  | ExtCall C P reg => ExtCall C P (clear_regs reg)\n  | ExtRet reg => ExtRet (clear_regs reg) \n  | End => End\n  end.\n\nDefinition zetaC_Ea (a:action) : action :=\n  match a with\n  | Ext gamma ContextOrigin => Ext (zeta_gamma gamma) ContextOrigin\n  | _ => a\n  end.\n\nFixpoint zetaC_t (t:trace) : trace :=\n  match t with\n  | [] => []\n  | (Ext g ContextOrigin)::t' => \n    (zetaC_Ea (Ext g ContextOrigin))::(zetaC_t t')\n  | h::t' => h :: (zetaC_t t')\n  end.\n\nFixpoint zetaC_T (T:trace) : trace :=\n  match T with\n  | [] => []\n  | (Ext g ContextOrigin)::T' => (zetaC_Ea (Ext g ContextOrigin))::(zetaC_T T')\n  | (Int g ContextOrigin)::T' => (Int g ContextOrigin)::(zetaC_T T')\n  | H::T' => H :: (zetaC_T T')\n  end.\n\nDefinition zetaP_Ea (a:action) : action :=\n  match a with\n  | Ext gamma ProgramOrigin => Ext (zeta_gamma gamma) ProgramOrigin\n  | _ => a\n  end.\n\nFixpoint zetaP_t (t:trace) : trace :=\n  match t with\n  | [] => []\n  | (Ext g ProgramOrigin)::t' => \n    (zetaP_Ea (Ext g ProgramOrigin))::(zetaP_t t')\n  | h::t' => h :: (zetaP_t t')\n  end.\n\nFixpoint zetaP_T (T:trace) : trace :=\n  match T with\n  | [] => []\n  | (Ext g ProgramOrigin)::T' => \n    (zetaP_Ea (Ext g ProgramOrigin))::(zetaP_T T')\n  | (Int g ProgramOrigin)::T' => \n    (Int g ProgramOrigin)::(zetaP_T T')\n  | _ => T\n  end.\n\n\n(* _____________________________________ \n            WELL-FORMEDNESS\n   _____________________________________ *)\n\nInductive wellformed_o (E:entry_points) : sigma -> Prop :=\n  | WF_Nil_o :\n    wellformed_o E []\n  | WF_Cons_o : forall o o' C pc,\n    (o = (C,pc)::o') -> (In (Some C) (dom_entry_points E)) ->\n    (wellformed_o E o') -> (wellformed_o E o).\n\nInductive wellformed_Ao (E:entry_points) : A_sigma -> Prop :=\n  | WF_Nil_Ao :\n    wellformed_Ao E []\n  | WF_Cons_Ao : forall C Ao Ao',\n    (Ao = C::Ao') -> ~(In (Some C) (dom_entry_points E)) ->\n    (wellformed_Ao E Ao') -> (wellformed_Ao E Ao).\n\nInductive wellformed_PE (E:entry_points) : P_SIGMA -> Prop :=\n  | WF_Init_PE : forall o PE,\n    PE = alt_init sigma A_sigma o -> wellformed_PE E PE\n  | WF_Cons_PE : forall PE AE h t o,\n    PE = alt_cons sigma A_sigma o AE ->\n    Top AE = h::t ->\n    wellformed_o E o -> wellformed_AE E AE ->\n    wellformed_PE E PE\nwith wellformed_AE (E:entry_points) : A_SIGMA -> Prop :=\n  | WF_Init_AE : forall AE Ao,\n    AE = alt_init A_sigma sigma Ao -> wellformed_AE E AE\n  | WF_Cons_AE : forall AE Ao h t PE,\n    AE = alt_cons A_sigma sigma Ao PE ->\n    Top PE = h::t ->\n    wellformed_Ao E Ao -> wellformed_PE E PE ->\n    wellformed_AE E AE.\n\nInductive wellformed_P0 (E:entry_points) : \n  program_state -> Prop :=\n  | WF_P0 : forall P0 PE C mem reg pc,\n    In (Some C) (dom_entry_points E) ->\n    (dom_global_memory mem = dom_entry_points E) -> \n    wellformed_PE E PE -> P0 = (C, PE, mem, reg, pc) ->\n    wellformed_P0 E P0.\n\nInductive wellformed_A0 (E:entry_points) :\n  context_state -> Prop :=\n  | WF_A0 : forall A0 AE C mem,\n    ~(In (Some C) (dom_entry_points E)) ->\n    (dom_global_memory mem = dom_entry_points E) ->\n    wellformed_AE E AE -> A0 = (C, AE, mem) ->\n    wellformed_A0 E A0.\n\n(* _____________________________________ \n              STATE MERGING\n   _____________________________________ *)\n\nInductive mergeable_Ao_o : A_sigma -> sigma -> Prop :=\n  | M_Ao_o_Nil :\n    mergeable_Ao_o [] []\n  | M_Ao_o_Cons : forall C Ao o i,\n    (mergeable_Ao_o Ao o) ->\n    mergeable_Ao_o (C::Ao) ((C,i)::o).\n\nInductive mergeable_PE_AE : P_SIGMA -> A_SIGMA -> Prop :=\n  | M_AEPE_Init : forall Ao o,\n    mergeable_Ao_o Ao o -> mergeable_PE_AE \n      (alt_init sigma A_sigma o) (alt_init A_sigma sigma Ao)\n  | M_AEPE_Cons : forall Ao o AE PE,\n    mergeable_Ao_o Ao o -> mergeable_PE_AE PE AE -> mergeable_PE_AE \n    (alt_cons sigma A_sigma o AE) (alt_cons A_sigma sigma Ao PE).\n\nFixpoint combine_alt {A B C: Type} (f: A -> B -> list C) \n  (e1: alt_list A B) (e2: alt_list B A) :=\n  match e1, e2 with\n  | alt_init _ _ h1, alt_init _ _ h2 => f h1 h2\n  | alt_cons _ _ h1 t1, alt_cons _ _ h2 t2 => \n    f h1 h2 ++ @combine_alt B A C (fun b a => f a b) t1 t2\n  | _, _ => []\n  end.\n\n(* Assuming they are mergeable *)\nDefinition merge (e1: P_SIGMA) (e2: A_SIGMA): sigma :=\n  combine_alt (fun (s:sigma) (a_s:A_sigma) => s) e1 e2.\n\nDefinition option_pair_dismatch\n  (p:option component_id * option component_id) : bool :=\n  match p with\n  | (Some _, None) => true\n  | (None, Some _) => true\n  | _ => false\n  end.\n\nDefinition comps_are_complements \n  (cs1 cs2 : list (option component_id)) : bool :=\n  fold_right andb true (map option_pair_dismatch (combine cs1 cs2)).\n\nInductive mergeable_P0_A0 : \n  program_state -> context_state -> Prop :=\n  | M_P0_A0 : forall PE AE C mem_p mem_a pc reg,\n    mergeable_PE_AE PE AE -> \n    (comps_are_complements\n      (dom_global_memory mem_p)\n      (dom_global_memory mem_a)) = true ->\n    mergeable_P0_A0 (C,PE,mem_p,reg,pc) (C,AE,mem_a).\n\nDefinition merge_P0A0 (P0:program_state) (A0:context_state) :\n  program_state :=  \n  match P0, A0 with\n  | (C, PE, mem_p, reg, pc), (_, AE, mem_a) =>\n    (C, alt_init sigma A_sigma (merge PE AE), \n     mem_p ++ mem_a, reg, pc)\n  end.\n\n(* _____________________________________ \n                PROPERTIES\n   _____________________________________ *)\n\nLemma trace_extensibility :\n  forall t s g,\n  forall p, (LL_PROGRAM_SHAPE p ∈• s) ->\n  forall a, (LL_CONTEXT_SHAPE a ∈∘ s) ->\n    ((in_Traces_p t p s) /\\ \n    (in_Traces_a (t++[Ext g ContextOrigin]) a s)\n    -> (in_Traces_p (t++[Ext g ContextOrigin]) p s))\n      /\\\n    ((in_Traces_a t a s) /\\ \n    (in_Traces_p (t++[Ext g ProgramOrigin]) p s)\n    -> (in_Traces_a (t++[Ext g ProgramOrigin]) a s)).\nProof.\nAdmitted.\n\nLemma trace_decomposition :\n  forall s,\n  forall p, (LL_PROGRAM_SHAPE p ∈• s) ->\n  forall a, (LL_CONTEXT_SHAPE a ∈∘ s) ->\n    cprogram_terminates (LL_context_application a p)\n      ->\n    (exists t, exists t' o, t = t'++[Ext End o] /\\\n    ((in_Traces_p t p s) /\\ (in_Traces_a t a s))).\nProof.\nAdmitted.\n\nLemma trace_composition :\n  forall t s,\n  forall p, (LL_PROGRAM_SHAPE p ∈• s) ->\n  forall a, (LL_CONTEXT_SHAPE a ∈∘ s) ->\n    ((in_Traces_p t p s) /\\ (in_Traces_a t a s)) ->\n    (forall Ea o, \n      ~((in_Traces_p (t++[Ext Ea o]) p s) /\\ \n      (in_Traces_a (t++[Ext Ea o]) a s))) ->\n    (cprogram_terminates (LL_context_application a p)\n      <->\n     exists t' o, t = t'++[Ext End o]).\nProof.\nAdmitted.\n\n\n\n", "meta": {"author": "secure-compilation", "repo": "beyond-good-and-evil", "sha": "b34143988c7b5aed47381a63a7df2fd506a65c65", "save_path": "github-repos/coq/secure-compilation-beyond-good-and-evil", "path": "github-repos/coq/secure-compilation-beyond-good-and-evil/beyond-good-and-evil-b34143988c7b5aed47381a63a7df2fd506a65c65/simple-instance-coq/TraceSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2461546467657137}}
{"text": "From Pony Require Import Language LocalMap.\n\nRequire Import Coq.FSets.FMapInterface.\nRequire Import Coq.Structures.Equalities.\n\nModule Context (Map : WSfun).\n\nExport Syntax.\n\nModule LocalMap := LocalMap Map.\nExport LocalMap.\n\nDefinition context : Type := (LocalMap.t aliasedType ponyType).\n\nDefinition sendableCtxt (gamma : context) : context :=\n  LocalMap.fold_var\n    (fun var varType sendableMap =>\n      match varType with\n      | aType _ b =>\n          if isSendable b\n            then LocalMap.addVar var varType sendableMap\n            else sendableMap\n      end)\n    gamma\n    (LocalMap.empty aliasedType ponyType).\n\nEnd Context.\n\nModule Typing (Map : WSfun).\n\nModule Program := Program Map.\nExport Program. \n\nModule Context := Context Map.\nImport Context.\n\nImport Context.LocalMap.\n\n(* Partial function - not defined for @tag@ *)\nDefinition viewAdapt\n  (objCap : capability)\n  (fieldCap : baseCapability) \n  : option capability :=\n  match objCap with\n  | base iso =>\n      match fieldCap with\n      | iso => Some (base iso)\n      | trn => Some (base iso)\n      | ref => Some (base iso)\n      | val => Some (base val)\n      | box => Some (base tag)\n      | tag => Some (base tag)\n      end\n  | base trn => \n      match fieldCap with\n      | iso => Some (base iso)\n      | trn => Some (base trn)\n      | ref => Some (base trn)\n      | val => Some (base val)\n      | box => Some (base box)\n      | tag => Some (base tag)\n      end\n  | base ref =>\n      match fieldCap with\n      | iso => Some (base iso)\n      | trn => Some (base trn)\n      | ref => Some (base ref)\n      | val => Some (base val)\n      | box => Some (base box)\n      | tag => Some (base tag)\n      end\n  | base val =>\n      match fieldCap with\n      | iso => Some (base val)\n      | trn => Some (base val)\n      | ref => Some (base val)\n      | val => Some (base val)\n      | box => Some (base val)\n      | tag => Some (base val)\n      end\n  | base box =>\n      match fieldCap with\n      | iso => Some (base tag)\n      | trn => Some (base box)\n      | ref => Some (base box)\n      | val => Some (base val)\n      | box => Some (base box)\n      | tag => Some (base tag)\n      end\n  | base tag => None\n  | isohat =>\n      match fieldCap with\n      | iso => Some isohat\n      | trn => Some isohat\n      | ref => Some isohat\n      | val => Some (base val)\n      | box => Some (base val)\n      | tag => Some (base tag)\n      end\n  | trnhat => \n      match fieldCap with\n      | iso => Some isohat\n      | trn => Some trnhat\n      | ref => Some trnhat\n      | val => Some (base val)\n      | box => Some (base val)\n      | tag => Some (base tag)\n      end\n  end.\n\n(* Partial function - not defined for @val@, @box@, @tag@ *)\nDefinition writeAdapt\n  (objCap : capability)\n  (fieldCap : baseCapability) \n  : option capability :=\n  match objCap with\n  | base iso =>\n      match fieldCap with\n      | iso => Some isohat\n      | trn => Some (base val)\n      | ref => Some (base tag)\n      | val => Some (base val)\n      | box => Some (base tag)\n      | tag => Some (base tag)\n      end\n  | base trn => \n      match fieldCap with\n      | iso => Some isohat\n      | trn => Some (base val)\n      | ref => Some (base box)\n      | val => Some (base val)\n      | box => Some (base box)\n      | tag => Some (base tag)\n      end\n  | base ref =>\n      match fieldCap with\n      | iso => Some isohat\n      | trn => Some trnhat\n      | ref => Some (base ref)\n      | val => Some (base val)\n      | box => Some (base box)\n      | tag => Some (base tag)\n      end\n  | base val => None\n  | base box => None\n  | base tag => None\n  | isohat =>\n      match fieldCap with\n      | iso => Some isohat\n      | trn => Some isohat\n      | ref => Some isohat\n      | val => Some (base val)\n      | box => Some (base val)\n      | tag => Some (base tag)\n      end\n  | trnhat => \n      match fieldCap with\n      | iso => Some isohat\n      | trn => Some trnhat\n      | ref => Some trnhat\n      | val => Some (base val)\n      | box => Some (base box)\n      | tag => Some (base tag)\n      end\n  end.\n\nInductive safeToWrite : capability -> baseCapability -> Prop :=\n  (* Write to an @iso@ *)\n  | safeToWrite_iso_iso : safeToWrite (base iso) iso\n  | safeToWrite_iso_val : safeToWrite (base iso) val\n  | safeToWrite_iso_tag : safeToWrite (base iso) tag\n  (* Write to a @trn@ *)\n  | safeToWrite_trn_iso : safeToWrite (base trn) iso\n  | safeToWrite_trn_trn : safeToWrite (base trn) trn\n  | safeToWrite_trn_val : safeToWrite (base trn) val\n  | safeToWrite_trn_tag : safeToWrite (base trn) tag\n  (* Write to a @ref@ *)\n  | safeToWrite_ref (b : baseCapability) : safeToWrite (base ref) b\n  (* Write to an @iso^@ *)\n  | safeToWrite_isohat (b : baseCapability) : safeToWrite isohat b\n  (* Write to a @trn^@ *)\n  | safeToWrite_trnhat (b : baseCapability) : safeToWrite trnhat b.\n\nExample safeToWrite_implies_writeAdapt_defined : forall k b, safeToWrite k b -> exists k', writeAdapt k b = Some k'.\nProof.\n  intros k b stw_k_b.\n  induction stw_k_b; try (compute; eauto).\n  (* Solve the three \"general\" cases, which take any value of b *)\n  induction b; try (compute; eauto).\n  induction b; try (compute; eauto).\n  induction b; try (compute; eauto).\n  Qed.\n \nReserved Notation \"g |- x : T ==> g'\" (at level 9, x at level 50, T at level 50).\n\nInductive typing { P : program } : context -> cw_encoding -> ponyType -> context -> Prop :=\n  (* Path rules *)\n  | path_var (gamma : context) (x : var) (aT : aliasedType) \n  : VarMapsTo x aT gamma \n      -> gamma |- (ePath (use x)) : asPonyType aT ==> gamma\n  | path_temp (gamma : context) (t : temp) (T : ponyType)\n  : TempMapsTo t T gamma\n      -> gamma |- (ePath (useTemp t)) : T ==> (removeTemp t gamma)\n  | path_consume (gamma : context) (x : var) (aT : aliasedType)\n  : VarMapsTo x aT gamma\n      -> gamma |- (ePath (consume x)) : hat aT ==> (removeVar x gamma)\n  | path_field (gamma gamma' : context) (p : path) (s s' : typeId) (k k'' : capability) (k' : baseCapability) (f : fieldId)\n  : gamma |- (ePath p) : (type s k) ==> gamma'\n      -> @fieldLookup P s f (aType s' k')\n      -> viewAdapt k k' = Some k''\n      -> gamma |- (eFieldOfPath (p, f)) : (type s' k'') ==> gamma'\n  (* The alias rule *)\n  | expr_alias (gamma gamma': context) (x : cw_encoding) (s : typeId) (k : capability) (b : baseCapability)\n  : gamma |- x : (type s k) ==> gamma'\n    -> (alias k <; base b)\n    -> gamma |- (eAlias x) : (type s (base b)) ==> gamma'\n  | expr_vardecl (gamma : context) (x : var) (aT : aliasedType)\n  : ~ VarIn x gamma\n      -> gamma |- (eExpr (varDecl x)) : asPonyType aT ==> (addVar x aT gamma)\n  | expr_localassign (gamma gamma' : context) (x : var) (r : rhs) (aT : aliasedType)\n  : gamma |- (eAlias (eRhs r)) : asPonyType aT ==> gamma\n    -> VarMapsTo x aT gamma'\n    -> gamma |- (eExpr (assign x (aliasOf r))) : hat aT ==> gamma'\n  | expr_tempassign (gamma gamma' : context) (t : temp) (pf : fieldOfPath) (T : ponyType)\n  : gamma |- (eFieldOfPath pf) : T ==> gamma'\n    -> gamma |- (eExpr (tempAssign t pf)) : T ==> (LocalMap.addTemp t T gamma')\n  | expr_fieldassign (gamma gamma' gamma'' : context) (p p' : path) (f : fieldId) (s s' : typeId) (k k' : capability) (b b' : baseCapability)\n  : gamma |- (eAlias (ePath p')) : (type s' (base b)) ==> gamma'\n      -> gamma' |- (ePath p) : (type s k) ==> gamma''\n      -> @fieldLookup P s f (aType s' b')\n      -> safeToWrite k b\n      -> (base b) <; (base b')\n      -> writeAdapt k b' = Some k'\n      -> gamma |- (eRhs (fieldAssign (p, f) (aliasOf p'))) : type s' k' ==> gamma''\n  | expr_funcall (gamma gamma' gamma'' : context) (p : path) (args : list (@aliased path)) (s : typeId) (b : baseCapability)\n      (mId : methodId) (mArgs : arrayVarMap aliasedType) (returnType : ponyType) (body : expressionSeq)\n  : @methodLookup P s mId (mDef b mArgs returnType body)\n    -> typing_list gamma (eAPaths args) (argValues mArgs) gamma'\n    -> gamma' |- (eAlias (ePath p)) : (type s (base b)) ==> gamma''\n    -> gamma |- (eRhs (methodCall (aliasOf p) mId args)) : returnType ==> gamma''\n  | expr_becall (gamma gamma' gamma'' : context) (p : path) (args : list (@aliased path)) (s : typeId)\n      (bId : behaviourId) (bArgs : arrayVarMap aliasedType) (body : expressionSeq)\n  : @behaviourLookup P s bId (bDef bArgs body)\n    -> typing_list gamma (eAPaths args) (argValues bArgs) gamma'\n    -> gamma' |- (eAlias (ePath p)) : (type s (base tag)) ==> gamma''\n    -> gamma |- (eRhs (behaviourCall (aliasOf p) bId args)) : (type s (base tag)) ==> gamma''\n  | expr_classcon (gamma gamma' : context) (args : list (@aliased path)) (c : classId)\n      (kId : constructorId) (cnArgs : arrayVarMap aliasedType) (body : expressionSeq)\n  : @constructorLookup P (inl c) kId (cnDef cnArgs body)\n    -> typing_list gamma (eAPaths args) (argValues cnArgs) gamma'\n    -> gamma |- (eRhs (constructorCall (inl c) kId args)) : (type (inl c) (base ref)) ==> gamma'\n  | expr_actorcon (gamma gamma' : context) (args : list (@aliased path)) (a : actorId)\n      (kId : constructorId) (cnArgs : arrayVarMap aliasedType) (body : expressionSeq)\n  : @constructorLookup P (inr a) kId (cnDef cnArgs body)\n    -> typing_list gamma (eAPaths args) (argValues cnArgs) gamma'\n    -> gamma |- (eRhs (constructorCall (inr a) kId args)) : (type (inr a) (base tag)) ==> gamma'\nwhere \"G |- x : T ==> G'\" := (typing G x T G')\nwith\ntyping_list { P : program } : context -> list cw_encoding -> list ponyType -> context -> Prop :=\n  | typing_list_nil (gamma : context)\n  : typing_list gamma nil nil gamma\n  | typing_list_cons (gamma gamma' gamma'' : context) (x : cw_encoding) (t : ponyType) (lx : list cw_encoding) (lt : list ponyType)\n  : gamma |- x : t ==> gamma'\n    -> typing_list gamma' lx lt gamma''\n    -> typing_list gamma (x :: lx) (t :: lt) gamma''.\n\nLemma typing_paths_func_on_type_and_outcome :\n  forall P : program,\n  forall gamma gamma' gamma'' : context,\n  forall p : path,\n  forall T T' : ponyType,\n  @typing P gamma (ePath p) T gamma'\n  -> @typing P gamma (ePath p) T' gamma''\n  -> T = T' /\\ gamma' = gamma''.\n  intros P gamma gamma' gamma'' p T T' p_type_T_gamma' p_type_T'_gamma''.\n  \n  destruct p as [ x | x | t ].\n  { inversion p_type_T_gamma' as [ _gamma0 _x0 aT p_mapsto_aT | | | | | | | | | | | | ].\n    inversion p_type_T'_gamma'' as [ _gamma1 _x1 aT' p_mapsto_aT' | | | | | | | | | | | | ].\n    assert (gamma' = gamma'') as ctxts_same by (transitivity gamma; auto).\n\n    split.\n    { enough (aT = aT') as aTs_equal.\n      rewrite <- aTs_equal. \n      reflexivity.\n\n      apply VarMapsTo_func with (m:=gamma') (var:=x).\n      assumption.\n      rewrite ctxts_same; assumption.\n    }\n    { assumption.\n    }\n  }\n  { inversion p_type_T_gamma' as [ | | _gamma0 _x0 aT p_mapsto_aT | | | | | | | | | | ].\n    inversion p_type_T'_gamma'' as [ | | _gamma1 _x1 aT' p_mapsto_aT' | | | | | | | | | | ].\n\n    assert (gamma' = gamma'') as ctxts_same by (transitivity (removeVar x gamma); auto).\n\n    split.\n    { enough (aT = aT') as aTs_equal.\n      rewrite <- aTs_equal.\n      reflexivity.\n\n      apply VarMapsTo_func with (m:=gamma) (var:=x); assumption.\n    }\n    { reflexivity.\n    }\n  }\n  { inversion p_type_T_gamma' as [ | _gamma0 _t0 _T0 t_mapsto_T | | | | | | | | | | | ].\n    inversion p_type_T'_gamma'' as [ | _gamma1 _t1 _T'0 t_mapsto_T' | | | | | | | | | | | ].\n    \n    split.\n    { apply TempMapsTo_func with (m:=gamma) (temp:=t); assumption.\n    }\n    { reflexivity.\n    }\n  }\n  Qed.\n\nLemma typing_func_on_type_and_outcome :\n  forall P : program,\n  forall gamma gamma' gamma'' : context,\n  forall x : cw_encoding,\n  forall T T' : ponyType,\n  @typing P gamma x T gamma'\n  -> @typing P gamma x T' gamma''\n  -> T = T' /\\ gamma' = gamma''.\nProof.\n  intros P gamma gamma' gamma'' x T T' x_type_T_gamma' x_type_T'_gamma''.\n  induction x as [ p | fp | x' IHx' | [] | [] ].\n  (* Case for paths is shown as a lemma *)\n  { apply typing_paths_func_on_type_and_outcome with (P:=P) (p:=p) (gamma:=gamma); assumption.\n  }\n  { inversion x_type_T_gamma' as [ | | | _gamma0 _gamma'0 p1 S1 S1' k1 k1' b1 f1 p1_typed_s1_k1 lookup_s1_f1_is_s1'_k1' viewadapt_k1_b1_k1' | | | | | | | | | ].\n    inversion x_type_T'_gamma'' as [ | | | _gamma1 _gamma'1 p2 S2 S2' k2 k2' b2 f2 p2_typed_s2_k2 lookup_s2_f2_is_s2'_k2' viewadapt_k2_b2_k2' | | | | | | | | | ].\n\n    assert (p1 = p2 /\\ f1 = f2) as [ paths_same fields_same ].\n    { assert ((p1, f1) = (p2, f2)) as fps_same by (transitivity fp; auto).\n      now inversion fps_same.\n    }\n\n    assert (type S1 k1 = type S2 k2 /\\ gamma' = gamma'') as [ paths_typed_same ctxts_same ].\n    { apply typing_paths_func_on_type_and_outcome with (P:=P) (p:=p1) (gamma:=gamma).\n      assumption.\n      rewrite paths_same.\n      assumption.\n    }\n\n    split.\n    { assert (S1' = S2' /\\ b1 = b2) as [ f_type_ids_same bs_same ].\n      { assert (aType S1' b1 = aType S2' b2) as aTypes_same.\n        { apply fieldLookup_func with (P:=P) (s:=S1) (f:=f1).\n          assumption.\n          rewrite fields_same.\n          assert (S1 = S2) as type_ids_same by (inversion paths_typed_same; auto).\n          rewrite type_ids_same.\n          assumption.\n        }\n        \n        now inversion aTypes_same.\n      }\n\n      enough (k1' = k2') as vAs_same.\n      rewrite f_type_ids_same.\n      rewrite vAs_same.\n      reflexivity.\n\n      assert (Some k1' = Some k2') as somes_eq.\n      { transitivity (viewAdapt k1 b1).\n        auto.\n        rewrite bs_same.\n        assert (k1 = k2) as ks_eq by (inversion paths_typed_same; auto).\n        rewrite ks_eq.\n        auto.\n      }\n\n      inversion somes_eq.\n      reflexivity.\n    }\n    { assumption.\n    }\n  }\n  { admit. (* TODO *)\n  }\n  { admit. (* TODO *)\n  }\n  { admit. (* TODO *)\n  }\n  { admit. (* TODO *)\n  }\n  { admit. (* TODO *)\n  }\n  { admit. (* TODO *)\n  }\n  { admit. (* TODO *)\n  }\n  { admit. (* TODO *)\n  }\n  { admit. (* TODO *)\n  }\n  Admitted. (* TODO: prove this helper lemma (v. obvious) *)\n\nEnd Typing.\n\nRequire Import Coq.MSets.MSetInterface.\n\nModule WFExpressions (Map : WSfun) (SetM : WSetsOn).\n\nModule Typing := Typing Map.\nExport Typing.\n\nImport Typing.Context.\n\nModule TempSet := SetM DecidableTemp.\nDefinition tempSet := TempSet.t.\n\nDefinition consumePath (p : path) : tempSet :=\n  match p with\n  | useTemp t => TempSet.singleton t\n  | _         => TempSet.empty\n  end.\n\nDefinition consumeRhs (r : rhs) : tempSet :=\n  match r with\n  | rhsPath p => consumePath p\n  | fieldAssign (p, _) (aliasOf p') => TempSet.union (consumePath p) (consumePath p')\n  | methodCall (aliasOf rcvr) _ args =>\n      fold_left \n        (fun consumed ap =>\n          match ap with\n          | aliasOf p => TempSet.union consumed (consumePath p)\n          end\n        )\n        args\n        (consumePath rcvr)\n  | behaviourCall (aliasOf rcvr) _ args =>\n      fold_left \n        (fun consumed ap =>\n          match ap with\n          | aliasOf p => TempSet.union consumed (consumePath p)\n          end\n        )\n        args\n        (consumePath rcvr)\n  | constructorCall _ _ args =>\n      fold_left \n        (fun consumed ap =>\n          match ap with\n          | aliasOf p => TempSet.union consumed (consumePath p)\n          end\n        )\n        args\n        TempSet.empty\n  end.\n\n\nDefinition consumeExpr (e : expression) : tempSet :=\n  match e with\n  | varDecl _ => TempSet.empty\n  | assign _ (aliasOf r) => consumeRhs r\n  | tempAssign _ (p, _) => consumePath p\n  end.\n\nInductive well_formed_expr { P : program } : context -> expressionSeq -> ponyType -> Prop :=\n  | wf_return (gamma gamma' : context) (p : path) (t : ponyType)\n  : @typing P gamma (ePath p) t gamma'\n    -> well_formed_expr gamma (final p) t\n  | wf_vardecl (gamma gamma' : context) (x : var) (E : expressionSeq) (t t' : ponyType)\n  : @typing P gamma (eExpr (varDecl x)) t' gamma'\n    -> well_formed_expr gamma' E t\n    -> well_formed_expr gamma (seq (varDecl x) E) t\n  | wf_localassign (gamma gamma' : context) (x : var) (arhs : @aliased rhs) (E : expressionSeq) (t t' : ponyType)\n  : @typing P gamma (eExpr (assign x arhs)) t' gamma'\n    -> well_formed_expr gamma' E t\n    -> well_formed_expr gamma (seq (assign x arhs) E) t\n  | wf_tempassign_final (gamma gamma' : context) (t : temp) (pf : fieldOfPath) (p : path) (T T' : ponyType)\n  : @typing P gamma (eExpr (tempAssign t pf)) T' gamma'\n    -> well_formed_expr gamma' (final p) T\n    -> well_formed_expr gamma (seq (tempAssign t pf) (final p)) T\n  | wf_tempassign (gamma gamma' : context) (t : temp) (pf : fieldOfPath) (e : expression) (E : expressionSeq) (T T' : ponyType)\n  : @typing P gamma (eExpr (tempAssign t pf)) T' gamma'\n    -> TempSet.In t (consumeExpr e)\n    -> well_formed_expr gamma' (seq e E) T\n    -> well_formed_expr gamma (seq (tempAssign t pf) (seq e E)) T.\n\n(* For some method arguments, produce the corresponding typing context *)\nDefinition argsToContext (args : arrayVarMap aliasedType) : context :=\n  ArrayVarMap.fold\n    (fun key val ctxt => LocalMap.addVar key val ctxt)\n    args\n    (LocalMap.empty aliasedType ponyType).\n\nDefinition well_formed_constructor_def { P : program }\n  (thisType : aliasedType) (kD : constructorDef) : Prop\n  := forall args body, kD = cnDef args body\n        -> exists (t : ponyType),\n            @well_formed_expr P\n              (LocalMap.addVar this thisType (argsToContext args))\n              body\n              t.\n\nDefinition well_formed_method_def { P : program }\n  (thisTypeId : typeId) (mD : methodDef) : Prop\n  := forall rcvrCap args returnType body, mD = mDef rcvrCap args returnType body\n        -> @well_formed_expr P\n            (LocalMap.addVar this (aType thisTypeId rcvrCap) (argsToContext args))\n            body\n            returnType.\n\nDefinition well_formed_behaviour_def { P : program }\n  (thisTypeId : actorId) (bD : behaviourDef) : Prop\n  := forall args body, bD = bDef args body\n        -> exists (t : ponyType),\n            @well_formed_expr P\n              (LocalMap.addVar this (aType (inr thisTypeId) iso) (argsToContext args))\n              body\n              t.\n\nDefinition well_formed_class { P : program } (c : classId) : Prop :=\n  (forall k kD, @constructorLookup P (inl c) k kD -> @well_formed_constructor_def P (aType (inl c) ref) kD)\n  /\\\n  (forall m mD, @methodLookup P (inl c) m mD -> @well_formed_method_def P (inl c) mD).\n\nDefinition well_formed_actor { P : program } (a : actorId) : Prop :=\n  (forall k kD, @constructorLookup P (inr a) k kD -> @well_formed_constructor_def P (aType (inr a) iso) kD)\n  /\\\n  (forall m mD, @methodLookup P (inr a) m mD -> @well_formed_method_def P (inr a) mD)\n  /\\\n  (forall b bD, @behaviourLookup P (inr a) b bD -> @well_formed_behaviour_def P a bD).\n\nDefinition well_formed_program (P : program) : Prop :=\n  (forall a : actorId, @well_formed_actor P a)\n  /\\ (forall c : classId, @well_formed_class P c).\n\nEnd WFExpressions.\n", "meta": {"author": "ivanbakel", "repo": "minimal-pony-coq", "sha": "24b04deeea4f7a664edd5c17b3c545355e1425b1", "save_path": "github-repos/coq/ivanbakel-minimal-pony-coq", "path": "github-repos/coq/ivanbakel-minimal-pony-coq/minimal-pony-coq-24b04deeea4f7a664edd5c17b3c545355e1425b1/src/Typing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2461546467657137}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\nRequire Export Coq.Logic.ConstructiveEpsilon.\nRequire Export stronger_continuity_defs.\nRequire Export stronger_continuity_defs0.\nRequire Export per_props_atom.\nRequire Export terms5.\nRequire Export per_props_nat2.\n\n\nLemma equality_mkc_union_tnat_unit {o} :\n  forall lib (a b : @CTerm o),\n    equality lib a b (mkc_union mkc_tnat mkc_unit)\n    <=>\n    ({k : nat\n      , ccequivc lib a (mkc_inl (mkc_nat k))\n      # ccequivc lib b (mkc_inl (mkc_nat k))}\n     {+}\n     (ccequivc lib a (mkc_inr mkc_axiom)\n      # ccequivc lib b (mkc_inr mkc_axiom))).\nProof.\n  introv.\n  rw @equality_mkc_union.\n  split; intro k; exrepnd; repndors; exrepnd; spcast; dands; eauto 3 with slow.\n\n  - allrw @equality_in_tnat.\n    allunfold @equality_of_nat; exrepnd; spcast.\n    left.\n    exists k; dands; spcast.\n    + eapply cequivc_trans;[apply computes_to_valc_implies_cequivc; exact k2|].\n      apply cequivc_mkc_inl_if.\n      apply computes_to_valc_implies_cequivc; auto.\n    + eapply cequivc_trans;[apply computes_to_valc_implies_cequivc; exact k4|].\n      apply cequivc_mkc_inl_if.\n      apply computes_to_valc_implies_cequivc; auto.\n\n  - allrw @equality_in_unit; repnd; spcast.\n    right; dands; spcast.\n    + eapply cequivc_trans;[apply computes_to_valc_implies_cequivc; exact k2|].\n      apply cequivc_mkc_inr_if.\n      apply computes_to_valc_implies_cequivc; auto.\n    + eapply cequivc_trans;[apply computes_to_valc_implies_cequivc; exact k4|].\n      apply cequivc_mkc_inr_if.\n      apply computes_to_valc_implies_cequivc; auto.\n\n  - left.\n    apply cequivc_sym in k2; apply cequivc_mkc_inl_implies in k2.\n    apply cequivc_sym in k1; apply cequivc_mkc_inl_implies in k1.\n    exrepnd.\n    exists b1 b0; dands; spcast; auto.\n    eapply equality_respects_cequivc_left;[exact k4|].\n    eapply equality_respects_cequivc_right;[exact k3|].\n    apply equality_in_tnat.\n    unfold equality_of_nat.\n    exists k0; dands; spcast; auto;\n    apply computes_to_valc_refl; eauto 3 with slow.\n\n  - right.\n    apply cequivc_sym in k0; apply cequivc_mkc_inr_implies in k0.\n    apply cequivc_sym in k; apply cequivc_mkc_inr_implies in k.\n    exrepnd.\n    exists b1 b0; dands; spcast; auto.\n    eapply equality_respects_cequivc_left;[exact k3|].\n    eapply equality_respects_cequivc_right;[exact k1|].\n    apply equality_in_unit.\n    dands; spcast;\n    apply computes_to_valc_refl; eauto 3 with slow.\nQed.\n\nLemma equality_in_mkc_texc {o} :\n  forall lib (a b N E : @CTerm o),\n    equality lib a b (mkc_texc N E)\n    <=> {n1 : CTerm\n         , {n2 : CTerm\n         , {e1 : CTerm\n         , {e2 : CTerm\n         , a ===e>(lib,n1) e1\n         # b ===e>(lib,n2) e2\n         # equality lib n1 n2 N\n         # equality lib e1 e2 E }}}}.\nProof.\n  introv.\n  split; introv k; exrepnd; spcast.\n\n  - unfold equality in k; exrepnd.\n    inversion k1; subst; try not_univ.\n    clear k1.\n    match goal with\n      | [ H : per_texc _ _ _ _ _ |- _ ] => rename H into p\n    end.\n    allunfold @per_texc; exrepnd; spcast; computes_to_value_isvalue.\n    apply p1 in k0.\n    unfold per_texc_eq in k0; exrepnd; spcast.\n    exists n1 n2 e1 e2; dands; spcast; auto.\n\n    + eapply eq_equality1; eauto.\n\n    + eapply eq_equality1; eauto.\n\n  - allunfold @equality; exrepnd.\n    rename eq0 into eqn.\n    rename eq into eqe.\n    exists (per_texc_eq lib eqn eqe).\n    dands; auto.\n\n    + apply CL_texc.\n      unfold per_texc.\n      exists eqn eqe N N E E.\n      dands; spcast; auto;\n      try (apply computes_to_valc_refl; apply iscvalue_mkc_texc).\n\n    + unfold per_texc_eq.\n      exists n1 n2 e1 e2; dands; spcast; auto.\nQed.\n\nLemma tequality_mkc_texc {o} :\n  forall lib (N1 E1 N2 E2 : @CTerm o),\n    tequality lib (mkc_texc N1 E1) (mkc_texc N2 E2)\n    <=> (tequality lib N1 N2 # tequality lib E1 E2).\nProof.\n  introv; split; intro teq; repnd.\n\n  - unfold tequality in teq; exrepnd.\n    inversion teq0; try not_univ; allunfold @per_texc; exrepnd.\n    computes_to_value_isvalue; sp; try (complete (spcast; sp)).\n    + exists eqn; sp.\n    + exists eqe; sp.\n\n  - unfold tequality in teq0; exrepnd.\n    rename eq into eqn.\n    unfold tequality in teq; exrepnd.\n    rename eq into eqe.\n    exists (per_texc_eq lib eqn eqe); apply CL_texc; unfold per_texc.\n    exists eqn eqe N1 N2 E1 E2; sp; spcast;\n    try (apply computes_to_valc_refl; apply iscvalue_mkc_texc).\nQed.\n\nLemma disjoint_nat_exc {o} :\n  forall lib (a b : @CTerm o),\n    disjoint_types lib mkc_tnat (mkc_texc a b).\nProof.\n  introv mem; repnd.\n\n  allrw @equality_in_tnat.\n  allunfold @equality_of_nat; exrepnd; spcast; GC.\n\n  allrw @equality_in_mkc_texc; exrepnd; spcast.\n  eapply computes_to_valc_and_excc_false in mem0; eauto.\nQed.\n\nLemma tequality_mkc_singleton_uatom {o} :\n  forall lib (n1 n2 : @get_patom_set o),\n    tequality lib (mkc_singleton_uatom n1) (mkc_singleton_uatom n2)\n    <=> n1 = n2.\nProof.\n  introv.\n  unfold mkc_singleton_uatom.\n  rw @tequality_set; split; introv k; repnd; subst; tcsp.\n\n  - clear k0.\n    pose proof (k (mkc_utoken n1) (mkc_utoken n1)) as h; clear k.\n    autodimp h hyp.\n    { apply equality_in_uatom_iff.\n      exists n1; dands; spcast;\n      try (apply computes_to_valc_refl; apply iscvalue_mkc_utoken). }\n    allrw @mkcv_cequiv_substc.\n    allrw @mkc_var_substc.\n    allrw @mkcv_utoken_substc.\n    allrw @tequality_mkc_cequiv.\n    destruct h as [h h2]; clear h2.\n    autodimp h hyp; spcast; eauto 3 with slow.\n    allrw @cequivc_mkc_utoken; auto.\n\n  - dands;[apply tequality_uatom|].\n    introv e.\n    apply equality_in_uatom_iff in e; exrepnd; spcast.\n    allrw @mkcv_cequiv_substc.\n    allrw @mkc_var_substc.\n    allrw @mkcv_utoken_substc.\n    allrw @tequality_mkc_cequiv.\n    allapply @computes_to_valc_implies_cequivc.\n    split; intro k; spcast.\n    + eapply cequivc_trans in k;[|apply cequivc_sym;exact e1].\n      allrw @cequivc_mkc_utoken; subst; auto.\n    + eapply cequivc_trans in k;[|apply cequivc_sym;exact e0].\n      allrw @cequivc_mkc_utoken; subst; auto.\nQed.\n\nLemma tequality_mkc_ntexc {o} :\n  forall lib n1 n2 (E1 E2 : @CTerm o),\n    tequality lib (mkc_ntexc n1 E1) (mkc_ntexc n2 E2)\n    <=> (n1 = n2 # tequality lib E1 E2).\nProof.\n  introv.\n  unfold mkc_ntexc.\n  rw @tequality_mkc_texc.\n  rw @tequality_mkc_singleton_uatom; auto.\nQed.\n\nLemma type_mkc_ntexc {o} :\n  forall lib n (E : @CTerm o),\n    type lib (mkc_ntexc n E) <=> (type lib E).\nProof.\n  introv.\n  rw @tequality_mkc_ntexc; split; sp.\nQed.\n\nLemma inhabited_type_mkc_cequiv {o} :\n  forall lib (t1 t2 : @CTerm o),\n    inhabited_type lib (mkc_cequiv t1 t2) <=> ccequivc lib t1 t2.\nProof.\n  introv.\n  unfold inhabited_type; split; introv k; exrepnd.\n\n  - allunfold @member; allunfold @equality; allunfold @nuprl; exrepnd.\n    inversion k0; subst; try not_univ.\n\n    allunfold @per_cequiv; sp.\n    uncast; computes_to_value_isvalue.\n    discover; sp.\n\n  - exists (@mkc_axiom o).\n    apply member_cequiv_iff; auto.\nQed.\n\nLemma equality_in_mkc_singleton_uatom {o} :\n  forall lib a b (n : @get_patom_set o),\n    equality lib a b (mkc_singleton_uatom n)\n    <=> (a ===>(lib) (mkc_utoken n) # b ===>(lib) (mkc_utoken n)).\nProof.\n  introv.\n  unfold mkc_singleton_uatom.\n  rw @equality_in_set.\n  allrw @mkcv_cequiv_substc.\n  allrw @mkc_var_substc.\n  allrw @mkcv_utoken_substc.\n  allrw @inhabited_type_mkc_cequiv.\n  allrw @equality_in_uatom_iff.\n  split; intro k; exrepnd; spcast; dands; tcsp.\n\n  - eapply close_type_sys_per_ffatom.cequivc_utoken in k;[|exact k1].\n    apply computes_to_valc_isvalue_eq in k; try (eqconstr k); eauto 3 with slow.\n    dands; spcast; auto.\n\n  - eapply close_type_sys_per_ffatom.cequivc_utoken in k;[|exact k1].\n    apply computes_to_valc_isvalue_eq in k; try (eqconstr k); eauto 3 with slow.\n    dands; spcast; auto.\n\n  - introv e.\n    allrw @mkcv_cequiv_substc.\n    allrw @mkc_var_substc.\n    allrw @mkcv_utoken_substc.\n    allrw @equality_in_uatom_iff; exrepnd; spcast.\n    apply tequality_mkc_cequiv.\n    allapply @computes_to_valc_implies_cequivc.\n    split; intro h; spcast.\n    + eapply cequivc_trans in h;[|apply cequivc_sym;exact e1].\n      allrw @cequivc_mkc_utoken; subst; auto.\n    + eapply cequivc_trans in h;[|apply cequivc_sym;exact e0].\n      allrw @cequivc_mkc_utoken; subst; auto.\n\n  - exists n; dands; spcast; auto.\n\n  - spcast.\n    allapply @computes_to_valc_implies_cequivc; auto.\nQed.\n\nLemma equality_in_mkc_ntexc {o} :\n  forall lib n (a b E : @CTerm o),\n    equality lib a b (mkc_ntexc n E)\n    <=> {n1 : CTerm\n         , {n2 : CTerm\n         , {e1 : CTerm\n         , {e2 : CTerm\n         , n1 ===>(lib) (mkc_utoken n)\n         # n2 ===>(lib) (mkc_utoken n)\n         # a ===e>(lib,n1) e1\n         # b ===e>(lib,n2) e2\n         # equality lib e1 e2 E }}}}.\nProof.\n  introv.\n  rw @equality_in_mkc_texc; split; intro k; exrepnd; spcast.\n\n  - allrw @equality_in_mkc_singleton_uatom; repnd; spcast.\n    exists n1 n2 e1 e2; dands; spcast; auto.\n\n  - exists n1 n2 e1 e2; dands; spcast; auto.\n    allrw @equality_in_mkc_singleton_uatom; dands; spcast; auto.\nQed.\n\nLemma equality_in_natE {o} :\n  forall lib n (a b : @CTerm o),\n    equality lib a b (natE n)\n    <=> (equality_of_nat lib a b\n         {+} (ccequivc lib a (spexcc n) # ccequivc lib b (spexcc n))).\nProof.\n  introv.\n  unfold natE, with_nexc_c.\n\n  pose proof (equality_in_disjoint_bunion lib a b mkc_tnat (mkc_ntexc n mkc_unit)) as h.\n  autodimp h hyp.\n  { unfold mkc_ntexc; apply disjoint_nat_exc. }\n  rw h; clear h.\n  rw @type_mkc_ntexc.\n\n  split; intro k; repnd; dands; eauto 3 with slow; repndors; tcsp;\n  allrw @equality_in_tnat;\n  allrw @equality_in_mkc_ntexc;\n  exrepnd; spcast; tcsp;\n  allrw @equality_in_unit;\n  repnd; spcast.\n\n  - allapply @computes_to_excc_implies_cequivc.\n    allapply @computes_to_valc_implies_cequivc.\n    right; dands; spcast.\n    + eapply cequivc_trans;[exact k5|].\n      unfold spexc.\n      apply cequivc_mkc_exception; auto.\n    + eapply cequivc_trans;[exact k6|].\n      unfold spexc.\n      apply cequivc_mkc_exception; auto.\n\n  - left; allrw @equality_in_tnat; auto.\n\n  - right; allrw @equality_in_mkc_ntexc.\n    allunfold @spexc.\n    apply cequivc_sym in k0; apply cequivc_sym in k.\n    apply cequivc_exception_implies in k0.\n    apply cequivc_exception_implies in k.\n    exrepnd.\n    allapply @cequivc_axiom_implies.\n    allapply @cequivc_utoken_implies.\n    exists x0 x c0 c; dands; spcast; auto.\n    allrw @equality_in_unit; dands; spcast; auto.\nQed.\n\nLemma dec_reduces_ksteps_excc {o} :\n  forall lib k (t v : @CTerm o),\n    (forall x, decidable (x = get_cterm v))\n    -> decidable (reduces_ksteps_excc lib t v k).\nProof.\n  introv d.\n  destruct_cterms; allsimpl.\n  pose proof (dec_reduces_in_atmost_k_steps_exc lib k x0 x d) as h.\n  destruct h as [h|h];[left|right].\n  - spcast; tcsp.\n  - intro r; spcast; tcsp.\nQed.\n\nLemma reduces_ksteps_excc_spexcc_decompose {o} :\n  forall lib (k : nat) a (t : @CTerm o),\n    reduces_ksteps_excc lib t (spexcc a) k\n    -> {k1 : nat\n        & {k2 : nat\n        & {k3 : nat\n        & {a' : CTerm\n        & {e' : CTerm\n        & k1 + k2 + k3 <= k\n        # reduces_in_atmost_k_stepsc lib t (mkc_exception a' e') k1\n        # reduces_in_atmost_k_stepsc lib a' (mkc_utoken a) k2\n        # reduces_in_atmost_k_stepsc lib e' mkc_axiom k3 }}}}}.\nProof.\n  introv r.\n  pose proof (dec_reduces_in_atmost_k_steps_excc lib k t (spexcc a)) as h; allsimpl.\n  try (fold (spexc a) in h).\n  autodimp h hyp; eauto 3 with slow.\n  destruct h as [d|d].\n  - apply reduces_in_atmost_k_steps_excc_decompose in d; eauto 2 with slow.\n  - provefalse; spcast; sp.\nQed.\n\nLemma reduces_ksteps_excc_impossible1 {o} :\n  forall lib k1 k2 (t : @CTerm o) a n,\n    reduces_ksteps_excc lib t (spexcc a) k1\n    -> reduces_ksteps_excc lib t (mkc_nat n) k2\n    -> False.\nProof.\n  introv r1 r2; spcast.\n  eapply reduces_in_atmost_k_steps_excc_impossible1 in r1; eauto.\nQed.\n\nLemma dec_reduces_ksteps_excc_nat {o} :\n  forall lib k (t : @CTerm o),\n    decidable {n : nat & reduces_ksteps_excc lib t (mkc_nat n) k}.\nProof.\n  introv; destruct_cterms; allsimpl.\n  pose proof (dec_reduces_in_atmost_k_steps_exc_nat lib k x) as h.\n  destruct h as [h|h];[left|right].\n  - exrepnd; exists n; spcast; tcsp.\n  - intro r; exrepnd; destruct h; exists n; spcast; tcsp.\nQed.\n\nLemma equality_in_natE_implies {o} :\n  forall lib (t u : @CTerm o) a,\n    equality lib t u (natE a)\n    -> equality_of_nat_tt lib t u\n       [+] (cequivc lib t (spexcc a) # cequivc lib u (spexcc a)).\nProof.\n  introv equ.\n\n  assert {k : nat\n          , {m : nat\n          , (reduces_ksteps_excc lib t (mkc_nat m) k\n             # reduces_ksteps_excc lib u (mkc_nat m) k)\n            {+} (reduces_ksteps_excc lib t (spexcc a) k\n                  # reduces_ksteps_excc lib u (spexcc a) k)}} as j.\n  { apply equality_in_natE in equ.\n    repndors.\n\n    - unfold equality_of_nat in equ; exrepnd; spcast.\n      allrw @computes_to_valc_iff_reduces_in_atmost_k_stepsc; exrepnd.\n      exists (Peano.max k0 k1) k.\n      left; dands; spcast.\n\n      + apply (reduces_in_atmost_k_stepsc_le _ _ _ _ (Peano.max k0 k1)) in equ4; eauto 3 with slow;\n        try (apply Nat.le_max_l; auto).\n        apply reduces_in_atmost_k_steps_excc_can in equ4; tcsp.\n\n      + apply (reduces_in_atmost_k_stepsc_le _ _ _ _ (Peano.max k0 k1)) in equ2; eauto 3 with slow;\n        try (apply Nat.le_max_r; auto).\n        apply reduces_in_atmost_k_steps_excc_can in equ2; tcsp.\n\n    - repnd; spcast.\n      apply cequivc_spexcc in equ0.\n      apply cequivc_spexcc in equ.\n      exrepnd.\n      allrw @computes_to_valc_iff_reduces_in_atmost_k_stepsc; exrepnd.\n      allrw @computes_to_excc_iff_reduces_in_atmost_k_stepsc; exrepnd.\n\n      exists (Peano.max (k3 + k + k0) (k4 + k1 + k2)) 0.\n      right; dands; spcast.\n\n      + apply (reduces_in_atmost_k_steps_excc_le_exc _ (k3 + k + k0));\n        eauto 3 with slow; tcsp;\n        try (apply Nat.le_max_l; auto).\n        pose proof (reduces_in_atmost_k_steps_excc_exception\n                      lib k k0 n0 e0 (mkc_utoken a) mkc_axiom) as h.\n        repeat (autodimp h hyp); tcsp; exrepnd.\n        pose proof (reduces_in_atmost_k_steps_excc_trans2\n                      lib k3 i\n                      t\n                      (mkc_exception n0 e0)\n                      (mkc_exception (mkc_utoken a) mkc_axiom)) as q.\n        repeat (autodimp q hyp); exrepnd.\n        apply (reduces_in_atmost_k_steps_excc_le_exc _ i0); tcsp; try omega.\n\n      + apply (reduces_in_atmost_k_steps_excc_le_exc _ (k4 + k1 + k2));\n        eauto 3 with slow; tcsp;\n        try (apply Nat.le_max_r; auto).\n        pose proof (reduces_in_atmost_k_steps_excc_exception\n                      lib k1 k2 n e (mkc_utoken a) mkc_axiom) as h.\n        repeat (autodimp h hyp); tcsp; exrepnd.\n        pose proof (reduces_in_atmost_k_steps_excc_trans2\n                      lib k4 i\n                      u\n                      (mkc_exception n e)\n                      (mkc_exception (mkc_utoken a) mkc_axiom)) as q.\n        repeat (autodimp q hyp); exrepnd.\n        apply (reduces_in_atmost_k_steps_excc_le_exc _ i0); tcsp; try omega.\n  }\n\n  apply (constructive_indefinite_ground_description nat (fun x => x) (fun x => x))\n    in j; auto.\n\n  { exrepnd.\n    apply (constructive_indefinite_ground_description nat (fun x => x) (fun x => x))\n      in j0; auto.\n\n    - exrepnd.\n      pose proof (dec_reduces_ksteps_excc lib x t (mkc_nat x0)) as h.\n      autodimp h hyp; simpl; eauto 3 with slow.\n      pose proof (dec_reduces_ksteps_excc lib x t (spexcc a)) as q.\n      autodimp q hyp; simpl; try (fold (spexc a)); eauto 3 with slow.\n      pose proof (dec_reduces_ksteps_excc lib x u (mkc_nat x0)) as j.\n      autodimp j hyp; simpl; eauto 3 with slow.\n      pose proof (dec_reduces_ksteps_excc lib x u (spexcc a)) as l.\n      autodimp l hyp; simpl; try (fold (spexc a)); eauto 3 with slow.\n\n      destruct h as [h|h];\n      destruct q as [q|q];\n      destruct j as [j|j];\n      destruct l as [l|l];\n      try (complete (eapply reduces_ksteps_excc_impossible1 in h;[|exact q]; tcsp));\n      try (complete (eapply reduces_ksteps_excc_impossible1 in j;[|exact l]; eauto; tcsp));\n      try (complete (provefalse; repndors; repnd; tcsp)).\n\n      { left; exists x0; dands; split; simpl; eauto 3 with slow; exists x; spcast;\n        apply reduces_in_atmost_k_steps_excc_can_implies in h;\n        apply reduces_in_atmost_k_steps_excc_can_implies in j;\n        allunfold @reduces_in_atmost_k_stepsc; allsimpl;\n        allrw @get_cterm_apply; tcsp. }\n\n      { right.\n        apply reduces_ksteps_excc_spexcc_decompose in q.\n        apply reduces_ksteps_excc_spexcc_decompose in l.\n        exrepnd.\n        allunfold @reduces_in_atmost_k_stepsc; allsimpl.\n        allrw @get_cterm_apply; allsimpl.\n        allrw @get_cterm_mkc_exception; allsimpl.\n        dands;\n          apply cequiv_spexc_if;\n          try (apply isprog_apply);\n          try (apply isprog_mk_nat);\n          eauto 3 with slow.\n        - exists (get_cterm a'0) (get_cterm e'0); dands; eauto 3 with slow.\n          unfold computes_to_exception; exists k0; auto.\n        - exists (get_cterm a') (get_cterm e'); dands; eauto 3 with slow.\n          unfold computes_to_exception; exists k1; auto. }\n\n    - clear j0.\n      introv.\n\n      pose proof (dec_reduces_ksteps_excc lib x t (mkc_nat x0)) as h.\n      autodimp h hyp; simpl; eauto 3 with slow.\n      pose proof (dec_reduces_ksteps_excc lib x t (spexcc a)) as q.\n      autodimp q hyp; simpl; try (fold (spexc a)); eauto 3 with slow.\n      pose proof (dec_reduces_ksteps_excc lib x u (mkc_nat x0)) as j.\n      autodimp j hyp; simpl; eauto 3 with slow.\n      pose proof (dec_reduces_ksteps_excc lib x u (spexcc a)) as l.\n      autodimp l hyp; simpl; try (fold (spexc a)); eauto 3 with slow.\n\n      destruct h as [h|h];\n        destruct q as [q|q];\n        destruct j as [j|j];\n        destruct l as [l|l];\n        tcsp;\n        try (complete (right; intro xx; repndors; repnd; tcsp)).\n  }\n\n  { clear j; introv.\n\n    pose proof (dec_reduces_ksteps_excc_nat lib x t) as h.\n    pose proof (dec_reduces_ksteps_excc lib x t (spexcc a)) as q.\n    autodimp q hyp; simpl; try (fold (spexc a)); eauto 3 with slow.\n    pose proof (dec_reduces_ksteps_excc_nat lib x u) as j.\n    pose proof (dec_reduces_ksteps_excc lib x u (spexcc a)) as l.\n    autodimp l hyp; simpl; try (fold (spexc a)); eauto 3 with slow.\n\n    destruct h as [h|h];\n      destruct q as [q|q];\n      destruct j as [j|j];\n      destruct l as [l|l];\n      exrepnd;\n      try (destruct (deq_nat n0 n) as [d|d]); subst;\n      tcsp;\n      try (complete (eapply reduces_ksteps_excc_impossible1 in h0; eauto; tcsp));\n      try (complete (eapply reduces_ksteps_excc_impossible1 in j0; eauto; tcsp));\n      try (complete (provefalse; repndors; repnd; tcsp));\n      try (complete (right; intro xx; exrepnd; repndors; repnd; tcsp;\n                     try (complete (destruct h; eexists; eauto));\n                     try (complete (destruct j; eexists; eauto))));\n      try (complete (left; exists n; left; tcsp));\n      try (complete (left; exists 0; right; tcsp)).\n\n    right; intro xx; exrepnd; repndors; repnd; tcsp; spcast.\n    allunfold @reduces_in_atmost_k_steps_excc; allsimpl.\n    allunfold @reduces_in_atmost_k_steps_exc.\n    rw xx1 in h0.\n    rw xx0 in j0.\n    inversion h0.\n    inversion j0.\n    allapply Znat.Nat2Z.inj; subst; tcsp.\n  }\nQed.\n\nLemma tequality_with_nexc_c {o} :\n  forall lib a1 a2 (T1 T2 E1 E2 : @CTerm o),\n    tequality lib (with_nexc_c a1 T1 E1) (with_nexc_c a2 T2 E2)\n    <=> (a1 = a2 # tequality lib T1 T2 # tequality lib E1 E2).\nProof.\n  introv.\n  unfold with_nexc_c.\n  rw @tequality_bunion.\n  rw @tequality_mkc_texc.\n  rw @tequality_mkc_singleton_uatom.\n  split; sp.\nQed.\n\nLemma tequality_natE {o} :\n  forall lib (a1 a2 : @get_patom_set o),\n    tequality lib (natE a1) (natE a2) <=> a1 = a2.\nProof.\n  introv.\n  unfold natE.\n  rw @tequality_with_nexc_c.\n  allrw @fold_type.\n  split; intro k; repnd; dands; eauto with slow.\nQed.\n\nLemma type_natE {o} :\n  forall lib (a : @get_patom_set o),\n    type lib (natE a).\nProof.\n  introv.\n  rw @tequality_natE; auto.\nQed.\nHint Resolve type_natE : slow.\n\nLemma disjoint_nat_unit {o}:\n  forall (lib : @library o),\n    disjoint_types lib mkc_tnat mkc_unit.\nProof.\n  introv mem; repnd.\n  allrw @equality_in_tnat.\n  allrw @equality_in_unit.\n  allunfold @equality_of_nat; exrepnd; spcast; GC.\n  computes_to_eqval.\nQed.\nHint Resolve disjoint_nat_unit : slow.\n\nLemma member_bunion_nat_unit_implies_cis_spcan_not_atom {o} :\n  forall lib (t : @CTerm o) a,\n    member lib t (mkc_bunion mkc_tnat mkc_unit)\n    -> cis_spcan_not_atom lib t a.\nProof.\n  introv mem.\n  apply @equality_in_disjoint_bunion in mem; eauto 3 with slow.\n  repnd.\n  clear mem0 mem1.\n  repndors.\n  - apply equality_in_tnat in mem.\n    unfold equality_of_nat in mem; exrepnd; spcast.\n    exists (@mkc_nat o k); dands; spcast; simpl; tcsp.\n  - apply equality_in_unit in mem; repnd; spcast.\n    exists (@mkc_axiom o); dands; spcast; simpl; tcsp.\nQed.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/continuity/stronger_continuity_defs_typ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.24615464138712362}}
{"text": "From Coq Require Import Arith ZArith OrderedType.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq.\nFrom nbits Require Import NBits.\nFrom ssrlib Require Import Types SsrOrder Var Nats ZAriths Tactics.\nFrom BitBlasting Require Import Typ TypEnv State QFBV CNF BBExport.\nFrom BBCache Require Import CompCache.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n\n(* ==== bit-blasting with complete cache information ==== *)\n\nDefinition bit_blast_eunop (op : QFBV.eunop) :=\n  match op with\n  | QFBV.Unot => bit_blast_not\n  | QFBV.Uneg => bit_blast_neg\n  | QFBV.Uextr i j => (fun g ls => bit_blast_extract g i j ls)\n  | QFBV.Uhigh n => (fun g ls => bit_blast_high g n ls)\n  | QFBV.Ulow n => (fun g ls => bit_blast_low g n ls)\n  | QFBV.Uzext n => bit_blast_zeroextend n\n  | QFBV.Usext n => bit_blast_signextend n\n  | QFBV.Urepeat n => (fun g ls => bit_blast_repeat g n ls)\n  | QFBV.Urotl n => (fun g ls => bit_blast_rotateleft g n ls)\n  | QFBV.Urotr n => (fun g ls => bit_blast_rotateright g n ls)\n  end .\n\nDefinition bit_blast_ebinop (op : QFBV.ebinop) :=\n  match op with\n  | QFBV.Band => bit_blast_and\n  | QFBV.Bor => bit_blast_or \n  | QFBV.Bxor => bit_blast_xor \n  | QFBV.Badd => bit_blast_add \n  | QFBV.Bsub => bit_blast_sub \n  | QFBV.Bmul => bit_blast_mul\n  | QFBV.Bdiv => bit_blast_udiv'\n  | QFBV.Bmod => bit_blast_umod\n  | QFBV.Bsdiv => bit_blast_sdiv\n  | QFBV.Bsrem => bit_blast_srem\n  | QFBV.Bsmod => bit_blast_smod\n  | QFBV.Bshl => bit_blast_shl \n  | QFBV.Blshr => bit_blast_lshr \n  | QFBV.Bashr => bit_blast_ashr \n  | QFBV.Bconcat => bit_blast_concat \n  | QFBV.Bcomp => bit_blast_comp\n  end .\n\nDefinition bit_blast_bbinop (op : QFBV.bbinop) :=\n  match op with\n  | QFBV.Beq => bit_blast_eq \n  | QFBV.Bult => bit_blast_ult \n  | QFBV.Bule => bit_blast_ule \n  | QFBV.Bugt => bit_blast_ugt \n  | QFBV.Buge => bit_blast_uge \n  | QFBV.Bslt => bit_blast_slt \n  | QFBV.Bsle => bit_blast_sle \n  | QFBV.Bsgt => bit_blast_sgt \n  | QFBV.Bsge => bit_blast_sge \n  | QFBV.Buaddo => bit_blast_uaddo \n  | QFBV.Busubo => bit_blast_usubo \n  | QFBV.Bumulo => bit_blast_umulo \n  | QFBV.Bsaddo => bit_blast_saddo \n  | QFBV.Bssubo => bit_blast_ssubo \n  | QFBV.Bsmulo => bit_blast_smulo \n  end .\n\nFixpoint bit_blast_exp_ccache te m cc g e :\n  vm * compcache * generator * cnf * word :=\n  (* = bit_blast_exp_nocet = *)\n  let bit_blast_exp_nocet te m cc g e : \n        vm * compcache * generator * cnf * word * cnf :=\n      match e with\n      | QFBV.Evar v =>\n        match find_het e cc with\n        | Some (cs, ls) => (m, cc, g, cs, ls, cs)\n        | None => match SSAVM.find v m with\n                  | None => let '(g', cs, rs) := bit_blast_var te g v in\n                            (SSAVM.add v rs m, add_het e cs rs cc, g', cs, rs, cs)\n                  | Some rs => (m, add_het e [::] rs cc, g, [::], rs, [::])\n                  end\n        end\n      | QFBV.Econst bs => \n        match find_het e cc with\n        | Some (cs, ls) => (m, cc, g, cs, ls, cs)\n        | None => let '(g', cs, rs) := bit_blast_const g bs in\n                  (m, add_het e cs rs cc, g', cs, rs, cs)\n        end\n      | QFBV.Eunop op e1 =>\n        let '(m1, cc1, g1, cs1, ls1) := bit_blast_exp_ccache te m cc g e1 in\n        match find_het e cc1 with\n        | Some (csop, lsop) => (m1, cc1, g1, catrev cs1 csop, lsop, csop)\n        | None =>\n          let '(gop, csop, lsop) := bit_blast_eunop op g1 ls1 in\n          (m1, add_het e csop lsop cc1, gop, catrev cs1 csop, lsop, csop)\n        end\n      | QFBV.Ebinop op e1 e2 =>\n        let '(m1, cc1, g1, cs1, ls1) := bit_blast_exp_ccache te m cc g e1 in\n        let '(m2, cc2, g2, cs2, ls2) := bit_blast_exp_ccache te m1 cc1 g1 e2 in\n        match find_het e cc2 with\n        | Some (csop, lsop) => (m2, cc2, g2, catrev cs1 (catrev cs2 csop), lsop, csop)\n        | None => \n          let '(gop, csop, lsop) := bit_blast_ebinop op g2 ls1 ls2 in\n          (m2, add_het e csop lsop cc2, gop, catrev cs1 (catrev cs2 csop), lsop, csop)\n        end\n      | QFBV.Eite c e1 e2 => \n        let '(mc, ccc, gc, csc, lc) := bit_blast_bexp_ccache te m cc g c in\n        let '(m1, cc1, g1, cs1, ls1) := bit_blast_exp_ccache te mc ccc gc e1 in\n        let '(m2, cc2, g2, cs2, ls2) := bit_blast_exp_ccache te m1 cc1 g1 e2 in\n        match find_het e cc2 with\n        | Some (csop, lsop) => \n          (m2, cc2, g2, catrev csc (catrev cs1 (catrev cs2 csop)), lsop, csop)\n        | None => \n          let '(gop, csop, lsop) := bit_blast_ite g2 lc ls1 ls2 in\n          (m2, add_het e csop lsop cc2, gop, \n           catrev csc (catrev cs1 (catrev cs2 csop)), lsop, csop)\n        end\n      end\n  (* = = *)\n  in\n  match CompCache.find_cet e cc with\n  | Some (cs, ls) => (m, cc, g, [::], ls)\n  | None => let '(m', cc', g', cs, lrs, csop) := bit_blast_exp_nocet te m cc g e in\n            (m', CompCache.add_cet e csop lrs cc', g', cs, lrs)\n  end\nwith\nbit_blast_bexp_ccache te m cc g e : vm * compcache * generator * cnf * literal :=\n  (* = bit_blast_bexp_nocbt = *)\n  let bit_blast_bexp_nocbt te m cc g e : \n        vm * compcache * generator * cnf * literal * cnf :=\n      match e with\n      | QFBV.Bfalse => \n        match find_hbt e cc with\n        | Some (cs, l) => (m, cc, g, cs, l, cs)\n        | None => (m, add_hbt e [::] lit_ff cc, g, [::], lit_ff, [::])\n        end\n      | QFBV.Btrue => \n        match find_hbt e cc with\n        | Some (cs, l) => (m, cc, g, cs, l, cs)\n        | None => (m, add_hbt e [::] lit_tt cc, g, [::], lit_tt, [::])\n        end\n      | QFBV.Bbinop op e1 e2 =>\n        let '(m1, cc1, g1, cs1, ls1) := bit_blast_exp_ccache te m cc g e1 in\n        let '(m2, cc2, g2, cs2, ls2) := bit_blast_exp_ccache te m1 cc1 g1 e2 in\n        match find_hbt e cc2 with\n        | Some (csop, lop) => (m2, cc2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => \n          let '(gop, csop, lop) := bit_blast_bbinop op g2 ls1 ls2 in\n          (m2, add_hbt e csop lop cc2, gop, catrev cs1 (catrev cs2 csop), lop, csop)\n        end\n      | QFBV.Blneg e1 => \n        let '(m1, cc1, g1, cs1, l1) := bit_blast_bexp_ccache te m cc g e1 in\n        match find_hbt e cc1 with\n        | Some (csop, lop) => (m1, cc1, g1, catrev cs1 csop, lop, csop)\n        | None => let '(gop, csop, lop) := bit_blast_lneg g1 l1 in\n                  (m1, add_hbt e csop lop cc1, gop, catrev cs1 csop, lop, csop)\n        end\n      | QFBV.Bconj e1 e2 => \n        let '(m1, cc1, g1, cs1, l1) := bit_blast_bexp_ccache te m cc g e1 in\n        let '(m2, cc2, g2, cs2, l2) := bit_blast_bexp_ccache te m1 cc1 g1 e2 in\n        match find_hbt e cc2 with\n        | Some (csop, lop) => (m2, cc2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => let '(gop, csop, lop) := bit_blast_conj g2 l1 l2 in\n                  (m2, add_hbt e csop lop cc2, gop, \n                   catrev cs1 (catrev cs2 csop), lop, csop)\n        end\n      | QFBV.Bdisj e1 e2 => \n        let '(m1, cc1, g1, cs1, l1) := bit_blast_bexp_ccache te m cc g e1 in\n        let '(m2, cc2, g2, cs2, l2) := bit_blast_bexp_ccache te m1 cc1 g1 e2 in\n        match find_hbt e cc2 with\n        | Some (csop, lop) => (m2, cc2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => let '(gop, csop, lop) := bit_blast_disj g2 l1 l2 in\n                  (m2, add_hbt e csop lop cc2, gop, \n                   catrev cs1 (catrev cs2 csop), lop, csop)\n        end\n      end\n  (* = = *)\n  in\n  match CompCache.find_cbt e cc with\n  | Some (cs, l) => (m, cc, g, [::], l)\n  | None => let '(m', cc', g', cs, lr, csop) := bit_blast_bexp_nocbt te m cc g e in\n            (m', CompCache.add_cbt e csop lr cc', g', cs, lr)\n  end.\n\n\nLemma bit_blast_exp_ccache_equation : \n  forall te m cc g e, \n    bit_blast_exp_ccache te m cc g e =\n  (* = bit_blast_exp_nocet = *)\n  let bit_blast_exp_nocet te m cc g e : \n        vm * compcache * generator * cnf * word * cnf :=\n      match e with\n      | QFBV.Evar v =>\n        match find_het e cc with\n        | Some (cs, ls) => (m, cc, g, cs, ls, cs)\n        | None => match SSAVM.find v m with\n                  | None => let '(g', cs, rs) := bit_blast_var te g v in\n                            (SSAVM.add v rs m, add_het e cs rs cc, g', cs, rs, cs)\n                  | Some rs => (m, add_het e [::] rs cc, g, [::], rs, [::])\n                  end\n        end\n      | QFBV.Econst bs => \n        match find_het e cc with\n        | Some (cs, ls) => (m, cc, g, cs, ls, cs)\n        | None => let '(g', cs, rs) := bit_blast_const g bs in\n                  (m, add_het e cs rs cc, g', cs, rs, cs)\n        end\n      | QFBV.Eunop op e1 =>\n        let '(m1, cc1, g1, cs1, ls1) := bit_blast_exp_ccache te m cc g e1 in\n        match find_het e cc1 with\n        | Some (csop, lsop) => (m1, cc1, g1, catrev cs1 csop, lsop, csop)\n        | None =>\n          let '(gop, csop, lsop) := bit_blast_eunop op g1 ls1 in\n          (m1, add_het e csop lsop cc1, gop, catrev cs1 csop, lsop, csop)\n        end\n      | QFBV.Ebinop op e1 e2 =>\n        let '(m1, cc1, g1, cs1, ls1) := bit_blast_exp_ccache te m cc g e1 in\n        let '(m2, cc2, g2, cs2, ls2) := bit_blast_exp_ccache te m1 cc1 g1 e2 in\n        match find_het e cc2 with\n        | Some (csop, lsop) => (m2, cc2, g2, catrev cs1 (catrev cs2 csop), lsop, csop)\n        | None => \n          let '(gop, csop, lsop) := bit_blast_ebinop op g2 ls1 ls2 in\n          (m2, add_het e csop lsop cc2, gop, catrev cs1 (catrev cs2 csop), lsop, csop)\n        end\n      | QFBV.Eite c e1 e2 => \n        let '(mc, ccc, gc, csc, lc) := bit_blast_bexp_ccache te m cc g c in\n        let '(m1, cc1, g1, cs1, ls1) := bit_blast_exp_ccache te mc ccc gc e1 in\n        let '(m2, cc2, g2, cs2, ls2) := bit_blast_exp_ccache te m1 cc1 g1 e2 in\n        match find_het e cc2 with\n        | Some (csop, lsop) => \n          (m2, cc2, g2, catrev csc (catrev cs1 (catrev cs2 csop)), lsop, csop)\n        | None => \n          let '(gop, csop, lsop) := bit_blast_ite g2 lc ls1 ls2 in\n          (m2, add_het e csop lsop cc2, gop, \n           catrev csc (catrev cs1 (catrev cs2 csop)), lsop, csop)\n        end\n      end\n  (* = = *)\n  in\n  match CompCache.find_cet e cc with\n  | Some (cs, ls) => (m, cc, g, [::], ls)\n  | None => let '(m', cc', g', cs, lrs, csop) := bit_blast_exp_nocet te m cc g e in\n            (m', CompCache.add_cet e csop lrs cc', g', cs, lrs)\n  end.\nProof. move=> te m cc g e. elim e; done. Qed.\n\nLemma bit_blast_bexp_ccache_equation :\n  forall te m cc g e, \n    bit_blast_bexp_ccache te m cc g e =\n  (* = bit_blast_bexp_nocbt = *)\n  let bit_blast_bexp_nocbt te m cc g e : \n        vm * compcache * generator * cnf * literal * cnf :=\n      match e with\n      | QFBV.Bfalse => \n        match find_hbt e cc with\n        | Some (cs, l) => (m, cc, g, cs, l, cs)\n        | None => (m, add_hbt e [::] lit_ff cc, g, [::], lit_ff, [::])\n        end\n      | QFBV.Btrue => \n        match find_hbt e cc with\n        | Some (cs, l) => (m, cc, g, cs, l, cs)\n        | None => (m, add_hbt e [::] lit_tt cc, g, [::], lit_tt, [::])\n        end\n      | QFBV.Bbinop op e1 e2 =>\n        let '(m1, cc1, g1, cs1, ls1) := bit_blast_exp_ccache te m cc g e1 in\n        let '(m2, cc2, g2, cs2, ls2) := bit_blast_exp_ccache te m1 cc1 g1 e2 in\n        match find_hbt e cc2 with\n        | Some (csop, lop) => (m2, cc2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => \n          let '(gop, csop, lop) := bit_blast_bbinop op g2 ls1 ls2 in\n          (m2, add_hbt e csop lop cc2, gop, catrev cs1 (catrev cs2 csop), lop, csop)\n        end\n      | QFBV.Blneg e1 => \n        let '(m1, cc1, g1, cs1, l1) := bit_blast_bexp_ccache te m cc g e1 in\n        match find_hbt e cc1 with\n        | Some (csop, lop) => (m1, cc1, g1, catrev cs1 csop, lop, csop)\n        | None => let '(gop, csop, lop) := bit_blast_lneg g1 l1 in\n                  (m1, add_hbt e csop lop cc1, gop, catrev cs1 csop, lop, csop)\n        end\n      | QFBV.Bconj e1 e2 => \n        let '(m1, cc1, g1, cs1, l1) := bit_blast_bexp_ccache te m cc g e1 in\n        let '(m2, cc2, g2, cs2, l2) := bit_blast_bexp_ccache te m1 cc1 g1 e2 in\n        match find_hbt e cc2 with\n        | Some (csop, lop) => (m2, cc2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => let '(gop, csop, lop) := bit_blast_conj g2 l1 l2 in\n                  (m2, add_hbt e csop lop cc2, gop, \n                   catrev cs1 (catrev cs2 csop), lop, csop)\n        end\n      | QFBV.Bdisj e1 e2 => \n        let '(m1, cc1, g1, cs1, l1) := bit_blast_bexp_ccache te m cc g e1 in\n        let '(m2, cc2, g2, cs2, l2) := bit_blast_bexp_ccache te m1 cc1 g1 e2 in\n        match find_hbt e cc2 with\n        | Some (csop, lop) => (m2, cc2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => let '(gop, csop, lop) := bit_blast_disj g2 l1 l2 in\n                  (m2, add_hbt e csop lop cc2, gop, \n                   catrev cs1 (catrev cs2 csop), lop, csop)\n        end\n      end\n  (* = = *)\n  in\n  match CompCache.find_cbt e cc with\n  | Some (cs, l) => (m, cc, g, [::], l)\n  | None => let '(m', cc', g', cs, lr, csop) := bit_blast_bexp_nocbt te m cc g e in\n            (m', CompCache.add_cbt e csop lr cc', g', cs, lr)\n  end.\nProof. move=> te m cc g e. elim e; done. Qed.\n\n\n\n(* === mk_env_exp_ccache and mk_env_bexp_ccache === *)\n\nDefinition mk_env_eunop (op : QFBV.eunop) :=\n  match op with\n  | QFBV.Unot => mk_env_not\n  | QFBV.Uneg => mk_env_neg\n  | QFBV.Uextr i j => (fun E g ls => mk_env_extract E g i j ls)\n  | QFBV.Uhigh n => (fun E g ls => mk_env_high E g n ls)\n  | QFBV.Ulow n => (fun E g ls => mk_env_low E g n ls)\n  | QFBV.Uzext n => mk_env_zeroextend n\n  | QFBV.Usext n => mk_env_signextend n\n  | QFBV.Urepeat n => (fun E g ls => mk_env_repeat E g n ls)\n  | QFBV.Urotl n => (fun E g ls => mk_env_rotateleft E g n ls)\n  | QFBV.Urotr n => (fun E g ls => mk_env_rotateright E g n ls)\n  end .\n\nDefinition mk_env_ebinop (op : QFBV.ebinop) :=\n  match op with\n  | QFBV.Band => mk_env_and\n  | QFBV.Bor => mk_env_or\n  | QFBV.Bxor => mk_env_xor\n  | QFBV.Badd => mk_env_add\n  | QFBV.Bsub => mk_env_sub\n  | QFBV.Bmul => mk_env_mul\n  | QFBV.Bdiv => mk_env_udiv'\n  | QFBV.Bmod => mk_env_umod\n  | QFBV.Bsdiv => mk_env_sdiv\n  | QFBV.Bsrem => mk_env_srem\n  | QFBV.Bsmod => mk_env_smod\n  | QFBV.Bshl => mk_env_shl\n  | QFBV.Blshr => mk_env_lshr\n  | QFBV.Bashr => mk_env_ashr\n  | QFBV.Bconcat => mk_env_concat\n  | QFBV.Bcomp => mk_env_comp\n  end .\n\nDefinition mk_env_bbinop (op : QFBV.bbinop) :=\n  match op with\n  | QFBV.Beq => mk_env_eq\n  | QFBV.Bult => mk_env_ult\n  | QFBV.Bule => mk_env_ule\n  | QFBV.Bugt => mk_env_ugt\n  | QFBV.Buge => mk_env_uge\n  | QFBV.Bslt => mk_env_slt\n  | QFBV.Bsle => mk_env_sle\n  | QFBV.Bsgt => mk_env_sgt\n  | QFBV.Bsge => mk_env_sge\n  | QFBV.Buaddo => mk_env_uaddo\n  | QFBV.Busubo => mk_env_usubo\n  | QFBV.Bumulo => mk_env_umulo\n  | QFBV.Bsaddo => mk_env_saddo\n  | QFBV.Bssubo => mk_env_ssubo\n  | QFBV.Bsmulo => mk_env_smulo\n  end .\n\n\n\nLemma mk_env_eunop_env_equal op E1 E2 g ls E1' E2' g1' g2' cs1 cs2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_eunop op E1 g ls = (E1', g1', cs1, lrs1) ->\n  mk_env_eunop op E2 g ls = (E2', g2', cs2, lrs2) ->\n  env_equal E1' E2' /\\ g1' = g2' /\\ cs1 = cs2 /\\ lrs1 = lrs2.\nProof.\n  case: op => /=.\n  - exact: mk_env_not_env_equal.\n  - exact: mk_env_neg_env_equal.\n  - move=> ? ?; exact: mk_env_extract_env_equal.\n  - move=> ?; exact: mk_env_high_env_equal.\n  - move=> ?; exact: mk_env_low_env_equal.\n  - move=> ?; exact: mk_env_zeroextend_env_equal.\n  - move=> ?; exact: mk_env_signextend_env_equal.\n  - move=> ?; exact: mk_env_repeat_env_equal.\n  - move=> ?; exact: mk_env_rotateleft_env_equal.\n  - move=> ?; exact: mk_env_rotateright_env_equal.\nQed.\n\nLemma mk_env_ebinop_env_equal op E1 E2 g ls1 ls2 E1' E2' g1' g2' cs1 cs2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_ebinop op E1 g ls1 ls2 = (E1', g1', cs1, lrs1) ->\n  mk_env_ebinop op E2 g ls1 ls2 = (E2', g2', cs2, lrs2) ->\n  env_equal E1' E2' /\\ g1' = g2' /\\ cs1 = cs2 /\\ lrs1 = lrs2.\nProof.\n  case: op => /=.\n  - exact: mk_env_and_env_equal.\n  - exact: mk_env_or_env_equal.\n  - exact: mk_env_xor_env_equal.\n  - exact: mk_env_add_env_equal.\n  - exact: mk_env_sub_env_equal.\n  - exact: mk_env_mul_env_equal.\n  - exact: mk_env_udiv'_env_equal.\n  - exact: mk_env_umod_env_equal.\n  - exact: mk_env_sdiv_env_equal.\n  - exact: mk_env_srem_env_equal.\n  - exact: mk_env_smod_env_equal.\n  - exact: mk_env_shl_env_equal.\n  - exact: mk_env_lshr_env_equal.\n  - exact: mk_env_ashr_env_equal.\n  - exact: mk_env_concat_env_equal.\n  - exact: mk_env_comp_env_equal.\nQed.\n\nLemma mk_env_bbinop_env_equal op E1 E2 g ls1 ls2 E1' E2' g1' g2' cs1 cs2 lr1 lr2 :\n  env_equal E1 E2 ->\n  mk_env_bbinop op E1 g ls1 ls2 = (E1', g1', cs1, lr1) ->\n  mk_env_bbinop op E2 g ls1 ls2 = (E2', g2', cs2, lr2) ->\n  env_equal E1' E2' /\\ g1' = g2' /\\ cs1 = cs2 /\\ lr1 = lr2.\nProof.\n  case: op => /=.\n  - exact: mk_env_eq_env_equal.\n  - exact: mk_env_ult_env_equal.\n  - exact: mk_env_ule_env_equal.\n  - exact: mk_env_ugt_env_equal.\n  - exact: mk_env_uge_env_equal.\n  - exact: mk_env_slt_env_equal.\n  - exact: mk_env_sle_env_equal.\n  - exact: mk_env_sgt_env_equal.\n  - exact: mk_env_sge_env_equal.\n  - exact: mk_env_uaddo_env_equal.\n  - exact: mk_env_usubo_env_equal.\n  - exact: mk_env_umulo_env_equal.\n  - exact: mk_env_saddo_env_equal.\n  - exact: mk_env_ssubo_env_equal.\n  - exact: mk_env_smulo_env_equal.\nQed.\n\n\n\nFixpoint mk_env_exp_ccache m cc s E g e :\n  vm * compcache * env * generator * cnf * word :=\n  (* = mk_env_exp_nocet = *)\n  let mk_env_exp_nocet m cc s E g e :\n        vm * compcache * env * generator * cnf * word * cnf :=\n      match e with\n      | QFBV.Evar v =>\n        match find_het e cc with\n        | Some (cs, ls) => (m, cc, E, g, cs, ls, cs)\n        | None => match SSAVM.find v m with\n                  | None =>\n                    let '(E', g', cs, rs) := mk_env_var E g (SSAStore.acc v s) v in\n                    (SSAVM.add v rs m, add_het e cs rs cc, E', g', cs, rs, cs)\n                  | Some rs => (m, add_het e [::] rs cc, E, g, [::], rs, [::])\n                  end\n        end\n      | QFBV.Econst bs =>\n        match find_het e cc with\n        | Some (cs, ls) => (m, cc, E, g, cs, ls, cs)\n        | None => let '(E', g', cs, rs) := mk_env_const E g bs in\n                  (m, add_het e cs rs cc, E', g', cs, rs, cs)\n        end\n      | QFBV.Eunop op e1 =>\n        let '(m1, cc1, E1, g1, cs1, ls1) := mk_env_exp_ccache m cc s E g e1 in\n        match find_het e cc1 with\n        | Some (csop, lsop) => (m1, cc1, E1, g1, catrev cs1 csop, lsop, csop)\n        | None =>\n          let '(Eop, gop, csop, lsop) := mk_env_eunop op E1 g1 ls1 in\n          (m1, add_het e csop lsop cc1, Eop, gop, catrev cs1 csop, lsop, csop)\n        end\n      | QFBV.Ebinop op e1 e2 =>\n        let '(m1, cc1, E1, g1, cs1, ls1) := mk_env_exp_ccache m cc s E g e1 in\n        let '(m2, cc2, E2, g2, cs2, ls2) := mk_env_exp_ccache m1 cc1 s E1 g1 e2 in\n        match find_het e cc2 with\n        | Some (csop, lsop) => (m2, cc2, E2, g2, catrev cs1 (catrev cs2 csop), lsop, csop)\n        | None =>\n          let '(Eop, gop, csop, lsop) := mk_env_ebinop op E2 g2 ls1 ls2 in\n          (m2, add_het e csop lsop cc2, Eop, gop, catrev cs1 (catrev cs2 csop), lsop, csop)\n        end\n      | QFBV.Eite c e1 e2 =>\n        let '(mc, ccc, Ec, gc, csc, lc) := mk_env_bexp_ccache m cc s E g c in\n        let '(m1, cc1, E1, g1, cs1, ls1) := mk_env_exp_ccache mc ccc s Ec gc e1 in\n        let '(m2, cc2, E2, g2, cs2, ls2) := mk_env_exp_ccache m1 cc1 s E1 g1 e2 in\n        match find_het e cc2 with\n        | Some (csop, lsop) =>\n          (m2, cc2, E2, g2, catrev csc (catrev cs1 (catrev cs2 csop)), lsop, csop)\n        | None =>\n          let '(Eop, gop, csop, lsop) := mk_env_ite E2 g2 lc ls1 ls2 in\n          (m2, add_het e csop lsop cc2, Eop, gop,\n           catrev csc (catrev cs1 (catrev cs2 csop)), lsop, csop)\n        end\n      end\n  (* = = *)\n  in\n  match CompCache.find_cet e cc with\n  | Some (cs, ls) => (m, cc, E, g, [::], ls)\n  | None => let '(m', cc', E', g', cs, lrs, csop) := mk_env_exp_nocet m cc s E g e in\n            (m', CompCache.add_cet e csop lrs cc', E', g', cs, lrs)\n  end\nwith\nmk_env_bexp_ccache m cc s E g e : vm * compcache * env * generator * cnf * literal :=\n  (* = mk_env_bexp_nocbt = *)\n  let mk_env_bexp_nocbt m cc s E g e :\n        vm * compcache * env * generator * cnf * literal * cnf :=\n      match e with\n      | QFBV.Bfalse =>\n        match find_hbt e cc with\n        | Some (cs, l) => (m, cc, E, g, cs, l, cs)\n        | None => (m, add_hbt e [::] lit_ff cc, E, g, [::], lit_ff, [::])\n        end\n      | QFBV.Btrue =>\n        match find_hbt e cc with\n        | Some (cs, l) => (m, cc, E, g, cs, l, cs)\n        | None => (m, add_hbt e [::] lit_tt cc, E, g, [::], lit_tt, [::])\n        end\n      | QFBV.Bbinop op e1 e2 =>\n        let '(m1, cc1, E1, g1, cs1, ls1) := mk_env_exp_ccache m cc s E g e1 in\n        let '(m2, cc2, E2, g2, cs2, ls2) := mk_env_exp_ccache m1 cc1 s E1 g1 e2 in\n        match find_hbt e cc2 with\n        | Some (csop, lop) => (m2, cc2, E2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None =>\n          let '(Eop, gop, csop, lop) := mk_env_bbinop op E2 g2 ls1 ls2 in\n          (m2, add_hbt e csop lop cc2, Eop, gop, catrev cs1 (catrev cs2 csop), lop, csop)\n        end\n      | QFBV.Blneg e1 =>\n        let '(m1, cc1, E1, g1, cs1, l1) := mk_env_bexp_ccache m cc s E g e1 in\n        match find_hbt e cc1 with\n        | Some (csop, lop) => (m1, cc1, E1, g1, catrev cs1 csop, lop, csop)\n        | None => let '(Eop, gop, csop, lop) := mk_env_lneg E1 g1 l1 in\n                  (m1, add_hbt e csop lop cc1, Eop, gop, catrev cs1 csop, lop, csop)\n        end\n      | QFBV.Bconj e1 e2 =>\n        let '(m1, cc1, E1, g1, cs1, l1) := mk_env_bexp_ccache m cc s E g e1 in\n        let '(m2, cc2, E2, g2, cs2, l2) := mk_env_bexp_ccache m1 cc1 s E1 g1 e2 in\n        match find_hbt e cc2 with\n        | Some (csop, lop) => (m2, cc2, E2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => let '(Eop, gop, csop, lop) := mk_env_conj E2 g2 l1 l2 in\n                  (m2, add_hbt e csop lop cc2, Eop, gop,\n                   catrev cs1 (catrev cs2 csop), lop, csop)\n        end\n      | QFBV.Bdisj e1 e2 =>\n        let '(m1, cc1, E1, g1, cs1, l1) := mk_env_bexp_ccache m cc s E g e1 in\n        let '(m2, cc2, E2, g2, cs2, l2) := mk_env_bexp_ccache m1 cc1 s E1 g1 e2 in\n        match find_hbt e cc2 with\n        | Some (csop, lop) => (m2, cc2, E2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => let '(Eop, gop, csop, lop) := mk_env_disj E2 g2 l1 l2 in\n                  (m2, add_hbt e csop lop cc2, Eop, gop,\n                   catrev cs1 (catrev cs2 csop), lop, csop)\n        end\n      end\n  (* = = *)\n  in\n  match CompCache.find_cbt e cc with\n  | Some (cs, l) => (m, cc, E, g, [::], l)\n  | None => let '(m', cc', E', g', cs, lr, csop) := mk_env_bexp_nocbt m cc s E g e in\n            (m', CompCache.add_cbt e csop lr cc', E', g', cs, lr)\n  end.\n\n\nLemma mk_env_exp_ccache_equation :\n  forall m cc s E g e,  mk_env_exp_ccache m cc s E g e =\n  (* = mk_env_exp_nocet = *)\n  let mk_env_exp_nocet m cc s E g e :\n        vm * compcache * env * generator * cnf * word * cnf :=\n      match e with\n      | QFBV.Evar v =>\n        match find_het e cc with\n        | Some (cs, ls) => (m, cc, E, g, cs, ls, cs)\n        | None => match SSAVM.find v m with\n                  | None =>\n                    let '(E', g', cs, rs) := mk_env_var E g (SSAStore.acc v s) v in\n                    (SSAVM.add v rs m, add_het e cs rs cc, E', g', cs, rs, cs)\n                  | Some rs => (m, add_het e [::] rs cc, E, g, [::], rs, [::])\n                  end\n        end\n      | QFBV.Econst bs =>\n        match find_het e cc with\n        | Some (cs, ls) => (m, cc, E, g, cs, ls, cs)\n        | None => let '(E', g', cs, rs) := mk_env_const E g bs in\n                  (m, add_het e cs rs cc, E', g', cs, rs, cs)\n        end\n      | QFBV.Eunop op e1 =>\n        let '(m1, cc1, E1, g1, cs1, ls1) := mk_env_exp_ccache m cc s E g e1 in\n        match find_het e cc1 with\n        | Some (csop, lsop) => (m1, cc1, E1, g1, catrev cs1 csop, lsop, csop)\n        | None =>\n          let '(Eop, gop, csop, lsop) := mk_env_eunop op E1 g1 ls1 in\n          (m1, add_het e csop lsop cc1, Eop, gop, catrev cs1 csop, lsop, csop)\n        end\n      | QFBV.Ebinop op e1 e2 =>\n        let '(m1, cc1, E1, g1, cs1, ls1) := mk_env_exp_ccache m cc s E g e1 in\n        let '(m2, cc2, E2, g2, cs2, ls2) := mk_env_exp_ccache m1 cc1 s E1 g1 e2 in\n        match find_het e cc2 with\n        | Some (csop, lsop) => (m2, cc2, E2, g2, catrev cs1 (catrev cs2 csop), lsop, csop)\n        | None =>\n          let '(Eop, gop, csop, lsop) := mk_env_ebinop op E2 g2 ls1 ls2 in\n          (m2, add_het e csop lsop cc2, Eop, gop, catrev cs1 (catrev cs2 csop), lsop, csop)\n        end\n      | QFBV.Eite c e1 e2 =>\n        let '(mc, ccc, Ec, gc, csc, lc) := mk_env_bexp_ccache m cc s E g c in\n        let '(m1, cc1, E1, g1, cs1, ls1) := mk_env_exp_ccache mc ccc s Ec gc e1 in\n        let '(m2, cc2, E2, g2, cs2, ls2) := mk_env_exp_ccache m1 cc1 s E1 g1 e2 in\n        match find_het e cc2 with\n        | Some (csop, lsop) =>\n          (m2, cc2, E2, g2, catrev csc (catrev cs1 (catrev cs2 csop)), lsop, csop)\n        | None =>\n          let '(Eop, gop, csop, lsop) := mk_env_ite E2 g2 lc ls1 ls2 in\n          (m2, add_het e csop lsop cc2, Eop, gop,\n           catrev csc (catrev cs1 (catrev cs2 csop)), lsop, csop)\n        end\n      end\n  (* = = *)\n  in\n  match CompCache.find_cet e cc with\n  | Some (cs, ls) => (m, cc, E, g, [::], ls)\n  | None => let '(m', cc', E', g', cs, lrs, csop) := mk_env_exp_nocet m cc s E g e in\n            (m', CompCache.add_cet e csop lrs cc', E', g', cs, lrs)\n  end .\nProof. move=> m cc s E g e. elim e; done. Qed.\n\nLemma mk_env_bexp_ccache_equation :\n  forall m cc s E g e,\n    mk_env_bexp_ccache m cc s E g e =\n  (* = mk_env_bexp_nocbt = *)\n  let mk_env_bexp_nocbt m cc s E g e :\n        vm * compcache * env * generator * cnf * literal * cnf :=\n      match e with\n      | QFBV.Bfalse =>\n        match find_hbt e cc with\n        | Some (cs, l) => (m, cc, E, g, cs, l, cs)\n        | None => (m, add_hbt e [::] lit_ff cc, E, g, [::], lit_ff, [::])\n        end\n      | QFBV.Btrue =>\n        match find_hbt e cc with\n        | Some (cs, l) => (m, cc, E, g, cs, l, cs)\n        | None => (m, add_hbt e [::] lit_tt cc, E, g, [::], lit_tt, [::])\n        end\n      | QFBV.Bbinop op e1 e2 =>\n        let '(m1, cc1, E1, g1, cs1, ls1) := mk_env_exp_ccache m cc s E g e1 in\n        let '(m2, cc2, E2, g2, cs2, ls2) := mk_env_exp_ccache m1 cc1 s E1 g1 e2 in\n        match find_hbt e cc2 with\n        | Some (csop, lop) => (m2, cc2, E2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None =>\n          let '(Eop, gop, csop, lop) := mk_env_bbinop op E2 g2 ls1 ls2 in\n          (m2, add_hbt e csop lop cc2, Eop, gop, catrev cs1 (catrev cs2 csop), lop, csop)\n        end\n      | QFBV.Blneg e1 =>\n        let '(m1, cc1, E1, g1, cs1, l1) := mk_env_bexp_ccache m cc s E g e1 in\n        match find_hbt e cc1 with\n        | Some (csop, lop) => (m1, cc1, E1, g1, catrev cs1 csop, lop, csop)\n        | None => let '(Eop, gop, csop, lop) := mk_env_lneg E1 g1 l1 in\n                  (m1, add_hbt e csop lop cc1, Eop, gop, catrev cs1 csop, lop, csop)\n        end\n      | QFBV.Bconj e1 e2 =>\n        let '(m1, cc1, E1, g1, cs1, l1) := mk_env_bexp_ccache m cc s E g e1 in\n        let '(m2, cc2, E2, g2, cs2, l2) := mk_env_bexp_ccache m1 cc1 s E1 g1 e2 in\n        match find_hbt e cc2 with\n        | Some (csop, lop) => (m2, cc2, E2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => let '(Eop, gop, csop, lop) := mk_env_conj E2 g2 l1 l2 in\n                  (m2, add_hbt e csop lop cc2, Eop, gop,\n                   catrev cs1 (catrev cs2 csop), lop, csop)\n        end\n      | QFBV.Bdisj e1 e2 =>\n        let '(m1, cc1, E1, g1, cs1, l1) := mk_env_bexp_ccache m cc s E g e1 in\n        let '(m2, cc2, E2, g2, cs2, l2) := mk_env_bexp_ccache m1 cc1 s E1 g1 e2 in\n        match find_hbt e cc2 with\n        | Some (csop, lop) => (m2, cc2, E2, g2, catrev cs1 (catrev cs2 csop), lop, csop)\n        | None => let '(Eop, gop, csop, lop) := mk_env_disj E2 g2 l1 l2 in\n                  (m2, add_hbt e csop lop cc2, Eop, gop,\n                   catrev cs1 (catrev cs2 csop), lop, csop)\n        end\n      end\n  (* = = *)\n  in\n  match CompCache.find_cbt e cc with\n  | Some (cs, l) => (m, cc, E, g, [::], l)\n  | None => let '(m', cc', E', g', cs, lr, csop) := mk_env_bexp_nocbt m cc s E g e in\n            (m', CompCache.add_cbt e csop lr cc', E', g', cs, lr)\n  end.\nProof. move=> m cc s E g e. elim e; done. Qed.\n\n", "meta": {"author": "fmlab-iis", "repo": "coq-qfbv", "sha": "0e9521febd1564747723a773d25e54781e81b762", "save_path": "github-repos/coq/fmlab-iis-coq-qfbv", "path": "github-repos/coq/fmlab-iis-coq-qfbv/coq-qfbv-0e9521febd1564747723a773d25e54781e81b762/src/bbcache/BitBlastingCCacheDef.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.24615464138712362}}
{"text": "Require Import List.\nRequire Import Coq.Lists.ListSet.\nRequire Import Omega.\n\nRequire Import Stream.\nRequire Import Unify.\nRequire Import MiniKanrenSyntax.\nRequire Import OperationalSem.\nRequire Import DenotationalSem.\n\n\nModule OperationalSemCompletenessAbstr (CS : ConstraintStoreSig).\n\nImport CS.\n\nModule OperationalSemCS := OperationalSemAbstr CS.\n\nImport OperationalSemCS.\n\nLemma search_completeness_generalized\n      (l    : nat)\n      (g    : goal)\n      (CG   : consistent_goal g)\n      (s    : subst)\n      (cs   : constraint_store s)\n      (n    : nat)\n      (WF   : well_formed_state' (Leaf g s cs n))\n      (t    : trace)\n      (OP   : op_sem (State (Leaf g s cs n)) t)\n      (f    : repr_fun)\n      (DSG  : [| l | g , f |])\n      (DSS  : [ s , f ])\n      (DSCS : [| s , cs , f |]) :\n      exists (f' : repr_fun), {| t , f' |} /\\\n                            forall (x : name), x < n -> gt_eq (f x) (f' x).\nProof.\n  revert OP. revert t. revert CG DSG DSS DSCS WF. revert cs. revert g f s n. induction l.\n  { intros. apply in_denotational_sem_zero_lev in DSG. contradiction. }\n  { induction g; intros; good_inversion CG.\n    { good_inversion DSG. }\n    { exists f. split.\n      { econstructor. eexists. eexists. split; eauto.\n        good_inversion OP. good_inversion EV. simpl_existT_cs_same. constructor. }\n      { intros; red; auto. } }\n    { exists f. split.\n      2: intros; red; auto.\n      good_inversion OP. good_inversion EV; good_inversion DSG; simpl_existT_cs_same.\n      { destruct DSS as [fs COMP_s_fs]. red in UNI.\n        rewrite <- (repr_fun_eq_apply _ _ t COMP_s_fs) in UNI.\n        rewrite <- (repr_fun_eq_apply _ _ t0 COMP_s_fs) in UNI.\n        rewrite (repr_fun_apply_compose s fs t) in UNI.\n        rewrite (repr_fun_apply_compose s fs t0) in UNI.\n        apply unfier_from_gt_unifier in UNI.\n        destruct UNI as [sc [SC_UNIFIES _]]. specialize (mgu_non_unifiable _ _ MGU sc).\n        contradiction. }\n      { specialize (upd_cs_fail_condition _ _ _ UPD_CS f).\n        intros C. exfalso. apply C. split; auto.\n        apply (denotational_sem_uni _ _ _ _ MGU); auto. }\n      { red. exists (compose s d). exists cs'. exists n. split.\n        { constructor. }\n        { apply and_comm. specialize (upd_cs_success_condition _ _ _ _ UPD_CS f).\n          intro EQUI. apply EQUI. split; auto. apply (denotational_sem_uni _ _ _ _ MGU); auto. } } }\n    { exists f. split.\n      2: intros; red; auto.\n      good_inversion DSG. good_inversion OP.\n      good_inversion EV; simpl_existT_cs_same.\n      { exfalso. eapply add_constraint_fail_condition in ADD_C. eauto. }\n      { red. exists s. exists cs'. exists n. split.\n        { constructor. }\n        { apply and_comm. eapply add_constraint_success_condition in ADD_C.\n          apply ADD_C. auto. } } }\n    { good_inversion OP. inversion EV; subst.\n      apply well_formedness_preservation in EV; auto. good_inversion EV. simpl_existT_cs_same.\n      good_inversion wfState.\n      specialize (op_sem_exists (State (Leaf g1 s cs n))). intro p1. destruct p1 as [t1 OP1].\n      specialize (op_sem_exists (State (Leaf g2 s cs n))). intro p2. destruct p2 as [t2 OP2].\n      specialize (sum_op_sem _ _ _ _ _ OP1 OP2 OP0). intro Hinter.\n      good_inversion DSG.\n      { specialize (IHg1 f s n cs CG_G1 DSG0 DSS DSCS WF_L t1 OP1).\n        destruct IHg1 as [f' [HinDA ff'_eq]]. exists f'. split; auto.\n        red in HinDA. destruct HinDA as [sr [csr [nr [Hin [DSSr DSCSr]]]]].\n        red. exists sr. exists csr. exists nr. split; auto. constructor.\n        apply (interleave_in _ _ _ Hinter (Answer sr csr nr)). auto. }\n      { specialize (IHg2 f s n cs CG_G2 DSG0 DSS DSCS WF_R t2 OP2).\n        destruct IHg2 as [f' [HinDA ff'_eq]]. exists f'. split; auto.\n        red in HinDA. destruct HinDA as [sr [csr [nr [Hin [DSSr DSCSr]]]]].\n        red. exists sr. exists csr. exists nr. split; auto. constructor.\n        apply (interleave_in _ _ _ Hinter (Answer sr csr nr)). auto. } }\n    { good_inversion DSG. good_inversion OP. inversion EV; simpl_existT_cs_same; subst.\n      specialize (op_sem_exists (State (Leaf g1 s cs n))). intro p1. destruct p1 as [t1 OP1].\n      assert (wfst'1 : well_formed_state' (Leaf g1 s cs n)).\n      { constructor; good_inversion WF; simpl_existT_cs_same; auto. }\n      specialize (IHg1 f s n cs CG_G1 DSG_L DSS DSCS wfst'1 t1 OP1).\n      destruct IHg1 as [f' [HinDA ff'_eq]]. red in HinDA.\n      destruct HinDA as [s' [cs' [n' [Hinstr' [HDAS' HDACS']]]]].\n      specialize (op_sem_exists (State (Leaf g2 s' cs' n'))). intro p2. destruct p2 as [t2 OP2].\n      specialize (counter_in_trace _ _ _ _ _ _ _ _ OP1 Hinstr'). intro n_le_n'.\n      assert (wfst'2 : well_formed_state' (Leaf g2 s' cs' n')).\n      { good_inversion WF. simpl_existT_cs_same.\n        destruct (well_formed_subst_in_trace _ (wfNonEmpty _ wfst'1)  _ OP1 _ _ _ Hinstr').\n        specialize (well_formed_ds_in_trace _ (wfNonEmpty _ wfst'1)  _ OP1 _ _ _ Hinstr').\n        intros. constructor; auto. intros.\n        apply lt_le_trans with n; auto. }\n      assert (Hg2' : in_denotational_sem_lev_goal (S l) g2 f').\n      { apply completeness_condition_lev with f; auto. intros. apply ff'_eq.\n        good_inversion WF. auto. }\n      specialize (IHg2 f' s' n' cs' CG_G2 Hg2' HDAS' HDACS' wfst'2 t2 OP2).\n      destruct IHg2 as [f'' [HinDA f'f''_eq]]. red in HinDA.\n      destruct HinDA as [s'' [cs'' [n'' [Hinstr'' [HDAS'' HDACS'']]]]].\n      exists f''. split.\n      { red. exists s''. exists cs''. exists n''. split; auto.\n        constructor. eapply prod_op_sem_in; eauto. }\n      { intros. red. apply eq_trans with (proj1_sig (f' x)).\n        { apply ff'_eq. auto. }\n        { apply f'f''_eq. omega. } } }\n    { good_inversion DSG. good_inversion OP. inversion EV; simpl_existT_cs_same; subst.\n      apply well_formedness_preservation in EV; auto. good_inversion EV.\n      rename fn into fa.\n      remember (fun x => if name_eq_dec x n\n                         then fa a\n                         else f x) as fn.\n      assert (Hgn : [| S l | g n , fn |]).\n      { good_inversion WF. apply den_sem_another_fresh_var with n a fa; auto.\n        { intro C. apply FV_LT_COUNTER in C. omega. }\n        {  destruct (name_eq_dec n n); try contradiction. reflexivity. }\n        { intros. destruct (name_eq_dec x n); try contradiction. auto. } }\n      assert (DSSn_AND_DSCSn : [ s , fn ] /\\ [| s , cs , fn |]).\n      { good_inversion WF. simpl_existT_cs_same. apply (DS_LT_COUNTER f); auto.\n        intros. destruct (name_eq_dec x n); try omega. reflexivity. }\n      destruct DSSn_AND_DSCSn as [DSSn DSCSn].\n      specialize (H n fn s (S n) cs (CG_BODY n) Hgn DSSn DSCSn wfState t0 OP0).\n      destruct H as [f' [HinDA ff'_eq]]. exists f'. split.\n      { red. red in HinDA. destruct HinDA as [s' [cs' [n' [Hinstr [HDAS HDACS]]]]].\n        exists s'. exists cs'. exists n'. split; auto. constructor; auto. }\n      { intros. assert (x < S n). { omega. }\n        specialize (ff'_eq x H0). red in ff'_eq. red. rewrite <- ff'_eq.\n        rewrite Heqfn. destruct (name_eq_dec x n); try omega. reflexivity. } }\n    { good_inversion DSG. good_inversion OP. inversion EV; subst.\n      apply well_formedness_preservation in EV; auto. good_inversion EV. simpl_existT_cs_same.\n      assert (cg_body : consistent_goal (proj1_sig (MiniKanrenSyntax.Prog n) t)).\n      { remember (MiniKanrenSyntax.Prog n) as d. destruct d as [rel [Hcl Hco]].\n        red in Hco. destruct (Hco t) as [Hcog Hcof]. auto. }\n      specialize (IHl (proj1_sig (MiniKanrenSyntax.Prog n) t) f s n0 cs cg_body DSG0 DSS DSCS wfState t1 OP0).\n      destruct IHl as [f' [HinDA ff'_eq]]. exists f'. split; auto.\n      red. red in HinDA. destruct HinDA as [s' [cs' [n' [Hinstr [HDAS HDACS]]]]].\n      exists s'. exists cs'. exists n'. split; auto. constructor; auto. } }\nQed.\n\nLemma search_completeness\n      (g   : goal)\n      (CG  : consistent_goal g)\n      (k   : nat)\n      (HC  : closed_goal_in_context (first_nats k) g)\n      (f   : repr_fun)\n      (t   : trace)\n      (OP : op_sem (State (Leaf g empty_subst init_cs k)) t)\n      (HDS : [| g , f |]) :\n      exists (f' : repr_fun), {| t , f' |} /\\\n                            forall (x : name), In x (first_nats k) -> gt_eq (f x) (f' x).\nProof.\n  apply in_denotational_sem_some_lev in HDS. destruct HDS as [l HDS].\n  assert (WF : well_formed_state' (Leaf g empty_subst init_cs k)).\n  { apply well_formed_initial_state; auto. }\n  specialize (search_completeness_generalized l g CG empty_subst init_cs k WF t OP f HDS (empty_subst_ds f) (init_condition f)).\n  intro. destruct H as [f' [HinDA ff'eq]]. exists f'. split; auto.\n  intros. apply ff'eq. apply first_nats_less; auto.\nQed.\n\nEnd OperationalSemCompletenessAbstr.\n", "meta": {"author": "miniKanren-disequality-semantics", "repo": "coq", "sha": "322b9406f7140d5005603cae456ec54d4646a246", "save_path": "github-repos/coq/miniKanren-disequality-semantics-coq", "path": "github-repos/coq/miniKanren-disequality-semantics-coq/coq-322b9406f7140d5005603cae456ec54d4646a246/src/OpSemCompleteness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2461340827375984}}
{"text": "(**  Mathematical model of the causal memory implementation\n     from \"Causal memory: definitions, implementation, and programming\"\n     (https://link.springer.com/article/10.1007/BF01784241).*)\n\nFrom aneris.aneris_lang Require Import lang resources.\nFrom stdpp Require Import gmap.\nFrom aneris.prelude Require Import misc.\nFrom aneris.examples.ccddb.spec Require Import base.\nFrom aneris.examples.ccddb.model Require Export events model_spec model_lhst.\n\n(** Global state validity implementation. *)\nSection Global_state_valid.\n  Context `{!anerisG Mdl Σ, !DB_params}.\n\n  (* The following two definitions capture the fact that the\n       union of erasure of s_i (for i = 1 to n) is in M *)\n\n  Definition DBM_lhst_in_gmem (M : gmap Key (gset write_event))\n             (s: gset apply_event) :=\n    ∀ e, e ∈ s → ∃ h, M !! e.(ae_key) = Some h ∧ erase e ∈ h.\n\n  Definition DBM_gs_hst_in_gs_mem (gs : Gst) : Prop :=\n    ∀ s, s ∈ gs.(Gst_hst) → DBM_lhst_in_gmem gs.(Gst_mem) s.\n\n  (* The following definition captures that the write events in the global\n       memory come from the sections s_ii (for i = 1 to n) *)\n  Definition DBM_gs_mem_in_gs_hst (gs : Gst) :=\n    ∀ a h, gs.(Gst_mem) !! a.(we_key) = Some h → a ∈ h →\n           ∃ s si e, gs.(Gst_hst) !! a.(we_orig) = Some s ∧\n                     DBM_lsec a.(we_orig) s = si ∧\n                     e ∈ si ∧ erase e = a.\n\n  Definition DBM_gs_hst_valid (gs : Gst) :=\n    ∀ i s, gs.(Gst_hst) !! i = Some s → DBM_lhst_valid i s.\n\n  Definition DBM_dom (gs : Gst) :=\n    dom gs.(Gst_mem) = DB_keys.\n\n  Definition DBM_gs_hst_size (gs : Gst) :=\n    length gs.(Gst_hst) = length DB_addresses.\n\n  Definition DBM_gs_gmem_elements_key (gs : Gst) :=\n    ∀ k h a, gs.(Gst_mem) !! k = Some h → a ∈ h → k = a.(we_key).\n\n  (** Valid Global states *)\n  Record DBM_Gst_valid (gs: Gst) : Prop :=\n    {\n    DBM_GV_dom : DBM_dom gs;\n    DBM_GV_hst_size : DBM_gs_hst_size gs;\n    DBM_GV_hst_lst_valid : DBM_gs_hst_valid gs ;\n    DBM_GV_hst_in_mem : DBM_gs_hst_in_gs_mem gs;\n    DBM_GV_mem_in_hst : DBM_gs_mem_in_gs_hst gs;\n    DBM_GV_mem_elements_key : DBM_gs_gmem_elements_key gs;\n    }.\n\n  Global Arguments DBM_GV_dom {_} _.\n  Global Arguments DBM_GV_hst_size {_} _.\n  Global Arguments DBM_GV_hst_lst_valid {_} _.\n  Global Arguments DBM_GV_hst_in_mem {_} _.\n  Global Arguments DBM_GV_mem_in_hst {_} _.\n  Global Arguments DBM_GV_mem_elements_key {_} _.\n\n  Lemma DBM_gs_mem_in_gs_hst_aux (gs : Gst) :\n    DBM_Gst_valid gs →\n    ∀ a h k, gs.(Gst_mem) !! k = Some h → a ∈ h →\n             ∃ s si e, gs.(Gst_hst) !! a.(we_orig) = Some s ∧\n                       DBM_lsec a.(we_orig) s = si ∧\n                       e ∈ si ∧ erase e = a .\n  Proof.\n    intros Hvg a h k Hkh Hah.\n    pose proof (DBM_GV_mem_elements_key Hvg k h a Hkh Hah) as ->.\n      by eapply DBM_GV_mem_in_hst.\n  Qed.\n\n  Global Arguments DBM_gs_mem_in_gs_hst_aux {_} _.\n\n  Lemma DBM_Gst_valid_hst_ith gs i s :\n    DBM_Gst_valid gs →\n    gs.(Gst_hst) !! i = Some s →\n    i < length DB_addresses.\n  Proof.\n    intros Hvg His.\n    apply lookup_lt_Some in His.\n      by pose proof (DBM_GV_hst_size Hvg) as <- .\n  Qed.\n\n  Lemma we_in_valid_gs_orig gs k a h :\n    DBM_Gst_valid gs →\n    gs.(Gst_mem) !! k = Some h → a ∈ h →\n    a.(we_orig) < length DB_addresses.\n  Proof.\n    intros Hvg Hkh Hak.\n    pose proof (DBM_gs_mem_in_gs_hst_aux Hvg a h k Hkh Hak)\n      as (s & sr & e & Hs & <- & Her & Hea).\n    pose proof (DBM_GV_hst_lst_valid Hvg  (we_orig a) s Hs).\n      by eapply DBM_LHV_bound_at.\n  Qed.\n\n  Lemma we_in_valid_gs_time gs k a h :\n    DBM_Gst_valid gs →\n    gs.(Gst_mem) !! k = Some h → a ∈ h →\n    ∃ p, 0 < p ∧ a.(we_time) !! a.(we_orig) = Some p.\n  Proof.\n    intros Hvg Hkh Hak.\n    pose proof (DBM_gs_mem_in_gs_hst_aux Hvg a h k Hkh Hak)\n      as (s & sr & e & Hs & <- & Her & Hea); subst.\n    pose proof (DBM_GV_hst_lst_valid Hvg (we_orig (erase e)) s Hs) as Hsv.\n    assert ((erase e).(we_orig) < length DB_addresses) as Hao.\n    { by eapply we_in_valid_gs_orig. }\n    pose proof (DBM_LHV_secs_valid Hsv (we_orig (erase e)) Hao) as Hsrv.\n    assert (is_Some (ae_time e !! (we_orig (erase e)))) as [q Hq].\n    eapply in_lhs_time_component;\n      eauto using in_lsec_in_lhst.\n    rewrite erase_time.\n    exists q; split; try done.\n    eapply DBM_LSV_strongly_complete; [|done|by eauto|by eauto].\n    eapply DBM_LHV_times; eauto.\n  Qed.\n\n  Lemma DBM_Gst_valid_empty : DBM_Gst_valid empty_Gst.\n  Proof.\n    split; [| | | | |];\n      rewrite /empty_Gst /empty_gmem /empty_lhsts\n              /DBM_dom /DBM_gs_hst_size /DBM_gs_hst_valid\n              /DBM_gs_hst_in_gs_mem /DBM_gs_mem_in_gs_hst\n              / DBM_gs_gmem_elements_key //=.\n    - eauto using dom_gset_to_gmap.\n    - by rewrite fmap_length.\n    - intros ? ?; rewrite list_lookup_fmap.\n      pose proof (lookup_lt_is_Some_1 DB_addresses i).\n      destruct (_ !! _); simpl; last done.\n      intros ?; simplify_eq.\n      apply empty_lhst_valid; eauto.\n    - intros s.\n      rewrite elem_of_list_fmap.\n        by intros (?&->&?) ? ?.\n    - intros a ?; rewrite lookup_gset_to_gmap.\n      destruct (decide (we_key a ∈ DB_keys));\n        last by rewrite option_guard_False.\n        by rewrite option_guard_True //; intros ?; simplify_eq.\n    - intros k ? ?; rewrite lookup_gset_to_gmap.\n      destruct (decide (k ∈ DB_keys));\n        last by rewrite option_guard_False.\n        by rewrite option_guard_True //; intros ?; simplify_eq.\n  Qed.\n\n  Lemma DBM_Gst_valid_gmem_ext_internal\n        (gs : Gst) (k k' : Key) (h h' : gset write_event) (a a' : write_event) :\n    DBM_Gst_valid gs →\n    gs.(Gst_mem) !! k = Some h → gs.(Gst_mem) !! k' = Some h' →\n    a ∈ h → a' ∈ h' →\n    a.(we_orig) = a'.(we_orig) →\n    a.(we_time) !! a.(we_orig) = a'.(we_time) !! a.(we_orig) →\n    a = a'.\n  Proof.\n    intros Hvg Hkh Hkh' Hak Hak' Horg Htime.\n    pose proof (DBM_gs_mem_in_gs_hst_aux Hvg a h k Hkh Hak)\n      as (s & sr & e & Hs & <- & Her & Hea); subst.\n    pose proof (DBM_gs_mem_in_gs_hst_aux Hvg a' h' k' Hkh' Hak')\n      as (s' & sr' & e' & Hs' & <- & Her' & Hea'); subst.\n    rewrite -Horg in Hs', Her'.\n    assert (s' = s) as -> by naive_solver; clear Hs'.\n    pose proof (DBM_GV_hst_lst_valid Hvg  (we_orig (erase e)) s Hs) as Hsv.\n    assert ((erase e).(we_orig) < length DB_addresses) as Hao.\n    { by eapply (we_in_valid_gs_orig gs _ (erase e) h). }\n    pose proof (DBM_LHV_secs_valid Hsv (we_orig (erase e)) Hao) as Hsrv.\n    pose proof (DBM_LSV_ext (DBM_LHV_times Hsv) Hao Hsrv) as Hext.\n    f_equal.\n      by apply Hext; auto; rewrite -!erase_time.\n  Qed.\n\n  Lemma DBM_Gst_valid_gmem_ext_internal_2\n        (gs : Gst) (k k' : Key) (h h' : gset write_event) (a1 a2 : write_event):\n    DBM_Gst_valid gs →\n    gs.(Gst_mem) !! k = Some h → gs.(Gst_mem) !! k' = Some h' →\n    a1 ∈ h → a2 ∈ h' → (we_time a1) = (we_time a2) → a1 = a2.\n  Proof.\n    intros Hvg Hkh Hkh' Hah Hah' Heq.\n    destruct (decide (a1.(we_orig) = a2.(we_orig))) as [Horg | Horg ].\n    - eapply (DBM_Gst_valid_gmem_ext_internal gs k k' h h'); auto.\n      rewrite Heq; done.\n    - pose proof (DBM_gs_mem_in_gs_hst_aux Hvg a1 h k Hkh Hah)\n        as (s & sr & e1 & Hs & <- & Her & Hea); subst.\n      pose proof (DBM_GV_hst_lst_valid Hvg _ _ Hs) as Hoe1s.\n      pose proof (DBM_gs_mem_in_gs_hst_aux Hvg a2 h' k' Hkh' Hah')\n        as (s' & sr' & e2 & Hs' & <- & Her' & Hea'); subst.\n      pose proof (DBM_GV_hst_lst_valid Hvg _ _ Hs') as Hoe2s'.\n      assert (we_orig (erase e2) < length DB_addresses) as He2dba\n          by eauto using we_in_valid_gs_orig.\n      assert (∃ q, (erase e1).(we_time) !! (we_orig (erase e2)) = Some q)\n        as [q Hq].\n      { rewrite erase_time.\n        destruct (in_lhs_time_component e1 (we_orig (erase e2))\n                                        (we_orig (erase e1)) s);\n          eauto using in_lsec_in_lhst, we_in_valid_gs_orig. }\n      destruct (DBM_lsec_causality_lemma (we_orig (erase e1)) s e1 q q\n                                         (we_orig (erase e2)))\n        as (e12&He2s&He2tm); eauto using we_in_valid_gs_orig, in_lsec_in_lhst.\n      { eapply (DBM_LSV_strongly_complete\n                  (DBM_LHV_times Hoe2s') He2dba\n                  (DBM_LHV_secs_valid Hoe2s' (we_orig (erase e2)) He2dba)).\n        eexists; split; eauto.\n        rewrite -erase_time.\n        rewrite -Heq; done. }\n      { by rewrite -erase_time. }\n      assert (e12 = e1) as He121.\n      { eapply DBM_LHV_ext; first apply Hoe1s; eauto using in_lsec_in_lhst.\n        pose proof (DBM_GV_hst_in_mem Hvg) as Hgh.\n        assert (s ∈ Gst_hst gs) as Hsgs by by apply elem_of_list_lookup; eauto.\n        destruct (Hgh _ Hsgs e12) as (h'' & Hh''1 & He12);\n          first by eauto using in_lsec_in_lhst.\n        rewrite -!erase_time.\n        rewrite Heq.\n        f_equal.\n        symmetry.\n        eapply (DBM_Gst_valid_gmem_ext_internal _ _ _ h' h''); eauto.\n        - rewrite !erase_orig; erewrite !orig_in_lsec; eauto.\n        - rewrite !erase_time He2tm.\n          rewrite -erase_time.\n          rewrite -Heq; done. }\n      exfalso; apply Horg.\n      rewrite -He121 erase_orig.\n      erewrite orig_in_lsec; eauto.\n  Qed.\n\n  Lemma DBM_Gst_valid_gmem_ext\n        (gs : Gst) (k k' : Key) (h h' : gset write_event) (a a' : write_event):\n    DBM_Gst_valid gs →\n    gs.(Gst_mem) !! k = Some h → gs.(Gst_mem) !! k' = Some h' →\n    a ∈ h → a' ∈ h' → we_time a = we_time a' → a = a'.\n  Proof.\n    intros Hvg Hkh Hkh' Hah Hah' Heq.\n    apply (DBM_Gst_valid_gmem_ext_internal_2 gs k k' h h'); eauto.\n  Qed.\n\n  Lemma DBM_Gst_valid_lhst_ext\n        (gs : Gst) (i i' : nat) (s s' : gset apply_event) (e e' : apply_event):\n    DBM_Gst_valid gs →\n    gs.(Gst_hst) !! i = Some s →  gs.(Gst_hst) !! i' = Some s' →\n    e ∈ s → e' ∈ s' → ae_time e = ae_time e' →\n    e.(ae_key) = e'.(ae_key) ∧ e.(ae_val) = e'.(ae_val).\n  Proof.\n    intros Hgv ? ? He He' ?.\n    rewrite -!erase_key -!erase_val.\n    assert (erase e = erase e') as ->; last done.\n    edestruct (DBM_GV_hst_in_mem Hgv s) as (h & Hh & Hea);\n      eauto using elem_of_list_lookup_2.\n    edestruct (DBM_GV_hst_in_mem Hgv s') as (h' & Hh' & Hea');\n      eauto using elem_of_list_lookup_2.\n    eapply (DBM_Gst_valid_gmem_ext_internal_2 _ _ _ h h'); eauto.\n    rewrite -> !erase_time; done.\n  Qed.\n\nLemma DBM_Gst_valid_lhst_strong_ext\n        (gs : Gst) (i : nat) (s : gset apply_event) (e e' : apply_event):\n    DBM_Gst_valid gs →\n    gs.(Gst_hst) !! i = Some s →\n    e ∈ s → e' ∈ s → ae_time e = ae_time e' → e = e'.\n  Proof.\n    intros Hgv ? He He' ?.\n    eapply DBM_LHV_ext; eauto.\n    eapply DBM_GV_hst_lst_valid; eauto.\n  Qed.\n\n  Lemma DBM_Gst_valid_ae_provenance (gs : Gst) (i : nat) (s : gset apply_event)\n        (e : apply_event) :\n    DBM_Gst_valid gs → gs.(Gst_hst) !! i = Some s → e ∈ s →\n    ∃ (h : gset write_event), gs.(Gst_mem) !! e.(ae_key) = Some h ∧ erase e ∈ h.\n  Proof.\n    intros; eapply DBM_GV_hst_in_mem; eauto using elem_of_list_lookup_2.\n  Qed.\n\n  Lemma DBM_Gst_valid_causality\n        (gs : Gst) (i : nat) (s : gset apply_event) (k : Key)\n        (h: gset write_event) (e : apply_event) (a : write_event) :\n    DBM_Gst_valid gs →\n    gs.(Gst_mem) !! k = Some h → gs.(Gst_hst) !! i = Some s →\n    a ∈ h → e ∈ s → vector_clock_lt (we_time a) (ae_time e) →\n    ∃ e', e' ∈ (restrict_key k s) ∧ erase e' = a.\n  Proof.\n    intros Hvg Hkh His Hah Hes Hae.\n    pose proof (DBM_GV_mem_elements_key Hvg k h a Hkh Hah) as ->.\n    assert (∃ p,  0 < p ∧ a.(we_time) !! a.(we_orig) = Some p)\n      as (p & H0p & Harp).\n    { by eapply we_in_valid_gs_time. }\n    assert (∃ q, p <= q ∧ e.(ae_time) !! a.(we_orig) = Some q)\n      as (q & Hpq & Herq).\n    { pose proof (vector_clock_lt_le a.(we_time) e.(ae_time) Hae) as Hle.\n      eapply Forall2_lookup_l in Hle as (q & Her & Hpq); eauto. }\n    edestruct (DBM_lsec_causality_lemma i s e p q) as (e' & He'rs & He'rp);\n      eauto using we_in_valid_gs_orig.\n    { by eapply DBM_GV_hst_lst_valid. }\n    assert (ae_orig e' = we_orig a) as He'_orig.\n    { by apply elem_of_filter in He'rs as (Horig&_). }\n    assert (∃ h', gs.(Gst_mem) !! e'.(ae_key) = Some h' ∧ erase e' ∈ h')\n      as (h' & Hh' & He'h').\n    { eapply DBM_GV_hst_in_mem; last eapply in_lsec_in_lhst; eauto.\n      eapply elem_of_list_lookup_2; eauto. }\n    assert (erase e' = a) as He'a.\n    { eapply (DBM_Gst_valid_gmem_ext_internal\n                gs (ae_key e') (we_key a) h' h (erase e') a); try done.\n      - rewrite -He'_orig. by apply erase_orig.\n      - rewrite !erase_time !erase_orig.\n          by rewrite !He'_orig Harp He'rp. }\n    exists e'; split; last done.\n    rewrite elem_of_filter; split; last by eapply in_lsec_in_lhst.\n      by rewrite /= -erase_key He'a.\n  Qed.\n\n  Global Instance db_states : DB_global_state_valid :=\n    {|\n    DBM_GstValid gs := DBM_Gst_valid gs;\n    DBM_GstValid_empty := DBM_Gst_valid_empty;\n    DBM_GstValid_dom gs Hvg := Hvg.(DBM_GV_dom);\n    DBM_GstValid_lhst_size gs Hvg:= Hvg.(DBM_GV_hst_size);\n    DBM_GstValid_gmem_ext := DBM_Gst_valid_gmem_ext;\n    DBM_GstValid_lhst_ext := DBM_Gst_valid_lhst_ext;\n    DBM_GstValid_lhst_strong_ext := DBM_Gst_valid_lhst_strong_ext;\n    DBM_GstValid_ae_provenance := DBM_Gst_valid_ae_provenance;\n    DBM_GstValid_causality := DBM_Gst_valid_causality  |}.\n\nEnd Global_state_valid.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/ccddb/model/model_gst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24613408273759832}}
{"text": "(**\n * Copyright (C) 2022 BedRock Systems, Inc.\n * All rights reserved.\n *\n * SPDX-License-Identifier: LGPL-2.1 WITH BedRock Exception for use over network, see repository root for details.\n *)\n\nRequire Import iris.proofmode.proofmode.\nRequire Import bedrock.lang.algebra.dfrac_agree.\nRequire Import bedrock.lang.bi.spec.frac_splittable.\nRequire Import bedrock.lang.bi.spec.knowledge.\nRequire Import bedrock.lang.cpp.logic.\nRequire Import bedrock.lang.cpp.logic.own_instances.\n\nSet Printing Coercions.\n\n(**\nGhost reference cell:\n\n- [dfrac_agree.own (g : dfrac_agree.gname A) (q : Qp) (x : A) : mpred]\nrepresents fractional ownership of ghost cell [g] currently containing\n[x]\n\n- [dfrac_agree.know (g : dfrac_agree.gname A) (x : A) : mpred]\nrepresents knowledge that ghost cell contains [x]\n\n*)\n\nModule Type DFRAC_AGREE.\n\n  (** CMRA *)\n\n  Parameter G : ∀ (A : Type) (Σ : gFunctors), Set.\n  Existing Class G.\n  Parameter Σ : ∀ (A : Type), gFunctors.\n  #[global] Declare Instance subG {A Σ} : subG (DFRAC_AGREE.Σ A) Σ -> G A Σ.\n\n  (** Ghosts *)\n\n  Parameter gname : ∀ (A : Type), Set.\n\n  #[global] Declare Instance gname_inhabited A : Inhabited (gname A).\n  #[global] Declare Instance gname_eq_dec A : EqDecision (gname A).\n  #[global] Declare Instance gname_countable A : Countable (gname A).\n\n  (** Predicates *)\n\n  Parameter own : ∀ {A} `{Σ : cpp_logic, !DFRAC_AGREE.G A Σ}\n    (g : gname A) (q : Qp) (x : A), mpred.\n  Parameter know : ∀ {A} `{Σ : cpp_logic, !DFRAC_AGREE.G A Σ}\n    (g : gname A) (x : A), mpred.\n\n  Section properties.\n    Context {A} `{Σ : cpp_logic, !DFRAC_AGREE.G A Σ}.\n\n    (** Structure *)\n\n    #[global] Declare Instance own_objective : Objective3 own.\n    #[global] Declare Instance own_frac g : FracSplittable_1 (own g).\n    #[global] Declare Instance own_agree g : AgreeF1 (own g).\n\n    #[global] Declare Instance know_objective : Objective2 know.\n    #[global] Declare Instance know_timeless : Timeless2 know.\n    #[global] Declare Instance know_knowledge : Knowledge2 know.\n    #[global] Declare Instance know_agree g : Agree1 (know g).\n\n    #[global] Declare Instance know_own_agree g q x1 x2 :\n      Observe2 [| x1 = x2 |] (know g x1) (own g q x2).\n\n    (** Allocation *)\n\n    Axiom alloc_strong_dep : ∀ (f : gname A -> A) (P : gname A -> Prop),\n      pred_infinite P ->\n      |-- |==> Exists g, [| P g |] ** own g 1 (f g).\n\n    Axiom alloc_cofinite_dep : ∀ (f : gname A -> A) (G : gset (gname A)),\n      |-- |==> Exists g, [| g ∉ G |] ** own g 1 (f g).\n\n    Axiom alloc_dep : ∀ (f : gname A -> A),\n      |-- |==> Exists g, own g 1 (f g).\n\n    Axiom alloc_strong : ∀ (P : gname A -> Prop) x,\n      pred_infinite P ->\n      |-- |==> Exists g, [| P g |] ** own g 1 x.\n\n    Axiom alloc_cofinite : ∀ (G : gset (gname A)) x,\n      |-- |==> Exists g, [| g ∉ G |] ** own g 1 x.\n\n    Axiom alloc : ∀ x, |-- |==> Exists g, own g 1 x.\n\n    (** Updates *)\n\n    Axiom update : ∀ x g y, own g 1 y |-- |==> own g 1 x.\n\n    Axiom discard : ∀ g q x, own g q x |-- |==> know g x.\n\n  End properties.\n\nEnd DFRAC_AGREE.\n\nModule dfrac_agree : DFRAC_AGREE.\n\n  (** CMRA *)\n\n  #[local] Notation RA A := (dfrac_agreeR (leibnizO A)).\n  Class G (A : Type) (Σ : gFunctors) : Set := G_inG :> inG Σ (RA A).\n  Definition Σ (A : Type) : gFunctors := #[ GFunctor (RA A) ].\n  Lemma subG {A Σ} : subG (dfrac_agree.Σ A) Σ -> G A Σ.\n  Proof. solve_inG. Qed.\n\n  (** Ghosts *)\n\n  Definition gname (A : Type) : Set := iprop.gname.\n  Definition gname_inhabited A : Inhabited (gname A) := _.\n  Definition gname_eq_dec A : EqDecision (gname A) := _.\n  Definition gname_countable A : Countable (gname A) := _.\n\n  (** Predicates *)\n\n  Section defs.\n    Context {A} `{Σ : cpp_logic, !dfrac_agree.G A Σ}.\n\n    Definition know (g : gname A) (x : A) : mpred :=\n      own g (to_dfrac_agree (A:=leibnizO A) DfracDiscarded x).\n    Definition own (g : gname A) (q : Qp) (x : A) : mpred :=\n      own g (to_dfrac_agree (A:=leibnizO A) (DfracOwn q) x).\n\n    Definition own_objective : Objective3 own := _.\n    Lemma own_frac g : FracSplittable_1 (own g).\n    Proof.\n      split.\n      - intros x q1 q2. by rewrite -own_op -dfrac_agree_op.\n      - apply _.\n      - intros. iIntros \"O\".\n        iDestruct (own_valid with \"O\") as %?%to_dfrac_agree_valid.\n        auto.\n    Qed.\n\n    #[local] Ltac solve_agree :=\n      intros; iIntros \"O1 O2\";\n      iDestruct (own_valid_2 with \"O1 O2\") as %[_ ?]%dfrac_agree_op_valid_L;\n      solve [ auto ].\n\n    Lemma own_agree g : AgreeF1 (own g).\n    Proof. solve_agree. Qed.\n\n    Definition know_objective : Objective2 know := _.\n    Definition know_timeless : Timeless2 know := _.\n    Definition know_knowledge : Knowledge2 know.\n    Proof. solve_knowledge. Qed.\n    Lemma know_agree g : Agree1 (know g).\n    Proof. solve_agree. Qed.\n\n    Lemma know_own_agree g q x1 x2 :\n      Observe2 [| x1 = x2 |] (know g x1) (own g q x2).\n    Proof. solve_agree. Qed.\n\n    Lemma alloc_strong_dep : ∀ (f : gname A -> A) (P : gname A -> Prop),\n      pred_infinite P ->\n      |-- |==> Exists g, [| P g |] ** own g 1 (f g).\n    Proof. intros. by apply : own_alloc_strong_dep. Qed.\n\n    Lemma alloc_cofinite_dep : ∀ (f : gname A -> A) (G : gset (gname A)),\n      |-- |==> Exists g, [| g ∉ G |] ** own g 1 (f g).\n    Proof. intros. by apply : own_alloc_cofinite_dep. Qed.\n\n    Lemma alloc_dep : ∀ (f : gname A -> A),\n      |-- |==> Exists g, own g 1 (f g).\n    Proof. intros. by apply : own_alloc_dep. Qed.\n\n    Lemma alloc_strong : ∀ (P : gname A -> Prop) x,\n      pred_infinite P ->\n      |-- |==> Exists g, [| P g |] ** own g 1 x.\n    Proof. intros. by apply : own_alloc_strong. Qed.\n\n    Lemma alloc_cofinite : ∀ (G : gset (gname A)) x,\n      |-- |==> Exists g, [| g ∉ G |] ** own g 1 x.\n    Proof. intros. by apply : own_alloc_cofinite. Qed.\n\n    Lemma alloc x : |-- |==> Exists g, own g 1 x.\n    Proof. by apply own_alloc. Qed.\n\n    Lemma update x g y : own g 1 y |-- |==> own g 1 x.\n    Proof. by apply own_update, cmra_update_exclusive. Qed.\n\n    Lemma discard g q x : own g q x |-- |==> know g x.\n    Proof. apply own_update, dfrac_agree_persist. Qed.\n  End defs.\n\nEnd dfrac_agree.\n", "meta": {"author": "bedrocksystems", "repo": "BRiCk", "sha": "23d7e64cc53706de608dbff0be75d1c4b8c3a7ec", "save_path": "github-repos/coq/bedrocksystems-BRiCk", "path": "github-repos/coq/bedrocksystems-BRiCk/BRiCk-23d7e64cc53706de608dbff0be75d1c4b8c3a7ec/theories/lang/cpp/logic/lib/dfrac_agree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24613407631440598}}
{"text": "(* ------------------------------------------------------- *)\n(** #<hr> <center> <h1>#\n        The double time redundancy (DTR) transformation   \n#</h1>#    \n--   Properties of mem block sub-part called rhsPar with stepg\n\n          Dmitry Burlyaev - Pascal Fradet - 2015\n#</center> <hr>#                                           *)\n(* ------------------------------------------------------- *)\n(*Add LoadPath \"..\\..\\Common\\\".\n        Require Import CirReflect . \nAdd LoadPath \"..\\..\\TMRProof\\\".\nAdd LoadPath \"..\\\". *)\n\nAdd LoadPath \"..\\..\\Common\\\".\nAdd LoadPath \"..\\..\\TMRProof\\\".\nAdd LoadPath \"..\\Transf\\\".\n\nRequire Import dtrTransform.\n\nSet Implicit Arguments.\n\n(* ###################################################################### *)\n(** Properties of sub-circuit of Memory Block called rhsPar with Glitches *)\n(* ###################################################################### *)\n\n(* Type of rhsPar (IO interface):\n  ((si1 # ({save#rollBack} # failF)) # (r_O # save)) -> \n  ( [((save # rollBack) # failF) # s1 ]# rNew)\n*)\n\n(* State before/after for both cycles with a glitch (stepg) inside the circuit *)\n(*by reflexion*)\nLemma stepg_rhs_R : forall p t c, ((fun p => pure_bset p) p)\n                  -> stepg ((fun p => \n                                     let si_I :=   (fstS(fstS(fstS(fstS(fstS p))))) in \n                                     let sav_I :=   (sndS(fstS(fstS(fstS(fstS p))))) in\n                                     let sav2_I :=  (sndS(fstS(fstS(fstS p)))) in \n                                     let fai_I :=  (sndS(fstS(fstS p))) in \n                                     let rol_I :=   (sndS(fstS p)) in \n                                     let rO_I :=   (sndS p) in\n\n                                     rhsPar) p)\n                           ((fun p =>\n                                     let si_I :=   (fstS(fstS(fstS(fstS(fstS p))))) in \n                                     let sav_I :=   (sndS(fstS(fstS(fstS(fstS p))))) in\n                                     let sav2_I :=  (sndS(fstS(fstS(fstS p)))) in \n                                     let fai_I :=  (sndS(fstS(fstS p))) in \n                                     let rol_I :=   (sndS(fstS p)) in  \n                                     let rO_I :=   (sndS p) in\n\n                                   {si_I,{{{ sav_I, rol_I},fai_I},{rO_I,sav2_I}}}) p) t c\n\n                  -> (fun e => let p := fst(fst e) in \n                               let t := snd(fst e) in\n                               let c := snd e in\n\n                               let si_I :=   (fstS(fstS(fstS(fstS(fstS p))))) in \n                               let sav_I :=   (sndS(fstS(fstS(fstS(fstS p))))) in\n                               let sav2_I :=  (sndS(fstS(fstS(fstS p)))) in \n                               let fai_I :=  (sndS(fstS(fstS p))) in \n                               let rol_I :=   (sndS(fstS p)) in \n                               let rO_I :=   (sndS p) in \n\n                               let rI_I:=  if (beq_buset_t sav2_I (~1)) then si_I \n                                           else rO_I in\n\n((c=rhsPar)/\\ ( t= {{ {{sav_I,rol_I}, fai_I}, si_I}, rI_I} \n\\/ t= {{ {{sav_I,rol_I}, fai_I}, si_I},~?}))) (p,t,c).\nProof. introv. Reflo_step_g; Simpl. Qed.\n\n(** The aforementioned property in a more useable form  *)\nLemma stepg_rhs: forall (si sav sav2 fai rol r :bool) si_I sav_I  sav2_I fai_I rol_I rO_I t c,\nsi_I =  bool2bset si -> sav_I  = bool2bset sav -> sav2_I =  bool2bset sav2 -> \nfai_I  = bool2bset fai -> rol_I =  bool2bset rol ->  rO_I  = bool2bset r ->\nstepg rhsPar  {si_I,{{{ sav_I, rol_I},fai_I},{rO_I,sav2_I}}} t c\n->           \nlet rI_I:=  if (beq_buset_t sav2_I (~1)) then si_I else rO_I in                    \n((c=rhsPar)/\\ ( t= {{ {{sav_I,rol_I}, fai_I}, si_I}, rI_I} \n\\/ t= {{ {{sav_I,rol_I}, fai_I}, si_I},~?})).\nProof.\nintrov G1 G2 G3 G4 G5 G6 H.\nset (p := {bool2bset si, bool2bset sav, bool2bset sav2, bool2bset fai, bool2bset rol, bool2bset r}).\nassert (X1:   si_I =   (fstS(fstS(fstS(fstS(fstS p)))))) by\n(replace p with  {bool2bset si, bool2bset sav, bool2bset sav2, bool2bset fai, bool2bset rol, bool2bset r}; destruct si ; easy).\nassert (X2:    sav_I =   (sndS(fstS(fstS(fstS(fstS p)))))) by\n(replace p with  {bool2bset si, bool2bset sav, bool2bset sav2, bool2bset fai, bool2bset rol, bool2bset r}; destruct sav; easy).\nassert (X3:    sav2_I =  (sndS(fstS(fstS(fstS p))))) by\n(replace p with  {bool2bset si, bool2bset sav, bool2bset sav2, bool2bset fai, bool2bset rol, bool2bset r}; destruct sav2 ; easy).\nassert (X4:    fai_I =  (sndS(fstS(fstS p)))) by\n(replace p with  {bool2bset si, bool2bset sav, bool2bset sav2, bool2bset fai, bool2bset rol, bool2bset r}; destruct fai ; easy).\nassert (X5:    rol_I =   (sndS(fstS p))) by\n(replace p with  {bool2bset si, bool2bset sav, bool2bset sav2, bool2bset fai, bool2bset rol, bool2bset r}; destruct rol ; easy).\nassert (X6:   rO_I =   (sndS p)) by\n(replace p with  {bool2bset si, bool2bset sav, bool2bset sav2, bool2bset fai, bool2bset rol, bool2bset r}; destruct r ; easy).\nintros. rewrite X1 in H. rewrite  X2 in H. rewrite  X3 in H.  rewrite X5 in H. rewrite  X6 in H.\nrewrite X4 in H. Apply stepg_rhs_R in H. simpl fst in H. simpl snd in H.\nrewrite <- X1 in H. rewrite <- X2 in H. rewrite <- X3 in H.\nrewrite <- X5 in H. rewrite <- X6 in H.  rewrite <- X4 in H. apply H. \nQed.", "meta": {"author": "dburl", "repo": "Coq_LDDL", "sha": "691023b88314c1ad531a1177954a1c6596fe4483", "save_path": "github-repos/coq/dburl-Coq_LDDL", "path": "github-repos/coq/dburl-Coq_LDDL/Coq_LDDL-691023b88314c1ad531a1177954a1c6596fe4483/DTRProof/memoryBlocks/rightStepg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24613407631440595}}
{"text": "(* ***************************************************************** *)\n(* Progress.v                                                        *)\n(*                                                                   *)\n(* 2019 Xuan Huang                                                   *)\n(* ***************************************************************** *)\n\n(* ################################################################# *)\n(** * Progress *)\n\nFrom Wasm Require Export Validation.\nFrom Wasm Require Export Execution.\nFrom Wasm Require Export ExtendedTyping.\nFrom Wasm Require Export ProofAux.\n\n(* Coercions are too confusing during proofs. *)\nSet Printing Coercions.\n\n(* Sometimes. *)\n(* Unset Printing Notations. *)\n\n(**************************************************************)\n(** ** Implicit Types - Copied from ExtendedTyping *)\n\n(* Primary *)\nImplicit Type b : bool.\nImplicit Type n m : nat.\n\n(* Value *)\nImplicit Type val : val.\nImplicit Type vals : list val.\n\n(* Structure *)\nImplicit Type M : module.\nImplicit Type l : labelidx.\n\nImplicit Type instr : instr.\nImplicit Type instrs : list instr.\nImplicit Type f func : func.\nImplicit Type fs funcs : list func.\nImplicit Type tab table: table.\nImplicit Type tabs tables: list table.\n\n(* Type *)\nImplicit Type t : valtype.\nImplicit Type ts : list valtype.\nImplicit Type rt : resulttype.\nImplicit Type bt : blocktype.\nImplicit Type ft functype: functype.\nImplicit Type fts functypes: list functype.\nImplicit Type tt tabletype: tabletype.\nImplicit Type tts tabletypes: list tabletype.\n\n(* Validation *)\nImplicit Type C : context.\n\n(* Execution *)\nImplicit Type cfg : config.\nImplicit Type res : result.\nImplicit Type S : store.\nImplicit Type F : frame.\nImplicit Type T : thread.\nImplicit Type E : eval_context.\n\nImplicit Type ainstr : admin_instr.\nImplicit Type ainstrs : list admin_instr.\n\nImplicit Type fa: funcaddr.\nImplicit Type fas : list funcaddr.\nImplicit Type ta: tableaddr.\nImplicit Type tas : list tableaddr.\n\nImplicit Type fi funcinst: funcinst.\nImplicit Type fis funcinsts: list funcinst.\nImplicit Type ti tableinst: tableinst.\nImplicit Type tis tableinsts: list tableinst.\n\nImplicit Type Mi mi moduleinst: moduleinst.\n\n\n(* ================================================================= *)\n(** ** Termination State *)\n(** Terminal thread/config was not explicit defined. Should be straightforward.\n\n    Q1:\n      How to construct a result during step relation?\n    A:\n      we need to extract [list val] or [Trap] from [list admin_instr]\n      to be able to construct [result] then construct [valid_result]. \n\n    Q2:\n      [Inductive result] looks redundant,\n      like [val], it's coincident with [instr]/[admin_instr].\n      It's not used in other places besides of [valid_result]\n    A:\n      one important fact about [Inductive result] is that,\n      like [val], it contains more information than [instr].\\\n      It's equiv to a proof-carrying form of [instr].\n *)\n\n(* Transform between [result] and [admin_instr] *)\n\n\nDefinition result_to_ainstr (res: result) : list admin_instr :=\n  match res with\n  | R_vals vals => ⇈vals  (* lost information *)\n  | R_trap => [Trap]\n  end.\n\nNotation \"! res\" := (result_to_ainstr res) (at level 9).\n\nExample ex : list admin_instr := !R_trap.\n  \n\n(* extended from [valid_result] *)\nReserved Notation \" '⊢R' T '∈' rt\" (at level 70).\nInductive result_thread : thread -> resulttype -> Prop :=\n\n  | RT : forall res rt F,\n      ⊢r res ∈ rt ->\n      ⊢R (F, !res) ∈ rt\n\nwhere \" '⊢R' T '∈' rt\" := (result_thread T rt).\nHint Constructors result_thread.\n\nLemma R_vals_ϵ :\n    !(R_vals []) = @nil admin_instr.\nProof.\n  auto.\nQed.\n\nLemma R_vals_vals : forall vals,\n    !(R_vals vals) = ⇈vals.\nProof.\n  auto.\nQed.\n\nLemma F_vals_R: forall F vals rt,\n    Forall2 (fun (val : val) (t : valtype) => ⊢v val ∈ t) vals rt ->\n    ⊢R (F, ⇈vals) ∈ rt.\nProof with eauto.\n  introv HForall2.\n  rewrite <- R_vals_vals...\nQed.\n\nLemma F_ϵ_R: forall F,\n    ⊢R (F, []) ∈ [].\nProof with eauto.\n  intros.\n  rewrite <- R_vals_ϵ...\nQed.\n\nLemma F_Trap_R: forall F rt,\n    ⊢R (F, [Trap]) ∈ rt.\nProof with eauto.\n  intros.\n  asserts_rewrite ([Trap] = !R_trap)... \nQed.\n\n\n(* ================================================================= *)\n(** ** Lemma Forall2 *)\n\n(* A specialized version of [Forall2_app_inv_r] *)\nLemma Forall2_snoc_app_r: forall {X Y : Type} {R: X -> Y -> Prop} (xs: list X) (ys': list Y) (y: Y),\n     Forall2 R xs (ys' ++ [y]) ->\n     exists xs' x, Forall2 R xs' ys' /\\ R x y /\\ xs = xs' ++ [x].\nProof.\n  introv HForall2.\n  apply Forall2_app_inv_r in HForall2.\n  destruct HForall2 as (xs' & unit & Hxs' & Hunit & Heq).\n  inverts Hunit as HRxy Hnil.\n  inverts Hnil.\n  exists xs' x.\n  splits; auto.\nQed.\n\nLemma Forall2_snoc_app_r2: forall {X Y : Type} {R: X -> Y -> Prop} (xs: list X) (ys': list Y) (y1 y2: Y),\n     Forall2 R xs (ys' ++ [y1; y2]) ->\n     exists xs' x1 x2, Forall2 R xs' ys' /\\ R x1 y1 /\\ R x2 y2 /\\ xs = xs' ++ [x1; x2].\nProof with eauto.\n  introv HForall2.\n  apply Forall2_app_inv_r in HForall2.\n  destruct HForall2 as (l & r & Hl & Hr & Heq).\n  inverts Hr as Hr1 Hr'.\n  inverts Hr' as Hr2 Hr''.\n  inverts Hr''.\n  exists l x x0. splits...\nQed.\n\nLemma Forall2_snoc_app_r3: forall {X Y : Type} {R: X -> Y -> Prop} (xs: list X) (ys': list Y) (y1 y2 y3: Y),\n     Forall2 R xs (ys' ++ [y1; y2; y3]) ->\n     exists xs' x1 x2 x3, Forall2 R xs' ys' /\\ R x1 y1 /\\ R x2 y2 /\\ R x3 y3 /\\ xs = xs' ++ [x1; x2; x3].\nProof with eauto.\n  introv HForall2.\n  apply Forall2_app_inv_r in HForall2.\n  destruct HForall2 as (l & r & Hl & Hr & Heq).\n  inverts Hr as Hr1 Hr'.\n  inverts Hr' as Hr2 Hr''.\n  inverts Hr'' as Hr3 Hr'''.\n  inverts Hr'''.\n  exists l x x0 x1. splits...\nQed.\n\n\nLtac invert_Forall2_app_r1 HForall2 l r Hl Hr:=\n  apply Forall2_snoc_app_r in HForall2;\n  destruct HForall2 as (l & r & Hl & Hr & _Heq);\n  rewrite _Heq.\n\nLtac invert_Forall2_app_r2 HForall2 xs' x1 x2 Hxs' Hx1 Hx2:=\n  apply Forall2_snoc_app_r2 in HForall2;\n  destruct HForall2 as (xs' & x1 & x2 & Hxs' & Hx1 & Hx2 & _Heq);\n  rewrite _Heq.\n\nLtac invert_Forall2_app_r3 HForall2 xs' x1 x2 x3 Hxs' Hx1 Hx2 Hx3:=\n  apply Forall2_snoc_app_r3 in HForall2;\n  destruct HForall2 as (xs' & x1 & x2 & x3 & Hxs' & Hx1 & Hx2 & Hx3 & _Heq);\n  rewrite _Heq.\n\n\n\n(* ================================================================= *)\n(** ** Build/Extract/Decompose Execution Context *)\n\n(* Decompose on left, which has to be value *)\nLemma decompose_vals_as_E_seq: forall vals ainstrs, \n    ⇈vals ++ ainstrs = plug__E (E_seq vals E_hole []) ainstrs.\nProof.\n  intros. \n  simpl in *. \n  rewrite app_nil_r.\n  auto.\nQed.\n         \nLtac decompose_vals_as_E_seq_E vals :=\n  rewrite decompose_vals_as_E_seq;\n  remember (E_seq vals E_hole []) as E.\n\n(* Decompose on right, which has to be rest of the ainstrs *)\nLemma decompose_rest_as_E_seq: forall ainstrs ainstrs', \n    ainstrs ++ ainstrs' = plug__E (E_seq [] E_hole ainstrs') ainstrs.\nProof with auto.\n  intros. \n  simpl in *...\nQed.\n\nLtac decompose_rest_as_E_seq_E rest :=\n  rewrite decompose_rest_as_E_seq;\n  remember (E_seq [] E_hole rest) as E.\n\n\n\n(* ================================================================= *)\n(** ** Progress - VAIS_snoc -> SC_simple*)\n\nLtac step_VR_trap S F list car :=\n  right;\n  asserts_rewrite (\n    list = [Trap] ++ car\n  ); try reflexivity;\n  rewrite decompose_rest_as_E_seq;\n  exists S F [Trap]; apply SC_trap__E.\n\nLtac step_snoc_app_cdr S F HSC rest :=\n  right;\n  decompose_rest_as_E_seq_E rest;\n  destruct HSC as (S' & F' & ainstrs' & HSC);\n  exists S' F'; eexists;\n  eapply SC_E;\n  apply HSC.\n\n\n(* ================================================================= *)\n(** ** Main Theorem *)\n\nTheorem progress : forall S T rt,\n    ⊢c (S, T) ∈ rt ->\n    ⊢R T ∈ rt \\/ exists S' F' ainstrs', $(S, T) ↪ (S', F', ainstrs').   (* TODO: [exists T'] *)\nProof with eauto.\n  introv HVC.\n\n  (* valid_config *)\n  inverts HVC as HSok HVT.\n    (* valid_store *)\n    (* valid_thread *)\n    inverts HVT as HVA HVAIS.\n      (* valid_frame *)\n      inverts HVA as HVMI HVV.\n        (* valid_moduleinst *)\n        (* valid_value *)\n      (* valid_admin_instrs *)\n\n  dependent induction HVAIS.\n\n  - (* VAIS_empty *)\n    left.\n    apply F_ϵ_R.\n\n  - remember {| A_locals := vals; A_module := mi |} as F.\n    remember (C0 with_locals = ts with_return = None) as C.\n    rename H into HVAI__N.\n    (* VAIS_snoc:\n       we could not extract this case as a lemma since we need IH.\n\n      [IHHVAIS : ... ->\n      [          ⊢R (F, ainstrs) ∈ rt \n      [          \\/ exists S' T', (S0, F, ainstrs) ↪ $(S', T')\n\n      [HVAIS : (S,C) ⊢a* ainstrs ∈ ϵ --> (ts0 ++ ts2)]\n      [HVAI__N : (S,C) ⊢a  ainstr__N ∈ ts2 --> ts3]             (* H *)\n     --------------------------------------------------------------\n       ⊢R (F, ainstrs ++ [ainstr__N])\n      [  \\/ exists S' T', (S, F, ainstrs ++ [ainstr__N]) ↪ $(S', T') ]\n    *)\n    inverts HVAI__N as.\n  \n    + (* VAI_instr *)\n      intros HVI__N.\n      inverts keep HVI__N.\n\n      ++ (* VI_const *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            left.\n            asserts_rewrite ([Plain (Const val)] = ⇈[val]). reflexivity.\n            rewrite <- upup_app.\n            eapply F_vals_R.\n            apply Forall2_app.\n            +++++ rewrite app_nil_r in HForall2...\n            +++++ constructor; try constructor...\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain (Const val)] [Plain (Const val)].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain (Const val)].\n            \n\n      ++ (* VI_unop *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            invert_Forall2_app_r1 HForall2 vals' val0 Hval' Hval0.\n            rewrite upup_app; rewrite <- app_assoc; simpl.\n            decompose_vals_as_E_seq_E vals'.\n            exists S F.\n            destruct (eval_unop op val0) as [val__opt | ] eqn:Heval.\n            +++++ (* Ok *)\n              destruct val__opt;\n              eexists;\n                eapply SC_E;\n                eapply SC_simple.\n              ++++++ (* Ok Some *) eapply SS_unop__some...\n              ++++++ (* Ok None *) eapply SS_unop__none...\n            +++++ (* Err *)\n              inverts Hval0 as Heqtype_of.\n              destruct (eval_unop_no_runtime_err op val0 Heqtype_of Heval).\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain (Unop op)] [Plain (Unop op)].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain (Unop op)].\n\n\n      ++ (* VI_binop *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            invert_Forall2_app_r2 HForall2 vals' val1 val2 Hval' Hval1 Hval2.\n            rewrite upup_app; rewrite <- app_assoc; simpl.\n            decompose_vals_as_E_seq_E vals'.\n            exists S F. \n            destruct (eval_binop op val1 val2) as [val__opt | ] eqn:Heval.\n            +++++ (* Ok *)\n              destruct val__opt;\n              eexists;\n                eapply SC_E;\n                eapply SC_simple.\n              ++++++ (* Ok Some *) eapply SS_binop__some...\n              ++++++ (* Ok None *) eapply SS_binop__none...\n            +++++ (* Err *)\n              inverts Hval1 as Heqtype_of1.\n              inverts Hval2 as Heqtype_of2.\n              destruct (eval_binop_no_runtime_err op val1 val2 Heqtype_of1 Heqtype_of2 Heval).\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain (Binop op)] [Plain (Binop op)].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain (Binop op)].\n\n\n      ++ (* VI_testop *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            invert_Forall2_app_r1 HForall2 vals' val0 Hvals' Hval0.\n            rewrite upup_app; rewrite <- app_assoc; simpl.\n            decompose_vals_as_E_seq_E vals'.\n            exists S F. \n            destruct (eval_testop op val0) as [ bval | ] eqn:Heval.\n            +++++ (* Ok *)\n              eexists;\n                eapply SC_E;\n                eapply SC_simple;\n                eapply SS_testop...\n            +++++ (* Err *)\n              inverts Hval0 as Heqtype_of.\n              destruct (eval_testop_no_runtime_err op val0 Heqtype_of Heval).\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain (Testop op)] [Plain (Testop op)].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain (Testop op)].\n\n\n      ++ (* VI_relop *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            invert_Forall2_app_r2 HForall2 vals' val1 val2 Hvals' Hval1 Hval2.\n            rewrite upup_app; rewrite <- app_assoc; simpl.\n            decompose_vals_as_E_seq_E vals'.\n            exists S F. \n            destruct (eval_relop op val1 val2) as [ bval | ] eqn:Heval.\n            +++++ (* Ok *)\n              eexists;\n                eapply SC_E;\n                eapply SC_simple;\n                eapply SS_relop...\n            +++++ (* Err *)\n              inverts Hval1 as Heqtype_of1.\n              inverts Hval2 as Heqtype_of2.\n              destruct (eval_relop_no_runtime_err op val1 val2 Heqtype_of1 Heqtype_of2 Heval).\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain (Relop op)] [Plain (Relop op)].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain (Relop op)].\n\n\n      ++ (* VI_drop *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            invert_Forall2_app_r1 HForall2 vals' val0 Hvals' Hval0.\n            rewrite upup_app; rewrite <- app_assoc; simpl.\n            decompose_vals_as_E_seq_E vals'.\n            exists S F. eexists;\n                eapply SC_E;\n                eapply SC_simple;\n                eapply SS_drop...\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain Drop] [Plain Drop].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain Drop].\n\n\n      ++ (* VI_select *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            invert_Forall2_app_r3 HForall2 vals' val1 val2 valc Hvals' Hval1 Hval2 Hvalc.\n            rewrite upup_app; rewrite <- app_assoc; simpl.\n            inverts Hvalc as Htypeof. \n            destruct valc as [c | | | ] ; inverts Htypeof. (* inverts our the underlying [I32.t] *)\n            decompose_vals_as_E_seq_E vals'.\n            exists S F.  \n            destruct (I32.eqz c) eqn:Heqz;\n              eexists;\n              eapply SC_E;\n              eapply SC_simple.\n            +++++ eapply SS_select2...\n            +++++ eapply SS_select1...\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain Select] [Plain Select].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain Select].\n\n\n      ++ (* VI_nop *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            decompose_vals_as_E_seq_E vals0.\n            exists S F. eexists;\n              eapply SC_E;\n              eapply SC_simple;\n              eapply SS_nop.\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain Nop] [Plain Nop].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain Nop].\n\n\n      ++ (* VI_unreachable *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            decompose_vals_as_E_seq_E vals0.\n            exists S F. eexists;\n              eapply SC_E;\n              eapply SC_simple;\n              eapply SS_unreachable.\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain Unreachable] [Plain Unreachable].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain Unreachable].\n\n\n      ++ (* VI_block *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            decompose_vals_as_E_seq_E vals0.\n            exists S F. eexists;\n              eapply SC_E;\n              (* eapply SC_block *)\n              admit.\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain (Block bt instrs)] [Plain (Block bt instrs)].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain (Block bt instrs)].\n\n\n      ++ (* VI_loop *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            decompose_vals_as_E_seq_E vals0.\n            exists S F. eexists;\n              eapply SC_E;\n              (* eapply SC_loop *)\n              admit.\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain (Loop bt instrs)] [Plain (Loop bt instrs)].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain (Loop bt instrs)].\n\n\n      ++ (* VI_if *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            decompose_vals_as_E_seq_E vals0.\n            exists S F. eexists;\n              eapply SC_E;\n              (* eapply SC_if two cases *)\n              admit.\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain (If bt instrs1 instrs2)] [Plain (If bt instrs1 instrs2)].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain (If bt instrs1 instrs2)].\n\n\n      ++ (* VI_br *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            (* We are not inside a label...how to step?\n               SS_br require a label to br.\n               This would be vacuously true. \n             *)\n            admit.\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain (Br l0)] [Plain (Br l0)].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain (Br l0)].\n\n\n      ++ (* VI_br_if *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            rewrite app_assoc in HForall2.\n            invert_Forall2_app_r1 HForall2 vals' val0 Hvals' Hval0.\n            rewrite upup_app; rewrite <- app_assoc; simpl.\n            decompose_vals_as_E_seq_E vals'.\n            exists S F. \n            inverts Hval0 as Htypeof.\n            destruct val0 as [ c | | | ]; inverts Htypeof.\n            destruct (I32.eqz c) eqn:Heqz;\n              eexists;\n              eapply SC_E;\n              eapply SC_simple.\n            +++++ (* I32.eqz c = true  *) eapply SS_br_if2...\n            +++++ (* I32.eqz c = false *) eapply SS_br_if1...\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain (Br_if l0)] [Plain (Br_if l0)].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain (Br_if l0)].\n\n      ++ (* VI_br_table *)\n        edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n        +++ (* ⊢R *) \n          inverts HRT as HVR.\n          inverts HVR as HForall2; simpl.\n          ++++ (* VR_vals *)\n            right.\n            rewrite app_assoc in HForall2. rewrite app_assoc in HForall2.\n            invert_Forall2_app_r1 HForall2 vals' val0 Hvals' Hval0.\n            rewrite upup_app; rewrite <- app_assoc; simpl.\n            decompose_vals_as_E_seq_E vals'.\n            exists S F. \n            inverts Hval0 as Htypeof.\n            destruct val0 as [ i | | | ]; inverts Htypeof.\n            destruct (leb (length ls) (I32.to_nat i)) eqn:Hleb;\n              eexists;\n              eapply SC_E;\n              eapply SC_simple.\n            +++++ (* out of bound [SS_br_table__N] *)\n              (* Need to make two numbers consistent *)\n              admit.\n            +++++ (* in bound [SS_br_table__i] *) \n              admit.\n          ++++ (* VR_trap *)\n            step_VR_trap S F [Trap; Plain (Br_table ls l__N)] [Plain (Br_table ls l__N)].\n        +++ (* ↪ *)\n          step_snoc_app_cdr S' F' HSC [Plain (Br_table ls l__N)].\n\n    + (* VAI_trap *)\n      edestruct IHHVAIS as [HRT | HSC]; try solve [subst; eauto].\n      ++ (* ⊢R *) \n        inverts HRT as HVR.\n        inverts HVR as HForall2; simpl. \n        +++ (* VR_vals *)\n          right.\n          decompose_vals_as_E_seq_E vals0.\n          exists S F [Trap]. apply SC_trap__E.\n        +++ (* VR_trap *)\n            (* need to execute the first trap... though I doubt this case could happen? *)\n          step_VR_trap S F [Trap; Trap] [Trap].\n      ++ (* ↪ *)\n        step_snoc_app_cdr S' F' HSC [Trap].\n\n    + (* VAIS_label *)\n      introv HVAIS__cont HVAIS__rest.\n      inverts HVAIS__rest.\n      ++ (* [] *) skip.\n         (* TODO: need to generailize the context, i.e., the entire theorem *)\n\nAdmitted.\n\n(** Archive - How I found it need to be a induction. *)\n\n(* For SC_Simple, we don't care S and F *)\nLemma progress_SC_simple : forall S C F ainstrs ainstr__N ts0 ts2 ts3,\n      (S,C) ⊢a* ainstrs ∈ [] --> (ts0 ++ ts2) ->  (* [HVAIS] *)  \n      (S,C) ⊢a  ainstr__N ∈ ts2 --> ts3 ->          (* [HVAI__N] *)\n(* -------------------------------------------------------------- *)\n      ⊢R (F, ainstrs ++ [ainstr__N]) ∈ ts0 ++ ts3\n      \\/ exists S' T', (S, F, ainstrs ++ [ainstr__N]) ↪ $(S', T').\nProof with eauto.\n  introv HVAIS HVAI__N.\n  inverts HVAI__N as.\n  \n  - (* VAI_instr *)\n    intros HVI__N.\n    inverts keep HVI__N.\n\n    + (* VI_const *)\n      left.\n      (* we have shown [ainstrs ++ ⇈[val]] is a normal form\n         but how do we show it's a result of vals?\n         i.e. all ainstrs here should be some [vals] as well? *)\n      admit.\n\n    + (* VI_unop *)\n      right.\n      (*\n\n  HVAIS : (S, C) ⊢a* ainstrs ∈ [] --> (ts0 ++ [type_of op])\n--------------------------------------------------------------\n [exists S' T', (S, F, ainstrs ++ [Plain (Unop op)]) ↪ $ (S', T')]\n\nThe problem here is that,\nthe substructure [ainstrs] could take a step...\nwhen it's not, it would be a result\n- either it's trap, then we trap\n- or it's a value, then we can possibly take a step\n\nmeaning we need a induction hypothesis on HVAIS here.\n       *)\nAbort.\n\n\n\n  \n", "meta": {"author": "Huxpro", "repo": "WasmCert", "sha": "7b7385ccbaa62b0aaf6b7757e6847c7d5c32933c", "save_path": "github-repos/coq/Huxpro-WasmCert", "path": "github-repos/coq/Huxpro-WasmCert/WasmCert-7b7385ccbaa62b0aaf6b7757e6847c7d5c32933c/coq/Progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2460592149504696}}
{"text": "Require Import Coqlib.\nRequire Import Asm.\nRequire Import PeekTactics.\nRequire Import PeepsLib.\nRequire Import PregTactics.\nRequire Import StepIn.\nRequire Import AsmBits.\nRequire Import Values.\nRequire Import ValEq.\nRequire Import Integers.\nRequire Import PeepsTactics.\nRequire Import StepEquiv.\nRequire Import Globalenvs.\nRequire Import Memory.\nRequire Import MemEq.\nRequire Import MemoryAxioms.\nRequire Import UseBasic.\n\n\n(*TODO: Replace with newer version*)\nLtac prep_r :=\n  T0 _destruct state_bits;      \n    NP0 app_new step_fwd_exec step_fwd; eauto;    \n  repeat break_and;      \n  P0 _clear step_through;\n  P0 _clear step_fwd;\n  P0 _clear current_fn;\n  NP app_new mem_eq_match_metadata_r MemEq.mem_eq.\n\nLtac step_l :=\n    NP1 app_new step_through_current_instr step_through;\n    NP1 app_new step_through_current_fn step_through; [ | simpl; eauto ];\n    (step_l_str || step_l_jmp);\n    break_and; compute_skipz; P1 _simpl step_through; try break_and;\n    NP1 app_new step_fwd_transf_block step_fwd.\n\nDefinition aiken_3_example :=     \n            Ptest_rr ECX ECX ::\n            Pjcc Cond_e xH ::\n            Pmov_rr ECX EDX ::\n            Plabel xH ::\n            Pnop ::\n            nil.\n\nSection AIKEN_3.\n\n  Variable concrete : code.  \n  Variable r2 : ireg.\n  Variable r3 : ireg.\n  Variable r4 : ireg.\n  Variable l : label.  \n  Hypothesis r2_r3_neq : r2 <> r3.\n  Hypothesis r2_r4_neq : r2 <> r4.\n  Hypothesis r3_r4_neq : r3 <> r4.  \n\n  Definition aiken_3_defs : rewrite_defs :=\n    {|\n      fnd :=                \n        (* test %ecx, %ecx *)\n        (* je .l *)\n        (* mov %edx, %ebx *)\n        (* .l:         *)\n                Ptest_rr r3 r3 ::\n                Pjcc Cond_e l ::\n                Pmov_rr r2 r4 ::\n                Plabel l ::\n                Pnop ::\n                nil\n      ; rpl :=\n          (* test %ecx, %ecx *)\n          (* cmovne %edx, %ebx           *)\n                  Ptest_rr r3 r3 ::\n                  Pcmov Cond_ne r2 r4 ::\n                  Pnop ::\n                  Pnop ::\n                  Pnop ::\n                  nil\n      ; lv_in := PC :: IR r2 :: IR r3 :: IR r4 :: nil\n      ; lv_out := PC :: IR r4 :: IR r2 :: nil\n      ; clobbered := flags\n    |}.\n  \n  Lemma aiken_3_selr:\n    StepEquiv.step_through_equiv_live (fnd aiken_3_defs) (rpl aiken_3_defs) (lv_in aiken_3_defs) (lv_out aiken_3_defs).\n  Proof.    \n    prep_l.\n    step_l.\n    step_l.\n    {\n      step_l.\n      prep_r.\n      step_r.\n      prep_exec_instr.\n      simpl.\n      repeat break_match; eauto.\n      repeat break_exists.\n      step_r.\n      step_r.\n      step_r.\n      step_r.\n      assert (x6 = md').\n      {\n        specialize (H23 x3).\n        simpl_and_clear.\n      }\n      subst x6.\n      finish_r.      \n      \n      P0 _clear step_through;\n        P0 _clear at_code;\n        P0 _clear at_code_end;\n        P0 _clear not_after_label_in_code;\n        P0 _clear st_rs;\n        inv_state;\n        P0 bump val_eq;\n        P0 bump exec_instr_bits.\n      specialize (H24 x5).      \n      repeat clear_dup.      \n      unfold exec_instr_bits in *.\n      remember r1 as cond_l_rs.\n      remember (eval_testcond Cond_e cond_l_rs) as cond_l.\n      remember ((nextinstr\n               (compare_ints (Val.and (rsr r3) (rsr r3)) Vzero rsr mr))) as cond_r_rs.\n      remember (eval_testcond Cond_ne cond_r_rs) as cond_r.\n      Ltac gentle_inv_next :=\n        match goal with\n          | [H: Nxt _ _ _ = Nxt _ _ _ |- _] => inversion H; clear H\n        end.\n      repeat gentle_inv_next.\n      subst m0. subst m1.\n      exploit (eval_testcond_match cond_l_rs cond_r_rs Cond_e);\n        try solve [\n              subst;\n              subst r1;\n              try eapply val_eq_nextinstr;\n              try eapply val_eq_compare_ints;\n              try eapply val_eq_and;\n              simpl;\n              try assumption;      \n              try reflexivity;\n              eauto 8 ].\n      intro.      \n      unfold jumps_to_label in *.\n      rewrite H28 in H31.\n      break_match_lem H31.\n      break_if.\n      2: inv_false.\n      2: inv_false.\n      clear_taut.\n      subst cond_l.\n      break_or'.\n      congruence.\n      symmetry in H11.\n      eapply eval_testcond_e_neg in H11.\n      Focus 2.      \n      subst.\n      clear -H11.\n      unfold eval_testcond in *.\n      simpl_match_hyp.\n      inv_some.\n      left.\n      apply PtrEquiv.int_eq_true in H0.\n      subst. unfold Vtrue.\n      reflexivity.\n      \n      subst cond_r.\n      collapse_match_hyp.\n      P1 _simpl negb.\n      gentle_inv_next.\n      subst x4.\n      unfold goto_label_bits in *.\n      simpl_match_hyp.\n      gentle_inv_next.\n      subst m.\n      P0 _clear current_instr.\n      subst b0.\n      subst a1.\n      subst a0.\n\n      split.\n      2: eq_mem_tac.\n      intros.\n      repeat break_or_reg.\n      + subst.\n        preg_simpl.\n        repeat find_rewrite_goal.\n        simpl.        \n        preg_simpl_hyp H41.\n        preg_simpl_hyp H42.\n        P0 _clear current_block.\n        P0 _clear no_ptr_regs.\n        simpl in *.\n        rewrite H40 in H41.        \n        inv_vint.\n        rewrite H2 in H41.\n        simpl in H41.\n        inv_vint.\n        f_equal.\n        ring.\n      + subst.\n        subst r1.\n        preg_simpl.\n        assumption.\n      + subst.\n        subst r1.\n        preg_simpl.\n        assumption.\n    }\n    {\n      step_l.\n      step_l.\n      step_l.\n      prep_r.\n      step_r.      \n      prep_exec_instr.\n      simpl.\n      repeat break_match; eauto.\n      repeat break_exists.\n      step_r.\n      step_r.\n      step_r.\n      step_r.      \n      assert (x6 = md').\n      {\n        specialize (H23 x3).\n        simpl_and_clear.\n      }\n      subst x6.\n      finish_r.\n      \n      P0 _clear step_through;\n        P0 _clear at_code;\n        P0 _clear at_code_end;\n        P0 _clear not_after_label_in_code;\n        P0 _clear st_rs;\n        P0 _clear current_block;\n        P0 _clear no_ptr_regs;\n        P0 _clear no_ptr_mem;\n        P0 _clear match_metadata;\n        P0 _clear global_perms;\n        inv_state;\n        P0 bump val_eq;\n        P0 bump exec_instr_bits.\n      specialize (H14 x5).\n      repeat clear_dup.      \n      unfold exec_instr_bits in *.\n      remember r6 as cond_l_rs.\n      remember (eval_testcond Cond_e cond_l_rs) as cond_l.\n      remember ((nextinstr\n               (compare_ints (Val.and (rsr r3) (rsr r3)) Vzero rsr mr))) as cond_r_rs.\n      remember (eval_testcond Cond_ne cond_r_rs) as cond_r.\n      repeat gentle_inv_next.      \n      subst m2. subst m3. subst m0. subst m1.\n      subst a3 a0 a1 a2.\n      exploit (eval_testcond_match cond_l_rs cond_r_rs Cond_e);\n        try solve [\n              subst;\n              subst r6;\n              try eapply val_eq_nextinstr;\n              try eapply val_eq_compare_ints;\n              try eapply val_eq_and;\n              simpl;\n              try assumption;      \n              try reflexivity;\n              eauto 8 ].\n      intro.\n      \n      unfold jumps_to_label in *.\n      rewrite H28 in H31.\n      assert (cond_l = Some false \\/ cond_l = None).\n      {\n        break_match_lem H31.\n        break_if.\n        congruence.\n        left.\n        congruence.\n        right.\n        congruence.\n      }\n      clear H31.\n      \n      break_or'.      \n      - subst cond_l.\n        rewrite H21 in H5.\n        gentle_inv_next.\n        subst m.\n        clear H10.\n        break_or'.\n        congruence.\n        symmetry in H5.\n        rewrite H21 in H5.\n        eapply eval_testcond_e_neg in H5.\n        Focus 2.\n        subst.\n        clear -H5 H0 H1 H6.\n        unfold compare_ints.\n        preg_simpl.\n        unfold Val.cmpu.\n        unfold Val.of_optbool.\n        unfold eval_testcond in *.\n        \n        simpl_match_hyp.\n        inv_some.\n        preg_simpl_hyp Heqv.\n        unfold Val.cmpu in *.\n        unfold Val.of_optbool in *.\n        break_match.\n        break_if; auto.\n        congruence.        \n                \n        subst cond_r.\n        collapse_match_hyp.\n        P1 _simpl negb.\n        gentle_inv_next.        \n        subst x4.                \n        P0 _clear current_instr.\n        \n        split.\n        2: eq_mem_tac.\n        intros.\n        repeat break_or_reg.\n        + subst.\n          preg_simpl.\n          repeat find_rewrite_goal.\n          simpl.\n          reflexivity.\n        + subst.\n          subst r6.\n          preg_simpl.\n          assumption.\n        + subst.\n          subst r6.\n          preg_simpl.\n          assumption.\n      - subst cond_l.\n        rewrite H21 in H5.\n        congruence.\n    }      \n  Qed.\n\n  Definition aiken_3_proofs : rewrite_proofs :=\n    {|\n      defs := aiken_3_defs\n      ; selr := aiken_3_selr\n    |}.\n\n  Definition peep_aiken_3 : \n    concrete = fnd aiken_3_defs ->\n    StepEquiv.rewrite.\n  Proof.\n    intros.\n    peep_tac_mk_rewrite aiken_3_defs aiken_3_proofs.\n  Qed.\n\nEnd AIKEN_3.\n  \nDefinition aiken_3_rewrite (c : code) : option StepEquiv.rewrite.\n  name peep_aiken_3 p.\n  unfold aiken_3_defs in p.\n  simpl in p. \n  specialize (p c).\n  do 5 set_code_cons c.\n  set_code_nil c.\n  set_instr_eq i 0%nat aiken_3_example.\n  set_instr_eq i0 1%nat aiken_3_example.\n  set_instr_eq i1 2%nat aiken_3_example.\n  set_instr_eq i2 3%nat aiken_3_example.\n  set_instr_eq i3 4%nat aiken_3_example.  \n  rename_all label lb.\n  rename_all ireg a.    \n  set_testcond_eq c Cond_e.\n  set_label_eq lb0 lb.\n  set_ireg_eq a2 a1.\n  set_ireg_neq a0 a.\n  specialize (p a0 a1 a lb n eq_refl).\n  exact (Some p).\nDefined.\n\nDefinition aiken_3 (c : code) : list StepEquiv.rewrite :=\n  collect (map aiken_3_rewrite (ParamSplit.matched_pat aiken_3_example c)).\n", "meta": {"author": "uwplse", "repo": "peek", "sha": "4943735ed39fd5ddadf2c28fc2ada31504228561", "save_path": "github-repos/coq/uwplse-peek", "path": "github-repos/coq/uwplse-peek/peek-4943735ed39fd5ddadf2c28fc2ada31504228561/compcert/peeps/Aiken3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24605920824597813}}
{"text": "\n(** * Invertibility results for the negative phase\n\nThis file proves that exchange is admissible also in the list L in\n[seq Gamma Delta (> L)]. For that, some invertibility lemmas are\nneeded.\n *)\nRequire Export LL.Misc.Hybrid.\nRequire Export LL.SL.MMLL.Tactics.\nRequire Import Lia.\nRequire Import LL.Misc.Permutations.\nRequire Import FunInd.\nRequire Import Coq.Program.Equality.\nRequire Export LL.Misc.UtilsForall.\n\nExport ListNotations.\nExport LLNotations.\nSet Implicit Arguments.\n\nSection InvNPhase .\n    Context `{SI : SigMMLL}.\n  Context `{OLS: OLSig}.\n  Hint Constructors isFormula  seqN IsPositiveAtom : core .\n\n  Variable theory : oo -> Prop .\n  Notation \" n '|---' B ';' L ';' X \" := (seqN theory n B L X) (at level 80).\n  Notation \" '|--' B ';' L ';' X \" := (seq theory B L X) (at level 80).\n\n  Theorem exp_weight0LF : forall l L, 0%nat = complexity l + complexityL L -> False.\n  Proof.\n    intros.\n    assert(complexity l > 0%nat) by (apply Complexity0).\n    lia.\n  Qed.\n\n  \n  Theorem EquivAuxBot :  forall CC LC M M',\n      |-- CC ; LC ; (UP (M ++ M') ) ->\n     |-- CC ;  LC ; (UP (M ++ Bot :: M') ) .\n  Proof with sauto.\n    intros.\n    remember (complexityL M) as SizeM.\n    revert dependent CC.\n    revert dependent LC.\n    revert dependent M.\n    revert dependent M'.\n    induction SizeM using strongind;intros ...\n    \n    symmetry in HeqSizeM; apply ComplexityL0 in HeqSizeM ...\n    solveLL ...\n    \n    destruct M as [ | a]; simpl in HeqSizeM.\n    inversion HeqSizeM.\n    destruct a; simpl in *; invTri' H0;solveLL; \n      repeat rewrite app_comm_cons.\n    all:  try match goal with\n          |  [ |- seq _ _ _ (UP (?M ++ Bot :: _)) ] =>\n             eapply H with (m:= complexityL M);simpl in *; inversion HeqSizeM; solveF\n          end. \n    assert (Hvar : proper (VAR con 0%nat)) by constructor.\n    generalize (ComplexityUniformEq H5 properX Hvar);intro.\n    lia.\n  Qed.\n\n  Theorem EquivAuxWith :  forall F G CC LC M M',\n      |-- CC ; LC ; (UP (M ++ [F] ++ M') ) ->\n      |-- CC ; LC ;(UP (M ++ [G] ++ M') ) ->\n      |-- CC ; LC ; (UP (M ++ (AAnd F G) :: M') ) .\n  Proof with sauto.\n    intros.\n    remember (complexityL M) as SizeM.\n    revert dependent CC.\n    revert dependent LC.\n    revert dependent M.\n    revert dependent M'.\n    induction SizeM using strongind;intros ...\n    \n    symmetry in HeqSizeM; apply ComplexityL0 in HeqSizeM ...\n    \n    destruct M as [ | a]; simpl in HeqSizeM.\n    inversion HeqSizeM.\n    \n    destruct a; simpl in *; invTri' H0;solveLL;\n      repeat rewrite app_comm_cons.\n   all:   try solve [\n            match goal with\n            |  [ |- seq _ _ _ (UP (?M ++ (AAnd _ _) :: _)) ] =>\n               eapply H with (m:= complexityL M);simpl in *; inversion HeqSizeM;solveF;FLLInversionAll;auto\n            end] .\n    eapply H with (M:= o x:: M) (m:= complexityL (o x:: M));simpl in *; inversion HeqSizeM;solveF;FLLInversionAll;auto.\n    generalize (ComplexityUniformEq H6 properX (proper_VAR con 0%nat));intro...\n  Qed.\n  \n  \n  \n  Theorem EquivAuxPar : forall F G CC LC M M',\n      |-- CC ; LC ; (UP (M ++ [F ; G] ++ M') ) ->\n      |-- CC ; LC ;(UP (M ++ (MOr F G) :: M') ) .\n  Proof with sauto.\n    intros.\n    remember (complexityL M) as SizeM.\n    revert dependent CC.\n    revert dependent LC.\n    revert dependent M.\n    revert dependent M'.\n    induction SizeM using strongind;intros ...\n    \n    symmetry in HeqSizeM; apply ComplexityL0 in HeqSizeM ...\n    \n    destruct M as [ | a]; simpl in HeqSizeM.\n    inversion HeqSizeM.\n    \n    destruct a; simpl in *; invTri' H0;solveLL;\n      repeat rewrite app_comm_cons;\n      match goal with\n      |  [ |- seq _ _ _ (UP (?M ++ (MOr F G) :: _)) ] =>\n         eapply H with (m:= complexityL M);simpl in *; inversion HeqSizeM; solveF\n      end.\n    generalize (ComplexityUniformEq H5 properX (proper_VAR con 0%nat));intro...\n  Qed.\n  \n  Theorem EquivAuxStore :\n    forall F CC LC M M', positiveLFormula  F ->\n                         |-- CC ; (LC ++ [F]) ;(UP (M ++ M') ) ->\n                         |-- CC ; LC ; (UP (M ++ F :: M') ) .\n  Proof with sauto.\n  \n    intros.\n    remember (complexityL M) as SizeM.\n    revert dependent CC;\n    revert dependent LC;\n    revert dependent M;\n    revert dependent M'.\n    induction SizeM using strongind;intros ...\n    - symmetry in HeqSizeM; apply ComplexityL0 in HeqSizeM ...\n      LLStore.\n      LLExact H0.\n    - destruct M as [ | a]; simpl in HeqSizeM.\n      inversion HeqSizeM.\n      destruct a;CleanContext;invTri' H1;try rewrite <- app_comm_cons;solveLL.\n      -- eapply H0 with (m:= complexityL M)...\n         inversion HeqSizeM;auto.\n      -- eapply H0 with (m:= complexityL M)...\n         inversion HeqSizeM;auto.\n      -- eapply H0 with (m:= complexityL M)...\n         inversion HeqSizeM;auto.\n      -- eapply H0 with (m:= complexityL M)...\n         inversion HeqSizeM;auto.\n      -- eapply H0 with (m:= complexityL M)...\n         inversion HeqSizeM;auto.\n      -- rewrite app_comm_cons. \n         eapply H0 with (m:= complexityL (a1 :: M))...\n         inversion HeqSizeM;simpl;try lia.\n      -- rewrite app_comm_cons. \n         eapply H0 with (m:= complexityL (a2 :: M))...\n         inversion HeqSizeM;simpl;try lia.\n      -- eapply H0 with (m:= complexityL M)...\n         inversion HeqSizeM;try lia.                  \n      -- eapply H0 with (m:= complexityL M)...\n         inversion HeqSizeM;try lia.                  \n      -- rewrite app_comm_cons.\n         rewrite app_comm_cons. \n         eapply H0 with (m:= complexityL (a1 :: a2 :: M))...\n         inversion HeqSizeM;simpl;try lia.\n      -- eapply H0 with (m:= complexityL M)...\n         inversion HeqSizeM;try lia.        \n      -- eapply H0 with (m:= complexityL M)...\n         inversion HeqSizeM;try lia.              \n      -- rewrite app_comm_cons.\n         eapply H0 with (m:= complexityL (o x :: M))...\n         inversion HeqSizeM;simpl;try lia.       \n         generalize (ComplexityUniformEq H6 properX (proper_VAR con 0%nat));intro...  rewrite <- app_comm_cons...\n      -- eapply H0 with (m:= complexityL M)...\n         inversion HeqSizeM;try lia. \n  Qed.\n  \n  \n  Theorem EquivAuxQuest : forall a F CC LC M M',\n      |--  (a,F)::CC ; LC ;(UP (M ++  M') ) ->\n      |-- CC ; LC ; (UP (M ++ [Quest a F] ++ M') ) .\n  Proof with sauto.\n    intros.\n    remember (complexityL M) as SizeM.\n    revert dependent CC.\n    revert dependent LC.\n    revert dependent M.\n    revert dependent M'.\n    induction SizeM using strongind;intros ...\n    \n    symmetry in HeqSizeM; apply ComplexityL0 in HeqSizeM ...\n    simpl;solveLL...\n  \n    destruct M; simpl in HeqSizeM.\n    inversion HeqSizeM.\n    \n    destruct o; simpl in *; invTri' H0;solveLL;\n      repeat rewrite app_comm_cons;\n      try solve [\n            match goal with\n            |  [ |- seq _ _ _ (UP (?M ++ (Quest _ _) :: _)) ] =>\n              eapply H with (m:= complexityL M);simpl in *; inversion HeqSizeM;solveF;FLLInversionAll;auto\n            end] .\n        \n       rewrite perm_swap in H4.     \n      eapply H with (m:= complexityL M);simpl in *; inversion HeqSizeM;solveF;FLLInversionAll;auto.\n            \n    eapply H with (m:= complexityL (o x :: M));simpl in *; inversion HeqSizeM;solveF;FLLInversionAll;auto.\n    generalize (ComplexityUniformEq H5 properX (proper_VAR con 0%nat));intro...\n  Qed.\n  \n  \n  Theorem EquivAuxTop :  forall CC LC M M',\n      isFormulaL M ->\n      |-- CC ; LC ; (UP (M ++ Top :: M') ) .\n  Proof with sauto.\n    intros.\n    remember (complexityL M) as SizeM.\n    revert dependent CC.\n    revert dependent LC.\n    revert dependent M.\n    revert dependent M'.\n    induction SizeM using strongind;intros ...\n    \n    symmetry in HeqSizeM; apply ComplexityL0 in HeqSizeM ...\n   \n    destruct M as [ | a]; simpl in HeqSizeM.\n    \n    inversion HeqSizeM.\n   \n    destruct a; simpl in *;solveLL;\n      repeat rewrite app_comm_cons;\n      try solve [\n            match goal with\n            |  [ |- seq _ _ _ (UP (?M ++ Top :: _)) ] =>\n               eapply H with (m:= complexityL M);simpl in *; inversion HeqSizeM; solveF; inversion H0;subst;auto\n            end].\n    \n    eapply H with (m:= complexityL (a1 ::M));simpl in * ; inversion HeqSizeM; solveF; inversion H0;subst;auto.\n    inversion H3;subst...\n    eapply H with (m:= complexityL (a2 ::M));simpl in * ; inversion HeqSizeM; solveF; inversion H0;subst;auto.\n    inversion H3;subst...\n    eapply H with (m:= complexityL (a1 :: a2 ::M));simpl in * ; inversion HeqSizeM; solveF; inversion H0;subst;auto.\n    inversion H3;subst...\n  \n    rewrite <- app_comm_cons. \n    \n    LLStore.\n    eapply H with (m:= complexityL M);simpl in *; inversion HeqSizeM; solveF; inversion H0;subst;auto.\n    \n     inversion H0... inversion H3...\n   rewrite <- app_comm_cons. \n    LLForall.\n    eapply H with (M:= o x :: M) (m:= complexityL (o x ::M));simpl in * ; inversion HeqSizeM; solveF; inversion H0;subst;auto.\n\n    \n    rewrite (ComplexityUniformEq  H2 H1 (proper_VAR con 0%nat));auto.\n  Qed.\n\n  Theorem EquivAuxForAll : forall FX CC LC M M' ,\n      isFormulaL M -> uniform_oo FX ->\n      (forall t, proper t ->  |-- CC ; LC ; (UP (M ++ (FX t) ::M') )) ->\n      |--  CC ; LC ; (UP (M ++ All FX:: M') ) .\n  Proof with sauto.\n    intros.\n    remember (complexityL M) as SizeM.\n    revert dependent CC.\n    revert dependent LC.\n    revert dependent M.\n    revert dependent M'.\n    induction SizeM using strongind;intros ...\n    \n    symmetry in HeqSizeM; apply ComplexityL0 in HeqSizeM ...\n    \n    destruct M as [ | a]; simpl in HeqSizeM.\n    inversion HeqSizeM.\n    inversion H1...\n    \n    destruct a; simpl in *;solveLL;\n      try solve [eapply H with (m:= complexityL M);inversion HeqSizeM;subst;solveF;intros;solveLL; inversion H1;subst;auto;\n                 generalize (H2 _ H3);intros Hs;invTri' Hs ;solveF]...\n\n    \n    eapply H with (M:= a1 :: M)(m:= complexityL (a1 :: M));inversion HeqSizeM;subst...  simpl. lia.\n    inversion H5... intros. generalize (H2 _ H3);intros Hs;invTri' Hs ;solveF.\n\n    eapply H with (M:= a2 :: M)(m:= complexityL (a2 :: M));inversion HeqSizeM;subst... simpl. lia.\n    inversion H5... intros. generalize (H2 _ H3);intros Hs;invTri' Hs ;solveF.\n\n    eapply H with (M:= a1 :: a2 :: M)(m:= complexityL (a1 :: a2 :: M));inversion HeqSizeM;subst... simpl. lia.\n    inversion H5... intros. generalize (H2 _ H3);intros Hs;invTri' Hs ;solveF.\n    \n   inversion H5...\n   LLStore.\n    eapply H with (M:= M)(m:= complexityL (M));inversion HeqSizeM;subst... intros. generalize (H2 _ H3);intros Hs;invTri' Hs ;solveF.\n    inversion H5...\n    \n   LLForall.\n   \n    eapply H with (M:=  o x :: M)(m:= complexityL (o x :: M));inversion HeqSizeM;subst...\n    generalize (ComplexityUniformEq H4 H3 (proper_VAR con 0%nat));intros... simpl...\n    intros...\n    \n    generalize (H2 _ H8);intros Hs. invTri' Hs...\n    apply H14 in H3...\n  Qed.\n  \n\n  Theorem EquivUpArrow : forall B L L' M n,\n      isFormulaL L' ->\n      (n |--- B ; M ; UP L) ->\n      Permutation L L' ->\n      |-- B ; M ;  UP L'.\n  Proof with sauto.\n    intros.\n    remember (complexityL L) as w.\n    generalize dependent n .\n    generalize dependent L .\n    generalize dependent L' .\n    generalize dependent B .\n    generalize dependent M .\n    generalize dependent w .\n    \n    induction w as [| w' IH] using strongind;  intros ;  destruct L as [|l]...\n    +  apply seqNtoSeq in H0;auto.\n    + inversion Heqw.\n      apply exp_weight0LF in H3...\n    +  destruct L' as [| l']...\n       \n       assert\n         ((l = l' /\\ Permutation L L') \\/\n          (exists L1 L2 L1' L2', L = L1 ++ [l'] ++ L2 /\\ L' = L1' ++ [l] ++ L2' /\\ Permutation (L1 ++ L2) (L1' ++ L2') )) .\n       { checkPermutationCases H1.\n         right.\n         assert (exists T1 T2, L' = T1 ++ [l] ++ T2).\n         { induction x.\n           do 2 eexists []...\n           sauto.\n           assert (In l  L') as Hm.\n           rewrite H1...\n           apply in_split;auto. } \n         assert (exists T1 T2, L = T1 ++ [l'] ++ T2).\n         { induction x.\n           do 2 eexists []...\n           sauto.\n           assert (In l'  L) as Hm.\n           rewrite H3...\n           apply in_split;auto. }\n          simplifier.\n       eexists x0; eexists x1;eexists x2; eexists x3. \n       intuition. \n      rewrite H4 in H3.\n      simpl in H3.\n      rewrite Permutation_midle in H3. \n      apply Permutation_cons_inv in H3.\n      rewrite H2 in H1.\n      simpl in H1.\n      rewrite Permutation_midle in H1. \n      apply Permutation_cons_inv in H1.\n      rewrite H1. rewrite H3. auto. }\n      destruct H2 as [Heq | Heq].\n        ++ destruct Heq;subst.\n           inversion H0;subst;try(simpl in Heqw; inversion Heqw; subst;simpl;try(lia)).\n           +++  (* top *)\n             LLTop.\n           +++ (* bottom *)\n             eapply IH with (L' :=L') in H7;auto.\n             inversion H;subst;auto.\n           +++ (* par *)\n             eapply IH with (L' := F::G::L') in H7;auto.\n             inversion H;subst.\n             inversion H5;subst.\n             SLSolve.\n             simpl. lia.\n           +++ (* with *)\n             eapply IH with (m:= complexityL (F::L)) (L:= F ::L) (L' := F :: L') in H8;auto.\n             eapply IH with (m:= complexityL (G::L)) (L := G :: L) (L' := G :: L') in H9;auto.\n             simpl. lia.\n             inversion H;subst.\n             inversion H5;subst.\n             SLSolve.\n             simpl. lia.\n             inversion H;subst.\n             inversion H5;subst.\n             change (F :: L') with ([F] ++ L').\n             apply Forall_app;auto.           \n           +++  (* quest *)\n             eapply IH with (m:= complexityL L) (L' :=L') in H7;auto.\n             lia.\n             inversion H;subst;auto.\n           +++  (* store *)\n             eapply IH with (m:= complexityL L) (L' :=L') in H9;auto.\n             assert (complexity l' > 0) by (apply Complexity0).\n             lia.\n             inversion H;subst;auto.\n           +++ (* forall *)\n             eapply tri_fx';auto;intros.\n             generalize (H9 x H2);intro.\n             eapply IH with (m:= complexity (FX x) + complexityL L) (L' := FX x :: L') in H4;auto.\n             assert(complexity (FX (VAR con 0%nat)) = complexity (FX x) ).\n             apply ComplexityUniformEq;auto.          \n             constructor.\n             lia.\n             inversion H;subst.\n             inversion H7;subst.\n             change (FX x  :: L') with ([FX x ] ++ L').\n             apply Forall_app;auto.\n             \n        ++\n          destruct Heq as [L1 [L2 [L1' [L2' Heq]]]].\n          destruct Heq as [Heq [Heq1 Heq2]];subst.\n          \n          inversion H0;subst.\n          \n          +++ (* top *)\n            eapply EquivAuxTop with (M:= l' :: L1').\n          rewrite app_comm_cons in H.\n            autounfold in H.\n            autounfold.\nsolveForall.\n          +++ (* bottom *)\n            eapply IH with (m:= complexityL (L1 ++ l' :: L2))(L:=L1 ++ l' :: L2) (L' := [l'] ++ L1' ++ L2') in H6 .\n            simpl in H6. \n            apply EquivAuxBot with (M:= l' :: L1');auto.\n            simpl in Heqw. inversion Heqw. auto.\n            inversion H;subst;auto.\n              rewrite app_comm_cons in H.  SLFormulaSolve.\n             autounfold in H.\n            autounfold.\n            solveForall.  \n          \n            rewrite Permutation_midle.\n            apply Permutation_cons;auto. \n            auto.\n            \n          +++ (* par *)\n            eapply IH with (m:= complexityL (F :: G :: L1 ++ l' :: L2))\n                           (L:=F :: G :: L1 ++ l' :: L2)\n                           (L' := [l'] ++ L1' ++ [F ; G] ++ L2') in H6.\n            apply seqtoSeqN in H6. destruct H6.\n            eapply EquivAuxPar with (M:= l' :: L1');simpl;simpl in H2;eauto using seqNtoSeq.\n            simpl in Heqw. inversion Heqw. simpl.  lia.\n              inversion H;subst;auto.\n              rewrite app_comm_cons in H.  SLFormulaSolve.\n   autounfold in H.\n            autounfold.\n            solveForall.  \n          \n          \n            apply Forall_app in H5;auto.\n            inversion H5;subst;auto.\n            inversion H3;subst;auto.\n            inversion H9...\n             apply Forall_app in H5;auto.\n            inversion H5;subst;auto.\n            inversion H3;subst;auto.\n            inversion H9...\n            rewrite Permutation_midle. \n            rewrite Heq2. perm.\n            auto.\n\n\n          +++ (* with *)\n            eapply IH with (m:= complexityL (F :: L1 ++ l' :: L2))\n                           (L:=F :: L1 ++ l' :: L2)\n                           (L' := [l'] ++ L1' ++ [F ] ++ L2') in H7;auto .\n            eapply IH with (m:= complexityL (G :: L1 ++ l' :: L2))\n                           (L:=G :: L1 ++ l' :: L2)\n                           (L' := [l'] ++ L1' ++ [G ] ++ L2') in H8;auto .\n            \n            apply EquivAuxWith with (M := l' :: L1'); simpl;auto.\n            inversion Heqw. simpl. lia.\n              inversion H;subst;auto.\n              rewrite app_comm_cons in H.  SLFormulaSolve.\n              autounfold in H.\n            autounfold.\n            solveForall.  \n          \n            apply Forall_app in H5;auto.\n            inversion H5;subst;auto.\n            inversion H3;subst;auto.\n            inversion H10...\n            \n            rewrite Permutation_midle. rewrite Heq2. perm.\n            inversion Heqw. simpl. lia.\n              inversion H;subst;auto.\n              rewrite app_comm_cons in H.  SLFormulaSolve.\n              autounfold in H.\n            autounfold.\n            solveForall.  \n          \n            apply Forall_app in H5;auto.\n            inversion H5;subst;auto.\n            inversion H3;subst;auto.\n            inversion H10...\n            simpl.\n            \n            rewrite Permutation_midle. rewrite Heq2. perm.\n            \n          +++ (* quest *)\n            eapply IH with (m:= complexityL (L1 ++ l' :: L2))(L:=L1 ++ l' :: L2) (L' := [l'] ++ L1' ++ L2') in H6;auto .\n            apply seqtoSeqN in H6. destruct H6.   \n            eapply EquivAuxQuest with (M := l' :: L1');simpl in H2.\n            eauto using seqNtoSeq.\n            \n            inversion Heqw. simpl. lia.\n              inversion H;subst;auto.\n              rewrite app_comm_cons in H.  SLFormulaSolve.\n              autounfold in H.\n            autounfold.\n            solveForall.  \n          \n            rewrite Permutation_midle. rewrite Heq2. perm.\n\n          +++ (* copy *)\n            eapply IH with (m:= complexityL(L1 ++ l' :: L2))(L:=L1 ++ l' :: L2) (L' := [l'] ++ L1' ++ L2') in H8;auto .\n\n            eapply EquivAuxStore with (M:=l' :: L1');eauto.\n            rewrite Permutation_app_comm;eauto. \n            inversion Heqw.\n            assert (complexity l > 0) by (apply Complexity0).\n            lia.\n              inversion H;subst;auto.\n              rewrite app_comm_cons in H.  SLFormulaSolve.\n    autounfold in H.\n            autounfold.\n            solveForall.  \n          \n            rewrite Permutation_midle. rewrite Heq2. perm.\n          +++ (* forall *)\n            \n            \n            assert(forall x, proper x -> |-- B; M; UP ((l' :: L1' ) ++ [FX x] ++ L2')).\n            intros x pX.\n            eapply IH with (m:= complexityL(FX x :: L1 ++ l' :: L2)) (L:=FX x :: L1 ++ l' :: L2)  ;auto.\n            inversion Heqw.\n            simpl. \n            assert(complexity (FX (VAR con 0%nat)) = complexity (FX x) ).\n            \n            apply ComplexityUniformEq;auto. \n            constructor. lia.\n            \n            inversion H;subst;auto.\n            change ((l' :: L1') ++ [FX x] ++ L2') with ([l'] ++ L1' ++ [FX x] ++ L2').\n              inversion H;subst;auto.\n              rewrite app_comm_cons in H.  SLFormulaSolve.\n    autounfold in H.\n            autounfold.\n            solveForall.  \n          \n            apply Forall_app in H5;auto.\n            inversion H5;subst;auto.\n            inversion H3;subst;auto.\n            inversion H12...\n            rewrite Permutation_midle. rewrite Heq2. perm.\n\n            assert(forall B  L L' M   FX, \n                      isFormulaL L -> uniform_oo FX ->  (forall x, proper x -> |-- B ; M ; UP (L ++ [FX x]++ L')) ->  |-- B ; M ;  UP (L ++ [All FX] ++ L')).\n            intros.\n            eapply EquivAuxForAll;auto.\n            \n            apply H3 in H2;auto.\n            inversion H;subst.\n              inversion H;subst;auto.\n              rewrite app_comm_cons in H.  SLFormulaSolve.\n              autounfold in H.\n            autounfold.\n            solveForall.  \n          \n  Qed.\n\n  Theorem EquivUpArrow2 : forall B L L' M ,\n      isFormulaL L' ->\n      (|-- B ; M ; UP L) -> Permutation L L' ->\n      |-- B ; M ;  UP L'.\n    intros.\n    apply seqtoSeqN in H0.\n    destruct H0.\n    eapply EquivUpArrow in H0;eauto.\n  Qed.\n\n\n\n  Generalizable All Variables.\n  Global Instance Forall_morph : \n    Proper ((@Permutation oo) ==> Basics.impl) (Forall positiveLFormula).\n  Proof.\n    unfold Proper; unfold respectful; unfold Basics.impl.\n    intros.\n    rewrite <- H;eauto.\n  Qed. \n\n  \n  \n  Lemma UpExtension: forall B M L F n,\n      positiveLFormula F ->\n      (n |--- B; F::M ; UP L) ->\n      exists m, m<= S n /\\ m |--- B; M ; UP (L ++ [F]).\n  Proof with subst;auto.\n    intros.\n    remember (complexityL L) as w.\n    generalize dependent L .\n    generalize dependent B .\n    generalize dependent F .\n    generalize dependent M .\n    generalize dependent n .\n    generalize dependent w .\n\n    induction w as [| w' IH] using strongind .\n    intros n M F HNA B L HD Hw.\n    + (* w = 0 *)\n      destruct L. (* L must be empty. The second case is trivial *)\n      { exists ((S n)). firstorder.\n      simpl.\n      eapply tri_store;auto. }\n      simpl in Hw.\n      apply exp_weight0LF in Hw;contradiction.\n    + intros.\n      destruct L. (* L cannot be empty *)\n      inversion Heqw.\n      inversion H0;auto;subst;inversion Heqw;subst.\n      ++ (* top *)\n        exists 0%nat. \n        firstorder;[lia | eapply tri_top ].\n      ++ (* bot *)\n        apply IH with (m:= complexityL L) in H5;auto.\n        destruct H5 as [n'  [IHn IHd]].\n        exists (S n').\n        firstorder;[lia | eapply tri_bot;auto ].\n      ++  (* PAR *)\n        apply IH with (m:= complexity F0 + complexity  G + complexityL  L) in H5;auto.\n        destruct H5 as [n'  [IHn IHd]].\n        exists (S n').\n        firstorder ;[lia | eapply tri_par;auto ].\n        simpl. lia.\n      ++ (* with *)\n        apply IH with (m:= complexity  F0 + complexityL  L) in H6;try lia;auto.\n        apply IH with (m:= complexity  G + complexityL L) in H7;try lia;auto.\n        destruct H6 as [n'  [IHn IHd]].\n        destruct H7 as [m'  [IHn' IHd']].\n        simpl.\n        exists (S (S n0)).\n        firstorder; eapply tri_with;auto.\n        eapply HeightGeq with (n:=n');try firstorder.  \n       eapply HeightGeq with (n:=m');try firstorder.  \n      ++  (* quest *)\n        apply IH with (m:= complexityL  L) in H5;auto.\n        destruct H5 as [n'  [IHn IHd]].\n        exists (S n').\n        firstorder ;[lia | eapply tri_quest;auto ]. \n        lia.\n      ++ (* Store *)\n        assert(exists m0 : nat, m0 <= S n0 /\\ m0 |--- B; M ++ [o]; UP (L ++ [F])).\n        apply IH with (m:= complexityL L);auto.\n        assert (complexity o > 0) by (apply Complexity0);lia.\n        eapply exchangeLCN;[|exact H7].\n        perm.\n        \n        destruct H1 as [n'  [IHn IHd]].\n        exists (S n').\n        firstorder ;[lia | eapply tri_store;[auto | LLExact IHd] ].\n     ++  (* FORALL *)\n        assert(forall x, proper x -> exists m, m <= S n0 /\\  m |--- B; M; UP ((FX x :: L)  ++ [F])).\n        intros.\n        generalize (H7 x H1);intro.\n        eapply IH with (m:=complexity (FX x) + complexityL L);auto.\n        assert(complexity (FX (VAR con 0%nat)) = complexity (FX x) ).\n        \n        apply ComplexityUniformEq;auto. \n        \n        constructor.\n        lia.\n        \n        simpl.\n        exists (S (S n0)). \n        split ; [auto|eapply tri_fx;auto;intros].\n        \n        generalize (H1 _ H2);intro.\n        \n        destruct H3 as [n H3].\n        destruct H3 as [H3 H3'].\n        eapply @HeightGeq with (n:=n);try firstorder.\n       \n  Qed.\n  \n    Lemma UpExtension': forall B M L F,\n      positiveLFormula F ->\n      (|-- B; F::M ; UP L) -> |-- B; M ; UP (L ++ [F]).\n  Proof with sauto.\n  intros.\n  apply seqtoSeqN in H0.\n  destruct H0.\n  apply UpExtension in H0...\n  apply seqNtoSeq in H2...\n  Qed.\n\n(* Lemma UpExtensionInv n F B M L :\n     n |---  B ; M ; (UP (L++[F])) -> |-- B ; F::M; (UP L).\n  Proof with sauto;solveF;try solveLL.\n  intros.\n  \n  revert dependent F. \n  revert B M L.\n  induction n using strongind;intros...\n  + inversion H...\n    apply ListConsApp in H4...\n    LFocus. Print positiveFormula. constructor. \n  + inversion H0... \n    -\n    apply ListConsApp in H5...\n    decide1 top M.\n    -\n    apply ListConsApp in H2...\n    decide1 bot M.\n    apply seqNtoSeq in H5...\n    eapply H in H5...\n    -\n    apply ListConsApp in H2...\n    decide1 (F0 $ G) M.\n    apply seqNtoSeq in H5...\n    rewrite app_comm_cons in H5.\n    rewrite app_comm_cons in H5. \n    eapply H in H5...\n    -\n    apply ListConsApp in H2...\n    decide1 (F0 & G) M.\n    apply seqNtoSeq in H3...\n    apply seqNtoSeq in H6...\n    rewrite app_comm_cons in H3. \n    eapply H in H3...    \n    rewrite app_comm_cons in H6.\n    eapply H in H6...\n    -\n    apply ListConsApp in H2...\n    decide1 (i ? F0) M.\n    apply seqNtoSeq in H5...\n    eapply H in H5...\n    -\n    apply ListConsApp in H2...\n    apply seqNtoSeq in H6;auto.\n    eapply H in H6...\n    LLExact H6.        \n    - \n    apply ListConsApp in H2...\n    decide1 (F{ FX}) M.\n    apply H6 in properX...\n    apply seqNtoSeq in properX...\n    apply H6 in properX...\n    rewrite app_comm_cons in properX.\n    eapply H in properX...\n Qed. \n\n\nLemma UpExtensionInvN n F B M L :\n     n |---  B ; M ; (UP (L++[F])) -> S (S n) |--- B ; F::M; (UP L).\n  Proof with sauto;solveF;solveLL.\n  intros.\n  revert dependent F. \n  revert B M L.\n  induction n using strongind;intros...\n  + inversion H...\n    apply ListConsApp in H4...\n    decide1 top M.\n  + inversion H0...\n    -\n    apply ListConsApp in H5...\n    decide1 top M.\n    -\n    apply ListConsApp in H2...\n    decide1 bot M.\n    -\n    apply ListConsApp in H2...\n    decide1 (F0 $ G) M.\n    -\n    apply ListConsApp in H2...\n    decide1 (F0 & G) M.\n    -\n    apply ListConsApp in H2...\n    decide1 (i ? F0) M.\n    -\n    apply ListConsApp in H2...\n    LLExact H6.\n    apply (exchangeLCN (perm_swap F0 F M))...\n    -\n    apply ListConsApp in H2...\n    decide1 (F{ FX}) M.\n    apply H6 in properX...\n Qed. \n  \n  Lemma UpExtensionInv' F B M L : \n       |--  B ; M ; (UP (L++[F])) -> |-- B ; F::M; (UP L).\n  Proof with sauto.\n  intros.\n  apply seqtoSeqN in H.\n  destruct H.\n  apply UpExtensionInv in H... \n  Qed.\n *)\n\n(* Lemma UpExtensionInv2 n F B M L1 L2 :\n   positiveLFormula F ->  n |---  B ; M ; (UP (L1++[F]++L2)) -> |-- B ; F::M; (UP (L1++L2)).\n  Proof with sauto;solveF;try solveLL.\n  intros.\n  apply UpExtensionInv'.\n  \n  rewrite app_assoc_reverse.\n  revert dependent F. \n  revert B M L1 L2.\n  induction n using strongind;intros...\n  + inversion H0...\n    apply ListConsApp' in H5...\n  + inversion H1...\n    -\n    apply ListConsApp' in H6...\n    -\n    apply ListConsApp' in H3...\n    eapply H in H6...\n    -\n    apply ListConsApp' in H3...\n    rewrite app_comm_cons in H6.\n    rewrite app_comm_cons in H6. \n    eapply H in H6...\n    -\n    apply ListConsApp' in H3...\n    rewrite app_comm_cons in H4. \n    eapply H in H4...    \n    rewrite app_comm_cons in H7.\n    eapply H in H7...\n    -\n    apply ListConsApp' in H3...\n    eapply H in H6...\n    -\n    apply ListConsApp' in H3...\n    apply seqNtoSeq in H7...\n    apply UpExtension';auto.\n    eapply H in H7...        \n    -\n    apply ListConsApp' in H3...\n    apply H7 in properX...\n    rewrite app_comm_cons in properX.\n    eapply H in properX...\n Qed. \n *) \nEnd InvNPhase.\n", "meta": {"author": "brunofx86", "repo": "LLFramework", "sha": "d12e01875912ef52397d8cd899b7fb0e26977ac5", "save_path": "github-repos/coq/brunofx86-LLFramework", "path": "github-repos/coq/brunofx86-LLFramework/LLFramework-d12e01875912ef52397d8cd899b7fb0e26977ac5/SL/MMLL/InvNegativePhase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24605920824597813}}
{"text": "From stbor.sim Require Import left_step right_step.\n\nLemma sim_body_copy_local fs ft r r' n l t ty ss st σs σt Φ :\n  tsize ty = 1%nat →\n  r ≡ r' ⋅ res_loc l [(ss, st)] t →\n  (r ⊨{n,fs,ft} (#[ss], σs) ≥ (#[st], σt) : Φ) →\n  r ⊨{S n,fs,ft}\n    (Copy (Place l (Tagged t) ty), σs) ≥ (Copy (Place l (Tagged t) ty), σt)\n  : Φ.\nProof.\n  intros ?? Hcont.\n  eapply sim_body_copy_local_l; [done..|].\n  eapply sim_body_copy_local_r; done.\nQed.\n", "meta": {"author": "ocecaco", "repo": "stacked-borrows", "sha": "92090a71d2cb61887b8d037fff6fe13a0199e3c5", "save_path": "github-repos/coq/ocecaco-stacked-borrows", "path": "github-repos/coq/ocecaco-stacked-borrows/stacked-borrows-92090a71d2cb61887b8d037fff6fe13a0199e3c5/theories/sim/derived_step.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.24604901585646127}}
{"text": "(****************************************************************************)\n(* Copyright 2020 The Project Oak Authors                                   *)\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\nRequire Import Coq.micromega.Lia.\nRequire Import Cava.Cava.\nLocal Open Scope vector_scope.\n\nSection WithCava.\n  Context {signal} `{Cava signal}.\n\n  Definition twoSorter {signal} `{Cava signal} {n}\n                     (ab:  signal (Vec (Vec Bit n) 2)) :\n                     cava (signal (Vec (Vec Bit n) 2)) :=\n   a <- indexConst ab 0 ;;\n   b <- indexConst ab 1 ;;\n   comparison <- greaterThanOrEqual (a, b) ;;\n   negComparison <- inv comparison ;;\n   out0 <- mux2 comparison (a, b) ;;\n   out1 <- mux2 negComparison (a, b) ;;\n   packV [out0; out1].\n\nEnd WithCava.\n\nDefinition two_sorter_Interface bitSize\n  := combinationalInterface \"two_sorter\"\n     [mkPort \"inputs\" (Vec (Vec Bit bitSize) 2)]\n     [mkPort \"sorted\" (Vec (Vec Bit bitSize) 2)].\n\nDefinition two_sorter_Netlist\n  := makeNetlist (two_sorter_Interface 8) twoSorter.\n\nDefinition v0 := N2Bv_sized 8   5.\nDefinition v1 := N2Bv_sized 8 157.\nDefinition v2 := N2Bv_sized 8 255.\nDefinition v3 := N2Bv_sized 8  63.\n\nDefinition two_sorter_tb_inputs : list (Vector.t (Bvector 8) _) :=\n  [[v0; v1];\n   [v1; v0];\n   [v1; v2];\n   [v2; v1];\n   [v2; v3];\n   [v3; v2]\n  ].\n\nDefinition two_sorter_tb_expected_outputs : list (Vector.t (Bvector 8) _) :=\n  simulate (Comb twoSorter) two_sorter_tb_inputs.\n\nDefinition two_sorter_tb :=\n  testBench \"two_sorter_tb\" (two_sorter_Interface 8)\n  two_sorter_tb_inputs two_sorter_tb_expected_outputs.\n\nDefinition twoSorterSpec {bw: nat} (ab : Vector.t (Bvector bw) 2) :\n                                   Vector.t (Bvector bw) 2 :=\n  let a := @Vector.nth_order _ 2 ab 0 (ltac:(lia)) in\n  let b := @Vector.nth_order _ 2 ab 1 (ltac:(lia)) in\n  if (Bv2N b <=? Bv2N a)%N then\n    [b; a]\n  else\n    [a; b].\n\nLemma twoSorterCorrect {bw : nat} (v : Vector.t (Bvector bw) 2) :\n  @twoSorter combType _ _ v = twoSorterSpec v.\nProof.\n  constant_vector_simpl v.\n  cbv [twoSorterSpec twoSorter Vector.nth_order].\n  simpl.\n  destruct (Bv2N _ <=? Bv2N _)%N; try reflexivity.\nQed.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/examples/TwoSorter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.24604901585646127}}
{"text": "Require Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Eta.\nRequire Import Crypto.Compilers.ExprInversion.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.DestructHead.\n\nSection language.\n  Context {base_type_code : Type}\n          {interp_base_type : base_type_code -> Type}\n          {op : flat_type base_type_code -> flat_type base_type_code -> Type}\n          {interp_op : forall src dst, op src dst -> interp_flat_type interp_base_type src -> interp_flat_type interp_base_type dst}.\n\n  Local Notation exprf := (@exprf base_type_code op interp_base_type).\n\n  Local Ltac t_step :=\n    match goal with\n    | _ => reflexivity\n    | _ => progress simpl in *\n    | _ => intro\n    | _ => progress break_match\n    | _ => progress destruct_head prod\n    | _ => progress cbv [LetIn.Let_In]\n    | [ H : _ |- _ ] => rewrite H\n    | _ => progress autorewrite with core\n    | [ H : forall A B x, ?f A B x = x, H' : context[?f _ _ _] |- _ ]\n      => rewrite H in H'\n    | _ => progress unfold interp_flat_type_eta, interp_flat_type_eta', exprf_eta, exprf_eta', expr_eta, expr_eta'\n    end.\n  Local Ltac t := repeat t_step.\n\n  Section gen_flat_type.\n    Context (eta : forall {A B}, A * B -> A * B)\n            (eq_eta : forall A B x, @eta A B x = x).\n    Lemma eq_interp_flat_type_eta_gen {var t T f} x\n      : @interp_flat_type_eta_gen base_type_code var eta t T f x = f x.\n    Proof using eq_eta. induction t; t. Qed.\n\n    (* Local *) Hint Rewrite @eq_interp_flat_type_eta_gen.\n\n    Section gen_type.\n      Context (exprf_eta : forall {t} (e : exprf t), exprf t)\n              (eq_interp_exprf_eta : forall t e, interpf (@interp_op) (@exprf_eta t e) = interpf (@interp_op) e).\n      Lemma interp_expr_eta_gen {t e}\n        : forall x,\n          interp (@interp_op) (expr_eta_gen eta exprf_eta (t:=t) e) x = interp (@interp_op) e x.\n      Proof using Type*. t. Qed.\n    End gen_type.\n    (* Local *) Hint Rewrite @interp_expr_eta_gen.\n\n    Lemma interpf_exprf_eta_gen {t e}\n      : interpf (@interp_op) (exprf_eta_gen eta (t:=t) e) = interpf (@interp_op) e.\n    Proof using eq_eta. induction e; t. Qed.\n\n    Lemma InterpExprEtaGen {t e}\n      : forall x, Interp (@interp_op) (ExprEtaGen eta (t:=t) e) x = Interp (@interp_op) e x.\n    Proof using eq_eta. apply interp_expr_eta_gen; intros; apply interpf_exprf_eta_gen. Qed.\n  End gen_flat_type.\n  (* Local *) Hint Rewrite @eq_interp_flat_type_eta_gen.\n  (* Local *) Hint Rewrite @interp_expr_eta_gen.\n  (* Local *) Hint Rewrite @interpf_exprf_eta_gen.\n\n  Lemma eq_interp_flat_type_eta {var t T f} x\n    : @interp_flat_type_eta base_type_code var t T f x = f x.\n  Proof using Type. t. Qed.\n  (* Local *) Hint Rewrite @eq_interp_flat_type_eta.\n  Lemma eq_interp_flat_type_eta' {var t T f} x\n    : @interp_flat_type_eta' base_type_code var t T f x = f x.\n  Proof using Type. t. Qed.\n  (* Local *) Hint Rewrite @eq_interp_flat_type_eta'.\n  Lemma interpf_exprf_eta {t e}\n    : interpf (@interp_op) (exprf_eta (t:=t) e) = interpf (@interp_op) e.\n  Proof using Type. t. Qed.\n  (* Local *) Hint Rewrite @interpf_exprf_eta.\n  Lemma interpf_exprf_eta' {t e}\n    : interpf (@interp_op) (exprf_eta' (t:=t) e) = interpf (@interp_op) e.\n  Proof using Type. t. Qed.\n  (* Local *) Hint Rewrite @interpf_exprf_eta'.\n  Lemma interp_expr_eta {t e}\n    : forall x, interp (@interp_op) (expr_eta (t:=t) e) x = interp (@interp_op) e x.\n  Proof using Type. t. Qed.\n  Lemma interp_expr_eta' {t e}\n    : forall x, interp (@interp_op) (expr_eta' (t:=t) e) x = interp (@interp_op) e x.\n  Proof using Type. t. Qed.\n  Lemma InterpExprEta {t e}\n    : forall x, Interp (@interp_op) (ExprEta (t:=t) e) x = Interp (@interp_op) e x.\n  Proof using Type. apply interp_expr_eta. Qed.\n  Lemma InterpExprEta' {t e}\n    : forall x, Interp (@interp_op) (ExprEta' (t:=t) e) x = Interp (@interp_op) e x.\n  Proof using Type. apply interp_expr_eta'. Qed.\n  Lemma InterpExprEta_arrow {s d e}\n    : forall x, Interp (t:=Arrow s d) (@interp_op) (ExprEta (t:=Arrow s d) e) x = Interp (@interp_op) e x.\n  Proof using Type. exact (@InterpExprEta (Arrow s d) e). Qed.\n  Lemma InterpExprEta'_arrow {s d e}\n    : forall x, Interp (t:=Arrow s d) (@interp_op) (ExprEta' (t:=Arrow s d) e) x = Interp (@interp_op) e x.\n  Proof using Type. exact (@InterpExprEta' (Arrow s d) e). Qed.\n\n  Lemma InterpExprEta_ind {t} (P : _ -> Prop) {e x}\n    : P (Interp (@interp_op) e x) -> P (Interp (@interp_op) (ExprEta (t:=t) e) x).\n  Proof using Type. rewrite InterpExprEta; exact id. Qed.\n  Lemma InterpExprEta'_ind {t} (P : _ -> Prop) {e x}\n    : P (Interp (@interp_op) e x) -> P (Interp (@interp_op) (ExprEta' (t:=t) e) x).\n  Proof using Type. rewrite InterpExprEta'; exact id. Qed.\n  Lemma InterpExprEta_arrow_ind {s d} (P : _ -> Prop) {e x}\n    : P (Interp (@interp_op) e x) -> P (Interp (t:=Arrow s d) (@interp_op) (ExprEta (t:=Arrow s d) e) x).\n  Proof using Type. rewrite InterpExprEta_arrow; exact id. Qed.\n  Lemma InterpExprEta'_arrow_ind {s d} (P : _ -> Prop) {e x}\n    : P (Interp (@interp_op) e x) -> P (Interp (t:=Arrow s d) (@interp_op) (ExprEta' (t:=Arrow s d) e) x).\n  Proof using Type. rewrite InterpExprEta'_arrow; exact id. Qed.\n\n  Lemma eq_interp_eta {t e}\n    : forall x, interp_eta interp_op (t:=t) e x = interp interp_op e x.\n  Proof using Type. apply eq_interp_flat_type_eta. Qed.\n  Lemma eq_InterpEta {t e}\n    : forall x, InterpEta interp_op (t:=t) e x = Interp interp_op e x.\n  Proof using Type. apply eq_interp_eta. Qed.\nEnd language.\n\nHint Rewrite @eq_interp_flat_type_eta @eq_interp_flat_type_eta' @interpf_exprf_eta @interpf_exprf_eta' @interp_expr_eta @interp_expr_eta' @InterpExprEta @InterpExprEta' @InterpExprEta_arrow @InterpExprEta'_arrow @eq_interp_eta @eq_InterpEta : reflective_interp.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Compilers/EtaInterp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.24604901585646127}}
{"text": "Require Import Coq.ZArith.BinInt coqutil.Z.Lia.\nRequire Import coqutil.Word.Interface coqutil.Map.Interface.\nRequire coqutil.Map.SortedList.\n\nSection __. Local Set Default Proof Using \"All\".\n  Context {width} (word : word width) {word_ok : @word.ok width word}.\n  Global Instance strict_order_word\n    : SortedList.parameters.strict_order (T:=word) word.ltu.\n  Proof.\n    split; try setoid_rewrite word.unsigned_ltu; intros;\n      repeat match goal with\n             | H: context[Z.ltb ?a ?b] |- _ => destruct (Z.ltb_spec a b)\n             | |- context[Z.ltb ?a ?b] => destruct (Z.ltb_spec a b)\n             end; try congruence; try blia; [].\n    rewrite <-word.of_Z_unsigned; rewrite <-word.of_Z_unsigned at 1; f_equal.\n    blia.\n  Qed.\n\n  Context (value : Type).\n  Definition SortedList_parameters : SortedList.parameters :=\n    {| SortedList.parameters.value := value;\n       SortedList.parameters.key := word;\n       SortedList.parameters.ltb := word.ltu |}.\n  Definition map : map.map word value := SortedList.map SortedList_parameters strict_order_word.\n  Global Instance ok : map.ok map := @SortedList.map_ok SortedList_parameters strict_order_word.\nEnd __.\n", "meta": {"author": "mit-plv", "repo": "coqutil", "sha": "48eeef16cc9aa3a057d4a76207b88b34fd397e24", "save_path": "github-repos/coq/mit-plv-coqutil", "path": "github-repos/coq/mit-plv-coqutil/coqutil-48eeef16cc9aa3a057d4a76207b88b34fd397e24/src/coqutil/Map/SortedListWord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2460016130350515}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nRequire Export Coq.Strings.String.\nRequire Import Coq.Classes.RelationClasses.\n\nFrom Fairness Require Export ITreeLib FairBeh Mod.\nFrom Fairness Require Import pind LPCM WFLib.\nFrom Fairness Require Import ModSim.\n\nSet Implicit Arguments.\n\n\n\nSection PRIMIVIESIM.\n  Context `{M: URA.t}.\n\n  Variable state_src: Type.\n  Variable state_tgt: Type.\n\n  Variable ident_src: ID.\n  Variable _ident_tgt: ID.\n  Let ident_tgt := @ident_tgt _ident_tgt.\n\n  Variable wf_src: WF.\n  Variable wf_tgt: WF.\n\n  Let srcE := programE ident_src state_src.\n  Let tgtE := programE _ident_tgt state_tgt.\n\n  Let shared := shared state_src state_tgt ident_src _ident_tgt wf_src wf_tgt.\n\n  Let shared_rel: Type := shared -> Prop.\n\n  Variable I: shared -> URA.car -> Prop.\n\n  Variant __lsim\n          (tid: thread_id)\n          (lsim: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          (_lsim: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel),bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n  | lsim_ret\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      r_src r_tgt\n      (LSIM: RR r_src r_tgt r_ctx (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (Ret r_src) (Ret r_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_tauL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (Tau itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_chooseL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X ktr_src itr_tgt\n      (LSIM: exists x, _lsim _ _ RR true f_tgt r_ctx (ktr_src x) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Choose X) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_rmwL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X rmw ktr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src (snd (rmw st_src) : X)) itr_tgt (ths, im_src, im_tgt, fst (rmw st_src), st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Rmw rmw) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_tidL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src tid) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (GetTid) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_UB\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Undefined) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_fairL\n      f_src f_tgt r_ctx\n      ths im_src0 im_tgt st_src st_tgt\n      f ktr_src itr_tgt\n      (LSIM: exists im_src1,\n          (<<FAIR: fair_update im_src0 im_src1 f>>) /\\\n            (<<LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src tt) itr_tgt (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Fair f) >>= ktr_src) itr_tgt (ths, im_src0, im_tgt, st_src, st_tgt)\n\n  | lsim_tauR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: _lsim _ _ RR f_src true r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (Tau itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_chooseR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X itr_src ktr_tgt\n      (LSIM: forall x, _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt x) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (Choose X) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_rmwR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X rmw itr_src ktr_tgt\n      (LSIM: _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt (snd (rmw st_tgt) : X)) (ths, im_src, im_tgt, st_src, fst (rmw st_tgt)))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (Rmw rmw) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_tidR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src ktr_tgt\n      (LSIM: _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt tid) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (GetTid) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_fairR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt0 st_src st_tgt\n      f itr_src ktr_tgt\n      (LSIM: forall im_tgt1\n                   (FAIR: fair_update im_tgt0 im_tgt1 (prism_fmap inrp f)),\n          (<<LSIM: _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt tt) (ths, im_src, im_tgt1, st_src, st_tgt)>>))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (Fair f) >>= ktr_tgt) (ths, im_src, im_tgt0, st_src, st_tgt)\n\n  | lsim_observe\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src ktr_tgt\n      (LSIM: forall ret,\n          _lsim _ _ RR true true r_ctx (ktr_src ret) (ktr_tgt ret) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Observe fn args) >>= ktr_src) (trigger (Observe fn args) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_call\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src itr_tgt\n    : __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Call fn args) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_yieldL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src tt) (trigger (Yield) >>= itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_yieldR\n      f_src f_tgt r_ctx0\n      ths0 im_src0 im_tgt0 st_src0 st_tgt0\n      r_own r_shared\n      ktr_src ktr_tgt\n      (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared)\n      (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx0))\n      (LSIM: forall ths1 im_src1 im_tgt1 st_src1 st_tgt1 r_shared1 r_ctx1\n                    (INV: I (ths1, im_src1, im_tgt1, st_src1, st_tgt1) r_shared1)\n                    (VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx1))\n                    im_tgt2\n                    (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths1))),\n          _lsim _ _ RR f_src true r_ctx1 (trigger (Yield) >>= ktr_src) (ktr_tgt tt) (ths1, im_src1, im_tgt2, st_src1, st_tgt1))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx0 (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n  | lsim_sync\n      f_src f_tgt r_ctx0\n      ths0 im_src0 im_tgt0 st_src0 st_tgt0\n      r_own r_shared\n      ktr_src ktr_tgt\n      (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared)\n      (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx0))\n      (LSIM: forall ths1 im_src1 im_tgt1 st_src1 st_tgt1 r_shared1 r_ctx1\n               (INV: I (ths1, im_src1, im_tgt1, st_src1, st_tgt1) r_shared1)\n               (VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx1))\n               im_tgt2\n               (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths1))),\n          (<<LSIM: _lsim _ _ RR true true r_ctx1 (ktr_src tt) (ktr_tgt tt) (ths1, im_src1, im_tgt2, st_src1, st_tgt1)>>))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx0 (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n\n  | lsim_progress\n      r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: lsim _ _ RR false false r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR true true r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  .\n\n  Definition lsim (tid: thread_id)\n             R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel):\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n    paco9 (fun r => pind9 (__lsim tid r) top9) bot9 R_src R_tgt RR.\n\n  Lemma __lsim_mon tid:\n    forall r r' (LE: r <9= r'), (__lsim tid r) <10= (__lsim tid r').\n  Proof.\n    ii. inv PR; try (econs; eauto; fail).\n  Qed.\n\n  Lemma _lsim_mon tid: forall r, monotone9 (__lsim tid r).\n  Proof.\n    ii. inv IN; try (econs; eauto; fail).\n    { des. econs; eauto. }\n    { des. econs; eauto. }\n    { econs. i. eapply LE. eapply LSIM. eauto. }\n    { eapply lsim_sync; eauto. i. eapply LE. eapply LSIM; eauto. }\n  Qed.\n\n  Lemma lsim_mon tid: forall q, monotone9 (fun r => pind9 (__lsim tid r) q).\n  Proof.\n    ii. eapply pind9_mon_gen; eauto.\n    ii. eapply __lsim_mon; eauto.\n  Qed.\n\n  Local Hint Constructors __lsim: core.\n  Local Hint Unfold lsim: core.\n  Local Hint Resolve __lsim_mon: paco.\n  Local Hint Resolve _lsim_mon: paco.\n  Local Hint Resolve lsim_mon: paco.\n\n  Lemma modsim_implies_gensim\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        ps pt r_ctx src tgt\n        (shr: shared)\n        (LSIM: ModSim.lsim I tid RR ps pt r_ctx src tgt shr)\n    :\n    lsim tid RR ps pt r_ctx src tgt shr.\n  Proof.\n    revert_until tid. pcofix CIH; i.\n    punfold LSIM.\n    pattern R0, R1, RR, ps, pt, r_ctx, src, tgt, shr.\n    revert R0 R1 RR ps pt r_ctx src tgt shr LSIM. apply pind9_acc.\n    intros rr DEC IH. clear DEC. intros R0 R1 RR ps pt r_ctx src tgt shr LSIM.\n    eapply pind9_unfold in LSIM.\n    2:{ eapply ModSim._lsim_mon. }\n    inv LSIM.\n\n    { pfold. eapply pind9_fold. eapply lsim_ret; eauto. }\n    { pfold. eapply pind9_fold. eapply lsim_tauL; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND.\n    }\n    { pfold. eapply pind9_fold. eapply lsim_chooseL; eauto.\n      des. exists x.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND.\n    }\n    { pfold. eapply pind9_fold. eapply lsim_rmwL; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND.\n    }\n    { pfold. eapply pind9_fold. eapply lsim_tidL; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND.\n    }\n    { pfold. eapply pind9_fold. eapply lsim_UB; eauto. }\n    { pfold. eapply pind9_fold. eapply lsim_fairL; eauto.\n      des. esplits; eauto.\n      split; ss. destruct LSIM as [LSIM IND]. eapply IH in IND. punfold IND.\n    }\n    { pfold. eapply pind9_fold. eapply lsim_tauR; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND.\n    }\n    { pfold. eapply pind9_fold. eapply lsim_chooseR; eauto.\n      i. specialize (LSIM0 x).\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND.\n    }\n    { pfold. eapply pind9_fold. eapply lsim_rmwR; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND.\n    }\n    { pfold. eapply pind9_fold. eapply lsim_tidR; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND.\n    }\n    { pfold. eapply pind9_fold. eapply lsim_fairR; eauto.\n      i. specialize (LSIM0 _ FAIR).\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_observe; eauto.\n      i. specialize (LSIM0 ret). pclearbot.\n      split; ss. eapply pind9_fold. eapply lsim_progress.\n      right. eapply CIH; eauto. eapply ModSim.lsim_set_prog. auto.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_call. }\n\n    { pfold. eapply pind9_fold. eapply lsim_yieldL.\n      des. esplits; eauto.\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_yieldR; eauto.\n      i. specialize (LSIM0 _ _ _ _ _ _ _ INV0 VALID0 _ TGT).\n      split; ss. destruct LSIM0 as [LSIM IND]. eapply IH in IND. punfold IND.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_sync; eauto.\n      i. specialize (LSIM0 _ _ _ _ _ _ _ INV0 VALID0 _ TGT).\n      split; ss. eapply pind9_fold. eapply lsim_progress. pclearbot.\n      right. eapply CIH. apply ModSim.lsim_set_prog; auto.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_progress. right.\n      eapply CIH. pclearbot. auto.\n    }\n\n  Qed.\n\nEnd PRIMIVIESIM.\n#[export] Hint Constructors __lsim: core.\n#[export] Hint Unfold lsim: core.\n#[export] Hint Resolve __lsim_mon: paco.\n#[export] Hint Resolve _lsim_mon: paco.\n#[export] Hint Resolve lsim_mon: paco.\n\nSection GENORDER.\n  Context `{M: URA.t}.\n\n  Variable state_src: Type.\n  Variable state_tgt: Type.\n\n  Variable ident_src: ID.\n  Variable _ident_tgt: ID.\n  Let ident_tgt := @ident_tgt _ident_tgt.\n\n  Variable wf_src: WF.\n  Variable wf_tgt: WF.\n\n  Let srcE := programE ident_src state_src.\n  Let tgtE := programE _ident_tgt state_tgt.\n\n  Let shared := shared state_src state_tgt ident_src _ident_tgt wf_src wf_tgt.\n  Let shared_rel: Type := shared -> Prop.\n  Variable I: shared -> URA.car -> Prop.\n\n  Let A R0 R1 := (bool * bool * URA.car * (itree srcE R0) * (itree tgtE R1) * shared)%type.\n  Let wf_stt R0 R1 := @ord_tree_WF (A R0 R1).\n\n  Variant _genos\n          (tid: thread_id)\n          (genos: forall R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel), bool -> bool -> URA.car -> ((wf_stt R0 R1).(T) * itree srcE R0) -> ((wf_stt R0 R1).(T) * itree tgtE R1) -> shared_rel)\n          R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> ((wf_stt R0 R1).(T) * itree srcE R0) -> ((wf_stt R0 R1).(T) * itree tgtE R1) -> shared_rel :=\n  | genos_ret\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      r_src r_tgt\n      (GENOS: RR r_src r_tgt r_ctx (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, Ret r_src) (ot, Ret r_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | genos_tauL\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (GENOS: genos _ _ RR true f_tgt r_ctx (os, itr_src) (ot, itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, Tau itr_src) (ot, itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | genos_chooseL\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      X ktr_src itr_tgt\n      (GENOS: exists x, genos _ _ RR true f_tgt r_ctx (os, ktr_src x) (ot, itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, trigger (Choose X) >>= ktr_src) (ot, itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | genos_rmwL\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      X rmw ktr_src itr_tgt\n      (GENOS: genos _ _ RR true f_tgt r_ctx (os, ktr_src (snd (rmw st_src) : X)) (ot, itr_tgt) (ths, im_src, im_tgt, fst (rmw st_src), st_tgt))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, trigger (Rmw rmw) >>= ktr_src) (ot, itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | genos_tidL\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (GENOS: genos _ _ RR true f_tgt r_ctx (os, ktr_src tid) (ot, itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, trigger (GetTid) >>= ktr_src) (ot, itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | genos_UB\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, trigger (Undefined) >>= ktr_src) (ot, itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | genos_fairL\n      f_src f_tgt r_ctx os ot\n      ths im_src0 im_tgt st_src st_tgt\n      f ktr_src itr_tgt\n      (GENOS: exists im_src1,\n          (<<FAIR: fair_update im_src0 im_src1 f>>) /\\\n            (<<GENOS: genos _ _ RR true f_tgt r_ctx (os, ktr_src tt) (ot, itr_tgt) (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, trigger (Fair f) >>= ktr_src) (ot, itr_tgt) (ths, im_src0, im_tgt, st_src, st_tgt)\n\n  | genos_tauR\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (GENOS: genos _ _ RR f_src true r_ctx (os, itr_src) (ot, itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, itr_src) (ot, Tau itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | genos_chooseR\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      X itr_src ktr_tgt\n      (GENOS: forall x, genos _ _ RR f_src true r_ctx (os, itr_src) (ot, ktr_tgt x) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, itr_src) (ot, trigger (Choose X) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | genos_rmwR\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      X rmw itr_src ktr_tgt\n      (GENOS: genos _ _ RR f_src true r_ctx (os, itr_src) (ot, ktr_tgt (snd (rmw st_tgt) : X)) (ths, im_src, im_tgt, st_src, fst (rmw st_tgt)))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, itr_src) (ot, trigger (Rmw rmw) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | genos_tidR\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      itr_src ktr_tgt\n      (GENOS: genos _ _ RR f_src true r_ctx (os, itr_src) (ot, ktr_tgt tid) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, itr_src) (ot, trigger (GetTid) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | genos_fairR\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt0 st_src st_tgt\n      f itr_src ktr_tgt\n      (GENOS: forall im_tgt1 (FAIR: fair_update im_tgt0 im_tgt1 (prism_fmap inrp f)),\n          (<<GENOS: genos _ _ RR f_src true r_ctx (os, itr_src) (ot, ktr_tgt tt) (ths, im_src, im_tgt1, st_src, st_tgt)>>))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, itr_src) (ot, trigger (Fair f) >>= ktr_tgt) (ths, im_src, im_tgt0, st_src, st_tgt)\n\n  | genos_observe\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src ktr_tgt\n      (GENOS: forall ret,\n          genos _ _ RR true true r_ctx (os, ktr_src ret) (ot, ktr_tgt ret) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, trigger (Observe fn args) >>= ktr_src) (ot, trigger (Observe fn args) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | genos_call\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src itr_tgt\n    : _genos tid genos RR f_src f_tgt r_ctx (os, trigger (Call fn args) >>= ktr_src) (ot, itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | genos_yieldL\n      f_src f_tgt r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (GENOS: exists os1 ot1,\n          (<<GENOS: genos _ _ RR true f_tgt r_ctx (os1, ktr_src tt) (ot1, trigger (Yield) >>= itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)>>) /\\\n            (<<LT: (wf_stt R0 R1).(lt) os1 os>>))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx (os, trigger (Yield) >>= ktr_src) (ot, trigger (Yield) >>= itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | genos_yieldR\n      f_src f_tgt r_ctx0 os ot\n      ths0 im_src0 im_tgt0 st_src0 st_tgt0\n      r_own r_shared\n      ktr_src ktr_tgt\n      (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared)\n      (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx0))\n      (GENOS: forall ths1 im_src1 im_tgt1 st_src1 st_tgt1 r_shared1 r_ctx1\n               (INV: I (ths1, im_src1, im_tgt1, st_src1, st_tgt1) r_shared1)\n               (VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx1))\n               im_tgt2\n               (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths1))),\n        exists os1 ot1,\n          (<<GENOS: genos _ _ RR f_src true r_ctx1 (os1, trigger (Yield) >>= ktr_src) (ot1, ktr_tgt tt) (ths1, im_src1, im_tgt2, st_src1, st_tgt1)>>) /\\\n            (<<LT: (wf_stt R0 R1).(lt) ot1 ot>>))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx0 (os, trigger (Yield) >>= ktr_src) (ot, trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n  | genos_sync\n      f_src f_tgt r_ctx0 os ot\n      ths0 im_src0 im_tgt0 st_src0 st_tgt0\n      r_own r_shared\n      ktr_src ktr_tgt\n      (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared)\n      (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx0))\n      (GENOS: forall ths1 im_src1 im_tgt1 st_src1 st_tgt1 r_shared1 r_ctx1\n               (INV: I (ths1, im_src1, im_tgt1, st_src1, st_tgt1) r_shared1)\n               (VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx1))\n               im_tgt2\n               (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths1))),\n        exists os1 ot1,\n          (<<GENOS: genos _ _ RR true true r_ctx1 (os1, ktr_src tt) (ot1, ktr_tgt tt) (ths1, im_src1, im_tgt2, st_src1, st_tgt1)>>))\n    :\n    _genos tid genos RR f_src f_tgt r_ctx0 (os, trigger (Yield) >>= ktr_src) (ot, trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n\n  | genos_progress\n      r_ctx os ot\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (GENOS: lsim I tid RR false false r_ctx (itr_src) (itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    _genos tid genos RR true true r_ctx (os, itr_src) (ot, itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  .\n\n  Definition genos (tid: thread_id)\n             R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel):\n    bool -> bool -> URA.car -> ((wf_stt R0 R1).(T) * itree srcE R0) -> ((wf_stt R0 R1).(T) * itree tgtE R1) -> shared_rel :=\n    pind9 (_genos tid) top9 R0 R1 RR.\n\n  Lemma genos_mon tid: monotone9 (_genos tid).\n  Proof.\n    ii. inv IN; try (econs; eauto; fail).\n    { des. econs; eauto. }\n    { des. econs; eauto. }\n    { econs. i. eapply LE. eapply GENOS. eauto. }\n    { des. econs; eauto. esplits; eauto. }\n    { eapply genos_yieldR; eauto. i. hexploit GENOS; eauto. i. des. esplits; eauto. }\n    { eapply genos_sync; eauto. i. hexploit GENOS; eauto. i. des. esplits; eauto. }\n  Qed.\n\n  Local Hint Constructors _genos: core.\n  Local Hint Unfold genos: core.\n  Local Hint Resolve genos_mon: paco.\n\n\n  Lemma genos_ord_weakL\n        tid R0 R1 (LRR: R0 -> R1 -> URA.car -> shared_rel)\n        ps pt r_ctx src tgt (shr: shared)\n        os0 os1\n        (LT: (wf_stt R0 R1).(lt) os0 os1)\n        (GENOS: genos tid LRR ps pt r_ctx (os0, src) tgt shr)\n    :\n    genos tid LRR ps pt r_ctx (os1, src) tgt shr.\n  Proof.\n    remember (os0, src) as osrc.\n    move GENOS before tid. revert_until GENOS.\n    pattern R0, R1, LRR, ps, pt, r_ctx, osrc, tgt, shr.\n    revert R0 R1 LRR ps pt r_ctx osrc tgt shr GENOS. apply pind9_acc.\n    intros rr DEC IH. clear DEC. intros R0 R1 LRR ps pt r_ctx osrc tgt shr GENOS.\n    i; clarify.\n    eapply pind9_unfold in GENOS; eauto with paco.\n    inv GENOS.\n\n    { eapply pind9_fold. eapply genos_ret; eauto. }\n    { eapply pind9_fold. eapply genos_tauL; eauto.\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_chooseL; eauto.\n      des. destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. esplits; eauto.\n      split; ss; eauto.\n    }\n    { eapply pind9_fold. eapply genos_rmwL; eauto.\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_tidL; eauto.\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_UB; eauto. }\n    { eapply pind9_fold. eapply genos_fairL; eauto.\n      des. destruct GENOS as [GENOS IND]. eapply IH in IND; eauto. esplits; eauto.\n      split; ss; eauto.\n    }\n\n    { eapply pind9_fold. eapply genos_tauR; eauto.\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_chooseR; eauto.\n      i. specialize (GENOS0 x).\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_rmwR; eauto.\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_tidR; eauto.\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_fairR; eauto.\n      i. specialize (GENOS0 _ FAIR).\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_observe; eauto.\n      i. specialize (GENOS0 ret).\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n\n    { eapply pind9_fold. eapply genos_call; eauto. }\n\n    { eapply pind9_fold. eapply genos_yieldL; eauto.\n      des. destruct GENOS as [GENOS IND]. eapply IH in IND; eauto.\n      esplits. split; ss. eapply IND. auto.\n    }\n\n    { eapply pind9_fold. eapply genos_yieldR; eauto.\n      i. specialize (GENOS0 _ _ _ _ _ _ _ INV0 VALID0 _ TGT). des. esplits; eauto.\n      eapply upind9_mon; eauto. ss.\n    }\n\n    { eapply pind9_fold. eapply genos_sync; eauto.\n      i. specialize (GENOS0 _ _ _ _ _ _ _ INV0 VALID0 _ TGT). des. esplits; eauto.\n      eapply upind9_mon; eauto. ss.\n    }\n\n    { eapply pind9_fold. eapply genos_progress; eauto. }\n\n  Qed.\n\n  Lemma genos_ord_weakR\n        tid R0 R1 (LRR: R0 -> R1 -> URA.car -> shared_rel)\n        ps pt r_ctx src tgt (shr: shared)\n        ot0 ot1\n        (LT: (wf_stt R0 R1).(lt) ot0 ot1)\n        (GENOS: genos tid LRR ps pt r_ctx src (ot0, tgt) shr)\n    :\n    genos tid LRR ps pt r_ctx src (ot1, tgt) shr.\n  Proof.\n    remember (ot0, tgt) as otgt.\n    move GENOS before tid. revert_until GENOS.\n    pattern R0, R1, LRR, ps, pt, r_ctx, src, otgt, shr.\n    revert R0 R1 LRR ps pt r_ctx src otgt shr GENOS. apply pind9_acc.\n    intros rr DEC IH. clear DEC. intros R0 R1 LRR ps pt r_ctx src otgt shr GENOS.\n    i; clarify.\n    eapply pind9_unfold in GENOS; eauto with paco.\n    inv GENOS.\n\n    { eapply pind9_fold. eapply genos_ret; eauto. }\n    { eapply pind9_fold. eapply genos_tauL; eauto.\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_chooseL; eauto.\n      des. destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. esplits; eauto.\n      split; ss; eauto.\n    }\n    { eapply pind9_fold. eapply genos_rmwL; eauto.\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_tidL; eauto.\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_UB; eauto. }\n    { eapply pind9_fold. eapply genos_fairL; eauto.\n      des. destruct GENOS as [GENOS IND]. eapply IH in IND; eauto. esplits; eauto.\n      split; ss; eauto.\n    }\n\n    { eapply pind9_fold. eapply genos_tauR; eauto.\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_chooseR; eauto.\n      i. specialize (GENOS0 x).\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_rmwR; eauto.\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_tidR; eauto.\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_fairR; eauto.\n      i. specialize (GENOS0 _ FAIR).\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n    { eapply pind9_fold. eapply genos_observe; eauto.\n      i. specialize (GENOS0 ret).\n      destruct GENOS0 as [GENOS IND]. eapply IH in IND; eauto. split; ss.\n    }\n\n    { eapply pind9_fold. eapply genos_call; eauto. }\n\n    { eapply pind9_fold. eapply genos_yieldL; eauto.\n      des. esplits; eauto.\n      eapply upind9_mon; eauto. ss.\n    }\n\n    { eapply pind9_fold. eapply genos_yieldR; eauto.\n      i. specialize (GENOS0 _ _ _ _ _ _ _ INV0 VALID0 _ TGT). des.\n      destruct GENOS as [GENOS IND]. eapply IH in IND; eauto.\n      esplits; eauto. split; ss. eauto.\n    }\n\n    { eapply pind9_fold. eapply genos_sync; eauto.\n      i. specialize (GENOS0 _ _ _ _ _ _ _ INV0 VALID0 _ TGT). des. esplits; eauto.\n      eapply upind9_mon; eauto. ss.\n    }\n\n    { eapply pind9_fold. eapply genos_progress; eauto. }\n\n  Qed.\n\n  Lemma gensim_genos\n        tid R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        ps pt r_ctx src tgt shr\n        (LSIM: lsim I tid RR ps pt r_ctx src tgt shr)\n    :\n    exists os ot, genos tid RR ps pt r_ctx (os, src) (ot, tgt) shr.\n  Proof.\n    punfold LSIM.\n    pattern R0, R1, RR, ps, pt, r_ctx, src, tgt, shr.\n    revert R0 R1 RR ps pt r_ctx src tgt shr LSIM. apply pind9_acc.\n    intros rr DEC IH. clear DEC. intros R0 R1 RR ps pt r_ctx src tgt shr LSIM.\n    eapply pind9_unfold in LSIM; eauto with paco.\n    set (zero:= @ord_tree_base (A R0 R1)). set (fzero:= fun _: (A R0 R1) => zero). set (one:= ord_tree_cons fzero).\n    inv LSIM.\n\n    { exists zero, zero. eapply pind9_fold. eapply genos_ret; eauto. }\n\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      exists os, ot. eapply pind9_fold. eapply genos_tauL; eauto. split; ss.\n    }\n    { des. destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      exists os, ot. eapply pind9_fold. eapply genos_chooseL; eauto. eexists. split; ss. eauto.\n    }\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      exists os, ot. eapply pind9_fold. eapply genos_rmwL; eauto. split; ss.\n    }\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      exists os, ot. eapply pind9_fold. eapply genos_tidL; auto. split; ss.\n    }\n    { exists zero, zero. eapply pind9_fold. eapply genos_UB; eauto. }\n    { des. destruct LSIM as [LSIM IND]. eapply IH in IND. des.\n      exists os, ot. eapply pind9_fold. eapply genos_fairL; eauto. esplits; eauto. split; ss.\n    }\n\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des. exists os, ot.\n      eapply pind9_fold. eapply genos_tauR; eauto. ss.\n    }\n\n    { hexploit ord_tree_join.\n      { instantiate (2:=A R0 R1).\n        instantiate (2:= fun '(ps, pt, rs, src, tgt, shr) => @rr R0 R1 RR ps pt rs src tgt shr).\n        i. ss. des_ifs. eapply IH in SAT.\n        instantiate (1:= fun '(ps, pt, rs, src, tgt, shr) o =>\n                           exists ot, genos tid RR ps pt rs (o, src) (ot, tgt) shr).\n        eauto.\n      }\n      intro JOIN1. des. exists o1.\n      hexploit ord_tree_join.\n      { instantiate (2:=A R0 R1).\n        instantiate (2:= fun '(ps, pt, rs, src, tgt, shr) => @rr R0 R1 RR ps pt rs src tgt shr).\n        i. ss. des_ifs.\n        specialize (JOIN1 (b, b0, c, i0, i, s)). destruct JOIN1; auto. des.\n        instantiate (1:= fun '(ps, pt, rs, src, tgt, shr) o =>\n                           genos tid RR ps pt rs (o1, src) (o, tgt) shr).\n        exists ot. eapply genos_ord_weakL; eauto.\n      }\n      intro JOIN2. des. exists o0.\n      eapply pind9_fold. eapply genos_chooseR.\n      i. specialize (LSIM0 x). destruct LSIM0 as [LSIM IND].\n      specialize (JOIN1 (ps, true, r_ctx, src, (ktr_tgt x), (ths, im_src, im_tgt, st_src, st_tgt))).\n      destruct JOIN1; auto. des.\n      specialize (JOIN2 (ps, true, r_ctx, src, (ktr_tgt x), (ths, im_src, im_tgt, st_src, st_tgt))).\n      destruct JOIN2; auto. des.\n      split; ss.\n      eapply genos_ord_weakR; eauto.\n    }\n\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des. exists os, ot.\n      eapply pind9_fold. eapply genos_rmwR; eauto. ss.\n    }\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des. exists os, ot.\n      eapply pind9_fold. eapply genos_tidR; eauto. ss.\n    }\n\n    { hexploit ord_tree_join.\n      { instantiate (2:=A R0 R1).\n        instantiate (2:= fun '(ps, pt, rs, src, tgt, shr) => @rr R0 R1 RR ps pt rs src tgt shr).\n        i. ss. des_ifs. eapply IH in SAT.\n        instantiate (1:= fun '(ps, pt, rs, src, tgt, shr) o =>\n                           exists ot, genos tid RR ps pt rs (o, src) (ot, tgt) shr).\n        eauto.\n      }\n      intro JOIN1. des. exists o1.\n      hexploit ord_tree_join.\n      { instantiate (2:=A R0 R1).\n        instantiate (2:= fun '(ps, pt, rs, src, tgt, shr) => @rr R0 R1 RR ps pt rs src tgt shr).\n        i. ss. des_ifs.\n        specialize (JOIN1 (b, b0, c, i0, i, s)). destruct JOIN1; auto. des.\n        instantiate (1:= fun '(ps, pt, rs, src, tgt, shr) o =>\n                           genos tid RR ps pt rs (o1, src) (o, tgt) shr).\n        exists ot. eapply genos_ord_weakL; eauto.\n      }\n      intro JOIN2. des. exists o0.\n      eapply pind9_fold. eapply genos_fairR.\n      i. specialize (LSIM0 _ FAIR). destruct LSIM0 as [LSIM IND].\n      specialize (JOIN1 (ps, true, r_ctx, src, (ktr_tgt tt), (ths, im_src, im_tgt1, st_src, st_tgt))).\n      destruct JOIN1; auto. des.\n      specialize (JOIN2 (ps, true, r_ctx, src, (ktr_tgt tt), (ths, im_src, im_tgt1, st_src, st_tgt))).\n      destruct JOIN2; auto. des.\n      split; ss.\n      eapply genos_ord_weakR; eauto.\n    }\n\n    { hexploit ord_tree_join.\n      { instantiate (2:=A R0 R1).\n        instantiate (2:= fun '(ps, pt, rs, src, tgt, shr) => @rr R0 R1 RR ps pt rs src tgt shr).\n        i. ss. des_ifs. eapply IH in SAT.\n        instantiate (1:= fun '(ps, pt, rs, src, tgt, shr) o =>\n                           exists ot, genos tid RR ps pt rs (o, src) (ot, tgt) shr).\n        eauto.\n      }\n      intro JOIN1. des. exists o1.\n      hexploit ord_tree_join.\n      { instantiate (2:=A R0 R1).\n        instantiate (2:= fun '(ps, pt, rs, src, tgt, shr) => @rr R0 R1 RR ps pt rs src tgt shr).\n        i. ss. des_ifs.\n        specialize (JOIN1 (b, b0, c, i0, i, s)). destruct JOIN1; auto. des.\n        instantiate (1:= fun '(ps, pt, rs, src, tgt, shr) o =>\n                           genos tid RR ps pt rs (o1, src) (o, tgt) shr).\n        exists ot. eapply genos_ord_weakL; eauto.\n      }\n      intro JOIN2. des. exists o0.\n      eapply pind9_fold. eapply genos_observe.\n      i. specialize (LSIM0 ret). destruct LSIM0 as [LSIM IND].\n      specialize (JOIN1 (true, true, r_ctx, (ktr_src ret), (ktr_tgt ret), (ths, im_src, im_tgt, st_src, st_tgt))).\n      destruct JOIN1; auto. des.\n      specialize (JOIN2 (true, true, r_ctx, (ktr_src ret), (ktr_tgt ret), (ths, im_src, im_tgt, st_src, st_tgt))).\n      destruct JOIN2; auto. des.\n      split; ss.\n      eapply genos_ord_weakR; eauto.\n    }\n\n    { hexploit ord_tree_join.\n      { instantiate (2:=A R0 R1).\n        instantiate (2:= fun '(ps, pt, rs, src, tgt, shr) => @rr R0 R1 RR ps pt rs src tgt shr).\n        i. ss. des_ifs. eapply IH in SAT.\n        instantiate (1:= fun '(ps, pt, rs, src, tgt, shr) o =>\n                           exists ot, genos tid RR ps pt rs (o, src) (ot, tgt) shr).\n        eauto.\n      }\n      intro JOIN1. des. exists o1.\n      hexploit ord_tree_join.\n      { instantiate (2:=A R0 R1).\n        instantiate (2:= fun '(ps, pt, rs, src, tgt, shr) => @rr R0 R1 RR ps pt rs src tgt shr).\n        i. ss. des_ifs.\n        specialize (JOIN1 (b, b0, c, i0, i, s)). destruct JOIN1; auto. des.\n        instantiate (1:= fun '(ps, pt, rs, src, tgt, shr) o =>\n                           genos tid RR ps pt rs (o1, src) (o, tgt) shr).\n        exists ot. eapply genos_ord_weakL; eauto.\n      }\n      intro JOIN2. des. exists o0.\n      eapply pind9_fold. eapply genos_call.\n    }\n\n    { destruct LSIM0 as [LSIM IND]. eapply IH in IND. des.\n      set (fos:= fun _: (A R0 R1) => os). exists (ord_tree_cons fos), ot.\n      eapply pind9_fold. eapply genos_yieldL; eauto. esplits; eauto.\n      split; ss. eauto. ss.\n      replace os with (fos (true, pt, r_ctx, (ktr_src tt), (x <- trigger Yield;; itr_tgt x), (ths, im_src, im_tgt, st_src, st_tgt))); ss.\n    }\n\n    { hexploit ord_tree_join.\n      { instantiate (2:=A R0 R1).\n        instantiate (2:= fun '(ps, pt, rs, src, tgt, shr) => @rr R0 R1 RR ps pt rs src tgt shr).\n        i. ss. des_ifs. eapply IH in SAT.\n        instantiate (1:= fun '(ps, pt, rs, src, tgt, shr) o =>\n                           exists ot, genos tid RR ps pt rs (o, src) (ot, tgt) shr).\n        eauto.\n      }\n      intro JOIN1. des. exists o1.\n      hexploit ord_tree_join.\n      { instantiate (2:=A R0 R1).\n        instantiate (2:= fun '(ps, pt, rs, src, tgt, shr) => @rr R0 R1 RR ps pt rs src tgt shr).\n        i. ss. des_ifs.\n        specialize (JOIN1 (b, b0, c, i0, i, s)). destruct JOIN1; auto. des.\n        instantiate (1:= fun '(ps, pt, rs, src, tgt, shr) o =>\n                           genos tid RR ps pt rs (o1, src) (o, tgt) shr).\n        exists ot. eapply genos_ord_weakL; eauto.\n      }\n      intro JOIN2. des. exists o0.\n      eapply pind9_fold. eapply genos_yieldR. 1,2: eauto.\n      i. specialize (LSIM0 _ _ _ _ _ _ _ INV0 VALID0 _ TGT). destruct LSIM0 as [LSIM IND].\n      specialize (JOIN1 (ps, true, r_ctx1, (x <- trigger Yield;; ktr_src x), ktr_tgt tt, (ths1, im_src1, im_tgt2, st_src1, st_tgt1))).\n      destruct JOIN1; auto. des.\n      specialize (JOIN2 (ps, true, r_ctx1, (x <- trigger Yield;; ktr_src x), ktr_tgt tt, (ths1, im_src1, im_tgt2, st_src1, st_tgt1))).\n      destruct JOIN2; auto. des.\n      exists o1, x0. esplits; eauto.\n      split; ss.\n    }\n\n    { exists zero, zero. eapply pind9_fold. eapply genos_sync; eauto.\n      i. specialize (LSIM0 _ _ _ _ _ _ _ INV0 VALID0 _ TGT). destruct LSIM0 as [LSIM IND].\n      eapply IH in IND. des. do 2 eexists. split; ss. eapply IND.\n    }\n\n    { exists zero, zero. eapply pind9_fold. eapply genos_progress. pclearbot. auto. }\n\n  Qed.\n\nEnd GENORDER.\n#[export] Hint Constructors _genos: core.\n#[export] Hint Unfold genos: core.\n#[export] Hint Resolve genos_mon: paco.\n", "meta": {"author": "damhiya", "repo": "fairness", "sha": "279dcc679bd18b85666b97d6b540d94299c5d66e", "save_path": "github-repos/coq/damhiya-fairness", "path": "github-repos/coq/damhiya-fairness/fairness-279dcc679bd18b85666b97d6b540d94299c5d66e/src/simulation/GenYOrd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318194686359, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2460016014200844}}
{"text": "(* These always worked. *)\nGoal prod True True. firstorder. Qed.\nGoal True -> @sigT True (fun _ => True). firstorder. Qed.\nGoal prod True True. dtauto. Qed.\nGoal prod True True. tauto. Qed.\n\n(* These should work. *)\nGoal @sigT True (fun _ => True). dtauto. Qed.\n(* These should work, but don't *)\n(* Goal @sigT True (fun _ => True). firstorder. Qed. *)\n(* Goal @sigT True (fun _ => True). tauto. Qed. *)\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/opened/6393.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.24597395361641358}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\n\nRequire Export general_Q.\nRequire Export positive_fraction_encoding.\nRequire Import Merge_Order.\nRequire Import Wf_nat.\n\nDefinition top_more (a b c d : Z) :=\n  (c <= a)%Z /\\ (d < b)%Z \\/ (c < a)%Z /\\ (d <= b)%Z.\n\nLemma top_more_informative :\n forall a b c d : Z, {top_more a b c d} + {~ top_more a b c d}.\nProof.\n intros.\n case (quadro_leq_inf a b c d). \n intro.\n elim a0.\n intros. \n case (Z_le_lt_eq_dec c a H).\n intro. \n left.\n right.\n split.\n assumption.\n assumption.\n intro. \n case (Z_le_lt_eq_dec d b H0).\n intro.\n left.\n left.\n split.\n assumption.\n assumption.\n intro.\n right.  \n intro.\n case H1.\n intro.\n elim H2.\n intros.\n rewrite e0 in H4.\n apply (Zgt_irrefl b).\n Flip.\n intro.\n elim H2.\n intros.\n rewrite e in H3.\n apply (Zgt_irrefl a).\n Flip.\n\n unfold top_more in |- *. \n intro.\n right.\n intro.\n case H.\n intro. \n apply n.\n elim H0. \n intros.\n split.\n assumption.\n apply Zlt_le_weak. \n assumption.\n intro.\n apply n.\n elim H0. \n intros.\n split.\n apply Zlt_le_weak.\n assumption.\n assumption. \nDefined.\n\nLemma top_more_1 :\n forall a b c d : Z, top_more a b c d -> (0 < a - c + (b - d))%Z.\nProof.\n intros.\n case H.\n intros.\n elim H0.\n intros.\n replace 0%Z with (0 + 0)%Z.\n apply Zplus_le_lt_compat.\n unfold Zminus in |- *.\n apply Zle_left.\n assumption.\n apply Zlt_minus.\n assumption.    \n constructor.\n intro.\n elim H0.   \n intros.\n replace 0%Z with (0 + 0)%Z.\n apply Zplus_lt_le_compat.\n apply Zlt_minus.\n assumption.\n unfold Zminus in |- *.\n apply Zle_left.\n assumption.\n constructor.\nDefined.\n\nLemma top_more_2 : forall a b c d : Z, top_more a b c d -> (c + d < a + b)%Z.\nProof. \n intros.\n case H.\n intros.\n elim H0.\n intros.\n apply Zplus_le_lt_compat. \n assumption.\n assumption.\n intros.\n elim H0.\n intros.\n apply Zplus_lt_le_compat. \n assumption.\n assumption.\nDefined.\n\n\nLemma top_more_3 :\n forall a b c d : Z, (0 < c + d)%Z -> (a - c + (b - d) < a + b)%Z.\nProof.\n intros.\n apply Zplus_lt_reg_l with (c + d)%Z.\n apply Zplus_lt_reg_l with (- a - b)%Z.\n replace (- a - b + (c + d + (a - c + (b - d))))%Z with 0%Z.\n replace (- a - b + (c + d + (a + b)))%Z with (c + d)%Z.\n assumption.\n ring.\n ring.\nDefined.\n\nLemma top_more_4 : forall a b c d : Z, top_more a b c d -> (c <= a)%Z.\nProof. \n intros.\n case H.\n intros.\n elim H0.\n intros.\n assumption.\n intros.\n elim H0.\n intros.\n apply Zlt_le_weak.\n assumption.\nDefined.\n\nLemma top_more_4' : forall a b c d : Z, top_more a b c d -> (d <= b)%Z.\nProof. \n intros.\n case H.\n intros.\n elim H0.\n intros.\n apply Zlt_le_weak.\n assumption.\n intros.\n elim H0.\n intros.\n assumption.\nDefined.\n\nLemma top_more_5 :\n forall a b c d : Z,\n (0 < c + d)%Z -> (a - c + (b - d) + c + d < a + b + c + d)%Z.\nProof.\n intros.\n assert ((a - c + (b - d) + c + d)%Z = (a + b + 0)%Z).\n ring.\n rewrite H0.\n rewrite Zplus_assoc_reverse with (n := (a + b)%Z).\n apply Zplus_le_lt_compat.  \n apply Z.le_refl.\n assumption.\nDefined.\n\nLemma top_more_5' :\n forall a b c d : Z,\n (0 < a + b)%Z -> (a + b + (c - a) + (d - b) < a + b + c + d)%Z.\nProof.\n intros.\n assert ((a + b + (c - a) + (d - b))%Z = (0 + (c + d))%Z).\n ring.\n rewrite H0.\n rewrite Zplus_assoc_reverse with (n := (a + b)%Z).\n apply Zplus_lt_le_compat.  \n assumption.\n apply Z.le_refl.\nDefined.\n\n\n\nInductive homographicAcc : Z -> Z -> Z -> Z -> Qpositive -> Prop :=\n  | homographicacc0 :\n      forall (a b c d : Z) (p : Qpositive),\n      p = One -> (0 < a + b)%Z -> (0 < c + d)%Z -> homographicAcc a b c d p\n  | homographicacc1 :\n      forall (a b c d : Z) (p : Qpositive),\n      p <> One ->\n      top_more a b c d ->\n      homographicAcc (a - c)%Z (b - d)%Z c d p -> homographicAcc a b c d p\n  | homographicacc2 :\n      forall (a b c d : Z) (p : Qpositive),\n      p <> One ->\n      ~ top_more a b c d ->\n      top_more c d a b ->\n      homographicAcc a b (c - a)%Z (d - b)%Z p -> homographicAcc a b c d p\n  | homographicacc3 :\n      forall (a b c d : Z) (xs : Qpositive),\n      ~ top_more a b c d ->\n      ~ top_more c d a b ->\n      homographicAcc a (a + b)%Z c (c + d)%Z xs ->\n      homographicAcc a b c d (nR xs)\n  | homographicacc3' :\n      forall (a b c d : Z) (xs : Qpositive),\n      ~ top_more a b c d ->\n      ~ top_more c d a b ->\n      homographicAcc (a + b)%Z b (c + d)%Z d xs ->\n      homographicAcc a b c d (dL xs).\n\nLemma homographicacc_0_num :\n forall a b c d : Z, homographicAcc a b c d One -> (0 < a + b)%Z.\nProof.\n intros.\n abstract (inversion H; trivial; Irreflex; discriminate H0).\nDefined.\n\nLemma homographicacc_0_denom :\n forall a b c d : Z, homographicAcc a b c d One -> (0 < c + d)%Z.\nProof.\n intros.\n abstract (inversion H; trivial; Irreflex; discriminate H0).\nDefined.\n\n\nLemma homographicacc_1 :\n forall (a b c d : Z) (p : Qpositive),\n homographicAcc a b c d p ->\n p <> One -> top_more a b c d -> homographicAcc (a - c) (b - d) c d p.\nProof.\n simple destruct 1; intros; trivial; Falsum.\nDefined.  \n\nLemma homographicacc_2 :\n forall (a b c d : Z) (p : Qpositive),\n homographicAcc a b c d p ->\n p <> One ->\n ~ top_more a b c d ->\n top_more c d a b -> homographicAcc a b (c - a) (d - b) p.\nProof.\n simple destruct 1; intros; trivial; Falsum.\nDefined.  \n\nLemma homographicacc_3 :\n forall (a b c d : Z) (p : Qpositive),\n homographicAcc a b c d p ->\n forall xs : Qpositive,\n p = nR xs ->\n ~ top_more a b c d ->\n ~ top_more c d a b -> homographicAcc a (a + b) c (c + d) xs.\nProof.\n intros a b c d p HAcc; case HAcc; intros; try solve [ Falsum ];\n  [ rewrite H2 in H; clear H2; discriminate H\n  | let T_local := eval compute in (f_equal Qpositive_tail H2) in\n    (rewrite <- T_local; assumption)\n  | discriminate H2 ].\nDefined.  \n\nLemma homographicacc_3' :\n forall (a b c d : Z) (p : Qpositive),\n homographicAcc a b c d p ->\n forall xs : Qpositive,\n p = dL xs ->\n ~ top_more a b c d ->\n ~ top_more c d a b -> homographicAcc (a + b) b (c + d) d xs.\nProof.\n intros a b c d p HAcc xs.\n case HAcc; intros; try solve [ Falsum ];\n  [ rewrite H2 in H; clear H2; discriminate H\n  | discriminate H2\n  | let T_local := eval compute in (f_equal Qpositive_tail H2) in\n    (rewrite <- T_local; assumption) ].\nDefined.  \n\n\nFixpoint Qhomographic_Qpositive_to_Qpositive (a b c d : Z) \n (p : Qpositive) (hyp : homographicAcc a b c d p) {struct hyp} : Qpositive :=\n  match Qpositive_dec_One p with\n  | left H_p_is_One =>\n      let H :=\n        eq_ind p (fun p : Qpositive => homographicAcc a b c d p) hyp One\n          H_p_is_One in\n      (fun hyp0 : homographicAcc a b c d One =>\n       (fun (Hab : (0 < a + b)%Z) (Hcd : (0 < c + d)%Z) =>\n        positive_fraction_encoding (a + b) (c + d) Hab Hcd)\n         (homographicacc_0_num a b c d hyp0)\n         (homographicacc_0_denom a b c d hyp0)) H\n  | right H_p_not_One =>\n      match top_more_informative a b c d with\n      | left H_abcd =>\n          nR\n            (Qhomographic_Qpositive_to_Qpositive (a - c)%Z \n               (b - d)%Z c d p\n               (homographicacc_1 a b c d p hyp H_p_not_One H_abcd))\n      | right H_abcd =>\n          match top_more_informative c d a b with\n          | left H_cdab =>\n              dL\n                (Qhomographic_Qpositive_to_Qpositive a b \n                   (c - a)%Z (d - b)%Z p\n                   (homographicacc_2 a b c d p hyp H_p_not_One H_abcd H_cdab))\n          | right H_cdab =>\n              match p as q return (p = q -> Qpositive) with\n              | nR q =>\n                  fun H : p = nR q =>\n                  Qhomographic_Qpositive_to_Qpositive a \n                    (a + b)%Z c (c + d)%Z q\n                    (homographicacc_3 a b c d p hyp q H H_abcd H_cdab)\n              | dL q =>\n                  fun H : p = dL q =>\n                  Qhomographic_Qpositive_to_Qpositive \n                    (a + b)%Z b (c + d)%Z d q\n                    (homographicacc_3' a b c d p hyp q H H_abcd H_cdab)\n              | One =>\n                  fun q : p = One =>\n                  False_rec Qpositive (False_ind False (H_p_not_One q))\n              end (refl_equal p)\n          end\n      end\n  end.\n\n(** some sort of lexicographical order on binary lists *)\n\nFixpoint Qpositive_length (qp : Qpositive) : nat :=\n  match qp with\n  | One => 0\n  | dL qp1 => S (Qpositive_length qp1)\n  | nR qp1 => S (Qpositive_length qp1)\n  end.\n\n\nDefinition bin_lt (qp1 qp2 : Qpositive) : Prop :=\n  Qpositive_length qp1 < Qpositive_length qp2.\n\n\nDefinition bin_eq (x y : Qpositive) := x = y.\n\n(* We mention the following form only for the proof of the well-foundedness  *)\nLemma bin_lt_compat_via_length :\n forall x y : Qpositive,\n bin_lt x y -> Qpositive_length x < Qpositive_length y.\nProof.\n trivial.\nDefined.\n\nLemma compare_dL : forall x : Qpositive, bin_lt x (dL x). \nProof.\n unfold bin_lt in |- *.\n simpl in |- *.\n auto with arith.\nDefined.\n\nLemma compare_nR : forall x : Qpositive, bin_lt x (nR x). \nProof.\n unfold bin_lt in |- *.\n simpl in |- *.\n auto with arith.\nDefined.\n\n\n(** Definition of order for quadroples and a binary sequnce *)\n\n\nRecord Z_pos : Set :=  {zposcrr :> Z; z4prf_Z_pos : (0 <= zposcrr)%Z}.\n\n\nDefinition qlt (a b c d : Z) (p : Qpositive) (a' b' c' d' : Z)\n  (p' : Qpositive) : Prop :=\n  bin_lt p p' \\/ p = p' /\\ (a + b + c + d < a' + b' + c' + d')%Z. \n\nDefinition qle (a b c d : Z) (p : Qpositive) (a' b' c' d' : Z)\n  (p' : Qpositive) : Prop :=\n  qlt a b c d p a' b' c' d' p' \\/\n  a = a' /\\ b = b' /\\ c = c' /\\ d = d' /\\ p = p'. \n\nDefinition quadrointegral_lt (a b c d a' b' c' d' : Z) :=\n  (a + b + c + d < a' + b' + c' + d')%Z.\n\nDefinition quadrointegral_eq (a b c d a' b' c' d' : Z) :=\n  a = a' /\\ b = b' /\\ c = c' /\\ d = d'.\n\n\nRecord Z4 : Set := \n  {z4crr :> Z * Z * (Z * Z);\n   z4prf :\n    (0 <= fst (fst z4crr))%Z /\\\n    (0 <= snd (fst z4crr))%Z /\\\n    (0 <= fst (snd z4crr))%Z /\\ (0 <= snd (snd z4crr))%Z}.\n\n\nDefinition Z4_lt (x y : Z4) :=\n  let (V1, V2) := z4crr x in\n  let (V3, V4) := z4crr y in\n  let (a, b) := V1 in\n  let (c, d) := V2 in\n  let (a', b') := V3 in\n  let (c', d') := V4 in quadrointegral_lt a b c d a' b' c' d'.\n\n\nDefinition Z4_eq (x y : Z4) :=\n  let (V1, V2) := z4crr x in\n  let (V3, V4) := z4crr y in\n  let (a, b) := V1 in\n  let (c, d) := V2 in\n  let (a', b') := V3 in\n  let (c', d') := V4 in quadrointegral_eq a b c d a' b' c' d'.\n\n\nLemma Z4_lt_is_irreflexive : forall x : Z4, ~ Z4_lt x x.\nProof.\n intros (((a, b), (c, d)), z4prf0).\n unfold Z4_lt in |- *. \n unfold quadrointegral_lt in |- *.\n simpl in |- *.\n apply Z.lt_irrefl. \nDefined.\n\n\nLemma Z4_lt_is_transitive :\n forall x y z : Z4, Z4_lt x y -> Z4_lt y z -> Z4_lt x z.\nProof.\n intros (((a, b), (c, d)), z4prf0) (((a', b'), (c', d')), z4prf1)\n  (((a2, b2), (c2, d2)), z4prf2).\n unfold Z4_lt in |- *.\n unfold quadrointegral_lt in |- *.\n simpl in |- *.\n intros.\n apply Z.lt_trans with (a' + b' + c' + d')%Z; assumption.\nDefined.\n\n\nLemma Z4_lt_is_order : is_order Z4 Z4_lt.\nProof.\n split.\n apply Z4_lt_is_irreflexive.\n apply Z4_lt_is_transitive.\nDefined.\n\n\n\nLemma Z4_eq_is_reflexive : forall x : Z4, Z4_eq x x.\nProof.\n intros (((a, b), (c, d)), z4prf0).\n unfold Z4_eq in |- *. \n unfold quadrointegral_eq in |- *; repeat split. \nDefined.  \n\n\nLemma Z4_eq_is_symmetric : forall x y : Z4, Z4_eq x y -> Z4_eq y x.\nProof.\n intros (((a, b), (c, d)), z4prf0) (((a', b'), (c', d')), z4prf1).\n unfold Z4_eq in |- *.\n unfold quadrointegral_eq in |- *.\n intros (HH1, (HH2, (HH3, HH4))); repeat split; symmetry  in |- *; assumption.\nDefined.\n\nLemma Z4_eq_is_transitive :\n forall x y z : Z4, Z4_eq x y -> Z4_eq y z -> Z4_eq x z.\nProof.\n intros (((a, b), (c, d)), z4prf0) (((a', b'), (c', d')), z4prf1)\n  (((a2, b2), (c2, d2)), z4prf2).\n unfold Z4_eq in |- *.\n unfold quadrointegral_eq in |- *.\n simpl in |- *.\n intros (HH2, (HH4, (HH6, HH7))) (HH9, (HH11, (HH13, HH14))); repeat split;\n  match goal with\n  | id12:(?X1 = ?X2),id23:(?X2 = ?X3) |- (?X1 = ?X3) =>\n      try apply (trans_eq id12 id23)\n  end.\nDefined.\n\n\nLemma Z4_eq_is_equality : is_equality Z4 Z4_eq.\nProof.\n split.\n apply Z4_eq_is_reflexive.\n split.\n apply Z4_eq_is_symmetric.\n apply Z4_eq_is_transitive.\nDefined.\n\n\nLemma Z_pos_lt_is_wf :\n forall P : Z_pos -> Prop,\n (forall q : Z_pos, (forall r : Z_pos, (r < q)%Z -> P r) -> P q) ->\n forall q : Z_pos, P q.\nProof.\n intros.\n destruct q.\n rename zposcrr0 into q.\n set (P2 := fun p : Z => forall Hp : (0 <= p)%Z, P (Build_Z_pos p Hp)) in *. \n assert (P2 q).\n apply Zind_wf with (p := 0%Z).\n intros.\n unfold P2 in |- *. \n intro.\n apply H.\n intros.\n destruct r.\n rename zposcrr0 into r.\n assert (P2 r).\n apply H0.\n split.\n assumption.\n assumption.\n apply (H2 z4prf_Z_pos1).\n assumption.\n apply (H0 z4prf_Z_pos0).\nDefined. \n\n\nLemma Z4_lt_is_wf : wf_ind Z4 Z4_lt.\nProof.\n red in |- *.\n intros P H (((a, b), (c, d)), p); revert p;\n simpl in |- *.\n intros (Ha, (Hb, (Hc, Hd))).\n assert (H_a_b_c_d : (0 <= a + b + c + d)%Z); repeat apply Zplus_le_0_compat;\n  try assumption.\n (* Here Omega tactic would have worked as opposed to the similar situation below *)\n set\n  (P4 :=\n   fun k : Z_pos =>\n   forall (a b c d : Z)\n     (Habcd : (0 <= a)%Z /\\ (0 <= b)%Z /\\ (0 <= c)%Z /\\ (0 <= d)%Z)\n     (Hk : zposcrr k = (a + b + c + d)%Z), P (Build_Z4 (a, b, (c, d)) Habcd))\n  in *.\n assert (P4 (Build_Z_pos (a + b + c + d) H_a_b_c_d)).\n\n apply Z_pos_lt_is_wf.\n intros q_pos.\n red in |- *.\n intros.\n apply H.\n intros (((r_a, r_b), (r_c, r_d)), p); revert p.\n simpl in |- *.\n intros (H_r_a, (H_r_b, (H_r_c, H_r_d))).\n intro Hq.\n\n assert (H_r_a_b_c_d : (0 <= r_a + r_b + r_c + r_d)%Z);\n  repeat apply Zplus_le_0_compat; try assumption.\n (* Here Omega tactic does not work, as if we say \"Clear z4prf1\" and gives an error! *)\n assert (P4 (Build_Z_pos (r_a + r_b + r_c + r_d) H_r_a_b_c_d)).\n\n apply H0.\n rewrite Hk.\n simpl in |- *.\n assumption.\n\n apply H1.\n reflexivity.\n apply H0.\n reflexivity.\nDefined.\n\n\nLemma Z4_lt_is_well_def_rht : is_well_def_rht Z4 Z4_lt Z4_eq.\nProof.\n red in |- *.\n intros (((a, b), (c, d)), z4prf0) (((a', b'), (c', d')), z4prf1).\n intro H.\n intros (((a2, b2), (c2, d2)), z4prf2).\n generalize H.\n unfold Z4_lt in |- *.\n unfold Z4_eq in |- *. \n unfold quadrointegral_lt in |- *.\n unfold quadrointegral_eq in |- *.\n simpl in |- *.\n clear H z4prf0 z4prf1 z4prf2.\n intros H0 (H1, (H2, (H3, H4))).\n repeat\n  match goal with\n  | id:(?X1 = ?X2) |- _ => try rewrite id in H0; clear id\n  end.\n assumption.\nDefined.\n\n\nDefinition Z4_as_well_ordering :=\n  Build_well_ordering Z4 Z4_lt Z4_eq Z4_lt_is_order Z4_eq_is_equality\n    Z4_lt_is_wf Z4_lt_is_well_def_rht.\n\n\nLemma bin_lt_is_irreflexive : forall x : Qpositive, ~ bin_lt x x.\nProof.\n intros x.\n unfold bin_lt in |- *.\n apply lt_irrefl.\nDefined.\n\n\nLemma bin_lt_is_transitive :\n forall x y z : Qpositive, bin_lt x y -> bin_lt y z -> bin_lt x z.\nProof.\n intros x y z; unfold bin_lt in |- *.\n apply lt_trans.\nDefined.\n\nLemma bin_lt_is_order : is_order Qpositive bin_lt.\nProof.\n split.\n apply bin_lt_is_irreflexive.\n apply bin_lt_is_transitive.\nDefined.\n\n\nLemma bin_eq_is_reflexive : forall x : Qpositive, bin_eq x x.\nProof.\n intros.\n unfold bin_eq in |- *.\n reflexivity.\nDefined.  \n\n\nLemma bin_eq_is_symmetric : forall x y : Qpositive, bin_eq x y -> bin_eq y x.\nProof.\n intros x y.\n unfold bin_eq in |- *.\n apply sym_eq.\nDefined.\n\nLemma bin_eq_is_transitive :\n forall x y z : Qpositive, bin_eq x y -> bin_eq y z -> bin_eq x z.\nProof.\n intros x y z.\n unfold bin_eq in |- *.\n apply trans_eq.\nDefined.\n\n\n\nLemma bin_eq_is_equality : is_equality Qpositive bin_eq.\nProof.\n split.\n apply bin_eq_is_reflexive.\n split.\n apply bin_eq_is_symmetric.\n apply bin_eq_is_transitive.\nDefined.\n\n\nLemma bin_lt_is_wf : wf_ind Qpositive bin_lt.\nProof.\n generalize\n  (well_founded_lt_compat Qpositive Qpositive_length bin_lt\n     bin_lt_compat_via_length).\n intro H.\n exact (well_founded_ind H).\nDefined.\n\nLemma bin_lt_is_well_def_rht : is_well_def_rht Qpositive bin_lt bin_eq.\nProof.\n red in |- *.\n intros.\n red in H0.\n rewrite <- H0.\n assumption.\nDefined.\n\nDefinition Qpositive_as_well_ordering :=\n  Build_well_ordering Qpositive bin_lt bin_eq bin_lt_is_order\n    bin_eq_is_equality bin_lt_is_wf bin_lt_is_well_def_rht.\n\n\nLemma qlt_wf_rec_without_zeros_and_One :\n forall P : Z -> Z -> Z -> Z -> Qpositive -> Prop,\n (forall (a b c d : Z_pos) (p : Qpositive),\n  (forall (r s t u : Z_pos) (p1 : Qpositive),\n   qlt r s t u p1 a b c d p -> P r s t u p1) -> P a b c d p) ->\n forall (a b c d : Z_pos) (p : Qpositive), P a b c d p.\nProof.\n intros P H (a, Ha) (b, Hb) (c, Hc) (d, Hd) p.\n set\n  (P2 :=\n   fun (p_i : Qpositive) (x : Z4) =>\n   P (fst (fst x)) (snd (fst x)) (fst (snd x)) (snd (snd x)) p_i) \n  in *.\n simpl in |- *.\n\n assert (z4prf_Z4 : (0 <= a)%Z /\\ (0 <= b)%Z /\\ (0 <= c)%Z /\\ (0 <= d)%Z);\n  repeat split; try assumption.\n\n assert (P2 p (Build_Z4 (a, b, (c, d)) z4prf_Z4)).\n \n apply (merge_lt_wf Qpositive_as_well_ordering Z4_as_well_ordering).\n intro p_i.\n intros (((a_i, b_i), (c_i, d_i)), q); revert q.\n unfold P2 in |- *.\n simpl in |- *.\n intros (Ha_i, (Hb_i, (Hc_i, Hd_i))).\n intros.\n change\n   (P (Build_Z_pos a_i Ha_i) (Build_Z_pos b_i Hb_i) \n      (Build_Z_pos c_i Hc_i) (Build_Z_pos d_i Hd_i) p_i) \n  in |- *.\n apply H.\n intros (r_, r_p) (s_, s_p) (t_, t_p) (u_, u_p) p1.\n simpl in |- *.\n intro H1.\n assert\n  (z4prf2_Z4 : (0 <= r_)%Z /\\ (0 <= s_)%Z /\\ (0 <= t_)%Z /\\ (0 <= u_)%Z);\n  repeat split; try assumption.\n apply (H0 p1 (Build_Z4 (r_, s_, (t_, u_)) z4prf2_Z4)).\n case H1.\n intro.\n left.\n assumption.\n intros (H2, H3).\n right.\n split; assumption.\n assumption.\nDefined.\n\n\nLemma homographicAcc_wf :\n forall (a b c d : Z) (p : Qpositive),\n (0 < a + b)%Z ->\n (0 < c + d)%Z ->\n (0 <= a)%Z ->\n (0 <= b)%Z -> (0 <= c)%Z -> (0 <= d)%Z -> homographicAcc a b c d p.\nProof.\n intros a b c d p Hab Hcd Ha Hb Hc Hd.\n set (ha := Build_Z_pos a Ha) in *.\n set (hb := Build_Z_pos b Hb) in *.\n set (hc := Build_Z_pos c Hc) in *.\n set (hd := Build_Z_pos d Hd) in *.\n generalize Hab Hcd Ha Hb Hc Hd.\n change\n   ((0 < ha + hb)%Z ->\n    (0 < hc + hd)%Z ->\n    (0 <= ha)%Z ->\n    (0 <= hb)%Z -> (0 <= hc)%Z -> (0 <= hd)%Z -> homographicAcc ha hb hc hd p)\n  in |- *.\n\n\n apply\n  qlt_wf_rec_without_zeros_and_One\n   with\n     (P := fun (r s t u : Z) (p1 : Qpositive) =>\n           (0 < r + s)%Z ->\n           (0 < t + u)%Z ->\n           (0 <= r)%Z ->\n           (0 <= s)%Z ->\n           (0 <= t)%Z -> (0 <= u)%Z -> homographicAcc r s t u p1).\n                       \n intros a0 b0 c0 d0 p0 hyp1_aux.\n\n \n(* modifying hyp1_aux *)\n assert\n  (hyp1 :\n   forall (r s t u : Z) (p1 : Qpositive),\n   qlt r s t u p1 a0 b0 c0 d0 p0 ->\n   (0 < r + s)%Z ->\n   (0 < t + u)%Z ->\n   (0 <= r)%Z ->\n   (0 <= s)%Z -> (0 <= t)%Z -> (0 <= u)%Z -> homographicAcc r s t u p1).\n intros.\n change\n   (homographicAcc (Build_Z_pos r H2) (Build_Z_pos s H3) \n      (Build_Z_pos t H4) (Build_Z_pos u H5) p1) in |- *.\n apply hyp1_aux; repeat assumption.\n(* end modifying hyp1 *)\n\n\n\n destruct p0 as [q| q| ].\n\n (** p0 = (nR p0) *)\n  case (top_more_informative a0 b0 c0 d0).\n  (** (top_more a0 b0 c0 d0) *)\n   intros.\n   apply homographicacc1.\n   discriminate.\n   assumption.\n   apply hyp1.\n   right.\n   split.\n   reflexivity.\n   apply top_more_5.\n   assumption.\n   apply top_more_1.\n   assumption.\n   assumption.\n   apply Zle_minus.\n   apply (top_more_4 _ _ _ _ t).\n   apply Zle_minus.\n   apply (top_more_4' _ _ _ _ t).\n   assumption.\n   assumption.\n  (** ~(top_more a0 b0 c0 d0) *)\n   intro.\n   case (top_more_informative c0 d0 a0 b0).\n   (** (top_more c0 d0 a0 b0) *)\n    intros.\n    apply homographicacc2.\n    discriminate.\n    assumption.\n    assumption.\n    apply hyp1.\n    right.\n    split.\n    reflexivity.\n    apply top_more_5'.\n    assumption.\n    assumption.    \n    apply top_more_1.\n    assumption.\n    assumption.\n    assumption.   \n    apply Zle_minus.\n    apply (top_more_4 _ _ _ _ t).\n    apply Zle_minus.\n    apply (top_more_4' _ _ _ _ t).\n   (** ~(top_more c0 d0 a0 b0) *)\n    intros.\n    apply homographicacc3.\n    (* Discriminate. *)(**)\n    assumption.\n    assumption.\n    apply hyp1.\n\n    left.\n    unfold bin_lt in |- *.\n    apply compare_nR.    \n\n    replace 0%Z with (0 + 0)%Z.\n    apply Zplus_le_lt_compat.\n    assumption.\n    assumption.\n    constructor.\n    replace 0%Z with (0 + 0)%Z.\n    apply Zplus_le_lt_compat.\n    assumption.\n    assumption.\n    constructor.\n    assumption.\n    apply Zlt_le_weak.\n    assumption.\n    assumption.\n    apply Zlt_le_weak.\n    assumption.\n (** p0 = (dL p0) *)\n  case (top_more_informative a0 b0 c0 d0).\n  (** (top_more a0 b0 c0 d0) *)\n   intros.\n   apply homographicacc1.\n   discriminate.\n   assumption.\n   apply hyp1.\n   right.\n\n   split.\n   reflexivity.\n\n\n   apply top_more_5.\n   assumption.\n\n   apply top_more_1.\n   assumption.\n   assumption.\n   apply Zle_minus.\n   apply (top_more_4 _ _ _ _ t).\n   apply Zle_minus.\n   apply (top_more_4' _ _ _ _ t).\n   assumption.\n   assumption.\n  (** ~(top_more a0 b0 c0 d0) *)\n   intro.\n   case (top_more_informative c0 d0 a0 b0).\n   (** (top_more c0 d0 a0 b0) *)\n    intros.\n    apply homographicacc2.\n    discriminate.\n    assumption.\n    assumption.\n    apply hyp1.\n    right.\n\n    split.\n    reflexivity.\n\n    apply top_more_5'.\n    assumption.\n\n    assumption.    \n    apply top_more_1.\n    assumption.\n    assumption.\n    assumption.   \n    apply Zle_minus.\n    apply (top_more_4 _ _ _ _ t).\n    apply Zle_minus.\n    apply (top_more_4' _ _ _ _ t).\n   (** ~(top_more c0 d0 a0 b0) *)\n    intros.\n    apply homographicacc3'.\n\n    assumption.\n    assumption.\n    apply hyp1.\n    left.\n\n    unfold bin_lt in |- *.\n    apply compare_dL.  \n    replace 0%Z with (0 + 0)%Z.\n    apply Zplus_lt_le_compat.\n    assumption.\n    assumption.\n    constructor.\n    replace 0%Z with (0 + 0)%Z.\n    apply Zplus_lt_le_compat.\n    assumption.\n    assumption.\n    constructor.\n    apply Zlt_le_weak.\n    assumption.\n    assumption.\n    apply Zlt_le_weak.\n    assumption.\n    assumption.\n (** p = One *)\n  intros.\n  apply homographicacc0.\n  reflexivity.\n  assumption.\n  assumption.\nDefined.\n\n\n(* TEST part *)\n(* This part is an attempt to test the computational power of \"Qhomographic_Qpositive_to_Qpositive\" function. We try to calculate h(x)=2x+3/(x+4) for x:=1 *) \n(* TEST 1 : 01_08_02 RAM:386MB Coq:7.3 OS:Redhat7.3   RESULT:insufficient memory *) \n\nRemark one_non_negative : (0 <= 1)%Z.\nProof. \n apply Zorder.Zle_0_pos. \nDefined.\n\n\nRemark two_non_negative : (0 <= 2)%Z.\nProof. \n apply Zorder.Zle_0_pos. \nDefined.\n\nRemark three_non_negative : (0 <= 3)%Z.\nProof.\n apply Zorder.Zle_0_pos.\nDefined.\n\n\nRemark four_non_negative : (0 <= 4)%Z.\nProof.\n apply Zorder.Zle_0_pos.\nDefined.\n\nRemark five_non_negative : (0 <= 5)%Z.\nProof.\n apply Zorder.Zle_0_pos.\nDefined.\n\n\nRemark six_non_negative : (0 <= 6)%Z.\nProof.\n apply Zorder.Zle_0_pos.\nDefined.\n\nRemark seven_non_negative : (0 <= 7)%Z.\nProof.\n apply Zorder.Zle_0_pos.\nDefined.\n\n\nRemark two_plus_three_positive : (0 < 2 + 3)%Z.\nProof. \n simpl in |- *.\n apply ZERO_lt_POS. \nDefined.\n\nRemark one_plus_four_positive : (0 < 1 + 4)%Z.\nProof.\n simpl in |- *.\n apply ZERO_lt_POS.\nDefined.\n\n\n\nDefinition homographicacc_wf_for_five_over_five :=\n  homographicAcc_wf 2 3 1 4 One two_plus_three_positive\n    one_plus_four_positive two_non_negative three_non_negative\n    one_non_negative four_non_negative.\n\n(* TEST: Eval Compute in (Qhomographic_Qpositive_to_Qpositive `2` `3` `1` `4` (One) homographicacc_wf_for_five_over_five). *)\n\n(* End of the TEST part *)\n\n\n(** Proof independence of Qhomographic_Qpositive_to_Qpositive: *)\n\nScheme homographicAcc_ind_dep := Induction for homographicAcc Sort Prop.\n\n\nLemma Qhomographic_Qpositive_to_Qpositive_equal :\n forall (a b c d : Z) (p : Qpositive) (hyp1 hyp2 : homographicAcc a b c d p),\n Qhomographic_Qpositive_to_Qpositive a b c d p hyp1 =\n Qhomographic_Qpositive_to_Qpositive a b c d p hyp2.\nProof.\n intros a b c d p hyp1 hyp2.\n generalize hyp2.\n clear hyp2.\n pattern a, b, c, d, p, hyp1 in |- *.\n elim hyp1 using homographicAcc_ind_dep; clear a b c d p hyp1.\n\n\n (* 1st big subgoal *)\n   intros a b c d p Hp Hab Hcd hyp2; generalize Hp Hab Hcd; clear Hp Hab Hcd.\n   pattern a, b, c, d, p, hyp2 in |- *.\n   elim hyp2 using homographicAcc_ind_dep; clear a b c d p hyp2; intros.\n\n    \n    (* 1.1 *)\n    simpl in |- *.\n    case (Qpositive_dec_One p); intro Hp_; [ idtac | Falsum ].\n    apply positive_fraction_encoding_equal. \n    (* 1.2 *)\n    Falsum.\n    (* 1.3 *)\n    Falsum.\n    (* 1.4 *)\n    discriminate Hp.\n    (* 1.5 *)\n    discriminate Hp.\n\n\n (* 2nd big subgoal *)\n   intros a b c d p Hp Habcd hyp1 H_ind hyp2; generalize Hp Habcd hyp1 H_ind;\n    clear Hp Habcd H_ind hyp1.\n   pattern a, b, c, d, p, hyp2 in |- *.\n   elim hyp2 using homographicAcc_ind_dep; clear a b c d p hyp2; intros.\n\n    \n    (* 2.1 *)\n    Falsum.\n    (* 2.2 *)\n    simpl in |- *; case (Qpositive_dec_One p); intro Hp_; [ Falsum | idtac ];\n     case (top_more_informative a b c d); intro Habcd_; \n     [ idtac | Falsum ]; apply f_equal with Qpositive; \n     apply H_ind.\n    (* 2.3 *)\n    Falsum.\n    (* 2.4 *)\n    Falsum.\n    (* 2.5 *)\n    Falsum.\n\n (* 3rd big subgoal *)\n   intros a b c d p Hp Habcd Hcdab hyp1 H_ind hyp2;\n    generalize Hp Habcd Hcdab hyp1 H_ind; clear Hp Habcd Hcdab H_ind hyp1.\n   pattern a, b, c, d, p, hyp2 in |- *.\n   elim hyp2 using homographicAcc_ind_dep; clear a b c d p hyp2; intros.\n\n    \n    (* 3.1 *)\n    Falsum.\n    (* 3.2 *)\n    Falsum.\n    (* 3.3 *)\n    simpl in |- *; case (Qpositive_dec_One p); intro Hp_; [ Falsum | idtac ];\n     case (top_more_informative a b c d); intro Habcd_; \n     [ Falsum | idtac ]; case (top_more_informative c d a b); \n     intro Hcdab_; [ idtac | Falsum ]; apply f_equal with Qpositive;\n     apply H_ind.\n    (* 3.4 *)\n    Falsum.\n    (* 3.5 *)\n    Falsum.\n\n (* 4th big subgoal *)\n   intros a b c d xs Habcd Hcdab hyp1 H_ind hyp2.\n   set (P := nR xs) in *; assert (HP : P = nR xs); trivial; generalize HP.\n   generalize Habcd Hcdab hyp1 H_ind.\n   clear Habcd Hcdab H_ind hyp1.\n   (* here we copy-paste the current goal but change the 2nd occurnece of P to (dL xs) *)\n   elim hyp2 using\n    homographicAcc_ind_dep\n     with\n       (P := fun (a b c d : Z) (P : Qpositive)\n               (hyp2 : homographicAcc a b c d P) =>\n             forall (Habcd : ~ top_more a b c d) (Hcdab : ~ top_more c d a b)\n               (hyp1 : homographicAcc a (a + b) c (c + d) xs),\n             (forall hyp2 : homographicAcc a (a + b) c (c + d) xs,\n              Qhomographic_Qpositive_to_Qpositive a (a + b) c (c + d) xs hyp1 =\n              Qhomographic_Qpositive_to_Qpositive a (a + b) c (c + d) xs hyp2) ->\n             P = nR xs ->\n             Qhomographic_Qpositive_to_Qpositive a b c d \n               (nR xs) (homographicacc3 a b c d xs Habcd Hcdab hyp1) =\n             Qhomographic_Qpositive_to_Qpositive a b c d P hyp2);\n    clear a b c d hyp2; intros.\n    \n    (* 4.1 *)\n    Falsum; rewrite H0 in e; discriminate e.\n    (* 4.2 *)\n    Falsum.\n    (* 4.3 *)\n    Falsum.\n    (* 4.4 *)\n    simpl in |- *.\n    case (top_more_informative a b c d); intro Habcd_; [ Falsum | idtac ];\n     case (top_more_informative c d a b); intro Hcdab_; \n     [ Falsum | idtac ].\n    generalize h;\n     let T_local := eval compute in (f_equal Qpositive_tail H1) in\n     rewrite T_local.\n    intro; apply H0.\n    (* 4.5 *)\n    discriminate H1.\n\n (* 5th big subgoal *)\n   intros a b c d xs Habcd Hcdab hyp1 H_ind hyp2.\n   set (P := dL xs) in *; assert (HP : P = dL xs); trivial; generalize HP.\n   generalize Habcd Hcdab hyp1 H_ind.\n   clear Habcd Hcdab H_ind hyp1.\n   elim hyp2 using\n    homographicAcc_ind_dep\n     with\n       (P := fun (a b c d : Z) (P : Qpositive)\n               (hyp2 : homographicAcc a b c d P) =>\n             forall (Habcd : ~ top_more a b c d) (Hcdab : ~ top_more c d a b)\n               (hyp1 : homographicAcc (a + b) b (c + d) d xs),\n             (forall hyp2 : homographicAcc (a + b) b (c + d) d xs,\n              Qhomographic_Qpositive_to_Qpositive (a + b) b (c + d) d xs hyp1 =\n              Qhomographic_Qpositive_to_Qpositive (a + b) b (c + d) d xs hyp2) ->\n             P = dL xs ->\n             Qhomographic_Qpositive_to_Qpositive a b c d \n               (dL xs) (homographicacc3' a b c d xs Habcd Hcdab hyp1) =\n             Qhomographic_Qpositive_to_Qpositive a b c d P hyp2);\n    clear a b c d hyp2; intros.\n    \n    (* 5.1 *)\n    Falsum; rewrite H0 in e; discriminate e.\n    (* 5.2 *)\n    Falsum.\n    (* 5.3 *)\n    Falsum.\n    (* 5.4 *)\n    discriminate H1.\n    (* 5.5 *)\n    simpl in |- *.\n    case (top_more_informative a b c d); intro Habcd_; [ Falsum | idtac ];\n     case (top_more_informative c d a b); intro Hcdab_; \n     [ Falsum | idtac ].\n    generalize h;\n     let T_local := eval compute in (f_equal Qpositive_tail H1) in\n     rewrite T_local.\n    intro; apply H0.\nDefined. \n\n\nLemma Qhomographic_Qpositive_to_Qpositive_equal_strong :\n forall (a1 a2 b1 b2 c1 c2 d1 d2 : Z) (p1 p2 : Qpositive)\n   (hyp1 : homographicAcc a1 b1 c1 d1 p1)\n   (hyp2 : homographicAcc a2 b2 c2 d2 p2),\n a1 = a2 ->\n b1 = b2 ->\n c1 = c2 ->\n d1 = d2 ->\n p1 = p2 ->\n Qhomographic_Qpositive_to_Qpositive a1 b1 c1 d1 p1 hyp1 =\n Qhomographic_Qpositive_to_Qpositive a2 b2 c2 d2 p2 hyp2.\nProof.\n intros.\n subst.\n apply Qhomographic_Qpositive_to_Qpositive_equal. \nDefined.\n\n\n(** Here we expand the fixpoint equations of \"Qhomographic_Qpositive_to_Qpositive\" function *)\n\nLemma Qhomographic_Qpositive_to_Qpositive_0 :\n forall (a b c d : Z) (p : Qpositive) (hyp : homographicAcc a b c d p),\n p = One ->\n forall (H1 : (0 < a + b)%Z) (H2 : (0 < c + d)%Z),\n Qhomographic_Qpositive_to_Qpositive a b c d p hyp =\n positive_fraction_encoding (a + b) (c + d) H1 H2. \nProof. \n intros. \n apply\n  trans_eq\n   with\n     (Qhomographic_Qpositive_to_Qpositive a b c d One\n        (homographicacc0 a b c d One (refl_equal One) H1 H2)).\n apply Qhomographic_Qpositive_to_Qpositive_equal_strong; repeat reflexivity.\n assumption.\n  simpl in |- *.\n  apply positive_fraction_encoding_equal.\nDefined.\n\n\nLemma Qhomographic_Qpositive_to_Qpositive_1 :\n forall (a b c d : Z) (p : Qpositive) (hyp : homographicAcc a b c d p),\n p <> One ->\n top_more a b c d ->\n forall h : homographicAcc (a - c) (b - d) c d p,\n Qhomographic_Qpositive_to_Qpositive a b c d p hyp =\n nR (Qhomographic_Qpositive_to_Qpositive (a - c) (b - d) c d p h).\nProof.\n intros.\n apply\n  trans_eq\n   with\n     (Qhomographic_Qpositive_to_Qpositive a b c d p\n        (homographicacc1 a b c d p H H0 h)).\n apply Qhomographic_Qpositive_to_Qpositive_equal.\n  simpl in |- *.\n  case (Qpositive_dec_One p); intros Hp; [ Falsum | idtac ].\n  case (top_more_informative a b c d); intros Habcd; [ idtac | Falsum ].\n  apply f_equal with Qpositive; reflexivity.\nDefined.\n\nLemma Qhomographic_Qpositive_to_Qpositive_2 :\n forall (a b c d : Z) (p : Qpositive) (hyp : homographicAcc a b c d p),\n p <> One ->\n ~ top_more a b c d ->\n top_more c d a b ->\n forall h : homographicAcc a b (c - a) (d - b) p,\n Qhomographic_Qpositive_to_Qpositive a b c d p hyp =\n dL (Qhomographic_Qpositive_to_Qpositive a b (c - a) (d - b) p h).\nProof.\n intros.\n apply\n  trans_eq\n   with\n     (Qhomographic_Qpositive_to_Qpositive a b c d p\n        (homographicacc2 a b c d p H H0 H1 h)).\n apply Qhomographic_Qpositive_to_Qpositive_equal.\n  simpl in |- *.\n  case (Qpositive_dec_One p); intros Hp; [ Falsum | idtac ].\n  case (top_more_informative a b c d); intros Habcd; [ Falsum | idtac ].\n  case (top_more_informative c d a b); intros Hcdab; [ idtac | Falsum ].\n  apply f_equal with Qpositive; reflexivity.\nDefined.\n\n\nLemma Qhomographic_Qpositive_to_Qpositive_3 :\n forall (a b c d : Z) (p : Qpositive) (hyp : homographicAcc a b c d p),\n ~ top_more a b c d ->\n ~ top_more c d a b ->\n forall xs : Qpositive,\n p = nR xs ->\n forall h : homographicAcc a (a + b) c (c + d) xs,\n Qhomographic_Qpositive_to_Qpositive a b c d p hyp =\n Qhomographic_Qpositive_to_Qpositive a (a + b) c (c + d) xs h.\nProof.\n intros.\n apply\n  trans_eq\n   with\n     (Qhomographic_Qpositive_to_Qpositive a b c d (nR xs)\n        (homographicacc3 a b c d xs H H0 h)).\n apply Qhomographic_Qpositive_to_Qpositive_equal_strong; trivial.\n  simpl in |- *.\n  case (top_more_informative a b c d); intros Habcd; [ Falsum | idtac ].\n  case (top_more_informative c d a b); intros Hcdab; [ Falsum | idtac ].\n  reflexivity.\nDefined.\n\nLemma Qhomographic_Qpositive_to_Qpositive_3' :\n forall (a b c d : Z) (p : Qpositive) (hyp : homographicAcc a b c d p),\n ~ top_more a b c d ->\n ~ top_more c d a b ->\n forall xs : Qpositive,\n p = dL xs ->\n forall h : homographicAcc (a + b) b (c + d) d xs,\n Qhomographic_Qpositive_to_Qpositive a b c d p hyp =\n Qhomographic_Qpositive_to_Qpositive (a + b) b (c + d) d xs h.\nProof.\n intros.\n apply\n  trans_eq\n   with\n     (Qhomographic_Qpositive_to_Qpositive a b c d (dL xs)\n        (homographicacc3' a b c d xs H H0 h)).\n apply Qhomographic_Qpositive_to_Qpositive_equal_strong; trivial.\n  simpl in |- *.\n  case (top_more_informative a b c d); intros Habcd; [ Falsum | idtac ].\n  case (top_more_informative c d a b); intros Hcdab; [ Falsum | idtac ].\n  reflexivity.\nDefined.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/qarith-stern-brocot/Qhomographic_Qpositive_to_Qpositive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.24597395361641358}}
{"text": "(** \n_AUTHOR_\n\n<<\nZhi Zhang\nDepartment of Computer and Information Sciences\nKansas State University\nzhangzhi@ksu.edu\n>>\n*)\n\nRequire Export FunInd rt_gen_impl.\n\n(* ***************************************************************\n                 Semantics Equivalence Proof\n   *************************************************************** *)\n\n(** * Semantics Consistency Proof for Run-Time Check Generator *)\n\nScheme expression_ind := Induction for exp Sort Prop \n                         with name_ind := Induction for name Sort Prop.\n\n(** * Soundness of RT-GEN Implementation *)\n\nSection Checks_Generator_Implementation_Soundness_Proof.\n\n  (** ** toExpRTImpl_soundness *)\n  Lemma toExpRTImpl_soundness: forall e e' st,\n    toExpRTImpl st e = e' ->\n      toExpRT st e e'.\n  Proof.\n    apply (expression_ind\n      (fun e: exp => forall (e' : expRT) (st: symTab),\n        toExpRTImpl st e = e' ->\n        toExpRT   st e e')\n      (fun n: name => forall (n': nameRT) (st: symTab),\n        toNameRTImpl st n = n' ->\n        toNameRT   st n n')\n      ); smack;\n    [ (*Literal*) \n      destruct l;\n      [ remember ((min_signed <=? z)%Z && (z <=? max_signed)%Z) as b; destruct b;\n        smack; constructor; smack |\n        smack; constructor\n      ] | \n      (*Name*) | \n      (*BinOp a b e e0*) destruct b |\n      (*UnOp a u e*) destruct u |\n      (*Identifier a i*) |\n      (*IndexedComponent a n e*) |\n      (*SelectedComponent a n i*)\n    ];\n    match goal with\n    | [H: _ = ?b |- in_bound _ _ ?b] => rewrite <- H; constructor; smack\n    | _ => constructor; smack\n    end.\n  Qed.\n\n  (** ** toNameRTImpl_soundness *)\n  Lemma toNameRTImpl_soundness: forall st n n',\n    toNameRTImpl st n = n' ->\n      toNameRT st n n'.\n  Proof.\n    intros st n;\n    induction n; smack; constructor; smack;\n    apply toExpRTImpl_soundness; auto.\n  Qed.\n\n  (** ** toArgsRTImpl_soundness *)\n  Lemma toArgsRTImpl_soundness: forall st params args args',\n    toArgsRTImpl st params args = Some args' ->\n      toArgsRT st params args args'.\n  Proof.\n    induction params; smack.\n  - destruct args; smack;\n    constructor.\n  - destruct args; smack.\n    remember (toArgsRTImpl st params args) as b1;\n    remember (parameter_mode a) as b2; \n    destruct b1, b2; smack.\n    + (*In Mode*)\n      remember (is_range_constrainted_type (parameter_subtype_mark a)) as x;\n      destruct x; smack;\n      [ apply ToArgsInRangeCheck |\n        apply ToArgsIn\n      ]; smack; \n      apply toExpRTImpl_soundness; auto.\n    + (*Out Mode*)\n      destruct e; smack;\n      remember (fetch_exp_type a0 st) as b3;\n      destruct b3; smack;\n      remember (is_range_constrainted_type t) as b4; destruct b4; smack;\n      [ apply ToArgsOutRangeCheck with (t := t) |\n        apply ToArgsOut with (t := t)\n      ]; smack;\n      apply toNameRTImpl_soundness; auto.\n    + (*In_Out Mode*)\n      destruct e; smack;\n      remember (is_range_constrainted_type (parameter_subtype_mark a)) as b3;\n      remember (fetch_exp_type a0 st) as b4;\n      destruct b3, b4; smack;\n      remember (is_range_constrainted_type t) as b5;\n      destruct b5; smack;\n      [ apply ToArgsInOutRangeCheck with (t:=t) |\n        apply ToArgsInOutRangeCheckIn with (t:=t) |\n        apply ToArgsInOutRangeCheckOut with (t:=t) |\n        apply ToArgsInOut with (t:=t)\n      ]; auto;\n      apply toNameRTImpl_soundness; auto.\n  Qed.\n\n  (** ** toStmtRTImpl_soundness *)\n  Lemma toStmtRTImpl_soundness: forall st c c',\n    toStmtRTImpl st c = Some c' ->\n      toStmtRT st c c'.\n  Proof.\n    induction c; smack.\n  - (*Null*)\n    constructor.\n  - (*Assign*)\n    remember (fetch_exp_type (name_astnum n) st ) as b1;\n    destruct b1; smack;\n    remember (is_range_constrainted_type t) as b2;\n    destruct b2; smack;\n    [ apply ToAssignRangeCheck with (t := t) |\n      apply ToAssign with (t := t)\n    ]; auto;\n    solve \n    [ apply toNameRTImpl_soundness; auto |\n      apply toExpRTImpl_soundness; auto\n    ].\n  - (*If*)\n    remember (toStmtRTImpl st c1) as b1;\n    remember (toStmtRTImpl st c2) as b2;\n    destruct b1, b2; smack;\n    constructor; smack;\n    apply toExpRTImpl_soundness; auto.\n  - (*While*)\n    remember (toStmtRTImpl st c) as b1;\n    destruct b1; smack;\n    constructor; smack;\n    apply toExpRTImpl_soundness; auto.\n  - (*Call*)\n    remember (fetch_proc p st) as b1;\n    destruct b1; smack;\n    destruct t;\n    remember (toArgsRTImpl st (procedure_parameter_profile p0) l) as b2;\n    destruct b2; smack;\n    apply ToCall with (n0 := l0) (pb := p0) (params := (procedure_parameter_profile p0)); smack;\n    apply toArgsRTImpl_soundness; auto.\n  - (*Seq*)\n    remember (toStmtRTImpl st c1) as b1;\n    remember (toStmtRTImpl st c2) as b2;\n    destruct b1, b2; smack;\n    constructor; auto.\n  Qed.\n\n  Lemma toTypeDeclRTImpl_soundness: forall t t',\n    toTypeDeclRTImpl t = t' ->\n        toTypeDeclRT t t'.\n  Proof.\n    destruct t; smack;\n    try (destruct r); constructor.\n  Qed.\n\n  Lemma toObjDeclRTImpl_soundness: forall st o o',\n    toObjDeclRTImpl st o = o' ->\n      toObjDeclRT st o o'.\n  Proof.\n    intros;\n    functional induction toObjDeclRTImpl st o; smack;\n    [ constructor |\n      apply ToObjDeclRangeCheck |\n      apply ToObjDecl \n    ]; auto; apply toExpRTImpl_soundness; auto.\n  Qed.\n\n  Lemma toObjDeclsRTImpl_soundness: forall st lo lo',\n    toObjDeclsRTImpl st lo = lo' ->\n      toObjDeclsRT st lo lo'.\n  Proof.\n    induction lo; smack;\n    constructor; smack;\n    apply toObjDeclRTImpl_soundness; auto.\n  Qed.\n\n  Lemma toParamSpecRTImpl_soundness: forall param param',\n    toParamSpecRTImpl param = param' ->\n      toParamSpecRT param param'.\n  Proof.\n    smack;\n    destruct param;\n    constructor.  \n  Qed.\n\n  Lemma toParamSpecsRTImpl_soundness: forall lparam lparam',\n    toParamSpecsRTImpl lparam = lparam' ->\n      toParamSpecsRT lparam lparam'.\n  Proof.\n    induction lparam; smack;\n    constructor; smack;\n    apply toParamSpecRTImpl_soundness; auto.\n  Qed.\n\n\n  Scheme declaration_ind := Induction for decl Sort Prop \n                            with procedure_body_ind := Induction for procBodyDecl Sort Prop.\n\n  (** ** toDeclRTImpl_soundness *)\n\n  Lemma toDeclRTImpl_soundness: forall d d' st,\n    toDeclRTImpl st d = Some d' ->\n      toDeclRT st d d'.\n  Proof.\n    apply (declaration_ind\n      (fun d: decl => forall (d' : declRT) (st: symTab),\n        toDeclRTImpl st d = Some d' ->\n        toDeclRT st d d')\n      (fun p: procBodyDecl => forall (p': procBodyDeclRT) (st: symTab),\n        toProcBodyDeclRTImpl st p = Some p' ->\n        toProcBodyDeclRT st p p')\n      ); smack.\n  - constructor.\n  - constructor;\n    apply toTypeDeclRTImpl_soundness; auto.\n  - constructor;\n    apply toObjDeclRTImpl_soundness; auto.\n  - remember (toProcBodyDeclRTImpl st p) as x; \n    destruct x; smack;\n    constructor; auto.\n  - remember (toDeclRTImpl st d) as x;\n    remember (toDeclRTImpl st d0) as y;\n    destruct x, y; smack;\n    constructor; smack.\n  - remember (toDeclRTImpl st procedure_declarative_part) as x;\n    remember (toStmtRTImpl st procedure_statements) as y;\n    destruct x, y; smack;\n    constructor;\n    [ apply toParamSpecsRTImpl_soundness | |\n      apply toStmtRTImpl_soundness\n    ]; auto.\n  Qed.\n\n  (** ** toProcBodyDeclRTImpl_soundness *)\n\n  Lemma toProcBodyDeclRTImpl_soundness: forall st p p',\n    toProcBodyDeclRTImpl st p = Some p' ->\n      toProcBodyDeclRT st p p'.\n  Proof.\n    intros;\n    destruct p; smack.\n    remember (toDeclRTImpl st procedure_declarative_part) as x;\n    remember (toStmtRTImpl st procedure_statements) as y;\n    destruct x, y; smack;\n    constructor;\n    [ apply toParamSpecsRTImpl_soundness |\n      apply toDeclRTImpl_soundness |\n      apply toStmtRTImpl_soundness \n    ]; auto.\n  Qed.\n\n  (** ** toProgramRTImpl_soundness *)\n\n  Lemma toProgramRTImpl_soundness: forall st p p',\n    toProgramRTImpl st p = Some p' ->\n      toProgramRT st p p'.\n  Proof.\n    intros.\n    destruct p, p'.\n    unfold toProgramRTImpl in H; \n    inversion H; subst; clear H.\n    remember (toDeclRTImpl st decls) as x.\n    destruct x; inversion H1; subst.\n    constructor;\n    apply toDeclRTImpl_soundness; auto.\n  Qed.\n\nEnd Checks_Generator_Implementation_Soundness_Proof.\n\n\n(** * Completeness of RT-GEN Implementation *)\n\nSection Checks_Generator_Implementation_Completeness_Proof.\n\n  (** ** toExpRTImpl_completeness *)\n\n  Lemma toExpRTImpl_completeness: forall e e' st,\n    toExpRT st e e' ->\n      toExpRTImpl st e = e'.\n  Proof.\n    apply (expression_ind\n      (fun e: exp => forall (e' : expRT) (st: symTab),\n        toExpRT   st e e' ->\n        toExpRTImpl st e = e')\n      (fun n: name => forall (n': nameRT) (st: symTab),\n        toNameRT   st n n' ->\n        toNameRTImpl st n = n')\n      ); smack;\n    match goal with\n    | [H: toExpRT  _ ?e ?e' |- _] => inversion H; clear H; smack\n    | [H: toNameRT _ ?n ?n' |- _] => inversion H; clear H; smack\n    end;\n    repeat progress match goal with\n    | [H1:forall (e' : expRT) (st : symTab),\n          toExpRT _ ?e e' ->\n          toExpRTImpl _ ?e = e',\n       H2:toExpRT _ ?e ?e1RT |- _] => specialize (H1 _ _ H2); smack\n    | [H1:forall (n' : nameRT) (st : symTab),\n          toNameRT _ ?n n' ->\n          toNameRTImpl _ ?n = n',\n       H2:toNameRT _ ?n ?nRT |- _] => specialize (H1 _ _ H2); smack\n    end;\n    match goal with\n    | [H: in_bound _ _ _ |- _] => inversion H; smack\n    | _ => idtac\n    end;\n    [ destruct b | \n      destruct u \n    ]; smack.\n  Qed.\n\n  (** ** toNameRTImpl_completeness *)\n  Lemma toNameRTImpl_completeness: forall st n n',\n    toNameRT st n n' ->\n      toNameRTImpl st n = n'.\n  Proof.\n    intros;\n    induction H; smack;\n    match goal with\n    | [H: toExpRT ?st ?e ?e' |- _] => \n        specialize (toExpRTImpl_completeness _ _ _ H); smack\n    end; auto.\n  Qed.\n\n  (** ** toArgsRTImpl_completeness *)\n\n  Lemma toArgsRTImpl_completeness: forall st params args args',\n    toArgsRT st params args args' ->\n      toArgsRTImpl st params args = Some args'.\n  Proof.\n    induction params; smack;\n    match goal with\n    | [H: toArgsRT _ _ ?args ?args' |- _] => inversion H; clear H; smack\n    end;\n    match goal with\n    | [H1: forall (args : list exp) (args' : list expRT),\n           toArgsRT _ ?params _ _ ->\n           toArgsRTImpl _ ?params _ = Some _,\n       H2: toArgsRT _ ?params _ _ |- _] => specialize (H1 _ _ H2)\n    end;\n    match goal with\n    | [H: toArgsRTImpl ?st ?params ?larg = Some _ |- _] => rewrite H; simpl\n    end;\n    match goal with\n    | [H: toExpRT _ ?e ?e' |- _] => specialize (toExpRTImpl_completeness _ _ _ H); smack\n    | [H: toNameRT _ ?n ?n' |- _] => specialize (toNameRTImpl_completeness _ _ _ H); smack\n    | _ => idtac\n    end; auto.\n  Qed.\n\n  (** ** toStmtRTImpl_completeness *)\n\n  Lemma toStmtRTImpl_completeness: forall st c c',\n    toStmtRT st c c' ->\n      toStmtRTImpl st c = Some c'.\n  Proof.\n    induction c; smack;\n    match goal with\n    | [H: toStmtRT _ ?c ?c' |- _] => inversion H; clear H; smack\n    end;\n    repeat progress match goal with\n    | [H: toExpRT  _ ?e ?e' |- _] => specialize (toExpRTImpl_completeness  _ _ _ H); clear H\n    | [H: toNameRT _ ?n ?n' |- _] => specialize (toNameRTImpl_completeness _ _ _ H); clear H\n    | [H1: forall c' : stmtRT,\n           toStmtRT _ ?c _ ->\n           toStmtRTImpl _ ?c = Some _,\n       H2: toStmtRT _ ?c _ |- _ ] => specialize (H1 _ H2)\n    end; smack;\n    match goal with\n    | [H: toArgsRT _ _ _ _ |- _ ] => specialize (toArgsRTImpl_completeness _ _ _ _ H); smack\n    end.\n  Qed.\n\n  Lemma toTypeDeclRTImpl_completeness: forall t t',\n    toTypeDeclRT t t' ->\n      toTypeDeclRTImpl t = t'.\n  Proof.\n    destruct t; intros;\n    match goal with\n    | [H: toTypeDeclRT _ _ |- _] => inversion H; smack\n    end.\n  Qed.\n\n  Lemma toObjDeclRTImpl_completeness: forall st o o',\n    toObjDeclRT st o o' ->\n      toObjDeclRTImpl st o = o'.\n  Proof.\n    intros;\n    functional induction toObjDeclRTImpl st o;\n    match goal with\n    | [H: toObjDeclRT _ _ _ |- _] => inversion H; smack\n    end;\n    match goal with\n    | [H: toExpRT _ _ _ |- _] => \n        specialize (toExpRTImpl_completeness _ _ _ H); smack\n    end. \n  Qed.\n\n  Lemma toObjDeclsRTImpl_completeness: forall st lo lo',\n    toObjDeclsRT st lo lo' ->\n      toObjDeclsRTImpl st lo = lo'.\n  Proof.\n    induction lo; smack;\n    match goal with\n    | [H: toObjDeclsRT _ _ _ |- _] => inversion H; clear H; smack\n    end;\n    match goal with\n    | [H: toObjDeclRT _ ?o ?o' |- _] => \n        specialize (toObjDeclRTImpl_completeness _ _ _ H); smack\n    end;\n    specialize (IHlo _ H5); smack.\n  Qed.\n\n  Lemma toParamSpecRTImpl_completeness: forall param param',\n    toParamSpecRT param param' ->\n      toParamSpecRTImpl param = param'.\n  Proof.\n    intros;\n    inversion H; auto.\n  Qed.\n\n  Lemma toParamSpecsRTImpl_completeness: forall lparam lparam',\n    toParamSpecsRT lparam lparam' ->\n      toParamSpecsRTImpl lparam = lparam'.\n  Proof.\n    induction lparam; intros;\n    inversion H; auto;\n    specialize (IHlparam _ H4);\n    match goal with\n    | [H: toParamSpecRT _ _ |- _] => \n        specialize (toParamSpecRTImpl_completeness _ _ H); smack\n    end.\n  Qed.\n\n  (** ** toDeclRTImpl_completeness *)\n\n  Lemma toDeclRTImpl_completeness: forall d d' st,\n    toDeclRT st d d' ->\n      toDeclRTImpl st d = Some d'.\n  Proof.\n    apply (declaration_ind\n      (fun d: decl => forall (d' : declRT) (st: symTab),\n        toDeclRT st d d' ->\n        toDeclRTImpl st d = Some d')\n      (fun p: procBodyDecl => forall (p': procBodyDeclRT) (st: symTab),\n        toProcBodyDeclRT st p p' ->\n        toProcBodyDeclRTImpl st p = Some p')\n      ); smack;\n    match goal with\n    | [H: toDeclRT _ _ _ |- _] => inversion H; clear H; smack\n    | [H: toProcBodyDeclRT _ _ _ |- _] => inversion H; clear H; smack\n    end;\n    repeat progress match goal with\n    | [H: toTypeDeclRT _ _ |- _] => \n        specialize (toTypeDeclRTImpl_completeness _ _ H); smack\n    | [H: toObjDeclRT _ _ _ |- _] =>\n        specialize (toObjDeclRTImpl_completeness _ _ _ H); smack\n    | [H: toParamSpecsRT _ _ |- _] =>\n        specialize (toParamSpecsRTImpl_completeness _ _ H); clear H; smack\n    | [H: toStmtRT _ _ _ |- _] =>\n        specialize (toStmtRTImpl_completeness _ _ _ H); clear H; smack\n    | [H1: forall (p' : procBodyDeclRT) (st : symTab),\n           toProcBodyDeclRT _ ?p _ ->\n           toProcBodyDeclRTImpl _ ?p = Some _,\n       H2: toProcBodyDeclRT _ ?p _ |- _] =>\n        specialize (H1 _ _ H2); smack\n    | [H1: forall (d' : declRT) (st : symTab),\n           toDeclRT _ ?d _ ->\n           toDeclRTImpl _ ?d = Some _,\n       H2: toDeclRT _ ?d _ |- _] => \n        specialize (H1 _ _ H2); clear H2; smack\n    end.\n  Qed.\n\n  (** ** toProcBodyDeclRTImpl_completeness *)\n\n  Lemma toProcBodyDeclRTImpl_completeness: forall st p p',\n    toProcBodyDeclRT st p p' ->\n      toProcBodyDeclRTImpl st p = Some p'.\n  Proof.\n    intros;\n    destruct p;\n    match goal with\n    [H: toProcBodyDeclRT _ _ _ |- _] => inversion H; clear H; smack\n    end;\n    repeat progress match goal with\n    | [H: toParamSpecsRT _ _ |- _] =>\n        specialize (toParamSpecsRTImpl_completeness _ _ H); clear H; smack\n    | [H: toStmtRT _ _ _ |- _] =>\n        specialize (toStmtRTImpl_completeness _ _ _ H); clear H; smack\n    | [H: toDeclRT _ _ _ |- _] => \n        specialize (toDeclRTImpl_completeness _ _ _ H); clear H; smack\n    end.\n  Qed.\n\n  (** ** toProgramRTImpl_completeness *)\n\n  Lemma toProgramRTImpl_completeness: forall st p p',\n    toProgramRT st p p' ->\n      toProgramRTImpl st p = Some p'.\n  Proof.\n    intros.\n    destruct p, p'.\n    inversion H; subst; clear H.\n    simpl in H3.\n    specialize (toDeclRTImpl_completeness _ _ _ H3); intro HZ.\n    unfold toProgramRTImpl; simpl. \n    rewrite HZ; auto.\n  Qed.\n\nEnd Checks_Generator_Implementation_Completeness_Proof.\n\n(** * Consistency of RT-GEN Impl and RT-GEN Spec *)\n\n(** ** toExpRTImplConsistent *)\nLemma toExpRTImplConsistent: forall e e' st,\n  toExpRT st e e' <-> \n    toExpRTImpl st e = e'.\nProof.\n  intros; split; intro;\n  [ apply toExpRTImpl_completeness; auto |\n    apply toExpRTImpl_soundness; auto \n  ].\nQed.  \n\n(** ** toStmtRTImplConsistent *)\nLemma toStmtRTImplConsistent: forall st c c',\n  toStmtRT st c c' <->\n    toStmtRTImpl st c = Some c'.\nProof.\n  intros; split; intro;\n  [ apply toStmtRTImpl_completeness; auto |\n    apply toStmtRTImpl_soundness; auto \n  ].\nQed.\n\n(** ** toProcBodyDeclRTConsistent *)\nLemma toProcBodyDeclRTConsistent: forall st p p',\n  toProcBodyDeclRT st p p' <->\n    toProcBodyDeclRTImpl st p = Some p'.\nProof.\n  intros; split; intro;\n  [ apply toProcBodyDeclRTImpl_completeness; auto |\n    apply toProcBodyDeclRTImpl_soundness; auto \n  ].\nQed.\n\n\n(** ** toProgramRTImplConsistent *)\nLemma toProgramRTImplConsistent: forall st p p',\n  toProgramRT st p p' <->\n    toProgramRTImpl st p = Some p'.\nProof.\n  intros; split; intro;\n  [ apply toProgramRTImpl_completeness; auto |\n    apply toProgramRTImpl_soundness; auto \n  ].\nQed.\n\n", "meta": {"author": "AdaCore", "repo": "sparkformal", "sha": "51ed67be1b1d80f7f2681237dfbf4ee7add395d6", "save_path": "github-repos/coq/AdaCore-sparkformal", "path": "github-repos/coq/AdaCore-sparkformal/sparkformal-51ed67be1b1d80f7f2681237dfbf4ee7add395d6/spark2014_semantics/src/rt_gen_impl_consistent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.24597395361641358}}
{"text": "Require Import syntax.\nRequire Import alist.\nRequire Import FMapWeakList.\n\nRequire Import Classical.\nRequire Import Coqlib.\nRequire Import infrastructure.\nRequire Import Metatheory.\nImport LLVMsyntax.\nImport LLVMinfra.\nRequire Import opsem.\nRequire Import memory_props.\n\nRequire Import sflib.\nRequire Import paco.\nImport Opsem.\n\nRequire Import TODO.\nRequire Import Exprs.\nRequire Import Postcond.\nRequire Import Hints.\nRequire Import Validator.\nRequire Import GenericValues.\nRequire AssnMem.\nRequire AssnState.\nRequire Import Inject.\nRequire Import SoundBase.\nRequire Import SoundSnapshot.\nRequire Import SoundForgetStack.\nRequire Import SoundReduceMaydiff.\nRequire Import SoundImplies.\nRequire Import TODOProof.\nRequire Import OpsemAux.\nRequire Import MemAux.\n\nSet Implicit Arguments.\n\n\nLemma add_terminator_cond_br_uncond\n      inv bid_src bid_tgt l:\n  Postcond.add_terminator_cond\n    inv\n    (insn_br_uncond bid_src l)\n    (insn_br_uncond bid_tgt l)\n    l =\n  inv.\nProof. destruct inv, src, tgt. ss. Qed.\n\nLemma add_terminator_cond_switch_unary\n      conf val st gmax public\n      ty gval cases l_dflt l_dest id\n      invst assnmem inv\n      (VAL : getOperandValue (CurTargetData conf) val\n                             (Locals (EC st)) (Globals conf) = Some gval)\n      (DECIDE : get_switch_branch (CurTargetData conf)\n                                  ty gval cases l_dflt = Some l_dest)\n      (STATE : AssnState.Unary.sem conf st invst assnmem gmax public inv)\n  : AssnState.Unary.sem conf st invst assnmem gmax public\n                       (Assertion.update_lessdef\n                          (add_terminator_cond_lessdef\n                             (insn_switch id ty val l_dflt cases) l_dest) inv).\nProof.\n  inv STATE.\n  econs; eauto. ss. ii.\n  des_ifs; try by eapply LESSDEF; eauto.\n  destruct p as [const_case l_case]. ss.\n  rename Heq into FILTER_CASES.\n\n  assert (CASE_AUX: In (const_case, l_case)\n                       (List.filter (fun cl : const * l => l_dec l_dest (snd cl)) cases)).\n  { rewrite FILTER_CASES. unfold In. eauto. }\n\n  assert (CASE_IN: In (const_case, l_case) cases).\n  { apply filter_In in CASE_AUX. des. eauto. }\n\n  assert (CASE_UNIQUE: forall cl, In cl cases -> l_dec l_dest (snd cl) ->\n                             cl = (const_case, l_case)).\n  { i.\n    cut (In cl [(const_case, l_case)]).\n    { intro IN. inv IN; eauto. contradiction. }\n    rewrite <- FILTER_CASES.\n    apply filter_In. split; eauto.\n  }\n  (* gv_chunks_match_typ *)\n\n  unfold get_switch_branch in DECIDE. des_ifs.\n  unfold get_switch_branch_aux in *. des_ifs.\n  exploit find_some; eauto. i. des. des_ifs. ss.\n  exploit CASE_UNIQUE; eauto.\n  { ss. destruct (l_dec l0 l0); ss. }\n  i. clarify.\n  specialize (Fcore_Zaux.Zeq_bool_spec z0 z).\n  intro ZEQ. inv ZEQ; try congruence.\n  destruct x as [e1 e2].\n\n  do 2 rewrite ExprPairSetFacts.add_iff in *. des.\n  - ss. clarify. ss.\n    solve_leibniz. clarify. ss.\n    rewrite AssnState.Unary.sem_valueT_physical in VAL1. clarify.\n\n    unfold intConst2Z in *. des_ifs.\n\n    esplits; eauto.\n    + unfold const2GV. ss.\n    + ss.\n      unfold GV2int in *. des_ifs.\n      unfold val2GV.\n      econs; try by apply list_forall2_nil.\n      split; ss.\n      { rewrite <- H1.\n        rewrite <- e.\n        replace (n0+1-1)%nat with n0; try omega.\n        rewrite Integers.Int.repr_signed. eauto.\n      }\n      { esplits; eauto.\n        - rewrite <- e.\n          replace (n0+1-1)%nat with n0; try omega.\n          ss.\n        - chunk_simpl.\n      }\n  - ss. clarify. ss.\n    solve_leibniz. clarify. ss.\n    rewrite AssnState.Unary.sem_valueT_physical. clarify.\n\n    unfold intConst2Z in *. des_ifs.\n\n    esplits; eauto.\n    unfold const2GV in *. ss. clarify.\n    unfold GV2int in *. des_ifs.\n    econs; try by apply list_forall2_nil.\n    ss. split.\n    { rewrite <- H1.\n      rewrite <- e.\n      replace (n0+1-1)%nat with n0; try omega.\n      rewrite Integers.Int.repr_signed. eauto.\n    }\n    { esplits; eauto.\n      - rewrite <- e. replace (n0+1-1)%nat with n0; try omega. ss.\n      - chunk_simpl.\n    }\n  - apply LESSDEF; eauto.\nQed.\n\nLemma add_terminator_cond_switch\n      conf_src conf_tgt\n      st_src st_tgt\n      invst assnmem inv\n      ty cases l_dflt l_dest\n      id_src val_src gval_src\n      id_tgt val_tgt gval_tgt\n      (STATE: AssnState.Rel.sem\n                conf_src conf_tgt st_src st_tgt\n                invst assnmem inv)\n      (VAL_SRC: getOperandValue\n                  conf_src.(CurTargetData)\n                  val_src\n                  st_src.(EC).(Locals)\n                  conf_src.(Globals) = Some gval_src)\n      (VAL_TGT: getOperandValue\n                  conf_tgt.(CurTargetData)\n                  val_tgt\n                  st_tgt.(EC).(Locals)\n                  conf_tgt.(Globals) = Some gval_tgt)\n      (DECIDE_SRC: get_switch_branch conf_src.(CurTargetData) ty gval_src cases l_dflt = Some l_dest)\n      (DECIDE_TGT: get_switch_branch conf_tgt.(CurTargetData) ty gval_tgt cases l_dflt = Some l_dest)\n  : AssnState.Rel.sem\n      conf_src conf_tgt\n      st_src st_tgt\n      invst assnmem\n      (Postcond.add_terminator_cond\n         inv\n         (insn_switch id_src ty val_src l_dflt cases)\n         (insn_switch id_tgt ty val_tgt l_dflt cases) l_dest).\nProof.\n  inv STATE.\n  econs; eauto; ss.\n  - eapply add_terminator_cond_switch_unary; eauto.\n  - eapply add_terminator_cond_switch_unary; eauto.\nQed.\n\nLemma int_sizezero_cases_aux\n      (i : Integers.Int.int 0)\n  : (Integers.Int.eq 0 i (Integers.Int.zero 0) = true) \\/\n    (Integers.Int.eq 0 i (Integers.Int.one 0) = true).\nProof.\n  destruct i. destruct intval.\n  - left. ss.\n  - unfold Integers.Int.modulus, two_power_nat in intrange. ss.\n    destruct p.\n    + specialize (Pos2Z.inj_xI p). i.\n      specialize (Zgt_pos_0 p). i. omega.\n    + specialize (Pos2Z.inj_xO p). i.\n      specialize (Zgt_pos_0 p). i. omega.\n    + right. ss.\n  - specialize (Zlt_neg_0 p). i. omega.\nQed.\n\nLemma int_sizezero_cases\n      (i : Integers.Int.int 0)\n  : (i = (Integers.Int.zero 0)) \\/\n    (i = (Integers.Int.one 0)).\nProof.\n  specialize (int_sizezero_cases_aux i). i. des.\n  - left.\n    exploit Integers.Int.eq_spec. i.\n    rewrite H in *. eauto.\n  - right.\n    exploit Integers.Int.eq_spec. i.\n    rewrite H in *. eauto.\nQed.\n\nLemma add_terminator_cond_br_unary\n      conf val st gval decision\n      invst assnmem inv gmax public\n      id l1 l2\n      (VAL : getOperandValue (CurTargetData conf) val \n                             (Locals (EC st)) (Globals conf) = Some gval)\n      (DECIDE : decide_nonzero (CurTargetData conf) gval decision)\n      (STATE : AssnState.Unary.sem conf st invst assnmem gmax public inv)\n  : AssnState.Unary.sem conf st invst assnmem gmax public\n                       (Assertion.update_lessdef\n                          (add_terminator_cond_lessdef (insn_br id val l1 l2)\n                                                       (ite decision l1 l2))\n                          inv).\nProof.\n  inv STATE.\n  econs; eauto.\n  ii. unfold add_terminator_cond_lessdef in *. ss.\n  destruct (l_dec l1 l2).\n  { eapply LESSDEF; eauto. }\n  inv DECIDE.\n\n  destruct x as [e1 e2]. ss.\n\n  do 2 rewrite ExprPairSetFacts.add_iff in *.\n  des.\n  - clarify. ss.\n    solve_leibniz. clarify. ss.\n    rewrite AssnState.Unary.sem_valueT_physical in VAL1.\n    unfold ite in *.\n    unfold GV2int in INT.\n    unfold Size.to_nat, Size.One in *.\n    des_ifs; ss.\n    + rename n0 into wz.\n      esplits; ss. ss.\n      destruct wz; try omega.\n      specialize (int_sizezero_cases i0). i.\n      unfold val2GV. ss. econs; ss; cycle 1.\n      { apply list_forall2_nil. }\n      econs; eauto.\n      { (* value *)\n        des; subst; unfold Integers.Int.repr; ss. }\n      { split; ss. }\n    +  esplits; ss. ss.\n       rename n1 into wz.\n       destruct wz; try omega.\n       specialize (int_sizezero_cases i0). i.\n       unfold val2GV. ss. econs; ss; cycle 1.\n       { apply list_forall2_nil. }\n       econs; eauto.\n       { (* value *)\n         des; subst; unfold Integers.Int.repr; ss. }\n       { split; ss. }\n  - clarify. ss.\n    solve_leibniz. clarify. ss.\n    rewrite AssnState.Unary.sem_valueT_physical.\n    unfold ite in *.\n    unfold GV2int in INT.\n    unfold Size.to_nat, Size.One in *.\n    des_ifs; ss.\n    + esplits; ss; eauto.\n      rename n0 into wz.\n      destruct wz; try omega.\n      specialize (int_sizezero_cases i0). i.\n      unfold const2GV in *. des_ifs. ss. clarify. ss.\n      \n      unfold val2GV.\n      \n      econs; ss; cycle 1.\n      { apply list_forall2_nil. }\n      econs; eauto.\n      { (* value *)\n        des; subst; unfold Integers.Int.repr; ss. }\n      { ss. }\n    + esplits; ss; eauto.\n      rename n0 into wz.\n      destruct wz; try omega.\n      specialize (int_sizezero_cases i0). i.\n      unfold const2GV in *. des_ifs. ss. clarify. ss.\n      \n      unfold val2GV.\n      \n      econs; ss; cycle 1.\n      { apply list_forall2_nil. }\n      econs; eauto.\n      { (* value *)\n        des; subst; unfold Integers.Int.repr; ss. }\n      { ss. }\n  - exploit LESSDEF; eauto.\nQed.\n\nLemma add_terminator_cond_br\n      conf_src conf_tgt\n      st_src st_tgt\n      invst assnmem inv\n      decision l1 l2\n      id_src val_src gval_src\n      id_tgt val_tgt gval_tgt\n      (STATE: AssnState.Rel.sem\n                conf_src conf_tgt st_src st_tgt\n                invst assnmem inv)\n      (VAL_SRC: getOperandValue\n                  conf_src.(CurTargetData)\n                  val_src\n                  st_src.(EC).(Locals)\n                  conf_src.(Globals) = Some gval_src)\n      (VAL_TGT: getOperandValue\n                  conf_tgt.(CurTargetData)\n                  val_tgt\n                  st_tgt.(EC).(Locals)\n                  conf_tgt.(Globals) = Some gval_tgt)\n      (DECIDE_SRC: decide_nonzero conf_src.(CurTargetData) gval_src decision)\n      (DECIDE_TGT: decide_nonzero conf_tgt.(CurTargetData) gval_tgt decision):\n  AssnState.Rel.sem\n    conf_src conf_tgt\n    st_src st_tgt\n    invst assnmem\n    (Postcond.add_terminator_cond\n       inv\n       (insn_br id_src val_src l1 l2)\n       (insn_br id_tgt val_tgt l1 l2) (ite decision l1 l2)).\nProof.\n  inv STATE.\n  econs; eauto; ss.\n  - eapply add_terminator_cond_br_unary; eauto.\n  - eapply add_terminator_cond_br_unary; eauto.\nQed.\n\nLemma get_lessdef_spec\n      ep assigns\n      (IN: ExprPairSet.In ep (Postcond.Phinode.get_lessdef assigns)):\n  exists phix phiv phity,\n    <<IN: In (Postcond.Phinode.assign_intro phix phity phiv) assigns>> /\\\n    __guard__\n      (<<DEFINEDNESS: ep = (Expr.value (ValueT.const (const_undef phity)),\n                            Expr.value (ValueT.id (Tag.physical, phix)))>> \\/\n       <<PAIR1: ep = (Expr.value (ValueT.id (Tag.physical, phix)),\n                      Expr.value (ValueT.lift Tag.previous phiv))>> \\/\n       <<PAIR2: ep = (Expr.value (ValueT.lift Tag.previous phiv),\n                      Expr.value (ValueT.id (Tag.physical, phix)))>>).\nProof.\n  cut\n    (exists phix phiv phity,\n        <<IN: In (Postcond.Phinode.assign_intro phix phity phiv) (rev assigns)>> /\\\n        __guard__\n          (<<DEFINEDNESS: ep = (Expr.value (ValueT.const (const_undef phity)),\n                            Expr.value (ValueT.id (Tag.physical, phix)))>> \\/\n           <<PAIR1: ep = (Expr.value (ValueT.id (Tag.physical, phix)),\n                          Expr.value (ValueT.lift Tag.previous phiv))>> \\/\n           <<PAIR2: ep = (Expr.value (ValueT.lift Tag.previous phiv),\n                          Expr.value (ValueT.id (Tag.physical, phix)))>>)).\n  { i. des. esplits; eauto. apply in_rev. eauto. }\n  unfold Postcond.Phinode.get_lessdef in IN.\n  rewrite <- fold_left_rev_right in IN.\n  rewrite <- fold_left_rev_right in IN.\n  rewrite <- map_rev in IN.\n  rewrite ExprPairSetFacts.union_iff in IN. des.\n  { (* assigns *)\n    induction (rev assigns); ss.\n    { apply ExprPairSetFacts.empty_iff in IN. done. }\n    destruct a. ss.\n    repeat rewrite -> ExprPairSetFacts.add_iff in IN. des.\n    - solve_leibniz.\n      esplits; eauto. right. left. eauto.\n    - solve_leibniz.\n      esplits; eauto. right. right. eauto.\n    - exploit IHl0; eauto. i. des. esplits; eauto.\n  }\n  { (* definedness *)\n    induction (rev assigns); ss.\n    { apply ExprPairSetFacts.empty_iff in IN. done. }\n    destruct a. ss.\n    repeat rewrite -> ExprPairSetFacts.add_iff in IN. des.\n    - solve_leibniz. esplits; eauto. left. eauto.\n    - exploit IHl0; eauto. i. des. esplits; eauto.\n  }\nQed.\n\nLemma phinode_assign_sound\n      conf phinodes b assigns\n      locals locals'\n      x ty v\n      (ASSIGNS: forallb_map (Postcond.Phinode.resolve (fst b)) phinodes = Some assigns)\n      (LOCALS': getIncomingValuesForBlockFromPHINodes\n                  conf.(CurTargetData) phinodes b conf.(Globals) locals = Some locals')\n      (UNIQUE_PHI: unique id_dec (List.map Postcond.Phinode.get_def assigns) = true)\n      (ASSIGN_IN: In (Postcond.Phinode.assign_intro x ty v) assigns)\n  : exists gv,\n    <<VAL_V: getOperandValue conf.(CurTargetData) v locals conf.(Globals) = Some gv>> /\\\n    <<VAL_X: getOperandValue conf.(CurTargetData) (value_id x) locals' conf.(Globals) = Some gv>>.\nProof.\n  revert_until b. induction phinodes; i; ss.\n  { inv ASSIGNS. ss. }\n  simtac. des.\n  - inv ASSIGN_IN.\n    assert (EQV: v = v0).\n    { match goal with\n      | [H1: getValueViaBlockFromValuels _ _ = Some v0,\n         H2: lookupAL _ _ _ = Some v |- _] => clear -H1 H2\n      end.\n      unfold getValueViaBlockFromValuels in *.\n      induction l0; ss; simtac.\n      eapply IHl0; eauto.\n    }\n    subst. esplits; eauto.\n    match goal with\n    | [H:_ |- (if ?c then _ else _) = _ ] => destruct c; try done\n    end.\n  - exploit IHphinodes; eauto. i. des.\n    esplits; eauto.\n    fold id. destruct (x == id5); ss. subst.\n    destruct (in_dec id_dec id5 (List.map Postcond.Phinode.get_def l2)); ss. contradict n.\n    replace id5 with (Postcond.Phinode.get_def (Postcond.Phinode.assign_intro id5 ty v)); eauto.\n    apply In_map; eauto.\nQed.\n\nLemma gv_chunks_match_typb_aux_implies_chunk_eq\n      gv mcs\n      (CHUNK: gv_chunks_match_typb_aux gv mcs)\n  :\n    <<CHUNK_EQ: List.map snd gv = mcs>>\n.\nProof.\n  exploit gv_chunks_match_typb_aux__gv_chunks_match_typ; eauto. i; des.\n  exploit vm_matches_typ__eq__snd; eauto. i. clarify.\n  rewrite util.snd_split__map_snd. ss.\nQed.\n\nLemma incomingPHINodes_lookup_chunk\n      TD phinodes blk gl ls idgs\n      (PHI: getIncomingValuesForBlockFromPHINodes TD phinodes blk gl ls = Some idgs)\n      phix phity phiv assigns\n      (ASSIGNS: In (Phinode.assign_intro phix phity phiv) assigns)\n      gv\n      (LOOKUP: lookupAL GenericValue idgs phix = Some gv)\n      (RESOLVE: forallb_map (Phinode.resolve blk.(fst)) phinodes = Some assigns)\n      (UNIQUE_PHI: unique id_dec (List.map Phinode.get_def assigns) = true)\n      mcs\n      (FLATTEN: flatten_typ TD phity = Some mcs)\n  :\n    <<CHUNK: gv_chunks_match_typb_aux gv mcs>>\n    (* <<CHUNK: List.map snd gv = mcs>> *)\n.\nProof.\n  red.\n  ginduction phinodes; ii; ss; clarify.\n  des_ifs.\n  ss.\n  des_ifs_safe.\n  destruct (phix == id5); ss.\n  - clarify. des_ifs_safe.\n    unfold gv_chunks_match_typb in *. des_ifs_safe.\n    des.\n    { clarify. }\n    { repeat (des_bool; des; des_sumbool; clarify).\n      exfalso. clear - UNIQUE_PHI ASSIGNS.\n      apply UNIQUE_PHI. clear UNIQUE_PHI.\n      ginduction l0; ii; ss.\n      des; clarify; ss.\n      - left; ss.\n      - right. eapply IHl0; eauto.\n    }\n  - des_ifs_safe.\n    repeat (des_bool; des; des_sumbool; clarify).\n    { eapply IHphinodes; eauto. }\nQed.\n\nLemma phinodes_add_lessdef_sound\n      conf st0 st1 gmax public\n      l_to phinodes cmds terminator\n      invst assnmem inv0\n      assigns\n      (STEP: switchToNewBasicBlock conf.(CurTargetData)\n                                   (l_to, stmts_intro phinodes cmds terminator)\n                                   st0.(EC).(CurBB)\n                                   conf.(Globals)\n                                   st0.(EC).(Locals) = Some st1.(EC).(Locals))\n      (ASSIGNS: forallb_map (Postcond.Phinode.resolve st0.(EC).(CurBB).(fst)) phinodes = Some assigns)\n      (UNIQUE_PHI: unique id_dec (List.map Postcond.Phinode.get_def assigns) = true)\n      (STATE: AssnState.Unary.sem conf st1 invst assnmem gmax public inv0)\n      (PREV: forall x, AssnState.Unary.sem_idT st0 invst (Tag.previous, x) =\n                          lookupAL _ st0.(EC).(Locals) x)\n  : AssnState.Unary.sem\n      conf st1 invst assnmem gmax public\n      (Hints.Assertion.update_lessdef (Postcond.postcond_phinodes_add_lessdef assigns) inv0).\nProof.\n  econs; try by inv STATE.\n  s. ii. apply ExprPairSet.union_1 in H.  des.\n  { eapply STATE; eauto. }\n  exploit get_lessdef_spec; eauto. i. des.\n  unfold switchToNewBasicBlock in *.\n  solve_match_bool. inv STEP. ss.\n  destruct (CurBB (EC st0)). ss. des_ifs.\n  exploit phinode_assign_sound; eauto; ss. i. des. ss.\n  exploit opsem_props.OpsemProps.updateValuesForNewBlock_spec4; eauto.\n  match goal with\n  | [H: updateValuesForNewBlock _ _ = _ |- _] => rewrite H; i\n  end.\n  unguardH x0. des; subst; ss.\n  - esplits.\n    + unfold AssnState.Unary.sem_idT. ss. eauto.\n    + exploit const2GV_undef; eauto. i. des.\n      exploit incomingPHINodes_lookup_chunk; eauto. intro CHUNK; des.\n      apply all_undef_lessdef_aux; eauto.\n      { rewrite x3.\n        apply gv_chunks_match_typb_aux_implies_chunk_eq in CHUNK.\n        rewrite <- CHUNK. ss. }\n      { clear - CHUNK.\n        ginduction gv; ii; ss.\n        des_ifs.\n        unfold is_true in *. repeat (des_bool; des; ss; clarify).\n        econs; eauto.\n      }\n  - esplits; [|reflexivity].\n    assert (GV_VAL1: gv = val1).\n    { unfold AssnState.Unary.sem_idT in VAL1. ss. congruence. }\n    subst.\n    unfold getOperandValue in VAL_V.\n    destruct phiv; eauto.\n    rewrite <- PREV in VAL_V. ss.\n  - esplits; [|reflexivity].\n    assert (GV_VAL1: gv = val1).\n    { destruct phiv; ss.\n      - rewrite <- PREV in VAL_V.\n        unfold AssnState.Unary.sem_idT in *. ss. congruence.\n      - congruence.\n    }\n    subst. eauto.\nQed.\n\nLemma phinodes_progress_getPhiNodeID_safe\n      TD phinodes b gl locals locals' id assigns\n      (GETINC: getIncomingValuesForBlockFromPHINodes TD phinodes b\n                                                     gl locals = Some locals')\n      (IN: In id (List.map getPhiNodeID phinodes))\n      (RESOLVE : forallb_map (Postcond.Phinode.resolve (fst b)) phinodes = Some assigns)\n  :\n    <<IN: In id (List.map Postcond.Phinode.get_def assigns)>>.\nProof.\n  revert_until gl. induction phinodes; ss. i. simtac.\n  des; auto. exploit IHphinodes; eauto.\nQed.\n\nLemma locals_equiv_after_phinode\n      conf l_to phinodes cmds tmn b assigns\n      locals locals'\n      (SWITCH: switchToNewBasicBlock conf.(CurTargetData)\n                                     (l_to, stmts_intro phinodes cmds tmn)\n                                     b conf.(Globals) locals = Some locals')\n      (RESOLVE: forallb_map (Postcond.Phinode.resolve b.(fst)) phinodes = Some assigns)\n  :\n    <<EQUIV: locals_equiv_except (AtomSetImpl_from_list (List.map Postcond.Phinode.get_def assigns))\n                                 locals locals'>>.\nProof.\n  ii. unfold switchToNewBasicBlock in SWITCH. simtac.\n  apply opsem_props.OpsemProps.updateValuesForNewBlock_spec5; ss.\n  destruct (in_dec id_dec id0 (List.map getPhiNodeID phinodes)).\n  - exploit phinodes_progress_getPhiNodeID_safe; eauto. i. des.\n    contradict NOT_MEM. unfold not.\n    apply eq_true_false_abs, AtomSetImpl_from_list_spec. eauto.\n  - hexploit opsem_props.OpsemProps.getIncomingValuesForBlockFromPHINodes_spec8; eauto. i.\n    exploit notin_lookupAL_None; eauto.\nQed.\n\nLemma IdTSet_from_list_spec':\n  forall ids id0, IdTSet.mem id0 (IdTSetFacts.from_list ids) = false <-> ~ In id0 ids.\nProof.\n  split; i.\n  - ii. apply IdTSet_from_list_spec in H0. congruence.\n  - apply not_true_iff_false. ii.\n    apply IdTSet_from_list_spec in H0. eauto.\nQed.\n\nLemma lookupAL_reverse_aux\n      X lbl l v\n      (IN_REV: lookupAL X (List.map (fun x => (snd x, fst x)) l) lbl = Some v)\n  : In (v, lbl) l.\nProof.\n  revert IN_REV.\n  induction l; ss.\n  des_ifs.\n  - i. clarify. left. destruct a; eauto.\n  - i. right. eauto.\nQed.\n\nLemma resolve_eq_getValueViaLabelFromValuels\n      l_from phinodes passigns\n      p ty vls v\n      (RESOLVE : forallb_map (Phinode.resolve l_from) phinodes = Some passigns)\n      (UNIQUE_ID : unique id_dec (List.map Phinode.get_def passigns) = true)\n      (IN_PHIS: In (insn_phi p ty vls) phinodes)\n      (GET_VALUE: getValueViaLabelFromValuels vls l_from = Some v)\n  : In (Phinode.assign_intro p ty v) passigns.\nProof.\n  revert dependent passigns.\n  revert IN_PHIS.\n  induction phinodes; ss; i.\n  des_ifs. des.\n  - subst. ss. des_ifs.\n    assert (XX: v = v0).\n    { clear -GET_VALUE Heq1.\n      induction vls; ss.\n      des_ifs. exploit IHvls; eauto.\n    }\n    subst. eauto.\n  - exploit IHphinodes; eauto.\n    + ss. des_bool. des. eauto.\n    + i. ss. right. eauto.\nQed.\n\nLemma wf_const_valid_ptr\n      conf st0 assnmem phinodes gmax public\n  (MEM : AssnMem.Unary.sem conf gmax public (Mem st0) assnmem)\n  (WF_SUBSET : Forall\n                (fun phi : phinode =>\n                 exists b : block, phinodeInBlockB phi b /\\ blockInFdefB b (CurFunction (EC st0))) phinodes)\n  reg val' t1 vls1 const5\n  nextbb\n  (WF_INSN: wf_insn (CurSystem conf)\n                    conf\n                    (CurFunction (EC st0)) nextbb (insn_phinode (insn_phi reg t1 vls1)))\n  (INCOMING_IN : In (insn_phi reg t1 vls1) phinodes)\n  (INCOMING_VALUES : getValueViaLabelFromValuels vls1 (getBlockLabel (CurBB (EC st0))) = Some (value_const const5))\n  (INCOMING_GET : const2GV (CurTargetData conf) (Globals conf) const5 = Some val')\n  :\n    <<VALID_PTR: memory_props.MemProps.valid_ptrs (gmax + 1)%positive val'>>\n.\nProof.\n  move WF_SUBSET at bottom.\n  rewrite List.Forall_forall in WF_SUBSET.\n  specialize (WF_SUBSET (insn_phi reg t1 vls1) INCOMING_IN). des.\n\n  inv WF_INSN. clear H7 H8.\n  exploit H6.\n  {\n    instantiate (1:= value_const const5).\n    exploit infrastructure_props.getValueViaLabelFromValuels__InValueList; eauto.\n    intros IN_CONST.\n    clear - IN_CONST.\n    {\n      induction vls1; ss.\n      des_ifs.\n      des; clarify.\n      - left; ss.\n      - right; ss. eapply IHvls1; eauto.\n    }\n  (* split_combine *)\n  (* in_combine_l *)\n  }\n  intro WF_VALUE. ss. des.\n\n  inv WF_VALUE. destruct conf; ss. des_ifs.\n  symmetry in INCOMING_GET.\n\n  inv MEM.\n  clear WF PRIVATE_PARENT MEM_PARENT UNIQUE_PARENT_MEM\n        UNIQUE_PARENT_GLOBALS UNIQUE_PRIVATE_PARENT NEXTBLOCK.\n  rename GLOBALS into WF_GLOBALS.\n  eapply wf_globals_eq in WF_GLOBALS.\n\n  exploit MemAux.wf_globals_const2GV; eauto.\n  eapply wf_globals_eq; eauto.\nQed.\n\nLemma wf_const_diffblock\n      conf st0 assnmem phinodes gmax public\n  (MEM : AssnMem.Unary.sem conf gmax public (Mem st0) assnmem)\n  (WF_SUBSET : Forall\n                (fun phi : phinode =>\n                 exists b : block, phinodeInBlockB phi b /\\ blockInFdefB b (CurFunction (EC st0))) phinodes)\n  val reg val' t1 vls1 const5\n  nextbb\n  (WF_INSN: wf_insn (CurSystem conf)\n                    conf\n                    (CurFunction (EC st0)) nextbb (insn_phinode (insn_phi reg t1 vls1)))\n  (GLOBALS : forall b : Values.block, In b (GV2blocks val) -> (gmax < b)%positive)\n  (INCOMING_IN : In (insn_phi reg t1 vls1) phinodes)\n  (INCOMING_VALUES : getValueViaLabelFromValuels vls1 (getBlockLabel (CurBB (EC st0))) = Some (value_const const5))\n  (INCOMING_GET : const2GV (CurTargetData conf) (Globals conf) const5 = Some val')\n  :\n    <<DIFFBLOCK: AssnState.Unary.sem_diffblock conf val val'>>\n.\nProof.\n  ii.\n  exploit wf_const_valid_ptr; eauto; []; ii; des.\n  eapply valid_ptr_globals_diffblock; eauto.\nQed.\n\nLemma wf_phinodes_wf_insn\n      reg t1 vls1 phinodes5\n      (INCOMING_IN: In (insn_phi reg t1 vls1) phinodes5)\n      CurFunction0 CurSystem0 stmts md\n      (WF: wf_phinodes CurSystem0 md CurFunction0\n                       stmts phinodes5)\n  :\n    <<WF: wf_insn CurSystem0 md CurFunction0 stmts (insn_phinode (insn_phi reg t1 vls1))>>\n.\nProof.\n  ginduction phinodes5; ii; ss.\n  inv WF.\n  des.\n  - clarify.\n  - eapply IHphinodes5; eauto.\nQed.\n\nLemma wf_ec_lookup_wf_ec\n      st0\n      l_to\n      conf\n      phinodes5 cmds_src terminator_src\n      (LOOKUP: lookupAL stmts (get_blocks (CurFunction (EC st0))) l_to =\n               Some (stmts_intro phinodes5 cmds_src terminator_src))\n      (WF_FDEF: wf_fdef (CurSystem conf) (OpsemAux.module_of_conf conf) (CurFunction (EC st0)))\n      (WF_EC: OpsemAux.wf_EC (EC st0))\n      locals_src\n  :\n    <<WF: OpsemAux.wf_EC\n            {|\n              CurFunction := CurFunction (EC st0);\n              CurBB := (l_to, stmts_intro phinodes5 cmds_src terminator_src);\n              CurCmds := cmds_src;\n              Terminator := terminator_src;\n              Locals := locals_src;\n              Allocas := Allocas (EC st0) |}>>\n.\nProof.\n  inv WF_EC.\n  econs; ss; eauto.\n  - unfold get_blocks in *. des_ifs.\n    destruct st0; ss. destruct EC0; ss. clarify.\n    clear - LOOKUP.\n    (* TODO: pull out lemma? Use Set Printing All and then pull out, otherwise type checking fails *)\n    ginduction blocks5; ii; ss.\n    apply orb_true_iff.\n    des_ifs.\n    + left. unfold blockEqB. unfold sumbool2bool. des_ifs.\n    + right. eapply IHblocks5; eauto.\n  - autounfold. ss.\n    apply sublist_refl.\n  - unfold terminatorEqB. unfold sumbool2bool. des_ifs.\nQed.\n\nHint Unfold OpsemAux.get_cmds_from_block. (* TODO: move to definition point *)\nHint Unfold OpsemAux.module_of_conf. (* TODO: move to definition point *)\n\n(* st0 is the state before entering \"phinodes\". *)\n(* Therefore, phinodes in st0.(EC).(CurBB) <> \"phinodes\". *)\n(* st0.(EC).(CurBB) is the block before \"phinodes\". *)\n(* \"nextbb\" represents block of the \"phinodes\". *)\n(* It is introduced for \"WF_PHIS\" only. *)\nLemma phinodes_unique_preserved_except\n      conf st0 inv0 assnmem invst\n      l_to phinodes cmds terminator locals l0\n      gmax public\n      (STATE : AssnState.Unary.sem conf st0 invst assnmem gmax public inv0)\n      (MEM : AssnMem.Unary.sem conf gmax public st0.(Mem) assnmem)\n      (RESOLVE : forallb_map (Phinode.resolve (fst (CurBB (EC st0)))) phinodes = Some l0)\n      (UNIQUE_ID : unique id_dec (List.map Phinode.get_def l0) = true)\n      (STEP : switchToNewBasicBlock (CurTargetData conf) (l_to, stmts_intro phinodes cmds terminator)\n                                    (CurBB (EC st0)) (Globals conf) (Locals (EC st0)) = Some locals)\n      nextbb\n      (WF_PHIS: wf_phinodes (CurSystem conf) conf (CurFunction (EC st0)) nextbb phinodes)\n      (WF_SUBSET: List.Forall (fun phi =>\n                          exists b,\n                            insnInBlockB (insn_phinode phi) b\n                            /\\ blockInFdefB b (CurFunction (EC st0))) phinodes)\n  : unique_preserved_except conf inv0 assnmem.(AssnMem.Unary.unique_parent)\n                                               (mkState (mkEC\n                                                           st0.(EC).(CurFunction)\n                                                                      (l_to, stmts_intro phinodes cmds terminator)\n                                                                      cmds\n                                                                      terminator\n                                                                      locals\n                                                                      st0.(EC).(Allocas))\n                                                        st0.(ECS) st0.(Mem))\n                                               gmax\n                                               (AtomSetImpl.union (AtomSetImpl_from_list (List.map Phinode.get_def l0))\n                                                                  (AtomSetImpl_from_list (filter_map Phinode.get_use l0))).\nProof.\n  econs; ss.\n  - i.\n    rewrite <- AtomSetFacts.not_mem_iff in *.\n    hexploit notin_union_1; eauto. intro NOT_IN_DEF.\n    hexploit notin_union_2; eauto. intro NOT_IN_USE.\n    rewrite AtomSetImpl_from_list_spec2 in *.\n\n    inv STATE.\n    rewrite <- AtomSetFacts.mem_iff in *.\n    exploit UNIQUE; eauto. intro UNIQUE_U.\n\n    unfold switchToNewBasicBlock in STEP. des_ifs.\n    inv UNIQUE_U.\n    econs; eauto; ss.\n    + rewrite opsem_props.OpsemProps.updateValuesForNewBlock_spec7'; eauto.\n      eapply opsem_props.OpsemProps.getIncomingValuesForBlockFromPHINodes_spec8; eauto.\n      ss. ii.\n      exploit phinodes_progress_getPhiNodeID_safe; eauto.\n    + i.\n      destruct (AtomSetImpl.mem reg (dom l1)) eqn:REG_MEM.\n      { rewrite <- AtomSetFacts.mem_iff in REG_MEM.\n        hexploit indom_lookupAL_Some; eauto. i. des.\n        exploit opsem_props.OpsemProps.getIncomingValuesForBlockFromPHINodes_spec9'; eauto.\n        intros INCOMING. destruct INCOMING as [t1 [vls1 [v [INCOMING_IN [INCOMING_VALUES INCOMING_GET]]]]].\n        (* better way to name it?? *)\n\n        exploit resolve_eq_getValueViaLabelFromValuels; eauto. intro IN_PASSIGNS.\n        rewrite opsem_props.OpsemProps.updateValuesForNewBlock_spec6' in *; eauto. clarify.\n        destruct v as [y|].\n        - ss. eapply LOCALS; [| eauto].\n          ii. subst.\n          apply NOT_IN_USE. clarify.\n          eapply filter_map_spec; eauto.\n        - eapply wf_const_diffblock; eauto.\n          eapply wf_phinodes_wf_insn; eauto.\n      }\n      { rewrite <- AtomSetFacts.not_mem_iff in REG_MEM.\n        rewrite opsem_props.OpsemProps.updateValuesForNewBlock_spec7' in VAL'; eauto.\n      }\n  - inv STATE.\n    i. unfold switchToNewBasicBlock in *.\n    des_ifs.\n    destruct (AtomSetImpl.mem x (dom l1)) eqn:REG_MEM.\n    { rewrite <- AtomSetFacts.mem_iff in REG_MEM.\n      hexploit indom_lookupAL_Some; eauto. i. des.\n      exploit opsem_props.OpsemProps.getIncomingValuesForBlockFromPHINodes_spec9'; eauto. i. des.\n      ss.\n\n      \n      exploit phinode_assign_sound; eauto.\n      { eapply resolve_eq_getValueViaLabelFromValuels; eauto. }\n      i. des.\n      apply opsem_props.OpsemProps.updateValuesForNewBlock_spec4 with (lc:=st0.(EC).(Locals)) in VAL_X.\n      clarify.\n      destruct v as [y|]; ss.\n      - eapply UNIQUE_PARENT_LOCAL; eauto.\n      - hexploit wf_const_valid_ptr; eauto.\n        { eapply wf_phinodes_wf_insn; eauto.\n        }\n        intro VALID_PTR; des.\n        inv MEM.\n        eapply valid_ptr_globals_diffblock_with_blocks; eauto.\n    }\n    { rewrite <- AtomSetFacts.not_mem_iff in REG_MEM.\n      rewrite opsem_props.OpsemProps.updateValuesForNewBlock_spec7' in PTR; eauto.\n    }\n  - inv MEM. eauto.\n  - inv MEM. eauto.\nUnshelve.\nss.\nQed.\n\nLemma switchToNewBasicBlock_wf\n      conf mem locals locals'\n      l_from l_to stmts\n      (WF_LOCAL : memory_props.MemProps.wf_lc mem locals)\n      (STEP: switchToNewBasicBlock (CurTargetData conf) (l_to, stmts)\n                                   l_from (Globals conf) locals = Some locals')\n      gmax public assnmem\n      (* st0 invst0 inv0 *)\n      (* (STATE: AssnState.Unary.sem conf st0 invst0 assnmem0 gmax public inv0) *)\n      (MEM : AssnMem.Unary.sem conf gmax public mem assnmem)\n  : memory_props.MemProps.wf_lc mem locals'.\nProof.\n  unfold switchToNewBasicBlock in *. des_ifs.\n  intros x gvx Hx.\n  destruct (AtomSetImpl.mem x (dom l0)) eqn:REG_MEM.\n  { rewrite <- AtomSetFacts.mem_iff in REG_MEM.\n    hexploit indom_lookupAL_Some; eauto. i. des.\n    exploit opsem_props.OpsemProps.getIncomingValuesForBlockFromPHINodes_spec9'; eauto. i. des.\n    (* assert(H2:= H). *)\n    apply opsem_props.OpsemProps.updateValuesForNewBlock_spec4 with (lc:=locals) in H. clarify.\n    {\n      destruct v; ss.\n      - eapply WF_LOCAL; eauto.\n      - inv MEM.\n        exploit MemAux.wf_globals_const2GV; eauto; []; ii; des.\n        unfold memory_props.MemProps.wf_Mem in WF. des.\n        clear - WF0 x4.\n        eapply memory_props.MemProps.valid_ptrs__trans; eauto.\n        eapply Pos.lt_succ_r.\n        replace (gmax + 1)%positive with (Pos.succ gmax); cycle 1.\n        { destruct gmax; ss. }\n        rewrite <- Pos.succ_lt_mono; eauto.\n    }\n  }\n  { rewrite <- AtomSetFacts.not_mem_iff in REG_MEM.\n    rewrite opsem_props.OpsemProps.updateValuesForNewBlock_spec7' in Hx; eauto.\n  }\nQed.\n\nLemma lookup_implies_wf_subset\n      st0 l_to phinodes cmds terminator\n      (STMT : lookupAL stmts (get_blocks (CurFunction (EC st0))) l_to =\n                  Some (stmts_intro phinodes cmds terminator))\n  :\n    <<WF_SUBSET: List.Forall\n      (fun phi : phinode =>\n         exists b : block, insnInBlockB (insn_phinode phi) b /\\ blockInFdefB b (CurFunction (EC st0)))\n      phinodes>>\n.\nProof.\n  destruct st0; ss. destruct EC0; ss. destruct CurFunction0; ss.\n  clear - phinodes STMT.\n  red.\n  rewrite List.Forall_forall.\n  i.\n  induction blocks5; ii; ss.\n  destruct a; ss.\n  rename s into __s__.\n  des_ifs.\n  - esplits; eauto; cycle 1.\n    + unfold is_true.\n      rewrite orb_true_iff.\n      left. instantiate (1:= (l0, stmts_intro phinodes cmds terminator)).\n      rewrite infrastructure_props.blockEqB_refl. ss.\n    + ss. clear - H.\n      apply infrastructure_props.In_InPhiNodesB; ss.\n  - exploit IHblocks5; eauto; []; ii; des.\n    esplits; eauto.\n    unfold is_true.\n    rewrite orb_true_iff.\n    right.\n    ss.\nQed.\n\nLemma postcond_phinodes_sound\n      m_src conf_src st0_src phinodes_src cmds_src terminator_src locals_src\n      m_tgt conf_tgt st0_tgt phinodes_tgt cmds_tgt terminator_tgt locals_tgt\n      invst0 assnmem inv0 inv1\n      l_from l_to\n      (CONF: AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (CMD_SRC: st0_src.(EC).(CurCmds) = [])\n      (CMD_TGT: st0_tgt.(EC).(CurCmds) = [])\n      (L_SRC: st0_src.(EC).(CurBB).(fst) = l_from)\n      (L_TGT: st0_tgt.(EC).(CurBB).(fst) = l_from)\n      (STMT_SRC: lookupAL stmts st0_src.(EC).(CurFunction).(get_blocks) l_to =\n                 Some (stmts_intro phinodes_src cmds_src terminator_src))\n      (STMT_TGT: lookupAL stmts st0_tgt.(EC).(CurFunction).(get_blocks) l_to =\n                 Some (stmts_intro phinodes_tgt cmds_tgt terminator_tgt))\n      (POSTCOND: Postcond.postcond_phinodes l_from phinodes_src phinodes_tgt inv0 = Some inv1)\n      (STATE: AssnState.Rel.sem conf_src conf_tgt st0_src st0_tgt invst0 assnmem inv0)\n      (MEM: AssnMem.Rel.sem conf_src conf_tgt st0_src.(Mem) st0_tgt.(Mem) assnmem)\n      (STEP_SRC: switchToNewBasicBlock\n                   conf_src.(CurTargetData)\n                   (l_to, stmts_intro phinodes_src cmds_src terminator_src)\n                   st0_src.(EC).(CurBB)\n                   conf_src.(Globals)\n                   st0_src.(EC).(Locals)\n                 = Some locals_src)\n      (STEP_TGT: switchToNewBasicBlock\n                   conf_tgt.(CurTargetData)\n                   (l_to, stmts_intro phinodes_tgt cmds_tgt terminator_tgt)\n                   st0_tgt.(EC).(CurBB)\n                   conf_tgt.(Globals)\n                   st0_tgt.(EC).(Locals)\n                 = Some locals_tgt):\n  exists invst1,\n    <<STATE: AssnState.Rel.sem\n               conf_src conf_tgt\n               (mkState\n                  (mkEC\n                     st0_src.(EC).(CurFunction)\n                     (l_to, stmts_intro phinodes_src cmds_src terminator_src)\n                     cmds_src\n                     terminator_src\n                     locals_src\n                     st0_src.(EC).(Allocas))\n                  st0_src.(ECS)\n                  st0_src.(Mem))\n               (mkState\n                  (mkEC\n                     st0_tgt.(EC).(CurFunction)\n                     (l_to, stmts_intro phinodes_tgt cmds_tgt terminator_tgt)\n                     cmds_tgt\n                     terminator_tgt\n                     locals_tgt\n                     st0_tgt.(EC).(Allocas))\n                  st0_tgt.(ECS)\n                  st0_tgt.(Mem))\n               invst1 assnmem inv1>>.\nProof.\n  unfold Postcond.postcond_phinodes in *.\n  unfold Postcond.postcond_phinodes_assigns in *.\n  clarify.\n  des_ifs_safe ss. clarify.\n  des_bool. des.\n  (* simtac. *) (* TODO: simtac LOSES INFORMATION on PHIS_SRC/PHIS_TGT *)\n  (* TODO: REMOVE ALL SIMTAC *)\n  exploit snapshot_sound; eauto. i. des.\n\n  exploit forget_stack_sound; [eauto|eauto|eauto|eauto|eauto|eauto|eauto|..].\n  { instantiate (1 := mkState (mkEC _ _ _ _ _ _) _ _). econs; s; eauto.\n    eapply locals_equiv_after_phinode; eauto.\n  }\n  { instantiate (1 := mkState (mkEC _ _ _ _ _ _) _ _). econs; s; eauto.\n    eapply locals_equiv_after_phinode; eauto.\n    rewrite L_TGT. eauto.\n  }\n  { inv STATE_SNAPSHOT. inv MEM.\n    instantiate (6:= (_, stmts_intro phinodes_src _ _)).\n    eapply phinodes_unique_preserved_except; eauto.\n    { instantiate (1:= (l_to, (stmts_intro phinodes_src cmds_src terminator_src))).\n      inv STATE. inv SRC.\n      clear - STMT_SRC WF_EC WF_FDEF.\n      rpapply typings_props.wf_fdef__wf_phinodes; eauto. Undo 1.\n      destruct st0_src; ss. destruct EC0; ss. destruct CurBB0; ss. destruct s; ss.\n      eapply typings_props.wf_fdef__wf_phinodes; eauto.\n      rpapply infrastructure_props.lookupBlock_blocks_inv; try eassumption. Undo 1.\n      destruct CurFunction0.\n      rpapply infrastructure_props.lookupBlock_blocks_inv; eauto.\n    }\n    { eapply lookup_implies_wf_subset; eauto. }\n  }\n  { inv STATE_SNAPSHOT. inv MEM.\n    instantiate (6:= (_, stmts_intro phinodes_tgt _ _)).\n    eapply phinodes_unique_preserved_except; eauto.\n    { rewrite L_TGT. ss. }\n    { instantiate (1:= (l_to, (stmts_intro phinodes_tgt cmds_tgt terminator_tgt))).\n      inv STATE. inv TGT.\n      clear - STMT_TGT WF_EC WF_FDEF.\n      rpapply typings_props.wf_fdef__wf_phinodes; eauto. Undo 1.\n      destruct st0_tgt; ss. destruct EC0; ss. destruct CurBB0; ss. destruct s; ss.\n      eapply typings_props.wf_fdef__wf_phinodes; eauto.\n      rpapply infrastructure_props.lookupBlock_blocks_inv; try eassumption. Undo 1.\n      destruct CurFunction0.\n      rpapply infrastructure_props.lookupBlock_blocks_inv; eauto.\n    }\n    { eapply lookup_implies_wf_subset; eauto. }\n  }\n  { eapply switchToNewBasicBlock_wf; try exact STEP_SRC; eauto. apply STATE. apply MEM. }\n  { eapply switchToNewBasicBlock_wf; try exact STEP_TGT; eauto. apply STATE. apply MEM. }\n  { ss. }\n  { ss. }\n  { apply STATE. }\n  { apply STATE. }\n  { apply STATE. }\n  { apply STATE. }\n  { apply STATE. }\n  { eapply wf_ec_lookup_wf_ec; eauto; try apply STATE. }\n  { eapply wf_ec_lookup_wf_ec; eauto; try apply STATE. }\n  intros STATE_FORGET. des.\n  inv STATE_FORGET.\n  exploit phinodes_add_lessdef_sound; try exact SRC; eauto; i.\n  exploit phinodes_add_lessdef_sound; try exact TGT; eauto; i.\n  { rewrite L_TGT. eauto. }\n  exploit reduce_maydiff_sound; swap 1 2.\n  { instantiate (1 := Hints.Assertion.mk _ _ _). econs; eauto. }\n  { eauto. }\n  { eauto. }\n  intro STATE_MAYDIFF. exact STATE_MAYDIFF.\nQed.\n", "meta": {"author": "snu-sf", "repo": "crellvm", "sha": "668249b88756233f96b3ef21f12993501a348afc", "save_path": "github-repos/coq/snu-sf-crellvm", "path": "github-repos/coq/snu-sf-crellvm/crellvm-668249b88756233f96b3ef21f12993501a348afc/coq/proof/SoundPostcondPhinodes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2459192903550164}}
{"text": "From RecordUpdate Require Import RecordSet.\n\nFrom Perennial.program_proof Require Import disk_lib.\nFrom Perennial.program_proof Require Import wal.invariant wal.common_proof.\n\nSection goose_lang.\nContext `{!heapGS Σ}.\nContext `{!walG Σ}.\n\nImplicit Types (v:val) (z:Z).\nImplicit Types (γ: wal_names).\nImplicit Types (s: log_state.t) (memLog: list update.t) (txns: list (u64 * list update.t)).\nImplicit Types (pos: u64) (txn_id: nat).\n\nContext (P: log_state.t -> iProp Σ).\nLet N := walN.\nLet innerN := walN .@ \"wal\".\nLet circN := walN .@ \"circ\".\n\nTheorem wal_wf_update_durable :\n  relation.wf_preserved (update_durable) wal_wf.\nProof.\n  intros s1 s2 [] Hwf ?; simpl in *; monad_inv.\n  destruct Hwf as (Hwf1&Hwf2&Hwf3).\n  destruct s1; split; unfold log_state.updates in *; simpl in *; eauto.\n  split; eauto.\n  lia.\nQed.\n\n(* just an example, to work out the Flush proof without all the complications *)\nTheorem wp_updateDurable (Q: iProp Σ) l γ dinit :\n  {{{ is_wal P l γ dinit ∗\n       (∀ σ σ' b,\n         ⌜wal_wf σ⌝ -∗\n         ⌜relation.denote (update_durable) σ σ' b⌝ -∗\n         (P σ ={⊤ ∖ ↑N}=∗ P σ' ∗ Q))\n   }}}\n    Skip\n  {{{ RET #(); Q}}}.\nProof.\n  iIntros (Φ) \"[#Hwal Hfupd] HΦ\".\n  iDestruct \"Hwal\" as \"[Hwal Hcirc]\".\n  iInv \"Hwal\" as \"Hinv\".\n  wp_call.\n  iDestruct \"Hinv\" as (σ) \"(Hinner&HP)\".\n  iNamed \"Hinner\".\n  iNamed \"Hdisk\".\n  iNamed \"Hdisk\".\n  iNamed \"circ.end\".\n  pose proof (is_txn_bound _ _ _ Hend_txn) as Hend_bound.\n  iMod (fupd_mask_subseteq (⊤ ∖ ↑N)) as \"HinnerN\"; first by solve_ndisj.\n  iMod (\"Hfupd\" $! σ (set log_state.durable_lb (λ _, (σ.(log_state.durable_lb) `max` diskEnd_txn_id)%nat) σ)\n          with \"[% //] [%] [$HP]\") as \"[HP HQ]\".\n  { simpl.\n    econstructor; monad_simpl.\n    econstructor; monad_simpl; lia. }\n  iMod \"HinnerN\" as \"_\".\n  iSpecialize (\"HΦ\" with \"HQ\").\n  iFrame \"HΦ\".\n  iIntros \"!> !>\".\n  iExists _; iFrame \"HP\".\n  iSplit.\n  - iPureIntro.\n    eapply wal_wf_update_durable; eauto.\n    { simpl; monad_simpl.\n      econstructor; monad_simpl.\n      econstructor; monad_simpl; lia. }\n  - simpl.\n    iFrame.\n    iExists _. iFrame \"Howncs\".\n    iExists installed_txn_id, _, _. simpl. iFrame \"# ∗ %\".\n    iExists _, diskEnd_txn_id.\n    rewrite (Nat.max_l (_ `max` _)%nat _); last by lia.\n    iFrame \"# %\".\n    iPureIntro.\n    split; first by lia.\n    split; first by lia.\n    destruct (decide (σ.(log_state.durable_lb) ≤ diskEnd_txn_id)).\n    {\n      rewrite Nat.max_r; last by lia.\n      rewrite subslice_zero_length.\n      apply Forall_nil_2.\n    }\n    rewrite Nat.max_l; last by lia.\n    rewrite -(subslice_app_contig _ (S diskEnd_txn_id)) in Hdurable_nils;\n      last by lia.\n    apply Forall_app in Hdurable_nils.\n    intuition.\nQed.\n\nTheorem simulate_flush l γ Q σ dinit pos txn_id nextDiskEnd_txn_id mutable :\n  is_circular circN (circular_pred γ) γ.(circ_name) -∗\n  (is_wal_inner l γ σ dinit ∗ P σ) -∗\n  diskEnd_at_least γ.(circ_name) (int.Z pos) -∗\n  txn_pos γ txn_id pos -∗\n  memLog_linv_nextDiskEnd_txn_id γ mutable nextDiskEnd_txn_id -∗\n  (∀ (σ σ' : log_state.t) (b : ()),\n      ⌜wal_wf σ⌝\n        -∗ ⌜relation.denote (log_flush pos txn_id) σ σ' b⌝ -∗ P σ ={⊤ ∖ ↑N}=∗ P σ' ∗ Q) -∗\n  |NC={⊤ ∖ ↑innerN}=>\n    ∃ σ' nextDiskEnd_txn_id',\n      is_wal_inner l γ σ' dinit ∗ P σ' ∗ Q ∗\n      memLog_linv_nextDiskEnd_txn_id γ mutable nextDiskEnd_txn_id' ∗\n      ⌜nextDiskEnd_txn_id ≤ nextDiskEnd_txn_id' < length σ.(log_state.txns)⌝ ∗\n      ⌜Forall (λ x, x.2 = []) (\n        subslice (S nextDiskEnd_txn_id) (S nextDiskEnd_txn_id')\n        σ.(log_state.txns)\n      )⌝.\nProof.\n  iIntros \"#Hcirc Hinv #Hlb #Hpos_txn HstableSet Hfupd\".\n  iDestruct \"Hinv\" as \"[Hinner HP]\".\n  iNamed \"Hinner\".\n  iNamed \"Hdisk\".\n  iNamed \"Hdisk\".\n  iNamed \"circ.end\".\n  iMod (is_circular_diskEnd_lb_agree with \"Hlb Hcirc Howncs\") as \"(%Hlb&Howncs)\"; first by solve_ndisj.\n  iDestruct (txn_pos_valid_general with \"Htxns_ctx Hpos_txn\") as %His_txn.\n  pose proof (is_txn_bound _ _ _ His_txn).\n  pose proof (is_txn_bound _ _ _ Hend_txn).\n  pose proof (wal_wf_txns_mono_pos Hwf His_txn Hend_txn) as Hpos_diskEnd.\n\n  iMod (fupd_mask_subseteq (⊤ ∖ ↑N)) as \"HinnerN\"; first by solve_ndisj.\n  iMod (\"Hfupd\" $!\n    σ\n    (\n      set log_state.durable_lb (λ _,\n        (diskEnd_txn_id `max` (σ.(log_state.durable_lb) `max` txn_id))%nat\n      ) σ\n    )\n    with \"[% //] [%] HP\"\n  ) as \"[HP HQ]\".\n  { simpl; monad_simpl.\n    repeat (econstructor; monad_simpl; eauto); lia.\n  }\n  iMod \"HinnerN\" as \"_\".\n  iFrame \"HQ\".\n\n  iAssert (⌜\n    int.Z pos = int.Z diskEnd →\n    Forall (λ x, x.2 = []) (\n      subslice\n        (S (σ.(log_state.durable_lb) `max` diskEnd_txn_id))\n        (S txn_id)\n        σ.(log_state.txns)\n    )\n  ⌝)%I with \"[HstableSet HnextDiskEnd_inv]\" as \"%Hpos_diskEnd_nils\".\n  {\n    iApply pure_impl_2.\n    iIntros (Hpos_diskEnd_eq).\n    apply word.unsigned_inj in Hpos_diskEnd_eq.\n    rewrite Hpos_diskEnd_eq in His_txn.\n    iPoseProof (subslice_stable_nils2 with \"[HstableSet HnextDiskEnd_inv]\")\n      as \"Hnils\".\n    1: eassumption.\n    1: apply Hdurable_lb_pos.\n    1: apply His_txn.\n    {\n      iSplit; first by iFrame.\n      iFrame \"#\".\n    }\n    iFrame.\n  }\n\n  iAssert (|==>\n    ⌜Forall (λ x, x.2 = []) (\n      subslice\n        (S diskEnd_txn_id)\n        (S (diskEnd_txn_id `max` (txn_id)))\n        σ.(log_state.txns)\n    )⌝ ∗\n    (diskEnd_txn_id `max` (txn_id))%nat\n      [[γ.(stable_txn_ids_name)]]↦ro tt ∗\n    nextDiskEnd_inv γ σ.(log_state.txns) ∗\n    txns_ctx γ σ.(log_state.txns) ∗\n    ∃ nextDiskEnd_txn_id',\n      memLog_linv_nextDiskEnd_txn_id γ mutable nextDiskEnd_txn_id' ∗\n      ⌜nextDiskEnd_txn_id ≤ nextDiskEnd_txn_id' < length σ.(log_state.txns)⌝ ∗\n      ⌜Forall (λ x, x.2 = []) (\n        subslice (S nextDiskEnd_txn_id) (S nextDiskEnd_txn_id')\n        σ.(log_state.txns)\n      )⌝\n  )%I\n    with \"[HstableSet HnextDiskEnd_inv Htxns_ctx]\"\n    as \"H\".\n  {\n    destruct (decide (\n      txn_id ≤ diskEnd_txn_id\n    )%nat).\n    { rewrite -> (max_l diskEnd_txn_id _) by lia.\n      rewrite ?subslice_zero_length. iSplitR; first by done.\n\n      iAssert (⌜nextDiskEnd_txn_id < length σ.(log_state.txns)⌝)%I as \"%HnextDiskEnd_txn_bound\".\n      {\n        iNamed \"HstableSet\".\n        iDestruct (txn_pos_valid_general with \"Htxns_ctx HnextDiskEnd_txn\") as %HnextDiskEnd_txn_bound.\n        eapply is_txn_bound in HnextDiskEnd_txn_bound. iPureIntro. lia.\n      }\n\n      iFrame \"Hend_txn_stable\".\n      iFrame \"HnextDiskEnd_inv\".\n      iFrame \"Htxns_ctx\".\n      iExists nextDiskEnd_txn_id.\n      rewrite ?subslice_zero_length.\n      iFrame \"HstableSet\".\n      iModIntro.\n      iSplit; first by iPureIntro; lia.\n      iPureIntro.\n      eauto.\n    }\n\n    pose proof (wal_wf_txns_mono_pos Hwf His_txn Hend_txn).\n    replace diskEnd with pos in * by word.\n\n    iMod (stable_txn_id_advance _ _ _ txn_id\n          with \"HstableSet HnextDiskEnd_inv Hend_txn_stable Htxns_ctx\")\n      as \"H\"; eauto.\n    { lia. }\n\n    iDestruct \"H\" as \"(#Hstable & HnextDiskEnd_inv & Htxns_ctx & H)\".\n    iDestruct \"H\" as (nextDiskEnd_txn_id') \"(HstableSet & %Hle & %Hnils')\".\n    iModIntro.\n\n    iSplit.\n    {\n      iDestruct (subslice_stable_nils with \"[$HnextDiskEnd_inv $Hend_txn_stable]\") as \"%Hnils_txn\".\n      1: eassumption.\n      2: eassumption.\n      2: eapply His_txn.\n      1: lia.\n      iPureIntro.\n      destruct (decide (diskEnd_txn_id ≤ txn_id)%nat).\n      {\n        rewrite Nat.max_r; last by lia.\n        assumption.\n      }\n      rewrite Nat.max_l; last by lia.\n      rewrite subslice_zero_length.\n      apply Forall_nil_2.\n    }\n\n    iFrame \"HnextDiskEnd_inv\".\n    iSplitR.\n    {\n      destruct (decide (diskEnd_txn_id ≤ txn_id)%nat).\n      {\n        rewrite (Nat.max_r _ txn_id); last by lia.\n        iFrame \"#\".\n      }\n      rewrite (Nat.max_l _ txn_id); last by lia.\n      iFrame \"#\".\n    }\n    iFrame \"Htxns_ctx\".\n    iExists nextDiskEnd_txn_id'.\n    iFrame \"HstableSet\".\n    done.\n  }\n\n  iMod \"H\" as \"(%Hnils & #Hstable & HnextDiskEnd_inv & Htxns_ctx & H)\".\n  iDestruct \"H\" as (nextDiskEnd_txn_id') \"(HstableSet & %Hle & %Hnils')\".\n\n  iModIntro.\n  iExists _, _; iFrame \"HP\".\n  iFrame (Hle Hnils') \"HstableSet\".\n  iSplit; auto.\n  { iPureIntro.\n    eapply wal_wf_update_durable; eauto.\n    simpl; monad_simpl.\n    repeat (econstructor; monad_simpl; eauto); lia.\n  }\n  simpl.\n  iFrame.\n  iExists _; iFrame.\n  iExists installed_txn_id, _, _. iFrame \"# ∗\".\n  iSplitL.\n  2: {\n    iPureIntro.\n    auto with lia.\n  }\n  iExists _, diskEnd_txn_id.\n  simpl.\n  iSplit; first by (iPureIntro; lia).\n  iSplit; first by (iPureIntro; lia).\n  iSplit.\n  {\n    iPureIntro.\n    destruct (decide (\n      (diskEnd_txn_id `max` txn_id) ≤ σ.(log_state.durable_lb)\n    )%nat).\n    {\n      rewrite Nat.max_r; last by lia.\n      rewrite Nat.max_l; last by lia.\n      destruct (decide (S diskEnd_txn_id ≤ txn_id)%nat).\n      {\n        rewrite Nat.max_r in Hnils; last by lia.\n        rewrite -(subslice_app_contig _ (S diskEnd_txn_id)) in Hdurable_nils;\n          last by lia.\n        apply Forall_app in Hdurable_nils.\n        intuition.\n      }\n      rewrite -(subslice_app_contig _ (S diskEnd_txn_id)) in Hdurable_nils;\n        last by lia.\n      apply Forall_app in Hdurable_nils.\n      intuition.\n    }\n    replace (_ `max` (_ `max` _))%nat with (diskEnd_txn_id `max` txn_id)%nat\n      by lia.\n    assumption.\n  }\n  iSplit.\n  {\n    iPureIntro.\n    destruct (decide (int.Z pos < int.Z diskEnd)) as [Hcmp|Hcmp].\n    {\n      apply Hpos_diskEnd in Hcmp.\n      replace (_ `max` _)%nat\n        with (σ.(log_state.durable_lb) `max` diskEnd_txn_id)%nat\n        by lia.\n      eassumption.\n    }\n    rewrite -HdiskEnd_val in Hlb.\n    assert (int.Z pos = int.Z diskEnd) as Hpos_diskEnd_eq by lia.\n    apply word.unsigned_inj in Hpos_diskEnd_eq.\n    subst pos.\n    rewrite Nat.max_l; last by lia.\n    destruct (decide\n      ((σ.(log_state.durable_lb) `max` diskEnd_txn_id) ≤ txn_id)%nat\n    ).\n    {\n      rewrite Nat.max_r; last by lia.\n      rewrite Nat.max_r; last by lia.\n      assumption.\n    }\n    replace (_ `max` _)%nat\n      with (σ.(log_state.durable_lb) `max` diskEnd_txn_id)%nat; last by lia.\n    assumption.\n  }\n  iSplit; first by (iPureIntro; assumption).\n  iSplit; first by (iPureIntro; assumption).\n  destruct (decide (\n    txn_id ≤ (σ.(log_state.durable_lb) `max` diskEnd_txn_id)\n  )%nat).\n  {\n    replace ((_ `max` _) `max` _)%nat\n      with (σ.(log_state.durable_lb) `max` diskEnd_txn_id)%nat;\n      last by lia.\n    iFrame \"#\".\n  }\n  replace ((_ `max` _) `max` _)%nat\n    with (diskEnd_txn_id `max` txn_id)%nat; last by lia.\n  iFrame \"#\".\n\n  Unshelve.\n  all: try constructor.\nQed.\n\n(* this is a dumb memory safety proof for loading nextDiskEnd when its value\ndoesn't matter for correctness *)\nTheorem wp_load_some_nextDiskEnd st γ :\n  {{{ wal_linv st γ }}}\n        struct.loadF sliding \"mutable\"\n          (struct.loadF WalogState \"memLog\" #st)\n  {{{ (nextDiskEnd:u64), RET #nextDiskEnd; wal_linv st γ }}}.\nProof.\n  iIntros (Φ) \"Hinv HΦ\".\n  iNamed \"Hinv\".\n  iNamed \"Hfields\".\n  iNamed \"Hfield_ptsto\".\n  wp_loadField.\n  (* this is very bad, breaks sliding abstraction boundary *)\n  iNamed \"His_memLog\"; iNamed \"Hinv\". wp_loadField.\n  iApply \"HΦ\".\n  iExists _; iFrame \"# ∗\".\n  iExists _; iFrame \"# ∗\".\n  iSplit; auto.\n  iSplit; auto.\n  iExists _, _; iFrame \"# ∗\".\nQed.\n\nTheorem wp_Walog__Flush (Q: iProp Σ) l γ dinit txn_id pos :\n  {{{ is_wal P l γ dinit ∗\n      txn_pos γ txn_id pos ∗\n       (∀ σ σ' b,\n         ⌜wal_wf σ⌝ -∗\n         ⌜relation.denote (log_flush pos txn_id) σ σ' b⌝ -∗\n         (P σ ={⊤ ∖ ↑N}=∗ P σ' ∗ Q))\n   }}}\n    Walog__Flush #l #pos\n  {{{ RET #(); Q}}}.\nProof.\n  iIntros (Φ) \"(#Hwal & #Hpos_txn & Hfupd) HΦ\".\n  destruct_is_wal.\n\n  wp_apply util_proof.wp_DPrintf.\n  wp_loadField.\n  wp_apply (acquire_spec with \"lk\"). iIntros \"(Hlocked&Hlkinv)\".\n  wp_loadField.\n  wp_apply (wp_condBroadcast with \"cond_logger\").\n  wp_loadField.\n\n  wp_apply (wp_load_some_nextDiskEnd with \"Hlkinv\"); iIntros (x) \"Hlkinv\".\n  wp_pures.\n\n  wp_apply (wp_If_optional with \"[] [Hlkinv Hlocked]\"); [ | iAccu | ].\n  {\n    iIntros (Φ') \"(Hlkinv&Hlocked) HΦ\".\n    wp_loadField.\n    wp_apply (wp_endGroupTxn with \"Hlkinv\").\n    iIntros \"Hlkinv\".\n    wp_pures.\n    iApply (\"HΦ\" with \"[$]\").\n  }\n  iIntros \"(Hlkinv&Hlocked)\".\n  wp_pures.\n\n  wp_bind (For _ _ _).\n  wp_apply (wp_forBreak_cond (λ b,\n    wal_linv σₛ.(wal_st) γ ∗ locked #σₛ.(memLock) ∗\n    if b then ⊤ else diskEnd_at_least γ.(circ_name) (int.Z pos)\n  )%I with \"[] [$Hlkinv $Hlocked]\").\n  { iIntros \"!>\" (Φ') \"(Hlkinv&Hlocked&_) HΦ\".\n    wp_loadField.\n    iNamed \"Hlkinv\".\n    iNamed \"Hfields\".\n    iNamed \"Hfield_ptsto\".\n    wp_loadField.\n    wp_pures.\n    wp_if_destruct.\n    - wp_loadField.\n      wp_apply (wp_condWait with \"[-HΦ $cond_logger $lk $Hlocked]\").\n      { iExists _; iFrame \"∗ #\".\n        iExists _; by iFrame \"∗ #\". }\n      iIntros \"(Hlocked&Hlockin)\".\n      wp_pures.\n      iApply \"HΦ\"; by iFrame.\n    - iApply \"HΦ\".\n      iFrame \"Hlocked\".\n      iNamed \"HdiskEnd_circ\".\n      iSplitL.\n      { iExists _; iFrame \"# ∗\".\n        iExists _; by iFrame \"# ∗\". }\n      iApply (diskEnd_at_least_mono with \"HdiskEnd_at_least\"); auto.\n  }\n\n  iIntros \"(Hlkinv&Hlocked&#HdiskEnd_lb)\".\n  wp_seq.\n  wp_bind Skip.\n  iDestruct \"Hwal\" as \"[Hwal Hcirc]\".\n  iInv \"Hwal\" as \"Hinv\".\n  iApply wp_ncfupd.\n  wp_call.\n  iDestruct \"Hinv\" as (σ) \"[Hinner HP]\".\n  iNamed \"Hlkinv\".\n  iNamed \"HmemLog_linv\".\n\n  iAssert (⌜txns = σ.(log_state.txns)⌝)%I as \"%Htxnseq\".\n  {\n    iNamed \"Hinner\".\n    iDestruct (ghost_var_agree with \"Howntxns γtxns\") as \"%Htxnseq\".\n    done.\n  }\n  subst.\n\n  iMod (simulate_flush with \"Hcirc [$Hinner $HP] HdiskEnd_lb Hpos_txn HnextDiskEnd Hfupd\") as \"H\".\n  iDestruct \"H\" as (σ' nextDiskEnd_txn_id') \"(Hinner & HP & HQ & HnextDiskEnd & %Hle & %Hnils)\".\n  iApply fupd_ncfupd. iApply fupd_intro.\n  iModIntro.\n\n  iSplitL \"Hinner HP\".\n  { iNext. iExists _. iFrame. }\n\n  wp_loadField.\n  wp_apply (release_spec with \"[-HQ HΦ]\").\n  { iFrame \"lk\". iFrame \"Hlocked\". iNext. iExists _.\n    iFrame \"Hfields HdiskEnd_circ Hstart_circ\".\n    iExists _, _, _, _, _, _, _.\n    iFrame \"∗#%\".\n    iNamed \"Hlinv_pers\".\n    iFrame \"#%\".\n    iPureIntro.\n    split; first by (intuition (eauto; try lia)).\n    pose proof Htxns as [Hbnds Hregs].\n    split.\n    {\n      intros bndry Hbndry.\n      specialize (Hbnds bndry).\n      apply elem_of_list_lookup in Hbndry.\n      destruct Hbndry as [i Hbndry].\n      do 4 (destruct i; first by (\n        simpl in Hbndry; inversion Hbndry; subst bndry; clear Hbndry;\n        apply Hbnds; set_solver\n      )).\n      destruct i.\n      2: {\n        destruct i; first by (\n          simpl in Hbndry; inversion Hbndry; subst bndry; clear Hbndry;\n          apply Hbnds; set_solver\n        ).\n        inversion Hbndry.\n      }\n      simpl in Hbndry; inversion Hbndry; subst bndry; clear Hbndry.\n      simpl.\n      clear Hbnds.\n      pose proof Htxns as [Hbnds _].\n      unshelve (epose proof (Hbnds _ _) as Hbnd).\n      2: {\n        apply elem_of_list_lookup.\n        exists mwrb_us.\n        reflexivity.\n      }\n      simpl in Hbnd.\n      lia.\n    }\n    intros i bndry1 bndry2 Hbndry1 Hbndry2.\n    specialize (Hregs i bndry1 bndry2).\n    do 3 (destruct i; first by (\n      simpl in Hbndry1; inversion Hbndry1; subst bndry1; clear Hbndry1;\n      simpl in Hbndry2; inversion Hbndry2; subst bndry2; clear Hbndry2;\n      simpl; apply Hregs; reflexivity\n    )).\n    clear Hregs.\n    unshelve (epose proof (\n      is_memLog_boundaries_region_consec mwrb_uss _ _ _ _ _ Htxns _ _\n    ) as Hreg1).\n    3-4: reflexivity.\n    unshelve (epose proof (\n      is_memLog_boundaries_region_consec mwrb_us _ _ _ _ _ Htxns _ _\n    ) as Hreg2).\n    3-4: reflexivity.\n    simpl in Hreg1.\n    simpl in Hreg2.\n    destruct i.\n    {\n      simpl in Hbndry1; inversion Hbndry1; subst bndry1; clear Hbndry1;\n      simpl in Hbndry2; inversion Hbndry2; subst bndry2; clear Hbndry2.\n      simpl.\n      split; first by lia.\n      split; first by lia.\n      rewrite -(subslice_app_contig _ (S nextDiskEnd_txn_id)); last by lia.\n      apply is_memLog_region_append_nils; first by assumption.\n      intuition.\n    }\n    destruct i; last by inversion Hbndry2.\n    simpl in Hbndry1; inversion Hbndry1; subst bndry1; clear Hbndry1;\n    simpl in Hbndry2; inversion Hbndry2; subst bndry2; clear Hbndry2.\n    simpl.\n    split; first by lia.\n    split; first by lia.\n    eapply is_memLog_region_prepend_nils; first by eassumption.\n    rewrite subslice_app_contig; last by lia.\n    intuition.\n  }\n  wp_pures. by iApply (\"HΦ\" with \"HQ\").\nQed.\n\nEnd goose_lang.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/wal/flush_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2459192847130005}}
{"text": "Require Import Common.Definitions.\nRequire Import Common.Linking.\nRequire Import Common.Blame.\nRequire Import Common.CompCertExtensions.\nRequire Import CompCert.Smallstep.\nRequire Import CompCert.Behaviors.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* The repetition verbatim of theorem statements as axioms is\n   particularly annoying; we will want to eliminate this duplication.\n     [CH: Agreed, but easy to fix with some extra definitions.]\n\n   Naming conventions can also be harmonized.\n\n   The current proof is generic while still relying on our Common and\n   CompCert's infrastructure. [CH: I find this just fine for now.] *)\n\n(* CH: It seemed a bit strange that Program.interface is used\n       concretely, instead of being just another parameter below.\n       Same for linkable. It seems related to using everything in\n       Common though, and so it's just fine for now. *)\n\nModule Type Source_Sig.\n  Parameter program : Type.\n\n  Parameter prog_interface : program -> Program.interface.\n\n  Parameter well_formed_program : program -> Prop.\n\n  Parameter closed_program : program -> Prop.\n\n  Parameter linkable_mains : program -> program -> Prop.\n\n  Local Axiom linkable_mains_sym : forall prog1 prog2,\n    linkable_mains prog1 prog2 ->\n    linkable_mains prog2 prog1.\n\n  Local Axiom linkable_disjoint_mains: forall prog1 prog2,\n    well_formed_program prog1 ->\n    well_formed_program prog2 ->\n    linkable (prog_interface prog1) (prog_interface prog2) ->\n    linkable_mains prog1 prog2.\n\n  Parameter program_link : program -> program -> program.\n\n  Local Axiom linking_well_formedness : forall p1 p2,\n    well_formed_program p1 ->\n    well_formed_program p2 ->\n    linkable (prog_interface p1) (prog_interface p2) ->\n    well_formed_program (program_link p1 p2).\n\n  Local Axiom interface_preserves_closedness_l : forall p1 p2 p1',\n    closed_program (program_link p1 p2) ->\n    prog_interface p1 = prog_interface p1' ->\n    well_formed_program p1 ->\n    well_formed_program p1' ->\n    closed_program (program_link p1' p2).\n\n  Module CS.\n    Parameter sem : program -> semantics.\n  End CS.\n\n  (* Notes:\n     - the trace (i.e. behavior) `t` in the diagram from the paper\n       corresponds to `Goes_wrong t'` in the notation below\n     - in the paper we use the following notations:\n       + t ≺ m = exists m' <= m. t = Goes_wrong m'\n         t ≺P m = exists m' <= m. t = Goes_wrong m' /\\ undef_in t (prog_interface P)\n       + this means that t' plays below the role of m' above\n  *)\n  Local Axiom blame_program : forall p Cs t' P' m,\n    well_formed_program p ->\n    well_formed_program Cs ->\n    linkable (prog_interface p) (prog_interface Cs) ->\n    closed_program (program_link p Cs) ->\n    program_behaves (CS.sem (program_link p Cs)) (Goes_wrong t') ->\n    well_formed_program P' ->\n    prog_interface P' = prog_interface p ->\n    closed_program (program_link P' Cs) ->\n    does_prefix (CS.sem (program_link P' Cs)) m ->\n    not_wrong_finpref m ->\n    trace_finpref_prefix t' m ->\n    (prefix m (Goes_wrong t') \\/ undef_in t' (prog_interface p)).\n\nEnd Source_Sig.\n\n(* CH: The number of different well-formedness conditions seems a bit\n       out of control here. *)\n\nModule Type Intermediate_Sig.\n  Parameter program : Type.\n\n  Parameter prog_interface : program -> Program.interface.\n\n  Parameter well_formed_program : program -> Prop.\n\n  Parameter closed_program : program -> Prop.\n\n  Parameter linkable_mains : program -> program -> Prop.\n\n  Parameter matching_mains : program -> program -> Prop.\n\n  Parameter program_link : program -> program -> program.\n\n  Local Axiom linkable_mains_sym : forall p1 p2,\n    linkable_mains p1 p2 -> linkable_mains p2 p1.\n\n  Local Axiom program_linkC : forall p1 p2,\n    well_formed_program p1 ->\n    well_formed_program p2 ->\n    linkable (prog_interface p1) (prog_interface p2) ->\n    program_link p1 p2 = program_link p2 p1.\n\n  Local Axiom linking_well_formedness : forall p1 p2,\n    well_formed_program p1 ->\n    well_formed_program p2 ->\n    linkable (prog_interface p1) (prog_interface p2) ->\n    well_formed_program (program_link p1 p2).\n\n  Local Axiom interface_preserves_closedness_r : forall p1 p2 p2',\n    well_formed_program p1 ->\n    well_formed_program p2' ->\n    prog_interface p2 = prog_interface p2' ->\n    linkable (prog_interface p1) (prog_interface p2) ->\n    closed_program (program_link p1 p2) ->\n    linkable_mains p1 p2 ->\n    matching_mains p2 p2' ->\n    closed_program (program_link p1 p2').\n\n  Module CS.\n    Parameter sem : program -> semantics.\n  End CS.\n\n  (* Local Axiom decomposition_with_refinement : *)\n  (*   forall p c, *)\n  (*     well_formed_program p -> *)\n  (*     well_formed_program c -> *)\n  (*     linkable (prog_interface p) (prog_interface c) -> *)\n  (*     linkable_mains p c -> *)\n  (*   forall beh1, *)\n  (*     program_behaves (CS.sem (program_link p c)) beh1 -> *)\n  (*   exists beh2, *)\n  (*     program_behaves (PS.sem p (prog_interface c)) beh2 /\\ *)\n  (*     behavior_improves beh1 beh2. *)\n\n  (* Local Axiom decomposition_prefix : *)\n  (*   forall p c m, *)\n  (*     well_formed_program p -> *)\n  (*     well_formed_program c -> *)\n  (*     linkable (prog_interface p) (prog_interface c) -> *)\n  (*     linkable_mains p c -> *)\n  (*     not_wrong_finpref m -> (* needed here, and will have it in main proof *) *)\n  (*     does_prefix (CS.sem (program_link p c)) m -> *)\n  (*     does_prefix (PS.sem p (prog_interface c)) m. *)\n\n  (* Local Axiom composition_prefix : *)\n  (*   forall p c m, *)\n  (*     well_formed_program p -> *)\n  (*     well_formed_program c -> *)\n  (*     linkable_mains p c -> *)\n  (*     closed_program (program_link p c) -> *)\n  (*     mergeable_interfaces (prog_interface p) (prog_interface c) -> *)\n  (*     does_prefix (PS.sem p (prog_interface c)) m -> *)\n  (*     does_prefix (PS.sem c (prog_interface p)) m -> *)\n  (*     does_prefix (CS.sem (program_link p c)) m. *)\n\n  Local Axiom compose_mergeable_interfaces :\n    forall p c,\n      linkable (prog_interface p) (prog_interface c) ->\n      closed_program (program_link p c) ->\n      mergeable_interfaces (prog_interface p) (prog_interface c).\n\n  Local Axiom recombination_prefix :\n    forall p c p' c',\n      well_formed_program p ->\n      well_formed_program c ->\n      well_formed_program p' ->\n      well_formed_program c' ->\n      mergeable_interfaces (prog_interface p) (prog_interface c) ->\n      prog_interface p = prog_interface p' ->\n      prog_interface c = prog_interface c' ->\n      closed_program (program_link p c) ->\n      closed_program (program_link p' c') ->\n    forall m,\n      does_prefix (CS.sem (program_link p c)) m ->\n      does_prefix (CS.sem (program_link p' c')) m ->\n      does_prefix (CS.sem (program_link p c')) m.\nEnd Intermediate_Sig.\n\nModule Type S2I_Sig (Source : Source_Sig) (Intermediate : Intermediate_Sig).\n  Parameter matching_mains : Source.program -> Intermediate.program -> Prop.\n\n  Local Axiom matching_mains_equiv : forall p1 p2 p3,\n    matching_mains p1 p2 ->\n    matching_mains p1 p3 ->\n    Intermediate.matching_mains p2 p3.\nEnd S2I_Sig.\n\nModule Type Linker_Sig\n       (Source : Source_Sig)\n       (Intermediate : Intermediate_Sig)\n       (S2I : S2I_Sig Source Intermediate).\n  Local Axiom definability_with_linking :\n    forall p c b m,\n      Intermediate.well_formed_program p ->\n      Intermediate.well_formed_program c ->\n      linkable (Intermediate.prog_interface p) (Intermediate.prog_interface c) ->\n      Intermediate.closed_program (Intermediate.program_link p c) ->\n      program_behaves (Intermediate.CS.sem (Intermediate.program_link p c)) b ->\n      prefix m b ->\n      not_wrong_finpref m ->\n    exists p' c',\n      Source.prog_interface p' = Intermediate.prog_interface p /\\\n      Source.prog_interface c' = Intermediate.prog_interface c /\\\n      S2I.matching_mains p' p /\\\n      S2I.matching_mains c' c /\\\n      Source.well_formed_program p' /\\\n      Source.well_formed_program c' /\\\n      Source.closed_program (Source.program_link p' c') /\\\n      does_prefix (Source.CS.sem (Source.program_link p' c')) m.\n\n(* TODO: split definability_with_linking into a more standard\n         definability + a \"unlinking\" lemma *)\n\n  (* Local Axiom definability : *)\n  (*   forall p m, *)\n  (*     Intermediate.well_formed_program p -> *)\n  (*     Intermediate.closed_program p -> *)\n  (*     does_prefix (Intermediate.CS.sem p) m -> *)\n  (*     not_wrong_finpref m -> *)\n  (*   exists p', *)\n  (*     Source.prog_interface p' = Intermediate.prog_interface p /\\ *)\n  (*     S2I.matching_mains p' p /\\ *)\n  (*     Source.well_formed_program p' /\\ *)\n  (*     Source.closed_program p' /\\ *)\n  (*     does_prefix (Source.CS.sem p') m. *)\n\n  (* Local Axiom unlinking : forall p i1 i2, *)\n  (*   Source.prog_interface p = unionm i1 i2 -> *)\n  (*   Source.well_formed_program p -> *)\n  (*   linkable i1 i2 -> *)\n  (*   exists p1 p2, Source.program_link p1 p2 = p /\\ *)\n  (*     Source.prog_interface p1 = i1 /\\ *)\n  (*     Source.prog_interface p2 = i2. *)\n\nEnd Linker_Sig.\n\nModule Type Compiler_Sig\n       (Source : Source_Sig)\n       (Intermediate : Intermediate_Sig)\n       (S2I : S2I_Sig Source Intermediate).\n  Parameter compile_program : Source.program -> option Intermediate.program.\n\n  Local Axiom well_formed_compilable :\n    forall p,\n      Source.well_formed_program p ->\n    exists pc,\n      compile_program p = Some pc.\n\n  Local Axiom compilation_preserves_well_formedness : forall p p_compiled,\n    Source.well_formed_program p ->\n    compile_program p = Some p_compiled ->\n    Intermediate.well_formed_program p_compiled.\n\n  Local Axiom compilation_preserves_interface : forall p p_compiled,\n    compile_program p = Some p_compiled ->\n    Intermediate.prog_interface p_compiled = Source.prog_interface p.\n\n  Local Axiom compilation_preserves_linkability : forall p p_compiled c c_compiled,\n    Source.well_formed_program p ->\n    Source.well_formed_program c ->\n    linkable (Source.prog_interface p) (Source.prog_interface c) ->\n    compile_program p = Some p_compiled ->\n    compile_program c = Some c_compiled ->\n    linkable (Intermediate.prog_interface p_compiled) (Intermediate.prog_interface c_compiled).\n\n  Local Axiom compilation_preserves_linkable_mains : forall p1 p1' p2 p2',\n    Source.well_formed_program p1 ->\n    Source.well_formed_program p2 ->\n    Source.linkable_mains p1 p2 ->\n    compile_program p1 = Some p1' ->\n    compile_program p2 = Some p2' ->\n    Intermediate.linkable_mains p1' p2'.\n\n  Local Axiom compilation_has_matching_mains : forall p p_compiled,\n    Source.well_formed_program p ->\n    compile_program p = Some p_compiled ->\n    S2I.matching_mains p p_compiled.\n\n  (* CH: To match the paper this should be weakened even more to work with prefixes *)\n  (* Local Axiom separate_compilation_weaker : *)\n  (*   forall p c pc_comp p_comp c_comp, *)\n  (*     Source.well_formed_program p -> *)\n  (*     Source.well_formed_program c -> *)\n  (*     linkable (Source.prog_interface p) (Source.prog_interface c) -> *)\n  (*     compile_program p = Some p_comp -> *)\n  (*     compile_program c = Some c_comp -> *)\n  (*     compile_program (Source.program_link p c) = Some pc_comp -> *)\n  (*   forall b : program_behavior, *)\n  (*     program_behaves (Intermediate.CS.sem pc_comp) b <-> *)\n  (*     program_behaves (Intermediate.CS.sem (Intermediate.program_link p_comp c_comp)) b. *)\n\n  (* Local Axiom S_simulates_I: *)\n  (*   forall p, *)\n  (*     Source.closed_program p -> *)\n  (*     Source.well_formed_program p -> *)\n  (*   forall tp, *)\n  (*     compile_program p = Some tp -> *)\n  (*     backward_simulation (Source.CS.sem p) (Intermediate.CS.sem tp). *)\n\n  Local Axiom forward_simulation_same_safe_prefix:\n    forall p p_compiled c c_compiled m,\n      linkable (Source.prog_interface p) (Source.prog_interface c) ->\n      Source.closed_program (Source.program_link p c) ->\n      Source.well_formed_program p ->\n      Source.well_formed_program c ->\n      does_prefix (Source.CS.sem (Source.program_link p c)) m ->\n      not_wrong_finpref m ->\n      compile_program p = Some p_compiled ->\n      compile_program c = Some c_compiled ->\n      does_prefix (Intermediate.CS.sem (Intermediate.program_link p_compiled c_compiled)) m.\n\n  Local Axiom backward_simulation_behavior_improves_prefix :\n    forall p p_compiled c c_compiled m,\n      linkable (Source.prog_interface p) (Source.prog_interface c) ->\n      Source.closed_program (Source.program_link p c) ->\n      Source.well_formed_program p ->\n      Source.well_formed_program c ->\n      compile_program p = Some p_compiled ->\n      compile_program c = Some c_compiled ->\n      does_prefix (Intermediate.CS.sem (Intermediate.program_link p_compiled c_compiled)) m ->\n    exists b,\n      program_behaves (Source.CS.sem (Source.program_link p c)) b /\\\n      (prefix m b \\/ behavior_improves_finpref b m).\n\nEnd Compiler_Sig.\n", "meta": {"author": "secure-compilation", "repo": "when-good-components-go-bad", "sha": "7bef0fa18780f1e9699abcdadd61e15bf3aba95d", "save_path": "github-repos/coq/secure-compilation-when-good-components-go-bad", "path": "github-repos/coq/secure-compilation-when-good-components-go-bad/when-good-components-go-bad-7bef0fa18780f1e9699abcdadd61e15bf3aba95d/RSC_DC_MD_Sigs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2459192790709846}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq path.\nFrom Coq Require Import Eqdep Relation_Operators.\nFrom pcm Require Import pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL Require Import Freshness DepMaps EqTypeX.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Shared state, as implemented by the message soup.\n\n   At this point, the implementation is based on top of standard union\n   maps. This defines the procedure for allocating new messages: just\n   by taking the next-to-the largest id in the corresponding\n   batch. Indeed, this is not particularly nice, as it assumes the\n   _global_ message soup.\n\n   It's not clear at this moment, what will be the best representation\n   of the soup so it would be in the same time _local_ and also would\n   allow for th allocation. Perhaps, we should just consider local\n   soups, ensuring that they all carry distinct labels, and then when\n   cojoin them, make sure that for clashing message id's protocol\n   labels are different.\n\n *)\n\nSection TaggedMessages. \n\n  Structure TaggedMessage :=\n    TMsg {\n        tag: nat;\n        (* Okay, this is a big omissin, but for now I'm sick and tired\n           to deal with casts everywhere, so for the moment the\n           contents of the messages are going to be just sequences of\n           natural number, and it's up to the client-supplied\n           coherence predicate to restrict them appropriately, relating this thing to tags *)\n        tms_cont :> seq nat          \n      }.\n\nEnd TaggedMessages.\n\nSection Shared.\n\n  Definition Label := [ordType of nat].\n\n  (* (Heterogenious) messages are parametrized by\n\n     - lab   - protocol Label\n     - ptype - protocol, defining the content type\n     - content  - the contents of the message\n     - from/to  - IDs of the sender.receiver node\n     - active - a bit, indicating whether the message hasn't been consumed yet (i.e., read)\n\n     I'm not sure, if we're going to need anything else. *)\n  Structure msg (mtype : Type) :=\n    Msg {content  : mtype;\n         from     : nat;\n         to       : nat;\n         active   : bool }.\n\n  (* Message IDs: pairs Label * id, where Label comes from the protocol. *)\n  Definition mid := [ordType of nat].\n\n  (* Message soup (for a specific protocol) is just a partial finite\n     map from message IDs (mid) to arbitrary Messages. *)\n  Definition soup : Type :=\n    union_map mid (msg (TaggedMessage)).\n\n  Variables (s: soup) (V: valid s).\n\n  (* Allocating new message in the soup *)\n  Definition post_msg m : soup * mid :=\n    let: f := fresh s in (s \\+ f \\\\-> m, f).\n\n  Lemma post_valid m :  valid (post_msg m).1.\n  Proof. by rewrite ?valid_fresh. Qed.\n\n  Lemma post_fresh m : (post_msg m).2 \\notin dom s.\n  Proof. by rewrite ?dom_fresh. Qed.\n\n  (* Marking is  *)\n  Definition mark_msg T (m : msg T) : msg T :=\n    Msg (content m) (from m) (to m) false.\n\n  (* Updating the message soup, consuming the message id *)\n  Definition consume_msg (s : soup) (id : mid) : soup :=\n    let: mr := find id s in\n    if mr is Some m then upd id (mark_msg m) s else s.\n\n  Definition is_active (id : mid) :=\n    exists m, find id s = Some m /\\ active m.\n\n  Definition is_consumed (id : mid) :=\n    exists m, find id s = Some m /\\ ~~ active m.\n\n  (* TODO: consumes \"truth table\" -- three possible scenarios (how to express?) *)\n\n  (* Obvious fact about marking message *)\n  Lemma find_consume s' (id: mid) m:\n    valid s' -> find id s' = Some m ->\n    find id (consume_msg s' id) = Some (mark_msg m).\n  Proof. by move=>V' E; rewrite/consume_msg E findU eqxx V'/=. Qed.\n\n  Lemma find_mark m s' msg :\n    valid s' -> find m (consume_msg s' m) = Some msg ->\n    exists msg', find m s' = Some msg' /\\ msg = mark_msg msg'.\n  Proof.\n  move=>V'; rewrite /consume_msg; case D: (m \\in dom s').\n  - move/um_eta: D=>[msg'][->]_; rewrite findU eqxx/= V'.\n    by case=><-; eexists _.\n  by case: dom_find (D)=>//->_; move/find_some=>Z; rewrite Z in D.\n  Qed.   \n\n  Lemma mark_other m m' s' :\n    valid s' -> m' == m = false -> find m' (consume_msg s' m) = find m' s'.\n  Proof.\n  move=>V' N; rewrite /consume_msg; case D: (m \\in dom s').\n  by case: dom_find (D)=>//v->_ _; rewrite findU N.\n  by case: dom_find (D)=>//->_.\n  Qed.   \n\n  Lemma consume_valid s' m : valid s' -> valid (consume_msg s' m).\n  Proof.\n  move=>V'; rewrite /consume_msg; case (find m s')=>//v.\n  by rewrite /mark_msg validU.\n  Qed.\n\n  Lemma consumeUn (s': soup) (i : mid) mm\n        (j : mid) : valid (s' \\+ i \\\\-> mm) ->\n    consume_msg (s' \\+ i \\\\-> mm) j = \n    if i == j then s' \\+ i \\\\-> mark_msg mm\n    else (consume_msg s' j) \\+ (i \\\\-> mm).\n  Proof.\n  rewrite ![_ \\+ i \\\\-> _]joinC; rewrite eq_sym.\n  move=>V'; case B: (j==i); rewrite /consume_msg findPtUn2// B.\n  - by move/eqP: B=>?; subst j; rewrite updPtUn.\n  by case X: (find j s')=>//; rewrite updUnL domPt inE eq_sym B.   \n  Qed.\n\n  Notation \"'{{' m 'in' s 'at' id '}}'\" := (find id s = Some m).\n  Notation \"'{{' m 'in' s '}}'\" := (exists id, {{m in s at id}}).\n\n\n  \nEnd Shared.\n\n(* Local per-protocol state with per-node resources *)\nSection Local.\n\n  Variable U : Type.\n\n  Definition nid := nat.\n\n  (* Local state of a a protocol is simply a partial map from node ids\n     to their local contributions, along with the validity of the\n     cumulative contribution. *)\n\n  Definition lstate_type := union_map [ordType of nid] U.\n\nEnd Local.\n\n(*\nDefinition um_all {A:ordType} {B} (p : A -> B -> bool) (u : union_map A B) : bool :=\n  um_recf false true (fun k v f rec Hval Hpath => p k v && rec) u.\n\nDefinition um_some {A:ordType} {B} (p : A -> B -> bool) (u : union_map A B) : bool :=\n  um_recf false false (fun k v f rec Hval Hpath => p k v || rec) u.\n*)\n\nSection Statelets.\n\n  (* A particular statelet instance.\n     The Label and the PCM are the parameters and are defined by the protocol.\n     The lstate and dsop are subject of the evolution.\n   *)\n  Structure dstatelet  :=\n    DStatelet {\n        (* Not sure if it's the best way to represent information\n           about kinds of messages in this particular dstatelet, but\n           let's think of tags as of integers for now, so dTagToCont\n           will map the tags to specific types. *)\n\n        (* Local state for each node as a pair of heaps; first heap is\n           real, second heap is a ghost one. Let's deal with this\n           model for now before we figure out how to discharge\n           equalities in a better way *)\n        dstate     : lstate_type heap;\n        dsoup      : soup\n    }.\n\n  Fixpoint empty_lstate (ns : seq nid) :=\n    if ns is n :: ns'\n    then n \\\\-> Heap.empty \\+ (empty_lstate ns')\n    else  Unit.\n    \n  (* Definition empty_dstatelet ns : dstatelet := *)\n  (*   @DStatelet (empty_lstate (undup ns)) Unit. *)\n\n  (* Lemma valid_mt_soup ns : valid (dsoup (empty_dstatelet ns)). *)\n  (* Proof. by rewrite /= valid_unit. Qed. *)\n\n  (* Lemma dom_mt ns : *)\n  (*   valid (empty_lstate (undup ns)) /\\ dom (empty_lstate (undup ns)) =i undup ns. *)\n  (* Proof. *)\n  (* elim: ns=>//=[|n ns [H1 H2]]; first by rewrite dom0. *)\n  (* case B: (n \\in ns)=>//=; split. *)\n  (* - by rewrite gen_validPtUn/= H1 H2/=; apply/negbT; rewrite mem_undup. *)\n  (* move=> z; rewrite um_domPtUn inE/= gen_validPtUn/= H1 H2/=. *)\n  (* rewrite -mem_undup in B; rewrite B/=. *)\n  (* case C: (n == z)=>//=; first by rewrite in_cons eq_sym C. *)\n  (* by rewrite H2 in_cons eq_sym C/=. *)\n  (* Qed. *)\n\n  (* Lemma valid_mt_state ns : valid (dstate (empty_dstatelet ns)). *)\n  (* Proof. *)\n  (* elim:ns=>//=n ns H; case I: (n \\in ns)=>//=.   *)\n  (* by rewrite gen_validPtUn H/=; case: (dom_mt ns)=>_->; rewrite mem_undup I. *)\n  (* Qed. *)\n\n  (* Lemma mt_nodes ns : dom (dstate (empty_dstatelet ns)) =i ns. *)\n  (* Proof. *)\n  (* by case: (dom_mt ns)=>_ H2 z; rewrite -mem_undup -H2. *)\n  (* Qed. *)\n\n  Definition empty_dstatelet : dstatelet :=\n    @DStatelet (empty_lstate [::]) Unit.\n\n  Lemma valid_mt_soup : valid (dsoup empty_dstatelet).\n  Proof. by rewrite /= valid_unit. Qed.\n\n  Lemma valid_mt_state  : valid (dstate empty_dstatelet).\n  Proof. by rewrite valid_unit. Qed.\n\n  Lemma mt_nodes : dom (dstate empty_dstatelet) =i [::].\n  Proof. by rewrite dom0. Qed.\n\nEnd Statelets.\n\n\nModule StateGetters.\nSection StateGetters.\n\nDefinition state := union_map Label dstatelet.\n\n(* Retrieve statelet from the state *)\nDefinition getStatelet (s: state) (i : Label) : dstatelet :=\n  match find i s with\n  | Some d => d\n  | None => empty_dstatelet\n  end.\n\nEnd StateGetters.\nEnd StateGetters.\n\n\nExport StateGetters.\n", "meta": {"author": "DistributedComponents", "repo": "disel", "sha": "88dc15450394a5963f513d220001b49389c6b52f", "save_path": "github-repos/coq/DistributedComponents-disel", "path": "github-repos/coq/DistributedComponents-disel/disel-88dc15450394a5963f513d220001b49389c6b52f/theories/Core/State.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.2458966942333554}}
{"text": "From caml5 Require Import\n  prelude.\nFrom caml5.lang Require Import\n  notations\n  proofmode.\nFrom caml5.std Require Export\n  base.\n\nSection heapGS.\n  Context `{!heapGS Σ}.\n  Implicit Types l : loc.\n\n  Definition record2_make : val :=\n    λ: \"v₀\" \"v₁\",\n      let: \"l\" := AllocN #2 \"v₀\" in\n      \"l\".(1) <- \"v₁\" ;;\n      \"l\".\n\n  Definition record2_model l dq v₀ v₁ : iProp Σ :=\n    l.(0) ↦{dq} v₀ ∗\n    l.(1) ↦{dq} v₁.\n\n  #[global] Instance record2_model_timeless l dq v₀ v₁ :\n    Timeless (record2_model l dq v₀ v₁).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance record2_model_persistent l v₀ v₁ :\n    Persistent (record2_model l DfracDiscarded v₀ v₁).\n  Proof.\n    apply _.\n  Qed.\n\n  #[global] Instance record2_model_fractional l v₀ v₁ :\n    Fractional (λ q, record2_model l (DfracOwn q) v₀ v₁).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance record2_model_as_fractional l q v₀ v₁ :\n    AsFractional (record2_model l (DfracOwn q) v₀ v₁) (λ q, record2_model l (DfracOwn q) v₀ v₁) q.\n  Proof.\n    split; done || apply _.\n  Qed.\n\n  Lemma record2_model_persist l dq v₀ v₁ :\n    record2_model l dq v₀ v₁ ==∗\n    record2_model l DfracDiscarded v₀ v₁.\n  Proof.\n    iIntros \"(Hv₀ & Hv₁)\".\n    iMod (mapsto_persist with \"Hv₀\") as \"$\".\n    iMod (mapsto_persist with \"Hv₁\") as \"$\".\n    done.\n  Qed.\n\n  Lemma record2_model_valid l dq v₀ v₁ :\n    record2_model l dq v₀ v₁ -∗\n    ⌜✓ dq⌝.\n  Proof.\n    iIntros \"(Hv₀ & Hv₁)\". iApply (mapsto_valid with \"Hv₀\").\n  Qed.\n  Lemma record2_model_combine l dq1 v₀1 v₁1 dq2 v₀2 v₁2 :\n    record2_model l dq1 v₀1 v₁1 -∗\n    record2_model l dq2 v₀2 v₁2 -∗\n      record2_model l (dq1 ⋅ dq2) v₀1 v₁1 ∗\n      ⌜v₀1 = v₀2 ∧ v₁1 = v₁2⌝.\n  Proof.\n    iIntros \"(Hv₀1 & Hv₁1) (Hv₀2 & Hv₁2)\".\n    iDestruct (mapsto_combine with \"Hv₀1 Hv₀2\") as \"(Hv₀ & <-)\".\n    iDestruct (mapsto_combine with \"Hv₁1 Hv₁2\") as \"(Hv₁ & <-)\".\n    iSplit; last done. iFrame.\n  Qed.\n  Lemma record2_model_valid_2 l dq1 v₀1 v₁1 dq2 v₀2 v₁2 :\n    record2_model l dq1 v₀1 v₁1 -∗\n    record2_model l dq2 v₀2 v₁2 -∗\n    ⌜✓ (dq1 ⋅ dq2) ∧ v₀1 = v₀2 ∧ v₁1 = v₁2⌝.\n  Proof.\n    iIntros \"Hl1 Hl2\".\n    iDestruct (record2_model_combine with \"Hl1 Hl2\") as \"(Hl & %)\".\n    iDestruct (record2_model_valid with \"Hl\") as %?.\n    done.\n  Qed.\n  Lemma record2_model_agree l dq1 v₀1 v₁1 dq2 v₀2 v₁2 :\n    record2_model l dq1 v₀1 v₁1 -∗\n    record2_model l dq2 v₀2 v₁2 -∗\n    ⌜v₀1 = v₀2 ∧ v₁1 = v₁2⌝.\n  Proof.\n    iIntros \"Hl1 Hl2\".\n    iDestruct (record2_model_valid_2 with \"Hl1 Hl2\") as %?. naive_solver.\n  Qed.\n  Lemma record2_model_dfrac_ne l1 dq1 v₀1 v₁1 l2 dq2 v₀2 v₁2 :\n    ¬ ✓ (dq1 ⋅ dq2) →\n    record2_model l1 dq1 v₀1 v₁1 -∗\n    record2_model l2 dq2 v₀2 v₁2 -∗\n    ⌜l1 ≠ l2⌝.\n  Proof.\n    iIntros \"% Hl1 Hl2\" (->).\n    iDestruct (record2_model_valid_2 with \"Hl1 Hl2\") as %?. naive_solver.\n  Qed.\n  Lemma record2_model_ne l1 v₀1 v₁1 l2 dq2 v₀2 v₁2 :\n    record2_model l1 (DfracOwn 1) v₀1 v₁1 -∗\n    record2_model l2 dq2 v₀2 v₁2 -∗\n    ⌜l1 ≠ l2⌝.\n  Proof.\n    iApply record2_model_dfrac_ne. intros []%exclusive_l. apply _.\n  Qed.\n  Lemma record2_model_exclusive l v₀1 v₁1 v₀2 v₁2 :\n    record2_model l (DfracOwn 1) v₀1 v₁1 -∗\n    record2_model l (DfracOwn 1) v₀2 v₁2 -∗\n    False.\n  Proof.\n    iIntros \"Hl1 Hl2\".\n    iDestruct (record2_model_ne with \"Hl1 Hl2\") as %?. naive_solver.\n  Qed.\n\n  Lemma record2_dfrac_relax dq l v₀ v₁ :\n    ✓ dq →\n    record2_model l (DfracOwn 1) v₀ v₁ ==∗\n    record2_model l dq v₀ v₁.\n  Proof.\n    iIntros \"% (Hv₀ & Hv₁)\".\n    iMod (mapsto_dfrac_relax with \"Hv₀\") as \"Hv₀\"; first done.\n    iMod (mapsto_dfrac_relax with \"Hv₁\") as \"Hv₁\"; first done.\n    iFrame. done.\n  Qed.\n\n  Lemma record2_make_spec v₀ v₁ :\n    {{{ True }}}\n      record2_make v₀ v₁\n    {{{ l, RET #l; record2_model l (DfracOwn 1) v₀ v₁ ∗ meta_token l ⊤ }}}.\n  Proof.\n    iIntros \"%Φ _ HΦ\".\n    wp_rec. wp_pures.\n    wp_apply (wp_allocN with \"[//]\"); first done. iIntros \"%l (Hl & Hmeta & _)\". rewrite loc_add_0.\n    wp_pures.\n    iDestruct (array_cons with \"Hl\") as \"(Hv₀ & Hl)\".\n    iEval (setoid_rewrite <- loc_add_0) in \"Hv₀\".\n    iDestruct (array_singleton with \"Hl\") as \"Hv₁\".\n    wp_store.\n    iApply \"HΦ\". iFrame. done.\n  Qed.\n\n  Lemma record2_get0_spec l dq v₀ v₁ :\n    {{{ record2_model l dq v₀ v₁ }}}\n      !#l.(0)\n    {{{ RET v₀; record2_model l dq v₀ v₁ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁) HΦ\".\n    wp_load.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁]\").\n  Qed.\n  Lemma record2_get1_spec l dq v₀ v₁ :\n    {{{ record2_model l dq v₀ v₁ }}}\n      !#l.(1)\n    {{{ RET v₁; record2_model l dq v₀ v₁ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁) HΦ\".\n    wp_load.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁]\").\n  Qed.\n\n  Lemma record2_set0_spec l v₀ v₁ v :\n    {{{ record2_model l (DfracOwn 1) v₀ v₁ }}}\n      #l.(0) <- v\n    {{{ RET #(); record2_model l (DfracOwn 1) v v₁ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁) HΦ\".\n    wp_store.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁]\").\n  Qed.\n  Lemma record2_set1_spec l v₀ v₁ v :\n    {{{ record2_model l (DfracOwn 1) v₀ v₁ }}}\n      #l.(1) <- v\n    {{{ RET #(); record2_model l (DfracOwn 1) v₀ v }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁) HΦ\".\n    wp_store.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁]\").\n  Qed.\nEnd heapGS.\n\n#[global] Opaque record2_make.\n\n#[global] Opaque record2_model.\n", "meta": {"author": "clef-men", "repo": "caml5", "sha": "0de06d5792138eb17877ed1536a0401b7a322ee2", "save_path": "github-repos/coq/clef-men-caml5", "path": "github-repos/coq/clef-men-caml5/caml5-0de06d5792138eb17877ed1536a0401b7a322ee2/theories/std/record2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24589668826323888}}
{"text": "From Coq Require Import ZArith List.\nFrom mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq.\nFrom BitBlasting Require Import QFBV CNF BBCommon BBEq BBUlt BBDisj.\nFrom ssrlib Require Import ZAriths Tactics Bools Seqs.\nFrom nbits Require Import NBits.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n\nDefinition bit_blast_ule g ls1 ls2 : generator * cnf * literal :=\n  let '(g_eq, cs_eq, r_eq) := bit_blast_eq g ls1 ls2 in\n  let '(g_ult, cs_ult, r_ult) := bit_blast_ult g_eq ls1 ls2 in\n  let '(g_disj, cs_disj, r_disj) := bit_blast_disj g_ult r_eq r_ult in\n  (g_disj, catrev cs_eq (catrev cs_ult cs_disj), r_disj).\n\nDefinition mk_env_ule E g ls1 ls2 : env * generator * cnf * literal :=\n  let '(E_eq, g_eq, cs_eq, r_eq) := mk_env_eq E g ls1 ls2 in\n  let '(E_ult, g_ult, cs_ult, r_ult) := mk_env_ult E_eq g_eq ls1 ls2 in\n  let '(E_disj, g_disj, cs_disj, r_disj) := mk_env_disj E_ult g_ult r_eq r_ult in\n  (E_disj, g_disj, catrev cs_eq (catrev cs_ult cs_disj), r_disj).\n\nLemma bit_blast_ule_correct g bs1 bs2 E ls1 ls2 g' cs lr:\n  bit_blast_ule g ls1 ls2 = (g', cs, lr) ->\n  size ls1 = size ls2 ->\n  enc_bits E ls1 bs1 ->\n  enc_bits E ls2 bs2 ->\n  interp_cnf E (add_prelude cs) ->\n  enc_bit E lr (leB bs1 bs2).\nProof.\n  rewrite /bit_blast_ule.\n  case Heq : (bit_blast_eq g ls1 ls2) => [[g_eq cs_eq] r_eq].\n  case Hult : (bit_blast_ult g_eq ls1 ls2) => [[g_ult cs_ult] r_ult].\n  case Hdisj : (bit_blast_disj g_ult r_eq r_ult) => [[g_disj cs_disj] r_disj].\n  case => _ <- <- Hsz Henc1 Henc2.\n  rewrite 2!add_prelude_catrev.\n  move => Hcnf.\n  move/andP : Hcnf => [Hcnf_eq Hcnf].\n  move/andP : Hcnf => [Hcnf_ult Hcnf_disj].\n  move : (bit_blast_eq_correct Heq Hsz Henc1 Henc2 Hcnf_eq) => Hreq.\n  move : (bit_blast_ult_correct Hult Henc1 Henc2 Hcnf_ult) => Hrult.\n  move : (bit_blast_disj_correct Hdisj Hreq Hrult Hcnf_disj) => Hrdisj.\n  rewrite /enc_bit in Hrdisj. move/eqP: Hrdisj => Hrdisj.\n  apply/eqP. by rewrite /leB/enc_bit.\nQed.\n\nLemma mk_env_ule_is_bit_blast_ule E g ls1 ls2 E' g' cs lr:\n  mk_env_ule E g ls1 ls2 = (E', g', cs, lr) ->\n  bit_blast_ule g ls1 ls2 = (g', cs, lr).\nProof.\n  rewrite /bit_blast_ule /mk_env_ule /=.\n  move => H. dcase_hyps. subst.\n  rewrite (mk_env_eq_is_bit_blast_eq H).\n  rewrite (mk_env_ult_is_bit_blast_ult H1).\n  done.\nQed.\n\nLemma mk_env_ule_newer_gen E g ls1 ls2 E' g' cs lr:\n  mk_env_ule E g ls1 ls2 = (E', g', cs, lr) ->\n  (g <=? g')%positive.\nProof.\n  rewrite /mk_env_ule. rewrite /gen.\n  case Heq: (mk_env_eq E g ls1 ls2) => [[[E_eq g_eq] cs_eq] lr_eq].\n  case Hult: (mk_env_ult E_eq g_eq ls1 ls2) => [[[E_ult g_ult] cs_ult] lr_ult].\n  case Hdisj: (mk_env_disj E_ult g_ult lr_eq lr_ult) => [[[E_disj g_disj] cs_disj] lr_disj].\n  case. move=> _ <- _ _ .\n  move: (mk_env_disj_newer_gen Hdisj) => g_ult_le_g_disj.\n  move: (mk_env_ult_newer_gen Hult) => g_eq_le_g_ult.\n  move: (mk_env_eq_newer_gen Heq) => g_le_g_eq.\n  apply: (pos_leb_trans (pos_leb_trans g_le_g_eq g_eq_le_g_ult) g_ult_le_g_disj).\nQed.\n\nLemma mk_env_ule_newer_res E g ls1 ls2 E' g' cs lr :\n  mk_env_ule E g ls1 ls2 = (E', g', cs, lr) ->\n  newer_than_lit g' lr.\nProof.\n  rewrite /mk_env_ule. rewrite /gen.\n  case Heq: (mk_env_eq E g ls1 ls2) => [[[E_eq g_eq] cs_eq] lr_eq].\n  case Hult: (mk_env_ult E_eq g_eq ls1 ls2) => [[[E_ult g_ult] cs_ult] lr_ult].\n  case Hdisj: (mk_env_disj E_ult g_ult lr_eq lr_ult) => [[[E_disj g_disj] cs_disj] lr_disj].\n  case. move=> _ <- _ <-.\n  exact: (mk_env_disj_newer_res Hdisj).\nQed.\n\nLemma mk_env_ule_newer_cnf E g ls1 ls2 E' g' cs lr :\n  mk_env_ule E g ls1 ls2 = (E', g', cs, lr) ->\n  newer_than_lit g lit_tt ->\n  newer_than_lits g ls1 -> newer_than_lits g ls2 ->\n  newer_than_cnf g' cs.\nProof.\n  rewrite /mk_env_ule. rewrite /gen.\n  case Heq: (mk_env_eq E g ls1 ls2) => [[[E_eq g_eq] cs_eq] lr_eq].\n  case Hult: (mk_env_ult E_eq g_eq ls1 ls2) => [[[E_ult g_ult] cs_ult] lr_ult].\n  case Hdisj: (mk_env_disj E_ult g_ult lr_eq lr_ult) => [[[E_disj g_disj] cs_disj] lr_disj].\n  case. move=> _ <- <- _. move=> Hnew_gtt Hnew_gls1 Hnew_gls2.\n  rewrite 2!newer_than_cnf_catrev.\n  move: (mk_env_eq_newer_cnf Heq Hnew_gtt Hnew_gls1 Hnew_gls2) => H_new_cnf_geq_cseq.\n  move: (mk_env_eq_newer_gen Heq) => g_le_geq.\n  move: (mk_env_ult_newer_gen Hult) => geq_le_gult.\n  move: (newer_than_lit_le_newer Hnew_gtt g_le_geq) => Hnew_geqtt.\n  move: (newer_than_lits_le_newer Hnew_gls1 g_le_geq) => Hnew_geqls1.\n  move: (newer_than_lits_le_newer Hnew_gls2 g_le_geq) => Hnew_geqls2.\n  move: (mk_env_ult_newer_cnf Hult Hnew_geqtt Hnew_geqls1 Hnew_geqls2) => H_new_cnf_gult_csult.\n  move: (mk_env_disj_newer_res Hdisj) => tmp.\n  move: (mk_env_ult_newer_res Hult Hnew_geqtt) => tmp2.\n  move: (mk_env_eq_newer_res Heq) => tmp3.\n  move: (newer_than_lit_le_newer tmp3 geq_le_gult) => tmp4.\n  move: (mk_env_disj_newer_cnf Hdisj tmp4 tmp2) => -> /=.\n  move: (mk_env_disj_newer_gen Hdisj) => g_ult_le_g_disj.\n  move: (newer_than_cnf_le_newer H_new_cnf_gult_csult g_ult_le_g_disj) => -> /=.\n  move: (pos_leb_trans geq_le_gult g_ult_le_g_disj) => geq_le_gdisj.\n  move: (newer_than_cnf_le_newer H_new_cnf_geq_cseq geq_le_gdisj) => -> /=.\n  done.\nQed.\n\n\nLemma mk_env_ule_preserve E g ls1 ls2 E' g' cs lr :\n  mk_env_ule E g ls1 ls2 = (E', g', cs, lr) ->\n  env_preserve E E' g.\nProof.\n  rewrite /mk_env_ule. rewrite /gen.\n  case Heq: (mk_env_eq E g ls1 ls2) => [[[E_eq g_eq] cs_eq] lr_eq].\n  case Hult: (mk_env_ult E_eq g_eq ls1 ls2) => [[[E_ult g_ult] cs_ult] lr_ult].\n  case Hdisj: (mk_env_disj E_ult g_ult lr_eq lr_ult) => [[[E_disj g_disj] cs_disj] lr_disj].\n  case=> <- _ _ _.\n  move: (mk_env_eq_preserve Heq) => Hpre_eq.\n  move: (mk_env_ult_preserve Hult) => Hpre_ult.\n  move: (mk_env_disj_preserve Hdisj) => Hpre_disj.\n  move: (mk_env_eq_newer_gen Heq) => Hng_eq.\n  move: (mk_env_ult_newer_gen Hult) => Hng_ult.\n  move: (mk_env_disj_newer_gen Hdisj) => Hng_disj.\n  move: (env_preserve_le Hpre_ult Hng_eq) => Hpre2.\n  move: (pos_leb_trans Hng_eq Hng_ult) => g_le_gult.\n  move: (env_preserve_le Hpre_disj g_le_gult) => Hpre3.\n  exact: (env_preserve_trans (env_preserve_trans Hpre_eq Hpre2) Hpre3).\nQed.\n\n\nLemma mk_env_ule_sat E g ls1 ls2 E' g' cs lr :\n    mk_env_ule E g ls1 ls2 = (E', g', cs, lr) ->\n    newer_than_lit g lit_tt ->\n    newer_than_lits g ls1 -> newer_than_lits g ls2 ->\n    interp_cnf E' cs.\nProof.\n  rewrite /mk_env_ule. rewrite /gen.\n  case Heq: (mk_env_eq E g ls1 ls2) => [[[E_eq g_eq] cs_eq] lr_eq].\n  case Hult: (mk_env_ult E_eq g_eq ls1 ls2) => [[[E_ult g_ult] cs_ult] lr_ult].\n  case Hdisj: (mk_env_disj E_ult g_ult lr_eq lr_ult) => [[[E_disj g_disj] cs_disj] lr_disj].\n  case=> <- _ <- _. move=> Hnew_gtt Hnew_gls1 Hnew_gls2.\n  rewrite 2!interp_cnf_catrev.\n  move: (mk_env_eq_newer_cnf Heq Hnew_gtt Hnew_gls1 Hnew_gls2) => H_new_cnf_geq_cseq.\n  move: (mk_env_eq_newer_gen Heq) => g_le_geq.\n  move: (mk_env_ult_newer_gen Hult) => geq_le_gult.\n  move: (newer_than_lit_le_newer Hnew_gtt g_le_geq) => Hnew_geqtt.\n  move: (newer_than_lits_le_newer Hnew_gls1 g_le_geq) => Hnew_geqls1.\n  move: (newer_than_lits_le_newer Hnew_gls2 g_le_geq) => Hnew_geqls2.\n  move: (mk_env_ult_sat Hult Hnew_geqtt Hnew_geqls1 Hnew_geqls2) => Hsat_ult.\n  move: (mk_env_disj_newer_gen Hdisj) => g_ult_le_g_disj.\n  move: (mk_env_disj_preserve Hdisj) => Hpre_disj.\n  move: (newer_than_lit_le_newer Hnew_geqtt geq_le_gult) => Hnew_gulttt.\n  move: (newer_than_lits_le_newer Hnew_geqls1 geq_le_gult) => Hnew_gultls1.\n  move: (newer_than_lits_le_newer Hnew_geqls2 geq_le_gult) => Hnew_gultls2.\n  move: (mk_env_ult_newer_cnf Hult Hnew_geqtt Hnew_geqls1 Hnew_geqls2) => Hnew_cnf_gult_csult.\n  move: (env_preserve_cnf Hpre_disj Hnew_cnf_gult_csult) => -> /=.\n  rewrite Hsat_ult /=.\n  move: (mk_env_disj_newer_res Hdisj) => tmp.\n  move: (mk_env_ult_newer_res Hult Hnew_geqtt) => tmp2.\n  move: (mk_env_eq_newer_res Heq) => tmp3.\n  move: (newer_than_lit_le_newer tmp3 geq_le_gult) => tmp4.\n  move: (mk_env_disj_sat Hdisj tmp4 tmp2) => -> /=.\n  move: (mk_env_eq_sat Heq Hnew_gtt Hnew_gls1 Hnew_gls2) => H.\n  move: (mk_env_eq_preserve Heq) => Hpre_eq.\n  move: (mk_env_ult_preserve Hult) => Hpre_ult.\n  move: (mk_env_eq_newer_cnf Heq Hnew_gtt Hnew_gls1 Hnew_gls2) => Hnew_cnf_geq_cseq.\n  move: (env_preserve_cnf Hpre_ult Hnew_cnf_geq_cseq) => eq1.\n  rewrite H in eq1.\n  move: (mk_env_disj_newer_cnf Hdisj tmp4 tmp2) => Hnew_cnf_gdisj_csdisj.\n  move: (newer_than_cnf_le_newer Hnew_cnf_geq_cseq geq_le_gult) => Hnewcnf_gult_cseq.\n  move: (env_preserve_cnf Hpre_disj Hnewcnf_gult_cseq) => -> /=.\n    by rewrite eq1 /=.\nQed.\n\nLemma mk_env_ule_env_equal E1 E2 g ls1 ls2 E1' E2' g1' g2' cs1 cs2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_ule E1 g ls1 ls2 = (E1', g1', cs1, lrs1) ->\n  mk_env_ule E2 g ls1 ls2 = (E2', g2', cs2, lrs2) ->\n  env_equal E1' E2' /\\ g1' = g2' /\\ cs1 = cs2 /\\ lrs1 = lrs2.\nProof.\n  rewrite /mk_env_ule => Heq.\n  dcase (mk_env_eq E1 g ls1 ls2) => [[[[E_eq1 g_eq1] cs_eq1] lrs_eq1] Hv_eq1].\n  dcase (mk_env_eq E2 g ls1 ls2) => [[[[E_eq2 g_eq2] cs_eq2] lrs_eq2] Hv_eq2].\n  move: (mk_env_eq_env_equal Heq Hv_eq1 Hv_eq2) => [Heq1 [? [? ?]]]; subst.\n  dcase (mk_env_ult E_eq1 g_eq2 ls1 ls2) => [[[[E_lt1 g_lt1] cs_lt1] lrs_lt1] Hv_lt1].\n  dcase (mk_env_ult E_eq2 g_eq2 ls1 ls2) => [[[[E_lt2 g_lt2] cs_lt2] lrs_lt2] Hv_lt2].\n  move: (mk_env_ult_env_equal Heq1 Hv_lt1 Hv_lt2) => [Heq2 [? [? ?]]]; subst.\n  dcase (mk_env_disj E_lt1 g_lt2 lrs_eq2 lrs_lt2) =>[[[[E_d1 g_d1] cs_d1] lrs_d1] Hv_d1].\n  dcase (mk_env_disj E_lt2 g_lt2 lrs_eq2 lrs_lt2) =>[[[[E_d2 g_d2] cs_d2] lrs_d2] Hv_d2].\n  move: (mk_env_disj_env_equal Heq2 Hv_d1 Hv_d2) => [Heq3 [? [? ?]]]; subst.\n  case=> ? ? ? ?; case=> ? ? ? ?; subst. done.\nQed.\n", "meta": {"author": "fmlab-iis", "repo": "coq-qfbv", "sha": "0e9521febd1564747723a773d25e54781e81b762", "save_path": "github-repos/coq/fmlab-iis-coq-qfbv", "path": "github-repos/coq/fmlab-iis-coq-qfbv/coq-qfbv-0e9521febd1564747723a773d25e54781e81b762/src/BBUle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.24589668826323885}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Common subexpression elimination over RTL.  This optimization\n  proceeds by value numbering over extended basic blocks. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import ValueDomain.\nRequire Import ValueAnalysis.\nRequire Import CSEdomain.\nRequire Import Kildall.\nRequire Import CombineOp.\n\n(** The idea behind value numbering algorithms is to associate\n  abstract identifiers (``value numbers'') to the contents of registers\n  at various program points, and record equations between these\n  identifiers.  For instance, consider the instruction\n  [r1 = add(r2, r3)] and assume that [r2] and [r3] are mapped\n  to abstract identifiers [x] and [y] respectively at the program\n  point just before this instruction.  At the program point just after,\n  we can add the equation [z = add(x, y)] and associate [r1] with [z],\n  where [z] is a fresh abstract identifier.  However, if we already\n  knew an equation [u = add(x, y)], we can preferably add no equation\n  and just associate [r1] with [u].  If there exists a register [r4]\n  mapped with [u] at this point, we can then replace the instruction\n  [r1 = add(r2, r3)] by a move instruction [r1 = r4], therefore eliminating\n  a common subexpression and reusing the result of an earlier addition.\n\n  The representation of value numbers and equations is described in\n  module [CSEdomain]. *)\n\n(** * Operations on value numberings *)\n\n(** [valnum_reg n r] returns the value number for the contents of\n  register [r].  If none exists, a fresh value number is returned\n  and associated with register [r].  The possibly updated numbering\n  is also returned.  [valnum_regs] is similar, but for a list of\n  registers. *)\n\nDefinition valnum_reg (n: numbering) (r: reg) : numbering * valnum :=\n  match PTree.get r n.(num_reg) with\n  | Some v => (n, v)\n  | None   =>\n      let v := n.(num_next) in\n      ( {| num_next := Psucc v;\n           num_eqs  := n.(num_eqs);\n           num_reg  := PTree.set r v n.(num_reg);\n           num_val  := PMap.set v (r :: nil) n.(num_val) |},\n       v)\n  end.\n\nFixpoint valnum_regs (n: numbering) (rl: list reg)\n                     {struct rl} : numbering * list valnum :=\n  match rl with\n  | nil =>\n      (n, nil)\n  | r1 :: rs =>\n      let (n1, v1) := valnum_reg n r1 in\n      let (ns, vs) := valnum_regs n1 rs in\n      (ns, v1 :: vs)\n  end.\n\n(** [find_valnum_rhs rhs eqs] searches the list of equations [eqs]\n  for an equation of the form [vn = rhs] for some value number [vn].\n  If found, [Some vn] is returned, otherwise [None] is returned. *)\n\nFixpoint find_valnum_rhs (r: rhs) (eqs: list equation)\n                         {struct eqs} : option valnum :=\n  match eqs with\n  | nil => None\n  | Eq v str r' :: eqs1 =>\n      if str && eq_rhs r r' then Some v else find_valnum_rhs r eqs1\n  end.\n\n(** [find_valnum_rhs' rhs eqs] is similar, but also accepts equations\n  of the form [vn >= rhs]. *)\n\nFixpoint find_valnum_rhs' (r: rhs) (eqs: list equation)\n                          {struct eqs} : option valnum :=\n  match eqs with\n  | nil => None\n  | Eq v str r' :: eqs1 =>\n      if eq_rhs r r' then Some v else find_valnum_rhs' r eqs1\n  end.\n\n(** [find_valnum_num vn eqs] searches the list of equations [eqs]\n  for an equation of the form [vn = rhs] for some equation [rhs].\n  If found, [Some rhs] is returned, otherwise [None] is returned. *)\n\nFixpoint find_valnum_num (v: valnum) (eqs: list equation)\n                         {struct eqs} : option rhs :=\n  match eqs with\n  | nil => None\n  | Eq v' str r' :: eqs1 =>\n      if str && peq v v' then Some r' else find_valnum_num v eqs1\n  end.\n\n(** [reg_valnum n vn] returns a register that is mapped to value number\n    [vn], or [None] if no such register exists. *)\n\nDefinition reg_valnum (n: numbering) (vn: valnum) : option reg :=\n  match PMap.get vn n.(num_val) with\n  | nil => None\n  | r :: rs => Some r\n  end.\n\n(** [regs_valnums] is similar, for a list of value numbers. *)\n\nFixpoint regs_valnums (n: numbering) (vl: list valnum) : option (list reg) :=\n  match vl with\n  | nil => Some nil\n  | v1 :: vs =>\n      match reg_valnum n v1, regs_valnums n vs with\n      | Some r1, Some rs => Some (r1 :: rs)\n      | _, _ => None\n      end\n  end.\n\n(** [find_rhs] return a register that already holds the result of the\n    given arithmetic operation or memory load, or a value more defined\n    than this result, according to the given\n    numbering.  [None] is returned if no such register exists. *)\n\nDefinition find_rhs (n: numbering) (rh: rhs) : option reg :=\n  match find_valnum_rhs' rh n.(num_eqs) with\n  | None => None\n  | Some vres => reg_valnum n vres\n  end.\n\n(** Update the [num_val] mapping prior to a redefinition of register [r]. *)\n\nDefinition forget_reg (n: numbering) (rd: reg) : PMap.t (list reg) :=\n  match PTree.get rd n.(num_reg) with\n  | None => n.(num_val)\n  | Some v => PMap.set v (List.remove peq rd (PMap.get v n.(num_val))) n.(num_val)\n  end.\n\nDefinition update_reg (n: numbering) (rd: reg) (vn: valnum) : PMap.t (list reg) :=\n  let nv := forget_reg n rd in PMap.set vn (rd :: PMap.get vn nv) nv.\n\n(** [add_rhs n rd rhs] updates the value numbering [n] to reflect\n  the computation of the operation or load represented by [rhs]\n  and the storing of the result in register [rd].  If an equation\n  [vn = rhs] is known, register [rd] is set to [vn].  Otherwise,\n  a fresh value number [vn] is generated and associated with [rd],\n  and the equation [vn = rhs] is added. *)\n\nDefinition add_rhs (n: numbering) (rd: reg) (rh: rhs) : numbering :=\n  match find_valnum_rhs rh n.(num_eqs) with\n  | Some vres =>\n      {| num_next := n.(num_next);\n         num_eqs  := n.(num_eqs);\n         num_reg  := PTree.set rd vres n.(num_reg);\n         num_val  := update_reg n rd vres |}\n  | None =>\n      {| num_next := Psucc n.(num_next);\n         num_eqs  := Eq n.(num_next) true rh :: n.(num_eqs);\n         num_reg  := PTree.set rd n.(num_next) n.(num_reg);\n         num_val  := update_reg n rd n.(num_next) |}\n  end.\n\n(** [add_op n rd op rs] specializes [add_rhs] for the case of an\n  arithmetic operation.  The right-hand side corresponding to [op]\n  and the value numbers for the argument registers [rs] is built\n  and added to [n] as described in [add_rhs].   \n\n  If [op] is a move instruction, we simply assign the value number of\n  the source register to the destination register, since we know that\n  the source and destination registers have exactly the same value.\n  This enables more common subexpressions to be recognized. For instance:\n<<\n     z = add(x, y);  u = x; v = add(u, y);\n>>\n  Since [u] and [x] have the same value number, the second [add] \n  is recognized as computing the same result as the first [add],\n  and therefore [u] and [z] have the same value number. *)\n\nDefinition add_op (n: numbering) (rd: reg) (op: operation) (rs: list reg) :=\n  match is_move_operation op rs with\n  | Some r =>\n      let (n1, v) := valnum_reg n r in\n      {| num_next := n1.(num_next);\n         num_eqs  := n1.(num_eqs);\n         num_reg  := PTree.set rd v n1.(num_reg);\n         num_val  := update_reg n1 rd v |}\n  | None =>\n      let (n1, vs) := valnum_regs n rs in\n      add_rhs n1 rd (Op op vs)\n  end.\n\n(** [add_load n rd chunk addr rs] specializes [add_rhs] for the case of a\n  memory load.  The right-hand side corresponding to [chunk], [addr]\n  and the value numbers for the argument registers [rs] is built\n  and added to [n] as described in [add_rhs]. *)\n\nDefinition add_load (n: numbering) (rd: reg) \n                    (chunk: memory_chunk) (addr: addressing)\n                    (rs: list reg) :=\n  let (n1, vs) := valnum_regs n rs in\n  add_rhs n1 rd (Load chunk addr vs).\n\n(** [set_unknown n rd] returns a numbering where [rd] is mapped to \n  no value number, and no equations are added.  This is useful\n  to model instructions with unpredictable results such as [Ibuiltin]. *)\n\nDefinition set_unknown (n: numbering) (rd: reg) :=\n  {| num_next := n.(num_next);\n     num_eqs  := n.(num_eqs);\n     num_reg  := PTree.remove rd n.(num_reg);\n     num_val  := forget_reg n rd |}.\n\n(** [kill_equations pred n] remove all equations satisfying predicate [pred]. *)\n\nFixpoint kill_eqs (pred: rhs -> bool) (eqs: list equation) : list equation :=\n  match eqs with\n  | nil => nil\n  | (Eq l strict r) as eq :: rem =>\n      if pred r then kill_eqs pred rem else eq :: kill_eqs pred rem\n  end.\n\nDefinition kill_equations (pred: rhs -> bool) (n: numbering) : numbering :=\n  {| num_next := n.(num_next);\n     num_eqs  := kill_eqs pred n.(num_eqs);\n     num_reg  := n.(num_reg);\n     num_val  := n.(num_val) |}.\n\n(** [kill_all_loads n] removes all equations involving memory loads,\n  as well as those involving memory-dependent operators.\n  It is used to reflect the effect of a builtin operation, which can\n  change memory in unpredictable ways and potentially invalidate all such equations. *)\n\nDefinition filter_loads (r: rhs) : bool :=\n  match r with\n  | Op op _ => op_depends_on_memory op\n  | Load _ _ _ => true\n  end.\n\nDefinition kill_all_loads (n: numbering) : numbering :=\n  kill_equations filter_loads n.\n\n(** [kill_loads_after_store app n chunk addr args] removes all equations\n  involving loads that could be invalidated by a store of quantity [chunk]\n  at address determined by [addr] and [args].  Loads that are disjoint\n  from this store are preserved.  Equations involving memory-dependent\n  operators are also removed. *)\n\nDefinition filter_after_store (app: VA.t) (n: numbering) (p: aptr) (sz: Z) (r: rhs) :=\n  match r with\n  | Op op vl =>\n      op_depends_on_memory op\n  | Load chunk addr vl =>\n      match regs_valnums n vl with\n      | None => true\n      | Some rl =>\n          negb (pdisjoint (aaddressing app addr rl) (size_chunk chunk) p sz)\n      end\n  end.\n\nDefinition kill_loads_after_store\n             (app: VA.t) (n: numbering)\n             (chunk: memory_chunk) (addr: addressing) (args: list reg) :=\n  let p := aaddressing app addr args in\n  kill_equations (filter_after_store app n p (size_chunk chunk)) n.\n\n(** [add_store_result n chunk addr rargs rsrc] updates the numbering [n]\n  to reflect the knowledge gained after executing an instruction\n  [Istore chunk addr rargs rsrc].  An equation [vsrc >= Load chunk addr vargs]\n  is added, but only if the value of [rsrc] is known to be normalized\n  with respect to [chunk]. *)\n\nDefinition store_normalized_range (chunk: memory_chunk) : aval :=\n  match chunk with\n  | Mint8signed => Sgn 8\n  | Mint8unsigned => Uns 8\n  | Mint16signed => Sgn 16\n  | Mint16unsigned => Uns 16\n  | _ => Vtop\n  end.\n\nDefinition add_store_result (app: VA.t) (n: numbering) (chunk: memory_chunk) (addr: addressing)\n                            (rargs: list reg) (rsrc: reg) :=\n  if vincl (avalue app rsrc) (store_normalized_range chunk) then\n    let (n1, vsrc) := valnum_reg n rsrc in\n    let (n2, vargs) := valnum_regs n1 rargs in\n    {| num_next := n2.(num_next);\n       num_eqs  := Eq vsrc false (Load chunk addr vargs) :: n2.(num_eqs);\n       num_reg  := n2.(num_reg);\n       num_val  := n2.(num_val) |}\n  else n.\n\n(** [kill_loads_after_storebyte app n dst sz] removes all equations\n  involving loads that could be invalidated by a store of [sz] bytes\n  starting at address [dst]. Loads that are disjoint from this\n  store-bytes are preserved.  Equations involving memory-dependent\n  operators are also removed. *)\n\nDefinition kill_loads_after_storebytes\n             (app: VA.t) (n: numbering) (dst: reg) (sz: Z) :=\n  let p := aaddr app dst in\n  kill_equations (filter_after_store app n p sz) n.\n\n(** [add_memcpy app n1 n2 rsrc rdst sz] adds equations to [n2] that \n  represent the effect of a [memcpy] block copy operation of [sz] bytes\n  from the address denoted by [rsrc] to the address denoted by [rdst].\n  [n2] is the numbering returned by [kill_loads_after_storebytes]\n  and [n1] is the original numbering before the [memcpy] operation.\n  Valid equations (found in [n1]) involving loads within the source\n  area of the [memcpy] are translated as equations involving loads\n  within the destination area, and added to numbering [n2].\n  Currently, we only track [memcpy] operations between stack\n  locations, as often occur when compiling assignments between local C\n  variables of struct type. *)\n\nDefinition shift_memcpy_eq (src sz delta: Z) (e: equation) :=\n  match e with\n  | Eq l strict (Load chunk (Ainstack i) _) =>\n      let i := Int.unsigned i in\n      let j := i + delta in\n      if zle src i\n      && zle (i + size_chunk chunk) (src + sz)\n      && zeq (Zmod delta (align_chunk chunk)) 0\n      && zle 0 j\n      && zle j Int.max_unsigned\n      then Some(Eq l strict (Load chunk (Ainstack (Int.repr j)) nil))\n      else None\n  | _ => None\n  end.\n\nFixpoint add_memcpy_eqs (src sz delta: Z) (eqs1 eqs2: list equation) :=\n  match eqs1 with\n  | nil => eqs2\n  | e :: eqs =>\n      match shift_memcpy_eq src sz delta e with\n      | None => add_memcpy_eqs src sz delta eqs eqs2\n      | Some e' => e' :: add_memcpy_eqs src sz delta eqs eqs2\n      end\n  end.\n\nDefinition add_memcpy (app: VA.t) (n1 n2: numbering) (rsrc rdst: reg) (sz: Z) :=\n  match aaddr app rsrc, aaddr app rdst with\n  | Stk src, Stk dst =>\n      {| num_next := n2.(num_next);\n         num_eqs  := add_memcpy_eqs (Int.unsigned src) sz\n                                    (Int.unsigned dst - Int.unsigned src)\n                                    n1.(num_eqs) n2.(num_eqs);\n         num_reg  := n2.(num_reg);\n         num_val  := n2.(num_val) |}\n  | _, _ => n2\n  end.\n\n(** Take advantage of known equations to select more efficient\n  forms of operations, addressing modes, and conditions. *)\n\nSection REDUCE.\n\nVariable A: Type.\nVariable f: (valnum -> option rhs) -> A -> list valnum -> option (A * list valnum).\nVariable n: numbering.\n\nFixpoint reduce_rec (niter: nat) (op: A) (args: list valnum) : option(A * list reg) :=\n  match niter with\n  | O => None\n  | Datatypes.S niter' =>\n      match f (fun v => find_valnum_num v n.(num_eqs)) op args with\n      | None => None\n      | Some(op', args') =>\n          match reduce_rec niter' op' args' with\n          | None =>\n              match regs_valnums n args' with Some rl => Some(op', rl) | None => None end\n          | Some _ as res =>\n              res\n          end\n      end\n  end.\n\nDefinition reduce (op: A) (rl: list reg) (vl: list valnum) : A * list reg :=\n  match reduce_rec 4%nat op vl with\n  | None     => (op, rl)\n  | Some res => res\n  end.\n\nEnd REDUCE.\n\n(** * The static analysis *)\n\n(** We now equip the type [numbering] with a partial order and a greatest\n  element.  The partial order is based on entailment: [n1] is greater\n  than [n2] if [n1] is satisfiable whenever [n2] is.  The greatest element\n  is, of course, the empty numbering (no equations). *)\n\nModule Numbering.\n  Definition t := numbering.\n  Definition ge (n1 n2: numbering) : Prop :=\n    forall valu ge sp rs m, \n    numbering_holds valu ge sp rs m n2 ->\n    numbering_holds valu ge sp rs m n1.\n  Definition top := empty_numbering.\n  Lemma top_ge: forall x, ge top x.\n  Proof.\n    intros; red; intros. unfold top. apply empty_numbering_holds.\n  Qed.\n  Lemma refl_ge: forall x, ge x x.\n  Proof.\n    intros; red; auto.\n  Qed.\nEnd Numbering.\n\n(** We reuse the solver for forward dataflow inequations based on\n  propagation over extended basic blocks defined in library [Kildall]. *)\n\nModule Solver := BBlock_solver(Numbering).\n\n(** The transfer function for the dataflow analysis returns the numbering\n  ``after'' execution of the instruction at [pc], as a function of the\n  numbering ``before''.  For [Iop] and [Iload] instructions, we add\n  equations or reuse existing value numbers as described for\n  [add_op] and [add_load].  For [Istore] instructions, we forget\n  equations involving memory loads at possibly overlapping locations,\n  then add an equation for loads from the same location stored to.\n  For [Icall] instructions, we could simply associate a fresh, unconstrained by equations value number\n  to the result register.  However, it is often undesirable to eliminate\n  common subexpressions across a function call (there is a risk of \n  increasing too much the register pressure across the call), so we\n  just forget all equations and start afresh with an empty numbering.\n  Finally, for instructions that modify neither registers nor\n  the memory, we keep the numbering unchanged.\n\n  For builtin invocations [Ibuiltin], we have three strategies:\n- Forget all equations.  This is appropriate for builtins that can be\n  turned into function calls ([EF_external], [EF_malloc], [EF_free]).\n- Forget equations involving loads but keep equations over registers.\n  This is appropriate for builtins that can modify memory,\n  e.g. volatile stores, or [EF_builtin]\n- Keep all equations, taking advantage of the fact that neither memory\n  nor registers are modified.  This is appropriate for annotations\n  and for volatile loads.\n*)\n\nDefinition transfer (f: function) (approx: PMap.t VA.t) (pc: node) (before: numbering) :=\n  match f.(fn_code)!pc with\n  | None => before\n  | Some i =>\n      match i with\n      | Inop s =>\n          before\n      | Iop op args res s =>\n          add_op before res op args\n      | Iload chunk addr args dst s =>\n          add_load before dst chunk addr args\n      | Istore chunk addr args src s =>\n          let app := approx!!pc in\n          let n := kill_loads_after_store app before chunk addr args in\n          add_store_result app n chunk addr args src\n      | Icall sig ros args res s =>\n          empty_numbering\n      | Itailcall sig ros args =>\n          empty_numbering\n      | Ibuiltin ef args res s =>\n          match ef with\n          | EF_inline_asm _ =>\n              empty_numbering\n          | EF_i64_builtin _ | EF_builtin _ _ | EF_vstore _ | EF_vstore_global _ _ _ =>\n              set_unknown (kill_all_loads before) res\n          | EF_memcpy sz al =>\n              match args with\n              | rdst :: rsrc :: nil =>\n                  let app := approx!!pc in\n                  let n := kill_loads_after_storebytes app before rdst sz in\n                  set_unknown (add_memcpy app before n rsrc rdst sz) res\n              | _ =>\n                  empty_numbering\n              end\n          | EF_vload _ | EF_vload_global _ _ _ | EF_annot _ _ | EF_annot_val _ _ =>\n              set_unknown before res\n          end\n      | Icond cond args ifso ifnot =>\n          before\n      | Ijumptable arg tbl =>\n          before\n      | Ireturn optarg =>\n          before\n      end\n  end.\n\n(** The static analysis solves the dataflow inequations implied\n  by the [transfer] function using the ``extended basic block'' solver,\n  which produces sub-optimal solutions quickly.  The result is\n  a mapping from program points to numberings. *)\n\nDefinition analyze (f: RTL.function) (approx: PMap.t VA.t): option (PMap.t numbering) :=\n  Solver.fixpoint (fn_code f) successors_instr (transfer f approx) f.(fn_entrypoint).\n\n(** * Code transformation *)\n\n(** The code transformation is performed instruction by instruction.\n  [Iload] instructions and non-trivial [Iop] instructions are turned\n  into move instructions if their result is already available in a\n  register, as indicated by the numbering inferred at that program point.\n\n  Some operations are so cheap to compute that it is generally not\n  worth reusing their results.  These operations are detected by the\n  function [is_trivial_op] in module [Op]. *)\n\nDefinition transf_instr (n: numbering) (instr: instruction) :=\n  match instr with\n  | Iop op args res s =>\n      if is_trivial_op op then instr else\n        let (n1, vl) := valnum_regs n args in\n        match find_rhs n1 (Op op vl) with\n        | Some r =>\n            Iop Omove (r :: nil) res s\n        | None =>\n            let (op', args') := reduce _ combine_op n1 op args vl in\n            Iop op' args' res s\n        end\n  | Iload chunk addr args dst s =>\n      let (n1, vl) := valnum_regs n args in\n      match find_rhs n1 (Load chunk addr vl) with\n      | Some r =>\n          Iop Omove (r :: nil) dst s\n      | None =>\n          let (addr', args') := reduce _ combine_addr n1 addr args vl in\n          Iload chunk addr' args' dst s\n      end\n  | Istore chunk addr args src s =>\n      let (n1, vl) := valnum_regs n args in\n      let (addr', args') := reduce _ combine_addr n1 addr args vl in\n      Istore chunk addr' args' src s\n  | Icond cond args s1 s2 =>\n      let (n1, vl) := valnum_regs n args in\n      let (cond', args') := reduce _ combine_cond n1 cond args vl in\n      Icond cond' args' s1 s2\n  | _ =>\n      instr\n  end.\n\nDefinition transf_code (approxs: PMap.t numbering) (instrs: code) : code :=\n  PTree.map (fun pc instr => transf_instr approxs!!pc instr) instrs.\n\nDefinition vanalyze := ValueAnalysis.analyze.\n\nDefinition transf_function (rm: romem) (f: function) : res function :=\n  let approx := vanalyze rm f in\n  match analyze f approx with\n  | None => Error (msg \"CSE failure\")\n  | Some approxs =>\n      OK(mkfunction\n           f.(fn_sig)\n           f.(fn_params)\n           f.(fn_stacksize)\n           (transf_code approxs f.(fn_code))\n           f.(fn_entrypoint))\n  end.\n\nDefinition transf_fundef (rm: romem) (f: fundef) : res fundef :=\n  AST.transf_partial_fundef (transf_function rm) f.\n\nDefinition transf_program (p: program) : res program :=\n  transform_partial_program (transf_fundef (romem_for_program p)) p.\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/backend/CSE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24589668229312237}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of CFGV project.\n\n  CFGV is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  CFGV is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with CFGV.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/CFGVLFMTP2014/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\nSet Implicit Arguments.\nRequire Export AlphaEqProps.\nRequire Import Omega.\n\n\nLtac EqDecRefl :=\n  let dec:= fresh \"dec\" in\n  let HH:= fresh \"Hrefl\" in\nrepeat match goal with\n[pp : @eq ?T ?ta ?tb |- _ ] => \n  assert (Deq T) as dec by eauto with Deq;\n  pose proof (UIPReflDeq dec _ pp) as HH;\n  try rewrite HH; clear HH dec\nend.\n\nLtac EqDec ta tb :=\n  let dec:= fresh \"dec\" in\n  let Heq:= fresh \"Heq\" ta tb in\n  let Hneq:= fresh \"Hneq\" ta tb in\n  let T := type of ta in\n  assert (Deq T) as dec by eauto with Deq;\n  destruct (dec ta tb) as [Heq| Hneq]; clear dec.\n\n\nDefinition tAlphaEqG {G} (sa sb : GSym G) \n  (vc: VarSym G ) (ta : Term sa) (tb : Term sb):=\nmatch (deqGSym sa sb) with\n| left eqq => tAlphaEq vc (transport eqq ta) tb\n| right eqq => False\nend.\n\nDefinition pAlphaEqG {G} (sa sb : GSym G) \n  (vc: VarSym G ) (ta : Pattern sa) (tb : Pattern sb):=\nmatch (deqGSym sa sb) with\n| left eqq => pAlphaEq vc (transport eqq ta) tb\n| right eqq => False\nend.\n\nLtac notAlpha :=\n  let Halc := fresh \"Halc\" in\n  let AlphaTac := introv Halc;\n    inverts Halc;\n    EqDecSndEq;\n    subst;\n    contradiction in\n  let Hseq := fresh  \"Hseq\" in\n  let Hseqd := fresh  \"Hseqd\" in\n  try(AlphaTac);\n  unfold  tAlphaEqG; unfold  pAlphaEqG;\n  match goal with\n  [|- context [deqGSym ?l ?l]] =>\n    rewrite DeqTrue; simpl; AlphaTac\n  | [|- context [deqGSym ?l ?r]] =>\n    destruct (deqGSym l r) as [Hseq |?]; cpx;\n    duplicate Hseq as Hseqd;\n    inverts Hseq; cpx ; try subst; cpx\n  end.\n\nLemma decideAbsT {G} (vc : VarSym G) \n  (sa : GSym G) (ta: Term sa)\n(Hdt : forall phnew : Term sa,\n      tSize phnew <= tSize ta ->\n      forall (sb : GSym G) (tb : Term sb), \n     decidable (tAlphaEqG vc phnew tb))\n(sb : GSym G) (tb: Term sa)\n(la lb :(list (vType vc))) :\ndecidable (AlphaEqAbs (termAbs vc la ta) (termAbs vc lb tb)).\nProof.\n  remember (beq_nat (length la) (length lb)) as blen.\n  destruct blen;\n    [\n        applysym beq_nat_true in Heqblen\n      | \n        right ;\n        applysym beq_nat_false in Heqblen;\n        introv Hal; inverts Hal;\n        EqDecSndEq; omega\n    ].\n  remember (GFreshVars (la++lb\n              ++ tAllVars ta++tAllVars tb) la) as lvn.\n  remember (tSwap ta (combine la lvn)) as phnew.\n  pose proof (tcase \n        (@swapPreservesSize G vc (combine la lvn)) _ ta) as Hs.\n  specialize (Hdt (tSwap ta (combine la lvn))).\n  rewrite Hs in Hdt.\n  dimp Hdt. apply Hdt with \n        (tb:= (tSwap tb (combine lb lvn))) in hyp.\n  unfold tAlphaEqG in hyp.\n  rewrite DeqTrue in hyp. allsimpl.\n  clear Hs  Hdt.\n  clear dependent phnew.\n  destruct hyp as [? | Hnal];[left| right];\n  pose proof (FreshDistVarsSpec \n      (la ++ lb ++ tAllVars ta ++ tAllVars tb) la ) as XX;\n  rewrite <- Heqlvn in XX;\n  simpl in XX; repnd; dands;\n  symmetry in XX.\n  - apply alAbT with (lbnew:=lvn); \n        cpx; try congruence;\n    unfold tFresh; allsimpl; repeat(disjoint_reasoning).\n  - introv Hal. apply Hnal. clear Hnal. clear Heqlvn.\n    apply betterAbsTElim \n    with (lvAvoid:= lvn) in Hal.\n     allsimpl. exrepnd.\n    apply tAlphaEqEquivariantRev with \n    (sw := combine lvn lbnew).\n    autorewrite with SwapAppR.\n    unfold tFresh in Hal3.\n    allsimpl. repnd.\n    symmetry in XX.\n    autorewrite with slow; try congruence;\n    cpx; repeat (disjoint_reasoning);\n    repeat match goal with\n    [ H : disjoint _ _ |- _ ] => clear H\n    | [ H : no_repeats _ _ |- _ ] => clear H\n    end.\nDefined.\n\n\nLemma decideAbsP {G} (vc : VarSym G) \n  (sa : GSym G) (ta: Pattern sa)\n(Hdt : forall phnew : Pattern sa,\n      pSize phnew <= pSize ta ->\n      forall (sb : GSym G) (tb : Pattern sb),\n        decidable (pAlphaEqG vc phnew tb))\n(sb : GSym G) (tb: Pattern sa)\n(la lb :(list (vType vc))) :\ndecidable (AlphaEqAbs (patAbs vc la ta) (patAbs vc lb tb)).\nProof.\n  remember (beq_nat (length la) (length lb)) as blen.\n  destruct blen;\n    [\n        applysym beq_nat_true in Heqblen\n      | \n        right ;\n        applysym beq_nat_false in Heqblen;\n        introv Hal; inverts Hal;\n        EqDecSndEq; omega\n    ].\n  remember (GFreshVars (la++lb\n              ++ pAllVars ta++pAllVars tb) la) as lvn.\n  remember (pSwap ta (combine la lvn)) as phnew.\n  pose proof (pcase \n        (@swapPreservesSize G vc (combine la lvn)) _ ta) as Hs.\n  specialize (Hdt (pSwap ta (combine la lvn))).\n  rewrite Hs in Hdt.\n  dimp Hdt. apply Hdt with \n        (tb:= (pSwap tb (combine lb lvn))) in hyp.\n  unfold pAlphaEqG in hyp.\n  rewrite DeqTrue in hyp. allsimpl.\n  clear Hs  Hdt.\n  clear dependent phnew.\n  destruct hyp as [? | Hnal];[left| right];\n  pose proof (FreshDistVarsSpec \n      (la ++ lb ++ pAllVars ta ++ pAllVars tb) la ) as XX;\n  rewrite <- Heqlvn in XX;\n  simpl in XX; repnd; dands;\n  symmetry in XX.\n  - apply alAbP with (lbnew:=lvn); \n        cpx; try congruence;\n    unfold pFresh; allsimpl; repeat(disjoint_reasoning).\n  - introv Hal. apply Hnal. clear Hnal. clear Heqlvn.\n    apply betterAbsPElim \n    with (lvAvoid:= lvn) in Hal.\n     allsimpl. exrepnd.\n    apply pAlphaEqEquivariantRev with \n    (sw := combine lvn lbnew).\n    autorewrite with SwapAppR.\n    unfold pFresh in Hal3.\n    allsimpl. repnd.\n    symmetry in XX.\n    autorewrite with slow; try congruence;\n    cpx; repeat (disjoint_reasoning);\n    repeat match goal with\n    [ H : disjoint _ _ |- _ ] => clear H\n    | [ H : no_repeats _ _ |- _ ] => clear H\n    end.\nDefined.\n\nDefinition diffVarClasses{G} {sa : GSym G} (ta: Term sa)\n            {sb: GSym G} (tb : Term sb) :=\nmatch (ta, tb) with\n| (vleaf vca va, vleaf vcb vb) \n    => match (DeqVarSym vca vcb) with\n      |left _ => False\n      |right _ => True\n      end\n| _ => False\nend.\n\nDefinition diffPVarClasses{G} \n        {sa : GSym G} (ta: Pattern sa)\n        {sb: GSym G} (tb : Pattern sb) :=\nmatch (ta, tb) with\n| (pvleaf vca va, pvleaf vcb vb) \n    => match (DeqVarSym vca vcb) with\n      |left _ => False\n      |right _ => True\n      end\n| _ => False\nend.\n\n\nDefinition diffTProdsNode {G} {sa : GSym G} (ta: Term sa)\n            {sb: GSym G} (tb : Term sb) :=\nmatch (ta, tb) with\n| (tnode pa va, tnode pb vb) \n    => match (deqPr G pa pb) with\n      |left _ => False\n      |right _ => True\n      end\n| _ => False\nend.\n\nDefinition diffPProdsNode {G} {sa : GSym G} \n        (ta: Pattern sa)\n            {sb: GSym G} (tb : Pattern sb) :=\nmatch (ta, tb) with\n| (pnode pa va, pnode pb vb) \n    => match (deqPPr G pa pb) with\n      |left _ => False\n      |right _ => True\n      end\n| _ => False\nend.\n\nDefinition diffEmbedNode {G} {sa : GSym G} \n        (ta: Pattern sa)\n            {sb: GSym G} (tb : Pattern sb) :=\nmatch (ta, tb) with\n| (embed pa va, embed pb vb) \n    => match (deqEm G pa pb) with\n      |left _ => False\n      |right _ => True\n      end\n| _ => False\nend.\n\n\nDefinition isVLeaf {G} {sa : GSym G} (ta: Term sa) :=\nmatch ta with\n| vleaf vca va \n    => True\n| _ => False\nend.\n\nDefinition isPNode {G} {sa : GSym G} \n  (ta: Pattern sa) :=\nmatch ta with\n| pnode vca va \n    => True\n| _ => False\nend.\n\nDefinition isEmbed {G} {sa : GSym G} \n  (ta: Pattern sa) :=\nmatch ta with\n| embed vca va \n    => True\n| _ => False\nend.\n\n\nLemma alphaEqDecidable : forall {G} (vc : VarSym G),\n     (  (forall (sa : GSym G) (ta: Term sa)\n            (sb: GSym G) (tb : Term sb),\n           decidable (tAlphaEqG vc ta tb))\n         *\n        (forall (sa : GSym G) (ta: Pattern sa)\n            (sb: GSym G) (tb : Pattern sb),\n            decidable (pAlphaEqG vc ta tb))\n         *\n        (forall (l : MixtureParam) (ma mb : Mixture l) \n        (lbva : list (list (vType vc)))\n        (lbvb : list (list (vType vc))),\n           decidable \n              (lAlphaEqAbs (MakeAbstractions vc ma lbva) \n                           (MakeAbstractions vc mb lbvb)))).\nProof.\n  intros.\n  GInductionS; introns Hyp; intros;  allsimpl.\n- Case \"tleaf\".\n  destruct tb;[ | right; notAlpha | right; notAlpha];[].\n  \n  EqDec T T0; [| right; notAlpha]; subst.\n  EqDec t t0; [left|right]; subst;\n  unfold tAlphaEqG; try rewrite DeqTrue; allsimpl;\n  eauto with Alpha;[]; notAlpha.\n\n- Case \"vleaf\".\n  destruct tb; [right; notAlpha | |].\n  + EqDec vc0 vc1;[| right]; subst; try EqDecRefl; simpl.\n    * EqDec v v0; [left|right]; subst; unfolds_base;\n      try rewrite DeqTrue;\n      eauto with Alpha.\n      notAlpha.\n\n    * notAlpha.\n      revert Hseqd0.\n      remember (vleaf vc0 v) as vvl.\n      remember (vleaf vc1 v0) as vvr.\n      assert ( diffVarClasses vvl vvr) as Hdd\n       by (subst; unfold diffVarClasses;\n          cases_if; cpx).\n      clear Heqvvr Heqvvl.\n      remember (vSubstType G vc0).\n      remember (vSubstType G vc1).\n      generalize dependent vvl.\n      generalize dependent vvr.\n      rewrite H0.\n      intros. allsimpl.\n      EqDecRefl. simpl.\n      clear dependent t.\n      clear Hneqvc0vc1.\n      clear v0 v vc0 Heqt0 Hseqd0 vc1. introv Hc; inverts Hc;\n      EqDecSndEq; subst vvl; subst vvr; repnud Hdd; allsimpl; cpx.\n      rewrite DeqTrue in Hdd.\n      trivial.\n  + right. notAlpha.\n    introv Hal. inverts Hal.\n    EqDecSndEq.\n    GC. clear H6. clear X. clear H0.\n    generalize dependent H3. \n    remember (vleaf vc0 v) as xx.\n    assert (isVLeaf xx) as Hxx by (subst;simpl; auto).\n    clear Heqxx.\n    generalize dependent xx.\n    rewrite Hseqd0. \n    allsimpl.\n    introv Hisv Heq.\n    inverts keep Heq.\n    cpx.\n- Case \"tnode\".\n  destruct tb; [right; notAlpha;fail | |].\n\n    right. notAlpha;\n    remember (vleaf vc0 v) as xx.\n    assert (isVLeaf xx) as Hxx by (subst;simpl; auto).\n    clear Heqxx.\n    generalize dependent xx.\n    rewrite <- Hseqd0. \n    allsimpl.\n    introv Hisv Heq.\n    inverts Heq. EqDecSndEq. subst xx.\n    cpx; fail.\n\n    EqDec p p0;[| right].\n    Focus 2. notAlpha.\n    introv Hal.\n\n    remember (tnode p m) as vvl.\n    remember (tnode p0 m0) as vvr.\n    assert (diffTProdsNode vvl vvr) as Hdd\n     by (subst; unfold diffTProdsNode;\n        cases_if; cpx).\n    clear Heqvvr Heqvvl.\n    remember (tpLhs G p).\n    remember (tpLhs G p0).\n    generalize dependent vvl.\n    generalize dependent vvr.\n    generalize Hseqd0.\n    rewrite H0.\n    introv. allsimpl.\n    EqDecRefl. simpl.\n    clear dependent t.\n    introv Hta Hdd.\n    clear Hseqd1 Heqt0  Hneqpp0 m0 Hyp m.\n    inverts Hta;\n    EqDecSndEq;\n    subst vvl; subst vvr; repnud Hdd; allsimpl; cpx.\n    rewrite DeqTrue in Hdd;\n    trivial; fail.\n\n\n  (* back to the real business *)\n  subst p0. unfold tAlphaEqG.\n  rewrite DeqTrue.\n  simpl. rename m0 into mb.\n  destruct (Hyp mb (allBndngVars vc p m) (allBndngVars vc p mb)) as\n    [Hleq | Hnleq];[left; constructor;auto | right; notAlpha].\n      \n- Case \"ptleaf\".\n  destruct tb;[ | right; notAlpha \n                | right; notAlpha \n                | right; notAlpha]; [].\n  \n  EqDec T T0; [| right; notAlpha]; subst;[].\n  EqDec t t0; [left|right]; subst;\n  unfold pAlphaEqG; try rewrite DeqTrue; allsimpl;\n  eauto with Alpha;[]; notAlpha.\n    \n- Case \"pvleaf\".\n  destruct tb;[ right; notAlpha | \n                | right; notAlpha \n                | right; notAlpha]; [].\n  EqDec vc0 vc1;[ left;subst; try EqDecRefl; simpl;\n                  unfold pAlphaEqG; rewrite DeqTrue\n                  ; constructor; fail\n                | right; notAlpha].\n    \n- Case \"pembed\".\n  destruct tb;[ right; notAlpha \n                | right; notAlpha |\n                | right; notAlpha].\n\n  Focus 2.\n    introv Hal. inverts Hal.\n    EqDecSndEq.\n    GC. clear H6. clear X. clear H0.\n    generalize dependent H3.\n    remember (embed p t) as xx.\n    assert (isEmbed xx) as Hxx by (subst;simpl; auto).\n    clear Heqxx.\n    generalize dependent xx.\n    rewrite Hseqd0. \n    allsimpl.\n    introv Hisv Heq.\n    inverts keep Heq.\n    cpx; fail.\n\n\n  EqDec p p0;[ subst p0; unfold pAlphaEqG; rewrite DeqTrue\n               | right; notAlpha].\n  Focus 2.\n    remember (embed p t) as vvl.\n    remember (embed p0 t0) as vvr.\n    assert (diffEmbedNode vvl vvr) as Hdd\n     by (subst; unfold diffEmbedNode;\n        cases_if; cpx).\n    clear Heqvvr Heqvvl.\n    remember (epLhs G p).\n    remember (epLhs G p0).\n    generalize dependent vvl.\n    generalize dependent vvr.\n    generalize Hseqd0.\n    rewrite H0.\n    introv. allsimpl.\n    EqDecRefl. simpl.\n    clear dependent p.\n    introv Hta Hdd.\n    clear H0 Hseqd1 Hseqd0 Heqp2 p1 t0 p0.\n    inverts Hdd;\n    EqDecSndEq;\n    subst vvl; subst vvr; repnud Hta; allsimpl; cpx.\n    rewrite DeqTrue in Hta;\n    trivial; fail.\n\n\n\n  (* back to the real business *)\n  simpl.\n  pose proof (Hyp _ t0) as Hd.\n  unfold tAlphaEqG in Hd.\n  rewrite DeqTrue in Hd.\n  simpl in Hd.\n  destruct Hd;[left; constructor; trivial | right; notAlpha].\n  \n- Case \"pnode\".\n  destruct tb;[ right; notAlpha \n                | right; notAlpha \n                | right; notAlpha| ].\n\n    introv Hal. inverts Hal.\n    EqDecSndEq.\n    GC. clear H6. clear X. clear H0.\n    generalize dependent H3.\n    remember (pnode p m) as xx.\n    assert (isPNode xx) as Hxx by (subst;simpl; auto).\n    clear Heqxx.\n    generalize dependent xx.\n    rewrite Hseqd0. \n    allsimpl.\n    introv Hisv Heq.\n    inverts keep Heq.\n    cpx; fail.\n\n    EqDec p p0;[| right].\n    Focus 2. notAlpha.\n    remember (pnode p m) as vvl.\n    remember (pnode p0 m0) as vvr.\n    assert (diffPProdsNode vvl vvr) as Hdd\n     by (subst; unfold diffPProdsNode;\n        cases_if; cpx).\n    clear Heqvvr Heqvvl.\n    remember (ppLhs G p).\n    remember (ppLhs G p0).\n    generalize dependent vvl.\n    generalize dependent vvr.\n    generalize Hseqd0.\n    rewrite H0.\n    introv. allsimpl.\n    EqDecRefl. simpl.\n    clear dependent p.\n    introv Hta Hdd.\n    clear H0 Hseqd1 Hseqd0 Heqp2 p1 m0 p0.\n    inverts Hdd;\n    EqDecSndEq;\n    subst vvl; subst vvr; repnud Hta; allsimpl; cpx.\n    rewrite DeqTrue in Hta;\n    trivial; fail.\n\n    (* back to the real business *)\n  subst p0. unfold pAlphaEqG.\n  rewrite DeqTrue.\n  simpl. rename m0 into mb.\n  destruct (Hyp mb [] []) as\n  [Hleq | Hnleq];[left; constructor;auto | right; notAlpha].\n\n- Case \"mnil\".\n  dependent inversion mb. simpl. left.\n  constructor.\n\n  \n- Case \"mtcons\".\n  dependent inversion mb. simpl.\n  subst. \n  remember (lhead lbva) as lha.\n  remember (lhead lbvb) as lhb.\n  remember (tail lbva) as lta.\n  remember (tail lbvb) as ltb.\n  clear Heqlha Heqlhb Heqlta Heqltb.\n  specialize (Hyp0 m lta ltb).\n  destruct (Hyp0); [| right ; notAlpha].\n  destruct (decideAbsT vc ph Hyp h t lha lhb);\n    [left; constructor; auto| right; notAlpha].\n  \n- Case \"mpcons\".\n  dependent inversion mb. simpl.\n  subst. \n  remember (lhead lbva) as lha.\n  remember (lhead lbvb) as lhb.\n  remember (tail lbva) as lta.\n  remember (tail lbvb) as ltb.\n  clear Heqlha Heqlhb Heqlta Heqltb.\n  specialize (Hyp0 m lta ltb).\n  destruct (Hyp0); [| right ; notAlpha].\n  destruct (decideAbsP vc ph Hyp h p lha lhb);\n    [left; constructor; auto| right; notAlpha].\nDefined.\n \n(*\nDefinition transpEm {G} {pl pr : EmbedProd G}\n  (eqq : pl = pr)\n  (tl : Term (gsymTN (epRhs G pl))) :=\n(@transport _ _ _ (fun p => Term (gsymTN (epRhs G p)))  eqq tl).\n\nFixpoint tAlphaEqb {G} (vc : VarSym G) {gs : GSym G}\n  (tl tr : Term gs) {struct tr}: bool :=\nmatch (tl,tr) with\n| (tnode pl ml, tnode pr mr) => true\n| (tleaf tcl tl, tleaf tcr tr) \n    => Deq2Bool (deqSigTSemType) \n          (existT _ tcl tl) (existT _ tcr tr)\n| (vleaf tcl tl, vleaf tcr tr) \n    => Deq2Bool (deqSigVType) \n          (existT _ tcl tl) (existT _ tcr tr)\n| _ => false\nend\nwith  pAlphaEqb {G} (vc : VarSym G) {gs : GSym G}\n  (tl tr : Pattern gs) {struct tr} : bool :=\nmatch (tl,tr) with\n| (pnode pl ml, pnode pr mr) => true\n| (ptleaf tcl tl, ptleaf tcr tr) \n    => Deq2Bool (deqSigTSemType) \n          (existT _ tcl tl) (existT _ tcr tr)\n| (pvleaf tcl tl, pvleaf tcr tr) \n    => Deq2Bool (deqSigVType) \n          (existT _ tcl tl) (existT _ tcr tr)\n| (embed pl tl, embed pr tr) =>\n     match (deqEm G pl pr) with\n     | right _ => false\n     | left eqq => tAlphaEqb vc (transpEm eqq tl) tr\n     end\n| _ => false\nend\nwith AlphaEqAbsb {G} (vc : VarSym G)\n  (tl tr : Abstraction G vc) {struct tr}: bool :=\nmatch (tl,tr) with\n| (termAbs gsl lvl tll, termAbs gsr lvr trr) => \n    (beq_nat (length lvl) (length lvr)) &&\n    match (deqGSym gsl gsr) with\n    | right _ => false\n    | left eqq => tAlphaEqb vc (transport eqq tll) trr\n    end    \n| (patAbs _ lvl tl, patAbs _ lvr tr) => true\n|  _ => false\nend.\n  \n\n*)\n", "meta": {"author": "coq-contribs", "repo": "cfgv", "sha": "d9f4d58ddf571639217f0ba1706e1141921a693a", "save_path": "github-repos/coq/coq-contribs-cfgv", "path": "github-repos/coq/coq-contribs-cfgv/cfgv-d9f4d58ddf571639217f0ba1706e1141921a693a/AlphaDecider.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2458689177634208}}
{"text": "From iris.algebra Require Import dfrac_agree mono_list.\nFrom Perennial.program_proof Require Import grove_prelude.\n\n(*\n  \"Gauge-invariant\" part of the proof\n *)\nLocal Definition configR := gmapR u64 (dfrac_agreeR (listO u64O)).\nLocal Definition logR := mono_listR u8O.\nLocal Definition cn_logR := gmapR u64 logR.\nLocal Definition cn_rep_logR := gmapR (u64*u64) logR.\nClass pb_ghostG Σ :=\n  { pb_ghost_configG :> inG Σ configR;\n    pb_ghost_logG :> inG Σ logR;\n    pb_ghost_cn_logG :> inG Σ cn_logR;\n    pb_ghost_cn_rep_logG :> inG Σ cn_rep_logR }.\n\nDefinition pb_ghostΣ := #[GFunctor configR; GFunctor logR; GFunctor cn_logR; GFunctor cn_rep_logR].\n\nGlobal Instance subG_pb_ghostG {Σ} :\n  subG pb_ghostΣ Σ → pb_ghostG Σ.\nProof. solve_inG. Qed.\n\nRecord pb_names :=\n  {\n  pb_config_gn : gname;\n  pb_proposal_gn : gname;\n  pb_accepted_gn : gname;\n  pb_commit_gn : gname;\n  }.\n\nDefinition Log := list u8.\n\nDefinition log_po (lhs rhs:Log) : Prop :=\n  prefix lhs rhs.\n\nNotation \"lhs ⪯ rhs\" := (log_po lhs rhs)\n(at level 20, format \"lhs ⪯ rhs\") : stdpp_scope.\n\nSection definitions.\n\nContext `{!gooseGlobalGS Σ, !pb_ghostG Σ}.\n\nImplicit Type γ : pb_names.\n\nDefinition config_ptsto γ (cn:u64) (conf:list u64): iProp Σ :=\n  own γ.(pb_config_gn) (A:=configR) {[cn := to_dfrac_agree DfracDiscarded conf]} ∗\n  ⌜length conf > 0⌝.\nDefinition config_unset γ (cn:u64) : iProp Σ :=\n  own γ.(pb_config_gn) (A:=configR) {[cn := to_dfrac_agree (DfracOwn 1) []]}.\n\nDefinition proposal_ptsto γ (cn:u64) (l:Log): iProp Σ :=\n  own γ.(pb_proposal_gn) (A:=cn_logR) {[cn := ●ML l]}.\nDefinition proposal_ptsto_ro γ (cn:u64) (l:Log): iProp Σ :=\n  own γ.(pb_proposal_gn) (A:=cn_logR) {[cn := ●ML□ l]}.\nDefinition proposal_lb γ (cn:u64) (l:Log): iProp Σ :=\n  own γ.(pb_proposal_gn) (A:=cn_logR) {[cn := ◯ML l]}.\n\nDefinition accepted_ptsto γ (cn:u64) (r:u64) (l:Log): iProp Σ :=\n  own γ.(pb_accepted_gn) (A:=cn_rep_logR) {[(cn,r) := ●ML l]}.\nDefinition accepted_ptsto_ro γ (cn:u64) (r:u64) (l:Log): iProp Σ :=\n  own γ.(pb_accepted_gn) (A:=cn_rep_logR) {[(cn,r) := ●ML□ l]}.\nDefinition accepted_lb γ (cn:u64) (r:u64) (l:Log): iProp Σ :=\n  own γ.(pb_accepted_gn) (A:=cn_rep_logR) {[(cn,r) := ◯ML l]}.\n\nDefinition commit_ptsto γ (l:Log): iProp Σ :=\n  own γ.(pb_commit_gn) (A:=logR) (●ML l).\nDefinition commit_lb γ (l:Log): iProp Σ :=\n  own γ.(pb_commit_gn) (A:=logR) (◯ML l).\n\nGlobal Instance config_ptsto_pers γ cn conf :\n  Persistent (config_ptsto γ cn conf).\nProof. apply _. Qed.\n\nGlobal Instance proposal_lb_pers γ cn l :\n  Persistent (proposal_lb γ cn l).\nProof. apply _. Qed.\n\nGlobal Instance accepted_lb_pers γ cn r l :\n  Persistent (accepted_lb γ cn r l).\nProof. apply _. Qed.\n\nGlobal Instance committed_lb_pers γ l :\n  Persistent (commit_lb γ l).\nProof. apply _. Qed.\n\nDefinition accepted_by γ cn l : iProp Σ := (* persistent *)\n  ∃ conf, config_ptsto γ cn conf ∗\n      ∀ (r:u64), ⌜r ∈ conf⌝ → accepted_lb γ cn r l.\n\nDefinition oldConfMax γ (cn:u64) log : iProp Σ := (* persistent *)\n  □(∀ cn_old log_old ,\n   ⌜int.Z cn_old < int.Z cn⌝ →\n   accepted_by γ cn_old log_old → ⌜log_old ⪯ log⌝).\n\nDefinition commit_lb_by γ (cn:u64) l : iProp Σ := (* persistent *)\n  commit_lb γ l ∗ (∃ cn_old, ⌜int.Z cn_old <= int.Z cn⌝ ∗ accepted_by γ cn_old l).\n\n(* Want better name *)\nDefinition proposal_ptsto_fancy γ cn log : iProp Σ :=\n  proposal_ptsto γ cn log ∗\n  oldConfMax γ cn log.\n\nDefinition proposal_lb_fancy γ cn log : iProp Σ := (* persistent *)\n  proposal_lb γ cn log ∗\n  oldConfMax γ cn log.\n\n(* System-wide invariant for primary/backup replication with many replicas with\n   configuration changes *)\nDefinition pb_invariant γ : iProp Σ :=\n  ∃ cn_committed l_committed,\n  \"Hcommit\" ∷ commit_ptsto γ l_committed ∗\n  \"Haccepted\" ∷ accepted_by γ cn_committed l_committed ∗ oldConfMax γ cn_committed l_committed\n.\n\nDefinition pbN := nroot .@ \"pb_inv\".\n\nDefinition pb_inv γ : iProp Σ :=\n  inv pbN (pb_invariant γ).\n\nLemma config_ptsto_agree γ cn conf conf' :\n  config_ptsto γ cn conf -∗ config_ptsto γ cn conf' -∗ ⌜conf = conf'⌝.\nProof.\n  iIntros \"[Hconf _] [Hconf' _]\".\n  iDestruct (own_valid_2 with \"Hconf Hconf'\") as %Hval. iPureIntro. revert Hval.\n  rewrite singleton_op singleton_valid dfrac_agree_op_valid_L.\n  naive_solver.\nQed.\n\nLemma config_ptsto_nonempty γ cn conf :\n  config_ptsto γ cn conf -∗ ⌜∃ r, r ∈ conf⌝.\nProof.\n  iIntros \"[_ %Hconf]\". iPureIntro.\n  destruct conf as [|r rs]; first done.\n  exists r. constructor.\nQed.\n\nLemma config_ptsto_set γ cn conf :\n  length conf > 0 →\n  config_unset γ cn ==∗ config_ptsto γ cn conf.\nProof.\n  iIntros (?) \"Hconf\".\n  iMod (own_update with \"Hconf\") as \"$\"; last done.\n  apply singleton_update. apply cmra_update_exclusive.\n  done.\nQed.\n\nLemma accepted_update {γ cn r l} l' :\n  (l ⪯ l') → accepted_ptsto γ cn r l ==∗ accepted_ptsto γ cn r l'.\nProof.\n  iIntros (Hll'). iApply own_update.\n  apply singleton_update, mono_list_update.\n  done.\nQed.\n\nLemma accepted_witness γ cn r l :\n  accepted_ptsto γ cn r l -∗ accepted_lb γ cn r l.\nProof.\n  iApply own_mono.\n  apply singleton_mono, mono_list_included.\nQed.\n\nLemma accepted_lb_monotonic γ cn r l l':\n  l ⪯ l' → accepted_lb γ cn r l' -∗ accepted_lb γ cn r l.\nProof.\n  iIntros (Hll'). iApply own_mono.\n  apply singleton_mono, mono_list_lb_mono.\n  done.\nQed.\n\nLemma accepted_lb_le γ cn r l l' :\n  accepted_ptsto γ cn r l' -∗ accepted_lb γ cn r l -∗ ⌜l ⪯ l'⌝.\nProof.\n  iIntros \"Hl Hl'\".\n  iDestruct (own_valid_2 with \"Hl Hl'\") as %Hval.\n  iPureIntro. revert Hval.\n  rewrite singleton_op singleton_valid.\n  rewrite mono_list_both_valid_L.\n  done.\nQed.\n\nLemma accepted_lb_comparable γ cn r l l' :\n  accepted_lb γ cn r l -∗ accepted_lb γ cn r l' -∗ ⌜l ⪯ l' ∨  l' ⪯ l⌝.\nProof.\n  iIntros \"Hl Hl'\".\n  iDestruct (own_valid_2 with \"Hl Hl'\") as %Hval.\n  iPureIntro. revert Hval.\n  rewrite singleton_op singleton_valid => /mono_list_lb_op_valid_L.\n  done.\nQed.\n\nLemma proposal_lb_monotonic γ cn l l' :\n  l ⪯ l' →\n  proposal_lb γ cn l' -∗ proposal_lb γ cn l.\nProof.\n  intros Hle.\n  iApply own_mono.\n  apply singleton_mono. apply mono_list_lb_mono.\n  done.\nQed.\n\nLemma oldConfMax_monotonic γ cn l l' :\n  (l ⪯ l') → oldConfMax γ cn l -∗ oldConfMax γ cn l'.\nProof.\n  iIntros (Hll') \"#Hocm\".\n  iIntros \"!# %cn_old %log_old % Hacc\".\n  iAssert (⌜log_old⪯l⌝)%I as %?.\n  2:{ iPureIntro. by etrans. }\n  iApply \"Hocm\"; done.\nQed.\n\nLemma proposal_lb_le γ cn l l' :\n  proposal_ptsto γ cn l' -∗ proposal_lb γ cn l -∗ ⌜l ⪯ l'⌝.\nProof.\n  iIntros \"Hl Hl'\".\n  iDestruct (own_valid_2 with \"Hl Hl'\") as %Hval.\n  iPureIntro. revert Hval.\n  rewrite singleton_op singleton_valid mono_list_both_valid_L.\n  done.\nQed.\n\nLemma proposal_lb_comparable γ cn l l' :\n  proposal_lb γ cn l -∗ proposal_lb γ cn l' -∗ ⌜l ⪯ l' ∨  l' ⪯ l⌝.\nProof.\n  iIntros \"Hl Hl'\".\n  iDestruct (own_valid_2 with \"Hl Hl'\") as %Hval.\n  iPureIntro. revert Hval.\n  rewrite singleton_op singleton_valid => /mono_list_lb_op_valid_L.\n  done.\nQed.\n\nLemma commit_update {γ l} l' :\n  (l ⪯ l') → commit_ptsto γ l ==∗ commit_ptsto γ l'.\nProof.\n  iIntros (Hll'). iApply own_update.\n  apply mono_list_update.\n  done.\nQed.\n\nLemma commit_witness γ l :\n  commit_ptsto γ l -∗ commit_lb γ l.\nProof.\n  iApply own_mono.\n  apply mono_list_included.\nQed.\n\nLemma commit_lb_monotonic γ l l':\n  l ⪯ l' → commit_lb γ l' -∗ commit_lb γ l.\nProof.\n  iIntros (Hll'). iApply own_mono.\n  apply mono_list_lb_mono.\n  done.\nQed.\n\nLemma proposal_lb_fancy_comparable γ cn l l' :\n  proposal_lb_fancy γ cn l -∗ proposal_lb_fancy γ cn l' -∗ ⌜l ⪯ l' ∨  l' ⪯ l⌝.\nProof.\n  iIntros \"[Hl _] [Hl' _]\". iApply (proposal_lb_comparable with \"Hl Hl'\").\nQed.\n\nLemma accepted_by_monotonic γ cn l l' :\n  (l ⪯ l') → accepted_by γ cn l' -∗ accepted_by γ cn l.\nProof.\n  iIntros (Hll') \"[%conf [Hconf Hacc]]\".\n  iExists conf. iFrame \"Hconf\".\n  iIntros (r Hr). iApply accepted_lb_monotonic; first done.\n  by iApply \"Hacc\".\nQed.\n\n(* commit_lb_by is covariant in cn, contravariant in l *)\nLemma commit_lb_by_monotonic γ cn cn' l l' :\n  int.Z cn' <= int.Z cn → (l ⪯ l') → commit_lb_by γ cn' l' -∗ commit_lb_by γ cn l.\nProof.\n  iIntros (Hcn Hl) \"[Hcomm [%cn_old [%Hcn_old Hacc]]]\".\n  iSplitL \"Hcomm\".\n  { by iApply commit_lb_monotonic. }\n  iExists cn_old. iSplit.\n  - iPureIntro. lia.\n  - by iApply accepted_by_monotonic.\nQed.\n\nLemma oldConfMax_commit_lb_by γ cn l cn_old l_old :\n  int.Z cn_old < int.Z cn → proposal_lb_fancy γ cn l -∗ commit_lb_by γ cn_old l_old -∗ ⌜l_old ⪯ l⌝.\nProof.\n  iIntros (?) \"#Hφ [_ #Hcommit]\".\n  iDestruct \"Hφ\" as \"[_ Hφ]\".\n  iDestruct \"Hcommit\" as (? ?) \"Haccepted_by\".\n  iApply (\"Hφ\" $! cn_old0).\n  { iPureIntro. word. }\n  iFrame \"#\".\nQed.\n\nLemma do_commit γ cn l :\n  pb_inv γ -∗\n  proposal_lb_fancy γ cn l -∗\n  accepted_by γ cn l\n  ={⊤}=∗\n  commit_lb_by γ cn l.\nProof.\n  iIntros \"#Hinv #Hprop #Hacc\".\n  iInv \"Hinv\" as \">Hpb\" \"HpbClose\".\n  iDestruct \"Hpb\" as \"[%cn_comitted [%l_committed (Hcomm & #Hcomm_acc & #Holdconf)]]\".\n  rewrite /named.\n  destruct (Z_dec (int.Z cn) (int.Z cn_comitted)) as [[Hcn|Hcn]|Hcn].\n  - (* [cn] is older than [cn_comitted]. *)\n    iDestruct (\"Holdconf\" with \"[//] Hacc\") as %Hlog.\n    iDestruct (commit_witness with \"Hcomm\") as \"#Hwit\".\n    iMod (\"HpbClose\" with \"[Hcomm]\") as \"_\".\n    { iExists _, _. by eauto with iFrame. }\n    iDestruct (commit_lb_monotonic with \"Hwit\") as \"$\".\n    { done. }\n    iExists _. iFrame \"Hacc\". done.\n  - (* [cn] is greater than [cn_committed]. *)\n    iClear \"Holdconf\". (* the one from the invariant, now useless *)\n    iDestruct \"Hprop\" as \"[Hprop #Holdconf]\".\n    iDestruct (\"Holdconf\" with \"[] Hcomm_acc\") as %Hlog.\n    { iPureIntro. lia. }\n    iMod (commit_update l with \"Hcomm\") as \"Hcomm\"; first done.\n    iDestruct (commit_witness with \"Hcomm\") as \"#Hwit\".\n    iMod (\"HpbClose\" with \"[Hcomm]\") as \"_\".\n    {\n      iExists _, _. iFrame \"Hcomm\". iSplitR.\n      * iApply accepted_by_monotonic; done.\n      * done.\n    }\n    iSplitR; first done.\n    iExists _. iFrame \"Hacc\". done.\n  - (* [cn] is equal to [cn_committed]. *)\n    assert (cn = cn_comitted) by word. subst cn. clear Hcn.\n    iPoseProof \"Hacc\" as (conf) \"[#Hconf Hacc_lb]\".\n    iPoseProof \"Hcomm_acc\" as (comm_conf) \"[#Hcomm_conf Hcomm_acc_lb]\".\n    iDestruct (config_ptsto_agree with \"Hconf Hcomm_conf\") as %<-.\n    iClear \"Hcomm_conf\".\n    iDestruct (config_ptsto_nonempty with \"Hconf\") as %[r Hr].\n    iSpecialize (\"Hacc_lb\" with \"[//]\").\n    iSpecialize (\"Hcomm_acc_lb\" with \"[//]\").\n    iDestruct (accepted_lb_comparable with \"Hacc_lb Hcomm_acc_lb\") as \"[%Hl|%Hl]\".\n    + (* [l] is already committed. *)\n      iDestruct (commit_witness with \"Hcomm\") as \"#Hwit\".\n      iMod (\"HpbClose\" with \"[Hcomm]\") as \"_\".\n      { iExists _, _. by eauto with iFrame. }\n      iSplitR; first by iApply commit_lb_monotonic.\n      iExists _. iFrame \"Hacc\". done.\n    + (* we can commit [l] now. *)\n      iMod (commit_update l with \"Hcomm\") as \"Hcomm\"; first done.\n      iDestruct (commit_witness with \"Hcomm\") as \"#Hwit\".\n      iMod (\"HpbClose\" with \"[Hcomm]\") as \"_\".\n      {\n        iExists _, _. iFrame \"Hcomm\". iSplitR.\n        -- iApply accepted_by_monotonic; done.\n        -- iApply oldConfMax_monotonic; done.\n      }\n      iSplitR; first done.\n      iExists _. iFrame \"Hacc\". done.\nQed.\n\nEnd definitions.\n\nTypeclasses Opaque config_ptsto config_unset proposal_ptsto proposal_ptsto_ro proposal_lb accepted_ptsto accepted_ptsto_ro accepted_lb commit_ptsto commit_lb.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/pb/ghost_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2458689177634208}}
{"text": "Require Import Coq.Classes.Morphisms.\nRequire Import Crypto.Reflection.Syntax.\nRequire Import Crypto.Util.Tactics.RewriteHyp.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Notations.\n\nSection homogenous_type.\n  Context {base_type_code : Type}\n          {op : flat_type base_type_code -> flat_type base_type_code -> Type}\n          {var : base_type_code -> Type}.\n\n  Local Notation flat_type := (flat_type base_type_code).\n  Local Notation type := (type base_type_code).\n  Local Notation interp_flat_type := (@interp_flat_type base_type_code).\n  Local Notation exprf := (@exprf base_type_code op var).\n  Local Notation expr := (@expr base_type_code op var).\n\n  (** Sometimes, we want to deal with partially-interpreted\n      expressions, things like [prod (exprf A) (exprf B)] rather than\n      [exprf (Prod A B)], or like [prod (var A) (var B)] when we start\n      with the type [Prod A B].  These convenience functions let us\n      recurse on the type in only one place, and replace one kind of\n      pairing operator (be it [pair] or [Pair] or anything else) with\n      another kind, and simultaneously mapping a function over the\n      base values (e.g., [Var] (for turning [var] into [exprf]) or\n      [Const] (for turning [interp_base_type] into [exprf])). *)\n  Fixpoint smart_interp_flat_map {f g}\n           (h : forall x, f x -> g (Tbase x))\n           (tt : g Unit)\n           (pair : forall A B, g A -> g B -> g (Prod A B))\n           {t}\n    : interp_flat_type f t -> g t\n    := match t return interp_flat_type f t -> g t with\n       | Syntax.Tbase _ => h _\n       | Unit => fun _ => tt\n       | Prod A B => fun v : interp_flat_type _ A * interp_flat_type _ B\n                     => pair _ _\n                             (@smart_interp_flat_map f g h tt pair A (fst v))\n                             (@smart_interp_flat_map f g h tt pair B (snd v))\n       end.\n  Fixpoint smart_interp_flat_map2 {f1 f2 g}\n           (h : forall x, f1 x -> f2 x -> g (Tbase x))\n           (tt : g Unit)\n           (pair : forall A B, g A -> g B -> g (Prod A B))\n           {t}\n    : interp_flat_type f1 t -> interp_flat_type f2 t -> g t\n    := match t return interp_flat_type f1 t -> interp_flat_type f2 t -> g t with\n       | Syntax.Tbase _ => h _\n       | Unit => fun _ _ => tt\n       | Prod A B => fun (v1 : interp_flat_type _ A * interp_flat_type _ B)\n                         (v2 : interp_flat_type _ A * interp_flat_type _ B)\n                     => pair _ _\n                             (@smart_interp_flat_map2 f1 f2 g h tt pair A (fst v1) (fst v2))\n                             (@smart_interp_flat_map2 f1 f2 g h tt pair B (snd v1) (snd v2))\n       end.\n  Fixpoint smart_interp_flat_map3 {f1 f2 f3 g}\n           (h : forall x, f1 x -> f2 x -> f3 x -> g (Tbase x))\n           (tt : g Unit)\n           (pair : forall A B, g A -> g B -> g (Prod A B))\n           {t}\n    : interp_flat_type f1 t -> interp_flat_type f2 t -> interp_flat_type f3 t -> g t\n    := match t return interp_flat_type f1 t -> interp_flat_type f2 t -> interp_flat_type f3 t -> g t with\n       | Syntax.Tbase _ => h _\n       | Unit => fun _ _ _ => tt\n       | Prod A B => fun (v1 : interp_flat_type _ A * interp_flat_type _ B)\n                         (v2 : interp_flat_type _ A * interp_flat_type _ B)\n                         (v3 : interp_flat_type _ A * interp_flat_type _ B)\n                     => pair _ _\n                             (@smart_interp_flat_map3 f1 f2 f3 g h tt pair A (fst v1) (fst v2) (fst v3))\n                             (@smart_interp_flat_map3 f1 f2 f3 g h tt pair B (snd v1) (snd v2) (snd v3))\n       end.\n  Definition smart_interp_map_hetero {f g g'}\n             (h : forall x, f x -> g (Tbase x))\n             (tt : g Unit)\n             (pair : forall A B, g A -> g B -> g (Prod A B))\n             (abs : forall A B, (g A -> g B) -> g' (Arrow A B))\n             {t}\n    : interp_type_gen_hetero g (interp_flat_type f) t -> g' t\n    := match t return interp_type_gen_hetero g (interp_flat_type f) t -> g' t with\n       | Arrow A B => fun v => abs _ _\n                                   (fun x => @smart_interp_flat_map f g h tt pair _ (v x))\n       end.\n  Fixpoint SmartValf {T} (val : forall t : base_type_code, T t) t : interp_flat_type T t\n    := match t return interp_flat_type T t with\n       | Syntax.Tbase _ => val _\n       | Unit => tt\n       | Prod A B => (@SmartValf T val A, @SmartValf T val B)\n       end.\n\n  (** [SmartVar] is like [Var], except that it inserts\n      pair-projections and [Pair] as necessary to handle [flat_type],\n      and not just [base_type_code] *)\n  Local Notation exprfb := (fun t => exprf (Tbase t)).\n  Definition SmartPairf {t} : interp_flat_type exprfb t -> exprf t\n    := @smart_interp_flat_map exprfb exprf (fun t x => x) TT (fun A B x y => Pair x y) t.\n  Lemma SmartPairf_Pair {A B} (e1 : interp_flat_type _ A) (e2 : interp_flat_type _ B)\n    : SmartPairf (t:=Prod A B) (e1, e2)%core = Pair (SmartPairf e1) (SmartPairf e2).\n  Proof. reflexivity. Qed.\n  Definition SmartVarf {t} : interp_flat_type var t -> exprf t\n    := @smart_interp_flat_map var exprf (fun t => Var) TT (fun A B x y => Pair x y) t.\n  Definition SmartVarf_Pair {A B v}\n    : @SmartVarf (Prod A B) v = Pair (SmartVarf (fst v)) (SmartVarf (snd v))\n    := eq_refl.\n  Definition SmartVarfMap {var var'} (f : forall t, var t -> var' t) {t}\n    : interp_flat_type var t -> interp_flat_type var' t\n    := @smart_interp_flat_map var (interp_flat_type var') f tt (fun A B x y => pair x y) t.\n  Lemma SmartVarfMap_compose {var' var'' var''' t} f g x\n    : @SmartVarfMap var'' var''' g t (@SmartVarfMap var' var'' f t x)\n      = @SmartVarfMap _ _ (fun t v => g t (f t v)) t x.\n  Proof.\n    unfold SmartVarfMap; clear; induction t; simpl; destruct_head_hnf unit; destruct_head_hnf prod;\n      rewrite_hyp ?*; congruence.\n  Qed.\n  Lemma SmartVarfMap_id {var' t} x : @SmartVarfMap var' var' (fun _ x => x) t x = x.\n  Proof.\n    unfold SmartVarfMap; clear; induction t; simpl; destruct_head_hnf unit; destruct_head_hnf prod;\n      rewrite_hyp ?*; congruence.\n  Qed.\n  Global Instance smart_interp_flat_map_Proper {f g}\n    : Proper ((forall_relation (fun t => pointwise_relation _ eq))\n                ==> eq\n                ==> (forall_relation (fun A => forall_relation (fun B => pointwise_relation _ (pointwise_relation _ eq))))\n                ==> forall_relation (fun t => eq ==> eq))\n             (@smart_interp_flat_map f g).\n  Proof.\n    unfold forall_relation, pointwise_relation, respectful.\n    intros F G HFG x y ? Q R HQR t a b ?; subst y b.\n    induction t; simpl in *; auto.\n    rewrite_hyp !*; reflexivity.\n  Qed.\n  Global Instance SmartVarfMap_Proper {var' var''}\n    : Proper (forall_relation (fun t => pointwise_relation _ eq) ==> forall_relation (fun t => eq ==> eq))\n             (@SmartVarfMap var' var'').\n  Proof.\n    repeat intro; eapply smart_interp_flat_map_Proper; trivial; repeat intro; reflexivity.\n  Qed.\n  Definition SmartVarfMap2 {var var' var''} (f : forall t, var t -> var' t -> var'' t) {t}\n    : interp_flat_type var t -> interp_flat_type var' t -> interp_flat_type var'' t\n    := @smart_interp_flat_map2 var var' (interp_flat_type var'') f tt (fun A B x y => pair x y) t.\n  Lemma SmartVarfMap2_fst_arg {var' var''} {t}\n        (x : interp_flat_type var' t)\n        (y : interp_flat_type var'' t)\n    : SmartVarfMap2 (fun _ a b => a) x y = x.\n  Proof.\n    unfold SmartVarfMap2; clear; induction t; simpl; destruct_head_hnf unit; destruct_head_hnf prod;\n      rewrite_hyp ?*; congruence.\n  Qed.\n  Lemma SmartVarfMap2_snd_arg {var' var''} {t}\n        (x : interp_flat_type var' t)\n        (y : interp_flat_type var'' t)\n    : SmartVarfMap2 (fun _ a b => b) x y = y.\n  Proof.\n    unfold SmartVarfMap2; clear; induction t; simpl; destruct_head_hnf unit; destruct_head_hnf prod;\n      rewrite_hyp ?*; congruence.\n  Qed.\n  Definition SmartVarfMap3 {var var' var'' var'''} (f : forall t, var t -> var' t -> var'' t -> var''' t) {t}\n    : interp_flat_type var t -> interp_flat_type var' t -> interp_flat_type var'' t -> interp_flat_type var''' t\n    := @smart_interp_flat_map3 var var' var'' (interp_flat_type var''') f tt (fun A B x y => pair x y) t.\n  Definition SmartVarfTypeMap {var} (f : forall t, var t -> Type) {t}\n    : interp_flat_type var t -> Type\n    := @smart_interp_flat_map var (fun _ => Type) f unit (fun _ _ P Q => P * Q)%type t.\n  Definition SmartVarfPropMap {var} (f : forall t, var t -> Prop) {t}\n    : interp_flat_type var t -> Prop\n    := @smart_interp_flat_map var (fun _ => Prop) f True (fun _ _ P Q => P /\\ Q)%type t.\n  Definition SmartVarfTypeMap2 {var var'} (f : forall t, var t -> var' t -> Type) {t}\n    : interp_flat_type var t -> interp_flat_type var' t -> Type\n    := @smart_interp_flat_map2 var var' (fun _ => Type) f unit (fun _ _ P Q => P * Q)%type t.\n  Definition SmartVarfPropMap2 {var var'} (f : forall t, var t -> var' t -> Prop) {t}\n    : interp_flat_type var t -> interp_flat_type var' t -> Prop\n    := @smart_interp_flat_map2 var var' (fun _ => Prop) f True (fun _ _ P Q => P /\\ Q)%type t.\n  Definition SmartFlatTypeMap {var'} (f : forall t, var' t -> base_type_code) {t}\n    : interp_flat_type var' t -> flat_type\n    := @smart_interp_flat_map var' (fun _ => flat_type) (fun t v => Tbase (f t v)) Unit (fun _ _ => Prod) t.\n  Definition SmartFlatTypeUnMap (t : flat_type)\n    : interp_flat_type (fun _ => base_type_code) t\n    := SmartValf (fun t => t) t.\n  Fixpoint SmartFlatTypeMapInterp {var' var''} (f : forall t, var' t -> base_type_code)\n           (fv : forall t v, var'' (f t v)) t {struct t}\n    : forall v, interp_flat_type var'' (SmartFlatTypeMap f (t:=t) v)\n    := match t return forall v, interp_flat_type var'' (SmartFlatTypeMap f (t:=t) v) with\n       | Syntax.Tbase x => fv _\n       | Unit => fun v => v\n       | Prod A B => fun xy : interp_flat_type _ A * interp_flat_type _ B\n                     => (@SmartFlatTypeMapInterp _ _ f fv A (fst xy),\n                         @SmartFlatTypeMapInterp _ _ f fv B (snd xy))\n       end.\n  Fixpoint SmartFlatTypeMapInterp2 {var' var'' var'''} (f : forall t, var' t -> base_type_code)\n           (fv : forall t v, var'' t -> var''' (f t v)) t {struct t}\n    : forall v, interp_flat_type var'' t -> interp_flat_type var''' (SmartFlatTypeMap f (t:=t) v)\n    := match t return forall v, interp_flat_type var'' t -> interp_flat_type var''' (SmartFlatTypeMap f (t:=t) v) with\n       | Syntax.Tbase x => fv _\n       | Unit => fun v _ => v\n       | Prod A B => fun (xy : interp_flat_type _ A * interp_flat_type _ B)\n                         (x'y' : interp_flat_type _ A * interp_flat_type _ B)\n                     => (@SmartFlatTypeMapInterp2 _ _ _ f fv A (fst xy) (fst x'y'),\n                         @SmartFlatTypeMapInterp2 _ _ _ f fv B (snd xy) (snd x'y'))\n       end.\n  Fixpoint SmartFlatTypeMapUnInterp var' var'' var''' (f : forall t, var' t -> base_type_code)\n           (fv : forall t (v : var' t), var'' (f t v) -> var''' t)\n           {t} {struct t}\n    : forall v, interp_flat_type var'' (SmartFlatTypeMap f (t:=t) v)\n                -> interp_flat_type var''' t\n    := match t return forall v, interp_flat_type var'' (SmartFlatTypeMap f (t:=t) v)\n                                -> interp_flat_type var''' t with\n       | Syntax.Tbase x => fv _\n       | Unit => fun _ v => v\n       | Prod A B => fun (v : interp_flat_type _ A * interp_flat_type _ B)\n                         (xy : interp_flat_type _ (SmartFlatTypeMap _ (fst v)) * interp_flat_type _ (SmartFlatTypeMap _ (snd v)))\n                     => (@SmartFlatTypeMapUnInterp _ _ _ f fv A _ (fst xy),\n                         @SmartFlatTypeMapUnInterp _ _ _ f fv B _ (snd xy))\n       end.\n  Definition SmartVarMap {var' var''} (f : forall t, var' t -> var'' t) (f' : forall t, var'' t -> var' t) {t}\n    : interp_type_gen (interp_flat_type var') t -> interp_type_gen (interp_flat_type var'') t\n    := match t return interp_type_gen (interp_flat_type var') t -> interp_type_gen (interp_flat_type var'') t with\n       | Arrow src dst => fun F x => SmartVarfMap f (F (SmartVarfMap f' x))\n       end.\n  Lemma SmartVarMap_id {var' t} x v : @SmartVarMap var' var' (fun _ x => x) (fun _ x => x) t x v = x v.\n  Proof. destruct t; simpl; rewrite !SmartVarfMap_id; reflexivity. Qed.\n  Definition SmartVarVarf {t} : interp_flat_type var t -> interp_flat_type exprfb t\n    := SmartVarfMap (fun t => Var).\nEnd homogenous_type.\n\nGlobal Arguments SmartVarf {_ _ _ _} _.\nGlobal Arguments SmartPairf {_ _ _ t} _.\nGlobal Arguments SmartValf {_} T _ t.\nGlobal Arguments SmartVarVarf {_ _ _ _} _.\nGlobal Arguments SmartVarfMap {_ _ _} _ {!_} _ / .\nGlobal Arguments SmartVarfMap2 {_ _ _ _} _ {!t} _ _ / .\nGlobal Arguments SmartVarfMap3 {_ _ _ _ _} _ {!t} _ _ _ / .\nGlobal Arguments SmartVarfTypeMap {_ _} _ {_} _.\nGlobal Arguments SmartVarfPropMap {_ _} _ {_} _.\nGlobal Arguments SmartVarfTypeMap2 {_ _ _} _ {t} _ _.\nGlobal Arguments SmartVarfPropMap2 {_ _ _} _ {t} _ _.\nGlobal Arguments SmartFlatTypeMap {_ _} _ {_} _.\nGlobal Arguments SmartFlatTypeUnMap {_} _.\nGlobal Arguments SmartFlatTypeMapInterp {_ _ _ _} _ {_} _.\nGlobal Arguments SmartFlatTypeMapInterp2 {_ _ _ _ f} fv {t} _ _.\nGlobal Arguments SmartFlatTypeMapUnInterp {_ _ _ _ _} fv {_ _} _.\nGlobal Arguments SmartVarMap {_ _ _} _ _ {!_} _ / _.\n\nSection hetero_type.\n  Fixpoint flatten_flat_type {base_type_code} (t : flat_type (flat_type base_type_code)) : flat_type base_type_code\n    := match t with\n       | Tbase T => T\n       | Unit => Unit\n       | Prod A B => Prod (@flatten_flat_type _ A) (@flatten_flat_type _ B)\n       end.\n\n  Section smart_flat_type_map2.\n    Context {base_type_code1 base_type_code2 : Type}.\n\n    Definition SmartFlatTypeMap2 {var' : base_type_code1 -> Type} (f : forall t, var' t -> flat_type base_type_code2) {t}\n      : interp_flat_type var' t -> flat_type base_type_code2\n      := @smart_interp_flat_map base_type_code1 var' (fun _ => flat_type base_type_code2) f Unit (fun _ _ => Prod) t.\n    Fixpoint SmartFlatTypeMap2Interp {var' var''} (f : forall t, var' t -> flat_type base_type_code2)\n             (fv : forall t v, interp_flat_type var'' (f t v)) t {struct t}\n      : forall v, interp_flat_type var'' (SmartFlatTypeMap2 f (t:=t) v)\n      := match t return forall v, interp_flat_type var'' (SmartFlatTypeMap2 f (t:=t) v) with\n         | Tbase x => fv _\n         | Unit => fun v => v\n         | Prod A B => fun xy : interp_flat_type _ A * interp_flat_type _ B\n                       => (@SmartFlatTypeMap2Interp _ _ f fv A (fst xy),\n                           @SmartFlatTypeMap2Interp _ _ f fv B (snd xy))\n         end.\n    Fixpoint SmartFlatTypeMapUnInterp2 var' var'' var''' (f : forall t, var' t -> flat_type base_type_code2)\n             (fv : forall t (v : var' t), interp_flat_type var'' (f t v) -> var''' t)\n             {t} {struct t}\n      : forall v, interp_flat_type var'' (SmartFlatTypeMap2 f (t:=t) v)\n                  -> interp_flat_type var''' t\n      := match t return forall v, interp_flat_type var'' (SmartFlatTypeMap2 f (t:=t) v)\n                                  -> interp_flat_type var''' t with\n         | Tbase x => fv _\n         | Unit => fun _ v => v\n         | Prod A B => fun (v : interp_flat_type _ A * interp_flat_type _ B)\n                           (xy : interp_flat_type _ (SmartFlatTypeMap2 _ (fst v)) * interp_flat_type _ (SmartFlatTypeMap2 _ (snd v)))\n                       => (@SmartFlatTypeMapUnInterp2 _ _ _ f fv A _ (fst xy),\n                           @SmartFlatTypeMapUnInterp2 _ _ _ f fv B _ (snd xy))\n         end.\n    Fixpoint SmartFlatTypeMap2Interp2 {var' var'' var'''} (f : forall t, var' t -> flat_type base_type_code2)\n             (fv : forall t v, var'' t -> interp_flat_type var''' (f t v)) t {struct t}\n      : forall v, interp_flat_type var'' t -> interp_flat_type var''' (SmartFlatTypeMap2 f (t:=t) v)\n      := match t return forall v, interp_flat_type var'' t -> interp_flat_type var''' (SmartFlatTypeMap2 f (t:=t) v) with\n         | Tbase x => fv _\n         | Unit => fun v _ => v\n         | Prod A B => fun (xy : interp_flat_type _ A * interp_flat_type _ B)\n                           (x'y' : interp_flat_type _ A * interp_flat_type _ B)\n                       => (@SmartFlatTypeMap2Interp2 _ _ _ f fv A (fst xy) (fst x'y'),\n                           @SmartFlatTypeMap2Interp2 _ _ _ f fv B (snd xy) (snd x'y'))\n         end.\n\n    Lemma SmartFlatTypeMapUnInterp2_SmartFlatTypeMap2Interp2\n          var' var'' var'''\n          (f : forall t, var' t -> flat_type base_type_code2)\n          (fv : forall t (v : var' t), interp_flat_type var'' (f t v) -> var''' t)\n          (gv : forall t v, var''' t -> interp_flat_type var'' (f t v))\n          {t} v\n          (e : interp_flat_type var''' t)\n      : @SmartFlatTypeMapUnInterp2\n          _ _ _ f fv t v\n          (@SmartFlatTypeMap2Interp2\n             _ _ _ f gv t v e)\n        = SmartVarfMap2 (fun t v e => fv t v (gv t v e)) v e.\n    Proof.\n      induction t; simpl in *; destruct_head' unit;\n        rewrite_hyp ?*; reflexivity.\n    Qed.\n  End smart_flat_type_map2.\nEnd hetero_type.\n\nGlobal Arguments SmartFlatTypeMap2 {_ _ _} _ {!_} _ / .\nGlobal Arguments SmartFlatTypeMap2Interp {_ _ _ _ _} fv {_} _.\nGlobal Arguments SmartFlatTypeMap2Interp2 {_ _ _ _ _ _} fv {t} v _.\nGlobal Arguments SmartFlatTypeMapUnInterp2 {_ _ _ _ _ _} fv {_ _} _.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_crypto_defined/src/Reflection/SmartMap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.24586891776342076}}
{"text": "Require Import Lia IndefiniteDescription Arith.\nFrom hahn Require Import Hahn.\nRequire Import AuxRel.\nRequire Import AuxProp.\nRequire Import Labels.\nRequire Import Events.\nRequire Import Execution.\nRequire Import View.\nRequire Import SCOHop.\nRequire Import CompactedTrace.\nRequire Import PropExtensionality.\nRequire Import TraceWf.\n\nSet Implicit Arguments.\n\n#[local]\nHint Resolve is_init_InitEvent : core.\n\nSection DECL_to_OP.\n  Variable G : execution.\n  Hypothesis WF: Wf G.\n  Variable nu : nat -> Event.\n  Hypothesis ENUM : enumerates nu (acts G \\₁ is_init).\n  Hypothesis IMPL :\n    forall i (LTi: lt_size i (acts G \\₁ is_init))\n           j (LTj: lt_size j (acts G \\₁ is_init))\n           (REL: hb G (nu i) (nu j)), i < j.\n  Hypothesis COMPL : rf_complete G.\n  Hypothesis CONS : scoh_consistent G.\n  Hypothesis FAIR : mem_fair G.\n  \n  Hypothesis THRB :\n    set_finite (fun t => exists x, acts G x /\\ t = tid x).\n\n  Lemma BOUND : bounded_threads G.\n  Proof.\n    set (AA:=THRB). apply  set_finite_nat_bounded in AA. desf.\n    exists bound. ins. apply AA; eauto.\n  Qed.\n\n  (* In the paper, it is the function mapping eᵢ to i. *)\n  Definition nu_inv (x : Event) : nat :=\n    match excluded_middle_informative ((acts G \\₁ is_init) x) with\n    | left PF =>\n      proj1_sig (constructive_indefinite_description\n                   _ (proj2 (proj2 (proj1 (enumeratesE _ _) ENUM)) x PF))\n    | right _ => 0\n    end.\n\n  Lemma nu_nu_inv x (ACTS: acts G x) (NI: ~ is_init x) : nu (nu_inv x) = x.\n  Proof.\n    unfold nu_inv, proj1_sig; unfolder; desf; try clear Heq;\n      clarify_not; desf.\n  Qed.\n\n  Lemma nu_inv_nu n (LT: lt_size n (acts G \\₁ is_init)) : nu_inv (nu n) = n.\n  Proof.\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    unfold nu_inv, proj1_sig; desf; try clear Heq;\n      clarify_not; desf; eauto.\n    all: apply RNG in LT; red in LT; desf.\n  Qed.\n\n  Lemma nu_inv_lt_size x (EE : (acts G \\₁ is_init) x) :\n    lt_size (nu_inv x) (acts G \\₁ is_init).\n  Proof.\n    unfold nu_inv. desf.\n    unfold proj1_sig. do 2 desf.\n  Qed.\n\n  Definition ev_ts_w n :=\n    length (filterP (fun x => (co G) x n)\n                    (undup (proj1_sig (constructive_indefinite_description\n                                         _ (proj1 FAIR n))))).\n\n  (* In the paper, it is called _tmap_. *)\n  Definition ev_ts n :=\n    ifP is_w n then ev_ts_w n\n    else match excluded_middle_informative\n                 ((acts G ∩₁ (fun a => is_r a)) n) with\n         | left PF =>\n           ev_ts_w (proj1_sig (constructive_indefinite_description\n                                 _ (COMPL PF)))\n         | right _ => 0\n         end.\n\n  Lemma ev_ts_w_init x : ev_ts_w (InitEvent x) = 0.\n  Proof.\n    unfold ev_ts_w, proj1_sig; desf; clear Heq.\n    apply length_zero_iff_nil, filterP_eq_nil; ins.\n    unfolder in COND; desf; eauto using co_init_r, rf_init_r.\n  Qed.\n\n  Lemma ev_ts_init x : ev_ts (InitEvent x) = 0.\n  Proof.\n    unfold ev_ts, ev_ts_w, proj1_sig; desf; clear Heq.\n    apply length_zero_iff_nil, filterP_eq_nil; ins.\n    unfolder in COND; desf; eauto using co_init_r, rf_init_r.\n  Qed.\n\n  Lemma rf_tsE x y :\n    rf G x y -> ~ is_w y -> ev_ts x = ev_ts y.\n  Proof.\n    intros RF NWy.\n    apply wf_rfD in RF; unfolder in RF; desf.\n    apply wf_rfE in RF0; unfolder in RF0; desf.\n    unfold ev_ts; desf; unfold proj1_sig; desf;\n      unfolder in *; clarify_not; desf.\n    f_equal; eapply (wf_rff WF); red; eauto.\n  Qed.\n\n  Lemma co_tsE x y :\n    co G x y ->\n    ev_ts x < ev_ts y.\n  Proof.\n    intro CO; apply wf_coD in CO; unfolder in CO; desf.\n    unfold ev_ts; desf; unfold ev_ts_w.\n    do 2 destruct (constructive_indefinite_description); ins.\n    assert (H := CO0).\n    eapply i1, in_undup_iff, In_NoDup_Permutation in H; desf.\n    rewrite H; ins; desf; ins.\n    rewrite Nat.lt_succ_r; ins.\n    eapply NoDup_incl_length; auto with hahn.\n    red; ins; in_simp.\n    assert (CO': co G a y) by eauto using (co_trans WF).\n    specialize (i1 _ CO'); rewrite <- in_undup_iff, H in i1; ins; desf.\n    edestruct (co_irr WF); eauto.\n  Qed.\n\n  Lemma rf_tsE_gen x y :\n    rf G x y -> ev_ts x <= ev_ts y.\n  Proof.\n    ins. destruct (classic (is_w y)) as [WY|NWY].\n    2: { eapply rf_tsE in NWY; eauto. lia. }\n    enough (ev_ts x < ev_ts y); [lia|].\n    eapply co_tsE. apply rf_w_in_co; auto.\n    basic_solver.\n  Qed.\n\n  Lemma co_tsE_alt :\n    co G ≡\n       fun x y => \n         ⟪ EX : acts G x ⟫ /\\\n         ⟪ WX : is_w x ⟫ /\\\n         ⟪ EY : acts G y ⟫ /\\\n         ⟪ WY : is_w y ⟫ /\\\n         ⟪ SL : loc x = loc y ⟫ /\\\n         ⟪ LTTS : ev_ts x < ev_ts y ⟫.\n  Proof.\n    unfolder.\n    split; intros x y HH; desf.\n    { apply (wf_coE WF) in HH. unfolder in HH. desf.\n      apply (wf_coD WF) in HH0. unfolder in HH0. desf.\n      set (AA:=HH2). apply (wf_col WF) in AA.\n      splits; auto. by apply co_tsE. }\n    assert (x <> y) as NEQ.\n    { intros UU. desf. lia. }\n    eapply wf_co_total in NEQ; eauto.\n    2,3: eby unfolder; splits.\n    desf. exfalso. apply co_tsE in NEQ. lia.\n  Qed.\n\n  Lemma fr_tsE x y :\n    fr G x y -> ev_ts x < ev_ts y.\n  Proof.\n    destruct (classic (is_w x)) as [WX|NWX]; intros FR.\n    { apply co_tsE.\n      apply w_fr_in_co; auto.\n      { apply scoh_rmw_atomicity; auto. }\n      basic_solver. }\n    apply wf_frD in FR; unfolder in FR; desf.\n    red in FR0. unfolder in FR0. desf.\n    rewrite <- (rf_tsE _ _ FR0); auto. by apply co_tsE.\n  Qed.\n\n  Lemma fr_tsE_alt :\n    fr G ≡\n       fun x y => \n         ⟪ EX : acts G x ⟫ /\\\n         ⟪ RX : is_r x ⟫ /\\\n         ⟪ EY : acts G y ⟫ /\\\n         ⟪ WY : is_w y ⟫ /\\\n         ⟪ SL : loc x = loc y ⟫ /\\\n         ⟪ LTTS : ev_ts x < ev_ts y ⟫.\n  Proof.\n    unfolder.\n    split; intros x y HH; desf.\n    { apply (wf_frE WF) in HH. unfolder in HH. desf.\n      apply (wf_frD WF) in HH0. unfolder in HH0. desf.\n      set (AA:=HH2). apply (wf_frl WF) in AA.\n      splits; auto. by apply fr_tsE. }\n    set (AA:=RX). edestruct COMPL with (x:=x) as [w RF].\n    { basic_solver. }\n    red. split.\n    2: { unfolder. intros HH. desf. lia. }\n    exists w. split; auto.\n    apply (wf_rfD WF) in RF. unfolder in RF. desf.\n    apply (wf_rfE WF) in RF0. unfolder in RF0. desf.\n    set (BB:=RF2). apply (wf_rfl WF) in BB.\n    apply co_tsE_alt. splits; auto.\n    { by rewrite BB. }\n    apply rf_tsE_gen in RF2. lia.\n  Qed.\n\n  (* Lemma hb_ww_tsE x y *)\n  (*       (HB : hb G x y) *)\n  (*       (WX : is_w x) (WY : is_w y) *)\n  (*       (LL : loc x = loc y) : *)\n  (*   ev_ts x < ev_ts y. *)\n  (* Proof. *)\n  (*   apply (wf_hbE WF) in HB. unfolder in HB. desf. *)\n  (*   assert (x <> y) as NEQ. *)\n  (*   { intros HH; subst. eapply hb_irr; eauto. } *)\n  (*   edestruct wf_co_total as [|AA]; eauto. *)\n  (*   1,2: eby unfolder; splits. *)\n  (*   { by apply co_tsE. } *)\n  (*   exfalso. *)\n  (*   cdes CONS. eapply CONS0. generalize HB0 AA. basic_solver 10. *)\n  (* Qed. *)\n\n  (* Lemma hb_tsE x y *)\n  (*       (HB : hb G x y) *)\n  (*       (WX : is_w x) *)\n  (*       (LL : loc x = loc y) : *)\n  (*   ev_ts x <= ev_ts y. *)\n  (* Proof. *)\n  (*   apply (wf_hbE WF) in HB. unfolder in HB. desf. *)\n  (*   assert (exists w, ((hb G) ⨾ ((rf G)⁻¹)^?) x w /\\ is_w w /\\ acts G w /\\ *)\n  (*                     ev_ts y = ev_ts w /\\ loc w = loc y) *)\n  (*     as [w [AA [BB [CC [DD FF]]]]]. *)\n  (*   { destruct (classic (is_w y)) as [WY|NWY]. *)\n  (*     { exists y. split; auto. generalize HB0. basic_solver. } *)\n  (*     destruct (r_or_w y) as [RY|WY]. *)\n  (*     2: by intuition. *)\n  (*     assert (exists w, rf G w y) as [w RF]. *)\n  (*     { apply COMPL. by split. } *)\n  (*     exists w. *)\n  (*     apply (wf_rfE WF) in RF. unfolder in RF. desf. *)\n  (*     apply (wf_rfD WF) in RF0. unfolder in RF0. desf. *)\n  (*     splits; auto. *)\n  (*     { generalize RF2 HB0. basic_solver. } *)\n  (*     { symmetry. by apply rf_tsE. } *)\n  (*       by apply (wf_rfl WF). } *)\n  (*   rewrite DD. *)\n  (*   destruct (classic (x = w)) as [|NEQ]; subst; auto. *)\n  (*   apply Nat.lt_le_incl. *)\n  (*   edestruct wf_co_total as [|EE]; eauto. *)\n  (*   1,2: eby unfolder; splits. *)\n  (*   { by apply co_tsE. } *)\n  (*   exfalso. *)\n  (*   cdes CONS. eapply CONS0 with (x:=x). *)\n  (*   unfolder in AA. desf. *)\n  (*   { generalize AA EE. basic_solver 10. } *)\n  (*   enough (fr G z x) as GG. *)\n  (*   { generalize AA GG. basic_solver 10. } *)\n  (*   red. split. *)\n  (*   { generalize AA0 EE. basic_solver. } *)\n  (*   unfolder. intros HH; desf. *)\n  (*   eapply hb_irr; eauto. *)\n  (* Qed. *)\n\n  Lemma co_imm_tsE x y :\n    immediate (co G) x y -> S (ev_ts x) = ev_ts y.\n  Proof.\n    intros [CO IMM]; apply wf_coD in CO; unfolder in CO; desf.\n    unfold ev_ts; desf; unfold ev_ts_w.\n    do 2 destruct (constructive_indefinite_description); ins.\n    assert (H := CO0).\n    eapply i1, in_undup_iff, In_NoDup_Permutation in H; desf.\n    rewrite H; ins; desf; ins.\n    f_equal.\n    apply Permutation_length, NoDup_Permutation; eauto with hahn.\n    eapply nodup_filterP, nodup_consD, Permutation_NoDup; eauto.\n    intro z; in_simp; split; ins; desc.\n    - assert (X: co G z y) by eauto using (co_trans WF).\n      split; ins; desf; eapply i1, in_undup_iff in X.\n      rewrite H in X; ins; desf; eauto.\n      exfalso; eauto using (co_irr WF).\n    - destruct (classic (z = x)) as [|NEQ]; desf.\n      hahn_rewrite (wf_coE WF) in CO0; unfolder in CO0; desf.\n      hahn_rewrite (wf_coD WF) in CO2; unfolder in CO2; desc.\n      hahn_rewrite (wf_coE WF) in H2; unfolder in H2; desf.\n      hahn_rewrite (wf_coD WF) in H3; unfolder in H3; desc.\n      eapply (wf_co_total WF) in NEQ; unfolder; ins.\n      desf; solve [eauto | exfalso; eauto].\n      eapply (wf_col WF) in CO4.\n      eapply (wf_col WF) in H5; unfold same_loc in *; splits; ins;\n        congruence.\n  Qed.\n\n  Lemma rf_rmw_tsE x y (RF : rf G x y) (Wy : is_w y) :\n    S (ev_ts x) = ev_ts y.\n  Proof.\n    ins; apply co_imm_tsE.\n    assert (L := wf_rfl WF _ _ RF); unfold same_loc, loc in *; ins; clarify.\n    assert (V := wf_rfv WF _ _ RF); unfold valw, valr in *; ins; clarify.\n    apply (wf_rfE WF) in RF; unfolder in RF; desf.\n    apply (wf_rfD WF) in RF0; unfolder in RF0; desf.\n    cdes CONS.\n    destruct (classic (x = y)) as [|NEQ]; desf.\n    { exfalso. eapply CONS0 with (x:=y).\n      apply ct_step.  generalize RF2. basic_solver. }\n    eapply (wf_co_total WF) in NEQ; unfolder; ins; desf.\n    { split; auto. ins. eapply CONS1. basic_solver 10. }\n    exfalso. eapply CONS0.\n    apply ct_ct; eexists; split; apply ct_step; generalize RF2 NEQ; basic_solver.\n  Qed.\n  \n  Lemma co_ts x y :\n    co G x y <-> acts G x /\\ acts G y /\\ is_w x /\\ is_w y /\\\n                 loc x = loc y /\\ ev_ts x < ev_ts y.\n  Proof.\n    split; ins; desc.\n      hahn_rewrite (wf_coE WF) in H;\n        hahn_rewrite (wf_coD WF) in H; unfolder in H; desf; splits; ins;\n          eauto using co_tsE.\n      eapply wf_col; eauto.\n    destruct (classic (x = y)) as [|NEQ]; desf; try lia.\n    eapply (wf_co_total WF) in NEQ; desf; ins.\n    eapply co_tsE in NEQ; lia.\n  Qed.\n\n\n  Lemma ts_uniq x y :\n    acts G x -> acts G y -> is_w x -> is_w y ->\n    loc x = loc y ->\n    ev_ts x = ev_ts y ->\n    x = y.\n  Proof.\n    ins; apply NNPP; intro NEQ.\n    eapply wf_co_total in NEQ; unfolder; eauto.\n    desf; apply co_tsE in NEQ; lia.\n  Qed.\n  \n  (** Safe points **)\n  Definition safepoints w :=\n    let f := fun e => \n               ⟪ TL   : ev_ts e < ev_ts w\n                        (* Required for updates. *)\n                        \\/ e = w ⟫ /\\\n               ⟪ LOC  : loc e = loc w ⟫\n    in\n    set_compl (dom_rel ((hb G)^? ⨾ ⦗f⦘)).\n  \n  Lemma safepoints_irr e : ~ safepoints e e.\n  Proof. intros AA. apply AA. exists e. basic_solver. Qed.\n\n  Lemma safepoint_hb_mon w :\n    codom_rel (⦗safepoints w⦘ ⨾ hb G) ⊆₁ safepoints w.\n  Proof.\n    unfold safepoints.\n    intros x [y HH] AA. apply seq_eqv_l in HH. destruct HH as [BB HB].\n    apply BB. generalize AA HB (@hb_trans G). basic_solver 10.\n  Qed.\n\n  (** tslot: Time slot for message's propagation **)\n  Definition tslot t w :=\n    match excluded_middle_informative\n            (acts G w /\\ is_w w /\\ ~ is_init w /\\\n             t <> 0 /\\\n             (exists et, acts G et /\\ tid et = t)) with\n    | left B =>\n      let P := fun n =>\n                 ⟪ LT  : nu_inv w <= n ⟫ /\\\n                 ⟪ SP  : forall m (GT : n < m) (EM : lt_size m (acts G \\₁ is_init))\n                                (TIDT : tid (nu m) = t),\n                     safepoints w (nu m) ⟫ in\n      let minP := fun n => forall m (PM : P m), n <= m in\n      match excluded_middle_informative (exists n, P n /\\ minP n) with\n      | left A  => Some (proj1_sig (constructive_indefinite_description _ A))\n      | right _ => None\n      end\n    | _ => None\n    end.\n\n  Lemma tslot_defined_only_for_w t w m\n        (TS : Some m = tslot t w) :\n    is_w w.\n  Proof. unfold tslot in *. desf; desf. Qed.\n\n  Lemma tslot_defined_only_for_non_init t e m\n        (TS : Some m = tslot t e) :\n    t <> 0.\n  Proof. unfold tslot in *. desf; desf. Qed.\n\n  Lemma tslot_defined_only_for_non_init_e t e m\n        (TS : Some m = tslot t e) :\n    ~ is_init e.\n  Proof. unfold tslot in *. desf; desf. Qed.\n\n  Lemma tslot_defined_only_for_E t w m\n        (TS : Some m = tslot t w) :\n    acts G w.\n  Proof. unfold tslot in *. desf; desf. Qed.\n\n  Lemma tslot_defined_only_for_non_empty_threads t w m\n        (TS : Some m = tslot t w) :\n    exists e, acts G e /\\ tid e = t.\n  Proof. unfold tslot in *. desf; desf; eauto. Qed.\n  \n(*   Lemma tslot_is_safepoint t w m *)\n(*         (TS : Some m = tslot t w) : *)\n(*     safepoints w (nu m). *)\n(*   Proof. *)\n(*     unfold tslot in *. do 2 desf. *)\n(*     unfold proj1_sig. do 2 desf. clear Heq. *)\n(* desf. *)\n(*     { rewrite nu_nu_inv; auto. *)\n(*       red. intros HH. desc. *)\n(*       assert (hb G w e) as HBWE. *)\n(*       { generalize INHB (@hb_trans G) (@sb_in_hb G). *)\n(*         basic_solver. } *)\n(*       apply hb_tsE in HBWE; auto. desf. *)\n(*       { lia. } *)\n(*       destruct INHB as [x HH]. apply seq_eqv_l in HH. desf. *)\n(*       eapply hb_irr with (x:=x); eauto. generalize HH0 (@sb_in_hb G) (@hb_trans G). *)\n(*       basic_solver. } *)\n(*     red. intros HH. desc. *)\n(*     destruct INHB as [x AA]. *)\n(*     apply seq_eqv_l in AA. destruct AA as [XX AA]. *)\n(*     enough (safepoints w x) as BB. *)\n(*     { clear XX. apply BB. eexists. splits; eauto. *)\n(*       exists x. basic_solver. } *)\n(*     clear dependent e0. subst. *)\n(*     unfold proj1_sig. do 2 desf. *)\n(*   Qed. *)\n\n  Lemma tslot_lt_index t w n \n        (TS : Some n = tslot t w) :\n    nu_inv w <= n.\n  Proof.\n    unfold tslot in *. do 2 desf.\n    unfold proj1_sig. do 2 desf.\n  Qed.\n  \n  (* Lemma no_sb_is_safepoint w e *)\n  (*       (NSB : codom_rel (⦗eq e⦘ ⨾ sb G) ⊆₁ ∅) : *)\n  (*   safepoints w e. *)\n  (* Proof. *)\n  (*   red. intros HH. desc. *)\n  (*   generalize NSB INHB. basic_solver. *)\n  (* Qed. *)\n\n  Lemma sb_nu n (Ln : lt_size n (acts G \\₁ is_init))\n        m (Lm : lt_size m (acts G \\₁ is_init)) :\n    sb G (nu n) (nu m) <->\n    tid (nu n) = tid (nu m) /\\ index (nu n) < index (nu m).\n  Proof.\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    unfold sb; split; ins; unfolder in *; desc.\n    all: unfold ext_sb in *; desf; ins; desf; try lia.\n    { eapply RNG in Ln; desf; destruct (nu n); ins; ins. }\n    all: splits; ins; rewrite <- ?Heq, <- ? Heq0; apply RNG; ins.\n  Qed.\n\n  Lemma sb_nu_alt n (Ln : lt_size n (acts G \\₁ is_init))\n        m (Lm : lt_size m (acts G \\₁ is_init))\n        (TID : tid (nu m) = tid (nu n)) :\n    index (nu m) < index (nu n) <-> m < n.\n  Proof.\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    split; intro X.\n    apply IMPL; eauto using lt_lt_size.\n    apply t_step, or_introl, sb_nu; ins.\n    destruct (lt_eq_lt_dec (index (nu m)) (index (nu n))) as [[|EQ]|LT]; ins; try lia.\n      assert (m = n); desf; try lia.\n      apply INJ; ins; apply (wf_index WF); splits; ins; try apply RNG; ins.\n    assert (n < m); try lia.\n    eapply IMPL; ins; apply t_step, or_introl, sb_nu; ins.\n  Qed.\n\n  Lemma sb_nu_lt n (Ln : lt_size n (acts G \\₁ is_init))\n        m (Lm : lt_size m (acts G \\₁ is_init)) :\n    sb G (nu n) (nu m) <->\n    tid (nu n) = tid (nu m) /\\ n < m.\n  Proof.\n    etransitivity.\n    { apply sb_nu; auto. }\n    split; intros [BB CC]; split; auto.\n    all: apply sb_nu_alt; auto.\n  Qed.\n\n  Lemma tslot_defined t w\n        (TNINIT : t <> 0)\n        (ACT : acts G w)\n        (NINIT : ~ is_init w)\n        (WW : is_w w)\n        (TNEMPTY : exists e, acts G e /\\ tid e = t) :\n    exists m, tslot t w = Some m.\n  Proof.\n    assert (forall e, acts G e /\\ tid e = t -> ~ is_init e) as GNINIT.\n    { intros e [GE TE]. rewrite <- TE in TNINIT.\n      intros HH. rewrite <- wf_tid_init in HH; eauto. }\n    desf. unfold tslot. desf; eauto.\n    2: { exfalso. apply n. splits; eauto. }\n    exfalso. rename n into AA. apply AA.\n    enough (exists n : nat,\n               (nu_inv w <= n /\\\n                forall m : nat,\n                  n < m -> tid (nu m) = tid e -> lt_size m (acts G \\₁ is_init) ->\n                  safepoints w (nu m)))\n      as HH'.\n    { desf. eapply set_nat_exists_min with (n:=n); splits; eauto. }\n    clear a. clear AA.\n    destruct (classic (exists j,\n                          ⟪ JGE  : nu_inv w < j ⟫ /\\\n                          ⟪ GEJ  : lt_size j (acts G \\₁ is_init) ⟫ /\\\n                          ⟪ TMJ  : tid (nu j) = tid e ⟫ /\\\n                          ⟪ NSFJ : ~ safepoints w (nu j) ⟫)) as [|NEX].\n    2: { exists (nu_inv w). splits; auto. ins. apply NNPP. intros HH.\n         apply NEX; eauto. }\n    desf.\n    set (TT:=ENUM). rewrite enumeratesE in TT. desf.\n    assert (acts G (nu j)) as NUJE.\n    { by apply RNG. }\n    destruct (classic (set_finite (acts G \\₁ is_init))) as [FIN|INF].\n    { edestruct @set_finite_r_min_precise_bounded\n        with (A:=Event)\n             (s:=(acts G ∩₁ (fun x => tid x = tid e) ∩₁ (fun x => nu_inv w < nu_inv x)))\n             (r:=(sb G)⁻¹)\n             (n:=nu j) as [bound].\n      { eapply set_finite_mori; [|by apply FIN].\n        red. basic_solver. }\n      { apply transitive_transp. by apply sb_trans. }\n      { by apply sb_irr. }\n      { unfolder. splits; auto. by rewrite nu_inv_nu. }\n      desf.\n      unfolder in INS. desf.\n      exists (nu_inv bound).\n      splits; auto.\n      { lia. }\n      intros m LTT TIDM LTM. exfalso.\n      assert (acts G (nu m)) as ME by (by apply RNG).\n      assert (~ is_init (nu m)) as NINIM; auto.\n      edestruct same_thread with (x:=bound) (y:=nu m) as [[EQ|SB]|SB]; eauto; subst.\n      { by rewrite INS1. }\n      { rewrite nu_inv_nu in LTT; auto. lia. }\n      { eapply BND; eauto. unfolder. splits; auto.\n        rewrite nu_inv_nu; auto. lia. }\n      apply sb_in_hb in SB. rewrite <- nu_nu_inv with (x:=bound) in SB; auto.\n      eapply IMPL in SB; auto.\n      { lia. }\n      apply nu_inv_lt_size. split; auto. }\n    destruct (classic\n                (set_finite\n                   (fun n => (acts G ∩₁ (fun x => tid x = tid e)) (nu n))))\n      as [SF|NSF].\n    { assert (set_finite (acts G ∩₁ (fun x => tid x = tid e))) as AA.\n      { red in SF. desf.\n        exists (map nu findom). ins.\n        assert (acts G x) by apply IN.\n        assert (~ is_init x).\n        { apply GNINIT. apply IN. }\n        rewrite <- nu_nu_inv with (x:=x); auto.\n        apply in_map. apply SF.\n        rewrite nu_nu_inv with (x:=x); auto. }\n      eapply set_finite_r_min_precise_bounded with (r:=(sb G)⁻¹) (n:=nu j) in AA.\n      4: by split.\n      3: by apply sb_irr.\n      2: { apply transitive_transp. by apply sb_trans. }\n      desf.\n      unfolder in INS. desf.\n      destruct (SUR bound) as [nbound].\n      { split; auto. }\n      desf. exists nbound.\n      assert (~ dom_rel (sb G) (nu nbound)) as NSB.\n      { intros [y SB].\n        assert (tid y = tid e).\n        { apply sb_tid_init in SB. desf; intuition.\n          red in SB. desf. ins. intuition. }\n        eapply BND; eauto. split; auto.\n        apply (@wf_sbE G) in SB. unfolder in SB. desf. }\n      splits; auto.\n      2: { red. ins. intros HH. desc.\n           assert (acts G (nu m)) as EGM.\n           { by apply RNG. }\n           assert (sb G (nu nbound) (nu m)) as SB.\n           { apply sb_nu_lt; auto. rewrite INS0. split; auto. }\n           generalize SB NSB. basic_solver. }\n      apply Nat.le_ngt; intros AA.\n      assert (sb G (nu nbound) (nu j)) as SB.\n      { apply sb_nu_lt; auto. rewrite INS0. split; auto. lia. }\n      generalize SB NSB. basic_solver. }\n    apply not_all_not_ex.\n    intros HH.\n    remember (fun e =>\n                (acts G \\₁ is_init) e /\\\n                ev_ts e < ev_ts w /\\\n                loc e = loc w) as ff.\n    enough (~ set_finite ff) as PR.\n    { apply PR. eapply set_finite_more with (y:=(is_r ∪₁ is_w) ∩₁ ff).\n      { generalize r_or_w. basic_solver. }\n      rewrite set_inter_union_l. eapply set_finite_union.\n      cdes FAIR. apply and_comm.\n      rewrite co_tsE_alt in FAIR0.\n      rewrite fr_tsE_alt in FAIR1.\n      split.\n      { eapply set_finite_mori; [|by apply FAIR0 with (y:=w)].\n        subst ff. red. basic_solver. }\n      eapply set_finite_mori; [|by apply FAIR1 with (y:=w)].\n      subst ff. red. basic_solver. }\n    intros SF.\n    assert (set_finite (fun n => ff (nu n))) as SFNU.\n    { red in SF. desf. exists (map nu_inv findom).\n      ins. desf.\n      arewrite (x = nu_inv (nu x)).\n      { rewrite nu_inv_nu; auto. apply lt_size_infinite; auto. }\n      apply in_map. apply SF. by splits. }\n    apply set_finite_nat_bounded in SFNU. destruct SFNU as [bound SFNU].\n    eapply set_infinite_nat_exists_bigger\n      with (n:=1+bound+j) in NSF.\n    destruct NSF as [m [LT [GM TT]]]. unnw.\n    specialize (HH m). apply HH. splits; auto.\n    { lia. }\n    ins. red. intros [e0 AA]. apply seq_eqv_r in AA. desc.\n    assert (~ is_init (nu m0)) as NINITM0.\n    { by apply RNG. }\n    assert (~ is_init e0) as NINIT'.\n    { destruct AA as [|HB]; desf. apply no_hb_to_init in HB; auto. unfolder in HB. desf. }\n    assert ((acts G \\₁ is_init) (nu m0)) as ACTNINTIM0 by (by apply RNG).\n    assert ((acts G \\₁ is_init) e0) as ACTNINITE0.\n    { destruct AA as [|HB]; desf.\n      split.\n      2: by apply no_hb_to_init in HB; auto.\n      apply (wf_hbE WF) in HB. unfolder in HB. desf. }\n    assert (acts G e0) by apply ACTNINITE0.\n    assert (m0 <= nu_inv e0) as LTT.\n    { destruct AA as [|HB]; desc; subst.\n      { rewrite nu_inv_nu; auto. }\n      apply Nat.lt_le_incl.\n      rewrite <- nu_inv_nu with (n:=m0); auto.\n      apply IMPL; auto.\n      all: try rewrite nu_inv_nu; auto.\n      all: try rewrite nu_nu_inv; auto.\n      apply nu_inv_lt_size; auto. }\n    desf.\n    2: lia.\n    enough (nu_inv e0 <= bound).\n    { lia. }\n    apply Nat.lt_le_incl. apply SFNU.\n    rewrite nu_nu_inv; auto.\n  Qed.\n\n  Hint Resolve hb_irr : hahn.\n\n  Lemma hb_preds y :\n    set_finite (fun x => (hb G)^? x y /\\ ~ is_init x).\n  Proof.\n    forward eapply fsupp_hb as X; eauto with hahn.\n    { eapply has_finite_antichains_sb; ins.\n      apply BOUND. }\n    specialize (X y); desf.\n    exists (y :: findom); unfolder in *; ins; desf; eauto 6.\n  Qed.\n\n  Lemma sbrf_preds y :\n    set_finite (fun x => ((rf G)^? ;; (sb G)^?) x y /\\ ~ is_init x).\n  Proof.\n    eapply set_finite_mori.\n    2: by apply (hb_preds y).\n    assert (((rf G)^? ⨾ (sb G)^?) ⊆ (hb G)^?) as AA.\n    { unfold hb. rewrite cr_of_ct.\n      rewrite <- rt_cr. rewrite <- inclusion_r_rt with (r:=sb G ∪ rf G).\n      all: basic_solver 10. }\n    red. intros x HH. desf. apply AA in HH. basic_solver.\n  Qed.\n  \n  (* In the paper, it is called _vmap_. *)\n  Definition ev_view e l :=\n    max_of_list\n      (map\n         ev_ts\n         (filterP\n            (fun a => is_w a /\\ loc a = l)\n            (proj1_sig\n               (constructive_indefinite_description\n                  _ ((proj1 (set_finiteE _) (sbrf_preds e))))))).\n\n  Lemma ev_view_includes x y :\n    ((rf G)^? ;; (sb G)^?) x y -> is_w x -> ev_ts x <= ev_view y (loc x).\n  Proof.\n    unfold ev_view.\n    destruct (constructive_indefinite_description); ins.\n    destruct (classic (is_init x)) as [INITx|NIx].\n    destruct x; ins; rewrite ev_ts_init; lia.\n    desf. destruct a0 as [a0 i].\n    specialize_full i; eauto. red in i.\n    apply in_max_of_list. in_simp.\n    exists x. splits; auto.\n    in_simp. auto.\n  Qed.\n  \n  (* TODO: move to a more appropriate place *)\n  Lemma rfsb_sb : (rf G)^? ⨾ (sb G)^? ;; (sb G) ⊆ (rf G)^? ⨾ (sb G)^?.\n  Proof using.\n    arewrite ((sb G)^? ⨾ sb G ⊆ sb G).\n    { generalize (@sb_trans G). basic_solver. }\n    basic_solver 10.\n  Qed.\n\n  (* TODO: move to a more appropriate place *)\n  Lemma rfsb_in_hb : (rf G)^? ⨾ (sb G)^? ⊆ (hb G)^?.\n  Proof using.\n    unfold hb. rewrite cr_of_ct. rewrite <- rt_rt.\n    rewrite <- inclusion_r_rt with (r:=sb G ∪ rf G); [|done].\n    basic_solver 10.\n  Qed.\n\n  Lemma sb_viewE x y :\n    sb G x y -> view_le (ev_view x) (ev_view y).\n  Proof.\n    unfold ev_view.\n    ins. do 2 destruct (constructive_indefinite_description); intros. ins.\n    desf.\n    intro l; apply incl_max_of_list; red; ins; in_simp.\n    exists x2. splits; auto.\n    in_simp. splits; auto. apply a1. apply a2 in H1.\n    desf. splits; auto.\n    apply rfsb_sb. apply seqA. eexists; eauto.\n  Qed.\n\n  Lemma sb_hb_preds y :\n    set_finite (fun x => (sb G ⨾ (hb G)^?) x y /\\ ~ is_init x).\n  Proof.\n    eapply set_finite_mori.\n    2: by apply hb_preds with (y:=y).\n    assert (sb G ⨾ (hb G)^? ⊆ (hb G)^?) as AA.\n    { rewrite sb_in_hb. generalize hb_trans. basic_solver. }\n    red. generalize AA. basic_solver 10.\n  Qed.\n  \n  Lemma tslot_dom_finite_lt n :\n    set_finite (fun tw =>\n                  exists m,\n                    Some m = tslot (fst tw) (snd tw) /\\\n                    m < n).\n  Proof.\n    set (AA:=BOUND). destruct AA as [nt AA].\n    exists (list_prod (List.seq 0 nt)\n                      (map nu (List.seq 0 (S n)))).\n    ins. desf. destruct x as [t w]. ins.\n    apply in_prod_iff. split.\n    { apply in_seq0_iff.\n      edestruct tslot_defined_only_for_non_empty_threads; eauto.\n      desf. by apply AA. }\n    assert (~ is_init w) as NINIT.\n    { eapply tslot_defined_only_for_non_init_e; eauto. }\n    assert (acts G w) as EW.\n    { eapply tslot_defined_only_for_E; eauto. }\n    rewrite <- nu_nu_inv with (x:=w); auto.\n    in_simp. eexists. splits; eauto.\n    apply in_seq0_iff.\n    apply tslot_lt_index in IN. lia.\n  Qed.\n\n  Lemma tslot_dom_finite n :\n    set_finite (fun tw => Some n = tslot (fst tw) (snd tw)).\n  Proof.\n    eapply set_finite_mori.\n    2: by apply tslot_dom_finite_lt.\n    red. basic_solver.\n  Qed.\n\n  Lemma tslot_w_dom_finite_lt t n :\n    set_finite (fun w =>\n                  exists m,\n                    Some m = tslot t w /\\\n                    m < n).\n  Proof.\n    exists (map nu (List.seq 0 (S n))).\n    ins. desf. ins.\n    assert (~ is_init x) as NINIT.\n    { eapply tslot_defined_only_for_non_init_e; eauto. }\n    assert (acts G x) as EW.\n    { eapply tslot_defined_only_for_E; eauto. }\n    rewrite <- nu_nu_inv with (x:=x); auto.\n    in_simp. eexists. splits; eauto.\n    apply in_seq0_iff.\n    apply tslot_lt_index in IN. lia.\n  Qed.\n\n  Definition props_before t n :=\n    proj1_sig\n      (constructive_indefinite_description\n         _ ((proj1 (set_finiteE _) (tslot_w_dom_finite_lt t n)))).\n\n  (* In the paper, it is called _vmap-propagate_. *)\n  Definition ev_view_prop e l : nat :=\n    let n := nu_inv e in\n    max_of_list\n      (map ev_ts (filterP (fun w => loc w = l)\n                          (props_before (tid e) n))).\n\n  Lemma props_before_sb_mon x y z (SB : sb G x y)\n        (IN : In z (props_before (tid x) (nu_inv x))) :\n    In z (props_before (tid y) (nu_inv y)).\n  Proof.\n    assert (acts G x /\\ acts G y) as [EX EY].\n    { apply wf_sbE in SB; auto. unfolder in SB. desf. }\n    unfold props_before, proj1_sig in *. do 2 desf. clear Heq Heq0.\n    apply a2 in IN. desf. apply a1. splits; auto.\n    clear dependent x0. clear dependent x1.\n    assert (tid x <> 0) as TIDXNINIT.\n    { eapply tslot_defined_only_for_non_init; eauto. }\n    assert (~ is_init x) as NINITX.\n    { unfold is_init. desf. }\n    assert (tid y = tid x) as TEQ.\n    { apply sb_tid_init in SB. desf. }\n    assert (~ is_init y) as NINITY.\n    { unfold is_init. desf. ins. auto. }\n    rewrite TEQ.\n    exists m. splits; auto.\n    enough (nu_inv x < nu_inv y); [lia|].\n    apply IMPL.\n    1,2: by apply nu_inv_lt_size; split; auto.\n    apply sb_in_hb. do 2 (rewrite nu_nu_inv; auto).\n  Qed.\n\n  Lemma props_before_index_mon t x y z (LE : x <= y)\n        (IN : In z (props_before t x)) :\n    In z (props_before t y).\n  Proof.\n    unfold props_before, proj1_sig in *. do 2 desf. clear Heq Heq0.\n    apply a2 in IN. desf. apply a1. splits; auto.\n    clear dependent x0. clear dependent x1.\n    eexists. splits; eauto. lia.\n  Qed.\n\n  Lemma tslot_gt_is_safepoint t w m n\n        (TS : Some m = tslot t w)\n        (ACT : lt_size n (acts G \\₁ is_init))\n        (TT : tid (nu n) = t)\n        (LT : m < n) :\n    safepoints w (nu n).\n  Proof.\n    unfold tslot in TS. do 2 desf. unfold proj1_sig in LT. do 2 desf. clear Heq.\n    apply SP0; auto.\n  Qed.\n\n  Lemma props_before_hb_mon x y z (HB : hb G x y)\n        (IN : In z (props_before (tid x) (nu_inv x))) :\n    In z (props_before (tid y) (nu_inv y)).\n  Proof.\n    assert (acts G x /\\ acts G y) as [EX EY].\n    { apply wf_hbE in HB; auto. unfolder in HB. desf. }\n    unfold props_before, proj1_sig in *. do 2 desf. clear Heq Heq0.\n    apply a2 in IN. desf. apply a1. splits; auto.\n    clear dependent x0. clear dependent x1.\n    assert (tid x <> 0) as TIDXNINIT.\n    { eapply tslot_defined_only_for_non_init; eauto. }\n    assert (~ is_init x) as NINITX.\n    { unfold is_init. desf. }\n    assert (~ is_init y) as NINITY.\n    { intros HH. eapply hb_init_r; eauto. }\n    assert (tid y <> 0) as TIDYNINIT.\n    { intros HH. apply (wf_tid_init WF) in HH; auto. }\n    assert (lt_size (nu_inv x) (acts G \\₁ is_init)) as LTNUINVX.\n    { apply nu_inv_lt_size. split; auto. }\n    assert (lt_size (nu_inv y) (acts G \\₁ is_init)) as LTNUINVY.\n    { apply nu_inv_lt_size. split; auto. }\n    assert (acts G z) as EZ.\n    { eapply tslot_defined_only_for_E; eauto. }\n    assert (is_w z) as WZ.\n    { eapply tslot_defined_only_for_w; eauto. }\n    assert (~ is_init z) as NINITZ.\n    { eapply tslot_defined_only_for_non_init_e; eauto. }\n    assert (lt_size (nu_inv z) (acts G \\₁ is_init)) as LTNUINVZ.\n    { apply nu_inv_lt_size. split; auto. }\n    assert (nu_inv x < nu_inv y) as NUINVLT.\n    { apply IMPL.\n      1,2: by apply nu_inv_lt_size; split; auto.\n      do 2 (rewrite nu_nu_inv; auto). }\n    assert (safepoints z x) as SFZX.\n    { rewrite <- nu_nu_inv with (x:=x); auto.\n      eapply tslot_gt_is_safepoint with (m:=m); eauto.\n      rewrite nu_nu_inv; auto. }\n    assert (safepoints z y) as SFZY.\n    { eapply safepoint_hb_mon. exists x. basic_solver. }\n\n    unfold tslot in IN. do 2 desf.\n    unfold proj1_sig in IN0. do 2 desf. clear Heq.\n    clear dependent n.\n    unfold tslot. desf.\n    3: { exfalso. apply n. splits; eauto. }\n    2: { exfalso. desf. apply n. eapply set_nat_exists_min with (n:=nu_inv y).\n         splits; eauto.\n         { lia. }\n         ins.\n         assert (sb G y (nu m)) as SB.\n         { rewrite <- nu_nu_inv with (x:=y); auto.\n           apply sb_nu_lt; auto.\n           rewrite nu_nu_inv; auto. }\n         intros AA. apply SP0 with (m:=nu_inv x); auto.\n         all: rewrite nu_nu_inv; auto.\n         apply sb_in_hb in SB.\n         generalize HB SB (@hb_trans G) AA. basic_solver 10. }\n    eexists. splits; eauto. unfold proj1_sig. do 2 desf. clear Heq.\n    enough (x1 <= Nat.pred (nu_inv y)); [lia|].\n    apply a13. splits; [lia|].\n    ins.\n    destruct (classic (m = nu_inv y)) as [|NEQ]; subst.\n    { rewrite nu_nu_inv; auto. }\n    assert (sb G y (nu m)) as SB.\n    { rewrite <- nu_nu_inv with (x:=y); auto.\n      apply sb_nu_lt; auto.\n      rewrite nu_nu_inv; auto. split; auto. lia. }\n    apply sb_in_hb in SB.\n    eapply safepoint_hb_mon. exists y. basic_solver.\n  Qed.\n\n  Lemma hb_view_propE x y (HB : hb G x y) :\n    view_le (ev_view_prop x) (ev_view_prop y).\n  Proof.\n    unfold ev_view_prop.\n    intros l. apply incl_max_of_list. red. ins. in_simp.\n    eexists. splits; eauto. in_simp. splits; eauto.\n    eapply props_before_hb_mon; eauto.\n  Qed.\n\n  (* In the paper, it is called _vmap-full_. *)\n  Definition ev_view_full (e : Event) := view_join (ev_view e) (ev_view_prop e).\n\n  Lemma ev_view_full_includes x y :\n    ((rf G)^? ;; (sb G)^?) x y -> is_w x -> ev_ts x <= ev_view_full y (loc x).\n  Proof.\n    ins. etransitivity.\n    { eapply ev_view_includes; eauto. }\n    unfold ev_view_full, view_join. apply Nat.le_max_l.\n  Qed.\n\n  Lemma sb_view_fullE x y :\n    sb G x y -> view_le (ev_view_full x) (ev_view_full y).\n  Proof.\n    ins. unfold ev_view_full.\n    eapply view_le_join.\n    { by apply sb_viewE. }\n    apply hb_view_propE. by apply sb_in_hb.\n  Qed.\n\n  Definition msg_of (n : nat) :=\n    {| mloc := loc (nu n) ;\n       mval := valw (nu n) ;\n       mts := ev_ts (nu n) ;\n       mview := ev_view_full (nu n) |}.\n\n  (* In the paper, it is called M_i. *)\n  Definition scoh_mem (n : nat) :=\n    Minit ∪₁ ⋃₁ m < n, ifP is_w (nu m) then eq (msg_of m) else ∅.\n\n  (* In the paper, it is called T'_i. *)\n  Definition scoh_view' (n : nat) t :=\n    view_join (view_joinl (map ev_view_full\n                               (filterP (fun x => tid x = t)\n                                        (map nu (List.seq 0 n)))))\n              (fun l : Loc =>\n                 max_of_list\n                   (map ev_ts (filterP (fun w => loc w = l)\n                                       (props_before t (Nat.pred n))))).\n\n  (* In the paper, it is called T_i. *)\n  Definition scoh_view (n : nat) t :=\n    view_join (scoh_view' n t)\n              (fun l : Loc =>\n                 max_of_list\n                   (map ev_ts (filterP (fun w => loc w = l)\n                                       (props_before t n)))).\n\n  Definition scoh_state (n : nat) : State :=\n    (scoh_mem n, scoh_view n).\n  \n  Lemma props_before_zero t : props_before t 0 = nil.\n  Proof.\n    unfold props_before, proj1_sig. desf. clear Heq. desf.\n    destruct x; auto. exfalso. destruct a0 as [_ HH].\n    specialize (HH e). destruct HH; desf; lia.\n  Qed.\n\n  Lemma scoh_state_init :\n    scoh_state 0 = Sinit.\n  Proof.\n    unfold scoh_state, Sinit; f_equal.\n    { unfold scoh_mem; extensionality msg.\n      apply propositional_extensionality; unfolder.\n      split; ins; desf; eauto; lia. }\n    unfold scoh_view, scoh_view'. ins.\n    extensionality t.\n    arewrite (List.seq 0 0 = nil); ins.\n    rewrite props_before_zero; auto.\n  Qed.\n  \n  (* TODO: move to a more appropriate place. *)\n  Lemma rfsb_init_r :\n    (rf G)^? ;; (sb G)^? ⊆ <|fun _ => True|> ∪ (rf G)^? ;; (sb G)^? ;; <|set_compl is_init|>.\n  Proof using WF.\n    rewrite no_sb_to_init at 1.\n    rewrite no_rf_to_init at 1; auto.\n    basic_solver 20.\n  Qed.\n\n  (* TODO: move to a more appropriate place. *)\n  Lemma wf_rfsbE :\n    (rf G)^? ;; (sb G)^? ⊆ <|fun _ => True|> ∪\n                           <|acts G|> ;; (rf G)^? ;; (sb G)^? ;; <|acts G|>.\n  Proof using WF.\n    rewrite wf_sbE at 1.\n    rewrite (wf_rfE WF) at 1.\n    basic_solver 20.\n  Qed.\n\n  Lemma ev_view_init x :\n    ev_view (InitEvent x) = (fun _ => 0).\n  Proof.\n    extensionality l. unfold ev_view, proj1_sig; desf; desf. clear Heq.\n    induction x0; ins; desc; ins; desc.\n    inv a. desf; ins; rewrite IHx0; auto.\n    { rewrite Nat.max_0_r.\n      destruct a0 as [_ [HH BB]]; eauto.\n      apply rfsb_init_r  in HH. unfolder in HH. desf. }\n    all: split; intros y HH; [|by desf; apply a0; auto].\n    all: desf; apply rfsb_init_r in HH; unfolder in HH; desf.\n  Qed.\n\n  Lemma props_before_tnit_is_empty e :\n    props_before 0 e = nil.\n  Proof.\n    unfold props_before, proj1_sig. do 2 desf. clear Heq.\n    destruct x; auto.\n    assert (In e0 (e0::x)) as AA by (by constructor).\n    apply a0 in AA. desf.\n    apply tslot_defined_only_for_non_init in AA. lia.\n  Qed.\n\n  Lemma ev_view_prop_init x :\n    ev_view_prop (InitEvent x) = (fun _ => 0).\n  Proof.\n    unfold ev_view_prop. extensionality l.\n    apply Nat.le_antisymm.\n    2: lia.\n    apply le_max_of_list_l. ins. in_simp.\n    rewrite props_before_tnit_is_empty in H0. inv H0.\n  Qed.\n\n  Lemma ev_view_full_init x :\n    ev_view_full (InitEvent x) = (fun _ => 0).\n  Proof.\n    unfold ev_view_full. rewrite ev_view_init, ev_view_prop_init.\n      by rewrite view_join_0_l.\n  Qed.\n\n  Lemma ev_ts_nzero n (Ln : lt_size n (acts G \\₁ is_init)) :\n    is_w (nu n) -> ev_ts (nu n) <> 0.\n  Proof.\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    unfold ev_ts; desf.\n    unfold ev_ts_w, proj1_sig; desf; clear Heq.\n    intros _.\n    specialize (i0 (InitEvent (loc (nu n)))); specialize_full i0.\n      apply co_init_l; ins; eauto.\n    apply in_undup_iff, in_split in i0; desc.\n    rewrite i0, filterP_app, length_app; ins; desf; ins; try lia.\n    destruct n0; apply co_init_l; ins; eauto.\n  Qed.\n\n  Lemma ev_viewI x (ELEM: (acts G \\₁ is_init) x) l :\n    exists y, acts G y /\\ is_w y /\\ loc y = l\n              /\\ ((rf G)^? ;; (sb G)^?) y x\n              /\\ ev_ts y = ev_view x l.\n  Proof.\n    unfold ev_view, proj1_sig; desf; clear Heq; desf.\n    destruct a0 as [_ a0].\n    rename x0 into l'.\n    induction l'; ins; desf; eauto 10.\n    { exists (InitEvent l); rewrite ev_ts_init; splits; ins.\n      apply (wf_initE WF); ins.\n      red in ELEM; desc.\n      eexists; splits.\n      { by left. }\n      right. apply init_ninit_sb; auto.\n      apply (wf_initE WF); ins. }\n    2: { inv a. apply IHl'; auto.\n         etransitivity; [|by apply a0].\n         basic_solver. }\n    ins; desf; ins; desf; eauto 10.\n    inv a. rewrite maxE; desf; eauto 10.\n    { apply IHl'; auto.\n      etransitivity; [|by apply a0].\n      basic_solver. }\n    specialize (a0 a1). destruct a0 as [HH]; eauto.\n    exists a1. splits; eauto.\n    apply wf_rfsbE in HH. unfolder in HH. desf.\n    apply ELEM.\n  Qed.\n\n  Lemma hb_from_sb_nu n m\n    (LTm : lt_size m (acts G \\₁ is_init))\n    (LTn : n < m)\n    (TID : tid (nu n) <> 0 -> tid (nu m) <> 0 -> tid (nu n) = tid (nu m)) :\n    hb G (nu n) (nu m).\n  Proof.\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    assert (tid (nu m) <> 0) as NM.\n    { intros HH. apply (wf_tid_init WF) in HH.\n      { apply RNG in HH; auto. }\n      apply RNG; auto. }\n    assert (LTnn : lt_size n (acts G \\₁ is_init)).\n    { eapply lt_lt_size; eauto. }\n    assert (tid (nu n) <> 0) as NN.\n    { intros HH. apply (wf_tid_init WF) in HH.\n      { apply RNG in HH; auto. }\n      apply RNG; auto. }\n    apply t_step, or_introl, sb_nu; eauto using lt_lt_size.\n    rewrite sb_nu_alt; ins; eauto using lt_lt_size.\n  Qed.\n\n  (* TODO: move to a more appropriate place *)\n  Lemma fr_rfsb (SPL : SCpL G) : irreflexive (fr G ;; (rf G)^? ;; (sb G)^?).\n  Proof using WF.\n    red. intros x HH. unfolder in HH. desf.\n    { eapply SPL with (x:=x). apply ct_step.\n      generalize HH. basic_solver. }\n    { eapply SPL with (x:=x).\n      apply ct_ct; exists z; split; apply ct_step; generalize HH HH0; basic_solver. }\n    { set (AA:=HH). apply (wf_frl WF) in AA.\n      eapply SPL with (x:=x).\n      apply ct_ct; exists z0; split; apply ct_step;\n        generalize HH HH1 AA; basic_solver 10. }\n    set (AA:=HH0). apply (wf_rfl WF) in AA.\n    set (BB:=HH ). apply (wf_frl WF) in BB.\n    unfold same_loc in *. rewrite AA in BB. symmetry in BB.\n    eapply SPL with (x:=x).\n    apply ct_ct; exists z0; split.\n    2: { repeat left. basic_solver. }\n    apply ct_ct; exists z; split; apply ct_step;\n      generalize HH0 HH1 AA; basic_solver 20.\n  Qed.\n\n  (* TODO: move to a more appropriate place *)\n  Lemma co_rfsb (SPL : SCpL G) : irreflexive (co G ;; (rf G)^? ;; (sb G)^?).\n  Proof using WF.\n    red. intros x HH. unfolder in HH. desf.\n    { eapply SPL with (x:=x). apply ct_step.\n      generalize HH. basic_solver. }\n    { eapply SPL with (x:=x).\n      apply ct_ct; exists z; split; apply ct_step; generalize HH HH0; basic_solver. }\n    { set (AA:=HH). apply (wf_col WF) in AA.\n      eapply SPL with (x:=x).\n      apply ct_ct; exists z0; split; apply ct_step;\n        generalize HH HH1 AA; basic_solver 10. }\n    set (AA:=HH0). apply (wf_rfl WF) in AA.\n    set (BB:=HH ). apply (wf_col WF) in BB.\n    unfold same_loc in *. rewrite AA in BB. symmetry in BB.\n    eapply SPL with (x:=x).\n    apply ct_ct; exists z0; split.\n    2: { repeat left. basic_solver. }\n    apply ct_ct; exists z; split; apply ct_step;\n      generalize HH0 HH1 AA; basic_solver 20.\n  Qed.\n\n  Lemma ev_view_loc_w x (W: is_w x) :\n    ev_view x (loc x) = ev_ts x.\n  Proof.\n    unfold ev_view, proj1_sig, scoh_view; desf; clear Heq.\n    desf.\n    destruct (classic (is_init x)).\n    { destruct x; ins; rewrite ev_ts_init.\n      apply max_of_list_eq_zero; ins; in_simp.\n      apply a0 in H1. desf.\n      apply rfsb_init_r in H1. unfolder in H1. desf. }\n    assert (IN: In x x0).\n    { apply a0. basic_solver 10. }\n    apply in_split in IN; desf.\n    rewrite filterP_app, map_app, max_of_list_app; ins; desf; ins;\n      clarify_not; desf; try solve [destruct x; ins; destruct l; ins].\n    rewrite Nat.max_comm, <- Nat.max_assoc, Nat.max_l; ins.\n    rewrite <- max_of_list_app, <- map_app, <- filterP_app.\n    rewrite le_max_of_list_l; ins; in_simp.\n    destruct (classic (x0 = x)) as [|NEQ]; desf.\n    destruct a0 as [_ HH]. destruct (HH x0) as [HB NINIT].\n    { apply in_app_or in H1. desf.\n      { apply in_app_r. red; auto. }\n        by apply in_app_l. }\n    set (CC:=HB). apply wf_rfsbE in CC.\n    destruct CC as [CC|CC].\n    { unfolder in CC. desf. }\n    apply seq_eqv_l in CC. desf.\n    assert (acts G x) as EX.\n    { unfolder in CC0. desf. }\n    eapply (wf_co_total WF) in NEQ; unfolder; splits; ins; desf; eauto.\n    { apply co_tsE in NEQ; lia. }\n    exfalso. eapply co_rfsb.\n    { apply CONS. }\n    exists x0; split; eauto.\n  Qed.\n\n  Lemma ev_view_prop_loc x (ACTX : (acts G \\₁ is_init) x) :\n    ev_view_prop x (loc x) <= ev_ts x.\n  Proof.\n    assert (acts G x /\\ ~ is_init x) as [AX NIX] by apply ACTX.\n    unfold ev_view_prop, props_before, proj1_sig. do 2 desf. clear Heq.\n    apply le_max_of_list_l. ins. in_simp.\n    apply a0 in H0. desf.\n    apply Nat.nlt_ge. intros LTT.\n    eapply tslot_gt_is_safepoint; eauto.\n    { by apply nu_inv_lt_size. }\n    all: rewrite nu_nu_inv; auto.\n    exists x. apply seq_eqv_r. splits; auto.\n  Qed.\n\n  Lemma ev_view_full_loc_w x (W: is_w x) (ACTX : (acts G \\₁ is_init) x) :\n    ev_view_full x (loc x) = ev_ts x.\n  Proof.\n    unfold ev_view_full, view_join.\n    rewrite ev_view_loc_w; auto.\n    apply Max.max_l. by apply ev_view_prop_loc.\n  Qed.\n  \n  Lemma ev_view_loc x (Ax : acts G x) :\n    ev_view x (loc x) = ev_ts x.\n  Proof.\n    destruct (classic (is_w x)) as [|NW]; eauto using ev_view_loc_w.\n    unfold ev_ts, proj1_sig; desf; clarify_not.\n    2: by destruct x; ins; destruct l; ins.\n    clear Heq s; rename x0 into w.\n    assert (W: is_w w) by (apply wf_rfD in r; unfolder in *; desf).\n    assert (L: loc w = loc x) by (apply wf_rfl in r; unfolder in *; desf).\n    apply Nat.le_antisymm.\n    2: { rewrite <- L; eapply Nat.le_trans, ev_view_includes; ins.\n         { unfold ev_ts; desf; right; vauto. }\n         generalize r. basic_solver 10. }\n    replace (ev_ts_w w) with (ev_ts w) by (unfold ev_ts; desf).\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    forward apply (SUR x) as (i & I); try split; ins; desf.\n    { apply (wf_rfD WF) in r; unfolder in r. desf. destruct x; ins. }\n    unfold ev_view, proj1_sig; desf; clear Heq.\n    apply le_max_of_list_l; ins; in_simp.\n    destruct (classic (x0 = w)) as [|NEQ]; desf.\n    set (AA:=H0). apply a0 in AA. desf.\n    apply wf_rfsbE in AA. destruct AA as [AA|AA].\n    { unfolder in AA. desf. }\n    apply seq_eqv_l in AA. destruct AA as [EX0 AA].\n    (* unfolder in AA. desf. *)\n    (* apply (wf_hbE WF) in AA; unfolder in AA; desc. *)\n    apply (wf_rfE WF) in r; unfolder in r; desc.\n    eapply (wf_co_total WF) in NEQ; unfolder; splits; ins; try congruence.\n    desf; try solve [apply co_tsE in NEQ; lia].\n    exfalso. eapply fr_rfsb; [by apply CONS|].\n    eexists; split. \n    { split.\n      { exists w; split; eauto. }\n      intros HH. unfolder in HH. desf. }\n    apply a0 in H0. desf.\n  Qed.\n\n  Lemma ev_view_full_loc x (ACTX : (acts G \\₁ is_init) x) :\n    ev_view_full x (loc x) = ev_ts x.\n  Proof.\n    assert (acts G x) by apply ACTX.\n    unfold ev_view_full, view_join.\n    rewrite ev_view_loc; auto.\n    apply Max.max_l. by apply ev_view_prop_loc.\n  Qed.\n\n  Lemma scoh_view'_r n\n        (LT : lt_size n (acts G \\₁ is_init))\n        w (RF : rf G w (nu n)) :\n    scoh_view' n (tid (nu n)) (loc (nu n)) <= ev_ts w.\n  Proof.\n    set (TT:=ENUM). apply enumeratesE in TT. desf.\n    assert (~ is_init (nu n)) as NINITN.\n    { intros HH. apply rf_init_r in RF; auto. }\n    assert (R := RF).\n    apply (wf_rfE WF) in RF; unfolder in RF; desc.\n    apply (wf_rfD WF) in RF0; unfolder in RF0; desc.\n    apply (wf_rfl WF) in R; red in R; unfold loc in *; ins.\n    assert (is_init w \\/ exists m, m < n /\\ w = nu m).\n    { apply (wf_rfE WF) in RF2; unfolder in RF2; desf.\n      assert (X := proj1 (enumeratesE _ _) ENUM); desc.\n      classical_right.\n      specialize (SUR w); specialize_full SUR; ins; desf.\n      eexists; split; ins; eapply IMPL; ins; apply t_step; vauto. }\n    destruct (le_lt_dec (scoh_view' n (tid (nu n)) (loc (nu n)))\n                        (ev_ts w)) as [|LT']; ins.\n    exfalso; unfold scoh_view in LT'.\n    clear H.\n    unfold scoh_view', view_join in LT'.\n    apply NPeano.Nat.max_lt_iff in LT'.\n    desf.\n    { rewrite view_joinlE, lt_max_of_list_r in LT'; desf. in_simp.\n      assert (HB: sb G (nu x) (nu n)).\n      { assert (X := ENUM); apply enumeratesE in X; desc.\n        specialize (RNG x); specialize_full RNG; eauto using lt_lt_size.\n        apply proj2 in RNG.\n        apply sb_nu; eauto using lt_lt_size.\n        rewrite sb_nu_alt; ins; eauto using lt_lt_size. }\n      assert (acts G (nu x)) as ENUX.\n      { apply wf_sbE in HB. unfolder in HB. desf. }\n      assert (lt_size x (acts G \\₁ is_init)) as LTACTX.\n      { eapply lt_lt_size; eauto. }\n      unfold ev_view_full, view_join in LT'0.\n      apply NPeano.Nat.max_lt_iff in LT'0. desf.\n      { unfold ev_view, proj1_sig in LT'0; desf; clear Heq.\n        rewrite lt_max_of_list_r in LT'0; desf; in_simp.\n        set (AA:=LT'4). apply a0 in AA. desf.\n        assert (acts G x1) as EX1.\n        { apply wf_rfsbE in AA. unfolder in AA. desf. }\n        assert (co G w x1).\n        { rewrite co_ts; unfold loc; splits; ins; try congruence.\n          red in LT'0; desf. by rewrite R. }\n        eapply fr_rfsb; [by apply CONS|].\n        exists x1. split.\n        2: { eapply rfsb_sb. apply seqA. exists (nu x). split; eauto. }\n        split.\n        { eexists; eauto. }\n        intros HH. unfolder in HH. desf.\n        cdes CONS. eapply PORF.\n        eapply ct_end. eexists. split.\n        2: by left; apply HB.\n        apply rfsb_in_hb in AA.\n          by apply cr_of_ct in AA. }\n      unfold loc in LT'0. rewrite <- R in LT'0.\n      unfold ev_view_prop in LT'0. apply lt_max_of_list_r in LT'0. desf.\n      in_simp. unfold props_before in *.\n      unfold proj1_sig in *; desf. clear Heq. desf.\n      apply a0 in LT'4. desf. clear dependent x1.\n      rewrite nu_inv_nu in LT'5; auto.\n      assert (safepoints x0 (nu x)) as SFWX.\n      { eapply tslot_gt_is_safepoint; eauto. }\n      assert (safepoints x0 (nu n)) as SFWN.\n      { eapply safepoint_hb_mon. apply sb_in_hb in HB. basic_solver 10. }\n      assert (acts G x0) as ACTSX0.\n      { eapply tslot_defined_only_for_E; eauto. }\n      apply SFWN. exists (nu n). apply seq_eqv_r. splits; eauto.\n      2: by rewrite LT'0.\n      assert (is_w x0) as WY.\n      { by apply tslot_defined_only_for_w in LT'4. }\n      destruct (classic (nu n = x0)) as [|NEQ]; auto. left.\n      destruct (classic (is_w (nu n))).\n      2: by rewrite <- rf_tsE with (x:=w) (y:=nu n).\n      assert (ev_ts (nu n) <> ev_ts x0) as TNEQ.\n      { intros HH. apply NEQ. apply ts_uniq; auto. by rewrite LT'0. }\n      rewrite <- rf_rmw_tsE with (x:=w) (y:=nu n); auto.\n      rewrite <- rf_rmw_tsE with (x:=w) (y:=nu n) in TNEQ; auto.\n      clear -LT'2 TNEQ. lia. }\n    apply lt_max_of_list_r in LT'. desf. in_simp.\n    unfold props_before, proj1_sig in LT'1. do 2 desf. clear Heq.\n    apply a0 in LT'1. desf. clear dependent x0.\n    assert (acts G x) as EX.\n    { eapply tslot_defined_only_for_E; eauto. }\n    assert (is_w x) as WX.\n    { eapply tslot_defined_only_for_w; eauto. }\n    assert (co G w x) as CO.\n    { rewrite co_ts; unfold loc; splits; ins; try congruence.\n      rewrite R. simpls. }\n    assert (safepoints x (nu n)) as SFXN.\n    { eapply tslot_gt_is_safepoint; eauto. lia. }\n    assert (is_w x) as WY.\n    { eapply tslot_defined_only_for_w; eauto. }\n    apply SFXN. exists (nu n). apply seq_eqv_r. splits; eauto.\n    destruct (classic (nu n = x)) as [|NEQ]; auto. left.\n    destruct (classic (is_w (nu n))).\n    2: by rewrite <- rf_tsE with (x:=w) (y:=nu n).\n    assert (ev_ts (nu n) <> ev_ts x) as TNEQ.\n    { intros HH. apply NEQ. apply ts_uniq; auto. }\n    rewrite <- rf_rmw_tsE with (x:=w) (y:=nu n); auto.\n    rewrite <- rf_rmw_tsE with (x:=w) (y:=nu n) in TNEQ; auto.\n    lia.\n  Qed.\n\n  Lemma scoh_view'_load n\n        (LT : lt_size n (acts G \\₁ is_init)) thread index x v\n        (N : nu n = ThreadEvent thread index (Aload x v))\n        w (RF : rf G w (nu n)) :\n    scoh_view' n thread x <= ev_ts w.\n  Proof.\n    rewrite <- scoh_view'_r; eauto.\n    rewrite N; ins.\n  Qed.\n\n  Lemma scoh_view_r n\n        (LT : lt_size n (acts G \\₁ is_init))\n        w (RF : rf G w (nu n)) :\n    scoh_view n (tid (nu n)) (loc (nu n)) <= ev_ts w.\n  Proof.\n    unfold scoh_view, view_join.\n    apply Max.max_lub.\n    { apply scoh_view'_r; auto. }\n    set (TT:=ENUM). apply enumeratesE in TT. desf.\n    assert (~ is_init (nu n)) as NINITN.\n    { intros HH. apply rf_init_r in RF; auto. }\n    assert (R := RF).\n    apply (wf_rfE WF) in RF; unfolder in RF; desc.\n    apply (wf_rfD WF) in RF0; unfolder in RF0; desc.\n    apply (wf_rfl WF) in R; red in R; unfold loc in *; ins.\n    apply Nat.nlt_ge. intros LT'.\n    apply lt_max_of_list_r in LT'. desf. in_simp.\n    unfold props_before, proj1_sig in LT'1. do 2 desf. clear Heq.\n    apply a0 in LT'1. desf. clear dependent x0.\n    assert (acts G x) as EX.\n    { eapply tslot_defined_only_for_E; eauto. }\n    assert (is_w x) as WX.\n    { eapply tslot_defined_only_for_w; eauto. }\n    assert (co G w x) as CO.\n    { rewrite co_ts; unfold loc; splits; ins; try congruence. }\n    assert (safepoints x (nu n)) as SFXN.\n    { eapply tslot_gt_is_safepoint; eauto. }\n    assert (is_w x) as WY.\n    { eapply tslot_defined_only_for_w; eauto. }\n    apply SFXN. exists (nu n). apply seq_eqv_r. splits; eauto.\n    destruct (classic (nu n = x)) as [|NEQ]; auto. left.\n    destruct (classic (is_w (nu n))).\n    2: by rewrite <- rf_tsE with (x:=w) (y:=nu n).\n    assert (ev_ts (nu n) <> ev_ts x) as TNEQ.\n    { intros HH. apply NEQ. apply ts_uniq; auto. }\n    rewrite <- rf_rmw_tsE with (x:=w) (y:=nu n); auto.\n    rewrite <- rf_rmw_tsE with (x:=w) (y:=nu n) in TNEQ; auto.\n    lia.\n  Qed.\n\n  Lemma scoh_view_load n\n        (LT : lt_size n (acts G \\₁ is_init)) thread index x v\n        (N : nu n = ThreadEvent thread index (Aload x v))\n        w (RF : rf G w (nu n)) :\n    scoh_view n thread x <= ev_ts w.\n  Proof.\n    rewrite <- scoh_view_r; eauto.\n    rewrite N; ins.\n  Qed.\n\n  Lemma view_le_scoh_ev' n (LT :  lt_size n (acts G \\₁ is_init)) :\n    view_le (scoh_view' n (tid (nu n))) (ev_view_full (nu n)).\n  Proof.\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    assert (NIn: ~ is_init (nu n)) by (apply RNG; ins).\n    intro x.\n    unfold scoh_view', view_join.\n    apply Nat.max_lub.\n    2: { apply le_max_of_list_l. ins. in_simp.\n         unfold props_before, proj1_sig in *. do 2 desf. clear Heq.\n         unfold ev_view_full. unfold view_join.\n         etransitivity; [|by apply Nat.le_max_r].\n         unfold ev_view_prop. apply in_max_of_list. in_simp. exists x0.\n         splits; auto.\n         apply a0 in H0. clear dependent x. desf.\n         in_simp. splits; auto. unfold props_before, proj1_sig. do 2 desf. clear Heq.\n         apply a0. clear dependent x. splits; auto.\n         exists m. splits; auto. rewrite nu_inv_nu; auto. lia. }\n    destruct (exists_max (fun x => tid (nu x) = tid (nu n)) n) as [MAX|]; desc.\n    { unfold scoh_view'.\n      replace (filterP _ _) with (@nil Event); ins.\n      { forward apply ev_viewI with (x := nu n) (l := x) as X; desc; eauto.\n        lia. }\n      symmetry; rewrite filterP_eq_nil; ins; in_simp.\n      eapply MAX; eauto. }\n    unfold scoh_view.\n    rewrite view_joinlE, (seq_split0 H), map_app, filterP_app.\n    rewrite map_app, map_app, max_of_list_app;\n      ins; desf; ins; try congruence.\n    rewrite Nat.max_comm, <- Nat.max_assoc, <- max_of_list_app.\n    rewrite Nat.max_l; ins.\n    { eapply sb_view_fullE. apply sb_nu; eauto using lt_lt_size.\n      splits; auto. apply sb_nu_alt; auto. eapply lt_lt_size; eauto. }\n    rewrite le_max_of_list_l; ins; in_simp.\n    rewrite in_app_iff in *; desf; in_simp.\n    { edestruct H1 with (j := x0); try lia. }\n    apply sb_view_fullE; eauto using lt_lt_size.\n    apply sb_nu; eauto using lt_lt_size.\n    split.\n    { etransitivity; eauto. }\n    apply sb_nu_alt; eauto using lt_lt_size.\n    etransitivity; eauto.\n  Qed.\n\n  Lemma view_le_scoh_ev n (LT :  lt_size n (acts G \\₁ is_init)) :\n    view_le (scoh_view n (tid (nu n))) (ev_view_full (nu n)).\n  Proof.\n    unfold scoh_view. apply view_join_lub.\n    { by apply view_le_scoh_ev'. }\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    assert (NIn: ~ is_init (nu n)) by (apply RNG; ins).\n    intro x.\n    apply le_max_of_list_l. ins. in_simp.\n    unfold props_before, proj1_sig in *. do 2 desf. clear Heq.\n    unfold ev_view_full. unfold view_join.\n    etransitivity; [|by apply Nat.le_max_r].\n    unfold ev_view_prop. apply in_max_of_list. in_simp. exists x0.\n    splits; auto.\n    apply a0 in H0. clear dependent x. desf.\n    in_simp. splits; auto. unfold props_before, proj1_sig. do 2 desf. clear Heq.\n    apply a0. clear dependent x. splits; auto.\n    exists m. splits; auto. rewrite nu_inv_nu; auto.\n  Qed.\n\n  Lemma scoh_view_sb l n pn (SB : sb G pn (nu n))\n        (LTN : lt_size n (acts G \\₁ is_init)) :\n    ev_view_full pn l <= scoh_view n (tid (nu n)) l.\n  Proof using IMPL.\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    ins.\n    set (AA:=SB). apply sb_tid_init in AA. desf.\n    2: { destruct pn; ins. rewrite ev_view_full_init. lia. }\n    eapply Nat.le_trans, Nat.le_max_l.\n    unfold scoh_view'. eapply Nat.le_trans, Nat.le_max_l.\n    rewrite view_joinlE. apply in_max_of_list.\n    do 2 (in_simp; eexists; splits; eauto).\n    in_simp. splits; auto.\n    assert (acts G (nu n) /\\ ~ is_init (nu n)) as [EN NN] by (by apply RNG).\n    assert (tid (nu n) <> 0) as NNN.\n    { intros HH. apply NN. eapply wf_tid_init; eauto. }\n    assert (~ is_init pn) as NINITPN.\n    { intros BB. destruct pn; ins. eauto. }\n    apply wf_sbE in SB. unfolder in SB. desf.\n    edestruct (SUR pn).\n    { by split. }\n    desf. eexists; split; eauto. apply in_seq0_iff.\n    apply IMPL; auto. by apply sb_in_hb.\n  Qed.\n\n  Lemma ev_view_w n (LT :  lt_size n (acts G \\₁ is_init))\n        (NR: ~ is_r (nu n)) :\n    ev_view_full (nu n) =\n    upd (scoh_view n (tid (nu n)))\n        (loc (nu n)) (ev_ts (nu n)).\n  Proof.\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    assert (NIn: ~ is_init (nu n)) by (apply RNG; ins).\n    assert (Wn: is_w (nu n))\n      by (destruct (nu n); ins; destruct l; ins).\n    extensionality x.\n    unfold upd; desf.\n    { apply ev_view_full_loc_w; auto. }\n    apply Nat.le_antisymm.\n    2: by apply view_le_scoh_ev.\n    unfold scoh_view, view_join.\n    unfold ev_view_full at 1, view_join at 1.\n    apply Max.max_lub.\n    2: { unfold ev_view_prop.\n         unfold scoh_view, view_join.\n         etransitivity; [|by apply Nat.le_max_r].\n         rewrite nu_inv_nu; auto. }\n    destruct ev_viewI with (x := nu n) (l := x) as [i I]; desf; auto.\n    rewrite <- I3.\n    destruct I2 as [pn [[RF|RF] [SB|SB]]]; subst.\n    { desf. }\n    2: { exfalso. apply (wf_rfD WF) in RF. unfolder in RF. desf. }\n    2: { transitivity (ev_view_full pn (loc i)).\n         2: by apply scoh_view_sb.\n         apply ev_view_full_includes; auto.\n         generalize RF. basic_solver 10. }\n    transitivity (ev_view_full pn (loc pn)).\n    2: by apply scoh_view_sb.\n    unfold ev_view_full, view_join.\n    eapply Nat.le_trans, Nat.le_max_l.\n    rewrite ev_view_loc; auto.\n  Qed.\n\n  Lemma ev_view_r n (LT :  lt_size n (acts G \\₁ is_init))\n        w (RF: rf G w (nu n)) :\n    ev_view_full (nu n) =\n    upd (scoh_view n (tid (nu n)))\n        (loc (nu n)) (ev_ts (nu n)).\n  Proof.\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    assert (NIn: ~ is_init (nu n)) by (apply RNG; ins).\n    extensionality x.\n    apply (wf_rfE WF) in RF; unfolder in RF; desf.\n    apply (wf_rfD WF) in RF0; unfolder in RF0; desf.\n    assert (hb G w (nu n)) as HB.\n    { by apply rf_in_hb. }\n    apply Nat.le_antisymm.\n    2: { unfold view_join, upd; desf.\n         { rewrite ev_view_full_loc; auto. }\n           by eapply view_le_scoh_ev. }\n    unfold view_join, upd; desf.\n    { rewrite ev_view_full_loc; auto with arith; apply RNG. }\n    unfold ev_view_full at 1, view_join at 1.\n    apply Max.max_lub.\n    2: { unfold ev_view_prop.\n         unfold scoh_view, view_join.\n         etransitivity; [|by apply Nat.le_max_r].\n         rewrite nu_inv_nu; auto. }\n    destruct ev_viewI with (x := nu n) (l := x) as [i I]; desf; auto.\n    rewrite <- I3.\n    rename RF into RFG.\n    destruct I2 as [pn [[RF|RF] [SB|SB]]]; subst.\n    { desf. }\n    2: { assert (i = w); subst.\n         { eapply wf_rff; eauto. }\n         exfalso. apply (wf_rfl WF) in RF. apply n0 in RF. desf. }\n    2: { transitivity (ev_view_full pn (loc i)).\n         2: by apply scoh_view_sb.\n         apply ev_view_full_includes; auto.\n         generalize RF. basic_solver 10. }\n    transitivity (ev_view_full pn (loc pn)).\n    2: by apply scoh_view_sb.\n    unfold ev_view_full, view_join.\n    eapply Nat.le_trans, Nat.le_max_l.\n    rewrite ev_view_loc; auto.\n  Qed.\n\n  Lemma scoh_view_S n (LT : lt_size n (acts G \\₁ is_init)):\n    scoh_view' (S n) = upd (scoh_view n) (tid (nu n)) (ev_view_full (nu n)).\n  Proof.\n    extensionality t; extensionality l; unfold scoh_view, upd; desf.\n    2: { unfold scoh_view' at 1. unfold view_join; ins.\n         assert (view_joinl\n                    (map ev_view_full\n                         (filterP (fun x : Event => tid x = t) (map nu (List.seq 0 (S n)))))\n                    l =\n                 view_joinl\n                    (map ev_view_full\n                         (filterP (fun x : Event => tid x = t) (map nu (List.seq 0 n))))\n                    l) as AA.\n         { rewrite !view_joinlE.\n           apply Nat.le_antisymm.\n           all: apply incl_max_of_list; red; ins; in_simp.\n           all: do 2 (eexists; splits; eauto; in_simp).\n           all: splits; eauto.\n           all: eexists; splits; eauto.\n           all: apply in_seq0_iff; try lia.\n           destruct (classic (x = n)); [exfalso; desf|lia]. }\n         rewrite AA.\n         apply Nat.le_antisymm.\n         all: apply Nat.max_lub.\n         all: try by apply Nat.le_max_r.\n         { etransitivity; [|by apply Nat.le_max_l].\n           unfold scoh_view'. by apply Nat.le_max_l. }\n         unfold scoh_view'. apply Nat.max_lub.\n         { by apply Nat.le_max_l. }\n         etransitivity; [|by apply Nat.le_max_r].\n         apply incl_max_of_list; red; ins; in_simp.\n         do 2 (eexists; splits; eauto; in_simp).\n         eapply props_before_index_mon; [|by eauto]. lia. }\n    apply Nat.le_antisymm.\n    { unfold scoh_view', view_join; ins.\n      apply Nat.max_lub.\n      2: { unfold ev_view_full, view_join.\n           etransitivity; [|by apply Nat.le_max_r].\n           unfold ev_view_prop. rewrite nu_inv_nu; auto. }\n      eapply view_le_joinl_l; ins; in_simp.\n      destruct (classic (x = n)); subst.\n      { by apply view_le_refl. }\n      apply sb_view_fullE.\n      assert (x < n) by lia.\n      apply sb_nu_lt; splits; auto.\n      eapply lt_lt_size; eauto. }\n    unfold scoh_view', view_join.\n    etransitivity; [|by apply Nat.le_max_l].\n    rewrite view_joinlE. apply in_max_of_list.\n    do 2 (in_simp; eexists; splits; eauto).\n    in_simp; splits; eauto. eexists; splits; eauto.\n    apply in_seq0_iff. lia.\n  Qed.\n\n  Definition scoh_state' (n : nat) : State :=\n    (scoh_mem n, scoh_view' n).\n\n  Definition lab_of_ev e :=\n    match e with\n    | ThreadEvent t i (Aload x v) =>\n      SCOH_event (ThreadEvent t i (Aload x v)) (ev_ts e) (ev_view_full e)\n    | ThreadEvent t i lab =>\n      SCOH_event (ThreadEvent t i lab) (Nat.pred (ev_ts e)) (ev_view_full e)\n    | InitEvent _ => deflabel\n    end.\n\n  Lemma scoh_step_all' n (LT: lt_size n (acts G \\₁ is_init)) :\n    SCOH_step (scoh_state n) (lab_of_ev (nu n)) (scoh_state' (S n)).\n  Proof.\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    assert (acts G (nu n)) as ACTSN.\n    { apply RNG; auto. }\n    destruct (nu n) eqn: N; ins.\n    { specialize (RNG _ LT); rewrite N in *; red in RNG; ins; desf. }\n    destruct l; ins.\n    { destruct (COMPL (x := nu n)) as [w RF].\n      split; [apply (proj1 (enumeratesE _ _) ENUM); ins| rewrite N; ins].\n      rewrite <- rf_tsE with (x := w); eauto.\n      2: by rewrite <- N; ins.\n      eapply SCOHstep_read with (view := ev_view_full w);\n        try rewrite scoh_view_S, N; ins.\n      { assert (is_init w \\/ exists m, m < n /\\ w = nu m).\n        { apply (wf_rfE WF) in RF; unfolder in RF; desf.\n          assert (X := proj1 (enumeratesE _ _) ENUM); desc.\n          classical_right.\n          specialize (SUR w); specialize_full SUR; ins; desf.\n          eexists; split; ins; eapply IMPL; ins; apply t_step; vauto. }\n        rewrite N in *.\n        assert (L := wf_rfl WF _ _ RF); unfold same_loc, loc in *; ins; clarify.\n        assert (V := wf_rfv WF _ _ RF); unfold valw, valr in *; ins; clarify.\n        apply (wf_rfD WF) in RF; unfolder in RF; desc.\n        desf; [left; red; ins | right; exists m; ins; splits; desf ].\n        destruct w; ins; rewrite ev_ts_init, ev_view_full_init; ins. }\n      { eapply scoh_view_load; eauto; congruence. }\n      { unfold scoh_mem; apply set_extensionality.\n        apply (wf_rfD WF) in RF; unfolder in RF; desc.\n        rewrite set_bunion_lt_S, N; ins; desf; rels. }\n      2: { rewrite scoh_view_S; auto. rewrite N. ins. }\n      rewrite <- N in *.\n      erewrite ev_view_r; eauto.\n      f_equal; try solve [rewrite N; unfold loc; ins].\n      symmetry. apply rf_tsE; auto.\n      unfold is_w, is_w_l. rewrite N. desf. }\n    { assert (Wn : is_w (nu n)) by (rewrite N; ins).\n      assert (ev_ts (nu n) <> 0) as NUNTNZ.\n      { apply ev_ts_nzero; auto. }\n      eapply SCOHstep_write; ins;\n        try rewrite scoh_view_S, N; ins.\n      all: try rewrite Nat.succ_pred;\n        try rewrite <- N; eauto using ev_ts_nzero.\n      { rewrite ev_view_w, N; ins; rewrite N; ins. }\n      { unfold scoh_view, view_join.\n        apply Nat.max_lub_lt.\n        (* TODO: a lot of repetion below. *)\n        2: { apply lt_max_of_list_l. split.\n             { apply ev_ts_nzero; auto. }\n             ins. in_simp. unfold props_before, proj1_sig in *. do 2 desf. clear Heq.\n             apply a0 in H0. desf. clear dependent x.\n             assert (is_w x0) as WX0 by (eapply tslot_defined_only_for_w; eauto).\n             assert (acts G x0) as ACTSX0.\n             { eapply tslot_defined_only_for_E; eauto. }\n             eapply tslot_gt_is_safepoint in H1; eauto.\n             2: by rewrite N; ins.\n             apply Nat.nle_gt. intros LE.\n             apply le_lt_or_eq in LE. destruct LE as [LTT|EQ].\n             2: { apply ts_uniq in EQ; auto; try by rewrite N; ins. desf.\n                  eapply safepoints_irr; eauto. }\n             apply H1. exists (nu n). unfolder. ins. splits; eauto.\n             rewrite N. ins. }\n        unfold scoh_view'. apply Nat.max_lub_lt.\n        2: { apply lt_max_of_list_l. split; auto.\n             ins. in_simp. unfold props_before, proj1_sig in *. do 2 desf. clear Heq.\n             apply a0 in H0. desf. clear dependent x.\n             assert (is_w x0) as WX0 by (eapply tslot_defined_only_for_w; eauto).\n             assert (acts G x0) as ACTSX0.\n             { eapply tslot_defined_only_for_E; eauto. }\n             eapply tslot_gt_is_safepoint in H0; eauto.\n             3: lia.\n             2: by rewrite N; ins.\n             apply Nat.nle_gt. intros LE.\n             apply le_lt_or_eq in LE. destruct LE as [LTT|EQ].\n             2: { apply ts_uniq in EQ; auto; try by rewrite N; ins. desf.\n                  eapply safepoints_irr; eauto. }\n             apply H0. exists (nu n). unfolder. ins. splits; eauto.\n             rewrite N. ins. }\n        rewrite view_joinlE.\n        rewrite lt_max_of_list_l; split;\n          eauto using ev_ts_nzero; ins; in_simp.\n        (* forward eapply hb_from_sb_nu as HB'; eauto. *)\n        (* { rewrite N; unfold tid; desf. } *)\n        unfold ev_view_full, view_join. apply Nat.max_lub_lt.\n        2: { unfold ev_view_prop. apply lt_max_of_list_l; splits; auto.\n             ins. in_simp. rewrite nu_inv_nu in *; auto.\n             2: eby eapply lt_lt_size.\n             unfold props_before, proj1_sig in *. do 2 desf. clear Heq.\n             apply a0 in H1. desf. clear dependent x.\n             assert (acts G x1) as EX1 by (eapply tslot_defined_only_for_E; eauto).\n             assert (is_w x1) as WX1 by (eapply tslot_defined_only_for_w; eauto).\n             eapply tslot_gt_is_safepoint in H1; eauto.\n             3: lia.\n             2: by rewrite N; ins.\n             apply Nat.nle_gt. intros LE.\n             apply le_lt_or_eq in LE. destruct LE as [LTT|EQ].\n             2: { apply ts_uniq in EQ; auto; try by rewrite N; ins. desf.\n                  eapply safepoints_irr; eauto. }\n             apply H1. exists (nu n). unfolder. splits; eauto.\n             rewrite N. ins. }\n        assert (LTS0 : lt_size x0 (acts G \\₁ is_init)) by eauto using lt_lt_size.\n        assert (TX0  : tid (nu x0) = tid (nu n)) by (by rewrite N; unfold tid; desf).\n        assert (SB' : sb G (nu x0) (nu n)).\n        { apply sb_nu; eauto. split; auto.\n          apply sb_nu_alt; auto. }\n        unfold ev_view, proj1_sig; desf. clear Heq.\n        rewrite lt_max_of_list_l; split; auto.\n        ins; in_simp.\n        apply a0 in H1. desf. clear dependent x1.\n        destruct (classic (x2 = nu n)) as [|NEQ]; desf.\n        { exfalso.\n          apply rfsb_in_hb in H1. destruct H1 as [AA|AA].\n          { rewrite AA in SB'. eapply sb_irr; eauto. }\n          eapply hb_irr; eauto. apply ct_ct; eexists. split; eauto.\n          apply sb_in_hb; eauto. }\n        assert (HB : hb G x2 (nu n)).\n        { apply rfsb_in_hb in H1. destruct H1 as [AA|AA]; subst; auto.\n          { by apply sb_in_hb. }\n          apply ct_ct. eexists; split; eauto.\n            by apply sb_in_hb. }\n        apply wf_hbE in HB; auto. unfolder in HB. desf.\n        eapply wf_co_total in NEQ; eauto.\n        all: unfolder; splits; ins; eauto;\n          try solve [rewrite N; ins].\n        desf; eauto using co_tsE.\n        exfalso. eapply co_rfsb; [by apply CONS|].\n        eexists; split; eauto.\n        apply rfsb_sb. apply seqA. eexists; eauto. }\n      { unfold scoh_mem; apply set_extensionality.\n        rewrite set_bunion_lt_S, N; ins; desf; rels.\n        rewrite <- set_unionA; apply set_equiv_union; ins.\n        unfold msg_of; rewrite N; unfold loc, valw; ins. }\n      assert (X := ENUM); apply enumeratesE in X; desc.\n      unfold fresh_tstamp, scoh_mem, Minit, msg_of; unfolder; red; ins; desf.\n      eapply ev_ts_nzero; eauto.\n      apply ts_uniq in H2; ins; try apply RNG; eauto using lt_lt_size.\n      unfold ev_ts in *; desf.\n      apply INJ in H2; ins; desf; eauto using lt_lt_size; lia.\n      rewrite N; ins. }\n    unfold scoh_mem.\n    assert (Wn : is_w (nu n)) by (rewrite N; ins).\n    destruct (COMPL (x := nu n)) as [w RF].\n    split; [apply (proj1 (enumeratesE _ _) ENUM); ins| rewrite N; ins].\n    forward apply rf_rmw_tsE as TS; eauto.\n    eapply SCOHstep_rmw with (view := ev_view_full w); ins;\n      try rewrite scoh_view_S, N; ins.\n    all: try rewrite Nat.succ_pred;\n      try rewrite <- N; eauto using ev_ts_nzero.\n    { assert (L := wf_rfl WF _ _ RF); unfold same_loc, loc in *; ins; clarify.\n      assert (V := wf_rfv WF _ _ RF); unfold valw, valr in *; ins; clarify.\n      apply (wf_rfE WF) in RF; unfolder in RF; desf.\n      apply (wf_rfD WF) in RF0; unfolder in RF0; desf.\n      assert (is_init w \\/ exists m, m < n /\\ w = nu m).\n      { assert (X := proj1 (enumeratesE _ _) ENUM); desc.\n        classical_right.\n        specialize (SUR w); specialize_full SUR; ins; desf.\n        eexists; split; ins; eapply IMPL; ins; apply t_step; vauto. }\n      rewrite N in *.\n      desf; [left; red; ins | right; exists m; splits; ins; desf ].\n      destruct w; ins; rewrite ev_ts_init, ev_view_full_init in *.\n      all: rewrite <- TS; ins. }\n    { rewrite <- TS; ins.\n      forward eapply scoh_view_r; eauto.\n      rewrite N; ins. }\n    { erewrite ev_view_r with (w := w); eauto.\n      f_equal; f_equal; rewrite N; ins. }\n    { unfold scoh_mem; apply set_extensionality.\n      rewrite set_bunion_lt_S, N; ins; desf; rels.\n      rewrite <- set_unionA; apply set_equiv_union; ins.\n      unfold msg_of; rewrite N; unfold loc, valw; ins. }\n    clear TS.\n    assert (X := ENUM); apply enumeratesE in X; desc.\n    unfold fresh_tstamp, scoh_mem, Minit, msg_of; unfolder; red; ins; desf.\n    eapply ev_ts_nzero; eauto.\n    apply ts_uniq in H2; ins; try apply RNG; eauto using lt_lt_size.\n    unfold ev_ts in *; desf.\n    apply INJ in H2; ins; desf; eauto using lt_lt_size; lia.\n    rewrite N; ins.\n  Qed.\n\n  Definition SCOH_step_no_lbl_gen (l : SCOH_label) (a b : State) :=\n    exists w t x v tstamp view view',\n      << TBT   : t <> 0 /\\ exists e, acts G e /\\ t = tid e >> /\\\n      << LBL   : l = SCOH_internal t x tstamp >> /\\\n      << EW    : acts G w >> /\\\n      << NINIT : ~ is_init w >> /\\\n      << WW    : is_w w >> /\\\n      << ST    : tstamp = ev_ts w >> /\\\n      << SV    : v = valw w >> /\\\n      << INMEM : fst a (Msg x v tstamp view) >> /\\\n      << LTX   : snd a t x < tstamp >> /\\\n      << SMMEM : fst b = fst a >> /\\\n      << NVIEW : view' = upd (snd a t) x tstamp >> /\\\n      << NST   : snd b = upd (snd a) t view' >>.\n  \n  Definition SCOH_step_no_lbl (a b : State) :=\n    exists l, SCOH_step_no_lbl_gen l a b.\n  \n  Lemma SCOH_step_no_lbl_same_mem : SCOH_step_no_lbl ⊆ fst ↓ eq.\n  Proof. unfold SCOH_step_no_lbl, SCOH_step_no_lbl_gen. unfolder. ins. desf. Qed.\n\n  Lemma SCOH_steps_no_lbl_same_mem : SCOH_step_no_lbl^* ⊆ fst ↓ eq.\n  Proof.\n    apply inclusion_rt_ind.\n    { basic_solver. }\n    { by apply SCOH_step_no_lbl_same_mem. }\n    unfolder. intros x y z HH AA. by rewrite HH.\n  Qed.\n  \n  Lemma SCOH_steps_view_mono t :\n    (fun a b => exists l, SCOH_step a l b)^* ⊆ (fun x => snd x t) ↓ view_le.\n  Proof.\n    apply inclusion_rt_ind.\n    { basic_solver. }\n    { unfolder. ins. desf. eapply SCOH_step_view_mono; eauto. }\n    unfolder. intros x y z HH AA.\n    eapply view_le_trans; eauto.\n  Qed.\n\n  Lemma scoh_props_steps_gen n (LT: lt_size n (acts G \\₁ is_init))\n        ram rav tslotlist\n        (TSD : forall t w (IN : In (t, w) tslotlist),\n            acts G w /\\ ~ is_init w /\\ is_w w /\\\n            t <> 0 /\\ (exists e, acts G e /\\ t = tid e) /\\ \n            exists view,\n              ram (Msg (loc w) (valw w) (ev_ts w) view)) :\n    SCOH_step_no_lbl＊\n      (ram, rav)\n      (ram, fun t => view_join\n                       (rav t)\n                       (fun l =>\n                          max_of_list\n                            (map (fun x => ev_ts (snd x))\n                                 (filterP (fun tw => loc (snd tw) = l /\\ fst tw = t)\n                                          tslotlist)))).\n  Proof.\n    induction tslotlist; ins.\n    { arewrite (rav = fun t : Tid => view_join (rav t) (fun _ : Loc => 0)) at 1.\n      2: by apply rt_refl.\n      extensionality l. by rewrite view_join_0_r. }\n    destruct a as [t w]. ins.\n    match goal with\n    | |- SCOH_step_no_lbl＊ (ram, rav) (ram, ?X) => set (Y:=X)\n    end.\n    match goal with\n    | H: _ -> SCOH_step_no_lbl＊ (ram, rav) (ram, ?X) |- _ => set (Z:=X)\n    end.\n    assert (SCOH_step_no_lbl＊ (ram, rav) (ram, Z)) as HH.\n    { apply IHtslotlist. ins. eapply TSD; eauto. }\n    clear IHtslotlist.\n    destruct (le_lt_dec (ev_ts w) (Z t (loc w))) as [LE|LTT].\n    { arewrite (Y = Z); auto. extensionality t'. extensionality l'.\n      unfold Z, Y, view_join. do 2 desf. ins.\n      rewrite Nat.max_comm with (n := ev_ts w).\n      rewrite Nat.max_assoc.\n      rewrite Nat.max_l; auto. }\n    apply rt_end. right. exists (ram, Z). splits; auto.\n    edestruct (TSD t w); eauto. desf.\n    red. eexists. exists w, (tid e), (loc w), (valw w), (ev_ts w). do 2 eexists.\n    splits; eauto.\n    extensionality t'. extensionality l'; ins.\n    unfold upd. do 2 desf.\n    all: try by unfold Y, view_join; do 2 desf.\n    unfold Y, view_join. do 2 desf.\n    2: { exfalso. apply n0. desf. }\n    ins.\n    rewrite Nat.max_comm with (n := ev_ts w).\n    rewrite Nat.max_assoc.\n    rewrite Nat.max_r; auto. unfold Z, view_join in LTT. lia.\n  Qed.\n\n  Lemma scoh_props_steps n (LT: lt_size n (acts G \\₁ is_init)) :\n    SCOH_step_no_lbl＊ (scoh_state' (S n)) (scoh_state (S n)).\n  Proof.\n    set (s:=fun tw => Some n = tslot (fst tw) (snd tw)).\n    assert (set_finite s) as SF by apply tslot_dom_finite.\n    apply set_finiteE in SF. desf.\n    unfold scoh_state, scoh_state', scoh_view.\n    pose (scoh_props_steps_gen LT (scoh_mem (S n)) (scoh_view' (S n)) findom) as HH.\n    match goal with\n    | |- SCOH_step_no_lbl＊ (_, _) (_, ?X) => set (Y:=X)\n    end.\n    match goal with\n    | H: _ -> SCOH_step_no_lbl＊ (_, _) (_, ?X) |- _ => set (Z:=X)\n    end.\n    arewrite (Y = Z).\n    2: { apply HH. ins. apply SF0 in IN. unfold s in *. ins.\n         unfold scoh_mem.\n         assert (acts G w) as EW.\n         { eapply tslot_defined_only_for_E; eauto. }\n         assert (is_w w) as WW.\n         { eapply tslot_defined_only_for_w; eauto. }\n         assert (~ is_init w) as NINITW.\n         { eapply tslot_defined_only_for_non_init_e; eauto. }\n         splits; auto.\n         { eapply tslot_defined_only_for_non_init; eauto. }\n         { apply tslot_defined_only_for_non_empty_threads in IN. desf. eauto. }\n         set (AA:=IN). apply tslot_lt_index in AA.\n         eexists. right. exists (nu_inv w). splits.\n         { lia. }\n         unfold msg_of.\n         rewrite nu_nu_inv; auto. desf. }\n    extensionality t. extensionality l.\n    unfold Y, Z, view_join.\n    apply Nat.le_antisymm; apply Nat.max_lub.\n    all: try by apply Nat.le_max_l.\n    2: { etransitivity; [|by apply Nat.le_max_r].\n         apply incl_max_of_list. red. ins. in_simp.\n         eexists. splits; eauto. in_simp. splits; auto.\n         unfold props_before, proj1_sig. do 2 desf. clear Heq.\n         apply a0. clear dependent x0. apply SF0 in H0. red in H0.\n         eexists. splits; eauto. }\n    (* TODO: generalize to a lemma? *)\n    unfold scoh_view', view_join. rewrite <- Nat.max_assoc.\n    etransitivity; [|by apply Nat.le_max_r].\n    apply le_max_of_list_l. ins. in_simp.\n    unfold props_before, proj1_sig in *. do 2 desf. clear Heq Heq0.\n    apply a2 in H0. desf.\n    destruct (classic (m = n)); subst.\n    { etransitivity; [|by apply Nat.le_max_r].\n      apply in_max_of_list. in_simp. exists (t, x). splits; eauto.\n      in_simp. splits; auto. apply SF0. red. ins. }\n    etransitivity; [|by apply Nat.le_max_l].\n    apply in_max_of_list. in_simp. exists x. splits; eauto.\n    in_simp. splits; auto. apply a1. exists m. splits; auto. lia.\n  Qed.\n\n  Lemma scoh_step_all n (LT: lt_size n (acts G \\₁ is_init)) :\n    ((fun x => SCOH_step x (lab_of_ev (nu n))) ⨾ SCOH_step_no_lbl＊) \n                                             (scoh_state n)  (scoh_state (S n)).\n  Proof.\n    eexists. split.\n    { by apply scoh_step_all'. }\n      by apply scoh_props_steps.\n  Qed.\n\nEnd DECL_to_OP.\n\n\nLemma proj_ev_lab_of_ev (G : execution) (WF : Wf G) (FAIR : mem_fair G) RFC CONS\n      nu (ENUM : enumerates nu (acts G \\₁ is_init))\n      n (LT : lt_size n (acts G \\₁ is_init))\n      (THRB : set_finite (fun t => exists x, acts G x /\\ t = tid x)) :\n  proj_ev (lab_of_ev WF ENUM RFC CONS FAIR THRB (nu n)) = (nu n).\nProof.\n  unfold lab_of_ev; desf; ins.\n  apply enumeratesE in ENUM; desc.\n  specialize (RNG _ LT); red in RNG; desc; rewrite Heq in *; ins.\nQed.\n\n\nLemma SCOH_decl_implies_op G\n      (WF : Wf G) (FAIR: mem_fair G)\n      (RFC : rf_complete G)\n      (CONS: scoh_consistent G)\n      (THRB : set_finite (fun t => exists x, acts G x /\\ t = tid x)) :\n  exists s t,\n    LTS_trace_param scoh_lts s t  /\\\n    run_fair s t /\\\n    trace_elems (trproj t) ≡₁ acts G \\₁ is_init /\\\n    trace_wf (trproj t).\nProof.\n  assert (IRRhb: irreflexive (hb G)) by (by apply CONS).\n  assert (B: bounded_threads G).\n  { by apply BOUND. }\n\n  assert (dom_rel (lt ⨾ ⦗fun n => lt_size n (acts G \\₁ is_init)⦘) ⊆₁\n                  (fun n => lt_size n (acts G \\₁ is_init))) as LTCLOS.\n  { generalize (@lt_lt_size _ (acts G \\₁ is_init)). basic_solver. }\n\n  assert (forall l : SCOH_label, ~ SCOH_step_no_lbl_gen RFC FAIR l ≡ ∅₂ -> ~ is_external l)\n    as NLBLNEXT.\n  { ins. intros HH. red in HH. apply H. split.\n    2: basic_solver.\n    intros x y AA. cdes AA. desf. }\n  assert (forall l, SCOH_step_no_lbl_gen RFC FAIR l ⊆ (fun rl x y => SCOH_step x rl y) l)\n    as STEPINSTEP.\n  { unfolder. intros l x y S. cdes S. eapply SCOHstep_internal; eauto. }\n\n  forward eapply exec_exists_enum with (r := hb G) as (nu & ENUM & ORD);\n    eauto using fsupp_hb, has_finite_antichains_sb with hahn.\n\n  set (DD:=ENUM). apply enumeratesE in DD. desf. \n\n  assert ((fun n => lab_of_ev WF ENUM RFC CONS FAIR THRB (nu n))\n            ↑₁ (fun n => lt_size n (acts G \\₁ is_init)) ⊆₁ is_external) as LOELTS.\n  { intros x [y HH]. desf. red. unfold lab_of_ev. desf.\n    eapply RNG; eauto. red. desf. }\n\n  edestruct compacted_trace_exists with \n      (lab     := fun n => lab_of_ev WF ENUM RFC CONS FAIR THRB (nu n))\n      (labdom  := fun n => lt_size n (acts G \\₁ is_init))\n      (STEP    := fun rl : SCOH_label =>\n                    fun (x y : State) => SCOH_step x rl y)\n      (INTSTEP := SCOH_step_no_lbl_gen RFC FAIR)\n      (cstate  := scoh_state WF ENUM RFC CONS FAIR THRB) as [ct CT]; auto.\n  { ins. apply scoh_step_all; auto. }\n  edestruct ct2t_exists as [t CT2T]; eauto.\n  { apply deflabel. }\n  set (TT:=CT2T). unfold ct2t in TT.\n\n  assert (Sinit = ct2r ct 0) as SINIT.\n  { arewrite (0 = cti2ri ct 0). rewrite wf_cti2ri.\n    destruct (CT 0) as [AA]. desc. rewrite AA. ins.\n      by rewrite scoh_state_init. }\n\n  exists (ct2r ct).\n  assert (X := scoh_step_all WF ENUM ORD RFC).\n  tertium_non_datur (set_finite (acts G \\₁ is_init)) as [FIN|INF].\n  2: { exists (trace_inf t).\n       assert (trace_elems (trproj (trace_inf t)) ≡₁ acts G \\₁ is_init) as TETRP.\n       { unfold trproj. rewrite trace_elems_map, trace_elems_filter.\n         unfolder. split; intros x HH.\n         2: { apply SUR in HH. desf.\n              eexists. splits.\n              3: by eapply proj_ev_lab_of_ev; eauto.\n              2: { unfold lab_of_ev. desf.\n                   exfalso. apply RNG in HH. apply HH. by rewrite Heq. }\n              exists (cti2ri ct i).\n              edestruct (TT (cti2ri ct i)) as [XX YY].\n              { red. exists i. splits; auto.\n                enough (cti2ri ct i < cti2ri ct (1 + i)); [lia|].\n                apply cti2ri_S_mon. }\n              desf.\n              2: { exfalso. apply n. eauto. }\n              desf. rewrite YY. unfold proj1_sig. do 2 desf. clear Heq.\n              clear YY. apply cti2ri_inj in REP0; subst; eauto. }\n         desf. red in HH. desf.\n         edestruct (TT n) as [XX YY].\n         { red. exists n. splits; auto.\n           { by apply lt_size_infinite. }\n           apply cti2ri_lt_n. }\n         do 2 desf.\n         2: { cdes YY. rewrite LBL in HH1. inv HH1. }\n         rewrite YY. unfold proj1_sig. do 2 desf. clear Heq.\n         assert (lt_size x (acts G \\₁ is_init)) as QQ.\n         { by apply lt_size_infinite. }\n         rewrite proj_ev_lab_of_ev; auto. by apply RNG. }\n       assert (trace_length (trproj (trace_inf t)) = NOinfinity) as TLINF.\n       { unfold trace_length. desf. exfalso. apply INF. rewrite <- TETRP. exists l. ins. }\n       assert (forall i d, trace_nth i (trproj (trace_inf t)) d = nu i) as TNNU.\n       { intros i d. unfold trproj. \n         erewrite ct2t_infinite_filtered; eauto.\n         2: { split; [basic_solver|]. red. ins. by apply lt_size_infinite. }\n         ins. unfold proj_ev, lab_of_ev. desf.\n         exfalso. eapply RNG with (i:=i); eauto.\n         { by apply lt_size_infinite. }\n         red. desf. }\n       assert (trace_nodup (trproj (trace_inf t))) as TNDP.\n       { red. ins. rewrite !TNNU. intros HH. assert (i <> j) as AA by lia.\n         apply AA. apply INJ; auto. all: by apply lt_size_infinite. }\n       ins. splits; ins.\n       { ins. apply TT. red.\n         exists i. splits; auto.\n         { by apply lt_size_infinite. }\n         apply cti2ri_lt_n. }\n       2: { eapply trace_wf_helper; eauto.\n            ins. apply ORD; auto. by apply sb_in_hb. }\n       exists (fun t => exists x, acts G x /\\ ~ is_init x /\\ t = tid x). splits.\n       { eapply set_finite_mori.\n         2: by apply THRB.\n         red. basic_solver. }\n       { unfolder. ins. desf.\n         edestruct (TT n) as [XX YY].\n         { red. exists n. splits; auto.\n           { by apply lt_size_infinite. }\n           apply cti2ri_lt_n. }\n         unfold proj1_sig in *. do 2 desf.\n         { clear Heq. apply cti2ri_inj in REP; subst.\n           arewrite (tid_of (t (cti2ri ct x)) = tid (nu x)).\n           { rewrite YY. unfold lab_of_ev. desf. }\n           assert ((acts G \\₁ is_init) (nu x)) as [HH AA] by (by apply RNG).\n           eauto. }\n         cdes YY. rewrite LBL; ins; subst.\n         exists e. splits; auto. intros HH. apply TBT.\n         eapply wf_tid_init; eauto. }\n       intros i tid [e FF] l tstamp. desf.\n       destruct (classic\n                   (exists st', SCOH_step (ct2r ct i) (SCOH_internal (tid e) l tstamp) st'))\n         as [[st' ST]|NST].\n       2: { exists i. splits; auto. right. ins. apply NST. eauto. }\n       assert (compacted_trace_dom\n                 (fun n => lt_size n (acts G \\₁ is_init))\n                 ct i) as CTD.\n       { red. exists i. splits.\n         { apply lt_size_infinite; auto. }\n         enough (1 + i <= cti2ri ct (1 + i)); [lia|].\n         apply cti2ri_lt_n. }\n       edestruct wf_compacted_trace_dom with (i:=i) (ct:=ct) as [n HH]; eauto.\n       assert (exists n',\n                  i <= cti2ri ct n' /\\\n                  (internal_step (SCOH_step_no_lbl_gen RFC FAIR))^*\n                                                               (ct2r ct i) (ct2r ct (cti2ri ct n')))\n         as [n' [LL SS]].\n       { desf.\n         2: { eexists. splits; eauto. apply rt_refl. }\n         edestruct c2tr_trace_istep_helper with (i:=i) (n:=n) as [n']; eauto. }\n       clear dependent n. rename n' into n.\n       assert (fst (ct2r ct i) = fst (ct2r ct (cti2ri ct n))) as SMEM.\n       { eapply SCOH_steps_no_lbl_same_mem.\n         eapply clos_refl_trans_mori; [|by apply SS].\n           by unfold internal_step, SCOH_step_no_lbl. }\n       inv ST.\n       rewrite SMEM in *. rewrite wf_cti2ri in *.\n       assert (bs (ct n) = scoh_state WF ENUM RFC CONS FAIR THRB n) as AA by apply CT.\n       rewrite AA in *.\n       unfold scoh_state, scoh_mem in MSG. ins.\n       destruct MSG as [MSG|MSG].\n       { red in MSG. desf. ins. lia. }\n       red in MSG. desf. unfold msg_of in MSG0. inv MSG0. clear MSG0.\n       assert (lt_size y (acts G \\₁ is_init)) as LTY.\n       { by apply lt_size_infinite. }\n       edestruct tslot_defined with (t:=tid e) (w:=nu y) as [m HH]; eauto.\n       { intros HH. apply FF0. eapply wf_tid_init; eauto. }\n       1,2: by apply RNG.\n       assert\n         (ev_ts RFC FAIR (nu y) <= snd (ct2r ct (cti2ri ct (1 + m))) (tid e) (loc (nu y)))\n         as CC.\n       { rewrite wf_cti2ri. ins.\n         assert (bs (ct (S m)) =\n                 scoh_state WF ENUM RFC CONS FAIR THRB (S m)) as BB by apply CT.\n         rewrite BB. unfold scoh_state.\n         unfold scoh_view, view_join. ins.\n         etransitivity; [|by apply Max.le_max_r].\n         apply in_max_of_list. in_simp. exists (nu y). splits; auto.\n         in_simp. splits; auto. unfold props_before, proj1_sig. do 2 desf. clear Heq.\n         apply a0. eexists. splits; auto. eauto. }\n       exists (cti2ri ct (1 + m)). split.\n       2: { right. ins. inv STEP. lia. }\n       apply Nat.le_ngt. intros RR.\n       apply Nat.lt_le_incl in RR.\n       eapply ct2t_steps with (ct:=ct) in RR; eauto.\n       eapply SCOH_steps_view_mono with (t:=tid e) in RR.\n       enough (ev_ts RFC FAIR (nu y) <= snd (ct2r ct i) (tid e) (loc (nu y))); [lia|].\n       etransitivity; [by apply CC|]. by apply RR. }\n  apply set_finiteE in FIN. desc.\n  assert (forall i,\n             i < length findom <->\n             lt_size i (acts G \\₁ is_init)) as LTSG.\n  { ins. split; intros HH.\n    { exists findom. splits; auto.\n      ins. by apply FIN0. }\n    red in HH. desc.\n    enough (length dom <= length findom); [lia|].\n    apply NoDup_incl_length; auto.\n    red. ins. apply FIN0. by apply HH0. }\n  assert ((fun y => y < length findom) ⊆₁ (fun n => lt_size n (acts G \\₁ is_init))) as LTSGg.\n  { unfolder. ins. by apply LTSG. }\n  exists (trace_fin (map t (List.seq 0 (cti2ri ct (length findom))))).\n  ins. splits; ins.\n  { ins. rewrite nth_indep with (d':=t 0); auto.\n    rewrite map_nth, seq_nth; ins.\n    2: by rewrite map_length, seq_length in LLEN.\n    apply TT. red.\n    rewrite map_length, seq_length in LLEN.\n    edestruct wf_compacted_trace_dom with (i:=i) (ct:=ct) as [n]; eauto.\n    { red.\n      assert (0 < length findom) as NNIL.\n      { unfold cti2ri, cti2ri_helper in LLEN.\n        destruct findom; ins; lia. }\n      exists (Nat.pred (length findom)). splits.\n      { apply LTSG. lia. }\n      arewrite (1 + Nat.pred (length findom) = length findom) by lia.\n      lia. }\n    desf.\n    { exists n. splits; auto. }\n    exists (1 + n). splits; auto.\n    2: { apply lt_le_S. apply cti2ri_S_mon. }\n    apply LTSG. apply cti2ri_mon in LLEN. lia. }\n  { rewrite filterP_map, map_map.\n    unfolder. split; intros x HH.\n    2: { apply SUR in HH. desf.\n         edestruct (TT (cti2ri ct i)) as [XX YY].\n         { red. exists i. splits; auto.\n           enough (cti2ri ct i < cti2ri ct (1 + i)); [lia|].\n           apply cti2ri_S_mon. }\n         desf.\n         2: { exfalso. apply n. eauto. }\n         unfold proj1_sig in YY. do 2 desf. clear Heq.\n         apply cti2ri_inj in REP; subst.\n         apply cti2ri_inj in REP0; subst.\n         in_simp. exists (cti2ri ct x).\n         split.\n         { rewrite YY. eapply proj_ev_lab_of_ev; eauto. }\n         in_simp. split.\n         2: { rewrite YY. unfold lab_of_ev. desf.\n              exfalso. apply RNG in HH. apply HH. by rewrite Heq. }\n         apply RNG in LBDOM. apply FIN0 in LBDOM.\n         apply cti2ri_mon. by apply LTSG. }\n    in_simp. rename x0 into n.\n    edestruct (TT n) as [XX YY].\n    { red.\n      assert (0 < length findom) as NNIL.\n      { unfold cti2ri, cti2ri_helper in HH0.\n        destruct findom; ins; lia. }\n      exists (Nat.pred (length findom)). splits.\n      { apply LTSG. lia. }\n      arewrite (1 + Nat.pred (length findom) = length findom) by lia. }\n    do 2 desf.\n    2: { cdes YY. rewrite LBL in HH1. inv HH1. }\n    rewrite YY. unfold proj1_sig. do 2 desf. clear Heq.\n    rewrite proj_ev_lab_of_ev; auto. apply RNG.\n    clear YY. by apply cti2ri_inj in REP. }\n  assert\n  (forall i d\n          (HH : NOmega.lt_nat_l\n                  i (trace_length\n                       (trproj (trace_fin\n                                  (map t (List.seq 0 (cti2ri ct (length findom)))))))),\n                trace_nth\n                  i (trproj (trace_fin (map t (List.seq 0 (cti2ri ct (length findom)))))) d\n                = nu i /\\\n                i < length findom) as AA.\n  { intros i d. unfold trproj. erewrite ct2t_finite_filtered; eauto.\n    ins. rewrite map_map. rewrite !map_length in HH.\n    rewrite nth_indep with\n        (d:=d)\n        (d':=proj_ev (lab_of_ev WF ENUM RFC CONS FAIR THRB (nu 0))); auto.\n    2: by rewrite map_length.\n    rewrite seq_length in HH.\n    rewrite map_nth with\n        (f:=fun x : nat => proj_ev (lab_of_ev WF ENUM RFC CONS FAIR THRB (nu x))).\n    rewrite seq_nth; auto; ins.\n    rewrite proj_ev_lab_of_ev; auto. }\n  eapply trace_wf_helper; eauto.\n  4: by intros; destruct (AA i d) as [AI II]; auto.\n  { ins. apply ORD; auto. by apply sb_in_hb. }\n  { unfold trproj. erewrite ct2t_finite_filtered; eauto.\n    ins. rewrite map_map. split; red; intros x HH.\n    { apply in_map_iff in HH. desf.\n      apply in_seq_iff in HH0. ins.\n      assert (lt_size x0 (acts G \\₁ is_init)) by (apply LTSGg; lia).\n      rewrite proj_ev_lab_of_ev; auto. }\n    apply SUR in HH. desf. erewrite <- proj_ev_lab_of_ev; eauto.\n    apply in_map_iff. eexists; splits; eauto.\n    apply in_seq_iff. ins. split; [lia|]. by apply LTSG. }\n  unfold trproj. red. ins.\n  destruct (AA i d) as [AI II]; [lia|].\n  destruct (AA j d) as [AJ JJ]; auto.\n  rewrite AI, AJ.\n  intros HH. apply INJ in HH; auto.\n  lia. \nQed.\n", "meta": {"author": "weakmemory", "repo": "fairness", "sha": "537609d3c23490a82f11f13125d1f0ce4ce3fef8", "save_path": "github-repos/coq/weakmemory-fairness", "path": "github-repos/coq/weakmemory-fairness/fairness-537609d3c23490a82f11f13125d1f0ce4ce3fef8/src/equivalence/strong_coh/SCOHdeclToOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7122321720225279, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.24579507671074846}}
{"text": "(** Infrastructure lemmas and tactic definitions for Fsub.\n\n    Authors: Brian Aydemir and Arthur Charguéraud, with help from\n    Aaron Bohannon, Jeffrey Vaughan, and Dimitrios Vytiniotis.\n\n    This file contains a number of definitions, tactics, and lemmas\n    that are based only on the syntax of the language at hand.  While\n    the exact statements of everything here would change for a\n    different language, the general structure of this file (i.e., the\n    sequence of definitions, tactics, and lemmas) would remain the\n    same.\n\n    Table of contents:\n      - #<a href=\"##fv\">Free variables</a>#\n      - #<a href=\"##subst\">Substitution</a>#\n      - #<a href=\"##pick_fresh\">The \"pick fresh\" tactic</a>#\n      - #<a href=\"##apply_fresh\">The \"pick fresh and apply\" tactic</a>#\n      - #<a href=\"##properties\">Properties of opening and substitution</a>#\n      - #<a href=\"##lc\">Local closure is preserved under substitution</a>#\n      - #<a href=\"##auto\">Automation</a># *)\n\nRequire Export LinF_Definitions.\n\n(* ********************************************************************** *)\n(** * #<a name=\"fv\"></a># Free variables *)\n\n(** In this section, we define free variable functions.  The functions\n    [fv_tt] and [fv_te] calculate the set of atoms used as free type\n    variables in a type or expression, respectively.  The function\n    [fv_ee] calculates the set of atoms used as free expression\n    variables in an expression.  Cases involving binders are\n    straightforward since bound variables are indices, not names, in\n    locally nameless representation. *)\n\nFixpoint fv_tt (T : typ) {struct T} : atoms :=\n  match T with\n  | typ_bvar J => {}\n  | typ_fvar X => singleton X\n  | typ_arrow K T1 T2 => (fv_tt T1) `union` (fv_tt T2)\n  | typ_all K T2 => (fv_tt T2)\n  end.\n\nFixpoint fv_te (e : exp) {struct e} : atoms :=\n  match e with\n  | exp_bvar i => {}\n  | exp_fvar x => {}\n  | exp_abs K V e1  => (fv_tt V) `union` (fv_te e1)\n  | exp_app e1 e2 => (fv_te e1) `union` (fv_te e2)\n  | exp_tabs K e1 => (fv_te e1)\n  | exp_tapp e1 V => (fv_tt V) `union` (fv_te e1)\n  end.\n\nFixpoint fv_ee (e : exp) {struct e} : atoms :=\n  match e with\n  | exp_bvar i => {}\n  | exp_fvar x => singleton x\n  | exp_abs K V e1 => (fv_ee e1)\n  | exp_app e1 e2 => (fv_ee e1) `union` (fv_ee e2)\n  | exp_tabs K e1 => (fv_ee e1)\n  | exp_tapp e1 V => (fv_ee e1)\n  end.\n\nFixpoint fv_lenv (D : lenv) {struct D} : atoms :=\n  match D with\n  | nil => {}\n  | cons (x, lbind_typ T) l => fv_tt T `union` fv_lenv l\n  end.\n\n(* ********************************************************************** *)\n(** * #<a name=\"subst\"></a># Substitution *)\n\n(** In this section, we define substitution for expression and type\n    variables appearing in types, expressions, and environments.\n    Substitution differs from opening because opening replaces indices\n    whereas substitution replaces free variables.  The definitions\n    below are relatively simple for two reasons.\n      - We are using locally nameless representation, where bound\n        variables are represented using indices.  Thus, there is no\n        need to rename variables to avoid capture.\n      - The definitions below assume that the term being substituted\n        in, i.e., the second argument to each function, is locally\n        closed.  Thus, there is no need to shift indices when passing\n        under a binder. *)\n\nFixpoint subst_tt (Z : atom) (U : typ) (T : typ) {struct T} : typ :=\n  match T with\n  | typ_bvar J => typ_bvar J\n  | typ_fvar X => if X == Z then U else T\n  | typ_arrow K T1 T2 => typ_arrow K (subst_tt Z U T1) (subst_tt Z U T2)\n  | typ_all K T2 => typ_all K (subst_tt Z U T2)\n  end.\n\nFixpoint subst_te (Z : atom) (U : typ) (e : exp) {struct e} : exp :=\n  match e with\n  | exp_bvar i => exp_bvar i\n  | exp_fvar x => exp_fvar x\n  | exp_abs K V e1 => exp_abs  K (subst_tt Z U V)  (subst_te Z U e1)\n  | exp_app e1 e2 => exp_app  (subst_te Z U e1) (subst_te Z U e2)\n  | exp_tabs K e1 => exp_tabs K  (subst_te Z U e1)\n  | exp_tapp e1 V => exp_tapp (subst_te Z U e1) (subst_tt Z U V)\n  end.\n\nFixpoint subst_ee (z : atom) (u : exp) (e : exp) {struct e} : exp :=\n  match e with\n  | exp_bvar i => exp_bvar i\n  | exp_fvar x => if x == z then u else e\n  | exp_abs K V e1 => exp_abs K V (subst_ee z u e1)\n  | exp_app e1 e2 => exp_app (subst_ee z u e1) (subst_ee z u e2)\n  | exp_tabs K e1 => exp_tabs K (subst_ee z u e1)\n  | exp_tapp e1 V => exp_tapp (subst_ee z u e1) V\n  end.\n\nDefinition subst_tb (Z : atom) (P : typ) (b : binding) : binding :=\n  match b with\n  | bind_kn K => bind_kn K\n  | bind_typ T => bind_typ (subst_tt Z P T)\n  end.\n\nDefinition subst_tlb (Z : atom) (P : typ) (b : lbinding) : lbinding :=\n  match b with\n  | lbind_typ T => lbind_typ (subst_tt Z P T)\n  end.\n\n\n(* ********************************************************************** *)\n(** * #<a name=\"pick_fresh\"></a># The \"[pick fresh]\" tactic *)\n\n(** The \"[pick fresh]\" tactic introduces a fresh atom into the context.\n    We define it in two steps.\n\n    The first step is to define an auxiliary tactic [gather_atoms],\n    meant to be used in the definition of other tactics, which returns\n    a set of atoms in the current context.  The definition of\n    [gather_atoms] follows a pattern based on repeated calls to\n    [gather_atoms_with].  The one argument to this tactic is a\n    function that takes an object of some particular type and returns\n    a set of atoms that appear in that argument.  It is not necessary\n    to understand exactly how [gather_atoms_with] works.  If we add a\n    new inductive datatype, say for kinds, to our language, then we\n    would need to modify [gather_atoms].  On the other hand, if we\n    merely add a new type, say products, then there is no need to\n    modify [gather_atoms]; the required changes would be made in\n    [fv_tt]. *)\n\nLtac gather_atoms :=\n  let A := gather_atoms_with (fun x : atoms => x) in\n  let B := gather_atoms_with (fun x : atom => singleton x) in\n  let C := gather_atoms_with (fun x : exp => fv_te x) in\n  let D := gather_atoms_with (fun x : exp => fv_ee x) in\n  let E := gather_atoms_with (fun x : typ => fv_tt x) in\n  let F := gather_atoms_with (fun x : env => dom x) in\n  let G := gather_atoms_with (fun x : lenv => dom x) in\n  let H := gather_atoms_with (fun x : lenv => fv_lenv x) in\n  constr:(A `union` B `union` C `union` D `union` E `union` F `union` G `union` H).\n\n(** The second step in defining \"[pick fresh]\" is to define the tactic\n    itself.  It is based on the [(pick fresh ... for ...)] tactic\n    defined in the [Atom] library.  Here, we use [gather_atoms] to\n    construct the set [L] rather than leaving it to the user to\n    provide.  Thus, invoking [(pick fresh x)] introduces a new atom\n    [x] into the current context that is fresh for \"everything\" in the\n    context. *)\n\nTactic Notation \"pick\" \"fresh\" ident(x) :=\n  let L := gather_atoms in (pick fresh x for L).\n\n\n(* *********************************************************************** *)\n(** * #<a name=\"apply_fresh\"></a># The \"[pick fresh and apply]\" tactic *)\n\n(** This tactic is implementation specific only because of its\n    reliance on [gather_atoms], which is itself implementation\n    specific.  The definition below may be copied between developments\n    without any changes, assuming that the other other developments\n    define an appropriate [gather_atoms] tactic.  For documentation on\n    the tactic on which the one below is based, see the\n    [Metatheory] library. *)\n\nTactic Notation\n      \"pick\" \"fresh\" ident(atom_name) \"and\" \"apply\" constr(lemma) :=\n  let L := gather_atoms in\n  pick fresh atom_name excluding L and apply lemma.\n\n\n(* ********************************************************************** *)\n(** * #<a name=\"properties\"></a># Properties of opening and substitution *)\n\n(** The following lemmas provide useful structural properties of\n    substitution and opening.  While the exact statements are language\n    specific, we have found that similar properties are needed in a\n    wide range of languages.\n\n    Below, we indicate which lemmas depend on which other lemmas.\n    Since [te] functions depend on their [tt] counterparts, a similar\n    dependency can be found in the lemmas.\n\n    The lemmas are split into three sections, one each for the [tt],\n    [te], and [ee] functions.  The most important lemmas are the\n    following:\n      - Substitution and opening commute with each other, e.g.,\n        [subst_tt_open_tt_var].\n      - Opening a term is equivalent to opening the term with a fresh\n        name and then substituting for that name, e.g.,\n        [subst_tt_intro].\n\n    We keep the sections as uniform in structure as possible.  In\n    particular, we state explicitly strengthened induction hypotheses\n    even when there are more concise ways of proving the lemmas of\n    interest. *)\n\n\n(* ********************************************************************** *)\n(** ** Properties of type substitution in types *)\n\n(** The next lemma is the strengthened induction hypothesis for the\n    lemma that follows, which states that opening a locally closed\n    term is the identity.  This lemma is not otherwise independently\n    useful. *)\n\nLemma open_tt_rec_type_aux : forall T j V i U,\n  i <> j ->\n  open_tt_rec j V T = open_tt_rec i U (open_tt_rec j V T) ->\n  T = open_tt_rec i U T.\nProof with eauto*.\n  induction T; intros j V i U Neq H; simpl in *; inversion H; f_equal...\n  Case \"typ_bvar\".\n    destruct (j === n)... destruct (i === n)...\nQed.\n\n(** Opening a locally closed term is the identity.  This lemma depends\n    on the immediately preceding lemma. *)\n\nLemma open_tt_rec_type : forall T U k,\n  type T ->\n  T = open_tt_rec k U T.\nProof with auto*.\n  intros T U k Htyp. revert k.\n  induction Htyp; intros k; simpl; f_equal...\n  Case \"typ_all\".\n    unfold open_tt in *.\n    pick fresh X.\n    apply (open_tt_rec_type_aux T2 0 (typ_fvar X))...\nQed.\n\n(** If a name is fresh for a term, then substituting for it is the\n    identity. *)\n\nLemma subst_tt_fresh : forall Z U T,\n   Z `notin` fv_tt T ->\n   T = subst_tt Z U T.\nProof with auto*.\n  induction T; simpl; intro H; f_equal...\n  Case \"typ_fvar\".\n    destruct (a == Z)...\n    absurd_hyp H; fsetdec.\nQed.\n\n(** Substitution commutes with opening under certain conditions.  This\n    lemma depends on the fact that opening a locally closed term is\n    the identity. *)\n\nLemma subst_tt_open_tt_rec : forall T1 T2 X P k,\n  type P ->\n  subst_tt X P (open_tt_rec k T2 T1) =\n    open_tt_rec k (subst_tt X P T2) (subst_tt X P T1).\nProof with auto*.\n  intros T1 T2 X P k WP. revert k.\n  induction T1; intros K; simpl; f_equal...\n  Case \"typ_bvar\".\n    destruct (K === n); subst...\n  Case \"typ_fvar\".\n    destruct (a == X); subst... apply open_tt_rec_type...\nQed.\n\n(** The next lemma is a direct corollary of the immediately preceding\n    lemma---the index is specialized to zero. *)\n\nLemma subst_tt_open_tt : forall T1 T2 (X:atom) P,\n  type P ->\n  subst_tt X P (open_tt T1 T2) = open_tt (subst_tt X P T1) (subst_tt X P T2).\nProof with auto*.\n  intros.\n  unfold open_tt.\n  apply subst_tt_open_tt_rec...\nQed.\n\n(** The next lemma is a direct corollary of the immediately preceding\n    lemma---here, we're opening the term with a variable.  In\n    practice, this lemma seems to be needed as a left-to-right rewrite\n    rule, when stated in its current form. *)\n\nLemma subst_tt_open_tt_var : forall (X Y:atom) P T,\n  Y <> X ->\n  type P ->\n  open_tt (subst_tt X P T) Y = subst_tt X P (open_tt T Y).\nProof with auto*.\n  intros X Y P T Neq Wu.\n  unfold open_tt.\n  rewrite subst_tt_open_tt_rec...\n  simpl.\n  destruct (Y == X)...\nQed.\n\n(** The next lemma states that opening a term is equivalent to first\n    opening the term with a fresh name and then substituting for the\n    name.  This is actually the strengthened induction hypothesis for\n    the version we use in practice. *)\n\nLemma subst_tt_intro_rec : forall X T2 U k,\n  X `notin` fv_tt T2 ->\n  open_tt_rec k U T2 = subst_tt X U (open_tt_rec k (typ_fvar X) T2).\nProof with auto*.\n  induction T2; intros U K Fr; simpl in *; f_equal...\n  Case \"typ_bvar\".\n    destruct (K === n)... simpl. destruct (X == X)...\n  Case \"typ_fvar\".\n    destruct (a == X)... absurd_hyp Fr; fsetdec.\nQed.\n\n(** The next lemma is a direct corollary of the immediately preceding\n    lemma---the index is specialized to zero.  *)\n\nLemma subst_tt_intro : forall X T2 U,\n  X `notin` fv_tt T2 ->\n  open_tt T2 U = subst_tt X U (open_tt T2 X).\nProof with auto*.\n  intros.\n  unfold open_tt.\n  apply subst_tt_intro_rec...\nQed.\n\n\n(* ********************************************************************** *)\n(** ** Properties of type substitution in expressions *)\n\n(** This section follows the structure of the previous section.  The\n    one notable difference is that we require two auxiliary lemmas to\n    show that substituting a type in a locally-closed expression is\n    the identity. *)\n\nLemma open_te_rec_expr_aux : forall e j u i P ,\n  open_ee_rec j u e = open_te_rec i P (open_ee_rec j u e) ->\n  e = open_te_rec i P e.\nProof with eauto*.\n  induction e; intros j u i P H; simpl in *; inversion H; f_equal...\nQed.\n\nLemma open_te_rec_type_aux : forall e j Q i P,\n  i <> j ->\n  open_te_rec j Q e = open_te_rec i P (open_te_rec j Q e) ->\n  e = open_te_rec i P e.\nProof.\n  induction e; intros j Q i P Neq Heq; simpl in *; inversion Heq;\n    f_equal; eauto using open_tt_rec_type_aux.\nQed.\n\nLemma open_te_rec_expr : forall e U k,\n  expr e ->\n  e = open_te_rec k U e.\nProof with auto*.\n  intros e U k WF. revert k.\n  induction WF; intros k; simpl; f_equal; auto using open_tt_rec_type;\n  try solve [\n    unfold open_ee in *;\n    pick fresh x;\n    eapply open_te_rec_expr_aux with (j := 0) (u := exp_fvar x);\n    auto*\n  | unfold open_te in *;\n    pick fresh X;\n    eapply open_te_rec_type_aux with (j := 0) (Q := typ_fvar X);\n    auto*\n  ].\nQed.\n\nLemma subst_te_fresh : forall X U e,\n  X `notin` fv_te e ->\n  e = subst_te X U e.\nProof.\n  induction e; simpl; intros; f_equal; auto using subst_tt_fresh.\nQed.\n\nLemma subst_te_open_te_rec : forall e T X U k,\n  type U ->\n  subst_te X U (open_te_rec k T e) =\n    open_te_rec k (subst_tt X U T) (subst_te X U e).\nProof.\n  intros e T X U k WU. revert k.\n  induction e; intros K; simpl; f_equal; auto using subst_tt_open_tt_rec.\nQed.\n\nLemma subst_te_open_te : forall e T X U,\n  type U ->\n  subst_te X U (open_te e T) = open_te (subst_te X U e) (subst_tt X U T).\nProof with auto*.\n  intros.\n  unfold open_te.\n  apply subst_te_open_te_rec...\nQed.\n\nLemma subst_te_open_te_var : forall (X Y:atom) U e,\n  Y <> X ->\n  type U ->\n  open_te (subst_te X U e) Y = subst_te X U (open_te e Y).\nProof with auto*.\n  intros X Y U e Neq WU.\n  unfold open_te.\n  rewrite subst_te_open_te_rec...\n  simpl.\n  destruct (Y == X)...\nQed.\n\nLemma subst_te_intro_rec : forall X e U k,\n  X `notin` fv_te e ->\n  open_te_rec k U e = subst_te X U (open_te_rec k (typ_fvar X) e).\nProof.\n  induction e; intros U K Fr; simpl in *; f_equal;\n    auto using subst_tt_intro_rec.\nQed.\n\nLemma subst_te_intro : forall X e U,\n  X `notin` fv_te e ->\n  open_te e U = subst_te X U (open_te e X).\nProof with auto*.\n  intros.\n  unfold open_te.\n  apply subst_te_intro_rec...\nQed.\n\n\n(* ********************************************************************** *)\n(** ** Properties of expression substitution in expressions *)\n\n(** This section follows the structure of the previous two sections. *)\n\nLemma open_ee_rec_expr_aux : forall e j v u i,\n  i <> j ->\n  open_ee_rec j v e = open_ee_rec i u (open_ee_rec j v e) ->\n  e = open_ee_rec i u e.\nProof with eauto*.\n  induction e; intros j v u i Neq H; simpl in *; inversion H; f_equal...\n  Case \"exp_bvar\".\n    destruct (j===n)... destruct (i===n)...\nQed.\n\nLemma open_ee_rec_type_aux : forall e j V u i,\n  open_te_rec j V e = open_ee_rec i u (open_te_rec j V e) ->\n  e = open_ee_rec i u e.\nProof.\n  induction e; intros j V u i H; simpl; inversion H; f_equal; eauto.\nQed.\n\nLemma open_ee_rec_expr : forall u e k,\n  expr e ->\n  e = open_ee_rec k u e.\nProof with auto*.\n  intros u e k Hexpr. revert k.\n  induction Hexpr; intro k; simpl; f_equal; auto*;\n  try solve [\n    unfold open_ee in *;\n    pick fresh x;\n    eapply open_ee_rec_expr_aux with (j := 0) (v := exp_fvar x);\n    auto*\n  | unfold open_te in *;\n    pick fresh X;\n    eapply open_ee_rec_type_aux with (j := 0) (V := typ_fvar X);\n    auto*\n  ].\nQed.\n\nLemma subst_ee_fresh : forall (x: atom) u e,\n  x `notin` fv_ee e ->\n  e = subst_ee x u e.\nProof with auto*.\n  intros x u e; induction e; simpl; intro H; f_equal...\n  Case \"exp_fvar\".\n    destruct (a==x)...\n    absurd_hyp H; fsetdec.\nQed.\n\nLemma subst_ee_open_ee_rec : forall e1 e2 x u k,\n  expr u ->\n  subst_ee x u (open_ee_rec k e2 e1) =\n    open_ee_rec k (subst_ee x u e2) (subst_ee x u e1).\nProof with auto*.\n  intros e1 e2 x u k WP. revert k.\n  induction e1; intros K; simpl; f_equal...\n  Case \"exp_bvar\".\n    destruct (K === n); subst...\n  Case \"exp_fvar\".\n    destruct (a == x); subst... apply open_ee_rec_expr...\nQed.\n\nLemma subst_ee_open_ee : forall e1 e2 x u,\n  expr u ->\n  subst_ee x u (open_ee e1 e2) =\n    open_ee (subst_ee x u e1) (subst_ee x u e2).\nProof with auto*.\n  intros.\n  unfold open_ee.\n  apply subst_ee_open_ee_rec...\nQed.\n\nLemma subst_ee_open_ee_var : forall (x y:atom) u e,\n  y <> x ->\n  expr u ->\n  open_ee (subst_ee x u e) y = subst_ee x u (open_ee e y).\nProof with auto*.\n  intros x y u e Neq Wu.\n  unfold open_ee.\n  rewrite subst_ee_open_ee_rec...\n  simpl.\n  destruct (y == x)...\nQed.\n\nLemma subst_te_open_ee_rec : forall e1 e2 Z P k,\n  subst_te Z P (open_ee_rec k e2 e1) =\n    open_ee_rec k (subst_te Z P e2) (subst_te Z P e1).\nProof with auto*.\n  induction e1; intros e2 Z P K; simpl; f_equal...\n  Case \"exp_bvar\".\n    destruct (K === n)...\nQed.\n\nLemma subst_te_open_ee : forall e1 e2 Z P,\n  subst_te Z P (open_ee e1 e2) = open_ee (subst_te Z P e1) (subst_te Z P e2).\nProof with auto*.\n  intros.\n  unfold open_ee.\n  apply subst_te_open_ee_rec...\nQed.\n\nLemma subst_te_open_ee_var : forall Z (x:atom) P e,\n  open_ee (subst_te Z P e) x = subst_te Z P (open_ee e x).\nProof with auto*.\n  intros.\n  rewrite subst_te_open_ee...\nQed.\n\nLemma subst_ee_open_te_rec : forall e P z u k,\n  expr u ->\n  subst_ee z u (open_te_rec k P e) = open_te_rec k P (subst_ee z u e).\nProof with auto*.\n  induction e; intros P z u K H; simpl; f_equal...\n  Case \"exp_fvar\".\n    destruct (a == z)... apply open_te_rec_expr...\nQed.\n\nLemma subst_ee_open_te : forall e P z u,\n  expr u ->\n  subst_ee z u (open_te e P) = open_te (subst_ee z u e) P.\nProof with auto*.\n  intros.\n  unfold open_te.\n  apply subst_ee_open_te_rec...\nQed.\n\nLemma subst_ee_open_te_var : forall z (X:atom) u e,\n  expr u ->\n  open_te (subst_ee z u e) X = subst_ee z u (open_te e X).\nProof with auto*.\n  intros z X u e H.\n  rewrite subst_ee_open_te...\nQed.\n\nLemma subst_ee_intro_rec : forall x e u k,\n  x `notin` fv_ee e ->\n  open_ee_rec k u e = subst_ee x u (open_ee_rec k (exp_fvar x) e).\nProof with auto*.\n  induction e; intros u K Fr; simpl in *; f_equal...\n  Case \"exp_bvar\".\n    destruct (K === n)... simpl. destruct (x == x)...\n  Case \"exp_fvar\".\n    destruct (a == x)... absurd_hyp Fr; fsetdec.\nQed.\n\nLemma subst_ee_intro : forall x e u,\n  x `notin` fv_ee e ->\n  open_ee e u = subst_ee x u (open_ee e x).\nProof with auto*.\n  intros.\n  unfold open_ee.\n  apply subst_ee_intro_rec...\nQed.\n\n\n(* *********************************************************************** *)\n(** * #<a name=\"lc\"></a># Local closure is preserved under substitution *)\n\n(** While these lemmas may be considered properties of substitution, we\n    separate them out due to the lemmas that they depend on. *)\n\n(** The following lemma depends on [subst_tt_open_tt_var]. *)\n\nLemma subst_tt_type : forall Z P T,\n  type T ->\n  type P ->\n  type (subst_tt Z P T).\nProof with auto.\n  intros Z P T HT HP.\n  induction HT; simpl...\n  Case \"type_fvar\".\n    destruct (X == Z)...\n  Case \"type_all\".\n    pick fresh Y and apply type_all...\n    rewrite subst_tt_open_tt_var...\nQed.\n\n(** The following lemma depends on [subst_tt_type] and\n    [subst_te_open_ee_var]. *)\n\nLemma subst_te_expr : forall Z P e,\n  expr e ->\n  type P ->\n  expr (subst_te Z P e).\nProof with eauto using subst_tt_type.\n  intros Z P e He Hp.\n  induction He; simpl; auto using subst_tt_type;\n  try solve [\n    econstructor;\n    try instantiate (1 := L `union` singleton Z);\n    intros;\n    try rewrite subst_te_open_ee_var;\n    try rewrite subst_te_open_te_var;\n    eauto using subst_tt_type\n  ].\nQed.\n\n(** The following lemma depends on [subst_ee_open_ee_var] and\n    [subst_ee_open_te_var]. *)\n\nLemma subst_ee_expr : forall z e1 e2,\n  expr e1 ->\n  expr e2 ->\n  expr (subst_ee z e2 e1).\nProof with auto.\n  intros z e1 e2 He1 He2.\n  induction He1; simpl; auto;\n  try solve [\n    econstructor;\n    try instantiate (1 := L `union` singleton z);\n    intros;\n    try rewrite subst_ee_open_ee_var;\n    try rewrite subst_ee_open_te_var;\n    auto\n  ].\n  Case \"expr_var\".\n    destruct (x == z)...\nQed.\n\n\n\n\n(* *********************************************************************** *)\n(** * #<a name=\"auto\"></a># Automation *)\n\n(** We add as hints the fact that local closure is preserved under\n    substitution.  This is part of our strategy for automatically\n    discharging local-closure proof obligations. *)\n\nHint Resolve subst_tt_type subst_te_expr subst_ee_expr.\n\n(** When reasoning about the [binds] relation and [map], we\n    occasionally encounter situations where the binding is\n    over-simplified.  The following hint undoes that simplification,\n    thus enabling [Hint]s from the [Environment] library. *)\n\nHint Extern 1 (binds _ (?F (subst_tt ?X ?U ?T)) _) =>\n  unsimpl (subst_tb X U (F T)).\n\nHint Extern 1 (binds _ (?F (subst_tt ?X ?U ?T)) _) =>\n  unsimpl (subst_tlb X U (F T)).\n", "meta": {"author": "Zdancewic", "repo": "linearity", "sha": "b2662939b2e8fb8fbe34f7ec0d3c69ef1bdff916", "save_path": "github-repos/coq/Zdancewic-linearity", "path": "github-repos/coq/Zdancewic-linearity/linearity-b2662939b2e8fb8fbe34f7ec0d3c69ef1bdff916/declarative/LinF_Infrastructure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.24573395951675683}}
{"text": "Require Import\n  Coq.Unicode.Utf8\n  (* Coq.ZArith.ZArith *)\n  (* Coq.Logic.PropExtensionality *)\n  (* Hask.Control.Monad *)\n  Data.Semigroup\n  Data.Monoid\n  (* Data.Either *)\n  (* Pact.Lib *)\n  (* Pact.Ty *)\n  (* Pact.Exp *)\n  (* Pact.Value *)\n  (* Pact.Ren *)\n  (* Pact.Sub *)\n  (* Pact.SemTy *)\n  (* Pact.Lang *)\n  (* Pact.Lang.Capability *)\n  (* Pact.SemExp *)\n  Coq.Classes.RelationClasses\n  Coq.Classes.Morphisms\n  (* Pact.Ltac *)\n.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* Set Equations With UIP. *)\n\nGeneralizable All Variables.\nSet Primitive Projections.\n\n(* Import ListNotations. *)\n\nDeclare Scope hoare_scope.\nDeclare Scope hoare_scope_ext.\n\nReserved Infix \"\\u\" (at level 45, right associativity).\nReserved Infix \"==>\" (at level 55, right associativity).\nReserved Infix \"===>\" (at level 55, right associativity).\nReserved Infix \"\\*\" (at level 41, right associativity).\nReserved Notation \"'\\exists' x1 .. xn , H\"\n  (at level 39, x1 binder, H at level 50, right associativity,\n   format \"'[' '\\exists' '/ '  x1  ..  xn , '/ '  H ']'\").\nReserved Notation \"'\\forall' x1 .. xn , H\"\n  (at level 39, x1 binder, H at level 50, right associativity,\n   format \"'[' '\\forall' '/ '  x1  ..  xn , '/ '  H ']'\").\nReserved Notation \"\\[ P ]\" (at level 0, format \"\\[ P ]\").\nReserved Notation \"H1 \\-* H2\" (at level 43, right associativity).\nReserved Notation \"Q1 \\--* Q2\" (at level 43).\n\nClass HoareLogic (heap : Type) := {\n  heap_empty : heap;\n\n  (** In traditional Separation Logic, two heaps are compatible (that is, can\n      be composed) if and only if they have disjoint domains, and their\n      composition is just their union. *)\n  heap_compat : heap → heap → Prop;\n\n  heap_compat_irr {h} :\n    h <> heap_empty →\n    ¬ heap_compat h h;\n  heap_compat_sym {h1 h2} :\n    heap_compat h1 h2 →\n    heap_compat h2 h1;\n  heap_compat_empty_l {h} :\n    heap_compat heap_empty h;\n\n  heap_union : heap → heap → heap\n    where \"X \\u Y\" := (heap_union X Y) : hoare_scope;\n\n  heap_compat_union_l_eq {h1 h2 h3} :\n    heap_compat h1 h2 →\n    heap_compat (h1 \\u h2) h3 = (heap_compat h1 h3 ∧ heap_compat h2 h3);\n\n  heap_union_empty_l {h} :\n    heap_empty \\u h = h;\n  heap_union_comm {h1 h2} :\n    heap_compat h1 h2 →\n    h1 \\u h2 = h2 \\u h1;\n  heap_union_assoc {h1 h2 h3} :\n    heap_compat h1 h2 →\n    heap_compat h2 h3 →\n    heap_compat h1 h3 →\n    (h1 \\u h2) \\u h3 = h1 \\u (h2 \\u h3);\n\n  hprop := heap → Prop;\n  himpl (H1 H2 : hprop) : Prop :=\n    ∀ h : heap, H1 h → H2 h\n    where \"H1 ==> H2\" := (himpl H1 H2) : hoare_scope;\n  qimpl {A} (Q1 Q2 : A → hprop) : Prop :=\n    ∀ v : A, Q1 v ==> Q2 v\n    where \"Q1 ===> Q2\" := (qimpl Q1 Q2) : hoare_scope;\n\n  hempty : hprop := λ h, h = heap_empty;\n\n  hstar (H1 H2 : hprop) : hprop :=\n    λ h, ∃ h1 h2,\n        H1 h1\n      ∧ H2 h2\n      ∧ heap_compat h1 h2\n      ∧ h = h1 \\u h2\n    where \"H1 '\\*' H2\" := (hstar H1 H2) : hoare_scope;\n\n  hexists {A} (J : A → hprop) : hprop :=\n    λ h, ∃ x, J x h\n    where \"'\\exists' x1 .. xn , H\" :=\n      (hexists (λ x1, .. (hexists (λ xn, H)) ..)) : hoare_scope;\n\n  hforall {A : Type} (J : A → hprop) : hprop :=\n    λ h, ∀ x, J x h\n    where \"'\\forall' x1 .. xn , H\" :=\n      (hforall (λ x1, .. (hforall (λ xn, H)) ..)) : hoare_scope;\n\n  hpure (P : Prop) : hprop :=\n    hexists (λ p : P, hempty)\n    where \"\\[ P ]\" := (hpure P) : hoare_scope;\n\n  hwand (H1 H2 : hprop) : hprop :=\n    hexists (λ H : hprop, H \\* (hpure (H1 \\* H ==> H2)))\n    where \"H1 \\-* H2\" := (hwand H1 H2) : hoare_scope;\n\n  qwand {A} (Q1 Q2 : A → hprop) : hprop :=\n    hforall (λ x, hwand (Q1 x) (Q2 x))\n    where \"Q1 \\--* Q2\" := (qwand Q1 Q2) : hoare_scope;\n\n  hor (H1 H2 : hprop) : hprop :=\n    \\exists (b : bool), if b then H1 else H2;\n\n  hand (H1 H2 : hprop) : hprop :=\n    \\forall (b : bool), if b then H1 else H2;\n\n  htop : hprop :=\n    hexists (λ H : hprop, H);\n}.\n\nInfix \"\\u\" := heap_union (at level 45, right associativity) : hoare_scope.\nInfix \"==>\" := himpl (at level 55, right associativity) : hoare_scope.\nInfix \"===>\" := qimpl (at level 55, right associativity) : hoare_scope.\nInfix \"\\*\" := hstar (at level 41, right associativity) : hoare_scope.\nNotation \"'\\exists' x1 .. xn , H\" :=\n  (hexists (λ x1, .. (hexists (λ xn, H)) ..))\n  (at level 39, x1 binder, H at level 50, right associativity,\n   format \"'[' '\\exists' '/ '  x1  ..  xn , '/ '  H ']'\") : hoare_scope.\nNotation \"'\\forall' x1 .. xn , H\" :=\n  (hforall (λ x1, .. (hforall (λ xn, H)) ..))\n  (at level 39, x1 binder, H at level 50, right associativity,\n   format \"'[' '\\forall' '/ '  x1  ..  xn , '/ '  H ']'\") : hoare_scope.\nNotation \"\\[ P ]\" := (hpure P) (at level 0, format \"\\[ P ]\") : hoare_scope.\nNotation \"H1 \\-* H2\" := (hwand H1 H2)\n  (at level 43, right associativity) : hoare_scope.\nNotation \"Q1 \\--* Q2\" := (qwand Q1 Q2) (at level 43) : hoare_scope.\n\nNotation \"\\[]\" := hempty (at level 0) : hoare_scope.\nNotation \"Q \\*+ H\" := (λ x, hstar (Q x) H) (at level 40) : hoare_scope.\nNotation \"\\Top\" := htop (at level 0) : hoare_scope.\n\nDelimit Scope hoare_scope with hprop.\n\nNotation \"H1 ==+> H2\" := (H1%hprop ==> hstar H1%hprop H2%hprop)%hprop\n  (at level 55, only parsing) : hoare_scope_ext.\n\nSection Hoare.\n\nOpen Scope hoare_scope.\n\nContext `{HL : HoareLogic heap}.\n\nImplicit Types h : heap.\nImplicit Types P : Prop.\nImplicit Types H : hprop.\n\n(** Properties of entailment *)\n\nLemma himpl_refl {H} :\n  (H ==> H).\nProof. now repeat intro. Qed.\n\n#[local] Hint Resolve himpl_refl : core.\n\nLemma himpl_trans {H2 H1 H3} :\n  (H1 ==> H2) →\n  (H2 ==> H3) →\n  (H1 ==> H3).\nProof.\n  repeat intro.\n  now apply H0, H.\nQed.\n\n#[export]\nProgram Instance himpl_PreOrder : PreOrder himpl.\nNext Obligation.\n  repeat intro.\n  eapply himpl_trans; eauto.\nQed.\n\nLemma himpl_antisym {H1 H2} :\n  (H1 ==> H2) →\n  (H2 ==> H1) →\n  (H1 = H2).\nProof. Admitted.\n\n(** Additional properties of [himpl] *)\n\nLemma himpl_forall_trans {H1 H2} :\n  (∀ H, H ==> H1 → H ==> H2) →\n  (H1 ==> H2).\nProof. Admitted.\n\nLemma himpl_inv {H1 H2 h} :\n  (H1 ==> H2) →\n  (H1 h) →\n  (H2 h).\nProof. auto. Qed.\n\n(** Properties of entailment for postconditions *)\n\nLemma qimpl_refl {A} {Q : A → hprop} :\n  (Q ===> Q).\nProof. Admitted.\n\n#[local] Hint Resolve qimpl_refl : core.\n\nLemma qimpl_trans {A} {Q2 Q1 Q3 : A → hprop} :\n  (Q1 ===> Q2) →\n  (Q2 ===> Q3) →\n  (Q1 ===> Q3).\nProof. Admitted.\n\n#[export]\nProgram Instance qimpl_PreOrder {A} : PreOrder (qimpl (A:=A)).\nNext Obligation.\n  repeat intro.\n  eapply qimpl_trans; eauto.\nQed.\n\nLemma qimpl_antisym {A} {Q1 Q2 : A → hprop} :\n  (Q1 ===> Q2) →\n  (Q2 ===> Q1) →\n  (Q1 = Q2).\nProof. Admitted.\n\nLemma heap_compat_sym_eq {h1 h2} :\n  heap_compat h1 h2 = heap_compat h2 h1.\nProof. Admitted.\n\nLemma heap_compat_empty_r {h} :\n  heap_compat h heap_empty.\nProof.\n  rewrite heap_compat_sym_eq.\n  apply heap_compat_empty_l.\nQed.\n\nLemma heap_union_empty_r {h} :\n  h \\u heap_empty = h.\nProof. Admitted.\n\nLemma heap_compat_union_r_eq {h1 h2 h3} :\n  heap_compat h2 h3 →\n  heap_compat h1 (h2 \\u h3) = (heap_compat h1 h2 ∧ heap_compat h1 h3).\nProof. Admitted.\n\nLemma heap_compat_union_l {h1 h2 h3} :\n  heap_compat h1 h2 →\n  heap_compat h1 h3 →\n  heap_compat h2 h3 →\n  heap_compat (h1 \\u h2) h3.\nProof. Admitted.\n\nLemma heap_compat_union_r {h1 h2 h3} :\n  heap_compat h1 h2 →\n  heap_compat h1 h3 →\n  heap_compat h2 h3 →\n  heap_compat h1 (h2 \\u h3).\nProof. Admitted.\n\n(* ---------------------------------------------------------------------- *)\n(* ** Tactic *)\n\n(* Hint Rewrite heap_union_empty_l heap_union_empty_r heap_union_assoc : rew_heaps. *)\n\n(* Tactic Notation \"rew_heaps\" := *)\n(*   autorewrite with rew_heaps. *)\n(* Tactic Notation \"rew_heaps\" \"in\" hyp(H) := *)\n(*   autorewrite with rew_heaps in H. *)\n(* Tactic Notation \"rew_heaps\" \"in\" \"*\" := *)\n(*   autorewrite with rew_heaps in *. *)\n\n(* ---------------------------------------------------------------------- *)\n(* ** Introduction and Inversion Lemmas for Core Heap Predicates *)\n\n(** Core heap predicates *)\n\nLemma hempty_intro :\n  \\[] heap_empty.\nProof. Admitted.\n\nLemma hempty_inv {h} :\n  \\[] h →\n  h = heap_empty.\nProof. Admitted.\n\nLemma hstar_intro {H1 H2 : hprop} {h1 h2} :\n  H1 h1 →\n  H2 h2 →\n  heap_compat h1 h2 →\n  (H1 \\* H2) (h1 \\u h2).\nProof. Admitted.\n\nLemma hstar_inv {H1 H2 h} :\n  (H1 \\* H2) h →\n  exists h1 h2, H1 h1 ∧ H2 h2 ∧ heap_compat h1 h2 ∧ h = h1 \\u h2.\nProof. Admitted.\n\nLemma hexists_intro {A} {J : A → hprop} {x h} :\n  J x h →\n  (hexists J) h.\nProof. Admitted.\n\nLemma hexists_inv {A} {J : A → hprop} {h} :\n  (hexists J) h →\n  exists x, J x h.\nProof. Admitted.\n\nLemma hforall_intro {A} {J : A → hprop} {h} :\n  (∀ x, J x h) →\n  (hforall J) h.\nProof. Admitted.\n\nLemma hforall_inv {A} {J : A → hprop} {h} :\n  (hforall J) h →\n  ∀ x, J x h.\nProof. Admitted.\n\n(** Derived heap predicates *)\n\nLemma hpure_intro {P} :\n  P →\n  \\[P] heap_empty.\nProof. Admitted.\n\nLemma hpure_inv {P h} :\n  \\[P] h →\n  P ∧ h = heap_empty.\nProof. Admitted.\n\n(* ---------------------------------------------------------------------- *)\n(* ** Proving core properties of operators *)\n\n(** Lemmas from this section should be the last ones to access the\n    internal definition of the operators hempty and hstar. *)\n\nSection CoreProperties.\n\n#[local] Hint Resolve heap_compat_empty_l heap_compat_empty_r\n  heap_union_empty_l heap_union_empty_r hempty_intro\n  heap_compat_union_l heap_compat_union_r : core.\n\n(** Empty is left neutral for star *)\n\nLemma hstar_hempty_l {H} :\n  \\[] \\* H = H.\nProof. Admitted.\n\n(** Star is commutative *)\n\nLemma hstar_comm {H1 H2} :\n   H1 \\* H2 = H2 \\* H1.\nProof. Admitted.\n\n(** Star is associative *)\n\nLemma hstar_assoc {H1 H2 H3} :\n  (H1 \\* H2) \\* H3 = H1 \\* (H2 \\* H3).\nProof. Admitted.\n\n#[export]\nInstance hstar_Semigroup : Semigroup hprop := {|\n  mappend := hstar\n|}.\n\n#[export]\nProgram Instance hstar_SemigroupLaws : SemigroupLaws hprop.\nNext Obligation.\n  symmetry.\n  apply hstar_assoc.\nQed.\n\n(** Extrusion of existentials out of star *)\n\nLemma hstar_hexists {A} {J : A → hprop} {H} :\n  (hexists J) \\* H = hexists (fun x => (J x) \\* H).\nProof. Admitted.\n\n(** Extrusion of foralls out of star *)\n\nLemma hstar_hforall {H A} {J : A → hprop} :\n  (hforall J) \\* H ==> hforall (J \\*+ H).\nProof. Admitted.\n\n(** The frame property (star on H2) holds for entailment *)\n\nLemma himpl_frame_l {H2 H1 H1'} :\n  H1 ==> H1' →\n  (H1 \\* H2) ==> (H1' \\* H2).\nProof. Admitted.\n\n(** Properties of [hpure] *)\n\nLemma hstar_hpure_l {P H h} :\n  (\\[P] \\* H) h = (P ∧ H h).\nProof. Admitted.\n\nEnd CoreProperties.\n\n#[global] Opaque hempty hpure hstar hexists.\n\n(* ---------------------------------------------------------------------- *)\n(* ** Properties of [hstar] *)\n\nLemma hstar_hempty_r {H} :\n  H \\* \\[] = H.\nProof. Admitted.\n\n#[export]\nInstance hstar_Monoid : Monoid hprop := {|\n  mempty := hempty\n|}.\n\n#[export]\nProgram Instance hstar_MonoidLaws : MonoidLaws hprop.\nNext Obligation. apply hstar_hempty_l. Qed.\nNext Obligation. apply hstar_hempty_r. Qed.\n\nLemma himpl_frame_r {H1 H2 H2'} :\n  H2 ==> H2' →\n  (H1 \\* H2) ==> (H1 \\* H2').\nProof. Admitted.\n\nLemma himpl_frame_lr {H1 H1' H2 H2'} :\n  H1 ==> H1' →\n  H2 ==> H2' →\n  (H1 \\* H2) ==> (H1' \\* H2').\nProof. Admitted.\n\nLemma himpl_hstar_trans_l {H1 H2 H3 H4} :\n  H1 ==> H2 →\n  H2 \\* H3 ==> H4 →\n  H1 \\* H3 ==> H4.\nProof. Admitted.\n\nLemma himpl_hstar_trans_r {H1 H2 H3 H4} :\n  H1 ==> H2 →\n  H3 \\* H2 ==> H4 →\n  H3 \\* H1 ==> H4.\nProof. Admitted.\n\n(* ---------------------------------------------------------------------- *)\n(** Properties of [hpure] *)\n\nLemma hstar_hpure_r {P H h} :\n  (H \\* \\[P]) h = (H h ∧ P).\nProof. Admitted.\n\n(* backward compatibility *)\nDefinition hstar_hpure {P H h} := @hstar_hpure_l P H h.\n\n  (* corollary only used for the SL course *)\nLemma hstar_hpure_iff {P H h} :\n  (\\[P] \\* H) h ↔ (P ∧ H h).\nProof. Admitted.\n\nLemma himpl_hstar_hpure_r {P H H'} :\n  P →\n  (H ==> H') →\n  H ==> (\\[P] \\* H').\nProof. Admitted.\n\nLemma hpure_inv_hempty {P h} :\n  \\[P] h →\n  P ∧ \\[] h.\nProof. Admitted.\n\nLemma hpure_intro_hempty {P h} :\n  \\[] h →\n  P →\n  \\[P] h.\nProof. Admitted.\n\nLemma himpl_hempty_hpure {P} :\n  P →\n  \\[] ==> \\[P].\nProof. Admitted.\n\nLemma himpl_hstar_hpure_l {P H H'} :\n  (P → H ==> H') →\n  (\\[P] \\* H) ==> H'.\nProof. Admitted.\n\nLemma hempty_eq_hpure_true :\n  \\[] = \\[True].\nProof. Admitted.\n\nLemma hfalse_hstar_any {H} :\n  \\[False] \\* H = \\[False].\nProof. Admitted.\n\nLemma hpure_eq_hexists_empty {P} :\n  \\[P] = (\\exists (p : P), \\[]).\nProof. auto. Qed.\n\n(* ---------------------------------------------------------------------- *)\n(** Properties of [hexists] *)\n\nLemma himpl_hexists_l {A H} {J : A → hprop} :\n  (∀ x, J x ==> H) →\n  (hexists J) ==> H.\nProof. Admitted.\n\nLemma himpl_hexists_r {A} {x : A} {H J} :\n  (H ==> J x) →\n  H ==> (hexists J).\nProof. Admitted.\n\nLemma himpl_hexists {A} {J1 J2 : A → hprop} :\n  J1 ===> J2 →\n  hexists J1 ==> hexists J2.\nProof. Admitted.\n\n(* ---------------------------------------------------------------------- *)\n(** Properties of [hforall] *)\n\nLemma himpl_hforall_r {A} {J : A → hprop} {H} :\n  (∀ x, H ==> J x) →\n  H ==> (hforall J).\nProof. Admitted.\n\nLemma himpl_hforall_l {A x} {J : A → hprop} {H} :\n  (J x ==> H) →\n  (hforall J) ==> H.\nProof. Admitted.\n\nLemma himpl_hforall_l_exists {A} {J : A → hprop} {H} :\n  (exists x, J x ==> H) →\n  (hforall J) ==> H.\nProof. Admitted.\n\nLemma himpl_hforall {A} {J1 J2 : A → hprop} :\n  J1 ===> J2 →\n  hforall J1 ==> hforall J2.\nProof. Admitted.\n\nLemma hforall_specialize {A} {x : A} {J : A → hprop} :\n  (hforall J) ==> (J x).\nProof. Admitted.\n\n(* ---------------------------------------------------------------------- *)\n(** Properties of hwand (others are found further in the file) *)\n\nLemma hwand_eq_hexists {H1 H2} :\n  (H1 \\-* H2) = (\\exists H, H \\* \\[H1 \\* H ==> H2]).\nProof. auto. Qed.\n\nLemma hwand_equiv {H0 H1 H2} :\n  (H0 ==> H1 \\-* H2) ↔ (H1 \\* H0 ==> H2).\nProof. Admitted.\n\nLemma himpl_hwand_r {H1 H2 H3} :\n  H2 \\* H1 ==> H3 →\n  H1 ==> (H2 \\-* H3).\nProof. Admitted.\n\nLemma himpl_hwand_r_inv {H1 H2 H3} :\n  H1 ==> (H2 \\-* H3) →\n  H2 \\* H1 ==> H3.\nProof. Admitted.\n\nLemma hwand_cancel {H1 H2} :\n  H1 \\* (H1 \\-* H2) ==> H2.\nProof. Admitted.\n\nArguments hwand_cancel : clear implicits.\n\nLemma himpl_hempty_hwand_same {H} :\n  \\[] ==> (H \\-* H).\nProof. Admitted.\n\nLemma hwand_hempty_l {H} :\n  (\\[] \\-* H) = H.\nProof. Admitted.\n\nLemma hwand_hpure_l {P H} :\n  P →\n  (\\[P] \\-* H) = H.\nProof. Admitted.\n\nArguments hwand_hpure_l : clear implicits.\n\nLemma hwand_curry {H1 H2 H3} :\n  (H1 \\* H2) \\-* H3 ==> H1 \\-* (H2 \\-* H3).\nProof. Admitted.\n\nLemma hwand_uncurry {H1 H2 H3} :\n  H1 \\-* (H2 \\-* H3) ==> (H1 \\* H2) \\-* H3.\nProof. Admitted.\n\nLemma hwand_curry_eq {H1 H2 H3} :\n  (H1 \\* H2) \\-* H3 = H1 \\-* (H2 \\-* H3).\nProof. Admitted.\n\n(* ---------------------------------------------------------------------- *)\n(** Properties of [qwand] *)\n\nLemma qwand_equiv {H A} {Q1 Q2 : A → hprop} :\n  H ==> (Q1 \\--* Q2) ↔ (Q1 \\*+ H) ===> Q2.\nProof. Admitted.\n\nLemma himpl_qwand_r {A} {Q1 Q2 : A → hprop} {H} :\n  Q1 \\*+ H ===> Q2 →\n  H ==> (Q1 \\--* Q2).\nProof. Admitted.\n\nArguments himpl_qwand_r [A].\n\nLemma qwand_specialize {A} {x : A} {Q1 Q2 : A → hprop} :\n  (Q1 \\--* Q2) ==> (Q1 x \\-* Q2 x).\nProof. Admitted.\n\nArguments qwand_specialize [ A ].\n\n(* ---------------------------------------------------------------------- *)\n(** Properties of [htop] *)\n\nLemma htop_intro {h} :\n  \\Top h.\nProof. Admitted.\n\nLemma himpl_htop_r {H} :\n  H ==> \\Top.\nProof. Admitted.\n\nLemma htop_eq :\n  \\Top = (\\exists H, H).\nProof. auto. Qed.\n\nLemma hstar_htop_htop :\n  \\Top \\* \\Top = \\Top.\nProof. Admitted.\n\n(* ---------------------------------------------------------------------- *)\n(* ** Properties of [hor] *)\n\nLemma hor_eq_exists_bool {H1 H2} :\n  hor H1 H2 = \\exists (b : bool), if b then H1 else H2.\nProof. auto. Qed.\n\nLemma hor_sym {H1 H2} :\n  hor H1 H2 = hor H2 H1.\nProof. Admitted.\n\nLemma himpl_hor_r_r {H1 H2} :\n  H1 ==> hor H1 H2.\nProof. Admitted.\n\nLemma himpl_hor_r_l {H1 H2} :\n  H2 ==> hor H1 H2.\nProof. Admitted.\n\nLemma himpl_hor_l {H1 H2 H3} :\n  H1 ==> H3 →\n  H2 ==> H3 →\n  hor H1 H2 ==> H3.\nProof. Admitted.\n\n#[global] Opaque hor.\n\n(* ---------------------------------------------------------------------- *)\n(* ** Properties of [hand] *)\n\nLemma hand_eq_forall_bool {H1 H2} :\n  hand H1 H2 = \\forall (b : bool), if b then H1 else H2.\nProof. auto. Qed.\n\nLemma hand_sym {H1 H2} :\n  hand H1 H2 = hand H2 H1.\nProof. Admitted.\n\nLemma himpl_hand_l_r {H1 H2} :\n  hand H1 H2 ==> H1.\nProof. Admitted.\n\nLemma himpl_hand_l_l {H1 H2} :\n  hand H1 H2 ==> H2.\nProof. Admitted.\n\nLemma himpl_hand_r {H1 H2 H3} :\n  H3 ==> H1 →\n  H3 ==> H2 →\n  H3 ==> hand H1 H2.\nProof. Admitted.\n\n#[global] Opaque hand.\n\n(** Experimental tactic [xsimpl_hand] *)\n\n(* Tactic Notation \"xsimpl_hand\" := *)\n(*    xsimpl; try (applys himpl_hand_r; xsimpl). *)\n\n(* ---------------------------------------------------------------------- *)\n(* ** Set operators to be opaque *)\n\n#[global] Opaque hempty hpure hstar hexists htop hand hor.\n\n(* ********************************************************************** *)\n(* * More properties of the magic wand *)\n\n(* ---------------------------------------------------------------------- *)\n(* ** Properties of [hwand] *)\n\nLemma hwand_eq_hexists_hstar_hpure {H1 H2} :\n  (H1 \\-* H2) = (\\exists H, H \\* \\[H1 \\* H ==> H2]).\nProof. auto. Qed.\n\nLemma hwand_himpl {H1 H1' H2 H2'} :\n  H1' ==> H1 →\n  H2 ==> H2' →\n  (H1 \\-* H2) ==> (H1' \\-* H2').\nProof. Admitted.\n\nLemma hwand_himpl_r {H1 H2 H2'} :\n  H2 ==> H2' →\n  (H1 \\-* H2) ==> (H1 \\-* H2').\nProof. Admitted.\n\nLemma hwand_himpl_l {H1' H1 H2} :\n  H1' ==> H1 →\n  (H1 \\-* H2) ==> (H1' \\-* H2).\nProof. Admitted.\n\nLemma hwand_hpure_r_intro {H1 H2} {P : Prop} :\n  (P → H1 ==> H2) →\n  H1 ==> (\\[P] \\-* H2).\nProof. Admitted.\n\nLemma hstar_hwand {H1 H2 H3} :\n  (H1 \\-* H2) \\* H3 ==> H1 \\-* (H2 \\* H3).\nProof. Admitted.\n\nArguments hstar_hwand : clear implicits.\n\n(* ---------------------------------------------------------------------- *)\n(* ** Properties of [qwand] *)\n\nLemma himpl_qwand_hstar_same_r {A} {Q : A → hprop} {H} :\n  H ==> Q \\--* (Q \\*+ H).\nProof. Admitted.\n\nLemma himpl_qwand_r_inv {H A} {Q1 Q2 : A → hprop} :\n  H ==> (Q1 \\--* Q2) →\n  (Q1 \\*+ H) ===> Q2.\nProof. Admitted.\n\nLemma hstar_qwand {H A} {Q1 Q2 : A → hprop} :\n  (Q1 \\--* Q2) \\* H ==> Q1 \\--* (Q2 \\*+ H).\nProof. Admitted.\n\nLemma qwand_cancel {A} {Q1 Q2 : A → hprop} :\n  Q1 \\*+ (Q1 \\--* Q2) ===> Q2.\nProof. Admitted.\n\nLemma qwand_cancel_part {H A} {Q1 Q2 : A → hprop} :\n  H \\* ((Q1 \\*+ H) \\--* Q2) ==> (Q1 \\--* Q2).\nProof. Admitted.\n\nLemma qwand_himpl {A} {Q1 Q1' Q2 Q2' : A → hprop} :\n  Q1' ===> Q1 →\n  Q2 ===> Q2' →\n  (Q1 \\--* Q2) ==> (Q1' \\--* Q2').\nProof. Admitted.\n\nLemma qwand_himpl_l {A} {Q1 Q1' Q2 : A → hprop} :\n  Q1' ===> Q1 →\n  (Q1 \\--* Q2) ==> (Q1' \\--* Q2).\nProof. Admitted.\n\nLemma qwand_himpl_r {A} {Q1 Q2 Q2' : A → hprop} :\n  Q2 ===> Q2' →\n  (Q1 \\--* Q2) ==> (Q1 \\--* Q2').\nProof. Admitted.\n\n(* ********************************************************************** *)\n(* * Tactics for heap entailments *)\n\n(* ---------------------------------------------------------------------- *)\n(** Specific cleanup for formulaes *)\n\nLtac on_formula_pre cont :=\n  match goal with\n  | |- _ ?H ?Q => cont H\n  | |- _ _ ?H ?Q => cont H\n  | |- _ _ _ ?H ?Q => cont H\n  | |- _ _ _ _ ?H ?Q => cont H\n  | |- _ _ _ _ _ ?H ?Q => cont H\n  | |- _ _ _ _ _ _ ?H ?Q => cont H\n  | |- _ _ _ _ _ _ _ ?H ?Q => cont H\n  | |- _ _ _ _ _ _ _ _ ?H ?Q => cont H\n  | |- _ _ _ _ _ _ _ _ _ ?H ?Q => cont H\n  | |- _ _ _ _ _ _ _ _ _ _ ?H ?Q => cont H\n  end.\n\nLtac on_formula_post cont :=\n  match goal with\n  | |- _ ?H ?Q => cont Q\n  | |- _ _ ?H ?Q => cont Q\n  | |- _ _ _ ?H ?Q => cont Q\n  | |- _ _ _ _ ?H ?Q => cont Q\n  | |- _ _ _ _ _ ?H ?Q => cont Q\n  | |- _ _ _ _ _ _ ?H ?Q => cont Q\n  | |- _ _ _ _ _ _ _ ?H ?Q => cont Q\n  | |- _ _ _ _ _ _ _ _ ?H ?Q => cont Q\n  | |- _ _ _ _ _ _ _ _ _ ?H ?Q => cont Q\n  | |- _ _ _ _ _ _ _ _ _ _ ?H ?Q => cont Q\n  end.\n\n(* Ltac remove_empty_heaps_formula tt := *)\n(*   repeat (on_formula_pre ltac:(remove_empty_heaps_from)). *)\n\n(* ---------------------------------------------------------------------- *)\n(* ** Tactic [xsimplh] to prove [H h] from [H' h] *)\n\n(** [xsimplh] applies to a goal of the form [H h].\n   It looks up for an hypothesis of the form [H' h],\n   where [H'] is a heap predicate (whose type is syntactically [hprop]).\n   It then turns the goal into [H ==> H'], and calls [xsimpl].\n\n   This tactic is very useful for establishing the soundness of\n   Separation Logic derivation rules. It should never be used in\n   the verification of concrete programs, since a heap [h] should\n   never appear explicitly in such a proof, all the reasoning being\n   conducted at the level of heap predicates. *)\n\n(* Ltac xsimplh_core tt := *)\n(*   match goal with N: ?H ?h |- _ ?h => *)\n(*     match type of H with hprop => *)\n(*     applys himpl_inv N; clear N; xsimpl *)\n(*   end end. *)\n\n(* Tactic Notation \"xsimplh\" := xsimplh_core tt. *)\n(* Tactic Notation \"xsimplh\" \"~\" := xsimplh; auto_tilde. *)\n(* Tactic Notation \"xsimplh\" \"*\" := xsimplh; auto_star. *)\n\n(* ********************************************************************** *)\n(** * Predicate [local] *)\n\n(* ---------------------------------------------------------------------- *)\n(* ** Definition of [local] *)\n\n(** Type of characteristic formulae on values of type B *)\n\nNotation \"'~~' B + E\" := (hprop → (B → hprop) → (E → Prop) → Prop)\n  (at level 8, B at next level, E at next level, only parsing) : type_scope.\n\n(** A formula [F] is mklocal (e.g. [F] could be the predicate SL [triple])\n    if it is sufficient for establishing [F H Q] to establish that the\n    the formula holds on a subheap, in the sense that [F H1 Q1] with\n    [H = H1 \\* H2] and [Q = Q1 \\*+ H2]. *)\n\nDefinition local {B E} (F : ~~B+E) : Prop :=\n  ∀ H Q Z,\n    (H ==> \\exists H1 H2 Q1, H1 \\* H2 \\*\n             \\[F H1 Q1 Z ∧ Q1 \\*+ H2 ===> Q]) →\n    F H Q Z.\n\n(** [local_pred S] asserts that [local (S x)] holds for any [x].\n    It is useful for describing loop invariants. *)\n\nDefinition local_pred {A B E} (S : A → ~~B+E) :=\n  ∀ x, local (S x).\n\n(* ---------------------------------------------------------------------- *)\n(* ** Properties of [local] *)\n\n(** Remark: for conciseness, we abbreviate names of lemmas,\n    e.g. [local_inv_frame] is named [mklocal_conseq_frame]. *)\n\nSection IsLocal.\n\nVariables B E : Type.\nImplicit Types (F : ~~B+E).\n\n(** A introduction rule to establish [local], exposing the definition *)\n\nLemma local_intro {F} :\n  (∀ H Q Z,\n    (H ==> \\exists H1 H2 Q1, H1 \\* H2 \\*\n             \\[F H1 Q1 Z ∧ Q1 \\*+ H2 ===> Q]) →\n    F H Q Z) →\n  local F.\nProof. auto. Qed.\n\n(** An elimination rule for [local] *)\n\nLemma local_elim {F H Q Z} :\n  local F →\n  (H ==> \\exists H1 H2 Q1, H1 \\* H2 \\* \\[F H1 Q1 Z ∧ Q1 \\*+ H2 ===> Q]) →\n  F H Q Z.\nProof. auto. Qed.\n\n(** An elimination rule for [local] without [htop] *)\n\nLemma local_elim_frame {F H Q Z} :\n  local F →\n  (H ==> \\exists H1 H2 Q1, H1 \\* H2 \\* \\[F H1 Q1 Z ∧ Q1 \\*+ H2 ===> Q]) →\n  F H Q Z.\nProof. Admitted.\n\n(** An elimination rule for [local] specialized for no frame, and no [htop] *)\n\nLemma local_elim_conseq_pre {F H Q Z} :\n  local F →\n  (H ==> \\exists H1, H1 \\* \\[F H1 Q Z]) →\n  F H Q Z.\nProof. Admitted.\n\n(** Weaken and frame properties from [mklocal] *)\n\nLemma local_conseq_frame {H1 H2 Q1 F H Q Z} :\n  local F →\n  F H1 Q1 Z →\n  H ==> H1 \\* H2 →\n  Q1 \\*+ H2 ===> Q →\n  F H Q Z.\nProof. Admitted.\n\n(** Frame rule *)\n\nLemma local_frame {H2 Q1 Z H1 F} :\n  local F →\n  F H1 Q1 Z →\n  F (H1 \\* H2) (Q1 \\*+ H2) Z.\nProof. Admitted.\n\n(** Ramified frame rule *)\n\nLemma local_ramified_frame {Q1 H1 F H Q Z} :\n  local F →\n  F H1 Q1 Z →\n  H ==> H1 \\* (Q1 \\--* Q) →\n  F H Q Z.\nProof. Admitted.\n\n(** Consequence rule *)\n\nLemma local_conseq {H' Q' F H Q Z} :\n  local F →\n  F H' Q' Z →\n  H ==> H' →\n  Q' ===> Q →\n  F H Q Z.\nProof. Admitted.\n\n(** Weakening on pre from [mklocal] *)\n\nLemma local_conseq_pre {H' F H Q Z} :\n  local F →\n  F H' Q Z →\n  H ==> H' →\n  F H Q Z.\nProof. Admitted.\n\n(** Weakening on post from [mklocal] *)\n\nLemma local_conseq_post {Q' F H Q Z} :\n  local F →\n  F H Q' Z →\n  Q' ===> Q →\n  F H Q Z.\nProof. Admitted.\n\n(** Extraction of pure facts from [mklocal] *)\n\nLemma local_hpure {F H P Q Z} :\n  local F →\n  (P → F H Q Z) →\n  F (\\[P] \\* H) Q Z.\nProof. Admitted.\n\n(** Extraction of existentials from [mklocal] *)\n\nLemma local_hexists {F A} {J : A → hprop} {Q Z} :\n  local F →\n  (∀ x, F (J x) Q Z) →\n  F (hexists J) Q Z.\nProof. Admitted.\n\n(** Extraction of existentials below a star from [mklocal] *)\n\nLemma local_hstar_hexists {F H A} {J : A → hprop} {Q Z} :\n  local F →\n  (∀ x, F ((J x) \\* H) Q Z) →\n   F (hexists J \\* H) Q Z.\nProof. Admitted.\n\n(** Extraction of forall from [mklocal] *)\n\nLemma local_hforall {A} {x : A} {F} {J : A → hprop} {Q Z} :\n  local F →\n  F (J x) Q Z →\n  F (hforall J) Q Z.\nProof. Admitted.\n\nLemma local_hforall_exists {F A} {J : A → hprop} {Q Z} :\n  local F →\n  (exists x, F (J x) Q Z) →\n  F (hforall J) Q Z.\nProof. Admitted.\n\n(** Extraction of forall below a star from [mklocal] *)\n(* --TODO needed? *)\n\nLemma local_hstar_hforall_l {F H A} {J : A → hprop} {Q Z} :\n  local F →\n  (exists x, F ((J x) \\* H) Q Z) →\n  F (hforall J \\* H) Q Z.\nProof. Admitted.\n\n(** Case analysis for [hor] *)\n\nLemma local_hor {F H1 H2 Q Z} :\n  local F →\n  F H1 Q Z →\n  F H2 Q Z →\n  F (hor H1 H2) Q Z.\nProof. Admitted.\n\n(** Left branch for [hand] *)\n\nLemma local_hand_l {F H1 H2 Q Z} :\n  local F →\n  F H1 Q Z →\n  F (hand H1 H2) Q Z.\nProof. Admitted.\n\n(** Right branch for [hand] *)\n\nLemma local_hand_r {F H1 H2 Q Z} :\n  local F →\n  F H2 Q Z →\n  F (hand H1 H2) Q Z.\nProof. Admitted.\n\n(** Extraction of heap representation from [mklocal] *)\n\nLemma local_name_heap {F H Q Z} :\n  local F →\n  (∀ h, H h → F (λ h', h' = h) Q Z) →\n  F H Q Z.\nProof. Admitted.\n\n(** Extraction of pure facts from the precondition under local *)\n\nLemma local_prop {F H Q P Z} :\n  local F →\n  (H ==> H \\* \\[P]) →\n  (P → F H Q Z) →\n  F H Q Z.\nProof. Admitted.\n\n(** Extraction of proof obligations from the precondition under local *)\n\nLemma local_hwand_hpure_l {F} {P : Prop} {H Q Z} :\n  local F →\n  P →\n  F H Q Z →\n  F (\\[P] \\-* H) Q Z.\nProof. Admitted.\n\nEnd IsLocal.\n\n#[global] Opaque local.\n\n(** [xtpull] plays a similar role to [xpull], except that it works on\n   goals of the form [F H Q], where [F] is typically a triple predicate\n   or a characteristic formula.\n\n   [xtpull] simplifies the precondition [H] as follows:\n   - it removes empty heap predicates\n   - it pulls pure facts out as hypotheses into the context\n   - it pulls existentials as variables into the context.\n\n   At the end, it regeneralizes in the goals the new variables\n   from the context, so as to allow the user to introduce them\n   by giving appropriate names. *)\n\n(** Lemmas *)\n\nLemma xtpull_start {B E} {F : ~~B+E} {H Q Z} :\n  F (\\[] \\* H) Q Z →\n  F H Q Z.\nProof. Admitted.\n\nLemma xtpull_keep {B E} {F : ~~B+E} {H1 H2 H3 Q Z} :\n  F ((H2 \\* H1) \\* H3) Q Z →\n  F (H1 \\* (H2 \\* H3)) Q Z.\nProof. Admitted.\n\nLemma xtpull_assoc {B E} {F : ~~B+E} {H1 H2 H3 H4 Q Z} :\n  F (H1 \\* (H2 \\* (H3 \\* H4))) Q Z →\n  F (H1 \\* ((H2 \\* H3) \\* H4)) Q Z.\nProof. Admitted.\n\nLemma xtpull_starify {B E} {F : ~~B+E} {H1 H2 Q Z} :\n  F (H1 \\* (H2 \\* \\[])) Q Z →\n  F (H1 \\* H2) Q Z.\nProof. Admitted.\n\nLemma xtpull_empty {B E} {F : ~~B+E} {H1 H2 Q Z} :\n  (F (H1 \\* H2) Q Z) →\n  F (H1 \\* (\\[] \\* H2)) Q Z.\nProof. Admitted.\n\nLemma xtpull_hpure {B E} {F : ~~B+E} {H1 H2 P Q Z} :\n  local F →\n  (P → F (H1 \\* H2) Q Z) →\n  F (H1 \\* (\\[P] \\* H2)) Q Z.\nProof. Admitted.\n\n(* Lemma xtpull_id {A} {x X : A} {B E} {F : ~~B+E} {H1 H2 Q Z} : *)\n(*   local F → *)\n(*   (x = X → F (H1 \\* H2) Q Z) → *)\n(*   F (H1 \\* (x ~> Id X \\* H2)) Q Z. *)\n(* Proof. Admitted. *)\n\nLemma xtpull_hexists {B E} {F : ~~B+E} {H1 H2 A} {J : A → hprop} {Q Z} :\n  local F →\n  (∀ x, F (H1 \\* ((J x) \\* H2)) Q Z) →\n   F (H1 \\* (hexists J \\* H2)) Q Z.\nProof. Admitted.\n\n(*--------------------------------------------------------*)\n(* ** [xtchange] *)\n\n(** [xtchange E] applies to a goal of the form [F H Q]\n    and to a lemma [E] of type [H1 ==> H2] or [H1 = H2].\n    It replaces the goal with [F H' Q], where [H']\n    is computed by replacing [H1] with [H2] in [H].\n\n    The substraction is computed by solving [H ==> H1 \\* ?H']\n    with [xsimpl]. If you need to solve this implication by hand,\n    use [xtchange_no_simpl E] instead.\n\n    [xtchange <- E] is useful when [E] has type [H2 = H1]\n      instead of [H1 = H2].\n\n    [xtchange_show E] is useful to visualize the instantiation\n    of the lemma used to implement [xtchange].\n    *)\n\n(* Lemma used by [xtchange] *)\n\nLemma xtchange_lemma {H1 H1' H2 B E H Q Z} {F : ~~B+E} :\n  local F →\n  (H1 ==> H1') →\n  (H ==> H1 \\* H2) →\n  F (H1' \\* H2) Q Z →\n  F H Q Z.\nProof. Admitted.\n\n(* ********************************************************************** *)\n(* * Iterated star *)\n\n(* ---------------------------------------------------------------------- *)\n(** Separation commutative monoid [(hstar,hempty)] *)\n\n(* jww (2022-08-10): TODO: Semigroup, Monoid, Commutative Monoid *)\n(* Definition sep_monoid := monoid_make hstar hempty. *)\n\n(* ********************************************************************** *)\n(* * Weakest-preconditions *)\n\n(* ---------------------------------------------------------------------- *)\n(* ** Definition of the weakest precondition for a formula *)\n\nDefinition weakestpre {B E : Type}\n  (F : ~~ B+E) (Q : B → hprop) (Z : E → Prop) : hprop :=\n  \\exists (H:hprop), H \\* \\[F H Q Z].\n\nLemma weakestpre_eq {B E} {F : ~~B+E} {H Q Z} :\n  local F → (* in fact, only requires weaken-pre and extract-hexists rules to hold *)\n  F H Q Z = (H ==> weakestpre F Q Z).\nProof. Admitted.\n\nLemma weakestpre_conseq {B E} {F : ~~B+E} {Q1 Q2 Z} :\n  local F →\n  Q1 ===> Q2 →\n  weakestpre F Q1 Z ==> weakestpre F Q2 Z.\nProof. Admitted.\n\nLemma weakestpre_conseq_wand {B E} {F : ~~B+E} {Q1 Q2 Z} :\n  local F →\n  (Q1 \\--* Q2) \\* weakestpre F Q1 Z ==> weakestpre F Q2 Z.\nProof. Admitted.\n\nLemma weakestpre_frame {B E} {F : ~~B+E} {H Q Z} :\n  local F →\n  (weakestpre F Q Z) \\* H ==> weakestpre F (Q \\*+ H) Z.\nProof. Admitted.\n\nLemma weakestpre_pre {B E} {F : ~~B+E} {Q Z} :\n  local F →\n  F (weakestpre F Q Z) Q Z.\nProof. Admitted.\n\nLemma himpl_weakestpre {B E} {F : ~~B+E} {H Q Z} :\n  F H Q Z →\n  H ==> weakestpre F Q Z.\nProof. Admitted.\n\nEnd Hoare.\n\nRequire Import\n  Pact.Lib\n  Pact.Ltac\n  Pact.Ty\n  Pact.Exp\n  Pact.Lang\n  Pact.SemTy\n  Pact.SemExp.\n\nSection Sep.\n\nDefinition heap : Type := PactState.\nDefinition val  : Ty → Type := Φ.\n\nContext `{HL : HoareLogic heap}.\n\nDefinition vprop τ : Type := val τ → hprop.\nDefinition eprop   : Type := Err → Prop.\n\nOpen Scope hoare_scope.\n\nDefinition eimpl (Z1 Z2 : Err → Prop) : Prop :=\n  ∀ e : Err, Z1 e → Z2 e.\n\nInfix \"==!>\" := eimpl (at level 55, right associativity) : hoare_scope.\n\nImplicit Type h : heap.\nImplicit Type H : hprop.\nImplicit Type Z : eprop.\nImplicit Type P : Prop.\n\nImport ListNotations.\n\nDefinition hoare `(e : Exp SemTy τ) H Q Z : Prop :=\n  ∀ h : heap, H h →\n    match ⟦e⟧ h : Err + ⟦τ⟧ * heap with\n    | inr (v, h') => Q v h'\n    | inl err => Z err\n    end.\n\nLemma hoare_conseq {τ} {t : Exp SemTy τ} {H' Q' H Q Z} :\n  hoare t H' Q' Z ->\n  H ==> H' ->\n  Q' ===> Q ->\n  hoare t H Q Z.\nProof. Admitted.\n\nLemma hoare_named_heap {τ} {t : Exp SemTy τ} {H Q Z} :\n  (∀ h, H h -> hoare t (λ h', h' = h) Q Z) ->\n  hoare t H Q Z.\nProof. Admitted.\n\n(*\nLemma hoare_val : ∀ v H Q,\n  H ==> Q v ->\n  hoare (trm_val v) H Q.\n\nLemma hoare_fun : ∀ x t1 H Q,\n  H ==> Q (val_fun x t1) ->\n  hoare (trm_fun x t1) H Q.\n\nLemma hoare_let : ∀ z t1 t2 H Q Q1,\n  hoare t1 H Q1 ->\n  (∀ v, hoare (subst1 z v t2) (Q1 v) Q) ->\n  hoare (trm_let z t1 t2) H Q.\n\nLemma hoare_seq : ∀ t1 t2 H Q H1,\n  hoare t1 H (fun r => H1) ->\n  hoare t2 H1 Q ->\n  hoare (trm_seq t1 t2) H Q.\n\nLemma hoare_if : ∀ (b:bool) t1 t2 H Q,\n  hoare (if b then t1 else t2) H Q ->\n  hoare (trm_if b t1 t2) H Q.\n\nLemma hoare_if_trm : ∀ Q1 t0 t1 t2 H Q,\n  hoare t0 H Q1 ->\n  (∀ v, hoare (trm_if v t1 t2) (Q1 v) Q) ->\n  hoare (trm_if t0 t1 t2) H Q.\n\nLemma hoare_apps_funs : ∀ xs F vs t1 H Q,\n  F = (val_funs xs t1) ->\n  var_funs xs (length vs) ->\n  hoare (substn xs vs t1) H Q ->\n  hoare (trm_apps F vs) H Q.\n*)\n\nDefinition quadruple {τ} (t : Exp SemTy τ) (H : hprop) (Q : val τ → hprop) Z :=\n  ∀ H', hoare t (H \\* H') (Q \\*+ H') Z.\n\n(* jww (2022-08-10): TODO *)\n(* Lemma local_quadruple {τ} (t : Exp SemTy τ) : *)\n(*   local (quadruple t). *)\n\nLemma triple_of_hoare {τ} {t : Exp SemTy τ} {H Q Z} :\n  (∀ H', exists Q', hoare t (H \\* H') Q' Z ∧ Q' ===> Q \\*+ H') →\n  quadruple t H Q Z.\nProof. Admitted.\n\nLemma hoare_of_quadruple {τ} {t : Exp SemTy τ} {H Q Z HF} :\n  quadruple t H Q Z →\n  hoare t (H \\* HF) (fun r => Q r \\* HF) Z.\nProof. Admitted.\n\nLemma quadruple_conseq {τ} {t : Exp SemTy τ} {H' Q' H Q Z} :\n  quadruple t H' Q' Z →\n  H ==> H' →\n  Q' ===> Q →\n  quadruple t H Q Z.\nProof. Admitted.\n\nLemma quadruple_frame {τ} {t : Exp SemTy τ} {H Q Z H'} :\n  quadruple t H Q Z →\n  quadruple t (H \\* H') (Q \\*+ H') Z.\nProof. Admitted.\n\nLemma quadruple_ramified_frame {τ} {t : Exp SemTy τ} {H1 Q1 H Q Z} :\n  quadruple t H1 Q1 Z →\n  H ==> H1 \\* (Q1 \\--* Q) →\n  quadruple t H Q Z.\nProof. Admitted.\n\nLemma quadruple_hexists {τ} {t : Exp SemTy τ} {A : Type} {J : A → hprop} {Q Z} :\n  (∀ x, quadruple t (J x) Q Z) →\n  quadruple t (hexists J) Q Z.\nProof. Admitted.\n\nLemma quadruple_hforall {A} {x : A} {τ} {t : Exp SemTy τ} {J : A → hprop} {Q Z} :\n  quadruple t (J x) Q Z →\n  quadruple t (hforall J) Q Z.\nProof. Admitted.\n\nLemma quadruple_hpure {τ} {t : Exp SemTy τ} {P : Prop} {H Q Z} :\n  (P → quadruple t H Q Z) →\n  quadruple t (\\[P] \\* H) Q Z.\nProof. Admitted.\n\nLemma quadruple_hwand_hpure_l {τ} {t : Exp SemTy τ} {P : Prop} {H Q Z} :\n  P →\n  quadruple t H Q Z →\n  quadruple t (\\[P] \\-* H) Q Z.\nProof. Admitted.\n\nLemma quadruple_hor {τ} {t : Exp SemTy τ} {H1 H2 Q Z} :\n  quadruple t H1 Q Z →\n  quadruple t H2 Q Z →\n  quadruple t (hor H1 H2) Q Z.\nProof. Admitted.\n\nLemma quadruple_hand_l {τ} {t : Exp SemTy τ} {H1 H2 Q Z} :\n  quadruple t H1 Q Z →\n  quadruple t (hand H1 H2) Q Z.\nProof. Admitted.\n\nLemma quadruple_hand_r {τ} {t : Exp SemTy τ} {H1 H2 Q Z} :\n  quadruple t H2 Q Z →\n  quadruple t (hand H1 H2) Q Z.\nProof. Admitted.\n\nLemma quadruple_conseq_frame {τ} {t : Exp SemTy τ} {H2 H1 Q1 H Q Z} :\n  quadruple t H1 Q1 Z →\n  H ==> H1 \\* H2 →\n  Q1 \\*+ H2 ===> Q →\n  quadruple t H Q Z.\nProof. Admitted.\n\n(*\nLemma quadruple_val {v H Q Z} :\n  H ==> Q v →\n  quadruple (trm_val v) H Q.\nProof.\n  introv M. intros HF. applys hoare_val. { xchanges M. }\nQed.\n\nLemma quadruple_let {z t1 t2 H Q Q1} :\n  quadruple t1 H Q1 →\n  (∀ (X:val), quadruple (subst1 z X t2) (Q1 X) Q) →\n  quadruple (trm_let z t1 t2) H Q.\nProof.\n  introv M1 M2. intros HF. applys hoare_let.\n  { applys M1. }\n  { intros v. applys* hoare_of_quadruple. }\nQed.\n\nLemma quadruple_seq {t1 t2 H Q Q1} :\n  quadruple t1 H Q1 →\n  (∀ (X:val), quadruple t2 (Q1 X) Q) →\n  quadruple (trm_seq t1 t2) H Q.\nProof.\n  introv M1 M2. applys* quadruple_let. (* BIND intros. rewrite* subst1_anon. *)\nQed.\n\nLemma quadruple_if {(b:bool) t1 t2 H Q Z} :\n  quadruple (if b then t1 else t2) H Q →\n  quadruple (trm_if b t1 t2) H Q.\nProof.\n  introv M1. intros HF. applys hoare_if. applys M1.\nQed.\n\nLemma quadruple_if_bool {(b:bool) t1 t2 H Q Z} :\n  (b = true → quadruple t1 H Q) →\n  (b = false → quadruple t2 H Q) →\n  quadruple (trm_if b t1 t2) H Q.\nProof.\n  introv M1 M2. applys quadruple_if. case_if*.\nQed.\n\nLemma quadruple_if_trm {Q1 t0 t1 t2 H Q Z} :\n  quadruple t0 H Q1 →\n  (∀ v, quadruple (trm_if v t1 t2) (Q1 v) Q) →\n  quadruple (trm_if t0 t1 t2) H Q.\nProof.\n  introv M1 M2. intros HF. applys* hoare_if_trm.\n  { intros v. applys* hoare_of_quadruple. }\nQed.\n\nLemma quadruple_if_trm' {Q1 t0 t1 t2 H Q, (* not very useful *)\n  quadruple t0 H Q1 →\n  (∀ (b:bool), quadruple (if b then t1 else t2) (Q1 b) Q) →\n  (∀ v, ~ is_val_bool v → (Q1 v) ==> \\[False]) →\n  quadruple (trm_if t0 t1 t2) H Q.\nProof.\n  introv M1 M2 M3. applys* quadruple_if_trm.\n  { intros v. tests C: (is_val_bool v).\n    { destruct C as (b&E). subst. applys* quadruple_if. }\n    { xtchange* M3. xtpull ;=>. false. } }\nQed.\n\nLemma quadruple_apps_funs {xs F (Vs:vals) t1 H Q Z} :\n  F = (val_funs xs t1) →\n  var_funs xs (length Vs) →\n  quadruple (substn xs Vs t1) H Q →\n  quadruple (trm_apps F Vs) H Q.\nProof. introv E N M. intros HF. applys* hoare_apps_funs. Qed.\n*)\n\nDefinition formula τ := (val τ → hprop) → eprop → hprop.\n\nDefinition wp `(t : Exp SemTy τ) : formula τ :=\n  weakestpre (quadruple t).\n\nDefinition WP : Type := ∀ τ (t : Exp (Φ) τ), formula τ.\n\nDefinition formula' (B E : Type) := (B → hprop) → (E → Prop) → hprop.\n\nDeclare Scope pred_scope.\nOpen Scope pred_scope.\n\nNotation \"{{ H }} x ← e { Q | Z }\" :=\n  (hoare e H (λ x, Q) Z) (at level 1, e at next level) : pred_scope.\n\n#[local] Hint Unfold hoare : core.\n\nTheorem hoare_post_true H `(Q : vprop τ) Z e :\n  (∀ v s, Q v s) →\n  (∀ err, Z err) →\n  {{H}} x ← e {Q x|Z}.\nProof.\n  unfold hoare; sauto.\nQed.\n\nTheorem hoare_pre_false H `(Q : vprop τ) Z e :\n  (∀ s, ¬ (H s)) →\n  {{H}} x ← e {Q x|Z}.\nProof.\n  autounfold; intros.\n  intuition.\nQed.\n\nLtac heaps :=\n  repeat\n    match goal with\n    | [ H : (_ \\* _) _  |- _ ] => destruct H\n    | [ H : (\\exists _, _) _  |- _ ] => destruct H\n    | [ H : \\[ _ ] _ |- _ ] => inversion H; subst; clear H\n    end; reduce.\n\nTheorem wp_equiv {H} `{e : Exp SemTy τ} {Q : vprop τ} {Z} :\n  (H ==> wp e Q Z) ↔ (quadruple e H Q Z).\nProof.\n  unfold himpl, wp, weakestpre, quadruple.\n  split; repeat intro.\n  - heaps.\n    specialize (H0 _ H1).\n    heaps.\n    heaps.\n    rewrite heap_compat_union_l_eq in H3; auto.\n    reduce.\n    rewrite heap_union_empty_r in H1.\n    rewrite heap_union_empty_r.\n    assert ((x1 \\* H') (x2 \\u x0))\n      by now apply hstar_intro.\n    unshelve epose proof (x _ _ H6); auto.\n  - repeat eexists; eauto.\n    apply heap_compat_empty_r.\n    now rewrite heap_union_empty_r.\nQed.\n\nTheorem wp_unique {wp1 wp2 : WP} :\n  (∀ H τ (e : Exp SemTy τ) (Q : vprop τ) Z,\n     quadruple e H Q Z ↔ H ==> wp1 _ e Q Z) →\n  (∀ H τ (e : Exp SemTy τ) (Q : vprop τ) Z,\n     quadruple e H Q Z ↔ H ==> wp2 _ e Q Z) →\n  wp1 = wp2.\nProof.\n  intros.\n  extensionality τ.\n  extensionality e.\n  extensionality Q.\n  extensionality Z.\n  apply himpl_antisym.\n  - destruct (H0 (wp1 τ e Q Z) τ e Q Z) as [H5 H6]; clear H0.\n    apply H5; intros.\n    apply H.\n    reflexivity.\n  - destruct (H (wp2 τ e Q Z) τ e Q Z) as [H5 H6]; clear H.\n    apply H5; intros.\n    apply H0.\n    reflexivity.\nQed.\n\nTheorem wp_from_weakest_pre (wp' : WP) :\n  (∀ H τ (e : Exp SemTy τ) (Q : vprop τ) Z,\n     quadruple e (wp' _ e Q Z) Q Z) →          (* wp_pre *)\n  (∀ H τ (e : Exp SemTy τ) (Q : vprop τ) Z,\n     quadruple e H Q Z → H ==> wp' _ e Q Z) → (* wp_weakest *)\n  (∀ H τ (e : Exp SemTy τ) (Q : vprop τ) Z,\n     H ==> wp' _ e Q Z ↔ quadruple e H Q Z).  (* wp_equiv *)\nProof.\n  intros M1 M2.\n  split; intro M.\n  - eapply quadruple_conseq; eauto.\n    reflexivity.\n  - eapply M2; eauto.\nQed.\n\nNotation \"e =====> e'\" :=\n  (∀ Q Z, wp e Q Z ==> wp e' Q Z) (at level 100, e' at next level) : pred_scope.\n\nLemma eval_if_trm (t0 : Exp SemTy 𝔹) v0 {τ} (t1 t2 : Exp SemTy τ)\n  (v : SemTy τ) s s' s'' :\n  t0 ~[s => s']~> v0 →\n  If (Lit (LitBool v0)) t1 t2 ~[s' => s'']~> v →\n  If t0 t1 t2 ~[s => s'']~> v.\nProof.\n  unfold eval.\n  intros.\n  simp SemExp in *; simpl in *; autounfold in *.\n  now rewrite H.\nQed.\n\nLemma hoare_if H (b : Exp SemTy 𝔹) τ (t1 t2 : Exp SemTy τ)\n  (Q' : vprop 𝔹) (Q : vprop τ) Z :\n  hoare b H Q' Z →\n  (∀ v, hoare (If (Lit (LitBool v)) t1 t2) (Q' v) Q Z) →\n  hoare (If b t1 t2) H Q Z.\nProof.\n  autounfold.\n  repeat intro.\n  simp SemExp in *; simpl in *; autounfold in *.\n  specialize (H0 _ H2).\n  destruct (⟦b⟧ _) eqn:Heqe; auto.\n  reduce.\n  specialize (H1 _ _ H0).\n  simp SemExp in *; simpl in *; autounfold in *.\n  exact H1.\nQed.\n\nLemma quadruple_if H (b : Exp SemTy 𝔹) τ (t1 t2 : Exp SemTy τ)\n  (Q' : vprop 𝔹) (Q : vprop τ) Z :\n  quadruple b H Q' Z →\n  (∀ v, quadruple (If (Lit (LitBool v)) t1 t2) (Q' v) Q Z) →\n  quadruple (If b t1 t2) H Q Z.\nProof.\n  unfold quadruple.\n  intros.\n  eapply hoare_if; eauto.\n  intros.\n  apply H1.\nQed.\n\nLtac wp r H :=\n  intros;\n  eapply wp_equiv;\n  eapply H; eauto;\n  eapply wp_equiv;\n  subst; reflexivity.\n\n(* An if statement simply propagates the environment. *)\nCorollary wp_if (b : Exp SemTy 𝔹) τ (t1 t2 : Exp SemTy τ) (Q : vprop τ) Z :\n  wp b (λ v, wp (If (Lit (LitBool v)) t1 t2) Q Z) Z\n    ==> wp (If b t1 t2) Q Z.\nProof.\n  unfold wp.\n  simpl.\n  repeat intro.\n  destruct H as [H [HH H0]].\n  exists H.\nAdmitted.\n(*\n  split; auto.\n  eapply quadruple_if; eauto; intros.\n  simpl.\n  unfold quadruple, hoare in *.\n  intros.\n  simpl in *.\n  reduce.\n  specialize (H0 _ _ (conj HH HH)).\n  destruct (⟦b⟧ _);\n  simp SemExp in *; simpl in *;\n  unravel; reduce;\n  exact (H3 _ _ (conj H1 H2)).\nQed.\n*)\n\n(*\nLemma quadruple_app_fun H `(v : Exp SemTy dom) x `(e : Exp [dom] cod)\n  (Q : vprop cod) Z :\n  (∀ s, v ~[ s => s ]~> x) →\n  quadruple ⟦ (x, tt) ⊨ e ⟧ H Q Z →\n  quadruple ⟦APP (LAM e) v⟧ H Q Z.\nProof.\n  intros.\n  repeat intro.\n  specialize (H1 _ _ H2).\n  simpl in *.\n  erewrite sem_app_lam; eauto.\nQed.\n\nLemma wp_app_fun `(v : Exp SemTy dom) x `(e : Exp [dom] cod) :\n  (∀ s, v ~[ s => s ]~> x) →\n  ⟦ (x, tt) ⊨ e ⟧ =====> ⟦APP (LAM e) v⟧.\nProof. wp r quadruple_app_fun. Qed.\n*)\n\n(* This encodes a boolean predicate in positive normal form. *)\nInductive Pred : Ty → Set :=\n  | P_True : Pred 𝔹\n  | P_False : Pred 𝔹\n  | P_Eq {τ} : Pred τ → Pred τ → Pred 𝔹\n  | P_Or : Pred 𝔹 → Pred 𝔹 → Pred 𝔹\n  | P_And : Pred 𝔹 → Pred 𝔹 → Pred 𝔹.\n\n#[local] Hint Constructors Pred : core.\n\n(*\nEquations wpc `(e : Exp SemTy τ) {τ'}\n  (Q : val τ → state → Pred τ') Z :\n  state → Pred τ' :=\n  wpc (Lit l) Q Z := Q (SemLit l);\n  (* wpc (APP f v) Q Z := wp ⟦APP f v⟧ Q Z; *)\n  wpc (Seq e1 e2) Q Z := wpc e1 (λ _, wpc e2 Q Z) Z;\n  wpc (If b t e) Q Z :=\n    wpc b (λ b', if b' then wpc t Q Z else wpc e Q Z) Z;\n  wpc _ Q Z := _.\n*)\n\n(*\nEquations wpc `(e : Exp SemTy τ) (Q : vprop τ) Z : hprop :=\n  wpc (Lit l) Q Z := Q (SemLit l);\n  wpc (APP f v) Q Z := wp ⟦APP f v⟧ Q Z;\n  wpc (Seq e1 e2) Q Z := wpc e1 (λ _, wpc e2 Q Z) Z;\n  wpc (If b t e) Q Z :=\n    wpc b (λ b', if b' then wpc t Q Z else wpc e Q Z) Z;\n  wpc _ Q Z := _.\n*)\n\nEnd Sep.\n", "meta": {"author": "kadena-io", "repo": "pact-model", "sha": "2a6ab4b3b53d7e53857aa0148f57ed86ffe9e3f4", "save_path": "github-repos/coq/kadena-io-pact-model", "path": "github-repos/coq/kadena-io-pact-model/pact-model-2a6ab4b3b53d7e53857aa0148f57ed86ffe9e3f4/src/Sep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.2457339595167568}}
{"text": "Require Import msl.msl_standard.\nRequire Import share_dec_base.\nRequire Import share_equation_system.\nRequire Import base_properties.\nRequire Import share_dec_interface.\n\nModule Interpreter (sv : SV)\n                   (Import es : EQUATION_SYSTEM sv with Module dom := Bool_Domain)\n                   (Import bf : BOOL_FORMULA sv) <: INTERPRETER sv es bf.\n\n \n Module sys_features := System_Features sv es.\n Import sys_features.\n\n Class B2F (A B : Type):= Interpret {\n  interpret : A -> B\n }.\n Implicit Arguments Interpret [A B].\n\n Definition v_int := fun (v : var) => varF v.\n Instance b2f_v : B2F _ _ := Interpret v_int.\n Definition b_int := fun b => valF b.\n Instance b2f_b : B2F _ _ := Interpret b_int.\n Definition obj_int := fun (obj : object) => \n  match obj with \n  |Vobject v => varF v \n  |Cobject c => valF c\n  end.\n Instance b2f_obj : B2F _ _ := Interpret obj_int.\n Definition eql_int := fun (eql : equality) => \n  let (obj1,obj2) := eql in\n  match (obj1,obj2) with\n  |(Cobject c1, Cobject c2) => if bool_dec c1 c2 then valF true else valF false\n  |(Vobject v, Cobject c)\n  |(Cobject c, Vobject v) => if c then varF v else negF (varF v)\n  |_ => orF (andF (interpret obj1) (interpret obj2)) \n            (andF (negF (interpret obj1)) (negF (interpret obj2)))\n  end.\n Instance b2f_eql : B2F _ _ := Interpret eql_int.\n\n Definition eqn_int := fun (eqn : equation) =>\n  match eqn with (obj1,obj2,obj3) =>\n  match (obj1,obj2,obj3) with\n  |(Cobject c1,Cobject c2, Cobject c3) => if c1 then valF (negb c2 && c3) else \n                                           if bool_dec c2 c3 then valF true else valF false  \n  |(Vobject v1, Vobject v2, Cobject true) => orF (andF (varF v1) (negF (varF v2)))\n                                                 (andF (varF v2) (negF (varF v1)))\n  |(Vobject v1, Vobject v2, Cobject false) => andF (negF (varF v1)) (negF (varF v2))\n  |(Vobject v1, Cobject true, Vobject v2) \n  |(Cobject true, Vobject v1, Vobject v2) => andF (negF (varF v1)) (varF v2)\n  |(Vobject v1, Cobject false, Vobject v2) \n  |(Cobject false, Vobject v1, Vobject v2) => interpret (Vobject v1, Vobject v2)\n  |(Vobject v, Cobject c1, Cobject c2)\n  |(Cobject c1, Vobject v, Cobject c2) => if c1 then if c2 then negF (varF v) else valF false\n                                          else interpret (Vobject v, Cobject c2)\n  |(Cobject c1, Cobject c2, Vobject v) => if c1 then if c2 then valF false else varF v\n                                          else interpret (Vobject v, Cobject c2)\n  |_ => orF (andF (negF (interpret obj1)) (interpret (obj2,obj3)))\n            (andF (interpret obj1) (andF (negF (interpret obj2)) (interpret obj3)))\n  end\n  end.\n Instance b2f_eqn : B2F _ _ := Interpret eqn_int.\n Definition list_int {A} `{@B2F A bF} :=\n  fun (l : list A) => fold_right (fun a f => andF (interpret a) f) (valF true) l.\n Instance b2f_list {A} `{@B2F A bF} : B2F _ _:= Interpret list_int.\n\n Fixpoint fold_right_nodup {A B}(f : B -> A -> A) (a : A) (l : list B) `{EqDec B}:=\n match l with\n |nil => a\n |b::l' => match in_dec eq_dec b l' with\n           |left _ => fold_right_nodup f a l'\n           |right _ => f b (fold_right_nodup f a l')\n           end\n \n end.\n\n Definition exF_quan := fun l f => fold_right_nodup exF f l.\n Definition allF_quan := fun l f => fold_right_nodup allF f l.\n \n Definition ses_int := fun (ses : sat_equation_system) =>\n  let f1    := interpret (sat_nzvars ses) in\n  let f2    := interpret (sat_equalities ses) in\n  let f3    := interpret (sat_equations ses) in\n   andF f1 (andF f2 f3).\n Instance b2f_ses : B2F _ _ := Interpret ses_int.\n\n Definition ies_int := fun (ies : impl_equation_system) =>\n  let f1    := interpret (impl_nzvars ies) in\n  let f2    := interpret (impl_equalities ies) in\n  let f3    := interpret (impl_equations ies) in\n   exF_quan (impl_exvars ies) (andF f1 (andF f2 f3)).\n Instance b2f_ies : B2F _ _ := Interpret ies_int.\n\n Definition is_int := fun (is : impl_system) =>\n  let (ies1,ies2) := is in\n  let f1 := interpret (ies1) in\n  let f2 := interpret (ies2) in\n   implF f1 f2.\n Instance b2f_is : B2F _ _ := Interpret is_int.\n\n Definition vars_interpret_spec (A : Type) `{@B2F A bF} `{varsable A var}:= \n  forall a, sublist (vars (interpret a)) (vars a).\n Class vars_interpret_prop (A : Type) `{@B2F A bF} `{varsable A var} := Vars_interpret_prop {\n  vars_int : vars_interpret_spec A\n }.\n\n Instance obj_int_vars : vars_interpret_prop object.\n Proof with try tauto.\n  constructor.\n  repeat intro. icase a...\n Qed.\n Instance var_vars : varsable var var.\n Proof.\n  constructor. intro. apply (X::nil).\n Defined.\n Lemma vars_list_var: forall (l : list var),\n  vars l = l.\n Proof with try tauto.\n  induction l...\n  simpl in *;congruence.\n Qed.\n Instance var_int_vars : vars_interpret_prop var.\n Proof with try tauto.\n  constructor.\n  repeat intro...\n Qed.\n Instance eql_int_vars : vars_interpret_prop equality.\n Proof with try tauto.\n  constructor.\n  repeat intro.\n  destruct a as [obj1 obj2].\n  icase obj1;icase obj2; try icase s0;try icase s1;simpl in *...\n Qed.\n Instance eqn_int_vars : vars_interpret_prop equation.\n Proof with try tauto.\n  constructor.\n  repeat intro.\n  destruct a as [[obj1 obj2] obj3].\n  icase obj1;icase obj2;icase obj3;\n  try icase s0;try icase s1;try icase s2;simpl in *...\n Qed.\n Instance list_int_vars {A} `{vars_interpret_prop A} : vars_interpret_prop (list A).\n Proof with try tauto.\n  constructor.\n  induction a;repeat intro;\n  simpl...\n  repeat rewrite in_app_iff.\n  generalize (vars_int a e);intro.\n  simpl in H2. rewrite in_app_iff in H2.\n  spec IHa e...\n Qed.\n\n Lemma exF_quan_vars: forall l f v,\n  In v (vars (exF_quan l f)) <-> In v (l++vars f).\n Proof with try tauto.\n  induction l;intros;unfold exF_quan in *.\n  simpl... simpl.\n  destruct (in_dec eq_dec a l);split;intros.\n  apply IHl in H...\n  destruct H;subst...\n  apply IHl. rewrite in_app_iff...\n  apply IHl... \n  simpl in H. destruct H;subst...\n  apply IHl in H...\n  destruct H;subst...\n  simpl...\n  rewrite in_app_iff in H...\n  destruct H; simpl.\n  right. apply IHl. rewrite in_app_iff...\n  right. apply IHl. rewrite in_app_iff...\n Qed.\n\n Lemma allF_quan_vars: forall l f v,\n  In v (vars (allF_quan l f)) <-> In v (l++vars f).\n Proof with try tauto.\n  induction l;intros;unfold allF_quan in *.\n  simpl... simpl.\n  destruct (in_dec eq_dec a l);split;intros.\n  apply IHl in H...\n  destruct H;subst...\n  apply IHl. rewrite in_app_iff...\n  apply IHl... \n  simpl in H. destruct H;subst...\n  apply IHl in H...\n  destruct H;subst...\n  simpl...\n  rewrite in_app_iff in H...\n  destruct H; simpl.\n  right. apply IHl. rewrite in_app_iff...\n  right. apply IHl. rewrite in_app_iff...\n Qed.\n\n Instance ses_int_vars : vars_interpret_prop sat_equation_system.\n Proof with try tauto.\n  constructor.\n  repeat intro.\n  simpl in *.\n  destruct a as [l1 l2 l3];simpl in *.\n  repeat rewrite in_app_iff in *.\n  generalize (vars_int l1 e);intro.\n  generalize (vars_int l2 e);intro.  \n  generalize (vars_int l3 e);intro.\n  assert (vars l1 = l1) by apply vars_list_var.\n  simpl in *. unfold es.var,var in *. \n  rewrite H3 in H0...\n Qed.\n\n Instance ies_int_vars : vars_interpret_prop impl_equation_system.\n Proof with try tauto.\n  constructor.\n  repeat intro.\n  simpl in *.\n  unfold ies_int in H;simpl in H.\n  rewrite exF_quan_vars in H.\n  destruct a as [l1 l2 l3 l4];simpl in *.\n  unfold ies_int in H;simpl in H.\n  repeat rewrite in_app_iff in *.\n  generalize (vars_int l2 e);intro.  \n  generalize (vars_int l3 e);intro.\n  generalize (vars_int l4 e);intro.\n  assert (vars l2 = l2) by apply vars_list_var.\n  unfold es.var,var in *.\n  rewrite H3 in H0...\n Qed.\n \n Instance is_int_vars : vars_interpret_prop impl_system.\n Proof with try tauto.\n  constructor.\n  repeat intro.\n  simpl in *.\n  unfold is_int.\n  destruct a as [ies1 ies2].\n  simpl in *.\n  repeat rewrite in_app_iff in *.\n  generalize (vars_int ies1 e);intro.\n  generalize (vars_int ies2 e);intro...\n Qed. \n\n Definition beval_interpret_spec (A : Type) `{@B2F A bF} `{evalable context A}:=\n  forall a rho, rho |= a <-> beval rho (interpret a) = true.\n\n Class beval_interpret_prop (A : Type) `{@B2F A bF} `{evalable context A} := Beval_interpret_prop {\n  beval_int : beval_interpret_spec A\n }.\n\n Instance v_int_prop : beval_interpret_prop var.\n Proof with (try tauto;try congruence).\n  constructor. repeat intro. simpl.\n  icase (rho a); split;repeat intro;disc...\n Qed.\n\n Lemma obj_beval: forall rho obj,\n  beval rho (interpret obj) = get rho obj.\n Proof with try tauto.\n  intros. icase obj...\n Qed.\n \n Instance eql_int_prop : beval_interpret_prop equality.\n Proof with firstorder.\n  constructor. repeat intro.\n  destruct a as [obj1 obj2].\n  icase obj1;icase obj2;\n  try icase s0;try icase s1; simpl;\n  try icase (rho v); try icase (rho v0); simpl...\n Qed.\n\n Instance eqn_int_prop : beval_interpret_prop equation.\n Proof with firstorder.\n  constructor. repeat intro.\n  destruct a as [[obj1 obj2] obj3].\n  icase obj1;icase obj2;icase obj3;\n  try icase s0;try icase s1;try icase s2; simpl;\n  try icase (rho v); try icase (rho v0); try icase (rho v1);simpl...\n Qed. \n\n Instance list_int_prop {A} `{beval_interpret_prop A} : beval_interpret_prop (list A).\n Proof with try tauto.\n  constructor. induction a;intros.\n  simpl...\n  simpl.\n  rewrite andb_true_iff.\n  spec IHa rho.\n  generalize (beval_int a rho);intro...\n Qed.\n\n Instance ses_int_prop : beval_interpret_prop sat_equation_system.\n Proof with try tauto.\n  constructor. repeat intro.\n  destruct a as [l1 l2 l3].\n  simpl. unfold eval_sat_equation_system;simpl.\n  repeat rewrite andb_true_iff.\n  generalize (beval_int l1 rho);intro.\n  generalize (beval_int l2 rho);intro.\n  generalize (beval_int l3 rho);intro...\n Qed.\n\n (*To make life easier*)\n Lemma upd_id {A B} `{EqDec A}: forall (rho : A -> B) v b,\n  rho v = b ->\n  upd rho v b = rho.\n Proof with try tauto.\n  repeat intro.\n  subst. extensionality v'.\n  destruct (eq_dec v v'). subst.\n  apply upd_eq.\n  apply upd_neq...\n Qed.\n\n Lemma upd_override_not_in {A B} `{EqDec A}: forall (rho rho': A -> B) v b l,\n  ~In v l ->\n  [l => upd rho' v b]rho = [l => rho']rho.\n Proof with try tauto.\n  repeat intro.\n  extensionality v'.\n  destruct (in_dec eq_dec v' l).\n  repeat rewrite override_in...\n  rewrite upd_neq... intro;subst...\n  repeat rewrite override_not_in...\n Qed.\n (*To make life easier*)\n\n Lemma exF_quan_beval: forall l f (rho:context),\n  beval rho (exF_quan l f) = true <-> \n  exists rho', beval ([l => rho']rho) f = true.\n Proof with try tauto.\n  induction l;intros;unfold exF_quan in *;simpl.\n  split;intro. exists rho...\n  destruct H...\n  destruct (in_dec eq_dec a l).\n  rewrite IHl.\n  split;intros H; destruct H as [rho' H];exists rho'.\n  rewrite upd_id... rewrite override_in...\n  rewrite upd_id in H... rewrite override_in...\n  simpl. rewrite orb_true_iff.\n  generalize (IHl f (upd rho a true));intro.\n  generalize (IHl f (upd rho a false));intro.\n  split;intro.\n  destruct H1.\n  \n  apply H in H1.\n  destruct H1 as [rho' H1].\n  exists (upd rho' a true).\n  rewrite upd_eq.\n  rewrite<- override_absorb_not_in...\n  rewrite upd_override_not_in...\n\n  apply H0 in H1.\n  destruct H1 as [rho' H1].\n  exists (upd rho' a false).\n  rewrite upd_eq.\n  rewrite<- override_absorb_not_in...\n  rewrite upd_override_not_in...\n\n  destruct H1 as [rho' H1].\n  remember (rho' a) as b.\n  symmetry in Heqb. destruct b.\n  left. apply H. exists rho'.\n  rewrite override_absorb_not_in...\n  right. apply H0. exists rho'.\n  rewrite override_absorb_not_in...\n Qed.\n\n Lemma allF_quan_beval: forall l f (rho:context),\n  beval rho (allF_quan l f) = true <-> \n  forall rho', beval ([l => rho']rho) f = true.\n Proof with try tauto.\n  induction l;intros;unfold allF_quan in *;simpl.\n  split;intros...\n  destruct (in_dec eq_dec a l).\n  rewrite IHl.\n  split;intros.\n  rewrite upd_id...\n  apply H...\n  rewrite override_in...\n  spec H rho'. rewrite upd_id in H...\n  rewrite override_in...\n  \n  simpl.\n  rewrite andb_true_iff.\n  generalize (IHl f (upd rho a true));intro.\n  generalize (IHl f (upd rho a false));intro.\n  rewrite H. rewrite H0.\n  split;intros.\n  destruct H1 as [H1 H2].\n  spec H1 rho'. spec H2 rho'.\n  rewrite<- override_absorb_not_in...\n  icase (rho' a).\n  split;intros.\n  spec H1 (upd rho' a true).\n  rewrite<- override_absorb_not_in in H1...\n  rewrite upd_eq in H1...\n  rewrite upd_override_not_in in H1...\n  spec H1 (upd rho' a false).\n  rewrite<- override_absorb_not_in in H1...\n  rewrite upd_eq in H1...\n  rewrite upd_override_not_in in H1...  \n Qed.\n\n Instance ies_int_prop : beval_interpret_prop impl_equation_system.\n Proof with try tauto.\n  constructor. repeat intro.\n  simpl.\n  unfold eval_impl_equation_system,ies_int,e_eval.\n  rewrite exF_quan_beval.\n  destruct a as [l1 l2 l3 l4];simpl.\n  unfold eval_sat_equation_system,ies2ses;simpl.\n  generalize (beval_int l2);intro.\n  generalize (beval_int l3);intro.\n  generalize (beval_int l4);intro...  \n  split;intro H2;destruct H2 as [rho' H2];exists rho';\n  spec H ([l1 =>rho']rho);\n  spec H0 ([l1 =>rho']rho);\n  spec H1 ([l1 =>rho']rho);\n  repeat rewrite andb_true_iff in *...\n Qed.\n\n Lemma beval_implF_rewrite: forall rho f1 f2, \n  beval rho (implF f1 f2) = negb (beval rho f1)|| (beval rho f2).\n Proof.\n  intros. simpl.\n  icase (beval rho f1);icase (beval rho f2).\n Qed.\n\n Instance is_int_prop : beval_interpret_prop impl_system.\n Proof with try tauto.\n  constructor. repeat intro.\n  destruct a as [ies1 ies2].\n  unfold interpret,b2f_is,is_int.\n  generalize (beval_int ies1 rho);intro.\n  generalize (beval_int ies2 rho);intro.\n  rewrite beval_implF_rewrite.\n  icase (beval rho (interpret ies1));\n  icase (beval rho (interpret ies2));simpl;\n  split;repeat intro...\n  apply H0. apply H1. apply H...\n Qed.\n\n Lemma exF_quan_In: forall l bf v,\n  In v l ->\n  not_free v (exF_quan l bf).\n Proof with try tauto.\n  induction l;intros;unfold exF_quan in *. inv H.\n  simpl. \n  destruct (in_dec eq_dec a l).\n  apply IHl... destruct H;subst...\n  simpl. destruct (eq_dec v a)...\n  destruct H;subst... apply IHl...\n Qed.\n\n Lemma exF_quan_In_iff: forall l bf v,\n  not_free v (exF_quan l bf) <-> (In v l \\/ not_free v bf).\n Proof with try tauto.\n  induction l;intros;unfold exF_quan in *. simpl...\n  simpl. destruct (in_dec eq_dec a l).\n  rewrite IHl. split;intros...\n  destruct H... destruct H;subst...\n  simpl. destruct (eq_dec v a);subst...\n  rewrite IHl. split;intros...\n  destruct H... destruct H;subst...\n Qed.\n\n Lemma allF_quan_In: forall l bf v,\n  In v l ->\n  not_free v (allF_quan l bf).\n Proof with try tauto.\n  induction l;intros;unfold allF_quan in *. inv H.\n  simpl. \n  destruct (in_dec eq_dec a l).\n  apply IHl... destruct H;subst...\n  simpl. destruct (eq_dec v a)...\n  destruct H;subst... apply IHl...\n Qed.\n\n Lemma allF_quan_In_iff: forall l bf v,\n  not_free v (allF_quan l bf) <-> (In v l \\/ not_free v bf).\n Proof with try tauto.\n  induction l;intros;unfold allF_quan in *. simpl...\n  simpl. destruct (in_dec eq_dec a l).\n  rewrite IHl. split;intros...\n  destruct H... destruct H;subst...\n  simpl. destruct (eq_dec v a);subst...\n  rewrite IHl. split;intros...\n  destruct H... destruct H;subst...\n Qed.\n\n Definition is_free (v : var) (ies : impl_equation_system) : bool :=\n   if in_dec eq_dec v (impl_exvars ies) then false else true.\n\n Lemma is_free_In: forall v ies,\n  is_free v ies = true <-> ~In v (impl_exvars ies).\n Proof with try tauto.\n  intros. unfold is_free.\n  destruct (in_dec eq_dec v (impl_exvars ies))...\n  split;intros;disc...\n Qed.\n\n Definition in_not_free_spec (A : Type) `{@B2F A bF}:= \n  forall a v, In v (vars (interpret a)) -> not_free v (interpret a) -> False .\n Class in_not_free_prop (A : Type) `{@B2F A bF} := In_not_free_prop {\n  in_not_free : in_not_free_spec A\n }.\n\n Instance in_not_free_obj: in_not_free_prop object.\n Proof with try tauto.\n  constructor. repeat intro.\n  icase a... inv H; simpl in H0...\n  destruct (eq_dec v v)...\n Qed.\n\n Instance in_not_free_eql: in_not_free_prop equality.\n Proof with try tauto.\n  constructor. repeat intro.\n  destruct a.\n  icase o;icase o0;\n  simpl in *;\n  try destruct (eq_dec v v0);\n  try destruct (eq_dec v v1);\n  subst;\n  try icase s0; \n  try icase s1;\n  subst;simpl in *;firstorder;\n  try destruct (@eq_dec var sv.t_eq_dec v0 v0)...\n Qed.\n\n Instance in_not_free_eqn: in_not_free_prop equation.\n Proof with try tauto.\n  constructor. repeat intro.\n  destruct a as [[? ?] ?].\n  icase o;icase o0;icase o1;\n  simpl in *;\n  try destruct (eq_dec v v0);\n  try destruct (eq_dec v v1);\n  try destruct (eq_dec v v2);\n  subst;\n  try icase s0; \n  try icase s1;\n  try icase s2;\n  subst;simpl in *;firstorder;\n  try destruct (@eq_dec var sv.t_eq_dec v0 v0);\n  try destruct (@eq_dec var sv.t_eq_dec v1 v1);\n  try destruct (@eq_dec var sv.t_eq_dec v2 v2)...\n Qed.\n\n Instance in_not_free_var: in_not_free_prop var.\n Proof with try tauto.\n  constructor.\n  repeat intro.\n  inv H;simpl in *...\n  destruct (eq_dec v v);subst...\n Qed.\n\n Instance in_not_free_list  {A} `{in_not_free_prop A} : in_not_free_prop (list A).\n Proof with try tauto.\n  constructor.\n  induction a;intros. inv H1.\n  simpl in *. destruct H2.\n  rewrite in_app_iff in H1.\n  destruct H1.\n  apply in_not_free in H2...\n  apply IHa with (v:=v)...\n Qed.\n  \n Lemma ies_is_free_equiv: forall v ies,\n  In v (vars (interpret ies)) ->\n  (is_free v ies = true <-> ~not_free v (interpret ies)).\n Proof with try tauto.\n  intros.\n  rewrite is_free_In.\n  split;repeat intro.\n  - apply H0. \n    destruct ies as [l1 l2 l3 l4].\n    simpl in *. unfold ies_int in H;simpl in H.\n    rewrite exF_quan_vars in H.\n    rewrite in_app_iff in H.\n    destruct H...\n    unfold ies_int in H1;simpl in H1.\n    rewrite exF_quan_In_iff in H1.\n    destruct H1...\n    inv H1. inv H3.\n    simpl in H.\n    repeat rewrite in_app_iff in H.\n    destruct H. \n    generalize (in_not_free l2 v H H2)...\n    destruct H.\n    generalize (in_not_free l3 v H H1)...\n    generalize (in_not_free l4 v H H4)...\n\n  - apply H0.\n    simpl. unfold ies_int.\n    apply exF_quan_In...\n Qed.\n\n Require Import Classical.\n\n Lemma not_free_ies: forall v (ies : impl_equation_system),\n  In v (vars (interpret ies)) ->\n  (In v (impl_exvars ies) <-> not_free v (interpret ies)).\n Proof with try tauto.\n  intros. apply ies_is_free_equiv in H.\n  unfold is_free in *.\n  unfold var,es.var in *.\n  destruct (in_dec eq_dec v (impl_exvars ies))...\n  split;intros...\n  destruct (classic (not_free v (interpret ies)))...\n  rewrite<- H in H1. inv H1.\n Qed.\n\nEnd Interpreter.", "meta": {"author": "lexuanbach", "repo": "certified-permission-procedure", "sha": "f0ac470d8096b106ea03c22e95950bae684bcc86", "save_path": "github-repos/coq/lexuanbach-certified-permission-procedure", "path": "github-repos/coq/lexuanbach-certified-permission-procedure/certified-permission-procedure-f0ac470d8096b106ea03c22e95950bae684bcc86/bool_to_formula.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24573395951675675}}
{"text": "(** * Bicolano: Semantic domains (interface implementation) *)\n(* Hendra : - Modified to suit DEX program (Removed Operand Stack).\n            - Removed Reference comparison. \n            - Also trim the system to contain only Arithmetic *)\n\nRequire Export DEX_ImplemProgramWithMap.\nRequire Export DEX_Domain.\n \nLtac caseeq t := generalize (refl_equal t); pattern t at -1 in |- * ; case t.\n\n(** All semantic domains and basic operation are encapsulated in a module signature *)\n\nModule DEX_Dom <: DEX_SEMANTIC_DOMAIN.\n\n (** We depend on the choices done for program data structures *)\n Module DEX_Prog := DEX_ImplemProgramWithMap.DEX_Make.\n Import DEX_Prog.\n\nOpen Scope Z_scope.\n Module SByte <: Numeric.NUMSIZE. Definition power := 7%nat. End SByte.\n Module SShort<: Numeric.NUMSIZE. Definition power := 15%nat. End SShort.\n Module SInt  <: Numeric.NUMSIZE. Definition power := 31%nat. End SInt.\n\n Module Byte  : Numeric.NUMERIC with Definition power := 7%nat := Numeric.Make SByte.\n Module Short : Numeric.NUMERIC with Definition power := 15%nat := Numeric.Make SShort.\n Module Int   : Numeric.NUMERIC with Definition power := 31%nat := Numeric.Make SInt.\n\n (** conversion *)\n Definition b2i (b:Byte.t) : Int.t := Int.const (Byte.toZ b).\n Definition s2i (s:Short.t) : Int.t := Int.const (Short.toZ s).\n Definition i2b (i:Int.t) : Byte.t := Byte.const (Int.toZ i).\n Definition i2s (i:Int.t) : Short.t := Short.const (Int.toZ i).\n Definition i2bool (i:Int.t) : Byte.t := Byte.const (Int.toZ i mod 2).\n\n Inductive DEX_num : Set :=\n   | I : Int.t -> DEX_num\n   | B : Byte.t -> DEX_num\n   | Sh : Short.t -> DEX_num.\n\n Inductive DEX_value : Set :=\n   | Num : DEX_num -> DEX_value.\n\n Definition init_value (t:DEX_type) : DEX_value :=\n    match t with\n     | DEX_PrimitiveType _ => Num (I (Int.const 0))\n    end.\n\n (** Domain of local variables *)\n Module Type DEX_REGISTERS.\n   Parameter t : Type.\n   Parameter get : t-> DEX_Reg -> option DEX_value.\n   Parameter update : t -> DEX_Reg -> DEX_value -> t.\n   Parameter dom : t -> list DEX_Reg.\n   Parameter get_update_new : forall l x v, get (update l x v) x = Some v.\n   Parameter get_update_old : forall l x y v,\n     x<>y -> get (update l x v) y = get l y.\n End DEX_REGISTERS.\n\n Module DEX_MapReg <: MAP with Definition key := DEX_Reg := BinNatMap.\n\n Module DEX_Registers <: DEX_REGISTERS.\n   Definition t := DEX_MapReg.t DEX_value.\n   Definition get : t -> DEX_Reg -> option DEX_value := @DEX_MapReg.get DEX_value.\n   Definition update : t -> DEX_Reg -> DEX_value -> t := @DEX_MapReg.update DEX_value.\n   Definition dom : t -> list DEX_Reg := @DEX_MapReg.dom DEX_value.\n   Lemma get_update_new : forall l x v, get (update l x v) x = Some v.\n   Proof. exact (DEX_MapReg.get_update1 DEX_value). Qed.\n   Lemma get_update_old : forall l x y v,\n     x<>y -> get (update l x v) y = get l y.\n   Proof. \n    intros;refine (DEX_MapReg.get_update2 DEX_value _ _ _ _ _). \n    intro;apply H;subst;trivial.\n  Qed.\n  Definition empty := DEX_MapReg.empty DEX_value.\n End DEX_Registers.\n\n Fixpoint listreg2regs_rec\n    (l_ori:DEX_Registers.t) (n:nat) (lv:list DEX_Reg) (l:DEX_Registers.t) {struct n}: DEX_Registers.t :=\n   match n with \n   | O => l\n   | S n =>\n     match lv with \n     | nil => l\n     | h :: t =>\n       match DEX_Registers.get l_ori h with\n       | None =>\n         listreg2regs_rec l_ori n t l\n       | Some v => \n         listreg2regs_rec l_ori n t (DEX_Registers.update l (N_toReg n) v)\n       end\n     end\n   end.\n Definition listreg2regs (l_ori:DEX_Registers.t) (n:nat) (lv:list DEX_Reg)\n   := listreg2regs_rec l_ori n lv DEX_Registers.empty.\n\n\n Fixpoint all_super_classes (p:DEX_Program) (c:DEX_Class) (n:nat) {struct n} : option (list DEX_Class) :=\n   match n with\n     | O => None\n     | S n =>\n       match DEX_CLASS.superClass c with\n         | None => Some nil\n         | Some super_name => \n           match DEX_PROG.class p super_name with\n             | None => None\n             | Some super => \n               match (all_super_classes p super n) with\n                 | None => None\n                 | Some l => Some (super::l)\n               end\n           end\n       end\n   end.\n\n Ltac inv H := inversion H; subst; clear H.\n\n Lemma clos_refl_trans_ind2 :\n      forall (A:Type) (R:A -> A -> Prop) (P:A -> A -> Prop),\n        (forall x, P x x) ->\n        (forall x y z:A, R x y -> clos_refl_trans A R y z -> P y z  -> P x z) ->\n        forall x y, clos_refl_trans A R x y -> P x y.\n Proof.\n   intros A R P H1 H2.\n   assert (forall x y, clos_refl_trans A R x y -> \n              forall z, clos_refl_trans A R y z -> P y z -> P x z).\n   induction 1; eauto; intros.\n   apply IHclos_refl_trans1.\n   constructor 3 with z; auto.\n   apply IHclos_refl_trans2; auto.\n   intros.\n   apply H with y; auto.\n   constructor 2.\n Qed.\n\nLemma subclass_left : forall p c1 c2,\n  subclass p c1 c2 -> c1=c2 \\/ (exists c, direct_subclass p c1 c /\\ subclass p c c2).\nProof.\n  intros p; unfold subclass; apply clos_refl_trans_ind2; intros; auto.\n  destruct H1; subst; auto.\n  right; exists z; auto.\n  destruct H1 as [c [T1 T2]].\n  right; exists y; split; auto.\nQed.\n\n Definition all_super_classes_correct : forall p n c l,\n   all_super_classes p c n = Some l ->\n   DEX_PROG.defined_Class p c -> \n   forall c', subclass p c c' -> In c' (c::l).\n Proof.\n   induction n; simpl.\n   intros; discriminate.\n   intros c l; case_eq (DEX_CLASS.superClass c).\n   intros c' H'.\n   case_eq (DEX_PROG.class p c'); try (intros; discriminate).\n   intros c'' H''.\n   case_eq (all_super_classes p c'' n); try (intros; discriminate).\n   intros.\n   inv H0.\n   destruct (subclass_left _ _ _ H2); auto.\n   destruct H0 as [c0 [T1 T2]].\n   clear H2.\n   inv T1.\n   unfold DEX_PROG.defined_Class in *.\n   assert (c0 = c'') by congruence.\n   assert (c'=DEX_CLASS.name c'') by congruence.\n   subst.\n   clear H2 H3 H1.\n   right; apply (IHn _ _ H H'' _ T2).\n\n   intros.\n   destruct (subclass_left _ _ _ H2); auto.\n   destruct H3 as [c0 [T1 T2]].\n   inv T1.\n   congruence.\n Qed.\n\n Fixpoint all_super_interfaces (p:DEX_Program) (n:nat) {struct n} : \n                          DEX_Interface -> option (list DEX_Interface) :=\n   match n with\n     | O => fun _ => None\n     | S n => fun c =>\n       List.fold_left \n         (fun o iname =>\n           match o with\n             | None => None\n             | Some l => \n               match DEX_PROG.interface p iname with\n                 | None => None\n                 | Some itf => \n                   match all_super_interfaces p n itf with\n                     | None => None\n                     | Some l' => Some (itf::l++l')\n                   end\n               end\n           end) \n         (DEX_INTERFACE.superInterfaces c)\n         (Some (c::nil))\n   end.\n\nLemma subinterface_left : forall p c1 c2,\n  subinterface p c1 c2 -> c1=c2 \\/ (exists c, direct_subinterface p c1 c /\\ subinterface p c c2).\nProof.\n  intros p; unfold subinterface; apply clos_refl_trans_ind2; intros; auto.\n  destruct H1; subst; auto.\n  right; exists z; auto.\n  destruct H1 as [c [T1 T2]].\n  right; exists y; split; auto.\nQed.\n\nLemma all_super_interfaces_aux : forall p n l3,\n   fold_left\n     (fun (o : option (list DEX_Interface)) (iname : DEX_InterfaceName) =>\n      match o with\n      | Some l6 => \n             match DEX_PROG.interface p iname with\n             | Some itf =>\n                 match all_super_interfaces p n itf with\n                 | Some l' => Some (itf :: l6 ++ l')\n                 | None => None (A:=list DEX_Interface)\n                 end\n             | None => None (A:=list DEX_Interface)\n             end\n      | None => None (A:=list DEX_Interface)\n      end) l3 None=None.\nProof.\n  induction l3; simpl; auto.\nQed.\n\nLemma all_super_interfaces_aux' : forall p n l0 l1 l2,\n     fold_left\n        (fun (o : option (list DEX_Interface)) (iname : DEX_InterfaceName) =>\n         match o with\n         | Some l =>\n             match DEX_PROG.interface p iname with\n             | Some itf =>\n                 match all_super_interfaces p n itf with\n                 | Some l' => Some (itf :: l ++ l')\n                 | None => None (A:=list DEX_Interface)\n                 end\n             | None => None (A:=list DEX_Interface)\n             end\n         | None => None (A:=list DEX_Interface)\n         end) l0 (Some l1) = Some l2 -> incl l1 l2.\nProof.\n  induction l0; simpl.\n  intros.\n  inversion H; subst; intro; auto.\n  destruct (DEX_PROG.interface p a); try (intros; discriminate).\n  destruct (all_super_interfaces p n d); try (intros; discriminate).\n  intros.\n  assert (IH:=IHl0 _ _ H); clear H IHl0.\n  repeat intro; apply IH.\n  right; auto with datatypes.\n  rewrite all_super_interfaces_aux; intros; discriminate.\n  rewrite all_super_interfaces_aux; intros; discriminate.\n Qed.\n\n\n Definition all_super_interfaces_correct : forall p n c l,\n   all_super_interfaces p n c = Some l ->\n   DEX_PROG.defined_Interface p c -> \n   forall c', subinterface p c c' -> In c' (c::l).\n Proof.\n   induction n; simpl.\n   intros; discriminate.\n   intros.\n   destruct (subinterface_left _ _ _ H1); clear H1; auto.\n   right; destruct H2 as [c0 [T1 T2]].\n   inv T1.\n   generalize dependent (Some (c::nil)).\n   generalize dependent (DEX_INTERFACE.superInterfaces c).\n   induction l0; simpl; intros.\n   elim H3.\n   destruct o; simpl in H; try discriminate.\n   case_eq (DEX_PROG.interface p a); intros.   \n   rewrite H4 in H.\n   case_eq (all_super_interfaces p n d); intros.\n   rewrite H5 in H.\n   destruct H3; subst.\n   unfold DEX_PROG.defined_Interface in *.\n   assert (c0=d) by congruence; clear H4; subst.\n   generalize (IHn _ _ H5 H2 _ T2).\n   assert (T:=all_super_interfaces_aux' _ _ _ _ _ H).\n   simpl; intros.\n   apply T.\n   destruct H3.\n   left; auto.\n   right; auto with datatypes.\n   apply IHl0 with (Some (d :: l1 ++ l2)); auto.\n   rewrite H5 in H.\n   rewrite all_super_interfaces_aux in H; discriminate.\n   rewrite H4 in H.\n   rewrite all_super_interfaces_aux in H; discriminate.\n   rewrite all_super_interfaces_aux in H; discriminate.\n Qed.\n\n  Definition all_interfaces (p:DEX_Program) (n:nat) (c:DEX_Class) : option (list DEX_Interface) :=\n    List.fold_left \n    (fun o iname =>\n      match o with\n        | None => None\n        | Some l => \n          match DEX_PROG.interface p iname with\n            | None => None\n            | Some itf => \n              match all_super_interfaces p n itf with\n                | None => None\n                | Some l' => Some (itf::l++l')\n              end\n          end\n      end) \n    (DEX_CLASS.superInterfaces c)\n    (Some nil).\n\n  Lemma all_interfaces_correct : forall p n c l,\n    all_interfaces p n c = Some l -> forall i I I',\n      In i (DEX_CLASS.superInterfaces c) ->\n      DEX_PROG.interface p i = Some I ->\n      subinterface p I I' -> \n      In I l.\n  Proof.\n    unfold all_interfaces.\n    intros p n c.\n    generalize (@nil DEX_Interface).\n    generalize (DEX_CLASS.superInterfaces c).\n    induction l; simpl.\n    intuition.\n    intros l0; case_eq (DEX_PROG.interface p a).\n    intros i Hi; case_eq (all_super_interfaces p n i); intros.\n    destruct H1; subst.\n    assert (I0=i) by congruence; subst; clear Hi.\n    apply (all_super_interfaces_aux' _ _ _ _ _ H0).\n    left; reflexivity.\n    eapply IHl ;eauto.\n    rewrite all_super_interfaces_aux in H0; discriminate.\n    intros.\n    rewrite all_super_interfaces_aux in H0; intros; discriminate.\n  Qed.\n\n\n\nSet Implicit Arguments.\n\n  Inductive DEX_ReturnVal : Set :=\n   | Normal : option DEX_value -> DEX_ReturnVal.\n\n (** Domain of frames *)\n Module Type DEX_FRAME.\n   Inductive t : Type := \n      make : DEX_Method -> DEX_PC -> DEX_Registers.t -> t.\n End DEX_FRAME.\n \n Module DEX_Frame.\n   Inductive t : Type := \n      make : DEX_Method -> DEX_PC -> DEX_Registers.t -> t.\n End DEX_Frame.\n\n (** Domain of call stacks *)\n Module Type DEX_CALLSTACK.\n   Definition t : Type := list DEX_Frame.t.\n End DEX_CALLSTACK.\n\n Module DEX_CallStack.\n   Definition t : Type := list DEX_Frame.t.\n End DEX_CallStack.\n\n (** Domain of states *)\n Module Type DEX_STATE.\n   Inductive t : Type := \n      normal : DEX_Frame.t -> DEX_CallStack.t -> t.\n   Definition get_sf  (s:t) : DEX_CallStack.t :=\n     match s with\n       normal _ sf => sf\n     end.\n   Definition get_m (s:t) : DEX_Method :=\n     match s with\n       normal (DEX_Frame.make m _ _)_ => m\n     end.\n End DEX_STATE.\n\n Module DEX_State.\n  Inductive t : Type := \n      normal : DEX_Frame.t -> DEX_CallStack.t -> t.\n   Definition get_sf (s:t) : DEX_CallStack.t :=\n     match s with\n       normal _ sf => sf\n     end.\n   Definition get_m (s:t) : DEX_Method :=\n     match s with\n       normal (DEX_Frame.make m _ _)_ => m\n     end.\n End DEX_State.\n (** Some notations *)\n Notation St := DEX_State.normal.\n Notation Fr := DEX_Frame.make.\n\n  (** compatibility between ValKind and value *) \n  Inductive compat_ValKind_value : DEX_ValKind -> DEX_value -> Prop :=\n    | compat_ValKind_value_int : forall n,\n        compat_ValKind_value DEX_Ival (Num (I n)).\n\n  (** [assign_compatible_num source target] holds if a numeric value [source] can be \n    assigned to a variable of type [target]. This point is not clear in the JVM spec. *)\n  Inductive assign_compatible_num : DEX_num -> DEX_primitiveType -> Prop :=\n   | assign_compatible_int_int : forall i, assign_compatible_num (I i) DEX_INT\n   | assign_compatible_short_int : forall sh, assign_compatible_num (Sh sh) DEX_INT\n   | assign_compatible_byte_int : forall b, assign_compatible_num (B b) DEX_INT\n   | assign_compatible_short_short : forall sh, assign_compatible_num (Sh sh) DEX_SHORT\n   | assign_compatible_byte_byte : forall b, assign_compatible_num (B b) DEX_BYTE\n   | assign_compatible_byte_boolean : forall b, assign_compatible_num (B b) DEX_BOOLEAN.\n\n  (** [assign_compatible h source target] holds if a value [source] can be \n    assigned to a variable of type [target] *)\n  Inductive assign_compatible (p:DEX_Program) : DEX_value -> DEX_type -> Prop :=\n   | assign_compatible_num_val : forall (n:DEX_num) (t:DEX_primitiveType),\n       assign_compatible_num n t -> assign_compatible p (*h*) (Num n) (DEX_PrimitiveType t).\n\n  Definition SemCompInt (cmp:DEX_CompInt) (z1 z2: Z) : Prop :=\n    match cmp with\n      DEX_EqInt =>  z1=z2\n    | DEX_NeInt => z1<>z2\n    | DEX_LtInt => z1<z2\n    | DEX_LeInt => z1<=z2\n    | DEX_GtInt => z1>z2\n    | DEX_GeInt => z1>=z2\n    end.\n\n  Definition SemBinopInt (op:DEX_BinopInt) (i1 i2:Int.t) : Int.t :=\n    match op with \n    | DEX_AddInt => Int.add i1 i2\n    | DEX_AndInt => Int.and i1 i2\n    | DEX_DivInt => Int.div i1 i2\n    | DEX_MulInt => Int.mul i1 i2\n    | DEX_OrInt => Int.or i1 i2\n    | DEX_RemInt => Int.rem i1 i2\n    | DEX_ShlInt => Int.shl i1 i2\n    | DEX_ShrInt => Int.shr i1 i2\n    | DEX_SubInt => Int.sub i1 i2\n    | DEX_UshrInt => Int.ushr i1 i2\n    | DEX_XorInt => Int.xor i1 i2\n    end.\n\nEnd DEX_Dom.", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/DEX_I/DEX_ImplemDomain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283033, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2456515749847413}}
{"text": "From ITree Require Import ITree.\nRequire Import sflib.\nRequire Import StdlibExt.\n\nRequire Import ITreeTac.\n\nRequire Import ZArith List Lia.\n\nImport ITreeNotations.\n\nLocal Opaque Nat.min.\n\nSet Nested Proofs Allowed.\n\nLtac unf_resum :=\n  unfold resum, ReSum_id, id_, Id_IFun in *.\n\nInductive msg_t: Type :=\n| Acquire\n| Release\n| Grant\n.\n\nInductive sysE: Type -> Type :=\n| Demand: sysE nat\n| UseRes: sysE unit\n| Compl: sysE unit\n.\n\nInductive event: Type :=\n| Event (R: Type) (e: sysE R) (r: R).\n\nInductive ctrl_err: Set :=\n  Success | FailBefore | FailAfter.\n\nDefinition Tid: Set := nat.\n\nDefinition MAX_TOUT: nat := 5.\n\nInductive sendE: Type -> Type :=\n  Send (dest: Tid) (m: msg_t): sendE unit.\n\nDefinition msgbox_t: Set := msg_t? * msg_t? * msg_t?.\n\nDefinition update_msgbox\n           (mbox: msgbox_t)\n           (tid: nat) (msg: msg_t)\n  : msgbox_t :=\n  let '(m1, m2, m3) := mbox in\n  match tid with\n  | 1 => (Some msg, m2, m3)\n  | 2 => (m1, Some msg, m3)\n  | 3 => (m1, m2, Some msg)\n  | _ => mbox\n  end.\n\n\nModule Ctrl.\n\n  Record t : Type :=\n    mk { timeout: nat ;\n         queue: list Tid ;\n       }.\n\n  Definition init: t := mk O [].\n\n  Definition try_addq (tid: nat) (st: t): t :=\n    let 'mk tout q := st in\n    if existsb (Nat.eqb tid) q then st\n    else mk tout (snoc q tid).\n\n  Definition try_relq (tid: nat) (st: t): t :=\n    let 'mk tout q := st in\n    if orb (tout =? O) (tout =? MAX_TOUT) then st\n    else\n      match q with\n      | [] => st\n      | h :: t =>\n        if tid =? h then mk 1 (h :: t) else st\n      end.\n\n  Definition apply_msg\n             (tid: nat) (msg: msg_t?)\n             (st: t)\n    : t :=\n    match msg with\n    | None => st\n    | Some m =>\n      match m with\n      | Acquire => try_addq tid st\n      | Release => try_relq tid st\n      | _ => st\n      end\n    end.\n\n  Definition reduce_timeout (st: t): t * bool :=\n    match timeout st with\n    | O => (st, true)\n    | 1 => (mk O (tl (queue st)), false)\n    | S (S n) => (mk (S n) (queue st), false)\n    end.\n\n  Definition update\n             (inb_c: msgbox_t)\n             (st: t): t * bool :=\n    let '(cm1, cm2, cm3) := inb_c in\n    let st1 := apply_msg 1 cm1 st in\n    let st2 := apply_msg 2 cm2 st1 in\n    let st3 := apply_msg 3 cm3 st2 in\n    reduce_timeout st3.\n\n  (* Do this if tout = 0 & queue is nonempty: *)\n  (* if tzero_flag is true, ignore cerr *)\n  (* if cerr = success, set tout to max & send Grant *)\n  (* if cerr = failafter, send Grant *)\n  (* if cerr = failbefore, do nothing *)\n  Definition send_grant (cerr: ctrl_err) (st: t)\n             (tzero_flag: bool)\n    : itree (sysE +' sendE) t :=\n    if timeout st =? O then\n      match queue st with\n      | [] => Ret st\n      | h :: t =>\n        let cerr' :=\n            if tzero_flag then Success else cerr in\n        match cerr' with\n        | FailBefore => Ret st\n        | FailAfter =>\n          trigger (Send h Grant);;\n          Ret (mk 0 (h :: t))\n        | Success =>\n          trigger (Send h Grant);;\n          Ret (mk MAX_TOUT (h :: t))\n        end\n      end\n    else Ret st.\n\n  Definition send_grant_func (cerr: ctrl_err) (st: t)\n             (tzero_flag: bool)\n    : t * (Tid * msg_t)? :=\n    if timeout st =? O then\n      match queue st with\n      | [] => (st, None)\n      | h :: t =>\n        let cerr' :=\n            if tzero_flag then Success else cerr in\n        match cerr' with\n        | FailBefore => (st, None)\n        | FailAfter =>\n          (mk 0 (h :: t), Some (h, Grant))\n          (* trigger (Send h Grant);; *)\n          (* Ret (mk 0 (h :: t)) *)\n        | Success =>\n          (* trigger (Send h Grant);; *)\n          (* Ret (mk MAX_TOUT (h :: t)) *)\n          (mk MAX_TOUT (h :: t), Some (h, Grant))\n        end\n      end\n    else (st, None).\n\n\n  Definition job (cerr: ctrl_err)\n             (inbox: msgbox_t)\n             (st: t): itree (sysE +' sendE) t :=\n    let (st_upd, tzero_flag) := update inbox st in\n    st' <- send_grant cerr st_upd tzero_flag ;;\n    Ret st'.\n    (* st' <- match new_owner with *)\n    (*       | None => Ret st_upd *)\n    (*       | Some tid_nown => *)\n    (*         match cerr with *)\n    (*         | FailBefore => *)\n    (*           Ret (set_tout_zero st_upd) *)\n    (*         | FailAfter => *)\n    (*           trigger (Send tid_nown Grant);; *)\n    (*           Ret (set_tout_zero st_upd) *)\n    (*         | Success => *)\n    (*           trigger (Send tid_nown Grant);; *)\n    (*           Ret st_upd *)\n    (*         end *)\n    (*       end;; *)\n    (* trigger Compl;; *)\n    (* Ret st'. *)\n\n  Definition job_func (cerr: ctrl_err)\n             (inbox: msgbox_t)\n             (st: t)\n    : t * msgbox_t :=\n    let (st_upd, tzero_flag) := update inbox st in\n    let (st', om) := send_grant_func\n                      cerr st_upd tzero_flag in\n    let outbox_i := (None, None, None) in\n    let outbox := match om with\n                  | None => outbox_i\n                  | Some (tid, msg) =>\n                    update_msgbox outbox_i tid msg\n                  end in\n    (st', outbox).\n\n  Inductive run_itree\n            (itr: itree (sysE +' sendE) t)\n            (out: msgbox_t)\n    : list event -> t -> msgbox_t -> Prop :=\n  | RunITree_Ret\n      st'\n      (OBS_RET: observe itr = RetF st')\n    : run_itree itr out [] st' out\n  | RunITree_Tau\n      itr' es st' out'\n      (OBS_TAU: observe itr = TauF itr')\n      (RUN_REST: run_itree itr' out es st' out')\n    : run_itree itr out es st' out'\n  | RunITree_SysEvt\n      R (syse: sysE R) (k: R -> itree _ t) (r: R)\n      e es st' out'\n      (OBS_EVT: observe itr = VisF (inl1 syse) k)\n      (RUN_REST: run_itree (k r) out es st' out')\n      (EVENT: e = Event _ syse r)\n    : run_itree itr out (e :: es) st' out'\n  | RunITree_Send\n      tid msg (k: unit -> itree _ t)\n      out_upd es st' out'\n      (OBS_EVT: observe itr = VisF (inr1 (Send tid msg)) k)\n      (UPDATE_OUTBOX: out_upd = update_msgbox\n                                  out tid msg)\n      (RUN_REST: run_itree (k tt) out_upd es st' out')\n    : run_itree itr out es st' out'\n  .\n\n  Lemma run_itree_func\n        cerr inb st es st' out\n        (RUN: run_itree (job cerr inb st)\n                        (None, None, None) es st' out)\n    : <<CTRL_SILENT: es = []>> /\\\n      <<JOB_FUNC: job_func cerr inb st = (st', out)>>.\n  Proof.\n    unfold job in RUN.\n    unfold job_func.\n\n    assert (AUX1: exists st_upd tzero_flag,\n               update inb st = (st_upd, tzero_flag)).\n    { esplits. eapply surjective_pairing. }\n    des.\n    rewrite AUX1 in *.\n\n    destruct st_upd as [tout q].\n    unfold send_grant in RUN.\n    unfold send_grant_func.\n    ss.\n\n    destruct  (Nat.eqb_spec tout 0); ss.\n    2: {\n      simpl_itree_hyp RUN.\n      inv RUN; ss.\n      clarify.\n    }\n\n    destruct q as [| qh qt].\n    { simpl_itree_hyp RUN.\n      inv RUN; ss. clarify. }\n    { destruct tzero_flag; ss.\n      - simpl_itree_hyp RUN.\n        simpl_itree_hyp RUN.\n        inv RUN; ss.\n        clarify. existT_elim. subst.\n        simpl_itree_hyp RUN_REST.\n\n        inv RUN_REST; ss. clarify.\n      - simpl_itree_hyp RUN.\n        destruct cerr.\n        + simpl_itree_hyp RUN.\n          inv RUN; ss.\n          clarify. existT_elim. subst.\n          inv RUN_REST; ss.\n          clarify.\n        + inv RUN; ss.\n          clarify.\n        + simpl_itree_hyp RUN.\n          inv RUN; ss.\n          clarify. existT_elim. subst.\n          inv RUN_REST; ss.\n          clarify.\n    }\n  Qed.\n\n  Inductive step (inb: msgbox_t)\n    : t -> list event -> t -> msgbox_t -> Prop :=\n  | Step\n      (cerr: ctrl_err)\n      st es st' out\n      (RUN_ITREE: run_itree (job cerr inb st)\n                            (None, None, None)\n                            es st' out)\n    : step inb st es st' out\n  .\n\n\nEnd Ctrl.\n\n\nModule Dev.\n  Inductive t: Type :=\n  | Init\n  | Running (is_owner: bool) (demand: nat)\n  .\n\n  Definition update_ownership\n             (inb: msg_t?) (is_owner: bool): bool :=\n    match inb with\n    | None => is_owner\n    | Some m =>\n      match m with\n      | Grant => true\n      | _ => is_owner\n      end\n    end.\n\n  Definition update_demand (dmd: nat)\n    : itree (sysE +' sendE) (nat * bool) :=\n    if dmd =? O then\n      dmd' <- trigger Demand;;\n      Ret (Nat.min MAX_TOUT dmd', true)\n    else Ret (dmd, false).\n\n\n  Definition use_res (own: bool) (dmd: nat)\n    : itree (sysE +' sendE) nat :=\n    if andb own (0 <? dmd) then\n      trigger UseRes;; Ret (pred dmd)\n    else Ret dmd.\n\n  Definition send_msg (own: bool) (dmd: nat) (dupd: bool)\n    : itree (sysE +' sendE) bool :=\n    if andb own (dmd =? O) then\n      trigger (Send 0 Release);; Ret false\n    else\n      if andb (negb own) (andb (0 <? dmd) dupd) then\n        trigger (Send 0 Acquire);; Ret own\n       else Ret own.\n\n  Definition job\n             (inbox: msg_t?) (st: t)\n    : itree (sysE +' sendE) t :=\n    match st with\n    | Init =>\n      trigger (Send 0 Release) ;;\n      Ret (Running false 0)\n    | Running is_owner dmd =>\n      let is_owner1 := update_ownership inbox is_owner in\n      '(dmd1, dmd_upd) <- update_demand dmd ;;\n      dmd' <- use_res is_owner1 dmd1 ;;\n      is_owner'<- send_msg is_owner1 dmd' dmd_upd ;;\n      trigger Compl ;;\n      Ret (Running is_owner' dmd')\n    end.\n\n  Inductive run_itree\n            (itr: itree (sysE +' sendE) t)\n            (out: msg_t?)\n    : list event -> t? -> msg_t? -> Prop :=\n  | RunITree_Fail\n    : run_itree itr out [] None out\n  | RunITree_Ret\n      st'\n      (OBS_RET: observe itr = RetF st')\n    : run_itree itr out [] (Some st') out\n  | RunITree_Tau\n      itr' es ost' out'\n      (OBS_TAU: observe itr = TauF itr')\n      (RUN_REST: run_itree itr' out es ost' out')\n    : run_itree itr out es ost' out'\n  | RunITree_SysEvt\n      R (syse: sysE R) (k: R -> itree _ t) (r: R)\n      e es ost' out'\n      (OBS_EVT: observe itr = VisF (inl1 syse) k)\n      (RUN_REST: run_itree (k r) out es ost' out')\n      (EVENT: e = Event _ syse r)\n    : run_itree itr out (e :: es) ost' out'\n  | RunITree_Send\n      tid msg (k: unit -> itree _ t)\n      es ost' out'\n      (OBS_EVT: observe itr = VisF (inr1 (Send tid msg)) k)\n      (RUN_REST: run_itree (k tt) (Some msg) es ost' out')\n    : run_itree itr out es ost' out'\n  .\n\n  Lemma job_dzero_ngrant_cases\n        es ost' out\n        (RUN: run_itree (job None (Running false 0))\n                        None es ost' out)\n    : <<FAILED: es = [] /\\ out = None /\\ ost' = None>>\n        \\/\n      <<DEMAND_FAILED: exists dmd',\n        es = [Event _ Demand dmd'] /\\\n        out = None /\\ ost' = None>>\n        \\/\n      <<DEMAND_ZERO_SUCC:\n        es = [Event _ Demand 0; Event _ Compl tt] /\\\n        out = None /\\\n        option_rel1 (fun st => st = Running false 0) ost'>>\n        \\/\n      <<DEMAND_ACQ_FAILED: exists dmd',\n          0 < dmd' /\\\n          es = [Event _ Demand dmd'] /\\\n          out = Some Acquire /\\ ost' = None>> \\/\n      <<DEMAND_ACQ_SUCC: exists dmd',\n          0 < dmd' /\\\n          es = [Event _ Demand dmd'; Event _ Compl tt] /\\\n          out = Some Acquire /\\\n          option_rel1 (fun st => st = Running false\n                                           (Nat.min MAX_TOUT dmd')) ost'>>\n  .\n  Proof.\n      unfold job in RUN.\n      unfold update_demand in RUN.\n      rewrite Nat.eqb_refl in RUN.\n      simpl_itree_hyp RUN.\n      simpl_itree_hyp RUN.\n\n      inv RUN; ss.\n      { left. eauto. }\n\n      clarify. existT_elim. subst.\n      rename RUN_REST into RUN.\n      simpl_itree_hyp RUN.\n      unfold use_res in RUN. ss.\n      simpl_itree_hyp RUN.\n      unfold send_msg in RUN. ss.\n\n      pose (dmd_trim := Nat.min MAX_TOUT r).\n      fold dmd_trim in RUN.\n\n      destruct (Nat.ltb_spec 0 dmd_trim); ss.\n      2: {\n        assert (r = 0).\n        { subst dmd_trim.\n          destruct r; ss.\n          exfalso. unfold MAX_TOUT in *. nia.\n        }\n        subst r.\n\n        simpl_itree_hyp RUN.\n        simpl_itree_hyp RUN.\n        inv RUN; ss.\n        { right. left. eauto. }\n\n        clarify. existT_elim. subst.\n        inv RUN_REST; ss.\n        { right. right. left.\n          esplits; eauto.\n          destruct r; ss. }\n\n        clarify.\n        destruct r; ss.\n\n        right. right. left.\n        esplits; eauto.\n      }\n\n      assert (0 < r).\n      { subst dmd_trim.\n        destruct r; ss. nia. }\n\n      simpl_itree_hyp RUN.\n      simpl_itree_hyp RUN.\n      inv RUN; ss.\n      { right. left. eauto. }\n\n      clarify. existT_elim. subst.\n      rename RUN_REST into RUN.\n      simpl_itree_hyp RUN.\n      simpl_itree_hyp RUN.\n\n      inv RUN; ss.\n      { right. right. right. left.\n        esplits; eauto. }\n\n      clarify. existT_elim. subst.\n      destruct r0; ss.\n\n      inv RUN_REST; ss.\n      { right. right. right. right.\n        esplits; eauto. }\n\n      clarify.\n      right. right. right. right.\n      esplits; eauto.\n  Qed.\n\n  Lemma job_dzero_grant_cases\n        es ost' out\n        (RUN: run_itree (job (Some Grant) (Running false 0))\n                        None es ost' out)\n    : <<FAILED: es = [] /\\ out = None /\\ ost' = None>>\n        \\/\n      <<DEMAND_FAILED: exists dmd',\n        es = [Event _ Demand dmd'] /\\\n        out = None /\\ ost' = None>>\n        \\/\n      <<DEMAND_ZERO_REL:\n        es = [Event _ Demand 0] /\\\n        out = Some Release /\\\n        ost' = None>>\n        \\/\n      <<DEMAND_ZERO_SUCC:\n        es = [Event _ Demand 0; Event _ Compl tt] /\\\n        out = Some Release /\\\n        option_rel1 (fun st => st = Running false 0) ost'>>\n        \\/\n      <<DEMAND_USE_FAILED: exists dmd',\n          0 < dmd' /\\\n          es = [Event _ Demand dmd'; Event _ UseRes tt] /\\\n          out = None /\\ ost' = None>> \\/\n      <<DEMAND_USE_FAILED: exists dmd',\n          0 < dmd' /\\\n          es = [Event _ Demand dmd'; Event _ UseRes tt] /\\\n          out = None /\\ ost' = None>> \\/\n      <<DEMAND_ACQ_SUCC: exists dmd',\n          0 < dmd' /\\\n          es = [Event _ Demand dmd'; Event _ Compl tt] /\\\n          out = Some Acquire /\\\n          option_rel1 (fun st => st = Running false\n                                           (Nat.min MAX_TOUT dmd')) ost'>>\n  .\n  Proof.\n\n\n  Inductive step (inbox: msg_t?)\n    : t? -> list event -> t? -> msg_t? -> Prop :=\n  | Step_Fail st\n    : step inbox st [] None None\n  | Step_Init\n    : step inbox None [] (Some Init) None\n  | Step_Run\n      st es ost' out\n      (RUN: run_itree (job inbox st)\n                      None es ost' out)\n    : step inbox (Some st) es ost' out\n  .\n\nEnd Dev.\n\n\nModule Sys.\n  Record t: Set :=\n    mk { time: nat ;\n         inbox_controller: msgbox_t ;\n         controller: Ctrl.t ;\n\n         inbox_device1: msg_t? ;\n         device1: Dev.t? ;\n         inbox_device2: msg_t? ;\n         device2: Dev.t? ;\n         inbox_device3: msg_t? ;\n         device3: Dev.t? ;\n       }.\n\n  Definition sys_trace_t: Type :=\n    list (nat * event) *\n    list (nat * event) *\n    list (nat * event) *\n    list (nat * event).\n\n  Inductive step: t -> sys_trace_t -> t -> Prop :=\n    Step\n      tm inbc ctrl\n      dm1 dev1 dm2 dev2 dm3 dev3\n      es_c ctrl' dm1' dm2' dm3'\n      es_d1 dev1' cm1'\n      es_d2 dev2' cm2'\n      es_d3 dev3' cm3'\n      inbc' tr\n      (STEP_C: Ctrl.step inbc ctrl es_c ctrl'\n                         (dm1', dm2', dm3'))\n      (STEP_D1: Dev.step dm1 dev1 es_d1 dev1' cm1')\n      (STEP_D2: Dev.step dm2 dev2 es_d2 dev2' cm2')\n      (STEP_D3: Dev.step dm3 dev3 es_d3 dev3' cm3')\n      (INB_CTRL': inbc' = (cm1', cm2', cm3'))\n      (TRACE: tr = (map (fun x => (tm, x)) es_c ,\n                    map (fun x => (tm, x)) es_d1 ,\n                    map (fun x => (tm, x)) es_d2 ,\n                    map (fun x => (tm, x)) es_d3))\n    : step (mk tm inbc ctrl\n               dm1 dev1 dm2 dev2 dm3 dev3)\n           tr\n           (mk (S tm) inbc' ctrl'\n               dm1' dev1' dm2' dev2' dm3' dev3').\n\n  Definition init: t :=\n    mk O (None, None, None) Ctrl.init\n       None None None None None None.\n\n  Inductive state_trace\n    : t -> sys_trace_t -> t -> Prop :=\n  | StateTrace_Base st\n    : state_trace st ([], [], [], []) st\n\n  | StateTrace_Step\n      st tr1 tr2 tr3 tr4 st1\n      tr1' tr2' tr3' tr4' st'\n      str\n      (STEP: step st (tr1, tr2, tr3, tr4) st1)\n      (REST: state_trace st1 (tr1', tr2', tr3', tr4') st')\n      (TRACES: str = (tr1 ++ tr1', tr2 ++ tr2',\n                      tr3 ++ tr3', tr4 ++ tr4'))\n    : state_trace st str st'\n  .\n\nEnd Sys.\n\n\nSection PF.\n\n  Definition wf_queue (q: list nat): Prop :=\n    <<NODUP_Q: NoDup q >> /\\\n    <<VALID_IDS: Forall (fun x => 1 <= x <= 3) q>>.\n\n  Inductive tout_grant_rel: nat -> msg_t? -> Prop :=\n  | TOutGrant_MaxSent\n    : tout_grant_rel MAX_TOUT (Some Grant)\n  | TOutGrant_ZeroSent\n    : tout_grant_rel 0 (Some Grant)\n  | TOutGrant_ZeroNotSent\n    : tout_grant_rel 0 None\n  .\n\n  Inductive dms_inv: nat -> list Tid -> msgbox_t -> Prop :=\n  | DMSInv_NoMsgs\n      tout q\n      (NO_MSGS_COND: q = [] \\/ (0 < tout < MAX_TOUT))\n    : dms_inv tout q (None, None, None)\n\n  | DMSInv_Dev1\n      tout q' dm1\n      (DM1: tout_grant_rel tout dm1)\n    : dms_inv tout (1::q') (dm1, None, None)\n  | DMSInv_Dev2\n      tout q' dm2\n      (DM2: tout_grant_rel tout dm2)\n    : dms_inv tout (2::q') (None, dm2, None)\n  | DMSInv_Dev3\n      tout q' dm3\n      (DM3: tout_grant_rel tout dm3)\n    : dms_inv tout (3::q') (None, None, dm3)\n  .\n\n  Inductive ctrl_inv: Ctrl.t -> msgbox_t -> Prop :=\n    CtrlInv\n      tout q dms\n      (RANGE_TOUT: 0 <= tout <= MAX_TOUT)\n      (WF_Q: wf_queue q)\n      (EMPTY_QUEUE_TOUT_ZERO: length q = 0 -> tout = 0)\n      (DMS_INV: dms_inv tout q dms)\n    : ctrl_inv (Ctrl.mk tout q) dms.\n\n  Inductive dev_inv (tid: Tid) (ctrl: Ctrl.t)\n    : Dev.t? -> msg_t? -> Prop :=\n  | DevInv_Off cm\n    : dev_inv tid ctrl None cm\n  | DevInv_Init\n    : dev_inv tid ctrl (Some Dev.Init) None\n  | DevInv_NotOwnerWithDemand\n      dmd cm\n      (QHD_NEQ: hd_error (Ctrl.queue ctrl) = Some tid ->\n                Ctrl.timeout ctrl = 0 \\/\n                Ctrl.timeout ctrl = MAX_TOUT)\n      (DMD_POS: 0 < dmd <= MAX_TOUT)\n      (CM_CASES: cm = None \\/ cm = Some Acquire)\n      (CTRL_KNOWS_DEMAND: In tid (Ctrl.queue ctrl) \\/\n                          cm = Some Acquire)\n    : dev_inv tid ctrl\n              (Some (Dev.Running false dmd)) cm\n  | DevInv_NotOwnerWithoutDemand\n      cm\n      (QHD_REL: hd_error (Ctrl.queue ctrl) = Some tid ->\n                0 < Ctrl.timeout ctrl < MAX_TOUT ->\n                cm = Some Release)\n      (CM_CASES: cm = None \\/ cm = Some Release)\n    : dev_inv tid ctrl\n              (Some (Dev.Running false 0)) cm\n  | DevInv_Owner\n      dmd\n      (DMD_POS: 0 < dmd < MAX_TOUT)\n      (DMD_LE_TOUT:dmd <= Ctrl.timeout ctrl)\n      (QHD_EQ: hd_error (Ctrl.queue ctrl) = Some tid)\n    : dev_inv tid ctrl\n              (Some (Dev.Running true dmd)) None\n  .\n\n  Inductive sys_inv: Sys.t -> Prop :=\n    SysInv\n      tm cm1 cm2 cm3 ctrl\n      dm1 dev1 dm2 dev2 dm3 dev3\n      (INV_CTRL: ctrl_inv ctrl (dm1, dm2, dm3))\n      (INV_DEV1: dev_inv 1 ctrl dev1 cm1)\n      (INV_DEV2: dev_inv 2 ctrl dev2 cm2)\n      (INV_DEV3: dev_inv 3 ctrl dev3 cm3)\n    : sys_inv (Sys.mk tm (cm1, cm2, cm3) ctrl\n                      dm1 dev1 dm2 dev2 dm3 dev3).\n\n\n  Lemma sys_inv_init\n    : sys_inv Sys.init.\n  Proof.\n    econs.\n    - econs; ss.\n      { nia. }\n      { r. splits.\n        - econs.\n        - econs.\n      }\n      { econs 1. eauto. }\n    - econs 1.\n    - econs 1.\n    - econs 1.\n  Qed.\n\n  (* Lemma ctrl_inv_prsv *)\n  (*       ctrl dms cms *)\n  (*       es ctrl' dms' *)\n  (*       (INV: ctrl_inv ctrl dms) *)\n  (*       (STEP: Ctrl.step cms *)\n  (*                        ctrl es ctrl' dms') *)\n  (*   : ctrl_inv ctrl' dms'. *)\n  (* Proof. *)\n  (*   inv INV. *)\n  (*   inv STEP. *)\n  (* Admitted. *)\n\n\n  (* Lemma new_owner_timeout_aux1 *)\n  (*       tid cerr ms tout q *)\n  (*       ctrl' ms' *)\n  (*       (* (IF_QHD_TOUT_ZERO: hd_error q = Some tid -> tout = 0) *) *)\n  (*       (QHD_NEQ: hd_error q <> Some tid) *)\n  (*       (JOB_FUNC: Ctrl.job_func cerr ms (Ctrl.mk tout q) = (ctrl', ms')) *)\n  (*       (QHD': hd_error (Ctrl.queue ctrl') = Some tid) *)\n  (*   : Ctrl.timeout ctrl' = 0 \\/ *)\n  (*     Ctrl.timeout ctrl' = MAX_TOUT. *)\n  (* Proof. *)\n  (*   unfold Ctrl.job_func in *. *)\n  (* Admitted. *)\n\n\n  (* Lemma new_owner_timeout_aux2 *)\n  (*       tid cerr ms tout q *)\n  (*       ctrl' ms' *)\n  (*       (* (IF_QHD_TOUT_ZERO: hd_error q = Some tid -> tout = 0) *) *)\n  (*       (QHD_NEQ: hd_error q = Some tid) *)\n  (*       (TIMEOUT: tout = 0) *)\n  (*       (JOB_FUNC: Ctrl.job_func cerr ms (Ctrl.mk tout q) = (ctrl', ms')) *)\n  (*   : hd_error (Ctrl.queue ctrl') = Some tid /\\ *)\n  (*     Ctrl.timeout ctrl' = MAX_TOUT. *)\n  (* Proof. *)\n  (* Admitted. *)\n\n  Lemma inv_prsv_each_dev\n        (tid: Tid) (ctrl: Ctrl.t) (dev: Dev.t?)\n        (cm cm1 cm2 cm3: msg_t?)\n        (dm dm1 dm2 dm3: msg_t?)\n        es_c ctrl'\n        dm1' dm2' dm3'\n        es_d dev' cm'\n        (DEV_CASES:\n           (tid = 1 /\\ cm = cm1 /\\ dm = dm1) \\/\n           (tid = 2 /\\ cm = cm2 /\\ dm = dm2) \\/\n           (tid = 3 /\\ cm = cm3 /\\ dm = dm3))\n        (INV_CTRL: ctrl_inv ctrl (dm1, dm2, dm3))\n        (INV_DEV: dev_inv tid ctrl dev cm)\n        (STEP_C : Ctrl.step (cm1, cm2, cm3)\n                            ctrl es_c ctrl'\n                            (dm1', dm2', dm3'))\n        (STEP_D : Dev.step dm dev es_d dev' cm')\n    : <<INV_CTRL': ctrl_inv ctrl' (dm1', dm2', dm3')>> /\\\n      <<INV_DEV': dev_inv tid ctrl' dev' cm'>>.\n  Proof.\n    des; ss.\n    - subst.\n      inv INV_CTRL.\n      inv INV_DEV.\n      + (* dev none *)\n        assert (CTRL': ctrl_inv ctrl' (dm1', dm2', dm3')).\n        { admit. }\n        des.\n\n        inv STEP_D.\n        { splits.\n          2: { econs 1. }\n          eauto.\n        }\n        { splits.\n          2: { econs 2. }\n          eauto.\n        }\n      + (* init *)\n        assert (CTRL': ctrl_inv ctrl' (dm1', dm2', dm3')).\n        { admit. }\n\n        inv STEP_D.\n        { splits.\n          2: { econs 1. }\n          eauto.\n        }\n        { inv RUN; ss.\n          { splits.\n            2: { econs 1. }\n            eauto.\n          }\n\n          unfold Dev.job in OBS_EVT.\n          simpl_itree_hyp OBS_EVT.\n          ss. clarify. existT_elim. subst.\n          rename RUN_REST into RUN.\n          inv RUN; ss.\n          { esplits.\n            2: { econs 1. }\n            eauto.\n          }\n\n          clarify.\n          splits.\n          2: { econs 4; eauto. }\n          eauto.\n        }\n      + (* not_owner with_demand *)\n        guardH CM_CASES. ss.\n        guardH CTRL_KNOWS_DEMAND.\n\n        assert (<<CTRL': ctrl_inv ctrl' (dm1', dm2', dm3')>> /\\\n                <<IN_Q': In 1 (Ctrl.queue ctrl')>>).\n                (* <<QHD': hd_error q = Some 1 /\\ tout = 0 -> *)\n                (*       hd_error (Ctrl.queue ctrl') = Some 1 /\\ tout = MAX_TOUT>>). *)\n        { admit. }\n        des.\n\n        splits; ss.\n        inv STEP_D.\n        { econs. }\n\n        unfold Dev.job in RUN.\n        unfold Dev.update_demand in RUN.\n\n        destruct (Nat.eqb_spec dmd 0).\n        { exfalso. nia. }\n\n        unfold Dev.use_res in RUN.\n        simpl_itree_hyp RUN.\n\n        assert (DM_CASES: dm1 = None \\/ dm1 = Some Grant).\n        { inv DMS_INV; ss; eauto.\n          inv DM1; eauto. }\n        desH DM_CASES.\n        { subst dm1.\n          unfold Dev.send_msg in RUN.\n          simpl in RUN.\n          simpl_itree_hyp RUN.\n          rewrite Bool.andb_false_r in RUN.\n          simpl_itree_hyp RUN.\n          simpl_itree_hyp RUN.\n\n          inv RUN; ss.\n          { econs. }\n\n          clarify. existT_elim. subst.\n          inv RUN_REST; ss.\n          { econs 1. }\n          clarify.\n\n          econs 3; eauto.\n\n          assert (IF_QHD_TOUT_ZERO:\n                    hd_error q = Some 1 -> tout = 0).\n          { intro HD.\n            inv DMS_INV; ss.\n            - desH NO_MSGS_COND; ss.\n              + subst q. ss.\n              + exfalso.\n                hexploit QHD_NEQ; eauto. nia.\n            - inv DM1. ss.\n          }\n          (* from DMS_INV *)\n          intro QHD'.\n\n          inv STEP_C.\n          hexploit Ctrl.run_itree_func; eauto.\n          intro AUX1. desH AUX1. subst.\n\n          (* eapply new_owner_timeout_aux; eauto. *)\n          admit.\n        }\n        { (* dm1 = Some Grant *)\n          subst dm1.\n          ss.\n\n          assert (QHD_EQ: hd_error q = Some 1).\n          { inv DMS_INV.\n            inv DM1; ss. }\n\n          destruct (Nat.ltb_spec 0 dmd); ss.\n          2: { nia. }\n          simpl_itree_hyp RUN.\n          simpl_itree_hyp RUN.\n\n          inv RUN; ss.\n          { econs. }\n          clarify. existT_elim. subst.\n\n          simpl_itree_hyp RUN_REST.\n          unfold Dev.send_msg in RUN_REST. ss.\n\n          destruct (pred dmd) as [| dmd'] eqn:DMD'; ss.\n          - simpl_itree_hyp RUN_REST.\n            simpl_itree_hyp RUN_REST.\n            rename RUN_REST into RUN.\n            inv RUN; ss.\n            { econs. }\n            clarify. existT_elim. subst.\n\n            simpl_itree_hyp RUN_REST.\n            simpl_itree_hyp RUN_REST.\n            rename RUN_REST into RUN.\n            inv RUN; ss.\n            { econs 1. }\n\n            clarify. existT_elim. subst.\n            inv RUN_REST; ss.\n            { econs 1. }\n            clarify.\n            econs 4; eauto.\n\n          - simpl_itree_hyp RUN_REST.\n            simpl_itree_hyp RUN_REST.\n            rename RUN_REST into RUN.\n            inv RUN; ss.\n            { econs 1. }\n            clarify. existT_elim. subst.\n            inv RUN_REST; ss.\n            { econs 1. }\n            clarify.\n\n            assert (CASES': hd_error (Ctrl.queue ctrl') = Some 1 /\\\n                    ((Ctrl.timeout ctrl') = MAX_TOUT \\/\n                     (Ctrl.timeout ctrl') = pred MAX_TOUT)).\n            { admit. }\n            desH CASES'.\n            { econs 5; eauto.\n              nia. }\n            { econs 5; eauto.\n              nia. }\n        }\n\n      + (* not owner, without_demand *)\n        guardH CM_CASES. ss.\n\n        assert (<<CTRL': ctrl_inv ctrl' (dm1', dm2', dm3')>> /\\\n                <<IF_QHD_EQ': hd_error (Ctrl.queue ctrl') = Some 1 ->\n                              Ctrl.timeout ctrl' = 0 \\/\n                              Ctrl.timeout ctrl' = MAX_TOUT>>).\n        { admit. }\n        des.\n\n        splits; ss.\n        inv STEP_D.\n        { econs. }\n\n        unfold Dev.job in RUN.\n        unfold Dev.update_demand in RUN.\n        rewrite Nat.eqb_refl in RUN.\n        simpl_itree_hyp RUN.\n        simpl_itree_hyp RUN.\n\n        inv RUN; ss.\n        { econs 1. }\n\n        destruct dm1 as [m|].\n        * (* grant *)\n          clarify. existT_elim. subst.\n\n          inv DMS_INV.\n          assert (TOUT_CASES: m = Grant /\\\n                              (tout = 0 \\/ tout = MAX_TOUT)).\n          { inv DM1; eauto. }\n          destruct TOUT_CASES as [? TOUT_CASES].\n          subst m. guardH TOUT_CASES.\n          clear DM1. ss.\n\n          rename RUN_REST into RUN.\n          simpl_itree_hyp RUN.\n          unfold Dev.use_res in RUN. ss.\n\n          pose (dmd' := Nat.min MAX_TOUT r).\n          fold dmd' in RUN.\n\n          destruct (Nat.ltb_spec 0 dmd').\n          {\n\n\n\n\n\n\n          guardH TOUT_CASES.\n\n\n\n\n\n        TODO\n\n\n        assert (DM_CASES: dm1 = None \\/ dm1 = Some Grant).\n        { inv DMS_INV; ss; eauto.\n          inv DM1; eauto. }\n        desH DM_CASES.\n        { subst dm1.\n          unfold Dev.send_msg in RUN.\n          simpl in RUN.\n          simpl_itree_hyp RUN.\n          rewrite Bool.andb_false_r in RUN.\n          simpl_itree_hyp RUN.\n          simpl_itree_hyp RUN.\n\n          inv RUN; ss.\n          { econs. }\n\n          clarify. existT_elim. subst.\n          inv RUN_REST; ss.\n          { econs 1. }\n          clarify.\n\n          econs 3; eauto.\n\n          assert (IF_QHD_TOUT_ZERO:\n                    hd_error q = Some 1 -> tout = 0).\n          { intro HD.\n            inv DMS_INV; ss.\n            - desH NO_MSGS_COND; ss.\n              + subst q. ss.\n              + exfalso.\n                hexploit QHD_NEQ; eauto. nia.\n            - inv DM1. ss.\n          }\n          (* from DMS_INV *)\n          intro QHD'.\n\n          inv STEP_C.\n          hexploit Ctrl.run_itree_func; eauto.\n          intro AUX1. desH AUX1. subst.\n\n          (* eapply new_owner_timeout_aux; eauto. *)\n          admit.\n        }\n        { (* dm1 = Some Grant *)\n          subst dm1.\n          ss.\n\n          assert (QHD_EQ: hd_error q = Some 1).\n          { inv DMS_INV.\n            inv DM1; ss. }\n\n          destruct (Nat.ltb_spec 0 dmd); ss.\n          2: { nia. }\n          simpl_itree_hyp RUN.\n          simpl_itree_hyp RUN.\n\n          inv RUN; ss.\n          { econs. }\n          clarify. existT_elim. subst.\n\n          simpl_itree_hyp RUN_REST.\n          unfold Dev.send_msg in RUN_REST. ss.\n\n          destruct (pred dmd) as [| dmd'] eqn:DMD'; ss.\n          - simpl_itree_hyp RUN_REST.\n            simpl_itree_hyp RUN_REST.\n            rename RUN_REST into RUN.\n            inv RUN; ss.\n            { econs. }\n            clarify. existT_elim. subst.\n\n            simpl_itree_hyp RUN_REST.\n            simpl_itree_hyp RUN_REST.\n            rename RUN_REST into RUN.\n            inv RUN; ss.\n            { econs 1. }\n\n            clarify. existT_elim. subst.\n            inv RUN_REST; ss.\n            { econs 1. }\n            clarify.\n            econs 4. eauto.\n\n          - simpl_itree_hyp RUN_REST.\n            simpl_itree_hyp RUN_REST.\n            rename RUN_REST into RUN.\n            inv RUN; ss.\n            { econs 1. }\n            clarify. existT_elim. subst.\n            inv RUN_REST; ss.\n            { econs 1. }\n            clarify.\n\n            assert (CASES': hd_error (Ctrl.queue ctrl') = Some 1 /\\\n                    ((Ctrl.timeout ctrl') = MAX_TOUT \\/\n                     (Ctrl.timeout ctrl') = pred MAX_TOUT)).\n            { admit. }\n            desH CASES'.\n            { econs 5; eauto.\n              nia. }\n            { econs 5; eauto.\n              nia. }\n        }\n\n\n\n    }\n\n\n\n\n\n\n        desH CM_CASES.\n        * subst cm1.\n          desH CTRL_KNOWS_DEMAND; ss.\n\n          assert (<<CTRL': ctrl_inv ctrl' (dm1', dm2', dm3')>> /\\\n                  <<IN_Q': In 1 (Ctrl.queue ctrl')>>).\n          { admit. }\n          des.\n\n          splits; ss.\n          inv STEP_D.\n          { econs. }\n\n          unfold Dev.job in RUN.\n          unfold Dev.update_demand in RUN.\n\n          destruct (Nat.eqb_spec dmd 0).\n          { exfalso. nia. }\n\n          unfold Dev.use_res in RUN.\n          simpl_itree_hyp RUN.\n\n          assert (DM_CASES: dm1 = None \\/ dm1 = Some Grant).\n          { admit. }\n          desH DM_CASES.\n          { subst dm1.\n            unfold Dev.send_msg in RUN.\n            simpl in RUN.\n            simpl_itree_hyp RUN.\n            rewrite Bool.andb_false_r in RUN.\n            simpl_itree_hyp RUN.\n            simpl_itree_hyp RUN.\n\n            inv RUN; ss.\n            { econs. }\n\n            clarify. existT_elim. subst.\n            inv RUN_REST; ss.\n            { econs 1. }\n            clarify.\n\n            econs 3; eauto.\n\n            assert (hd_error q = Some 1 -> tout = 0).\n            { intro HD.\n              inv DMS_INV; ss.\n              - des; ss.\n                + subst q. ss.\n                + hexploit QHD_NEQ; eauto. nia.\n              - inv DM1. ss.\n            }\n            (* from DMS_INV *)\n            admit. (* if tout = 0, nxt timeout should be MAX_TOUT *)\n          }\n          { (* dm1 = Some Grant *)\n            subst dm1.\n            ss.\n\n            assert (QHD_EQ: hd_error q = Some 1).\n            { inv DMS_INV.\n              inv DM1; ss. }\n\n            destruct (Nat.ltb_spec 0 dmd); ss.\n            2: { nia. }\n            simpl_itree_hyp RUN.\n            simpl_itree_hyp RUN.\n\n            inv RUN; ss.\n            { econs. }\n            clarify. existT_elim. subst.\n\n            simpl_itree_hyp RUN_REST.\n            unfold Dev.send_msg in RUN_REST. ss.\n\n            destruct (pred dmd) as [| dmd'] eqn:DMD'; ss.\n            - simpl_itree_hyp RUN_REST.\n              simpl_itree_hyp RUN_REST.\n              rename RUN_REST into RUN.\n              inv RUN; ss.\n              { econs. }\n              clarify. existT_elim. subst.\n\n              simpl_itree_hyp RUN_REST.\n              simpl_itree_hyp RUN_REST.\n              rename RUN_REST into RUN.\n              inv RUN; ss.\n              { econs 1. }\n\n              clarify. existT_elim. subst.\n              inv RUN_REST; ss.\n              { econs 1. }\n              clarify.\n              econs 4. eauto.\n\n            - simpl_itree_hyp RUN_REST.\n              simpl_itree_hyp RUN_REST.\n              rename RUN_REST into RUN.\n              inv RUN; ss.\n              { econs 1. }\n              clarify. existT_elim. subst.\n              inv RUN_REST; ss.\n              { econs 1. }\n              clarify.\n\n              assert (hd_error (Ctrl.queue ctrl') = Some 1 /\\\n                      ((Ctrl.timeout ctrl') = MAX_TOUT \\/\n                       (Ctrl.timeout ctrl') = pred MAX_TOUT)).\n              { admit. }\n              des.\n              { econs 5; eauto.\n                nia. }\n              { econs 5; eauto.\n                nia. }\n          }\n\n        * (* cm1 is Acquire *)\n          subst cm1. ss.\n          clear CTRL_KNOWS_DEMAND.\n\n          assert (CTRL': ctrl_inv ctrl' (dm1', dm2', dm3')).\n          { admit. }\n\n          splits; eauto.\n\n          inv STEP_D.\n          { econs 1. }\n\n          unfold Dev.job in RUN.\n          unfold Dev.update_demand in RUN.\n\n          destruct (Nat.eqb_spec dmd 0).\n          { exfalso. nia. }\n\n          unfold Dev.use_res in RUN.\n          simpl_itree_hyp RUN.\n\n          assert (DM_CASES: dm1 = None \\/ dm1 = Some Grant).\n          { admit. }\n          desH DM_CASES.\n          { subst dm1.\n            unfold Dev.send_msg in RUN.\n            simpl in RUN.\n            simpl_itree_hyp RUN.\n            rewrite Bool.andb_false_r in RUN.\n            simpl_itree_hyp RUN.\n            simpl_itree_hyp RUN.\n\n            inv RUN; ss.\n            { econs. }\n\n            clarify. existT_elim. subst.\n            inv RUN_REST; ss.\n            { econs 1. }\n            clarify.\n\n            econs 3; eauto.\n\n            assert (hd_error q = Some 1 -> tout = 0).\n            { intro HD.\n              inv DMS_INV; ss.\n              - des; ss.\n                + subst q. ss.\n                + hexploit QHD_NEQ; eauto. nia.\n              - inv DM1. ss.\n            }\n            (* from DMS_INV *)\n            admit. (* if tout = 0, nxt timeout should be MAX_TOUT *)\n          }\n          { (* dm1 = Some Grant *)\n            subst dm1.\n            ss.\n\n            assert (QHD_EQ: hd_error q = Some 1).\n            { inv DMS_INV.\n              inv DM1; ss. }\n\n            destruct (Nat.ltb_spec 0 dmd); ss.\n            2: { nia. }\n            simpl_itree_hyp RUN.\n            simpl_itree_hyp RUN.\n\n            inv RUN; ss.\n            { econs. }\n            clarify. existT_elim. subst.\n\n            simpl_itree_hyp RUN_REST.\n            unfold Dev.send_msg in RUN_REST. ss.\n\n            destruct (pred dmd) as [| dmd'] eqn:DMD'; ss.\n            - simpl_itree_hyp RUN_REST.\n              simpl_itree_hyp RUN_REST.\n              rename RUN_REST into RUN.\n              inv RUN; ss.\n              { econs. }\n              clarify. existT_elim. subst.\n\n              simpl_itree_hyp RUN_REST.\n              simpl_itree_hyp RUN_REST.\n              rename RUN_REST into RUN.\n              inv RUN; ss.\n              { econs 1. }\n\n              clarify. existT_elim. subst.\n              inv RUN_REST; ss.\n              { econs 1. }\n              clarify.\n              econs 4. eauto.\n\n            - simpl_itree_hyp RUN_REST.\n              simpl_itree_hyp RUN_REST.\n              rename RUN_REST into RUN.\n              inv RUN; ss.\n              { econs 1. }\n              clarify. existT_elim. subst.\n              inv RUN_REST; ss.\n              { econs 1. }\n              clarify.\n\n              assert (hd_error (Ctrl.queue ctrl') = Some 1 /\\\n                      ((Ctrl.timeout ctrl') = MAX_TOUT \\/\n                       (Ctrl.timeout ctrl') = pred MAX_TOUT)).\n              { admit. }\n              des.\n              { econs 5; eauto.\n                nia. }\n              { econs 5; eauto.\n                nia. }\n          }\n\n\n\n          inv RUN; ss.\n\n\n\n\n\n\n\n              econs 5.\n              { (* dmd <= Ctrl.timeout -> dmd' <= Ctrl.timeout' *)\n                admit. }\n\n\n\n              destruct (Nat.eqb_spec dmd 0); ss.\n\n            inv RUN_REST; ss.\n            { econs. }\n\n            simpl_itree_hyp OBS_RET.\n            ss.\n\n\n\n\n          inv RUN; ss.\n          { econs. }\n\n\n\n\n\n\n\n\n\n        destruct q as [| qh qt].\n        { hexploit EMPTY_QUEUE_TOUT_ZERO; eauto.\n          clear EMPTY_QUEUE_TOUT_ZERO.\n          i. subst.\n\n          inv DMS_INV.\n          clear NO_MSGS_COND WF_Q RANGE_TOUT.\n\n          inv STEP_D.\n          - esplits.\n            2: { econs. }\n            admit. (* ctrl_inv prsv *)\n          -\n\n\n\n\n\n  Admitted.\n\n\n  Lemma sys_inv_prsv\n        st str st'\n        (INV: sys_inv st)\n        (STEP: Sys.step st str st')\n    : sys_inv st'.\n  Proof.\n    inv INV.\n    inv STEP.\n\n    hexploit (inv_prsv_each_dev 1); eauto.\n    hexploit (inv_prsv_each_dev 2); eauto.\n    hexploit (inv_prsv_each_dev 3); eauto.\n    i. des.\n    econs; eauto.\n  Qed.\n", "meta": {"author": "kim-yoonseung", "repo": "pals-thesis-dev", "sha": "1a165028f5461ed4d00a1e2720b3b1e4542f5dc2", "save_path": "github-repos/coq/kim-yoonseung-pals-thesis-dev", "path": "github-repos/coq/kim-yoonseung-pals-thesis-dev/pals-thesis-dev-1a165028f5461ed4d00a1e2720b3b1e4542f5dc2/src/apps/active_standby/design/DesignTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24564155936464754}}
{"text": "From RecoveryRefinement Require Import Lib.\n\nRequire Import OneDiskAPI.\nRequire Import TwoDiskAPI.\nRequire Import TwoDiskTheorems.\nRequire Import HoareTactics.\n\n(**\nReplicatedDisk provides a single-disk API on top of two disks, handling disk\nfailures with replication.\n*)\n\n\nModule ReplicatedDisk.\n\n  Import TwoDiskAPI.TwoDisk.\n\n  Import ProcNotations EqualDecNotation.\n  Open Scope proc_scope.\n\n  Definition read (a:addr) : proc Op block :=\n    mv0 <- td.read d0 a;\n    match mv0 with\n    | Working v => Ret v\n    | Failed =>\n      mv2 <- td.read d1 a;\n      match mv2 with\n      | Working v => Ret v\n      | Failed => Ret block0\n      end\n    end.\n\n  Definition write (a:addr) (b:block) : proc Op unit :=\n    _ <- td.write d0 a b;\n    _ <- td.write d1 a b;\n    Ret tt.\n\n  Definition size : proc Op nat :=\n    msz <- td.size d0;\n    match msz with\n    | Working sz => Ret sz\n    | Failed =>\n      msz <- td.size d1;\n      match msz with\n      | Working sz => Ret sz\n      | Failed => Ret 0\n      end\n    end.\n\n  (** [sizeInit] computes the size during initialization; it may return None if\n  the sizes of the underlying disks differ. *)\n  Definition sizeInit : proc Op (option nat) :=\n    sz1 <- td.size d0;\n    sz2 <- td.size d1;\n    match sz1 with\n    | Working sz1 =>\n      match sz2 with\n      | Working sz2 =>\n        if sz1 == sz2 then Ret (Some sz1) else Ret None\n      | Failed => Ret (Some sz1)\n      end\n    | Failed =>\n      match sz2 with\n      | Working sz2 => Ret (Some sz2)\n      | Failed => Ret None\n      end\n    end.\n\n  (* Recursively initialize block a and below. For simplicity, we make the disks\n  match by setting every block to [block0]. *)\n  Fixpoint init_at (a:nat) : proc Op unit :=\n    match a with\n    | 0 => Ret tt\n    | S a =>\n      _ <- td.write d0 a block0;\n      _ <- td.write d1 a block0;\n      init_at a\n    end.\n\n  (* Initialize every disk block *)\n  Definition init' : proc Op InitStatus :=\n    size <- sizeInit;\n    match size with\n    | Some sz =>\n      _ <- init_at sz;\n      Ret Initialized\n    | None =>\n      Ret InitFailed\n    end.\n\n  (**\n   * Helper theorems and tactics for proofs.\n   *)\n\n  Tactic Notation \"evar_tuple\" ident(a) ident(b) :=\n    match goal with\n    | [ |- ?aT * ?bT ] =>\n      let a := fresh a in\n      let b := fresh b in\n      evar (a : aT);\n      evar (b : bT);\n      exact (a, b)\n    end.\n\n  Ltac simplify :=\n    repeat match goal with\n           | |- forall _, _ => intros\n           | _ => deex\n           | _ => destruct_tuple\n           | [ u: unit |- _ ] => destruct u\n           | |- _ /\\ _ => split; [ solve [auto] | ]\n           | |- _ /\\ _ => split; [ | solve [auto] ]\n           | [ H: identity _ _ _ |- _ ] => apply identity_unfold in H\n           | |- list block => shelve\n           | |- disk => shelve\n           | |- disk*(disk -> Prop) => evar_tuple d F\n           | |- list block*(list block -> Prop) => evar_tuple d F\n           | _ => progress simpl in *\n           | _ => progress safe_intuition\n           | _ => progress subst\n           | _ => progress autorewrite with length array in *\n           end.\n\n  (* The [finish] tactic tries a number of techniques to solve the goal. *)\n  Ltac finish :=\n    repeat match goal with\n           | _ => solve_false\n           | _ => congruence\n           | _ => solve [ intuition (subst; eauto; try congruence) ]\n           | _ =>\n             (* if we can solve all the side conditions automatically, then it's\n             safe to run descend and create existential variables *)\n             descend; (intuition eauto);\n             lazymatch goal with\n             | |- proc_hspec _ _ _ => idtac\n             | |- proc_rspec _ _ _ _ => idtac\n             | _ => fail\n             end\n           end.\n\n  Ltac step :=\n    unshelve (step_proc); simplify; finish.\n\n  (**\n   * Specifications and proofs about our implementation of the replicated disk API,\n   * without considering our recovery.\n   *\n   * These intermediate specifications separate reasoning about the\n   * implementations from recovery behavior.\n   *)\n\n  Theorem both_disks_not_missing : forall (state: State),\n      disk0 state ?|= missing ->\n      disk1 state ?|= missing ->\n      False.\n  Proof.\n    destruct state; unfold missing; simpl; intuition auto.\n  Qed.\n\n  Global Hint Resolve both_disks_not_missing : false.\n\n  Theorem missing0_implies_any : forall (state: State) P,\n      disk0 state ?|= missing ->\n      disk0 state ?|= P.\n  Proof.\n    destruct state; unfold missing; simpl; intuition auto.\n  Qed.\n\n  Theorem missing1_implies_any : forall (state: State) P,\n      disk1 state ?|= missing ->\n      disk1 state ?|= P.\n  Proof.\n    destruct state; unfold missing; simpl; intuition auto.\n  Qed.\n\n  Global Hint Resolve missing0_implies_any : core.\n  Global Hint Resolve missing1_implies_any : core.\n  Global Hint Resolve read_ok write_ok size_ok : core.\n\n  Theorem read_int_ok : forall a d,\n      proc_hspec TDLayer\n        (read a)\n        (fun state =>\n           {|\n             pre := disk0 state ?|= eq d /\\\n                    disk1 state ?|= eq d;\n             post :=\n               fun state' r =>\n                 index d a ?|= eq r /\\\n                 disk0 state' ?|= eq d /\\\n                 disk1 state' ?|= eq d;\n             alternate :=\n               fun state' _ =>\n                 disk0 state' ?|= eq d /\\\n                 disk1 state' ?|= eq d;\n           |}).\n  Proof.\n    unfold read.\n    repeat (step; destruct r).\n  Qed.\n\n  Global Hint Resolve read_int_ok : core.\n\n  Theorem write_int_ok : forall a b d,\n      proc_hspec TDLayer\n        (write a b)\n        (fun state =>\n           {|\n             pre :=\n               disk0 state ?|= eq d /\\\n               disk1 state ?|= eq d;\n             post :=\n               fun state' r =>\n                 r = tt /\\\n                 disk0 state' ?|= eq (assign d a b) /\\\n                 disk1 state' ?|= eq (assign d a b);\n             alternate :=\n               fun state' _ =>\n                 (disk0 state' ?|= eq d /\\\n                  disk1 state' ?|= eq d) \\/\n                  ((disk0 state' ?|= eq (assign d a b) /\\\n                  disk1 state' ?|= eq d)) \\/\n                 (disk0 state' ?|= eq (assign d a b) /\\\n                  disk1 state' ?|= eq (assign d a b));\n           |}).\n  Proof.\n    unfold write.\n    step.\n\n    destruct r; step.\n    - descend; intuition eauto.\n\n      step.\n      destruct r; (intuition eauto); simplify.\n    - destruct (lt_dec a (length d)).\n      + eauto.\n        simplify.\n        destruct r; step.\n      + destruct r; step.\n  Qed.\n\n  Global Hint Resolve write_int_ok : core.\n\n  Theorem size_int_ok d_0 d_1:\n    proc_hspec TDLayer\n      (size)\n      (fun state =>\n         {|\n           pre :=\n             disk0 state ?|= eq d_0 /\\\n             disk1 state ?|= eq d_1 /\\\n             length d_0 = length d_1;\n           post :=\n             fun state' r =>\n               r = length d_0 /\\\n               r = length d_1 /\\\n               disk0 state' ?|= eq d_0 /\\\n               disk1 state' ?|= eq d_1;\n           alternate :=\n             fun state' _ =>\n               disk0 state' ?|= eq d_0 /\\\n               disk1 state' ?|= eq d_1;\n         |}).\n  Proof.\n    unfold size.\n    step.\n    destruct r; step.\n    destruct r; step.\n  Qed.\n\n  Global Hint Resolve size_int_ok : core.\n\n  Definition equal_after a (d_0 d_1: disk) :=\n    length d_0 = length d_1 /\\\n    forall a', a <= a' -> index d_0 a' = index d_1 a'.\n\n  Theorem le_eq_or_S_le : forall n m,\n      n <= m ->\n      n = m \\/\n      S n <= m /\\ n <> m.\n  Proof.\n    intros.\n    lia.\n  Qed.\n\n  Theorem equal_after_assign : forall a d_0 d_1 b,\n      equal_after (S a) d_0 d_1 ->\n      equal_after a (assign d_0 a b) (assign d_1 a b).\n  Proof.\n    unfold equal_after; intuition.\n    - autorewrite with length; eauto.\n    - apply le_eq_or_S_le in H; intuition subst.\n      + destruct (lt_dec a' (length d_0)); autorewrite with array; auto.\n      + autorewrite with array; auto.\n  Qed.\n\n  Global Hint Resolve equal_after_assign : core.\n\n  Theorem init_at_ok : forall a d_0 d_1,\n      proc_hspec TDLayer\n        (init_at a)\n        (fun state =>\n           {| pre :=\n                disk0 state ?|= eq d_0 /\\\n                disk1 state ?|= eq d_1 /\\\n                equal_after a d_0 d_1;\n              post :=\n                fun state' _ =>\n                  exists d_0' d_1': disk,\n                    disk0 state' ?|= eq d_0' /\\\n                    disk1 state' ?|= eq d_1' /\\\n                    equal_after 0 d_0' d_1';\n              alternate :=\n                fun state' _ => True;\n           |}).\n  Proof.\n    induction a; simpl; intros.\n    - step.\n    - step.\n\n      step. do 2 especialize IHa.\n      destruct r; finish.\n      + step; destruct r; simplify; finish.\n      + step; destruct r; finish.\n  Qed.\n\n  Global Hint Resolve init_at_ok : core.\n\n  Theorem sizeInit_ok d_0 d_1 :\n    proc_hspec TDLayer\n      (sizeInit)\n      (fun state =>\n         {| pre :=\n              disk0 state ?|= eq d_0 /\\\n              disk1 state ?|= eq d_1;\n            post :=\n              fun state' r =>\n                exists d_0' d_1',\n                  disk0 state' ?|= eq d_0' /\\\n                  disk1 state' ?|= eq d_1' /\\\n                  match r with\n                  | Some sz => length d_0' = sz /\\ length d_1' = sz\n                  | None => True\n                  end;\n            alternate :=\n              fun state' _ => True;\n         |}).\n  Proof.\n    unfold sizeInit.\n    step.\n    destruct r.\n    - step.\n      destruct r.\n      + destruct (length d_0 == v).\n        * step.\n        * step.\n      + step.\n    - step.\n      destruct r.\n      + step.\n      + step.\n  Qed.\n\n  Global Hint Resolve sizeInit_ok : core.\n\n\n  Theorem equal_after_0_to_eq : forall d_0 d_1,\n      equal_after 0 d_0 d_1 ->\n      d_0 = d_1.\n  Proof.\n    unfold equal_after; intuition.\n    eapply index_ext_eq; intros.\n    eapply H1; lia.\n  Qed.\n\n  Theorem equal_after_size : forall d_0 d_1,\n      length d_0 = length d_1 ->\n      equal_after (length d_0) d_0 d_1.\n  Proof.\n    unfold equal_after; intuition.\n    assert (~a' < length d_0) by lia.\n    assert (~a' < length d_1) by congruence.\n    autorewrite with array; eauto.\n  Qed.\n\n  Global Hint Resolve equal_after_size : core.\n  Global Hint Resolve equal_after_0_to_eq : core.\n\n  Theorem init'_ok d_0 d_1:\n    proc_hspec TDLayer\n      (init')\n      (fun state =>\n         {| pre :=\n              disk0 state ?|= eq d_0 /\\\n              disk1 state ?|= eq d_1;\n            post :=\n              fun state' r =>\n                match r with\n                | Initialized =>\n                  exists d_0' d_1',\n                  disk0 state' ?|= eq d_0' /\\\n                  disk1 state' ?|= eq d_1' /\\\n                  d_0' = d_1'\n                | InitFailed =>\n                  True\n                end;\n            alternate :=\n              fun state' _ => True;\n         |}).\n  Proof.\n    step.\n    spec_intros.\n    simpl in H1. repeat deex.\n    destruct r; step.\n    step.\n  Qed.\n\n  Theorem init'_ok_closed:\n    proc_hspec TDLayer\n      (init')\n      (fun state =>\n         {| pre := True;\n            post :=\n              fun state' r =>\n                match r with\n                | Initialized =>\n                  exists d_0' d_1',\n                  disk0 state' ?|= eq d_0' /\\\n                  disk1 state' ?|= eq d_1' /\\\n                  d_0' = d_1'\n                | InitFailed =>\n                  True\n                end;\n            alternate :=\n              fun state' _ => True;\n         |}).\n  Proof.\n    spec_intros.\n    destruct state0; simplify.\n    - eapply proc_hspec_impl; unfold spec_impl; [| eapply (init'_ok d_0)]; simplify.\n    - eapply proc_hspec_impl; unfold spec_impl; [| eapply (init'_ok d_0 d_0)]; simplify.\n    - eapply proc_hspec_impl; unfold spec_impl; [| eapply (init'_ok d_1)]; simplify.\n  Qed.\n\n  (**\n   * Recovery implementation.\n   *\n   * General structure for recovery: essentially, it consists of\n   * a loop around [fixup] that terminates after either fixing an out-of-sync\n   * disk block or when a disk has failed.\n  *)\n\n  (* [fixup] returns a [RecStatus] to implement early termination in [recovery_at]. *)\n  Inductive RecStatus :=\n  (* continue working, nothing interesting has happened *)\n  | Continue\n  (* some address has been repaired (or the recovery has exhausted the\n     addresses) - only one address can be out of sync and thus only it must be\n     recovered. *)\n  (* OR, one of the disks has failed, so don't bother continuing recovery since\n     the invariant is now trivially satisfied *)\n  | RepairDoneOrFailed.\n\n  Definition fixup (a:addr) : proc Op RecStatus :=\n    mv0 <- td.read d0 a;\n    match mv0 with\n    | Working v =>\n      mv2 <- td.read d1 a;\n      match mv2 with\n      | Working v' =>\n        if v == v' then\n          Ret Continue\n        else\n          mu <- td.write d1 a v;\n          Ret RepairDoneOrFailed\n      | Failed => Ret RepairDoneOrFailed\n      end\n    | Failed => Ret RepairDoneOrFailed\n    end.\n\n  (* recursively performs recovery at [a-1], [a-2], down to 0 *)\n  Fixpoint recover_at (a:addr) : proc Op unit :=\n    match a with\n    | 0 => Ret tt\n    | S n =>\n      s <- fixup n;\n      match s with\n      | Continue => recover_at n\n      | RepairDoneOrFailed => Ret tt\n      end\n    end.\n\n  Definition Recover : proc Op unit :=\n    sz <- size;\n    _ <- recover_at sz;\n    Ret tt.\n\n\n  (**\n   * Theorems and recovery proofs.\n   *)\n\n  Theorem if_lt_dec : forall A n m (a a':A),\n      n < m ->\n      (if lt_dec n m then a else a') = a.\n  Proof.\n    intros.\n    destruct (lt_dec n m); auto.\n    contradiction.\n  Qed.\n\n  Theorem disks_eq_inbounds : forall (d: disk) a v v',\n      a < length d ->\n      index d a ?|= eq v ->\n      index d a ?|= eq v' ->\n      v = v'.\n  Proof.\n    intros.\n    case_eq (index d a); intros.\n    - rewrite H2 in *. simpl in *. congruence.\n    - exfalso.\n      apply index_not_none in H2; eauto.\n  Qed.\n\n  (* To make these specifications precise while also covering both the already\n   * synced and diverged disks cases, we keep track of which input state we're\n   * in from the input and use it to give an exact postcondition. *)\n  Inductive DiskStatus :=\n  | FullySynced\n  | OutOfSync (a:addr) (b:block).\n\n  Theorem assign_maybe_same : forall (d:disk) a b,\n      index d a ?|= eq b ->\n      assign d a b = d.\n  Proof.\n    intros.\n    destruct (lt_dec a (length d));\n      autorewrite with array;\n      auto.\n    destruct_with_eqn (index d a); simpl in *; subst; eauto.\n    - apply index_ext_eq; intros i.\n      destruct (lt_dec i (length d)), (a == i);\n        subst;\n        autorewrite with array;\n        auto.\n    - exfalso; apply index_not_none in Heqo; auto.\n  Qed.\n\n#[global]\n  Hint Rewrite assign_maybe_same using (solve [ auto ]) : array.\n  Global Hint Resolve PeanoNat.Nat.lt_neq : core.\n  Global Hint Resolve disks_eq_inbounds : core.\n\n  (* we will show that fixup does nothing once the disks are the same *)\n  Theorem fixup_equal_ok : forall a d,\n      proc_hspec TDLayer\n        (fixup a)\n        (fun state =>\n           {|\n             pre :=\n               (* for simplicity we only consider in-bounds addresses, though\n                  if a is out-of-bounds fixup just might uselessly write to\n                  disk and not do anything *)\n               a < length d /\\\n               disk0 state ?|= eq d /\\\n               disk1 state ?|= eq d;\n             post :=\n               fun state' r =>\n                 disk0 state' ?|= eq d /\\\n                 disk1 state' ?|= eq d;\n             alternate :=\n               fun state' _ =>\n                 disk0 state' ?|= eq d /\\\n                 disk1 state' ?|= eq d;\n           |}).\n  Proof.\n    unfold fixup.\n    step.\n\n    destruct r; step.\n\n    destruct r; try step.\n    destruct (v == v0); subst; try step.\n\n    Unshelve.\n    { auto. }\n    { exact (fun _ => True). }\n  Qed.\n\n  Theorem fixup_correct_addr_ok : forall a d b,\n      proc_hspec TDLayer\n        (fixup a)\n        (fun state =>\n           {|\n             pre :=\n               a < length d /\\\n               disk0 state ?|= eq (assign d a b) /\\\n               disk1 state ?|= eq d;\n             post :=\n               fun state' r =>\n                 match r with\n                 | Continue =>\n                   (* could happen if b already happened to be value *)\n                   disk0 state' ?|= eq (assign d a b) /\\\n                   disk1 state' ?|= eq (assign d a b)\n                 | RepairDoneOrFailed =>\n                   (disk0 state' ?|= eq (assign d a b) /\\\n                    disk1 state' ?|= eq (assign d a b)) \\/\n                   (disk0 state' ?|= eq d /\\\n                    disk1 state' ?|= eq d)\n                 end;\n             alternate :=\n               fun state' _ =>\n                 (disk0 state' ?|= eq (assign d a b) /\\\n                  disk1 state' ?|= eq (assign d a b)) \\/\n                 (disk0 state' ?|= eq (assign d a b) /\\\n                  disk1 state' ?|= eq d) \\/\n                 (disk0 state' ?|= eq d /\\\n                  disk1 state' ?|= eq d);\n           |}).\n  Proof.\n    unfold fixup; intros.\n    step.\n\n    destruct r; try step.\n\n    destruct r; try step.\n    destruct (b == v); subst; try step.\n\n    step.\n    destruct r; simplify; finish.\n  Qed.\n\n  Theorem fixup_wrong_addr_ok : forall a d b a',\n      proc_hspec TDLayer\n        (fixup a)\n        (fun state =>\n           {|\n             pre :=\n               a < length d /\\\n               (* recovery, working from end of disk, has not yet reached the\n                  correct address *)\n               a' < a /\\\n               disk0 state ?|= eq (assign d a' b) /\\\n               disk1 state ?|= eq d;\n             post :=\n               fun state' r =>\n                 match r with\n                 | Continue =>\n                   disk0 state' ?|= eq (assign d a' b) /\\\n                   disk1 state' ?|= eq d\n                 | RepairDoneOrFailed =>\n                   (disk0 state' ?|= eq d /\\\n                    disk1 state' ?|= eq d) \\/\n                   (disk0 state' ?|= eq (assign d a' b) /\\\n                    disk1 state' ?|= eq (assign d a' b))\n                 end;\n             alternate :=\n               fun state' _ =>\n                 (disk0 state' ?|= eq (assign d a' b) /\\\n                  disk1 state' ?|= eq d) \\/\n                 (disk0 state' ?|= eq d /\\\n                  disk1 state' ?|= eq d);\n           |}).\n  Proof.\n    unfold fixup; intros.\n    step.\n\n    destruct r; try step.\n    destruct r; try step.\n\n    destruct (v == v0); subst.\n    - step.\n    - step.\n    Unshelve.\n    { auto. }\n    { exact (fun _ => True). }\n  Qed.\n\n  Ltac spec_case pf :=\n    eapply proc_hspec_impl; [ unfold spec_impl | solve [ apply pf ] ].\n\n\n  Theorem fixup_ok : forall a d s,\n      proc_hspec TDLayer\n        (fixup a)\n        (fun state =>\n           {|\n             pre :=\n               a < length d /\\\n               match s with\n               | FullySynced => disk0 state ?|= eq d /\\\n                               disk1 state ?|= eq d\n               | OutOfSync a' b => a' <= a /\\\n                                  disk0 state ?|= eq (assign d a' b) /\\\n                                  disk1 state ?|= eq d\n               end;\n             post :=\n               fun state' r =>\n                 match s with\n                 | FullySynced => disk0 state' ?|= eq d /\\\n                                 disk1 state' ?|= eq d\n                 | OutOfSync a' b =>\n                   match r with\n                   | Continue =>\n                     (a' < a /\\\n                      disk0 state' ?|= eq (assign d a' b) /\\\n                      disk1 state' ?|= eq d) \\/\n                     (disk0 state' ?|= eq (assign d a' b) /\\\n                      disk1 state' ?|= eq (assign d a' b))\n                   | RepairDoneOrFailed =>\n                     (disk0 state' ?|= eq d /\\\n                      disk1 state' ?|= eq d) \\/\n                     (disk0 state' ?|= eq (assign d a' b) /\\\n                      disk1 state' ?|= eq (assign d a' b))\n                   end\n                 end;\n             alternate :=\n               fun state' _ =>\n                 match s with\n                 | FullySynced => disk0 state' ?|= eq d /\\\n                                 disk1 state' ?|= eq d\n                 | OutOfSync a' b =>\n                   (disk0 state' ?|= eq (assign d a' b) /\\\n                    disk1 state' ?|= eq (assign d a' b)) \\/\n                   (disk0 state' ?|= eq (assign d a' b) /\\\n                    disk1 state' ?|= eq d) \\/\n                   (disk0 state' ?|= eq d /\\\n                    disk1 state' ?|= eq d)\n                 end;\n           |}).\n  Proof.\n    spec_intros; simplify.\n    destruct s; intuition eauto.\n    - spec_case fixup_equal_ok; simplify; finish.\n    - apply PeanoNat.Nat.lt_eq_cases in H1; intuition.\n      + spec_case (fixup_wrong_addr_ok a d b a0); simplify; finish.\n        destruct v; finish.\n      + spec_case fixup_correct_addr_ok; simplify; finish.\n        split. { intuition eauto. }\n        simplify; finish.\n        destruct v; finish.\n  Qed.\n\n  Global Hint Resolve fixup_ok : core.\n\n  (* Hint Resolve Lt.lt_n_Sm_le. *)\n\n  Theorem recover_at_ok : forall a d s,\n      proc_hspec TDLayer\n        (recover_at a)\n        (fun state =>\n           {|\n             pre :=\n               a <= length d /\\\n               match s with\n               | FullySynced => disk0 state ?|= eq d /\\\n                               disk1 state ?|= eq d\n               | OutOfSync a' b => a' < a /\\\n                                  disk0 state ?|= eq (assign d a' b) /\\\n                                  disk1 state ?|= eq d\n               end;\n             post :=\n               fun state' r =>\n                 match s with\n                 | FullySynced =>\n                   disk0 state' ?|= eq d /\\\n                   disk1 state' ?|= eq d\n                 | OutOfSync a' b =>\n                   (disk0 state' ?|= eq d /\\\n                    disk1 state' ?|= eq d) \\/\n                   (disk0 state' ?|= eq (assign d a' b) /\\\n                    disk1 state' ?|= eq (assign d a' b))\n                 end;\n             alternate :=\n               fun state' _ =>\n                 match s with\n                 | FullySynced => disk0 state' ?|= eq d /\\\n                                 disk1 state' ?|= eq d\n                 | OutOfSync a' b =>\n                   (disk0 state' ?|= eq d /\\\n                    disk1 state' ?|= eq d) \\/\n                   (disk0 state' ?|= eq (assign d a' b) /\\\n                    disk1 state' ?|= eq d) \\/\n                   (disk0 state' ?|= eq (assign d a' b) /\\\n                    disk1 state' ?|= eq (assign d a' b))\n                 end;\n           |}).\n  Proof.\n    induction a; simpl; intros.\n    - step.\n      destruct s; simplify.\n    - step.\n      destruct s; simplify.\n      * specialize (IHa d FullySynced).\n        simplify; finish.\n        destruct r; step.\n        lia.\n      * split; [intuition; eauto; try lia|].\n        simplify; finish.\n        destruct r.\n        ** spec_intros. simpl in H3. destruct H3.\n           *** specialize (IHa d (OutOfSync a0 b)).\n               step. lia.\n           *** specialize (IHa (assign d a0 b) FullySynced).\n               step. autorewrite with length in *; lia.\n        ** step.\n  Qed.\n\n  Global Hint Resolve recover_at_ok : core.\n\n  Definition Recover_spec : _ -> _ -> Specification unit unit State :=\n    fun d s state =>\n      {|\n        pre :=\n          match s with\n          | FullySynced => disk0 state ?|= eq d /\\\n                          disk1 state ?|= eq d\n          | OutOfSync a b => disk0 state ?|= eq (assign d a b) /\\\n                             disk1 state ?|= eq d\n          end;\n        post :=\n          fun state' (_:unit) =>\n            match s with\n            | FullySynced => disk0 state' ?|= eq d /\\\n                            disk1 state' ?|= eq d\n            | OutOfSync a b =>\n              (disk0 state' ?|= eq d /\\\n               disk1 state' ?|= eq d) \\/\n              (disk0 state' ?|= eq (assign d a b) /\\\n               disk1 state' ?|= eq (assign d a b))\n            end;\n        alternate :=\n          fun state' (_:unit) =>\n            match s with\n            | FullySynced => disk0 state' ?|= eq d /\\\n                            disk1 state' ?|= eq d\n            | OutOfSync a b =>\n              (disk0 state' ?|= eq d /\\\n               disk1 state' ?|= eq d) \\/\n              (disk0 state' ?|= eq (assign d a b) /\\\n               disk1 state' ?|= eq d) \\/\n              (disk0 state' ?|= eq (assign d a b) /\\\n               disk1 state' ?|= eq (assign d a b))\n            end;\n      |}.\n\n  Inductive rec_prot : Type :=\n    | prot_sync1 : rec_prot\n    | prot_out : rec_prot\n    | prot_sync2 : rec_prot.\n\n  Theorem Recover_rok1 d s :\n    proc_hspec TDLayer\n      (Recover)\n      (Recover_spec d s).\n  Proof.\n    unfold Recover, Recover_spec; intros.\n    spec_intros; simplify.\n    destruct s; simplify.\n    + step.\n      unshelve (step).\n      { exact d. } { exact FullySynced. }\n      simplify; finish.\n      step.\n    + step.\n      intuition eauto.\n      { simplify. }\n      destruct (lt_dec a (length d)).\n      * unshelve (step).\n        { exact d. } { exact (OutOfSync a b). }\n        simplify; finish.\n        step.\n      * unshelve (step).\n        { exact d. } { exact FullySynced. }\n        simplify.\n        step.\n  Qed.\n\n  Theorem Recover_rok2 d a b rp:\n    proc_hspec TDLayer\n      (Recover)\n      (match rp with\n       | prot_sync1 => Recover_spec d (FullySynced)\n       | prot_out => Recover_spec d (OutOfSync a b)\n       | prot_sync2 => Recover_spec (assign d a b) (FullySynced)\n       end).\n  Proof.\n    unfold Recover, Recover_spec; intros.\n    spec_intros; simplify.\n    destruct rp; simplify.\n    + step.\n        unshelve (step).\n        { exact d. } { exact FullySynced. }\n        simplify; finish.\n        step.\n    + step.\n      intuition eauto.\n      { simplify. }\n      destruct (lt_dec a (length d)).\n      * unshelve (step).\n        { exact d. } { exact (OutOfSync a b). }\n        simplify; finish.\n        step.\n      * unshelve (step).\n        { exact d. } { exact FullySynced. }\n        simplify.\n        step.\n    + step.\n      intuition eauto.\n      simplify.\n      destruct (lt_dec a (length d)).\n      * unshelve (step).\n        { exact (assign d a b). }\n        { exact (OutOfSync a b). }\n        simplify; finish.\n        step.\n        intuition simplify.\n      * unshelve (step).\n        { exact (assign d a b). } { exact (FullySynced). }\n        simplify; finish.\n        step.\n  Qed.\n\n  Theorem Recover_spec_idempotent1 d :\n    idempotent (fun (t : unit) => Recover_spec d (FullySynced)).\n  Proof.\n    unfold idempotent; intuition; simplify.\n    exists tt; finish.\n  Qed.\n\n  Theorem Recover_spec_idempotent2 d a b :\n    idempotent\n      (fun rp : rec_prot =>\n         match rp with\n         | prot_sync1 => Recover_spec d (FullySynced)\n         | prot_out => Recover_spec d (OutOfSync a b)\n         | prot_sync2 => Recover_spec (assign d a b) (FullySynced)\n         end).\n  Proof.\n    unfold idempotent; intuition; simplify.\n    unfold identity in *; subst.\n    destruct a0.\n    - exists prot_sync1; simplify; finish.\n    - destruct H0; [| destruct H0].\n      ** exists (prot_sync1); simplify; finish.\n      ** exists (prot_out); simplify; finish.\n      ** exists (prot_sync2); simplify; finish.\n    - exists prot_sync2; simplify; finish.\n  Qed.\n\n  (* As the final step in giving the correctness of the replicated disk\n  operations, we prove recovery specs that include the replicated disk Recover\n  function. *)\n\n  Definition rd_abstraction (d:D.State) (state: State) (u: unit) : Prop :=\n    disk0 state ?|= eq d /\\\n    disk1 state ?|= eq d.\n\n  Theorem read_rec_ok :\n    forall a d, proc_rspec TDLayer (read a) Recover\n                           (refine_spec rd_abstraction (OneDiskAPI.read_spec a) d).\n  Proof.\n    intros a d.\n    eapply proc_hspec_to_rspec; eauto using Recover_spec_idempotent1;\n      unfold refine_spec, rd_abstraction in *.\n    - intros []. eapply Recover_rok1.\n    - descend; simplify; intuition eauto.\n    - descend; simplify; intuition eauto.\n      exists tt. subst; intuition eauto.\n    - simplify. exists d; split; eauto.\n  Qed.\n\n  Theorem write_rec_ok :\n    forall a b d, proc_rspec TDLayer (write a b) Recover\n                             (refine_spec rd_abstraction (OneDiskAPI.write_spec a b) d).\n  Proof.\n    intros a b d.\n    eapply proc_hspec_to_rspec; eauto using Recover_spec_idempotent2;\n      unfold refine_spec, rd_abstraction in *.\n    - intros. eapply Recover_rok2.\n    - descend; simplify; intuition eauto.\n    - intros.\n      simpl in *.\n      (intuition eauto);\n        repeat match goal with\n               | [ H: identity _ _ _ |- _ ] => inv_clear H\n               end.\n      * exists (prot_sync1); simplify; finish.\n      * exists (prot_out); simpl.\n        intuition eauto.\n      * assert (a < length d \\/ a >= length d) as [Hlt|Hoob] by lia.\n        ** exists (prot_sync2); simplify; finish.\n        ** exists (prot_sync1); simplify; finish.\n    - unfold rd_abstraction in *; simplify. destruct a0, H0.\n      * exists d. simplify; finish.\n      * exists d. simplify; finish.\n      * exists (assign d a b); simplify; finish.\n      * exists (assign d a b); simplify; finish.\n  Qed.\n\n  Theorem size_rec_ok :\n    forall d, proc_rspec TDLayer (size) Recover\n                         (refine_spec rd_abstraction (OneDiskAPI.size_spec) d).\n  Proof.\n    intros d.\n    eapply proc_hspec_to_rspec; eauto using Recover_spec_idempotent1;\n      unfold refine_spec, rd_abstraction in *.\n    - intros. eapply Recover_rok1.\n    - descend; simplify; intuition eauto.\n    - descend; simplify; intuition eauto.\n      exists tt. intuition eauto.\n    - simplify. exists d; split; eauto.\n  Qed.\n\n  Global Hint Resolve read_rec_ok size_rec_ok write_rec_ok : core.\n\n  Import Helpers.RelationAlgebra.\n  Import RelationNotations.\n\n  Definition Impl_TD_OD: LayerImpl Op D.Op :=\n    {| compile_op := fun (T : Type) (op : D.Op T) =>\n                       match op in (D.Op T0) return (proc Op T0) with\n                       | D.op_read a => read a\n                       | D.op_write a b => write a b\n                       | D.op_size => size\n                       end;\n       init := init';\n       Layer.recover := Recover |}.\n\n\n  Lemma one_disk_failure_id x:\n    D.one_disk_failure x x tt.\n  Proof. econstructor. Qed.\n\n  Lemma one_disk_failure_id_l r x:\n    (D.one_disk_failure + r)%rel x x tt.\n  Proof. left. econstructor. Qed.\n\n  Global Hint Resolve one_disk_failure_id one_disk_failure_id_l : core.\n  Global Hint Constructors D.op_step : core.\n\n  Lemma compile_refine_TD_OD:\n    compile_op_refines_step TDLayer D.ODLayer Impl_TD_OD rd_abstraction.\n  Proof.\n    unfold compile_op_refines_step.\n    intros T op. destruct op.\n    * eapply proc_rspec_crash_refines_op; [ intros; eapply read_rec_ok |..]; simplify; eauto.\n      econstructor; destruct (index _ _); eauto.\n    * eapply proc_rspec_crash_refines_op; [ intros; eapply write_rec_ok |..]; simplify; eauto.\n      intuition; subst; intuition eauto.\n    * eapply proc_rspec_crash_refines_op; [ intros; eapply size_rec_ok |..]; simplify; eauto.\n  Qed.\n\n  Theorem Recover_noop d :\n    proc_rspec TDLayer\n      (Recover)\n      (Recover)\n      (Recover_spec d (FullySynced)).\n  Proof.\n    eapply proc_hspec_to_rspec; eauto using Recover_spec_idempotent1.\n    { eapply Recover_rok1. }\n    { intros []. eapply Recover_rok1. }\n    { simplify. exists tt. eauto. }\n    { simplify. }\n  Qed.\n\n  Lemma recovery_refines_TD_OD:\n    recovery_refines_crash_step TDLayer D.ODLayer Impl_TD_OD rd_abstraction.\n  Proof.\n    unfold recovery_refines_crash_step.\n    eapply proc_rspec_recovery_refines_crash_step; [ eapply Recover_noop|..];\n      unfold rd_abstraction; simplify; subst; finish.\n  Qed.\n\n  Lemma Refinement_TD_OD: LayerRefinement TDLayer D.ODLayer.\n  Proof.\n    unshelve (econstructor).\n    - apply Impl_TD_OD.\n    - exact rd_abstraction.\n    - exact compile_refine_TD_OD.\n    - exact recovery_refines_TD_OD.\n    - eapply proc_hspec_init_ok; unfold rd_abstraction.\n      { eapply init'_ok_closed. }\n      { simplify. }\n      { simplify; firstorder. }\n  Defined.\n\nEnd ReplicatedDisk.\n\n(*\nPrint Assumptions ReplicatedDisk.Refinement_TD_OD.\n*)\n", "meta": {"author": "mit-pdos", "repo": "argosy", "sha": "a6a5aa0d3868efd4ada0b40927b5748e5d8967d3", "save_path": "github-repos/coq/mit-pdos-argosy", "path": "github-repos/coq/mit-pdos-argosy/argosy-a6a5aa0d3868efd4ada0b40927b5748e5d8967d3/src/Examples/ReplicatedDisk/ReplicatedDiskImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24564155936464754}}
{"text": "Require Import Term_Defs StructTactics.\n\nCheck Term.\n\nRequire Import List.\nImport List.ListNotations.\nRequire Import MonadVM VmSemantics Impl_vm Term_Defs ConcreteEvidence. \n\nDefinition secret_evidence_rel := Evidence -> Plc -> Prop.\n\nDefinition evidence_subset_of (e:Evidence) (e':Evidence): Prop.\nAdmitted.\n\nDefinition policy_protects : secret_evidence_rel.\nAdmitted.\n\nInductive evidence_disclosed' : Plc -> Plc -> Evidence -> Term -> secret_evidence_rel :=\n| cumul_req: forall t e e' init requester me,\n    evidence_subset_of e e' ->\n    e' = eval t me init ->\n    evidence_disclosed' requester me init t e requester\n| cumul_me: forall t e e' init requester me,\n    evidence_subset_of e e' ->\n    e' = eval t me init ->\n    evidence_disclosed' requester me init t e me\n\n(* These two NOT redundant since t could clear init *)\n| always_me_init': forall requester me init t,\n    evidence_disclosed' requester me init t init me\n| always_requester_init': forall requester me init t,\n    evidence_disclosed' requester me init t init requester\n                        \n| ed_at'': forall requester me init q t',\n    evidence_disclosed' requester me init (att q t') init q\n| ed_at''': forall requester me init q q' t' e,\n    evidence_disclosed' me q init t' e q' ->\n    evidence_disclosed' requester me init (att q t') e q'.\n\nInductive evidence_disclosed : Plc -> Plc -> Evidence -> Term -> secret_evidence_rel :=\n| always_me_init: forall requester me init t, evidence_disclosed requester me init t init me\n| always_requester_init: forall requester me init t, evidence_disclosed requester me init t init requester\n(*| ed_asp_val: forall requester me init, evidence_disclosed requester me init (asp SIG) init requester *)\n| ed_asp: forall requester me init a, evidence_disclosed requester me init (asp a) (eval_asp a me init) requester\n| ed_at: forall requester me init q t',\n    evidence_disclosed requester me init (att q t') init q\n| ed_at': forall requester me init q q' t' e,\n    evidence_disclosed me q init t' e q' ->\n    evidence_disclosed requester me init (att q t') e q'\n| ed_ln_l: forall requester me init t1 t2 q e,\n    evidence_disclosed requester me init t1 e q ->\n    evidence_disclosed requester me init (lseq t1 t2) e q\n| ed_ln_r: forall requester me init t1 t2 q e,\n    evidence_disclosed requester me init t1 e q ->\n    evidence_disclosed requester me init (lseq t1 t2) e q\n| ed_bseq_l: forall requester me init t1 t2 q e sp1 sp2,\n    evidence_disclosed requester me (splitEv_T sp1 init) t1 e q ->\n    evidence_disclosed requester me init (bseq (sp1,sp2) t1 t2) e q\n| ed_bseq_r: forall requester me init t1 t2 q e sp1 sp2,\n    evidence_disclosed requester me (splitEv_T sp2 init) t1 e q ->\n    evidence_disclosed requester me init (bseq (sp1,sp2) t1 t2) e q\n| ed_bpar_l: forall requester me init t1 t2 q e sp1 sp2,\n    evidence_disclosed requester me (splitEv_T sp1 init) t1 e q ->\n    evidence_disclosed requester me init (bpar (sp1,sp2) t1 t2) e q\n| ed_bpar_r: forall requester me init t1 t2 q e sp1 sp2,\n    evidence_disclosed requester me (splitEv_T sp2 init) t1 e q ->\n    evidence_disclosed requester me init (bpar (sp1,sp2) t1 t2) e q.\n\n\nInductive disclosure_event: Ev -> Plc -> (*Plc ->*) Evidence -> Plc -> Prop :=\n| req_dis: forall i loc requester (* me them *) p q q' ev t e b,\n    events (annotated t []) q ev ->\n    disclosure_event ev q' e b ->\n    disclosure_event (req i loc p q t) requester e b\n| asp_dis: forall i p id args requester init,\n    disclosure_event (umeas i p id args) requester (eval_asp (ASPC id args) p init) requester.\n\n\nInductive events: AnnoTerm -> Plc -> Evidence -> Ev -> Prop :=.\n\nRequire Import Trace Main Term.\n\nRequire Import ConcreteEvidence.\n\nFixpoint evshape (e:EvidenceC) :=\n  match e with\n  | mtc => mt\n  | uuc i _ e' => uu i [] 0 (evshape e')\n  | ggc p e' => gg p (evshape e')\n  | hhc p e' => hh p (evshape e')\n  | nnc i _ e' => nn i (evshape e')\n  | ssc e1 e2 => ss (evshape e1) (evshape e2)\n  | ppc e1 e2 => ss (evshape e1) (evshape e2)\n  end.\n\n\nLemma evshape_eval: forall init,\n    Ev_Shape init (evshape init).\nProof.\nAdmitted.\n\nInductive trace: AnnoTerm -> Plc -> Evidence ->\n                 list Ev -> Prop :=.\n\nLemma cvm_respects_disclosed': forall t ev tr p bad_p requester e  et,\n  well_formed t ->\n  (* copland_compile t (mk_st init_ev [] p o) = (Some tt, (mk_st e' tr p' o')) -> *)\n  (*st_trace (run_cvm t\n                    (mk_st e [] p o)) = tr -> *)\n  (*st_trace\n    (run_cvm t (mk_st init_ev [] p o)) = tr -> *)\n\n   trace t p et tr ->\n   In ev tr ->                            \n  disclosure_event ev requester e bad_p ->\n  (*Ev_Shape init_ev et -> *)\n  evidence_disclosed requester p et (unanno t) e bad_p.\nProof.\n  intros.\n  generalizeEverythingElse t.\n  induction t; intros.\n  -\n    destruct a.\n    (*\n      solve_by_inversion.\n  -\n    invc H1.\n    invc H3.\n    invc H4.\n    invc H5.\n    invc H3.\n    solve_by_inversion.\n  -\n    solve_by_inversion.\n  -\n    solve_by_inversion.\n  -\n    solve_by_inversion.\nDefined.\n     *)\nAdmitted.\n\n(*\n    invc H0\n      try (\n    \n      invc H0;\n      cbn;\n      invc H1; solve_by_inversion).\n    +\n      (*\n      assert (Ev_Shape init_ev (evshape init_ev)).\n      {\n        eapply evshape_eval; eauto.\n      }\n      \n      assert (et = evshape init_ev). admit.\n      subst.\n       *)\n\n      (*\n      \n      \n      invc H4.\n      invc H1; try solve_by_inversion.\n      cbn.\n      invc H2.\n      assert (et = init). admit.\n      subst.\n      econstructor.\n  -\n*)\nAdmitted.\n*)\n\nLemma cvm_respects_disclosed: forall t ev tr p bad_p requester o e init_ev et e' p' o',\n  well_formed t ->\n  copland_compile t (mk_st init_ev [] p o) = (Some tt, (mk_st e' tr p' o')) ->\n  (*st_trace (run_cvm t\n                    (mk_st e [] p o)) = tr -> *)\n  (*st_trace\n    (run_cvm t (mk_st init_ev [] p o)) = tr -> *)\n  In ev tr ->                                   \n  disclosure_event ev requester e bad_p ->\n  Ev_Shape init_ev et ->\n  evidence_disclosed requester p et (unanno t) e bad_p.\nProof.\n  intros.\n    assert (trace t p et tr).\n    {\n      (*\n    eapply lstar_trace.\n    eapply wf_implies_wfr; eauto.\n\n    eapply cvm_refines_lts_event_ordering; eauto.\n       *)\n      admit.\n    }\n    eapply cvm_respects_disclosed'; eauto.\nAdmitted.\n\n\n\n\nDefinition policy_check_rel := Term -> Prop.\n\nInductive policy1: policy_check_rel :=\n| allSigs: policy1 (asp SIG).\n\nDefinition my_secrets (e:Evidence) (p:Plc) :=\n  match (e,p) with\n  | (mt,3)  => True\n  | _ => False\n  end.\n\nDefinition passes_policy\n           (policy:policy_check_rel)\n           (secrets:secret_evidence_rel)\n           (requester:Plc)\n           (me:Plc)\n           (init:Evidence) : Prop :=\n  forall t e q,\n    policy t ->\n    secrets e q ->\n    not (evidence_disclosed requester me init t e q).\n\nCheck annotated.\n\nDefinition cvm_passes_policy\n           (policy:policy_check_rel)\n           (secrets:secret_evidence_rel)\n           (requester:Plc)\n           (me:Plc)\n           (init:EvidenceC) : Prop :=\n  forall t e q ev et o o' p' tr e',\n    policy (unanno t) ->\n    secrets e q ->\n    Ev_Shape init et ->\n    well_formed t ->\n    (* events t me et ev -> *)\n    copland_compile t (mk_st init [] me o) = (Some tt, (mk_st e' tr p' o')) ->\n    In ev tr ->\n    not (disclosure_event ev requester e q).\n\nLemma passes_implies_cvm_passes: forall p s r m i i',\n  Ev_Shape i i' ->\n  passes_policy p s r m i' ->\n  cvm_passes_policy p s r m i.\n  Proof.\n    intros.\n    unfold cvm_passes_policy in *.\n    unfold passes_policy in *.\n\n    intros.\n    unfold not in *.\n    intros.\n    eapply H0.\n    eassumption.\n    eassumption.\n\n    eapply cvm_respects_disclosed with (init_ev:=i).\n    eassumption.\n    eassumption.\n    eassumption.\n    eassumption.\n    eassumption.\n  Defined.\n\n    \n    \n\n  \n(*\n    not (evidence_disclosed requester me init t e q). *)\n\nLemma policy1_passes : passes_policy policy1 my_secrets 0 1 mt.\nProof.\n  cbv in *;\n    intros.\n  invc H.\n  destruct e; try solve_by_inversion.\n  (*\n  repeat (destruct q; try solve_by_inversion).\n  invc H1. *)\nDefined.\n\nDefinition derive_policy (secrets:secret_evidence_rel) : policy_check_rel.\nProof.\n  cbv in *.\nAdmitted.\n\nLemma derive_passes_policy:\n  forall secrets requester me init,\n    passes_policy (derive_policy secrets) secrets requester me init.\nProof.\nAdmitted.\n\n\n\nLemma derive_passes_cvm_policy:\n  forall secrets requester me init,\n    cvm_passes_policy (derive_policy secrets) secrets requester me init.\nProof.\n  intros.\n  eapply passes_implies_cvm_passes.\n  eapply evshape_eval.\n  eapply derive_passes_policy.\nDefined.\n\n\n  \n\n\n  \n    \n    \n  \n\n\n\n\n\n\n\n\n", "meta": {"author": "ku-sldg", "repo": "copland-avm", "sha": "6c08b0e3df96a22cc675bcea309fe99ea7deca65", "save_path": "github-repos/coq/ku-sldg-copland-avm", "path": "github-repos/coq/ku-sldg-copland-avm/copland-avm-6c08b0e3df96a22cc675bcea309fe99ea7deca65/src/extra/Policy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24564155301056112}}
{"text": "(* Check behavior of evar-evar subtyping problems in the presence of\n   nested let-ins *)\n(* Expected time < 2.00s *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nParameter f : forall P, forall (i : nat), P i -> P i.\nParameter P : nat -> Type.\n\nTime Definition g (n : nat) (a0 : P n) : P n :=\n  let a1  := f a0 in\n  let a2  := f a1 in\n  let a3  := f a2 in\n  let a4  := f a3 in\n  let a5  := f a4 in\n  let a6  := f a5 in\n  let a7  := f a6 in\n  let a8  := f a7 in\n  let a9  := f a8 in\n  let a10 := f a9 in \n  let a11 := f a10 in\n  let a12 := f a11 in\n  let a13 := f a12 in\n  let a14 := f a13 in\n  let a15 := f a14 in\n  let a16 := f a15 in\n  let a17 := f a16 in\n  a17.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/complexity/bug4076.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24564154665647464}}
{"text": "Require Import HoareDef SimModSem.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import Relation_Definitions.\n\n(*** TODO: export these in Coqlib or Universe ***)\nRequire Import Relation_Operators.\nRequire Import RelationPairs.\nFrom ITree Require Import\n     Events.MapDefault.\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Maps\n     Data.Map.FMapAList.\nRequire Import HTactics ProofMode IPM.\nRequire Import OpenDef.\nRequire Import Mem1 MemOpen STB.\n\nRequire Import Imp.\nRequire Import ImpNotations.\nRequire Import ImpProofs.\n\nRequire Import EchoMain0 EchoMainImp.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\nSection SIMMODSEM.\n\n  Import ImpNotations.\n\n  Context `{Σ: GRA.t}.\n\n  Let W: Type := Any.t * Any.t.\n\n  Let wf: unit -> W -> Prop :=\n    fun _ '(mrps_src0, mrps_tgt0) =>\n      (<<SRC: mrps_src0 = tt↑>>) /\\\n      (<<TGT: mrps_tgt0 = tt↑>>)\n  .\n\n  Theorem correct:\n    refines2 [EchoMainImp.EchoMain] [EchoMain0.Main].\n  Proof.\n    eapply adequacy_local2. econs; ss. i.\n    econstructor 1 with (wf:=wf) (le:=top2); et; ss.\n    econs; ss.\n    { init.\n      unfold main_body, main.\n      steps.\n      rewrite unfold_eval_imp. steps.\n      des_ifs.\n      2:{ exfalso; apply n. solve_NoDup. }\n      unfold ccallU. imp_steps.\n      red. esplits; et.\n    }\n    Unshelve. all: try exact 0. all: ss.\n  Qed.\n\nEnd SIMMODSEM.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/echo/EchoMainImp0proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4225046348141883, "lm_q1q2_score": 0.2456032500290346}}
{"text": "From iris.algebra Require Import frac.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic Require Import invariants.\nRequire Import Eqdep_dec List.\nFrom cap_machine Require Import rules logrel.\nFrom cap_machine Require Export addr_reg_sample region_macros contiguous stack_macros_helpers malloc fetch\n     awkward_example_helpers.\nFrom cap_machine.rules Require Import rules_StoreU_derived rules_LoadU_derived.\n\nSection stack_macros.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n          {stsg : STSG Addr region_type Σ} {heapg : heapG Σ}\n          {nainv: logrel_na_invs Σ}\n          `{MP: MachineParameters}.\n\n  (* --------------------------------------------------------------------------------- *)\n  (* ------------------------------------- MALLOC ------------------------------------ *)\n  (* --------------------------------------------------------------------------------- *)\n\n  (* malloc stores the result in r_t1, rather than a user chosen destination. \n     f_m is the offset of the malloc capability *)\n  Definition malloc_instrs f_m size :=\n    fetch_instrs f_m ++\n    [move_r r_t5 r_t0;\n    move_r r_t3 r_t1;\n    move_z r_t1 size;\n    move_r r_t0 PC;\n    lea_z r_t0 3;\n    jmp r_t3;\n    move_r r_t0 r_t5;\n    move_z r_t5 0].\n\n  Definition malloc f_m size a : iProp Σ :=\n    ([∗ list] a_i;w_i ∈ a;(malloc_instrs f_m size), a_i ↦ₐ w_i)%I.\n\n  (* malloc spec *)\n  Lemma malloc_spec W size cont a pc_p pc_g pc_b pc_e a_first a_last\n        b_link e_link a_link f_m a_entry mallocN b_m e_m EN rmap φ :\n    isCorrectPC_range pc_p pc_g pc_b pc_e a_first a_last →\n    contiguous_between a a_first a_last →\n    withinBounds (RW, Global, b_link, e_link, a_entry) = true →\n    (a_link + f_m)%a = Some a_entry →\n    dom (gset RegName) rmap = all_registers_s ∖ {[ PC; r_t0 ]} →\n    ↑mallocN ⊆ EN →\n    size > 0 →\n\n    (* malloc program and subroutine *)\n    ▷ malloc f_m size a\n    ∗ na_inv logrel_nais mallocN (malloc_inv b_m e_m)\n    ∗ na_own logrel_nais EN\n    (* we need to assume that the malloc capability is in the linking table at offset f_m *)\n    ∗ ▷ pc_b ↦ₐ inr (RO,Global,b_link,e_link,a_link)\n    ∗ ▷ a_entry ↦ₐ inr (E,Global,b_m,e_m,b_m)\n    (* register state *)\n    ∗ ▷ PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,a_first)\n    ∗ ▷ r_t0 ↦ᵣ cont\n    ∗ ▷ ([∗ map] r_i↦w_i ∈ rmap, r_i ↦ᵣ w_i)\n    (* current world *)\n    ∗ ▷ region W\n    ∗ ▷ sts_full_world W\n    (* continuation *)\n    ∗ ▷ (PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,a_last) ∗ malloc f_m size a\n         ∗ pc_b ↦ₐ inr (RO,Global,b_link,e_link,a_link)\n         ∗ a_entry ↦ₐ inr (E,Global,b_m,e_m,b_m)\n         (* the newly allocated region *)\n         ∗ (∃ (b e : Addr),\n            ⌜(b + size)%a = Some e⌝\n            ∗ r_t1 ↦ᵣ inr (RWX,Global,b,e,b)\n            ∗ [[b,e]] ↦ₐ [[region_addrs_zeroes b e]])\n         ∗ r_t0 ↦ᵣ cont\n         ∗ na_own logrel_nais EN\n         ∗ ([∗ map] r_i↦w_i ∈ (<[r_t2:=inl 0%Z]>\n                               (<[r_t3:=inl 0%Z]>\n                                (<[r_t4:=inl 0%Z]>\n                                 (<[r_t5:=inl 0%Z]> (delete r_t1 rmap))))), r_i ↦ᵣ w_i)\n         (* the newly allocated region is fresh in the current world *)\n         (* ∗ ⌜Forall (λ a, a ∉ dom (gset Addr) (std W)) (region_addrs b e)⌝ *)\n         ∗ region W\n         ∗ sts_full_world W\n         -∗ WP Seq (Instr Executable) {{ φ }})\n    ⊢\n      WP Seq (Instr Executable) {{ λ v, φ v ∨ ⌜v = FailedV⌝ }}.\n  Proof.\n    iIntros (Hvpc Hcont Hwb Ha_entry Hrmap_dom HmallocN Hsize)\n            \"(>Hprog & #Hmalloc & Hna & >Hpc_b & >Ha_entry & >HPC & >Hr_t0 & >Hregs & Hr & Hsts & Hφ)\".\n    (* extract necessary registers from regs *)\n    iDestruct (big_sepL2_length with \"Hprog\") as %Hlength.\n    assert (is_Some (rmap !! r_t1)) as [rv1 ?]. by rewrite elem_of_gmap_dom Hrmap_dom; set_solver.\n    iDestruct (big_sepM_delete _ _ r_t1 with \"Hregs\") as \"[Hr_t1 Hregs]\"; eauto.\n    assert (is_Some (rmap !! r_t2)) as [rv2 ?]. by rewrite elem_of_gmap_dom Hrmap_dom; set_solver.\n    iDestruct (big_sepM_delete _ _ r_t2 with \"Hregs\") as \"[Hr_t2 Hregs]\". by rewrite lookup_delete_ne //.\n    assert (is_Some (rmap !! r_t3)) as [rv3 ?]. by rewrite elem_of_gmap_dom Hrmap_dom; set_solver.\n    iDestruct (big_sepM_delete _ _ r_t3 with \"Hregs\") as \"[Hr_t3 Hregs]\". by rewrite !lookup_delete_ne //.\n    assert (is_Some (rmap !! r_t5)) as [rv5 ?]. by rewrite elem_of_gmap_dom Hrmap_dom; set_solver.\n    iDestruct (big_sepM_delete _ _ r_t5 with \"Hregs\") as \"[Hr_t5 Hregs]\". by rewrite !lookup_delete_ne //.\n    destruct a as [|a l];[inversion Hlength|].\n    apply contiguous_between_cons_inv_first in Hcont as Heq. subst.\n    (* fetch f *)\n    iDestruct (contiguous_between_program_split with \"Hprog\") as (fetch_prog rest link)\n                                                                   \"(Hfetch & Hprog & #Hcont)\";[apply Hcont|].\n    iDestruct \"Hcont\" as %(Hcont_fetch & Hcont_rest & Heqapp & Hlink).\n    iApply (fetch_spec with \"[- $HPC $Hfetch $Hr_t1 $Hr_t2 $Hr_t3 $Ha_entry $Hpc_b]\");\n      [|apply Hcont_fetch|apply Hwb|apply Ha_entry|].\n    { intros mid Hmid. apply isCorrectPC_inrange with a_first a_last; auto.\n      apply contiguous_between_bounds in Hcont_rest. revert Hcont_rest Hmid; clear. solve_addr. }\n    iNext. iIntros \"(HPC & Hfetch& Hr_t1 & Hr_t2 & Hr_t3 & Hpc_b & Ha_entry)\".\n    iDestruct (big_sepL2_length with \"Hprog\") as %Hlength_rest.\n    assert (isCorrectPC_range pc_p pc_g pc_b pc_e link a_last) as Hvpc_rest.\n    { intros mid Hmid. apply isCorrectPC_inrange with a_first a_last; auto. revert Hmid Hlink;clear. solve_addr. }\n    destruct rest as [|a l'];[inversion Hlength_rest|].\n    apply contiguous_between_cons_inv_first in Hcont_rest as Heq. subst.\n    (* move r_t5 r_t0 *)\n    destruct l';[inversion Hlength_rest|].\n    iPrologue \"Hprog\".\n    iApply (wp_move_success_reg with \"[$HPC $Hi $Hr_t5 $Hr_t0]\");\n      [apply decode_encode_instrW_inv|iCorrectPC link a_last|iContiguous_next Hcont_rest 0|auto|..].\n    iEpilogue \"(HPC & Hprog_done & Hr_t5 & Hr_t0)\". iCombine \"Hprog_done\" \"Hfetch\" as \"Hprog_done\".\n    (* move r_t3 r_t1 *)\n    destruct l';[inversion Hlength_rest|].\n    iPrologue \"Hprog\".\n    iApply (wp_move_success_reg with \"[$HPC $Hi $Hr_t3 $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC link a_last|iContiguous_next Hcont_rest 1|auto|..].\n    iEpilogue \"(HPC & Hi & Hr_t3 & Hr_t1)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* move r_t1 size *)\n    destruct l';[inversion Hlength_rest|].\n    iPrologue \"Hprog\".\n    iApply (wp_move_success_z with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC link a_last|iContiguous_next Hcont_rest 2|auto|..].\n    iEpilogue \"(HPC & Hi & Hr_t1)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* move r_t0 PC *)\n    destruct l';[inversion Hlength_rest|].\n    iPrologue \"Hprog\".\n    iApply (wp_move_success_reg_fromPC with \"[$HPC $Hi $Hr_t0]\");\n      [apply decode_encode_instrW_inv|iCorrectPC link a_last|iContiguous_next Hcont_rest 3|auto|..].\n    iEpilogue \"(HPC & Hi & Hr_t0)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* lea r_t0 3 *)\n    destruct l';[inversion Hlength_rest|]. destruct l';[inversion Hlength_rest|].\n    iPrologue \"Hprog\".\n    assert ((a1 + 3)%a = Some a4) as Hlea.\n    { apply (contiguous_between_incr_addr_middle _ _ _ 3 3 a1 a4) in Hcont_rest; auto. }\n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr_t0]\");\n      [apply decode_encode_instrW_inv|iCorrectPC link a_last|iContiguous_next Hcont_rest 4|apply Hlea|auto..].\n    { apply contiguous_between_length in Hcont.\n      apply isCorrectPC_range_perm in Hvpc; [|revert Hcont; clear; solve_addr].\n      destruct Hvpc as [-> | [-> | ->] ]; auto. }\n    { apply contiguous_between_length in Hcont.\n      apply isCorrectPC_range_perm in Hvpc; [|revert Hcont; clear; solve_addr].\n      destruct Hvpc as [-> | [-> | ->] ]; auto. }\n    iEpilogue \"(HPC & Hi & Hr_t0)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* jmp r_t3 *)\n    destruct l';[inversion Hlength_rest|].\n    iPrologue \"Hprog\".\n    iApply (wp_jmp_success with \"[$HPC $Hi $Hr_t3]\");\n      [apply decode_encode_instrW_inv|iCorrectPC link a_last|]. \n    iEpilogue \"(HPC & Hi & Hr_t3) /=\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* we are now ready to use the malloc subroutine spec. For this we prepare the registers *)\n    iDestruct (big_sepM_insert _ _ r_t3 with \"[$Hregs $Hr_t3]\") as \"Hregs\".\n      by rewrite lookup_delete_ne // lookup_delete.\n    iDestruct (big_sepM_insert _ _ r_t2 with \"[$Hregs $Hr_t2]\") as \"Hregs\".\n      by rewrite lookup_insert_ne // lookup_delete_ne // lookup_delete_ne // lookup_delete.\n    rewrite -(delete_insert_ne _ r_t5 r_t3) // insert_delete.\n    rewrite -(delete_insert_ne _ r_t5 r_t2) // (insert_commute _ r_t2 r_t3) //.\n    rewrite insert_delete.\n    iDestruct (big_sepM_insert _ _ r_t5 with \"[$Hregs $Hr_t5]\") as \"Hregs\".\n      by rewrite lookup_delete. rewrite insert_delete.\n    iApply (wp_wand with \"[-]\").\n    iApply (simple_malloc_subroutine_spec with \"[- $Hmalloc $Hna $Hregs $Hr_t0 $HPC $Hr_t1]\"); auto.\n    { rewrite !dom_insert_L dom_delete_L Hrmap_dom.\n      rewrite !difference_difference_L !singleton_union_difference_L !all_registers_union_l.\n      f_equal. set_solver-. }\n    iNext.\n    rewrite updatePcPerm_cap_non_E.\n    2: { eapply isCorrectPC_range_npE; eauto.\n         generalize (contiguous_between_length _ _ _ Hcont_rest). cbn.\n         clear; solve_addr. }\n    iIntros \"((Hna & Hregs) & Hr_t0 & HPC & Hbe) /=\".\n    iDestruct \"Hbe\" as (b e z Hbe Hbounds Hpos Hsizebe) \"(Hr_t1 & Hbe)\". inversion Hbe; subst z.\n    iDestruct (big_sepM_delete _ _ r_t3 with \"Hregs\") as \"[Hr_t3 Hregs]\".\n      by rewrite lookup_insert_ne // lookup_insert //.\n      rewrite delete_insert_ne // delete_insert_delete.\n      repeat (rewrite delete_insert_ne //;[]). rewrite delete_insert_delete.\n    iDestruct (big_sepM_delete _ _ r_t5 with \"Hregs\") as \"[Hr_t5 Hregs]\".\n      by (repeat (rewrite lookup_insert_ne //;[]); rewrite lookup_insert //).\n      repeat (rewrite delete_insert_ne //;[]). rewrite delete_insert_delete.\n    (* move r_t0 r_t5 *)\n    iPrologue \"Hprog\".\n    iApply (wp_move_success_reg with \"[$HPC $Hi $Hr_t0 $Hr_t5]\");\n      [apply decode_encode_instrW_inv|iCorrectPC link a_last|iContiguous_next Hcont_rest 6|auto|..].\n    iEpilogue \"(HPC & Hi & Hr_t0 & Hr_t5)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* move r_t5 0 *)\n    destruct l';[| by inversion Hlength_rest].\n    iPrologue \"Hprog\".\n    apply contiguous_between_last with (ai:=a5) in Hcont_rest as Hlast;[|auto]. \n    iApply (wp_move_success_z with \"[$HPC $Hi $Hr_t5]\");\n      [apply decode_encode_instrW_inv|iCorrectPC link a_last|apply Hlast|auto|..].\n    iEpilogue \"(HPC & Hi & Hr_t5)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* continuation *)\n    iApply \"Hφ\".\n    iFrame \"HPC\". iSplitL \"Hprog_done\".\n    { rewrite Heqapp. repeat (iDestruct \"Hprog_done\" as \"[$ Hprog_done]\"). iFrame. done. }\n    iFrame.\n    iDestruct (big_sepM_insert _ _ r_t5 with \"[$Hregs $Hr_t5]\") as \"Hregs\".\n      repeat (rewrite lookup_insert_ne //;[]). apply lookup_delete.\n    iDestruct (big_sepM_insert _ _ r_t3 with \"[$Hregs $Hr_t3]\") as \"Hregs\".\n      repeat (rewrite lookup_insert_ne //;[]).\n      rewrite lookup_delete_ne // lookup_delete //.\n    repeat (rewrite (insert_commute _ r_t5) //;[]).\n    rewrite insert_delete -(delete_insert_ne _ _ r_t5) //.\n    rewrite (insert_commute _ r_t5 r_t2) // (delete_insert_ne _ r_t3 r_t2)//.\n    rewrite (insert_commute _ r_t4 r_t2) // insert_insert.\n    rewrite (insert_commute _ r_t3 r_t2) //.\n    rewrite -(delete_insert_ne _ r_t3) // insert_delete.\n    iFrame.\n    iExists b,e. iFrame. auto. auto.\n  Qed.\n\n  (* ---------------------------------------- CRTCLS ------------------------------------ *)\n  (* The following macro creates a closure with one variable. A more general create closure would \n     allow for more than one variable in the closure, but this is so far not necessary for our \n     examples. The closure allocates a new region with a capability to the closure code, the closure \n     variable, and the closure activation *)\n\n  (* encodings of closure activation code *)\n  Definition v1 := encodeInstr (Mov r_t1 (inr PC)).\n  Definition v2 := encodeInstr (Lea r_t1 (inl 7%Z)).\n  Definition v3 := encodeInstr (Load r_env r_t1).\n  Definition v4 := encodeInstr (Lea r_t1 (inl (-1)%Z)).\n  Definition v5 := encodeInstr (Load r_t1 r_t1).\n  Definition v6 := encodeInstr (Jmp r_t1).\n\n  (* crtcls instructions *)\n  (* f_m denotes the offset to the malloc capability in the lookup table *)\n  (* crtcls assumes that the code lies in register r_t1 and the variable lies in r_t2 *)\n  Definition crtcls_instrs f_m :=\n    [move_r r_t6 r_t1;\n    move_r r_t7 r_t2] ++\n    malloc_instrs f_m 8%nat ++\n    [store_z r_t1 v1;\n    lea_z r_t1 1;\n    store_z r_t1 v2;\n    lea_z r_t1 1;\n    store_z r_t1 v3;\n    lea_z r_t1 1;\n    store_z r_t1 v4;\n    lea_z r_t1 1;\n    store_z r_t1 v5;\n    lea_z r_t1 1;\n    store_z r_t1 v6;\n    lea_z r_t1 1;\n    store_r r_t1 r_t6;\n    move_z r_t6 0;\n    lea_z r_t1 1;\n    store_r r_t1 r_t7;\n    move_z r_t7 0;\n    lea_z r_t1 (-7)%Z;\n    restrict_z r_t1 global_e].\n\n  Definition crtcls f_m a : iProp Σ :=\n    ([∗ list] a_i;w_i ∈ a;(crtcls_instrs f_m), a_i ↦ₐ w_i)%I.\n\n  (* crtcls spec *)\n  Lemma crtcls_spec W f_m wvar wcode a pc_p pc_g pc_b pc_e\n        a_first a_last b_link a_link e_link a_entry b_m e_m mallocN EN rmap cont φ :\n    isCorrectPC_range pc_p pc_g pc_b pc_e a_first a_last →\n    contiguous_between a a_first a_last →\n    withinBounds (RW, Global, b_link, e_link, a_entry) = true →\n    (a_link + f_m)%a = Some a_entry →\n    dom (gset RegName) rmap = all_registers_s ∖ {[ PC; r_t0; r_t1; r_t2 ]} →\n    isLocalWord wcode = false → (* the closure must be a Global Word! *)\n    isLocalWord wvar = false → (* the closure must be a Global Word! *)\n    ↑mallocN ⊆ EN →\n\n      ▷ crtcls f_m a\n    ∗ ▷ PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,a_first)\n    ∗ na_inv logrel_nais mallocN (malloc_inv b_m e_m)\n    ∗ na_own logrel_nais EN\n    (* we need to assume that the malloc capability is in the linking table at offset 0 *)\n    ∗ ▷ pc_b ↦ₐ inr (RO,Global,b_link,e_link,a_link)\n    ∗ ▷ a_entry ↦ₐ inr (E,Global,b_m,e_m,b_m)\n    (* register state *)\n    ∗ ▷ r_t0 ↦ᵣ cont\n    ∗ ▷ r_t1 ↦ᵣ wcode\n    ∗ ▷ r_t2 ↦ᵣ wvar\n    ∗ ▷ ([∗ map] r_i↦w_i ∈ rmap, r_i ↦ᵣ w_i)\n    (* current world *)\n    ∗ ▷ region W\n    ∗ ▷ sts_full_world W\n    (* continuation *)\n    ∗ ▷ (PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,a_last) ∗ crtcls f_m a\n         ∗ pc_b ↦ₐ inr (RO,Global,b_link,e_link,a_link)\n         ∗ a_entry ↦ₐ inr (E,Global,b_m,e_m,b_m)\n         (* the newly allocated region *)\n         ∗ (∃ (b e : Addr), ⌜(b + 8)%a = Some e⌝ ∧ r_t1 ↦ᵣ inr (E,Global,b,e,b)\n         ∗ [[b,e]] ↦ₐ [[ [inl v1;inl v2;inl v3;inl v4;inl v5;inl v6;wcode;wvar] ]]\n         ∗ r_t0 ↦ᵣ cont\n         ∗ r_t2 ↦ᵣ inl 0%Z\n         ∗ na_own logrel_nais EN\n         ∗ ([∗ map] r_i↦w_i ∈ <[r_t3:=inl 0%Z]>\n                               (<[r_t4:=inl 0%Z]>\n                                (<[r_t5:=inl 0%Z]>\n                                 (<[r_t6:=inl 0%Z]>\n                                  (<[r_t7:=inl 0%Z]> rmap)))), r_i ↦ᵣ w_i)\n         (* the newly allocated region is fresh in the current world *)\n         (* ∗ ⌜Forall (λ a, a ∉ dom (gset Addr) (std W)) (region_addrs b e)⌝ *)\n         ∗ region W\n         ∗ sts_full_world W)\n         -∗ WP Seq (Instr Executable) {{ φ }})\n    ⊢\n      WP Seq (Instr Executable) {{ λ v, φ v ∨ ⌜v = FailedV⌝ }}.\n  Proof.\n    iIntros (Hvpc Hcont Hwb Ha_entry Hrmap_dom Hlocal Hlocal' HmallocN)\n            \"(>Hprog & >HPC & #Hmalloc & Hna & >Hpc_b & >Ha_entry & >Hr_t0 & >Hr_t1 & >Hr_t2 & >Hregs & Hr & Hsts & Hφ)\".\n    (* get some registers out of regs *)\n    iDestruct (big_sepL2_length with \"Hprog\") as %Hlength.\n    assert (is_Some (rmap !! r_t6)) as [rv6 ?]. by rewrite elem_of_gmap_dom Hrmap_dom; set_solver.\n    iDestruct (big_sepM_delete _ _ r_t6 with \"Hregs\") as \"[Hr_t6 Hregs]\"; eauto.\n    assert (is_Some (rmap !! r_t7)) as [rv7 ?]. by rewrite elem_of_gmap_dom Hrmap_dom; set_solver.\n    iDestruct (big_sepM_delete _ _ r_t7 with \"Hregs\") as \"[Hr_t7 Hregs]\". by rewrite lookup_delete_ne //.\n    destruct a as [|a l];[inversion Hlength|].\n    apply contiguous_between_cons_inv_first in Hcont as Heq. subst.\n    (* move r_t6 r_t1 *)\n    destruct l;[inversion Hlength|].\n    iPrologue \"Hprog\".\n    iApply (wp_move_success_reg with \"[$HPC $Hi $Hr_t6 $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next Hcont 0|].\n    iEpilogue \"(HPC & Hprog_done & Hr_t6 & Hr_t1)\".\n    (* move r_t7 r_t2 *)\n    destruct l;[inversion Hlength|].\n    iPrologue \"Hprog\".\n    iApply (wp_move_success_reg with \"[$HPC $Hi $Hr_t7 $Hr_t2]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a_first a_last|iContiguous_next Hcont 1|].\n    iEpilogue \"(HPC & Hi & Hr_t7 & Hr_t2)\"; iCombine \"Hi Hprog_done\" as \"Hprog_done\".\n    assert (contiguous_between (a0 :: l) a0 a_last) as Hcont'.\n    { apply contiguous_between_cons_inv in Hcont as [_ (? & ? & Hcont)].\n      apply contiguous_between_cons_inv in Hcont as [_ (? & ? & Hcont)].\n      pose proof (contiguous_between_cons_inv_first _ _ _ _ Hcont). subst. apply Hcont. }\n    (* malloc 8 *)\n    iDestruct (contiguous_between_program_split with \"Hprog\") as\n        (malloc_prog rest link) \"(Hmalloc_prog & Hprog & #Hcont)\";[apply Hcont'|].\n    iDestruct \"Hcont\" as %(Hcont_fetch & Hcont_rest & Heqapp & Hlink).\n    (* we start by putting the registers back together *)\n    iDestruct (big_sepM_insert with \"[$Hregs $Hr_t6]\") as \"Hregs\".\n      by rewrite lookup_delete_ne // lookup_delete.\n      rewrite delete_commute // insert_delete.\n    iDestruct (big_sepM_insert with \"[$Hregs $Hr_t7]\") as \"Hregs\".\n      by rewrite lookup_insert_ne // lookup_delete.\n      rewrite insert_commute // insert_delete.\n    assert (∀ (r:RegName), r ∈ ({[PC;r_t0;r_t1;r_t2]} : gset RegName) → rmap !! r = None) as Hnotin_rmap.\n    { intros r Hr. eapply (@not_elem_of_dom _ _ (gset RegName)). typeclasses eauto.\n      rewrite Hrmap_dom. set_solver. }\n    iDestruct (big_sepM_insert with \"[$Hregs $Hr_t2]\") as \"Hregs\".\n      by rewrite !lookup_insert_ne //; apply Hnotin_rmap; set_solver.\n    iDestruct (big_sepM_insert with \"[$Hregs $Hr_t1]\") as \"Hregs\".\n      by rewrite !lookup_insert_ne //; apply Hnotin_rmap; set_solver.\n    (* apply the malloc spec *)\n    rewrite -/(malloc _ _ _ _).\n    iApply (malloc_spec with \"[- $HPC $Hmalloc $Hna $Hpc_b $Ha_entry $Hr_t0 $Hregs $Hr $Hsts $Hmalloc_prog]\");\n      [|apply Hcont_fetch|apply Hwb|apply Ha_entry| |auto|lia|..].\n    { intros mid Hmid. apply isCorrectPC_inrange with a_first a_last; auto.\n      apply contiguous_between_bounds in Hcont_rest.\n      apply contiguous_between_incr_addr with (i:=2) (ai:=a0) in Hcont;auto.\n      revert Hcont Hcont_rest Hmid; clear. solve_addr. }\n    { rewrite !dom_insert_L. rewrite Hrmap_dom.\n      repeat (rewrite singleton_union_difference_L all_registers_union_l).\n      f_equal. clear; set_solver. }\n    iNext. iIntros \"(HPC & Hmalloc_prog & Hpc_b & Ha_entry & Hbe & Hr_t0 & Hna & Hregs & Hr & Hsts)\".\n    iDestruct \"Hbe\" as (b e Hbe) \"(Hr_t1 & Hbe)\".\n    rewrite delete_insert_delete.\n    rewrite (delete_insert_ne _ r_t1 r_t2) //.\n    repeat (rewrite (insert_commute _ _ r_t2) //;[]).\n    rewrite insert_insert.\n    (* we now want to infer a list of contiguous addresses between b and e *)\n    assert (b < e)%a as Hlt;[solve_addr|]. \n    assert (contiguous (region_addrs b e)) as Hcontbe';[apply region_addrs_contiguous|].\n    apply contiguous_iff_contiguous_between in Hcontbe'. destruct Hcontbe' as [b' [e' Hcontbe] ].\n    assert (exists l, l = region_addrs b e) as [h Heqh];[eauto|].\n    rewrite -Heqh in Hcontbe.\n    rewrite /region_mapsto /region_addrs_zeroes -Heqh.\n    assert (region_size b e = 8) as ->.\n    { rewrite /region_size. revert Hbe; clear; solve_addr. }\n    simpl.\n    (* prepare the execution of the rest of the program *)\n    iDestruct (big_sepL2_length with \"Hprog\") as %Hlength_rest.\n    assert (isCorrectPC_range pc_p pc_g pc_b pc_e link a_last) as Hvpc_rest.\n    { intros mid Hmid. apply isCorrectPC_inrange with a_first a_last; auto.\n      apply contiguous_between_incr_addr with (i:=2) (ai:=a0) in Hcont;auto.\n      revert Hcont Hmid Hlink;clear. solve_addr. }\n    destruct rest as [|a1 l'];[inversion Hlength_rest|].\n    apply contiguous_between_cons_inv_first in Hcont_rest as Heq. subst link. \n    iDestruct (big_sepL2_length with \"Hbe\") as %Hlengthbe. \n    destruct h;[inversion Hlengthbe|]. \n    apply region_addrs_first in Hlt as Hfirst. rewrite -Heqh in Hfirst; inversion Hfirst. subst a2.\n    apply contiguous_between_cons_inv_first in Hcontbe as Heq. subst b'. \n    assert (∀ i a', (b :: h) !! i = Some a' -> withinBounds (RWX, Global, b, e, a') = true) as Hwbbe.\n    { intros i a' Hsome. apply andb_true_intro.\n      apply contiguous_between_incr_addr with (i:=i) (ai:=a') in Hcontbe;[|congruence].\n      apply lookup_lt_Some in Hsome. rewrite Heqh region_addrs_length in Hsome. \n      revert Hsome Hcontbe Hbe. rewrite /region_size. clear; intros. split;[apply Z.leb_le|apply Z.ltb_lt];solve_addr.\n    }\n    iCombine \"Hmalloc_prog\" \"Hprog_done\" as \"Hprog_done\". \n    (* store r_t1 v1 *)\n    destruct l';[inversion Hlength_rest|]. \n    iPrologue \"Hprog\". \n    iDestruct \"Hbe\" as \"[Hb Hbe]\". \n    iApply (wp_store_success_z with \"[$HPC $Hi $Hr_t1 $Hb]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 0|..].\n    { split;auto. apply Hwbbe with 0. auto. }\n    iEpilogue \"(HPC & Hi & Hr_t1 & Heb)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* lea r_t1 1 *)\n    destruct l';[inversion Hlength_rest|].\n    destruct h;[inversion Hlengthbe|]. \n    iPrologue \"Hprog\". \n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 1|iContiguous_next Hcontbe 0|simpl;auto..].\n    iEpilogue \"(HPC & Hi & Hr_t1)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* store r_t1 v2 *)\n    destruct l';[inversion Hlength_rest|]. \n    iPrologue \"Hprog\". \n    iDestruct \"Hbe\" as \"[Hb Hbe]\". \n    iApply (wp_store_success_z with \"[$HPC $Hi $Hr_t1 $Hb]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 2|..].\n    { split;auto. apply Hwbbe with 1. auto. }\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hb)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\"; iCombine \"Hb\" \"Heb\" as \"Heb\". \n    (* lea r_t1 1 *)\n    destruct l';[inversion Hlength_rest|].\n    destruct h;[inversion Hlengthbe|]. \n    iPrologue \"Hprog\". \n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 3|iContiguous_next Hcontbe 1|simpl;auto..].\n    iEpilogue \"(HPC & Hi & Hr_t1)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* store r_t1 v3 *)\n    destruct l';[inversion Hlength_rest|]. \n    iPrologue \"Hprog\". \n    iDestruct \"Hbe\" as \"[Hb Hbe]\". \n    iApply (wp_store_success_z with \"[$HPC $Hi $Hr_t1 $Hb]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 4|..].\n    { split;auto. apply Hwbbe with 2. auto. }\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hb)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\"; iCombine \"Hb\" \"Heb\" as \"Heb\". \n    (* lea r_t1 1 *)\n    destruct l';[inversion Hlength_rest|].\n    destruct h;[inversion Hlengthbe|]. \n    iPrologue \"Hprog\". \n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 5|iContiguous_next Hcontbe 2|simpl;auto..].\n    iEpilogue \"(HPC & Hi & Hr_t1)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* store r_t1 v4 *)\n    destruct l';[inversion Hlength_rest|]. \n    iPrologue \"Hprog\". \n    iDestruct \"Hbe\" as \"[Hb Hbe]\". \n    iApply (wp_store_success_z with \"[$HPC $Hi $Hr_t1 $Hb]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 6|..].\n    { split;auto. apply Hwbbe with 3. auto. }\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hb)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\"; iCombine \"Hb\" \"Heb\" as \"Heb\". \n    (* lea r_t1 1 *)\n    destruct l';[inversion Hlength_rest|].\n    destruct h;[inversion Hlengthbe|]. \n    iPrologue \"Hprog\". \n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 7|iContiguous_next Hcontbe 3|simpl;auto..].\n    iEpilogue \"(HPC & Hi & Hr_t1)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* store r_t1 v5 *)\n    destruct l';[inversion Hlength_rest|]. \n    iPrologue \"Hprog\". \n    iDestruct \"Hbe\" as \"[Hb Hbe]\". \n    iApply (wp_store_success_z with \"[$HPC $Hi $Hr_t1 $Hb]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 8|..].\n    { split;auto. apply Hwbbe with 4. auto. }\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hb)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\"; iCombine \"Hb\" \"Heb\" as \"Heb\". \n    (* lea r_t1 1 *)\n    destruct l';[inversion Hlength_rest|].\n    destruct h;[inversion Hlengthbe|]. \n    iPrologue \"Hprog\". \n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 9|iContiguous_next Hcontbe 4|simpl;auto..].\n    iEpilogue \"(HPC & Hi & Hr_t1)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* store r_t1 v6 *)\n    destruct l';[inversion Hlength_rest|]. \n    iPrologue \"Hprog\". \n    iDestruct \"Hbe\" as \"[Hb Hbe]\". \n    iApply (wp_store_success_z with \"[$HPC $Hi $Hr_t1 $Hb]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 10|..].\n    { split;auto. apply Hwbbe with 5. auto. }\n    iEpilogue \"(HPC & Hi & Hr_t1 & Hb)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\"; iCombine \"Hb\" \"Heb\" as \"Heb\". \n    (* lea r_t1 1 *)\n    destruct l';[inversion Hlength_rest|].\n    destruct h;[inversion Hlengthbe|]. \n    iPrologue \"Hprog\". \n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 11|iContiguous_next Hcontbe 5|simpl;auto..].\n    iEpilogue \"(HPC & Hi & Hr_t1)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* store r_t1 r_t6 *)\n    (* first we must extract r_t6 *)\n    iDestruct (big_sepM_delete _ _ r_t6 with \"Hregs\") as \"[Hr_t6 Hregs]\".\n      by rewrite !lookup_insert_ne // lookup_delete_ne // lookup_insert //.\n    (* then we can store *)\n    destruct l';[inversion Hlength_rest|]. \n    iPrologue \"Hprog\". \n    iDestruct \"Hbe\" as \"[Hb Hbe]\". \n    iApply (wp_store_success_reg with \"[$HPC $Hi $Hr_t6 $Hr_t1 $Hb]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 12|..].\n    { split;auto. apply Hwbbe with 6. auto. }\n    { destruct wcode;auto. destruct c,p,p,p,p,l0;auto;inversion Hlocal'. }\n\n    iEpilogue \"(HPC & Hi & Hr_t6 & Hr_t1 & Hb)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\"; iCombine \"Hb\" \"Heb\" as \"Heb\".\n    (* move r_t6 0 *)\n    destruct l';[inversion Hlength_rest|]. \n    iPrologue \"Hprog\". \n    iApply (wp_move_success_z with \"[$HPC $Hi $Hr_t6]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 13|auto..].\n    iEpilogue \"(HPC & Hi & Hr_t6)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* lea r_t1 1 *)\n    destruct l';[inversion Hlength_rest|].\n    destruct h;[inversion Hlengthbe|]. \n    iPrologue \"Hprog\". \n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 14|iContiguous_next Hcontbe 6|simpl;auto..].\n    iEpilogue \"(HPC & Hi & Hr_t1)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* store r_t1 r_t7 *)\n    (* first we must extract r_t7 *)\n    iDestruct (big_sepM_delete _ _ r_t7 with \"Hregs\") as \"[Hr_t7 Hregs]\".\n      rewrite lookup_delete_ne // !lookup_insert_ne // lookup_delete_ne //\n              lookup_insert_ne // lookup_insert //.\n    (* then we can store *)\n    destruct l';[inversion Hlength_rest|]. \n    iPrologue \"Hprog\". \n    iDestruct \"Hbe\" as \"[Hb Hbe]\". \n    iApply (wp_store_success_reg with \"[$HPC $Hi $Hr_t7 $Hr_t1 $Hb]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 15|..].\n    { split;auto. apply Hwbbe with 7. auto. }\n    { destruct wvar;auto. destruct c,p,p,p,p,l0;auto;inversion Hlocal. }\n    iEpilogue \"(HPC & Hi & Hr_t7 & Hr_t1 & Hb)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\"; iCombine \"Hb\" \"Heb\" as \"Heb\".\n    (* move r_t7 0 *)\n    destruct l';[inversion Hlength_rest|]. \n    iPrologue \"Hprog\". \n    iApply (wp_move_success_z with \"[$HPC $Hi $Hr_t7]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 16|auto..].\n    iEpilogue \"(HPC & Hi & Hr_t7)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* put r_t6 and r_t7 back *)\n    iDestruct (big_sepM_insert with \"[$Hregs $Hr_t7]\") as \"Hregs\". by rewrite lookup_delete.\n    rewrite insert_delete.\n    iDestruct (big_sepM_insert with \"[$Hregs $Hr_t6]\") as \"Hregs\". by rewrite lookup_insert_ne // lookup_delete.\n    rewrite -(delete_insert_ne _ r_t6) // insert_delete.\n    iClear \"Hbe\".\n    (* lea r_t1 -7 *)\n    destruct h;[|inversion Hlengthbe]. \n    destruct l';[inversion Hlength_rest|]. \n    iPrologue \"Hprog\".\n    apply contiguous_between_last with (ai:=a23) in Hcontbe as Hnext; auto.\n    assert ((a23 + (-7))%a = Some b) as Hlea.\n    { apply contiguous_between_length in Hcontbe. revert Hbe Hnext Hcontbe; clear. solve_addr. }\n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|iContiguous_next Hcont_rest 17|apply Hlea|simpl;auto..].\n    iEpilogue \"(HPC & Hi & Hr_t1)\";iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\". \n    (* restrict r_t1 (Global,E) *)\n    destruct l';[|inversion Hlength_rest].\n    apply contiguous_between_last with (ai:=a26) in Hcont_rest as Hlast; auto.\n    iPrologue \"Hprog\". iClear \"Hprog\". \n    iApply (wp_restrict_success_z with \"[$HPC $Hi $Hr_t1]\");\n      [apply decode_encode_instrW_inv|iCorrectPC a1 a_last|apply Hlast|auto..].\n    { rewrite decode_encode_permPair_inv. auto. }\n    rewrite decode_encode_permPair_inv.\n    iEpilogue \"(HPC & Hi & Hr_t1)\"; iCombine \"Hi\" \"Hprog_done\" as \"Hprog_done\".\n    (* continuation *)\n    iApply \"Hφ\".\n    iFrame \"HPC Hpc_b Ha_entry\". iSplitL \"Hprog_done\".\n    { rewrite Heqapp.\n      do 22 iDestruct \"Hprog_done\" as \"[$ Hprog_done]\". iFrame. done. \n    }\n    iExists b,e. iSplitR;auto.\n    iFrame \"Hr_t1 Hr_t0\".\n    iSplitL \"Heb\".\n    { rewrite -Heqh. do 7 iDestruct \"Heb\" as \"[$ Heb]\". iFrame. done. }\n    iDestruct (big_sepM_delete _ _ r_t2 with \"Hregs\") as \"[Hr_t2 Hregs]\".\n      by do 2 (rewrite lookup_insert_ne //); rewrite lookup_insert //.\n    iFrame \"Hr Hsts Hr_t2 Hna\".\n    repeat (rewrite delete_insert_ne //; []). rewrite delete_insert_delete.\n    rewrite !delete_insert_ne // !delete_notin; [| apply Hnotin_rmap; set_solver ..].\n    repeat (rewrite (insert_commute _ r_t6) //;[]). rewrite insert_insert.\n    repeat (rewrite (insert_commute _ r_t7) //;[]). rewrite insert_insert. eauto.\n  Qed.\n\n  (* ------------------------------- Closure Activation --------------------------------- *)\n\n  Lemma closure_activation_spec pc_p pc_g b_cls e_cls r1v renvv wcode wenv φ :\n    readAllowed pc_p = true →\n    isCorrectPC_range pc_p pc_g b_cls e_cls b_cls e_cls →\n    pc_p ≠ E →\n    PC ↦ᵣ inr (pc_p, pc_g, b_cls, e_cls, b_cls)\n    ∗ r_t1 ↦ᵣ r1v\n    ∗ r_env ↦ᵣ renvv\n    ∗ [[b_cls, e_cls]]↦ₐ[[ [inl v1; inl v2; inl v3; inl v4; inl v5; inl v6; wcode; wenv] ]]\n    ∗ (  PC ↦ᵣ updatePcPerm wcode\n       ∗ r_t1 ↦ᵣ wcode\n       ∗ r_env ↦ᵣ wenv\n       ∗ [[b_cls, e_cls]]↦ₐ[[ [inl v1; inl v2; inl v3; inl v4; inl v5; inl v6; wcode; wenv] ]]\n       -∗ WP Seq (Instr Executable) {{ φ }})\n    ⊢\n      WP Seq (Instr Executable) {{ φ }}.\n  Proof.\n    iIntros (Hrpc Hvpc HnpcE) \"(HPC & Hr1 & Hrenv & Hcode & Hcont)\".\n    rewrite /region_mapsto.\n    iDestruct (big_sepL2_length with \"Hcode\") as %Hcls_len. simpl in Hcls_len.\n    assert (b_cls + 8 = Some e_cls)%a as Hbe.\n    { rewrite region_addrs_length /region_size in Hcls_len.\n      revert Hcls_len; clear; solve_addr. }\n    assert (contiguous_between (region_addrs b_cls e_cls) b_cls e_cls) as Hcont_cls.\n    { apply contiguous_between_of_region_addrs; auto. revert Hbe; clear; solve_addr. }\n    pose proof (region_addrs_NoDup b_cls e_cls) as Hcls_nodup.\n    iDestruct (big_sepL2_split_at 6 with \"Hcode\") as \"[Hprog Hcls_data]\".\n    cbn [take drop].\n    destruct (region_addrs b_cls e_cls) as [| ? ll]; [by inversion Hcls_len|].\n    pose proof (contiguous_between_cons_inv_first _ _ _ _ Hcont_cls). subst.\n    do 7 (destruct ll as [| ? ll]; [by inversion Hcls_len|]).\n    destruct ll;[| by inversion Hcls_len]. cbn [take drop].\n    iDestruct \"Hcls_data\" as \"(Hcls_ptr & Hcls_env & _)\".\n    (* move r_t1 PC *)\n    iPrologue \"Hprog\".\n    iApply (wp_move_success_reg_fromPC with \"[$HPC $Hi $Hr1]\");\n      [apply decode_encode_instrW_inv|  iCorrectPC b_cls e_cls |\n       iContiguous_next Hcont_cls 0 |  ..].\n    iEpilogue \"(HPC & Hprog_done & Hr1)\".\n    (* lea r_t1 7 *)\n    iPrologue \"Hprog\".\n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr1]\");\n      [apply decode_encode_instrW_inv | iCorrectPC b_cls e_cls |\n       iContiguous_next Hcont_cls 1 | | done | ..].\n    { eapply contiguous_between_incr_addr_middle' with (i:=0); eauto.\n      cbn. clear. lia. }\n    { destruct pc_p; simpl in *; try discriminate; auto. }\n    iEpilogue \"(HPC & Hi & Hr1)\". iCombine \"Hi Hprog_done\" as \"Hprog_done\".\n    (* load r_env r_t1 *)\n    iPrologue \"Hprog\".\n    (* FIXME: tedious & fragile *)\n    assert ((a5 =? a0)%a = false) as H_5_0.\n    { apply Z.eqb_neq. intros Heqb. assert (a5 = a0) as ->. revert Heqb; clear; solve_addr.\n      exfalso. by pose proof (NoDup_lookup _ 2 7 _ Hcls_nodup eq_refl eq_refl). }\n    iApply (wp_load_success with \"[$HPC $Hi $Hrenv $Hr1 Hcls_env]\");\n      [apply decode_encode_instrW_inv | iCorrectPC b_cls e_cls |\n       split;[done|] | iContiguous_next Hcont_cls 2 | ..].\n    { eapply contiguous_between_middle_bounds' in Hcont_cls as [? ?].\n      by eapply le_addr_withinBounds; eauto. repeat constructor. }\n    { rewrite H_5_0. iFrame. }\n    iEpilogue \"(HPC & Hrenv & Hi & Hr1 & Hcls_env)\". rewrite H_5_0.\n    iCombine \"Hi Hprog_done\" as \"Hprog_done\".\n    (* lea r_t1 (-1) *)\n    iPrologue \"Hprog\".\n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr1]\");\n      [apply decode_encode_instrW_inv | iCorrectPC b_cls e_cls |\n       iContiguous_next Hcont_cls 3 | | done | ..].\n    { assert ((a4 + 1)%a = Some a5) as HH. by iContiguous_next Hcont_cls 6.\n      instantiate (1 := a4). revert HH. clear; solve_addr. }\n    { destruct pc_p; simpl in *; try discriminate; auto. }\n    iEpilogue \"(HPC & Hi & Hr1)\". iCombine \"Hi Hprog_done\" as \"Hprog_done\".\n    (* load r_t1 r_t1 *)\n    iPrologue \"Hprog\".\n    (* FIXME: tedious & fragile *)\n    assert ((a4 =? a2)%a = false) as H_4_2.\n    { apply Z.eqb_neq. intros Heqb. assert (a4 = a2) as ->. revert Heqb; clear; solve_addr.\n      exfalso. by pose proof (NoDup_lookup _ 4 6 _ Hcls_nodup eq_refl eq_refl). }\n    iApply (wp_load_success_same with \"[$HPC $Hi $Hr1 Hcls_ptr]\");\n      [(* FIXME *) auto | apply decode_encode_instrW_inv | iCorrectPC b_cls e_cls |\n       auto | | iContiguous_next Hcont_cls 4 | ..].\n    { eapply contiguous_between_middle_bounds' in Hcont_cls as [? ?].\n      by eapply le_addr_withinBounds; eauto. repeat constructor. }\n    { rewrite H_4_2. iFrame. }\n    iEpilogue \"(HPC & Hr1 & Hi & Hcls_ptr)\". rewrite H_4_2.\n    iCombine \"Hi Hprog_done\" as \"Hprog_done\".\n    (* jmp r_t1 *)\n    iPrologue \"Hprog\".\n    iApply (wp_jmp_success with \"[$HPC $Hi $Hr1]\");\n      [apply decode_encode_instrW_inv | iCorrectPC b_cls e_cls | .. ].\n    iEpilogue \"(HPC & Hi & Hr1)\".\n\n    iApply \"Hcont\". do 4 (iDestruct \"Hprog_done\" as \"(? & Hprog_done)\"). iFrame.\n  Qed.\n\nEnd stack_macros.\n", "meta": {"author": "logsem", "repo": "cerise-stack-monotone", "sha": "dff1909f6abc6de99c28d8f12e903b98dd76fb41", "save_path": "github-repos/coq/logsem-cerise-stack-monotone", "path": "github-repos/coq/logsem-cerise-stack-monotone/cerise-stack-monotone-dff1909f6abc6de99c28d8f12e903b98dd76fb41/theories/examples/macros/crtcls.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.24560325002903458}}
{"text": "Require Import Kami.AllNotations.\n\nRequire Import ProcKami.FU.\n\nImport ListNotations.\n\nSection trap.\n  Context {procParams: ProcParams}.\n  Variable ty: Kind -> Type.\n\n  Local Open Scope kami_expr.\n  Local Open Scope kami_action.\n\n  Local Definition NumInterrupts := 12.\n  Local Definition NumDelegs  := 16.\n\n  Local Definition isInterruptSelect\n    (k : Kind)\n    (f : bool -> ActionT ty k)\n    (isInterrupt : Bool @# ty)\n    :  ActionT ty k\n    := If isInterrupt\n         then f true\n         else f false\n         as res;\n       Ret #res.\n\n  Local Definition delegModeSelect\n    (k : Kind)\n    (f : nat -> ActionT ty k)\n    (delegMode : PrivMode @# ty)\n    :  ActionT ty k\n    := If delegMode == $MachineMode\n         then f MachineMode\n         else\n           If delegMode == $SupervisorMode\n             then f SupervisorMode\n             else f UserMode\n             as res;\n           Ret #res\n         as res;\n       Ret #res.\n\n  Local Definition delegated (deleg : Array NumDelegs Bool @# ty) (trap : Trap @# ty) : Bool @# ty\n    := deleg@[trap].\n\n  Local Definition delegModeAux\n    (trap : Trap @# ty)\n    :  list ((PrivMode @# ty) * (Array NumDelegs Bool @# ty)) -> PrivMode @# ty\n    := fold_right\n         (fun deleg lowerMode\n           => IF delegated (snd deleg) trap\n                then lowerMode\n                else fst deleg)\n         $UserMode.\n\n  Local Definition delegMode\n    (mdeleg : Array NumDelegs Bool @# ty)\n    (sdeleg : Array NumDelegs Bool @# ty)\n    (trap : Trap @# ty)\n    :  PrivMode @# ty\n    := delegModeAux trap [($MachineMode, mdeleg); ($SupervisorMode, sdeleg)].\n\n  Local Definition getModePrefix (mode : nat) : string\n    := if Nat.eqb mode MachineMode then \"m\"\n         else if Nat.eqb mode SupervisorMode then \"s\" else \"u\".\n\n  Local Definition delegName (mode : nat) (isInterrupt : bool) : string\n    := @^((getModePrefix mode) ++ (if isInterrupt then \"i\" else \"e\") ++ \"deleg\")%string.\n\n  Local Definition getDelegMode\n    (trap : Trap @# ty)\n    :  forall isInterrupt : Bool @# ty, ActionT ty PrivMode\n    := isInterruptSelect\n         (fun isInterrupt : bool\n           => let delegSz : nat\n                := if isInterrupt then NumInterrupts else NumDelegs in\n              Read mdeleg'\n                :  Bit delegSz\n                <- (delegName MachineMode isInterrupt);\n              Read sdeleg'\n                :  Bit delegSz\n                <- (delegName SupervisorMode isInterrupt);\n              LET mdeleg : Array NumDelegs Bool <- unpack _ (ZeroExtendTruncLsb _ #mdeleg');\n              LET sdeleg : Array NumDelegs Bool <- unpack _ (ZeroExtendTruncLsb _ #sdeleg');\n              Ret (delegMode #mdeleg #sdeleg trap)).\n\n  Local Definition getInterruptEnable\n    (mip : Array NumInterrupts Bool @# ty)\n    (mie : Array NumInterrupts Bool @# ty)\n    (interrupt : Interrupt @# ty)\n    :  Bool @# ty\n    := mip@[interrupt] && mie@[interrupt].\n\n  Local Definition PriorityBitStringSz : nat := 1 + PrivModeWidth + TrapSz + 0.\n\n  Local Definition PriorityBitString := Bit PriorityBitStringSz.\n\n  Local Definition getPriorityBitString\n    (status : Bool @# ty) (* pending and enabled. *)\n    (delegMode : PrivMode @# ty)\n    (trap : Trap @# ty)\n    :  PriorityBitString @# ty\n    := {< pack status, delegMode, trap >}.\n\n  Local Definition getPriorityInterrupt\n    (mip : Array NumInterrupts Bool @# ty)\n    (mie : Array NumInterrupts Bool @# ty)\n    (mideleg : Array NumDelegs Bool @# ty)\n    (sideleg : Array NumDelegs Bool @# ty)\n    :  PriorityBitString ## ty :=\n    fold_tree\n      (fun (priorityBitStringExpr : PriorityBitString ## ty)\n        (accExpr : PriorityBitString ## ty) =>\n        LETE acc <- accExpr;\n        LETE priorityBitString <- priorityBitStringExpr;\n        RetE\n          (IF #acc <= #priorityBitString\n            then #priorityBitString\n            else #acc))\n      (RetE $0)\n      (map\n        (fun trap : nat =>\n          RetE (getPriorityBitString\n            (getInterruptEnable mip mie $trap)\n            (delegMode mideleg sideleg $trap)\n            $trap))\n        (seq 0 (NumInterrupts - 1))).\n\n  (* returns either mip or mie. *)\n  Local Definition readInterruptStatus\n    (suffix : string)\n    :  ActionT ty (Array NumInterrupts Bool)\n    := Read mei : Bool <- @^(\"mei\" ++ suffix);\n       Read msi : Bool <- @^(\"msi\" ++ suffix);\n       Read mti : Bool <- @^(\"mti\" ++ suffix);\n       Read sei : Bool <- @^(\"sei\" ++ suffix);\n       Read ssi : Bool <- @^(\"ssi\" ++ suffix);\n       Read sti : Bool <- @^(\"sti\" ++ suffix);\n       Read uei : Bool <- @^(\"uei\" ++ suffix);\n       Read usi : Bool <- @^(\"usi\" ++ suffix);\n       Read uti : Bool <- @^(\"uti\" ++ suffix);\n       Ret (ARRAY {#usi; #ssi; $$false; #msi;\n                   #uti; #sti; $$false; #mti;\n                   #uei; #sei; $$false; #mei}\n            : Array NumInterrupts Bool @# ty).\n\n  Local Definition getPPWidth (mode : nat) : nat\n    := if Nat.eqb mode MachineMode then 2\n         else if Nat.eqb mode SupervisorMode then 1\n           else 0.\n\n  Local Definition updateTrapStack\n    (delegMode : nat)\n    (isInterrupt : Bool @# ty)\n    (currMode : PrivMode @# ty)\n    :  ActionT ty Void\n    := Read ie : Bool <- @^(getModePrefix delegMode ++ \"ie\");\n       Write @^(getModePrefix delegMode ++ \"pie\") : Bool <- #ie;\n       Write @^(getModePrefix delegMode ++ \"ie\") : Bool <- $$false;\n       Read extRegs: ExtensionsReg <- @^\"extRegs\";\n       LET extensions: Extensions <- ExtRegToExt #extRegs;\n       Write @^(getModePrefix delegMode ++ \"pp\")\n         :  Bit (getPPWidth delegMode)\n         <- ZeroExtendTruncLsb (getPPWidth delegMode) (modeFix #extensions currMode);\n       Write @^\"mode\" : PrivMode <- modeFix #extensions $delegMode;\n       If isInterrupt\n         then\n           Write @^\"isWfi\" : Bool <- $$false;\n           Retv;\n       Retv.\n\n  Local Definition getExceptionValue\n             (exception: Exception @# ty)\n             (pc: VAddr @# ty)\n             (inst: Inst @# ty)\n             (update_pkt : ExecUpdPkt @# ty)\n             (next_pc: VAddr @# ty)\n             (exceptionUpper: Bool @# ty) :=\n    LETC currPc <- SignExtendTruncLsb Rlen pc;\n    LETC currPc2 <- (#currPc + IF exceptionUpper then $2 else $0);\n    LETC nextPc <- SignExtendTruncLsb Rlen next_pc;\n    LETC memAddr <- (update_pkt @% \"val2\" @% \"data\" @% \"data\");\n    RetE\n      (ZeroExtendTruncLsb Xlen\n        (Switch exception Retn Data With {\n          ($InstAddrMisaligned : Exception @# ty) ::= #nextPc;\n          ($InstAccessFault: Exception @# ty) ::= #currPc2;\n          ($Breakpoint: Exception @# ty) ::= #currPc;\n          ($InstPageFault: Exception @# ty) ::= #currPc2;\n          ($IllegalInst: Exception @# ty) ::= ZeroExtendTruncLsb Rlen inst;\n          ($LoadAddrMisaligned: Exception @# ty) ::= #memAddr;\n          ($SAmoAddrMisaligned: Exception @# ty) ::= #memAddr;\n          ($LoadAccessFault: Exception @# ty) ::= #memAddr;\n          ($SAmoAccessFault: Exception @# ty) ::= #memAddr;\n          ($LoadPageFault: Exception @# ty) ::= #memAddr;\n          ($SAmoPageFault: Exception @# ty) ::= #memAddr\n        })).\n\n  Local Definition setTrapContext\n    (delegMode : nat)\n    (isInterrupt : Bool @# ty)\n    (xlen : XlenValue @# ty)\n    (trap: Trap @# ty)\n    (pc: VAddr @# ty)\n    (inst: Inst @# ty)\n    (updatePkt : ExecUpdPkt @# ty)\n    (nextPc: VAddr @# ty)\n    (exceptionUpper: Bool @# ty)\n    :  ActionT ty VAddr\n    := Read tvecMode : Bit 2 <- @^(getModePrefix delegMode ++ \"tvec_mode\");\n       Read tvecBase : Bit (Xlen - 2) <- @^(getModePrefix delegMode ++ \"tvec_base\");\n       LET addrBase : VAddr <- xlen_sign_extend Xlen xlen #tvecBase << ($2 : Bit 2 @# ty);\n       LET addrOffset : VAddr <- xlen_sign_extend Xlen xlen trap << ($2 : Bit 2 @# ty);\n       LETA trapValue : Bit Xlen\n         <- convertLetExprSyntax_ActionT\n              (getExceptionValue trap pc inst updatePkt nextPc exceptionUpper);\n       LET finalTrapValue: Bit Xlen <- IF isInterrupt then $0 else #trapValue;\n       LET nextPc\n         :  VAddr\n         <- IF #tvecMode == $0\n              then #addrBase\n              else (#addrBase + #addrOffset);\n       Write @^(getModePrefix delegMode ++ \"epc\") : VAddr <- pc;\n       Write @^(getModePrefix delegMode ++ \"cause_interrupt\") : Bool <- isInterrupt;\n       Write @^(getModePrefix delegMode ++ \"cause_code\")\n         :  Bit (Xlen - 1)\n         <- ZeroExtendTruncLsb (Xlen - 1) trap;\n       Write @^(getModePrefix delegMode ++ \"tval\") : Bit Xlen <- #finalTrapValue;\n       Ret #nextPc.\n\n  Local Definition trapAction\n    (delegMode : nat)\n    (isInterrupt : Bool @# ty)\n    (xlen : XlenValue @# ty)\n    (debug : Bool @# ty)\n    (currMode : PrivMode @# ty)\n    (pc : VAddr @# ty)\n    (trap : Trap @# ty)\n    (inst: Inst @# ty)\n    (updatePkt: ExecUpdPkt @# ty)\n    (returnPc: VAddr @# ty)\n    (exceptionUpper: Bool @# ty)\n    :  ActionT ty VAddr\n    := LETA _ <- updateTrapStack delegMode isInterrupt currMode;\n       setTrapContext delegMode isInterrupt xlen trap pc inst updatePkt returnPc exceptionUpper.\n\n  Definition enterDebugMode\n    (mode : PrivMode @# ty)\n    (pc : VAddr @# ty)\n    (cause : Bit 3 @# ty)\n    :  ActionT ty Void\n    := Write @^\"dpc\" : Bit Xlen <- SignExtendTruncLsb Xlen pc;\n       Write @^\"prv\" : Bit 2 <- ZeroExtendTruncLsb PrivModeWidth mode;\n       Write @^\"cause\" : Bit 3 <- cause;\n       Write @^\"debugMode\" : Bool <- $$true;\n       Retv.\n\n  Definition exitDebugMode\n    (dpc : Bit Xlen @# ty)\n    (prv : Bit 2 @# ty)\n    :  ActionT ty Void\n    := Write @^\"mode\" : PrivMode <- ZeroExtendTruncLsb PrivModeWidth prv;\n       Write @^\"debugMode\" : Bool <- $$ false;\n       Retv.\n\n  Definition trapException \n    (xlen : XlenValue @# ty)\n    (debug : Bool @# ty)\n    (currMode : PrivMode @# ty)\n    (pc : VAddr @# ty)\n    (exception : Exception @# ty)\n    (inst: Inst @# ty)\n    (updatePkt: ExecUpdPkt @# ty)\n    (returnPc: VAddr @# ty)\n    (exceptionUpper: Bool @# ty)\n    :  ActionT ty VAddr\n    := LETA delegMode\n         :  PrivMode\n         <- getDelegMode exception $$false;\n       LETA nextPc\n         :  VAddr\n         <- delegModeSelect\n              (fun delegMode : nat\n                => If $delegMode >= currMode\n                     then\n                       trapAction delegMode $$false xlen debug currMode\n                         pc exception inst updatePkt returnPc exceptionUpper\n                     else Ret returnPc\n                     as nextPc;\n                   Ret #nextPc)\n              #delegMode;\n       Ret #nextPc.\n\n  Definition trapInterrupt\n    (xlen : XlenValue @# ty)\n    (debug : Bool @# ty)\n    (currMode : PrivMode @# ty)\n    (pc : VAddr @# ty)\n    :  ActionT ty (Maybe VAddr)\n    := LETA mip : Array NumInterrupts Bool <- readInterruptStatus \"p\";\n       LETA mie : Array NumInterrupts Bool <- readInterruptStatus \"e\";\n       Read mideleg : Bit NumInterrupts <- @^\"mideleg\";\n       Read sideleg : Bit NumInterrupts <- @^\"sideleg\";\n       LETA priorityBitString\n         :  PriorityBitString\n         <- convertLetExprSyntax_ActionT\n              (getPriorityInterrupt #mip #mie\n                (unpack (Array NumDelegs Bool) (ZeroExtendTruncLsb NumDelegs #mideleg))\n                (unpack (Array NumDelegs Bool) (ZeroExtendTruncLsb NumDelegs #sideleg)));\n       LET trap : Interrupt <- UniBit (TruncLsb TrapSz _) #priorityBitString;\n       LET trapIsPendingAndEnabled : Bool\n         <- (UniBit (TruncMsb (PrivModeWidth + TrapSz + 0) 1) #priorityBitString) == $1;\n       LETA delegMode\n         :  PrivMode\n         <- getDelegMode #trap $$true;\n       LETA trapsEnabled\n         :  Bool\n         <- delegModeSelect\n              (fun delegMode : nat\n                => Read enabled : Bool <- @^(getModePrefix delegMode ++ \"ie\");\n                   Ret #enabled)\n              #delegMode;\n       LET shouldTrap : Bool\n         <- ((#delegMode > currMode) || (#delegMode == currMode && #trapsEnabled)) &&\n            #trapIsPendingAndEnabled;\n       If #shouldTrap\n         then\n           delegModeSelect\n             (fun delegMode : nat\n               => trapAction delegMode $$true xlen debug currMode pc (unsafeTruncLsb TrapSz #trap) $0\n                    $$(getDefaultConst ExecUpdPkt) $0 $$false)\n             #delegMode\n         else Ret $$(getDefaultConst VAddr)\n         as nextPc;\n       Ret (STRUCT {\n         \"valid\" ::= #shouldTrap;\n         \"data\"  ::= #nextPc\n       } : Maybe VAddr @# ty).\n\n  Local Close Scope kami_action.\n  Local Close Scope kami_expr.\n\nEnd trap.\n", "meta": {"author": "sifive", "repo": "ProcKami", "sha": "7094363c5587d50653b918c323e043105fd172d6", "save_path": "github-repos/coq/sifive-ProcKami", "path": "github-repos/coq/sifive-ProcKami/ProcKami-7094363c5587d50653b918c323e043105fd172d6/Pipeline/Trap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.24559122087402285}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*          Tahina Ramananandro, Reservoir Labs Inc.                   *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** The Linear2 intermediate language: abstract syntax and semantics *)\n\n(** The Linear2 language is a variant of Linear where two executions\n    of the same code happen \"in parallel\" on two different memory\n    states. It is needed in some verified separate compilation\n    contexts where the source code has to run on the memory state\n    without argument locations at the module boundary, when the\n    initial memory state is provided by arbitrary assembly code.\n*)\n\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Locations.\nRequire Import LTL.\nRequire Import Conventions.\n\nRequire Import Linear.\nRequire Import Morphisms.\n\nInductive invar_stackframe: stackframe -> stackframe -> Prop :=\n| invar_stackframe_intro\n    fh sph rsh ch\n    fl spl rsl cl\n    (f_eq: fh = fl)\n    (sp_lessdef: Val.lessdef sph spl)\n    (rs_lessdef: forall l, Val.lessdef (rsh l) (rsl l))\n    (c_eq: ch = cl)\n  :\n    invar_stackframe\n      (Stackframe fh sph rsh ch)\n      (Stackframe fl spl rsl cl)\n.\n\nGlobal Instance invar_stackframe_refl:\n  Reflexive invar_stackframe.\nProof.\n  red. intro x.\n  destruct x.\n  econstructor; eauto.\nQed.\n\nDefinition invar_stack := list_forall2 invar_stackframe.\n\nGlobal Instance invar_stack_refl: Reflexive invar_stack.\nProof.\n  red. intro x.\n  induction x; econstructor; eauto.\n  reflexivity.\nQed.\n\nSection WITHMEMORYMODELOPS.\nContext  `{memory_model_ops: Mem.MemoryModelOps}.\n\nInductive invar: state -> state -> Prop :=\n| invar_state\n    stackh fh sph ch rsh mh\n    stackl fl spl cl rsl ml\n    (stack_inv: invar_stack stackh stackl)\n    (f_eq: fh = fl)\n    (sp_lessdef: Val.lessdef sph spl)\n    (c_eq: ch = cl)\n    (rs_lessdef: forall l, Val.lessdef (rsh l) (rsl l))\n    (m_ext: Mem.extends mh ml)\n  :\n    invar\n      (State stackh fh sph ch rsh mh)\n      (State stackl fl spl ch rsl ml)\n| invar_callstate\n    stackh fh rsh mh\n    stackl fl rsl ml\n    (stack_inv: invar_stack stackh stackl)\n    (f_eq: fh = fl)\n    (rs_lessdef: forall l, Val.lessdef (rsh l) (rsl l))\n    (m_ext: Mem.extends mh ml)\n  :\n    invar\n      (Callstate stackh fh rsh mh)\n      (Callstate stackl fl rsl ml)\n| invar_returnstate\n    stackh rsh mh\n    stackl rsl ml\n    (stack_inv: invar_stack stackh stackl)\n    (rs_lessdef: forall l, Val.lessdef (rsh l) (rsl l))\n    (m_ext: Mem.extends mh ml)\n  :\n    invar\n      (Returnstate stackh rsh mh)\n      (Returnstate stackl rsl ml)\n.\n\nContext `{memory_model: !Mem.MemoryModel mem}.\n\nGlobal Instance invar_refl: Reflexive invar.\nProof.\n  red.\n  intro x. destruct x.\n  {\n    econstructor; eauto; try reflexivity.\n    apply Mem.extends_refl.\n  }\n  {\n    econstructor; eauto; try reflexivity.\n    apply Mem.extends_refl.\n  }\n  {\n    econstructor; eauto; try reflexivity.\n    apply Mem.extends_refl.\n  }\nQed.\n\nEnd WITHMEMORYMODELOPS.\n\nSection WITHCONFIG.\nContext `{external_calls_prf: ExternalCalls}.\n\nRecord state: Type := State\n  {\n    state_higher: Linear.state;\n    state_lower:  Linear.state;\n    state_ge: Linear.genv;\n    state_init_ls: locset;\n    state_invariant: invar state_higher state_lower\n  }.\n\nRecord step (ge: genv) (before: state) (t: trace) (after: state): Prop :=\n  {\n    step_ge_eq_before: ge = state_ge before;\n    step_ge_eq_after: ge = state_ge after;\n    step_init_ls_eq: state_init_ls after = state_init_ls before;\n    step_high: Linear.step (state_init_ls before) ge (state_higher before) t (state_higher after);\n    step_low: Linear.step (state_init_ls before) ge (state_lower before) t (state_lower after)\n  }.\n\n(* Whole-program case *)\n\nInductive initial_state (p: program) (s: state): Prop :=\n| initial_state_intro\n    (init_higher: Linear.initial_state p (state_higher s))\n    (init_lower: Linear.initial_state p (state_lower s))\n    (init_ls: state_init_ls s = Locmap.init Vundef)\n.\n\nInductive final_state (s: state) (i: int): Prop :=\n| final_state_intro\n    j (fin_higher: Linear.final_state (state_higher s) j)\n    (fin_lower: Linear.final_state (state_lower s) i)\n.\n\nDefinition semantics (p: program) :=\n  Semantics step (initial_state p) final_state (Genv.globalenv p).\n\n(* Whole-program Linear trivially forward-simulates into Linear2:\n   the two executions are actually the same as the Linear one.\n*)\n\nRecord whole_program_invariant (ge: genv) (u: unit) (s: Linear.state) (s2: state): Prop :=\n{\n  wp_inv_state_higher_eq:\n    state_higher s2 = s;\n  wp_inv_state_lower_eq:\n    state_lower s2 = s;\n  wp_inv_ge_eq:\n    state_ge s2 = ge;\n  wp_inv_init_ls_eq:\n    state_init_ls s2 = Locmap.init Vundef\n}.\n\nTheorem whole_program_linear_to_linear2 p:\n  forward_simulation\n    (Linear.semantics p)\n    (semantics p)\n.\nProof.\n  apply Forward_simulation with\n    (order := fun _ _ => False)\n      (match_states := whole_program_invariant (Genv.globalenv p)).\n  constructor.\n  * constructor. contradiction.\n  * intros s1 H.\n    exists tt.\n    eexists (State s1 s1 (Genv.globalenv p) (Locmap.init Vundef) _).\n    split.\n    { econstructor; eauto. }\n    econstructor; eauto.\n  * inversion 1; subst.\n    simpl.\n    intros.\n    econstructor; eauto.\n    congruence.\n  * simpl.\n    intros s1 t s1' H i s2 H0.\n    inversion H0; subst.\n    exists tt.\n    eexists (State s1' s1' (Genv.globalenv p) (Locmap.init Vundef) _).\n    split.\n    {\n      left.\n      eapply plus_one.\n      econstructor; simpl; eauto; congruence.\n    }\n    econstructor; eauto.\n  * reflexivity.\nGrab Existential Variables.\neauto.\nreflexivity.\neauto.\nreflexivity.\nDefined.\n\nEnd WITHCONFIG.", "meta": {"author": "CertiKOS", "repo": "compcert.old", "sha": "1fbd4e9beeb9e58b15f7f20ab1c949f6381a4105", "save_path": "github-repos/coq/CertiKOS-compcert.old", "path": "github-repos/coq/CertiKOS-compcert.old/compcert.old-1fbd4e9beeb9e58b15f7f20ab1c949f6381a4105/backend/Linear2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.24559121566605585}}
{"text": "Require Import Rupicola.Lib.Api.\n\n\nInductive annotation {width: Z} {BW: Bitwidth width} {word: word.word width} : Type :=\n| Reserved : word -> annotation\n| Borrowed : word -> annotation\n| Owned : annotation\n.\n\nSection KVStore.\n  Context {width: Z} {BW: Bitwidth width} {word: word.word width} {mem: map.map word Byte.byte}.\n  Context {locals: map.map String.string word}.\n  Context {env: map.map String.string (list String.string * list String.string * Syntax.cmd)}.\n  Context {ext_spec: bedrock2.Semantics.ExtSpec}.\n  Context {word_ok : word.ok word} {mem_ok : map.ok mem}.\n  Context {locals_ok : map.ok locals}.\n  Context {env_ok : map.ok env}.\n  Context {ext_spec_ok : Semantics.ext_spec.ok ext_spec}.\n  Local Notation annotation := (@annotation _ BW word).\n\n  Definition AnnotatedValue_gen {value}\n             (Value : word -> value -> mem -> Prop)\n             (addr : word) (av : annotation * value)\n    : mem -> Prop :=\n    match (fst av) with\n    | Reserved pv => (emp (addr = pv) * Value pv (snd av))%sep\n    | Borrowed pv => emp (addr = pv)\n    | Owned => Value addr (snd av)\n    end.\n\n  Class kv_ops :=\n    { map_init : func;\n      get : func;\n      put : func; }.\n\n  Class kv_parameters\n        {ops : kv_ops} {key value : Type}\n        {Value : word -> value -> mem -> Prop} :=\n    { map_gen : forall value, map.map key value;\n      map := map_gen value;\n      annotated_map := map_gen (annotation * value);\n      init_map_size_in_bytes : nat;\n      key_eqb : key -> key -> bool;\n      Key : word -> key -> mem -> Prop;\n      Map_gen :\n        forall value (Value : word -> value ->\n                              mem -> Prop),\n          word -> map.rep (map:=map_gen value) ->\n          mem -> Prop;\n      Map : _ -> map -> _ -> _ := Map_gen value Value;\n      AnnotatedMap : _ -> annotated_map -> _ -> _ :=\n        Map_gen (annotation * value)\n                (AnnotatedValue_gen Value);\n    }.\n\n  Class kv_parameters_ok\n        {ops : kv_ops} {key value Value}\n        {p : @kv_parameters ops key value Value} :=\n    { map_ok_gen : forall value, map.ok (map_gen value);\n      map_ok : map.ok map := map_ok_gen value;\n      annotated_map_ok : map.ok annotated_map :=\n        map_ok_gen (annotation * value);\n      key_eq_dec :\n        forall x y : key, BoolSpec (x = y) (x <> y) (key_eqb x y);\n      Map_put_impl1 :\n        forall value Value pm\n               (m : map.rep (map:=map_gen value))\n               k v1 v2 R1 R2,\n          (forall pv,\n              Lift1Prop.impl1\n                (sep (Value pv v1) R1)\n                (sep (Value pv v2) R2)) ->\n          Lift1Prop.impl1\n            (sep (Map_gen value Value pm (map.put m k v1)) R1)\n            (sep (Map_gen value Value pm (map.put m k v2)) R2);\n      Map_fold_iff1 :\n        forall value1 value2 Value1 Value2 (f : value1 -> value2),\n          (forall pv v,\n              Lift1Prop.iff1 (Value1 pv v) (Value2 pv (f v))) ->\n          forall pm m,\n            Lift1Prop.iff1\n              (Map_gen value1 Value1 pm m)\n              (Map_gen value2 Value2 pm\n                       (map.fold\n                          (fun m' k v => map.put m' k (f v))\n                          map.empty m)); }.\n\n  Section specs.\n    Context {ops key value Value}\n            {kvp : @kv_parameters ops key value Value}.\n\n    Instance spec_of_map_init : spec_of \"map_init\" :=\n      fun functions =>\n        forall p start R tr mem,\n          (* { p -> start } *)\n          (* space must already be allocated at start *)\n          (truncated_scalar\n             access_size.word p (word.unsigned start)\n           * Lift1Prop.ex1\n               (fun xs: list _ =>\n                  sep (emp (length xs = init_map_size_in_bytes))\n                      (array ptsto (word.of_Z 1) start xs))\n           * R)%sep mem ->\n          WeakestPrecondition.call\n            functions \"map_init\" tr mem [p]\n            (fun tr' mem' rets =>\n               tr = tr'\n               /\\ rets = []\n               /\\ (Map p map.empty * R)%sep mem').\n\n    (* get returns a pair; a boolean (true if there was an error) and a value,\n       which is meaningless if there was an error. *)\n    Instance spec_of_map_get : spec_of \"get\" :=\n      fun functions =>\n        forall pm m pk k R tr mem,\n          sep (sep (AnnotatedMap pm m) (Key pk k)) R mem ->\n          WeakestPrecondition.call\n            functions \"get\" tr mem [pm; pk]\n            (fun tr' mem' rets =>\n               tr = tr'\n               /\\ length rets = 2%nat\n               /\\ let err := hd (word.of_Z 0) rets in\n                  let pv := hd (word.of_Z 0) (tl rets) in\n                  match map.get m k with\n                  | Some (a, v) =>\n                    err = word.of_Z 0\n                    /\\ (match a with\n                        | Borrowed pv' => pv = pv'\n                        | Reserved pv' => pv = pv'\n                        | Owned => True\n                        end)\n                    /\\ (AnnotatedMap\n                          pm (match a with\n                              | Borrowed _ => m\n                              | Reserved _ => m\n                              | Owned => map.put m k (Reserved pv, v)\n                              end) * Key pk k * R)%sep mem'\n                  | None =>\n                    (* if k not \\in m, err = true and no change *)\n                    err = word.of_Z 1\n                    /\\ (AnnotatedMap pm m * Key pk k * R)%sep mem'\n                  end).\n\n    (* put returns a boolean indicating whether the key was already\n       present. If true, the original value pointer now points to the old\n       value. *)\n    Instance spec_of_map_put : spec_of \"put\" :=\n      fun functions =>\n        forall pm m pk k pv v R tr mem,\n          (AnnotatedMap pm m\n           * Key pk k * Value pv v * R)%sep mem ->\n          WeakestPrecondition.call\n            functions \"put\" tr mem [pm; pk; pv]\n            (fun tr' mem' rets =>\n               tr = tr'\n               /\\ length rets = 1%nat\n               /\\ let was_overwrite := hd (word.of_Z 0) rets in\n                  match map.get m k with\n                  | Some (a, old_v) =>\n                    match a with\n                    | Borrowed _ => True (* no guarantees *)\n                    | Reserved pv' =>\n                      was_overwrite = word.of_Z 1\n                      /\\ (AnnotatedMap pm (map.put m k (Reserved pv', v))\n                          * Key pk k * Value pv old_v * R)%sep mem'\n                    | Owned =>\n                      was_overwrite = word.of_Z 1\n                      /\\ (AnnotatedMap pm (map.put m k (Owned, v))\n                          * Key pk k * Value pv old_v * R)%sep mem'\n                    end\n                  | None =>\n                    (* if there was no previous value, the map consumes both\n                       the key and value memory *)\n                    was_overwrite = word.of_Z 0\n                    /\\ (AnnotatedMap pm (map.put m k (Owned, v))\n                        * R)%sep mem'\n                  end).\n  End specs.\nEnd KVStore.\n", "meta": {"author": "mit-plv", "repo": "rupicola", "sha": "3f59b3d2404ce425ddf4fd55ad2314996a573dc3", "save_path": "github-repos/coq/mit-plv-rupicola", "path": "github-repos/coq/mit-plv-rupicola/rupicola-3f59b3d2404ce425ddf4fd55ad2314996a573dc3/src/Rupicola/Examples/KVStore/KVStore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2455691446387585}}
{"text": "From stbor.lang Require Export lang.\n\nSet Default Proof Using \"Type\".\n\n(** Wellformedness *)\nClass Wellformed A := Wf : A → Prop.\nExisting Class Wf.\n\nDefinition wf_mem_tag (h: mem) (nxtp: ptr_id) :=\n  ∀ l l' pid, h !! l = Some (ScPtr l' (Tagged pid)) → (pid < nxtp)%nat.\n\nDefinition stack_item_included (stk: stack) (nxtp: ptr_id) (nxtc: call_id) :=\n  ∀ si, si ∈ stk → match si.(tg) with\n                    | Tagged t => (t < nxtp)%nat\n                    | _ => True\n                   end ∧\n                   match si.(protector) with\n                    | Some c => (c < nxtc)%nat\n                    | _ => True\n                   end.\n\nDefinition is_tagged (it: item) :=\n  match it.(tg) with Tagged _ => True | _ => False end.\nInstance is_tagged_dec: Decision (is_tagged it).\nProof. intros. rewrite /is_tagged. case tg; solve_decision. Defined.\nDefinition stack_item_tagged_NoDup (stk : stack) :=\n  NoDup (fmap tg (filter is_tagged stk)).\n\nDefinition wf_stack_item (α: stacks) (nxtp: ptr_id) (nxtc: call_id) :=\n  ∀ l stk, α !! l = Some stk → stack_item_included stk nxtp nxtc ∧ stack_item_tagged_NoDup stk.\nDefinition wf_non_empty (α: stacks) :=\n  ∀ l stk, α !! l = Some stk → stk ≠ [].\nDefinition wf_no_dup (α: stacks) :=\n  ∀ l stk, α !! l = Some stk → NoDup stk.\nDefinition wf_cid_incl (cids: call_id_stack) (nxtc: call_id) :=\n  ∀ c : call_id, c ∈ cids → (c < nxtc)%nat.\n\nRecord state_wf' (s: state) := {\n  state_wf_dom : dom (gset loc) s.(shp) ≡ dom (gset loc) s.(sst);\n  state_wf_mem_tag : wf_mem_tag s.(shp) s.(snp);\n  state_wf_stack_item : wf_stack_item s.(sst) s.(snp) s.(snc);\n  state_wf_non_empty : wf_non_empty s.(sst);\n  state_wf_cid_no_dup : NoDup s.(scs) ;\n  state_wf_cid_agree: wf_cid_incl s.(scs) s.(snc);\n  (* state_wf_cid_non_empty : s.(scs) ≠ []; *)\n  (* state_wf_no_dup : wf_no_dup σ.(cst).(sst); *)\n}.\n\nInstance state_wf : Wellformed state :=  state_wf'.\nInstance config_wf : Wellformed config := λ cfg, Wf cfg.(cst).\n\nFixpoint active_SRO (stk: stack) : gset ptr_id :=\n  match stk with\n  | [] => ∅\n  | it :: stk =>\n    match it.(perm) with\n    | SharedReadOnly => match it.(tg) with\n                        | Tagged t => {[t]} ∪ active_SRO stk\n                        | Untagged => active_SRO stk\n                        end\n    | _ => ∅\n    end\n  end.\n\nNotation terminal e := (is_Some (to_result e)).\nLemma expr_terminal_False (e: expr) : ¬ terminal e ↔ to_result e = None.\nProof.\n  split.\n  - destruct (to_result e) eqn:Eqv; [|done].\n    intros TERM. exfalso. apply TERM. by eexists.\n  - intros Eq1 [? Eq2]. by rewrite Eq1 in Eq2.\nQed.\n\n\n(** IntoResult is like IntoVal but works with our parameterized semantics. *)\nClass IntoResult (e: expr) (r: result) := into_result : of_result r = e.\nGlobal Instance val_into_result (v: value) : IntoResult v v.\nProof. done. Qed.\nGlobal Instance place_into_result l tg ty : IntoResult (Place l tg ty) (PlaceR l tg ty).\nProof. done. Qed.\nGlobal Instance result_into_result r : IntoResult (of_result r) r.\nProof. done. Qed.\n\nLemma into_result_terminal e r :\n  IntoResult e r → terminal e.\nProof. intros <-. destruct r; eauto. Qed.\n\n(** Thread steps *)\nInductive tstep (fns: fn_env) (eσ1 eσ2 : expr * state) : Prop :=\n| ThreadStep ev efs\n    (PRIM: prim_step (Λ:= bor_ectx_lang fns) eσ1.1 eσ1.2 ev eσ2.1 eσ2.2 efs)\n.\n\nNotation \"x ~{ fn }~> y\" := (tstep fn x y) (at level 70, format \"x  ~{ fn }~>  y\").\nNotation \"x ~{ fn }~>* y\" := (rtc (tstep fn) x y)\n  (at level 70, format \"x  ~{ fn }~>*  y\").\nNotation \"x ~{ fn }~>+ y\" := (tc (tstep fn) x y)\n  (at level 70, format \"x  ~{ fn }~>+  y\").\n\nDefinition reducible fs e σ := (∃ e' σ', (e,σ) ~{fs}~> (e', σ')).\nDefinition never_stuck fs e σ :=\n  ∀ e' σ', (e, σ) ~{fs}~>* (e', σ') → terminal e' ∨ reducible fs  e' σ'.\n\nDefinition init_expr := (Call #[\"main\"] []).\nDefinition init_state := (mkState ∅ ∅ [O] O 1).\n\n(*=================================== UNUSED =================================*)\n(* Implicit Type (ρ: cfg bor_lang). *)\n\n(* TODO: this may need strengthening *)\n(* Definition cfg_wf' ρ : Prop := Wf ρ.2. *)\n(* Instance cfg_wf : Wellformed (cfg bor_lang) :=  cfg_wf'. *)\n\n(* Definition threads_terminal' (el: list expr) := ∀ e, e ∈ el → terminal e. *)\n(* Instance threads_terminal : Terminal (list expr) := threads_terminal'. *)\n(* Definition cfg_terminal' ρ : Prop := terminal ρ.1. *)\n(* Instance cfg_terminal : Terminal (cfg bor_lang) := cfg_terminal'. *)\n", "meta": {"author": "ocecaco", "repo": "stacked-borrows", "sha": "92090a71d2cb61887b8d037fff6fe13a0199e3c5", "save_path": "github-repos/coq/ocecaco-stacked-borrows", "path": "github-repos/coq/ocecaco-stacked-borrows/stacked-borrows-92090a71d2cb61887b8d037fff6fe13a0199e3c5/theories/lang/defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.2455691446387585}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export close_type_sys.\nRequire Export Peano.\n(** printing #  $\\times$ #×# *)\n(** printing <=>  $\\Leftrightarrow$ #&hArr;# *)\n(** printing ~<~  $\\preceq$ *)\n(** printing ~=~  $\\sim$ *)\n(** printing ===>  $\\Downarrow$ *)\n(** printing [[  $[$ *)\n(** printing ]]  $]$ *)\n(** printing \\\\  $\\backslash$ *)\n(** printing mkc_axiom   $\\mathtt{Ax}$ *)\n(** printing mkc_base    $\\mathtt{Base}$ *)\n(** printing mkc_int     $\\intg$ *)\n(** printing mkc_integer $\\mathtt{int}$ *)\n(* begin hide *)\n\n\nLemma defines_only_universes_univi {o} :\n  forall lib i, @defines_only_universes o lib (univi lib i).\nProof.\n  unfold defines_only_universes; sp.\n  allrw @univi_exists_iff; sp.\n  exists j; sp.\nQed.\n\nLemma defines_only_universes_univ {o} :\n  forall lib, @defines_only_universes o lib (univ lib).\nProof.\n  unfold defines_only_universes, univ; sp.\n  induction i; allsimpl; sp.\n  exists i; sp.\nQed.\n\n\n(* end hide *)\n\n(**\n\n  We prove that all the Nuprl universes satisfy the type system\n  properties.\n\n*)\n\nLemma univi_type_system {o} :\n  forall lib (i : nat), @type_system o lib (univi lib i).\nProof.\n  induction i using comp_ind_type.\n  unfold type_system; sp.\n\n  - unfold uniquely_valued, eq_term_equals; sp.\n    allrw @univi_exists_iff; sp.\n    spcast; computes_to_eqval.\n    allrw; sp.\n\n  - introv q h.\n    allrw @univi_exists_iff; exrepnd.\n    exists j; sp.\n    rw <- h; auto.\n\n  - unfold type_symmetric; sp.\n    allrw @univi_exists_iff; sp.\n    exists j; sp.\n\n  - unfold type_transitive; sp.\n    allrw @univi_exists_iff; sp.\n    spcast; computes_to_eqval.\n    eexists; sp; spcast; sp.\n\n  - unfold type_value_respecting; sp.\n    allrw @univi_exists_iff; sp.\n    exists j; sp; thin_trivials.\n    spcast; apply cequivc_uni with (t := T); auto.\n\n  - unfold term_symmetric, term_equality_symmetric; sp.\n    allrw @univi_exists_iff; sp; spcast.\n    discover; sp.\n    allrw.\n    exists eqa; auto.\n    generalize (@close_type_system o lib (univi lib j)); intro k.\n    repeat (dest_imp k hyp).\n    apply defines_only_universes_univi.\n    inversion k; sp.\n\n  - unfold term_transitive, term_equality_transitive; sp.\n    allrw @univi_exists_iff; sp.\n    discover; sp; spcast.\n    allrw.\n    generalize (@close_type_system o lib (univi lib j)); intro k.\n    repeat (dest_imp k hyp).\n    apply defines_only_universes_univi.\n    inversion k; sp.\n    exists eqa0.\n    apply uniquely_valued_trans4 with (T2 := t2) (eq1 := eqa); sp.\n\n  - unfold term_value_respecting, term_equality_respecting; sp.\n    allrw @univi_exists_iff; sp.\n    discover; sp; spcast; GC.\n    allrw.\n    exists eqa.\n    generalize (@close_type_system o lib (univi lib j)); intro k.\n    repeat (dest_imp k hyp).\n    apply defines_only_universes_univi.\n    inversion k; sp.\nQed.\n\n(* begin hide *)\n\nLemma nuprli_type_system {o} :\n  forall lib (i : nat), @type_system o lib (nuprli lib i).\nProof.\n  unfold nuprli; sp.\n  apply close_type_system.\n  apply univi_type_system.\n  apply defines_only_universes_univi.\nQed.\n\nLemma nuprli_uniquely_valued {o} :\n  forall lib i1 i2 (T T' : @CTerm o) eq eq',\n    nuprli lib i1 T T' eq\n    -> nuprli lib i2 T T' eq'\n    -> eq_term_equals eq eq'.\nProof.\n  sp.\n  assert (nuprli lib (i2 + i1) T T' eq) as c1 by (apply typable_in_higher_univ; auto).\n  assert (nuprli lib (i1 + i2) T T' eq') as c2 by (apply typable_in_higher_univ; auto).\n  assert (i1 + i2 = i2 + i1) as e by omega.\n  rww e.\n  generalize (@nuprli_type_system o lib (i2 + i1)); intro nts.\n  destruct nts; sp.\n  unfold uniquely_valued in u.\n  apply u with (T := T) (T' := T'); auto.\nQed.\n\nLemma nuprli_type_transitive {o} :\n  forall lib i1 i2 (T1 T2 T3 : @CTerm o) eq,\n    nuprli lib i1 T1 T2 eq\n    -> nuprli lib i2 T2 T3 eq\n    -> {i : nat & nuprli lib i T1 T3 eq # i1 <= i # i2 <= i}.\nProof.\n  sp.\n  assert (nuprli lib (i1 + i2) T1 T2 eq) as c1 by (apply typable_in_higher_univ_r; auto).\n  assert (nuprli lib (i1 + i2) T2 T3 eq) as c2 by (apply typable_in_higher_univ; auto).\n  exists (i1 + i2); sp; try omega.\n  generalize (@nuprli_type_system o lib (i1 + i2)); intro nts.\n  destruct nts; sp.\n  apply p2 with (T2 := T2); sp.\nQed.\n\nLemma univi_uniquely_valued {o} :\n  forall lib i1 i2 (T T' : @CTerm o) eq eq',\n    univi lib i1 T T' eq\n    -> univi lib i2 T T' eq'\n    -> eq_term_equals eq eq'.\nProof.\n  sp.\n  assert (univi lib (i2 + i1) T T' eq) as c1 by (apply uni_in_higher_univ; auto).\n  assert (univi lib (i1 + i2) T T' eq') as c2 by (apply uni_in_higher_univ; auto).\n  assert (i1 + i2 = i2 + i1) as e by omega.\n  rww e.\n  generalize (@univi_type_system o lib (i2 + i1)); intro uts.\n  destruct uts; sp.\n  unfold uniquely_valued in u.\n  apply u with (T := T) (T' := T'); auto.\nQed.\n\n(* end hide *)\n\n\n(**\n\n  We prove that that [univ] satisfies the type system properties.\n\n*)\n\nLemma univ_type_system {o} : forall lib, @type_system o lib (univ lib).\nProof.\n  unfold univ, type_system; sp.\n\n  - unfold uniquely_valued; sp.\n    apply (univi_uniquely_valued lib) with (i1 := i0) (i2 := i) (T := T) (T' := T'); auto.\n\n  - unfold type_extensionality; sp.\n    exists i.\n    generalize (@univi_type_system o lib i); intro uts.\n    dest_ts uts.\n    unfold type_extensionality in ts_ext.\n    apply ts_ext with (eq := eq); auto.\n\n  - unfold type_symmetric; sp.\n    exists i.\n    generalize (@univi_type_system o lib i); intro uts.\n    dest_ts uts; auto.\n\n  - unfold type_transitive; introv u1 u2; exrepnd.\n    apply uni_in_higher_univ with (k := i0) in u0.\n    apply uni_in_higher_univ_r with (k := i) in u2.\n    exists (i0 + i).\n    generalize (@univi_type_system o lib (i0 + i)); intro uts.\n    dest_ts uts; auto.\n    apply ts_tyt with (T2 := T2); auto.\n\n  - unfold type_value_respecting; sp.\n    exists i.\n    generalize (@univi_type_system o lib i); intro uts.\n    dest_ts uts; sp.\n\n  - unfold term_symmetric, term_equality_symmetric; introv u e1; exrepnd.\n    generalize (@univi_type_system o lib i); intro uts.\n    dest_ts uts; sp.\n    apply ts_tes in u0.\n    apply u0; auto.\n\n  - unfold term_transitive, term_equality_transitive; introv u e1 e2; exrepnd.\n    generalize (@univi_type_system o lib i); intro uts.\n    dest_ts uts; sp.\n    apply ts_tet in u0.\n    apply u0 with (t2 := t2); auto.\n\n  - unfold term_value_respecting, term_equality_respecting; introv u e1 c1; exrepnd.\n    generalize (@univi_type_system o lib i); intro uts.\n    dest_ts uts; sp.\n    apply ts_tev in u0.\n    apply u0; auto.\nQed.\n\n(**\n\n  Finally, we prove that that [nuprl] satisfies the type system properties.\n\n*)\n\nLemma nuprl_type_system {p} : forall lib, @type_system p lib (nuprl lib).\nProof.\n  introv.\n  apply close_type_system.\n  apply univ_type_system.\n  apply defines_only_universes_univ.\nQed.\n\n(* begin hide *)\n\n(** Here is a tactic to use the fact that nuprl is a type system *)\nLtac nts :=\n  match goal with\n      [ p : POpid , lib : library |- _ ] =>\n      pose proof (@nuprl_type_system p lib) as nts;\n        destruct nts as [ nts_uv nts ];\n        destruct nts as [ nts_ext nts ];\n        destruct nts as [ nts_tys nts ];\n        destruct nts as [ nts_tyt nts ];\n        destruct nts as [ nts_tyv nts ];\n        destruct nts as [ nts_tes nts ];\n        destruct nts as [ nts_tet nts_tev ]\n  end.\n\nLemma nuprl_refl {p} :\n  forall lib (t1 t2 : @CTerm p) eq,\n    nuprl lib t1 t2 eq -> nuprl lib t1 t1 eq.\nProof.\n  intros.\n  nts.\n  assert (nuprl lib t2 t1 eq); sp.\n  use_trans t2; sp.\nQed.\n\nLemma nuprl_sym {p} :\n  forall lib (t1 t2 : @CTerm p) eq,\n    nuprl lib t1 t2 eq -> nuprl lib t2 t1 eq.\nProof.\n  intros; nts; sp.\nQed.\n\nLemma nuprl_trans {p} :\n  forall lib (t1 t2 t3 : @CTerm p) eq1 eq2,\n    nuprl lib t1 t2 eq1 -> nuprl lib t2 t3 eq2 -> nuprl lib t1 t3 eq1.\nProof.\n  introv n1 n2; nts.\n  use_trans t2; sp.\n  use_ext eq2; sp.\n  apply uniquely_valued_eq with (ts := nuprl lib) (T := t2) (T1 := t3) (T2 := t1); sp.\nQed.\n\nLemma nuprl_uniquely_valued {p} :\n  forall lib (t : @CTerm p) eq1 eq2,\n    nuprl lib t t eq1\n    -> nuprl lib t t eq2\n    -> eq_term_equals eq1 eq2.\nProof.\n  introv n1 n2; nts.\n  apply nts_uv with (T := t) (T' := t); sp.\nQed.\n\nLemma nuprl_value_respecting_left {p} :\n  forall lib (t1 t2 t3 : @CTerm p) eq,\n    nuprl lib t1 t2 eq\n    -> cequivc lib t1 t3\n    -> nuprl lib t3 t2 eq.\nProof.\n  intros.\n  nts.\n  assert (nuprl lib t1 t3 eq) as eq13\n    by (apply nts_tyv; auto; apply nts_tyt with (T2 := t2); auto).\n  apply nts_tyt with (T2 := t1); auto.\nQed.\n\nLemma nuprl_value_respecting_right {p} :\n  forall lib t1 t2 t3 eq,\n    @nuprl p lib t1 t2 eq\n    -> cequivc lib t2 t3\n    -> nuprl lib t1 t3 eq.\nProof.\n  intros.\n  nts.\n  assert (nuprl lib t2 t3 eq) as eq23\n    by (apply nts_tyv; auto; apply nts_tyt with (T2 := t1); auto).\n  apply nts_tyt with (T2 := t2); auto.\nQed.\n\nLemma nuprl_eq_implies_eqorceq_refl {p} :\n  forall lib T1 T2 eq t1 t2,\n    @nuprl p lib T1 T2 eq\n    -> eq t1 t2\n    -> eqorceq lib eq t1 t1 # eqorceq lib eq t2 t2.\nProof.\n  introv n e.\n  nts; sp; left.\n  unfold term_transitive, term_equality_transitive in nts_tet.\n  apply nts_tet with (t2 := t2) (T := T1) (T' := T2); sp.\n  unfold term_symmetric, term_equality_symmetric in nts_tes.\n  apply nts_tes with (T := T1) (T' := T2); sp.\n  unfold term_transitive, term_equality_transitive in nts_tet.\n  apply nts_tet with (t2 := t1) (T := T1) (T' := T2); sp.\n  unfold term_symmetric, term_equality_symmetric in nts_tes.\n  apply nts_tes with (T := T1) (T' := T2); sp.\nQed.\n\n(* end hide *)\n\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/per/nuprl_type_sys.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2453745533667865}}
{"text": "(* Class Cl (a : Type).\nParameter A : Type.\nInstance cl_a : Cl A.\n\nParameter Foo Bar : Type -> Type.\n\nParameter conv : forall {k} `{Cl k}, Foo k -> Bar k.\nParameter func : Bar A -> bool.\n\nCoercion conv : Foo >-> Bar.\n\nFail Definition test (b : Foo A) : bool := func b. *)\n\nClass Cl (a : Type).\nParameter A : Type.\nDeclare Instance cl_a : Cl A.\n\nParameter Foo Bar : Type -> Type.\n\nParameter conv : forall {k} `{Cl k}, Foo k -> Bar k.\nParameter func : forall {a}, Bar a -> bool.\n\nSubClass FooA := Foo A.\nSubClass BarA := Bar A.\nCoercion conv_A := conv : FooA -> BarA.\n(* Not used, doesn't help *)\n(* Coercion bar_a_back := @id _ : BarA -> Bar A.\nCoercion foo_a_back := @id _ : FooA -> Foo A. *)\n\n(* Not usable, it violates uniform inheritance *)\n(* Coercion conv_A' := conv : Foo A -> Bar A. *)\n\nDefinition test1 (b : FooA) : bool := func b.\nFail Definition test2 (b : Foo A) : bool := func b.\n(* Print Coercion Paths Foo BarA. *)\n\nDefinition func_A : Bar A -> bool := func.\n\nDefinition test_3 (b : FooA) : bool := func_A b.\nFail Definition test_4 (b : Foo A) : bool := func_A b.\n\nDefinition func_A_1 : BarA -> bool := func.\n\nDefinition test_5 (b : FooA) : bool := func_A_1 b.\nFail Definition test_6 (b : Foo A) : bool := func_A_1 b.\n", "meta": {"author": "Blaisorblade", "repo": "Coq-playground", "sha": "add7e5b75cfc127b7a76012325a68ddfd9dc463e", "save_path": "github-repos/coq/Blaisorblade-Coq-playground", "path": "github-repos/coq/Blaisorblade-Coq-playground/Coq-playground-add7e5b75cfc127b7a76012325a68ddfd9dc463e/theories/test_coerce.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.24537455336678649}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.fieldlist.\nRequire Import VST.floyd.computable_theorems.\nImport compcert.lib.Maps.\nOpen Scope nat.\n\nInductive ListType: list Type -> Type :=\n  | Nil: ListType nil\n  | Cons: forall {A B} (a: A) (b: ListType B), ListType (A :: B).\n\nFixpoint ListTypeGen {A} (F: A -> Type) (f: forall A, F A) (l: list A) : ListType (map F l) :=\n  match l with\n  | nil => Nil\n  | cons h t => Cons (f h) (ListTypeGen F f t)\n  end.\n\nLemma ListTypeGen_preserve: forall A F f1 f2 (l: list A),\n  (forall a, In a l -> f1 a = f2 a) ->\n  ListTypeGen F f1 l = ListTypeGen F f2 l.\nProof.\n  intros.\n  induction l.\n  + reflexivity.\n  + simpl.\n    rewrite H, IHl.\n    - reflexivity.\n    - intros; apply H; simpl; tauto.\n    - simpl; left; auto.\nDefined.\n\nDefinition decay' {X} {F: Type} {l: list X} (v: ListType (map (fun _ => F) l)): list F.\n  remember (map (fun _ : X => F) l) eqn:E.\n  revert l E.\n  induction v; intros.\n  + exact nil.\n  + destruct l; inversion E.\n    specialize (IHv l H1).\n    rewrite H0 in a.\n    exact (a :: IHv).\nDefined.\n\nFixpoint decay'' {X} {F: Type} (l0 : list Type) (v: ListType l0) :\n  forall (l: list X), l0 = map (fun _ => F) l -> list F :=\n  match v in ListType l1\n    return forall l2, l1 = map (fun _ => F) l2 -> list F\n  with\n  | Nil => fun _ _ => nil\n  | Cons A B a b =>\n    fun (l1 : list X) (E0 : A :: B = map (fun _ : X => F) l1) =>\n    match l1 as l2 return (A :: B = map (fun _ : X => F) l2 -> list F) with\n    | nil => fun _ => nil (* impossible case *)\n    | x :: l2 =>\n       fun E1 : A :: B = map (fun _ : X => F) (x :: l2) =>\n       (fun\n          X0 : map (fun _ : X => F) (x :: l2) =\n               map (fun _ : X => F) (x :: l2) -> list F =>\n        X0 eq_refl)\n         match\n           E1 in (_ = y)\n           return (y = map (fun _ : X => F) (x :: l2) -> list F)\n         with\n         | eq_refl =>\n             fun H0 : A :: B = map (fun _ : X => F) (x :: l2) =>\n              (fun (H3 : A = F) (H4 : B = map (fun _ : X => F) l2) =>\n                  (eq_rect A (fun A0 : Type => A0) a F H3) :: (decay'' B b l2 H4))\n                 (f_equal\n                    (fun e : list Type =>\n                     match e with\n                     | nil => A\n                     | T :: _ => T\n                     end) H0)\n                (f_equal\n                   (fun e : list Type =>\n                    match e with\n                    | nil => B\n                    | _ :: l3 => l3\n                    end) H0)\n         end\n    end E0\n  end.\n\nDefinition decay {X} {F: Type} {l: list X} (v: ListType (map (fun _ => F) l)): list F :=\n  let l0 := map (fun _ => F) l in\n  let E := @eq_refl _ (map (fun _ => F) l) : l0 = map (fun _ => F) l in\n  decay'' l0 v l E.\n\nLemma decay_spec: forall A F f l,\n  decay (ListTypeGen (fun _: A => F) f l) = map f l.\nProof.\n  intros.\n  unfold decay.\n  induction l.\n  + simpl.\n    reflexivity.\n  + simpl.\n    f_equal.\n    auto.\nDefined.\n\nSection COMPOSITE_ENV.\nContext {cs: compspecs}.\n\nLemma type_ind: forall P : type -> Prop,\n  (forall t,\n  match t with\n  | Tarray t0 _ _ => P t0\n  | Tstruct id _ => let m := co_members (get_co id) in Forall (fun it => P (field_type (name_member it) m)) m\n  | Tunion id _ => let m := co_members (get_co id) in Forall (fun it => P (field_type (name_member it) m)) m\n  | _ => True\n  end -> P t) ->\n  forall t, P t.\nProof.\n  intros P IH_TYPE.\n  intros.\n  remember (rank_type cenv_cs t) as n eqn: RANK'.\n  assert (rank_type cenv_cs t <= n)%nat as RANK.\n  subst. apply le_n.\n  clear RANK'.\n  revert t RANK.\n  induction n;\n  intros;\n  specialize (IH_TYPE t); destruct t;\n  try solve [specialize (IH_TYPE I); auto].\n  + (* Tarray level 0 *)\n    simpl in RANK. inv RANK.\n  + (* Tstruct level 0 *)\n    simpl in RANK.\n    unfold get_co in IH_TYPE.\n    destruct (cenv_cs ! i); [inv RANK | apply IH_TYPE; simpl; constructor].\n  + (* Tunion level 0 *)\n    simpl in RANK.\n    unfold get_co in IH_TYPE.\n    destruct (cenv_cs ! i); [inv RANK | apply IH_TYPE].\n    simpl; constructor.\n  + (* Tarray level positive *)\n    simpl in RANK.\n    specialize (IHn t).\n    apply IH_TYPE, IHn.\n    apply le_S_n; auto.\n  + (* Tstruct level positive *)\n    simpl in RANK.\n    pose proof get_co_members_no_replicate i.\n    unfold get_co in *.\n    destruct (cenv_cs ! i) as [co |] eqn:CO; [| apply IH_TYPE; simpl; constructor].\n    apply IH_TYPE; clear IH_TYPE.\n    apply Forall_forall.\n    intros ? ?; simpl.\n    * apply IHn.\n       pose proof In_field_type _ _ H H0.\n    simpl in H1; rewrite H1.\n    apply rank_type_members with (ce := cenv_cs) in H0.\n    rewrite <- co_consistent_rank in H0.\n    eapply le_trans; [eassumption |].\n    apply le_S_n; auto.\n    exact (cenv_consistent i co CO).\n  + (* Tunion level positive *)\n    simpl in RANK.\n    pose proof get_co_members_no_replicate i.\n    unfold get_co in *.\n    destruct (cenv_cs ! i) as [co |] eqn:CO; [| apply IH_TYPE; simpl; constructor].\n    apply IH_TYPE; clear IH_TYPE.\n    apply Forall_forall.\n    intros ? ?; simpl.\n    apply IHn.\n    pose proof In_field_type _ _ H H0.\n    simpl in H1; rewrite H1.\n    apply rank_type_members with (ce := cenv_cs) in H0.\n    rewrite <- co_consistent_rank in H0.\n    eapply le_trans; [eassumption |].\n    apply le_S_n; auto.\n    exact (cenv_consistent i co CO).\nDefined.\n\nLtac type_induction t :=\n  pattern t;\n  match goal with\n  | |- ?P t =>\n    apply type_ind; clear t;\n    let t := fresh \"t\" in\n    intros t IH;\n    let id := fresh \"id\" in\n    let a := fresh \"a\" in\n    destruct t as [| | | | | | | id a | id a]\n  end.\n\nVariable A: type -> Type.\n\nDefinition A_members (ms: members) (m: member) : Type :=\n    A (field_type (name_member m) ms).\n\nDefinition FT_aux id :=\n    let m := co_members (get_co id) in ListType (map (fun it => A (field_type (name_member it) m)) m).\n\nVariable F_ByValue: forall t: type, A t.\nVariable F_Tarray: forall t n a, A t -> A (Tarray t n a).\nVariable F_Tstruct: forall id a, FT_aux id -> A (Tstruct id a).\nVariable F_Tunion: forall id a, FT_aux id -> A (Tunion id a).\n\n\nFixpoint type_func_rec (n: nat) (t: type): A t :=\n  match n with\n  | 0 =>\n    match t as t0 return A t0 with\n    | Tstruct id a =>\n       match cenv_cs ! id with\n       | None => let m := co_members (get_co id) in\n                       F_Tstruct id a (ListTypeGen (fun it => A (field_type (name_member it) m))\n                                     (fun it => F_ByValue (field_type (name_member it) m)) m)\n       | _ => F_ByValue (Tstruct id a)\n       end\n    | Tunion id a =>\n       match cenv_cs ! id with\n       | None => let m := co_members (get_co id) in\n                      F_Tunion id a (ListTypeGen (fun it => A (field_type (name_member it) m))\n                                     (fun it => F_ByValue (field_type (name_member it) m)) m)\n       | _ => F_ByValue (Tunion id a)\n       end\n    | t' => F_ByValue t'\n    end\n  | S n' =>\n    match t as t0 return A t0 with\n    | Tarray t0 n a => F_Tarray t0 n a (type_func_rec n' t0)\n    | Tstruct id a =>  let m := co_members (get_co id) in\n                            F_Tstruct id a (ListTypeGen (fun it => A (field_type (name_member it) m))\n                                        (fun it => type_func_rec n' (field_type (name_member it) m)) m)\n    | Tunion id a =>  let m := co_members (get_co id) in\n                            F_Tunion id a (ListTypeGen (fun it => A (field_type (name_member it) m))\n                                        (fun it => type_func_rec n' (field_type (name_member it) m)) m)\n    | t' => F_ByValue t'\n    end\n  end.\n\nDefinition type_func t := type_func_rec (rank_type cenv_cs t) t.\n\nLemma rank_type_Tstruct: forall id a co, cenv_cs ! id = Some co ->\n  rank_type cenv_cs (Tstruct id a) = S (co_rank (get_co id)).\nProof.\n  intros.\n  unfold get_co; simpl.\n  destruct (cenv_cs ! id); auto; congruence.\nDefined.\n\nLemma rank_type_Tunion: forall id a co, cenv_cs ! id = Some co ->\n  rank_type cenv_cs (Tunion id a) = S (co_rank (get_co id)).\nProof.\n  intros.\n  unfold get_co; simpl.\n  destruct (cenv_cs ! id); auto; congruence.\nDefined.\n\nLemma type_func_rec_rank_irrelevent: forall t n n0,\n  n >= rank_type cenv_cs t ->\n  n0 >= rank_type cenv_cs t ->\n  type_func_rec n t = type_func_rec n0 t.\nProof.\n (* DON'T USE lia IN THIS PROOF!\n   We want the proof to compute reasonably efficiently.\n*)\n  intros t.\n  type_induction t;\n  intros;\n  try solve [destruct n; simpl; auto; destruct n0; simpl; auto].\n  + (* Tarray *)\n    destruct n; simpl in H; try solve [inv H].\n    destruct n0; simpl in H; try solve [inv H0].\n    simpl. f_equal.\n    apply IH; apply le_S_n; auto.\n  + (* Tstruct *)\n    destruct (cenv_cs ! id) as [co |] eqn: CO.\n    - erewrite rank_type_Tstruct in H by eauto.\n      erewrite rank_type_Tstruct in H0 by eauto.\n      clear co CO.\n    destruct n; simpl in H; try solve [inv H].\n    destruct n0; simpl in H; try solve [inv H0].\n      simpl.\n      f_equal.\n      apply ListTypeGen_preserve.\n      intros m Hin.\n      simpl in IH.\n      generalize (Forall_forall1 _ _ IH); clear IH; intro IH.\n      specialize (IH _ Hin n n0).\n      apply le_S_n in H; apply le_S_n in H0.\n      assert (H3 := rank_type_members cenv_cs _ _ Hin).\n      pose proof get_co_members_no_replicate id.\n      pose proof In_field_type _ _ H1 Hin.\n      rewrite <- (co_consistent_rank cenv_cs (get_co id) (get_co_consistent _)) in H3.\n      unfold field_type in H2.\n      apply IH;\n       (eapply le_trans; [ | eassumption]; rewrite H2; auto).\n    - destruct n, n0; simpl;  unfold FT_aux in *;\n      generalize (F_Tstruct id a) as FF; unfold get_co;\n      rewrite CO; intros; auto.\n  + (* Tunion *)\n    destruct (cenv_cs ! id) as [co |] eqn: CO.\n    - erewrite rank_type_Tunion in H by eauto.\n      erewrite rank_type_Tunion in H0 by eauto.\n      clear co CO.\n    destruct n; simpl in H; try solve [inv H].\n    destruct n0; simpl in H; try solve [inv H0].\n      simpl.\n      f_equal.\n      apply ListTypeGen_preserve.\n      intros m Hin.\n      generalize (Forall_forall1 _ _ IH); clear IH; intro IH.\n      specialize (IH _ Hin n n0).\n      apply le_S_n in H; apply le_S_n in H0.\n      assert (H3 := rank_type_members cenv_cs _ _ Hin).\n      pose proof get_co_members_no_replicate id.\n      pose proof In_field_type _ _ H1 Hin.\n      rewrite <- (co_consistent_rank cenv_cs (get_co id) (get_co_consistent _)) in H3.\n      apply IH;\n       (eapply le_trans; [ | eassumption]; rewrite H2; auto).\n    - destruct n, n0; simpl;  unfold FT_aux in *;\n      generalize (F_Tunion id a) as FF; unfold get_co;\n      rewrite CO; intros; auto.\nDefined.\n\nDefinition FTI_aux id :=\n    let m := co_members (get_co id) in\n    (ListTypeGen (fun it => A (field_type (name_member it) m)) (fun it => type_func (field_type (name_member it) m)) m).\n\nLemma type_func_eq: forall t,\n  type_func t =\n  match t as t0 return A t0 with\n  | Tarray t0 n a => F_Tarray t0 n a (type_func t0)\n  | Tstruct id a => F_Tstruct id a (FTI_aux id)\n  | Tunion id a => F_Tunion id a (FTI_aux id)\n  | t' => F_ByValue t'\n  end.\nProof.\n  intros.\n  type_induction t; try reflexivity.\n  + (* Tstruct *)\n    unfold type_func in *.\n    simpl type_func_rec.\n    destruct (cenv_cs ! id) as [co |] eqn:CO; simpl.\n    - f_equal.\n      apply ListTypeGen_preserve; intro m.\n      unfold get_co; rewrite CO.\n      intro Hin.\n      generalize (Forall_forall1 _ _ IH); clear IH; intro IH.\n      apply type_func_rec_rank_irrelevent.\n      * assert (H0 := get_co_members_no_replicate id).\n        unfold get_co in H0; rewrite CO in H0.\n        rewrite (In_field_type _ _ H0 Hin).\n        rewrite (co_consistent_rank cenv_cs _\n                           (cenv_consistent id co CO)).\n        eapply rank_type_members; eauto.\n      * apply le_n.\n    - rewrite CO.\n      f_equal.\n      unfold FTI_aux, get_co; rewrite CO.\n      reflexivity.\n  + (* Tunion *)\n    unfold type_func in *.\n    simpl type_func_rec.\n    destruct (cenv_cs ! id) as [co |] eqn:CO; simpl.\n    - f_equal.\n      apply ListTypeGen_preserve; intro m.\n      unfold get_co; rewrite CO.\n      intro Hin.\n      generalize (Forall_forall1 _ _ IH); clear IH; intro IH.\n      apply type_func_rec_rank_irrelevent.\n      * assert (H0 := get_co_members_no_replicate id).\n        unfold get_co in H0; rewrite CO in H0.\n        rewrite (In_field_type _ _ H0 Hin).\n        rewrite (co_consistent_rank cenv_cs _\n                           (cenv_consistent id co CO)).\n        eapply rank_type_members; eauto.\n      * apply le_n.\n    - rewrite CO.\n      f_equal.\n      unfold FTI_aux, get_co; rewrite CO.\n      reflexivity.\nDefined.\n\nEnd COMPOSITE_ENV.\n\nArguments type_func {cs} A F_ByValue F_Tarray F_Tstruct F_Tunion t / .\n\nLtac type_induction t :=\n  pattern t;\n  match goal with\n  | |- ?P t =>\n    apply type_ind; clear t;\n    let t := fresh \"t\" in\n    intros t IH;\n    let id := fresh \"id\" in\n    let a := fresh \"a\" in\n    destruct t as [| | | | | | | id a | id a]\n  end.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/floyd/type_induction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.24537455336678649}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import AbsAccessor.Spec.\nRequire Import RVIC2.Specs.rvic_clear_flag.\nRequire Import RVIC2.LowSpecs.rvic_clear_flag.\nRequire Import RVIC2.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       interrupt_bitmap_dword_spec\n       interrupt_bit_spec\n       get_bitmap_loc_spec\n       atomic_bit_clear_release_64_spec\n    .\n\n  Lemma shiftl4:\n    forall n, Z.shiftl n 4 = n * 16.\n  Proof.\n    intros. Local Transparent Z.shiftl.\n    unfold Z.shiftl; simpl. omega.\n    Local Opaque Z.shiftl.\n  Qed.\n\n  Lemma rvic_clear_flag_spec_exists:\n    forall habd habd'  labd intid bitmap\n      (Hspec: rvic_clear_flag_spec intid bitmap habd = Some habd')\n      (Hrel: relate_RData habd labd),\n    exists labd', rvic_clear_flag_spec0 intid bitmap labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    intros. inv Hrel. destruct bitmap.\n    unfold rvic_clear_flag_spec, rvic_clear_flag_spec0 in *.\n    repeat autounfold in *. simpl in *.\n    hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec;\n      repeat destruct_con; bool_rel; simpl in *; srewrite;\n        repeat (simpl_htarget; grewrite; simpl in * ).\n    - (solve_bool_range; grewrite). (solve_bool_range; grewrite). (solve_bool_range; grewrite).\n      extract_if. rewrite shiftl4. apply andb_true_iff; split; bool_rel; omega. grewrite.\n      (solve_bool_range; grewrite). rewrite a_plus_16; try omega.\n      repeat (simpl_htarget; grewrite; simpl in * ).\n      eexists; split. reflexivity. constructor.\n      rewrite a_plus_16'; try omega. reflexivity.\n    - (solve_bool_range; grewrite). (solve_bool_range; grewrite). (solve_bool_range; grewrite).\n      extract_if. rewrite shiftl4. apply andb_true_iff; split; bool_rel; omega. grewrite.\n      (solve_bool_range; grewrite). rewrite a_plus_16; try omega.\n      repeat (simpl_htarget; grewrite; simpl in * ).\n      eexists; split. reflexivity. constructor.\n      rewrite a_plus_16'; try omega. reflexivity.\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RVIC2/RefProof/rvic_clear_flag.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.24531185012717538}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** RTL function inlining: relational specification *)\n\nRequire Import Coqlib Wfsimpl Maps Errors Integers.\nRequire Import AST Linking.\nRequire Import Op Registers RTL.\nRequire Import Inlining.\n\n(** ** Soundness of function environments. *)\n\n(** A compile-time function environment is compatible with a whole\n  program if the following condition holds. *)\n\nDefinition fenv_compat (p: program) (fenv: funenv) : Prop :=\n  forall id f,\n  fenv!id = Some f -> (prog_defmap p)!id = Some (Gfun (Internal f)).\n\nLemma funenv_program_compat:\n  forall p, fenv_compat p (funenv_program p).\nProof.\n  set (P := fun (dm: PTree.t (globdef fundef unit)) (fenv: funenv) =>\n              forall id f,\n              fenv!id = Some f -> dm!id = Some (Gfun (Internal f))).\n  assert (REMOVE: forall dm fenv id g,\n             P dm fenv ->\n             P (PTree.set id g dm) (PTree.remove id fenv)).\n  { unfold P; intros. rewrite PTree.grspec in H0. destruct (PTree.elt_eq id0 id).\n    discriminate.\n    rewrite PTree.gso; auto.\n  }\n  assert (ADD: forall io dm fenv idg,\n             P dm fenv ->\n             P (PTree.set (fst idg) (snd idg) dm) (add_globdef io fenv idg)).\n  { intros io dm fenv [id g]; simpl; intros.\n    destruct g as [ [f|ef] | v]; auto.\n    destruct (should_inline io id f); auto.\n    red; intros. rewrite ! PTree.gsspec in *.\n    destruct (peq id0 id); auto. inv H0; auto.\n  }\n  assert (REC: forall p l dm fenv,\n            P dm fenv ->\n            P (fold_left (fun x idg => PTree.set (fst idg) (snd idg) x) l dm)\n              (fold_left (add_globdef p) l fenv)).\n  { induction l; simpl; intros.\n  - auto.\n  - apply IHl. apply ADD; auto.\n  }\n  intros. apply REC. red; intros.  rewrite PTree.gempty in H; discriminate.\nQed.\n\nLemma fenv_compat_linkorder:\n  forall cunit prog fenv,\n  linkorder cunit prog -> fenv_compat cunit fenv -> fenv_compat prog fenv.\nProof.\n  intros; red; intros. apply H0 in H1.\n  destruct (prog_defmap_linkorder _ _ _ _ H H1) as (gd' & P & Q).\n  inv Q. inv H3. auto.\nQed.\n\n(** ** Properties of shifting *)\n\nLemma shiftpos_eq: forall x y, Zpos (shiftpos x y) = (Zpos x + Zpos y) - 1.\nProof.\n  intros. unfold shiftpos. zify.  try rewrite Pos2Z.inj_sub. auto.\n  zify. lia.\nQed.\n\nLemma shiftpos_inj:\n  forall x y n, shiftpos x n = shiftpos y n -> x = y.\nProof.\n  intros.\n  assert (Zpos (shiftpos x n) = Zpos (shiftpos y n)) by congruence.\n  rewrite ! shiftpos_eq in H0.\n  assert (Z.pos x = Z.pos y) by lia.\n  congruence.\nQed.\n\nLemma shiftpos_diff:\n  forall x y n, x <> y -> shiftpos x n <> shiftpos y n.\nProof.\n  intros; red; intros. elim H. eapply shiftpos_inj; eauto.\nQed.\n\nLemma shiftpos_above:\n  forall x n, Ple n (shiftpos x n).\nProof.\n  intros. unfold Ple; zify. rewrite shiftpos_eq. extlia.\nQed.\n\nLemma shiftpos_not_below:\n  forall x n, Plt (shiftpos x n) n -> False.\nProof.\n  intros. generalize (shiftpos_above x n). extlia.\nQed.\n\nLemma shiftpos_below:\n  forall x n, Plt (shiftpos x n) (Pos.add x n).\nProof.\n  intros. unfold Plt; zify. rewrite shiftpos_eq. lia.\nQed.\n\nLemma shiftpos_le:\n  forall x y n, Ple x y -> Ple (shiftpos x n) (shiftpos y n).\nProof.\n  intros. unfold Ple in *; zify. rewrite ! shiftpos_eq. lia.\nQed.\n\n\n(** ** Working with the state monad *)\n\nRemark bind_inversion:\n  forall (A B: Type) (f: mon A) (g: A -> mon B)\n         (y: B) (s1 s3: state) (i: sincr s1 s3),\n  bind f g s1 = R y s3 i ->\n  exists x, exists s2, exists i1, exists i2,\n  f s1 = R x s2 i1 /\\ g x s2 = R y s3 i2.\nProof.\n  unfold bind; intros. destruct (f s1). exists x; exists s'; exists I.\n  destruct (g x s'). inv H. exists I0; auto.\nQed.\n\nLtac monadInv1 H :=\n  match type of H with\n  | (R _ _ _ = R _ _ _) =>\n      inversion H; clear H; try subst\n  | (ret _ _ = R _ _ _) =>\n      inversion H; clear H; try subst\n  | (bind ?F ?G ?S = R ?X ?S' ?I) =>\n      let x := fresh \"x\" in (\n      let s := fresh \"s\" in (\n      let i1 := fresh \"INCR\" in (\n      let i2 := fresh \"INCR\" in (\n      let EQ1 := fresh \"EQ\" in (\n      let EQ2 := fresh \"EQ\" in (\n      destruct (bind_inversion _ _ F G X S S' I H) as [x [s [i1 [i2 [EQ1 EQ2]]]]];\n      clear H;\n      try (monadInv1 EQ2)))))))\n  end.\n\nLtac monadInv H :=\n  match type of H with\n  | (ret _ _ = R _ _ _) => monadInv1 H\n  | (bind ?F ?G ?S = R ?X ?S' ?I) => monadInv1 H\n  | (?F _ _ _ _ _ _ _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ _ _ _ _ _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ _ _ _ _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ _ _ _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ _ _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  end.\n\nFixpoint mlist_iter2 {A B: Type} (f: A -> B -> mon unit) (l: list (A*B)): mon unit :=\n  match l with\n  | nil => ret tt\n  | (x,y) :: l' => do z <- f x y; mlist_iter2 f l'\n  end.\n\nRemark mlist_iter2_fold:\n  forall (A B: Type) (f: A -> B -> mon unit) l s,\n  exists i,\n  mlist_iter2 f l s =\n  R tt (fold_left (fun a p => match f (fst p) (snd p) a with R _ s2 _ => s2 end) l s) i.\nProof.\n  induction l; simpl; intros.\n  exists (sincr_refl s); auto.\n  destruct a as [x y]. unfold bind. simpl. destruct (f x y s) as [xx s1 i1].\n  destruct (IHl s1) as [i2 EQ]. rewrite EQ. econstructor; eauto.\nQed.\n\nLemma ptree_mfold_spec:\n  forall (A: Type) (f: positive -> A -> mon unit) t s x s' i,\n  ptree_mfold f t s = R x s' i ->\n  exists i', mlist_iter2 f (PTree.elements t) s = R tt s' i'.\nProof.\n  intros.\n  destruct (mlist_iter2_fold _ _ f (PTree.elements t) s) as [i' EQ].\n  unfold ptree_mfold in H. inv H. rewrite PTree.fold_spec.\n  econstructor. eexact EQ.\nQed.\n\n(** ** Relational specification of the translation of moves *)\n\nInductive tr_moves (c: code) : node -> list reg -> list reg -> node -> Prop :=\n  | tr_moves_cons: forall pc1 src srcs dst dsts pc2 pc3,\n      tr_moves c pc1 srcs dsts pc2 ->\n      c!pc2 = Some(Iop Omove (src :: nil) dst pc3) ->\n      tr_moves c pc1 (src :: srcs) (dst :: dsts) pc3\n  | tr_moves_nil: forall srcs dsts pc,\n      srcs = nil \\/ dsts = nil ->\n      tr_moves c pc srcs dsts pc.\n\nLemma add_moves_unchanged:\n  forall srcs dsts pc2 s pc1 s' i pc,\n  add_moves srcs dsts pc2 s = R pc1 s' i ->\n  Plt pc s.(st_nextnode) \\/ Ple s'.(st_nextnode) pc ->\n  s'.(st_code)!pc = s.(st_code)!pc.\nProof.\n  induction srcs; simpl; intros.\n  monadInv H. auto.\n  destruct dsts; monadInv H. auto.\n  transitivity (st_code s0)!pc. eapply IHsrcs; eauto. monadInv EQ; simpl. extlia.\n  monadInv EQ; simpl. apply PTree.gso.\n  inversion INCR0; simpl in *. extlia.\nQed.\n\nLemma add_moves_spec:\n  forall srcs dsts pc2 s pc1 s' i c,\n  add_moves srcs dsts pc2 s = R pc1 s' i ->\n  (forall pc, Ple s.(st_nextnode) pc -> Plt pc s'.(st_nextnode) -> c!pc = s'.(st_code)!pc) ->\n  tr_moves c pc1 srcs dsts pc2.\nProof.\n  induction srcs; simpl; intros.\n  monadInv H. apply tr_moves_nil; auto.\n  destruct dsts; monadInv H. apply tr_moves_nil; auto.\n  apply tr_moves_cons with x. eapply IHsrcs; eauto.\n  intros. inversion INCR. apply H0; extlia.\n  monadInv EQ.\n  rewrite H0. erewrite add_moves_unchanged; eauto.\n  simpl. apply PTree.gss.\n  simpl. extlia.\n  extlia.\n  inversion INCR; inversion INCR0; simpl in *; extlia.\nQed.\n\n(** ** Relational specification of CFG expansion *)\n\nSection INLINING_SPEC.\n\nVariable fenv: funenv.\n\nDefinition context_below (ctx1 ctx2: context): Prop :=\n  Ple (Pos.add ctx1.(dreg) ctx1.(mreg)) ctx2.(dreg).\n\nDefinition context_stack_call (ctx1 ctx2: context): Prop :=\n  ctx1.(mstk) >= 0 /\\ ctx1.(dstk) + ctx1.(mstk) <= ctx2.(dstk).\n\nDefinition context_stack_tailcall (ctx1: context) (f: function) (ctx2: context) : Prop :=\n  ctx2.(dstk) = align ctx1.(dstk) (min_alignment f.(fn_stacksize)).\n\nSection INLINING_BODY_SPEC.\n\nVariable stacksize: Z.\n\nInductive tr_instr: context -> node -> instruction -> code -> Prop :=\n  | tr_nop: forall ctx pc c s,\n      c!(spc ctx pc) = Some (Inop (spc ctx s)) ->\n      tr_instr ctx pc (Inop s) c\n  | tr_op: forall ctx pc c op args res s,\n      Ple res ctx.(mreg) ->\n      c!(spc ctx pc) = Some (Iop (sop ctx op) (sregs ctx args) (sreg ctx res) (spc ctx s)) ->\n      tr_instr ctx pc (Iop op args res s) c\n  | tr_load: forall ctx pc c chunk addr args res s,\n      Ple res ctx.(mreg) ->\n      c!(spc ctx pc) = Some (Iload chunk (saddr ctx addr) (sregs ctx args) (sreg ctx res) (spc ctx s)) ->\n      tr_instr ctx pc (Iload chunk addr args res s) c\n  | tr_store: forall ctx pc c chunk addr args src s,\n      c!(spc ctx pc) = Some (Istore chunk (saddr ctx addr) (sregs ctx args) (sreg ctx src) (spc ctx s)) ->\n      tr_instr ctx pc (Istore chunk addr args src s) c\n  | tr_call: forall ctx pc c sg ros args res s,\n      Ple res ctx.(mreg) ->\n      c!(spc ctx pc) = Some (Icall sg (sros ctx ros) (sregs ctx args) (sreg ctx res) (spc ctx s)) ->\n      tr_instr ctx pc (Icall sg ros args res s) c\n  | tr_call_inlined:forall ctx pc sg id args res s c f pc1 ctx',\n      Ple res ctx.(mreg) ->\n      fenv!id = Some f ->\n      c!(spc ctx pc) = Some(Inop pc1) ->\n      tr_moves c pc1 (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)) ->\n      tr_funbody ctx' f c ->\n      ctx'.(retinfo) = Some(spc ctx s, sreg ctx res) ->\n      context_below ctx ctx' ->\n      context_stack_call ctx ctx' ->\n      tr_instr ctx pc (Icall sg (inr _ id) args res s) c\n  | tr_tailcall: forall ctx pc c sg ros args,\n      c!(spc ctx pc) = Some (Itailcall sg (sros ctx ros) (sregs ctx args)) ->\n      ctx.(retinfo) = None ->\n      tr_instr ctx pc (Itailcall sg ros args) c\n  | tr_tailcall_call: forall ctx pc c sg ros args res s,\n      c!(spc ctx pc) = Some (Icall sg (sros ctx ros) (sregs ctx args) res s) ->\n      ctx.(retinfo) = Some(s, res) ->\n      tr_instr ctx pc (Itailcall sg ros args) c\n  | tr_tailcall_inlined: forall ctx pc sg id args c f pc1 ctx',\n      fenv!id = Some f ->\n      c!(spc ctx pc) = Some(Inop pc1) ->\n      tr_moves c pc1 (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)) ->\n      tr_funbody ctx' f c ->\n      ctx'.(retinfo) = ctx.(retinfo) ->\n      context_below ctx ctx' ->\n      context_stack_tailcall ctx f ctx' ->\n      tr_instr ctx pc (Itailcall sg (inr _ id) args) c\n  | tr_builtin: forall ctx pc c ef args res s,\n      match res with BR r => Ple r ctx.(mreg) | _ => True end ->\n      c!(spc ctx pc) = Some (Ibuiltin ef (map (sbuiltinarg ctx) args) (sbuiltinres ctx res) (spc ctx s)) ->\n      tr_instr ctx pc (Ibuiltin ef args res s) c\n  | tr_cond: forall ctx pc cond args s1 s2 c,\n      c!(spc ctx pc) = Some (Icond cond (sregs ctx args) (spc ctx s1) (spc ctx s2)) ->\n      tr_instr ctx pc (Icond cond args s1 s2) c\n  | tr_jumptable: forall ctx pc r tbl c,\n      c!(spc ctx pc) = Some (Ijumptable (sreg ctx r) (List.map (spc ctx) tbl)) ->\n      tr_instr ctx pc (Ijumptable r tbl) c\n  | tr_return: forall ctx pc or c,\n      c!(spc ctx pc) = Some (Ireturn (option_map (sreg ctx) or)) ->\n      ctx.(retinfo) = None ->\n      tr_instr ctx pc (Ireturn or) c\n  | tr_return_inlined: forall ctx pc or c rinfo,\n      c!(spc ctx pc) = Some (inline_return ctx or rinfo) ->\n      ctx.(retinfo) = Some rinfo ->\n      tr_instr ctx pc (Ireturn or) c\n\nwith tr_funbody: context -> function -> code -> Prop :=\n  | tr_funbody_intro: forall ctx f c,\n      (forall r, In r f.(fn_params) -> Ple r ctx.(mreg)) ->\n      (forall pc i, f.(fn_code)!pc = Some i -> tr_instr ctx pc i c) ->\n      ctx.(mstk) = Z.max f.(fn_stacksize) 0 ->\n      (min_alignment f.(fn_stacksize) | ctx.(dstk)) ->\n      ctx.(dstk) >= 0 -> ctx.(dstk) + ctx.(mstk) <= stacksize ->\n      tr_funbody ctx f c.\n\nDefinition fenv_agree (fe: funenv) : Prop :=\n  forall id f, fe!id = Some f -> fenv!id = Some f.\n\nSection EXPAND_INSTR.\n\nVariable fe: funenv.\nHypothesis FE: fenv_agree fe.\n\nVariable rec: forall fe', (size_fenv fe' < size_fenv fe)%nat -> context -> function -> mon unit.\n\nHypothesis rec_unchanged:\n  forall fe' (L: (size_fenv fe' < size_fenv fe)%nat) ctx f s x s' i pc,\n  rec fe' L ctx f s = R x s' i ->\n  Ple ctx.(dpc) s.(st_nextnode) ->\n  Plt pc ctx.(dpc) ->\n  s'.(st_code)!pc = s.(st_code)!pc.\n\nRemark set_instr_other:\n  forall pc instr s x s' i pc',\n  set_instr pc instr s = R x s' i ->\n  pc' <> pc ->\n  s'.(st_code)!pc' = s.(st_code)!pc'.\nProof.\n  intros. monadInv H; simpl. apply PTree.gso; auto.\nQed.\n\nRemark set_instr_same:\n  forall pc instr s x s' i c,\n  set_instr pc instr s = R x s' i ->\n  c!(pc) = s'.(st_code)!pc ->\n  c!(pc) = Some instr.\nProof.\n  intros. rewrite H0. monadInv H; simpl. apply PTree.gss.\nQed.\n\nLemma expand_instr_unchanged:\n  forall ctx pc instr s x s' i pc',\n  expand_instr fe rec ctx pc instr s = R x s' i ->\n  Ple ctx.(dpc) s.(st_nextnode) ->\n  Plt pc' s.(st_nextnode) ->\n  pc' <> spc ctx pc ->\n  s'.(st_code)!pc' = s.(st_code)!pc'.\nProof.\n  generalize set_instr_other; intros A.\n  intros. unfold expand_instr in H; destruct instr; eauto.\n(* call *)\n  destruct (can_inline fe s1). eauto.\n  monadInv H. unfold inline_function in EQ. monadInv EQ.\n  transitivity (s2.(st_code)!pc'). eauto.\n  transitivity (s5.(st_code)!pc'). eapply add_moves_unchanged; eauto.\n    left. inversion INCR5. inversion INCR3. monadInv EQ1; simpl in *. extlia.\n  transitivity (s4.(st_code)!pc'). eapply rec_unchanged; eauto.\n    simpl. monadInv EQ; simpl. monadInv EQ1; simpl. extlia.\n    simpl. monadInv EQ1; simpl. auto.\n  monadInv EQ; simpl. monadInv EQ1; simpl. auto.\n(* tailcall *)\n  destruct (can_inline fe s1).\n  destruct (retinfo ctx) as [[rpc rreg]|]; eauto.\n  monadInv H. unfold inline_tail_function in EQ. monadInv EQ.\n  transitivity (s2.(st_code)!pc'). eauto.\n  transitivity (s5.(st_code)!pc'). eapply add_moves_unchanged; eauto.\n    left. inversion INCR5. inversion INCR3. monadInv EQ1; simpl in *. extlia.\n  transitivity (s4.(st_code)!pc'). eapply rec_unchanged; eauto.\n    simpl. monadInv EQ; simpl. monadInv EQ1; simpl. extlia.\n    simpl. monadInv EQ1; simpl. auto.\n  monadInv EQ; simpl. monadInv EQ1; simpl. auto.\n(* return *)\n  destruct (retinfo ctx) as [[rpc rreg]|]; eauto.\nQed.\n\nLemma iter_expand_instr_unchanged:\n  forall ctx pc l s x s' i,\n  mlist_iter2 (expand_instr fe rec ctx) l s = R x s' i ->\n  Ple ctx.(dpc) s.(st_nextnode) ->\n  Plt pc s.(st_nextnode) ->\n  ~In pc (List.map (spc ctx) (List.map (@fst _ _) l)) ->\n  list_norepet (List.map (@fst _ _) l) ->\n  s'.(st_code)!pc = s.(st_code)!pc.\nProof.\n  induction l; simpl; intros.\n  (* base case *)\n  monadInv H. auto.\n  (* inductive case *)\n  destruct a as [pc1 instr1]; simpl in *.\n  monadInv H. inv H3.\n  transitivity ((st_code s0)!pc).\n  eapply IHl; eauto. destruct INCR; extlia. destruct INCR; extlia.\n  eapply expand_instr_unchanged; eauto.\nQed.\n\nLemma expand_cfg_rec_unchanged:\n  forall ctx f s x s' i pc,\n  expand_cfg_rec fe rec ctx f s = R x s' i ->\n  Ple ctx.(dpc) s.(st_nextnode) ->\n  Plt pc ctx.(dpc) ->\n  s'.(st_code)!pc = s.(st_code)!pc.\nProof.\n  intros. unfold expand_cfg_rec in H. monadInv H. inversion EQ.\n  transitivity ((st_code s0)!pc).\n  exploit ptree_mfold_spec; eauto. intros [INCR' ITER].\n  eapply iter_expand_instr_unchanged; eauto.\n    subst s0; auto.\n    subst s0; simpl. extlia.\n    red; intros. exploit list_in_map_inv; eauto. intros [pc1 [A B]].\n    subst pc. unfold spc in H1. eapply shiftpos_not_below; eauto.\n    apply PTree.elements_keys_norepet.\n  subst s0; auto.\nQed.\n\nHypothesis rec_spec:\n  forall fe' (L: (size_fenv fe' < size_fenv fe)%nat) ctx f s x s' i c,\n  rec fe' L ctx f s = R x s' i ->\n  fenv_agree fe' ->\n  Ple (ctx.(dpc) + max_pc_function f) s.(st_nextnode) ->\n  ctx.(mreg) = max_reg_function f ->\n  Ple (Pos.add ctx.(dreg) ctx.(mreg)) s.(st_nextreg) ->\n  ctx.(mstk) >= 0 ->\n  ctx.(mstk) = Z.max (fn_stacksize f) 0 ->\n  (min_alignment (fn_stacksize f) | ctx.(dstk)) ->\n  ctx.(dstk) >= 0 ->\n  s'.(st_stksize) <= stacksize ->\n  (forall pc, Ple ctx.(dpc) pc -> Plt pc s'.(st_nextnode) -> c!pc = s'.(st_code)!pc) ->\n  tr_funbody ctx f c.\n\nRemark min_alignment_pos:\n  forall sz, min_alignment sz > 0.\nProof.\n  intros; unfold min_alignment.\n  destruct (zle sz 1). lia. destruct (zle sz 2). lia. destruct (zle sz 4); lia.\nQed.\n\nLtac inv_incr :=\n  match goal with\n  | [ H: sincr _ _ |- _ ] => destruct H; inv_incr\n  | _ => idtac\n  end.\n\nLemma expand_instr_spec:\n  forall ctx pc instr s x s' i c,\n  expand_instr fe rec ctx pc instr s = R x s' i ->\n  (forall r, instr_defs instr = Some r -> Ple r ctx.(mreg)) ->\n  Plt (spc ctx pc) s.(st_nextnode) ->\n  Ple (ctx.(dreg) + ctx.(mreg)) s.(st_nextreg) ->\n  ctx.(mstk) >= 0 -> ctx.(dstk) >= 0 ->\n  s'.(st_stksize) <= stacksize ->\n  (forall pc', Ple s.(st_nextnode) pc' -> Plt pc' s'.(st_nextnode) -> c!pc' = s'.(st_code)!pc') ->\n  c!(spc ctx pc) = s'.(st_code)!(spc ctx pc) ->\n  tr_instr ctx pc instr c.\nProof.\n  intros until c; intros EXP DEFS OPC OREG STK1 STK2 STK3 S1 S2.\n  generalize set_instr_same; intros BASE.\n  unfold expand_instr in EXP; destruct instr; simpl in DEFS;\n  try (econstructor; eauto; fail).\n(* call *)\n  destruct (can_inline fe s1) as [|id f P Q].\n  (* not inlined *)\n  eapply tr_call; eauto.\n  (* inlined *)\n  subst s1.\n  monadInv EXP. unfold inline_function in EQ; monadInv EQ.\n  set (ctx' := callcontext ctx x1 x2 (max_reg_function f) (fn_stacksize f) n r).\n  inversion EQ0; inversion EQ1; inversion EQ. inv_incr.\n  apply tr_call_inlined with (pc1 := x0) (ctx' := ctx') (f := f); auto.\n  eapply BASE; eauto.\n  eapply add_moves_spec; eauto.\n    intros. rewrite S1. eapply set_instr_other; eauto. unfold node; extlia.\n    extlia. extlia.\n  eapply rec_spec; eauto.\n    red; intros. rewrite PTree.grspec in H. destruct (PTree.elt_eq id0 id); try discriminate. auto.\n    simpl. subst s2; simpl in *; extlia.\n    simpl. subst s3; simpl in *; extlia.\n    simpl. extlia.\n    simpl. apply align_divides. apply min_alignment_pos.\n    assert (dstk ctx + mstk ctx <= dstk ctx'). simpl. apply align_le. apply min_alignment_pos. lia.\n    lia.\n    intros. simpl in H. rewrite S1.\n    transitivity (s1.(st_code)!pc0). eapply set_instr_other; eauto. unfold node in *; extlia.\n    eapply add_moves_unchanged; eauto. unfold node in *; extlia. extlia.\n  red; simpl. subst s2; simpl in *. extlia.\n  red; simpl. split. auto. apply align_le. apply min_alignment_pos.\n(* tailcall *)\n  destruct (can_inline fe s1) as [|id f P Q].\n  (* not inlined *)\n  destruct (retinfo ctx) as [[rpc rreg] | ] eqn:?.\n  (* turned into a call *)\n  eapply tr_tailcall_call; eauto.\n  (* preserved *)\n  eapply tr_tailcall; eauto.\n  (* inlined *)\n  subst s1.\n  monadInv EXP. unfold inline_function in EQ; monadInv EQ.\n  set (ctx' := tailcontext ctx x1 x2 (max_reg_function f) (fn_stacksize f)) in *.\n  inversion EQ0; inversion EQ1; inversion EQ. inv_incr.\n  apply tr_tailcall_inlined with (pc1 := x0) (ctx' := ctx') (f := f); auto.\n  eapply BASE; eauto.\n  eapply add_moves_spec; eauto.\n    intros. rewrite S1. eapply set_instr_other; eauto. unfold node; extlia. extlia. extlia.\n  eapply rec_spec; eauto.\n    red; intros. rewrite PTree.grspec in H. destruct (PTree.elt_eq id0 id); try discriminate. auto.\n    simpl. subst s3; simpl in *. subst s2; simpl in *. extlia.\n    simpl. subst s3; simpl in *; extlia.\n    simpl. extlia.\n    simpl. apply align_divides. apply min_alignment_pos.\n    assert (dstk ctx <= dstk ctx'). simpl. apply align_le. apply min_alignment_pos. lia.\n    lia.\n    intros. simpl in H. rewrite S1.\n    transitivity (s1.(st_code))!pc0. eapply set_instr_other; eauto. unfold node in *; extlia.\n    eapply add_moves_unchanged; eauto. unfold node in *; extlia. extlia.\n  red; simpl.\nsubst s2; simpl in *; extlia.\n  red; auto.\n(* builtin *)\n  eapply tr_builtin; eauto. destruct b; eauto.\n(* return *)\n  destruct (retinfo ctx) as [[rpc rreg] | ] eqn:?.\n  (* inlined *)\n  eapply tr_return_inlined; eauto.\n  (* unchanged *)\n  eapply tr_return; eauto.\nQed.\n\nLemma iter_expand_instr_spec:\n  forall ctx l s x s' i c,\n  mlist_iter2 (expand_instr fe rec ctx) l s = R x s' i ->\n  list_norepet (List.map (@fst _ _) l) ->\n  (forall pc instr r, In (pc, instr) l -> instr_defs instr = Some r -> Ple r ctx.(mreg)) ->\n  (forall pc instr, In (pc, instr) l -> Plt (spc ctx pc) s.(st_nextnode)) ->\n  Ple (ctx.(dreg) + ctx.(mreg)) s.(st_nextreg) ->\n  ctx.(mstk) >= 0 -> ctx.(dstk) >= 0 ->\n  s'.(st_stksize) <= stacksize ->\n  (forall pc', Ple s.(st_nextnode) pc' -> Plt pc' s'.(st_nextnode) -> c!pc' = s'.(st_code)!pc') ->\n  (forall pc instr, In (pc, instr) l -> c!(spc ctx pc) = s'.(st_code)!(spc ctx pc)) ->\n  forall pc instr, In (pc, instr) l -> tr_instr ctx pc instr c.\nProof.\n  induction l; simpl; intros.\n  (* base case *)\n  contradiction.\n  (* inductive case *)\n  destruct a as [pc1 instr1]; simpl in *. inv H0. monadInv H. inv_incr.\n  assert (A: Ple ctx.(dpc) s0.(st_nextnode)).\n    assert (B: Plt (spc ctx pc) (st_nextnode s)) by eauto.\n    unfold spc in B. generalize (shiftpos_above pc (dpc ctx)). extlia.\n  destruct H9. inv H.\n  (* same pc *)\n  eapply expand_instr_spec; eauto.\n  lia.\n  intros.\n    transitivity ((st_code s')!pc').\n    apply H7. auto. extlia.\n    eapply iter_expand_instr_unchanged; eauto.\n    red; intros. rewrite list_map_compose in H9. exploit list_in_map_inv; eauto.\n    intros [[pc0 instr0] [P Q]]. simpl in P.\n    assert (Plt (spc ctx pc0) (st_nextnode s)) by eauto. extlia.\n  transitivity ((st_code s')!(spc ctx pc)).\n    eapply H8; eauto.\n    eapply iter_expand_instr_unchanged; eauto.\n    assert (Plt (spc ctx pc) (st_nextnode s)) by eauto. extlia.\n    red; intros. rewrite list_map_compose in H. exploit list_in_map_inv; eauto.\n    intros [[pc0 instr0] [P Q]]. simpl in P.\n    assert (pc = pc0) by (eapply shiftpos_inj; eauto). subst pc0.\n    elim H12. change pc with (fst (pc, instr0)). apply List.in_map; auto.\n  (* older pc *)\n  inv_incr. eapply IHl; eauto.\n  intros. eapply Pos.lt_le_trans. eapply H2. right; eauto. extlia.\n  intros; eapply Ple_trans; eauto.\n  intros. apply H7; auto. extlia.\nQed.\n\nLemma expand_cfg_rec_spec:\n  forall ctx f s x s' i c,\n  expand_cfg_rec fe rec ctx f s = R x s' i ->\n  Ple (ctx.(dpc) + max_pc_function f) s.(st_nextnode) ->\n  ctx.(mreg) = max_reg_function f ->\n  Ple (ctx.(dreg) + ctx.(mreg)) s.(st_nextreg) ->\n  ctx.(mstk) >= 0 ->\n  ctx.(mstk) = Z.max (fn_stacksize f) 0 ->\n  (min_alignment (fn_stacksize f) | ctx.(dstk)) ->\n  ctx.(dstk) >= 0 ->\n  s'.(st_stksize) <= stacksize ->\n  (forall pc', Ple ctx.(dpc) pc' -> Plt pc' s'.(st_nextnode) -> c!pc' = s'.(st_code)!pc') ->\n  tr_funbody ctx f c.\nProof.\n  intros. unfold expand_cfg_rec in H. monadInv H. inversion EQ.\n  constructor.\n  intros. rewrite H1. eapply max_reg_function_params; eauto.\n  intros. exploit ptree_mfold_spec; eauto. intros [INCR' ITER].\n  eapply iter_expand_instr_spec; eauto.\n    apply PTree.elements_keys_norepet.\n    intros. rewrite H1. eapply max_reg_function_def with (i := instr); eauto.\n    eapply PTree.elements_complete; eauto.\n  intros.\n    assert (Ple pc0 (max_pc_function f)).\n      eapply max_pc_function_sound. eapply PTree.elements_complete; eauto.\n      eapply Pos.lt_le_trans. apply shiftpos_below. subst s0; simpl; extlia.\n  subst s0; simpl; auto.\n  intros. apply H8; auto. subst s0; simpl in H11; extlia.\n  intros. apply H8. apply shiftpos_above.\n  assert (Ple pc0 (max_pc_function f)).\n    eapply max_pc_function_sound. eapply PTree.elements_complete; eauto.\n  eapply Pos.lt_le_trans. apply shiftpos_below. inversion i; extlia.\n  apply PTree.elements_correct; auto.\n  auto. auto. auto.\n  inversion INCR0. subst s0; simpl in STKSIZE; extlia.\nQed.\n\nEnd EXPAND_INSTR.\n\nLemma expand_cfg_unchanged:\n  forall fe ctx f s x s' i pc,\n  expand_cfg fe ctx f s = R x s' i ->\n  Ple ctx.(dpc) s.(st_nextnode) ->\n  Plt pc ctx.(dpc) ->\n  s'.(st_code)!pc = s.(st_code)!pc.\nProof.\n  intros fe0; pattern fe0. apply well_founded_ind with (R := ltof _ size_fenv).\n  apply well_founded_ltof.\n  intros. unfold expand_cfg in H0. rewrite unroll_Fixm in H0.\n  eapply expand_cfg_rec_unchanged; eauto. assumption.\nQed.\n\nLemma expand_cfg_spec:\n  forall fe ctx f s x s' i c,\n  expand_cfg fe ctx f s = R x s' i ->\n  fenv_agree fe ->\n  Ple (ctx.(dpc) + max_pc_function f) s.(st_nextnode) ->\n  ctx.(mreg) = max_reg_function f ->\n  Ple (ctx.(dreg) + ctx.(mreg)) s.(st_nextreg) ->\n  ctx.(mstk) >= 0 ->\n  ctx.(mstk) = Z.max (fn_stacksize f) 0 ->\n  (min_alignment (fn_stacksize f) | ctx.(dstk)) ->\n  ctx.(dstk) >= 0 ->\n  s'.(st_stksize) <= stacksize ->\n  (forall pc', Ple ctx.(dpc) pc' -> Plt pc' s'.(st_nextnode) -> c!pc' = s'.(st_code)!pc') ->\n  tr_funbody ctx f c.\nProof.\n  intros fe0; pattern fe0. apply well_founded_ind with (R := ltof _ size_fenv).\n  apply well_founded_ltof.\n  intros. unfold expand_cfg in H0. rewrite unroll_Fixm in H0.\n  eapply expand_cfg_rec_spec; eauto.\n  simpl. intros. eapply expand_cfg_unchanged; eauto. assumption.\nQed.\n\nEnd INLINING_BODY_SPEC.\n\nEnd INLINING_SPEC.\n\n(** ** Relational specification of the translation of a function *)\n\nInductive tr_function: program -> function -> function -> Prop :=\n  | tr_function_intro: forall p fenv f f' ctx,\n      fenv_compat p fenv ->\n      tr_funbody fenv f'.(fn_stacksize) ctx f f'.(fn_code) ->\n      ctx.(dstk) = 0 ->\n      ctx.(retinfo) = None ->\n      f'.(fn_sig) = f.(fn_sig) ->\n      f'.(fn_params) = sregs ctx f.(fn_params) ->\n      f'.(fn_entrypoint) = spc ctx f.(fn_entrypoint) ->\n      0 <= fn_stacksize f' < Ptrofs.max_unsigned ->\n      tr_function p f f'.\n\nLemma tr_function_linkorder:\n  forall cunit prog f f',\n  linkorder cunit prog ->\n  tr_function cunit f f' ->\n  tr_function prog f f'.\nProof.\n  intros. inv H0. econstructor; eauto. eapply fenv_compat_linkorder; eauto.\nQed.\n\nLemma transf_function_spec:\n  forall cunit f f',\n  transf_function (funenv_program cunit) f = OK f' ->\n  tr_function cunit f f'.\nProof.\n  intros. unfold transf_function in H.\n  set (fenv := funenv_program cunit) in *.\n  destruct (expand_function fenv f initstate) as [ctx s i] eqn:?.\n  destruct (zlt (st_stksize s) Ptrofs.max_unsigned); inv H.\n  monadInv Heqr. set (ctx := initcontext x x0 (max_reg_function f) (fn_stacksize f)) in *.\nOpaque initstate.\n  destruct INCR3. inversion EQ1. inversion EQ.\n  apply tr_function_intro with fenv ctx; auto.\n  apply funenv_program_compat.\n  eapply expand_cfg_spec with (fe := fenv); eauto.\n    red; auto.\n    unfold ctx; rewrite <- H1; rewrite <- H2; rewrite <- H3; simpl. extlia.\n    unfold ctx; rewrite <- H0; rewrite <- H1; simpl. extlia.\n    simpl. extlia.\n    simpl. apply Z.divide_0_r.\n    simpl. lia.\n  simpl. lia.\n  simpl. split; auto. destruct INCR2. destruct INCR1. destruct INCR0. destruct INCR.\n  simpl. change 0 with (st_stksize initstate). lia.\nQed.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/backend/Inliningspec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.24531185012717527}}
{"text": "Add LoadPath \"/home/amos/applpi\".\n\nRequire Import libapplpi.\nRequire Import SG_applpi_string.\nRequire Import Coq.FSets.FMapList.\nRequire Import Coq.Strings.String.\nImport ListNotations.\n\nRecord FileSystemState : Set := file_sys_st\n  {fs_st : list (string * list bool)}.\n\n(* Helper func: search offset and return content for FS_Read *)\nFixpoint return_offset (content : list bool) (offset : nat) : option bool :=\n  match offset with\n    | O => match content with (* offset == 0 *)\n             | [] => None\n             | a :: t => Some a\n           end\n    | S rest => match content with (* offset != 0 and keeping searching *)\n                  | [] => None\n                  | a :: t => return_offset t rest\n                 end \n  end.\n\n(* Helper func: search file_name in fs and return content of the offset *)\nFixpoint FS_Read (file_name : string) (offset : nat) \n                   (file_st : list (string * list bool)) : option bool :=\n  match file_st with\n    | nil => None\n    | a::t => match a with (* compare the file_name and keeping searching from fs *)\n             | (s,b) => if string_dec file_name s then return_offset b offset\n                        else FS_Read file_name offset t\n           end\n  end.\n\n(** FS_Read_Main using FS_Read and return_offset *)\nDefinition FS_Read_Main (file_name : string) (offset : nat) \n                          (file_st : FileSystemState) : option bool :=\n  match file_st with\n    | file_sys_st a => FS_Read file_name offset a\n  end.\n\n(* Helper func: search offset and write new content *)\nFixpoint write_content (content : list bool) (offset : nat) \n                         (new_content : bool) : option (list bool) :=\n  match offset with\n    | O => match content with\n             | [] => Some [new_content]\n             | a :: t => Some (new_content :: t) (* write the new content and the rest appends *)\n           end\n    | S rest => match content with\n                  | [] => None (* if the file doesn't have enough sapce, do nothing *)\n                  | a :: t => match write_content t rest new_content with\n                                | None => None\n                                | Some b => Some (a :: b)\n                              end\n                 end \n  end.\n\n(* Helper func: search file_name and offset; then, write the content *)\nFixpoint FS_Write (file_name : string) (offset : nat) (content : bool) \n                    (file_st : list (string * list bool)) : \n                      option (list (string * list bool)) :=\n  match file_st with\n    | nil => None\n    | a::t => match a with\n             | (s,b) => if string_dec file_name s then \n                            match write_content b offset content with\n                              | None => None\n                              | Some a => Some ((s,a)::t)\n                            end\n                        else match FS_Write file_name offset content t with\n                               | None => None\n                               | Some b => Some (a::b)\n                             end\n              end\n  end.\n\n(** FS_Write_Main using FS_Write and write_content *)\nDefinition FS_Write_Main (file_name : string) \n                           (offset : nat) (content : bool) \n                             (file_st : FileSystemState) : option FileSystemState :=\n  match file_st with\n    | file_sys_st a => match FS_Write file_name offset content a with\n                         | None => None\n                         | Some new => Some (file_sys_st new)\n                       end\n  end.\n\n\nFixpoint FS_Create (file_name : string) \n                     (file_st : list (string * list bool)) : \n                       option (list (string * list bool)) :=\n  match file_st with\n    | nil => Some [(file_name,nil)]\n    | hd::tl => match hd with\n                  | (name,content) => if string_dec file_name name then None\n                                      else match FS_Create file_name tl with\n                                             | None => None\n                                             | Some a => Some (hd::a) \n                                           end\n                end \n  end.\n\nDefinition FS_Create_Main (file_name : string) \n                            (file_st : FileSystemState) : \n                              option FileSystemState :=\n  match file_st with\n    | file_sys_st st => match FS_Create file_name st with\n                          | None => None\n                          | Some new => Some (file_sys_st new)\n                        end\n  end.\n\nFixpoint FS_Delete (file_name : string) (file_st : list (string * list bool)) : \n                                                  option (list (string * list bool)) :=\n  match file_st with\n    | nil => None\n    | hd::tl => match hd with\n                  | (name, content) => if string_dec file_name name then Some tl\n                                       else match FS_Delete file_name tl with\n                                              | None => None\n                                              | Some a => Some (hd::a)\n                                            end\n                end\n  end.\n\nDefinition FS_Delete_Main (file_name : string) (file_st : FileSystemState) : option FileSystemState :=\n  match file_st with\n    | file_sys_st st => match FS_Delete file_name st with\n                          | None => None\n                          | Some new => Some (file_sys_st new)\n                        end\n  end.\n\nFixpoint FS_Rename (old_file_name : string) \n                     (new_file_name : string) \n                       (file_st : list (string * list bool)) : \n                         option (list (string * list bool)) :=\n  match file_st with\n    | nil => None\n    | hd::tl => match hd with\n                  | (name, content) => \n                    if string_dec new_file_name name then None (* check duplicate filename *)\n                    else if string_dec old_file_name name then \n                            match FS_Rename old_file_name new_file_name tl with\n                              | None => None\n                              | Some a => Some ((new_file_name, content)::a)\n                            end\n                         else match FS_Rename old_file_name new_file_name tl with\n                                | None => None\n                                | Some a => Some (hd::a)\n                              end\n                end                     \n  end.\n\nDefinition FS_Rename_Main (old_file_name : string) \n                            (new_file_name : string) \n                              (file_st : FileSystemState) : \n                                option FileSystemState :=\n  match file_st with\n    | file_sys_st st => match FS_Rename old_file_name new_file_name st with\n                          | None => None\n                          | Some new => Some (file_sys_st new)\n                        end\n  end.\n\nFixpoint Truncate_Length (new_len : nat) (content : list bool) : option (list bool) :=\n  match new_len with \n    | O => Some []\n    | S rest => match content with\n                  | [] => None\n                  | hd::tl => match Truncate_Length rest tl with\n                                | None => None\n                                | Some new_content => Some (hd::new_content)\n                              end\n                end\n  end.\n\nFixpoint FS_Truncate (file_name : string) (new_len : nat) \n                       (file_st : list (string * list bool)) : \n                         option (list (string * list bool)) :=\n  match file_st with\n    | [] => None\n    | hd::tl => match hd with\n                  | (name, content) => \n                    if string_dec file_name name then \n                       match Truncate_Length new_len content with\n                         | None => None\n                         | Some new_content => Some ((name, new_content)::tl)\n                       end\n                    else match FS_Truncate file_name new_len tl with\n                           | None => None\n                           | Some a => Some (hd::a)\n                         end\n                end\n  end.\n\nDefinition FS_Truncate_Main (file_name : string) (new_len : nat) \n                              (file_st : FileSystemState) : \n                                option FileSystemState :=\n  match file_st with\n    | file_sys_st st => match FS_Truncate file_name new_len st with\n                          | None => None\n                          | Some new => Some (file_sys_st new)\n                        end\n  end.\n\n\nFixpoint Return_List_String (file_st : list (string * list bool)) : list string :=\n  match file_st with\n    | [] => []\n    | hd::tl => match hd with\n                  | (name, content) => (name::Return_List_String tl)\n                end\n  end.\n\n(* retrieve all filenames from the file system *)\nDefinition Return_All_Filename (file_st : FileSystemState) : list string :=\n  match file_st with\n    | file_sys_st st => Return_List_String st\n  end.\n\n(* Proof: write operation doesn't change the existing file name in the file system *)\nLemma Check_Write_Doesnot_Change_Filename : \n        forall file_st file_name offset content, \n          match FS_Write_Main file_name offset content file_st with \n            | None => True (* write fail means always true *)\n            | Some new_st => Return_All_Filename new_st = Return_All_Filename file_st \n          end. (* new and old file names in file system remain the same *)\nintros.                                    (* introduce inductive definition *)\ndestruct file_st.                          (* destruct inductive data type for file_st become fs_st0 *)\nsimpl.                                     (* compute *)\ninduction fs_st0.                          (* instantiate fs_st0 into two cases *)\nsimpl.                                     (* case [] is trivial *)\nauto.                                      (* solve the current goal *)\nsimpl.                                     (* bring FS_Write func in *)\ndestruct a.                                (* pair is also an inductive type *)\ndestruct (string_dec file_name s).         (* instantiate if into two cases *)\ndestruct (write_content l offset content). (* instantiate write_content into its cases *)\nsimpl.                                     (* compute *)\nreflexivity.                               (* equal to *)\nauto.                                      (* solve the current goal *)\ndestruct (FS_Write file_name offset content fs_st0). (* instantiate FS_Write into its cases *)\nsimpl.                                     (* compute *)\nsimpl in IHfs_st0.                         (* in induction, we need to use hypothesis *)\nrewrite IHfs_st0.                          (* apply IHfs_st0 into current goal *)\nreflexivity.                               (* equal to *)\nauto.                                      (* solve the current goal *)\nQed.\n\n(* check new string append to the current list of string *)\nFixpoint New_String_Append (list_string : list string) \n                             (new_string : string) : list string :=\n  match list_string with\n    | [] => [new_string]\n    | hd::tl => hd::New_String_Append tl new_string\n  end.\n\n(* Compare new string to the strings of the list strings in the way of bubble sort *)\nFixpoint Check_StringUnique_List (new_string : string) \n                                   (list_string : list string) : Prop :=\n  match list_string with\n    | [] => True\n    | hd::tl => ~(new_string = hd) /\\ Check_StringUnique_List new_string tl\n  end.\n\n(* check all strings are unique in the list strings *)\nFixpoint Check_AllStringUnique_List (list_string : list string) : Prop :=\n  match list_string with\n    | [] => True\n    | hd::tl => Check_StringUnique_List hd tl /\\ Check_AllStringUnique_List tl\n  end.\n\n(* check all filenames are unique when input is FileSystemState *)\nDefinition Check_Filename_Unique (file_st : FileSystemState) : Prop :=\n  Check_AllStringUnique_List (Return_All_Filename file_st).\n\n(* Proof: write operation doesn't violate the property that all filenames are unique *)\nLemma Check_Write : \n        forall file_st file_name offset content, \n          Check_Filename_Unique file_st -> \n            match FS_Write_Main file_name offset content file_st with \n              | None => True (* write fail means always true *)\n              | Some a => Check_Filename_Unique a\n            end. (* all filenames are unique after write operation *)\nintros.                                                       (* introduce inductive definition *)\ndestruct file_st.                                             (* destruct inductive data type for file_st become fs_st0 *)\nsimpl.                                                        (* go into FS_Write_Main *)\npose Check_Write_Doesnot_Change_Filename.                     (* apply other lemma in this proof *)\nspecialize (y (file_sys_st fs_st0) file_name offset content). (* bring concrete terms for universal quantification of lemma; name new one as y *)\nsimpl in y.                                                   (* compute for y*)\ndestruct (FS_Write file_name offset content fs_st0).          (* instantiate FS_write into its cases *)\nsimpl in y.                                                   (* compute for y *)\nunfold Check_Filename_Unique.                                 (* bring function in *)\nunfold Return_All_Filename.                                   (* can be replaced by simpl *)\nunfold Check_Filename_Unique in H.                            (* bring function in H *)\nunfold Return_All_Filename in H.                              (* can be replace by simpl in H *)\nrewrite y.                                                    (* apply y into our goal *)\nauto.                                                         (* compute *)\nauto.                                                         (* solve the current goal *)\nQed.\n\n(* ref: https://github.com/xu-hao/CertifiedQueryArrow/blob/master/Algebra/Utils.v Line:491 *)\nSection NatListDoubleInductionPrinciple.\n    Variable\n      (T : Type)\n      (P : nat ->  list T  -> Prop)\n      (onil : P 0   nil)\n      (ocons : forall a b, P 0 b -> P 0 (a :: b))\n      (snil : forall b, P b List.nil -> P (S b) List.nil)\n      (scons : forall b c d, P b d -> P (S b) (c :: d)).\n    \n    Fixpoint nat_list_ind_2\n             (l1 : nat) ( l2 : list T) : P l1 l2 :=\n      match l1 in nat return P l1 l2 with\n        | 0 =>\n          (fix h' (l2' : list T) : P 0 l2' :=\n             match l2' with\n               | List.nil => onil\n               | a :: b => ocons a b (h' b)\n             end) l2\n        | S b =>\n          (fix h' (l2' : list T) : P (S b) l2' :=\n             match l2' with\n               | List.nil => snil b (nat_list_ind_2 b nil)\n               | c :: d => scons b c d (nat_list_ind_2 b d)\n             end) l2\n      end\n    .\nEnd NatListDoubleInductionPrinciple.\n\n(* Proof: check written content by write_content is the same as the content returned by return_offset *)\nLemma check_written_content_sameas_newcontent: \n        forall list_content offset content, \n          match write_content list_content offset content with\n            | None => True\n            | Some a => return_offset a offset = Some content\n          end.\nintros.\ngeneralize offset list_content.\nclear list_content offset.\napply nat_list_ind_2.\nsimpl.\nreflexivity.\nintros.\nsimpl.\nauto.\nintros.\nsimpl.\nauto.\nintros.\nsimpl.\ndestruct (write_content d b content).\nsimpl.\nassumption.\nauto.\nQed.\n\n(* Proof: Always read latest written file - \n   A content c, written by write operation to a file_name f with a offset o,\n   is the same as read operation return by reading f with o *)\nLemma Read_After_Write : \n        forall file_st file_name offset content, \n          match FS_Write_Main file_name offset content file_st with \n            | None => True (* write fail means always true *)\n            | Some a => match FS_Read_Main file_name offset a with\n                          | None => True\n                          | Some return_content => return_content = content\n                        end\n          end.\nintros.\ndestruct file_st.\nsimpl.\ninduction fs_st0.\nsimpl.\nauto.\nsimpl.\ndestruct a.\ndestruct (string_dec file_name s).\ndestruct (write_content l offset content) eqn: H.\nsimpl.\ndestruct (string_dec file_name s). (* write_content l offset content = Some l0, match return_offset l0 offset with *)\npose check_written_content_sameas_newcontent.\nspecialize (y l offset content).\nrewrite H in y.\nrewrite y.\nreflexivity.\ncontradiction.\nauto.\ndestruct (FS_Write file_name offset content fs_st0).\nsimpl.\ndestruct (string_dec file_name s).\ncontradiction.\nassumption.\nauto.\nQed.\n\n(* Proof: truncate operation doesn't change the existing file name in the file system *)\nLemma Truncate_Doesnot_Change_Filename : \n        forall file_st file_name length, \n          match FS_Truncate_Main file_name length file_st with \n            | None => True (* truncate fail means always true *)\n            | Some new_st => Return_All_Filename new_st = Return_All_Filename file_st \n          end. (* new and old file names in file system remain the same *)\nintros.\ndestruct file_st.\nsimpl.\ninduction fs_st0.\nsimpl.\nauto.\nsimpl.\ndestruct a.\ndestruct (string_dec file_name s).\ndestruct (Truncate_Length length l).\nsimpl.\nreflexivity.\nauto.\ndestruct (FS_Truncate file_name length fs_st0).\nsimpl.\nsimpl in IHfs_st0.\nrewrite IHfs_st0.\nreflexivity.\nauto.\nQed.\n\n(* Proof: truncate operation doesn't violate the property that all filenames are unique *)\nLemma Check_Truncate : \n        forall file_st file_name length, \n          Check_Filename_Unique file_st -> \n            match FS_Truncate_Main file_name length file_st with \n              | None => True (* truncate fail means always true *)\n              | Some a => Check_Filename_Unique a\n            end. (* all filenames are unique after write operation *)\nintros.\ndestruct file_st.\nsimpl.\npose Truncate_Doesnot_Change_Filename.\nspecialize (y (file_sys_st fs_st0) file_name length).\nsimpl in y.\ndestruct (FS_Truncate file_name length fs_st0).\nsimpl in y.\nunfold Check_Filename_Unique.\nunfold Return_All_Filename.\nunfold Check_Filename_Unique in H.\nunfold Return_All_Filename in H.\nrewrite y.\nauto.\nauto.\nQed.\n\n(* Proof: create operation always append new filename in the end *)\nLemma Check_Create_Append: \n        forall file_st file_name, \n          match FS_Create_Main file_name file_st with\n            | None => True (* create fail means always true *)\n            | Some new_st => \n                New_String_Append (Return_All_Filename file_st) file_name = Return_All_Filename new_st\n          end. (* new and old file names in file system remain the same *)\nintros.                                (* introduce inductive definition *)\ndestruct file_st.                      (* destruct inductive data type for file_st become fs_st0 *)\nsimpl.                                 (* compute *)\ninduction fs_st0.                      (* instantiate fs_st0 into two cases *)\nsimpl.                                 (* case [] is trivial *)\nreflexivity.                           (* equal to *)\nsimpl.                                 (* go into FS_Create *)\ndestruct a.                            (* pair is also an inductive type *)\ndestruct (string_dec file_name s).     (* instantiate if into two cases *)\nauto.                                  (* solve the current goal *)\ndestruct (FS_Create file_name fs_st0). (* instantiate FS_Create into its cases *)\nsimpl.                                 (* compute *)\nsimpl in IHfs_st0.                     (* in induction, we need to use hypothesis *)\nrewrite IHfs_st0.                      (* apply IHfs_st0 into current goal *)\nreflexivity.                           (* equal to *)\nauto.                                  (* solve the current goal *)\nQed.\n\n(* Proof: create operation always create unique filename in the existing file system *)\nLemma Create_UniqueOne_inFileSys : \n        forall file_st file_name, \n          match FS_Create_Main file_name file_st with \n            | None => True (* truncate fail means always true *)\n            | Some a => Check_StringUnique_List file_name (Return_All_Filename file_st)\n          end. (* all filenames are unique after create operation *)\nintros.\ndestruct file_st.\nsimpl.\ninduction fs_st0.\nsimpl.\nauto.\nsimpl.\ndestruct a.\ndestruct (string_dec file_name s).\nauto.\ndestruct (FS_Create file_name fs_st0).\nsimpl.\nsplit.\nauto.\napply IHfs_st0.\nauto.\nQed.\n\n(* Proof: created file is always append and unique *)\nLemma Create_File_AppendUnique : \n        forall file_st file_name, \n          match FS_Create_Main file_name file_st with\n            | None => True (* truncate fail means always true *)\n            | Some new_st => \n                Check_StringUnique_List file_name (Return_All_Filename file_st) /\\ \n                New_String_Append (Return_All_Filename file_st) file_name = Return_All_Filename new_st\n          end. (* all filenames are unique after create operation *)\nintros.\npose Check_Create_Append.\nspecialize (y file_st file_name).\npose Create_UniqueOne_inFileSys.\nspecialize (y0 file_st file_name).\ndestruct (FS_Create_Main file_name file_st).\ntauto.\nauto.\nQed.\n\n(* Proof: New_String_Append func doesn't violate the property that all strings are unique *)\n(* 1. The new string is diffent from any string in the esisting string list *)\n(* 2. The strings in the existing string list are unique *)\nLemma Check_CreatedString : \n        forall old_string_list file_name, \n          Check_StringUnique_List file_name old_string_list ->\n            Check_AllStringUnique_List old_string_list -> \n              Check_AllStringUnique_List (New_String_Append old_string_list file_name).                                  \nintros.                                 (* introduce inductive definition *)\ninduction old_string_list.              (* instantiate old_string_list into two cases *)\nsimpl.                                  \ntauto.                                  (* prove true *)\nsimpl.                                  \nsimpl in H.                             \nsimpl in H0.                            \nsplit.                                  (* split goal into two cases *)\ndestruct H0.                            (* break H0 down *)\ndestruct H.                             (* break H down *)\nclear H1 H2 IHold_string_list.          (* clear hypothesis, but why? *)\ninduction old_string_list.              (* instantiate old_string_list into two cases *)\nsimpl.                                  \nsplit.                                  (* split goal into two cases *)\nintro.                                  (* same as hypothesis *)\napply H.                                \nsymmetry.                               (* form t = u to u = t *)\nassumption.                             (* type is equal to the goal *)\nauto.                                   \nsimpl.                                  \nsimpl in H0.                            \ndestruct H0.                            (* break H0 down *)\nsplit.                                  (* split goal into two cases *)\nassumption.                             (* type is equal to the goal *)\napply IHold_string_list.                (* become the precondition *)\nassumption.                             (* type is equal to the goal, H1 *)\napply IHold_string_list.                (* become the precondition *)\ntauto.                                  \ntauto.                                  \nQed.   \n\n(* Proof: create operation doesn't violate the property that all filenames are unique *)\nLemma Check_Create : \n        forall file_st file_name, \n          Check_Filename_Unique file_st -> \n            match FS_Create_Main file_name file_st with\n              | None => True (* truncate fail means always true *)\n              | Some new_st => Check_AllStringUnique_List (Return_All_Filename new_st)\n            end. (* all filenames are unique after create operation *)\nintros.\npose Create_File_AppendUnique.\nspecialize (y file_st file_name).\ndestruct (FS_Create_Main file_name file_st).\ndestruct y.\nrewrite <- H1.\napply Check_CreatedString.\nassumption.\nassumption.\nauto.\nQed.\n\n\n(* delete a string from the current list of string *)\nFixpoint Delete_String_List (list_string : list string) (delete_name : string) : list string :=\n  match list_string with\n    | [] => []\n    | hd::tl => if string_dec delete_name hd then tl\n                                             else hd::Delete_String_List tl delete_name\n  end.\n\n(* Proof: delete operation doesn't change the existing file name in the file system *)\nLemma Delete_Doesnot_Change_Filename : \n        forall file_st file_name, \n          match FS_Delete_Main file_name file_st with\n            | None => True (* delete fail means always true *)\n            | Some new_st => \n                Delete_String_List (Return_All_Filename file_st) file_name = Return_All_Filename new_st\n          end. (* rest filenames doesn't change  *)\nintros.\ndestruct file_st.\nsimpl.\ninduction fs_st0.\nsimpl.\nauto.\nsimpl.\ndestruct a.\nsimpl.\ndestruct (string_dec file_name s).\nreflexivity.\ndestruct (FS_Delete file_name fs_st0).\nrewrite IHfs_st0.\nreflexivity.\nauto.\nQed.\n\n(* Proof: after deleting one string from the string list, the rest strings of the string list are unique *)\nLemma StringUnique_AfterDeleteOneString : \n        forall old_string_list file_name delete_name, \n          Check_StringUnique_List file_name old_string_list ->\n            Check_StringUnique_List file_name (Delete_String_List old_string_list delete_name).\nintros.\ninduction old_string_list.\nsimpl.\nauto.\nsimpl.\ndestruct (string_dec file_name a).\ndestruct (string_dec delete_name a).\nsimpl in H.\ndestruct H.\nassumption.\nsimpl.\nsplit.\nsimpl in H.\ndestruct H.\nassumption.\napply IHold_string_list.\nsimpl in H.\ndestruct H.\nassumption.\ndestruct (string_dec delete_name a).\nsimpl in H.\ndestruct H.\nassumption.\nsimpl.\nsplit.\nsimpl in H.\ndestruct H.\nassumption.\napply IHold_string_list.\nsimpl in H.\ndestruct H.\nassumption.\nQed.\n\n(* Proof: a list of string still unique after delete one string *)\nLemma StringsUnique_AfterDelete : \n        forall old_string_list file_name, \n          Check_AllStringUnique_List old_string_list ->\n            Check_AllStringUnique_List (Delete_String_List old_string_list file_name).\nintros.\ninduction old_string_list.\nsimpl.\nauto.\nsimpl.\ndestruct (string_dec file_name a).\nsimpl in H.\ndestruct H.\nassumption.\nsimpl.\nsplit.\nsimpl in H.\ndestruct H.\napply StringUnique_AfterDeleteOneString.\nassumption.\napply IHold_string_list.\nsimpl in H.\ndestruct H.\nassumption.\nQed.\n\n(* Proof: delete operation doesn't violate the property that all filenames are unique *)\nLemma Check_Delete : \n        forall file_st file_name, \n          Check_Filename_Unique file_st -> \n            match FS_Delete_Main file_name file_st with\n              | None => True (* truncate fail means always true *)\n              | Some new_st => Check_AllStringUnique_List (Return_All_Filename new_st)\n            end. (* all filenames are unique after delete operation *)\nintros.\npose Delete_Doesnot_Change_Filename.\nspecialize (y file_st file_name).\ndestruct (FS_Delete_Main file_name file_st).\nrewrite <- y.\napply StringsUnique_AfterDelete.\nassumption.\nauto.\nQed.\n\n\n(* rename a string from the current list of string *)\nFixpoint Rename_aString_inList (old_name : string) (new_name : string) \n                                                   (list_string : list string) : list string :=\n  match list_string with\n    | [] => []\n    | hd::tl => if string_dec new_name hd then hd::tl (* check the duplicate string *)\n                else if string_dec old_name hd then new_name::(Rename_aString_inList old_name new_name tl)\n                else hd::Rename_aString_inList old_name new_name tl\n  end.\n\n(* Proof: rename operation doesn't change the other original file name in the file system *)\nLemma Rename_Doesnot_Change_Filename : \n        forall old_name new_name file_st, \n          match FS_Rename_Main old_name new_name file_st with\n            | None => True (* delete fail means always true *)\n            | Some new_st => \n                Rename_aString_inList old_name new_name (Return_All_Filename file_st) = \n                                                                        Return_All_Filename new_st\n          end. (* the other filenames doesn't change  *)\nintros.\ndestruct file_st.\nsimpl.\ninduction fs_st0.\nsimpl.\nauto.\nsimpl.\ndestruct a.\ndestruct (string_dec new_name s).\nauto.\ndestruct (string_dec old_name s).\ndestruct (FS_Rename old_name new_name fs_st0) eqn:?. (* destruct term but left term's relation *)\nsimpl in IHfs_st0.\nsimpl.\ndestruct (string_dec new_name s).\ncontradiction.                                       (* new_name <> s && new_name = s *)\ndestruct (string_dec old_name s).\nrewrite IHfs_st0.\nreflexivity.\ncontradiction.\nauto.\ndestruct (FS_Rename old_name new_name fs_st0).\nsimpl.\ndestruct (string_dec new_name s).\ncontradiction.\ndestruct (string_dec old_name s).\ncontradiction.\nsimpl in IHfs_st0.\nrewrite <- IHfs_st0.\nreflexivity.\nauto.\nQed.\n\n(* Proof: The NewName of the rename operation is different from the string lists *)\nLemma NewName_isUnique : \n        forall file_st old_name new_name, \n          Check_Filename_Unique file_st -> \n            match FS_Rename_Main old_name new_name file_st with\n              | None => True (* rename fail means always true *)\n              | Some new_st => Check_StringUnique_List new_name (Return_All_Filename file_st)\n            end.\nintros.\ndestruct file_st.\nsimpl.\ninduction fs_st0.\nsimpl.\nauto.\nsimpl.\ndestruct a.\ndestruct (string_dec new_name s).\nauto.\ndestruct (string_dec old_name s).\ndestruct (FS_Rename old_name new_name fs_st0).\nsimpl.\nsplit.\nassumption.\napply IHfs_st0.\nunfold Check_Filename_Unique.\nunfold Check_Filename_Unique in H.\nsimpl in H.\ndestruct H.\nassumption.\nauto.\ndestruct (FS_Rename old_name new_name fs_st0).\nsimpl.\nsplit.\nassumption.\napply IHfs_st0.\nunfold Check_Filename_Unique.\nunfold Check_Filename_Unique in H.\nsimpl in H.\ndestruct H.\nassumption.\nauto.\nQed.\n\n(* rename a string from the current list of string, but has different form; it's v2 *)\nFixpoint Rename_aString_inList_v2 (old_name : string) (new_name : string) (list_string : list string) \n                                                      {struct list_string}: list string :=\n  match list_string with\n    | [] => []\n    | hd::tl => if string_dec new_name hd then hd::tl (* check the duplicate string *)\n                else if string_dec old_name hd then new_name::tl\n                else hd::Rename_aString_inList_v2 old_name new_name tl\n  end.\n\n(* If the new_name and old_name don't match each other, the string_list remains the same *)\nLemma RenamedNames_NotMatch : \n        forall old_name new_name string_list, \n          Check_StringUnique_List old_name string_list -> \n            Rename_aString_inList old_name new_name string_list = string_list.\nintros.\ninduction string_list.\nreflexivity.\nsimpl.\ndestruct H.\ndestruct (string_dec new_name a).\nreflexivity.\ndestruct (string_dec old_name a).\ncontradiction.\nrewrite IHstring_list.\nreflexivity.\nassumption.\nQed.\n\n(* Proof: Rename_aString_inList v1 and v2 behave the same *)\nLemma Rename_Version_Equal : \n        forall old_name new_name string_list, \n          Check_AllStringUnique_List string_list ->\n            Check_StringUnique_List new_name string_list ->\n              Rename_aString_inList old_name new_name string_list = \n                                    Rename_aString_inList_v2 old_name new_name string_list.\nintros.\ninduction string_list.\nreflexivity.\nsimpl.\nsimpl in H.\nsimpl in H0.\ndestruct (string_dec new_name a).\ndestruct H0.\ncontradiction.\ndestruct (string_dec old_name a). (*Check_StringUnique_List old_name string_list -> Rename_aString_inList old_name new_name string_list = string_list*)\nrewrite RenamedNames_NotMatch.\nreflexivity.\nrewrite e.\ndestruct H.\nauto.\nrewrite IHstring_list.\nreflexivity.\ntauto.\ntauto.\nQed.\n\n(* Proof: after renaming old_name to new_name, unique_name is still unique *)\nLemma rename_neq_unique : \n        forall unique_name old_name new_name string_list, \n          unique_name <> new_name -> \n            Check_StringUnique_List unique_name string_list -> \n              Check_StringUnique_List unique_name (Rename_aString_inList_v2 old_name new_name string_list).\nintros.\ninduction string_list.\nsimpl.\nauto.\nsimpl.\nsimpl in H0.\ndestruct H0.\ndestruct (string_dec new_name a).\nrewrite <- e.\nsimpl. \ntauto.\ndestruct (string_dec old_name a).\nsimpl.\ntauto.\nsimpl. \ntauto.\nQed.\n\n(* All strings are unique after rename old_name to new_name in the list of strings *)\nLemma AllString_Unique_AfterRenameAString : \n        forall file_st old_name new_name, \n          Check_Filename_Unique file_st -> \n            match FS_Rename_Main old_name new_name file_st with\n              | None => True (* rename fail means always true *)\n              | Some new_st => \n                  Check_AllStringUnique_List (Rename_aString_inList old_name new_name (Return_All_Filename file_st))\n            end.\nintros.\npose NewName_isUnique.\nspecialize (y file_st old_name new_name).\ndestruct (FS_Rename_Main old_name new_name file_st).\nrewrite Rename_Version_Equal.\ndestruct file_st.\nsimpl.\nspecialize (y H).\nsimpl in y.\ninduction fs_st0.\nsimpl.\nauto.\nsimpl.\ndestruct a.\nunfold Check_Filename_Unique in H.\nsimpl in H.\nsimpl.\ndestruct (string_dec new_name s).\nauto.\ndestruct (string_dec old_name s).\nsimpl.\nsplit.\nsimpl in y.\ntauto.\ndestruct H.\nassumption.\ndestruct H.\nsimpl.\nsplit.\napply rename_neq_unique.\nintros.\nintro.\napply n.\nsymmetry.\nassumption.\nassumption.\napply IHfs_st0.\nassumption.\ndestruct y.\nassumption.\nauto.\nauto.\nauto.\nQed.\n\n(* Proof: rename operation doesn't violate the property that all filenames are unique *)\n(*Lemma Check_Rename : \n          forall file_st old_name new_name, \n            Check_Filename_Unique file_st -> \n              match FS_Rename_Main old_name new_name file_st with\n                | None => True (* rename fail means always true *)\n                | Some new_st => Check_AllStringUnique_List (Return_All_Filename new_st)\n              end. (* all filenames are unique after rename operation *)\nintros.\npose Rename_Doesnot_Change_Filename.\nspecialize (y old_name new_name file_st).\ndestruct (FS_Rename_Main old_name new_name file_st).\nrewrite <- y.\npose AllString_Unique_AfterRenameAString.\nspecialize (y0 file_st old_name new_name).\ndestruct (FS_Rename_Main old_name new_name file_st).\napply y0.\nassumption.\n\n\ndestruct f.\nsimpl.\ndestruct file_st.\nsimpl in H.*)\n\n", "meta": {"author": "ChunKunWang", "repo": "syndicate-core-logic", "sha": "3e9fa11ca16868fee74737986d0de3946c03162e", "save_path": "github-repos/coq/ChunKunWang-syndicate-core-logic", "path": "github-repos/coq/ChunKunWang-syndicate-core-logic/syndicate-core-logic-3e9fa11ca16868fee74737986d0de3946c03162e/SG_fs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2453118435562797}}
{"text": "(* Instantiation *)\n(* see https://webassembly.github.io/spec/core/exec/modules.html#exec-instantiation *)\n(* (C) J. Pichon, M. Bodin - see LICENSE.txt *)\n\nFrom mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq.\nFrom ITree Require Import ITree.\nFrom ITree Require ITreeFacts.\nFrom Wasm Require Import list_extra datatypes datatypes_properties\n                         interpreter binary_format_parser operations\n                         typing opsem type_checker memory memory_list.\nFrom Coq Require Import BinNat.\n\n(* TODO: Documentation *)\n\n(* TODO: separate algorithmic aspects from specification, incl. dependencies *)\n\n(* TODO: get rid of old notation that doesn't follow standard *)\n\nSection Host.\n\nVariable host_function : eqType.\nLet host := host host_function.\n\nVariable host_instance : host.\n\nLet store_record_eq_dec := @store_record_eq_dec host_function.\nLet store_record_eqType := @store_record_eqType host_function.\n\n(* Before adding a canonical structure to [name], we save the base one to ensure better extraction. *)\nLocal Canonical Structure name_eqType := Eval hnf in EqType name (seq_eqMixin _).\n\nLet store_record := store_record host_function.\n(*Let administrative_instruction := administrative_instruction host_function.*)\nLet host_state := host_state host_instance.\n\nLet executable_host := executable_host host_function.\nVariable executable_host_instance : executable_host.\nLet host_event := host_event executable_host_instance.\n\nContext {eff : Type -> Type}.\nContext {eff_has_host_event : host_event -< eff}.\n\nLet run_v {eff' eff'_has_host_event} :=\n  @interpreter.run_v _ executable_host_instance eff' eff'_has_host_event.\n\nDefinition addr := nat.\nDefinition funaddr := addr.\nDefinition tableaddr := addr.\nDefinition memaddr := addr.\nDefinition globaladdr := addr.\n\nDefinition alloc_Xs {A B} f (s : store_record) (xs : list A) : store_record * list B :=\n  let '(s', fas) :=\n    List.fold_left\n      (fun '(s, ys) x =>\n        let '(s', y) := f s x in\n        (s', y :: ys))\n        xs\n        (s, nil) in\n  (s', List.rev fas).\n\nInductive externval : Type :=\n| ev_func : funaddr -> externval\n| ev_table : tableaddr -> externval\n| ev_mem : memaddr -> externval\n| ev_global : globaladdr -> externval.\n\nDefinition funcs_of_externals (evs : list externval) : list addr :=\n  seq.pmap (fun ev => match ev with | ev_func fa => Some fa | _ => None end) evs.\n\nDefinition tables_of_externals (evs : list externval) : list addr :=\n  seq.pmap (fun ev => match ev with | ev_table ta => Some ta | _ => None end) evs.\n\nDefinition mems_of_externals (evs : list externval) : list addr :=\n  seq.pmap (fun ev => match ev with | ev_mem ta => Some ta | _ => None end) evs.\n\nDefinition globals_of_externals (evs : list externval) : list addr :=\n  seq.pmap (fun ev => match ev with | ev_global ta => Some ta | _ => None end) evs.\n\nDefinition add_func (s : store_record) funcinst := {|\n  s_funcs := List.app s.(s_funcs) [::funcinst];\n  s_tables := s.(s_tables);\n  s_mems := s.(s_mems);\n  s_globals := s.(s_globals);\n|}.\n\nDefinition alloc_func (s : store_record) (m_f : module_func) (mi : instance) : store_record * funcidx :=\n  let funcaddr := List.length s.(s_funcs) in\n  let functype := List.nth (match m_f.(modfunc_type) with | Mk_typeidx n => n end) mi.(inst_types) (Tf nil nil (* TODO: partiality problem *) ) in\n  let funcinst := FC_func_native mi functype m_f.(modfunc_locals) m_f.(modfunc_body) in\n  let S' := add_func s funcinst in\n  (S', Mk_funcidx funcaddr).\n\nDefinition alloc_funcs (s : store_record) (m_fs : list module_func) (mi : instance) : store_record * list funcidx :=\n  alloc_Xs (fun s m_f => alloc_func s m_f mi) s m_fs.\n\nDefinition add_table (s : store_record) (ti : tableinst) : store_record := {|\n  s_funcs := s.(s_funcs);\n  s_tables := List.app s.(s_tables) [::ti];\n  s_mems := s.(s_mems);\n  s_globals := s.(s_globals);\n|}.\n\nDefinition alloc_tab (s : store_record) (tty : table_type) : store_record * tableidx :=\n  let '{| tt_limits := {| lim_min := min; lim_max := maxo |} as lim; tt_elem_type := ety |} := tty in\n  let tableaddr := Mk_tableidx (List.length s.(s_tables)) in\n  let tableinst := {|\n    table_data := (List.repeat None min);\n    table_max_opt := maxo;\n  |} in\n  (add_table s tableinst, tableaddr).\n\nDefinition alloc_tabs (s : store_record) (ts : list table_type) : store_record * list tableidx :=\n  alloc_Xs alloc_tab s ts.\n\nDefinition mem_mk (lim : limits) : memory :=\n  let len := BinNatDef.N.mul page_size lim.(lim_min) in\n  {| mem_data := mem_make Integers.Byte.zero len;\n    mem_max_opt := lim.(lim_max);\n  |}.\n\nDefinition add_mem (s : store_record) (m_m : memory) : store_record := {|\n  s_funcs := s.(s_funcs);\n  s_tables := s.(s_tables);\n  s_mems := List.app s.(s_mems) [::m_m];\n  s_globals := s.(s_globals);\n|}.\n\nDefinition alloc_mem (s : store_record) (m_m : memory_type) : store_record * memidx :=\n  let '{| lim_min := min; lim_max := maxo |} := m_m in\n  let memaddr := Mk_memidx (List.length s.(s_mems)) in\n  let meminst := mem_mk m_m in\n  (add_mem s meminst, memaddr).\n\nDefinition alloc_mems (s : store_record) (m_ms : list memory_type) : store_record * list memidx :=\n  alloc_Xs alloc_mem s m_ms.\n\nDefinition add_glob (s : store_record) (m_g : global) : store_record := {|\n  s_funcs := s.(s_funcs);\n  s_tables := s.(s_tables);\n  s_mems := s.(s_mems);\n  s_globals := List.app s.(s_globals) [::m_g];\n|}.\n\nDefinition alloc_glob (s : store_record) (m_g_v : module_glob * value) : store_record * globalidx :=\n  let '(m_g, v) := m_g_v in\n  let globaddr := Mk_globalidx (List.length s.(s_globals)) in\n  let globinst := Build_global m_g.(modglob_type).(tg_mut) v in\n  (add_glob s globinst, globaddr).\n\nDefinition alloc_globs s m_gs vs :=\n  alloc_Xs alloc_glob s (List.combine m_gs vs).\n\n(* TODO: lemmas *)\n\nDefinition v_ext := module_export_desc.\n\nDefinition export_get_v_ext (inst : instance) (exp : module_export_desc) : v_ext :=\n  (* we circumvent partiality by providing 0 as a default *)\n  match exp with\n  | MED_func (Mk_funcidx i) => MED_func (Mk_funcidx (List.nth i inst.(inst_funcs) 0))\n  | MED_table (Mk_tableidx i) => MED_table (Mk_tableidx (List.nth i inst.(inst_tab) 0))\n  | MED_mem (Mk_memidx i) => MED_mem (Mk_memidx (List.nth i inst.(inst_memory) 0))\n  | MED_global (Mk_globalidx i) => MED_global (Mk_globalidx (List.nth i inst.(inst_globs) 0))\n  end.\n\nDefinition ext_funcs :=\n  seq.pmap\n    (fun x =>\n      match x with\n      | MED_func i => Some i\n      | _ => None\n      end).\n\nDefinition ext_tabs :=\n  seq.pmap\n    (fun x =>\n      match x with\n      | MED_table i => Some i\n      | _ => None\n      end).\n\nDefinition ext_mems :=\n  seq.pmap\n    (fun x =>\n      match x with\n      | MED_mem i => Some i\n      | _ => None\n      end).\n\nDefinition ext_globs :=\n  seq.pmap\n    (fun x =>\n      match x with\n      | MED_global i => Some i\n      | _ => None\n      end).\n\nDefinition ext_t_funcs :=\n  seq.pmap\n    (fun x =>\n      match x with\n      | ET_func tf => Some tf\n      | _ => None\n      end).\n\nDefinition ext_t_tabs :=\n  seq.pmap\n    (fun x =>\n      match x with\n      | ET_tab i => Some i\n      | _ => None\n      end).\n\nDefinition ext_t_mems :=\n  seq.pmap\n    (fun x =>\n      match x with\n      | ET_mem i => Some i\n      | _ => None\n      end).\n\nDefinition ext_t_globs :=\n  seq.pmap\n    (fun x =>\n      match x with\n      | ET_glob i => Some i\n      | _ => None\n      end).\n\nDefinition alloc_module (s : store_record) (m : module) (imps : list v_ext) (gvs : list value)\n    (s'_inst_exps : store_record * instance * seq module_export) : bool :=\n  let '(s'_goal, inst, exps) := s'_inst_exps in\n  let '(s1, i_fs) := alloc_funcs s m.(mod_funcs) inst in\n  let '(s2, i_ts) := alloc_tabs s1 (List.map (fun t => t.(modtab_type)) m.(mod_tables)) in\n  let '(s3, i_ms) := alloc_mems s2 m.(mod_mems) in\n  let '(s', i_gs) := alloc_globs s3 m.(mod_globals) gvs in\n  (s'_goal == s') &&\n  (inst.(inst_types) == m.(mod_types)) &&\n  (inst.(inst_funcs) == List.map (fun '(Mk_funcidx i) => i) (List.app (ext_funcs imps) i_fs)) &&\n  (inst.(inst_tab) == List.map (fun '(Mk_tableidx i) => i) (List.app (ext_tabs imps) i_ts)) &&\n  (inst.(inst_memory) == List.map (fun '(Mk_memidx i) => i) (List.app (ext_mems imps) i_ms)) &&\n  (inst.(inst_globs) == List.map (fun '(Mk_globalidx i) => i) (List.app (ext_globs imps) i_gs)) &&\n  (exps == (List.map (fun m_exp => {| modexp_name := m_exp.(modexp_name); modexp_desc := (export_get_v_ext inst m_exp.(modexp_desc)) |}) m.(mod_exports) : seq module_export)).\n\nDefinition interp_alloc_module (s : store_record) (m : module) (imps : list v_ext) (gvs : list value) : (store_record * instance * list module_export) :=\n  let i_fs := List.map (fun i => Mk_funcidx i) (seq.iota (List.length s.(s_funcs)) (List.length m.(mod_funcs))) in\n  let i_ts := List.map (fun i => Mk_tableidx i) (seq.iota (List.length s.(s_tables)) (List.length m.(mod_tables))) in\n  let i_ms := List.map (fun i => Mk_memidx i) (seq.iota (List.length s.(s_mems)) (List.length m.(mod_mems))) in\n  let i_gs := List.map (fun i => Mk_globalidx i) (seq.iota (List.length s.(s_globals)) (min (List.length m.(mod_globals)) (List.length gvs))) in\n  let inst := {|\n    inst_types := m.(mod_types);\n    inst_funcs := List.map (fun '(Mk_funcidx i) => i) (List.app (ext_funcs imps) i_fs);\n    inst_tab := List.map (fun '(Mk_tableidx i) => i) (List.app (ext_tabs imps) i_ts);\n    inst_memory := List.map (fun '(Mk_memidx i) => i) (List.app (ext_mems imps) i_ms);\n    inst_globs := List.map (fun '(Mk_globalidx i) => i) (List.app (ext_globs imps) i_gs);\n  |} in\n  let '(s1, _) := alloc_funcs s m.(mod_funcs) inst in\n  let '(s2, _) := alloc_tabs s1 (List.map (fun t => t.(modtab_type)) m.(mod_tables)) in\n  let '(s3, _) := alloc_mems s2 m.(mod_mems) in\n  let '(s', _) := alloc_globs s3 m.(mod_globals) gvs in\n  let exps := List.map (fun m_exp => {| modexp_name := m_exp.(modexp_name); modexp_desc := export_get_v_ext inst m_exp.(modexp_desc) |}) m.(mod_exports) in\n  (s', inst, exps).\n\n(* TODO: lemmas *)\n\nDefinition insert_at {A} (v : A) (n : nat) (l : list A) : list A :=\nList.app (List.firstn n l) (List.app [::v] (List.skipn (n + 1) l)).\n\nDefinition dummy_table := {| table_data := nil; table_max_opt := None; |}.\n\nDefinition init_tab (s : store_record) (inst : instance) (e_ind : nat) (e : module_element) : store_record :=\n  let t_ind := List.nth (match e.(modelem_table) with Mk_tableidx i => i end) inst.(inst_tab) 0 in\n  let '{|table_data := tab_e; table_max_opt := maxo |} := List.nth t_ind s.(s_tables) dummy_table in\n  let e_pay := List.map (fun i => List.nth_error inst.(inst_funcs) (match i with Mk_funcidx j => j end)) e.(modelem_init) in\n  let tab'_e := List.app (List.firstn e_ind tab_e) (List.app e_pay (List.skipn (e_ind + length e_pay) tab_e)) in\n  {| s_funcs := s.(s_funcs);\n     s_tables := insert_at {| table_data := tab'_e; table_max_opt := maxo |} t_ind s.(s_tables);\n     s_mems := s.(s_mems);\n     s_globals := s.(s_globals) |}.\n\nDefinition init_tabs (s : store_record) (inst : instance) (e_inds : list nat) (es : list module_element) : store_record :=\n  List.fold_left (fun s' '(e_ind, e) => init_tab s' inst e_ind e) (List.combine e_inds es) s.\n\nDefinition dummy_data_vec :=\n  mem_make Integers.Byte.zero (N.zero).\n\nDefinition dummy_mem := {|\n  mem_data := dummy_data_vec;\n  mem_max_opt := None\n|}.\n\nDefinition init_mem (s : store_record) (inst : instance) (d_ind : N) (d : module_data) : store_record :=\n  let m_ind := List.nth (match d.(moddata_data) with Mk_memidx i => i end) inst.(inst_memory) 0 in\n  let mem := List.nth m_ind s.(s_mems) dummy_mem in\n  let d_pay := List.map bytes.compcert_byte_of_byte d.(moddata_init) in\n  let mem'_e := List.app (List.firstn d_ind mem.(mem_data).(ml_data)) (List.app d_pay (List.skipn (d_ind + length d_pay) mem.(mem_data).(ml_data))) in\n  let mems' := insert_at {| mem_data := {| ml_data := mem'_e; ml_init := #00 |}; mem_max_opt := mem.(mem_max_opt) |} m_ind s.(s_mems) in\n  {| s_funcs := s.(s_funcs);\n     s_tables := s.(s_tables);\n     s_mems := mems';\n     s_globals := s.(s_globals); |}.\n\nDefinition init_mems (s : store_record) (inst : instance) (d_inds : list N) (ds : list module_data) : store_record :=\n  List.fold_left (fun s' '(d_ind, d) => init_mem s' inst d_ind d) (List.combine d_inds ds) s.\n\nDefinition module_func_typing (c : t_context) (m : module_func) (tf : function_type) : Prop :=\n  let '{| modfunc_type := Mk_typeidx i; modfunc_locals := t_locs; modfunc_body := b_es |} := m in\n  let '(Tf tn tm) := tf in\n  i < List.length c.(tc_types_t) /\\\n  List.nth i c.(tc_types_t) (Tf nil nil) == tf /\\\n  let c' := {|\n    tc_types_t := c.(tc_types_t);\n    tc_func_t := c.(tc_func_t);\n    tc_global := c.(tc_global);\n    tc_table := c.(tc_table);\n    tc_memory := c.(tc_memory);\n    tc_local := c.(tc_local) ++ tn ++ t_locs;\n    tc_label := tm :: c.(tc_label);\n    tc_return := Some tm;\n  |} in\n  typing.be_typing c' b_es (Tf [::] tm).\n\nDefinition limit_typing (lim : limits) (k : N) : bool :=\n  let '{| lim_min := min; lim_max := maxo |} := lim in\n  (N.leb k (N.pow 2 32)) &&\n  (match maxo with None => true | Some max => N.leb max k end) &&\n  (match maxo with None => true | Some max => N.leb min k end).\n\nDefinition module_tab_typing (t : module_table) : bool :=\n  limit_typing t.(modtab_type).(tt_limits) (N.pow 2 32).\n\nDefinition module_mem_typing (m : memory_type) : bool :=\n  limit_typing m (N.pow 2 32).\n\nDefinition const_expr (c : t_context) (b_e : basic_instruction) : bool :=\n  match b_e with\n  | BI_const _ => true\n  | BI_get_global k =>\n    (k < length c.(tc_global)) &&\n    match List.nth_error c.(tc_global) k with\n    | None => false\n    | Some t => t.(tg_mut) == MUT_immut\n    end\n  | _ => false\n  end.\n\nDefinition const_exprs (c : t_context) (es : list basic_instruction) : bool :=\n  seq.all (const_expr c) es.\n\nDefinition module_glob_typing (c : t_context) (g : module_glob) (tg : global_type) : Prop :=\n  let '{| modglob_type := tg'; modglob_init := es |} := g in\n  const_exprs c es /\\\n  tg = tg' /\\\n  typing.be_typing c es (Tf nil [::tg.(tg_t)]).\n\nDefinition module_elem_typing (c : t_context) (e : module_element) : Prop :=\n  let '{| modelem_table := Mk_tableidx t; modelem_offset := es; modelem_init := is_ |} := e in\n  const_exprs c es /\\\n  typing.be_typing c es (Tf nil [::T_i32]) /\\\n  t < List.length c.(tc_table) /\\\n  seq.all (fun '(Mk_funcidx i) => i < List.length c.(tc_func_t)) is_.\n\nDefinition module_data_typing (c : t_context) (m_d : module_data) : Prop :=\n  let '{| moddata_data := Mk_memidx d; moddata_offset := es; moddata_init := bs |} := m_d in\n  const_exprs c es /\\\n  typing.be_typing c es (Tf nil [::T_i32]) /\\\n  d < List.length c.(tc_memory).\n\nDefinition module_start_typing (c : t_context) (ms : module_start) : bool :=\n  let '(Mk_funcidx i) := ms.(modstart_func) in\n  (i < length c.(tc_func_t)) &&\n  match List.nth_error c.(tc_func_t) i with\n  | None => false\n  | Some tf => tf == (Tf nil nil)\n  end.\n\nDefinition module_import_typing (c : t_context) (d : import_desc) (e : extern_t) : bool :=\n  match (d, e) with\n  | (ID_func i, ET_func tf) =>\n    (i < List.length c.(tc_types_t)) &&\n    match List.nth_error c.(tc_types_t) i with\n    | None => false\n    | Some tf' => tf == tf'\n    end\n  | (ID_table t_t, ET_tab t_t') =>\n    (t_t == t_t') && module_tab_typing {| modtab_type := t_t |}\n  | (ID_mem mt, ET_mem mt') =>\n    (mt == mt') && module_mem_typing mt\n  | (ID_global gt, ET_glob gt') => gt == gt'\n  | _ => false\n  end.\n\nDefinition module_export_typing (c : t_context) (d : module_export_desc) (e : extern_t) : bool :=\n  match (d, e) with\n  | (MED_func (Mk_funcidx i), ET_func tf) =>\n    (i < List.length c.(tc_func_t)) &&\n    match List.nth_error c.(tc_func_t) i with\n    | None => false\n    | Some tf' => tf == tf'\n    end\n  | (MED_table (Mk_tableidx i), ET_tab t_t) =>\n    (i < List.length c.(tc_table)) &&\n    match List.nth_error c.(tc_table) i with\n    | None => false\n    | Some lim' => t_t == lim'\n    end\n  | (MED_mem (Mk_memidx i), ET_mem t_m) =>\n    (i < List.length c.(tc_memory)) &&\n    match List.nth_error c.(tc_memory) i with\n    | None => false\n    | Some lim' => t_m == lim' (* TODO: should check for equality of `memory_type`s *)\n                            (* UPD: changed a bit *)\n    end\n  | (MED_global (Mk_globalidx i), ET_glob gt) =>\n    (i < List.length c.(tc_global)) &&\n    match List.nth_error c.(tc_global) i with\n    | None => false\n    | Some gt' => gt == gt'\n    end\n  | (_, _) => false\n  end.\n\nDefinition pred_option {A} (p : A -> bool) (a_opt : option A) : bool :=\n  match a_opt with\n  | None => true\n  | Some a => p a\n  end.\n\nDefinition module_typing (m : module) (impts : list extern_t) (expts : list extern_t) : Prop :=\n  exists fts gts,\n  let '{| \n    mod_types := tfs;\n    mod_funcs := fs;\n    mod_tables := ts;\n    mod_mems := ms;\n    mod_globals := gs;\n    mod_elem := els;\n    mod_data := ds;\n    mod_start := i_opt;\n    mod_imports := imps;\n    mod_exports := exps;\n  |} := m in\n  let ifts := ext_t_funcs impts in\n  let its := ext_t_tabs impts in\n  let ims := ext_t_mems impts in\n  let igs := ext_t_globs impts in\n  let c := {|\n    tc_types_t := tfs;\n    tc_func_t := List.app ifts fts;\n    tc_global := List.app igs gts;\n    tc_table := List.app its (List.map (fun t => t.(modtab_type)) ts);\n    tc_memory := List.app ims ms; (* TODO: should use `mem_type`s *) (* UPD: fixed? *)\n    tc_local := nil;\n    tc_label := nil;\n    tc_return := None;\n  |} in\n  let c' := {|\n    tc_types_t := nil;\n    tc_func_t := nil;\n    tc_global := igs;\n    tc_table := nil;\n    tc_memory := nil;\n    tc_local := nil;\n    tc_label := nil;\n    tc_return := None;\n  |} in\n  List.Forall2 (module_func_typing c) fs fts /\\\n  seq.all module_tab_typing ts /\\\n  seq.all module_mem_typing ms /\\\n  List.Forall2 (module_glob_typing c') gs gts /\\\n  List.Forall (module_elem_typing c) els /\\\n  List.Forall (module_data_typing c) ds /\\\n  pred_option (module_start_typing c) i_opt /\\\n  List.Forall2 (fun imp => module_import_typing c imp.(imp_desc)) imps impts /\\\n  List.Forall2 (fun exp => module_export_typing c exp.(modexp_desc)) exps expts.\n\nInductive external_typing : store_record -> v_ext -> extern_t -> Prop :=\n| ETY_func :\n  forall (s : store_record) (i : nat) cl (tf : function_type),\n  i < List.length s.(s_funcs) ->\n  List.nth_error s.(s_funcs) i = Some cl ->\n  tf = operations.cl_type cl ->\n  external_typing s (MED_func (Mk_funcidx i)) (ET_func tf)\n| ETY_tab :\n  forall (s : store_record) (i : nat) (ti : tableinst) tt,\n  i < List.length s.(s_tables) ->\n  List.nth_error s.(s_tables) i = Some ti ->\n  typing.tab_typing ti tt ->\n  external_typing s (MED_table (Mk_tableidx i)) (ET_tab tt) (* {| tt_limits := lim; tt_elem_type := ELT_funcref |})*)\n| ETY_mem :\n  forall (s : store_record) (i : nat) (m : memory) (mt : memory_type),\n  i < List.length s.(s_mems) ->\n  List.nth_error s.(s_mems) i = Some m ->\n  typing.mem_typing m mt ->\n  external_typing s (MED_mem (Mk_memidx i)) (ET_mem mt)\n| ETY_glob :\n  forall (s : store_record) (i : nat) (g : global) (gt : global_type),\n  i < List.length s.(s_globals) ->\n  List.nth_error s.(s_globals) i = Some g ->\n  typing.global_agree g gt ->\n  external_typing s (MED_global (Mk_globalidx i)) (ET_glob gt).\n\nDefinition instantiate_globals inst (hs' : host_state) (s' : store_record) m g_inits : Prop :=\n  List.Forall2 (fun g v =>\n      opsem.reduce_trans (hs', s', (Build_frame nil inst), operations.to_e_list g.(modglob_init))\n                         (hs', s', (Build_frame nil inst), [::AI_basic (BI_const v)]))\n    m.(mod_globals) g_inits.\n\nDefinition instantiate_elem inst (hs' : host_state) (s' : store_record) m e_offs : Prop :=\n  List.Forall2 (fun e c =>\n      opsem.reduce_trans (hs', s', (Build_frame nil inst), operations.to_e_list e.(modelem_offset))\n                         (hs', s', (Build_frame nil inst), [::AI_basic (BI_const (VAL_int32 c))]))\n    m.(mod_elem)\n    e_offs.\n\nDefinition instantiate_data inst (hs' : host_state) (s' : store_record) m d_offs : Prop :=\n  List.Forall2 (fun d c =>\n      opsem.reduce_trans (hs', s', (Build_frame nil inst), operations.to_e_list d.(moddata_offset))\n                         (hs', s', (Build_frame nil inst), [::AI_basic (BI_const (VAL_int32 c))]))\n    m.(mod_data)\n    d_offs.\n\nDefinition nat_of_int (i : i32) : nat :=\n  BinInt.Z.to_nat i.(Wasm_int.Int32.intval).\n\nDefinition N_of_int (i : i32) : N :=\n  BinInt.Z.to_N i.(Wasm_int.Int32.intval).\n\nDefinition check_bounds_elem (inst : instance) (s : store_record) (m : module) (e_offs : seq i32) : bool :=\n  seq.all2\n    (fun e_off e =>\n      match List.nth_error inst.(inst_tab) (match e.(modelem_table) with Mk_tableidx i => i end) with\n      | None => false\n      | Some i =>\n        match List.nth_error s.(s_tables) i with\n        | None => false\n        | Some ti =>\n          N.leb (N.add (N_of_int e_off) (N.of_nat (List.length e.(modelem_init)))) (N.of_nat (List.length ti.(table_data)))\n        end\n      end)\n      e_offs\n      m.(mod_elem).\n\nDefinition mem_length (m : memory) : N :=\n  mem_length m.(mem_data).\n\nDefinition check_bounds_data (inst : instance) (s : store_record) (m : module) (d_offs : seq i32) : bool :=\n  seq.all2\n    (fun d_off d =>\n      match List.nth_error inst.(inst_memory) (match d.(moddata_data) with Mk_memidx i => i end) with\n      | None => false\n      | Some i =>\n        match List.nth_error s.(s_mems) i with\n        | None => false\n        | Some mem =>\n          N.leb (N.add (N_of_int d_off) (N.of_nat (List.length d.(moddata_init)))) (mem_length mem)\n        end\n      end)\n      d_offs\n      m.(mod_data).\n\nDefinition check_start m inst start : bool :=\n  let start' :=\n    operations.option_bind\n    (fun i_s =>\n      List.nth_error inst.(inst_funcs) (match i_s.(modstart_func) with Mk_funcidx i => i end))\n    m.(mod_start) in\n  start' == start.\n\nDefinition instantiate (* FIXME: Do we need to use this: [(hs : host_state)] ? *)\n                       (s : store_record) (m : module) (v_imps : list v_ext)\n                       (z : (store_record * instance * list module_export) * option nat) : Prop :=\n  let '((s_end, inst, v_exps), start) := z in\n  exists t_imps t_exps hs' s' g_inits e_offs d_offs,\n    module_typing m t_imps t_exps /\\\n    List.Forall2 (external_typing s) v_imps t_imps /\\\n    alloc_module s m v_imps g_inits (s', inst, v_exps) /\\\n    instantiate_globals inst hs' s' m g_inits /\\\n    instantiate_elem inst hs' s' m e_offs /\\\n    instantiate_data inst hs' s' m d_offs /\\\n    check_bounds_elem inst s' m e_offs /\\\n    check_bounds_data inst s' m d_offs /\\\n    check_start m inst start /\\\n    let s'' := init_tabs s' inst (map (fun o => BinInt.Z.to_nat o.(Wasm_int.Int32.intval)) e_offs) m.(mod_elem) in\n    (s_end : store_record_eqType)\n      == init_mems s'' inst (map (fun o => BinInt.Z.to_N o.(Wasm_int.Int32.intval)) d_offs) m.(mod_data).\n\nDefinition gather_m_f_type (tfs : list function_type) (m_f : module_func) : option function_type :=\n  let '(Mk_typeidx i) := m_f.(modfunc_type) in\n  if i < List.length tfs then List.nth_error tfs i\n  else None.\n\nDefinition gather_m_f_types (tfs : list function_type) (m_fs : list module_func) : option (list function_type) :=\n  list_extra.those (List.map (gather_m_f_type tfs) m_fs).\n\nDefinition module_import_typer (tfs : list function_type) (imp : import_desc) : option extern_t :=\n  match imp with\n  | ID_func i =>\n    if i < List.length tfs then\n      match List.nth_error tfs i with\n      | None => None\n      | Some ft => Some (ET_func ft)\n      end\n    else None\n  | ID_table t_t =>\n    if module_tab_typing {| modtab_type := t_t |} then Some (ET_tab t_t) else None\n  | ID_mem mt =>\n    if module_mem_typing mt then Some (ET_mem mt) else None\n  | ID_global gt => Some (ET_glob gt)\n  end.\n\nDefinition module_imports_typer (tfs : list function_type) (imps : list module_import) : option (list extern_t) :=\n  those (List.map (fun imp => module_import_typer tfs imp.(imp_desc)) imps).\n\nDefinition module_export_typer (c : t_context) (exp : module_export_desc) : option extern_t :=\n  match exp with\n  | MED_func (Mk_funcidx i) =>\n    if i < List.length c.(tc_func_t) then\n      match List.nth_error c.(tc_func_t) i with\n      | None => None\n      | Some ft => Some (ET_func ft)\n      end\n    else None\n  | MED_table (Mk_tableidx i) =>\n    if i < List.length c.(tc_table) then\n      match List.nth_error c.(tc_table) i with\n      | None => None\n      | Some t_t => Some (ET_tab t_t)\n      end\n    else None\n  | MED_mem (Mk_memidx i) =>\n    if i < List.length c.(tc_memory) then\n      match List.nth_error c.(tc_memory) i with\n      | None => None\n      | Some lim => Some (ET_mem lim)\n      end\n    else None\n  | MED_global (Mk_globalidx i) =>\n    if i < List.length c.(tc_global) then\n      match List.nth_error c.(tc_global) i with\n      | None => None\n      | Some g => Some (ET_glob g)\n      end\n    else None\n  end.\n\nDefinition module_exports_typer (c : t_context) exps :=\n  those (List.map (fun exp => module_export_typer c exp.(modexp_desc)) exps).\n\nDefinition gather_m_g_types (mgs : list module_glob) : list global_type :=\n  List.map (fun mg => mg.(modglob_type)) mgs.\n\nDefinition module_func_type_checker (c : t_context) (m : module_func) : bool :=\n  let '{| modfunc_type := Mk_typeidx i; modfunc_locals := t_locs; modfunc_body := b_es |} := m in\n  (i < List.length c.(tc_types_t)) &&\n  match List.nth_error c.(tc_types_t) i with\n  | None => false\n  | Some (Tf tn tm) =>\n    let c' := {|\n      tc_types_t := c.(tc_types_t);\n      tc_func_t := c.(tc_func_t);\n      tc_global := c.(tc_global);\n      tc_table := c.(tc_table);\n      tc_memory := c.(tc_memory);\n      tc_local := List.app c.(tc_local) (List.app tn t_locs);\n      tc_label := tm :: c.(tc_label);\n      tc_return := Some tm;\n    |} in\n    type_checker.b_e_type_checker c' b_es (Tf [::] tm)\n  end.\n\nDefinition module_tab_type_checker := module_tab_typing.\nDefinition module_memory_type_checker := module_mem_typing.\n\nDefinition module_glob_type_checker (c : t_context) (mg : module_glob) : bool :=\n  let '{| modglob_type := tg; modglob_init := es |} := mg in\n  const_exprs c es &&\n  type_checker.b_e_type_checker c es (Tf nil [::tg.(tg_t)]).\n\nDefinition module_elem_type_checker (c : t_context) (e : module_element) : bool :=\n  let '{| modelem_table := Mk_tableidx t; modelem_offset := es; modelem_init := is_ |} := e in\n  const_exprs c es &&\n  type_checker.b_e_type_checker c es (Tf nil [::T_i32]) &&\n  (t < List.length c.(tc_table)) &&\n  seq.all (fun '(Mk_funcidx i) => i < List.length c.(tc_func_t)) is_.\n\nDefinition module_data_type_checker (c : t_context) (d : module_data) : bool :=\n  let '{| moddata_data := Mk_memidx d; moddata_offset := es; moddata_init := bs |} := d in\n  const_exprs c es &&\n  type_checker.b_e_type_checker c es (Tf nil [::T_i32]) &&\n  (d < List.length c.(tc_memory)).\n\nDefinition module_start_type_checker (c : t_context) (ms : module_start) : bool :=\n  module_start_typing c ms.\n\nDefinition module_type_checker (m : module) : option ((list extern_t) * (list extern_t)) :=\n  let '{|\n    mod_types := tfs;\n    mod_funcs := fs;\n    mod_tables := ts;\n    mod_mems := ms;\n    mod_globals := gs;\n    mod_elem := els;\n    mod_data := ds;\n    mod_start := i_opt;\n    mod_imports := imps;\n    mod_exports := exps;\n    |} := m in\n  match (gather_m_f_types tfs fs, module_imports_typer tfs imps) with\n  | (Some fts, Some impts) =>\n    let ifts := ext_t_funcs impts in\n    let its := ext_t_tabs impts in\n    let ims := ext_t_mems impts in\n    let igs := ext_t_globs impts in\n    let gts := gather_m_g_types gs in\n    let c := {|\n      tc_types_t := tfs;\n      tc_func_t := List.app ifts fts;\n      tc_global := List.app igs gts;\n      tc_table := List.app its (List.map (fun t => t.(modtab_type)) ts);\n      tc_memory := List.app ims ms;\n      tc_local := nil;\n      tc_label := nil;\n      tc_return := None |} in\n    let c' := {|\n      tc_types_t := nil;\n      tc_func_t := nil;\n      tc_global := igs;\n      tc_table := nil;\n      tc_memory := nil;\n      tc_local := nil;\n      tc_label := nil;\n      tc_return := None\n    |} in\n    if seq.all (module_func_type_checker c) fs &&\n       seq.all module_tab_type_checker ts &&\n       seq.all module_memory_type_checker ms &&\n       seq.all (module_glob_type_checker c') gs &&\n       seq.all (module_elem_type_checker c) els &&\n       seq.all (module_data_type_checker c) ds &&\n       pred_option (module_start_type_checker c) i_opt then\n       match module_exports_typer c exps with\n       | Some expts => Some (impts, expts)\n       | None => None\n       end\n    else None\n  | (Some _, None) | (None, Some _) | (None, None) => None\n  end.\n\nDefinition external_type_checker (s : store_record) (v : v_ext) (e : extern_t) : bool :=\n  match (v, e) with\n  | (MED_func (Mk_funcidx i), ET_func tf) =>\n    (i < List.length s.(s_funcs)) &&\n    match List.nth_error s.(s_funcs) i with\n    | None => false\n    | Some cl => tf == operations.cl_type cl\n    end\n  | (MED_table (Mk_tableidx i), ET_tab tf) =>\n(* TODO   let '{| tt_limits := lim; tt_elem_type := elem_type_tt |} := tf in*)\n    (i < List.length s.(s_tables)) &&\n    match List.nth_error s.(s_tables) i with\n    | None => false\n    | Some ti => typing.tab_typing ti tf\n    end\n  | (MED_mem (Mk_memidx i), ET_mem mt) =>\n    (i < List.length s.(s_mems)) &&\n    match List.nth_error s.(s_mems) i with\n    | None => false\n    | Some m => typing.mem_typing m mt\n    end\n  | (MED_global (Mk_globalidx i), ET_glob gt) =>\n    (i < List.length s.(s_globals)) &&\n    match List.nth_error s.(s_globals) i with\n    | None => false\n    | Some g => typing.global_agree g gt\n    end\n  | (_, _) => false\n  end.\n\nImport ITree ITreeFacts.\n\nImport Monads.\nImport MonadNotation.\n\n(** The following type is returned as an event when the instantiation failed. **)\nInductive instantiation_error (T : Type) : Type :=\n  | Instantiation_error : instantiation_error T.\n\nArguments Instantiation_error {T}.\n\nDefinition interp_get_v (s : store_record) (inst : instance) (b_es : list basic_instruction)\n  : itree (instantiation_error +' eff) value (* FIXME: isa mismatch *) :=\n  res <- burn 2 (run_v 0 inst (s, (Build_frame nil inst), operations.to_e_list b_es)) ;;\n  match res with\n  | (_, interpreter.R_value vs) =>\n    match vs with\n    | v :: nil => ret v\n    | _ => trigger_inl1 Instantiation_error\n    end\n  | _ => trigger_inl1 Instantiation_error\n  end.\n\nDefinition interp_get_i32 (s : store_record) (inst : instance) (b_es : list basic_instruction)\n  : itree (instantiation_error +' eff) i32 (* FIXME: isa mismatch *) :=\n  v <- interp_get_v s inst b_es ;;\n  match v with\n  | VAL_int32 c => ret c\n  | _ => trigger_inl1 Instantiation_error\n  end.\n\nDefinition interp_instantiate (s : store_record) (m : module) (v_imps : list v_ext)\n  : itree (instantiation_error +' eff) ((store_record * instance * list module_export) * option nat) :=\n  match module_type_checker m with\n  | None => trigger_inl1 Instantiation_error\n  | Some (t_imps, t_exps) =>\n    if seq.all2 (external_type_checker s) v_imps t_imps then\n      let inst_c := {|\n            inst_types := nil;\n            inst_funcs := nil;\n            inst_tab := nil;\n            inst_memory := nil;\n            inst_globs := List.map (fun '(Mk_globalidx i) => i) (ext_globs v_imps);\n          |} in\n      g_inits <- bind_list (fun g => interp_get_v s inst_c g.(modglob_init)) m.(mod_globals) ;;\n      let '(s', inst, v_exps) := interp_alloc_module s m v_imps g_inits in\n      e_offs <- bind_list (fun e => interp_get_i32 s' inst e.(modelem_offset)) m.(mod_elem) ;;\n      d_offs <- bind_list (fun d => interp_get_i32 s' inst d.(moddata_offset)) m.(mod_data) ;;\n      if check_bounds_elem inst s' m e_offs &&\n         check_bounds_data inst s' m d_offs then\n        let start : option nat := operations.option_bind (fun i_s => List.nth_error inst.(inst_funcs) (match i_s.(modstart_func) with Mk_funcidx i => i end)) m.(mod_start) in\n        let s'' := init_tabs s' inst (List.map nat_of_int e_offs) m.(mod_elem) in\n        let s_end := init_mems s' inst (List.map N_of_int d_offs) m.(mod_data) in\n        ret ((s_end, inst, v_exps), start)\n      else trigger_inl1 Instantiation_error\n    else trigger_inl1 Instantiation_error\n  end.\n\nLemma interp_instantiate_imp_instantiate :\n  forall s m v_imps s_end inst v_exps start,\n  interp_instantiate s m v_imps ≈ ret ((s_end, inst, v_exps), start) ->\n  instantiate s m v_imps ((s_end, inst, v_exps), start).\nProof.\nAdmitted. (* TODO *)\n\nDefinition empty_store_record : store_record := {|\n    s_funcs := nil;\n    s_tables := nil;\n    s_mems := nil;\n    s_globals := nil;\n  |}.\n\nDefinition interp_instantiate_wrapper (m : module)\n  : itree _ ((store_record * instance * list module_export) * option nat) :=\n  interp_instantiate empty_store_record m nil.\n\nDefinition lookup_exported_function (n : name) (store_inst_exps : store_record * instance * list module_export)\n    : option (config_tuple host_function) :=\n  let '(s, inst, exps) := store_inst_exps in\n  List.fold_left\n    (fun acc e =>\n      match acc with\n      | Some cfg => Some cfg\n      | None =>\n        if e.(modexp_name) == n then\n          match e.(modexp_desc) with\n          | MED_func (Mk_funcidx fi) =>\n(*            Some (s, (Build_frame nil inst), [::AI_invoke fi])*)\n            match List.nth_error s.(s_funcs) fi with\n            | None => None\n            | Some fc => Some (s, (Build_frame nil inst), [::AI_invoke fi])\n            end\n          | _ => None\n          end\n        else None\n      end)\n    exps\n    None.\n\nEnd Host.\n\n(** As-is, [eqType] tends not to extract well.\n  This section provides alternative definitions for better extraction. **)\nModule Instantiation (EH : Executable_Host).\n\nModule Exec := convert_to_executable_host EH.\nImport Exec.\n\nDefinition lookup_exported_function :\n    name -> store_record * instance * seq module_export ->\n    option config_tuple :=\n  @lookup_exported_function _.\n\nDefinition interp_instantiate_wrapper :\n  module ->\n  itree (instantiation_error +' host_event)\n    (store_record * instance * seq module_export * option nat) :=\n  @interp_instantiate_wrapper _ executable_host_instance _ (fun T e => e).\n\nEnd Instantiation.\n\n", "meta": {"author": "WasmCert", "repo": "WasmCert-Coq", "sha": "df58f3517170fa3cf8b9206ec86f8d7ce66a57d2", "save_path": "github-repos/coq/WasmCert-WasmCert-Coq", "path": "github-repos/coq/WasmCert-WasmCert-Coq/WasmCert-Coq-df58f3517170fa3cf8b9206ec86f8d7ce66a57d2/theories/instantiation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2453118435562797}}
{"text": "(*\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\nRequire Import List.\nRequire Import ZArith.\nRequire Import EquivDec.\nRequire Import RelationClasses.\nRequire Import Equivalence.\nRequire Import String.\nRequire Import Utils.\nRequire Import DataSystem.\nRequire Import ForeignReduceOps.\nRequire Import ForeignToReduceOps.\n\nRequire Import EnhancedData.\nRequire Import EnhancedReduceOps.\n\nImport ListNotations.\nLocal Open Scope list_scope.\nLocal Open Scope string_scope.\nLocal Open Scope nstring_scope.\n\nDefinition enhanced_to_reduce_op (uop:unary_op) : option NNRCMR.reduce_op :=\n  match uop with\n  | OpCount => Some (NNRCMR.RedOpForeign RedOpCount)\n  | OpNatSum =>\n    Some (NNRCMR.RedOpForeign (RedOpSum enhanced_numeric_int))\n  | OpFloatSum =>\n    Some (NNRCMR.RedOpForeign (RedOpSum enhanced_numeric_float))\n  | OpNatMin =>\n    Some (NNRCMR.RedOpForeign (RedOpMin enhanced_numeric_int))\n  | OpFloatBagMin =>\n    Some (NNRCMR.RedOpForeign (RedOpMin enhanced_numeric_float))\n  | OpNatMax =>\n    Some (NNRCMR.RedOpForeign (RedOpMax enhanced_numeric_int))\n  | OpFloatBagMax =>\n    Some (NNRCMR.RedOpForeign (RedOpMax enhanced_numeric_float))\n  | OpNatMean =>\n    Some (NNRCMR.RedOpForeign (RedOpArithMean enhanced_numeric_int))\n  | OpFloatMean =>\n    Some (NNRCMR.RedOpForeign (RedOpArithMean enhanced_numeric_float))\n  | _ => None\n  end.\n\nDefinition enhanced_of_reduce_op (rop:NNRCMR.reduce_op) : option unary_op :=\n  match rop with\n  | NNRCMR.RedOpForeign RedOpCount => Some OpCount\n  | NNRCMR.RedOpForeign (RedOpSum enhanced_numeric_int) =>\n    Some (OpNatSum)\n  | NNRCMR.RedOpForeign (RedOpSum enhanced_numeric_float) =>\n    Some (OpFloatSum)\n  | NNRCMR.RedOpForeign (RedOpMin enhanced_numeric_int) =>\n    Some (OpNatMin)\n  | NNRCMR.RedOpForeign (RedOpMin enhanced_numeric_float) =>\n    Some (OpFloatBagMin)\n  | NNRCMR.RedOpForeign (RedOpMax enhanced_numeric_int) =>\n    Some (OpNatMax)\n  | NNRCMR.RedOpForeign (RedOpMax enhanced_numeric_float) =>\n    Some (OpFloatBagMax)\n  | NNRCMR.RedOpForeign (RedOpArithMean enhanced_numeric_int) =>\n    Some (OpNatMean)\n  | NNRCMR.RedOpForeign (RedOpArithMean enhanced_numeric_float) =>\n    Some (OpFloatMean)\n  | NNRCMR.RedOpForeign (RedOpStats _) =>\n    None (* XXX TODO? XXX *)\n  end.\n\nProgram Instance enhanced_foreign_to_reduce_op : foreign_to_reduce_op :=\n  mk_foreign_to_reduce_op enhanced_foreign_runtime enhanced_foreign_reduce_op enhanced_to_reduce_op _ enhanced_of_reduce_op _.\nNext Obligation.\n  unfold NNRCMR.reduce_op_eval.\n  destruct uop; simpl in *; invcs H; try reflexivity.\nQed.\nNext Obligation.\n  unfold NNRCMR.reduce_op_eval.\n  destruct rop; simpl in *; invcs H; try reflexivity.\n  destruct f; invcs H1; simpl; try reflexivity.\n  destruct typ; invcs H0; reflexivity.\n  destruct typ; invcs H0; reflexivity.\n  destruct typ; invcs H0; reflexivity.\n  destruct typ; invcs H0; reflexivity.\nQed.\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/Compiler/Enhanced/EnhancedToReduceOps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24531184355627964}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  Ifnot, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export csubst2.\nRequire Export continuity_defs.\nRequire Export alphaeq3.\nRequire Export list.  (* Why?? *)\n\n\nLtac gen_newvar :=\n  match goal with\n    | [ |- context[newvarlst ?l] ] => remember (newvarlst l)\n    | [ |- context[newvar ?x] ] => remember (newvar x)\n  end.\n\nLemma oneswapvar_eq1 :\n  forall a b, oneswapvar a b a = b.\nProof.\n  introv.\n  unfold oneswapvar; boolvar; sp.\nQed.\n\nLemma oneswapvar_neq :\n  forall a b v, v <> a -> v <> b -> oneswapvar a b v = v.\nProof.\n  introv ni1 ni2.\n  unfold oneswapvar; boolvar; sp.\nQed.\n\nLemma newvar_prop2 {p} :\n  forall v (t : @NTerm p), LIn v (free_vars t) -> newvar t <> v.\nProof.\n  introv i e; subst.\n  apply newvar_prop in i; sp.\nQed.\nHint Resolve newvar_prop2 : slow.\n\n\nDefinition agree_upto_b_type_v2 {o} vi (b f g T : @NTerm o) : NTerm :=\n  mk_isect\n    (mk_set\n       mk_int\n       vi\n       (mk_member (absolute_value (mk_var vi)) (mk_natk_aux vi b)))\n    vi\n    (mk_equality\n       (mk_apply f (mk_var vi))\n       (mk_apply g (mk_var vi))\n       T).\n\nDefinition int2int {o} := @mk_fun o mk_int mk_int.\nDefinition int2T {o} (T : @NTerm o) := @mk_fun o mk_int T.\n\nDefinition continuous_type_aux_aux_v2 {o} vb vg vi vf (F f T : @NTerm o) :=\n  mk_product\n    mk_tnat\n    vb\n    (mk_isect\n       (int2T T)\n       vg\n       (mk_isect\n          (agree_upto_b_type_v2\n             vi\n             (mk_var vb)\n             f\n             (mk_var vg)\n             T)\n          vf\n          (mk_equality\n             (mk_apply F f)\n             (mk_apply F (mk_var vg))\n             mk_int))).\n\nDefinition allvars_op {o} (t : @NTerm o) := all_vars t.\nLemma all_vars_eq_op {o} :\n  forall (t : @NTerm o), free_vars t ++ bound_vars t = allvars_op t.\nProof.\n  sp.\nQed.\nOpaque allvars_op.\n\nLtac dis_deq_nvar :=\n  match goal with\n    | [ H : !(?v1 = ?v2) |- context[deq_nvar ?v1 ?v2] ] => destruct (deq_nvar v1 v2); tcsp; GC;[]\n    | [ H : !(?v2 = ?v1) |- context[deq_nvar ?v1 ?v2] ] => destruct (deq_nvar v1 v2); tcsp; GC;[]\n    | [ H : ?v1 <> ?v2 |- context[deq_nvar ?v1 ?v2] ] => destruct (deq_nvar v1 v2); tcsp; GC;[]\n    | [ H : ?v2 <> ?v1 |- context[deq_nvar ?v1 ?v2] ] => destruct (deq_nvar v1 v2); tcsp; GC;[]\n  end.\n\nLtac nvo :=\n  match goal with\n    | [ H : context[!(_ [+] _)] |- _ ] => trw_h not_over_or H\n    | [ |- context[!(_ [+] _)] ] => trw not_over_or\n  end.\n\nLemma sub_find_trivial1 {o} :\n  forall v1 v2 (t : @NTerm o),\n    sub_find (if deq_nvar v1 v2 then [] else [(v1, t)]) v2 = None.\nProof.\n  introv.\n  boolvar; simpl; boolvar; tcsp.\nQed.\n\nLemma alphaeq_continuous_type_aux_aux {o} :\n  forall vb1 vb2 vg1 vg2 vi1 vi2 vf1 vf2 (F f T : @NTerm o),\n    closed F\n    -> closed f\n    -> closed T\n\n    -> vi1 <> vb1\n    -> vi1 <> vg1\n    -> vg1 <> vb1\n    -> vf1 <> vg1\n\n    -> vi2 <> vb2\n    -> vi2 <> vg2\n    -> vg2 <> vb2\n    -> vf2 <> vg2\n\n    -> alphaeq\n         (continuous_type_aux_aux_v2 vb1 vg1 vi1 vf1 F f T)\n         (continuous_type_aux_aux_v2 vb2 vg2 vi2 vf2 F f T).\nProof.\n  introv clF clf clT;\n  introv ni1 ni2 ni3 ni4 ni5 ni6 ni7 ni8.\n\n  apply alphaeq_eq.\n  unfold continuous_type_aux_aux_v2, mk_product.\n  repeat prove_alpha_eq4.\n\n  pose proof (ex_fresh_var (vb1 :: vb2 :: vg1 :: vg2 :: vi1 :: vi2 :: vf1 :: vf2\n                                :: (newvar T)\n                                :: (@newvar o mk_void)\n                                :: (@newvar o (mk_less_than (mk_var vi1) (vterm vb1)))\n                                :: (@newvar o (mk_less_than (mk_var vi2) (vterm vb2)))\n                                :: (allvars_op\n        (oterm (Can NIsect)\n           [bterm [] (int2T T),\n           bterm [vg1]\n             (oterm (Can NIsect)\n                [bterm []\n                   (agree_upto_b_type_v2 vi1 (vterm vb1) f (vterm vg1) T),\n                bterm [vf1]\n                  (oterm (Can NEquality)\n                     [bterm [] (oterm (NCan NApply) [bterm [] F, bterm [] f]),\n                     bterm []\n                       (oterm (NCan NApply)\n                          [bterm [] F, bterm [] (vterm vg1)]),\n                     bterm [] (oterm (Can NInt) [])])])]) ++\n      allvars_op\n        (oterm (Can NIsect)\n           [bterm [] (int2T T),\n           bterm [vg2]\n             (oterm (Can NIsect)\n                [bterm []\n                   (agree_upto_b_type_v2 vi2 (vterm vb2) f (vterm vg2) T),\n                bterm [vf2]\n                  (oterm (Can NEquality)\n                     [bterm [] (oterm (NCan NApply) [bterm [] F, bterm [] f]),\n                     bterm []\n                       (oterm (NCan NApply)\n                          [bterm [] F, bterm [] (vterm vg2)]),\n                     bterm [] (oterm (Can NInt) [])])])])))) as fv.\n  exrepnd.\n  allsimpl.\n  rw in_app_iff in fv0.\n  allrw not_over_or; repnd.\n\n  apply (al_bterm_aux [v]); simpl; auto;[|].\n  { unfold all_vars; allrw @all_vars_eq_op.\n    apply disjoint_singleton_l; allrw in_app_iff; sp. }\n\n  allrw @sub_filter_nil_r.\n  allrw memvar_singleton.\n\n  pose proof (newvar_prop T) as nv1.\n  remember (newvar T) as v1; clear Heqv1.\n  pose proof (@newvar_prop o mk_void) as nv2.\n  remember (newvar mk_void) as v2; clear Heqv2.\n  pose proof (@newvar_prop o (mk_less_than (mk_var vi1) (vterm vb1))) as nv3.\n  remember (newvar (mk_less_than (mk_var vi1) (vterm vb1))) as v3; clear Heqv3.\n  pose proof (@newvar_prop o (mk_less_than (mk_var vi2) (vterm vb2))) as nv4.\n  remember (newvar (mk_less_than (mk_var vi2) (vterm vb2))) as v4; clear Heqv4.\n  allsimpl; allrw not_over_or; repnd.\n\n  allrw @sub_find_sub_filter_eq.\n  allrw memvar_singleton.\n  allrw <- @beq_var_refl.\n  GC.\n  fold_terms.\n  allrw beq_deq.\n  repeat dis_deq_nvar.\n\n  simpl.\n  allrw memvar_singleton.\n  allrw <- @beq_var_refl.\n  GC.\n  fold_terms.\n  allrw beq_deq.\n  repeat dis_deq_nvar.\n\n  repeat (rw @lsubst_aux_trivial_cl_term2; eauto 3 with slow;[]).\n\n  repeat prove_alpha_eq4.\n\n  pose proof (ex_fresh_var (vb1 :: vb2 :: vg1 :: vg2 :: vi1 :: vi2 :: vf1 :: vf2\n                                :: v1 :: v2 :: v3 :: v4 :: v\n                                :: (allvars_op\n        (mk_isect\n           (mk_isect\n              (mk_set mk_int vi1\n                 (mk_member (absolute_value (mk_var vi1))\n                    (mk_set mk_int vi1\n                       (mk_product\n                          (mk_function (mk_less_than (mk_var vi1) mk_zero) v2\n                             mk_void) v3\n                          (mk_less_than (mk_var vi1) (mk_var v)))))) vi1\n              (mk_equality (mk_apply f (mk_var vi1))\n                 (mk_apply (mk_var vg1) (mk_var vi1)) T)) vf1\n           (mk_equality (mk_apply F f) (mk_apply F (mk_var vg1)) mk_int)) ++\n      allvars_op\n        (mk_isect\n           (mk_isect\n              (mk_set mk_int vi2\n                 (mk_member (absolute_value (mk_var vi2))\n                    (mk_set mk_int vi2\n                       (mk_product\n                          (mk_function (mk_less_than (mk_var vi2) mk_zero) v2\n                             mk_void) v4\n                          (mk_less_than (mk_var vi2) (mk_var v)))))) vi2\n              (mk_equality (mk_apply f (mk_var vi2))\n                 (mk_apply (mk_var vg2) (mk_var vi2)) T)) vf2\n           (mk_equality (mk_apply F f) (mk_apply F (mk_var vg2)) mk_int))))) as fvs.\n  exrepnd.\n  allsimpl.\n  allrw in_app_iff.\n  allrw not_over_or; repnd.\n\n  apply (al_bterm_aux [v0]); simpl; auto;[|].\n  { unfold all_vars; allrw @all_vars_eq_op.\n    fold_terms.\n    apply disjoint_singleton_l; allrw in_app_iff; sp. }\n\n  allrw @sub_filter_nil_r.\n  allrw @sub_find_sub_filter_eq.\n\n  simpl.\n  allrw memvar_singleton.\n  allrw <- @beq_var_refl.\n  GC.\n  fold_terms.\n  allrw beq_deq.\n  repeat dis_deq_nvar.\n\n  simpl.\n  allrw memvar_singleton.\n  allrw <- @beq_var_refl.\n  GC.\n  fold_terms.\n  allrw beq_deq.\n  repeat dis_deq_nvar.\n\n  repeat (rw @lsubst_aux_trivial_cl_term2; eauto 3 with slow;[]).\n\n  repeat prove_alpha_eq4.\n\n  { pose proof (ex_fresh_var (vb1 :: vb2 :: vg1 :: vg2 :: vi1 :: vi2 :: vf1 :: vf2\n                                  :: v1 :: v2 :: v3 :: v4 :: v :: v0 :: nvarx\n                                  :: allvars_op\n                          (mk_member (absolute_value (mk_var vi2))\n                             (mk_set mk_int vi2\n                                (mk_product\n                                   (mk_function\n                                      (mk_less_than (mk_var vi2) mk_zero) v2\n                                      mk_void) v4\n                                   (mk_less_than (mk_var vi2) (@mk_var o v))))) )) as fvs.\n    exrepnd.\n    allsimpl.\n    allrw in_app_iff.\n    repeat nvo.\n    repnd.\n\n    apply (al_bterm_aux [v5]); simpl; auto;[|].\n    { unfold all_vars; allrw @all_vars_eq_op.\n      fold_terms.\n      apply disjoint_singleton_l.\n      simpl.\n      allrw in_app_iff.\n      repeat nvo.\n      allrw app_nil_r.\n      simpl.\n      allrw in_remove_nvars.\n      simpl.\n      allrw in_remove_nvars.\n      simpl.\n      repeat nvo.\n      dands; tcsp. }\n\n    allrw @sub_filter_nil_r.\n    allrw @sub_find_sub_filter_eq.\n\n    simpl.\n    allrw memvar_singleton.\n    allrw <- @beq_var_refl.\n    GC.\n    fold_terms.\n    allrw beq_deq.\n    repeat dis_deq_nvar.\n\n    simpl.\n\n    unfold mk_member, mk_equality.\n    repeat prove_alpha_eq4.\n\n    pose proof (ex_fresh_var (vb1 :: vb2 :: vg1 :: vg2 :: vi1 :: vi2 :: vf1 :: vf2\n                                    :: v1 :: v2 :: v3 :: v4 :: v :: v0 :: nvarx :: v5\n                                    :: (allvars_op\n             (mk_product\n                (mk_function (mk_less_than (mk_var vi2) mk_zero) v2 mk_void)\n                v4 (mk_less_than (mk_var vi2) (@mk_var o v)))) )) as fvs.\n    exrepnd.\n    allsimpl.\n    allrw in_app_iff.\n    repeat nvo.\n    repnd.\n\n    apply (al_bterm_aux [v6]); simpl; auto;[|].\n    { unfold all_vars; allrw @all_vars_eq_op.\n      fold_terms.\n      apply disjoint_singleton_l.\n      simpl.\n      allrw app_nil_r.\n      allrw in_app_iff.\n      repeat nvo.\n      simpl.\n      allrw in_remove_nvars.\n      simpl.\n      repeat nvo.\n      dands; tcsp. }\n\n    allrw @sub_filter_nil_r.\n    allrw @sub_find_sub_filter_eq.\n\n    simpl.\n    allrw memvar_singleton.\n    allrw <- @beq_var_refl.\n    GC.\n    fold_terms.\n    allrw beq_deq.\n    repeat dis_deq_nvar.\n\n    simpl.\n    allrw memvar_singleton.\n    allrw <- @beq_var_refl.\n    GC.\n    fold_terms.\n    allrw beq_deq.\n    repeat dis_deq_nvar.\n\n    unfold mk_product, mk_function, mk_less.\n    allrw @sub_find_trivial1.\n\n    repeat prove_alpha_eq4.\n\n    pose proof (ex_fresh_var (v3 :: v4 :: v6 :: v :: nvarx\n                                 :: [] )) as fvs.\n    exrepnd.\n    allsimpl.\n    allrw in_app_iff.\n    repeat nvo.\n    repnd.\n\n    apply (al_bterm_aux [v7]); simpl; auto;[|].\n    { unfold all_vars; simpl.\n      apply disjoint_singleton_l.\n      simpl; sp. }\n\n    allrw @sub_filter_nil_r.\n    allrw @sub_find_sub_filter_eq.\n\n    simpl.\n    allrw memvar_singleton.\n    allrw <- @beq_var_refl.\n    GC.\n    fold_terms.\n    allrw beq_deq.\n    repeat dis_deq_nvar.\n    allrw @sub_find_trivial1.\n\n    unfold mk_less.\n    repeat prove_alpha_eq4.\n  }\n\n  { pose proof (ex_fresh_var (vb1 :: vb2 :: vg1 :: vg2 :: vi1 :: vi2 :: vf1 :: vf2\n                                    :: v1 :: v2 :: v3 :: v4 :: v :: v0 :: nvarx\n                                    :: (allvars_op\n        (mk_equality (mk_apply f (mk_var vi1))\n           (mk_apply (mk_var v0) (mk_var vi1)) T) ++\n      allvars_op\n        (mk_equality (mk_apply f (mk_var vi2))\n           (mk_apply (mk_var v0) (mk_var vi2)) T)) )) as fvs.\n    exrepnd.\n    allsimpl.\n    allrw in_app_iff.\n    repeat nvo.\n    repnd.\n\n    apply (al_bterm_aux [v5]); simpl; auto;[|].\n    { unfold all_vars; allrw @all_vars_eq_op.\n      fold_terms.\n      apply disjoint_singleton_l.\n      allrw in_app_iff.\n      sp. }\n\n    allrw @sub_filter_nil_r.\n    allrw @sub_find_sub_filter_eq.\n\n    simpl.\n    allrw memvar_singleton.\n    allrw <- @beq_var_refl.\n    GC.\n    fold_terms.\n    allrw beq_deq.\n    repeat dis_deq_nvar.\n    allrw @sub_find_trivial1.\n\n    repeat (rw @lsubst_aux_trivial_cl_term2; eauto 3 with slow).\n  }\n\n  { pose proof (ex_fresh_var (vb1 :: vb2 :: vg1 :: vg2 :: vi1 :: vi2 :: vf1 :: vf2\n                                    :: v1 :: v2 :: v3 :: v4 :: v :: v0 :: nvarx\n                                    :: (allvars_op\n         (mk_equality (mk_apply F f) (mk_apply F (mk_var v0)) mk_int) ++\n       allvars_op\n         (mk_equality (mk_apply F f) (mk_apply F (mk_var v0)) mk_int)) )) as fvs.\n    exrepnd.\n    allsimpl.\n    allrw in_app_iff.\n    repeat nvo.\n    repnd.\n\n    apply (al_bterm_aux [v5]); simpl; auto;[|].\n    { unfold all_vars; allrw @all_vars_eq_op.\n      fold_terms.\n      apply disjoint_singleton_l.\n      allrw in_app_iff.\n      sp. }\n\n    allrw @sub_filter_nil_r.\n    allrw @sub_find_sub_filter_eq.\n\n    simpl.\n    allrw memvar_singleton.\n    allrw <- @beq_var_refl.\n    GC.\n    fold_terms.\n    allrw beq_deq.\n    repeat dis_deq_nvar.\n    allrw @sub_find_trivial1.\n\n    repeat (rw @lsubst_aux_trivial_cl_term2; eauto 3 with slow).\n  }\nQed.\n", "meta": {"author": "coq-contribs", "repo": "intuitionistic-nuprl", "sha": "6279ed83244dc4aec2e23ffb4c87e3f10a50326d", "save_path": "github-repos/coq/coq-contribs-intuitionistic-nuprl", "path": "github-repos/coq/coq-contribs-intuitionistic-nuprl/intuitionistic-nuprl-6279ed83244dc4aec2e23ffb4c87e3f10a50326d/continuity_type_aux_v2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24531183698538403}}
{"text": "From mathcomp.ssreflect Require Import ssreflect seq ssrbool\n        ssrnat ssrfun eqtype seq fintype finfun.\n\nSet Implicit Arguments.\nRequire Import Coq.Classes.RelationClasses.\n\nRequire Import VST.msl.Coqlib2.\nRequire Import VST.sepcomp.mem_lemmas.\nRequire Import VST.sepcomp.event_semantics.\nRequire Import VST.concurrency.common.threads_lemmas.\nRequire Import VST.concurrency.common.permjoin_def.\nRequire Import compcert.common.Memory.\nRequire Import VST.concurrency.lib.Coqlib3.\nRequire Import compcert.common.Values. (*for val*)\nRequire Import compcert.lib.Integers.\nRequire Export compcert.lib.Maps.\nRequire Import Coq.ZArith.ZArith.\nFrom VST.veric Require Import shares juicy_mem juicy_mem_lemmas.\nRequire Import VST.msl.msl_standard.\nRequire Import FunInd.\nImport cjoins.\n\n(*IM using proof irrelevance!*)\nRequire Import ProofIrrelevance.\n\nSet Nested Proofs Allowed.\n\nLemma po_refl: forall p, Mem.perm_order'' p p.\nProof.\n  destruct p; [apply perm_refl| simpl]; auto.\nQed.\n\nLemma perm_order_antisym :\n  forall p p'\n    (Hlt: Mem.perm_order'' p p')\n    (Hgt: Mem.perm_order'' p' p),\n    p = p'.\nProof.\n  intros.\n  unfold Mem.perm_order'' in *.\n  destruct p as [p|], p' as [p'|];\n    try destruct p; try destruct p';\n    auto;\n    try (by inversion Hgt); try (by inversion Hlt).\nQed.\n\nDefinition access_map := Maps.PMap.t (Z -> option permission).\nDefinition delta_map := Maps.PTree.t (Z -> option (option permission)).\n\n\nDefinition dmap_get' (dm:delta_map) b ofs:=\n  match dm ! b with\n    Some f =>\n    match f ofs with\n      Some p => Some p\n    | None => None \n    end\n  |None => None\n  end.\n\nDefinition dmap_get (dm:delta_map) b ofs:=\n  (fun _ => None, dm) !! b ofs.\nHint Transparent dmap_get.\n(* go back in time \n   It is to go back to the previous definition.\n   only to help transitioning. Hopefully one day we get rid of this.\n *)\nLemma dmap_get_bit':\n  forall dm b ofs, dmap_get dm b ofs  = dmap_get' dm b ofs.\nProof.\n  unfold dmap_get, dmap_get', PMap.get.\n  intros; simpl.\n  destruct (dm ! b); auto.\n  destruct (o ofs); auto.\nQed.\nLemma dmap_get_bit:\n  forall dm b, dmap_get dm b = dmap_get' dm b.\nProof. intros. extensionality ofs; eapply dmap_get_bit'. Qed.\n\nLemma dmap_get_Some:\n  forall dm b ofs p,\n    dmap_get dm b ofs = Some p ->\n    exists f, dm ! b = Some f /\\\n         f ofs = Some p.\nProof.\n  intros * H.\n  rewrite dmap_get_bit in H.\n  unfold dmap_get' in *.\n  destruct (dm ! b) eqn:HH1; try solve[inversion H].\n  destruct (o ofs) eqn: HH2; inv H.\n  do 2 econstructor; eauto.\nQed.\n\nSection permMapDefs.\n\n  Definition empty_map : access_map :=\n    (fun z => None, Maps.PTree.empty (Z -> option permission)).\n\n  Lemma empty_map_spec: forall b ofs,\n      Maps.PMap.get b empty_map ofs = None.\n        intros. unfold empty_map, Maps.PMap.get.\n        rewrite Maps.PTree.gempty; reflexivity.\n  Qed.\n\n  Definition permission_at (m : mem) (b : block) (ofs : Z) (k : perm_kind) :=\n    Maps.PMap.get b (Mem.mem_access m) ofs k.\n\n  (** Coherence between permissions. This is used for the relation between data\n  and lock permissions*)\n  (** Note: p1 should be data permission and p2 lock permission*)\n  Definition perm_coh (p1 p2 : option permission) :=\n    match p1 with\n    | Some Freeable | Some Writable | Some Readable =>\n                                      match p2 with\n                                      | None => True\n                                      | _ => False\n                                      end\n    | Some Nonempty | None =>\n                      match p2 with\n                      | Some Freeable => False\n                      | _ => True\n                      end\n    end.\n\n  Lemma perm_coh_lower:\n    forall p1 p2 p3 p4\n      (Hpu: perm_coh p1 p2)\n      (Hperm2: Mem.perm_order'' p2 p4)\n      (Hperm1: Mem.perm_order'' p1 p3),\n      perm_coh p3 p4.\n  Proof.\n    intros.\n    destruct p2 as [p|];\n      try (destruct p); simpl in Hperm2;\n      destruct p4 as [p|];\n      try (destruct p); inversion Hperm2; subst;\n      destruct p1 as [p|];\n      try (destruct p); simpl in Hpu, Hperm1; try (now exfalso);\n      destruct p3; try inversion Hperm1; subst; simpl; auto.\n    destruct p; auto.\n  Qed.\n\n  Lemma perm_coh_not_freeable:\n    forall p p',\n      perm_coh p p' ->\n      p' <> Some Freeable.\n  Proof.\n    intros.\n    destruct p as [p|];\n      try (destruct p); simpl in H;\n      destruct p'; try (by exfalso);\n      intro Hcontra; try discriminate.\n    inversion Hcontra; subst; auto.\n    inversion Hcontra; subst; auto.\n  Qed.\n\n  Lemma perm_coh_empty_1:\n    forall p,\n      perm_coh p None.\n  Proof.\n    intros.\n    destruct p as [p|];\n      try (destruct p); simpl;\n      auto.\n  Qed.\n\n  Lemma perm_coh_empty_2:\n    forall p : option permission,\n      Mem.perm_order'' (Some Writable) p ->\n      perm_coh None p.\n  Proof.\n    intros p H.\n    destruct p; try destruct p; try solve[inversion H];\n    constructor.\n  Qed.\n\n  Lemma perm_of_glb_not_Freeable: forall sh,\n      ~ perm_of_sh (Share.glb Share.Rsh sh) = Some Freeable.\n  Proof.\n    intros ??%perm_of_sh_Freeable_top%glb_Rsh_not_top; auto.\n  Qed.\n\n  Lemma perm_coh_self: forall res,\n      perm_coh (perm_of_res res)\n               (perm_of_res_lock res).\n        destruct res; simpl; auto.\n        - apply perm_coh_empty_1.\n        - destruct k; try apply perm_coh_empty_1; simpl.\n            destruct (perm_of_sh (Share.glb Share.Rsh sh)) eqn: ?; auto.\n            destruct p0; auto.\n            eapply perm_of_glb_not_Freeable; eauto.\n  Qed.\n\n\n  Lemma perm_coh_joins:\n    forall a b, joins a b ->\n           perm_coh (perm_of_res a) (perm_of_res_lock b).\n  Proof.\n    intros a b H.\n    destruct H as [c H].\n    inversion H; subst; simpl.\n    - apply perm_coh_empty_1.\n    - apply perm_coh_empty_1.\n    - destruct k; try apply perm_coh_empty_1.\n      + destruct (perm_of_sh (Share.glb Share.Rsh sh2)) eqn:AA;\n        destruct (eq_dec sh1 Share.bot) eqn:BB;\n        try destruct p0;\n        try constructor.\n        * apply perm_of_sh_Freeable_top in AA; inversion AA; subst.\n          exfalso; eapply glb_Rsh_not_top; eauto.\n        * apply perm_of_sh_Freeable_top in AA; inversion AA; subst.\n          exfalso; eapply glb_Rsh_not_top; eauto.\n    - destruct k; try apply perm_coh_empty_1.\n      + destruct (perm_of_sh (Share.glb Share.Rsh sh2)) eqn:AA;\n        destruct (eq_dec sh1 Share.bot) eqn:BB;\n        try destruct p0;\n        try constructor.\n        * apply perm_of_sh_Freeable_top in AA; inversion AA; subst.\n          exfalso; eapply glb_Rsh_not_top; eauto.\n        * apply perm_of_sh_Freeable_top in AA; inversion AA; subst.\n          exfalso; eapply glb_Rsh_not_top; eauto.\n    - constructor.\n  Qed.\n\n  \n  Lemma po_join_sub_lock:\n  forall r1 r2 ,\n    join_sub r2 r1 ->\n    Mem.perm_order'' (perm_of_res_lock r1) (perm_of_res_lock r2).\n  Proof.\n  intros.\n  destruct H as [x H].\n  inversion H; subst; simpl; try constructor.\n  - destruct k; simpl; auto;\n      apply juicy_mem_lemmas.po_join_sub_sh; eexists;\n        eapply compcert_rmaps.join_glb_Rsh; eassumption.\n  - apply event_semantics.po_None.\n    \n  - destruct k; simpl; auto;\n      apply juicy_mem_lemmas.po_join_sub_sh; eexists;\n        eapply compcert_rmaps.join_glb_Rsh; eassumption.\n    \nQed.\n\n\n  Definition permMapCoherence (pmap1 pmap2 : access_map) :=\n    forall b ofs, perm_coh (pmap1 !! b ofs) (pmap2 !! b ofs).\n\n  Lemma permCoh_empty: forall r,\n      (forall b ofs, Mem.perm_order'' (Some Writable) (r !! b ofs)) ->\n      permMapCoherence empty_map r.\n        intros r H b ofs.\n        rewrite empty_map_spec.\n        specialize (H b ofs).\n        apply perm_coh_empty_2; assumption.\n  Qed.\n\n  Lemma permCoh_empty': forall x,\n      permMapCoherence x empty_map.\n  Proof.\n    intros x b ofs.\n    rewrite empty_map_spec.\n    apply perm_coh_empty_1.\n  Qed.\n\n  Lemma perm_of_res_lock_not_Freeable:\n    forall r,\n      Mem.perm_order'' (Some Writable) (perm_of_res_lock r).\n  Proof.\n    destruct r; try constructor; destruct k ; simpl; auto.\n    - destruct (perm_of_sh (Share.glb Share.Rsh sh)) eqn:HH; auto.\n      destruct p0; try constructor.\n      apply perm_of_sh_Freeable_top in HH; inversion HH.\n          exfalso; eapply glb_Rsh_not_top; eauto.\n  Qed.\n\n  (* Some None represents the empty permission. None is used for\n  permissions that conflict/race. *)\n\n  Definition perm_union (p1 p2 : option permission) : option (option permission) :=\n    match p1,p2 with\n      | None, _ => Some p2\n      | _, None => Some p1\n      | Some p1', Some p2' =>\n        match p1', p2' with\n          | Freeable, _ => None\n          | _, Freeable => None\n          | Nonempty, _ => Some p2\n          | _, Nonempty => Some p1\n          | Writable, _ => None\n          | _, Writable => None\n          | Readable, Readable => Some (Some Readable)\n        end\n    end.\n\n  Lemma perm_union_comm :\n    forall p1 p2,\n      perm_union p1 p2 = perm_union p2 p1.\n  Proof.\n    intros. destruct p1 as [p1|];\n      destruct p2 as [p2|];\n    try destruct p1, p2; simpl in *; reflexivity.\n  Defined.\n\n  Lemma perm_union_result : forall p1 p2 pu (Hunion: perm_union p1 p2 = Some pu),\n                              pu = p1 \\/ pu = p2.\n  Proof.\n    intros. destruct p1 as [p1|]; destruct p2 as [p2|];\n            try destruct p1, p2; simpl in Hunion; try discriminate;\n            try inversion Hunion; subst; auto.\n  Defined.\n\n  Lemma perm_union_ord : forall p1 p2 pu (Hunion: perm_union p1 p2 = Some pu),\n                           Mem.perm_order'' pu p1 /\\ Mem.perm_order'' pu p2.\n  Proof.\n    intros. destruct p1 as [p1|]; destruct p2 as [p2|];\n            try destruct p1, p2; simpl in Hunion; try discriminate;\n            try inversion Hunion; subst; unfold Mem.perm_order''; split; constructor.\n  Defined.\n\n  Lemma perm_union_lower:\n    forall p1 p2 p3\n      (Hpu: exists pu, perm_union p1 p2 = Some pu)\n      (Hperm: Mem.perm_order'' p2 p3),\n    exists pu, perm_union p1 p3 = Some pu.\n  Proof.\n    intros.\n    destruct p2 as [p|].\n    destruct p; simpl in Hperm;\n    destruct Hpu as [pu Hpu];\n    destruct p1 as [p|]; try destruct p; simpl in Hpu;\n    try congruence;\n    destruct p3; inversion Hperm; simpl; eexists; eauto.\n    simpl in Hperm.\n    destruct p3; simpl in *; tauto.\n  Qed.\n\n  Lemma perm_union_lower_2:\n    forall p1 p2 p3 p4\n      (Hpu: exists pu, perm_union p1 p2 = Some pu)\n      (Hperm: Mem.perm_order'' p1 p3)\n      (Hperm': Mem.perm_order'' p2 p4),\n    exists pu, perm_union p3 p4 = Some pu.\n  Proof.\n    intros.\n    destruct p2 as [p2|]; simpl in Hperm;\n      destruct p4 as [p4|];\n      destruct p1 as [p1 |];\n      destruct p3 as [p3|];\n      try (destruct p1);\n      simpl in *; inversion Hperm; subst;\n        destruct Hpu; try (discriminate);\n          try (destruct p2; inversion Hperm'; subst);\n          try (discriminate); try (by exfalso);\n            eexists; eauto.\n  Qed.\n\n\n  Inductive not_racy : option permission -> Prop :=\n  | empty : not_racy None.\n\n  Inductive racy : option permission -> Prop :=\n  | freeable : racy (Some Freeable).\n\n  Lemma not_racy_union :\n    forall p1 p2 (Hnot_racy: not_racy p1),\n    exists pu, perm_union p1 p2 = Some pu.\n  Proof. intros. destruct p2 as [o |]; [destruct o|]; inversion Hnot_racy; subst;\n                 simpl; eexists; reflexivity.\n  Qed.\n\n  Lemma no_race_racy : forall p1 p2 (Hracy: racy p1)\n                              (Hnorace: exists pu, perm_union p1 p2 = Some pu),\n                         not_racy p2.\n  Proof.\n    intros.\n    destruct p2 as [o|]; [destruct o|];\n    inversion Hracy; subst;\n    simpl in *; inversion Hnorace;\n    (discriminate || constructor).\n  Qed.\n\n  Lemma perm_order_clash:\n    forall p p'\n      (Hreadable: Mem.perm_order' p Readable)\n      (Hwritable: Mem.perm_order' p' Writable),\n      ~ exists pu, perm_union p p' = Some pu.\n  Proof.\n    intros. intro Hcontra.\n    destruct p as [p0|], p' as [p0'|];\n      try destruct p0;\n      try destruct p0';\n      simpl in *;\n      destruct Hcontra as [pu H];\n      try inversion H;\n      try (by inversion Hwritable);\n      try (by inversion Hreadable).\n  Qed.\n\n  Lemma perm_order_incompatible:\n    forall p p'\n      (Hreadable: Mem.perm_order'' p (Some Readable))\n      (Hwritable: Mem.perm_order'' p' (Some Writable)),\n      perm_union p p' = None.\n  Proof.\n    intros.\n    destruct p as [p0|], p' as [p0'|];\n      try destruct p0;\n      try destruct p0';\n      simpl in *; try (reflexivity);\n      try (by inversion Hwritable);\n      try (by inversion Hreadable).\n  Qed.\n\n  Definition perm_max (p1 p2 : option permission) : option permission :=\n    match p1,p2 with\n      | Some Freeable, _ => p1\n      | _, Some Freeable => p2\n      | Some Writable, _ => p1\n      | _, Some Writable => p2\n      | Some Readable, _ => p1\n      | _, Some Readable => p2\n      | Some Nonempty, _ => p1\n      | _, Some Nonempty => p2\n      | None, None => None\n    end.\n\n  Lemma perm_max_comm :\n    forall p1 p2,\n      perm_max p1 p2 = perm_max p2 p1.\n  Proof.\n    intros. destruct p1 as [p1|];\n      destruct p2 as [p2|];\n    try destruct p1, p2; simpl in *; reflexivity.\n  Defined.\n\n  Lemma perm_max_result : forall p1 p2 pu (Hmax: perm_max p1 p2 = pu),\n                            pu = p1 \\/ pu = p2.\n  Proof.\n    intros. destruct p1 as [p1|]; destruct p2 as [p2|];\n            try destruct p1, p2; simpl in Hmax; try rewrite Hmax; auto.\n    destruct p1; auto. destruct p2; auto.\n  Defined.\n\n  Lemma perm_max_ord : forall p1 p2 pu (Hmax: perm_max p1 p2 = pu),\n                           Mem.perm_order'' pu p1 /\\ Mem.perm_order'' pu p2.\n  Proof.\n    intros. destruct p1 as [p1|]; destruct p2 as [p2|];\n            try destruct p1; try destruct p2; simpl in Hmax;\n            try discriminate; subst; unfold Mem.perm_order'';\n    split; constructor.\n  Defined.\n\n  Definition getMaxPerm (m : mem) : access_map :=\n    Maps.PMap.map (fun f => fun ofs => f ofs Max) (Mem.mem_access m).\n\n  Definition getCurPerm (m : mem) : access_map :=\n    Maps.PMap.map (fun f => fun ofs => f ofs Cur) (Mem.mem_access m).\n\n  Definition getPermMap (m : mem) : Maps.PMap.t (Z -> perm_kind -> option permission) :=\n    Mem.mem_access m.\n\n  Lemma getCur_Max : forall m b ofs,\n                       Mem.perm_order'' (Maps.PMap.get b (getMaxPerm m) ofs)\n                                        (Maps.PMap.get b  (getCurPerm m) ofs).\n  Proof.\n    intros.\n    assert (Hlt:= Mem.access_max m b ofs).\n    unfold Mem.perm_order'' in *.\n    unfold getMaxPerm, getCurPerm.\n    do 2 rewrite Maps.PMap.gmap.\n    auto.\n  Qed.\n\n  Lemma getMaxPerm_correct :\n    forall m b ofs,\n      Maps.PMap.get b (getMaxPerm m) ofs = permission_at m b ofs Max.\n  Proof. intros. unfold getMaxPerm. by rewrite Maps.PMap.gmap. Qed.\n\n  Lemma getCurPerm_correct :\n    forall m b ofs,\n      Maps.PMap.get b (getCurPerm m) ofs = permission_at m b ofs Cur.\n  Proof. intros. unfold getCurPerm. by rewrite Maps.PMap.gmap. Qed.\n  \n\n  Definition permDisjoint p1 p2:=\n    exists pu : option permission,\n      perm_union p1 p2 = Some pu.\n\n   Lemma permDisjoint_None: forall p,\n      permDisjoint None p.\n  Proof. intros p. exists p; reflexivity. Qed.\n\n  Lemma permDisjoint_comm: forall p1 p2,\n      permDisjoint p1 p2 -> permDisjoint p2 p1.\n  Proof. intros p1 p2.\n         unfold permDisjoint, perm_union.\n         destruct p1 as [p3|]; destruct p2 as [p4|];\n         try destruct p3, p4; intros [k H]; exists k; inversion H;\n         reflexivity.\n  Qed.\n\n  Lemma permDisjointLT: forall a b c,\n      permDisjoint a c ->\n      Mem.perm_order'' a b ->\n      permDisjoint b c.\n        intros a b c H1 H2.\n        destruct a, b; try solve[inversion H2];\n        try solve[exists c; reflexivity].\n        simpl in H2.\n        destruct H1 as [k H1].\n        inversion H2; subst.\n        - exists k; assumption.\n        - destruct c; inversion H1.\n          exists (Some p0); reflexivity.\n        - destruct c; inversion H1.\n          destruct p; inversion H0.\n          exists (Some Readable); reflexivity.\n        - exists (Some Readable); reflexivity.\n        - destruct c; inversion H1;\n          try solve[exists (Some Nonempty); reflexivity].\n          destruct p; inversion H0; try(destruct p0; inversion H3);\n          try solve[exists (Some Nonempty); reflexivity];\n          try solve[exists (Some Readable); reflexivity];\n          try solve[exists (Some Writable); reflexivity].\n  Qed.\n\n  (* Lemma join_sh_permDisjoint: forall rsh1 rsh2 rsh3 (sh1 sh2 sh3: pshare),\n      join rsh1 rsh2 rsh3 ->\n      join sh1 sh2 sh3 ->\n      permDisjoint (perm_of_sh (Share.glb Share.Rsh sh1))) (perm_of_sh (Share.glb Share.Rsh sh1))).\n  Proof.\n    intros rsh1 rsh2 rsh3 sh1 sh2 sh3.\n    intros H1.\n    intros H2.\n    move: (perm_of_sh_pshare rsh1 sh1) (perm_of_sh_pshare rsh2 sh2) =>\n    [] p1 HH1 [] p2 HH2.\n    rewrite HH1 HH2 /permDisjoint /=.\n    destruct p1.\n    - apply perm_of_sh_Freeable_top in HH1; inversion HH1; subst.\n      destruct sh1.\n      unfold join, Join_pshare, Join_lift in H2.\n      simpl in H2.\n      simpl in H3; subst x.\n      apply pshare_join_full_false4 in H2.\n      exfalso; assumption.\n    - move: HH1.\n      unfold perm_of_sh.\n      repeat if_tac; try solve[intros HH; inversion HH].\n      destruct sh1.\n      unfold join, Join_pshare, Join_lift in H2.\n      simpl in H2.\n      simpl in H; subst x.\n      apply pshare_join_full_false4 in H2.\n      exfalso; assumption.\n    - move: HH1.\n      unfold perm_of_sh.\n      repeat if_tac; try solve[intros HH; inversion HH].\n      destruct p2; try solve[eexists; reflexivity].\n      + apply perm_of_sh_Freeable_top in HH2; inversion HH2; subst.\n        destruct sh2.\n        unfold join, Join_pshare, Join_lift in H2.\n        simpl in H2.\n        simpl in H5; subst x.\n        apply pshare_join_full_false3 in H2.\n        exfalso; assumption.\n      + move: HH2.\n        unfold perm_of_sh.\n        repeat if_tac; try solve[intros HH; inversion HH].\n        destruct sh2.\n        unfold join, Join_pshare, Join_lift in H2.\n        simpl in H2.\n        simpl in H3; subst x.\n        apply pshare_join_full_false3 in H2.\n        exfalso; assumption.\n    - destruct p2; try solve[eexists; reflexivity].\n      apply perm_of_sh_Freeable_top in HH2; inversion HH2; subst.\n      destruct sh2.\n      unfold join, Join_pshare, Join_lift in H2.\n      simpl in H2.\n      simpl in H3; subst x.\n      apply pshare_join_full_false3 in H2.\n      exfalso; assumption.\n  Qed.\n   *)\n  (*The new version of the above*)\n  Ltac if_simpl:=\n    repeat match goal with\n           | [ H: ?X = true |- context[if ?X then _ else _] ] => rewrite H; simpl \n           | [ H: ?X = false |- context[if ?X then _ else _] ] => rewrite H; simpl \n           | [ H: ?X = left _ |- context[match ?X with left _ => _ | right _ => _ end] ]=>\n             rewrite H; simpl \n           | [ H: ?X = right _ |- context[match ?X with left _ => _ | right _ => _ end] ]=>\n             rewrite H; simpl \n           | [ H: (@is_left _ _ ?X) = true |-\n               context [match ?X with left _ => _ | right _ => _ end ]] => destruct X; inversion H\n           | [ H: (@is_left _ _ ?X) = false |-\n               context [match ?X with left _ => _ | right _ => _ end ]] => destruct X; inversion H\n           end.\n\n  Ltac permDisj_solve:= eexists; simpl; reflexivity.\n  \n  Lemma join_sh_permDisjoint:\n        forall sh1 sh2,\n          joins sh1 sh2 ->\n          permDisjoint (perm_of_sh sh1) (perm_of_sh sh2).\n  \n\n  Lemma writable0_not_join_readable:\n    forall sh1 sh2,\n      joins sh1 sh2 ->\n      writable0_share sh1 ->\n      ~ readable_share sh2.\n  Proof.\n    intros.\n    intro.\n    destruct H as [sh ?].\n    apply join_writable0_readable in H; eauto.\n Qed.\n\n  Lemma writable0_not_join_writable0 :\n    forall sh1 sh2,\n      joins sh1 sh2 ->\n      writable0_share sh1 ->\n      ~ writable0_share sh2.\n   Proof.\n     intros. intro.\n    pose proof (writable0_not_join_readable H H0).\n    apply H2. auto.\n   Qed.\n\n    Ltac joins_sh_contradiction_onside:=\n      match goal with\n      | [ H: joins ?sh1 ?sh2,\n             W1: writable0_share ?sh1,\n                 W2: writable0_share ?sh2 |- _ ] =>\n        exfalso; eapply writable0_not_join_writable0; eassumption\n      | [ H: joins ?sh1 ?sh2,\n             W1: writable0_share ?sh1,\n                 W2: readable_share ?sh2 |- _ ] =>\n        exfalso; eapply writable0_not_join_readable; eassumption\n      | [ H: joins Share.top ?sh2,\n             H0: ?sh2 <> Share.bot |- _ ] =>\n        exfalso; eapply H0; eapply only_bot_joins_top; eassumption\n      end.\n    Ltac joins_sh_contradiction:=\n      first[ joins_sh_contradiction_onside |\n             match goal with\n             | [ H: joins ?sh1 ?sh2 |- _ ] =>\n               eapply joins_comm in H\n             end; joins_sh_contradiction_onside].\n  Proof.\n    (*intros.\n        unfold perm_of_sh.\n        destruct (writable_share_dec sh1).\n          \n        - pose proof (writable_not_join_writable H w).\n          pose proof (writable_not_join_readable H w).\n          destruct (writable_share_dec sh2); try contradiction.\n          destruct (readable_share_dec sh2); try contradiction.\n          destruct (eq_dec sh1 Share.top).\n          + subst. apply only_bot_joins_top in H; subst.\n            destruct (eq_dec Share.bot Share.bot); try contradiction.\n            eexists; reflexivity.\n          + destruct (eq_dec sh2 Share.bot); eexists; reflexivity.\n        - destruct (readable_share_dec sh1).\n          pose proof (readable_not_join_writable H r). \n          pose proof (readable_not_join_readable H r). \n          destruct ( writable_share_dec sh2); try contradiction.\n          destruct (readable_share_dec sh2); try contradiction.\n          destruct (eq_dec sh2 Share.bot); eexists; reflexivity.*)\n    intros.\n\n    functional induction (perm_of_sh sh1) using perm_of_sh_ind;\n      functional induction (perm_of_sh sh2) using perm_of_sh_ind;\n      try permDisj_solve;\n      joins_sh_contradiction.\n    Qed.\n \n  (*HERE*)\n  Lemma joins_permDisjoint: forall r1 r2,\n      joins r1 r2 ->\n      permDisjoint (perm_of_res r1) (perm_of_res r2).\n  Proof.\n(*\n    intros.\n    destruct H as [X H]; inversion H; simpl;\n      try permDisj_solve.\n    - destruct (eq_dec sh1 Share.bot); destruct (eq_dec sh2 Share.bot);\n      try permDisj_solve.\n    - destruct k; destruct (eq_dec sh2 Share.bot); try solve[eexists; reflexivity].\n      + eapply permDisjoint_comm. apply permDisjoint_None.\n      + subst; unfold perm_of_sh.\n        destruct (writable_share_dec sh1).\n          destruct (eq_dec sh1 Share.top); simpl;\n            try permDisj_solve.\n        * inversion RJ; subst.\n          rewrite Share.glb_commute in H0.\n          rewrite Share.glb_top in H0; contradiction.\n        * destruct (readable_share_dec sh1); try contradiction.\n          permDisj_solve.\n    - unfold permDisjoint.\n      destruct k; destruct (eq_dec sh1 Share.bot); try permDisj_solve.\n      subst; unfold perm_of_sh.\n      destruct (writable_share_dec sh2).\n      * destruct (eq_dec sh2 Share.top);\n          try permDisj_solve.\n        subst; inversion RJ.\n        rewrite Share.glb_top in H0; contradiction.\n      * destruct (readable_share_dec sh2);\n          try permDisj_solve.\n        destruct (eq_dec sh2 Share.bot); \n          try permDisj_solve.\n    - destruct k; try permDisj_solve.\n\n      Restart.\n\n      (*Explicit consturction of cases and induction*)\n\n      Inductive perm_of_res_cases (r : compcert_rmaps.RML.R.resource):=\n        | NO_bot: forall sh Psh, r = compcert_rmaps.RML.R.NO sh Psh ->\n                  is_left (eq_dec sh Share.bot) = true ->\n                  perm_of_res_cases r\n        | NO_nbot: forall sh Psh, r = compcert_rmaps.RML.R.NO sh Psh ->\n                   is_left (eq_dec sh Share.bot) = false ->\n                  perm_of_res_cases r\n        | YES_VAL_Freeable: forall sh Psh k Pk v, r = compcert_rmaps.RML.R.YES sh Psh k Pk ->\n                   k = compcert_rmaps.VAL v ->\n                    is_left (writable_share_dec sh) = true ->\n                    is_left (eq_dec sh Share.top) = true ->\n                   perm_of_res_cases r\n        | YES_VAL_Writable: forall sh Psh k Pk v, r = compcert_rmaps.RML.R.YES sh Psh k Pk ->\n                   k = compcert_rmaps.VAL v ->\n                    is_left (writable_share_dec sh) = true ->\n                    is_left (eq_dec sh Share.top) = false ->\n                   perm_of_res_cases r\n        | YES_VAL_Readable: forall sh Psh k Pk v, r = compcert_rmaps.RML.R.YES sh Psh k Pk ->\n                   k = compcert_rmaps.VAL v ->\n                    is_left (writable_share_dec sh) = false ->\n                    is_left (readable_share_dec sh)  = true ->\n                   perm_of_res_cases r\n        | YES_LK: forall sh Psh k Pk v, r = compcert_rmaps.RML.R.YES sh Psh k Pk ->\n                   k = compcert_rmaps.LK v ->\n                   perm_of_res_cases r\n        | YES_CT: forall sh Psh k Pk v, r = compcert_rmaps.RML.R.YES sh Psh k Pk ->\n                   k = compcert_rmaps.CT v ->\n                   perm_of_res_cases r\n        | YES_FUN: forall sh Psh k Pk x1 x2, r = compcert_rmaps.RML.R.YES sh Psh k Pk ->\n                   k = compcert_rmaps.FUN x1 x2 ->\n                   perm_of_res_cases r\n        | IS_PURE: forall P Q, r = compcert_rmaps.RML.R.PURE P Q ->\n                          perm_of_res_cases r.\n      (* Print perm_of_res_cases_ind. *)\n\n      Restart.\n      \n      intros.\n      (* Print perm_of_res_ind.*)\n      Functional Scheme perm_of_res_ind := Induction for perm_of_res Sort Prop.\n      Functional Scheme perm_of_sh_ind := Induction for perm_of_sh Sort Prop.\n\n      functional induction (perm_of_res r1) using perm_of_res_ind; simpl; subst;\n        unfold perm_of_sh; if_simpl; subst;\n      functional induction (perm_of_res r2) using perm_of_res_ind; simpl; subst;\n        unfold perm_of_sh; if_simpl; subst;\n          try permDisj_solve.\n      \n      functional induction (perm_of_sh sh0) using perm_of_sh_ind; simpl; subst;\n        unfold perm_of_sh; if_simpl; subst;\n          try permDisj_solve.\n\n      Restart.\n      *)\n\n      intros.\n      \n       Ltac join_sh_contradiction:=\n        match goal with\n        | [ H: @join Share.t _ _ _ _ |- _ ] => apply join_joins in H\n        end;\n      joins_sh_contradiction.\n      functional induction (perm_of_res_explicit r1) using perm_of_res_expl_ind;\n        simpl;subst;\n        unfold perm_of_sh; if_simpl; subst;\n          functional induction (perm_of_res_explicit r2) using perm_of_res_expl_ind;\n          simpl; subst;\n        unfold perm_of_sh; if_simpl; subst;\n          try permDisj_solve;\n          inversion H; inversion H0; subst;\n      try join_sh_contradiction.\n      \n  Qed.                                    \n  \n  \n  \n  Ltac glb_contradictions:=\n    repeat match goal with\n           | [ H: writable0_share_dec _ = _ |- _ ] => clear H\n           end;\n    match goal with\n    | [ H:  Share.glb Share.Rsh ?sh = Share.top  |- _ ] =>\n      exfalso; eapply glb_Rsh_not_top; eassumption\n    | [ H: writable0_share (Share.glb Share.Rsh ?sh) |- _ ] =>\n      eapply writable0_right in H\n    end; join_sh_contradiction.\n  \n  Lemma joins_permDisjoint_lock: forall r1 r2,\n      joins r1 r2 ->\n      permDisjoint (perm_of_res_lock r1) (perm_of_res_lock r2).\n  Proof.\n    intros.\n    \n    functional induction (perm_of_res_lock_explicit r1) using perm_of_res_lock_expl_ind;\n      simpl; subst;\n        unfold perm_of_sh; if_simpl; subst;\n    functional induction (perm_of_res_lock_explicit r2) using perm_of_res_lock_expl_ind;\n          simpl; subst;\n            unfold perm_of_sh; if_simpl; subst;\n              try permDisj_solve;\n          inversion H; inversion H0; subst;\n            try glb_contradictions.\n  Qed.\n  \n  (*Lemma permDisjoint_sub: forall r1 r2 p,\n      join_sub r2 r1 ->\n      permDisjoint (perm_of_res r1) p ->\n      permDisjoint (perm_of_res r2) p.\n  Proof.*)\n\n  (*Lemma join_permDisjoint: forall r1 r2 r3 p,\n      join r1 r2 r3 ->\n      permDisjoint (perm_of_res r1) p ->\n      permDisjoint (perm_of_res r2) p ->\n      permDisjoint (perm_of_res r3) p.\nProof.*)\n\n  Definition permMapsDisjoint (pmap1 pmap2 : access_map) : Prop :=\n    forall b ofs, exists pu,\n      perm_union ((Maps.PMap.get b pmap1) ofs)\n                 ((Maps.PMap.get b pmap2) ofs) = Some pu.\n\n  Definition permMapsDisjoint2 (pmap pmap': access_map * access_map) :=\n    permMapsDisjoint pmap.1 pmap'.1 /\\\n    permMapsDisjoint pmap.2 pmap'.2.\n\n  Lemma permDisjoint_permMapsDisjoint: forall r1 r2,\n      (forall b ofs, permDisjoint (r1 !! b ofs) (r2 !! b ofs))->\n      permMapsDisjoint r1 r2.\n        intros. intros b ofs. apply H.\n  Qed.\n\n  Lemma permMapsDisjoint_permDisjoint: forall r1 r2 b ofs,\n      permMapsDisjoint r1 r2 ->\n      permDisjoint (r1 !! b ofs) (r2 !! b ofs).\n        intros. destruct  (H b ofs) as [k H'].\n        exists k; assumption.\n  Qed.\n\n  Lemma empty_disjoint':\n    forall pmap,\n      permMapsDisjoint empty_map pmap.\n        intros pmap b ofs. exists (pmap !! b ofs). rewrite empty_map_spec; reflexivity.\n  Qed.\n  Lemma empty_disjoint:\n    permMapsDisjoint empty_map\n                     empty_map.\n      unfold permMapsDisjoint.\n      unfold empty_map; intros; simpl.\n      unfold Maps.PMap.get; simpl.\n      rewrite Maps.PTree.gempty; simpl.\n      exists None; reflexivity.\n  Qed.\n\n  Lemma permMapsDisjoint_comm :\n    forall pmap1 pmap2\n      (Hdis: permMapsDisjoint pmap1 pmap2),\n      permMapsDisjoint pmap2 pmap1.\n  Proof.\n    unfold permMapsDisjoint in *.\n    intros. destruct (Hdis b ofs) as [pu Hpunion].\n    rewrite perm_union_comm in Hpunion.\n    eexists; eauto.\n  Qed.\n\n  Lemma permMapsDisjoint2_comm:\n    forall pmaps pmaps',\n      permMapsDisjoint2 pmaps pmaps' <-> permMapsDisjoint2 pmaps' pmaps.\n  Proof.\n    intros.\n    split; intros (? & ?); split;\n      eauto using permMapsDisjoint_comm.\n  Qed.\n\n  Lemma disjoint_norace:\n    forall (mi mj : mem) (b : block) (ofs : Z)\n      (Hdisjoint: permMapsDisjoint (getCurPerm mi) (getCurPerm mj))\n      (Hpermj: Mem.perm mj b ofs Cur Readable)\n      (Hpermi: Mem.perm mi b ofs Cur Writable),\n      False.\n  Proof.\n    intros.\n    unfold Mem.perm, Mem.perm_order' in *.\n    unfold permMapsDisjoint, getCurPerm in Hdisjoint. simpl in Hdisjoint.\n    destruct (Hdisjoint b ofs) as [pu Hunion].\n    clear Hdisjoint.\n    do 2 rewrite Maps.PMap.gmap in Hunion.\n    destruct (Maps.PMap.get b (Mem.mem_access mj) ofs Cur) as [pj|] eqn:Hpj;\n      auto.\n    destruct (Maps.PMap.get b (Mem.mem_access mi) ofs Cur) as [pi|] eqn:Hpi;\n      auto.\n    inversion Hpermi; inversion Hpermj; subst; simpl in Hunion;\n    discriminate.\n  Qed.\n\n  Definition isCanonical (pmap : access_map) := pmap.1 = fun _ => None.\n  Import Maps.\n  Definition TreeMaxIndex {A} (t:Maps.PTree.t A): positive:=\n    compcert.lib.Coqlib.list_fold_left (fun a => [eta Pos.max a.1]) 1%positive (Maps.PTree.elements t) .\n  Lemma fold_max_monoton: forall  {A} (ls: seq.seq (positive * A)), forall i,\n        (Coqlib.list_fold_left (fun a => [eta Pos.max a.1]) i ls >= i)%positive.\n  Proof.\n    induction ls.\n    - simpl. intros; apply Pos.le_ge; apply Pos.le_refl.\n    - intros. simpl.\n      destruct (Pos.max_spec a.1 i) as [LT | GE].\n      + destruct LT as [LT MAX]; rewrite MAX.\n        apply IHls.\n      + destruct GE as [GE MAX]; rewrite MAX.\n        apply Pos.le_ge. apply (Pos.le_trans _ a.1); try assumption.\n        apply Pos.ge_le; apply IHls.\n  Qed.\n  Lemma fold_max_monoton': forall  {A} (ls: seq.seq (positive * A)), forall i j,\n        (i >= j)%positive ->\n        (compcert.lib.Coqlib.list_fold_left (fun a => [eta Pos.max a.1]) i ls >=\n         compcert.lib.Coqlib.list_fold_left (fun a => [eta Pos.max a.1]) j ls)%positive.\n  Proof.\n    induction ls.\n    - auto.\n    - intros. simpl.\n      destruct (Pos.max_spec a.1 i) as [LTi | GEi];\n      destruct (Pos.max_spec a.1 j) as [LTj | GEj];\n      try destruct LTi as [LTi MAXi]; try destruct LTj as [LTj MAXj];\n      try destruct GEi as [GEi MAXi]; try destruct GEj as [GEj MAXj];\n      try rewrite MAXi; try rewrite MAXj; simpl.\n      + apply IHls; assumption.\n      + apply IHls. apply Pos.le_ge. apply Pos.lt_le_incl; assumption.\n      + pose (contra:= Pos.le_lt_trans  _ _ _ GEi LTj).\n        apply Pos.ge_le in H. apply Pos.le_nlt in H. contradict H; assumption.\n      + apply Pos.le_ge. apply Pos.le_refl.\n  Qed.\n  Lemma TreeMaxIndex_help: forall {A} (ls: seq.seq (positive * A)), forall i v,\n        In (i, v) ls -> (compcert.lib.Coqlib.list_fold_left (fun a => [eta Pos.max a.1])\n                                              1%positive ls >= i)%positive.\n  Proof.\n    induction ls.\n    - intros. inversion H.\n    - intros. simpl in H.\n      destruct H as [eq | ineq].\n      + subst a. simpl.\n        rewrite Pos.max_1_r.\n        apply fold_max_monoton.\n      +  simpl. rewrite Pos.max_1_r.\n         pose (ineq':=ineq).\n         apply IHls in ineq'.\n         apply Pos.le_ge.\n         apply (Pos.le_trans _ (compcert.lib.Coqlib.list_fold_left\n                                  (fun a0 : positive * A => [eta Pos.max a0.1])\n                                  1%positive ls)).\n         * apply Pos.ge_le. eapply IHls.\n           eassumption.\n         * apply Pos.ge_le. apply fold_max_monoton'.\n           apply Pos.le_ge; apply Pos.le_1_l.\n  Qed.\n\n  Lemma max_works: forall A (t:PTree.t A) m, (m > TreeMaxIndex t)%positive ->\n                                        t ! m = None.\n  Proof.\n    intros. destruct (t ! m) eqn: GET; try reflexivity.\n    apply PTree.elements_correct in GET.\n    unfold TreeMaxIndex in H. simpl in H.\n    apply TreeMaxIndex_help in GET.\n    apply Pos.ge_le in GET. apply Pos.le_nlt in GET.\n    contradict GET. apply Pos.gt_lt; assumption.\n  Qed.\n\n  Lemma Cur_isCanonical: forall m, isCanonical (getCurPerm m).\n        unfold isCanonical. intros.\n        pose (BigNumber:= Pos.max (Pos.succ( TreeMaxIndex (getCurPerm m).2) ) (Mem.nextblock m)).\n        assert (HH: (BigNumber >= (Pos.succ ( TreeMaxIndex (getCurPerm m).2)))%positive )\n          by (unfold BigNumber; apply Pos.le_ge; apply Pos.le_max_l).\n        apply Pos.ge_le in HH; apply Pos.le_succ_l in HH.\n        apply Pos.lt_gt in HH; eapply max_works in HH.\n        extensionality x.\n        pose (property:= Mem.nextblock_noaccess m BigNumber x Cur).\n        rewrite <- property.\n        - replace ((Mem.mem_access m) !! BigNumber x Cur) with\n          (permission_at m BigNumber x Cur); try reflexivity.\n          rewrite <- getCurPerm_correct.\n          unfold PMap.get.\n          rewrite HH.\n          reflexivity.\n        - apply Pos.le_nlt. unfold BigNumber. apply Pos.le_max_r.\n  Qed.\n\n  Lemma Max_isCanonical: forall m, isCanonical (getMaxPerm m).\n        unfold isCanonical. intros.\n        pose (BigNumber:= Pos.max (Pos.succ( TreeMaxIndex (getMaxPerm m).2) ) (Mem.nextblock m)).\n        assert (HH: (BigNumber >= (Pos.succ ( TreeMaxIndex (getMaxPerm m).2)))%positive )\n          by (unfold BigNumber; apply Pos.le_ge; apply Pos.le_max_l).\n        apply Pos.ge_le in HH; apply Pos.le_succ_l in HH.\n        apply Pos.lt_gt in HH; eapply max_works in HH.\n        extensionality x.\n        pose (property:= Mem.nextblock_noaccess m BigNumber x Max).\n        rewrite <- property.\n        - replace ((Mem.mem_access m) !! BigNumber x Max) with\n          (permission_at m BigNumber x Max); try reflexivity.\n          rewrite <- getMaxPerm_correct.\n          unfold PMap.get.\n          rewrite HH.\n          reflexivity.\n        - apply Pos.le_nlt. unfold BigNumber. apply Pos.le_max_r.\n  Qed.\n\n  Definition permMapLt (pmap1 pmap2 : access_map) : Prop :=\n    forall b ofs,\n      Mem.perm_order'' (Maps.PMap.get b pmap2 ofs)\n                       (Maps.PMap.get b pmap1 ofs).\n\n  Lemma empty_LT: forall pmap,\n             permMapLt empty_map pmap.\n               intros pmap b ofs.\n               rewrite empty_map_spec.\n               destruct (pmap !! b ofs); simpl; exact I.\n  Qed.\n\n  Lemma canonical_lt :\n    forall p' m\n      (Hlt: permMapLt p' (getMaxPerm m)),\n      isCanonical p'.\n  Proof.\n    intros.\n    assert (Hcan:= Max_isCanonical m).\n    unfold isCanonical in *.\n    unfold permMapLt in *.\n    remember (Pos.max (Pos.succ(TreeMaxIndex\n                                  (getMaxPerm m).2) ) (Mem.nextblock m)) as b.\n    remember (Pos.max (Pos.succ(TreeMaxIndex p'.2)) b) as b'.\n    assert (Hb: ((Pos.succ ( TreeMaxIndex (getMaxPerm m).2)) <= b)%positive )\n      by (subst; apply Pos.le_max_l).\n    assert (Hm: (b' >= (Pos.succ ( TreeMaxIndex (getMaxPerm m).2)))%positive).\n    { subst b'. apply Pos.le_ge. eapply Pos.le_trans; eauto.\n      apply Pos.le_max_r.\n    }\n    assert (Hp': (b' >= (Pos.succ ( TreeMaxIndex p'.2)))%positive).\n    { subst b'. apply Pos.le_ge. apply Pos.le_max_l.\n    }\n    apply Pos.ge_le in Hm; apply Pos.le_succ_l in Hm.\n    apply Pos.lt_gt in Hm; eapply max_works in Hm.\n    apply Pos.ge_le in Hp'; apply Pos.le_succ_l in Hp'.\n    apply Pos.lt_gt in Hp'; eapply max_works in Hp'.\n    extensionality ofs.\n    assert (H:= Mem.nextblock_noaccess m b' ofs Max).\n    assert (Hinvalid: ~ compcert.lib.Coqlib.Plt b' (Mem.nextblock m)).\n    { clear - Heqb Heqb'.\n      subst. intros Hcontra.\n      unfold compcert.lib.Coqlib.Plt in Hcontra.\n      apply Pos.max_lub_lt_iff in Hcontra. destruct Hcontra as [? Hcontra].\n      apply Pos.max_lub_lt_iff in Hcontra. destruct Hcontra as [? Hcontra].\n        by apply Pos.lt_irrefl in Hcontra.\n    }\n    specialize (H Hinvalid).\n    specialize (Hlt b' ofs).\n    rewrite getMaxPerm_correct in Hlt Hm.\n    unfold permission_at in *. rewrite H in Hlt. simpl in Hlt.\n    unfold Maps.PMap.get in Hlt.\n    rewrite Hp' in Hlt.\n    destruct (p'.1 ofs); tauto.\n  Qed.\n\n   Lemma invalid_block_empty:\n    forall pmap m\n      (Hlt: permMapLt pmap (getMaxPerm m)),\n    forall b, ~ Mem.valid_block m b ->\n         forall ofs,\n           pmap !! b ofs = None.\n  Proof.\n    intros.\n    apply Mem.nextblock_noaccess with (ofs := ofs) (k := Max) in H.\n    specialize (Hlt b ofs).\n    rewrite getMaxPerm_correct in Hlt.\n    unfold permission_at in Hlt.\n    rewrite H in Hlt. simpl in Hlt.\n    destruct (pmap !! b ofs); [by exfalso | reflexivity].\n  Qed.\n\n  Definition setPerm (p : option permission) (b : block)\n             (ofs : Z) (pmap : access_map) : access_map :=\n    Maps.PMap.set b (fun ofs' => if compcert.lib.Coqlib.zeq ofs ofs' then\n                                p\n                              else\n                                Maps.PMap.get b pmap ofs')\n                  pmap.\n\n   Fixpoint setPermBlock (p : option permission) (b : block)\n           (ofs : Z) (pmap : access_map) (length: nat): access_map :=\n    match length with\n      0 => pmap\n    | S len =>\n      setPerm p b (ofs + (Z_of_nat len))%Z (setPermBlock p b ofs pmap len)\n    end.\n\n  Lemma setPermBlock_same:\n    forall p b ofs ofs' pmap sz\n      (Hofs: (ofs <= ofs' < ofs + (Z.of_nat sz))%Z),\n      (Maps.PMap.get b (setPermBlock p b ofs pmap sz)) ofs' = p.\n  Proof. intros.\n         generalize dependent ofs'.\n         induction sz; simpl in *; intros.\n         - unfold setPerm.\n           exfalso. destruct Hofs. omega.\n         - unfold setPerm.\n           rewrite PMap.gss.\n           destruct (compcert.lib.Coqlib.zeq (ofs + Z.of_nat sz) ofs');\n             first by (subst; reflexivity).\n           simpl.\n           eapply IHsz.\n           destruct Hofs.\n           split; auto.\n           clear - H0 n.\n           zify. omega.\n  Qed.\n\n  Lemma setPermBlock_other_1:\n    forall p b ofs ofs' pmap sz\n      (Hofs: (ofs' < ofs)%Z \\/ (ofs' >= ofs + (Z.of_nat sz))%Z),\n      (Maps.PMap.get b (setPermBlock p b ofs pmap sz)) ofs' =\n      Maps.PMap.get b pmap ofs'.\n  Proof. intros.\n         generalize dependent ofs'.\n         induction sz; simpl in *; intros; unfold setPerm.\n         - reflexivity.\n         - rewrite Maps.PMap.gss.\n           destruct (compcert.lib.Coqlib.zeq (ofs + Z.of_nat sz) ofs') as [Hcontra | ?].\n           subst. exfalso.\n           destruct Hofs; zify; omega.\n           simpl. eapply IHsz.\n           destruct Hofs; auto.\n           right.\n           zify. omega.\n  Qed.\n\n  Lemma setPermBlock_other_2:\n    forall p b b' ofs ofs' pmap sz,\n      b <> b' ->\n      (Maps.PMap.get b' (setPermBlock p b ofs pmap sz)) ofs' =\n      Maps.PMap.get b' pmap ofs'.\n  Proof. intros.\n         induction sz;\n           simpl;\n           auto.\n         rewrite Maps.PMap.gso; auto.\n  Qed.\n\n  Lemma setPermBlock_or:\n    forall p b ofs sz pmap b' ofs',\n      (setPermBlock p b ofs pmap sz) !! b' ofs' = p \\/\n      (setPermBlock p b ofs pmap sz) !! b' ofs' = pmap !! b' ofs'.\n  Proof.\n    induction sz; intros.\n    - simpl. right; reflexivity.\n    - simpl.\n      unfold setPerm.\n      destruct (Pos.eq_dec b b').\n      + subst.\n        erewrite Maps.PMap.gss by eauto.\n        destruct (Z.eq_dec (ofs + Z.of_nat sz) ofs').\n        * subst.\n          left.\n          erewrite if_true\n            by (now apply compcert.lib.Coqlib.proj_sumbool_is_true).\n          reflexivity.\n        * erewrite if_false\n            by (apply Bool.negb_true_iff; now apply proj_sumbool_is_false).\n          eauto.\n      + erewrite Maps.PMap.gso by eauto.\n        eauto.\n  Qed.\n\n  Fixpoint setPermBlock_var (fp : nat -> option permission) (b : block)\n           (ofs : Z) (pmap : access_map) (length: nat): access_map :=\n    match length with\n      0 => pmap\n    | S len =>\n      setPerm (fp length) b (ofs + (Z_of_nat len))%Z\n              (setPermBlock_var fp b ofs pmap len)\n    end.\n\n  Lemma setPermBlock_var_other_2:\n    forall p b b' ofs ofs' pmap sz,\n      b <> b' ->\n      (Maps.PMap.get b' (setPermBlock_var p b ofs pmap sz)) ofs' =\n      Maps.PMap.get b' pmap ofs'.\n  Proof.\n    intros.\n    induction sz;\n      simpl;\n      auto.\n    rewrite Maps.PMap.gso; auto.\n  Qed.\n\n   Lemma setPermBlock_var_other_1:\n    forall p b ofs ofs' pmap sz\n      (Hofs: (ofs' < ofs)%Z \\/ (ofs' >= ofs + (Z.of_nat sz))%Z),\n      (Maps.PMap.get b (setPermBlock_var p b ofs pmap sz)) ofs' =\n      Maps.PMap.get b pmap ofs'.\n  Proof.\n    intros.\n    generalize dependent ofs'.\n    induction sz; simpl in *; intros; unfold setPerm.\n    - reflexivity.\n    - rewrite Maps.PMap.gss.\n      destruct (compcert.lib.Coqlib.zeq (ofs + Z.of_nat sz) ofs') as [Hcontra | ?].\n      subst. exfalso.\n      destruct Hofs; zify; omega.\n      simpl. eapply IHsz.\n      destruct Hofs; auto.\n      right.\n      zify. omega.\n  Qed.\n\n  Lemma setPermBlock_var_same:\n    forall p b ofs ofs' pmap sz\n      (Hofs: (ofs <= ofs' < ofs + (Z.of_nat sz))%Z),\n      (Maps.PMap.get b (setPermBlock_var p b ofs pmap sz)) ofs' =\n      p (Z.to_nat (ofs' - ofs +1)).\n  Proof.\n    intros.\n    generalize dependent ofs'.\n    induction sz; simpl in *; intros.\n    - unfold setPerm.\n      exfalso. destruct Hofs. omega.\n    - unfold setPerm.\n      rewrite PMap.gss.\n      destruct (compcert.lib.Coqlib.zeq (ofs + Z.of_nat sz) ofs'); simpl.\n      + f_equal. rewrite -e.\n        replace (ofs + Z.of_nat sz - ofs +1 )%Z with\n            (Z.of_nat sz + 1)%Z; try omega.\n        rewrite <- (coqlib4.nat_of_Z_eq sz.+1); f_equal.\n        apply Nat2Z.inj_succ.\n        apply IHsz; simpl. \n        rewrite Zpos_P_of_succ_nat in Hofs.\n        replace (ofs + Z.succ (Z.of_nat sz))%Z with\n            (Z.succ (ofs + Z.of_nat sz))%Z in Hofs;\n          omega.\n  Qed.\n\n  Lemma setPermBlock_setPermBlock_var:\n    forall b ofs sz pmap p,\n      setPermBlock p b ofs pmap sz =\n      setPermBlock_var (fun _ => p) b ofs pmap sz.\n  Proof.\n    intros b ofs sz.\n    generalize dependent ofs.\n    induction sz; intros.\n    - reflexivity.\n    - simpl.\n      rewrite IHsz.\n      reflexivity.\n  Qed.\n\n  Lemma setPermBlock_range_perm:\n    forall (m1 : mem) (b : block) (ofs : Z) (n : nat)\n      perm perm_map,\n      permMapLt\n        (setPermBlock (Some perm) b ofs\n                      perm_map n) (getMaxPerm m1) ->\n      Mem.range_perm m1 b ofs (ofs + Z.of_nat n) Max\n                     perm.\n  Proof.\n    intros m1 b ofs n perm perm_map H0.\n    intros ? ?.\n    specialize (H0 b ofs0).\n    rewrite setPermBlock_same in H0; auto.\n    unfold Mem.perm.\n    rewrite mem_lemmas.po_oo.\n    rewrite getMaxPerm_correct in H0; auto.\n  Qed.\n\n  (*Lemma setPermBlock_var_or:\n    forall p b ofs sz pmap b' ofs',\n      (setPermBlock_var p b ofs pmap sz) !! b' ofs' = p \\/\n      (setPermBlock_var p b ofs pmap sz) !! b' ofs' = pmap !! b' ofs'.\n  Proof.\n    induction sz; intros.\n    - simpl. right; reflexivity.\n    - simpl.\n      unfold setPerm.\n      destruct (Pos.eq_dec b b').\n      + subst.\n        erewrite Maps.PMap.gss by eauto.\n        destruct (Z.eq_dec (ofs + Z.of_nat sz) ofs').\n        * subst.\n          left.\n          erewrite if_true\n            by (now apply compcert.lib.Coqlib.proj_sumbool_is_true).\n          reflexivity.\n        * erewrite if_false\n            by (apply Bool.negb_true_iff; now apply proj_sumbool_is_false).\n          eauto.\n      + erewrite Maps.PMap.gso by eauto.\n        eauto.\n  Qed. *)\n\n\n\n  Lemma permMapCoherence_increase:\n    forall pmap pmap' b ofs sz_nat sz\n      (Hsz: sz = Z.of_nat (sz_nat))\n      (Hcoh: permMapCoherence pmap pmap')\n      (Hreadable: forall ofs', Intv.In ofs' (ofs, ofs + sz)%Z ->\n                          Mem.perm_order' (pmap' !! b ofs') Readable),\n      permMapCoherence pmap (setPermBlock (Some Writable) b ofs pmap' sz_nat).\n  Proof.\n    intros.\n    intros b' ofs'.\n    specialize (Hcoh b' ofs').\n    destruct (Pos.eq_dec b b') as [Heq | Hneq].\n    - subst.\n      destruct (Intv.In_dec ofs' (ofs, ofs + Z.of_nat sz_nat)%Z).\n      + specialize (Hreadable _ i).\n        erewrite setPermBlock_same by eauto.\n        destruct (pmap' !! b' ofs') as [p|]; simpl in *;\n          try (by exfalso);\n          destruct p; inversion Hreadable; subst;\n            destruct (pmap !! b' ofs') as [p1|];\n            try (destruct p1); simpl in *; auto.\n      + destruct sz_nat; first by (simpl; eauto).\n        erewrite setPermBlock_other_1\n          by (eapply Intv.range_notin in n;\n              simpl; eauto; zify; omega).\n        assumption.\n    - erewrite setPermBlock_other_2 by eauto.\n      assumption.\n  Qed.\n\n  (*setPermBlock with a function*)\n  Fixpoint setPermBlockFunc (fp : Z -> option permission) (b : block)\n           (ofs : Z) (pmap : access_map) (length: nat): access_map :=\n    match length with\n      0 => pmap\n    | S len =>\n      setPerm (fp (ofs + (Z_of_nat len))%Z) b (ofs + (Z_of_nat len))%Z (setPermBlockFunc fp b ofs pmap len)\n    end.\n\n  Lemma setPermBlockFunc_same:\n    forall fp b ofs ofs' pmap sz\n      (Hofs: (ofs <= ofs' < ofs + (Z.of_nat sz))%Z),\n      (Maps.PMap.get b (setPermBlockFunc fp b ofs pmap sz)) ofs' = fp ofs'.\n  Proof.\n    intros.\n    generalize dependent ofs'.\n    induction sz; simpl in *; intros.\n    - unfold setPerm.\n      exfalso. destruct Hofs. omega.\n    - unfold setPerm.\n      rewrite PMap.gss.\n      destruct (compcert.lib.Coqlib.zeq (ofs + Z.of_nat sz) ofs');\n        first by (subst; reflexivity).\n      simpl.\n      eapply IHsz.\n      destruct Hofs.\n      split; auto.\n      clear - H0 n.\n      zify. omega.\n  Qed.\n\n  Lemma setPermBlockFunc_other_1:\n    forall fp b ofs ofs' pmap sz\n      (Hofs: (ofs' < ofs)%Z \\/ (ofs' >= ofs + (Z.of_nat sz))%Z),\n      (Maps.PMap.get b (setPermBlock fp b ofs pmap sz)) ofs' =\n      Maps.PMap.get b pmap ofs'.\n  Proof.\n    intros.\n    generalize dependent ofs'.\n    induction sz; simpl in *; intros; unfold setPerm.\n    - reflexivity.\n    - rewrite Maps.PMap.gss.\n      destruct (compcert.lib.Coqlib.zeq (ofs + Z.of_nat sz) ofs') as [Hcontra | ?].\n      subst. exfalso.\n      destruct Hofs; zify; omega.\n      simpl. eapply IHsz.\n      destruct Hofs; auto.\n      right.\n      zify. omega.\n  Qed.\n\n  Lemma setPermBlockFunc_other_2:\n    forall fp b b' ofs ofs' pmap sz,\n      b <> b' ->\n      (Maps.PMap.get b' (setPermBlock fp b ofs pmap sz)) ofs' =\n      Maps.PMap.get b' pmap ofs'.\n  Proof.\n    intros.\n    induction sz;\n      simpl;\n      auto.\n    rewrite Maps.PMap.gso; auto.\n  Qed.\n\n  Lemma setPermBlock_coherent:\n    forall pmap pmap' b ofs sz\n      (Hcoh: permMapCoherence pmap pmap')\n      (Hnonempty: forall ofs', Intv.In ofs' (ofs, ofs + Z.of_nat sz)%Z ->\n                          ~ Mem.perm_order' (pmap !! b ofs') Readable),\n      permMapCoherence pmap (setPermBlock (Some Writable) b ofs pmap' sz).\n  Proof.\n    intros.\n    intros b' ofs'.\n    specialize (Hcoh b' ofs').\n    destruct (Pos.eq_dec b b').\n    - subst.\n      destruct (Intv.In_dec ofs' (ofs, (ofs + Z.of_nat sz)%Z)).\n      + erewrite setPermBlock_same by eauto.\n        specialize (Hnonempty _ i).\n        destruct (pmap !! b' ofs') as [p|] eqn:Hpmap'; simpl; auto;\n          destruct p; simpl in Hnonempty; eauto using perm_order.\n      + destruct sz;\n          first by (simpl; assumption).\n        erewrite setPermBlock_other_1.\n        assumption.\n        apply Intv.range_notin in n; eauto.\n        simpl. rewrite Zpos_P_of_succ_nat. omega.\n    - erewrite setPermBlock_other_2 by eauto.\n      assumption.\n  Qed.\n\n  (** Apply a [delta_map] to an [access_map]*)\n  Definition computeMap (pmap : access_map) (delta : delta_map) : access_map :=\n    (pmap.1,\n     @Maps.PTree.combine (Z -> option permission)\n                         (Z -> option (option permission))\n                         (Z -> option permission)\n                         (fun p1 pd => match pd, p1 with\n                                    | Some pd', Some p1' =>\n                                      Some (fun z => match pd' z with\n                                                    Some pd'' => pd''\n                                                  | _ => p1' z\n                                                  end)\n                                    | Some pd', None =>\n                                      Some (fun z => match pd' z with\n                                                    Some pd'' => pd''\n                                                  | _ => pmap.1 z\n                                                  end)\n                                    | None, _ => p1\n                                    end)\n                         pmap.2 delta).\n\n  (** If the [delta_map] changes the [access_map] at a specific [address] *)\n  Lemma computeMap_1 :\n    forall (pmap : access_map) (dmap : delta_map) b ofs df (p : option permission),\n      Maps.PTree.get b dmap = Some df ->\n      df ofs = Some p ->\n      Maps.PMap.get b (computeMap pmap dmap) ofs = p.\n  Proof.\n    intros pmap dmap b ofs df p Hdmap Hdf.\n    unfold computeMap, Maps.PMap.get. simpl.\n    rewrite Maps.PTree.gcombine; try reflexivity.\n    rewrite Hdmap.\n    destruct ((pmap.2) ! b);\n      by rewrite Hdf.\n  Qed.\n\n  (** If the [delta_map] changes the [access_map] at this [block] but not at this [offset] *)\n  Lemma computeMap_2 :\n    forall (pmap : access_map) (dmap : delta_map) b ofs df,\n      Maps.PTree.get b dmap = Some df ->\n      df ofs = None ->\n      Maps.PMap.get b (computeMap pmap dmap) ofs = Maps.PMap.get b pmap ofs.\n  Proof.\n    intros pmap dmap b ofs df Hdmap Hdf.\n    unfold computeMap, Maps.PMap.get. simpl.\n    rewrite Maps.PTree.gcombine; try reflexivity.\n    rewrite Hdmap.\n    destruct ((pmap.2) ! b);\n      by rewrite Hdf.\n  Qed.\n\n  (** If the [delta_map] does not change the [access_map] at this [block] *)\n  Lemma computeMap_3 :\n    forall (pmap : access_map) (dmap : delta_map) b ofs,\n      Maps.PTree.get b dmap = None ->\n      Maps.PMap.get b (computeMap pmap dmap) ofs = Maps.PMap.get b pmap ofs.\n  Proof.\n    intros pmap dmap b ofs Hdmap.\n    unfold computeMap, Maps.PMap.get. simpl.\n    rewrite Maps.PTree.gcombine; try reflexivity.\n    rewrite Hdmap.\n      by reflexivity.\n  Qed.\n  \n      Lemma dmap_get_copmute_Some:\n        forall C A b ofs p,\n          dmap_get A b ofs = Some p ->\n          (computeMap C A) !! b ofs = p.\n      Proof.\n        intros; rewrite dmap_get_bit in H.\n        unfold dmap_get' in H.\n        destruct (A ! b) eqn:Ab; try solve[inversion H].\n        destruct (o ofs) eqn:oofs; try solve[inversion H].\n        erewrite computeMap_1; eauto.\n        rewrite oofs; assumption.\n      Qed.\n      Lemma dmap_get_copmute_None:\n        forall C A b ofs,\n          dmap_get A b ofs = None ->\n          (computeMap C A) !! b ofs = C !! b ofs.\n      Proof.\n        intros; rewrite dmap_get_bit in H.\n        unfold dmap_get' in H.\n        destruct (A ! b) eqn:Ab.\n        destruct (o ofs) eqn:oofs; try solve[inversion H].\n        - erewrite computeMap_2; eauto.\n        - erewrite computeMap_3; eauto.\n      Qed.\n  \n  Lemma computeMap_backwards:\n    forall (pmap : access_map) (dmap : delta_map)\n      b ofs (p : option permission),\n      (computeMap pmap dmap) !! b ofs = p ->\n      (fun _=> None, dmap) !! b ofs = Some p \\/\n      (fun _=> None, dmap) !! b ofs = None /\\\n      pmap !! b ofs = p.\n  Proof.\n    intros.\n    unfold PMap.get; simpl.\n    destruct (dmap ! b) eqn:HH1.\n    1: destruct (o ofs) eqn:HH2.\n    - left. eapply computeMap_1 in HH1; eauto.\n      rewrite HH1 in H; inversion H; auto.\n    - right. split; auto.\n      eapply computeMap_2 in HH1; eauto.\n      rewrite HH1 in H; inversion H; auto.\n    - right; split; auto.\n      eapply computeMap_3 in HH1; eauto.\n      rewrite HH1 in H; inversion H; auto.\n      Unshelve.\n      all: assumption.\n  Qed.\n  \n  Import Maps BlockList.\n\n  Definition maxF (f : Z -> perm_kind -> option permission) :=\n    fun ofs k => match k with\n              | Max => Some Freeable\n              | Cur => f ofs k\n              end.\n\n  Definition allF (f : Z -> perm_kind -> option permission) :=\n    fun (_ : Z) (_ : perm_kind) => Some Freeable.\n\n  Fixpoint PList (f : (Z -> perm_kind -> option permission) ->\n                      Z -> perm_kind -> option permission)\n           l m : list (positive * (Z -> perm_kind -> option permission)) :=\n    match l with\n      | nil => nil\n      | x :: l =>\n        (Pos.of_nat x, f (PMap.get (Pos.of_nat x) m)) :: (PList f l m)\n  end.\n\n  Lemma PList_app :\n    forall l m x f,\n      (PList f l m) ++ ((Pos.of_nat x,\n                                f (PMap.get (Pos.of_nat x) m)) :: nil) =\n      PList f (l ++ (x :: nil)) m.\n  Proof.\n    intro l. induction l; intros.\n    reflexivity.\n    simpl. apply f_equal.\n    auto.\n  Qed.\n\n  Lemma PList_cons :\n    forall f l m x,\n      (Pos.of_nat x, f (PMap.get (Pos.of_nat x) m)) :: (PList f l m) =\n      PList f (x :: l) m.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma PList_correct :\n    forall f l m k v\n           (HInl: List.In k l)\n           (HInMap: List.In (Pos.of_nat k, v) (PTree.elements m.2)),\n      List.In (Pos.of_nat k, f v) (PList f l m).\n  Proof.\n    intros f l m. induction l; intros; inversion HInl.\n    - subst. simpl. apply PTree.elements_complete in HInMap.\n      unfold PMap.get. rewrite HInMap. now left.\n    - simpl. right. auto.\n  Qed.\n\n  Lemma PList_mkBlock_complete :\n    forall f k v m n\n           (Hk: k > 0)\n           (HIn1: List.In (Pos.of_nat k, v) (PList f (mkBlockList n) m)),\n      List.In k (mkBlockList n).\n  Proof.\n    intros.\n    induction n.\n    simpl in *. auto.\n    destruct n. simpl in HIn1. auto.\n    rewrite <- mkBlockList_unfold' in HIn1.\n    rewrite <- PList_cons in HIn1.\n    apply List.in_inv in HIn1.\n    destruct HIn1 as [Heq | HIn1].\n    assert (Heqn: Pos.of_nat (S n) = Pos.of_nat k) by (inversion Heq; auto).\n    apply Nat2Pos.inj_iff in Heqn.\n    subst. simpl; auto.\n    auto. intro Hcontra. subst. auto.\n    rewrite <- mkBlockList_unfold'.\n    right. auto.\n  Qed.\n\n  Lemma PList_mkBlock_det :\n    forall n f k v v' m\n           (HIn1: List.In (Pos.of_nat k, v) (PList f (mkBlockList n) m))\n           (HIn2: List.In (Pos.of_nat k, v') (PList f (mkBlockList n) m)),\n      v = v'.\n  Proof.\n    intros n. induction n.\n    - simpl. intros. exfalso. auto.\n    - intros.\n      destruct n. simpl in HIn1. exfalso; auto.\n      destruct n. simpl in HIn1, HIn2.\n      destruct HIn1 as [HIn1 | HIn1];\n        destruct HIn2 as [HIn2 | HIn2];\n        inversion HIn1; inversion HIn2; now subst.\n      rewrite <- mkBlockList_unfold' in HIn1, HIn2.\n      rewrite <- PList_cons in HIn1, HIn2.\n      apply List.in_inv in HIn1.\n      apply List.in_inv in HIn2.\n      destruct HIn1 as [Heq1 | HIn1].\n      + destruct HIn2 as [Heq2 | HIn2].\n        inversion Heq1; inversion Heq2. reflexivity.\n        assert (Heq:Pos.of_nat (S (S n)) =\n                    Pos.of_nat k /\\ f (m !! (Pos.of_nat (S (S n)))) = v)\n          by (inversion Heq1; auto).\n        destruct Heq as [HEqk Hv].\n        rewrite <- HEqk in HIn2.\n        exfalso.\n        clear Hv HEqk Heq1 IHn v k.\n        apply PList_mkBlock_complete in HIn2.\n        eapply mkBlockList_not_in in HIn2; eauto. auto.\n      + destruct HIn2 as [Heq | HIn2].\n        assert (Heq':Pos.of_nat (S (S n)) = Pos.of_nat k) by (inversion Heq; auto).\n        rewrite <- Heq' in HIn1.\n        apply PList_mkBlock_complete in HIn1; auto.\n        apply mkBlockList_not_in in HIn1; auto. now exfalso.\n        eauto.\n  Qed.\n\n  Fixpoint canonicalPTree (l : list (positive * (Z -> perm_kind -> option permission))) :=\n    match l with\n      | nil => PTree.empty _\n      | x :: l =>\n        PTree.set (fst x) (snd x) (canonicalPTree l)\n    end.\n\n  Lemma canonicalPTree_elements :\n    forall l x\n           (Hin: List.In x (PTree.elements (canonicalPTree l))),\n      List.In x l.\n  Proof.\n    intro l.\n    induction l; intros; auto.\n    simpl.\n    simpl in Hin.\n    unfold PTree.elements in Hin.\n    destruct x as [p o].\n    apply PTree.elements_complete in Hin.\n    destruct (Pos.eq_dec a.1 p).\n    - subst. rewrite PTree.gss in Hin. inversion Hin; subst.\n      left.  destruct a; reflexivity.\n    - rewrite PTree.gso in Hin; auto.\n      apply PTree.elements_correct in Hin. right. auto.\n  Qed.\n\n  Lemma canonicalPTree_get_complete :\n    forall l m k f fn\n           (HGet: (canonicalPTree (PList fn l m)) ! k = Some f),\n      List.In (k, f) (PList fn l m).\n  Proof.\n    intro l. induction l.\n    simpl. intros. rewrite PTree.gempty in HGet. discriminate.\n    intros.\n    rewrite <- PList_cons in HGet.\n    apply PTree.elements_correct in HGet.\n    apply canonicalPTree_elements in HGet.\n    destruct (List.in_inv HGet) as [Heq | Hin].\n    inversion Heq; subst. simpl; auto.\n    auto.\n  Qed.\n\n  Lemma canonicalPTree_get_sound :\n    forall n m k fn\n           (Hk: k > 0)\n           (Hn: n > 1)\n           (HGet: (canonicalPTree (PList fn (mkBlockList n) m)) ! (Pos.of_nat k) = None),\n      ~ List.In k (mkBlockList n).\n  Proof.\n    intros.\n    destruct n. simpl; auto.\n    induction n. simpl; auto.\n    intro HIn.\n    rewrite <- mkBlockList_unfold' in HGet, HIn.\n    destruct (List.in_inv HIn) as [? | HIn']; subst.\n    rewrite <- PList_cons in HGet.\n    unfold canonicalPTree in HGet. fold canonicalPTree in HGet.\n    rewrite PTree.gss in HGet. discriminate.\n    destruct n. simpl in *; auto.\n    apply IHn. auto. rewrite <- PList_cons in HGet.\n    unfold canonicalPTree in HGet. fold canonicalPTree in HGet.\n    apply mkBlockList_range in HIn'.\n    assert (k <> S (S n)). destruct HIn'. intros Hcontra; subst. auto.\n    rewrite ltnn in H. auto.\n    rewrite PTree.gso in HGet.\n    assumption.\n    intros HContra.\n    unfold fst in HContra.\n    apply Nat2Pos.inj_iff in HContra. auto. intros ?; subst; auto.\n    intros ?; subst. discriminate.\n    assumption.\n  Qed.\n\n  Definition canonicalPMap fn n m : Maps.PMap.t (Z -> perm_kind -> option permission) :=\n    let l := mkBlockList n in\n    (fun _ _ => None, canonicalPTree (PList fn l m)).\n\n  Lemma canonicalPMap_sound :\n    forall k n m fn\n           (Hk : k > 0)\n           (Hkn : k < n),\n      fn (m !! (Pos.of_nat k)) = (canonicalPMap fn n m) !! (Pos.of_nat k).\n  Proof.\n    intros.\n    unfold PMap.get.\n    destruct (((canonicalPMap fn n m).2) ! (Pos.of_nat k)) as [f|] eqn:HGet.\n    - apply PTree.elements_correct in HGet.\n      unfold canonicalPMap in HGet.  simpl in HGet.\n      destruct ((m.2) ! (Pos.of_nat k)) eqn:HGet'.\n      + apply PTree.elements_correct in HGet'.\n        apply canonicalPTree_elements in HGet.\n        apply PList_correct with (f := fn) (l := mkBlockList n) in HGet'.\n        eapply PList_mkBlock_det; eauto.\n        apply PList_mkBlock_complete in HGet. assumption.\n        assumption.\n      + apply PTree.elements_complete in HGet.\n        apply canonicalPTree_get_complete in HGet.\n        induction (mkBlockList n). simpl in HGet. by exfalso.\n        simpl in HGet. destruct HGet as [Heq | Hin].\n        inversion Heq; subst.\n        unfold PMap.get. rewrite <- H0 in HGet'. rewrite HGet'. reflexivity.\n        auto.\n    - unfold canonicalPMap in HGet. simpl in HGet.\n      apply canonicalPTree_get_sound in HGet.\n      destruct n. exfalso. auto. destruct n. exfalso. ssromega.\n      exfalso. apply HGet. apply mkBlockList_include; auto.\n      assumption. clear HGet.\n      eapply leq_ltn_trans; eauto.\n  Qed.\n\n  Lemma canonicalPMap_default :\n    forall n k m fn\n           (Hkn : k >= n),\n      (canonicalPMap fn n m) !! (Pos.of_nat k) = fun _ _ => None.\n  Proof.\n    intro. induction n; intros. unfold canonicalPMap. simpl.\n    unfold PMap.get.\n    rewrite PTree.gempty. reflexivity.\n    assert (Hkn': n <= k) by ssromega.\n    unfold canonicalPMap.\n    destruct n. simpl. unfold PMap.get. simpl. rewrite PTree.gempty. reflexivity.\n    unfold PMap.get.\n    rewrite <- mkBlockList_unfold'. rewrite <- PList_cons.\n    unfold canonicalPTree.\n    rewrite PTree.gso. fold canonicalPTree.\n    specialize (IHn _ m fn Hkn').\n    unfold canonicalPMap, PMap.get, snd in IHn.\n    destruct ((canonicalPTree (PList fn (mkBlockList n.+1) m)) ! (Pos.of_nat k)); auto.\n    unfold fst. intros HContra. apply Nat2Pos.inj_iff in HContra; subst; ssromega.\n  Qed.\n\n  Definition setMaxPerm (m : mem) : mem.\n  Proof.\n    refine (Mem.mkmem (Mem.mem_contents m)\n                      (canonicalPMap maxF (Pos.to_nat (Mem.nextblock m))\n                                     (Mem.mem_access m))\n                      (Mem.nextblock m) _ _ _).\n      { intros.\n        replace b with (Pos.of_nat (Pos.to_nat b)) by (rewrite Pos2Nat.id; done).\n        destruct (leq (Pos.to_nat (Mem.nextblock m)) (Pos.to_nat b)) eqn:Hbn.\n          by rewrite canonicalPMap_default.\n          erewrite <- canonicalPMap_sound. simpl.\n          match goal with\n          | [|- match ?Expr with _ => _ end] => destruct Expr\n          end; constructor.\n          apply/ltP/Pos2Nat.is_pos.\n          ssromega. }\n      { intros b ofs k H.\n        replace b with (Pos.of_nat (Pos.to_nat b)) by (rewrite Pos2Nat.id; done).\n        erewrite canonicalPMap_default. reflexivity.\n        apply Pos.le_nlt in H.\n        apply/leP.\n        now apply Pos2Nat.inj_le.\n      }\n      { apply Mem.contents_default. }\n  Defined.\n\n  Lemma setMaxPerm_Max :\n    forall m b ofs,\n      (Mem.valid_block m b ->\n       permission_at (setMaxPerm m) b ofs Max = Some Freeable) /\\\n      (~Mem.valid_block m b ->\n       permission_at (setMaxPerm m) b ofs Max = None).\n  Proof.\n    intros.\n    assert (Hb : b = Pos.of_nat (Pos.to_nat b))\n      by (by rewrite Pos2Nat.id).\n    split.\n    { intros Hvalid. unfold permission_at,  setMaxPerm. simpl.\n      rewrite Hb.\n      rewrite <- canonicalPMap_sound.\n      reflexivity.\n      assert (H := Pos2Nat.is_pos b). ssromega.\n      apply Pos2Nat.inj_lt in Hvalid. ssromega.\n    }\n    { intros Hinvalid.\n      unfold permission_at, setMaxPerm. simpl.\n      rewrite Hb.\n      rewrite canonicalPMap_default. reflexivity.\n      apply Pos.le_nlt in Hinvalid.\n      apply Pos2Nat.inj_le in Hinvalid. ssromega.\n    }\n  Qed.\n\n   Lemma setMaxPerm_MaxV :\n    forall m b ofs,\n      Mem.valid_block m b ->\n       permission_at (setMaxPerm m) b ofs Max = Some Freeable.\n  Proof.\n    intros;\n    assert (Hmax := setMaxPerm_Max m b ofs);\n    destruct Hmax; auto.\n  Qed.\n\n  Lemma setMaxPerm_MaxI :\n    forall m b ofs,\n      ~ Mem.valid_block m b ->\n      permission_at (setMaxPerm m) b ofs Max = None.\n  Proof.\n    intros;\n    assert (Hmax := setMaxPerm_Max m b ofs);\n    destruct Hmax; auto.\n  Qed.\n\n  Lemma setMaxPerm_Cur :\n    forall m b ofs,\n      permission_at (setMaxPerm m) b ofs Cur = permission_at m b ofs Cur.\n  Proof.\n    intros. unfold setMaxPerm, permission_at. simpl.\n    assert (Hb : b = Pos.of_nat (Pos.to_nat b))\n      by (by rewrite Pos2Nat.id).\n    rewrite Hb.\n    destruct (compcert.lib.Coqlib.plt b (Mem.nextblock m)) as [Hvalid | Hinvalid].\n    rewrite <- canonicalPMap_sound. reflexivity.\n    assert (H := Pos2Nat.is_pos b). ssromega.\n    apply Pos2Nat.inj_lt in Hvalid. ssromega.\n    rewrite canonicalPMap_default.\n    apply Mem.nextblock_noaccess with (ofs := ofs) (k := Cur) in Hinvalid.\n    rewrite <- Hb.\n    rewrite Hinvalid. reflexivity.\n    apply Pos.le_nlt in Hinvalid.\n    apply Pos2Nat.inj_le in Hinvalid. ssromega.\n  Qed.\n\n  Definition makeCurMax_map (mem_access:PMap.t (Z -> perm_kind -> option permission)):\n    PMap.t (Z -> perm_kind -> option permission):=\n    PMap.map (fun f => fun z k => f z Max) mem_access.\n\n\n  Definition makeCurMax (m:mem): mem.\n  apply (Mem.mkmem (Mem.mem_contents m)\n                   (makeCurMax_map (Mem.mem_access m))\n                   (Mem.nextblock m)).\n  - intros. unfold makeCurMax_map; simpl. rewrite PMap.gmap.\n    apply po_refl.\n  - intros. unfold makeCurMax_map; simpl. rewrite PMap.gmap.\n    apply Mem.nextblock_noaccess; assumption.\n  - intros; apply Mem.contents_default.\n  Defined.\n\n  Lemma makeCurMax_correct :\n    forall m b ofs k,\n      permission_at m b ofs Max = permission_at (makeCurMax m) b ofs k.\n  Proof.\n    intros.\n    unfold permission_at, makeCurMax, makeCurMax_map.\n    simpl;\n      by rewrite Maps.PMap.gmap.\n  Qed.\n\n  Lemma makeCurMax_valid :\n    forall m b,\n      Mem.valid_block m b <-> Mem.valid_block (makeCurMax m) b.\n  Proof.\n    intros;\n    unfold Mem.valid_block, makeCurMax; simpl;\n      by auto.\n  Qed.\n\n  Definition restrPermMap p' m (Hlt: permMapLt p' (getMaxPerm m)) : mem.\n  Proof.\n    refine ({|\n               Mem.mem_contents := Mem.mem_contents m;\n               Mem.mem_access :=\n                 (fun ofs k =>\n                    match k with\n                      | Cur => None\n                      | Max => fst (Mem.mem_access m) ofs k\n                    end, Maps.PTree.map (fun b f =>\n                                           fun ofs k =>\n                                             match k with\n                                               | Cur =>\n                                                 (Maps.PMap.get b p') ofs\n                                               | Max =>\n                                                 f ofs Max\n                                             end) (Mem.mem_access m).2);\n               Mem.nextblock := Mem.nextblock m;\n               Mem.access_max := _;\n               Mem.nextblock_noaccess := _;\n               Mem.contents_default := Mem.contents_default m |}).\n    - unfold permMapLt in Hlt.\n      assert (Heq: forall b ofs, Maps.PMap.get b (getMaxPerm m) ofs =\n                            Maps.PMap.get b (Mem.mem_access m) ofs Max).\n      { unfold getMaxPerm. intros.\n        rewrite Maps.PMap.gmap. reflexivity. }\n      intros.\n      specialize (Hlt b ofs).\n      specialize (Heq b ofs).\n      unfold getMaxPerm in Hlt.\n      unfold Maps.PMap.get in *. simpl in *.\n      rewrite Maps.PTree.gmap; simpl.\n      match goal with\n        | [|- context[match compcert.lib.Coqlib.option_map ?Expr1 ?Expr2  with _ => _ end]] =>\n          destruct (compcert.lib.Coqlib.option_map Expr1 Expr2) as [f|] eqn:?\n      end; auto; unfold compcert.lib.Coqlib.option_map in Heqo.\n      destruct (Maps.PTree.get b (Mem.mem_access m).2) eqn:?; try discriminate.\n      + inversion Heqo; subst; clear Heqo.\n        rewrite Heq in Hlt. auto.\n      + unfold Mem.perm_order''. by destruct ((Mem.mem_access m).1 ofs Max).\n    - intros b ofs k Hnext.\n    - unfold permMapLt in Hlt.\n      assert (Heq: forall b ofs, Maps.PMap.get b (getMaxPerm m) ofs =\n                            Maps.PMap.get b (Mem.mem_access m) ofs Max).\n      { unfold getMaxPerm. intros.\n        rewrite Maps.PMap.gmap. reflexivity. }\n      specialize (Hlt b ofs).\n      specialize (Heq b ofs).\n      unfold Maps.PMap.get in *.\n      simpl in *.\n      rewrite Maps.PTree.gmap; simpl.\n      assert (H := Mem.nextblock_noaccess m).\n      specialize (H b). unfold Maps.PMap.get in H.\n      match goal with\n        | [|- context[match compcert.lib.Coqlib.option_map ?Expr1 ?Expr2  with _ => _ end]] =>\n          destruct (compcert.lib.Coqlib.option_map Expr1 Expr2) as [f|] eqn:?\n      end; auto; unfold compcert.lib.Coqlib.option_map in Heqo;\n      destruct (Maps.PTree.get b (Mem.mem_access m).2) eqn:Heqo2; try discriminate.\n      inversion Heqo. subst f. clear Heqo.\n      destruct k; auto.\n      rewrite Heq in Hlt.\n      specialize (H ofs Max). rewrite H in Hlt; auto.\n      unfold Mem.perm_order'' in Hlt. destruct (Maps.PTree.get b p'.2).\n      destruct (o0 ofs); tauto.\n      destruct (p'.1 ofs); tauto.\n      rewrite H; auto. destruct k; auto.\n  Defined.\n\nLemma restrPermMap_irr:\n      forall p1 p2 m1 m2\n        (P1: permMapLt p1 (getMaxPerm m1))\n        (P2: permMapLt p2 (getMaxPerm m2)),\n        p1 = p2 -> m1 = m2 ->\n        restrPermMap P1 = restrPermMap P2.\n    Proof.\n      intros; subst.\n      replace P1 with P2.\n      reflexivity.\n      apply proof_irrelevance.\n    Qed.\n    Lemma restrPermMap_ext:\n      forall p1 p2 m\n        (P1: permMapLt p1 (getMaxPerm m))\n        (P2: permMapLt p2 (getMaxPerm m)),\n        (forall b, (p1 !! b) = (p2 !! b)) ->\n        restrPermMap P1 = restrPermMap P2.\n    Proof.\n      intros; subst.\n      remember (restrPermMap P1) as M1.\n      remember (restrPermMap P2) as M2.\n      assert (Mem.mem_contents M1 = Mem.mem_contents M2) by\n          (subst; reflexivity).\n      assert (Mem.nextblock M1 = Mem.nextblock M2) by\n          (subst; reflexivity).\n      assert (Mem.mem_access M1 = Mem.mem_access M2).\n      {\n        subst. simpl.\n        f_equal. f_equal.\n        simpl.\n        do 4 (apply functional_extensionality; intro).\n        destruct x2; try rewrite H; reflexivity.\n      }\n      subst.\n      destruct (restrPermMap P1);\n        destruct (restrPermMap P2); simpl in *.\n      subst. f_equal;\n      apply proof_irrelevance.\n    Qed.\n\n  Lemma restrPermMap_nextblock :\n    forall p' m (Hlt: permMapLt p' (getMaxPerm m)),\n      Mem.nextblock (restrPermMap Hlt) = Mem.nextblock m.\n  Proof.\n    intros. unfold restrPermMap. reflexivity.\n  Qed.\n\n  Lemma restrPermMap_valid :\n    forall p' m (Hlt: permMapLt p' (getMaxPerm m)) b,\n      Mem.valid_block (restrPermMap Hlt) b <-> Mem.valid_block m b.\n  Proof.\n    intros. unfold Mem.valid_block. rewrite restrPermMap_nextblock.\n      by split.\n  Qed.\n\n  Lemma restrPermMap_contents :\n    forall p' m (Hlt: permMapLt p' (getMaxPerm m)),\n      contents_at (restrPermMap Hlt) = contents_at m.\n  Proof.\n    intros. unfold restrPermMap. reflexivity.\n  Qed.\n\n  Lemma restrPermMap_max :\n    forall p' m (Hlt: permMapLt p' (getMaxPerm m)),\n      max_access_at (restrPermMap Hlt) = max_access_at m.\n  Proof.\n    intros.\n    unfold max_access_at; simpl. unfold Memory.access_at.\n    extensionality loc; simpl.\n    unfold Maps.PMap.get at 1; simpl.\n    rewrite Maps.PTree.gmap.\n    unfold Maps.PMap.get at 2; simpl.\n    destruct (((Mem.mem_access m).2) ! (loc.1)) eqn:AA; reflexivity.\n  Qed.\n\n  Lemma getMax_restr :\n    forall p' m (Hlt: permMapLt p' (getMaxPerm m)) b,\n      (getMaxPerm (restrPermMap Hlt)) !!  b = (getMaxPerm m) !! b.\n  Proof.\n    intros.\n    unfold getMaxPerm.\n    unfold Maps.PMap.get.\n    simpl. do 2 rewrite Maps.PTree.gmap1.\n    unfold compcert.lib.Coqlib.option_map.\n    rewrite Maps.PTree.gmap.\n    unfold compcert.lib.Coqlib.option_map.\n    simpl.\n    destruct ((Mem.mem_access m).2 ! b);\n      by auto.\n  Qed.\n\n  Lemma restrPermMap_irr' : forall p' p'' m\n                             (Hlt : permMapLt p' (getMaxPerm m))\n                             (Hlt': permMapLt p'' (getMaxPerm m))\n                             (Heq_new: p' = p''),\n                             restrPermMap Hlt = restrPermMap Hlt'.\n  Proof.\n    intros. subst.\n    apply f_equal. by apply proof_irr.\n  Qed.\n\n  Lemma restrPermMap_disjoint_inv:\n    forall (mi mj m : mem) (pi pj : access_map)\n      (Hltj: permMapLt pj (getMaxPerm m))\n      (Hlti: permMapLt pi (getMaxPerm m))\n      (Hdisjoint: permMapsDisjoint pi pj)\n      (Hrestrj: restrPermMap Hltj = mj)\n      (Hrestri: restrPermMap Hlti = mi),\n      permMapsDisjoint (getCurPerm mi) (getCurPerm mj).\n  Proof.\n    intros. rewrite <- Hrestri. rewrite <- Hrestrj.\n    unfold restrPermMap, getCurPerm, permMapsDisjoint. simpl in *.\n    intros b ofs.\n    do 2 rewrite Maps.PMap.gmap.\n    clear Hrestrj Hrestri.\n    unfold permMapLt, Mem.perm_order'' in *.\n    specialize (Hltj b ofs); specialize (Hlti b ofs).\n    unfold getMaxPerm in *; simpl in *.\n    rewrite Maps.PMap.gmap in Hlti, Hltj.\n    unfold permMapsDisjoint, Maps.PMap.get in *; simpl in *.\n    do 2 rewrite Maps.PTree.gmap. unfold compcert.lib.Coqlib.option_map.\n    specialize (Hdisjoint b ofs).\n    assert (Hnone: (Mem.mem_access m).1 ofs Max = None)\n      by (assert (Hcan_m := Max_isCanonical m);\n           unfold isCanonical in Hcan_m; simpl in Hcan_m;\n            by apply equal_f with (x:=ofs) in Hcan_m).\n    destruct (Maps.PTree.get b (Mem.mem_access m).2) eqn:?; auto.\n    rewrite Hnone in Hlti, Hltj;\n      destruct (Maps.PTree.get b pi.2)\n      as [f1 |] eqn:?;\n                destruct (Maps.PTree.get b pj.2) as [f2|] eqn:?;\n      repeat match goal with\n               | [H: match ?Expr with _ => _ end |- _] => destruct Expr\n             end; tauto.\n  Qed.\n\n  Lemma restrPermMap_correct :\n    forall p' m (Hlt: permMapLt p' (getMaxPerm m))\n      b ofs,\n      permission_at (restrPermMap Hlt) b ofs Max =\n      Maps.PMap.get b (getMaxPerm m) ofs /\\\n      permission_at (restrPermMap Hlt) b ofs Cur =\n      Maps.PMap.get b p' ofs.\n  Proof.\n    intros.\n    assert (Hcan_p' := canonical_lt Hlt).\n    assert (Hcan_m := Max_isCanonical m).\n    unfold restrPermMap, getMaxPerm, permission_at. simpl.\n    rewrite Maps.PMap.gmap. split;\n      unfold permMapLt in Hlt; specialize (Hlt b ofs);\n      unfold Maps.PMap.get; simpl; rewrite Maps.PTree.gmap;\n      unfold compcert.lib.Coqlib.option_map; simpl;\n      destruct (Maps.PTree.get b (Mem.mem_access m).2) eqn:?; auto.\n    unfold Maps.PMap.get in Hlt.\n    unfold isCanonical in *.\n    destruct (Maps.PTree.get b p'.2) eqn:?; [| by rewrite Hcan_p'].\n    rewrite Hcan_m in Hlt.\n    unfold getMaxPerm in Hlt. rewrite Maps.PTree.gmap1 in Hlt.\n    unfold compcert.lib.Coqlib.option_map in Hlt.\n    rewrite Heqo in Hlt. simpl in Hlt.\n    destruct (o ofs); tauto.\n  Qed.\n\n  Corollary restrPermMap_Cur :\n    forall p' m (Hlt: permMapLt p' (getMaxPerm m)) b ofs,\n      permission_at (restrPermMap Hlt) b ofs Cur =\n      Maps.PMap.get b p' ofs.\n  Proof.\n    intros.\n    assert (Heq := restrPermMap_correct Hlt b ofs).\n    by destruct Heq.\n  Qed.\n\n  Corollary restrPermMap_Max :\n    forall p' m (Hlt: permMapLt p' (getMaxPerm m)) b ofs,\n      permission_at (restrPermMap Hlt) b ofs Max =\n      Maps.PMap.get b (getMaxPerm m) ofs.\n  Proof.\n    intros.\n    assert (Heq := restrPermMap_correct Hlt b ofs).\n      by destruct Heq.\n  Qed.\n\n\n  Lemma restrPermMap_can : forall (p : access_map) (m m': mem)\n                             (Hlt: permMapLt p (getMaxPerm m))\n                             (Hrestrict: restrPermMap Hlt = m'),\n      isCanonical (getCurPerm m').\n  Proof.\n    intros. subst.\n    unfold restrPermMap, getCurPerm, isCanonical in *. simpl in *.\n    auto.\n  Defined.\n\n  Lemma restrPermMap_can_max : forall (p : access_map) (m m': mem)\n                                 (Hlt: permMapLt p (getMaxPerm m))\n                                 (Hrestrict: restrPermMap Hlt = m'),\n      isCanonical (getMaxPerm m').\n  Proof.\n    intros. subst.\n    assert (Hcanonical := Max_isCanonical m).\n    unfold restrPermMap, getMaxPerm, isCanonical in *. simpl in *.\n    auto.\n  Defined.\n\n  Definition erasePerm (m : mem) : mem.\n  Proof.\n    refine (Mem.mkmem (Mem.mem_contents m)\n                      (canonicalPMap allF (Pos.to_nat (Mem.nextblock m))\n                                     (Mem.mem_access m))\n                      (Mem.nextblock m) _ _ _).\n      { intros.\n        replace b with (Pos.of_nat (Pos.to_nat b)) by (rewrite Pos2Nat.id; done).\n        destruct (leq (Pos.to_nat (Mem.nextblock m)) (Pos.to_nat b)) eqn:Hbn.\n          by rewrite canonicalPMap_default.\n          erewrite <- canonicalPMap_sound. simpl.\n          constructor.\n          apply/ltP/Pos2Nat.is_pos.\n          ssromega. }\n      { intros b ofs k H.\n        replace b with (Pos.of_nat (Pos.to_nat b)) by (rewrite Pos2Nat.id; done).\n        erewrite canonicalPMap_default. reflexivity.\n        apply Pos.le_nlt in H.\n        apply/leP.\n        now apply Pos2Nat.inj_le.\n      }\n      { apply Mem.contents_default. }\n  Defined.\n\n  Lemma erasePerm_Perm :\n    forall m b ofs k ,\n      (Mem.valid_block m b ->\n       permission_at (erasePerm m) b ofs k = Some Freeable) /\\\n      (~Mem.valid_block m b ->\n       permission_at (erasePerm m) b ofs k = None).\n  Proof.\n    intros.\n    assert (Hb : b = Pos.of_nat (Pos.to_nat b))\n      by (by rewrite Pos2Nat.id).\n    split.\n    { intros Hvalid. unfold permission_at,  setMaxPerm. simpl.\n      rewrite Hb.\n      rewrite <- canonicalPMap_sound.\n      reflexivity.\n      assert (H := Pos2Nat.is_pos b). ssromega.\n      apply Pos2Nat.inj_lt in Hvalid. ssromega.\n    }\n    { intros Hinvalid.\n      unfold permission_at, setMaxPerm. simpl.\n      rewrite Hb.\n      rewrite canonicalPMap_default. reflexivity.\n      apply Pos.le_nlt in Hinvalid.\n      apply Pos2Nat.inj_le in Hinvalid. ssromega.\n    }\n  Qed.\n\n   Lemma erasePerm_V :\n    forall m b ofs k,\n      Mem.valid_block m b ->\n       permission_at (erasePerm m) b ofs k = Some Freeable.\n  Proof.\n    intros;\n    assert (Hperm := erasePerm_Perm m b ofs k);\n    destruct Hperm; auto.\n  Qed.\n\n  Lemma erasePerm_I :\n    forall m b ofs k,\n      ~ Mem.valid_block m b ->\n      permission_at (erasePerm m) b ofs k = None.\n  Proof.\n    intros;\n    assert (Hperm := erasePerm_Perm m b ofs k);\n    destruct Hperm; auto.\n  Qed.\n\n   Definition decay m_before m_after := forall b ofs,\n      (~Mem.valid_block m_before b ->\n       Mem.valid_block m_after b ->\n       (forall k, Maps.PMap.get b (Mem.mem_access m_after) ofs k = Some Freeable)\n       \\/ (forall k, Maps.PMap.get b (Mem.mem_access m_after) ofs k = None)) /\\\n      (Mem.valid_block m_before b ->\n       (forall k,\n           (Maps.PMap.get b (Mem.mem_access m_before) ofs k = Some Freeable /\\\n            Maps.PMap.get b (Mem.mem_access m_after) ofs k = None)) \\/\n       (forall k, Maps.PMap.get b (Mem.mem_access m_before) ofs k =\n             Maps.PMap.get b (Mem.mem_access m_after) ofs k)).\n\n   Definition strong_decay m_before m_after := forall b ofs,\n       (~Mem.valid_block m_before b ->\n       Mem.valid_block m_after b ->\n       (forall k, Maps.PMap.get b (Mem.mem_access m_after) ofs k = Some Freeable)\n       \\/ (forall k, Maps.PMap.get b (Mem.mem_access m_after) ofs k = None)) /\\\n      (Mem.valid_block m_before b ->\n       (forall k, Maps.PMap.get b (Mem.mem_access m_before) ofs k =\n             Maps.PMap.get b (Mem.mem_access m_after) ofs k)).\n\n   Lemma strong_decay_implies_decay:\n     forall m m',\n       strong_decay m m' ->\n       decay m m'.\n   Proof.\n     intros.\n     intros b ofs.\n     destruct (H b ofs);\n       intros;\n       now auto.\n   Qed.\n\n  Lemma decay_refl:\n    forall m,\n      decay m m.\n  Proof.\n    intros m b ofs.\n    split; intros; first by exfalso.\n    right; auto.\n  Qed.\n\n  Lemma decay_trans :\n    forall m m' m'',\n      (forall b, Mem.valid_block m b -> Mem.valid_block m' b) ->\n      decay m m' ->\n      decay m' m'' ->\n      decay m m''.\n  Proof.\n    intros m m' m'' Hvblocks H H0.\n    unfold decay in *.\n    intros b ofs.\n    specialize (H b ofs).\n    specialize (H0 b ofs).\n    destruct H, H0.\n    split.\n    - intros Hinvalid Hvalid''.\n      destruct (valid_block_dec m' b) as [Hvalid' | Hinvalid'];\n        eauto.\n      specialize (H Hinvalid Hvalid').\n      specialize (H2 Hvalid').\n      destruct H2.\n      right. intros k; destruct (H2 k); eauto.\n      destruct H;\n        [left | right]; intros k; specialize (H k);\n        specialize (H2 k); rewrite <- H2; auto.\n    - intros Hvalid.\n      clear H.\n      specialize (H1 Hvalid).\n      specialize (Hvblocks _ Hvalid).\n      specialize (H2 Hvblocks).\n      destruct H2 as [H2 | H2], H1 as [H1 | H1].\n      + left; intros k; destruct (H1 k); destruct (H2 k);\n        eauto.\n      + left; intros k; specialize (H1 k); destruct (H2 k);\n        rewrite H1; eauto.\n      + left; intros k; destruct (H1 k); specialize (H2 k);\n        rewrite <- H2; eauto.\n      + right; intros k; specialize (H1 k); specialize (H2 k);\n        rewrite H1; rewrite H2; eauto.\n  Qed.\n\n  Definition permMapJoin (pmap1 pmap2 pmap3: access_map) :=\n    forall b ofs,\n      permjoin ((pmap1 !! b) ofs) ((pmap2 !! b) ofs) ((pmap3 !! b) ofs).\n\n  Lemma permMapJoin_order:\n    forall p1 p2 p3\n      (Hjoin: permMapJoin p1 p2 p3),\n    forall b ofs,\n      Mem.perm_order'' (p3 !! b ofs) (p1 !! b ofs) /\\\n      Mem.perm_order'' (p3 !! b ofs) (p2 !! b ofs).\n  Proof.\n    intros.\n    specialize (Hjoin b ofs);\n      auto using permjoin_order.\n  Qed.\n\n  Lemma permMapLt_invalid_block:\n    forall pmap m b ofs\n      (Hlt: permMapLt pmap (getMaxPerm m))\n      (Hinvalid: ~ Mem.valid_block m b),\n      (pmap !! b ofs) = None.\n  Proof.\n    intros.\n    apply Mem.nextblock_noaccess with (ofs := ofs) (k := Max) in Hinvalid.\n    specialize (Hlt b ofs).\n    rewrite getMaxPerm_correct in Hlt.\n    unfold permission_at in Hlt.\n    rewrite Hinvalid in Hlt.\n    simpl in Hlt. destruct (pmap !! b ofs);\n                    [by exfalso | auto].\n  Qed.\n\n  Lemma perm_order_valid_block:\n    forall pmap m b ofs p\n      (Hperm: Mem.perm_order'' (pmap !! b ofs) (Some p))\n      (Hlt: permMapLt pmap (getMaxPerm m)),\n      Mem.valid_block m b.\n  Proof.\n    intros.\n    destruct (valid_block_dec m b);\n      auto.\n    eapply permMapLt_invalid_block with (ofs := ofs) in n;\n      eauto.\n    rewrite n in Hperm.\n    simpl in Hperm.\n      by exfalso.\n  Qed.\n\n  Definition perm_order''_dec : forall (op op' : option permission),\n      {Mem.perm_order'' op op'} + {~ Mem.perm_order'' op op'}.\n  Proof.\n    intros.\n    destruct op, op'; simpl; auto.\n    eapply Mem.perm_order_dec.\n  Defined.\n\n  Definition perm_eq_dec: forall (op op' : option permission),\n      {op = op'} + {~ op = op'}.\n  Proof.\n    intros; destruct op as [op|], op' as [op'|]; simpl; auto;\n    try (destruct op, op'); auto;\n    right; intros Hcontra; discriminate.\n  Defined.\n\nEnd permMapDefs.\n\nLtac unfold_getMaxPerm:=\n  repeat rewrite getMaxPerm_correct in *;\n  repeat rewrite getMaxPerm_correct;\n  unfold permission_at in *;\n  unfold permission_at.\nLtac unfold_getCurPerm:=\n  repeat rewrite getCurPerm_correct in *;\n  repeat rewrite getCurPerm_correct;\n  unfold permission_at in *;\n  unfold permission_at.\nLtac unfold_getPerm:=\n  try unfold_getMaxPerm;\n  try unfold_getCurPerm.\n\nRequire Import VST.concurrency.common.core_semantics.\nRequire Import compcert.lib.Coqlib.\n\nLemma storebytes_decay:\n  forall m loc p vl m', Mem.storebytes m loc p vl = Some m' -> decay m m'.\nProof.\nintros.\nhnf; intros.\nsplit; intros.\ncontradiction (Mem.storebytes_valid_block_2 _ _ _ _ _ H _ H1).\nright.\nintros.\nrewrite (Mem.storebytes_access _ _ _ _ _ H); auto.\nQed.\n\nLemma alloc_decay:\n  forall m lo hi m1 b1, Mem.alloc m lo hi = (m1,b1) -> decay m m1.\nProof.\nintros.\nhnf; intros.\nsplit; intros.\ndestruct (eq_block b1 b).\nsubst.\ndestruct (Memory.range_dec lo ofs hi).\nleft.\nintros.\nTransparent Mem.alloc.\nunfold Mem.alloc in H.\ninv H.\nsimpl. rewrite PMap.gss.\ndestruct (zle lo ofs); try omega.\ndestruct (zlt ofs hi); try omega; auto.\nright.\nintros.\ninv H; simpl.\nrewrite PMap.gss.\ndestruct (zle lo ofs); try omega;\ndestruct (zlt ofs hi); try omega; auto.\ncontradiction H0.\npose proof (Mem.valid_block_alloc_inv _ _ _ _ _ H b H1).\ndestruct H2. subst. contradiction n; auto.\nauto.\nright.\nintros.\nassert (b1<>b).\nintro. subst.\ncontradiction (Mem.fresh_block_alloc _ _ _ _ _ H).\ndestruct ((Mem.mem_access m1) !! b ofs k) eqn:?H.\ndestruct (semantics_lemmas.alloc_access_inv _ _ _ _ _ H _ _ _ _ H2).\ndestruct H3; congruence.\ndestruct H3; auto.\napply (semantics_lemmas.alloc_access_inv_None _ _ _ _ _ H _ _ _ H2).\nOpaque Mem.alloc.\nQed.\n\nLemma free_decay: forall m b lo hi m', Mem.free m b lo hi = Some m' -> decay m m'.\nProof.\nintros.\nhnf; intros.\ndestruct (eq_block b b0).\nsubst b0.\nsplit; intros.\ncontradiction H0.\neapply Mem.valid_block_free_2; eauto.\nTransparent Mem.free.\nunfold Mem.free in H.\nif_tac in H; inv H.\ndestruct (Memory.range_dec lo ofs hi) as [?H|?H].\nspecialize (H1 _ H).\nleft.\nintros.\nhnf in H1.\ndestruct ((Mem.mem_access m) !! b ofs Cur) eqn:H2; try contradiction.\nassert (p=Freeable) by (destruct p; inv H1; auto). subst p; clear H1.\nsplit.\ndestruct k; auto.\npose proof (Mem.access_max m b ofs).\nrewrite H2 in H1.\ndestruct ((Mem.mem_access m) !! b ofs Max); inv H1; auto.\nsimpl.\nrewrite PMap.gss.\ndestruct (zle lo ofs); try omega.\ndestruct (zlt ofs hi); try omega.\nsimpl. auto.\nright.\nintros.\nsimpl.\nrewrite PMap.gss.\ndestruct (zle lo ofs); destruct (zlt ofs hi); try omega; auto.\nsplit.\nintros.\ncontradiction H0.\neapply Mem.valid_block_free_2; eauto.\nintros.\nright.\nintros.\nunfold Mem.free in H.\ndestruct (Mem.range_perm_dec m b lo hi Cur Freeable).\ninv H.\nsimpl.\nrewrite PMap.gso; auto.\ninv H.\nOpaque Mem.free.\nQed.\n\n\nLemma msem_decay: \n  forall C (Sem: MemSem C) c m c' m',\n   corestep (csem Sem)  c m c' m' ->\n  decay m m'.\nProof.\n  intros.\n apply corestep_mem in H.\n induction H.\n eapply storebytes_decay; eauto.\n eapply alloc_decay; eauto.\n revert m H; induction l; simpl; intros. inv H. apply decay_refl.\n destruct a as [[? ?] ?].\n destruct (Mem.free m b z z0) eqn:?; inv H.\n apply IHl in H1.\n apply decay_trans with m0; auto.\n eapply Mem.valid_block_free_1; eauto.\n eapply free_decay; eauto.\n apply decay_trans with m''; auto.\n apply semantics_lemmas.mem_step_nextblock' in H.\n apply semantics_lemmas.mem_step_nextblock' in H0.\n pose proof (Pos.le_trans _ _ _ H H0).\n intros.\n red in H2|-*.\n  unfold Plt in *.\n  eapply Pos.lt_le_trans; eauto.\nQed.\n\n\n\nLemma range_no_overlap:\n  forall (mu : meminj) (m1 : mem) (b1 b1' b2 b2': block)\n    (ofs delt delta ofs0 : Z) (n : nat),\n    Mem.meminj_no_overlap mu m1 ->\n    mu b1 = Some (b1', delt) ->\n    mu b2 = Some (b2', delta) ->\n    b1 <> b2 ->\n    Mem.perm m1 b1 ofs0 Max Nonempty ->\n    Mem.range_perm m1 b2 ofs (ofs + Z.of_nat n) Max Nonempty ->\n    b1' <> b2' \\/ b1' = b2' /\\\n    ~ Intv.In (ofs0 + delt)\n      ((ofs + delta)%Z, (ofs + delta + Z.of_nat n)%Z).\nProof.\n  intros ??????????? Hno_overlap Hinj1\n         Hinj2 Hneq Hperm1 Hrange_perm2.\n  \n  (* The key is to do an induction over the length of the range\n   *)\n  assert(H: forall m, (m <= n)%coq_nat -> b1' <> b2' \\/\n                             (~ Intv.In (ofs0 + delt)\n                                (ofs + delta, ofs + delta + Z.of_nat m))%Z).\n  { induction m.\n    - intros ?. simpl; right.\n      unfold Intv.In; simpl. clear.\n      intros ?; omega.\n    -  intros ?.\n       specialize (Hno_overlap\n                     _ _ _ _ _ _\n                     ofs0 (ofs+Z.of_nat m)%Z\n                     Hneq Hinj1 Hinj2).\n       apply Hno_overlap in Hperm1.\n       2: { eapply Hrange_perm2. omega.     }\n       destruct Hperm1 as [Hperm1|Hperm1]; auto.\n       specialize (IHm ltac:(omega)).\n       destruct IHm as [IHm|IHm]; auto.\n       right; clear - IHm Hperm1.\n       intros [? ?]; eapply IHm.\n       split; auto.\n       unfold Intv.In; simpl in *.\n       clear IHm H.\n       rewrite Zpos_P_of_succ_nat in H0.\n       omega. }\n\n  specialize (H _ ltac:(reflexivity)).\n  destruct H; auto.\n  destruct (base.block_eq_dec b1' b2'); subst; auto.\nQed.\n\nLemma setPermBLock_no_overlap:\n  forall (mu : meminj) (m1 : mem) (b b' b1 b2 : block)\n    (ofs delt delta ofs0 : Z) (n : nat),\n    Mem.meminj_no_overlap mu m1 ->\n    permMapLt (setPermBlock (Some Writable)\n                            b ofs (getCurPerm m1) n)\n              (getMaxPerm m1) ->\n    mu b = Some (b', delt) ->\n    mu b1 = Some (b2, delta) ->\n    b1 <> b ->\n    Mem.perm m1 b1 ofs0 Max Nonempty ->\n    b2 <> b' \\/\n    b2 = b' /\\\n    ~ Intv.In (ofs0 + delta)\n      ((ofs + delt)%Z, (ofs + delt + Z.of_nat n)%Z).\nProof.\n  intros; eapply range_no_overlap; eauto.\n  clear H4.\n  eapply setPermBlock_range_perm in H0; eauto.\n  unfold Mem.range_perm, Mem.perm in *; intros.\n  rewrite mem_lemmas.po_oo.\n  specialize (H0 _ H4).\n  rewrite mem_lemmas.po_oo in H0.\n  eapply mem_lemmas.po_trans; eauto.\n  constructor.\nQed.\n\n\nLemma range_perm_trans:\n  forall m b ofs0 ofs1 k p1 p2,\n    Mem.range_perm m b ofs0 ofs1 k p1 ->\n    perm_order p1 p2 ->\n    Mem.range_perm m b ofs0 ofs1 k p2.\nProof.\n  unfold Mem.range_perm, Mem.perm; intros.\n  eapply H in H1.\n  rewrite mem_lemmas.po_oo.\n  rewrite mem_lemmas.po_oo in H1.\n  eapply juicy_mem.perm_order''_trans; eauto.\nQed.\n\nLemma perm_order''_trans:\n  transitive _ Mem.perm_order''.\n  intros a b c H1 H2; destruct a, b, c; inversion H1;\n    inversion H2; subst; eauto;\n      eapply perm_order_trans; eauto.\nQed.\n\nLemma perm_order_trans211:\n  forall oa ob c,\n    Mem.perm_order'' oa ob ->\n    Mem.perm_order' ob c ->\n    Mem.perm_order' oa c.\nProof.\n  intros. rewrite mem_lemmas.po_oo in H0.\n  eapply (perm_order''_trans _ _ (Some c)); eassumption.\nQed.\n\nLemma permMapJoin_lt:\n  forall p1 p2 p3\n    (Hjoin: permMapJoin p1 p2 p3), permMapLt p1 p3.\nProof. intros ** ??; eapply permMapJoin_order in Hjoin; eapply Hjoin. Qed.\n\nLemma perm_order_from_map:\n  forall perm b (ofs : Z) p,\n    perm !! b ofs  = Some p ->\n    Mem.perm_order' (perm !! b ofs) Nonempty.\nProof. intros * H; rewrite H; constructor. Qed.\n\nLemma restr_proof_irr:\n  forall m perm Hlt Hlt',\n    (@restrPermMap m perm Hlt) = (@restrPermMap m perm Hlt').\n  intros. replace Hlt with Hlt'.\n  - reflexivity.\n  - apply Axioms.proof_irr.\nQed.\nLemma restrPermMap_rewrite:\n  forall p1 p2 m H1 H2,\n    p1 = p2 -> @restrPermMap p1 m H1 = @restrPermMap p2 m H2.\nProof. intros; subst p1; apply restr_proof_irr. Qed.\nLemma permMapLt_eq:\n  forall {p1 p2 m}, p1 = p2 -> permMapLt p1 m -> permMapLt p2 m.\nProof. intros; subst; assumption. Qed.\nLemma restrPermMap_rewrite_strong:\n  forall p1 p2 m H1\n    (Heq: p1 = p2),\n    @restrPermMap p1 m H1 =\n    @restrPermMap p2 m (permMapLt_eq Heq H1).\nProof. intros; eapply restrPermMap_rewrite; auto. Qed.\n\nLemma permMapJoin_comm:\n  forall A B C, permMapJoin A B C -> permMapJoin B A C.\nProof.\n  unfold permMapJoin; intros * HH b ofs.\n  specialize (HH b ofs); inversion HH; econstructor.\nQed.\n\n\n\n\n\n\n\n\n\n\n(* End of old Permissions. *)\n\n\n\n      (* cann be used to expose the implicit arguemtns. *)\n      Definition restrPermMap' a b H:= @restrPermMap a b H.\n      Lemma RPM: restrPermMap = restrPermMap'. Proof. reflexivity. Qed.\n      Arguments restrPermMap' a b H.\n      \n      Lemma restr_proof_irr':\n        forall (perm1 perm2 : access_map) (m1 m2 : mem)\n               (Hlt1 : permMapLt perm1 (getMaxPerm m1))\n               (Hlt2 : permMapLt perm2 (getMaxPerm m2)),\n          perm1 = perm2 ->\n          m1 = m2 ->\n          restrPermMap Hlt1 = restrPermMap Hlt2.\n      Proof. intros. subst. apply restr_proof_irr. Qed.\n      \n\n      Lemma cur_lt_max:\n        forall m, permMapLt (getCurPerm m) (getMaxPerm m).\n      Proof.\n        intros ** ??.\n        rewrite getCurPerm_correct getMaxPerm_correct; eapply m.\n      Qed.\n      \n      Lemma mem_cur_lt_max:\n        forall m, permMapLt (getCurPerm m) (getMaxPerm m).\n      Proof.\n        intros.\n        intros ??.\n        rewrite getCurPerm_correct getMaxPerm_correct.\n        unfold permission_at.\n        eapply Mem.access_max.\n      Qed.\n      Lemma restr_Max_eq:\n        forall p m Hlt,\n          getMaxPerm (@restrPermMap p m Hlt) = getMaxPerm m.  \n      Proof.\n        intros.\n        unfold getMaxPerm, restrPermMap.\n        simpl. unfold PMap.map; simpl.\n        f_equal.\n        repeat rewrite map_map1; simpl.\n        unfold PTree.map.\n        rewrite xmap_compose.\n        reflexivity.\n      Qed.\n      \n      Lemma setPermBlock_setPermBlock_var':\n        forall v, setPermBlock v = setPermBlock_var (fun _ : nat => v).\n      Proof.\n        intros.\n        extensionality b.\n        extensionality ofs.\n        extensionality pmap.\n        extensionality n.\n        eapply setPermBlock_setPermBlock_var.\n      Qed.\n      Lemma perm_range_perm:\n        forall m b low high k p,\n          Mem.range_perm m b low high k p ->\n          forall ofs', Intv.In ofs' (low,high) ->\n                  Mem.perm m b ofs' k p.\n      Proof.\n        unfold Mem.range_perm, Mem.perm; intros.\n        eapply H; eauto.\n      Qed.\n\nLemma mem_max_lt_max:\n forall m, permMapLt (getMaxPerm m) (getMaxPerm m).\nProof.\n intros.\n intros ? ?. apply po_refl.\nQed.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/concurrency/common/permissions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6688802735722127, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2452046431199316}}
{"text": "Require Import Spec.Proc Spec.ProcTheorems.\nRequire Import Tactical.Propositional.\nRequire Import Tactical.ExistentialVariants.\nRequire Import Tactical.Misc.\nRequire Import Helpers.RelationAlgebra.\nRequire Import Helpers.RelationRewriting.\nRequire Import Helpers.RelationTheorems.\nRequire Import Spec.Hoare.\n\nImport RelationNotations.\nLtac spec_intros := intros; first [ eapply rspec_intros | eapply hspec_intros ] ; intros.\n\nLtac monad_simpl :=\n  repeat match goal with\n         | |- proc_hspec _ (Bind (Ret _) _) _ =>\n           eapply proc_hspec_exec_equiv; [ apply monad_left_id | ]\n         | |- proc_hspec _ (Bind (Bind _ _) _) _ =>\n           eapply proc_hspec_exec_equiv; [ apply monad_assoc | ]\n         end.\n\nLtac step_proc :=\n  intros;\n  match goal with\n  | |- proc_hspec _ (Ret _) _ =>\n    eapply ret_hspec\n  | |- proc_hspec _ _ _ =>\n    monad_simpl;\n    eapply proc_hspec_rx; [ solve [ eauto ] | ]\n  | [ H: proc_hspec _ ?p _\n      |- proc_hspec _ ?p _ ] =>\n    eapply proc_hspec_impl; [ unfold spec_impl | eapply H ]\n  end;\n  intros; simpl;\n  cbn [pre post alternate] in *;\n  repeat match goal with\n         | [ H: _ /\\ _ |- _ ] => destruct H\n         | [ |- rec_noop _ _ _ ] => eauto\n         | [ |- forall _, _ ] => intros\n         | [ |- exists (_:unit), _ ] => exists tt\n         | [ |- _ /\\ _ ] => split; [ solve [ trivial ] | ]\n         | [ |- _ /\\ _ ] => split; [ | solve [ trivial ] ]\n         | _ => solve [ trivial ]\n         | _ => progress subst\n         | _ => progress autounfold in *\n         end.\n\n(* The [finish] tactic tries a number of techniques to solve the goal. *)\nLtac finish :=\n  repeat match goal with\n         | _ => solve_false\n         | _ => congruence\n         | _ => solve [ intuition (subst; eauto; try congruence) ]\n         | _ =>\n           (* if we can solve all the side conditions automatically, then it's\n             safe to run descend and create existential variables *)\n           descend; (intuition eauto);\n           lazymatch goal with\n           | |- proc_hspec _ _ _ => idtac\n           | |- proc_rspec _ _ _ _ => idtac\n           | _ => fail\n           end\n         end.\n", "meta": {"author": "mit-pdos", "repo": "argosy", "sha": "a6a5aa0d3868efd4ada0b40927b5748e5d8967d3", "save_path": "github-repos/coq/mit-pdos-argosy", "path": "github-repos/coq/mit-pdos-argosy/argosy-a6a5aa0d3868efd4ada0b40927b5748e5d8967d3/src/Spec/HoareTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.24515028033031297}}
{"text": "From Hammer Require Import Hammer.\n\n\n\nFrom WeakUpTo Require Export Monotonic.\nSet Implicit Arguments.\n\nSection Global.\n\nVariable A: Type.\n\nSection A.\n\nVariables X Y: Type.\nVariable TX: reduction_t A X.\nVariable TY: reduction_t A Y.\n\n\nLemma monotonic_wmonotonic: forall F, monotonic TX TY F -> wmonotonic TX TY F.\nProof. hammer_hook \"WeakMonotonic\" \"WeakMonotonic.monotonic_wmonotonic\".\nintros F HF; split; auto.\napply (mon_m HF).\nintros R HR; apply (mon_t HF HR); auto.\nintros R S HR HS HRS HRS'; apply (mon_a HF); auto.\nintro l; destruct l; auto.\napply evolve_incl with R; auto.\nQed.\n\n\nLemma star_wmon: wmonotonic TX TX (star (X:=X)).\nProof. hammer_hook \"WeakMonotonic\" \"WeakMonotonic.star_wmon\".\nsplit.\nintros R S H x y XY; induction XY as [ x | w x y XW WY IH ]; auto; apply S_star with w; auto.\nintros R HR; unfold simulation_t, evolve_t, evolve_1.\napply diagram_reverse; apply diagram_incl with (Weak TX (T _)) (Weak TX (T _)); auto; apply diagram_reverse.\napply diagram_star; apply diagram_incl with R R; auto; apply weak_strong_t; exact HR.\nintros R S HR HS HRS HRS' a; unfold evolve_1.\napply diagram_reverse; apply diagram_incl with (Weak TX (L a)) (Weak TX (L a)); auto; apply diagram_reverse.\nintros x x' y Hxx' xRy; cgen Hxx'; cgen x'; induction xRy as [ x | w x y xRw wRy IH ]; intros x' Hxx'.\nexists x'; auto.\ndestruct Hxx' as [ x1 Hxx1 Hx1x' ]; destruct Hx1x' as [ x2 Hx1x2 Hx2x' ].\ndestruct (weak_strong_t HR _ Hxx1 xRw) as [ w1 Hww1 x1Rw1 ].\ndestruct (HRS _ _ _ _ Hx1x2 x1Rw1) as [ w2 Hw1w2 x2Rw2 ].\ndestruct (weak_strong_t HS _ Hx2x' x2Rw2) as [ w' Hw2w' x'Rw' ].\nelim IH with w'.\nintros y' Hyy' w'Ry'; exists y'; auto; apply S_star with w'; auto.\napply taus_weak with w1; auto; apply weak_taus with w2; auto.\nQed.\n\nVariables F G: function X Y.\nHypothesis HF: wmonotonic TX TY F.\nHypothesis HG: wmonotonic TX TY G.\n\n\nLemma Comp_wmon: wmonotonic TX TY (Comp G F).\nProof. hammer_hook \"WeakMonotonic\" \"WeakMonotonic.Comp_wmon\".\nunfold Comp; split.\nintros R S HRS; apply (wmon_m HG); apply (wmon_m HF); exact HRS.\nintros R HR; exact (wmon_t HG (wmon_t HF HR)).\nintros R S HR HS HRS HRS'; apply (wmon_a HG).\napply (wmon_t HF HR).\napply (wmon_t HF HS).\nexact (wmon_a HF HR HS HRS HRS').\napply (wmon_m HF HRS').\nQed.\n\n\nLemma Union2_wmon: wmonotonic TX TY (Union2 F G).\nProof. hammer_hook \"WeakMonotonic\" \"WeakMonotonic.Union2_wmon\".\nunfold Union2; split.\nintros R S HRS x y H; destruct H; [ left; apply (wmon_m HF HRS) | right; apply (wmon_m HG HRS) ]; auto.\nintros R HR x x' y Hxx' xRy; celim xRy; intro xRy;\n[ destruct (wmon_t HF HR _ _ _ Hxx' xRy) as [ y' ]\n| destruct (wmon_t HG HR _ _ _ Hxx' xRy) as [ y' ] ];\nexists y'; auto; [ left | right ]; auto.\nintros R S HR HS HRS HRS' a x x' y Hxx' xRy; celim xRy; intro xRy;\n[ destruct (wmon_a HF HR HS HRS HRS' _ _ _ _ Hxx' xRy) as [ y' ]\n| destruct (wmon_a HG HR HS HRS HRS' _ _ _ _ Hxx' xRy) as [ y' ] ];\nexists y'; auto; [ left | right ]; auto.\nQed.\n\nSection Union.\n\nVariable I: Type.\nVariable H: I -> function X Y.\nHypothesis HH: forall i, wmonotonic TX TY (H i).\n\n\nLemma Union_wmon: wmonotonic TX TY (Union H).\nProof. hammer_hook \"WeakMonotonic\" \"WeakMonotonic.Union_wmon\".\nunfold Union; split.\nintros R S HRS x y K; destruct K as [ i ]; exists i; apply (wmon_m (HH i) HRS); auto.\nintros R HR x x' y Hxx' xRy; destruct xRy as [ i xRy ];\ndestruct (wmon_t (HH i) HR _ _ _ Hxx' xRy) as [ y' ];\nexists y'; auto; exists i; auto.\nintros R S HR HS HRS HRS' a x x' y Hxx' xRy; destruct xRy as [ i xRy ];\ndestruct (wmon_a (HH i) HR HS HRS HRS' _ _ _ _ Hxx' xRy) as [ y' ];\nexists y'; auto; exists i; auto.\nQed.\n\nEnd Union.\n\nEnd A.\n\nSection B.\n\nVariables X Y: Type.\nVariable TX: reduction_t A X.\nVariable TY: reduction_t A Y.\n\nVariables F G: function X Y.\nHypothesis HF: wmonotonic TX TY F.\nHypothesis HG: wmonotonic TX TY G.\n\n\nLemma UExp_wmon: forall n, wmonotonic TX TY (fun R => UExp F R n).\nProof. hammer_hook \"WeakMonotonic\" \"WeakMonotonic.UExp_wmon\".\nintro n; induction n as [ | n IH ].\napply (monotonic_wmonotonic (identity_mon TX TY)).\nsimpl; fold (Union2 (fun R => UExp F R n) (fun R => F (UExp F R n))).\napply Union2_wmon; auto.\nfold (Comp F (fun R => UExp F R n)).\napply Comp_wmon; auto.\nQed.\nLemma UIter_wmon: wmonotonic TX TY (UIter F).\nProof. hammer_hook \"WeakMonotonic\" \"WeakMonotonic.UIter_wmon\".\nunfold UIter.\nchange (fun R => union (UExp F R)) with (Union (fun n => (fun R => UExp F R n))).\napply Union_wmon; intro i; apply UExp_wmon.\nQed.\n\nEnd B.\n\nSection C.\n\nVariables X Y: Type.\nVariable TX: reduction_t A X.\nVariable TY: reduction_t A Y.\n\nVariables F G: function X X.\nHypothesis HF: wmonotonic TX TX F.\nHypothesis HG: wmonotonic TX TX G.\n\n\nLemma Chaining_wmon: wmonotonic TX TX (Chain F G).\nProof. hammer_hook \"WeakMonotonic\" \"WeakMonotonic.Chaining_wmon\".\nunfold Chain; split.\nintros R S HRS x y H; destruct H as [ w H1 H2 ]; exists w;\n[ apply (wmon_m HF HRS) | apply (wmon_m HG HRS) ]; auto.\nintros R HR x x' y Hxx' xRy; destruct xRy as [ w xRw wRy ].\ndestruct (wmon_t HF HR _ _ _ Hxx' xRw) as [ w' Hww' x'Rw' ].\ndestruct (weak_strong_t (wmon_t HG HR) _ Hww' wRy) as [ y' Hyy' x'Ry' ].\nexists y'; auto; exists w'; auto.\nintros R S HR HS HRS HRS' a x x' y Hxx' xRy; destruct xRy as [ w xRw wRy ].\ndestruct (wmon_a HF HR HS HRS HRS' _ _ _ _ Hxx' xRw) as [ w' Hww' x'Rw' ].\ndestruct Hww' as [ w1 Hww1 Hw1w' ]; destruct Hw1w' as [ w2 Hw1w2 Hw2w' ].\ndestruct (weak_strong_t (wmon_t HG HR) _ Hww1 wRy) as [ y1 Hyy1 w1Ry1 ].\ndestruct (wmon_a HG HR HS HRS HRS' _ _ _ _ Hw1w2 w1Ry1) as [ y2 Hy1y2 w2Ry2 ].\ndestruct (weak_strong_t (wmon_t HG HS) _ Hw2w' w2Ry2) as [ y' Hy2y' w'Ry' ].\nexists y'.\napply taus_weak with y1; auto; apply weak_taus with y2; auto.\nexists w'; auto.\nQed.\n\n\nVariable L: relation Y.\nHypothesis HL: simulation TY TY L.\n\n\nLemma chaing_l_wmon: wmonotonic TY TX (chaining_l L).\nProof. hammer_hook \"WeakMonotonic\" \"WeakMonotonic.chaing_l_wmon\".\nsplit.\nintros R S HRS x y H; destruct H as [ w ]; exists w; auto.\nintros R HR x x' y Hxx' xRy; destruct xRy as [ w xRw wRy ].\ndestruct (HL Hxx' xRw) as [ w' Hww' x'Rw' ].\ndestruct (weak_strong_t HR _ Hww' wRy) as [ y' Hyy' x'Ry' ].\nexists y'; auto; exists w'; auto.\nintros R S HR HS HRS HRS' a x x' y Hxx' xRy; destruct xRy as [ w xRw wRy ].\ndestruct (HL Hxx' xRw) as [ w' Hww' x'Rw' ].\ndestruct Hww' as [ w1 Hww1 Hw1w' ]; destruct Hw1w' as [ w2 Hw1w2 Hw2w' ].\ndestruct (weak_strong_t HR _ Hww1 wRy) as [ y1 Hyy1 w1Ry1 ].\ndestruct (HRS _ _ _ _ Hw1w2 w1Ry1) as [ y2 Hy1y2 w2Ry2 ].\ndestruct (weak_strong_t HS _ Hw2w' w2Ry2) as [ y' Hy2y' w'Ry' ].\nexists y'.\napply taus_weak with y1; auto; apply weak_taus with y2; auto.\nexists w'; auto.\nQed.\n\nEnd C.\n\nEnd Global.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/weak-up-to/WeakMonotonic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2451502803303129}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Bool.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import ZArith NArith Nnat Ndec Ndigits.\nFrom IntMap Require Import Allmaps.\nRequire Import Wf_nat.\n\nRequire Import BDDvar_ad_nat.\nRequire Import bdd1.\nRequire Import bdd2.\nRequire Import bdd3.\nRequire Import bdd4.\nRequire Import bdd5_1.\nRequire Import bdd5_2.\nRequire Import bdd6.\n\n\n\n\nFixpoint BDDor_1 (cfg : BDDconfig) (memo : BDDor_memo) \n (node1 node2 : ad) (bound : nat) {struct bound} :\n BDDconfig * (ad * BDDor_memo) :=\n  match BDDor_memo_lookup memo node1 node2 with\n  | Some node => (cfg, (node, memo))\n  | None =>\n      if N.eqb node1 BDDzero\n      then (cfg, (node2, BDDor_memo_put memo BDDzero node2 node2))\n      else\n       if N.eqb node1 BDDone\n       then (cfg, (BDDone, BDDor_memo_put memo BDDone node2 BDDone))\n       else\n        if N.eqb node2 BDDzero\n        then (cfg, (node1, BDDor_memo_put memo node1 BDDzero node1))\n        else\n         if N.eqb node2 BDDone\n         then (cfg, (BDDone, BDDor_memo_put memo node1 BDDone BDDone))\n         else\n          match bound with\n          | O => (initBDDconfig, (BDDzero, initBDDor_memo))\n          | S bound' =>\n              match BDDcompare (var cfg node1) (var cfg node2) with\n              | Datatypes.Eq =>\n                  (fst\n                     (BDDmake\n                        (fst\n                           (BDDor_1\n                              (fst\n                                 (BDDor_1 cfg memo \n                                    (low cfg node1) \n                                    (low cfg node2) bound'))\n                              (snd\n                                 (snd\n                                    (BDDor_1 cfg memo \n                                       (low cfg node1) \n                                       (low cfg node2) bound')))\n                              (high cfg node1) (high cfg node2) bound'))\n                        (var cfg node1)\n                        (fst\n                           (snd\n                              (BDDor_1 cfg memo (low cfg node1)\n                                 (low cfg node2) bound')))\n                        (fst\n                           (snd\n                              (BDDor_1\n                                 (fst\n                                    (BDDor_1 cfg memo \n                                       (low cfg node1) \n                                       (low cfg node2) bound'))\n                                 (snd\n                                    (snd\n                                       (BDDor_1 cfg memo \n                                          (low cfg node1) \n                                          (low cfg node2) bound')))\n                                 (high cfg node1) (high cfg node2) bound')))),\n                  (snd\n                     (BDDmake\n                        (fst\n                           (BDDor_1\n                              (fst\n                                 (BDDor_1 cfg memo \n                                    (low cfg node1) \n                                    (low cfg node2) bound'))\n                              (snd\n                                 (snd\n                                    (BDDor_1 cfg memo \n                                       (low cfg node1) \n                                       (low cfg node2) bound')))\n                              (high cfg node1) (high cfg node2) bound'))\n                        (var cfg node1)\n                        (fst\n                           (snd\n                              (BDDor_1 cfg memo (low cfg node1)\n                                 (low cfg node2) bound')))\n                        (fst\n                           (snd\n                              (BDDor_1\n                                 (fst\n                                    (BDDor_1 cfg memo \n                                       (low cfg node1) \n                                       (low cfg node2) bound'))\n                                 (snd\n                                    (snd\n                                       (BDDor_1 cfg memo \n                                          (low cfg node1) \n                                          (low cfg node2) bound')))\n                                 (high cfg node1) (high cfg node2) bound')))),\n                  BDDor_memo_put\n                    (snd\n                       (snd\n                          (BDDor_1\n                             (fst\n                                (BDDor_1 cfg memo (low cfg node1)\n                                   (low cfg node2) bound'))\n                             (snd\n                                (snd\n                                   (BDDor_1 cfg memo \n                                      (low cfg node1) \n                                      (low cfg node2) bound')))\n                             (high cfg node1) (high cfg node2) bound')))\n                    node1 node2\n                    (snd\n                       (BDDmake\n                          (fst\n                             (BDDor_1\n                                (fst\n                                   (BDDor_1 cfg memo \n                                      (low cfg node1) \n                                      (low cfg node2) bound'))\n                                (snd\n                                   (snd\n                                      (BDDor_1 cfg memo \n                                         (low cfg node1) \n                                         (low cfg node2) bound')))\n                                (high cfg node1) (high cfg node2) bound'))\n                          (var cfg node1)\n                          (fst\n                             (snd\n                                (BDDor_1 cfg memo (low cfg node1)\n                                   (low cfg node2) bound')))\n                          (fst\n                             (snd\n                                (BDDor_1\n                                   (fst\n                                      (BDDor_1 cfg memo \n                                         (low cfg node1) \n                                         (low cfg node2) bound'))\n                                   (snd\n                                      (snd\n                                         (BDDor_1 cfg memo \n                                            (low cfg node1) \n                                            (low cfg node2) bound')))\n                                   (high cfg node1) \n                                   (high cfg node2) bound')))))))\n              | Datatypes.Lt =>\n                  (fst\n                     (BDDmake\n                        (fst\n                           (BDDor_1\n                              (fst\n                                 (BDDor_1 cfg memo node1 \n                                    (low cfg node2) bound'))\n                              (snd\n                                 (snd\n                                    (BDDor_1 cfg memo node1 \n                                       (low cfg node2) bound'))) node1\n                              (high cfg node2) bound')) \n                        (var cfg node2)\n                        (fst\n                           (snd\n                              (BDDor_1 cfg memo node1 (low cfg node2) bound')))\n                        (fst\n                           (snd\n                              (BDDor_1\n                                 (fst\n                                    (BDDor_1 cfg memo node1 \n                                       (low cfg node2) bound'))\n                                 (snd\n                                    (snd\n                                       (BDDor_1 cfg memo node1\n                                          (low cfg node2) bound'))) node1\n                                 (high cfg node2) bound')))),\n                  (snd\n                     (BDDmake\n                        (fst\n                           (BDDor_1\n                              (fst\n                                 (BDDor_1 cfg memo node1 \n                                    (low cfg node2) bound'))\n                              (snd\n                                 (snd\n                                    (BDDor_1 cfg memo node1 \n                                       (low cfg node2) bound'))) node1\n                              (high cfg node2) bound')) \n                        (var cfg node2)\n                        (fst\n                           (snd\n                              (BDDor_1 cfg memo node1 (low cfg node2) bound')))\n                        (fst\n                           (snd\n                              (BDDor_1\n                                 (fst\n                                    (BDDor_1 cfg memo node1 \n                                       (low cfg node2) bound'))\n                                 (snd\n                                    (snd\n                                       (BDDor_1 cfg memo node1\n                                          (low cfg node2) bound'))) node1\n                                 (high cfg node2) bound')))),\n                  BDDor_memo_put\n                    (snd\n                       (snd\n                          (BDDor_1\n                             (fst\n                                (BDDor_1 cfg memo node1 \n                                   (low cfg node2) bound'))\n                             (snd\n                                (snd\n                                   (BDDor_1 cfg memo node1 \n                                      (low cfg node2) bound'))) node1\n                             (high cfg node2) bound'))) node1 node2\n                    (snd\n                       (BDDmake\n                          (fst\n                             (BDDor_1\n                                (fst\n                                   (BDDor_1 cfg memo node1 \n                                      (low cfg node2) bound'))\n                                (snd\n                                   (snd\n                                      (BDDor_1 cfg memo node1 \n                                         (low cfg node2) bound'))) node1\n                                (high cfg node2) bound')) \n                          (var cfg node2)\n                          (fst\n                             (snd\n                                (BDDor_1 cfg memo node1 \n                                   (low cfg node2) bound')))\n                          (fst\n                             (snd\n                                (BDDor_1\n                                   (fst\n                                      (BDDor_1 cfg memo node1 \n                                         (low cfg node2) bound'))\n                                   (snd\n                                      (snd\n                                         (BDDor_1 cfg memo node1\n                                            (low cfg node2) bound'))) node1\n                                   (high cfg node2) bound')))))))\n              | Datatypes.Gt =>\n                  (fst\n                     (BDDmake\n                        (fst\n                           (BDDor_1\n                              (fst\n                                 (BDDor_1 cfg memo \n                                    (low cfg node1) node2 bound'))\n                              (snd\n                                 (snd\n                                    (BDDor_1 cfg memo \n                                       (low cfg node1) node2 bound')))\n                              (high cfg node1) node2 bound')) \n                        (var cfg node1)\n                        (fst\n                           (snd\n                              (BDDor_1 cfg memo (low cfg node1) node2 bound')))\n                        (fst\n                           (snd\n                              (BDDor_1\n                                 (fst\n                                    (BDDor_1 cfg memo \n                                       (low cfg node1) node2 bound'))\n                                 (snd\n                                    (snd\n                                       (BDDor_1 cfg memo \n                                          (low cfg node1) node2 bound')))\n                                 (high cfg node1) node2 bound')))),\n                  (snd\n                     (BDDmake\n                        (fst\n                           (BDDor_1\n                              (fst\n                                 (BDDor_1 cfg memo \n                                    (low cfg node1) node2 bound'))\n                              (snd\n                                 (snd\n                                    (BDDor_1 cfg memo \n                                       (low cfg node1) node2 bound')))\n                              (high cfg node1) node2 bound')) \n                        (var cfg node1)\n                        (fst\n                           (snd\n                              (BDDor_1 cfg memo (low cfg node1) node2 bound')))\n                        (fst\n                           (snd\n                              (BDDor_1\n                                 (fst\n                                    (BDDor_1 cfg memo \n                                       (low cfg node1) node2 bound'))\n                                 (snd\n                                    (snd\n                                       (BDDor_1 cfg memo \n                                          (low cfg node1) node2 bound')))\n                                 (high cfg node1) node2 bound')))),\n                  BDDor_memo_put\n                    (snd\n                       (snd\n                          (BDDor_1\n                             (fst\n                                (BDDor_1 cfg memo (low cfg node1) node2\n                                   bound'))\n                             (snd\n                                (snd\n                                   (BDDor_1 cfg memo \n                                      (low cfg node1) node2 bound')))\n                             (high cfg node1) node2 bound'))) node1 node2\n                    (snd\n                       (BDDmake\n                          (fst\n                             (BDDor_1\n                                (fst\n                                   (BDDor_1 cfg memo \n                                      (low cfg node1) node2 bound'))\n                                (snd\n                                   (snd\n                                      (BDDor_1 cfg memo \n                                         (low cfg node1) node2 bound')))\n                                (high cfg node1) node2 bound'))\n                          (var cfg node1)\n                          (fst\n                             (snd\n                                (BDDor_1 cfg memo (low cfg node1) node2\n                                   bound')))\n                          (fst\n                             (snd\n                                (BDDor_1\n                                   (fst\n                                      (BDDor_1 cfg memo \n                                         (low cfg node1) node2 bound'))\n                                   (snd\n                                      (snd\n                                         (BDDor_1 cfg memo \n                                            (low cfg node1) node2 bound')))\n                                   (high cfg node1) node2 bound')))))))\n              end\n          end\n  end.\n\n\n\n\n\nLemma BDDor_1_lemma_1 :\n forall (cfg : BDDconfig) (memo : BDDor_memo) (node1 node2 node : ad)\n   (bound : nat),\n BDDor_memo_lookup memo node1 node2 = Some node ->\n BDDor_1 cfg memo node1 node2 bound = (cfg, (node, memo)).\nProof.\n  intros cfg memo node1 node2 node bound H.  elim bound.  simpl in |- *.  rewrite H.  reflexivity.  intros n H0.  simpl in |- *; rewrite H; reflexivity.\nQed.\n\nLemma BDDor_1_lemma_zero_1 :\n forall (cfg : BDDconfig) (memo : BDDor_memo) (node1 : ad) (bound : nat),\n BDDor_memo_lookup memo node1 BDDzero = None ->\n BDDor_1 cfg memo node1 BDDzero bound =\n (cfg, (node1, BDDor_memo_put memo node1 BDDzero node1)).\nProof.\n  intros cfg memo node1 bound H.  elim bound.  simpl in |- *.  rewrite H.  elim (sumbool_of_bool (N.eqb node1 BDDzero)).\n  intro y.  rewrite y.  cut (node1 = BDDzero).  intro H0.  rewrite H0; reflexivity.  \n  apply Neqb_complete.  assumption.  intro y.  rewrite y.  elim (sumbool_of_bool (N.eqb node1 BDDone)); intro y0.\n  rewrite y0.  cut (node1 = BDDone).  intro H0.  rewrite H0; reflexivity.  apply Neqb_complete.\n  assumption.  rewrite y0.  reflexivity.  intros n H0.  simpl in |- *.  rewrite H.  elim (sumbool_of_bool (N.eqb node1 BDDzero)).\n  intro y.  rewrite y.  cut (node1 = BDDzero).  intro H1.  rewrite H1.  reflexivity.\n  apply Neqb_complete; assumption.  intro y.  rewrite y.  elim (sumbool_of_bool (N.eqb node1 BDDone)).\n  intro y0.  rewrite y0.  cut (node1 = BDDone).  intro H1.  rewrite H1.  reflexivity.  \n  apply Neqb_complete.  assumption.  intro y0.  rewrite y0.  reflexivity.\nQed.\n\nLemma BDDor_1_lemma_one_1 :\n forall (cfg : BDDconfig) (memo : BDDor_memo) (node1 : ad) (bound : nat),\n BDDor_memo_lookup memo node1 BDDone = None ->\n BDDor_1 cfg memo node1 BDDone bound =\n (cfg, (BDDone, BDDor_memo_put memo node1 BDDone BDDone)).\nProof.\n  intros cfg memo node1 bound H.  elim bound.  simpl in |- *.  rewrite H.  elim (sumbool_of_bool (N.eqb node1 BDDzero)).\n  intro y.  rewrite y.  cut (node1 = BDDzero).  intro H0.  rewrite H0; reflexivity.\n  apply Neqb_complete.  assumption.  intro y.  rewrite y.  elim (sumbool_of_bool (N.eqb node1 BDDone)); intro y0.\n  rewrite y0.  cut (node1 = BDDone).  intro H0.  rewrite H0; reflexivity.  apply Neqb_complete.\n  assumption.  rewrite y0.  reflexivity.  intros n H0.  simpl in |- *.  rewrite H.  elim (sumbool_of_bool (N.eqb node1 BDDzero)).\n  intro y.  rewrite y.  cut (node1 = BDDzero).  intro H1.  rewrite H1.  reflexivity.\n  apply Neqb_complete; assumption.  intro y.  rewrite y.  elim (sumbool_of_bool (N.eqb node1 BDDone)).\n  intro y0.  rewrite y0.  cut (node1 = BDDone).  intro H1.  rewrite H1.  reflexivity.\n  apply Neqb_complete.  assumption.  intro y0.  rewrite y0.  reflexivity.\nQed.\n\nLemma BDDor_1_lemma_zero_2 :\n forall (cfg : BDDconfig) (memo : BDDor_memo) (node2 : ad) (bound : nat),\n BDDor_memo_lookup memo BDDzero node2 = None ->\n BDDor_1 cfg memo BDDzero node2 bound =\n (cfg, (node2, BDDor_memo_put memo BDDzero node2 node2)).\nProof.\n  intros cfg memo node2 bound H.  elim bound.  simpl in |- *.  rewrite H.  reflexivity.  intros n H0.  simpl in |- *.  rewrite H.  reflexivity.\nQed.\n\nLemma BDDor_1_lemma_one_2 :\n forall (cfg : BDDconfig) (memo : BDDor_memo) (node2 : ad) (bound : nat),\n BDDor_memo_lookup memo BDDone node2 = None ->\n BDDor_1 cfg memo BDDone node2 bound =\n (cfg, (BDDone, BDDor_memo_put memo BDDone node2 BDDone)).\nProof.\n  intros cfg memo node2 bound H.  elim bound.  simpl in |- *.  rewrite H.  reflexivity.  intros n H0.  simpl in |- *.  rewrite H.  reflexivity.\nQed.\n\nLemma BDDor_1_lemma_internal_1 :\n forall (cfg : BDDconfig) (memo : BDDor_memo) (node1 node2 : ad)\n   (bound bound' : nat),\n BDDor_memo_lookup memo node1 node2 = None ->\n BDDconfig_OK cfg ->\n is_internal_node cfg node1 ->\n is_internal_node cfg node2 ->\n max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)) < bound ->\n bound = S bound' ->\n BDDcompare (var cfg node1) (var cfg node2) = Datatypes.Eq ->\n BDDor_1 cfg memo node1 node2 bound =\n (fst\n    (BDDmake\n       (fst\n          (BDDor_1\n             (fst (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound'))\n             (snd\n                (snd\n                   (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound')))\n             (high cfg node1) (high cfg node2) bound')) \n       (var cfg node1)\n       (fst (snd (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound')))\n       (fst\n          (snd\n             (BDDor_1\n                (fst\n                   (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound'))\n                (snd\n                   (snd\n                      (BDDor_1 cfg memo (low cfg node1) \n                         (low cfg node2) bound'))) \n                (high cfg node1) (high cfg node2) bound')))),\n (snd\n    (BDDmake\n       (fst\n          (BDDor_1\n             (fst (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound'))\n             (snd\n                (snd\n                   (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound')))\n             (high cfg node1) (high cfg node2) bound')) \n       (var cfg node1)\n       (fst (snd (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound')))\n       (fst\n          (snd\n             (BDDor_1\n                (fst\n                   (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound'))\n                (snd\n                   (snd\n                      (BDDor_1 cfg memo (low cfg node1) \n                         (low cfg node2) bound'))) \n                (high cfg node1) (high cfg node2) bound')))),\n BDDor_memo_put\n   (snd\n      (snd\n         (BDDor_1\n            (fst (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound'))\n            (snd\n               (snd (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound')))\n            (high cfg node1) (high cfg node2) bound'))) node1 node2\n   (snd\n      (BDDmake\n         (fst\n            (BDDor_1\n               (fst (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound'))\n               (snd\n                  (snd\n                     (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound')))\n               (high cfg node1) (high cfg node2) bound')) \n         (var cfg node1)\n         (fst (snd (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound')))\n         (fst\n            (snd\n               (BDDor_1\n                  (fst\n                     (BDDor_1 cfg memo (low cfg node1) (low cfg node2) bound'))\n                  (snd\n                     (snd\n                        (BDDor_1 cfg memo (low cfg node1) \n                           (low cfg node2) bound'))) \n                  (high cfg node1) (high cfg node2) bound'))))))).\nProof.\n  intros cfg memo node1 node2 bound bound' H H0 H1 H2 H3 H4 H5.  rewrite H4.  simpl in |- *.  rewrite H.  cut (N.eqb node1 BDDzero = false).  cut (N.eqb node1 BDDone = false).\n  cut (N.eqb node2 BDDzero = false).  cut (N.eqb node2 BDDone = false).  intros H6 H7 H8 H9.\n  rewrite H6; rewrite H7; rewrite H8; rewrite H9; rewrite H5; reflexivity.\n  apply not_true_is_false.  unfold not in |- *.  intro H6.  cut (node2 = BDDone).  intro H7.\n  inversion H2.  inversion H8.  inversion H9.  rewrite H7 in H10.  rewrite (config_OK_one cfg H0) in H10; discriminate.\n  apply Neqb_complete.  assumption.  apply not_true_is_false.  unfold not in |- *; intro.\n  cut (node2 = BDDzero).  intro H7.  inversion H2.  inversion H8.  inversion H9.  rewrite H7 in H10.\n  rewrite (config_OK_zero cfg H0) in H10; discriminate.  apply Neqb_complete; assumption.\n  apply not_true_is_false.  unfold not in |- *; intro.  cut (node1 = BDDone).  intro H7.\n  inversion H1.  inversion H8.  inversion H9.  rewrite H7 in H10.\n  rewrite (config_OK_one cfg H0) in H10; discriminate.  apply Neqb_complete; assumption.\n  apply not_true_is_false.  unfold not in |- *; intro.  cut (node1 = BDDzero).  intro H7.\n  inversion H1.  inversion H8.  inversion H9.  rewrite H7 in H10.  rewrite (config_OK_zero cfg H0) in H10; discriminate.\n  apply Neqb_complete; assumption.\nQed.\n\nLemma BDDor_1_lemma_internal_2 :\n forall (cfg : BDDconfig) (memo : BDDor_memo) (node1 node2 : ad)\n   (bound bound' : nat),\n BDDor_memo_lookup memo node1 node2 = None ->\n BDDconfig_OK cfg ->\n is_internal_node cfg node1 ->\n is_internal_node cfg node2 ->\n max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)) < bound ->\n bound = S bound' ->\n BDDcompare (var cfg node1) (var cfg node2) = Datatypes.Lt ->\n BDDor_1 cfg memo node1 node2 bound =\n (fst\n    (BDDmake\n       (fst\n          (BDDor_1 (fst (BDDor_1 cfg memo node1 (low cfg node2) bound'))\n             (snd (snd (BDDor_1 cfg memo node1 (low cfg node2) bound')))\n             node1 (high cfg node2) bound')) (var cfg node2)\n       (fst (snd (BDDor_1 cfg memo node1 (low cfg node2) bound')))\n       (fst\n          (snd\n             (BDDor_1 (fst (BDDor_1 cfg memo node1 (low cfg node2) bound'))\n                (snd (snd (BDDor_1 cfg memo node1 (low cfg node2) bound')))\n                node1 (high cfg node2) bound')))),\n (snd\n    (BDDmake\n       (fst\n          (BDDor_1 (fst (BDDor_1 cfg memo node1 (low cfg node2) bound'))\n             (snd (snd (BDDor_1 cfg memo node1 (low cfg node2) bound')))\n             node1 (high cfg node2) bound')) (var cfg node2)\n       (fst (snd (BDDor_1 cfg memo node1 (low cfg node2) bound')))\n       (fst\n          (snd\n             (BDDor_1 (fst (BDDor_1 cfg memo node1 (low cfg node2) bound'))\n                (snd (snd (BDDor_1 cfg memo node1 (low cfg node2) bound')))\n                node1 (high cfg node2) bound')))),\n BDDor_memo_put\n   (snd\n      (snd\n         (BDDor_1 (fst (BDDor_1 cfg memo node1 (low cfg node2) bound'))\n            (snd (snd (BDDor_1 cfg memo node1 (low cfg node2) bound'))) node1\n            (high cfg node2) bound'))) node1 node2\n   (snd\n      (BDDmake\n         (fst\n            (BDDor_1 (fst (BDDor_1 cfg memo node1 (low cfg node2) bound'))\n               (snd (snd (BDDor_1 cfg memo node1 (low cfg node2) bound')))\n               node1 (high cfg node2) bound')) (var cfg node2)\n         (fst (snd (BDDor_1 cfg memo node1 (low cfg node2) bound')))\n         (fst\n            (snd\n               (BDDor_1 (fst (BDDor_1 cfg memo node1 (low cfg node2) bound'))\n                  (snd (snd (BDDor_1 cfg memo node1 (low cfg node2) bound')))\n                  node1 (high cfg node2) bound'))))))).\nProof.\n  intros cfg memo node1 node2 bound bound' H H0 H1 H2 H3 H4 H5.  rewrite H4.  simpl in |- *.  rewrite H.  cut (N.eqb node1 BDDzero = false).  cut (N.eqb node1 BDDone = false).\n  cut (N.eqb node2 BDDzero = false).  cut (N.eqb node2 BDDone = false).  intros H6 H7 H8 H9.\n  rewrite H6; rewrite H7; rewrite H8; rewrite H9; rewrite H5; reflexivity.\n  apply not_true_is_false.  unfold not in |- *.  intro H6.  cut (node2 = BDDone).  intro H7.\n  inversion H2.  inversion H8.  inversion H9.  rewrite H7 in H10.  rewrite (config_OK_one cfg H0) in H10; discriminate.\n  apply Neqb_complete.  assumption.  apply not_true_is_false.  unfold not in |- *; intro.\n  cut (node2 = BDDzero).  intro H7.  inversion H2.  inversion H8.  inversion H9.  rewrite H7 in H10.\n  rewrite (config_OK_zero cfg H0) in H10; discriminate.  apply Neqb_complete; assumption.\n  apply not_true_is_false.  unfold not in |- *; intro.  cut (node1 = BDDone).  intro H7.\n  inversion H1.  inversion H8.  inversion H9.  rewrite H7 in H10.\n  rewrite (config_OK_one cfg H0) in H10; discriminate.  apply Neqb_complete; assumption.\n  apply not_true_is_false.  unfold not in |- *; intro.  cut (node1 = BDDzero).  intro H7.\n  inversion H1.  inversion H8.  inversion H9.  rewrite H7 in H10.  rewrite (config_OK_zero cfg H0) in H10; discriminate.\n  apply Neqb_complete; assumption.\nQed.\n\nLemma BDDor_1_lemma_internal_3 :\n forall (cfg : BDDconfig) (memo : BDDor_memo) (node1 node2 : ad)\n   (bound bound' : nat),\n BDDor_memo_lookup memo node1 node2 = None ->\n BDDconfig_OK cfg ->\n is_internal_node cfg node1 ->\n is_internal_node cfg node2 ->\n max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)) < bound ->\n bound = S bound' ->\n BDDcompare (var cfg node1) (var cfg node2) = Datatypes.Gt ->\n BDDor_1 cfg memo node1 node2 bound =\n (fst\n    (BDDmake\n       (fst\n          (BDDor_1 (fst (BDDor_1 cfg memo (low cfg node1) node2 bound'))\n             (snd (snd (BDDor_1 cfg memo (low cfg node1) node2 bound')))\n             (high cfg node1) node2 bound')) (var cfg node1)\n       (fst (snd (BDDor_1 cfg memo (low cfg node1) node2 bound')))\n       (fst\n          (snd\n             (BDDor_1 (fst (BDDor_1 cfg memo (low cfg node1) node2 bound'))\n                (snd (snd (BDDor_1 cfg memo (low cfg node1) node2 bound')))\n                (high cfg node1) node2 bound')))),\n (snd\n    (BDDmake\n       (fst\n          (BDDor_1 (fst (BDDor_1 cfg memo (low cfg node1) node2 bound'))\n             (snd (snd (BDDor_1 cfg memo (low cfg node1) node2 bound')))\n             (high cfg node1) node2 bound')) (var cfg node1)\n       (fst (snd (BDDor_1 cfg memo (low cfg node1) node2 bound')))\n       (fst\n          (snd\n             (BDDor_1 (fst (BDDor_1 cfg memo (low cfg node1) node2 bound'))\n                (snd (snd (BDDor_1 cfg memo (low cfg node1) node2 bound')))\n                (high cfg node1) node2 bound')))),\n BDDor_memo_put\n   (snd\n      (snd\n         (BDDor_1 (fst (BDDor_1 cfg memo (low cfg node1) node2 bound'))\n            (snd (snd (BDDor_1 cfg memo (low cfg node1) node2 bound')))\n            (high cfg node1) node2 bound'))) node1 node2\n   (snd\n      (BDDmake\n         (fst\n            (BDDor_1 (fst (BDDor_1 cfg memo (low cfg node1) node2 bound'))\n               (snd (snd (BDDor_1 cfg memo (low cfg node1) node2 bound')))\n               (high cfg node1) node2 bound')) (var cfg node1)\n         (fst (snd (BDDor_1 cfg memo (low cfg node1) node2 bound')))\n         (fst\n            (snd\n               (BDDor_1 (fst (BDDor_1 cfg memo (low cfg node1) node2 bound'))\n                  (snd (snd (BDDor_1 cfg memo (low cfg node1) node2 bound')))\n                  (high cfg node1) node2 bound'))))))).\nProof.\n  intros cfg memo node1 node2 bound bound' H H0 H1 H2 H3 H4 H5.  rewrite H4.  simpl in |- *.  rewrite H.  cut (N.eqb node1 BDDzero = false).  cut (N.eqb node1 BDDone = false).\n  cut (N.eqb node2 BDDzero = false).  cut (N.eqb node2 BDDone = false).  intros H6 H7 H8 H9.\n  rewrite H6; rewrite H7; rewrite H8; rewrite H9; rewrite H5; reflexivity.\n  apply not_true_is_false.  unfold not in |- *.  intro H6.  cut (node2 = BDDone).  intro H7.\n  inversion H2.  inversion H8.  inversion H9.  rewrite H7 in H10.  rewrite (config_OK_one cfg H0) in H10; discriminate.\n  apply Neqb_complete.  assumption.  apply not_true_is_false.  unfold not in |- *; intro.\n  cut (node2 = BDDzero).  intro H7.  inversion H2.  inversion H8.  inversion H9.  rewrite H7 in H10.\n  rewrite (config_OK_zero cfg H0) in H10; discriminate.  apply Neqb_complete; assumption.\n  apply not_true_is_false.  unfold not in |- *; intro.  cut (node1 = BDDone).  intro H7.\n  inversion H1.  inversion H8.  inversion H9.  rewrite H7 in H10.\n  rewrite (config_OK_one cfg H0) in H10; discriminate.  apply Neqb_complete; assumption.\n  apply not_true_is_false.  unfold not in |- *; intro.  cut (node1 = BDDzero).  intro H7.\n  inversion H1.  inversion H8.  inversion H9.  rewrite H7 in H10.  rewrite (config_OK_zero cfg H0) in H10; discriminate.\n  apply Neqb_complete; assumption.\nQed.\n\n\n\nLemma BDDvar_le_max_2 :\n forall x y : BDDvar, BDDvar_le x (BDDvar_max y x) = true.\nProof.\n  unfold BDDvar_max in |- *.  unfold BDDvar_le in |- *.  intros x y.  elim (sumbool_of_bool (Nleb y x)).\n  intro y0.  rewrite y0.  apply Nleb_refl.  intro y0.  rewrite y0.  apply Nltb_leb_weak.\n  assumption.\nQed.\n\nLemma BDDvar_le_max_1 :\n forall x y : BDDvar, BDDvar_le x (BDDvar_max x y) = true.\nProof.\n  intros x y.  elim (sumbool_of_bool (Nleb x y)); unfold BDDvar_max in |- *;\n   unfold BDDvar_le in |- *.\n  intro y0.  rewrite y0.  assumption.  intro y0.  rewrite y0.  apply Nleb_refl.\nQed.\n\nLemma BDDor_1_internal :\n forall (cfg : BDDconfig) (memo : BDDor_memo) (node1 node2 : ad)\n   (bound : nat),\n BDDconfig_OK cfg ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n BDDor_memo_OK cfg memo ->\n is_internal_node (fst (BDDor_1 cfg memo node1 node2 bound))\n   (fst (snd (BDDor_1 cfg memo node1 node2 bound))) ->\n is_internal_node cfg node1 \\/ is_internal_node cfg node2.\nProof.\n  intros cfg memo node1 node2 bound H H0 H1 H2 H3.  elim H0; intro.  elim H1; intro.  rewrite H4 in H3.  rewrite H5 in H3.\n  elim (option_sum _ (BDDor_memo_lookup memo BDDzero BDDzero)).  intro y.  inversion y.\n  rewrite (BDDor_1_lemma_1 cfg memo BDDzero BDDzero x bound H6) in H3.  simpl in H3.\n  unfold BDDor_memo_OK in H2.  cut\n   (bool_fun_eq (bool_fun_of_BDD cfg x)\n      (bool_fun_or (bool_fun_of_BDD cfg BDDzero)\n         (bool_fun_of_BDD cfg BDDzero))).\n  intro H7.  rewrite (proj1 (bool_fun_of_BDD_semantics cfg H)) in H7.  cut (x = BDDzero).\n  intro H8.  inversion H3.  inversion H9.  inversion H10.  rewrite H8 in H11.\n  rewrite (config_OK_zero cfg H) in H11.  discriminate.  apply BDDunique with (cfg := cfg).\n  assumption.  right.  right.  unfold in_dom in |- *.  inversion H3.  inversion H8.  inversion H9.\n  rewrite H10.  reflexivity.  left; reflexivity.  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_or bool_fun_zero bool_fun_zero).\n  assumption.  rewrite (proj1 (bool_fun_of_BDD_semantics cfg H)).  unfold bool_fun_eq in |- *.\n  reflexivity.  exact (proj2 (proj2 (proj2 (proj2 (H2 BDDzero BDDzero x H6))))).\n  intro y.  rewrite (BDDor_1_lemma_zero_1 cfg memo BDDzero bound y) in H3.  simpl in H3.\n  inversion H3.  inversion H6.  inversion H7.  rewrite (config_OK_zero cfg H) in H8.\n  discriminate.  elim H5; clear H5; intro.  rewrite H4 in H3.  rewrite H5 in H3.\n  elim (option_sum _ (BDDor_memo_lookup memo BDDzero BDDone)).  intro y.  inversion y.\n  rewrite (BDDor_1_lemma_1 cfg memo BDDzero BDDone x bound H6) in H3.  simpl in H3.\n  unfold BDDor_memo_OK in H2.  cut\n   (bool_fun_eq (bool_fun_of_BDD cfg x)\n      (bool_fun_or (bool_fun_of_BDD cfg BDDzero) (bool_fun_of_BDD cfg BDDone))).\n  intro H7.  rewrite (proj1 (bool_fun_of_BDD_semantics cfg H)) in H7.  rewrite (proj1 (proj2 (bool_fun_of_BDD_semantics cfg H))) in H7.\n  cut (x = BDDone).  intro H8.  inversion H3.  inversion H9.  inversion H10.  rewrite H8 in H11.\n  rewrite (config_OK_one cfg H) in H11.  discriminate.  apply BDDunique with (cfg := cfg).\n  assumption.  right.  right.  unfold in_dom in |- *.  inversion H3.  inversion H8.\n  inversion H9.  rewrite H10.  reflexivity.  right; left; reflexivity.\n  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_or bool_fun_zero bool_fun_one).\n  assumption.  rewrite (proj1 (proj2 (bool_fun_of_BDD_semantics cfg H))).\n  unfold bool_fun_eq in |- *.  reflexivity.  exact (proj2 (proj2 (proj2 (proj2 (H2 BDDzero BDDone x H6))))).\n  intro y.  rewrite (BDDor_1_lemma_one_1 cfg memo BDDzero bound y) in H3.  simpl in H3.\n  inversion H3.  inversion H6.  inversion H7.  rewrite (config_OK_one cfg H) in H8.\n  discriminate.  right.  apply in_dom_is_internal.  assumption.  elim H4; clear H4; intro.\n  rewrite H4 in H3.  elim (option_sum _ (BDDor_memo_lookup memo BDDone node2)).\n  intro y.  inversion y.  rewrite (BDDor_1_lemma_1 cfg memo BDDone node2 x bound H5) in H3.\n  simpl in H3.  unfold BDDor_memo_OK in H2.  cut (x = BDDone).  intro H6.  rewrite H6 in H3.\n  inversion H3.  inversion H7.  inversion H8.  rewrite (config_OK_one cfg H) in H9.\n  discriminate.  apply BDDunique with (cfg := cfg).  assumption.  exact (proj1 (proj2 (proj2 (H2 BDDone node2 x H5)))).\n  right; left; reflexivity.  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_or (bool_fun_of_BDD cfg BDDone)\n                (bool_fun_of_BDD cfg node2)).\n  exact (proj2 (proj2 (proj2 (proj2 (H2 BDDone node2 x H5))))).\n  rewrite (proj1 (proj2 (bool_fun_of_BDD_semantics cfg H))).  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_or (bool_fun_of_BDD cfg node2) bool_fun_one).\n  apply bool_fun_or_commute.  apply bool_fun_or_one.  intro y.  rewrite (BDDor_1_lemma_one_2 cfg memo node2 bound y) in H3.\n  simpl in H3.  inversion H3.  inversion H5.  inversion H6.  rewrite (config_OK_one cfg H) in H7.\n  discriminate.  left.  apply in_dom_is_internal.  assumption.\nQed.", "meta": {"author": "coq-contribs", "repo": "bdds", "sha": "2a66529afca7c780fa18d21ecd4f6c8d55182a6d", "save_path": "github-repos/coq/coq-contribs-bdds", "path": "github-repos/coq/coq-contribs-bdds/bdds-2a66529afca7c780fa18d21ecd4f6c8d55182a6d/bdd7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24512061337500554}}
{"text": "(* Correctness proof of the lowering pass *)\n\nRequire Export specIR.\nRequire Export lowering.\nRequire Export ir_properties.\nRequire Export internal_simulations.\n\n(* Matching stackframes: a version may have been replaced with its lowered version *)\nInductive match_stackframe: stackframe -> stackframe -> Prop :=\n| frame_same: forall sf, match_stackframe sf sf\n| frame_lowered:\n    forall r v lbl rm vlow\n      (LOW: lowering_version v = vlow),\n      match_stackframe (Stackframe r v lbl rm) (Stackframe r vlow lbl rm).\n\n(* Generalizing match_stackframe to the entire stack *)\nInductive match_stack: stack -> stack -> Prop :=\n| match_nil:\n    match_stack nil nil\n| match_cons:\n    forall s s' sf sf'\n      (MS: match_stack s s')\n      (MSF: match_stackframe sf sf'),\n      match_stack (sf::s) (sf'::s').\n\nLemma match_stack_same:\n  forall s, match_stack s s.\nProof.\n  intros. induction s; constructor. auto. apply frame_same.\nQed.\n\n(** * Lowering Properties *)\nLemma base_low_refl_code:\n  forall c,\n    base_code c ->\n    lowering_code c = c.\nProof.\n  intros c H. unfold base_code in H. unfold lowering_code.\n  unfold PTree.map1. induction c; auto.\n  rewrite IHc2. 2: { intros. eapply H with (pc:=(pc~1)%positive). simpl. auto. }\n  rewrite IHc1. 2: { intros. eapply H with (pc:=(pc~0)%positive). simpl. auto. }\n  destruct o; simpl; auto.\n  assert (~is_spec i). { apply H with (pc:=1%positive). simpl. auto. }\n  assert (transf_instr i = i). { destruct i; auto. exfalso. apply H0. constructor. }\n  rewrite H1. auto.\nQed.\n\nLemma fn_base_low:\n  forall f,\n    lowering_version (fn_base f) = fn_base f.\nProof.\n  intros f. unfold lowering_version. rewrite base_low_refl_code.\n  destruct f; simpl; auto. destruct fn_base; simpl; auto.\n  destruct f. simpl. unfold base_version in base_no_spec. auto.\nQed.\n\nLemma base_low_refl:\n  forall v,\n    base_version v ->\n    lowering_version v = v.\nProof.\n  intros v H. unfold lowering_version. unfold base_version in H. rewrite base_low_refl_code; auto.\n  destruct v. simpl. auto.\nQed.  \n\nLemma same_params:\n  forall f,\n    (fn_params f) = (fn_params (lowering_function f)).\nProof.\n  intros. unfold lowering_function. destruct (fn_opt f); simpl; auto.\nQed.\n\nLemma same_entry:\n  forall f,\n    ver_entry (current_version f) = ver_entry (current_version (lowering_function f)).\nProof.\n  intros f. unfold lowering_function. destruct (fn_opt f) eqn:OPT; simpl; auto.\n  unfold current_version. rewrite OPT. auto.\nQed.\n\nLemma lowering_current:\n  forall f, lowering_version (current_version f) = current_version (lowering_function f).\nProof.\n  intros f. unfold lowering_function. destruct (fn_opt f) eqn:OPT; simpl; auto.\n  unfold current_version. rewrite OPT. simpl. auto.\n  unfold current_version. rewrite OPT. apply fn_base_low.\nQed.\n\n(** * Match states invariant  *)\n(* This proof is a lockstep backward internal simulation.\n   Each step of the optimized program is matched with a step of the source.\n   No index is needed for the match_states invariant.\n   Framestate steps are matched with Nop steps.\n\n<<\n                 \n       st1 --------------- st2\n        |                   |\n       t|                   |t\n        |                   |\n        v                   v\n       st1'--------------- st2'\n                 \n>>\n*)\n\nInductive match_states (p:program) : unit -> specIR.state -> specIR.state -> Prop :=\n| lowered_match:\n    forall s s' v vlow pc rm ms\n      (LOW: lowering_version v = vlow)\n      (MATCHSTACK: match_stack s s'),\n      (match_states p) tt (State s v pc rm ms) (State s' vlow pc rm ms)\n| refl_match:\n    forall s s' v pc rm ms\n      (MATCHSTACK: match_stack s s'),\n      (match_states p) tt (State s v pc rm ms) (State s' v pc rm ms)\n| final_match:\n    forall retval ms,\n      (match_states p) tt (Final retval ms) (Final retval ms).\n\nInductive order : unit -> unit -> Prop := .\nLemma wfounded:\n  well_founded order.\nProof.\n  unfold well_founded. intros. destruct a. constructor. intros. inv H.\nQed.\n\nLemma trans:\n  Relation_Definitions.transitive _ order.\nProof.\n  unfold Relation_Definitions.transitive. intros. inv H.\nQed.\n\n(** * Code preservation properties  *)\nLemma preserved_code:\n  forall v vlow i pc,\n    lowering_version v = vlow ->  \n    (ver_code vlow) # pc = Some i ->\n    exists i', (ver_code v) # pc = Some i' /\\ transf_instr i' = i.\nProof.\n  intros v vlow i pc LOW CODE. unfold lowering_version in LOW. rewrite <- LOW in CODE.\n  simpl in CODE. unfold lowering_code in CODE.\n  rewrite PTree.gmap1 in CODE. unfold option_map in CODE.\n  destruct ((ver_code v)!pc); inv CODE.\n  exists i0. split; auto.\nQed.\n\nLemma code_preserved:\n  forall v vlow i pc,\n    lowering_version v = vlow ->  \n    (ver_code v) # pc = Some i ->\n    (ver_code vlow) # pc = Some (transf_instr i).\nProof.\n  intros v vlow i pc LOW CODE. unfold lowering_version in LOW. rewrite <- LOW. simpl.\n  unfold lowering_code. rewrite PTree.gmap1. unfold option_map. rewrite CODE. auto.\nQed.\n\nLemma base_version_unchanged:\n  forall p fid,\n    find_base_version fid p = find_base_version fid (lowering p).\nProof.\n  intros. unfold find_base_version, lowering, find_function, find_function_list.\n  simpl. rewrite PTree.gmap1. unfold option_map.\n  destruct ((prog_funlist p)!fid) eqn:FINDF; auto.\n  unfold lowering_function. destruct (fn_opt f); auto.\nQed.\n\nLemma find_function_lowered:\n  forall p fid f,\n    find_function fid (lowering p) = Some f ->\n    exists f', find_function fid p = Some f' /\\ lowering_function f' = f.\nProof.\n  intros p fid f H. unfold find_function, find_function_list in *. unfold lowering in H. simpl in H.\n  rewrite PTree.gmap1 in H. unfold option_map in H.\n  destruct ((prog_funlist p)!fid) eqn:FINDF; inv H.\n  exists f0. split; auto.\nQed.\n\nLemma lowered_find_function:\n  forall p fid f,\n    find_function fid p = Some f ->\n    find_function fid (lowering p) = Some (lowering_function f).\nProof.\n  unfold find_function, find_function_list, lowering. intros p fid f FINDF. simpl.\n  rewrite PTree.gmap1. unfold option_map. rewrite FINDF. auto.\nQed.\n\n(** * Invariant preservation  *)\nLemma match_synth:\n  forall p rm sl synthlow p0,\n    p0 = lowering p ->\n    specIR.synthesize_frame p0 rm sl synthlow ->\n    exists synthsrc, specIR.synthesize_frame p rm sl synthsrc /\\ match_stack synthsrc synthlow.\nProof.\n  intros p rm sl synthlow p0 LOW SYNTH.\n  induction SYNTH; intros.\n  - exists nil. split; constructor.\n  - specialize (IHSYNTH LOW). destruct IHSYNTH as [synthsrc [SYNTH' MATCH]]. exists ((Stackframe r version l update)::synthsrc).\n    split. constructor; auto.\n    rewrite LOW in FINDV. rewrite <- base_version_unchanged in FINDV. rewrite FINDV. auto.\n    constructor; auto. constructor; auto.\nQed.\n\nLemma synth_match:\n  forall p rm sl synth,\n    specIR.synthesize_frame p rm sl synth ->\n    exists synthlow, specIR.synthesize_frame (lowering p) rm sl synthlow.\nProof.\n  intros p rm sl synth SYNTH. induction SYNTH.\n  - exists nil. constructor.\n  - destruct IHSYNTH as [sylow IHSYNTH].\n    rewrite base_version_unchanged in FINDV.\n    exists (Stackframe r version l update::sylow). constructor; auto.\nQed.\n\nLemma app_match:\n  forall synth synthlow s slow,\n    match_stack s slow ->\n    match_stack synth synthlow ->\n    match_stack (synth++s) (synthlow++slow).\nProof.\n  intros. induction H0.\n  - simpl. auto.\n  - repeat rewrite <- app_comm_cons. apply match_cons; auto.\nQed.\n\n\n(* for backward simulations, safety of the source must be shown to be preserved *)\nLemma safe_preserved_state:\n  forall p i s v pc rm ms s2,\n    match_states p i (State s v pc rm ms) s2 ->\n    safe (specir_sem p) (State s v pc rm ms) ->\n    exists t, exists s2', specir_step (lowering p) s2 t s2'.\nProof.\n  intros p i s v pc rm ms s2 MATCH SAFE. inv MATCH.\n  { apply safe_step in SAFE as [nexts [t STEP]]. exists t.\n    inv STEP.\n    - inv STEP0; eapply code_preserved in CODE; eauto; simpl in CODE; simpl; eauto.\n      + exists (State s' (lowering_version v) next rm ms). apply nd_exec_lowered. eapply exec_Nop. eauto.\n      + exists (State s' (lowering_version v) next (rm#reg<-v0) ms). apply nd_exec_lowered. eapply exec_Op; eauto.\n      + exists (State s' (lowering_version v) next newrm ms). apply nd_exec_lowered. eapply exec_Move; eauto.\n      + exists (State s' (lowering_version v) (pc_cond v0 iftrue iffalse) rm ms). apply nd_exec_lowered.\n        eapply exec_Cond; eauto.\n      + apply lowered_find_function in FINDF. simpl in FINDF.\n        exists (State (Stackframe retreg (lowering_version v) next rm ::s') (current_version (lowering_function func)) (ver_entry (current_version (lowering_function func))) newrm ms).\n        apply nd_exec_lowered. eapply exec_Call; eauto. unfold lowering_function.\n        destruct (fn_opt func); simpl; auto.      \n      + inv MATCHSTACK. inv MSF.\n        * exists (State s'0 fprev next (rmprev#retreg<-retval) ms).\n          apply nd_exec_lowered. eapply exec_Return; eauto.\n        * exists (State s'0 (lowering_version fprev) next (rmprev#retreg<-retval) ms).\n          apply nd_exec_lowered. eapply exec_Return; eauto.\n      + inv MATCHSTACK. exists (Final retval ms). apply nd_exec_lowered. eapply exec_Return_Final; eauto.\n      + exists (State s' (lowering_version v) next rm ms). apply nd_exec_lowered. eapply exec_Printexpr; eauto.\n      + exists (State s' (lowering_version v) next rm ms). apply nd_exec_lowered. eapply exec_Printstring. auto.\n      + exists (State s' (lowering_version v) next rm newms). apply nd_exec_lowered. eapply exec_Store; eauto.\n      + exists (State s' (lowering_version v) next (rm#reg<-val) ms). apply nd_exec_lowered. eapply exec_Load; eauto.\n      + exists (State s' (lowering_version v) next rm ms). apply nd_exec_lowered. eapply exec_Assume_holds; eauto.\n      + apply synth_match in SYNTH as [synthlow SYNTH]. rewrite base_version_unchanged in FINDF.\n        exists (State (synthlow ++ s') newver la newrm ms). apply nd_exec_lowered. eapply exec_Assume_fails; eauto.\n    - exists (State s' (lowering_version v) next rm ms). apply nd_exec_lowered. eapply exec_Nop. inv DEOPT_COND.\n      eapply code_preserved in CODE; eauto.\n    - exists (State s' (lowering_version v) next rm ms). apply nd_exec_lowered. eapply exec_Nop. inv DEOPT_COND.\n      eapply code_preserved in CODE; eauto. }\n  { apply safe_step in SAFE as [nexts [t STEP]]. exists t.\n    inv STEP.\n    - inv STEP0. \n      + exists (State s' v next rm ms). apply nd_exec_lowered. eapply exec_Nop. eauto.\n      + exists (State s' v next (rm#reg<-v0) ms). apply nd_exec_lowered. eapply exec_Op; eauto.\n      + exists (State s' v next newrm ms). apply nd_exec_lowered. eapply exec_Move; eauto.\n      + exists (State s' v (pc_cond v0 iftrue iffalse) rm ms). apply nd_exec_lowered. eapply exec_Cond; eauto.\n      + apply lowered_find_function in FINDF. simpl in FINDF.\n        exists (State (Stackframe retreg v next rm ::s') (current_version (lowering_function func)) (ver_entry (current_version (lowering_function func))) newrm ms).\n        apply nd_exec_lowered. eapply exec_Call; eauto. unfold lowering_function.\n        destruct (fn_opt func); simpl; auto.      \n      + inv MATCHSTACK. inv MSF.\n        * exists (State s'0 fprev next (rmprev#retreg<-retval) ms).\n          apply nd_exec_lowered. eapply exec_Return; eauto.\n        * exists (State s'0 (lowering_version fprev) next (rmprev#retreg<-retval) ms).\n          apply nd_exec_lowered. eapply exec_Return; eauto.\n      + inv MATCHSTACK. exists (Final retval ms). apply nd_exec_lowered. eapply exec_Return_Final; eauto.\n      + exists (State s' v next rm ms). apply nd_exec_lowered. eapply exec_Printexpr; eauto.\n      + exists (State s' v next rm ms). apply nd_exec_lowered. eapply exec_Printstring. auto.\n      + exists (State s' v next rm newms). apply nd_exec_lowered. eapply exec_Store; eauto.\n      + exists (State s' v next (rm#reg<-val) ms). apply nd_exec_lowered. eapply exec_Load; eauto.\n      + exists (State s' v next rm ms). apply nd_exec_lowered. eapply exec_Assume_holds; eauto.\n      + apply synth_match in SYNTH as [synthlow SYNTH]. rewrite base_version_unchanged in FINDF.\n        exists (State (synthlow ++ s') newver la newrm ms). apply nd_exec_lowered. eapply exec_Assume_fails; eauto.\n    - exists (State s' v next rm ms). inv DEOPT_COND. apply synth_match in SYNTH as [sl' SYNTH].\n      eapply nd_exec_Framestate_go_on. \n      econstructor; eauto. rewrite <- base_version_unchanged. eauto. \n    - exists (State s' v next rm ms). inv DEOPT_COND. apply synth_match in SYNTH as [sl' SYNTH].\n      eapply nd_exec_Framestate_go_on. \n      econstructor; eauto. rewrite <- base_version_unchanged. eauto. }\nQed.\n\nLemma safe_preserved_final:\n  forall p i v ms s2,\n    match_states p i (Final v ms) s2 ->\n    exists r, final_state (lowering p) s2 r.\nProof.\n  intros p i v ms s2 MATCH. inv MATCH. exists v. constructor.\nQed.\n\n\n(* Proved directly with a backward simulation *)\nTheorem lowering_correct:\n  forall p newp,\n    lowering p = newp ->\n    backward_internal_simulation p newp.\nProof.\n  intros. apply Backward_internal_simulation with (bsim_match_states:=match_states p) (bsim_order:=order).\n  - apply wfounded.\n  - apply trans.\n  - unfold reflexive_forge. intros synchro stack r1 s1 ms FORGE.\n    destruct synchro; simpl in FORGE; repeat do_ok; simpl.\n    + erewrite lowered_find_function; eauto. simpl. rewrite <- same_params. rewrite HDO0. simpl.\n      repeat (esplit; eauto). simpl. rewrite <- same_entry. apply lowered_match.\n      apply lowering_current. apply match_stack_same.\n    + destruct stack; try destruct s; inv FORGE.\n      * repeat (esplit; eauto). constructor.\n      * repeat (esplit; eauto). simpl. apply refl_match. apply match_stack_same.\n    + destruct d. repeat do_ok. simpl. rewrite <- base_version_unchanged. rewrite HDO0. simpl.\n      repeat (esplit; eauto). simpl. apply refl_match. apply match_stack_same.\n    + inv FORGE. exists r1. exists s1. split; auto. exists tt. destruct r1; simpl.\n      * apply refl_match. apply match_stack_same.\n      * apply final_match.\n  - intros i s1 s2 r MATCH SAFE FINAL.\n    inv FINAL. inv MATCH. exists (Final r ms). split. apply star_refl. constructor.\n\n  - intros i s1 s2 MATCH SAFE.  (* safe preserved *)\n    inv MATCH.\n    + eapply safe_preserved_state in SAFE as [t [s2' STEP]]. 2: constructor; eauto.\n      right. exists t. exists s2'. auto.\n    + eapply safe_preserved_state in SAFE as [t [s2' STEP]]. \n      right. exists t. exists s2'. apply STEP. apply refl_match. auto.\n    + left. simpl. eapply safe_preserved_final. constructor.\n\n  - intros s2 t s2' STEP i s1 MATCH SAFE. exists tt. inv MATCH.\n    +                           (* lowered_match *)\n      inv STEP.\n      { inv STEP0; eapply preserved_code in CODE as [i' [CODE TRANSF]]; eauto; destruct i'; inv TRANSF.\n        - exists (State s v next rm ms). split. (* When Nop in the target comes from Nop in the source *)\n            left. apply plus_one. apply nd_exec_lowered. eapply exec_Nop; eauto.\n            constructor; auto.\n        - exists (State s v next rm ms). split. (* Nop in the target comes from Framestate in the source *)\n          left. apply plus_one. apply safe_step in SAFE as [s'' [t STEP]].\n          { inv STEP.\n            + inv STEP0; rewrite CODE0 in CODE; inv CODE.\n            + inv DEOPT_COND. rewrite CODE0 in CODE. inv CODE.\n              eapply nd_exec_Framestate_go_on. econstructor; eauto.\n            + inv DEOPT_COND. rewrite CODE0 in CODE. inv CODE.\n              eapply nd_exec_Framestate_go_on. econstructor; eauto. }\n          constructor; auto.\n        - exists (State s v next (rm#reg<-v0) ms). split.\n          left. apply plus_one. apply nd_exec_lowered. eapply exec_Op; eauto.\n          constructor; auto.\n        - exists (State s v next newrm ms). split.\n          left. apply plus_one. apply nd_exec_lowered. eapply exec_Move; eauto.\n          constructor; auto.\n        - exists (State s v (pc_cond v0 iftrue iffalse) rm ms). split.\n          left. apply plus_one. apply nd_exec_lowered. eapply exec_Cond; eauto.\n          constructor; auto.\n        - destruct (fn_opt func) eqn:OPT.\n          + apply find_function_lowered in FINDF as [f' [FINDF LOW]].\n            exists (State (Stackframe retreg v next rm::s) (current_version f') (ver_entry (current_version f')) newrm ms).\n            split.\n            left. apply plus_one. apply nd_exec_lowered.\n            { eapply exec_Call.\n              - apply CODE.\n              - apply FINDF.\n              - auto.\n              - apply EVALL.\n              - rewrite <- LOW in INIT_REGS. unfold lowering_function in INIT_REGS.\n                destruct (fn_opt f'); simpl in INIT_REGS; auto. }\n            assert (ver_entry (current_version f') = ver_entry (current_version func)).\n            { rewrite <- LOW. unfold lowering_function, current_version.\n              destruct (fn_opt f') eqn:OPT'; simpl; auto.\n              rewrite OPT'. auto. }\n            rewrite H. constructor; auto.\n            * rewrite <- LOW. unfold current_version, lowering_function.\n              destruct (fn_opt f') eqn:OPT'; simpl; try rewrite OPT'; auto.\n              apply fn_base_low.\n            * constructor; auto. constructor; auto.\n          + exists (State (Stackframe retreg v next rm::s) (current_version func) (ver_entry (current_version func)) newrm ms). split.\n            left. apply plus_one. apply nd_exec_lowered.\n            unfold find_function, find_function_list, lowering in *. simpl in FINDF.\n            rewrite PTree.gmap1 in FINDF. unfold option_map in FINDF. simpl.\n            destruct ((prog_funlist p)! fid) eqn:FIND; inv FINDF.\n            destruct (fn_opt f) eqn:OPT'. { unfold lowering_function in OPT. rewrite OPT' in OPT. inv OPT. }\n            { eapply exec_Call.\n              - apply CODE.\n              - unfold find_function, find_function_list. rewrite FIND. auto.\n              - unfold current_version. unfold lowering_function. rewrite OPT'. rewrite OPT'. auto.\n              - apply EVALL.\n              - unfold lowering_function in INIT_REGS. rewrite OPT' in INIT_REGS. auto. }\n            constructor; auto.\n            * unfold current_version. rewrite OPT. apply fn_base_low.\n            * constructor; auto. constructor; auto.\n        - inv MATCHSTACK. inv MSF.\n          + exists (State s1 fprev next (rmprev#retreg<-retval) ms). split.\n            left. apply plus_one. apply nd_exec_lowered. eapply exec_Return; eauto.\n            apply refl_match. auto.\n          + exists (State s1 v0 next (rmprev#retreg<-retval) ms). split.\n            left. apply plus_one. apply nd_exec_lowered. eapply exec_Return; eauto.\n            constructor; auto.\n        - inv MATCHSTACK. exists (Final retval ms). split.\n          left. apply plus_one. apply nd_exec_lowered. eapply exec_Return_Final; eauto.\n          constructor; auto.\n        - exists (State s v next rm ms). split.\n          left. apply plus_one. apply nd_exec_lowered. eapply exec_Printexpr; eauto.\n          constructor; auto.\n        - exists (State s v next rm ms). split.\n          left. apply plus_one. apply nd_exec_lowered. eapply exec_Printstring; eauto.\n          constructor; eauto.\n        - exists (State s v next rm newms). split.\n          left. apply plus_one. apply nd_exec_lowered. eapply exec_Store; eauto.\n          constructor; auto.\n        - exists (State s v next (rm#reg<-val) ms). split.\n          left. apply plus_one. apply nd_exec_lowered. eapply exec_Load; eauto.\n          constructor; auto.\n        - exists (State s v next rm ms). split.\n          left. apply plus_one. apply nd_exec_lowered. eapply exec_Assume_holds; eauto.\n          constructor; auto.\n        - eapply match_synth in SYNTH as [synthsrc [SYNTH MATCH]]; simpl; eauto.\n          exists (State (synthsrc++s) newver la newrm ms). split.\n          left. apply plus_one. apply nd_exec_lowered. eapply exec_Assume_fails; eauto.\n          rewrite base_version_unchanged. auto.\n          constructor; auto. unfold find_base_version in FINDF. simpl in FINDF.\n          destruct (find_function fa (lowering p)) eqn:FINDF'; inv FINDF. apply fn_base_low.\n          apply app_match; auto. }\n      * inv DEOPT_COND. unfold lowering_version, lowering_code in CODE. simpl in CODE.\n        rewrite PTree.gmap1 in CODE. unfold option_map in CODE.\n        destruct ((ver_code v)!pc); inv CODE. destruct i; inv H0.\n      * inv DEOPT_COND. unfold lowering_version, lowering_code in CODE. simpl in CODE.\n        rewrite PTree.gmap1 in CODE. unfold option_map in CODE.\n        destruct ((ver_code v)!pc); inv CODE. destruct i; inv H0.\n    + inv STEP.                 (* refl match *)\n      { inv STEP0.\n        - exists (State s v next rm ms). split.\n          + left. apply plus_one. apply nd_exec_lowered. eapply exec_Nop; eauto.\n          + apply refl_match; auto.\n        - exists (State s v next (rm#reg<-v0) ms). split.\n          + left. apply plus_one. apply nd_exec_lowered. eapply exec_Op; eauto.\n          + apply refl_match; auto.\n        - exists (State s v next newrm ms). split.\n          + left. apply plus_one. apply nd_exec_lowered. eapply exec_Move; eauto.\n          + apply refl_match; auto.\n        - exists (State s v (pc_cond v0 iftrue iffalse) rm ms). split.\n          + left. apply plus_one. apply nd_exec_lowered. eapply exec_Cond; eauto.\n          + apply refl_match; auto.\n        - destruct (fn_opt func) eqn:OPT.\n          + apply find_function_lowered in FINDF as [f' [FINDF LOW]].\n            exists (State (Stackframe retreg v next rm::s) (current_version f') (ver_entry (current_version f')) newrm ms).\n            split.\n            left. apply plus_one. apply nd_exec_lowered.\n            { eapply exec_Call.\n              - apply CODE.\n              - apply FINDF.\n              - auto.\n              - apply EVALL.\n              - rewrite <- LOW in INIT_REGS. unfold lowering_function in INIT_REGS.\n                destruct (fn_opt f'); simpl in INIT_REGS; auto. }\n            assert (ver_entry (current_version f') = ver_entry (current_version func)).\n            { rewrite <- LOW. unfold lowering_function, current_version.\n              destruct (fn_opt f') eqn:OPT'; simpl; auto.\n              rewrite OPT'. auto. }\n            rewrite H. constructor; auto.\n            * rewrite <- LOW. unfold current_version, lowering_function.\n              destruct (fn_opt f') eqn:OPT'; simpl; try rewrite OPT'; auto.\n              apply fn_base_low.\n            * constructor; auto. constructor; auto.\n          + exists (State (Stackframe retreg v next rm::s) (current_version func) (ver_entry (current_version func)) newrm ms). split.\n            left. apply plus_one. apply nd_exec_lowered.\n            unfold find_function, find_function_list, lowering in *. simpl in FINDF.\n            rewrite PTree.gmap1 in FINDF. unfold option_map in FINDF. simpl.\n            destruct ((prog_funlist p)! fid) eqn:FIND; inv FINDF.\n            destruct (fn_opt f) eqn:OPT'. { unfold lowering_function in OPT. rewrite OPT' in OPT. inv OPT. }\n            { eapply exec_Call.\n              - apply CODE.\n              - unfold find_function, find_function_list. rewrite FIND. auto.\n              - unfold current_version. unfold lowering_function. rewrite OPT'. rewrite OPT'. auto.\n              - apply EVALL.\n              - unfold lowering_function in INIT_REGS. rewrite OPT' in INIT_REGS. auto. }\n            constructor; auto.\n            * unfold current_version. rewrite OPT. apply fn_base_low.\n            * constructor; auto. constructor; auto.          \n        - inv MATCHSTACK. inv MSF.\n          + exists (State s1 fprev next (rmprev#retreg<-retval) ms). split.\n            * left. apply plus_one. apply nd_exec_lowered. eapply exec_Return; eauto.\n            * apply refl_match. auto.\n          + exists (State s1 v0 next (rmprev#retreg<-retval) ms). split.\n            * left. apply plus_one. apply nd_exec_lowered. eapply exec_Return; eauto.\n            * constructor; auto.\n        - inv MATCHSTACK. exists (Final retval ms). split.\n          + left. apply plus_one. apply nd_exec_lowered. eapply exec_Return_Final; eauto.\n          + apply final_match; auto.\n        - exists (State s v next rm ms). split.\n          + left. apply plus_one. apply nd_exec_lowered. eapply exec_Printexpr; eauto.\n          + apply refl_match; auto.\n        - exists (State s v next rm ms). split.\n          + left. apply plus_one. apply nd_exec_lowered. eapply exec_Printstring; eauto.\n          + apply refl_match; auto.\n        - exists (State s v next rm newms). split.\n          + left. apply plus_one. apply nd_exec_lowered. eapply exec_Store; eauto.\n          + apply refl_match; auto.\n        - exists (State s v next (rm#reg<-val) ms). split.\n          + left. apply plus_one. apply nd_exec_lowered. eapply exec_Load; eauto.\n          + apply refl_match; auto.\n        - exists (State s v next rm ms). split.\n          + left. apply plus_one. apply nd_exec_lowered. eapply exec_Assume_holds; eauto.\n          + apply refl_match; auto.\n        - simpl in SYNTH. eapply match_synth with (p:=p) in SYNTH as [synthsrc [SYNTH MS]].\n          exists (State (synthsrc++s) newver la newrm ms). split.\n          + left. apply plus_one. apply nd_exec_lowered. eapply exec_Assume_fails; eauto.\n            rewrite base_version_unchanged; auto. \n          + apply refl_match; auto. apply app_match; auto.\n          + auto. }\n      { inv DEOPT_COND. eapply match_synth in SYNTH as [synthsrc [SYNTH MS]].\n        exists (State s v next rm ms). split.\n        - left. apply plus_one. eapply nd_exec_Framestate_go_on. econstructor; eauto.\n          rewrite base_version_unchanged. eauto.\n        - apply refl_match; auto.\n        - simpl. auto. }\n      { inv DEOPT_COND. eapply match_synth in SYNTH as [synthsrc [SYNTH MS]].\n        exists (State (synthsrc++s) newver la newrm ms). split.\n        - left. apply plus_one. eapply nd_exec_Framestate_deopt. econstructor; eauto.\n          rewrite base_version_unchanged. eauto.\n        - apply refl_match; auto. apply app_match; auto.\n        - simpl. auto. }\n          \n    +                           (* final_match *) \n      inv STEP. inv STEP0.\nQed.\n", "meta": {"author": "Aurele-Barriere", "repo": "CoreJIT", "sha": "8740d4149be649d0746d9f0d2d759b387a8f3246", "save_path": "github-repos/coq/Aurele-Barriere-CoreJIT", "path": "github-repos/coq/Aurele-Barriere-CoreJIT/CoreJIT-8740d4149be649d0746d9f0d2d759b387a8f3246/src/coqjit/lowering_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2451206070904123}}
{"text": "From stdpp Require Import relations sorting.\nFrom Coq Require Import ssreflect.\n\nDeclare Scope grammar_scope.\nLocal Open Scope grammar_scope.\n\n(* Positioned token. *)\nRecord pos_token (Σ : Type) := {\n  token : Σ;\n  pos : nat (* line number *) * nat (* column number *);\n}.\n\nArguments token {_}.\nArguments pos {_}.\n\nNotation \"a @ p\" := {|\n  token := a;\n  pos := p;\n|} (at level 40) : grammar_scope.\n\nGlobal Instance pos_token_eq_dec Σ `{!EqDecision Σ} : EqDecision (pos_token Σ).\nProof.\n  intros [a1 p1] [a2 p2].\n  destruct (decide (a1 = a2 ∧ p1 = p2)); [left | right]; naive_solver.\nQed.\n\nDefinition pos_token_lt (Σ : Type) : relation (pos_token Σ) := λ pt1 pt2,\n  match pos pt1, pos pt2 with (x1, y1), (x2, y2) =>\n    (x1 < x2) ∨ (x1 = x2 ∧ y1 < y2)\n  end.\n\nGlobal Instance pos_token_lt_trans Σ : Transitive (pos_token_lt Σ).\nProof.\n  intros [? [? ?]] [? [? ?]] [? [? ?]].\n  unfold pos_token_lt. simpl. lia.\nQed.\n\n(* Sentence: a list of positioned tokens. *)\nDefinition sentence (Σ : Type) : Type := list (pos_token Σ).\n\n(* A well-formed sentence: positions are increasing. *)\nDefinition well_formed {Σ : Type} (w : sentence Σ) : Prop :=\n  Sorted (pos_token_lt Σ) w.\n\n(* Layout-free clauses. *)\nInductive lf_clause (Σ N : Type) : Type :=\n  | lf_ε\n  | lf_atom (a : Σ)\n  | lf_unary (A : N)\n  | lf_binary (Al Ar : N)\n  .\n\nArguments lf_ε {_} {_}.\nArguments lf_atom {_} {_}.\nArguments lf_unary {_} {_}.\nArguments lf_binary {_} {_}.\n\nDefinition check_lf_clause_eq {Σ N} `{!EqDecision Σ} `{!EqDecision N} (α β : lf_clause Σ N) : bool :=\n  match α, β with\n  | lf_ε, lf_ε => true\n  | lf_atom a, lf_atom b => bool_decide (a = b)\n  | lf_unary A, lf_unary A' => bool_decide (A = A')\n  | lf_binary Al Ar, lf_binary Al' Ar' =>\n    bool_decide (Al = Al') && bool_decide (Ar = Ar')\n  | _, _ => false\n  end.\n\nLemma check_lf_clause_eq_spec {Σ N} `{!EqDecision Σ} `{!EqDecision N} (α β : lf_clause Σ N) :\n  check_lf_clause_eq α β = true ↔ α = β.\nProof.\n  destruct α; destruct β => //=.\n  all: try rewrite !andb_true_iff.\n  all: rewrite !bool_decide_eq_true.\n  all: naive_solver.\nQed.\n\nGlobal Instance lf_clause_eq_dec Σ N `{!EqDecision Σ} `{!EqDecision N} : EqDecision (lf_clause Σ N).\nProof.\n  intros α β.\n  have ? : check_lf_clause_eq α β = true ↔ α = β by apply check_lf_clause_eq_spec.\n  destruct (check_lf_clause_eq α β); [left | right]; naive_solver.\nQed.\n\n(* Layout predicates. *)\nDefinition unary_predicate (Σ : Type) : Type := {p : sentence Σ → bool & p [] = true}.\nDefinition app₁ {Σ : Type} (φ : unary_predicate Σ) := projT1 φ.\n\nDefinition binary_predicate (Σ : Type) : Type :=\n  {p : sentence Σ → sentence Σ → bool & ∀ w1 w2, w1 = [] ∨ w2 = [] → p w1 w2 = true}.\nDefinition app₂ {Σ : Type} (φ : binary_predicate Σ) := projT1 φ.\n\n(* Layout-sensitive binary normal form. *)\nRecord grammar (Σ N : Type) := {\n  (* start symbol *)\n  start : N;\n  (* productions *)\n  lf_clauses : N → list (lf_clause Σ N);\n  lf_clauses_no_dup : ∀ A, NoDup (lf_clauses A);\n  unary_clause_predicate : N → N → unary_predicate Σ;\n  binary_clause_predicate : N → N → N → binary_predicate Σ;\n}.\n\nArguments lf_clauses {_} {_}.\nArguments lf_clauses_no_dup {_} {_}.\nArguments unary_clause_predicate {_} {_}.\nArguments binary_clause_predicate {_} {_}.\n\n(* Layout-sensitive clauses. *)\nInductive clause (Σ N : Type) : Type :=\n  | ε\n  | atom (token : Σ)\n  | unary (A : N) (φ : unary_predicate Σ)\n  | binary (Al Ar : N) (φ : binary_predicate Σ)\n  .\n\nArguments ε {_} {_}.\nArguments atom {_} {_}.\nArguments unary {_} {_}.\nArguments binary {_} {_}.\n\nDefinition clauses {Σ N : Type} (G : grammar Σ N) (A : N) : list (clause Σ N) :=\n  (λ α, match α with\n  | lf_ε => ε\n  | lf_atom a => atom a\n  | lf_unary B => unary B (unary_clause_predicate G A B)\n  | lf_binary Bl Br => binary Bl Br (binary_clause_predicate G A Bl Br)\n  end) <$> lf_clauses G A.\n\nInductive production (Σ N : Type) : Type :=\n  mk_production (lhs : N) (rhs : clause Σ N).\nArguments mk_production {_} {_}.\nNotation \"A ↦ α\" := (mk_production A α) (at level 40) : grammar_scope.\n\nGlobal Instance production_elem_of_grammar Σ N : ElemOf (production Σ N) (grammar Σ N) := λ p G,\n  match p with\n  | mk_production A α => α ∈ clauses G A\n  end.\n(* So that one can write \"A ↦ α ∈ G\". *)\n\nLtac invert H := inversion H; subst; clear H.\n\nSection clauses.\n  Context {Σ N : Type}.\n  Context (G : grammar Σ N).\n\n  Lemma elem_of_clauses A α :\n    A ↦ α ∈ G → match α with\n    | ε => lf_ε ∈ lf_clauses G A\n    | atom a => lf_atom a ∈ lf_clauses G A\n    | unary B φ => lf_unary B ∈ lf_clauses G A ∧\n        φ = unary_clause_predicate G A B\n    | binary Bl Br φ => lf_binary Bl Br ∈ lf_clauses G A ∧\n        φ = binary_clause_predicate G A Bl Br\n    end.\n  Proof.\n    unfold elem_of, production_elem_of_grammar.\n    rewrite elem_of_list_fmap. intros [? [Heq ?]]. destruct α.\n    all: case_match => //.\n    all: by invert Heq.\n  Qed.\n\n  Lemma unary_clause_predicate_unique A B φ φ' :\n    A ↦ unary B φ ∈ G →\n    A ↦ unary B φ' ∈ G →\n    φ = φ'.\n  Proof.\n    intros Hφ Hφ'. apply elem_of_clauses in Hφ, Hφ'.\n    naive_solver.\n  Qed.\n\n  Lemma binary_clause_predicate_unique A Bl Br φ φ' :\n    A ↦ binary Bl Br φ ∈ G →\n    A ↦ binary Bl Br φ' ∈ G →\n    φ = φ'.\n  Proof.\n    intros Hφ Hφ'. apply elem_of_clauses in Hφ, Hφ'.\n    naive_solver.\n  Qed.\nEnd clauses.\n\nSection parsing.\n  Context {Σ N : Type}.\n\n  (* Parse tree. *)\n  Inductive tree : Type :=\n    | ε_tree (r : N)\n    | token_tree (r : N) (pt : pos_token Σ)\n    | unary_tree (r : N) (t : tree)\n    | binary_tree (r : N) (tl tr : tree)\n    .\n\n  Definition root t : N :=\n    match t with\n    | ε_tree R => R\n    | token_tree R _ => R\n    | unary_tree R _ => R\n    | binary_tree R _ _ => R\n    end.\n\n  Fixpoint word t : sentence Σ :=\n    match t with\n    | ε_tree _ => []\n    | token_tree _ tk => [tk]\n    | unary_tree _ t' => word t'\n    | binary_tree _ t1 t2 => word t1 ++ word t2\n    end.\n\n  Context `{!EqDecision Σ} `{!EqDecision N}.\n\n  Fixpoint check_tree_eq t1 t2 : bool :=\n    match t1, t2 with\n    | ε_tree A, ε_tree A' => bool_decide (A = A')\n    | token_tree A tk1, token_tree A' tk2 => bool_decide (A = A' ∧ tk1 = tk2)\n    | unary_tree A t1, unary_tree A' t2 =>\n      bool_decide (A = A') && check_tree_eq t1 t2\n    | binary_tree A tA1 tB1, binary_tree A' tA2 tB2 =>\n      bool_decide (A = A') && check_tree_eq tA1 tA2 && check_tree_eq tB1 tB2\n    | _, _ => false\n    end.\n\n  Lemma check_tree_eq_spec t1 t2 :\n    check_tree_eq t1 t2 = true ↔ t1 = t2.\n  Proof.\n    generalize dependent t2.\n    induction t1; destruct t2 => //=.\n    all: try rewrite !andb_true_iff.\n    all: rewrite !bool_decide_eq_true.\n    all: naive_solver.\n  Qed.\n\n  Global Instance tree_eq_dec : EqDecision tree.\n  Proof.\n    intros t1 t2.\n    have ? := check_tree_eq_spec t1 t2.\n    destruct (check_tree_eq t1 t2); [left | right]; naive_solver.\n  Qed.\n\n  Context (G : grammar Σ N).\n\n  (* Parse tree validity. *)\n  Inductive tree_valid : tree → Prop :=\n    | valid_ε A :\n      A ↦ ε ∈ G →\n      tree_valid (ε_tree A)\n    | valid_token A a p :\n      A ↦ atom a ∈ G →\n      tree_valid (token_tree A (a @ p))\n    | valid_unary A t' φ :\n      A ↦ unary (root t') φ ∈ G →\n      tree_valid t' →\n      app₁ φ (word t') = true →\n      tree_valid (unary_tree A t')\n    | valid_binary A t1 t2 φ :\n      A ↦ binary (root t1) (root t2) φ ∈ G →\n      tree_valid t1 →\n      tree_valid t2 →\n      app₂ φ (word t1) (word t2) = true →\n      tree_valid (binary_tree A t1 t2)\n    .\n\n  Definition tree_witness t A w := root t = A ∧ word t = w ∧ tree_valid t.\n\n  (* derivation *)\n  Definition derive A w : Prop := ∃ t, tree_witness t A w.\n\nEnd parsing.\nNotation \"✓{ G } t\" := (tree_valid G t) (at level 40, format \"'✓{' G '}'  t\") : grammar_scope.\nNotation \"t ▷ A ={ G }=> w\" := (tree_witness G t A w) (at level 40) : grammar_scope.\nNotation \"G ⊨ A => w\" := (derive G A w) (at level 65) : grammar_scope.\n", "meta": {"author": "lay-it-out", "repo": "LS2NF-theory", "sha": "62d5ff7ef947ce61589cc3a7d86c2cfe9d3bf765", "save_path": "github-repos/coq/lay-it-out-LS2NF-theory", "path": "github-repos/coq/lay-it-out-LS2NF-theory/LS2NF-theory-62d5ff7ef947ce61589cc3a7d86c2cfe9d3bf765/theories/grammar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24512060709041225}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Bool.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import ZArith NArith Nnat Ndec Ndigits.\nFrom IntMap Require Import Allmaps.\nRequire Import Wf_nat.\n\nRequire Import BDDvar_ad_nat.\nRequire Import bdd1.\nRequire Import bdd2.\nRequire Import bdd3.\nRequire Import bdd4.\nRequire Import bdd5_1.\nRequire Import bdd5_2.\nRequire Import bdd6.\nRequire Import bdd7.\nRequire Import BDDdummy_lemma_2.\nRequire Import BDDdummy_lemma_3.\nRequire Import BDDdummy_lemma_4.\n\nLemma BDDor_1_lemma :\n forall (bound : nat) (cfg : BDDconfig) (node1 node2 : ad)\n   (memo : BDDor_memo),\n BDDconfig_OK cfg ->\n BDDor_memo_OK cfg memo ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n (is_internal_node cfg node1 ->\n  is_internal_node cfg node2 ->\n  max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)) < bound) ->\n BDDconfig_OK (fst (BDDor_1 cfg memo node1 node2 bound)) /\\\n BDDor_memo_OK (fst (BDDor_1 cfg memo node1 node2 bound))\n   (snd (snd (BDDor_1 cfg memo node1 node2 bound))) /\\\n config_node_OK (fst (BDDor_1 cfg memo node1 node2 bound))\n   (fst (snd (BDDor_1 cfg memo node1 node2 bound))) /\\\n nodes_preserved cfg (fst (BDDor_1 cfg memo node1 node2 bound)) /\\\n BDDvar_le\n   (var (fst (BDDor_1 cfg memo node1 node2 bound))\n      (fst (snd (BDDor_1 cfg memo node1 node2 bound))))\n   (BDDvar_max (var cfg node1) (var cfg node2)) = true /\\\n bool_fun_eq\n   (bool_fun_of_BDD (fst (BDDor_1 cfg memo node1 node2 bound))\n      (fst (snd (BDDor_1 cfg memo node1 node2 bound))))\n   (bool_fun_or (bool_fun_of_BDD cfg node1) (bool_fun_of_BDD cfg node2)).\nProof.\nintro bound.\napply\n lt_wf_ind\n  with\n    (P := fun bound : nat =>\n          forall (cfg : BDDconfig) (node1 node2 : ad) (memo : BDDor_memo),\n          BDDconfig_OK cfg ->\n          BDDor_memo_OK cfg memo ->\n          config_node_OK cfg node1 ->\n          config_node_OK cfg node2 ->\n          (is_internal_node cfg node1 ->\n           is_internal_node cfg node2 ->\n           max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)) <\n           bound) ->\n          BDDconfig_OK (fst (BDDor_1 cfg memo node1 node2 bound)) /\\\n          BDDor_memo_OK (fst (BDDor_1 cfg memo node1 node2 bound))\n            (snd (snd (BDDor_1 cfg memo node1 node2 bound))) /\\\n          config_node_OK (fst (BDDor_1 cfg memo node1 node2 bound))\n            (fst (snd (BDDor_1 cfg memo node1 node2 bound))) /\\\n          nodes_preserved cfg (fst (BDDor_1 cfg memo node1 node2 bound)) /\\\n          BDDvar_le\n            (var (fst (BDDor_1 cfg memo node1 node2 bound))\n               (fst (snd (BDDor_1 cfg memo node1 node2 bound))))\n            (BDDvar_max (var cfg node1) (var cfg node2)) = true /\\\n          bool_fun_eq\n            (bool_fun_of_BDD (fst (BDDor_1 cfg memo node1 node2 bound))\n               (fst (snd (BDDor_1 cfg memo node1 node2 bound))))\n            (bool_fun_or (bool_fun_of_BDD cfg node1)\n               (bool_fun_of_BDD cfg node2))).\n\n\n\n\nclear bound.\nintro bound.\nintro H.\nintros cfg node1 node2 memo H0 H1 H2 H3 H4.\nelim (option_sum _ (BDDor_memo_lookup memo node1 node2)); intro y.\nelim y; clear y.\nintros node H5.\nrewrite (BDDor_1_lemma_1 cfg memo node1 node2 node bound H5).\nsimpl in |- *.\nunfold BDDor_memo_OK in H1.\nsplit.\nassumption.\n\nsplit.\nassumption.\n\nsplit.\nexact (proj1 (proj2 (proj2 (H1 node1 node2 node H5)))).\n\nsplit.\nunfold nodes_preserved in |- *.\nintros x l r node0 H6.\nassumption.\n\nsplit.\nexact (proj1 (proj2 (proj2 (proj2 (H1 node1 node2 node H5))))).\n\nexact (proj2 (proj2 (proj2 (proj2 (H1 node1 node2 node H5))))).\n\nelim H2; intro.\nrewrite H5.\n\n\n\n\n\nrewrite (BDDor_1_lemma_zero_2 cfg memo node2 bound).\nsimpl in |- *.\ncut\n (bool_fun_eq (bool_fun_of_BDD cfg node2)\n    (bool_fun_or (bool_fun_of_BDD cfg BDDzero) (bool_fun_of_BDD cfg node2))).\nintro H6.\nsplit.\nassumption.\n\nsplit.\nunfold BDDor_memo_OK in |- *.\nintros node1' node2' node.\nintros H7.\nrewrite (BDDor_memo_lookup_semantics memo BDDzero node2 node2 node1' node2')\n  in H7.\nelim (sumbool_of_bool (N.eqb BDDzero node1' && N.eqb node2 node2')); intro y0.\ncut (BDDzero = node1').\ncut (node2 = node2').\nintros H8 H9.\nsplit.\nrewrite <- H9.\nleft; reflexivity.\n\nsplit.\nrewrite <- H8; assumption.\n\nsplit.\nrewrite y0 in H7.\ninjection H7.\nintro H10.\nrewrite <- H10.\nassumption.\n\nsplit.\nrewrite y0 in H7.\ninjection H7; intro.\nrewrite <- H10.\nrewrite <- H8.\napply BDDvar_le_max_2.\n\nrewrite y0 in H7; injection H7; intro.\nrewrite <- H10.\nrewrite <- H9.\nrewrite <- H8.\nassumption.\n\n\n\napply Neqb_complete.\nexact (proj2 (andb_prop (N.eqb BDDzero node1') (N.eqb node2 node2') y0)).\n\napply Neqb_complete.\nexact (proj1 (andb_prop (N.eqb BDDzero node1') (N.eqb node2 node2') y0)).\n\nrewrite y0 in H7.\nunfold BDDor_memo_OK in H1.\nsplit.\nexact (proj1 (H1 node1' node2' node H7)).\n\nsplit.\nexact (proj1 (proj2 (H1 node1' node2' node H7))).\n\nsplit.\nexact (proj1 (proj2 (proj2 (H1 node1' node2' node H7)))).\n\nsplit.\nexact (proj1 (proj2 (proj2 (proj2 (H1 node1' node2' node H7))))).\n\nexact (proj2 (proj2 (proj2 (proj2 (H1 node1' node2' node H7))))).\n\nsplit.\nassumption.\n\nsplit.\nunfold nodes_preserved in |- *; intro.\nintros l r node H7.\nassumption.\n\nsplit.\napply BDDvar_le_max_2.\n\nassumption.\n\nrewrite (proj1 (bool_fun_of_BDD_semantics cfg H0)).\napply bool_fun_eq_symm.\napply\n bool_fun_eq_trans\n  with (bool_fun_or (bool_fun_of_BDD cfg node2) bool_fun_zero).\napply bool_fun_or_commute.\n\napply bool_fun_or_zero.\n\n\n\nrewrite <- H5; assumption.\n\nelim H5; clear H5; intro.\nrewrite H5.\nrewrite (BDDor_1_lemma_one_2 cfg memo node2 bound).\nsimpl in |- *.\ncut\n (bool_fun_eq (bool_fun_of_BDD cfg BDDone)\n    (bool_fun_or (bool_fun_of_BDD cfg BDDone) (bool_fun_of_BDD cfg node2))).\nintro H6.\nsplit.\nassumption.\n\nsplit.\nunfold BDDor_memo_OK in |- *.\nintros node1' node2' node.\nintros H7.\nrewrite (BDDor_memo_lookup_semantics memo BDDone node2 BDDone node1' node2')\n  in H7.\nelim (sumbool_of_bool (N.eqb BDDone node1' && N.eqb node2 node2')); intro y0.\ncut (BDDone = node1').\ncut (node2 = node2').\nintros H8 H9.\nsplit.\nrewrite <- H9.\nright; left; reflexivity.\n\nsplit.\nrewrite <- H8; assumption.\n\nsplit.\nrewrite y0 in H7.\ninjection H7.\nintro H10.\nrewrite <- H10.\nright; left; reflexivity.\n\nsplit.\nrewrite y0 in H7.\ninjection H7; intro.\nrewrite <- H10.\nrewrite <- H8.\nunfold var at 1 in |- *.\nrewrite (config_OK_one cfg H0).\n\n\n\n\nunfold BDDzero in |- *.\napply BDDvar_le_z.\n\nrewrite y0 in H7; injection H7; intro.\nrewrite <- H10.\nrewrite <- H9.\nrewrite <- H8.\nassumption.\n\napply Neqb_complete.\nexact (proj2 (andb_prop (N.eqb BDDone node1') (N.eqb node2 node2') y0)).\n\napply Neqb_complete.\nexact (proj1 (andb_prop (N.eqb BDDone node1') (N.eqb node2 node2') y0)).\n\nrewrite y0 in H7.\nunfold BDDor_memo_OK in H1.\nsplit.\nexact (proj1 (H1 node1' node2' node H7)).\n\nsplit.\nexact (proj1 (proj2 (H1 node1' node2' node H7))).\n\nsplit.\nexact (proj1 (proj2 (proj2 (H1 node1' node2' node H7)))).\n\nsplit.\nexact (proj1 (proj2 (proj2 (proj2 (H1 node1' node2' node H7))))).\n\nexact (proj2 (proj2 (proj2 (proj2 (H1 node1' node2' node H7))))).\n\nsplit.\nright; left; reflexivity.\n\nsplit.\nunfold nodes_preserved in |- *; intro.\nintros l r node H7.\nassumption.\n\n\n\n\n\nsplit.\napply BDDvar_le_max_1.\n\nassumption.\n\nrewrite (proj1 (proj2 (bool_fun_of_BDD_semantics cfg H0))).\napply\n bool_fun_eq_trans\n  with (bf2 := bool_fun_or (bool_fun_of_BDD cfg node2) bool_fun_one).\napply bool_fun_eq_symm.\napply bool_fun_or_one.\n\napply bool_fun_or_commute.\n\nrewrite <- H5; assumption.\n\nelim H3; intro.\nrewrite H6.\nrewrite (BDDor_1_lemma_zero_1 cfg memo node1 bound).\nsimpl in |- *.\ncut\n (bool_fun_eq (bool_fun_of_BDD cfg node1)\n    (bool_fun_or (bool_fun_of_BDD cfg node1) (bool_fun_of_BDD cfg BDDzero))).\nintro H7.\nsplit.\nassumption.\n\nsplit.\nunfold BDDor_memo_OK in |- *.\nintros node1' node2' node.\nintros H8.\nrewrite (BDDor_memo_lookup_semantics memo node1 BDDzero node1 node1' node2')\n  in H8.\nelim (sumbool_of_bool (N.eqb node1 node1' && N.eqb BDDzero node2')); intro y0.\ncut (node1 = node1').\ncut (BDDzero = node2').\nintros H9 H10.\nsplit.\nrewrite <- H10; assumption.\n\nsplit.\nrewrite <- H9; left; reflexivity.\n\nsplit.\nrewrite y0 in H8.\ninjection H8; intro.\n\n\n\n\n\n\n\n\nrewrite <- H11; assumption.\n\nsplit.\nrewrite y0 in H8.\ninjection H8; intro.\nrewrite <- H10.\nrewrite <- H11.\napply BDDvar_le_max_1.\n\nrewrite <- H9.\nrewrite <- H10.\nrewrite y0 in H8; injection H8; intro.\nrewrite <- H11.\nassumption.\n\napply Neqb_complete.\nexact (proj2 (andb_prop (N.eqb node1 node1') (N.eqb BDDzero node2') y0)).\n\napply Neqb_complete.\nexact (proj1 (andb_prop (N.eqb node1 node1') (N.eqb BDDzero node2') y0)).\n\nrewrite y0 in H8.\nunfold BDDor_memo_OK in H1.\nsplit.\nexact (proj1 (H1 node1' node2' node H8)).\n\nsplit.\nexact (proj1 (proj2 (H1 node1' node2' node H8))).\n\nsplit.\nexact (proj1 (proj2 (proj2 (H1 node1' node2' node H8)))).\n\nsplit.\nexact (proj1 (proj2 (proj2 (proj2 (H1 node1' node2' node H8))))).\n\nexact (proj2 (proj2 (proj2 (proj2 (H1 node1' node2' node H8))))).\n\nsplit.\n\n\n\n\n\n\nassumption.\n\nsplit.\nunfold nodes_preserved in |- *; intro.\nintros l r node H8.\nassumption.\n\nsplit.\napply BDDvar_le_max_1.\n\nassumption.\n\nrewrite (proj1 (bool_fun_of_BDD_semantics cfg H0)).\napply bool_fun_eq_symm.\napply bool_fun_or_zero.\n\nrewrite <- H6; assumption.\n\nelim H6.\nclear H5 H6.\nintro H5.\nrewrite H5.\nrewrite (BDDor_1_lemma_one_1 cfg memo node1 bound).\nsimpl in |- *.\ncut\n (bool_fun_eq (bool_fun_of_BDD cfg BDDone)\n    (bool_fun_or (bool_fun_of_BDD cfg node1) (bool_fun_of_BDD cfg BDDone))).\nintro H6.\nsplit.\nassumption.\n\nsplit.\nunfold BDDor_memo_OK in |- *.\nintros node1' node2' node.\nintros H7.\nrewrite (BDDor_memo_lookup_semantics memo node1 BDDone BDDone node1' node2')\n  in H7.\nelim (sumbool_of_bool (N.eqb node1 node1' && N.eqb BDDone node2')); intro y0.\ncut (node1 = node1').\ncut (BDDone = node2').\nintros H8 H9.\nintros.\n\n\n\n\n\n\n\n\nsplit.\nrewrite <- H9; assumption.\n\nsplit.\nrewrite <- H8; right; left; reflexivity.\n\nsplit.\nrewrite y0 in H7.\ninjection H7.\nintro H10.\nrewrite <- H10.\nright; left; reflexivity.\n\nsplit.\nrewrite y0 in H7.\ninjection H7; intro.\nrewrite <- H10.\nrewrite <- H9.\nrewrite <- H8.\napply BDDvar_le_max_2.\n\nrewrite y0 in H7; injection H7; intro.\nrewrite <- H10.\nrewrite <- H9.\nrewrite <- H8.\nassumption.\n\napply Neqb_complete.\nexact (proj2 (andb_prop (N.eqb node1 node1') (N.eqb BDDone node2') y0)).\n\napply Neqb_complete.\nexact (proj1 (andb_prop (N.eqb node1 node1') (N.eqb BDDone node2') y0)).\n\nrewrite y0 in H7.\nunfold BDDor_memo_OK in H1.\nsplit.\nexact (proj1 (H1 node1' node2' node H7)).\n\n\n\n\n\n\nsplit.\nexact (proj1 (proj2 (H1 node1' node2' node H7))).\n\nsplit.\nexact (proj1 (proj2 (proj2 (H1 node1' node2' node H7)))).\n\nsplit.\nexact (proj1 (proj2 (proj2 (proj2 (H1 node1' node2' node H7))))).\n\nexact (proj2 (proj2 (proj2 (proj2 (H1 node1' node2' node H7))))).\n\nsplit.\nright; left; reflexivity.\n\nsplit.\nunfold nodes_preserved in |- *; intro.\nintros l r node H7.\nassumption.\n\nsplit.\napply BDDvar_le_max_2.\n\nassumption.\n\nrewrite (proj1 (proj2 (bool_fun_of_BDD_semantics cfg H0))).\napply bool_fun_eq_symm.\napply bool_fun_or_one.\n\nrewrite <- H5; assumption.\n\ncut (is_internal_node cfg node1).\n\n\n\nintros H8 H9.\ncut (is_internal_node cfg node2).\nintro H7.\nelim (nat_sum bound).\nintro y0.\nelim y0; clear y0.\nintro bound'.\nintro y0.\ncut (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)) < bound).\nintro H10.\nelim (relation_sum (BDDcompare (var cfg node1) (var cfg node2))); intro y1.\nelim y1; clear y1; intro.\napply BDDdummy_lemma_2 with (bound' := bound').\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\napply BDDdummy_lemma_3 with (bound' := bound').\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\ncut (BDDcompare (var cfg node2) (var cfg node1) = Datatypes.Lt).\nintro y11.\napply BDDdummy_lemma_4 with (bound' := bound').\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\nassumption.\napply BDDcompare_sup_inf.\nassumption.\napply H4.\nassumption.\n\nassumption.\n\nintro y0.\nrewrite y0 in H4.\nabsurd (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)) < 0).\napply lt_n_O.\n\napply H4.\nassumption.\n\nassumption.\n\napply in_dom_is_internal.\nassumption.\n\napply in_dom_is_internal.\nassumption.\nQed.", "meta": {"author": "coq-contribs", "repo": "bdds", "sha": "2a66529afca7c780fa18d21ecd4f6c8d55182a6d", "save_path": "github-repos/coq/coq-contribs-bdds", "path": "github-repos/coq/coq-contribs-bdds/bdds-2a66529afca7c780fa18d21ecd4f6c8d55182a6d/bdd8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24512060709041222}}
{"text": "Require Import sound_include.\nRequire Import rulesound.\n\n\nTheorem RuleSound: \n  forall (Spec:funspec) (sd : ossched) (I:Inv) (r:retasrt) (ri:asrt)\n         (pre:asrt) (s:stmts) (post:asrt) lasrt tid,\n    InfRules Spec sd lasrt I r ri pre s post tid ->  \n    RuleSem Spec sd lasrt I r ri pre s post tid.\nProof.\n  introv Hspe.\n  inductions Hspe.\n  eapply pfalse_rule_sound;eauto.\n  eapply pure_split_rule_sound;eauto.\n  eapply genv_introret_rule_sound ;eauto.\n  eapply genv_introexint_rule_sound ;eauto.\n  eapply ret_rule_sound; eauto. \n  eapply exitint_rule_sound; eauto.\n  eapply rete_rule_sound;eauto.\n  eapply call_rule_sound;eauto. \n  eapply calle_rule_sound; eauto.\n  eapply calle_rule_lvar_sound; eauto.\n  eapply conseq_rule_sound;eauto.\n  eapply conseq_rule_r_sound;eauto.\n  eapply abscsq_rule_sound;eauto.\n  eapply seq_rule_sound;eauto.\n  eapply if_rule_sound;eauto.\n  eapply ift_rule_sound; eauto.\n  eapply while_rule_sound; eauto.\n  eapply frame_rule_sound;eauto.\n  eapply frame_rule_all_sound;eauto.\n  eapply retspec_intro_rule_sound;eauto.\n  eapply assign_rule_sound;eauto.\n  eapply encrit1_rule_sound ;eauto.\n  eapply encrit2_rule_sound;eauto.\n  eapply excrit1_rule_sound ;eauto.\n  eapply excrit2_rule_sound;eauto.\n  eapply cli1_rule_sound;eauto.\n  eapply cli2_rule_sound;eauto.\n  eapply sti1_rule_sound;eauto.\n  eapply sti2_rule_sound;eauto.\n  eapply switch_rule_sound;eauto.\n  eapply switch_dead_rule_sound; eauto.\n  eapply checkis_rule_sound;eauto.\n  eapply eoi_ieon_rule_sound;eauto.\n  eapply eoi_ieoff_rule_sound;eauto.\n  eapply ex_intro_rule_sound;eauto.\n  eapply disj_rule_sound;eauto.\n  eapply task_crt_rule_sound; eauto.\n  eapply task_delself_rule_sound; eauto.\n  eapply task_delother_rule_sound;eauto.\nQed.\n\nHint Resolve RuleSound.\n\nLemma WFFunEnv_imply_WFFuncsSim :\n  forall P FSpec sd I lasrt, \n    WFFunEnv P FSpec sd lasrt I ->\n    WFFuncsSim P FSpec sd lasrt I .\nProof.\n  introv Hwfenv.\n  unfolds in Hwfenv.\n  destruct Hwfenv as [Heqd Hwfenv].\n  unfolds.\n  split; auto.\n  introv Hf.\n  lets Hre :  Hwfenv Hf. \n  destruct Hre as (d1&d2&s & Hpf & Htm & Hgood & Hforal).\n  do 3 eexists; splits; eauto.\nQed.\n\n\nLemma  MethSim_to_Methsim' :  \n  forall P FSpec sd  I s r p ri q lasrt tid, \n    GoodI I sd lasrt->\n    WFFuncsSim  P FSpec sd lasrt I ->\n    RuleSem FSpec sd lasrt I r ri p s q tid->\n    (forall o O aop, (o, O, aop) |= p /\\ satp o O (CurLINV lasrt tid) -> \n                     MethSim P sd (nilcont s) o  aop O lasrt I r ri (lift q) tid). \nProof.\n  introv goodi.\n  introv Hwf Hrsem Hsat.\n  lets Hsim : Hrsem Hsat.\n  eapply MethSim_to_Methsim'_aux ; eauto.\nQed.\n\nLemma WFFunEnv_imply_Methsim' :  \n  forall P FSpec  sd I lasrt, \n    GoodI I sd lasrt->\n    WFFunEnv P FSpec sd lasrt I -> \n    WFFuncsSim' P FSpec sd lasrt I.\nProof.\n  introv GoodI.\n  introv Hwf. \n  unfolds.\n  split.\n  destruct Hwf.\n  auto.\n  introv Hsf.\n  lets Hre :  WFFunEnv_imply_WFFuncsSim  Hwf. \n  unfolds in Hre.\n  destruct Hre as [Heqd Hre].\n  lets Hree : Hre Hsf.\n  destruct Hree as (d1 & d2 & s & Hpf & Htm & Hgood & Hforall).\n  do 3 eexists; splits; eauto.\n  introv Hp Hr.\n  lets Hof : Hforall Hp Hr.\n  eapply MethSim_to_Methsim'; eauto.\n  split; auto.\nQed.\n\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/framework/proof/soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24512060709041222}}
{"text": "Require Import FP.Data.String.\nRequire Import FP.Data.N.\nRequire Import FP.Data.Z.\nRequire Import FP.Structures.Monoid.\nRequire Import FP.Data.Function.\nRequire Import FP.Data.List.\nRequire Import FP.Data.ListStructures.\nRequire Import FP.Data.GeneralizedList.\nRequire Import FP.Data.Ascii.\nRequire Import FP.Structures.Convertible.\nRequire Import FP.Structures.Additive.\nRequire Import FP.Structures.Ord.\nRequire Import FP.Structures.Foldable.\nRequire Import FP.Data.List.\nRequire Import FP.Data.Fuel.\nRequire Import FP.Data.Susp.\nRequire Import FP.Structures.MonadFix.\nRequire Import FP.Structures.Functor.\nRequire Import FP.Structures.Applicative.\nRequire Import FP.Structures.Monad.\nRequire Import FP.Data.Option.\nRequire Import FP.Data.PrettyI.\nRequire Import FP.Data.StringBuilder.\n\nImport StringNotation.\nImport NNotation.\nImport SuspNotation.\nImport MonadNotation.\nImport ApplicativeNotation.\nImport FunctorNotation.\nImport ZNotation.\nImport CharNotation.\nImport ListNotation.\nImport MonoidNotation.\nImport FunctionNotation.\nImport AdditiveNotation.\nImport OrdNotation.\n\nInductive tinydoc :=\n  | NilTD : tinydoc\n  | ConcatTD : string -> tinydoc -> tinydoc\n  | LineTD : N -> tinydoc -> tinydoc.\n\nFixpoint layout (td:tinydoc) : string_builder :=\n  match td with\n  | NilTD => mk_string_builder \"\"\n  | ConcatTD s td => mk_string_builder s ** layout td\n  | LineTD i td => mk_string_builder (convert_to string (newline :: replicate i \" \"%char)) ** layout td\n  end.\nInductive fmode :=\n  | Flat\n  | Break.\n\nDefinition fits : Z -> list (N*fmode*doc) -> fuel bool :=\n  mfix2 $ fun fits w ps =>\n    if w <! 0%Z then\n      ret false\n    else\n      match ps with\n      | [] => ret true\n      | (_,_,NilD)::ps => fits w ps\n      | (i,m,ConcatD dl dr)::ps => fits w ((i,m,dl)::(i,m,dr)::ps)\n      | (i,m,NestD j dn)::ps => fits w ((i+j,m,dn)::ps)\n      | (i,m,TextD s)::ps => fits (w - length s) ps\n      | (i,Flat,LineD s)::ps => fits (w - length s) ps\n      | (i,Break,LineD _)::_ => ret true\n      | (i,m,GroupD dg)::ps => fits w ((i,Flat,dg)::ps)\n      end.\n\nDefinition format : Z -> Z -> list (N*fmode*doc) -> fuel tinydoc :=\n  curry $\n  mfix2 $ fun format wk ps =>\n    let format (w:Z) (k:Z) (ps:list (N*fmode*doc)) := format (w,k) ps in\n    let '(w,k) := wk in\n    match ps with\n    | [] => ret NilTD\n    | (i,m,NilD)::ps => format w k ps\n    | (i,m,ConcatD dl dr)::ps => format w k ((i,m,dl)::(i,m,dr)::ps)\n    | (i,m,NestD j dn)::ps => format w k ((i+j,m,dn)::ps)\n    | (i,m,TextD s)::ps => ConcatTD s <$> format w (k + length s) ps\n    | (i,Flat,LineD s)::ps => ConcatTD s <$> format w (k + length s) ps\n    | (i,Break,LineD s)::ps => LineTD i <$> format w (convert i) ps\n    | (i,m,GroupD dg)::ps =>\n        b <- fits (w-k) ((i,Flat,dg)::ps) ;;\n        if b then\n          format w k ((i,Flat,dg)::ps)\n        else\n          format w k ((i,Break,dg)::ps)\n   end.\n    \nDefinition run_pretty (w:N) (d:doc) : option string :=\n  let one_million := 1000000 in\n  run_fuel one_million $ begin\n    td <- format (convert w) 0%Z [(0,Flat,GroupD d)] ;;\n    let nl := mk_string_builder $ convert [newline] in\n    ret $ run_string_builder $ nl ** layout td ** nl\n  end.\n\n(* example *)\n\nInductive tree := Node : string -> list tree -> tree.\n\nFixpoint show_tree (t:tree) : doc :=\n  let map_show_trees :=\n  fix map_show_trees ts :=\n    match ts with\n    | [] => []\n    | t::ts => show_tree t::map_show_trees ts\n    end\n  in\n  let show_trees :=\n  fix show_trees t ts :=\n    let tl :=\n      match ts with\n      | [] => nil_d\n      | t::ts => text_d \",\" `concat_d` line_d `concat_d` show_trees t ts\n      end\n    in t `concat_d` tl\n  in\n  let show_bracket :=\n  fix show_bracket ts :=\n    match ts with\n    | [] => nil_d\n    | t::ts => text_d \"[\" `concat_d` nest_d 1 (show_trees t ts) `concat_d` text_d \"]\"\n    end\n  in\n  let '(Node s ts) := t in\n  group_d (text_d s `concat_d` nest_d (convert (length (convert s))) (show_bracket (map_show_trees ts))).\n\nDefinition t1 : tree :=\n  Node \"aaa\" [Node \"bbb\" [Node \"ccc\" []; Node \"ddd\" []]; Node \"eee\" [Node \"fff\" []; Node \"ggg\" []]; Node \"hhh\" []].\n\n(*\nEval compute in\n  s <- run_pretty 20 $ show_tree t1 ;;\n  ret $ convert [newline] ** s.\n*)", "meta": {"author": "davdar", "repo": "coq-fp", "sha": "d0b752d9ea9592ba0bc7b067b46a63740fcff056", "save_path": "github-repos/coq/davdar-coq-fp", "path": "github-repos/coq/davdar-coq-fp/coq-fp-d0b752d9ea9592ba0bc7b067b46a63740fcff056/tmp/Data/Pretty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038302, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24512060080581888}}
{"text": "Require Import LibTactics.\nRequire Import Metalib.Metatheory.\n\nRequire Import\n        syntax_ott\n        rules_inf\n        Infrastructure\n        Key_Properties\n        Subtyping_inversion\n        Deterministic\n        Typing.\n\nRequire Import List. Import ListNotations.\nRequire Import Arith Lia.\n\n\n(* requires sub Top A -> toplike A *)\nLemma TypedReduce_trans : forall v v1 v2 A B,\n    value v -> TypedReduce v A v1 -> TypedReduce v1 B v2 -> TypedReduce v B v2.\nProof.\n  introv Val Red1 Red2.\n  lets Lc: value_lc Val.\n  gen B v2.\n  induction* Red1;\n    introv Red2.\n  - (* v1 = v_top *)\n    remember e_top.\n    induction* Red2;\n      try solve [inversion Heqe].\n  - (* v1 = abs e B *)\n    inductions Red2;\n      try solve [constructor*].\n    apply TReduce_arrow; auto.\n    auto_sub.\n  - (* v = v1,,v2 v1'~->v0 *)\n    inverts* Val.\n    inverts* Lc.\n    induction Red2;\n      eauto.\n  - (* v = v1,,v2 v2'~->v0 *)\n    inverts* Val.\n    inverts* Lc.\n    induction Red2;\n      eauto.\n  - (* and *)\n    gen v0.\n    induction B0; introv Red2;\n      try solve [inverts* Red2];\n      try solve [inversion Ord].\nQed.\n\nLemma consistent_afterTR : forall v A B C v1 v2, value v -> Typing nil v Inf C -> TypedReduce v A v1 -> TypedReduce v B v2 -> consistencySpec v1 v2.\nProof.\n  intros v A B C v1 v2 Val Typ Red1 Red2.\n  unfold consistencySpec.\n  intros D v1' v2' Red1' Red2'.\n  forwards*: TypedReduce_trans Red1 Red1'.\n  forwards*: TypedReduce_trans Red2 Red2'.\n  forwards*: TypedReduce_unique H H0.\nQed.\n\nLemma TypedReduce_prv_value: forall v A v',\n    value v -> TypedReduce v A v' -> value v'.\nProof.\n  intros v A v' Val Red.\n  induction* Red.\n  -\n    apply value_anno.\n    inverts* H.\n  - inverts* Val.\n  - inverts* Val.\nQed.\n\n#[export]\nHint Immediate TypedReduce_prv_value : core.\n\nLemma TypedReduce_preservation: forall v v' A,\n    value v -> TypedReduce v A v'-> Typing nil v Chk A\n    -> exists B, Typing nil v' Inf B /\\ subsub B A.\nProof with auto.\n  introv Val Red Typ'.\n  lets (C & Typ & Sub): Typing_chk2inf Typ'.\n  clear Typ' Sub. gen C.\n  induction Red; intros;\n    try solve [inverts* Typ].\n  - (* absv *)\n    inverts Typ.\n    exists*. split.\n    eapply Typ_abs.\n    intros.\n    applys~ Typing_chk_sub.\n    auto_sub.\n  - (* mergel *)\n    inverts Val.\n    inverts Typ;\n      forwards*: IHRed.\n  - (* merger *)\n    inverts Val.\n    inverts Typ;\n      forwards*: IHRed.\n  - (* merge_and *)\n    forwards* (?&?&?): IHRed1 Val Typ.\n    forwards* (?&?&?): IHRed2 Val Typ.\n    lets Con: consistent_afterTR Val Typ Red1 Red2.\n    exists. split.\n    applys* Typ_mergev.\n    eauto.\nQed.\n\nLemma preservation_subsub : forall e e' dir A,\n    Typing nil e dir A ->\n    step e e' ->\n    exists C, Typing nil e' dir C /\\ subsub C A.\nProof.\n  introv Typ. gen e'.\n  lets Typ' : Typ.\n  inductions Typ;\n    try solve [introv J; inverts* J]; introv J.\n  - (* typing_app *)\n    inverts* J.\n    + (* top *)\n      inverts Typ1. inverts* H.\n    + (* e_absv A0 . e : A0->B0  v *)\n      inverts Typ1. inverts H.\n      exists B. split*.\n      constructor.\n      forwards* (?&Typ_v'&Sub): TypedReduce_preservation H5.\n      pick_fresh y.\n      forwards~ Typ_chk: H8 y.\n      rewrite_env(nil++[(y,A)]++nil) in Typ_chk.\n      forwards~ (?&?&?): Typing_subst_2 Typ_chk Typ_v'.\n      eapply Typing_chk_sub.\n      rewrite* (@subst_exp_intro y).\n      apply~ subsub2sub.\n    + forwards* (?&?&?): IHTyp1.\n      forwards* (?&C'&?&?&?): arrTyp_subsub H H1.\n      exists C'. split*.\n      applys* Typ_app.\n      applys~ Typing_chk_sub Typ2.\n    +\n      forwards* (?&?&?): IHTyp2.\n      apply subsub2sub in H1.\n      forwards*: Typing_chk_sub H0 H1.\n  - (* Typ_merge *)\n    inverts* J.\n    + forwards~ (?&?&?): IHTyp1 H4.\n      exists (t_and x B). split*.\n      apply~ Typ_merge.\n      forwards*: subsub_disjointSpec_l H1 H.\n    + forwards~ (?&?&?): IHTyp2 H4.\n      exists (t_and A x). split*.\n      apply~ Typ_merge.\n      forwards*: subsub_disjointSpec_r H1 H.\n  - (* typing_anno *)\n    inverts J.\n    + forwards*: TypedReduce_prv_value e e'.\n      inverts* Typ'.\n      forwards*: TypedReduce_preservation H3.\n    + forwards* (?&?&?): IHTyp.\n      exists A. split*.\n      apply Typ_anno.\n      apply subsub2sub in H0.\n      forwards*: Typing_chk_sub H H0.\n  - (* typing_fix *)\n    inverts J.\n    exists A. split*.\n    eapply Typ_anno.\n    pick_fresh x.\n    rewrite* (@subst_exp_intro x).\n    forwards~ Typ_chk: H.\n    rewrite_env(nil++[(x,A)]++nil) in Typ_chk.\n    lets~ (?&?&?): Typing_subst_2 Typ_chk Typ'.\n    apply subsub2sub in H2.\n    forwards*: Typing_chk_sub H2.\n  - (* typing_mergev *)\n    inverts J.\n    + inverts H0.\n      forwards*: step_not_value H5 H6.\n    + inverts H0.\n      forwards*: step_not_value H7 H6.\n  - (* Typ_sub *)\n    forwards* (?&?&?): IHTyp.\n    exists B. split*.\n    apply subsub2sub in H1.\n    assert (S: sub x B) by auto_sub.\n    forwards*: Typ_sub H0 S.\nQed.\n\n\nTheorem preservation : forall e e' dir A,\n    Typing nil e dir A ->\n    step e e' ->\n    Typing nil e' Chk A.\nProof.\n  intros e e' dir A H H0.\n  lets* (?&?&?): preservation_subsub H H0.\n  apply subsub2sub in H2.\n  destruct dir.\n  - sapply* Typ_sub.\n  - sapply* Typing_chk_sub.\nQed.\n\n#[export]\nHint Resolve value_lc : core.\n\n(* Progress *)\nLemma TypedReduce_progress: forall v A,\n    value v -> Typing [] v Chk A -> exists v', TypedReduce v A v'.\nProof with auto_sub.\n  intros v A Val TypC.\n  (* convert Chk to Inf & introduce B <: A*)\n  lets* (B&Typ&Sub): Typing_chk2inf TypC. clear TypC.\n  gen B.\n  induction A; intros.\n  - (* int *)\n    inductions Typ; inverts* Val;\n    try solve [inverts Sub; solve_false];\n    (* intersection <: ordinary type *)\n    try solve [forwards* [?|[?|(?&?&HF)]]: sub_inversion_and_l Sub;\n               try solve [forwards* (?&?): IHTyp1];\n               try solve [forwards* (?&?): IHTyp2];\n               try solve [inverts HF]].\n  - (* top *)\n    exists. apply~ TReduce_top.\n  - (* arrow *)\n    destruct (toplike_decidable A2).\n    + exists. apply~ TReduce_top.\n    + clear IHA1 IHA2.\n      inductions Typ; inverts* Val;\n    try solve [inverts Sub; solve_false];\n    (* intersection <: ordinary type *)\n    try solve [forwards* [?|[?|(?&?&HF)]]: sub_inversion_and_l Sub;\n               try solve [forwards* (?&?): IHTyp1];\n               try solve [forwards* (?&?): IHTyp2];\n               try solve [inverts HF]].\n      * (* arrow *)\n        inverts* Sub.\n  - (* and *)\n    forwards* (?&?): IHA1...\n    forwards* (?&?): IHA2...\nQed.\n\n#[export]\nHint Resolve Typing_regular_1 : core.\n\nTheorem progress : forall e dir A,\n    Typing nil e dir A ->\n    value e \\/ exists e', step e e' .\nProof.\n  introv Typ.\n  inductions Typ;\n    try solve [left*];\n    try solve [right*].\n  - (* var *)\n    invert H0.\n  - (* app *)\n    right.\n    lets* [Val1 | [e1' Red1]]: IHTyp1.\n    lets* [Val2 | [e2' Red2]]: IHTyp2.\n    inverts* Typ1;\n      try solve [ inverts Val1 ]; inverts H.\n    + (* e_app (e_absv _ _) v2 *)\n      lets* (v2' & Tyr): TypedReduce_progress Typ2.\n  - (* merge *)\n    destruct~ IHTyp1 as [ Val1 | [t1' Red1]];\n      destruct~ IHTyp2 as [ Val2 | [t2' Red2]];\n      subst.\n    + (* e_merge v1 e2 *)\n      inverts* Typ1.\n    + (* e_merge e1 v2 *)\n      inverts* Typ2.\n    + (* e_merge e1 e2 *)\n      inverts* Typ2.\n  - (* anno *)\n    right.\n    destruct~ IHTyp as [? | (?&?)].\n    + (* value e *)\n      lets* (v1' & Tyr) : TypedReduce_progress H.\n    + exists*.\n  - (* subsumption *)\n    destruct~ IHTyp.\nQed.\n\n\n(* Type Safety *)\nTheorem preservation_multi_step : forall e e' dir A,\n    Typing nil e dir A ->\n    e ->* e' ->\n    exists C, Typing nil e' dir C /\\ subsub C A.\nProof.\n  introv Typ Red.\n  gen A. induction* Red.\n  intros.\n  lets* (?&?&?): preservation_subsub Typ H.\n  forwards* (?&?&?): IHRed H0.\n  exists x0. split*.\n  forwards*: subsub_trans H3 H1.\nQed.\n\n\nTheorem type_safety : forall e e' dir A,\n    Typing nil e dir A ->\n    e ->* e' ->\n    value e' \\/ exists e'', step e' e''.\nProof.\n  introv Typ Red. gen A.\n  induction Red; intros.\n  lets*: progress Typ.\n  lets* (?&?&?): preservation_subsub Typ H.\nQed.\n", "meta": {"author": "XSnow", "repo": "TamingMerge", "sha": "f2c55da56db597ed94a1a45a49c31e2869362d9c", "save_path": "github-repos/coq/XSnow-TamingMerge", "path": "github-repos/coq/XSnow-TamingMerge/TamingMerge-f2c55da56db597ed94a1a45a49c31e2869362d9c/simple/coq/Type_Safety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24507923728798503}}
{"text": "(** Code, specifications, proofs for manipulating arrays in kernel memory *)\n\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import List.\nRequire Import Utils.\nRequire Import LibTactics.\nImport ListNotations.\n\nRequire Import Memory.\nRequire Import Instr.\nRequire Import Lattices.\nRequire Import Concrete.\nRequire Import CodeGen.\nRequire Import CodeTriples.\nRequire Import CodeSpecs.\nRequire Import Concrete.\nRequire Import ConcreteExecutions.\nRequire Import ConcreteMachine.\nRequire Import Coq.Arith.Compare_dec.\n\n(* Everything to do with machine execution and triples has to be parameterized over SysTable. *)\nSection with_cblock.\n\nVariable cblock : block privilege.\nHypothesis stamp_cblock : Mem.stamp cblock = Kernel.\nVariable table : CSysTable.\n\nLocal Notation val := (val privilege).\nLocal Notation Atom := (Atom val privilege).\nLocal Notation memory := (Mem.t Atom privilege).\nLocal Notation PcAtom := (PcAtom val).\nLocal Notation block := (block privilege).\n\nFixpoint narrow (n : nat) (A B : Type) : Type :=\n  match n with\n    | O => B\n    | S n' => A -> narrow n' A B\n  end.\n\nFixpoint nexists {n : nat} {A : Type}\n                 (P : narrow n A Prop) : Prop :=\n  match n return narrow n A Prop -> Prop with\n    | O => fun P => P\n    | S n' => fun P => exists a, nexists (P a)\n  end P.\n\nFixpoint stk_env_aux\n           (e : list val) (s0 : list CStkElmt)\n           (k : list CStkElmt -> Prop) : narrow (length e) val Prop :=\n  match e with\n    | nil => k s0\n    | v :: e' => fun t => stk_env_aux e' s0 (fun r => k ((v,t):::r))\n  end.\n\nDefinition stk_env (s : list CStkElmt) (e : list val)\n                   (s0 : list CStkElmt) : Prop :=\n  Eval compute in\n    nexists (stk_env_aux e s0 (fun r => s = r)).\n\nLtac apply_wp :=\n  try unfold pop, nop, push, dup, swap, sub, genEq;\n  try eapply add_spec;\n  try eapply sub_spec;\n  try eapply genEq_spec;\n  try eapply dup_spec;\n  try eapply swap_spec;\n  try eapply push_spec;\n  try eapply pop_spec;\n  try eapply PushCachePtr_spec;\n  try eapply alloc_spec;\n  try eapply load_spec;\n  try eapply store_spec;\n  try eapply unpack_spec;\n  try eapply pack_spec;\n  try eapply getoff_spec;\n  simpl.\n\nLtac build_vc wptac :=\n  let awp := (try apply_wp; try wptac) in\n  try (eapply HT_compose_flip; [(build_vc wptac; awp)| (awp; eapply HT_strengthen_premise; awp)]).\n\n(*\nLtac apply_wp :=\n  try unfold pop, nop, push, dup, swap;\n  match goal with\n  | |- HT _ _ [Store] _ _ => eapply store_spec\n  | |- HT _ _ [Add] _ _  => eapply add_spec\n  | |- HT _ _ [Dup ?N] _ _ => eapply dup_spec\n  | |- HT _ _ [Swap ?N] _ _ => eapply swap_spec\n  | |- HT _ _ [Load] _ _ => eapply load_spec\n  | |- HT _ _ [Push ?N] _ _ => eapply push_spec\n  | |- HT _ _ [Pop] _ _ => eapply pop_spec\n  end;\n  simpl.\n\nLtac build_vc wptac :=\n  let awp := (try apply_wp; try wptac) in\n  try (eapply HT_compose_flip; [(build_vc wptac; awp)| (awp; eapply HT_strengthen_premise; awp)]).\n*)\n\n(* This version doesn't progress past introductions, which makes it useful when\n   we need to do some manual work after an introduction but before doing an eexists *)\nLtac split_vc' :=\n  (try subst; simpl;\n   match goal with\n   | H: exists X,_ |- _ => (destruct H; split_vc')\n   | H: ?P /\\ ?Q |- _ => (destruct H; split_vc')\n   | |- exists X, _ => (eexists; split_vc')\n   | |- ?P /\\ ?Q => (split; [(eauto; try (zify; lia);fail) | split_vc'])\n   | _ => (eauto; try (zify; lia))\n   end).\n\n(* This version is more aggressive. *)\nLtac split_vc :=\n  (try subst; simpl;\n   match goal with\n   | H: exists X,_ |- _ => (destruct H; split_vc)\n   | H: ?P /\\ ?Q |- _ => (destruct H; split_vc)\n   | |- forall P, _ => (intro; try subst; split_vc)\n   | |- exists X, _ => (eexists; split_vc)\n   | |- ?P /\\ ?Q => (split; [(eauto; try (zify; lia);fail) | split_vc])\n   | _ => (eauto; try (zify; lia))\n   end).\n\nSection with_hints.  (* Limit hints to this section. *)\n\n(* These are intended to work with split_vc. *)\nHint Resolve extends_refl : core.\nHint Resolve extends_trans : core.\nHint Resolve extends_valid_address : core.\nHint Resolve extends_update : core.\n\n(* Memory copy.  *)\n\n(* Initial stack:  count :: dst0 :: src0 :: _\n   Final stack:    0 :: dst0 :: src0 :: _\n   Side Effects: copies (src0,src0+count] to (dst0,dst0+count]  (provided these regions are disjoint) *)\n\nDefinition copy :=\n  genFor ([Dup 2] ++ (* src0 :: count :: dst0 :: src0 :: _ *)\n          [Dup 1] ++ (* count :: src0 :: count :: dst0 :: src0 :: _ *)\n          [Add] ++   (* src0+count :: count :: dst0 :: src0 :: _ *)\n          [Load] ++  (* mem[src0+count] :: count :: dst0 :: src0 :: _ *)\n          [Dup 2] ++ (* dst0 :: mem[src0+count] :: count :: dst0 :: src0 :: _ *)\n          [Dup 2] ++ (* count :: dst0 :: mem[src0+count] :: count :: dst0 :: src0 :: _ *)\n          [Add] ++   (* dst0+count :: mem[src0+count] :: count :: dst0 :: src0 :: _ *)\n          [Store]).\n\n(* The loop invariant for copy. *)\nDefinition Icopy (sz cnt:Z) bdst odst bsrc osrc (m0 : memory) s0 :=\n  fun m s =>\n    exists t2 t3,\n      s = (Vptr (bdst, odst),t2):::(Vptr (bsrc, osrc),t3):::s0 /\\\n      (cnt <= sz) /\\\n      (forall z, osrc < z <= osrc+cnt -> valid_address (bsrc, z) m) /\\\n      (forall z, odst < z <= odst+cnt -> valid_address (bdst, z) m) /\\\n      (bdst <> bsrc) /\\\n      (Mem.stamp bdst = Kernel) /\\\n      (Mem.stamp bsrc = Kernel) /\\\n      (forall z, cnt < z <= sz -> load (bsrc,osrc+z) m = load (bdst,odst+z) m) /\\\n      (forall z, ~ (odst+cnt < z <= odst+sz) -> load (bdst,z) m = load (bdst,z) m0) /\\\n      (forall b, b <> bdst -> Mem.get_frame m b = Mem.get_frame m0 b).\n\nLemma copy_spec : forall (Q : memory -> stack -> Prop),\n  HT cblock table copy\n  (fun m s => exists sz bdst odst bsrc osrc s0 t1 t2 t3,\n                0 <= sz /\\\n                s = (Vint sz,t1):::(Vptr (bdst,odst),t2):::(Vptr (bsrc,osrc),t3):::s0 /\\\n                (forall z, osrc < z <= osrc+sz -> valid_address (bsrc,z) m) /\\\n                (forall z, odst < z <= odst+sz -> valid_address (bdst,z) m) /\\\n                (bdst <> bsrc) /\\\n                Mem.stamp bdst = Kernel /\\\n                Mem.stamp bsrc = Kernel /\\\n                (forall m1 t1' t2' t3',\n                   (forall z, 0 < z <= sz -> load (bsrc,osrc+z) m1 = load (bdst,odst+z) m1) /\\\n                   (forall z, ~ (odst < z <= odst+sz) -> load (bdst,z) m1 = load (bdst,z) m) /\\\n                   (forall b, b <> bdst -> Mem.get_frame m1 b = Mem.get_frame m b) ->\n                   Q m1 ((Vint 0,t1'):::(Vptr (bdst,odst),t2'):::(Vptr (bsrc,osrc),t3'):::s0)))\n  Q.\nProof.\n  intros. unfold copy.\n  eapply HT_strengthen_premise with\n  (fun m s => exists sz bdst odst bsrc osrc s0 m0 t1 t2 t3,\n                0 <= sz /\\\n                m = m0 /\\\n                s = (Vint sz,t1):::(Vptr (bdst,odst),t2):::(Vptr (bsrc,osrc),t3):::s0 /\\\n                (forall z, osrc < z <= osrc+sz -> valid_address (bsrc,z) m) /\\\n                (forall z, odst < z <= odst+sz -> valid_address (bdst,z) m) /\\\n                (bdst <> bsrc) /\\\n                Mem.stamp bdst = Kernel /\\\n                Mem.stamp bsrc = Kernel /\\\n                (forall m1 t1' t2' t3',\n                   (forall z, 0 < z <= sz -> load (bsrc,osrc+z) m1 = load (bdst,odst+z) m1) /\\\n                   (forall z, ~ (odst < z <= odst+sz) -> load (bdst,z) m1 = load (bdst,z) m) /\\\n                   (forall b, b <> bdst -> Mem.get_frame m1 b = Mem.get_frame m b) ->\n                   Q m1 ((Vint 0,t1'):::(Vptr (bdst,odst),t2'):::(Vptr (bsrc,osrc),t3'):::s0)));\n    [|solve [split_vc]].\n  eapply HT_forall_exists. intro sz.\n  eapply HT_forall_exists. intro bdst.\n  eapply HT_forall_exists. intro odst.\n  eapply HT_forall_exists. intro bsrc.\n  eapply HT_forall_exists. intro osrc.\n  eapply HT_forall_exists. intro s0.\n  eapply HT_forall_exists. intro m0.\n  eapply HT_forall_exists. intro t1.\n  eapply HT_forall_exists. intro t2.\n  eapply HT_forall_exists. intro t3.\n  eapply HT_fold_constant_premise; intro.\n  eapply HT_strengthen_premise.\n  { eapply genFor_spec\n      with (I := fun (Q : _ -> _ -> Prop) m s i =>\n                   Icopy sz i bdst odst bsrc osrc m0 s0 m s /\\\n                   forall m' s' ti',\n                     Icopy sz 0 bdst odst bsrc osrc m0 s0 m' s' ->\n                     Q m' ((Vint 0, ti') ::: s')).\n    { intros i POS.\n      eexists. split.\n      - build_vc idtac.\n      - intros m s t (INV & END).\n        unfold Icopy in *.\n        destruct INV as (t5 & t6 & Hs & ? & VALIDSRC & VALIDDST & ? & ? & ? & COPY & REST & ?).\n        subst.\n        exploit (VALIDSRC (i + osrc)); try lia. intros [val Hval].\n        exploit (VALIDDST (i + odst)); try lia. intros [val' Hval'].\n        eapply load_some_store_some in Hval'. destruct Hval' as [m' Hm'].\n        split_vc.\n        split; [|split; eauto]; eauto.\n        split_vc.\n        split.\n        { split_vc.\n          repeat split; eauto; try lia.\n          + intros.\n            eapply valid_address_upd; eauto.\n            eapply VALIDSRC. lia.\n          + intros.\n            eapply valid_address_upd; eauto.\n            apply VALIDDST. lia.\n          + intros.\n            destruct (Z.eq_dec i z) as [ZEQ | ZNEQ].\n            * subst.\n              replace (odst + z) with (z + odst) by lia.\n              erewrite (load_store_new Hm').\n              rewrite <- Hval.\n              replace (osrc + z) with (z + osrc) by ring.\n              eapply load_store_old; eauto.\n              congruence.\n            * do 2 (erewrite (load_store_old Hm'); eauto; try congruence).\n              2: (intros contra; inversion contra; lia).\n              eapply COPY. lia.\n          + intros.\n            erewrite (load_store_old Hm'); eauto; try congruence.\n            2: (intros contra; inversion contra; lia).\n            apply REST. lia.\n          + intros.\n            erewrite (get_frame_store_neq _ _ _ _ _ _ _ _ Hm'); eauto. }\n        intros. split_vc. apply END.\n        do 2 eexists. repeat (split; eauto). }\n\n    intros m s t (END & POST). eauto. }\n\n  unfold Icopy. split_vc. split.\n  - split_vc.\n  - split_vc.\n    replace (odst + 0) with odst in * by ring. eauto.\nQed.\n\n(* A (counted) array is a sequence of values in memory, proceeded by their count:\n\n        -----------\na ----> |    n    |\n        -----------\n        |  v_1    |\n        -----------\n        |  ...    |\n        -----------\n        |  v_n    |\n        -----------\n\n*)\n\n\nInductive memseq (m:memory) b : Z -> list val -> Prop :=\n| memseq_nil : forall z, memseq m b z nil\n| memseq_cons : forall z v t vs, load (b,z) m = Some (v, t) -> memseq m b (z+1) vs -> memseq m b z (v::vs)\n.\n\nLemma memseq_valid : forall m b a vs,\n  memseq m b a vs ->\n  forall z, a <= z < a + Z.of_nat(length vs) -> valid_address (b,z) m.\nProof.\n  induction 1; intros.\n  simpl in H. exfalso; lia.\n  simpl in H1.\n  destruct (Z.eq_dec z z0).\n  { subst. econstructor. eauto. }\n  eapply IHmemseq. zify; lia.\nQed.\n\nHint Resolve memseq_valid : core.\n\nLemma memseq_read : forall m b a vs,\n  memseq m b a vs ->\n  forall z, a <= z < a + Z.of_nat(length vs) -> exists v t, load (b,z) m = Some(v,t).\nProof.\n  induction 1; intros.\n  simpl in H. exfalso; lia.\n  simpl in H1.\n  destruct (Z.eq_dec z z0).\n  { subst. eexists; eauto. }\n  eapply IHmemseq. zify; lia.\nQed.\n\nLemma memseq_app: forall m b a vs1 vs2,\n  memseq m b a (vs1 ++ vs2) <-> (memseq m b a vs1 /\\ memseq m b (a + Z.of_nat(length vs1)) vs2).\nProof.\n  intros. split.\n  - generalize dependent a.\n    induction vs1; intros.\n    + simpl in *.\n      split. constructor.\n      replace (a+0) with a by ring. auto.\n    + simpl in H.\n      inv H.\n      destruct (IHvs1 (a0+1) H4).\n      split.\n      econstructor; eauto.\n      simpl (length (a::vs1)).\n      replace (a0 + Z.of_nat (S (length vs1))) with (a0 + 1 + Z.of_nat(length vs1)) by (zify;lia).\n      assumption.\n  - generalize dependent a.\n    induction vs1; intros.\n    + simpl in *. inv H. replace (a+0) with a in H1 by ring. auto.\n    + inv H. simpl. inv H0. econstructor; eauto.\n      eapply IHvs1. split. auto. simpl (length (a::vs1)) in H1.\n      replace (a0 + 1 + Z.of_nat (length vs1)) with (a0 + Z.of_nat(S(length vs1))) by (zify;lia).\n      assumption.\nQed.\n\nLemma memseq_eq :\n  forall m1 m2 b1 b2 a1 a2 vs\n         (LOAD : forall z, 0 <= z < Z.of_nat (length vs) ->\n                           load (b1,a1+z) m1 = load (b2,a2+z) m2)\n         (SEQ : memseq m1 b1 a1 vs),\n    memseq m2 b2 a2 vs.\nProof.\n  intros.\n  generalize dependent a2.\n  induction SEQ.\n  - intros. constructor.\n  - intros.\n    assert (Hz : load (b1,z) m1 = load (b2,a2) m2).\n    { replace z with (z+0) by ring. replace a2 with (a2+0) by ring.\n      eapply LOAD. simpl. zify; lia. }\n    destruct (load (b2,a2) m2) as [[v0 l0]|] eqn:E; try congruence.\n    rewrite Hz in H. inv H.\n    econstructor; eauto.\n    eapply IHSEQ. intros.\n    replace (z+1 + z0) with (z+(1+z0)) by lia.\n    replace (a2+1 + z0) with (a2+ (1+z0)) by lia.\n    eapply LOAD. simpl (length (v::vs)). zify; lia.\nQed.\n\nLemma memseq_drop :\n  forall ms b z p vs\n         (MEM : memseq ms b z vs),\n    memseq ms b (z + Z.of_nat p) (drop p vs).\nProof.\n  intros.\n  gdep z. gdep p.\n  induction vs as [|v vs IH]; intros p z MEM.\n  - destruct p; constructor.\n  - destruct p.\n    * simpl.\n      rewrite Zplus_comm. auto.\n    * rewrite Nat2Z.inj_succ in *.\n      inv MEM.\n      replace (z + Z.succ (Z.of_nat p)) with (z + 1 + Z.of_nat p); try lia.\n      apply IH. auto.\nQed.\n\nInductive memarr (m:memory) b (vs:list val) : Prop :=\n| memarr_i : forall c t\n                    (LOAD : load (b,0) m = Some (Vint (Z_of_nat c), t))\n                    (SEQ : memseq m b 1 vs)\n                    (LEN : c = length vs),\n               memarr m b vs.\n\n(* Array allocation.  *)\n\n(* Initial stack: count :: _\n   Final stack:  ptr-to-array :: _\n   Side effects: allocates fresh array of size count *)\n\nDefinition alloc_array:= push 0 ++ [Dup 1] ++ push 1 ++ [Add] ++ [Alloc] ++ dup ++ [Swap 2] ++ [Swap 1] ++ [Store].\n\nLemma alloc_array_spec: forall (Q : memory -> stack -> Prop),\n  HT cblock table alloc_array\n     (fun m s => exists cnt t s0,\n                   s = (Vint cnt,t):::s0 /\\\n                   cnt >= 0 /\\\n                   (forall b m1 t2,\n                      extends m m1 ->\n                      (forall p, 0 < p <= cnt -> valid_address (b,p) m1) ->\n                      (exists t1, load (b,0) m1 = Some (Vint cnt, t1)) ->\n                      Mem.get_frame m b = None ->\n                      Mem.stamp b = Kernel ->\n                      Q m1 ((Vptr (b,0),t2):::s0)))\n     Q.\nProof.\n  intros.\n  unfold alloc_array.\n  Opaque Z.add. (* not sure why this is necessary this time *)\n  unfold alloc_array.\n  build_vc ltac: (try apply alloc_spec; eauto).\n  intros m s (cnt & t & s0 & ? & ? & H). subst.\n  split_vc'. intros.\n  assert (VALID : valid_address (b,0) m0).\n  { eexists (Vint 0, handlerTag).\n    erewrite load_alloc; eauto.\n    simpl.\n    (* suffices for 8.4pl1:\n    destruct (EquivDec.equiv_dec b b ). *)\n    (* explicit arguments in following needed for 8.4 *)\n    destruct(\n       @EquivDec.equiv_dec _ _\n         (@eq_equivalence (Memory.block privilege)) _ b b); try congruence.\n    destruct (Z_lt_dec 0 (1 + cnt)); try lia.\n    reflexivity. }\n  eapply valid_store in VALID. destruct VALID.\n  assert (ALLOC' := H0).\n  unfold c_alloc, alloc in H0.\n  match goal with\n    | H : match ?B with _ => _ end = Some _ |- _ =>\n      destruct B; inv H\n  end.\n  split_vc. intuition eauto.\n  - eapply Mem.alloc_stamp; eauto.\n  - assert (FRESH : Mem.get_frame m b = None).\n    { eapply Mem.alloc_get_fresh; eauto. }\n    apply H; eauto.\n    + intros b' fr' FRAME'.\n      assert (b <> b') by congruence.\n      eapply get_frame_store_neq in H2; eauto.\n      eapply alloc_get_frame_old in H4; eauto.\n      congruence.\n    + intros.\n      unfold c_alloc in ALLOC'.\n      eexists (Vint 0, handlerTag).\n      erewrite load_store_old; eauto.\n      * erewrite (load_alloc (b := b)); eauto.\n        (* suffices for 8.4pl1:\n        destruct (EquivDec.equiv_dec b b); try congruence. *)\n        (* explicit arguments for 8.4 *)\n        destruct (\n           @EquivDec.equiv_dec _\n              (@eq (Memory.block privilege)) _ _ b); try congruence.\n        destruct (Z_le_dec 0 p); try lia.\n        destruct (Z_lt_dec p (1 + cnt)); try lia.\n        reflexivity.\n      * intros contra.\n        inv contra.\n        lia.\n    + eexists. eapply load_store_new; eauto.\n    + eapply Mem.alloc_stamp; eauto.\nQed.\nTransparent Z.add.\n\n(* Sum array lengths *)\n\n(* Initial stack:  array1 :: array2 :: _\n   Final stack:    (l1+l2) :: array1 :: array2 :: _\n      where l1,l2 are lengths of array1,array2\n   Side effects: none\n*)\n\nDefinition sum_array_lengths := [Dup 1] ++ [Load] ++ [Dup 1] ++ [Load] ++ [Add].\n\nLemma sum_array_lengths_spec : forall Q : HProp,\n  HT cblock table sum_array_lengths\n     (fun m s => exists a1 a2 s0 l1 l2 t1 t2 t1' t2',\n                 s = (Vptr (a2,0),t2):::(Vptr (a1,0),t1):::s0 /\\\n                 load (a2,0) m = Some (Vint l2, t1') /\\\n                 load (a1,0) m = Some (Vint l1, t2') /\\\n                 Mem.stamp a1 = Kernel /\\\n                 Mem.stamp a2 = Kernel /\\\n                 forall t1'' t2'',\n                   Q m ((Vint (l2+l1),handlerTag):::(Vptr (a2,0),t2''):::(Vptr (a1,0),t1''):::s0))\n      Q.\nProof.\n  intros. unfold sum_array_lengths.\n  build_vc ltac:(idtac).\n  split_vc.\nQed.\n\n\n(* Concatenate two existing arrays into a freshly allocated new array. *)\n\n(* Initial stack: array1::array2::_\n   Final stack:   r::_\n        where r is pointer to newly allocated array\n   Side effects: allocates new array and concatenates existing contents into it.  *)\n\nDefinition concat_arrays :=      (* a2 a1 *)\n     sum_array_lengths           (* (l2+l1) a2 a1 *)\n  ++ alloc_array                 (* r a2 a1 *)\n  ++ [Dup 2]                     (* a1 r a2 a1 *)\n  ++ [Dup 1]                     (* r a1 r a2 a1 *)\n  ++ [Dup 1]                     (* a1 r a1 r a2 a1 *)\n  ++ [Load]                      (* l1 r a1 r a2 a1 *)\n  ++ copy                        (* 0 r a1 r a2 a1 *)\n  ++ pop                         (* r a1 r a2 a1 *)\n  ++ [Dup 1]                     (* a1 r a1 r a2 a1 *)\n  ++ [Load]                      (* l1 r a1 r a2 a1 *)\n  ++ [Add]                       (* (l1+r) a1 r a2 a1 *)\n  ++ [Swap 1]                    (* a1 (l1+r) r a2 a1 *)\n  ++ pop                         (* (l1+r) r a2 a1 *)\n  ++ [Dup 2]                     (* a2 (l1+r) r a2 a1 *)\n  ++ [Swap 1]                    (* (l1+r) a2 r a2 a1 *)\n  ++ [Dup 1]                     (* a2 (l1+r) a2 r a2 a1 *)\n  ++ [Load]                      (* l2 (l1+r) a2 r a2 a1 *)\n  ++ copy                        (* 0 (l1+r) a2 r a2 a1 *)\n  ++ pop                         (* (l1+r) a2 r a2 a1 *)\n  ++ pop                         (* a2 r a2 a1 *)\n  ++ pop                         (* r a2 a1 *)\n  ++ [Swap 2]                    (* a2 a1 r *)\n  ++ pop                         (* a1 r *)\n  ++ pop                         (* r *)\n.\n\n\nLemma concat_arrays_spec : forall (Q :memory -> stack -> Prop),\n  HT cblock table\n   concat_arrays\n   (fun m s => exists a2 a1 vs1 vs2 s0 t1 t2,\n                 s = (Vptr (a2,0),t2):::(Vptr (a1,0),t1):::s0 /\\\n                 memarr m a1 vs1 /\\ memarr m a2 vs2 /\\\n                 Mem.stamp a1 = Kernel /\\ Mem.stamp a2 = Kernel /\\\n                 (forall r m1 t,\n                    extends m m1 ->\n                    memarr m1 r (vs1 ++ vs2) ->\n                    Mem.get_frame m r = None ->\n                    Mem.stamp r = Kernel ->\n                    Q m1 ((Vptr (r,0),t):::s0)))\n   Q.\nProof.\n  intros. unfold concat_arrays.\n\n  build_vc ltac:(try apply copy_spec; try apply alloc_array_spec; try apply sum_array_lengths_spec).\n\n  intros m s (a2 & a1 & vs1 & vs2 & t1 & t2 & s0 & ? & ARR1 & ARR2 & K1 & K2 & POST).\n  destruct ARR1. destruct ARR2.\n  split_vc'. intros t1'' t2''. split_vc'.\n  intros b m1 t'' EXT VALID [t''' LOADSUM] FRESH KERNEL.\n  assert (a1 <> b).\n  { intros contra. subst. unfold load in *. simpl in *.\n    rewrite FRESH in LOAD.\n    congruence. }\n  assert (a2 <> b).\n  { intros contra. subst. unfold load in *. simpl in *.\n    rewrite FRESH in LOAD0.\n    congruence. }\n(* XXX *)\n\n  split_vc'.\n  split; eauto using extends_load.\n  exists (Z.of_nat (length vs1)).\n  split_vc'.\n  split.\n  { intros.\n    eapply extends_valid_address; eauto.\n    eapply memseq_valid; eauto.\n    lia. }\n  split.\n  { intros. apply VALID. lia. }\n  split; try congruence.\n  split_vc.\n  assert (LOADm0m1 : forall b' off,\n                       b' <> b ->\n                       load (b', off) m0 = load (b', off) m1).\n  { unfold load.\n    intros.\n    rewrite H3; trivial. }\n  split.\n  { assert (LOAD'' := LOAD).\n    eapply extends_load with (m3 := m1) in LOAD''; eauto.\n    cut (load (a1, 0) m0 = load (a1, 0) m1).\n    { intros E. rewrite E. eassumption. }\n    unfold load.\n    rewrite H3; trivial. }\n  split_vc.\n  split.\n  { assert (LOAD'' := LOAD0).\n    eapply extends_load with (m3 := m1) in LOAD''; eauto.\n    cut (load (a2, 0) m0 = load (a2, 0) m1).\n    { intros E. rewrite E. eassumption. }\n    unfold load.\n    rewrite H3; trivial. }\n  exists (Z.of_nat (length vs2)).\n  split_vc.\n  split.\n  { simpl. intros.\n    eapply memseq_valid with (z := z) in SEQ0; try lia.\n    exploit @extends_valid_address; eauto.\n    unfold valid_address in *.\n    rewrite LOADm0m1; eauto. }\n  split.\n  { intros.\n    unfold valid_address in *.\n    rewrite H2; try lia.\n    apply VALID. lia. }\n  split_vc.\n  apply POST; trivial.\n  - intros b' fr' FRAME'.\n    rewrite H6; try congruence.\n    rewrite H3; try congruence.\n    eauto.\n  - econstructor; eauto.\n    + rewrite H5; try lia.\n      rewrite H2; try lia.\n      rewrite LOADSUM.\n      repeat f_equal.\n      rewrite app_length. zify. lia.\n    + rewrite memseq_app.\n      split.\n      * apply memseq_eq with (m1 := m) (b1 := a1) (a1 := 1); eauto.\n        intros.\n        rewrite H5; try lia.\n        rewrite <- H1; try lia.\n        rewrite LOADm0m1; try congruence.\n        assert (VALID' : valid_address (a1,1 + z) m).\n        { eapply memseq_valid; eauto. lia. }\n        destruct VALID' as [a VALID'].\n        rewrite VALID'.\n        symmetry.\n        eapply extends_load; eauto.\n      * apply memseq_eq with (m1 := m) (b1 := a2) (a1 := 1); eauto.\n        intros.\n        replace (1 + Z.of_nat (length vs1) + z) with (Z.of_nat (length vs1) + 0 + (1 + z)) by ring.\n        rewrite <- H4; try lia.\n        assert (LOADm2m0 : load (a2,1 + z) m2 = load (a2,1 + z) m0).\n        { unfold load. rewrite H6; trivial. }\n        rewrite LOADm2m0.\n        rewrite LOADm0m1; try congruence.\n        assert (VALID' : valid_address (a2,1 + z) m).\n        { eapply memseq_valid; eauto. lia. }\n        destruct VALID' as [a VALID'].\n        rewrite VALID'.\n        symmetry.\n        eapply extends_load with (m3 := m); eauto.\nQed.\n\n\n(* Foldr over an array. *)\n\n(* Initial stack:   a::S\n   Final stack:     r::S\n       where gen_n assumes _::S and generates v::_::S  with v the initial accumulator value\n       where gen_f assumes x::v::_::_::_::S and generates v'::_::_::_::S with v' the new accumulator value\n       and r is overall accumulator value for entire list. *)\nDefinition fold_array_body gen_f :=   (* i v a S *)\n      [Dup 1]                         (* v i v a S *)\n   ++ [Dup 3]                         (* a v i v a S *)\n   ++ [Dup 2]                         (* i a v i v a S *)\n   ++ [Add]                           (* i+a v i v a S *)\n   ++ [Load]                          (* x v i v a S *)\n   ++ gen_f                           (* v' i v a S *)\n   ++ [Swap 2]                        (* v i v' a S *)\n   ++ pop                             (* i v' a S *)\n.\n\nDefinition fold_array gen_n gen_f :=     (* a S *)\n      gen_n                              (* v a S *)\n  ++  [Dup 1]                            (* a v a S *)\n  ++  [Load]                             (* l v a S *)\n  ++  genFor                             (* i v a S *)\n        (fold_array_body gen_f)          (* i v' a S *)\n  ++ pop                                 (* r a S *)\n  ++ [Swap 1]                            (* a r S *)\n  ++ pop                                 (* r S *)\n.\n\n(* Invariant for fold array body *)\nDefinition Ifab (f : val -> val -> val) (n: val)\n                (a:block) (vs:list val) m0 s0 i :=\n    fun m s =>\n      exists v,\n        i <= Z.of_nat (length vs) /\\\n        memarr m a vs /\\\n        Mem.stamp a = Kernel /\\\n        m = m0 /\\\n        stk_env s [v; Vptr (a,0)] s0 /\\\n        v = fold_right f n (dropZ i vs).\n\nLemma memseq_dropZ :\n  forall ms b z p vs\n         (SEQ : memseq ms b z vs)\n         (POS : p >= 0),\n    memseq ms b (z + p) (dropZ p vs).\nProof.\n  intros.\n  unfold dropZ.\n  destruct (Z.ltb_spec0 p 0); try lia.\n  replace (_ + p) with (z + Z.of_nat (Z.to_nat p)) by (rewrite Z2Nat.id; lia).\n  auto using memseq_drop.\nQed.\n\nLemma memarr_load :\n  forall m a vs i x t\n         (ARR : memarr m a vs)\n         (LOAD : load (a,i) m = Some (x,t))\n         (BOUNDS : 0 < i <= Z.of_nat (length vs)),\n    index_list_Z (Z.pred i) vs = Some x.\nProof.\n  intros.\n  destruct ARR.\n  assert (SEQ' : memseq m a i (dropZ (Z.pred i) vs)).\n  { assert (E : i = 1 + Z.pred i) by lia.\n    rewrite E at 1. apply memseq_dropZ; trivial.\n    lia. }\n  rewrite index_list_Z_dropZ_zero; try lia.\n  exploit (@dropZ_cons _ (Z.pred i) vs); try lia.\n  intros (x' & H). rewrite H in *.\n  rewrite <- Zsucc_pred in *.\n  inv SEQ'.\n  assert (x' = x) by congruence. subst.\n  reflexivity.\nQed.\n\n(* AAA: When we use a Hoare triple in the premise of a WP rule (such\nas in fab_spec' below), using WP style is not very convenient.\n\nSuppose for concreteness that we want to prove a rule for a\nhigher-order generator [macro] of the form\n\n   macro_spec : forall c (Q : HProp),\n                  Hc -> HT (macro c) P Q\n\nwhere P is some expression involving Q, and Hc is some hypothesis that\nstates that some triple should be valid for c. (An example of this is\nfab_spec.) After proving this, we use macro_spec for proving another\ntriple. If Hc is in WP form (i.e., something like (forall Q, HT c P'\nQ), where P' depends on Q), more likely than not, there will be a\nmismatch between P' and the precondition that is computed from Q when\napplying other previously proven Hoare logic rules. This forces us to\napply HT_strengthen_premise explicitly to be able to prove the triple,\nand then prove the additional implication forall m s, P' m s -> P'' m\ns.\n\nOne partial solution is to quantify the precondition in Hc\nexistentially and supplying the postcondition we want as \"input\", as\nin genFor_spec:\n\n(* genFor_spec *)\n(*      : forall (cblock : block) (table : CSysTable) *)\n(*          (I : HProp -> CodeTriples.memory -> list CStkElmt -> Z -> Prop) *)\n(*          (c : CodeTriples.code) (Q : HProp), *)\n(*        (forall i : Z, *)\n(*         i > 0 -> *)\n(*         exists Pc, *)\n(*         HT cblock table c Pc *)\n(*           (fun (m : CodeTriples.memory) (s : CodeTriples.stack) => *)\n(*            exists t s', s = (Vint i, t) ::: s' /\\ I Q m s' (Z.pred i)) /\\ *)\n(*         (forall (m : CodeTriples.memory) (s : list CStkElmt) (t : val), *)\n(*          I Q m s i -> Pc m ((Vint i, t) ::: s))) -> *)\n(*        (forall (m : CodeTriples.memory) (s : list CStkElmt) (t : val), *)\n(*         I Q m s 0 -> Q m ((Vint 0, t) ::: s)) -> *)\n(*        HT cblock table (genFor c) *)\n(*          (fun (m : CodeTriples.memory) (s : CodeTriples.stack) => *)\n(*           exists i t s', s = (Vint i, t) ::: s' /\\ i >= 0 /\\ I Q m s' i) Q *)\n\nA good rule-of-thumb seems to be: triples in conclusions map an\narbitrary postcondition to a precondition that validates the\ntriple. In hypotheses, however, we instead suply the postcondition we\nneed as input and let the other rules we've proved before figure out\nwhat the precondition should be.\n*)\n\nDefinition fab_spec :\n  forall gen_f f n m0 s0\n         (HTf : forall (Q : memory -> stack -> Prop),\n                  HT cblock table gen_f\n                     (fun m s =>\n                        exists x v i0 i1 i2,\n                          stk_env s [x; v; i0; i1; i2] s0 /\\\n                          m = m0 /\\\n                          forall s',\n                            stk_env s' [f x v; i0; i1; i2] s0 ->\n                            Q m s')\n                     Q)\n         (Q : memory -> stack -> Prop),\n    HT cblock table (fold_array_body gen_f)\n       (fun m s =>\n          exists i a vs s',\n            stk_env s [Vint i] s' /\\\n            i > 0 /\\\n            Ifab f n a vs m0 s0 i m s' /\\\n            forall s'' s''',\n              stk_env s'' [Vint i] s''' ->\n              Ifab f n a vs m0 s0 (Z.pred i) m s''' ->\n              Q m s'')\n       Q.\nProof.\n  intros.\n  unfold fold_array_body.\n  eapply HT_strengthen_premise.\n  { repeat (eapply HT_compose; [eapply dup_spec|]).\n    eapply HT_compose; try eapply add_spec.\n    eapply HT_compose; try eapply load_spec.\n    eapply HT_compose; try eapply HTf.\n    eapply HT_compose; try eapply swap_spec.\n    apply pop_spec. }\n  clear.\n  intros m ? (i & a & vs & s' & (ti & ?) & POS & INV & POST). subst.\n  destruct INV as (v & BOUNDS & ARR & STAMP & ? & (tv & ta & ?) & ?).\n  subst m0. subst. simpl.\n\n  do 3 (eexists; split; eauto).\n  do 6 eexists. split; eauto. simpl. split; eauto.\n  assert (Hx : exists x tx, load (a,i) m = Some (x,tx)).\n  { eapply memseq_read.\n    destruct ARR. eauto. lia. }\n  destruct Hx as (x & tx & Hx).\n  do 4 eexists. split; eauto. simpl. split; trivial.\n  replace (i + 0) with i by ring. split; eauto.\n  do 5 eexists. split; [do 5 eexists; eauto|].\n  split; trivial.\n  intros s' (? & ? & ? & ? & ?). subst.\n  do 4 eexists. do 3 (split; eauto).\n  do 3 eexists. split; eauto.\n  change (f x (fold_right f n (dropZ i vs))) with (fold_right f n (x :: dropZ i vs)).\n  exploit (@dropZ_cons _ (Z.pred i) vs); try lia.\n  intros (x' & H).\n  rewrite <- Zsucc_pred in H.\n  replace x' with x in *.\n  { rewrite <- H. eapply POST.\n    - eexists. eauto.\n    - eexists. repeat split; eauto; try lia.\n      do 2 eexists. reflexivity. }\n  exploit memarr_load; eauto; try lia.\n  intros H'.\n  rewrite index_list_Z_dropZ_zero in H'; try lia.\n  rewrite H in H'. compute in H'.\n  congruence.\nQed.\n\nLemma fold_array_spec :\n  forall gen_f gen_n n f m0 s0\n         (HTn : forall (Q : memory -> stack -> Prop),\n                  HT cblock table gen_n\n                     (fun m s =>\n                        exists i0,\n                          stk_env s [i0] s0 /\\\n                          m = m0 /\\\n                          forall s',\n                            stk_env s' [n; i0] s0 ->\n                            Q m s')\n                     Q)\n         (HTf : forall (Q : memory -> stack -> Prop),\n                  HT cblock table gen_f\n                     (fun m s =>\n                        exists x v i0 i1 i2,\n                          stk_env s [x; v; i0; i1; i2] s0 /\\\n                          m = m0 /\\\n                          forall s',\n                            stk_env s' [f x v; i0; i1; i2] s0 ->\n                            Q m s')\n                     Q)\n         (Q : memory -> stack -> Prop),\n    HT cblock table\n       (fold_array gen_n gen_f)\n       (fun m s => exists a vs,\n                     memarr m a vs /\\\n                     Mem.stamp a = Kernel /\\\n                     stk_env s [Vptr (a, 0)] s0 /\\\n                     m = m0 /\\\n                     forall s',\n                       stk_env s' [fold_right f n vs] s0 ->\n                       Q m s')\n       Q.\nProof.\n  intros.\n  unfold fold_array.\n  eapply HT_strengthen_premise.\n\n  (* Using PTs would remove the need for the things between the { }\n     with no need for ad-hoc tactics. *)\n\n  { eapply HT_compose; try eapply HTn.\n    eapply HT_compose; try eapply dup_spec.\n    eapply HT_compose; try eapply load_spec.\n    eapply HT_compose; try eapply genFor_spec\n                       with (I := fun (Q : HProp) m s i =>\n                                    exists a vs,\n                                      Ifab f n a vs m0 s0 i m s /\\\n                                      forall s' s'',\n                                        stk_env s' [Vint 0] s'' ->\n                                        Ifab f n a vs m0 s0 0 m s'' ->\n                                        Q m s').\n    { intros. eexists. split.\n      - eapply fab_spec. apply HTf.\n      - simpl.\n        intros m s t (a & vs & INV & POST).\n        do 4 eexists. split; [eexists; eauto|]. split; try lia.\n        split; eauto.\n        intros s'' s''' (? & ?) INV'. subst.\n        do 2 eexists. split; eauto. }\n\n    { intros m s t (a & vs & INV & POST). eapply POST; eauto. eexists. eauto. }\n    eapply HT_compose; try eapply pop_spec.\n    eapply HT_compose; try eapply swap_spec.\n    eapply pop_spec. }\n\n  intros m s (a & vs & ARR & KERNEL & ? & ? & POST).\n  subst. simpl.\n  eexists. do 2 (split; eauto).\n  intros s' (? & ? & ?). subst.\n  destruct ARR as [c ? LOAD SEQ ?]. subst.\n  eexists. split; eauto.\n  do 4 eexists. do 3 (split; eauto).\n  do 3 eexists. split; eauto. split; try lia.\n  do 2 eexists.\n  split.\n  { unfold Ifab.\n    eexists.\n    repeat split; eauto; try solve [econstructor; eauto]; try lia.\n    rewrite dropZ_all. do 2 eexists. reflexivity. }\n  clear - POST.\n  intros s' s'' (? & ?) (? & _ & ARR & KERNEL & _ & (? & ? & ?) & ?). subst.\n  do 3 eexists. split; eauto.\n  do 4 eexists. do 3 (split; eauto).\n  do 3 eexists. split; eauto.\n  apply POST.\n  eexists. reflexivity.\nQed.\n\n(* Existsb. *)\n\n(* Initial stack: a::S\n   Final stack: r::S\n        where gen_f assumes x::_::_::_::_::S and generates b::_::_::_::_::S with b the result of testing x\n        and r = boolean: gen_f answers true on some element\n*)\nDefinition exists_array gen_f :=  (* a S *)\n      fold_array (                (* _ S *)\n                    genFalse      (* 0 _ S *)\n                 )                (* v _ S *)\n                 (                (* x v _ _ _ S *)\n                    gen_f         (* b v _ _ _ S *)\n                 ++ genOr         (* b\\/v _ _ _ S *)\n                 )                (* v' _ _ _ S *)\n.\n\nDefinition boolToVal (b : bool) : val := Vint (boolToZ b).\n\nLemma boolToVal_existsb : forall f xs,\n                          boolToVal (existsb f xs) =\n                          fold_right (fun x v : val => orv (boolToVal (f x)) v) (Vint 0) xs.\nProof.\n  induction xs;  simpl; auto.\n  destruct (f a); unfold orv in *; simpl; auto.\nQed.\n\nLemma exists_array_spec : forall gen_f (f: val -> bool) s0 m0,\n  (forall (Q: memory -> stack -> Prop),\n  HT cblock table gen_f\n     (fun m s => exists x i0 i1 i2 i3,\n                   stk_env s [x; i0; i1; i2; i3] s0 /\\\n                   m = m0 /\\\n                   forall s',\n                     stk_env s' [boolToVal (f x); i0; i1; i2; i3] s0 ->\n                     Q m s')\n     Q) ->\n  forall (Q: memory -> stack -> Prop),\n  HT cblock table (exists_array gen_f)\n     (fun m s => exists a vs,\n                      memarr m a vs /\\\n                      Mem.stamp a = Kernel /\\\n                      stk_env s [Vptr (a, 0)] s0 /\\\n                      m = m0 /\\\n                      forall s',\n                        stk_env s' [boolToVal (existsb f vs)] s0 ->\n                        Q m s')\n     Q.\nProof.\n  intros.\n  unfold exists_array.\n  eapply HT_strengthen_premise.\n  { eapply fold_array_spec with\n           (n:= boolToVal false)\n           (f:= fun x v => orv (boolToVal (f x)) v); eauto.\n    - clear Q. intros Q.\n      eapply HT_strengthen_premise. eapply genFalse_spec.\n      intros m s (i0 & (? & ?) & ? & POST).\n      subst s.\n      apply POST.\n      do 2 eexists. reflexivity.\n    - clear Q. intro Q.\n      eapply HT_compose_flip; try eapply genOr_spec; eauto.\n      eapply HT_strengthen_premise.\n      eapply H.\n      intros m s (x & v & i0 & i1 & i2 & E & ? & POST).\n      do 5 eexists. split; eauto. split; eauto.\n      intros s' (? & ? & ? & ? & ? & ?). subst.\n      do 5 eexists. split; eauto.\n      intros.\n      eapply POST.\n      do 4 eexists. eauto. }\n\n  - unfold stk_env. split_vc.\n    rewrite <- boolToVal_existsb. eauto.\nQed.\n\n(* Forallb. *)\n\n(* Initial stack: a::S\n   Final stack: r::S\n        where gen_f assumes x::_::_::_::_::S and generates b::_::_::_::_::S with b the result of testing x\n        and r = boolean: gen_f answers true on all elements\n*)\n\nDefinition forall_array gen_f :=  (* a S *)\n      fold_array (                (* _ S *)\n                    genTrue       (* 1 _ S *)\n                 )                (* v _ S *)\n                 (                (* x v _ _ _ S *)\n                    gen_f         (* b v _ _ _ S *)\n                 ++ genAnd        (* b/\\v _ _ _ S *)\n                 )                (* v' _ _ _ S *)\n.\n\nLemma boolToVal_forallb : forall f xs, boolToVal (forallb f xs) =\n                                       fold_right (fun x v : val => andv (boolToVal (f x)) v) (Vint 1) xs.\nProof.\n  induction xs;  simpl; auto.\n  destruct (f a); unfold andv in *; simpl; auto.\nQed.\n\nLemma forall_array_spec : forall gen_f (f: val -> bool) s0 m0,\n  (forall (Q: memory -> stack -> Prop),\n  HT cblock table gen_f\n     (fun m s => exists x i0 i1 i2 i3,\n                   stk_env s [x; i0; i1; i2; i3] s0 /\\\n                   m = m0 /\\\n                   forall s',\n                     stk_env s' [boolToVal (f x); i0; i1; i2; i3] s0 ->\n                     Q m s')\n     Q) ->\n  forall (Q: memory -> stack -> Prop),\n  HT cblock table (forall_array gen_f)\n     (fun m s => exists a vs,\n                      memarr m a vs /\\\n                      Mem.stamp a = Kernel /\\\n                      stk_env s [Vptr (a, 0)] s0 /\\\n                      m = m0 /\\\n                      forall s',\n                        stk_env s' [boolToVal (forallb f vs)] s0 ->\n                        Q m s')\n     Q.\nProof.\n  intros.\n  unfold exists_array.\n  eapply HT_strengthen_premise.\n  { eapply fold_array_spec with\n           (n:= boolToVal true)\n           (f:= fun x v => andv (boolToVal (f x)) v); eauto.\n    - clear Q. intros Q.\n      eapply HT_strengthen_premise. eapply genFalse_spec.\n      intros m s (i0 & (? & ?) & ? & POST).\n      subst s.\n      apply POST.\n      do 2 eexists. reflexivity.\n    - clear Q. intro Q.\n      eapply HT_compose_flip; try eapply genAnd_spec; eauto.\n      eapply HT_strengthen_premise.\n      eapply H.\n      intros m s (x & v & i0 & i1 & i2 & E & ? & POST).\n      do 5 eexists. split; eauto. split; eauto.\n      intros s' (? & ? & ? & ? & ? & ?). subst.\n      do 5 eexists. split; eauto.\n      intros.\n      eapply POST.\n      do 4 eexists. eauto. }\n\n  - unfold stk_env. split_vc.\n    rewrite <- boolToVal_forallb. eauto.\nQed.\n\n(* In_array *)\n\n(* Initial stack:  a::x::_\n   Final stack:    r::_\n      where r = boolean: x is in array a. *)\n\nDefinition in_array :=           (* a x *)\n      exists_array (             (* y _ _ _ _ x *)\n                       [Dup 5]   (* x y _ _ _ _ x *)\n                   ++  genEq     (* x=y _ _ _ _ x *)\n                   )             (* r x *)\n   ++ [Swap 1]                   (* x r *)\n   ++ pop                        (* r *)\n.\n\nDefinition val_list_in_b (x: val) (xs:list val) : bool :=\n  existsb (fun x' => if EquivDec.equiv_dec x x' then true else false) xs.\n\nLemma in_array_spec : forall (Q: memory -> stack -> Prop),\n  HT cblock table\n    in_array\n    (fun m s => exists a vs x t1 t2 s0 m0,\n                  memarr m0 a vs /\\\n                  s = (Vptr (a, 0),t1):::(x,t2):::s0 /\\\n                  Mem.stamp a = Kernel /\\\n                  m = m0 /\\\n                  forall t,\n                    Q m0 ((boolToVal(val_list_in_b x vs),t):::s0))\n    Q.\nProof.\n  intros. unfold in_array.\n  eapply HT_forall_exists. intro a.\n  eapply HT_forall_exists. intro vs.\n  eapply HT_forall_exists. intro x.\n  eapply HT_forall_exists. intro t1.\n  eapply HT_forall_exists. intro t2.\n  eapply HT_forall_exists. intro s0.\n  eapply HT_forall_exists. intro m0.\n  eapply HT_strengthen_premise.\n  { eapply HT_compose; try eapply exists_array_spec with\n                         (f := fun y => if EquivDec.equiv_dec x y then true else false)\n                         (s0 := (x,t2):::s0).\n    { clear Q. intros Q.\n      eapply HT_strengthen_premise.\n      { eapply HT_compose; try eapply dup_spec.\n        eapply genEq_spec. }\n      intros m s (? & ? & ? & ? & ? & (? & ? & ? & ? & ? & ?) & ? & POST).\n      subst s. simpl.\n      eexists. split; eauto.\n      do 5 eexists. split; eauto.\n      eapply POST.\n      do 5 eexists.\n      unfold val_eq.\n      destruct (EquivDec.equiv_dec x x0); eauto. }\n\n    eapply HT_compose; try eapply swap_spec.\n    eapply pop_spec. }\n\n  intros m s (? & ? & ? & ? & POST). subst.\n  unfold stk_env.\n  split_vc.\nQed.\n\n(* Subset_arrays *)\n\n(* Initial stack:  a1::a2::_.\n   Final_stack:    r::_.\n      where r = boolean: all elements of a1 are in a2\n*)\nDefinition subset_arrays :=      (* a1 a2 *)\n    forall_array (               (* x1 _ _ _ _ a2 *)\n                    [Dup 5]      (* a2 x1 _ _ _ _ a2 *)\n                 ++ in_array     (* x1ina2 _ _ _ _ a2 *)\n                 )               (* r a2 *)\n ++ [Swap 1]                     (* a2 r *)\n ++ pop                          (* r *)\n.\n\n\nDefinition val_list_subset_b (xs1 xs2:list val) : bool :=\n  forallb (fun x1 => val_list_in_b x1 xs2) xs1.\n\nLemma subset_arrays_spec : forall (Q: memory -> stack -> Prop),\n  HT cblock table\n    subset_arrays\n    (fun m s => exists a1 a2 vs1 vs2 t1 t2 s0 m0,\n                  memarr m0 a1 vs1 /\\\n                  memarr m0 a2 vs2 /\\\n                  Mem.stamp a1 = Kernel /\\ Mem.stamp a2 = Kernel /\\\n                  s = (Vptr (a1, 0),t1):::(Vptr (a2, 0),t2):::s0 /\\\n                  m = m0 /\\\n                  forall t,\n                    Q m0 ((Vint (boolToZ(val_list_subset_b vs1 vs2)),t):::s0))\n    Q.\nProof.\n  intros. unfold subset_arrays.\n  eapply HT_forall_exists. intro a1.\n  eapply HT_forall_exists. intro a2.\n  eapply HT_forall_exists. intro vs1.\n  eapply HT_forall_exists. intro vs2.\n  eapply HT_forall_exists. intro t1.\n  eapply HT_forall_exists. intro t2.\n  eapply HT_forall_exists. intro s0.\n  eapply HT_forall_exists. intro m0.\n  eapply HT_fold_constant_premise. intro.\n  eapply HT_fold_constant_premise. intro.\n  eapply HT_fold_constant_premise. intro.\n  eapply HT_fold_constant_premise. intro.\n  eapply HT_strengthen_premise.\n  { eapply HT_compose; try eapply forall_array_spec with\n                           (f := fun y => val_list_in_b y vs2)\n                           (s0 := (Vptr (a2, 0), t2) ::: s0).\n    { clear Q. intros Q.\n      eapply HT_strengthen_premise.\n      { eapply HT_compose; try eapply dup_spec.\n        eapply in_array_spec. }\n      intros m s (x & ? & ? & ? & ? & (? & ? & ? & ? & ? & ?) & ? & POST).\n      subst s. simpl.\n      eexists. split; eauto.\n      do 7 eexists. split_vc.\n      eapply POST.\n      unfold stk_env.\n      split_vc. }\n    build_vc idtac. }\n  intros m s (? & ? & POST). subst.\n  unfold stk_env.\n  eexists a1. split_vc.\nQed.\n\n(* Extend array *)\n\n(* Initial stack:   a::x::_\n   Final stack:     r::_\n          where r is a fresh array containing the contents of a followed by x\n   Side effects: allocates and fills the fresh array *)\n\nDefinition extend_array :=   (* a x *)\n     [Dup 0]                 (* a a x *)\n  ++ [Load]                  (* l a x *)\n  ++ [Push 1]                (* 1 l a x *)\n  ++ [Add]                   (* l+1 a x *)\n  ++ alloc_array             (* r a x *)\n  ++ [Dup 1]                 (* a r a x *)\n  ++ [Load]                  (* l r a x *)\n  ++ copy                    (* 0 r a x *)\n  ++ pop                     (* r a x *)\n  ++ [Dup 0]                 (* r r a x *)\n  ++ [Swap 2]                (* a r r x *)\n  ++ [Load]                  (* l r r x *)\n  ++ [Push 1]                (* 1 l r r x *)\n  ++ [Add]                   (* l+1 r r x *)\n  ++ [Add]                   (* r+l+1 r x *)\n  ++ [Swap 1]                (* r r+l+1 x *)\n  ++ [Swap 2]                (* x r+l+1 r *)\n  ++ [Swap 1]                (* r+l+1 x r *)\n  ++ [Store]                 (* r *)\n.\n\n\nLemma extend_array_spec : forall (Q : memory -> stack -> Prop),\n  HT cblock table\n   extend_array\n   (fun m s => exists a vs x s0 t1 t2,\n                 s = (Vptr (a, 0),t1):::(x,t2):::s0 /\\\n                 memarr m a vs /\\\n                 Mem.stamp a = Kernel /\\\n                 (forall r m1 t,\n                    extends m m1 ->\n                    Mem.get_frame m r = None ->\n                    Mem.stamp r = Kernel ->\n                    memarr m1 r (vs++[x]) ->\n                    Q m1 ((Vptr (r, 0),t):::s0)))\n   Q.\n\nProof.\n  intros. unfold extend_array.\n\n  build_vc ltac:(try apply copy_spec; try apply alloc_array_spec). auto.\n\n  intros m ? (a & vs & x & s & t1 & t2 & ? & ARR & STAMPa & POST). subst.\n  destruct ARR. subst.\n  simpl.\n  eexists. split; eauto.\n  do 4 eexists.\n  do 3 (split; eauto).\n  do 6 eexists.\n  do 2 (split; try reflexivity).\n  do 3 eexists.\n  do 2 (split; try reflexivity; try lia).\n  intros b m' t' EXT VALID [t'' LOAD'] FRESH STAMPb.\n  assert (NEQab : a <> b).\n  { intros contra. subst. unfold load in LOAD. simpl in *.\n    destruct (Mem.get_frame m b); congruence. }\n  eexists. split; try reflexivity.\n  assert (LOAD'' := extends_load _ _ _ _ EXT LOAD).\n  do 4 eexists.\n  do 3 (split; eauto).\n  do 9 eexists.\n  split.\n  2: split; eauto. lia.\n  split.\n  { intros.\n    eapply extends_valid_address; eauto.\n    eapply memseq_valid; eauto. lia. }\n  split.\n  { intros. apply VALID. lia. }\n  split; try congruence.\n  do 2 (split; auto).\n  intros m'' t1' t2' t3' (COPY & EQLOAD & EQFRAME).\n  simpl in COPY.\n  assert (EQFRAME' : forall b' off, b' <> b -> load (b', off) m'' = load (b', off) m').\n  { unfold load.\n    intros.\n    rewrite EQFRAME; eauto. }\n  do 3 eexists.\n  split; eauto.\n  simpl.\n  eexists. split; eauto.\n  do 4 eexists. do 3 (split; eauto).\n  do 4 eexists.\n  do 3 (split; eauto).\n  { rewrite EQFRAME'; eauto. }\n  do 6 eexists. do 2 (split; try reflexivity).\n  do 6 eexists. do 2 (split; try reflexivity).\n  do 4 eexists. do 3 (split; eauto).\n  do 4 eexists. do 3 (split; eauto).\n  do 4 eexists. do 3 (split; eauto).\n  assert (STORE : valid_address (b,1 + Z.of_nat (length vs) + 0) m'').\n  { unfold valid_address.\n    rewrite EQLOAD; try lia.\n    apply VALID. lia. }\n  eapply valid_store in STORE. destruct STORE as [m''' STORE].\n  do 5 eexists. split; [|split; eauto]; eauto.\n  split; eauto.\n  apply POST; eauto.\n  - intros b' fr' FRAME.\n    assert (b' <> b) by congruence.\n    erewrite (get_frame_store_neq _ _ _ _ _ _ _ _ STORE); eauto.\n    rewrite EQFRAME; eauto.\n  - econstructor; eauto.\n    + erewrite load_store_old; eauto.\n      * rewrite EQLOAD; try lia.\n        rewrite LOAD'.\n        repeat f_equal.\n        rewrite app_length.\n        simpl (length [x]).\n        zify. ring.\n      * intros contra.\n        assert (0 = 1 + Z.of_nat (length vs) + 0) by congruence.\n        lia.\n    + apply memseq_app with (vs1 := vs) (vs2 := [x]).\n      split.\n      * eapply memseq_eq with (m1 := m); eauto.\n        intros z RANGE.\n        { rewrite (load_store_old STORE); eauto.\n          - rewrite <- COPY; try lia.\n            rewrite EQFRAME'; try congruence.\n            unfold load in LOAD.\n            unfold load. simpl in *.\n            destruct (Mem.get_frame m a) as [fr|] eqn:FRAME; try congruence.\n            apply EXT in FRAME.\n            rewrite FRAME.\n            reflexivity.\n          - intros contra.\n            assert (1 + z = 1 + Z.of_nat (length vs) + 0) by congruence.\n            lia. }\n      * econstructor; try solve [constructor].\n        replace (1 + Z.of_nat (length vs) + 0) with (1 + Z.of_nat (length vs)) in STORE by ring.\n        erewrite load_store_new; eauto.\nQed.\n\nEnd with_hints.\n\nEnd with_cblock.\n", "meta": {"author": "micro-policies", "repo": "verified-ifc", "sha": "1ce5075b3a5580679feddb718d274d89fc7dd77f", "save_path": "github-repos/coq/micro-policies-verified-ifc", "path": "github-repos/coq/micro-policies-verified-ifc/verified-ifc-1ce5075b3a5580679feddb718d274d89fc7dd77f/extended_machines/Arrays.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2449800509836695}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import malloc2.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\nOpen Scope logic.  (* this should not be necessary *)\n\nDefinition HEAPSIZE := proj1_sig (opaque_constant 1000).\nDefinition HEAPSIZE_eq : HEAPSIZE = 1000 := proj2_sig (opaque_constant _).\nHint Rewrite HEAPSIZE_eq : rep_lia.\n\nDefinition tcell := Tunion _cell noattr.\n\nDefinition idT := ltac:(\n   let x := constr:(fn_return f_T_alloc) in\n   let x := eval simpl in x in\n   match x with tptr (Tstruct ?i _) => exact i end).\n\nDefinition tT := Tstruct idT noattr.\n\nFixpoint freelistrep (n: nat) (x: val) : mpred :=\n match n with\n | S n' => \n    EX y:val, \n      data_at Ews tcell (inr y) x  *  freelistrep n' y\n | O => \n    !! (x = nullval) && emp\n end.\n\nArguments freelistrep n x : simpl never.\n\n(** Whenever you define a new spatial operator, such as\n ** [listrep] here, it's useful to populate two hint databases.\n ** The [saturate_local] hint is a lemma that extracts\n ** pure propositional facts from a spatial fact.\n ** The [valid_pointer] hint is a lemma that extracts a\n ** valid-pointer fact from a spatial lemma.\n **)\n\nLemma freelistrep_local_facts:\n  forall n p,\n   freelistrep n p |--\n   !! (is_pointer_or_null p /\\ (p=nullval <-> n=O)).\nProof.\nintros.\nrevert p; induction n; intros; unfold freelistrep; fold freelistrep; simpl.\n- entailer!. intuition.\n- Intros y. entailer!.\nsplit; intro. subst p. destruct H; contradiction. inv H2.\nQed.\n\nHint Resolve freelistrep_local_facts : saturate_local.\n\nLemma freelistrep_valid_pointer:\n  forall n p,\n   freelistrep n p |-- valid_pointer p.\nProof.\n destruct n; unfold freelistrep; fold freelistrep;\n intros; normalize.\n auto with valid_pointer.\n apply sepcon_valid_pointer1.\n apply data_at_valid_ptr; auto.\n simpl;  computable.\nQed.\n\nHint Resolve freelistrep_valid_pointer : valid_pointer.\n\nDefinition mem_mgr (k: Z) (gv: globals) :=\n EX r:Z, EX n: nat, EX p: val, \n   !! (0 <= r <= HEAPSIZE /\\ k = (HEAPSIZE-r)+(Z.of_nat n)\n       /\\ field_compatible (tarray tcell HEAPSIZE) nil (gv _heap)) &&\n   data_at Ews (tptr tcell) p (gv _first_free) *\n   freelistrep n p *\n   data_at Ews (tptr tcell) \n           (field_address0 (tarray tcell HEAPSIZE) [ArraySubsc r] (gv _heap))\n           (gv _limit) *\n   data_at_ Ews (tarray tcell (HEAPSIZE-r)) \n       (field_address0 (tarray tcell HEAPSIZE) [ArraySubsc r] (gv _heap)).\n\nDefinition T_alloc_token (p: val) : mpred :=\n  !! (field_compatible tcell [] p) && data_at_ Ews tT p -* data_at_ Ews tcell p.\n\nDefinition T_alloc_spec :=\n   DECLARE _T_alloc\n   WITH k: Z, gv: globals\n   PRE [ ]\n       PROP ()\n       PARAMS() GLOBALS(gv)\n       SEP (mem_mgr k gv)\n    POST [ tptr tT ] EX p:val,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (if zlt 0 k\n             then (mem_mgr (k-1) gv * data_at_ Ews tT p * T_alloc_token p)\n             else (!!(p=nullval) &&  mem_mgr k gv)).\n\nDefinition T_free_spec :=\n   DECLARE _T_free\n   WITH p: val, k: Z, gv: globals\n   PRE [ tptr tT ]\n       PROP ()\n       PARAMS (p) GLOBALS (gv)\n       SEP (data_at_ Ews tT p; T_alloc_token p; mem_mgr k gv)\n    POST [ tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (mem_mgr (k+1) gv).\n\nDefinition vstrcpy_spec :=\n   DECLARE _vstrcpy\n   WITH bl: list byte, d: val, shd: share, n: Z, s: val, shs: share\n   PRE [ tptr tschar, tptr tschar ]\n     PROP(writable_share shd; readable_share shs; Zlength bl < n)\n     PARAMS(d;s) GLOBALS()\n     SEP(data_at_ shd (tarray tschar n) d; cstring shs bl s)\n   POST [ tvoid ]\n     PROP() LOCAL() SEP(cstringn shd bl n d; cstring shs bl s).\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre prog tt gv\n  POST [ tint ]  \n     PROP() \n     LOCAL (temp ret_temp (Vint (Int.repr 0)))\n     SEP(TT).\n\nDefinition Gprog : funspecs :=\n         [T_alloc_spec; T_free_spec; vstrcpy_spec; main_spec].\n\nLemma init_mem_mgr:\n forall (gv: globals),\ndata_at Ews tuint (Vint (Int.repr 0)) (gv _first_free) *\n   data_at Ews (tptr (Tunion _cell noattr))\n     (offset_val 0 (gv _heap)) (gv _limit) * \n   data_at_ Ews (tarray (Tunion _cell noattr) 1000) (gv _heap) |--\n mem_mgr 1000 gv.\nProof.\nintros.\nunfold mem_mgr.\nrewrite <- HEAPSIZE_eq.\nExists 0 O nullval.\nunfold freelistrep.\nentailer!.\nrewrite <- data_at_nullptr.\nchange size_t with tuint.\nunfold field_address0.\nrewrite if_true.\n2:{ \n apply field_compatible0_ArraySubsc0.\n auto with field_compatible.\n split; auto; simpl; rep_lia.\n}\nsimpl.\nnormalize.\ncancel.\nQed.\n\nLtac strip_int_repr L :=\n match L with\n | Int.repr ?a :: ?L' => let bl := strip_int_repr L' in \n                                 let cl := constr:(a::bl) in\n                                 cl\n | nil => constr:(@nil Z)\n end.\n\nLtac process_stringlit :=\n match goal with\n | |- context [data_at Ers (tarray tschar ?n)\n    (map (Vint oo cast_int_int I8 Signed) ?L) (_ ?id)] =>\n    let bl := strip_int_repr L in\n   let v := fresh id \"_val\" in\n   pose (v := map Vbyte (map Byte.repr bl));\n    change (map (Vint oo cast_int_int I8 Signed) L)\n     with v\n  end.\n\nLemma data_at__tT_eq:\n  forall p sh,\n  field_compatible tT nil p ->\n   data_at_ sh tT p = data_at_ sh (tarray tschar 42) p.\nProof.\nintros.\nrewrite data_at__memory_block.\nrewrite data_at__memory_block.\nrewrite !prop_true_andp; auto.\ndestruct H as [? [? [? [? ?]]]].\nsplit3; auto.\nsplit3; auto.\ndestruct p; try contradiction.\nred.\napply align_compatible_rec_Tarray.\nintros.\neapply align_compatible_rec_by_value; [reflexivity | ].\napply Z.divide_1_l.\nQed.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nsep_apply init_mem_mgr.\nrepeat process_stringlit.\nforward_call (1000, gv).\nif_tac; try lia.\nIntros p.\nassert_PROP (field_compatible tT nil p) by entailer!.\nforward_call (map Byte.repr [102; 111; 111], p, Ews, 42, \n                    gv ___stringlit_1, Ers).\nrewrite data_at__tT_eq by auto.\nunfold cstring.\nrewrite prop_true_andp.\ncancel.\nclear; intro.\ncompute in H.\ndecompose [or] H; try discriminate; auto. \nrepeat apply seq_assoc1.\nmatch goal with |- semax _ ?pre _ _ =>\n apply semax_seq' with pre\nend.\nadmit.  (* printf *)\nforward_call (p, 1000-1, gv).\nunfold cstringn.\nIntros.\nrewrite data_at__tT_eq by auto.\ncancel.\nforward.\nAdmitted.\n\nLemma field_at_union_convert: \n  (* shouldn't need this if unfold_data_at worked correctly *)\n  forall q p, \n    field_at Ews (Tunion _cell noattr) [UnionField _next_free] q p\n           |-- data_at Ews (tptr tcell) q p.\nProof.\n intros.\n entailer!.\n unfold field_at.\n Intros. simpl. unfold at_offset. normalize.\n unfold data_at, field_at, at_offset; simpl.\n normalize. fold tcell.\n apply andp_right; auto.\n apply prop_right.\n destruct H as [? [? [? [? ?]]]].\n split3; auto. split3; simpl; auto.\n destruct p; try contradiction.\n simpl in H2|-*. lia.\n destruct p; try contradiction.\n red. red in H3.\n eapply align_compatible_rec_Tunion_inv' in H3.\n instantiate (1:= _next_free) in H3.\n simpl field_type in H3.\n eapply align_compatible_rec_by_value_inv in H3; [ | reflexivity].\n eapply align_compatible_rec_by_value; [reflexivity | ].\n auto.\n compute; auto.\nQed.\n\nLemma fold_alloc_token: forall p,\n data_at_ Ews tcell p |-- data_at_ Ews tT p * T_alloc_token p.\nProof.\nintros.\n unfold T_alloc_token.\n rewrite data_at__memory_block.\n Intros.\n rewrite !prop_true_andp by auto.\n change (sizeof tcell) with (sizeof tT + (sizeof tcell - sizeof tT)).\n make_Vptr p.\n rewrite <- (Ptrofs.repr_unsigned i) in *.\n rewrite memory_block_split.\n 2,3: compute; congruence.\n 2:{  simpl. destruct H as [_ [? [? _]]].\n red in H0. rewrite Ptrofs.repr_unsigned in H0. simpl in H0. rep_lia. }\n apply sepcon_derives.\n -\n  rewrite data_at__memory_block.\n  rewrite prop_true_andp; auto.\n destruct H as [? [? [? [? ?]]]].\n split3; auto. split3; auto.\n simpl in H1|-*. lia.\n unfold tT. \n eapply align_compatible_rec_Tstruct.\n simpl. reflexivity.\n intros.\n simpl in H4.\n if_tac in H4; [ | inv H4].\n subst i0.\n inv H5. inv H4.\n apply align_compatible_rec_Tarray. intros.\n eapply align_compatible_rec_by_value; [reflexivity |].\n apply Z.divide_1_l.\n-\n apply wand_sepcon_adjoint.\n cancel.\n rewrite data_at__memory_block.\n Intros. auto.\nQed.\n\nLemma body_T_alloc: semax_body Vprog Gprog f_T_alloc T_alloc_spec.\nProof.\nstart_function.\nunfold mem_mgr.\nIntros r n p.\nforward.\nforward_if (\n   EX q:val, PROP ( ) LOCAL (temp _ptr q)\n         SEP (if zlt 0 k\n              then mem_mgr (k - 1) gv * data_at_ Ews tT q * T_alloc_token q\n              else !! (q = nullval) && mem_mgr k gv)).\n-\ndestruct n; unfold freelistrep; fold freelistrep.\n+\nIntros. subst. contradiction.\n+\nIntros q.\nassert_PROP (field_compatible tcell nil p) as FCcell by entailer!.\nunfold tcell.\nunfold_data_at (data_at Ews (Tunion _ _) _ _).\nforward.\nforward.\nforward.\nExists p.\nentailer!.\nrewrite if_true by (rewrite inj_S; lia).\nunfold mem_mgr.\nExists r n q.\nentailer!.\neapply derives_trans; [ | apply fold_alloc_token].\nsep_apply field_at_union_convert.\nunfold spacer.\nrewrite if_false by computable.\nunfold at_offset.\nsep_apply data_at_data_at_.\nrewrite data_at__memory_block.\nIntros.\nrewrite data_at__memory_block.\nrewrite prop_true_andp by auto.\nchange (sizeof tcell) with (4+(44-4)).\nmake_Vptr p.\n rewrite <- (Ptrofs.repr_unsigned i) in *.\nrewrite memory_block_split.\n simpl sizeof. simpl Z.sub.\n unfold offset_val.\n rewrite ptrofs_add_repr.\n cancel.\n computable.\n computable.\n simpl.\n clear - FCcell.\n destruct FCcell as [_ [_ [? _]]].\n simpl in H.\n rewrite Ptrofs.repr_unsigned in H. \n rep_lia.\n-\n forward.\n forward_if.\n +\n set (A := (_ * freelistrep _ _)%logic). clearbody A.\n clear - H.\n unfold field_address0.\n if_tac.\n 2: entailer!; destruct H3; contradiction.\n simpl.\n make_Vptr (gv _heap).\n simpl.\n unfold test_order_ptrs.\n simpl.\n destruct (peq b b); [ | contradiction n; auto].\n simpl.\n clear e.\n rewrite data_at__memory_block. Intros.\n apply andp_right; apply sepcon_weak_valid_pointer2.\n eapply derives_trans.\n apply memory_block_weak_valid_pointer with (i:=0).\n simpl. rewrite Z.max_r by lia. lia.\n simpl. rewrite Z.max_r by lia.\n admit.\n auto. normalize.\n \n eapply derives_trans.\n apply memory_block_weak_valid_pointer with (i:=(44 * (HEAPSIZE-r))%Z).\n simpl. rewrite Z.max_r by lia. lia.\n simpl. rewrite Z.max_r by lia.\n admit.\n auto.\n simpl.\n normalize.\n apply derives_refl'. f_equal. f_equal. f_equal. f_equal.\n rewrite HEAPSIZE_eq. lia. \n +\n  forward.\n  Exists (Vint (Int.repr 0)).\n  entailer!.\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "cverified", "repo": "cbench-vst", "sha": "b3119729b39c4f5439dee78c633a9d2e3257df41", "save_path": "github-repos/coq/cverified-cbench-vst", "path": "github-repos/coq/cverified-cbench-vst/cbench-vst-b3119729b39c4f5439dee78c633a9d2e3257df41/malloc/verif_malloc2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.24498004492533795}}
{"text": "Require Export FcEtt.tactics.\nRequire Export FcEtt.ett_inf.\n\nRequire Import FcEtt.utils.\nRequire Import FcEtt.imports.\n\nRequire Import FcEtt.ett_ind.\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Implicit Arguments.\n\n\n(* --------------------------------------------------------------------------- *)\n\nHint Resolve AnnCtx_uniq.\nHint Unfold AtomSetImpl.Subset.\n\nLtac solve_binds :=\n  match goal with\n    | [ b : binds ?v _ ?G\n      , H : forall v' _, binds v' _ ?G -> _ [<=] dom ?G ∧ _ [<=] dom ?G\n      |- _ ] =>\n      apply H in b; simpl in b; split_hyp; (done || fsetdec)\n  end.\n\nTheorem ann_context_fv_mutual :\n  (forall G (a : tm) A (H: AnnTyping G a A),\n      fv_tm_tm_tm a [<=] dom G /\\ fv_co_co_tm a [<=] dom G /\\\n      fv_tm_tm_tm A [<=] dom G /\\ fv_co_co_tm A [<=] dom G)\n  /\\\n  (forall G phi (H : AnnPropWff G phi),\n      fv_tm_tm_constraint phi [<=] dom G /\\ fv_co_co_constraint phi [<=] dom G)\n  /\\\n  (forall G D g p1 p2 (H : AnnIso G D g p1 p2),\n      fv_tm_tm_co         g  [<=] dom G /\\ fv_co_co_co         g  [<=] dom G /\\\n      fv_tm_tm_constraint p1 [<=] dom G /\\ fv_co_co_constraint p1 [<=] dom G /\\\n      fv_tm_tm_constraint p2 [<=] dom G /\\ fv_co_co_constraint p2 [<=] dom G)\n  /\\\n  (forall G D g A B (H : AnnDefEq G D g A B),\n      fv_tm_tm_co g [<=] dom G /\\ fv_co_co_co g [<=] dom G /\\\n      fv_tm_tm_tm A [<=] dom G /\\ fv_co_co_tm A [<=] dom G /\\\n      fv_tm_tm_tm B [<=] dom G /\\ fv_co_co_tm B [<=] dom G)\n  /\\\n  (forall G (H : AnnCtx G),\n      (forall x A,\n          binds x (Tm A)   G ->\n          fv_tm_tm_tm         A   [<=] dom G /\\ fv_co_co_tm         A   [<=] dom G) /\\\n      (forall c phi,\n          binds c (Co phi) G ->\n          fv_tm_tm_constraint phi [<=] dom G /\\ fv_co_co_constraint phi [<=] dom G)).\n\nProof.\n  eapply ann_typing_wff_iso_defeq_mutual.\n  all: autounfold.\n  (* We can't just use `repeat split` because we don't want to split under foralls *)\n  all: intros; repeat match goal with |- _ ∧ _ => split end; split_hyp; simpl.\n  all: eauto 1.\n  (* split all asummptions about unions *)\n\n  (* Do the cases about the context at the end. *)\n  all: try (intros x0 A0 BI).\n  all: try solve [inversion BI].\n  all: try (match goal with |- _ ∧ _ => split end).\n  all: try solve\n  [intros y h1; inversion BI; [inversion H5; subst; clear H5; eauto|\n                               destruct (H x0 _ H5); eauto]].\n  all: try solve\n  [intros y h1; inversion BI; [inversion H5; subst; clear H5; eauto|\n                              destruct (H4 x0 _ H5); eauto]].\n  all: try solve\n  [intros y h1; inversion BI; [inversion H3; subst; clear H3; eauto|\n                              destruct (H x0 _ H3); eauto]].\n  all: try solve\n  [intros y h1; inversion BI; [inversion H3; subst; clear H3; eauto|\n                               destruct (H2 x0 _ H3); eauto]].\n\n  (* rest of the cases *)\n  all: intros y IN.\n\n  (* more splitting, assumption has a union type *)\n  all: try match goal with\n    [ H7 : ?y `in` union ?A ?B |- _ ] =>\n    apply F.union_iff in H7; destruct H7; eauto end.\n\n  all: try solve [ apply notin_empty_1 in IN; contradiction].\n  all: try solve [ assert (x = y) by fsetdec; subst; eapply binds_In; eauto ].\n  all: try solve [ destruct (H _ _ b); eauto ].\n\n  all: try solve [apply H1; eauto; simpl; auto].\n  all: try solve [apply H2; eauto; simpl; auto].\n  all: try solve [apply H3; eauto; simpl; auto].\n  all: try solve [apply H4; eauto; simpl; auto].\n\n\n  all: try match goal with\n    [ H5 : forall x : atom, (x `in` ?L -> False) -> ( _ /\\ _ ) |- _ ] =>\n    pick fresh x; destruct (H5 x); eauto; split_hyp\n           end.\n\n  all: try match goal with\n    [ H4 : ?y `in` fv_tm_tm_tm ?B,\n      H5 : ∀ a : atom,\n       a `in` fv_tm_tm_tm (open_tm_wrt_tm ?B (a_Var_f ?x))\n            → a `in` dom ([(?x, ?s)] ++ ?G) |- _ ] =>\n    assert (h0: y `in` dom ([(x,s)] ++ G)) by\n    (eapply H5; auto;\n    eapply fv_tm_tm_tm_open_tm_wrt_tm_lower; auto);\n      simpl in h0; apply F.add_neq_iff in h0; auto\n           end.\n  all: try match goal with\n    [ H4 : ?y `in` fv_co_co_tm ?B,\n      H5 : ∀ a : atom,\n       a `in` fv_co_co_tm (open_tm_wrt_tm ?B (a_Var_f ?x))\n            → a `in` dom ([(?x, ?s)] ++ ?G) |- _ ] =>\n    assert (h0: y `in` dom ([(x,s)] ++ G)) by\n    (eapply H5; eauto;\n    eapply fv_co_co_tm_open_tm_wrt_tm_lower; auto);\n      simpl in h0; apply F.add_neq_iff in h0; auto\n           end.\n  all: try match goal with\n    [ H4 : ?y `in` fv_tm_tm_tm ?B,\n      H5 : ∀ a : atom,\n       a `in` fv_tm_tm_tm (open_tm_wrt_co ?B (g_Var_f ?x))\n            → a `in` dom ([(?x, ?s)] ++ ?G) |- _ ] =>\n    assert (h0: y `in` dom ([(x,s)] ++ G)) by\n    (eapply H5; eauto;\n    eapply fv_tm_tm_tm_open_tm_wrt_co_lower; auto);\n    simpl in h0; apply F.add_neq_iff in h0; auto\n           end.\n  all: try match goal with\n    [ H4 : ?y `in` fv_co_co_tm ?B,\n      H5 : ∀ a : atom,\n       a `in` fv_co_co_tm (open_tm_wrt_co ?B (g_Var_f ?x))\n            → a `in` dom ([(?x, ?s)] ++ ?G) |- _ ] =>\n    assert (h0: y `in` dom ([(x,s)] ++ G)) by\n    (eapply H5; eauto;\n    eapply fv_co_co_tm_open_tm_wrt_co_lower; auto);\n      simpl in h0; apply F.add_neq_iff in h0; auto\n           end.\n\n  all: try (simpl in *; eapply fv_tm_tm_tm_open_tm_wrt_tm_upper in IN;\n    apply F.union_iff in IN; destruct IN; eauto).\n  all: try (simpl in *; eapply fv_co_co_tm_open_tm_wrt_tm_upper in IN;\n    apply F.union_iff in IN; destruct IN; eauto).\n  all: try (simpl in *; eapply fv_tm_tm_tm_open_tm_wrt_co_upper in IN;\n    apply F.union_iff in IN; destruct IN; eauto).\n  all: try (simpl in *; eapply fv_co_co_tm_open_tm_wrt_co_upper in IN;\n    apply F.union_iff in IN; destruct IN; eauto).\n\n  all: try (apply H0 in IN; apply notin_empty_1 in IN; contradiction).\n  all: try (apply H1 in IN; apply notin_empty_1 in IN; contradiction).\n\n  all: try match goal with\n    [ H7 : ?y `in` union ?A ?B |- _ ] =>\n    apply F.union_iff in H7; destruct H7; eauto end.\n\n  all: try solve [apply H1; eauto; simpl; auto].\n  all: try solve [apply H2; eauto; simpl; auto].\n  all: try solve [apply H3; eauto; simpl; auto].\n  all: try solve [apply H4; eauto; simpl; auto].\n  all: try solve [apply H5; eauto; simpl; auto].\n\n  all: try match goal with\n    [IN : ?y `in` singleton ?c |- _ ] =>\n                assert (c = y) by fsetdec; subst; eapply binds_In; eauto\n     end.\n  all: try solve [ destruct (H0 _ _ b0); simpl in *; eauto].\n\n  all: try  match goal with\n    [ H4 : ?y `in` fv_tm_tm_co ?B,\n      H5 : ∀ a : atom,\n       a `in` fv_tm_tm_co (open_co_wrt_tm ?B (a_Var_f ?x))\n            → a `in` dom ([(?x, ?s)] ++ ?G) |- _ ] =>\n    assert (h0: y `in` dom ([(x,s)] ++ G)) by\n    (eapply H5; eauto;\n    eapply fv_tm_tm_co_open_co_wrt_tm_lower; auto);\n      simpl in h0; apply F.add_neq_iff in h0; auto\n           end.\n\n  all: try match goal with\n    [ H4 : ?y `in` fv_co_co_co ?B,\n      H5 : ∀ a : atom,\n       a `in` fv_co_co_co (open_co_wrt_tm ?B (a_Var_f ?x))\n            → a `in` dom ([(?x, ?s)] ++ ?G) |- _ ] =>\n    assert (h0: y `in` dom ([(x,s)] ++ G)) by\n    (eapply H5; eauto;\n    eapply fv_co_co_co_open_co_wrt_tm_lower; auto);\n      simpl in h0; apply F.add_neq_iff in h0; auto\n           end.\n\n  all: try match goal with\n    [ H4 : ?y `in` fv_tm_tm_co ?B,\n      H5 : ∀ a : atom,\n       a `in` fv_tm_tm_co (open_co_wrt_co ?B (g_Var_f ?x))\n            → a `in` dom ([(?x, ?s)] ++ ?G) |- _ ] =>\n    assert (h0: y `in` dom ([(x,s)] ++ G)) by\n    (eapply H5; eauto;\n    eapply fv_tm_tm_co_open_co_wrt_co_lower; auto);\n      simpl in h0; apply F.add_neq_iff in h0; auto\n           end.\n\n  all: try match goal with\n    [ H4 : ?y `in` fv_co_co_co ?B,\n      H5 : ∀ a : atom,\n       a `in` fv_co_co_co (open_co_wrt_co ?B (g_Var_f ?x))\n            → a `in` dom ([(?x, ?s)] ++ ?G) |- _ ] =>\n    assert (h0: y `in` dom ([(x,s)] ++ G)) by\n    (eapply H5; eauto;\n    eapply fv_co_co_co_open_co_wrt_co_lower; auto);\n      simpl in h0; apply F.add_neq_iff in h0; auto\n           end.\n\n\n  (* Eta cases *)\n\n  all: try match goal with \n      [ IN : ?y `in` ?fv_tm_tm_tm ?a, \n        H : ∀ a : atom, a `in` ?fv_tm_tm_tm ?b → a `in` dom ?G,\n        e : ∀ x : atom,\n            (x `in` ?L → False) → \n            ?open_tm_wrt_tm ?a (a_Var_f x) = ?c\n       |- _ ] => \n      eapply H; pick fresh x; move: (e x ltac:(auto)) => h0;\n      assert (x <> y); [ fsetdec|];\n      clear Fr;\n      have h1: y `in` fv_tm_tm_tm (open_tm_wrt_tm a (a_Var_f x));\n      [ move: (fv_tm_tm_tm_open_tm_wrt_tm_lower a (a_Var_f x)) => ?;\n        move: (fv_co_co_tm_open_tm_wrt_tm_lower a (a_Var_f x)) => ?;\n        fsetdec|\n      rewrite h0 in h1; \n      simpl in h1;\n      fsetdec ]\n    end.\n\n  all: try match goal with \n      [ IN : ?y `in` ?fv_tm_tm_tm ?a, \n        H : ∀ a : atom, a `in` ?fv_tm_tm_tm ?b → a `in` dom ?G,\n        e : ∀ x : atom,\n            (x `in` ?L → False) → \n            ?open_tm_wrt_tm ?a (g_Var_f x) = ?c\n       |- _ ] => \n      eapply H; pick fresh x; move: (e x ltac:(auto)) => h0;\n      assert (x <> y); [ fsetdec|];\n      clear Fr;\n      have h1: y `in` fv_tm_tm_tm (open_tm_wrt_tm a (g_Var_f x));\n      [ move: (fv_tm_tm_tm_open_tm_wrt_co_lower a (g_Var_f x)) => ?;\n        move: (fv_co_co_tm_open_tm_wrt_co_lower a (g_Var_f x)) => ?;\n        fsetdec|];\n      rewrite h0 in h1; \n      simpl in h1;\n      fsetdec\n    end.\n\n\n  (* last hard cases *)\n  - assert (FR1 : x `notin` L) by auto. assert (FR2 : x <> y) by auto.\n    clear Fr. clear H0. clear r. clear r0.\n    clear H19. clear H20. clear H22. clear H24.\n    clear H10 H12 H13 H7 H4 H9 H6.\n    move: (e x FR1) => EX.\n    match goal with\n      [H18 :  y `in` fv_tm_tm_tm b3 |- _ ] =>\n       erewrite fv_tm_tm_tm_open_tm_wrt_tm_lower  in H18;\n       erewrite EX in H18;\n       erewrite fv_tm_tm_tm_open_tm_wrt_tm_upper  in H18;\n       apply F.union_iff in H18; destruct H18 as [h2 | h3]\n       end.\n    simpl in h2.\n    apply F.union_iff in h2; destruct h2 as [h4 | h5].\n    fsetdec.\n    eauto.\n\n    assert (y `in` dom ((x ~ Tm A1) ++ G)). eapply H23.\n    eapply fv_tm_tm_tm_open_tm_wrt_tm_lower.  auto.\n    simpl in H0; apply F.add_neq_iff in H0; auto.\n  - assert (FR1 : x `notin` L) by auto. assert (FR2 : x <> y) by auto.\n    clear Fr. clear H0. clear r. clear r0.\n    move: (e x FR1) => EX.\n    match goal with\n      [H14 : y `in` fv_co_co_tm b3 |- _ ] =>\n      erewrite fv_co_co_tm_open_tm_wrt_tm_lower  in H14;\n        erewrite EX in H14;\n        erewrite fv_co_co_tm_open_tm_wrt_tm_upper  in H14;\n        apply F.union_iff in H14; destruct H14 as [h2 | h3]\n    end.\n    simpl in h2.\n    apply F.union_iff in h2; destruct h2 as [h4 | h5].\n    fsetdec.\n    eauto.\n\n    assert (y `in` dom ((x ~ Tm A1) ++ G)). eapply H24.\n    eapply fv_co_co_tm_open_tm_wrt_tm_lower.  auto.\n    simpl in H0; apply F.add_neq_iff in H0; auto.\nQed.\n\nDefinition AnnTyping_context_fv  := @first  _ _ _ _ _ ann_context_fv_mutual.\nDefinition AnnPropWff_context_fv := @second _ _ _ _ _ ann_context_fv_mutual.\nDefinition AnnIso_context_fv     := @third  _ _ _ _ _ ann_context_fv_mutual.\nDefinition AnnDefEq_context_fv   := @fourth _ _ _ _ _ ann_context_fv_mutual.\nDefinition AnnCtx_context_fv     := @fifth  _ _ _ _ _ ann_context_fv_mutual.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/corespec/src/FcEtt/fc_context_fv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.24498004492533795}}
{"text": "Require Import Omega.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\n\nSet Implicit Arguments.\n\n\nModule MemoryFacts.\n  Lemma promise_time_lt\n        promises1 mem1 loc from to val released promises2 mem2 kind\n        (PROMISE: Memory.promise promises1 mem1 loc from to val released promises2 mem2 kind):\n    Time.lt from to.\n  Proof.\n    inv PROMISE.\n    - inv MEM. inv ADD. auto.\n    - inv MEM. inv SPLIT. auto.\n    - inv MEM. inv LOWER. auto.\n  Qed.\n\n  Lemma write_time_lt\n        promises1 mem1 loc from to val released promises2 mem2 kind\n        (WRITE: Memory.write promises1 mem1 loc from to val released promises2 mem2 kind):\n    Time.lt from to.\n  Proof.\n    inv WRITE. eapply promise_time_lt. eauto.\n  Qed.\n\n  Lemma promise_get1_diff\n        promises1 mem1 loc from to val released promises2 mem2 kind\n        l t f v r\n        (PROMISE: Memory.promise promises1 mem1 loc from to val released promises2 mem2 kind)\n        (GET: Memory.get l t mem1 = Some (f, Message.mk v r))\n        (DIFF: (loc, to) <> (l, t)):\n    exists f', Memory.get l t mem2 = Some (f', Message.mk v r).\n  Proof.\n    inv PROMISE.\n    - erewrite Memory.add_o; eauto. condtac; ss.\n      + des. subst. congr.\n      + esplits; eauto.\n    - erewrite Memory.split_o; eauto. repeat condtac; ss.\n      + des. subst. congr.\n      + guardH o. des. subst.\n        exploit Memory.split_get0; eauto. i. des.\n        rewrite GET3 in GET. inv GET. esplits; eauto.\n      + esplits; eauto.\n    - erewrite Memory.lower_o; eauto. condtac; ss.\n      + des. subst. congr.\n      + esplits; eauto.\n  Qed.\n\n  Lemma promise_get_inv_diff\n        promises1 mem1 loc from to val released promises2 mem2 kind\n        l t f v r\n        (PROMISE: Memory.promise promises1 mem1 loc from to val released promises2 mem2 kind)\n        (GET: Memory.get l t mem2 = Some (f, Message.mk v r))\n        (DIFF: (loc, to) <> (l, t)):\n    exists f', Memory.get l t mem1 = Some (f', Message.mk v r).\n  Proof.\n    revert GET. inv PROMISE.\n    - erewrite Memory.add_o; eauto. condtac; ss.\n      + des. subst. congr.\n      + i. inv GET. esplits; eauto.\n    - erewrite Memory.split_o; eauto. repeat condtac; ss.\n      + des. subst. congr.\n      + guardH o. des. subst. i. inv GET.\n        exploit Memory.split_get0; try exact MEM; eauto. i. des. esplits; eauto.\n      + i. esplits; eauto.\n    - erewrite Memory.lower_o; eauto. condtac; ss.\n      + des. subst. congr.\n      + i. inv GET. esplits; eauto.\n  Qed.        \n\n  Lemma promise_get_promises_inv_diff\n        promises1 mem1 loc from to val released promises2 mem2 kind\n        l t f v r\n        (PROMISE: Memory.promise promises1 mem1 loc from to val released promises2 mem2 kind)\n        (GET: Memory.get l t promises2 = Some (f, Message.mk v r))\n        (DIFF: (loc, to) <> (l, t)):\n    exists f', Memory.get l t promises1 = Some (f', Message.mk v r).\n  Proof.\n    revert GET. inv PROMISE.\n    - erewrite Memory.add_o; eauto. condtac; ss.\n      + des. subst. congr.\n      + i. inv GET. esplits; eauto.\n    - erewrite Memory.split_o; eauto. repeat condtac; ss.\n      + des. subst. congr.\n      + guardH o. des. subst. i. inv GET.\n        exploit Memory.split_get0; try exact PROMISES; eauto. i. des. esplits; eauto.\n      + i. esplits; eauto.\n    - erewrite Memory.lower_o; eauto. condtac; ss.\n      + des. subst. congr.\n      + i. inv GET. esplits; eauto.\n  Qed.\n\n  Lemma remove_get_diff\n        promises0 mem0 loc from to val released promises1\n        l t\n        (LOC: loc <> l)\n        (LE: Memory.le promises0 mem0)\n        (REMOVE: Memory.remove promises0 loc from to val released promises1):\n    Memory.get l t promises1 = Memory.get l t promises0.\n  Proof.\n    erewrite Memory.remove_o; eauto. condtac; ss.\n    des. subst. congr.\n  Qed.\n\n  Lemma remove_cell_diff\n        promises0 loc from to val released promises1\n        l\n        (LOC: loc <> l)\n        (REMOVE: Memory.remove promises0 loc from to val released promises1):\n    promises1 l = promises0 l.\n  Proof.\n    apply Cell.ext. i. eapply remove_get_diff; eauto. refl.\n  Qed.\n\n  Lemma get_same_from_aux\n        l f t1 t2 m msg1 msg2\n        (GET1: Memory.get l t1 m = Some (f, msg1))\n        (GET2: Memory.get l t2 m = Some (f, msg2))\n        (LE: Time.le t1 t2)\n        (T1: t1 <> Time.bot):\n    t1 = t2 /\\ msg1 = msg2.\n  Proof.\n    inv LE; cycle 1.\n    { inv H. rewrite GET1 in GET2. inv GET2. ss. }\n    destruct (m l).(Cell.WF). exfalso.\n    assert (t1 <> t2).\n    { ii. subst. eapply Time.lt_strorder. eauto. }\n    eapply DISJOINT; try exact H0; eauto.\n    - apply Interval.mem_ub. exploit VOLUME; try exact GET1; eauto. i. des; ss.\n      inv x. congr.\n    - econs; ss.\n      + exploit VOLUME; try exact GET1; eauto. i. des; ss. inv x. congr.\n      + left. ss.\n  Qed.\n\n  Lemma get_same_from\n        l f t1 t2 m msg1 msg2\n        (GET1: Memory.get l t1 m = Some (f, msg1))\n        (GET2: Memory.get l t2 m = Some (f, msg2))\n        (T1: t1 <> Time.bot)\n        (T2: t2 <> Time.bot):\n    t1 = t2 /\\ msg1 = msg2.\n  Proof.\n    destruct (Time.le_lt_dec t1 t2).\n    - eapply get_same_from_aux; eauto.\n    - exploit get_same_from_aux; (try by left; eauto); eauto. i. des. ss.\n  Qed.\n\n  Lemma write_not_bot\n        pm1 mem1 loc from to val released pm2 mem2 kind\n        (WRITE: Memory.write pm1 mem1 loc from to val released pm2 mem2 kind):\n    to <> Time.bot.\n  Proof.\n    ii. subst. inv WRITE. inv PROMISE.\n    - inv MEM. inv ADD. inv TO.\n    - inv MEM. inv SPLIT. inv TS12.\n    - inv MEM. inv LOWER. inv TS0.\n  Qed.\n\n  Lemma write_add_promises\n        promises1 mem1 loc from to val released promises2 mem2\n        (WRITE: Memory.write promises1 mem1 loc from to val released promises2 mem2 Memory.op_kind_add):\n    promises2 = promises1.\n  Proof.\n    apply Memory.ext. i.\n    inv WRITE. inv PROMISE.\n    erewrite (@Memory.remove_o promises2); eauto. condtac; ss.\n    - des. subst. symmetry. eapply Memory.add_get0. eauto.\n    - guardH o. erewrite (@Memory.add_o promises0); eauto. condtac; ss.\n  Qed.\n\n  Lemma promise_exists_None\n        promises1 mem1 loc from to val released\n        (LE: Memory.le promises1 mem1)\n        (GET: Memory.get loc to promises1 = Some (from, Message.mk val released))\n        (LT: Time.lt from to):\n    exists promises2 mem2,\n      Memory.promise promises1 mem1 loc from to val None promises2 mem2 (Memory.op_kind_lower released).\n  Proof.\n    exploit Memory.lower_exists; eauto; try by econs. i. des.\n    exploit LE; eauto. i.\n    exploit Memory.lower_exists; eauto; try by econs. i. des.\n    esplits. econs; eauto. apply Time.bot_spec.\n  Qed.\n\n  Lemma some_released_time_lt\n  mem loc from to val released\n  (CLOSED: Memory.closed mem)\n  (GET: Memory.get loc to mem = Some (from, Message.mk val (Some released))):\n    Time.lt from to.\n  Proof.\n    destruct (mem loc).(Cell.WF). exploit VOLUME; eauto. i. des; ss. inv x.\n    inv CLOSED. rewrite INHABITED in GET. inv GET.\n  Qed.\nEnd MemoryFacts.\n", "meta": {"author": "snu-sf", "repo": "promising-coq", "sha": "bff53239c51681ea653745cebf3b30ddd38f97ba", "save_path": "github-repos/coq/snu-sf-promising-coq", "path": "github-repos/coq/snu-sf-promising-coq/promising-coq-bff53239c51681ea653745cebf3b30ddd38f97ba/src/lang/MemoryFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24498004492533793}}
{"text": "Require Import Rules Channel DataTypes MsiState ChannelAxiomHelp.\n\nModule mkLatestValueAxioms (ch: ChannelPerAddr mkDataTypes).\n  Import mkDataTypes ch.\n\n  Theorem toChild: forall {n a t p m},\n                     defined n -> defined p ->\n                     parent n p -> \n                     mark mch p n a t m -> from m = MsiState.In -> dataM m = data p a t.\n  Proof.\n    intros n a t p m defn defp n_p markm fromm.\n    unfold mark in *; unfold data in *. unfold mkDataTypes.mark in *.\n    destruct (trans oneBeh t).\n    firstorder.\n    firstorder.\n    destruct markm as [[_ [_ [use _]]] _]; discriminate.\n    destruct markm as [[use0 [_ [_ [_ [_ [use1 [use2 _]]]]]]] use3];\n    rewrite <- use1 in *; rewrite use3 in *; rewrite use0 in *; assumption.\n    firstorder.\n    destruct markm as [[_ [_ [use _]]] _]; discriminate.\n    destruct markm as [[use3 [use0 _]] _];\n    rewrite use3 in *; rewrite use0 in *; pose proof (noCycle n_p p1); firstorder.\n    firstorder.\n    destruct markm as [[use3 [use0 _]] _];\n    rewrite use3 in *; rewrite use0 in *; pose proof (noCycle n_p p1); firstorder.\n    firstorder.\n  Qed.\n\n  Theorem fromParent: forall {n a t p m}, defined n -> defined p ->\n                      parent n p -> \n                      recv mch p n a t m -> from m = MsiState.In -> data n a (S t) = dataM m.\n  Proof.\n    intros n a t p m defn defp n_p recvm fromm.\n    unfold recv in *; unfold data; unfold mkDataTypes.recv in *.\n    destruct (trans oneBeh t).\n    firstorder.\n    firstorder.\n    firstorder.\n    destruct recvm as [[use1 [use2 _]] _];\n    rewrite use1 in *; rewrite use2 in *; pose proof (noCycle n_p p1); firstorder.\n    simpl;\n    assert (eq: m0 = List.last (ch (sys oneBeh t) mch p0 c) dmy) by auto;\n      assert (eq2: a0 = addrB m0) by auto;\n    destruct recvm as [[use1 [use2 [_ [use3 [_ [use4 [use5 _]]]]]]] use0]; rewrite <- eq in *;\n    rewrite use1 in *; rewrite use2 in *;\n    rewrite use3 in *; rewrite use4 in *; rewrite use0 in *; rewrite eq2 in *; rewrite fromm in *; rewrite use5 in *;\n    destruct (decTree n n); destruct (decAddr a a); firstorder.\n    firstorder.\n    assert (e2: r = List.last (ch (sys oneBeh t) mch p0 c) dmy) by auto.\n    rewrite <- e2 in recvm.\n    rewrite e in *.\n    destruct recvm as [[_ [_ [use _]]] _]; discriminate. \n    destruct recvm as [[use1 [use2 _]] _];\n    rewrite use1 in *; rewrite use2 in *; pose proof (noCycle n_p p1); firstorder.\n    firstorder.\n    assert (e2: r = List.last (ch (sys oneBeh t) mch p0 c) dmy) by auto.\n    rewrite <- e2 in recvm.\n    rewrite e in *.\n    destruct recvm as [[_ [_ [use _]]] _]; discriminate. \n  Qed.\n\n  Theorem toParent: forall {n a t c m},\n                      defined n -> defined c ->\n                      parent c n ->\n                      mark mch c n a t m -> slt Sh (from m) -> dataM m = data c a t.\n  Proof.\n    intros n a t c m defn defc c_n markm isM.\n    assert (fromm: from m = Mo) by (unfold slt; destruct (from m); firstorder); clear isM.\n    unfold mark in *; unfold data in *. unfold mkDataTypes.mark in *.\n    destruct (trans oneBeh t).\n    firstorder.\n    firstorder.\n    destruct markm as [[_ [_ [use _]]] _]; discriminate.\n    destruct markm as [[use0 [_ [_ [_ [_ [use1 [use2 _]]]]]]] use3];\n    rewrite <- use1 in *; rewrite use3 in *; rewrite use0 in *; assumption.\n    firstorder.\n    destruct markm as [[_ [_ [use _]]] _]; discriminate.\n    destruct markm as [[use0 [_ [_ [_ [_ [use1 [use2 _]]]]]]] use3];\n    rewrite <- use1 in *; rewrite use3 in *; rewrite use0 in *; assumption.\n    firstorder.\n    destruct markm as [[use0 [_ [_ [_ [_ [use1 [use2 _]]]]]]] use3];\n    rewrite <- use1 in *; rewrite use3 in *; rewrite use0 in *; assumption.\n    firstorder.\n  Qed.\n\n  Theorem fromChild: forall {n a t c m},\n                       defined n -> defined c ->\n                       parent c n ->\n                       recv mch c n a t m -> slt Sh (from m) -> data n a (S t) = dataM m.\n  Proof.\n    intros n a t c m defn defc c_n recvm isM.\n    assert (fromm: from m = Mo) by (unfold slt; destruct (from m); firstorder); clear isM.\n    unfold recv in *; unfold data in *. unfold mkDataTypes.recv in *.\n    destruct (trans oneBeh t).\n    firstorder.\n    firstorder.\n    firstorder.\n    pose proof (enqC2P p0 n0) as contra.\n    rewrite contra in recvm.\n    destruct recvm as [[_ [_ [use _]]] _]; discriminate.\n    destruct recvm as [[use1 [use2 _]] _];\n    rewrite use1 in *; rewrite use2 in *; pose proof (noCycle c_n p0); firstorder.\n    firstorder.\n    assert (re: r = List.last (ch (sys oneBeh t) mch p c0) dmy) by auto.\n    rewrite re in e.\n    rewrite e in recvm.\n    destruct recvm as [[_ [_ [use _]]] _]; discriminate.\n    simpl;\n    assert (eq: m0 = List.last (ch (sys oneBeh t) mch c0 p) dmy) by auto;\n      assert (eq2: a0 = addrB m0) by auto;\n    destruct recvm as [[use1 [use2 [_ [use3 [_ [use4 [use5 _]]]]]]] use0]; rewrite <- eq in *;\n    rewrite use1 in *; rewrite use2 in *;\n    rewrite use3 in *; rewrite use4 in *; rewrite use0 in *; rewrite eq2 in *; rewrite fromm in *; rewrite use5 in *;\n    destruct (decTree n n); destruct (decAddr a a); firstorder.\n    firstorder.\n    assert (re: r = List.last (ch (sys oneBeh t) mch p c0) dmy) by auto.\n    rewrite re in e.\n    rewrite e in recvm.\n    destruct recvm as [[_ [_ [use _]]] _]; discriminate.\n  Qed.\n\n  Theorem initLatest: forall a, data hier a 0 = initData a /\\ state hier a 0 = Mo.\n  Proof.\n    intros a.\n    unfold data; unfold state.\n    pose proof (init oneBeh) as initi.\n    rewrite initi.\n    unfold initGlobalState.\n    simpl.\n    destruct (decTree hier hier) as [eq |neq].\n    constructor; firstorder.\n    firstorder.\n  Qed.\n\n  Theorem deqImpData: forall {a n t i}, defined n -> deqR a n i t -> desc (reqFn a n i) = St ->\n                                          data n a (S t) = dataQ (reqFn a n i).\n  Proof.\n    intros a n t i defn deqr isSt.\n    unfold deqR in *; unfold data.\n    destruct (trans oneBeh t).\n    destruct deqr as [e1 [eq reqI]].\n    rewrite <- e1, eq in *.\n    rewrite reqI in e.\n    rewrite e in isSt.\n    discriminate.\n    simpl.\n    destruct deqr as [e1 [seq reqi]].\n    destruct (decTree n c) as [eq | neq].\n    rewrite e1, seq in *.\n    rewrite reqi in *.\n    destruct (decAddr a a).\n    reflexivity.\n    firstorder.\n    assert (n = c) by auto; firstorder.\n    firstorder.\n    firstorder.\n    firstorder.\n    firstorder.\n    firstorder.\n    firstorder.\n    firstorder.\n    firstorder.\n  Qed.\n\n  Theorem changeData:\n    forall {n a t}, defined n ->\n                    data n a (S t) <> data n a t ->\n                    (exists m, (exists p, defined p /\\ parent n p /\\ recv mch p n a t m /\\ from m = MsiState.In) \\/\n                               (exists c, defined c /\\ parent c n /\\ recv mch c n a t m /\\\n                                          slt Sh (from m))) \\/\n                    exists i, deqR a n i t /\\ desc (reqFn a n i) = St.\n  Proof.\n    intros n a t defn dtNeq.\n    unfold data in *; unfold recv in *; unfold deqR in *; unfold mkDataTypes.recv in *.\n    destruct (trans oneBeh t).\n\n    simpl in *. firstorder.\n\n    simpl in *.\n    right.\n    destruct (decTree n c).\n    destruct (decAddr a a0).\n    rewrite e1, e2 in *.\n    exists (req (sys oneBeh t) a c).\n    firstorder; auto.\n    rewrite e2 in *.\n    firstorder.\n    rewrite e2 in *.\n    firstorder.\n\n    simpl in *.\n    firstorder.\n\n    simpl in *.\n    firstorder.\n\n    simpl in *.\n    firstorder.\n\n    simpl in *.\n    firstorder.\n\n    simpl in *.\n    left.\n    exists (Build_Mesg (fromB m) (toB m) (addrB m) (dataBM m) (List.last (labelCh t mch p c) 0)).\n    simpl.\n    left.\n    exists p.\n    assert (sth: m = List.last (ch (sys oneBeh t) mch p c) dmy) by auto.\n    rewrite <- sth in *.\n    destruct (decTree n c) as [nEq | nNeq].\n    rewrite <- nEq in *.\n    destruct (decAddr a a0) as [aEq | aNeq].\n    destruct (fromB m); intuition.\n    firstorder.\n    firstorder.\n\n    simpl in *; firstorder.\n    simpl in *; firstorder.\n\n    simpl in *.\n    left.\n    exists (Build_Mesg (fromB m) (toB m) (addrB m) (dataBM m) (List.last (labelCh t mch c p) 0)).\n    simpl.\n    right.\n    exists c.\n    assert (sth: m = List.last (ch (sys oneBeh t) mch c p) dmy) by auto.\n    rewrite <- sth in *.\n    destruct (decTree n p) as [nEq | nNeq].\n    rewrite <- nEq in *.\n    destruct (decAddr a a0) as [aEq | aNeq].\n    pose proof (enqC2P p0 n0) as sth2.\n    rewrite <- sth in sth2.\n    rewrite sth2.\n    destruct (fromB m); intuition.\n    firstorder.\n    firstorder.\n\n    simpl in *; firstorder.\n    simpl in *; firstorder.\n  Qed.\n\n  Theorem deqImpNoSend: forall {c a i t},\n                          defined c -> deqR a c i t ->\n                          forall {m p}, defined p -> ~ mark mch c p a t m.\n  Proof.\n    unfold not; intros c a i t defc deqr m p defp markm.\n    unfold deqR in *; unfold mark in *; unfold mkDataTypes.mark in *.\n\n    destruct (trans oneBeh t); firstorder.\n  Qed.\nEnd mkLatestValueAxioms.\n", "meta": {"author": "vmurali", "repo": "CacheProofBetter", "sha": "e00bb4a4f1677c69969797c25ab9ef4bb8a213a0", "save_path": "github-repos/coq/vmurali-CacheProofBetter", "path": "github-repos/coq/vmurali-CacheProofBetter/CacheProofBetter-e00bb4a4f1677c69969797c25ab9ef4bb8a213a0/LatestValueAxioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24498003886700628}}
{"text": "\nRequire Export Iron.Language.SystemF2Store.Store.\nRequire Export Iron.Language.SystemF2Store.StepContext.\nRequire Export Iron.Language.SystemF2Store.TyJudge.\nRequire Export Iron.Language.SystemF2Store.SubstExpExp.\nRequire Export Iron.Language.SystemF2Store.Exp.\n\n(********************************************************************)\n(** * Single Small Step Evaluation *)\n(** The single step rules model the individual transitions that the \n     machine can make at runtime. *)\n\nInductive STEP : store -> exp -> store -> exp -> Prop :=\n\n (* Step some sub-expression in an evaluation context *)\n | EsContext \n   :  forall C s x s' x'\n   ,  exp_ctx C\n   -> STEP s x      s' x'\n   -> STEP s (C x)  s' (C x')\n\n | EsLamApp\n   : forall s t11 x12 v2\n   ,  wnfX v2\n   -> STEP s (XApp   (XLam t11 x12) v2)\n           s (substXX 0 v2 x12)\n\n (* Type application *)\n | EsLAMAPP\n   :  forall s x12 t2      \n   ,  STEP s (XAPP (XLAM x12) t2)\n           s (substTX 0 t2 x12)\n\n (* Allocate a new data object in the store *)\n | EsAlloc\n   :  forall s dc tsParam xs svs\n   ,  Forall2 svalueOf xs svs\n   -> STEP s                      (XCon dc tsParam xs)\n           (snoc (SObj dc svs) s) (XLoc (length s))\n\n (* Case branching reads data objects from the store *)\n | EsCaseAlt\n   :  forall s dc svs vs alts x l\n   ,  get l s        = Some (SObj dc svs)\n   -> getAlt dc alts = Some (AAlt dc x)\n   -> Forall2 svalueOf vs svs\n   -> STEP s (XCase (XLoc l) alts)\n           s (substXXs 0 vs x)\n\n (* If an update operator matches the data constructor in the heap then\n    update the appropriate field. *)\n | EsUpdate \n   :  forall l s dc cn i tsParam svs vField svField\n   ,  get l s =  Some (SObj dc svs)\n   -> dc      =  cn\n   -> svalueOf vField svField\n   -> STEP s\n           (XUpdate cn i tsParam (XLoc l) vField)\n           (replace l (SObj dc (replace i svField svs)) s)\n           xUnit\n\n (* If an update operator does not match the data constructor in the heap\n    then just return unit. *)\n | EsUpdateSkip\n   :  forall l s dc cn i tsParam svs vField\n   ,  get l s =  Some (SObj dc svs)\n   -> ~(dc    = cn)\n   -> STEP s (XUpdate cn i tsParam (XLoc l) vField)\n           s xUnit.\n\nHint Constructors STEP.\n\n\n(* Multi-step evaluation\n   A sequence of small step transitions.\n   As opposed to STEPSL, this version has an append constructor\n   ESAppend that makes it easy to join two evaluations together.\n   We use this when converting big-step evaluations to small-step. *)\nInductive STEPS : store -> exp -> store -> exp -> Prop :=\n\n (* After no steps, we get the same exp.\n    We need this constructor to match the EVDone constructor\n    in the big-step evaluation, so we can convert between big-step\n    and multi-step evaluations. *)\n | EsNone\n   :  forall s1 x1\n   ,  STEPS s1 x1 s1 x1\n\n (* Take a single step. *)\n | EsStep\n   :  forall s1 x1 s2 x2\n   ,  STEP  s1 x1 s2 x2\n   -> STEPS s1 x1 s2 x2\n\n (* Combine two evaluations into a third. *)\n | EsAppend\n   :  forall s1 x1 s2 x2 s3 x3\n   ,  STEPS s1 x1 s2 x2 -> STEPS s2 x2 s3 x3\n   -> STEPS s1 x1 s3 x3.\n\nHint Constructors STEPS.\n\n\n(* Stepping a wnf doesn't change it. *)\nLemma step_wnfX\n :  forall x v s1 s2\n ,  wnfX x -> STEP s1 x s2 v -> v = x.\nProof.\n intros x v s1 s2 HW HS.\n induction HS; nope.\n  destruct H; auto; nope.\nQed.\n\n\n(* If we have a list context we can step some expression \n   applied to a data constructor *)\nLemma step_context_XCon_exists\n :  forall  C x dc ts s1 s2\n ,  exps_ctx wnfX C \n -> (exists x', STEP s1 x s2 x')\n -> (exists x', STEP s1 (XCon dc ts (C x)) s2 (XCon dc ts (C x'))).\nProof.\n intros C x dc ts s1 s2 HC HS.\n shift x'.\n eapply (EsContext (fun xx => XCon dc ts (C xx))); auto.\nQed.\n\n\n(* Multi-step evaluating a wnf doesn't change it. *)\nLemma steps_wnfX \n :  forall x v s1 s2\n ,  wnfX x -> STEPS s1 x s2 v -> v = x.\nProof.\n intros x v s1 s2 HW HS.\n induction HS; auto.\n  Case \"EsStep\".\n   eapply step_wnfX; eauto.\n  \n  Case \"EsAppend\".\n   have (x2 = x1).\n   subst. auto.\nQed.\n\n\n(* Multi-step evaluation in a context. *)\nLemma steps_context\n :  forall C s1 x1 s2 x1'\n ,  exp_ctx C\n -> STEPS s1 x1     s2 x1'\n -> STEPS s1 (C x1) s2 (C x1').\nProof.\n intros C s1 x1 s2 x1' HC HS.\n induction HS; eauto.\nQed.\n\n\n(* Multi-step evaluation of a data constructor argument. *)\nLemma steps_context_XCon\n :  forall C s1 x s2 v dc ts\n ,  exps_ctx wnfX C\n -> STEPS s1 x s2 v\n -> STEPS s1 (XCon dc ts (C x)) s2 (XCon dc ts (C v)).\nProof.\n intros C s1 x s2 v dc ts HC HS.\n induction HS; auto.\n\n Case \"XCon\".\n  lets D: EsContext XcCon; eauto. \n  eauto.\nQed.\n\n(* TODO: First premise doesn't work because each xs uses a different store\nLemma steps_in_XCon\n :  forall xs ts vs dc\n ,  Forall2 STEPS xs vs\n -> Forall wnfX vs\n -> STEPS (XCon dc ts xs) (XCon dc ts vs).\nProof.\n intros xs ts vs dc HS HW.\n lets HC: make_chain HS HW.\n  eapply steps_wnfX.\n\n clear HS. clear HW.\n induction HC; auto.\n  eapply (EsAppend (XCon dc ts (C x)) (XCon dc ts (C v))); auto.\n  eapply steps_context_XCon; auto.\nQed.\n*)\n\n(********************************************************************)\n(* Left linearised multi-step evaluation\n   As opposed to STEPS, this version provides a single step at a time\n   and does not have an append constructor. This is convenient\n   when converting a small-step evaluations to big-step, via the\n   eval_expansion lemma. *)\nInductive STEPSL : store -> exp -> store -> exp -> Prop :=\n | EslNone \n   : forall s1 x1\n   , STEPSL s1 x1 s1 x1\n\n | EslCons\n   :  forall s1 x1 s2 x2 s3 x3\n   ,  STEP   s1 x1 s2 x2 -> STEPSL s2 x2 s3 x3 \n   -> STEPSL s1 x1 s3 x3.\n\nHint Constructors STEPSL.\n\n\n(* Transitivity of left linearised multi-step evaluation.\n   We use this when \"flattening\" a big step evaluation to the\n   small step one. *)\nLemma stepsl_trans\n :  forall s1 x1 s2 x2 s3 x3\n ,  STEPSL s1 x1 s2 x2 -> STEPSL s2 x2 s3 x3\n -> STEPSL s1 x1 s3 x3.\nProof.\n intros s1 x1 s2 x2 s3 x3 H1 H2.\n induction H1; eauto.\nQed.\n\n\n(* Linearise a regular multi-step evaluation.\n   This flattens out all the append constructors, leaving us with\n   a list of individual transitions. *)\nLemma stepsl_of_steps\n :  forall s1 x1 s2 x2\n ,  STEPS  s1 x1 s2 x2\n -> STEPSL s1 x1 s2 x2.\nProof. \n intros s1 x1 s2 x2 HS.\n induction HS; \n  eauto using stepsl_trans.\nQed.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/SystemF2Store/Step.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24489644129620294}}
{"text": "Require Import Bool List String Peano_dec Lia.\nRequire Import Common FMap IndexSupport HVector Syntax Topology Semantics SemFacts StepM.\nRequire Import Invariant TrsInv Simulation Serial SerialFacts.\nRequire Import RqRsLang RqRsInvMsg RqRsCorrect.\n\nRequire Import Ex.Spec Ex.SpecInds Ex.Template.\nRequire Import Ex.Mesi Ex.Mesi.Mesi Ex.Mesi.MesiTopo.\n\nRequire Import Ex.Mesi.MesiInv.\n\nSet Implicit Arguments.\n\nImport PropMonadNotations.\nImport CaseNotations.\n\nLocal Open Scope list.\nLocal Open Scope hvec.\nLocal Open Scope fmap.\n\n#[global] Existing Instance Mesi.ImplOStateIfc.\n\nDefinition InvL1DirI (cifc: CIfc) (st: State): Prop :=\n  Forall (fun oidx =>\n            ost <+- (st_oss st)@[oidx];\n              ost#[dir].(dir_st) = mesiI)\n         (c_l1_indices cifc).\n\nSection InvL1DirI.\n  Variable (tr: tree).\n  Hypothesis (Htr: tr <> Node nil).\n\n  Let topo: DTree := fst (tree2Topo tr 0).\n  Let cifc: CIfc := snd (tree2Topo tr 0).\n  Let impl: System := impl Htr.\n\n  Lemma mesi_InvL1DirI_init:\n    Invariant.InvInit impl (InvL1DirI cifc).\n  Proof.\n    do 2 (red; simpl); intros.\n    apply Forall_forall; intros oidx ?.\n    destruct (implOStatesInit tr)@[oidx] as [ost|] eqn:Host; simpl; auto.\n    rewrite implOStatesInit_value_non_root in Host;\n      [|assumption|apply in_or_app; auto].\n    inv Host.\n    reflexivity.\n  Qed.\n\n  Lemma mesi_InvL1DirI_step:\n    Invariant.InvStep impl step_m (InvL1DirI cifc).\n  Proof. (* SKIP_PROOF_ON\n    red; intros.\n    inv H1; [assumption..|].\n    simpl in H2; destruct H2; [subst|apply in_app_or in H1; destruct H1].\n\n    - (*! Cases for the main memory *)\n      red; simpl.\n      apply Forall_forall; intros oidx ?.\n      red in H0; simpl in H0.\n      rewrite Forall_forall in H0; specialize (H0 _ H1).\n      mred.\n\n      exfalso.\n      eapply tree2Topo_root_not_in_l1; eauto.\n\n    - (*! Cases for Li caches *)\n      apply in_map_iff in H1; destruct H1 as [oidx [? ?]]; subst; simpl in *.\n\n      apply Forall_forall; intros roidx ?; simpl.\n      red in H0; simpl in H0.\n      rewrite Forall_forall in H0; specialize (H0 _ H1).\n      mred.\n\n      exfalso.\n      pose proof (tree2Topo_WfCIfc tr 0) as [? _].\n      apply (DisjList_NoDup idx_dec) in H4.\n      apply tl_In in H2.\n      eapply DisjList_In_1; eassumption.\n\n    - (*! Cases for L1 caches *)\n      apply in_map_iff in H1; destruct H1 as [oidx [? ?]]; subst.\n\n      apply Forall_forall; intros roidx ?; simpl.\n      red in H0; simpl in H0.\n      rewrite Forall_forall in H0; specialize (H0 _ H1).\n      mred; clear H1; simpl.\n      simpl in H5; rewrite H5 in H0; simpl in H0.\n\n      (** Do case analysis per a rule. *)\n      dest_in.\n      all: disc_rule_conds_ex. (* takes 10 seconds *)\n\n      END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Theorem mesi_InvL1DirI_ok:\n    InvReachable impl step_m (InvL1DirI cifc).\n  Proof.\n    eapply inv_reachable.\n    - typeclasses eauto.\n    - apply mesi_InvL1DirI_init.\n    - apply mesi_InvL1DirI_step.\n  Qed.\n\nEnd InvL1DirI.\n\nDefinition ObjWBDir (oidx: IdxT) (ost: OState) (msgs: MessagePool Msg) :=\n  (ObjInvWRq oidx msgs \\/ ObjInvRq oidx msgs \\/ ObjInvRs oidx msgs) ->\n  ost#[dir].(dir_st) = mesiI.\n\nDefinition InvWBDir (st: State): Prop :=\n  forall oidx,\n    ost <+- (st_oss st)@[oidx]; ObjWBDir oidx ost (st_msgs st).\n\n(** NOTE: [InvWBCoh] requires [InvWBDir] during the proof *)\nDefinition InvWBCoh (st: State): Prop :=\n  forall oidx,\n    ost <+- (st_oss st)@[oidx];\n      CohInvRq oidx ost (st_msgs st).\n\nSection InvWBDir.\n  Variable (tr: tree).\n  Hypothesis (Htr: tr <> Node nil).\n\n  Let topo: DTree := fst (tree2Topo tr 0).\n  Let cifc: CIfc := snd (tree2Topo tr 0).\n  Let impl: System := impl Htr.\n\n  Lemma mesi_InvWBDir_init:\n    Invariant.InvInit impl InvWBDir.\n  Proof.\n    do 2 (red; simpl).\n    intros.\n    destruct (implOStatesInit tr)@[oidx] as [orq|] eqn:Host; simpl; auto.\n    red; intros.\n    exfalso; destruct H as [|[|]].\n    - destruct H as [idm [? ?]].\n      do 2 red in H; dest_in.\n    - destruct H as [idm [? ?]].\n      do 2 red in H; dest_in.\n    - destruct H as [idm [? ?]].\n      do 2 red in H; dest_in.\n  Qed.\n\n  Lemma mesi_InvWBDir_ext_in:\n    forall oss orqs msgs,\n      InvWBDir {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n      InObjInds tr 0 {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n      forall eins,\n        ValidMsgsExtIn impl eins ->\n        InvWBDir {| st_oss := oss; st_orqs := orqs; st_msgs := enqMsgs eins msgs |}.\n  Proof.\n    red; simpl; intros.\n    specialize (H oidx); simpl in H.\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros.\n    destruct H2 as [|[|]].\n    - destruct H2 as [idm [? ?]].\n      apply InMP_enqMsgs_or in H2.\n      destruct H2; [|apply H; left; do 2 red; eauto].\n      apply in_map with (f:= idOf) in H2; simpl in H2.\n      apply H1 in H2; simpl in H2.\n      exfalso; eapply DisjList_In_1.\n      + apply tree2Topo_minds_merqs_disj.\n      + eassumption.\n      + eapply tree2Topo_obj_chns_minds_SubList.\n        * specialize (H0 oidx); simpl in H0.\n          rewrite Host in H0; simpl in H0.\n          eassumption.\n        * destruct idm as [midx msg]; inv H3.\n          simpl; tauto.\n    - destruct H2 as [idm [? ?]].\n      apply InMP_enqMsgs_or in H2.\n      destruct H2; [|apply H; right; left; do 2 red; eauto].\n      apply in_map with (f:= idOf) in H2; simpl in H2.\n      apply H1 in H2; simpl in H2.\n      exfalso; eapply DisjList_In_1.\n      + apply tree2Topo_minds_merqs_disj.\n      + eassumption.\n      + eapply tree2Topo_obj_chns_minds_SubList.\n        * specialize (H0 oidx); simpl in H0.\n          rewrite Host in H0; simpl in H0.\n          eassumption.\n        * destruct idm as [midx msg]; inv H3.\n          simpl; tauto.\n    - destruct H2 as [idm [? ?]].\n      apply InMP_enqMsgs_or in H2.\n      destruct H2; [|apply H; right; right; do 2 red; eauto].\n      apply in_map with (f:= idOf) in H2; simpl in H2.\n      apply H1 in H2; simpl in H2.\n      exfalso; eapply DisjList_In_1.\n      + apply tree2Topo_minds_merqs_disj.\n      + eassumption.\n      + eapply tree2Topo_obj_chns_minds_SubList.\n        * specialize (H0 oidx); simpl in H0.\n          rewrite Host in H0; simpl in H0.\n          eassumption.\n        * destruct idm as [midx msg]; inv H3.\n          simpl; tauto.\n  Qed.\n\n  Lemma mesi_InvWBDir_ext_out:\n    forall oss orqs msgs,\n      InvWBDir {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n      InObjInds tr 0 {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n      forall (eouts: list (Id Msg)),\n        InvWBDir {| st_oss := oss;\n                    st_orqs := orqs;\n                    st_msgs := deqMsgs (idsOf eouts) msgs |}.\n  Proof.\n    red; simpl; intros.\n    specialize (H oidx); simpl in H.\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros.\n    destruct H1 as [|[|]].\n    - destruct H1 as [idm [? ?]].\n      apply InMP_deqMsgs in H1.\n      apply H; left; do 2 red; eauto.\n    - destruct H1 as [idm [? ?]].\n      apply InMP_deqMsgs in H1.\n      apply H; right; left; do 2 red; eauto.\n    - destruct H1 as [idm [? ?]].\n      apply InMP_deqMsgs in H1.\n      apply H; right; right; do 2 red; eauto.\n  Qed.\n\n  Lemma InvWBDir_no_update:\n    forall oss orqs msgs,\n      InvWBDir {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall oidx (post nost: OState),\n        oss@[oidx] = Some post ->\n        nost#[dir].(dir_st) = post#[dir].(dir_st) ->\n        InvWBDir {| st_oss:= oss +[oidx <- nost];\n                    st_orqs:= orqs; st_msgs:= msgs |}.\n  Proof.\n    unfold InvWBDir; simpl; intros.\n    mred; simpl; auto.\n    specialize (H oidx).\n    rewrite H0 in H; simpl in H.\n    red; intros.\n    simpl; rewrite H1; auto.\n  Qed.\n\n  Lemma InvWBDir_update_status_NoRqI_NoRsI:\n    forall oss orqs msgs,\n      InvWBDir {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall oidx (ost: OState),\n        NoRqI oidx msgs ->\n        NoRsI oidx msgs ->\n        InvWBDir {| st_oss:= oss +[oidx <- ost];\n                    st_orqs:= orqs; st_msgs:= msgs |}.\n  Proof.\n    unfold InvWBDir; simpl; intros.\n    mred; simpl; auto.\n    red; intros.\n    exfalso; destruct H2 as [|[|]].\n    - eapply MsgExistsSig_MsgsNotExist_false; [apply H0| |eassumption].\n      simpl; tauto.\n    - eapply MsgExistsSig_MsgsNotExist_false; [apply H0| |eassumption].\n      simpl; tauto.\n    - eapply MsgExistsSig_MsgsNotExist_false; [apply H1| |eassumption].\n      simpl; tauto.\n  Qed.\n\n  Lemma InvWBDir_enqMP_rq_valid:\n    forall oss orqs msgs,\n      InvWBDir {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall oidx ost midx msg,\n        oss@[oidx] = Some ost ->\n        ost#[dir].(dir_st) = mesiI ->\n        midx = rqUpFrom oidx ->\n        msg.(msg_id) = mesiInvWRq \\/ msg.(msg_id) = mesiInvRq ->\n        InvWBDir {| st_oss:= oss; st_orqs:= orqs;\n                    st_msgs:= enqMP midx msg msgs |}.\n  Proof.\n    unfold InvWBDir; simpl; intros.\n    destruct (idx_dec oidx0 oidx); subst.\n    - specialize (H oidx).\n      rewrite H0 in *; simpl in *.\n      red; intros; auto.\n    - specialize (H oidx0).\n      destruct (oss@[oidx0]) as [ost0|]; simpl in *; auto.\n      red; intros.\n      destruct H2 as [|[|]].\n      + destruct H2 as [idm [? ?]].\n        apply InMP_enqMP_or in H2; destruct H2.\n        * dest; inv H4; rewrite H2 in H7; inv H7.\n          exfalso; auto.\n        * apply H; left; do 2 red; eauto.\n      + destruct H2 as [idm [? ?]].\n        apply InMP_enqMP_or in H2; destruct H2.\n        * dest; inv H4; rewrite H2 in H7; inv H7.\n          exfalso; auto.\n        * apply H; right; left; do 2 red; eauto.\n      + destruct H2 as [idm [? ?]].\n        apply InMP_enqMP_or in H2; destruct H2.\n        * dest; inv H4; rewrite H2 in H7; inv H7.\n        * apply H; right; right; do 2 red; eauto.\n  Qed.\n\n  Lemma InvWBDir_enqMP_rs_valid:\n    forall oss orqs msgs,\n      InvWBDir {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall oidx rqm midx msg,\n        FirstMP msgs (rqUpFrom oidx) rqm ->\n        (rqm.(msg_id) = mesiInvWRq \\/ rqm.(msg_id) = mesiInvRq) ->\n        rqm.(msg_type) = MRq ->\n        midx = downTo oidx ->\n        InvWBDir {| st_oss:= oss; st_orqs:= orqs;\n                    st_msgs:= enqMP midx msg (deqMP (rqUpFrom oidx) msgs) |}.\n  Proof.\n    unfold InvWBDir; simpl; intros.\n    destruct (idx_dec oidx0 oidx); subst.\n    - specialize (H oidx).\n      destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n      red; intros; apply H.\n      destruct H1.\n      + left; do 2 red.\n        exists (rqUpFrom oidx, rqm); split.\n        * apply FirstMP_InMP; assumption.\n        * unfold sigOf; simpl.\n          rewrite H1, H2; reflexivity.\n      + right; left; do 2 red.\n        exists (rqUpFrom oidx, rqm); split.\n        * apply FirstMP_InMP; assumption.\n        * unfold sigOf; simpl.\n          rewrite H1, H2; reflexivity.\n    - specialize (H oidx0).\n      destruct (oss@[oidx0]) as [ost0|]; simpl in *; auto.\n      red; intros.\n      destruct H3 as [|[|]].\n      + destruct H3 as [idm [? ?]].\n        apply InMP_enqMP_or in H3; destruct H3.\n        * dest; inv H4; rewrite H3 in H7; inv H7.\n        * apply InMP_deqMP in H3.\n          apply H; left; do 2 red; eauto.\n      + destruct H3 as [idm [? ?]].\n        apply InMP_enqMP_or in H3; destruct H3.\n        * dest; inv H4; rewrite H3 in H7; inv H7.\n        * apply InMP_deqMP in H3.\n          apply H; right; left; do 2 red; eauto.\n      + destruct H3 as [idm [? ?]].\n        apply InMP_enqMP_or in H3; destruct H3.\n        * dest; inv H4; rewrite H3 in H7; inv H7.\n          exfalso; auto.\n        * apply InMP_deqMP in H3.\n          apply H; right; right; do 2 red; eauto.\n  Qed.\n\n  Lemma InvWBDir_other_msg_id_enqMP:\n    forall oss orqs msgs,\n      InvWBDir {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall midx msg,\n        msg.(msg_id) <> mesiInvWRq ->\n        msg.(msg_id) <> mesiInvRq ->\n        msg.(msg_id) <> mesiInvRs ->\n        InvWBDir {| st_oss:= oss; st_orqs:= orqs;\n                    st_msgs:= enqMP midx msg msgs |}.\n  Proof.\n    unfold InvWBDir; simpl; intros.\n    specialize (H oidx).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros.\n    destruct H3 as [|[|]].\n    - destruct H3 as [idm [? ?]].\n      apply InMP_enqMP_or in H3; destruct H3.\n      + dest; subst; inv H4; exfalso; auto.\n      + apply H; left; do 2 red; eauto.\n    - destruct H3 as [idm [? ?]].\n      apply InMP_enqMP_or in H3; destruct H3.\n      + dest; subst; inv H4; exfalso; auto.\n      + apply H; right; left; do 2 red; eauto.\n    - destruct H3 as [idm [? ?]].\n      apply InMP_enqMP_or in H3; destruct H3.\n      + dest; subst; inv H4; exfalso; auto.\n      + apply H; right; right; do 2 red; eauto.\n  Qed.\n\n  Lemma InvWBDir_other_msg_id_enqMsgs:\n    forall oss orqs msgs,\n      InvWBDir {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall nmsgs,\n        Forall (fun idm => (valOf idm).(msg_id) <> mesiInvWRq /\\\n                           (valOf idm).(msg_id) <> mesiInvRq /\\\n                           (valOf idm).(msg_id) <> mesiInvRs) nmsgs ->\n        InvWBDir {| st_oss:= oss; st_orqs:= orqs;\n                    st_msgs:= enqMsgs nmsgs msgs |}.\n  Proof.\n    intros.\n    generalize dependent msgs.\n    induction nmsgs as [|[nmidx nmsg] nmsgs]; simpl; intros; auto.\n    inv H0; dest.\n    apply IHnmsgs; auto.\n    apply InvWBDir_other_msg_id_enqMP; assumption.\n  Qed.\n\n  Lemma InvWBDir_deqMP:\n    forall oss orqs msgs,\n      InvWBDir {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall midx,\n        InvWBDir {| st_oss:= oss; st_orqs:= orqs;\n                    st_msgs:= deqMP midx msgs |}.\n  Proof.\n    unfold InvWBDir; simpl; intros.\n    specialize (H oidx).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros.\n    destruct H0 as [|[|]].\n    - destruct H0 as [idm [? ?]].\n      apply InMP_deqMP in H0.\n      apply H; left; do 2 red; eauto.\n    - destruct H0 as [idm [? ?]].\n      apply InMP_deqMP in H0.\n      apply H; right; left; do 2 red; eauto.\n    - destruct H0 as [idm [? ?]].\n      apply InMP_deqMP in H0.\n      apply H; right; right; do 2 red; eauto.\n  Qed.\n\n  Lemma InvWBDir_deqMsgs:\n    forall oss orqs msgs,\n      InvWBDir {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall minds,\n        InvWBDir {| st_oss:= oss; st_orqs:= orqs;\n                    st_msgs:= deqMsgs minds msgs |}.\n  Proof.\n    unfold InvWBDir; simpl; intros.\n    specialize (H oidx).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros.\n    destruct H0 as [|[|]].\n    - destruct H0 as [idm [? ?]].\n      apply InMP_deqMsgs in H0.\n      apply H; left; do 2 red; eauto.\n    - destruct H0 as [idm [? ?]].\n      apply InMP_deqMsgs in H0.\n      apply H; right; left; do 2 red; eauto.\n    - destruct H0 as [idm [? ?]].\n      apply InMP_deqMsgs in H0.\n      apply H; right; right; do 2 red; eauto.\n  Qed.\n\n  Ltac simpl_InvWBDir_enqMP :=\n    simpl;\n    try match goal with\n        | [H: msg_id ?rmsg = _ |- msg_id ?rmsg <> _] => rewrite H\n        end;\n    discriminate.\n\n  Ltac simpl_InvWBDir_enqMsgs :=\n    let idm := fresh \"idm\" in\n    let Hin := fresh \"H\" in\n    apply Forall_forall; intros idm Hin;\n    apply in_map_iff in Hin; dest; subst;\n    repeat ssplit; simpl_InvWBDir_enqMP.\n\n  Ltac simpl_InvWBDir :=\n    repeat\n      (first [apply InvWBDir_other_msg_id_enqMP; [|simpl_InvWBDir_enqMP..]\n             |apply InvWBDir_other_msg_id_enqMsgs; [|simpl_InvWBDir_enqMsgs]\n             |apply InvWBDir_deqMP\n             |apply InvWBDir_deqMsgs\n             |apply InvWBDir_update_status_NoRqI_NoRsI; [|assumption..]\n             |eapply InvWBDir_no_update; [|eauto; fail..]\n             |assumption]).\n\n  Ltac solve_InvWBDir :=\n    let oidx := fresh \"oidx\" in\n    red; simpl; intros oidx;\n    match goal with\n    | [Hi: InvWBDir _ |- _] =>\n      specialize (Hi oidx); simpl in Hi;\n      mred; simpl;\n      let Hinv := fresh \"H\" in\n      intros Hinv;\n      specialize (Hi Hinv)\n    end;\n    simpl in *; solve_mesi.\n\n  Lemma mesi_InvWBDir_step:\n    Invariant.InvStep impl step_m InvWBDir.\n  Proof. (* SKIP_PROOF_ON\n    red; intros.\n    pose proof (footprints_ok\n                  (mesi_GoodORqsInit Htr)\n                  (mesi_GoodRqRsSys Htr) H) as Hftinv.\n    pose proof (mesi_InObjInds H) as Hioi.\n    pose proof (mesi_MsgConflictsInv\n                  (@mesi_RootChnInv_ok _ Htr) H) as Hpmcf.\n    pose proof (MesiDownLockInv_ok H) as Hmdl.\n    inv H1; [assumption\n            |apply mesi_InvWBDir_ext_in; auto\n            |apply mesi_InvWBDir_ext_out; auto\n            |].\n\n    simpl in H2; destruct H2; [subst|apply in_app_or in H1; destruct H1].\n\n    - (*! Cases for the main memory *)\n\n      (** Abstract the root. *)\n      assert (In (rootOf (fst (tree2Topo tr 0)))\n                 (c_li_indices (snd (tree2Topo tr 0)))) as Hin.\n      { rewrite c_li_indices_head_rootOf by assumption.\n        left; reflexivity.\n      }\n\n      remember (rootOf (fst (tree2Topo tr 0))) as oidx; clear Heqoidx.\n\n      (** Do case analysis per a rule. *)\n      apply concat_In in H3; destruct H3 as [crls [? ?]].\n      apply in_map_iff in H1; destruct H1 as [cidx [? ?]]; subst.\n      dest_in; disc_rule_conds_ex.\n\n      all: try (simpl_InvWBDir; fail).\n      all: try (assert (NoRqI oidx msgs)\n                 by (solve_NoRqI_base; solve_NoRqI_by_no_locks oidx);\n                assert (NoRsI oidx msgs)\n                  by (solve_NoRsI_base; solve_NoRsI_by_no_uplock oidx);\n                simpl_InvWBDir).\n      all: try (eapply InvWBDir_enqMP_rs_valid; eauto;\n                simpl_InvWBDir; fail).\n\n    - (*! Cases for Li caches *)\n\n      (** Derive some necessary information: each Li has a parent. *)\n      apply in_map_iff in H1; destruct H1 as [oidx [? ?]]; subst; simpl in *.\n\n      pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n      pose proof (c_li_indices_tail_has_parent Htr _ _ H2).\n      destruct H1 as [pidx [? ?]].\n      pose proof (Htn _ _ H4); dest.\n\n      (** Do case analysis per a rule. *)\n      apply in_app_or in H3; destruct H3.\n\n      1: { (** Rules per a child *)\n        apply concat_In in H3; destruct H3 as [crls [? ?]].\n        apply in_map_iff in H3; destruct H3 as [cidx [? ?]]; subst.\n        dest_in; disc_rule_conds_ex.\n\n        all: try (simpl_InvWBDir; fail).\n        all: try (assert (NoRqI oidx msgs)\n                   by (solve_NoRqI_base; solve_NoRqI_by_no_locks oidx);\n                  assert (NoRsI oidx msgs)\n                    by (solve_NoRsI_base; solve_NoRsI_by_no_uplock oidx);\n                  simpl_InvWBDir).\n        all: try (eapply InvWBDir_enqMP_rs_valid; eauto;\n                  simpl_InvWBDir; fail).\n      }\n\n      dest_in; disc_rule_conds_ex.\n\n      all: try (simpl_InvWBDir; fail).\n      all: try (derive_footprint_info_basis oidx;\n                assert (NoRqI oidx msgs)\n                  by (solve_NoRqI_base; solve_NoRqI_by_rsDown oidx);\n                assert (NoRsI oidx msgs)\n                  by (solve_NoRsI_base; solve_NoRsI_by_rsDown oidx);\n                simpl_InvWBDir).\n      all: try (simpl_InvWBDir; solve_InvWBDir; fail).\n      all: try (disc_MesiDownLockInv oidx Hmdl;\n                simpl_InvWBDir; solve_InvWBDir; fail).\n      { eapply InvWBDir_enqMP_rq_valid; eauto.\n        { solve_InvWBDir. }\n        { mred. }\n        { assumption. }\n      }\n      { eapply InvWBDir_enqMP_rq_valid; eauto.\n        { solve_InvWBDir. }\n        { mred. }\n        { assumption. }\n      }\n\n    - (*! Cases for L1 caches *)\n\n      (** Derive some necessary information: each Li has a parent. *)\n      apply in_map_iff in H1; destruct H1 as [oidx [? ?]]; subst.\n\n      pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n      pose proof (c_l1_indices_has_parent Htr _ _ H2).\n      destruct H1 as [pidx [? ?]].\n      pose proof (Htn _ _ H4); dest.\n\n      (** Register an invariant that holds only for L1 caches. *)\n      pose proof (mesi_InvL1DirI_ok H) as Hl1d.\n      red in Hl1d; simpl in Hl1d.\n      rewrite Forall_forall in Hl1d; specialize (Hl1d _ H2).\n      simpl in H5; rewrite H5 in Hl1d; simpl in Hl1d.\n\n      (** Do case analysis per a rule. *)\n      dest_in; disc_rule_conds_ex.\n\n      all: try (simpl_InvWBDir; fail).\n      { eapply InvWBDir_enqMP_rq_valid; eauto.\n        { solve_InvWBDir. }\n        { mred. }\n        { assumption. }\n      }\n      { eapply InvWBDir_enqMP_rq_valid; eauto.\n        { solve_InvWBDir. }\n        { mred. }\n        { assumption. }\n      }\n\n      END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Theorem mesi_InvWBDir_ok:\n    InvReachable impl step_m InvWBDir.\n  Proof.\n    eapply inv_reachable.\n    - typeclasses eauto.\n    - apply mesi_InvWBDir_init.\n    - apply mesi_InvWBDir_step.\n  Qed.\n\nEnd InvWBDir.\n\nLtac derive_InvWBDir oidx :=\n  repeat\n    match goal with\n    | [Hi: InvWBDir _ |- _] =>\n      specialize (Hi oidx); simpl in Hi;\n      repeat\n        match type of Hi with\n        | _ <+- ?ov; _ =>\n          match goal with\n          | [Hv: ov = Some _ |- _] => rewrite Hv in Hi; simpl in Hi\n          end\n        end\n    | [Ho: ObjWBDir _ _ _ |- _] => red in Ho\n    end.\n\nSection InvWBCoh.\n  Variable (tr: tree).\n  Hypothesis (Htr: tr <> Node nil).\n\n  Let topo: DTree := fst (tree2Topo tr 0).\n  Let cifc: CIfc := snd (tree2Topo tr 0).\n  Let impl: System := impl Htr.\n\n  Lemma mesi_InvWBCoh_init:\n    Invariant.InvInit impl InvWBCoh.\n  Proof.\n    do 2 (red; simpl).\n    intros.\n    destruct (implOStatesInit tr)@[oidx] as [orq|] eqn:Host; simpl; auto.\n    destruct (in_dec idx_dec oidx (c_li_indices cifc ++ c_l1_indices cifc)).\n    - subst cifc; rewrite c_li_indices_head_rootOf in i by assumption.\n      inv i.\n      + rewrite implOStatesInit_value_root in Host by assumption.\n        inv Host.\n        red; intros.\n        do 2 (red in H); dest_in.\n      + rewrite implOStatesInit_value_non_root in Host by assumption.\n        inv Host.\n        red; intros.\n        do 2 (red in H0); dest_in.\n    - rewrite implOStatesInit_None in Host by assumption.\n      discriminate.\n  Qed.\n\n  Lemma mesi_InvWBCoh_ext_in:\n    forall oss orqs msgs,\n      InvWBCoh {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n      InObjInds tr 0 {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n      forall eins,\n        ValidMsgsExtIn impl eins ->\n        InvWBCoh {| st_oss := oss; st_orqs := orqs; st_msgs := enqMsgs eins msgs |}.\n  Proof.\n    red; simpl; intros.\n    specialize (H oidx); simpl in H.\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros.\n    apply InMP_enqMsgs_or in H2.\n    destruct H2; [|eapply H; eauto].\n    apply in_map with (f:= idOf) in H2; simpl in H2.\n    apply H1 in H2; simpl in H2.\n    exfalso; eapply DisjList_In_1.\n    - apply tree2Topo_minds_merqs_disj.\n    - eassumption.\n    - eapply tree2Topo_obj_chns_minds_SubList.\n      + specialize (H0 oidx); simpl in H0.\n        rewrite Host in H0; simpl in H0.\n        eassumption.\n      + destruct idm as [midx msg]; inv H3.\n        simpl; tauto.\n  Qed.\n\n  Lemma mesi_InvWBCoh_ext_out:\n    forall oss orqs msgs,\n      InvWBCoh {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n      InObjInds tr 0 {| st_oss := oss; st_orqs := orqs; st_msgs := msgs |} ->\n      forall (eouts: list (Id Msg)),\n        InvWBCoh {| st_oss := oss;\n                    st_orqs := orqs;\n                    st_msgs := deqMsgs (idsOf eouts) msgs |}.\n  Proof.\n    red; simpl; intros.\n    specialize (H oidx); simpl in H.\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros; apply InMP_deqMsgs in H1; auto.\n  Qed.\n\n  Lemma InvWBCoh_no_update:\n    forall oss orqs msgs,\n      InvWBCoh {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall oidx (post nost: OState),\n        oss@[oidx] = Some post ->\n        nost#[val] = post#[val] ->\n        nost#[owned] = post#[owned] ->\n        nost#[status] = post#[status] ->\n        nost#[dir].(dir_st) = post#[dir].(dir_st) ->\n        InvWBCoh {| st_oss:= oss +[oidx <- nost];\n                    st_orqs:= orqs; st_msgs:= msgs |}.\n  Proof.\n    unfold InvWBCoh; simpl; intros.\n    mred; simpl; auto.\n    specialize (H oidx).\n    rewrite H0 in H; simpl in H.\n    red; intros.\n    specialize (H _ H5 H6).\n    simpl in *.\n    rewrite H1.\n    apply H; auto.\n    congruence.\n  Qed.\n\n  Lemma InvWBCoh_update_status_NoRqI:\n    forall oss orqs msgs,\n      InvWBCoh {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall oidx (ost: OState),\n        NoRqI oidx msgs ->\n        InvWBCoh {| st_oss:= oss +[oidx <- ost];\n                    st_orqs:= orqs; st_msgs:= msgs |}.\n  Proof.\n    unfold InvWBCoh; simpl; intros.\n    mred; simpl; auto.\n    red; intros.\n    specialize (H0 _ H1).\n    red in H0; rewrite H2 in H0.\n    unfold map in H0.\n    rewrite caseDec_head_neq in H0 by discriminate.\n    rewrite caseDec_head_eq in H0 by reflexivity.\n    exfalso; auto.\n  Qed.\n\n  Lemma InvWBCoh_enqMP_valid:\n    forall oss orqs msgs,\n      InvWBCoh {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall oidx ost midx msg,\n        oss@[oidx] = Some ost ->\n        midx = rqUpFrom oidx ->\n        msg.(msg_id) = mesiInvWRq ->\n        msg.(msg_value) = ost#[val] ->\n        InvWBCoh {| st_oss:= oss; st_orqs:= orqs;\n                    st_msgs:= enqMP midx msg msgs |}.\n  Proof.\n    unfold InvWBCoh; simpl; intros.\n    destruct (idx_dec oidx0 oidx); subst.\n    - specialize (H oidx).\n      rewrite H0 in *; simpl in *.\n      red; intros.\n      apply InMP_enqMP_or in H1; destruct H1.\n      + dest; simpl in *.\n        intros; inv H4; assumption.\n      + apply H; auto.\n    - specialize (H oidx0).\n      destruct (oss@[oidx0]) as [ost0|]; simpl in *; auto.\n      red; intros.\n      apply InMP_enqMP_or in H1; destruct H1.\n      + exfalso; dest; subst.\n        inv H4; rewrite H1 in H7; inv H7; auto.\n      + apply H; auto.\n  Qed.\n\n  Lemma InvWBCoh_other_msg_id_enqMP:\n    forall oss orqs msgs,\n      InvWBCoh {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall midx msg,\n        msg.(msg_id) <> mesiInvWRq ->\n        InvWBCoh {| st_oss:= oss; st_orqs:= orqs;\n                    st_msgs:= enqMP midx msg msgs |}.\n  Proof.\n    unfold InvWBCoh; simpl; intros.\n    specialize (H oidx).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros.\n    apply InMP_enqMP_or in H1; destruct H1; auto.\n    dest; subst.\n    destruct idm as [midx msg]; simpl in *.\n    inv H2; exfalso; auto.\n  Qed.\n\n  Lemma InvWBCoh_other_msg_id_enqMsgs:\n    forall oss orqs msgs,\n      InvWBCoh {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall nmsgs,\n        Forall (fun idm => (valOf idm).(msg_id) <> mesiInvWRq) nmsgs ->\n        InvWBCoh {| st_oss:= oss; st_orqs:= orqs;\n                    st_msgs:= enqMsgs nmsgs msgs |}.\n  Proof.\n    intros.\n    generalize dependent msgs.\n    induction nmsgs as [|[nmidx nmsg] nmsgs]; simpl; intros; auto.\n    inv H0; dest.\n    apply IHnmsgs; auto.\n    apply InvWBCoh_other_msg_id_enqMP; assumption.\n  Qed.\n\n  Lemma InvWBCoh_deqMP:\n    forall oss orqs msgs,\n      InvWBCoh {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall midx,\n        InvWBCoh {| st_oss:= oss; st_orqs:= orqs;\n                    st_msgs:= deqMP midx msgs |}.\n  Proof.\n    unfold InvWBCoh; simpl; intros.\n    specialize (H oidx).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros; apply InMP_deqMP in H0; auto.\n  Qed.\n\n  Lemma InvWBCoh_deqMsgs:\n    forall oss orqs msgs,\n      InvWBCoh {| st_oss:= oss; st_orqs:= orqs; st_msgs:= msgs |} ->\n      forall minds,\n        InvWBCoh {| st_oss:= oss; st_orqs:= orqs;\n                    st_msgs:= deqMsgs minds msgs |}.\n  Proof.\n    unfold InvWBCoh; simpl; intros.\n    specialize (H oidx).\n    destruct (oss@[oidx]) as [ost|] eqn:Host; simpl in *; auto.\n    red; intros; apply InMP_deqMsgs in H0; auto.\n  Qed.\n\n  Ltac simpl_InvWBCoh_enqMP :=\n    simpl;\n    try match goal with\n        | [H: msg_id ?rmsg = _ |- msg_id ?rmsg <> _] => rewrite H\n        end;\n    discriminate.\n\n  Ltac simpl_InvWBCoh_enqMsgs :=\n    let idm := fresh \"idm\" in\n    let Hin := fresh \"H\" in\n    apply Forall_forall; intros idm Hin;\n    apply in_map_iff in Hin; dest; subst;\n    simpl_InvWBCoh_enqMP.\n\n  Ltac simpl_InvWBCoh :=\n    repeat\n      (first [apply InvWBCoh_other_msg_id_enqMP; [|simpl_InvWBCoh_enqMP..]\n             |apply InvWBCoh_other_msg_id_enqMsgs; [|simpl_InvWBCoh_enqMsgs]\n             |apply InvWBCoh_deqMP\n             |apply InvWBCoh_deqMsgs\n             |apply InvWBCoh_update_status_NoRqI; [|assumption]\n             |eapply InvWBCoh_no_update; [|eauto; fail..]\n             |assumption]).\n\n  Ltac solve_InvWBCoh :=\n    let oidx := fresh \"oidx\" in\n    red; simpl; intros oidx;\n    match goal with\n    | [Hi: InvWBCoh _ |- _] =>\n      specialize (Hi oidx); simpl in Hi\n    end;\n    mred; simpl;\n    let Hin := fresh \"H\" in\n    let Hsig := fresh \"H\" in\n    red; intros ? Hin Hsig;\n    repeat\n      match goal with\n      | [Hc: CohInvRq _ _ _ |- _] => specialize (Hc _ Hin Hsig); dest\n      | [Hi: ObjInvWRq _ _ \\/ _ -> _ |- _] =>\n        specialize (Hi (or_introl (@ex_intro _ _ _ (conj Hin Hsig))))\n      end;\n    simpl in *;\n    solve [exfalso; solve_mesi|\n           simpl; intros;\n           try match goal with\n               | [H: context [invalidate ?st] |- _] =>\n                 pose proof (invalidate_sound st)\n               end;\n           intuition solve_mesi].\n\n  Lemma mesi_InvWBCoh_step:\n    Invariant.InvStep impl step_m InvWBCoh.\n  Proof. (* SKIP_PROOF_ON\n    red; intros.\n    pose proof (footprints_ok\n                  (mesi_GoodORqsInit Htr)\n                  (mesi_GoodRqRsSys Htr) H) as Hftinv.\n    pose proof (mesi_InObjInds H) as Hioi.\n    pose proof (mesi_MsgConflictsInv\n                  (@mesi_RootChnInv_ok _ Htr) H) as Hpmcf.\n    pose proof (MesiDownLockInv_ok H) as Hmdl.\n    pose proof (mesi_InvWBDir_ok H) as Hidir.\n    inv H1; [assumption\n            |apply mesi_InvWBCoh_ext_in; auto\n            |apply mesi_InvWBCoh_ext_out; auto\n            |].\n\n    simpl in H2; destruct H2; [subst|apply in_app_or in H1; destruct H1].\n\n    - (*! Cases for the main memory *)\n\n      (** Abstract the root. *)\n      assert (In (rootOf (fst (tree2Topo tr 0)))\n                 (c_li_indices (snd (tree2Topo tr 0)))) as Hin.\n      { rewrite c_li_indices_head_rootOf by assumption.\n        left; reflexivity.\n      }\n\n      remember (rootOf (fst (tree2Topo tr 0))) as oidx; clear Heqoidx.\n\n      (** Do case analysis per a rule. *)\n      apply concat_In in H3; destruct H3 as [crls [? ?]].\n      apply in_map_iff in H1; destruct H1 as [cidx [? ?]]; subst.\n      dest_in; disc_rule_conds_ex.\n\n      all: try (simpl_InvWBCoh; fail).\n      all: try (assert (NoRqI oidx msgs)\n                 by (solve_NoRqI_base; solve_NoRqI_by_no_locks oidx);\n                simpl_InvWBCoh).\n\n    - (*! Cases for Li caches *)\n\n      (** Derive some necessary information: each Li has a parent. *)\n      apply in_map_iff in H1; destruct H1 as [oidx [? ?]]; subst; simpl in *.\n\n      pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n      pose proof (c_li_indices_tail_has_parent Htr _ _ H2).\n      destruct H1 as [pidx [? ?]].\n      pose proof (Htn _ _ H4); dest.\n\n      (** Do case analysis per a rule. *)\n      apply in_app_or in H3; destruct H3.\n\n      1: { (** Rules per a child *)\n        apply concat_In in H3; destruct H3 as [crls [? ?]].\n        apply in_map_iff in H3; destruct H3 as [cidx [? ?]]; subst.\n        dest_in; disc_rule_conds_ex.\n\n        all: try (simpl_InvWBCoh; fail).\n        all: try (assert (NoRqI oidx msgs)\n                   by (solve_NoRqI_base; solve_NoRqI_by_no_locks oidx);\n                  simpl_InvWBCoh).\n      }\n\n      dest_in; disc_rule_conds_ex.\n\n      all: try (simpl_InvWBCoh; fail).\n      all: try (assert (NoRqI oidx msgs)\n                 by (solve_NoRqI_base; solve_NoRqI_by_no_locks oidx);\n                simpl_InvWBCoh).\n      all: try (derive_footprint_info_basis oidx;\n                assert (NoRqI oidx msgs)\n                  by (solve_NoRqI_base; solve_NoRqI_by_rsDown oidx);\n                simpl_InvWBCoh).\n      all: try (simpl_InvWBCoh; solve_InvWBCoh; fail).\n      all: try (disc_MesiDownLockInv oidx Hmdl;\n                derive_InvWBDir oidx;\n                simpl_InvWBCoh; solve_InvWBCoh; fail).\n      { eapply InvWBCoh_enqMP_valid; eauto. }\n\n    - (*! Cases for L1 caches *)\n\n      (** Derive some necessary information: each Li has a parent. *)\n      apply in_map_iff in H1; destruct H1 as [oidx [? ?]]; subst.\n\n      pose proof (tree2Topo_TreeTopoNode tr 0) as Htn.\n      pose proof (c_l1_indices_has_parent Htr _ _ H2).\n      destruct H1 as [pidx [? ?]].\n      pose proof (Htn _ _ H4); dest.\n\n      (** Do case analysis per a rule. *)\n      dest_in; disc_rule_conds_ex.\n\n      all: try (simpl_InvWBCoh; fail).\n      all: try (assert (NoRqI oidx msgs)\n                 by (solve_NoRqI_base; solve_NoRqI_by_no_locks oidx);\n                simpl_InvWBCoh).\n      all: try (derive_footprint_info_basis oidx;\n                assert (NoRqI oidx msgs)\n                  by (solve_NoRqI_base; solve_NoRqI_by_rsDown oidx);\n                simpl_InvWBCoh).\n      all: try (simpl_InvWBCoh; solve_InvWBCoh; fail).\n      { eapply InvWBCoh_enqMP_valid; eauto. }\n\n      END_SKIP_PROOF_ON *) admit.\n  Qed.\n\n  Theorem mesi_InvWBCoh_ok:\n    InvReachable impl step_m InvWBCoh.\n  Proof.\n    eapply inv_reachable.\n    - typeclasses eauto.\n    - apply mesi_InvWBCoh_init.\n    - apply mesi_InvWBCoh_step.\n  Qed.\n\nEnd InvWBCoh.\n", "meta": {"author": "mit-plv", "repo": "hemiola", "sha": "1984b4de903259ce2d7abda737e76e16e6436dee", "save_path": "github-repos/coq/mit-plv-hemiola", "path": "github-repos/coq/mit-plv-hemiola/hemiola-1984b4de903259ce2d7abda737e76e16e6436dee/src/Ex/Mesi/MesiInvInv0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4610167793123158, "lm_q1q2_score": 0.24489642761036218}}
{"text": "(**************************************************************************)\n(*                                                                        *)\n(*     SMTCoq                                                             *)\n(*     Copyright (C) 2011 - 2014                                          *)\n(*                                                                        *)\n(*     Michaël Armand                                                     *)\n(*     Benjamin Grégoire                                                  *)\n(*     Chantal Keller                                                     *)\n(*                                                                        *)\n(*     INRIA - École Polytechnique - MSR                                  *)\n(*                                                                        *)\n(*   This file is distributed under the terms of the CeCILL-C licence     *)\n(*                                                                        *)\n(**************************************************************************)\n\nAdd LoadPath \".\" as SMTCoq.\nAdd LoadPath \"cnf\" as SMTCoq.cnf.\nAdd LoadPath \"euf\" as SMTCoq.euf.\nAdd LoadPath \"lia\" as SMTCoq.lia.\nAdd LoadPath \"spl\" as SMTCoq.spl.\n\nRequire Import Bool Int31 PArray.\nRequire Import Misc State SMT_terms Cnf Euf Lia Syntactic Arithmetic Operators.\n\nLocal Open Scope array_scope.\nLocal Open Scope int31_scope.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nSet Vm Optimize.\nSection trace.\n\n  (* We are given a certificate, a checker for it (that modifies a\n     state), and a proof that the checker is correct: the state it\n     returns must be valid and well-formed. *)\n\n  Variable step : Type.\n\n  Variable check_step : S.t -> step -> S.t.\n\n  Variable rho : Valuation.t.\n\n  (* We use [array array step] to allow bigger trace *)\n  Definition _trace_ := array (array step).\n\n  (* A checker for such a trace *)\n\n  Variable is_false : C.t -> bool.\n  Hypothesis is_false_correct : forall c, is_false c -> ~ C.interp rho c.\n\n  Definition _checker_ (s: S.t) (t: _trace_) (confl:clause_id) : bool :=\n    let s' := PArray.fold_left (fun s a => PArray.fold_left check_step s a) s t in\n    is_false (S.get s' confl).\n  Register _checker_ as PrimInline.\n\n  (* For debugging *)\n  (*\n\n  Variable check_step_debug : S.t -> step -> option S.t.\n\n  Definition _checker_debug_ (s: S.t) (t: _trace_) : sum S.t ((int*int)*S.t) :=\n    let s' := PArray.foldi_left (fun i s a => PArray.foldi_left (fun j s' a' =>\n      match s' with\n        | inl s'' =>\n          match check_step_debug s'' a' with\n            | Some s''' => inl s'''\n            | None => inr ((i,j),s'')\n          end\n        | u => u\n      end) s a) (inl s) t in\n    s'.\n\n  Definition _checker_partial_ (s: S.t) (t: _trace_) (max:int) : S.t :=\n    PArray.fold_left (fun s a => PArray.foldi_left (fun i s' a' => if i < max then check_step s' a' else s') s a) s t.\n  *)\n\n  (* Proof of its partial correction: if it returns true, then the\n     initial state is not valid *)\n\n  Hypothesis valid_check_step :\n    forall s, S.valid rho s -> forall c, S.valid rho (check_step s c).\n\n  Lemma _checker__correct :\n    forall s, forall t confl, _checker_ s t confl-> ~ (S.valid rho s).\n  Proof.\n    unfold _checker_.\n    intros s t' cid Hf Hv.\n    apply (is_false_correct Hf).\n    apply S.valid_get.\n    apply PArray.fold_left_ind; auto.\n    intros a i _ Ha;apply PArray.fold_left_ind;trivial.\n    intros a0 i0 _ H1;auto.\n  Qed.\n \nEnd trace.\n\n\n(* Application to resolution *)\n\nModule Sat_Checker.\n\n Inductive step :=\n   | Res (_:int) (_:resolution).\n\n Definition resolution_checker s t :=\n    _checker_ (fun s (st:step) => let (pos, r) := st in S.set_resolve s pos r) s t.\n\n Lemma resolution_checker_correct :\n    forall rho, Valuation.wf rho ->\n    forall s t cid, resolution_checker C.is_false s t cid->\n     ~S.valid rho s.\n Proof.\n   intros rho Hwr;apply _checker__correct.\n   intros; apply C.is_false_correct; trivial.\n   intros s Hv (pos, r);apply S.valid_set_resolve;trivial. \n Qed.\n   \n (** Application to Zchaff *)\n Definition dimacs := PArray.array (PArray.array _lit).\n\n Definition C_interp_or rho c := \n   afold_left _ _ false orb (Lit.interp rho) c.\n\n Lemma C_interp_or_spec : forall rho c,\n   C_interp_or rho c = C.interp rho (to_list c).\n Proof.\n   intros rho c; unfold C_interp_or; case_eq (C.interp rho (to_list c)).\n   unfold C.interp; rewrite List.existsb_exists; intros [x [H1 H2]]; destruct (In_to_list _ _ H1) as [i [H3 H4]]; subst x; apply (afold_left_orb_true _ i); auto.\n   unfold C.interp; intro H; apply afold_left_orb_false; intros i H1; case_eq (Lit.interp rho (c .[ i])); auto; intro Heq; assert (H2: exists x, List.In x (to_list c) /\\ Lit.interp rho x = true).\n   exists (c.[i]); split; auto; apply to_list_In; auto.\n   rewrite <- List.existsb_exists in H2; rewrite H2 in H; auto.\nQed.\n\n Definition valid rho (d:dimacs) :=\n   afold_left _ _ true andb (C_interp_or rho) d.\n\n Lemma valid_spec : forall rho d,\n   valid rho d <->\n   (forall i : int, i < length d -> C.interp rho (PArray.to_list (d.[i]))).\n Proof.\n   unfold valid; intros rho d; split; intro H.\n   intros i Hi; case_eq (C.interp rho (to_list (d .[ i]))); try reflexivity.\n   intro Heq; erewrite afold_left_andb_false in H; try eassumption.\n   rewrite C_interp_or_spec; auto.\n   apply afold_left_andb_true; try assumption; intros i Hi; rewrite C_interp_or_spec; apply H; auto.\n Qed.\n\n Inductive certif :=\n   | Certif : int -> _trace_ step -> clause_id -> certif.\n\n Definition add_roots s (d:dimacs) := \n   PArray.foldi_right (fun i c s => S.set_clause s i (PArray.to_list c)) d s.\n\n Definition checker (d:dimacs) (c:certif) :=\n   let (nclauses, t, confl_id) := c in\n   resolution_checker C.is_false (add_roots (S.make nclauses) d) t confl_id.\n\n Lemma valid_add_roots : forall rho, Valuation.wf rho ->\n    forall d s, valid rho d -> S.valid rho s ->\n    S.valid rho (add_roots s d).\n Proof.\n   intros rho Hwr d s Hd Hs; unfold add_roots; apply (PArray.foldi_right_Ind _ _ (fun _ a => S.valid rho a)); auto; intros a i Hlt Hv; apply S.valid_set_clause; auto; rewrite valid_spec in Hd; apply Hd; auto.\n Qed.\n\n Lemma checker_correct : forall d c,\n    checker d c = true ->\n    forall rho, Valuation.wf rho -> ~valid rho d.\n Proof.\n   unfold checker; intros d (nclauses, t, confl_id) Hc rho Hwf Hv.\n   apply (resolution_checker_correct Hwf Hc).\n   apply valid_add_roots; auto.\n   apply S.valid_make; auto.\n Qed.\n\n Definition interp_var rho x := \n   match compare x 1 with\n   | Lt => true\n   | Eq => false\n   | Gt => rho (x - 1) \n     (* This allows to have variable starting at 1 in the interpretation as in dimacs files *)\n   end.\n\n Lemma theorem_checker : \n   forall d c,\n     checker d c = true ->\n     forall rho, ~valid (interp_var rho) d.\n Proof.\n  intros d c H rho;apply checker_correct with c;trivial.\n  split;compute;trivial;discriminate.\n Qed.\n\nEnd Sat_Checker.\n\nModule Cnf_Checker.\n  \n  Inductive step :=\n  | Res (pos:int) (res:resolution)\n  | ImmFlatten (pos:int) (cid:clause_id) (lf:_lit) \n  | CTrue (pos:int)       \n  | CFalse (pos:int)\n  | BuildDef (pos:int) (l:_lit)\n  | BuildDef2 (pos:int) (l:_lit)\n  | BuildProj (pos:int) (l:_lit) (i:int)\n  | ImmBuildDef (pos:int) (cid:clause_id)\n  | ImmBuildDef2 (pos:int) (cid:clause_id)\n  | ImmBuildProj (pos:int) (cid:clause_id) (i:int).\n\n  Local Open Scope list_scope.\n\n  Local Notation check_flatten t_form := (check_flatten t_form (fun i1 i2 => i1 == i2) (fun _ _ => false)) (only parsing).\n\n  Definition step_checker t_form s (st:step) :=\n    match st with\n    | Res pos res => S.set_resolve s pos res\n    | ImmFlatten pos cid lf => S.set_clause s pos (check_flatten t_form s cid lf) \n    | CTrue pos => S.set_clause s pos Cnf.check_True\n    | CFalse pos => S.set_clause s pos Cnf.check_False\n    | BuildDef pos l => S.set_clause s pos (check_BuildDef t_form l)\n    | BuildDef2 pos l => S.set_clause s pos (check_BuildDef2 t_form l)\n    | BuildProj pos l i => S.set_clause s pos (check_BuildProj t_form l i)\n    | ImmBuildDef pos cid => S.set_clause s pos (check_ImmBuildDef t_form s cid) \n    | ImmBuildDef2 pos cid => S.set_clause s pos (check_ImmBuildDef2 t_form s cid)\n    | ImmBuildProj pos cid i => S.set_clause s pos (check_ImmBuildProj t_form s cid i) \n    end.\n\n  Lemma step_checker_correct : forall rho t_form,\n    Form.check_form t_form ->\n    forall s, S.valid (Form.interp_state_var rho t_form) s ->\n      forall st : step, S.valid (Form.interp_state_var rho t_form)\n        (step_checker t_form s st).\n  Proof.\n    intros rho t_form Ht s H; destruct (Form.check_form_correct rho _ Ht) as [[Ht1 Ht2] Ht3]; intros [pos res|pos cid lf|pos|pos|pos l|pos l|pos l i|pos cid|pos cid|pos cid i]; simpl; try apply S.valid_set_clause; auto.\n    apply S.valid_set_resolve; auto.\n    apply valid_check_flatten; auto; try discriminate; intros a1 a2; unfold is_true; rewrite Int31Properties.eqb_spec; intro; subst a1; auto.\n    apply valid_check_True; auto.\n    apply valid_check_False; auto.\n    apply valid_check_BuildDef; auto.\n    apply valid_check_BuildDef2; auto.\n    apply valid_check_BuildProj; auto.\n    apply valid_check_ImmBuildDef; auto.\n    apply valid_check_ImmBuildDef2; auto.\n    apply valid_check_ImmBuildProj; auto.\n  Qed.\n\n  Definition cnf_checker t_form s t :=\n    _checker_ (step_checker t_form) s t.\n\n  Lemma cnf_checker_correct : forall rho t_form,\n    Form.check_form t_form -> forall s t confl,\n      cnf_checker t_form C.is_false s t confl ->\n      ~ (S.valid (Form.interp_state_var rho t_form) s).\n  Proof.\n    unfold cnf_checker; intros rho t_form Ht; apply _checker__correct.\n    intros c H; apply C.is_false_correct; auto.\n    apply step_checker_correct; auto.\n  Qed.\n\n\n Inductive certif :=\n   | Certif : int -> _trace_ step -> int -> certif.\n\n Definition checker t_form l (c:certif) :=\n   let (nclauses, t, confl) := c in   \n   Form.check_form t_form &&\n   cnf_checker t_form C.is_false (S.set_clause (S.make nclauses) 0 (l::nil)) t confl.\n\n Lemma checker_correct : forall t_form l c,\n    checker t_form l c = true ->\n    forall rho, ~ (Lit.interp (Form.interp_state_var rho t_form) l).\n Proof.\n   unfold checker; intros t_form l (nclauses, t, confl); unfold is_true; rewrite andb_true_iff; intros [H1 H2] rho H; apply (cnf_checker_correct (rho:=rho) H1 H2); destruct (Form.check_form_correct rho _ H1) as [[Ht1 Ht2] Ht3]; apply S.valid_set_clause; auto.\n   apply S.valid_make; auto.\n   unfold C.valid; simpl; rewrite H; auto.\n Qed.\n\n Definition checker_b t_form l (b:bool) (c:certif) :=\n   let l := if b then Lit.neg l else l in\n   checker t_form l c.\n\n Lemma checker_b_correct : forall t_var t_form l b c,\n    checker_b t_form l b c = true ->\n    Lit.interp (Form.interp_state_var (PArray.get t_var) t_form) l = b.\n Proof.\n   unfold checker_b; intros t_var t_form l b c; case b; case_eq (Lit.interp (Form.interp_state_var (get t_var) t_form) l); auto; intros H1 H2; elim (checker_correct H2 (rho:=get t_var)); auto; rewrite Lit.interp_neg, H1; auto.\n Qed.\n\n Definition checker_eq t_form l1 l2 l (c:certif) :=\n   negb (Lit.is_pos l) && \n   match t_form.[Lit.blit l] with\n   | Form.Fiff l1' l2' => (l1 == l1') && (l2 == l2')\n   | _ => false\n   end && \n   checker t_form l c.\n\n Lemma checker_eq_correct : forall t_var t_form l1 l2 l c,\n   checker_eq t_form l1 l2 l c = true ->\n    Lit.interp (Form.interp_state_var (PArray.get t_var) t_form) l1 =\n    Lit.interp (Form.interp_state_var (PArray.get t_var) t_form) l2.\n Proof.\n   unfold checker_eq; intros t_var t_form l1 l2 l c; rewrite !andb_true_iff; case_eq (t_form .[ Lit.blit l]); [intros _ _|intros _|intros _|intros _ _ _|intros _ _|intros _ _|intros _ _|intros _ _ _|intros l1' l2' Heq|intros _ _ _ _]; intros [[H1 H2] H3]; try discriminate; rewrite andb_true_iff in H2; rewrite !Int31Properties.eqb_spec in H2; destruct H2 as [H2 H4]; subst l1' l2'; case_eq (Lit.is_pos l); intro Heq'; rewrite Heq' in H1; try discriminate; clear H1; assert (H:PArray.default t_form = Form.Ftrue /\\ Form.wf t_form).\n   unfold checker in H3; destruct c as (nclauses, t, confl); rewrite andb_true_iff in H3; destruct H3 as [H3 _]; destruct (Form.check_form_correct (get t_var) _ H3) as [[Ht1 Ht2] Ht3]; split; auto.\n   destruct H as [H1 H2]; case_eq (Lit.interp (Form.interp_state_var (get t_var) t_form) l1); intro Heq1; case_eq (Lit.interp (Form.interp_state_var (get t_var) t_form) l2); intro Heq2; auto; elim (checker_correct H3 (rho:=get t_var)); unfold Lit.interp; rewrite Heq'; unfold Var.interp; rewrite Form.wf_interp_form; auto; rewrite Heq; simpl; rewrite Heq1, Heq2; auto.\n Qed.\n\nEnd Cnf_Checker.\n\n\n(* Application to resolution + cnf justification + euf + lia *)\n\n(* Require Cnf.Cnf. *)\n(* Require Euf.Euf. *)\n(* Require Lia.Lia. *)\n\nModule Euf_Checker.\n\n  Inductive step :=\n  | Res (pos:int) (res:resolution)\n  | ImmFlatten (pos:int) (cid:clause_id) (lf:_lit)\n  | CTrue (pos:int)\n  | CFalse (pos:int)\n  | BuildDef (pos:int) (l:_lit)\n  | BuildDef2 (pos:int) (l:_lit)\n  | BuildProj (pos:int) (l:_lit) (i:int)\n  | ImmBuildDef (pos:int) (cid:clause_id)\n  | ImmBuildDef2 (pos:int) (cid:clause_id)\n  | ImmBuildProj (pos:int) (cid:clause_id) (i:int)\n  | EqTr (pos:int) (l:_lit) (fl: list _lit)\n  | EqCgr (pos:int) (l:_lit) (fl: list (option _lit))\n  | EqCgrP (pos:int) (l1:_lit) (l2:_lit) (fl: list (option _lit))\n  | LiaMicromega (pos:int) (cl:list _lit) (c:list ZMicromega.ZArithProof)\n  | LiaDiseq (pos:int) (l:_lit)\n  | SplArith (pos:int) (orig:clause_id) (res:_lit) (l:list ZMicromega.ZArithProof)\n  | SplDistinctElim (pos:int) (orig:clause_id) (res:_lit).\n\n  Local Open Scope list_scope.\n\n  Local Notation check_flatten t_atom t_form := (check_flatten t_form (check_hatom t_atom) (check_neg_hatom t_atom)) (only parsing).\n\n  Definition step_checker t_atom t_form s (st:step) :=\n    match st with\n      | Res pos res => S.set_resolve s pos res\n      | ImmFlatten pos cid lf => S.set_clause s pos (check_flatten t_atom t_form s cid lf)\n      | CTrue pos => S.set_clause s pos Cnf.check_True\n      | CFalse pos => S.set_clause s pos Cnf.check_False\n      | BuildDef pos l => S.set_clause s pos (check_BuildDef t_form l)\n      | BuildDef2 pos l => S.set_clause s pos (check_BuildDef2 t_form l)\n      | BuildProj pos l i => S.set_clause s pos (check_BuildProj t_form l i)\n      | ImmBuildDef pos cid => S.set_clause s pos (check_ImmBuildDef t_form s cid)\n      | ImmBuildDef2 pos cid => S.set_clause s pos (check_ImmBuildDef2 t_form s cid)\n      | ImmBuildProj pos cid i => S.set_clause s pos (check_ImmBuildProj t_form s cid i)\n      | EqTr pos l fl => S.set_clause s pos (check_trans t_form t_atom l fl)\n      | EqCgr pos l fl => S.set_clause s pos (check_congr t_form t_atom l fl)\n      | EqCgrP pos l1 l2 fl => S.set_clause s pos (check_congr_pred t_form t_atom l1 l2 fl)\n      | LiaMicromega pos cl c => S.set_clause s pos (check_micromega t_form t_atom cl c)\n      | LiaDiseq pos l => S.set_clause s pos (check_diseq t_form t_atom l)\n      | SplArith pos orig res l => S.set_clause s pos (check_spl_arith t_form t_atom (S.get s orig) res l)\n      | SplDistinctElim pos orig res => S.set_clause s pos (check_distinct_elim t_form t_atom (S.get s orig) res)\n    end.\n\n  Lemma step_checker_correct : forall t_i t_func t_atom t_form,\n    let rho := Form.interp_state_var (Atom.interp_form_hatom t_i t_func t_atom) t_form in\n      Form.check_form t_form -> Atom.check_atom t_atom ->\n      Atom.wt t_i t_func t_atom ->\n      forall s, S.valid rho s ->\n        forall st : step, S.valid rho (step_checker t_atom t_form s st).\n  Proof.\n    intros t_i t_func t_atom t_form rho H1 H2 H10 s Hs. destruct (Form.check_form_correct (Atom.interp_form_hatom t_i t_func t_atom) _ H1) as [[Ht1 Ht2] Ht3]. destruct (Atom.check_atom_correct _ H2) as [Ha1 Ha2]. intros [pos res|pos cid lf|pos|pos|pos l|pos l|pos l i|pos cid|pos cid|pos cid i|pos l fl|pos l fl|pos l1 l2 fl|pos cl c|pos l|pos orig res l|pos orig res]; simpl; try apply S.valid_set_clause; auto.\n    apply S.valid_set_resolve; auto.\n    apply valid_check_flatten; auto; intros h1 h2 H.\n    rewrite (Syntactic.check_hatom_correct_bool _ _ _ Ha1 Ha2 _ _ H); auto.\n    rewrite (Syntactic.check_neg_hatom_correct_bool _ _ _ H10 Ha1 Ha2 _ _ H); auto.\n    apply valid_check_True; auto.\n    apply valid_check_False; auto.\n    apply valid_check_BuildDef; auto.\n    apply valid_check_BuildDef2; auto.\n    apply valid_check_BuildProj; auto.\n    apply valid_check_ImmBuildDef; auto.\n    apply valid_check_ImmBuildDef2; auto.\n    apply valid_check_ImmBuildProj; auto.\n    apply valid_check_trans; auto.\n    apply valid_check_congr; auto.\n    apply valid_check_congr_pred; auto.\n    apply valid_check_micromega; auto.\n    apply valid_check_diseq; auto.\n    apply valid_check_spl_arith; auto.\n    apply valid_check_distinct_elim; auto.\n  Qed.\n\n  Definition euf_checker t_atom t_form s t :=\n    _checker_ (step_checker t_atom t_form) s t.\n\n  Lemma euf_checker_correct : forall t_i t_func t_atom t_form,\n    let rho := Form.interp_state_var (Atom.interp_form_hatom t_i t_func t_atom) t_form in\n      Form.check_form t_form -> Atom.check_atom t_atom ->\n      Atom.wt t_i t_func t_atom ->\n      forall s t confl,\n        euf_checker t_atom t_form C.is_false s t confl ->\n        ~ (S.valid rho s).\n  Proof.\n    unfold euf_checker; intros t_i t_func t_atom t_form rho H1 H2 H10; apply _checker__correct.\n    intros c H; apply C.is_false_correct; auto.\n    apply step_checker_correct; auto.\n  Qed.\n\n  Inductive certif :=\n  | Certif : int -> _trace_ step -> int -> certif.\n\n  Definition add_roots s d used_roots :=\n    match used_roots with\n      | Some ur => PArray.foldi_right (fun i c_index s =>\n        let c := if c_index < length d then (d.[c_index])::nil else C._true in\n          S.set_clause s i c) ur s\n      | None => PArray.foldi_right (fun i c s => S.set_clause s i (c::nil)) d s\n    end.\n\n  Definition valid t_i t_func t_atom t_form d :=\n    let rho := Form.interp_state_var (Atom.interp_form_hatom t_i t_func t_atom) t_form in\n    afold_left _ _ true andb (Lit.interp rho) d.\n\n  Lemma add_roots_correct : forall t_i t_func t_atom t_form,\n    let rho := Form.interp_state_var (Atom.interp_form_hatom t_i t_func t_atom) t_form in\n      Form.check_form t_form -> Atom.check_atom t_atom ->\n      Atom.wt t_i t_func t_atom ->\n      forall s d used_roots, S.valid rho s -> valid t_func t_atom t_form d ->\n        S.valid rho (add_roots s d used_roots).\n  Proof.\n    intros t_i t_func t_atom t_form rho H1 H2 H10 s d used_roots H3; unfold valid; intro H4; pose (H5 := (afold_left_andb_true_inv _ _ _ H4)); unfold add_roots; assert (Valuation.wf rho) by (destruct (Form.check_form_correct (Atom.interp_form_hatom t_i t_func t_atom) _ H1) as [_ H]; auto); case used_roots.\n    intro ur; apply (foldi_right_Ind _ _ (fun _ a => S.valid rho a)); auto; intros a i H6 Ha; apply S.valid_set_clause; auto; case_eq (ur .[ i] < length d).\n    intro; unfold C.valid; simpl; rewrite H5; auto.\n    intros; apply C.interp_true; auto.\n    apply (foldi_right_Ind _ _ (fun _ a => S.valid rho a)); auto; intros a i H6 Ha; apply S.valid_set_clause; auto; unfold C.valid; simpl; rewrite H5; auto.\n  Qed.\n\n  Definition checker t_i t_func t_atom t_form d used_roots (c:certif) :=\n    let (nclauses, t, confl) := c in\n    Form.check_form t_form && Atom.check_atom t_atom &&\n    Atom.wt t_i t_func t_atom &&\n    euf_checker t_atom t_form C.is_false (add_roots (S.make nclauses) d used_roots) t confl.\n  Implicit Arguments checker [].\n\n  Lemma checker_correct : forall t_i t_func t_atom t_form d used_roots c,\n    checker t_i t_func t_atom t_form d used_roots c = true ->\n    ~ valid t_func t_atom t_form d.\n  Proof.\n    unfold checker; intros t_i t_func t_atom t_form d used_roots (nclauses, t, confl); rewrite !andb_true_iff; intros [[[H1 H2] H10] H3] H; eelim euf_checker_correct; try eassumption; apply add_roots_correct; try eassumption; apply S.valid_make; destruct (Form.check_form_correct (Atom.interp_form_hatom t_i t_func t_atom) _ H1) as [_ H4]; auto.\n  Qed.\n\n  Definition checker_b t_i t_func t_atom t_form l (b:bool) (c:certif) :=\n    let l := if b then Lit.neg l else l in\n    let (nclauses,_,_) := c in\n    checker t_i t_func t_atom t_form (PArray.make nclauses l) None c.\n\n  Lemma checker_b_correct : forall t_i t_func t_atom t_form l b c,\n    checker_b t_func t_atom t_form l b c = true ->\n    Lit.interp (Form.interp_state_var (Atom.interp_form_hatom t_i t_func t_atom) t_form) l = b.\n  Proof.\n   unfold checker_b; intros t_i t_func t_atom t_form l b (nclauses, t, confl); case b; intros H2; case_eq (Lit.interp (Form.interp_state_var (Atom.interp_form_hatom t_i t_func t_atom) t_form) l); auto; intros H1; elim (checker_correct H2 (t_func:=t_func)); auto; unfold valid; apply afold_left_andb_true; intros i Hi; rewrite get_make; auto; rewrite Lit.interp_neg, H1; auto.\n Qed.\n\n  Definition checker_eq t_i t_func t_atom t_form l1 l2 l (c:certif) :=\n    negb (Lit.is_pos l) &&\n    match t_form.[Lit.blit l] with\n      | Form.Fiff l1' l2' => (l1 == l1') && (l2 == l2')\n      | _ => false\n    end &&\n    let (nclauses,_,_) := c in\n    checker t_i t_func t_atom t_form (PArray.make nclauses l) None c.\n\n  Lemma checker_eq_correct : forall t_i t_func t_atom t_form l1 l2 l c,\n    checker_eq t_func t_atom t_form l1 l2 l c = true ->\n    Lit.interp (Form.interp_state_var (Atom.interp_form_hatom t_i t_func t_atom) t_form) l1 =\n    Lit.interp (Form.interp_state_var (Atom.interp_form_hatom t_i t_func t_atom) t_form) l2.\n  Proof.\n   unfold checker_eq; intros t_i t_func t_atom t_form l1 l2 l (nclauses, t, confl); rewrite !andb_true_iff; case_eq (t_form .[ Lit.blit l]); [intros _ _|intros _|intros _|intros _ _ _|intros _ _|intros _ _|intros _ _|intros _ _ _|intros l1' l2' Heq|intros _ _ _ _]; intros [[H1 H2] H3]; try discriminate; rewrite andb_true_iff in H2; rewrite !Int31Properties.eqb_spec in H2; destruct H2 as [H2 H4]; subst l1' l2'; case_eq (Lit.is_pos l); intro Heq'; rewrite Heq' in H1; try discriminate; clear H1; assert (H:PArray.default t_form = Form.Ftrue /\\ Form.wf t_form).\n   unfold checker in H3; rewrite !andb_true_iff in H3; destruct H3 as [[[H3 _] _] _]; destruct (Form.check_form_correct (Atom.interp_form_hatom t_i t_func t_atom) _ H3) as [[Ht1 Ht2] Ht3]; split; auto.\n   destruct H as [H1 H2]; case_eq (Lit.interp (Form.interp_state_var (Atom.interp_form_hatom t_i t_func t_atom) t_form) l1); intro Heq1; case_eq (Lit.interp (Form.interp_state_var (Atom.interp_form_hatom t_i t_func t_atom) t_form) l2); intro Heq2; auto; elim (checker_correct H3 (t_func:=t_func)); unfold valid; apply afold_left_andb_true; intros i Hi; rewrite get_make; unfold Lit.interp; rewrite Heq'; unfold Var.interp; rewrite Form.wf_interp_form; auto; rewrite Heq; simpl; rewrite Heq1, Heq2; auto.\n Qed.\n\n  (* For debugging *)\n  (*\n  Fixpoint is__true (c:C.t) :=\n    match c with\n      | cons l q => if (l == 0) then true else is__true q\n      | _ => false\n    end.\n\n  Definition step_checker_debug t_atom t_form s (st:step) :=\n    match st with\n      | Res pos res =>\n        let s' := S.set_resolve s pos res in\n          if is__true (s'.[pos]) then None else Some s'\n      | ImmFlatten pos cid lf =>\n        let c := check_flatten t_atom t_form s cid lf in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | CTrue pos => Some (S.set_clause s pos Cnf.check_True)\n      | CFalse pos => Some (S.set_clause s pos Cnf.check_False)\n      | BuildDef pos l =>\n        let c := check_BuildDef t_form l in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | BuildDef2 pos l =>\n        let c := check_BuildDef2 t_form l in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | BuildProj pos l i =>\n        let c := check_BuildProj t_form l i in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | ImmBuildDef pos cid =>\n        let c := check_ImmBuildDef t_form s cid in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | ImmBuildDef2 pos cid =>\n        let c := check_ImmBuildDef2 t_form s cid in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | ImmBuildProj pos cid i =>\n        let c := check_ImmBuildProj t_form s cid i in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | EqTr pos l fl =>\n        let c := check_trans t_form t_atom l fl in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | EqCgr pos l fl =>\n        let c := check_congr t_form t_atom l fl in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | EqCgrP pos l1 l2 fl =>\n        let c := check_congr_pred t_form t_atom l1 l2 fl in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | LiaMicromega pos cl c =>\n        let c := check_micromega t_form t_atom cl c in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | LiaDiseq pos l =>\n        let c := check_diseq t_form t_atom l in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | SplArith pos orig res l =>\n        let c := check_spl_arith t_form t_atom (S.get s orig) res l in\n          if is__true c then None else Some (S.set_clause s pos c)\n      | SplDistinctElim pos input res =>\n        let c := check_distinct_elim t_form t_atom (S.get s input) res in\n          if is__true c then None else Some (S.set_clause s pos c)\n    end.\n\n  Definition euf_checker_debug t_atom t_form s t :=\n    _checker_debug_ (step_checker_debug t_atom t_form) s t.\n\n  Definition euf_checker_partial t_atom t_form s t :=\n    _checker_partial_ (step_checker t_atom t_form) s t.\n  *)\n\nEnd Euf_Checker.\n\n\nUnset Implicit Arguments.\n", "meta": {"author": "smtcoq", "repo": "smtcoq-resource", "sha": "610c01d5898c74f3372c871085e7c623c72b3873", "save_path": "github-repos/coq/smtcoq-smtcoq-resource", "path": "github-repos/coq/smtcoq-smtcoq-resource/smtcoq-resource-610c01d5898c74f3372c871085e7c623c72b3873/src/Trace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2448946433146656}}
{"text": "(** * Definition of the generic part of the interface of the correctness proof of the CFG parser *)\n\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.GenericBaseTypes.\nRequire Import Fiat.Parsers.BaseTypes.\n\nSet Implicit Arguments.\n\nSection correctness.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char}\n          {predata : @parser_computational_predataT Char}\n          {gendata : @generic_parser_dataT Char}.\n\n  Class generic_parser_decidable_data {gendata : @generic_parser_dataT Char} :=\n    {\n      parse_nt_T_to_bool : parse_nt_T -> bool;\n      parse_item_T_to_bool : parse_item_T -> bool;\n      parse_production_T_to_bool : parse_production_T -> bool;\n      parse_productions_T_to_bool : parse_productions_T -> bool\n    }.\n\n  Class generic_parser_decidable_correctness_data {gendata : @generic_parser_dataT Char} {gddata : generic_parser_decidable_data} :=\n    {\n      ret_Terminal_true_to_bool\n      : forall ch, parse_item_T_to_bool (ret_Terminal_true ch) = true;\n      ret_Terminal_false_to_bool\n      : forall ch, parse_item_T_to_bool (ret_Terminal_false ch) = false;\n      ret_NonTerminal_true_to_bool\n      : forall nt rv, parse_item_T_to_bool (ret_NonTerminal_true nt rv) = parse_nt_T_to_bool rv;\n      ret_NonTerminal_false_to_bool\n      : forall nt, parse_item_T_to_bool (ret_NonTerminal_false nt) = false;\n      ret_production_nil_true_to_bool\n      : parse_production_T_to_bool ret_production_nil_true = true;\n      ret_production_nil_false_to_bool\n      : parse_production_T_to_bool ret_production_nil_false = false;\n      ret_orb_production_base_to_bool\n      : parse_production_T_to_bool ret_orb_production_base = false;\n      ret_orb_production_to_bool\n      : forall rv1 rv2, parse_production_T_to_bool (ret_orb_production rv1 rv2)\n                        = orb (parse_production_T_to_bool rv1) (parse_production_T_to_bool rv2);\n      ret_production_cons_to_bool\n      : forall rv1 rv2, parse_production_T_to_bool (ret_production_cons rv1 rv2)\n                        = andb (parse_item_T_to_bool rv1) (parse_production_T_to_bool rv2);\n      ret_orb_productions_base_to_bool\n      : parse_productions_T_to_bool ret_orb_productions_base = false;\n      ret_orb_productions_to_bool\n      : forall rv1 rv2, parse_productions_T_to_bool (ret_orb_productions rv1 rv2)\n                        = orb (parse_production_T_to_bool rv1) (parse_productions_T_to_bool rv2);\n      ret_nt_to_bool\n      : forall nt v, parse_nt_T_to_bool (ret_nt nt v) = parse_productions_T_to_bool v;\n      ret_nt_invalid_to_bool\n      : parse_nt_T_to_bool ret_nt_invalid = false\n    }.\nEnd correctness.\n\nCreate HintDb generic_parser_decidable_correctness discriminated.\n#[global]\nHint Rewrite @ret_Terminal_true_to_bool @ret_Terminal_false_to_bool @ret_NonTerminal_true_to_bool @ret_NonTerminal_false_to_bool @ret_production_nil_true_to_bool @ret_production_nil_false_to_bool @ret_orb_production_base_to_bool @ret_orb_production_to_bool @ret_production_cons_to_bool @ret_orb_productions_base_to_bool @ret_orb_productions_to_bool @ret_nt_to_bool @ret_nt_invalid_to_bool : generic_parser_decidable_correctness.\n\nLemma fold_right_ret_orb_production_eq\n      {Char}\n      {gendata : @generic_parser_dataT Char}\n      {gddata : generic_parser_decidable_data}\n      {gdcdata : generic_parser_decidable_correctness_data}\n      ls b\n  : parse_production_T_to_bool (List.fold_right ret_orb_production b ls)\n    = List.fold_right orb (parse_production_T_to_bool b) (List.map parse_production_T_to_bool ls).\nProof.\n  revert b; induction ls as [|?? IHls]; simpl; trivial; intros; [].\n  rewrite <- IHls; clear IHls.\n  autorewrite with generic_parser_decidable_correctness; trivial.\nQed.\n\nLemma fold_right_ret_orb_productions_eq\n      {Char}\n      {gendata : @generic_parser_dataT Char}\n      {gddata : generic_parser_decidable_data}\n      {gdcdata : generic_parser_decidable_correctness_data}\n      ls b\n  : parse_productions_T_to_bool (List.fold_right ret_orb_productions b ls)\n    = List.fold_right orb (parse_productions_T_to_bool b) (List.map parse_production_T_to_bool ls).\nProof.\n  revert b; induction ls as [|?? IHls]; simpl; trivial; intros; [].\n  rewrite <- IHls; clear IHls.\n  autorewrite with generic_parser_decidable_correctness; trivial.\nQed.\n\n#[global]\nHint Rewrite @fold_right_ret_orb_production_eq @fold_right_ret_orb_productions_eq : generic_parser_decidable_correctness.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/GenericBoolCorrectnessBaseTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2448946368113344}}
{"text": "Set Implicit Arguments.\nSet Bullet Behavior \"Strict Subproofs\".\n\nRequire Import Bool String List ZArith.\nImport ListNotations.\nOpen Scope string.\nOpen Scope list.\nFrom coqutil Require Import Map.Interface.\nFrom Utils Require Import Utils Natlike ExtraMaps Monad RelationalDB.\nImport Sets.\nFrom Utils Require ArrayList UnionFind.\nFrom Named Require Import Term Rule Core.\nFrom Named.egraph Require Import Defs.\nImport StateMonad.\n\nSection __.\n  Context {idx : Type}\n          `{Natlike idx}\n          {array : Type -> Type}\n          `{ArrayList.ArrayList idx array}.\n  \n  Notation named_list := (@named_list idx).\n  Notation named_map := (@named_map idx).\n  Notation term := (@term idx).\n  Notation ctx := (@ctx idx).\n  Notation sort := (@sort idx).\n  Notation subst := (@subst idx).\n  Notation rule := (@rule idx).\n  Notation lang := (@lang idx).\n\n  Notation union_find := (@UnionFind.union_find idx array).\n\n\n  (*TODO: gather all contexts from (& in) Defs.v*)\n  Context (eclass_map : map.map idx eclass).\n\n  Notation egraph := (egraph (array:=array) eclass_map).\n  Notation empty_egraph := (empty_egraph eclass_map).\n  Notation find := (find (eclass_map := eclass_map)).\n  \n  Context (idx_set : set idx).\n  Context (eqn_set : set (idx*idx)).\n\n  \n  (*Parameterize by query trie since the inductive can't be defined generically *)\n  Context (query_trie : Type)\n          (qt_unconstrained : query_trie -> query_trie)\n          (trie_map : map.map idx query_trie)\n          (qt_tree : trie_map -> query_trie)\n          (values_of_next_var : query_trie -> set_with_top idx_set)\n          (choose_next_val : idx -> query_trie -> query_trie).\n  Context (relation : set (list idx))\n          (db : map.map idx relation)\n          (arg_map : map.map idx idx).\n\n  \n  Section WithLang.\n\n    Context (l : lang).\n    \n    Notation check_ctx' :=\n      (check_ctx' (idx:=idx) (array := array)\n                  eclass_map eqn_set l\n                  qt_unconstrained _ qt_tree\n                  values_of_next_var choose_next_val relation db arg_map).\n    \n    Notation check_ctx :=\n      (check_ctx (idx:=idx) (array := array)\n                 eclass_map eqn_set l\n                 qt_unconstrained _ qt_tree\n                 values_of_next_var choose_next_val relation db arg_map).\n\n    Notation add_and_check_ctx_cons :=\n      (add_and_check_ctx_cons eqn_set l qt_unconstrained trie_map qt_tree values_of_next_var choose_next_val relation db arg_map).\n\n    Notation Checker :=\n      (Checker eclass_map eqn_set).\n\n    Notation equality_saturation :=\n      (equality_saturation l qt_unconstrained trie_map qt_tree values_of_next_var choose_next_val relation db\n       arg_map).\n    \n    Notation resolve_checker' :=\n      (resolve_checker' l qt_unconstrained trie_map qt_tree values_of_next_var choose_next_val relation db arg_map).\n\n    \n    (*possibly poor naming*)\n    Definition principal_sort c e : option sort :=\n      match e with\n      | var x => named_list_lookup_err c x\n      | con n s =>\n          @! let (term_rule c' _ t) <?- named_list_lookup_err l n in\n             ret t[/with_names_from c' s/]\n      end.\n\n    (*TODO: what's the best way to define this?\n      In terms of find or in parallel?\n      TODO: Move to UnionFind.v\n     *)\n    Definition union_find_equivalence uf a b :=\n      snd (UnionFind.find uf a) = snd (UnionFind.find uf b).\n\n    Inductive term_in_egraph_at_index (g : egraph) i : term -> Prop :=\n    | var_in_egraph v\n      : map.get g.(hashcons) (var_node v) = Some i ->\n        term_in_egraph_at_index g i (var v)\n    | con_in_egraph n s s_i\n      : Forall2 (term_in_egraph_at_index g) s_i s ->\n        (*TODO: handle s_i up to uf_equiv? *)\n        map.get g.(hashcons) (con_node n s_i) = Some i ->\n        term_in_egraph_at_index g i (con n s).\n    \n    Variant sort_in_egraph_at_index (g : egraph) i : sort -> Prop :=\n    | scon_in_egraph n s s_i\n      : Forall2 (term_in_egraph_at_index g) s_i s ->\n        (*TODO: handle s_i up to uf_equiv? *)\n        map.get g.(hashcons) (con_node n s_i) = Some i ->\n        sort_in_egraph_at_index g i (scon n s).\n        \n    Definition is_ctx_of_egraph (g : egraph) (c : ctx) : Prop :=\n      Forall2 (fun '(x1,i) '(x2,t) => x1 = x2 /\\ sort_in_egraph_at_index g i t)\n              g.(ectx) c.\n\n    Section WithCtx.\n      Context (wfl : wf_lang l)\n              (c : ctx)\n              (wfc : wf_ctx l c).\n\n      Definition wf_egraph g (wf_ids : list idx) :=\n        all (fun x => In x wf_ids) (map snd g.(ectx))\n        /\\ is_ctx_of_egraph g c\n        /\\ (forall t1 t2 i,\n               sort_in_egraph_at_index g i t1 ->\n               sort_in_egraph_at_index g i t2 ->\n               In i wf_ids ->\n               eq_sort l c t1 t2)\n        /\\ (forall e1 e2 t i,\n               term_in_egraph_at_index g i e1 ->\n               term_in_egraph_at_index g i e2 ->\n               In i wf_ids ->\n               (*TODO: does it matter whether the sort is in the egraph?*)\n               principal_sort c e1 = Some t ->\n               eq_term l c t e1 e2).\n\n      Lemma wf_egraph_sort_wf g wf_ids t i\n        : wf_egraph g wf_ids ->\n          sort_in_egraph_at_index g i t ->\n          In i wf_ids ->\n          wf_sort l c t.\n      Proof.\n        unfold wf_egraph.\n        basic_goal_prep.\n        eapply eq_sort_wf_l; eauto.\n      Qed.\n\n      \n      Lemma wf_egraph_term_wf g wf_ids e t i\n        : wf_egraph g wf_ids ->\n          term_in_egraph_at_index g i e ->\n          In i wf_ids ->\n          (*TODO: does it matter whether the sort is in the egraph?*)\n          principal_sort c e = Some t ->\n          wf_term l c e t.\n      Proof.\n        unfold wf_egraph.\n        basic_goal_prep.\n        eapply eq_term_wf_l; eauto.\n      Qed.\n\n      (*TODO: allow context extension?*)\n      Definition egraph_extends g1 g2 :=\n        (forall e i, term_in_egraph_at_index g1 i e ->\n                     term_in_egraph_at_index g2 i e)\n        /\\ (forall t i, sort_in_egraph_at_index g1 i t ->\n                        sort_in_egraph_at_index g2 i t)\n        /\\ (forall i j, union_find_equivalence g1.(id_equiv) i j ->\n                        union_find_equivalence g2.(id_equiv) i j).\n\n      Lemma egraph_extends_refl g : egraph_extends g g.\n      Proof.\n        unfold egraph_extends; intuition.\n      Qed.\n      \n    End WithCtx.\n\n    \n    Lemma empty_egraph_is_wf : wf_egraph [] empty_egraph [].\n    Proof.\n      unfold wf_egraph, is_ctx_of_egraph; basic_goal_prep; basic_utils_crush.\n    Qed.\n\n    \n    Definition indexed_terms_related c g i1 i2 :=\n      (forall t1 t2,\n          sort_in_egraph_at_index g i1 t1 ->\n          sort_in_egraph_at_index g i2 t2 ->\n          eq_sort l c t1 t2)\n      /\\ (forall e1 e2 t,\n             term_in_egraph_at_index g i1 e1 ->\n             term_in_egraph_at_index g i2 e2 ->\n             (*TODO: does it matter whether the sort is in the egraph?*)\n             principal_sort c e1 = Some t ->\n             eq_term l c t e1 e2).\n    \n    Definition up_to_checking {A} P (ch : Checker A) c\n      := forall g g' a eqns, ch g = (g', Some (a,eqns)) ->\n                            (forall i j, member eqns (i,j) = true ->\n                                         indexed_terms_related c g i j) ->\n                     P g' a.\n\n    \n    Lemma equality_saturation_sound {A} upd pred base fuel g g' (a:A) c good_ids\n      : (g', a) = equality_saturation upd pred base fuel g ->\n        wf_egraph c g good_ids ->\n        egraph_extends g g'\n        /\\ wf_egraph c g' good_ids.\n    Proof.\n      revert g g' a base.\n      induction fuel; basic_goal_prep.\n      {\n        basic_utils_crush.\n        eapply egraph_extends_refl.\n      }\n      {\n        revert H1; case_match.\n        {\n          basic_utils_crush.\n          eapply egraph_extends_refl.\n        }\n        {\n          TODO: db reasoning\n        \n    Qed.\n      \n    \n    Lemma resolve_checker'_sound {A} g fuel ch g' (a : A) P c\n      : (g', Some a) = resolve_checker' ch fuel g ->\n        up_to_checking P ch c ->\n        P g' a.\n    Proof.\n      unfold resolve_checker'.\n      simpl.\n      case_match.\n      case_match; [| cbv; congruence].\n      destruct p.\n      case_match.\n      case_match; [| cbv; congruence].\n      intro H'; inversion H'; subst; clear H'.\n\n\n      \n      case_match.\n      \n    Qed.\n    \n    Lemma add_and_check_ctx_cons_sound i t c g g' good_ids\n      : (g',true) = add_and_check_ctx_cons i t g ->\n        wf_egraph c g good_ids ->\n        fresh i c ->\n        exists good_ids',\n          wf_egraph ((i,t)::c) g' (good_ids'++good_ids).\n    Proof.\n      unfold add_and_check_ctx_cons.\n      \n      case_match.\n      [| cbv; congruence].\n      case\n    Qed.\n\n    Lemma check_ctx'_sound c g\n      : check_ctx' c = Some g -> exists good_ids, wf_egraph c g good_ids.\n      revert g.\n      induction c; basic_goal_prep; basic_utils_crush.\n      { eexists;now eapply empty_egraph_is_wf. }\n      {\n        revert H1.\n        case_match; [| cbv; congruence].\n        symmetry in HeqH1; apply use_compute_fresh in HeqH1.\n        case_match; [| cbv; congruence].\n        specialize (IHc e eq_refl); destruct IHc.\n        case_match.\n        destruct b; [| cbv; congruence].\n        basic_goal_prep; basic_utils_crush.\n        eapply add_and_check_ctx_cons_sound in HeqH2; eauto.\n        destruct HeqH2; eexists; eauto.\n      }\n    Qed.\n\n        \n        \n    Abort.\n    \n    (*TODO: do I want a lookup_term function in defs?*)\n    \n    (*Properties I expect to hold:*)\n\n             \n                      \n      \n    \n    Lemma check_ctx'_sound c g\n      : check_ctx' c = Some g -> wf_egraph g.\n    Abort.\n    \n    Theorem check_ctx_sound c\n      : check_ctx c = true -> wf_ctx l c.\n    Abort.\n    \n    Lemma find_idempotent\n      : find i1 g1 = (g2,i2) ->\n        find i2 g2 = (g2,i2).\n    Abort.\n\n    \n    (*Possibly useful definitions*)\n\n    (*possibly poor naming*)\n    Definition principal_sort l c e : option sort :=\n      match e with\n      | var x => named_list_lookup_err c x\n      | con n s =>\n          @! let (term_rule c' _ t) <?- named_list_lookup_err l n in\n             ret t[/with_names_from c' s/]\n      end.\n", "meta": {"author": "DIJamner", "repo": "pyrosome", "sha": "a8d7f0aa3141b35a3c59d8d72aadf47a3b0c5df6", "save_path": "github-repos/coq/DIJamner-pyrosome", "path": "github-repos/coq/DIJamner-pyrosome/pyrosome-a8d7f0aa3141b35a3c59d8d72aadf47a3b0c5df6/WIP/EGraph/Proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.24484930975070635}}
{"text": "Set Warnings \"-notation-overridden\".\nSet Warnings \"-spurious-ssr-injection\".\n\nRequire Import LinearScan.Lib.\nRequire Import LinearScan.Context.\nRequire Import LinearScan.UsePos.\nRequire Import LinearScan.Range.\nRequire Import LinearScan.Interval.\nRequire Import LinearScan.Blocks.\nRequire Import LinearScan.ScanState.\nRequire Import LinearScan.Morph.\nRequire Import LinearScan.Cursor.\nRequire Import LinearScan.Spec.\nRequire Import LinearScan.Spill.\nRequire Import LinearScan.Split.\nRequire Import Coq.Program.Wf.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nGeneralizable All Variables.\n\nSection Allocate.\n\nVariable maxReg : nat.          (* max number of registers *)\nHypothesis registers_exist : maxReg > 0.\nDefinition PhysReg := 'I_maxReg.\n\nOpen Scope program_scope.\n\nDefinition intersectsWithFixedInterval {pre} (reg : PhysReg) :\n  SState pre (@SSMorphHasLen maxReg) (@SSMorphHasLen maxReg) (option nat) :=\n  withCursor (maxReg:=maxReg) $ fun sd cur =>\n    ipure $ if vnth (fixedIntervals sd) reg is Some i\n            then intervalIntersectsWithSubrange (curIntDetails cur).1 i.1\n            else None.\n\nDefinition updateRegisterPos (v : Vec (option nat) maxReg)\n  (r : PhysReg) (p : option nat) : Vec (option nat) maxReg :=\n  match p with\n  | None => v\n  | Some x => vreplace v r (Some (match vnth v r with\n                                  | Some n => if n < x then n else x\n                                  | None   => x\n                                  end))\n  end.\n\nDefinition findEligibleRegister (sd : ScanStateDesc maxReg)\n  `(current : Interval d) xs : PhysReg * option nat :=\n  (* Make sure that if there's a fixed interval that intersection with the\n     current interval, that we indicate that the register is only free up\n     until that point. *)\n  let: (xs, fixedAndIntersects) :=\n    vfoldl_with_index (fun reg acc (mint : option IntervalSig) =>\n      let: (fup, fai) := acc in\n      if mint is Some int\n      then let op := intervalIntersectsWithSubrange current int.2 in\n           (updateRegisterPos fup reg op, vreplace fai reg (isSome op))\n      else acc) (xs, vconst false) (fixedIntervals sd) in\n  registerWithHighestPos registers_exist fixedAndIntersects xs.\n\n(** If [tryAllocateFreeReg] fails to allocate a register, the [ScanState] is\n    left unchanged.  If it succeeds, or is forced to split [current], then a\n    register will have been assigned. *)\nDefinition tryAllocateFreeReg {pre} :\n  SState pre (@SSMorphHasLen maxReg) (@SSMorphHasLen maxReg)\n    (option (SState pre (@SSMorphHasLen maxReg) (@SSMorph maxReg) PhysReg)) :=\n  withCursor (maxReg:=maxReg) $ fun sd cur =>\n    let current := curInterval cur in\n\n    (* set freeUntilPos of all physical registers to maxInt\n       for each interval it in active do\n         freeUntilPos[it.reg] = 0\n       for each interval it in inactive intersecting with current do\n         freeUntilPos[it.reg] = next intersection of it with current *)\n    let go f v p := let: (i, r) := p in updateRegisterPos v r (f i) in\n    let actives := foldl (go (fun _ => Some 0)) (vconst None) (active sd) in\n    let freeUntilPos :=\n        foldl (go (fun i => intervalsIntersect current (getInterval i)))\n          actives (inactive sd) in\n\n    (* reg = register with highest freeUntilPos *)\n    (* mres = highest use position of the found register *)\n    let (reg, mres) := findEligibleRegister sd current freeUntilPos in\n\n    (** [moveUnhandledToActive] not only moves an [IntervalId] from the\n        [unhandled] list to the [active] list in the current [ScanStateDesc],\n        it also assigns a register to the newly active interval that can be\n        accessed by calling [getAssignment]. *)\n    let success := moveUnhandledToActive reg ;;; ipure reg in\n\n    let cid := curId cur in\n    context (ETryAllocateFreeReg reg mres (fst cid)) $\n      ipure $\n        match mres with\n        | None => Some success\n        | Some n =>\n          (* if freeUntilPos[reg] = 0 then\n               // no register available without spilling\n               allocation failed\n             else if current ends before freeUntilPos[reg] then\n               // register available for the whole interval\n               current.reg = reg\n             else\n               // register available for the first part of the interval\n               current.reg = reg\n               split current before freeUntilPos[reg] *)\n          if n <= intervalStart current\n          then None\n          else @Some _ $\n            if intervalEnd current < n\n            then success\n            else splitCurrentInterval (BeforePos n) ;;;\n                 success\n        end.\n\n(** If [allocateBlockedReg] fails, it's possible no register was assigned and\n    that the only outcome was to split one or more intervals.  In either case,\n    the change to the [ScanState] must be a productive one. *)\nDefinition allocateBlockedReg {pre} :\n  SState pre (@SSMorphHasLen maxReg) (@SSMorph maxReg) (option PhysReg) :=\n  withCursor (maxReg:=maxReg) $ fun sd cur =>\n    let current := curInterval cur in\n    let pos     := intervalStart current in\n\n    (* set nextUsePos of all physical registers to maxInt\n       for each interval it in active do\n         nextUsePos[it.reg] = next use of it after start of current\n       for each interval it in inactive intersecting with current do\n         nextUsePos[it.reg] = next use of it after start of current *)\n    let go (v : Vec (option nat) maxReg) (p : IntervalSig * PhysReg) :=\n        let: (int, reg) := p in\n        let atPos u := (pos == uloc u) && regReq u in\n        let pos' :=\n            (* In calculating the highest use position of this register, if we\n               know that it is being used at the current position, then it\n               cannot be spilled there, and so we try to take it out of the\n               running by returning one. *)\n            match findIntervalUsePos int.2 atPos with\n            | Some _ => Some 0\n            | None   => nextUseAfter int.2 pos\n            end in\n        updateRegisterPos v reg pos' in\n\n    let resolve xs :=\n        [seq (packInterval (getInterval (fst i)), snd i) | i <- xs] in\n    let actives := foldl go (vconst None) (resolve (active sd)) in\n    let nextUsePos'' :=\n        foldl go actives (filter (fun x => intervalsIntersect current (fst x).1)\n                                 (resolve (inactive sd))) in\n\n    (* reg = register with highest nextUsePos *)\n    (* mres = highest use position of the found register *)\n    let (reg, mres) := findEligibleRegister sd current nextUsePos'' in\n\n    let cid := curId cur in\n    context (EAllocateBlockedReg reg mres (fst cid)) $\n      if (match mres with\n          | None   => false\n          | Some n =>\n              n < if lookupUsePos current (fun u => pos <= uloc u)\n                       is Some (nextUse; _)\n                  then nextUse\n                  else intervalEnd current\n          end)\n      then\n        (* if first usage of current is after nextUsePos[reg] then\n             // all other intervals are used before current, so it is best\n             // to spill current itself\n             assign spill slot to current\n             split current before its first use position that requires a\n               register *)\n        @spillCurrentInterval maxReg pre ;;;\n\n        (* // make sure that current does not intersect with\n           // the fixed interval for reg\n           if current intersects with the fixed interval for reg then\n             split current before this intersection *)\n\n        (* The allocation failed, so we had to spill some part of the current\n           interval instead. *)\n        ipure None\n      else\n        (* // spill intervals that currently block reg\n           current.reg = reg\n           split active interval for reg at position\n           split any inactive interval for reg at the end of its lifetime\n             hole *)\n        splitAnyInactiveIntervalForReg reg pos ;;;\n        splitActiveIntervalForReg reg pos ;;;\n\n        (* The remaining part of these active and inactive intervals go back\n           onto the unhandled list; the former part goes onto the inact list. *)\n\n        (* // make sure that current does not intersect with\n           // the fixed interval for reg\n           if current intersects with the fixed interval for reg then\n             split current before this intersection *)\n        mloc <<- intersectsWithFixedInterval reg ;;;\n        match mloc with\n        | Some n => context (EIntersectsWithFixedInterval n reg) $\n                      splitCurrentInterval (BeforePos n)\n        | None   => ipure tt\n        end ;;;\n\n        moveUnhandledToActive reg ;;;\n        ipure $ Some reg.\n\nDefinition morphlen_transport {b b'} :\n  @SSMorphLen maxReg b b' -> IntervalId b -> IntervalId b'.\nProof.\n  case. case=> ? ?.\n  exact: (widen_ord _).\nDefined.\n\nDefinition mt_fst b b' (sslen : SSMorphLen b b')\n  (x : IntervalId b * PhysReg) :=\n  let: (xid, reg) := x in (morphlen_transport sslen xid, reg).\n\nNotation int_reg sd := (@IntervalId maxReg sd * PhysReg)%type.\nDefinition int_reg_seq sd := seq (int_reg sd).\n\nDefinition intermediate_result (sd z : ScanStateDesc maxReg)\n  (xs : int_reg_seq z)\n  (f : forall sd' : ScanStateDesc maxReg, int_reg_seq sd') :=\n  { res : {z' : ScanStateDesc maxReg | SSMorphLen z z'}\n  | (ScanState InUse res.1 /\\ SSMorphLen sd res.1)\n  & subseq [seq mt_fst res.2 i | i <- xs] (f res.1) }.\n\nProgram Definition goActive (pos : nat) (sd : ScanStateDesc maxReg)\n  (e : seq SSTrace) (z : ScanStateDesc maxReg)\n  (Pz : ScanState InUse z /\\ SSMorphLen sd z)\n  (x : int_reg z) (xs : int_reg_seq z)\n  (Hsub : subseq (x :: xs) (active z)) :\n  seq SSTrace + intermediate_result sd xs (@active maxReg) :=\n  (* for each interval it in active do\n       if it ends before position then\n         move it from active to handled\n       else if it does not cover position then\n         move it from active to inactive *)\n  let: conj st sslen := Pz in\n  let i := getInterval (fst x) in\n  let Hin : x \\in active z := @in_subseq_sing _ _ _ x xs _ Hsub in\n  let eres :=\n    if intervalEnd i < pos\n    then\n      if prop (verifyNewHandled z i (snd x)) isn't Some Hreq\n      then let: (p1, p2) := x in\n           inl (ERegisterAssignmentsOverlap p2 p1 1 :: e)\n      else let: exist2 x H1 H2 :=\n             moveActiveToHandled st Hin Hreq (spilled:=false) in\n           inr (exist2 _ _ x H1 (proj1 H2))\n    else inr $ if ~~ posWithinInterval i pos\n               then moveActiveToInactive st Hin\n               else exist2 _ _ z st (newSSMorphLen z) in\n  match eres with\n  | inl err => inl err\n  | inr (exist2 sd' st' sslen') =>\n      inr (exist2 _ _ (sd'; sslen')\n                  (conj st' (transitivity sslen sslen')) _)\n  end.\nNext Obligation.\n  move: Heq_eres.\n\n  case: (iend (vnth (intervals z) i).1 < pos);\n  case: (prop (verifyNewHandled z (vnth (intervals z) i).1 p)) => a;\n  try discriminate.\n\n  - rewrite /moveActiveToHandled /=.\n    invert as [H1]; subst; simpl.\n    rewrite /mt_fst /morphlen_transport /=.\n    case: sslen'.\n    case=> [[?] _].\n    rewrite map_widen_ord_refl.\n    exact: subseq_cons_rem.\n\n  - case: (~~ (ibeg (vnth (intervals z) i).1\n             <= pos < iend (vnth (intervals z) i).1)).\n      rewrite /moveActiveToInactive /=.\n      invert as [H1]; subst; simpl.\n      rewrite /mt_fst /morphlen_transport /=.\n      case: sslen'.\n      case=> [[?] _].\n      rewrite map_widen_ord_refl.\n      exact: subseq_cons_rem.\n\n    invert as [H1]; subst; simpl.\n    rewrite /mt_fst /morphlen_transport /=.\n    case: sslen'.\n    case=> [[?] _].\n    rewrite map_widen_ord_refl.\n    apply: subseq_impl_cons.\n    exact Hsub.\n\n  - case: (~~ (ibeg (vnth (intervals z) i).1\n             <= pos < iend (vnth (intervals z) i).1)) in a *.\n      inv a.\n      rewrite /mt_fst /morphlen_transport /=.\n      case: sslen'.\n      case=> [[?] _].\n      rewrite map_widen_ord_refl.\n      exact: subseq_cons_rem.\n    inv a.\n    rewrite /mt_fst /morphlen_transport /=.\n    case: sslen'.\n    case=> [[?] _].\n    rewrite map_widen_ord_refl.\n    apply: subseq_impl_cons.\n    exact Hsub.\nQed.\n\n(* This rather excessively complicated, dependent fold function is needed in\n   order to walk through a list of intervals of a [ScanState] (which have a\n   type dependent on that [ScanState]), while at the same time mutating the\n   same [ScanState] and adjusting the type of the remainder of the interval\n   list, such that it is known to still have a relationship with the new\n   [ScanState]. *)\nProgram Fixpoint dep_foldl_invE\n  {errType : Type}              (* the short-circuiting error type *)\n  {A : Type}                    (* the value being mutated through the fold *)\n  {P : A -> Prop}               (* inductive predicate to be maintained on A *)\n  {R : A -> A -> Prop}          (* a relation on A that must be preserved *)\n  {E : A -> eqType}             (* type of the elements we are folding over *)\n  (b : A)                       (* the initial state value *)\n  (Pb : P b)                    (* predicate on the initial state value *)\n  (v : seq (E b))               (* list of elements from the initial state *)\n\n  (n : nat)                     (* the length of this list (as a [nat]) *)\n  (* The reason to [nat] rather than [size v] is that the type of v changes\n     with each iteration of the fold, which confuses [Program Fixpoint] enough\n     that it fails to compute the final proof term even after ten minutes. *)\n\n  (Hn : n == size v)            (* witness that [length == size v] *)\n  (Q : forall x : A, seq (E x)) (* function that can determine [v] from [b] *)\n  (Hsub : subseq v (Q b))       (* a proof that [v] is a subseq of [Q b] *)\n\n  (F : forall (b b' : A) (Rbb' : R b b'), E b -> E b')\n                                (* transports element types between states *)\n\n  (* The fold function [f] takes an intermediate state, a witness for the\n     inductive predicate on that state, an element from the initial list which\n     is known to be related to that state (and whose type has been transported\n     to relate to that state), the list of remaining elements to be processed\n     by the fold, and proof that this element and remaining list are at least\n     a subsequence of the state.\n         The expected result is a new state, proof that this new state relates\n     to the incoming state in terms of [R] (which must be transitive), proof\n     that the inductive predicate holds for this new state, and proof that the\n     transported remainder [xs] is also a subsequence of the list determined\n     by [Q] from the new state. *)\n  (f : forall (z : A) (Pz : P z) (x : E z) (xs : seq (E z)),\n         subseq (x :: xs) (Q z)\n           -> errType +\n              { res : { z' : A | R z z' }\n              | P res.1 & subseq (map (F z res.1 res.2) xs) (Q res.1) })\n\n  (* The fold is done when [n] reaches zero *)\n  {struct n} :\n  (* The result is a final, inductively predicated state *)\n  errType + { b' : A | P b' } :=\n  match (v, n) with\n  | (y :: ys, S n') =>\n      match f b Pb y ys Hsub with\n      | inl err => inl err\n      | inr (exist2 (exist b' Rbb') Pb' Hsub') =>\n          let ys' := map (F b b' Rbb') ys in\n          @dep_foldl_invE errType A P R E b' Pb' ys' n' _ Q Hsub' F f\n      end\n  | _ => inr (exist P b Pb)\n  end.\nObligation 2.\n  first [ inversion Heq_anonymous;\n          subst;\n          clear Heq_anonymous0;\n          move: eqSS Hn => /= -> /eqP ->;\n          by rewrite size_map\n        | inversion Heq_anonymous0;\n          subst;\n          clear Heq_anonymous;\n          move: eqSS Hn => /= -> /eqP ->;\n          by rewrite size_map ].\nQed.\n\nDefinition checkActiveIntervals {pre} (pos : nat) :\n  SState pre (@SSMorphLen maxReg) (@SSMorphLen maxReg) unit :=\n  withScanStatePO (maxReg:=maxReg) $ fun sd (st : ScanState InUse sd) =>\n    e <<- Context.iask ;;;\n    let unchanged := exist2 _ _ sd st (newSSMorphLen sd) in\n    let eres : seq SSTrace + { sd' : ScanStateDesc maxReg\n                             | ScanState InUse sd' /\\ SSMorphLen sd sd' } :=\n        @dep_foldl_invE (seq SSTrace) (ScanStateDesc maxReg)\n          (fun sd' => ScanState InUse sd' /\\ SSMorphLen sd sd')\n          (@SSMorphLen maxReg) _ sd (conj st (newSSMorphLen sd))\n          (active sd) (size (active sd)) (eq_refl _)\n          (@active maxReg) (subseq_refl _) mt_fst (@goActive pos sd e) in\n    match eres with\n    | inl err => error_ err\n    | inr (exist sd' (conj st' H)) =>\n        Context.iput {| thisDesc  := sd'\n                      ; thisHolds := H\n                      ; thisState := st' |}\n    end.\n\nProgram Definition moveInactiveToActive' `(st : ScanState InUse z)\n  (x : int_reg z) (xs : int_reg_seq z)\n  (Hsub : subseq (x :: xs) (inactive z))\n  (Hin : x \\in inactive z) (e : seq SSTrace) :\n  seq SSTrace +\n  { sd' : ScanStateDesc maxReg | ScanState InUse sd'\n  & { sslen : SSMorphLen z sd'\n    | subseq [seq mt_fst sslen i | i <- xs] (inactive sd')\n    }\n  } :=\n  match snd x \\notin [seq snd i | i <- active z] with\n  | true  =>\n      match moveInactiveToActive st Hin _ with\n      | exist2 sd' st' sslen' =>\n          inr (exist2 _ _ sd' st' (sslen'; _))\n      end\n  | false =>\n      let: (p1, p2) := x in\n      inl (ERegisterAssignmentsOverlap p2 p1 2 :: e)\n  end.\nNext Obligation.\n  rewrite /moveActiveToInactive /mt_fst /morphlen_transport /=.\n  case: sslen'; case=> [[?] _].\n  rewrite map_widen_ord_refl.\n  exact: subseq_cons_rem.\nDefined.\n\nProgram Definition goInactive (pos : nat) (sd : ScanStateDesc maxReg)\n  (e : seq SSTrace) (z : ScanStateDesc maxReg)\n  (Pz : ScanState InUse z /\\ SSMorphLen sd z)\n  (x : int_reg z) (xs : int_reg_seq z)\n  (Hsub : subseq (x :: xs) (inactive z)) :\n  seq SSTrace + intermediate_result sd xs (@inactive maxReg) :=\n  (* for each interval it in inactive do\n       if it ends before position then\n         move it from inactive to handled\n       else if it covers position then\n         move it from inactive to active *)\n  let: conj st sslen := Pz in\n  match getInterval (fst x)\n  return seq SSTrace + intermediate_result sd xs (@inactive maxReg) with\n  | i =>\n    let Hin : x \\in inactive z := @in_subseq_sing _ _ _ x xs _ Hsub in\n    let f (sd'    : ScanStateDesc maxReg)\n          (st'    : ScanState InUse sd')\n          (sslen' : SSMorphLen z sd')\n          (Hsub'  : subseq [seq mt_fst sslen' i | i <- xs]\n                           (inactive sd')) :=\n        inr (exist2 _ _ (sd'; sslen')\n                    (conj st' (transitivity sslen sslen')) Hsub') in\n    if intervalEnd i < pos\n    then\n      if prop (verifyNewHandled z i (snd x)) isn't Some Hreq\n      then let: (p1, p2) := x in\n           inl (ERegisterAssignmentsOverlap p2 p1 3 :: e)\n      else\n        match moveInactiveToHandled st Hin Hreq (spilled:=false) with\n        | exist2 sd' st' (conj sslen' _) =>\n            f sd' st' sslen' _\n        end\n    else\n      if posWithinInterval i pos\n      then match moveInactiveToActive' st Hsub Hin e with\n           | inl err => inl err\n           | inr (exist2 sd' st' (exist sslen' Hsub')) =>\n               f sd' st' sslen' Hsub'\n           end\n      else f z st (newSSMorphLen z) _\n  end.\nNext Obligation.\n  rewrite /mt_fst /morphlen_transport /=.\n  case: sslen'.\n  case=> [[?] _].\n  rewrite map_widen_ord_refl.\n  exact: subseq_cons_rem.\nDefined.\nNext Obligation.\n  rewrite /mt_fst /morphlen_transport /=.\n  rewrite map_widen_ord_refl.\n  apply: subseq_impl_cons.\n  exact Hsub.\nDefined.\n\nDefinition checkInactiveIntervals {pre} (pos : nat) :\n  SState pre (@SSMorphLen maxReg) (@SSMorphLen maxReg) unit :=\n  withScanStatePO (maxReg:=maxReg) $ fun sd (st : ScanState InUse sd) =>\n    e <<- Context.iask ;;;\n    let unchanged := exist2 _ _ sd st (newSSMorphLen sd) in\n    let eres : seq SSTrace + { sd' : ScanStateDesc maxReg\n                             | ScanState InUse sd' /\\ SSMorphLen sd sd'} :=\n        @dep_foldl_invE (seq SSTrace) (ScanStateDesc maxReg)\n          (fun sd' => ScanState InUse sd' /\\ SSMorphLen sd sd')\n          (@SSMorphLen maxReg) _ sd (conj st (newSSMorphLen sd))\n          (inactive sd) (size (inactive sd)) (eq_refl _)\n          (@inactive maxReg) (subseq_refl _) mt_fst (@goInactive pos sd e) in\n    match eres with\n    | inl err => error_ err\n    | inr (exist sd' (conj st' H)) =>\n        Context.iput {| thisDesc  := sd'\n                      ; thisHolds := H\n                      ; thisState := st' |}\n    end.\n\nDefinition handleInterval {pre} :\n  SState pre (@SSMorphHasLen maxReg) (@SSMorph maxReg) (option PhysReg) :=\n  (* position = start position of current *)\n  withCursor (maxReg:=maxReg) $ fun _ cur =>\n    let current := curInterval cur in\n    let pos     := intervalStart current in\n    let cid     := curId cur in\n\n    (* Remove any empty intervals from the unhandled list *)\n    if firstUsePos current is None\n    then @moveUnhandledToHandled maxReg pre ;;; ipure None\n    else\n      (* // check for intervals in active that are handled or inactive *)\n      liftLen (fun sd => @checkActiveIntervals sd pos) ;;;\n      (* // check for intervals in inactive that are handled or active *)\n      liftLen (fun sd => @checkInactiveIntervals sd pos) ;;;\n\n      (* // find a register for current\n         tryAllocateFreeReg\n         if allocation failed then\n           allocateBlockedReg\n         if current has a register assigned then\n           add current to active (done by the helper functions) *)\n      mres <<- tryAllocateFreeReg ;;;\n      match mres with\n      | Some x => imap (@Some _) x\n      | None   => allocateBlockedReg\n      end.\n\nProgram Definition finalizeScanState\n  `(st : ScanState InUse sd) (finalPos : nat) :\n  seq SSTrace +\n  { sd' : ScanStateDesc maxReg\n  | [&& size (unhandled sd') == 0\n    ,   size (active sd') == 0\n    &   size (inactive sd') == 0 ] } :=\n  match (checkActiveIntervals   finalPos ;;;\n         checkInactiveIntervals finalPos) [::]\n          {| thisDesc  := sd\n           ; thisHolds := newSSMorphLen sd\n           ; thisState := st |} with\n  | inl errs => inl errs\n  | inr (tt, ss) => _\n  end.\nNext Obligation.\n  destruct ss.\n  case H1: (size (unhandled thisDesc) == 0).\n    case H2: (size (active thisDesc) == 0).\n      case H3: (size (inactive thisDesc) == 0).\n        apply: inr _.\n        exists thisDesc.\n        apply/andP; split => //.\n        apply/andP; split => //.\n      exact: inl [:: EInactiveIntervalsRemain].\n    exact: inl [:: EActiveIntervalsRemain].\n  exact: inl [:: EUnhandledIntervalsRemain].\nQed.\n\n(* Walk through all the intervals which had been defined previously as the\n   [unhandled] list, and use those to determine register allocations.  The\n   final result will be a [ScanState] whose [handled] list represents the\n   final allocations for each interval. *)\nFixpoint walkIntervals `(st : ScanState InUse sd) (positions : nat) :\n  (seq SSTrace * ScanStateSig maxReg InUse) + ScanStateSig maxReg InUse :=\n  (* while unhandled /= { } do\n       current = pick and remove first interval from unhandled\n       HANDLE_INTERVAL (current) *)\n  if positions isn't S n\n  then inl ([:: EFuelExhausted], packScanState st)\n  else let fix go count ss :=\n    if count is S cnt\n    then\n      match handleInterval [::] ss with\n      | inl err => inl (err, packScanState (thisState ss))\n      | inr (_, ss') =>\n        (* A [ScanState InUse] may not insert new unhandled intervals at the\n           same position as [curPos], and so even though [unhandled sd] may\n           have been changed by the call to [handleInterval], it will not\n           have changed it with respect to subsequent intervals at the same\n           position. *)\n        match strengthenHasLen (thisHolds ss') with\n        | None => inr ss'\n        | Some holds' =>\n            go cnt {| thisDesc  := thisDesc ss'\n                    ; thisHolds := holds'\n                    ; thisState := thisState ss' |}\n        end\n      end\n    else inr {| thisDesc  := thisDesc ss\n              ; thisHolds := weakenHasLen (thisHolds ss)\n              ; thisState := thisState ss |} in\n\n    match List.destruct_list (unhandled sd) with\n    | inright _ => inr (packScanState st)\n    | inleft (existT (_, pos) (_; H)) =>\n        match go (count (fun x => snd x == pos) (unhandled sd))\n                 {| thisDesc  := sd\n                  ; thisHolds := newSSMorphHasLen (list_cons_nonzero H)\n                  ; thisState := st |} with\n        | inl err => inl err\n        | inr ss  => walkIntervals (thisState ss) n\n        end\n    end.\n\nRecord Allocation := {\n  intId  : nat;                 (* the interval ident *)\n  intVal : IntervalDesc;        (* the interval description data *)\n  intReg : option PhysReg       (* None if it was spilled to the stack *)\n}.\n\nDefinition determineAllocations (sd : @ScanStateDesc maxReg) : seq Allocation :=\n  [seq {| intId  := nat_of_ord (fst x)\n        ; intVal := getIntervalDesc (getInterval (fst x))\n        ; intReg := snd x |} | x <- handled sd].\n\nEnd Allocate.\n", "meta": {"author": "jwiegley", "repo": "linearscan", "sha": "1f8c74134d7634061d3cce4b2817708e9e82037d", "save_path": "github-repos/coq/jwiegley-linearscan", "path": "github-repos/coq/jwiegley-linearscan/linearscan-1f8c74134d7634061d3cce4b2817708e9e82037d/src/Allocate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947425132314, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.24484930154823883}}
{"text": "Require Import Bool.\nRequire Import List.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Event.\nRequire Import Time.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Thread.\n\nRequire Import SimMemory.\nRequire Import MemorySplit.\nRequire Import MemoryMerge.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\n\nInductive fulfill_step (lc1:Local.t) (sc1:TimeMap.t) (loc:Loc.t) (from to:Time.t) (val:Const.t) (releasedm released:option View.t) (ord:Ordering.t): forall (lc2:Local.t) (sc2:TimeMap.t), Prop :=\n| step_fulfill\n    promises2\n    (REL_LE: View.opt_le (TView.write_released lc1.(Local.tview) sc1 loc to releasedm ord) released)\n    (REL_WF: View.opt_wf released)\n    (WRITABLE: TView.writable lc1.(Local.tview).(TView.cur) sc1 loc to ord)\n    (REMOVE: Memory.remove lc1.(Local.promises) loc from to val released promises2)\n    (TIME: Time.lt from to):\n    fulfill_step lc1 sc1 loc from to val releasedm released ord\n                 (Local.mk (TView.write_tview lc1.(Local.tview) sc1 loc to ord) promises2)\n                 sc1\n.\n\nLemma fulfill_step_future lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2\n      (STEP: fulfill_step lc1 sc1 loc from to val releasedm released ord lc2 sc2)\n      (REL: Memory.closed_opt_view releasedm mem1)\n      (WF1: Local.wf lc1 mem1)\n      (SC1: Memory.closed_timemap sc1 mem1)\n      (CLOSED1: Memory.closed mem1):\n  <<WF2: Local.wf lc2 mem1>> /\\\n  <<SC2: Memory.closed_timemap sc2 mem1>> /\\\n  <<SC_FUTURE: TimeMap.le sc1 sc2>>.\nProof.\n  inv STEP.\n  hexploit Memory.remove_future; try apply REMOVE; try apply WF1; eauto. i. des.\n  exploit Memory.remove_get0; eauto. i.\n  inversion WF1. exploit PROMISES; eauto. i.\n  exploit TViewFacts.write_future_fulfill; try apply x; try apply SC1; try apply WF1; eauto.\n  { eapply CLOSED1. eauto. }\n  i. des.\n  esplits; eauto.\n  - econs; eauto.\n  - refl.\nQed.\n\nLemma write_promise_fulfill\n      lc0 sc0 mem0 loc from to val releasedm released ord lc2 sc2 mem2 kind\n      (WRITE: Local.write_step lc0 sc0 mem0 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n      (REL_WF: View.opt_wf releasedm)\n      (REL_CLOSED: Memory.closed_opt_view releasedm mem0)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0):\n  exists lc1,\n    <<STEP1: Local.promise_step lc0 mem0 loc from to val released lc1 mem2 kind>> /\\\n    <<STEP2: fulfill_step lc1 sc0 loc from to val releasedm released ord lc2 sc2>> /\\\n    <<REL: released = TView.write_released lc0.(Local.tview) sc0 loc to releasedm ord>> /\\\n    <<ORD: Ordering.le Ordering.strong_relaxed ord ->\n           Memory.nonsynch_loc loc lc0.(Local.promises) /\\\n           kind = Memory.op_kind_add>>.\nProof.\n  exploit Local.write_step_future; eauto. i. des.\n  inv WRITE. inv WRITE0. esplits; eauto.\n  - econs; eauto.\n  - refine (step_fulfill _ _ _ _ _ _ _); auto.\n    + refl.\n    + eapply MemoryFacts.promise_time_lt. eauto.\nQed.\n\nLemma fulfill_write\n      lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2\n      (FULFILL: fulfill_step lc1 sc1 loc from to val releasedm released ord lc2 sc2)\n      (REL_WF: View.opt_wf releasedm)\n      (REL_CLOSED: Memory.closed_opt_view releasedm mem1)\n      (ORD: Ordering.le ord Ordering.relaxed)\n      (WF1: Local.wf lc1 mem1)\n      (SC1: Memory.closed_timemap sc1 mem1)\n      (MEM1: Memory.closed mem1):\n  exists released' mem2',\n    <<STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released' ord lc2 sc2 mem2' (Memory.op_kind_lower released)>> /\\\n    <<REL_LE: View.opt_le released' released>> /\\\n    <<MEM: sim_memory mem2' mem1>>.\nProof.\n  inv FULFILL.\n  exploit TViewFacts.write_future_fulfill;\n    try exact REL_CLOSED; try exact SC1; eauto; try by apply WF1.\n  { apply WF1. eapply Memory.remove_get0. eauto. }\n  i. des.\n  exploit MemorySplit.remove_promise_remove;\n    try exact REMOVE; eauto; try apply WF1; try refl.\n  { eapply MEM1. apply WF1. eapply Memory.remove_get0. eauto. }\n  i. des.\n  esplits; eauto.\n  - econs; eauto.\n    + econs; eauto.\n    + i. destruct ord; inv ORD; inv H.\n  - eapply promise_lower_sim_memory. eauto.\nQed.\n\nLemma promise_fulfill_write\n      lc0 sc0 mem0 loc from to val releasedm released ord lc1 lc2 sc2 mem2 kind\n      (PROMISE: Local.promise_step lc0 mem0 loc from to val released lc1 mem2 kind)\n      (FULFILL: fulfill_step lc1 sc0 loc from to val releasedm released ord lc2 sc2)\n      (REL_WF: View.opt_wf releasedm)\n      (REL_CLOSED: Memory.closed_opt_view releasedm mem0)\n      (ORD: Ordering.le Ordering.strong_relaxed ord ->\n            Memory.nonsynch_loc loc lc0.(Local.promises) /\\\n            kind = Memory.op_kind_add)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0):\n  exists released' mem2',\n    <<STEP: Local.write_step lc0 sc0 mem0 loc from to val releasedm released' ord lc2 sc2 mem2' kind>> /\\\n    <<REL_LE: View.opt_le released' released>> /\\\n    <<MEM: sim_memory mem2' mem2>> /\\\n    <<REL: released' = TView.write_released lc0.(Local.tview) sc0 loc to releasedm ord>>.\nProof.\n  exploit Local.promise_step_future; eauto. i. des.\n  inv PROMISE. inv FULFILL. ss.\n  exploit TViewFacts.write_future_fulfill; try exact REL_WF; eauto; try by apply WF2.\n  { eapply Memory.future_closed_opt_view; eauto. }\n  { apply WF2. eapply Memory.promise_get2. eauto. }\n  s. i. des.\n  exploit MemorySplit.remove_promise_remove;\n    try exact REMOVE; eauto; try apply WF2; try refl. i. des.\n  esplits; eauto.\n  - econs; eauto. econs; eauto.\n    eapply MemoryMerge.promise_promise_promise; eauto.\n  - eapply promise_lower_sim_memory. eauto.\nQed.\n\nLemma promise_fulfill_write_exact\n      lc0 sc0 mem0 loc from to val releasedm released ord lc1 lc2 sc2 mem2 kind\n      (PROMISE: Local.promise_step lc0 mem0 loc from to val released lc1 mem2 kind)\n      (FULFILL: fulfill_step lc1 sc0 loc from to val releasedm released ord lc2 sc2)\n      (REL_WF: View.opt_wf releasedm)\n      (REL_CLOSED: Memory.closed_opt_view releasedm mem0)\n      (ORD: Ordering.le Ordering.strong_relaxed ord ->\n            Memory.nonsynch_loc loc lc0.(Local.promises) /\\\n            kind = Memory.op_kind_add)\n      (WF0: Local.wf lc0 mem0)\n      (SC0: Memory.closed_timemap sc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (REL: released = TView.write_released lc0.(Local.tview) sc0 loc to releasedm ord):\n  Local.write_step lc0 sc0 mem0 loc from to val releasedm released ord lc2 sc2 mem2 kind.\nProof.\n  exploit Local.promise_step_future; eauto. i. des.\n  inv PROMISE. inv FULFILL.\n  exploit MemorySplit.remove_promise_remove;\n    try exact REMOVE; eauto; try apply WF2; try refl. i. des.\n  refine (Local.write_step_intro _ _ _ _ _ _); eauto.\n  econs; eauto.\nQed.\n\nLemma fulfill_step_promises_diff\n      lc1 sc1 loc1 from to val releasedm released ord lc2 sc2 loc2\n      (LOC: loc1 <> loc2)\n      (FULFILL: fulfill_step lc1 sc1 loc1 from to val releasedm released ord lc2 sc2):\n  lc1.(Local.promises) loc2 = lc2.(Local.promises) loc2.\nProof.\n  inv FULFILL. inv REMOVE. unfold LocFun.add. s.\n  condtac; [congr|]. auto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-coq", "sha": "bff53239c51681ea653745cebf3b30ddd38f97ba", "save_path": "github-repos/coq/snu-sf-promising-coq", "path": "github-repos/coq/snu-sf-promising-coq/promising-coq-bff53239c51681ea653745cebf3b30ddd38f97ba/src/opt/FulfillStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.3738758157951908, "lm_q1q2_score": 0.2448493010805959}}
{"text": "Require Import Coqlib.\nRequire Import ITreelib.\nRequire Import ImpPrelude.\nRequire Import STS.\nRequire Import Behavior.\nRequire Import ModSem.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import HoareDef STB.\nRequire Import ProofMode.\n\nSet Implicit Arguments.\n\n\n\nLet _memRA: URA.t := (mblock ==> Z ==> (Excl.t val))%ra.\nCompute (URA.car (t:=_memRA)).\nInstance memRA: URA.t := Auth.t _memRA.\nCompute (URA.car).\n\nLocal Arguments Z.of_nat: simpl nomatch.\n\n\nSection PROOF.\n  Context `{@GRA.inG memRA Σ}.\n\n  Definition _points_to (loc: mblock * Z) (vs: list val): _memRA :=\n    let (b, ofs) := loc in\n    (fun _b _ofs => if (dec _b b) && ((ofs <=? _ofs) && (_ofs <? (ofs + Z.of_nat (List.length vs))))%Z\n                    then (List.nth_error vs (Z.to_nat (_ofs - ofs))) else ε)\n  .\n\n  (* Opaque _points_to. *)\n  Lemma unfold_points_to loc vs:\n    _points_to loc vs =\n    let (b, ofs) := loc in\n    (fun _b _ofs => if (dec _b b) && ((ofs <=? _ofs) && (_ofs <? (ofs + Z.of_nat (List.length vs))))%Z\n                    then (List.nth_error vs (Z.to_nat (_ofs - ofs))) else ε)\n  .\n  Proof. refl. Qed.\n\n  Definition points_to (loc: mblock * Z) (vs: list val): memRA := Auth.white (_points_to loc vs).\n\n  Definition var_points_to (skenv: SkEnv.t) (var: gname) (v: val): memRA :=\n    match (skenv.(SkEnv.id2blk) var) with\n    | Some  blk => points_to (blk, 0%Z) [v]\n    | None => ε\n    end.\n\n  Lemma points_to_split\n        blk ofs hd tl\n    :\n      (points_to (blk, ofs) (hd :: tl)) = (points_to (blk, ofs) [hd]) ⋅ (points_to (blk, (ofs + 1)%Z) tl)\n  .\n  Proof.\n    ss. unfold points_to. unfold Auth.white. repeat (rewrite URA.unfold_add; ss).\n    f_equal.\n    repeat (apply func_ext; i).\n    des_ifs; bsimpl; des; des_sumbool; subst; ss;\n      try rewrite Z.leb_gt in *; try rewrite Z.leb_le in *; try rewrite Z.ltb_ge in *; try rewrite Z.ltb_lt in *; try lia.\n    - clear_tac. subst. rewrite Zpos_P_of_succ_nat in *. rewrite <- Zlength_correct in *.\n      assert(x0 = ofs). { lia. } subst.\n      rewrite Z.sub_diag in *. ss.\n    - clear_tac. rewrite Zpos_P_of_succ_nat in *. rewrite <- Zlength_correct in *.\n      destruct (Z.to_nat (x0 - ofs)) eqn:T; ss.\n      { exfalso. lia. }\n      rewrite Z.sub_add_distr in *. rewrite Z2Nat.inj_sub in Heq1; ss. rewrite T in *. ss. rewrite Nat.sub_0_r in *. ss.\n    - clear_tac. rewrite Zpos_P_of_succ_nat in *. rewrite <- Zlength_correct in *.\n      destruct (Z.to_nat (x0 - ofs)) eqn:T; ss.\n      { exfalso. lia. }\n      rewrite Z.sub_add_distr in *. rewrite Z2Nat.inj_sub in Heq1; ss. rewrite T in *. ss. rewrite Nat.sub_0_r in *. ss.\n    - clear_tac. rewrite Zpos_P_of_succ_nat in *. rewrite <- Zlength_correct in *.\n      assert(x0 = ofs). { lia. } subst.\n      rewrite Z.sub_diag in *. ss.\n    - clear_tac. rewrite Zpos_P_of_succ_nat in *. rewrite <- Zlength_correct in *.\n      destruct (Z.to_nat (x0 - ofs)) eqn:T; ss.\n      { exfalso. lia. }\n      rewrite Z.sub_add_distr in *. rewrite Z2Nat.inj_sub in Heq1; ss. rewrite T in *. ss. rewrite Nat.sub_0_r in *. ss.\n    - clear_tac. rewrite Zpos_P_of_succ_nat in *. rewrite <- Zlength_correct in *.\n      assert(x0 = ofs). { lia. } subst.\n      rewrite Z.sub_diag in *. ss.\n  Qed.\n\n  Definition initial_mem_mr (csl: gname -> bool) (sk: Sk.t): _memRA :=\n    fun blk ofs =>\n      match List.nth_error sk blk with\n      | Some (g, gd) =>\n        match gd with\n        | Sk.Gfun => ε\n        | Sk.Gvar gv => if csl g then if (dec ofs 0%Z) then Some (Vint gv) else ε else ε\n        end\n      | _ => ε\n      end.\n\n\n(* Lemma points_tos_points_to *)\n(*       loc v *)\n(*   : *)\n(*     (points_to loc v) = (points_tos loc [v]) *)\n(* . *)\n(* Proof. *)\n(*   apply func_ext. i. *)\n(*   apply prop_ext. *)\n(*   ss. split; i; r. *)\n(*   - des_ifs. ss. eapply Own_extends; et. rp; try refl. repeat f_equal. repeat (apply func_ext; i). *)\n(*     des_ifs; bsimpl; des; des_sumbool; ss; clarify. *)\n(*     + rewrite Z.sub_diag; ss. *)\n(*     + rewrite Z.leb_refl in *; ss. *)\n(*     + rewrite Z.ltb_ge in *. lia. *)\n(*     + rewrite Z.ltb_lt in *. lia. *)\n(*   - des_ifs. ss. eapply Own_extends; et. rp; try refl. repeat f_equal. repeat (apply func_ext; i). *)\n(*     des_ifs; bsimpl; des; des_sumbool; ss; clarify. *)\n(*     + rewrite Z.sub_diag; ss. *)\n(*     + rewrite Z.ltb_lt in *. lia. *)\n(*     + rewrite Z.leb_refl in *; ss. *)\n(*     + rewrite Z.ltb_ge in *. lia. *)\n(* Qed. *)\n\nEnd PROOF.\n\nNotation \"loc |-> vs\" := (points_to loc vs) (at level 20).\n\n\n\nSection AUX.\n  Context `{@GRA.inG memRA Σ}.\n\n  Lemma points_to_disj\n        ptr x0 x1\n    :\n      (OwnM (ptr |-> [x0]) -∗ OwnM (ptr |-> [x1]) -* ⌜False⌝)\n  .\n  Proof.\n    destruct ptr as [blk ofs].\n    iIntros \"A B\". iCombine \"A B\" as \"A\". iOwnWf \"A\" as WF0.\n    unfold points_to in WF0. rewrite ! unfold_points_to in *. repeat (ur in WF0); ss.\n    specialize (WF0 blk ofs). des_ifs; bsimpl; des; des_sumbool; zsimpl; ss; try lia.\n  Qed.\n\n  Fixpoint is_list (ll: val) (xs: list val): iProp :=\n    match xs with\n    | [] => (⌜ll = Vnullptr⌝: iProp)%I\n    | xhd :: xtl =>\n      (∃ lhd ltl, ⌜ll = Vptr lhd 0⌝ ** (OwnM ((lhd,0%Z) |-> [xhd; ltl]))\n                             ** is_list ltl xtl: iProp)%I\n    end\n  .\n\n  Lemma unfold_is_list: forall ll xs,\n      is_list ll xs =\n      match xs with\n      | [] => (⌜ll = Vnullptr⌝: iProp)%I\n      | xhd :: xtl =>\n        (∃ lhd ltl, ⌜ll = Vptr lhd 0⌝ ** (OwnM ((lhd,0%Z) |-> [xhd; ltl]))\n                               ** is_list ltl xtl: iProp)%I\n      end\n  .\n  Proof.\n    i. destruct xs; auto.\n  Qed.\n\n  Lemma unfold_is_list_cons: forall ll xhd xtl,\n      is_list ll (xhd :: xtl) =\n      (∃ lhd ltl, ⌜ll = Vptr lhd 0⌝ ** (OwnM ((lhd,0%Z) |-> [xhd; ltl]))\n                             ** is_list ltl xtl: iProp)%I.\n  Proof.\n    i. eapply unfold_is_list.\n  Qed.\n\n  Lemma is_list_wf\n        ll xs\n    :\n      (is_list ll xs) -∗ (⌜(ll = Vnullptr) \\/ (match ll with | Vptr _ 0 => True | _ => False end)⌝)\n  .\n  Proof.\n    iIntros \"H0\". destruct xs; ss; et.\n    { iPure \"H0\" as H0. iPureIntro. left. et. }\n    iDestruct \"H0\" as (lhd ltl) \"[[H0 H1] H2]\".\n    iPure \"H0\" as H0. iPureIntro. right. subst. et.\n  Qed.\n\n  (* Global Opaque is_list. *)\nEnd AUX.\n\n\n\n\n\nSection PROOF.\n  Context `{@GRA.inG memRA Σ}.\n\n  Definition alloc_spec: fspec :=\n    (mk_simple (fun sz => (\n                    (ord_pure 0),\n                    (fun varg => (⌜varg = [Vint (Z.of_nat sz)]↑ /\\ (8 * (Z.of_nat sz) < modulus_64)%Z⌝: iProp)%I),\n                    (fun vret => (∃ b, (⌜vret = (Vptr b 0)↑⌝)\n                                         ** OwnM ((b, 0%Z) |-> (List.repeat Vundef sz))): iProp)%I\n    ))).\n\n  Definition free_spec: fspec :=\n    (mk_simple (fun '(b, ofs) => (\n                    (ord_pure 0),\n                    (fun varg => (∃ v, (⌜varg = ([Vptr b ofs])↑⌝) ** OwnM ((b, ofs) |-> [v]))%I),\n                    fun vret => ⌜vret = (Vint 0)↑⌝%I\n    ))).\n\n  Definition load_spec: fspec :=\n    (mk_simple (fun '(b, ofs, v) => (\n                    (ord_pure 0),\n                    (fun varg => (⌜varg = ([Vptr b ofs])↑⌝) ** OwnM(((b, ofs) |-> [v]))),\n                    (fun vret => OwnM((b, ofs) |-> [v]) ** ⌜vret = v↑⌝)\n    ))).\n\n  Definition store_spec: fspec :=\n    (mk_simple\n       (fun '(b, ofs, v_new) => (\n            (ord_pure 0),\n            (fun varg => (∃ v_old, (⌜varg = ([Vptr b ofs ; v_new])↑⌝) ** OwnM((b, ofs) |-> [v_old]))%I),\n            (fun vret => OwnM((b, ofs) |-> [v_new]) ** ⌜vret = (Vint 0)↑⌝\n    )))).\n\n  Definition cmp_spec: fspec :=\n    (mk_simple\n       (fun '(result, resource) => (\n            (ord_pure 0),\n            (fun varg =>\n               ((∃ b ofs v, ⌜varg = [Vptr b ofs; Vnullptr]↑⌝ ** ⌜resource = ((b, ofs) |-> [v])⌝ ** ⌜result = false⌝) ∨\n                (∃ b ofs v, ⌜varg = [Vnullptr; Vptr b ofs]↑⌝ ** ⌜resource = ((b, ofs) |-> [v])⌝ ** ⌜result = false⌝) ∨\n                (∃ b0 ofs0 v0 b1 ofs1 v1, ⌜varg = [Vptr b0 ofs0; Vptr b1 ofs1]↑⌝ ** ⌜resource = (((b0, ofs0) |-> [v0])) ⋅ ((b1, ofs1) |-> [v1])⌝ ** ⌜result = false⌝) ∨\n                (∃ b ofs v, ⌜varg = [Vptr b ofs; Vptr b  ofs]↑⌝ ** ⌜resource = ((b, ofs) |-> [v])⌝ ** ⌜result = true⌝) ∨\n                (⌜varg = [Vnullptr; Vnullptr]↑ /\\ result = true⌝))\n                 ** OwnM(resource)\n            ),\n            (fun vret => OwnM(resource) ** ⌜vret = (if result then Vint 1 else Vint 0)↑⌝)\n    ))).\n\n  Definition MemStb: list (gname * fspec).\n    eapply (Seal.sealing \"stb\").\n    apply [(\"alloc\", alloc_spec) ; (\"free\", free_spec) ; (\"load\", load_spec) ; (\"store\", store_spec) ; (\"cmp\", cmp_spec)].\n  Defined.\n\n  Definition MemSbtb: list (gname * fspecbody) :=\n    [(\"alloc\", mk_specbody alloc_spec (fun _ => trigger (Choose _)));\n    (\"free\",   mk_specbody free_spec (fun _ => trigger (Choose _)));\n    (\"load\",   mk_specbody load_spec (fun _ => trigger (Choose _)));\n    (\"store\",  mk_specbody store_spec (fun _ => trigger (Choose _)));\n    (\"cmp\",    mk_specbody cmp_spec (fun _ => trigger (Choose _)))\n    ]\n  .\n\n  Variable csl: gname -> bool.\n\n  Definition SMemSem (sk: Sk.t): SModSem.t := {|\n    SModSem.fnsems := MemSbtb;\n    SModSem.mn := \"Mem\";\n    SModSem.initial_mr := (GRA.embed (Auth.black (initial_mem_mr csl sk)));\n    SModSem.initial_st := tt↑;\n  |}\n  .\n\n  Definition SMem: SMod.t := {|\n    SMod.get_modsem := SMemSem;\n    SMod.sk := Sk.unit;\n  |}\n  .\n\n  Definition Mem: Mod.t := (SMod.to_tgt (fun _ => to_stb [])) SMem.\n\nEnd PROOF.\nGlobal Hint Unfold MemStb: stb.\n\nGlobal Opaque _points_to.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/mem/Mem1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.3738758157951908, "lm_q1q2_score": 0.24484930108059585}}
{"text": "Require Import Coq.Strings.String.\n\nFrom mathcomp Require Import\n  ssreflect ssrfun ssrbool ssrnat eqtype choice seq ssrnum ssrint ssralg bigop.\n\nFrom deriving Require Import deriving.\nFrom extructures Require Import ord fset fmap fperm.\n\nFrom CoqUtils Require Import nominal.\n\nFrom memsafe Require Import basic.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Cast.\n\nLocal Open Scope fset_scope.\n\nLemma eval_com_domm safe ls h ls' h' c k :\n  fsubset (vars_c c) (domm ls) ->\n  eval_com safe c (ls, h) k = Done (ls', h') ->\n  domm ls' = domm ls.\nProof.\nelim: k ls ls' h h' c => [|k IH] //= ls ls' h h'.\ncase=> [x e|x e|e e'|x e|e| |c1 c2|e c1 c2|e c] //=.\n- rewrite fsubU1set=> /andP [Px Pe] [<- _]; rewrite domm_set.\n  apply/eqP; rewrite eqEfsubset; apply/andP; split.\n    by rewrite fsubU1set Px fsubsetxx.\n  by rewrite fsubsetUr.\n- case: eval_expr => // p sz; case: (h p)=> [v|] //=.\n  rewrite fsubU1set=> /andP [Px Pe] [<- _]; rewrite domm_set.\n  apply/eqP; rewrite eqEfsubset; apply/andP; split.\n    by rewrite fsubU1set Px fsubsetxx.\n  by rewrite fsubsetUr.\n- case: eval_expr => // p sz; rewrite /updm; case: (h p)=> [v|] //=.\n  by rewrite fsubUset=> /andP [Pe Pe'] [<- _].\n- case: eval_expr => // - [n|] //.\n  rewrite fsubU1set=> /andP [Px Pe] [<- _]; rewrite domm_set.\n  apply/eqP; rewrite eqEfsubset; apply/andP; split.\n    by rewrite fsubU1set Px fsubsetxx.\n  by rewrite fsubsetUr.\n- case: eval_expr => // p sz.\n  by case: ifP=> //= _; case: ifP=> //= _ _ [<-].\n- congruence.\n- case eval_c1: eval_com=> [[ls'' h'']| | ] //.\n  rewrite fsubUset=> /andP [vars_c1 vars_c2] eval_c2.\n  rewrite -(IH _ _ _ _ _ vars_c1 eval_c1) in vars_c2 *.\n  by rewrite (IH _ _ _ _ _ vars_c2 eval_c2).\n- case: eval_expr=> // - b.\n  by rewrite 2!fsubUset -andbA => /and3P [_ vars_c1 vars_c2]; case: b; eauto.\ncase: eval_expr=> // - [] P; apply: IH.\n  by rewrite /= fsetUC -fsetUA fsetUid.\nby rewrite fsub0set.\nQed.\n\nLet namesm_set (T S : nominalType) (m : {fmap T -> S}) (k : T) (x : S) :\n  fsubset (names (setm m k x)) (names m :|: names k :|: names x).\nProof. eapply nom_finsuppP; finsupp. Qed.\n\nTheorem weak_frame ls1 h1 ls2 h2 ls' h' safe c k :\n  fsubset (vars_c c) (domm ls1) ->\n  fdisjoint (domm ls1) (domm ls2) ->\n  fdisjoint (names (ls1, h1)) (names (domm h2)) ->\n  eval_com safe c (unionm ls1 ls2, unionm h1 h2) k =\n  Done (ls', h') ->\n  exists ls1' h1',\n    [/\\ ls' = unionm ls1' ls2,\n        h'  = unionm h1' h2,\n        fdisjoint (domm ls1') (domm ls2) &\n        fsubset (names (ls1', h1') :&: (names h2))\n                (names (ls1, h1))].\nProof.\nelim: k ls1 h1 ls' h' c=> [//=|k IH] ls1 h1 ls' h' c.\ncase: c=> [x e|x e|e e'|x e|e| |c1 c2|e c1 c2|e c] //=.\n- (* Assn *)\n  rewrite fsubU1set=> /andP [Px sub] disl dish [<- <-].\n  rewrite setm_union; do 3!eexists; eauto.\n    by rewrite domm_set; apply/fdisjointP=> x' /fsetU1P [->|];\n    move/fdisjointP: disl; apply.\n  rewrite fsetIUl fsetUSS //= 1?fsubsetIl //.\n  rewrite (fsubset_trans (fsetSI _ (namesm_set _ _ _))) // fsetU0.\n  rewrite eval_expr_unionm // fsetIUl fsubUset fsubsetIl /=.\n  rewrite (fsubset_trans (fsubsetIl _ _)) //.\n  by rewrite (fsubset_trans (eval_expr_names _ _ _)) // fsubsetxx.\n- (* Load *)\n  rewrite fsubU1set=> /andP [Px sub] disl dish.\n  rewrite eval_expr_unionm //.\n  case eval_e: eval_expr=> [| |p|] //.\n  rewrite unionmE; case get_p: (h1 p)=> [v|] /=.\n    move=> [<- <-]; rewrite setm_union; do 3!eexists; eauto.\n      by rewrite domm_set; apply/fdisjointP=> x' /fsetU1P [->|];\n      move/fdisjointP: disl; apply.\n    rewrite fsetIUl /= fsubUset; apply/andP; split.\n      apply: (fsubset_trans (fsubsetIl _ _)).\n      apply: (fsubset_trans (namesm_set _ _ _)).\n      rewrite fsetU0 fsetUSS // ?fsubsetxx //=.\n      apply/fsubsetP=> n Pn; apply/namesmP.\n      by eapply PMFreeNamesVal; eauto.\n    by apply: fsubIset; rewrite fsubsetUr.\n  move: (eval_expr_names safe ls1 e); rewrite eval_e namesvE fsub1set=> Pp.\n  move/fdisjointP/(_ p.1): dish; rewrite in_fsetU /= Pp /= => /(_ erefl).\n  case get_p': (h2 p) => [v|] //= /namesfsPn/(_ p).\n  by rewrite mem_domm get_p'=> /(_ erefl); rewrite in_fsetU in_fset1 eqxx.\n- (* Store *)\n  rewrite fsubUset=> /andP [sub1 sub2] disl dish.\n  rewrite !eval_expr_unionm //.\n  case eval_e: eval_expr=> [| |p| ] //.\n  rewrite /updm unionmE setm_union.\n  case get_p: (h1 p)=> [v|] //=.\n    move=> [<- <-]; do 3!eexists; eauto.\n    apply: (fsubset_trans (fsubsetIl _ _)).\n    rewrite fsubUset; apply/andP; split; first by rewrite fsubsetUl.\n    apply/(fsubset_trans (namesm_set _ _ _)); rewrite 2!fsubUset.\n    rewrite fsubsetUr /=; apply/andP; split.\n      apply/fsubsetU/orP; right; apply/fsubsetP=> i Pi /=.\n      by apply/namesmP; eapply PMFreeNamesKey; eauto.\n    by apply/(fsubset_trans (eval_expr_names _ _ _))/fsubsetUl.\n  move: (eval_expr_names safe ls1 e); rewrite eval_e namesvE fsub1set=> Pp.\n  move/fdisjointP/(_ p.1): dish; rewrite in_fsetU /= Pp /= => /(_ erefl).\n  case get_p': (h2 p) => [v|] //= /namesfsPn/(_ p).\n  by rewrite mem_domm get_p'=> /(_ erefl); rewrite in_fsetU in_fset1 eqxx.\n- (* Alloc *)\n  rewrite fsubU1set=> /andP [Px sub] disl dish; rewrite eval_expr_unionm //.\n  case eval_e: eval_expr=> [|[n|]| |] //= [<- <-].\n  rewrite setm_union /= unionmA.\n  have dis': fdisjoint (domm h1) (domm h2).\n    apply/fdisjoint_names_domm/fdisjointP=> i Pi'.\n    by move/fdisjointP: dish; apply; apply/fsetUP; right; apply/fsetUP; left.\n  have F := (freshP (names (unionm ls1 ls2, unionm h1 h2))).\n  do 3!eexists; eauto.\n    by rewrite domm_set; apply/fdisjointP=> x' /fsetU1P [->|];\n    move/fdisjointP: disl; apply.\n  rewrite fsetIUl fsubUset; apply/andP; split=> /=.\n    apply/(fsubset_trans _ (fsubsetUl _ _)).\n    apply/(fsubset_trans (fsetSI _ (namesm_set _ _ _))).\n    rewrite /= 2!fsetIUl 2!fsubUset fsubsetIl fset0I fsub0set /=.\n    rewrite namesvE /=.\n    apply/fsubsetP=> i /fsetIP [/namesnP -> {i} /= Pi].\n    move: F; rewrite in_fsetU negb_or=> /andP [_] /=.\n    by rewrite namesm_union_disjoint // in_fsetU negb_or Pi andbF.\n  apply/fsubsetU/orP; right=> /=.\n  move: (fresh _) F => i.\n  rewrite namespE /= (namesm_union_disjoint dis').\n  rewrite in_fsetU negb_or in_fsetU negb_or.\n  case/and3P=> Fl Fh1 Fh2.\n  rewrite namesm_union_disjoint 1?fsetIUl ?fdisjoint_names_domm //.\n    rewrite fsubUset fsubsetIl andbT names_mkblock names_nseq if_same.\n    by rewrite fun_if if_arg fsetU0 fset1I fset0I (negbTE Fh2) if_same fsub0set.\n  rewrite names_domm_mkblock.\n  case: ifP => _; first by rewrite fdisjoint0s.\n  rewrite fdisjointC fdisjoints1.\n  by apply: contra Fh1; rewrite in_fsetU => ->.\n- (* Free *)\n  move=> sub disl dish; rewrite eval_expr_unionm //.\n  case eval_e: eval_expr=> [| |p|] //=.\n  have [|] := altP eqP=> // _.\n  rewrite domm_curry; case: ifP=> [/imfsetP [/= p' inD Pp]|] //=.\n  move: inD; rewrite mem_domm unionmE.\n  have dish': fdisjoint (names (domm h1)) (names (domm h2)).\n    apply/fdisjointP=> i Pi'.\n    by move/fdisjointP: dish; apply; apply/fsetUP; right; apply/fsetUP; left.\n  case get_p': (h1 p') => [v|] /=.\n    move=> _ [<- <-]; exists ls1, (filterm (fun p'' _ => p''.1 != p.1) h1).\n    split=> //.\n      rewrite filterm_union; last by apply fdisjoint_names_domm.\n      congr unionm; apply/eq_fmap=> p''; rewrite filtermE.\n      case get_p'': (h2 p'')=> [v'|] //=.\n      have [Pp'|] //= := altP eqP.\n      have names_p: p.1 \\in names (domm h1).\n        apply/namesfsP; exists p'; first by rewrite mem_domm get_p'.\n        by rewrite Pp; rewrite in_fsetU; apply/orP; left; apply/namesnP.\n      move/fdisjointP: dish'=> /(_ _ names_p).\n      suff ->: p.1 \\in names (domm h2) by [].\n      apply/namesfsP; exists p''; first by rewrite mem_domm get_p''.\n      by rewrite -Pp'; rewrite in_fsetU; apply/orP; left; apply/namesnP.\n    rewrite fsetIUl fsetUSS //= ?fsubsetIl //.\n    by apply/(fsubset_trans (fsubsetIl _ _))/namesm_filter.\n  case get_p'': (h2 p') => [v'|] //= _.\n  move: (eval_expr_names safe ls1 e); rewrite eval_e namesvE.\n  move=> /fsubsetP/(_ p.1); rewrite in_fset1 eqxx=> /(_ erefl) Pp'.\n  rewrite fdisjointC in dish; move/fdisjointP/(_ p.1): dish.\n  have h: p.1 \\in names (domm h2).\n    apply/namesfsP; exists p'; first by rewrite mem_domm get_p''.\n    by rewrite Pp in_fsetU; apply/orP; left; apply/namesnP.\n  by rewrite in_fsetU Pp' /= => /(_ h).\n- (* Skip *)\n  move=> _ ? ? [<- <-]; do 3!eexists; eauto; exact: fsubsetIl.\n- (* Seq *)\n  case eval_c1: eval_com=> [[ls'' h'']| |] //=.\n  rewrite fsubUset=> /andP [sub1 sub2] disl dish eval_c2.\n  have [ls1' [h1' [? ? disl' sub']]] := IH _ _ _ _ _ sub1 disl dish eval_c1.\n  subst ls'' h''.\n  have dish': fdisjoint (names (ls1', h1')) (names (domm h2)).\n    move/eqP in dish.\n    rewrite /fdisjoint -fsubset0 -dish fsubsetI fsubsetIr andbT.\n    by rewrite (fsubset_trans _ sub') // fsetIS // fsubsetUl.\n  have sub1': fsubset (vars_c c1) (domm (unionm ls1 ls2)).\n    by rewrite domm_union (fsubset_trans sub1) // fsubsetUl.\n  have sub2' : fsubset (vars_c c2) (domm ls1').\n    apply/fsubsetP=> x x_in.\n    move/fsubsetP/(_ x x_in): (sub2)=> sub2'.\n    have: x \\in domm (unionm ls1' ls2).\n      by rewrite (eval_com_domm sub1' eval_c1) domm_union in_fsetU sub2'.\n    move/fdisjointP/(_ _ sub2') in disl.\n    by rewrite domm_union in_fsetU (negbTE disl) orbF.\n  have [ls1'' [h1'' [? ? disl'' sub'']]] :=\n    IH _ _ _ _ _ sub2' disl' dish' eval_c2.\n  subst; do 3!eexists; eauto.\n  by apply/(fsubset_trans _ sub'); rewrite fsubsetI fsubsetIr andbT.\n- (* If *)\n  rewrite 2!fsubUset=> /andP [/andP [sub1 sub2] sub3].\n  rewrite eval_expr_unionm //.\n  case eval_e: eval_expr=> [b| | |] //= disl dish eval_c.\n  have [|ls1' [h1' [? ? disl' sub']]] := IH _ _ _ _ _ _ disl dish eval_c.\n    by case: b {eval_e eval_c}.\n  by subst ls' h'; do 3!eexists; eauto.\n(* While *)\nrewrite fsubUset=> /andP [sub1 sub2]; rewrite eval_expr_unionm //.\ncase eval_e: eval_expr=> [b| | |] //= disl dish eval_c.\nhave [|ls1' [h1' [? ? sub']]] := IH _ _ _ _ _ _ disl dish eval_c.\n  case: (b); last by rewrite fsub0set.\n  by rewrite /= fsetUC -fsetUA fsetUid fsubUset sub1.\nby subst ls' h'; do 3!eexists; eauto.\nQed.\n\nEnd Cast.\n", "meta": {"author": "arthuraa", "repo": "memory-safe-language", "sha": "1a32e879b93b5e9d6fc97100464c8432faece72d", "save_path": "github-repos/coq/arthuraa-memory-safe-language", "path": "github-repos/coq/arthuraa-memory-safe-language/memory-safe-language-1a32e879b93b5e9d6fc97100464c8432faece72d/cast.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.24474177059970778}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\nRequire Import omega.Omega.\nRequire Import Setoid.\nRequire Import ZArith.\n\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith. \n\nLocal Open Scope struct_scope.\n\nRequire Import FinProof.CommonProofs.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolClass.\nRequire Import depoolContract.SolidityNotations.\n\nRequire Import depoolContract.DePoolFunc.\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\n(* Import SolidityNotations. *)\nSet Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100.\n(*Set Typeclasses Strict Resolution. *)\n(* Set Typeclasses Debug.  *) \n(* Set Typeclasses Unique Instances. \nUnset Typeclasses Unique Solutions. *)\n\n(* Existing Instance monadStateT.\nExisting Instance monadStateStateT. *)\n(* Module MultiSigWalletSpecSig := MultiSigWalletSpecSig XTypesSig StateMonadSig. *)\n\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\nRequire Import depoolContract.Lib.CommonCommon.\nRequire Import depoolContract.Lib.CommonStateProofs.\n\n(* Require Import MultiSigWallet.Proofs.tvmFunctionsProofs. *)\n\nImport DePoolSpec.LedgerClass.SolidityNotations. \n\nLocal Open Scope solidity_scope.\n\n(* Require Import MultiSigWallet.Specifications._validatelimit_inlineSpec.\nModule _validatelimit_inlineSpec := _validatelimit_inlineSpec MultiSigWalletSpecSig.\nImport _validatelimit_inlineSpec. *)\n\nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope solidity_scope.\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\n\n(* function generateRound() internal returns (Round) {\n        DePoolLib.Request req;\n        Round r = Round({                      (*<<< порядок <<<<<*)\n            id: m_roundQty,\n            supposedElectedAt: 0, // set when round in elections phase\n            unfreeze: DePoolLib.MAX_TIME, // set when round in unfreeze phase\n            stakeHeldFor: 0,                    (*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*)\n            vsetHashInElectionPhase: 0, // set when round in elections phase\n            step: RoundStep.PrePooling,\n            completionReason: CompletionReason.Undefined,\n\n            stake: 0,\n            recoveredStake: 0,                 (*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*)\n            unused: 0,\n            isValidatorStakeCompleted: false,  (*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*)\n            rewards: 0,\n            participantQty : 0,\n            validatorStake: 0,                 (*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*)\n            validatorRemainingStake: 0,        (*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*)\n            handledStakesAndRewards: 0,        (*<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*)\n\n            validatorRequest: req,\n            elector: address(0), // set when round in elections phase\n            proxy: getProxy(m_roundQty)\n       });\n        ++m_roundQty;\n        return r;\n    }\n*) \n\nOpaque Z.eqb Z.add Z.sub Z.div Z.mul hmapLookup hmapInsert Z.ltb Z.geb Z.leb Z.gtb Z.modulo.\n\nLemma DePoolContract_Ф_generateRound_exec : forall (l: Ledger) , \nexec_state ( ↓ DePoolContract_Ф_generateRound ) l = \n\nlet m_roundQty1 := ( eval_state ( ↑11 ε RoundsBase_ι_m_roundQty ) l ) + 1 in\n\n    {$ l With ( RoundsBase_ι_m_roundQty , m_roundQty1 ) $} .  \n Proof. \n   intros. destruct l. auto. \n Qed. \n \nLemma DePoolContract_Ф_generateRound_eval : forall (l: Ledger) , \neval_state ( ↓ DePoolContract_Ф_generateRound ) l = \n\nlet req (* : DePoolLib_ι_RequestP *) := default in\nlet r := ( RoundsBase_ι_RoundC \n  ( eval_state ( ↑11 ε RoundsBase_ι_m_roundQty ) l )  \n \t0  \n \t( eval_state ( ↑9 ε DePoolLib_ι_MAX_TIME ) l )\n \t RoundsBase_ι_RoundStepP_ι_PrePooling \n \t RoundsBase_ι_CompletionReasonP_ι_Undefined  \n \t 0 0 default req 0 0 0  \n \t( eval_state ( ↓ ( ProxyBase_Ф_getProxy ( eval_state ( ↑11 ε RoundsBase_ι_m_roundQty ) l ) ) ) l )\n\t0 0 0 false 0 0 0 ) in r . \n Proof.  \n   intros. destruct l. auto. \nQed. ", "meta": {"author": "Pruvendo", "repo": "depool_contract_scenarios", "sha": "f0146bda676f3a1a35a7695b9598c7d2e337bbc2", "save_path": "github-repos/coq/Pruvendo-depool_contract_scenarios", "path": "github-repos/coq/Pruvendo-depool_contract_scenarios/depool_contract_scenarios-f0146bda676f3a1a35a7695b9598c7d2e337bbc2/src/Proofs/DePoolContract_generateRound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.24474176519895388}}
{"text": "(** * SLOT: a formally verified model checker *)\n\n(** SLOT is a collection of definitions and tactics for verification\nof safety properties of concurrent and distributed functional programs\ndoing I/O, based on Hoare logic. SLOT models have the following\nproperties:\n\n- Verified systems are written in a shallow-embedded DSL, and take\n  advantage of most Gallina features. They can be extracted to CPS\n  programs in Ocaml or Haskell via Coq's extraction feature\n\n- Users can define their own I/O operations (called syscalls from now\n  on)\n\n- Syscall definitions can be composed together, and all theorems about\n  the individual syscall types hold for the combined system\n\n- Syscalls can be nondeterminisic\n\n- Current version of SLOT doesn't support verification of liveness\n  properties\n\nSome notes on the naming: originally SLOT stood for Separation Logic\nOf Traces, but the current implementation has nothing to do with\nseparation logic. However this name was catchy, so it stuck.\n\n* Motivation\n\nBefore diving into lengthy description of the model, let me first\nmotivate a skeptical reader:\n\n** Q: Why not TLA+?\n\nA: In SLOT the verified system is clearly separated from the I/O\nmodel, and therefore its definition looks much like conventional\nfunctional program. It makes extraction of the verified code easier\n(at least in theory). Model of the non-deterministic I/O is\nseparated. This leads to much more structured definitions and proofs.\n\nAnother obvious difference is that SLOT is entirely based on Coq and\nmakes heavy use of inductive datatypes and symbolic evaluation under\nthe hood. This has both advantages and disadvantages:\n\n- SLOT is much less automated, but it can work with inductive\n  definitions and anything that can be expressed in Coq\n\n- SLOT model checker outputs Coq proofs, ultimately it means that it\n  needs to store all execution histories. Given that the number of\n  histories grows exponentially, solving large proofs by pure\n  bruteforce is impossible. Although this disadvantage is partially\n  mitigated by several formally-verified branch-pruning algorithms, it\n  means proofs about large systems should be split to lemmas\n\n- Verified program can be extracted\n\n- While TLA+ model checker is top notch, its proof language is not\n\n** Q: Why not (insert model checker name)?\n\nA: Model checkers show why the code _fails_, which is suitable for\nverifying algorithms, but structured formal proofs show why the code\n_works_ (via tree of assumptions). It allows to reason about\nalgorithms and, in particular, to predict the outcome of\noptimizations. Also model checkers typically can't work with infinite\nstate space, while SLOT can do it to some extend via magic of Coq.\n\n** Q: Why not Verdi?\n\nhttps://github.com/uwplse/verdi\n\n- Nondeterminisic part of Verdi is hardcoded, while SLOT allows user\n  to define custom IO handlers\n\n- Verdi models are low level: think UDP packets and disk iops. SLOT\n  can work with higher-level I/O handlers: think databases and pubsub\n  services.\n\n** Q: Why not disel?\n\nhttps://github.com/DistributedComponents/disel\n\nA: disel models are closer to what I need, but implementation itself\nis an incomprehensible, impenetrable wall of ssreflect. Proofs are\nonly as useful as their premises: \"garbage in - garbage out\". Good\nmodel should be well documented and well understood.\n\n** Q: Why not iris/aneris?\n\nhttps://gitlab.mpi-sws.org/iris/iris\n\nA: iris allows user to define semantics of their very own programming\nlanguage. SLOT is focused on proving properties of _regular pure\nfunctinal programs_ that do IO from time to time. Hence it defines\nactors in regular Gallina language, rather than some DSL, and frees\nthe user from reinventing basic control flow constructions.\n\n* Navigating the code\n\n** Core definitions\n\n - [LibTx.SLOT.Hoare] module contains definitions used to describe a\n   single execution history\n\n*)\n\nFrom LibTx Require Export\n     SLOT.EventTrace\n     SLOT.Hoare\n     SLOT.Handler\n     SLOT.Process\n     SLOT.Ensemble.\n\nFrom Coq Require Import\n     String\n     List.\n\n(*Module Model.\n  Section defn.\n    Context {PID} {SUT : Type} {Handler : @Handler.t PID}.\n\n    Record t : Type :=\n      mkModel\n        { model_sut : SUT;\n          model_handler : h_state Handler;\n        }.\n\n   Context `{Runnable  SUT}.\n\n    Definition model_state_transition m m' te : Prop :=\n      match m, m' with\n      | mkModel s h, mkModel s' h' => (h_state_transition Handler) h h' te /\\\n                                     runnable_step s s' te\n      end.\n\n    Global Instance modelStateSpace : StateSpace t (@TraceElem ctx) :=\n      {| state_transition := model_state_transition; |}.\n  End defn.\n\n  (* Helper function for infering type of model: *)\n  Definition model_t {SUT} {PID} (sut : SUT) (h : @Handler.t PID) : Type :=\n    @t PID SUT h.\nEnd Model. *)\n\nLtac bruteforce Ht Hls :=\n  let Ht' := type of Ht in\n  match eval lazy in Ht' with\n  | ThreadGenerator _ _ _ =>\n    unfold_thread Ht\n  | Parallel ?e1 ?e2 ?t =>\n    let t1 := fresh \"t_l\" in\n    let t2 := fresh \"t_r\" in\n    let H1 := fresh \"H\" t1 in\n    let H2 := fresh \"H\" t2 in\n    let t := fresh \"t\" in\n    let Hint := fresh \"Hint_\" t in\n    destruct Ht as [t1 t2 t H1 H2 Hint];\n    bruteforce H1 Hls; subst; bruteforce H2 Hls;\n    unfold_interleaving Hint with trace_step Hls\n  end.\n\nRequire Import\n        Handlers.Mutex\n        Handlers.Deterministic.\n\n(*\nModule ExampleModelDefn.\n  Section handler.\n    Context {PID : Type}.\n\n    Definition Handler := AtomicVar.t nat <+> mutexHandler PID.\n  End handler.\n\n  Let req := get_handler_req (@Handler).\n  Let ret := get_handler_ret (@Handler).\n\n  Section defs.\n    (* Let req : Type := (@avar_req_t nat + req_t).     *)\n    Context {PID : Type}.\n\n    Definition put (val : nat) : req :=\n      inl (AtomicVar.write val).\n\n    Definition get : req :=\n      inl (AtomicVar.read).\n\n    Definition grab : req :=\n      inr (Mutex.grab).\n\n    Definition release : req :=\n      inr (Mutex.release).\n\n    Let Thread := @Thread req ret.\n\n    (* Just a demonstration how to define a program that loops\n    indefinitely, as long as it does IO: *)\n\n    CoFixpoint infinite_loop (self : PID) : Thread :=\n      do _ <- put 0;\n      infinite_loop self.\n\n    (* Data race example: *)\n    Definition inc (n : nat) ret : Thread :=\n      do v <- get;\n      do _ <- put (v + n);\n      ret (v + n).\n\n    (* Fixed example: *)\n    Definition counter_correct (self : PID) :=\n      do _ <- grab;\n      call x <- inc 1;\n      done release.\n\n    (* Definition nop (self : PID) : Thread := *)\n    (*   @throw ctx \"Exception\".  TODO *)\n  End defs.\n\n  Section simple.\n    Let PID := bool.\n\n    Let SUT := counter_correct I.\n    Let Handler := @Handler PID.\n\n    Let mk_counter (pid : PID) := ThreadGenerator pid (counter_correct pid).\n    Let SingletonEnsemble := mk_counter true.\n    Let PairEnsemble := (mk_counter true) -|| (mk_counter false).\n    Let InfLoopEnsemble := ThreadGenerator true (infinite_loop true).\n\n    Goal EnsembleInvariant (fun _ => True) SingletonEnsemble.\n    Proof.\n      intros t Ht.\n      unfold_thread Ht. subst.\n      now repeat constructor.\n    Qed.\n\n    Goal EnsembleInvariant (fun _ => True) SingletonEnsemble.\n    Proof.\n      intros t Ht.\n      unfold_thread Ht. subst.\n      now repeat constructor.\n    Qed.\n\n    Goal forall v1 v2,\n      {{ fun s  => True }}\n        [true @ v1 <~ get;\n         true @ I <~ grab;\n         true @ v2 <~ get;\n         false @ I <~ grab;\n         true @ I <~ grab]\n      {{ fun s => False }}.\n    Proof.\n      intros v1 v2.\n      unfold_ht.\n      repeat trace_step Hls.\n    Qed.\n\n    Goal -{{ fun (s : h_state Handler) => fst s = 0 }} PairEnsemble {{ fun s => fst s = 2 }}.\n    Proof.\n      intros t Ht.\n      unfold_ht.\n      cbn in Hpre.\n      bruteforce Ht Hls;\n      cbn in *; repeat match goal with\n                         [ H : _ /\\ _ |- _] => destruct H\n                       end; subst; auto.\n    Qed.\n\n    (*Let counter_invariant (sys : Model) : Prop :=\n      match sys with\n        mkModel sut (M, l) =>\n        match l with\n        | Some _ => True\n        | None =>\n          let n_alive := match sut with\n                         | t_dead => 0\n                         | t_cont _ _ => 1\n                         end\n          in n_alive + M = 1\n        end\n      end.*)\n  End simple.\nEnd ExampleModelDefn.\n*)\n", "meta": {"author": "Zabrane", "repo": "libtx", "sha": "0e3f24ef165a240ee6af59a4956995c2205fe9aa", "save_path": "github-repos/coq/Zabrane-libtx", "path": "github-repos/coq/Zabrane-libtx/libtx-0e3f24ef165a240ee6af59a4956995c2205fe9aa/theories/SLOT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.24474176519895385}}
{"text": "(**\nSimSoC-Cert, a toolkit for generating certified processor simulators.\n\nSee the COPYRIGHTS and LICENSE files.\n\nNotations and coercions for C programs.\n*)\n\nSet Implicit Arguments.\n\nRequire Import List BinInt String.\nRequire Export Integers AST Values Csyntax Ascii.\n\n(****************************************************************************)\n(** notations for Coq data structures *)\n\nNotation \"[ ]\" := nil.\nNotation \"[ a ; .. ; b ]\" := (a :: .. (b :: nil) ..).\n\n(****************************************************************************)\n(** convert Coq strings into lists of Values.init_data *)\n\nDefinition init_data_of_ascii a := Init_int8 (Int.repr (Z_of_N (N_of_ascii a))).\n\nDefinition list_init_data_of_list_ascii := List.map init_data_of_ascii.\n\nFixpoint list_init_data_of_string s :=\n  match s with\n    | EmptyString => []\n    | String a s => init_data_of_ascii a :: list_init_data_of_string s\n  end.\n\nDefinition null_termin_string s := (s ++ String \"000\" \"\")%string.\n\n(****************************************************************************)\n(** coercions *)\n\nCoercion Int.repr : Z >-> int.\nCoercion Vint : int >-> val.\nCoercion Sdo : expr >-> statement.\nCoercion init_data_of_ascii : ascii >-> init_data.\nCoercion list_init_data_of_string : string >-> list.\n\n(****************************************************************************)\n(* notations *)\n\nNotation \"a -: b\" := (pair a b) (at level 60).\n\nNotation \"` x\" := (Int.repr x) (at level 9).\nNotation \"`` x\" := (Init_int8 ` x) (at level 9).\n\nNotation int8 := (Tint I8 Signed).\nNotation uint8 := (Tint I8 Unsigned).\nNotation int16 := (Tint I16 Signed).\nNotation uint16 := (Tint I16 Unsigned).\nNotation int32 := (Tint I32 Signed).\nNotation uint32 := (Tint I32 Unsigned).\nNotation float32 := (Tfloat F32).\nNotation float64 := (Tfloat F64).\n\nNotation void := Tvoid.\nNotation \"`*` t\" := (Tpointer t) (at level 20).\n\nNotation \"a :T: b\" := (Tcons a b) (at level 70, right associativity).\nNotation \"T[ ]\" := Tnil.\nNotation \"T[ a ; .. ; b ]\" := (a :T: .. (b :T: Tnil) ..).\n\nDefinition fcons a := Fcons (fst a) (snd a).\nNotation \"a :F: b\" := (fcons a b) (at level 70, right associativity).\nNotation \"F[ ]\" := Fnil.\nNotation \"F[ a ; .. ; b ]\" := (a :F: .. (b :F: Fnil) ..).\n\nNotation \"a :E: b\" := (Econs a b) (at level 70, right associativity).\nNotation \"E[ ]\" := Enil.\nNotation \"E[ a ; .. ; b ]\" := (a :E: .. (b :E: Enil) ..).\n\nNotation \"! x `: t\" := (Eunop Onotbool x t) (at level 10).\nNotation \"`~ x `: t\" := (Eunop Onotint x t) (at level 10).\nNotation \"`- x `: t\" := (Eunop Oneg x t) (at level 10).\n\nNotation \"x + y `: t\" := (Ebinop Oadd x y t) (at level 20).\nNotation \"x - y `: t\" := (Ebinop Osub x y t) (at level 20).\nNotation \"x * y `: t\" := (Ebinop Omul x y t) (at level 20).\nNotation \"x / y `: t\" := (Ebinop Odiv x y t) (at level 20).\nNotation \"x % y `: t\" := (Ebinop Omod x y t) (at level 20).\nNotation \"x & y `: t\" := (Ebinop Oand x y t) (at level 20).\nNotation \"x `| y `: t\" := (Ebinop Oor x y t) (at level 20).\nNotation \"x ^ y `: t\" := (Ebinop Oxor x y t) (at level 20).\nNotation \"x << y `: t\" := (Ebinop Oshl x y t) (at level 20).\nNotation \"x >> y `: t\" := (Ebinop Oshr x y t) (at level 20).\n\nNotation \"x == y `: t\" := (Ebinop Oeq x y t) (at level 20).\nNotation \"x != y `: t\" := (Ebinop One x y t) (at level 20).\nNotation \"x < y `: t\" := (Ebinop Olt x y t) (at level 20).\nNotation \"x > y `: t\" := (Ebinop Ogt x y t) (at level 20).\nNotation \"x <= y `: t\" := (Ebinop Ole x y t) (at level 20).\nNotation \"x >= y `: t\" := (Ebinop Oge x y t) (at level 20).\n\nNotation \"x += y `: t1 `: t2\" := (Eassignop Oadd x y t1 t2) (at level 8).\nNotation \"x -= y `: t1 `: t2\" := (Eassignop Osub x y t1 t2) (at level 8).\nNotation \"x *= y `: t1 `: t2\" := (Eassignop Omul x y t1 t2) (at level 8).\nNotation \"x /= y `: t1 `: t2\" := (Eassignop Odiv x y t1 t2) (at level 8).\nNotation \"x %= y `: t1 `: t2\" := (Eassignop Omod x y t1 t2) (at level 8).\nNotation \"x &= y `: t1 `: t2\" := (Eassignop Oand x y t1 t2) (at level 8).\nNotation \"x `|= y `: t1 `: t2\" := (Eassignop Oor x y t1 t2) (at level 8).\nNotation \"x ^= y `: t1 `: t2\" := (Eassignop Oxor x y t1 t2) (at level 8).\nNotation \"x <<= y `: t1 `: t2\" := (Eassignop Oshl x y t1 t2) (at level 8).\nNotation \"x >>= y `: t1 `: t2\" := (Eassignop Oshr x y t1 t2) (at level 8).\n\nNotation \"`* e `: t\" := (Ederef e t) (at level 20).\nNotation \"# v `: t\" := (Eval v t) (at level 20).\nNotation \"$ id `: t\" := (Evar id t) (at level 20).\nNotation \"\\ id `: t\" := (Evalof (Evar id t) t) (at level 20).\nNotation \"& e `: t\" := (Eaddrof e t) (at level 20).\nNotation \"e1 ? e2 `: e3 `: t\" := (Econdition e1 e2 e3 t) (at level 20).\nNotation \"e -- `: t\" := (Epostincr Decr e t) (at level 20).\nNotation \"e ++ `: t\" := (Epostincr Incr e t) (at level 20).\nNotation \"e1 `= e2 `: t\" := (Eassign e1 e2 t) (at level 8).\nNotation \"e | id `: t\" := (Efield e id t) (at level 20).\nNotation \"'call'\" := (Ecall).\nNotation \"'sizeof'\" := (Esizeof).\nNotation \"'valof'\" := (Evalof).\n\nNotation \"a ;; b\" := (Ssequence a b) (at level 51, right associativity).\nNotation \"`if a 'then' b 'else' c\" := (Sifthenelse a b c) (at level 9).\nNotation \"'while' a `do b\" := (Swhile a b) (at level 19).\nNotation \"`do a 'while' b\" := (Sdowhile b a) (at level 19).\nNotation \"'label' l `: s\" := (Slabel l s) (at level 5).\nNotation \"'for' ( s1 , e , s2 ) { s3 }\" := (Sfor s1 e s2 s3) (at level 19).\n\nNotation \"'return'\" := (Sreturn) (at level 10).\nNotation \"'goto'\" := (Sgoto).\nNotation \"'continue'\" := (Scontinue).\nNotation \"'break'\" := (Sbreak).\nNotation \"'skip'\" := (Sskip).\nNotation \"'switch'\" := (Sswitch).\n\nNotation \"`case i `: s :L: ls\" := (LScase i s ls) (at level 70).\nNotation \"'default' `: s\" := (LSdefault s) (at level 80).\n", "meta": {"author": "git-inria", "repo": "simsoc-cert", "sha": "2a2d45c3d94745fb33d91ed75ca91de083b4cebd", "save_path": "github-repos/coq/git-inria-simsoc-cert", "path": "github-repos/coq/git-inria-simsoc-cert/simsoc-cert-2a2d45c3d94745fb33d91ed75ca91de083b4cebd/coq/Cnotations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24461313884192074}}
{"text": "Require Export\n        Fiat.CertifiedExtraction.Extraction.Extraction.\n\nRequire Import\n        Fiat.CertifiedExtraction.Extraction.BinEncoders.Basics\n        Fiat.CertifiedExtraction.Extraction.BinEncoders.Wrappers\n        Fiat.CertifiedExtraction.Extraction.BinEncoders.Properties.\n\nRequire Import\n        Coq.Program.Program\n        Coq.Lists.List.\n\nUnset Implicit Arguments.\n\nLemma CompileCompose :\n  forall {av} E B B' (transformer: Transformer.Transformer B) enc1 enc2\n    (vstream: NameTag av B') (stream: B) (cache: E)\n    (tenv t1 t2: Telescope av) f (g: B -> B') ext env p1 p2,\n    (forall a1 a2 b, f (a1, b) = f (a2, b)) ->\n    {{ [[ vstream  ->> g stream as _ ]]\n         :: tenv }}\n      p1\n    {{ TelAppend ([[ NTNone ->> enc1 cache as encoded1 ]]\n                    :: [[ vstream ->> g (Transformer.transform stream (fst encoded1)) as _ ]]\n                    :: f encoded1)\n                 t1 }}\n    ∪ {{ ext }} // env ->\n    (let encoded1 := enc1 cache in\n     let stream1 := Transformer.transform stream (fst encoded1) in\n     {{ TelAppend ([[ vstream ->> g stream1 as _ ]] :: f encoded1) t1 }}\n       p2\n     {{ TelAppend ([[ NTNone ->> enc2 (snd encoded1) as encoded2 ]]\n                     :: [[ vstream ->> g (Transformer.transform stream1 (fst encoded2)) as _ ]]\n                     :: f encoded2) t2 }}\n     ∪ {{ ext }} // env) ->\n    {{ [[ vstream ->> g stream as _ ]] :: tenv }}\n      (Seq p1 p2)\n    {{ TelAppend ([[ NTNone ->> @Compose.compose E B transformer enc1 enc2 cache as composed ]]\n                    :: [[ vstream ->> g (Transformer.transform stream (fst composed)) as _ ]]\n                    :: f composed) t2 }}\n    ∪ {{ ext }} // env.\nProof.\n  intros.\n  repeat hoare.\n  setoid_rewrite Compose_compose_acc.\n  unfold compose_acc, encode_continue.\n  cbv zeta in *.\n  setoid_rewrite Propagate_anonymous_ret.\n  setoid_rewrite Propagate_anonymous_ret in H0.\n  setoid_rewrite Propagate_anonymous_ret in H1.\n  destruct (enc1 _); simpl in *.\n  destruct (enc2 _); simpl in *.\n  erewrite (H (Transformer.transform _ _)); rewrite Transformer.transform_assoc; eassumption.\nQed.\n\nLemma CompileCompose_init :\n  forall {av} E B B' (transformer: Transformer.Transformer B) enc1 enc2\n    (vstream: NameTag av B') (cache: E)\n    (tenv t1 t2: Telescope av) f (g : B -> B') ext env p1 p2 pAlloc,\n    (forall a1 a2 b, f (a1, b) = f (a2, b)) ->\n    {{ tenv }}\n      pAlloc\n    {{ [[ vstream ->> g Transformer.transform_id as _ ]] :: tenv }} ∪ {{ ext }} // env ->\n    {{ [[ vstream ->> g Transformer.transform_id as _ ]] :: tenv }}\n      p1\n    {{ TelAppend ([[ NTNone ->> enc1 cache as encoded1 ]]\n                    :: [[ vstream ->> g (Transformer.transform (Transformer.transform_id) (fst encoded1)) as _ ]]\n                    :: f encoded1)\n                 t1 }} ∪ {{ ext }} // env ->\n    (let encoded1 := enc1 cache in\n     let stream1 := Transformer.transform Transformer.transform_id (fst encoded1) in\n     {{ TelAppend ([[ vstream ->> g stream1 as _ ]] :: f encoded1) t1 }}\n       p2\n     {{ TelAppend ([[ NTNone ->> enc2 (snd encoded1) as encoded2 ]]\n                     :: [[ vstream ->> g (Transformer.transform stream1 (fst encoded2)) as _ ]]\n                     :: f encoded2) t2 }} ∪ {{ ext }} // env) ->\n    {{ tenv }}\n      (Seq pAlloc (Seq p1 p2))\n    {{ TelAppend ([[ NTNone ->> @Compose.compose E B transformer enc1 enc2 cache as composed ]]\n                    :: [[ vstream ->> g (fst composed) as _ ]]\n                    :: f composed) t2 }}\n    ∪ {{ ext }} // env.\nProof.\n  intros; hoare.\n  setoid_rewrite <- (Transformer.transform_id_left (fst _)).\n  eauto using CompileCompose.\nQed.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/CertifiedExtraction/Extraction/BinEncoders/CallRules/Compose.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2445714984900063}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import AbsAccessor.Spec.\nRequire Import RealmSyncHandlerAux.Specs.handle_icc_el1_sysreg_trap.\nRequire Import RealmSyncHandlerAux.LowSpecs.handle_icc_el1_sysreg_trap.\nRequire Import RealmSyncHandlerAux.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       ESR_EL2_SYSREG_ISS_RT_spec\n       ESR_EL2_SYSREG_IS_WRITE_spec\n       set_rec_regs_spec\n    .\n\n  Lemma handle_icc_el1_sysreg_trap_spec_exists:\n    forall habd habd'  labd rec esr\n      (Hspec: handle_icc_el1_sysreg_trap_spec rec esr habd = Some habd')\n      (Hrel: relate_RData habd labd),\n    exists labd', handle_icc_el1_sysreg_trap_spec0 rec esr labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque ptr_eq.\n    intros. destruct Hrel. destruct rec.\n    unfold handle_icc_el1_sysreg_trap_spec, handle_icc_el1_sysreg_trap_spec0 in *.\n    repeat autounfold in *. simpl in *.\n    hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec;\n      repeat destruct_con; bool_rel; simpl in *; srewrite; repeat simpl_update_reg;\n        repeat (simpl_htarget; grewrite; simpl in * );\n        try solve[repeat (solve_bool_range; grewrite); eexists; split; [reflexivity|constructor; reflexivity]].\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RealmSyncHandlerAux/RefProof/handle_icc_el1_sysreg_trap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.244571492275262}}
{"text": "From caml5 Require Import\n  prelude.\nFrom caml5.lang Require Import\n  notations\n  proofmode.\nFrom caml5.std Require Export\n  base.\n\nSection heapGS.\n  Context `{!heapGS Σ}.\n  Implicit Types l : loc.\n\n  Definition record3_make : val :=\n    λ: \"v₀\" \"v₁\" \"v₂\",\n      let: \"l\" := AllocN #3 \"v₀\" in\n      \"l\".(1) <- \"v₁\" ;;\n      \"l\".(2) <- \"v₂\" ;;\n      \"l\".\n\n  Definition record3_model l dq v₀ v₁ v₂ : iProp Σ :=\n    l.(0) ↦{dq} v₀ ∗\n    l.(1) ↦{dq} v₁ ∗\n    l.(2) ↦{dq} v₂.\n\n  #[global] Instance record3_model_timeless l dq v₀ v₁ v₂ :\n    Timeless (record3_model l dq v₀ v₁ v₂).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance record3_model_persistent l v₀ v₁ v₂ :\n    Persistent (record3_model l DfracDiscarded v₀ v₁ v₂).\n  Proof.\n    apply _.\n  Qed.\n\n  #[global] Instance record3_model_fractional l v₀ v₁ v₂ :\n    Fractional (λ q, record3_model l (DfracOwn q) v₀ v₁ v₂).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance record3_model_as_fractional l q v₀ v₁ v₂ :\n    AsFractional (record3_model l (DfracOwn q) v₀ v₁ v₂) (λ q, record3_model l (DfracOwn q) v₀ v₁ v₂) q.\n  Proof.\n    split; done || apply _.\n  Qed.\n\n  Lemma record3_model_persist l dq v₀ v₁ v₂ :\n    record3_model l dq v₀ v₁ v₂ ==∗\n    record3_model l DfracDiscarded v₀ v₁ v₂.\n  Proof.\n    iIntros \"(Hv₀ & Hv₁ & Hv₂)\".\n    iMod (mapsto_persist with \"Hv₀\") as \"$\".\n    iMod (mapsto_persist with \"Hv₁\") as \"$\".\n    iMod (mapsto_persist with \"Hv₂\") as \"$\".\n    done.\n  Qed.\n\n  Lemma record3_model_valid l dq v₀ v₁ v₂ :\n    record3_model l dq v₀ v₁ v₂ -∗\n    ⌜✓ dq⌝.\n  Proof.\n    iIntros \"(Hv₀ & Hv₁ & Hv₂)\". iApply (mapsto_valid with \"Hv₀\").\n  Qed.\n  Lemma record3_model_combine l dq1 v₀1 v₁1 v₂1 dq2 v₀2 v₁2 v₂2 :\n    record3_model l dq1 v₀1 v₁1 v₂1 -∗\n    record3_model l dq2 v₀2 v₁2 v₂2 -∗\n      record3_model l (dq1 ⋅ dq2) v₀1 v₁1 v₂1 ∗\n      ⌜v₀1 = v₀2 ∧ v₁1 = v₁2 ∧ v₂1 = v₂2⌝.\n  Proof.\n    iIntros \"(Hv₀1 & Hv₁1 & Hv₂1) (Hv₀2 & Hv₁2 & Hv₂2)\".\n    iDestruct (mapsto_combine with \"Hv₀1 Hv₀2\") as \"(Hv₀ & <-)\".\n    iDestruct (mapsto_combine with \"Hv₁1 Hv₁2\") as \"(Hv₁ & <-)\".\n    iDestruct (mapsto_combine with \"Hv₂1 Hv₂2\") as \"(Hv₂ & <-)\".\n    iSplit; last done. iFrame.\n  Qed.\n  Lemma record3_model_valid_2 l dq1 v₀1 v₁1 v₂1 dq2 v₀2 v₁2 v₂2 :\n    record3_model l dq1 v₀1 v₁1 v₂1 -∗\n    record3_model l dq2 v₀2 v₁2 v₂2 -∗\n    ⌜✓ (dq1 ⋅ dq2) ∧ v₀1 = v₀2 ∧ v₁1 = v₁2 ∧ v₂1 = v₂2⌝.\n  Proof.\n    iIntros \"Hl1 Hl2\".\n    iDestruct (record3_model_combine with \"Hl1 Hl2\") as \"(Hl & %)\".\n    iDestruct (record3_model_valid with \"Hl\") as %?.\n    done.\n  Qed.\n  Lemma record3_model_agree l dq1 v₀1 v₁1 v₂1 dq2 v₀2 v₁2 v₂2 :\n    record3_model l dq1 v₀1 v₁1 v₂1 -∗\n    record3_model l dq2 v₀2 v₁2 v₂2 -∗\n    ⌜v₀1 = v₀2 ∧ v₁1 = v₁2 ∧ v₂1 = v₂2⌝.\n  Proof.\n    iIntros \"Hl1 Hl2\".\n    iDestruct (record3_model_valid_2 with \"Hl1 Hl2\") as %?. naive_solver.\n  Qed.\n  Lemma record3_model_dfrac_ne l1 dq1 v₀1 v₁1 v₂1 l2 dq2 v₀2 v₁2 v₂2 :\n    ¬ ✓ (dq1 ⋅ dq2) →\n    record3_model l1 dq1 v₀1 v₁1 v₂1 -∗\n    record3_model l2 dq2 v₀2 v₁2 v₂2 -∗\n    ⌜l1 ≠ l2⌝.\n  Proof.\n    iIntros \"% Hl1 Hl2\" (->).\n    iDestruct (record3_model_valid_2 with \"Hl1 Hl2\") as %?. naive_solver.\n  Qed.\n  Lemma record3_model_ne l1 v₀1 v₁1 v₂1 l2 dq2 v₀2 v₁2 v₂2 :\n    record3_model l1 (DfracOwn 1) v₀1 v₁1 v₂1 -∗\n    record3_model l2 dq2 v₀2 v₁2 v₂2 -∗\n    ⌜l1 ≠ l2⌝.\n  Proof.\n    iApply record3_model_dfrac_ne. intros []%exclusive_l. apply _.\n  Qed.\n  Lemma record3_model_exclusive l v₀1 v₁1 v₂1 v₀2 v₁2 v₂2 :\n    record3_model l (DfracOwn 1) v₀1 v₁1 v₂1 -∗\n    record3_model l (DfracOwn 1) v₀2 v₁2 v₂2 -∗\n    False.\n  Proof.\n    iIntros \"Hl1 Hl2\".\n    iDestruct (record3_model_ne with \"Hl1 Hl2\") as %?. naive_solver.\n  Qed.\n\n  Lemma record3_dfrac_relax dq l v₀ v₁ v₂ :\n    ✓ dq →\n    record3_model l (DfracOwn 1) v₀ v₁ v₂ ==∗\n    record3_model l dq v₀ v₁ v₂.\n  Proof.\n    iIntros \"% (Hv₀ & Hv₁ & Hv₂)\".\n    iMod (mapsto_dfrac_relax with \"Hv₀\") as \"Hv₀\"; first done.\n    iMod (mapsto_dfrac_relax with \"Hv₁\") as \"Hv₁\"; first done.\n    iMod (mapsto_dfrac_relax with \"Hv₂\") as \"Hv₂\"; first done.\n    iFrame. done.\n  Qed.\n\n  Lemma record3_make_spec v₀ v₁ v₂ :\n    {{{ True }}}\n      record3_make v₀ v₁ v₂\n    {{{ l, RET #l; record3_model l (DfracOwn 1) v₀ v₁ v₂ ∗ meta_token l ⊤ }}}.\n  Proof.\n    iIntros \"%Φ _ HΦ\".\n    wp_rec. wp_pures.\n    wp_apply (wp_allocN with \"[//]\"); first done. iIntros \"%l (Hl & Hmeta & _)\". rewrite loc_add_0.\n    wp_pures.\n    iDestruct (array_cons with \"Hl\") as \"(Hv₀ & Hl)\".\n    iEval (setoid_rewrite <- loc_add_0) in \"Hv₀\".\n    iDestruct (array_cons with \"Hl\") as \"(Hv₁ & Hl)\".\n    iDestruct (array_singleton with \"Hl\") as \"Hv₂\".\n    rewrite loc_add_assoc Z.add_1_r -Z.two_succ.\n    wp_store. wp_store.\n    iApply \"HΦ\". iFrame. done.\n  Qed.\n\n  Lemma record3_get0_spec l dq v₀ v₁ v₂ :\n    {{{ record3_model l dq v₀ v₁ v₂ }}}\n      !#l.(0)\n    {{{ RET v₀; record3_model l dq v₀ v₁ v₂ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂) HΦ\".\n    wp_load.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂]\").\n  Qed.\n  Lemma record3_get1_spec l dq v₀ v₁ v₂ :\n    {{{ record3_model l dq v₀ v₁ v₂ }}}\n      !#l.(1)\n    {{{ RET v₁; record3_model l dq v₀ v₁ v₂ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂) HΦ\".\n    wp_load.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂]\").\n  Qed.\n  Lemma record3_get2_spec l dq v₀ v₁ v₂ :\n    {{{ record3_model l dq v₀ v₁ v₂ }}}\n      !#l.(2)\n    {{{ RET v₂; record3_model l dq v₀ v₁ v₂ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂) HΦ\".\n    wp_load.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂]\").\n  Qed.\n\n  Lemma record3_set0_spec l v₀ v₁ v₂ v :\n    {{{ record3_model l (DfracOwn 1) v₀ v₁ v₂ }}}\n      #l.(0) <- v\n    {{{ RET #(); record3_model l (DfracOwn 1) v v₁ v₂ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂) HΦ\".\n    wp_store.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂]\").\n  Qed.\n  Lemma record3_set1_spec l v₀ v₁ v₂ v :\n    {{{ record3_model l (DfracOwn 1) v₀ v₁ v₂ }}}\n      #l.(1) <- v\n    {{{ RET #(); record3_model l (DfracOwn 1) v₀ v v₂ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂) HΦ\".\n    wp_store.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂]\").\n  Qed.\n  Lemma record3_set2_spec l v₀ v₁ v₂ v :\n    {{{ record3_model l (DfracOwn 1) v₀ v₁ v₂ }}}\n      #l.(2) <- v\n    {{{ RET #(); record3_model l (DfracOwn 1) v₀ v₁ v }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂) HΦ\".\n    wp_store.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂]\").\n  Qed.\nEnd heapGS.\n\n#[global] Opaque record3_make.\n\n#[global] Opaque record3_model.\n", "meta": {"author": "clef-men", "repo": "caml5", "sha": "0de06d5792138eb17877ed1536a0401b7a322ee2", "save_path": "github-repos/coq/clef-men-caml5", "path": "github-repos/coq/clef-men-caml5/caml5-0de06d5792138eb17877ed1536a0401b7a322ee2/theories/std/record3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24457149227526198}}
{"text": "\nRequire Import VST.floyd.proofauto.\nRequire Import mk_acc.\nFrom SSL_VST Require Import core.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition malloc_spec :=\n  DECLARE _malloc\n        WITH t: type\n        PRE [ tuint ]\n        PROP()\n        PARAMS(Vint (Int.repr (sizeof t)))\n        SEP()\n        POST [tptr tvoid] EX p:_,\n        PROP()\n        RETURN(p)\n        SEP(data_at_ Tsh t p).\n\nInductive account_card : Set :=\n    | account_card_0 : account_card.\n\nFixpoint account (x: val) (id: Z) (bal: Z) (self_card: account_card) {struct self_card} : mpred := match self_card with\n    | account_card_0  =>  !!(is_true true) && (data_at Tsh (tarray (Tunion _sslval noattr) 2) [(inl ((Vint (Int.repr id)) : val)); (inl ((Vint (Int.repr bal)) : val))] (x : val))\nend.\n\n\nDefinition mk_acc_spec :=\n  DECLARE _mk_acc\n   WITH r: val, id: val, bal: Z\n   PRE [ (tptr (Tunion _sslval noattr)), tint ]\n   PROP( is_pointer_or_null((r : val)); ssl_is_valid_int((id : val)) )\n   PARAMS(r; id)\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inl ((Vint (Int.repr bal)) : val))] (r : val)))\n   POST[ tvoid ]\n   EX x: val,\n   EX _alpha_513: account_card,\n   PROP( is_pointer_or_null((x : val)) )\n   LOCAL()\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inr (x : val))] (r : val)); (account (x : val) (force_signed_int (id : val)) (bal : Z) (_alpha_513 : account_card))).\n\nLemma account_x_valid_pointerP x id bal self_card: account x id bal self_card |-- valid_pointer x. Proof. destruct self_card; simpl; entailer;  entailer!; eauto. Qed.\nHint Resolve account_x_valid_pointerP : valid_pointer.\nLemma account_local_factsP x id bal self_card :\n  account x id bal self_card|-- !!((((is_true true)) -> (self_card = account_card_0))/\\is_pointer_or_null((x : val))).\n Proof.  destruct self_card;  simpl; entailer; saturate_local; apply prop_right; eauto. Qed.\nHint Resolve account_local_factsP : saturate_local.\nLemma unfold_account_card_0  (x: val) (id: Z) (bal: Z) : account x id bal (account_card_0 ) =  !!(is_true true) && (data_at Tsh (tarray (Tunion _sslval noattr) 2) [(inl ((Vint (Int.repr id)) : val)); (inl ((Vint (Int.repr bal)) : val))] (x : val)). Proof. auto. Qed.\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [mk_acc_spec; malloc_spec]).\n\nLemma body_mk_acc : semax_body Vprog Gprog f_mk_acc mk_acc_spec.\nProof.\nstart_function.\nssl_open_context.\nassert_PROP (isptr r). { entailer!. }\ntry rename bal into bal2.\nforward.\nforward_call (tarray (Tunion _sslval noattr) 2).\nIntros x2.\nassert_PROP (isptr x2). { entailer!. }\nforward.\nforward.\nforward.\nforward; entailer!.\nExists (x2 : val).\nExists (account_card_0  : account_card).\nssl_entailer.\nrewrite (unfold_account_card_0 ) at 1.\nssl_entailer.\n\nQed.", "meta": {"author": "TyGuS", "repo": "ssl-vst", "sha": "638107b15e18608ef364ae1d900eb2d2aaf8a475", "save_path": "github-repos/coq/TyGuS-ssl-vst", "path": "github-repos/coq/TyGuS-ssl-vst/ssl-vst-638107b15e18608ef364ae1d900eb2d2aaf8a475/examples/verif_mk_acc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24457149227526195}}
{"text": "Require Import MirrorCharge.ModularFunc.ILogicFunc.\nRequire Import MirrorCharge.ModularFunc.BILogicFunc.\nRequire Import MirrorCharge.SynSepLog.\nRequire Import MirrorCharge.SepLogFold.\nRequire Export MirrorCore.RTac.RTac.\nRequire Export MirrorCore.RTac.Core.\n(*Require Import MirrorCore.STac.STac.*)\nRequire Export mc_reify.bool_funcs.\nRequire MirrorCore.syms.SymEnv.\nRequire MirrorCore.syms.SymSum.\nRequire Import MirrorCore.Subst.FMapSubst.\n(*Require Import MirrorCharge.RTac.ReifyLemma.*)\nRequire Import floyd_funcs.\nRequire Export MirrorCore.Lambda.Expr.\nRequire Export mc_reify.types.\nRequire Export mc_reify.func_eq.\nRequire Export mc_reify.funcs.\n\nDefinition typeof_func_opt t := Some (typeof_func t).\n\nDefinition eqb_sym a b := match func_beq a b with\n                        | true => Some true\n                        | false => None\nend.\n\nGlobal Instance RSym_Func' : SymI.RSym func' := {\n   typeof_sym := typeof_func_opt;\n   symD := funcD;\n   sym_eqb := eqb_sym\n}.\n\nGlobal Instance RSymOk_Func' : SymI.RSymOk RSym_Func'.\nconstructor.\nintros. unfold sym_eqb. simpl. unfold eqb_sym. simpl.\ndestruct (func_beq a b) eqn :?. apply func_beq_sound. auto.\nauto.\nQed.\n\n\nDefinition appR (e1 : func') e2 :=\nApp (@Inj typ func (inr e1)) (e2).\nDefinition injR (e1 : func') := @Inj typ func (inr e1).\n\nInstance ILogicOps_mpred : ILogic.ILogicOps expr.mpred := {\nlentails := derives;\nltrue := TT;\nlfalse := FF;\nland := andp;\nlor := orp;\nlimpl := imp;\nlforall := @allp mpred _;\nlexists := @exp mpred _\n}.\n\nInstance ILogic_mpred : ILogic.ILogic mpred.\nProof.\nsplit; intros.\n+ split.\n  * intro x; apply derives_refl.\n  * intros x y z Hxy Hyz; apply derives_trans with y; assumption.\n+ apply prop_right. apply I.\n+ apply prop_left. intro H; destruct H.\n+ apply allp_left with x; assumption.\n+ apply allp_right; apply H.\n+ apply exp_left; apply H.\n+ apply exp_right with x; apply H.\n+ apply andp_left1; apply H.\n+ apply andp_left2; apply H.\n+ apply orp_right1; apply H.\n+ apply orp_right2; apply H.\n+ apply andp_right; [apply H | apply H0].\n+ apply orp_left; [apply H | apply H0].\n+ apply imp_andp_adjoint. apply H.\n+ apply imp_andp_adjoint. apply H.\nQed.\n\nInstance BILOperators_mpred : BILogic.BILOperators mpred := {\n  empSP := emp;\n  sepSP := sepcon;\n  wandSP := wand\n}.\n\nInstance BILogic_mpred : BILogic.BILogic mpred.\nProof.\nsplit; intros.\n+ apply _.\n+ unfold BILogic.sepSP; simpl; rewrite sepcon_comm; apply derives_refl.\n+ unfold BILogic.sepSP; simpl; rewrite sepcon_assoc; apply derives_refl.\n+ apply wand_sepcon_adjoint.\n+ apply sepcon_derives; [apply H | apply derives_refl].\n+ unfold BILogic.sepSP; simpl; rewrite sepcon_emp; reflexivity.\nQed.\n\n\nDefinition ilops : @logic_ops _ RType_typ :=\nfun t =>\n  match t\n          return option (ILogic.ILogicOps (typD t))\n  with\n  | tympred => Some _\n  | typrop => Some _\n  | _ => None\nend.\n\nDefinition bilops : @bilogic_ops _ RType_typ :=\nfun t =>\n  match t\n          return option (BILogic.BILOperators (typD t))\n  with\n  | tympred => Some _\n  | _ => None\nend.\n\nInstance RSym_ilfunc : RSym (@ilfunc typ) :=\n\tRSym_ilfunc _ _ ilops.\nInstance RSym_bilfunc : RSym (@bilfunc typ) :=\n\tRSym_bilfunc _ bilops.\n\nExisting Instance SymSum.RSym_sum.\nExisting Instance SymSum.RSymOk_sum.\n\nDefinition subst : Type :=\n  FMapSubst.SUBST.raw (expr typ func).\nInstance SS : SubstI.Subst subst (expr typ func) :=\n  @FMapSubst.SUBST.Subst_subst _.\n(*Instance SU : SubstI.SubstUpdate subst (expr typ func) :=\n  FMapSubst.SUBST.SubstUpdate_subst (@instantiate typ func).\nInstance SO : SubstI.SubstOk SS :=\n  @FMapSubst.SUBST.SubstOk_subst typ RType_typ (expr typ func) _ _.\n*)\n\nDefinition RSym_sym fs := SymSum.RSym_sum\n  (SymSum.RSym_sum (SymSum.RSym_sum (SymEnv.RSym_func fs) RSym_ilfunc) RSym_bilfunc)\n  RSym_Func'.\n\n\nSearchAbout Expr.\nDefinition Expr_expr_fs fs: ExprI.Expr _ (ExprCore.expr typ func) := @ExprD.Expr_expr typ func _ _ (RSym_sym fs).\nDefinition Expr_ok_fs fs: @ExprI.ExprOk typ RType_typ (ExprCore.expr typ func) (Expr_expr_fs fs) := ExprD.ExprOk_expr.\n\nDefinition reflect ft tus tvs e (ty : typ)\n := @exprD _ _ _ (Expr_expr_fs ft) tus tvs e ty.\n\nDefinition reflect_prop tbl e := reflect tbl nil nil e (typrop).\n\nDefinition reflect_prop' tbl e := match (reflect tbl nil nil e typrop) with\n| Some p => p\n| None => False\nend.\n\nDefinition node l o r t : expr typ func :=\n(App (App (App (Inj (inr (Data (fnode t)))) l) o) r).\n\nDefinition leaf t : expr typ func:=\n(Inj (inr (Data (fleaf t)))).\n\nDefinition some_reif e t : expr typ func :=\n(App (Inj (inr (Other (fsome t)))) e).\n\nDefinition none_reif t : expr typ func :=\n(Inj (inr (Other (fnone t)))).\n\nInstance MA : MentionsAny (expr typ func) := {\n  mentionsAny := ExprCore.mentionsAny\n}.\n\nLet elem_ctor : forall x : typ, typD x -> @SymEnv.function typ _ :=\n  @SymEnv.F _ _.\n\nLet Ext x := @ExprCore.Inj typ func (inl (inl (inl x))).\n\nSection tbled.\n\nVariable tbl : SymEnv.functions RType_typ.\n\nLet RSym_sym := RSym_sym tbl.\nExisting Instance RSym_sym.\nLet Expr_expr := Expr_expr_fs tbl.\nExisting Instance Expr_expr.\nExisting Instance Expr_ok_fs.\n\nDefinition exprD_Prop (uvar_env var_env : EnvI.env) (e : expr typ func) :=\n  match exprD uvar_env var_env e typrop with\n    | Some e' => e'\n    | None => True\n  end.\n\nDefinition goalD_Prop (uvar_env var_env : EnvI.env) goal :=\n  let (tus, us) := split_env uvar_env in\n  let (tvs, vs) := split_env var_env in\n  match goalD tus tvs goal with\n    | Some e => e us vs\n    | None => False\n  end.\n\nDefinition goalD_aux tus tvs goal (us : HList.hlist typD tus) (vs : HList.hlist typD tvs) :=\n  match goalD tus tvs goal with\n    | Some e => Some (e us vs)\n    | None => None\n  end.\n\nEnd tbled.\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/mc_reify/func_defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24457149227526195}}
{"text": "Require Import msl.msl_standard.\nRequire Import Maps.\nRequire Import FuncListMachine.\nRequire Import lemmas.\nRequire Import hoare_total.\nRequire Import wp.\n\n(* This is some tentative work-in-progress *)\n\nFixpoint list_nat (n:nat) (x:value) {struct n} :=\n  match n, x with\n  | 0, value_label 1%positive => True\n  | S n', value_cons (value_label 1%positive) x' => list_nat n' x'\n  | _, _ => False\n  end.\n\nFixpoint list_length (x:value) :=\n  match x with\n  | value_cons _ x' => S (list_length x')\n  | _ => 0\n  end.\n\nDefinition list_nat_var (n:nat) (v:var) (r:store) :=\n  match r#v with\n  | None => False\n  | Some x => list_nat n x\n  end.\n\nProgram Definition add_term_measure : termMeas :=\n  fun r n =>\n  match r#(V 1) with\n  | Some x => list_length x = n\n  | None => False\n  end.\nNext Obligation.\n destruct x as [ | x o0 x1] ; [contradiction H | ].\n destruct x; [ contradiction H | simpl in *] .\n destruct o; simpl in *;  [congruence | contradiction].\nQed.\n\nDefinition add_P' n m st :=\n    list_nat_var n (V 1) st /\\\n    list_nat_var m (V 2) st.\n\nDefinition add_Q' n m st := list_nat_var (n+m) (V 2) st.\n\nDefinition add_P (nm:nat*nat) := store_op (add_P' (fst nm) (snd nm)).\nDefinition add_Q (nm:nat*nat) := store_op (add_Q' (fst nm) (snd nm)).\n\nDefinition valueTermMeas :=\n  { R: value -> nat -> Prop |\n    forall v n n', R v n -> R v n' -> n = n' }.\n\nRecord stdFunspec A :=\n  { sfs_t     : valueTermMeas\n  ; sfs_P     : A -> value -> pred prog\n  ; sfs_Q     : A -> value -> pred prog\n  }.\n\nImplicit Arguments sfs_t.\nImplicit Arguments sfs_P.\nImplicit Arguments sfs_Q.\n\nProgram Definition value_to_store_termMeas (vt:valueTermMeas) : termMeas :=\n  fun s n => match s#(V 0) with\n             | Some v => proj1_sig vt v n\n             | None   => False\n             end.\nNext Obligation.\n  destruct x; simpl in *; intuition.\n  destruct o; simpl in *; intuition.\n  destruct vt; simpl in *.\n  eauto.\nQed.\n\n(* Define a simple calling convention for \"standard\"\n   functions.  register 0 is for arguments and results.\n   registers 1 2 3 and 4 are callee-saves registers,\n   and registers >= 5 are caller-saves.\n\n   It is not specified, but register 1 is usually\n   used as a value stack.\n *)\nDefinition stdfun (l:label) (fs:{A:Type & stdFunspec A}) :=\n  funptr l (projT1 fs * (value*value*value*value))\n         (value_to_store_termMeas (sfs_t (projT2 fs)))\n         (fun avs =>\n           match avs with\n             (a,(v1,v2,v3,v4)) =>\n             EX v0:_,\n             world_op\n               (sfs_P (projT2 fs) a v0)\n               (fun s =>\n                 s#(V 0) = Some v0 /\\\n                 s#(V 1) = Some v1 /\\\n                 s#(V 2) = Some v2 /\\\n                 s#(V 3) = Some v3 /\\\n                 s#(V 4) = Some v4)\n           end)\n         (fun avs =>\n           match avs with\n             (a,(v1,v2,v3,v4)) =>\n             EX v0:_,\n             world_op\n                (sfs_Q (projT2 fs) a v0)\n                (fun s =>\n                  s#(V 0) = Some v0 /\\\n                  s#(V 1) = Some v1 /\\\n                  s#(V 2) = Some v2 /\\\n                  s#(V 3) = Some v3 /\\\n                  s#(V 4) = Some v4)\n           end).\n\nDefinition apply_P (fs:{ A:Type & stdFunspec A}) (x:projT1 fs) (v:value) : pred prog :=\n  match v with\n  | value_cons (value_label l) v' =>\n       stdfun l fs && sfs_P (projT2 fs) x v'\n  | _ => FF\n  end.\n\nDefinition apply_Q (fs:{A :Type & stdFunspec A}) (x:projT1 fs) (v:value) : pred prog :=\n  sfs_Q (projT2 fs) x v.\n\nProgram Definition apply_tm (fs:{A:Type & stdFunspec A}) : valueTermMeas :=\n  fun v n =>\n  match v, n with\n  | value_cons (value_label l) v', S n' =>\n      sfs_t (projT2 fs) v' n'\n  | _, _ => False\n  end.\nNext Obligation.\n  destruct v; simpl in *; intuition.\n  discriminate.\n  destruct v1; simpl in *; intuition; discriminate.\nQed.\nNext Obligation.\n intros [? ?].\n inv H.\nQed.\nNext Obligation.\n destruct v; simpl in *; try contradiction.\n destruct v1; simpl in *; try contradiction.\n destruct n; simpl in *; try contradiction.\n destruct n'; simpl in *; try contradiction.\n destruct fs; simpl in *.\n destruct s; simpl in *.\n destruct sfs_t0; simpl in *.\n f_equal; eapply e; eauto.\nQed.\n\nDefinition apply_fs (fs:{A:Type & stdFunspec A}) : {A:Type & stdFunspec A} :=\n  existT _ (projT1 fs)\n     (Build_stdFunspec (projT1 fs) (apply_tm fs) (apply_P fs) (apply_Q fs)).\n\nProgram Definition phi : map instruction :=\n  set _ (set _ (set _ (set _ (set _ (set _ (empty _)\n\n  (* The \"map\" wrapper function *)\n  (L 5)\n    ( (* push the values of V2 and V3 *)\n      instr_cons (V 2) (V 1) (V 1) ;;\n      instr_cons (V 3) (V 1) (V 1) ;;\n      (* load the function pointer into V2 *)\n      instr_fetch_field (V 0) 0 (V 2) ;;\n      (* load the remainder of the list into V3 *)\n      instr_fetch_field (V 0) 1 (V 3) ;;\n      (* call the map worker function *)\n      instr_getlabel (L 4) (V 5) ;;\n      instr_call (V 5) ;;\n      (* restore V3 *)\n      instr_fetch_field (V 1) 0 (V 3) ;;\n      instr_fetch_field (V 1) 1 (V 1) ;;\n      (* restore V2 *)\n      instr_fetch_field (V 1) 0 (V 2) ;;\n      instr_fetch_field (V 1) 1 (V 1) ;;\n      instr_return\n    ))\n\n  (* The \"map\" worker function *)\n  (L 4)\n    ( instr_if_nil (V 3)\n       (*if nil, return nil *)\n        ( instr_getlabel (L 0) (V 0) ;;\n          instr_return )\n       (*otherwise, recursive call*)\n        ( (* get the head of the list *)\n          instr_fetch_field (V 3) 0 (V 0) ;;\n          (* call the mapping function *)\n          instr_call (V 2) ;;\n          (* push the mapped value *)\n          instr_cons (V 0) (V 1) (V 1) ;;\n          (* pop the head of the list *)\n          instr_fetch_field (V 3) 1 (V 3) ;;\n          (* recursive \"map\" call *)\n          instr_getlabel (L 4) (V 5) ;;\n          instr_call (V 5) ;;\n          (* add the new list head *)\n          instr_fetch_field (V 1) 0 (V 5) ;;\n          instr_cons (V 5) (V 0) (V 0) ;;\n          (* pop the stack *)\n          instr_fetch_field (V 1) 1 (V 1) ;;\n          instr_return\n         )\n       (* endif *)\n    ))\n\n  (* The \"succ\" function *)\n  (L 3)\n    ( instr_getlabel (L 0) (V 5) ;;\n      instr_cons (V 5) (V 0) (V 0) ;;\n      instr_return\n    ))\n\n  (* Set up a double-indirect call to succ.\n     Call apply, which indirectly calls apply to\n     call succ.\n  *)\n  (L 2)\n    ( instr_getlabel (L 0) (V 0) ;;\n      instr_getlabel (L 3) (V 1) ;;\n      instr_getlabel (L 0) (V 2) ;;\n      instr_getlabel (L 0) (V 3) ;;\n      instr_getlabel (L 0) (V 4) ;;\n      instr_cons (V 2) (V 0) (V 0) ;;\n      instr_cons (V 2) (V 0) (V 0) ;;\n      instr_cons (V 1) (V 0) (V 0) ;;\n      instr_getlabel (L 1) (V 1) ;;\n      instr_cons (V 1) (V 0) (V 0) ;;\n      instr_call (V 1) ;;\n      instr_return\n    ))\n\n  (* The \"apply\" function *)\n  (L 1)\n    ( instr_fetch_field (V 0) 0 (V 5) ;;\n      instr_fetch_field (V 0) 1 (V 0) ;;\n      instr_call (V 5) ;;\n      instr_return\n    ))\n\n  (* An addition function *)\n  (L 0)\n    ( instr_assert (EX nm:_, add_P nm) ;;\n      instr_if_nil (V 1)\n        (*then *) (\n          instr_return\n        ) (*else *) (\n          (instr_fetch_field (V 1) 0 (V 3) ;;\n          instr_fetch_field (V 1) 1 (V 1) ;;\n          instr_cons (V 3) (V 2) (V 2)) ;;\n          instr_getlabel (L 0) (V 0) ;;\n          (instr_call (V 0) ;;\n           instr_return)\n        )\n    ).\n\nProgram Definition succ_fs : stdFunspec nat :=\n  Build_stdFunspec nat\n    (fun _ n => n = 0)\n    (fun n v => !!(list_nat n v))\n    (fun n v => !!(list_nat (S n) v)).\n\nDefinition succ_fs' : {A:Type & stdFunspec A} :=\n  existT (fun X => stdFunspec X) nat succ_fs.\n\nLemma succ_verify : forall G,\n  verify_prog phi G ->\n  verify_prog\n    phi\n    (stdfun (L 3) succ_fs' && G).\nProof.\n  intros.\n  eapply verify_func_simple; auto.\n  simpl. reflexivity.\n  clear H.\nOpaque get set funptr.\n  simpl; intros.\n  apply hoare_wp. simpl.\n  intros [? ?].\n  simpl. intuition.\n  destruct a as [x [[[v1 v2] v3] v4]].\n  destruct H0 as [v0 [? ?]].\n  intuition.\n  rewrite H7 in H5.\n  inv H5.\n  inv H3.\n  simpl in H0.\n  rewrite get_set_same.\n  rewrite get_set_other. 2: discriminate.\n  do 2 econstructor. intuition; eauto.\n  inv H3.\n  econstructor; split.\n  2: repeat split;\n    repeat (rewrite get_set_other; [ | discriminate]);\n        try rewrite get_set_same; auto.\n  simpl. auto.\nQed.\n\nSection map_tm.\n  Variable (f_tm : valueTermMeas).\n\n  Fixpoint map_inner_tm (v:value) : nat -> Prop :=\n    fun n =>\n    match v with\n      | value_label _ => n = 0\n      | value_cons v1 v2 =>\n          exists x1, exists x2,\n           proj1_sig f_tm v1 x1 /\\\n           map_inner_tm v2 x2  /\\\n           n = 1 + x1 + 1 + x2\n    end.\n\n  Lemma map_inner_tm_fun : forall v x1 x2,\n    map_inner_tm v x1 ->\n    map_inner_tm v x2 ->\n    x1 = x2.\n  Proof.\n    induction v; simpl; intros. congruence.\n    destruct H as [a1 [a2 [? [? ?]]]].\n    destruct H0 as [b1 [b2 [? [? ?]]]].\n    subst.\n    cut (a1 = b1 /\\ a2 = b2).\n    intuition congruence.\n    split; auto.\n    eapply (proj2_sig f_tm); eauto.\n  Qed.\nEnd map_tm.\n\nProgram Definition map_worker_tm (fs:{A:Type & stdFunspec A}) : termMeas :=\n  fun s n =>\n  match s#(V 3) with\n  | Some v => map_inner_tm (sfs_t (projT2 fs)) v n\n  | _ => False\n  end.\nNext Obligation.\n congruence.\nQed.\nNext Obligation.\n simpl in *.\n  destruct (x#4); simpl in *; intuition.\n  eapply map_inner_tm_fun; eauto.\nQed.\n\nProgram Definition map_tm (fs:{A:Type & stdFunspec A}) : valueTermMeas :=\n  fun v n =>\n  match v, n with\n  | value_cons _ v, S n'  =>\n     map_inner_tm (sfs_t (projT2 fs)) v n'\n  | _, _ => False\n  end.\nNext Obligation.\nintros [? ?]. inv H.\nQed.\nNext Obligation.\n  destruct v. elim H.\n  destruct n; destruct n'; try tauto.\n  f_equal.\n  eapply map_inner_tm_fun; eauto.\nQed.\n\nSection map_pre_post.\n  Variable A:Type.\n  Variable P:A->value->pred prog.\n\n  Fixpoint list_val_match (l:list A) (v:value) {struct l} : pred prog :=\n    match l, v with\n    | nil, value_label 1%positive => TT\n    | x::l', value_cons v1 v2 => P x v1 && list_val_match l' v2\n    | _, _ => FF\n    end.\nEnd map_pre_post.\n\nDefinition map_worker_pre (fs:{A:Type & stdFunspec A}) (x:value*label*list (projT1 fs)*value) :=\n  match x with\n    (v1,lab,l,v4) =>\n    EX v3:_,\n    world_op\n      (stdfun lab fs &&\n       list_val_match (projT1 fs) (sfs_P (projT2 fs)) l v3)\n      (fun s =>\n         s#(V 1) = Some v1 /\\\n         s#(V 2) = Some (value_label lab) /\\\n         s#(V 3) = Some v3 /\\\n         s#(V 4) = Some v4)\n  end.\n\nDefinition map_worker_post (fs:{A:Type & stdFunspec A}) (x:value*label*list (projT1 fs)*value) :=\n  match x with\n    (v1,lab,l,v4) =>\n    EX v0:_,\n    world_op\n      (stdfun lab fs &&\n        list_val_match (projT1 fs) (sfs_Q (projT2 fs)) l v0)\n      (fun s =>\n         s#(V 0) = Some v0 /\\\n         s#(V 1) = Some v1 /\\\n         s#(V 2) = Some (value_label lab) /\\\n         s#(V 4) = Some v4)\n  end.\n\nDefinition map_pre\n  (fs:{A:Type & stdFunspec A})\n  l\n  (x:value) :=\n  match x with\n  | value_cons (value_label lab) v =>\n      stdfun lab fs &&\n      list_val_match (projT1 fs) (sfs_P (projT2 fs)) l v\n  | _ => FF\n  end.\n\nDefinition map_post\n  (fs:{A:Type & stdFunspec A})\n  l\n  (x:value) :=\n  list_val_match (projT1 fs) (sfs_Q (projT2 fs)) l x.\n\nDefinition map_spec (fs:{A:Type & stdFunspec A}) : {A:Type & stdFunspec A} :=\n  existT (fun X => stdFunspec X) (list (projT1 fs))\n    (Build_stdFunspec _ (map_tm fs) (map_pre fs) (map_post fs)).\n\nLemma map_worker_verify : forall G,\n  verify_prog phi G ->\n  verify_prog\n    phi\n    ((ALL fs:{A:Type & stdFunspec A},\n         funptr (L 4) _ (map_worker_tm fs) (map_worker_pre fs) (map_worker_post fs)) && G).\nProof.\n  intros.\nTransparent get set.\n  eapply verify_func; auto.\n  simpl. reflexivity.\n  clear H.\nOpaque get set funptr.\n  simpl; intros.\n  apply hoare_wp. simpl.\n  intros [? ?].\n  simpl. intuition.\n  destruct a as [[[v1 lab] l] v4].\n  clear H2. unfold map_worker_pre in H0.\n  destruct H0 as [v3 [[? ?] ?]].\n  intuition.\n  clear H.\n  econstructor. intuition.\n  eauto.\n  destruct l; simpl in H2; [ left | right ].\n  destruct v3; try (elim H2; fail).\n  destruct l; try (elim H2; fail).\n  split; auto.\n  intros. inv H.\n  unfold map_worker_post.\n  simpl. exists (value_label 1%positive).\n  intuition;\n    repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  destruct v3; try (elim H2; fail).\n  destruct H2.\n  split. eauto.\n  do 2 econstructor; intuition.\n  eauto.\n  hnf in H5.\n  unfold map_worker_tm in H5.\n  simpl in H7.\n  rewrite H7 in H5. simpl in H5.\n  destruct H5 as [n0 [n1 [? [? ?]]]].\n  subst n.\n  exists (1+n0). exists (1+n1).\n  split. 2: omega.\n  inv H8.\n  do 5 econstructor; intuition.\n  exists n0.\n  econstructor.\n  intuition.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  eauto.\n  2: apply H0.\n  simpl.\n  rewrite get_set_same; auto.\n  simpl.\n  instantiate (1:=(p0,(v1,(value_label lab),value_cons v3_1 v3_2,v4))).\n  simpl. econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  eauto.\n  simpl in H12.\n  destruct a'.\n  hnf in H8. simpl in H8. subst.\n  destruct a'0.\n  rewrite worldNec_unfold in H11.\n  destruct H11; subst.\n  destruct H12; intuition.\n  do 2 econstructor; intuition; eauto.\n  inv H16.\n  do 2 econstructor. intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  eauto.\n  inv H16. inv H18.\n  do 5 econstructor. exists n1.\n  exists (value_cons x v1,lab,l,v4).\n  intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  2: eapply pred_nec_hereditary; [ | apply H1 ]; auto.\n  unfold map_worker_tm. simpl.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  simpl. split.\n  econstructor; intuition; auto.\n  eapply pred_nec_hereditary; eauto.\n  eapply pred_nec_hereditary; eauto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  split. auto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  simpl.\n  exists n1. split. auto.\n  omega.\n  destruct a'. destruct a'0.\n  inv H16. rewrite worldNec_unfold in H18.\n  destruct H18; simpl in *; subst.\n  destruct H19 as [? [? ?] ?]; intuition.\n  do 2 econstructor; intuition; eauto.\n  inv H23.\n  do 2 econstructor; intuition;\n    repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H23.\n  do 2 econstructor; intuition;\n    repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H23.\n  exists (value_cons x x0); intuition.\n  split; auto.\n  eapply pred_nec_hereditary; eauto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n    repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\nQed.\n\nLemma map_verify : forall G,\n    verify_prog phi G ->\n    verify_prog\n    phi\n    ((ALL fs:{A:Type & stdFunspec A}, stdfun (L 5) (map_spec fs)) &&\n    ((ALL fs:{A:Type & stdFunspec A},\n         funptr (L 4) _ (map_worker_tm fs) (map_worker_pre fs) (map_worker_post fs))\n        && G)).\nProof.\n  intros.\nTransparent get set.\n  eapply verify_func.\n  simpl. auto.\n  2: apply map_worker_verify; auto.\n  clear H.\nOpaque get set funptr.\n  simpl; intros.\n  apply hoare_wp. simpl.\n  intros [? ?].\n  simpl. intuition.\n  destruct a as [x [[[v1 v2] v3] v4]].\n  destruct H0 as [v0 [? ?]]. intuition.\n  rewrite H7 in H5.\n  clear H H2.\n  unfold map_pre in H0.\n  destruct v0; try (elim H0; fail).\n  destruct v0_1; try (elim H0; fail).\n  destruct H0.\n  do 2 econstructor; intuition; eauto.\n  inv H2.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H2.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H2.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H2; inv H10.\n  simpl in H5.\n  destruct n; try tauto.\n  do 5 econstructor.\n  exists n.\n  exists (value_cons v3 (value_cons v2 v1),l,x,v4).\n  intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  unfold map_worker_tm. simpl.\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  simpl. econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; auto.\n  eauto.\n  destruct a'; destruct a'0.\n  rewrite worldNec_unfold in H10.\n  destruct H10; subst.\n  destruct H12 as [? [? ?] ?]; intuition.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H16.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H16.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H16.\n  do 2 econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\n  inv H16.\n  destruct H2. simpl in *; subst.\n  econstructor; intuition;\n  repeat (rewrite get_set_other; [ | discriminate]);\n      try rewrite get_set_same; eauto.\nQed.\n\nLemma apply_verify : forall G,\n  verify_prog phi G ->\n  verify_prog\n    phi\n    ((ALL fs:{A:Type & stdFunspec A}, stdfun (L 1) (apply_fs fs)) && G).\nProof.\n  intros.\nTransparent get set.\n  eapply verify_func; auto.\n  simpl. reflexivity.\n  clear H.\nOpaque get set funptr.\n  simpl; intros.\n  apply hoare_wp. simpl.\n  intros [? ?].\n  simpl. intuition.\n  destruct a as [x [[[v1 v2] v3] v4]].\n  destruct H0 as [v0 [? ?]]. intuition.\n  rewrite H6 in H5.\n  unfold apply_tm in H5.\n  destruct v0; try tauto.\n  destruct v0_1; try tauto.\n  destruct n; try tauto.\n  do 2 econstructor.\n  intuition; eauto.\n  inv H9.\n  do 2 econstructor.\n  intuition; eauto.\n  rewrite get_set_other. 2: discriminate.\n  eauto.\n  inv H9.\n  do 5 econstructor.\n  exists n.\n  exists (x,(v1,v2,v3,v4)).\n  econstructor.\n  intuition.\n  destruct H0.\n  3: apply H0.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_same. auto.\n  simpl.\n  simpl. rewrite get_set_same. auto.\n  simpl.\n  destruct H0.\n  econstructor. split. eauto.\n  repeat split;\n  repeat (rewrite get_set_other; [ | discriminate]);\n    try rewrite get_set_same; auto.\n  simpl. intros. auto.\nQed.\n\nLemma add_verify : forall G,\n  verify_prog phi G ->\n  verify_prog phi (funptr (L 0) _ add_term_measure add_P add_Q && G).\nProof.\n  intros. eapply verify_func_simple; auto.\n\nTransparent get set.\n  simpl. reflexivity.\n  intros.\nOpaque get set funptr.\n  intros. apply hoare_wp.\n  subst Pr Pr'. simpl.\n  intros [? ?].\n  destruct a as [n1 m1]; simpl in *.\n  simpl; intuition.\n  exists (n1,m1). simpl; split; auto.\n  intuition; subst; auto.\n  destruct H6.\n  hnf in H4, H6. simpl V in *.\n  case_eq (s#2); intros;\n    rewrite H8 in H4; try tauto.\n  case_eq (s#3); intros;\n    rewrite H9 in H6; try tauto.\n  unfold add_term_measure in H7.\n  simpl in H7; rewrite H8 in H7.\n  inv H7.\n  exists v; intuition.\n  destruct n1; simpl in H4;\n    destruct v; try tauto.\n  destruct l; try tauto.\n  left; simpl; intuition.\n  hnf. simpl. rewrite H9. auto.\n  destruct v1; try tauto.\n  destruct l; try tauto.\n  simpl in *.\n  right; simpl; intuition.\n  eauto.\n  do 2 econstructor; intuition.\n  inv H7.\n  do 2 econstructor; intuition.\n  rewrite get_set_other. 2: discriminate. eauto.\n  inv H7.\n  do 2 econstructor; intuition.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_same. auto.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_other. 2: discriminate.\n  eauto.\n  inv H7. inv H10.\n  exists (L 0). exists (nat * nat)%type.\n  exists add_term_measure.\n  do 2 econstructor.\n  exists (list_length v2).\n  exists (n1, S m1).\n  intuition.\n  rewrite get_set_same. auto.\n  unfold add_term_measure; simpl.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_same. auto.\n  apply H2.\n  simpl; intuition.\n  split; hnf; simpl.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_same. auto.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_same. auto.\n  exists (list_length v2).\n  unfold add_term_measure. simpl.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_other. 2: discriminate.\n  rewrite get_set_same. auto.\n  destruct a' as [? ?].\n  inv H7. simpl in *.\n  destruct a'0 as [? ?].\n  intuition; subst.\n  apply worldNec_unfold in H10. destruct H10; subst.\n  hnf in H13. hnf.\n  simpl V in *.\n  destruct (s1#3).\n  replace (S n1 + m1) with (n1 + S m1) by omega. auto.\n  auto.\nQed.\n\nProgram Definition main_tm : termMeas :=\n  fun _ n => n = 5.\n\nLet PROG_G :=\n  (funptr (L 2) unit main_tm\n                     (fun _ => TT)\n                     (fun _ => store_op (fun r => exists v, r#(V 0) = Some v /\\ list_nat 3 v))) &&\n  ((stdfun (L 3) succ_fs') &&\n   ((ALL fs:{A:Type & stdFunspec A}, stdfun (L 1) (apply_fs fs)) &&\n    ((funptr (L 0) _ add_term_measure add_P add_Q) && TT))).\n\nLemma main_verify :\n  verify_prog phi PROG_G.\nProof.\n  unfold PROG_G.\n  eapply verify_func_simple.\nTransparent get set.\n  simpl. reflexivity.\n  2: apply succ_verify.\n  2: apply apply_verify.\n  2: apply add_verify.\n  2: repeat intro; hnf; auto.\n  intros.\nOpaque get set funptr list_nat.\n  apply hoare_wp; subst.\n  simpl. intros [? ?]. subst Pr Pr'.\n  simpl; intuition.\n  inv H5.\n  inv H7; inv H9; inv H10; inv H11; inv H12.\n  clear H H0 H2 H8.\n  do 2 econstructor; intuition;\n      repeat (rewrite get_set_other; [ | discriminate]);\n        try rewrite get_set_same; auto.\n  inv H.\n  do 2 econstructor; intuition;\n      repeat (rewrite get_set_other; [ | discriminate]);\n        try rewrite get_set_same; auto.\n  inv H.\n  do 2 econstructor; intuition;\n      repeat (rewrite get_set_other; [ | discriminate]);\n        try rewrite get_set_same; auto.\n  inv H. inv H0.\n  do 2 econstructor; intuition;\n      repeat (rewrite get_set_other; [ | discriminate]);\n        try rewrite get_set_same; auto.\n  inv H.\n  repeat (rewrite get_set_other; [ | discriminate]);\n    try rewrite get_set_same; auto.\n  do 5 econstructor.\n  exists 2.\n  evar (x1:value).\n  evar (x2:value).\n  evar (x3:value).\n  evar (x4:value).\n  exists (2,(x1,x2,x3,x4)).\n  subst x1 x2 x3 x4.\n  intuition.\n  2: apply (H4 (apply_fs succ_fs')).\n  simpl.\n  repeat (rewrite get_set_other; [ | discriminate]);\n    try rewrite get_set_same; auto.\n  simpl.\n  repeat (rewrite get_set_other; [ | discriminate]);\n    try rewrite get_set_same; auto.\n  econstructor; split.\n  2: repeat split;\n   repeat (rewrite get_set_other; [ | discriminate]);\n    try rewrite get_set_same; auto.\n  unfold apply_P.\n  simpl. intuition.\nTransparent list_nat.\n  simpl. auto.\nOpaque list_nat.\n  simpl in H2.\n  destruct H2.\n  hnf in H. simpl in H. subst.\n  destruct a'0.\n  intuition.\n  exists x. split; auto.\nQed.\n\nLemma main_totally_correct :\n  forall r c,\n    phi#(L 2) = Some c ->\n    exists n', exists p', exists r',\n      stepstar (K.squash (n',phi)) p'\n        r ((c ;; instr_assert FF)::nil)\n        r' nil /\\\n        exists v, r'#(V 0) = Some v /\\ list_nat 3 v.\nProof.\n  intros.\n  generalize (verify_totally_correct PROG_G unit (fun _ => TT)\n    (fun _ => store_op (fun r => exists v, r#(V 0) = Some v /\\ list_nat 3 v))\n    phi (L 2) main_tm tt); intros.\n  spec H0. apply main_verify.\n  spec H0. unfold PROG_G. hnf; simpl; intuition.\n  spec H0 r. spec H0. intros; hnf. auto.\n  spec H0 5.\n  spec H0 c.\n  spec H0. simpl; auto.\n  spec H0. auto.\n  destruct H0 as [p' [r' [? ?]]].\n  econstructor.\n  exists p'. exists r'.\n  split; eauto.\n  destruct H1; auto.\nQed.\n\n(* For every store satisfying the addition precondition,\n   calling the addition function will halt with a store\n   satisfing the postcondition.\n *)\n\nTransparent list_nat.\nLemma addition_totally_correct :\n  forall r n m c,\n    add_P' n m r ->\n    phi#(L 0) = Some c ->\n    exists n', exists p', exists r',\n      stepstar (K.squash (n',phi)) p'\n        r ((c ;; instr_assert FF)::nil)\n        r' nil /\\\n      add_Q' n m r'.\nProof.\n  intros.\n  generalize (verify_totally_correct (funptr (L 0) _ add_term_measure add_P add_Q && TT) _ add_P add_Q phi (L 0) add_term_measure (n,m)); intros.\n  spec H1. apply add_verify.\n  repeat intro; hnf; auto.\n  spec H1. hnf; simpl; intuition.\n  spec H1 r. spec H1.\n  simpl; intuition.\n  spec H1 n c.\n  spec H1.\n  destruct H. simpl.\n  unfold list_nat_var in *.\n  simpl in *.\n  destruct (r#2); auto.\n\n  clear - H.\n  revert v H; induction n; simpl; intros;\n    destruct v; try tauto.\n  destruct v1; try tauto.\n  destruct l; try tauto.\n  simpl. f_equal. auto.\n  spec H1; auto.\n  destruct H1 as [p' [r' [? ?]]].\n  do 3 econstructor; split; eauto.\n  destruct H2; auto.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/examples/funclistmach2/programs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2444767708714831}}
{"text": "From iris_c.clang Require Import notations lang logic tactics.\nFrom iris_c.lib Require Import int.\n\nSection proof.\n  Context `{clangG Σ}.\n\n  Definition f : expr :=\n    if: (!\"x\"@Tint8 != 0)\n    then: (\n      \"x\" <- !\"x\"@Tint8 - 1 ;;\n      Ecall Tvoid \"g\" (Epair (Evar \"x\") (Evalue Vvoid)) ;;\n      return: void)\n    else: ( return: void ).\n\n  Definition g : expr :=\n    if: (!\"x\"@Tint8 != 0)\n    then: (\n      \"x\" <- !\"x\"@Tint8 - 1 ;;\n      Ecall Tvoid \"f\" (Epair (Evar \"x\") (Evalue Vvoid));;\n      return: void)\n    else: ( return: void ).\n\n  Definition rec_env n : env := (sset \"x\" (Tptr Tint8, Vptr n) semp).\n\n  Definition Pn : Prop :=\n    (∀ n: nat, Byte.repr n = ((Z.pos (Pos.of_succ_nat n) - 1%Z)%int)) ∧\n    (∀ n: nat, evalbop oneq (Z.pos (Pos.of_succ_nat n)) 0%Z = Some vtrue).\n  \n  Lemma rec_example (ln: addr) (n: nat) k ks Φ:\n    Pn →\n    ln ↦ n @ Tint8 ∗\n    \"f\" T↦ Function Tvoid [(\"x\", Tptr Tint8)] f ∗\n    \"g\" T↦ Function Tvoid [(\"x\", Tptr Tint8)] g ∗ (WP (fill_ectxs void k, ks) {{ Φ }})\n    ⊢ WP (fill_ectxs (Ecall Tvoid \"f\"\n                            (Evalue (Vpair ln void))) k, ks) {{ Φ }}.\n  Proof.\n    iIntros (Hn) \"[Hn [#? [#? HΦ]]]\".\n    iLöb as \"IH\" forall (n k ks Φ Hn). destruct ks.\n    iApply (wp_call (rec_env ln) e _ (Vpair ln Vvoid) [(\"x\", Tptr Tint8)])=>//.\n    destruct n eqn:?; subst; iFrame \"#\"; iNext.\n    - unfold f. wp_var. by wp_run.\n    - unfold f. wp_var. wp_run=>//.\n      { destruct Hn as [H1 H2].\n        specialize H2 with n0. done. }\n      wp_step. iNext. wp_var. wp_var. wp_run.\n      wp_unfill (Ecall _ _ _).\n      rewrite (fill_app (Evar \"x\")\n                        [EKcall Tvoid \"g\"; EKpairl void]).\n      iApply wp_bind=>//.\n      wp_var. iApply wp_value=>//.\n      wp_unfill (Ecall _ _ _).\n      rewrite (fill_app (Epair ln void)\n                        [EKcall Tvoid \"g\"]).\n      iApply wp_bind=>//. wp_pair.\n      iApply wp_value=>//.\n      replace ((Z.pos (Pos.of_succ_nat n0) - 1%Z)%int)\n        with (Byte.repr n0).\n      iApply (wp_call (rec_env ln) (rec_env ln)\n                         [EKseq (return: void)] (Vpair ln void)\n                         [(\"x\", Tptr Tint8)]);\n        last iFrame \"#\"; first done.\n      iNext. unfold g. wp_var. wp_load.\n      destruct n0 eqn:Heqn; subst.\n      + wp_run. simpl. wp_run. done.\n      + simpl.\n        wp_op=>//.\n        { destruct Hn as [H1 H2]. simpl. apply H2. }\n        wp_step. iApply wp_seq=>//. wp_run.\n        wp_unfill (Ecall _ _ _)%E.\n        rewrite (fill_app (Evar \"x\")\n                          [EKcall Tvoid \"f\"; EKpairl void]).\n        iApply wp_bind=>//.\n        wp_var. iApply wp_value=>//.\n        wp_unfill (Ecall _ _ _).\n        rewrite (fill_app (Epair ln void) [EKcall Tvoid \"f\"]).\n        iApply wp_bind=>//. wp_pair.\n        iApply wp_value=>//.\n        wp_unfill (Ecall _ _ _).\n        replace (Z.pos (Pos.of_succ_nat n) - 1%Z)%int\n        with (Byte.repr n).\n        iDestruct (\"IH\" $! n) as \"IH'\".\n        iDestruct (\"IH'\" $! _ _ _ with \"[]\") as \"?\"=>//.\n        iApply (\"~2\" with \"[-HΦ]\")=>//.\n        simpl. wp_run. simpl. wp_run.\n        { by destruct Hn as [? ?]. }\n        { by destruct Hn as [? ?]. }\n      + by destruct Hn as [? ?].\n  Qed.\n\nEnd proof.\n", "meta": {"author": "izgzhen", "repo": "iris-c-coq", "sha": "ca4bbc8fd86d8c53406a371eb30d0dda64a0920e", "save_path": "github-repos/coq/izgzhen-iris-c-coq", "path": "github-repos/coq/izgzhen-iris-c-coq/iris-c-coq-ca4bbc8fd86d8c53406a371eb30d0dda64a0920e/theories/tests/rec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2444486783098288}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\nRequire Import omega.Omega.\nRequire Import Setoid.\nRequire Import ZArith.\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith. \nLocal Open Scope struct_scope.\nRequire Import FinProof.CommonProofs.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolClass.\nRequire Import depoolContract.SolidityNotations.\nRequire Import depoolContract.DePoolFunc.\nRequire Import depoolContract.DePoolConsts.\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\nRequire Import depoolContract.Scenarios.ScenarioCommon.\nImport DePoolSpec.LedgerClass.SolidityNotations. \nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope solidity_scope.\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\nSet Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100.\nModule Scenario2  (dc : DePoolConstsTypesSig XTypesSig StateMonadSig).\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig dc.\nImport dc.\nModule ScenarioCommon := ScenarioCommon dc.\nImport ScenarioCommon.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\nLemma Scenario_OrdinaryStakeLose_byValidator: forall \n                        (minStake validatorAssurance proxyCode validatorWallet   participantRewardFraction : Z)\n                        (proxyCode : TvmCell)\n                        (now_constructor msg_pubkey_constructor : Z)\n                        (NetParams_init : NetParams)\n                        (stake :Z )\n                        (NetParams_addOrdinaryStake :  NetParams)\n                        (now_addOrdinaryStake msg_value_addOrdinaryStake msg_sender_addOrdinaryStake : Z)\n                        (now_round1  msg_value_round1 msg_sender_round1 : Z)\n                        (NetParams_round1 :  NetParams)\n                        (queryId0 validatorKey stakeAt maxFactor adnlAddr : Z)\n                        ( signature : XList XInteger8 )\n                        (now_participateInElections  msg_value_participateInElections msg_sender_participateInElections : Z)\n                        (NetParams_participateInElections :  NetParams)                        \n                        (queryId comment elector : Z)\n                        (now_onStakeAccept  msg_value_onStakeAccept msg_sender_onStakeAccept : Z)\n                        (NetParams_onStakeAccept :  NetParams)\n                        (now_toWaitingIfValidatorWinElections  msg_value_toWaitingIfValidatorWinElections msg_sender_toWaitingIfValidatorWinElections : Z)\n                        (NetParams_toWaitingIfValidatorWinElections :  NetParams)\n                        (now_onSuccessToRecoverStake  msg_value_onSuccessToRecoverStake msg_sender_onSuccessToRecoverStake : Z)\n                        (NetParams_onSuccessToRecoverStake :  NetParams)\n                        (now_toWaitingReward  msg_value_toWaitingReward msg_sender_toWaitingReward : Z)\n                        (NetParams_toWaitingReward :  NetParams),\nlet l_init_NetParams := withNetParams default NetParams_init in\nlet l_init := {$ l_init_NetParams With (VMState_ι_now,   now_constructor); \n                                       (VMState_ι_msg_pubkey,   msg_pubkey_constructor)$} in \nlet l_constructor:= exec_state (DePoolContract_Ф_Constructor6 minStake validatorAssurance proxyCode validatorWallet   participantRewardFraction  ) l_init in \nlet (r, l_fin) := run  (modify (fun l => withNetParams l NetParams_addOrdinaryStake) >>\n                        modify (fun l => {$ l With (VMState_ι_now,   now_addOrdinaryStake);\n                                                   (VMState_ι_msg_value , msg_value_addOrdinaryStake);\n                                                   (VMState_ι_msg_sender , msg_sender_addOrdinaryStake) $}) >>\n                        do _ ← DePoolContract_Ф_addOrdinaryStake'' stake ??;\n                        modify (fun l => withNetParams l NetParams_round1) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_round1);\n                                                   (VMState_ι_msg_value ,   msg_value_round1);\n                                                   (VMState_ι_msg_sender ,  msg_sender_round1) $}) >>\n                        do _ ← DePoolContract_Ф_ticktock ??;\n                        modify (fun l => withNetParams l NetParams_participateInElections) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_participateInElections);\n                                                   (VMState_ι_msg_value ,   msg_value_participateInElections);\n                                                   (VMState_ι_msg_sender ,  msg_sender_participateInElections) $}) >>\n                        do _ ← DePoolContract_Ф_participateInElections'' queryId0 validatorKey stakeAt maxFactor adnlAddr signature ??;\n                        modify (fun l => withNetParams l NetParams_onStakeAccept) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_onStakeAccept);\n                                                   (VMState_ι_msg_value ,   msg_value_onStakeAccept);\n                                                   (VMState_ι_msg_sender ,  msg_sender_onStakeAccept) $}) >>\n                        do _ ← DePoolContract_Ф_onStakeAccept queryId comment elector ??;\n                        modify (fun l => withNetParams l NetParams_toWaitingIfValidatorWinElections) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_toWaitingIfValidatorWinElections);\n                                                   (VMState_ι_msg_value ,   msg_value_toWaitingIfValidatorWinElections);\n                                                   (VMState_ι_msg_sender ,  msg_sender_toWaitingIfValidatorWinElections) $}) >>\n                        do _ ← DePoolContract_Ф_ticktock ??;\n                        modify (fun l => withNetParams l NetParams_onSuccessToRecoverStake) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_onSuccessToRecoverStake);\n                                                   (VMState_ι_msg_value ,   msg_value_onSuccessToRecoverStake);\n                                                   (VMState_ι_msg_sender ,  msg_sender_onSuccessToRecoverStake) $}) >>\n                        do _ ← DePoolContract_Ф_onSuccessToRecoverStake queryId elector ??;\n                        modify (fun l => withNetParams l NetParams_toWaitingReward) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_toWaitingReward);\n                                                   (VMState_ι_msg_value ,   msg_value_toWaitingReward);\n                                                   (VMState_ι_msg_sender ,  msg_sender_toWaitingReward) $}) >>\n                        do _ ← DePoolContract_Ф_ticktock ?;\n                        $ I )  l_constructor in errorValueIsValue r = true ->\nmsg_sender_addOrdinaryStake = validatorWallet -> \n(now_round1 >=? NetParams_round1 ->> NetParams_ι_utime_until - NetParams_round1 ->> NetParams_ι_electionsStartBefore) = true -> \n((negb (tvm_hash (NetParams_init ->> NetParams_ι_curValidatorData) =? tvm_hash (NetParams_round1 ->> NetParams_ι_curValidatorData))) &&\n(negb (tvm_hash (NetParams_init ->> NetParams_ι_prevValidatorData) =? tvm_hash (NetParams_round1 ->> NetParams_ι_curValidatorData))))%bool= true ->    \n(stake >=? validatorAssurance) = true -> \n( tvm_hash  (NetParams_round1 ->> NetParams_ι_curValidatorData)  =?  tvm_hash  (NetParams_toWaitingIfValidatorWinElections ->> NetParams_ι_prevValidatorData))  = true ->\n(now_toWaitingIfValidatorWinElections >=? NetParams_toWaitingIfValidatorWinElections ->> NetParams_ι_utime_until - NetParams_toWaitingIfValidatorWinElections ->> NetParams_ι_electionsStartBefore) = true ->\n(negb (0 =? tvm_hash ((NetParams_toWaitingIfValidatorWinElections ->> NetParams_ι_curValidatorData)))) = true ->\n((negb (tvm_hash ((NetParams_toWaitingReward ->> NetParams_ι_curValidatorData)) =? tvm_hash ((NetParams_round1 ->> NetParams_ι_curValidatorData)))) &&\n(negb (tvm_hash ((NetParams_toWaitingReward ->> NetParams_ι_prevValidatorData)) =? tvm_hash ((NetParams_round1 ->> NetParams_ι_curValidatorData)))))%bool= false ->      \n(now_toWaitingReward >=? NetParams_toWaitingReward ->> NetParams_ι_utime_since + NetParams_round1 ->> NetParams_ι_stakeHeldFor + DePoolLib_ι_ELECTOR_UNFREEZE_LAG) = true ->\n(msg_value_onSuccessToRecoverStake + DePoolLib_ι_PROXY_FEE >=? stake) = true ->\n let optRound := eval_state ( ↓ ( RoundsBase_Ф_fetchRound queryId ) ) l_fin in                  \n let round := maybeGet optRound in \n let stakes :=  round ->> RoundsBase_ι_Round_ι_stakes in\n let optStake := stakes ->fetch validatorWallet in\n let current_stakes := maybeGet optStake in\n round ->> RoundsBase_ι_Round_ι_stake = stake\n /\\ current_stakes ->> RoundsBase_ι_StakeValue_ι_ordinary  = stake.\nProof.\n\nAbort.\nEnd Scenario2.", "meta": {"author": "Pruvendo", "repo": "depool_contract", "sha": "6afe23011d62f65921ac2493df691ab888ffeb95", "save_path": "github-repos/coq/Pruvendo-depool_contract", "path": "github-repos/coq/Pruvendo-depool_contract/depool_contract-6afe23011d62f65921ac2493df691ab888ffeb95/src/Scenarios/Scenario2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2444376298614681}}
{"text": "Require Import VST.msl.seplog.\nRequire Import VST.msl.sepalg.\nRequire Import VST.msl.psepalg.\nRequire Import VST.msl.alg_seplog_direct.\nRequire Import RamifyCoq.msl_ext.abs_addr.\nRequire Import RamifyCoq.msl_ext.seplog.\nRequire Import RamifyCoq.msl_ext.overlapping_direct.\nRequire Import RamifyCoq.msl_ext.alg_seplog_direct.\nRequire Import RamifyCoq.msl_ext.ramify_tactics.\nRequire Import RamifyCoq.heap_model_direct.SeparationAlgebra.\nRequire Import RamifyCoq.heap_model_direct.mapsto.\nRequire Import VST.msl.msl_direct.\nRequire Import VST.msl.predicates_sa.\n\nInstance Ndirect : NatDed (pred world) := algNatDed world.\nInstance Sdirect : SepLog (pred world) := algSepLog world.\nInstance Cldirect : ClassicalSep (pred world) := algClassicalSep world.\nInstance CSLdirect : CorableSepLog (pred world) := algCorableSepLog world.\nInstance PSLdirect : PreciseSepLog (pred world) := algPreciseSepLog world.\nInstance OSLdirect : OverlapSepLog (pred world) := algOverlapSepLog world.\nInstance DSLdirect : DisjointedSepLog (pred world) := algDisjointedSepLog world.\n\nInstance MSLdirect : MapstoSepLog AbsAddr_world mapsto.\nProof.\n  apply mkMapstoSepLog.\n  apply mapsto__precise.\nDefined.\n\nInstance sMSLdirect : StaticMapstoSepLog AbsAddr_world mapsto.\nProof.\n  apply mkStaticMapstoSepLog; simpl; intros.\n  + hnf in H. simpl in H. unfold adr_conflict in H. destruct (eq_nat_dec p p).\n    - inversion H.\n    - exfalso; tauto.\n  + apply mapsto_conflict.\n    unfold adr_conflict in H.\n    destruct (eq_nat_dec p1 p2); congruence.\n  + apply disj_mapsto_.\n    unfold adr_conflict in H.\n    destruct (eq_nat_dec p1 p2); congruence.\nDefined.\n\nInstance nMSLdirect : NormalMapstoSepLog AbsAddr_world mapsto.\nProof.\n  apply mkNormalMapstoSepLog.\n  apply mapsto_inj.\nDefined.\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/heap_model_direct/SeparationLogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24432942065783597}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The L2C verified compiler                              *)\n(*                                                                     *)\n(*            L2C Group, Tsinghua University                           *)\n(*                                                                     *)\n(*  Copyright Tsinghua University.  All rights reserved.  This file is *)\n(*  distributed under the terms of the GNU General Public License as   *)\n(*  published by the Free Software Foundation, either version 2 of the *)\n(*  License, or (at your option) any later version.  This file is also *)\n(*  distributed under the terms of the INRIA Non-Commercial License    *)\n(*  Agreement.                                                         *)\n(*                                                                     *)\n(* *********************************************************************)\n\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Errors.\nRequire Import Memdata.\nRequire Import Lint.\nRequire Import Integers.\nRequire Import Ctypes.\nRequire Import Cltypes.\n\nDefinition sizeof_fld(fld: fieldlist):=\n  align (sizeof_struct fld 0) (alignof_fields fld).\n\nLemma sizeof_fld_pos:\n  forall fld, 0 <= sizeof_fld fld.\nProof.\n  unfold sizeof_fld. intros.\n  apply Zle_trans with (sizeof_struct fld 0); try omega.\n  apply sizeof_struct_incr; auto.\n  apply align_le. apply alignof_fields_pos.\nQed.\n\nLemma field_offset_in_range_simpl:\n  forall id fld delta ty,\n  field_offset id fld = OK delta ->\n  field_type id fld = OK ty ->\n  0 <= delta /\\ delta + sizeof ty <= sizeof_fld fld.\nProof.\n  intros.\n  apply field_offset_in_range with (sid:=xH) (ty:=ty) in H; auto.\nQed.\n\nLemma field_offset_unsigned_repr:\n  forall id fld z ty,\n  field_offset id fld = OK z ->\n  field_type id fld = OK ty ->\n  sizeof_fld fld <= Int.max_unsigned ->\n  Int.unsigned (Int.repr z) = z.\nProof.\n  intros.\n  eapply field_offset_in_range_simpl in H; eauto.\n  generalize (sizeof_pos ty); intros.\n  rewrite Int.unsigned_repr; try omega.\nQed.\n\nLemma field_offset_rec_type_exists:\n  forall fld fid ofs pos,\n  field_offset_rec fid fld pos = OK ofs ->\n  exists ty, field_type fid fld = OK ty.\nProof.\n  induction fld; simpl; intros.\n  inv H.\n  destruct (ident_eq _ _); eauto.\nQed.\n\nLemma field_offset_type_exists:\n  forall fld fid ofs,\n  field_offset fid fld = OK ofs ->\n  exists ty, field_type fid fld = OK ty.\nProof.\n  unfold field_offset. intros.\n  eapply field_offset_rec_type_exists; eauto.\nQed.\n\nLemma field_type_offset_rec_exists:\n  forall fld fid ty pos,\n  field_type fid fld = OK ty ->\n  exists ofs, field_offset_rec fid fld pos = OK ofs.\nProof.\n  induction fld; simpl; intros.\n  congruence.\n  destruct (ident_eq fid i).\n  inv H. eauto.\n  eapply IHfld; eauto.\nQed.\n\nLemma field_type_offset_exists:\n  forall fld fid ty,\n  field_type fid fld = OK ty ->\n  exists ofs, field_offset fid fld = OK ofs.\nProof.\n  unfold field_offset. intros.\n  eapply field_type_offset_rec_exists; eauto.\nQed.\n\nDefinition fieldlist_of(vas: list (ident*type)): fieldlist :=\n  fold_right (fun p=> Fcons (fst p) (snd p)) Fnil vas.\n\nLemma fieldlist_list_in:\n  forall al id ty,\n  field_type id (fieldlist_of al) = OK ty ->\n  In (id, ty) al.\nProof.\n  induction al; simpl; intros.\n  inv H.\n  destruct a. simpl in *.\n  compare id i; intros.\n  subst. rewrite peq_true in *. inv H; auto.\n  rewrite peq_false in *; eauto.\nQed.\n\nLemma list_in_fieldlist:\n  forall al id ty,\n  In (id, ty) al ->\n  list_norepet (map fst al) ->\n  field_type id (fieldlist_of al) = OK ty.\nProof.\n  induction al; intros.\n  +inv H.\n  +inv H0. destruct H; subst; simpl.\n   -rewrite peq_true; auto.\n   -assert(id <> fst a).\n      apply in_map with _ _ fst _ _ in H; eauto.\n      simpl in H. red; intros. subst. auto.\n    repeat rewrite peq_false; auto.\nQed.\n\nLemma fieldlist_list_in_offset_exists:\n  forall al id pos,\n  In id (map fst al) ->\n  exists delta, field_offset_rec id (fieldlist_of al) pos = OK delta.\nProof.\n  induction al; simpl; intros.\n  +inv H.\n  +destruct H; subst; simpl.\n   -rewrite peq_true; eauto.\n   -destruct (ident_eq id (fst a)) eqn:?; eauto.\nQed.\n\nLemma fieldlist_list_id_in:\n  forall al id delta pos,\n  field_offset_rec id (fieldlist_of al) pos = OK delta ->\n  In id (map fst al).\nProof.\n  induction al; simpl; intros.\n  inv H.\n  compare id (fst a); intros.\n  subst. rewrite peq_true in *. inv H; auto.\n  rewrite peq_false in *; eauto.\nQed.\n\nLemma fieldlist_list_notin:\n  forall al id pos msg,\n  field_offset_rec id (fieldlist_of al) pos = Error msg ->\n  ~ In id (map fst al).\nProof.\n  induction al; simpl; intros; auto.\n  compare (fst a) id; intros; subst.\n  rewrite peq_true in H. inv H.\n  rewrite peq_false in H; auto.\n  red. intros. destruct H0; auto.\n  eapply IHal; eauto.\nQed.\n\nLemma field_type_notin_app:\n  forall l1 l2 id,\n  ~ In id (map fst l1) ->\n  field_type id (fieldlist_of (l1++l2)) = field_type id (fieldlist_of l2).\nProof.\n  induction l1; simpl; intros; eauto.\n  rewrite peq_false; auto.\nQed.\n\nLemma fieldlist_list_notin_inv:\n  forall al id pos,\n  ~ In id (map fst al) ->\n  exists msg, field_offset_rec id (fieldlist_of al) pos = Error msg.\nProof.\n  induction al; simpl; intros; eauto.\n  rewrite peq_false; auto.\nQed.\n\nLemma field_type_offset_error_rec:\n  forall fld id msg1 pos,\n  field_type id fld = Error msg1 ->\n  exists msg2, field_offset_rec id fld pos = Error msg2.\nProof.\n  induction fld; simpl; intros; eauto.\n  destruct (ident_eq _ _); try congruence.\n  eauto.\nQed.\n\nLemma field_type_offset_error:\n  forall fld id msg1,\n  field_type id fld = Error msg1 ->\n  exists msg2, field_offset id fld = Error msg2.\nProof.\n  intros. apply field_type_offset_error_rec with msg1; auto.\nQed.\n\nLemma field_type_ok_app:\n  forall l1 l2 id ty,\n  field_type id (fieldlist_of l1) = OK ty ->\n  field_type id (fieldlist_of (l1 ++ l2))  = OK ty.\nProof.\n  induction l1; simpl; intros.\n  congruence.\n\n  destruct a; simpl in *.\n  compare id i; intros ; subst.\n  rewrite peq_true in *; auto.\n  rewrite peq_false in *; auto.\nQed.\n\nLemma field_offset_rec_fieldlist_of_notin_app_cons:\n  forall id ty l1 l2 z,\n  ~ In id (map fst l1) ->\n  field_offset_rec id (fieldlist_of (l1 ++ (id, ty) :: l2)) z = OK (align (sizeof_struct (fieldlist_of l1) z) (alignof ty)).\nProof.\n  induction l1; simpl; intros; auto.\n  +rewrite peq_true; auto.\n  +rewrite peq_false; auto.\nQed.\n\nLemma sizeof_struct_fieldlist_of_app_cons:\n  forall l id ty z,\n  sizeof_struct (fieldlist_of (l ++ (id, ty) :: nil)) z =\n  align (sizeof_struct (fieldlist_of l) z) (alignof ty) + sizeof ty.\nProof.\n  induction l; simpl; auto.\nQed.\n\nDefinition access_mode (ty: type) : mode :=\n  match ty with\n  | Tint I8 Signed => By_value Mint8signed\n  | Tint I8 Unsigned => By_value Mint8unsigned\n  | Tint I16 Signed => By_value Mint16signed\n  | Tint I16 Unsigned => By_value Mint16unsigned\n  | Tint I32 _ => By_value Mint32\n  | Tint IBool _ => By_value Mint8unsigned\n  | Tfloat F32 => By_value Mfloat32\n  | Tfloat F64 => By_value Mfloat64\n  | Tvoid => By_nothing\n  | Tpointer _ => By_nothing\n  | Tarray _ _ _ => By_reference\n  | Tfunction _ _ _ => By_nothing\n  | Tstruct _ _ => By_copy\nend.\n\nDefinition typeof_array(t: type): res (type*Z) :=\n  match t with\n  | Tarray _ ty num => OK (ty,num)\n  | _ => Error (MSG \"Not Tarray \" :: nil)\n  end.\n\nDefinition fieldof_struct(t: type): res fieldlist :=\n  match t with\n  | Tstruct _ fld => OK fld\n  | _ => Error (MSG \"Not Tstruct \" :: nil)\n  end.\n\nLemma access_mode_eq:\n  forall t, (exists c, access_mode t = By_value c) \\/ access_mode t = By_copy \\/ access_mode t = By_reference ->\n  access_mode t = Cltypes.access_mode t.\nProof.\n  destruct t; simpl; intros; auto;\n  destruct H as [? | [? | ?]]; inv H; inv H0.\nQed.\n\nLemma sizeof_chunk_eq:\n  forall t chunk,\n  access_mode t = By_value chunk ->\n  size_chunk chunk = sizeof t.\nProof.\n  destruct t; intros; inv H; simpl; auto.\n  destruct i; destruct s; inv H1; auto.\n  destruct f; inv H1; auto.\nQed.\n\nLemma alignof_chunk_eq:\n  forall ty chunk,\n  access_mode ty = By_value chunk ->\n  alignof ty = align_chunk chunk.\nProof.\n  induction ty; simpl; intros; try congruence; auto.\n  destruct i,s; inv H; auto.\n  destruct f; inv H; auto.\nQed.\n\nLemma field_type_alignof_le:\n  forall i f t,\n  field_type i f = OK t ->\n  alignof t <= alignof_fields f.\nProof.\n  induction f; simpl; intros.\n  congruence.\n  destruct (ident_eq _ _).\n  +inv H. apply zmax_l_le. omega.\n  +apply zmax_r_le. auto.\nQed.\n\nLemma field_type_alignof:\n  forall i f t,\n  field_type i f = OK t ->\n  (alignof t | alignof_fields f).\nProof.\n  intros. generalize (alignof_1248 t).\n  generalize (alignof_fields_1248 f).\n  apply field_type_alignof_le in H. intros.\n  destruct H0 as [ | [ | [ | ]]]; destruct H1 as [ | [ | [ | ]]];\n  rewrite H0,H1 in *; try omega; try (exists 1; omega; fail);\n  try (exists 2; omega; fail) .\n  exists 4; omega. exists 8. omega. exists 4. omega.\nQed.\n\nDefinition is_arystr(t: type): bool :=\n  match t with\n  | Tarray _ _ _ => true\n  | Tstruct _ _ => true\n  | _ => false\n  end.\n", "meta": {"author": "l2ctsinghua", "repo": "l2c", "sha": "cb766eed459091dfa7ae19639f0c10b6953cb3a8", "save_path": "github-repos/coq/l2ctsinghua-l2c", "path": "github-repos/coq/l2ctsinghua-l2c/l2c-cb766eed459091dfa7ae19639f0c10b6953cb3a8/src/Ltypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24432941467075914}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export terms2.\nRequire Export terms_tacs.\nRequire Export tactics2.\n\n\n\n(* ------ binary and ------ *)\n\n\nDefinition mk_uand {p} (A B : @NTerm p) :=\n  match newvars2 [A,B] with\n    | (vx,vy) =>\n      mk_isect mk_base vx\n               (mk_isect (mk_halts (mk_var vx)) vy\n                         (mk_isaxiom (mk_var vx) A B))\n  end.\n\nLemma isprog_vars_uand {o} :\n  forall (A B : @NTerm o) vs,\n    isprog_vars vs (mk_uand A B) <=> (isprog_vars vs A # isprog_vars vs B).\nProof.\n  introv.\n  unfold mk_uand.\n  remember (newvars2 [A,B]); repnd.\n  apply newvars2_prop2 in Heqp; simpl in Heqp.\n  allrw app_nil_r; allrw in_app_iff; allrw not_over_or; repnd.\n  repeat (rw <- @isprog_vars_isect_iff).\n  rw @isprog_vars_isaxiom.\n  rw @isprog_vars_halts.\n  allrw <- @isprog_vars_var_iff; simpl; split; intro k; repnd; dands; auto.\n  repeat (apply isprog_vars_cons_if2 in k3; auto).\n  repeat (apply isprog_vars_cons_if2 in k; auto).\n  repeat (apply isprog_vars_cons; auto).\n  repeat (apply isprog_vars_cons; auto).\nQed.\n\nLemma wf_uand {o} :\n  forall a b : @NTerm o, wf_term (mk_uand a b) <=> (wf_term a # wf_term b).\nProof.\n  introv.\n  unfold mk_uand.\n  remember (newvars2 [a,b]); repnd.\n  apply newvars2_prop2 in Heqp; simpl in Heqp.\n  allrw app_nil_r; allrw in_app_iff; allrw not_over_or; repnd.\n  allrw <- @wf_isect_iff.\n  rw <- @wf_halts_iff.\n  rw @wf_isaxiom; split; sp.\nQed.\n\n\n(* ------ free vars ------ *)\n\nLemma free_vars_lam {o} :\n  forall v b, free_vars (@mk_lam o v b) = remove_nvars [v] (free_vars b).\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_isect {o} :\n  forall a v b, free_vars (@mk_isect o a v b) = free_vars a ++ (remove_nvars [v] (free_vars b)).\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_function {o} :\n  forall a v b, free_vars (@mk_function o a v b) = free_vars a ++ (remove_nvars [v] (free_vars b)).\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_product {o} :\n  forall a v b, free_vars (@mk_product o a v b) = free_vars a ++ (remove_nvars [v] (free_vars b)).\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_tunion {o} :\n  forall a v b, free_vars (@mk_tunion o a v b) = free_vars a ++ (remove_nvars [v] (free_vars b)).\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_cbv {o} :\n  forall a v b, free_vars (@mk_cbv o a v b) = free_vars a ++ (remove_nvars [v] (free_vars b)).\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_base {o} :\n  free_vars (@mk_base o) = [].\nProof.\n  introv; simpl; sp.\nQed.\n\nLemma free_vars_axiom {o} :\n  @free_vars o mk_axiom = [].\nProof.\n  introv; simpl; sp.\nQed.\n\nLemma free_vars_approx {o} :\n  forall a b, free_vars (@mk_approx o a b) = free_vars a ++ free_vars b.\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_isaxiom {o} :\n  forall a b c, free_vars (@mk_isaxiom o a b c) = free_vars a ++ free_vars b ++ free_vars c.\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_equality {o} :\n  forall a b c, free_vars (@mk_equality o a b c) = free_vars a ++ free_vars b ++ free_vars c.\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_tequality {o} :\n  forall a b, free_vars (@mk_tequality o a b) = free_vars a ++ free_vars b.\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_apply {o} :\n  forall a b, free_vars (@mk_apply o a b) = free_vars a ++ free_vars b.\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_union {o} :\n  forall a b : @NTerm o, free_vars (mk_union a b) = free_vars a ++ free_vars b.\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_eunion {o} :\n  forall a b : @NTerm o, free_vars (mk_eunion a b) = free_vars a ++ free_vars b.\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_halts {o} :\n  forall a, free_vars (@mk_halts o a) = free_vars a.\nProof.\n  introv.\n  unfold mk_halts.\n  rw @free_vars_approx.\n  rw @free_vars_cbv.\n  rw @free_vars_axiom.\n  rw remove_nvars_nil_r; rw app_nil_r; simpl; sp.\nQed.\n\nLemma free_vars_uand {o} :\n  forall A B, free_vars (@mk_uand o A B) = free_vars A ++ free_vars B.\nProof.\n  introv.\n  unfold mk_uand.\n\n  remember (newvars2 [A,B]); repnd.\n  apply newvars2_prop2 in Heqp; simpl in Heqp.\n  repeat (rw app_nil_r in Heqp); repeat (rw in_app_iff in Heqp).\n  repeat (rw not_over_or in Heqp); repnd.\n\n  repeat rw @free_vars_isect.\n\n  rw @free_vars_halts.\n  rw @free_vars_base.\n  rw @free_vars_isaxiom; simpl.\n  repeat (rw remove_nvars_cons_r; boolvar; allrw not_over_or; repnd; spFalseHyp).\n  rw remove_nvars_app_l; simpl.\n  rw remove_nvars_app_r.\n  repeat (rw remove_nvars_cons_l_weak; sp).\nQed.\n\nLemma free_vars_decide {o} :\n  forall (a : @NTerm o) v1 b1 v2 b2,\n    free_vars (mk_decide a v1 b1 v2 b2)\n    = free_vars a\n                ++ remove_nvars [v1] (free_vars b1)\n                ++ remove_nvars [v2] (free_vars b2).\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_spread {o} :\n  forall (a : @NTerm o) v1 v2 b,\n    free_vars (mk_spread a v1 v2 b)\n    = free_vars a ++ remove_nvars [v1,v2] (free_vars b).\nProof.\n  introv; simpl.\n  rw app_nil_r; sp.\nQed.\n\nLemma free_vars_unit {o} :\n  @free_vars o mk_unit = [].\nProof.\n  unfold mk_unit, mk_true.\n  rw @free_vars_approx; rw @free_vars_axiom; auto.\nQed.\n\nLemma free_vars_bool {o} :\n  @free_vars o mk_bool = [].\nProof.\n  unfold mk_bool.\n  rw @free_vars_union.\n  rw @free_vars_unit; auto.\nQed.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/terms/terms_props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2443005306581844}}
{"text": "Require Import Ensembles.\nRequire Import syntax.\nRequire Import infrastructure.\nRequire Import infrastructure_props.\nRequire Import analysis.\nRequire Import typings.\nRequire Import static.\nRequire Import List.\nRequire Import Arith.\nRequire Import tactics.\nRequire Import monad.\nRequire Import events.\nRequire Import Metatheory.\nRequire Import genericvalues.\nRequire Import alist.\nRequire Import Memory.\nRequire Import Integers.\nRequire Import Coqlib.\nRequire Import targetdata.\nRequire Import AST.\nRequire Import Maps.\nRequire Import opsem.\nRequire Import vellvm_tactics.\nRequire Import util.\n\n(***********************************************************)\n(* This file proves the properties of operational semantics. *)\n\nModule OpsemProps. Section OpsemProps.\n\nContext `{GVsSig : GenericValues}.\n\nExport Opsem.\n\nNotation GVs := GVsSig.(GVsT).\nNotation \"gv @ gvs\" :=\n  (GVsSig.(instantiate_gvs) gv gvs) (at level 43, right associativity).\nNotation \"$ gv # t $\" := (GVsSig.(gv2gvs) gv t) (at level 41).\n\n(***********************************************************)\n(* Properties of updating locals after calls. *)\nLemma func_callUpdateLocals_is_returnUpdateLocals :\n  forall TD rid noret0 tailc0 rt va fid lp Result lc lc' gl,\n  @returnUpdateLocals GVsSig TD \n    (insn_call rid noret0 tailc0 rt va fid lp) Result lc lc' gl =\n  callUpdateLocals TD rt noret0 rid (Some Result) lc' lc gl.\nProof.\n  intros.\n  unfold returnUpdateLocals.\n  unfold callUpdateLocals.\n  destruct noret0; auto.\nQed.\n\nLemma proc_callUpdateLocals_is_id : forall TD rt rid noret0 lc lc' gl lc'',\n  @callUpdateLocals GVsSig TD rt noret0 rid None lc' lc gl = Some lc'' ->\n  lc' = lc'' /\\ noret0 = true.\nProof.\n  intros.\n  unfold callUpdateLocals in H.\n  destruct noret0; inversion H; auto.\nQed.\n\n(***********************************************************)\n(* Properties of sop_star *)\nLemma sInsn__implies__sop_star : forall cfg state state' tr,\n  @sInsn GVsSig cfg state state' tr ->\n  sop_star cfg state state' tr.\nProof.\n  intros cfg state state' tr HdsInsn.\n  rewrite <- E0_right.\n  eauto.\nQed.\n\nLemma sop_star_trans : forall cfg state1 state2 state3 tr12 tr23,\n  @sop_star GVsSig cfg state1 state2 tr12 ->\n  sop_star cfg state2 state3 tr23 ->\n  sop_star cfg state1 state3 (Eapp tr12 tr23).\nProof.\n  intros cfg state1 state2 state3 tr12 tr23 Hdsop12 Hdsop23.\n  generalize dependent state3.\n  generalize dependent tr23.\n  induction Hdsop12; intros; auto.\n    rewrite Eapp_assoc. eauto.\nQed.\n\n(***********************************************************)\n(* Properties of sop_plus *)\nLemma sInsn__implies__sop_plus : forall cfg state state' tr,\n  @sInsn GVsSig cfg state state' tr ->\n  sop_plus cfg state state' tr.\nProof.\n  intros cfg state state' tr HdsInsn.\n  rewrite <- E0_right.\n  eauto.\nQed.\n\nLemma sop_plus__implies__sop_star : forall cfg state state' tr,\n  @sop_plus GVsSig cfg state state' tr ->\n  sop_star cfg state state' tr.\nProof.\n  intros cfg state state' tr Hdsop_plus.\n  inversion Hdsop_plus; subst; eauto.\nQed.\n\nHint Resolve sInsn__implies__sop_star sInsn__implies__sop_plus\n  sop_plus__implies__sop_star.\n\nLemma sop_plus_star__implies__sop_plus: forall cfg S1 S2 S3 tr1 tr2,\n  sop_plus cfg S1 S2 tr1 ->\n  @sop_star GVsSig cfg S2 S3 tr2 ->\n  sop_plus cfg S1 S3 (tr1 ** tr2).\nProof.\n  induction 1; intros; auto.\n    rewrite Eapp_assoc; auto. \n    econstructor; eauto.\n    eapply sop_star_trans; eauto.\nQed.\n\nLemma sop_star_plus__implies__sop_plus: forall cfg S1 S2 S3 tr1 tr2,\n  @sop_star GVsSig cfg S1 S2 tr1 ->\n  sop_plus cfg S2 S3 tr2 ->\n  sop_plus cfg S1 S3 (tr1 ** tr2).\nProof.\n  induction 1; intros; auto.\n    apply IHsop_star in H1.\n    rewrite Eapp_assoc; auto. \n    econstructor; eauto.\nQed.\n\nLemma sop_step_plus__implies__sop_plus: forall cfg S1 S2 S3 tr1 tr2,\n  sInsn cfg S1 S2 tr1 ->\n  @sop_plus GVsSig cfg S2 S3 tr2 ->\n  sop_plus cfg S1 S3 (tr1 ** tr2).\nProof.\n  intros. inv H0.\n  econstructor; eauto.\nQed.\n\n(***********************************************************)\n(* Properties of sop_diverges *)\nLemma sop_diverging_trans : forall cfg state tr1 state' tr2,\n  @sop_star GVsSig cfg state state' tr1 ->\n  sop_diverges cfg state' tr2 ->\n  sop_diverges cfg state (Eappinf tr1 tr2).\nProof.\n  intros cfg state tr1 state' tr2 state_dsop_state' state'_dsop_diverges.\n  generalize dependent tr2.\n  (sop_star_cases (induction state_dsop_state') Case); intros; auto.\n  Case \"sop_star_cons\".\n    rewrite Eappinf_assoc. eauto.\nQed.\n\nLemma sop_star_diverges'__sop_diverges': forall cfg IS1 IS2 tr1 tr2,\n  @sop_star GVsSig cfg IS1 IS2 tr1 ->\n  sop_diverges' cfg IS2 tr2 ->\n  sop_diverges' cfg IS1 (Eappinf tr1 tr2).\nProof.\n  induction 1; intros; auto.\n    apply IHsop_star in H1.\n    rewrite Eappinf_assoc.\n    econstructor; eauto.\nQed.\n\nLemma sop_plus_diverges'__sop_diverges': forall cfg IS1 IS2 tr1 tr2,\n  @sop_plus GVsSig cfg IS1 IS2 tr1 ->\n  sop_diverges' cfg IS2 tr2 ->\n  sop_diverges' cfg IS1 (Eappinf tr1 tr2).\nProof.\n  intros. inv H.\n  eapply sop_star_diverges'__sop_diverges' in H2; eauto.\n  rewrite Eappinf_assoc.\n  econstructor; eauto.\nQed.\n\nLemma sop_star_diverges__sop_diverges: forall cfg IS1 IS2 tr1 tr2,\n  @sop_star GVsSig cfg IS1 IS2 tr1 ->\n  sop_diverges cfg IS2 tr2 ->\n  sop_diverges cfg IS1 (Eappinf tr1 tr2).\nProof.\n  induction 1; intros; auto.\n    apply IHsop_star in H1.\n    rewrite Eappinf_assoc.\n    rewrite <- E0_right at 1.\n    econstructor; eauto.\nQed.\n\nLemma sop_diverges__sop_diverges': forall cfg IS tr,\n  @sop_diverges GVsSig cfg IS tr -> sop_diverges' cfg IS tr.\nProof.\n  cofix CIH.\n  intros.\n  inv H.\n  inv H0.\n  assert (sop_diverges cfg state0 (tr3***tr2)) as J.\n    clear CIH. \n    eapply sop_star_diverges__sop_diverges; eauto.\n  apply CIH in J. clear CIH.\n  rewrite Eappinf_assoc.\n  econstructor; eauto.\nQed.\n\nLemma sop_diverges'__sop_diverges: forall cfg IS tr,\n  sop_diverges' cfg IS tr -> @sop_diverges GVsSig cfg IS tr.\nProof.\n  cofix CIH.\n  intros.\n  inv H.\n  apply CIH in H1. clear CIH.\n  econstructor; eauto.\nQed.\n\nLemma sop_star_diverges__sop_diverges_coind: forall cfg IS1 IS2 tr1 tr2,\n  Opsem.sop_star cfg IS1 IS2 tr1 ->\n  @Opsem.sop_diverges GVsSig cfg IS2 tr2 ->\n  Opsem.sop_diverges cfg IS1 (Eappinf tr1 tr2).\nProof.\n  intros.\n  inv H0.\n  rewrite <- Eappinf_assoc.\n  eapply sop_diverges_intro; eauto.\n  eapply sop_star_plus__implies__sop_plus; eauto.\nQed.\n\nLemma sop_star_diverges'__sop_diverges'_coind: forall cfg IS1 IS2 tr1 tr2,\n  Opsem.sop_star cfg IS1 IS2 tr1 ->\n  @Opsem.sop_diverges' GVsSig cfg IS2 tr2 ->\n  Opsem.sop_diverges' cfg IS1 (Eappinf tr1 tr2).\nProof.\n  cofix CIH.\n  intros.\n  inv H0.\n  inv H.\n    clear CIH.\n    rewrite <- Eappinf_assoc.\n    econstructor; eauto.\n\n    assert (sop_diverges' cfg state0 (tr4 *** tr0 *** tr3)) as J.\n      rewrite <- Eappinf_assoc.\n      eapply CIH; eauto.\n      eapply sop_star_trans; eauto. \n    clear CIH.\n    rewrite Eappinf_assoc.\n    eapply sop_diverges_intro'; eauto.\nQed.\n\nSection SOP_WF_DIVERGES.\n\nContext `{Measure: Type}.\nContext `{R:Measure -> Measure -> Prop}.\nContext `{Hwf_founded_R: well_founded R}.\n\nLemma sop_wf_diverges__inv: forall m1 cfg S1 Tr\n  (Hdiv: sop_wf_diverges Measure R cfg m1 S1 Tr),\n  exists S2, exists m2, exists tr, exists Tr',\n    @sop_plus GVsSig cfg S1 S2 tr /\\\n    sop_wf_diverges Measure R cfg m2 S2 Tr' /\\\n    Tr = Eappinf tr Tr'.\nProof.\n  intro m1. pattern m1.\n  apply (well_founded_ind Hwf_founded_R); intros.\n  inv Hdiv.\n    exists state2. exists m2. exists tr1. exists tr2. \n    split; auto.\n\n    apply H in H2; auto.\n    destruct H2 as [S2 [m2' [tr [Tr' [J1 [J2 J3]]]]]]; subst.\n    exists S2. exists m2'. exists (Eapp tr1 tr). exists Tr'.\n    split.\n      eapply sop_star_plus__implies__sop_plus; eauto.\n    split; auto.\n      rewrite Eappinf_assoc; auto.\nQed.\n\nLemma sop_wf_diverges__sop_diverges: forall cfg m IS tr,\n  sop_wf_diverges Measure R cfg m IS tr ->@sop_diverges GVsSig cfg IS tr.\nProof.\n  cofix CIH.\n  intros.\n  inv H.\n    apply sop_wf_diverges__inv in H1; auto.\n    destruct H1 as [S2 [m2' [tr [Tr' [J1 [J2 J3]]]]]]; subst.\n    econstructor; eauto.\n\n    apply sop_wf_diverges__inv in H2; auto.\n    destruct H2 as [S2 [m2' [tr [Tr' [J1 [J2 J3]]]]]]; subst.\n    rewrite <- Eappinf_assoc.\n    econstructor; eauto using sop_star_plus__implies__sop_plus.\nQed.\n\nEnd SOP_WF_DIVERGES.\n\n(***********************************************************)\n(** big-step convergence -> small-step convergence *)\n\n(** First, by mutual induction, we prove that bInsn, bops and\n    bFdef imply small-step semantics. *)\n\nDefinition bInsn__implies__sop_plus_prop cfg state state' tr\n  (db:@bInsn GVsSig cfg state state' tr) :=\n  forall S TD Ps gl fs F B cs tmn lc als Mem B' cs' tmn' lc' als' Mem' ECs,\n  cfg = (mkbCfg S TD Ps gl fs F) ->\n  state = (mkbEC B cs tmn lc als Mem) ->\n  state' = (mkbEC B' cs' tmn' lc' als' Mem') ->\n  sop_plus (mkCfg S TD Ps gl fs)\n           (mkState ((mkEC F B cs tmn lc als)::ECs) Mem)\n           (mkState ((mkEC F B' cs' tmn' lc' als')::ECs) Mem') tr.\nDefinition bops__implies__sop_star_prop cfg state state' tr\n  (db:@bops GVsSig cfg state state' tr) :=\n  forall S TD Ps gl fs F B cs tmn lc als Mem B' cs' tmn' lc' als' Mem' ECs,\n  cfg = (mkbCfg S TD Ps gl fs F) ->\n  state = (mkbEC B cs tmn lc als Mem) ->\n  state' = (mkbEC B' cs' tmn' lc' als' Mem') ->\n  sop_star (mkCfg S TD Ps gl fs)\n           (mkState ((mkEC F B cs tmn lc als)::ECs) Mem)\n           (mkState ((mkEC F B' cs' tmn' lc' als')::ECs) Mem') tr.\nDefinition bFdef__implies__sop_star_prop fv rt lp S TD Ps lc gl fs Mem lc'\nals' Mem' B'' rid oResult tr\n(db:@bFdef GVsSig fv rt lp S TD Ps lc gl fs Mem lc' als' Mem' B'' rid oResult tr)\n  :=\n  match oResult with\n  | Some Result => forall ECs fptrs,\n    getOperandValue TD fv lc gl = Some fptrs ->\n    exists fptr, exists fa, exists fid, exists la, exists va, exists lb,\n    exists l', exists ps', exists cs', exists tmn', exists gvs, exists lc0,\n    fptr @ fptrs /\\\n    lookupFdefViaPtr Ps fs fptr =\n      Some (fdef_intro (fheader_intro fa rt fid la va) lb) /\\\n    getEntryBlock (fdef_intro (fheader_intro fa rt fid la va) lb) =\n      Some (l', stmts_intro ps' cs' tmn') /\\\n    params2GVs TD lp lc gl = Some gvs /\\\n    initLocals TD la gvs = Some lc0 /\\\n    sop_star (mkCfg S TD Ps gl fs)\n      (mkState ((mkEC (fdef_intro (fheader_intro fa rt fid la va) lb)\n                              (l', stmts_intro ps' cs' tmn') cs' tmn'\n                              lc0 nil)::ECs) Mem)\n      (mkState ((mkEC (fdef_intro (fheader_intro fa rt fid la va) lb)\n                               B'' nil (insn_return rid rt Result) lc'\n                               als')::ECs) Mem')\n      tr\n  | None => forall ECs fptrs,\n    getOperandValue TD fv lc gl = Some fptrs ->\n    exists fptr, exists fa, exists fid, exists la, exists va, exists lb,\n    exists l', exists ps', exists cs', exists tmn', exists gvs, exists lc0,\n    fptr @ fptrs /\\\n    lookupFdefViaPtr Ps fs fptr =\n      Some (fdef_intro (fheader_intro fa rt fid la va) lb) /\\\n    getEntryBlock (fdef_intro (fheader_intro fa rt fid la va) lb) =\n      Some (l', stmts_intro ps' cs' tmn') /\\\n    params2GVs TD lp lc gl = Some gvs /\\\n    initLocals TD la gvs = Some lc0 /\\\n    sop_star (mkCfg S TD Ps gl fs)\n      (mkState ((mkEC (fdef_intro (fheader_intro fa rt fid la va) lb)\n                              (l', stmts_intro ps' cs' tmn') cs' tmn'\n                              lc0 nil)::ECs) Mem)\n      (mkState ((mkEC (fdef_intro (fheader_intro fa rt fid la va) lb)\n                               B'' nil (insn_return_void rid) lc'\n                               als')::ECs) Mem')\n      tr\n  end\n  .\n\nLtac app_inv :=\n  match goal with\n  | [ H: ?f _ _ _ _ _ _ = ?f _ _ _ _ _ _ |- _ ] => inv H\n  | [ H: ?f _ _ _ _ _ = ?f _ _ _ _ _ |- _ ] => inv H\n  | [ H: ?f _ _ = ?f _ _ |- _ ] => inv H\n  end.\n\nLemma b__implies__s:\n  (forall cfg state state' t db,\n     @bInsn__implies__sop_plus_prop cfg state state' t db) /\\\n  (forall cfg state state' t db,\n     @bops__implies__sop_star_prop cfg state state' t db) /\\\n  (forall fv rt lp S TD Ps lc gl fs Mem lc' als' Mem' B'' rid oret tr db,\n     @bFdef__implies__sop_star_prop fv rt lp S TD Ps lc gl fs Mem lc' als'\n       Mem' B'' rid oret tr db).\nProof.\n(b_mutind_cases\n  apply b_mutind with\n    (P  := bInsn__implies__sop_plus_prop)\n    (P0 := bops__implies__sop_star_prop)\n    (P1 := bFdef__implies__sop_star_prop)\n    Case);\n  unfold bInsn__implies__sop_plus_prop,\n         bops__implies__sop_star_prop,\n         bFdef__implies__sop_star_prop;\n  intros; subst; simpl; repeat app_inv; eauto.\n  Case \"bCall\".\n    inversion b; subst.\n    SCase \"bFdef_func\".\n    assert (Hlookup:=H0).\n    apply H with (ECs:=(mkEC F0 B0 \n                         ((insn_call rid noret0 ca rt1 va1 fv lp)::cs')\n                         tmn0 lc0 als0)::ECs) in H0; auto. clear H.\n    destruct H0 as [fptr' [fa0 [fid0 [la0 [va0 [lb0 [l0 [ps0 [cs0 [tmn0' [gvs0\n      [lc0' [J1 [J2 [J3 [J4 [J5 J6]]]]]]]]]]]]]]]]].\n    rewrite <- E0_left.\n    apply sop_plus_cons with\n     (state2:=mkState ((mkEC (fdef_intro (fheader_intro fa0 rt fid0 la0 va0) lb0)\n                             (l0, stmts_intro ps0 cs0 tmn0') cs0 tmn0' lc0' nil)::\n                        (mkEC F0 B0 \n                          ((insn_call rid noret0 ca rt1 va1 fv lp)::cs')\n                          tmn0 lc0 als0)::ECs) Mem1); eauto.\n    rewrite <- E0_right.\n    apply sop_star_trans with\n     (state2:=mkState ((mkEC (fdef_intro (fheader_intro fa0 rt fid0 la0 va0) lb0)\n                               (l'', stmts_intro ps'' cs''\n                                (insn_return Rid rt Result)) nil\n                                (insn_return Rid rt Result) lc'\n                                als')::\n                        (mkEC F0 B0 \n                          ((insn_call rid noret0 ca rt1 va1 fv lp)::cs')\n                          tmn0 lc0 als0)::ECs) Mem'); auto.\n      apply sInsn__implies__sop_star.\n        apply sReturn; auto.\n          erewrite func_callUpdateLocals_is_returnUpdateLocals; eauto.\n\n    SCase \"bFdef_proc\".\n    assert (Hlookup:=H0).\n    apply H with (ECs:=(mkEC F0 B0 \n                         ((insn_call rid noret0 ca rt1 va1 fv lp)::cs')\n                         tmn0 lc0 als0)::ECs) in H0; auto. clear H.\n    destruct H0 as [fptr' [fa0 [fid0 [la0 [va0 [lb0 [l0 [ps0 [cs0 [tmn0' [gvs0\n      [lc0'' [J1 [J2 [J3 [J4 [J5 J6]]]]]]]]]]]]]]]]].\n    rewrite <- E0_left.\n    apply sop_plus_cons with\n     (state2:=mkState ((mkEC (fdef_intro (fheader_intro fa0 rt fid0 la0 va0) lb0)\n                            (l0, stmts_intro ps0 cs0 tmn0') cs0 tmn0' lc0'' nil)::\n                        (mkEC F0 B0 \n                         ((insn_call rid noret0 ca rt1 va1 fv lp)::cs')\n                         tmn0 lc0 als0)::ECs) Mem1); eauto.\n    rewrite <- E0_right.\n    apply proc_callUpdateLocals_is_id in e0.\n    destruct e0; subst.\n    apply sop_star_trans with\n     (state2:=mkState ((mkEC (fdef_intro (fheader_intro fa0 rt fid0 la0 va0) lb0)\n                               (l'', stmts_intro ps'' cs'' (insn_return_void Rid))\n                                nil (insn_return_void Rid) lc' als')::\n                        (mkEC F0 B0 \n                         ((insn_call rid true ca rt1 va1 fv lp)::cs')\n                         tmn0 lc'0 als0)::ECs) Mem'); auto.\n\n  Case \"bops_cons\".\n    destruct S2 as [b3 cs3 tmn3 lc3 als3].\n    apply sop_star_trans with\n      (state2:=mkState ((mkEC F b3 cs3 tmn3 lc3 als3)::ECs) bMem0); auto.\n\n  Case \"bFdef_func\".\n    rewrite H0 in e. inv e. exists fptr. exists fa. exists fid. exists la.\n    exists va. exists lb. exists l'. exists ps'. exists cs'. exists tmn'.\n    exists gvs. exists lc0. repeat (split; auto).\n\n  Case \"bFdef_proc\".\n   rewrite H0 in e. inv e. exists fptr. exists fa. exists fid. exists la.\n    exists va. exists lb. exists l'. exists ps'. exists cs'. exists tmn'.\n    exists gvs. exists lc0. repeat (split; auto).\nQed.\n\nLemma bInsn__implies__sop_plus : forall tr S TD Ps gl fs F B cs tmn lc als Mem B'\n    cs' tmn' lc' als' Mem' ECs,\n  @bInsn GVsSig (mkbCfg S TD Ps gl fs F) (mkbEC B cs tmn lc als Mem)\n    (mkbEC B' cs' tmn' lc' als' Mem') tr ->\n  sop_plus (mkCfg S TD Ps gl fs)\n           (mkState ((mkEC F B cs tmn lc als)::ECs) Mem)\n           (mkState ((mkEC F B' cs' tmn' lc' als')::ECs) Mem') tr.\nProof.\n  destruct b__implies__s as [J _]. intros.\n  unfold bInsn__implies__sop_plus_prop in J. eapply J; eauto.\nQed.\n\nLemma bInsn__implies__sop_star : forall tr S TD Ps gl fs F B cs tmn lc als Mem B'\n    cs' tmn' lc' als' Mem' ECs,\n  @bInsn GVsSig (mkbCfg S TD Ps gl fs F) (mkbEC B cs tmn lc als Mem)\n    (mkbEC B' cs' tmn' lc' als' Mem') tr ->\n  sop_star (mkCfg S TD Ps gl fs)\n           (mkState ((mkEC F B cs tmn lc als)::ECs) Mem)\n           (mkState ((mkEC F B' cs' tmn' lc' als')::ECs) Mem') tr.\nProof.\n  intros. eapply bInsn__implies__sop_plus in H; eauto.\nQed.\n\nLemma bops__implies__sop_star : forall tr S TD Ps gl fs F B cs tmn lc als Mem B'\n    cs' tmn' lc' als' Mem' ECs,\n  @bops GVsSig (mkbCfg S TD Ps gl fs F) (mkbEC B cs tmn lc als Mem)\n    (mkbEC B' cs' tmn' lc' als' Mem') tr ->\n  sop_star (mkCfg S TD Ps gl fs)\n           (mkState ((mkEC F B cs tmn lc als)::ECs) Mem)\n           (mkState ((mkEC F B' cs' tmn' lc' als')::ECs) Mem') tr.\nProof.\n  destruct b__implies__s as [_ [J _]]. intros.\n  unfold bops__implies__sop_star_prop in J. eapply J; eauto.\nQed.\n\nLemma bFdef_func__implies__sop_star : forall fv rt lp S TD Ps ECs lc gl fs\n    Mem lc' als' Mem' B'' rid Result tr fptrs,\n  @bFdef GVsSig fv rt lp S TD Ps lc gl fs Mem lc' als' Mem' B'' rid\n    (Some Result) tr ->\n  getOperandValue TD fv lc gl = Some fptrs ->\n  exists fptr, exists fa, exists fid, exists la, exists va, exists lb,\n  exists l', exists ps', exists cs', exists tmn', exists gvs, exists lc0,\n  fptr @ fptrs /\\\n  lookupFdefViaPtr Ps fs fptr =\n    Some (fdef_intro (fheader_intro fa rt fid la va) lb) /\\\n  getEntryBlock (fdef_intro (fheader_intro fa rt fid la va) lb) =\n    Some (l', stmts_intro ps' cs' tmn') /\\\n  params2GVs TD lp lc gl = Some gvs /\\\n  initLocals TD la gvs = Some lc0 /\\\n  sop_star (mkCfg S TD Ps gl fs)\n    (mkState ((mkEC (fdef_intro (fheader_intro fa rt fid la va) lb)\n                             (l', stmts_intro ps' cs' tmn') cs' tmn' lc0\n                             nil)::ECs) Mem)\n    (mkState ((mkEC (fdef_intro (fheader_intro fa rt fid la va) lb)\n                             B'' nil (insn_return rid rt Result) lc'\n                             als')::ECs) Mem')\n    tr.\nProof.\n  intros fv rt lp S TD Ps ECs lc gl fs Mem0 lc' als' Mem' B'' rid Result tr\n    fptrs H H1.\n  destruct b__implies__s as [_ [_ J]].\n  assert (K:=@J fv rt lp S TD Ps lc gl fs Mem0 lc' als' Mem' B'' rid\n    (Some Result) tr H ECs fptrs H1); auto.\nQed.\n\nLemma bFdef_proc__implies__sop_star : forall fv rt lp S TD Ps ECs lc gl fs\n    Mem lc' als' Mem' B'' rid tr fptrs,\n  @bFdef GVsSig fv rt lp S TD Ps lc gl fs  Mem lc' als' Mem' B'' rid None tr ->\n  getOperandValue TD fv lc gl = Some fptrs ->\n  exists fptr, exists fa, exists fid, exists la, exists va, exists lb,\n  exists l', exists ps', exists cs', exists tmn', exists gvs, exists lc0,\n  fptr @ fptrs /\\\n  lookupFdefViaPtr Ps fs fptr =\n    Some (fdef_intro (fheader_intro fa rt fid la va) lb) /\\\n  getEntryBlock (fdef_intro (fheader_intro fa rt fid la va) lb) =\n    Some (l', stmts_intro ps' cs' tmn') /\\\n  params2GVs TD lp lc gl = Some gvs /\\\n  initLocals TD la gvs = Some lc0 /\\\n  sop_star (mkCfg S TD Ps gl fs)\n    (mkState ((mkEC (fdef_intro (fheader_intro fa rt fid la va) lb)\n                            (l', stmts_intro ps' cs' tmn') cs' tmn' lc0\n                            nil)::ECs) Mem)\n    (mkState ((mkEC (fdef_intro (fheader_intro fa rt fid la va) lb)\n                             B'' nil (insn_return_void rid) lc'\n                             als')::ECs) Mem')\n    tr.\nProof.\n  intros fv rt lp S TD Ps ECs lc gl fs Mem0 lc' als' Mem' B'' rid tr fptrs H H1.\n  destruct b__implies__s as [_ [_ J]].\n  assert (K:=@J fv rt lp S TD Ps lc gl fs Mem0 lc' als' Mem' B'' rid None tr\n    H ECs fptrs H1); auto.\nQed.\n\n(** Then we prove that the whole program holds the same property. *)\n\nLemma b_genInitState_inv : forall S main Args initmem S0 TD Ps gl fs F B cs tmn\n  lc als M,\n @b_genInitState GVsSig S main Args initmem =\n   Some (mkbCfg S0 TD Ps gl fs F, mkbEC B cs tmn lc als M) ->\n s_genInitState S main Args initmem =\n   Some (mkCfg S0 TD Ps gl fs, mkState ((mkEC F B cs tmn lc als)::nil) M).\nProof.\n  intros.\n  unfold b_genInitState in H.\n  remember (s_genInitState S main Args initmem) as R.\n  destruct R as [[]|]; tinv H. destruct c; tinv H. destruct s; tinv H.\n  destruct ECS0; tinv H. destruct e; tinv H. destruct ECS0; inv H; auto.\nQed.\n\nLemma b_converges__implies__s_converges : forall sys main VarArgs tr rg,\n  @b_converges GVsSig sys main VarArgs tr rg ->\n  s_converges sys main VarArgs tr rg.\nProof.\n  intros sys main VarArgs tr rg Hdb_converges.\n  inversion Hdb_converges; subst. destruct cfg, IS, FS.\n  match goal with\n  | H: b_genInitState _ _ _ _ = _ |- _ =>\n    apply b_genInitState_inv in H; simpl in H\n  end.\n  eapply s_converges_intro; eauto.\n    apply bops__implies__sop_star; eauto.\n    simpl. auto.\nQed.\n\n(***********************************************************)\n(** big-step divergence -> small-step divergence *)\n\n(** First,we prove that bInsn, bops and bFdef imply small-step semantics,\n    by nested coinduction. *)\n\nLemma bFdefInf_bopInf__implies__sop_diverges :\n   forall (fv : value) (rt : typ) (lp : params) (S : system)\n     (TD : TargetData) (Ps : products) (ECs : list ExecutionContext)\n     (lc : GVsMap) (gl fs : GVMap) (Mem0 : mem) (tr : traceinf) \n     (fid : id) (fa : fnattrs) (lc1 : GVsMap) (l' : l) \n     (ps' : phinodes) (cs' : cmds) (tmn' : terminator) \n     (la : args) (va : varg) (lb : blocks) (gvs : list GVs) \n     (fptrs0 : GVs) (fptr : GenericValue),\n   fptr @ fptrs0 ->\n   lookupFdefViaPtr Ps fs fptr =\n   ret fdef_intro (fheader_intro fa rt fid la va) lb ->\n   getEntryBlock (fdef_intro (fheader_intro fa rt fid la va) lb) =\n   ret (l', stmts_intro ps' cs' tmn') ->\n   params2GVs TD lp lc gl = ret gvs ->\n   initLocals TD la gvs = ret lc1 ->\n   bopInf (mkbCfg S TD Ps gl fs (fdef_intro (fheader_intro fa rt fid la va) lb))\n     {|\n     bCurBB := (l', stmts_intro ps' cs' tmn');\n     bCurCmds := cs';\n     bTerminator := tmn';\n     bLocals := lc1;\n     bAllocas := nil;\n     bMem := Mem0 |} tr ->\n   getOperandValue TD fv lc gl = ret fptrs0 ->\n   sop_diverges (mkCfg S TD Ps gl fs)\n     {|\n     ECS := {|\n            CurFunction := fdef_intro (fheader_intro fa rt fid la va) lb;\n            CurBB := (l', stmts_intro ps' cs' tmn');\n            CurCmds := cs';\n            Terminator := tmn';\n            Locals := lc1;\n            Allocas := nil |} :: ECs;\n     Mem := Mem0 |} tr.\nProof.\n  cofix CIH_bFdefInf.\n\n  assert (forall S tr TD Ps gl fs F B cs tmn lc als Mem ECs,\n    @bInsnInf GVsSig (mkbCfg S TD Ps gl fs F) (mkbEC B cs tmn lc als Mem) tr ->\n    sop_diverges (mkCfg S TD Ps gl fs)\n                 (mkState ((mkEC F B cs tmn lc als)::ECs) Mem) tr)\n    as bInsnInf__implies__sop_diverges.\n    cofix CIH_bInsnInf.\n    intros S tr TD Ps gl fs F B cs tmn lc als Mem ECs HbInsnInf.\n\n    inversion HbInsnInf; subst.\n    rewrite <- E0_left_inf.\n    assert (HbFdefInf:=H12).\n    inversion H12; subst.\n    apply sop_diverges_intro with\n      (state2:=mkState ((mkEC (fdef_intro (fheader_intro fa rt fid la va)lb)\n                               ((l', stmts_intro ps' cs' tmn')) cs' tmn' lc1\n                               nil)::\n                        (mkEC F B \n                          ((insn_call rid noret0 ca rt1 va1 fv lp)::cs0)\n                          tmn lc als)::ECs) Mem);\n      try solve [clear CIH_bFdefInf CIH_bInsnInf; eauto].\n      inv HbFdefInf.\n      eapply CIH_bFdefInf with (fid:=fid)(l':=l')(ps':=ps')(cs':=cs')(tmn':=tmn')\n        (fa:=fa)(la:=la)(va:=va)(lb:=lb)(gvs:=gvs)(lc1:=lc1)(fptr:=fptr)(fv:=fv)\n        (lp:=lp)(lc:=lc)(fptrs0:=fptrs) in H5; eauto.\n\n  assert (forall S tr TD Ps gl fs F B cs tmn lc als Mem ECs,\n    @bopInf GVsSig (mkbCfg S TD Ps gl fs F) (mkbEC B cs tmn lc als Mem) tr ->\n    sop_diverges (mkCfg S TD Ps gl fs)\n                 (mkState ((mkEC F B cs tmn lc als)::ECs) Mem) tr)\n    as bopInf__implies__sop_diverges.\n    cofix CIH_bopInf.\n    intros S tr TD Ps gl fs F B cs tmn lc als Mem ECs HbopInf.\n    inversion HbopInf; subst.\n    Case \"bopInf_insn\".\n      eapply bInsnInf__implies__sop_diverges in H; eauto.\n    Case \"bopInf_cons\".\n      destruct state2.\n      apply bInsn__implies__sop_plus with (ECs:=ECs) in H.\n      inversion H; subst.\n      SCase \"dsop_plus_cons\".\n        apply CIH_bopInf with (ECs:=ECs) in H0. clear CIH_bopInf.\n        eapply sop_diverges_intro; eauto.\n\n  intros fv rt lp S TD Ps ECs lc gl fs Mem0 tr fid fa lc1 l' ps' cs' tmn' la va\n    lb gvs fptrs0 fptr Hin Hlookup HgetEntryBlock Hp2gvs Hinit HbFdefInf Hget.\n  inversion HbFdefInf; subst; eauto.\nQed.\n\nLemma bFdefInf__implies__sop_diverges : forall fv rt lp S TD Ps ECs lc gl fs Mem\n    tr fptrs,\n  bFdefInf fv rt lp S TD Ps lc gl fs Mem tr ->\n  getOperandValue TD fv lc gl = Some fptrs ->\n  exists fptr, exists fa, exists fid, exists la, exists va, exists lb,\n  exists l', exists ps', exists cs', exists tmn', exists gvs, exists lc0,\n  fptr @ fptrs /\\\n  lookupFdefViaPtr Ps fs fptr =\n    Some (fdef_intro (fheader_intro fa rt fid la va) lb) /\\\n  getEntryBlock (fdef_intro (fheader_intro fa rt fid la va) lb) =\n    Some (l', stmts_intro ps' cs' tmn') /\\\n  params2GVs TD lp lc gl = Some gvs /\\\n  initLocals TD la gvs = Some lc0 /\\\n  sop_diverges (mkCfg S TD Ps gl fs)\n    (mkState ((mkEC (fdef_intro (fheader_intro fa rt fid la va) lb)\n              (l', stmts_intro ps' cs' tmn') cs' tmn' lc0 nil)::ECs) Mem)\n    tr.\nProof.\n  intros fv rt lp S TD Ps ECs lc gl fs Mem0 tr fptrs HdbFdefInf Hget.\n  inv HdbFdefInf; subst.\n  exists fptr. exists fa. exists fid. exists la. exists va. exists lb. exists l'.\n  exists ps'. exists cs'. exists tmn'. exists gvs. exists lc1.\n  rewrite Hget in H. inv H.\n  repeat (split; auto).\n    eapply bFdefInf_bopInf__implies__sop_diverges; eauto.\nQed.\n\nLemma bInsnInf__implies__sop_diverges : forall S tr TD Ps gl fs F B cs tmn lc als\n  Mem ECs,\n  @bInsnInf GVsSig (mkbCfg S TD Ps gl fs F) (mkbEC B cs tmn lc als Mem) tr ->\n  sop_diverges (mkCfg S TD Ps gl fs)\n    (mkState ((mkEC F B cs tmn lc als)::ECs) Mem) tr.\nProof.\n  cofix CIH_bInsnInf.\n  intros S tr TD Ps gl fs F B cs tmn lc als Mem ECs HbInsnInf.\n\n  inversion HbInsnInf; subst.\n  rewrite <- E0_left_inf.\n  assert (HbFdefInf:=H12).\n  inversion H12; subst.\n  apply sop_diverges_intro with\n    (state2:=mkState ((mkEC (fdef_intro (fheader_intro fa rt fid la va)lb)\n                             (l', stmts_intro ps' cs' tmn') cs' tmn' lc1\n                             nil)::\n                      (mkEC F B \n                        ((insn_call rid noret0 ca rt1 va1 fv lp)::cs0)\n                        tmn lc als)::ECs) Mem);\n    try solve [clear CIH_bInsnInf; eauto].\n    eapply bFdefInf_bopInf__implies__sop_diverges with (l':=l')(ps':=ps')\n      (cs':=cs')(tmn':=tmn')(la:=la)(va:=va)(lb:=lb)(fa:=fa)(gvs:=gvs)(lc1:=lc1)\n      in H5; eauto.\nQed.\n\nLemma bopInf__implies__sop_diverges : forall S tr TD Ps gl fs F B cs tmn lc als\n  Mem ECs,\n  @bopInf GVsSig (mkbCfg S TD Ps gl fs F) (mkbEC B cs tmn lc als Mem) tr ->\n  sop_diverges (mkCfg S TD Ps gl fs)\n    (mkState ((mkEC F B cs tmn lc als)::ECs) Mem) tr.\nProof.\n  cofix CIH_bopInf.\n  intros S tr TD Ps gl fs F B cs tmn lc als Mem ECs HbopInf.\n  inversion HbopInf; subst.\n  Case \"bopInf_insn\".\n    eapply bInsnInf__implies__sop_diverges in H; eauto.\n  Case \"bopInf_cons\".\n    destruct state2.\n    apply bInsn__implies__sop_plus with (ECs:=ECs) in H.\n    inversion H; subst.\n    SCase \"dsop_plus_cons\".\n      apply CIH_bopInf with (ECs:=ECs) in H0. clear CIH_bopInf.\n      eapply sop_diverges_intro; eauto.\nQed.\n\n(** Then we prove that the whole program holds the same property. *)\n\nLemma b_diverges__implies__s_diverges : forall sys main VarArgs tr,\n  @b_diverges GVsSig sys main VarArgs tr ->\n  s_diverges sys main VarArgs tr.\nProof.\n  intros sys main VarArgs tr Hdb_diverges.\n  inversion Hdb_diverges; subst.\n  destruct cfg. destruct IS.\n  apply b_genInitState_inv in H.\n  eapply s_diverges_intro; eauto.\n  apply bopInf__implies__sop_diverges; eauto.\nQed.\n\n(***********************************************************)\n(* Inversion of operations *)\nLemma BOP_inversion : forall TD lc gl b s v1 v2 gv2,\n  BOP TD lc gl b s v1 v2 = Some gv2 ->\n  exists gvs1, exists gvs2,\n    getOperandValue TD v1 lc gl = Some gvs1 /\\\n    getOperandValue TD v2 lc gl = Some gvs2 /\\\n    GVsSig.(lift_op2) (mbop TD b s) gvs1 gvs2 (typ_int s) = Some gv2.\nProof.\n  intros TD lc gl b s v1 v2 gv2 HBOP.\n  unfold BOP in HBOP.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HBOP].\n  remember (getOperandValue TD v2 lc gl) as ogv2.\n  destruct ogv2; inv HBOP.\n  eauto.\nQed.\n\nLemma FBOP_inversion : forall TD lc gl b fp v1 v2 gv,\n  FBOP TD lc gl b fp v1 v2 = Some gv ->\n  exists gv1, exists gv2,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    getOperandValue TD v2 lc gl = Some gv2 /\\\n    GVsSig.(lift_op2) (mfbop TD b fp) gv1 gv2 (typ_floatpoint fp) = Some gv.\nProof.\n  intros TD lc gl b fp v1 v2 gv HFBOP.\n  unfold FBOP in HFBOP.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HFBOP].\n  remember (getOperandValue TD v2 lc gl) as ogv2.\n  destruct ogv2; inv HFBOP.\n  eauto.\nQed.\n\nLemma CAST_inversion : forall TD lc gl op t1 v1 t2 gv,\n  CAST TD lc gl op t1 v1 t2 = Some gv ->\n  exists gv1,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    GVsSig.(lift_op1) (mcast TD op t1 t2) gv1 t2 = Some gv.\nProof.\n  intros TD lc gl op t1 v1 t2 gv HCAST.\n  unfold CAST in HCAST.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; inv HCAST.\n  eauto.\nQed.\n\nLemma TRUNC_inversion : forall TD lc gl op t1 v1 t2 gv,\n  TRUNC TD lc gl op t1 v1 t2 = Some gv ->\n  exists gv1,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    GVsSig.(lift_op1) (mtrunc TD op t1 t2) gv1 t2 = Some gv.\nProof.\n  intros TD lc gl op t1 v1 t2 gv HTRUNC.\n  unfold TRUNC in HTRUNC.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; inv HTRUNC.\n  eauto.\nQed.\n\nLemma EXT_inversion : forall TD lc gl op t1 v1 t2 gv,\n  EXT TD lc gl op t1 v1 t2 = Some gv ->\n  exists gv1,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    GVsSig.(lift_op1) (mext TD op t1 t2) gv1 t2 = Some gv.\nProof.\n  intros TD lc gl op t1 v1 t2 gv HEXT.\n  unfold EXT in HEXT.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; inv HEXT.\n  eauto.\nQed.\n\nLemma ICMP_inversion : forall TD lc gl cond t v1 v2 gv,\n  ICMP TD lc gl cond t v1 v2 = Some gv ->\n  exists gv1, exists gv2,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    getOperandValue TD v2 lc gl = Some gv2 /\\\n    GVsSig.(lift_op2) (micmp TD cond t) gv1 gv2 (typ_int 1%nat) = Some gv.\nProof.\n  intros TD lc gl cond0 t v1 v2 gv HICMP.\n  unfold ICMP in HICMP.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HICMP].\n  remember (getOperandValue TD v2 lc gl) as ogv2.\n  destruct ogv2; inv HICMP.\n  eauto.\nQed.\n\nLemma FCMP_inversion : forall TD lc gl cond fp v1 v2 gv,\n  FCMP TD lc gl cond fp v1 v2 = Some gv ->\n  exists gv1, exists gv2,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    getOperandValue TD v2 lc gl = Some gv2 /\\\n    GVsSig.(lift_op2) (mfcmp TD cond fp) gv1 gv2 (typ_int 1%nat) = Some gv.\nProof.\n  intros TD lc gl cond0 fp v1 v2 gv HFCMP.\n  unfold FCMP in HFCMP.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HFCMP].\n  remember (getOperandValue TD v2 lc gl) as ogv2.\n  destruct ogv2; inv HFCMP.\n  eauto.\nQed.\n\n(***********************************************************)\n(* Equivalence of operations *)\nLemma const2GV_eqAL : forall c gl1 gl2 TD,\n  eqAL _ gl1 gl2 ->\n  @const2GV GVsSig TD gl1 c = const2GV TD gl2 c.\nProof.\n  intros. unfold const2GV.\n  destruct const2GV_eqAL_aux.\n  erewrite H0; eauto.\nQed.\n\nLemma getOperandValue_eqAL : forall lc1 gl lc2 v TD,\n  eqAL _ lc1 lc2 ->\n  @getOperandValue GVsSig TD v lc1 gl = getOperandValue TD v lc2 gl.\nProof.\n  intros lc1 gl lc2 v TD HeqAL.\n  unfold getOperandValue in *.\n  destruct v; auto.\nQed.\n\nLemma BOP_eqAL : forall lc1 gl lc2 bop0 sz0 v1 v2 TD,\n  eqAL _ lc1 lc2 ->\n  @BOP GVsSig TD lc1 gl bop0 sz0 v1 v2 = BOP TD lc2 gl bop0 sz0 v1 v2.\nProof.\n  intros lc1 gl lc2 bop0 sz0 v1 v2 TD HeqEnv.\n  unfold BOP in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v2); auto.\nQed.\n\nLemma FBOP_eqAL : forall lc1 gl lc2 fbop0 fp0 v1 v2 TD,\n  eqAL _ lc1 lc2 ->\n  @FBOP GVsSig TD lc1 gl fbop0 fp0 v1 v2 = FBOP TD lc2 gl fbop0 fp0 v1 v2.\nProof.\n  intros lc1 gl lc2 fbop0 fp0 v1 v2 TD HeqEnv.\n  unfold FBOP in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v2); auto.\nQed.\n\nLemma CAST_eqAL : forall lc1 gl lc2 op t1 v1 t2 TD,\n  eqAL _ lc1 lc2 ->\n  @CAST GVsSig TD lc1 gl op t1 v1 t2 = CAST TD lc2 gl op t1 v1 t2.\nProof.\n  intros lc1 gl lc2 op t1 v1 t2 TD HeqAL.\n  unfold CAST in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\nQed.\n\nLemma TRUNC_eqAL : forall lc1 gl lc2 op t1 v1 t2 TD,\n  eqAL _ lc1 lc2 ->\n  @TRUNC GVsSig TD lc1 gl op t1 v1 t2 = TRUNC TD lc2 gl op t1 v1 t2.\nProof.\n  intros lc1 gl lc2 op t1 v1 t2 TD HeqAL.\n  unfold TRUNC in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\nQed.\n\nLemma EXT_eqAL : forall lc1 gl lc2 op t1 v1 t2 TD,\n  eqAL _ lc1 lc2 ->\n  @EXT GVsSig TD lc1 gl op t1 v1 t2 = EXT TD lc2 gl op t1 v1 t2.\nProof.\n  intros lc1 gl lc2 op t1 v1 t2 TD HeqAL.\n  unfold EXT in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\nQed.\n\nLemma ICMP_eqAL : forall lc1 gl lc2 cond t v1 v2 TD,\n  eqAL _ lc1 lc2 ->\n  @ICMP GVsSig TD lc1 gl cond t v1 v2 = ICMP TD lc2 gl cond t v1 v2.\nProof.\n  intros lc1 gl lc2 cond0 t v1 v2 TD HeqAL.\n  unfold ICMP in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v2); auto.\nQed.\n\nLemma FCMP_eqAL : forall lc1 gl lc2 cond fp v1 v2 TD,\n  eqAL _ lc1 lc2 ->\n  @FCMP GVsSig TD lc1 gl cond fp v1 v2 = FCMP TD lc2 gl cond fp v1 v2.\nProof.\n  intros lc1 gl lc2 cond0 fp v1 v2 TD HeqAL.\n  unfold FCMP in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v2); auto.\nQed.\n\nLemma values2GVs_eqAL : forall l0 lc1 gl lc2 TD,\n  eqAL _ lc1 lc2 ->\n  @values2GVs GVsSig TD l0 lc1 gl = values2GVs TD l0 lc2 gl.\nProof.\n  induction l0 as [|[s v] l0]; intros lc1 gl lc2 TD HeqAL; simpl; auto.\n    rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v); auto.\n    erewrite IHl0; eauto.\nQed.\n\nLemma eqAL_callUpdateLocals : forall TD noret0 rid oResult lc1 lc2 gl lc1'\n  lc2' rt,\n  eqAL _ lc1 lc1' ->\n  eqAL _ lc2 lc2' ->\n  match (@callUpdateLocals GVsSig TD rt noret0 rid oResult lc1 lc2 gl,\n         callUpdateLocals TD rt noret0 rid oResult lc1' lc2' gl) with\n  | (Some lc, Some lc') => eqAL _ lc lc'\n  | (None, None) => True\n  | _ => False\n  end.\nProof.\n  intros TD noret0 rid oResult lc1 lc2 gl lc1' lc2' rt H1 H2.\n    unfold callUpdateLocals.\n    destruct noret0; auto.\n      destruct oResult; simpl; auto.\n        destruct v as [i0|c]; simpl.\n          rewrite H2.\n          destruct (lookupAL _ lc2' i0); auto using eqAL_updateAddAL.\n\n          destruct (@const2GV GVsSig TD gl c); auto using eqAL_updateAddAL.\n      destruct oResult; simpl; auto.\n        destruct v as [i0|c]; simpl.\n          rewrite H2.\n          destruct (lookupAL _ lc2' i0); auto.\n          destruct (GVsSig.(lift_op1) (fit_gv TD rt) g rt);\n            auto using eqAL_updateAddAL.\n\n          destruct (@const2GV GVsSig TD gl c); auto using eqAL_updateAddAL.\n          destruct (GVsSig.(lift_op1) (fit_gv TD rt) g rt);\n            auto using eqAL_updateAddAL.\nQed.\n\nLemma eqAL_getIncomingValuesForBlockFromPHINodes : forall TD ps B gl lc lc',\n  eqAL _ lc lc' ->\n  @getIncomingValuesForBlockFromPHINodes GVsSig TD ps B gl lc =\n  getIncomingValuesForBlockFromPHINodes TD ps B gl lc'.\nProof.\n  induction ps; intros; simpl; auto.\n    destruct a; auto.\n    destruct (getValueViaBlockFromValuels l0 B); auto.\n    destruct v; simpl; erewrite IHps; eauto.\n      rewrite H. auto.\nQed.\n\nLemma eqAL_updateValuesForNewBlock : forall vs lc lc',\n  eqAL _ lc lc' ->\n  eqAL _ (@updateValuesForNewBlock GVsSig vs lc)(updateValuesForNewBlock vs lc').\nProof.\n  induction vs; intros; simpl; auto.\n    destruct a; auto using eqAL_updateAddAL.\nQed.\n\nLemma eqAL_switchToNewBasicBlock : forall TD B1 B2 gl lc lc',\n  eqAL _ lc lc' ->\n  match (@switchToNewBasicBlock GVsSig TD B1 B2 gl lc,\n         switchToNewBasicBlock TD B1 B2 gl lc') with\n  | (Some lc1, Some lc1') => eqAL _ lc1 lc1'\n  | (None, None) => True\n  | _ => False\n  end.\nProof.\n  intros.\n  unfold switchToNewBasicBlock.\n  erewrite eqAL_getIncomingValuesForBlockFromPHINodes; eauto.\n  destruct\n    (getIncomingValuesForBlockFromPHINodes TD (getPHINodesFromBlock B1) B2 gl\n    lc'); auto using eqAL_updateValuesForNewBlock.\nQed.\n\nLemma eqAL_switchToNewBasicBlock' : forall TD B1 B2 gl lc lc' lc1,\n  eqAL _ lc lc' ->\n  @switchToNewBasicBlock GVsSig TD B1 B2 gl lc = Some lc1 ->\n  exists lc1', switchToNewBasicBlock TD B1 B2 gl lc' = Some lc1' /\\\n               eqAL _ lc1 lc1'.\nProof.\n  intros.\n  assert (J:=@eqAL_switchToNewBasicBlock TD B1 B2 gl lc lc' H).\n  rewrite H0 in J.\n  destruct (switchToNewBasicBlock TD B1 B2 gl lc'); try solve [inversion J].\n  exists g. auto.\nQed.\n\nLemma eqAL_params2GVs : forall lp TD lc gl lc',\n  eqAL _ lc lc' ->\n  @params2GVs GVsSig TD lp lc gl = params2GVs TD lp lc' gl.\nProof.\n  induction lp; intros; simpl; auto.\n    destruct a.\n    destruct v; simpl.\n      rewrite H. erewrite IHlp; eauto.\n      erewrite IHlp; eauto.\nQed.\n\nLemma eqAL_exCallUpdateLocals : forall TD noret0 rid oResult lc lc' rt,\n  eqAL _ lc lc' ->\n  match (@exCallUpdateLocals GVsSig TD rt noret0 rid oResult lc,\n         exCallUpdateLocals TD rt noret0 rid oResult lc') with\n  | (Some lc1, Some lc1') => eqAL _ lc1 lc1'\n  | (None, None) => True\n  | _ => False\n  end.\nProof.\n  intros TD noret0 rid oResult lc lc' rt H1.\n    unfold exCallUpdateLocals.\n    destruct noret0; auto.\n    destruct oResult; auto.\n    destruct (fit_gv TD rt g); auto using eqAL_updateAddAL.\nQed.\n\nLemma eqAL_callUpdateLocals' : forall TD ft noret0 rid oResult lc1 lc2 gl lc1'\n    lc2' lc,\n  eqAL _ lc1 lc1' ->\n  eqAL _ lc2 lc2' ->\n  @callUpdateLocals GVsSig TD ft noret0 rid oResult lc1 lc2 gl = Some lc ->\n  exists lc',\n    callUpdateLocals TD ft noret0 rid oResult lc1' lc2' gl = Some lc' /\\\n    eqAL _ lc lc'.\nProof.\n  intros TD ft noret0 rid oResult lc1 lc2 gl lc1' lc2' lc H H0 H1.\n  assert (J:=@eqAL_callUpdateLocals TD noret0 rid oResult lc1 lc2 gl lc1' lc2'\n    ft H H0).\n  rewrite H1 in J.\n  destruct (callUpdateLocals TD ft noret0 rid oResult lc1' lc2' gl);\n    try solve [inversion J].\n  exists g. auto.\nQed.\n\nLemma eqAL_exCallUpdateLocals' : forall TD ft noret0 rid oResult lc lc' lc0,\n  eqAL _ lc lc' ->\n  @exCallUpdateLocals GVsSig TD ft noret0 rid oResult lc = Some lc0 ->\n  exists lc0', exCallUpdateLocals TD ft noret0 rid oResult lc' = Some lc0' /\\\n               eqAL _ lc0 lc0'.\nProof.\n  intros TD ft noret0 rid oResult lc lc' lc0 H H0.\n  assert (J:=@eqAL_exCallUpdateLocals TD noret0 rid oResult lc lc' ft H).\n  rewrite H0 in J.\n  destruct (exCallUpdateLocals TD ft noret0 rid oResult lc');\n    try solve [inversion J].\n  exists g. auto.\nQed.\n\nLemma getIncomingValuesForBlockFromPHINodes_eq :\n  forall ps TD l1 ps1 cs1 tmn1 ps2 cs2 tmn2,\n  @getIncomingValuesForBlockFromPHINodes GVsSig TD ps\n    (l1, stmts_intro ps1 cs1 tmn1) =\n  getIncomingValuesForBlockFromPHINodes TD ps (l1, stmts_intro ps2 cs2 tmn2).\nProof.\n  induction ps; intros; auto.\n    simpl.\n    erewrite IHps; eauto.\nQed.\n\nLemma switchToNewBasicBlock_eq :\n  forall TD B l1 ps1 cs1 tmn1 ps2 cs2 tmn2 gl lc,\n  @switchToNewBasicBlock GVsSig TD B (l1, stmts_intro ps1 cs1 tmn1) gl lc =\n  switchToNewBasicBlock TD B (l1, stmts_intro ps2 cs2 tmn2) gl lc.\nProof.\n  intros.\n  unfold switchToNewBasicBlock.\n  erewrite getIncomingValuesForBlockFromPHINodes_eq; eauto.\nQed.\n\n(***********************************************************)\n(* Uniqueness of operations *)\nLemma exCallUpdateLocals_uniq : forall TD rt noret0 rid oresult lc lc',\n  uniq lc ->\n  @exCallUpdateLocals GVsSig TD rt noret0 rid oresult lc = Some lc' ->\n  uniq lc'.\nProof.\n  intros.\n  unfold exCallUpdateLocals in H0.\n  destruct noret0; auto.\n    inversion H0; subst; auto.\n\n    destruct oresult; try solve [inversion H0].\n    destruct (fit_gv TD rt g); inversion H0; subst.\n      apply updateAddAL_uniq; auto.\nQed.\n\nLemma callUpdateLocals_uniq : forall TD rt noret0 rid oresult lc lc' gl lc'',\n  uniq lc ->\n  @callUpdateLocals GVsSig TD rt noret0 rid oresult lc lc' gl = Some lc'' ->\n  uniq lc''.\nProof.\n  intros.\n  unfold callUpdateLocals in H0.\n  destruct noret0; auto.\n    destruct oresult; try solve [inversion H0; subst; auto].\n    destruct (getOperandValue TD v lc' gl); inversion H0; subst; auto.\n\n    destruct oresult; try solve [inversion H0; subst; auto].\n    destruct (getOperandValue TD v lc' gl); tinv H0.\n    destruct (lift_op1 _ (fit_gv TD rt) g rt); inv H0.\n      apply updateAddAL_uniq; auto.\nQed.\n\nLemma updateValuesForNewBlock_uniq : forall l0 lc,\n  uniq lc ->\n  uniq (@updateValuesForNewBlock GVsSig l0 lc).\nProof.\n  induction l0; intros lc Uniqc; simpl; auto.\n    destruct a; apply updateAddAL_uniq; auto.\nQed.\n\nLemma switchToNewBasicBlock_uniq : forall TD B1 B2 gl lc lc',\n  uniq lc ->\n  @switchToNewBasicBlock GVsSig TD B1 B2 gl lc = Some lc' ->\n  uniq lc'.\nProof.\n  intros TD B1 B2 gl lc lc' Uniqc H.\n  unfold switchToNewBasicBlock in H.\n  destruct (getIncomingValuesForBlockFromPHINodes TD (getPHINodesFromBlock B1)\n    B2 gl lc); inversion H; subst.\n  apply updateValuesForNewBlock_uniq; auto.\nQed.\n\nLemma initializeFrameValues_init : forall TD la l0 lc,\n  @_initializeFrameValues GVsSig TD la l0 nil = Some lc ->\n  uniq lc.\nProof.\n  induction la; intros; simpl in *; auto.\n    inv H. auto.\n\n    destruct a as [[t ?] id0].\n    destruct l0.\n      remember (@_initializeFrameValues GVsSig TD la nil nil) as R.\n      destruct R; tinv H.\n      destruct (gundef TD t); inv H; eauto using updateAddAL_uniq.\n\n      remember (@_initializeFrameValues GVsSig TD la l0 nil) as R.\n      destruct R; tinv H.\n      destruct (GVsSig.(lift_op1) (fit_gv TD t) g t); inv H;\n        eauto using updateAddAL_uniq.\nQed.\n\nLemma initLocals_uniq : forall TD la ps lc,\n  @initLocals GVsSig TD la ps = Some lc -> uniq lc.\nProof.\n  intros la ps.\n  unfold initLocals.\n  apply initializeFrameValues_init; auto.\nQed.\n\nLemma updateValuesForNewBlock_spec4 : forall rs lc id1 gv,\n  lookupAL _ rs id1 = Some gv ->\n  lookupAL _ (@updateValuesForNewBlock GVsSig rs lc) id1 = Some gv.\nProof.\n  induction rs; intros; simpl in *.\n    inversion H.\n\n    destruct a.\n    destruct (id1==a); subst.\n      inversion H; subst. apply lookupAL_updateAddAL_eq; auto.\n      rewrite <- lookupAL_updateAddAL_neq; auto.\nQed.\n\n(***********************************************************)\n(* Properties of initLocals and initializeFrameValues *)\nLemma initLocals_spec : forall TD la gvs id1 lc,\n  In id1 (getArgsIDs la) ->\n  @initLocals GVsSig TD la gvs = Some lc ->\n  exists gv, lookupAL _ lc id1 = Some gv.\nProof.\n  unfold initLocals.\n  induction la; intros; simpl in *.\n    inversion H.\n\n    destruct a as [[t c] id0].\n    simpl in H.\n    destruct H as [H | H]; subst; simpl.\n      destruct gvs.\n        remember (@_initializeFrameValues GVsSig TD la nil nil) as R1.\n        destruct R1; tinv H0.\n        remember (gundef TD t) as R2.\n        destruct R2; inv H0.\n        eauto using lookupAL_updateAddAL_eq.\n\n        remember (@_initializeFrameValues GVsSig TD la gvs nil) as R1.\n        destruct R1; tinv H0.\n        destruct (GVsSig.(lift_op1) (fit_gv TD t) g t); inv H0.\n        eauto using lookupAL_updateAddAL_eq.\n\n      destruct (eq_atom_dec id0 id1); subst.\n        destruct gvs.\n          remember (@_initializeFrameValues GVsSig TD la nil nil) as R1.\n          destruct R1; tinv H0.\n          remember (gundef TD t) as R2.\n          destruct R2; inv H0.\n          eauto using lookupAL_updateAddAL_eq.\n\n          remember (@_initializeFrameValues GVsSig TD la gvs nil) as R1.\n          destruct R1; tinv H0.\n          destruct (GVsSig.(lift_op1) (fit_gv TD t) g t); inv H0.\n          eauto using lookupAL_updateAddAL_eq.\n\n        destruct gvs.\n          remember (@_initializeFrameValues GVsSig TD la nil nil) as R1.\n          destruct R1; tinv H0.\n          remember (gundef TD t) as R2.\n          destruct R2; inv H0.\n          symmetry in HeqR1.\n          eapply IHla in HeqR1; eauto.\n          destruct HeqR1 as [gv HeqR1].\n          rewrite <- lookupAL_updateAddAL_neq; eauto.\n\n          remember (@_initializeFrameValues GVsSig TD la gvs nil) as R1.\n          destruct R1; tinv H0.\n          destruct (GVsSig.(lift_op1) (fit_gv TD t) g t); inv H0.\n          symmetry in HeqR1.\n          eapply IHla in HeqR1; eauto.\n          destruct HeqR1 as [gv HeqR1].\n          rewrite <- lookupAL_updateAddAL_neq; eauto.\nQed.\n\nLemma In_initializeFrameValues__In_getArgsIDs: forall\n  (TD : TargetData) (la : args) (gvs : list (GVsT GVsSig)) (id1 : atom)\n  (lc : Opsem.GVsMap) (gv : GVsT GVsSig) acc,\n  Opsem._initializeFrameValues TD la gvs acc = ret lc ->\n  lookupAL (GVsT GVsSig) lc id1 = ret gv ->\n  In id1 (getArgsIDs la) \\/ id1 `in` dom acc.\nProof.\n  induction la as [|[]]; simpl; intros.\n    inv H.\n    right. apply lookupAL_Some_indom in H0; auto.\n\n    destruct p.\n    destruct gvs.\n      inv_mbind. \n      destruct (id_dec i0 id1); subst; auto.\n      rewrite <- lookupAL_updateAddAL_neq in H0; auto.\n      eapply IHla in H0; eauto.\n      destruct H0 as [H0 | H0]; auto.\n\n      inv_mbind.\n      destruct (id_dec i0 id1); subst; auto.\n      rewrite <- lookupAL_updateAddAL_neq in H0; auto.\n      eapply IHla in H0; eauto.\n      destruct H0 as [H0 | H0]; auto.\nQed.\n\nLemma In_initLocals__In_getArgsIDs : forall TD la gvs id1 lc gv,\n  @Opsem.initLocals GVsSig TD la gvs = Some lc ->\n  lookupAL _ lc id1 = Some gv ->\n  In id1 (getArgsIDs la).\nProof.\n  unfold Opsem.initLocals.\n  intros.\n  eapply In_initializeFrameValues__In_getArgsIDs in H; eauto.\n  destruct H as [H | H]; auto.\n    fsetdec.\nQed.\n\nLemma dom_initializeFrameValues: forall\n  (TD : TargetData) (la : args) gvs lc acc,\n  @Opsem._initializeFrameValues GVsSig TD la gvs acc = ret lc ->\n  (forall i0, i0 `in` dom lc -> i0 `in` dom acc \\/ In i0 (getArgsIDs la)).\nProof.\n  induction la as [|[[]]]; simpl; intros.\n    inv H. auto.\n\n    destruct gvs.\n      inv_mbind'.\n      rewrite updateAddAL_dom_eq in H0.\n      assert (i1 `in` (dom g) \\/ i1 = i0) as J.\n        fsetdec.\n      destruct J as [J | J]; subst; auto.\n        symmetry in HeqR.\n        apply IHla with (i0:=i1) in HeqR; auto.\n        destruct HeqR as [HeqR | HeqR]; auto.\n\n      inv_mbind'.\n      rewrite updateAddAL_dom_eq in H0.\n      assert (i1 `in` (dom g0) \\/ i1 = i0) as J.\n        fsetdec.\n      destruct J as [J | J]; subst; auto.\n        symmetry in HeqR.\n        apply IHla with (i0:=i1) in HeqR; auto.\n        destruct HeqR as [HeqR | HeqR]; auto.\nQed.\n\nLemma NotIn_getArgsIDs__NotIn_initializeFrameValues: forall\n  (TD : TargetData) (la : args) gvs (id1 : atom) lc acc,\n  @Opsem._initializeFrameValues GVsSig TD la gvs acc = ret lc ->\n  ~ In id1 (getArgsIDs la) /\\ id1 `notin` dom acc ->\n  lookupAL _ lc id1 = None.\nProof.\n  induction la as [|[]]; simpl; intros.\n    inv H.\n    destruct H0.\n    apply notin_lookupAL_None; auto.\n\n    destruct H0 as [H1 H2].\n    assert (i0 <> id1 /\\ ~ In id1 (getArgsIDs la)) as J.\n      split; intro; subst; contradict H1; auto.\n    destruct J as [J1 J2].\n    destruct p.\n    destruct gvs.\n      inv_mbind'.\n      rewrite <- lookupAL_updateAddAL_neq; auto.\n      apply notin_lookupAL_None; auto.\n      intro J. symmetry in HeqR.\n      apply dom_initializeFrameValues with (i0:=id1) in HeqR; auto.\n      destruct HeqR; auto.\n\n      inv_mbind'.\n      rewrite <- lookupAL_updateAddAL_neq; auto.\n      eapply IHla; eauto.\nQed.\n\nLemma NotIn_getArgsIDs__NotIn_initLocals : forall TD la gvs id1 lc,\n  @Opsem.initLocals GVsSig TD la gvs = Some lc ->\n  ~ In id1 (getArgsIDs la) ->\n  lookupAL _ lc id1 = None.\nProof.\n  unfold Opsem.initLocals.\n  intros.\n  eapply NotIn_getArgsIDs__NotIn_initializeFrameValues in H; eauto.\nQed.\n\n(***********************************************************)\n(* Properties of updateValuesForNewBlock *)\nLemma updateValuesForNewBlock_spec6 : forall lc rs id1 gvs\n  (Hlk : lookupAL _ (@updateValuesForNewBlock GVsSig rs lc) id1 = ret gvs)\n  (Hin : id1 `in` (dom rs)),\n  lookupAL _ rs id1 = Some gvs.\nProof.\n  induction rs; simpl; intros.\n    fsetdec.\n\n    destruct a.\n    assert (id1 = i0 \\/ id1 `in` dom rs) as J. fsetdec.\n    destruct J as [J | J]; subst.\n      rewrite lookupAL_updateAddAL_eq in Hlk; auto. inv Hlk.\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i0 i0); auto.\n        contradict n; auto.\n\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id1 i0);\n        subst; eauto.\n        rewrite lookupAL_updateAddAL_eq in Hlk; auto.\n        rewrite <- lookupAL_updateAddAL_neq in Hlk; eauto.\nQed.\n\nLemma updateValuesForNewBlock_spec7 : forall lc rs id1 gvs\n  (Hlk : lookupAL _ (@updateValuesForNewBlock GVsSig rs lc) id1 = ret gvs)\n  (Hnotin : id1 `notin` (dom rs)),\n  lookupAL _ lc id1 = ret gvs.\nProof.\n  induction rs; simpl; intros; auto.\n    destruct a.\n\n    destruct_notin.\n    rewrite <- lookupAL_updateAddAL_neq in Hlk; eauto.\nQed.\n\nLemma updateValuesForNewBlock_spec6' : forall lc rs id1\n  (Hin : id1 `in` (dom rs)),\n  lookupAL _ (@updateValuesForNewBlock GVsSig rs lc) id1 = lookupAL _ rs id1.\nProof.\n  induction rs; simpl; intros.\n    fsetdec.\n\n    destruct a.\n    assert (id1 = a \\/ id1 `in` dom rs) as J. fsetdec.\n    destruct J as [J | J]; subst.\n      rewrite lookupAL_updateAddAL_eq.\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) a a); auto.\n        contradict n; auto.\n\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id1 a);\n        subst; eauto.\n        rewrite lookupAL_updateAddAL_eq; auto.\n        rewrite <- lookupAL_updateAddAL_neq; eauto.\nQed.\n\nLemma updateValuesForNewBlock_spec7' : forall lc rs id1\n  (Hin : id1 `notin` (dom rs)),\n  lookupAL _ (@updateValuesForNewBlock GVsSig rs lc) id1 = lookupAL _ lc id1.\nProof.\n  induction rs; simpl; intros; auto.\n    destruct a. destruct_notin.\n    rewrite <- lookupAL_updateAddAL_neq; eauto.\nQed.\n\nLemma updateValuesForNewBlock_sim : forall id0 lc lc'\n  (Heq : forall id' : id,\n        id' <> id0 ->\n        lookupAL _ lc id' = lookupAL GVs lc' id')\n  g0 g\n  (EQ : forall id' : id,\n       id' <> id0 ->\n       lookupAL _ g0 id' = lookupAL _ g id'),\n  forall id', id' <> id0 ->\n   lookupAL _ (updateValuesForNewBlock g0 lc) id' =\n   lookupAL _ (updateValuesForNewBlock g lc') id'.\nProof.\n  intros.\n  destruct (AtomSetProperties.In_dec id' (dom g0)).\n    rewrite updateValuesForNewBlock_spec6'; auto.\n    destruct (AtomSetProperties.In_dec id' (dom g)).\n      rewrite updateValuesForNewBlock_spec6'; auto.\n\n      apply notin_lookupAL_None in n.\n      erewrite <- EQ in n; eauto.\n      apply indom_lookupAL_Some in i0.\n      destruct i0 as [gv0 i0].\n      rewrite i0 in n. congruence.\n\n    rewrite updateValuesForNewBlock_spec7'; auto.\n    destruct (AtomSetProperties.In_dec id' (dom g)).\n      apply notin_lookupAL_None in n.\n      erewrite EQ in n; eauto.\n      apply indom_lookupAL_Some in i0.\n      destruct i0 as [gv0 i0].\n      rewrite i0 in n. congruence.\n\n      rewrite updateValuesForNewBlock_spec7'; auto.\nQed.\n\nLemma updateValuesForNewBlock_spec5: forall lc1' lc2' i0\n  (Hlk: lookupAL _ lc1' i0 = lookupAL _ lc2' i0) lc2\n  (Hlk: merror = lookupAL _ lc2 i0),\n  lookupAL _ lc1' i0 =\n    lookupAL _ (@Opsem.updateValuesForNewBlock GVsSig lc2 lc2') i0.\nProof.\n  induction lc2 as [|[]]; simpl; intros; auto.\n    destruct (i0 == a); try congruence.\n    rewrite <- lookupAL_updateAddAL_neq; auto.\nQed.\n\n(***********************************************************)\n(* Properties of getIncomingValuesForBlockFromPHINodes *)\nLemma getIncomingValuesForBlockFromPHINodes_spec6 : forall TD b gl lc ps' rs id1\n  (HeqR1 : ret rs = @getIncomingValuesForBlockFromPHINodes GVsSig TD ps' b gl lc)\n  (Hin : In id1 (getPhiNodesIDs ps')),\n  id1 `in` dom rs.\nProof.\n  induction ps'; simpl; intros.\n    inv Hin.\n\n    destruct a. destruct b. simpl in *.\n    inv_mbind. inv HeqR1.\n    destruct Hin as [Hin | Hin]; subst; simpl; auto.\nQed.\n\nLemma getIncomingValuesForBlockFromPHINodes_spec7 : forall TD b gl lc ps' rs id1\n  (HeqR1 : ret rs = @getIncomingValuesForBlockFromPHINodes GVsSig TD ps' b gl lc)\n  (Hin : id1 `in` dom rs),\n  In id1 (getPhiNodesIDs ps').\nProof.\n  induction ps'; simpl; intros.\n    inv HeqR1. fsetdec.\n\n    destruct a as [i0 ?]. destruct b as [l2 ? ? ?]. simpl in *.\n    inv_mbind. inv HeqR1. simpl in *.\n    assert (id1 = i0 \\/ id1 `in` dom l1) as J. fsetdec.\n    destruct J as [J | J]; subst; eauto.\nQed.\n\nLemma getIncomingValuesForBlockFromPHINodes_spec8 : forall TD b gl lc ps' rs id1\n  (HeqR1 : ret rs = @getIncomingValuesForBlockFromPHINodes GVsSig TD ps' b gl lc)\n  (Hnotin : ~ In id1 (getPhiNodesIDs ps')),\n  id1 `notin` dom rs.\nProof.\n  intros.\n  intro J. apply Hnotin.\n  eapply getIncomingValuesForBlockFromPHINodes_spec7 in HeqR1; eauto.\nQed.\n\nLemma getIncomingValuesForBlockFromPHINodes_spec9: forall TD gl lc b id0 gvs0\n  ps' l0,\n  ret l0 = @Opsem.getIncomingValuesForBlockFromPHINodes GVsSig TD ps' b gl lc ->\n  id0 `in` dom l0 ->\n  lookupAL _ l0 id0 = ret gvs0 ->\n  exists id1, exists t1, exists vls1, exists v, exists n,\n    In (insn_phi id1 t1 vls1) ps' /\\\n    nth_error vls1 n = Some (v, getBlockLabel b) /\\\n    Opsem.getOperandValue TD v lc gl= Some gvs0.\nProof.\n  induction ps' as [|[i0 t l0]]; simpl; intros.\n    inv H. fsetdec.\n\n    inv_mbind. simpl in *.\n    destruct (id0 == i0); subst.\n      destruct b. simpl in *.\n      symmetry in HeqR.\n      apply getValueViaLabelFromValuels__nth_list_value_l in HeqR; auto.\n      destruct HeqR as [n HeqR].\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i0 i0);\n        try congruence.\n      inv H1.\n      exists i0. exists t. exists l0. exists v. exists n.\n      split; auto.\n\n      apply IHps' in H1; auto; try fsetdec.\n      destruct H1 as [id1 [t1 [vls1 [v' [n' [J1 [J2 J3]]]]]]].\n      exists id1. exists t1. exists vls1. exists v'. exists n'.\n      split; auto.\nQed.\n\nLemma getIncomingValuesForBlockFromPHINodes_spec9': forall TD gl lc b id0 gvs0\n  ps' l0,\n  ret l0 = @Opsem.getIncomingValuesForBlockFromPHINodes GVsSig TD ps' b gl lc ->\n  id0 `in` dom l0 ->\n  lookupAL _ l0 id0 = ret gvs0 ->\n  exists t1, exists vls1, exists v, \n    In (insn_phi id0 t1 vls1) ps' /\\\n    getValueViaLabelFromValuels vls1 (getBlockLabel b) = Some v /\\\n    Opsem.getOperandValue TD v lc gl= Some gvs0.\nProof.\n  induction ps' as [|[i0 t l0]]; simpl; intros.\n    inv H. fsetdec.\n\n    inv_mbind. simpl in *.\n    destruct (id0 == i0); subst.\n      destruct b. simpl in *.\n      symmetry in HeqR.\n      inv H1.\n      exists t. exists l0. exists v. \n      split; auto.\n\n      apply IHps' in H1; auto; try fsetdec.\n      destruct H1 as [t1 [vls1 [v' [J1 [J2 J3]]]]].\n      exists t1. exists vls1. exists v'.\n      split; auto.\nQed.\n\n(***********************************************************)\n(* Properties of bop *)\nLemma bops_trans : forall cfg state1 state2 state3 tr1 tr2,\n  @bops GVsSig cfg state1 state2 tr1 ->\n  bops cfg state2 state3 tr2 ->\n  bops cfg state1 state3 (Eapp tr1 tr2).\nProof.\n  intros cfg state1 state2 state3 tr1 tr2 H.\n  generalize dependent state3.\n  generalize dependent tr2.\n  induction H; intros; auto.\n    rewrite Eapp_assoc. eauto.\nQed.\n\nLemma bInsn__bops : forall cfg state1 state2 tr,\n  @bInsn GVsSig cfg state1 state2 tr ->\n  bops cfg state1 state2 tr.\nProof.\n  intros.\n  rewrite <- E0_right.\n  eauto.\nQed.\n\nLemma bInsn__inv : forall cfg B1 c cs tmn3 lc1 als1 Mem1 B2 tmn4 lc2 als2\n  Mem2 tr,\n  @bInsn GVsSig cfg (mkbEC B1 (c::cs) tmn3 lc1 als1 Mem1)\n    (mkbEC B2 cs tmn4 lc2 als2 Mem2) tr ->\n  B1 = B2 /\\ tmn3 = tmn4.\nProof.\n  intros.\n  inversion H; subst; repeat (split; auto).\nQed.\n\nLemma bInsn_Call__inv : forall cfg B1 c cs tmn3 lc1 als1 Mem1 B2 tmn4 lc2 als2\n  Mem2 tr,\n  @bInsn GVsSig cfg\n    (mkbEC B1 (c::cs) tmn3 lc1 als1 Mem1) (mkbEC B2 cs tmn4 lc2 als2 Mem2) tr ->\n  Instruction.isCallInst c = true ->\n  B1 = B2 /\\ tmn3 = tmn4 /\\ als1 = als2.\nProof.\n  intros.\n  inversion H; subst; try solve [inversion H0 | repeat (split; auto)].\nQed.\n\n(* preservation of uniqueness and inclusion for bop *)\n\nDefinition bInsn_preservation_prop cfg state1 state2 tr\n  (db:@bInsn GVsSig cfg state1 state2 tr) :=\n  forall S los nts Ps gl fs F B cs tmn lc als Mem cs' tmn' B' lc' als' Mem',\n  cfg = (mkbCfg S (los, nts) Ps gl fs F) ->\n  state1 = (mkbEC B cs tmn lc als Mem) ->\n  uniqSystem S ->\n  blockInSystemModuleFdef B S (module_intro los nts Ps) F ->\n  state2 = (mkbEC B' cs' tmn' lc' als' Mem') ->\n  blockInSystemModuleFdef B' S (module_intro los nts Ps) F.\nDefinition bops_preservation_prop cfg state1 state2 tr\n  (db:@bops GVsSig cfg state1 state2 tr) :=\n  forall S los nts Ps gl fs F B cs tmn lc als Mem B' cs' tmn' lc' als' Mem',\n  cfg = (mkbCfg S (los, nts) Ps gl fs F) ->\n  state1 = (mkbEC B cs tmn lc als Mem) ->\n  state2 = (mkbEC B' cs' tmn' lc' als' Mem') ->\n  uniqSystem S ->\n  blockInSystemModuleFdef B S (module_intro los nts Ps) F ->\n  blockInSystemModuleFdef B' S (module_intro los nts Ps) F.\nDefinition bFdef_preservation_prop fv rt lp S TD Ps lc gl fs Mem lc' als'\n Mem' B' Rid oResult tr\n (db:@bFdef GVsSig fv rt lp S TD Ps lc gl fs Mem lc' als' Mem' B' Rid oResult tr)\n  :=\n  forall los nts,\n  TD = (los, nts) ->\n  uniqSystem S ->\n  moduleInSystem (module_intro los nts Ps) S ->\n  exists fptrs, exists fptr, exists F,\n    getOperandValue TD fv lc gl = Some fptrs /\\\n    fptr @ fptrs /\\\n    lookupFdefViaPtr Ps fs fptr = Some F /\\\n    uniqFdef F /\\\n    blockInSystemModuleFdef B' S (module_intro los nts Ps) F.\n\nLemma b_preservation :\n  (forall cfg state1 state2 tr db,\n     @bInsn_preservation_prop cfg state1 state2 tr db) /\\\n  (forall cfg state1 state2 tr db,\n     @bops_preservation_prop cfg state1 state2 tr  db) /\\\n  (forall fv rt lp S TD Ps lc gl fs Mem lc' als' Mem' B' Rid oResult tr db,\n    @bFdef_preservation_prop fv rt lp S TD Ps lc gl fs Mem lc' als' Mem' B' Rid\n      oResult tr db).\nProof.\n(b_mutind_cases\n  apply b_mutind with\n    (P  := bInsn_preservation_prop)\n    (P0 := bops_preservation_prop)\n    (P1 := bFdef_preservation_prop) Case);\n  unfold bInsn_preservation_prop,\n         bops_preservation_prop,\n         bFdef_preservation_prop; intros; subst; repeat app_inv; auto.\nCase \"bBranch\".\n  apply andb_true_iff in H2.\n  destruct H2.\n  eapply andb_true_iff.\n  split; auto.\n    assert (uniqFdef F0) as UniqF0.\n      eapply uniqSystem__uniqFdef with (S:=S0); eauto.\n    symmetry in e0.\n    destruct (isGVZero (los, nts) c);\n      apply lookupBlockViaLabelFromFdef_inv in e0; auto.\n\nCase \"bBranch_uncond\".\n  apply andb_true_iff in H2.\n  destruct H2.\n  eapply andb_true_iff.\n  split; auto.\n    assert (uniqFdef F0) as UniqF0.\n      eapply uniqSystem__uniqFdef with (S:=S0); eauto.\n    symmetry in e.\n    apply lookupBlockViaLabelFromFdef_inv in e; auto.\n\nCase \"bops_cons\".\n  destruct S2 as [b2 cs2 tmn2 lc2 als2 M2].\n  eapply H with (cs0:=cs)(lc0:=lc)(als0:=als)(gl0:=gl)(fs0:=fs)(Mem:=Mem0)\n    (B':=b2)(lc':=lc2)(cs':=cs2)(tmn':=tmn2)(als':=als2)(Mem':=M2) in H5; eauto.\n\nCase \"bFdef_func\".\n  exists fptrs. exists fptr.\n  exists (fdef_intro (fheader_intro fa rt fid la va) lb).\n  split; auto.\n  split; auto.\n  split; auto.\n  split.\n    eapply lookupFdefViaPtr_uniq; eauto.\n    eapply H with (lc'0:=lc')(cs'0:=nil)(als'0:=als')(Mem'0:=Mem');\n      eauto using entryBlockInSystemBlockFdef''.\n\nCase \"bFdef_proc\".\n  exists fptrs. exists fptr.\n  exists (fdef_intro (fheader_intro fa rt fid la va) lb).\n  split; auto.\n  split; auto.\n  split; auto.\n  split.\n    eapply lookupFdefViaPtr_uniq; eauto.\n    eapply H; eauto using entryBlockInSystemBlockFdef''.\nQed.\n\nLemma bInsn_preservation : forall tr S los nts Ps F cs tmn lc als\n  gl fs Mem cs' tmn' lc' als' Mem' B B',\n  @bInsn GVsSig (mkbCfg S (los, nts) Ps gl fs F)\n    (mkbEC B cs tmn lc als Mem)\n    (mkbEC B' cs' tmn' lc' als' Mem') tr ->\n  uniqSystem S ->\n  blockInSystemModuleFdef B S (module_intro los nts Ps) F ->\n  blockInSystemModuleFdef B' S (module_intro los nts Ps) F.\nProof.\n  intros.\n  destruct b_preservation as [J _].\n  unfold bInsn_preservation_prop in J.\n  eapply J; eauto.\nQed.\n\nLemma bops_preservation : forall tr S los nts Ps F B cs tmn lc als gl\n    fs Mem B' cs' tmn' lc' als' Mem',\n  @bops GVsSig (mkbCfg S (los, nts) Ps gl fs F)\n    (mkbEC B cs tmn lc als Mem) (mkbEC B' cs' tmn' lc' als' Mem')\n    tr ->\n  uniqSystem S ->\n  blockInSystemModuleFdef B S (module_intro los nts Ps) F ->\n  blockInSystemModuleFdef B' S (module_intro los nts Ps) F.\nProof.\n  intros.\n  destruct b_preservation as [_ [J _]].\n  unfold bops_preservation_prop in J.\n  eapply J; eauto.\nQed.\n\nLemma bFdef_preservation : forall fv rt lp S los nts Ps lc gl fs Mem lc'\n    als' Mem' B' Rid oResult tr,\n  @bFdef GVsSig fv rt lp S (los, nts) Ps lc gl fs Mem lc' als' Mem' B' Rid\n    oResult tr ->\n  uniqSystem S ->\n  moduleInSystem (module_intro los nts Ps) S ->\n  exists fptrs, exists fptr, exists F,\n    getOperandValue (los, nts) fv lc gl = Some fptrs /\\\n    fptr @ fptrs /\\\n    lookupFdefViaPtr Ps fs fptr = Some F /\\\n    uniqFdef F /\\\n    blockInSystemModuleFdef B' S (module_intro los nts Ps) F.\nProof.\n  intros.\n  destruct b_preservation as [_ [_ J]].\n  unfold bFdef_preservation_prop in J.\n  eapply J; eauto.\nQed.\n\nEnd OpsemProps. End OpsemProps.\n", "meta": {"author": "vellvm", "repo": "vellvm-legacy", "sha": "e4c22d795974ba7c768c18b74fa098b0be2f86f7", "save_path": "github-repos/coq/vellvm-vellvm-legacy", "path": "github-repos/coq/vellvm-vellvm-legacy/vellvm-legacy-e4c22d795974ba7c768c18b74fa098b0be2f86f7/src/Vellvm/opsem_props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.24422292271020377}}
{"text": "Require Import Coq.Relations.Relation_Definitions.\nRequire Import Coq.Relations.Relation_Operators.\nRequire Import List.\n\nRequire Export Syntax.\n\nReserved Notation \" P '/' cfg '==>' cfg' \" (at level 40).\n\nInductive step (P : program) : configuration -> configuration -> Prop :=\n(***************)\n(* Parallelism *)\n(***************)\n  | EvalAsyncLeft :\n      forall H H' V V' n n' T1 T1' T2 e,\n        P / (H, V, n, T1) ==>\n          (H', V', n', T1') ->\n        P / (H, V, n, T_Async T1 T2 e) ==>\n          (H', V', n', T_Async T1' T2 e)\n  | EvalAsyncRight :\n      forall H H' V V' n n' T1 T2 T2' e,\n        P / (H, V, n, T2) ==>\n          (H', V', n', T2') ->\n        P / (H, V, n, T_Async T1 T2 e) ==>\n          (H', V', n', T_Async T1 T2' e)\n  | EvalAsyncJoin :\n      forall H V n e1 T2 Ls e,\n        threads_done(T_Thread Ls e1) ->\n        threads_done(T2) ->\n        P / (H, V, n, T_Async (T_Thread Ls e1) T2 e) ==>\n          (H, V, n, T_Thread Ls e)\n  | EvalSpawn :\n      forall H V n e1 e2 e3 Ls,\n        P / (H, V, n, T_Thread Ls (EPar e1 e2 e3)) ==>\n          (H, V, n, T_Async (T_Thread Ls e1) (T_Thread nil e2) e3)\n  | EvalSpawnContext :\n      forall H V n ctx e e1 e2 e3 Ls,\n        is_econtext ctx ->\n        P / (H, V, n, T_Thread Ls e) ==>\n          (H, V, n, T_Async (T_Thread Ls e1) (T_Thread nil e2) e3) ->\n        P / (H, V, n, T_Thread Ls (ctx e)) ==>\n          (H, V, n, T_Async (T_Thread Ls e1) (T_Thread nil e2) (ctx e3))\n(*****************)\n(* Single thread *)\n(*****************)\n  | EvalContext :\n      forall H H' V V' n n' ctx e e' Ls Ls',\n        is_econtext ctx ->\n        P / (H, V, n, T_Thread Ls e) ==>\n          (H', V', n', T_Thread Ls' e') ->\n        P / (H, V, n, T_Thread Ls (ctx e)) ==>\n          (H', V', n', T_Thread Ls' (ctx e'))\n  | EvalVar :\n      forall H V n x v Ls,\n        V x = Some v ->\n        P / (H, V, n, T_Thread Ls (EVar (DV x))) ==>\n          (H, V, n, T_Thread Ls (EVal v))\n  | EvalConsume :\n      forall H V n x v Ls,\n        V x = Some v ->\n        P / (H, V, n, T_Thread Ls (EConsume (DV x))) ==>\n          (H, extend V x VNull, n, T_Thread Ls (EVal v))\n  | EvalCast :\n      forall H V n v t Ls,\n        P / (H, V, n, T_Thread Ls (ECast t (EVal v))) ==>\n          (H, V, n, T_Thread Ls (EVal v))\n  | EvalNew :\n      forall H V n c i fs RL ms Ls,\n        classLookup P c = (Some (Cls c i fs ms)) ->\n        declsToRegionLocks fs RL ->\n        P / (H, V, n, T_Thread Ls (ENew c)) ==>\n          (heapExtend H (c, declsToFields fs, RL),\n           V, n, T_Thread Ls (EVal (VLoc (length H))))\n  | EvalCall :\n      forall H V n x l m v c mtds y body t t' Ls,\n        V x = Some (VLoc l) ->\n        (exists F RL, heapLookup H l = Some (c, F, RL)) ->\n        methods P (TClass c) = Some mtds ->\n        methodLookup mtds m = Some (Method m (y, t) t' body) ->\n        P / (H, V, n, T_Thread Ls (ECall (DV x) m (EVal v))) ==>\n          (H, extend (extend V (dthis, n) (VLoc l)) (DVar n, n) v, S n,\n           T_Thread Ls (subst y (DVar n, n) (subst this (dthis, n) (sigma n body))))\n  | EvalSelect :\n      forall H V n x l f c F RL v Ls,\n        V x = Some (VLoc l) ->\n        heapLookup H l = Some (c, F, RL) ->\n        F f = Some v ->\n        P / (H, V, n, T_Thread Ls (ESelect (DV x) f)) ==>\n          (H, V, n, T_Thread Ls (EVal v))\n  | EvalConsumeField :\n      forall H V n x l f c F RL v Ls,\n        V x = Some (VLoc l) ->\n        heapLookup H l = Some (c, F, RL) ->\n        F f = Some v ->\n        P / (H, V, n, T_Thread Ls (EConsumeField (DV x) f)) ==>\n          (heapUpdate H l (c, extend F f VNull, RL), V, n, T_Thread Ls (EVal v))\n  | EvalUpdate :\n      forall H V n x l f v c F RL Ls,\n        V x = Some (VLoc l) ->\n        heapLookup H l = Some (c, F, RL) ->\n        P / (H, V, n, T_Thread Ls (EUpdate (DV x) f (EVal v))) ==>\n          (heapUpdate H l (c, extend F f v, RL), V, n, T_Thread Ls (EVal VNull))\n  | EvalLet :\n      forall H V n frame x v body Ls,\n        P / (H, V, n, T_Thread Ls (ELet x frame (EVal v) body)) ==>\n          (H, extend V (DVar n, frame) v, S n, T_Thread Ls ((subst x (DVar n, frame) body)))\n  | EvalAssert :\n      forall H V n x y l e Ls,\n        V x = Some (VLoc l) ->\n        V y = Some (VLoc l) ->\n        P / (H, V, n, T_Thread Ls (EAssert (DV x) (DV y) e)) ==>\n          (H, V, n, T_Thread Ls e)\n(***********)\n(* Locking *)\n(***********)\n  | EvalWlock :\n      forall H V n x r l e c F RL Ls,\n        V x = Some (VLoc l) ->\n        heapLookup H l = Some (c, F, RL) ->\n        RL r = Some (LReaders 0) ->\n        ~ In (l, r) Ls ->\n        P / (H, V, n, T_Thread Ls (EWlock (DV x) r e)) ==>\n          (heapUpdate H l (c, F, extend RL r LLocked), V, n, T_Thread ((l, r) :: Ls) (EWlocked (l, r) e))\n  | EvalWlock_Reentrant :\n      forall H V n x r l e c F RL Ls,\n        V x = Some (VLoc l) ->\n        heapLookup H l = Some (c, F, RL) ->\n        RL r = Some LLocked ->\n        In (l, r) Ls ->\n        P / (H, V, n, T_Thread Ls (EWlock (DV x) r e)) ==>\n          (H, V, n, T_Thread Ls e)\n  | EvalWlock_Release :\n      forall H V n r l v c F RL Ls,\n        heapLookup H l = Some (c, F, RL) ->\n        RL r = Some LLocked ->\n        In (l, r) Ls ->\n        P / (H, V, n, T_Thread Ls (EWlocked (l, r) (EVal v))) ==>\n          (heapUpdate H l (c, F, extend RL r (LReaders 0)), V, n, T_Thread (remove id_eq_dec (l, r) Ls) (EVal v))\n  | EvalRlock :\n      forall H V n x r l m e c F RL Ls,\n        V x = Some (VLoc l) ->\n        heapLookup H l = Some (c, F, RL) ->\n        RL r = Some (LReaders m) ->\n        P / (H, V, n, T_Thread Ls (ERlock (DV x) r e)) ==>\n          (heapUpdate H l (c, F, extend RL r (LReaders (S m))), V, n, T_Thread Ls (ERlocked (l, r) e))\n  | EvalRlock_Reentrant :\n      forall H V n x r l e c F RL Ls,\n        V x = Some (VLoc l) ->\n        heapLookup H l = Some (c, F, RL) ->\n        RL r = Some LLocked ->\n        In (l, r) Ls ->\n        P / (H, V, n, T_Thread Ls (ERlock (DV x) r e)) ==>\n          (H, V, n, T_Thread Ls e)\n  | EvalRlock_Release :\n      forall H V n r l m v c F RL Ls,\n        heapLookup H l = Some (c, F, RL) ->\n        RL r = Some (LReaders m) ->\n        P / (H, V, n, T_Thread Ls (ERlocked (l, r) (EVal v))) ==>\n          (heapUpdate H l (c, F, extend RL r (LReaders (pred m))), V, n, T_Thread Ls (EVal v))\n(**************)\n(* Exceptions *)\n(**************)\n  | EvalEXN_AsyncLeft :\n      forall H V n T1 T2 e,\n        threads_exn(T1) ->\n        P / (H, V, n, T_Async T1 T2 e) ==>\n          (H, V, n, T_EXN (leftmost_locks T1))\n  | EvalEXN_AsyncRight :\n      forall H V n T1 T2 e,\n        threads_exn(T2) ->\n        P / (H, V, n, T_Async T1 T2 e) ==>\n          (H, V, n, T_EXN (leftmost_locks T1))\n  | EvalEXN_Context :\n      forall ctx H V n e Ls,\n        is_econtext ctx ->\n        P / (H, V, n, T_Thread Ls e) ==> \n           (H, V, n, T_EXN Ls) ->\n        P / (H, V, n, T_Thread Ls (ctx e)) ==>\n          (H, V, n, T_EXN Ls)\n  | EvalEXN_Call :\n      forall H V n x m v Ls,\n        V x = Some VNull ->\n        P / (H, V, n, T_Thread Ls (ECall (DV x) m (EVal v))) ==>\n          (H, V, n, T_EXN Ls)\n  | EvalEXN_Select :\n      forall H V n x f Ls,\n        V x = Some VNull ->\n        P / (H, V, n, T_Thread Ls (ESelect (DV x) f)) ==>\n          (H, V, n, T_EXN Ls)\n  | EvalEXN_ConsumeField :\n      forall H V n x f Ls,\n        V x = Some VNull ->\n        P / (H, V, n, T_Thread Ls (EConsumeField (DV x) f)) ==>\n          (H, V, n, T_EXN Ls)\n  | EvalEXN_Update :\n      forall H V n x f v Ls,\n        V x = Some VNull ->\n        P / (H, V, n, T_Thread Ls (EUpdate (DV x) f (EVal v))) ==>\n          (H, V, n, T_EXN Ls)\n  | EvalEXN_WLock :\n      forall H V n x r e Ls,\n        V x = Some VNull ->\n        P / (H, V, n, T_Thread Ls (EWlock (DV x) r e)) ==>\n          (H, V, n, T_EXN Ls)\n  | EvalEXN_RLock :\n      forall H V n x r e Ls,\n        V x = Some VNull ->\n        P / (H, V, n, T_Thread Ls (ERlock (DV x) r e)) ==>\n          (H, V, n, T_EXN Ls)\n  | EvarEXN_AssertL :\n      forall H V n x y e Ls,\n        V x = Some VNull ->\n        P / (H, V, n, T_Thread Ls (EAssert (DV x) (DV y) e)) ==>\n          (H, V, n, T_EXN Ls)\n  | EvarEXN_AssertR :\n      forall H V n x y e Ls,\n        V y = Some VNull ->\n        P / (H, V, n, T_Thread Ls (EAssert (DV x) (DV y) e)) ==>\n          (H, V, n, T_EXN Ls)\n  | EvarEXN_Assert :\n      forall H V n x y l1 l2 e Ls,\n        V x = Some (VLoc l1) ->\n        V y = Some (VLoc l2) ->\n        l1 <> l2 ->\n        P / (H, V, n, T_Thread Ls (EAssert (DV x) (DV y) e)) ==>\n          (H, V, n, T_EXN Ls)\n      \n  where \" P '/' cfg '==>' cfg' \" := (step P cfg cfg').\n\nHint Constructors step.\n\nTactic Notation \"step_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"EvalAsyncLeft\" \n  | Case_aux c \"EvalAsyncRight\" \n  | Case_aux c \"EvalAsyncJoin\" \n  | Case_aux c \"EvalSpawn\" \n  | Case_aux c \"EvalSpawnContext\" \n\n  | Case_aux c \"EvalContext\" \n  | Case_aux c \"EvalVar\" \n  | Case_aux c \"EvalConsume\" \n  | Case_aux c \"EvalNew\" \n  | Case_aux c \"EvalCall\" \n  | Case_aux c \"EvalSelect\"\n  | Case_aux c \"EvalConsumeField\"\n  | Case_aux c \"EvalUpdate\" \n  | Case_aux c \"EvalLet\" \n  | Case_aux c \"EvalAssert\" \n\n  | Case_aux c \"EvalWlock\"\n  | Case_aux c \"EvalWlock_Reentrant\"\n  | Case_aux c \"EvalWlock_Release\"\n  | Case_aux c \"EvalRlock\"\n  | Case_aux c \"EvalRlock_Reentrant\"\n  | Case_aux c \"EvalRlock_Release\"\n\n  | Case_aux c \"EvalEXN_AsyncLeft\"\n  | Case_aux c \"EvalEXN_AsyncRight\"\n  | Case_aux c \"EvalEXN_Context\"\n  | Case_aux c \"EvalEXN_Call\"\n  | Case_aux c \"EvalEXN_Select\"\n  | Case_aux c \"EvalEXN_Update\"\n  | Case_aux c \"EvalEXN_Assert\"\n  ].\n\nDefinition multistep (P : program) := clos_refl_trans_1n configuration (step P).\nNotation \" P '/' cfg '==>*' cfg' \" := (multistep P cfg cfg') (at level 40).\n\nInductive cfg_blocked : configuration -> Prop :=\n  | Blocked_Deadlock :\n      forall H V n T1 T2 e,\n        cfg_blocked (H, V, n, T1) ->\n        cfg_blocked (H, V, n, T2) ->\n        cfg_blocked (H, V, n, T_Async T1 T2 e)\n  | Blocked_Left :\n      forall H V n T1 T2 e,\n        cfg_blocked (H, V, n, T1) ->\n        threads_done T2 ->\n        cfg_blocked (H, V, n, T_Async T1 T2 e)\n  | Blocked_Right :\n      forall H V n T1 T2 e,\n        threads_done T1 ->\n        cfg_blocked (H, V, n, T2) ->\n        cfg_blocked (H, V, n, T_Async T1 T2 e)\n  | Blocked_WW :\n      forall H V n x r e l c F RL Ls,\n        V x = Some (VLoc l) ->\n        heapLookup H l = Some (c, F, RL) ->\n        RL r = Some LLocked ->\n        ~ In (l, r) Ls ->\n        cfg_blocked (H, V, n, T_Thread Ls (EWlock (DV x) r e))\n  | Blocked_WR :\n      forall H V n x r e l c F RL m Ls,\n        V x = Some (VLoc l) ->\n        heapLookup H l = Some (c, F, RL) ->\n        RL r = Some (LReaders m) ->\n        m > 0 ->\n        cfg_blocked (H, V, n, T_Thread Ls (EWlock (DV x) r e))\n  | Blocked_RW :\n      forall H V n x r e l c F RL Ls,\n        V x = Some (VLoc l) ->\n        heapLookup H l = Some (c, F, RL) ->\n        RL r = Some LLocked ->\n        ~ In (l, r) Ls ->\n        cfg_blocked (H, V, n, T_Thread Ls (ERlock (DV x) r e))\n  | Blocked_Context :\n      forall H V n ctx e Ls,\n        is_econtext ctx -> \n        cfg_blocked (H, V, n, T_Thread Ls e) ->\n        cfg_blocked (H, V, n, T_Thread Ls (ctx e)).\n\n  \n\n\n", "meta": {"author": "EliasC", "repo": "kappaf", "sha": "b94256feae361a2f3d3daf1c7a08bb55b06a2f9b", "save_path": "github-repos/coq/EliasC-kappaf", "path": "github-repos/coq/EliasC-kappaf/kappaf-b94256feae361a2f3d3daf1c7a08bb55b06a2f9b/KappaF/Dynamic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.24422292271020377}}
{"text": "(** Realisation of the RCB_resources interface *)\nFrom iris.algebra Require Import agree auth excl gmap.\nFrom aneris.algebra Require Import monotone.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic Require Import invariants.\nFrom aneris.aneris_lang Require Import lang resources.\nFrom aneris.examples.rcb.spec Require Import base.\nFrom aneris.examples.rcb.model Require Import events model_spec.\nFrom aneris.examples.rcb.resources Require Import base.\n\nSection Local_history.\n\n  Context `{!anerisG Mdl Σ, !RCB_params, !internal_RCBG Σ}.\n\n  Section Predicates.\n\n    (* One ghost location per replica *)\n    Context (γLs : list gname).\n\n    Definition mk_hst (q : Qp)\n                       (h : gset local_event) :\n                       prodR fracR (agreeR (gsetO local_event)) :=\n      (q, to_agree h).\n\n    (* For some reason we can't write 6%Qp... *)\n    Definition one_sixth_qp := (1 / pos_to_Qp 6)%Qp.\n\n    (* Lives in the global invariant *)\n    Definition lhst_glob_aux (γ : gname) (s : gset local_event) : iProp Σ :=\n      own γ (mk_hst one_sixth_qp s).\n\n    Definition lhst_glob (i : nat) (s : gset local_event) : iProp Σ :=\n      ∃ γ, ⌜γLs !! i = Some γ⌝ ∗ lhst_glob_aux γ s.\n\n    (* Lives in the lock invariant *)\n    Definition lhst_lock_aux (γ : gname) (s : gset local_event) : iProp Σ :=\n      own γ (mk_hst one_sixth_qp s).\n\n    Definition lhst_lock (i : nat) (s : gset local_event) : iProp Σ :=\n      ∃ γ, ⌜γLs !! i = Some γ⌝ ∗  lhst_lock_aux γ s.\n\n    (* Given to the user *)\n    Definition lhst_user_aux (γ : gname) (s : gset local_event) : iProp Σ :=\n      own γ (mk_hst (2/3)%Qp s).\n\n    Definition lhst_user (i : nat) (s : gset local_event) : iProp Σ :=\n      ∃ γ, ⌜γLs !! i = Some γ⌝ ∗ lhst_user_aux γ s.\n\n\n    Lemma lhst_glob_lock_user_full :\n      (2 / 3 + 1 / pos_to_Qp 6 + 1 / pos_to_Qp 6)%Qp = 1%Qp.\n    Proof. compute_done. Qed.\n\n    Lemma lhst_user_excl (i : nat) (s s' : gset local_event) :\n      lhst_user i s ⊢ lhst_user i s' -∗ False.\n    Proof.\n      iIntros \"Hl1 Hl2\".\n      iDestruct \"Hl1\" as (γ1) \"[%Heq1 Hown1]\".\n      iDestruct \"Hl2\" as (γ2) \"[%Heq2 Hown2]\".\n      assert (γ1 = γ2) as ->.\n      { rewrite Heq1 in Heq2.\n        inversion Heq2; done. }\n      iPoseProof (own_valid_2 with \"Hown1 Hown2\") as \"%Hv\".\n      exfalso.\n      rewrite /mk_hst in Hv.\n      eapply frac_pair_valid_implies_false; [apply Hv | by compute ].\n    Qed.\n\n    Lemma lhst_mk_hst_agree (γ : gname) (p q : Qp) (s1 s2 : gset local_event) :\n      own γ (mk_hst p s1) ⊢ own γ (mk_hst q s2)  -∗ ⌜s1 = s2⌝.\n    Proof.\n      iIntros \"H1 H2\".\n      iPoseProof (own_valid_2 with \"H1 H2\") as \"%Hv\".\n      iPureIntro.\n      rewrite -pair_op in Hv.\n      apply (iffLR (pair_valid _ _)) in Hv as [_ Hv].\n      apply to_agree_op_valid in Hv.\n      by (apply leibniz_equiv).\n    Qed.\n\n    Lemma lhst_user_lock_aux_agree γ s1 s2 :\n      lhst_user_aux γ s1 ⊢ lhst_lock_aux γ s2 -∗ ⌜s1 = s2⌝.\n    Proof. apply lhst_mk_hst_agree. Qed.\n\n    Lemma lhst_user_glob_aux_agree γ s1 s2 :\n      lhst_user_aux γ s1 ⊢ lhst_glob_aux γ s2 -∗ ⌜s1 = s2⌝.\n    Proof. apply lhst_mk_hst_agree. Qed.\n\n    Lemma lhst_lock_glob_aux_agree γ s1 s2 :\n      lhst_lock_aux γ s1 ⊢ lhst_glob_aux γ s2 -∗ ⌜s1 = s2⌝.\n    Proof. apply lhst_mk_hst_agree. Qed.\n\n    Lemma lhst_user_lock_agree i s1 s2 :\n      lhst_user i s1 ⊢ lhst_lock i s2 -∗ ⌜s1 = s2⌝.\n    Proof.\n      iIntros \"Huser Hlock\".\n      iDestruct \"Huser\" as (γ1) \"[%Hl1 Huser]\".\n      iDestruct \"Hlock\" as (γ2) \"[%Hl2 Hlock]\".\n      assert (γ1 = γ2) as ->.\n      { rewrite Hl1 in Hl2; inversion Hl2; done. }\n      iApply (lhst_user_lock_aux_agree with \"Huser Hlock\").\n    Qed.\n\n    Lemma lhst_user_glob_agree i s1 s2 :\n      lhst_user i s1 ⊢ lhst_glob i s2 -∗ ⌜s1 = s2⌝.\n    Proof.\n      iIntros \"Huser Hglob\".\n      iDestruct \"Huser\" as (γ1) \"[%Hl1 Huser]\".\n      iDestruct \"Hglob\" as (γ2) \"[%Hl2 Hglob]\".\n      assert (γ1 = γ2) as ->.\n      { rewrite Hl1 in Hl2; inversion Hl2; done. }\n      iApply (lhst_user_glob_aux_agree with \"Huser Hglob\").\n    Qed.\n\n    Lemma lhst_lock_glob_agree i s1 s2 :\n      lhst_lock i s1 ⊢ lhst_glob i s2 -∗ ⌜s1 = s2⌝.\n    Proof.\n      iIntros \"Hlock Hglob\".\n      iDestruct \"Hlock\" as (γ1) \"[%Hl1 Hlock]\".\n      iDestruct \"Hglob\" as (γ2) \"[%Hl2 Hglob]\".\n      assert (γ1 = γ2) as ->.\n      { rewrite Hl1 in Hl2; inversion Hl2; done. }\n      iApply (lhst_lock_glob_aux_agree with \"Hlock Hglob\").\n    Qed.\n\n    Lemma lhst_user_lookup i s Ss :\n      ([∗ list] γs';S ∈ γLs;Ss, lhst_glob_aux γs' S) ⊢\n      lhst_user i s -∗\n      ⌜Ss !! i = Some s⌝.\n    Proof.\n      iIntros \"HL Hs\".\n      iDestruct \"Hs\" as (γ) \"[% Hs]\".\n      iDestruct (big_sepL2_length with \"HL\") as %Hlen.\n      destruct (lookup_lt_is_Some_2 Ss i) as [S HS].\n      { rewrite -Hlen; apply lookup_lt_is_Some; eauto. }\n      iDestruct (big_sepL2_lookup_acc _ _ _ i with \"HL\") as \"[HS Hrest]\";\n        eauto.\n      by (iDestruct (lhst_user_glob_aux_agree with \"Hs HS\") as %->).\n    Qed.\n\n    Lemma lhst_lock_lookup i s Ss :\n      ([∗ list] γs';S ∈ γLs;Ss, lhst_glob_aux γs' S) ⊢\n      lhst_lock i s -∗\n      ⌜Ss !! i = Some s⌝.\n    Proof.\n      iIntros \"HL Hs\".\n      iDestruct \"Hs\" as (γ) \"[% Hs]\".\n      iDestruct (big_sepL2_length with \"HL\") as %Hlen.\n      destruct (lookup_lt_is_Some_2 Ss i) as [S HS].\n      { rewrite -Hlen; apply lookup_lt_is_Some; eauto. }\n      iDestruct (big_sepL2_lookup_acc _ _ _ i with \"HL\") as \"[HS Hrest]\";\n        eauto.\n      by (iDestruct (lhst_lock_glob_aux_agree with \"Hs HS\") as %->).\n    Qed.\n\n    Lemma lhst_update_aux γ s e :\n      lhst_user_aux γ s ⊢\n      lhst_lock_aux γ s -∗\n      lhst_glob_aux γ s ==∗\n      lhst_user_aux γ (s ∪ {[e]}) ∗\n      lhst_lock_aux γ (s ∪ {[e]}) ∗\n      lhst_glob_aux γ (s ∪ {[e]}).\n    Proof.\n      iIntros \"Hu Hl Hg\".\n      iMod (own_update_3 _ _ _ _\n                         ((mk_hst (2/3)%Qp (s ∪ {[e]})) ⋅\n                          (mk_hst one_sixth_qp (s ∪ {[e]})) ⋅\n                          (mk_hst one_sixth_qp (s ∪ {[e]}))) with \"Hu Hl Hg\") as \"Hfull\".\n      { assert (Exclusive (mk_hst (2 / 3) s ⋅\n                           mk_hst one_sixth_qp s ⋅\n                           mk_hst one_sixth_qp s)) as excl.\n        { rewrite -pair_op; simpl.\n          apply pair_exclusive_l.\n          rewrite /one_sixth_qp.\n          do 2 rewrite frac_op.\n          rewrite lhst_glob_lock_user_full.\n          apply frac_full_exclusive. }\n        apply cmra_update_exclusive.\n        rewrite /mk_hst /one_sixth_qp.\n        rewrite -pair_op.\n        apply pair_valid; simpl; split.\n        - apply frac_valid; done.\n        - do 2 rewrite agree_idemp; done. }\n      iDestruct (own_op with \"Hfull\") as \"[Hfull Hglob]\".\n      iDestruct (own_op with \"Hfull\") as \"[Hfull Hlock]\".\n      iModIntro.\n      iFrame.\n    Qed.\n\n    Lemma lhst_update i s Ss e:\n      lhst_user i s ⊢\n      lhst_lock i s -∗\n      ([∗ list] γs;S ∈ γLs;Ss, lhst_glob_aux γs S) ==∗\n      lhst_user i (s ∪ {[ e ]}) ∗\n      lhst_lock i (s ∪ {[ e ]}) ∗\n      ([∗ list] γs;S ∈ γLs; <[i := s ∪ {[ e ]} ]> Ss, lhst_glob_aux γs S).\n    Proof.\n      iIntros \"Hu Hl HL\".\n      iDestruct \"Hu\" as (γu) \"[%Hlu Hu]\".\n      iDestruct \"Hl\" as (γl) \"[%Hll Hl]\".\n      iDestruct (big_sepL2_length with \"HL\") as %Hlen.\n      destruct (lookup_lt_is_Some_2 Ss i) as [s' Hs'].\n      { rewrite -Hlen; apply lookup_lt_is_Some; eauto. }\n      iDestruct (big_sepL2_insert_acc _ _ _ i with \"HL\") as \"[HS Hback]\";\n        eauto.\n      assert (γl = γu) as ->.\n      { rewrite Hlu in Hll; inversion Hll; done. }\n      iDestruct (lhst_lock_glob_aux_agree with \"Hl HS\") as %->.\n      iMod ((lhst_update_aux _ _ e) with \"Hu Hl HS\") as \"(Hu & Hl & HS)\".\n      iSpecialize (\"Hback\" $! γu (s' ∪ {[e]}) with \"HS\").\n      rewrite (list_insert_id γLs); last done.\n      iModIntro; iFrame.\n      iSplitL \"Hu\"; iExists _; by iFrame.\n    Qed.\n\n  End Predicates.\n\n  Section init.\n\n    Lemma alloc_lhst :\n    True ⊢ |==>\n      ∃ γLs,\n        ⌜length γLs = length RCB_addresses⌝ ∗\n        ([∗ list] i ↦ _ ∈ RCB_addresses, lhst_glob γLs i ∅) ∗\n        ([∗ list] i ↦ _ ∈ RCB_addresses, lhst_lock γLs i ∅) ∗\n        ([∗ list] i ↦ _ ∈ RCB_addresses, lhst_user γLs i ∅).\n    Proof.\n      iIntros (_).\n      iInduction RCB_addresses as [|dba] \"IHdba\"; simpl.\n      { by iModIntro; iExists []. }\n      iMod (\"IHdba\") as (γLs Hlen) \"(Hg & Hl & Hu)\".\n      iMod (own_alloc (mk_hst (2 / 3)%Qp ∅ ⋅ mk_hst one_sixth_qp ∅ ⋅ mk_hst one_sixth_qp ∅)) as (γ') \"Hnew\".\n      { rewrite -pair_op /one_sixth_qp frac_op frac_op; simpl.\n        apply pair_valid; split; [ | do 2 rewrite agree_idemp; done].\n        rewrite lhst_glob_lock_user_full; done. }\n      iDestruct (own_op with \"Hnew\") as \"[Hnew Hg']\".\n      iDestruct (own_op with \"Hnew\") as \"[Hu' Hl']\".\n      iModIntro.\n      iExists (γ' :: γLs).\n      rewrite -Hlen /=; iSplit; first done.\n      iFrame.\n      iSplitL \"Hg'\"; [iExists γ'; iFrame; done |].\n      iSplitL \"Hl'\"; [iExists γ'; iFrame; done |].\n      iExists γ'; iFrame; done.\n    Qed.\n\n  End init.\n\nEnd Local_history.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/rcb/resources/resources_lhst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24421372091167384}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\nRequire Import Coqlib.\nRequire Import Compopts.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Op.\nRequire Import ValueDomain.\nRequire Import RTL.\n\n(** Value analysis for IA32 operators *)\n\nDefinition eval_static_condition (cond: condition) (vl: list aval): abool :=\n  match cond, vl with\n  | Ccomp c, v1 :: v2 :: nil => cmp_bool c v1 v2\n  | Ccompu c, v1 :: v2 :: nil => cmpu_bool c v1 v2\n  | Ccompimm c n, v1 :: nil => cmp_bool c v1 (I n)\n  | Ccompuimm c n, v1 :: nil => cmpu_bool c v1 (I n)\n  | Ccompf c, v1 :: v2 :: nil => cmpf_bool c v1 v2\n  | Cnotcompf c, v1 :: v2 :: nil => cnot (cmpf_bool c v1 v2)\n  | Ccompfs c, v1 :: v2 :: nil => cmpfs_bool c v1 v2\n  | Cnotcompfs c, v1 :: v2 :: nil => cnot (cmpfs_bool c v1 v2)\n  | Cmaskzero n, v1 :: nil => maskzero v1 n\n  | Cmasknotzero n, v1 :: nil => cnot (maskzero v1 n)\n  | _, _ => Bnone\n  end.\n\nDefinition eval_static_addressing (addr: addressing) (vl: list aval): aval :=\n  match addr, vl with\n  | Aindexed n, v1::nil => add v1 (I n)\n  | Aindexed2 n, v1::v2::nil => add (add v1 v2) (I n)\n  | Ascaled sc ofs, v1::nil => add (mul v1 (I sc)) (I ofs)\n  | Aindexed2scaled sc ofs, v1::v2::nil => add v1 (add (mul v2 (I sc)) (I ofs))\n  | Aglobal s ofs, nil => Ptr (Gl s ofs)\n  | Abased s ofs, v1::nil => add (Ptr (Gl s ofs)) v1\n  | Abasedscaled sc s ofs, v1::nil => add (Ptr (Gl s ofs)) (mul v1 (I sc))\n  | Ainstack ofs, nil => Ptr(Stk ofs)\n  | _, _ => Vbot\n  end.\n\nDefinition eval_static_operation (op: operation) (vl: list aval): aval :=\n  match op, vl with\n  | Omove, v1::nil => v1\n  | Ointconst n, nil => I n\n  | Ofloatconst n, nil => if propagate_float_constants tt then F n else ftop\n  | Osingleconst n, nil => if propagate_float_constants tt then FS n else ftop\n  | Oindirectsymbol id, nil => Ptr (Gl id Int.zero)\n  | Ocast8signed, v1 :: nil => sign_ext 8 v1\n  | Ocast8unsigned, v1 :: nil => zero_ext 8 v1\n  | Ocast16signed, v1 :: nil => sign_ext 16 v1\n  | Ocast16unsigned, v1 :: nil => zero_ext 16 v1\n  | Oneg, v1::nil => neg v1\n  | Osub, v1::v2::nil => sub v1 v2\n  | Omul, v1::v2::nil => mul v1 v2\n  | Omulimm n, v1::nil => mul v1 (I n)\n  | Omulhs, v1::v2::nil => mulhs v1 v2\n  | Omulhu, v1::v2::nil => mulhu v1 v2\n  | Odiv, v1::v2::nil => divs v1 v2\n  | Odivu, v1::v2::nil => divu v1 v2\n  | Omod, v1::v2::nil => mods v1 v2\n  | Omodu, v1::v2::nil => modu v1 v2\n  | Oand, v1::v2::nil => and v1 v2\n  | Oandimm n, v1::nil => and v1 (I n)\n  | Oor, v1::v2::nil => or v1 v2\n  | Oorimm n, v1::nil => or v1 (I n)\n  | Oxor, v1::v2::nil => xor v1 v2\n  | Oxorimm n, v1::nil => xor v1 (I n)\n  | Onot, v1::nil => notint v1\n  | Oshl, v1::v2::nil => shl v1 v2\n  | Oshlimm n, v1::nil => shl v1 (I n)\n  | Oshr, v1::v2::nil => shr v1 v2\n  | Oshrimm n, v1::nil => shr v1 (I n)\n  | Oshrximm n, v1::nil => shrx v1 (I n)\n  | Oshru, v1::v2::nil => shru v1 v2\n  | Oshruimm n, v1::nil => shru v1 (I n)\n  | Ororimm n, v1::nil => ror v1 (I n)\n  | Oshldimm n, v1::v2::nil => or (shl v1 (I n)) (shru v2 (I (Int.sub Int.iwordsize n)))\n  | Olea addr, _ => eval_static_addressing addr vl\n  | Onegf, v1::nil => negf v1\n  | Oabsf, v1::nil => absf v1\n  | Oaddf, v1::v2::nil => addf v1 v2\n  | Osubf, v1::v2::nil => subf v1 v2\n  | Omulf, v1::v2::nil => mulf v1 v2\n  | Odivf, v1::v2::nil => divf v1 v2\n  | Onegfs, v1::nil => negfs v1\n  | Oabsfs, v1::nil => absfs v1\n  | Oaddfs, v1::v2::nil => addfs v1 v2\n  | Osubfs, v1::v2::nil => subfs v1 v2\n  | Omulfs, v1::v2::nil => mulfs v1 v2\n  | Odivfs, v1::v2::nil => divfs v1 v2\n  | Osingleoffloat, v1::nil => singleoffloat v1\n  | Ofloatofsingle, v1::nil => floatofsingle v1\n  | Ointoffloat, v1::nil => intoffloat v1\n  | Ofloatofint, v1::nil => floatofint v1\n  | Ointofsingle, v1::nil => intofsingle v1\n  | Osingleofint, v1::nil => singleofint v1\n  | Omakelong, v1::v2::nil => longofwords v1 v2\n  | Olowlong, v1::nil => loword v1\n  | Ohighlong, v1::nil => hiword v1\n  | Ocmp c, _ => of_optbool (eval_static_condition c vl)\n  | _, _ => Vbot\n  end.\n\nSection SOUNDNESS.\n\nVariable bc: block_classification.\nVariable ge: genv.\nHypothesis GENV: genv_match bc ge.\nVariable sp: block.\nHypothesis STACK: bc sp = BCstack.\n\nTheorem eval_static_condition_sound:\n  forall cond vargs m aargs,\n  Forall2 (vmatch bc) vargs aargs ->\n  cmatch (eval_condition cond vargs m) (eval_static_condition cond aargs).\nProof.\n  intros until aargs; intros VM.\n  inv VM.\n  destruct cond; auto with va.\n  inv H0.\n  destruct cond; simpl; eauto with va.\n  inv H2.\n  destruct cond; simpl; eauto with va.\n  destruct cond; auto with va.\nQed.\n\nLemma symbol_address_sound:\n  forall id ofs,\n  vmatch bc (Genv.symbol_address ge id ofs) (Ptr (Gl id ofs)).\nProof.\n  intros; apply symbol_address_sound; apply GENV.\nQed.\n\nHint Resolve symbol_address_sound: va.\n\nLtac InvHyps :=\n  match goal with\n  | [H: None = Some _ |- _ ] => discriminate\n  | [H: Some _ = Some _ |- _] => inv H\n  | [H1: match ?vl with nil => _ | _ :: _ => _ end = Some _ ,\n     H2: Forall2 _ ?vl _ |- _ ] => inv H2; InvHyps\n  | _ => idtac\n  end.\n\nTheorem eval_static_addressing_sound:\n  forall addr vargs vres aargs,\n  eval_addressing ge (Vptr sp Int.zero) addr vargs = Some vres ->\n  Forall2 (vmatch bc) vargs aargs ->\n  vmatch bc vres (eval_static_addressing addr aargs).\nProof.\n  unfold eval_addressing, eval_static_addressing; intros;\n  destruct addr; InvHyps; eauto with va.\n  rewrite Int.add_zero_l; auto with va. \nQed.\n\nTheorem eval_static_operation_sound:\n  forall op vargs m vres aargs,\n  eval_operation ge (Vptr sp Int.zero) op vargs m = Some vres ->\n  Forall2 (vmatch bc) vargs aargs ->\n  vmatch bc vres (eval_static_operation op aargs).\nProof.\n  unfold eval_operation, eval_static_operation; intros;\n  destruct op; InvHyps; eauto with va.\n  destruct (propagate_float_constants tt); constructor.\n  destruct (propagate_float_constants tt); constructor.\n  eapply eval_static_addressing_sound; eauto.\n  apply of_optbool_sound. eapply eval_static_condition_sound; eauto. \nQed.\n\nEnd SOUNDNESS.\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/ia32/ValueAOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24421371541608913}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export per_props_more.\n\n\n\n(* ========= W TYPES ========= *)\n\nDefinition wlistA T := mkc_union mkc_unit T.\n\nDefinition wlistB v :=\n  mkc_ite_vars\n    [v]\n    (mkc_var v)\n    (mk_cv [v] mkc_void)\n    (mk_cv [v] mkc_unit).\n\nDefinition wlist (T : CTerm) := mkc_w (wlistA T) nvarx (wlistB nvarx).\n\nDefinition wnil := mkc_sup (mkc_inl mkc_axiom) mkc_id.\n\nDefinition wcons a b := mkc_sup (mkc_inr a) (mkc_lamc nvarx b).\n\nDefinition ex3ones :=\n  wcons (mkc_nat 1) (wcons (mkc_nat 1) (wcons (mkc_nat 1) wnil)).\n\nDefinition unit_eq : term-equality :=\n  fun t t' =>\n    ccomputes_to_valc t mkc_axiom\n    # ccomputes_to_valc t' mkc_axiom\n    # capproxc mkc_axiom mkc_axiom.\n\nDefinition void_eq : term-equality := fun (t t' : CTerm) => void.\n\nDefinition wlist_eqa eqT :=\n  fun t t' => per_union_eq unit_eq eqT t t'.\n\nDefinition per_isl (a a' : CTerm)\n                   (eq : term-equality)\n                   (e : wlist_eqa eq a a')\n                   (T1 T2 : [U]) :=\n  match e with\n    | or_introl _ => T1\n    | or_intror _ => T2\n  end.\n\nDefinition wlist_eqb eqT :=\n  fun a a' (e : wlist_eqa eqT a a') t t' =>\n    per_isl a a' eqT e (void_eq t t') (unit_eq t t').\n\nDefinition wlist_eq eqT :=\n  fun t t' => weq (wlist_eqa eqT) (wlist_eqb eqT) t t'.\n\nLemma lsubst_wlistB_as_decide :\n  forall v x,\n    ! LIn nvarx (free_vars x)\n    -> lsubst (mk_decide (mk_var v) nvarx mk_void nvarx mk_unit) [(v, x)]\n       = mk_decide x nvarx mk_void nvarx mk_unit.\nProof.\n  introv ninx.\n  unfold lsubst.\n  destruct (dec_disjointv\n              (bound_vars (mk_decide (mk_var v) nvarx mk_void nvarx mk_unit))\n              (flat_map free_vars (range [(v, x)]))).\n\n  simpl.\n  remember (beq_var v v); destruct b; simpl.\n  remember (memvar v [nvarx]); destruct b; simpl.\n  symmetry in Heqb0.\n  rw fold_assert in Heqb0.\n  rw assert_memvar in Heqb0; simpl in Heqb0; sp.\n  rw <- Heqb0; simpl.\n  remember (beq_var v nvarx); destruct b; simpl; sp.\n  apply beq_var_true in Heqb1; sp; subst.\n  symmetry in Heqb0. rw not_of_assert in Heqb0.\n  rw assert_memvar in Heqb0; simpl in Heqb0; sp.\n  rw not_over_or in Heqb0; sp.\n  rw <- beq_var_refl in Heqb; sp.\n\n  assert (eqvars\n            (bound_vars (mk_decide (mk_var v) nvarx mk_void nvarx mk_unit))\n            [nvarx]) as eqv1.\n  simpl; rw eqvars_prop; simpl; sp; split; sp.\n\n  assert (flat_map free_vars (range [(v, x)]) = free_vars x) as eqv2.\n  simpl; rw app_nil_r; sp.\n\n  destruct n.\n  rewrite eqv2.\n  apply eqvars_disjoint with (s1 := [nvarx]); sp.\n  rw disjoint_singleton_l; sp.\nQed.\n\nLemma computes_substc_wlistB_inl :\n  forall a x,\n    computes_to_valc a (mkc_inl x)\n    -> computes_to_valc (substc a nvarx (wlistB nvarx)) mkc_void.\nProof.\n  introv c.\n  destruct_cterms.\n  allunfold computes_to_valc; allsimpl.\n  unfold subst.\n\n  allrw isprog_eq.\n  allunfold isprogram; repnd.\n\n  assert (lsubst (mk_decide (mk_var nvarx) nvarx mk_void nvarx mk_unit) [(nvarx, x0)]\n          = mk_decide x0 nvarx mk_void nvarx mk_unit) as eq.\n  change_to_lsubst_aux4; try (complete (simpl; allrw; simpl; sp)).\n\n  rw eq.\n\n  apply implies_computes_to_value_inl_decide with (a := x); sp.\n  unfold subst; simpl.\n  change_to_lsubst_aux4; simpl; sp; allrw; simpl; sp.\n  apply computes_to_value_isvalue_refl; sp.\nQed.\n\nLemma computes_substc_wlistB_inr :\n  forall a x,\n    computes_to_valc a (mkc_inr x)\n    -> computes_to_valc (substc a nvarx (wlistB nvarx)) mkc_unit.\nProof.\n  introv c.\n  destruct_cterms.\n  allunfold computes_to_valc; allsimpl.\n  unfold subst.\n\n  allrw isprog_eq.\n  allunfold isprogram; repnd.\n\n  assert (lsubst (mk_decide (mk_var nvarx) nvarx mk_void nvarx mk_unit) [(nvarx, x0)]\n          = mk_decide x0 nvarx mk_void nvarx mk_unit) as eq.\n  change_to_lsubst_aux4; try (complete (simpl; allrw; simpl; sp)).\n\n  rw eq.\n\n  apply implies_computes_to_value_inr_decide with (a := x); sp.\n  unfold subst; simpl.\n  change_to_lsubst_aux4; simpl; sp; allrw; simpl; sp.\n  apply computes_to_value_isvalue_refl; sp.\nQed.\n\nLemma nuprl_mkc_void :\n  nuprl mkc_void mkc_void void_eq.\nProof.\n  apply CL_sqle; unfold per_sqle.\n  exists mkc_axiom mkc_bot mkc_axiom mkc_bot; sp;\n  try (complete (rw <- mkc_false_eq; rw mkc_void_eq_mkc_false;\n                 apply computes_to_valc_refl; sp;\n                 apply iscvalue_mkc_false)).\n  unfold void_eq; split; sp.\n  allapply not_axiom_approxc_bot; sp.\nQed.\nHint Immediate nuprl_mkc_void.\n\nLemma nuprl_mkc_unit :\n  nuprl mkc_unit mkc_unit unit_eq.\nProof.\n  apply CL_sqle; unfold per_sqle.\n  exists mkc_axiom mkc_axiom mkc_axiom mkc_axiom; sp;\n  try (complete (rw <- mkc_true_eq; rw mkc_unit_eq_mkc_true;\n                 apply computes_to_valc_refl; sp;\n                 apply iscvalue_mkc_true)).\nQed.\nHint Immediate nuprl_mkc_unit.\n\nLemma wnil_is_list :\n  forall T, type T -> member wnil (wlist T).\nProof.\n  introv tT.\n  unfold member, equality, nuprl.\n  unfold type, tequality in tT; exrepnd.\n  exists (wlist_eq eq); sp.\n  apply CL_w; unfold per_w, type_family.\n  exists (wlist_eqa eq) (wlist_eqb eq); sp.\n  exists (wlistA T) (wlistA T) nvarx nvarx (wlistB nvarx) (wlistB nvarx); sp;\n  repeat (apply computes_to_valc_refl; try (apply iscvalue_mkc_w)).\n\n  apply CL_union; unfold per_union.\n  exists unit_eq eq mkc_unit mkc_unit T T; sp;\n  repeat (apply computes_to_valc_refl; try (apply iscvalue_mkc_union)).\n\n  fold nuprl.\n  unfold wlist_eqa, per_union_eq in e; exrepnd; repdors; repnd.\n\n  unfold unit_eq in e0; repnd.\n  generalize (computes_substc_wlistB_inl a x)\n             (computes_substc_wlistB_inl a' y);\n    intros c1 c2.\n  dest_imp c1 hyp.\n  dest_imp c2 hyp.\n  apply computes_to_valc_implies_cequivc in c1.\n  apply computes_to_valc_implies_cequivc in c2.\n  apply nuprl_value_respecting_left with (t1 := mkc_void);\n    try (complete (apply cequivc_sym; sp)).\n  apply nuprl_value_respecting_right with (t2 := mkc_void);\n    try (complete (apply cequivc_sym; sp)).\n\n  unfold wlist_eqb, per_isl; simpl.\n  unfold void_eq; fold void_eq.\n  apply nuprl_mkc_void.\n\n  unfold unit_eq in e2; repnd.\n  generalize (computes_substc_wlistB_inr a x)\n             (computes_substc_wlistB_inr a' y);\n    intros c1 c2.\n  dest_imp c1 hyp.\n  dest_imp c2 hyp.\n  apply computes_to_valc_implies_cequivc in c1.\n  apply computes_to_valc_implies_cequivc in c2.\n  apply nuprl_value_respecting_left with (t1 := mkc_unit);\n    try (complete (apply cequivc_sym; sp)).\n  apply nuprl_value_respecting_right with (t2 := mkc_unit);\n    try (complete (apply cequivc_sym; sp)).\n\n  unfold wlist_eqb, per_isl; simpl.\n  unfold unit_eq; fold unit_eq.\n  apply nuprl_mkc_unit.\n\n  unfold wlist_eq.\n\n  assert (wlist_eqa eq (mkc_inl mkc_axiom) (mkc_inl mkc_axiom)) as e.\n  unfold wlist_eqa, per_union_eq.\n  exists mkc_axiom mkc_axiom; sp; left; sp;\n  repeat (apply computes_to_valc_refl; try (apply iscvalue_mkc_inl)).\n  unfold unit_eq; sp;\n  repeat (apply computes_to_valc_refl; try (apply iscvalue_mkc_axiom)).\n  assert (cequivc mkc_axiom mkc_axiom) as c; sp.\n  destruct c; sp.\n\n  apply weq_cons with\n        (a := mkc_inl mkc_axiom) (a' := mkc_inl mkc_axiom)\n        (f := mkc_id) (f' := mkc_id)\n        (e := e); sp;\n  repeat (apply computes_to_valc_refl; try (apply iscvalue_mkc_sup)).\n  unfold wlist_eqb, void_eq, per_isl in X; allsimpl; sp.\n  destruct e; allsimpl; sp; allsimpl; sp.\n  provefalse.\n  allunfold computes_to_valc; allsimpl.\n  destruct_cterms.\n  unfold mkc_inr in p0; allsimpl.\n  apply computes_to_value_isvalue_eq in p0; sp.\n  inversion p0.\n  apply isvalue_inl; sp.\nQed.\n", "meta": {"author": "coq-contribs", "repo": "intuitionistic-nuprl", "sha": "6279ed83244dc4aec2e23ffb4c87e3f10a50326d", "save_path": "github-repos/coq/coq-contribs-intuitionistic-nuprl", "path": "github-repos/coq/coq-contribs-intuitionistic-nuprl/intuitionistic-nuprl-6279ed83244dc4aec2e23ffb4c87e3f10a50326d/wtypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.24408211334856852}}
{"text": "Require Import Kami.Syntax Kami.Semantics Kami.RefinementFacts Kami.Renaming Kami.Wf.\nRequire Import Kami.Inline Kami.InlineFacts Kami.Tactics Lib.CommonTactics.\nRequire Import Ex.SC Ex.MemTypes Ex.ProcThreeStage.\n\nSet Implicit Arguments.\n\nSection Inlined.\n  Variables addrSize iaddrSize instBytes dataBytes rfIdx: nat.\n\n  Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes)\n            (dec: AbsDec addrSize instBytes dataBytes rfIdx)\n            (exec: AbsExec addrSize instBytes dataBytes rfIdx).\n\n  Variable (d2eElt: Kind).\n  Variable (d2ePack:\n              forall ty,\n                Expr ty (SyntaxKind (Bit 2)) -> (* opTy *)\n                Expr ty (SyntaxKind (Bit rfIdx)) -> (* dst *)\n                Expr ty (SyntaxKind (Bit addrSize)) -> (* addr *)\n                Expr ty (SyntaxKind (Array Bool dataBytes)) -> (* byteEn *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val1 *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val2 *)\n                Expr ty (SyntaxKind (Data instBytes)) -> (* rawInst *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* curPc *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* nextPc *)\n                Expr ty (SyntaxKind Bool) -> (* epoch *)\n                Expr ty (SyntaxKind d2eElt)).\n  Variables\n    (d2eOpType: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Bit 2)))\n    (d2eDst: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                        Expr ty (SyntaxKind (Bit rfIdx)))\n    (d2eAddr: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                         Expr ty (SyntaxKind (Bit addrSize)))\n    (d2eByteEn: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Array Bool dataBytes)))\n    (d2eVal1 d2eVal2: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                                 Expr ty (SyntaxKind (Data dataBytes)))\n    (d2eRawInst: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                            Expr ty (SyntaxKind (Data instBytes)))\n    (d2eCurPc: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                          Expr ty (SyntaxKind (Pc addrSize)))\n    (d2eNextPc: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Pc addrSize)))\n    (d2eEpoch: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                          Expr ty (SyntaxKind Bool)).\n\n  Variable (e2wElt: Kind).\n  Variable (e2wPack:\n              forall ty,\n                Expr ty (SyntaxKind d2eElt) -> (* decInst *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* execVal *)\n                Expr ty (SyntaxKind e2wElt)).\n  Variables\n    (e2wDecInst: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                            Expr ty (SyntaxKind d2eElt))\n    (e2wVal: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                        Expr ty (SyntaxKind (Data dataBytes))).\n\n  Variable (init: ProcInit addrSize dataBytes rfIdx).\n\n  Definition p3st := p3st fetch dec exec\n                          d2ePack d2eOpType d2eDst d2eAddr d2eByteEn d2eVal1 d2eVal2\n                          d2eRawInst d2eCurPc d2eNextPc d2eEpoch\n                          e2wPack e2wDecInst e2wVal init.\n  #[local] Hint Unfold p3st: ModuleDefs. (* for kinline_compute *)\n\n  Definition p3stInl: sigT (fun m: Modules => p3st <<== m).\n  Proof. (* SKIP_PROOF_ON\n    kinline_refine p3st.\n    END_SKIP_PROOF_ON *) apply cheat.\n  Defined.\n\nEnd Inlined.\n\n", "meta": {"author": "mit-plv", "repo": "kami", "sha": "cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0", "save_path": "github-repos/coq/mit-plv-kami", "path": "github-repos/coq/mit-plv-kami/kami-cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0/Kami/Ex/ProcThreeStInl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.24408211334856847}}
{"text": "Require Import Omega.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Time.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import SmallStep.\n\nSet Implicit Arguments.\n\nInductive fulfilled c l f t msg :=\n| fulfilled_intro\n    (GET: Memory.get l t c.(Configuration.memory) = Some (f, msg))\n    (FULFILLED: forall tid, ~ Threads.is_promised tid l t c.(Configuration.threads))\n.\n\nLemma writing_small_step_fulfilled_forward\n      withprm tid e c1 c2 loc from to val released ord\n      (WF: Configuration.wf c1)\n      (STEP: small_step withprm tid e c1 c2)\n      (WRITING: ThreadEvent.is_writing e = Some (loc, from, to, val, released, ord)):\n  forall l f t msg\n    (NP: fulfilled c1 l f t msg),\n    fulfilled c2 l f t msg.\nProof.\n  inv STEP. guardH PFREE.\n  inv STEP0; inv STEP; ss. inv LOCAL; inv WRITING; ss.\n  - inv LOCAL0. inv WRITE. inv PROMISE.\n    { i. inv NP. econs; s.\n      - erewrite Memory.add_o; eauto. condtac; ss.\n        des. subst. exploit Memory.add_get0; eauto. congr.\n      - ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac.\n        + i. inv TID0. apply inj_pair2 in H1. subst. ss.\n          revert PROMISES0. erewrite Memory.remove_o; eauto. condtac; ss.\n          erewrite Memory.add_o; eauto. condtac; ss. i.\n          eapply FULFILLED. econs; eauto.\n        + i. eapply FULFILLED. econs; eauto.\n    }\n    { i. inv NP. econs; s.\n      - erewrite Memory.split_o; eauto. condtac; ss.\n        { des. subst. exploit Memory.split_get0; eauto. i. des. congr. }\n        condtac; ss. guardH o. des. subst.\n        exfalso. eapply FULFILLED. econs; eauto.\n        hexploit Memory.split_get0; try exact PROMISES; eauto. i. des. eauto.\n      - ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac.\n        + i. inv TID0. apply inj_pair2 in H1. subst. ss.\n          revert PROMISES0. erewrite Memory.remove_o; eauto. condtac; ss.\n          erewrite Memory.split_o; eauto. repeat condtac; ss.\n          * guardH o. guardH o0. i. des. inv PROMISES0.\n            eapply FULFILLED. econs; eauto.\n            hexploit Memory.split_get0; try exact PROMISES; eauto. i. des. eauto.\n          * i. eapply FULFILLED. econs; eauto.\n        + i. eapply FULFILLED. econs; eauto.\n    }\n    { i. inv NP. econs; s.\n      - erewrite Memory.lower_o; eauto. condtac; ss.\n        des. subst. exfalso. eapply FULFILLED. econs; eauto.\n        hexploit Memory.lower_get0; try exact PROMISES; eauto.\n      - ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac.\n        + i. inv TID0. apply inj_pair2 in H1. subst. ss.\n          revert PROMISES0. erewrite Memory.remove_o; eauto. condtac; ss.\n          erewrite Memory.lower_o; eauto. condtac; ss.\n          guardH o. guardH o0. i. des. inv PROMISES0.\n          eapply FULFILLED. econs; eauto.\n        + i. eapply FULFILLED. econs; eauto.\n    }\n  - inv LOCAL1. clear GET.\n    inv LOCAL2. inv WRITE. inv PROMISE.\n    { i. inv NP. econs; s.\n      - erewrite Memory.add_o; eauto. condtac; ss.\n        des. subst. exploit Memory.add_get0; eauto. congr.\n      - ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac.\n        + i. inv TID0. apply inj_pair2 in H1. subst. ss.\n          revert PROMISES0. erewrite Memory.remove_o; eauto. condtac; ss.\n          erewrite Memory.add_o; eauto. condtac; ss. i.\n          eapply FULFILLED. econs; eauto.\n        + i. eapply FULFILLED. econs; eauto.\n    }\n    { i. inv NP. econs; s.\n      - erewrite Memory.split_o; eauto. condtac; ss.\n        { des. subst. exploit Memory.split_get0; eauto. i. des. congr. }\n        condtac; ss. guardH o. des. subst.\n        exfalso. eapply FULFILLED. econs; eauto.\n        hexploit Memory.split_get0; try exact PROMISES; eauto. i. des. eauto.\n      - ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac.\n        + i. inv TID0. apply inj_pair2 in H1. subst. ss.\n          revert PROMISES0. erewrite Memory.remove_o; eauto. condtac; ss.\n          erewrite Memory.split_o; eauto. repeat condtac; ss.\n          * guardH o. guardH o0. i. des. inv PROMISES0.\n            eapply FULFILLED. econs; eauto.\n            hexploit Memory.split_get0; try exact PROMISES; eauto. i. des. eauto.\n          * i. eapply FULFILLED. econs; eauto.\n        + i. eapply FULFILLED. econs; eauto.\n    }\n    { i. inv NP. econs; s.\n      - erewrite Memory.lower_o; eauto. condtac; ss.\n        des. subst. exfalso. eapply FULFILLED. econs; eauto.\n        hexploit Memory.lower_get0; try exact PROMISES; eauto.\n      - ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac.\n        + i. inv TID0. apply inj_pair2 in H1. subst. ss.\n          revert PROMISES0. erewrite Memory.remove_o; eauto. condtac; ss.\n          erewrite Memory.lower_o; eauto. condtac; ss.\n          guardH o. guardH o0. i. des. inv PROMISES0.\n          eapply FULFILLED. econs; eauto.\n        + i. eapply FULFILLED. econs; eauto.\n    }\nQed.\n\nLemma writing_small_step_fulfilled_new\n      withprm tid e c1 c2 loc from to val released ord\n      (WF: Configuration.wf c1)\n      (STEP: small_step withprm tid e c1 c2)\n      (WRITING: ThreadEvent.is_writing e = Some (loc, from, to, val, released, ord)):\n  fulfilled c2 loc from to (Message.mk val released).\nProof.\n  inv STEP. guardH PFREE.\n  inv STEP0; inv STEP; ss. inv LOCAL; inv WRITING; ss.\n  - inv LOCAL0. inv WRITE. inv PROMISE.\n    { econs; s.\n      - erewrite Memory.add_o; eauto. condtac; ss. des; congr.\n      - ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac.\n        + i. inv TID0. apply inj_pair2 in H1. subst. ss.\n          revert PROMISES0. erewrite Memory.remove_o; eauto. condtac; ss.\n          des; congr.\n        + i. exploit Memory.add_get0; eauto. i.\n          inv WF. inv WF0. exploit THREADS; eauto. i. inv x.\n          apply PROMISES1 in PROMISES0. congr.\n    }\n    { econs; s.\n      - erewrite Memory.split_o; eauto. condtac; ss.\n        exfalso. clear -o. des; apply o; auto.\n      - ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac.\n        + i. inv TID0. apply inj_pair2 in H1. subst. ss.\n          revert PROMISES0. erewrite Memory.remove_o; eauto. condtac; ss.\n          des; congr.\n        + i. exploit Memory.split_get0; eauto. i. des.\n          inv WF. inv WF0. exploit THREADS; eauto. i. inv x.\n          apply PROMISES1 in PROMISES0. congr.\n    }\n    { econs; s.\n      - erewrite Memory.lower_o; eauto. condtac; ss. des; congr.\n      - ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac.\n        + i. inv TID0. apply inj_pair2 in H1. subst. ss.\n          revert PROMISES0. erewrite Memory.remove_o; eauto. condtac; ss.\n          des; congr.\n        + i. exploit Memory.lower_get0; eauto. i.\n          inv WF. inv WF0. exploit DISJOINT; eauto. i.\n          eapply Memory.disjoint_get; try apply x; eauto.\n          eapply Memory.lower_get0. eauto.\n    }\n  - inv LOCAL1. clear GET.\n    inv LOCAL2. inv WRITE. inv PROMISE.\n    { econs; s.\n      - erewrite Memory.add_o; eauto. condtac; ss. des; congr.\n      - ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac.\n        + i. inv TID0. apply inj_pair2 in H1. subst. ss.\n          revert PROMISES0. erewrite Memory.remove_o; eauto. condtac; ss.\n          des; congr.\n        + i. exploit Memory.add_get0; eauto. i.\n          inv WF. inv WF0. exploit THREADS; eauto. i. inv x.\n          apply PROMISES1 in PROMISES0. congr.\n    }\n    { econs; s.\n      - erewrite Memory.split_o; eauto. condtac; ss.\n        exfalso. clear -o. des; apply o; auto.\n      - ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac.\n        + i. inv TID0. apply inj_pair2 in H1. subst. ss.\n          revert PROMISES0. erewrite Memory.remove_o; eauto. condtac; ss.\n          des; congr.\n        + i. exploit Memory.split_get0; eauto. i. des.\n          inv WF. inv WF0. exploit THREADS; eauto. i. inv x.\n          apply PROMISES1 in PROMISES0. congr.\n    }\n    { econs; s.\n      - erewrite Memory.lower_o; eauto. condtac; ss. des; congr.\n      - ii. inv H. revert TID0. rewrite IdentMap.gsspec. condtac.\n        + i. inv TID0. apply inj_pair2 in H1. subst. ss.\n          revert PROMISES0. erewrite Memory.remove_o; eauto. condtac; ss.\n          des; congr.\n        + i. exploit Memory.lower_get0; eauto. i.\n          inv WF. inv WF0. exploit DISJOINT; eauto. i.\n          eapply Memory.disjoint_get; try apply x; eauto.\n          eapply Memory.lower_get0. eauto.\n    }\nQed.\n\nLemma writing_small_step_fulfilled_backward\n      withprm tid e c1 c2 loc from to val released ord\n      (WF: Configuration.wf c1)\n      (STEP: small_step withprm tid e c1 c2)\n      (WRITING: ThreadEvent.is_writing e = Some (loc, from, to, val, released, ord)):\n  forall l f t msg\n    (NP: fulfilled c2 l f t msg),\n    fulfilled c1 l f t msg \\/ (l, f, t, msg) = (loc, from, to, Message.mk val released).\nProof.\n  inv STEP. guardH PFREE.\n  inv STEP0; inv STEP; ss. inv LOCAL; inv WRITING; ss.\n  - inv LOCAL0. inv WRITE. inv PROMISE.\n    { i. inv NP. ss. revert GET. erewrite Memory.add_o; eauto. condtac; ss.\n      { i. des. inv GET. auto. }\n      { left. econs; eauto. ii. inv H.\n        destruct (Ident.eq_dec tid0 tid).\n        - subst. rewrite TID in TID0. inv TID0. apply inj_pair2 in H1. subst.\n          eapply FULFILLED. econs.\n          + rewrite IdentMap.gss. eauto.\n          + s. erewrite Memory.remove_o; eauto. condtac; ss.\n            erewrite Memory.add_o; eauto. condtac; [|eauto]. ss.\n        - eapply FULFILLED. econs; eauto.\n          rewrite IdentMap.gso; eauto.\n      }\n    }\n    { i. inv NP. ss. revert GET. erewrite Memory.split_o; eauto. condtac; ss.\n      { i. des. inv GET. auto. }\n      guardH o. condtac; ss.\n      { i. des. inv GET. exfalso. eapply FULFILLED. econs.\n        - rewrite IdentMap.gss. eauto.\n        - erewrite Memory.remove_o; eauto. condtac; ss.\n          erewrite Memory.split_o; eauto.\n          do 2 (condtac; try congr). eauto.\n      }\n      { left. econs; eauto. ii. inv H.\n        destruct (Ident.eq_dec tid0 tid).\n        - subst. rewrite TID in TID0. inv TID0. apply inj_pair2 in H1. subst.\n          eapply FULFILLED. econs.\n          + rewrite IdentMap.gss. eauto.\n          + s. erewrite Memory.remove_o; eauto. condtac; ss.\n            erewrite Memory.split_o; eauto. do 2 (condtac; try congr). eauto.\n        - eapply FULFILLED. econs; eauto.\n          rewrite IdentMap.gso; eauto.\n      }\n    }\n    { i. inv NP. ss. revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n      { i. des. inv GET. auto. }\n      { left. econs; eauto. ii. inv H.\n        destruct (Ident.eq_dec tid0 tid).\n        - subst. rewrite TID in TID0. inv TID0. apply inj_pair2 in H1. subst.\n          eapply FULFILLED. econs.\n          + rewrite IdentMap.gss. eauto.\n          + s. erewrite Memory.remove_o; eauto. condtac; ss.\n            erewrite Memory.lower_o; eauto. condtac; [|eauto]. ss.\n        - eapply FULFILLED. econs; eauto.\n          rewrite IdentMap.gso; eauto.\n      }\n    }\n  - inv LOCAL1. clear GET.\n    inv LOCAL2. inv WRITE. inv PROMISE.\n    { i. inv NP. ss. revert GET. erewrite Memory.add_o; eauto. condtac; ss.\n      { i. des. inv GET. auto. }\n      { left. econs; eauto. ii. inv H.\n        destruct (Ident.eq_dec tid0 tid).\n        - subst. rewrite TID in TID0. inv TID0. apply inj_pair2 in H1. subst.\n          eapply FULFILLED. econs.\n          + rewrite IdentMap.gss. eauto.\n          + s. erewrite Memory.remove_o; eauto. condtac; ss.\n            erewrite Memory.add_o; eauto. condtac; [|eauto]. ss.\n        - eapply FULFILLED. econs; eauto.\n          rewrite IdentMap.gso; eauto.\n      }\n    }\n    { i. inv NP. ss. revert GET. erewrite Memory.split_o; eauto. condtac; ss.\n      { i. des. inv GET. auto. }\n      guardH o. condtac; ss.\n      { i. des. inv GET. exfalso. eapply FULFILLED. econs.\n        - rewrite IdentMap.gss. eauto.\n        - erewrite Memory.remove_o; eauto. condtac; ss.\n          erewrite Memory.split_o; eauto.\n          do 2 (condtac; try congr). eauto.\n      }\n      { left. econs; eauto. ii. inv H.\n        destruct (Ident.eq_dec tid0 tid).\n        - subst. rewrite TID in TID0. inv TID0. apply inj_pair2 in H1. subst.\n          eapply FULFILLED. econs.\n          + rewrite IdentMap.gss. eauto.\n          + s. erewrite Memory.remove_o; eauto. condtac; ss.\n            erewrite Memory.split_o; eauto. do 2 (condtac; try congr). eauto.\n        - eapply FULFILLED. econs; eauto.\n          rewrite IdentMap.gso; eauto.\n      }\n    }\n    { i. inv NP. ss. revert GET. erewrite Memory.lower_o; eauto. condtac; ss.\n      { i. des. inv GET. auto. }\n      { left. econs; eauto. ii. inv H.\n        destruct (Ident.eq_dec tid0 tid).\n        - subst. rewrite TID in TID0. inv TID0. apply inj_pair2 in H1. subst.\n          eapply FULFILLED. econs.\n          + rewrite IdentMap.gss. eauto.\n          + s. erewrite Memory.remove_o; eauto. condtac; ss.\n            erewrite Memory.lower_o; eauto. condtac; [|eauto]. ss.\n        - eapply FULFILLED. econs; eauto.\n          rewrite IdentMap.gso; eauto.\n      }\n    }\nQed.\n\nLemma writing_small_step_fulfilled\n      withprm tid e c1 c2 loc from to val released ord\n      (WF: Configuration.wf c1)\n      (STEP: small_step withprm tid e c1 c2)\n      (WRITING: ThreadEvent.is_writing e = Some (loc, from, to, val, released, ord)):\n  forall l f t msg,\n    fulfilled c2 l f t msg <-> fulfilled c1 l f t msg \\/ (l, f, t, msg) = (loc, from, to, Message.mk val released).\nProof.\n  econs; i.\n  - eapply writing_small_step_fulfilled_backward; eauto.\n  - des.\n    + eapply writing_small_step_fulfilled_forward; eauto.\n    + inv H. eapply writing_small_step_fulfilled_new; eauto.\nQed.\n\nLemma nonwriting_small_step_fulfilled_forward\n      tid e c1 c2\n      (WF: Configuration.wf c1)\n      (STEP: small_step false tid e c1 c2)\n      (NONWRITING: ThreadEvent.is_writing e = None):\n  forall l f t msg\n    (NP: fulfilled c1 l f t msg),\n    fulfilled c2 l f t msg.\nProof.\n  inv STEP. guardH PFREE.\n  inv STEP0; inv STEP; inv LOCAL; inv NONWRITING.\n  - unguardH PFREE.\n    apply promise_pf_inv in PFREE. des. subst. inv PROMISE.\n    i. inv NP. econs; ss.\n    + erewrite Memory.lower_o; eauto. condtac; ss. des. subst.\n      exfalso. eapply FULFILLED. econs; eauto. eapply Memory.lower_get0. eauto.\n    + ii. inv H.\n      revert TID0. rewrite IdentMap.gsspec. condtac; ss; i.\n      * inv TID0. ss. eapply FULFILLED.\n        destruct msg0. hexploit Memory.op_get_inv; eauto.\n        { econs 3. eauto. }\n        i. des.\n        { subst. econs; eauto. eapply Memory.lower_get0. eauto. }\n        { econs; eauto. }\n      * eapply FULFILLED. econs; eauto.\n  - i. inv NP. econs; eauto. ii. inv H. ss.\n    revert TID0. rewrite IdentMap.gsspec. condtac; ss; i.\n    + inv TID0. eapply FULFILLED. econs; eauto.\n    + eapply FULFILLED. econs; eauto.\n  - inv LOCAL0.\n    i. inv NP. econs; eauto. ii. inv H. ss.\n    revert TID0. rewrite IdentMap.gsspec. condtac; ss; i.\n    + inv TID0. eapply FULFILLED. econs; eauto.\n    + eapply FULFILLED. econs; eauto.\n  - inv LOCAL0.\n    i. inv NP. econs; eauto. ii. inv H. ss.\n    revert TID0. rewrite IdentMap.gsspec. condtac; ss; i.\n    + inv TID0. eapply FULFILLED. econs; eauto.\n    + eapply FULFILLED. econs; eauto.\n  - inv LOCAL0.\n    i. inv NP. econs; eauto. ii. inv H. ss.\n    revert TID0. rewrite IdentMap.gsspec. condtac; ss; i.\n    + inv TID0. eapply FULFILLED. econs; eauto.\n    + eapply FULFILLED. econs; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-coq", "sha": "bff53239c51681ea653745cebf3b30ddd38f97ba", "save_path": "github-repos/coq/snu-sf-promising-coq", "path": "github-repos/coq/snu-sf-promising-coq/promising-coq-bff53239c51681ea653745cebf3b30ddd38f97ba/src/drf/Fulfilled.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.3557749003442964, "lm_q1q2_score": 0.24404359899676414}}
{"text": "Require Import UNIVERSE.\nRequire Import Smallstep.\nRequire Import CoqlibC.\nRequire Import ModSem.\nRequire Import LinkingC.\n\nRequire Import Syntax Sem Mod ModSem.\nRequire Import Sound.\nRequire Import SimSymb SimMem SimModSem.\n\nSet Implicit Arguments.\n\n\n\n\n\n\n\nModule ModPair.\n\nSection MODPAIR.\nContext `{SM: SimMem.class} {SS: SimSymb.class SM} {SU: Sound.class}.\n\n  Record t: Type := mk {\n    src: Mod.t;\n    tgt: Mod.t;\n    ss: SimSymb.t;\n  }.\n\n  Definition to_msp (skenv_link_src skenv_link_tgt: SkEnv.t) (sm: SimMem.t) (mp: t): ModSemPair.t :=\n    ModSemPair.mk (Mod.modsem (mp.(src)) skenv_link_src) (Mod.modsem (mp.(tgt)) skenv_link_tgt) mp.(ss) sm.\n\n  (* TODO: Actually, ModPair can have idx/ord and transfer it to ModSemPair. *)\n  (* Advantage: We can unify ord at Mod state. *)\n  Inductive sim (mp: t): Prop :=\n  | sim_intro\n      (SIMSK: SimSymb.wf mp.(ss))\n      (SKSRC: mp.(ss).(SimSymb.src) = (Mod.sk mp.(src)))\n      (SKTGT: mp.(ss).(SimSymb.tgt) = (Mod.sk mp.(tgt)))\n      (SIMMS: forall skenv_link_src skenv_link_tgt ss_link sm_init_link\n          (INCLSRC: SkEnv.includes skenv_link_src (Mod.sk mp.(src)))\n          (INCLTGT: SkEnv.includes skenv_link_tgt (Mod.sk mp.(tgt)))\n          (WFSRC: SkEnv.wf skenv_link_src)\n          (WFTGT: SkEnv.wf skenv_link_tgt)\n          (SSLE: SimSymb.le mp.(ss) ss_link)\n          (SIMSKENVLINK: SimSymb.sim_skenv sm_init_link ss_link skenv_link_src skenv_link_tgt),\n          <<SIMMSP: ModSemPair.sim (to_msp skenv_link_src skenv_link_tgt sm_init_link mp)>>).\n\n  (* Design: ModPair only has data, properties are stated in sim *)\n\nEnd MODPAIR.\nEnd ModPair.\n\nHint Unfold ModPair.to_msp.\n", "meta": {"author": "snu-sf", "repo": "CoreRUSC", "sha": "84dac2342e15f40e579cc48dc0add91e322069d9", "save_path": "github-repos/coq/snu-sf-CoreRUSC", "path": "github-repos/coq/snu-sf-CoreRUSC/CoreRUSC-84dac2342e15f40e579cc48dc0add91e322069d9/proof/SimMod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.24399446837471767}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import RunAux.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition complete_hvc_exit_spec (rec: Pointer) (adt: RData) : option RData :=\n    rely (peq (base rec) buffer_loc);\n    when gidx == (buffer (priv adt)) @ (offset rec);\n    let gn := (gs (share adt)) @ gidx in\n    rely (ref_accessible gn CPU_ID);\n    rely (g_tag (ginfo gn) =? GRANULE_STATE_REC);\n    let esr := g_esr (grec gn) in\n    rely is_int64 esr;\n    if (Z.land esr ESR_EL2_EC_MASK) =? ESR_EL2_EC_HVC then\n      rely is_int64 ((rec_run (priv adt)) @ 5); rely is_int64 ((rec_run (priv adt)) @ 6);\n      rely is_int64 ((rec_run (priv adt)) @ 7); rely is_int64 ((rec_run (priv adt)) @ 8);\n      rely is_int64 ((rec_run (priv adt)) @ 9); rely is_int64 ((rec_run (priv adt)) @ 10);\n      rely is_int64 ((rec_run (priv adt)) @ 11);\n      let g' := gn {grec: (grec gn) {g_regs: (g_regs (grec gn)) {r_x0: ((rec_run (priv adt)) @ 5)} {r_x1: (rec_run (priv adt)) @ 6}\n                                                                {r_x2: ((rec_run (priv adt)) @ 7)} {r_x3: (rec_run (priv adt)) @ 8}\n                                                                {r_x4: ((rec_run (priv adt)) @ 9)} {r_x5: (rec_run (priv adt)) @ 10}\n                                                                {r_x6: ((rec_run (priv adt)) @ 11)}} {g_esr: 0}} in\n      Some adt {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}\n    else Some adt.\n\nEnd Spec.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RunComplete/Specs/complete_hvc_exit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.24399446223014667}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n  Copyright 2018 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Export list_util1.\nRequire Export PBFTprops2.\nRequire Export List.\n\n\nSection PBFTprops3.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { pbft_context : PBFTcontext      }.\n  Context { pbft_auth    : PBFTauth         }.\n  Context { pbft_keys    : PBFTinitial_keys }.\n  Context { pbft_hash    : PBFThash         }.\n\n\n\n  Lemma request_data_and_rep_toks2prepare_as_pre_prepare2prepare :\n    forall pp d i keys,\n      request_data_and_rep_toks2prepare\n        (pre_prepare2request_data pp d)\n        (pre_prepare2rep_toks_of_prepare i keys pp d)\n      = pre_prepare2prepare i keys pp d.\n  Proof.\n    introv; auto.\n    destruct pp, b; simpl; auto.\n  Qed.\n  Hint Rewrite request_data_and_rep_toks2prepare_as_pre_prepare2prepare : pbft.\n\n  Lemma is_primary_PBFTprimary :\n    forall v, is_primary v (PBFTprimary v) = true.\n  Proof.\n    introv.\n    unfold is_primary; simpl; pbft_dest_all x.\n  Qed.\n  Hint Rewrite is_primary_PBFTprimary : pbft.\n\n  Lemma eq_request_data_same :\n    forall x, eq_request_data x x = true.\n  Proof.\n    introv; unfold eq_request_data; pbft_dest_all x.\n  Qed.\n  Hint Rewrite eq_request_data_same : pbft.\n\n  Hint Rewrite orb_false_r : bool.\n\n  Lemma find_rep_toks_in_list_none_iff :\n    forall i preps,\n      find_rep_toks_in_list i preps = None\n      <-> forall rt, In rt preps -> i <> rt_rep rt.\n  Proof.\n    induction preps; simpl; introv; split; intro h; tcsp; smash_pbft.\n\n    - introv j; repndors; subst; tcsp.\n      rewrite IHpreps in h.\n      apply h; auto.\n\n    - pose proof (h a) as q; autodimp q hyp; tcsp.\n\n    - apply IHpreps; exrepnd.\n      introv j; apply h; tcsp.\n  Qed.\n\n  Lemma own_prepare_is_already_in_entry_with_different_digest_false_and_same_request_data_implies_same_digest :\n    forall i s v d d' a entry,\n      own_prepare_is_already_in_entry_with_different_digest i s v d entry = None\n      -> log_entry_request_data entry = request_data v s d'\n      -> In (MkRepToks i a) (log_entry_prepares entry)\n      -> d = d'.\n  Proof.\n    introv h q k.\n    unfold own_prepare_is_already_in_entry_with_different_digest in h.\n    smash_pbft.\n\n    { rewrite q; simpl; auto. }\n\n    { allrw find_rep_toks_in_list_none_iff.\n      discover; simpl in *; tcsp. }\n\n    { match goal with\n      | [ H : _ <> _ |- _ ] => destruct H; rewrite q; simpl; auto\n      end. }\n\n    { match goal with\n      | [ H : _ <> _ |- _ ] => destruct H; rewrite q; simpl; auto\n      end. }\n  Qed.\n\n  Lemma own_prepare_is_already_logged_with_different_digest_false_and_prepare_in_log_implies_same_digest :\n    forall L i s v d d' a,\n      own_prepare_is_already_logged_with_different_digest i s v d L = None\n      -> prepare_in_log (mk_prepare v s d' i a) L = true\n      -> d = d'.\n  Proof.\n    induction L; introv h w; simpl in *; pbft_simplifier.\n    smash_pbft.\n\n    allrw is_prepare_for_entry_true_iff; simpl in *.\n    allrw existsb_exists; exrepnd.\n    allrw same_rep_tok_true_iff; subst.\n\n    rename_hyp_with own_prepare_is_already_in_entry_with_different_digest own.\n    eapply own_prepare_is_already_in_entry_with_different_digest_false_and_same_request_data_implies_same_digest in own; eauto.\n  Qed.\n\n  Lemma mk_prepare_eq_pre_prepare2prepare_implies_eq :\n    forall v n d1 i1 a i2 keys pp d2,\n      mk_prepare v n d1 i1 a = pre_prepare2prepare i2 keys pp d2\n      -> i1 = i2 /\\ d1 = d2.\n  Proof.\n    introv h.\n    destruct pp, b; simpl in *.\n    unfold pre_prepare2prepare, mk_prepare in *; ginv; tcsp.\n  Qed.\n\n  Lemma mk_prepare_eq_pre_prepare2prepare_implies_eq_seq :\n    forall v n d1 i1 a i2 keys pp d2,\n      mk_prepare v n d1 i1 a = pre_prepare2prepare i2 keys pp d2\n      -> pre_prepare2seq pp = n.\n  Proof.\n    introv h.\n    destruct pp, b; simpl in *.\n    unfold pre_prepare2prepare, mk_prepare in *; ginv; tcsp.\n  Qed.\n\n  Lemma correct_new_view_implies_norepeatsb :\n    forall nv,\n      correct_new_view nv = true\n      -> norepeatsb\n           SeqNumDeq\n           (map pre_prepare2seq (new_view2oprep nv ++ new_view2nprep nv)) = true.\n  Proof.\n    introv cor; unfold correct_new_view in cor; smash_pbft.\n  Qed.\n\n  Lemma norepeatsb_and_in_map_digest_same_seq_implies_eq :\n    forall pp1 d1 pp2 d2 L,\n      norepeatsb SeqNumDeq (map pre_prepare2seq L) = true\n      -> In (pp1, d1) (map add_digest L)\n      -> In (pp2, d2) (map add_digest L)\n      -> pre_prepare2seq pp1 = pre_prepare2seq pp2\n      -> pp1 = pp2 /\\ d1 = d2.\n  Proof.\n    induction L; introv norep i1 i2 e; simpl in *; tcsp.\n    smash_pbft.\n    repndors; tcsp.\n\n    - rewrite i1 in i2; ginv.\n\n    - clear IHL.\n      match goal with\n      | [ H : ~ _ |- _ ] => destruct H\n      end.\n      unfold add_digest in i2; ginv.\n      apply in_map_iff in i1; exrepnd.\n      unfold add_digest in i1; ginv.\n      allrw <-.\n      apply in_map_iff; eexists; eauto.\n\n    - clear IHL.\n      match goal with\n      | [ H : ~ _ |- _ ] => destruct H\n      end.\n      unfold add_digest in i1; ginv.\n      apply in_map_iff in i2; exrepnd.\n      unfold add_digest in i1; ginv.\n      allrw <-.\n      apply in_map_iff; eexists; eauto.\n  Qed.\n\n  Lemma eq_primary_implies_eq_primary :\n    forall v i,\n      i = PBFTprimary v\n      -> is_primary v i = true.\n  Proof.\n    introv h.\n    subst; autorewrite with pbft; auto.\n  Qed.\n  Hint Resolve eq_primary_implies_eq_primary : pbft.\n\n  Lemma nat_seq_num:\n    forall (n : nat) (s : SeqNum),\n      n = s -> seq_num n = seq_num s.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Resolve nat_seq_num : pbft.\n\n  Lemma in_map_seq_num:\n    forall (n A B : SeqNum),\n      In n (map seq_num (seq A B))\n      -> A <= n <= (A + B).\n  Proof.\n    introv H.\n     apply in_map_iff in H.\n    exrepnd.\n    apply in_seq in H0.\n    rewrite <- H1.\n    smash_pbft. omega.\n  Qed.\n  Hint Resolve in_map_seq_num : pbft.\n\n\n  Lemma in_map_seq_num_natAB:\n    forall n A B,\n      In n (map seq_num (seq A B))\n      -> A <= n <= (A + B).\n  Proof.\n    introv H.\n    apply in_map_iff in H.\n    exrepnd.\n    apply in_seq in H0.\n    rewrite <- H1.\n    smash_pbft. omega.\n  Qed.\n  Hint Resolve in_map_seq_num_natAB : pbft.\n\n  Lemma max_seq_num_left :\n    forall (n n1 n2 : SeqNum), n <= n1 -> n <= max_seq_num n1 n2.\n  Proof.\n    introv h; destruct n, n1, n2; unfold max_seq_num; simpl in *; smash_pbft.\n    allrw SeqNumLe_true; auto; simpl in *; omega.\n  Qed.\n  Hint Resolve max_seq_num_left : pbft.\n\n  Lemma max_seq_num_right :\n    forall (n n1 n2 : SeqNum), n <= n2 -> n <= max_seq_num n1 n2.\n  Proof.\n    introv h; destruct n1, n2; unfold max_seq_num; simpl in *; smash_pbft.\n    allrw SeqNumLe_false; simpl in *; omega.\n  Qed.\n  Hint Resolve max_seq_num_right : pbft.\n\n  Lemma in_from_min_to_max_op_implies :\n    forall n minop maxop,\n      In n (from_min_to_max_op minop maxop)\n      ->\n      exists min max,\n        minop = Some min\n        /\\ maxop = Some max\n        /\\ min <= max\n        /\\ min < n\n        /\\ n <= max.\n  Proof.\n    introv h; unfold from_min_to_max_op, from_min_to_max in h;\n      smash_pbft; repndors; subst; tcsp.\n\n    apply in_map_iff in h; exrepnd; subst.\n    apply in_seq in h0.\n    rewrite plus_Sn_m in h0; rewrite le_plus_minus_r in h0; smash_pbft.\n    eexists; eexists; dands; eauto; try omega.\n  Qed.\n\n  Lemma vce_view_changes_replace_own_view_change_in_entry :\n    forall vc e,\n      vce_view_changes (replace_own_view_change_in_entry vc e)\n      = vce_view_changes e.\n  Proof.\n    destruct e; simpl; auto.\n  Qed.\n  Hint Rewrite vce_view_changes_replace_own_view_change_in_entry : pbft.\n\n  Lemma view_changed_entry_some_implies_eq_vce_view_changes :\n    forall state entry vc entry',\n      view_changed_entry state entry = Some (vc, entry')\n      -> vce_view_changes entry' = vce_view_changes entry.\n  Proof.\n    introv h; unfold view_changed_entry in h; smash_pbft.\n  Qed.\n\n  Lemma view_changed_entry_some_implies_cons :\n    forall state entry vc entry',\n      view_changed_entry state entry = Some (vc, entry')\n      -> view_change_entry2view_changes entry' = vc :: vce_view_changes entry.\n  Proof.\n    introv h; unfold view_changed_entry in h; smash_pbft.\n    unfold view_change_entry2view_changes.\n    destruct entry; simpl in *.\n    destruct vce_view_change; simpl in *; ginv.\n  Qed.\n\n  Fixpoint max_seq_nums (L : list SeqNum) : SeqNum :=\n    match L with\n    | [] => seq_num 0\n    | s :: sn => max_seq_num s (max_seq_nums sn)\n    end.\n\n  Fixpoint ordered {T} (R : T -> T -> bool) (L : list T) : Prop :=\n    match L with\n    | [] => True\n    | x :: xs =>\n      (forall a, In a xs -> R x a = true)\n      /\\ ordered R xs\n    end.\n\n  Lemma max_seq_num_assoc :\n    forall (a b c : SeqNum),\n      max_seq_num a (max_seq_num b c) = max_seq_num (max_seq_num a b) c.\n  Proof.\n    introv; destruct a, b, c; unfold max_seq_num; smash_pbft;\n      allrw SeqNumLe_true;\n      allrw SeqNumLe_false; simpl in *; omega.\n  Qed.\n\n  Lemma max_seq_num_eq_right :\n    forall (a b : SeqNum),\n      a < b\n      -> max_seq_num a b = b.\n  Proof.\n    introv h; destruct a, b; unfold max_seq_num; smash_pbft.\n    allrw SeqNumLe_false; simpl in *; omega.\n  Qed.\n\n  Lemma max_seq_num_eq_left :\n    forall (a b : SeqNum),\n      b <= a\n      -> max_seq_num a b = a.\n  Proof.\n    introv h; destruct a, b; unfold max_seq_num; smash_pbft.\n    allrw SeqNumLe_true; simpl in *.\n    assert (n = n0) as xx by omega; subst; auto.\n  Qed.\n\n  Lemma max_seq_num_0_right :\n    forall (a : SeqNum),\n      max_seq_num a 0 = a.\n  Proof.\n    introv; pose proof (max_seq_num_eq_left a (seq_num 0)) as h.\n    apply h; destruct a; simpl in *; omega.\n  Qed.\n  Hint Rewrite max_seq_num_0_right : pbft.\n\n  Lemma max_seq_nums_right_if_lt :\n    forall K a,\n      (forall x : SeqNum, In x K -> SeqNumLt a x = true)\n      -> K <> []\n      -> max_seq_num a (max_seq_nums K) = max_seq_nums K.\n  Proof.\n    destruct K; introv h w; simpl in *; autorewrite with pbft in *; tcsp.\n    pose proof (h s) as q; autodimp q hyp.\n    allrw SeqNumLt_true.\n    rewrite max_seq_num_assoc.\n    rewrite (max_seq_num_eq_right a s); auto.\n  Qed.\n\n  Lemma nullb_false_iff :\n    forall {T} (L : list T),\n      nullb L = false <-> L <> [].\n  Proof.\n    introv; destruct L; simpl; split; intro q; tcsp.\n  Qed.\n\n  Lemma implies_eq_seq_nums :\n    forall (s1 s2 : SeqNum), seqnum2nat s1 = seqnum2nat s2 -> s1 = s2.\n  Proof.\n    introv; destruct s1, s2; simpl in *; tcsp.\n  Qed.\n\n  Lemma max_seq_num_diff_left_implies_gt :\n    forall (a b : SeqNum),\n      max_seq_num a b <> a -> a < b.\n  Proof.\n    introv h; unfold max_seq_num in *; smash_pbft.\n    allrw SeqNumLe_true; simpl in *.\n    destruct a as [n], b as [m]; simpl in *.\n    assert (n <> m); try omega.\n    intro xx; subst; tcsp.\n  Qed.\n\n  Lemma diff_nat_implies_diff_seq_num :\n    forall (a b : SeqNum),\n      seqnum2nat a <> seqnum2nat b -> a <> b.\n  Proof.\n    introv h; destruct a, b; simpl in *; intro xx; subst; destruct h; tcsp.\n    inversion xx; auto.\n  Qed.\n\n(*  Lemma exists_find_pre_prepare_certificate_in_prepared_infos :\n    forall vc n,\n      view_change2max_seq_preps vc = Some n\n      ->\n      exists ppi,\n        find_pre_prepare_certificate_in_prepared_infos\n          (view_change2max_seq_preps vc) (view_change2prep vc) = Some ppi.\n  Proof.\n    introv n0.\n    destruct vc, v; simpl.\n    unfold view_change2max_seq in *; simpl in *.\n    unfold view_change2prep in *; simpl in *.\n    induction P; simpl in *; tcsp.\n    smash_pbft.\n\n    match goal with\n    | [ H : _ <> _ |- _ ] =>\n      apply max_seq_num_diff_left_implies_gt in H\n    end.\n    autodimp IHP hyp.\n    { apply diff_nat_implies_diff_seq_num; simpl; omega. }\n\n    rewrite max_seq_num_eq_right; auto.\n  Qed.*)\n\n  Lemma create_new_prepare_message_implies_same_sequence_number :\n    forall n v keys cert b p d,\n      create_new_prepare_message n v keys cert = (b,(p,d))\n      -> pre_prepare2seq p = n.\n  Proof.\n    introv create.\n    unfold create_new_prepare_message in create; smash_pbft.\n  Qed.\n\n  Lemma create_new_prepare_message_implies_same_view :\n    forall n v keys cert b p d,\n      create_new_prepare_message n v keys cert = (b,(p,d))\n      -> pre_prepare2view p = v.\n  Proof.\n    introv create.\n    unfold create_new_prepare_message in create; smash_pbft.\n  Qed.\n\n  Lemma create_new_prepare_message_implies_auth :\n    forall n v keys cert b p d,\n      create_new_prepare_message n v keys cert = (b,(p,d))\n      -> pre_prepare2auth p = authenticate (PBFTmsg_bare_pre_prepare (pre_prepare2bare p)) keys.\n  Proof.\n    introv create.\n    unfold create_new_prepare_message in create; smash_pbft.\n  Qed.\n\n  Lemma eqset_cons_lr :\n    forall {A} (a : A) l1 l2,\n      eqset l1 l2\n      -> eqset (a :: l1) (a :: l2).\n  Proof.\n    introv eqs; introv; split; intro h; simpl in *; repndors; tcsp; right;\n      apply eqs; auto.\n  Qed.\n\n  Lemma eqset_cons_middle :\n    forall {A} (a : A) l1 l2,\n      eqset (l1 ++ a :: l2) (a :: l1 ++ l2).\n  Proof.\n    repeat introv; split; intro h; simpl in *; allrw in_app_iff; simpl in *; tcsp.\n  Qed.\n\n  Lemma implies_norepeatsb_middle :\n    forall {A} (deq : Deq A) (a : A) l1 l2,\n      norepeatsb deq (a :: l1 ++ l2) = true\n      -> norepeatsb deq (l1 ++ a :: l2) = true.\n  Proof.\n    induction l1; introv norep; simpl in *; smash_pbft.\n\n    - allrw in_app_iff; simpl in *.\n      repeat match goal with\n             | [ H : ~ (_ \\/ _) |- _ ] => apply not_or in H; repnd\n             end.\n      repndors; tcsp.\n\n    - allrw in_app_iff; simpl in *.\n      repeat match goal with\n             | [ H : ~ (_ \\/ _) |- _ ] => apply not_or in H; repnd\n             end.\n      repndors; tcsp.\n      apply IHl1; smash_pbft.\n      allrw in_app_iff; tcsp.\n  Qed.\n\n  Lemma create_new_prepare_messages_implies_eqset_and_norepeatsb :\n    forall sns v keys cert OP NP,\n      norepeatsb SeqNumDeq sns = true\n      -> create_new_prepare_messages sns v keys cert = (OP, NP)\n      -> eqset sns (map pre_prepare2seq (map fst OP ++ map fst NP))\n         /\\ norepeatsb SeqNumDeq (map pre_prepare2seq (map fst OP ++ map fst NP)) = true.\n  Proof.\n    induction sns; introv norep create; simpl in *; smash_pbft; repnd; simpl in *.\n\n    - assert False; tcsp.\n\n      match goal with\n      | [ H : create_new_prepare_messages _ _ _ _ = _ |- _ ] =>\n        eapply IHsns in H; auto;[]; repnd\n      end.\n\n      match goal with\n      | [ H : create_new_prepare_message _ _ _ _ = _ |- _ ] =>\n        apply create_new_prepare_message_implies_same_sequence_number in H;\n          rewrite H in *\n      end.\n\n      match goal with\n      | [ H1 : In _ ?x, H2 : eqset _ ?x |- _ ] => apply H2 in H1; tcsp\n      end.\n\n    - match goal with\n      | [ H : create_new_prepare_messages _ _ _ _ = _ |- _ ] =>\n        eapply IHsns in H; auto;[]; repnd\n      end.\n\n      match goal with\n      | [ H : create_new_prepare_message _ _ _ _ = _ |- _ ] =>\n        dup H as create;\n          apply create_new_prepare_message_implies_same_sequence_number in create;\n          rewrite create in *\n      end.\n\n      dands; tcsp.\n      apply eqset_cons_lr; auto.\n\n    - match goal with\n      | [ H : create_new_prepare_messages _ _ _ _ = _ |- _ ] =>\n        eapply IHsns in H; auto;[]; repnd\n      end.\n\n      match goal with\n      | [ H : create_new_prepare_message _ _ _ _ = _ |- _ ] =>\n        dup H as create;\n          apply create_new_prepare_message_implies_same_sequence_number in create\n      end.\n\n      allrw map_app; simpl in *.\n\n      rewrite create.\n      dands.\n\n      + eapply eqset_trans;[apply eqset_cons_lr;eauto|].\n        apply eqset_sym; apply eqset_cons_middle.\n\n      + apply implies_norepeatsb_middle; auto.\n        simpl; smash_pbft.\n\n        match goal with\n        | [ H1 : In _ ?x, H2 : eqset _ ?x |- _ ] => apply H2 in H1; tcsp\n        end.\n  Qed.\n\n  Lemma create_new_prepare_messages_implies_norepeatsb :\n    forall sns v keys cert OP NP,\n      norepeatsb SeqNumDeq sns = true\n      -> create_new_prepare_messages sns v keys cert = (OP, NP)\n      -> norepeatsb SeqNumDeq (map pre_prepare2seq (map fst OP ++ map fst NP)) = true.\n  Proof.\n    introv norep create.\n    eapply create_new_prepare_messages_implies_eqset_and_norepeatsb in create; eauto; tcsp.\n  Qed.\n  Hint Resolve create_new_prepare_messages_implies_norepeatsb : pbft.\n\n  Lemma implies_norepeatsb_map_seq_num :\n    forall l,\n      norepeatsb deq_nat l = true\n      -> norepeatsb SeqNumDeq (map seq_num l) = true.\n  Proof.\n    induction l; introv norep; simpl in *; smash_pbft.\n    apply in_map_iff in i; exrepnd; subst.\n    inversion i1; simpl in *; subst; GC; tcsp.\n  Qed.\n  Hint Resolve implies_norepeatsb_map_seq_num : pbft.\n\n  Lemma norepeatsb_seq :\n    forall len pos,\n      norepeatsb deq_nat (seq pos len) = true.\n  Proof.\n    induction len; introv; simpl in *; smash_pbft.\n    apply in_seq in i; omega.\n  Qed.\n  Hint Resolve norepeatsb_seq : pbft.\n\n  Lemma norepeatsb_from_min_to_max :\n    forall a b, norepeatsb SeqNumDeq (from_min_to_max a b) = true.\n  Proof.\n    introv; unfold from_min_to_max; smash_pbft; simpl in *.\n  Qed.\n  Hint Resolve norepeatsb_from_min_to_max : pbft.\n\n  Lemma norepeatsb_from_min_to_max_op :\n    forall a b, norepeatsb SeqNumDeq (from_min_to_max_op a b) = true.\n  Proof.\n    introv; unfold from_min_to_max_op; smash_pbft.\n  Qed.\n  Hint Resolve norepeatsb_from_min_to_max_op : pbft.\n\n  Lemma norepeatsb_from_min_to_max_of_view_changes :\n    forall entry,\n      norepeatsb SeqNumDeq (from_min_to_max_of_view_changes entry) = true.\n  Proof.\n    introv; unfold from_min_to_max_of_view_changes, from_min_to_max_of_view_changes_cert; smash_pbft.\n  Qed.\n  Hint Resolve norepeatsb_from_min_to_max_of_view_changes : pbft.\n\n  Lemma pre_prepare2seq_mk_auth_pre_prepare :\n    forall v sn rs keys,\n      pre_prepare2seq (mk_auth_pre_prepare v sn rs keys) = sn.\n  Proof.\n    sp.\n  Qed.\n  Hint Rewrite pre_prepare2seq_mk_auth_pre_prepare : pbft.\n\n  Lemma implies_le_max_seq_nums :\n    forall (n : SeqNum) (L : list SeqNum),\n      In n L\n      -> n <= max_seq_nums L.\n  Proof.\n    induction L; introv i; simpl in *; tcsp.\n    repndors; subst; simpl in *; tcsp; eauto 2 with pbft.\n    autodimp IHL hyp.\n    eauto 2 with pbft.\n  Qed.\n\n  (*Lemma implies_create_new_prepare_message_cons_true :\n    forall n v keys c C ppd,\n      create_new_prepare_message n v keys C = (true, ppd)\n      -> exists ppd1, create_new_prepare_message n v keys (c :: C) = (true, ppd1).\n  Proof.\n    introv h.\n    unfold create_new_prepare_message in *; simpl in *.\n    unfold find_request_info_in_view_change_cert in *; simpl in *.\n    smash_pbft.\n  Qed.\n  Hint Resolve implies_create_new_prepare_message_cons_true : pbft.*)\n\n(*  Lemma PreparedInfos2max_seq_implies_find_pre_prepare_certificate_in_prepared_infos_some :\n    forall L n,\n      PreparedInfos2max_seq L = Some n\n      -> exists x, find_pre_prepare_certificate_in_prepared_infos n L = Some x.\n  Proof.\n    induction L; introv h; simpl in *; smash_pbft.\n  Qed.*)\n\n(*  Lemma view_change2max_seq_preps_some_implies_create_new_prepare_message_true :\n    forall vc n v keys C,\n      view_change2max_seq_preps vc = Some n\n      -> exists ppd, create_new_prepare_message n v keys (vc :: C) = (true, ppd).\n  Proof.\n    introv h; unfold view_change2max_seq_preps in h.\n    unfold create_new_prepare_message; simpl.\n    unfold find_request_info_in_view_change_cert; simpl.\n    smash_pbft.\n    assert False; tcsp.\n  Qed.*)\n\n  Lemma PreparedInfos2max_seq_some_implies_ex :\n    forall F L n,\n      PreparedInfos2max_seq F L = Some n\n      -> exists p, In p L /\\ n = prepared_info2seq p /\\ F p = true.\n  Proof.\n    induction L; introv h; simpl in *; ginv.\n    remember (PreparedInfos2max_seq F L) as m; symmetry in Heqm; destruct m.\n\n    - pose proof (IHL s) as q; autodimp q hyp; clear IHL; exrepnd; simpl in *.\n      unfold max_seq_num in *; smash_pbft; allrw SeqNumLe_true; allrw SeqNumLe_false.\n\n      + exists p; dands; tcsp.\n\n      + exists a; dands; tcsp.\n\n      + exists p; dands; tcsp.\n\n    - clear IHL; simpl in *; smash_pbft.\n      exists a; dands; tcsp.\n  Qed.\n\n  Lemma view_change_cert2max_seq_preps_some_implies :\n    forall F C n vc,\n      view_change_cert2max_seq_preps_vc F C = Some (n,vc)\n      -> In vc C\n         /\\\n         exists p,\n           In p (view_change2prep vc)\n           /\\ n = prepared_info2seq p\n           /\\ F p = true.\n  Proof.\n    induction C; introv h; simpl in *; ginv; simpl in *; tcsp.\n    smash_pbft; allrw SeqNumLt_true; allrw SeqNumLt_false.\n\n    - pose proof (IHC n vc) as q; autodimp q hyp; clear IHC; repnd; tcsp.\n\n    - dands; tcsp.\n      apply PreparedInfos2max_seq_some_implies_ex; auto.\n\n    - dands; tcsp.\n      apply PreparedInfos2max_seq_some_implies_ex; auto.\n\n    - pose proof (IHC x0 x) as q; clear IHC; autodimp q hyp; dands; tcsp.\n  Qed.\n\n  (*Lemma implies_pre_prepare_certificate_in_prepared_infos_some :\n    forall p L,\n      In p L\n      ->\n      exists x,\n        find_pre_prepare_certificate_in_prepared_infos (prepared_info2seq p) L = Some x.\n  Proof.\n    induction L; introv i; simpl in *; tcsp.\n    repndors; subst; smash_pbft.\n  Qed.*)\n\n(*  Lemma implies_in_view_change2prep_implies_create_new_prepare_message_true :\n    forall vc p v keys C,\n      In vc C\n      -> In p (view_change2prep vc)\n      -> exists ppd, create_new_prepare_message (prepared_info2seq p) v keys C = (true, ppd).\n  Proof.\n    induction C; introv i j; simpl in *; tcsp.\n    repndors; subst; tcsp.\n\n    - unfold create_new_prepare_message; simpl.\n      unfold find_request_info_in_view_change_cert; simpl.\n      smash_pbft.\n\n      apply implies_pre_prepare_certificate_in_prepared_infos_some in j; exrepnd.\n      allrw j0; ginv.\n\n    - repeat (autodimp IHC hyp); exrepnd.\n      unfold create_new_prepare_message in *; simpl in *.\n      unfold find_request_info_in_view_change_cert in *; simpl in *.\n      smash_pbft.\n  Qed.*)\n\n(*  Lemma view_change_cert2max_seq_preps_vc_implies_exists_or_zero :\n    forall v keys C n vc,\n      view_change_cert2max_seq_preps_vc C = Some (n,vc)\n      -> exists ppd, create_new_prepare_message n v keys C = (true, ppd).\n  Proof.\n    introv cert.\n    apply view_change_cert2max_seq_preps_some_implies in cert.\n    exrepnd.\n    subst.\n    eapply implies_in_view_change2prep_implies_create_new_prepare_message_true; eauto.\n  Qed.*)\n\n(*  Lemma view_change_cert2max_seq_preps_implies_exists_or_zero :\n    forall v keys C n,\n      view_change_cert2max_seq_preps C = Some n\n      -> exists ppd, create_new_prepare_message n v keys C = (true, ppd).\n  Proof.\n    introv cert.\n    unfold view_change_cert2max_seq_preps in cert; smash_pbft.\n    eapply view_change_cert2max_seq_preps_vc_implies_exists_or_zero; eauto.\n  Qed.*)\n\n(*  Lemma view_change_cert2max_seq_preps_and_create_new_prepare_messages_implies_le :\n    forall K sn v keys C OP NP,\n      view_change_cert2max_seq_preps C = Some sn\n      -> create_new_prepare_messages K v keys C = (OP, NP)\n      -> ordered SeqNumLt K\n      -> sn = max_seq_nums K\n      -> K <> []\n      -> sn <= max_O OP.\n  Proof.\n    induction K; introv h q ord w knn; simpl in *; ginv.\n    smash_pbft; repnd.\n\n    - remember (nullb K) as b; symmetry in Heqb.\n      destruct b.\n\n      + rewrite nullb_true_iff in Heqb; subst; simpl in *; ginv; simpl in *; GC.\n        clear ord knn.\n        autorewrite with pbft in *.\n\n        match goal with\n        | [ H : create_new_prepare_message _ _ _ _ = _ |- _ ] =>\n          apply create_new_prepare_message_implies in H; exrepnd; subst; simpl; auto\n        end.\n\n      + apply nullb_false_iff in Heqb.\n        eapply IHK in h;[|eauto| | |]; auto; eauto 2 with pbft.\n        apply max_seq_nums_right_if_lt; auto.\n\n    - remember (nullb K) as b; symmetry in Heqb.\n      destruct b.\n\n      + rewrite nullb_true_iff in Heqb; subst; simpl in *; ginv; simpl in *; GC.\n        clear ord knn.\n        autorewrite with pbft in *.\n\n        apply (view_change_cert2max_seq_preps_implies_exists_or_zero v keys) in h.\n        repndors; subst; tcsp;[].\n        exrepnd.\n        rewrite h0 in *; ginv.\n\n      + apply nullb_false_iff in Heqb.\n        eapply IHK in h;[|eauto| | |]; auto; eauto 2 with pbft.\n        apply max_seq_nums_right_if_lt; auto.\n  Qed.*)\n\n(*  Lemma pre_prepares2max_seq_OP_of_create_new_prepare_messages :\n    forall L v keys C sn ovc OP NP,\n      view_change_cert2max_seq C = (sn, ovc)\n      -> sn = max_seq_nums L\n      -> ordered SeqNumLt L\n      -> L <> []\n      -> create_new_prepare_messages L v keys C = (OP, NP)\n      -> forall n, In n L -> n <= pre_prepares2max_seq (map fst OP).\n  Proof.\n    introv vmax eqsn ord diff create i.\n    eapply view_change_cert2max_seq_and_create_new_prepare_messages_implies_le in create;\n      [|eauto|eauto| |]; auto.\n    rewrite <- max_O_as_pre_prepares2max_seq.\n    eapply le_trans;[|eauto].\n    subst.\n    apply implies_le_max_seq_nums; auto.\n  Qed.*)\n\n  Lemma implies_ordered_map_seq_num :\n    forall (L : list nat),\n      ordered Nat.ltb L\n      -> ordered SeqNumLt (map seq_num L).\n  Proof.\n    induction L; simpl in *; introv h; auto.\n    repnd.\n    dands; auto.\n    introv i.\n    apply in_map_iff in i; exrepnd; subst.\n    apply SeqNumLt_true.\n    apply h0 in i0; pbft_simplifier; auto.\n  Qed.\n\n  Lemma ordered_seq :\n    forall (len n : nat),\n      ordered Nat.ltb (seq n len).\n  Proof.\n    induction len; simpl; auto.\n    introv; dands; auto.\n    introv i.\n    apply Nat.ltb_lt; auto.\n    apply in_seq in i; tcsp.\n  Qed.\n  Hint Resolve ordered_seq : num.\n\n(*  Lemma le_seq_num_implies_from_min_to_max_not_null :\n    forall (sn1 sn2 : SeqNum),\n      sn1 < sn2\n      -> from_min_to_max sn1 sn2 <> [].\n  Proof.\n    introv d.\n    unfold from_min_to_max; smash_pbft; try omega; tcsp.\n\n  Qed.\n  Hint Resolve le_seq_num_implies_from_min_to_max_not_null : pbft.*)\n\n  Lemma in_list_implies_diff_nil :\n    forall {A} (l : list A) a,\n      In a l -> l <> [].\n  Proof.\n    introv i; destruct l; simpl in *; tcsp.\n  Qed.\n  Hint Resolve in_list_implies_diff_nil : pbft.\n\n  Lemma ordered_from_min_to_max :\n    forall (sn1 sn2 : SeqNum),\n      ordered SeqNumLt (from_min_to_max sn1 sn2).\n  Proof.\n    introv; unfold from_min_to_max; smash_pbft.\n    apply implies_ordered_map_seq_num; eauto 3 with num.\n  Qed.\n  Hint Resolve ordered_from_min_to_max : pbft.\n\n  Lemma ordered_from_min_to_max_op :\n    forall (sn1 sn2 : option SeqNum),\n      ordered SeqNumLt (from_min_to_max_op sn1 sn2).\n  Proof.\n    introv; unfold from_min_to_max_op; smash_pbft.\n  Qed.\n  Hint Resolve ordered_from_min_to_max_op : pbft.\n\n  Lemma max_seq_nums_map_seq_num_seq :\n    forall (len n : nat),\n      0 < len\n      -> max_seq_nums (map seq_num (seq (S n) len)) = len + n.\n  Proof.\n    induction len; introv h; simpl; autorewrite with pbft; auto; try omega.\n    simpl in *.\n    destruct (lt_dec 0 len) as [d|d].\n    { rewrite IHlen; auto.\n      rewrite max_seq_num_eq_right; auto; simpl; try omega. }\n    { assert (len = 0) by omega; subst; simpl in *; autorewrite with pbft; auto. }\n  Qed.\n\n  Lemma max_seq_nums_from_min_to_max :\n    forall (sn1 sn2 : SeqNum),\n      sn1 < sn2\n      -> max_seq_nums (from_min_to_max sn1 sn2) = sn2.\n  Proof.\n    Opaque seq.\n    introv h; unfold from_min_to_max; smash_pbft; try omega.\n    rewrite max_seq_nums_map_seq_num_seq; simpl in *; try omega.\n    rewrite Nat.sub_add; simpl; auto.\n    destruct sn2; simpl; auto.\n  Qed.\n\n  Lemma in_from_min_to_max_implies_lt :\n    forall n (min max : SeqNum),\n      In n (from_min_to_max min max)\n      -> min < max.\n  Proof.\n    introv i; unfold from_min_to_max in i; smash_pbft.\n    apply in_map_iff in i; exrepnd; subst.\n    apply in_seq in i0.\n    omega.\n  Qed.\n  Hint Resolve in_from_min_to_max_implies_lt : pbft.\n\n(*  Lemma view_changed_entry_some_and_check_broadcast_new_view_implies_le :\n    forall n entry vc i keys nv opreps npreps,\n      In n (from_min_to_max_of_view_changes entry)\n      -> view_changed_entry (vce_view entry) entry = Some vc\n      -> check_broadcast_new_view i keys entry = Some (nv, opreps, npreps)\n      -> n <= max_O opreps.\n  Proof.\n    introv k vce c.\n    unfold check_broadcast_new_view in c; smash_pbft.\n    unfold from_min_to_max_of_view_changes in *; smash_pbft.\n\n    applydup in_from_min_to_max_op_implies in k; exrepnd.\n    eapply le_trans;[eauto|].\n\n    match goal with\n    | [ H : view_changed_entry _ _ = _ |- _ ] =>\n      applydup view_changed_entry_some_implies_cons in H as eqvcs;\n        rewrite eqvcs in *\n    end.\n\n    match goal with\n    | [ H : context[vce_view_changes ?e] |- _ ] =>\n      remember (vce_view_changes e) as VCS\n    end.\n\n    match goal with\n    | [ H : context[view_change_cert2max_seq ?a] |- _ ] =>\n      remember (view_change_cert2max_seq a) as sn1\n    end.\n\n    subst.\n    allrw k1.\n    allrw k2.\n    simpl in *.\n\n    match goal with\n    | [ H : create_new_prepare_messages _ _ _ _ = _ |- _ ] =>\n      eapply view_change_cert2max_seq_preps_and_create_new_prepare_messages_implies_le in H;\n        [|eauto| | |]; auto; allrw; simpl; eauto 2 with pbft;[]\n    end.\n\n    rewrite max_seq_nums_from_min_to_max; eauto 2 with pbft.\n  Qed.*)\n\n  Lemma next_seq_not_le :\n    forall (sn : SeqNum),\n      next_seq sn <= sn -> False.\n  Proof.\n    introv h; destruct sn; unfold next_seq in h; simpl in *; omega.\n  Qed.\n\n  Lemma pre_prepare_in_map_correct_new_view_implies :\n    forall v n rs a d nv,\n      In (mk_pre_prepare v n rs a, d) (map add_digest (new_view2oprep nv ++ new_view2nprep nv))\n      -> correct_new_view nv = true\n      -> new_view2view nv = v.\n  Proof.\n    introv i cor.\n    unfold correct_new_view in cor; smash_pbft.\n    destruct nv, v0; simpl in *.\n    allrw forallb_forall.\n    allrw in_map_iff; exrepnd.\n    unfold add_digest in *; ginv.\n    allrw in_app_iff; repndors.\n\n    - match goal with\n      | [ H : context[forall _ : _, In _ OP -> _], H' : In _ OP |- _ ] =>\n        apply H in H'; clear H\n      end.\n      unfold correct_new_view_opre_prepare_op in *; smash_pbft.\n      unfold correct_new_view_opre_prepare in *; smash_pbft.\n\n    - match goal with\n      | [ H : context[forall _ : _, In _ NP -> _], H' : In _ NP |- _ ] =>\n        apply H in H'; clear H\n      end.\n      unfold correct_new_view_npre_prepare_op in *; smash_pbft.\n      unfold correct_new_view_npre_prepare in *; smash_pbft.\n  Qed.\n\n  Lemma new_view2sender_eq_primary :\n    forall nv, new_view2sender nv = PBFTprimary (new_view2view nv).\n  Proof.\n    destruct nv, v; simpl; auto.\n  Qed.\n  Hint Resolve new_view2sender_eq_primary : pbft.\n\n  Lemma nexists_last_prepared_true_implies :\n    forall pp P,\n      nexists_last_prepared pp P = true\n      ->\n      exists nfo,\n        In nfo P\n        /\\ pre_prepare2seq pp = prepared_info2seq nfo\n        /\\ valid_prepared_info P nfo = true.\n  Proof.\n    introv h; unfold nexists_last_prepared in h.\n    apply existsb_exists in h; exrepnd; smash_pbft.\n    exists x; tcsp.\n  Qed.\n\n  Lemma last_prepared_info_app_true :\n    forall nfo l1 l2,\n      last_prepared_info nfo (l1 ++ l2)\n      = last_prepared_info nfo l1 && last_prepared_info nfo l2.\n  Proof.\n    induction l1; introv; simpl; auto.\n    smash_pbft; try (rewrite IHl1); auto;\n      try (complete (rewrite andb_assoc; auto)).\n  Qed.\n\n  Lemma create_new_prepare_messages_view_change_cert2max_seq_none_implies :\n    forall entry view keys OP NP,\n      create_new_prepare_messages\n        (from_min_to_max_of_view_changes entry)\n        view keys\n        (view_change_cert2prep (view_change_entry2view_changes entry)) = (OP, NP)\n      -> view_change_cert2max_seq (view_change_entry2view_changes entry) = None\n      -> OP = []\n         /\\ NP = []\n         /\\ from_min_to_max_of_view_changes entry = [].\n  Proof.\n    introv h q.\n    unfold from_min_to_max_of_view_changes, from_min_to_max_of_view_changes_cert in *.\n    rewrite q in *; simpl in *; ginv.\n  Qed.\n\n  Lemma in_from_min_to_max_of_view_changes_implies_lt_min :\n    forall entry min n,\n      view_change_cert2max_seq (view_change_entry2view_changes entry) = Some min\n      -> In n (from_min_to_max_of_view_changes entry)\n      -> min < n.\n  Proof.\n    introv h i.\n    apply in_from_min_to_max_op_implies in i; exrepnd.\n    rewrite h in *; ginv.\n  Qed.\n  Hint Resolve in_from_min_to_max_of_view_changes_implies_lt_min : pbft.\n\n  Lemma implies_length_view_change_entry2view_changes :\n    forall entry n,\n      is_some (vce_view_change entry) = true\n      -> n = length (vce_view_changes entry)\n      -> n + 1 = length (view_change_entry2view_changes entry).\n  Proof.\n    introv h q; destruct entry; simpl in *.\n    destruct vce_view_change; simpl in *; ginv; omega.\n  Qed.\n\n  Lemma oexists_last_prepared_false_implies :\n    forall pp d P,\n      oexists_last_prepared pp d P = false\n      ->\n      forall nfo,\n        In nfo P\n        -> pre_prepare2seq pp <> prepared_info2seq nfo\n           \\/  d <> prepared_info2digest nfo\n           \\/ valid_prepared_info P nfo = false.\n  Proof.\n    introv h i; unfold oexists_last_prepared in h.\n    rewrite existsb_false in h.\n    apply h in i; smash_pbft.\n  Qed.\n\n  Lemma max_O_in :\n    forall L,\n      L <> []\n      ->\n      exists pp d,\n        max_O L = pre_prepare2seq pp\n        /\\ In (pp,d) L.\n  Proof.\n    induction L; intro h; tcsp; repnd; simpl in *.\n    clear h.\n    destruct L; simpl in *; tcsp.\n\n    - clear IHL.\n      autorewrite with pbft.\n      eexists; dands; eauto.\n\n    - autodimp IHL hyp; tcsp;[].\n      exrepnd.\n      repndors; ginv; tcsp;\n        allrw;\n        unfold max_seq_num; simpl; smash_pbft;\n          eexists; eexists; dands; eauto.\n  Qed.\n\n  Lemma false_implies_in_create_new_prepare_messages_n_pre_prepare :\n    forall n ppd L view keys C OP NP,\n      create_new_prepare_messages L view keys C = (OP, NP)\n      -> In n L\n      -> create_new_prepare_message n view keys C = (false, ppd)\n      -> In ppd NP.\n  Proof.\n    induction L; introv creates i create; simpl in *; smash_pbft.\n\n    - repndors; subst; tcsp.\n\n      + rewrite create in *; ginv.\n\n      + eapply IHL; eauto.\n\n    - repndors; subst; tcsp.\n\n      + rewrite create in *; ginv.\n\n      + right; eapply IHL; eauto.\n  Qed.\n\n  Lemma create_new_prepare_message_true_implies_oprep_not_nil :\n    forall L view keys C OP NP n ppd,\n      create_new_prepare_messages L view keys C = (OP, NP)\n      -> In n L\n      -> create_new_prepare_message n view keys C = (true,ppd)\n      -> In ppd OP.\n  Proof.\n    induction L; introv creates i create; simpl in *; tcsp.\n    smash_pbft; repndors; subst; tcsp.\n\n    - rewrite create in *; ginv.\n\n    - right; eapply IHL; eauto.\n\n    - rewrite create in *; ginv.\n\n    - eapply IHL; eauto.\n  Qed.\n\n  Lemma seq_num_seqnum2nat :\n    forall (n : SeqNum), seq_num (seqnum2nat n) = n.\n  Proof.\n    destruct n; simpl; auto.\n  Qed.\n  Hint Rewrite seq_num_seqnum2nat : pbft.\n\n  Lemma implies_max_in_from_min_to_max :\n    forall n min max,\n      In n (from_min_to_max min max)\n      -> In max (from_min_to_max min max).\n  Proof.\n    unfold from_min_to_max; introv h; smash_pbft; simpl in *.\n    allrw in_map_iff; exrepnd; subst.\n    exists max; dands; simpl in *; autorewrite with pbft in *; auto.\n    allrw in_seq; omega.\n  Qed.\n  Hint Resolve implies_max_in_from_min_to_max : pbft.\n\n  Lemma norepeatsb_pre_prepare2seq_oprep_nprep_implies :\n    forall (OP NP : list (Pre_prepare * PBFTdigest)) pp1 d1 pp2 d2,\n      norepeatsb SeqNumDeq (map pre_prepare2seq (map fst OP ++ map fst NP)) = true\n      -> pre_prepare2seq pp1 = pre_prepare2seq pp2\n      -> In (pp1, d1) NP\n      -> In (pp2, d2) OP\n      -> False.\n  Proof.\n    introv norep e i1 i2.\n    apply norepeatsb_as_no_repeats in norep.\n    rewrite map_app in norep.\n    apply no_repeats_app in norep; repnd.\n\n    apply (norep (pre_prepare2seq pp1)); apply in_map_iff.\n\n    - exists pp2; dands; auto.\n      apply in_map_iff; eexists; dands; eauto; simpl; auto.\n\n    - exists pp1; dands; auto.\n      apply in_map_iff; eexists; dands; eauto; simpl; auto.\n  Qed.\n\n(*  Lemma find_pre_prepare_certificate_in_prepared_infos_none_implies :\n    forall sn L,\n      find_pre_prepare_certificate_in_prepared_infos sn L = None\n      -> ~ In sn (map prepared_info2seq L).\n  Proof.\n    induction L; introv i j; simpl in *; tcsp.\n    smash_pbft.\n    repndors; subst; tcsp.\n  Qed.*)\n\n(*  Lemma find_pre_prepare_certificate_in_view_change_cert_none_implies :\n    forall sn C,\n      find_pre_prepare_certificate_in_view_change_cert sn C = None\n      -> ~ In sn (map prepared_info2seq (view_change_cert2prep C)).\n  Proof.\n    induction C; introv h i; simpl in *; tcsp.\n    allrw map_app.\n    allrw in_app_iff.\n    smash_pbft.\n    autodimp IHC hyp.\n    repndors; tcsp.\n\n    match goal with\n    | [ H : find_pre_prepare_certificate_in_prepared_infos _ _ = _ |- _ ] =>\n      apply find_pre_prepare_certificate_in_prepared_infos_none_implies in H\n    end; tcsp.\n  Qed.*)\n\n(*  Lemma implies_find_pre_prepare_certificate_in_view_change_cert_some :\n    forall sn C nfo,\n      In nfo (view_change_cert2prep C)\n      -> sn = prepared_info2seq nfo\n      -> last_prepared_info nfo (view_change_cert2prep C) = true\n      -> exists nfo', find_pre_prepare_certificate_in_view_change_cert sn C = Some nfo'.\n  Proof.\n    induction C; introv i h q; simpl in *; tcsp.\n    allrw in_app_iff.\n    allrw last_prepared_info_app_true.\n    allrw andb_true; repnd.\n    repndors; tcsp; smash_pbft.\n\n    - unfold pick_prepared_info_with_highest_view; smash_pbft.\n  Qed.*)\n\n(*  Lemma find_pre_prepare_certificate_in_view_change_cert_none_implies_nexists_last_prepared_none :\n    forall sn vcs v rs keys,\n      find_pre_prepare_certificate_in_view_change_cert sn vcs = None\n      -> nexists_last_prepared\n           (mk_auth_pre_prepare v sn rs keys)\n           (view_change_cert2prep vcs) = false.\n  Proof.\n    introv h.\n    match goal with\n    | [ |- ?a = _ ] => remember a as b; destruct b; auto; symmetry in Heqb\n    end.\n\n    assert False; tcsp.\n    apply nexists_last_prepared_true_implies in Heqb; exrepnd; simpl in *.\n\n    Check find_pre_prepare_certificate_in_view_change_cert.\n\n    apply find_pre_prepare_certificate_in_view_change_cert_none_implies in h.\n    destruct h.\n    apply in_map_iff.\n    exists nfo; dands; auto.\n  Qed.*)\n\n(*  Lemma create_new_prepare_message_false_implies_correct :\n    forall (sn : SeqNum) v keys vcs pp d (n max : SeqNum),\n      n < sn\n      -> sn < max\n      -> create_new_prepare_message sn v keys vcs = (false,(pp,d))\n      -> correct_new_view_npre_prepare v n max (view_change_cert2prep vcs) pp = true.\n  Proof.\n    introv ltsn ltmax create.\n    unfold create_new_prepare_message in create; smash_pbft.\n    unfold find_request_info_in_view_change_cert in *; smash_pbft.\n\n    unfold correct_new_view_npre_prepare; simpl; smash_pbft;\n      allrw SeqNumLt_true; allrw SeqNumLt_false; simpl in *; try omega; GC.\n\n    apply negb_true_iff.\n    apply find_pre_prepare_certificate_in_view_change_cert_none_implies_nexists_last_prepared_none; auto.\n  Qed.*)\n\n(*  Lemma create_new_prepare_messages_implies_correct_NPs :\n    forall n max sns v keys vcs OP NP,\n      (forall (x : SeqNum) ppd,\n          In x sns\n          -> create_new_prepare_message x v keys vcs = (false, ppd)\n          -> n < x /\\ x < max)\n      -> create_new_prepare_messages sns v keys vcs = (OP, NP)\n      -> forallb\n           (correct_new_view_npre_prepare v n max (view_change_cert2prep vcs))\n           (map fst NP) = true.\n  Proof.\n    induction sns; introv imp create; simpl in *; smash_pbft; dands; tcsp;\n      try (complete (eapply IHsns; eauto)).\n    repnd; simpl in *.\n\n    pose proof (imp a (x0,x1)) as q.\n    autodimp q hyp.\n\n    eapply create_new_prepare_message_false_implies_correct;[| |eauto];tcsp.\n  Qed.*)\n\n  (*Lemma find_pre_prepare_certificate_in_view_change_cert_some_implies :\n    forall sn L nfo,\n      find_pre_prepare_certificate_in_view_change_cert sn L = Some nfo\n      -> In nfo (view_change_cert2prep L)\n         /\\ sn = prepared_info2seq nfo\n         /\\ last_prepared_info nfo (view_change_cert2prep L) = true.\n  Proof.\n    induction L; introv i; simpl in *; tcsp.\n    smash_pbft.\n\n    - pose proof (IHL x0) as q; autodimp q hyp; repnd; clear IHL.\n\n      unfold pick_prepared_info_with_highest_view; smash_pbft.\n\n      + rewrite in_app_iff; dands; tcsp.\n        rewrite last_prepared_info_app_true.\n        apply andb_true_iff; dands; auto;[].\n\n  Qed.*)\n\n  (*Lemma find_pre_prepare_certificate_in_view_change_cert_some_implies_oexists_last_prepared_true :\n    forall sn vcs v keys nfo,\n      find_pre_prepare_certificate_in_view_change_cert sn vcs = Some nfo\n      -> oexists_last_prepared\n           (mk_auth_pre_prepare v sn (prepared_info2requests nfo) keys)\n           (create_hash_messages (map PBFTrequest (prepared_info2requests nfo)))\n           (view_change_cert2prep vcs) = true.\n  Proof.\n    introv h.\n    match goal with\n    | [ |- ?a = _ ] => remember a as b; destruct b; auto; symmetry in Heqb\n    end.\n\n    assert False; tcsp.\n\n    match goal with\n    | [ H : oexists_last_prepared ?a ?b ?c = _ |- _ ] =>\n      pose proof (oexists_last_prepared_false_implies a b c H) as q; clear H; simpl in q\n    end.\n\n\n\nXXXXXX\n\n    apply find_pre_prepare_certificate_in_view_change_cert_none_implies in h.\n    apply nexists_last_prepared_true_implies in Heqb; exrepnd; simpl in *.\n    destruct h.\n    apply in_map_iff.\n    exists nfo; dands; auto.\n  Qed.*)\n\n  (*Lemma create_new_prepare_message_true_implies_correct :\n    forall (sn : SeqNum) v keys vcs pp d (n : SeqNum),\n      n < sn\n      -> create_new_prepare_message sn v keys vcs = (true,(pp,d))\n      -> correct_new_view_opre_prepare v n (view_change_cert2prep vcs) pp = true.\n  Proof.\n    introv ltsn create.\n    unfold create_new_prepare_message in create; smash_pbft.\n    unfold find_request_info_in_view_change_cert in *; smash_pbft.\n\n    unfold correct_new_view_opre_prepare; simpl; smash_pbft;\n      allrw SeqNumLt_true; allrw SeqNumLt_false; simpl in *; try omega; GC.\n\n    apply find_pre_prepare_certificate_in_view_change_cert_none_implies_nexists_last_prepared_none; auto.\n  Qed.*)\n\n  (*Lemma create_new_prepare_messages_implies_correct_OPs :\n    forall n max sns v keys vcs OP NP,\n      (forall (x : SeqNum) ppd,\n          In x sns\n          -> create_new_prepare_message x v keys vcs = (true, ppd)\n          -> n < x)\n      -> create_new_prepare_messages sns v keys vcs = (OP, NP)\n      -> forallb\n           (correct_new_view_npre_prepare v n max (view_change_cert2prep vcs))\n           (map fst OP) = true.\n  Proof.\n    induction sns; introv imp create; simpl in *; smash_pbft; dands; tcsp;\n      try (complete (eapply IHsns; eauto)).\n    repnd; simpl in *.\n\n    pose proof (imp a (x2,x1)) as q.\n    autodimp q hyp.\n\n    eapply create_new_prepare_message_implies_correct;[| |eauto];tcsp.\n  Qed.*)\n\n  Lemma find_pre_prepare_certificate_in_prepared_infos_none_implies :\n    forall F n P,\n      find_pre_prepare_certificate_in_prepared_infos F n P = None\n      ->\n      forall p, In p P -> n <> prepared_info2seq p \\/ F p = false.\n  Proof.\n    induction P; introv find; simpl in *; tcsp.\n    introv i; repndors; subst; tcsp; smash_pbft.\n  Qed.\n\n  Lemma create_new_prepare_message_false_implies_correct :\n    forall (sn : SeqNum) v keys P pp d (n max : SeqNum),\n      n < sn\n      -> sn < max\n      -> create_new_prepare_message sn v keys P = (false,(pp,d))\n      -> correct_new_view_npre_prepare v n max P pp = true.\n  Proof.\n    introv ltsn ltmax create.\n    unfold create_new_prepare_message in create; smash_pbft.\n\n    unfold correct_new_view_npre_prepare; simpl; smash_pbft;\n      allrw SeqNumLt_true; allrw SeqNumLt_false; simpl in *; try omega; GC.\n\n    unfold nexists_last_prepared; simpl.\n    apply existsb_false.\n    introv i.\n    smash_pbft;[].\n\n    unfold valid_prepared_info.\n\n    apply andb_false_iff.\n    match goal with\n    | [ |- _ \\/ ?x = _ ] => remember x as b; symmetry in Heqb; destruct b; auto\n    end.\n    match goal with\n    | [ |- ?x = _ \\/ _ ] => remember x as c; symmetry in Heqc; destruct c; auto\n    end.\n    assert False; tcsp.\n\n    eapply find_pre_prepare_certificate_in_prepared_infos_none_implies in i;[|eauto].\n    repndors; tcsp.\n\n    unfold valid_prepared_info in i.\n    rewrite andb_false_iff in i; repndors; smash_pbft.\n  Qed.\n\n  Lemma create_new_prepare_messages_implies_correct_NPs :\n    forall n max sns v keys P OP NP,\n      (forall (x : SeqNum) ppd,\n          In x sns\n          -> create_new_prepare_message x v keys P = (false, ppd)\n          -> n < x /\\ x < max)\n      -> create_new_prepare_messages sns v keys P = (OP, NP)\n      -> forallb\n           (correct_new_view_npre_prepare v n max P)\n           (map fst NP) = true.\n  Proof.\n    induction sns; introv imp create; simpl in *; smash_pbft; dands; tcsp;\n      try (complete (eapply IHsns; eauto)).\n    repnd; simpl in *.\n\n    pose proof (imp a (x3,x1)) as q.\n    repeat (autodimp q hyp).\n    eapply create_new_prepare_message_false_implies_correct;[| |eauto]; tcsp.\n  Qed.\n\n  Lemma implies_in_view_change_cert2prep :\n    forall vc p C,\n      In vc C\n      -> In p (view_change2prep vc)\n      -> In p (view_change_cert2prep C).\n  Proof.\n    induction C; introv i j; simpl in *; tcsp; repndors; subst; tcsp;\n      allrw in_app_iff; tcsp.\n  Qed.\n  Hint Resolve implies_in_view_change_cert2prep : pbft.\n\n  Lemma view_change_cert2max_seq_preps_vc_implies_exists_create_new_prepare_message :\n    forall v keys C n vc,\n      view_change_cert2max_seq_preps_vc (valid_prepared_info (view_change_cert2prep C)) C = Some (n,vc)\n      -> exists ppd, create_new_prepare_message n v keys (view_change_cert2prep C) = (true, ppd).\n  Proof.\n    introv cert.\n    apply view_change_cert2max_seq_preps_some_implies in cert.\n    exrepnd.\n    subst.\n    unfold create_new_prepare_message; smash_pbft.\n\n    assert False; tcsp.\n\n    match goal with\n    | [ H : find_pre_prepare_certificate_in_prepared_infos _ _ _ = _ |- _ ] =>\n      eapply find_pre_prepare_certificate_in_prepared_infos_none_implies in H;\n        [|eauto 2 with pbft]\n    end.\n    repndors; smash_pbft.\n  Qed.\n\n  Lemma view_change_cert2max_seq_preps_implies_exists_create_new_prepare_message :\n    forall v keys C n,\n      view_change_cert2max_seq_preps (valid_prepared_info (view_change_cert2prep C)) C = Some n\n      -> exists ppd, create_new_prepare_message n v keys (view_change_cert2prep C) = (true, ppd).\n  Proof.\n    introv cert.\n    unfold view_change_cert2max_seq_preps in cert; smash_pbft.\n    eapply view_change_cert2max_seq_preps_vc_implies_exists_create_new_prepare_message; eauto.\n  Qed.\n\n  Lemma view_change_cert2max_seq_preps_and_create_new_prepare_messages_implies_le :\n    forall K sn v keys C OP NP,\n      view_change_cert2max_seq_preps (valid_prepared_info (view_change_cert2prep C)) C = Some sn\n      -> create_new_prepare_messages K v keys (view_change_cert2prep C) = (OP, NP)\n      -> ordered SeqNumLt K\n      -> sn = max_seq_nums K\n      -> K <> []\n      -> sn <= max_O OP.\n  Proof.\n    induction K; introv h q ord w knn; simpl in *; ginv.\n    smash_pbft; repnd.\n\n    - remember (nullb K) as b; symmetry in Heqb.\n      destruct b.\n\n      + rewrite nullb_true_iff in Heqb; subst; simpl in *; ginv; simpl in *; GC.\n        clear ord knn.\n        autorewrite with pbft in *.\n\n        match goal with\n        | [ H : create_new_prepare_message _ _ _ _ = _ |- _ ] =>\n          apply create_new_prepare_message_implies_same_sequence_number in H;subst;auto\n        end.\n\n      + apply nullb_false_iff in Heqb.\n        eapply IHK in h;[|eauto| | |]; auto; eauto 2 with pbft.\n        apply max_seq_nums_right_if_lt; auto.\n\n    - remember (nullb K) as b; symmetry in Heqb.\n      destruct b.\n\n      + rewrite nullb_true_iff in Heqb; subst; simpl in *; ginv; simpl in *; GC.\n        clear ord knn.\n        autorewrite with pbft in *.\n        apply (view_change_cert2max_seq_preps_implies_exists_create_new_prepare_message v keys) in h.\n        exrepnd.\n        rewrite h0 in *; ginv.\n\n      + apply nullb_false_iff in Heqb.\n        eapply IHK in h;[|eauto| | |]; auto; eauto 2 with pbft.\n        apply max_seq_nums_right_if_lt; auto.\n  Qed.\n\n  Lemma view_changed_entry_some_and_check_broadcast_new_view_implies_le :\n    forall n entry state vc entry' i nv  opreps npreps,\n      In n (from_min_to_max_of_view_changes entry')\n      -> view_changed_entry state entry = Some (vc, entry')\n      -> check_broadcast_new_view i state entry = Some (nv, entry', opreps, npreps)\n      -> n <= max_O opreps.\n  Proof.\n    introv k vce c.\n    unfold check_broadcast_new_view in c; smash_pbft.\n    unfold from_min_to_max_of_view_changes, from_min_to_max_of_view_changes_cert in *; smash_pbft.\n\n    applydup in_from_min_to_max_op_implies in k; exrepnd.\n    eapply le_trans;[eauto|].\n\n    match goal with\n    | [ H : view_changed_entry _ _ = _ |- _ ] =>\n      applydup view_changed_entry_some_implies_cons in H as eqvcs;\n        rewrite eqvcs in *\n    end.\n\n    match goal with\n    | [ H : context[vce_view_changes ?e] |- _ ] =>\n      remember (vce_view_changes e) as VCS\n    end.\n\n    match goal with\n    | [ H : context[view_change_cert2max_seq ?a] |- _ ] =>\n      remember (view_change_cert2max_seq a) as sn1\n    end.\n\n    subst.\n    allrw k1.\n    allrw k2.\n    simpl in *.\n\n    rename_hyp_with create_new_prepare_messages cr.\n    eapply (view_change_cert2max_seq_preps_and_create_new_prepare_messages_implies_le\n              _ _ _ _ (vc :: _)) in cr;\n        [|simpl;eauto| | |]; auto; allrw; simpl; eauto 2 with pbft;[].\n    rewrite max_seq_nums_from_min_to_max; eauto 2 with pbft; omega.\n  Qed.\n\n  Lemma create_new_prepare_messages_preserves_view :\n    forall L v keys P OP NP pp d,\n      create_new_prepare_messages L v keys P = (OP, NP)\n      -> In (pp,d) (OP ++ NP)\n      -> v = pre_prepare2view pp.\n  Proof.\n    induction L; introv create i; simpl in *; smash_pbft; simpl in *; tcsp.\n\n    - repndors; smash_pbft.\n      symmetry; eapply create_new_prepare_message_implies_same_view; eauto.\n\n    - allrw in_app_iff; simpl in *; repndors; smash_pbft.\n\n      + eapply IHL;[eauto|]; apply in_app_iff; eauto.\n\n      + symmetry; eapply create_new_prepare_message_implies_same_view; eauto.\n\n      + eapply IHL;[eauto|]; apply in_app_iff; eauto.\n  Qed.\n  Hint Resolve create_new_prepare_messages_preserves_view : pbft.\n\n  Lemma check_broadcast_new_view_preserves_view :\n    forall i state entry nv entry' OP NP pp d,\n      check_broadcast_new_view i state entry = Some (nv, entry', OP, NP)\n      -> In (pp, d) (OP ++ NP)\n      -> new_view2view nv = pre_prepare2view pp.\n  Proof.\n    introv check k.\n    unfold check_broadcast_new_view in check; smash_pbft.\n  Qed.\n  Hint Resolve check_broadcast_new_view_preserves_view : pbft.\n\n  Lemma pre_prepare_in_map_correct_new_view_implies2 :\n    forall p nv,\n      In p (map add_digest (new_view2oprep nv ++ new_view2nprep nv))\n      -> correct_new_view nv = true\n      -> new_view2view nv = pre_prepare2view (fst p).\n  Proof.\n    introv i cor.\n    destruct p, p, b.\n    eapply pre_prepare_in_map_correct_new_view_implies in i; simpl; auto.\n  Qed.\n\nEnd PBFTprops3.\n\n\nHint Resolve eq_primary_implies_eq_primary : pbft.\nHint Resolve nat_seq_num : pbft.\nHint Resolve in_map_seq_num : pbft.\nHint Resolve in_map_seq_num_natAB : pbft.\nHint Resolve max_seq_num_left : pbft.\nHint Resolve max_seq_num_right : pbft.\nHint Resolve ordered_seq : num.\nHint Resolve in_list_implies_diff_nil : pbft.\n(*Hint Resolve le_seq_num_implies_from_min_to_max_not_null : pbft.*)\nHint Resolve ordered_from_min_to_max : pbft.\nHint Resolve ordered_from_min_to_max_op : pbft.\nHint Resolve new_view2sender_eq_primary : pbft.\nHint Resolve create_new_prepare_messages_implies_norepeatsb : pbft.\nHint Resolve implies_norepeatsb_map_seq_num : pbft.\nHint Resolve norepeatsb_seq : pbft.\nHint Resolve norepeatsb_from_min_to_max : pbft.\nHint Resolve norepeatsb_from_min_to_max_of_view_changes : pbft.\nHint Resolve implies_in_view_change_cert2prep : pbft.\nHint Resolve in_from_min_to_max_of_view_changes_implies_lt_min : pbft.\nHint Resolve implies_max_in_from_min_to_max : pbft.\nHint Resolve create_new_prepare_messages_preserves_view : pbft.\nHint Resolve check_broadcast_new_view_preserves_view : pbft.\n\n\nHint Rewrite @request_data_and_rep_toks2prepare_as_pre_prepare2prepare : pbft.\nHint Rewrite @is_primary_PBFTprimary : pbft.\nHint Rewrite @eq_request_data_same : pbft.\nHint Rewrite @orb_false_r : bool.\nHint Rewrite @max_seq_num_0_right : pbft.\nHint Rewrite @pre_prepare2seq_mk_auth_pre_prepare : pbft.\nHint Rewrite @seq_num_seqnum2nat : pbft.\nHint Rewrite @vce_view_changes_replace_own_view_change_in_entry : pbft.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/PBFT/PBFTprops3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.24399446223014667}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nRequire Import Psatz.\nRequire Import Bool.\nRequire Import Eqdep_dec.\n\nFrom compcert Require Import Core.\nFrom compcert Require Import Digits.\nFrom compcert Require Import Operations.\nFrom compcert Require Import Round.\nFrom compcert Require Import Bracket.\nFrom compcert Require Import Sterbenz.\nFrom compcert Require Import Binary.\nFrom compcert Require Import Round_odd.\n\nLocal Open Scope Z_scope.\n\nSection Extra_ops.\n\n\n\nVariable prec emax : Z.\nContext (prec_gt_0_ : Prec_gt_0 prec).\nLet emin := (3 - emax - prec)%Z.\nLet fexp := FLT_exp emin prec.\nHypothesis Hmax : (prec < emax)%Z.\nLet binary_float := binary_float prec emax.\n\n\n\nRemark is_finite_not_is_nan:\nforall (f: binary_float), is_finite _ _ f = true -> is_nan _ _ f = false.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.is_finite_not_is_nan\".\ndestruct f; reflexivity || discriminate.\nQed.\n\nRemark is_finite_strict_finite:\nforall (f: binary_float), is_finite_strict _ _ f = true -> is_finite _ _ f = true.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.is_finite_strict_finite\".\ndestruct f; reflexivity || discriminate.\nQed.\n\n\n\nDefinition is_finite_pos0 (f: binary_float) : bool :=\nmatch f with\n| B754_zero _ _ s => negb s\n| B754_infinity _ _ _ => false\n| B754_nan _ _ _ _ _ => false\n| B754_finite _ _ _ _ _ _ => true\nend.\n\nLemma Bsign_pos0:\nforall x, is_finite_pos0 x = true -> Bsign _ _ x = Rlt_bool (B2R _ _ x) 0%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bsign_pos0\".\nintros. destruct x as [ [] | | | [] ex mx Bx ]; try discriminate; simpl.\n- rewrite Rlt_bool_false; auto. lra.\n- rewrite Rlt_bool_true; auto. apply F2R_lt_0. compute; auto.\n- rewrite Rlt_bool_false; auto.\nassert ((F2R (Float radix2 (Z.pos ex) mx) > 0)%R) by\n( apply F2R_gt_0; compute; auto ).\nlra.\nQed.\n\nTheorem B2R_inj_pos0:\nforall x y,\nis_finite_pos0 x = true -> is_finite_pos0 y = true ->\nB2R _ _ x = B2R _ _ y ->\nx = y.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.B2R_inj_pos0\".\nintros. apply B2R_Bsign_inj.\ndestruct x; reflexivity||discriminate.\ndestruct y; reflexivity||discriminate.\nauto.\nrewrite ! Bsign_pos0 by auto. rewrite H1; auto.\nQed.\n\n\n\nDefinition Beq_dec: forall (f1 f2: binary_float), {f1 = f2} + {f1 <> f2}.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Beq_dec\".\nassert (UIP_bool: forall (b1 b2: bool) (e e': b1 = b2), e = e').\n{ intros. apply UIP_dec. decide equality. }\nLtac try_not_eq := try solve [right; congruence].\ndestruct f1 as [s1|s1|s1 p1 H1|s1 m1 e1 H1], f2 as [s2|s2|s2 p2 H2|s2 m2 e2 H2];\ntry destruct s1; try destruct s2;\ntry solve [left; auto]; try_not_eq.\ndestruct (Pos.eq_dec p1 p2); try_not_eq;\nsubst; left; f_equal; f_equal; apply UIP_bool.\ndestruct (Pos.eq_dec p1 p2); try_not_eq;\nsubst; left; f_equal; f_equal; apply UIP_bool.\ndestruct (Pos.eq_dec m1 m2); try_not_eq;\ndestruct (Z.eq_dec e1 e2); try solve [right; intro H; inversion H; congruence];\nsubst; left; f_equal; apply UIP_bool.\ndestruct (Pos.eq_dec m1 m2); try_not_eq;\ndestruct (Z.eq_dec e1 e2); try solve [right; intro H; inversion H; congruence];\nsubst; left; f_equal; apply UIP_bool.\nDefined.\n\n\n\n\n\nDefinition integer_representable (n: Z): Prop :=\nZ.abs n <= 2^emax - 2^(emax - prec) /\\ generic_format radix2 fexp (IZR n).\n\nLet int_upper_bound_eq: 2^emax - 2^(emax - prec) = (2^prec - 1) * 2^(emax - prec).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Extra_ops.int_upper_bound_eq\".\nred in prec_gt_0_.\nring_simplify. rewrite <- (Zpower_plus radix2) by omega. f_equal. f_equal. omega.\nQed.\n\nLemma integer_representable_n2p:\nforall n p,\n-2^prec < n < 2^prec -> 0 <= p -> p <= emax - prec ->\ninteger_representable (n * 2^p).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.integer_representable_n2p\".\nintros; split.\n- red in prec_gt_0_. replace (Z.abs (n * 2^p)) with (Z.abs n * 2^p).\nrewrite int_upper_bound_eq.\napply Zmult_le_compat. zify; omega. apply (Zpower_le radix2); omega.\nzify; omega. apply (Zpower_ge_0 radix2).\nrewrite Z.abs_mul. f_equal. rewrite Z.abs_eq. auto. apply (Zpower_ge_0 radix2).\n- apply generic_format_FLT. exists (Float radix2 n p).\nunfold F2R; simpl.\nrewrite <- IZR_Zpower by auto. apply mult_IZR.\nsimpl; zify; omega.\nunfold emin, Fexp; red in prec_gt_0_; omega.\nQed.\n\nLemma integer_representable_2p:\nforall p,\n0 <= p <= emax - 1 ->\ninteger_representable (2^p).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.integer_representable_2p\".\nintros; split.\n- red in prec_gt_0_.\nrewrite Z.abs_eq by (apply (Zpower_ge_0 radix2)).\napply Z.le_trans with (2^(emax-1)).\napply (Zpower_le radix2); omega.\nassert (2^emax = 2^(emax-1)*2).\n{ change 2 with (2^1) at 3. rewrite <- (Zpower_plus radix2) by omega.\nf_equal. omega. }\nassert (2^(emax - prec) <= 2^(emax - 1)).\n{ apply (Zpower_le radix2). omega. }\nomega.\n- red in prec_gt_0_.\napply generic_format_FLT. exists (Float radix2 1 p).\nunfold F2R; simpl.\nrewrite Rmult_1_l. rewrite <- IZR_Zpower. auto. omega.\nsimpl Z.abs. change 1 with (2^0). apply (Zpower_lt radix2). omega. auto.\nunfold emin, Fexp; omega.\nQed.\n\nLemma integer_representable_opp:\nforall n, integer_representable n -> integer_representable (-n).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.integer_representable_opp\".\nintros n (A & B); split. rewrite Z.abs_opp. auto.\nrewrite opp_IZR. apply generic_format_opp; auto.\nQed.\n\nLemma integer_representable_n2p_wide:\nforall n p,\n-2^prec <= n <= 2^prec -> 0 <= p -> p < emax - prec ->\ninteger_representable (n * 2^p).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.integer_representable_n2p_wide\".\nintros. red in prec_gt_0_.\ndestruct (Z.eq_dec n (2^prec)); [idtac | destruct (Z.eq_dec n (-2^prec))].\n- rewrite e. rewrite <- (Zpower_plus radix2) by omega.\napply integer_representable_2p. omega.\n- rewrite e. rewrite <- Zopp_mult_distr_l. apply integer_representable_opp.\nrewrite <- (Zpower_plus radix2) by omega.\napply integer_representable_2p. omega.\n- apply integer_representable_n2p; omega.\nQed.\n\nLemma integer_representable_n:\nforall n, -2^prec <= n <= 2^prec -> integer_representable n.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.integer_representable_n\".\nred in prec_gt_0_. intros.\nreplace n with (n * 2^0) by (change (2^0) with 1; ring).\napply integer_representable_n2p_wide. auto. omega. omega.\nQed.\n\nLemma round_int_no_overflow:\nforall n,\nZ.abs n <= 2^emax - 2^(emax-prec) ->\n(Rabs (round radix2 fexp (round_mode mode_NE) (IZR n)) < bpow radix2 emax)%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.round_int_no_overflow\".\nintros. red in prec_gt_0_.\nrewrite <- round_NE_abs.\napply Rle_lt_trans with (IZR (2^emax - 2^(emax-prec))).\napply round_le_generic. apply fexp_correct; auto. apply valid_rnd_N.\napply generic_format_FLT. exists (Float radix2 (2^prec-1) (emax-prec)).\nrewrite int_upper_bound_eq. unfold F2R; simpl.\nrewrite <- IZR_Zpower by omega. rewrite <- mult_IZR. auto.\nassert (0 < 2^prec) by (apply (Zpower_gt_0 radix2); omega).\nunfold Fnum; simpl; zify; omega.\nunfold emin, Fexp; omega.\nrewrite <- abs_IZR. apply IZR_le. auto.\nrewrite <- IZR_Zpower by omega. apply IZR_lt. simpl.\nassert (0 < 2^(emax-prec)) by (apply (Zpower_gt_0 radix2); omega).\nomega.\napply fexp_correct. auto.\nQed.\n\n\n\nDefinition BofZ (n: Z) : binary_float :=\nbinary_normalize prec emax prec_gt_0_ Hmax mode_NE n 0 false.\n\nTheorem BofZ_correct:\nforall n,\nif Rlt_bool (Rabs (round radix2 fexp (round_mode mode_NE) (IZR n))) (bpow radix2 emax)\nthen\nB2R prec emax (BofZ n) = round radix2 fexp (round_mode mode_NE) (IZR n) /\\\nis_finite _ _ (BofZ n) = true /\\\nBsign prec emax (BofZ n) = Z.ltb n 0\nelse\nB2FF prec emax (BofZ n) = binary_overflow prec emax mode_NE (Z.ltb n 0).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.BofZ_correct\".\nintros.\ngeneralize (binary_normalize_correct prec emax prec_gt_0_ Hmax mode_NE n 0 false).\nfold emin; fold fexp; fold (BofZ n).\nreplace (F2R {| Fnum := n; Fexp := 0 |}) with (IZR n).\ndestruct Rlt_bool.\n- intros (A & B & C). split; [|split].\n+ auto.\n+ auto.\n+ rewrite C. rewrite Rcompare_IZR.\nunfold Z.ltb. auto.\n- intros A; rewrite A. f_equal.\ngeneralize (Z.ltb_spec n 0); intros SPEC; inversion SPEC.\napply Rlt_bool_true; apply IZR_lt; auto.\napply Rlt_bool_false; apply IZR_le; auto.\n- unfold F2R; simpl. ring.\nQed.\n\nTheorem BofZ_finite:\nforall n,\nZ.abs n <= 2^emax - 2^(emax-prec) ->\nB2R _ _ (BofZ n) = round radix2 fexp (round_mode mode_NE) (IZR n)\n/\\ is_finite _ _ (BofZ n) = true\n/\\ Bsign _ _ (BofZ n) = Z.ltb n 0%Z.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.BofZ_finite\".\nintros.\ngeneralize (BofZ_correct n). rewrite Rlt_bool_true. auto.\napply round_int_no_overflow; auto.\nQed.\n\nTheorem BofZ_representable:\nforall n,\ninteger_representable n ->\nB2R _ _ (BofZ n) = IZR n\n/\\ is_finite _ _ (BofZ n) = true\n/\\ Bsign _ _ (BofZ n) = (n <? 0).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.BofZ_representable\".\nintros. destruct H as (P & Q). destruct (BofZ_finite n) as (A & B & C). auto.\nintuition. rewrite A. apply round_generic. apply valid_rnd_round_mode. auto.\nQed.\n\nTheorem BofZ_exact:\nforall n,\n-2^prec <= n <= 2^prec ->\nB2R _ _ (BofZ n) = IZR n\n/\\ is_finite _ _ (BofZ n) = true\n/\\ Bsign _ _ (BofZ n) = Z.ltb n 0%Z.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.BofZ_exact\".\nintros. apply BofZ_representable. apply integer_representable_n; auto.\nQed.\n\nLemma BofZ_finite_pos0:\nforall n,\nZ.abs n <= 2^emax - 2^(emax-prec) -> is_finite_pos0 (BofZ n) = true.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.BofZ_finite_pos0\".\nintros.\ngeneralize (binary_normalize_correct prec emax prec_gt_0_ Hmax mode_NE n 0 false).\nfold emin; fold fexp; fold (BofZ n).\nreplace (F2R {| Fnum := n; Fexp := 0 |}) with (IZR n) by\n(unfold F2R; simpl; ring).\nrewrite Rlt_bool_true by (apply round_int_no_overflow; auto).\nintros (A & B & C).\ndestruct (BofZ n); auto; try discriminate.\nsimpl in *. rewrite C. rewrite Rcompare_IZR.\ngeneralize (Zcompare_spec n 0); intros SPEC; inversion SPEC; auto.\nassert ((round radix2 fexp ZnearestE (IZR n) <= -1)%R).\n{ apply round_le_generic. apply fexp_correct. auto. apply valid_rnd_N.\napply (integer_representable_opp 1).\napply (integer_representable_2p 0).\nred in prec_gt_0_; omega.\napply IZR_le; omega.\n}\nlra.\nQed.\n\nLemma BofZ_finite_equal:\nforall x y,\nZ.abs x <= 2^emax - 2^(emax-prec) ->\nZ.abs y <= 2^emax - 2^(emax-prec) ->\nB2R _ _ (BofZ x) = B2R _ _ (BofZ y) ->\nBofZ x = BofZ y.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.BofZ_finite_equal\".\nintros. apply B2R_inj_pos0; auto; apply BofZ_finite_pos0; auto.\nQed.\n\n\n\nTheorem BofZ_plus:\nforall nan p q,\ninteger_representable p -> integer_representable q ->\nBplus _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) = BofZ (p + q).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.BofZ_plus\".\nintros.\ndestruct (BofZ_representable p) as (A & B & C); auto.\ndestruct (BofZ_representable q) as (D & E & F); auto.\ngeneralize (Bplus_correct _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) B E).\nfold emin; fold fexp.\nrewrite A, D. rewrite <- plus_IZR.\ngeneralize (BofZ_correct (p + q)). destruct Rlt_bool.\n- intros (P & Q & R) (U & V & W).\napply B2R_Bsign_inj; auto.\nrewrite P, U; auto.\nrewrite R, W, C, F.\nrewrite Rcompare_IZR. unfold Z.ltb at 3.\ngeneralize (Zcompare_spec (p + q) 0); intros SPEC; inversion SPEC; auto.\nassert (EITHER: 0 <= p \\/ 0 <= q) by omega.\ndestruct EITHER; [apply andb_false_intro1 | apply andb_false_intro2];\napply Zlt_bool_false; auto.\n- intros P (U & V).\napply B2FF_inj.\nrewrite P, U, C. f_equal. rewrite C, F in V.\ngeneralize (Zlt_bool_spec p 0) (Zlt_bool_spec q 0). rewrite <- V.\nintros SPEC1 SPEC2; inversion SPEC1; inversion SPEC2; try congruence; symmetry.\napply Zlt_bool_true; omega.\napply Zlt_bool_false; omega.\nQed.\n\nTheorem BofZ_minus:\nforall nan p q,\ninteger_representable p -> integer_representable q ->\nBminus _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) = BofZ (p - q).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.BofZ_minus\".\nintros.\ndestruct (BofZ_representable p) as (A & B & C); auto.\ndestruct (BofZ_representable q) as (D & E & F); auto.\ngeneralize (Bminus_correct _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) B E).\nfold emin; fold fexp.\nrewrite A, D. rewrite <- minus_IZR.\ngeneralize (BofZ_correct (p - q)). destruct Rlt_bool.\n- intros (P & Q & R) (U & V & W).\napply B2R_Bsign_inj; auto.\nrewrite P, U; auto.\nrewrite R, W, C, F.\nrewrite Rcompare_IZR. unfold Z.ltb at 3.\ngeneralize (Zcompare_spec (p - q) 0); intros SPEC; inversion SPEC; auto.\nassert (EITHER: 0 <= p \\/ q < 0) by omega.\ndestruct EITHER; [apply andb_false_intro1 | apply andb_false_intro2].\nrewrite Zlt_bool_false; auto.\nrewrite Zlt_bool_true; auto.\n- intros P (U & V).\napply B2FF_inj.\nrewrite P, U, C. f_equal. rewrite C, F in V.\ngeneralize (Zlt_bool_spec p 0) (Zlt_bool_spec q 0). rewrite V.\nintros SPEC1 SPEC2; inversion SPEC1; inversion SPEC2; symmetry.\nrewrite <- H3 in H1; discriminate.\napply Zlt_bool_true; omega.\napply Zlt_bool_false; omega.\nrewrite <- H3 in H1; discriminate.\nQed.\n\nTheorem BofZ_mult:\nforall nan p q,\ninteger_representable p -> integer_representable q ->\n0 < q ->\nBmult _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q) = BofZ (p * q).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.BofZ_mult\".\nintros.\nassert (SIGN: xorb (p <? 0) (q <? 0) = (p * q <? 0)).\n{\nrewrite (Zlt_bool_false q) by omega.\ngeneralize (Zlt_bool_spec p 0); intros SPEC; inversion SPEC; simpl; symmetry.\napply Zlt_bool_true. rewrite Z.mul_comm. apply Z.mul_pos_neg; omega.\napply Zlt_bool_false. apply Zsame_sign_imp; omega.\n}\ndestruct (BofZ_representable p) as (A & B & C); auto.\ndestruct (BofZ_representable q) as (D & E & F); auto.\ngeneralize (Bmult_correct _ _ _ Hmax nan mode_NE (BofZ p) (BofZ q)).\nfold emin; fold fexp.\nrewrite A, B, C, D, E, F. rewrite <- mult_IZR.\ngeneralize (BofZ_correct (p * q)). destruct Rlt_bool.\n- intros (P & Q & R) (U & V & W).\napply B2R_Bsign_inj; auto.\nrewrite P, U; auto.\nrewrite R, W; auto.\napply is_finite_not_is_nan; auto.\n- intros P U.\napply B2FF_inj. rewrite P, U. f_equal. auto.\nQed.\n\nTheorem BofZ_mult_2p:\nforall nan x p,\nZ.abs x <= 2^emax - 2^(emax-prec) ->\n2^prec <= Z.abs x ->\n0 <= p <= emax - 1 ->\nBmult _ _ _ Hmax nan mode_NE (BofZ x) (BofZ (2^p)) = BofZ (x * 2^p).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.BofZ_mult_2p\".\nintros.\ndestruct (Z.eq_dec x 0).\n- subst x. apply BofZ_mult.\napply integer_representable_n.\ngeneralize (Zpower_ge_0 radix2 prec). simpl; omega.\napply integer_representable_2p. auto.\napply (Zpower_gt_0 radix2).\nomega.\n- assert (IZR x <> 0%R) by (apply (IZR_neq _ _ n)).\ndestruct (BofZ_finite x H) as (A & B & C).\ndestruct (BofZ_representable (2^p)) as (D & E & F).\napply integer_representable_2p. auto.\nassert (cexp radix2 fexp (IZR (x * 2^p)) =\ncexp radix2 fexp (IZR x) + p).\n{\nunfold cexp, fexp. rewrite mult_IZR.\nchange (2^p) with (radix2^p). rewrite IZR_Zpower by omega.\nrewrite mag_mult_bpow by auto.\nassert (prec + 1 <= mag radix2 (IZR x)).\n{ rewrite <- (mag_abs radix2 (IZR x)).\nrewrite <- (mag_bpow radix2 prec).\napply mag_le.\napply bpow_gt_0. rewrite <- IZR_Zpower by (red in prec_gt_0_;omega).\nrewrite <- abs_IZR. apply IZR_le; auto. }\nunfold FLT_exp.\nunfold emin; red in prec_gt_0_; zify; omega.\n}\nassert (forall m, round radix2 fexp m (IZR x) * IZR (2^p) =\nround radix2 fexp m (IZR (x * 2^p)))%R.\n{\nintros. unfold round, scaled_mantissa. rewrite H3.\nrewrite mult_IZR. rewrite Z.opp_add_distr. rewrite bpow_plus.\nset (a := IZR x); set (b := bpow radix2 (- cexp radix2 fexp a)).\nreplace (a * IZR (2^p) * (b * bpow radix2 (-p)))%R with (a * b)%R.\nunfold F2R; simpl. rewrite Rmult_assoc. f_equal.\nrewrite bpow_plus.  f_equal. apply (IZR_Zpower radix2). omega.\ntransitivity ((a * b) * (IZR (2^p) * bpow radix2 (-p)))%R.\nrewrite (IZR_Zpower radix2). rewrite <- bpow_plus.\nreplace (p + -p) with 0 by omega. change (bpow radix2 0) with 1%R. ring.\nomega.\nring.\n}\nassert (forall m x,\nround radix2 fexp (round_mode m) (round radix2 fexp (round_mode m) x) =\nround radix2 fexp (round_mode m) x).\n{\nintros. apply round_generic. apply valid_rnd_round_mode.\napply generic_format_round.  apply fexp_correct; auto.\napply valid_rnd_round_mode.\n}\nassert (xorb (x <? 0) (2^p <? 0) = (x * 2^p <? 0)).\n{\nassert (0 < 2^p) by (apply (Zpower_gt_0 radix2); omega).\nrewrite (Zlt_bool_false (2^p)) by omega. rewrite xorb_false_r.\nsymmetry. generalize (Zlt_bool_spec x 0); intros SPEC; inversion SPEC.\napply Zlt_bool_true. apply Z.mul_neg_pos; auto.\napply Zlt_bool_false. apply Z.mul_nonneg_nonneg; omega.\n}\ngeneralize (Bmult_correct _ _ _ Hmax nan mode_NE (BofZ x) (BofZ (2^p)))\n(BofZ_correct (x * 2^p)).\nfold emin; fold fexp. rewrite A, B, C, D, E, F, H4, H5.\ndestruct Rlt_bool.\n+ intros (P & Q & R) (U & V & W).\napply B2R_Bsign_inj; auto.\nrewrite P, U. auto.\nrewrite R, W. auto.\napply is_finite_not_is_nan; auto.\n+ intros P U.\napply B2FF_inj. rewrite P, U. f_equal; auto.\nQed.\n\n\n\nLemma round_odd_flt:\nforall prec' emin' x choice,\nprec > 1 -> prec' > 1 -> prec' >= prec + 2 -> emin' <= emin - 2 ->\nround radix2 fexp (Znearest choice) (round radix2 (FLT_exp emin' prec') Zrnd_odd x) =\nround radix2 fexp (Znearest choice) x.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.round_odd_flt\".\nintros. apply round_N_odd. auto. apply fexp_correct; auto.\napply exists_NE_FLT. right; omega.\napply FLT_exp_valid. red; omega.\napply exists_NE_FLT. right; omega.\nunfold fexp, FLT_exp; intros. zify; omega.\nQed.\n\nCorollary round_odd_fix:\nforall x p choice,\nprec > 1 ->\n0 <= p ->\n(bpow radix2 (prec + p + 1) <= Rabs x)%R ->\nround radix2 fexp (Znearest choice) (round radix2 (FIX_exp p) Zrnd_odd x) =\nround radix2 fexp (Znearest choice) x.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.round_odd_fix\".\nintros. destruct (Req_EM_T x 0%R).\n- subst x. rewrite round_0. auto. apply valid_rnd_odd.\n- set (prec' := mag radix2 x - p).\nset (emin' := emin - 2).\nassert (PREC: mag radix2 (bpow radix2 (prec + p + 1)) <= mag radix2 x).\n{ rewrite <- (mag_abs radix2 x).\napply mag_le; auto. apply bpow_gt_0. }\nrewrite mag_bpow in PREC.\nassert (CANON: cexp radix2 (FLT_exp emin' prec') x =\ncexp radix2 (FIX_exp p) x).\n{\nunfold cexp, FLT_exp, FIX_exp.\nreplace (mag radix2 x - prec') with p by (unfold prec'; omega).\napply Z.max_l. unfold emin', emin. red in prec_gt_0_; omega.\n}\nassert (RND: round radix2 (FIX_exp p) Zrnd_odd x =\nround radix2 (FLT_exp emin' prec') Zrnd_odd x).\n{\nunfold round, scaled_mantissa. rewrite CANON. auto.\n}\nrewrite RND.\napply round_odd_flt. auto.\nunfold prec'. red in prec_gt_0_; omega.\nunfold prec'. omega.\nunfold emin'. omega.\nQed.\n\nDefinition int_round_odd (x: Z) (p: Z) :=\n(if Z.eqb (x mod 2^p) 0 || Z.odd (x / 2^p) then x / 2^p else x / 2^p + 1) * 2^p.\n\nLemma Zrnd_odd_int:\nforall n p, 0 <= p ->\nZrnd_odd (IZR n * bpow radix2 (-p)) * 2^p =\nint_round_odd n p.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Zrnd_odd_int\".\nintros.\nassert (0 < 2^p) by (apply (Zpower_gt_0 radix2); omega).\nassert (n = (n / 2^p) * 2^p + n mod 2^p) by (rewrite Z.mul_comm; apply Z.div_mod; omega).\nassert (0 <= n mod 2^p < 2^p) by (apply Z_mod_lt; omega).\nunfold int_round_odd. set (q := n / 2^p) in *; set (r := n mod 2^p) in *.\nf_equal.\npose proof (bpow_gt_0 radix2 (-p)).\nassert (bpow radix2 p * bpow radix2 (-p) = 1)%R.\n{ rewrite <- bpow_plus. replace (p + -p) with 0 by omega. auto. }\nassert (IZR n * bpow radix2 (-p) = IZR q + IZR r * bpow radix2 (-p))%R.\n{ rewrite H1. rewrite plus_IZR, mult_IZR.\nchange (IZR (2^p)) with (IZR (radix2^p)).\nrewrite IZR_Zpower by omega. ring_simplify.\nrewrite Rmult_assoc. rewrite H4. ring. }\nassert (0 <= IZR r < bpow radix2 p)%R.\n{ split. apply IZR_le; omega.\nrewrite <- IZR_Zpower by omega. apply IZR_lt; tauto. }\nassert (0 <= IZR r * bpow radix2 (-p) < 1)%R.\n{ generalize (bpow_gt_0 radix2 (-p)). intros.\nsplit. apply Rmult_le_pos; lra.\nrewrite <- H4. apply Rmult_lt_compat_r. auto. tauto. }\nassert (Zfloor (IZR n * bpow radix2 (-p)) = q).\n{ apply Zfloor_imp. rewrite H5. rewrite plus_IZR. lra. }\nunfold Zrnd_odd. destruct Req_EM_T.\n- assert (IZR r * bpow radix2 (-p) = 0)%R.\n{ rewrite H8 in e. rewrite e in H5. lra. }\napply Rmult_integral in H9. destruct H9; [ | lra ].\napply (eq_IZR r 0) in H9. apply <- Z.eqb_eq in H9. rewrite H9. assumption.\n- assert (IZR r * bpow radix2 (-p) <> 0)%R.\n{ rewrite H8 in n0. lra. }\ndestruct (Z.eqb r 0) eqn:RZ.\napply Z.eqb_eq in RZ. rewrite RZ in H9.\nrewrite Rmult_0_l in H9. congruence.\nrewrite Zceil_floor_neq by lra. rewrite H8.\nchange Zeven with Z.even. rewrite Zodd_even_bool. destruct (Z.even q); auto.\nQed.\n\nLemma int_round_odd_le:\nforall p x y, 0 <= p ->\nx <= y -> int_round_odd x p <= int_round_odd y p.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.int_round_odd_le\".\nintros.\nassert (Zrnd_odd (IZR x * bpow radix2 (-p)) <= Zrnd_odd (IZR y * bpow radix2 (-p))).\n{ apply Zrnd_le. apply valid_rnd_odd. apply Rmult_le_compat_r. apply bpow_ge_0.\napply IZR_le; auto. }\nrewrite <- ! Zrnd_odd_int by auto.\napply Zmult_le_compat_r. auto. apply (Zpower_ge_0 radix2).\nQed.\n\nLemma int_round_odd_exact:\nforall p x, 0 <= p ->\n(2^p | x) -> int_round_odd x p = x.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.int_round_odd_exact\".\nintros. unfold int_round_odd. apply Znumtheory.Zdivide_mod in H0.\nrewrite H0. simpl. rewrite Z.mul_comm. symmetry. apply Z_div_exact_2.\napply Z.lt_gt. apply (Zpower_gt_0 radix2). auto. auto.\nQed.\n\nTheorem BofZ_round_odd:\nforall x p,\nprec > 1 ->\nZ.abs x <= 2^emax - 2^(emax-prec) ->\n0 <= p <= emax - prec ->\n2^(prec + p + 1) <= Z.abs x ->\nBofZ x = BofZ (int_round_odd x p).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.BofZ_round_odd\".\nintros x p PREC XRANGE PRANGE XGE.\nassert (DIV: (2^p | 2^emax - 2^(emax - prec))).\n{ rewrite int_upper_bound_eq. apply Z.divide_mul_r.\nexists (2^(emax - prec - p)). red in prec_gt_0_.\nrewrite <- (Zpower_plus radix2) by omega. f_equal; omega. }\nassert (YRANGE: Z.abs (int_round_odd x p) <= 2^emax - 2^(emax-prec)).\n{ apply Z.abs_le. split.\nreplace (-(2^emax - 2^(emax-prec))) with (int_round_odd (-(2^emax - 2^(emax-prec))) p).\napply int_round_odd_le; zify; omega.\napply int_round_odd_exact. omega. apply Z.divide_opp_r. auto.\nreplace (2^emax - 2^(emax-prec)) with (int_round_odd (2^emax - 2^(emax-prec)) p).\napply int_round_odd_le; zify; omega.\napply int_round_odd_exact. omega. auto. }\ndestruct (BofZ_finite x XRANGE) as (X1 & X2 & X3).\ndestruct (BofZ_finite (int_round_odd x p) YRANGE) as (Y1 & Y2 & Y3).\napply BofZ_finite_equal; auto.\nrewrite X1, Y1.\nassert (IZR (int_round_odd x p) = round radix2 (FIX_exp p) Zrnd_odd (IZR x)).\n{\nunfold round, scaled_mantissa, cexp, FIX_exp.\nrewrite <- Zrnd_odd_int by omega.\nunfold F2R; simpl. rewrite mult_IZR. f_equal. apply (IZR_Zpower radix2). omega.\n}\nrewrite H. symmetry. apply round_odd_fix. auto. omega.\nrewrite <- IZR_Zpower. rewrite <- abs_IZR. apply IZR_le; auto.\nred in prec_gt_0_; omega.\nQed.\n\nLemma int_round_odd_shifts:\nforall x p, 0 <= p ->\nint_round_odd x p =\nZ.shiftl (if Z.eqb (x mod 2^p) 0 then Z.shiftr x p else Z.lor (Z.shiftr x p) 1) p.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.int_round_odd_shifts\".\nintros.\nunfold int_round_odd. rewrite Z.shiftl_mul_pow2 by auto. f_equal.\nrewrite Z.shiftr_div_pow2 by auto.\ndestruct (x mod 2^p =? 0) eqn:E. auto.\nassert (forall n, (if Z.odd n then n else n + 1) = Z.lor n 1).\n{ destruct n; simpl; auto.\ndestruct p0; auto.\ndestruct p0; auto. induction p0; auto. }\nsimpl. apply H0.\nQed.\n\nLemma int_round_odd_bits:\nforall x y p, 0 <= p ->\n(forall i, 0 <= i < p -> Z.testbit y i = false) ->\nZ.testbit y p = (if Z.eqb (x mod 2^p) 0 then Z.testbit x p else true) ->\n(forall i, p < i -> Z.testbit y i = Z.testbit x i) ->\nint_round_odd x p = y.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.int_round_odd_bits\".\nintros until p; intros PPOS BELOW AT ABOVE.\nrewrite int_round_odd_shifts by auto.\napply Z.bits_inj'. intros.\ngeneralize (Zcompare_spec n p); intros SPEC; inversion SPEC.\n- rewrite BELOW by auto. apply Z.shiftl_spec_low; auto.\n- subst n. rewrite AT. rewrite Z.shiftl_spec_high by omega.\nreplace (p - p) with 0 by omega.\ndestruct (x mod 2^p =? 0).\n+ rewrite Z.shiftr_spec by omega. f_equal; omega.\n+ rewrite Z.lor_spec. apply orb_true_r.\n- rewrite ABOVE by auto.  rewrite Z.shiftl_spec_high by omega.\ndestruct (x mod 2^p =? 0).\nrewrite Z.shiftr_spec by omega. f_equal; omega.\nrewrite Z.lor_spec, Z.shiftr_spec by omega.\nchange 1 with (Z.ones 1). rewrite Z.ones_spec_high by omega. rewrite orb_false_r.\nf_equal; omega.\nQed.\n\n\n\n\n\nDefinition ZofB (f: binary_float): option Z :=\nmatch f with\n| B754_finite _ _ s m (Zpos e) _ => Some (cond_Zopp s (Zpos m) * Z.pow_pos radix2 e)%Z\n| B754_finite _ _ s m 0 _ => Some (cond_Zopp s (Zpos m))\n| B754_finite _ _ s m (Zneg e) _ => Some (cond_Zopp s (Zpos m / Z.pow_pos radix2 e))%Z\n| B754_zero _ _ _ => Some 0%Z\n| _ => None\nend.\n\nTheorem ZofB_correct:\nforall f,\nZofB f = if is_finite _ _ f then Some (Ztrunc (B2R _ _ f)) else None.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.ZofB_correct\".\ndestruct f as [s|s|s p H|s m e H]; simpl; auto.\n- f_equal. symmetry. apply (Ztrunc_IZR 0).\n- destruct e; f_equal.\n+ unfold F2R; simpl. rewrite Rmult_1_r. rewrite Ztrunc_IZR. auto.\n+ unfold F2R; simpl. rewrite <- mult_IZR. rewrite Ztrunc_IZR. auto.\n+ unfold F2R; simpl. rewrite IZR_cond_Zopp. rewrite <- cond_Ropp_mult_l.\nassert (EQ: forall x, Ztrunc (cond_Ropp s x) = cond_Zopp s (Ztrunc x)).\n{\nintros. destruct s; simpl; auto. apply Ztrunc_opp.\n}\nrewrite EQ. f_equal.\ngeneralize (Zpower_pos_gt_0 2 p (eq_refl _)); intros.\nrewrite Ztrunc_floor. symmetry. apply Zfloor_div. omega.\napply Rmult_le_pos. apply IZR_le. compute; congruence.\napply Rlt_le. apply Rinv_0_lt_compat. apply IZR_lt. auto.\nQed.\n\n\n\nRemark Ztrunc_range_pos:\nforall x, 0 < Ztrunc x -> (IZR (Ztrunc x) <= x < IZR (Ztrunc x + 1)%Z)%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Ztrunc_range_pos\".\nintros.\nrewrite Ztrunc_floor. split. apply Zfloor_lb. rewrite plus_IZR. apply Zfloor_ub.\ngeneralize (Rle_bool_spec 0%R x). intros RLE; inversion RLE; subst; clear RLE.\nauto.\nrewrite Ztrunc_ceil in H by lra. unfold Zceil in H.\nassert (-x < 0)%R.\n{ apply Rlt_le_trans with (IZR (Zfloor (-x)) + 1)%R. apply Zfloor_ub.\nrewrite <- plus_IZR.\napply IZR_le. omega. }\nlra.\nQed.\n\nRemark Ztrunc_range_zero:\nforall x, Ztrunc x = 0 -> (-1 < x < 1)%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Ztrunc_range_zero\".\nintros; generalize (Rle_bool_spec 0%R x). intros RLE; inversion RLE; subst; clear RLE.\n- rewrite Ztrunc_floor in H by auto. split.\n+ apply Rlt_le_trans with 0%R; auto. rewrite <- Ropp_0. apply Ropp_lt_contravar. apply Rlt_0_1.\n+ replace 1%R with (IZR (Zfloor x) + 1)%R. apply Zfloor_ub. rewrite H. simpl. apply Rplus_0_l.\n- rewrite Ztrunc_ceil in H by (apply Rlt_le; auto). split.\n+ apply (Ropp_lt_cancel (-(1))). rewrite Ropp_involutive.\nreplace 1%R with (IZR (Zfloor (-x)) + 1)%R. apply Zfloor_ub.\nunfold Zceil in H. replace (Zfloor (-x)) with 0 by omega. simpl. apply Rplus_0_l.\n+ apply Rlt_le_trans with 0%R; auto. apply Rle_0_1.\nQed.\n\nTheorem ZofB_range_pos:\nforall f n, ZofB f = Some n -> 0 < n -> (IZR n <= B2R _ _ f < IZR (n + 1)%Z)%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.ZofB_range_pos\".\nintros. rewrite ZofB_correct in H. destruct (is_finite prec emax f) eqn:FIN; inversion H.\napply Ztrunc_range_pos. congruence.\nQed.\n\nTheorem ZofB_range_neg:\nforall f n, ZofB f = Some n -> n < 0 -> (IZR (n - 1)%Z < B2R _ _ f <= IZR n)%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.ZofB_range_neg\".\nintros. rewrite ZofB_correct in H. destruct (is_finite prec emax f) eqn:FIN; inversion H.\nset (x := B2R prec emax f) in *. set (y := (-x)%R).\nassert (A: (IZR (Ztrunc y) <= y < IZR (Ztrunc y + 1)%Z)%R).\n{ apply Ztrunc_range_pos. unfold y. rewrite Ztrunc_opp. omega. }\ndestruct A as [B C].\nunfold y in B, C. rewrite Ztrunc_opp in B, C.\nreplace (- Ztrunc x + 1) with (- (Ztrunc x - 1)) in C by omega.\nrewrite opp_IZR in B, C. lra.\nQed.\n\nTheorem ZofB_range_zero:\nforall f, ZofB f = Some 0 -> (-1 < B2R _ _ f < 1)%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.ZofB_range_zero\".\nintros. rewrite ZofB_correct in H. destruct (is_finite prec emax f) eqn:FIN; inversion H.\napply Ztrunc_range_zero. auto.\nQed.\n\nTheorem ZofB_range_nonneg:\nforall f n, ZofB f = Some n -> 0 <= n -> (-1 < B2R _ _ f < IZR (n + 1)%Z)%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.ZofB_range_nonneg\".\nintros. destruct (Z.eq_dec n 0).\n- subst n. apply ZofB_range_zero. auto.\n- destruct (ZofB_range_pos f n) as (A & B). auto. omega.\nsplit; auto. apply Rlt_le_trans with 0%R. simpl; lra.\napply Rle_trans with (IZR n); auto. apply IZR_le; auto.\nQed.\n\n\n\nTheorem ZofBofZ_exact:\nforall n, integer_representable n -> ZofB (BofZ n) = Some n.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.ZofBofZ_exact\".\nintros. destruct (BofZ_representable n H) as (A & B & C).\nrewrite ZofB_correct. rewrite A, B. f_equal. apply Ztrunc_IZR.\nQed.\n\n\n\nRemark Zfloor_minus:\nforall x n, Zfloor (x - IZR n) = Zfloor x - n.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Zfloor_minus\".\nintros. apply Zfloor_imp. replace (Zfloor x - n + 1) with ((Zfloor x + 1) - n) by omega.\nrewrite ! minus_IZR. unfold Rminus. split.\napply Rplus_le_compat_r. apply Zfloor_lb.\napply Rplus_lt_compat_r. rewrite plus_IZR. apply Zfloor_ub.\nQed.\n\nTheorem ZofB_minus:\nforall minus_nan m f p q,\nZofB f = Some p -> 0 <= p < 2*q -> q <= 2^prec -> (IZR q <= B2R _ _ f)%R ->\nZofB (Bminus _ _ _ Hmax minus_nan m f (BofZ q)) = Some (p - q).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.ZofB_minus\".\nintros.\nassert (Q: -2^prec <= q <= 2^prec).\n{ split; auto.  generalize (Zpower_ge_0 radix2 prec); simpl; omega. }\nassert (RANGE: (-1 < B2R _ _ f < IZR (p + 1)%Z)%R) by (apply ZofB_range_nonneg; auto; omega).\nrewrite ZofB_correct in H. destruct (is_finite prec emax f) eqn:FIN; try discriminate.\nassert (PQ2: (IZR (p + 1) <= IZR q * 2)%R).\n{ rewrite <- mult_IZR. apply IZR_le. omega. }\nassert (EXACT: round radix2 fexp (round_mode m) (B2R _ _ f - IZR q)%R = (B2R _ _ f - IZR q)%R).\n{ apply round_generic. apply valid_rnd_round_mode.\napply sterbenz_aux. now apply FLT_exp_valid. apply FLT_exp_monotone. apply generic_format_B2R.\napply integer_representable_n. auto. lra. }\ndestruct (BofZ_exact q Q) as (A & B & C).\ngeneralize (Bminus_correct _ _ _ Hmax minus_nan m f (BofZ q) FIN B).\nrewrite Rlt_bool_true.\n- fold emin; fold fexp. intros (D & E & F).\nrewrite ZofB_correct. rewrite E. rewrite D. rewrite A. rewrite EXACT.\ninversion H. f_equal. rewrite ! Ztrunc_floor. apply Zfloor_minus.\nlra. lra.\n- rewrite A. fold emin; fold fexp. rewrite EXACT.\napply Rle_lt_trans with (bpow radix2 prec).\napply Rle_trans with (IZR q). apply Rabs_le. lra.\nrewrite <- IZR_Zpower. apply IZR_le; auto. red in prec_gt_0_; omega.\napply bpow_lt. auto.\nQed.\n\n\n\nDefinition ZofB_range (f: binary_float) (zmin zmax: Z): option Z :=\nmatch ZofB f with\n| None => None\n| Some z => if Z.leb zmin z && Z.leb z zmax then Some z else None\nend.\n\nTheorem ZofB_range_correct:\nforall f min max,\nlet n := Ztrunc (B2R _ _ f) in\nZofB_range f min max =\nif is_finite _ _ f && Z.leb min n && Z.leb n max then Some n else None.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.ZofB_range_correct\".\nintros. unfold ZofB_range. rewrite ZofB_correct. fold n.\ndestruct (is_finite prec emax f); auto.\nQed.\n\nLemma ZofB_range_inversion:\nforall f min max n,\nZofB_range f min max = Some n ->\nmin <= n /\\ n <= max /\\ ZofB f = Some n.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.ZofB_range_inversion\".\nintros. rewrite ZofB_range_correct in H. rewrite ZofB_correct.\ndestruct (is_finite prec emax f); try discriminate.\nset (n1 := Ztrunc (B2R _ _ f)) in *.\ndestruct (min <=? n1) eqn:MIN; try discriminate.\ndestruct (n1 <=? max) eqn:MAX; try discriminate.\nsimpl in H. inversion H. subst n.\nsplit. apply Zle_bool_imp_le; auto.\nsplit. apply Zle_bool_imp_le; auto.\nauto.\nQed.\n\nTheorem ZofB_range_minus:\nforall minus_nan m f p q,\nZofB_range f 0 (2 * q - 1) = Some p -> q <= 2^prec -> (IZR q <= B2R _ _ f)%R ->\nZofB_range (Bminus _ _ _ Hmax minus_nan m f (BofZ q)) (-q) (q - 1) = Some (p - q).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.ZofB_range_minus\".\nintros. destruct (ZofB_range_inversion _ _ _ _ H) as (A & B & C).\nset (f' := Bminus prec emax prec_gt_0_ Hmax minus_nan m f (BofZ q)).\nassert (D: ZofB f' = Some (p - q)).\n{ apply ZofB_minus. auto. omega. auto. auto. }\nunfold ZofB_range. rewrite D. rewrite Zle_bool_true by omega. rewrite Zle_bool_true by omega. auto.\nQed.\n\n\n\n\n\nTheorem Bplus_commut:\nforall plus_nan mode (x y: binary_float),\nplus_nan x y = plus_nan y x ->\nBplus _ _ _ Hmax plus_nan mode x y = Bplus _ _ _ Hmax plus_nan mode y x.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bplus_commut\".\nintros until y; intros NAN.\npose proof (Bplus_correct _ _ _ Hmax plus_nan mode x y).\npose proof (Bplus_correct _ _ _ Hmax plus_nan mode y x).\nunfold Bplus in *; destruct x as [sx|sx|sx px Hx|sx mx ex Hx]; destruct y as [sy|sy|sy py Hy|sy my ey Hy]; auto.\n- rewrite (eqb_sym sy sx). destruct (eqb sx sy) eqn:EQB; auto.\nf_equal; apply eqb_prop; auto.\n- rewrite NAN; auto.\n- rewrite (eqb_sym sy sx). destruct (eqb sx sy) eqn:EQB.\nf_equal; apply eqb_prop; auto.\nrewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- generalize (H (eq_refl _) (eq_refl _)); clear H.\ngeneralize (H0 (eq_refl _) (eq_refl _)); clear H0.\nfold emin. fold fexp.\nset (x := B754_finite prec emax sx mx ex Hx). set (rx := B2R _ _ x).\nset (y := B754_finite prec emax sy my ey Hy). set (ry := B2R _ _ y).\nrewrite (Rplus_comm ry rx). destruct Rlt_bool.\n+ intros (A1 & A2 & A3) (B1 & B2 & B3).\napply B2R_Bsign_inj; auto. rewrite <- B1 in A1. auto.\nrewrite Z.add_comm. rewrite Z.min_comm. auto.\n+ intros (A1 & A2) (B1 & B2). apply B2FF_inj. rewrite B2 in B1. rewrite <- B1 in A1. auto.\nQed.\n\nTheorem Bmult_commut:\nforall mult_nan mode (x y: binary_float),\nmult_nan x y = mult_nan y x ->\nBmult _ _ _ Hmax mult_nan mode x y = Bmult _ _ _ Hmax mult_nan mode y x.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bmult_commut\".\nintros until y; intros NAN.\npose proof (Bmult_correct _ _ _ Hmax mult_nan mode x y).\npose proof (Bmult_correct _ _ _ Hmax mult_nan mode y x).\nunfold Bmult in *; destruct x as [sx|sx|sx px Hx|sx mx ex Hx]; destruct y as [sy|sy|sy py Hy|sy my ey Hy]; auto.\n- rewrite (xorb_comm sx sy); auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite (xorb_comm sx sy); auto.\n- rewrite NAN; auto.\n- rewrite (xorb_comm sx sy); auto.\n- rewrite NAN; auto.\n- rewrite (xorb_comm sx sy); auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite NAN; auto.\n- rewrite (xorb_comm sx sy); auto.\n- rewrite (xorb_comm sx sy); auto.\n- rewrite NAN; auto.\n- revert H H0. fold emin. fold fexp.\nset (x := B754_finite prec emax sx mx ex Hx). set (rx := B2R _ _ x).\nset (y := B754_finite prec emax sy my ey Hy). set (ry := B2R _ _ y).\nrewrite (Rmult_comm ry rx).\ndestruct (Rlt_bool (Rabs (round radix2 fexp (round_mode mode) (rx * ry)))\n(bpow radix2 emax)).\n+ intros (A1 & A2 & A3) (B1 & B2 & B3).\napply B2R_Bsign_inj; auto. rewrite <- B1 in A1. auto.\nrewrite ! Bsign_FF2B. f_equal. f_equal. apply xorb_comm. now rewrite Pos.mul_comm. apply Z.add_comm.\n+ intros A B. apply B2FF_inj. etransitivity. eapply A. rewrite xorb_comm. auto.\nQed.\n\n\n\nTheorem Bmult2_Bplus:\nforall plus_nan mult_nan mode (f: binary_float),\n(forall (x y: binary_float),\nis_nan _ _ x = true -> is_finite _ _ y = true -> plus_nan x x = mult_nan x y) ->\nBplus _ _ _ Hmax plus_nan mode f f = Bmult _ _ _ Hmax mult_nan mode f (BofZ 2%Z).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bmult2_Bplus\".\nintros until f; intros NAN.\ndestruct (BofZ_representable 2) as (A & B & C).\napply (integer_representable_2p 1). red in prec_gt_0_; omega.\npose proof (Bmult_correct _ _ _ Hmax mult_nan mode f (BofZ 2%Z)). fold emin in H.\nrewrite A, B, C in H. rewrite xorb_false_r in H.\ndestruct (is_finite _ _ f) eqn:FIN.\n- pose proof (Bplus_correct _ _ _ Hmax plus_nan mode f f FIN FIN). fold emin in H0.\nassert (EQ: (B2R prec emax f * IZR 2%Z = B2R prec emax f + B2R prec emax f)%R).\n{ ring. }\nrewrite <- EQ in H0. destruct Rlt_bool.\n+ destruct H0 as (P & Q & R). destruct H as (S & T & U).\napply B2R_Bsign_inj; auto.\nrewrite P, S. auto.\nrewrite R, U.\nreplace 0%R with (0 * 2)%R by ring. rewrite Rcompare_mult_r.\nrewrite andb_diag, orb_diag. destruct f as [s|s|s p H|s m e H]; try discriminate; simpl.\nrewrite Rcompare_Eq by auto. destruct mode; auto.\nreplace 0%R with (@F2R radix2 {| Fnum := 0%Z; Fexp := e |}).\nrewrite Rcompare_F2R. destruct s; auto.\nunfold F2R. simpl. ring.\napply IZR_lt. omega.\ndestruct (Bmult prec emax prec_gt_0_ Hmax mult_nan mode f (BofZ 2)); reflexivity || discriminate.\n+ destruct H0 as (P & Q). apply B2FF_inj. rewrite P, H. auto.\n- destruct f as [sf|sf|sf pf Hf|sf mf ef Hf]; try discriminate.\n+ simpl Bplus. rewrite eqb_true. destruct (BofZ 2) as [| | |s2 m2 e2 H2] eqn:B2; try discriminate; simpl in *.\nassert ((0 = 2)%Z) by (apply eq_IZR; auto). discriminate.\nsubst s2. rewrite xorb_false_r. auto.\nauto.\n+ unfold Bplus, Bmult. rewrite <- NAN by auto. auto.\nQed.\n\n\n\nDefinition Bexact_inverse_mantissa := Z.iter (prec - 1) xO xH.\n\nRemark Bexact_inverse_mantissa_value:\nZpos Bexact_inverse_mantissa = 2 ^ (prec - 1).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bexact_inverse_mantissa_value\".\nassert (REC: forall n, Z.pos (nat_rect _ xH (fun _ => xO) n) = 2 ^ (Z.of_nat n)).\n{ induction n. reflexivity.\nsimpl nat_rect. transitivity (2 * Z.pos (nat_rect _ xH (fun _ => xO) n)). reflexivity.\nrewrite Nat2Z.inj_succ. rewrite IHn. unfold Z.succ. rewrite Zpower_plus by omega.\nchange (2 ^ 1) with 2. ring. }\nred in prec_gt_0_.\nunfold Bexact_inverse_mantissa. rewrite iter_nat_of_Z by omega. rewrite REC.\nrewrite Zabs2Nat.id_abs. rewrite Z.abs_eq by omega. auto.\nQed.\n\nRemark Bexact_inverse_mantissa_digits2_pos:\nZ.pos (digits2_pos Bexact_inverse_mantissa) = prec.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bexact_inverse_mantissa_digits2_pos\".\nassert (DIGITS: forall n, digits2_pos (nat_rect _ xH (fun _ => xO) n) = Pos.of_nat (n+1)).\n{ induction n; simpl. auto. rewrite IHn. destruct n; auto. }\nred in prec_gt_0_.\nunfold Bexact_inverse_mantissa. rewrite iter_nat_of_Z by omega. rewrite DIGITS.\nrewrite Zabs2Nat.abs_nat_nonneg, Z2Nat.inj_sub by omega.\ndestruct prec; try  discriminate. rewrite Nat.sub_add.\nsimpl. rewrite Pos2Nat.id. auto.\nsimpl. zify; omega.\nQed.\n\nRemark bounded_Bexact_inverse:\nforall e,\nemin <= e <= emax - prec <-> bounded prec emax Bexact_inverse_mantissa e = true.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.bounded_Bexact_inverse\".\nintros. unfold bounded, canonical_mantissa. rewrite andb_true_iff.\nrewrite <- Zeq_is_eq_bool. rewrite <- Zle_is_le_bool.\nrewrite Bexact_inverse_mantissa_digits2_pos.\nsplit.\n- intros; split. unfold FLT_exp. unfold emin in H. zify; omega. omega.\n- intros [A B]. unfold FLT_exp in A. unfold emin. zify; omega.\nQed.\n\nProgram Definition Bexact_inverse (f: binary_float) : option binary_float :=\nmatch f with\n| B754_finite _ _ s m e B =>\nif Pos.eq_dec m Bexact_inverse_mantissa then\nlet e' := -e - (prec - 1) * 2 in\nif Z_le_dec emin e' then\nif Z_le_dec e' emax then\nSome(B754_finite _ _ s m e' _)\nelse None else None else None\n| _ => None\nend.\nNext Obligation.\nrewrite <- bounded_Bexact_inverse in B. rewrite <- bounded_Bexact_inverse.\nunfold emin in *. omega.\nQed.\n\nLemma Bexact_inverse_correct:\nforall f f', Bexact_inverse f = Some f' ->\nis_finite_strict _ _ f = true\n/\\ is_finite_strict _ _ f' = true\n/\\ B2R _ _ f' = (/ B2R _ _ f)%R\n/\\ B2R _ _ f <> 0%R\n/\\ Bsign _ _ f' = Bsign _ _ f.\nProof with (try discriminate). hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bexact_inverse_correct\".\nintros f f' EI. unfold Bexact_inverse in EI. destruct f as [s|s|s p H|s m e H]...\ndestruct (Pos.eq_dec m Bexact_inverse_mantissa)...\nset (e' := -e - (prec - 1) * 2) in *.\ndestruct (Z_le_dec emin e')...\ndestruct (Z_le_dec e' emax)...\ninversion EI; clear EI; subst f' m.\nsplit. auto. split. auto. split. unfold B2R. rewrite Bexact_inverse_mantissa_value.\nunfold F2R; simpl. rewrite IZR_cond_Zopp.\nrewrite <- ! cond_Ropp_mult_l.\nred in prec_gt_0_.\nreplace (IZR (2 ^ (prec - 1))) with (bpow radix2 (prec - 1))\nby (symmetry; apply (IZR_Zpower radix2); omega).\nrewrite <- ! bpow_plus.\nreplace (prec - 1 + e') with (- (prec - 1 + e)) by (unfold e'; omega).\nrewrite bpow_opp. unfold cond_Ropp; destruct s; auto.\nrewrite Ropp_inv_permute. auto. apply Rgt_not_eq. apply bpow_gt_0.\nsplit. simpl. apply F2R_neq_0. destruct s; simpl in H; discriminate.\nauto.\nQed.\n\nTheorem Bdiv_mult_inverse:\nforall div_nan mult_nan mode x y z,\n(forall (x y z: binary_float),\nis_nan _ _ x = true -> is_finite _ _ y = true -> is_finite _ _ z = true ->\ndiv_nan x y = mult_nan x z) ->\nBexact_inverse y = Some z ->\nBdiv _ _ _ Hmax div_nan mode x y = Bmult _ _ _ Hmax mult_nan mode x z.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bdiv_mult_inverse\".\nintros until z; intros NAN; intros. destruct (Bexact_inverse_correct _ _ H) as (A & B & C & D & E).\npose proof (Bmult_correct _ _ _ Hmax mult_nan mode x z).\nfold emin in H0. fold fexp in H0.\npose proof (Bdiv_correct _ _ _ Hmax div_nan mode x y D).\nfold emin in H1. fold fexp in H1.\nunfold Rdiv in H1. rewrite <- C in H1.\ndestruct (is_finite _ _ x) eqn:FINX.\n- destruct Rlt_bool.\n+ destruct H0 as (P & Q & R). destruct H1 as (S & T & U).\napply B2R_Bsign_inj; auto.\nrewrite Q. simpl. apply is_finite_strict_finite; auto.\nrewrite P, S. auto.\nrewrite R, U, E. auto.\napply is_finite_not_is_nan; auto.\napply is_finite_not_is_nan. rewrite Q. simpl. apply is_finite_strict_finite; auto.  + apply B2FF_inj. rewrite H0, H1. rewrite E. auto.\n- destruct y; try discriminate. destruct z; try discriminate.\ndestruct x; try discriminate; simpl.\n+ simpl in E; congruence.\n+ erewrite NAN; eauto.\nQed.\n\n\n\n\n\nFixpoint pos_pow (x y: positive) : positive :=\nmatch y with\n| xH => x\n| xO y => Pos.square (pos_pow x y)\n| xI y => Pos.mul x (Pos.square (pos_pow x y))\nend.\n\nLemma pos_pow_spec:\nforall x y, Z.pos (pos_pow x y) = Z.pos x ^ Z.pos y.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.pos_pow_spec\".\nintros x.\nassert (REC: forall y a, Pos.iter (Pos.mul x) a y = Pos.mul (pos_pow x y) a).\n{ induction y; simpl; intros.\n- rewrite ! IHy, Pos.square_spec, ! Pos.mul_assoc. auto.\n- rewrite ! IHy, Pos.square_spec, ! Pos.mul_assoc. auto.\n- auto.\n}\nintros. simpl. rewrite <- Pos2Z.inj_pow_pos. unfold Pos.pow. rewrite REC. rewrite Pos.mul_1_r. auto.\nQed.\n\n\n\nDefinition Bparse (base: positive) (m: positive) (e: Z): binary_float :=\nmatch e with\n| Z0 =>\nBofZ (Zpos m)\n| Zpos p =>\nif e * Z.log2 (Zpos base) <? emax\nthen BofZ (Zpos m * Zpos (pos_pow base p))\nelse B754_infinity _ _ false\n| Zneg p =>\nif e * Z.log2 (Zpos base) + Z.log2_up (Zpos m) <? emin\nthen B754_zero _ _ false\nelse FF2B prec emax _ (proj1 (Bdiv_correct_aux prec emax prec_gt_0_ Hmax mode_NE\nfalse m Z0 false (pos_pow base p) Z0))\nend.\n\n\n\nLemma Zpower_log:\nforall (base: radix) n,\n0 < n ->\n2 ^ (n * Z.log2 base) <= base ^ n <= 2 ^ (n * Z.log2_up base).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Zpower_log\".\nintros.\nassert (A: 0 < base) by apply radix_gt_0.\nassert (B: 0 <= Z.log2 base) by apply Z.log2_nonneg.\nassert (C: 0 <= Z.log2_up base) by apply Z.log2_up_nonneg.\ndestruct (Z.log2_spec base) as [D E]; auto.\ndestruct (Z.log2_up_spec base) as [F G]. apply radix_gt_1.\nassert (K: 0 <= 2 ^ Z.log2 base) by (apply Z.pow_nonneg; omega).\nrewrite ! (Z.mul_comm n). rewrite ! Z.pow_mul_r by omega.\nsplit; apply Z.pow_le_mono_l; omega.\nQed.\n\nLemma bpow_log_pos:\nforall (base: radix) n,\n0 < n ->\n(bpow radix2 (n * Z.log2 base)%Z <= bpow base n)%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.bpow_log_pos\".\nintros. rewrite <- ! IZR_Zpower. apply IZR_le; apply Zpower_log; auto.\nomega.\nrewrite Z.mul_comm; apply Zmult_gt_0_le_0_compat. omega. apply Z.log2_nonneg.\nQed.\n\nLemma bpow_log_neg:\nforall (base: radix) n,\nn < 0 ->\n(bpow base n <= bpow radix2 (n * Z.log2 base)%Z)%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.bpow_log_neg\".\nintros. set (m := -n). replace n with (-m) by (unfold m; omega).\nrewrite ! Z.mul_opp_l, ! bpow_opp. apply Rinv_le.\napply bpow_gt_0.\napply bpow_log_pos. unfold m; omega.\nQed.\n\n\n\nLemma round_integer_overflow:\nforall (base: radix) e m,\n0 < e ->\nemax <= e * Z.log2 base ->\n(bpow radix2 emax <= round radix2 fexp (round_mode mode_NE) (IZR (Zpos m) * bpow base e))%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.round_integer_overflow\".\nintros.\nrewrite <- (round_generic radix2 fexp (round_mode mode_NE) (bpow radix2 emax)); auto.\napply round_le; auto. apply fexp_correct; auto. apply valid_rnd_round_mode.\nrewrite <- (Rmult_1_l (bpow radix2 emax)). apply Rmult_le_compat.\napply Rle_0_1.\napply bpow_ge_0.\napply IZR_le. zify; omega.\neapply Rle_trans. eapply bpow_le. eassumption. apply bpow_log_pos; auto.\napply generic_format_FLT. exists (Float radix2 1 emax).\nunfold F2R; simpl. ring.\nsimpl. apply (Zpower_gt_1 radix2); auto.\nsimpl. unfold emin; red in prec_gt_0_; omega.\nQed.\n\nLemma round_NE_underflows:\nforall x,\n(0 <= x <= bpow radix2 (emin - 1))%R ->\nround radix2 fexp (round_mode mode_NE) x = 0%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.round_NE_underflows\".\nintros.\nset (eps := bpow radix2 (emin - 1)) in *.\nassert (A: round radix2 fexp (round_mode mode_NE) eps = 0%R).\n{ unfold round. simpl.\nassert (E: cexp radix2 fexp eps = emin).\n{ unfold cexp, eps. rewrite mag_bpow. unfold fexp, FLT_exp. zify; red in prec_gt_0_; omega. }\nunfold scaled_mantissa; rewrite E.\nassert (P: (eps * bpow radix2 (-emin) = / 2)%R).\n{ unfold eps. rewrite <- bpow_plus. replace (emin - 1 + -emin) with (-1) by omega. auto. }\nrewrite P. unfold Znearest.\nassert (F: Zfloor (/ 2)%R = 0).\n{ apply Zfloor_imp. simpl. lra. }\nrewrite F. rewrite Rminus_0_r. rewrite Rcompare_Eq by auto.\nsimpl. unfold F2R; simpl. apply Rmult_0_l.\n}\napply Rle_antisym.\n- rewrite <- A. apply round_le. apply fexp_correct; auto. apply valid_rnd_round_mode. tauto.\n- rewrite <- (round_0 radix2 fexp (round_mode mode_NE)).\napply round_le. apply fexp_correct; auto. apply valid_rnd_round_mode. tauto.\nQed.\n\nLemma round_integer_underflow:\nforall (base: radix) e m,\ne < 0 ->\ne * Z.log2 base + Z.log2_up (Zpos m) < emin ->\nround radix2 fexp (round_mode mode_NE) (IZR (Zpos m) * bpow base e) = 0%R.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.round_integer_underflow\".\nintros. apply round_NE_underflows. split.\n- apply Rmult_le_pos. apply IZR_le. zify; omega. apply bpow_ge_0.\n- apply Rle_trans with (bpow radix2 (Z.log2_up (Z.pos m) + e * Z.log2 base)).\n+ rewrite bpow_plus. apply Rmult_le_compat.\napply IZR_le; zify; omega.\napply bpow_ge_0.\nrewrite <- IZR_Zpower. apply IZR_le.\ndestruct (Z.eq_dec (Z.pos m) 1).\nrewrite e0. simpl. omega.\napply Z.log2_up_spec. zify; omega.\napply Z.log2_up_nonneg.\napply bpow_log_neg. auto.\n+ apply bpow_le. omega.\nQed.\n\n\n\nTheorem Bparse_correct:\nforall b m e (BASE: 2 <= Zpos b),\nlet base := {| radix_val := Zpos b; radix_prop := Zle_imp_le_bool _ _ BASE |} in\nlet r := round radix2 fexp (round_mode mode_NE) (IZR (Zpos m) * bpow base e) in\nif Rlt_bool (Rabs r) (bpow radix2 emax) then\nB2R _ _ (Bparse b m e) = r\n/\\ is_finite _ _ (Bparse b m e) = true\n/\\ Bsign _ _ (Bparse b m e) = false\nelse\nB2FF _ _ (Bparse b m e) = F754_infinity false.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bparse_correct\".\nintros.\nassert (A: forall x, @F2R radix2 {| Fnum := x; Fexp := 0 |} = IZR x).\n{ intros. unfold F2R, Fnum; simpl. ring. }\nunfold Bparse, r. destruct e as [ | e | e].\n-\nchange (bpow base 0) with 1%R. rewrite Rmult_1_r.\nexact (BofZ_correct (Z.pos m)).\n-\ndestruct (Z.ltb_spec (Z.pos e * Z.log2 (Z.pos b)) emax).\n+\nrewrite pos_pow_spec. rewrite <- IZR_Zpower by (zify; omega). rewrite <- mult_IZR.\nreplace false with (Z.pos m * Z.pos b ^ Z.pos e <? 0).\nexact (BofZ_correct (Z.pos m * Z.pos b ^ Z.pos e)).\nrewrite Z.ltb_ge. rewrite Z.mul_comm. apply Zmult_gt_0_le_0_compat. zify; omega.  apply (Zpower_ge_0 base).\n+\nrewrite Rlt_bool_false. auto. eapply Rle_trans; [idtac|apply Rle_abs].\napply (round_integer_overflow base). zify; omega. auto.\n-\ndestruct (Z.ltb_spec (Z.neg e * Z.log2 (Z.pos b) + Z.log2_up (Z.pos m)) emin).\n+\nrewrite round_integer_underflow; auto.\nrewrite Rlt_bool_true. auto.\nreplace (Rabs 0)%R with 0%R. apply bpow_gt_0. apply (abs_IZR 0).\nzify; omega.\n+\ngeneralize (Bdiv_correct_aux prec emax prec_gt_0_ Hmax mode_NE false m 0 false (pos_pow b e) 0).\nset (f := let '(mz, ez, lz) := Fdiv_core_binary prec emax (Z.pos m) 0 (Z.pos (pos_pow b e)) 0\nin binary_round_aux prec emax mode_NE (xorb false false) mz ez lz).\nfold emin; fold fexp. rewrite ! A. unfold cond_Zopp. rewrite pos_pow_spec.\nassert (B: (IZR (Z.pos m) / IZR (Z.pos b ^ Z.pos e) =\nIZR (Z.pos m) * bpow base (Z.neg e))%R).\n{ change (Z.neg e) with (- (Z.pos e)). rewrite bpow_opp. auto. }\nrewrite B. intros [P Q].\ndestruct (Rlt_bool\n(Rabs\n(round radix2 fexp (round_mode mode_NE)\n(IZR (Z.pos m) * bpow base (Z.neg e))))\n(bpow radix2 emax)).\n* destruct Q as (Q1 & Q2 & Q3).\nsplit. rewrite B2R_FF2B, Q1. auto.\nsplit. rewrite is_finite_FF2B. auto.\nrewrite Bsign_FF2B. auto.\n* rewrite B2FF_FF2B. auto.\nQed.\n\nEnd Extra_ops.\n\n\n\nSection Conversions.\n\nVariable prec1 emax1 prec2 emax2 : Z.\nContext (prec1_gt_0_ : Prec_gt_0 prec1) (prec2_gt_0_ : Prec_gt_0 prec2).\nLet emin1 := (3 - emax1 - prec1)%Z.\nLet fexp1 := FLT_exp emin1 prec1.\nLet emin2 := (3 - emax2 - prec2)%Z.\nLet fexp2 := FLT_exp emin2 prec2.\nHypothesis Hmax1 : (prec1 < emax1)%Z.\nHypothesis Hmax2 : (prec2 < emax2)%Z.\nLet binary_float1 := binary_float prec1 emax1.\nLet binary_float2 := binary_float prec2 emax2.\n\nDefinition Bconv (conv_nan: binary_float1 -> {x | is_nan prec2 emax2 x = true}) (md: mode) (f: binary_float1) : binary_float2 :=\nmatch f with\n| B754_nan _ _ _ _ _ => build_nan prec2 emax2 (conv_nan f)\n| B754_infinity _ _ s => B754_infinity _ _ s\n| B754_zero _ _ s => B754_zero _ _ s\n| B754_finite _ _ s m e _ => binary_normalize _ _ _ Hmax2 md (cond_Zopp s (Zpos m)) e s\nend.\n\nTheorem Bconv_correct:\nforall conv_nan m f,\nis_finite _ _ f = true ->\nif Rlt_bool (Rabs (round radix2 fexp2 (round_mode m) (B2R _ _ f))) (bpow radix2 emax2)\nthen\nB2R _ _ (Bconv conv_nan m f) = round radix2 fexp2 (round_mode m) (B2R _ _ f)\n/\\ is_finite _ _ (Bconv conv_nan m f) = true\n/\\ Bsign _ _ (Bconv conv_nan m f) = Bsign _ _ f\nelse\nB2FF _ _ (Bconv conv_nan m f) = binary_overflow prec2 emax2 m (Bsign _ _ f).\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bconv_correct\".\nintros. destruct f as [sf|sf|sf pf Hf|sf mf ef Hf]; try discriminate.\n- simpl. rewrite round_0. rewrite Rabs_R0. rewrite Rlt_bool_true. auto.\napply bpow_gt_0. apply valid_rnd_round_mode.\n- generalize (binary_normalize_correct _ _ _ Hmax2 m (cond_Zopp sf (Zpos mf)) ef sf).\nfold emin2; fold fexp2. simpl. destruct Rlt_bool.\n+ intros (A & B & C). split. auto. split. auto. rewrite C.\ndestruct sf; simpl.\nrewrite Rcompare_Lt. auto. apply F2R_lt_0. simpl. compute; auto.\nrewrite Rcompare_Gt. auto. apply F2R_gt_0. simpl. compute; auto.\n+ intros A. rewrite A. f_equal. destruct sf.\napply Rlt_bool_true. apply F2R_lt_0. simpl. compute; auto.\napply Rlt_bool_false. apply Rlt_le. apply Rgt_lt. apply F2R_gt_0. simpl. compute; auto.\nQed.\n\n\n\nTheorem Bconv_widen_exact:\n(prec2 >= prec1)%Z -> (emax2 >= emax1)%Z ->\nforall conv_nan m f,\nis_finite _ _ f = true ->\nB2R _ _ (Bconv conv_nan m f) = B2R _ _ f\n/\\ is_finite _ _ (Bconv conv_nan m f) = true\n/\\ Bsign _ _ (Bconv conv_nan m f) = Bsign _ _ f.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bconv_widen_exact\".\nintros PREC EMAX; intros. generalize (Bconv_correct conv_nan m f H).\nassert (LT: (Rabs (B2R _ _ f) < bpow radix2 emax2)%R).\n{\ndestruct f; try discriminate; simpl.\nrewrite Rabs_R0. apply bpow_gt_0.\napply Rlt_le_trans with (bpow radix2 emax1).\nrewrite F2R_cond_Zopp. rewrite abs_cond_Ropp. rewrite <- F2R_Zabs. simpl Z.abs.\neapply bounded_lt_emax; eauto.\napply bpow_le. omega.\n}\nassert (EQ: round radix2 fexp2 (round_mode m) (B2R prec1 emax1 f) = B2R prec1 emax1 f).\n{\napply round_generic. apply valid_rnd_round_mode. eapply generic_inclusion_le.\n5: apply generic_format_B2R. apply fexp_correct; auto. apply fexp_correct; auto.\ninstantiate (1 := emax2). intros. unfold fexp2, FLT_exp. unfold emin2. zify; omega.\napply Rlt_le; auto.\n}\nrewrite EQ. rewrite Rlt_bool_true by auto. auto.\nQed.\n\n\n\nTheorem Bconv_BofZ:\nforall conv_nan n,\ninteger_representable prec1 emax1 n ->\nBconv conv_nan mode_NE (BofZ prec1 emax1 _ Hmax1 n) = BofZ prec2 emax2 _ Hmax2 n.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bconv_BofZ\".\nintros.\ndestruct (BofZ_representable _ _ _ Hmax1 n H) as (A & B & C).\nset (f := BofZ prec1 emax1 prec1_gt_0_ Hmax1 n) in *.\ngeneralize (Bconv_correct conv_nan mode_NE f B).\nunfold BofZ.\ngeneralize (binary_normalize_correct _ _ _ Hmax2 mode_NE n 0 false).\nfold emin2; fold fexp2. rewrite A.\nreplace (F2R {| Fnum := n; Fexp := 0 |}) with (IZR n).\ndestruct Rlt_bool.\n- intros (P & Q & R) (D & E & F). apply B2R_Bsign_inj; auto.\ncongruence. rewrite F, C, R. rewrite Rcompare_IZR.\nunfold Z.ltb. auto.\n- intros P Q. apply B2FF_inj. rewrite P, Q. rewrite C. f_equal.\ngeneralize (Zlt_bool_spec n 0); intros LT; inversion LT.\nrewrite Rlt_bool_true; auto. apply IZR_lt; auto.\nrewrite Rlt_bool_false; auto. apply IZR_le; auto.\n- unfold F2R; simpl. rewrite Rmult_1_r. auto.\nQed.\n\n\n\nTheorem ZofB_Bconv:\nprec2 >= prec1 -> emax2 >= emax1 ->\nforall conv_nan m f n,\nZofB _ _ f = Some n -> ZofB _ _ (Bconv conv_nan m f) = Some n.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.ZofB_Bconv\".\nintros. rewrite ZofB_correct in H1. destruct (is_finite _ _ f) eqn:FIN; inversion H1.\ndestruct (Bconv_widen_exact H H0 conv_nan m f) as (A & B & C). auto.\nrewrite ZofB_correct. rewrite B. rewrite A. auto.\nQed.\n\nTheorem ZofB_range_Bconv:\nforall min1 max1 min2 max2,\nprec2 >= prec1 -> emax2 >= emax1 -> min2 <= min1 -> max1 <= max2 ->\nforall conv_nan m f n,\nZofB_range _ _ f min1 max1 = Some n ->\nZofB_range _ _ (Bconv conv_nan m f) min2 max2 = Some n.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.ZofB_range_Bconv\".\nintros.\ndestruct (ZofB_range_inversion _ _ _ _ _ _ H3) as (A & B & C).\nunfold ZofB_range. erewrite ZofB_Bconv by eauto.\nrewrite ! Zle_bool_true by omega. auto.\nQed.\n\n\n\nTheorem Bcompare_Bconv_widen:\nprec2 >= prec1 -> emax2 >= emax1 ->\nforall conv_nan m x y,\nBcompare _ _ (Bconv conv_nan m x) (Bconv conv_nan m y) = Bcompare _ _ x y.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bcompare_Bconv_widen\".\nintros. destruct (is_finite _ _ x && is_finite _ _ y) eqn:FIN.\n- apply andb_true_iff in FIN. destruct FIN.\ndestruct (Bconv_widen_exact H H0 conv_nan m x H1) as (A & B & C).\ndestruct (Bconv_widen_exact H H0 conv_nan m y H2) as (D & E & F).\nrewrite ! Bcompare_correct by auto. rewrite A, D. auto.\n- generalize (Bconv_widen_exact H H0 conv_nan m x)\n(Bconv_widen_exact H H0 conv_nan m y); intros P Q.\ndestruct x as [sx|sx|sx px Hx|sx mx ex Hx], y as [sy|sy|sy py Hy|sy my ey Hy]; try discriminate; simpl in P, Q; simpl;\nrepeat (match goal with |- context [conv_nan ?b ?pl] => destruct (conv_nan b pl) end);\nauto.\ndestruct Q as (D & E & F); auto.\nnow destruct binary_normalize.\ndestruct P as (A & B & C); auto.\nnow destruct binary_normalize.\ndestruct P as (A & B & C); auto.\nnow destruct binary_normalize.\nQed.\n\nEnd Conversions.\n\nSection Compose_Conversions.\n\nVariable prec1 emax1 prec2 emax2 : Z.\nContext (prec1_gt_0_ : Prec_gt_0 prec1) (prec2_gt_0_ : Prec_gt_0 prec2).\nLet emin1 := (3 - emax1 - prec1)%Z.\nLet fexp1 := FLT_exp emin1 prec1.\nLet emin2 := (3 - emax2 - prec2)%Z.\nLet fexp2 := FLT_exp emin2 prec2.\nHypothesis Hmax1 : (prec1 < emax1)%Z.\nHypothesis Hmax2 : (prec2 < emax2)%Z.\nLet binary_float1 := binary_float prec1 emax1.\nLet binary_float2 := binary_float prec2 emax2.\n\n\nTheorem Bconv_narrow_widen:\nprec2 >= prec1 -> emax2 >= emax1 ->\nforall narrow_nan widen_nan m f,\nis_nan _ _ f = false ->\nBconv prec2 emax2 prec1 emax1 _ Hmax1 narrow_nan m (Bconv prec1 emax1 prec2 emax2 _ Hmax2 widen_nan m f) = f.\nProof. hammer_hook \"IEEE754_extra\" \"IEEE754_extra.Bconv_narrow_widen\".\nintros. destruct (is_finite _ _ f) eqn:FIN.\n- assert (EQ: round radix2 fexp1 (round_mode m) (B2R prec1 emax1 f) = B2R prec1 emax1 f).\n{ apply round_generic. apply valid_rnd_round_mode. apply generic_format_B2R. }\ngeneralize (Bconv_widen_exact _ _ _ _ _ _ Hmax2 H H0 widen_nan m f FIN).\nset (f' := Bconv prec1 emax1 prec2 emax2 _ Hmax2 widen_nan m f).\nintros (A & B & C).\ngeneralize (Bconv_correct _ _ _ _ _ Hmax1 narrow_nan m f' B).\nfold emin1. fold fexp1. rewrite A, C, EQ. rewrite Rlt_bool_true.\nintros (D & E & F).\napply B2R_Bsign_inj; auto.\ndestruct f; try discriminate; simpl.\nrewrite Rabs_R0. apply bpow_gt_0.\nrewrite F2R_cond_Zopp. rewrite abs_cond_Ropp. rewrite <- F2R_Zabs. simpl Z.abs.\neapply bounded_lt_emax; eauto.\n- destruct f; try discriminate. simpl. auto.\nQed.\n\nEnd Compose_Conversions.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/compcert/IEEE754_extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.24399278040385788}}
{"text": "\nRequire Import VST.floyd.proofauto.\nRequire Import listcopy.\nFrom SSL_VST Require Import core.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition malloc_spec :=\n  DECLARE _malloc\n        WITH t: type\n        PRE [ tuint ]\n        PROP()\n        PARAMS(Vint (Int.repr (sizeof t)))\n        SEP()\n        POST [tptr tvoid] EX p:_,\n        PROP()\n        RETURN(p)\n        SEP(data_at_ Tsh t p).\n\nInductive lseg_card : Set :=\n    | lseg_card_0 : lseg_card\n    | lseg_card_1 : lseg_card -> lseg_card.\n\nFixpoint lseg (x: val) (s: (list Z)) (self_card: lseg_card) {struct self_card} : mpred := match self_card with\n    | lseg_card_0  =>  !!((x : val) = nullval) && !!((s : list Z) = ([] : list Z)) && emp\n    | lseg_card_1 _alpha_513 => \n      EX v : Z,\n      EX s1 : (list Z),\n      EX nxt : val,\n !!(Int.min_signed <= v <= Int.max_signed) && !!(is_pointer_or_null nxt) && !!(~ ((x : val) = nullval)) && !!((s : list Z) = (([(v : Z)] : list Z) ++ (s1 : list Z))) && (data_at Tsh (tarray (Tunion _sslval noattr) 2) [(inl ((Vint (Int.repr v)) : val)); (inr (nxt : val))] (x : val)) * (lseg (nxt : val) (s1 : list Z) (_alpha_513 : lseg_card))\nend.\n\nInductive lseg2_card : Set :=\n    | lseg2_card_0 : lseg2_card\n    | lseg2_card_1 : lseg2_card -> lseg2_card.\n\nFixpoint lseg2 (x: val) (y: val) (s: (list Z)) (self_card: lseg2_card) {struct self_card} : mpred := match self_card with\n    | lseg2_card_0  =>  !!((x : val) = (y : val)) && !!((s : list Z) = ([] : list Z)) && emp\n    | lseg2_card_1 _alpha_514 => \n      EX v : Z,\n      EX s1 : (list Z),\n      EX nxt : val,\n !!(Int.min_signed <= v <= Int.max_signed) && !!(is_pointer_or_null nxt) && !!(~ ((x : val) = (y : val))) && !!((s : list Z) = (([(v : Z)] : list Z) ++ (s1 : list Z))) && (data_at Tsh (tarray (Tunion _sslval noattr) 2) [(inl ((Vint (Int.repr v)) : val)); (inr (nxt : val))] (x : val)) * (lseg2 (nxt : val) (y : val) (s1 : list Z) (_alpha_514 : lseg2_card))\nend.\n\n\nDefinition listcopy_spec :=\n  DECLARE _listcopy\n   WITH r: val, x: val, s: (list Z), _alpha_515: lseg_card\n   PRE [ (tptr (Tunion _sslval noattr)) ]\n   PROP( is_pointer_or_null((r : val)); is_pointer_or_null((x : val)) )\n   PARAMS(r)\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inr (x : val))] (r : val)); (lseg (x : val) (s : list Z) (_alpha_515 : lseg_card)))\n   POST[ tvoid ]\n   EX y: val,\n   EX _alpha_516: lseg_card,\n   EX _alpha_517: lseg_card,\n   PROP( is_pointer_or_null((y : val)) )\n   LOCAL()\n   SEP ((data_at Tsh (tarray (Tunion _sslval noattr) 1) [(inr (y : val))] (r : val)); (lseg (x : val) (s : list Z) (_alpha_516 : lseg_card)); (lseg (y : val) (s : list Z) (_alpha_517 : lseg_card))).\n\nLemma lseg_x_valid_pointerP x s self_card: lseg x s self_card |-- valid_pointer x. Proof. destruct self_card; simpl; entailer;  entailer!; eauto. Qed.\nHint Resolve lseg_x_valid_pointerP : valid_pointer.\nLemma lseg_local_factsP x s self_card :\n  lseg x s self_card|-- !!(((((x : val) = nullval)) -> (self_card = lseg_card_0))/\\(((~ ((x : val) = nullval))) -> (exists _alpha_513, self_card = lseg_card_1 _alpha_513))/\\is_pointer_or_null((x : val))).\n Proof.  destruct self_card;  simpl; entailer; saturate_local; apply prop_right; eauto. Qed.\nHint Resolve lseg_local_factsP : saturate_local.\nLemma unfold_lseg_card_0  (x: val) (s: (list Z)) : lseg x s (lseg_card_0 ) =  !!((x : val) = nullval) && !!((s : list Z) = ([] : list Z)) && emp. Proof. auto. Qed.\nLemma unfold_lseg_card_1 (_alpha_513 : lseg_card) (x: val) (s: (list Z)) : lseg x s (lseg_card_1 _alpha_513) = \n      EX v : Z,\n      EX s1 : (list Z),\n      EX nxt : val,\n !!(Int.min_signed <= v <= Int.max_signed) && !!(is_pointer_or_null nxt) && !!(~ ((x : val) = nullval)) && !!((s : list Z) = (([(v : Z)] : list Z) ++ (s1 : list Z))) && (data_at Tsh (tarray (Tunion _sslval noattr) 2) [(inl ((Vint (Int.repr v)) : val)); (inr (nxt : val))] (x : val)) * (lseg (nxt : val) (s1 : list Z) (_alpha_513 : lseg_card)). Proof. auto. Qed.\nLemma lseg2_local_factsP x y s self_card :\n  lseg2 x y s self_card|-- !!(((((x : val) = (y : val))) -> (self_card = lseg2_card_0))/\\(((~ ((x : val) = (y : val)))) -> (exists _alpha_514, self_card = lseg2_card_1 _alpha_514))).\n Proof.  destruct self_card;  simpl; entailer; saturate_local; apply prop_right; eauto. Qed.\nHint Resolve lseg2_local_factsP : saturate_local.\nLemma unfold_lseg2_card_0  (x: val) (y: val) (s: (list Z)) : lseg2 x y s (lseg2_card_0 ) =  !!((x : val) = (y : val)) && !!((s : list Z) = ([] : list Z)) && emp. Proof. auto. Qed.\nLemma unfold_lseg2_card_1 (_alpha_514 : lseg2_card) (x: val) (y: val) (s: (list Z)) : lseg2 x y s (lseg2_card_1 _alpha_514) = \n      EX v : Z,\n      EX s1 : (list Z),\n      EX nxt : val,\n !!(Int.min_signed <= v <= Int.max_signed) && !!(is_pointer_or_null nxt) && !!(~ ((x : val) = (y : val))) && !!((s : list Z) = (([(v : Z)] : list Z) ++ (s1 : list Z))) && (data_at Tsh (tarray (Tunion _sslval noattr) 2) [(inl ((Vint (Int.repr v)) : val)); (inr (nxt : val))] (x : val)) * (lseg2 (nxt : val) (y : val) (s1 : list Z) (_alpha_514 : lseg2_card)). Proof. auto. Qed.\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [listcopy_spec; malloc_spec]).\n\nLemma body_listcopy : semax_body Vprog Gprog f_listcopy listcopy_spec.\nProof.\nstart_function.\nssl_open_context.\nassert_PROP (isptr r). { entailer!. }\ntry rename x into x2.\nforward.\nforward_if.\n\n - {\nassert_PROP (_alpha_515 = lseg_card_0) as ssl_card_assert. { entailer!; ssl_dispatch_card. }\nssl_card lseg ssl_card_assert .\nassert_PROP (((x2 : val) = nullval)). { entailer!. }\nlet ssl_var := fresh in assert_PROP(s = ([] : list Z)) as ssl_var; try rewrite ssl_var in *. { entailer!. }\nforward; entailer!.\nExists nullval.\nExists (lseg_card_0  : lseg_card).\nExists (lseg_card_0  : lseg_card).\nssl_entailer.\nrewrite (unfold_lseg_card_0 ) at 1.\nssl_entailer.\nrewrite (unfold_lseg_card_0 ) at 1.\nssl_entailer.\n\n}\n - {\nassert_PROP (exists _alpha_513, _alpha_515 = lseg_card_1 _alpha_513) as ssl_card_assert. { entailer!; ssl_dispatch_card. }\nssl_card lseg ssl_card_assert _alpha_513x2.\nassert_PROP ((~ ((x2 : val) = nullval))). { entailer!. }\nIntros vx2 s1x2 nxtx2.\nlet ssl_var := fresh in assert_PROP(s = (([(vx2 : Z)] : list Z) ++ (s1x2 : list Z))) as ssl_var; try rewrite ssl_var in *. { entailer!. }\ntry rename vx2 into vx22.\nforward.\ntry rename nxtx2 into nxtx22.\nforward.\nforward.\nassert_PROP(is_pointer_or_null((r : val))). { entailer!. }\nassert_PROP(is_pointer_or_null((nxtx22 : val))). { entailer!. }\nforward_call ((r : val), (nxtx22 : val), (s1x2 : list Z), (_alpha_513x2 : lseg_card)).\nlet ret := fresh vret in Intros ret; destruct ret as [[y1 _alpha_5161] _alpha_5171].\nassert_PROP(is_pointer_or_null((nxtx22 : val))). { entailer!. }\nassert_PROP(is_pointer_or_null((y1 : val))). { entailer!. }\ntry rename y1 into y12.\nforward.\nforward_call (tarray (Tunion _sslval noattr) 2).\nIntros y2.\nassert_PROP (isptr y2). { entailer!. }\nforward.\nforward.\nforward.\nforward; entailer!.\nExists (y2 : val).\nExists (lseg_card_1 (_alpha_5161 : lseg_card) : lseg_card).\nExists (lseg_card_1 (_alpha_5171 : lseg_card) : lseg_card).\nssl_entailer.\nrewrite (unfold_lseg_card_1 (_alpha_5161 : lseg_card)) at 1.\nExists (vx22 : Z).\nExists (s1x2 : list Z).\nExists (nxtx22 : val).\nssl_entailer.\nrewrite (unfold_lseg_card_1 (_alpha_5171 : lseg_card)) at 1.\nExists (vx22 : Z).\nExists (s1x2 : list Z).\nExists (y12 : val).\nssl_entailer.\n\n}\nQed.", "meta": {"author": "TyGuS", "repo": "ssl-vst", "sha": "638107b15e18608ef364ae1d900eb2d2aaf8a475", "save_path": "github-repos/coq/TyGuS-ssl-vst", "path": "github-repos/coq/TyGuS-ssl-vst/ssl-vst-638107b15e18608ef364ae1d900eb2d2aaf8a475/examples/verif_listcopy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.24397418769957563}}
{"text": "Require Import Coq.Strings.String Coq.Arith.Arith\n        Fiat.QueryStructure.Implementation.DataStructures.Bags.BagsInterface\n        Fiat.Common.Ensembles.IndexedEnsembles\n        Fiat.QueryStructure.Specification.Representation.QueryStructureNotations\n        Fiat.QueryStructure.Implementation.ListImplementation\n        Fiat.QueryStructure.Implementation.DataStructures.Bags.BagsOfTuples\n        Fiat.QueryStructure.Implementation.Operations.General.EmptyRefinements\n        Fiat.Common.List.ListFacts.\n\nLtac is_sumbool expr :=\n  match type of expr with\n    | (sumbool _ _) => idtac\n    | _ => fail\n  end.\n\nLtac unfold_functions expr :=\n  match expr with\n    | context [ ?f _ ] => unfold f\n  end.\n\nLtac destruct_ifs_inside conditional :=\n  match conditional with\n    | context [ if ?sub_conditional then _ else _ ] => destruct_ifs_inside sub_conditional\n    | _ => first [ is_sumbool conditional; destruct conditional | progress unfold_functions conditional ]\n  end.\n\nLtac destruct_ifs :=\n  intros;\n  repeat (match goal with\n            | [ |- ?body ] =>\n              destruct_ifs_inside body\n          end; simpl in *).\n\nLtac prove_extensional_eq :=\n  clear;\n  unfold ExtensionalEq;\n  destruct_ifs; first [ solve [intuition] | solve [exfalso; intuition] | idtac ].\n\nExample ifs_destruction :\n  forall w x y z,\n    (if (if string_dec w x then true else false) then (if eq_nat_dec y z then false else true) else (if eq_nat_dec z y then true else false)) = (if (if eq_nat_dec y z then true else false) then (if string_dec x w then false else true) else (if string_dec x w then true else false)).\nProof.\n  destruct_ifs; intuition.\nQed.\n\nLtac autoconvert func :=\n  match goal with\n    | [ src := cons ?head ?tail |- list _ ] =>\n      refine (func head _ :: _);\n        [ solve [ eauto with * ] | clear src;\n                            set (src := tail);\n                            autoconvert func ]\n    | [ src := nil |- list _ ] => apply []\n    | _ => idtac\n  end.\n\n(* [mkIndex] builds a [BagPlusProof] record packaging an indexed\n   with all its operations and proofs of correctness. *)\n\nLtac mkIndex heading attributes' :=\n  set (src := attributes');\n  assert (list (@ProperAttribute heading)) as decorated_source by autoconvert (@CheckType heading);\n  apply (@NestedTreeFromAttributesAsCorrectBagPlusProof heading decorated_source).\n\n\n Tactic Notation \"lift\" \"list\" \"property\" constr(prop) \"as\" ident(name) :=\n  pose proof prop as name;\n  setoid_rewrite EnsembleIndexedListEquivalence_lift_property in name;\n  [ | eassumption].\n\nTactic Notation \"call\" \"eapply\" constr(hypothesis) \"after\" tactic1(preprocessor) :=\n  first [ preprocessor; eapply hypothesis | eapply hypothesis ].\n\nTactic Notation\n       \"rewrite\" \"filter\" \"over\" reference(indexed_storage)\n       \"using\" \"search\" \"term\" constr(keyword) :=\n  match goal with\n    | [ H: EnsembleBagEquivalence ?bag_plus ?table ?storage\n        |- context [ filter ?filter1 (benumerate ?storage) ] ] =>\n      let temp := fresh in\n      let filter2 := constr:(bfind_matcher (Bag := BagPlus indexed_storage)\n                                           keyword) in\n          assert (ExtensionalEq filter1 filter2) as temp by prove_extensional_eq;\n            rewrite (filter_by_equiv filter1 filter2 temp);\n            clear temp\n      end.\n\nTactic Notation\n       \"rewrite\" \"dependent\" \"filter\" constr(filter1)\n       \"over\" reference(indexed_storage)\n       \"using\" \"dependent\" \"search\" \"term\" constr(keyword) :=\n  let temp := fresh in\n  let filter2 := constr:(fun x => bfind_matcher (Bag := BagPlus indexed_storage) (keyword x)) in\n  assert (forall x, ExtensionalEq (filter1 x) (filter2 x)) as temp by prove_extensional_eq;\n    setoid_rewrite (filter_by_equiv_meta filter1 filter2 temp);\n    clear temp.\n\n\n(* The following tactic is useful when we have a set of hypotheses\n     of the form\n\n     H0 : In DB tuple\n     H  : tupleAgree tuple <COL :: x, ...> COL\n     H' : forall tuple', In DB tuple' -> (tuple'!COL <> x)\n\n     which essentially means that we have a tuple that's in the DB and\n     matches another one on the COL column, and an hypothesis H' that\n     guarantees that such a match is in fact impossible. In that case,\n     it's essentially enough to call exfalso, which this tactic does\n *)\n\nTactic Notation \"prove\" \"trivial\" \"constraints\" :=\n  unfold decides, not in *;\n  intros;\n  match goal with\n    | [ H: tupleAgree _ _ (?column :: _) |- _ ] =>\n      specialize (H column);\n        exfalso;\n        match goal with\n          | [ H': _ |- _] =>\n            eapply H';\n              try eassumption;\n              call eapply H after symmetry;\n              simpl;\n              auto\n        end\n  end.\n\nDefinition ID {A} := fun (x: A) => x.\n\nLemma ens_red {heading}\n      {BagType TSearchTerm TUpdateTerm} :\n  forall (y_is_bag: Bag BagType (@Tuple heading) TSearchTerm TUpdateTerm) x y,\n    @EnsembleIndexedListEquivalence (@Tuple heading) x (benumerate (Bag := y_is_bag) y) =\n    (ID (fun y => EnsembleIndexedListEquivalence x (benumerate y))) y.\nProof.\n  intros; reflexivity.\nQed.\n\nLemma EnsembleBagEquivalence_pick_new_index {heading} :\n  forall storage (ens : Ensemble (@IndexedTuple heading)) seq,\n    EnsembleBagEquivalence storage ens seq ->\n    exists bound, UnConstrFreshIdx ens bound.\nProof.\n  intros * (indexes & equiv) ** ;\n  eapply EnsembleIndexedListEquivalence_pick_new_index; eauto.\n  apply indexes.\nQed.\n\nLemma refine_bag_update_other_table :\n  forall (db_schema : QueryStructureSchema) (qs : UnConstrQueryStructure db_schema)\n         (index1 index2 : Fin.t _) bag_store store Rel,\n    EnsembleBagEquivalence bag_store (GetUnConstrRelation qs index2) store ->\n    index1 <> index2 ->\n      EnsembleBagEquivalence bag_store\n                             (GetUnConstrRelation\n                                (UpdateUnConstrRelation qs index1 Rel) index2)\n                             store.\nProof.\n  intros; rewrite get_update_unconstr_neq; eauto.\nQed.\n\nLtac refine_bag_update_other_table :=\n  match goal with\n    | [ |- context [\n               EnsembleBagEquivalence\n                 ?bag\n                 (GetUnConstrRelation\n                    (UpdateUnConstrRelation ?qs ?index1 ?Rel) ?index2) ] ] =>\n      apply (@refine_bag_update_other_table _ qs index1 index2 bag);\n        [ eauto | intuition discriminate ]\n  end.\n\n(* Workaround Coq's algorithms not being able to infer ther arguments to refineEquiv_pick_pair *)\nLtac refineEquiv_pick_pair_benumerate :=\n  setoid_rewrite refineEquiv_pick_pair;\n  unfold ID; cbv beta.\n\nLtac snd_bdelete_correct search_term :=\n  match goal with\n      H : EnsembleBagEquivalence ?bag_plus (GetUnConstrRelation ?Rel' ?Ridx) ?bag\n      |- EnsembleBagEquivalence\n           ?bag_plus\n           (GetUnConstrRelation\n              (UpdateUnConstrRelation\n                 ?Rel ?Ridx\n                 (EnsembleDelete (GetUnConstrRelation ?Rel' ?Ridx) ?DeletedTuples))\n              ?Ridx) _ =>\n      eapply (@bdeletePlus_correct_DB_snd _ Rel Ridx bag_plus bag H DeletedTuples _ search_term);\n        prove_extensional_eq\n  end.\n\nLtac binsert_correct_DB :=\n  match goal with\n    | [ H: EnsembleBagEquivalence ?bag_plus\n                                  (GetUnConstrRelation ?qs ?index)\n                                  ?store,\n        H0 : UnConstrFreshIdx (GetUnConstrRelation ?qs ?index) ?bound |- _ ] =>\n      solve [ simpl; apply (binsertPlus_correct_DB qs index bag_plus store H _ bound H0) ]\n  end.\n\n(*Lemma refine_Perm_map\n      {TItem A}\n      {BagPl : BagPlusProof TItem}\n:\n  forall search_term b f,\n    refine {l' : list A |\n            Permutation\n              (map f (filter (bfind_matcher (Bag := BagPlus BagPl) search_term)\n                             (benumerate (Bag := BagPlus BagPl) b))) l' }\n           {l' : list A |\n            Permutation\n              (map f (bfind (Bag := BagPlus BagPl) b search_term)) l' }.\n    Admitted.\n\nTactic Notation \"replace\" \"filter\" \"enumerate\" constr(storage) :=\n    match goal with\n        |- context[map ?f (filter (bfind_matcher ?search_term)\n                                  (benumerate ?bag))] =>\n        rewrite (@refine_Perm_map _ _ storage search_term bag f)\n    end. *)\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/QueryStructure/Implementation/DataStructures/Bags/BagsTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.2439741813327489}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\nRequire Import VerdiRaft.CommonTheorems.\n\nRequire Import VerdiRaft.RequestVoteMaxIndexMaxTermInterface.\nRequire Import VerdiRaft.RequestVoteReplyTermSanityInterface.\nRequire Import VerdiRaft.VotedForMoreUpToDateInterface.\n\nRequire Import VerdiRaft.RequestVoteReplyMoreUpToDateInterface.\n\nSection RequestVoteReplyMoreUpToDate.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n  Context {rvmimti : requestVote_maxIndex_maxTerm_interface}.\n  Context {rvrtsi : requestVoteReply_term_sanity_interface}.\n  Context {vfmutdi : votedFor_moreUpToDate_interface}.\n  \n  Lemma requestVoteReply_moreUpToDate_append_entries :\n    refined_raft_net_invariant_append_entries requestVoteReply_moreUpToDate.\n  Proof using. \n    red. unfold requestVoteReply_moreUpToDate. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    assert (In p0 (nwPackets net)) by\n        (find_apply_hyp_hyp; repeat find_rewrite; intuition; [in_crush|];\n         exfalso; subst; simpl in *; subst;\n         unfold handleAppendEntries in *;\n           repeat break_match; find_inversion).\n    repeat find_rewrite.\n    destruct_update; simpl in *; eauto;\n    try rewrite votesWithLog_same_append_entries; eauto;\n    find_apply_lem_hyp handleAppendEntries_log_term_type;\n    intuition; repeat find_rewrite; try congruence;\n    eauto.\n  Qed.\n\n  Lemma requestVoteReply_moreUpToDate_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply requestVoteReply_moreUpToDate.\n  Proof using. \n    red. unfold requestVoteReply_moreUpToDate. intros. simpl in *.\n    assert (In p0 (nwPackets net)) by\n        (repeat find_rewrite;\n         find_apply_lem_hyp handleAppendEntriesReply_packets;\n         subst; simpl in *; find_apply_hyp_hyp; intuition; in_crush).\n    repeat find_rewrite.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_votesReceived.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_log_term_type.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    intuition; try congruence; repeat find_rewrite; eauto.\n  Qed.\n  \n  Lemma requestVoteReply_moreUpToDate_request_vote :\n    refined_raft_net_invariant_request_vote requestVoteReply_moreUpToDate.\n  Proof using vfmutdi rvmimti. \n    red. unfold requestVoteReply_moreUpToDate. intros. simpl in *.\n    find_copy_apply_lem_hyp handleRequestVote_votesReceived.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto. \n    - find_copy_apply_lem_hyp handleRequestVote_log_term_type; intuition; try congruence.\n      repeat find_rewrite.\n      find_apply_hyp_hyp. intuition.\n      + assert (In p0 (nwPackets net)) by (repeat find_rewrite; in_crush).\n        repeat find_rewrite.\n        eapply_prop_hyp pBody pBody; eauto.\n        break_exists_exists. intuition.\n        eauto using update_elections_data_request_vote_votesWithLog_old.\n      + remember (pSrc p0) as h.\n        subst_max. simpl in *. subst_max.\n        find_copy_apply_lem_hyp handleRequestVote_reply_true.\n        find_eapply_lem_hyp update_elections_data_request_vote_votedFor; eauto;\n        intuition; eauto; repeat find_rewrite.\n        * find_eapply_lem_hyp votedFor_moreUpToDate_invariant; eauto.\n          repeat conclude_using eauto.\n          break_exists_exists; intuition; eauto using update_elections_data_request_vote_votesWithLog_old.\n        * find_apply_lem_hyp requestVote_maxIndex_maxTerm_invariant.\n          eapply_prop_hyp requestVote_maxIndex_maxTerm pBody; eauto.\n          concludes. intuition; subst.\n          eexists; intuition; eauto.\n    - find_copy_apply_lem_hyp handleRequestVote_log_term_type; intuition; try congruence.\n      repeat find_rewrite.\n      find_apply_hyp_hyp. intuition.\n      + assert (In p0 (nwPackets net)) by (repeat find_rewrite; in_crush).\n        repeat find_rewrite.\n        eapply_prop_hyp pBody pBody; eauto.\n      + remember (pDst p0) as h.\n        subst_max. simpl in *. subst_max.\n        find_copy_apply_lem_hyp handleRequestVote_reply_true. intuition.\n    - find_apply_hyp_hyp; intuition.\n      + assert (In p0 (nwPackets net)) by (repeat find_rewrite; in_crush).\n        repeat find_rewrite.\n        eapply_prop_hyp pBody pBody; eauto.\n        break_exists_exists. intuition.\n        eauto using update_elections_data_request_vote_votesWithLog_old.\n      + remember (pSrc p0) as h.\n        subst. simpl in *. subst.\n        find_copy_apply_lem_hyp handleRequestVote_reply_true. intuition.\n        find_eapply_lem_hyp update_elections_data_request_vote_votedFor; eauto.\n        intuition; repeat find_rewrite; eauto.\n        * find_copy_apply_lem_hyp votedFor_moreUpToDate_invariant.\n          eapply_prop_hyp votedFor_moreUpToDate RaftState.votedFor; eauto.\n          concludes.\n          break_exists_exists; intuition; eauto using update_elections_data_request_vote_votesWithLog_old.\n        * find_apply_lem_hyp requestVote_maxIndex_maxTerm_invariant.\n          eapply_prop_hyp requestVote_maxIndex_maxTerm pBody; eauto.\n          concludes. intuition; subst.\n          eexists; intuition; eauto.\n    - find_apply_hyp_hyp. intuition.\n      + assert (In p0 (nwPackets net)) by (repeat find_rewrite; in_crush).\n        repeat find_rewrite.\n        eapply_prop_hyp pBody pBody; eauto.\n      + subst. simpl in *. subst. simpl in *.\n        find_copy_apply_lem_hyp handleRequestVote_reply_true. intuition.\n  Qed.\n\n  Lemma requestVoteReply_moreUpToDate_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply requestVoteReply_moreUpToDate.\n  Proof using. \n    red. unfold requestVoteReply_moreUpToDate. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    - erewrite handleRequestVoteReply_log; eauto.\n      find_copy_eapply_lem_hyp handleRequestVoteReply_log_term_type; eauto.\n      intuition.\n      repeat find_rewrite.\n      rewrite update_elections_data_request_vote_reply_votesWithLog.\n      eauto.\n    - erewrite handleRequestVoteReply_log; eauto.\n      find_copy_eapply_lem_hyp handleRequestVoteReply_log_term_type; eauto.\n      intuition.\n      repeat find_rewrite. eauto.\n    - rewrite update_elections_data_request_vote_reply_votesWithLog.\n      eauto.\n  Qed.\n\n  Lemma requestVoteReply_moreUpToDate_timeout :\n    refined_raft_net_invariant_timeout requestVoteReply_moreUpToDate.\n  Proof using rvrtsi. \n    red. unfold requestVoteReply_moreUpToDate. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    - find_eapply_lem_hyp update_elections_data_timeout_votesWithLog_votesReceived; eauto.\n      intuition; try congruence.\n      repeat find_rewrite. simpl in *. intuition. subst.\n      exists (log d). intuition. auto using moreUpToDate_refl.\n    - find_copy_eapply_lem_hyp update_elections_data_timeout_votesWithLog_votesReceived; eauto.\n      intuition; try congruence.\n      repeat find_rewrite. simpl in *.\n      find_eapply_lem_hyp requestVoteReply_term_sanity_invariant; eauto;\n      unfold raft_data in *; simpl in *;\n      unfold raft_data in *; simpl in *; try lia; [idtac].\n      find_apply_hyp_hyp. intuition.\n      exfalso.\n      do_in_map.\n      remember (pDst p) as h. subst p. simpl in *.\n      unfold handleTimeout, tryToBecomeLeader in *.\n      repeat break_match; find_inversion; simpl in *; intuition.\n    - find_apply_hyp_hyp.\n      intuition.\n      + eapply_prop_hyp pBody pBody; eauto.\n        break_exists_exists; intuition; eauto using update_elections_data_timeout_votesWithLog_old.\n      + exfalso.\n        do_in_map. remember (pSrc p).\n        subst p. simpl in *.\n        unfold handleTimeout, tryToBecomeLeader in *.\n        repeat break_match; find_inversion; simpl in *; intuition;\n        do_in_map; subst; simpl in *; congruence.\n    - find_apply_hyp_hyp.\n      intuition.\n      + eapply_prop_hyp pBody pBody; eauto.\n      + exfalso.\n        do_in_map. remember (pSrc p).\n        subst p. simpl in *.\n        unfold handleTimeout, tryToBecomeLeader in *.\n        repeat break_match; find_inversion; simpl in *; intuition;\n        do_in_map; subst; simpl in *; congruence.\n  Qed.\n\n  Lemma requestVoteReply_moreUpToDate_client_request :\n    refined_raft_net_invariant_client_request requestVoteReply_moreUpToDate.\n  Proof using. \n    red. unfold requestVoteReply_moreUpToDate. intros. simpl in *.\n    find_copy_apply_lem_hyp handleClientRequest_packets.\n    subst. simpl in *.\n    find_apply_hyp_hyp. intuition.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    try rewrite votesWithLog_same_client_request; eauto;\n    find_apply_lem_hyp handleClientRequest_candidate; subst; eauto.\n  Qed.\n\n  Lemma requestVoteReply_moreUpToDate_do_leader :\n    refined_raft_net_invariant_do_leader requestVoteReply_moreUpToDate.\n  Proof using. \n    red. unfold requestVoteReply_moreUpToDate. intros. simpl in *.\n    assert (In p (nwPackets net)) by\n        (find_apply_hyp_hyp; intuition;\n         do_in_map; subst;\n         unfold doLeader, replicaMessage in *;\n           repeat break_match; find_inversion; subst; simpl in *; intuition;\n         do_in_map; subst; simpl in *; congruence).\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    find_apply_lem_hyp doLeader_candidate; subst; eauto.\n  Qed.\n  \n  Lemma requestVoteReply_moreUpToDate_do_generic_server :\n    refined_raft_net_invariant_do_generic_server requestVoteReply_moreUpToDate.\n  Proof using. \n    red. unfold requestVoteReply_moreUpToDate. intros. simpl in *.\n    find_copy_apply_lem_hyp doGenericServer_packets. subst. simpl in *.\n    find_apply_hyp_hyp. intuition.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    find_apply_lem_hyp doGenericServer_log_type_term_votesReceived;\n    intuition; repeat find_rewrite; eauto.\n  Qed.\n\n  Lemma requestVoteReply_moreUpToDate_reboot :\n    refined_raft_net_invariant_reboot requestVoteReply_moreUpToDate.\n  Proof using. \n    red. unfold requestVoteReply_moreUpToDate. intros. simpl in *.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto; congruence.\n  Qed.\n\n  Lemma requestVoteReply_moreUpToDate_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset requestVoteReply_moreUpToDate.\n  Proof using. \n    red. unfold requestVoteReply_moreUpToDate. intros. simpl in *.\n    subst. repeat find_reverse_higher_order_rewrite.\n    eauto.\n  Qed.\n\n  Lemma requestVoteReply_moreUpToDate_init :\n    refined_raft_net_invariant_init requestVoteReply_moreUpToDate.\n  Proof using. \n    red. unfold requestVoteReply_moreUpToDate. intros. simpl in *.\n    intuition.\n  Qed.\n  \n  Instance rvrmutdi : requestVoteReply_moreUpToDate_interface.\n  split.\n  intros.\n  apply refined_raft_net_invariant; auto.\n  - apply requestVoteReply_moreUpToDate_init.\n  - apply requestVoteReply_moreUpToDate_client_request.\n  - apply requestVoteReply_moreUpToDate_timeout.\n  - apply requestVoteReply_moreUpToDate_append_entries.\n  - apply requestVoteReply_moreUpToDate_append_entries_reply.\n  - apply requestVoteReply_moreUpToDate_request_vote.\n  - apply requestVoteReply_moreUpToDate_request_vote_reply.\n  - apply requestVoteReply_moreUpToDate_do_leader.\n  - apply requestVoteReply_moreUpToDate_do_generic_server.\n  - apply requestVoteReply_moreUpToDate_state_same_packet_subset.\n  - apply requestVoteReply_moreUpToDate_reboot.\n  Qed.\n  \nEnd RequestVoteReplyMoreUpToDate.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft-proofs/RequestVoteReplyMoreUpToDateProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24397417496592197}}
{"text": "Require Import List.\nRequire Import Arith.\nRequire Import StructTact.StructTactics.\nRequire Import StructTact.Util.\nRequire Import InfSeqExt.infseq.\nImport ListNotations.\n\nModule Type DynamicSystem.\n  Parameter addr : Type. (* must be finite, decidable *)\n  Parameter client_addr : addr -> Prop.\n  Parameter client_addr_dec : forall a : addr, {client_addr a} + {~ client_addr a}.\n  Parameter addr_eq_dec : forall x y : addr, {x = y} + {x <> y}.\n  Parameter payload : Type. (* must be serializable *)\n  Parameter payload_eq_dec : forall x y : payload, {x = y} + {x <> y}.\n  Parameter client_payload : payload -> Prop. (* holds for payloads that clients can send *)\n  Parameter client_payload_dec : forall p : payload, {client_payload p} + {~ client_payload p}.\n  Parameter data : Type.\n  Parameter timeout : Type.\n  Parameter timeout_eq_dec : forall x y : timeout, {x = y} + {x <> y}.\n  Parameter label : Type.\n  Parameter label_eq_dec : forall x y : label, {x = y} + {x <> y}.\n\n  Parameter start_handler : addr -> list addr -> data * list (addr * payload) * list timeout.\n  Definition res := (data * list (addr * payload) * list timeout * list timeout)%type.\n  Parameter recv_handler : addr -> addr -> data -> payload -> res.\n  Parameter timeout_handler : addr -> data -> timeout -> res.\n  Parameter recv_handler_l : addr -> addr -> data -> payload -> (res * label).\n  Parameter timeout_handler_l : addr -> data -> timeout -> (res * label).\n  Parameter label_input : addr -> addr -> payload -> label.\n  Parameter label_output : addr -> addr -> payload -> label.\n\n  Parameter recv_handler_labeling :\n    forall src dst st p r,\n      (recv_handler src dst st p = r ->\n       exists l,\n         recv_handler_l src dst st p = (r, l)) /\\\n      (forall l,\n          recv_handler_l src dst st p = (r, l) ->\n          recv_handler src dst st p = r).\n\n  Parameter timeout_handler_labeling :\n    forall h st t r,\n      (timeout_handler h st t = r ->\n       exists l,\n         timeout_handler_l h st t = (r, l)) /\\\n      (forall l,\n          timeout_handler_l h st t = (r, l) ->\n          timeout_handler h st t = r).\n\nEnd DynamicSystem.\n\nModule Type ConstrainedDynamicSystem.\n  Include DynamicSystem.\n  (* msgs *)\n\n  Definition msg : Type := (addr * (addr * payload))%type.\n\n  Inductive event : Type :=\n  | e_send : msg -> event\n  | e_recv : msg -> event\n  | e_timeout : addr -> timeout -> event\n  | e_fail : addr -> event.\n\n  Record global_state :=\n    { nodes : list addr;\n      failed_nodes : list addr;\n      timeouts : addr -> list timeout;\n      sigma : addr -> option data;\n      msgs : list msg;\n      trace : list event\n    }.\n\n  Parameter timeout_constraint : global_state -> addr -> timeout -> Prop.\n  (* failure_constraint is parametrized over an initial state, the\n     address of the failing node, and what the state would be after\n     the failure. *)\n  Parameter failure_constraint : global_state -> addr -> global_state -> Prop.\n  Parameter start_constraint : global_state -> addr -> Prop.\nEnd ConstrainedDynamicSystem.\n\nModule DynamicSemantics (S : ConstrainedDynamicSystem).\n  Include S.\n  Definition msg_eq_dec :\n    forall x y : msg, {x = y} + {x <> y}.\n  Proof.\n    repeat decide equality;\n      auto using addr_eq_dec, payload_eq_dec.\n  Defined.\n\n  Definition send (a : addr) (p : addr * payload) : msg :=\n    (a, p).\n\n  Definition update_msgs (gst : global_state) (ms : list msg) : global_state :=\n    {| nodes := nodes gst;\n       failed_nodes := failed_nodes gst;\n       timeouts := timeouts gst;\n       sigma := sigma gst;\n       msgs := ms;\n       trace := trace gst\n    |}.\n\n  Definition fail_node (gst : global_state) (h : addr) : global_state :=\n    {| nodes := nodes gst;\n       failed_nodes := h :: failed_nodes gst;\n       timeouts := timeouts gst;\n       sigma := sigma gst;\n       msgs := msgs gst;\n       trace := trace gst\n    |}.\n\n  Definition apply_handler_result (h : addr) (r : res) (es : list event) (gst : global_state) : global_state :=\n    let '(st, ms, nts, cts) := r in\n    let sends := map (send h) ms in\n    let ts' := nts ++ remove_all timeout_eq_dec cts (timeouts gst h) in\n    {| nodes := nodes gst;\n       failed_nodes := failed_nodes gst;\n       timeouts := update addr_eq_dec (timeouts gst) h ts';\n       sigma := update addr_eq_dec (sigma gst) h (Some st);\n       msgs := sends ++ msgs gst;\n       trace := trace gst ++ es\n    |}.\n\n  Lemma apply_handler_result_nodes :\n    forall h r e gst,\n      nodes (apply_handler_result h r e gst) = nodes gst.\n  Proof using.\n    unfold apply_handler_result.\n    intros.\n    now repeat break_let.\n  Qed.\n\n  Definition update_for_start\n             (gst : global_state) (h : addr)\n             (res : data * list (addr * payload) * list timeout) : global_state :=\n    let '(st, ms, newts) := res in\n    let sends := map (send h) ms in\n    {| nodes := h :: nodes gst;\n       failed_nodes := failed_nodes gst;\n       timeouts := update addr_eq_dec (timeouts gst) h newts;\n       sigma := update addr_eq_dec (sigma gst) h (Some st);\n       msgs := sends ++ msgs gst;\n       trace := trace gst ++ (map e_send sends)\n    |}.\n\n  Lemma update_for_start_nodes :\n    forall gst gst' h res,\n      update_for_start gst h res = gst' ->\n      h :: nodes gst = nodes gst'.\n  Proof using.\n    unfold update_for_start.\n    intros.\n    repeat break_let.\n    now repeat find_reverse_rewrite.\n  Qed.\n\n  Lemma update_for_start_nodes_eq :\n    forall gst h res,\n      nodes (update_for_start gst h res) = h :: nodes gst.\n  Proof using.\n    unfold update_for_start.\n    intros.\n    now repeat break_let.\n  Qed.\n\n  Lemma update_for_start_sigma_h_exists :\n    forall gst h res,\n    exists st,\n      sigma (update_for_start gst h res) h = Some st.\n  Proof using.\n    unfold update_for_start.\n    intros.\n    repeat break_let.\n    simpl.\n    eexists; eauto using update_eq.\n  Qed.\n\n  Lemma update_for_start_sigma_h_n :\n    forall gst h n res st,\n      h <> n ->\n      sigma gst n = Some st ->\n      sigma (update_for_start gst h res) n = Some st.\n  Proof using.\n    unfold update_for_start.\n    intros.\n    repeat break_let.\n    simpl.\n    now rewrite update_diff.\n  Qed.\n\n  Definition live_with_state (gst : global_state) (h : addr) (st : data) :=\n    In h (nodes gst) /\\\n    ~ In h (failed_nodes gst) /\\\n    sigma gst h = Some st.\n\n  Definition update_msgs_and_trace (gst : global_state) (ms : list msg) (e : event) : global_state :=\n    {| nodes := nodes gst;\n       failed_nodes := failed_nodes gst;\n       timeouts := timeouts gst;\n       sigma := sigma gst;\n       msgs := ms;\n       trace := trace gst ++ [e] |}.\n\n  Inductive step_dynamic : global_state -> global_state -> Prop :=\n  | Start :\n      forall h gst gst' k,\n        ~ In h (nodes gst) ->\n        ~ client_addr h ->\n        start_constraint gst h ->\n        (* hypotheses on the list of known nodes *)\n        In k (nodes gst) ->\n        ~ In k (failed_nodes gst) ->\n        gst' = update_for_start gst h (start_handler h (k :: nil)) ->\n        step_dynamic gst gst'\n  | Fail :\n      forall h gst gst',\n        In h (nodes gst) ->\n        ~ In h (failed_nodes gst) ->\n        gst' = fail_node gst h ->\n        failure_constraint gst h gst' ->\n        step_dynamic gst gst'\n  | Timeout :\n      forall gst gst' h st t st' ms newts clearedts,\n        In h (nodes gst) ->\n        ~ In h (failed_nodes gst) ->\n        sigma gst h = Some st ->\n        In t (timeouts gst h) ->\n        timeout_handler h st t = (st', ms, newts, clearedts) ->\n        gst' = (apply_handler_result\n                  h\n                  (st', ms, newts, t :: clearedts)\n                  [e_timeout h t]\n                  gst) ->\n        timeout_constraint gst h t ->\n        step_dynamic gst gst'\n  | Deliver_node :\n      forall gst gst' m h d xs ys ms st newts clearedts,\n        msgs gst = xs ++ m :: ys ->\n        h = fst (snd m) ->\n        In h (nodes gst) ->\n        ~ In h (failed_nodes gst) ->\n        sigma gst h = Some d ->\n        recv_handler (fst m) h d (snd (snd m)) = (st, ms, newts, clearedts) ->\n        gst' = apply_handler_result\n                 h\n                 (st, ms, newts, clearedts)\n                 [e_recv m]\n                 (update_msgs gst (xs ++ ys)) ->\n        step_dynamic gst gst'\n  | Input :\n      forall gst gst' h i to m,\n        client_addr h ->\n        client_payload i ->\n        m = send h (to, i) ->\n        gst' = update_msgs_and_trace gst (m :: msgs gst) (e_send m) ->\n        step_dynamic gst gst'\n  | Deliver_client :\n      forall gst gst' h xs m ys,\n        client_addr h ->\n        msgs gst = xs ++ m :: ys ->\n        h = fst (snd m) ->\n        gst' = update_msgs_and_trace gst (xs ++ ys) (e_recv m) ->\n        step_dynamic gst gst'.\n\n  Inductive labeled_step_dynamic : global_state -> label -> global_state -> Prop :=\n  | LTimeout :\n      forall gst gst' h st t lb st' ms newts clearedts,\n        In h (nodes gst) ->\n        ~ In h (failed_nodes gst) ->\n        sigma gst h = Some st ->\n        In t (timeouts gst h) ->\n        timeout_handler_l h st t = (st', ms, newts, clearedts, lb) ->\n        gst' = (apply_handler_result\n                  h\n                  (st', ms, newts, t :: clearedts)\n                  [e_timeout h t]\n                  gst) ->\n        timeout_constraint gst h t ->\n        labeled_step_dynamic gst lb gst'\n  | LDeliver_node :\n      forall gst gst' m h d xs ys ms lb st newts clearedts,\n        msgs gst = xs ++ m :: ys ->\n        h = fst (snd m) ->\n        In h (nodes gst) ->\n        ~ In h (failed_nodes gst) ->\n        sigma gst h = Some d ->\n        recv_handler_l (fst m) h d (snd (snd m)) = (st, ms, newts, clearedts, lb) ->\n        gst' = apply_handler_result\n                 h\n                 (st, ms, newts, clearedts)\n                 [e_recv m]\n                 (update_msgs gst (xs ++ ys)) ->\n        labeled_step_dynamic gst lb gst'\n  | LInput :\n      forall gst gst' h i to m l,\n        client_addr h ->\n        client_payload i ->\n        m = send h (to, i) ->\n        l = label_input h to i ->\n        gst' = update_msgs_and_trace gst (m :: msgs gst) (e_send m) ->\n        labeled_step_dynamic gst l gst'\n  | LDeliver_client :\n      forall gst gst' h xs m ys l,\n        client_addr h ->\n        msgs gst = xs ++ m :: ys ->\n        h = fst (snd m) ->\n        l = label_output (fst m) h (snd (snd m)) ->\n        gst' = update_msgs_and_trace gst (xs ++ ys) (e_recv m) ->\n        labeled_step_dynamic gst l gst'.\n\n  Record occurrence := { occ_gst : global_state ; occ_label : label }.\n\n  Definition enabled (l : label) (gst : global_state) : Prop :=\n    exists gst', labeled_step_dynamic gst l gst'.\n\n  Definition l_enabled (l : label) (occ : occurrence) : Prop :=\n    enabled l (occ_gst occ).\n\n  Definition occurred (l : label) (occ :occurrence) : Prop := l = occ_label occ.\n\n  Definition inf_enabled (l : label) (s : infseq occurrence) : Prop :=\n    inf_often (now (l_enabled l)) s.\n\n  Definition cont_enabled (l : label) (s : infseq occurrence) : Prop :=\n    continuously (now (l_enabled l)) s.\n\n  Definition inf_occurred (l : label) (s : infseq occurrence) : Prop :=\n    inf_often (now (occurred l)) s.\n\n  Definition strong_local_fairness (s : infseq occurrence) : Prop :=\n    forall l : label, inf_enabled l s -> inf_occurred l s.\n\n  Definition weak_local_fairness (s : infseq occurrence) : Prop :=\n    forall l : label, cont_enabled l s -> inf_occurred l s.\n\n  Lemma strong_local_fairness_invar :\n    forall e s, strong_local_fairness (Cons e s) -> strong_local_fairness s.\n  Proof using.\n    unfold strong_local_fairness. unfold inf_enabled, inf_occurred, inf_often.\n    intros e s fair a alev.\n    assert (alevt_es: always (eventually (now (l_enabled a))) (Cons e s)).\n    constructor.\n    constructor 2. destruct alev; assumption.\n    simpl. assumption.\n    clear alev. generalize (fair a alevt_es); clear fair alevt_es.\n    intro fair; case (always_Cons fair); trivial.\n  Qed.\n\n  Lemma weak_local_fairness_invar :\n    forall e s, weak_local_fairness (Cons e s) -> weak_local_fairness s.\n  Proof using.\n    unfold weak_local_fairness. unfold cont_enabled, inf_occurred, continuously, inf_often.\n    intros e s fair l eval.\n    assert (eval_es: eventually (always (now (l_enabled l))) (Cons e s)).\n    apply E_next. assumption.\n    apply fair in eval_es.\n    apply always_invar in eval_es.\n    assumption.\n  Qed.\n\n  Lemma strong_local_fairness_weak :\n    forall s, strong_local_fairness s -> weak_local_fairness s.\n  Proof using.\n    intros [e s].\n    unfold strong_local_fairness, weak_local_fairness, inf_enabled, cont_enabled.\n    intros H_str l H_cont.\n    apply H_str.\n    apply continuously_inf_often.\n    assumption.\n  Qed.\n\n  CoInductive lb_execution : infseq occurrence -> Prop :=\n    Cons_lb_exec : forall (o o' : occurrence) (s : infseq occurrence),\n      labeled_step_dynamic (occ_gst o) (occ_label o) (occ_gst o') ->\n      lb_execution (Cons o' s) ->\n      lb_execution (Cons o (Cons o' s)).\n\n  Lemma lb_execution_invar :\n    forall x s, lb_execution (Cons x s) -> lb_execution s.\n  Proof using.\n    intros x s e. change (lb_execution (tl (Cons x s))).\n    destruct e; simpl. assumption.\n  Qed.\n\n  Lemma labeled_step_is_unlabeled_step :\n    forall gst l gst',\n      labeled_step_dynamic gst l gst' ->\n      step_dynamic gst gst'.\n  Proof using.\n    intuition.\n    match goal with\n    | H: labeled_step_dynamic _ _ _ |- _ =>\n      invc H\n    end.\n    - find_apply_lem_hyp timeout_handler_labeling.\n      eapply Timeout; eauto.\n    - find_apply_lem_hyp recv_handler_labeling.\n      eapply Deliver_node; eauto.\n    - eapply Input; eauto.\n    - eapply Deliver_client; eauto.\n  Qed.\n\n  Inductive churn_between (gst gst' : global_state) : Prop :=\n  | fail_churn : failed_nodes gst <> failed_nodes gst' -> churn_between gst gst'\n  | join_churn : nodes gst <> nodes gst' -> churn_between gst gst'.\n\n  Ltac invc_lstep :=\n    match goal with\n    | H: labeled_step_dynamic _ _ _ |- _ =>\n      invc H\n    end.\n\n  Lemma labeled_step_dynamic_preserves_nodes :\n    forall gst l gst',\n      labeled_step_dynamic gst l gst' ->\n      nodes gst = nodes gst'.\n  Proof.\n    intros.\n    inv_prop labeled_step_dynamic;\n      simpl; reflexivity.\n  Qed.\n\n  Lemma labeled_step_dynamic_preserves_failed_nodes :\n    forall gst l gst',\n      labeled_step_dynamic gst l gst' ->\n      failed_nodes gst = failed_nodes gst'.\n  Proof.\n    intros.\n    inv_prop labeled_step_dynamic;\n      simpl; reflexivity.\n  Qed.\n\n  Lemma labeled_step_dynamic_is_step_dynamic_without_churn :\n    forall gst gst',\n      step_dynamic gst gst' ->\n      ((exists l, labeled_step_dynamic gst l gst') /\\ ~ churn_between gst gst') \\/\n      ((~ exists l, labeled_step_dynamic gst l gst') /\\ churn_between gst gst').\n  Proof using.\n    intuition.\n    match goal with\n    | H: step_dynamic _ _ |- _ =>\n      invc H\n    end.\n    - right.\n      split.\n      * intuition.\n        break_exists.\n        invc_lstep;\n          find_apply_lem_hyp update_for_start_nodes;\n          try find_rewrite_lem apply_handler_result_nodes;\n          eapply list_neq_cons; eauto.\n      * apply join_churn.\n        rewrite update_for_start_nodes_eq.\n        eauto using list_neq_cons.\n    - right.\n      unfold fail_node.\n      split.\n      * intuition.\n        break_exists.\n        invc_lstep;\n          unfold apply_handler_result, update_msgs_and_trace in *;\n          find_inversion;\n          eapply list_neq_cons; eauto.\n      * eauto using fail_churn, list_neq_cons.\n    - left.\n      split.\n      * find_apply_lem_hyp timeout_handler_labeling.\n        break_exists_exists.\n        eauto using LTimeout.\n      * intuition.\n        match goal with\n        | H: churn_between _ _ |- _ =>\n          inversion H; eauto\n        end.\n    - left.\n      split.\n      * find_apply_lem_hyp recv_handler_labeling.\n        break_exists_exists.\n        eauto using LDeliver_node.\n      * intuition.\n        match goal with\n        | H: churn_between _ _ |- _ =>\n          inversion H; eauto\n        end.\n    - left. split.\n      + eauto using labeled_step_dynamic.\n      + intuition.\n        match goal with\n        | H: churn_between _ _ |- _ =>\n          inversion H; eauto\n        end.\n    - left. split.\n      + eauto using labeled_step_dynamic.\n      + intuition.\n        match goal with\n        | H: churn_between _ _ |- _ =>\n          inversion H; eauto\n        end.\n  Qed.\n\n  Ltac break_step :=\n    match goal with\n    | [ H : step_dynamic _ _ |- _ ] =>\n      induction H\n    end; subst.\n\n  (* Predicates on global states *)\n  Definition gpred : Type := global_state -> Prop.\n\n  Definition gpred_and (P Q : global_state -> Prop) (gst : global_state) : Prop :=\n    P gst /\\ Q gst.\n\n  Definition lift_gpred_to_occ (P : global_state -> Prop) (o : occurrence) : Prop :=\n    P (occ_gst o).\n\n  Definition lift_gpred_to_ex (P : global_state -> Prop) : infseq.infseq occurrence -> Prop :=\n    infseq.now (lift_gpred_to_occ P).\n\nEnd DynamicSemantics.\n", "meta": {"author": "DistributedComponents", "repo": "verdi-chord", "sha": "762fe660c648d7f2a009d2beaa5cf3b8ea4ac593", "save_path": "github-repos/coq/DistributedComponents-verdi-chord", "path": "github-repos/coq/DistributedComponents-verdi-chord/verdi-chord-762fe660c648d7f2a009d2beaa5cf3b8ea4ac593/core/DynamicNet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.24395876097908087}}
{"text": "Require Import String.\nRequire Import NPeano.\nRequire Import PeanoNat.\nRequire Import Coq.Strings.Ascii.\nRequire FMapWeakList.\nRequire Export Coq.Structures.OrderedTypeEx.\nRequire Import Lists.List.\nImport ListNotations.\nRequire Import JaSyntax.\nRequire Import JaTypes.\nRequire Import JaProgram.\nRequire Import JaEnvs.\nRequire Import Jafun.\nRequire Import JaIrisCommon.\nRequire Import JaSubtype.\nRequire Import Bool.\nRequire Import Classical_Prop.\nRequire Import Classical_Pred_Type.\n\nRequire Export FMapAVL.\nRequire Export Coq.Structures.OrderedTypeEx.\nRequire Import FMapFacts.\n\nModule HeapFacts := Facts Heap.\nModule StrMapFacts := JaIrisCommon.StrMapFacts.\nModule NatMapFacts := JaIrisCommon.NatMapFacts.\nModule JFXIdMapFacts := Facts JFXIdMap.\n\nLtac induction2 l1 l2 length_eq head1 head2 tail1 tail2 :=\n  set (_l1 := l1);\n  set (_l2 := l2);\n  (replace l1 with _l1 in *; try now unfold _l1);\n  (replace l2 with _l2 in *; try now unfold _l2);\n  (replace _l1 with l1 in length_eq; try now unfold _l1);\n  (replace _l2 with l2 in length_eq; try now unfold _l2);\n  (replace _l1 with (fst (split (combine l1 l2))) in *; try now rewrite combine_split);\n  (replace _l2 with (snd (split (combine l1 l2))) in *; try now rewrite combine_split);\n  clear _l1 _l2;\n  induction (combine l1 l2) as [ | _a _l];\n    [unfold split in *\n    | simpl in *; destruct _a as (head1 & head2), (split _l) as (tail1 & tail2)\n    ];\n  unfold fst, snd in *.\n\n\nDefinition PiMapsTo l1 l2 (pi : HeapPermutation) :=\n  match (l1, l2) with\n  | (null, null) => True\n  | (JFLoc n1, JFLoc n2) => NatMap.MapsTo n1 n2 (fst pi)\n  | _ => False\n  end.\n\nDefinition Bijection (pi : HeapPermutation) :=\n  forall n1 n2, NatMap.MapsTo n1 n2 (fst pi) <-> NatMap.MapsTo n2 n1 (snd pi).\n\nDefinition PiCoversHeap (pi : HeapPermutation) (h : Heap) :=\n  forall n1, Heap.In n1 h -> exists n2, NatMap.MapsTo n1 n2 (fst pi).\n\nDefinition HeapLocsPermuted (f : HeapInjection) (h1 h2 : Heap) :=\n  forall n1, Heap.In n1 h1 ->\n  exists n2, NatMap.MapsTo n1 n2 f /\\ Heap.In n2 h2.\n\nDefinition ObjPermuted (o1 o2 : Obj) pi :=\n  let (ro1, cn1) := o1 in\n  let (ro2, cn2) := o2 in\n  cn1 = cn2 /\\ forall f,\n    (forall v1, JFXIdMap.MapsTo f v1 ro1 -> exists v2, JFXIdMap.MapsTo f v2 ro2) /\\\n    (forall v2, JFXIdMap.MapsTo f v2 ro2 -> exists v1, JFXIdMap.MapsTo f v1 ro1) /\\\n    (forall v1 v2,\n      JFXIdMap.MapsTo f v1 ro1 ->\n      JFXIdMap.MapsTo f v2 ro2 ->\n      PiMapsTo v1 v2 pi).\n\nDefinition ObjsPermuted (pi : HeapPermutation) (h1 h2 : Heap) :=\n  forall n1 n2 o1 o2,\n    NatMap.MapsTo n1 n2 (fst pi) ->\n    Heap.MapsTo n1 o1 h1 ->\n    Heap.MapsTo n2 o2 h2 ->\n    ObjPermuted o1 o2 pi.\n\nDefinition HeapsPermuted (h1 h2 : Heap) pi :=\n  Bijection pi /\\\n  HeapLocsPermuted (fst pi) h1 h2 /\\\n  HeapLocsPermuted (snd pi) h2 h1 /\\\n  ObjsPermuted pi h1 h2.\n\nDefinition EnvsPermuted env1 env2 pi :=\n  Bijection pi /\\\n  (forall x, StrMap.In x env1 <-> StrMap.In x env2) /\\\n  forall x l1 l2,\n    StrMap.MapsTo x l1 env1 -> StrMap.MapsTo x l2 env2 ->\n    PiMapsTo l1 l2 pi.\n\nFixpoint LocsPermuted ls ls' pi :=\n  match (ls, ls') with\n  | ([], []) => True\n  | (l::ls, l'::ls') => PiMapsTo l l' pi /\\ LocsPermuted ls ls' pi\n  | _ => False\n  end.\n\nDefinition ValPermuted v v' pi :=\n  match (v, v') with\n  | (JFSyn x, JFSyn y) => x = y\n  | (JFVLoc l, JFVLoc l') => PiMapsTo l l' pi\n  | _ => False\n  end.\n\nFixpoint ValsPermuted vs vs' pi :=\n  match (vs, vs') with\n  | ([], []) => True\n  | (v::vs, v'::vs') => ValPermuted v v' pi /\\ ValsPermuted vs vs' pi\n  | _ => False\n  end.\n\nFixpoint ExprsPermuted e e' pi :=\n  match (e, e') with\n  | (JFNew mu cn vs, JFNew mu' cn' vs') =>\n      mu = mu' /\\ cn = cn' /\\\n      ValsPermuted vs vs' pi\n  | (JFLet cn x e1 e2, JFLet cn' x' e1' e2') =>\n      cn = cn' /\\ x = x' /\\\n      ExprsPermuted e1 e1' pi /\\ ExprsPermuted e2 e2' pi\n  | (JFIf v1 v2 e1 e2, JFIf v1' v2' e1' e2') =>\n      ExprsPermuted e1 e1' pi /\\ ExprsPermuted e2 e2' pi /\\\n      ValPermuted v1 v1' pi /\\ ValPermuted v2 v2' pi\n  | (JFInvoke v1 m vs, JFInvoke v1' m' vs') =>\n      ValPermuted v1 v1' pi /\\ ValsPermuted vs vs' pi /\\ m = m'\n  | (JFAssign (v1, f) v2, JFAssign (v1', f') v2') =>\n      f = f' /\\ ValPermuted v1 v1' pi /\\ ValPermuted v2 v2' pi\n  | (JFVal1 v1, JFVal1 v1') =>\n      ValPermuted v1 v1' pi\n  | (JFVal2 (v1, f), JFVal2 (v1', f')) =>\n      f = f' /\\ ValPermuted v1 v1' pi\n  | (JFThrow v1, JFThrow v1') =>\n      ValPermuted v1 v1' pi\n  | (JFTry e1 mu cn x e2, JFTry e1' mu' cn' x' e2') =>\n      mu = mu' /\\ cn = cn' /\\ x = x' /\\\n      ExprsPermuted e1 e1' pi /\\ ExprsPermuted e2 e2' pi\n  | _ => False\n  end.\n\nDefinition CtxPermuted ctx ctx' pi :=\n  match (ctx, ctx') with\n  | (JFCtxLet cn x _ e2, JFCtxLet cn' x' _ e2') => cn = cn' /\\ x = x' /\\ ExprsPermuted e2 e2' pi\n  | (JFCtxTry _ _ cn x e2, JFCtxTry _ _ cn' x' e2') => cn = cn' /\\ x = x' /\\ ExprsPermuted e2 e2' pi\n  | _ => False\n  end.\n\nFixpoint CtxsPermuted ctxs ctxs' pi :=\n  match (ctxs, ctxs') with\n  | ([], []) => True\n  | (ctx::ctxs, ctx'::ctxs') => CtxPermuted ctx ctx' pi /\\ CtxsPermuted ctxs ctxs' pi\n  | _ => False\n  end.\n\nDefinition FramesPermuted f f' pi :=\n  match (f, f') with\n  | (MkFrame ctxs e A, MkFrame ctxs' e' A') =>\n      ExprsPermuted e e' pi /\\ CtxsPermuted ctxs ctxs' pi /\\ A = A'\n  end.\n\nFixpoint StacksPermuted st st' pi :=\n  match (st, st') with\n  | ([], []) => True\n  | (f::st, f'::st') => FramesPermuted f f' pi /\\ StacksPermuted st st' pi\n  | _ => False\n  end.\n\nFixpoint ZipPermuted (flds flds' : list (JFXId * Loc)) pi :=\n  match (flds, flds') with\n  | ([], []) => True\n  | ((f, loc)::flds, (f', loc')::flds') => f = f' /\\ PiMapsTo loc loc' pi /\\ ZipPermuted flds flds' pi\n  | _ => False\n  end.\n\nDefinition PermutationSubset (pi pi' : HeapPermutation) :=\n  forall l1 l2, PiMapsTo l1 l2 pi -> PiMapsTo l1 l2 pi'.\n\nLemma ExtendedEnvsPermuted : forall env1 env2 x l1 l2 pi,\n  EnvsPermuted env1 env2 pi ->\n  PiMapsTo l1 l2 pi ->\n  EnvsPermuted (StrMap.add x l1 env1) (StrMap.add x l2 env2) pi.\nProof.\n  intros env1 env2 x l1 l2 pi.\n  intros pi_env pi_l.\n  split; [ | split].\n  + apply pi_env.\n  + intros y.\n    destruct (Classical_Prop.classic (x = y)).\n    ++ split; intros in_env; now apply StrMapFacts.add_in_iff, or_introl.\n    ++ split;\n       intros in_env;\n       apply StrMapFacts.add_in_iff, or_intror;\n       apply StrMapFacts.add_in_iff in in_env;\n       destruct in_env; try destruct (H H0);\n       now apply (proj1 (proj2 pi_env)).\n  + intros x' l1' l2'.\n    intros x'_l1' x'_l2'.\n    destruct (Classical_Prop.classic (x = x')).\n    ++ apply StrMapFacts.find_mapsto_iff in x'_l1'.\n       rewrite StrMapFacts.add_eq_o in x'_l1'; trivial.\n       apply StrMapFacts.find_mapsto_iff in x'_l2'.\n       rewrite StrMapFacts.add_eq_o in x'_l2'; trivial.\n       injection x'_l1' as l1_eq.\n       injection x'_l2' as l2_eq.\n       now rewrite <-l1_eq, <-l2_eq.\n    ++ apply StrMapFacts.add_neq_mapsto_iff in x'_l1'; trivial.\n       apply StrMapFacts.add_neq_mapsto_iff in x'_l2'; trivial.\n       now apply (proj2 pi_env) with (x := x').\nQed.\n\nLemma InvertedHeapPermutation : forall h1 h2 pi_fst pi_snd,\n  HeapsPermuted h1 h2 (pi_fst, pi_snd) ->\n  HeapsPermuted h2 h1 (pi_snd, pi_fst).\nProof.\n  intros h1 h2 pi_fst pi_snd pi_h.\n  unfold HeapsPermuted in pi_h |- *.\n  simpl in *.\n  destruct pi_h as (bijection & locs_fst & locs_snd & pi_h).\n  split; [ | split; [ | split]]; trivial.\n  + unfold Bijection in *.\n    simpl in *.\n    intros n1 n2.\n    split; apply (bijection n2 n1).\n  + unfold ObjsPermuted in *.\n    intros n2 n1 o2 o1.\n    intros n2_n1_snd n2_o2_h2 n1_o1_h1.\n    apply bijection in n2_n1_snd as n1_n2_fst.\n    destruct o1 as (o1 & cn1), o2 as (o2 & cn2).\n    destruct (pi_h n1 n2 (o1, cn1) (o2, cn2) n1_n2_fst n1_o1_h1 n2_o2_h2)\n      as (cn_eq & field_mapsto).\n    symmetry in cn_eq.\n    split; trivial.\n    intros f.\n    destruct (field_mapsto f) as (o1_fields & o2_fields & field_map).\n    clear field_mapsto.\n    split; [ | split]; trivial.\n    intros v2 v1 f_v2_o2 f_v1_o1.\n    simpl in *.\n    assert (v1_mapsto_v2 := field_map v1 v2 f_v1_o1 f_v2_o2).\n    unfold PiMapsTo in v1_mapsto_v2 |- *.\n    simpl in *.\n    destruct v2, v1; trivial.\n    now apply bijection.\nQed.\n\nLemma InvertedEnvPermutation : forall env1 env2 pi_fst pi_snd,\n  EnvsPermuted env1 env2 (pi_fst, pi_snd) ->\n  EnvsPermuted env2 env1 (pi_snd, pi_fst).\nProof.\n  intros env1 env2 pi_fst pi_snd.\n  intros pi_env.\n  unfold EnvsPermuted in *.\n  destruct pi_env as (bijection & same_keys & pi_env).\n  split; [ | split]; try easy.\n  intros x l2 l1.\n  intros x_l2_env2 x_l1_env1.\n  assert (l1_mapsto_l2 := pi_env x l1 l2 x_l1_env1 x_l2_env2).\n  unfold PiMapsTo in l1_mapsto_l2 |- *.\n  simpl in *.\n  destruct l2, l1; trivial.\n  now apply bijection.\nQed.\n\nLemma InvertPermutation : forall pi, exists pi',\n  (forall h1 h2, HeapsPermuted h1 h2 pi <-> HeapsPermuted h2 h1 pi') /\\\n  (forall env1 env2, EnvsPermuted env1 env2 pi <-> EnvsPermuted env2 env1 pi').\nProof.\n  intros (pi_fst, pi_snd).\n  exists (pi_snd, pi_fst).\n  split.\n  + intros h1 h2.\n    split; now apply InvertedHeapPermutation.\n  + intros env1 env2.\n    split; now apply InvertedEnvPermutation.\nQed.\n\nDefinition TryPermuteLoc (loc : Loc) (pi : HeapPermutation) :=\n  match loc with\n  | null => Some null\n  | JFLoc n =>\n      match (NatMap.find n (fst pi)) with\n      | Some n' => Some (JFLoc n')\n      | None => None\n      end\n   end.\n\nFixpoint TryPermuteObjFlds (flds : list (JFXId * Loc)) (pi : HeapPermutation) :=\n  match flds with\n  | [] => Some []\n  | (field_name, loc)::flds =>\n    match (TryPermuteLoc loc pi, TryPermuteObjFlds flds pi) with\n    | (Some new_loc, Some new_flds) => Some ((field_name, new_loc)::new_flds)\n    | _ => None\n    end\n  end.\n\nDefinition TryPermuteObj (obj : Obj) (pi : HeapPermutation) :=\n  match obj with\n  | (o, cn) => match TryPermuteObjFlds (JFXIdMap.elements o) pi with\n    | Some new_flds => Some ((fold_left (fun o f => JFXIdMap.add (fst f) (snd f) o) new_flds (JFXIdMap.empty Loc)), cn)\n    | None => None\n    end\n  end.\n\nFixpoint TryPermuteHeapElements (objs : list (nat * Obj)) (pi : HeapPermutation) :=\n  match objs with\n  | [] => Some []\n  | (n, obj)::objs =>\n    match (NatMap.find n (fst pi), TryPermuteObj obj pi, TryPermuteHeapElements objs pi) with\n    | (Some new_n, Some new_obj, Some new_els) => Some ((new_n, new_obj)::new_els)\n    | _ => None\n    end\n  end.\n\nDefinition TryPermuteHeap (h : Heap) (pi : HeapPermutation) :=\n  match (TryPermuteHeapElements (Heap.elements h) pi) with\n  | Some new_els => Some (fold_left (fun h o => Heap.add (fst o) (snd o) h) new_els (Heap.empty Obj))\n  | None => None\n  end.\n\n\nLemma MapsToEq : forall (pi : HeapInjection) n1 n2 n2',\n  NatMap.MapsTo n1 n2  pi ->\n  NatMap.MapsTo n1 n2' pi ->\n  n2 = n2'.\nProof.\n  intros pi n1 n2 n2'.\n  intros n1_n2_pi n1_n2'_pi.\n  apply NatMapFacts.find_mapsto_iff in n1_n2_pi.\n  apply NatMapFacts.find_mapsto_iff in n1_n2'_pi.\n  rewrite n1_n2'_pi in n1_n2_pi.\n  now injection n1_n2_pi.\nQed.\n\nLemma PiMapsToEqIff : forall l1 l2 l1' l2' pi,\n  Bijection pi ->\n  PiMapsTo l1 l1' pi ->\n  PiMapsTo l2 l2' pi ->\n  (l1 = l2 <-> l1' = l2').\nProof.\n  intros l1 l2 l1' l2' pi bijection pi_l1 pi_l2.\n  split.\n  + intros l_eq.\n    unfold PiMapsTo in *.\n    destruct l1, l2, l1', l2'; try easy.\n    injection l_eq as n_eq.\n    rewrite <-n_eq in pi_l2.\n    assert (n1_eq := MapsToEq (fst pi) n n1 n2 pi_l1 pi_l2).\n    now rewrite n1_eq.\n  + intros l_eq.\n    unfold PiMapsTo in *.\n    destruct l1, l2, l1', l2'; try easy.\n    apply bijection in pi_l1.\n    apply bijection in pi_l2.\n    injection l_eq as n1_eq.\n    rewrite <-n1_eq in pi_l2.\n    assert (n_eq := MapsToEq (snd pi) n1 n n0 pi_l1 pi_l2).\n    now rewrite n_eq.\nQed.\n\nLemma ObjFldsAux : forall n (pi : HeapPermutation) field_name n' (flds' : list (string * Loc)),\nNatMap.find (elt:=nat) n (fst pi) = Some n' ->\nmatch\n  match NatMap.find (elt:=nat) n (fst pi) with\n  | Some n'0 => Some (JFLoc n'0)\n  | None => None\n  end\nwith\n| Some new_loc => Some ((field_name, new_loc)::flds')\n| None => None\nend = Some ((field_name, (JFLoc n'))::flds').\nProof.\n  intros n pi field_name n' obj' n_n'_pi.\n  now rewrite n_n'_pi.\nQed.\n\nLemma SuccessfulObjFldsPermutation : forall flds pi,\n  (forall f n, In (f, (JFLoc n)) flds -> NatMap.In n (fst pi)) ->\n  exists obj', TryPermuteObjFlds flds pi = Some obj'.\nProof.\n  intros flds pi flds_in_p.\n  induction flds.\n  now exists [].\n  destruct a as (field_name & loc).\n  destruct IHflds as (obj' & flds_perm).\n  + intros f n in_flds.\n    apply (flds_in_p f n).\n    now apply in_cons.\n  + destruct loc.\n    ++ exists ((field_name, null)::obj').\n       simpl.\n       now rewrite flds_perm.\n    ++ destruct (flds_in_p field_name n) as (n' & n'_perm).\n       now apply in_eq.\n       simpl.\n       exists ((field_name, (JFLoc n'))::obj').\n       apply NatMapFacts.find_mapsto_iff in n'_perm.\n       rewrite flds_perm.\n       now apply ObjFldsAux.\nQed.\n\nLemma SuccessfulObjPermutation : forall obj pi,\n  (forall f n, JFXIdMap.find f (fst obj) = Some (JFLoc n) -> NatMap.In n (fst pi)) ->\n  exists obj', TryPermuteObj obj pi = Some obj'.\nProof.\n  intros obj pi fields_in_pi.\n  unfold TryPermuteObj.\n  destruct obj as (obj & cn).\n  destruct (SuccessfulObjFldsPermutation (JFXIdMap.elements obj) pi) as (obj' & obj_perm).\n  + intros f n f_n_obj.\n    apply fields_in_pi with (f := f).\n    apply JFXIdMapFacts.find_mapsto_iff.\n    rewrite JFXIdMapFacts.elements_mapsto_iff.\n    apply In_InA with (x := (f, JFLoc n)); trivial.\n    now exact JFXIdMapEqKeyEltEquivalence.\n  + rewrite obj_perm.\n    now exists (fold_left (fun o f => JFXIdMap.add (fst f) (snd f) o) obj' (JFXIdMap.empty Loc), cn).\nQed.\n\nLemma HeapPermutationAux : forall n (pi : HeapPermutation) n' obj' (h' : list (nat * Obj)),\n  NatMap.find (elt:=nat) n (fst pi) = Some n' ->\n  match NatMap.find (elt:=nat) n (fst pi) with\n  | Some new_n => Some ((new_n, obj') :: h')\n  | None => None\n  end = Some ((n', obj') :: h').\nProof.\n  intros.\n  now rewrite H.\nQed.\n\nLemma SuccessfulHeapElementsPermutation : forall objs pi,\n  (forall n obj f f_n,\n      In (n, obj) objs ->\n      JFXIdMap.find f (fst obj) = Some (JFLoc f_n) ->\n      NatMap.In f_n (fst pi)\n  ) ->\n  (forall n obj, In (n, obj) objs -> exists n', NatMap.MapsTo n n' (fst pi)) ->\n  exists h', TryPermuteHeapElements objs pi = Some h'.\nProof.\n  intros objs pi.\n  induction objs.\n  now exists [].\n  intros flds_in_pi a_objs_in_pi.\n  destruct IHobjs as (h' & objs_perm); trivial.\n  + intros n obj f f_n n_obj_obj f_fn_obj.\n    apply (flds_in_pi n obj f); trivial.\n    now apply in_cons.\n  + intros n obj n_obj_objs.\n    apply (a_objs_in_pi n obj); trivial.\n    now apply in_cons.\n  + destruct a as (n & obj).\n    destruct (SuccessfulObjPermutation obj pi) as (obj' & obj_perm).\n    ++ intros f f_n f_fn_obj.\n       apply (flds_in_pi n obj f); trivial.\n       now apply in_eq.\n    ++ destruct (a_objs_in_pi n obj) as (n' & n_n'_pi).\n       now apply in_eq.\n    exists ((n', obj')::h').\n    simpl.\n    rewrite NatMapFacts.find_mapsto_iff in n_n'_pi.\n    rewrite obj_perm, objs_perm.\n    now apply HeapPermutationAux.\nQed.\n\nLemma SuccessfulPermutation : forall h pi,\n  HeapConsistent h ->\n  PiCoversHeap pi h ->\n  exists h', TryPermuteHeap h pi = Some h'.\nProof.\n  intros h pi consistent covers.\n  unfold TryPermuteHeap.\n  destruct (SuccessfulHeapElementsPermutation (Heap.elements h) pi)\n    as (els' & els_perm).\n  + unfold PiCoversHeap in covers.\n    intros n obj f f_n n_obj_h f_fn_obj.\n    destruct consistent as (npe_in_h & consistent).\n    destruct (consistent n obj f f_n).\n    ++ apply HeapFacts.elements_mapsto_iff.\n       apply In_InA; trivial.\n       exact HeapEqKeyEltEquivalence. \n    ++ now apply JFXIdMapFacts.find_mapsto_iff in f_fn_obj.\n    ++ apply covers.\n       apply NatMapFacts.elements_in_iff.\n       exists x.\n       now apply NatMapFacts.elements_mapsto_iff.\n  + unfold PiCoversHeap in covers.\n    intros n obj n_obj_h.\n    destruct (covers n); trivial.\n    ++ apply HeapFacts.elements_in_iff.\n       exists obj.\n       apply In_InA; trivial.\n       exact HeapEqKeyEltEquivalence.\n    ++ now exists x. \n  + rewrite els_perm.\n    now exists (fold_left (fun h0 o => Heap.add (fst o) (snd o) h0) els'  (Heap.empty Obj)).\nQed.\n\nLemma PermutationDoesntAddNewHeapElements : forall n1 n2 els new_els pi,\n  TryPermuteHeapElements els pi = Some new_els ->\n  (~exists o1, In (n1, o1) els) ->\n  Bijection pi ->\n  NatMap.MapsTo n1 n2 (fst pi) ->\n  (~exists o2, In (n2, o2) new_els).\nProof.\n  intros n1 n2 els.\n  induction els; intros new_els pi pi_els n1_not_in_els bijection pi_n.\n  + intros  (o2 & n2_o2_new).\n    destruct new_els; try discriminate pi_els.\n    now apply in_nil in n2_o2_new.\n  + destruct new_els as [ | new_a new_els].\n      simpl in pi_els.\n      destruct a.\n      destruct (NatMap.find n (fst pi)),\n               (TryPermuteObj o pi),\n               (TryPermuteHeapElements els pi); try discriminate pi_els.\n    assert (n2_n1_pi := (proj1 (bijection n1 n2)) pi_n).\n    unfold Bijection in bijection.\n    destruct a as (n & o), new_a as (new_n & new_o).\n    destruct (Classical_Prop.classic (n2 = new_n)).\n    ++ rewrite <-H in *.\n       simpl in pi_els.\n       assert (NatMap.find n (fst pi) = Some n2).\n         destruct (NatMap.find n (fst pi)),\n                  (TryPermuteObj o pi),\n                   (TryPermuteHeapElements els pi); try discriminate pi_els.\n         injection pi_els as n_eq _ _.\n         now rewrite n_eq.\n       apply NatMapFacts.find_mapsto_iff in H0.\n       destruct (PiMapsToEqIff (JFLoc n1) (JFLoc n) (JFLoc n2) (JFLoc n2) pi) as (_ & n_eq); try easy.\n       injection n_eq; trivial; clear n_eq; intros n_eq.\n       exfalso.\n       apply n1_not_in_els.\n       rewrite n_eq.\n       exists o.\n       now apply in_eq.\n    ++ intros (o2 & n2_o2).\n       apply in_inv in n2_o2.\n       destruct n2_o2.\n         apply H.\n         now injection H0.\n       unfold not in IHels.\n       apply IHels with (new_els := new_els) (pi := pi); try easy.\n       +++ simpl in pi_els.\n           destruct (NatMap.find n (fst pi)),\n                    (TryPermuteObj o pi),\n                    (TryPermuteHeapElements els pi); try discriminate pi_els.\n           injection pi_els as _ _ l_eq.\n           now rewrite l_eq.\n       +++ intros (o1 & n1_o1).\n           apply n1_not_in_els.\n           exists o1.\n           now apply in_cons.\n       +++ now exists o2.\nQed.\n\nLemma EqFoldFromEqHeaps : forall els h1 h2 h',\n  HeapEq h1 h2 ->\n  HeapEq (fold_left (fun h o => Heap.add (fst o) (snd o) h) els h1) h' ->\n  HeapEq (fold_left (fun h o => Heap.add (fst o) (snd o) h) els h2) h'.\nProof.\n  intros els.\n  induction els; intros h1 h2 h' h_eq fold_eq.\n  + simpl in *.\n    apply HeapEqSym in h_eq.\n    now apply HeapEqTrans with (h2 := h1).\n  + simpl in *.\n    apply IHels with (h1 := (Heap.add (fst a) (snd a) h1)); trivial.\n    intros n.\n    destruct (Classical_Prop.classic (n = fst a)).\n    ++ now rewrite 2!HeapFacts.add_eq_o.\n    ++ rewrite 2!HeapFacts.add_neq_o; try easy; try now apply neq_symmetry.\nQed.\n\nLemma ChangeHeapAddOrder : forall n1 n2 o1 o2 h,\n  n1 <> n2 ->\n  HeapEq (Heap.add n1 o1 (Heap.add n2 o2 h)) (Heap.add n2 o2 (Heap.add n1 o1 h)).\nProof.\n  intros n1 n2 o1 o2 h n_neq.\n  intros n.\n  destruct (Classical_Prop.classic (n1 = n)) as [n1_eq | n1_neq], (Classical_Prop.classic (n2 = n)) as [n2_eq | n2_neq].\n  ++ now rewrite <-n2_eq in n1_eq.\n  ++ now rewrite n1_eq, HeapFacts.add_eq_o, HeapFacts.add_neq_o, HeapFacts.add_eq_o.\n  ++ now rewrite HeapFacts.add_neq_o, 2!HeapFacts.add_eq_o.\n  ++ now rewrite 4!HeapFacts.add_neq_o.\nQed.\n\nLemma HeapMapsToLastAddedObj : forall els n obj (h h' : Heap),\n  (~exists o, In (n, o) els) ->\n  HeapEq (fold_left (fun h o  => Heap.add (fst o) (snd o) h) els (Heap.add n obj h)) h' ->\n  Heap.MapsTo n obj h'.\nProof.\n  intros els.\n  induction els; intros n obj h h' n_not_in_els h'_eq.\n  + simpl in h'_eq.\n    rewrite <-h'_eq.\n    now apply HeapFacts.find_mapsto_iff, HeapFacts.add_eq_o.\n  + simpl in h'_eq.\n    apply IHels with (h := Heap.add (fst a) (snd a) h).\n    ++ intros (o & n_in_els).\n       apply n_not_in_els.\n       exists o.\n       now apply in_cons.\n    ++ apply EqFoldFromEqHeaps with (h1 := Heap.add (fst a) (snd a) (Heap.add n obj h)); trivial.\n       apply ChangeHeapAddOrder.\n       destruct a.\n       simpl.\n       intros k_eq_n.\n       apply n_not_in_els.\n       exists o.\n       rewrite k_eq_n.\n       now apply in_eq.\nQed.\n\nLemma InFoldIff : forall l n (h : Heap),\n  Heap.In n (fold_left (fun h o => Heap.add (fst o) (snd o) h) l h) <->\n  ((exists o, In (n, o) l) \\/ Heap.In n h).\nProof.\n  intros l.\n  induction l; intros n h.\n  + simpl.\n    split.\n    ++ intros n_h.\n       now apply or_intror.\n    ++ now destruct 1; try now (destruct H; destruct H).\n  + simpl.\n    split.\n    ++ intros n_h.\n       apply IHl in n_h.\n       destruct n_h.\n       +++ destruct H as (o & n_o_l).\n           apply or_introl.\n           exists o.\n           now apply or_intror.\n       +++ apply HeapFacts.elements_in_iff in H.\n           destruct H as (o & n_o_h).\n           apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff in n_o_h.\n           destruct (Classical_Prop.classic (fst a = n)).\n           - rewrite HeapFacts.add_eq_o in n_o_h; try easy.\n             apply or_introl.\n             exists o.\n             apply or_introl.\n             injection n_o_h as o_eq.\n             destruct a.\n             simpl in *.\n             now rewrite o_eq, H.\n           - rewrite HeapFacts.add_neq_o in n_o_h; try easy.\n             apply or_intror, HeapFacts.elements_in_iff.\n             exists o.\n             now apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n    ++ intros H.\n       apply IHl.\n       destruct H;  [ destruct H as (o & H); destruct H |].\n       +++ apply or_intror.\n           rewrite H.\n           simpl.\n           apply HeapFacts.elements_in_iff.\n           exists o.\n           apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n           now rewrite HeapFacts.add_eq_o.\n       +++ apply or_introl.\n           now exists o.\n       +++ apply or_intror.\n           apply HeapFacts.elements_in_iff.\n           destruct (Classical_Prop.classic (fst a = n)).\n           - exists (snd a).\n             apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n             now rewrite HeapFacts.add_eq_o.\n           - apply HeapFacts.elements_in_iff in H.\n             destruct H as (o & n_o_h).\n             exists o.\n             apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff in n_o_h.\n             apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n             now rewrite HeapFacts.add_neq_o.\nQed.\n\nLemma FoldStepDoesntRemoveElements : forall l n (h : Heap) n' o',\n  Heap.In n (fold_left (fun h o => Heap.add (fst o) (snd o) h) l h) ->\n  Heap.In n (fold_left (fun h o => Heap.add (fst o) (snd o) h) l (Heap.add n' o' h)).\nProof.\n  intros l.\n  induction l; intros n h n' o' in_h.\n  + simpl in *.\n    apply HeapFacts.elements_in_iff in in_h.\n    destruct in_h as (o & n_e_h).\n    apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff in n_e_h.\n    apply HeapFacts.elements_in_iff.\n    destruct (Classical_Prop.classic (n' = n)).\n    ++ exists o'.\n       apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n       now rewrite HeapFacts.add_eq_o.\n    ++ exists o.\n       apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n       now rewrite HeapFacts.add_neq_o.\n  + destruct a as (nn & oo).\n    simpl in *.\n    apply IHl with (n' := n') (o' := o') in in_h.\n    apply InFoldIff in in_h.\n    apply InFoldIff.\n    destruct in_h as [(o & n_o_l) | n_in_h].\n    ++ apply or_introl.\n       now exists o.\n    ++ apply or_intror.\n       apply HeapFacts.elements_in_iff in n_in_h as (o & n_o_h).\n       apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff in n_o_h.\n       apply HeapFacts.elements_in_iff.\n       destruct (Classical_Prop.classic (n' = n)) as [n'_eq | n'_neq],\n                (Classical_Prop.classic (nn = n)) as [nn_eq | nn_neq].\n       +++ exists oo.\n           apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n           now rewrite HeapFacts.add_eq_o.\n       +++ exists o'.\n           apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n           rewrite HeapFacts.add_neq_o, HeapFacts.add_eq_o; try easy.\n       +++ exists oo.\n           apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n           rewrite HeapFacts.add_eq_o; try easy.\n       +++ exists o.\n           rewrite !HeapFacts.add_neq_o in n_o_h; try easy.\n           apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n           now rewrite !HeapFacts.add_neq_o.\nQed.\n\nLemma FoldDoesntRemoveElements : forall l n (h : Heap),\n  Heap.In n h ->\n  Heap.In n (fold_left (fun h o => Heap.add (fst o) (snd o) h) l h).\nProof.\n  intros l.\n  induction l; intros n h n_h; try easy.\n  simpl.\n  apply FoldStepDoesntRemoveElements.\n  now apply IHl.\nQed.\n\nLemma RemoveFromFold : forall els n n' o' o2 cn2 (h : Heap),\n  n <> n' ->\n  Heap.find n (fold_left (fun h o => Heap.add (fst o) (snd o) h)\n                els (Heap.add n' o' h)) = Some (o2, cn2) ->\n  Heap.find n (fold_left (fun h o => Heap.add (fst o) (snd o) h)\n                els h) = Some (o2, cn2).\nProof.\n  intros els.\n  induction els; intros n n' o' o2 cn2 h n_neq find_n.\n  + simpl in *.\n    apply neq_symmetry in n_neq.\n    now rewrite HeapFacts.add_neq_o in find_n.\n  + simpl in *.\n    destruct (Classical_Prop.classic (n' = fst a)).\n    ++ rewrite <-H in *.\n       set (h' := (fold_left\n              (fun h o =>\n               Heap.add (fst o) (snd o) h) els\n              (Heap.add n' (snd a) (Heap.add n' o' h)))).\n       assert (heap_eq : HeapEq\n         (fold_left\n            (fun (h : Heap.t Obj) (o : Heap.key * Obj) =>\n             Heap.add (fst o) (snd o) h) els\n            (Heap.add n' (snd a) (Heap.add n' o' h))) h').\n         fold h'.\n         now apply EqImpliesHeapEq.\n       apply EqFoldFromEqHeaps with (h2 := (Heap.add n' (snd a) h)) in heap_eq.\n       +++ unfold h' in heap_eq.\n           unfold HeapEq in heap_eq.\n           now rewrite heap_eq.\n       +++ intros nn.\n           destruct (Classical_Prop.classic (n' = nn)).\n           - now rewrite !HeapFacts.add_eq_o.\n           - now rewrite !HeapFacts.add_neq_o.\n    ++ apply IHels with (n' := n') (o' := o'); try easy.\n       set (h' := (fold_left\n              (fun h o =>\n               Heap.add (fst o) (snd o) h) els\n              (Heap.add (fst a) (snd a) (Heap.add n' o' h)))).\n       assert (heap_eq : HeapEq\n         (fold_left\n            (fun (h : Heap.t Obj) (o : Heap.key * Obj) =>\n             Heap.add (fst o) (snd o) h) els\n            (Heap.add (fst a) (snd a) (Heap.add n' o' h))) h').\n         fold h'.\n         now apply EqImpliesHeapEq.\n       apply EqFoldFromEqHeaps with (h2 := (Heap.add n' o' (Heap.add (fst a) (snd a) h))) in heap_eq.\n       +++ unfold h' in heap_eq.\n           unfold HeapEq in heap_eq.\n           now rewrite heap_eq.\n       +++ intros nn.\n           destruct (Classical_Prop.classic (fst a = nn)).\n           - rewrite HeapFacts.add_eq_o, HeapFacts.add_neq_o, HeapFacts.add_eq_o; try easy.\n             intros n'_eq.\n             apply H.\n             now rewrite H0.\n           - rewrite HeapFacts.add_neq_o; try easy.\n             destruct (Classical_Prop.classic (n' = nn)).\n             now rewrite !HeapFacts.add_eq_o.\n             now rewrite !HeapFacts.add_neq_o.\nQed.\n\nLemma SuccessfulPermutationIsLocsPermutation : forall h pi n1 obj h',\n  match TryPermuteHeapElements (Heap.elements h) pi with\n  | Some new_els => Some (fold_left (fun h o => Heap.add (fst o) (snd o) h) new_els (Heap.empty Obj))\n  | None => None\n  end = Some h' ->\n  In (n1, obj) (Heap.elements h) ->\n  exists n2,\n    NatMap.MapsTo n1 n2 (fst pi) /\\\n    Heap.In (elt:=Obj) n2 h'.\nProof.\n  intros h pi n1 obj.\n  induction (Heap.elements h); intros h'.\n    intros _ in_empty.\n    exfalso.\n    now apply in_nil in in_empty.\n  intros perm n1_in_al.\n  destruct (Classical_Prop.classic ((n1, obj) = a)).\n  + rewrite <-H in perm.\n    simpl in perm.\n    destruct (Classical_Prop.classic (exists n2, NatMap.find n1 (fst pi) = Some n2)).\n    ++ destruct H0 as (n2 & n1_n2_pi).\n       exists n2.\n       rewrite n1_n2_pi in perm.\n       apply NatMapFacts.find_mapsto_iff in n1_n2_pi.\n       split; trivial.\n       destruct (TryPermuteObj obj pi), (TryPermuteHeapElements l pi); try discriminate perm.\n       injection perm as h'_eq.\n       rewrite <- h'_eq.\n       apply FoldDoesntRemoveElements.\n       apply HeapFacts.elements_in_iff.\n       exists p.\n       apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n       now rewrite HeapFacts.add_eq_o.\n    ++ destruct (NatMap.find n1 (fst pi)); try discriminate perm.\n       exfalso.\n       apply H0.\n       now exists n.\n  + simpl in perm.\n    destruct a.\n    destruct (NatMap.find (elt:=nat) k (fst pi)); try discriminate perm.\n    destruct (TryPermuteObj o pi); try discriminate perm.\n    destruct (TryPermuteHeapElements l pi); try discriminate perm.\n    injection perm as h'_eq.\n    rewrite <-h'_eq.\n    apply in_inv in n1_in_al.\n    destruct n1_in_al.\n    now symmetry in H0.\n    set (rest_h' := (fold_left (fun h o => Heap.add (fst o) (snd o) h) l0 (Heap.empty Obj))).\n    destruct (IHl rest_h') as (n2 & n1_n2_pi & n2_in_rest); trivial.\n    exists n2.\n    split; trivial.\n    unfold rest_h' in n2_in_rest.\n    now apply FoldStepDoesntRemoveElements.\nQed.\n\nLemma InElementsAdd : forall n n' o p t,\n  n <> n' ->\n  In (n, o) (Heap.elements (elt:=Obj) (Heap.add n' p t)) ->\n  In (n, o) (Heap.elements t).\nProof.\n  intros n n' o p t.\n  intros neq in_elements.\n  apply In_InA with (eqA := Heap.eq_key_elt (elt:=Obj)) in in_elements;\n  try apply HeapEqKeyEltEquivalence.\n  apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff in in_elements.\n  apply neq_symmetry in neq.\n  rewrite HeapFacts.add_neq_o in in_elements; trivial.\n  apply HeapFacts.find_mapsto_iff, HeapFacts.elements_mapsto_iff in in_elements.\n    apply InA_alt in in_elements.\n    destruct in_elements as ((n1, o1) & y_eq & y_in_h).\n    unfold Heap.eq_key_elt, Heap.Raw.Proofs.PX.eqke in y_eq.\n    simpl in y_eq.\n    now rewrite (proj1 y_eq), (proj2 y_eq).\nQed.\n\nLemma SuccessfulPermutationIsSndLocsPermutation : forall pi1 pi2 h h' n2 obj,\n  Bijection (pi1, pi2) ->\n  TryPermuteHeap h (pi1, pi2) = Some h' ->\n  In (n2, obj) (Heap.elements h') ->\n  exists n1 : nat,\n    NatMap.MapsTo n2 n1 (snd (pi1, pi2)) /\\\n    Heap.In (elt:=Obj) n1 h.\nProof.\n  intros pi1 pi2 h.\n  unfold TryPermuteHeap.\n  assert (in_h : forall a, In a (Heap.elements h) -> Heap.In (fst a) h).\n  intros (a1, a2) a_in_h.\n  apply HeapFacts.elements_in_iff.\n  apply In_InA with (eqA := Heap.eq_key_elt (elt:=Obj)) in a_in_h.\n  now exists a2.\n  now apply HeapEqKeyEltEquivalence.\n  induction (Heap.elements h); intros h' n2 obj bijection pi_h n2_obj_h'.\n  + simpl in pi_h.\n    injection pi_h as h'_empty.\n    rewrite <-h'_empty in n2_obj_h'.\n    destruct n2_obj_h'.\n  + destruct a as (n & obj_n).\n    destruct (Classical_Prop.classic (NatMap.MapsTo n n2 pi1)).\n    ++ exists n.\n       split.\n       +++ now apply bijection.\n       +++ apply (in_h (n, obj_n)).\n           apply in_eq.\n    ++ simpl in pi_h.\n       destruct (Classical_Prop.classic (exists n', NatMap.find n pi1 = Some n'))\n         as [(n' & n_n'_pi1) | ].\n       +++ assert (n_eq := n_n'_pi1).\n           apply NatMapFacts.find_mapsto_iff in n_n'_pi1.\n           rewrite n_eq in pi_h.\n           destruct (TryPermuteObj obj_n (pi1, pi2)); try discriminate pi_h.\n           destruct (TryPermuteHeapElements l (pi1, pi2)); try discriminate pi_h.\n           injection pi_h as h'_eq.\n           rewrite <-h'_eq in n2_obj_h'.\n           assert (next_in_h : forall a, In a l -> Heap.In (elt:=Obj) (fst a) h).\n           intros a a_in_l.\n           apply in_cons with (a := (n, obj_n)) in a_in_l.\n           apply (in_h a a_in_l).\n           set (rest_h' := (fold_left (fun h o => Heap.add (fst o) (snd o) h)\n                  l0 (Heap.empty Obj))).\n           apply (IHl next_in_h rest_h' n2 obj); trivial.\n           apply In_InA with (eqA := Heap.eq_key_elt (elt:=Obj)) in n2_obj_h'; [ | apply HeapEqKeyEltEquivalence].\n           apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff in n2_obj_h'.\n           fold Obj in n2_obj_h'.\n           destruct obj.\n           apply RemoveFromFold in n2_obj_h'.\n           - apply HeapFacts.find_mapsto_iff, HeapFacts.elements_mapsto_iff in n2_obj_h'.\n             apply InA_alt in n2_obj_h'.\n             destruct n2_obj_h' as (y & y_eq & n2_obj_h').\n             destruct y, p0.\n             unfold Heap.eq_key_elt, Heap.Raw.Proofs.PX.eqke in y_eq.\n             simpl in y_eq.\n             now rewrite <-(proj1 y_eq), <-(proj2 y_eq) in n2_obj_h'.\n           - intros n2_eq.\n             apply H.\n             now rewrite <-n2_eq in n_n'_pi1.\n       +++ destruct (NatMap.find n pi1); try discriminate pi_h.\n           exfalso.\n           apply H0.\n           now exists n0.\nQed.\n\nLemma BijectionIsInjective : forall pi n1 n1' n2,\n  Bijection pi ->\n  NatMap.MapsTo n1  n2 (fst pi) ->\n  NatMap.MapsTo n1' n2 (fst pi) ->\n  n1 = n1'.\nProof.\n  intros pi n1 n1' n2.\n  intros bijection n1_n2_pi n1'_n2_pi.\n  apply bijection in n1_n2_pi.\n  apply bijection in n1'_n2_pi.\n  now apply (MapsToEq (snd pi) n2 n1 n1').\nQed.\n\nLemma SuccessfulPermutationIsObjPermutation_elements : forall o1 o2 cn1 cn2 pi,\n  TryPermuteObj (o1, cn1) pi = Some (o2, cn2) ->\n  forall f : JFXIdMap.key,\n    (forall v1 : Loc, InA (JFXIdMap.eq_key_elt (elt:=Loc)) (f, v1) (JFXIdMap.elements o1) -> exists v2 : Loc, JFXIdMap.MapsTo f v2 o2) /\\\n    (forall v2 : Loc, JFXIdMap.MapsTo f v2 o2 -> exists v1 : Loc, InA (JFXIdMap.eq_key_elt (elt:=Loc)) (f, v1) (JFXIdMap.elements o1) ) /\\\n    (forall v1 v2 : Loc, InA (JFXIdMap.eq_key_elt (elt:=Loc)) (f, v1) (JFXIdMap.elements o1)  -> JFXIdMap.MapsTo f v2 o2 -> PiMapsTo v1 v2 pi).\nProof.\n  intros o1.\n  unfold TryPermuteObj.\n  induction (JFXIdMap.elements o1) as [ | fld flds]; intros o2 cn1 cn2 pi pi_o1 f.\n  + simpl in *.\n    injection pi_o1 as o2_eq cn_eq.\n    split; [ | split].\n    ++ intros v1 f_v1.\n       inversion f_v1.\n    ++ intros v2 f_v2.\n       exfalso.\n       rewrite <-o2_eq in f_v2.\n       now apply JFXIdMapFacts.empty_mapsto_iff in f_v2.\n    ++ intros v1 v2 f_v1 f_v2.\n       exfalso.\n       rewrite <-o2_eq in f_v2.\n       now apply JFXIdMapFacts.empty_mapsto_iff in f_v2.\n  + simpl in *. clear o1.\n    destruct fld as (f1 & l1).\n    assert (exists l1', TryPermuteLoc l1 pi = Some l1').\n      destruct (TryPermuteLoc l1 pi); try discriminate pi_o1.\n      now exists l.\n    destruct H as (l1' & pi_l1).\n    rewrite pi_l1 in pi_o1.\n    assert (exists flds', TryPermuteObjFlds flds pi = Some flds').\n      destruct (TryPermuteObjFlds flds pi); try discriminate pi_o1.\n      now exists l.\n    destruct H as (flds' & pi_flds).\n    rewrite pi_flds in pi_o1.\n    injection pi_o1 as o_eq cn_eq.\n    set (o' := fold_left (fun o f => JFXIdMap.add (fst f) (snd f) o) flds' (JFXIdMap.empty Loc)).\n    assert (H := IHflds o' cn1 cn1 pi).\n    rewrite pi_flds in H.\n    fold o' in H.\n    assert (IH := H eq_refl f).\n    clear H IHflds.\n    destruct IH as (IH1 & IH2 & IH3).\n    split; [ | split].\n    ++ intros v1 f_v1.\n       destruct (Classical_Prop.classic (f1 = f)).\n       +++ admit.\n       +++ inversion f_v1.\n             exfalso.\n             apply H.\n             now unfold JFXIdMap.eq_key_elt, JFXIdMap.Raw.PX.eqke, fst, snd in H1.\n           apply IH1 in H1 as (v2 & f_v2).\n           exists v2.\n           admit.\n    ++ intros v2 f_v2.\n       destruct (Classical_Prop.classic (f1 = f)).\n       +++ exists l1.\n           now apply InA_cons_hd.\n       +++ assert (f_v2' : JFXIdMap.MapsTo f v2 o'). admit.\n           apply IH2 in f_v2' as (v1 & f_v1).\n           exists v1.\n           now apply InA_cons_tl.\n    ++ intros v1 v2 f_v1 f_v2.\n       destruct (Classical_Prop.classic (f1 = f)).\n       +++ admit.\n       +++ assert (f_v2' : JFXIdMap.MapsTo f v2 o'). admit.\n           inversion f_v1.\n             exfalso.\n             apply H.\n             now unfold JFXIdMap.eq_key_elt, JFXIdMap.Raw.PX.eqke, fst, snd in H1.\n           now apply IH3.\nAdmitted.\n\nLemma SuccessfulPermutationIsObjPermutation : forall o1 o2 cn1 cn2 pi,\n  TryPermuteObj (o1, cn1) pi = Some (o2, cn2) ->\n  forall f : JFXIdMap.key,\n    (forall v1 : Loc, JFXIdMap.MapsTo f v1 o1 -> exists v2 : Loc, JFXIdMap.MapsTo f v2 o2) /\\\n    (forall v2 : Loc, JFXIdMap.MapsTo f v2 o2 -> exists v1 : Loc, JFXIdMap.MapsTo f v1 o1) /\\\n    (forall v1 v2 : Loc, JFXIdMap.MapsTo f v1 o1 -> JFXIdMap.MapsTo f v2 o2 -> PiMapsTo v1 v2 pi).\nProof.\n  apply SuccessfulPermutationIsObjPermutation_elements.\nQed.\n\nLemma SuccessfulPermutationIsHeapElementsPermutation : forall o1 cn1 n1 objs objs' n2 o2 cn2 pi,\n  TryPermuteHeapElements ((n1, (o1, cn1)) :: objs) pi = Some ((n2, (o2, cn2)) :: objs') ->\n  NatMap.MapsTo n1 n2 (fst pi) ->\n  (cn1 = cn2 /\\ forall f,\n      (forall v1, JFXIdMap.MapsTo f v1 o1 -> exists v2, JFXIdMap.MapsTo f v2 o2) /\\\n      (forall v2, JFXIdMap.MapsTo f v2 o2 -> exists v1, JFXIdMap.MapsTo f v1 o1) /\\\n      (forall v1 v2,\n        JFXIdMap.MapsTo f v1 o1 ->\n        JFXIdMap.MapsTo f v2 o2 ->\n        PiMapsTo v1 v2 pi)).\nProof.\n  intros o1 cn1 n1 objs objs' n2 o2 cn2 pi pi_h pi_n.\n  unfold TryPermuteHeapElements in pi_h.\n  fold TryPermuteHeapElements in pi_h.\n  apply NatMapFacts.find_mapsto_iff in pi_n.\n  rewrite pi_n in pi_h.\n  split.\n  +  simpl in pi_h.\n     destruct (TryPermuteObjFlds (JFXIdMap.elements (elt:=Loc) o1) pi),\n              (TryPermuteHeapElements objs pi); try discriminate pi_h.\n     now injection pi_h.\n  + apply SuccessfulPermutationIsObjPermutation with (cn1 := cn1) (cn2 := cn2).\n    destruct (TryPermuteObj (o1, cn1) pi), (TryPermuteHeapElements objs pi) in pi_h;\n    try discriminate pi_h.\n    injection pi_h.\n    intros _ p_eq.\n    now rewrite p_eq.\nQed.\n\nLemma HeadOfPermutedElementsIsPermuted : forall n1 n2 o1 o2 cn1 cn2 pi els h',\n  Bijection pi ->\n  match TryPermuteHeapElements ((n1, (o1, cn1)) :: els) pi with\n  | Some new_els =>\n      Some (fold_left (fun h o => Heap.add (fst o) (snd o) h) new_els (Heap.empty Obj))\n  | None => None\n  end = Some h' ->\n (~exists o1', In (n1, o1') els) ->\n  NatMap.MapsTo n1 n2 (fst pi) ->\n  Heap.MapsTo n2 (o2, cn2) h' ->\n  exists els', TryPermuteHeapElements ((n1, (o1, cn1)) :: els) pi = Some ((n2, (o2, cn2)) :: els').\nProof.\n  intros n1 n2 o1 o2 cn1 cn2 pi els h'.\n  intros bijection pi_elements n1_not_in_els pi_n n2_o2_h'.\n  unfold TryPermuteHeapElements in *.\n  fold TryPermuteHeapElements in *.\n  apply NatMapFacts.find_mapsto_iff in pi_n.\n  rewrite pi_n in *.\n\n  destruct (TryPermuteObj (o1, cn1) pi) as [new_obj | ]; try discriminate pi_elements.\n  assert (exists els', TryPermuteHeapElements els pi = Some els').\n    destruct (TryPermuteHeapElements els pi); try discriminate pi_elements.\n    now exists l.\n  destruct H as (els' & pi_els).\n  rewrite pi_els in *.\n  exists els'.\n  injection pi_elements as pi_elements.\n  apply NatMapFacts.find_mapsto_iff in pi_n.\n  apply EqImpliesHeapEq in pi_elements.\n  apply HeapMapsToLastAddedObj in pi_elements as n2_new_h';\n    [ | now apply PermutationDoesntAddNewHeapElements with (n1 := n1) (els := els) (pi := pi)].\n  apply HeapFacts.find_mapsto_iff in n2_new_h'.\n  apply HeapFacts.find_mapsto_iff in n2_o2_h'.\n  fold RawObj Obj in n2_o2_h'.\n  rewrite n2_new_h' in n2_o2_h'.\n  injection n2_o2_h' as obj_eq.\n  now rewrite obj_eq.\nQed.\n\nLemma AppNoDupA : forall l1 l2,\n  NoDupA (Heap.eq_key (elt:=Obj)) (l1 ++ l2) ->\n  NoDupA (Heap.eq_key (elt:=Obj))  l2.\nProof.\n  intros l1.\n  induction l1; trivial.\n  intros l2 no_dup.\n  apply IHl1.\n  now inversion no_dup.\nQed.\n\nLemma HeapElementsUnique : forall (h : Heap) els1 els2,\n  (Heap.elements h) = els1 ++ els2 ->\n  match els2 with\n  | [] => True\n  | ((n, _) :: els) => ~exists o, In (n, o) els\n  end.\nProof.\n  intros h els1 els2.\n  assert (no_dup := Heap.elements_3w h).\n  intros h_eq.\n  destruct els2; trivial.\n  destruct p as (n & o).\n  rewrite h_eq in no_dup.\n  apply AppNoDupA in no_dup.\n  intros (o' & n_in_els2).\n  inversion no_dup.\n  apply H1.\n  apply InA_eqA with (x := (n, o')); try easy.\n  now apply HeapEqKeyEquivalence.\n  apply In_InA; trivial.\n  now apply HeapEqKeyEquivalence.\nQed.\n\nLemma HeapElementsUniqueStep : forall (a : (Heap.key * Obj)) l,\n  (forall els1 els2,\n    a::l = els1 ++ els2 ->\n    match els2 with\n    | [] => True\n    | ((n, _) :: els) => ~exists o, In (n, o) els\n    end) ->\n  (forall els1 els2,\n    l = els1 ++ els2 ->\n    match els2 with\n    | [] => True\n    | ((n, _) :: els) => ~exists o, In (n, o) els\n    end).\nProof.\n  intros a l elements_unique.\n  intros els1 els2 l_eq.\n  apply elements_unique with (els1 := a::els1).\n  rewrite <-app_comm_cons.\n  now rewrite l_eq.\nQed.\n\nLemma SuccessfulPermutationIsObjsPermutation : forall h h' pi,\n  Bijection pi ->\n  TryPermuteHeap h pi = Some h' ->\n  ObjsPermuted pi h h'.\nProof.\n  intros h.\n  unfold TryPermuteHeap.\n  assert (in_els_mapsto : forall n obj, In (n, obj) (Heap.elements h) -> Heap.MapsTo n obj h).\n    intros n obj n_in_h.\n    apply HeapFacts.elements_mapsto_iff.\n    apply In_InA with (eqA := Heap.eq_key_elt (elt := Obj)) in n_in_h; trivial.\n    now apply HeapEqKeyEltEquivalence.\n  assert (els_unique := HeapElementsUnique h).\n  induction (Heap.elements h).\n  + intros h' pi bijection pi_h.\n    intros n1 n2 (o1 & cn1) (o2 & cn2).\n    intros n1_n2_pi n1_o1_h n2_o2_h'.\n    exfalso.\n    simpl in pi_h.\n    injection pi_h as h'_eq.\n    rewrite <-h'_eq in n2_o2_h'.\n    now apply HeapFacts.empty_mapsto_iff in n2_o2_h'.\n  + intros h' pi bijection pi_h.\n    intros n1 n2 (o1 & cn1) (o2 & cn2).\n    intros n1_n2_pi n1_o1_h n2_o2_h'.\n    destruct a as (n & obj).\n    destruct (Classical_Prop.classic (n = n1)).\n    ++ rewrite H in *.\n       clear H.\n       assert (n1_obj_h := in_els_mapsto n1 obj (in_eq (n1, obj) l)).\n       assert (obj_eq : obj = (o1, cn1)).\n         apply HeapFacts.find_mapsto_iff in n1_o1_h.\n         apply HeapFacts.find_mapsto_iff in n1_obj_h.\n         rewrite n1_obj_h in n1_o1_h.\n         now injection n1_o1_h.\n       rewrite obj_eq in pi_h.\n       destruct (HeadOfPermutedElementsIsPermuted n1 n2 o1 o2 cn1 cn2 pi l h') as (l' & pi_elements); trivial.\n         now apply els_unique with (els1 := []) (els2 := (n1, obj)::l).\n       now apply SuccessfulPermutationIsHeapElementsPermutation with (n1 := n1) (n2 := n2) (objs := l) (objs' := l').\n    ++ simpl in pi_h.\n       assert (exists n', NatMap.find n (fst pi) = Some n').\n       destruct (NatMap.find n (fst pi)); try discriminate pi_h.\n       now exists n0.\n       destruct H0 as (n' & n_pi_n').\n       rewrite n_pi_n' in pi_h.\n       destruct (TryPermuteObj obj pi); try discriminate pi_h.\n       assert (exists h', TryPermuteHeapElements l pi = Some h').\n       destruct (TryPermuteHeapElements l pi); try discriminate pi_h.\n       now exists l0.\n       destruct H0 as (rest_els_h' & pi_rest_els_h').\n       rewrite pi_rest_els_h' in *.\n       injection pi_h as h'_eq.\n       unfold ObjsPermuted in IHl.\n       rewrite <-h'_eq in n2_o2_h'.\n       assert (next_in_els : forall n obj, In (n, obj) l -> Heap.MapsTo n obj h).\n         intros n0 obj0 n0_in_l.\n         now apply in_els_mapsto, in_cons.\n       assert (next_els_unique := HeapElementsUniqueStep (n, obj) l els_unique).\n       set (rest_h' := fold_left (fun h o => Heap.add (fst o) (snd o) h) rest_els_h' (Heap.empty Obj)).\n       assert (pi_rest_h' : match TryPermuteHeapElements l pi with \n           | Some new_els => Some   (fold_left (fun h o => Heap.add (fst o) (snd o) h) new_els (Heap.empty Obj))\n           | None => None\n           end = Some rest_h').\n         now rewrite pi_rest_els_h'.\n       apply (IHl next_in_els next_els_unique rest_h' pi bijection pi_rest_h' n1 n2 (o1, cn1) (o2, cn2)); trivial.\n       apply HeapFacts.find_mapsto_iff in n2_o2_h'.\n       apply HeapFacts.find_mapsto_iff.\n       unfold rest_h'.\n       apply RemoveFromFold with (n' := n') (o' := p); trivial.\n       apply NatMapFacts.find_mapsto_iff in n_pi_n'.\n       intros n'_eq_n2.\n       rewrite <-n'_eq_n2 in n_pi_n'.\n       apply H.\n       now apply (BijectionIsInjective pi n n1 n2).\nQed.\n\nLemma SuccessfulPermutationIsPermutation : forall h h' pi,\n  Bijection pi ->\n  TryPermuteHeap h pi = Some h' ->\n  HeapsPermuted h h' pi.\nProof.\n  intros h h' pi bijection h_pi_h'.\n  unfold HeapsPermuted.\n  split; [ | split; [ | split]]; trivial.\n  + unfold HeapLocsPermuted.\n    intros n1 n1_in_h.\n    unfold TryPermuteHeap in h_pi_h'.\n    apply HeapFacts.elements_in_iff in n1_in_h.\n    destruct n1_in_h as (obj1 & n1_obj1_h).\n    apply SuccessfulPermutationIsLocsPermutation with (h := h) (obj := obj1); trivial.\n    apply InA_alt in n1_obj1_h.\n    destruct n1_obj1_h as ((n1', obj1') & y_eq & y_in_h).\n    unfold Heap.eq_key_elt, Heap.Raw.Proofs.PX.eqke in y_eq.\n    simpl in y_eq.\n    now rewrite (proj1 y_eq), (proj2 y_eq).\n  + unfold HeapLocsPermuted.\n    intros n1 n1_in_h'.\n    destruct pi as (pi1 & pi2).\n    unfold TryPermuteHeap in h_pi_h'.\n    apply HeapFacts.elements_in_iff in n1_in_h'.\n    destruct n1_in_h' as (obj1 & n1_obj1_h').\n    apply SuccessfulPermutationIsSndLocsPermutation with (h' := h') (obj := obj1); trivial.\n    apply InA_alt in n1_obj1_h'.\n    destruct n1_obj1_h' as ((n1', obj1') & y_eq & y_in_h).\n    unfold Heap.eq_key_elt, Heap.Raw.Proofs.PX.eqke in y_eq.\n    simpl in y_eq.\n    now rewrite (proj1 y_eq), (proj2 y_eq).\n  + now apply SuccessfulPermutationIsObjsPermutation.\nQed.\n\nLemma ExistsPermutedHeap : forall h pi,\n  Bijection pi ->\n  PiCoversHeap pi h ->\n  exists h', HeapsPermuted h h' pi.\nProof.\n  intros h pi bijection covers.\n  assert (consistent : HeapConsistent h). admit.\n  destruct (SuccessfulPermutation h pi consistent covers) as (h' & try_permute_h_h').\n  exists h'.\n  now apply SuccessfulPermutationIsPermutation.\nAdmitted.\n\nLemma ExistsPermutedVal : forall v pi,\n  exists v', ValPermuted v v' pi.\nProof.\n  intros v pi.\n  destruct v.\n  + destruct l.\n    ++ now exists JFnull.\n    ++ admit.\n  + now exists (JFSyn x).\nAdmitted.\n\nLemma ExistsPermutedVals : forall vs pi,\n  exists vs', ValsPermuted vs vs' pi.\nProof.\n  intros vs pi.\n  induction vs.\n  + now exists [].\n  + destruct IHvs as (vs' & pi_vs).\n    destruct (ExistsPermutedVal a pi) as (a' & pi_a).\n    now exists (a'::vs').\nQed.\n\nLemma ExistsPermutedExpr : forall e pi,\n  exists e', ExprsPermuted e e' pi.\nProof.\n  intros e pi.\n  induction e;\n    try destruct IHe1 as (e1' & pi_e1);\n    try destruct IHe2 as (e2' & pi_e2);\n    try destruct vx as (vx & f);\n    try destruct (ExistsPermutedVal v1 pi) as (v1' & pi_v1);\n    try destruct (ExistsPermutedVal v2 pi) as (v2' & pi_v2);\n    try destruct (ExistsPermutedVal vx pi) as (vx' & pi_vx);\n    try destruct (ExistsPermutedVal v pi) as (v' & pi_v);\n    try destruct (ExistsPermutedVals vs pi) as (vs' & pi_vs).\n  + now exists (JFNew mu cn vs').\n  + now exists (JFLet cn x e1' e2').\n  + now exists (JFIf v1' v2' e1' e2').\n  + now exists (JFInvoke v' m vs').\n  + now exists (JFAssign (vx', f) v').\n  + now exists (JFVal1 v').\n  + now exists (JFVal2 (vx', f)).\n  + now exists (JFThrow v').\n  + now exists (JFTry e1' mu cn x e2').\nQed.\n\nLemma DisjointPermuted : forall h1 h1_perm h2 h2_perm pi,\n  JFIHeapsDisjoint h1 h2 ->\n  HeapsPermuted h1 h1_perm pi ->\n  HeapsPermuted h2 h2_perm pi ->\n  JFIHeapsDisjoint h1_perm h2_perm.\nProof.\n  intros h1 h1_perm h2 h2_perm pi.\n  intros disj pi_h1 pi_h2.\n  intros n' (n'_in_h1_perm & n'_in_h2_perm).\n  destruct pi_h1 as (bijection & h1_fst & h1_snd & h1_objs).\n  destruct pi_h2 as (_ & h2_fst & h2_snd & h2_objs).\n  apply h1_snd in n'_in_h1_perm as (n1 & n'_n1_pi & n1_in_h1).\n  apply h2_snd in n'_in_h2_perm as (n2 & n'_n2_pi & n2_in_h2).\n  apply NatMapFacts.find_mapsto_iff in n'_n1_pi.\n  apply NatMapFacts.find_mapsto_iff in n'_n2_pi.\n  rewrite n'_n2_pi in n'_n1_pi.\n  injection n'_n1_pi as n_eq.\n  apply (disj n1).\n  split; trivial.\n  now rewrite <-n_eq.\nQed.\n\nLemma PermutedHeapCovered : forall h1 h2 pi,\n  HeapsPermuted h1 h2 pi ->\n  PiCoversHeap pi h1.\nProof.\n  intros h1 h2 pi (_ & locs_permuted & _ & _).\n  intros n n_in_h1.\n  unfold HeapLocsPermuted in *.\n  destruct (locs_permuted n n_in_h1) as (n2 & n1_n2_pi & n2_in_h2).\n  now exists n2.\nQed.\n\nLemma PermutationCoversUnion : forall h1 h2 h pi,\n  JFIHeapsUnion h1 h2 h ->\n  (PiCoversHeap pi h <-> PiCoversHeap pi h1/\\ PiCoversHeap pi h2).\nProof.\n  intros h1 h2 h pi.\n  intros union_h1_h2.\n  split.\n  + intro covers_h.\n    destruct union_h1_h2 as (h1_subheap & h2_subheap & _).\n    split.\n    ++ intros n n_in_h1.\n       apply HeapFacts.elements_in_iff in n_in_h1 as (o & n_o_h1).\n       apply HeapFacts.elements_mapsto_iff in n_o_h1.\n       assert (n_o_h := h1_subheap n o n_o_h1).\n       apply (covers_h n).\n       apply HeapFacts.elements_in_iff.\n       exists o.\n       now apply HeapFacts.elements_mapsto_iff.\n    ++ intros n n_in_h2.\n       apply HeapFacts.elements_in_iff in n_in_h2 as (o & n_o_h2).\n       apply HeapFacts.elements_mapsto_iff in n_o_h2.\n       assert (n_o_h := h2_subheap n o n_o_h2).\n       apply (covers_h n).\n       apply HeapFacts.elements_in_iff.\n       exists o.\n       now apply HeapFacts.elements_mapsto_iff.\n  + intros (covers_h1 & covers_h2).\n    intros n n_in_h.\n    destruct union_h1_h2 as (_ & _ & union).\n    destruct (union n n_in_h).\n    ++ apply (covers_h1 n H).\n    ++ apply (covers_h2 n H).\nQed.\n\nLemma UnionPermuted : forall h1 h1' h2 h2' h h' pi,\n  JFIHeapsUnion h1 h2 h ->\n  HeapsPermuted h1 h1' pi ->\n  HeapsPermuted h2 h2' pi ->\n  HeapsPermuted h h' pi ->\n  JFIHeapsUnion h1' h2' h'.\nProof.\n  intros h1 h1' h2 h2' h h' pi.\n  intros union_h1_h2 pi_h1 pi_h2 pi_h.\n  split; [ | split].\n  + intros n' o' n'_o'_h1'.\n    destruct pi_h1 as (bijection & locs_fst_h1 & locs_snd_h1 & _).\n    destruct (locs_snd_h1 n') as (n & n'_n_pi & n_in_h1).\n    admit.\n    destruct union_h1_h2 as (subheap_h1 & subheap_h2 & _).\n    apply HeapFacts.elements_in_iff in n_in_h1 as (o & n_o_h1).\n    apply HeapFacts.elements_mapsto_iff in n_o_h1.\n    assert (n_o_h := subheap_h1 n o n_o_h1).\n    apply bijection in n'_n_pi.\n    destruct pi_h as (_ & locs_fst_h & locs_snd_h & _).\n    unfold HeapLocsPermuted in locs_fst_h.\n    destruct (locs_fst_h n) as (n'' & n_n''_pi & n''_in_h2).\n    admit.\n    apply NatMapFacts.find_mapsto_iff in n'_n_pi.\n    apply NatMapFacts.find_mapsto_iff in n_n''_pi.\n    rewrite n_n''_pi in n'_n_pi.\n    apply NatMapFacts.find_mapsto_iff in n_n''_pi.\n    injection n'_n_pi as n'_eq.\n    rewrite n'_eq in *.\n    (* TODO replace with object equality *)\nAdmitted.\n\nLemma DisjointUnionPermuted : forall h1 h1_perm h2 h2_perm h h_perm pi,\n  JFIDisjointUnion h1 h2 h ->\n  HeapsPermuted h1 h1_perm pi ->\n  HeapsPermuted h2 h2_perm pi ->\n  HeapsPermuted h h_perm pi ->\n  JFIDisjointUnion h1_perm h2_perm h_perm.\nProof.\n  intros h1 h1_perm h2 h2_perm h h_perm pi.\n  intros (union & disj) pi_h1 pi_h2 pi_h.\n  split.\n  now apply UnionPermuted with (h1 := h1) (h2 := h2) (h := h) (pi := pi).\n  intros n' (n'_in_h1 & n'_in_h2).\n  destruct pi_h1 as (_ & _ & locs_h1 & _).\n  destruct pi_h2 as (_ & _ & locs_h2 & _).\n  destruct (locs_h1 n' n'_in_h1) as (n1 & n1_n'_pi & n_in_h1).\n  destruct (locs_h2 n' n'_in_h2) as (n2 & n2_n'_pi & n_in_h2).\n  apply NatMapFacts.find_mapsto_iff in n1_n'_pi.\n  apply NatMapFacts.find_mapsto_iff in n2_n'_pi.\n  rewrite n2_n'_pi in n1_n'_pi.\n  injection n1_n'_pi as n_eq.\n  rewrite n_eq in n_in_h2.\n  now apply (disj n1).\nQed.\n\nLemma PiMapsToSameType : forall h h_perm pi l type,\n  HeapsPermuted h h_perm pi ->\n  JFILocOfType l h type ->\n  exists l_perm,\n    PiMapsTo l l_perm pi /\\ JFILocOfType l_perm h_perm type.\nProof.\n  intros h h' pi l type pi_h l_of_type.\n  destruct pi_h as (_ & locs_h & _ & objs_h).\n  destruct l.\n  now exists null.\n  destruct (Classical_Prop.classic (exists o, Heap.find n h = Some o)) as [(o & n_o_h) | ].\n  + destruct (locs_h n) as (n' & n_n'_pi & n'_in_h').\n    ++ apply HeapFacts.elements_in_iff.\n       exists o.\n       now apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n    ++ exists (JFLoc n').\n       split; try easy.\n       unfold ObjsPermuted in objs_h.\n       apply HeapFacts.elements_in_iff in n'_in_h' as (o' & n'_o'_h').\n       apply HeapFacts.elements_mapsto_iff in n'_o'_h'.\n       apply HeapFacts.find_mapsto_iff in n_o_h.\n       unfold JFILocOfType.\n       apply HeapFacts.find_mapsto_iff in n'_o'_h'.\n       rewrite n'_o'_h'.\n       apply HeapFacts.find_mapsto_iff in n'_o'_h'.\n       destruct o' as (o' & type').\n       destruct o as (o & type_o).\n       unfold JFILocOfType in l_of_type.\n       apply HeapFacts.find_mapsto_iff in n_o_h.\n       rewrite n_o_h in l_of_type.\n       apply HeapFacts.find_mapsto_iff in n_o_h.\n       rewrite <-l_of_type in *.\n       now apply (objs_h n n' (o, type) (o', type')).\n  + exfalso; apply H.\n    unfold JFILocOfType in l_of_type.\n    destruct (Heap.find n h); try destruct l_of_type.\n    now exists o.\nQed.\n\nLemma ExtendPermutedEnvs : forall x l1 l2 env1 env2 pi,\n  EnvsPermuted env1 env2 pi ->\n  PiMapsTo l1 l2 pi ->\n  EnvsPermuted (StrMap.add x l1 env1) (StrMap.add x l2 env2) pi.\nProof.\n  intros x l1 l2 env1 env2 pi.\n  intros (bijection & same_keys & var_mapsto) pi_l1.\n  unfold EnvsPermuted in *.\n  split; [ | split]; trivial.\n  + intros y.\n    split.\n    ++ intros x_in_env.\n       apply StrMapFacts.elements_in_iff in x_in_env as (l & x_l_env).\n       apply StrMapFacts.elements_mapsto_iff, StrMapFacts.find_mapsto_iff in x_l_env.\n       apply StrMapFacts.elements_in_iff.\n       destruct (Classical_Prop.classic (x = y)).\n       +++ rewrite StrMapFacts.add_eq_o in x_l_env; trivial.\n           exists l2.\n           unfold PiMapsTo in pi_l1.\n           apply StrMapFacts.elements_mapsto_iff, StrMapFacts.find_mapsto_iff.\n           rewrite StrMapFacts.add_eq_o; trivial.\n       +++ rewrite StrMapFacts.add_neq_o in x_l_env; trivial.\n           apply StrMapFacts.find_mapsto_iff, StrMapFacts.elements_mapsto_iff in x_l_env.\n           assert (y_in_env : StrMap.In y env1).\n             apply StrMapFacts.elements_in_iff.\n             now exists l.\n           apply (same_keys y) in y_in_env.\n           apply StrMapFacts.elements_in_iff in y_in_env as (l' & x_l'_env).\n           exists l'.\n           apply StrMapFacts.elements_mapsto_iff, StrMapFacts.find_mapsto_iff.\n           apply StrMapFacts.elements_mapsto_iff, StrMapFacts.find_mapsto_iff in x_l'_env.\n           now rewrite StrMapFacts.add_neq_o.\n     ++ destruct (Classical_Prop.classic (x = y)).\n        +++ intros _.\n            apply StrMapFacts.elements_in_iff.\n            exists l1.\n            now rewrite <-StrMapFacts.elements_mapsto_iff, StrMapFacts.find_mapsto_iff,\n                StrMapFacts.add_eq_o.\n        +++ intros in_env2.\n            apply StrMapFacts.elements_in_iff in in_env2 as (l' & y_l').\n            rewrite <-StrMapFacts.elements_mapsto_iff, StrMapFacts.find_mapsto_iff,\n                StrMapFacts.add_neq_o, <-StrMapFacts.find_mapsto_iff in y_l'; trivial.\n            assert (in_env2 : StrMap.In y env2).\n              apply StrMapFacts.elements_in_iff.\n              exists l'.\n              now apply StrMapFacts.elements_mapsto_iff.\n            apply same_keys in in_env2 as in_env1.\n            apply StrMapFacts.elements_in_iff in in_env1 as (l'' & y_l'').\n            apply StrMapFacts.elements_in_iff.\n            exists l''.\n            now rewrite <-StrMapFacts.elements_mapsto_iff, StrMapFacts.find_mapsto_iff,\n                StrMapFacts.add_neq_o, <-StrMapFacts.find_mapsto_iff, StrMapFacts.elements_mapsto_iff.\n  + intros y l l' y_l y_l'.\n    destruct (Classical_Prop.classic (x = y)).\n    ++ rewrite StrMapFacts.find_mapsto_iff, StrMapFacts.add_eq_o in y_l, y_l'; trivial.\n       injection y_l as l_eq.\n       injection y_l' as l'_eq.\n       now rewrite <-l_eq, <-l'_eq.\n    ++ rewrite StrMapFacts.find_mapsto_iff, StrMapFacts.add_neq_o,\n           <-StrMapFacts.find_mapsto_iff in y_l, y_l'; trivial.\n       now apply var_mapsto with (x := y).\nQed.\n\nLemma PermutationSubsetTrans : forall pi1 pi2 pi3,\n  PermutationSubset pi1 pi2 ->\n  PermutationSubset pi2 pi3 ->\n  PermutationSubset pi1 pi3.\nProof.\n  intros pi1 pi2 pi3 pi1_pi2 pi2_pi3 x l pi1_x_l.\n  now apply pi2_pi3, pi1_pi2.\nQed.\n\nLemma ExistsPermutedResult : forall res A stn_ext pi',\n  StacksPermuted [ [] [[JFVal1 (JFVLoc res) ]]_ A] stn_ext pi' ->\n  exists res', PiMapsTo res res' pi' /\\\n       stn_ext = [ [] [[JFVal1 (JFVLoc res') ]]_ A].\nProof.\n  intros res A stn_ext pi'.\n  intros pi_st.\n  unfold StacksPermuted in pi_st.\n  destruct stn_ext; try destruct pi_st.\n  destruct stn_ext; try destruct H0.\n  unfold FramesPermuted in H.\n  destruct f.\n  destruct H as (pi_val & pi_ctxs & A_eq).\n  simpl in pi_ctxs.\n  destruct Ctx; try destruct pi_ctxs.\n  unfold ExprsPermuted in pi_val.\n  destruct E; try destruct pi_val.\n  destruct v; try destruct pi_val.\n  exists l.\n  now rewrite A_eq.\nQed.\n\nLemma PermutationPreservesClassName : forall h1 h2 n1 n2 pi C,\n  PiMapsTo (JFLoc n1) (JFLoc n2) pi ->\n  HeapsPermuted h1 h2 pi ->\n  getClassName h1 n1 = Some C ->\n  getClassName h2 n2 = Some C.\nProof.\n  intros h1 h2 n1 n2 pi C.\n  intros pi_n pi_h class.\n  unfold getClassName in *.\n  assert (exists o, Heap.find n1 h1 = Some o).\n    destruct (Heap.find n1 h1); try discriminate class.\n    now exists o.\n  destruct H as (o & n_o_h).\n  rewrite n_o_h in class.\n  destruct pi_h as (_ & locs_fst & _ & objs).\n  unfold PiMapsTo in pi_n.\n  assert (n1_in_h1 : Heap.In n1 h1).\n    apply HeapFacts.elements_in_iff.\n    exists o.\n    now apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n  destruct (locs_fst n1 n1_in_h1) as (n2' & n2'_pi & n2'_in_h2).\n  rewrite <-(MapsToEq (fst pi) n1 n2 n2') in *; trivial.\n  apply HeapFacts.elements_in_iff in n2'_in_h2.\n  destruct n2'_in_h2 as (o2 & n2_o2_h2).\n  apply HeapFacts.elements_mapsto_iff in n2_o2_h2.\n\n  apply HeapFacts.find_mapsto_iff in n_o_h.\n  destruct o as (o & cn), o2 as (o2 & cn2).\n  injection class as C_eq.\n  destruct (objs n1 n2 (o, cn) (o2, cn2)) as (cn_eq & _); trivial.\n\n  apply HeapFacts.find_mapsto_iff in n_o_h.\n  apply HeapFacts.find_mapsto_iff in n2_o2_h2.\n  now rewrite n2_o2_h2, <-cn_eq, C_eq.\nQed.\n\nLemma PermutationPreservesClassName_to_remove : forall h0 h0' h0_perm h0_ext n n_perm C pi,\n  PiMapsTo (JFLoc n) (JFLoc n_perm) pi ->\n  HeapsPermuted h0 h0_perm pi ->\n  JFIDisjointUnion h0_perm h0' h0_ext ->\n  getClassName h0 n = Some C ->\n  getClassName h0_ext n_perm = Some C.\nProof.\n  intros h0 h0' h0_perm h0_ext n n_perm C pi.\n  intros pi_n pi_h union class_name.\n  unfold getClassName in *.\n  assert (exists o, Heap.find n h0 = Some o).\n    destruct (Heap.find n h0); try discriminate class_name.\n    now exists o.\n  destruct H as (o & n_o_h).\n  rewrite n_o_h in class_name.\n  destruct pi_h as (_ & locs_fst & _ & objs).\n  unfold PiMapsTo in pi_n.\n  assert (n_in_h : Heap.In n h0).\n    apply HeapFacts.elements_in_iff.\n    exists o.\n    now apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n  destruct (locs_fst n n_in_h) as (n_perm' & n_nperm'_pi & n_perm'_in_h_perm).\n  rewrite <-(MapsToEq (fst pi) n n_perm n_perm') in *; trivial.\n  apply HeapFacts.elements_in_iff in n_perm'_in_h_perm.\n  destruct n_perm'_in_h_perm as (o' & n'_o'_h').\n  apply HeapFacts.elements_mapsto_iff in n'_o'_h'.\n\n  apply HeapFacts.find_mapsto_iff in n_o_h.\n  destruct o as (o & cn), o' as (o' & cn').\n  injection class_name as C_eq.\n  destruct (objs n n_perm (o, cn) (o', cn')) as (cn_eq & _); trivial.\n\n  apply HeapFacts.find_mapsto_iff in n_o_h.\n  assert (subheap : JFISubheap h0_perm h0_ext). apply union.\n  assert (n'_o'_h_ext := subheap n_perm (o', cn') n'_o'_h').\n  apply HeapFacts.find_mapsto_iff in n'_o'_h_ext.\n  now rewrite n'_o'_h_ext, <-cn_eq, C_eq.\nQed.\n\nLemma PermutationPreservesSubstExpr : forall e e' pi f l l' e_body e_body',\n  ExprsPermuted e_body e_body' pi ->\n  ExprsPermuted e e' pi ->\n  PiMapsTo l l' pi ->\n  substExpr f l e_body = e ->\n  substExpr f l' e_body' = e'.\nProof.\nAdmitted.\n\nLemma SubstPermutedExpr : forall f l l' e e' pi,\n  ExprsPermuted e e' pi ->\n  PiMapsTo l l' pi ->\n  ExprsPermuted (substExpr f l e) (substExpr f l' e') pi.\nProof.\nAdmitted.\n\nLemma PermutationPreservesSubstList : forall fs vs vs',\n  (forall f, In f fs -> f <> JFThis) ->\n  length fs = length vs ->\n  length vs = length vs' -> forall e_body e_body' n n' e pi,\n  ValsPermuted vs vs' pi ->\n  ExprsPermuted e_body e_body' pi ->\n  PiMapsTo (JFLoc n) (JFLoc n') pi ->\n  substList fs vs  (substExpr JFThis (JFLoc n) e_body) = Some e ->\n  exists e',\n  ExprsPermuted e e' pi /\\\n  substList fs vs' (substExpr JFThis (JFLoc n') e_body') = Some e'.\nProof.\n  intros fs vs vs' fs_not_this fs_length_eq vs_length_eq.\n  set (_fs := fs).\n  replace fs with _fs in fs_not_this; try now unfold _fs.\n  set (_vs := vs).\n  set (_vs' := vs').\n  replace _fs  with (fst (split (combine fs (combine vs vs')))) in *.\n  replace _vs  with (fst (split (snd (split (combine fs (combine vs vs')))))).\n  replace _vs' with (snd (split (snd (split (combine fs (combine vs vs')))))).\n  clear fs_length_eq vs_length_eq _fs _vs _vs'.\n  induction (combine fs (combine vs vs')); clear fs vs vs'.\n  + intros e_body e_body' n n' e pi.\n    intros pi_vs pi_body pi_n subst.\n    simpl in *.\n    destruct (ExistsPermutedExpr e pi) as (e' & pi_e).\n    exists e'.\n    split; trivial.\n    unfold substList in *.\n    injection subst as subst.\n    apply PermutationPreservesSubstExpr\n      with (e' := e') (e_body' := e_body') (l' := (JFLoc n')) (pi := pi) in subst; trivial.\n    now rewrite subst.\n  + intros e_body e_body' n n' e pi.\n    intros pi_vs pi_body pi_n subst.\n    destruct a as (f & (v & v')).\n    simpl in *.\n    destruct (split l) as (fs & vs_vs').\n    unfold fst, snd in *.\n    simpl in *.\n    unfold fst, snd in *.\n    destruct (split vs_vs') as (vs & vs').\n    destruct v; try discriminate subst.\n    destruct v'; try destruct pi_vs.\n    assert (next_f_not_this : (forall f : JFRef, In f fs -> f <> JFThis)).\n      intros f0 f0_in_fs. apply (fs_not_this f0). now apply or_intror.\n    rewrite SubstExprComm in subst; [ | now apply fs_not_this, or_introl].\n    destruct (IHl next_f_not_this (substExpr f l0 e_body) (substExpr f l1 e_body') n n' e pi)\n      as (e' & pi_e & subst'); trivial.\n    now apply SubstPermutedExpr.\n    rewrite SubstExprComm in subst'; [ | now apply neq_symmetry, fs_not_this, or_introl].\n    now exists e'.\n    now exists e.\n  + rewrite combine_split; trivial.\n    ++ unfold snd.\n       rewrite combine_split; trivial.\n    ++ rewrite combine_length.\n       rewrite <-vs_length_eq, <-fs_length_eq.\n       now rewrite min_r.\n  + rewrite combine_split; trivial.\n    ++ unfold snd.\n       rewrite combine_split; trivial.\n    ++ rewrite combine_length.\n       rewrite <-vs_length_eq, <-fs_length_eq.\n       now rewrite min_r.\n  + rewrite combine_split; trivial.\n    rewrite combine_length.\n    rewrite <-vs_length_eq, <-fs_length_eq.\n    now rewrite min_r.\nQed.\n\nLemma PermutedValsLength: forall vs vs' pi,\n  ValsPermuted vs vs' pi ->\n  length vs = length vs'.\nProof.\n  intros vs.\n  induction vs.\n + intros vs' pi pi_vs;\n    destruct vs';\n    try destruct a;\n    try now destruct pi_vs.\n  + intros vs' pi pi_vs.\n    destruct vs', a;\n    try now destruct pi_vs;\n    simpl in *;\n    now rewrite IHvs with (vs' := vs') (pi := pi).\nQed.\n\nLemma PermutedCtxsLength : forall ctxs ctxs_perm pi,\n  CtxsPermuted ctxs ctxs_perm pi ->\n  length ctxs = length ctxs_perm.\nProof.\n  intros ctxs.\n  induction ctxs;\n    intros ctxs_perm pi pi_ctxs;\n    destruct ctxs_perm; try now destruct pi_ctxs.\n  simpl in *.\n  now rewrite IHctxs with (ctxs_perm := ctxs_perm) (pi := pi).\nQed.\n\nLemma PermutedStacksLength : forall st st_perm pi,\n  StacksPermuted st st_perm pi ->\n  length st = length st_perm.\nProof.\n  intros st.\n  induction st;\n    intros st_perm pi pi_st;\n    destruct st_perm; try now destruct pi_st.\n  simpl in *.\n  now rewrite (IHst st_perm pi).\nQed.\n\nLemma PermutedZipLength: forall fs fs' pi,\n  ZipPermuted fs fs' pi ->\n  length fs = length fs'.\nProof.\n  intros vs.\n  induction vs.\n + intros vs' pi pi_vs;\n    destruct vs';\n    try destruct a;\n    try now destruct pi_vs.\n  + intros vs' pi pi_vs.\n    destruct vs';\n    try now destruct a, pi_vs.\n    simpl in *;\n    rewrite IHvs with (fs' := vs') (pi := pi); try easy.\n    now destruct a, p, pi_vs as (_ & _ & pi_zip).\nQed.\n\n(* Lemmas about extending permutations *)\n\nLemma ExtendValsPermutation : forall vs vs_perm pi pi',\n  ValsPermuted vs vs_perm pi ->\n  PermutationSubset pi pi' ->\n  ValsPermuted vs vs_perm pi'.\nProof.\n  intros vs vs_perm pi pi' pi_vs pi_subset.\n  assert (length_eq : length vs = length vs_perm).\n    now apply PermutedValsLength with (pi := pi).\n  induction2 vs vs_perm length_eq v v_perm vs' vs'_perm; try easy.\n  simpl in *.\n  destruct v, v_perm; try now destruct pi_vs; split.\n  + split; [now apply pi_subset | now apply IH_l].\n  + split; [now apply pi_vs | now apply IH_l].\nQed.\n\nLemma ExtendExprsPermutation : forall e e_perm pi pi',\n  ExprsPermuted e e_perm pi ->\n  PermutationSubset pi pi' ->\n  ExprsPermuted e e_perm pi'.\nProof.\n  intros e.\n  induction e;\n    intros e_perm pi pi' pi_e pi_subset;\n    destruct e_perm;\n    try now (\n    try destruct v;  try destruct v0;\n    try destruct v1; try destruct v2;\n    try destruct v3; try destruct vx, j;\n    destruct pi_e).\n  + simpl in *.\n    split; try split; try easy.\n    now apply ExtendValsPermutation with (pi := pi).\n  + simpl in *.\n    split; try split; try split; try easy.\n    now apply IHe1 with (pi := pi).\n    now apply IHe2 with (pi := pi).\n  + simpl in *.\n    destruct v0, v1, v2, v3; simpl in pi_e; try now destruct pi_e.\n    ++ split; try split; try split; try now apply pi_subset.\n       now apply IHe1 with (pi := pi).\n       now apply IHe2 with (pi := pi).\n    ++ split; try split; try split; try now apply pi_subset.\n       now apply IHe1 with (pi := pi).\n       now apply IHe2 with (pi := pi).\n       now apply pi_e.\n    ++ split; try split; try split; try now apply pi_subset.\n       now apply IHe1 with (pi := pi).\n       now apply IHe2 with (pi := pi).\n       now apply pi_e.\n    ++ split; try split; try split; try now apply pi_subset.\n       now apply IHe1 with (pi := pi).\n       now apply IHe2 with (pi := pi).\n       now apply pi_e.\n       now apply pi_e.\n  + simpl in *.\n    destruct v, v0; try now destruct pi_e.\n    ++ split; try split; try easy.\n       now apply pi_subset.\n       now apply ExtendValsPermutation with (pi := pi).\n    ++ split; try split; try easy.\n       now apply ExtendValsPermutation with (pi := pi).\n  + simpl in *.\n    destruct vx, v, vx0, j1, v0, j; try now destruct pi_e;\n    split; try split; try easy; now apply pi_subset.\n  + simpl in *.\n    destruct v, v0; try now destruct pi_e.\n    now apply pi_subset.\n  + simpl in *.\n    destruct vx, vx0, j, j1; try now destruct pi_e.\n    destruct pi_e.\n    split; try easy; now apply pi_subset.\n  + simpl in *.\n    destruct v, v0; try now destruct pi_e.\n    now apply pi_subset.\n  + simpl in *.\n    destruct pi_e as (mu_eq & cn_eq & x_eq & pi_e1 & pi_2).\n    split; [ | split; [ | split; [ | split]]]; trivial.\n    now apply IHe1 with (pi := pi).\n    now apply IHe2 with (pi := pi).\nQed.\n\nLemma ExtendCtxPermutation : forall ctx ctx_perm pi pi',\n  CtxPermuted ctx ctx_perm pi ->\n  PermutationSubset pi pi' ->\n  CtxPermuted ctx ctx_perm pi'.\nProof.\n  intros ctx ctx_perm pi pi' pi_ctx pi_subset.\n  destruct ctx, ctx_perm; try now destruct pi_ctx.\n  + unfold CtxPermuted in *.\n    destruct pi_ctx.\n    split; try split; try easy.\n    now apply ExtendExprsPermutation with (pi := pi).\n  + unfold CtxPermuted in *.\n    destruct pi_ctx.\n    split; try split; try easy.\n    now apply ExtendExprsPermutation with (pi := pi).\nQed.\n\nLemma ExtendCtxsPermutation : forall ctxs ctxs_perm pi pi',\n  CtxsPermuted ctxs ctxs_perm pi ->\n  PermutationSubset pi pi' ->\n  CtxsPermuted ctxs ctxs_perm pi'.\nProof.\n  intros ctxs ctxs_perm pi pi' pi_ctx pi_subset.\n  assert (length_eq : length ctxs = length ctxs_perm).\n    now apply PermutedCtxsLength with (pi := pi).\n\n  induction2 ctxs ctxs_perm length_eq ctx ctx_perm ctxs' ctxs'_perm; try easy.\n  simpl in *.\n  destruct pi_ctx as (pi_ctx & pi_ctxs).\n  split.\n  now apply ExtendCtxPermutation with (pi := pi).\n  now apply IH_l.\nQed.\n\nLemma ExtendFramePermutation : forall f f_perm pi pi',\n  FramesPermuted f f_perm pi ->\n  PermutationSubset pi pi' ->\n  FramesPermuted f f_perm pi'.\nProof.\n  intros f f_perm pi pi' pi_f pi_subset.\n  unfold FramesPermuted in *.\n  destruct f, f_perm.\n  destruct pi_f as (pi_e & pi_ctx & a_eq).\n  split; try split; try easy.\n  now apply ExtendExprsPermutation with (pi := pi).\n  now apply ExtendCtxsPermutation with (pi := pi).\nQed.\n\nLemma ExtendStacksPermutation : forall st st_perm pi pi',\n  StacksPermuted st st_perm pi ->\n  PermutationSubset pi pi' ->\n  StacksPermuted st st_perm pi'.\nProof.\n  intros st st_perm pi pi' pi_st pi_subset.\n  assert (length_eq : length st = length st_perm).\n    now apply PermutedStacksLength with (pi := pi).\n\n  induction2 st st_perm length_eq f f_perm st' st'_perm; try easy.\n  simpl in *.\n  destruct pi_st as (pi_f & pi_st).\n  split.\n  now apply ExtendFramePermutation with (pi := pi).\n  now apply IH_l.\nQed.\n\nLemma ExtendObjPermutation : forall o o_perm pi pi',\n  ObjPermuted o o_perm pi ->\n  PermutationSubset pi pi' ->\n  ObjPermuted o o_perm pi'.\nProof.\nAdmitted.\n\nLemma ExtendHeapsPermutation : forall h h_perm pi pi',\n  HeapsPermuted h h_perm pi ->\n  PermutationSubset pi pi' ->\n  HeapsPermuted h h_perm pi'.\nProof.\nAdmitted.\n\nLemma ExtendPermutedHeaps : forall h h' n n' o o' pi,\n  HeapsPermuted h h' pi ->\n  NatMap.MapsTo n n' (fst pi) ->\n  ObjPermuted o o' pi ->\n  HeapsPermuted (Heap.add n o h) (Heap.add n' o' h') pi.\nProof.\n  intros h h' n n' o o' pi.\n  intros pi_h pi_n pi_o.\n  destruct pi_h as (bijection & locs_fst & locs_snd & objs).\n  unfold HeapsPermuted.\n  split; [ | split; [ | split]]; trivial.\n  + unfold HeapLocsPermuted.\n    intros n1 n1_in_add.\n    destruct (Classical_Prop.classic (n = n1)).\n    ++ rewrite <-H in *.\n       exists n'.\n       split; trivial.\n       apply HeapFacts.elements_in_iff.\n       exists o'.\n       apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n       now rewrite HeapFacts.add_eq_o.\n    ++ apply HeapFacts.elements_in_iff in n1_in_add as (o1 & n1_o1).\n       apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff in n1_o1.\n       rewrite HeapFacts.add_neq_o in n1_o1; trivial.\n       destruct (locs_fst n1) as (n2 & pi_n1 & n2_in_h').\n         apply HeapFacts.elements_in_iff.\n         apply HeapFacts.find_mapsto_iff, HeapFacts.elements_mapsto_iff in n1_o1.\n         now exists o1.\n       exists n2.\n       split; trivial.\n       apply HeapFacts.elements_in_iff in n2_in_h' as (o2 & n2_o2).\n       apply HeapFacts.elements_in_iff.\n       exists o2.\n       apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n       assert (n' <> n2).\n         intros n1_eq.\n         apply H.\n         apply bijection in pi_n1.\n         apply bijection in pi_n.\n         rewrite <-n1_eq in pi_n1.\n         now apply MapsToEq with (n2 := n1) in pi_n.\n       rewrite HeapFacts.add_neq_o; trivial.\n       now apply HeapFacts.find_mapsto_iff, HeapFacts.elements_mapsto_iff.\n  + unfold HeapLocsPermuted.\n    intros n1 n1_in_add.\n    destruct (Classical_Prop.classic (n' = n1)).\n    ++ rewrite <-H in *.\n       exists n.\n       apply bijection in pi_n.\n       split; trivial.\n       apply HeapFacts.elements_in_iff.\n       exists o.\n       apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n       now rewrite HeapFacts.add_eq_o.\n    ++ apply HeapFacts.elements_in_iff in n1_in_add as (o1 & n1_o1).\n       apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff in n1_o1.\n       rewrite HeapFacts.add_neq_o in n1_o1; trivial.\n       destruct (locs_snd n1) as (n2 & pi_n1 & n2_in_h').\n         apply HeapFacts.elements_in_iff.\n         apply HeapFacts.find_mapsto_iff, HeapFacts.elements_mapsto_iff in n1_o1.\n         now exists o1.\n       exists n2.\n       split; trivial.\n       apply HeapFacts.elements_in_iff in n2_in_h' as (o2 & n2_o2).\n       apply HeapFacts.elements_in_iff.\n       exists o2.\n       apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n       assert (n <> n2).\n         intros n1_eq.\n         apply H.\n         apply bijection in pi_n1.\n         rewrite <-n1_eq in pi_n1.\n         now apply MapsToEq with (n2 := n1) in pi_n.\n       rewrite HeapFacts.add_neq_o; trivial.\n       now apply HeapFacts.find_mapsto_iff, HeapFacts.elements_mapsto_iff.\n  + unfold ObjsPermuted.\n    intros n1 n2 o1 o2.\n    intros pi_n1 n1_o1 n2_o2.\n    destruct (Classical_Prop.classic (n = n1)).\n    ++ rewrite <-H in *.\n       apply HeapFacts.find_mapsto_iff in n1_o1.\n       apply HeapFacts.find_mapsto_iff in n2_o2.\n       assert (n' = n2).\n         now apply MapsToEq with (n2 := n2) in pi_n.\n       rewrite HeapFacts.add_eq_o in n1_o1, n2_o2; trivial.\n       injection n1_o1 as o1_eq.\n       injection n2_o2 as o2_eq.\n       now rewrite <-o1_eq, <-o2_eq.\n    ++ assert (n' <> n2).\n         intros n'_eq_n2.\n         apply H.\n         rewrite n'_eq_n2 in *.\n         apply bijection in pi_n.\n         apply bijection in pi_n1.\n         now apply MapsToEq with (n2 := n1) in pi_n.\n    rewrite HeapFacts.find_mapsto_iff, HeapFacts.add_neq_o, <-HeapFacts.find_mapsto_iff in n1_o1, n2_o2; trivial.\n    now apply (objs n1 n2 o1 o2).\nQed.\n\nLemma ChangeFieldInPermutedHeaps : forall n n' f l l' ro ro' cid h h' pi,\n  HeapsPermuted h h' pi ->\n  NatMap.MapsTo n n' (fst pi) ->\n  Heap.find n h = Some (ro, cid) ->\n  Heap.find n' h' = Some (ro', cid) ->\n  PiMapsTo l l' pi ->\n  HeapsPermuted (Heap.add n  (JFXIdMap.add f l  ro , cid) h)\n                (Heap.add n' (JFXIdMap.add f l' ro', cid) h') pi.\nProof.\n  intros n n' f l l' ro ro' cid h h' pi.\n  intros pi_h pi_n n_ro n'_ro' pi_l.\n  apply ExtendPermutedHeaps; trivial.\n  destruct pi_h as (bijection & locs_fst & locs_snd & objs).\n  unfold ObjPermuted.\n  split; trivial.\n  intros f'.\n  destruct (Classical_Prop.classic (f = f')).\n  + split; [ | split].\n    ++ intros v1 f'_v1.\n       exists l'.\n       now rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_eq_o in f'_v1 |-*.\n    ++ intros v2 f'_v2.\n       exists l.\n       now rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_eq_o in f'_v2 |-*.\n    ++ intros v1 v2 f'_v1 f'_v2.\n       rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_eq_o in f'_v1, f'_v2; trivial.\n       injection f'_v1 as v1_eq.\n       injection f'_v2 as v2_eq.\n       now rewrite <-v1_eq, <-v2_eq.\n  + apply HeapFacts.find_mapsto_iff in n_ro.\n    apply HeapFacts.find_mapsto_iff in n'_ro'.\n    destruct (objs n n' (ro, cid) (ro', cid)) as (_ & H2); trivial.\n    destruct (H2 f') as (IH1 & IH2 & IH3); clear H2.\n    split; [ | split].\n    ++ intros v1 f'_v1.\n       rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_neq_o in f'_v1; trivial.\n       rewrite <-JFXIdMapFacts.find_mapsto_iff in f'_v1.\n       destruct (IH1 v1) as (v2 & f'_v2); trivial.\n       exists v2.\n       now rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_neq_o, <-JFXIdMapFacts.find_mapsto_iff.\n    ++ intros v2 f'_v2.\n       rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_neq_o in f'_v2; trivial.\n       rewrite <-JFXIdMapFacts.find_mapsto_iff in f'_v2.\n       destruct (IH2 v2) as (v1 & f'_v1); trivial.\n       exists v1.\n       now rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_neq_o, <-JFXIdMapFacts.find_mapsto_iff.\n    ++ intros v1 v2 f'_v1 f'_v2.\n       rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_neq_o, <-JFXIdMapFacts.find_mapsto_iff in f'_v1, f'_v2; trivial.\n       now apply IH3.\nQed.\n\nLemma ExistsInPermutedHeap : forall n n' h h' pi ro cid,\n  HeapsPermuted h h' pi ->\n  NatMap.MapsTo n n' (fst pi) ->\n  Heap.find n h = Some (ro, cid) ->\n  exists ro', Heap.find n' h' = Some (ro', cid).\nProof.\n  intros n n' h h' pi ro cid.\n  intros pi_h pi_n n_ro.\n  destruct pi_h as (bijection & locs_fst & locs_snd & objs).\n  destruct (locs_fst n) as (n'' & pi_n'' & n'_h').\n    rewrite HeapFacts.elements_in_iff.\n    exists (ro, cid).\n    now apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n  apply MapsToEq with (n2 := n'') in pi_n as n''_eq; trivial.\n  rewrite n''_eq in *.\n  apply HeapFacts.elements_in_iff in n'_h' as (o' & n'_o').\n  apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff in n'_o'.\n  destruct o' as (ro', cid').\n  rewrite <-HeapFacts.find_mapsto_iff in n_ro, n'_o'.\n  unfold ObjsPermuted in objs.\n  destruct (objs n n' (ro, cid) (ro', cid')) as (cid_eq & _); trivial.\n  rewrite <-cid_eq in *.\n  apply HeapFacts.find_mapsto_iff in n'_o'.\n  now exists ro'.\nQed.\n\nLemma LocOfValsPermutation : forall vs locs vs_perm pi,\n  list_map_opt loc_of_val vs = Some locs ->\n  ValsPermuted vs vs_perm pi ->\n  exists locs', \n    list_map_opt loc_of_val vs_perm = Some locs' /\\\n    LocsPermuted locs locs' pi.\nProof.\n  intros vs.\n  induction vs; intros locs vs_perm pi locs_of_vs pi_vs.\n  + exists [].\n    simpl in *.\n    destruct vs_perm; try destruct pi_vs.\n    injection locs_of_vs as locs_eq.\n    now rewrite <- locs_eq.\n  + simpl in *.\n    destruct a, vs_perm; try destruct j; try now destruct pi_vs.\n    simpl in locs_of_vs.\n    destruct locs as [ | loc locs].\n      destruct (list_map_opt loc_of_val vs); try discriminate locs_of_vs.\n    assert (locs_of_vs' : list_map_opt loc_of_val vs = Some locs).\n      destruct (list_map_opt loc_of_val vs); try discriminate locs_of_vs.\n      injection locs_of_vs.\n      intros locs_eq _.\n      now rewrite locs_eq.\n    assert (l_eq : l = loc).\n      destruct (list_map_opt loc_of_val vs); try discriminate locs_of_vs.\n      now injection locs_of_vs.\n    rewrite l_eq in *.\n    destruct (IHvs locs vs_perm pi) as (locs' & locs'_of_vs_perm & pi_locs) ; try easy.\n    exists (l0::locs').\n    split; try easy.\n    simpl.\n    now rewrite locs'_of_vs_perm.\nQed.\n\nLemma ExistsPermutedZip : forall flds locs locs_perm flds_locs pi,\n  JaUtils.zip flds locs = Some flds_locs ->\n  LocsPermuted locs locs_perm pi ->\n  exists flds_locs_perm,\n    JaUtils.zip flds locs_perm = Some flds_locs_perm /\\ ZipPermuted flds_locs flds_locs_perm pi.\nProof.\n  intros flds.\n  induction flds as [ | fld]; intros locs locs_perm flds_locs pi zip_flds_locs pi_locs.\n  + destruct locs, flds_locs; try discriminate zip_flds_locs.\n    destruct locs_perm; try now destruct pi_locs.\n    now exists [].\n  + destruct locs as [ | loc]; try discriminate zip_flds_locs.\n    simpl in zip_flds_locs.\n    destruct flds_locs as [ | fld_loc]; try now (destruct (JaUtils.zip flds locs); discriminate zip_flds_locs).\n    destruct locs_perm as [ | loc_perm]; try now destruct pi_locs.\n    destruct pi_locs as (pi_loc & pi_locs).\n    assert (exists flds_locs', JaUtils.zip flds locs = Some flds_locs').\n      destruct (JaUtils.zip flds locs) as [flds_locs' | ]; try discriminate zip_flds_locs.\n      now exists flds_locs'.\n    destruct H as (flds_locs' & zip_flds).\n    rewrite zip_flds in zip_flds_locs.\n    injection zip_flds_locs as fld_loc_eq flds_locs_eq.\n    rewrite flds_locs_eq in *.\n    destruct (IHflds locs locs_perm flds_locs pi)\n      as (flds_locs_perm & zip_perm & pi_zip); try easy.\n    exists ((fld, loc_perm)::flds_locs_perm).\n    simpl.\n    rewrite zip_perm.\n    split; trivial.\n    now rewrite <-fld_loc_eq.\nQed.\n\nLemma PermutedZipIsPermutedInit : forall flds_locs flds_locs_perm cn o o_perm pi,\n  ZipPermuted flds_locs flds_locs_perm pi ->\n  ObjPermuted (o, cn) (o_perm, cn) pi ->\n  ObjPermuted (init_obj_aux o flds_locs, cn)\n              (init_obj_aux o_perm flds_locs_perm, cn) pi.\nProof.\n  intros flds_locs flds_locs_perm.\n  intros cn o o_perm pi pi_zip.\n  generalize cn o o_perm.\n  clear o_perm o cn.\n  assert (length_eq : length flds_locs = length flds_locs_perm).\n    now apply PermutedZipLength with (pi := pi).\n  induction2 flds_locs flds_locs_perm length_eq fld_loc fld_loc_perm flds_locs' flds_locs_perm';\n    intros cn o o_perm pi_o.\n  + simpl.\n    split; trivial.\n    intros f.\n    destruct pi_o as (_ & pi_o).\n    apply pi_o.\n  + split; trivial.\n    intros f.\n    simpl in pi_zip.\n    destruct fld_loc as (fld & loc), fld_loc_perm as (fld_perm & loc_perm).\n    destruct pi_zip as (fld_eq & pi_loc & pi_locs).\n    rewrite <-fld_eq; clear fld_eq fld_perm.\n    apply (IH_l pi_locs cn (JFXIdMap.add fld loc o) (JFXIdMap.add fld loc_perm o_perm)); trivial.\n    split; trivial.\n    intros f'.\n    destruct (Classical_Prop.classic (fld = f')).\n    ++ split; [ | split].\n       +++ intros v1 f'_v1.\n           exists loc_perm.\n           now rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_eq_o.\n       +++ intros v2 f1'_v2.\n           exists loc.\n           now rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_eq_o.\n       +++ intros v1 v2 f'_v1 f'_v2.\n           rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_eq_o in f'_v1, f'_v2; trivial.\n           injection f'_v1 as v1_eq.\n           injection f'_v2 as v2_eq.\n           now rewrite <-v1_eq, <-v2_eq.\n    ++ destruct pi_o as (_ & H0).\n       destruct (H0 f') as (pi_fst & pi_snd & pi_o).\n       clear H0.\n       split; [ | split].\n       +++ intros v1 f'_v1.\n           rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_neq_o,\n                 <-JFXIdMapFacts.find_mapsto_iff in f'_v1; trivial.\n           apply pi_fst in f'_v1.\n           destruct f'_v1 as (v2 & f'_v2).\n           exists v2.\n           rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_neq_o,\n                 <-JFXIdMapFacts.find_mapsto_iff; trivial.\n       +++ intros v2 f'_v2.\n           rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_neq_o,\n                 <-JFXIdMapFacts.find_mapsto_iff in f'_v2; trivial.\n           apply pi_snd in f'_v2.\n           destruct f'_v2 as (v1 & f'_v1).\n           exists v1.\n           rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_neq_o,\n                 <-JFXIdMapFacts.find_mapsto_iff; trivial.\n      +++ intros v1 v2 f'_v1 f'_v2.\n          rewrite JFXIdMapFacts.find_mapsto_iff, JFXIdMapFacts.add_neq_o,\n                <-JFXIdMapFacts.find_mapsto_iff in f'_v1, f'_v2; trivial.\n          now apply pi_o.\nAdmitted.\n\nLemma ExtendPiSubset : forall pi n0 n0_perm,\n  ~(NatMap.In n0 (fst pi)) ->\n  PermutationSubset pi (NatMap.add n0 n0_perm (fst pi), NatMap.add n0_perm n0 (snd pi)).\nProof.\n  intros pi n0 n0_perm not_in_pi. \n  destruct pi as (pi_fst & pi_snd).\n  simpl.\n  intros l l' l_l'.\n  destruct l as [ | n], l' as [ | n']; try now destruct l_l'; try easy.\n  destruct (Classical_Prop.classic (n0 = n)).\n  + exfalso.\n    rewrite H in *.\n    apply not_in_pi.\n    unfold PiMapsTo in l_l'.\n    apply NatMapFacts.elements_in_iff.\n    exists n'.\n    now apply HeapFacts.elements_mapsto_iff.\n  + unfold PiMapsTo.\n    simpl.\n    rewrite NatMapFacts.find_mapsto_iff, NatMapFacts.add_neq_o, <-NatMapFacts.find_mapsto_iff; try easy.\nQed.\n\nLemma PermutedClass : forall h h' n n' cn pi,\n  HeapsPermuted h h' pi ->\n  PiMapsTo (JFLoc n) (JFLoc n') pi ->\n  class h n = Some cn ->\n  class h' n' = Some cn.\nProof.\n  intros h h' n n' cn pi.\n  intros pi_h pi_n n_cn.\n  unfold class in *.\n  assert (exists o, NatMap.find n h = Some o).\n    destruct (NatMap.find n h); try discriminate n_cn.\n    now exists o.\n  destruct H as (o & n_o).\n  rewrite n_o in n_cn.\n  destruct pi_h as (_ & locs_fst & _ & pi_o).\n  destruct (locs_fst n) as (n'' & n_n'' & n'_in_h).\n    apply HeapFacts.elements_in_iff.\n    exists o.\n    now apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\n  unfold PiMapsTo in pi_n.\n  apply MapsToEq with (n2 := n') in n_n''; trivial.\n  rewrite <-n_n'' in *; clear n_n'' n''.\n  apply HeapFacts.elements_in_iff in n'_in_h as (o' & n'_o').\n  apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff in n'_o'.\n  rewrite n'_o'.\n  destruct o as (ro, cn0), o' as (ro' & cn').\n  injection n_cn as cn_eq.\n  rewrite cn_eq in *; clear cn_eq cn0.\n  unfold ObjsPermuted in pi_o.\n  rewrite <-HeapFacts.find_mapsto_iff in n_o, n'_o'.\n  destruct (pi_o n n' (ro, cn) (ro', cn') pi_n n_o n'_o') as (cn_eq & _).\n  now rewrite cn_eq.\nQed.\n\nLemma EqPermuted1 : forall h1 h1' h2 pi,\n  HeapsPermuted h1 h2 pi ->\n  HeapEq h1 h1' ->\n  HeapsPermuted h1' h2 pi.\nProof.\nAdmitted.\n\nLemma EqPermuted2 : forall h1 h2 h2' pi,\n  HeapsPermuted h1 h2 pi ->\n  HeapEq h2 h2' ->\n  HeapsPermuted h1 h2' pi.\nProof.\nAdmitted.\n\nLemma SubenvPermuted : forall env1 env2 pi,\n  EnvsPermuted env2 env2 pi ->\n  Subenv env1 env2 ->\n  EnvsPermuted env1 env1 pi.\nProof.\n  intros env1 env2 pi.\n  intros (bijection & same_keys & pi_env) subenv.\n  unfold EnvsPermuted.\n  split; [ | split]; try easy.\n  intros x l1 l2 x_l1 x_l2.\n  apply pi_env with (x := x); now apply subenv.\nQed.\n\nLemma ExtendingSubenv : forall x l env1 env2,\n  Subenv env1 env2 ->\n  Subenv (StrMap.add x l env1) (StrMap.add x l env2).\nProof.\n  intros x l env1 env2 subenv.\n  intros x' l' x'_l'.\n  rewrite StrMapFacts.find_mapsto_iff in *.\n  destruct (Classical_Prop.classic (x = x')).\n  + now rewrite StrMapFacts.add_eq_o in *.\n  + rewrite StrMapFacts.add_neq_o in *; try easy.\n    rewrite <-StrMapFacts.find_mapsto_iff in *.\n    now apply subenv.\nQed.\n", "meta": {"author": "jbujak", "repo": "jafun", "sha": "4b9b2d21ba06e6a98c885c8bf2cc202f52595058", "save_path": "github-repos/coq/jbujak-jafun", "path": "github-repos/coq/jbujak-jafun/jafun-4b9b2d21ba06e6a98c885c8bf2cc202f52595058/JaIrisPermutation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.243726875761203}}
{"text": "\n\n\nFrom RecordUpdate Require Export RecordSet.\nExport RecordSetNotations.\nFrom mathcomp Require Export all_ssreflect.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n(********************)\n(* メタ・アサンプション *)\n(********************)\n\n\n(* finTypeのtimestamp *)\nParameter limit_time' : nat.\nDefinition limit_time := limit_time' + 1.\nDefinition timestamp := ordinal limit_time.\nParameter now : timestamp.\n\n(* 各行政機関を表す変数 *)\nInductive admin := Admin of nat.\n\n(* 通貨 *)\nInductive currency := Curr of nat.\n\nDefinition plusc (x y : currency) :=\n    match x, y with \n    | Curr x_, Curr y_ => Curr (x_ + y_)\n    end.\n    \nDefinition minusc (x y : currency) :=\n    match x, y with \n    | Curr x_, Curr y_ => Curr (x_ - y_)\n    end.   \n\n\n(* 市民 *)\nParameter citizen : finType.\n\n(* 乱数 *)\nDefinition random := Type.\n\n(* 乱数と集合をとり、ランダムに要素を抽出する関数 *)\nParameter random_choice : forall {T : finType}, {set T} -> random -> T.\nAxiom random_choice_axiom : forall (T : finType) r (A : {set T}), \n    random_choice A r \\in A.\n\n(* 乱数と集合をとり、任意の大きさの部分集合を返す関数 *)\n(* この公理は、#|A| < n の時に矛盾が生じるので要修正 *)\nParameter random_choice_set : forall {T : finType} (A : {set T}),random -> nat -> {set T}.\nAxiom random_choice_set_axiom : forall {T : finType} r (A : {set T}) n,\n    let B := @random_choice_set T A r n in \n    (B \\subset A) && (#|B| == n).\n\n\n\n\n(************)\n(* アクション *)\n(************)\n\nInductive proposal  :=\n    (* 国庫・予算の入出金 *)\n    | PwithdrawTreasury : currency -> proposal\n    | PdepositTreasury : currency -> proposal\n    | PwithdrawBudget : admin -> currency -> proposal \n    | PdepositBudget : admin -> currency -> proposal \n    | Pallocate : admin -> currency -> proposal\n    (* 役職への任免・罷免 *)\n    | PassignMember : admin -> citizen -> proposal\n    | PdismissalMember : admin -> citizen -> proposal    \n    | PassignTenureWorker : admin -> citizen -> timestamp -> proposal    \n    | PdismissalTenureWorker : admin -> citizen -> proposal\n    (* 市民登録・解除 *)\n    | Pregister : citizen -> proposal\n    | Pderegister : citizen -> proposal\n    (* 行政の追加・削除 *)\n    | PgenAdmin : admin -> proposal \n    | PslashAdmin : admin -> proposal.\n\n\n\nInductive act :=\n    (* グローバルな委員会への提案と熟議 *)\n    | AglobalPropose : proposal -> random -> random -> random -> nat -> act    \n    | AglobalDeliberate : act\n    (* subStateの委員会への提案と熟議 *)\n    | AsubPropose : admin -> proposal -> random -> random -> random -> nat -> act\n    | AsubDeliberate : admin -> act.\n    \n\n\n\n(************) \n(* 状態と熟議 *)\n(************)\n\nRecord comitee := mkDlb{\n    Dproposal : proposal;\n    Dprofessional : citizen;\n    Dfacilitator : citizen;\n    Ddeliberator : {set citizen};\n}.\n\nRecord subState := mkSubState {\n    SSbudget : currency;\n    SSmember : {set citizen};\n    SScomitee : option comitee;\n    SStenureWorker : {set citizen * timestamp};\n}.\n\nDefinition empty_subState := mkSubState (Curr 0) set0 None set0.\n\n\nRecord state := mkState{\n    Streasury : currency;\n    Smember : {set citizen};\n    Scomitee : option comitee;\n    Ssubstate : admin -> option subState\n}.\n\n(*******************)\n(* 各種インスタンス化 *)\n(*+++++++++++++++++*)\n\nInstance etaSubState : Settable subState :=\n    settable! mkSubState <SSbudget; SSmember; SScomitee; SStenureWorker>.        \n\nInstance etaState : Settable state := \n    settable! mkState \n        < Streasury; Smember; Scomitee;Ssubstate >.\n\n\nCoercion nat_of_admin a := let : Admin n := a in n.\nCanonical admin_subType  := [newType for nat_of_admin ].\nDefinition admin_eqMixin := Eval hnf in [eqMixin of admin by <:].\nCanonical admin_eqType := Eval hnf in EqType admin admin_eqMixin.\n\nCoercion nat_of_currency a := let : Curr n := a in n.\nCanonical currency_subType  := [newType for nat_of_currency ].\nDefinition currency_eqMixin := Eval hnf in [eqMixin of currency by <:].\nCanonical currency_eqType := Eval hnf in EqType currency currency_eqMixin.\n\nTactic Notation \"mkCompEq\"  :=\n    refine (EqMixin (compareP _)) => x y;\n    unfold decidable; decide equality; apply eq_comparable.\nNotation eqMixin := Equality.mixin_of.\n\n\nDefinition proposal_eqMixin : eqMixin proposal. Proof. mkCompEq. Qed.\nCanonical Structure proposal_eqType := Eval hnf in @EqType proposal proposal_eqMixin.\n\n\nDefinition comitee_eqMixin  : eqMixin comitee. Proof. mkCompEq. Qed.\nCanonical Structure comitee_eqType := Eval hnf in @EqType comitee comitee_eqMixin.        \n\nDefinition subState_eqMixin : eqMixin subState. Proof. \n    refine (EqMixin (compareP _)) => x y.\n    unfold decidable; decide equality; apply eq_comparable.\nQed.\nCanonical Structure subState_eqType := Eval hnf in @EqType subState subState_eqMixin.\n\n\n\n(**********)\n(* 状態遷移 *)\n(**********)\n\n(* 便利な関数 *)\nDefinition subst {dom : eqType} {ran} (d : dom) (r : ran) := \n    fun f => fun d' =>  if d == d' then Some r else (f d').\nNotation \"t ↦ b\" := (subst t b)(at level 10).\n\n\nLemma subst_lemma {dom ran : finType} (f : dom -> option ran) (d : dom) (r : ran) :\n    let f' := subst d r f in f' d = Some r.\nProof. rewrite /subst eq_refl => //. Qed.\n\nFixpoint findExpiration_ (p : seq (citizen * timestamp)) (c : citizen) : option timestamp :=\n    match p with \n    | [::] => None\n    | (m,n) :: p' => if c == m then Some n else findExpiration_ p' c \n    end.\n\nDefinition findExpiration (p : {set citizen * timestamp}) (c : citizen) : option timestamp :=\n    findExpiration_ (enum p) c.\n\n\n(* 熟議の実行関数の存在を仮定 *)\nParameter evalD : comitee -> bool.  \n\n\nDefinition transv_  (p : proposal) (x : state)  :=\n    match p with \n    | PwithdrawTreasury n => x <| Streasury ::= minusc n|>\n    | PdepositTreasury n => x <| Streasury ::= plusc n|>\n    | PwithdrawBudget t n => \n        let ss := Ssubstate x t in \n        match ss with \n        | None => x \n        | Some ss => \n            let ss' := ss <|SSbudget ::= minusc n|> in \n            x <| Ssubstate ::= t ↦ ss'|>  \n        end \n    | PdepositBudget t n => \n        let ss := Ssubstate x t in \n        match ss with \n        | None => x \n        | Some ss =>  \n            let ss' := ss <|SSbudget ::= plusc n|> in \n            x <| Ssubstate ::= t ↦ ss'|>  \n        end    \n    | Pallocate t n => \n        let ss := Ssubstate x t in \n        match ss with \n        | None => x \n        | Some ss =>  \n            let ss' := ss <|SSbudget ::= minusc n|> in \n            x  <| Ssubstate ::= t ↦ ss'|> <| Streasury ::= minusc n|>\n        end\n   \n    | PassignMember t m => \n        let ss := Ssubstate x t in \n        match ss with \n        | None => x \n        | Some ss =>  \n            let ss' := ss <| SSmember ::= fun mem => m |: mem |> in\n            x <| Ssubstate ::= t ↦ ss'|>   \n        end  \n    | PdismissalMember t m => \n        let ss := Ssubstate x t in \n        match ss with \n        | None => x \n        | Some ss =>  \n            let ss' := ss <| SSmember ::= fun mem => mem :\\ m |> in\n            x <| Ssubstate ::= t ↦ ss'|>\n        end\n    | PassignTenureWorker t m n =>\n        let tw := (m,n) in \n        let ss := Ssubstate x t in \n        match ss with \n        | None => x \n        | Some ss =>  \n            let tws := SStenureWorker ss in \n            x  <| Ssubstate ::= t ↦ (ss <|SStenureWorker := tw |: tws|>) |>\n        end\n\n    | PdismissalTenureWorker t m => \n        let ss := Ssubstate x t in \n        match ss with \n        | None => x \n        | Some ss =>  \n            let tws := SStenureWorker ss in \n            let n := findExpiration tws m in \n            match n with \n            | None => x \n            | Some n' => x <| Ssubstate ::= t ↦ (ss <|SStenureWorker := tws :\\ (m,n')|>) |>\n            end\n        end\n    | Pregister m => x <| Smember ::= fun mem => m |: mem|>\n    | Pderegister m => x <| Smember ::= fun mem => mem :\\ m|>\n    | PgenAdmin t => \n        let ss := Ssubstate x t in \n        match ss with \n        | None => x <|Ssubstate ::= t ↦ empty_subState|>\n        | Some _ => x        \n        end\n    | PslashAdmin t =>\n        let ss := Ssubstate x t in \n        match ss with \n        | None => x \n        | Some _ => x <|Ssubstate ::= fun f => fun t' => if t' == t then None else f t'|>\n        end\n\n    end.\n\n\n\n\nDefinition trans_ (a : act) (x : state) :=\n    match a with \n    | AsubPropose adm a' p_ f_ d_ n => \n        let ss := Ssubstate x adm in  \n        match ss with \n        | None => x \n        | Some ss =>  \n            let mem := SSmember ss in \n            let p := random_choice mem p_ in \n            let f := random_choice mem f_ in \n            let d := random_choice_set mem d_ n in \n            let ss' := ss <|SScomitee := Some (mkDlb a' p f d)|> in \n            x <| Ssubstate ::= adm ↦ ss'|>\n        end\n\n    | AsubDeliberate adm => \n        let ss := Ssubstate x adm in\n        match ss with \n        | None => x \n        | Some ss => \n            let dlb_ := SScomitee ss in\n            match dlb_ with \n            | Some dlb =>  \n                if evalD dlb then transv_ (Dproposal dlb) x else x\n            | None => x\n            end\n        end\n\n    | AglobalPropose a' p_ f_ d_ n =>\n        let mem := Smember x in\n        let p := random_choice mem p_ in \n        let f := random_choice mem f_ in \n        let d := random_choice_set mem d_ n in \n        x <|Scomitee := Some (mkDlb a' p f d)|>\n\n    | AglobalDeliberate => \n        let dlb := Scomitee x in \n        match dlb with \n        | None => x \n        | Some dlb_ => \n            if evalD dlb_ then transv_ (Dproposal dlb_) x else x \n        end\n    end.\n\nDefinition trans a x y := y = trans_ a x.\n\n(***********)\n(* 原子命題 *)\n(***********)\n\nInductive var :=\n    (* substaeの持ち得る状態についての制約 *)\n    | hasNoBudget : admin -> var\n    | hasNoComitee : admin -> var\n    | hasNoTenureWoker : admin -> var\n    | hasNoMember : admin -> var\n    (* 行政機関が熟議できる提案の制約 *)\n    | treasuryRestriction : admin -> var \n    | budgetRestriction : admin -> var\n    | allocateRestriction : admin -> var\n    | assignRestriction : admin -> var\n    | registerRestriction : admin -> var\n    | adminControlRestriction : admin -> var\n    (* globalStateが熟議できる提案の制約 *)\n    | globalRestriction : var\n    (* その他 *)\n    | isAssigned : admin -> citizen -> var\n    | isProposed : admin -> proposal -> var \n    | isTenureWorker : admin -> citizen -> var\n    | withinExpiration : admin -> citizen-> var  \n    (* | isValidComitee : admin -> admin -> admin -> var *)\n    .\n \n\n\nDefinition valuation (x : var) (s : state) : bool :=\n    match x with\n    | hasNoBudget t => \n        let ss := Ssubstate s t in\n        match ss with \n        | None => true\n        | Some ss => SSbudget ss == Curr 0\n        end \n    | hasNoComitee t => \n        let ss := Ssubstate s t in\n        match ss with \n        | None => true\n        | Some ss => SScomitee ss == None\n        end\n    | hasNoTenureWoker t => \n        let ss := Ssubstate s t in\n        match ss with \n        | None => true\n        | Some ss => SStenureWorker ss == set0\n        end\n    | hasNoMember t => \n        let ss := Ssubstate s t in\n        match ss with \n        | None => true\n        | Some ss => SSmember ss == set0\n        end\n    | treasuryRestriction t =>\n            let ss := Ssubstate s t in\n            match ss with \n            | None => true \n            | Some ss => let dlb := SScomitee ss\n                in match dlb with \n                | None => true \n                | Some dlb' => let prp := Dproposal dlb' in\n                    match prp with \n                    | PwithdrawTreasury  _ => false \n                    | PdepositTreasury _ => false  \n                    | _ => false\n                    end\n                end\n            end\n    | budgetRestriction t =>\n            let ss := Ssubstate s t in\n            match ss with \n            | None => true \n            | Some ss => let dlb := SScomitee ss\n                in match dlb with \n                | None => true \n                | Some dlb' => let prp := Dproposal dlb' in\n                    match prp with \n                    | PwithdrawBudget t' _ => t == t' \n                    | PdepositBudget t'  _ => t == t'  \n                    | _ => true\n                    end\n                end\n            end\n    | allocateRestriction t =>\n            let ss := Ssubstate s t in\n            match ss with \n            | None => true \n            | Some ss => let dlb := SScomitee ss\n                in match dlb with \n                | None => true \n                | Some dlb' => let prp := Dproposal dlb' in\n                    match prp with \n                    | Pallocate _ _ => false\n                    | _ => true\n                    end\n                end\n            end\n    | assignRestriction t => \n        let ss := Ssubstate s t in\n            match ss with \n            | None => true \n            | Some ss => let dlb := SScomitee ss\n                in match dlb with \n                | None => true \n                | Some dlb' => let prp := Dproposal dlb' in\n                    match prp with \n                    | PassignMember  _ _ => false\n                    | PdismissalMember  _ _ => false\n                    | PassignTenureWorker  _ _ _ => false\n                    | PdismissalTenureWorker  _ _ => false\n                    | _ => true\n                    end\n                end\n            end\n    | registerRestriction t => \n        let ss := Ssubstate s t in\n            match ss with \n            | None => true \n            | Some ss => let dlb := SScomitee ss\n                in match dlb with \n                | None => true \n                | Some dlb' => let prp := Dproposal dlb' in\n                    match prp with \n                    | Pregister _ => false\n                    | Pderegister _ => false\n                    | _ => true\n                    end\n                end\n            end\n    | adminControlRestriction t => \n        let ss := Ssubstate s t in\n            match ss with \n            | None => true \n            | Some ss => let dlb := SScomitee ss\n                in match dlb with \n                | None => true \n                | Some dlb' => let prp := Dproposal dlb' in\n                    match prp with \n                    | PgenAdmin _ => false\n                    | PslashAdmin _ => false\n                    | _ => true\n                    end\n                end\n            end\n    | globalRestriction =>\n        let dlb := Scomitee s in\n        match dlb with \n        | None => true \n        | Some dlb => let prp := Dproposal dlb in \n            match prp with \n            | Pregister  _ => false \n            | Pderegister _ => false \n            | PwithdrawBudget _ _ => false \n            | PdepositBudget  _ _ => false\n            | _ => true \n            end \n        end\n    \n    \n    | isAssigned a m => \n        let ss := Ssubstate s a in\n        match ss with \n        | None => true\n        | Some ss =>\n            let mem := SSmember ss in         \n            m \\in mem\n        end\n    | isProposed adm a => \n        let ss := Ssubstate s adm in\n        match ss with \n        | None => true\n        | Some ss =>\n            let dlb_ := SScomitee ss in\n            match dlb_ with \n            | Some  dlb =>  \n                a == Dproposal dlb\n            | None => false\n            end\n        end \n    | isTenureWorker t m  =>\n        let ss := Ssubstate s t in\n        match ss with \n        | None => true\n        | Some ss =>\n            let tws := SStenureWorker ss in \n            let n := findExpiration tws m in\n            match n with \n            | Some _ => true \n            | _ => false\n            end\n        end\n    | withinExpiration t m => \n        let ss := Ssubstate s t in\n        match ss with \n        | None => true\n        | Some ss =>\n            let tws := SStenureWorker ss in \n            let tw := findExpiration tws m in\n            match tw with \n            | None => false \n            | Some n => now < n \n            end \n        end\n    (* | isValidComitee t ps fs => \n        let ss := Ssubstate s t in\n        match ss with \n        | None => true\n        | Some ss =>\n            let ssp := Ssubstate s ps in \n            let ssf := Ssubstate s fs in \n            match ssp, ssf with \n            | Some ssp, Some ssf => \n                let pf := SStenureWorker ssp in \n                let fc := SStenureWorker ssf in \n                let dlb_ := SScomitee ss in\n                match dlb_ with \n                | Some  dlb =>  \n                    [exists n,  (Dprofessional dlb, n) \\in pf] && \n                    [exists n, (Dfacilitator dlb, n) \\in fc] &&\n                    (Ddeliberator dlb != set0)\n                | None => false\n                end     \n            | _ , _ => false \n            end \n        end      *)\n    end.\n", "meta": {"author": "gaxiiiiiiiiiiii", "repo": "GovernmentStateMachine", "sha": "4474833f55984d5b7139d3884bd18affedbcceef", "save_path": "github-repos/coq/gaxiiiiiiiiiiii-GovernmentStateMachine", "path": "github-repos/coq/gaxiiiiiiiiiiii-GovernmentStateMachine/GovernmentStateMachine-4474833f55984d5b7139d3884bd18affedbcceef/GSM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24372687576120297}}
{"text": "Require Import Arith.\nRequire Import Omega.\nRequire Import String.\nRequire Import List.\nImport ListNotations.\n\nRequire Import OrderedType OrderedTypeEx.\nRequire FMapList.\nRequire FMapFacts.\nModule NatMap := FMapList.Make Nat_as_OT.\nModule NatMapFacts := FMapFacts.WFacts_fun Nat_as_OT NatMap.\n\nRequire Import stringfacts.\nRequire Import base.\nRequire Import ast.\nRequire Import logic.\nRequire Import vfs.\n\n(* ************************************************************ *)\n(* ************************************************************ *)\n(*                                                              *)\n(*                           caponfs                            *)\n(*                                                              *)\n(* ************************************************************ *)\n(* ************************************************************ *)\n\nHypothesis undefined: forall T, T.\n\n(*\n * the most ... bastardized fs model\n *)\n\nInductive caponvnode: Set :=\n| capondir: nat -> dir_trace -> caponvnode\n| caponfile: nat -> file_trace -> caponvnode\n.\n\nInductive caponfs :=\n| capon: NatMap.t caponvnode -> caponfs\n.\n\nFunction caponfs_inum vn :=\n   match vn with\n   | capondir inum _ => inum\n   | caponfile inum _ => inum\n   end.\n\nFunction caponfs_isdir vn :=\n   match vn with\n   | capondir _ _ => true\n   | caponfile _ _ => false\n   end.\n\nFunction caponfs_isfile vn :=\n   match vn with\n   | capondir _ _ => false\n   | caponfile _ _ => true\n   end.\n\nFunction caponfs_dirtrace vn :=\n   match vn with\n   | capondir _ dt => dt\n   | caponfile _ _ => dirtrace_empty (* ugh *)\n   end.\n\nFunction caponfs_filetrace vn :=\n   match vn with\n   | capondir _ _ => filetrace_empty (* ugh *)\n   | caponfile _ ft => ft\n   end.\n\nFunction caponfs_getvnode fs inum: caponvnode :=\n   match fs with\n   | capon itbl => match NatMap.find inum itbl with\n        | Some vn => vn\n        | None => undefined caponvnode (* XXX *)\n        end\n   end.\n\nHypothesis caponfs_lookup: proc (caponvnode * string) (option caponvnode).\nHypothesis caponfs_create: proc (caponvnode * string) (option caponvnode).\nHypothesis caponfs_unlink: proc (caponvnode * string) (option unit).\nHypothesis caponfs_read: proc (caponvnode * nat * nat) bytes.\nHypothesis caponfs_write: proc (caponvnode * bytes * nat) unit.\nHypothesis caponfs_truncate: proc (caponvnode * nat) unit.\nHypothesis caponfs_fsync: proc caponvnode unit.\nHypothesis caponfs_getroot: proc caponfs caponvnode.\nHypothesis caponfs_sync: proc caponfs unit.\nHypothesis caponfs_newfs: proc unit caponfs.\n\nInstance caponvnode_is_vnode: vnodeclass caponvnode := {\n   inum_of_vnode := caponfs_inum;\n   isdir := caponfs_isdir;\n   isfile := caponfs_isfile;\n   dirtrace_of_vnode := caponfs_dirtrace;\n   filetrace_of_vnode := caponfs_filetrace;\n\n   VOP_LOOKUP := caponfs_lookup;\n   VOP_CREATE := caponfs_create;\n   VOP_UNLINK := caponfs_unlink;\n   VOP_READ := caponfs_read;\n   VOP_WRITE := caponfs_write;\n   VOP_TRUNCATE := caponfs_truncate;\n   VOP_FSYNC := caponfs_fsync;\n}.\nProof.\n  - admit.\n  - admit.\n  - admit.\n  - admit.\n  - admit.\n  - admit.\n  - admit.\nAdmitted.\n\nInstance caponfs_is_fs: fsclass caponfs := {\n   vnode := caponvnode;\n   vnode_is_vnodeclass := caponvnode_is_vnode;\n\n   root_inum := 1;\n   getvnode := caponfs_getvnode;\n\n   VFS_GETROOT := caponfs_getroot;\n   VFS_SYNC := caponfs_sync;\n\n   newfs := caponfs_newfs;\n}.\nProof.\n  - admit.\n  - admit.\n  - admit.\nAdmitted.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/src/caponfs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.24372687000742038}}
{"text": "Require Import MetaProp.\nRequire Import SyntaxProp.\nRequire Import DynamicProp.\nRequire Import TypesProp.\nRequire Import WellFormednessProp.\nRequire Import Shared.\n\nHint Constructors is_econtext.\nHint Constructors cfg_blocked.\n\nLemma exists_declsToRegionLocks :\n  forall fs,\n    exists RL, declsToRegionLocks fs RL.\nProof with eauto.\n  introv. induction fs as [| [f t r] fs' IH].\n  + exists (empty (A := region_id) (B := lock_status)).\n    econstructor.\n    introv fLookup.\n    simpl in fLookup...\n  + destruct IH as [RL H].\n    exists (extend RL r LUnlocked).\n    econstructor.\n    introv fLookup.\n    simpl in fLookup.\n    remember (beq_nat f0 f) as fEq.\n    destruct fEq.\n    - inv_eq.\n    - case_extend.\n      inv H...\nQed.\n\nLemma single_threaded_progress :\n  forall P t' Gamma H V n Ls e t,\n    wfProgram P t' ->\n    wfConfiguration P Gamma (H, V, n, T_Thread Ls e) t ->\n    threads_done (T_Thread Ls e) \\/\n    cfg_blocked (H, V, n, T_Thread Ls e) \\/\n    exists cfg', P / (H, V, n, T_Thread Ls e) ==> cfg'.\nProof with eauto using step.\n  introv wfP wfCfg.\n  inverts wfCfg as Hfresh wfH wfV wfT wfL.\n  inverts wfT as Hfree hasType wfLs wfL.\n  hasType_cases(induction hasType) Case;\n\n    (* All non-trivial cases step *)\n    simpl; try(solve[eauto]); right;\n\n    (* All variables must be dynamic *)\n    match goal with\n      | [Hfree : freeVars _ = nil |- _] =>\n        simpl in Hfree;\n          repeat\n          match goal with\n           | [Hfree : freeVars _ ++ _ = nil |- _] =>\n             simpl in Hfree;\n             apply app_eq_nil in Hfree as [Hfree1 Hfree2]\n           | [x : var |- _] =>\n             destruct x; try(congruence)\n          end\n      | _ => idtac\n    end;\n\n    (* If there's a target x, invert its typing derivation*)\n    repeat\n    match goal with\n      | [H : Types.hasType ?P ?Gamma (EVar (DV ?x)) _ |- _ ] =>\n        inv H\n      | _ => idtac\n    end;\n\n    (* Each variable lookup in Gamma corresponds to some lookup in V *)\n    repeat wfEnvLookup...\n  + Case \"T_New\".\n    right.\n    assert (cLookup: exists i fs ms, classLookup P c = Some (Cls c i fs ms))\n      by eauto using classLookup_not_none.\n    destruct cLookup as (i & fs & ms & cLookup).\n    assert(exRL: exists RL, declsToRegionLocks fs RL) by\n        eauto using exists_declsToRegionLocks.\n    destruct exRL as [RL].\n    eexists; eapply EvalNew...\n  + Case \"T_Call\".\n    assert (wfL': wfLocking H (T_Thread Ls e))\n      by eauto 3 using wfLocking_econtext.\n    assert (IH: threads_done (T_Thread Ls e) \\/\n                cfg_blocked (H, V, n, T_Thread Ls e) \\/\n                exists cfg', P / (H, V, n, T_Thread Ls e) ==> cfg')...\n    inv IH as [edone | [eBlocked | eSteps]]...\n    - SCase \"e done\".\n      right.\n      destruct e; try(contradiction).\n      inv hasType...\n      wfEnvLookup.\n      assert (wfC: wfType P (TClass c))...\n      inverts wfC as cLookup.\n      apply classLookup_not_none in cLookup as (i & fs & ms & cLookup).\n      assert (Hsigs: methodSigLookup (extractSigs ms) m = Some (MethodSig m (y, t2) t))\n        by eauto using methodSigs_sub.\n      eapply extractSigs_sound in Hsigs as [e mLookup].\n      assert (methods P (TClass c) = Some ms)\n        by (simpl; rewrite cLookup; eauto).\n      eexists; eapply EvalCall...\n    - SCase \"e can step\".\n      destruct eSteps as [[[[H' V'] n'] T'] eSteps].\n      destruct T'...\n      inv eSteps...\n      inv eSteps...\n  + Case \"T_Select\".\n    right.\n    inv hasType...\n    assert (t2 = TClass c)...\n    wfEnvLookup.\n    eapply dyn_wfFieldLookup in wfF as [v []]...\n    eexists. eapply EvalSelect...\n  + Case \"T_Update\".\n    assert (wfL': wfLocking H (T_Thread Ls e))\n      by eauto 3 using wfLocking_econtext.\n    assert (IH: threads_done (T_Thread Ls e) \\/\n                cfg_blocked (H, V, n, T_Thread Ls e) \\/\n                exists cfg', P / (H, V, n, T_Thread Ls e) ==> cfg')...\n    inv IH as [edone | [eBlocked | eSteps]]...\n    - SCase \"e done\".\n      destruct e; try(contradiction)...\n      inv hasType...\n      wfEnvLookup...\n    - SCase \"e can step\".\n      destruct eSteps as [[[[H' V'] n'] T'] eSteps].\n      destruct T'...\n      inv eSteps...\n      inv eSteps...\n  + Case \"T_Let\".\n    remember (fun e : expr => ELet x e body) as ctx.\n    assert (is_econtext ctx). subst. apply EC_Let.\n    assert (wfL': wfLocking H (T_Thread Ls e))\n      by (apply wfLocking_econtext with ctx; crush).\n    replace (ELet x e body) with (ctx e) by crush...\n    assert (IH: threads_done (T_Thread Ls e) \\/\n                cfg_blocked (H, V, n, T_Thread Ls e) \\/\n                exists cfg', P / (H, V, n, T_Thread Ls e) ==> cfg')...\n    inversion IH as [edone | [eBlocked | eSteps]]...\n    - SCase \"e done\".\n      subst.\n      destruct e; try(contradiction)...\n    - SCase \"e can step\".\n      destruct eSteps as [[[[H' V'] n'] T'] eSteps].\n      destruct T'...\n      inverts eSteps...\n      inverts eSteps...\n  + Case \"T_Cast\".\n    assert (wfL': wfLocking H (T_Thread Ls e))\n      by eauto 3 using wfLocking_econtext.\n    assert (IH: threads_done (T_Thread Ls e) \\/\n                cfg_blocked (H, V, n, T_Thread Ls e) \\/\n                exists cfg', P / (H, V, n, T_Thread Ls e) ==> cfg')...\n    inv IH as [edone | [eBlocked | eSteps]]...\n    - SCase \"e done\".\n      destruct e; try(contradiction)...\n    - SCase \"e can step\".\n      destruct eSteps as [[[[H' V'] n'] T'] eSteps].\n      destruct T'...\n      inverts eSteps...\n      inverts eSteps...\n  + Case \"T_Lock\".\n    destruct v...\n    inv hasType.\n    wfEnvLookup.\n    assert (TClass c = t2)\n      by (unfold fields in *; destruct t2; eauto).\n    subst.\n    assert(Hex: exists status, RL r = Some status).\n      inv wfRL... rewrite_and_invert.\n      destruct H1 as (f & t'' & fLookup)...\n    inv Hex as [status RLlookup].\n    assert(HIn: {In (l, r) Ls} + {~ In (l, r) Ls})\n      by (apply in_dec; apply id_eq_dec).\n    assert(wfLs: wfHeldLocks H Ls)\n      by (inv wfL; eauto).\n    destruct status; destruct HIn as [HIn|HnotIn]...\n    eapply wfHeldLocks_taken in HIn...\n    rewrite_and_invert.\n  + Case \"T_Locked\".\n    assert (wfL': wfLocking H (T_Thread Ls e))\n      by eauto 3 using wfLocking_econtext.\n    inv hasType1.\n    wfEnvLookup.\n    assert (HIn: In (l, r) Ls) by\n      (inverts wfL as _ _ []; simpls; eauto).\n    assert (Hlocked: RL r = Some LLocked)\n      by (inv wfL; eauto using wfHeldLocks_taken).\n    assert (IH: threads_done (T_Thread Ls e) \\/\n                cfg_blocked (H, V, n, T_Thread Ls e) \\/\n                exists cfg', P / (H, V, n, T_Thread Ls e) ==> cfg')...\n    inv IH as [edone | [eBlocked | eSteps]]...\n    - SCase \"e done\".\n      destruct e; try(contradiction)...\n    - destruct eSteps as [[[[H' V'] n'] T'] eSteps].\n      destruct T'...\n      inverts eSteps...\n      inverts eSteps...\nQed.\n\nTheorem progress :\n  forall P t' Gamma cfg t,\n    wfProgram P t' ->\n    wfConfiguration P Gamma cfg t ->\n    cfg_exn cfg \\/ cfg_done cfg \\/ cfg_blocked cfg \\/\n    exists cfg', P / cfg ==> cfg'.\nProof with eauto.\n  introv wfP wfCfg.\n  inverts wfCfg as Hfresh wfH wfV wfT wfL.\n  gen t.\n  induction T; intros; simpl...\n  + Case \"T = Thread\".\n    right. eapply single_threaded_progress...\n  + Case \"T = Async T1 T2 e\".\n    inverts wfT as Hfree hasType wfT1 wfT2.\n    inverts wfL as wfL HL Hdisj wfL1 wfL2.\n    right. right.\n    pose proof (IHT1 wfL1 t1 wfT1) as IH1.\n    pose proof (IHT2 wfL2 t2 wfT2) as IH2.\n    destruct IH1 as [T1EXN|[T1Done|[T1Blocked|T1Steps]]]...\n    - SCase \"T1 done\".\n      unfolds in T1Done. unfold threads_done in T1Done.\n      destruct T1; try(solve[inv T1Done]).\n      destruct IH2 as [T2EXN|[T2Done|[T2Blocked|T2Steps]]]...\n      * SSCase \"T2 steps\".\n        destruct T2Steps as [[[[H' V'] n'] T2']].\n        right. eexists; eapply EvalAsyncRight...\n    - SCase \"T1 blocked\".\n      destruct IH2 as [T2EXN|[T2Done|[T2Blocked|T2Steps]]]...\n      * SSCase \"T2 steps\".\n        destruct T2Steps as [[[[H' V'] n'] T2']].\n        right. eexists; eapply EvalAsyncRight...\n    - SCase \"T1 steps\".\n      destruct T1Steps as [[[[H' V'] n'] T2']].\n      right. eexists; eapply EvalAsyncLeft...\nQed.\n", "meta": {"author": "EliasC", "repo": "oolong", "sha": "f449d42f70da1c404883860296ec4f2c5ed088b7", "save_path": "github-repos/coq/EliasC-oolong", "path": "github-repos/coq/EliasC-oolong/oolong-f449d42f70da1c404883860296ec4f2c5ed088b7/coq/regions/Progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24372687000742033}}
{"text": "Require Import Coqlib.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import AST.\nRequire Import Lop.\nRequire Import Lustre.\nRequire Import Maps.\n\n(** * Global Declares *)\n\n(** * Types *)   \n\n(** Types include short (signed 16 bits), ushort (unsigned 16 bits),int(signed 32 bits),\n  uint(unsigned 32 bits), float (32 bits), real (64 bits), bool(true or false), char, \n  array, struct and enum. *) \n \n(** The syntax of type expressions.  Some points to note:\n- struct type, e.g type s1 = { n : int, m : real } is expressed by syntax as below:\n       Tstruct \"s1\" (Fcons \"n\" (Tint)\n                    (Fcons \"m\" (Treal)\n                    Fnil))\n- no recursive type, e.g type s = { m : s } is not allowed, although it canbe expressed by syntax. \n*)\n \nInductive typeL : Type :=\n  | Tint : typeL                            (**r integer types, signed 32 bits *)\n  | Treal : typeL                           (**r floating-point types, 64 bits *)\n  | Tbool : typeL                           (**r bool types *)\n  | Tarray : ident -> typeL -> Z -> typeL   (**r array types: array_type_id(ty^len) *)\n  | Tstruct : ident -> fieldlistL -> typeL  (**r struct types: struct_type_id {label1_id: type1; ...} *)\n  | Tenum : list ident -> typeL    (**r enum types: enum_type_id {value1_id, ...} *)         \n\nwith fieldlistL : Type :=\n  | Fnil : fieldlistL\n  | Fcons : ident -> typeL -> fieldlistL -> fieldlistL.\n\n(** const_block \n     Const block consisting of all character constants *)\n\nInductive constL : Type := \n  | IntConstL: int -> constL\n  | RealConstL: float -> constL\n  | BoolConstL: bool -> constL\n  | ConstructConstL : const_listL -> constL     (**r E.g struct {label1 : 1, label2 : 2}, or array [1, 2] *) \n  | ID : ident -> constL               (**r to define other constant by character constant *)     \n\nwith const_listL : Type :=\n  | ConstNilL : const_listL\n  | ConstConL : constL -> const_listL -> const_listL.\n\n(** * Expressions *)\n\nDefinition vars := list (ident * typeL * clock).\n\nInductive suboperator : Type := \n  | Nodehandler : ident -> bool -> list typeL -> suboperator.\n\nInductive exprT : Type := \n  | EconstT : const -> typeL -> exprT\n  | EvarT : ident -> typeL -> clock -> exprT\n  | ListExprT : expr_listT -> exprT                                           (**r list expression *)\n  | ApplyExprT : suboperator -> expr_listT ->  exprT \t              (**r operator application *)\n  | EconstructT : struct_listT -> exprT                                      (**r construct a struct, e.g {label1 : 3, label2 : false} *)\n  | EarrayaccT : exprT -> int -> exprT                                     (**r expr[i], access to (i+1)th member of an array \"expr\" *)\n  | EarraydefT :  exprT -> int -> exprT                               (**r expr ^ i, an array of size \"i\" with every element \"expr\" *)\n  | EarraydiffT : expr_listT ->  exprT                                      (**r [list expression], build an array with elements \"list expression\", e.g [1,2]*)\n  | EunopT : unary_operationL -> exprT -> exprT                            (**r unary operation *)\n  | EbinopT : binary_operationL -> exprT -> exprT -> exprT                 (**r binary operation *)\n  | EfieldT : exprT -> ident -> exprT                                      (**r access to a member of a struct *)\n  | EpreT : exprT -> exprT                              (**r pre : shift flows on the last instant backward, producing an undefined value at first instant*)\n  | EfbyT : expr_listT -> int -> expr_listT -> exprT  (**r fby : fby(b; n; a) = a -> pre fby(b; n-1; a) *) \n  | EarrowT : exprT -> exprT -> exprT                                         (**r -> : fix the inital value of flows*)\n  | EwhenT : exprT -> clock -> exprT                                          (**r x when h: if h=false, then no value; otherwise x *)\n  | EcurrentT: exprT -> exprT   \n  | EmergeT: ident -> exprT -> exprT -> exprT\n  | EifT : exprT -> exprT -> exprT -> exprT                                   (**r conditional*)\n  | EdieseT: exprT -> exprT  (**r #(a1, ..., an) -> boolred(0,1,n)[a1, ..., an] *)\n  | EnorT: exprT ->  exprT  (**r nor(a1, ..., an) boolred(0,0,n)[a1, ..., an] *)\n\nwith expr_listT : Type :=\n  | Enil: expr_listT\n  | Econs: exprT -> expr_listT -> expr_listT\n\nwith struct_listT: Type :=\n  | EstructNil: struct_listT\n  | EstructCons: ident -> exprT -> struct_listT -> struct_listT.\n\nInductive megaT : Type :=\n  | MegaT : ident -> ident -> megaT.\n\nInductive ctrl_exprT : Type :=\n  | ExprT : exprT -> ctrl_exprT\n  | MegaExprT : megaT -> ctrl_exprT.\n\nInductive ctrl_lhs : Type :=\n  | IdentT : vars -> ctrl_lhs\n  | MegaLhsT : megaT -> ctrl_lhs.\n\n(** * Equation *)\n\nInductive equationT : Type :=\n  | EquationT: vars -> exprT -> equationT.\n\nInductive ctrl_equationT : Type :=\n  | CtrlEquationT: ctrl_lhs -> ctrl_exprT -> ctrl_equationT.\n\n(** * Node *)\n\n(** Node : kind -> ID -> parameters -> returns -> locals -> body *)\n\nInductive nodeT : Type :=\n  | NodeT : bool -> ident -> vars -> vars -> vars -> list equationT -> nodeT.\n\nInductive widgetT : Type :=\n  | WidgetT : ident -> list(ident * typeL) -> vars -> vars -> widgetT.\n\nInductive ctrlT : Type :=\n  | CtrlT : ident -> vars -> list ctrl_equationT -> ctrlT.\n\n(** * Program *)\nDefinition wgtenvW := PTree.t widgetT.\nDefinition empty_wgtenvW := PTree.empty widgetT.\n\nRecord programT : Type := mkprogramT {\n  type_blockT : list (ident*typeL);\n  const_blockT : list (ident*typeL*constL);\n  node_blockT : list nodeT;\n  controlT : ctrlT;\n  widget_blockT : wgtenvW;\n  node_mainT : ident\n}.\n", "meta": {"author": "linusboyle", "repo": "L2CDisplay", "sha": "4eb5b4dbb01da56534c0b0a1560dec8c715a68a4", "save_path": "github-repos/coq/linusboyle-L2CDisplay", "path": "github-repos/coq/linusboyle-L2CDisplay/L2CDisplay-4eb5b4dbb01da56534c0b0a1560dec8c715a68a4/display/DisplayW.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24372687000742033}}
{"text": "(** Proofs of correctness *)\n\nFrom MetaCoq Require Import utils.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils\n     PCUICLiftSubst PCUICWcbvEval PCUICTyping.\n\nFrom ConCert Require Import CustomTactics MyEnv\n     EnvSubst Ast EvalE PCUICFacts  PCUICTranslate\n     PCUICCorrectnessAux Wf Misc.\n\n\nFrom Coq Require Import String List.\n\nImport ListNotations ssrbool Basics Lia.\nImport NamelessSubst.\n\nLocal Set Keyed Unification.\n\n(** Soundness (In the paper: Theorem 1) *)\nTheorem expr_to_term_sound (n : nat) (ρ : env val) Σ1 Σ2 (Γ:=[])\n        (e1 e2 : expr) (v : val) :\n  genv_ok Σ1 ->\n  env_ok Σ1 ρ ->\n  eval(n, Σ1, ρ, e1) = Ok v ->\n  e1.[exprs ρ] = e2 ->\n  iclosed_n 0 e2 = true ->\n  Σ2 ;;; Γ |- t⟦e2⟧Σ1 ⇓ t⟦of_val_i v⟧Σ1.\nProof.\n  revert dependent v.\n  revert dependent ρ.\n  revert dependent e2.\n  revert dependent e1.\n  induction n.\n  - intros;tryfalse.\n  - intros e1 e2 ρ v Hgeok Hρ_ok He Henv Hc;destruct e1.\n    + (* eRel *) simpl in *. autounfold with facts in *. simpl in *.\n      destruct (lookup_i ρ n0) as [v1| ] eqn:Hlookup;tryfalse; simpl in He;inversion He;subst.\n      destruct (Nat.ltb n0 (length ρ)) eqn:Hn0.\n      * destruct (inst_env_i_in _ _ Hn0) as [v2 HH].\n        destruct HH as [H1 H2].\n        assert (v = v2) by congruence. subst.\n        assert (ge_val_ok Σ1 v2) by (apply val_ok_ge_val_ok;eapply All_lookup_i;eauto).\n        rewrite H2.\n        eapply PcbvCurr.value_final; eapply Wcbv_of_value_value; eauto with hints.\n        eapply All_lookup_i;eauto.\n      * specialize (lookup_i_length_false _ _ Hn0) as Hnone;tryfalse.\n    + (* eVar *) simpl;tryfalse.\n    + (* eLambda *)\n      subst. simpl in *.\n      destruct (eval_type_i 0 ρ t) eqn:Hty;tryfalse;simpl in *.\n      destruct (valid_env ρ 1 e1) eqn:He1;tryfalse. inv_andb Hc.\n      inversion He;subst;simpl;eauto with hints.\n      erewrite eval_type_i_subst_env;eauto.\n      rewrite subst_env_ty_closed_n_eq with (n:=0) (m:=0);eauto with hints.\n    + simpl in *. destruct (valid_env ρ 1 e1) eqn:He1;tryfalse.\n      inversion He. subst;clear He.\n      simpl. constructor;eauto.\n    + (* eLetIn *)\n      subst;simpl in *.\n      unfold is_true in *;\n        repeat rewrite  Bool.andb_true_iff in *.\n      destruct Hc as [[? ?] ?].\n      destruct (eval (n, Σ1, ρ, e1_1)) eqn:He1;tryfalse.\n      destruct (eval_type_i 0 ρ t) eqn:Ht0;tryfalse. inversion He;subst;clear He.\n      assert (He11 : Σ2;;; Γ |- t⟦ e1_1 .[ exprs ρ] ⟧ Σ1 ⇓  t⟦ of_val_i v0 ⟧ Σ1)\n        by (eauto with hints).\n      assert (ty_expr_env_ok (exprs ρ) 0 e1_1) by (eapply eval_ty_expr_env_ok;eauto with hints).\n\n      assert (iclosed_n #|exprs ρ # [e ~> of_val_i v0]| e1_2 = true).\n      { simpl. eapply subst_env_iclosed_n_inv with (n:=1);eauto with hints. }\n\n      assert (ty_expr_env_ok (exprs ρ # [e ~> of_val_i v0]) 0 e1_2).\n      { change (exprs ρ # [e ~> of_val_i v0]) with (exprs (ρ # [e ~> v0])).\n        eapply eval_ty_expr_env_ok;eauto with hints. simpl.\n        replace #|ρ| with (#|exprs ρ|) by apply map_length.\n        eapply subst_env_iclosed_n_inv with (n:=1);eauto with hints. }\n\n      assert (val_ok Σ1 v0) by (eapply eval_val_ok;eauto with hints).\n      assert (He12 : Σ2;;; Γ |- t⟦ e1_2 .[exprs ((e, v0) :: ρ)] ⟧ Σ1 ⇓ t⟦ of_val_i v ⟧ Σ1).\n      { eapply IHn with (ρ:=((e, v0) :: ρ));simpl;eauto 6 with hints. }\n      simpl in *. unfold subst_env_i in *.\n      econstructor;eauto. unfold subst1.\n      erewrite <- subst_term_subst_env_par_rec in He12 by eauto with hints.\n      erewrite <- subst_term_subst_env_par_rec;eauto with hints.\n      now rewrite <- subst_app_simpl.\n      now eapply ty_expr_env_ok_app_rec with (n:=0) (ρ1:=[(e,of_val_i v0)]).\n    + (* eApp *)\n      autounfold with facts in *. subst; cbn in *.\n      destruct (expr_eval_general _ _ _ _ e1_2) eqn:He2;tryfalse.\n      destruct (expr_eval_general _ _ _ _ e1_1) eqn:He1;tryfalse.\n      apply Bool.andb_true_iff in Hc. destruct Hc as [Hce1 Hce2].\n      assert (Hneq1 : [t⟦ inst_env_i ρ e1_2 ⟧ Σ1] <> []) by easy.\n      destruct v1;tryfalse.\n      * (* application evaluates to a constructor *)\n        inversion_clear He. simpl_vars_to_apps. subst. simpl in *.\n        rename e into n0.\n        change (tApp (t⟦ vars_to_apps (eConstr i n0) (map of_val_i l) ⟧ Σ1) (t⟦ of_val_i v0 ⟧ Σ1))\n          with (mkApps (t⟦ vars_to_apps (eConstr i n0) (map of_val_i l) ⟧ Σ1) [t⟦ of_val_i v0 ⟧ Σ1]).\n\n        eapply PcbvCurr.eval_app_cong;eauto with hints.\n        change (vars_to_apps (eConstr i n0) (map of_val_i l)) with (of_val_i (vConstr i n0 l)).\n        eapply IHn;eauto with hints.\n      * destruct c.\n        ** (* the closure corresponds to lambda *)\n          simpl in *. rename e0 into n0.\n          simpl in *.\n          assert (Hv0 : Σ2;;; Γ |- t⟦e1_2 .[ exprs ρ]⟧ Σ1 ⇓ t⟦ of_val_i v0 ⟧ Σ1)\n            by eauto.\n          assert (Hv0_ok : val_ok Σ1 v0) by (eapply eval_val_ok;eauto with hints).\n          assert (Hlam_ok : val_ok Σ1 (vClos e n0 cmLam t t0 e1)) by\n             (eapply eval_val_ok with(e:=e1_1);eauto with hints).\n          inversion Hlam_ok;subst.\n          assert (He_ok1 : env_ok Σ1 (e # [n0 ~> v0])) by now constructor.\n          assert\n           (Hlam : Σ2;;; Γ |- t⟦e1_1 .[ exprs ρ]⟧ Σ1 ⇓ t⟦ of_val_i (vClos e n0 cmLam t t0 e1) ⟧ Σ1) by\n              (eapply IHn with (ρ:=ρ);eauto).\n          assert (AllEnv (fun e1 : expr => iclosed_n 0 e1 = true) (exprs e)).\n           { inversion He_ok1. subst.\n             apply All_map. unfold compose. simpl.\n             eapply (All_impl (P := fun x => val_ok Σ1 (snd x)));eauto.\n             intros a ?; destruct a; simpl;eauto with hints. }\n           assert (iclosed_n 1 (e1 .[ exprs e] 1) = true)\n            by eauto with hints.\n           assert (ty_expr_env_ok [(n0, of_val_i v0)] 0 (e1.[exprs e]1)).\n           { eapply ty_expr_env_ok_subst_env;eauto;simpl.\n             change (exprs e # [n0 ~> of_val_i v0]) with (exprs (e # [n0 ~> v0])).\n             eapply eval_ty_expr_env_ok;eauto. }\n\n           assert (Hsubst : Σ2;;;Γ |- (t⟦e1.[exprs e]1⟧Σ1){0 := t⟦of_val_i v0⟧Σ1} ⇓ t⟦of_val_i v⟧ Σ1).\n           { rewrite subst_term_subst_env with (nm:=n0); eauto 8 with hints. }\n\n           simpl in *.\n           eapply PcbvCurr.eval_beta;eauto.\n        ** (* the closure corresponds to fix *)\n          simpl in *. rename e into ρ'. rename e0 into n0.\n          destruct v0;tryfalse.\n          (* destruct (expr_eval_general _ _ _ _ e1) eqn:Hee1;tryfalse. *)\n          (* inversion He;subst. *)\n          simpl in *.\n          remember (t⟦e1_1.[exprs ρ] ⟧ Σ1) as tm1.\n          remember (t⟦ e1_2.[exprs ρ] ⟧ Σ1) as tm2.\n          assert (Hfix : Σ2;;; Γ |- tm1 ⇓ t⟦ of_val_i (vClos ρ' n0 (cmFix _) t t0 e1) ⟧ Σ1)\n            by (subst;eauto with hints).\n\n          change (tApp tm1 tm2) with (mkApps tm1 [tm2]).\n          simpl in Hfix.\n          assert (Hok_ctor: val_ok Σ1 (vConstr i _ l)) by\n              (eapply eval_val_ok with (e:=e1_2);eauto 8 with hints).\n          inversion Hok_ctor as [ | | | ?????  HresC |];subst;clear Hok_ctor;eauto.\n          assert (Hconstr : is_constructor 0 [t⟦ of_val_i (vConstr i e l) ⟧ Σ1]).\n          { simpl. rewrite <- mkApps_vars_to_apps. cbn.\n            unfold isConstruct_app.\n            rewrite decompose_app_mkApps; now rewrite HresC. }\n          eapply PcbvCurr.eval_fix with (args':=[t⟦ of_val_i (vConstr i e l) ⟧ Σ1]);\n            subst;eauto with hints;try reflexivity.\n          cbn. remember (tFix _ _) as tfix. rewrite simpl_subst_k by auto.\n          assert (Hok_fix : val_ok Σ1 ((vClos ρ' n0 (cmFix _) t t0 e1)))\n            by (eapply eval_val_ok with (e:=e1_1);eauto with hints).\n          assert (tfix = t⟦eFix e2 n0 t t0 (e1.[exprs ρ']2)⟧ Σ1).\n          { simpl. inversion Hok_fix;subst. subst.\n            repeat rewrite subst_env_i_ty_closed_eq;eauto with hints. }\n          clear Heqtfix. subst tfix.\n          inversion Hok_fix;subst;clear Hok_fix.\n\n          remember (eFix _ _ _ _ _) as efix.\n\n          assert (Hexprs : AllEnv (fun e => iclosed_n 0 e = true) (exprs ρ')).\n          { apply All_map.\n            eapply (All_impl (P := fun v => val_ok Σ1 (snd v)));try assumption;\n              intros a ?;destruct a;cbv;eauto with hints. }\n\n          eapply PcbvCurr.eval_beta;eauto with hints.\n          eapply PcbvCurr.value_final.\n          eapply Wcbv_value_vars_to_apps;eauto with hints.\n          now eapply All_value_of_val.\n          assert (All (fun v0 : val => iclosed_n 0 (of_val_i v0) = true) l).\n          { eapply All_impl. apply X. intros.\n            eapply of_value_closed;eauto with hints. }\n\n          remember (vars_to_apps _ _) as args.\n          assert (ty_expr_env_ok (nil # [e2 ~> efix] # [n0 ~> args]) 0 (e1.[ exprs ρ']2)).\n          { subst.\n            eapply ty_expr_env_ok_subst_env.\n            assert (H : ty_expr_env_ok (exprs ((n0, vConstr i e l) :: (e2, vClos ρ' n0 (cmFix e2) t t0 e1) :: ρ'))  0 e1) by (eapply eval_ty_expr_env_ok;eauto).\n            cbn in H. repeat rewrite subst_env_i_ty_closed_0_eq in H by auto. easy.\n            now eapply closed_exprs. }\n\n          assert (AllEnv (iclosed_n 0) [(n0, args); (e2, efix)]).\n          { subst;repeat constructor;unfold compose;simpl.\n            now eapply vars_to_apps_iclosed_n. repeat split_andb;eauto with hints. }\n\n          unfold subst1. rewrite <- subst_app_simpl. simpl.\n\n          erewrite subst_term_subst_env_2 with (nm1:=n0) (nm2:=e2) by eauto with hints.\n\n          remember ((n0,_) :: (e2,_) :: ρ') as ρ''.\n\n          assert (Hok_ctor: val_ok Σ1 (vConstr i _ l)) by eauto 8 with hints.\n          assert (Hok_fix : val_ok Σ1 ((vClos ρ' n0 (cmFix e2) t t0 e1))) by\n            (eapply eval_val_ok with (ρ:=ρ)(e:=e1_1);eauto with hints).\n\n          eapply IHn with (ρ:=ρ''); subst;eauto with hints.\n          rewrite <- subst_env_compose_2;\n            (simpl; eauto using vars_to_apps_iclosed_n with hints).\n          cbn.\n          now repeat rewrite subst_env_i_ty_closed_0_eq by auto.\n          repeat split_andb;eauto with hints.\n      * rename e0 into n0.\n        assert (Hv0 : Σ2;;; Γ |- t⟦e1_2 .[ exprs ρ]⟧ Σ1 ⇓ t⟦ of_val_i v0 ⟧ Σ1)\n          by eauto with hints.\n        assert (Hv0_ok : val_ok Σ1 v0) by eauto 8 with hints.\n        assert (Hlam_ok : val_ok Σ1 (vTyClos e n0 e1))\n          by eauto 8 with hints.\n        inversion Hlam_ok;subst.\n        assert (He_ok1 : env_ok Σ1 (e # [n0 ~> v0])) by now constructor.\n        assert\n         (Hlam : Σ2;;; Γ |- t⟦e1_1 .[ exprs ρ]⟧ Σ1 ⇓ t⟦ of_val_i (vTyClos e n0 e1) ⟧ Σ1) by\n            (eapply IHn with (ρ:=ρ);eauto).\n        assert (AllEnv (fun e1 : expr => iclosed_n 0 e1 = true) (exprs e)).\n         { inversion He_ok1. subst.\n           apply All_map. unfold compose. simpl.\n           eapply (All_impl (P := fun x => val_ok Σ1 (snd x)));eauto.\n           intros a ?; destruct a; simpl;eauto with hints. }\n         assert (iclosed_n 1 (e1 .[ exprs e] 1) = true)\n          by eauto with hints.\n         assert (ty_expr_env_ok [(n0, of_val_i v0)] 0 (e1.[exprs e]1)).\n         { eapply ty_expr_env_ok_subst_env;eauto;simpl.\n           change (exprs e # [n0 ~> of_val_i v0]) with (exprs (e # [n0 ~> v0])).\n           eapply eval_ty_expr_env_ok;eauto. }\n\n         assert (Hsubst : Σ2;;;Γ |- (t⟦e1.[exprs e]1⟧Σ1){0 := t⟦of_val_i v0⟧Σ1} ⇓ t⟦of_val_i v⟧ Σ1).\n         { rewrite subst_term_subst_env with (nm:=n0); eauto 8 with hints. }\n\n         simpl in *.\n         eapply PcbvCurr.eval_beta;eauto.\n    + (* eConstr *)\n      rename e into n0.\n      cbn in He. destruct (resolve_constr Σ1 i n0) eqn:Hres;tryfalse.\n      inversion He;subst;clear He.\n      simpl in *. rewrite Hres in *. eauto with hints.\n    + (* eConst *)\n      (* The traslation does not support constants yet *)\n      inversion He.\n    + (* eCase *)\n      unfold expr_eval_i in He. destruct p.\n      (* dealing with the interpreter *)\n      simpl in He.\n      unfold is_true in Hc;subst;simpl in Hc;repeat rewrite  Bool.andb_true_iff in *.\n      destruct Hc as [[[Hce1 ?] ?] HH].\n      destruct (forallb _ l) eqn:Hl;tryfalse.\n      destruct (eval_type_i _ _ t) eqn:Ht0;tryfalse;simpl in *.\n      destruct (monad_utils.monad_map) eqn:Hmm;tryfalse.\n      destruct (expr_eval_general _ _ _ _ e1) eqn:He1;tryfalse.\n      destruct v0;tryfalse.\n      destruct (string_dec _ _) eqn:Hi;tryfalse;subst.\n      unfold resolve_constr in *. simpl.\n      destruct (resolve_inductive _ _) eqn:HresI;tryfalse.\n      destruct (lookup_with_ind _ _) eqn:Hfind_i;tryfalse.\n      destruct p as [nparams cs]. destruct p0 as [i ci].  simpl in *.\n      rewrite map_length.\n      destruct (Nat.eqb nparams #|l0|) eqn:Hnparams;tryfalse.\n      assert (HresC: resolve_constr Σ1 i0 e = Some (nparams,i, ci)).\n      { unfold resolve_constr. rewrite HresI. rewrite Hfind_i. reflexivity. }\n\n      destruct (match_pat _ _ _ _) eqn:Hpat;tryfalse.\n\n      (* dealing with the translation and the evaluation in PCUIC *)\n      *  assert (IH' : Σ2;;; Γ |- t⟦ e1 .[ exprs ρ] ⟧ Σ1 ⇓ t⟦ of_val_i (vConstr i0 e l2) ⟧ Σ1) by\n            eauto with hints.\n        simpl in IH'.\n        destruct p as [nm tys].\n        rewrite map_map.\n        erewrite <- mkApps_vars_to_apps_constr in IH' by eauto.\n        simpl in IH'.\n        eapply PcbvCurr.eval_iota;eauto.\n        unfold iota_red in *. simpl in *.\n        rewrite <- nth_default_eq in *.\n        unfold nth_default in *.\n        rewrite map_map.\n        destruct (nth_error _) eqn:Hnth;remember ((fun (x : pat * expr) => _)) as f in Hnth.\n        ** (* destruct p as [i ci0];simpl in *. *)\n           specialize (lookup_ind_nth_error _ _ _ _ Hfind_i) as Hnth_eq.\n           rewrite nth_error_map in Hnth_eq. destruct (nth_error cs i) eqn:Nci0;tryfalse.\n           2 : { rewrite Nci0 in *;tryfalse. }\n           erewrite map_nth_error in Hnth by eauto.\n           inversion Hnth as [H1']. clear Hnth.\n           rewrite Nci0 in Hnth_eq. simpl in Hnth_eq. inversion Hnth_eq. subst e.\n\n           unfold trans_branch.\n\n           (* Exploiting the fact that pattern-matching succeeds *)\n           apply pat_match_succeeds in Hpat.\n           destruct Hpat as [pt [Hfnd [Hci [Hl0 Hl2]]]].\n           assert (\n               Hfind : find (fun x => (pName (fst x) =? c.1)) (map f l) =\n                     Some (f (pt, tys))).\n           { eapply find_map with (p1 := fun x => (pName (fst x) =? c.1));auto.\n             intros a;destruct a. subst f. cbn. reflexivity. }\n           specialize (find_forallb_map _ Hfnd HH) as Hce1'. simpl in Hce1'.\n           rewrite Hfind. subst f. cbn in *.\n           assert (Hci' : #|ci| = #|pVars pt|) by lia.\n           rewrite H3. rewrite Hci'. rewrite PeanoNat.Nat.eqb_refl.\n           (* inversion H1';clear H1'. *)\n           clear Hfind.\n\n           subst. replace ((#|pVars pt| + 0)) with (#|pVars pt|) in * by lia.\n           (* assert (Hcomb : *)\n           (*           #|rev (combine (pVars p) ci)| = #|map (fun x : val => t⟦ of_val_i x ⟧ Σ1) l0|). *)\n           (* { rewrite rev_length;rewrite map_length. rewrite Hl0. rewrite combine_length. rewrite Hci. lia. } *)\n           assert (Hok_constr: val_ok Σ1 (vConstr i0 c.1 l2)) by eauto 8 with hints.\n           inversion Hok_constr;subst;clear Hok_constr.\n           rewrite pat_to_lam_rev.\n           apply pat_to_lam_app_par;eauto with hints.\n           *** apply All_skipn.\n               apply All_map.\n               now eapply All_value_of_val.\n           *** apply All_forallb;eauto.\n               apply All_skipn.\n               apply All_map.\n               now eapply All_term_closed_of_val.\n           *** rewrite rev_length. rewrite combine_length.\n               rewrite map_length. rewrite Hci'.\n               rewrite PeanoNat.Nat.eqb_eq in Hnparams.\n               rewrite skipn_length. rewrite map_length.\n               lia.\n           *** rewrite PeanoNat.Nat.eqb_eq in Hnparams.\n               assert (Hlen_pl0 :\n                         #|pVars pt| = #|combine (rev (pVars pt)) (rev l2)|)\n                 by (rewrite combine_length; repeat rewrite rev_length; lia).\n\n               assert (#|pVars pt| = #|skipn nparams l2|) by (rewrite skipn_length;lia).\n               rewrite <- map_skipn.\n               rewrite <- map_rev.\n               remember (fun x : val => t⟦ _ ⟧ _) as f.\n               remember (fun x : string * expr => t⟦ snd x ⟧ Σ1) as g.\n               remember (t⟦ tys .[_] _⟧ _) as te3.\n               assert (Hmap : map f (rev (skipn nparams l2)) =\n                       map g (map (fun_prod id of_val_i)(rev (combine (pVars pt) (skipn nparams l2))))).\n               { rewrite map_map.\n                 subst g;simpl.\n                 rewrite <- combine_rev by auto.\n                 change (fun x : name * val => t⟦ of_val_i (snd x) ⟧ Σ1) with\n                  (fun x : name * val => ((expr_to_pcuic Σ1) ∘ of_val_i) (snd x)).\n                 rewrite <- map_map with (g:=(expr_to_term Σ1) ∘ of_val_i)\n                                        (f:=snd).\n                 rewrite map_combine_snd. now subst.\n                 now repeat rewrite rev_length. }\n               rewrite Hmap. subst g te3.\n               rewrite subst_term_subst_env_par;eauto with hints.\n               eapply IHn with (ρ:=(rev (combine (pVars pt) (skipn nparams l2)) ++ ρ)%list);\n                 eauto with hints.\n               ****  eapply All_app_inv;eauto. apply All_rev.\n                     eapply All_env_ok;eauto with hints. now apply All_skipn.\n               ****\n                     (* rewrite <- combine_rev by (subst;auto). *)\n                     unfold fun_prod,id.\n                     rewrite map_app. subst nparams.\n                     remember (rev (combine (pVars pt) (skipn #|l0| l2))) as l_rev.\n                     assert (Hlrev : #|pVars pt| = #|exprs l_rev|).\n                     { subst. rewrite map_length.\n                       rewrite rev_length. rewrite combine_length.\n                       rewrite skipn_length;lia. }\n                     rewrite Hlrev.\n                     symmetry. eapply subst_env_swap_app with (n:=0);\n                                 eauto with hints.\n                     apply All_map. subst.\n                     apply All_rev. unfold compose. simpl.\n                     apply All_snd_combine with (p:=(iclosed_n 0) ∘ of_val_i).\n                     unfold compose.\n                     eapply All_expr_iclosed_of_val;try apply All_skipn;eauto.\n               **** rewrite <- combine_rev by auto.\n                    rewrite map_combine_snd_funprod.\n                    eapply subst_env_iclosed_0;eauto with hints.\n                    remember ((combine (rev (pVars pt)) (map of_val_i (rev (skipn _ l2))))) as l_comb.\n                    assert (Hlen : #|l_comb| = #|pVars pt|).\n                    { subst. rewrite combine_length. rewrite map_length.\n                      repeat rewrite rev_length. rewrite skipn_length;lia.  }\n                    rewrite <- Hlen.\n                    eapply ty_expr_env_ok_subst_env with (k:=0).\n                    assert (Hcomb : exprs (rev (combine (pVars pt) (skipn nparams l2))) = l_comb).\n                    { subst. repeat rewrite map_rev.  rewrite combine_rev.\n                      apply f_equal. now rewrite  map_combine_snd_funprod.\n                      rewrite map_length. rewrite skipn_length;lia. }\n                    rewrite <- Hcomb. rewrite <- map_app.\n                    subst nparams. eapply eval_ty_expr_env_ok;eauto with hints.\n                    rewrite app_length.\n                    replace (#|rev (combine (pVars pt) (skipn #|l0| l2))|) with #|pVars pt| by\n                        (rewrite rev_length, combine_length, skipn_length;lia).\n                    replace #|ρ| with #|exprs ρ| by apply map_length. eauto with hints.\n\n                    eapply closed_exprs;eauto.\n\n                    eapply All_snd_combine with (p:=iclosed_n 0);eauto with hints.\n                    apply All_map. apply All_rev.\n                    eapply All_expr_iclosed_of_val;eauto using All_skipn.\n\n                    rewrite combine_length. rewrite map_length.\n                    repeat rewrite rev_length. rewrite skipn_length by lia.\n                    replace (min #|pVars pt| (#|l2| - nparams)) with #|pVars pt| by lia.\n                    eauto with hints.\n\n               **** rewrite <- combine_rev by auto.\n                    rewrite map_combine_snd_funprod.\n                    remember ((combine (rev (pVars pt)) (map of_val_i (rev (skipn _ l2))))) as l_comb.\n                    assert (Hlen : #|l_comb| = #|pVars pt|).\n                    { subst. rewrite combine_length. rewrite map_length.\n                      repeat rewrite rev_length. rewrite skipn_length;lia.  }\n                    rewrite <- Hlen.\n                    eapply ty_expr_env_ok_subst_env with (k:=0).\n                    assert (Hcomb : exprs (rev (combine (pVars pt) (skipn nparams l2))) = l_comb).\n                    { subst. repeat rewrite map_rev.  rewrite combine_rev.\n                      apply f_equal. now rewrite  map_combine_snd_funprod.\n                      rewrite map_length. rewrite skipn_length;lia. }\n                    rewrite <- Hcomb. rewrite <- map_app.\n                    subst nparams. eapply eval_ty_expr_env_ok;eauto with hints.\n                    rewrite app_length.\n                    replace (#|rev (combine (pVars pt) (skipn #|l0| l2))|) with #|pVars pt| by\n                        (rewrite rev_length, combine_length, skipn_length;lia).\n                    replace #|ρ| with #|exprs ρ| by apply map_length. eauto with hints.\n                    eapply closed_exprs;eauto.\n               **** rewrite map_length. subst nparams.\n                    replace (#|rev (combine (pVars pt) (skipn #|l0| l2))|) with #|pVars pt| by\n                        (rewrite rev_length, combine_length, skipn_length;lia).\n                    eauto with hints.\n               ****  apply All_map. subst.\n                     apply All_rev. unfold compose. simpl.\n                     apply All_snd_combine with (p:=(iclosed_n 0) ∘ of_val_i).\n                     unfold compose.\n                     eapply All_expr_iclosed_of_val;try apply All_skipn;eauto.\n        ** specialize (lookup_ind_nth_error _ _ _ _ Hfind_i) as Hnth_eq.\n           rewrite nth_error_map in Hnth_eq.\n           rewrite nth_error_map in Hnth.\n           destruct (nth_error _ _) eqn:Nci0;tryfalse.\n    + (* eFix *)\n      simpl in *.\n      destruct (valid_env _ _ _);tryfalse.\n      destruct (eval_type_i 0 ρ t) eqn:Ht0;tryfalse.\n      destruct (eval_type_i 0 ρ t0) eqn:Ht1;tryfalse.\n      cbn in *. inversion He.\n      subst;simpl. repeat erewrite eval_type_i_subst_env by eauto.\n      repeat rewrite subst_env_i_ty_closed_eq by eauto 8 with hints.\n      constructor;auto.\n    + (* eTy *)\n      simpl in *.\n      destruct (eval_type_i 0 ρ t) eqn:Ht0;tryfalse;simpl in *.\n      inversion He;subst;clear He. simpl.\n      erewrite eval_type_i_subst_env by eauto.\n      eapply Wcvb_type_to_term_eval;eauto with hints.\n      eapply closed_exprs;eauto.\nQed.\n\n(** ** Soundness for closed epxressions (In the paper: Corollary 2)*)\nCorollary expr_to_term_sound_closed (n : nat) Σ1 Σ2 (Γ:=[])\n          (e : expr) (v : val) :\n  genv_ok Σ1 ->\n  eval(n, Σ1, [], e) = Ok v ->\n  iclosed_n 0 e = true ->\n  Σ2 ;;; Γ |- t⟦e⟧Σ1 ⇓ t⟦of_val_i v⟧Σ1.\nProof.\n  intros.\n  eapply expr_to_term_sound;eauto with hints.\n  simpl. symmetry. eapply subst_env_i_empty.\nQed.\n\n(** ** Adequacy for terminating programs (In the paper: Theorem 3) *)\nTheorem adequacy_terminating (n : nat) Σ1 Σ2 (Γ:=[])\n        (e : expr) (t : term) (v : val) :\n  genv_ok Σ1 ->\n  eval(n, Σ1, [], e) = Ok v (* evaluation terminates *) ->\n  Σ2 ;;; Γ |- t⟦e⟧Σ1 ⇓ t ->\n  iclosed_n 0 e = true ->\n  t = t⟦of_val_i v⟧Σ1.\nProof.\n  intros.\n  assert (Hcbv1 : Σ2 ;;; Γ |- t⟦ e ⟧Σ1 ⇓ t⟦ of_val_i v ⟧ Σ1)\n    by (eapply expr_to_term_sound_closed;eauto).\n  eapply PcbvCurr.eval_deterministic;eauto.\nQed.\n", "meta": {"author": "malthelange", "repo": "CLVM", "sha": "e80aef02c3112b5b62db79bc2b233020367b0bde", "save_path": "github-repos/coq/malthelange-CLVM", "path": "github-repos/coq/malthelange-CLVM/CLVM-e80aef02c3112b5b62db79bc2b233020367b0bde/embedding/theories/pcuic/PCUICCorrectness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2437250143786896}}
{"text": "Set Warnings \"-notation-overridden\".\n\nRequire Import Category.Lib.\nRequire Export Category.Theory.Functor.\nRequire Export Category.Construction.Comma.\n\nGeneralizable All Variables.\nSet Primitive Projections.\nSet Universe Polymorphism.\nUnset Transparent Obligations.\n\nDefinition Arrow {C : Category} : Category := (Id[C] ↓ Id[C]).\n\nNotation \"C ⃗\" := (@Arrow C) (at level 90) : category_scope.\n", "meta": {"author": "agumonkey", "repo": "cats", "sha": "9f12c5090c2a75fe14eb72c1a806723e38dbb03c", "save_path": "github-repos/coq/agumonkey-cats", "path": "github-repos/coq/agumonkey-cats/cats-9f12c5090c2a75fe14eb72c1a806723e38dbb03c/coq/category-theory/Construction/Arrow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.24365168698760117}}
{"text": "From cap_machine Require Export rules_Restrict rules_binary_base.\nFrom iris.base_logic Require Export invariants gen_heap.\nFrom iris.program_logic Require Export weakestpre ectx_lifting.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import frac.\n\n\nSection cap_lang_spec_rules.\n  Context `{cfgSG Σ, MachineParameters, invG Σ}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types σ : cap_lang.state.\n  Implicit Types a b : Addr.\n  Implicit Types r : RegName.\n  Implicit Types w : Word.\n  Implicit Types reg : gmap RegName Word.\n  Implicit Types ms : gmap Addr Word.\n\n  Lemma step_Restrict Ep K pc_p pc_g pc_b pc_e pc_a w dst src regs :\n    decodeInstrW w = Restrict dst src ->\n    isCorrectPC (inr (pc_p, pc_g, pc_b, pc_e, pc_a)) →\n    regs !! PC = Some (inr (pc_p, pc_g, pc_b, pc_e, pc_a)) →\n    regs_of (Restrict dst src) ⊆ dom _ regs →\n\n    nclose specN ⊆ Ep →\n\n    spec_ctx ∗ ⤇ fill K (Instr Executable) ∗ pc_a ↣ₐ w ∗ ([∗ map] k↦y ∈ regs, k ↣ᵣ y)\n    ={Ep}=∗ ∃ retv regs', ⌜ Restrict_spec regs dst src regs' retv ⌝ ∗ ⤇ fill K (of_val retv) ∗ pc_a ↣ₐ w ∗ ([∗ map] k↦y ∈ regs', k ↣ᵣ y).\n  Proof.\n    iIntros (Hinstr Hvpc HPC Dregs Hcls) \"(#Hinv & Hj & Hpc_a & Hmap)\".\n    iDestruct \"Hinv\" as (ρ) \"Hinv\". rewrite /spec_inv.\n    iInv specN as \">Hinv'\" \"Hclose\". iDestruct \"Hinv'\" as (e [σr σm]) \"[Hown %] /=\".\n    iDestruct (regspec_heap_valid_inclSepM with \"Hown Hmap\") as %Hregs.\n    have HPC' := regs_lookup_eq _ _ _ HPC.\n    have Hx := lookup_weaken _ _ _ _ HPC Hregs.\n    iDestruct (spec_heap_valid with \"[$Hown $Hpc_a]\") as %Hpc_a.\n    iDestruct (spec_expr_valid with \"[$Hown $Hj]\") as %Heq; subst e.\n\n    specialize (normal_always_step (σr,σm)) as [c [ σ2 Hstep]].\n    eapply step_exec_inv in Hstep; eauto.\n\n    specialize (indom_regs_incl _ _ _ Dregs Hregs) as Hri.\n    unfold regs_of in Hri, Dregs. assert (Hstep':=Hstep).\n    destruct (Hri dst) as [wdst [H'dst Hdst]]. by set_solver+.\n    destruct wdst as [| cdst]; [| destruct_cap cdst].\n    { rewrite /= /RegLocate Hdst in Hstep.\n      destruct src; inv Hstep; simplify_pair_eq.\n      all: iFailStep Restrict_fail_dst_noncap. }\n\n    destruct (z_of_argument regs src) as [wsrc|] eqn:Hwsrc;\n      pose proof Hwsrc as H'wsrc; cycle 1.\n    { destruct src as [| r0]; cbn in Hwsrc; [ congruence |].\n      destruct (Hri r0) as [r0v [Hr'0 Hr0]]. by unfold regs_of_argument; set_solver+.\n      rewrite Hr'0 in Hwsrc. destruct r0v as [| cc]; [ congruence | destruct_cap cc].\n      assert (c = Failed ∧ σ2 = (σr, σm)) as (-> & ->).\n      { rewrite /= /RegLocate Hdst Hr0 in Hstep. by simplify_pair_eq. }\n      iFailStep Restrict_fail_src_nonz. }\n    eapply z_of_argument_Some_inv' in Hwsrc; eauto.\n\n    destruct (decide (cdst = E)).\n    { subst cdst. cbn in Hstep. rewrite /RegLocate Hdst in Hstep.\n      repeat case_match; inv Hstep; iFailStep Restrict_fail_pE. }\n\n    destruct (PermPairFlowsTo (decodePermPair wsrc) (cdst,cdst3)) eqn:Hflows; cycle 1.\n    { rewrite /= /RegLocate Hdst in Hstep.\n      destruct Hwsrc as [ -> | (r0 & -> & Hr0 & Hr0') ].\n      all: rewrite ?Hr0' Hflows in Hstep.\n      all: repeat case_match; inv Hstep; iFailStep Restrict_fail_invalid_perm. }\n\n    assert ((c, σ2) = updatePC (update_reg (σr, σm) dst (inr (decodePermPair wsrc, cdst2, cdst1, cdst0)))) as HH.\n    { rewrite /= /RegLocate Hdst in Hstep.\n      destruct Hwsrc as [ -> | (r0 & -> & Hr0 & Hr0') ].\n      all: rewrite ?Hr0' Hflows in Hstep.\n      all: repeat case_match; inv Hstep; eauto; congruence. }\n    clear Hstep. rewrite /update_reg /= in HH.\n\n    destruct (incrementPC (<[ dst := inr (decodePermPair wsrc, cdst2, cdst1, cdst0) ]> regs)) eqn:Hregs';\n      pose proof Hregs' as H'regs'; cycle 1.\n    { apply incrementPC_fail_updatePC with (m:=σm) in Hregs'.\n      eapply updatePC_fail_incl with (m':=σm) in Hregs'.\n      2: by apply lookup_insert_is_Some'; eauto.\n      2: by apply insert_mono; eauto.\n      simplify_pair_eq.\n      iMod ((regspec_heap_update_inSepM _ _ _ dst) with \"Hown Hmap\") as \"[Hown Hmap]\"; eauto.\n      iFailStep Restrict_fail_PC_overflow. }\n\n    eapply (incrementPC_success_updatePC _ σm) in Hregs'\n      as (p' & g' & b' & e' & a'' & a_pc' & HPC'' & Hincr & HuPC & -> & ?).\n    eapply updatePC_success_incl with (m':=σm) in HuPC. 2: by eapply insert_mono; eauto.\n    simplify_pair_eq. iFrame.\n    iMod ((regspec_heap_update_inSepM _ _ _ dst) with \"Hown Hmap\") as \"[Hr Hmap]\"; eauto.\n    iMod ((regspec_heap_update_inSepM _ _ _ PC) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n    iMod (exprspec_mapsto_update _ _ (fill K (Instr NextI)) with \"Hr Hj\") as \"[Hown Hj]\".\n    iExists NextIV,_. iFrame.\n    iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n    { iNext. iExists _,_;iFrame. iPureIntro. eapply rtc_r;eauto.\n      prim_step_from_exec.\n    }\n    iModIntro. iPureIntro. econstructor; eauto. Unshelve. all: try done.\n  Qed.\n\n  Lemma step_restrict_success_z Ep K pc_p pc_g pc_b pc_e pc_a pc_a' w r1 p g b e a z :\n     decodeInstrW w = Restrict r1 (inl z) →\n     isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) →\n     (pc_a + 1)%a = Some pc_a' →\n     PermPairFlowsTo (decodePermPair z) (p,g) = true →\n     p ≠ E →\n     nclose specN ⊆ Ep →\n\n     spec_ctx ∗ ⤇ fill K (Instr Executable)\n              ∗ ▷ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a)\n              ∗ ▷ pc_a ↣ₐ w\n              ∗ ▷ r1 ↣ᵣ inr (p,g,b,e,a)\n     ={Ep}=∗ ⤇ fill K (Instr NextI)\n         ∗ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n         ∗ pc_a ↣ₐ w\n         ∗ r1 ↣ᵣ inr (decodePermPair z,b,e,a).\n  Proof.\n    iIntros (Hinstr Hvpc Hpca' Hflows HpE Hnclose) \"(Hown & Hj & >HPC & >Hpc_a & >Hr1)\".\n    iDestruct (map_of_regs_2 with \"HPC Hr1\") as \"[Hmap %]\".\n    iMod (step_Restrict with \"[$Hown $Hj $Hmap $Hpc_a]\") as (retv regs' Hspec) \"(Hj & Hpc_a & Hregs)\";\n      eauto; simplify_map_eq_alt; try rewrite lookup_insert; eauto.\n      by unfold regs_of; rewrite !dom_insert; set_solver+.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iFrame. simpl in *. incrementPC_inv; simplify_map_eq_alt.\n      rewrite (insert_commute _ PC r1) // insert_insert\n              (insert_commute _ PC r1) // insert_insert.\n      iDestruct (regs_of_map_2 with \"Hregs\") as \"(?&?)\"; eauto; by iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; simpl in *; simplify_map_eq_alt; eauto; try congruence.\n      incrementPC_inv;[|rewrite lookup_insert_ne// lookup_insert;eauto].\n      destruct e4; try congruence. inv Hvpc; naive_solver. }\n  Qed.\n\n\nEnd cap_lang_spec_rules.\n", "meta": {"author": "logsem", "repo": "cerise-stack-monotone", "sha": "dff1909f6abc6de99c28d8f12e903b98dd76fb41", "save_path": "github-repos/coq/logsem-cerise-stack-monotone", "path": "github-repos/coq/logsem-cerise-stack-monotone/cerise-stack-monotone-dff1909f6abc6de99c28d8f12e903b98dd76fb41/theories/binary_model/rules_binary/rules_binary_Restrict.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24361672462087028}}
{"text": "From fae_gtlc_mu.refinements.gradual_static Require Export compat_cast.defs.\nFrom fae_gtlc_mu.stlc_mu Require Export lang.\nFrom fae_gtlc_mu.cast_calculus Require Export types.\n\nSection compat_cast_sum_sum.\n  Context `{!implG Σ,!specG Σ}.\n\n  Hint Extern 5 (AsVal _) => eexists; simpl; try done; eapply cast_calculus.lang.of_to_val; fast_done : typeclass_instances.\n\n  Lemma back_cast_ar_sum_sum:\n    ∀ (A : list (type * type)) (τ1 τ1' τ2 τ2' : type) (pC1 : alternative_consistency A τ1 τ1') (pC2 : alternative_consistency A τ2 τ2')\n      (IHpC1 : back_cast_ar pC1) (IHpC2 : back_cast_ar pC2),\n      back_cast_ar (throughSum A τ1 τ1' τ2 τ2' pC1 pC2).\n  Proof.\n    intros A τ1 τ1' τ2 τ2' pC1 pC2 IHpC1 IHpC2.\n    rewrite /back_cast_ar. iIntros (ei' K' v v' fs) \"(#Hfs & #Hvv' & #Hei' & Hv')\".\n    iDestruct \"Hfs\" as \"[% Hfs']\"; iAssert (rel_cast_functions A fs) with \"[Hfs']\" as \"Hfs\". iSplit; done. iClear \"Hfs'\".\n    rewrite /𝓕c /𝓕. fold (𝓕 pC1) (𝓕 pC2). rewrite between_TSum_subst_rewrite /between_TSum.\n    iMod ((step_lam _ ei' K') with \"[Hv']\") as \"Hv'\"; auto. simpl.\n    rewrite interp_rw_TSum.\n    iDestruct \"Hvv'\" as \"[H1 | H2]\".\n    + iDestruct \"H1\" as ((v1 , v1')) \"[% Hv1v1']\". inversion H0. clear H0 H2 H3 v v'.\n      iMod ((step_case_inl _ ei' K') with \"[Hv']\") as \"Hv'\"; auto. asimpl.\n      wp_head.\n      iApply (wp_bind [cast_calculus.lang.InjLCtx]).\n      iApply (wp_wand with \"[-]\").\n      iApply (IHpC1 ei' (InjLCtx :: K') with \"[Hv']\"); iFrame; auto.\n      iIntros (v1f) \"HHH\". iDestruct \"HHH\" as (v1f') \"[Hv1f' Hv1fv1f']\".\n      iApply wp_value.\n      iExists (InjLV v1f').\n      iSplitL \"Hv1f'\". done.\n      rewrite interp_rw_TSum.\n      iLeft. iExists (v1f , v1f'). by iFrame.\n    + iDestruct \"H2\" as ((v1 , v1')) \"[% Hv1v1']\". inversion H0. clear H0 H2 H3 v v'.\n      iMod ((step_case_inr _ ei' K') with \"[Hv']\") as \"Hv'\"; auto. asimpl.\n      wp_head.\n      iApply (wp_bind [cast_calculus.lang.InjRCtx]).\n      iApply (wp_wand with \"[-]\").\n      iApply (IHpC2 ei' (InjRCtx :: K') with \"[Hv']\"); iFrame; auto.\n      iIntros (v2f) \"HHH\". iDestruct \"HHH\" as (v2f') \"[Hv2f' Hv2fv2f']\".\n      iApply wp_value.\n      iExists (InjRV v2f').\n      iSplitL \"Hv2f'\". done.\n      rewrite interp_rw_TSum.\n      iRight. iExists (v2f , v2f'). by iFrame.\n  Qed.\n\n\nEnd compat_cast_sum_sum.\n", "meta": {"author": "scaup", "repo": "fae-gtlc-mu", "sha": "6c6e64f0844327d55059b97c7aefab023385973e", "save_path": "github-repos/coq/scaup-fae-gtlc-mu", "path": "github-repos/coq/scaup-fae-gtlc-mu/fae-gtlc-mu-6c6e64f0844327d55059b97c7aefab023385973e/theories/refinements/gradual_static/compat_cast/sum_sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.24361671903168122}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition handle_ptimer_sysreg_read_spec (rec: Pointer) (esr: Z64) (adt: RData) : option RData :=\n    match esr with\n    | VZ64 esr =>\n      rely is_int64 esr;\n      rely (peq (base rec) buffer_loc);\n      rely (offset rec =? SLOT_REC);\n      when gidx == (buffer (priv adt)) @ (offset rec);\n      rely is_gidx gidx;\n      let gn := (gs (share adt)) @ gidx in\n      rely (g_tag (ginfo gn) =? GRANULE_STATE_REC);\n      rely (ref_accessible gn CPU_ID);\n      let rt := __ESR_EL2_SYSREG_ISS_RT esr in\n      rely is_int rt;\n      let ec := Z.land esr ESR_EL2_SYSREG_MASK in\n      if ec =? ESR_EL2_SYSREG_TIMER_CNTP_TVAL_EL0 then\n        rely is_int64 (r_cntp_tval_el0 (cpu_regs (priv adt)));\n        let g' := gn {grec: (grec gn) {g_regs: set_reg rt (r_cntp_tval_el0 (cpu_regs (priv adt)))\n                                                       (g_regs (grec gn))}} in\n        Some adt {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}\n      else\n        if ec =? ESR_EL2_SYSREG_TIMER_CNTP_CTL_EL0 then\n          rely is_int64 (r_cntp_ctl_el0 (cpu_regs (priv adt)));\n          let cntp_ctl := Z.land (r_cntp_ctl_el0 (cpu_regs (priv adt))) NOT_CNTx_CTL_IMASK in\n          let val := (if t_masked (g_ptimer (grec gn)) =? 1\n                      then (Z.lor cntp_ctl CNTx_CTL_IMASK)\n                      else  cntp_ctl) in\n          let g' := gn {grec: (grec gn) {g_regs: set_reg rt val (g_regs (grec gn))}} in\n          Some adt {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}\n        else\n          if ec =? ESR_EL2_SYSREG_TIMER_CNTP_CVAL_EL0 then\n            rely is_int64 (r_cntp_cval_el0 (cpu_regs (priv adt)));\n            let g' := gn {grec: (grec gn) {g_regs: set_reg rt (r_cntp_cval_el0 (cpu_regs (priv adt)))\n                                                          (g_regs (grec gn))}} in\n            Some adt {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}\n          else Some adt\n    end.\n\nEnd Spec.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RealmTimerHandler/Specs/handle_ptimer_sysreg_read.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.2436167190316811}}
{"text": "From iris.program_logic Require Import language ectxi_language ectx_language lifting.\nFrom st.STLCmu Require Import lang.\n\nDefinition STLCmu_head_step (e e' : expr) := head_step e tt [] e' tt [].\n\nLemma head_to_STLCmu_head (e e' : expr) σ σ' κ efs : head_step e σ κ e' σ' efs → STLCmu_head_step e e'.\nProof. intro H. rewrite /STLCmu_head_step. inversion H; by econstructor. Qed.\n\nDefinition STLCmu_reducible (e : expr) := ∃ e', STLCmu_step e e'.\nDefinition STLCmu_irreducible (e : expr) := ∀ e', ¬ STLCmu_step e e'.\nDefinition STLCmu_head_reducible (e : expr) := ∃ e', STLCmu_head_step e e'.\nDefinition STLCmu_head_irreducible (e : expr) := ∀ e', ¬ STLCmu_head_step e e'.\n\nLemma prim_to_STLCmu (e1 e2 : expr) σ1 σ2 κ efs : prim_step e1 σ1 κ e2 σ2 efs -> STLCmu_step e1 e2.\nProof. intro H. apply STLCmu_pure. apply (prim_step_pure _ _ _ _ _ _ H). Qed.\n\nLemma STLCmu_prim_red (e : expr) : STLCmu_reducible e <-> reducible e tt.\nProof.\n  split. intro H. destruct H as [e' Hstep]. exists [], e', tt, []. apply Hstep.\n  intro H. destruct H as (a & e' & b & c & Hstep). exists e'. by eapply prim_to_STLCmu.\nQed.\nLemma STLCmu_prim_irred (e : expr) : STLCmu_irreducible e <-> irreducible e tt.\nProof.\n  split.\n  + rewrite /STLCmu_irreducible /irreducible.\n    intros. intro abs. apply (H e'). by eapply prim_to_STLCmu.\n  + intros H e' abs. rewrite /irreducible in H. by apply (H [] e' () []).\nQed.\nLemma STLCmu_prim_head_red (e : expr) : STLCmu_head_reducible e <-> head_reducible e tt.\nProof.\n  split. intro H. destruct H as [e' Hstep]. exists [], e', tt, []. apply Hstep.\n  intro H. destruct H as (a & e' & b & c & Hstep). exists e'. destruct Hstep; by econstructor.\nQed.\nLemma STLCmu_prim_head_irred (e : expr) : STLCmu_head_irreducible e <-> head_irreducible e tt.\nProof.\n  split. intro H. intros κ e' σ efs abs. apply (H e'). by eapply head_to_STLCmu_head.\n  intros H e' Hstep. apply (H [] e' () []). auto.\nQed.\n\nLemma stuck_no_val_irred e : (to_val e = None) → stuck e tt → irreducible e tt.\nProof. rewrite /stuck. intuition. Qed.\n\n(* Ltac head_stuck_solver := *)\n(*   lazymatch goal with *)\n(*   | |- stuck ?e () => apply head_stuck_stuck; head_stuck_solver *)\n(*   | |- head_stuck ?e () => split; head_stuck_solver *)\n(*   | |- rtc STLCmu_step _ _ => (eapply rtc_l; first (auto_STLCmu_step); simplify_custom) *)\n(*   | |- ectx_language.to_val _ = _ => (by simplify_custom) ; head_stuck_solver *)\n(*   | |- head_irreducible _ () => ((apply STLCmu_prim_head_irred; intros e' abs; inversion abs; simplify_option_eq); try done); head_stuck_solver *)\n(*   | |- sub_redexes_are_values _ => apply ectxi_language_sub_redexes_are_values; intros Ki' e' eqqq; destruct Ki'; inversion eqqq; head_stuck_solver *)\n(*   | |- is_Some _ => (by eexists; simplify_custom) ; head_stuck_solver *)\n(*   | |- _ => auto *)\n(*   end. *)\n\n(* Inductive reducibility (e : expr) : Type := *)\n(*   | is_val v : to_val e = Some v → reducibility e *)\n(*   | is_red : reducible e tt → reducibility e *)\n(*   | is_stuck : stuck e tt → reducibility e. *)\n\n(* Lemma fill_stuck (K : list ectx_item) (e : expr) : *)\n(*     stuck e tt → stuck (fill K e) tt. *)\n(* Proof. apply stuck_fill. Qed. *)\n\n(* Lemma dec_expr_reducibility (e : expr) : reducibility e. *)\n(* Proof. *)\n(*   induction e as [x | e1 IH1 e2 IH2 | e _ | e1 IH1 e2 IH2 | | op e1 IH1 e2 IH2 | e0 IH0 e1 IH1 e2 IH2 | e1 IH1 e2 IH2 | e1 IH1 e2 IH2 | e IH | e IH | e IH | e IH | e0 IH0 e1 IH1 e2 IH2 | e IH | e IH | e IH ]; *)\n(*     (try by eapply is_val). *)\n(*   - apply is_stuck. head_stuck_solver. *)\n(*   - destruct IH1 as [ v1 eq1 | is_red1 | is_stuck1 ]; [ rewrite -(of_to_val _ _ eq1) | | ]. *)\n(*     + apply is_red; apply STLCmu_prim_red; eexists; auto_STLCmu_step. *)\n(*     + apply is_red; by apply (fill_reducible [LetInCtx _]). *)\n(*     + apply is_stuck; by apply (fill_stuck [LetInCtx _]). *)\n(*   - destruct IH1 as [ v1 eq1 | is_red1 | is_stuck1 ]; [ rewrite -(of_to_val _ _ eq1) | | ]. *)\n(*     + destruct IH2 as [ v2 eq2 | is_red2 | is_stuck2 ]; [ rewrite -(of_to_val _ _ eq2) | | ]. *)\n(*       * destruct v1; try by (apply is_stuck; head_stuck_solver). *)\n(*         apply is_red; apply STLCmu_prim_red; eexists; auto_STLCmu_step. *)\n(*       * apply is_red; by apply (fill_reducible [AppRCtx _]). *)\n(*       * apply is_stuck; by apply (fill_stuck [AppRCtx _]). *)\n(*     + apply is_red; by apply (fill_reducible [AppLCtx _]). *)\n(*     + apply is_stuck; by apply (fill_stuck [AppLCtx _]). *)\n(*   - destruct IH1 as [ v1 eq1 | is_red1 | is_stuck1 ]; [ rewrite -(of_to_val _ _ eq1) | | ]. *)\n(*     + destruct IH2 as [ v2 eq2 | is_red2 | is_stuck2 ]; [ rewrite -(of_to_val _ _ eq2) | | ]. *)\n(*       * destruct v1; (lazymatch goal with | v : base_lit |- _ => destruct v | |- _ => auto end); try by (apply is_stuck; head_stuck_solver). *)\n(*         destruct v2; (lazymatch goal with | v : base_lit |- _ => destruct v | |- _ => auto end); try by (apply is_stuck; head_stuck_solver). *)\n(*         apply is_red; apply STLCmu_prim_red; eexists; auto_STLCmu_step. *)\n(*       * apply is_red; by apply (fill_reducible [BinOpRCtx _ _]). *)\n(*       * apply is_stuck; by apply (fill_stuck [BinOpRCtx _ _]). *)\n(*     + apply is_red; by apply (fill_reducible [BinOpLCtx _ _]). *)\n(*     + apply is_stuck; by apply (fill_stuck [BinOpLCtx _ _]). *)\n(*   - destruct IH0 as [ v0 eq0 | is_red0 | is_stuck0 ]; [ rewrite -(of_to_val _ _ eq0) | | ]. *)\n(*     + destruct v0; (lazymatch goal with | v : base_lit |- _ => destruct v | |- _ => auto end); try by (apply is_stuck; head_stuck_solver). *)\n(*       destruct b; apply is_red; apply STLCmu_prim_red; eexists; auto_STLCmu_step. *)\n(*     + apply is_red; by apply (fill_reducible [IfCtx _ _]). *)\n(*     + apply is_stuck; by apply (fill_stuck [IfCtx _ _]). *)\n(*   - destruct IH1 as [ v1 eq1 | is_red1 | is_stuck1 ]; [ rewrite -(of_to_val _ _ eq1) | | ]. *)\n(*     + destruct v1; (lazymatch goal with | v : base_lit |- _ => destruct v | |- _ => auto end); try by (apply is_stuck; head_stuck_solver). *)\n(*       apply is_red; apply STLCmu_prim_red; eexists; auto_STLCmu_step. *)\n(*     + apply is_red; by apply (fill_reducible [SeqCtx _]). *)\n(*     + apply is_stuck; by apply (fill_stuck [SeqCtx _]). *)\n(*   - destruct IH1 as [ v1 eq1 | is_red1 | is_stuck1 ]; [ rewrite -(of_to_val _ _ eq1) | | ]. *)\n(*     + destruct IH2 as [ v2 eq2 | is_red2 | is_stuck2 ]; [ rewrite -(of_to_val _ _ eq2) | | ]. *)\n(*       * by apply (is_val _ (v1, v2)%Vₙₒ); simplify_custom. *)\n(*       * apply is_red; by apply (fill_reducible [PairRCtx _]). *)\n(*       * apply is_stuck; by apply (fill_stuck [PairRCtx _]). *)\n(*     + apply is_red; by apply (fill_reducible [PairLCtx _]). *)\n(*     + apply is_stuck; by apply (fill_stuck [PairLCtx _]). *)\n(*   - destruct IH as [ v1 eq1 | is_red1 | is_stuck1 ]; [ rewrite -(of_to_val _ _ eq1) | | ]. *)\n(*     + destruct v1; try by (apply is_stuck; head_stuck_solver). *)\n(*       apply is_red; apply STLCmu_prim_red; eexists; auto_STLCmu_step. *)\n(*     + apply is_red. by apply (fill_reducible [FstCtx]). *)\n(*     + apply is_stuck; by apply (fill_stuck [FstCtx]). *)\n(*   - destruct IH as [ v1 eq1 | is_red1 | is_stuck1 ]; [ rewrite -(of_to_val _ _ eq1) | | ]. *)\n(*     + destruct v1; try by (apply is_stuck; head_stuck_solver). *)\n(*       apply is_red; apply STLCmu_prim_red; eexists; auto_STLCmu_step. *)\n(*     + apply is_red. by apply (fill_reducible [SndCtx]). *)\n(*     + apply is_stuck; by apply (fill_stuck [SndCtx]). *)\n(*   - destruct IH as [ v1 eq1 | is_red1 | is_stuck1 ]; [ rewrite -(of_to_val _ _ eq1) | | ]. *)\n(*     + apply (is_val _ (InjLV v1)). by simplify_custom. *)\n(*     + apply is_red. by apply (fill_reducible [InjLCtx]). *)\n(*     + apply is_stuck; by apply (fill_stuck [InjLCtx]). *)\n(*   - destruct IH as [ v1 eq1 | is_red1 | is_stuck1 ]; [ rewrite -(of_to_val _ _ eq1) | | ]. *)\n(*     + apply (is_val _ (InjRV v1)). by simplify_custom. *)\n(*     + apply is_red. by apply (fill_reducible [InjRCtx]). *)\n(*     + apply is_stuck; by apply (fill_stuck [InjRCtx]). *)\n(*   - destruct IH0 as [ v0 eq0 | is_red0 | is_stuck0 ]; [ rewrite -(of_to_val _ _ eq0) | | ]. *)\n(*     + (destruct v0; try by (apply is_stuck; head_stuck_solver)); *)\n(*       apply is_red; apply STLCmu_prim_red; eexists; auto_STLCmu_step. *)\n(*     + apply is_red; by apply (fill_reducible [CaseCtx _ _]). *)\n(*     + apply is_stuck; by apply (fill_stuck [CaseCtx _ _]). *)\n(*   - destruct IH as [ v1 eq1 | is_red1 | is_stuck1 ]; [ rewrite -(of_to_val _ _ eq1) | | ]. *)\n(*     + apply (is_val _ (FoldV v1)). by simplify_custom. *)\n(*     + apply is_red. by apply (fill_reducible [FoldCtx]). *)\n(*     + apply is_stuck; by apply (fill_stuck [FoldCtx]). *)\n(*   - destruct IH as [ v1 eq1 | is_red1 | is_stuck1 ]; [ rewrite -(of_to_val _ _ eq1) | | ]. *)\n(*     + destruct v1; try by (apply is_stuck; head_stuck_solver). *)\n(*       apply is_red; apply STLCmu_prim_red; eexists; auto_STLCmu_step. *)\n(*     + apply is_red. by apply (fill_reducible [UnfoldCtx]). *)\n(*     + apply is_stuck; by apply (fill_stuck [UnfoldCtx]). *)\n(*   - destruct IH as [ v1 eq1 | is_red1 | is_stuck1 ]; [ rewrite -(of_to_val _ _ eq1) | | ]. *)\n(*     + destruct v1; apply is_red; apply STLCmu_prim_red; eexists; auto_STLCmu_step. *)\n(*     + apply is_red. by apply (fill_reducible [VirtStepCtx]). *)\n(*     + apply is_stuck; by apply (fill_stuck [VirtStepCtx]). *)\n(* Qed. *)\n\nInductive Reducible : expr → Prop :=\n  | LetIn_L_Red e1 e2 : Reducible e1 → Reducible (LetIn e1 e2)\n  | LetIn_D_Red e1 v1 e2 : to_val e1 = Some v1 → Reducible (LetIn e1 e2)\n  | App_L_Red e1 e2 : Reducible e1 → Reducible (App e1 e2)\n  | App_R_Red e1 v1 e2 : to_val e1 = Some v1 → Reducible e2 → Reducible (App e1 e2)\n  | App_D_Red e1 e2 v2 : to_val e2 = Some v2 → Reducible (App (Lam e1) e2)\n  | BinOp_L_Red op e1 e2 : Reducible e1 → Reducible (BinOp op e1 e2)\n  | BinOp_R_Red op e1 v1 e2 : to_val e1 = Some v1 → Reducible e2 → Reducible (BinOp op e1 e2)\n  | BinOp_D_Red op z1 z2 : Reducible (BinOp op (Lit (LitInt z1)) (Lit (LitInt z2)))\n  | If_C_Red e e1 e2 : Reducible e → Reducible (If e e1 e2)\n  | If_D_Red b e1 e2 : Reducible (If (Lit (LitBool b)) e1 e2)\n  | Seq_C_Red e1 e2 : Reducible e1 → Reducible (Seq e1 e2)\n  | Seq_D_Red e2 : Reducible (Seq (Lit LitUnit) e2)\n  | Pair_L_Red e1 e2 : Reducible e1 → Reducible (Pair e1 e2)\n  | Pair_R_Red e1 v1 e2 : to_val e1 = Some v1 → Reducible e2 → Reducible (Pair e1 e2)\n  | Fst_C_Red e1 : Reducible e1 → Reducible (Fst e1)\n  | Fst_D_Red e1 e2 v1 v2 : to_val e1 = Some v1 → to_val e2 = Some v2 → Reducible (Fst (Pair e1 e2))\n  | Snd_C_Red e1 : Reducible e1 → Reducible (Snd e1)\n  | Snd_D_Red e1 e2 v1 v2 : to_val e1 = Some v1 → to_val e2 = Some v2 → Reducible (Snd (Pair e1 e2))\n  | InjL_Red e : Reducible e → Reducible (InjL e)\n  | InjR_Red e : Reducible e → Reducible (InjR e)\n  | Case_C_Red e e1 e2 : Reducible e → Reducible (Case e e1 e2)\n  | Case_D_InjL_Red e v e1 e2 : to_val e = Some v → Reducible (Case (InjL e) e1 e2)\n  | Case_D_InjR_Red e v e1 e2 : to_val e = Some v → Reducible (Case (InjR e) e1 e2)\n  | Fold_Red e : Reducible e → Reducible (Fold e)\n  | Unfold_C_Red e : Reducible e → Reducible (Unfold e)\n  | Unfold_D_Red e v : to_val e = Some v → Reducible (Unfold (Fold e)).\n\nLemma Reducible_valid (e : expr) : reducible e tt <-> Reducible e.\nProof.\n  induction e.\n  Ltac local_tactic := (repeat lazymatch goal with\n                               | |- reducible _ () => apply STLCmu_prim_red\n                               | H : reducible _ () |- _ => destruct (iffRL (STLCmu_prim_red _) H) as [e' Hstep]\n                               end).\n  - split; intro red.\n    + exfalso.\n      assert (head_reducible (Var x) ()). apply prim_head_reducible; auto.\n      apply (@ectxi_language_sub_redexes_are_values STLCmu_ectxi_lang).\n      { intros Ki' e'' eqqq; destruct Ki'; inversion eqqq. }\n      pose proof (iffRL (STLCmu_prim_head_red (Var x)) H).\n      inversion H0. inversion H1.\n    + exfalso. inversion red.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3. eapply LetIn_D_Red. eauto.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        simpl in *. apply LetIn_L_Red. apply IHe. inversion H1.\n        apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      * pose proof (iffRL IHe H0). local_tactic.\n        exists (LetIn e' e2). eapply (STLCmu_step_ctx (fill [LetInCtx _])); eauto.\n      * exists e2.[e/]. apply head_prim_step. by econstructor.\n  - split; intro red.\n    + exfalso.\n      assert (head_reducible (Lam e) ()). apply prim_head_reducible; auto.\n      apply (@ectxi_language_sub_redexes_are_values STLCmu_ectxi_lang).\n      { intros Ki' e'' eqqq; destruct Ki'; inversion eqqq. }\n      pose proof (iffRL (STLCmu_prim_head_red (Lam e)) H).\n      inversion H0. inversion H1.\n    + exfalso. inversion red.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3. eapply App_D_Red. eauto.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        -- simpl in *. apply App_L_Red. apply IHe1. inversion H1.\n           apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n        -- simpl in *. inversion H1. subst. eapply App_R_Red. by rewrite to_of_val.\n           apply IHe2. apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      * pose proof (iffRL IHe1 H0). local_tactic.\n        exists (App e' e2). eapply (STLCmu_step_ctx (fill [AppLCtx _])); eauto.\n      * pose proof (iffRL IHe2 H2). local_tactic.\n        exists (App e1 e'). rewrite -(of_to_val _ _ H1). eapply (STLCmu_step_ctx (fill [AppRCtx _])); eauto.\n      * exists e0.[e2/]. apply head_prim_step. by econstructor.\n  - split; intro red.\n    + exfalso.\n      assert (head_reducible (Lit l) ()). apply prim_head_reducible; auto.\n      apply (@ectxi_language_sub_redexes_are_values STLCmu_ectxi_lang).\n      { intros Ki' e'' eqqq; destruct Ki'; inversion eqqq. }\n      pose proof (iffRL (STLCmu_prim_head_red (Lit l)) H).\n      inversion H0. inversion H1.\n    + exfalso. inversion red.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3. subst. rewrite -(of_to_val _ _ H5) -(of_to_val _ _ H7). eapply BinOp_D_Red.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        -- simpl in *. apply BinOp_L_Red. apply IHe1. inversion H1.\n           apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n        -- simpl in *. inversion H1. subst. eapply BinOp_R_Red. by rewrite to_of_val.\n           apply IHe2. apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      * pose proof (iffRL IHe1 H0). local_tactic.\n        exists (BinOp op e' e2). eapply (STLCmu_step_ctx (fill [BinOpLCtx _ _])); eauto.\n      * pose proof (iffRL IHe2 H3). local_tactic.\n        exists (BinOp op e1 e'). rewrite -(of_to_val _ _ H1). eapply (STLCmu_step_ctx (fill [BinOpRCtx _ _])); eauto.\n      * eexists _. apply head_prim_step. by econstructor.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3; subst; eapply If_D_Red.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        simpl in *. apply If_C_Red. apply IHe1. inversion H1.\n        apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      * pose proof (iffRL IHe1 H0). local_tactic.\n        exists (If e' e2 e3). eapply (STLCmu_step_ctx (fill [IfCtx _ _])); eauto.\n      * destruct b; [exists e2 | exists e3]; apply head_prim_step; by econstructor.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3; subst. rewrite -(of_to_val _ _ H4). eapply Seq_D_Red.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        simpl in *. apply Seq_C_Red. apply IHe1. inversion H1.\n        apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      * pose proof (iffRL IHe1 H0). local_tactic.\n        exists (Seq e' e2). eapply (STLCmu_step_ctx (fill [SeqCtx _])); eauto.\n      * exists e2; apply head_prim_step; by econstructor.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        -- simpl in *. apply Pair_L_Red. apply IHe1. inversion H1.\n           apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n        -- simpl in *. inversion H1. subst. eapply Pair_R_Red. by rewrite to_of_val.\n           apply IHe2. apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      * pose proof (iffRL IHe1 H0). local_tactic.\n        exists (Pair e' e2). eapply (STLCmu_step_ctx (fill [PairLCtx _])); eauto.\n      * pose proof (iffRL IHe2 H2). local_tactic.\n        exists (Pair e1 e'). rewrite -(of_to_val _ _ H1). eapply (STLCmu_step_ctx (fill [PairRCtx _])); eauto.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3; subst. rewrite -(of_to_val _ _ H1) -(of_to_val _ _ H2). eapply Fst_D_Red; by rewrite to_of_val.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        simpl in *. apply Fst_C_Red. apply IHe. inversion H1.\n        apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      * pose proof (iffRL IHe H0). local_tactic.\n        exists (Fst e'). eapply (STLCmu_step_ctx (fill [FstCtx])); eauto.\n      * exists e1; apply head_prim_step. econstructor. by rewrite H0. by rewrite H1.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3; subst. rewrite -(of_to_val _ _ H1) -(of_to_val _ _ H2). eapply Snd_D_Red; by rewrite to_of_val.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        simpl in *. apply Snd_C_Red. apply IHe. inversion H1.\n        apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      * pose proof (iffRL IHe H0). local_tactic.\n        exists (Snd e'). eapply (STLCmu_step_ctx (fill [SndCtx])); eauto.\n      * exists e2; apply head_prim_step. econstructor. by rewrite H0. by rewrite H1.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3; subst.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        simpl in *. apply InjL_Red. apply IHe. inversion H1.\n        apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      pose proof (iffRL IHe H0). local_tactic.\n      exists (InjL e'). eapply (STLCmu_step_ctx (fill [InjLCtx])); eauto.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3; subst.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        simpl in *. apply InjR_Red. apply IHe. inversion H1.\n        apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      pose proof (iffRL IHe H0). local_tactic.\n      exists (InjR e'). eapply (STLCmu_step_ctx (fill [InjRCtx])); eauto.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3; subst.\n        -- rewrite -(of_to_val _ _ H6). eapply Case_D_InjL_Red. by rewrite to_of_val.\n        -- rewrite -(of_to_val _ _ H6). eapply Case_D_InjR_Red. by rewrite to_of_val.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        simpl in *. apply Case_C_Red. apply IHe. inversion H1.\n        apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      * pose proof (iffRL IHe H0). local_tactic.\n        exists (Case e' e1 e2). eapply (STLCmu_step_ctx (fill [CaseCtx _ _])); eauto.\n      * exists e1.[e0/]. apply head_prim_step; by econstructor.\n      * exists e2.[e0/]. apply head_prim_step; by econstructor.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3; subst.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        simpl in *. apply Fold_Red. apply IHe. inversion H1.\n        apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      pose proof (iffRL IHe H0). local_tactic.\n      exists (Fold e'). eapply (STLCmu_step_ctx (fill [FoldCtx])); eauto.\n  - split; intro red.\n    + pose proof (iffRL (STLCmu_prim_red _) red).\n      inversion H. inversion_clear H0. simpl in *. subst. destruct K as [|Ki K _] using rev_ind.\n      * simpl in *. subst. inversion H3; subst. rewrite -(of_to_val _ _ H1). eapply Unfold_D_Red; by rewrite to_of_val.\n      * simpl in *. rewrite fill_app in H1. destruct Ki; try by inversion H1.\n        simpl in *. apply Unfold_C_Red. apply IHe. inversion H1.\n        apply STLCmu_prim_red. exists (fill K e2'). econstructor; eauto.\n    + inversion red; subst; local_tactic.\n      * pose proof (iffRL IHe H0). local_tactic.\n        exists (Unfold e'). eapply (STLCmu_step_ctx (fill [UnfoldCtx])); eauto.\n      * exists e0; apply head_prim_step. econstructor. by rewrite H0.\nQed.\n", "meta": {"author": "scaup", "repo": "sem_backs_st", "sha": "e14aa7f421de94df5c1369d2b4b44d8644243cec", "save_path": "github-repos/coq/scaup-sem_backs_st", "path": "github-repos/coq/scaup-sem_backs_st/sem_backs_st-e14aa7f421de94df5c1369d2b4b44d8644243cec/theories/STLCmu/reducibility.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24358799464210024}}
{"text": "Set Implicit Arguments.\n\nRequire Import Bedrock.Platform.Cito.Syntax.\nRequire Import Bedrock.Platform.Cito.SyntaxExpr.\nRequire Import Bedrock.Platform.Cito.GeneralTactics.\nRequire Import Bedrock.Platform.Cito.Notations3.\nRequire Import Bedrock.Platform.Cito.SemanticsExpr.\nRequire Import Bedrock.Platform.Cito.GoodOptimizer.\n\nRequire Import Bedrock.StringSet.\nModule Import SS := StringSet.\nRequire Import Bedrock.Platform.Cito.StringSetFacts.\nModule SSF := StringSetFacts.\nRequire Import Bedrock.Platform.Cito.StringSetTactics.\n\nRequire Import Bedrock.Platform.Cito.StringMap.\nImport StringMap.\nRequire Import Bedrock.Platform.Cito.StringMapFacts.\n\nDefinition const_dec : forall e, {w | e = Const w} + {~ exists w, e = Const w}.\n  intros; destruct e; solve [ right; intuition; openhyp; intuition | left; eauto ].\nQed.\n\nDefinition const_zero_dec : forall e, {e = Const $0} + {e <> Const $0}.\n  intros; destruct e; solve [right; intuition | destruct (weq w $0); intuition ].\nQed.\n\nLtac f_equal' :=\n  match goal with\n    | |- (if ?E1 then _ else _) = (if ?E2 then _ else _) => replace E2 with E1; try reflexivity\n  end.\n\nRequire Import Bedrock.Platform.Cito.Option.\n\nLtac openhyp' :=\n  repeat match goal with\n           | H : context [const_dec ?E] |- _ => destruct (const_dec E)\n           | |- context [const_dec ?E] => destruct (const_dec E)\n           | H : context [const_zero_dec ?E] |- _ => destruct (const_zero_dec E)\n           | |- context [const_zero_dec ?E] => destruct (const_zero_dec E)\n           | H : context [option_dec ?E] |- _ => destruct (option_dec E)\n           | |- context [option_dec ?E] => destruct (option_dec E)\n           | H : { _ | _ } |- _ => destruct H\n         end.\n\nLtac descend :=\n  repeat match goal with\n           | [ |- exists x, _ ] => eexists\n         end.\n\nLtac unfold_all :=\n  repeat match goal with\n           | H := _ |- _ => unfold H in *; clear H\n         end.\n\nDefinition SET := SS.t.\nDefinition Map := t W.\nDefinition empty_set := SS.empty.\nDefinition empty_map := empty W.\nDefinition Submap elt m1 m2 := forall k v, @find elt k m1 = Some v -> find k m2 = Some v.\nDefinition subtract elt m s := @filter elt (fun k _ => negb (SS.mem k s)) m.\n\nSection TopSection.\n\n  Notation \"m %%- k\" := (remove k m) (at level 60).\n  Infix \"%<=\" := Subset (at level 60).\n  Infix \"%%<=\" := Submap (at level 60).\n  Infix \"+\" := union.\n  Infix \"-\" := subtract.\n  Notation \"! x\" := (singleton x) (at level 100).\n  Notation \"[]\" := (@empty _).\n  Open Scope stmt_scope.\n  Infix \"<-\" := Syntax.Assign.\n\n  Fixpoint const_folding_expr (e : Expr) (env : Map) : Expr :=\n    match e with\n      | Var var =>\n        match option_dec (find var env) with\n          | inleft (exist w _) => Const w\n          | _ => e\n        end\n      | Const w => e\n      | SyntaxExpr.Binop op a b =>\n        let a' := const_folding_expr a env in\n        let b' := const_folding_expr b env in\n        match const_dec a', const_dec b' with\n          | inleft (exist wa _),  inleft (exist wb _) => Const (evalBinop op wa wb)\n          | _, _ => SyntaxExpr.Binop op a' b'\n        end\n      | TestE op a b =>\n        let a' := const_folding_expr a env in\n        let b' := const_folding_expr b env in\n        match const_dec a', const_dec b' with\n          | inleft (exist wa _),  inleft (exist wb _) => Const (if evalTest op wa wb then $1 else $0)\n          | _, _ => TestE op a' b'\n        end\n    end.\n\n  Fixpoint const_folding (s : Stmt) (map : Map) : Stmt * Map * SET :=\n    match s with\n      | skip => (skip, map, empty_set)\n      | a ;; b =>\n        let result_a := const_folding a map in\n        let map' := snd (fst result_a) in\n        let result_b := const_folding b map' in\n        let a' := fst (fst result_a) in\n        let b' := fst (fst result_b) in\n        let map'' := snd (fst result_b) in\n        let written_a := snd result_a in\n        let written_b := snd result_b in\n        (a' ;; b', map'', written_a + written_b)\n      | Syntax.If c t f =>\n        let c' := const_folding_expr c map in\n        match const_dec c' with\n          | inleft (exist w _) =>\n            if wneb w $0 then\n              const_folding t map\n            else\n              const_folding f map\n          | inright _ =>\n            let result_t := const_folding t map in\n            let result_f := const_folding f map in\n            let t' := fst (fst result_t) in\n            let f' := fst (fst result_f) in\n            let written_t := snd result_t in\n            let written_f := snd result_f in\n            (* written vars in branches will no longer have known values *)\n            let map' := map - written_t - written_f in\n            (Syntax.If c' t' f', map', written_t + written_f)\n        end\n      | Syntax.While c b =>\n        if const_zero_dec (const_folding_expr c map) then\n          (skip, map, empty_set)\n        else\n          let c' := const_folding_expr c [] in\n          let result_b := const_folding b [] in\n          let b' := fst (fst result_b) in\n          let written_b := snd result_b in\n          (* written vars in loop body will no longer have known values *)\n          let map' := map - written_b in\n          (Syntax.While c' b', map', written_b)\n      | x <- e =>\n        let e' := const_folding_expr e map in\n        match const_dec e' with\n          | inleft (exist w _) =>\n            let map' := add x w map  in\n            (x <- w, map', !x)\n          | inright _ =>\n            let map' := map %%- x in\n            (x <- e', map', !x)\n        end\n      | Syntax.Label x l =>\n        let map := map %%- x in\n        (s, map, !x)\n      | Syntax.Call x f args =>\n        let f' := const_folding_expr f map in\n        let args' := List.map (fun e => const_folding_expr e map) args in\n        match x with\n          | Some s =>\n            let map := map %%- s in\n            (Syntax.Call x f' args', map, !s)\n          | None =>\n            (Syntax.Call x f' args', map, empty_set)\n        end\n    end.\n\n  Definition constant_folding s := fst (fst (const_folding s empty_map)).\n\n  Definition optimizer := constant_folding.\n\n  Definition opt : Optimizer := fun s _ => optimizer s.\n\n  Lemma union_same_subset : forall s, s + s %<= s.\n    intros; subset_solver.\n  Qed.\n\n  Require Import Bedrock.Platform.Cito.GeneralTactics2.\n  Require Import Coq.Bool.Bool.\n  Require Import Coq.Classes.Morphisms.\n\n  Lemma subtract_none : forall elt (m : t elt) s x, SS.In x s -> find x (m - s) = None.\n    unfold subtract; intros.\n    eapply not_find_in_iff.\n    nintro.\n    eapply In_MapsTo in H0; openhyp.\n    eapply filter_iff in H0; openhyp.\n    eapply negb_true_iff in H1.\n    eapply not_mem_iff in H1; intuition.\n    unfold Proper.\n    unfold respectful.\n    intros; subst; eauto.\n  Qed.\n\n  Lemma empty_submap : forall elt (m : t elt), [] %%<= m.\n    unfold Submap; intros.\n    eapply find_2 in H; eapply empty_mapsto_iff in H; intuition.\n  Qed.\n\n  Lemma subtract_submap : forall elt (m : t elt) s, m - s %%<= m.\n    unfold subtract, Submap.\n    intros.\n    eapply find_2 in H.\n    eapply filter_iff in H.\n    openhyp.\n    eapply find_1; eauto.\n    unfold Proper.\n    unfold respectful.\n    intros; subst; eauto.\n  Qed.\n\n  Lemma subtract_mapsto_iff : forall elt m s k v, @MapsTo elt k v (m - s) <-> (MapsTo k v m /\\ ~ SS.In k s).\n    unfold subtract.\n    split; intros.\n    eapply filter_iff in H.\n    openhyp.\n    split; eauto.\n    eapply negb_true_iff in H0.\n    eapply not_mem_iff; eauto.\n    unfold Proper.\n    unfold respectful.\n    intros; subst; eauto.\n    openhyp.\n    eapply filter_iff.\n    unfold Proper.\n    unfold respectful.\n    intros; subst; eauto.\n    split; eauto.\n    eapply negb_true_iff.\n    eapply not_mem_iff; eauto.\n  Qed.\n\n  Section HintsSection.\n\n    Hint Resolve empty_iff.\n    Hint Unfold Subset.\n    Hint Unfold Submap.\n    Hint Resolve subtract_none.\n    Hint Resolve singleton_iff.\n    Hint Resolve union_subset_1.\n    Hint Resolve union_subset_2.\n    Hint Immediate subset_refl.\n    Hint Resolve union_same_subset.\n    Hint Resolve empty_submap.\n    Hint Resolve subtract_submap.\n    Hint Resolve union_iff union_1 union_2 union_3.\n\n    Definition agree_with (v : vals) (m : Map) :=\n      forall x w,\n        find x m = Some w ->\n        Locals.sel v x = w.\n\n    Lemma agree_with_remove : forall local m x e, agree_with local m -> agree_with (upd local x e) (m %%- x).\n      unfold agree_with; intros; destruct (string_dec x x0).\n      subst.\n      eapply find_2 in H0; eapply remove_mapsto_iff in H0; intuition.\n      eapply find_2 in H0; eapply remove_mapsto_iff in H0; openhyp.\n      rewrite sel_upd_ne.\n      eapply H; eauto.\n      eapply find_1; eauto.\n      eauto.\n    Qed.\n    Hint Resolve agree_with_remove.\n\n    Lemma agree_with_add : forall local m x w, agree_with local m -> agree_with (upd local x w) (add x w m).\n      unfold agree_with; intros; destruct (string_dec x x0).\n      subst.\n      rewrite sel_upd_eq in *.\n      eapply find_2 in H0; eapply add_mapsto_iff in H0; openhyp; intuition.\n      eauto.\n      rewrite sel_upd_ne in *.\n      eapply H; eauto.\n      eapply find_1.\n      eapply find_2 in H0; eapply add_mapsto_iff in H0; openhyp; intuition.\n      eauto.\n    Qed.\n    Hint Resolve agree_with_add.\n\n    Lemma everything_agree_with_empty_map : forall v, agree_with v empty_map.\n      unfold agree_with.\n      intros.\n      eapply find_2 in H; eapply empty_mapsto_iff in H.\n      intuition.\n    Qed.\n    Hint Resolve everything_agree_with_empty_map.\n\n    Definition agree_except (a b : vals) (s : SET) :=\n      forall x,\n        Locals.sel a x <> Locals.sel b x -> SS.In x s.\n\n    Lemma agree_except_upd : forall local x w, agree_except local (upd local x w) (!x).\n      unfold agree_except.\n      intros.\n      destruct (string_dec x x0).\n      subst.\n      eapply singleton_iff; eauto.\n      rewrite sel_upd_ne in H.\n      intuition.\n      eauto.\n    Qed.\n    Hint Resolve agree_except_upd.\n\n    Lemma agree_except_same : forall local s, agree_except local local s.\n      intuition.\n    Qed.\n    Hint Resolve agree_except_same.\n\n    Lemma agree_except_incl : forall v1 v2 s s', agree_except v1 v2 s -> s %<= s' -> agree_except v1 v2 s'.\n      unfold agree_except; eauto.\n    Qed.\n    Hint Resolve agree_except_incl.\n\n    Lemma agree_except_trans : forall m1 m2 m3 s1 s2, agree_except m1 m2 s1 -> agree_except m2 m3 s2 -> agree_except m1 m3 (s1 + s2).\n      unfold agree_except.\n      intros.\n      destruct (weq (Locals.sel m1 x) (Locals.sel m2 x)).\n      destruct (weq (Locals.sel m2 x) (Locals.sel m3 x)).\n      intuition.\n      eauto.\n      eauto.\n    Qed.\n    Hint Resolve agree_except_trans.\n\n    Lemma agree_with_agree_except_subtract : forall v1 v2 m s, agree_with v1 m -> agree_except v1 v2 s -> agree_with v2 (m - s).\n      unfold agree_with, agree_except.\n      intros.\n      destruct (weq (Locals.sel v1 x) (Locals.sel v2 x)).\n      rewrite <- e.\n      eapply H.\n      eapply find_2 in H1.\n      eapply subtract_mapsto_iff in H1.\n      openhyp.\n      eapply find_1; eauto.\n      eapply H0 in n.\n      eapply subtract_none with (m := m) in n.\n      erewrite H1 in n.\n      intuition.\n    Qed.\n    Hint Resolve agree_with_agree_except_subtract.\n\n  End HintsSection.\n\n  Hint Resolve union_subset_1.\n  Hint Resolve union_subset_2.\n  Hint Immediate subset_refl.\n  Hint Resolve union_same_subset.\n  Hint Resolve empty_submap.\n  Hint Resolve subtract_submap.\n\n  Hint Resolve agree_with_remove.\n  Hint Resolve agree_with_add.\n  Hint Resolve everything_agree_with_empty_map.\n  Hint Resolve agree_except_upd.\n  Hint Resolve agree_except_same.\n  Hint Resolve agree_except_trans.\n  Hint Resolve agree_with_agree_except_subtract.\n  Hint Resolve agree_except_incl.\n\n  Remove Hints WordKey.W_as_OT.eq_trans.\n  Remove Hints WordKey.W_as_OT_new.eq_trans.\n\n  Lemma const_folding_expr_correct :\n    forall e m local,\n      agree_with local m ->\n      eval local (const_folding_expr e m) = eval local e.\n  Proof.\n    induction e; simpl; intuition; openhyp'; simpl in *; eauto.\n\n    symmetry; eauto.\n\n    f_equal.\n    erewrite <- (IHe1 m); eauto.\n    erewrite e0; eauto.\n    erewrite <- (IHe2 m); eauto.\n    erewrite e; eauto.\n\n    f_equal; eauto.\n\n    f_equal; eauto.\n\n    f_equal'; f_equal.\n    erewrite <- (IHe1 m); eauto.\n    erewrite e0; eauto.\n    erewrite <- (IHe2 m); eauto.\n    erewrite e; eauto.\n\n    f_equal'; f_equal; eauto.\n\n    f_equal'; f_equal; eauto.\n  Qed.\n\n  Lemma const_folding_expr_correct' :\n    forall e e' m local,\n      e' = const_folding_expr e m ->\n      agree_with local m ->\n      eval local e' = eval local e.\n  Proof.\n    intros; subst; eapply const_folding_expr_correct; eauto.\n  Qed.\n\n  Lemma const_folding_expr_submap_const : forall e m w, const_folding_expr e m = Const w -> forall m', m %%<= m' -> const_folding_expr e m' = Const w.\n    induction e; simpl; intuition; openhyp'; simpl in *; try discriminate.\n\n    eapply H0 in e0.\n    rewrite e0 in e.\n    injection e; intros; subst.\n    eauto.\n\n    eapply H0 in e0.\n    rewrite e0 in e.\n    discriminate.\n\n    eapply IHe1 in e4; eauto.\n    eapply IHe2 in e3; eauto.\n    rewrite e0 in e4; injection e4; intros; subst.\n    rewrite e in e3; injection e3; intros; subst.\n    eauto.\n\n    contradict n.\n    descend.\n    eauto.\n\n    contradict n.\n    descend.\n    eauto.\n\n    eapply IHe1 in e4; eauto.\n    eapply IHe2 in e3; eauto.\n    rewrite e0 in e4; injection e4; intros; subst.\n    rewrite e in e3; injection e3; intros; subst.\n    eauto.\n\n    contradict n.\n    descend.\n    eauto.\n\n    contradict n.\n    descend.\n    eauto.\n\n  Qed.\n  Hint Resolve const_folding_expr_submap_const.\n\n  Lemma not_const_zero_submap : forall e m m', const_folding_expr e m <> Const $0 -> m' %%<= m -> const_folding_expr e m' <> Const $0.\n    intuition eauto.\n  Qed.\n  Hint Resolve not_const_zero_submap.\n\n  Lemma not_const_zero_empty_map : forall e m, const_folding_expr e m <> Const $0 -> const_folding_expr e empty_map <> Const $0.\n    intros.\n    eapply not_const_zero_submap; eauto.\n    eapply empty_submap.\n  Qed.\n  Hint Resolve not_const_zero_empty_map.\n\n  Lemma break_pair : forall A B (p : A * B), p = (fst p, snd p).\n    intros; destruct p; eauto.\n  Qed.\n\nEnd TopSection.\n\nLtac rewrite_expr := repeat erewrite const_folding_expr_correct in * by eauto.\n\nLemma const_folding_expr_correct_list :\n  forall es m local,\n    agree_with local m ->\n    List.map (fun e => eval local (const_folding_expr e m)) es = List.map (eval local) es.\nProof.\n  induction es; simpl; intuition; rewrite_expr; f_equal; eauto.\nQed.\n\nLtac rewrite_expr_list := repeat erewrite map_map in *; repeat erewrite const_folding_expr_correct_list in * by eauto.\n\nRequire Import Bedrock.Platform.Cito.ADT.\n\nModule Make (Import E : ADT).\n\n  Module Import GoodOptimizerMake := GoodOptimizer.Make E.\n  Require Import Bedrock.Platform.Cito.Semantics.\n  Import SemanticsMake.\n\n  Section TopSection.\n\n    Notation \"m %%- k\" := (remove k m) (at level 60).\n    Infix \"%<=\" := Subset (at level 60).\n    Infix \"%%<=\" := Submap (at level 60).\n    Infix \"+\" := union.\n    Infix \"-\" := subtract.\n    Notation \"! x\" := (singleton x) (at level 100).\n    Notation \"[]\" := empty_map.\n    Open Scope stmt_scope.\n    Infix \"<-\" := Syntax.Assign.\n\n    Hint Resolve union_subset_1.\n    Hint Resolve union_subset_2.\n    Hint Immediate subset_refl.\n    Hint Resolve union_same_subset.\n    Hint Resolve empty_submap.\n    Hint Resolve subtract_submap.\n\n    Hint Resolve agree_with_remove.\n    Hint Resolve agree_with_add.\n    Hint Resolve everything_agree_with_empty_map.\n    Hint Resolve agree_except_upd.\n    Hint Resolve agree_except_same.\n    Hint Resolve agree_except_trans.\n    Hint Resolve agree_with_agree_except_subtract.\n    Hint Resolve agree_except_incl.\n\n    Hint Unfold RunsTo.\n    Hint Constructors Semantics.RunsTo.\n    Hint Unfold Safe.\n    Hint Constructors Semantics.Safe.\n\n    Lemma while_case :\n      forall fs t v v',\n        RunsTo fs t v v' ->\n        forall s c b m,\n          let result := const_folding s m in\n          let s' := fst (fst result) in\n          let m' := snd (fst result) in\n          let written := snd result in\n          s = Syntax.While c b ->\n          t = s' ->\n          agree_with (fst v) m ->\n          (let s := b in\n           (* the induction hypothesis from Lemma const_folding_is_backward_simulation' *)\n\n           forall (vs : vals) (heap : Heap) (vs' : vals)\n                  (heap' : Heap) (m : Map),\n             let result := const_folding s m in\n             let s' := fst (fst result) in\n             let m' := snd (fst result) in\n             let written := snd result in\n             RunsTo fs s' (vs, heap) (vs', heap') ->\n             agree_with vs m ->\n             RunsTo fs s (vs, heap) (vs', heap') /\\\n             agree_with vs' m' /\\\n             agree_except vs vs' written\n\n          ) ->\n          RunsTo fs s v v' /\\\n          agree_with (fst v') m' /\\\n          agree_except (fst v) (fst v') written.\n    Proof.\n      induction 1; simpl; intros; unfold_all; subst.\n\n      (* skip *)\n      simpl in *; openhyp'; simpl in *; intuition.\n      econstructor 6.\n      erewrite <- const_folding_expr_correct'.\n      2 : symmetry; eauto.\n      simpl; eauto.\n      simpl; eauto.\n      econstructor.\n\n      (* seq *)\n      simpl in *; openhyp'; simpl in *; intuition.\n\n      (* seq *)\n      simpl in *; openhyp'; simpl in *; intuition.\n\n      (* if *)\n      simpl in *; openhyp'; simpl in *; intuition.\n\n      (* if *)\n      simpl in *; openhyp'; simpl in *; intuition.\n\n      (* while *)\n      simpl in *; openhyp'; simpl in *; try discriminate.\n      injection H3; intros; subst.\n      destruct v; simpl in *.\n      destruct v'; simpl in *.\n      eapply H5 in H0; eauto; openhyp.\n      destruct v''; simpl in *.\n      edestruct IHRunsTo2; try reflexivity.\n      3 : eauto.\n      replace (While (const_folding_expr c _) (fst (fst (const_folding b _)))) with (fst (fst (const_folding (While c b ) (m - snd (const_folding b []))))).\n      Focus 2.\n      simpl in *; openhyp'; [contradict e; eauto | simpl; eauto ].\n      eapply not_const_zero_submap; eauto.\n      eauto.\n      eauto.\n      openhyp.\n      simpl in *; openhyp'; [ contradict e; eauto | ]; simpl in *.\n      eapply not_const_zero_submap; eauto.\n      rewrite_expr.\n      intuition eauto.\n\n      (* while *)\n      simpl in *; openhyp'; simpl in *; try discriminate.\n      injection H1; intros; subst.\n      rewrite_expr.\n      intuition eauto.\n\n      (* call *)\n      simpl in *; openhyp'; simpl in *; intuition.\n\n      (* call *)\n      simpl in *; openhyp'; simpl in *; intuition.\n\n      (* label *)\n      simpl in *; openhyp'; simpl in *; intuition.\n\n      (* assign *)\n      simpl in *; openhyp'; simpl in *; intuition.\n\n    Qed.\n\n    Lemma const_folding_is_backward_simulation :\n      forall fs s vs heap vs' heap' m,\n        let result := const_folding s m in\n        let s' := fst (fst result) in\n        let m' := snd (fst result) in\n        let written := snd result in\n        RunsTo fs s' (vs, heap) (vs', heap') ->\n        agree_with vs m ->\n        RunsTo fs s (vs, heap) (vs', heap') /\\\n        agree_with vs' m' /\\\n        agree_except vs vs' written.\n    Proof.\n      induction s;\n      match goal with\n        | |- context [Syntax.While] => solve [intros; split; intros; eapply while_case in H; eauto; openhyp; eauto]\n        | |- _ => idtac\n      end; simpl; intros.\n\n      (* skip *)\n      inversion H; unfold_all; subst; rewrite_expr; eauto.\n\n      (* seq *)\n      inversion H; unfold_all; subst.\n      destruct v'; simpl in *.\n      eapply IHs1 in H3; eauto; openhyp.\n      eapply IHs2 in H6; eauto; openhyp.\n      eauto 6.\n\n      (* if *)\n      openhyp'.\n\n      destruct (Sumbool.sumbool_of_bool (wneb x $0)); rewrite e1 in *; simpl in *.\n      eapply IHs1 in H; eauto; openhyp.\n      replace x with (eval vs x) in e1 by eauto.\n      rewrite <- e0 in e1.\n      rewrite_expr.\n      eauto.\n      eapply IHs2 in H; eauto; openhyp.\n      replace x with (eval vs x) in e1 by eauto.\n      rewrite <- e0 in e1.\n      rewrite_expr.\n      eauto.\n\n      simpl in *.\n      inversion H; unfold_all; subst.\n      rewrite_expr.\n      eapply IHs1 in H7; eauto; openhyp.\n      intuition eauto.\n      rewrite_expr.\n      eapply IHs2 in H7; eauto; openhyp.\n      split; [econstructor 4 | ]; eauto.\n\n      Focus 3.\n      (* assign *)\n      openhyp'; simpl in *; inversion H; unfold_all; subst; simpl in *.\n      split.\n      replace x with (eval vs x) by eauto.\n      rewrite <- e0.\n      rewrite_expr.\n      econstructor; eauto.\n      eauto.\n\n      split.\n      rewrite_expr.\n      econstructor; eauto.\n      eauto.\n\n      (* call *)\n      destruct o; openhyp'; simpl in *; inversion H; unfold_all; subst; simpl in *.\n      split.\n      rewrite_expr.\n      rewrite_expr_list.\n      specialize RunsToCallInternal; intros.\n      simpl in *.\n      specialize (H1 _ fs (Some s)).\n      simpl in *.\n      eapply H1; eauto.\n      eauto.\n\n      split.\n      rewrite_expr.\n      rewrite_expr_list.\n      specialize RunsToCallForeign; intros.\n      simpl in *.\n      specialize (H1 _ fs (Some s)).\n      simpl in *.\n      eapply H1; eauto.\n      eauto.\n\n      split.\n      rewrite_expr.\n      rewrite_expr_list.\n      specialize RunsToCallInternal; intros.\n      simpl in *.\n      specialize (H1 _ fs None).\n      simpl in *.\n      eapply H1; eauto.\n      eauto.\n\n      split.\n      rewrite_expr.\n      rewrite_expr_list.\n      specialize RunsToCallForeign; intros.\n      simpl in *.\n      specialize (H1 _ fs None).\n      simpl in *.\n      eapply H1; eauto.\n      eauto.\n\n      (* label *)\n      openhyp'; simpl in *; inversion H; unfold_all; subst; simpl in *.\n      split.\n      rewrite_expr.\n      econstructor; eauto.\n      eauto.\n    Qed.\n\n    Lemma PreserveRunsTo_opt : PreserveRunsTo opt.\n      unfold PreserveRunsTo, opt, optimizer, constant_folding; intros.\n      destruct v.\n      destruct v'; simpl in *.\n      eapply const_folding_is_backward_simulation in H; openhyp; eauto.\n    Qed.\n\n    Lemma const_folding_is_safety_preservation :\n      forall fs s vs heap m,\n        let result := const_folding s m in\n        let s' := fst (fst result) in\n        Safe fs s (vs, heap) ->\n        agree_with vs m ->\n        Safe fs s' (vs, heap).\n    Proof.\n      induction s.\n\n      Focus 4.\n      intros.\n      unfold_all.\n      eapply\n        (Safe_coind\n           (fun s' v =>\n              (exists c b m,\n                 let s := While c b in\n                 Safe fs s v /\\\n                 agree_with (fst v) m /\\\n                 (let s := b in\n                  forall (vs : vals) (heap : Heap) (m : Map),\n                    Safe fs s (vs, heap) ->\n                    agree_with vs m -> Safe fs (fst (fst (const_folding s m))) (vs, heap)\n                 ) /\\\n                 s' = fst (fst (const_folding s m))) \\/\n              Safe fs s' v\n        )); [ .. | left; descend; intuition eauto ]; clear; simpl; intros; openhyp.\n\n      (* seq *)\n      simpl in *; openhyp'; simpl in *; intuition.\n\n      inversion_clear H.\n      intuition eauto.\n\n      (* if *)\n      simpl in *; openhyp'; simpl in *; intuition.\n\n      inversion H; subst.\n      openhyp.\n      intuition eauto.\n      right; intuition eauto.\n\n      (* while *)\n      simpl in *; openhyp'; simpl in *; intuition.\n      injection H2; intros; subst.\n      rewrite_expr.\n      inversion H; unfold_all; subst.\n      destruct v; simpl in *.\n      left.\n      repeat split.\n      eauto.\n      right.\n      eauto.\n\n      intros.\n      left.\n      destruct v'; simpl in *.\n      eapply const_folding_is_backward_simulation in H3; eauto; openhyp.\n      descend; intuition.\n      simpl in *; openhyp'; [ contradict e; eauto | ]; simpl in *.\n      eapply not_const_zero_empty_map; eauto.\n      eauto.\n\n      right.\n      eauto.\n\n      inversion H; unfold_all; subst.\n      intuition eauto.\n      right.\n      intuition eauto.\n\n      simpl in *; openhyp'; simpl in *; intuition.\n\n      inversion H; unfold_all; subst.\n      left.\n      descend.\n      intuition eauto.\n      right.\n      descend.\n      intuition eauto.\n\n      simpl in *; openhyp'; simpl in *; intuition.\n      inversion_clear H; eauto.\n\n      (* skip *)\n      eauto.\n\n      (* seq *)\n      simpl; intros; inversion H; unfold_all; subst.\n      econstructor.\n      simpl in *.\n      eapply IHs1; eauto.\n      intros.\n      destruct v'; simpl in *.\n      eapply const_folding_is_backward_simulation in H1.\n      openhyp.\n      eapply IHs2; eauto.\n      eauto.\n\n      (* if *)\n      simpl; intros; openhyp'.\n\n      destruct (Sumbool.sumbool_of_bool (wneb x $0)); rewrite e1 in *; simpl in *.\n      inversion H; subst.\n      unfold_all.\n      openhyp.\n      eauto.\n      erewrite <- const_folding_expr_correct' in H1.\n      2 : symmetry; eauto.\n      simpl in *.\n      intuition.\n      eauto.\n      inversion H; subst.\n      unfold_all.\n      openhyp.\n      erewrite <- const_folding_expr_correct' in H1.\n      2 : symmetry; eauto.\n      simpl in *.\n      intuition.\n      eauto.\n      eauto.\n\n      simpl in *.\n      inversion H; subst.\n      unfold_all.\n      openhyp.\n      econstructor.\n      left.\n      rewrite_expr.\n      intuition eauto.\n      eapply IHs1; eauto.\n      econstructor.\n      right.\n      rewrite_expr.\n      intuition eauto.\n      eapply IHs2; eauto.\n\n      (* call *)\n      destruct o; simpl; intros; inversion H; unfold_all; subst.\n\n      econstructor; rewrite_expr; rewrite_expr_list; eauto.\n      rewrite map_length; eauto.\n\n      eapply SafeCallForeign; rewrite_expr; eauto; rewrite_expr_list; eauto.\n\n      econstructor; rewrite_expr; rewrite_expr_list; eauto.\n      rewrite map_length; eauto.\n\n      eapply SafeCallForeign; rewrite_expr; eauto; rewrite_expr_list; eauto.\n\n      (* assign *)\n      simpl; intros; simpl in *; openhyp'; simpl in *; eauto.\n\n      (* label *)\n      simpl; intros; simpl in *; openhyp'; simpl in *; eauto.\n\n    Qed.\n\n    Lemma PreserveSafe_opt : PreserveSafe opt.\n      unfold PreserveSafe, opt, optimizer, constant_folding; intros.\n      destruct v.\n      eapply const_folding_is_safety_preservation in H; openhyp; eauto.\n    Qed.\n\n    Require Import Bedrock.Platform.Cito.FreeVarsExpr.\n\n    Lemma const_folding_expr_footprint : forall e m, SS.Subset (free_vars (const_folding_expr e m)) (free_vars e).\n    Proof.\n      induction e; simpl; intros; openhyp'; simpl in *; subset_solver; eauto using subset_trans.\n    Qed.\n    Hint Resolve const_folding_expr_footprint.\n\n    Lemma const_folding_expr_footprint_list : forall es m, SS.Subset (Union.union_list (List.map free_vars (List.map (fun e => const_folding_expr e m) es))) (Union.union_list (List.map free_vars es)).\n    Proof.\n      unfold Union.union_list.\n      induction es; simpl; intuition eauto.\n      subset_solver; eauto using subset_trans.\n    Qed.\n\n    Hint Resolve const_folding_expr_footprint_list.\n\n    Require Import Bedrock.Platform.Cito.FreeVars.\n\n    Lemma const_folding_footprint : forall s m, SS.Subset (free_vars (fst (fst (const_folding s m)))) (free_vars s).\n    Proof.\n      induction s; simpl; intros; openhyp'; simpl in *; subset_solver.\n      eauto using subset_trans.\n      eauto using subset_trans.\n      destruct (Sumbool.sumbool_of_bool (wneb x $0)); rewrite e1 in *; simpl in *.\n      eauto using subset_trans.\n      eauto using subset_trans.\n      eauto using subset_trans.\n      eauto using subset_trans.\n      eauto using subset_trans.\n      eauto using subset_trans.\n      eauto using subset_trans.\n      destruct o; simpl in *.\n      subset_solver; eauto using subset_trans.\n      subset_solver; eauto using subset_trans.\n      eauto using subset_trans.\n    Qed.\n\n    Lemma optimizer_footprint : forall s, SS.Subset (free_vars (optimizer s)) (free_vars s).\n      unfold optimizer, constant_folding; intros; eapply const_folding_footprint.\n    Qed.\n\n    Open Scope nat.\n\n    Require Import Coq.Arith.Le.\n    Require Import Coq.Arith.Max.\n    Require Import Bedrock.Platform.Cito.MaxFacts.\n\n    Hint Resolve both_le Le.le_n_S.\n\n    Require Import Bedrock.Platform.Cito.DepthExpr.\n\n    Lemma const_folding_expr_depth : forall e m, depth (const_folding_expr e m) <= depth e.\n    Proof.\n      induction e; simpl; intuition; openhyp'; simpl in *; eauto.\n    Qed.\n    Hint Resolve const_folding_expr_depth.\n\n    Lemma const_folding_expr_depth_list : forall es m, le (Max.max_list 0 (List.map depth (List.map (fun e => const_folding_expr e m) es))) (Max.max_list 0 (List.map depth es)).\n    Proof.\n      unfold Max.max_list.\n      induction es; simpl; intuition eauto.\n    Qed.\n\n    Hint Resolve const_folding_expr_depth_list.\n\n    Require Import Bedrock.Platform.Cito.Depth.\n\n    Hint Extern 0 (le _ _) => progress (simpl; max_solver).\n\n    Lemma const_folding_depth : forall s m, depth (fst (fst (const_folding s m))) <= depth s.\n    Proof.\n      induction s; simpl; intuition; openhyp'; simpl in *; eauto.\n\n      destruct (Sumbool.sumbool_of_bool (wneb x $0)); rewrite e1 in *; simpl in *.\n      eauto using le_trans.\n      eauto using le_trans.\n      destruct o; simpl in *.\n      max_solver; eauto using le_trans.\n      max_solver; eauto using le_trans.\n    Qed.\n\n    Lemma optimizer_depth : forall s, depth (optimizer s) <= depth s.\n      unfold optimizer, constant_folding; intros; eapply const_folding_depth.\n    Qed.\n\n    Import NPeano.Nat.\n    Require Import Bedrock.Platform.Cito.GetLocalVars.\n    Require Import Bedrock.Platform.Cito.GetLocalVarsFacts.\n\n    Lemma PreserveGoodSize_opt : PreserveGoodSize opt.\n      unfold PreserveGoodSize, opt; intros.\n      eapply goodSize_weaken; eauto.\n      eapply add_le_mono.\n      2 : eapply optimizer_depth.\n      eapply get_local_vars_cardinal.\n      eapply optimizer_footprint; eauto.\n    Qed.\n\n    Require Import Bedrock.Platform.Cito.CompileStmtSpec.\n    Require Import Bedrock.Platform.Cito.SetoidListFacts.\n    Require Import Bedrock.Platform.Cito.GeneralTactics2.\n\n    Require Import Bedrock.Platform.Cito.WellFormed.\n\n    Hint Constructors args_not_too_long.\n\n    Lemma const_folding_wellformed : forall s m, wellformed s -> wellformed (fst (fst (const_folding s m))).\n      unfold wellformed.\n      induction s; simpl; intuition; openhyp'; inversion_clear H; simpl in *; eauto.\n      destruct (Sumbool.sumbool_of_bool (wneb x $0)); rewrite e1 in *; simpl in *; eauto.\n      destruct o; simpl in *; eauto; econstructor; eauto; rewrite map_length; eauto.\n    Qed.\n\n    Lemma PreserveSynReq_opt : PreserveSynReq opt.\n      unfold PreserveSynReq, opt; intros.\n      unfold syn_req in *.\n      unfold in_scope in *.\n      openhyp.\n      repeat split; eauto.\n      eapply get_local_vars_subset; eauto.\n      eapply const_folding_wellformed; eauto.\n    Qed.\n\n    Lemma good_optimizer : GoodOptimizer opt.\n      unfold GoodOptimizer.\n      split.\n      eapply PreserveRunsTo_opt.\n      split.\n      eapply PreserveSafe_opt.\n      split.\n      eapply PreserveGoodSize_opt.\n      eapply PreserveSynReq_opt.\n    Qed.\n\n  End TopSection.\n\nEnd Make.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Platform/Cito/optimizers/ConstFolding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.2435879946421002}}
{"text": "Require Export Axioms.\nRequire Import Errors.\nRequire Import Events.\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import compcert.common.Values.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Export Maps.\n\nRequire Import Csharpminor.\nRequire Import Cminor.\nRequire Import Cminorgen.\nRequire Import sepcomp.mem_lemmas.\nRequire Import sepcomp.core_semantics.\nRequire Import sepcomp.Cminor_coop.\nRequire Import sepcomp.Csharpminor_coop.\nRequire Import sepcomp.CminorgenproofRestructured.\n\nRequire Import Coq.Program.Equality.\n\nLemma allocvars_blocks_valid: forall vars E m e m1,\n alloc_variables E m vars e m1 ->\n forall b, Mem.valid_block m b -> Mem.valid_block m1 b.\nProof.\n  intros. induction H; simpl in *.  assumption.\n  apply IHalloc_variables. eapply Mem.valid_block_alloc; eauto.\nQed.\n\nLemma storev_valid_block_1:\nforall ch m addr v m',\nMem.storev ch m addr v = Some m' ->\n(forall b, Mem.valid_block m b -> Mem.valid_block m' b).\nProof. intros. destruct addr; inv H. eapply Mem.store_valid_block_1; eauto. Qed.\n\nLemma storev_valid_block_2:\nforall ch m addr v m',\nMem.storev ch m addr v = Some m' ->\n(forall b, Mem.valid_block m' b -> Mem.valid_block m b).\nProof. intros. destruct addr; inv H. eapply Mem.store_valid_block_2; eauto. Qed.\n\n(*auxiliary lemmas regarding init_mem and genv*)\nLemma add_global_find_symbol: forall {F V} (g: Genv.t F V) m0 m x\n    (G: Genv.alloc_global (Genv.add_global g x) m0 x = Some m)\n    (N: Genv.genv_next g = Mem.nextblock m0)\n    b (VB: Mem.valid_block m b),\n    Mem.valid_block m0 b \\/\n    exists id, Genv.find_symbol (Genv.add_global g x) id = Some b.\nProof. intros.\nunfold Genv.alloc_global in G.\ndestruct x. destruct g0.\n   remember (Mem.alloc m0 0 1) as d.\n   destruct d; inv G. apply eq_sym in Heqd.\n   apply (Mem.drop_perm_valid_block_2 _ _ _ _ _ _ H0) in VB. clear H0.\n   apply (Mem.valid_block_alloc_inv _ _ _ _ _ Heqd) in VB.\n   destruct VB; subst; try (left; assumption).\n     right. unfold Genv.add_global; simpl.\n     unfold Genv.find_symbol; simpl.\n     rewrite N. apply Mem.alloc_result in Heqd. subst.\n     exists i. apply PTree.gss.\nremember (Mem.alloc m0 0 (Genv.init_data_list_size (gvar_init v))) as d.\n  destruct d; inv G. apply eq_sym in Heqd.\n  remember (store_zeros m1 b0 0 (Genv.init_data_list_size (gvar_init v))) as q.\n  destruct q; inv H0. apply eq_sym in Heqq.\n  remember (Genv.store_init_data_list (Genv.add_global g (i, Gvar v)) m2 b0 0\n         (gvar_init v)) as w.\n  destruct w; inv H1. apply eq_sym in Heqw.\n  apply (Mem.drop_perm_valid_block_2 _ _ _ _ _ _ H0) in VB. clear H0.\n  assert (VB2: Mem.valid_block m2 b). unfold Mem.valid_block.\n    rewrite <- (@Genv.store_init_data_list_nextblock _ _ _ _ _ _ _ _ Heqw).\n    apply VB.\n  clear VB Heqw.\n  assert (VB1: Mem.valid_block m1 b). unfold Mem.valid_block.\n    rewrite <- (@Genv.store_zeros_nextblock _ _ _ _ _ Heqq).\n    apply VB2.\n  clear VB2 Heqq.\n  apply (Mem.valid_block_alloc_inv _ _ _ _ _ Heqd) in VB1.\n   destruct VB1; subst; try (left; assumption).\n     right. unfold Genv.add_global; simpl.\n     unfold Genv.find_symbol; simpl.\n     rewrite N. apply Mem.alloc_result in Heqd. subst.\n     exists i. apply PTree.gss.\nQed.\n\nLemma genv_find_add_global_fresh: forall {F V} (g:Genv.t F V) i i0 v0\n   (I:i0 <> i),\n   Genv.find_symbol (Genv.add_global g (i0, v0)) i =\n   Genv.find_symbol g i.\nProof. intros.\n    unfold Genv.find_symbol, Genv.genv_symb. simpl. rewrite PTree.gso. reflexivity.\n    intros N. apply I; subst; trivial.\nQed.\n\nLemma genv_find_add_globals_fresh: forall {F V} defs (g:Genv.t F V) i\n  (G: ~ In i (map fst defs)),\n  Genv.find_symbol (Genv.add_globals g defs) i =  Genv.find_symbol g i.\nProof. intros F V defs.\n  induction defs; simpl; intros. trivial.\n  destruct a.\n  rewrite IHdefs.\n    unfold Genv.find_symbol, Genv.genv_symb. simpl. rewrite PTree.gso. reflexivity.\n    intros N. apply G; left. subst; simpl; trivial.\n  intros N. apply G; right; trivial.\nQed.\n\nLemma add_globals_find_symbol: forall {F V} (defs : list (ident * globdef F V))\n    (R: list_norepet (map fst defs)) (g: Genv.t F V) m0 m\n    (G: Genv.alloc_globals (Genv.add_globals g defs) m0 defs = Some m)\n    (N: Genv.genv_next g = Mem.nextblock m0)\n    b (VB: Mem.valid_block m b),\n    Mem.valid_block m0 b \\/\n    exists id, Genv.find_symbol (Genv.add_globals g defs) id = Some b.\nProof. intros F V defs.\ninduction defs; simpl; intros.\n  inv G. left; trivial.\nremember (Genv.alloc_global (Genv.add_globals (Genv.add_global g a) defs) m0 a) as d.\n  destruct d; inv G. apply eq_sym in Heqd.\n  inv R.\n  specialize (IHdefs H3 _ _ _ H0). simpl in *.\n  rewrite N in *.\n  assert (P: Pos.succ (Mem.nextblock m0) = Mem.nextblock m1).\n    clear IHdefs N VB H0.\n    rewrite (@Genv.alloc_global_nextblock _ _ _ _ _ _ Heqd). trivial.\n  destruct (IHdefs P _ VB); try (right; assumption).\n  clear IHdefs P VB H0.\n  destruct a. destruct g0. simpl in Heqd.\n   remember (Mem.alloc m0 0 1) as t.\n   destruct t; inv Heqd. apply eq_sym in Heqt.\n   apply (Mem.drop_perm_valid_block_2 _ _ _ _ _ _ H1) in H. clear H1.\n   apply (Mem.valid_block_alloc_inv _ _ _ _ _ Heqt) in H.\n   destruct H; subst; try (left; assumption).\n     right. apply Mem.alloc_result in Heqt. subst.\n     exists i. rewrite genv_find_add_globals_fresh; trivial.\n     unfold Genv.find_symbol, Genv.genv_symb. simpl.\n     rewrite PTree.gss. rewrite N. trivial.\nsimpl in *.\n  remember (Mem.alloc m0 0 (Genv.init_data_list_size (gvar_init v))) as t.\n  destruct t; inv Heqd. apply eq_sym in Heqt.\n  remember (store_zeros m2 b0 0 (Genv.init_data_list_size (gvar_init v))) as q.\n  destruct q; inv H1. apply eq_sym in Heqq.\n  remember (Genv.store_init_data_list\n         (Genv.add_globals (Genv.add_global g (i, Gvar v)) defs) m3 b0 0\n         (gvar_init v)) as w.\n  destruct w; inv H4. apply eq_sym in Heqw.\n  apply (Mem.drop_perm_valid_block_2 _ _ _ _ _ _ H1) in H. clear H1.\n  assert (VB3: Mem.valid_block m3 b). unfold Mem.valid_block.\n    rewrite <- (@Genv.store_init_data_list_nextblock _ _ _ _ _ _ _ _ Heqw).\n    apply H.\n  clear H Heqw.\n  assert (VB2: Mem.valid_block m2 b). unfold Mem.valid_block.\n    rewrite <- (@Genv.store_zeros_nextblock _ _ _ _ _ Heqq).\n    apply VB3.\n  clear VB3 Heqq.\n  apply (Mem.valid_block_alloc_inv _ _ _ _ _ Heqt) in VB2.\n   destruct VB2; subst; try (left; assumption).\n     right. apply Mem.alloc_result in Heqt. subst.\n     exists i. rewrite genv_find_add_globals_fresh; trivial.\n     unfold Genv.find_symbol, Genv.genv_symb. simpl.\n     rewrite PTree.gss. rewrite N. trivial.\nQed.\n\nSection TRANSLATION.\nVariable prog: Csharpminor.program.\nVariable tprog: Cminor.program.\nHypothesis TRANSL: transl_program prog = OK tprog.\nLet ge : Csharpminor.genv := Genv.globalenv prog.\n(*Let gce : compilenv := build_global_compilenv prog.*)\nLet tge: genv := Genv.globalenv tprog.\n\nLet core_data := CSharpMin_core.\n\n(*Lenb -- meminj_preserves_globales is new, and needed since this property is now\n    required by the simulation realtions, rather than only at/efterexternal clauses*)\nInductive match_cores: core_data -> meminj -> CSharpMin_core -> mem -> CMin_core -> mem -> Prop :=\n  | MC_states:\n      forall d fn s k e le m tfn ts tk sp te tm cenv xenv j lo hi cs sz\n      (TRF: transl_funbody cenv sz fn = OK tfn)\n      (TR: transl_stmt cenv xenv s = OK ts)\n      (MINJ: Mem.inject j m tm)\n      (MCS: match_callstack prog j m tm\n               (Frame cenv tfn e le te sp lo hi :: cs)\n               (Mem.nextblock m) (Mem.nextblock tm))\n      (MK: match_cont k tk  cenv xenv cs)\n      (PG: meminj_preserves_globals ge j),\n      match_cores d j (CSharpMin_State fn s k e le) m\n                   (CMin_State tfn ts tk (Vptr sp Int.zero) te) tm\n  | MC_state_seq:\n      forall d fn s1 s2 k e le m tfn ts1 tk sp te tm cenv xenv j lo hi cs sz\n      (TRF: transl_funbody cenv sz fn = OK tfn)\n      (TR: transl_stmt cenv xenv s1 = OK ts1)\n      (MINJ: Mem.inject j m tm)\n      (MCS: match_callstack prog j m tm\n               (Frame cenv tfn e le te sp lo hi :: cs)\n               (Mem.nextblock m) (Mem.nextblock tm))\n      (MK: match_cont (Csharpminor.Kseq s2 k) tk cenv xenv cs)\n      (PG: meminj_preserves_globals ge j),\n      match_cores d j (CSharpMin_State fn (Csharpminor.Sseq s1 s2) k e le) m\n                   (CMin_State tfn ts1 tk (Vptr sp Int.zero) te) tm\n  | MC_callstate:\n      forall d fd args k m tfd targs tk tm j cs cenv\n      (TR: transl_fundef fd = OK tfd)\n      (MINJ: Mem.inject j m tm)\n      (MCS: match_callstack prog j m tm cs (Mem.nextblock m) (Mem.nextblock tm))\n      (MK: match_cont k tk cenv nil cs)\n      (ISCC: Csharpminor.is_call_cont k)\n      (ARGSINJ: val_list_inject j args targs)\n      (PG: meminj_preserves_globals ge j),\n\n      match_cores d j (CSharpMin_Callstate fd args k) m\n                   (CMin_Callstate tfd targs tk) tm\n  | MC_returnstate:\n      forall d v k m tv tk tm j cs cenv\n      (MINJ: Mem.inject j m tm)\n      (MCS: match_callstack prog j m tm cs (Mem.nextblock m) (Mem.nextblock tm))\n      (MK: match_cont k tk cenv nil cs)\n      (RESINJ: val_inject j v tv)\n      (PG: meminj_preserves_globals ge j),\n      match_cores d j (CSharpMin_Returnstate v k) m\n                   (CMin_Returnstate tv tk) tm.\n\n(*Lenb -- lemma is new, and needed for the proof of\nTheorem transl_program_correct at the end of this file*)\nLemma match_cores_valid:\nforall d j c1 m1 c2 m2,  match_cores d j c1 m1 c2 m2 ->\n          forall b1 b2 ofs, j b1 = Some(b2,ofs) ->\n               (Mem.valid_block m1 b1 /\\ Mem.valid_block m2 b2).\nProof.\nintros.\ninv H.\n  split. eapply Mem.valid_block_inject_1; eassumption.\n         eapply Mem.valid_block_inject_2; eassumption.\n  split. eapply Mem.valid_block_inject_1; eassumption.\n         eapply Mem.valid_block_inject_2; eassumption.\n  split. eapply Mem.valid_block_inject_1; eassumption.\n         eapply Mem.valid_block_inject_2; eassumption.\n  split. eapply Mem.valid_block_inject_1; eassumption.\n         eapply Mem.valid_block_inject_2; eassumption.\nQed.\n\nLemma match_cores_genvs:\nforall d j c1 m1 c2 m2,  match_cores d j c1 m1 c2 m2 ->\n          meminj_preserves_globals ge j.\nProof.\nintros.\ninv H; trivial.\nQed.\n\n(*-----A variant of CminorgenproofRestructured.match_globalenvs_init,\n   used for init_cores---*)\nLemma valid_init_is_global :\n  forall (R: list_norepet (map fst (prog_defs prog)))\n  m (G: Genv.init_mem prog = Some m)\n  b (VB: Mem.valid_block m b),\n  exists id, Genv.find_symbol (Genv.globalenv prog) id = Some b.\nProof. intros.\n  unfold Genv.init_mem, Genv.globalenv in G. simpl in *.\n  destruct (add_globals_find_symbol _ R (@Genv.empty_genv _ _ ) _ _ G (eq_refl _) _ VB)\n    as [VBEmpty | X]; trivial.\n  exfalso. clear - VBEmpty. unfold Mem.valid_block in VBEmpty.\n    rewrite Mem.nextblock_empty in VBEmpty. xomega.\nQed.\n\nLemma match_globalenvs_init':\n  forall (R: list_norepet (map fst (prog_defs prog)))\n  m j,\n  Genv.init_mem prog = Some m ->\n  meminj_preserves_globals ge j ->\n  match_globalenvs prog j (Mem.nextblock m).\nProof.\n  intros.\n  destruct H0 as [A [B C]].\n  constructor.\n  intros b D. intros [[id E]|[[gv E]|[fptr E]]]; eauto.\n  cut (exists id, Genv.find_symbol (Genv.globalenv prog) id = Some b).\n  intros [id ID].\n  solve[eapply A; eauto].\n  eapply valid_init_is_global; eauto.\n  intros. symmetry. solve[eapply (C _ _ _ _ H0); eauto].\n  intros. eapply Genv.find_symbol_not_fresh; eauto.\n  intros. eapply Genv.find_funct_ptr_not_fresh ; eauto.\n  intros. eapply Genv.find_var_info_not_fresh; eauto.\nQed.\n(*--------------------------------------------------------------------*)\n\nLemma init_cores: forall (v1 v2 : val) (sig : signature) entrypoints\n  (EP: In (v1, v2, sig) entrypoints)\n  (entry_points_ok :\n    forall v1 v2 sig,\n      In (v1, v2, sig) entrypoints ->\n      exists b f1 f2,\n        v1 = Vptr b Int.zero\n        /\\ v2 = Vptr b Int.zero\n        /\\ Genv.find_funct_ptr ge b = Some f1\n        /\\ Genv.find_funct_ptr tge b = Some f2)\n  (vals1 : list val) (c1 : core_data) (m1 : mem) (j : meminj)\n  (vals2 : list val) (m2 : mem)\n  (CSM_Ini : initial_core CSharpMin_core_sem ge v1 vals1 = Some c1)\n  (Inj : Mem.inject j m1 m2)\n  (VI: Forall2 (val_inject j) vals1 vals2)\n  (PG: meminj_preserves_globals ge j)\n  (R: list_norepet (map fst (prog_defs prog)))\n  (INIT_MEM: exists m0, Genv.init_mem prog = Some m0\n    /\\ Ple (Mem.nextblock m0) (Mem.nextblock m1)\n    /\\ Ple (Mem.nextblock m0) (Mem.nextblock m2)),\nexists c2 : CMin_core,\n  initial_core CMin_core_sem tge v2 vals2 = Some c2 /\\\n  match_cores c1 j c1 m1 c2 m2.\nProof. intros.\n  inversion CSM_Ini. unfold  CSharpMin_initial_core in H0. unfold ge in *. unfold tge in *.\n  destruct v1; inv H0.\n  remember (Int.eq_dec i Int.zero) as z; destruct z; inv H1. clear Heqz.\n  remember (Genv.find_funct_ptr (Genv.globalenv prog) b) as zz; destruct zz; inv H0.\n    apply eq_sym in Heqzz.\n  exploit function_ptr_translated; eauto. intros [tf [FIND TR]].\n  exists (CMin_Callstate tf vals2 Cminor.Kstop).\n  split.\n  simpl.\n  destruct (entry_points_ok _ _ _ EP) as [b0 [f1 [f2 [A [B [C D]]]]]].\n  subst. inv A. rewrite C in Heqzz. inv Heqzz. rewrite D in FIND. inv FIND.\n  unfold CMin_initial_core.\n  case_eq (Int.eq_dec Int.zero Int.zero). intros ? e.\n  solve[rewrite D; auto].\n  intros CONTRA.\n  solve[exfalso; auto].\n  eapply MC_callstate with (cenv:=PTree.empty _)(cs := @nil frame); try eassumption.\n  destruct INIT_MEM as [m0 [INIT_MEM [A B]]].\n  assert (Genv.init_mem tprog = Some m0).\n    unfold transl_program in TRANSL.\n    solve[eapply Genv.init_mem_transf_partial in TRANSL; eauto].\n  apply mcs_nil with (Mem.nextblock m0).\n  apply match_globalenvs_init'; auto.\n  apply A. apply B.\n  econstructor. simpl. trivial.\n  simpl. apply forall_inject_val_list_inject; auto.\nQed.\n\nLemma MC_safely_halted: forall (cd : core_data) (j : meminj) (c1 : CSharpMin_core) (m1 : mem)\n  (c2 : CMin_core) (m2 : mem) (v1 : val),\nmatch_cores cd j c1 m1 c2 m2 ->\nhalted CSharpMin_core_sem  c1 = Some v1 ->\nexists v2,\nhalted CMin_core_sem c2 = Some v2 /\\ Mem.inject j m1 m2 /\\\nval_inject j v1 v2.\nProof.\n  intros.\n  inv H; simpl in *; inv H0.\n  destruct k; inv H1. exists tv.\n  split.\n         inv MK. trivial.\n  split; trivial.\nQed.\n\nLemma MC_at_external: forall (cd : core_data) (j : meminj) (st1 : CSharpMin_core) (m1 : mem)\n  (st2 : CMin_core) (m2 : mem) (e : external_function) (vals1 : list val) sig,\n(cd = st1 /\\ match_cores cd j st1 m1 st2 m2) ->\nat_external CSharpMin_core_sem st1 = Some (e, sig, vals1) ->\nMem.inject j m1 m2 /\\\nEvents.meminj_preserves_globals ge j /\\\n(exists vals2 : list val,\n   Forall2 (val_inject j) vals1 vals2 /\\\n   at_external CMin_core_sem st2 = Some (e, sig, vals2)).\nProof.\n  intros. destruct H; subst.\n  inv H1; simpl in *; inv H0.\n  split; trivial.\n  split. destruct (match_callstack_match_globalenvs _ _ _ _ _ _ _ MCS) as [hi Hhi].\n              eapply inj_preserves_globals; eassumption.\n  destruct fd; inv H1.\n  exists targs.\n  split. eapply val_list_inject_forall_inject; eassumption.\n  inv TR.\n  split; trivial.\nQed.\n\nLemma MC_after_external:forall (d : core_data) (j j' : meminj) (st1 : core_data) (st2 : CMin_core)\n  (m1 : mem) (e : external_function) (vals1 : list val) (ret1 : val)\n  (m1' m2 m2' : mem) (ret2 : val) (sig : signature),\nd = st1 /\\ match_cores d j st1 m1 st2 m2 ->\nat_external CSharpMin_core_sem st1 = Some (e, sig, vals1) ->\nEvents.meminj_preserves_globals ge j ->\ninject_incr j j' ->\nEvents.inject_separated j j' m1 m2 ->\nMem.inject j' m1' m2' ->\nval_inject j' ret1 ret2 ->\nmem_forward m1 m1' ->\nMem.unchanged_on (Events.loc_unmapped j) m1 m1' ->\nmem_forward m2 m2' ->\nMem.unchanged_on (Events.loc_out_of_reach j m1) m2 m2' ->\nexists st1' : core_data,\n  exists st2' : CMin_core,\n    exists d' : core_data,\n      after_external CSharpMin_core_sem (Some ret1) st1 = Some st1' /\\\n      after_external CMin_core_sem (Some ret2) st2 = Some st2' /\\\n      d' = st1' /\\ match_cores d' j' st1' m1' st2' m2'.\nProof. intros.\n  destruct (MC_at_external _ _ _ _ _ _ _ _ _ H H0)\n    as [_ [_ [vals2 [ValsInj AtExt2]]]].\n  destruct H as [X MC]; subst.\n  inv MC; simpl in *; inv H0.\n  destruct fd; inv H10.\n  destruct tfd; inv AtExt2.\n  exists (CSharpMin_Returnstate ret1 k). eexists. eexists.\n    split. reflexivity.\n    split. reflexivity.\n    split. reflexivity.\n  simpl in *.\n  econstructor; try eassumption.\n  clear TR H10.\n  destruct k; simpl in *; try contradiction. (*cases k = Kseq and k=Kblock eliminated*)\n  (*k=Kstop*)\n      inv MK; simpl in *.\n      apply match_callstack_incr_bound with (Mem.nextblock m1) (Mem.nextblock m2).\n      eapply match_callstack_external_call; eauto.\n          intros. eapply H6; eauto.\n          xomega.\n          xomega.\n         eapply forward_nextblock; assumption.\n         eapply forward_nextblock; assumption.\n  (*k=Kcall*)\n      inv MK; simpl in *.\n      apply match_callstack_incr_bound with (Mem.nextblock m1) (Mem.nextblock m2).\n      eapply match_callstack_external_call; eauto.\n          intros. eapply H6; eauto.\n          xomega.\n          xomega.\n         eapply forward_nextblock; assumption.\n         eapply forward_nextblock; assumption.\n  solve [eapply meminj_preserves_incr_sep; eassumption].\nQed.\n\nLemma MC_MSI: forall d j\n       q m q' m',\n      match_cores d j q m q' m' ->\n      match_statesInj prog j  (ToState q m) (Cminor_coop.ToState q' m').\n  Proof. intros.\n    inv H; simpl in *.\n     eapply matchInj_state; try eassumption.\n     eapply matchInj_state_seq; try eassumption.\n     eapply matchInj_callstate; try eassumption.\n     eapply matchInj_returnstate; try eassumption.\nQed.\n\nLemma MSI_MC: forall j q m q' m' d\n      (*NEW:*) (PG: meminj_preserves_globals ge j),\n      match_statesInj prog j (ToState q m) (Cminor_coop.ToState q' m') ->\n      match_cores d j q m q' m'.\n  Proof. intros.\n    inv H; simpl in *.\n     destruct q; simpl in *; inv H2.\n        destruct q'; simpl in *; inv H3.\n        eapply MC_states; try eassumption.\n     destruct q; simpl in *; inv H2.\n        destruct q'; simpl in *; inv H3.\n        eapply MC_state_seq; try eassumption.\n     destruct q; simpl in *; inv H2.\n        destruct q'; simpl in *; inv H3.\n        eapply MC_callstate; try eassumption.\n     destruct q; simpl in *; inv H2.\n        destruct q'; simpl in *; inv H3.\n        eapply MC_returnstate; try eassumption.\nQed.\n\nLemma MSI_atExt: forall j c1 m1 c2 m2\n(H: match_statesInj prog j (ToState c1 m1) (Cminor_coop.ToState c2 m2) ),\n(CSharpMin_at_external c1 = None) = (CMin_at_external c2 = None).\nProof.\n  intros.\n  destruct c1; destruct c2; inv H; simpl in *; trivial.\n  destruct f; destruct f0; simpl in *; trivial.\n   apply bind_inversion in TR. destruct TR as [z [ZZ1 ZZ2]]; subst.\n  inv ZZ2.\n  inv TR.\n  inv TR.\n  apply prop_ext. split; intros; inv H.\nQed.\n\nParameter MC_order :  core_data -> core_data -> Prop.\nParameter MC_wellfounded: well_founded MC_order.\nDefinition MC_measure (q:CSharpMin_core): nat :=\n  match q with\n  | CSharpMin_State fn s k e lenv => seq_left_depth s\n  | _ => O\n  end.\n(*Parameter MC_measure: CSharpMin_core-> nat.*)\n\nLemma MS_step_case_SkipSeq:\nforall cenv sz f tfn j m tm  e lenv te sp lo hi cs s k tk xenv\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MK : match_cont (Csharpminor.Kseq s k) tk cenv xenv cs)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n        corestep_plus CMin_core_sem tge (CMin_State tfn Sskip tk (Vptr sp Int.zero) te) tm c2' m2' /\\\n        match_cores (CSharpMin_State f s k e lenv) j (CSharpMin_State f s k e lenv) m c2' m2'.\n(*   exists c' : CSharpMin_core,\n        inj_match_states_star unit match_cores MC_measure (tt,c') j (CSharpMin_State f s k e lenv) m c2' m2'.*)\nProof. intros.\n  dependent induction MK.\n\n  eexists. eexists.\n  split.\n    apply corestep_plus_one.\n        eapply CompCertStep_CMin_corestep'.  simpl.  econstructor. reflexivity.\n  simpl. (* exists (CSharpMin_State f s k e le).\n     left. *) eapply MC_states; eauto.\n\n  eexists. eexists.\n  split.\n    apply corestep_plus_one.\n        eapply CompCertStep_CMin_corestep'.  simpl.  econstructor. reflexivity.\n   simpl. (*exists (CSharpMin_State f (Csharpminor.Sseq s1 s2) k e le).\n      left.  *) eapply MC_state_seq; eauto.\n\n  exploit IHMK; eauto. clear IHMK.  intros [T2 [m2 [A C]]].\n  exists T2; exists m2.\n  split.\n     eapply corestep_star_plus_trans.\n        apply corestep_star_one.  eapply CompCertStep_CMin_corestep'.  simpl.  constructor. reflexivity.\n        simpl. apply A.\n  apply C.\nQed.\n\nLemma MS_step_case_SkipBlock:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MK : match_cont (Csharpminor.Kblock k) tk cenv xenv cs)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n        corestep_plus CMin_core_sem tge (CMin_State tfn Sskip tk (Vptr sp Int.zero) te) tm c2' m2' /\\\n         match_cores  (CSharpMin_State f Csharpminor.Sskip k e lenv)   j (CSharpMin_State f Csharpminor.Sskip k e lenv) m c2' m2'\n(*exists c' : CSharpMin_core,\n        inj_match_states_star unit match_cores MC_measure (tt,c') j (CSharpMin_State f Csharpminor.Sskip k e le) m c2' m2'*).\nProof. intros.\n  dependent induction MK.\n\n  eexists. eexists.\n  split.\n    apply corestep_plus_one.\n        eapply CompCertStep_CMin_corestep'.  simpl. constructor. reflexivity.\n   simpl. (*exists (CSharpMin_State f Csharpminor.Sskip k e le).\n      left.  *) eapply MC_states; eauto.\n\n  exploit IHMK; eauto. clear IHMK.  intros [T2 [m2 [A C]]].\n  exists T2; exists m2.\n  split.\n     eapply corestep_star_plus_trans.\n        apply corestep_star_one.  eapply CompCertStep_CMin_corestep'.  simpl.  constructor. reflexivity.\n        simpl. apply A.\n  (* simpl in *. exists c'.*) apply C.\nQed.\n\nLemma MS_match_is_call_cont:\n  forall tfn te sp tm k tk cenv xenv cs,\n  match_cont k tk cenv xenv cs ->\n  Csharpminor.is_call_cont k ->\n  exists tk',\n    corestep_star CMin_core_sem tge (CMin_State tfn Sskip tk sp te) tm\n                (CMin_State tfn Sskip tk' sp te) tm\n    /\\ is_call_cont tk'\n    /\\ match_cont k tk' cenv nil cs.\nProof.\n  induction 1; simpl; intros; try contradiction.\n  econstructor; split.\n     apply corestep_star_zero. split. exact I. econstructor; eauto.\n  exploit IHmatch_cont; eauto.\n  intros [tk' [A B]]. exists tk'; split.\n  eapply corestep_star_trans; eauto. apply corestep_star_one. simpl. eexists. constructor. auto.\n\n  econstructor; split. apply corestep_star_zero. split. exact I. econstructor; eauto.\nQed.\n\nLemma MS_step_case_SkipCall:\n forall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv m'\n(CC: Csharpminor.is_call_cont k)\n(FL: Mem.free_list m (blocks_of_env e) = Some m')\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MK : match_cont k tk cenv xenv cs)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n        corestep_plus CMin_core_sem tge (CMin_State  tfn Sskip tk (Vptr sp Int.zero) te) tm c2' m2' /\\\n         match_cores  (CSharpMin_Returnstate Vundef k)  j (CSharpMin_Returnstate Vundef k) m' c2' m2'.\n(*exists c' : CSharpMin_core,\n       inj_match_states_star unit match_cores MC_measure (tt,c') j\n       (CSharpMin_Returnstate Vundef k) m' c2' m2'.*)\nProof. intros.\n  exploit MS_match_is_call_cont; eauto. intros [tk' [A [B C]]].\n  exploit match_callstack_freelist; eauto. intros [tm' [P [Q R]]].\n\n  eexists. eexists.\n  split.\n    eapply corestep_star_plus_trans. eexact A. apply corestep_plus_one.\n      eapply CompCertStep_CMin_corestep'. apply step_skip_call. assumption.\n      eauto.\n    eauto.\n    econstructor; eauto.\nQed.\n\nLemma MS_step_case_Assign:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv  x a x0 v id\n(EE:Csharpminor.eval_expr ge e lenv m a v)\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MK : match_cont k tk cenv xenv cs)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(EQ : transl_expr cenv a = OK (x, x0))\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n    corestep_plus CMin_core_sem tge\n     (CMin_State tfn (Sassign id x) tk (Vptr sp Int.zero) te) tm c2' m2' /\\\n   match_cores\n     (CSharpMin_State f Csharpminor.Sskip k e (PTree.set id v lenv)) j\n     (CSharpMin_State f Csharpminor.Sskip k e (PTree.set id v lenv)) m c2'\n     m2'.\n(*  exists c' : CSharpMin_core,\n       inj_match_states_star unit match_cores MC_measure (tt,c') j\n       (CSharpMin_State f Csharpminor.Sskip k e lenv) m' c2' m2'.*)\nProof. intros.\n intros.\n  exploit transl_expr_correct; eauto. intros [tv [EVAL [VINJ APP]]].\n(*\n  exploit var_set_correct; eauto.\n  intros [te' [tm' [EXEC [MINJ' [MCS' OTHER]]]]].\n*)\n  eexists; eexists; split.\n     apply corestep_plus_one. eapply CompCertStep_CMin_corestep'.\n         econstructor. eassumption. reflexivity.\ninv MCS.\n  econstructor; eauto.\neconstructor; eauto.\neapply match_temps_assign; assumption.\nQed.\n\n(*no case Set in CompCert 2.0\nLemma MS_step_case_Set:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv x x0 v a id\n(H: Csharpminor.eval_expr ge e lenv m a v)\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont k tk (fn_return f) cenv xenv cs)\n(EQ : transl_expr cenv a = OK (x, x0)),\nexists c2' : CMin_core,\n  exists m2' : mem,\n        corestep_plus CMin_core_sem tge (CMin_State  tfn (Sassign (for_temp id) x) tk (Vptr sp Int.zero) te) tm c2' m2' /\\\n       match_cores (CSharpMin_State f Csharpminor.Sskip k e (PTree.set id v lenv)) j\n          (CSharpMin_State f Csharpminor.Sskip k e (PTree.set id v lenv)) m c2' m2' .\n(*  exists c' : CSharpMin_core,\n        inj_match_states_star unit match_cores MC_measure (tt,c') j\n          (CSharpMin_State f Csharpminor.Sskip k e (PTree.set id v lenv)) m c2' m2' .*)\nProof. intros.\n  exploit transl_expr_correct; eauto. intros [tv [EVAL [VINJ APP]]].\n  eexists; eexists; split.\n     apply corestep_plus_one. eapply CompCertStep_CMin_corestep'. econstructor; eauto.  reflexivity.\n  simpl in *.\n  econstructor; eauto.\n  apply (match_callstack_set_temp _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ id _ _ VINJ MCS).\n(*  exists (CSharpMin_State f Csharpminor.Sskip k e (PTree.set id v lenv)).\n    left. econstructor; eauto.*)\nQed.\n*)\n\nLemma MS_step_case_Store:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv x x0 x1 x2\n      chunk m' a addr vaddr v\n(CH: Mem.storev chunk m vaddr v = Some m')\n(EvAddr : Csharpminor.eval_expr ge e lenv m addr vaddr)\n(EvA : Csharpminor.eval_expr ge e lenv m a v)\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n                (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont k tk cenv xenv cs)\n(EQ : transl_expr cenv addr = OK (x, x0))\n(EQ1 : transl_expr cenv a = OK (x1, x2))\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n        corestep_plus CMin_core_sem tge (CMin_State  tfn (make_store chunk x x1) tk (Vptr sp Int.zero) te) tm c2' m2' /\\\n        match_cores (CSharpMin_State f Csharpminor.Sskip k e lenv) j\n                      (CSharpMin_State f Csharpminor.Sskip k e lenv) m' c2' m2' .\n(* exists c' : CSharpMin_core,\n        inj_match_states_star unit match_cores MC_measure (tt,c') j\n                      (CSharpMin_State f Csharpminor.Sskip k e lenv) m' c2' m2' .*)\nProof. intros.\n  exploit transl_expr_correct. eauto. eauto. eauto. eexact EvAddr. eauto.\n  intros [tv1 [EVAL1 [VINJ1 APP1]]].\n  exploit transl_expr_correct. eauto. eauto. eauto. eexact EvA. eauto.\n  intros [tv2 [EVAL2 [VINJ2 APP2]]].\n  exploit make_store_correct. eexact EVAL1. eexact EVAL2. eauto. eauto. auto. auto.\n  intros [tm' [tv' [EXEC [STORE' MINJ']]]].\n  eexists; eexists; split.\n      apply corestep_plus_one. eapply CompCertStep_CMin_corestep'. eexact EXEC. reflexivity.\n  simpl in *.\n  inv VINJ1; simpl in CH; try discriminate.\n  econstructor; eauto.\n  rewrite (Mem.nextblock_store _ _ _ _ _ _ CH).\n  rewrite (Mem.nextblock_store _ _ _ _ _ _ STORE').\n  eapply match_callstack_invariant (*with f0 m tm*); eauto.\n  intros. eapply Mem.perm_store_2; eauto.\n  intros. eapply Mem.perm_store_1; eauto.\nQed.\n\nLemma MS_step_case_Call:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv  x x0 x1 a vf fd optid vargs bl\n(EvalA: Csharpminor.eval_expr ge e lenv m a vf)\n(EvalBL: Csharpminor.eval_exprlist ge e lenv m bl vargs)\n(FF: Genv.find_funct ge vf = Some fd)\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont tk k cenv xenv cs)\n(EQ : transl_expr cenv a = OK (x, x0))\n(EQ1 : transl_exprlist cenv bl = OK x1)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n        corestep_plus CMin_core_sem tge\n             (CMin_State  tfn (Scall optid (Csharpminor.funsig fd) x x1)  k (Vptr sp Int.zero) te) tm c2' m2' /\\\n       match_cores (CSharpMin_Callstate fd vargs (Csharpminor.Kcall optid f e lenv tk))  j\n              (CSharpMin_Callstate fd vargs (Csharpminor.Kcall optid f e lenv tk)) m c2' m2'.\n(* exists c' : CSharpMin_core,\n        inj_match_states_star unit match_cores MC_measure (tt,c') j\n              (CSharpMin_Callstate fd vargs (Csharpminor.Kcall optid f e lenv tk)) m c2' m2'.*)\nProof. intros.\n  simpl in FF. exploit functions_translated; eauto. intros [tfd [FIND TRANS]].\n  exploit transl_expr_correct; eauto. intros [tvf [EVAL1 [VINJ1 APP1]]].\n  assert (tvf = vf).\n    exploit match_callstack_match_globalenvs; eauto. intros [bnd MG].\n    eapply val_inject_function_pointer; eauto.\n  subst tvf.\n  exploit transl_exprlist_correct; eauto.\n  intros [tvargs [EVAL2 VINJ2]].\n  eexists; eexists; split.\n      apply corestep_plus_one. eapply CompCertStep_CMin_corestep'.\n          eapply step_call. eassumption. eassumption. apply FIND.\n                      eapply sig_preserved; eauto.\n          econstructor; eauto.\n  simpl in *.\n     (*exists  (CSharpMin_Callstate fd vargs (Csharpminor.Kcall optid f e lenv tk)).\n     left.*) econstructor; eauto. eapply match_Kcall with (cenv' := cenv); eauto.\n            simpl; trivial.\nQed.\n\nLemma MS_step_case_Builtin:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv x t ef optid vres m' bl vargs\n(EvalArgs: Csharpminor.eval_exprlist ge e lenv m bl vargs)\n(ExtCall: Events.external_call ef ge vargs m t vres m')\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont k tk cenv xenv cs)\n(EQ : transl_exprlist cenv bl = OK x)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n      corestep_plus CMin_core_sem tge\n           (CMin_State tfn (Sbuiltin optid ef x) tk (Vptr sp Int.zero) te) tm c2' m2' /\\\n  exists j' : meminj,\n        inject_incr j j' /\\\n        Events.inject_separated j j' m tm /\\\n       match_cores (CSharpMin_State f Csharpminor.Sskip k e (set_optvar optid vres lenv))  j'\n              (CSharpMin_State f Csharpminor.Sskip k e (set_optvar optid vres lenv)) m' c2' m2'.\n(*  exists c',\n        inj_match_states_star unit match_cores MC_measure (tt,c') j'\n          (CSharpMin_State f Csharpminor.Sskip k e (set_optvar optid vres lenv)) m' c2' m2'.*)\nProof. intros.\n  exploit transl_exprlist_correct; eauto.\n  intros [tvargs [EVAL2 VINJ2]].\n  exploit match_callstack_match_globalenvs; eauto. intros [hi' MG].\n  exploit Events.external_call_mem_inject; eauto.\n  intros [j' [vres' [tm' [EC [VINJ [MINJ' [UNMAPPED [OUTOFREACH [INCR SEPARATED]]]]]]]]].\n  eexists; eexists; split.\n      apply corestep_plus_one. eapply CompCertStep_CMin_corestep'.\n           econstructor; try eassumption.\n             eapply Events.external_call_symbols_preserved; eauto.\n                 eapply symbols_preserved; assumption.\n                 eapply varinfo_preserved; assumption.\n           reflexivity.\n  assert (MCS': match_callstack prog j' m' tm'\n                 (Frame cenv tfn e lenv te sp lo hi :: cs)\n                 (Mem.nextblock m') (Mem.nextblock tm')).\n    apply match_callstack_incr_bound with (Mem.nextblock m) (Mem.nextblock tm).\n    eapply match_callstack_external_call; eauto.\n    intros. eapply Events.external_call_max_perm; eauto.\n    xomega. xomega.\n    eapply external_call_nextblock; eauto.\n    eapply external_call_nextblock; eauto.\nexists j'. split. assumption.  split. assumption.\n  simpl in *. (* exists  (CSharpMin_State f Csharpminor.Sskip k e (set_optvar optid vres lenv)).\n  left. *) econstructor; eauto.\nOpaque PTree.set.\n  unfold set_optvar. destruct optid; simpl.\n  eapply match_callstack_set_temp; eauto.\n  auto.\nsolve [eapply meminj_preserves_incr_sep; eassumption].\nQed.\n\nLemma MS_step_case_Ite:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv x x0 x1 x2 b v a s1 s2\n(H : Csharpminor.eval_expr ge e lenv m a v)\n(BoolOfVal : Val.bool_of_val v b)\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont k tk cenv xenv cs)\n(EQ : transl_expr cenv a = OK (x, x0))\n(EQ1 : transl_stmt cenv xenv s1 = OK x1)\n(EQ0 : transl_stmt cenv xenv s2 = OK x2)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n        corestep_plus CMin_core_sem tge\n             (CMin_State tfn (Sifthenelse x x1 x2) tk (Vptr sp Int.zero) te) tm c2' m2' /\\\n        match_cores  (CSharpMin_State f (if b then s1 else s2) k e lenv)  j\n             (CSharpMin_State f (if b then s1 else s2) k e lenv) m c2' m2'.\n(*  exists c',\n        inj_match_states_star unit match_cores MC_measure (tt,c') j\n             (CSharpMin_State f (if b then s1 else s2) k e lenv) m c2' m2'.*)\nProof. intros.\n  exploit transl_expr_correct; eauto. intros [tv [EVAL [VINJ APP]]].\n  exists (CMin_State tfn (if b then x1 else x2) tk (Vptr sp Int.zero) te). exists tm.\n  split.\n     apply corestep_plus_one. eapply CompCertStep_CMin_corestep.\n              eapply step_ifthenelse; eauto. eapply bool_of_val_inject; eauto.\n        econstructor; eauto.\n  simpl in *.\n (*   exists (CSharpMin_State f (if b then s1 else s2) k e lenv).\n    left. *) econstructor; eauto.\n       destruct b; auto.\nQed.\n\nLemma MS_step_case_Loop:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv x s\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont tk k cenv xenv cs)\n(EQ : transl_stmt cenv xenv s = OK x)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n      corestep_plus CMin_core_sem tge (CMin_State tfn (Sloop x) k (Vptr sp Int.zero) te) tm c2' m2' /\\\n      match_cores  (CSharpMin_State f s (Csharpminor.Kseq (Csharpminor.Sloop s) tk) e lenv)  j\n          (CSharpMin_State f s (Csharpminor.Kseq (Csharpminor.Sloop s) tk) e lenv) m c2' m2'.\n(*    exists c',   inj_match_states_star unit match_cores MC_measure (tt,c') j\n          (CSharpMin_State f s (Csharpminor.Kseq (Csharpminor.Sloop s) tk) e lenv) m c2' m2'. *)\nProof. intros.\n  eexists; eexists.\n  split.\n     apply corestep_plus_one. eapply CompCertStep_CMin_corestep'.\n        econstructor; eauto.\n        reflexivity.\n  simpl in *.\n(*      exists  (CSharpMin_State f s (Csharpminor.Kseq (Csharpminor.Sloop s) tk) e lenv).\n      left.*)\n      econstructor; eauto. econstructor; eauto. simpl. rewrite EQ; auto.\nQed.\n\nLemma MS_step_case_Block:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv x s\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont tk k cenv xenv cs)\n(EQ : transl_stmt cenv (true :: xenv) s = OK x)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n        corestep_plus CMin_core_sem tge (CMin_State tfn (Sblock x) k (Vptr sp Int.zero) te) tm c2' m2' /\\\n        match_cores (CSharpMin_State f s (Csharpminor.Kblock tk) e lenv) j\n                    (CSharpMin_State f s (Csharpminor.Kblock tk) e lenv) m c2' m2'.\n(*    exists c' ,\n       inj_match_states_star unit match_cores MC_measure (tt,c') j\n         (CSharpMin_State f s (Csharpminor.Kblock tk) e lenv) m c2' m2'.*)\nProof. intros.\n  eexists; eexists; split.\n     apply corestep_plus_one. eapply CompCertStep_CMin_corestep'.\n        econstructor; eauto.\n        reflexivity.\n  simpl in *.\n(*      exists  (CSharpMin_State f s (Csharpminor.Kblock tk) e lenv).\n      left.*)\n      econstructor; eauto. econstructor; eauto.\nQed.\n\nLemma MS_step_case_ExitSeq:\nforall  cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv n s\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont (Csharpminor.Kseq s tk) k cenv xenv cs)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n        corestep_plus CMin_core_sem tge\n               (CMin_State tfn (Sexit (shift_exit xenv n)) k (Vptr sp Int.zero) te) tm c2' m2'  /\\\n        match_cores (CSharpMin_State f (Csharpminor.Sexit n) tk e lenv) j\n                               (CSharpMin_State f (Csharpminor.Sexit n) tk e lenv) m c2' m2'.\n(*    exists c',  inj_match_states_star unit match_cores MC_measure (tt,c') j\n                                   (CSharpMin_State f (Csharpminor.Sexit n) tk e lenv) m c2' m2'.*)\nProof. intros.\n  dependent induction MK.\n\n  eexists; eexists; split.\n     apply corestep_plus_one. eapply CompCertStep_CMin_corestep'.\n        econstructor; eauto.\n        reflexivity.\n  simpl in *.\n      (*exists   (CSharpMin_State f (Csharpminor.Sexit n) tk e lenv).\n      left.*) econstructor; eauto. reflexivity.\n\n  exploit IHMK; eauto. intros [c2' [m2' [A B]]].\n  exists c2'. exists m2'.\n  split; auto.\n     eapply corestep_plus_trans.\n         apply corestep_plus_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n         simpl. apply A.\n\n  exploit IHMK; eauto.  intros [c2' [m2' [A B]]].\n  exists c2'. exists m2'.\n  split; auto.\n     eapply corestep_plus_trans.\n         apply corestep_plus_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n         simpl. apply A.\nQed.\n\nLemma MS_step_case_ExitBlockZero:\nforall  cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont (Csharpminor.Kblock tk) k cenv xenv cs)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n   corestep_plus CMin_core_sem tge\n     (CMin_State tfn (Sexit (shift_exit xenv 0)) k (Vptr sp Int.zero) te) tm c2' m2' /\\\n   match_cores  (CSharpMin_State f Csharpminor.Sskip tk e lenv) j\n                              (CSharpMin_State f Csharpminor.Sskip tk e lenv) m c2' m2'.\n(*    exists c', inj_match_states_star unit match_cores MC_measure (tt,c') j\n                                    (CSharpMin_State f Csharpminor.Sskip tk e lenv) m c2' m2'.*)\nProof. intros.\n  dependent induction MK.\n\n  eexists; eexists; split.\n     apply corestep_plus_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n  simpl in *.\n    (*exists  (CSharpMin_State f Csharpminor.Sskip tk e lenv).\n    left.*) econstructor; eauto.\n\n  exploit IHMK; eauto. intros [c2' [m2' [A B]]].\n  exists c2'. exists m2'.\n  split; auto.\n     eapply corestep_plus_trans.\n         apply corestep_plus_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n         simpl. apply A.\nQed.\n\nLemma MS_step_case_ExitBlockNonzero:\nforall  cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv n\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n                     (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont (Csharpminor.Kblock tk) k cenv xenv cs)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n        corestep_plus CMin_core_sem tge\n          (CMin_State tfn (Sexit (shift_exit xenv (S n))) k (Vptr sp Int.zero) te) tm c2' m2' /\\\n       match_cores (CSharpMin_State f (Csharpminor.Sexit n) tk e lenv)  j\n          (CSharpMin_State f (Csharpminor.Sexit n) tk e lenv) m c2' m2'.\nProof. intros.\n  dependent induction MK.\n\n  eexists; eexists; split.\n     apply corestep_plus_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n  simpl in *.\n    econstructor; eauto. auto.\n\n  exploit IHMK; eauto. intros [c2' [m2' [A B]]].\n  exists c2'. exists m2'.\n  split; auto.\n     eapply corestep_plus_trans.\n         apply corestep_plus_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n         simpl. apply A.\nQed.\n\nLemma MS_switch_descent:\n  forall cenv xenv k ls body s,\n  transl_lblstmt cenv (switch_env ls xenv) ls body = OK s ->\n  exists k',\n  transl_lblstmt_cont cenv xenv ls k k'\n  /\\ (forall f sp e m,\n      corestep_plus CMin_core_sem tge (CMin_State f s k sp e) m (CMin_State f body k' sp e) m).\nProof.\n  induction ls; intros.\n(*1*)\n  monadInv H.\n  eexists; split.\n      econstructor; eauto.\n  intros. eapply corestep_plus_trans.\n                   apply corestep_plus_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n                   simpl.  apply corestep_plus_one. eapply CompCertStep_CMin_corestep.  constructor. reflexivity.\n(*2*)\n  monadInv H. exploit IHls; eauto. intros [k' [A B]].\n  eexists; split.\n      econstructor; eauto.\n  intros. eapply corestep_plus_star_trans. eauto.\n  eapply corestep_star_trans.\n      apply corestep_star_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n      simpl. apply corestep_star_one. eapply CompCertStep_CMin_corestep.  constructor. reflexivity.\nQed.\n\nLemma MS_switch_ascent:\n  forall f n sp e m cenv xenv k ls k1,\n  let tbl := switch_table ls O in\n  let ls' := select_switch n ls in\n  transl_lblstmt_cont cenv xenv ls k k1 ->\n  exists k2,\n  corestep_star CMin_core_sem tge\n    (CMin_State f (Sexit (Switch.switch_target n (length tbl) tbl)) k1 sp e) m\n    (CMin_State f (Sexit O) k2 sp e) m\n  /\\ transl_lblstmt_cont cenv xenv ls' k k2.\nProof.\n  induction ls; intros; unfold tbl, ls'; simpl.\n(*1*)\n  inv H.\n  eexists; split.\n     apply corestep_star_zero.\n     econstructor; eauto.\n(*2*)\n  simpl in H. inv H.\n  rewrite Int.eq_sym. destruct (Int.eq i n).\n  econstructor; split.  apply corestep_star_zero. econstructor; eauto.\n  exploit IHls; eauto. intros [k2 [A B]].\n  rewrite (length_switch_table ls 1%nat 0%nat).\n  rewrite switch_table_shift.\n  exists k2; split; try exact B.\n  eapply corestep_star_trans.\n        eapply corestep_star_one.  eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n        simpl. eapply corestep_star_trans.\n          eapply corestep_star_one.  eapply CompCertStep_CMin_corestep'. econstructor. reflexivity.\n          apply A.\nQed.\n\nLemma MS_switch_MSI:\n  forall fn k e lenv m tfn ts tk sp te tm cenv xenv j lo hi cs sz ls body tk'\n    (TRF: transl_funbody cenv sz fn = OK tfn)\n    (TR: transl_lblstmt cenv (switch_env ls xenv) ls body = OK ts)\n    (MINJ: Mem.inject j m tm)\n    (MCS: match_callstack prog j m tm\n               (Frame cenv tfn e lenv te sp lo hi :: cs)\n               (Mem.nextblock m) (Mem.nextblock tm))\n    (MK: match_cont k tk cenv xenv cs)\n    (TK: transl_lblstmt_cont cenv xenv ls tk tk'),\n  exists S, exists mm,\n  corestep_plus CMin_core_sem tge (CMin_State tfn (Sexit O) tk' (Vptr sp Int.zero) te) tm S mm\n  /\\ match_statesInj prog j (Csharpminor.State fn (seq_of_lbl_stmt ls) k e lenv m) (Cminor_coop.ToState S mm).\nProof.\n  intros. destruct ls; simpl.\n(*1*)\n  inv TK. econstructor; eexists; split.\n     eapply corestep_plus_trans.\n         eapply corestep_plus_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n         simpl. eapply corestep_plus_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n    simpl. eapply matchInj_state; eauto.\n(*2*)\n  inv TK. econstructor; eexists; split.\n     eapply corestep_plus_trans.\n         eapply corestep_plus_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n         simpl. eapply corestep_plus_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n    simpl.\n       eapply matchInj_state_seq; eauto.\n        simpl. eapply  switch_match_cont; eauto.\nQed.\n\nLemma MS_step_case_Switch:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv a x x0 ts cases n\n(EvalA: Csharpminor.eval_expr ge e lenv m a (Vint n))\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont k tk cenv xenv cs)\n(EQ : transl_expr cenv a = OK (x, x0))\n(EQ0 : transl_lblstmt cenv (switch_env cases xenv) cases\n        (Sswitch x (switch_table cases 0) (length (switch_table cases 0))) =\n      OK ts)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n          corestep_plus CMin_core_sem tge (CMin_State tfn ts tk (Vptr sp Int.zero) te) tm c2' m2' /\\\n         match_cores (CSharpMin_State f (seq_of_lbl_stmt (select_switch n cases)) k e lenv)  j\n                               (CSharpMin_State f (seq_of_lbl_stmt (select_switch n cases)) k e lenv) m c2' m2'.\nProof. intros.\n  exploit transl_expr_correct; eauto. intros [tv [EVAL [VINJ APP]]].\n  inv VINJ.\n  exploit MS_switch_descent; eauto. intros [k1 [A B]].\n  exploit MS_switch_ascent; eauto. intros [k2 [C D]].\n  exploit transl_lblstmt_suffix; eauto. simpl. intros [body' [ts' E]].\n  exploit MS_switch_MSI; eauto. intros [T2 [m2' [F G]]].\n  exists T2; exists m2'; split.\n      eapply corestep_plus_star_trans.\n          eapply B.\n      eapply corestep_star_trans.\n         eapply corestep_star_one. eapply CompCertStep_CMin_corestep'. constructor. eassumption. reflexivity.\n      simpl.\n        eapply corestep_star_trans.\n         apply C.\n         eapply corestep_plus_star. eapply F.\n  simpl. eapply MSI_MC. apply PG. apply G.\nQed.\n\nLemma MS_step_case_ReturnNone:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv m'\n(Freelist: Mem.free_list m (blocks_of_env e) = Some m')\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n                 (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont tk k cenv xenv cs)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n        corestep_plus CMin_core_sem tge (CMin_State tfn (Sreturn None) k (Vptr sp Int.zero) te) tm c2' m2'  /\\\n       match_cores (CSharpMin_Returnstate Vundef (Csharpminor.call_cont tk))  j\n                             (CSharpMin_Returnstate Vundef (Csharpminor.call_cont tk)) m' c2' m2'.\nProof. intros.\n  exploit match_callstack_freelist; eauto. intros [tm' [A [B C]]].\n  eexists; eexists; split.\n     apply corestep_plus_one. eapply CompCertStep_CMin_corestep'. eapply step_return_0. eauto. reflexivity.\n  simpl in *.\n    econstructor; eauto. eapply match_call_cont; eauto.\nQed.\n\nLemma MS_step_case_ReturnSome:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv a x x0 m' v\n(EvalA: Csharpminor.eval_expr ge e lenv m a v)\n(Freelist: Mem.free_list m (blocks_of_env e) = Some m')\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont tk k cenv xenv cs)\n(EQ : transl_expr cenv a = OK (x, x0))\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n        corestep_plus CMin_core_sem tge (CMin_State tfn (Sreturn (Some x)) k (Vptr sp Int.zero) te) tm c2' m2' /\\\n        match_cores  (CSharpMin_Returnstate v (Csharpminor.call_cont tk)) j\n                 (CSharpMin_Returnstate v (Csharpminor.call_cont tk)) m' c2' m2'.\nProof. intros.\n  exploit transl_expr_correct; eauto. intros [tv [EVAL [VINJ APP]]].\n  exploit match_callstack_freelist; eauto. intros [tm' [A [B C]]].\n  eexists; eexists; split.\n     apply corestep_plus_one. eapply CompCertStep_CMin_corestep'. eapply step_return_1. eauto. eauto. reflexivity.\n  simpl in *.\n    econstructor; eauto. eapply match_call_cont; eauto.\nQed.\n\nLemma MS_step_case_Label:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv lbl x s\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont k tk cenv xenv cs)\n(EQ : transl_stmt cenv xenv s = OK x)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n       corestep_plus CMin_core_sem tge (CMin_State tfn (Slabel lbl x) tk (Vptr sp Int.zero) te) tm c2' m2' /\\\n      match_cores (CSharpMin_State f s k e lenv)  j (CSharpMin_State f s k e lenv) m c2' m2'.\nProof. intros.\n  eexists; eexists; split.\n    eapply corestep_plus_one. eapply CompCertStep_CMin_corestep'. constructor. reflexivity.\n  simpl.\n  econstructor; eauto.\nQed.\n\nLemma MS_step_case_Goto:\nforall cenv sz f tfn j m tm e lenv te sp lo hi cs k tk xenv lbl s' k'\n(FindLab: Csharpminor.find_label lbl (Csharpminor.fn_body f)\n       (Csharpminor.call_cont k) = Some (s', k'))\n(TRF : transl_funbody cenv sz f = OK tfn)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm (Frame cenv tfn e lenv te sp lo hi :: cs)\n        (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont k tk cenv xenv cs)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n       corestep_plus CMin_core_sem tge (CMin_State tfn (Sgoto lbl) tk (Vptr sp Int.zero) te) tm c2' m2' /\\\n       match_cores  (CSharpMin_State f s' k' e lenv) j (CSharpMin_State f s' k' e lenv) m c2' m2'.\nProof. intros.\n  exploit transl_find_label_body; eauto.\n  intros [ts' [tk' [xenv' [A [B C]]]]].\n  eexists; eexists; split.\n    eapply corestep_plus_one. eapply CompCertStep_CMin_corestep'. apply step_goto. eexact A. reflexivity.\n  simpl.\n  econstructor; eauto.\nQed.\n\n(******************************Functions required for internal call rule*****************************)\n(****These extend the original lemmas by additional guarantees of the (now exposed) memory injections, in order\n    for the overall lemma for internal calls to establish the inject_separated fact******************************)\n\nLemma MS_match_callstack_alloc_variables_rec:\n  forall tm sp tf cenv le te lo cs,\n  Mem.valid_block tm sp ->\n  fn_stackspace tf <= Int.max_unsigned ->\n  (forall ofs k p, Mem.perm tm sp ofs k p -> 0 <= ofs < fn_stackspace tf) ->\n  (forall ofs k p, 0 <= ofs < fn_stackspace tf -> Mem.perm tm sp ofs k p) ->\n  forall e1 m1 vars e2 m2,\n  alloc_variables e1 m1 vars e2 m2 ->\n  forall f1,\n  list_norepet (map fst vars) ->\n  cenv_compat cenv vars (fn_stackspace tf) ->\n  cenv_separated cenv vars ->\n  cenv_mem_separated cenv vars f1 sp m1 ->\n  (forall id sz, In (id, sz) vars -> e1!id = None) ->\n  match_callstack prog f1 m1 tm\n    (Frame (cenv_remove cenv vars) tf e1 le te sp lo (Mem.nextblock m1) :: cs)\n    (Mem.nextblock m1) (Mem.nextblock tm) ->\n  Mem.inject f1 m1 tm ->\n  exists f2,\n    match_callstack prog f2 m2 tm\n      (Frame cenv tf e2 le te sp lo (Mem.nextblock m2) :: cs)\n      (Mem.nextblock m2) (Mem.nextblock tm)\n  /\\ Mem.inject f2 m2 tm\n  /\\ (*LENB: THIS IS NEW*) inject_incr f1 f2\n(****************The following three conditions are new******************)\n  /\\ (forall b, Mem.valid_block m1 b -> f2 b = f1 b)\n  /\\ (forall b b' d', f1 b = None -> f2 b = Some (b',d') -> b' = sp)\n  /\\ forall j',  inject_incr f2 j' -> inject_separated f2 j' m2 tm ->\n                 inject_separated f2 j' m1 tm.\nProof.\nProof.\n  intros until cs; intros VALID REPRES STKSIZE STKPERMS.\n  induction 1; intros f1 NOREPET COMPAT SEP1 SEP2 UNBOUND MCS MINJ.\n  (* base case *)\n  simpl in MCS. exists f1.\n   split. assumption.\n   split. assumption.\n   split. apply inject_incr_refl.\n   split. auto.\n   split. intros. rewrite H in H0; inv H0.\n   intros. assumption.\n  (* inductive case *)\n  simpl in NOREPET. inv NOREPET.\n(* exploit Mem.alloc_result; eauto. intros RES.\n  exploit Mem.nextblock_alloc; eauto. intros NB.*)\n  exploit (COMPAT id sz). auto with coqlib. intros [ofs [CENV [ALIGNED [LOB HIB]]]].\n  exploit Mem.alloc_left_mapped_inject.\n    eexact MINJ.\n    eexact H.\n    eexact VALID.\n    instantiate (1 := ofs). zify. omega.\n    intros. exploit STKSIZE; eauto. omega.\n    intros. apply STKPERMS. zify. omega.\n    replace (sz - 0) with sz by omega. auto.\n    intros. eapply SEP2. eauto with coqlib. eexact CENV. eauto. eauto. omega.\n  intros [f2 [A [B [C D]]]].\n  exploit (IHalloc_variables f2); eauto.\n    red; intros. eapply COMPAT. auto with coqlib.\n    red; intros. eapply SEP1; eauto with coqlib.\n    red; intros. exploit Mem.perm_alloc_inv; eauto. destruct (eq_block b b1); intros P.\n    subst b. rewrite C in H5; inv H5.\n    exploit SEP1. eapply in_eq. eapply in_cons; eauto. eauto. eauto.\n    red; intros; subst id0. elim H3. change id with (fst (id, sz0)). apply in_map; auto.\n    omega.\n    eapply SEP2. apply in_cons; eauto. eauto.\n    rewrite D in H5; eauto. eauto. auto.\n    intros. rewrite PTree.gso. eapply UNBOUND; eauto with coqlib.\n    red; intros; subst id0. elim H3. change id with (fst (id, sz0)). apply in_map; auto.\n    eapply match_callstack_alloc_left; eauto.\n    rewrite cenv_remove_gso; auto.\n    apply UNBOUND with sz; auto with coqlib.\n  intros. destruct H1 as [f3 [HF1 [HF2 [Hf3 [HF4 [HF5 HF6]]]]]].\n    exists f3. split; trivial.\n    split; trivial.\n    split. eapply inject_incr_trans; eassumption.\n    split. intros.\n        rewrite HF4.\n         apply D.\n           intros N; subst.\n               eapply (Mem.fresh_block_alloc _ _ _ _ _ H H1).\n           apply (Mem.valid_block_alloc _ _ _ _ _ H _ H1).\n    split; intros.\n       destruct (eq_block b b1); subst.\n       rewrite (Hf3 _ _ _ C) in H2. inv H2. trivial.\n       specialize (D _ n).\n         rewrite <- D in H1. apply (HF5 _ _ _ H1 H2).\n    intros b; intros.\n      destruct (H2 _ _ _ H5 H6).\n      split; trivial.\n      intros N. apply H7; clear H7.\n      apply (Mem.valid_block_alloc _ _ _ _ _ H) in N.\n      eapply alloc_variables_forward. eassumption. apply N.\nQed.\n\nLemma MS_match_callstack_alloc_variables_aux:\n  forall tm1 sp tm2 m1 vars e m2 cenv f1 cs fn le te,\n  Mem.alloc tm1 0 (fn_stackspace fn) = (tm2, sp) ->\n  fn_stackspace fn <= Int.max_unsigned ->\n  alloc_variables empty_env m1 vars e m2 ->\n  list_norepet (map fst vars) ->\n  cenv_compat cenv vars (fn_stackspace fn) ->\n  cenv_separated cenv vars ->\n  (forall id ofs, cenv!id = Some ofs -> In id (map fst vars)) ->\n  Mem.inject f1 m1 tm1 ->\n  match_callstack prog f1 m1 tm1 cs (Mem.nextblock m1) (Mem.nextblock tm1) ->\n  match_temps f1 le te ->\n  exists f2,\n    match_callstack prog f2 m2 tm2 (Frame cenv fn e le te sp (Mem.nextblock m1) (Mem.nextblock m2) :: cs)\n                    (Mem.nextblock m2) (Mem.nextblock tm2)\n  /\\ Mem.inject f2 m2 tm2\n  /\\ (*LENB: THIS IS NEW*) inject_incr f1 f2\n(****************The following three conditions are new******************)\n(* In the third clause, we now stepfrom  m' to m, and also from f' to f and from tm' to tm******************)\n  /\\ (forall b, Mem.valid_block m1 b -> f2 b = f1 b)\n  /\\ (forall b b' d', f1 b = None -> f2 b = Some (b',d') -> b' = sp)\n  /\\ forall j',  inject_incr f2 j' -> Events.inject_separated f2 j' m2 tm2 ->\n          Events.inject_separated f2 j' m1 tm1.\nProof. clear core_data.\n  intros.\n  unfold build_compilenv in H.\nassert (AR: exists f',\n   match_callstack prog f' m2 tm2\n                     (Frame cenv fn e le te sp (Mem.nextblock m1) (Mem.nextblock m2) :: cs)\n                     (Mem.nextblock m2) (Mem.nextblock tm2)\n\n  /\\ Mem.inject f' m2 tm2\n  /\\ inject_incr f1 f'\n  /\\ (forall b, Mem.valid_block m1 b -> f' b = f1 b)\n  /\\ (forall b b' d', f1 b = None -> f' b = Some (b',d') -> b' = sp)\n  /\\ forall j',  inject_incr f' j' -> Events.inject_separated f' j' m2 tm2 ->\n                  Events.inject_separated f' j' m1 tm2).\n\n  eapply MS_match_callstack_alloc_variables_rec; eauto with mem.\n  (*instantiate (1 := f1).*) red; intros. eelim Mem.fresh_block_alloc; eauto.\n  eapply Mem.valid_block_inject_2; eauto.\n  intros. apply PTree.gempty.\n  eapply match_callstack_alloc_right; eauto.\n  intros. destruct (In_dec peq id (map fst vars)).\n  apply cenv_remove_gss; auto.\n  rewrite cenv_remove_gso; auto.\n  destruct (cenv!id) as [ofs|] eqn:?; auto. elim n; eauto.\n  eapply Mem.alloc_right_inject; eauto.\n\ndestruct AR as  [f' [INC [INJ [MC [VB1 [SP SEP]]]]]].\nexists f' ; intuition.\n  intros b; intros.\n  remember (f' b) as z; destruct z; apply eq_sym in Heqz.\n  (*Some p*) destruct p.\n            assert (j' b = Some (b0,z)). apply (H9 _ _ _ Heqz). inv H11.\n   (*None*) assert (HH:= SEP _ H9 H10).\n                     destruct (HH _ _ _ Heqz H12).\n                     split; trivial.\n                     intros N. apply H14. eapply Mem.valid_block_alloc; eauto.\nQed.\n\nLemma MS_match_callstack_alloc_variables:\n  forall tm1 sp tm2 m1 vars e m2 cenv f1 cs fn le te,\n  Mem.alloc tm1 0 (fn_stackspace fn) = (tm2, sp) ->\n  fn_stackspace fn <= Int.max_unsigned ->\n  alloc_variables empty_env m1 vars e m2 ->\n  list_norepet (map fst vars) ->\n  cenv_compat cenv vars (fn_stackspace fn) ->\n  cenv_separated cenv vars ->\n  (forall id ofs, cenv!id = Some ofs -> In id (map fst vars)) ->\n  Mem.inject f1 m1 tm1 ->\n  match_callstack prog f1 m1 tm1 cs (Mem.nextblock m1) (Mem.nextblock tm1) ->\n  match_temps f1 le te ->\n  exists f2,\n    match_callstack prog f2 m2 tm2 (Frame cenv fn e le te sp (Mem.nextblock m1) (Mem.nextblock m2) :: cs)\n                    (Mem.nextblock m2) (Mem.nextblock tm2)\n  /\\ Mem.inject f2 m2 tm2\n  /\\ (*LENB: THIS IS NEW*) inject_incr f1 f2\n  /\\ (*LENB this clause in new in coop-sim proof*) inject_separated f1 f2 m1 tm1.\nProof.\n  intros.\n  destruct (MS_match_callstack_alloc_variables_aux\n     _ _ _ _ _ _ _ _ _ _ _ _ _ H H0 H1 H2 H3 H4 H5 H6 H7 H8)\n     as [f2 [MCS2 [INJ2 [INC [HH1 [HH2 HH3]]]]]].\n  exists f2.\n  split; trivial.\n  split; trivial.\n  split; trivial.\n  intros b; intros.\n  specialize (HH2 _ _ _ H9 H10); subst.\n  split. intros N. rewrite (HH1 _ N) in H10.\n         rewrite H10 in H9; discriminate.\n  eapply (Mem.fresh_block_alloc _ _ _ _ _ H).\nQed.\n\n(***** All the additional conditions in the above auxiliary lemmas were needed for proving\n the condition Events.inject_separated j j' m tm in his lemma; otherwise, the claim is as before,\n  just updated by replacing star step by corestep_star, as ususal*)\n\nTheorem MS_match_callstack_function_entry:\n  forall fn cenv tf m e m' tm tm' sp f cs args targs le,\n  build_compilenv fn = (cenv, tf.(fn_stackspace)) ->\n  tf.(fn_stackspace) <= Int.max_unsigned ->\n  list_norepet (map fst (Csharpminor.fn_vars fn)) ->\n  list_norepet (Csharpminor.fn_params fn) ->\n  list_disjoint (Csharpminor.fn_params fn) (Csharpminor.fn_temps fn) ->\n  alloc_variables Csharpminor.empty_env m (Csharpminor.fn_vars fn) e m' ->\n  bind_parameters (Csharpminor.fn_params fn) args (create_undef_temps fn.(fn_temps)) = Some le ->\n  val_list_inject f args targs ->\n  Mem.alloc tm 0 tf.(fn_stackspace) = (tm', sp) ->\n  match_callstack prog f m tm cs (Mem.nextblock m) (Mem.nextblock tm) ->\n  Mem.inject f m tm ->\n  let te := set_locals (Csharpminor.fn_temps fn) (set_params targs (Csharpminor.fn_params fn)) in\n  exists f',\n     match_callstack prog f' m' tm'\n                     (Frame cenv tf e le te sp (Mem.nextblock m) (Mem.nextblock m') :: cs)\n                     (Mem.nextblock m') (Mem.nextblock tm')\n  /\\ Mem.inject f' m' tm'\n  /\\ (*LENB: this clause is new in Restructured Proof*) inject_incr f f'\n  /\\ (*LENB this clause in new in coop-sim proof*) inject_separated f f' m tm.\nProof.\n  intros.\n  exploit build_compilenv_sound; eauto. intros [C1 C2].\n  eapply MS_match_callstack_alloc_variables; eauto.\n  intros. eapply build_compilenv_domain; eauto.\n  eapply bind_parameters_agree; eauto.\nQed.\n\nLemma MS_step_case_InternalCall:\nforall cenv  f j m tm e cs k tk vargs targs x m1 lenv\n(Param1: list_norepet (map fst (Csharpminor.fn_vars f)))\n(Param2 : list_norepet (Csharpminor.fn_params f))\n(Param3 : list_disjoint (Csharpminor.fn_params f) (fn_temps f))\n(AlocVars : alloc_variables empty_env m (Csharpminor.fn_vars f) e m1)\n(BindParams: bind_parameters (Csharpminor.fn_params f) vargs\n       (create_undef_temps (fn_temps f)) = Some lenv)\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm cs (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont k tk cenv nil cs)\n(ISCC : Csharpminor.is_call_cont k)\n(ARGSINJ : val_list_inject j vargs targs)\n(EQ : transl_function f = OK x)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists (c2' : CMin_core) (m2' : mem),\n  corestep_plus CMin_core_sem tge (CMin_Callstate (AST.Internal x) targs tk) tm c2' m2'\n /\\ exists (j' : meminj),\n  inject_incr j j' /\\\n  inject_separated j j' m tm /\\\n  match_cores (CSharpMin_State f (Csharpminor.fn_body f) k e lenv) j'\n    (CSharpMin_State f (Csharpminor.fn_body f) k e lenv) m1 c2' m2'.\nProof. intros.\n  generalize EQ; clear EQ; unfold transl_function.\n  caseEq (build_compilenv f). intros ce sz BC.\n  destruct (zle sz Int.max_unsigned).\n  Focus 2. intros. exfalso. clear core_data.  congruence. (*core data versus congruence bug; Xavier's proof has\n             destruct (zle sz Int.max_unsigned); try congruence here....*)\n  intro TRBODY.\n  generalize TRBODY; intro TMP. monadInv TMP.\n  set (tf := mkfunction (Csharpminor.fn_sig f)\n                        (Csharpminor.fn_params f)\n                        (Csharpminor.fn_temps f)\n                        sz\n                        x0) in *.\n  caseEq (Mem.alloc tm 0 (fn_stackspace tf)). intros tm' sp ALLOC'.\n  exploit MS_match_callstack_function_entry; eauto. simpl; eauto. simpl; auto.\n  intros [j' [MCS2 [MINJ2 [IINCR SEP]]]].\n  exists (CMin_State tf x0 tk (Vptr sp Int.zero)\n     (set_locals (fn_temps f) (set_params targs (Csharpminor.fn_params f)))).\n  exists tm'.\n  split.\n    eapply corestep_plus_one. simpl.\n    econstructor.\n    constructor. assumption. reflexivity.\n  exists j'. split. assumption.\n  split. assumption.\n  econstructor. eexact TRBODY. eauto. eexact MINJ2.\n  eexact MCS2.\n  inv MK; simpl in ISCC; contradiction || econstructor; eauto.\nsolve [eapply meminj_preserves_incr_sep; eassumption].\nQed.\n\n(******************End of updated section for internal call rule*****************************)\n(************************************************************************************)\n\nLemma MS_step_case_Return:\nforall j m tm cs f e lenv k tk cenv v tv optid\n(MINJ : Mem.inject j m tm)\n(MCS : match_callstack prog j m tm cs (Mem.nextblock m) (Mem.nextblock tm))\n(MK : match_cont (Csharpminor.Kcall optid f e lenv k) tk cenv nil cs)\n(RESINJ : val_inject j v tv)\n(*NEW:*) (PG: meminj_preserves_globals ge j),\nexists c2' : CMin_core,\n  exists m2' : mem,\n       corestep_plus CMin_core_sem tge (CMin_Returnstate tv tk) tm c2' m2'  /\\\n       match_cores  (CSharpMin_State f Csharpminor.Sskip k e (set_optvar optid v lenv)) j\n             (CSharpMin_State f Csharpminor.Sskip k e (set_optvar optid v lenv)) m c2' m2' .\nProof. intros.\n  inv MK. simpl.\n  eexists; eexists; split.\n       eapply corestep_plus_one. eapply CompCertStep_CMin_corestep'. econstructor; eauto. reflexivity.\n  simpl.\n  unfold set_optvar. destruct optid; simpl option_map; econstructor; eauto.\n         eapply match_callstack_set_temp; eauto.\nQed.\n\nLemma MS_step: forall (c1 : core_data) (m1 : mem) (c1' : core_data) (m1' : mem),\ncorestep CSharpMin_core_sem ge c1 m1 c1' m1' ->\nforall (c2 : CMin_core) (m2 : mem) (j : meminj),\nmatch_cores c1 j c1 m1 c2 m2 ->\n(exists c2' : CMin_core,\n   exists m2' : mem,\n     exists j' : meminj,\n       inject_incr j j' /\\\n       Events.inject_separated j j' m1 m2 /\\\n       corestep_plus CMin_core_sem tge c2 m2 c2' m2' /\\\n       match_cores c1' j' c1' m1' c2' m2') \\/\n(MC_measure c1' < MC_measure c1)%nat /\\ match_cores c1' j c1' m1' c2 m2.\nProof.\n  intros. unfold core_data in *.\n   destruct (CSharpMin_corestep_2_CompCertStep _ _ _ _ _ H) as [t Ht]. simpl in *.\n  apply CSharpMin_corestep_not_at_external in H.\n   assert (PG:= match_cores_genvs _ _ _ _ _ _ H0).\n   apply MC_MSI in H0. rename H0 into MSTATE.\n   inv Ht; simpl in *.\n  (*skip seq*)\n      destruct c1; simpl in *; try inv H1.\n      destruct c1'; simpl in *; try inv H3.\n      inv MSTATE; simpl in *.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H8.\n      destruct (MS_step_case_SkipSeq _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        TRF MINJ MK MCS PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*skip Block*)\n      destruct c1; simpl in *; try inv H1.\n      destruct c1'; simpl in *; try inv H3.\n      inv MSTATE; simpl in *.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H8.\n      destruct (MS_step_case_SkipBlock _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        TRF MINJ MK MCS PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*skip Call*)\n      destruct c1; simpl in *; try inv H0.\n      destruct c1'; simpl in *; try inv H1.\n      inv MSTATE; simpl in *.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H10.\n      destruct (MS_step_case_SkipCall  _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        H2 H4 TRF MINJ MK MCS PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n   (*assign*)\n      destruct c1; simpl in *; try inv H0.\n      destruct c1'; simpl in *; try inv H1.\n      inv MSTATE; simpl in *.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H9.\n      rename  m1' into m'. rename m' into m.\n      rename m2 into tm. rename k0 into tk.\n      rename f0 into tfn. rename e0 into te.\n      rename le0 into lenv.\n      destruct (MS_step_case_Assign  _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        id H3 TRF MINJ MK MCS EQ PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n   (*set case has disappeared*)\n   (*store*)\n      destruct c1; simpl in *; try inv H0.\n      destruct c1'; simpl in *; try inv H1.\n      inv MSTATE; simpl in *.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H11.\n      rename f0 into tfn. rename m1 into m. rename m2  into tm.\n      rename e0 into te. rename k0 into tk. rename  m1' into m'.\n      destruct (MS_step_case_Store _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        H5 H2 H3 TRF MINJ MCS MK EQ EQ1 PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n   (*call*)\n      destruct c1; simpl in *; try inv H0.\n      destruct c1'; simpl in *; try inv H1.\n      inv MSTATE; simpl in *.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H11.\n      rename f into fd. rename f0 into f. rename f1 into tfn.\n      rename m1' into m. rename m2  into tm. rename e into te.\n      rename e0 into e.  rename k0 into tk. rename  le0 into le.\n      destruct (MS_step_case_Call _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        optid _ _ H2 H3 H4 TRF MINJ MCS MK EQ EQ1 PG) as [c2' [m2' [cstepPlusMS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*builtin*)\n      destruct c1; simpl in *; try inv H0.\n      destruct c1'; simpl in *; try inv H1.\n      inv MSTATE; simpl in *.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H10.\n      rename f0 into tfn.\n      rename m1 into m. rename m2  into tm. rename e into te.\n      rename e0 into e.  rename k0 into tk. rename  le0 into le.  rename m1' into m'.\n      destruct (MS_step_case_Builtin _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ optid\n        _ _ _ _ H2 H4 TRF MINJ MCS MK EQ PG)\n        as [c2' [m2' [cstepPlus [j' [InjIncr [InjSep MS]]]]]].\n      left. exists c2'. exists m2'.  exists j'. auto.\n  (* seq *)\n      destruct c1; simpl in *; try inv H1.\n      destruct c1'; simpl in *; try inv H3.\n     rename k0 into k.\n      inv MSTATE.\n      (*Case 1*)\n         monadInv TR. left.\n         destruct c2; simpl in *; try inv H8.\n         rename f0 into tfn. rename e0 into te. rename k0 into tk.\n         exists  (CMin_State tfn x (Kseq x0 tk) (Vptr sp Int.zero) te). exists m2.\n         exists j.\n                split. apply inject_incr_refl.\n                split. apply inject_separated_same_meminj.\n                split; simpl.\n                    eapply corestep_plus_one.\n                    eapply CompCertStep_CMin_corestep.\n                    econstructor; eauto. reflexivity.\n                econstructor; eauto.\n                          econstructor; eauto.\n      (* seq 2 *)\n         destruct c2; simpl in *; try inv H9.\n         right. split. omega.\n                   econstructor; eauto.\n(* ifthenelse *)\n      destruct c1; simpl in *; try inv H0.\n      destruct c1'; simpl in *; try inv H1.\n      inv MSTATE.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H10.\n         rename f0 into tfn. rename e0 into te. rename k0 into tk.\n      rename m1' into m. rename m2  into tm.\n      destruct (MS_step_case_Ite _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        H2 H4 TRF MINJ MCS MK EQ EQ1 EQ0 PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*loop*)\n      destruct c1; simpl in *; try inv H1.\n      destruct c1'; simpl in *; try inv H3.\n      inv MSTATE.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H8.\n         rename f0 into tfn. rename e0 into te. rename k0 into tk.\n      rename m1' into m. rename m2  into tm.\n      destruct (MS_step_case_Loop _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        TRF MINJ MCS MK EQ PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*block*)\n      destruct c1; simpl in *; try inv H1.\n      destruct c1'; simpl in *; try inv H3.\n      inv MSTATE.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H8.\n         rename f0 into tfn. rename e0 into te. rename k0 into tk.\n      rename m1' into m. rename m2  into tm.  rename s0 into s.\n      destruct (MS_step_case_Block _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        TRF MINJ MCS MK EQ PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*exit seq*)\n      destruct c1; simpl in *; try inv H1.\n      destruct c1'; simpl in *; try inv H3.\n      inv MSTATE.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H8.\n         rename f0 into tfn. rename e0 into te. rename k0 into tk.\n      rename m1' into m. rename m2  into tm.\n      destruct (MS_step_case_ExitSeq _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ n _\n        TRF MINJ MCS MK PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*exit block 0*)\n      destruct c1; simpl in *; try inv H1.\n      destruct c1'; simpl in *; try inv H3.\n      inv MSTATE.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H8.\n         rename f0 into tfn. rename e0 into te. rename k0 into tk.\n      rename m1' into m. rename m2  into tm.\n      destruct (MS_step_case_ExitBlockZero _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        TRF MINJ MCS MK PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*exit block n+1*)\n      destruct c1; simpl in *; try inv H1.\n      destruct c1'; simpl in *; try inv H3.\n      inv MSTATE.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H8.\n         rename f0 into tfn. rename e0 into te. rename k0 into tk.\n      rename m1' into m. rename m2  into tm.\n      destruct (MS_step_case_ExitBlockNonzero _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        n TRF MINJ MCS MK PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*switch*)\n      destruct c1; simpl in *; try inv H0.\n      destruct c1'; simpl in *; try inv H1.\n      inv MSTATE.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H9.\n         rename f0 into tfn.  rename e0 into te.\n         rename k0 into tk. rename m1' into m. rename m2  into tm.  rename s into ts.\n      destruct (MS_step_case_Switch _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        H3 TRF MINJ MCS MK EQ EQ0 PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*return none*)\n      destruct c1; simpl in *; try inv H0.\n      destruct c1'; simpl in *; try inv H1.\n      inv MSTATE.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H9.\n       rename f into tfn.  rename f0 into f. rename e into te. rename e0 into e.\n         rename k0 into tk. rename m1 into m. rename m2  into tm.\n         rename m1'  into m'.  rename le0 into le.\n      destruct (MS_step_case_ReturnNone _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        H3 TRF MINJ MCS MK PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*return some*)\n      destruct c1; simpl in *; try inv H0.\n      destruct c1'; simpl in *; try inv H1.\n      inv MSTATE.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H10.\n       rename f into tfn.  rename f0 into f. rename e into te.\n         rename e0 into e. rename k into tk.\n         rename k0 into k. rename m1 into m. rename m2  into tm.\n         rename m1'  into m'.  rename le0 into le. rename v0 into v.\n      destruct (MS_step_case_ReturnSome _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        H2 H4 TRF MINJ MCS MK EQ PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*label*)\n      destruct c1; simpl in *; try inv H1.\n      destruct c1'; simpl in *; try inv H3.\n      inv MSTATE.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H8.\n       rename f0 into tfn. rename e0 into te.\n         rename k0 into tk. rename m1' into m. rename m2  into tm. rename s0 into s.\n      destruct (MS_step_case_Label _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        lbl _ _ TRF MINJ MCS MK EQ PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n  (*goto*)\n      destruct c1; simpl in *; try inv H0.\n      destruct c1'; simpl in *; try inv H1.\n      inv MSTATE.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H9.\n       rename f0 into tfn. rename e0 into te.\n         rename k1 into tk. rename s into s'.  rename k into k'.\n         rename k0 into k. rename m1' into m. rename m2  into tm.\n      destruct (MS_step_case_Goto _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        H3 TRF MINJ MCS MK PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\n(* internal call *)\n      destruct c1; simpl in *; try inv H0.\n      destruct c1'; simpl in *; try inv H1.\n      inv MSTATE.\n      monadInv TR.\n      destruct c2; simpl in *; try inv H11.\n      rename m1 into m. rename m2 into tm.\n      rename f0 into f. rename e0 into e.\n      rename m1' into m1. rename args into vargs.\n      rename k0 into tk. rename le0 into lenv.\n      rename args0 into targs.\n      destruct (MS_step_case_InternalCall _ _ _ _ _ _ _ _ _ _ _ _ _ _\n        H2 H3 H4 H5 H7 MINJ MCS MK ISCC ARGSINJ EQ PG)\n        as [c2' [m2' [cstepPlus [j' [InjIncr [InjSep MS]]]]]].\n      left. exists c2'. exists m2'. exists j'. auto.\n(* external call *)\n      destruct c1; simpl in *; try inv H0. inv H.\n   (*nothing to show here - cf corestep not at external *)\n\n(* return *)\n      destruct c1; simpl in *; try inv H1.\n      destruct c1'; simpl in *; try inv H3.\n      inv MSTATE.\n      destruct c2; simpl in *; try inv H5.\n      rename m1' into m. rename m2 into tm. rename f0 into f.\n      rename e0 into e. rename k into tk. rename k0 into k.\n      rename v into tv. rename v0 into v.\n      destruct (MS_step_case_Return _ _ _ _ _ _ _ _ _ _ _\n        tv optid MINJ MCS MK RESINJ PG) as [c2' [m2' [cstepPlus MS]]].\n      left. exists c2'. exists m2'. exists j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      auto.\nQed.\n\nRequire Import sepcomp.forward_simulations.\n\nRequire Import sepcomp.forward_simulations_lemmas.\n\n(*program structure not yet updated to module*)\nTheorem transl_program_correct:\n  forall (R: list_norepet (map fst (prog_defs prog)))\n         entrypoints\n         (entry_points_ok :\n            forall v1 v2 sig,\n              In (v1, v2, sig) entrypoints ->\n              exists b f1 f2,\n                v1 = Vptr b Int.zero\n                /\\ v2 = Vptr b Int.zero\n                /\\ Genv.find_funct_ptr ge b = Some f1\n                /\\ Genv.find_funct_ptr tge b = Some f2)\n         (init_mem: exists m0, Genv.init_mem prog = Some m0),\n  Forward_simulation_inj.Forward_simulation_inject\n       CSharpMin_core_sem\n       CMin_core_sem ge tge entrypoints.\nProof.\nintros.\n eapply inj_simulation_star with\n  (match_states:=match_cores)(measure:=MC_measure).\n (*genvs_dom_eq*)\n    unfold genvs_domain_eq, genv2blocks.\n    simpl; split; intros.\n     split; intros; destruct H as [id Hid].\n      rewrite <- (symbols_preserved _ _ TRANSL) in Hid.\n      exists id; assumption.\n     rewrite (symbols_preserved _ _ TRANSL) in Hid.\n      exists id; assumption.\n     split; intros; destruct H as [id Hid].\n      rewrite <- (varinfo_preserved _ _ TRANSL) in Hid.\n      exists id; assumption.\n     rewrite (varinfo_preserved _ _ TRANSL) in Hid.\n      exists id; assumption.\n  apply match_cores_valid.\n (*preserves_globals*) apply match_cores_genvs.\n (*init_cores*)\n    intros.\n    eapply (init_cores _ _ _ entrypoints); eauto.\n    destruct init_mem as [m0 INIT].\n    exists m0; split; auto.\n    unfold meminj_preserves_globals in H3.\n    destruct H3 as [A [B C]].\n\n    assert (P: forall p q, {Ple p q} + {Plt q p}).\n      intros p q.\n      case_eq (Pos.leb p q).\n      intros TRUE.\n      apply Pos.leb_le in TRUE.\n      left; auto.\n      intros FALSE.\n      apply Pos.leb_gt in FALSE.\n      right; auto.\n\n    cut (forall b, Plt b (Mem.nextblock m0) ->\n           exists id, Genv.find_symbol ge id = Some b). intro D.\n\n    split.\n    destruct (P (Mem.nextblock m0) (Mem.nextblock m1)); auto.\n    exfalso.\n    destruct (D _ p).\n    apply A in H3.\n    assert (Mem.valid_block m1 (Mem.nextblock m1)).\n      eapply Mem.valid_block_inject_1; eauto.\n    clear - H4; unfold Mem.valid_block in H4.\n    xomega.\n\n    destruct (P (Mem.nextblock m0) (Mem.nextblock m2)); auto.\n    exfalso.\n    destruct (D _ p).\n    apply A in H3.\n    assert (Mem.valid_block m2 (Mem.nextblock m2)).\n      eapply Mem.valid_block_inject_2; eauto.\n    clear - H4; unfold Mem.valid_block in H4.\n    xomega.\n\n    intros b LT.\n    unfold ge.\n    apply valid_init_is_global with (b := b) in INIT.\n    eapply INIT; auto.\n    apply R.\n    apply LT.\n\n  (*halted*)\n  { intros.\n    eapply MC_safely_halted in H; eauto.\n    destruct H as [v2 [A [B C]]].\n    solve[exists v2; split; auto]. }\n  (*at_external*)\n  { intros.\n    destruct (MC_at_external _ _ _ _ _ _ _ _ _ H H0)\n           as [Inc [Presv [vals2 [ValsInj AtExt2]]]].\n    split; trivial.\n    exists vals2.\n    split; trivial. }\n (*after_external*)\n {  intros.\n    assert (PG: meminj_preserves_globals ge j).\n      destruct H; subst.\n      apply (match_cores_genvs _ _ _ _ _ _ H9).\n    destruct (MC_after_external _ _ _ _ _ _ _ _ _ _ _ _ _ _ H H0\n             PG H1 H2 H3 H4 H5 H6 H7 H8)\n           as [dd [core [dd' [afterExtA [afterExtB [ MC X]]]]]].\n     subst. eexists; eexists. eexists.\n        split. eassumption.\n        split. eassumption.\n        split. reflexivity. eassumption. }\n  (*core_diagram*)\n  { intros. destruct (MS_step _ _ _ _ H _ _ _ H0).\n    destruct H1 as [c2' [m2' [j' [INC [Sep [CSP MC]]]]]].\n      exists c2', m2', j'.\n       split; trivial.\n       split; trivial.\n       split; trivial.\n       left; trivial.\n    destruct H1.\n      exists c2, m2, j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      split; trivial.\n      right. split; trivial.\n      apply corestep_star_zero. }\nQed.\n\nLemma MS_step_coopsem: forall (c1 : core_data) (m1 : mem) (c1' : core_data) (m1' : mem),\ncorestep csharpmin_coop_sem ge c1 m1 c1' m1' ->\nforall (c2 : CMin_core) (m2 : mem) (j : meminj),\nmatch_cores c1 j c1 m1 c2 m2 ->\n(exists c2' : CMin_core,\n   exists m2' : mem,\n     exists j' : meminj,\n       inject_incr j j' /\\\n       Events.inject_separated j j' m1 m2 /\\\n       corestep_plus cmin_coop_sem tge c2 m2 c2' m2' /\\\n       match_cores c1' j' c1' m1' c2' m2') \\/\n(MC_measure c1' < MC_measure c1)%nat /\\ match_cores c1' j c1' m1' c2 m2.\nProof. intros.\n  eapply MS_step; eauto.\nQed.\n\nTheorem transl_program_correct_coopsem:\n  forall (R: list_norepet (map fst (prog_defs prog)))\n         entrypoints\n         (entry_points_ok :\n            forall v1 v2 sig,\n              In (v1, v2, sig) entrypoints ->\n              exists b f1 f2,\n                v1 = Vptr b Int.zero\n                /\\ v2 = Vptr b Int.zero\n                /\\ Genv.find_funct_ptr ge b = Some f1\n                /\\ Genv.find_funct_ptr tge b = Some f2)\n         (init_mem: exists m0, Genv.init_mem prog = Some m0),\n  Forward_simulation_inj.Forward_simulation_inject csharpmin_coop_sem\n   cmin_coop_sem ge tge entrypoints.\nProof.\nintros.\n eapply inj_simulation_star with\n  (match_states:=match_cores)(measure:=MC_measure).\n (*genvs_dom_eq*)\n    unfold genvs_domain_eq, genv2blocks.\n    simpl; split; intros.\n     split; intros; destruct H as [id Hid].\n      rewrite <- (symbols_preserved _ _ TRANSL) in Hid.\n      exists id; assumption.\n     rewrite (symbols_preserved _ _ TRANSL) in Hid.\n      exists id; assumption.\n     split; intros; destruct H as [id Hid].\n      rewrite <- (varinfo_preserved _ _ TRANSL) in Hid.\n      exists id; assumption.\n     rewrite (varinfo_preserved _ _ TRANSL) in Hid.\n      exists id; assumption.\n  apply match_cores_valid.\n (*preserves_globals*) apply match_cores_genvs.\n (*init_cores*)\n    intros.\n    eapply (init_cores _ _ _ entrypoints); eauto.\n    destruct init_mem as [m0 INIT].\n    exists m0; split; auto.\n    unfold meminj_preserves_globals in H3.\n    destruct H3 as [A [B C]].\n\n    assert (P: forall p q, {Ple p q} + {Plt q p}).\n      intros p q.\n      case_eq (Pos.leb p q).\n      intros TRUE.\n      apply Pos.leb_le in TRUE.\n      left; auto.\n      intros FALSE.\n      apply Pos.leb_gt in FALSE.\n      right; auto.\n\n    cut (forall b, Plt b (Mem.nextblock m0) ->\n           exists id, Genv.find_symbol ge id = Some b). intro D.\n\n    split.\n    destruct (P (Mem.nextblock m0) (Mem.nextblock m1)); auto.\n    exfalso.\n    destruct (D _ p).\n    apply A in H3.\n    assert (Mem.valid_block m1 (Mem.nextblock m1)).\n      eapply Mem.valid_block_inject_1; eauto.\n    clear - H4; unfold Mem.valid_block in H4.\n    xomega.\n\n    destruct (P (Mem.nextblock m0) (Mem.nextblock m2)); auto.\n    exfalso.\n    destruct (D _ p).\n    apply A in H3.\n    assert (Mem.valid_block m2 (Mem.nextblock m2)).\n      eapply Mem.valid_block_inject_2; eauto.\n    clear - H4; unfold Mem.valid_block in H4.\n    xomega.\n\n    intros b LT.\n    unfold ge.\n    apply valid_init_is_global with (b := b) in INIT.\n    eapply INIT; auto.\n    apply R.\n    apply LT.\n  (*halted*)\n  { intros.\n    eapply MC_safely_halted in H; eauto.\n    destruct H as [v2 [A [B C]]].\n    solve[exists v2; split; auto]. }\n  (*at_external*)\n  { intros.\n    destruct (MC_at_external _ _ _ _ _ _ _ _ _ H H0)\n           as [Inc [Presv [vals2 [ValsInj AtExt2]]]].\n    split; trivial.\n    exists vals2.\n    split; trivial. }\n (*after_external*)\n {  intros.\n    assert (PG: meminj_preserves_globals ge j).\n      destruct H; subst.\n      apply (match_cores_genvs _ _ _ _ _ _ H9).\n    destruct (MC_after_external _ _ _ _ _ _ _ _ _ _ _ _ _ _ H H0\n             PG H1 H2 H3 H4 H5 H6 H7 H8)\n           as [dd [core [dd' [afterExtA [afterExtB [ MC X]]]]]].\n     subst. eexists; eexists. eexists.\n        split. eassumption.\n        split. eassumption.\n        split. reflexivity. eassumption. }\n  (*core_diagram*)\n  { intros. destruct (MS_step_coopsem _ _ _ _ H _ _ _ H0).\n    destruct H1 as [c2' [m2' [j' [INC [Sep [CSP MC]]]]]].\n      exists c2', m2', j'.\n       split; trivial.\n       split; trivial.\n       split; trivial.\n       left; trivial.\n    destruct H1.\n      exists c2, m2, j.\n      split. apply inject_incr_refl.\n      split. apply inject_separated_same_meminj.\n      split; trivial.\n      right. split; trivial.\n      apply corestep_star_zero. }\nQed.\n\nEnd TRANSLATION.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/sepcomp/submit/CminorgenproofSIM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.24352584048754916}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect.\nRequire Import ssrbool.\nRequire Import funs.\nRequire Import dataset.\nRequire Import ssrnat.\nRequire Import seq.\nRequire Import paths.\nRequire Import finset.\nRequire Import connect.\nRequire Import hypermap.\nRequire Import geometry.\nRequire Import coloring.\nRequire Import birkhoff.\nRequire Import znat.\nRequire Import part.\nRequire Import discharge.\nRequire Import hubcap.\nRequire Import configurations.\nRequire Import present.\nRequire Import present5.\nRequire Import present6.\nRequire Import present7.\nRequire Import present8.\nRequire Import present9.\nRequire Import present10.\nRequire Import present11.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLemma unavoidability : reducibility -> forall g, ~ minimal_counter_example g.\nProof.\nmove=> Hred g Hg; case: (posz_dscore Hg) => x Hx.\nhave Hgx: valid_hub x by split.\nhave := (Hg : pentagonal g) x; rewrite 7!leq_eqVlt leqNgt.\nrewrite exclude5 ?exclude6 ?exclude7 ?exclude8 ?exclude9 ?exclude10 ?exclude11 //.\ncase/idP; apply: (@dscore_cap1 g 5) => {x n Hn Hx Hgx}// y.\npose x := inv_face2 y; pose n := arity x.\nhave ->: y = face (face x) by rewrite /x /inv_face2 !Enode.\nrewrite (dbound1_eq (DruleFork (DruleForkValues n))) // leqz_nat.\ncase Hn: (negb (Pr58 n)); first by rewrite source_drules_range //.\nhave Hrp := no_fit_the_redpart Hred Hg.\napply: (check_dbound1P (Hrp the_quiz_tree) _ (exact_fitp_pcons_ Hg x)) => //.\nrewrite -/n; move: n Hn; do 9 case=> //.\nQed.\n\nSet Strict Implicit.\nUnset Implicit Arguments.", "meta": {"author": "tangentforks", "repo": "FourColorTheorem", "sha": "eb30720f9e773fdcbf13dc6c61fdb245587cf401", "save_path": "github-repos/coq/tangentforks-FourColorTheorem", "path": "github-repos/coq/tangentforks-FourColorTheorem/FourColorTheorem-eb30720f9e773fdcbf13dc6c61fdb245587cf401/unavoidability.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.24352582179432763}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Import QArith_base.\nRequire Import tactics2.\nRequire Import list_util.\nRequire Import Eqdep_dec.\n\n\nRequire Import Node.\nRequire Import Msg.\nRequire Import Crypto.\nRequire Import EventOrdering.\nRequire Import Process.\nRequire Import PairState.\n\n\nSection Parallel.\n\nContext { pn     : @Node }.\nContext { pm     : @Msg }.\nContext { pk     : @Key }.\n\n(* transition form SX to sx *)\nDefinition parallel_upd {SX SY I O : Type}\n           (X : Update SX I (list O))\n           (Y : Update SY I (list O)) : Update (pstate SX SY) I (list O) :=\n  fun state i =>\n    match state with\n    | pstate_two sx sy =>\n      let (sx', outx) := X sx i in\n      let (sy', outy) := Y sy i in\n      (opt_states2pstate sx' sy', outx ++ outy)\n    | pstate_left sx =>\n      let (sx', outx) := X sx i in\n      (option_map (fun x => pstate_left x) sx', outx)\n    | pstate_right sy =>\n      let (sy', outy) := Y sy i in\n      (option_map (fun x => pstate_right x) sy', outy)\n    end.\n\nDefinition parallel {SX SY I O : Type}\n           (X : StateMachine SX I (list O))\n           (Y : StateMachine SY I (list O))\n  : StateMachine (pstate SX SY) I (list O) :=\n  mkSM (parallel_upd (sm_update X) (sm_update Y))\n       (pstate_two (sm_state X) (sm_state Y)).\n\nDefinition nparallel {SX SY I O : Type}\n           (X : NStateMachine SX I (list O))\n           (Y : NStateMachine SY I (list O))\n  : NStateMachine (pstate SX SY) I (list O) :=\n  fun slf => parallel (X slf) (Y slf).\n\nNotation \"a [||] b\" := (nparallel a b) (at level 100).\n\nLemma state_sm_on_event_parallel_some_pstate_two_implies :\n  forall {SX SY O}\n         (X  : StateMachine SX msg (list O))\n         (Y  : StateMachine SY msg (list O))\n         (eo : EventOrdering)\n         (e  : Event)\n         (l  : SX)\n         (r  : SY),\n    state_sm_on_event (parallel X Y) e = Some (pstate_two l r)\n    -> state_sm_on_event X e = Some l\n       /\\ state_sm_on_event Y e = Some r.\nProof.\n  intros SX SY O X Y eo.\n  induction e as [e ind] using predHappenedBeforeInd; introv h.\n  rewrite state_sm_on_event_unroll in h.\n  destruct (dec_isFirst e) as [d1|d1]; simpl in *.\n\n  - dest_cases w; symmetry in Heqw; simpl in *.\n    dest_cases y; symmetry in Heqy; simpl in *.\n    destruct w0; simpl in *; ginv.\n\n    + destruct y0; simpl in *; ginv.\n\n      rewrite (state_sm_on_event_unroll X).\n      rewrite (state_sm_on_event_unroll Y).\n      destruct (dec_isFirst e); tcsp; GC.\n      allrw; simpl; tcsp.\n\n    + destruct y0; simpl in *; ginv.\n\n  - remember (state_sm_on_event (parallel X Y) (local_pred e)) as sop; symmetry in Heqsop.\n    destruct sop; simpl in *; ginv.\n    destruct p; simpl in *; ginv.\n\n    + dest_cases w; symmetry in Heqw; simpl in *; ginv.\n      dest_cases y; symmetry in Heqy; simpl in *; ginv.\n      destruct w0; simpl in *; ginv.\n\n      * destruct y0; simpl in *; ginv.\n        rewrite (state_sm_on_event_unroll X).\n        rewrite (state_sm_on_event_unroll Y).\n        destruct (dec_isFirst e); tcsp; GC.\n        apply ind in Heqsop; auto;[|apply local_pred_is_direct_pred; auto].\n        repnd; repeat (allrw; simpl; tcsp).\n\n      * destruct y0; simpl in *; ginv.\n\n    + dest_cases w; symmetry in Heqw; simpl in *; ginv.\n      destruct w0; simpl in *; ginv.\n\n    + dest_cases w; symmetry in Heqw; simpl in *; ginv.\n      destruct w0; simpl in *; ginv.\nQed.\n\nLemma state_sm_on_event_parallel_some_pstate_left_implies :\n  forall {SX SY O}\n         (X  : StateMachine SX msg (list O))\n         (Y  : StateMachine SY msg (list O))\n         (eo : EventOrdering)\n         (e  : Event)\n         (l  : SX),\n    state_sm_on_event (parallel X Y) e = Some (pstate_left l)\n    -> state_sm_on_event X e = Some l\n       /\\ state_sm_on_event Y e = None.\nProof.\n  intros SX SY O X Y eo.\n  induction e as [e ind] using predHappenedBeforeInd; introv h.\n  rewrite state_sm_on_event_unroll in h.\n  destruct (dec_isFirst e) as [d1|d1]; simpl in *.\n\n  - dest_cases w; symmetry in Heqw; simpl in *.\n    dest_cases y; symmetry in Heqy; simpl in *.\n    destruct w0; simpl in *; ginv.\n\n    + destruct y0; simpl in *; ginv.\n\n      rewrite (state_sm_on_event_unroll X).\n      rewrite (state_sm_on_event_unroll Y).\n      destruct (dec_isFirst e); tcsp; GC.\n      allrw; simpl; tcsp.\n\n    + destruct y0; simpl in *; ginv.\n\n  - remember (state_sm_on_event (parallel X Y) (local_pred e)) as sop; symmetry in Heqsop.\n    destruct sop; simpl in *; ginv.\n    destruct p; simpl in *; ginv.\n\n    + apply state_sm_on_event_parallel_some_pstate_two_implies in Heqsop.\n      exrepnd.\n      dest_cases w; symmetry in Heqw; simpl in *; ginv.\n      dest_cases y; symmetry in Heqy; simpl in *; ginv.\n      destruct w0; simpl in *; ginv.\n\n      * destruct y0; simpl in *; ginv.\n        rewrite (state_sm_on_event_unroll X).\n        rewrite (state_sm_on_event_unroll Y).\n        destruct (dec_isFirst e); tcsp; GC.\n        repnd; repeat (allrw; simpl; tcsp).\n\n      * destruct y0; simpl in *; ginv.\n\n    + dest_cases w; symmetry in Heqw; simpl in *; ginv.\n      destruct w0; simpl in *; ginv.\n\n      * apply ind in Heqsop; auto;[|apply local_pred_is_direct_pred; auto].\n        repnd.\n        rewrite (state_sm_on_event_unroll X).\n        rewrite (state_sm_on_event_unroll Y).\n        destruct (dec_isFirst e); tcsp.\n        repeat(allrw; simpl in *; tcsp).\n\n    + dest_cases w; symmetry in Heqw; simpl in *; ginv.\n      destruct w0; simpl in *; ginv.\nQed.\n\nLemma state_sm_on_event_parallel_some_pstate_right_implies :\n  forall {SX SY O}\n         (X  : StateMachine SX msg (list O))\n         (Y  : StateMachine SY msg (list O))\n         (eo : EventOrdering)\n         (e  : Event)\n         (r  : SY),\n    state_sm_on_event (parallel X Y) e = Some (pstate_right r)\n    -> state_sm_on_event X e = None\n       /\\ state_sm_on_event Y e = Some r.\nProof.\n  intros SX SY O X Y eo.\n  induction e as [e ind] using predHappenedBeforeInd; introv h.\n  rewrite state_sm_on_event_unroll in h.\n  destruct (dec_isFirst e) as [d1|d1]; simpl in *.\n\n  - dest_cases w; symmetry in Heqw; simpl in *.\n    dest_cases y; symmetry in Heqy; simpl in *.\n    destruct y0; simpl in *; ginv.\n\n    + destruct w0; simpl in *; ginv.\n      rewrite (state_sm_on_event_unroll X).\n      rewrite (state_sm_on_event_unroll Y).\n      destruct (dec_isFirst e); tcsp; GC.\n      allrw; simpl; tcsp.\n\n    + destruct w0; simpl in *; ginv.\n\n  - remember (state_sm_on_event (parallel X Y) (local_pred e)) as sop; symmetry in Heqsop.\n    destruct sop; simpl in *; ginv.\n    destruct p; simpl in *; ginv.\n\n    + apply state_sm_on_event_parallel_some_pstate_two_implies in Heqsop.\n      exrepnd.\n      dest_cases w; symmetry in Heqw; simpl in *; ginv.\n      dest_cases y; symmetry in Heqy; simpl in *; ginv.\n      destruct y0; simpl in *; ginv.\n\n      * destruct w0; simpl in *; ginv.\n        rewrite (state_sm_on_event_unroll X).\n        rewrite (state_sm_on_event_unroll Y).\n        destruct (dec_isFirst e); tcsp; GC.\n        repnd; repeat (allrw; simpl; tcsp).\n\n      * destruct w0; simpl in *; ginv.\n\n    + dest_cases w; symmetry in Heqw; simpl in *; ginv.\n      destruct w0; simpl in *; ginv.\n\n    + dest_cases w; symmetry in Heqw; simpl in *; ginv.\n      destruct w0; simpl in *; ginv.\n\n      * apply ind in Heqsop ; auto;[|apply local_pred_is_direct_pred; auto]; repnd.\n        rewrite (state_sm_on_event_unroll X).\n        rewrite (state_sm_on_event_unroll Y).\n        destruct (dec_isFirst e); tcsp.\n        repeat(allrw; simpl in *; tcsp).\nQed.\n\nLemma state_sm_on_event_parallel_none_implies :\n  forall {SX SY O}\n         (X  : StateMachine SX msg (list O))\n         (Y  : StateMachine SY msg (list O))\n         (eo : EventOrdering)\n         (e  : Event),\n    state_sm_on_event (parallel X Y) e = None\n    -> state_sm_on_event X e = None\n       /\\ state_sm_on_event Y e = None.\nProof.\n  intros SX SY O X Y eo.\n  induction e as [e ind] using predHappenedBeforeInd; introv h.\n  rewrite state_sm_on_event_unroll in h.\n  destruct (dec_isFirst e) as [d1|d1]; simpl in *.\n\n  - dest_cases w; symmetry in Heqw; simpl in *.\n    dest_cases y; symmetry in Heqy; simpl in *.\n    destruct y0; simpl in *; ginv.\n\n    + destruct w0; simpl in *; ginv.\n\n    + destruct w0; simpl in *; ginv.\n      rewrite (state_sm_on_event_unroll X).\n      rewrite (state_sm_on_event_unroll Y).\n      destruct (dec_isFirst e); tcsp; GC.\n      allrw; simpl; tcsp.\n\n  - remember (state_sm_on_event (parallel X Y) (local_pred e)) as sop; symmetry in Heqsop.\n    destruct sop; simpl in *; ginv.\n\n    {\n      destruct p; simpl in *; ginv.\n\n      - apply state_sm_on_event_parallel_some_pstate_two_implies in Heqsop; repnd.\n\n        dest_cases w; symmetry in Heqw; simpl in *; ginv.\n        dest_cases y; symmetry in Heqy; simpl in *; ginv.\n        destruct y0; simpl in *; ginv.\n\n        + destruct w0; simpl in *; ginv.\n\n        + destruct w0; simpl in *; ginv.\n          rewrite (state_sm_on_event_unroll X).\n          rewrite (state_sm_on_event_unroll Y).\n          destruct (dec_isFirst e); tcsp; GC.\n          repnd; repeat (allrw; simpl; tcsp).\n\n      - dest_cases w; symmetry in Heqw; simpl in *; ginv.\n        destruct w0; simpl in *; ginv.\n        apply state_sm_on_event_parallel_some_pstate_left_implies in Heqsop; repnd.\n        rewrite (state_sm_on_event_unroll X).\n        rewrite (state_sm_on_event_unroll Y).\n        destruct (dec_isFirst e); tcsp; GC.\n        repeat (allrw; simpl; dands; auto).\n\n      - dest_cases w; symmetry in Heqw; simpl in *; ginv.\n        destruct w0; simpl in *; ginv.\n        apply state_sm_on_event_parallel_some_pstate_right_implies in Heqsop; repnd.\n        rewrite (state_sm_on_event_unroll X).\n        rewrite (state_sm_on_event_unroll Y).\n        destruct (dec_isFirst e); tcsp; GC.\n        repeat (allrw; simpl; dands; auto).\n    }\n\n    {\n      apply ind in Heqsop;[|apply local_pred_is_direct_pred; auto]; repnd.\n      rewrite (state_sm_on_event_unroll X).\n      rewrite (state_sm_on_event_unroll Y).\n      destruct (dec_isFirst e); tcsp.\n      repeat(allrw; simpl in *; tcsp).\n    }\nQed.\n\nLemma parallel_output_iff :\n  forall {SX SY O}\n         (X  : StateMachine SX msg (list O))\n         (Y  : StateMachine SY msg (list O))\n         (eo : EventOrdering)\n         (e  : Event)\n         (x  : O),\n    In x (loutput_sm_on_event (parallel X Y) e)\n    <->\n    (\n      In x (loutput_sm_on_event X e)\n      \\/\n      In x (loutput_sm_on_event Y e)\n    ).\nProof.\n  introv; split; intro h.\n\n  {\n    rewrite loutput_sm_on_event_unroll in h.\n    destruct (dec_isFirst e) as [d|d]; simpl in *.\n\n    {\n      dest_cases w; symmetry in Heqw; simpl in *.\n      dest_cases y; symmetry in Heqy; simpl in *.\n      rewrite in_app_iff in h.\n      repndors;[left|right].\n\n      - rewrite loutput_sm_on_event_unroll.\n        destruct (dec_isFirst e); tcsp; GC.\n        allrw; simpl; auto.\n\n      - rewrite loutput_sm_on_event_unroll.\n        destruct (dec_isFirst e); tcsp; GC.\n        allrw; simpl; auto.\n    }\n\n    {\n      remember (state_sm_on_event (parallel X Y) (local_pred e)) as sop; symmetry in Heqsop.\n      destruct sop; simpl in *; ginv; tcsp.\n\n      destruct p; simpl in *; tcsp.\n\n      + dest_cases w; symmetry in Heqw; simpl in *.\n        dest_cases y; symmetry in Heqy; simpl in *.\n        apply in_app_iff in h; repndors;[left|right].\n\n        * rewrite loutput_sm_on_event_unroll.\n          destruct (dec_isFirst e); tcsp; GC.\n          apply state_sm_on_event_parallel_some_pstate_two_implies in Heqsop; repnd.\n          repeat (allrw; simpl; tcsp).\n\n        * rewrite loutput_sm_on_event_unroll.\n          destruct (dec_isFirst e); tcsp; GC.\n          apply state_sm_on_event_parallel_some_pstate_two_implies in Heqsop; repnd.\n          repeat (allrw; simpl; tcsp).\n\n      + dest_cases w; symmetry in Heqw; simpl in *.\n        apply state_sm_on_event_parallel_some_pstate_left_implies in Heqsop; repnd.\n        left.\n        rewrite loutput_sm_on_event_unroll.\n        destruct (dec_isFirst e); tcsp; GC.\n        repeat (allrw; simpl; tcsp).\n\n      + dest_cases w; symmetry in Heqw; simpl in *.\n        apply state_sm_on_event_parallel_some_pstate_right_implies in Heqsop; repnd.\n        right.\n        rewrite loutput_sm_on_event_unroll.\n        destruct (dec_isFirst e); tcsp; GC.\n        repeat (allrw; simpl; tcsp).\n    }\n  }\n\n  {\n    rewrite loutput_sm_on_event_unroll.\n    destruct (dec_isFirst e) as [d|d]; simpl in *.\n\n    - dest_cases w; symmetry in Heqw; simpl in *.\n      dest_cases y; symmetry in Heqy; simpl in *.\n      apply in_app_iff.\n      repndors.\n\n      + rewrite loutput_sm_on_event_unroll in h.\n        destruct (dec_isFirst e); simpl in *; tcsp; GC.\n        rewrite Heqw in h; simpl in h; tcsp.\n\n      + rewrite loutput_sm_on_event_unroll in h.\n        destruct (dec_isFirst e); simpl in *; tcsp; GC.\n        rewrite Heqy in h; simpl in h; tcsp.\n\n    - remember (state_sm_on_event (parallel X Y) (local_pred e)) as sop.\n      symmetry in Heqsop; destruct sop; simpl in *; tcsp.\n\n      + destruct p; simpl in *.\n\n        * dest_cases w; symmetry in Heqw; simpl in *.\n          dest_cases y; symmetry in Heqy; simpl in *.\n          apply state_sm_on_event_parallel_some_pstate_two_implies in Heqsop; repnd.\n          apply in_app_iff.\n          repndors.\n\n          { rewrite loutput_sm_on_event_unroll in h.\n            destruct (dec_isFirst e); simpl in *; tcsp; GC.\n            rewrite Heqsop0 in h; simpl in h.\n            rewrite Heqw in h; simpl in h; tcsp. }\n\n          { rewrite loutput_sm_on_event_unroll in h.\n            destruct (dec_isFirst e); simpl in *; tcsp; GC.\n            rewrite Heqsop in h; simpl in h; tcsp.\n            rewrite Heqy in h; simpl in h; tcsp. }\n\n        * dest_cases w; symmetry in Heqw; simpl in *.\n          apply state_sm_on_event_parallel_some_pstate_left_implies in Heqsop; repnd.\n          repndors.\n\n          { rewrite loutput_sm_on_event_unroll in h.\n            destruct (dec_isFirst e); simpl in *; tcsp; GC.\n            rewrite Heqsop0 in h; simpl in h.\n            rewrite Heqw in h; simpl in h; tcsp. }\n\n          { rewrite loutput_sm_on_event_unroll in h.\n            destruct (dec_isFirst e); simpl in *; tcsp; GC.\n            rewrite Heqsop in h; simpl in h; tcsp. }\n\n        * dest_cases w; symmetry in Heqw; simpl in *.\n          apply state_sm_on_event_parallel_some_pstate_right_implies in Heqsop; repnd.\n          repndors.\n\n          { rewrite loutput_sm_on_event_unroll in h.\n            destruct (dec_isFirst e); simpl in *; tcsp; GC.\n            rewrite Heqsop0 in h; simpl in h; tcsp. }\n\n          { rewrite loutput_sm_on_event_unroll in h.\n            destruct (dec_isFirst e); simpl in *; tcsp; GC.\n            rewrite Heqsop in h; simpl in h; tcsp.\n            rewrite Heqw in h; simpl in *; auto. }\n\n      + apply state_sm_on_event_parallel_none_implies in Heqsop; repnd.\n        rewrite (loutput_sm_on_event_unroll X) in h.\n        rewrite (loutput_sm_on_event_unroll Y) in h.\n        destruct (dec_isFirst e); tcsp; GC.\n        rewrite Heqsop, Heqsop0 in h; simpl in h; tcsp.\n  }\nQed.\n\nEnd Parallel.\n\n\nOpen Scope proc.\nNotation \"a [||] b\" := (nparallel a b) (at level 100) : proc.\nClose Scope proc.\n", "meta": {"author": "vrahli", "repo": "Velisarios", "sha": "6fb353b18610cd79210755fcc90123536c367aaa", "save_path": "github-repos/coq/vrahli-Velisarios", "path": "github-repos/coq/vrahli-Velisarios/Velisarios-6fb353b18610cd79210755fcc90123536c367aaa/components/Parallel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2434713721650457}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config uGraph.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICOnOne\n     PCUICLiftSubst PCUICUnivSubst PCUICTyping PCUICNormal PCUICSR\n     PCUICGeneration PCUICReflect PCUICEquality PCUICInversion PCUICValidity\n     PCUICWeakeningConv PCUICWeakeningTyp PCUICReduction PCUICConversion\n     PCUICPosition PCUICCumulativity PCUICSafeLemmata PCUICSN\n     PCUICPretty PCUICArities PCUICConfluence PCUICSize\n     PCUICContextConversion PCUICConversion PCUICWfUniverses.\n\nFrom MetaCoq.SafeChecker Require Import PCUICWfEnv.\n\n\nFrom Equations Require Import Equations.\nRequire Import ssreflect ssrbool.\n\nLocal Set Keyed Unification.\nSet Equations Transparent.\n\nLemma Acc_no_loop X (R : X -> X -> Prop) t : Acc R t -> R t t -> False.\nProof.\n  induction 1. intros. eapply H0; eauto.\nQed.\n\n(* Show that taking head normal forms and then the subterm relation is well-founded *)\n\nInductive term_direct_subterm : term -> term -> Type :=\n| term_direct_subterm_4_1 : forall (na : aname) (A B : term),\n  term_direct_subterm B (tProd na A B)\n| term_direct_subterm_4_2 : forall (na : aname) (A B : term),\n  term_direct_subterm A (tProd na A B)\n| term_direct_subterm_5_1 : forall (na : aname) (A t : term),\n  term_direct_subterm t (tLambda na A t)\n| term_direct_subterm_5_2 : forall (na : aname) (A t : term),\n  term_direct_subterm A (tLambda na A t)\n| term_direct_subterm_6_1 : forall (na : aname) (b B t : term),\n  term_direct_subterm t (tLetIn na b B t)\n| term_direct_subterm_6_2 : forall (na : aname) (b B t : term),\n  term_direct_subterm B (tLetIn na b B t)\n| term_direct_subterm_6_3 : forall (na : aname) (b B t : term),\n  term_direct_subterm b (tLetIn na b B t)\n| term_direct_subterm_7_1 : forall u v : term,\n  term_direct_subterm v (tApp u v)\n| term_direct_subterm_7_2 : forall u v : term,\n  term_direct_subterm u (tApp u v)\n| term_direct_subterm_11_1 : forall (ci : case_info)\n     (p : predicate term) (c : term) (brs : list (branch term)),\n   term_direct_subterm c (tCase ci p c brs)\n| term_direct_subterm_11_2 : forall (ci : case_info)\n  (p : predicate term) (c : term) (brs : list (branch term)),\n  term_direct_subterm p.(preturn) (tCase ci p c brs)\n| term_direct_subterm_12_1 : forall (p : projection) (c : term),\n  term_direct_subterm c (tProj p c).\nDerive Signature for term_direct_subterm.\n\nDefinition term_direct_subterm_context (t u : term) (p : term_direct_subterm t u) : context :=\n  match p with\n  | term_direct_subterm_4_1 na A B => [vass na A]\n  | term_direct_subterm_5_1 na A t => [vass na A]\n  | term_direct_subterm_6_1 na b B t => [vdef na b B]\n  | term_direct_subterm_11_2 ci p c brs => inst_case_predicate_context p\n  | _ => []\n  end.\n\nRequire Equations.Type.WellFounded.\nDefinition term_subterm := Relation.trans_clos term_direct_subterm.\n\nFixpoint term_subterm_context {t u : term} (p : term_subterm t u) : context :=\n  match p with\n  | Relation.t_step y xy => term_direct_subterm_context _ _ xy\n  | Relation.t_trans y z rxy ryz =>\n    term_subterm_context rxy ++ term_subterm_context ryz\n  end.\n\nDefinition term_subterm_wf : Equations.Type.WellFounded.well_founded term_subterm.\nProof.\n  eapply WellFounded.wf_trans_clos.\n  red. fix IH 1. intro x; constructor.\n  destruct x; intros y sub; depelim sub; apply IH.\nDefined.\n\n(** At least one step of reduction *)\nDefinition redp Σ Γ t u := Relation.trans_clos (red1 Σ Γ) t u.\n\n#[global]\nInstance redp_trans Σ Γ : CRelationClasses.Transitive (redp Σ Γ).\nProof. econstructor 2; eauto. Qed.\n\n#[global]\nInstance redp_red Σ Γ : CRelationClasses.subrelation (redp Σ Γ) (red Σ Γ).\nProof.\n  intros x y.\n  induction 1; solve [econstructor; eauto].\nQed.\n\n#[global]\nInstance cored_transitive Σ Γ : RelationClasses.Transitive (cored Σ Γ).\nProof.\n  intros x y z.\n  induction 1 in z |- *. econstructor 2; eauto.\n  intros uz. specialize (IHcored _ uz).\n  econstructor 2. eapply IHcored. assumption.\nQed.\n\nLemma cored_redp Σ Γ t u : cored Σ Γ u t <-> ∥ redp Σ Γ t u ∥.\nProof.\n  split.\n  * induction 1; sq; try solve [econstructor; eauto].\n    transitivity v; auto. now constructor.\n  * intros []. induction X.\n    + now constructor.\n    + now transitivity y.\nQed.\n\n(** Well-founded relation allowing to define functions using weak-head reduction\non (welltyped) terms and going under binders. *)\nSection fix_sigma.\n  Context {cf : checker_flags} {no : normalizing_flags}.\n  Context {Σ : global_env_ext} {normalization:NormalizationIn Σ} {HΣ : ∥wf_ext Σ∥}.\n\n  Lemma term_subterm_red1 {Γ s s' t} {ts : term_subterm s t} :\n    red1 Σ (Γ ,,, term_subterm_context ts) s s' ->\n    exists t', ∥ red1 Σ Γ t t' × ∑ ts' : term_subterm s' t', term_subterm_context ts' = term_subterm_context ts ∥.\n  Proof using Type.\n    induction ts in Γ, s' |- *.\n    - induction r; simpl.\n    all:intros red; eexists; split;\n    try solve [split; [solve [eauto using red1]|unshelve eexists;[repeat constructor|simpl; eauto]]].\n    split.\n    eapply letin_red_body; eauto. unshelve eexists. repeat constructor. reflexivity.\n    split.\n    eapply letin_red_ty; eauto. unshelve eexists. repeat constructor. reflexivity.\n    split. eapply letin_red_def; eauto. unshelve eexists. repeat constructor. reflexivity.\n    split. eapply case_red_return; eauto. unshelve eexists. repeat constructor.\n    eapply (term_direct_subterm_11_2 ci (set_preturn p s')). simpl. reflexivity.\n    - simpl. intros.\n    rewrite app_context_assoc in X.\n    specialize (IHts1 _ _ X) as [t' [[yt' [ts Hts]]]].\n    specialize (IHts2 _ _ yt') as [t'' [[zt' [ts'' Hts'']]]].\n    exists t''. split; split; auto.\n    unshelve eexists. econstructor 2; eauto. simpl.\n    now rewrite Hts Hts''.\n  Qed.\n\n  Lemma term_subterm_redp {Γ s s' t} {ts : term_subterm s t} :\n    redp Σ (Γ ,,, term_subterm_context ts) s s' ->\n    exists t', ∥ redp Σ Γ t t' × ∑ ts' : term_subterm s' t', term_subterm_context ts' = term_subterm_context ts ∥.\n  Proof using Type.\n    intros r.\n    generalize_eqs r. intros ->. revert t ts.\n    induction r.\n    - intros t ts ->.\n      destruct (term_subterm_red1 r) as [t' [[red1 [ts' Hts']]]].\n      exists t'; split; auto. split; auto. now constructor. exists ts'; auto.\n    - intros t ts ->. specialize (IHr1 t ts eq_refl) as [t' [[yt' [ts' Hts]]]].\n      specialize (IHr2 t' ts').\n      forward IHr2. now rewrite Hts.\n      destruct IHr2 as [t'' [[zt' [ts'' Hts'']]]].\n      exists t''. split; split; auto.\n      now transitivity t'.\n      exists ts''.\n      now rewrite Hts'' Hts.\n  Qed.\n\n  Definition hnf_subterm_rel : Relation_Definitions.relation (∑ Γ t, welltyped Σ Γ t) :=\n    fun '(Γ2; t2; H) '(Γ1; t1; H2) =>\n    ∥∑ t', red (fst Σ) Γ1 t1 t' × ∑ ts : term_subterm t2 t', Γ2 = (Γ1 ,,, term_subterm_context ts) ∥.\n\n  Ltac sq' := try (destruct HΣ; clear HΣ);\n    repeat match goal with\n    | H : ∥ _ ∥ |- _ => destruct H; try clear H\n    end; try eapply sq.\n\n  Definition wf_hnf_subterm_rel : WellFounded hnf_subterm_rel.\n  Proof.\n    intros (Γ & s & H). sq'.\n    induction (normalization_in Γ s H) as [s _ IH].\n    induction (term_subterm_wf s) as [s _ IH_sub] in Γ, H, IH |- *.\n    econstructor.\n    intros (Γ' & t2 & ?) [(t' & r & ts & eqctx)].\n    eapply Relation_Properties.clos_rt_rtn1 in r. inversion r.\n    + subst. eapply IH_sub; auto.\n      intros.\n      inversion H0.\n      * subst.\n        destruct (term_subterm_red1 X0) as [t'' [[redt' [tst' Htst']]]].\n        eapply IH. econstructor. eauto. red.\n        sq. exists t''. split; eauto. exists tst'. now rewrite Htst'.\n        Unshelve.\n        eapply red_welltyped; sq. 3:eapply red1_red; tea. all:eauto.\n      * subst. eapply cored_redp in H2 as [].\n        pose proof (term_subterm_redp X1) as [t'' [[redt' [tst' Htst']]]].\n        rewrite -Htst' in X0.\n        destruct (term_subterm_red1 X0) as [t''' [[redt'' [tst'' Htst'']]]].\n        eapply IH.\n        eapply cored_redp. sq. transitivity t''; eauto.\n        constructor; eauto.\n        split.\n        exists t'''. split; auto. exists tst''.\n        now rewrite Htst'' Htst'.\n        Unshelve.\n        eapply red_welltyped in H; eauto. all:sq; eauto.\n        eapply redp_red in redt'.\n        now transitivity t''.\n      + subst. eapply IH.\n      * eapply red_neq_cored.\n        eapply Relation_Properties.clos_rtn1_rt. exact r.\n        intros ?. subst.\n        eapply Relation_Properties.clos_rtn1_rt in X1.\n        eapply cored_red_trans in X0; [| exact X1 ].\n        eapply Acc_no_loop in X0. eauto.\n        eapply @normalization; eauto.\n      * split. exists t'. split; eauto.\n    Unshelve.\n    - eapply red_welltyped; sq.\n      3:eapply Relation_Properties.clos_rtn1_rt in r; eassumption. all:eauto.\n  Defined.\n\n  Global Instance wf_hnf_subterm : WellFounded hnf_subterm_rel.\n  Proof.\n    refine (Wf.Acc_intro_generator 1000 _).\n    exact wf_hnf_subterm_rel.\n  Defined.\n  Opaque wf_hnf_subterm.\n  Opaque Acc_intro_generator.\n  Opaque Wf.Acc_intro_generator.\n  Ltac sq := try (destruct HΣ as [wfΣ]; clear HΣ);\n    repeat match goal with\n    | H : ∥ _ ∥ |- _ => destruct H\n    end; try eapply sq.\n\nEnd fix_sigma.\n\nSection fix_sigma.\n  Context {cf : checker_flags} {no : normalizing_flags}.\n\n  Context (X_type : abstract_env_impl).\n\n  Context (X : X_type.π2.π1).\n\n  Context {normalization_in : forall Σ, wf_ext Σ -> Σ ∼_ext X -> NormalizationIn Σ}.\n\n  (* Reducing at least one step or taking a subterm is well-founded *)\n  Definition redp_subterm_rel : Relation_Definitions.relation (∑ Γ t, forall Σ (wfΣ : abstract_env_ext_rel X Σ), welltyped Σ Γ t) :=\n    fun '(Γ2; t2; H) '(Γ1; t1; H2) => forall Σ (wfΣ : abstract_env_ext_rel X Σ),\n    ∥ (redp Σ Γ1 t1 t2 * (Γ1 = Γ2)) + ∑ ts : term_subterm t2 t1, Γ2 = (Γ1 ,,, term_subterm_context ts) ∥.\n\n  Definition wf_redp_subterm_rel : WellFounded redp_subterm_rel.\n  Proof.\n    intros (Γ & s & H). pose proof (abstract_env_ext_exists X) as [[Σ wfΣ]].\n    pose (wf_extΣ := abstract_env_ext_wf _ wfΣ). sq.\n    induction (normalization_in Σ wf_extΣ wfΣ Γ s (H _ wfΣ)) as [s _ IH].\n    induction (term_subterm_wf s) as [s _ IH_sub] in Γ, H, IH |- *.\n    econstructor.\n    intros (Γ' & t2 & ?). intro R. specialize (R _ wfΣ).\n    destruct R as [[[r eq]|[ts eqctx]]].\n    + subst. eapply Relation_Properties.trans_clos_tn1 in r.\n      eapply IH. clear -r.\n      induction r; try solve [econstructor; auto].\n      now eapply cored_trans with y.\n    + subst.\n      apply IH_sub. eauto.\n      intros. eapply cored_redp in H0 as [].\n      destruct (term_subterm_redp X0) as [t'' [[redt' [tst' Htst']]]].\n      eapply IH. eapply cored_redp. sq. eassumption. red. intros.\n      sq. right. exists tst'. now rewrite Htst'.\n    Unshelve. intros. erewrite (abstract_env_ext_irr _ _ wfΣ); eauto.\n              eapply redp_red in redt'; eapply red_welltyped; sq; eauto.\n    Unshelve. eauto.\n  Defined.\n\n  Global Instance wf_redp_subterm : WellFounded redp_subterm_rel.\n  Proof.\n    refine (Wf.Acc_intro_generator 1000 _).\n    exact wf_redp_subterm_rel.\n  Defined.\n  Opaque wf_redp_subterm.\n  Opaque Acc_intro_generator.\n  Opaque Wf.Acc_intro_generator.\n\nEnd fix_sigma.\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/safechecker/theories/PCUICWfReduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24347137216504566}}
{"text": "Require Import oeuf.Common.\nRequire oeuf.StepLib.\nRequire Import Psatz.\n\nRequire Import oeuf.Utopia.\nRequire Import oeuf.Monads.\n\nRequire Export oeuf.HigherValue.\nRequire Import oeuf.AllValues.\nRequire Import oeuf.OpaqueOps.\nRequire Import oeuf.ListLemmas.\n\nInductive expr :=\n| Arg\n| Self\n| Var (i : nat)\n| Deref (e : expr) (off : nat)\n.\n\nInductive stmt :=\n| Skip\n| Seq (s1 : stmt) (s2 : stmt)\n| Call (dst : nat) (f : expr) (a : expr)\n| MkConstr (dst : nat) (tag : nat) (args : list expr)\n| Switch (dst : nat) (cases : list stmt)\n| MkClose (dst : nat) (f : function_name) (free : list expr)\n| OpaqueOp (dst : nat) (op : opaque_oper_name) (args : list expr)\n| Assign (dst : nat) (e : expr)\n.\n\nDefinition env := list (stmt * nat).\n\n\n(* Continuation-based step relation *)\n\nRecord frame := Frame {\n    arg : value;\n    self : value;\n    locals : list (nat * value)\n}.\n\nDefinition set f l v :=\n    Frame (arg f) (self f) ((l, v) :: locals f).\n\nDefinition local f l := lookup (locals f) l.\n\n\n\nInductive cont :=\n| Kseq (code : stmt) (k : cont)\n| Kswitch (k : cont)\n| Kreturn (ret : nat) (k : cont)\n| Kcall (dst : nat) (f : frame) (k : cont)\n| Kstop (ret : nat).\n\nInductive state :=\n| Run (s : stmt) (f : frame) (k : cont)\n| Return (v : value) (k : cont)\n| Stop (v : value).\n\nInductive eval : frame -> expr -> value -> Prop :=\n| EArg : forall f,\n        eval f Arg (arg f)\n| ESelf : forall f,\n        eval f Self (self f)\n\n| EVar : forall f i v,\n        local f i = Some v ->\n        eval f (Var i) v\n\n| EDerefConstr : forall f e off tag args v,\n        eval f e (Constr tag args) ->\n        nth_error args off = Some v ->\n        eval f (Deref e off) v\n| EDerefClose : forall f e off fname free v,\n        eval f e (Close fname free) ->\n        nth_error free off = Some v ->\n        eval f (Deref e off) v\n.\n\nInductive sstep (E : env) : state -> state -> Prop :=\n| SSeq : forall s1 s2 f k,\n        sstep E (Run (Seq s1 s2) f k)\n                (Run s1 f (Kseq s2 k))\n\n| SConstrDone : forall dst tag args f k vs,\n        Forall2 (eval f) args vs ->\n        sstep E (Run (MkConstr dst tag args) f k)\n                (Run Skip (set f dst (Constr tag vs)) k)\n| SCloseDone : forall dst fname free f k vs,\n        Forall2 (eval f) free vs ->\n        sstep E (Run (MkClose dst fname free) f k)\n                (Run Skip (set f dst (Close fname vs)) k)\n| SOpaqueOpDone : forall dst op args f k vs v,\n        Forall2 (eval f) args vs ->\n        opaque_oper_denote_higher op vs = Some v ->\n        sstep E (Run (OpaqueOp dst op args) f k)\n                (Run Skip (set f dst v) k)\n\n| SMakeCall : forall dst fe ae f k  fname free arg body ret,\n        eval f fe (Close fname free) ->\n        eval f ae arg ->\n        nth_error E fname = Some (body, ret) ->\n        sstep E (Run (Call dst fe ae) f k)\n                (Run body (Frame arg (Close fname free) [])\n                    (Kreturn ret (Kcall dst f k)))\n\n(* NB: `Switch` still has an implicit target of `Arg` *)\n| SSwitchinate : forall dst cases f k  tag args case,\n        arg f = Constr tag args ->\n        nth_error cases tag = Some case ->\n        sstep E (Run (Switch dst cases) f k)\n                (Run case f (Kswitch k))\n\n| SAssign : forall dst src f k v,\n        eval f src v ->\n        sstep E (Run (Assign dst src) f k)\n                (Run Skip (set f dst v) k)\n\n| SContSeq : forall f s k,\n        sstep E (Run Skip f (Kseq s k))\n                (Run s f k)\n| SContSwitch : forall f k,\n        sstep E (Run Skip f (Kswitch k))\n                (Run Skip f k)\n| SContReturn : forall f ret k v,\n        local f ret = Some v ->\n        sstep E (Run Skip f (Kreturn ret k))\n                (Return v k)\n| SContCall : forall v dst f k,\n        sstep E (Return v (Kcall dst f k))\n                (Run Skip (set f dst v) k)\n| SContStop : forall ret f v,\n        local f ret = Some v ->\n        sstep E (Run Skip f (Kstop ret))\n                (Stop v)\n.\n\n\n\nDefinition sstar BE := StepLib.sstar (sstep BE).\nDefinition SStarNil := @StepLib.SStarNil state.\nDefinition SStarCons := @StepLib.SStarCons state.\n\nDefinition splus BE := StepLib.splus (sstep BE).\nDefinition SPlusOne := @StepLib.SPlusOne state.\nDefinition SPlusCons := @StepLib.SPlusCons state.\n\n\n\nRequire Import oeuf.Metadata.\nRequire oeuf.Semantics.\n\n\nDefinition prog_type : Type := env * list metadata.\nDefinition val_level := VlHigher.\nDefinition valtype := value_type val_level.\n\nInductive is_callstate (prog : prog_type) : valtype -> valtype -> state -> Prop :=\n| IsCallstate : forall fname free av body ret,\n        nth_error (fst prog) fname = Some (body, ret) ->\n        let fv := Close fname free in\n        HigherValue.public_value (snd prog) fv ->\n        HigherValue.public_value (snd prog) av ->\n        is_callstate prog fv av\n            (Run body\n                 (Frame av fv [])\n                 (Kstop ret)).\n\nInductive final_state (prog : prog_type) : state -> valtype -> Prop :=\n| FinalState : forall v,\n        HigherValue.public_value (snd prog) v ->\n        final_state prog (Stop v) v.\n\nDefinition initial_env (prog : prog_type) : env := fst prog.\n\nDefinition semantics (prog : prog_type) : Semantics.semantics :=\n  @Semantics.Semantics_gen state env val_level\n                 (is_callstate prog)\n                 (sstep)\n                 (final_state prog)\n                 (initial_env prog).\n\n\n(*\n\nDefinition prog_type : Type := env * list metadata.\n\nInductive initial_state (prog : prog_type) : state -> Prop :=.\n\nInductive final_state (prog : prog_type) : state -> Prop :=\n| FinalState : forall v, final_state prog (Stop v).\n\nDefinition initial_env (prog : prog_type) : env := fst prog.\n\nDefinition semantics (prog : prog_type) : Semantics.semantics :=\n  @Semantics.Semantics_gen state env\n                 (sstep)\n                 (initial_state prog)\n                 (final_state prog)\n                 (initial_env prog).\n*)\n\n\n(*\n * Mutual recursion/induction schemes for expr\n *)\n\nDefinition stmt_rect_mut\n        (P : stmt -> Type)\n        (Pl : list stmt -> Type)\n    (HSkip :    P Skip)\n    (HSeq :     forall s1 s2, P s1 -> P s2 -> P (Seq s1 s2))\n    (HCall :    forall dst f a, P (Call dst f a))\n    (HConstr :  forall dst tag args, P (MkConstr dst tag args))\n    (HSwitch :  forall dst cases, Pl cases -> P (Switch dst cases))\n    (HClose :   forall dst fname free, P (MkClose dst fname free))\n    (HOpaqueOp : forall dst op args, P (OpaqueOp dst op args))\n    (HAssign :  forall dst src, P (Assign dst src))\n    (Hnil :     Pl [])\n    (Hcons :    forall i is, P i -> Pl is -> Pl (i :: is))\n    (i : stmt) : P i :=\n    let fix go i :=\n        let fix go_list is :=\n            match is as is_ return Pl is_ with\n            | [] => Hnil\n            | i :: is => Hcons i is (go i) (go_list is)\n            end in\n        match i as i_ return P i_ with\n        | Skip => HSkip\n        | Seq s1 s2 => HSeq s1 s2 (go s1) (go s2)\n        | Call dst f a => HCall dst f a\n        | MkConstr dst tag args => HConstr dst tag args\n        | Switch dst cases => HSwitch dst cases (go_list cases)\n        | MkClose dst fname free => HClose dst fname free\n        | OpaqueOp dst op args => HOpaqueOp dst op args\n        | Assign dst src => HAssign dst src\n        end in go i.\n\n(* Useful wrapper for `expr_rect_mut with (Pl := Forall P)` *)\nDefinition stmt_ind' (P : stmt -> Prop)\n    (HSkip :    P Skip)\n    (HSeq :     forall s1 s2, P s1 -> P s2 -> P (Seq s1 s2))\n    (HCall :    forall dst f a, P (Call dst f a))\n    (HConstr :  forall dst tag args, P (MkConstr dst tag args))\n    (HSwitch :  forall dst cases, Forall P cases -> P (Switch dst cases))\n    (HClose :   forall dst fname free, P (MkClose dst fname free))\n    (HOpaqueOp : forall dst op args, P (OpaqueOp dst op args))\n    (HAssign :  forall dst src, P (Assign dst src))\n    (i : stmt) : P i :=\n    ltac:(refine (@stmt_rect_mut P (Forall P)\n        HSkip HSeq HCall HConstr HSwitch HClose HOpaqueOp HAssign _ _ i); eauto).\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/FlatExpr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961013, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24347137216504558}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Export Plans_paralleles.\nSet Implicit Arguments.\nUnset Strict Implicit.\nParameter secants : PL -> PL -> Prop.\n \nAxiom\n  def_secants :\n    forall A B C D E F I J : PO,\n    ~ alignes A B C ->\n    ~ alignes D E F ->\n    I <> J ->\n    incluse (droite I J) (plan A B C) ->\n    incluse (droite I J) (plan D E F) ->\n    ~ para_plan_plan (plan A B C) (plan D E F) ->\n    secants (plan A B C) (plan D E F).\n \nAxiom\n  def_secants2 :\n    forall A B C D E F : PO,\n    ~ alignes A B C ->\n    ~ alignes D E F ->\n    secants (plan A B C) (plan D E F) ->\n    ~ para_plan_plan (plan A B C) (plan D E F) /\\\n    (exists I : PO,\n       (exists J : PO,\n          I <> J /\\\n          incluse (droite I J) (plan A B C) /\\\n          incluse (droite I J) (plan D E F))).\n \nTheorem position_relative_plans :\n forall A B C D E F : PO,\n ~ alignes A B C ->\n ~ alignes D E F ->\n para_plan_plan (plan A B C) (plan D E F) \\/\n secants (plan A B C) (plan D E F).\nintros.\nlapply\n (plans_paralleles_ou_droite_incluse2 (A:=A) (B:=B) (C:=C) (D:=D) (E:=E)\n    (F:=F)); intros; auto.\nelim H1;\n [ intros H2; try clear H1\n | intros H2; elim H2;\n    [ intros I H3; elim H3;\n       [ intros J H4; elim H4;\n          [ intros H5 H6; elim H6;\n             [ intros H7 H8; try clear H6 H4 H3 H2 H1; try trivial ] ] ] ]\n | try trivial ].\nleft; try assumption.\nelim (classic (para_plan_plan (plan A B C) (plan D E F))); intros.\nleft; try assumption.\nright; try assumption.\napply def_secants with (I := I) (J := J); auto.\nQed.\n \nTheorem toit :\n forall A B C D E F : PO,\n ~ alignes A B C ->\n ~ alignes D E F ->\n paralleles (droite D E) (droite A B) ->\n ~ para_plan_plan (plan A B C) (plan D E F) ->\n exists I : PO,\n   (exists J : PO,\n      (I <> J :>PO /\\ paralleles (droite A B) (droite I J)) /\\\n      incluse (droite I J) (plan A B C) /\\ incluse (droite I J) (plan D E F)).\nintros.\nderoule_triangle A B C.\nderoule_triangle D E F.\nelim\n position_relative_droite_plan\n  with (A := A) (B := B) (C := C) (D := D) (E := F);\n [ intros H9; try clear position_relative_droite_plan\n | unfold perce in |- *; intros H9; try clear position_relative_droite_plan;\n    try exact H9\n | try trivial\n | trivial ].\n2: elim H9; [ intros H10 H11; try clear H9; try exact H11 ].\nabsurd (para_plan_plan (plan A B C) (plan D E F)); auto.\nelim para_plan_dr_vecteur with (A := A) (B := B) (C := C) (D := D) (E := F);\n [ intros k H10; elim H10;\n    [ intros k' H11; try clear H10 para_plan_dr_vecteur; auto ]\n | auto\n | auto\n | auto ].\nelim paralleles_vecteur with (A := D) (B := E) (C := A) (D := B);\n [ intros k0 H12; try clear paralleles_vecteur; auto | auto | auto | auto ].\napply couple_vecteurs_coplanaires with (a := k0) (b := 0) (c := k) (d := k');\n auto.\nrewrite H12; RingPP.\nelim def_contact2 with (A := A) (B := B) (C := C) (D := D) (E := F);\n [ intros I H12; try clear def_secants2 | trivial | trivial | trivial ].\nelim H12; [ intros H9 H13; try clear H12; try exact H13 ].\nexists I.\nelim existence_representant_vecteur with (A := I) (B := A) (C := B);\n intros J H14; try clear existence_representant_vecteur.\nexists J.\ncut (I <> J).\nintros H21.\ncut (paralleles (droite A B) (droite I J)).\nintros H16; try assumption.\nsplit; [ split; [ try assumption | idtac ] | idtac ].\ntry exact H16.\nsplit; [ try assumption | idtac ].\napply droite_incluse_plan2; auto.\napply paralleles_droite_plan_coplanaires_incluse with (D := I) (E := J); auto.\napply def_para_plan_dr with (D := A) (E := B); auto with geo.\ncut (coplanaires D E F I).\nintros H22.\napply droite_incluse_plan2; auto.\ncut (paralleles (droite D E) (droite I J)); intros.\napply paralleles_droite_plan_coplanaires_incluse with (D := I) (E := J); auto.\napply def_para_plan_dr with (D := D) (E := E); auto with geo.\napply paralleles_trans with (5 := H16); auto.\nauto with geo.\napply colineaires_paralleles with 1; auto.\nrewrite H14; RingPP.\nunfold not in |- *; intros; apply H5.\napply conversion_PP with (a := 1) (b := 1); auto with *.\ncut (vec A B = vec I J); intros.\nunfold vec in H15.\nRingPP2 H15.\nrewrite H12; RingPP.\nrewrite H14; auto.\nQed.\n \nLemma plans_paralleles_droite :\n forall A B C D E F I J : PO,\n ~ alignes A B C ->\n ~ alignes D E F ->\n I <> J ->\n para_plan_plan (plan A B C) (plan D E F) ->\n para_plan_dr (plan A B C) (droite I J) ->\n para_plan_dr (plan D E F) (droite I J).\nintros.\nderoule_triangle A B C.\nderoule_triangle D E F.\nelim para_plan_dr_vecteur with (A := A) (B := B) (C := C) (D := I) (E := J);\n [ intros k H10; elim H10; [ intros k' H11; try clear H10; try exact H11 ]\n | auto\n | auto\n | auto ].\nelim\n plans_paralleles_vecteurs\n  with (A := D) (B := E) (C := F) (D := A) (E := B) (F := C); \n auto.\nintros H10 H12; try assumption.\nelim H12;\n [ intros c H13; elim H13; [ intros d H14; try clear H13 H12; try exact H14 ] ].\nelim H10;\n [ intros a H12; elim H12; [ intros b H13; try clear H12 H10; try exact H13 ] ].\ncut\n (vec I J =\n  add_PP (mult_PP k (add_PP (mult_PP a (vec D E)) (mult_PP b (vec D F))))\n    (mult_PP k' (add_PP (mult_PP c (vec D E)) (mult_PP d (vec D F)))));\n intros.\napply vecteurs_para_plan_dr with (k := k * a + k' * c) (k' := k * b + k' * d);\n auto.\nrewrite H10; RingPP.\nrewrite H11; rewrite H14; rewrite H13; RingPP.\napply para_plan_sym; auto.\nQed.\n \nLemma plans_paralleles_secants_droites_paralleles :\n forall A B C D E F I J K : PO,\n ~ alignes A B C ->\n ~ alignes D E F ->\n ~ alignes I J K ->\n para_plan_plan (plan A B C) (plan D E F) ->\n ~ para_plan_plan (plan A B C) (plan I J K) ->\n incluse (droite I J) (plan A B C) ->\n ex\n   (fun G : PO =>\n    ex\n      (fun L : PO =>\n       (G <> L /\\ incluse (droite G L) (plan I J K)) /\\\n       incluse (droite G L) (plan D E F) /\\\n       paralleles (droite G L) (droite I J))).\nintros.\nderoule_triangle A B C.\nderoule_triangle D E F.\nderoule_triangle I J K.\ncut (para_plan_dr (plan D E F) (droite I J)); intros.\nelim\n position_relative_droite_plan\n  with (A := D) (B := E) (C := F) (D := I) (E := K);\n [ intros H15; try clear position_relative_droite_plan\n | unfold perce in |- *; intros H15; try clear position_relative_droite_plan;\n    try exact H15\n | try trivial\n | try trivial ].\n2: elim H15; [ intros H16 H17; try clear H15; try exact H17 ].\ncut (para_plan_plan (plan D E F) (plan I J K)); intros.\nabsurd (para_plan_plan (plan A B C) (plan I J K)); auto.\napply para_plan_trans with (D := D) (E := E) (F := F); auto.\napply def_para_plan_plan; auto.\nelim def_contact2 with (3 := H17);\n [ intros G H15; elim H15; intros; try clear H15; auto | auto | auto ].\nelim existence_representant_vecteur with (A := G) (B := I) (C := J);\n intros L H20; try clear existence_representant_vecteur.\nexists G; exists L.\ncut (G <> L); intros.\ncut (paralleles (droite G L) (droite I J)); intros.\nsplit; [ split; [ try assumption | idtac ] | idtac ].\ncut (coplanaires I J K G); intros.\napply droite_incluse_plan2; auto with geo.\napply paralleles_droite_plan_coplanaires_incluse with (D := G) (E := L); auto.\napply vecteurs_para_plan_dr with (k := 1) (k' := 0); auto.\nrewrite H20; RingPP.\nauto with geo.\nsplit; [ try assumption | auto ].\ncut (para_plan_dr (plan D E F) (droite G L)); intros.\napply droite_incluse_plan2; auto with geo.\napply paralleles_droite_plan_coplanaires_incluse with (D := G) (E := L); auto.\napply paralleles_droites_plan_trans with (D := I) (E := J); auto with geo.\napply colineaires_paralleles with 1; auto with geo.\nrewrite H20; RingPP.\nunfold not in |- *; intros; apply H13.\napply conversion_PP with (a := 1) (b := 1); auto with *.\ncut (vec I J = vec G L); intros.\nunfold vec in H21.\nRingPP2 H21.\nrewrite H15; RingPP.\nrewrite H20; auto.\napply plans_paralleles_droite with (4 := H2); auto.\napply paralleles_droite_incluse; auto.\nQed.\nParameter disjoints : PL -> PL -> Prop.\nParameter confondus : PL -> PL -> Prop.\n \nAxiom\n  def_disjoints :\n    forall A B C D E F : PO,\n    ~ alignes A B C ->\n    ~ alignes D E F ->\n    (forall I : PO, ~ (coplanaires A B C I /\\ coplanaires D E F I)) ->\n    disjoints (plan A B C) (plan D E F).\n \nAxiom\n  def_disjoints2 :\n    forall A B C D E F : PO,\n    ~ alignes A B C ->\n    ~ alignes D E F ->\n    disjoints (plan A B C) (plan D E F) ->\n    forall I : PO, ~ (coplanaires A B C I /\\ coplanaires D E F I).\n \nAxiom\n  def_confondus :\n    forall A B C D E F : PO,\n    ~ alignes A B C ->\n    ~ alignes D E F ->\n    (forall I : PO, coplanaires A B C I -> coplanaires D E F I) ->\n    confondus (plan A B C) (plan D E F).\n \nAxiom\n  def_confondus2 :\n    forall A B C D E F : PO,\n    ~ alignes A B C ->\n    ~ alignes D E F ->\n    confondus (plan A B C) (plan D E F) ->\n    forall I : PO, coplanaires A B C I -> coplanaires D E F I.\n \nLemma non_disjoints_exists :\n forall A B C D E F : PO,\n ~ alignes A B C ->\n ~ alignes D E F ->\n ~ disjoints (plan A B C) (plan D E F) ->\n exists I : PO, coplanaires A B C I /\\ coplanaires D E F I.\nintros A B C D E F H H0 H1; try assumption.\ncut (~ (forall I : PO, ~ (coplanaires A B C I /\\ coplanaires D E F I)));\n intros.\nelim\n not_all_not_ex\n  with\n    (U := PO)\n    (P := fun I : PO => coplanaires A B C I /\\ coplanaires D E F I);\n [ intros I H3; try clear not_all_not_ex; try exact H3 | auto ].\nexists I; auto.\nred in |- *; (intros; apply H1).\napply def_disjoints; auto.\nQed.\n \nTheorem position_relative_plans_paralleles :\n forall A B C D E F : PO,\n ~ alignes A B C ->\n ~ alignes D E F ->\n para_plan_plan (plan A B C) (plan D E F) ->\n disjoints (plan A B C) (plan D E F) \\/ confondus (plan A B C) (plan D E F).\nintros A B C D E F H H0 H3; try assumption.\nintros.\nassert (A <> B); auto with geo.\nassert (D <> E); auto with geo.\nelim (classic (disjoints (plan A B C) (plan D E F))); intros.\nleft; try assumption.\nright; try assumption.\nelim non_disjoints_exists with (3 := H4);\n [ intros I H5; try clear non_disjoints_exists; try exact H3 | auto | auto ].\nelim H5; [ intros H6 H7; try clear H5; try exact H6 ].\napply def_confondus; auto.\nintros J H5; try assumption.\nelim\n plans_paralleles_vecteurs\n  with (A := D) (B := E) (C := F) (D := A) (E := B) (F := C); \n auto.\nintros.\nelim H9; intros c H10; elim H10; intros d H11; try clear H10 H9;\n try exact H11.\nelim H8; intros a H9; elim H9; intros b H10; try clear H9 H8; try exact H10.\nhcoplanaires H5 x k'.\nhcoplanaires H6 x0 k'0.\nhcoplanaires H7 x1 k'1.\napply\n (vecteur_def_coplanaires\n    (k:=x1 + -1 * (x0 * a + k'0 * c) + (x * a + k' * c))\n    (k':=k'1 + -1 * (x0 * b + k'0 * d) + (x * b + k' * d))).\nreplace (vec D J) with\n (add_PP (add_PP (vec D I) (mult_PP (-1) (vec A I))) (vec A J)).\nrewrite H7.\nrewrite H6.\nrewrite H5.\nrewrite H10.\nrewrite H11.\nRingvec.\nRingvec.\napply para_plan_sym; auto.\nQed.\n \nTheorem position_relative_plans_general :\n forall A B C D E F : PO,\n ~ alignes A B C ->\n ~ alignes D E F ->\n (disjoints (plan A B C) (plan D E F) \\/ confondus (plan A B C) (plan D E F)) \\/\n secants (plan A B C) (plan D E F).\nintros.\nassert (A <> B); auto with geo.\nassert (D <> E); auto with geo.\nelim (classic (para_plan_plan (plan A B C) (plan D E F))); intros.\nleft; try assumption.\napply position_relative_plans_paralleles; auto.\nright; try assumption.\nelim\n position_relative_plans\n  with (A := A) (B := B) (C := C) (D := D) (E := E) (F := F);\n [ intros H4; try clear position_relative_plans\n | intros H4; try clear position_relative_plans; auto\n | auto\n | auto ].\ntauto.\nQed.\n \nTheorem position_relative_plans_non_disjoints :\n forall A B C D E F : PO,\n ~ alignes A B C ->\n ~ alignes D E F ->\n ~ disjoints (plan A B C) (plan D E F) ->\n secants (plan A B C) (plan D E F) \\/ confondus (plan A B C) (plan D E F).\nintros.\nelim\n position_relative_plans_general\n  with (A := A) (B := B) (C := C) (D := D) (E := E) (F := F);\n [ intros H2; elim H2;\n    [ intros H3; try clear H2 position_relative_plans_general\n    | intros H3; try clear H2 position_relative_plans_general; try exact H3 ]\n | intros H2\n | auto\n | auto ].\nelim H2; [ intros H4; try clear H2 | intros H4; try clear H2; try exact H4 ].\ntauto.\nright; try assumption.\nelim H2; [ intros H4; try clear H2; try exact H4 | intros H4; try clear H2 ].\ntauto.\nright; try assumption.\nleft; try assumption.\nQed.", "meta": {"author": "coq-community", "repo": "HighSchoolGeometry", "sha": "bbf0083ff9b228e873a7de972ee3190dbd229ead", "save_path": "github-repos/coq/coq-community-HighSchoolGeometry", "path": "github-repos/coq/coq-community-HighSchoolGeometry/HighSchoolGeometry-bbf0083ff9b228e873a7de972ee3190dbd229ead/theories/Plan_espace.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24338980745168254}}
{"text": "Require Import sem_common.\n\nOpen Scope code_scope.\n\nLemma semacc_new_fundation:\n  forall s P a msgq mq a' msgq' mq' n wls i x2 x3 x4 qid b tcbls,\n    s |= AEventData a msgq ** P ->\n    RLH_ECBData_P msgq mq ->\n    R_ECB_ETbl_P qid (a,b) tcbls ->\n    a = (V$OS_EVENT_TYPE_SEM :: Vint32 i :: Vint32 n :: x2 :: x3 :: x4 :: nil) ->\n    msgq = DSem n ->\n    mq = (abssem n, wls) ->\n    Int.ltu Int.zero n = true ->\n    a' = (V$OS_EVENT_TYPE_SEM :: Vint32 i :: Vint32 (n-ᵢ$ 1)  :: x2 :: x3 :: x4 :: nil) ->\n    msgq' = DSem (n-ᵢ$ 1) ->\n    mq' = (abssem (n-ᵢ$ 1), wls) ->\n    s |= AEventData a' msgq' **\n         [| RLH_ECBData_P msgq' mq' |] ** \n         [| R_ECB_ETbl_P qid (a',b) tcbls |] ** P. \n  intros.\n  sep pauto.\n  unfold AEventData in *.\n  sep pauto.\n  \n\n  apply semacc_ltu_trans; auto.\n  unfold RLH_ECBData_P in *.\n  destruct H0.\n  split.\n  auto.  \n  unfold RH_ECB_P in *.\n  destruct H2.\n  split.\n  intros.\n  apply H2; auto.\n  intros.\n  apply H2 in H5.\n  tryfalse.\nQed.\n\n\nLemma semacc_RH_TCBList_ECBList_P_hold:\n  forall mqls tcbls ct a n wl,\n    RH_TCBList_ECBList_P mqls tcbls ct ->\n    get mqls a = Some (abssem n, wl) ->\n    Int.ltu Int.zero n = true ->\n    RH_TCBList_ECBList_P \n      (set mqls a (abssem (Int.sub n Int.one), wl)) tcbls ct.\n  intros.\n  unfold RH_TCBList_ECBList_P in *.\n  destruct H as [Hq [Hsem [Hmbox Hmutex]]] .\n  intuition.\n\n\n(***************** Q begin ************)\n\n  unfold RH_TCBList_ECBList_Q_P in *.\n  destruct Hq as [F1 F2].\n  intuition.\n  destruct (dec a eid) eqn:Feq.\n  subst.\n  match goal with\n    | H: get (set _ _ _) _ = _ |- _ =>\n        rewrite set_a_get_a in H; tryfalse; auto\n  end.\n\n  eapply F1.\n  split; \n    [ rewrite set_a_get_a' in H2; eauto\n    | eauto].\n\n  destruct (dec a eid) eqn:Feq.\n  subst.\n  match goal with\n    | H: get _ _ = _ |- _ =>\n        apply F2 in H; mytac; tryfalse'\n  end.\n      \n  rewrite set_a_get_a'; \n    [ eapply F2; eauto\n    | auto].\n(**************** Q end ************)  \n\n  unfold RH_TCBList_ECBList_SEM_P in *.\n  destruct Hsem as [F1 F2].\n  intuition.\n  destruct (dec a eid) eqn:Feq.\n  subst.\n  rewrite set_a_get_a in H2; eauto.\n  inverts H2.\n  eapply F1.\n  split; eauto.\n\n  eapply F1.\n  split;\n    [ rewrite set_a_get_a' in H2; eauto\n    | eauto].\n\n  destruct (dec a eid) eqn:Feq.\n  subst.\n  apply F2 in H; mytac.\n  Ltac gel H :=\n    match type of H with\n      | ?A = ?B =>\n        change ((fun y => y = B) A) in H\n    end.\n  gel H0.\n  rewrite H in H0.\n  inverts H0.\n  rewrite set_a_get_a.\n  do 2 eexists.\n  eauto.\n\n  rewrite set_a_get_a'.\n  apply F2 in H; mytac.\n  do 2 eexists.\n  eauto.\n  auto.\n  \n  unfold RH_TCBList_ECBList_MBOX_P in *.\n  destruct Hmbox as [F1 F2].\n  intuition.\n  destruct (dec a eid) eqn:Feq.\n  subst.\n  match goal with\n    | H: get (set _ _ _) _ = _ |- _ =>\n        rewrite set_a_get_a in H; tryfalse; auto\n  end.\n\n  eapply F1.\n  split; \n    [ rewrite set_a_get_a' in H2; eauto\n    | eauto].\n\n  destruct (dec a eid) eqn:Feq.\n  subst.\n  match goal with\n    | H: get _ _ = _ |- _ =>\n        apply F2 in H; mytac; tryfalse'\n  end.\n      \n  rewrite set_a_get_a'; \n    [ eapply F2; eauto\n    | auto].\n\n\n  unfold RH_TCBList_ECBList_MUTEX_P in *.\n  destruct Hmutex as [F1 F2].\n  swallow; intros.\n  \n  destruct (dec a eid) eqn:Feq.\n  destruct H.\n  subst.\n  match goal with\n    | H: get (set _ _ _) _ = _ |- _ =>\n        rewrite set_a_get_a in H; tryfalse; auto\n  end.\n\n  eapply F1.\n  destruct H.\n  split; \n    [ rewrite set_a_get_a' in e; eauto\n    | eauto].\n\n  destruct (dec a eid) eqn:Feq.\n  subst.\n  match goal with\n    | H: get _ _ = _ |- _ =>\n        apply F2 in H; mytac; tryfalse'\n  end.\n      \n  rewrite set_a_get_a'; \n    [ eapply F2; eauto\n    | auto].\n\n  eapply Mutex_owner_set; eauto.\n  intro; mytac.\n  tryfalse.\n  mytac.\nQed.\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/ucos_lib/semacc_pure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24338980745168254}}
{"text": "Set Implicit Arguments.\n\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\n\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Axioms.\n\nFrom PromisingLib Require Import Event.\n\nRequire Import FoldN.\nRequire Import Knowledge.\nRequire Import Opt2.\n\nRequire Import ITreeLang.\n\nRequire Import DeadStoreElim.\n\n\n\n\n\nGlobal Program Instance le_PreOrder: PreOrder le.\nNext Obligation.\nProof.\n  eapply PreOrder_Reflexive. Unshelve.\n  apply (@MLattice.le_PreOrder ThreeML).\nQed.\nNext Obligation.\nProof.\n  eapply PreOrder_Transitive. Unshelve.\n  apply (@MLattice.le_PreOrder ThreeML).\nQed.\n\nGlobal Program Instance le_PartialOrder: PartialOrder eq le.\nNext Obligation.\nProof.\n  unfold relation_equivalence, relation_conjunction.\n  unfold predicate_equivalence, predicate_intersection.\n  unfold pointwise_lifting, pointwise_extension.\n  i. split; i.\n  - clarify. split; refl.\n  - des. unfold flip in H0. eapply antisymmetry; eauto.\n    Unshelve. auto. eapply partial_order_antisym.\n    eapply (@MLattice.le_PartialOrder ThreeML).\nQed.\n\n\n\nSection ANALYSIS.\n\n  Lemma ord_inv1:\n    forall o, (Ordering.le o Ordering.strong_relaxed) \\/\n         (Ordering.le Ordering.acqrel o).\n  Proof. i. destruct o; auto. Qed.\n\n  Lemma update_load_ord1:\n    forall ul o l t\n      (ORD: Ordering.le o Ordering.strong_relaxed),\n      update_load ul o l t = (if (Loc.eqb ul l) then none else t).\n  Proof. i. unfold update_load. des_ifs. Qed.\n\n  Lemma update_load_ord1f:\n    forall ul o mp\n      (ORD: Ordering.le o Ordering.strong_relaxed),\n      (fun p0: Loc.t => update_load ul o p0 (mp p0)) = fun p0 => (if (Loc.eqb ul p0) then none else (mp p0)).\n  Proof. i. extensionality p0. apply update_load_ord1; auto. Qed.\n\n  Lemma update_load_ord2:\n    forall ul o l t\n      (ORD: Ordering.le Ordering.acqrel o),\n      update_load ul o l t = (if (Loc.eqb ul l) then none else (acq_flag t)).\n  Proof. i. unfold update_load. destruct o; ss; clarify. Qed.\n\n  Lemma update_load_ord2f:\n    forall ul o mp\n      (ORD: Ordering.le Ordering.acqrel o),\n      (fun p0: Loc.t => update_load ul o p0 (mp p0)) = fun p0 => (if (Loc.eqb ul p0) then none else (acq_flag (mp p0))).\n  Proof. i. extensionality p0. apply update_load_ord2; auto. Qed.\n\n\n  Lemma ord_inv1':\n    forall o, (Ordering.le o Ordering.na) \\/\n         (Ordering.le Ordering.plain o).\n  Proof. i. destruct o; auto. Qed.\n\n  Lemma update_read_ord1:\n    forall ul o l t\n      (ORD: Ordering.le o Ordering.na),\n      update_read ul o l t = (if (Loc.eqb ul l) then none else t).\n  Proof. i. unfold update_read. des_ifs. Qed.\n\n  Lemma update_read_ord1f:\n    forall ul o mp\n      (ORD: Ordering.le o Ordering.na),\n      (fun p0: Loc.t => update_read ul o p0 (mp p0)) = fun p0 => (if (Loc.eqb ul p0) then none else (mp p0)).\n  Proof. i. extensionality p0. apply update_read_ord1; auto. Qed.\n\n  Lemma update_read_ord2:\n    forall ul o l t\n      (ORD: Ordering.le Ordering.plain o),\n      update_read ul o l t = (if (Loc.eqb ul l) then none else (acq_flag t)).\n  Proof. i. unfold update_read. destruct o; ss; clarify. Qed.\n\n  Lemma update_read_ord2f:\n    forall ul o mp\n      (ORD: Ordering.le Ordering.plain o),\n      (fun p0: Loc.t => update_read ul o p0 (mp p0)) = fun p0 => (if (Loc.eqb ul p0) then none else (acq_flag (mp p0))).\n  Proof. i. extensionality p0. apply update_read_ord2; auto. Qed.\n\n\n\n  Lemma ord_inv2:\n    forall o, (Ordering.le o Ordering.na) \\/\n         (Ordering.le Ordering.plain o)%bool.\n  Proof. i. destruct o; auto. Qed.\n\n  Lemma update_store_ord1:\n    forall ul o l t\n      (ORD: Ordering.le o Ordering.na),\n      update_store ul o l t = if (Loc.eqb ul l) then full else t.\n  Proof. i. unfold update_store. des_ifs. Qed.\n\n  Lemma update_store_ord1f:\n    forall ul o mp\n      (ORD: Ordering.le o Ordering.na),\n      (fun p0: Loc.t => update_store ul o p0 (mp p0)) = fun p0 => (if (Loc.eqb ul p0) then full else (mp p0)).\n  Proof. i. extensionality p0. apply update_store_ord1; auto. Qed.\n\n  Lemma update_store_ord2:\n    forall ul o l t\n      (ORD: (Ordering.le Ordering.plain o && Ordering.le o Ordering.na)%bool),\n      update_store ul o l t = (if (Loc.eqb ul l) then none else t).\n  Proof. i. destruct o; ss; clarify. Qed.\n\n  Lemma update_store_ord2f:\n    forall ul o mp\n      (ORD: (Ordering.le Ordering.plain o && Ordering.le o Ordering.na)%bool),\n      (fun p0: Loc.t => update_store ul o p0 (mp p0)) = fun p0 => (if (Loc.eqb ul p0) then none else (mp p0)).\n  Proof. i. extensionality p0. apply update_store_ord2; auto. Qed.\n\n  Lemma update_store_ord3:\n    forall ul o l t\n      (ORD: Ordering.le Ordering.plain o),\n      update_store ul o l t = (if (Loc.eqb ul l) then none else (rel_flag t)).\n  Proof. i. destruct o; ss; clarify. Qed.\n\n  Lemma update_store_ord3f:\n    forall ul o mp\n      (ORD: Ordering.le Ordering.plain o),\n      (fun p0: Loc.t => update_store ul o p0 (mp p0)) = fun p0 => (if (Loc.eqb ul p0) then none else (rel_flag (mp p0))).\n  Proof. i. extensionality p0. apply update_store_ord3; auto. Qed.\n\n\n\n  Lemma ord_inv3:\n    forall o, (Ordering.le o Ordering.strong_relaxed) \\/\n         (Ordering.le Ordering.acqrel o).\n  Proof. i. destruct o; auto. Qed.\n\n  Lemma update_fence_r_ord1:\n    forall o l t\n      (ORD: Ordering.le o Ordering.strong_relaxed),\n      update_fence_r o l t = t.\n  Proof. i. destruct o; ss; clarify. Qed.\n\n  Lemma update_fence_r_ord1f:\n    forall o mp\n      (ORD: Ordering.le o Ordering.strong_relaxed),\n      (fun p0: Loc.t => update_fence_r o p0 (mp p0)) = fun p0 => mp p0.\n  Proof. i. extensionality p0. apply update_fence_r_ord1; auto. Qed.\n\n  Lemma update_fence_r_ord2:\n    forall o l t\n      (ORD: (Ordering.le Ordering.acqrel o)),\n      update_fence_r o l t = (acq_flag t).\n  Proof. i. destruct o; ss; clarify. Qed.\n\n  Lemma update_fence_r_ord2f:\n    forall o mp\n      (ORD: (Ordering.le Ordering.acqrel o)),\n      (fun p0: Loc.t => update_fence_r o p0 (mp p0)) = fun p0 => (acq_flag (mp p0)).\n  Proof. i. extensionality p0. apply update_fence_r_ord2; auto. Qed.\n\n\n  Lemma ord_inv3':\n    forall o, (Ordering.le o Ordering.na) \\/\n         (Ordering.le Ordering.plain o && Ordering.le o Ordering.acqrel)%bool \\/\n         (Ordering.le Ordering.seqcst o).\n  Proof. i. destruct o; auto. Qed.\n\n  Lemma update_fence_w_ord1:\n    forall o l t\n      (ORD: Ordering.le o Ordering.na),\n      update_fence_w o l t = t.\n  Proof. i. destruct o; ss; clarify. Qed.\n\n  Lemma update_fence_w_ord1f:\n    forall o mp\n      (ORD: Ordering.le o Ordering.na),\n      (fun p0: Loc.t => update_fence_w o p0 (mp p0)) = fun p0 => mp p0.\n  Proof. i. extensionality p0. apply update_fence_w_ord1; auto. Qed.\n\n  Lemma update_fence_w_ord2:\n    forall o l t\n      (ORD: (Ordering.le Ordering.plain o && Ordering.le o Ordering.acqrel)%bool),\n      update_fence_w o l t = (rel_flag t).\n  Proof. i. destruct o; ss; clarify. Qed.\n\n  Lemma update_fence_w_ord2f:\n    forall o mp\n      (ORD: (Ordering.le Ordering.plain o && Ordering.le o Ordering.acqrel)%bool),\n      (fun p0: Loc.t => update_fence_w o p0 (mp p0)) = fun p0 => (rel_flag (mp p0)).\n  Proof. i. extensionality p0. apply update_fence_w_ord2; auto. Qed.\n\n  Lemma update_fence_w_ord3:\n    forall o l t\n      (ORD: Ordering.le Ordering.seqcst o),\n      update_fence_w o l t = (rel_flag (acq_flag t)).\n  Proof. i. destruct o; ss; clarify. Qed.\n\n  Lemma update_fence_w_ord3f:\n    forall o mp\n      (ORD: Ordering.le Ordering.seqcst o),\n      (fun p0: Loc.t => update_fence_w o p0 (mp p0)) = fun p0 => (rel_flag (acq_flag (mp p0))).\n  Proof. i. extensionality p0. apply update_fence_w_ord3; auto. Qed.\n\n\n  Lemma rel_flag_mon:\n    forall k1 k2 (LE: le k1 k2), le (rel_flag k1) (rel_flag k2).\n  Proof.\n    i. unfold rel_flag. des_ifs; ss; clarify.\n  Qed.\n\n  Lemma rel_flag_le:\n    forall k, le (rel_flag k) k.\n  Proof.\n    i. unfold rel_flag. des_ifs; ss; clarify.\n  Qed.\n\n  Lemma acq_flag_mon:\n    forall k1 k2 (LE: le k1 k2), le (acq_flag k1) (acq_flag k2).\n  Proof.\n    i. unfold acq_flag. des_ifs; ss; clarify.\n  Qed.\n\n  Lemma acq_flag_le:\n    forall k, le (acq_flag k) k.\n  Proof.\n    i. unfold acq_flag. des_ifs; ss; clarify.\n  Qed.\n\n\n\n  Lemma update_load_kspec:\n    forall l1 l2 o, knowledge_spec le bot (update_load l1 o l2).\n  Proof.\n    i. hexploit (ord_inv1 o). i. des.\n    - unfold knowledge_spec. split; red; i.\n      + rewrite ! update_load_ord1; auto. des_ifs.\n      + rewrite ! update_load_ord1; auto. des_ifs. right; refl. left; refl.\n    - unfold knowledge_spec. split; red; i.\n      + rewrite ! update_load_ord2; auto. des_ifs. apply acq_flag_mon; auto.\n      + rewrite ! update_load_ord2; auto. des_ifs. right; refl. left; apply acq_flag_le.\n  Qed.\n\n  Lemma update_read_kspec:\n    forall l1 l2 o, knowledge_spec le bot (update_read l1 o l2).\n  Proof.\n    i. hexploit (ord_inv1' o). i. des.\n    - unfold knowledge_spec. split; red; i.\n      + rewrite ! update_read_ord1; auto. des_ifs.\n      + rewrite ! update_read_ord1; auto. des_ifs. right; refl. left; refl.\n    - unfold knowledge_spec. split; red; i.\n      + rewrite ! update_read_ord2; auto. des_ifs. apply acq_flag_mon; auto.\n      + rewrite ! update_read_ord2; auto. des_ifs. right; refl. left; apply acq_flag_le.\n  Qed.\n\n  Lemma update_store_kspec:\n    forall l1 l2 o, knowledge_spec le bot (update_store l1 o l2).\n  Proof.\n    i. hexploit (ord_inv2 o). i; des.\n    - unfold knowledge_spec. split; red; i.\n      + rewrite ! update_store_ord1; auto. des_ifs.\n      + rewrite ! update_store_ord1; auto. des_ifs.\n        right; refl. left; refl.\n    - unfold knowledge_spec. split; red; i.\n      + rewrite ! update_store_ord3; auto. des_ifs.\n        apply rel_flag_mon; auto.\n      + rewrite ! update_store_ord3; auto. des_ifs.\n        right; refl. left; apply rel_flag_le; auto.\n  Qed.\n\n  Lemma update_fence_r_kspec:\n    forall l o, knowledge_spec le bot (update_fence_r o l).\n  Proof.\n    i. hexploit (ord_inv3 o). i; des.\n    - unfold knowledge_spec. split; red; i.\n      + rewrite ! update_fence_r_ord1; auto.\n      + rewrite ! update_fence_r_ord1; auto. left; refl.\n    - unfold knowledge_spec. split; red; i.\n      + rewrite ! update_fence_r_ord2; auto. apply acq_flag_mon; auto.\n      + rewrite ! update_fence_r_ord2; auto. left; apply acq_flag_le.\n  Qed.\n\n  Lemma update_fence_w_kspec:\n    forall l o, knowledge_spec le bot (update_fence_w o l).\n  Proof.\n    i. hexploit (ord_inv3' o). i; des.\n    - unfold knowledge_spec. split; red; i.\n      + rewrite ! update_fence_w_ord1; auto.\n      + rewrite ! update_fence_w_ord1; auto. left; refl.\n    - unfold knowledge_spec. split; red; i.\n      + rewrite ! update_fence_w_ord2; auto. apply rel_flag_mon; auto.\n      + rewrite ! update_fence_w_ord2; auto. left; apply rel_flag_le.\n    - unfold knowledge_spec. split; red; i.\n      + rewrite ! update_fence_w_ord3; auto. apply rel_flag_mon. apply acq_flag_mon. auto.\n      + rewrite ! update_fence_w_ord3; auto. left. etrans. apply rel_flag_le. apply acq_flag_le.\n  Qed.\n\n  Lemma update_inst_kspec:\n    forall (i: Inst.t) (l: Loc.t), knowledge_spec le bot (update_inst i l).\n  Proof.\n    i. destruct i.\n    1,2,7,8,9: unfold knowledge_spec; split; red; i; ss; clarify; auto.\n    all: try (left; refl).\n    all: unfold update_inst; ss.\n    apply update_load_kspec.\n    apply update_store_kspec.\n    - eapply kspec_app; eauto. apply le_PreOrder. apply bot_spec. apply update_read_kspec. apply update_store_kspec.\n    - eapply kspec_app; eauto. apply le_PreOrder. apply bot_spec. apply update_fence_r_kspec. apply update_fence_w_kspec.\n  Qed.\n\n  Lemma update_inst_sspec:\n    forall p k, eq (update_inst Inst.skip p k) k.\n  Proof. ss. Qed.\n\n  Lemma update_inst_mon: forall (i: Inst.t) p d1 d2 (LE: le d1 d2), le (update_inst i p d1) (update_inst i p d2).\n  Proof.\n    i. hexploit update_inst_kspec. i. unfold knowledge_spec in H. des. eapply MON; eauto.\n  Qed.\n\nEnd ANALYSIS.\n\n\n\n\n\nSection ALG.\n\n  Definition DSE_do_opt (mp: Data Three Loc.t) (i: Inst.t) : Prop :=\n    match i with\n    | Inst.store l _ o =>\n      match (mp l), o with\n      | half, Ordering.na\n      | full, Ordering.na => True\n      | _, _ => False\n      end\n    | _ => False\n    end\n  .\n\n  Lemma do_opt_not:\n    forall (i : Inst.t) (data : Data Three Loc.t)\n      (NOOPT: ~ (DSE_do_opt data i)),\n      DSE_opt_inst data i = i.\n  Proof.\n    i. destruct i; ss; clarify. des_ifs; ss; clarify.\n  Qed.\n\n  Lemma do_opt_not_skip:\n    forall data, not (DSE_do_opt data Inst.skip).\n  Proof. ss. Qed.\n\n\n\n  Definition DSE_opt2: Opt2.t :=\n    Opt2.mk_opt2\n      ThreeML bot bot_spec level\n      update_inst update_inst_mon update_inst_sspec\n      DSE_opt_inst\n      DSE_do_opt do_opt_not do_opt_not_skip\n      strict_order half.\n\n  Definition block_d := Opt2.block_d DSE_opt2.\n\n  Lemma analysis_correct: update_block = block_d.\n  Proof. ss. Qed.\n\n  Lemma opt_correct: DSE_opt_block = Opt2.opt_block DSE_opt2.\n  Proof. ss. Qed.\n\nEnd ALG.\n\nSection FIXPOINT.\n\n  Definition DSE_fix2: FixOpt2.t :=\n    @FixOpt2.mk_fix2\n      ThreeML bot bot_spec level level_grounded\n      Loc.t update_inst update_inst_kspec update_inst_sspec\n      half.\n\n\n  Lemma DSE_kspec2: forall blk p, knowledge_spec (MLattice.le ThreeML) bot (update_block blk p).\n  Proof.\n    i. eapply (@update_block_is_knowledge DSE_fix2).\n  Qed.\n\n  Theorem block_d_fix: forall blk f (FUN: f = block_d blk) p,\n      @n_fix Three (MLattice.eq ThreeML) (MLattice.eq_Equiv ThreeML) (f p) (S level).\n  Proof.\n    i. eapply (@update_block_fix DSE_fix2). eauto.\n  Qed.\n\n  Theorem block_d_dec: forall blk p d f (FUN: f = block_d blk p), (MLattice.le ThreeML) (f (f d)) (f d).\n  Proof.\n    i. clarify. ss. rewrite <- analysis_correct.\n    hexploit (knowledge_le_n eq_leibniz (@MLattice.le_PartialOrder ThreeML) bot_spec 1 (DSE_kspec2 blk p)).\n    i; ss. eauto.\n  Qed.\n\nEnd FIXPOINT.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/optimizer/DeadStoreElimProof1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24338980745168254}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** RTL function inlining *)\n\nRequire Import Coqlib.\nRequire Import Wfsimpl.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\n\nLtac xomega := unfold Plt, Ple in *; zify; omega.\n\nSection WITHEF.\nContext `{Hsc: SyntaxConfiguration}.\n\n(** ** Environment of inlinable functions *)\n\n(** We maintain a mapping from function names to their definitions.\n  In this mapping, we only include internal functions that are eligible for\n  inlining, as determined by the external heuristic\n  [should_inline]. *)\n\nDefinition funenv : Type := PTree.t function.\n\nDefinition size_fenv (fenv: funenv) := PTree_Properties.cardinal fenv.\n\nParameter should_inline: ident -> function -> bool.\n\nDefinition add_globdef (fenv: funenv) (idg: ident * globdef fundef unit) : funenv :=\n  match idg with\n  | (id, Gfun (Internal f)) =>\n      if should_inline id f\n      then PTree.set id f fenv\n      else PTree.remove id fenv\n  | (id, _) =>\n      PTree.remove id fenv\n  end.\n\nDefinition funenv_program (p: program) : funenv :=\n  List.fold_left add_globdef p.(prog_defs) (PTree.empty function).\n\n(** Resources used by a function. *)\n\n(** Maximum PC (node number) in the CFG of a function.  All nodes of\n  the CFG of [f] are between 1 and [max_pc_function f] (inclusive). *)\n\nDefinition max_pc_function (f: function) :=\n  PTree.fold (fun m pc i => Pmax m pc) f.(fn_code) 1%positive.\n\n(** Maximum pseudo-register defined in a function.  All results of\n  an instruction of [f], as well as all parameters of [f], are between\n  1 and [max_def_function] (inclusive). *)\n\nDefinition max_def_instr (i: instruction) :=\n  match i with\n  | Iop op args res s => res\n  | Iload chunk addr args dst s => dst\n  | Icall sg ros args res s => res\n  | Ibuiltin ef args res s => res\n  | _ => 1%positive\n  end.\n\nDefinition max_def_function (f: function) :=\n  Pmax\n    (PTree.fold (fun m pc i => Pmax m (max_def_instr i)) f.(fn_code) 1%positive)\n    (List.fold_left (fun m r => Pmax m r) f.(fn_params) 1%positive).\n\n(** State monad *)\n\n(** To construct incrementally the CFG of a function after inlining,\n  we use a state monad similar to that used in module [RTLgen].\n  It records the current state of the CFG, plus counters to generate\n  fresh pseudo-registers and fresh CFG nodes.  It also records the\n  stack size needed for the inlined function. *)\n\nRecord state : Type := mkstate {\n  st_nextreg: positive;                 (**r last used pseudo-register *)\n  st_nextnode: positive;                (**r last used CFG node *)\n  st_code: code;                        (**r current CFG  *)\n  st_stksize: Z                         (**r current stack size *)\n}.\n\n(** Monotone evolution of the state. *)\n\nInductive sincr (s1 s2: state) : Prop :=\n  Sincr (NEXTREG: Ple s1.(st_nextreg) s2.(st_nextreg))\n        (NEXTNODE: Ple s1.(st_nextnode) s2.(st_nextnode))\n        (STKSIZE: s1.(st_stksize) <= s2.(st_stksize)).\n\nRemark sincr_refl: forall s, sincr s s.\nProof.\n  intros; constructor; xomega.\nQed.\n\nLemma sincr_trans: forall s1 s2 s3, sincr s1 s2 -> sincr s2 s3 -> sincr s1 s3.\nProof.\n  intros. inv H; inv H0. constructor; xomega.\nQed.\n\n(** Dependently-typed state monad, ensuring that the final state is\n  greater or equal (in the sense of predicate [sincr] above) than\n  the initial state. *)\n\nInductive res {A: Type} {s: state}: Type := R (x: A) (s': state) (I: sincr s s').\n\nDefinition mon (A: Type) : Type := forall (s: state), @res A s.\n\n(** Operations on this monad. *)\n\nDefinition ret {A: Type} (x: A): mon A :=\n  fun s => R x s (sincr_refl s).\n\nDefinition bind {A B: Type} (x: mon A) (f: A -> mon B): mon B :=\n  fun s1 => match x s1 with R vx s2 I1 =>\n              match f vx s2 with R vy s3 I2 =>\n                R vy s3 (sincr_trans s1 s2 s3 I1 I2)\n              end\n            end.\n\nNotation \"'do' X <- A ; B\" := (bind A (fun X => B))\n   (at level 200, X ident, A at level 100, B at level 200).\n\nDefinition initstate :=\n  mkstate 1%positive 1%positive (PTree.empty instruction) 0.\n\nProgram Definition set_instr (pc: node) (i: instruction): mon unit :=\n  fun s => \n    R tt\n      (mkstate s.(st_nextreg) s.(st_nextnode) (PTree.set pc i s.(st_code)) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition add_instr (i: instruction): mon node :=\n  fun s =>\n    let pc := Psucc s.(st_nextnode) in\n    R pc\n      (mkstate s.(st_nextreg) pc (PTree.set pc i s.(st_code)) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition reserve_nodes (numnodes: positive): mon positive :=\n  fun s =>\n    R s.(st_nextnode)\n      (mkstate s.(st_nextreg) (Pplus s.(st_nextnode) numnodes) s.(st_code) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition reserve_regs (numregs: positive): mon positive :=\n  fun s =>\n    R s.(st_nextreg)\n      (mkstate (Pplus s.(st_nextreg) numregs) s.(st_nextnode) s.(st_code) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition request_stack (sz: Z): mon unit :=\n  fun s => \n    R tt\n      (mkstate s.(st_nextreg) s.(st_nextnode) s.(st_code) (Zmax s.(st_stksize) sz))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nFixpoint mlist_iter2 {A B: Type} (f: A -> B -> mon unit) (l: list (A*B)): mon unit :=\n  match l with\n  | nil => ret tt\n  | (x,y) :: l' => do z <- f x y; mlist_iter2 f l'\n  end.\n\n(** ** Inlining contexts *)\n\n(** A context describes how to insert the CFG for a source function into\n  the CFG for the function after inlining:\n- a source instruction at PC [n] is relocated to PC [n + ctx.(dpc)];\n- all pseudo-registers of this instruction are shifted by [ctx.(dreg)];\n- all stack references are shifted by [ctx.(dstk)];\n- \"return\" instructions are transformed into \"return\" or \"move\" instructions\n  as governed by [ctx.(retinfo)].\n*)\n\nRecord context: Type := mkcontext {\n  dpc: positive;                        (**r offset for PCs *)\n  dreg: positive;                       (**r offset for pseudo-regs *)\n  dstk: Z;                              (**r offset for stack references *)\n  mreg: positive;                       (**r max pseudo-reg number *)\n  mstk: Z;                              (**r original stack block size *)\n  retinfo: option(node * reg)           (**r where to branch on return *)\n                                        (**r and deposit return value *)\n}.\n\n(** The following functions \"shift\" (relocate) PCs, registers, operations, etc. *)\n\nDefinition spc (ctx: context) (pc: node) := Pplus pc ctx.(dpc).\n\nDefinition sreg (ctx: context) (r: reg) := Pplus r ctx.(dreg).\n\nDefinition sregs (ctx: context) (rl: list reg) := List.map (sreg ctx) rl.\n\nDefinition sros (ctx: context) (ros: reg + ident) := sum_left_map (sreg ctx) ros.\n\nDefinition sop (ctx: context) (op: operation) :=\n  shift_stack_operation (Int.repr ctx.(dstk)) op.\n\nDefinition saddr (ctx: context) (addr: addressing) :=\n  shift_stack_addressing (Int.repr ctx.(dstk)) addr.\n\n(** The initial context, used to copy the CFG of a toplevel function. *)\n\nDefinition initcontext (dpc dreg nreg: positive) (sz: Z) :=\n  {| dpc := dpc;\n     dreg := dreg;\n     dstk := 0;\n     mreg := nreg;\n     mstk := Zmax sz 0;\n     retinfo := None |}.\n\n(** The context used to inline a call to another function. *)\n\nDefinition min_alignment (sz: Z) :=\n  if zle sz 1 then 1\n  else if zle sz 2 then 2\n  else if zle sz 4 then 4 else 8.\n\nDefinition callcontext (ctx: context)\n                      (dpc dreg nreg: positive) (sz: Z)\n                      (retpc: node) (retreg: reg) :=\n  {| dpc := dpc;\n     dreg := dreg;\n     dstk := align (ctx.(dstk) + ctx.(mstk)) (min_alignment sz);\n     mreg := nreg;\n     mstk := Zmax sz 0;\n     retinfo := Some (spc ctx retpc, sreg ctx retreg) |}.\n\n(** The context used to inline a tail call to another function. *)\n\nDefinition tailcontext (ctx: context) (dpc dreg nreg: positive) (sz: Z) :=\n  {| dpc := dpc;\n     dreg := dreg;\n     dstk := align ctx.(dstk) (min_alignment sz);\n     mreg := nreg;\n     mstk := Zmax sz 0;\n     retinfo := ctx.(retinfo) |}.\n\n(** ** Recursive expansion and copying of a CFG *)\n\n(** Insert \"move\" instructions to copy the arguments of an inlined\n    function into its parameters. *)\n\nFixpoint add_moves (srcs dsts: list reg) (succ: node): mon node :=\n  match srcs, dsts with\n  | s1 :: sl, d1 :: dl =>\n      do n <- add_instr (Iop Omove (s1 :: nil) d1 succ);\n      add_moves sl dl n\n  | _, _ =>\n      ret succ\n  end.\n\n(** To prevent infinite inlining of a recursive function, when we\n  inline the body of a function [f], this function is removed from the\n  environment of inlinable functions and therefore becomes ineligible\n  for inlining.  This decreases the size (number of entries) of the\n  environment and guarantees termination.  Inlining is, therefore,\n  presented as a well-founded recursion over the size of the environment. *)\n\nSection EXPAND_CFG.\n\nVariable fenv: funenv.\n\n(** The [rec] parameter is the recursor: [rec fenv' P ctx f] copies \n  the body of function [f], with inline expansion within, as governed\n  by context [ctx].  It can only be called for function environments\n  [fenv'] strictly smaller than the current environment [fenv]. *)\n\nVariable rec: forall fenv', (size_fenv fenv' < size_fenv fenv)%nat -> context -> function -> mon unit.\n\n(** Given a register-or-symbol [ros], can we inline the corresponding call? *)\n\nInductive inline_decision (ros: reg + ident) : Type :=\n  | Cannot_inline\n  | Can_inline (id: ident) (f: function) (P: ros = inr reg id) (Q: fenv!id = Some f).\n\nProgram Definition can_inline (ros: reg + ident): inline_decision ros :=\n  match ros with\n  | inl r => Cannot_inline _\n  | inr id => match fenv!id with Some f => Can_inline _ id f _ _ | None => Cannot_inline _ end\n  end.\n\n(** Inlining of a call to function [f].  An appropriate context is\n  created, then the CFG of [f] is recursively copied, then moves\n  are inserted to copy the arguments of the call to the parameters of [f]. *)\n\nDefinition inline_function (ctx: context) (id: ident) (f: function)\n                           (P: PTree.get id fenv = Some f)\n                           (args: list reg)\n                           (retpc: node) (retreg: reg) : mon node :=\n  let npc := max_pc_function f in\n  let nreg := max_def_function f in\n  do dpc <- reserve_nodes npc;\n  do dreg <- reserve_regs nreg;\n  let ctx' := callcontext ctx dpc dreg nreg f.(fn_stacksize) retpc retreg in \n  do x <- rec (PTree.remove id fenv) (PTree_Properties.cardinal_remove P) ctx' f;\n  add_moves (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)).\n\n(** Inlining of a tail call to function [f].  Similar to [inline_function],\n  but the new context is different. *)\n\nDefinition inline_tail_function (ctx: context) (id: ident) (f: function)\n                               (P: PTree.get id fenv = Some f)\n                               (args: list reg): mon node :=\n  let npc := max_pc_function f in\n  let nreg := max_def_function f in\n  do dpc <- reserve_nodes npc;\n  do dreg <- reserve_regs nreg;\n  let ctx' := tailcontext ctx dpc dreg nreg f.(fn_stacksize) in \n  do x <- rec (PTree.remove id fenv) (PTree_Properties.cardinal_remove P) ctx' f;\n  add_moves (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)).\n\n(** The instruction generated for a [Ireturn] instruction found in an\n  inlined function body. *)\n\nDefinition inline_return (ctx: context) (or: option reg) (retinfo: node * reg): instruction :=\n  match retinfo, or with\n  | (retpc, retreg), Some r => Iop Omove (sreg ctx r :: nil) retreg retpc\n  | (retpc, retreg), None   => Inop retpc\n  end.\n\n(** Expansion and copying of an instruction.  For most instructions,\n  its registers and successor PC are shifted as per the context [ctx],\n  then the instruction is inserted in the final CFG at its final position\n  [spc ctx pc].  \n\n  [Icall] instructions are either replaced by a \"goto\" to the expansion\n  of the called function, or shifted as described above.\n\n  [Itailcall] instructions are similar, with one additional case.  If\n  the [Itailcall] occurs in the body of an inlined function, and\n  cannot be inlined itself, it must be turned into an [Icall]\n  instruction that branches to the return point of the inlined\n  function.\n\n  Finally, [Ireturn] instructions within an inlined function are\n  turned into a \"move\" or \"goto\" that stores the result, if any,\n  into the destination register, then branches back to the successor\n  of the inlined call. *)\n\nDefinition expand_instr (ctx: context) (pc: node) (i: instruction): mon unit :=\n  match i with\n  | Inop s =>\n      set_instr (spc ctx pc) (Inop (spc ctx s))\n  | Iop op args res s =>\n      set_instr (spc ctx pc)\n                (Iop (sop ctx op) (sregs ctx args) (sreg ctx res) (spc ctx s))\n  | Iload chunk addr args dst s =>\n      set_instr (spc ctx pc)\n                (Iload chunk (saddr ctx addr) (sregs ctx args) (sreg ctx dst) (spc ctx s))\n  | Istore chunk addr args src s =>\n      set_instr (spc ctx pc)\n                (Istore chunk (saddr ctx addr) (sregs ctx args) (sreg ctx src) (spc ctx s))\n  | Icall sg ros args res s =>\n      match can_inline ros with\n      | Cannot_inline =>\n          set_instr (spc ctx pc)\n                    (Icall sg (sros ctx ros) (sregs ctx args) (sreg ctx res) (spc ctx s))\n      | Can_inline id f P Q =>\n          do n <- inline_function ctx id f Q args s res;\n          set_instr (spc ctx pc) (Inop n)\n      end\n  | Itailcall sg ros args =>\n      match can_inline ros with\n      | Cannot_inline =>\n          match ctx.(retinfo) with\n          | None =>\n              set_instr (spc ctx pc)\n                        (Itailcall sg (sros ctx ros) (sregs ctx args))\n          | Some(rpc, rreg) =>\n              set_instr (spc ctx pc)\n                        (Icall sg (sros ctx ros) (sregs ctx args) rreg rpc)\n          end\n      | Can_inline id f P Q =>\n          do n <- inline_tail_function ctx id f Q args;\n          set_instr (spc ctx pc) (Inop n)\n      end          \n  | Ibuiltin ef args res s =>\n      set_instr (spc ctx pc)\n                (Ibuiltin ef (sregs ctx args) (sreg ctx res) (spc ctx s))\n  | Icond cond args s1 s2 =>\n      set_instr (spc ctx pc)\n                (Icond cond (sregs ctx args) (spc ctx s1) (spc ctx s2))\n  | Ijumptable r tbl =>\n      set_instr (spc ctx pc)\n                (Ijumptable (sreg ctx r) (List.map (spc ctx) tbl))\n  | Ireturn or =>\n      match ctx.(retinfo) with\n      | None =>\n          set_instr (spc ctx pc) (Ireturn (option_map (sreg ctx) or))\n      | Some rinfo =>\n          set_instr (spc ctx pc) (inline_return ctx or rinfo)\n      end\n  end.\n\n(** The expansion of a function [f] iteratively expands all its\n  instructions, after recording how much stack it needs. *)\n\nDefinition expand_cfg_rec (ctx: context) (f: function): mon unit :=\n  do x <- request_stack (ctx.(dstk) + ctx.(mstk));\n  mlist_iter2 (expand_instr ctx) (PTree.elements f.(fn_code)).\n\nEnd EXPAND_CFG.\n\n(** Here we \"tie the knot\" of the recursion, taking the fixpoint\n  of [expand_cfg_rec]. *)\n\nDefinition expand_cfg := Fixm size_fenv expand_cfg_rec.\n\n(** Start of the recursion: copy and inline function [f] in the\n  initial context. *)\n\nDefinition expand_function (fenv: funenv) (f: function): mon context :=\n  let npc := max_pc_function f in\n  let nreg := max_def_function f in\n  do dpc <- reserve_nodes npc;\n  do dreg <- reserve_regs nreg;\n  let ctx := initcontext dpc dreg nreg f.(fn_stacksize) in \n  do x <- expand_cfg fenv ctx f;\n  ret ctx.\n\n(** ** Inlining in functions and whole programs. *)\n\nLocal Open Scope string_scope.\n\n(** Inlining can increase the size of the function's stack block.  We must\n  make sure that the new size does not exceed [Int.max_unsigned], otherwise\n  address computations within the stack would overflow and produce incorrect\n  results. *)\n\nDefinition transf_function (fenv: funenv) (f: function) : Errors.res function :=\n  let '(R ctx s _) := expand_function fenv f initstate in\n  if zlt s.(st_stksize) Int.max_unsigned then\n    OK (mkfunction f.(fn_sig) \n                   (sregs ctx f.(fn_params))\n                   s.(st_stksize)\n                   s.(st_code)\n                   (spc ctx f.(fn_entrypoint)))\n  else\n    Error(msg \"Inlining: stack too big\").\n\nDefinition transf_fundef (fenv: funenv) (fd: fundef) : Errors.res fundef :=\n  AST.transf_partial_fundef (transf_function fenv) fd.\n\nDefinition transf_program (p: program): Errors.res program :=\n  let fenv := funenv_program p in\n  AST.transform_partial_program (transf_fundef fenv) p.\n\nEnd WITHEF.\n", "meta": {"author": "jeremie-koenig", "repo": "compcert", "sha": "e58b5a076931637f2e7b13f6e9ba7a47e2cdc437", "save_path": "github-repos/coq/jeremie-koenig-compcert", "path": "github-repos/coq/jeremie-koenig-compcert/compcert-e58b5a076931637f2e7b13f6e9ba7a47e2cdc437/backend/Inlining.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24338980137757824}}
{"text": "(** * Facts about Static Expressions *)\n\nRequire Import hvhdl.Environment.\nRequire Import hvhdl.StaticExpressions.\nRequire Import hvhdl.AbstractSyntax.\nRequire Import hvhdl.SemanticalDomains.\n\nRequire Import hvhdl.proofs.EnvironmentFacts.\n\n(** ** Facts about Locally Static Expressions *)\n\nSection LStatic.\n\nEnd LStatic.\n\n(** ** Facts about Globally Static Expressions *)\n\nSection GStatic.\n\n  Lemma IGStaticExpr_eq_iff_eq_gens :\n    forall {Δ1 Δ2 e},\n      EqGens Δ1 Δ2 ->\n      IGStaticExpr Δ1 e <->\n      IGStaticExpr Δ2 e.\n  Proof.\n    split.\n    (* CASE A -> B *)\n    - induction 1; eauto with hvhdl.\n      eapply IsGStaticGeneric with (t := t) (v := v);\n        rewrite <- H; assumption.\n    (* CASE B -> A *)\n    - induction 1; eauto with hvhdl.\n      eapply IsGStaticGeneric with (t := t) (v := v);\n        rewrite H; assumption.\n  Qed.\n  \nEnd GStatic.\n", "meta": {"author": "viampietro", "repo": "ver-hilecop", "sha": "cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4", "save_path": "github-repos/coq/viampietro-ver-hilecop", "path": "github-repos/coq/viampietro-ver-hilecop/ver-hilecop-cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4/hvhdl/proofs/StaticExpressionsFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.24333894270930437}}
{"text": "Require Import Coq.Bool.Sumbool.\nRequire Import Crypto.Compilers.SmartMap.\nRequire Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Wf.\nRequire Import Crypto.Compilers.WfProofs.\nRequire Import Crypto.Compilers.ExprInversion.\nRequire Import Crypto.Compilers.MapBaseType.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Crypto.Util.Sigma.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.Prod.\n\nSection language.\n  Context {base_type_code1 base_type_code2 : Type}\n          {op1 : flat_type base_type_code1 -> flat_type base_type_code1 -> Type}\n          {op2 : flat_type base_type_code2 -> flat_type base_type_code2 -> Type}\n          (f_base : base_type_code1 -> base_type_code2)\n          (f_op : forall var1 s d,\n              op1 s d\n              -> exprf _ op1 (var:=var1) s\n              -> option (op2 (lift_flat_type f_base s) (lift_flat_type f_base d))).\n\n  Local Hint Constructors wf wff or.\n\n  Local Notation mapf_base_type :=\n    (@mapf_base_type base_type_code1 base_type_code2 op1 op2 f_base f_op).\n  Local Notation map_base_type :=\n    (@map_base_type base_type_code1 base_type_code2 op1 op2 f_base f_op).\n\n  Section with_var.\n    Context {var1 var1' : base_type_code1 -> Type}\n            {var2 var2' : base_type_code2 -> Type}\n            (f_var12 : forall t, var1 t -> var2 (f_base t))\n            (f_var21 : forall t, var2 (f_base t) -> var1 t)\n            (f_var'12 : forall t, var1' t -> var2' (f_base t))\n            (f_var'21 : forall t, var2' (f_base t) -> var1' t)\n            (failb : forall t, exprf _ op2 (var:=var2) (Tbase t))\n            (failb' : forall t, exprf _ op2 (var:=var2') (Tbase t))\n            (Hwf_failb : forall t G, wff G (failb t) (failb' t))\n            (Hwf_f_op : forall G s d opc e1 e2,\n                wff G e1 e2\n                -> f_op var1 s d opc e1 = f_op var1' s d opc e2)\n            (Hvar12 : forall t v, f_var12 t (f_var21 t v) = v)\n            (Hvar'12 : forall t v, f_var'12 t (f_var'21 t v) = v).\n\n    Lemma wff_mapf_base_type G G' {t}\n          (e : exprf base_type_code1 op1 (var:=var1) t)\n          (e' : exprf base_type_code1 op1 (var:=var1') t)\n          (HG : forall t x x',\n              List.In (existT _ t (x, x')) G\n              -> List.In (existT _ (f_base t) (f_var12 _ x, f_var'12 _ x')) G')\n          (Hwf : wff G e e')\n      : wff G'\n            (mapf_base_type f_var12 f_var21 failb e)\n            (mapf_base_type f_var'12 f_var'21 failb' e').\n    Proof.\n      revert dependent G'; induction Hwf;\n        repeat first [ progress simpl in *\n                     | progress intros\n                     | progress inversion_option\n                     | progress subst\n                     | break_innermost_match_step\n                     | progress specialize_by_assumption\n                     | apply wff_SmartPairf_SmartValf\n                     | solve [ eauto using In_flatten_binding_list_untransfer_interp_flat_type ]\n                     | match goal with\n                       | [ |- wff _ _ _ ] => constructor\n                       | [ H : _ |- _ ] => apply H; try setoid_rewrite List.in_app_iff\n                       | [ H : f_op _ ?s ?d ?opc ?e = ?x, H' : f_op _ ?s ?d ?opc ?e' = ?y |- _ ]\n                         => assert (x = y) by (rewrite <- H, <- H'; eauto); clear H'\n                       end\n                     | progress destruct_head'_or ].\n    Qed.\n\n    Lemma wf_map_base_type {t}\n          (e : expr base_type_code1 op1 (var:=var1) t)\n          (e' : expr base_type_code1 op1 (var:=var1') t)\n          (Hwf : wf e e')\n      : wf\n          (map_base_type f_var12 f_var21 failb e)\n          (map_base_type f_var'12 f_var'21 failb' e').\n    Proof.\n      destruct Hwf; constructor; simpl; intros.\n      eapply wff_mapf_base_type; [ | eauto ].\n      eauto using In_flatten_binding_list_untransfer_interp_flat_type.\n    Qed.\n  End with_var.\n\n  Section MapBaseType.\n    Context (failb : forall var t, exprf _ op2 (var:=var) (Tbase t))\n            (Hwf_failb : forall var1 var2 G t, wff G (failb var1 t) (failb var2 t))\n            (Hwf_f_op : forall var1 var1' s d opc G e1 e2,\n                wff G e1 e2\n                -> f_op var1 s d opc e1 = f_op var1' s d opc e2)\n            {t} (e : Expr base_type_code1 op1 t)\n            (Hwf : Wf e).\n\n    Lemma Wf_MapBaseType'\n      : Wf (MapBaseType' f_base f_op failb e).\n    Proof using Hwf Hwf_failb Hwf_f_op.\n      intros var1 var2; apply wf_map_base_type; eauto.\n    Qed.\n\n    Lemma Wf_MapBaseType\n          r\n          (H : MapBaseType f_base f_op failb e = Some r)\n      : Wf r.\n    Proof using Hwf Hwf_failb Hwf_f_op.\n      cbv [MapBaseType] in *; break_innermost_match_hyps; inversion_option; subst.\n      apply Wf_MapBaseType'.\n    Qed.\n  End MapBaseType.\nEnd language.\n\nHint Resolve @Wf_MapBaseType' : wf.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Compilers/MapBaseTypeWf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.24333894270930437}}
{"text": "(** * Recursing under binders with typeclasses, tracking variables with explicit contexts *)\nRequire Import Reify.ReifyCommon.\n\n(** Points of note:\n\n    - We make sure to fill in all implicit arguments explicitly, to\n      minimize the number of evars generated; evars are one of the\n      main bottlenecks.\n\n    - In the [Hint] used to tie the recursive knot, we run [intros]\n      before binding any terms to avoid playing fast and loose with\n      binders, because we will sometimes be presented with goals with\n      unintroduced binders.  If we did not call [intros] first,\n      instead binding [?var] and [?term] in the hint pattern rule,\n      they might contain unbound identifiers, causing reification to\n      fail when it tried to deal with them. *)\n\nModule var_context.\n  Inductive var_context {var : Type} :=\n  | nil\n  | cons (n : nat) (v : var) (xs : var_context).\nEnd var_context.\n\nClass reify_helper_cls (var : Type) (term : nat)\n      (ctx : @var_context.var_context var)\n  := do_reify_helper : @expr var.\n\nLtac reify_helper var term ctx :=\n  let reify_rec term := reify_helper var term ctx in\n  lazymatch ctx with\n  | context[var_context.cons term ?v _]\n    => constr:(@Var var v)\n  | _\n    =>\n    lazymatch term with\n    | O => constr:(@NatO var)\n    | S ?x\n      => let rx := reify_rec x in\n         constr:(@NatS var rx)\n    | ?x * ?y\n      => let rx := reify_rec x in\n         let ry := reify_rec y in\n         constr:(@NatMul var rx ry)\n    | (dlet x := ?v in ?f)\n      => let rv := reify_rec v in\n         let not_x := fresh (*x *)in (* don't try to preserve variable names; c.f. comments around ReifyCommon.refresh *)\n         let rf\n             :=\n             lazymatch\n               constr:(_ : forall (x : nat) (not_x : var),\n                          @reify_helper_cls\n                            var f (@var_context.cons var x not_x ctx))\n             with\n             | fun _ => ?f => f\n             | ?f => error_cant_elim_deps f\n             end in\n         constr:(@LetIn var rv rf)\n    | ?v\n      => error_bad_term v\n    end\n  end.\n\nModule Export Exports.\n  Global Hint Extern 0 (@reify_helper_cls _ _ _)\n  => (intros;\n     lazymatch goal with\n     | [ |- @reify_helper_cls ?var ?term ?ctx ]\n       => let res := reify_helper var term ctx in\n          exact res\n     end) : typeclass_instances.\nEnd Exports.\n\nLtac reify var x :=\n  reify_helper var x (@var_context.nil var).\nLtac Reify x := Reify_of reify x.\nLtac do_Reify_rhs\n     do_trans\n     restart_timer_norm_reif finish_timing_norm_reif\n     restart_timer_actual_reif finish_timing_actual_reif\n     restart_timer_eval_lazy finish_timing_eval_lazy\n     time_lazy_beta_iota time_transitivity_Denote_rv\n     _ :=\n  do_Reify_rhs_of\n    do_trans\n    restart_timer_norm_reif finish_timing_norm_reif\n    restart_timer_actual_reif finish_timing_actual_reif\n    restart_timer_eval_lazy finish_timing_eval_lazy\n    time_lazy_beta_iota time_transitivity_Denote_rv\n    Reify ().\nLtac post_Reify_rhs do_trans _ := ReifyCommon.post_Reify_rhs do_trans ().\nLtac Reify_rhs\n     do_trans\n     restart_timer_norm_reif finish_timing_norm_reif\n     restart_timer_actual_reif finish_timing_actual_reif\n     restart_timer_eval_lazy finish_timing_eval_lazy\n     time_lazy_beta_iota time_transitivity_Denote_rv\n     _ :=\n  Reify_rhs_of\n    do_trans\n    restart_timer_norm_reif finish_timing_norm_reif\n    restart_timer_actual_reif finish_timing_actual_reif\n    restart_timer_eval_lazy finish_timing_eval_lazy\n    time_lazy_beta_iota time_transitivity_Denote_rv\n    Reify ().\n", "meta": {"author": "coq-community", "repo": "coq-performance-tests", "sha": "4aaef74e5742fe3ad87c5d18d735e82b1284ecc6", "save_path": "github-repos/coq/coq-community-coq-performance-tests", "path": "github-repos/coq/coq-community-coq-performance-tests/coq-performance-tests-4aaef74e5742fe3ad87c5d18d735e82b1284ecc6/PerformanceExperiments/Reify/LtacTCExplicitCtx.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24333894270930434}}
{"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import Axioms.\nRequire Import Tactics.\nRequire Import Sigma.\nRequire Import Equality.\nRequire Import Sequence.\nRequire Import Relation.\nRequire Import Ordinal.\nRequire Import Syntax.\nRequire Import SimpSub.\nRequire Import Dynamic.\nRequire Import Ofe.\nRequire Import Uniform.\nRequire Import Intensional.\nRequire Import System.\nRequire Import Semantics.\nRequire Import SemanticsKnot.\nRequire Import Judgement.\nRequire Import Hygiene.\nRequire Import ProperClosed.\nRequire Import ProperFun.\nRequire Import Shut.\nRequire Import Candidate.\n\nRequire Import SemanticsPositive.\nRequire Import Ceiling.\nRequire Import Extend.\nRequire Import Truncate.\nRequire Import ExtendTruncate.\nRequire Import ProperDownward.\nRequire Import ProperLevel.\nRequire Import SemanticsMu.\nRequire Import SemanticsSubtype.\nRequire Import SemanticsProperty.\nRequire Import MapTerm.\nRequire Import Equivalence.\nRequire Import ProperEquiv.\nRequire Import Urelsp.\nRequire Import SemanticsPi.\nRequire Import SoundUtil.\nRequire Import Defined.\nRequire Import PageType.\nRequire Import SemanticsUniv.\nRequire Import Lattice.\nRequire Import SoundPositive.\n\n\nLemma lfp_is_mu_urel :\n  forall w (F : wurel w -> wurel w) (h : monotone F),\n    lfp (wurel_ccp w) F h\n    =\n    mu_urel w F.\nProof.\nintros w F h.\napply lat_le_antisymm.\n  {\n  apply lfp_least.\n  apply mu_prefix; auto.\n  }\n\n  {\n  apply mu_least.\n  apply (lfp_prefix (wurel_ccp w)).\n  }\nQed.\n\n\nLemma extend_urel_mono :\n  forall u v,\n    impl incl incl (extend_urel u v).\nProof.\nintros u v.\nintros X Y Hincl.\nintros i m p Hmp.\ncbn.\napply Hincl; auto.\nQed.\n\n\nLemma extend_urel_comono :\n  forall u v X Y,\n    u <<= v\n    -> incl (extend_urel u v X) (extend_urel u v Y)\n    -> incl X Y.\nProof.\nintros u v X Y Huv Hincl.\nintros i m p Hmp.\nrewrite <- (extend_term_cancel _ _ Huv m) in Hmp |- *.\nrewrite <- (extend_term_cancel _ _ Huv p) in Hmp |- *.\napply Hincl; auto.\nQed.    \n\n\nLemma positive_negative_impl_monotone_antitone :\n  forall w (h : w << stop) (X Y : wurel w),\n    incl X Y\n    -> (forall n a pg s i A B,\n          positive n a\n          -> interp pg s i (subst (under n (dot (exttin w X h) id)) a) A\n          -> interp pg s i (subst (under n (dot (exttin w Y h) id)) a) B\n          -> incl (den A) (den B))\n       /\\\n       (forall n a pg s i A B,\n          negative n a\n          -> interp pg s i (subst (under n (dot (exttin w X h) id)) a) A\n          -> interp pg s i (subst (under n (dot (exttin w Y h) id)) a) B\n          -> incl (den B) (den A)).\nProof.\nintros w h X Y Hincl.\nexploit (positive_negative_ind (obj stop)\n           (fun n a =>\n              forall s pg z i A B,\n                interp pg z i (subst (compose (under n (dot (exttin w X h) id)) s) a) A\n                -> interp pg z i (subst (compose (under n (dot (exttin w Y h) id)) s) a) B\n                -> incl (den A) (den B))\n           (fun n a =>\n              forall s pg z i A B,\n                interp pg z i (subst (compose (under n (dot (exttin w X h) id)) s) a) A\n                -> interp pg z i (subst (compose (under n (dot (exttin w Y h) id)) s) a) B\n                -> incl (den B) (den A))) as Hind.\n\n(* var *)\n{\nintros n s pg z i A B HintA HintB.\nsimpsubin HintA.\nrewrite -> project_under_eq in HintA.\nsimpsubin HintA.\nrewrite -> subst_exttin in HintA.\nsimpsubin HintB.\nrewrite -> project_under_eq in HintB.\nsimpsubin HintB.\nrewrite -> subst_exttin in HintB.\ninvert (basic_value_inv _#6 value_extt HintA).\nintros ? R h'' _ Heq1 Heq2.\ninjection (objin_inj _ _ _ Heq1).\nintros Heq ->.\ninjectionT Heq.\nintros ->.\nso (proof_irrelevance _ h h''); subst h''.\nsubst A.\nclear Heq1.\ninvert (basic_value_inv _#6 value_extt HintB).\nintros ? R h'' _ Heq1 Heq2.\ninjection (objin_inj _ _ _ Heq1).\nintros Heq ->.\ninjectionT Heq.\nintros ->.\nso (proof_irrelevance _ h h''); subst h''.\nsubst B.\nclear Heq1.\nrewrite -> !den_extend_iurel.\nrewrite -> !den_iutruncate.\nintros j m p Hmp.\ndestruct Hmp as (Hj & Hmp).\nsplit; auto.\n}\n\n(* const *)\n{\nintros n a s pg z i A B HintA HintB.\nsimpsubin HintA.\nrewrite <- compose_assoc in HintA.\nrewrite <- compose_under in HintA.\nsimpsubin HintA.\nsimpsubin HintB.\nrewrite <- compose_assoc in HintB.\nrewrite <- compose_under in HintB.\nsimpsubin HintB.\nso (interp_fun _#7 HintA HintB); subst B.\napply incl_refl.\n}\n\n(* prod *)\n{\nintros n a b _ IH1 _ IH2 s pg z i ABX ABY HintX HintY.\nsimpsubin HintX.\nsimpsubin HintY.\ninvert (basic_value_inv _#6 value_prod HintX).\nintros AX BX HintAX HintBX <-.\ninvert (basic_value_inv _#6 value_prod HintY).\nintros AY BY HintAY HintBY <-.\ncbn.\nso (IH1 _#6 HintAX HintAY) as HinclA.\nso (IH2 _#6 HintBX HintBY) as HinclB.\nintros j m p Hmp.\ncbn in Hmp.\ndecompose Hmp.\nintros m1 p1 m2 p2 Hclm Hclp Hstepsm Hstepsp Hmp1 Hmp2.\nexists m1, p1, m2, p2.\ndo2 5 split; auto.\n}\n\n(* pi *)\n{\nintros n a b _ IH1 _ IH2 s pg z i ABX ABY HintX HintY.\nsimpsubin HintX.\nsimpsubin HintY.\ninvert (basic_value_inv _#6 value_pi HintX).\nintros AX BX HintAX HintBX <-.\ninvert (basic_value_inv _#6 value_pi HintY).\nintros AY BY HintAY HintBY <-.\nintros j m p Hmp.\ncbn in Hmp.\ndecompose Hmp.\nintros ml pl Hj Hclm Hclp Hstepsm Hstepsp Hact.\nexists ml, pl.\ndo2 5 split; auto.\nintros k q r Hk Hqr.\nassert (k <= i) as Hki by omega.\nso (IH1 _#6 HintAX HintAY) as HinclA.\nso (HinclA _ _ _ Hqr) as Hqr'.\nso (Hact _#3 Hk Hqr') as Hrel.\ninvert HintBX.\nintros _ _ HactX.\nso (HactX _#3 Hki Hqr') as HintBXqr.\nclear HactX.\ninvert HintBY.\nintros _ _ HactY.\nso (HactY _#3 Hki Hqr) as HintBYqr.\nclear HactY.\nsimpsubin HintBXqr.\nsimpsubin HintBYqr.\nset (qr := if z then q else r) in HintBXqr, HintBYqr.\nreplace (subst (dot qr (compose (under n (dot (exttin w X h) id)) s)) b)\n   with (subst (compose (under (S n) (dot (exttin w X h) id)) (dot qr s)) b) in HintBXqr by (simpsub; auto).\nreplace (subst (dot qr (compose (under n (dot (exttin w Y h) id)) s)) b)\n   with (subst (compose (under (S n) (dot (exttin w Y h) id)) (dot qr s)) b) in HintBYqr by (simpsub; auto).\nso (IH2 _#6 HintBXqr HintBYqr) as HinclB.\napply HinclB; auto.\n}\n\n(* sigma *)\n{\nintros n a b _ IH1 _ IH2 s pg z i ABX ABY HintX HintY.\nsimpsubin HintX.\nsimpsubin HintY.\ninvert (basic_value_inv _#6 value_sigma HintX).\nintros AX BX HintAX HintBX <-.\ninvert (basic_value_inv _#6 value_sigma HintY).\nintros AY BY HintAY HintBY <-.\nso (IH1 _#6 HintAX HintAY) as HinclA.\nintros j m p Hmp.\ncbn in Hmp.\ndecompose Hmp.\nintros m1 p1 m2 p2 Hmp1 Hclm Hclp Hstepsm Hstepsp Hmp2.\nso (HinclA _#3 Hmp1) as Hmp1'.\nso (basic_member_index _#9 HintAX Hmp1) as Hj.\nexists m1, p1, m2, p2, Hmp1'.\ndo2 4 split; auto.\ninvert HintBX.\nintros _ _ HactX.\nso (HactX _#3 Hj Hmp1) as HintBXmp.\nclear HactX.\ninvert HintBY.\nintros _ _ HactY.\nso (HactY _#3 Hj Hmp1') as HintBYmp.\nclear HactY.\nsimpsubin HintBXmp.\nsimpsubin HintBYmp.\nset (mp := if z then m1 else p1) in HintBXmp, HintBYmp.\nreplace (subst (dot mp (compose (under n (dot (exttin w X h) id)) s)) b)\n   with (subst (compose (under (S n) (dot (exttin w X h) id)) (dot mp s)) b) in HintBXmp by (simpsub; auto).\nreplace (subst (dot mp (compose (under n (dot (exttin w Y h) id)) s)) b)\n   with (subst (compose (under (S n) (dot (exttin w Y h) id)) (dot mp s)) b) in HintBYmp by (simpsub; auto).\nso (IH2 _#6 HintBXmp HintBYmp) as HinclB.\napply HinclB; auto.\n}\n\n(* mu *)\n{\nrename Hincl into HinclXY.\nintros n a _ IH s pg z i A B HintA HintB.\nsimpsubin HintA.\nsimpsubin HintB.\ninvert (basic_value_inv _#6 value_mu HintA).\nintros u F Hu HactX _ HmonoF HrobA <-.\nreplace (subst (dot (var 0) (compose (under n (dot (exttin w X h) id)) (compose s sh1))) a)\n   with (subst (compose (under (S n) (dot (exttin w X h) id)) (under 1 s)) a) in HrobA by (simpsub; auto).\nso (le_ord_succ _ _ (le_ord_trans _#3 Hu (cin_top pg))) as Hu_stop.\nchange (u << stop) in Hu_stop.\nso (lt_ord_impl_le_ord _ _ Hu_stop) as Hu_stop'.\ninvert (basic_value_inv _#6 value_mu HintB).\nintros v G Hv HactY _ HmonoG HrobB <-.\nreplace (subst (dot (var 0) (compose (under n (dot (exttin w Y h) id)) (compose s sh1))) a)\n   with (subst (compose (under (S n) (dot (exttin w Y h) id)) (under 1 s)) a) in HrobB by (simpsub; auto).\nso (le_ord_succ _ _ (le_ord_trans _#3 Hv (cin_top pg))) as Hv_stop.\nchange (v << stop) in Hv_stop.\nso (lt_ord_impl_le_ord _ _ Hv_stop) as Hv_stop'.\nrewrite -> !den_iubase.\n(* If we knew v <<= u, this would be much simpler and we wouldn't need fixpoint iteration. *)\nrewrite <- (lfp_is_mu_urel u (fun Z => den (F Z)) HmonoF).\napply (fixpoint_iteration (wurel_ccp u) (fun Z => den (F Z))\n         (fun Z => incl (extend_urel u stop Z) (extend_urel v stop (mu_urel v (fun Z => den (G Z)))))).\n  {\n  intros Z IHZ.\n  (* We have two endpoints.  We need a mediating term that uses the higher level (u or v). *)\n  so (le_lt_ord_dec u v) as [Huv | Hvu_lt].\n    {\n    so (HactX Z Hu_stop) as HintXZ.\n    simpsubin HintXZ.\n    replace (subst (dot (extt (objin (objsome (expair (qtype u) (iubase Z)) Hu_stop))) (compose (under n (dot (exttin w X h) id)) s)) a)\n       with (subst (compose (under (S n) (dot (exttin w X h) id)) (dot (exttin u Z Hu_stop) s)) a)\n       in HintXZ by (simpsub; auto).\n    so (HactY (extend_urel u v Z) Hv_stop) as HintYZ.\n    simpsubin HintYZ.\n    replace (subst (dot (extt (objin (objsome (expair (qtype v) (iubase (extend_urel u v Z))) Hv_stop))) (compose (under n (dot (exttin w Y h) id)) s)) a)\n       with (subst (compose (under (S n) (dot (exttin w Y h) id)) (dot (exttin v (extend_urel u v Z) Hv_stop) s)) a)\n       in HintYZ by (simpsub; auto).\n    exploit (raise_robust the_system pg z i (subst (compose (under (S n) (dot (exttin w X h) id)) (under 1 s)) a) u v Z (extend_urel u v Z) Hu_stop Hv_stop (extend_iurel (lt_ord_impl_le_ord u stop Hu_stop) (F Z))) as HintXZ'; auto.\n      {\n      apply extend_urel_compose_up; auto.\n      }\n    \n      {\n      simpsub.\n      simpsubin HintXZ.\n      exact HintXZ.\n      }\n    replace (subst1 (exttin v (extend_urel u v Z) Hv_stop) (subst (compose (under (S n) (dot (exttin w X h) id)) (under 1 s)) a))\n       with (subst (compose (under (S n) (dot (exttin w X h) id)) (dot (exttin v (extend_urel u v Z) Hv_stop) s)) a)\n       in HintXZ' by (simpsub; auto).\n    so (IH _#6 HintXZ' HintYZ) as Hincl.\n    rewrite -> !den_extend_iurel in Hincl.\n    eapply incl_trans; eauto.\n    clear Hincl.\n    rewrite -> mu_fix; auto.\n    apply extend_urel_mono.\n    apply HmonoG.\n    rewrite -> (extend_urel_compose_up u v stop Huv) in IHZ.\n    eapply extend_urel_comono; eauto.\n    }\n\n    {\n    so (lt_ord_impl_le_ord _ _ Hvu_lt) as Hvu; clear Hvu_lt.\n    so (HactY (mu_urel v (fun Z => den (G Z))) Hv_stop) as HintYB.\n    simpsubin HintYB.\n    replace (subst (dot (extt (objin (objsome (expair (qtype v) (iubase (mu_urel v (fun Z => den (G Z))))) Hv_stop))) (compose (under n (dot (exttin w Y h) id)) s)) a)\n       with (subst (compose (under (S n) (dot (exttin w Y h) id)) (dot (exttin v (mu_urel v (fun Z => den (G Z))) Hv_stop) s)) a)\n       in HintYB by (simpsub; auto).\n    so (HactX (extend_urel v u (mu_urel v (fun Z => den (G Z)))) Hu_stop) as HintXB.\n    simpsubin HintXB.\n    replace (subst (dot (extt (objin (objsome (expair (qtype u) (iubase (extend_urel v u (mu_urel v (fun Z => den (G Z)))))) Hu_stop))) (compose (under n (dot (exttin w X h) id)) s)) a)\n       with (subst (compose (under (S n) (dot (exttin w X h) id)) (dot (exttin u (extend_urel v u (mu_urel v (fun Z => den (G Z)))) Hu_stop) s)) a)\n       in HintXB by (simpsub; auto).\n    exploit (raise_robust the_system pg z i (subst (compose (under (S n) (dot (exttin w Y h) id)) (under 1 s)) a) v u (mu_urel v (fun Z => den (G Z))) (extend_urel v u (mu_urel v (fun Z => den (G Z)))) Hv_stop Hu_stop (extend_iurel (lt_ord_impl_le_ord v stop Hv_stop) (G (mu_urel v (fun Z => den (G Z)))))) as HintYB'; auto.\n      {\n      apply extend_urel_compose_up; auto.\n      }\n    \n      {\n      simpsub.\n      simpsubin HintYB.\n      exact HintYB.\n      }\n    replace (subst1 (exttin u (extend_urel v u (mu_urel v (fun Z => den (G Z)))) Hu_stop) (subst (compose (under (S n) (dot (exttin w Y h) id)) (under 1 s)) a))\n       with (subst (compose (under (S n) (dot (exttin w Y h) id)) (dot (exttin u (extend_urel v u (mu_urel v (fun Z => den (G Z)))) Hu_stop) s)) a)\n         in HintYB' by (simpsub; auto).\n    so (IH _#6 HintXB HintYB') as Hincl.\n    rewrite -> !den_extend_iurel in Hincl.\n    rewrite -> mu_fix; auto.\n    eapply incl_trans; eauto.\n    clear Hincl.\n    apply extend_urel_mono.\n    apply HmonoF.\n    rewrite -> (extend_urel_compose_up v u stop Hvu) in IHZ.\n    eapply extend_urel_comono; eauto.\n    }\n  }\n\n  {\n  intros C Hchain IHC.\n  intros j m p Hmp.\n  cbn in Hmp.\n  destruct Hmp as (R & HCR & Hmp).\n  so (IHC _ HCR) as Hincl.\n  apply Hincl; auto.\n  }\n}\n\n(* bite *)\n{\nintros n m a b _ IH1 _ IH2 s pg z i ABX ABY HintX HintY.\nsimpsubin HintX.\nsimpsubin HintY.\nrewrite <- compose_assoc in HintX, HintY.\nrewrite <- compose_under in HintX, HintY.\nsimpsubin HintX.\nsimpsubin HintY.\ninvert HintX.\nintros c HclX Hstepsc Hintc.\ninvert HintY.\nintros d HclY Hstepsd Hintd.\nso (eval_bite_invert _#5 (conj Hstepsc (basicv_value _#6 Hintc))) as [(Hstepsm & Hstepsa) | (Hstepsm & Hstepsb)].\n  {\n  so (eval_bite_invert _#5 (conj Hstepsd (basicv_value _#6 Hintd))) as [(_ & Hstepsa') | (Hstepsm' & _)].\n  2:{\n    so (determinism_eval _#4 (conj Hstepsm value_btrue) (conj Hstepsm' value_bfalse)) as H.\n    discriminate H.\n    }\n  assert (interp pg z i (subst (compose (under n (dot (exttin w X h) id)) s) a) ABX) as HintX'.\n    {\n    eapply interp_eval; eauto.\n    refine (steps_hygiene _#4 _ HclX).\n    eapply star_trans.\n      {\n      eapply (star_map _#4 (fun z => bite z _ _)); eauto using step_bite1.\n      }\n    apply star_one.\n    apply step_bite2.\n    }\n  assert (interp pg z i (subst (compose (under n (dot (exttin w Y h) id)) s) a) ABY) as HintY'.\n    {\n    eapply interp_eval; eauto.\n      {\n      refine (steps_hygiene _#4 _ HclY).\n      eapply star_trans.\n        {\n        eapply (star_map _#4 (fun z => bite z _ _)); eauto using step_bite1.\n        }\n      apply star_one.\n      apply step_bite2.\n      }\n    }\n  eapply IH1; eauto.\n  }\n\n  {\n  so (eval_bite_invert _#5 (conj Hstepsd (basicv_value _#6 Hintd))) as [(Hstepsm' & _) | (_ & Hstepsb')].\n  1:{\n    so (determinism_eval _#4 (conj Hstepsm value_bfalse) (conj Hstepsm' value_btrue)) as H.\n    discriminate H.\n    }\n  assert (interp pg z i (subst (compose (under n (dot (exttin w X h) id)) s) b) ABX) as HintX'.\n    {\n    eapply interp_eval; eauto.\n    refine (steps_hygiene _#4 _ HclX).\n    eapply star_trans.\n      {\n      eapply (star_map _#4 (fun z => bite z _ _)); eauto using step_bite1.\n      }\n    apply star_one.\n    apply step_bite3.\n    }\n  assert (interp pg z i (subst (compose (under n (dot (exttin w Y h) id)) s) b) ABY) as HintY'.\n    {\n    eapply interp_eval; eauto.\n      {\n      refine (steps_hygiene _#4 _ HclY).\n      eapply star_trans.\n        {\n        eapply (star_map _#4 (fun z => bite z _ _)); eauto using step_bite1.\n        }\n      apply star_one.\n      apply step_bite3.\n      }\n    }\n  eapply IH2; eauto.\n  }\n}\n\n(* weaken *)\n{\nintros n a _ IH s pg z i A B HintA HintB.\nsimpsubin HintA.\nsimpsubin HintB.\nrewrite <- compose_assoc in HintA, HintB.\nrewrite -> compose_sh_under_eq in HintA, HintB.\nsimpsubin HintA.\nsimpsubin HintB.\nrewrite -> subst_exttin in HintA, HintB.\nexploit (IH (compose (sh n) s) pg z i A B); auto.\n}\n\n(* equiv *)\n{\nintros n a b Hequiv _ IH s pg z i AX AY HintX HintY.\napply (IH s pg z i).\n  {\n  refine (basic_equiv _#7 _ _ HintX); eauto using equiv_subst, reduce_equiv.\n  refine (reduce_hygiene _#4 _ (basic_closed _#6 HintX)).\n  apply reduce_subst; auto.\n  }\n\n  {\n  refine (basic_equiv _#7 _ _ HintY); eauto using equiv_subst, reduce_equiv.\n  refine (reduce_hygiene _#4 _ (basic_closed _#6 HintY)).\n  apply reduce_subst; auto.\n  }\n}\n\n(* const *)\n{\nintros n a s pg z i A B HintA HintB.\nsimpsubin HintA.\nrewrite <- compose_assoc in HintA.\nrewrite <- compose_under in HintA.\nsimpsubin HintA.\nsimpsubin HintB.\nrewrite <- compose_assoc in HintB.\nrewrite <- compose_under in HintB.\nsimpsubin HintB.\nso (interp_fun _#7 HintA HintB); subst B.\napply incl_refl.\n}\n\n(* prod *)\n{\nintros n a b _ IH1 _ IH2 s pg z i ABX ABY HintX HintY.\nsimpsubin HintX.\nsimpsubin HintY.\ninvert (basic_value_inv _#6 value_prod HintX).\nintros AX BX HintAX HintBX <-.\ninvert (basic_value_inv _#6 value_prod HintY).\nintros AY BY HintAY HintBY <-.\ncbn.\nso (IH1 _#6 HintAX HintAY) as HinclA.\nso (IH2 _#6 HintBX HintBY) as HinclB.\nintros j m p Hmp.\ncbn in Hmp.\ndecompose Hmp.\nintros m1 p1 m2 p2 Hclm Hclp Hstepsm Hstepsp Hmp1 Hmp2.\nexists m1, p1, m2, p2.\ndo2 5 split; auto.\n}\n\n(* pi *)\n{\nintros n a b _ IH1 _ IH2 s pg z i ABX ABY HintX HintY.\nsimpsubin HintX.\nsimpsubin HintY.\ninvert (basic_value_inv _#6 value_pi HintX).\nintros AX BX HintAX HintBX <-.\ninvert (basic_value_inv _#6 value_pi HintY).\nintros AY BY HintAY HintBY <-.\nintros j m p Hmp.\ncbn in Hmp.\ndecompose Hmp.\nintros ml pl Hj Hclm Hclp Hstepsm Hstepsp Hact.\nexists ml, pl.\ndo2 5 split; auto.\nintros k q r Hk Hqr.\nassert (k <= i) as Hki by omega.\nso (IH1 _#6 HintAX HintAY) as HinclA.\nso (HinclA _ _ _ Hqr) as Hqr'.\nso (Hact _#3 Hk Hqr') as Hrel.\ninvert HintBX.\nintros _ _ HactX.\nso (HactX _#3 Hki Hqr) as HintBXqr.\nclear HactX.\ninvert HintBY.\nintros _ _ HactY.\nso (HactY _#3 Hki Hqr') as HintBYqr.\nclear HactY.\nsimpsubin HintBXqr.\nsimpsubin HintBYqr.\nset (qr := if z then q else r) in HintBXqr, HintBYqr.\nreplace (subst (dot qr (compose (under n (dot (exttin w X h) id)) s)) b)\n   with (subst (compose (under (S n) (dot (exttin w X h) id)) (dot qr s)) b) in HintBXqr by (simpsub; auto).\nreplace (subst (dot qr (compose (under n (dot (exttin w Y h) id)) s)) b)\n   with (subst (compose (under (S n) (dot (exttin w Y h) id)) (dot qr s)) b) in HintBYqr by (simpsub; auto).\nso (IH2 _#6 HintBXqr HintBYqr) as HinclB.\napply HinclB; auto.\n}\n\n(* sigma *)\n{\nintros n a b _ IH1 _ IH2 s pg z i ABX ABY HintX HintY.\nsimpsubin HintX.\nsimpsubin HintY.\ninvert (basic_value_inv _#6 value_sigma HintX).\nintros AX BX HintAX HintBX <-.\ninvert (basic_value_inv _#6 value_sigma HintY).\nintros AY BY HintAY HintBY <-.\nso (IH1 _#6 HintAX HintAY) as HinclA.\nintros j m p Hmp.\ncbn in Hmp.\ndecompose Hmp.\nintros m1 p1 m2 p2 Hmp1 Hclm Hclp Hstepsm Hstepsp Hmp2.\nso (HinclA _#3 Hmp1) as Hmp1'.\nso (basic_member_index _#9 HintAY Hmp1) as Hj.\nexists m1, p1, m2, p2, Hmp1'.\ndo2 4 split; auto.\ninvert HintBX.\nintros _ _ HactX.\nso (HactX _#3 Hj Hmp1') as HintBXmp.\nclear HactX.\ninvert HintBY.\nintros _ _ HactY.\nso (HactY _#3 Hj Hmp1) as HintBYmp.\nclear HactY.\nsimpsubin HintBXmp.\nsimpsubin HintBYmp.\nset (mp := if z then m1 else p1) in HintBXmp, HintBYmp.\nreplace (subst (dot mp (compose (under n (dot (exttin w X h) id)) s)) b)\n   with (subst (compose (under (S n) (dot (exttin w X h) id)) (dot mp s)) b) in HintBXmp by (simpsub; auto).\nreplace (subst (dot mp (compose (under n (dot (exttin w Y h) id)) s)) b)\n   with (subst (compose (under (S n) (dot (exttin w Y h) id)) (dot mp s)) b) in HintBYmp by (simpsub; auto).\nso (IH2 _#6 HintBXmp HintBYmp) as HinclB.\napply HinclB; auto.\n}\n\n(* mu *)\n{\nrename Hincl into HinclXY.\nrename X into Z.\nrename Y into X.\nrename Z into Y.\nintros n a _ IH s pg z i B A HintB HintA.\nsimpsubin HintA.\nsimpsubin HintB.\ninvert (basic_value_inv _#6 value_mu HintA).\nintros u F Hu HactX _ HmonoF HrobA <-.\nreplace (subst (dot (var 0) (compose (under n (dot (exttin w X h) id)) (compose s sh1))) a)\n   with (subst (compose (under (S n) (dot (exttin w X h) id)) (under 1 s)) a) in HrobA by (simpsub; auto).\nso (le_ord_succ _ _ (le_ord_trans _#3 Hu (cin_top pg))) as Hu_stop.\nchange (u << stop) in Hu_stop.\nso (lt_ord_impl_le_ord _ _ Hu_stop) as Hu_stop'.\ninvert (basic_value_inv _#6 value_mu HintB).\nintros v G Hv HactY _ HmonoG HrobB <-.\nreplace (subst (dot (var 0) (compose (under n (dot (exttin w Y h) id)) (compose s sh1))) a)\n   with (subst (compose (under (S n) (dot (exttin w Y h) id)) (under 1 s)) a) in HrobB by (simpsub; auto).\nso (le_ord_succ _ _ (le_ord_trans _#3 Hv (cin_top pg))) as Hv_stop.\nchange (v << stop) in Hv_stop.\nso (lt_ord_impl_le_ord _ _ Hv_stop) as Hv_stop'.\nrewrite -> !den_iubase.\n(* If we knew v <<= u, this would be much simpler and we wouldn't need fixpoint iteration. *)\nrewrite <- (lfp_is_mu_urel u (fun Z => den (F Z)) HmonoF).\napply (fixpoint_iteration (wurel_ccp u) (fun Z => den (F Z))\n         (fun Z => incl (extend_urel u stop Z) (extend_urel v stop (mu_urel v (fun Z => den (G Z)))))).\n  {\n  intros Z IHZ.\n  (* We have two endpoints.  We need a mediating term that uses the higher level (u or v). *)\n  so (le_lt_ord_dec u v) as [Huv | Hvu_lt].\n    {\n    so (HactX Z Hu_stop) as HintXZ.\n    simpsubin HintXZ.\n    replace (subst (dot (extt (objin (objsome (expair (qtype u) (iubase Z)) Hu_stop))) (compose (under n (dot (exttin w X h) id)) s)) a)\n       with (subst (compose (under (S n) (dot (exttin w X h) id)) (dot (exttin u Z Hu_stop) s)) a)\n       in HintXZ by (simpsub; auto).\n    so (HactY (extend_urel u v Z) Hv_stop) as HintYZ.\n    simpsubin HintYZ.\n    replace (subst (dot (extt (objin (objsome (expair (qtype v) (iubase (extend_urel u v Z))) Hv_stop))) (compose (under n (dot (exttin w Y h) id)) s)) a)\n       with (subst (compose (under (S n) (dot (exttin w Y h) id)) (dot (exttin v (extend_urel u v Z) Hv_stop) s)) a)\n       in HintYZ by (simpsub; auto).\n    exploit (raise_robust the_system pg z i (subst (compose (under (S n) (dot (exttin w X h) id)) (under 1 s)) a) u v Z (extend_urel u v Z) Hu_stop Hv_stop (extend_iurel (lt_ord_impl_le_ord u stop Hu_stop) (F Z))) as HintXZ'; auto.\n      {\n      apply extend_urel_compose_up; auto.\n      }\n    \n      {\n      simpsub.\n      simpsubin HintXZ.\n      exact HintXZ.\n      }\n    replace (subst1 (exttin v (extend_urel u v Z) Hv_stop) (subst (compose (under (S n) (dot (exttin w X h) id)) (under 1 s)) a))\n       with (subst (compose (under (S n) (dot (exttin w X h) id)) (dot (exttin v (extend_urel u v Z) Hv_stop) s)) a)\n       in HintXZ' by (simpsub; auto).\n    so (IH _#6 HintYZ HintXZ') as Hincl.\n    rewrite -> !den_extend_iurel in Hincl.\n    eapply incl_trans; eauto.\n    clear Hincl.\n    rewrite -> mu_fix; auto.\n    apply extend_urel_mono.\n    apply HmonoG.\n    rewrite -> (extend_urel_compose_up u v stop Huv) in IHZ.\n    eapply extend_urel_comono; eauto.\n    }\n\n    {\n    so (lt_ord_impl_le_ord _ _ Hvu_lt) as Hvu; clear Hvu_lt.\n    so (HactY (mu_urel v (fun Z => den (G Z))) Hv_stop) as HintYB.\n    simpsubin HintYB.\n    replace (subst (dot (extt (objin (objsome (expair (qtype v) (iubase (mu_urel v (fun Z => den (G Z))))) Hv_stop))) (compose (under n (dot (exttin w Y h) id)) s)) a)\n       with (subst (compose (under (S n) (dot (exttin w Y h) id)) (dot (exttin v (mu_urel v (fun Z => den (G Z))) Hv_stop) s)) a)\n       in HintYB by (simpsub; auto).\n    so (HactX (extend_urel v u (mu_urel v (fun Z => den (G Z)))) Hu_stop) as HintXB.\n    simpsubin HintXB.\n    replace (subst (dot (extt (objin (objsome (expair (qtype u) (iubase (extend_urel v u (mu_urel v (fun Z => den (G Z)))))) Hu_stop))) (compose (under n (dot (exttin w X h) id)) s)) a)\n       with (subst (compose (under (S n) (dot (exttin w X h) id)) (dot (exttin u (extend_urel v u (mu_urel v (fun Z => den (G Z)))) Hu_stop) s)) a)\n       in HintXB by (simpsub; auto).\n    exploit (raise_robust the_system pg z i (subst (compose (under (S n) (dot (exttin w Y h) id)) (under 1 s)) a) v u (mu_urel v (fun Z => den (G Z))) (extend_urel v u (mu_urel v (fun Z => den (G Z)))) Hv_stop Hu_stop (extend_iurel (lt_ord_impl_le_ord v stop Hv_stop) (G (mu_urel v (fun Z => den (G Z)))))) as HintYB'; auto.\n      {\n      apply extend_urel_compose_up; auto.\n      }\n    \n      {\n      simpsub.\n      simpsubin HintYB.\n      exact HintYB.\n      }\n    replace (subst1 (exttin u (extend_urel v u (mu_urel v (fun Z => den (G Z)))) Hu_stop) (subst (compose (under (S n) (dot (exttin w Y h) id)) (under 1 s)) a))\n       with (subst (compose (under (S n) (dot (exttin w Y h) id)) (dot (exttin u (extend_urel v u (mu_urel v (fun Z => den (G Z)))) Hu_stop) s)) a)\n         in HintYB' by (simpsub; auto).\n    so (IH _#6 HintYB' HintXB) as Hincl.\n    rewrite -> !den_extend_iurel in Hincl.\n    rewrite -> mu_fix; auto.\n    eapply incl_trans; eauto.\n    clear Hincl.\n    apply extend_urel_mono.\n    apply HmonoF.\n    rewrite -> (extend_urel_compose_up v u stop Hvu) in IHZ.\n    eapply extend_urel_comono; eauto.\n    }\n  }\n\n  {\n  intros C Hchain IHC.\n  intros j m p Hmp.\n  cbn in Hmp.\n  destruct Hmp as (R & HCR & Hmp).\n  so (IHC _ HCR) as Hincl.\n  apply Hincl; auto.\n  }\n}\n\n(* bite *)\n{\nintros n m a b _ IH1 _ IH2 s pg z i ABX ABY HintX HintY.\nsimpsubin HintX.\nsimpsubin HintY.\nrewrite <- compose_assoc in HintX, HintY.\nrewrite <- compose_under in HintX, HintY.\nsimpsubin HintX.\nsimpsubin HintY.\ninvert HintX.\nintros c HclX Hstepsc Hintc.\ninvert HintY.\nintros d HclY Hstepsd Hintd.\nso (eval_bite_invert _#5 (conj Hstepsc (basicv_value _#6 Hintc))) as [(Hstepsm & Hstepsa) | (Hstepsm & Hstepsb)].\n  {\n  so (eval_bite_invert _#5 (conj Hstepsd (basicv_value _#6 Hintd))) as [(_ & Hstepsa') | (Hstepsm' & _)].\n  2:{\n    so (determinism_eval _#4 (conj Hstepsm value_btrue) (conj Hstepsm' value_bfalse)) as H.\n    discriminate H.\n    }\n  assert (interp pg z i (subst (compose (under n (dot (exttin w X h) id)) s) a) ABX) as HintX'.\n    {\n    eapply interp_eval; eauto.\n    refine (steps_hygiene _#4 _ HclX).\n    eapply star_trans.\n      {\n      eapply (star_map _#4 (fun z => bite z _ _)); eauto using step_bite1.\n      }\n    apply star_one.\n    apply step_bite2.\n    }\n  assert (interp pg z i (subst (compose (under n (dot (exttin w Y h) id)) s) a) ABY) as HintY'.\n    {\n    eapply interp_eval; eauto.\n      {\n      refine (steps_hygiene _#4 _ HclY).\n      eapply star_trans.\n        {\n        eapply (star_map _#4 (fun z => bite z _ _)); eauto using step_bite1.\n        }\n      apply star_one.\n      apply step_bite2.\n      }\n    }\n  eapply IH1; eauto.\n  }\n\n  {\n  so (eval_bite_invert _#5 (conj Hstepsd (basicv_value _#6 Hintd))) as [(Hstepsm' & _) | (_ & Hstepsb')].\n  1:{\n    so (determinism_eval _#4 (conj Hstepsm value_bfalse) (conj Hstepsm' value_btrue)) as H.\n    discriminate H.\n    }\n  assert (interp pg z i (subst (compose (under n (dot (exttin w X h) id)) s) b) ABX) as HintX'.\n    {\n    eapply interp_eval; eauto.\n    refine (steps_hygiene _#4 _ HclX).\n    eapply star_trans.\n      {\n      eapply (star_map _#4 (fun z => bite z _ _)); eauto using step_bite1.\n      }\n    apply star_one.\n    apply step_bite3.\n    }\n  assert (interp pg z i (subst (compose (under n (dot (exttin w Y h) id)) s) b) ABY) as HintY'.\n    {\n    eapply interp_eval; eauto.\n      {\n      refine (steps_hygiene _#4 _ HclY).\n      eapply star_trans.\n        {\n        eapply (star_map _#4 (fun z => bite z _ _)); eauto using step_bite1.\n        }\n      apply star_one.\n      apply step_bite3.\n      }\n    }\n  eapply IH2; eauto.\n  }\n}\n\n(* weaken *)\n{\nintros n a _ IH s pg z i A B HintA HintB.\nsimpsubin HintA.\nsimpsubin HintB.\nrewrite <- compose_assoc in HintA, HintB.\nrewrite -> compose_sh_under_eq in HintA, HintB.\nsimpsubin HintA.\nsimpsubin HintB.\nrewrite -> subst_exttin in HintA, HintB.\nexploit (IH (compose (sh n) s) pg z i A B); auto.\n}\n\n(* equiv *)\n{\nintros n a b Hequiv _ IH s pg z i AX AY HintX HintY.\napply (IH s pg z i).\n  {\n  refine (basic_equiv _#7 _ _ HintX); eauto using equiv_subst, reduce_equiv.\n  refine (reduce_hygiene _#4 _ (basic_closed _#6 HintX)).\n  apply reduce_subst; auto.\n  }\n\n  {\n  refine (basic_equiv _#7 _ _ HintY); eauto using equiv_subst, reduce_equiv.\n  refine (reduce_hygiene _#4 _ (basic_closed _#6 HintY)).\n  apply reduce_subst; auto.\n  }\n}\n\n(* epilogue *)\n{\ndestruct Hind as (IHpos & IHneg).\nsplit.\n  {\n  intros n a pg s i A B Hpos HintA HintB.\n  exploit (IHpos _ _ Hpos id pg s i A B) as H; simpsub; auto.\n  }\n\n  {\n  intros n a pg s i A B Hneg HintA HintB.\n  exploit (IHneg _ _ Hneg id pg s i A B) as H; simpsub; auto.\n  }\n}\nQed.\n\n\nLemma positive_impl_monotone :\n  forall n a w X Y pg s i A B (h : w << stop),\n    positive n a\n    -> incl X Y\n    -> interp pg s i (subst (under n (dot (exttin w X h) id)) a) A\n    -> interp pg s i (subst (under n (dot (exttin w Y h) id)) a) B\n    -> incl (den A) (den B).\nProof.\nintros n a w X Y pg s i A B h Hpos Hincl HintA HintB.\nexact (positive_negative_impl_monotone_antitone w h X Y Hincl andel n a pg s i A B Hpos HintA HintB).\nQed.\n\n\nLemma extract_ind :\n  forall pg i a b,\n    (forall j (X Y : car (wurel_ofe (cin pg))) (h : cin pg << stop),\n       j <= i\n       -> dist (S j) X Y\n       -> exists R,\n            interp pg true j (subst1 (exttin (cin pg) X h) a) R\n            /\\ interp pg false j (subst1 (exttin (cin pg) Y h) b) R)\n    -> exists (F : wurel_ofe (cin pg) -n> wiurel_ofe (cin pg)),\n         forall (X : wurel (cin pg)) (h : cin pg << stop) (h' : cin pg <<= stop),\n           interp pg true i (subst1 (exttin (cin pg) X h) a) (extend_iurel h' (pi1 F X))\n           /\\ interp pg false i (subst1 (exttin (cin pg) X h) b) (extend_iurel h' (pi1 F X)).\nProof.\nintros pg i a b Hact.\nset (w := cin pg).\nso (le_ord_succ _ _ (cin_top pg)) as h.\nchange (cin pg << stop) in h.\nso (lt_ord_impl_le_ord _ _ h) as h'.\nexploit (choice (car (wurel_ofe w)) (car (wiurel_ofe w))\n           (fun X R =>\n              interp pg true i (subst1 (exttin w X h) a) (extend_iurel h' R)\n              /\\ interp pg false i (subst1 (exttin w X h) b) (extend_iurel h' R))) as H.\n  {\n  intros X.\n  so (Hact i X X h (le_refl _) (dist_refl _ _ _)) as (R & Hl & Hr).\n  so (interp_level_internal _#5 h' Hl) as (R' & ->).\n  exists R'.\n  split; auto.\n  intros R''.\n  intros (Hl' & _).\n  so (interp_fun _#7 Hl Hl') as Heq.\n  so (extend_iurel_inj _#5 Heq); subst R''.\n  reflexivity.\n  }\ndestruct H as (F & HF).\nassert (nonexpansive F) as Hne.\n  {\n  intros j X Y Hdist.\n  destruct j as [| j].\n    {\n    apply dist_zero.\n    }\n  so (le_lt_dec j i) as [Hji | Hlt].\n    {\n    apply (dist_trans _ _ _ (iutruncate (S j) (F X))).\n      {\n      apply dist_symm.\n      apply iutruncate_near.\n      }\n    apply (dist_trans _ _ _ (iutruncate (S j) (F Y))).\n    2:{\n      apply iutruncate_near.\n      }\n    apply dist_refl'.\n    so (HF X) as (Hli & _).\n    so (HF Y) as (_ & Hri).\n    so (Hact j X Y h Hji Hdist) as (R & Hlj & Hrj).\n    so (basic_downward _#7 Hji Hli) as Hlj'.\n    so (basic_downward _#7 Hji Hri) as Hrj'.\n    so (interp_fun _#7 Hlj Hlj'); subst R.\n    so (interp_fun _#7 Hrj Hrj') as Heq.\n    rewrite -> !iutruncate_extend_iurel in Heq.\n    exact (extend_iurel_inj _#5 Heq).\n    }\n\n    {\n    assert (S i <= S j) as Hij by omega.\n    apply dist_refl'.\n    so (Hact i X Y h (le_refl _) (dist_downward_leq _#5 Hij Hdist)) as (R & Hl & Hr).\n    so (HF X) as (Hl' & _).\n    so (HF Y) as (_ & Hr').\n    so (interp_fun _#7 Hl Hl'); subst R.\n    so (interp_fun _#7 Hr Hr') as Heq.\n    exact (extend_iurel_inj _#5 Heq).\n    }\n  }\nexists (expair F Hne).\nintros X h'' h'''.\nso (proof_irrelevance _ h h''); subst h''.\nso (proof_irrelevance _ h' h'''); subst h'''.\nso (HF X) as (Hl & Hr).\nsplit; auto.\nQed.\n\n\nLemma extract_ind_multi :\n  forall pg i a a' b b',\n    (forall j (X Y : car (wurel_ofe (cin pg))) (h : cin pg << stop),\n       j <= i\n       -> dist (S j) X Y\n       -> exists R,\n            interp pg true j (subst1 (exttin (cin pg) X h) a) R\n            /\\ interp pg false j (subst1 (exttin (cin pg) Y h) a') R\n            /\\ interp pg true j (subst1 (exttin (cin pg) X h) b) R\n            /\\ interp pg false j (subst1 (exttin (cin pg) Y h) b') R)\n    -> exists (F : wurel_ofe (cin pg) -n> wiurel_ofe (cin pg)),\n         forall (X : wurel (cin pg)) (h : cin pg << stop) (h' : cin pg <<= stop),\n           interp pg true i (subst1 (exttin (cin pg) X h) a) (extend_iurel h' (pi1 F X))\n           /\\ interp pg false i (subst1 (exttin (cin pg) X h) a') (extend_iurel h' (pi1 F X))\n           /\\ interp pg true i (subst1 (exttin (cin pg) X h) b) (extend_iurel h' (pi1 F X))\n           /\\ interp pg false i (subst1 (exttin (cin pg) X h) b') (extend_iurel h' (pi1 F X)).\nProof.\nintros pg i a b c d Hact.\nexploit (extract_ind pg i a b) as (F1 & HF1).\n  {\n  intros j X Y h Hj HXY.\n  so (Hact j X Y h Hj HXY) as (R & Ha & Hb & _).\n  eauto.\n  }\nexploit (extract_ind pg i c d) as (F2 & HF2).\n  {\n  intros j X Y h Hj HXY.\n  so (Hact j X Y h Hj HXY) as (R & _ & _ & Hc & Hd).\n  eauto.\n  }\nexploit (extract_ind pg i a d) as (F & HF).\n  {\n  intros j X Y h Hj HXY.\n  so (Hact j X Y h Hj HXY) as (R & Ha & _ & _ & Hd).\n  eauto.\n  }\nexists F.\nintros X h h'.\nso (HF X h h') as (Ha & Hd).\ndo2 3 split; auto.\n  {\n  so (HF1 X h h') as (Ha' & Hb).\n  so (interp_fun _#7 Ha Ha') as Heq.\n  rewrite -> (extend_iurel_inj _#5 Heq).\n  exact Hb.\n  }\n\n  {\n  so (HF2 X h h') as (Hc & Hd').\n  so (interp_fun _#7 Hd Hd') as Heq.\n  rewrite -> (extend_iurel_inj _#5 Heq).\n  exact Hc.\n  }\nQed.\n\n\nLemma pwctx_cons_exttin :\n  forall w i (X Y : car (wurel_ofe w)) h s s' G,\n    w <<= top\n    -> dist (S i) X Y\n    -> pwctx i s s' G\n    -> pwctx i (dot (exttin w X h) s) (dot (exttin w Y h) s') (hyp_tp :: G).\nProof.\nintros w i X Y h s s' G Hw Hdist Hs.\napply pwctx_cons_tp; auto.\napply (seqhyp_tp _#3 (extend_iurel (lt_ord_impl_le_ord _ _ h) (iutruncate (S i) (iubase X)))).\n  {\n  apply interp_eval_refl.\n  apply interp_extt; auto.\n  }\n\n  {\n  replace (iutruncate (S i) (iubase X)) with (iutruncate (S i) (iubase Y)).\n  2:{\n    symmetry.\n    rewrite -> !iutruncate_iubase.\n    f_equal.\n    apply ceiling_collapse; auto.\n    }\n  apply interp_eval_refl.\n  apply interp_extt; auto.\n  }\nQed.\n\n\nLemma pwctx_cons_exttin_univ :\n  forall pg w i (X Y : car (wurel_ofe w)) h lv s s' G,\n    w <<= cin pg\n    -> pginterp (subst s lv) pg\n    -> pginterp (subst s' lv) pg\n    -> (forall j t t',\n          j <= i\n          -> pwctx j t t' G\n          -> exists pg',\n               pginterp (subst t lv) pg'\n               /\\ pginterp (subst t' lv) pg')\n    -> dist (S i) X Y\n    -> pwctx i s s' G\n    -> pwctx i (dot (exttin w X h) s) (dot (exttin w Y h) s') (hyp_tm (univ lv) :: G).\nProof.\nintros pg w i X Y h lv s s' G Hw Hlvl Hlvr Hlvfunc Hdist Hs.\nso (pginterp_lt_top _ _ Hlvl) as Hltpg.\napply pwctx_cons_tm; auto.\n  {\n  apply (seqhyp_tm _#5 (iuuniv the_system i pg)).\n    {\n    simpsub.\n    apply interp_eval_refl.\n    destruct Hltpg.\n    apply interp_univ; auto.\n    }\n\n    {\n    simpsub.\n    apply interp_eval_refl.\n    destruct Hltpg.\n    apply interp_univ; auto.\n    }\n\n    {\n    split; auto.\n    exists (extend_iurel (lt_ord_impl_le_ord _ _ h) (iutruncate (S i) (iubase X))).\n    rewrite -> sint_unroll.\n    split.\n      {\n      apply interp_eval_refl.\n      apply interp_extt; auto.\n      }\n\n      {\n      replace (iutruncate (S i) (iubase X)) with (iutruncate (S i) (iubase Y)).\n      2:{\n        symmetry.\n        rewrite -> !iutruncate_iubase.\n        f_equal.\n        apply ceiling_collapse; auto.\n        }\n      apply interp_eval_refl.\n      apply interp_extt; auto.\n      }\n    }\n  }\n\n  {\n  intros j s'' Hj Hs'.\n  simpsub.\n  so (Hlvfunc _#3 Hj Hs') as (pg' & Hl & Hr).\n  so (pginterp_fun _#3 Hlvl Hl); subst pg'.\n  eapply relhyp_tm; eauto.\n    {\n    apply interp_eval_refl.\n    destruct Hltpg.\n    apply interp_univ; eauto.\n    }\n\n    {\n    apply interp_eval_refl.\n    destruct Hltpg.\n    apply interp_univ; eauto.\n    }\n  }\n\n  {\n  intros j s'' Hj Hs'.\n  simpsub.\n  so (Hlvfunc _#3 Hj Hs') as (pg' & Hl & Hr).\n  so (pginterp_fun _#3 Hlvr Hr); subst pg'.\n  eapply relhyp_tm; eauto.\n    {\n    apply interp_eval_refl.\n    destruct Hltpg.\n    apply interp_univ; eauto.\n    }\n\n    {\n    apply interp_eval_refl.\n    destruct Hltpg.\n    apply interp_univ; eauto.\n    }\n  }\nQed.\n\n\nLemma pwctx_cons_exttin_tm :\n  forall pg w i (X Y : car (wurel_ofe w)) h s s' G lv,\n    w <<= cin pg\n    -> pginterp (subst s lv) pg\n    -> seq G (deq lv lv pagetp)\n    -> dist (S i) X Y\n    -> pwctx i s s' G\n    -> pwctx i (dot (exttin w X h) s) (dot (exttin w Y h) s') (hyp_tm (univ lv) :: G).\nProof.\nintros pg w i X Y h s s' G lv Hw Hlvl Hseqlv Hdist Hs.\nrewrite -> seq_deq in Hseqlv.\nso (Hseqlv _#3 Hs) as (R & HR & _ & Hlv & _).\nso (interp_pagetp_invert _#7 HR Hlv) as (pg' & Hlvl' & Hlvr).\nso (pginterp_fun _#3 Hlvl Hlvl'); subst pg'.\nso (pginterp_lt_top _ _ Hlvl) as (Hltstr, Hltcex).\napply pwctx_cons_tm_seq; auto.\n  {\n  apply (seqhyp_tm _#5 (iuuniv the_system i pg)).\n    {\n    simpsub.\n    apply interp_eval_refl.\n    apply interp_univ; eauto.\n    }\n\n    {\n    simpsub.\n    apply interp_eval_refl.\n    apply interp_univ; eauto.\n    }\n\n    {\n    cbn.\n    split; auto.\n    exists (extend_iurel (lt_ord_impl_le_ord _ _ h) (iutruncate (S i) (iubase X))).\n    rewrite -> sint_unroll.\n    split.\n      {\n      apply interp_eval_refl.\n      apply interp_extt; auto.\n      }\n  \n      {\n      replace (iutruncate (S i) (iubase X)) with (iutruncate (S i) (iubase Y)).\n      2:{\n        symmetry.\n        rewrite -> !iutruncate_iubase.\n        f_equal.\n        apply ceiling_collapse; auto.\n        }\n      apply interp_eval_refl.\n      apply interp_extt; auto.\n      }\n    }\n  }\n\n  {\n  clear pg Hw R HR Hlv Hlvl Hlvr Hlvl' Hltstr Hltcex.\n  intros j t t' Ht.\n  so (Hseqlv _#3 Ht) as (R & HR & _ & Hlv & _).\n  so (interp_pagetp_invert _#7 HR Hlv) as (pg & Hlvl & Hlvr).\n  exists toppg, (iuuniv the_system j pg).\n  simpsub.\n  so (pginterp_lt_top _ _ Hlvl) as (Hltstr, Hltcex).\n  split; apply interp_eval_refl; apply interp_univ; auto.\n  }\nQed.\n\n\nLemma monotone_from_ispositive :\n  forall pg a G (F : wurel (cin pg) -> wiurel (cin pg)),\n    (forall i s s',\n       pwctx i s s' G\n       -> positive 0 (subst (under 1 s) a) /\\ positive 0 (subst (under 1 s') a))\n    -> forall i s s',\n         pwctx i s s' G\n         -> (forall (X : wurel (cin pg)) (h : cin pg << stop) (h' : cin pg <<= stop),\n               interp pg true i (subst (dot (exttin (cin pg) X h) s) a) (extend_iurel h' (F X)))\n         -> monotone (fun X => den (F X)).\nProof.\nintros pg a G F Hispos i s s' Hs Hact.\nso (Hispos _#3 Hs) as (Hpos & _).\nintros X Y Hincl.\nso (le_ord_succ _ _ (cin_top pg)) as h.\nchange (cin pg << stop) in h.\nso (cin_stop pg) as h'.\nso (Hact X h h') as HX.\nso (Hact Y h h') as HY.\nexploit (positive_impl_monotone 0 (subst (under 1 s) a) (cin pg) X Y pg true i (extend_iurel h' (F X)) (extend_iurel h' (F Y)) h) as H; auto; try (simpsub; auto; done).\neapply extend_urel_comono; eauto.\nQed.\n\n\nLemma sound_mu_formation :\n  forall G a b,\n    pseq (hyp_tp :: G) (deqtype a b)\n    -> pseq G (deq triv triv (ispositive a))\n    -> pseq G (deq triv triv (ispositive b))\n    -> pseq G (deqtype (mu a) (mu b)).\nProof.\nintros G a b.\nrevert G.\nrefine (seq_pseq 2 [hyp_tp] a [hyp_tp] b 3 [_] _ [] _ [] _ _ _); cbn.\nintros G Hcla Hclb Hab Hisroba Hisrobb.\nrewrite -> seq_eqtype in Hab |- *.\nrewrite -> seq_ispositive in Hisroba, Hisrobb; auto.\nintros i s s' Hs.\nsimpsub.\nexploit (extract_ind_multi toppg i (subst (under 1 s) a) (subst (under 1 s') a) (subst (under 1 s) b) (subst (under 1 s') b)) as H.\n  {\n  intros j X Y h Hj HXY.\n  so (pwctx_cons_exttin top j X Y h s s' G (le_ord_refl _) HXY (pwctx_downward _#5 Hj Hs)) as Hss.\n  so (Hab _ _ _ Hss) as (R & Hal & Har & Hbl & Hbr).\n  exists R.\n  simpsub.\n  auto.\n  }\ndestruct H as (F & HF).\nassert (nonexpansive (fun X => den (pi1 F X))) as Hne.\n  {\n  apply compose_ne_ne; auto using den_nonexpansive.\n  exact (pi2 F).\n  }\nassert (monotone (fun X => den (pi1 F X))) as HmonoF.\n  {\n  refine (monotone_from_ispositive _#4 Hisroba _#3 Hs _).\n  intros X h h'.\n  so (HF X h h') as (H & _).\n  simpsubin H.\n  exact H.\n  }\nexists (iubase (extend_urel top stop (mu_urel top (fun X => den (pi1 F X))))).\ndo2 3 split.\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (H & _).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisroba _#3 Hs andel)).\n    }\n  }\n\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (_ & H & _).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisroba _#3 Hs ander)).\n    }\n  }\n\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (_ & _ & H & _).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisrobb _#3 Hs andel)).\n    }\n  }\n\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (_ & _ & _ & H).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisrobb _#3 Hs ander)).\n    }\n  }\nQed.\n\n\nLemma sound_mu_formation_univ :\n  forall G lv a b,\n    pseq G (deq lv lv pagetp)\n    -> pseq (hyp_tm (univ lv) :: G) (deq a b (univ (subst sh1 lv)))\n    -> pseq G (deq triv triv (ispositive a))\n    -> pseq G (deq triv triv (ispositive b))\n    -> pseq G (deq (mu a) (mu b) (univ lv)).\nProof.\nintros G lv a b.\nrevert G.\nrefine (seq_pseq 2 [hyp_tp] a [hyp_tp] b 4 [] _ [_] _ [] _ [] _ _ _); cbn.\nintros G Hcla Hclb Hseqlv Hab Hisroba Hisrobb.\nrewrite -> seq_deq in Hseqlv.\nrewrite -> seq_univ in Hab |- *.\neassert _ as Hlv; [refine (seq_pagetp_invert G lv _) |].\n  {\n  intros i t t' Ht.\n  so (Hseqlv _#3 Ht) as (R & Hl & _ & Hlv & _).\n  eauto.\n  }\nrewrite -> seq_ispositive in Hisroba, Hisrobb; auto.\nintros i s s' Hs.\nsimpsub.\nso (Hlv _#3 Hs) as (pg & Hlvl & Hlvr).\nset (w := cin pg).\nexploit (extract_ind_multi pg i (subst (under 1 s) a) (subst (under 1 s') a) (subst (under 1 s) b) (subst (under 1 s') b)) as H.\n  {\n  intros j X Y h Hj HXY.\n  exploit (pwctx_cons_exttin_univ pg w j X Y h lv s s' G) as Hss; auto.\n    {\n    apply le_ord_refl.\n    }\n\n    {\n    intros k t t' Hk Ht.\n    so (Hseqlv _#3 Ht) as (R & Hl & _ & Hlvlr & _).\n    simpsubin Hl.\n    fold (@pagetp (obj stop)) in Hl.\n    exact (interp_pagetp_invert _#7 Hl Hlvlr).\n    }\n\n    {\n    eapply pwctx_downward; eauto.\n    }\n  so (Hab _ _ _ Hss) as (pg' & R & Hlvl' & _ & Hal & Har & Hbl & Hbr).\n  simpsubin Hlvl'.\n  so (pginterp_fun _#3 Hlvl Hlvl'); subst pg'.\n  exists R.\n  simpsub.\n  auto.\n  }\ndestruct H as (F & HF).\nassert (nonexpansive (fun X => den (pi1 F X))) as Hne.\n  {\n  apply compose_ne_ne; auto using den_nonexpansive.\n  exact (pi2 F).\n  }\nassert (monotone (fun X => den (pi1 F X))) as HmonoF.\n  {\n  refine (monotone_from_ispositive _#4 Hisroba _#3 Hs _).\n  intros X h h'.\n  so (HF X h h') as (H & _).\n  simpsubin H.\n  exact H.\n  }\nexists pg, (iubase (extend_urel w stop (mu_urel w (fun X => den (pi1 F X))))).\ndo2 5 split; auto.\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (H & _).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisroba _#3 Hs andel)).\n    }\n  }\n\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (_ & H & _).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisroba _#3 Hs ander)).\n    }\n  }\n\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (_ & _ & H & _).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisrobb _#3 Hs andel)).\n    }\n  }\n\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (_ & _ & _ & H).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisrobb _#3 Hs ander)).\n    }\n  }\nQed.\n\n\nLemma sound_mu_roll :\n  forall G a,\n    pseq (hyp_tp :: G) (deqtype a a)\n    -> pseq G (deq triv triv (ispositive a))\n    -> pseq G (dsubtype (subst1 (mu a) a) (mu a)).\nProof.\nintros G a.\nrevert G.\nrefine (seq_pseq 1 [hyp_tp] a 2 [_] _ [] _ _ _); cbn.\nintros G Hcla Hseqa Hisrob.\nrewrite -> seq_eqtype in Hseqa.\nrewrite -> seq_ispositive in Hisrob; auto.\nrewrite -> seq_subtype.\nintros i s s' Hs.\nsimpsub.\nexploit (extract_ind toppg i (subst (under 1 s) a) (subst (under 1 s') a)) as H.\n  {\n  intros j X Y h Hj HXY.\n  so (pwctx_cons_exttin top j X Y h s s' G (le_ord_refl _) HXY (pwctx_downward _#5 Hj Hs)) as Hss.\n  so (Hseqa _ _ _ Hss) as (R & Hal & Har & _).\n  exists R.\n  simpsub.\n  auto.\n  }\ndestruct H as (F & HF).\nassert (nonexpansive (fun X => den (pi1 F X))) as Hne.\n  {\n  apply compose_ne_ne; auto using den_nonexpansive.\n  exact (pi2 F).\n  }\nassert (monotone (fun X => den (pi1 F X))) as HmonoF.\n  {\n  refine (monotone_from_ispositive _#4 Hisrob _#3 Hs _).\n  intros X h h'.\n  so (HF X h h') as (H & _).\n  simpsubin H.\n  exact H.\n  }\nset (Mu := (iubase (extend_urel top stop (mu_urel top (fun X => den (pi1 F X)))))).\nassert (interp toppg true i (mu (subst (under 1 s) a)) Mu) as Hmul.\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (H & _).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisrob _#3 Hs andel)).\n    }\n  }\nassert (interp toppg false i (mu (subst (under 1 s') a)) Mu) as Hmur.\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (_ & H).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisrob _#3 Hs ander)).\n    }\n  }\nassert (pwctx i (dot (mu (subst (under 1 s) a)) s) (dot (mu (subst (under 1 s') a)) s') (hyp_tp :: G)) as Hss.\n  {\n  apply pwctx_cons_tp; auto.\n  apply (seqhyp_tp _#3 Mu); auto.\n  }\nso (Hseqa _#3 Hss) as (AMu & Hamul & Hamur & _).\nclear Hss.\nassert (den AMu = den Mu) as Heq.\n  {\n  unfold Mu.\n  rewrite -> mu_fix; auto.\n  so (succ_increase top) as h.\n  set (h' := lt_ord_impl_le_ord _ _ h).\n  rewrite <- (extend_iubase _ _ h').\n  assert (pwctx i (dot (mu (subst (under 1 s) a)) s) (dot (exttin top (mu_urel top (fun X => den (pi1 F X))) h) s') (hyp_tp :: G)) as Hss.\n    {\n    apply pwctx_cons_tp; auto.\n    apply (seqhyp_tp _#3 Mu); auto.\n    so (basic_impl_iutruncate _#6 Hmul) as Heq.\n    rewrite -> Heq.\n    unfold Mu.\n    rewrite <- (extend_iubase _ _ h').\n    rewrite -> iutruncate_extend_iurel.\n    apply interp_eval_refl.\n    apply interp_extt.\n    apply le_ord_refl.\n    }\n  so (Hseqa _#3 Hss) as (R & Hamul' & Hamur' & _).\n  simpsubin Hamul'.\n  simpsubin Hamur'.\n  so (HF (mu_urel top (fun X => den (pi1 F X))) h h') as (_ & Hamur'').\n  simpsubin Hamur''.\n  so (interp_fun _#7 Hamur' Hamur''); subst R.\n  so (interp_fun _#7 Hamul Hamul'); subst AMu.\n  rewrite -> !den_extend_iurel.\n  rewrite -> den_iubase.\n  reflexivity.\n  }\nexists AMu, Mu.  (* the only line that is different from sound_mu_unroll *)\ndo2 4 split; auto.\nrewrite -> Heq.\nintros j m p Hj Hmp.\nunfold Mu in Hmp |- *.\nexact Hmp.\nQed.\n\n\nLemma sound_mu_unroll :\n  forall G a,\n    pseq (hyp_tp :: G) (deqtype a a)\n    -> pseq G (deq triv triv (ispositive a))\n    -> pseq G (dsubtype (mu a) (subst1 (mu a) a)).\nProof.\nintros G a.\nrevert G.\nrefine (seq_pseq 1 [hyp_tp] a 2 [_] _ [] _ _ _); cbn.\nintros G Hcla Hseqa Hisrob.\nrewrite -> seq_eqtype in Hseqa.\nrewrite -> seq_ispositive in Hisrob; auto.\nrewrite -> seq_subtype.\nintros i s s' Hs.\nsimpsub.\nexploit (extract_ind toppg i (subst (under 1 s) a) (subst (under 1 s') a)) as H.\n  {\n  intros j X Y h Hj HXY.\n  so (pwctx_cons_exttin top j X Y h s s' G (le_ord_refl _) HXY (pwctx_downward _#5 Hj Hs)) as Hss.\n  so (Hseqa _ _ _ Hss) as (R & Hal & Har & _).\n  exists R.\n  simpsub.\n  auto.\n  }\ndestruct H as (F & HF).\nassert (nonexpansive (fun X => den (pi1 F X))) as Hne.\n  {\n  apply compose_ne_ne; auto using den_nonexpansive.\n  exact (pi2 F).\n  }\nassert (monotone (fun X => den (pi1 F X))) as HmonoF.\n  {\n  refine (monotone_from_ispositive _#4 Hisrob _#3 Hs _).\n  intros X h h'.\n  so (HF X h h') as (H & _).\n  simpsubin H.\n  exact H.\n  }\nset (Mu := (iubase (extend_urel top stop (mu_urel top (fun X => den (pi1 F X)))))).\nassert (interp toppg true i (mu (subst (under 1 s) a)) Mu) as Hmul.\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (H & _).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisrob _#3 Hs andel)).\n    }\n  }\nassert (interp toppg false i (mu (subst (under 1 s') a)) Mu) as Hmur.\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (_ & H).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisrob _#3 Hs ander)).\n    }\n  }\nassert (pwctx i (dot (mu (subst (under 1 s) a)) s) (dot (mu (subst (under 1 s') a)) s') (hyp_tp :: G)) as Hss.\n  {\n  apply pwctx_cons_tp; auto.\n  apply (seqhyp_tp _#3 Mu); auto.\n  }\nso (Hseqa _#3 Hss) as (AMu & Hamul & Hamur & _).\nclear Hss.\nassert (den AMu = den Mu) as Heq.\n  {\n  unfold Mu.\n  rewrite -> mu_fix; auto.\n  so (succ_increase top) as h.\n  set (h' := lt_ord_impl_le_ord _ _ h).\n  rewrite <- (extend_iubase _ _ h').\n  assert (pwctx i (dot (mu (subst (under 1 s) a)) s) (dot (exttin top (mu_urel top (fun X => den (pi1 F X))) h) s') (hyp_tp :: G)) as Hss.\n    {\n    apply pwctx_cons_tp; auto.\n    apply (seqhyp_tp _#3 Mu); auto.\n    so (basic_impl_iutruncate _#6 Hmul) as Heq.\n    rewrite -> Heq.\n    unfold Mu.\n    rewrite <- (extend_iubase _ _ h').\n    rewrite -> iutruncate_extend_iurel.\n    apply interp_eval_refl.\n    apply interp_extt.\n    apply le_ord_refl.\n    }\n  so (Hseqa _#3 Hss) as (R & Hamul' & Hamur' & _).\n  simpsubin Hamul'.\n  simpsubin Hamur'.\n  so (HF (mu_urel top (fun X => den (pi1 F X))) h h') as (_ & Hamur'').\n  simpsubin Hamur''.\n  so (interp_fun _#7 Hamur' Hamur''); subst R.\n  so (interp_fun _#7 Hamul Hamul'); subst AMu.\n  rewrite -> !den_extend_iurel.\n  rewrite -> den_iubase.\n  reflexivity.\n  }\nexists Mu, AMu.  (* the only line that is different from sound_mu_roll *)\ndo2 4 split; auto.\nrewrite -> Heq.\nintros j m p Hj Hmp.\nunfold Mu in Hmp |- *.\nexact Hmp.\nQed.\n\n\nLemma sound_mu_roll_univ :\n  forall G lv a,\n    pseq G (deq lv lv pagetp)\n    -> pseq (hyp_tm (univ lv) :: G) (deq a a (univ (subst sh1 lv)))\n    -> pseq G (deq triv triv (ispositive a))\n    -> pseq G (dsubtype (subst1 (mu a) a) (mu a)).\nProof.\nintros G lv a.\nrevert G.\nrefine (seq_pseq 1 [hyp_tp] a 3 [] _ [_] _ [] _ _ _); cbn.\nintros G Hcla Hseqlv Hseqa Hisrob.\nrewrite -> seq_deq in Hseqlv.\nrewrite -> seq_univ in Hseqa.\nrewrite -> seq_ispositive in Hisrob; auto.\nrewrite -> seq_subtype.\nexploit (seq_pagetp_invert G lv) as Hlevel.\n  {\n  intros i s s' Hs.\n  so (Hseqlv _#3 Hs) as (R & H1 & _ & H2 & _).\n  eauto.\n  }\nintros i s s' Hs.\nsimpsub.\nso (Hlevel _#3 Hs) as (pg & Hlvl & Hlvr).\nset (w := cin pg).\nexploit (extract_ind pg i (subst (under 1 s) a) (subst (under 1 s') a)) as H.\n  {\n  intros j X Y h Hj HXY.\n  exploit (pwctx_cons_exttin_univ pg w j X Y h lv s s' G) as Hss; auto.\n    {\n    apply le_ord_refl.\n    }\n\n    {\n    intros k t t' Hk Ht.\n    so (Hseqlv _#3 Ht) as (R & Hl & _ & Hlvlr & _).\n    simpsubin Hl.\n    fold (@pagetp (obj stop)) in Hl.\n    exact (interp_pagetp_invert _#7 Hl Hlvlr).\n    }\n\n    {\n    eapply pwctx_downward; eauto.\n    }\n  so (Hseqa _ _ _ Hss) as (pg' & R & Hlvl' & _ & Hal & Har & _).\n  simpsubin Hlvl'.\n  so (pginterp_fun _#3 Hlvl Hlvl'); subst pg'.\n  exists R.\n  simpsub.\n  auto.\n  }\ndestruct H as (F & HF).\nassert (nonexpansive (fun X => den (pi1 F X))) as Hne.\n  {\n  apply compose_ne_ne; auto using den_nonexpansive.\n  exact (pi2 F).\n  }\nassert (monotone (fun X => den (pi1 F X))) as HmonoF.\n  {\n  refine (monotone_from_ispositive _#4 Hisrob _#3 Hs _).\n  intros X h h'.\n  so (HF X h h') as (H & _).\n  simpsubin H.\n  exact H.\n  }\nset (Mu := (iubase (extend_urel w stop (mu_urel w (fun X => den (pi1 F X)))))).\nassert (interp pg true i (mu (subst (under 1 s) a)) Mu) as Hmul.\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (H & _).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisrob _#3 Hs andel)).\n    }\n  }\nassert (interp pg false i (mu (subst (under 1 s') a)) Mu) as Hmur.\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (_ & H).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisrob _#3 Hs ander)).\n    }\n  }\nassert (pwctx i (dot (mu (subst (under 1 s) a)) s) (dot (mu (subst (under 1 s') a)) s') (hyp_tm (univ lv) :: G)) as Hss.\n  {\n  apply pwctx_cons_tm_seq; auto.\n    {\n    simpsub.\n    apply (seqhyp_tm _#5 (iuuniv the_system i pg)).\n      {\n      apply interp_eval_refl.\n      apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n      }\n  \n      {\n      simpsub.\n      apply interp_eval_refl.\n      apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n      }\n\n      {\n      cbn.\n      split; auto.\n      rewrite -> sint_unroll.\n      exists Mu.\n      auto.\n      }\n    }\n\n    {\n    intros j t t' Ht.\n    so (Hlevel _#3 Ht) as (pgt & Hlvlt & Hlvrt).\n    exists toppg, (iuuniv the_system j pgt).\n    simpsub.\n    split.\n      {\n      apply interp_eval_refl.\n      apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n      }\n\n      {\n      apply interp_eval_refl.\n      apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n      }\n    }\n  }\nso (Hseqa _#3 Hss) as (pg' & AMu & Hlvl' & _ & Hamul & Hamur & _).\nclear Hss.\nsimpsubin Hlvl'.\nso (pginterp_fun _#3 Hlvl Hlvl'); subst pg'.\nclear Hlvl'.\nassert (den AMu = den Mu) as Heq.\n  {\n  unfold Mu.\n  rewrite -> mu_fix; auto.\n  so (lt_ord_trans _#3 (pginterp_cin_top _ _ Hlvl) (succ_increase top)) as h.\n  change (w << stop) in h.\n  set (h' := lt_ord_impl_le_ord _ _ h).\n  rewrite <- (extend_iubase _ _ h').\n  assert (pwctx i (dot (mu (subst (under 1 s) a)) s) (dot (exttin w (mu_urel w (fun X => den (pi1 F X))) h) s') (hyp_tm (univ lv) :: G)) as Hss.\n    {\n    apply pwctx_cons_tm_seq; auto.\n      {\n      simpsub.\n      apply (seqhyp_tm _#5 (iuuniv the_system i pg)).\n        {\n        apply interp_eval_refl.\n        apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n        }\n    \n        {\n        simpsub.\n        apply interp_eval_refl.\n        apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n        }\n\n        {\n        cbn.\n        split; auto.\n        rewrite -> sint_unroll.\n        exists Mu.\n        split; auto.\n        so (basic_impl_iutruncate _#6 Hmul) as Heq.\n        rewrite -> Heq.\n        unfold Mu.\n        rewrite <- (extend_iubase _ _ h').\n        rewrite -> iutruncate_extend_iurel.\n        apply interp_eval_refl.\n        apply interp_extt.\n        apply le_ord_refl.\n        }\n      }\n\n      {\n      intros j t t' Ht.\n      so (Hlevel _#3 Ht) as (pgt & Hlvlt & Hlvrt).\n      exists toppg, (iuuniv the_system j pgt).\n      simpsub.\n      split.\n        {\n        apply interp_eval_refl.\n        apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n        }\n  \n        {\n        apply interp_eval_refl.\n        apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n        }\n      }\n    }\n  so (Hseqa _#3 Hss) as (pg' & R & Hlvl' & _ & Hamul' & Hamur' & _).\n  simpsubin Hlvl'.\n  so (pginterp_fun _#3 Hlvl Hlvl'); subst pg'.\n  simpsubin Hamul'.\n  simpsubin Hamur'.\n  so (HF (mu_urel w (fun X => den (pi1 F X))) h h') as (_ & Hamur'').\n  simpsubin Hamur''.\n  so (interp_fun _#7 Hamur' Hamur''); subst R.\n  so (interp_fun _#7 Hamul Hamul'); subst AMu.\n  rewrite -> !den_extend_iurel.\n  rewrite -> den_iubase.\n  reflexivity.\n  }\nexists AMu, Mu.  (* the only line that is different from sound_mu_unroll_univ *)\ndo2 4 split.\n  {\n  apply (interp_increase pg); auto using toppg_max.\n  }\n\n  {\n  apply (interp_increase pg); auto using toppg_max.\n  }\n\n  {\n  apply (interp_increase pg); auto using toppg_max.\n  }\n\n  {\n  apply (interp_increase pg); auto using toppg_max.\n  }\nrewrite -> Heq.\nintros j m p Hj Hmp.\nunfold Mu in Hmp |- *.\nexact Hmp.\nQed.\n\n\nLemma sound_mu_unroll_univ :\n  forall G lv a,\n    pseq G (deq lv lv pagetp)\n    -> pseq (hyp_tm (univ lv) :: G) (deq a a (univ (subst sh1 lv)))\n    -> pseq G (deq triv triv (ispositive a))\n    -> pseq G (dsubtype (mu a) (subst1 (mu a) a)).\nProof.\nintros G lv a.\nrevert G.\nrefine (seq_pseq 1 [hyp_tp] a 3 [] _ [_] _ [] _ _ _); cbn.\nintros G Hcla Hseqlv Hseqa Hisrob.\nrewrite -> seq_deq in Hseqlv.\nrewrite -> seq_univ in Hseqa.\nrewrite -> seq_ispositive in Hisrob; auto.\nrewrite -> seq_subtype.\nexploit (seq_pagetp_invert G lv) as Hlevel.\n  {\n  intros i s s' Hs.\n  so (Hseqlv _#3 Hs) as (R & H1 & _ & H2 & _).\n  eauto.\n  }\nintros i s s' Hs.\nsimpsub.\nso (Hlevel _#3 Hs) as (pg & Hlvl & Hlvr).\nset (w := cin pg).\nexploit (extract_ind pg i (subst (under 1 s) a) (subst (under 1 s') a)) as H.\n  {\n  intros j X Y h Hj HXY.\n  exploit (pwctx_cons_exttin_univ pg w j X Y h lv s s' G) as Hss; auto.\n    {\n    apply le_ord_refl.\n    }\n\n    {\n    intros k t t' Hk Ht.\n    so (Hseqlv _#3 Ht) as (R & Hl & _ & Hlvlr & _).\n    simpsubin Hl.\n    fold (@pagetp (obj stop)) in Hl.\n    exact (interp_pagetp_invert _#7 Hl Hlvlr).\n    }\n\n    {\n    eapply pwctx_downward; eauto.\n    }\n  so (Hseqa _ _ _ Hss) as (pg' & R & Hlvl' & _ & Hal & Har & _).\n  simpsubin Hlvl'.\n  so (pginterp_fun _#3 Hlvl Hlvl'); subst pg'.\n  exists R.\n  simpsub.\n  auto.\n  }\ndestruct H as (F & HF).\nassert (nonexpansive (fun X => den (pi1 F X))) as Hne.\n  {\n  apply compose_ne_ne; auto using den_nonexpansive.\n  exact (pi2 F).\n  }\nassert (monotone (fun X => den (pi1 F X))) as HmonoF.\n  {\n  refine (monotone_from_ispositive _#4 Hisrob _#3 Hs _).\n  intros X h h'.\n  so (HF X h h') as (H & _).\n  simpsubin H.\n  exact H.\n  }\nset (Mu := (iubase (extend_urel w stop (mu_urel w (fun X => den (pi1 F X)))))).\nassert (interp pg true i (mu (subst (under 1 s) a)) Mu) as Hmul.\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (H & _).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisrob _#3 Hs andel)).\n    }\n  }\nassert (interp pg false i (mu (subst (under 1 s') a)) Mu) as Hmur.\n  {\n  apply interp_eval_refl.\n  apply interp_mu; auto using le_ord_refl.\n    {\n    intros X h.\n    simpsub.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (_ & H).\n    simpsubin H.\n    exact H.\n    }\n\n    {\n    exact (positive_impl_robust _#3 (Hisrob _#3 Hs ander)).\n    }\n  }\nassert (pwctx i (dot (mu (subst (under 1 s) a)) s) (dot (mu (subst (under 1 s') a)) s') (hyp_tm (univ lv) :: G)) as Hss.\n  {\n  apply pwctx_cons_tm_seq; auto.\n    {\n    simpsub.\n    apply (seqhyp_tm _#5 (iuuniv the_system i pg)).\n      {\n      apply interp_eval_refl.\n      apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n      }\n  \n      {\n      simpsub.\n      apply interp_eval_refl.\n      apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n      }\n\n      {\n      cbn.\n      split; auto.\n      rewrite -> sint_unroll.\n      exists Mu.\n      auto.\n      }\n    }\n\n    {\n    intros j t t' Ht.\n    so (Hlevel _#3 Ht) as (pgt & Hlvlt & Hlvrt).\n    exists toppg, (iuuniv the_system j pgt).\n    simpsub.\n    split.\n      {\n      apply interp_eval_refl.\n      apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n      }\n\n      {\n      apply interp_eval_refl.\n      apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n      }\n    }\n  }\nso (Hseqa _#3 Hss) as (pg' & AMu & Hlvl' & _ & Hamul & Hamur & _).\nclear Hss.\nsimpsubin Hlvl'.\nso (pginterp_fun _#3 Hlvl Hlvl'); subst pg'.\nclear Hlvl'.\nassert (den AMu = den Mu) as Heq.\n  {\n  unfold Mu.\n  rewrite -> mu_fix; auto.\n  so (lt_ord_trans _#3 (pginterp_cin_top _ _ Hlvl) (succ_increase top)) as h.\n  change (w << stop) in h.\n  set (h' := lt_ord_impl_le_ord _ _ h).\n  rewrite <- (extend_iubase _ _ h').\n  assert (pwctx i (dot (mu (subst (under 1 s) a)) s) (dot (exttin w (mu_urel w (fun X => den (pi1 F X))) h) s') (hyp_tm (univ lv) :: G)) as Hss.\n    {\n    apply pwctx_cons_tm_seq; auto.\n      {\n      simpsub.\n      apply (seqhyp_tm _#5 (iuuniv the_system i pg)).\n        {\n        apply interp_eval_refl.\n        apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n        }\n    \n        {\n        simpsub.\n        apply interp_eval_refl.\n        apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n        }\n\n        {\n        cbn.\n        split; auto.\n        rewrite -> sint_unroll.\n        exists Mu.\n        split; auto.\n        so (basic_impl_iutruncate _#6 Hmul) as Heq.\n        rewrite -> Heq.\n        unfold Mu.\n        rewrite <- (extend_iubase _ _ h').\n        rewrite -> iutruncate_extend_iurel.\n        apply interp_eval_refl.\n        apply interp_extt.\n        apply le_ord_refl.\n        }\n      }\n\n      {\n      intros j t t' Ht.\n      so (Hlevel _#3 Ht) as (pgt & Hlvlt & Hlvrt).\n      exists toppg, (iuuniv the_system j pgt).\n      simpsub.\n      split.\n        {\n        apply interp_eval_refl.\n        apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n        }\n  \n        {\n        apply interp_eval_refl.\n        apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n        }\n      }\n    }\n  so (Hseqa _#3 Hss) as (pg' & R & Hlvl' & _ & Hamul' & Hamur' & _).\n  simpsubin Hlvl'.\n  so (pginterp_fun _#3 Hlvl Hlvl'); subst pg'.\n  simpsubin Hamul'.\n  simpsubin Hamur'.\n  so (HF (mu_urel w (fun X => den (pi1 F X))) h h') as (_ & Hamur'').\n  simpsubin Hamur''.\n  so (interp_fun _#7 Hamur' Hamur''); subst R.\n  so (interp_fun _#7 Hamul Hamul'); subst AMu.\n  rewrite -> !den_extend_iurel.\n  rewrite -> den_iubase.\n  reflexivity.\n  }\nexists Mu, AMu.  (* the only line that is different from sound_mu_roll_univ *)\ndo2 4 split.\n  {\n  apply (interp_increase pg); auto using toppg_max.\n  }\n\n  {\n  apply (interp_increase pg); auto using toppg_max.\n  }\n\n  {\n  apply (interp_increase pg); auto using toppg_max.\n  }\n\n  {\n  apply (interp_increase pg); auto using toppg_max.\n  }\nrewrite -> Heq.\nintros j m p Hj Hmp.\nunfold Mu in Hmp |- *.\nexact Hmp.\nQed.\n\n\nDefinition down w := map_term (extend stop w).\nDefinition up w := map_term (extend w stop).\n\n\nDefinition contingent_action pg A (P : nat -> sterm -> sterm -> Prop)\n  : nat -> relation (wterm (cin pg))\n  :=\n  fun i m p =>\n    rel A i m p\n    /\\ exists R,\n         forall j b c,\n           j <= i\n           -> P j b c\n           -> interp pg true j (subst1 (up (cin pg) m) b) (iutruncate (S j) R)\n              /\\ interp pg false j (subst1 (up (cin pg) p) c) (iutruncate (S j) R)\n              /\\ rel (den R) j triv triv.\n\n\nLemma contingent_uniform :\n  forall pg A P, uniform _ (contingent_action pg A P).\nProof.\nintros pg A P.\ndo2 3 split.\n\n(* closed *)\n{\nintros i m p Hmp.\ndestruct Hmp as (Hmp & _).\neapply urel_closed; eauto.\n}\n\n(* equiv *)\n{\nintros i m m' p p' Hclm' Hclp' Hequivm Hequivp Hmp.\ndestruct Hmp as (Hmp & R & HR).\nsplit.\n  {\n  eapply urel_equiv; eauto.\n  }\nexists R.\nintros j b c Hj Hbc.\nso (HR j b c Hj Hbc) as (Hb & Hc & Hinh).\ndo2 2 split; auto.\n  {\n  eapply basic_equiv; eauto.\n    {\n    so (basic_closed _#6 Hb) as Hhyg.\n    so (hygiene_clo_subst1_invert_permit _#3 Hhyg) as Hclb.\n    apply hygiene_subst1; auto.\n    apply map_hygiene; auto.\n    }\n\n    {\n    apply equiv_funct1; auto using equiv_refl.\n    apply map_equiv; auto.\n    }\n  }\n\n  {\n  eapply basic_equiv; eauto.\n    {\n    so (basic_closed _#6 Hc) as Hhyg.\n    so (hygiene_clo_subst1_invert_permit _#3 Hhyg) as Hclb.\n    apply hygiene_subst1; auto.\n    apply map_hygiene; auto.\n    }\n\n    {\n    apply equiv_funct1; auto using equiv_refl.\n    apply map_equiv; auto.\n    }\n  }\n}\n\n(* zigzag *)\n{\nintros i m p n q Hmp Hnp Hnq.\ndestruct Hmp as (Hmp & R & HRmp).\ndestruct Hnp as (Hnp & R' & HRnp).\ndestruct Hnq as (Hnq & R'' & HRnq).\nsplit.\n  {\n  eapply urel_zigzag; eauto.\n  }\nexists R.\nintros j b c Hj Hbc.\nso (HRmp _ _ _ Hj Hbc) as (Hm & Hp & Hinh).\nso (HRnp _ _ _ Hj Hbc) as (Hn & Hp' & _).\nso (interp_fun _#7 Hp Hp') as Heq.\nso (HRnq _ _ _ Hj Hbc) as (Hn' & Hq & _).\nso (interp_fun _#7 Hn Hn') as Heq'.\ndo2 2 split; auto.\n  {\n  rewrite -> Heq.\n  rewrite -> Heq'.\n  auto.\n  }\n}\n\n(* downward *)\n{\nintros i m p Hmp.\ndestruct Hmp as (Hmp & R & HR).\nsplit.\n  {\n  apply urel_downward; auto.\n  }\nexists R.\nintros j b c Hj.\napply HR.\nomega.\n}\nQed.\n\n\nDefinition contingent pg A P := (mk_urel _ (contingent_uniform pg A P)).\n\n\nDefinition relctx i s s' t t' G :=\n  pwctx i s s' G\n  /\\ seqctx i t t' G\n  /\\ seqctx i s t' G.\n\n\nLemma relctx_refl :\n  forall i s s' G,\n    pwctx i s s' G\n    -> relctx i s s' s s' G.\nProof.\nintros i s s' G H.\ndo2 2 split; auto using pwctx_impl_seqctx.\nQed.\n\n\nLemma relctx_downward :\n  forall i j s s' t t' G,\n    j <= i\n    -> relctx i s s' t t' G\n    -> relctx j s s' t t' G.\nProof.\nintros i j s s' t t' G Hj (Hs & Ht & Hst).\ndo2 2 split; eauto using pwctx_downward, seqctx_downward.\nQed.\n\n\nLemma relctx_pwctx :\n  forall i s s' t t' G,\n    relctx i s s' t t' G\n    -> pwctx i t t' G.\nProof.\nintros i s s' t t' G Hst.\ndestruct Hst as (Hs & Ht & Hst).\nso (seqctx_pwctx_left _#5 Hs Hst) as Hst'.\nexact (seqctx_pwctx_right _#5 Hst' Ht).\nQed.\n\n\nLemma relctx_trans_right :\n  forall i s s' t t' u' G,\n    seqctx i t u' G\n    -> relctx i s s' t t' G\n    -> relctx i s s' t u' G.\nProof.\nintros i s s' t t' u' G Htu (Hs & Ht & Hst).\ndo2 2 split; auto.\napply (seqctx_zigzag i s t' t u'); auto.\nQed.\n\n\nLemma relctx_trans_left :\n  forall i s s' t t' u G,\n    seqctx i u t' G\n    -> relctx i s s' t t' G\n    -> relctx i s s' u t' G.\nProof.\nintros i s s' t t' u' G Htu (Hs & Ht & Hst).\ndo2 2 split; auto.\nQed.\n\n\nLemma relctx_swap1 :\n  forall i s s' t t' G,\n    relctx i s s' t t' G\n    -> relctx i s s' s t' G.\nProof.\nintros i s s' t t' G (Hs & Ht & Hst).\ndo2 2 split; auto.\nQed.\n\n\nLemma relctx_swap2 :\n  forall i s s' t t' G,\n    relctx i s s' t t' G\n    -> relctx i s s' t s' G.\nProof.\nintros i s s' t t' G (Hs & Ht & Hst).\ndo2 2 split; auto using pwctx_impl_seqctx.\neapply seqctx_zigzag; eauto using pwctx_impl_seqctx.\nQed.\n\n\nDefinition contingent_instance pg A b s s' G :=\n  contingent pg A (fun j c d =>\n                    exists t t',\n                      relctx j s s' t t' G\n                      /\\ c = subst (under 1 t) b\n                      /\\ d = subst (under 1 t') b).\n\n\nLemma contingent_instance_elim :\n  forall pg A b s s' G i m p,\n    rel (contingent_instance pg A b s s' G) i m p\n    -> rel A i m p\n       /\\ exists R,\n            forall j t t',\n              j <= i\n              -> relctx j s s' t t' G\n              -> interp pg true j (subst (dot (up (cin pg) m) t) b) (iutruncate (S j) R)\n                 /\\ interp pg false j (subst (dot (up (cin pg) p) t') b) (iutruncate (S j) R)\n                 /\\ rel (den R) j triv triv.\nProof.\nintros pg A b s s' G i m p H.\ndestruct H as (Hmp & R & HR).\nsplit; auto.\nexists R.\nintros j t t' Hj Ht.\nexploit (HR j (subst (under 1 t) b) (subst (under 1 t') b)) as H; auto.\n  {\n  exists t, t'.\n  auto.\n  }\nsimpsubin H.\nexact H.\nQed.\n\n       \nLemma interp_updown :\n  forall pg w z i s m a A,\n    cex pg <<= w\n    -> interp pg z i (subst (dot (up w (down w m)) s) a) A\n    -> interp pg z i (subst (dot m s) a) A.\nProof.\nintros pg w z i s m a A Hle Hint.\nunfold up, down in Hint.\nrewrite <- restrict_extend in Hint.\nso (restrict_impl_restriction w m) as Hrestm.\nso (restriction_refl w (subst (under 1 s) a)) as Hresta.\nso (restriction_funct1 _#5 Hrestm Hresta) as Hrest.\nsimpsubin Hrest.\neapply interp_restriction; eauto.\neapply restriction_decrease; eauto.\nQed.\n\n\n(* The sound_mu_ind_univ rule depends on the page's cex and cin being\n   equal.  That turns out to be true for every page that the syntax\n   supports, but we don't like to rely on that property.  If we ever\n   were to relax it, we would have to add an extra premise to\n   sound_mu_ind_univ to ensure it.\n*)\nLocal Lemma pginterp_cin_cex :\n  forall m pg,\n    pginterp m pg\n    -> cin pg = cex pg.\nProof.\nintros m pg H.\ndestruct H as (w & _ & _ & Hin & Hex).\nsubst w.\nauto.\nQed.\n\n\nLemma relctx_pginterp :\n  forall G lv i s s' t t' pg,\n    seq G (deq lv lv pagetp)\n    -> relctx i s s' t t' G\n    -> pginterp (subst s lv) pg\n    -> pginterp (subst t lv) pg /\\ pginterp (subst t' lv) pg.\nProof.\nintros G lv i s s' t t' pg Hseq Hrel Hlv.\nrewrite -> seq_deq in Hseq.\nexploit (seq_pagetp_invert G lv) as Hlevel.\n  {\n  clear i s s' t t' Hrel Hlv.\n  intros i s s' Hs.\n  so (Hseq _#3 Hs) as (R & Hl & _ & Hinh & _).\n  exists toppg, R.\n  split; auto.\n  }\nso (Hlevel _#3 (relctx_pwctx _#6 (relctx_swap1 _#6 Hrel))) as (pg' & Hlv' & Hlvtr).\nso (pginterp_fun _#3 Hlv Hlv'); subst pg'; clear Hlv'.\nso (Hlevel _#3 (relctx_pwctx _#6 Hrel)) as (pg' & Hlvtl & Hlvtr').\nso (pginterp_fun _#3 Hlvtr Hlvtr'); subst pg'.\nauto.\nQed.\n\n\nLemma sound_mu_ind :\n  forall G a b m,\n    pseq (hyp_tp :: G) (deqtype a a)\n    -> pseq G (deq triv triv (ispositive a))\n    -> pseq\n         (hyp_tm (pi (var 2) (subst (under 1 (sh 3)) b)) ::\n          hyp_tm (subtype (var 1) (mu (subst (under 1 (sh 2)) a))) ::\n          hyp_tm a ::\n          hyp_tp :: \n          G)\n         (deq triv triv (subst (dot (var 2) (sh 4)) b))\n    -> pseq G (deq m m (mu a))\n    -> pseq G (deq triv triv (subst1 m b)).\nProof.\nintros G a b m.\nrevert G.\nrefine (seq_pseq 2 [hyp_tp] a [hyp_tp] b 4 [_] _ [] _ [_; _; _; _] _ [] _ _ _).\ncbn.\n(* why is this necessary? *)\nreplace (varx (obj stop) 0) with (@var (obj stop) 0) by reflexivity.\nintros G Hcla Hclb Hseqa Hpos Hseqind Hseqm.\nrewrite -> seq_eqtype in Hseqa.\nrewrite -> seq_deq in Hseqind, Hseqm |- *.\nrewrite -> seq_ispositive in Hpos; auto.\nassert (forall i s s',\n          pwctx i s s' G\n          -> exists (F : wurel_ofe top -n> wiurel_ofe top) R,\n               interp toppg true i (mu (subst (under 1 s) a)) R\n               /\\ interp toppg false i (mu (subst (under 1 s') a)) R\n               /\\ R = iubase (extend_urel top stop (mu_urel top (fun X => den (pi1 F X))))\n               /\\ monotone (fun X => den (pi1 F X))\n               /\\ (forall X (h : top << stop) (h' : top <<= stop),\n                     interp toppg true i (subst (dot (exttin top X h) s) a) (extend_iurel h' (pi1 F X))\n                     /\\ interp toppg false i (subst (dot (exttin top X h) s') a) (extend_iurel h' (pi1 F X)))) as Hmu.\n  {\n  intros i s s' Hs.\n  so (Hseqm _#3 Hs) as (A & Hmul & Hmur & Hm & _).\n  simpsubin Hmul.\n  simpsubin Hmur.\n  exploit (extract_ind toppg i (subst (under 1 s) a) (subst (under 1 s') a)) as H.\n    {\n    intros j X Y h Hj HXY.\n    so (pwctx_cons_exttin top j X Y h s s' G (le_ord_refl _) HXY (pwctx_downward _#5 Hj Hs)) as Hss.\n    so (Hseqa _ _ _ Hss) as (R & Hal & Har & _).\n    exists R.\n    simpsub.\n    auto.\n    }\n  destruct H as (F & HF).\n  assert (nonexpansive (fun X => den (pi1 F X))) as Hne.\n    {\n    apply compose_ne_ne; auto using den_nonexpansive.\n    exact (pi2 F).\n    }\n  assert (monotone (fun X => den (pi1 F X))) as HmonoF.\n    {\n    refine (monotone_from_ispositive _#4 Hpos _#3 Hs _).\n    intros X h h'.\n    so (HF X h h') as (H & _).\n    simpsubin H.\n    exact H.\n    }\n  so (positive_impl_robust _#3 (Hpos _#3 Hs andel)) as Hrobust.\n  so (positive_impl_robust _#3 (Hpos _#3 Hs ander)) as Hrobust'.\n  exists F.\n  exists (iubase (extend_urel top stop (mu_urel top (fun X => den (pi1 F X))))).\n  assert (interp toppg true i (mu (subst (under 1 s) a)) (iubase (extend_urel top stop (mu_urel top (fun X => den (pi1 F X)))))) as Hmul'.\n    {\n    apply interp_eval_refl.\n    apply interp_mu; auto using le_ord_refl.\n    intros X h.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (H & _).\n    simpsubin H.\n    simpsub.\n    exact H.\n    }\n  so (interp_fun _#7 Hmul Hmul'); subst A.\n  do2 4 split; auto.\n  intros X h h'.\n  so (HF X h h') as H.\n  simpsubin H.\n  exact H.\n  }\nintros i s s' Hs.\nso (Hmu _ _ _ Hs) as (F & R & Hmul & Hmur & HeqMu & HmonoF & HF).\nsimpsubin Hmul.\nsimpsubin Hmur.\nso (Hseqm _#3 Hs) as (R' & H & _ & Hm & _).\nsimpsubin H.\nso (interp_fun _#7 H Hmul); subst R'; clear H.\nsubst R.\nset (Mu := mu_urel top (fun X => den (pi1 F X))) in Hmul, Hmur, Hm.\nrewrite -> den_iubase in Hm.\ncbn -[mu_urel] in Hm.\nset (C := contingent_instance toppg Mu b s s' G).\nassert (incl C Mu) as Hincl.\n  {\n  clear m Hseqm Hseqind Hm Hmu.\n  intros j m p Hmp.\n  destruct Hmp; auto.\n  }\ncut (rel C i (down top (subst s m)) (down top (subst s' m))).\n  {\n  intro H.\n  so (contingent_instance_elim _#9 H) as (Hn & R & HR); clear H.\n  so (HR i s s' (le_refl _) (relctx_refl _#4 Hs)) as H.\n  destruct H as (Hl & Hr & Hinh).\n  simpsubin Hl.\n  simpsubin Hr.\n  exists (iutruncate (S i) R).\n  simpsub.\n  do2 4 split; auto; try (split; [omega | auto]; done).\n    {\n    eapply interp_updown; eauto using le_ord_refl.\n    }\n\n    {\n    eapply interp_updown; eauto using le_ord_refl.\n    }\n  }\ncut (incl Mu C); auto.\nclear m Hm Hseqm.\napply mu_least.\nintros j m p Hmp.\nassert (j <= i) as Hj.\n  {\n  set (h := succ_increase top).\n  set (h' := succ_nodecrease top).\n  so (HF C h h') as (H & _).\n  assert (rel (den (extend_iurel h' (pi1 F C))) j (up top m) (up top p)) as Hmp'.\n    {\n    cbn.\n    unfold up.\n    rewrite -> !extend_term_cancel; auto.\n    }\n  refine (basic_member_index _#9 H Hmp').\n  }\nso (succ_increase top) as h.\nassert (forall k t t',\n          k <= j\n          -> relctx k s s' t t' G\n          -> let h' := lt_ord_impl_le_ord _ _ h in\n             let C' := extend_iurel h' (iutruncate (S k) (iubase C))\n             in\n               exists (B : urelsp (den C') -n> siurel_ofe),\n                 functional the_system toppg true k (den C') (subst (under 1 t) b) B\n                 /\\ functional the_system toppg false k (den C') (subst (under 1 t') b) B) as Hfunc.\n  {\n  intros k t t' Hk Hst h' C'.\n  assert (k <= i) as Hki by omega.\n  so (pwctx_impl_closub _#4 (relctx_pwctx _#6 Hst)) as (Hclt & Hclt').\n  apply extract_functional.\n    {\n    subst C'.\n    rewrite -> !den_extend_iurel.\n    rewrite -> !den_iutruncate.\n    rewrite -> ceiling_extend_urel.\n    rewrite -> ceiling_idem.\n    reflexivity.\n    }\n\n    {\n    eapply subst_closub_under_permit; eauto.\n    }\n    \n    {\n    eapply subst_closub_under_permit; eauto.\n    }\n    \n    {\n    intros l n q Hnq.\n    unfold C' in Hnq.\n    rewrite -> den_extend_iurel in Hnq.\n    cbn -[C] in Hnq.\n    destruct Hnq as (H & Hnq).\n    assert (l <= k) as Hlk by omega.\n    clear H.\n    so (contingent_instance_elim _#9 Hnq) as (_ & R & HR).\n    so (HR _#3 (le_refl _) (relctx_downward _#7 Hlk Hst)) as (Hn & Hq & _).\n    clear HR.\n    exists (iutruncate (S l) R).\n    simpsub.\n    change (map_term (extend (succ top) top) n) with (down top n) in Hn.\n    change (map_term (extend (succ top) top) q) with (down top q) in Hq.\n    split.\n      {\n      eapply (interp_updown _ top); eauto using le_ord_refl.\n      }\n\n      {\n      eapply (interp_updown _ top); eauto using le_ord_refl.\n      }\n    }\n  }\nassert (forall k t t',\n          k <= j\n          -> relctx k s s' t t' G\n          -> pwctx k (dot (exttin top C h) t) (dot (exttin top C h) t') (hyp_tp :: G)) as Htp.\n  {\n  intros k t t' Hk Ht.\n  set (h' := lt_ord_impl_le_ord _ _ h).\n  set (C' := extend_iurel h' (iutruncate (S k) (iubase C))).\n  apply pwctx_cons_tp.\n    {\n    eapply relctx_pwctx; eauto.\n    }\n  apply (seqhyp_tp _#3 C').\n    {\n    apply interp_eval_refl.\n    apply interp_extt.\n    apply le_ord_refl.\n    }\n\n    {\n    apply interp_eval_refl.\n    apply interp_extt.\n    apply le_ord_refl.\n    }\n  }\nassert (forall k t t',\n          k <= j\n          -> relctx k s s' t t' G\n          -> pwctx k\n               (dot (lam triv) (dot triv (dot (up top m) (dot (exttin top C h) t))))\n               (dot (lam triv) (dot triv (dot (up top p) (dot (exttin top C h) t'))))\n               (hyp_tm (pi (var 2) (subst (under 1 (sh 3)) b)) ::\n                hyp_tm (subtype (var 1) (mu (subst (dot (var 0) (sh 3)) a))) ::\n                hyp_tm a :: hyp_tp :: G)) as Hss.\n  {\n  intros k t t' Hk Hst.\n  assert (k <= i) as Hki by omega.\n  set (h' := lt_ord_impl_le_ord _ _ h).\n  set (C' := extend_iurel h' (iutruncate (S k) (iubase C))).\n  apply pwctx_cons_tm.\n    {\n    apply pwctx_cons_tm_seq.\n      {\n      apply pwctx_cons_tm_seq.\n        {\n        apply Htp; auto.\n        }\n\n        {\n        so (HF C h h') as (Hl & Hr).\n        simpsubin Hl.\n        simpsubin Hr.\n        so (basic_downward _#7 Hj Hl) as H.\n        renameover H into Hl.\n        so (basic_downward _#7 Hj Hr) as H.\n        renameover H into Hr.\n        so (Hseqa _ _ _ (Htp _ _ _ Hk Hst)) as (R' & Hlt & Hrt & _).\n        assert (R' = iutruncate (S k) (extend_iurel h' (pi1 F C))).\n          {\n          so (Hseqa _#3 (Htp _#3 Hk (relctx_swap1 _#6 Hst))) as (R'' & Hl' & _ & _ & Hrt').\n          so (interp_fun _#7 (basic_downward _#7 Hk Hl) Hl'); subst R''.\n          so (interp_fun _#7 Hrt Hrt') as H.\n          rewrite -> iutruncate_combine_le in H; auto.\n          omega.\n          }\n        subst R'.\n        apply (seqhyp_tm _#5 (iutruncate (S k) (extend_iurel h' (pi1 F C)))); auto.\n        cbn.\n        split; [omega |].\n        unfold up.\n        rewrite -> !extend_term_cancel; auto.\n        apply (urel_downward_leq _#3 j); auto.\n        }\n\n        {\n        intros l u u' Hu.\n        so (Hseqa _#3 Hu) as (R & Hl & Hr & _).\n        exists toppg, R.\n        auto.\n        }\n      }\n\n      {\n      simpsub.\n      apply (seqhyp_tm _#5 (iusubtype stop k C' (iutruncate (S k) (iubase (extend_urel top stop Mu))))).\n        {\n        apply interp_eval_refl.\n        apply interp_subtype.\n          {\n          apply interp_eval_refl.\n          apply interp_extt.\n          apply le_ord_refl.\n          }\n\n          {\n          so (Hmu _#3 (relctx_pwctx _#6 (relctx_swap2 _#6 Hst))) as (_ & R & Hl & Hr & _).\n          so (interp_fun _#7 (basic_downward _#7 Hki Hmur) Hr); subst R.\n          exact Hl.\n          }\n        }\n\n        {\n        apply interp_eval_refl.\n        apply interp_subtype.\n          {\n          apply interp_eval_refl.\n          apply interp_extt.\n          apply le_ord_refl.\n          }\n\n          {\n          so (Hmu _#3 (relctx_pwctx _#6 (relctx_swap1 _#6 Hst))) as (_ & R & Hl & Hr & _).\n          so (interp_fun _#7 (basic_downward _#7 Hki Hmul) Hl); subst R.\n          exact Hr.\n          }\n        }\n\n        {\n        cbn.\n        do2 5 split; auto using star_refl; try (apply hygiene_auto; cbn; auto; done).\n        intros l n q Hl Hnq.\n        destruct Hnq as (_, Hnq).\n        split; [omega |].\n        cbn -[Mu].\n        destruct Hnq as (Hnq & _).\n        exact Hnq.\n        }\n      }\n\n      {\n      clear i j m p Hmp s s' t t' Hs Hst Hmul Hmur HF C Hincl Hj Htp C' F Mu h h' HmonoF k Hk Hki Hfunc.\n      intros i ss ss' Hss.\n      so (pwctx_cons_invert_simple _#5 Hss) as (m & p & s1 & s1' & Hs1 & Hmp & -> & ->).\n      so (pwctx_cons_invert_simple _#5 Hs1) as (c & d & s & s' & Hs & Hcd & -> & ->).\n      simpsub.\n      clear Hss Hs1.\n      clear m p Hmp.\n      invertc Hcd.\n      intros R1 Hl1 Hr1.\n      so (Hmu _#3 Hs) as (_ & R2 & Hl2 & Hr2 & _).\n      exists toppg, (iusubtype stop i R1 R2).\n      split.\n        {\n        apply interp_eval_refl.\n        apply interp_subtype; auto.\n        }\n\n        {\n        apply interp_eval_refl.\n        apply interp_subtype; auto.\n        }\n      }\n    }\n\n    {\n    simpsub.\n    change (3 + 1) with 4.\n    simpsub.\n    clear m p Hmp.\n    so (Hfunc _ _ _ Hk Hst) as H.\n    destruct H as (B & Hbl & Hbr).\n    fold h' in Hbl, Hbr.\n    fold C' in Hbl, Hbr.\n    apply (seqhyp_tm _#5 (iupi stop k C' B)).\n      {\n      apply interp_eval_refl.\n      apply interp_pi; auto.\n      apply interp_eval_refl.\n      apply interp_extt.\n      apply le_ord_refl.\n      }\n\n      {\n      apply interp_eval_refl.\n      apply interp_pi; auto.\n      apply interp_eval_refl.\n      apply interp_extt.\n      apply le_ord_refl.\n      }\n\n      {\n      exists triv, triv.\n      do2 5 split; auto using star_refl.\n        {\n        apply hygiene_auto; cbn.\n        split; auto.\n        apply hygiene_auto; cbn; auto.\n        }\n\n        {\n        apply hygiene_auto; cbn.\n        split; auto.\n        apply hygiene_auto; cbn; auto.\n        }\n      intros l n q Hlk Hnq.\n      simpsub.\n      so Hnq as H.\n      unfold C' in H.\n      rewrite -> den_extend_iurel in H.\n      cbn -[C] in H.\n      destruct H as (_ & H).\n      so (contingent_instance_elim _#9 H) as (Hnq' & R & HR).\n      clear H.\n      so (HR _ _ _ (le_refl _) (relctx_downward _#7 Hlk Hst)) as (Hl & _ & Hinh).\n      clear HR.\n      invert Hbl.\n      intros _ _ Hact.\n      so (Hact _#3 Hlk Hnq) as Hl'.\n      clear Hact.\n      simpsubin Hl'.\n      so (interp_fun _#7 (interp_updown _#8 (le_ord_refl _) Hl) Hl') as Heq.\n      match goal with\n      | |- rel (den ?Z) _ _ _ => replace Z with (iutruncate (S l) R)\n      end.\n      rewrite -> den_iutruncate.\n      split; [omega |].\n      auto.\n      }\n    }\n\n    {\n    intros l u Hlk Htuu.\n    simpsub.\n    change (3 + 1) with 4.\n    simpsub.\n    so (pwctx_cons_invert_simple _#5 Htuu) as (x & y & u1 & u1' & Hu1 & Hxy & Heq & ->).\n    simpsub.\n    simpsubin Hu1.\n    injectionc Heq.\n    intros <- _.\n    clear x y Hxy Htuu.\n    so (pwctx_cons_invert_simple _#5 Hu1) as (x & y & u2 & u2' & Hu2 & Hxy & Heq & ->).\n    clear Hu1.\n    simpsub.\n    injectionc Heq.\n    intros <- _.\n    clear x y Hxy.\n    so (pwctx_cons_invert_simple _#5 Hu2) as (x & y & u & u' & Htu & Hxy & Heq & ->).\n    clear Hu2.\n    injectionc Heq.\n    intros <- <-.\n    simpsub.\n    simpsubin Hxy.\n    invertc Hxy.\n    intros R Hl Hr.\n    invert (basic_value_inv _#6 value_extt Hl).\n    intros w R' h'' _ Heq <-.\n    injection (objin_inj _ _ _ Heq); clear Heq.\n    intros Heq ->.\n    injectionT Heq.\n    intros ->.\n    so (proof_irrelevance _ h h''); subst h''.\n    assert (l <= j) as Hlj by omega.\n    so (relctx_trans_right _#7 (pwctx_impl_seqctx _#4 Htu) (relctx_downward _#7 Hlk Hst)) as Hstu.\n    clear C'.\n    set (C' := extend_iurel h' (iutruncate (S l) (iubase C))).\n    so (Hfunc _#3 Hlj Hstu) as (B & Hbtl & Hbur).\n    so (Hfunc _#3 Hlj (relctx_downward _#7 Hlk Hst)) as (B' & Hbtl' & Hbtr).\n    fold h' in Hbtl, Hbur, Hbtl', Hbtr.\n    fold C' in Hbtl, Hbur, Hbtl', Hbtr.\n    so (functional_fun _#8 Hbtl Hbtl'); subst B'.\n    clear Hbtl Hbtl'.\n    apply (relhyp_tm _#4 (iupi stop l C' B)).\n      {\n      apply interp_eval_refl.\n      apply interp_pi; auto.\n      apply interp_eval_refl.\n      apply interp_extt.\n      apply le_ord_refl.\n      }\n\n      {\n      apply interp_eval_refl.\n      apply interp_pi; auto.\n      }\n    }\n\n    (* symmetric *)\n    {\n    intros l u Hlk Htuu.\n    simpsub.\n    change (3 + 1) with 4.\n    simpsub.\n    so (pwctx_cons_invert_simple _#5 Htuu) as (x & y & u1 & u1' & Hu1 & Hxy & -> & Heq).\n    simpsub.\n    simpsubin Hu1.\n    injectionc Heq.\n    intros <- _.\n    clear x y Hxy Htuu.\n    so (pwctx_cons_invert_simple _#5 Hu1) as (x & y & u2 & u2' & Hu2 & Hxy & -> & Heq).\n    clear Hu1.\n    simpsub.\n    injectionc Heq.\n    intros <- _.\n    clear x y Hxy.\n    so (pwctx_cons_invert_simple _#5 Hu2) as (x & y & u & u' & Hut & Hxy & -> & Heq).\n    clear Hu2.\n    injectionc Heq.\n    intros <- <-.\n    simpsub.\n    simpsubin Hxy.\n    invertc Hxy.\n    intros R Hl Hr.\n    invert (basic_value_inv _#6 value_extt Hr).\n    intros w R' h'' _ Heq <-.\n    injection (objin_inj _ _ _ Heq); clear Heq.\n    intros Heq ->.\n    injectionT Heq.\n    intros ->.\n    so (proof_irrelevance _ h h''); subst h''.\n    assert (l <= j) as Hlj by omega.\n    so (relctx_trans_left _#7 (pwctx_impl_seqctx _#4 Hut) (relctx_downward _#7 Hlk Hst)) as Hstu.\n    clear C'.\n    set (C' := extend_iurel h' (iutruncate (S l) (iubase C))).\n    so (Hfunc _#3 Hlj Hstu) as (B & Hbul & Hbtr).\n    so (Hfunc _#3 Hlj (relctx_downward _#7 Hlk Hst)) as (B' & Hbtl & Hbtr').\n    fold h' in Hbul, Hbtr, Hbtl, Hbtr'.\n    fold C' in Hbul, Hbtr, Hbtl, Hbtr'.\n    so (functional_fun _#8 Hbtr Hbtr'); subst B'.\n    clear Hbtr Hbtr'.\n    apply (relhyp_tm _#4 (iupi stop l C' B)).\n      {\n      apply interp_eval_refl.\n      apply interp_pi; auto.\n      apply interp_eval_refl.\n      apply interp_extt.\n      apply le_ord_refl.\n      }\n\n      {\n      apply interp_eval_refl.\n      apply interp_pi; auto.\n      }\n    }\n  }\nso (Hseqind j _ _ (Hss j s s' (le_refl _) (relctx_refl _#4 (pwctx_downward _#5 Hj Hs)))) as (R & Hl & Hr & Hinh & _).\nsimpsubin Hl.\nsimpsubin Hr.\nsimpsubin Hinh.\nsplit.\n  {\n  unfold Mu.\n  rewrite -> mu_fix; auto.\n  so (HmonoF C Mu Hincl) as Hincl'.\n  cbn in Hincl'.\n  apply Hincl'; auto.\n  }\nexists R.\nintros k c d Hk Hcd.\ndestruct Hcd as (t & t' & Hst & -> & ->).\nsimpsub.\nassert (k <= i) as Hki by omega.\nso (Hseqind k _ _ (Hss k t t' Hk Hst)) as H.\nsimpsubin H.\ndestruct H as (R' & Hlt & Hrt & _).\nso (Hseqind k _ _ (Hss k s t' Hk (relctx_swap1 _#6 Hst))) as H.\nsimpsubin H.\ndestruct H as (R'' & Hl' & Hrt' & _).\nso (interp_fun _#7 Hl' (basic_downward _#7 Hk Hl)); subst R''.\nso (interp_fun _#7 Hrt Hrt'); subst R'.\ndo2 2 split; auto.\napply (urel_downward_leq _#3 j); auto.\nQed.\n\n\nLemma sound_mu_ind_univ :\n  forall G lv a b m,\n    pseq G (deq lv lv pagetp)\n    -> pseq (hyp_tm (univ lv) :: G) (deq a a (univ (subst sh1 lv)))\n    -> pseq G (deq triv triv (ispositive a))\n    -> pseq\n         (hyp_tm (pi (var 2) (subst (under 1 (sh 3)) b)) ::\n          hyp_tm (subtype (var 1) (mu (subst (under 1 (sh 2)) a))) ::\n          hyp_tm a ::\n          hyp_tm (univ lv) :: \n          G)\n         (deq \n            (subst (dot (var 2) (sh 4)) b)\n            (subst (dot (var 2) (sh 4)) b) \n            (univ (subst (sh 4) lv)))\n    -> pseq\n         (hyp_tm (pi (var 2) (subst (under 1 (sh 3)) b)) ::\n          hyp_tm (subtype (var 1) (mu (subst (under 1 (sh 2)) a))) ::\n          hyp_tm a ::\n          hyp_tm (univ lv) :: \n          G)\n         (deq triv triv (subst (dot (var 2) (sh 4)) b))\n    -> pseq G (deq m m (mu a))\n    -> pseq G (deq triv triv (subst1 m b)).\nProof.\nintros G lv a b m.\nrevert G.\nrefine (seq_pseq 2 [hyp_tp] a [hyp_tp] b 6 [] _ [_] _ [] _ [_; _; _; _] _ [_; _; _; _] _ [] _ _ _).\ncbn.\n(* why is this necessary? *)\nreplace (varx (obj stop) 0) with (@var (obj stop) 0) by reflexivity.\nintros G Hcla Hclb Hseqlv Hseqa Hpos Hseqb Hseqind Hseqm.\nrewrite -> seq_univ in Hseqa, Hseqb.\nrewrite -> seq_deq in Hseqind, Hseqm |- *.\nrewrite -> seq_ispositive in Hpos; auto.\nassert (forall i s s',\n          pwctx i s s'\n            (hyp_tm (pi (var 2) (subst (dot (var 0) (sh 4)) b))\n             :: hyp_tm (subtype (var 1) (mu (subst (dot (var 0) (sh 3)) a)))\n             :: hyp_tm a \n             :: hyp_tm (univ lv) \n             :: G)\n          -> exists pg R,\n               pginterp (subst s (subst (sh 4) lv)) pg\n               /\\ pginterp (subst s' (subst (sh 4) lv)) pg\n               /\\ interp pg true i (subst s (subst (dot (var 2) (sh 4)) b)) R\n               /\\ interp pg false i (subst s' (subst (dot (var 2) (sh 4)) b)) R\n               /\\ rel (den R) i triv triv) as Hseqind'.\n  {\n  intros i s s' Hs.\n  so (Hseqb _#3 Hs) as (pg & R & Hlvl & Hlvr & Hbl & Hbr & _).\n  so (Hseqind _#3 Hs) as (R' & Hbl' & _ & Hinh & _).\n  so (interp_fun _#7 Hbl Hbl'); subst R'.\n  exists pg, R.\n  do2 4 split; auto.\n  }\nclear Hseqb Hseqind.\nrename Hseqind' into Hseqind.\nso Hseqlv as H.\nrewrite -> seq_deq in H.\nexploit (seq_pagetp_invert G lv) as Hlevel.\n  {\n  intros i s s' Hs.\n  so (H _#3 Hs) as (R & H1 & _ & H2 & _).\n  eauto.\n  }\nclear H.\nassert (forall i s s',\n          pwctx i s s' G\n          -> exists pg (F : wurel_ofe (cin pg) -n> wiurel_ofe (cin pg)) R,\n               pginterp (subst s lv) pg\n               /\\ interp toppg true i (mu (subst (under 1 s) a)) R\n               /\\ interp toppg false i (mu (subst (under 1 s') a)) R\n               /\\ R = iubase (extend_urel (cin pg) stop (mu_urel (cin pg) (fun X => den (pi1 F X))))\n               /\\ monotone (fun X => den (pi1 F X))\n               /\\ (forall X (h : cin pg << stop) (h' : cin pg <<= stop),\n                     interp pg true i (subst (dot (exttin (cin pg) X h) s) a) (extend_iurel h' (pi1 F X))\n                     /\\ interp pg false i (subst (dot (exttin (cin pg) X h) s') a) (extend_iurel h' (pi1 F X)))) as Hmu.\n  {\n  intros i s s' Hs.\n  so (Hlevel _#3 Hs) as (pg & Hlvl & Hlvr).\n  so (Hseqm _#3 Hs) as (A & Hmul & Hmur & Hm & _).\n  simpsubin Hmul.\n  simpsubin Hmur.\n  exploit (extract_ind pg i (subst (under 1 s) a) (subst (under 1 s') a)) as H.\n    {\n    intros j X Y h Hj HXY.\n    so (pwctx_cons_exttin_tm pg (cin pg) j X Y h s s' G lv (le_ord_refl _) Hlvl Hseqlv HXY (pwctx_downward _#5 Hj Hs)) as Hss.\n    so (Hseqa _ _ _ Hss) as (pg' & R & Hlvl' & _ & Hal & Har & _).\n    simpsubin Hlvl'.\n    so (pginterp_fun _#3 Hlvl Hlvl'); subst pg'.\n    exists R.\n    simpsub.\n    eauto.\n    }\n  destruct H as (F & HF).\n  assert (nonexpansive (fun X => den (pi1 F X))) as Hne.\n    {\n    apply compose_ne_ne; auto using den_nonexpansive.\n    exact (pi2 F).\n    }\n  assert (monotone (fun X => den (pi1 F X))) as HmonoF.\n    {\n    refine (monotone_from_ispositive _#4 Hpos _#3 Hs _).\n    intros X h h'.\n    so (HF X h h') as (H & _).\n    simpsubin H.\n    exact H.\n    }\n  so (positive_impl_robust _#3 (Hpos _#3 Hs andel)) as Hrobust.\n  so (positive_impl_robust _#3 (Hpos _#3 Hs ander)) as Hrobust'.\n  exists pg, F.\n  exists (iubase (extend_urel (cin pg) stop (mu_urel (cin pg) (fun X => den (pi1 F X))))).\n  assert (interp pg true i (mu (subst (under 1 s) a)) (iubase (extend_urel (cin pg) stop (mu_urel (cin pg) (fun X => den (pi1 F X)))))) as Hmul'.\n    {\n    apply interp_eval_refl.\n    apply interp_mu; auto using le_ord_refl.\n    intros X h.\n    so (HF X h (lt_ord_impl_le_ord _ _ h)) as (H & _).\n    simpsubin H.\n    simpsub.\n    exact H.\n    }\n  so (interp_fun _#7 Hmul Hmul'); subst A.\n  do2 5 split; auto.\n  intros X h h'.\n  so (HF X h h') as H.\n  simpsubin H.\n  exact H.\n  }\nintros i s s' Hs.\nso (Hmu _ _ _ Hs) as (pg & F & R & Hlvl & Hmul & Hmur & HeqMu & HmonoF & HF).\nset (w := cin pg).\n(* We need cex pg <<= w = cin pg because we're using terms of candidate\n   level w (since they are in an inductive type belonging to pg), but \n   we need to cancel up and down inside a type expression (namely b),\n   which we can only do if cex b <<= w.  (Consider the rules of restriction.)\n\n   Perhaps this can be teased apart.  I haven't tried all that hard since, for\n   the moment at least, we always have cex pg = cin pg.\n*)\nassert (cex pg <<= w) as Hexw.\n  {\n  unfold w.\n  apply le_ord_refl'.\n  symmetry.\n  eapply pginterp_cin_cex; eauto.\n  }\nsimpsubin Hmul.\nsimpsubin Hmur.\nso (Hseqm _#3 Hs) as (R' & H & _ & Hm & _).\nsimpsubin H.\nso (interp_fun _#7 H Hmul); subst R'; clear H.\nsubst R.\nset (Mu := mu_urel w (fun X => den (pi1 F X))) in Hmul, Hmur, Hm.\nrewrite -> den_iubase in Hm.\ncbn -[mu_urel] in Hm.\nset (C := contingent_instance pg Mu b s s' G).\nassert (incl C Mu) as Hincl.\n  {\n  clear m Hseqm Hseqind Hm Hmu.\n  intros j m p Hmp.\n  destruct Hmp; auto.\n  }\ncut (rel C i (down w (subst s m)) (down w (subst s' m))).\n  {\n  intro H.\n  so (contingent_instance_elim _#9 H) as (Hn & R & HR); clear H.\n  so (HR i s s' (le_refl _) (relctx_refl _#4 Hs)) as H.\n  destruct H as (Hl & Hr & Hinh).\n  simpsubin Hl.\n  simpsubin Hr.\n  exists (iutruncate (S i) R).\n  simpsub.\n  do2 4 split; auto; try (split; [omega | auto]; done).\n    {\n    apply (interp_increase pg); auto using toppg_max.\n    eapply interp_updown; eauto.\n    }\n\n    {\n    apply (interp_increase pg); auto using toppg_max.\n    eapply interp_updown; eauto.\n    }\n  }\ncut (incl Mu C); auto.\nclear m Hm Hseqm.\napply mu_least.\nintros j m p Hmp.\nassert (j <= i) as Hj.\n  {\n  set (h := le_ord_succ _ _ (cin_top pg)).\n  set (h' := cin_stop pg).\n  so (HF C h h') as (H & _).\n  assert (rel (den (extend_iurel h' (pi1 F C))) j (up w m) (up w p)) as Hmp'.\n    {\n    cbn.\n    unfold w, up.\n    rewrite -> !extend_term_cancel; auto.\n    }\n  refine (basic_member_index _#9 H Hmp').\n  }\nso (le_ord_succ _ _ (cin_top pg)) as h.\nchange (w << stop) in h.\nassert (forall k t t',\n          k <= j\n          -> relctx k s s' t t' G\n          -> let h' := lt_ord_impl_le_ord _ _ h in\n             let C' := extend_iurel h' (iutruncate (S k) (iubase C))\n             in\n               exists (B : urelsp (den C') -n> siurel_ofe),\n                 functional the_system pg true k (den C') (subst (under 1 t) b) B\n                 /\\ functional the_system pg false k (den C') (subst (under 1 t') b) B) as Hfunc.\n  {\n  intros k t t' Hk Hst h' C'.\n  assert (k <= i) as Hki by omega.\n  so (pwctx_impl_closub _#4 (relctx_pwctx _#6 Hst)) as (Hclt & Hclt').\n  apply extract_functional.\n    {\n    subst C'.\n    rewrite -> !den_extend_iurel.\n    rewrite -> !den_iutruncate.\n    rewrite -> ceiling_extend_urel.\n    rewrite -> ceiling_idem.\n    reflexivity.\n    }\n\n    {\n    eapply subst_closub_under_permit; eauto.\n    }\n    \n    {\n    eapply subst_closub_under_permit; eauto.\n    }\n    \n    {\n    intros l n q Hnq.\n    unfold C' in Hnq.\n    rewrite -> den_extend_iurel in Hnq.\n    cbn -[C] in Hnq.\n    destruct Hnq as (H & Hnq).\n    assert (l <= k) as Hlk by omega.\n    clear H.\n    so (contingent_instance_elim _#9 Hnq) as (_ & R & HR).\n    so (HR _#3 (le_refl _) (relctx_downward _#7 Hlk Hst)) as (Hn & Hq & _).\n    clear HR.\n    exists (iutruncate (S l) R).\n    simpsub.\n    change (map_term (extend stop w) n) with (down w n) in Hn.\n    change (map_term (extend stop w) q) with (down w q) in Hq.\n    split.\n      {\n      eapply interp_updown; eauto.\n      }\n\n      {\n      eapply interp_updown; eauto.\n      }\n    }\n  }\nassert (forall k t t',\n          k <= j\n          -> relctx k s s' t t' G\n          -> pwctx k (dot (exttin w C h) t) (dot (exttin w C h) t') (hyp_tm (univ lv) :: G)) as Htp.\n  {\n  intros k t t' Hk Ht.\n  set (h' := lt_ord_impl_le_ord _ _ h).\n  set (C' := extend_iurel h' (iutruncate (S k) (iubase C))).\n  apply pwctx_cons_tm_seq.\n    {\n    eapply relctx_pwctx; eauto.\n    }\n    \n    {\n    apply (seqhyp_tm _#5 (iuuniv the_system k pg)).\n      {\n      simpsub.\n      apply interp_eval_refl.\n      apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n      exact (relctx_pginterp _#8 Hseqlv Ht Hlvl andel).\n      }\n  \n      {\n      simpsub.\n      apply interp_eval_refl.\n      apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n      exact (relctx_pginterp _#8 Hseqlv Ht Hlvl ander).\n      }\n\n      {\n      cbn.\n      split; auto.\n      exists C'.\n      rewrite -> sint_unroll.\n      split.\n        {\n        apply interp_eval_refl.\n        apply interp_extt.\n        apply le_ord_refl.\n        }\n\n        {\n        apply interp_eval_refl.\n        apply interp_extt.\n        apply le_ord_refl.\n        }\n      }\n    }\n\n    {\n    clear a b Hcla Hclb Hseqa Hpos Hseqind Hmu i s s' Hs pg F Hlvl Hmur Hmul HmonoF HF w Hexw Mu C Hincl j m p Hmp Hj h Hfunc k t t' Hk Ht h' C'.\n    intros i s s' Hs.\n    so (Hlevel _#3 Hs) as (pg & Hlvl & Hlvr).\n    exists toppg, (iuuniv the_system i pg).\n    simpsub.\n    split.\n      {\n      apply interp_eval_refl.\n      apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n      }\n\n      {\n      apply interp_eval_refl.\n      apply interp_univ; eauto using pginterp_str_top, pginterp_cex_top.\n      }\n    }\n  }\nassert (forall k t t',\n          k <= j\n          -> relctx k s s' t t' G\n          -> pwctx k\n               (dot (lam triv) (dot triv (dot (up w m) (dot (exttin w C h) t))))\n               (dot (lam triv) (dot triv (dot (up w p) (dot (exttin w C h) t'))))\n               (hyp_tm (pi (var 2) (subst (under 1 (sh 3)) b)) ::\n                hyp_tm (subtype (var 1) (mu (subst (dot (var 0) (sh 3)) a))) ::\n                hyp_tm a :: hyp_tm (univ lv) :: G)) as Hss.\n  {\n  intros k t t' Hk Hst.\n  assert (k <= i) as Hki by omega.\n  set (h' := lt_ord_impl_le_ord _ _ h).\n  set (C' := extend_iurel h' (iutruncate (S k) (iubase C))).\n  apply pwctx_cons_tm.\n    {\n    apply pwctx_cons_tm_seq.\n      {\n      apply pwctx_cons_tm_seq.\n        {\n        apply Htp; auto.\n        }\n\n        {\n        so (HF C h h') as (Hl & Hr).\n        simpsubin Hl.\n        simpsubin Hr.\n        so (basic_downward _#7 Hj Hl) as H.\n        renameover H into Hl.\n        so (basic_downward _#7 Hj Hr) as H.\n        renameover H into Hr.\n        so (Hseqa _ _ _ (Htp _ _ _ Hk Hst)) as (pg' & R' & Hlvtl & Hlvtr & Hlt & Hrt & _).\n        assert (R' = iutruncate (S k) (extend_iurel h' (pi1 F C))).\n          {\n          so (Hseqa _#3 (Htp _#3 Hk (relctx_swap1 _#6 Hst))) as (pg'' & R'' & Hlvtl' & _ & Hl' & _ & _ & Hrt').\n          so (interp_fun _#7 (basic_downward _#7 Hk Hl) Hl'); subst R''.\n          so (interp_fun _#7 Hrt Hrt') as H.\n          rewrite -> iutruncate_combine_le in H; auto.\n          omega.\n          }\n        subst R'.\n        apply (seqhyp_tm _#5 (iutruncate (S k) (extend_iurel h' (pi1 F C)))); eauto using interp_increase, toppg_max.\n        cbn.\n        split; [omega |].\n        unfold up.\n        rewrite -> !extend_term_cancel; auto.\n        apply (urel_downward_leq _#3 j); auto.\n        }\n\n        {\n        intros l u u' Hu.\n        so (Hseqa _#3 Hu) as (pg' & R & _ & _ & Hl & Hr & _).\n        exists pg', R.\n        auto.\n        }\n      }\n\n      {\n      simpsub.\n      apply (seqhyp_tm _#5 (iusubtype stop k C' (iutruncate (S k) (iubase (extend_urel w stop Mu))))).\n        {\n        apply interp_eval_refl.\n        apply interp_subtype.\n          {\n          apply interp_eval_refl.\n          apply interp_extt.\n          apply cin_top.\n          }\n\n          {\n          so (Hmu _#3 (relctx_pwctx _#6 (relctx_swap2 _#6 Hst))) as (_ & _ & R & _ & Hl & Hr & _).\n          so (interp_fun _#7 (basic_downward _#7 Hki Hmur) Hr); subst R.\n          exact Hl.\n          }\n        }\n\n        {\n        apply interp_eval_refl.\n        apply interp_subtype.\n          {\n          apply interp_eval_refl.\n          apply interp_extt.\n          apply cin_top.\n          }\n\n          {\n          so (Hmu _#3 (relctx_pwctx _#6 (relctx_swap1 _#6 Hst))) as (_ & _ & R & _ & Hl & Hr & _).\n          so (interp_fun _#7 (basic_downward _#7 Hki Hmul) Hl); subst R.\n          exact Hr.\n          }\n        }\n\n        {\n        cbn.\n        do2 5 split; auto using star_refl; try (apply hygiene_auto; cbn; auto; done).\n        intros l n q Hl Hnq.\n        destruct Hnq as (_, Hnq).\n        split; [omega |].\n        cbn -[Mu].\n        destruct Hnq as (Hnq & _).\n        exact Hnq.\n        }\n      }\n\n      {\n      clear i j m p Hmp s s' t t' Hs Hst Hmul Hmur HF C Hincl Hj Htp C' F Mu h h' HmonoF k Hk Hki Hfunc Hlvl.\n      intros i ss ss' Hss.\n      so (pwctx_cons_invert_simple _#5 Hss) as (m & p & s1 & s1' & Hs1 & Hmp & -> & ->).\n      so (pwctx_cons_invert_simple _#5 Hs1) as (c & d & s & s' & Hs & Hcd & -> & ->).\n      simpsub.\n      clear Hss Hs1.\n      clear m p Hmp.\n      simpsubin Hcd.\n      invertc Hcd.\n      intros Ru Huniv _ Hcd.\n      invert (basic_value_inv _#6 value_univ Huniv).\n      intros pg' _ _ _ <-.\n      cbn in Hcd.\n      destruct Hcd as (_ & R1 & Hl1 & Hr1).\n      rewrite -> sint_unroll in Hl1, Hr1.\n      so (Hmu _#3 Hs) as (_ & _ & R2 & _ & Hl2 & Hr2 & _).\n      exists toppg, (iusubtype stop i R1 R2).\n      split.\n        {\n        apply interp_eval_refl.\n        apply interp_subtype; auto.\n        apply (interp_increase pg'); auto using toppg_max.\n        }\n\n        {\n        apply interp_eval_refl.\n        apply interp_subtype; auto.\n        apply (interp_increase pg'); auto using toppg_max.\n        }\n      }\n    }\n\n    {\n    simpsub.\n    change (3 + 1) with 4.\n    simpsub.\n    clear m p Hmp.\n    so (Hfunc _ _ _ Hk Hst) as H.\n    destruct H as (B & Hbl & Hbr).\n    fold h' in Hbl, Hbr.\n    fold C' in Hbl, Hbr.\n    apply (seqhyp_tm _#5 (iupi stop k C' B)).\n      {\n      apply (interp_increase pg); auto using toppg_max.\n      apply interp_eval_refl.\n      apply interp_pi; auto.\n      apply interp_eval_refl.\n      apply interp_extt.\n      apply le_ord_refl.\n      }\n\n      {\n      apply (interp_increase pg); auto using toppg_max.\n      apply interp_eval_refl.\n      apply interp_pi; auto.\n      apply interp_eval_refl.\n      apply interp_extt.\n      apply le_ord_refl.\n      }\n\n      {\n      exists triv, triv.\n      do2 5 split; auto using star_refl.\n        {\n        apply hygiene_auto; cbn.\n        split; auto.\n        apply hygiene_auto; cbn; auto.\n        }\n\n        {\n        apply hygiene_auto; cbn.\n        split; auto.\n        apply hygiene_auto; cbn; auto.\n        }\n      intros l n q Hlk Hnq.\n      simpsub.\n      so Hnq as H.\n      unfold C' in H.\n      rewrite -> den_extend_iurel in H.\n      cbn -[C] in H.\n      destruct H as (_ & H).\n      so (contingent_instance_elim _#9 H) as (Hnq' & R & HR).\n      clear H.\n      so (HR _ _ _ (le_refl _) (relctx_downward _#7 Hlk Hst)) as (Hl & _ & Hinh).\n      clear HR.\n      invert Hbl.\n      intros _ _ Hact.\n      so (Hact _#3 Hlk Hnq) as Hl'.\n      clear Hact.\n      simpsubin Hl'.\n      so (interp_fun _#7 (interp_updown _#8 Hexw Hl) Hl') as Heq.\n      match goal with\n      | |- rel (den ?Z) _ _ _ => replace Z with (iutruncate (S l) R)\n      end.\n      rewrite -> den_iutruncate.\n      split; [omega |].\n      auto.\n      }\n    }\n\n    {\n    intros l u Hlk Htuu.\n    simpsub.\n    change (3 + 1) with 4.\n    simpsub.\n    so (pwctx_cons_invert_simple _#5 Htuu) as (x & y & u1 & u1' & Hu1 & Hxy & Heq & ->).\n    simpsub.\n    simpsubin Hu1.\n    injectionc Heq.\n    intros <- _.\n    clear x y Hxy Htuu.\n    so (pwctx_cons_invert_simple _#5 Hu1) as (x & y & u2 & u2' & Hu2 & Hxy & Heq & ->).\n    clear Hu1.\n    simpsub.\n    injectionc Heq.\n    intros <- _.\n    clear x y Hxy.\n    so (pwctx_cons_invert_simple _#5 Hu2) as (x & y & u & u' & Htu & Hxy & Heq & ->).\n    clear Hu2.\n    injectionc Heq.\n    intros <- <-.\n    simpsub.\n    simpsubin Hxy.\n    invertc Hxy.\n    intros Ru Huniv _ Hlr.\n    invert (basic_value_inv _#6 value_univ Huniv).\n    intros pg' Hlvt _ _ <-.\n    so (pginterp_fun _#3 Hlvt (relctx_pginterp _#8 Hseqlv Hst Hlvl andel)); subst pg'.\n    cbn in Hlr.\n    destruct Hlr as (_ & R & Hl & Hr).\n    rewrite -> sint_unroll in Hl, Hr.\n    invert (basic_value_inv _#6 value_extt Hl).\n    intros w' R' h'' _ Heq <-.\n    injection (objin_inj _ _ _ Heq); clear Heq.\n    intros Heq ->.\n    injectionT Heq.\n    intros ->.\n    so (proof_irrelevance _ h h''); subst h''.\n    assert (l <= j) as Hlj by omega.\n    so (relctx_trans_right _#7 (pwctx_impl_seqctx _#4 Htu) (relctx_downward _#7 Hlk Hst)) as Hstu.\n    clear C'.\n    set (C' := extend_iurel h' (iutruncate (S l) (iubase C))).\n    so (Hfunc _#3 Hlj Hstu) as (B & Hbtl & Hbur).\n    so (Hfunc _#3 Hlj (relctx_downward _#7 Hlk Hst)) as (B' & Hbtl' & Hbtr).\n    fold h' in Hbtl, Hbur, Hbtl', Hbtr.\n    fold C' in Hbtl, Hbur, Hbtl', Hbtr.\n    so (functional_fun _#8 Hbtl Hbtl'); subst B'.\n    clear Hbtl Hbtl'.\n    apply (relhyp_tm _#4 (iupi stop l C' B)).\n      {\n      apply (interp_increase pg); auto using toppg_max.\n      apply interp_eval_refl.\n      apply interp_pi; auto.\n      apply interp_eval_refl.\n      apply interp_extt.\n      apply le_ord_refl.\n      }\n\n      {\n      apply (interp_increase pg); auto using toppg_max.\n      apply interp_eval_refl.\n      apply interp_pi; auto.\n      }\n    }\n\n    (* symmetric *)\n    {\n    intros l u Hlk Htuu.\n    simpsub.\n    change (3 + 1) with 4.\n    simpsub.\n    so (pwctx_cons_invert_simple _#5 Htuu) as (x & y & u1 & u1' & Hu1 & Hxy & -> & Heq).\n    simpsub.\n    simpsubin Hu1.\n    injectionc Heq.\n    intros <- _.\n    clear x y Hxy Htuu.\n    so (pwctx_cons_invert_simple _#5 Hu1) as (x & y & u2 & u2' & Hu2 & Hxy & -> & Heq).\n    clear Hu1.\n    simpsub.\n    injectionc Heq.\n    intros <- _.\n    clear x y Hxy.\n    so (pwctx_cons_invert_simple _#5 Hu2) as (x & y & u & u' & Hut & Hxy & -> & Heq).\n    clear Hu2.\n    injectionc Heq.\n    intros <- <-.\n    simpsub.\n    simpsubin Hxy.\n    invertc Hxy.\n    intros Ru Huniv _ Hlr.\n    invert (basic_value_inv _#6 value_univ Huniv).\n    intros pg' Hlvu _ _ <-.\n    so (relctx_trans_left _#7 (pwctx_impl_seqctx _#4 Hut) (relctx_downward _#7 Hlk Hst)) as Hut'.\n    so (pginterp_fun _#3 Hlvu (relctx_pginterp _#8 Hseqlv Hut' Hlvl andel)); subst pg'.\n    cbn in Hlr.\n    destruct Hlr as (_ & R & Hl & Hr).\n    rewrite -> sint_unroll in Hl, Hr.\n    invert (basic_value_inv _#6 value_extt Hr).\n    intros w' R' h'' _ Heq <-.\n    injection (objin_inj _ _ _ Heq); clear Heq.\n    intros Heq ->.\n    injectionT Heq.\n    intros ->.\n    so (proof_irrelevance _ h h''); subst h''.\n    assert (l <= j) as Hlj by omega.\n    so (relctx_trans_left _#7 (pwctx_impl_seqctx _#4 Hut) (relctx_downward _#7 Hlk Hst)) as Hstu.\n    clear C'.\n    set (C' := extend_iurel h' (iutruncate (S l) (iubase C))).\n    so (Hfunc _#3 Hlj Hstu) as (B & Hbul & Hbtr).\n    so (Hfunc _#3 Hlj (relctx_downward _#7 Hlk Hst)) as (B' & Hbtl & Hbtr').\n    fold h' in Hbul, Hbtr, Hbtl, Hbtr'.\n    fold C' in Hbul, Hbtr, Hbtl, Hbtr'.\n    so (functional_fun _#8 Hbtr Hbtr'); subst B'.\n    clear Hbtr Hbtr'.\n    apply (relhyp_tm _#4 (iupi stop l C' B)).\n      {\n      apply (interp_increase pg); auto using toppg_max.\n      apply interp_eval_refl.\n      apply interp_pi; auto.\n      apply interp_eval_refl.\n      apply interp_extt.\n      apply le_ord_refl.\n      }\n\n      {\n      apply (interp_increase pg); auto using toppg_max.\n      apply interp_eval_refl.\n      apply interp_pi; auto.\n      }\n    }\n  }\nso (Hseqind j _ _ (Hss j s s' (le_refl _) (relctx_refl _#4 (pwctx_downward _#5 Hj Hs)))) as (pg' & R & Hlvl' & _ & Hl & Hr & Hinh).\nsimpsubin Hlvl'.\nso (pginterp_fun _#3 Hlvl Hlvl'); subst pg'; clear Hlvl'.\nsimpsubin Hl.\nsimpsubin Hr.\nsimpsubin Hinh.\nsplit.\n  {\n  unfold Mu.\n  rewrite -> mu_fix; auto.\n  so (HmonoF C Mu Hincl) as Hincl'.\n  cbn in Hincl'.\n  apply Hincl'; auto.\n  }\nexists R.\nintros k c d Hk Hcd.\ndestruct Hcd as (t & t' & Hst & -> & ->).\nsimpsub.\nassert (k <= i) as Hki by omega.\nfold w.\nso (Hseqind k _ _ (Hss k t t' Hk Hst)) as H.\nsimpsubin H.\ndestruct H as (pg' & R' & Hlvl' & _ & Hlt & Hrt & _).\nsimpsubin Hlvl'.\nso (pginterp_fun _#3 Hlvl' (relctx_pginterp _#8 Hseqlv Hst Hlvl andel)); subst pg'; clear Hlvl'.\nso (Hseqind k _ _ (Hss k s t' Hk (relctx_swap1 _#6 Hst))) as H.\nsimpsubin H.\ndestruct H as (pg' & R'' & Hlvl' & _ & Hl' & Hrt' & _).\nso (pginterp_fun _#3 Hlvl Hlvl'); subst pg'; clear Hlvl'.\nso (interp_fun _#7 Hl' (basic_downward _#7 Hk Hl)); subst R''.\nso (interp_fun _#7 Hrt Hrt'); subst R'.\ndo2 2 split; auto.\napply (urel_downward_leq _#3 j); auto.\nQed.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/SoundMu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477015, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2432211827171288}}
{"text": "(* Copyright © 1998-2006\n * Henk Barendregt\n * Luís Cruz-Filipe\n * Herman Geuvers\n * Mariusz Giero\n * Rik van Ginneken\n * Dimitri Hendriks\n * Sébastien Hinderer\n * Bart Kirkels\n * Pierre Letouzey\n * Iris Loeb\n * Lionel Mamane\n * Milad Niqui\n * Russell O’Connor\n * Randy Pollack\n * Nickolay V. Shmyrev\n * Bas Spitters\n * Dan Synek\n * Freek Wiedijk\n * Jan Zwanenburg\n *\n * This work is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This work is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this work; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *)\n(* begin hide *)\nRequire Export CoRN.reals.Q_in_CReals.\n\n\n(*----- Opaque_algebra.v will be loaded in line 151 -----*)\n\nLemma or_not_and :\n forall (A : CProp) (B : Prop), Not A \\/ ~ B -> Not (A and B).\nProof.\n intros.\n intro H0.\n elim H0.\n intros.\n case H.\n  intro H3.\n  apply H3.\n  assumption.\n intro H3.\n apply H3.\n assumption.\nQed.\n\nSection Interval_definition.\n Variable OF : COrdField.\n\n Record Interval : Type :=\n   {pair_crr :> prodT OF OF; is_interval : fstT pair_crr[<]sndT pair_crr}.\n\nDefinition Length (I1 : Interval) : OF := sndT I1[-]fstT I1.\n\nEnd Interval_definition.\n\nDefinition Rat_Interval := Interval Q_as_COrdField.\n\n(* we have this in Q_COrdField... *)\nLemma Qlt_eq_gt_dec' :\n forall q1 q2 : Q_as_COrdField, ((q1[<]q2) or (q2[<]q1)) or (q1[=]q2).\nProof.\n intros.\n case (Q_dec q1 q2); intuition.\nQed.\n\n(*\nLemma ex_informative_on_Q:(P:Q_as_COrdField->Prop)(Ex [q:Q_as_COrdField](P q))\n                             ->{q:Q_as_COrdField | (P q)}.\nProof.\n Intro.\n Intro.\n Apply ex_informative.\n Assumption.\nQed.\n*)\n\nSection COrdField_extra.\n\n\nVariable OF : COrdField.\n\n\n\n\nLemma AbsSmall_pos_reflexive : forall x : OF, ([0][<=]x) -> AbsSmall x x.\nProof.\n intros.\n split.\n  apply leEq_transitive with (y := [0]:OF).\n   apply inv_cancel_leEq.\n   rstepl ([0]:OF).\n   rstepr x.\n   assumption.\n  assumption.\n apply leEq_reflexive.\nQed.\n\nLemma AbsSmall_neg_reflexive : forall x : OF, ([0][<=]x) -> AbsSmall x [--]x.\nProof.\n intros.\n split.\n  apply leEq_reflexive.\n apply leEq_transitive with (y := [0]:OF).\n  apply inv_cancel_leEq.\n  rstepl ([0]:OF).\n  rstepr x.\n  assumption.\n assumption.\nQed.\n\n\nLemma AbsSmall_subinterval :\n forall a b x y : OF,\n (a[<=]x) -> (a[<=]y) -> (x[<=]b) -> (y[<=]b) -> AbsSmall (b[-]a) (x[-]y).\nProof.\n intros.\n split.\n  rstepl (a[+][--]b).\n  rstepr (x[+][--]y).\n  apply plus_resp_leEq_both.\n   assumption.\n  apply inv_resp_leEq.\n  assumption.\n rstepl (x[+][--]y).\n rstepr (b[+][--]a).\n apply plus_resp_leEq_both.\n  assumption.\n apply inv_resp_leEq.\n assumption.\nQed.\n\n\nEnd COrdField_extra.\n\n\nSection Rational_sequence.\nLoad \"Opaque_algebra\".  (* WARNING: A file is being loaded *)\nVariable R1 : CReals.\n\nDefinition start_l (x : R1) := let (N, _) := start_of_sequence _ x in N.\n\n\nLemma start_of_sequence2 :\n forall x : R1,\n {q2 : Q_as_COrdField | inj_Q R1 (start_l x)[<]x | x[<]inj_Q R1 q2}.\nProof.\n intro.\n apply (ProjT2 (start_of_sequence _ x)).\nQed.\n\nDefinition start_r (x : R1) := let (N, _, _) := start_of_sequence2 x in N.\n\nLemma start_of_sequence_property :\n forall x : R1, (inj_Q R1 (start_l x)[<]x) and (x[<]inj_Q R1 (start_r x)).\nProof.\n intro.\n unfold start_l, start_r in |- *.\n elim start_of_sequence2; auto.\nQed.\n\n\nLemma l_less_r : forall x : R1, start_l x[<]start_r x.\nProof.\n intro.\n apply less_inj_Q with (R1 := R1).\n elim (start_of_sequence_property x).\n apply less_transitive_unfolded.\nQed.\n\n\nLemma shrink23 :\n forall q1 q2 : Q_as_COrdField,\n (q1[<]q2) -> q1[+](q2[-]q1) [/]ThreeNZ[<]q2[-](q2[-]q1) [/]ThreeNZ.\nProof.\n intros.\n apply plus_cancel_less with (R := Q_as_COrdField) (z := (q2[-]q1) [/]ThreeNZ).\n rstepl (q2[-](q2[-]q1) [/]ThreeNZ).\n rstepr q2.\n apply plus_cancel_less with (R := Q_as_COrdField) (z := [--]q2).\n rstepr [--]([0]:Q_as_COrdField).\n rstepl [--]((q2[-]q1) [/]ThreeNZ).\n apply inv_resp_less.\n apply mult_cancel_less with (R := Q_as_COrdField) (z := Three:Q_as_COrdField).\n  apply pos_nring_S.\n rstepl ([0]:Q_as_COrdField).\n rstepr (q2[-]q1).\n apply shift_zero_less_minus.\n assumption.\nQed.\n\n\nLemma shrink13 :\n forall q1 q2 : Q_as_COrdField, (q1[<]q2) -> q1[<]q2[-](q2[-]q1) [/]ThreeNZ.\nProof.\n intros.\n apply less_transitive_unfolded with (q1[+](q2[-]q1) [/]ThreeNZ).\n  astepl (q1[+][0]).\n  apply plus_resp_less_lft.\n  apply div_resp_pos.\n   apply pos_three.\n  apply shift_zero_less_minus.\n  assumption.\n apply shrink23.\n assumption.\nQed.\n\nLemma shrink24 :\n forall q1 q2 : Q_as_COrdField, (q1[<]q2) -> q1[+](q2[-]q1) [/]ThreeNZ[<]q2.\nProof.\n intros.\n apply less_transitive_unfolded with (q2[-](q2[-]q1) [/]ThreeNZ).\n  apply shrink23.\n  assumption.\n astepl (q2[+][--]((q2[-]q1) [/]ThreeNZ)).\n astepr (q2[+][0]).\n apply plus_resp_less_lft.\n apply inv_cancel_less.\n rstepl ([0]:Q_as_COrdField).\n rstepr ((q2[-]q1) [/]ThreeNZ).\n apply div_resp_pos.\n  apply pos_three.\n apply shift_zero_less_minus.\n assumption.\nQed.\n\n\nDefinition cotrans_analyze :\n  forall (x : R1) (q1 q2 : Q_as_COrdField), (q1[<]q2) -> Q_as_COrdField.\nProof.\n intros.\n cut (inj_Q R1 q1[<]inj_Q R1 q2).\n  intro H0.\n  case (less_cotransitive_unfolded R1 (inj_Q R1 q1) (inj_Q R1 q2) H0 x).\n   intro.\n   exact q1.\n  intro.\n  exact q2.\n apply inj_Q_less.\n assumption.\nDefined.\n\n\n\nLemma cotrans_analyze_strong :\n forall (q1 q2 : Q_as_COrdField) (x : R1) (H : q1[<]q2),\n ((inj_Q R1 q1[<]x) and (cotrans_analyze x q1 q2 H[=]q1))\n or (x[<]inj_Q R1 q2) and (cotrans_analyze x q1 q2 H[=]q2).\nProof.\n intros.\n unfold cotrans_analyze in |- *.\n elim (less_cotransitive_unfolded R1 (inj_Q R1 q1) (inj_Q R1 q2) (inj_Q_less R1 q1 q2 H) x).\n  intros.\n  left.\n  split.\n   assumption.\n  algebra.\n intros.\n right.\n split.\n  assumption.\n algebra.\nQed.\n\n\nDefinition trichotomy :\n  R1 -> Q_as_COrdField -> Q_as_COrdField -> Q_as_COrdField.\nProof.\n intros x q1 q2.\n case (Qlt_eq_gt_dec' q1 q2).\n  intro s.\n  elim s.\n   intro a.\n   exact (cotrans_analyze x (q1[+](q2[-]q1) [/]ThreeNZ) (q2[-](q2[-]q1) [/]ThreeNZ) (shrink23 q1 q2 a)).\n  intro.\n  exact [0].\n intro.\n exact q1.\nDefined.\n\n\nLemma trichotomy_strong1 :\n forall (q1 q2 : Q_as_COrdField) (x : R1) (H : q1[<]q2),\n ((inj_Q R1 (q1[+](q2[-]q1) [/]ThreeNZ)[<]x)\n  and (trichotomy x q1 q2[=]q1[+](q2[-]q1) [/]ThreeNZ))\n or (x[<]inj_Q R1 (q2[-](q2[-]q1) [/]ThreeNZ))\n    and (trichotomy x q1 q2[=]q2[-](q2[-]q1) [/]ThreeNZ).\nProof.\n intros.\n unfold trichotomy in |- *.\n elim (Qlt_eq_gt_dec' q1 q2).\n  intro y.\n  elim y.\n   intro y0.\n   simpl in |- *.\n   apply cotrans_analyze_strong.\n  intro.\n  apply False_rect.\n  generalize b.\n  change (Not (q2[<]q1)) in |- *.\n  apply less_antisymmetric_unfolded.\n  assumption.\n intro.\n exfalso.\n generalize b.\n change (q1[~=]q2) in |- *.\n apply ap_imp_neq.\n apply less_imp_ap.\n assumption.\nQed.\n\nNotation \"( A , B )\" := (pairT A B).\nDefinition if_cotrans : forall (x : R1) (I1 : Rat_Interval), Rat_Interval.\nProof.\n intros.\n case I1.\n intros i pi.\n elim (trichotomy_strong1 (fstT i) (sndT i) x pi).\n  intro.\n  exact (Build_Interval _ (fstT i[+](sndT i[-]fstT i) [/]ThreeNZ, sndT i)\n    (shrink24 (fstT i) (sndT i) pi)).\n intro.\n exact (Build_Interval _ (fstT i, sndT i[-](sndT i[-]fstT i) [/]ThreeNZ)\n   (shrink13 (fstT i) (sndT i) pi)).\nDefined.\n\n\n\nLemma if_cotrans_strong :\n forall (x : R1) (I1 : Rat_Interval),\n ((inj_Q R1 (fstT I1[+](sndT I1[-]fstT I1) [/]ThreeNZ)[<]x)\n  and if_cotrans x I1 =\n      Build_Interval _ (fstT I1[+](sndT I1[-]fstT I1) [/]ThreeNZ, sndT I1)\n        (shrink24 (fstT I1) (sndT I1) (is_interval _ I1)))\n or (x[<]inj_Q R1 (sndT I1[-](sndT I1[-]fstT I1) [/]ThreeNZ))\n    and if_cotrans x I1 =\n        Build_Interval _ (fstT I1, sndT I1[-](sndT I1[-]fstT I1) [/]ThreeNZ)\n          (shrink13 (fstT I1) (sndT I1) (is_interval _ I1)).\nProof.\n intros.\n case I1.\n intros i pi.\n elim (trichotomy_strong1 (fstT i) (sndT i) x pi).\n  intro y.\n  elim y.\n  intros H H0.\n  left.\n  split.\n   exact H.\n  cut (if_cotrans x (Build_Interval Q_as_COrdField i pi) = Build_Interval Q_as_COrdField\n    (fstT i[+](sndT i[-]fstT i) [/]ThreeNZ, sndT i) (shrink24 (fstT i) (sndT i) pi)).\n   intro H1.\n   rewrite H1.\n   simpl in |- *.\n   reflexivity.\n  unfold if_cotrans in |- *.\n  apply not_r_cor_rect.\n  apply or_not_and.\n  right.\n  change (trichotomy x (fstT i) (sndT i)[~=]sndT i[-](sndT i[-]fstT i) [/]ThreeNZ) in |- *.\n  apply ap_imp_neq.\n  astepl (fstT i[+](sndT i[-]fstT i) [/]ThreeNZ).\n  apply less_imp_ap.\n  apply shrink23.\n  assumption.\n intro.\n elim b.\n intros H H0.\n right.\n split.\n  exact H.\n cut (if_cotrans x (Build_Interval Q_as_COrdField i pi) = Build_Interval Q_as_COrdField\n   (fstT i, sndT i[-](sndT i[-]fstT i) [/]ThreeNZ) (shrink13 (fstT i) (sndT i) pi)).\n  intro H1.\n  rewrite H1.\n  simpl in |- *.\n  reflexivity.\n unfold if_cotrans in |- *.\n apply not_l_cor_rect.\n apply or_not_and.\n right.\n change (trichotomy x (fstT i) (sndT i)[~=] (fstT i)[+]((sndT i[-]fstT i) [/]ThreeNZ)) in |- *.\n apply ap_imp_neq.\n astepl (sndT i[-](sndT i[-]fstT i) [/]ThreeNZ).\n apply Greater_imp_ap.\n apply shrink23.\n assumption.\nQed.\n\nFixpoint Intrvl (x : R1) (n : nat) {struct n} : Rat_Interval :=\n  match n with\n  | O => Build_Interval _ (start_l x, start_r x) (l_less_r x)\n  | S p => if_cotrans x (Intrvl x p)\n  end.\n\n\nDefinition G (x : R1) (n : nat) :=\n  (fstT (Intrvl x n)[+]sndT (Intrvl x n)) [/]TwoNZ.\n\nOpaque Q_as_CField.\n\nLemma delta_Intrvl :\n forall (x : R1) (n : nat),\n Length _ (Intrvl x (S n))[=]Two [/]ThreeNZ[*]Length _ (Intrvl x n).\nProof.\n intros.\n case (if_cotrans_strong x (Intrvl x n)).\n  intro H.\n  elim H.\n  intros H0 H1.\n  simpl in |- *.\n  rewrite H1.\n  unfold Length in |- *.\n  simpl in |- *.\n  rational.\n intro H.\n elim H.\n intros H0 H1.\n simpl in |- *.\n rewrite H1.\n unfold Length in |- *.\n simpl in |- *.\n rational.\nQed.\n\nLemma Length_Intrvl :\n forall (x : R1) (n : nat),\n Length _ (Intrvl x n)[=](Two [/]ThreeNZ)[^]n[*](start_r x[-]start_l x).\nProof.\n intros.\n induction  n as [| n Hrecn].\n  (* n=0 *)\n  unfold Length in |- *.\n  simpl in |- *.\n  rational.\n (* n=(S n0) & induction hypothesis *)\n astepr (Two [/]ThreeNZ[*]((Two [/]ThreeNZ)[^]n[*](start_r x[-]start_l x))).\n  astepr (Two [/]ThreeNZ[*]Length Q_as_COrdField (Intrvl x n)).\n  apply delta_Intrvl.\n astepr ((Two [/]ThreeNZ)[^]n[*]Two [/]ThreeNZ[*](start_r x[-]start_l x)).\n rational.\nQed.\n\n\nLemma Intrvl_inside_l_n :\n forall (x : R1) (m n : nat),\n m <= n -> fstT (Intrvl x m)[<=]fstT (Intrvl x n).\nProof.\n intros.\n induction  n as [| n Hrecn].\n  (* n=0 *)\n  cut (m = 0).\n   intro.\n   rewrite H0.\n   apply leEq_reflexive.\n  symmetry  in |- *.\n  apply le_n_O_eq.\n  assumption.\n (* n=(S n0) *)\n cut ({m = S n} + {m <= n}).\n  intro.\n  case H0.\n   intro H1.\n   rewrite H1.\n   apply leEq_reflexive.\n  intro.\n  apply leEq_transitive with (fstT (Intrvl x n)).\n   apply Hrecn.\n   assumption.\n  case (if_cotrans_strong x (Intrvl x n)).\n   intro H2.\n   elim H2.\n   intros H3 H4.\n   change (fstT (Intrvl x n)[<=]fstT (if_cotrans x (Intrvl x n))) in |- *.\n   rewrite H4.\n   astepl (fstT (Intrvl x n)[+][0]).\n   simpl.\n   apply (plus_resp_leEq_both Q_as_COrdField).\n    apply leEq_reflexive.\n   apply less_leEq.\n   apply (div_resp_pos Q_as_COrdField).\n    apply (pos_three Q_as_COrdField).\n   apply (shift_zero_less_minus Q_as_COrdField).\n   apply (is_interval Q_as_COrdField).\n  intro H2.\n  elim H2.\n  intros H3 H4.\n  change (fstT (Intrvl x n)[<=]fstT (if_cotrans x (Intrvl x n))) in |- *.\n  rewrite H4.\n  apply leEq_reflexive.\n case (le_lt_eq_dec m (S n) H).\n  intro.\n  right.\n  apply lt_n_Sm_le.\n  assumption.\n intro.\n left.\n assumption.\nQed.\n\nLemma Intrvl_inside_r_n :\n forall (x : R1) (m n : nat),\n m <= n -> sndT (Intrvl x n)[<=]sndT (Intrvl x m).\nProof.\n intros.\n induction  n as [| n Hrecn].\n  (* n=0 *)\n  cut (m = 0).\n   intro.\n   rewrite H0.\n   apply leEq_reflexive.\n  symmetry  in |- *.\n  apply le_n_O_eq.\n  assumption.\n (* n=(S n0) *)\n cut ({m = S n} + {m <= n}).\n  intro H0.\n  case H0.\n   intro H1.\n   rewrite H1.\n   apply leEq_reflexive.\n  intro.\n  apply leEq_transitive with (sndT (Intrvl x n)).\n   case (if_cotrans_strong x (Intrvl x n)).\n    intro H2.\n    elim H2.\n    intros H3 H4.\n    change (sndT (if_cotrans x (Intrvl x n))[<=]sndT (Intrvl x n)) in |- *.\n    rewrite H4.\n    apply leEq_reflexive.\n   intro H2.\n   elim H2.\n   intros H3 H4.\n   change (sndT (if_cotrans x (Intrvl x n))[<=]sndT (Intrvl x n)) in |- *.\n   rewrite H4.\n   astepr (sndT (Intrvl x n)[+][0]).\n   astepl (sndT (Intrvl x n)[+] [--]((sndT (Intrvl x n)[-]fstT (Intrvl x n)) [/]ThreeNZ)).\n   apply plus_resp_leEq_both.\n    apply leEq_reflexive.\n   apply inv_cancel_leEq.\n   astepl ([0]:Q_as_COrdField).\n   astepr ((sndT (Intrvl x n)[-]fstT (Intrvl x n)) [/]ThreeNZ).\n   apply less_leEq.\n   apply div_resp_pos.\n    apply pos_three.\n   apply shift_zero_less_minus.\n   apply is_interval.\n  apply Hrecn.\n  assumption.\n case (le_lt_eq_dec m (S n) H).\n  intro.\n  right.\n  apply lt_n_Sm_le.\n  assumption.\n intro.\n left.\n assumption.\nQed.\n\n\nLemma G_m_n_lower :\n forall (x : R1) (m n : nat), m <= n -> fstT (Intrvl x m)[<]G x n.\nProof.\n intros.\n unfold G in |- *.\n apply leEq_less_trans with (fstT (Intrvl x n)).\n  apply Intrvl_inside_l_n.\n  assumption.\n apply Smallest_less_Average.\n apply is_interval.\nQed.\n\nLemma G_m_n_upper :\n forall (x : R1) (m n : nat), m <= n -> G x n[<]sndT (Intrvl x m).\nProof.\n intros.\n unfold G in |- *.\n apply less_leEq_trans with (sndT (Intrvl x n)).\n  apply Average_less_Greatest.\n  apply is_interval.\n apply Intrvl_inside_r_n.\n assumption.\nQed.\n\nOpaque Q_as_COrdField.\n\nLemma a_simple_inequality :\n forall m : nat,\n 4 <= m ->\n (Two [/]ThreeNZ)[^]m[<]\n (([1]:Q_as_COrdField)[/] nring (S m)[//]nringS_ap_zero _ m).\nProof.\n intros.\n induction  m as [| m Hrecm].\n  apply False_rect.\n  generalize H.\n  change (~ 4 <= 0) in |- *.\n  apply le_Sn_O.\n case (le_lt_eq_dec 4 (S m) H).\n  intro.\n  apply less_transitive_unfolded with (Two [/]ThreeNZ[*]\n    (([1]:Q_as_COrdField)[/] nring (S m)[//]nringS_ap_zero _ m)).\n   astepl (((Two:Q_as_COrdField) [/]ThreeNZ)[^]m[*]Two [/]ThreeNZ).\n   astepl ((Two:Q_as_COrdField) [/]ThreeNZ[*](Two [/]ThreeNZ)[^]m).\n   apply mult_resp_less_lft.\n    apply Hrecm.\n    apply lt_n_Sm_le.\n    assumption.\n   apply div_resp_pos.\n    apply pos_three.\n   apply pos_two.\n  (* astepl ((Two::Q_as_COrdField)[/]ThreeNZ)[*](Two[/]ThreeNZ)[^]m.\n  Apply nexp_Sn with ((Two::Q_as_COrdField)[/]ThreeNZ). *)\n  apply mult_cancel_less with ((Three:Q_as_COrdField)[*]nring (S m)[*]nring (S (S m))).\n   apply mult_resp_pos.\n    apply mult_resp_pos.\n     apply pos_three.\n    apply pos_nring_S.\n   apply pos_nring_S.\n  rstepl ((Two:Q_as_COrdField)[*]nring (S (S m))).\n  rstepr ((Three:Q_as_COrdField)[*]nring (S m)).\n  astepl ((Two:Q_as_COrdField)[*](nring m[+]Two)).\n   astepr ((Three:Q_as_COrdField)[*](nring m[+][1])).\n   apply plus_cancel_less with ([--]((Two:Q_as_COrdField)[*]nring m[+]Three)).\n   rstepl ([1]:Q_as_COrdField).\n   rstepr (nring (R:=Q_as_COrdField) m).\n   astepl (nring (R:=Q_as_COrdField) 1).\n   apply nring_less.\n   apply lt_trans with (m := 3).\n    constructor.\n    constructor.\n   apply lt_S_n.\n   assumption.\n  simpl in |- *.\n  rational.\n intro.\n rewrite <- e.\n apply mult_cancel_less with (nring (R:=Q_as_COrdField) 5[*]Three[^]4).\n  apply mult_resp_pos.\n   apply pos_nring_S.\n  rstepr (Three[^]2[*]Three[^]2:Q_as_COrdField).\n  apply mult_resp_pos.\n   apply pos_square.\n   apply nringS_ap_zero.\n  apply pos_square.\n  apply nringS_ap_zero.\n rstepl (Two[^]4[*]nring (R:=Q_as_COrdField) 5).\n rstepr (Three[^]4:Q_as_COrdField).\n rstepl (nring (R:=Q_as_COrdField) 80).\n rstepr (nring (R:=Q_as_COrdField) 81).\n apply nring_less.\n constructor.\nQed.\n\nLemma G_conversion_rate2 :\n forall (x : R1) (m n : nat),\n 4 <= m ->\n m <= n ->\n AbsSmall (start_r x[-]start_l x[/] nring (S m)[//]nringS_ap_zero _ m)\n   (G x m[-]G x n).\nProof.\n intros.\n apply AbsSmall_leEq_trans with (Length _ (Intrvl x m)).\n  astepl ((Two [/]ThreeNZ)[^]m[*](start_r x[-]start_l x)).\n   rstepr (([1][/] nring (S m)[//]nringS_ap_zero _ m)[*](start_r x[-]start_l x)).\n   apply less_leEq.\n   apply mult_resp_less.\n    apply a_simple_inequality.\n    assumption.\n   apply shift_zero_less_minus.\n   apply l_less_r.\n  apply eq_symmetric_unfolded.\n  apply Length_Intrvl.\n unfold Length in |- *.\n apply AbsSmall_subinterval; apply less_leEq.\n    apply G_m_n_lower.\n    constructor.\n   apply G_m_n_lower.\n   assumption.\n  apply G_m_n_upper.\n  constructor.\n apply G_m_n_upper.\n assumption.\nQed.\n\nLemma CS_seq_G : forall x : R1, Cauchy_prop (fun m : nat => G x m).\nProof.\n intros.\n unfold Cauchy_prop in |- *.\n intros e H.\n cut {n : nat | (start_r x[-]start_l x[/] e[//]Greater_imp_ap _ e [0] H)[<]nring n}.\n  intro H0.\n  case H0.\n  intro N.\n  intro.\n  exists (S (N + 3)).\n  intros.\n  apply AbsSmall_minus.\n  apply AbsSmall_leEq_trans with (start_r x[-]start_l x[/] nring (S (S (N + 3)))[//]\n    nringS_ap_zero Q_as_COrdField (S (N + 3))).\n   apply less_leEq.\n   apply swap_div with (z_ := Greater_imp_ap _ e [0] H).\n     apply pos_nring_S.\n    assumption.\n   apply less_transitive_unfolded with (nring (R:=Q_as_COrdField) N).\n    assumption.\n   apply nring_less.\n   apply le_lt_n_Sm.\n   constructor.\n   apply le_plus_l.\n  apply G_conversion_rate2 with (m := S (N + 3)).\n   apply le_n_S.\n   apply le_plus_r.\n  assumption.\n apply Q_is_archemaedian.  (* Note the use of Q_is_archemaedian *)\nQed.\n\nDefinition G_as_CauchySeq (x : R1) :=\n  Build_CauchySeq Q_as_COrdField (fun m : nat => G x m) (CS_seq_G x).\n\n\n\nLemma CS_seq_inj_Q_G :\n forall x : R1, Cauchy_prop (fun m : nat => inj_Q R1 (G x m)).\nProof.\n intro.\n change (Cauchy_prop (fun m : nat => inj_Q R1 (CS_seq _ (G_as_CauchySeq x) m))) in |- *.\n apply inj_Q_Cauchy.\nQed.\n\nDefinition inj_Q_G_as_CauchySeq (x : R1) :=\n  Build_CauchySeq _ (fun m : nat => inj_Q R1 (G x m)) (CS_seq_inj_Q_G x).\n\n\nLemma x_in_Intrvl_l :\n forall (x : R1) (n : nat), inj_Q R1 (fstT (Intrvl x n))[<]x.\nProof.\n intros.\n induction  n as [| n Hrecn].\n  (* n=0 *)\n  simpl in |- *.\n  cut ((inj_Q R1 (start_l x)[<]x) and (x[<]inj_Q R1 (start_r x))).\n   intro H.\n   elim H.\n   intros.\n   assumption.\n  apply start_of_sequence_property.\n (* n= (S n0) *)\n case (if_cotrans_strong x (Intrvl x n)).\n  intro H.\n  elim H.\n  intros H0 H1.\n  change (inj_Q R1 (fstT (if_cotrans x (Intrvl x n)))[<]x) in |- *.\n  rewrite H1.\n  simpl in |- *.\n  assumption.\n intro H.\n elim H.\n intros H0 H1.\n change (inj_Q R1 (fstT (if_cotrans x (Intrvl x n)))[<]x) in |- *.\n rewrite H1.\n simpl in |- *.\n assumption.\nQed.\n\nLemma x_in_Intrvl_r :\n forall (x : R1) (n : nat), x[<]inj_Q R1 (sndT (Intrvl x n)).\nProof.\n intros.\n induction  n as [| n Hrecn].\n  (* n=0 *)\n  simpl in |- *.\n  cut ((inj_Q R1 (start_l x)[<]x) and (x[<]inj_Q R1 (start_r x))).\n   intro H.\n   elim H.\n   intros.\n   assumption.\n  apply start_of_sequence_property.\n (* n= (S n0) *)\n case (if_cotrans_strong x (Intrvl x n)).\n  intro H.\n  elim H.\n  intros H0 H1.\n  change (x[<]inj_Q R1 (sndT (if_cotrans x (Intrvl x n)))) in |- *.\n  rewrite H1.\n  simpl in |- *.\n  assumption.\n intro H.\n elim H.\n intros H0 H1.\n change (x[<]inj_Q R1 (sndT (if_cotrans x (Intrvl x n)))) in |- *.\n rewrite H1.\n simpl in |- *.\n assumption.\nQed.\n\n\n\nLemma G_conversion_rate_resp_x :\n forall (x : R1) (m : nat),\n 4 <= m ->\n AbsSmall\n   (inj_Q R1 (start_r x[-]start_l x[/] nring (S m)[//]nringS_ap_zero _ m))\n   (inj_Q R1 (G x m)[-]x).\nProof.\n intros.\n apply AbsSmall_leEq_trans with (e1 := inj_Q R1 (Length _ (Intrvl x m))).\n  apply less_leEq.\n  apply inj_Q_less.\n  astepl ((Two [/]ThreeNZ)[^]m[*](start_r x[-]start_l x)).\n   rstepr (([1][/] nring (S m)[//]nringS_ap_zero _ m)[*](start_r x[-]start_l x)).\n   apply mult_resp_less.\n    apply a_simple_inequality.\n    assumption.\n   apply shift_zero_less_minus.\n   apply l_less_r.\n  apply eq_symmetric_unfolded.\n  apply Length_Intrvl.\n unfold Length in |- *.\n astepl (inj_Q R1 (sndT (Intrvl x m))[-]inj_Q R1 (fstT (Intrvl x m))).\n apply AbsSmall_subinterval; apply less_leEq.\n    apply inj_Q_less.\n    apply G_m_n_lower.\n    constructor.\n   apply x_in_Intrvl_l.\n  apply inj_Q_less.\n  apply G_m_n_upper.\n  constructor.\n apply x_in_Intrvl_r.\nQed.\n\nLemma x_is_SeqLimit_G : forall x : R1, SeqLimit (inj_Q_G_as_CauchySeq x) x.\nProof.\n intros.\n unfold SeqLimit in |- *.\n intros e H.\n unfold inj_Q_G_as_CauchySeq in |- *.\n unfold CS_seq in |- *.\n cut {n : nat | (inj_Q R1 (start_r x[-]start_l x)[/] e[//]Greater_imp_ap _ e [0] H)[<] nring n}.\n  intro H0.\n  case H0.\n  intro N.\n  intro.\n  exists (S (N + 3)).\n  intros.\n  apply AbsSmall_leEq_trans with (e1 := inj_Q R1 ((start_r x[-]start_l x)[/]nring (S (S (N + 3)))[//]\n    nringS_ap_zero Q_as_COrdField (S (N + 3)))).\n   apply less_leEq.\n   apply less_transitive_unfolded with (y := inj_Q R1\n     ((start_r x[-]start_l x)[/]nring (R:=Q_as_COrdField) (S N)[//] nringS_ap_zero _ N)).\n    apply inj_Q_less.\n    apply mult_cancel_less with (nring (R:=Q_as_COrdField) (S (S (N + 3)))[*]nring (S N)).\n     apply mult_resp_pos.\n      apply pos_nring_S.\n     apply pos_nring_S.\n    rstepl ((start_r x[-]start_l x)[*]nring (S N)).\n    rstepr ((start_r x[-]start_l x)[*]nring (S (S (N + 3)))).\n    apply mult_resp_less_lft.\n     apply nring_less.\n     apply lt_n_S.\n     apply le_lt_n_Sm.\n     apply le_plus_l.\n    apply shift_zero_less_minus.\n    apply l_less_r.\n   astepl (inj_Q R1 (start_r x[-]start_l x)[/]nring (S N)[//]nringS_ap_zero R1 N).\n    apply swap_div with (z_ := Greater_imp_ap _ e [0] H).\n      apply pos_nring_S.\n     assumption.\n    apply less_transitive_unfolded with (y := nring (R:=R1) N).\n     assumption.\n    apply nring_less.\n    apply le_lt_n_Sm.\n    constructor.\n   apply mult_cancel_lft with (z := nring (R:=R1) (S N)).\n    apply nringS_ap_zero.\n   rstepl (inj_Q R1 (start_r x[-]start_l x)).\n   astepr (inj_Q R1 (nring (S N))[*] inj_Q R1 ((start_r x[-]start_l x)[/]nring (S N)[//]\n     nringS_ap_zero Q_as_COrdField N)).\n   astepr (inj_Q R1 (nring (S N)[*] ((start_r x[-]start_l x)[/]nring (S N)[//]\n     nringS_ap_zero Q_as_COrdField N))).\n   apply inj_Q_wd.\n   rational.\n  apply AbsSmall_leEq_trans with (e1 := inj_Q R1 ((start_r x[-]start_l x)[/]nring (S m)[//]\n    nringS_ap_zero Q_as_COrdField m)).\n   apply inj_Q_leEq.\n   apply mult_cancel_leEq with (nring (R:=Q_as_COrdField) (S (S (N + 3)))[*]nring (S m)).\n    apply mult_resp_pos.\n     apply pos_nring_S.\n    apply pos_nring_S.\n   rstepl ((start_r x[-]start_l x)[*]nring (S (S (N + 3)))).\n   rstepr ((start_r x[-]start_l x)[*]nring (S m)).\n   apply mult_resp_leEq_lft.\n    apply nring_leEq.\n    apply le_n_S.\n    assumption.\n   apply less_leEq.\n   apply shift_zero_less_minus.\n   apply l_less_r.\n  apply G_conversion_rate_resp_x.\n  apply le_trans with (m := S (N + 3)).\n   apply le_n_S.\n   apply le_plus_r.\n  assumption.\n apply Archimedes'.\nQed.\n\nEnd Rational_sequence.\n\n(* end hide *)\n", "meta": {"author": "coq-community", "repo": "corn", "sha": "cfbf6b297643935f0fe7e22d2b14b462bf7e3095", "save_path": "github-repos/coq/coq-community-corn", "path": "github-repos/coq/coq-community-corn/corn-cfbf6b297643935f0fe7e22d2b14b462bf7e3095/reals/Q_dense.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.44167300566462564, "lm_q1q2_score": 0.24318841007703082}}
{"text": "From iris.algebra Require Import gmap auth agree gset coPset.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.base_logic.lib Require Import wsat.\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.prelude Require Import options.\nImport uPred.\n\n(** This file contains the adequacy statements of the Iris program logic. First\nwe prove a number of auxilary results. *)\n\nSection adequacy.\nContext `{!irisGS_gen hlc Λ Σ}.\nImplicit Types e : expr Λ.\nImplicit Types P Q : iProp Σ.\nImplicit Types Φ : val Λ → iProp Σ.\nImplicit Types Φs : list (val Λ → iProp Σ).\n\nNotation wptp s t Φs := ([∗ list] e;Φ ∈ t;Φs, WP e @ s; ⊤ {{ Φ }})%I.\n\nLocal Lemma wp_step s e1 σ1 ns κ κs e2 σ2 efs nt Φ :\n  prim_step e1 σ1 κ e2 σ2 efs →\n  state_interp σ1 ns (κ ++ κs) nt -∗\n  £ (S (num_laters_per_step ns)) -∗\n  WP e1 @ s; ⊤ {{ Φ }}\n    ={⊤,∅}=∗ |={∅}▷=>^(S $ num_laters_per_step ns) |={∅,⊤}=>\n    state_interp σ2 (S ns) κs (nt + length efs) ∗ WP e2 @ s; ⊤ {{ Φ }} ∗\n    wptp s efs (replicate (length efs) fork_post).\nProof.\n  rewrite {1}wp_unfold /wp_pre. iIntros (?) \"Hσ Hcred H\".\n  rewrite (val_stuck e1 σ1 κ e2 σ2 efs) //.\n  iMod (\"H\" $! σ1 ns with \"Hσ\") as \"(_ & H)\". iModIntro.\n  iApply (step_fupdN_wand with \"(H [//] Hcred)\"). iIntros \">H\".\n  by rewrite Nat.add_comm big_sepL2_replicate_r.\nQed.\n\nLocal Lemma wptp_step s es1 es2 κ κs σ1 ns σ2 Φs nt :\n  step (es1,σ1) κ (es2, σ2) →\n  state_interp σ1 ns (κ ++ κs) nt -∗\n  £ (S (num_laters_per_step ns)) -∗\n  wptp s es1 Φs -∗\n  ∃ nt', |={⊤,∅}=> |={∅}▷=>^(S $ num_laters_per_step$ ns) |={∅,⊤}=>\n         state_interp σ2 (S ns) κs (nt + nt') ∗\n         wptp s es2 (Φs ++ replicate nt' fork_post).\nProof.\n  iIntros (Hstep) \"Hσ Hcred Ht\".\n  destruct Hstep as [e1' σ1' e2' σ2' efs t2' t3 Hstep]; simplify_eq/=.\n  iDestruct (big_sepL2_app_inv_l with \"Ht\") as (Φs1 Φs2 ->) \"[? Ht]\".\n  iDestruct (big_sepL2_cons_inv_l with \"Ht\") as (Φ Φs3 ->) \"[Ht ?]\".\n  iExists _. iMod (wp_step with \"Hσ Hcred Ht\") as \"H\"; first done. iModIntro.\n  iApply (step_fupdN_wand with \"H\"). iIntros \">($ & He2 & Hefs) !>\".\n  rewrite -(assoc_L app) -app_comm_cons. iFrame.\nQed.\n\n(* The total number of laters used between the physical steps number\n   [start] (included) to [start+ns] (excluded). *)\nLocal Fixpoint steps_sum (num_laters_per_step : nat → nat) (start ns : nat) : nat :=\n  match ns with\n  | O => 0\n  | S ns =>\n    S $ num_laters_per_step start + steps_sum num_laters_per_step (S start) ns\n  end.\n\nLocal Lemma wptp_preservation s n es1 es2 κs κs' σ1 ns σ2 Φs nt :\n  nsteps n (es1, σ1) κs (es2, σ2) →\n  state_interp σ1 ns (κs ++ κs') nt -∗\n  £ (steps_sum num_laters_per_step ns n) -∗\n  wptp s es1 Φs\n  ={⊤,∅}=∗ |={∅}▷=>^(steps_sum num_laters_per_step ns n) |={∅,⊤}=> ∃ nt',\n    state_interp σ2 (n + ns) κs' (nt + nt') ∗\n    wptp s es2 (Φs ++ replicate nt' fork_post).\nProof.\n  revert nt es1 es2 κs κs' σ1 ns σ2 Φs.\n  induction n as [|n IH]=> nt es1 es2 κs κs' σ1 ns σ2 Φs /=.\n  { inversion_clear 1; iIntros \"? ? ?\"; iExists 0=> /=.\n    rewrite Nat.add_0_r right_id_L. iFrame. by iApply fupd_mask_subseteq. }\n  iIntros (Hsteps) \"Hσ Hcred He\". inversion_clear Hsteps as [|?? [t1' σ1']].\n  rewrite -(assoc_L (++)) Nat.iter_add -{1}plus_Sn_m plus_n_Sm.\n  rewrite lc_split. iDestruct \"Hcred\" as \"[Hc1 Hc2]\".\n  iDestruct (wptp_step with \"Hσ Hc1 He\") as (nt') \">H\"; first eauto; simplify_eq.\n  iModIntro. iApply step_fupdN_S_fupd. iApply (step_fupdN_wand with \"H\").\n  iIntros \">(Hσ & He)\". iMod (IH with \"Hσ Hc2 He\") as \"IH\"; first done. iModIntro.\n  iApply (step_fupdN_wand with \"IH\"). iIntros \">IH\".\n  iDestruct \"IH\" as (nt'') \"[??]\".\n  rewrite -Nat.add_assoc -(assoc_L app) -replicate_add. by eauto with iFrame.\nQed.\n\nLocal Lemma wp_not_stuck κs nt e σ ns Φ :\n  state_interp σ ns κs nt -∗ WP e {{ Φ }} ={⊤, ∅}=∗ ⌜not_stuck e σ⌝.\nProof.\n  rewrite wp_unfold /wp_pre /not_stuck. iIntros \"Hσ H\".\n  destruct (to_val e) as [v|] eqn:?.\n  { iMod (fupd_mask_subseteq ∅); first set_solver. iModIntro. eauto. }\n  iSpecialize (\"H\" $! σ ns [] κs with \"Hσ\"). rewrite sep_elim_l.\n  iMod \"H\" as \"%\". iModIntro. eauto.\nQed.\n\n(** The adequacy statement of Iris consists of two parts:\n      (1) the postcondition for all threads that have terminated in values\n      and (2) progress (i.e., after n steps the program is not stuck).\n    For an n-step execution of a thread pool, the two parts are given by\n    [wptp_strong_adequacy] and [wptp_progress] below.\n\n    For the final adequacy theorem of Iris, [wp_strong_adequacy_gen], we would\n    like to instantiate the Iris proof (i.e., instantiate the\n    [∀ {Hinv : !invGS_gen hlc Σ} κs, ...]) and then use both lemmas to get\n    progress and the postconditions. Unfortunately, since the addition of later\n    credits, this is no longer possible, because the original proof relied on an\n    interaction of the update modality and plain propositions. So instead, we\n    employ a trick: we duplicate the instantiation of the Iris proof, such\n    that we can \"run the WP proof twice\". That is, we instantiate the\n    [∀ {Hinv : !invGS_gen hlc Σ} κs, ...] both in [wp_progress_gen] and\n    [wp_strong_adequacy_gen]. In doing  so, we can avoid the interactions with\n    the plain modality. In [wp_strong_adequacy_gen], we can then make use of\n    [wp_progress_gen] to prove the progress component of the main adequacy theorem.\n*)\n\nLocal Lemma wptp_postconditions Φs κs' s n es1 es2 κs σ1 ns σ2 nt:\n  nsteps n (es1, σ1) κs (es2, σ2) →\n  state_interp σ1 ns (κs ++ κs') nt -∗\n  £ (steps_sum num_laters_per_step ns n) -∗\n  wptp s es1 Φs\n  ={⊤,∅}=∗ |={∅}▷=>^(steps_sum num_laters_per_step ns n) |={∅,⊤}=> ∃ nt',\n    state_interp σ2 (n + ns) κs' (nt + nt') ∗\n    [∗ list] e;Φ ∈ es2;Φs ++ replicate nt' fork_post, from_option Φ True (to_val e).\nProof.\n  iIntros (Hstep) \"Hσ Hcred He\". iMod (wptp_preservation with \"Hσ Hcred He\") as \"Hwp\"; first done.\n  iModIntro. iApply (step_fupdN_wand with \"Hwp\").\n  iMod 1 as (nt') \"(Hσ & Ht)\"; simplify_eq/=.\n  iExists _. iFrame \"Hσ\".\n  iApply big_sepL2_fupd.\n  iApply (big_sepL2_impl with \"Ht\").\n  iIntros \"!#\" (? e Φ ??) \"Hwp\".\n  destruct (to_val e) as [v2|] eqn:He2'; last done.\n  apply of_to_val in He2' as <-. simpl. iApply wp_value_fupd'. done.\nQed.\n\n\nLocal Lemma wptp_progress Φs κs' n es1 es2 κs σ1 ns σ2 nt e2 :\n  nsteps n (es1, σ1) κs (es2, σ2) →\n  e2 ∈ es2 →\n  state_interp σ1 ns (κs ++ κs') nt -∗\n  £ (steps_sum num_laters_per_step ns n) -∗\n  wptp NotStuck es1 Φs\n  ={⊤,∅}=∗ |={∅}▷=>^(steps_sum num_laters_per_step ns n) |={∅}=> ⌜not_stuck e2 σ2⌝.\nProof.\n  iIntros (Hstep Hel) \"Hσ Hcred He\". iMod (wptp_preservation with \"Hσ Hcred He\") as \"Hwp\"; first done.\n  iModIntro. iApply (step_fupdN_wand with \"Hwp\").\n  iMod 1 as (nt') \"(Hσ & Ht)\"; simplify_eq/=.\n  eapply elem_of_list_lookup in Hel as [i Hlook].\n  destruct ((Φs ++ replicate nt' fork_post) !! i) as [Φ|] eqn: Hlook2; last first.\n  { rewrite big_sepL2_alt. iDestruct \"Ht\" as \"[%Hlen _]\". exfalso.\n    eapply lookup_lt_Some in Hlook. rewrite Hlen in Hlook.\n    eapply lookup_lt_is_Some_2 in Hlook. rewrite Hlook2 in Hlook.\n    destruct Hlook as [? ?]. naive_solver. }\n  iDestruct (big_sepL2_lookup with \"Ht\") as \"Ht\"; [done..|].\n  by iApply (wp_not_stuck with \"Hσ\").\nQed.\nEnd adequacy.\n\nLocal Lemma wp_progress_gen (hlc : has_lc) Σ Λ `{!invGpreS Σ} es σ1 n κs t2 σ2 e2\n        (num_laters_per_step : nat → nat)  :\n    (∀ `{Hinv : !invGS_gen hlc Σ},\n    ⊢ |={⊤}=> ∃\n         (stateI : state Λ → nat → list (observation Λ) → nat → iProp Σ)\n         (Φs : list (val Λ → iProp Σ))\n         (fork_post : val Λ → iProp Σ)\n         state_interp_mono,\n       let _ : irisGS_gen hlc Λ Σ := IrisG Hinv stateI fork_post num_laters_per_step\n                                  state_interp_mono\n       in\n       stateI σ1 0 κs 0 ∗\n       ([∗ list] e;Φ ∈ es;Φs, WP e @ ⊤ {{ Φ }})) →\n  nsteps n (es, σ1) κs (t2, σ2) →\n  e2 ∈ t2 →\n  not_stuck e2 σ2.\nProof.\n  iIntros (Hwp ??).\n  eapply pure_soundness.\n  eapply (step_fupdN_soundness_gen _ hlc (steps_sum num_laters_per_step 0 n)\n    (steps_sum num_laters_per_step 0 n)).\n  iIntros (Hinv) \"Hcred\".\n  iMod Hwp as (stateI Φ fork_post state_interp_mono) \"(Hσ & Hwp)\".\n  iDestruct (big_sepL2_length with \"Hwp\") as %Hlen1.\n  iMod (@wptp_progress _ _ _\n       (IrisG Hinv stateI fork_post num_laters_per_step state_interp_mono) _ []\n    with \"[Hσ] Hcred  Hwp\") as \"H\"; [done| done |by rewrite right_id_L|].\n  iAssert (|={∅}▷=>^(steps_sum num_laters_per_step 0 n) |={∅}=> ⌜not_stuck e2 σ2⌝)%I\n    with \"[-]\" as \"H\"; last first.\n  { destruct steps_sum; [done|]. by iApply step_fupdN_S_fupd. }\n  iApply (step_fupdN_wand with \"H\"). iIntros \"$\".\nQed.\n\n(** Iris's generic adequacy result *)\n(** The lemma is parameterized by [use_credits] over whether to make later credits available or not.\n  Below, a concrete instances is provided with later credits (see [wp_strong_adequacy]). *)\nLemma wp_strong_adequacy_gen (hlc : has_lc) Σ Λ `{!invGpreS Σ} s es σ1 n κs t2 σ2 φ\n        (num_laters_per_step : nat → nat) :\n  (* WP *)\n  (∀ `{Hinv : !invGS_gen hlc Σ},\n      ⊢ |={⊤}=> ∃\n         (stateI : state Λ → nat → list (observation Λ) → nat → iProp Σ)\n         (Φs : list (val Λ → iProp Σ))\n         (fork_post : val Λ → iProp Σ)\n         (* Note: existentially quantifying over Iris goal! [iExists _] should\n         usually work. *)\n         state_interp_mono,\n       let _ : irisGS_gen hlc Λ Σ := IrisG Hinv stateI fork_post num_laters_per_step\n                                  state_interp_mono\n       in\n       stateI σ1 0 κs 0 ∗\n       ([∗ list] e;Φ ∈ es;Φs, WP e @ s; ⊤ {{ Φ }}) ∗\n       (∀ es' t2',\n         (* es' is the final state of the initial threads, t2' the rest *)\n         ⌜ t2 = es' ++ t2' ⌝ -∗\n         (* es' corresponds to the initial threads *)\n         ⌜ length es' = length es ⌝ -∗\n         (* If this is a stuck-free triple (i.e. [s = NotStuck]), then all\n         threads in [t2] are not stuck *)\n         ⌜ ∀ e2, s = NotStuck → e2 ∈ t2 → not_stuck e2 σ2 ⌝ -∗\n         (* The state interpretation holds for [σ2] *)\n         stateI σ2 n [] (length t2') -∗\n         (* If the initial threads are done, their post-condition [Φ] holds *)\n         ([∗ list] e;Φ ∈ es';Φs, from_option Φ True (to_val e)) -∗\n         (* For all forked-off threads that are done, their postcondition\n            [fork_post] holds. *)\n         ([∗ list] v ∈ omap to_val t2', fork_post v) -∗\n         (* Under all these assumptions, and while opening all invariants, we\n         can conclude [φ] in the logic. After opening all required invariants,\n         one can use [fupd_mask_subseteq] to introduce the fancy update. *)\n         |={⊤,∅}=> ⌜ φ ⌝)) →\n  nsteps n (es, σ1) κs (t2, σ2) →\n  (* Then we can conclude [φ] at the meta-level. *)\n  φ.\nProof.\n  iIntros (Hwp ?).\n  eapply pure_soundness.\n  eapply (step_fupdN_soundness_gen _ hlc (steps_sum num_laters_per_step 0 n)\n    (steps_sum num_laters_per_step 0 n)).\n  iIntros (Hinv) \"Hcred\".\n  iMod Hwp as (stateI Φ fork_post state_interp_mono) \"(Hσ & Hwp & Hφ)\".\n  iDestruct (big_sepL2_length with \"Hwp\") as %Hlen1.\n  iMod (@wptp_postconditions _ _ _\n       (IrisG Hinv stateI fork_post num_laters_per_step state_interp_mono) _ []\n    with \"[Hσ] Hcred Hwp\") as \"H\"; [done|by rewrite right_id_L|].\n  iAssert (|={∅}▷=>^(steps_sum num_laters_per_step 0 n) |={∅}=> ⌜φ⌝)%I\n    with \"[-]\" as \"H\"; last first.\n  { destruct steps_sum; [done|]. by iApply step_fupdN_S_fupd. }\n  iApply (step_fupdN_wand with \"H\").\n  iMod 1 as (nt') \"(Hσ & Hval) /=\".\n  iDestruct (big_sepL2_app_inv_r with \"Hval\") as (es' t2' ->) \"[Hes' Ht2']\".\n  iDestruct (big_sepL2_length with \"Ht2'\") as %Hlen2.\n  rewrite replicate_length in Hlen2; subst.\n  iDestruct (big_sepL2_length with \"Hes'\") as %Hlen3.\n  rewrite -plus_n_O.\n  iApply (\"Hφ\" with \"[//] [%] [ ] Hσ Hes'\");\n    (* FIXME: Different implicit types for [length] are inferred, so [lia] and\n    [congruence] do not work due to https://github.com/coq/coq/issues/16634 *)\n    [by rewrite Hlen1 Hlen3| |]; last first.\n  { by rewrite big_sepL2_replicate_r // big_sepL_omap. }\n  (* At this point in the adequacy proof, we use a trick: we effectively run the\n    user-provided WP proof again (i.e., instantiate the `invGS_gen` and execute the\n    program) by using the lemma [wp_progress_gen]. In doing so, we can obtain\n    the progress part of the adequacy theorem.\n  *)\n  iPureIntro. intros e2 -> Hel.\n  eapply (wp_progress_gen hlc);\n    [ done | clear stateI Φ fork_post state_interp_mono Hlen1 Hlen3 | done|done].\n  iIntros (?).\n  iMod Hwp as (stateI Φ fork_post state_interp_mono) \"(Hσ & Hwp & Hφ)\".\n  iModIntro. iExists _, _, _, _. iFrame.\nQed.\n\n(** Adequacy when using later credits (the default) *)\nDefinition wp_strong_adequacy := wp_strong_adequacy_gen HasLc.\nGlobal Arguments wp_strong_adequacy _ _ {_}.\n\n(** Since the full adequacy statement is quite a mouthful, we prove some more\nintuitive and simpler corollaries. These lemmas are morover stated in terms of\n[rtc erased_step] so one does not have to provide the trace. *)\nRecord adequate {Λ} (s : stuckness) (e1 : expr Λ) (σ1 : state Λ)\n    (φ : val Λ → state Λ → Prop) := {\n  adequate_result t2 σ2 v2 :\n   rtc erased_step ([e1], σ1) (of_val v2 :: t2, σ2) → φ v2 σ2;\n  adequate_not_stuck t2 σ2 e2 :\n   s = NotStuck →\n   rtc erased_step ([e1], σ1) (t2, σ2) →\n   e2 ∈ t2 → not_stuck e2 σ2\n}.\n\nLemma adequate_alt {Λ} s e1 σ1 (φ : val Λ → state Λ → Prop) :\n  adequate s e1 σ1 φ ↔ ∀ t2 σ2,\n    rtc erased_step ([e1], σ1) (t2, σ2) →\n      (∀ v2 t2', t2 = of_val v2 :: t2' → φ v2 σ2) ∧\n      (∀ e2, s = NotStuck → e2 ∈ t2 → not_stuck e2 σ2).\nProof.\n  split.\n  - intros []; naive_solver.\n  - constructor; naive_solver.\nQed.\n\nTheorem adequate_tp_safe {Λ} (e1 : expr Λ) t2 σ1 σ2 φ :\n  adequate NotStuck e1 σ1 φ →\n  rtc erased_step ([e1], σ1) (t2, σ2) →\n  Forall (λ e, is_Some (to_val e)) t2 ∨ ∃ t3 σ3, erased_step (t2, σ2) (t3, σ3).\nProof.\n  intros Had ?.\n  destruct (decide (Forall (λ e, is_Some (to_val e)) t2)) as [|Ht2]; [by left|].\n  apply (not_Forall_Exists _), Exists_exists in Ht2; destruct Ht2 as (e2&?&He2).\n  destruct (adequate_not_stuck NotStuck e1 σ1 φ Had t2 σ2 e2) as [?|(κ&e3&σ3&efs&?)];\n    rewrite ?eq_None_not_Some; auto.\n  { exfalso. eauto. }\n  destruct (elem_of_list_split t2 e2) as (t2'&t2''&->); auto.\n  right; exists (t2' ++ e3 :: t2'' ++ efs), σ3, κ; econstructor; eauto.\nQed.\n\n(** This simpler form of adequacy requires the [irisGS] instance that you use\neverywhere to syntactically be of the form\n{|\n  iris_invGS := ...;\n  state_interp σ _ κs _ := ...;\n  fork_post v := ...;\n  num_laters_per_step _ := 0;\n  state_interp_mono _ _ _ _ := fupd_intro _ _;\n|}\nIn other words, the state interpretation must ignore [ns] and [nt], the number\nof laters per step must be 0, and the proof of [state_interp_mono] must have\nthis specific proof term.\n*)\n(** Again, we first prove a lemma generic over the usage of credits. *)\nLemma wp_adequacy_gen (hlc : has_lc) Σ Λ `{!invGpreS Σ} s e σ φ :\n  (∀ `{Hinv : !invGS_gen hlc Σ} κs,\n     ⊢ |={⊤}=> ∃\n         (stateI : state Λ → list (observation Λ) → iProp Σ)\n         (fork_post : val Λ → iProp Σ),\n       let _ : irisGS_gen hlc Λ Σ :=\n           IrisG Hinv (λ σ _ κs _, stateI σ κs) fork_post (λ _, 0)\n                 (λ _ _ _ _, fupd_intro _ _)\n       in\n       stateI σ κs ∗ WP e @ s; ⊤ {{ v, ⌜φ v⌝ }}) →\n  adequate s e σ (λ v _, φ v).\nProof.\n  intros Hwp. apply adequate_alt; intros t2 σ2 [n [κs ?]]%erased_steps_nsteps.\n  eapply (wp_strong_adequacy_gen hlc Σ _); [ | done]=> ?.\n  iMod Hwp as (stateI fork_post) \"[Hσ Hwp]\".\n  iExists (λ σ _ κs _, stateI σ κs), [(λ v, ⌜φ v⌝%I)], fork_post, _ => /=.\n  iIntros \"{$Hσ $Hwp} !>\" (e2 t2' -> ? ?) \"_ H _\".\n  iApply fupd_mask_intro_discard; [done|]. iSplit; [|done].\n  iDestruct (big_sepL2_cons_inv_r with \"H\") as (e' ? ->) \"[Hwp H]\".\n  iDestruct (big_sepL2_nil_inv_r with \"H\") as %->.\n  iIntros (v2 t2'' [= -> <-]). by rewrite to_of_val.\nQed.\n\n(** Instance for using credits *)\nDefinition wp_adequacy := wp_adequacy_gen HasLc.\nGlobal Arguments wp_adequacy _ _ {_}.\n\nLemma wp_invariance_gen (hlc : has_lc) Σ Λ `{!invGpreS Σ} s e1 σ1 t2 σ2 φ :\n  (∀ `{Hinv : !invGS_gen hlc Σ} κs,\n     ⊢ |={⊤}=> ∃\n         (stateI : state Λ → list (observation Λ) → nat → iProp Σ)\n         (fork_post : val Λ → iProp Σ),\n       let _ : irisGS_gen hlc Λ Σ := IrisG Hinv (λ σ _, stateI σ) fork_post\n              (λ _, 0) (λ _ _ _ _, fupd_intro _ _) in\n       stateI σ1 κs 0 ∗ WP e1 @ s; ⊤ {{ _, True }} ∗\n       (stateI σ2 [] (pred (length t2)) -∗ ∃ E, |={⊤,E}=> ⌜φ⌝)) →\n  rtc erased_step ([e1], σ1) (t2, σ2) →\n  φ.\nProof.\n  intros Hwp [n [κs ?]]%erased_steps_nsteps.\n  eapply (wp_strong_adequacy_gen hlc Σ); [done| |done]=> ?.\n  iMod (Hwp _ κs) as (stateI fork_post) \"(Hσ & Hwp & Hφ)\".\n  iExists (λ σ _, stateI σ), [(λ _, True)%I], fork_post, _ => /=.\n  iIntros \"{$Hσ $Hwp} !>\" (e2 t2' -> _ _) \"Hσ H _ /=\".\n  iDestruct (big_sepL2_cons_inv_r with \"H\") as (? ? ->) \"[_ H]\".\n  iDestruct (big_sepL2_nil_inv_r with \"H\") as %->.\n  iDestruct (\"Hφ\" with \"Hσ\") as (E) \">Hφ\".\n  by iApply fupd_mask_intro_discard; first set_solver.\nQed.\n\nDefinition wp_invariance := wp_invariance_gen HasLc.\nGlobal Arguments wp_invariance _ _ {_}.\n", "meta": {"author": "amintimany", "repo": "iris", "sha": "03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1", "save_path": "github-repos/coq/amintimany-iris", "path": "github-repos/coq/amintimany-iris/iris-03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1/iris/program_logic/adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2431884100770308}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\n(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(*                       trivial.v                                          *)\n(*                                                                          *)\n(* Author: Pierre Casteran.                                                 *)\n(*    LABRI, URA CNRS 1304,                                                 *)\n(*    Departement d'Informatique, Universite Bordeaux I,                    *)\n(*    33405 Talence CEDEX,                                                  *)\n(*    e-mail:  casteran@labri.u-bordeaux.fr                                 *)\n\n(* the trivial monoid *)\nRequire Import monoid.\nRequire Import Plus.\n\nLemma trivial : monoid nat.\nrefine (mkmonoid nat 0 plus _ _ _); auto with arith.\n(*\n Realizer (mkmonoid nat O plus).\n Program_all.\n*)\nDefined.\n\nLemma obsolete_debug : forall n : nat, power nat trivial n 1 = n.\n simpl in |- *; auto with arith.\nQed.\n\n", "meta": {"author": "coq-contribs", "repo": "additions", "sha": "0a2ba96483fcb424fa6ce7ebff1469956a0fa3a1", "save_path": "github-repos/coq/coq-contribs-additions", "path": "github-repos/coq/coq-contribs-additions/additions-0a2ba96483fcb424fa6ce7ebff1469956a0fa3a1/trivial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24310176528661562}}
{"text": "Require Export heap.     \nRequire Export Omega. \nRequire Export hetList. \nRequire Export Coq.Program.Equality. \n\n(*evaluation context decomposition*)\nInductive decompose : term -> ctxt -> term -> Prop :=\n|decompApp : forall e1 e2 E e, decompose e1 E e ->\n                               decompose (app e1 e2) (appCtxt e2 E) e\n|decompAppVal : forall v e2 E e (prf:value v), \n                  decompose e2 E e -> decompose (app v e2) (appValCtxt v prf E) e\n|appHole : forall e v, value v -> decompose (app (lambda e) v) hole (app (lambda e) v)\n|decompGet : forall e E e', decompose e E e' -> \n                            decompose (get e) (getCtxt E) e'\n|decompGetHole : forall l, decompose (get (loc l)) hole (get (loc l))\n|decompPut : forall e1 e2 E e, decompose e1 E e -> \n                               decompose (put e1 e2) (putCtxt e2 E) e\n|decompPutVal : forall v e2 E e (prf:value v), \n                  decompose e2 E e -> \n                  decompose (put v e2) (putValCtxt v prf E) e\n|decompPutHole : forall n v, value v -> decompose (put (loc n) v) hole (put (loc n) v)\n|decompAlloc : forall e E e', decompose e E e' ->\n                              decompose (alloc e) (allocCtxt E) e'\n|decompAllocHole : forall v, value v -> decompose (alloc v) hole (alloc v)\n|decompAtomicHole : forall e, decompose (atomic e) hole (atomic e)\n|decompFork : forall e, decompose (fork e) hole (fork e)\n|decompInAtomic : forall e e' E, decompose e E e' ->\n                            decompose (inatomic e) (inatomicCtxt E) e'\n|decompInAtomicHole : forall v, value v -> decompose (inatomic v) hole (inatomic v). \n\n(*values cannot be decomposed*)\nTheorem decomposeValFalse : forall t E e, value t -> decompose t E e -> False. \nProof.\n  intros t E e v d. inv d; try solve[inv v]. \nQed. \n\n(*proves that values cannot be decomposed*)\nLtac decompVal :=\n  match goal with\n      |H:value ?t, H':decompose ?t ?E ?e |- _ => \n       apply decomposeValFalse in H'; auto; inv H'\n      |H:decompose (lambda ?e) ?E ?e' |- _ => inv H\n      |H:decompose (loc ?l) ?E ?e |- _ => inv H\n  end. \n\n(*inverts a decomposition nested inside another*)\nLtac invertDecomp := \n  match goal with\n      |H:decompose (app ?e1 ?e2) ?E ?e |- _ => inv H\n      |H:decompose (get ?e) ?E ?e' |- _ => inv H\n      |H:decompose (put ?e1 ?e2) ?E ?e |- _ => inv H\n      |H:decompose (alloc ?e) ?E ?e' |- _ => inv H\n      |H:decompose (fork ?e) ?E ?e' |- _ => inv H\n      |H:decompose (inatomic ?e) ?E ?E' |- _ => inv H\n  end. \n\n(*evaluation context decomposition is deterministic*)\nTheorem decomposeDeterministic : forall t E E' e e', \n                                   decompose t E e -> decompose t E' e' ->\n                                   E = E' /\\ e = e'. \nProof.\n  intros t E E' e e' HD1 HD2. genDeps {{ E'; e'}}. \n  induction HD1; intros; try(invertDecomp; try decompVal); try solve[auto |\n  match goal with\n    |H:forall e'0 E', decompose ?e E' e'0 -> ?E = E' /\\ ?e' = e'0, \n     H':decompose ?e ?E'' ?e'' |- _ =>  apply H in H'; invertHyp; eauto; try (proofsEq; eauto)\n  end]. \n  inv HD2. eauto. \nQed. \n \n(*proves that the results of the same decomposition are the same*)\nLtac decompSame :=\n  match goal with\n      |H:decompose ?t ?E ?e,H':decompose ?t ?E' ?e' |- _ =>\n       eapply decomposeDeterministic in H; eauto; invertHyp\n  end.  \n\n(*fill an evaluation context*)\nFixpoint fill (E:ctxt) (e:term) := \n  match E with\n      |appCtxt e' E => app (fill E e) e'\n      |appValCtxt v _ E => app v (fill E e)\n      |getCtxt E => get (fill E e)\n      |putCtxt e' E => put (fill E e) e'\n      |putValCtxt v _ E => put v (fill E e)\n      |allocCtxt E => alloc (fill E e)\n      |inatomicCtxt E => inatomic (fill E e)\n      |hole => e \n  end.\n\n(*\ncommit H ==> indicates the log is valid and H contains the new writes from the log\nabort e L ==> log was invalid, resume execution at term e with log L\n*)\nInductive validateRes : Type := \n|commit : heap -> validateRes\n|abort : term -> log -> validateRes. \n\n(*Transactional log validation*)\nInductive validate : stamp -> log -> heap -> stamp -> validateRes -> Prop :=\n|validateNil : forall S S' H, validate S nil H S' (commit H)\n|validateCommitRead : forall S S' S'' l v E H H' L,\n                        lookup H l = Some(v, S') -> S > S' -> \n                        validate S L H S'' (commit H') ->\n                        validate S (readItem l E v::L) H S'' (commit H')\n|validateAbortPropogate : forall S S' L H x L' e, \n                            validate S L H S' (abort e L') ->\n                            validate S (x::L) H S' (abort e L')\n|validateAbortRead : forall S S' S'' H L E H' l v v',\n              validate S L H S'' (commit H') -> lookup H l = Some(v, S') ->\n              S' > S -> validate S (readItem l E v'::L) H S'' \n                                (abort (fill E(get(loc l))) L)\n|validateWrite : forall S S' L H H' l v,\n                   validate S L H S' (commit H') ->\n                   validate S (writeItem l v::L) H S' (commit ((l, v, S')::H'))\n.\n\n(*lookup a term in a thread's write set*)\nFixpoint logLookup (L:log) (l:location) :=\n  match L with\n      |readItem _ _ _::L' => logLookup L' l\n      |writeItem l' v::L' => if eq_nat_dec l l'\n                            then Some v\n                            else logLookup L' l\n      |nil => None\n  end. \n\nFixpoint open (e:term) (k:nat) (e':term) :=\n  match e with\n      |lambda e => lambda (open e (S k) e')\n      |loc l => loc l\n      |unit => unit\n      |var k' => if eq_nat_dec k k'\n                then e'\n                else var k'\n      |app e1 e2 => app (open e1 k e') (open e2 k e')\n      |get e => get (open e k e')\n      |put e1 e2 => put (open e1 k e') (open e2 k e')\n      |alloc e => alloc (open e k e')\n      |fork e => fork (open e k e')\n      |atomic e => atomic (open e k e')\n      |inatomic e => inatomic (open e k e')\n  end. \n\n(*transactional step (used by both p_step and f_step)*) \nInductive trans_step (H:heap) : thread -> thread -> Prop :=\n|t_readStep : forall S L E l t v e0 S', \n                decompose t E (get (loc l)) -> logLookup L l = None ->\n                lookup H l = Some(v, S') -> S > S' ->\n                trans_step H (Some(S, e0), L, t) \n                             (Some(S, e0), readItem l E v::L, fill E v)\n|t_readInDomainStep : forall S l v L E t e0,\n                      decompose t E (get (loc l)) -> logLookup L l = Some v ->\n                      trans_step H (Some(S, e0), L, t) (Some(S, e0), L, fill E v)\n|t_writeStep : forall S L E l v t,\n               decompose t E (put (loc l) v) -> S <> None ->\n               trans_step H (S, L, t) (S, writeItem l v::L, fill E unit)\n|t_atomicIdemStep : forall E e t L S,\n                     decompose t E (atomic e) -> S <> None ->\n                     trans_step H (S, L, t) (S, L, fill E e)\n|t_betaStep : forall L E e t v S, \n              decompose t E (app (lambda e) v) -> S <> None ->\n              trans_step H (S, L, t) (S, L, fill E (open e 0 v))\n.\n\n(*same as trans_step with addition of r_readStepInvalid*)\nInductive replay_step H : thread -> thread -> Prop :=\n|r_readStepValid : forall S L E l t v e0 S', \n                lookup H l = Some(v, S') -> S > S' ->\n                decompose t E (get (loc l)) -> logLookup L l = None ->\n                replay_step H (Some(S, e0), L, t) (Some(S, e0), readItem l E v::L, fill E v)\n|r_readStepInvalid : forall S L E v' l t v e0 S', \n                lookup H l = Some(v',S') -> S' >= S ->\n                decompose t E (get (loc l)) -> logLookup L l = None ->\n                replay_step H (Some(S, e0), L, t) (Some(S, e0), readItem l E v::L, fill E v)\n|r_readInDomainStep : forall S l v L E t e0,\n                      decompose t E (get (loc l)) -> logLookup L l = Some v ->\n                      replay_step H (Some(S, e0), L, t) (Some(S, e0), L, fill E v)\n|r_writeStep : forall S L E l v t,\n               decompose t E (put (loc l) v) -> S <> None ->\n               replay_step H (S, L, t) (S, writeItem l v::L, fill E unit)\n|r_atomicIdemStep : forall E e t L S,\n                     decompose t E (atomic e) -> S <> None ->\n                     replay_step H (S, L, t) (S, L, fill E e)\n|r_betaStep : forall L E e t v S, \n              decompose t E (app (lambda e) v) -> S <> None ->\n              replay_step H (S, L, t) (S, L, fill E (open e 0 v))\n.\n\n(*reflexive transitive closure of replay_step*)\nInductive replay H : thread -> thread -> Prop :=\n|replayRefl : forall t, replay H t t\n|replayStep : forall t t' t'', \n                replay_step H t t' -> replay H t' t'' -> \n                replay H t t''. \n\n(*left recursive version of replay*)\nInductive rewind H : thread -> thread -> Prop :=\n|rewindRefl : forall t, rewind H t t\n|rewindStep : forall t t' t'', \n                rewind H t t' -> replay_step H t' t'' -> \n                rewind H t t''. \n\n(*parital abort STM semantics (single step)*)\nInductive p_step : nat -> heap -> pool -> nat -> heap -> pool -> Prop :=\n|p_transStep : forall C H t t', trans_step H t t' -> \n                           p_step C H (Single t) C H (Single t')\n|p_parLStep : forall C H T1 T2 C' H' T1', \n          p_step C H T1 C' H' T1' -> p_step C H (Par T1 T2) C' H' (Par T1' T2)\n|p_parRStep : forall C H T1 T2 C' H' T2', \n          p_step C H T2 C' H' T2' -> p_step C H (Par T1 T2) C' H' (Par T1 T2')\n|p_forkStep : forall C H E e t, \n              decompose t E (fork e) ->\n              p_step C H (Single(None, nil, t)) C H \n                   (Par (Single(None, nil, fill E unit)) (Single(None, nil, e)))\n|p_eagerAbort : forall L S H L' C e0 e' t v E l S',\n                  lookup H l = Some(v, S') -> S < S' ->\n                  validate S (readItem l E v::L) H C (abort e' L') ->\n                  decompose t E (get (loc l)) -> logLookup L l = None ->\n                  p_step C H (Single (Some(S, e0), L, t))\n                         (C+1) H (Single(Some(C, e0), L', e'))\n|p_abortStep : forall L S H L' C e e0 e' S', \n           validate S L H S' (abort e' L') ->\n           p_step C H (Single(Some(S, e0), L, e))\n                  (plus 1 C) H (Single(Some(C, e0), L', e'))\n|p_allocStep : forall C H v E t l, \n               lookup H l = None -> decompose t E (alloc v) ->\n               p_step C H (Single(None, nil, t)) (plus 1 C) ((l, v, C)::H)\n                    (Single(None, nil, fill E (loc l)))\n|p_commitStep : forall C H S L v t E H' e0, \n                validate S L H C (commit H') -> decompose t E (inatomic v) ->\n                p_step C H (Single(Some(S, e0), L, t)) (plus 1 C) H' (Single(None, nil, fill E v))\n|p_atomicStep : forall C H E e t, \n                decompose t E (atomic e) ->\n                p_step C H (Single(None, nil, t)) (plus 1 C) H \n                       (Single(Some(C, fill E(inatomic e)),[],fill E (inatomic e)))\n|p_betaStep : forall C H E e t v, \n              decompose t E (app (lambda e) v) -> \n              p_step C H (Single(None, nil, t)) C H\n                     (Single(None, nil, fill E (open e 0 v))). \n\n(*reflexive transitive closure of partial multistep*)\nInductive p_multistep : nat -> heap -> pool -> nat -> heap -> pool -> Prop :=\n|p_multi_refl : forall C H T, p_multistep C H T C H T\n|p_multi_step : forall C H T C' H' T' C'' H'' T'', \n                p_step C H T C' H' T' -> p_multistep C' H' T' C'' H'' T'' ->\n                p_multistep C H T C'' H'' T''. \n\n(*full abort STM semantics (single step)*)\nInductive f_step : nat -> heap -> pool -> nat -> heap -> pool -> Prop :=\n|f_transStep : forall C H t t', trans_step H t t' -> \n                           f_step C H (Single t) C H (Single t')\n|f_parLStep : forall C H T1 T2 C' H' T1', \n          f_step C H T1 C' H' T1' -> f_step C H (Par T1 T2) C' H' (Par T1' T2)\n|f_parRStep : forall C H T1 T2 C' H' T2', \n          f_step C H T2 C' H' T2' -> f_step C H (Par T1 T2) C' H' (Par T1 T2')\n|f_forkStep : forall C H E e t, \n              decompose t E (fork e) ->\n              f_step C H (Single(None, nil, t)) C H \n                   (Par (Single(None, nil, fill E unit)) (Single(None, nil, e)))\n|f_eagerAbort : forall L S H L' C e0 e' t v E l S',\n                  lookup H l = Some(v, S') -> S < S' ->\n                  validate S (readItem l E v::L) H C (abort e' L') ->\n                  decompose t E (get (loc l)) -> logLookup L l = None ->\n                  f_step C H (Single (Some(S, e0), L, t))\n                         (C+1) H (Single(Some(C, e0), nil, e0))\n|f_abortStep : forall L S H L' C e e0 e' S', \n           validate S L H S' (abort e' L') -> \n           f_step C H (Single(Some(S, e0), L, e)) (plus 1 C) H \n                  (Single(Some(C, e0), nil, e0))\n|f_allocStep : forall C H v E t l, \n               lookup H l = None -> decompose t E (alloc v) ->\n               f_step C H (Single(None, nil, t)) (plus 1 C) ((l, v, C)::H)\n                    (Single(None, nil, fill E (loc l)))\n|f_commitStep : forall C H S L v t E H' e0, \n                validate S L H C (commit H') -> decompose t E (inatomic v) ->\n                f_step C H (Single(Some(S, e0), L, t)) (plus 1 C) H' (Single(None, nil, fill E v))\n|f_atomicStep : forall C H E e t, \n                decompose t E (atomic e) ->\n                f_step C H (Single(None, nil, t)) (plus 1 C) H \n                       (Single(Some(C, fill E (inatomic e)), nil, fill E (inatomic e)))\n|f_betaStep : forall C H E e t v, \n              decompose t E (app (lambda e) v) -> \n              f_step C H (Single(None, nil, t)) C H \n                     (Single(None, nil, fill E (open e 0 v))). \n\n(*reflexivie transitive closure of full multistep*)\nInductive f_multistep : nat -> heap -> pool -> nat -> heap -> pool -> Prop :=\n|f_multi_refl : forall C H T, f_multistep C H T C H T\n|f_multi_step : forall C H T C' H' T' C'' H'' T'', \n                f_step C H T C' H' T' -> f_multistep C' H' T' C'' H'' T'' ->\n                f_multistep C H T C'' H'' T''. \n\n(*reflexivit transitive closure of trans_step*)\nInductive trans_multistep H : thread -> thread -> Prop :=\n|trans_refl : forall t, trans_multistep H t t\n|trans_multi_step : forall t t' t'', \n                      trans_step H t t' -> trans_multistep H t' t'' ->\n                      trans_multistep H t t''. \n\n(*indicates that L1 is a postfix of L2*)\nDefinition postfix {A:Type} (L1 L2 : list A) := exists diff, L2 = diff ++ L1. \n\n(*all threads can rewind to their initial term of a transaction and have\n**a stamp number less than the global clock.  The stamp number \n**constraint probably doesn't belong here, but its handy to have*)\nInductive poolRewind C H : pool -> Prop :=\n|rewindSingleNoTX : forall e, poolRewind C H (Single(None,nil,e))\n|rewindSingleInTX : forall S e0 L e, \n                      rewind H (Some(S,e0),nil,e0) (Some(S,e0),L,e) ->\n                      S < C -> poolRewind C H (Single(Some(S,e0),L,e))\n|rewindPar : forall T1 T2, poolRewind C H T1 -> poolRewind C H T2 -> poolRewind C H (Par T1 T2). \n\n(*inject every step in a multistep derivation into a Par*)\nTheorem f_multi_L : forall C H T1 T2 T1' C' H', \n                      f_multistep C H T1 C' H' T1' ->\n                      f_multistep C H (Par T1 T2) C' H' (Par T1' T2). \nProof.\n  intros C H T1 T2 T1' C' H' HYP. induction HYP.\n  {constructor. }\n  {econstructor. eapply f_parLStep. eassumption. eassumption. }\nQed. \n\n(*inject every step in a multistep derivation into a Par*)\nTheorem f_multi_R : forall C H T1 T2 T2' C' H', \n                      f_multistep C H T2 C' H' T2' ->\n                      f_multistep C H (Par T1 T2) C' H' (Par T1 T2'). \nProof.\n  intros C H T1 T2 T2' C' H' HYP. induction HYP.\n  {constructor. }\n  {econstructor. eapply f_parRStep. eassumption. eassumption. }\nQed. \n\n(*validation is idempotent*)\nTheorem validateValidate : forall S L H S' L' e, \n                             validate S L H S' (abort e L') ->\n                             exists H'', validate S L' H S' (commit H''). \nProof.\n  intros S L H S' L' e HYP. dependent induction HYP; eauto. \nQed. \n\n(*the log returned in an abort is a postfix of the initial log*)\nTheorem abortLogPostfix : forall S L H S' L' e, \n                            validate S L H S' (abort e L') ->\n                            postfix L' L. \nProof.\n  intros S L H S' L' e HYP. remember (abort e L'). induction HYP; try solveByInv. \n  {apply IHHYP in Heqv. unfold postfix in *. invertHyp.  exists (x::x0). auto. }\n  {inv Heqv. unfold postfix. exists [readItem l E v']. auto. }\nQed.\n\n(*filling an evaluation context with the result of a decomposition\n**yields the initial term that was decomposed *)\nTheorem decomposeEq : forall E t e, decompose t E e -> t = fill E e. \nProof.\n  induction E; intros; try solve[inv H; simpl;erewrite <- IHE; eauto]. \n  {inv H; auto. }\nQed. \n\nTheorem lengthsEq : forall (A:Type) (x y : list A), x = y -> length x = length y. \nProof.\n  induction x; intros. \n  {destruct y. auto. inv H. }\n  {destruct y. inv H. inv H. simpl. apply f_equal. auto. }\nQed. \n\n(*replay relation is transitive*)\nTheorem trans_replay: forall H t t' t'', \n                         replay H t' t'' -> replay H t t' ->\n                         replay H t t''. \nProof.\n  intros H t t' t'' HYP1 HYP2. induction HYP2. auto. econstructor. eauto. auto. \nQed. \n\n(*rewind relation is transitive*)\nTheorem rewindTrans : forall H t t' t'', \n                        rewind H t t' -> rewind H t' t'' ->\n                        rewind H t t''. \nProof.\n  intros H t t' t'' HYP1 HYP2. generalize dependent t. induction HYP2; intros; auto.\n  econstructor. eapply IHHYP2. assumption. assumption. \nQed. \n\n(*replay and rewind are equivalent*)\nTheorem rewindIFFReplay : forall H t t', \n                            rewind H t t' <-> replay H t t'. \nProof.\n  intros H t t'. split; intros HYP. \n  {induction HYP. constructor. eapply trans_replay; eauto.\n   econstructor. eauto. constructor. }\n  {induction HYP. constructor. eapply rewindTrans; eauto.\n   econstructor; eauto. constructor. }\nQed. \n\n(*partial multistep relation is transitive*)\nTheorem p_multi_trans : forall C H T C' H' T' C'' H'' T'',\n                          p_multistep C H T C' H' T' ->\n                          p_multistep C' H' T' C'' H'' T'' ->\n                          p_multistep C H T C'' H'' T''.\nProof.\n  intros C H T C' H' T' C'' H'' T'' HYP1 HYP2. \n  induction HYP1; auto. econstructor; eauto.\nQed. \n\n(*full multistep relation is transitive*)\nTheorem f_multi_trans : forall C H T C' H' T' C'' H'' T'',\n                          f_multistep C H T C' H' T' ->\n                          f_multistep C' H' T' C'' H'' T'' ->\n                          f_multistep C H T C'' H'' T''.\nProof.\n  intros C H T C' H' T' C'' H'' T'' HYP1 HYP2. \n  induction HYP1; auto. econstructor; eauto. \nQed. \n\n(*inject left multistep derivation into a Par*)\nTheorem p_multi_L : forall C H T1 T2 T1' C' H', \n                      p_multistep C H T1 C' H' T1' ->\n                      p_multistep C H (Par T1 T2) C' H' (Par T1' T2). \nProof.\n  intros. induction H0.\n  {constructor. }\n  {econstructor. eapply p_parLStep. eassumption. eassumption. }\nQed. \n\n(*inject right multistep derivation into a Par*)\nTheorem p_multi_R : forall C H T1 T2 T2' C' H', \n                      p_multistep C H T2 C' H' T2' ->\n                      p_multistep C H (Par T1 T2) C' H' (Par T1 T2'). \nProof.\n  intros. induction H0.\n  {constructor. }\n  {econstructor. eapply p_parRStep. eassumption. eassumption. }\nQed. ", "meta": {"author": "lematt1991", "repo": "ICFP15-Coq-Proofs", "sha": "c84953450f1145bdc22b71f2557d9a08be58a34d", "save_path": "github-repos/coq/lematt1991-ICFP15-Coq-Proofs", "path": "github-repos/coq/lematt1991-ICFP15-Coq-Proofs/ICFP15-Coq-Proofs-c84953450f1145bdc22b71f2557d9a08be58a34d/semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2431017652866156}}
{"text": "Require Import MirrorCore.Lambda.ExprCore.\n\nRequire Import floyd_funcs.\n\nRequire Import ExtLib.Core.RelDec.\nRequire Import MirrorCore.TypesI.\nRequire Import ExtLib.Tactics.\nRequire Import ExtLib.Data.Fun.\n(*Require Import progs.list_dt. *)\nRequire Import Coq.FSets.FMapPositive.\n\nInductive typ :=\n| tyArr : typ -> typ -> typ\n| tytycontext\n| tyc_expr\n| tyc_type\n| tyenviron\n| tyval\n| tyshare\n| tyident\n| tylist : typ -> typ\n| tyint\n| tyZ\n| tynat\n| typositive\n| tybool\n| tycomparison\n| tytc_assert\n| tyint64\n| tyfloat\n| tyfloat32\n| tyattr\n| tysignedness\n| tyintsize\n| tyfloatsize\n| tytypelist\n| tyfieldlist\n| tybinary_operation\n| tyunary_operation\n| tyN\n| tyoption : typ -> typ\n| typrop\n| tympred\n| tysum : typ -> typ -> typ\n| typrod : typ -> typ -> typ\n| tyunit\n(*| tylistspec : type -> ident -> typ*)\n| tyOracleKind\n| tystatement\n| tyret_assert\n| tyexitkind\n| typtree : typ -> typ\n| tygfield\n| tyfunspec\n| tyefield\n| tytype_id_env\n| tyllrr\n(*| tyother : positive -> typ*)\n.\n\nFixpoint typD (t : typ) (*(m : PositiveMap.t Type)*): Type :=\n    match t with\n        | tyArr a b => typD a  -> typD b\n        | tytycontext => tycontext\n        | tyc_expr => expr\n        | tyc_type => type\n        | tyenviron => environ\n        | tyval => val\n        | tyshare => share\n        | tyident => ident\n        | tylist t => list (typD t )\n        | tyint => int\n        | tyZ => Z\n        | tynat => nat\n        | typositive => positive\n        | tybool => bool\n        | tycomparison => comparison\n        | tytc_assert => tc_assert\n        | tyint64 => int64\n        | tyfloat => float\n        | tyfloat32 => float32\n        | tyattr => attr\n        | tysignedness => signedness\n        | tyintsize => intsize\n        | tyfloatsize  => floatsize\n        | tytypelist => typelist\n        | tyfieldlist => fieldlist\n        | tybinary_operation => Cop.binary_operation\n        | tyunary_operation => Cop.unary_operation\n        | tyN => N\n        | tyoption t => option (typD t )\n        | typrop => Prop\n        | tympred => mpred\n        | tysum t1 t2 => sum (typD  t1 ) (typD  t2 )\n        | typrod t1 t2 => prod (typD  t1 ) (typD  t2 )\n        | tyunit => unit\n        (*| tylistspec t i => listspec t i *)\n        | tyOracleKind => OracleKind\n        | tystatement => statement\n        | tyret_assert => ret_assert\n(*        | tyother p => PositiveMap.find p m *)\n        | tyexitkind => exitkind\n        | typtree t => PTree.t (typD t)\n        | tygfield => gfield\n        | tyfunspec => funspec\n        | tyefield => efield\n        | tytype_id_env => type_id_env\n        | tyllrr => LLRR\n    end.\n(*\nLemma listspec_ext : forall t i (a b: listspec t i), a = b.\nintros. destruct a,b.\nsubst. inversion list_struct_eq0.\nsubst. f_equal.\napply proof_irr.\napply proof_irr.\napply proof_irr.\nQed.\n*)\n\nDefinition typ_eq_dec : forall a b : typ, {a = b} + {a <> b}.\n  decide equality.\nDefined.\n(*\n  consider (eqb_ident i i0); intros;\n  try rewrite eqb_ident_spec in H. auto.\n  destruct (eqb_ident_spec i i0). right. intro. intuition. subst.\n  congruence.\n  consider (eqb_type t t0); intros.\n  rewrite eqb_type_spec in H. auto.\n  destruct (eqb_type_spec t t0).\n  right; intuition; subst; congruence.\n Defined.\n*)\n\nInstance RelDec_eq_typ : RelDec (@eq typ) :=\n{ rel_dec := fun a b =>\n               match typ_eq_dec a b with\n                 | left _ => true\n                 | right _ => false\n               end }.\n\nInstance RelDec_Correct_eq_typ : RelDec_Correct RelDec_eq_typ.\nProof.\n  constructor.\n  intros.\n  unfold rel_dec; simpl.\n  destruct (typ_eq_dec x y); intuition.\nQed.\n\nInductive tyAcc' : typ -> typ -> Prop :=\n| tyArrL : forall a b, tyAcc' a (tyArr a b)\n| tyArrR : forall a b, tyAcc' b (tyArr a b).\n\nInstance RType_typ : RType typ :=\n{ typD := typD\n; tyAcc := tyAcc'\n; type_cast := fun a b => match typ_eq_dec a b with\n                              | left pf => Some pf\n                              | _ => None\n                            end\n}.\n\nInstance RTypeOk_typ : @RTypeOk typ _.\nProof.\n  eapply makeRTypeOk.\n  { red.\n    induction a; constructor; inversion 1.\n    subst; auto.\n    subst; auto. }\n  { unfold type_cast; simpl.\n    intros. destruct (typ_eq_dec x x).\n    f_equal. compute.\n    uip_all. reflexivity. congruence. }\n  { unfold type_cast; simpl.\n    intros. destruct (typ_eq_dec x y); try congruence. }\nQed.\n\nInstance Typ2_tyArr : Typ2 _ Fun :=\n{ typ2 := tyArr\n; typ2_cast := fun  _ _ => eq_refl\n; typ2_match :=\n    fun T  t tr =>\n      match t as t return T (TypesI.typD  t) -> T (TypesI.typD  t) with\n        | tyArr a b => fun _ => tr a b\n        | _ => fun fa => fa\n      end\n}.\n\nInstance Typ2Ok_tyArr : Typ2Ok Typ2_tyArr.\nProof.\n  constructor.\n  { reflexivity. }\n  { apply tyArrL. }\n  { intros; apply tyArrR. }\n  { inversion 1; subst; unfold Rty; auto. }\n  { destruct x; simpl; eauto.\n    left; do 2 eexists; exists eq_refl. reflexivity. }\n  { destruct pf. reflexivity. }\nQed.\n\nInstance Typ0_tyProp : Typ0 _ Prop :=\n{| typ0 := typrop\n ; typ0_cast :=  eq_refl\n ; typ0_match := fun T  t =>\n                   match t as t\n                         return T Prop -> T (TypesI.typD  t) -> T (TypesI.typD  t)\n                   with\n                     | typrop => fun tr _ => tr\n                     | _ => fun _ fa => fa\n                   end\n |}.\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/mc_reify/types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24310176528661556}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness proof for constant propagation (processor-dependent part). *)\n\nRequire Import Coqlib.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Events.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import ConstpropOp.\nRequire Import Constprop.\n\n(** * Correctness of the static analysis *)\n\nSection ANALYSIS.\n\nVariable ge: genv.\nVariable sp: val.\n\n(** We first show that the dataflow analysis is correct with respect\n  to the dynamic semantics: the approximations (sets of values) \n  of a register at a program point predicted by the static analysis\n  are a superset of the values actually encountered during concrete\n  executions.  We formalize this correspondence between run-time values and\n  compile-time approximations by the following predicate. *)\n\nDefinition val_match_approx (a: approx) (v: val) : Prop :=\n  match a with\n  | Unknown => True\n  | I p => v = Vint p\n  | F p => v = Vfloat p\n  | L p => v = Vlong p\n  | G symb ofs => v = symbol_address ge symb ofs\n  | S ofs => v = Val.add sp (Vint ofs)\n  | Novalue => False\n  end.\n\nInductive val_list_match_approx: list approx -> list val -> Prop :=\n  | vlma_nil:\n      val_list_match_approx nil nil\n  | vlma_cons:\n      forall a al v vl,\n      val_match_approx a v ->\n      val_list_match_approx al vl ->\n      val_list_match_approx (a :: al) (v :: vl).\n\nLtac SimplVMA :=\n  match goal with\n  | H: (val_match_approx (I _) ?v) |- _ =>\n      simpl in H; (try subst v); SimplVMA\n  | H: (val_match_approx (F _) ?v) |- _ =>\n      simpl in H; (try subst v); SimplVMA\n  | H: (val_match_approx (L _) ?v) |- _ =>\n      simpl in H; (try subst v); SimplVMA\n  | H: (val_match_approx (G _ _) ?v) |- _ =>\n      simpl in H; (try subst v); SimplVMA\n  | H: (val_match_approx (S _) ?v) |- _ =>\n      simpl in H; (try subst v); SimplVMA\n  | _ =>\n      idtac\n  end.\n\nLtac InvVLMA :=\n  match goal with\n  | H: (val_list_match_approx nil ?vl) |- _ =>\n      inv H\n  | H: (val_list_match_approx (?a :: ?al) ?vl) |- _ =>\n      inv H; SimplVMA; InvVLMA\n  | _ =>\n      idtac\n  end.\n\n(** We then show that [eval_static_operation] is a correct abstract\n  interpretations of [eval_operation]: if the concrete arguments match\n  the given approximations, the concrete results match the\n  approximations returned by [eval_static_operation]. *)\n\nLemma eval_static_condition_correct:\n  forall cond al vl m b,\n  val_list_match_approx al vl ->\n  eval_static_condition cond al = Some b ->\n  eval_condition cond vl m = Some b.\nProof.\n  intros until b.\n  unfold eval_static_condition. \n  case (eval_static_condition_match cond al); intros;\n  InvVLMA; simpl; congruence.\nQed.\n\nRemark shift_symbol_address:\n  forall symb ofs n,\n  symbol_address ge symb (Int.add ofs n) = Val.add (symbol_address ge symb ofs) (Vint n).\nProof.\n  unfold symbol_address; intros. destruct (Genv.find_symbol ge symb); auto. \nQed.\n\nLemma eval_static_addressing_correct:\n  forall addr al vl v,\n  val_list_match_approx al vl ->\n  eval_addressing ge sp addr vl = Some v ->\n  val_match_approx (eval_static_addressing addr al) v.\nProof.\n  intros until v. unfold eval_static_addressing.\n  case (eval_static_addressing_match addr al); intros;\n  InvVLMA; simpl in *; FuncInv; try subst v; auto.\n  rewrite shift_symbol_address; auto.\n  rewrite Val.add_assoc. auto.\n  repeat rewrite shift_symbol_address. auto.\n  fold (Val.add (Vint n1) (symbol_address ge id ofs)).\n  repeat rewrite shift_symbol_address. repeat rewrite Val.add_assoc. rewrite Val.add_permut. auto.\n  repeat rewrite Val.add_assoc. decEq; simpl. rewrite Int.add_assoc. auto.\n  fold (Val.add (Vint n1) (Val.add sp (Vint ofs))).\n  rewrite Val.add_assoc. rewrite Val.add_permut. rewrite Val.add_assoc. \n  simpl. rewrite Int.add_assoc; auto.\n  rewrite shift_symbol_address. auto.\n  rewrite Val.add_assoc. auto. \n  rewrite shift_symbol_address. auto.\n  rewrite shift_symbol_address. rewrite Int.mul_commut; auto. \nQed.\n\nLemma eval_static_operation_correct:\n  forall op al vl m v,\n  val_list_match_approx al vl ->\n  eval_operation ge sp op vl m = Some v ->\n  val_match_approx (eval_static_operation op al) v.\nProof.\n  intros until v.\n  unfold eval_static_operation. \n  case (eval_static_operation_match op al); intros;\n  InvVLMA; simpl in *; FuncInv; try subst v; auto.\n  destruct (propagate_float_constants tt); simpl; auto.\n  rewrite Int.sub_add_opp. rewrite shift_symbol_address. rewrite Val.sub_add_opp. auto.\n  destruct (Int.eq n2 Int.zero). inv H0. \n    destruct (Int.eq n1 (Int.repr Int.min_signed) && Int.eq n2 Int.mone); inv H0; simpl; auto.\n  destruct (Int.eq n2 Int.zero); inv H0; simpl; auto.\n  destruct (Int.eq n2 Int.zero). inv H0. \n    destruct (Int.eq n1 (Int.repr Int.min_signed) && Int.eq n2 Int.mone); inv H0; simpl; auto.\n  destruct (Int.eq n2 Int.zero); inv H0; simpl; auto.\n  destruct (Int.ltu n2 Int.iwordsize); simpl; auto.\n  destruct (Int.ltu n Int.iwordsize); simpl; auto.\n  destruct (Int.ltu n2 Int.iwordsize); simpl; auto.\n  destruct (Int.ltu n Int.iwordsize); simpl; auto.\n  destruct (Int.ltu n (Int.repr 31)); inv H0. simpl; auto.\n  destruct (Int.ltu n2 Int.iwordsize); simpl; auto.\n  destruct (Int.ltu n Int.iwordsize); simpl; auto.\n  destruct (Int.ltu n Int.iwordsize); simpl; auto.\n  destruct (Int.ltu n Int.iwordsize);\n  destruct (Int.ltu (Int.sub Int.iwordsize n) Int.iwordsize); simpl; auto.\n  eapply eval_static_addressing_correct; eauto.\n  unfold eval_static_intoffloat.\n  destruct (Float.intoffloat n1) eqn:?; simpl in H0; inv H0.\n  simpl; auto.\n  destruct (propagate_float_constants tt); simpl; auto.\n  unfold eval_static_condition_val. destruct (eval_static_condition c vl0) as [b|] eqn:?.\n  rewrite (eval_static_condition_correct _ _ _ m _ H Heqo). \n  destruct b; simpl; auto.\n  simpl; auto.\nQed.\n\n(** * Correctness of strength reduction *)\n\n(** We now show that strength reduction over operators and addressing\n  modes preserve semantics: the strength-reduced operations and\n  addressings evaluate to the same values as the original ones if the\n  actual arguments match the static approximations used for strength\n  reduction. *)\n\nSection STRENGTH_REDUCTION.\n\nVariable app: D.t.\nVariable rs: regset.\nVariable m: mem.\nHypothesis MATCH: forall r, val_match_approx (approx_reg app r) rs#r.\n\nLtac InvApproxRegs :=\n  match goal with\n  | [ H: _ :: _ = _ :: _ |- _ ] => \n        injection H; clear H; intros; InvApproxRegs\n  | [ H: ?v = approx_reg app ?r |- _ ] => \n        generalize (MATCH r); rewrite <- H; clear H; intro; InvApproxRegs\n  | _ => idtac\n  end.\n\nLemma cond_strength_reduction_correct:\n  forall cond args vl,\n  vl = approx_regs app args ->\n  let (cond', args') := cond_strength_reduction cond args vl in\n  eval_condition cond' rs##args' m = eval_condition cond rs##args m.\nProof.\n  intros until vl. unfold cond_strength_reduction.\n  case (cond_strength_reduction_match cond args vl); simpl; intros; InvApproxRegs; SimplVMA.\n  rewrite H0. apply Val.swap_cmp_bool. \n  rewrite H. auto.\n  rewrite H0. apply Val.swap_cmpu_bool.\n  rewrite H. auto.\n  auto.\nQed.\n\nLemma addr_strength_reduction_correct:\n  forall addr args vl,\n  vl = approx_regs app args ->\n  let (addr', args') := addr_strength_reduction addr args vl in\n  eval_addressing ge sp addr' rs##args' = eval_addressing ge sp addr rs##args.\nProof.\n  intros until vl. unfold addr_strength_reduction.\n  destruct (addr_strength_reduction_match addr args vl); simpl; intros; InvApproxRegs; SimplVMA.\n  rewrite shift_symbol_address; congruence.\n  rewrite H. rewrite Val.add_assoc; auto.\n  rewrite H; rewrite H0. repeat rewrite shift_symbol_address. auto.\n  rewrite H; rewrite H0. rewrite Int.add_assoc. rewrite Int.add_permut. repeat rewrite shift_symbol_address.\n  rewrite Val.add_assoc. rewrite Val.add_permut. auto.\n  rewrite H; rewrite H0. repeat rewrite Val.add_assoc. rewrite Int.add_assoc. auto.\n  rewrite H; rewrite H0. repeat rewrite Val.add_assoc. rewrite Val.add_permut. \n  rewrite Int.add_assoc. auto.\n  rewrite H0. rewrite shift_symbol_address. repeat rewrite Val.add_assoc. \n  decEq; decEq. apply Val.add_commut.\n  rewrite H. rewrite shift_symbol_address. repeat rewrite Val.add_assoc.\n  rewrite (Val.add_permut (rs#r1)). decEq; decEq. apply Val.add_commut.\n  rewrite H0. rewrite Val.add_assoc. rewrite Val.add_permut. auto.\n  rewrite H. rewrite Val.add_assoc. auto.\n  rewrite H; rewrite H0. rewrite Int.add_assoc. repeat rewrite shift_symbol_address. auto.\n  rewrite H0. rewrite shift_symbol_address. rewrite Val.add_assoc. decEq; decEq. apply Val.add_commut.\n  rewrite H. auto.\n  rewrite H. rewrite shift_symbol_address. auto.\n  rewrite H. rewrite shift_symbol_address. rewrite Int.mul_commut; auto.\n  auto.\nQed.\n\nLemma make_addimm_correct:\n  forall n r,\n  let (op, args) := make_addimm n r in\n  exists v, eval_operation ge sp op rs##args m = Some v /\\ Val.lessdef (Val.add rs#r (Vint n)) v.\nProof.\n  intros. unfold make_addimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros. \n  subst. exists (rs#r); split; auto. destruct (rs#r); simpl; auto; rewrite Int.add_zero; auto.\n  exists (Val.add rs#r (Vint n)); auto.\nQed.\n  \nLemma make_shlimm_correct:\n  forall n r1,\n  let (op, args) := make_shlimm n r1 in\n  exists v, eval_operation ge sp op rs##args m = Some v /\\ Val.lessdef (Val.shl rs#r1 (Vint n)) v.\nProof.\n  intros; unfold make_shlimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.\n  exists (rs#r1); split; auto. destruct (rs#r1); simpl; auto. rewrite Int.shl_zero. auto.\n  econstructor; split. simpl. eauto. auto.\nQed.\n\nLemma make_shrimm_correct:\n  forall n r1,\n  let (op, args) := make_shrimm n r1 in\n  exists v, eval_operation ge sp op rs##args m = Some v /\\ Val.lessdef (Val.shr rs#r1 (Vint n)) v.\nProof.\n  intros; unfold make_shrimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.\n  exists (rs#r1); split; auto. destruct (rs#r1); simpl; auto. rewrite Int.shr_zero. auto.\n  econstructor; split; eauto. simpl. auto.\nQed.\n\nLemma make_shruimm_correct:\n  forall n r1,\n  let (op, args) := make_shruimm n r1 in\n  exists v, eval_operation ge sp op rs##args m = Some v /\\ Val.lessdef (Val.shru rs#r1 (Vint n)) v.\nProof.\n  intros; unfold make_shruimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.\n  exists (rs#r1); split; auto. destruct (rs#r1); simpl; auto. rewrite Int.shru_zero. auto.\n  econstructor; split; eauto. simpl. congruence.\nQed.\n\nLemma make_mulimm_correct:\n  forall n r1,\n  let (op, args) := make_mulimm n r1 in\n  exists v, eval_operation ge sp op rs##args m = Some v /\\ Val.lessdef (Val.mul rs#r1 (Vint n)) v.\nProof.\n  intros; unfold make_mulimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros. subst.\n  exists (Vint Int.zero); split; auto. destruct (rs#r1); simpl; auto. rewrite Int.mul_zero; auto.\n  predSpec Int.eq Int.eq_spec n Int.one; intros. subst.\n  exists (rs#r1); split; auto. destruct (rs#r1); simpl; auto. rewrite Int.mul_one; auto.\n  destruct (Int.is_power2 n) eqn:?; intros.\n  rewrite (Val.mul_pow2 rs#r1 _ _ Heqo). apply make_shlimm_correct; auto. \n  econstructor; split; eauto. auto. \nQed.\n\nLemma make_divimm_correct:\n  forall n r1 r2 v,\n  Val.divs rs#r1 rs#r2 = Some v ->\n  rs#r2 = Vint n ->\n  let (op, args) := make_divimm n r1 r2 in\n  exists w, eval_operation ge sp op rs##args m = Some w /\\ Val.lessdef v w.\nProof.\n  intros; unfold make_divimm.\n  destruct (Int.is_power2 n) eqn:?.\n  destruct (Int.ltu i (Int.repr 31)) eqn:?.\n  exists v; split; auto. simpl. eapply Val.divs_pow2; eauto. congruence. \n  exists v; auto.\n  exists v; auto.\nQed.\n\nLemma make_divuimm_correct:\n  forall n r1 r2 v,\n  Val.divu rs#r1 rs#r2 = Some v ->\n  rs#r2 = Vint n ->\n  let (op, args) := make_divuimm n r1 r2 in\n  exists w, eval_operation ge sp op rs##args m = Some w /\\ Val.lessdef v w.\nProof.\n  intros; unfold make_divuimm.\n  destruct (Int.is_power2 n) eqn:?.\n  replace v with (Val.shru rs#r1 (Vint i)). \n  eapply make_shruimm_correct; eauto.\n  eapply Val.divu_pow2; eauto. congruence.\n  exists v; auto.\nQed.\n\nLemma make_moduimm_correct:\n  forall n r1 r2 v,\n  Val.modu rs#r1 rs#r2 = Some v ->\n  rs#r2 = Vint n ->\n  let (op, args) := make_moduimm n r1 r2 in\n  exists w, eval_operation ge sp op rs##args m = Some w /\\ Val.lessdef v w.\nProof.\n  intros; unfold make_moduimm.\n  destruct (Int.is_power2 n) eqn:?.\n  exists v; split; auto. simpl. decEq. eapply Val.modu_pow2; eauto. congruence.\n  exists v; auto.\nQed.\n\nLemma make_andimm_correct:\n  forall n r,\n  let (op, args) := make_andimm n r in\n  exists v, eval_operation ge sp op rs##args m = Some v /\\ Val.lessdef (Val.and rs#r (Vint n)) v.\nProof.\n  intros; unfold make_andimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros.\n  subst n. exists (Vint Int.zero); split; auto. destruct (rs#r); simpl; auto. rewrite Int.and_zero; auto.\n  predSpec Int.eq Int.eq_spec n Int.mone; intros.\n  subst n. exists (rs#r); split; auto. destruct (rs#r); simpl; auto. rewrite Int.and_mone; auto.\n  econstructor; split; eauto. auto. \nQed.\n\nLemma make_orimm_correct:\n  forall n r,\n  let (op, args) := make_orimm n r in\n  exists v, eval_operation ge sp op rs##args m = Some v /\\ Val.lessdef (Val.or rs#r (Vint n)) v.\nProof.\n  intros; unfold make_orimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros.\n  subst n. exists (rs#r); split; auto. destruct (rs#r); simpl; auto. rewrite Int.or_zero; auto.\n  predSpec Int.eq Int.eq_spec n Int.mone; intros.\n  subst n. exists (Vint Int.mone); split; auto. destruct (rs#r); simpl; auto. rewrite Int.or_mone; auto.\n  econstructor; split; eauto. auto. \nQed.\n\nLemma make_xorimm_correct:\n  forall n r,\n  let (op, args) := make_xorimm n r in\n  exists v, eval_operation ge sp op rs##args m = Some v /\\ Val.lessdef (Val.xor rs#r (Vint n)) v.\nProof.\n  intros; unfold make_xorimm.\n  predSpec Int.eq Int.eq_spec n Int.zero; intros.\n  subst n. exists (rs#r); split; auto. destruct (rs#r); simpl; auto. rewrite Int.xor_zero; auto.\n  econstructor; split; eauto. auto. \nQed.\n\nLemma make_mulfimm_correct:\n  forall n r1 r2,\n  rs#r2 = Vfloat n ->\n  let (op, args) := make_mulfimm n r1 r1 r2 in\n  exists v, eval_operation ge sp op rs##args m = Some v /\\ Val.lessdef (Val.mulf rs#r1 rs#r2) v.\nProof.\n  intros; unfold make_mulfimm. \n  destruct (Float.eq_dec n (Float.floatofint (Int.repr 2))); intros. \n  simpl. econstructor; split. eauto. rewrite H; subst n.\n  destruct (rs#r1); simpl; auto. rewrite Float.mul2_add; auto. \n  simpl. econstructor; split; eauto. \nQed.\n\nLemma make_mulfimm_correct_2:\n  forall n r1 r2,\n  rs#r1 = Vfloat n ->\n  let (op, args) := make_mulfimm n r2 r1 r2 in\n  exists v, eval_operation ge sp op rs##args m = Some v /\\ Val.lessdef (Val.mulf rs#r1 rs#r2) v.\nProof.\n  intros; unfold make_mulfimm. \n  destruct (Float.eq_dec n (Float.floatofint (Int.repr 2))); intros. \n  simpl. econstructor; split. eauto. rewrite H; subst n.\n  destruct (rs#r2); simpl; auto. rewrite Float.mul2_add; auto. \n  rewrite Float.mul_commut; auto. \n  simpl. econstructor; split; eauto. \nQed.\n\nLemma op_strength_reduction_correct:\n  forall op args vl v,\n  vl = approx_regs app args ->\n  eval_operation ge sp op rs##args m = Some v ->\n  let (op', args') := op_strength_reduction op args vl in\n  exists w, eval_operation ge sp op' rs##args' m = Some w /\\ Val.lessdef v w.\nProof.\n  intros until v; unfold op_strength_reduction;\n  case (op_strength_reduction_match op args vl); simpl; intros.\n(* sub *)\n  InvApproxRegs. SimplVMA. inv H0; rewrite H. rewrite Val.sub_add_opp. apply make_addimm_correct; auto. \n(* mul *)\n  InvApproxRegs. SimplVMA. inv H0; rewrite H1. rewrite Val.mul_commut. apply make_mulimm_correct; auto.\n  InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_mulimm_correct; auto.\n(* divs *) \n  assert (rs#r2 = Vint n2). clear H0. InvApproxRegs; SimplVMA; auto.\n  apply make_divimm_correct; auto.\n(* divu *) \n  assert (rs#r2 = Vint n2). clear H0. InvApproxRegs; SimplVMA; auto.\n  apply make_divuimm_correct; auto.\n(* modu *) \n  assert (rs#r2 = Vint n2). clear H0. InvApproxRegs; SimplVMA; auto.\n  apply make_moduimm_correct; auto.\n(* and *)\n  InvApproxRegs. SimplVMA. inv H0; rewrite H1. rewrite Val.and_commut. apply make_andimm_correct; auto.\n  InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_andimm_correct; auto.\n(* or *)\n  InvApproxRegs. SimplVMA. inv H0; rewrite H1. rewrite Val.or_commut. apply make_orimm_correct; auto.\n  InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_orimm_correct; auto.\n(* xor *)\n  InvApproxRegs. SimplVMA. inv H0; rewrite H1. rewrite Val.xor_commut. apply make_xorimm_correct; auto.\n  InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_xorimm_correct; auto.\n(* shl *)\n  InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_shlimm_correct; auto.\n(* shr *)\n  InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_shrimm_correct; auto.\n(* shru *)\n  InvApproxRegs. SimplVMA. inv H0; rewrite H. apply make_shruimm_correct; auto.\n(* lea *)\n  generalize (addr_strength_reduction_correct addr args0 vl0 H). \n  destruct (addr_strength_reduction addr args0 vl0) as [addr' args'].\n  intro EQ. exists v; split; auto. simpl. congruence.\n(* cond *)\n  generalize (cond_strength_reduction_correct c args0 vl0 H). \n  destruct (cond_strength_reduction c args0 vl0) as [c' args']; intros.\n  rewrite <- H1 in H0; auto. econstructor; split; eauto.\n(* mulf *)\n  inv H0. assert (rs#r2 = Vfloat n2). InvApproxRegs; SimplVMA; auto.\n  apply make_mulfimm_correct; auto.\n  inv H0. assert (rs#r1 = Vfloat n1). InvApproxRegs; SimplVMA; auto.\n  apply make_mulfimm_correct_2; auto.\n(* default *)\n  exists v; auto.\nQed.\n\nEnd STRENGTH_REDUCTION.\n\nEnd ANALYSIS.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/ia32/ConstpropOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24310176528661556}}
{"text": "(*\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(** CAMP is a small calculus for pattern matching. Its purpose is to\n  capture the semantics of rules languages that rely on the ability to\n  recover from match failure. *)\n\n(** Two distinct evaluation functions for CAMP are defined. The first\n  is a standard evaluation function and serves as semantic\n  definition. The second is equivalent but maintains a trace of the\n  evaluation for debugging purposes. *)\n  \n(** Summary:\n- Language: CAMP (Calculus for Aggregating Matching Patterns)\n- Based on: \"A Pattern Calculus for Rule Languages:\n  Expressiveness, Compilation, and Mechanization\" Avraham\n  Shinnar, Jérôme Siméon, and Martin Hirzel. ECOOP'2015.\n- URL: http://drops.dagstuhl.de/opus/volltexte/2015/5237/\n- Languages translating to CAMP: TechRule, DesignRule, CAMPRule, cNNRC\n- Languages translating from CAMP: NRA, cNRAEnv, NRAEnv\n*)\n  \nRequire Import String.\nRequire Import List.\nRequire Import EquivDec.\nRequire Import Morphisms.\nRequire Import Utils.\nRequire Import DataRuntime.\nRequire Import CAMPUtil.\n\nDeclare Scope camp_scope.\n\nSection CAMP.\n  Local Open Scope string.\n\n  Context {fruntime:foreign_runtime}.\n\n  (** * Abstract Syntax Tree *)\n\n  (** CAMP patterns are pure expressions. They match against a current\n  value in the context of an environment. The environment has a\n  globale component which is static, and a local component which can\n  be modified in the course of evaluation. *)\n\n  (** Operations include: pmap, a functional map which skips match\n  failure; passert, which turns match failure into a terminal failure,\n  and porElse which allows to continue to a new pattern in case of\n  match failure. *)\n\n  (** Compared to the published material, three new operators are\n  added: pgetConstant which accesses the global environment, pleft and\n  pright which support pattern matching against choice values. *)\n  \n  Inductive camp : Set :=\n  | pconst : data -> camp                  (**r Constant value *)\n  | punop : unary_op -> camp -> camp        (**r Unary operators *)\n  | pbinop : binary_op -> camp -> camp -> camp (**r Binary operators *)\n  | pmap : camp -> camp                    (**r Functional map *)\n  | passert : camp -> camp                 (**r Assert pattern-matching success *)\n  | porElse : camp -> camp -> camp         (**r Recover from failure *)\n  | pit : camp                             (**r Current value being matched *)\n  | pletIt : camp -> camp -> camp          (**r Set the current value *)\n  | pgetConstant : string -> camp          (**r Access to a global variable *)\n  | penv : camp                            (**r Current environment *)\n  | pletEnv : camp -> camp -> camp         (**r Add bindings to the environment *)\n  | pleft : camp                           (**r Matches if the value is a left choice *)\n  | pright : camp.                         (**r Matches if the value is a right choice *)\n\n  (* begin hide *)\n  Tactic Notation \"camp_cases\" tactic(first) ident(c) :=\n    first;\n    [ Case_aux c \"pconst\"%string\n    | Case_aux c \"punop\"%string\n    | Case_aux c \"pbinop\"%string\n    | Case_aux c \"pmap\"%string\n    | Case_aux c \"passert\"%string\n    | Case_aux c \"porElse\"%string\n    | Case_aux c \"pit\"%string\n    | Case_aux c \"pletIt\"%string\n    | Case_aux c \"pgetConstant\"%string\n    | Case_aux c \"penv\"%string\n    | Case_aux c \"pletEnv\"%string\n    | Case_aux c \"pleft\"%string\n    | Case_aux c \"pright\"%string].\n  (* end hide *)\n\n  (** Equality between two CAMP patterns is decidable. *)\n  \n  Global Instance camp_eqdec : EqDec camp eq.\n  Proof.\n    change (forall x y : camp, {x = y} + {x <> y}).\n    decide equality.\n    apply data_eqdec.\n    apply unary_op_eqdec.\n    apply binary_op_eqdec.\n    apply string_dec.\n  Qed.\n\n  (** * Evaluation Semantics *)\n  \n  (** Evaluation takes a camp pattern, a global environment, a local\n    environment and a current value. It returns a presult which can be\n    either a successful evaluation holding a value, a match failure,\n    or a terminal failure. *)\n\n  (** The external context for evaluation includes a brand relation,\n    and a global environment. *)\n  \n  Section Evaluation.\n    Context (h:brand_relation_t).\n    Context (constant_env:bindings).\n\n    Fixpoint camp_eval (p:camp) (bind:bindings) (d:data) : presult data\n      := match p with\n         | pconst d' => Success (normalize_data h d')\n         | punop op p₁ => bindpr (camp_eval p₁ bind d)\n                                 (fun d' => (op2tpr (unary_op_eval h op d')))\n         | pbinop op p₁ p₂ => \n           bindpr (camp_eval p₁ bind d)\n                  (fun d'₁ => \n                     bindpr (camp_eval p₂ bind d)\n                            (fun d'₂ =>  (op2tpr (binary_op_eval h op d'₁ d'₂))))\n         | pmap p₁ =>\n           match d with\n           | dcoll l => liftpr dcoll (gather_successes (map (camp_eval p₁ bind) l))\n           | _ => TerminalError\n           end\n         | passert p₁ =>\n           bindpr (camp_eval p₁ bind d)\n                  (fun d' => match d' with\n                             | dbool true => Success (drec nil)\n                             | dbool false => RecoverableError\n                             | _ => TerminalError \n                             end)\n         | porElse p₁ p₂ =>\n           match camp_eval p₁ bind d with\n           | TerminalError => TerminalError\n           | RecoverableError => camp_eval p₂ bind d\n           | Success x => Success x\n           end\n         | pit => Success d\n         | pletIt p₁ p₂ =>\n           bindpr (camp_eval p₁ bind d) (camp_eval p₂ bind)\n         | pgetConstant s => op2tpr (edot constant_env s)\n         | penv => Success (drec bind)\n         | pletEnv p₁ p₂ =>\n           bindpr (camp_eval p₁ bind d)\n                  (fun rd'₁ => match rd'₁ with\n                               | drec d'₁ => match merge_bindings bind d'₁ with\n                                             | Some bind' => camp_eval p₂ bind' d\n                                             | None => RecoverableError\n                                             end\n                               | _ => TerminalError \n                               end)\n         | pleft =>\n           match d with\n           | dleft d' => Success d'\n           | dright _ => RecoverableError \n           | _ => TerminalError \n           end\n         | pright =>\n           match d with\n           | dright d' => Success d'\n           | dleft _ => RecoverableError\n           | _ => TerminalError \n           end\n         end.\n\n  End Evaluation.\n\n  (** * Pretty Printing *)\n\n  (** Evaluation traces rely on printing support for CAMP's abstract syntax. *)\n    \n  Global Instance ToString_camp : ToString camp\n    := { toString :=\n           fix toStringp (p:camp) : string :=\n             match p with\n             | pconst d => \"(pconst \" ++ toString d ++ \")\"\n             | punop u p1 => \"(punop \" ++ toString u ++ \" \" ++ toStringp p1 ++ \")\"\n             | pbinop b p1 p2 => \"(pbinop \" ++ toString b ++ \" \" ++ toStringp p1++ \" \" ++ toStringp p2 ++ \")\"\n             | pmap p1 => \"(pmap \" ++ toStringp p1 ++ \")\"\n             | passert p1 => \"(passert \" ++ toStringp p1 ++ \")\"\n             | porElse p1 p2 => \"(porElse \" ++ toStringp p1++ \" \" ++ toStringp p2 ++ \")\"\n             | pit  => \"pit\"\n             | pletIt p1 p2 => \"(pletIt \" ++ toStringp p1++ \" \" ++ toStringp p2 ++ \")\"\n             | pgetConstant s => \"(pgetConstant \" ++ s ++ \")\"\n             | penv => \"penv\"\n             | pletEnv p1 p2 => \"(pletEnv \" ++ toStringp p1++ \" \" ++ toStringp p2 ++ \")\"\n             | pleft => \"pleft\"\n             | pright => \"pright\"\n             end\n       }.\n  \n  Fixpoint toString_camp_with_path (p:camp) (loc:camp_src_path) :=\n    match loc with\n    | nil => string_bracket \"<<<\"  (toString p) \">>>\"\n    | pos::loc' =>\n      match p with\n      | pconst d => \"(pconst \" ++ toString d ++ \")\"\n      | punop u p1 => \"(punop \" ++ toString u ++ \" \" ++\n                                toString_camp_with_path p1 loc' ++ \")\"\n      | pbinop b p1 p2 => \"(pbinop \"\n                            ++ toString b ++ \" \" ++\n                            (if pos == 0\n                             then toString_camp_with_path p1 loc'\n                             else toString p1)\n                            ++ \" \" ++\n                            (if pos == 1\n                             then toString_camp_with_path p2 loc'\n                             else toString p2) ++ \")\"\n      | pmap p1 => \"(pmap \" ++ toString_camp_with_path p1 loc' ++ \")\"\n      | passert p1 => \"(passert \" ++ toString_camp_with_path p1 loc' ++ \")\"\n      | porElse p1 p2 => \"(porElse \" ++\n                                     (if pos == 0\n                                      then toString_camp_with_path p1 loc'\n                                      else toString p1)\n                                     ++ \" \" ++\n                                     (if pos == 1\n                                      then toString_camp_with_path p2 loc'\n                                      else toString p2) ++ \")\"\n      | pit  => \"pit\"\n      | pletIt p1 p2 => \"(pletIt \" ++\n                                   (if pos == 0\n                                    then toString_camp_with_path p1 loc'\n                                    else toString p1)\n                                   ++ \" \" ++\n                                   (if pos == 1\n                                    then toString_camp_with_path p2 loc'\n                                    else toString p2) ++ \")\"\n      | pgetConstant s => \"(pgetConstant \" ++ s ++ \")\"\n      | penv => \"penv\"\n      | pletEnv p1 p2 => \"(pletEnv \" ++ \n                                     (if pos == 0\n                                      then toString_camp_with_path p1 loc'\n                                      else toString p1)\n                                     ++ \" \" ++\n                                     (if pos == 1\n                                      then toString_camp_with_path p2 loc'\n                                      else toString p2) ++ \")\"\n                                     \n      | pleft => \"pleft\"\n      | pright => \"pright\"\n      end\n    end.\n    \n  (** * Traced Evaluation *)\n  \n  (** An alternative version of the compiler that keeps debug\n     information. While this forces some code duplication, this is\n     mitigated by the fact that the evaluation code is relatively\n     small and simple. *)\n\n  (** The context is the same as for default evaluation, with an\n  additional printing flag. *)\n\n  Section EvaluationDebug.\n    Context (h:brand_relation_t).\n    Context (constant_env:list(string*data)).\n    Context (print_env:bool).\n\n    (** The following functions are used to produce error messages. *)\n    \n    Definition mk_err (desc:string) (p:camp) (bind:bindings) (it:data)\n      := toString p ++ \" failed\" ++ desc ++ \".\" ++\n                  (if print_env\n                   then \"\\n Current environment (env): \"\n                          ++ toString (drec bind)\n                   else \"\") ++\n                  \"\\n Current scrutinee (it): \"\n                  ++ toString it ++\n                  \"\\n\".\n  \n    (* It is important to separate out the debug messages.\n     Otherwise, they get reduced by proofs, which is painful *)\n    Definition punop_err (p:camp) (bind:bindings) (it:data) (d:data) : string\n      := (mk_err \"\" p bind it ++ \" The operator's argument was: \" ++ toString d ++ \"\\n\").\n    \n    Definition binop_err (p:camp) (bind:bindings) (it:data) (d'₁ d'₂:data) : string\n      := (mk_err \"\" p bind it ++ \" The operator's first argument was: \" ++ toString d'₁\n                 ++ \"\\n The operator's second argument was: \" ++ toString d'₂\n                 ++ \"\\n\").\n\n    Definition pmap_err (p:camp) (bind:bindings) (it:data) : string\n      := mk_err \" because the scrutinee was not a collection\" p bind it.\n\n    Definition passert_err (p:camp) (bind:bindings) (it d:data) : string\n      := mk_err \" because the argument was not a boolean\" p bind it\n                ++ \" The argument to passert was: \" ++ toString d\n                ++ \"\\n\".\n    \n    Definition pletEnv_err (p:camp) (bind:bindings) (it d:data) : string\n      := mk_err \" because its first argument was not a record\" p bind it\n                ++ \" The first argument to pletEnv was: \" ++ toString d.\n\n    Definition pleft_err (bind:bindings) (it:data) : string\n      := mk_err \" because the scrutinee was an incompatible type\" pleft bind it.\n    \n    Definition pright_err (bind:bindings) (it:data) : string\n      := mk_err \" because the scrutinee was an incompatible type\" pright bind it.\n    \n    Definition pgetConstant_err s (bind:bindings) (it:data) : string\n      := mk_err (\" because the given field (\" ++ s ++\n                                              \") is not a valid constant\") (pgetConstant s) bind it\n                ++ \" The set of constants for this execution is: \" ++\n                (string_bracket \"{\" (String.concat \"; \" (domain constant_env)) \"}\")\n                ++ \"\\n\".\n\n    (** The alternative traced evaluation is defined as follows. *)\n    \n    Fixpoint camp_eval_debug (loc:camp_src_path) (p:camp) (bind:bindings) (d:data) : presult_debug data\n      := match p with\n         | pconst d' => Success_debug (normalize_data h d')\n         | punop op p₁ =>\n           match camp_eval_debug (0::loc) p₁ bind d with\n           | TerminalError_debug s loc' => TerminalError_debug s loc'\n           | RecoverableError_debug s => RecoverableError_debug s\n           | Success_debug d' => \n             match unary_op_eval h op d' with\n             | None => TerminalError_debug (punop_err (punop op p₁) bind d d')  loc\n             | Some x => Success_debug x\n             end\n           end\n         | pbinop op p₁ p₂ =>\n           match camp_eval_debug (0::loc) p₁ bind d with\n           | TerminalError_debug s loc' => TerminalError_debug s loc'\n           | RecoverableError_debug s => RecoverableError_debug s\n           | Success_debug d'₁ =>\n             match camp_eval_debug (1::loc) p₂ bind d with\n             | TerminalError_debug s loc' => TerminalError_debug s loc'\n             | RecoverableError_debug s => RecoverableError_debug s\n             | Success_debug d'₂ =>\n               match binary_op_eval h op d'₁ d'₂ with\n               | None => TerminalError_debug (binop_err (pbinop op p₁ p₂) bind d d'₁ d'₂)  loc\n               | Some x => Success_debug x\n               end\n             end\n           end\n         | pmap p₁ =>\n           match d with\n           | dcoll l => liftpr_debug dcoll (gather_successes_debug (map (camp_eval_debug (0::loc) p₁ bind) l))\n           | _ => TerminalError_debug (pmap_err (pmap p₁) bind d) loc\n           end\n         | passert p₁ =>\n           match camp_eval_debug (0::loc) p₁ bind d with\n           | TerminalError_debug s loc' => TerminalError_debug s loc'\n           | RecoverableError_debug s => RecoverableError_debug s\n           | Success_debug d' =>\n             match d' with\n             | dbool true => Success_debug (drec nil)\n             | dbool false => RecoverableError_debug \"assertion failure\"\n             | _ => TerminalError_debug (passert_err (passert p₁) bind d d') loc\n             end\n           end\n         | porElse p₁ p₂ =>\n           match camp_eval_debug (0::loc) p₁ bind d with\n           | TerminalError_debug s loc' => TerminalError_debug s loc'\n           | RecoverableError_debug _ => camp_eval_debug (1::loc) p₂ bind d\n           | Success_debug x => Success_debug x\n           end\n         | pit => Success_debug d\n         | pletIt p₁ p₂ =>\n           match camp_eval_debug (0::loc) p₁ bind d with\n           | TerminalError_debug s loc' => TerminalError_debug s loc'\n           | RecoverableError_debug s => RecoverableError_debug s\n           | Success_debug x => camp_eval_debug (1::loc) p₂ bind x\n           end\n         | pgetConstant s =>\n           match edot constant_env s with\n           | Some x => Success_debug x\n           | None => TerminalError_debug (pgetConstant_err s bind d) loc\n           end\n         | penv => Success_debug (drec bind)\n         | pletEnv p₁ p₂ =>\n           match camp_eval_debug (0::loc) p₁ bind d with\n           | TerminalError_debug s loc' => TerminalError_debug s loc'\n           | RecoverableError_debug s => RecoverableError_debug s\n           | Success_debug rd'₁ => \n             match rd'₁ with\n             | drec d'₁ => match merge_bindings bind d'₁ with\n                           | Some bind' => camp_eval_debug (1::loc) p₂ bind' d\n                           | None => RecoverableError_debug \"bindings could not be unfied\"\n                           end\n             | _ => TerminalError_debug (pletEnv_err (pletEnv p₁ p₂) bind d rd'₁) loc\n             end\n           end\n         | pleft =>\n           match d with\n           | dleft d' => Success_debug d'\n           | dright _ => RecoverableError_debug \"pleft called on a pright\"\n           | _ => TerminalError_debug (pleft_err bind d) loc\n           end\n         | pright =>\n           match d with\n           | dright d' => Success_debug d'\n           | dleft _ => RecoverableError_debug \"pright called on a pleft\"\n           | _ => TerminalError_debug (pright_err bind d) loc\n           end\n         end.\n\n    (** The following theorem states that traced evaluation is equivalent to regular evaluation. *)\n    \n    Theorem camp_eval_debug_correct (loc:camp_src_path) (p:camp) (bind:bindings) (d:data) :\n      presult_same\n        (camp_eval h constant_env p bind d)\n        (camp_eval_debug loc p bind d).\n    Proof.\n      revert loc bind d.\n      camp_cases (induction p) Case; simpl; intros.\n      - trivial.\n      - apply bindpr_presult_same; [eauto | ]; intros.\n        destruct (unary_op_eval h u x); simpl; trivial. \n      - apply bindpr_presult_same; [eauto | ]; intros.\n        apply bindpr_presult_same; [eauto | ]; intros.\n        destruct (binary_op_eval h b x x0); simpl; trivial.\n      - destruct d; simpl; trivial.\n        apply liftpr_presult_same.\n        apply gather_successes_presult_same.\n        rewrite <- Forall2_map.\n        apply Forall2_refl; red; intros.\n        apply IHp.\n      - apply bindpr_presult_same; [eauto | ]; intros.\n        destruct x; simpl; trivial.\n        destruct b; simpl; trivial.\n      - specialize (IHp1 (0::loc) bind d); red in IHp1.\n        repeat match_destr_in IHp1; try tauto.\n      - trivial.\n      - apply bindpr_presult_same; [eauto | ]; intros.\n        eauto.\n      - unfold op2tpr. match_destr; simpl; trivial.\n      - trivial.\n      - apply bindpr_presult_same; [eauto | ]; intros.\n        destruct x; simpl; trivial.\n        destruct (merge_bindings bind l); simpl; trivial.\n      - destruct d; simpl; trivial.\n      - destruct d; simpl; trivial.\n    Qed.\n\n  End EvaluationDebug.\n\n  (** * Toplevel *)\n  \n  (** Top-level evaluation functions are used externally by the Q*cert\n  compiler. They take a CAMP pattern and a global environment as\n  input. The initial local environment is set to an empty record, and\n  the initial current value to unit. *)\n\n  (** The result of evaluation is lifted back from presult to and\n  optional value for consistency with evaluation functions for the\n  other intermediate languages. *)\n  \n  Section Top.\n    Context (h:brand_relation_t).\n\n    Definition presult_to_result (pr:presult data) : option data :=\n      match pr with\n      | Success l => Some (dcoll (l::nil))\n      | RecoverableError => Some (dcoll nil)\n      | TerminalError => None\n      end.\n\n    Definition camp_eval_top_to_presult (q:camp) (global_env:bindings) : presult data :=\n      camp_eval h (rec_sort global_env) q nil dunit.\n\n    (** The main top-level evaluation function for CAMP is as follows. *)\n    \n    Definition camp_eval_top (q:camp) (global_env:bindings) : option data :=\n      presult_to_result (camp_eval_top_to_presult q global_env).\n\n    Definition presult_to_result_debug (pr:presult_debug data) : option data :=\n      match pr with\n      | Success_debug l => Some (dcoll (l::nil))\n      | RecoverableError_debug _ => Some (dcoll nil)\n      | TerminalError_debug _ _ => None\n      end.\n\n    Definition pr2op_debug (pr:presult_debug data) : option data :=\n      match pr with\n      | Success_debug l => Some (dsome l)\n      | RecoverableError_debug _ => Some dnone\n      | TerminalError_debug _ _ => None\n      end.\n\n    Definition camp_eval_top_debug_to_presult_debug\n               (debug:bool) (q:camp) (global_env:bindings) : presult_debug data :=\n      camp_eval_debug h (rec_sort global_env) debug nil q nil dunit.\n\n    Theorem camp_eval_top_debug_correct (debug:bool) (p:camp) (global_env:bindings) (d:data) :\n      presult_same\n        (camp_eval_top_to_presult p global_env)\n        (camp_eval_top_debug_to_presult_debug debug p global_env).\n    Proof.\n      unfold camp_eval_top_to_presult.\n      unfold camp_eval_top_debug_to_presult_debug.\n      apply camp_eval_debug_correct.\n    Qed.\n    \n    Definition camp_eval_top_debug_to_data\n               (debug:bool) (q:camp) (global_env:bindings) : option data :=\n      presult_to_result_debug (camp_eval_debug h (rec_sort global_env) debug nil q nil dunit).\n\n    (** The main top-level traced evaluation function for CAMP is as follows. *)\n    \n    Definition camp_eval_top_debug (debug:bool) (q:camp) (global_env:bindings) : string :=\n      print_presult_debug q toString_camp_with_path\n                          (camp_eval_top_debug_to_presult_debug debug q global_env).\n  End Top.\n\nEnd CAMP.\n\n(* begin hide *)\nTactic Notation \"camp_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"pconst\"%string\n  | Case_aux c \"punop\"%string\n  | Case_aux c \"pbinop\"%string\n  | Case_aux c \"pmap\"%string\n  | Case_aux c \"passert\"%string\n  | Case_aux c \"porElse\"%string\n  | Case_aux c \"pit\"%string\n  | Case_aux c \"pletIt\"%string\n  | Case_aux c \"pgetConstant\"%string\n  | Case_aux c \"penv\"%string\n  | Case_aux c \"pletEnv\"%string\n  | Case_aux c \"pleft\"%string\n  | Case_aux c \"pright\"%string].\n(* end hide *)\n\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/CAMP/Lang/CAMP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24310175843743465}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\n\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.TermSanityInterface.\nRequire Import VerdiRaft.LogAllEntriesInterface.\n\nSection LogAllEntries.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n  Context {tsi : term_sanity_interface}.\n\n  Ltac rewrite_goal :=\n    match goal with\n      | H: _ = _ |- _ => rewrite H\n    end.\n    \n  Definition no_entries_past_current_term_host_lifted net :=\n    forall (h : name) e,\n      In e (log (snd (nwState net h))) ->\n      eTerm e <= currentTerm (snd (nwState net h)).\n\n  Lemma no_entries_past_current_term_host_lifted_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      no_entries_past_current_term_host_lifted net.\n  Proof using tsi rri. \n    unfold no_entries_past_current_term_host_lifted.\n    pose proof deghost_spec.\n    do 4 intro.\n    repeat find_reverse_higher_order_rewrite.\n    eapply lift_prop; eauto.\n    intros.\n    find_apply_lem_hyp no_entries_past_current_term_invariant; eauto.\n  Qed.\n\n  Lemma handleAppendEntries_currentTerm_monotonic:\n    forall h st (d : raft_data) \n      (m : msg) (t : term) (n : name) (pli : logIndex) \n      (plt : term) (es : list entry) (ci : logIndex),\n      handleAppendEntries h st t n pli plt es\n                          ci = (d, m) ->\n      currentTerm st <= currentTerm d.\n  Proof using. \n    intros.\n    unfold handleAppendEntries in *.\n    repeat break_match; simpl in *; do_bool; repeat find_inversion; auto; try lia;\n    simpl in *;\n    unfold advanceCurrentTerm in *; repeat break_match; do_bool; auto.\n  Qed.\n  \n  Lemma log_all_entries_append_entries :\n    refined_raft_net_invariant_append_entries log_all_entries.\n  Proof using tsi rri. \n    red. unfold log_all_entries. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    [|copy_eapply_prop_hyp In In; repeat find_rewrite; auto].\n    find_copy_apply_lem_hyp handleAppendEntries_currentTerm_monotonic.\n    find_eapply_lem_hyp update_elections_data_appendEntries_log_allEntries;\n      intuition; eauto; repeat find_rewrite; repeat rewrite_goal; eauto.\n    - copy_eapply_prop_hyp In In; repeat find_rewrite; auto.\n      find_apply_lem_hyp no_entries_past_current_term_host_lifted_invariant; auto.\n      repeat find_rewrite. eauto using Nat.le_antisymm.\n    - subst.\n      apply in_app_iff. right.\n      find_apply_hyp_hyp.\n      find_apply_lem_hyp no_entries_past_current_term_host_lifted_invariant; auto.\n      eauto using Nat.le_antisymm.\n    - subst.\n      apply in_app_iff.\n      left.\n      apply in_map_iff. eauto.\n    - do_in_app. intuition.\n      + subst.\n        apply in_app_iff.\n        left.\n        apply in_map_iff. eauto.\n      + subst.\n        apply in_app_iff. right.\n        find_apply_lem_hyp removeAfterIndex_in.\n        find_apply_hyp_hyp.\n        find_apply_lem_hyp no_entries_past_current_term_host_lifted_invariant; auto.\n        eauto using Nat.le_antisymm.\n  Qed.\n\n  Lemma log_all_entries_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply log_all_entries.\n  Proof using tsi rri. \n    red. unfold log_all_entries. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    [|copy_eapply_prop_hyp In In; repeat find_rewrite; auto].\n    find_copy_apply_lem_hyp handleAppendEntriesReply_log. find_rewrite.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_type_term.\n    intuition; repeat find_rewrite; copy_eapply_prop_hyp In In; repeat find_rewrite; auto.\n    find_apply_lem_hyp no_entries_past_current_term_host_lifted_invariant; auto.\n    repeat find_rewrite. eauto using Nat.le_antisymm.\n  Qed.\n\n  Lemma log_all_entries_request_vote :\n    refined_raft_net_invariant_request_vote log_all_entries.\n  Proof using tsi rri. \n    red. unfold log_all_entries. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    [|copy_eapply_prop_hyp In In; repeat find_rewrite; auto].\n    find_copy_apply_lem_hyp handleRequestVote_log. find_rewrite.\n    find_copy_apply_lem_hyp handleRequestVote_type_term.\n    rewrite update_elections_data_requestVote_allEntries.\n    intuition; repeat find_rewrite; copy_eapply_prop_hyp In In; repeat find_rewrite; auto.\n    find_apply_lem_hyp no_entries_past_current_term_host_lifted_invariant; auto.\n    repeat find_rewrite. eauto using Nat.le_antisymm.\n  Qed.\n\n  Lemma log_all_entries_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply log_all_entries.\n  Proof using tsi rri. \n    red. unfold log_all_entries. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    [|copy_eapply_prop_hyp In In; repeat find_rewrite; auto].\n    find_erewrite_lem handleRequestVoteReply_log.\n    rewrite update_elections_data_requestVoteReply_allEntries.\n    match goal with\n      | |- context [handleRequestVoteReply ?h ?st ?h' ?t ?v] =>\n        pose proof handleRequestVoteReply_type h st h' t v\n             (handleRequestVoteReply h st h' t v)\n    end.\n    intuition; repeat find_rewrite;\n    copy_eapply_prop_hyp In In; repeat find_rewrite; auto.\n    find_apply_lem_hyp no_entries_past_current_term_host_lifted_invariant; auto.\n    repeat find_rewrite.\n    unfold raft_data in *. simpl in *. \n    unfold raft_data in *. simpl in *.\n    lia.\n  Qed.\n\n  Lemma log_all_entries_do_leader :\n    refined_raft_net_invariant_do_leader log_all_entries.\n  Proof using. \n    red. unfold log_all_entries. intros.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    [|copy_eapply_prop_hyp In In; repeat find_rewrite; auto].\n    find_copy_apply_lem_hyp doLeader_type; intuition.\n    find_apply_lem_hyp doLeader_log. repeat find_rewrite.\n    copy_eapply_prop_hyp In In; repeat find_rewrite; auto.\n  Qed.\n  \n\n  Lemma log_all_entries_do_generic_server :\n    refined_raft_net_invariant_do_generic_server log_all_entries.\n  Proof using. \n    red. unfold log_all_entries. intros.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    [|copy_eapply_prop_hyp In In; repeat find_rewrite; auto].\n    find_copy_apply_lem_hyp doGenericServer_type; intuition.\n    find_apply_lem_hyp doGenericServer_log. repeat find_rewrite.\n    copy_eapply_prop_hyp In In; repeat find_rewrite; auto.\n  Qed.\n\n  Lemma log_all_entries_client_request :\n    refined_raft_net_invariant_client_request log_all_entries.\n  Proof using. \n    red. unfold log_all_entries. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    [|copy_eapply_prop_hyp In In; repeat find_rewrite; auto].\n    find_copy_apply_lem_hyp update_elections_data_client_request_log_allEntries.\n    find_apply_lem_hyp handleClientRequest_type.\n    intuition; repeat find_rewrite;\n    [copy_eapply_prop_hyp In In; repeat find_rewrite; auto|].\n    break_exists. intuition.\n    repeat find_rewrite.  simpl in *. intuition; subst; auto.\n    copy_eapply_prop_hyp In In; repeat find_rewrite; auto.\n  Qed.\n\n  Lemma log_all_entries_timeout :\n    refined_raft_net_invariant_timeout log_all_entries.\n  Proof using tsi rri. \n    red. unfold log_all_entries. intros.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    [|copy_eapply_prop_hyp In In; repeat find_rewrite; auto].\n    find_copy_apply_lem_hyp handleTimeout_log_same.\n    rewrite update_elections_data_timeout_allEntries.\n    find_apply_lem_hyp handleTimeout_type_strong.\n    intuition; repeat find_rewrite;\n    copy_eapply_prop_hyp In In; repeat find_rewrite; auto.\n    find_apply_lem_hyp no_entries_past_current_term_host_lifted_invariant; auto.\n    repeat find_rewrite.\n    unfold raft_data in *. simpl in *. \n    unfold raft_data in *. simpl in *.\n    lia.\n  Qed.\n\n  Lemma log_all_entries_reboot :\n    refined_raft_net_invariant_reboot log_all_entries.\n  Proof using. \n    red. unfold log_all_entries. intros.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    simpl in *. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    copy_eapply_prop_hyp In In; repeat find_rewrite; auto.\n  Qed.\n\n  Lemma log_all_entries_init :\n    refined_raft_net_invariant_init log_all_entries.\n  Proof using. \n    red. unfold log_all_entries. intros.\n    simpl in *. intuition.\n  Qed.\n\n  Lemma log_all_entries_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset log_all_entries.\n  Proof using. \n    red. unfold log_all_entries. intros.\n    simpl in *.\n    repeat find_reverse_higher_order_rewrite.\n    copy_eapply_prop_hyp In In; repeat find_rewrite; auto.\n  Qed.\n\n  Theorem log_all_entries_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      log_all_entries net.\n  Proof using tsi rri. \n    intros. apply refined_raft_net_invariant; auto.\n    - apply log_all_entries_init.\n    - apply log_all_entries_client_request.\n    - apply log_all_entries_timeout.\n    - apply log_all_entries_append_entries.\n    - apply log_all_entries_append_entries_reply.\n    - apply log_all_entries_request_vote.\n    - apply log_all_entries_request_vote_reply.\n    - apply log_all_entries_do_leader.\n    - apply log_all_entries_do_generic_server.\n    - apply log_all_entries_state_same_packet_subset.\n    - apply log_all_entries_reboot.\n  Qed.\n  \n  Instance laei : log_all_entries_interface.\n  split.\n  auto using log_all_entries_invariant.\n  Qed.\nEnd LogAllEntries.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft-proofs/LogAllEntriesProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24295081462946144}}
{"text": "Require Import String.\nRequire Import NPeano.\nRequire Import PeanoNat.\nRequire Import Coq.Strings.Ascii.\nRequire FMapWeakList.\nRequire Export Coq.Structures.OrderedTypeEx.\nRequire Import Lists.List.\nImport ListNotations.\nRequire Import JaSyntax.\nRequire Import JaTypes.\nRequire Import JaProgram.\nRequire Import JaEnvs.\nRequire Import Jafun.\nRequire Import JaIrisCommon.\nRequire Import JaEval.\nRequire Import JaSubtype.\nRequire Import Bool.\n\nRequire Export FMapAVL.\nRequire Export Coq.Structures.OrderedTypeEx.\nRequire Import FMapFacts.\n\nModule StrMap := JaIrisCommon.StrMap.\nModule HeapFacts := Facts Heap.\n\n(* Heaps *)\nDefinition JFIObjFieldEq (objLoc : Loc) (fieldName : string) (loc : Loc) (h : Heap) : Prop :=\n  match objLoc with\n    | null => False\n    | JFLoc n =>\n        match (Heap.find n h) with\n          | None => False\n          | Some obj => \n              match obj with\n                | (rawObj, className) =>\n                  match (JFXIdMap.find fieldName rawObj) with\n                    | Some val => val = loc\n                    | None => False\n                  end\n              end\n        end\n   end.\n\nDefinition JFIRawObjEq (obj1 : RawObj) (obj2 : RawObj) : Prop :=\n  forall id, match (JFXIdMap.find id obj1, JFXIdMap.find id obj2) with\n    | (Some l1, Some l2) => l1 = l2\n    | (None, None) => True\n    | _ => False\n  end.\n\nDefinition JFIObjEq (obj1 : Obj) (obj2 : Obj) : Prop := \n  match (obj1, obj2) with\n    | ((rawObj1, className1), (rawObj2, className2)) => className1 = className2 /\\ JFIRawObjEq rawObj1 rawObj2\n  end.\n\nDefinition JFIGetLocType (n : nat) (h : Heap) : option JFClassName :=\n  match (Heap.find n h) with\n    | None => None\n    | Some (_, objClass) => Some objClass\n  end.\n\nDefinition JFIValToLoc (val : JFIVal) (env : JFITermEnv) (this : nat) : option Loc :=\n  match val with\n  | JFINull => Some null\n  | JFIThis => Some (JFLoc this)\n  | JFIVar x => StrMap.find x env\n  end.\n\n(* Semantics *)\n\nFixpoint JFIHeapSatisfiesInEnv (h : Heap) (t : JFITerm) (env : JFITermEnv) (this : nat) (CC : JFProgram) : Prop :=\n  match t with\n    | JFITrue => True\n    | JFIFalse => False\n    | JFIAnd t1 t2 => JFIHeapSatisfiesInEnv h t1 env this CC /\\ JFIHeapSatisfiesInEnv h t2 env this CC\n    | JFIOr t1 t2 => JFIHeapSatisfiesInEnv h t1 env this CC \\/ JFIHeapSatisfiesInEnv h t2 env this CC\n    | JFIImplies t1 t2 => ~(JFIHeapSatisfiesInEnv h t1 env this CC) \\/ JFIHeapSatisfiesInEnv h t2 env this CC\n    | JFIHoare t1 e ex valueName t2 => JFIHeapSatisfiesInEnv h t1 env this CC -> exists confs hn res_ex res,\n        let newEnv := StrMap.add valueName res env\n        in (JFIEvalInEnv h e confs hn res_ex res env this CC) /\\\n           (res_ex = ex /\\ JFIHeapSatisfiesInEnv hn t2 newEnv this CC)\n    | JFIEq val1 val2 =>\n        let l1 := JFIValToLoc val1 env this\n        in let l2 := JFIValToLoc val2 env this\n        in match (l1, l2) with\n           | (Some loc1, Some loc2) => loc1 = loc2\n           | _ => False\n        end\n    | JFIFieldEq obj fieldName val =>\n        let l1 := JFIValToLoc obj env this\n        in let l2 := JFIValToLoc val env this\n        in match (l1, l2) with\n          | (Some objLoc, Some valLoc) => JFIObjFieldEq objLoc fieldName valLoc h\n          | _ => False\n        end\n    | JFISep t1 t2 => exists (h1 h2 : Heap), (* TODO free vars in t_n map to h_n *)\n        (HeapConsistent h1 /\\ HeapConsistent h2) /\\\n        (JFIHeapsUnion h1 h2 h /\\ JFIHeapsDisjoint h1 h2) /\\\n        (JFIHeapSatisfiesInEnv h1 t1 env this CC /\\ JFIHeapSatisfiesInEnv h2 t2 env this CC)\n    | JFIWand t1 t2 => forall h',\n        HeapConsistent h' ->\n        JFIHeapsDisjoint h h' ->\n        JFIHeapSatisfiesInEnv h' t1 env this CC ->\n        (exists h_h', JFIHeapsUnion h h' h_h' /\\ JFIHeapSatisfiesInEnv h_h' t2 env this CC) \n  end.\n\nFixpoint JFIHeapSatisfiesOuterInEnv (h : Heap) (t : JFIOuterTerm) (env : JFITermEnv) (this : nat) (CC : JFProgram) : Prop :=\n  match t with\n  | JFIOuterAnd t1 t2 => JFIHeapSatisfiesOuterInEnv h t1 env this CC /\\ JFIHeapSatisfiesOuterInEnv h t2 env this CC\n  | JFIOuterOr t1 t2 => JFIHeapSatisfiesOuterInEnv h t1 env this CC \\/ JFIHeapSatisfiesOuterInEnv h t2 env this CC\n  | JFIExists class name term => exists l : Loc,\n      let env1 := StrMap.add name l env\n      in JFILocOfType l h class /\\ JFIHeapSatisfiesOuterInEnv h term env1 this CC\n  | JFIInner t => JFIHeapSatisfiesInEnv h t env this CC\n  end.\n\nDefinition JFIGammaMatchEnv (h : Heap) (gamma : JFITypeEnv) (env : JFITermEnv) :=\n  forall var_name,\n    (StrMap.In var_name gamma <-> StrMap.In var_name env) /\\\n    (forall var_loc var_type,\n      (StrMap.MapsTo var_name var_type gamma) ->\n      (StrMap.MapsTo var_name var_loc env) ->\n       JFILocOfType var_loc h var_type).\n\nDefinition JFIHeapSatisfies (h : Heap) (t : JFITerm) (gamma : JFITypeEnv) (CC : JFProgram) : Prop :=\n  forall env this, JFIGammaMatchEnv h gamma env -> JFIHeapSatisfiesInEnv h t env this CC.\n\n(* Persistence *)\n\nFixpoint JFITermPersistent (t : JFITerm) : Prop :=\n  match t with\n  | JFITrue => True\n  | JFIFalse => True\n  | JFIAnd t1 t2 => JFITermPersistent t1 /\\ JFITermPersistent t2\n  | JFIOr t1 t2 => JFITermPersistent t1 /\\ JFITermPersistent t2\n  | JFIImplies t1 t2 => JFITermPersistent t1 /\\ JFITermPersistent t2\n  | JFIHoare t1 e ex valueName t2 => JFITermPersistent t1 /\\ JFITermPersistent t2\n  | JFIEq val1 val2 => True\n  | JFIFieldEq obj fieldName val => False\n  | JFISep t1 t2 => False\n  | JFIWand t1 t2 => False\n  end.\n\nFixpoint JFIOuterTermPersistent (t : JFIOuterTerm) : Prop :=\n  match t with\n  | JFIOuterAnd t1 t2 => JFIOuterTermPersistent t1 /\\ JFIOuterTermPersistent t2\n  | JFIOuterOr t1 t2 => JFIOuterTermPersistent t1 /\\ JFIOuterTermPersistent t2\n  | JFIExists class name term => JFIOuterTermPersistent term\n  | JFIInner t => JFITermPersistent t\n  end.\n\n(* Program structure for proofs *)\n\nInductive JFIInvariantType : Type :=\n| JFIInvariant (cn : string) (mn : string) (precondition : JFITerm) (ex : JFEvMode) (var : string) (postcondition : JFITerm).\n\nInductive JFIDeclsType : Type :=\n| JFIDecls (prog : JFProgram) (invariants : list JFIInvariantType) (class : JFClassDeclaration) (method : JFMethodDeclaration).\n\nDefinition JFIDeclsProg (decls : JFIDeclsType) : JFProgram :=\n  match decls with JFIDecls prog _ _ _ => prog end.\nDefinition JFIDeclsInvariants (decls : JFIDeclsType) : list JFIInvariantType :=\n  match decls with JFIDecls _ invariants _ _ => invariants end.\nDefinition JFIDeclsCDecl (decls : JFIDeclsType) : JFClassDeclaration :=\n  match decls with JFIDecls _ _ class _ => class end.\nDefinition JFIDeclsMD (decls : JFIDeclsType) : JFMethodDeclaration :=\n  match decls with JFIDecls _ _ _ method => method end.\n\n(* Types *)\n\nDefinition JFITypes : JFIDeclsType -> JFExEnv -> JFEnv -> JFExpr -> JFCId -> Prop :=\n  fun decls exEnv env expr cid =>\n    types (JFIDeclsProg decls) (JFIDeclsCDecl decls) (JFIDeclsMD decls) exEnv env expr (cid, JFrwr).\n\nDefinition JFIValType (decls : JFIDeclsType) (gamma : JFITypeEnv) (ref : JFIVal) : option JFClassName :=\n  match ref with\n  | JFIVar v => StrMap.find v gamma\n  | JFIThis => Some (name_of_cd (JFIDeclsCDecl decls))\n  | JFINull => None\n  end.\n\n(* TODO do wywalenia *)\nDefinition JFIGammaAdd (x : string) (type : JFClassName) (gamma : JFITypeEnv) : JFITypeEnv :=\n  StrMap.add x type gamma.\n\nDefinition JFIGammaAddNew (x : string) (type : JFClassName) (gamma : JFITypeEnv) : option JFITypeEnv :=\n  if StrMap.mem x gamma then None else Some (StrMap.add x type gamma).\n\nDefinition JFIEnvAddNew (x : string) (l : Loc) (env : JFITermEnv) : option JFITermEnv :=\n  if StrMap.mem x env then None else Some (StrMap.add x l env).\n\nDefinition JFIVarFreshInVal (x : string) (v : JFIVal) :=\n  match v with\n  | JFIVar y => x <> y\n  | _ => True\n  end.\n\nFixpoint JFIVarFreshInExpr (x : string) (e : JFExpr) := (* TODO pewnie wywalic *)\n  match e with\n    | JFNew mu C vs => True\n    | JFLet C x e1 e2 => True\n    | JFIf v1 v2 e1 e2 => True\n    | JFInvoke v1 m vs => True\n    | JFAssign (v1,fld) v2 => True\n    | JFVal1 v1 => True\n    | JFVal2 (v1, fld) => True\n    | JFThrow v1 => True\n    | JFTry e1 mu C x e2 => True\n  end.\n\nFixpoint JFIVarFreshInTerm (x : string) (t : JFITerm) :=\n  match t with\n  | JFITrue => True\n  | JFIFalse => True\n  | JFIAnd t1 t2 => JFIVarFreshInTerm x t1 /\\ JFIVarFreshInTerm x t2\n  | JFIOr t1 t2 => JFIVarFreshInTerm x t1 /\\ JFIVarFreshInTerm x t2\n  | JFIImplies t1 t2 => JFIVarFreshInTerm x t1 /\\ JFIVarFreshInTerm x t2\n  | JFIHoare t1 e ex name t2 => (* TODO maybe allow x = name *)\n      if String.eqb name x then False else\n        (JFIVarFreshInTerm x t1 /\\ JFIVarFreshInTerm x t2 /\\ JFIVarFreshInExpr x e)\n  | JFIEq val1 val2 => JFIVarFreshInVal x val1 /\\ JFIVarFreshInVal x val2\n  | JFIFieldEq obj fieldName val => JFIVarFreshInVal x obj /\\ JFIVarFreshInVal x val\n  | JFISep t1 t2 => JFIVarFreshInTerm x t1 /\\ JFIVarFreshInTerm x t2\n  | JFIWand t1 t2 => JFIVarFreshInTerm x t1 /\\ JFIVarFreshInTerm x t2\n  end.\n\nFixpoint JFIVarFreshInOuterTerm (x : string) (t : JFIOuterTerm) :=\n  match t with\n  | JFIOuterAnd t1 t2 => JFIVarFreshInOuterTerm x t1 /\\ JFIVarFreshInOuterTerm x t2\n  | JFIOuterOr t1 t2 => JFIVarFreshInOuterTerm x t1 /\\ JFIVarFreshInOuterTerm x t2\n  | JFIExists class name term => (* TODO maybe allow x = name *)\n      if String.eqb name x then False else JFIVarFreshInOuterTerm x term\n  | JFIInner t => JFIVarFreshInTerm x t\n  end.\n\nDefinition JFIValFreshInTerm (v : JFIVal) (t : JFITerm) :=\n  match v with\n  | JFIVar x => JFIVarFreshInTerm x t\n  | JFIThis => True\n  | JFINull => True\n  end.\n\nInductive JFIProves : JFIDeclsType -> JFITypeEnv -> JFITerm -> JFITerm -> Prop :=\n\n(* Rules for intuitionistic logic with equality *) \n\n| JFIAsmRule :\n    forall decls gamma p,\n      (FreeVarsInTermAreInGamma p gamma) ->\n      (*-----------------*)\n      JFIProves decls gamma p p\n\n| JFITransRule :\n    forall q decls gamma p r,\n      (JFIProves decls gamma p q) ->\n      (JFIProves decls gamma q r) ->\n      (*----------------*)\n      JFIProves decls gamma p r\n\n| JFIEqReflRule :\n    forall decls gamma p v,\n      (FreeVarsInTermAreInGamma p gamma) ->\n      (FreeVarsInValAreInGamma v gamma) ->\n      (*----------------------------------*)\n      JFIProves decls gamma p (JFIEq v v)\n\n| JFIEqSymRule :\n    forall decls gamma v1 v2 p,\n      (JFIProves decls gamma p (JFIEq v1 v2)) ->\n      (*-----------------------------------*)\n      JFIProves decls gamma p (JFIEq v2 v1)\n\n| JFIFalseElimRule :\n    forall decls gamma p q,\n      (FreeVarsInTermAreInGamma q gamma) ->\n      (JFIProves decls gamma p JFIFalse) ->\n      (*-----------------*)\n      JFIProves decls gamma p q\n\n| JFITrueIntroRule :\n    forall decls gamma p,\n      (FreeVarsInTermAreInGamma p gamma) ->\n      (*----------------------*)\n      JFIProves decls gamma p JFITrue\n\n| JFIAndIntroRule :\n    forall decls gamma p q r,\n      (JFIProves decls gamma r p) ->\n      (JFIProves decls gamma r q) ->\n      (*----------------------------*)\n      JFIProves decls gamma r (JFIAnd p q)\n\n| JFIAndElimLRule :\n    forall q decls gamma p r,\n      (JFIProves decls gamma r (JFIAnd p q)) ->\n      (*----------------*)\n      JFIProves decls gamma r p\n\n| JFIAndElimRRule :\n    forall p decls gamma q r,\n      (JFIProves decls gamma r (JFIAnd p q)) ->\n      (*-----------------*)\n      JFIProves decls gamma r q\n\n| JFIOrIntroLRule :\n    forall decls gamma p q r,\n      (FreeVarsInTermAreInGamma q gamma) ->\n      (JFIProves decls gamma r p) ->\n      (*--------------------------*)\n      JFIProves decls gamma r (JFIOr p q)\n\n| JFIOrIntroRRule :\n    forall decls gamma p q r,\n      (FreeVarsInTermAreInGamma p gamma) ->\n      (JFIProves decls gamma r q) ->\n      (*--------------------------*)\n      JFIProves decls gamma r (JFIOr p q)\n\n| JFIOrElimRule :\n    forall decls gamma p q r s,\n      (JFIProves decls gamma s (JFIOr p q)) ->\n      (JFIProves decls gamma (JFIAnd s p) r) ->\n      (JFIProves decls gamma (JFIAnd s q) r) ->\n      (*-----------------*)\n      JFIProves decls gamma s r\n\n| JFIImpliesIntroRule :\n    forall decls gamma p q r,\n      (JFIProves decls gamma (JFIAnd r p) q) ->\n      (*--------------------------------------*)\n      JFIProves decls gamma r (JFIImplies p q)\n\n| JFIImpliesElimRule:\n    forall p decls gamma q r,\n      (JFIProves decls gamma r (JFIImplies p q)) ->\n      (JFIProves decls gamma r p) ->\n      (*-----------------------*)\n      JFIProves decls gamma r q\n\n(* Rules for separation logic *)\n\n| JFIWeakRule :\n    forall decls gamma p1 p2,\n      (FreeVarsInTermAreInGamma p1 gamma) ->\n      (FreeVarsInTermAreInGamma p2 gamma) ->\n      (*------------------------------------*)\n      JFIProves decls gamma (JFISep p1 p2) p1\n\n| JFISepAssoc1Rule :\n    forall decls gamma p1 p2 p3,\n      (FreeVarsInTermAreInGamma p1 gamma) ->\n      (FreeVarsInTermAreInGamma p2 gamma) ->\n      (FreeVarsInTermAreInGamma p3 gamma) ->\n      (*------------------------------------------------------------------*)\n      JFIProves decls gamma (JFISep p1 (JFISep p2 p3)) (JFISep (JFISep p1 p2) p3)\n\n| JFISepAssoc2Rule :\n    forall decls gamma p1 p2 p3,\n      (FreeVarsInTermAreInGamma p1 gamma) ->\n      (FreeVarsInTermAreInGamma p2 gamma) ->\n      (FreeVarsInTermAreInGamma p3 gamma) ->\n      (*------------------------------------------------------------------*)\n      JFIProves decls gamma (JFISep (JFISep p1 p2) p3) (JFISep p1 (JFISep p2 p3))\n\n| JFISepSymRule :\n    forall decls gamma p1 p2,\n      (FreeVarsInTermAreInGamma p1 gamma) ->\n      (FreeVarsInTermAreInGamma p2 gamma) ->\n      (*-----------------------------------------*)\n      JFIProves decls gamma (JFISep p1 p2) (JFISep p2 p1)\n\n| JFISepIntroRule :\n    forall decls gamma p1 p2 q1 q2,\n      (JFIProves decls gamma p1 q1) ->\n      (JFIProves decls gamma p2 q2) ->\n      (*------------------------------------------*)\n      JFIProves decls gamma (JFISep p1 p2) (JFISep q1 q2)\n\n| JFISepIntroPersistentRule :\n    forall decls gamma p q,\n      (FreeVarsInTermAreInGamma p gamma) ->\n      (FreeVarsInTermAreInGamma q gamma) ->\n      (JFITermPersistent p) ->\n      (*---------------------------------------------*)\n      JFIProves decls gamma (JFIAnd p q) (JFISep p q)\n\n| JFIWandIntroRule :\n    forall decls gamma p q r,\n      (JFIProves decls gamma (JFISep r p) q) ->\n      (*----------------------------*)\n      JFIProves decls gamma r (JFIWand p q)\n\n| JFIWandElimRule :\n    forall decls gamma p q r1 r2,\n      (JFIProves decls gamma r1 (JFIWand p q)) ->\n      (JFIProves decls gamma r2 p) ->\n      (*------------------------------*)\n      JFIProves decls gamma (JFISep r1 r2) q\n\n(* Structural rules for Hoare triples *)\n\n| JFIHTFrameRule :\n    forall decls gamma p q r s e ex v,\n      (JFITermPersistent s) ->\n      (JFIVarFreshInTerm v r) ->\n      (JFIProves decls gamma s (JFIHoare p e ex v q)) ->\n      (*-------------------------------------------------------*)\n      JFIProves decls gamma s (JFIHoare (JFISep p r) e ex v (JFISep q r))\n\n| JFIHTRetRule :\n    forall decls gamma s v w w_expr,\n      FreeVarsInValAreInGamma w gamma ->\n      w_expr = JFIValToJFVal w ->\n      (*--------------------------------------------------------------------------------*)\n      JFIProves decls gamma s (JFIHoare JFITrue (JFVal1 w_expr) None v (JFIEq (JFIVar v) w))\n\n| JFIHTCsqRule:\n    forall p' q' cn decls gamma s p q ex v e,\n      (JFITermPersistent s) ->\n      (JFIVarFreshInTerm v s) ->\n      (JFIProves decls gamma s (JFIImplies p p')) ->\n      (JFIProves decls gamma s (JFIHoare p' e ex v q')) ->\n      (JFIProves decls (JFIGammaAdd v cn gamma) s (JFIImplies q' q)) ->\n      (*------------------------------*)\n      JFIProves decls gamma s (JFIHoare p e ex v q)\n\n| JFIHTDisjIntroRule :\n    forall decls gamma s p q r e ex v,\n      (JFIProves decls gamma s (JFIHoare p e ex v r)) ->\n      (JFIProves decls gamma s (JFIHoare q e ex v r)) ->\n      (*--------------------------------------------------*)\n      JFIProves decls gamma s (JFIHoare (JFIOr p q) e ex v r)\n\n(* TODO remove both and replace with persistent *)\n\n| JFIHTEqRule1 :\n    forall decls gamma s v1 v2 p e ex v q,\n      (JFIProves decls gamma (JFIAnd s (JFIEq v1 v2)) (JFIHoare p e ex v q)) ->\n      (*----------------------------------------------------------------*)\n      JFIProves decls gamma s (JFIHoare (JFIAnd p (JFIEq v1 v2)) e ex v q)\n\n| JFIHTEqRule2 :\n    forall decls gamma s v1 v2 p e ex v q,\n      (JFIProves decls gamma s (JFIHoare (JFIAnd p (JFIEq v1 v2)) e ex v q)) ->\n      (*----------------------------------------------------------------*)\n      JFIProves decls gamma (JFIAnd s (JFIEq v1 v2)) (JFIHoare p e ex v q)\n\n(* Rules for basic constructs of Jafun *)\n\n| JFIHTNewNotNullRule :\n    forall decls gamma s p mu cn vs v,\n      JFIProves decls gamma s (JFIHoare p (JFNew mu cn vs) None v (JFIImplies (JFIEq (JFIVar v) JFINull) JFIFalse))\n\n| JFIHTNewFieldRule :\n    forall decls gamma s p mu cn vs v objflds n field value,\n      (FreeVarsInValAreInGamma value gamma) ->\n      (flds (JFIDeclsProg decls) (JFClass cn) = Some objflds) ->\n      (nth_error objflds n = Some field) ->\n      (nth_error vs n = Some (JFIValToJFVal value)) ->\n      (value <> (JFIVar v)) ->\n      (*----------------------------------------------------------------*)\n      JFIProves decls gamma s (JFIHoare p (JFNew mu cn vs) None v (JFIFieldEq (JFIVar v) field value))\n\n| JFIHTLetRule :\n    forall q decls gamma p r s e1 e2 x ex u class,\n      (JFITermPersistent s) ->\n      (JFIVarFreshInTerm x s) ->\n      (JFIVarFreshInTerm x r) ->\n      (JFIProves decls gamma s (JFIHoare p e1 None x q)) ->\n      (JFIProves decls (JFIGammaAdd x class gamma) s (JFIHoare q e2 ex u r)) ->\n      (*------------------------------------------------------------*)\n      JFIProves decls gamma s (JFIHoare p (JFLet class x e1 e2) ex u r )\n\n| JFIHTLetExRule :\n    forall q decls gamma p s e1 e2 x ex u class,\n      (JFIProves decls gamma s (JFIHoare p e1 (Some ex) u q)) ->\n      (*------------------------------------------------------------*)\n      JFIProves decls gamma s (JFIHoare p (JFLet class x e1 e2) (Some ex) u q )\n\n| JFIHTFieldSetRule :\n    forall decls gamma s x x_expr field u v v_expr,\n      (FreeVarsInValAreInGamma x gamma) ->\n      (FreeVarsInValAreInGamma v gamma) ->\n      (x_expr = JFIValToJFVal x) ->\n      (v_expr = JFIValToJFVal v) ->\n      (x <> (JFIVar u)) ->\n      (v <> (JFIVar u)) ->\n      (*--------------------------------------------------*)\n      JFIProves decls gamma s\n        (JFIHoare\n          (JFIImplies (JFIEq x JFINull) JFIFalse)\n          (JFAssign (x_expr, field) v_expr)\n           None u (JFIFieldEq x field v))\n\n| JFIHTNullFieldSetRule :\n    forall decls gamma s x x_expr field v loc,\n      (x_expr = JFIValToJFVal x) ->\n      (*--------------------------------------------------*)\n      JFIProves decls gamma s\n        (JFIHoare (JFIEq x JFINull)\n          (JFAssign (x_expr, field) (JFVLoc loc))\n           NPE_mode v JFITrue)\n\n| JFIHTFieldGetRule :\n    forall decls gamma s x x_expr field u v,\n      (x_expr = JFIValToJFVal x) ->\n      (x <> (JFIVar u)) ->\n      (v <> (JFIVar u)) ->\n      (*--------------------------------------------------*)\n      JFIProves decls gamma s\n        (JFIHoare\n          (JFIFieldEq x field v)\n          (JFVal2 (x_expr, field))\n           None u (JFIEq (JFIVar u) v))\n\n| JFIHTNullFieldGetRule :\n    forall decls gamma s x x_expr field v,\n      (x_expr = JFIValToJFVal x) ->\n      (*--------------------------------------------------*)\n      JFIProves decls gamma s\n        (JFIHoare (JFIEq x JFINull)\n          (JFVal2 (x_expr, field))\n           NPE_mode v JFITrue)\n\n| JFIHTIfRule :\n    forall decls gamma p v1 v1_expr v2 v2_expr e1 e2 ex u q s,\n      (FreeVarsInValAreInGamma v1 gamma) ->\n      (FreeVarsInValAreInGamma v2 gamma) ->\n      (v1_expr = JFIValToJFVal v1) -> (v2_expr = JFIValToJFVal v2) ->\n      (JFIProves decls gamma s (JFIHoare (JFIAnd p (JFIEq v1 v2)) e1 ex u q)) ->\n      (JFIProves decls gamma s (JFIHoare (JFIAnd p (JFIImplies (JFIEq v1 v2) JFIFalse)) e2 ex u q)) ->\n      (*---------------------------------------------------------*)\n      JFIProves decls gamma s (JFIHoare p (JFIf v1_expr v2_expr e1 e2) ex u q)\n\n| JFIHTInvokeRetRule :\n    forall cn method rettypeCN ex w decls gamma s p q u v v_expr vs vs_expr mn,\n      (FreeVarsInValAreInGamma v gamma) ->\n      (v_expr = JFIValToJFVal v) -> (vs_expr = JFIValsToJFVals vs) ->\n      (JFIValType decls gamma v = Some cn) ->\n      (methodLookup (JFIDeclsProg decls) cn mn = Some method) ->\n      (fst (rettyp_of_md method) = JFClass rettypeCN) ->\n      (In (JFIInvariant cn mn p ex w q) (JFIDeclsInvariants decls)) ->\n      (JFIProves decls gamma (JFIAnd s p) (JFIImplies (JFIEq v JFINull) JFIFalse)) ->\n      (*--------------------------------------------------*)\n      JFIProves decls gamma s (JFIHoare p (JFInvoke v_expr mn vs_expr) ex u q)\n\n| JFIHTNullInvokeRule :\n    forall decls gamma s x x_expr mn vs v,\n      (FreeVarsInValAreInGamma x gamma) ->\n      (x_expr = JFIValToJFVal x) ->\n      (*--------------------------------------------------*)\n      JFIProves decls gamma s\n        (JFIHoare (JFIEq x JFINull)\n          (JFInvoke x_expr mn vs)\n           NPE_mode v JFITrue)\n\n| JFIHTThrowRule :\n    forall decls gamma s cn x x_expr v,\n      (FreeVarsInValAreInGamma x gamma) ->\n      (x_expr = JFIValToJFVal x) ->\n      (JFIValType decls gamma x = Some cn) ->\n      (*--------------------------------------------------*)\n      JFIProves decls gamma s\n        (JFIHoare (JFIImplies (JFIEq x JFINull) JFIFalse)\n           (JFThrow x_expr)\n           (Some cn) v (JFIEq (JFIVar v) x))\n\n| JFIHTNullThrowRule :\n    forall decls gamma s x x_expr v,\n      (FreeVarsInValAreInGamma x gamma) ->\n      (x_expr = JFIValToJFVal x) ->\n      (*--------------------------------------------------*)\n      JFIProves decls gamma s\n        (JFIHoare (JFIEq x JFINull)\n           (JFThrow x_expr)\n            NPE_mode v JFITrue)\n\n| JFIHTCatchNormalRule :\n    forall decls gamma s p e1 mu x e2 u q ex,\n      (JFIProves decls gamma s (JFIHoare p e1 None u q)) ->\n      (*------------------------------------------------------------*)\n      JFIProves decls gamma s (JFIHoare p (JFTry e1 mu ex x e2) None u q )\n\n| JFIHTCatchExRule :\n    forall decls gamma s p r e1 mu x e2 u q ex ex' ex'',\n      (JFITermPersistent s) ->\n      (JFIVarFreshInTerm x s) ->\n      (JFIVarFreshInTerm x r) ->\n      (JFIProves decls gamma s (JFIHoare p e1 (Some ex') x q)) ->\n      (JFIProves decls (JFIGammaAdd x ex gamma) s (JFIHoare q e2 ex'' u r)) ->\n      (Is_true (subtype_bool (JFIDeclsProg decls) (JFClass ex') (JFClass ex))) ->\n      (*------------------------------------------------------------*)\n      JFIProves decls gamma s (JFIHoare p (JFTry e1 mu ex x e2) ex'' u r )\n\n| JFIHTCatchPassExRule :\n    forall decls gamma s p e1 mu x e2 u q ex ex',\n      (JFIProves decls gamma s (JFIHoare p e1 (Some ex') u q)) ->\n       ~Is_true (subtype_bool (JFIDeclsProg decls) (JFClass ex') (JFClass ex)) ->\n      (*------------------------------------------------------------*)\n      JFIProves decls gamma s (JFIHoare p (JFTry e1 mu ex x e2) (Some ex') u q )\n.\n\nInductive JFIProvesOuter : JFIDeclsType -> JFITypeEnv -> JFIOuterTerm -> JFIOuterTerm -> Prop :=\n| JFIExistsIntroRule :\n    forall decls gamma p q x v type,\n      (JFIValType decls gamma v = Some type) ->\n      (JFIProvesOuter decls gamma q (JFIOuterTermSubstituteVal x v p)) ->\n      (*-----------------------------------*)\n      JFIProvesOuter decls gamma q (JFIExists type x p)\n\n| JFIExistsElimRule :\n    forall decls gamma p q r x type,\n      (JFIVarFreshInOuterTerm x r) ->\n      (JFIVarFreshInOuterTerm x q) ->\n      (JFIProvesOuter decls gamma r (JFIExists type x p)) ->\n      (JFIProvesOuter decls (JFIGammaAdd x type gamma) (JFIOuterAnd r p) q) ->\n      (*----------------*)\n      JFIProvesOuter decls gamma r q\n\n| JFIOuterInnerRule :\n    forall decls gamma p q,\n      (JFIProves decls gamma p q) ->\n      (JFIProvesOuter decls gamma (JFIInner p) (JFIInner q))\n\n| JFIOuterAndIntroRule :\n    forall decls gamma p q r,\n      (JFIProvesOuter decls gamma r p) ->\n      (JFIProvesOuter decls gamma r q) ->\n      (*----------------------------*)\n      JFIProvesOuter decls gamma r (JFIOuterAnd p q)\n\n| JFIOuterAndElimLRule :\n    forall q decls gamma p r,\n      (JFIProvesOuter decls gamma r (JFIOuterAnd p q)) ->\n      (*----------------*)\n      JFIProvesOuter decls gamma r p\n\n| JFIOuterAndElimRRule :\n    forall p decls gamma q r,\n      (JFIProvesOuter decls gamma r (JFIOuterAnd p q)) ->\n      (*-----------------*)\n      JFIProvesOuter decls gamma r q\n\n| JFIOuterOrIntroLRule :\n    forall decls gamma p q r,\n      (JFIProvesOuter decls gamma r p) ->\n      (*--------------------------*)\n      JFIProvesOuter decls gamma r (JFIOuterOr p q)\n\n| JFIOuterOrIntroRRule :\n    forall decls gamma p q r,\n      (JFIProvesOuter decls gamma r q) ->\n      (*--------------------------*)\n      JFIProvesOuter decls gamma r (JFIOuterOr p q)\n\n| JFIOuterOrElimRule :\n    forall decls gamma p q r s,\n      (JFIProvesOuter decls gamma s (JFIOuterOr p q)) ->\n      (JFIProvesOuter decls gamma (JFIOuterAnd s p) r) ->\n      (JFIProvesOuter decls gamma (JFIOuterAnd s q) r) ->\n      (*-----------------*)\n      JFIProvesOuter decls gamma s r\n.\n", "meta": {"author": "jbujak", "repo": "jafun", "sha": "4b9b2d21ba06e6a98c885c8bf2cc202f52595058", "save_path": "github-repos/coq/jbujak-jafun", "path": "github-repos/coq/jbujak-jafun/jafun-4b9b2d21ba06e6a98c885c8bf2cc202f52595058/JaIris.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2429508146294614}}
{"text": "(** * Undecidability of the subtyping problem of System FsubD *)\n\nRequire Import Undecidability.Synthetic.Undecidability.\n\nRequire Import FsubF_undec FsubD.\nRequire Import Reductions.FsubF_to_FsubD.\n\nLemma FsubD_SUBTYPE_undec : undecidable FsubD_SUBTYPE.\nProof.\n  apply (undecidability_from_reducibility FsubF_SUBTYPE_undec).\n  exact FsubF_to_FsubD.reduction.\nQed.", "meta": {"author": "uds-psl", "repo": "coq-undecidability-subtyping", "sha": "85c1e65228009bf57c9e2d5846e611a53ca06d34", "save_path": "github-repos/coq/uds-psl-coq-undecidability-subtyping", "path": "github-repos/coq/uds-psl-coq-undecidability-subtyping/coq-undecidability-subtyping-85c1e65228009bf57c9e2d5846e611a53ca06d34/FsubD_undec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24295080894803311}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.CorrectnessBaseTypes.\nRequire Import Fiat.Common.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Valid.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ValidReflective.\nRequire Import Fiat.Parsers.StringLike.Core.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Fiat.Parsers.MinimalParseOfParse.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nSection recursive_descent_parser.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char}\n          {G : pregrammar' Char}.\n\n  Context (Hvalid : is_true (grammar_rvalid G)).\n\n  Let predata := @rdp_list_predata _ G.\n  Local Existing Instance predata.\n\n  Let rdata' : @parser_removal_dataT' _ G predata := rdp_list_rdata'.\n  Local Existing Instance rdata'.\n\n  Context {splitdata : @split_dataT Char _ _}.\n  Let data : boolean_parser_dataT :=\n    {| split_data := splitdata |}.\n  Context {splitdata_correct : @boolean_parser_completeness_dataT' _ _ _ G data}.\n\n  Local Instance optsplitdata : @split_dataT Char _ _\n    := { split_string_for_production p_idx str offset len\n         := match to_production p_idx with\n              | nil => 0::nil\n              | _::nil => len::nil\n              | it::_\n                => match it with\n                     | Terminal _ => 1::nil\n                     | _ => @split_string_for_production _ _ _ splitdata p_idx str offset len\n                   end\n            end }.\n  Let optdata : boolean_parser_dataT :=\n    {| split_data := optsplitdata |}.\n\n  Local Arguments minus !_ !_.\n  Local Arguments min !_ !_.\n\n  Local Instance optsplitdata_correct : @boolean_parser_completeness_dataT' _ _ _ G optdata\n    := { split_string_for_production_complete := _ }.\n  Proof.\n    pose proof (@split_string_for_production_complete _ _ _ _ _ splitdata_correct) as H.\n    repeat (let x := fresh in intro x; specialize (H x)).\n    revert H.\n    apply ForallT_impl, ForallT_all; intro.\n    apply Forall_tails_impl, Forall_tails_all; intros [|??];\n    [ exact (fun x => x) | ].\n    intro H;\n      repeat (let x := fresh in intro x; specialize (H x));\n      revert H.\n    simpl in *.\n    repeat match goal with\n           | _ => assumption\n           | [ |- ?R ?x ?x ] => reflexivity\n           | [ H : S _ = 0 |- _ ] => clear -H; congruence\n           | [ H : 0 = S _ |- _ ] => clear -H; congruence\n           | [ H : nil = _::_ |- _ ] => clear -H; congruence\n           | [ H : _::_ = nil |- _ ] => clear -H; congruence\n           | [ H : _::_ = _::_ |- _ ] => inversion H; clear H\n           | _ => progress subst\n           | [ |- ?T -> ?T ] => exact (fun x => x)\n           | [ |- context[match ?e with Terminal _ => _ | _ => _ end] ]\n             => destruct e eqn:?\n           | [ |- context[match ?e with nil => _ | _ => _ end] ]\n             => destruct e eqn:?\n           | _ => progress simpl\n           | _ => rewrite Min.min_0_r\n           | _ => intro\n           | [ |- context[0 = min _ _] ] => exists 0\n           | [ |- ?x = ?x ] => reflexivity\n           | [ |- _ \\/ False ] => left\n           | _ => progress destruct_head @sigT\n           | _ => progress destruct_head @prod\n           | [ H : MinimalParse.minimal_parse_of_item _ _ (take _ (substring _ 0 _)) (Terminal _) |- _ ]\n             => exfalso; inversion H; clear H\n           | [ H : is_true (take _ (substring _ 0 _) ~= [_]) |- _ ]\n             => apply length_singleton in H\n           | [ H : length (take _ (substring _ 0 _)) = S _ |- _ ]\n             => rewrite take_length, substring_length, <- Nat.sub_min_distr_r, Nat.add_sub, !Min.min_0_r in H\n           | [ H : MinimalParse.minimal_parse_of_production _ _ _ nil |- _ ] => inversion H; clear H\n           | [ |- MinimalParse.minimal_parse_of_production _ _ _ nil ] => constructor\n           | [ H : MinimalParse.minimal_parse_of_item _ _ _ (Terminal _) |- _ ]\n             => inversion H; clear H\n           | [ |- MinimalParse.minimal_parse_of_item _ _ _ (Terminal _) ]\n             => econstructor; [ eassumption | ]\n           | [ H : length (drop _ (substring _ _ _)) = 0 |- _ ] => rewrite drop_length, substring_length in H\n           | [ |- length (drop _ (substring _ _ _)) = 0 ] => rewrite drop_length, substring_length\n           | [ H : ?x = 0 \\/ ?T |- _ ]\n             => let H' := fresh in\n                destruct (Compare_dec.zerop x) as [H'|H'];\n                  [ clear H\n                  | assert T by (clear -H H'; destruct H; try assumption; try omega); clear H ]\n           | [ |- (_ * _)%type ] => split\n           | [ |- { _ : nat & _ } ] => eexists; repeat split; [ left; reflexivity | .. ]\n           | [ H : ?x + ?y <= _ |- context[(?y + ?x)%nat] ]\n             => not constr_eq x y; rewrite (Plus.plus_comm y x)\n           | [ H : ?x + ?y <= _, H' : context[(?y + ?x)%nat] |- _ ]\n             => not constr_eq x y; rewrite (Plus.plus_comm y x) in H'\n           | [ H : context[(?x + 1)%nat] |- _ ] => rewrite (Plus.plus_comm x 1) in H; simpl plus in H\n           | [ H : context[min ?x ?y], H' : ?y <= ?x |- _ ] => rewrite (Min.min_r x y) in H by assumption\n           | [ H' : ?y <= ?x |- context[min ?x ?y] ] => rewrite (Min.min_r x y) by assumption\n           | [ H : _ - _ = 0 |- _ ] => apply Nat.sub_0_le in H\n           | [ |- _ - _ = 0 ] => apply Nat.sub_0_le\n           | [ H : _ |- _ ] => progress rewrite ?Nat.add_sub, ?Minus.minus_plus in H\n           | _ => progress rewrite ?Nat.add_sub, ?Minus.minus_plus, ?Minus.minus_diag, ?Min.min_idempotent\n           | [ |- is_true (is_char (take ?x (take ?x _)) _) ]\n             => rewrite take_take\n           | [ H : is_true (is_char (take ?n ?str) ?ch) |- is_true (is_char ?str ?ch) ]\n             => rewrite (take_long str)\n               in H\n               by (rewrite substring_length, Plus.plus_comm, Min.min_r by assumption; omega)\n           | [ H : is_true (is_char (take ?n ?str) ?ch) |- is_true (is_char (take 1 ?str) ?ch) ]\n             => apply take_n_1_singleton in H\n           | [ |- MinimalParse.minimal_parse_of_production _ _ _ (_::_) ]\n             => eapply @MinimalParseOfParse.expand_minimal_parse_of_production_beq;\n               [ try assumption.. | eassumption ]\n           | [ |- MinimalParse.minimal_parse_of_item _ _ (take 0 _) _ ]\n             => eapply @MinimalParseOfParse.expand_minimal_parse_of_item_beq;\n               [ try assumption.. | eassumption ]\n           | [ |- MinimalParse.minimal_parse_of_item _ _ _ _ ]\n             => eapply @MinimalParseOfParse.expand_minimal_parse_of_item_beq;\n               [ try assumption.. | eassumption ]\n           | [ H : is_true (is_char (take ?x _) _) |- ?R (drop ?x _) (drop 1 _) ]\n             => apply length_singleton in H; rewrite take_length, substring_length in H\n           | [ H : min ?x ?y = 1\n               |- ?R (drop ?x (substring _ ?y _)) (drop 1 (substring _ ?y _)) ]\n             => revert H; apply Min.min_case_strong; intros; subst;\n                try reflexivity;\n                apply bool_eq_empty\n           | [ |- context[S ?x - ?x] ]\n             => rewrite <- Nat.add_1_r, Minus.minus_plus\n           | [ |- context[take ?x (take 0 _)] ]\n             => rewrite take_take\n           | [ |- context[min _ ?x - ?x] ]\n             => rewrite <- Nat.sub_min_distr_r\n           | [ H : ?y <= ?x |- context[take ?x (substring ?z ?y ?str)] ]\n             => rewrite (take_long (substring z y str))\n               by (rewrite substring_length, Plus.plus_comm, Min.min_r by assumption; omega)\n           | [ |- context[take ?x (substring ?z ?x ?str)] ]\n             => rewrite (take_long (substring z x str))\n               by (rewrite substring_length, Plus.plus_comm, Min.min_r by assumption; omega)\n           end.\n  Qed.\nEnd recursive_descent_parser.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_eapply_example/src/Parsers/RecognizerPreOptimized.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.24295080894803306}}
{"text": "From Coq Require Import ssreflect.\nFrom stdpp Require Import strings gmap list.\nFrom melocoton Require Import named_props stdpp_extra.\nFrom melocoton.mlanguage Require Import mlanguage.\nFrom melocoton.language Require Import language weakestpre.\nFrom melocoton.mlanguage Require Import weakestpre.\nFrom melocoton.ml_lang Require Import lang lang_instantiation primitive_laws.\nFrom melocoton.c_interface Require Import defs notation.\nFrom melocoton.interop Require Import basics prims basics_resources state.\n\nGlobal Notation MLval := ML_lang.val.\nGlobal Notation Cval := C_intf.val.\n\nSection ChiZetaConstruction.\n\nDefinition lookup_reversed `{Countable A} {B} (m : gmap A B) (b : B) :=\n  { a | m !! a = Some b }.\n\nDefinition find_in_reverse `{Countable A} `{EqDecision B} (m : gmap A B) (b : B) :\n  sum (lookup_reversed m b) (lookup_reversed m b → False).\nProof.\n  pose (map_to_set (fun a b' => if decide (b' = b) then Some a else None) m : gset _) as Hset.\n  epose (filter (fun k => is_Some k) Hset) as Hset2.\n  destruct (elements Hset2) as [|[γ|] ?] eqn:Heq.\n  - right. intros (a & Ha).\n    apply elements_empty_inv in Heq. apply gset_leibniz in Heq.\n    eapply filter_empty_not_elem_of_L.\n    2: apply Heq. 1: apply _.\n    2: eapply elem_of_map_to_set.\n    2: exists a, b; split; done.\n    rewrite decide_True; done. Unshelve. all: apply _.\n  - left. exists γ.\n    assert (Some γ ∈ Hset2) as Hin.\n    1: eapply elem_of_elements; rewrite Heq; left.\n    eapply elem_of_filter in Hin. destruct Hin as [_ Hin].\n    eapply elem_of_map_to_set in Hin.\n    destruct Hin as (i & b' & H1 & H2).\n    destruct decide; congruence.\n  - exfalso. assert (None ∈ Hset2) as Hin.\n    + eapply elem_of_elements. rewrite Heq. left.\n    + apply elem_of_filter in Hin. destruct Hin as [[? Hc]?]. congruence.\nQed.\n\nLemma ensure_in_χ_pub χ ℓ :\n  lloc_map_inj χ →\n  ∃ χ' γ,\n    lloc_map_mono χ χ' ∧\n    χ' !! γ = Some (LlocPublic ℓ) ∧\n    (∀ γ' r, γ' ≠ γ → χ' !! γ' = r → χ !! γ' = r).\nProof.\n  intros Hinj.\n  destruct (find_in_reverse χ (LlocPublic ℓ)) as [[γ Hgam]|Hnot].\n  1: exists χ, γ; done.\n  eexists (<[fresh (dom χ) := LlocPublic ℓ]> χ), _.\n  erewrite lookup_insert; split_and!. 2: done.\n  2: intros γ' r Hne H1; by rewrite lookup_insert_ne in H1.\n  split.\n  1: eapply insert_subseteq, not_elem_of_dom, is_fresh.\n  intros γ1 γ2 ℓ' [[? ?]|[? ?]]%lookup_insert_Some [[? ?]|[? ?]]%lookup_insert_Some; subst.\n  1: done.\n  3: by eapply Hinj.\n  all: intros _; exfalso; apply Hnot; eexists; eauto.\nQed.\n\nLemma ensure_in_χ_foreign χ id :\n  lloc_map_inj χ →\n  ∃ χ' γ,\n    lloc_map_mono χ χ' ∧\n    χ' !! γ = Some (LlocForeign id) ∧\n    (∀ γ' r, γ' ≠ γ → χ' !! γ' = r → χ !! γ' = r).\nProof.\n  intros Hinj.\n  destruct (find_in_reverse χ (LlocForeign id)) as [[γ Hgam]|Hnot].\n  1: exists χ, γ; done.\n  eexists (<[fresh (dom χ) := LlocForeign id]> χ), _.\n  erewrite lookup_insert; split_and!. 2: done.\n  2: intros γ' r Hne H1; by rewrite lookup_insert_ne in H1.\n  split.\n  1: eapply insert_subseteq, not_elem_of_dom, is_fresh.\n  intros γ1 γ2 ℓ' [[? ?]|[? ?]]%lookup_insert_Some [[? ?]|[? ?]]%lookup_insert_Some; subst.\n  1: done.\n  3: by eapply Hinj.\n  all: intros _; exfalso; apply Hnot; eexists; eauto.\nQed.\n\nDefinition extended_to (χold : lloc_map) (ζ : lstore) (χnew : lloc_map) :=\n  lloc_map_mono χold χnew ∧ dom χold ## dom ζ ∧ is_private_blocks χnew ζ.\n\nLemma extended_to_inj χ1 ζ χ2 : extended_to χ1 ζ χ2 → lloc_map_inj χ2.\nProof.\n  intros (H&_); apply H.\nQed.\n\nLemma extended_to_dom_subset χ1 ζ χ2 : extended_to χ1 ζ χ2 → dom ζ ⊆ dom χ2.\nProof.\n  intros (H1&H2&H3).\n  eapply elem_of_subseteq. intros γ Hx; eapply elem_of_dom_2. by apply H3.\nQed.\n\nDefinition allocate_in_χ_priv_strong (exclusion : gset lloc) (χold : lloc_map) v : lloc_map_inj χold → exists χnew γ, extended_to χold {[γ := v]} χnew ∧ γ ∉ exclusion.\nProof.\n  intros Hinj.\n  pose (fresh (dom χold ∪ exclusion)) as γ.\n  pose (is_fresh (dom χold ∪ exclusion)) as Hγ.\n  eexists (<[γ := LlocPrivate]> χold), γ.\n  unfold extended_to; split_and!; first split.\n  - eapply insert_subseteq, not_elem_of_dom. intros HH; eapply Hγ, elem_of_union_l, HH.\n  - intros γ1 γ2 ℓ' [[? ?]|[? ?]]%lookup_insert_Some [[? ?]|[? ?]]%lookup_insert_Some; subst; try congruence.\n    by eapply Hinj.\n  - rewrite dom_singleton_L. eapply disjoint_singleton_r. intros HH; eapply Hγ, elem_of_union_l, HH.\n  - intros x. rewrite dom_singleton_L. intros ->%elem_of_singleton.\n    eapply lookup_insert.\n  - intros HH; eapply Hγ, elem_of_union_r, HH.\nQed.\n\nDefinition allocate_in_χ_priv (χold : lloc_map) v : lloc_map_inj χold → exists χnew γ, extended_to χold {[γ := v]} χnew.\nProof.\n  intros Hinj. destruct (allocate_in_χ_priv_strong ∅ χold v Hinj) as (χnew&γ&H&_).\n  by do 2 eexists.\nQed.\n\nLemma disjoint_weaken T `{Countable T} (A1 A2 B1 B2 : gset T) : A1 ## B1 → A2 ⊆ A1 → B2 ⊆ B1 → A2 ## B2.\nProof.\n  intros HD H1 H2.\n  apply elem_of_disjoint.\n  intros x HA HB.\n  edestruct (@elem_of_disjoint) as [HL _]; eapply HL.\n  - apply HD.\n  - eapply elem_of_weaken; first apply HA. done.\n  - eapply elem_of_weaken; first apply HB. done.\nQed.\n\nLemma extended_to_trans (χ1 χ2 χ3 : lloc_map) (ζ1 ζ2 : lstore) : \n  extended_to χ1 ζ1 χ2 →\n  extended_to χ2 ζ2 χ3 →\n  extended_to χ1 (ζ1 ∪ ζ2) χ3 /\\ ζ1 ##ₘ ζ2.\nProof.\n  intros (HA1 & HA2 & HA3) (HB1 & HB2 & HB3). unfold extended_to; split_and!.\n  - split; last apply HB1. etransitivity; first apply HA1; apply HB1.\n  - erewrite dom_union_L. eapply disjoint_union_r. split; first done.\n    eapply disjoint_weaken. 1: apply HB2. 2: done. apply subseteq_dom, HA1.\n  - intros γ. rewrite dom_union_L. intros [H|H]%elem_of_union; last by apply HB3.\n    eapply lookup_weaken; first by apply HA3.\n    apply HB1.\n  - eapply map_disjoint_dom. eapply disjoint_weaken. 1: apply HB2. 2: done.\n    eapply extended_to_dom_subset; done.\nQed.\n\nLemma extended_to_trans_2 (χ1 χ2 χ3 : lloc_map) (ζ1 ζ2 : lstore) : \n  extended_to χ1 ζ1 χ2 →\n  extended_to χ2 ζ2 χ3 →\n  extended_to χ1 (ζ2 ∪ ζ1) χ3 /\\ ζ1 ##ₘ ζ2.\nProof.\n  intros H1 H2.\n  destruct (extended_to_trans χ1 χ2 χ3 ζ1 ζ2) as (H3&H4). 1-2: done.\n  erewrite map_union_comm; done.\nQed.\n\nLemma extended_to_refl χ1 :\n  lloc_map_inj χ1 →\n  extended_to χ1 ∅ χ1.\nProof.\n  by repeat split.\nQed.\n\nLemma extended_to_mono χ1 χ2 :\n  lloc_map_mono χ1 χ2 →\n  extended_to χ1 ∅ χ2.\nProof.\n  intros (H1 & H2); by repeat split.\nQed.\n\nLemma is_val_extended_to_weaken χ1 χ2 ζ1 ζ2 v lv:\n  is_val χ1 ζ1 v lv →\n  extended_to χ1 ζ2 χ2 →\n  is_val χ2 (ζ1 ∪ ζ2) v lv.\nProof.\n  intros H1 (H21&H22&H23).\n  eapply is_val_mono; last done.\n  1: apply H21.\n  apply map_union_subseteq_l.\nQed.\n\nLemma deserialize_ML_value χMLold v :  \n  lloc_map_inj χMLold\n→ ∃ χC ζimm lv,\n    extended_to χMLold ζimm χC\n  ∧ is_val χC ζimm v lv.\nProof.\n  induction v as [[x|bo| |ℓ|]| |v1 IHv1 v2 IHv2|v IHv|v IHv] in χMLold|-*; intros Hinj.\n  1-3: eexists χMLold, ∅, _; split_and!; [by eapply extended_to_refl | econstructor ].\n  - destruct (ensure_in_χ_pub χMLold ℓ) as (χ' & γ & Hχ' & Hγ & _); first done.\n    exists χ', ∅, (Lloc γ); (split_and!; last by econstructor).\n    by eapply extended_to_mono.\n  - destruct (ensure_in_χ_foreign χMLold id) as (χ' & γ & Hχ' & Hid & _); first done.\n    exists χ', ∅, (Lloc γ); split_and!; last by econstructor.\n    by eapply extended_to_mono.\n  - destruct (allocate_in_χ_priv χMLold (Bclosure f x e)) as (χ & γ & Hextend); first done.\n    eexists _, _, (Lloc γ). split; eauto. econstructor. by simplify_map_eq.\n  - destruct (IHv1 χMLold) as (χ1 & ζ1 & lv1 & Hext1 & Hlv1); first done.\n    destruct (IHv2 χ1) as (χ2 & ζ2 & lv2 & Hext2 & Hlv2); first by eapply extended_to_inj.\n    pose (Bvblock (Immut,(TagDefault,[lv1;lv2]))) as blk.\n    edestruct (allocate_in_χ_priv χ2 blk) as (χ3 & γ & Hext3); first by eapply extended_to_inj.\n    eassert (extended_to χMLold _ χ3).\n    1: do 2 (eapply extended_to_trans; last done); done.\n    do 3 eexists; split; first done.\n    econstructor.\n    + rewrite lookup_union_r; first by erewrite lookup_singleton.\n      eapply map_disjoint_Some_r. 1: eapply extended_to_trans_2; first eapply extended_to_trans; done.\n      apply lookup_singleton.\n    + eapply is_val_extended_to_weaken; last done.\n      eapply is_val_extended_to_weaken; done.\n    + eapply is_val_extended_to_weaken; last done.\n      eapply is_val_mono; last done; try done.\n      eapply map_union_subseteq_r. eapply extended_to_trans; done.\n  - destruct (IHv χMLold) as (χ1 & ζ1 & lv1 & Hext1 & Hlv1); first done.\n    epose (Bvblock (Immut,(_,[lv1]))) as blk.\n    edestruct (allocate_in_χ_priv χ1 blk) as (χ3 & γ & Hext3); first by eapply extended_to_inj.\n    eassert (extended_to χMLold _ χ3).\n    1: (eapply extended_to_trans; last done); done.\n    do 3 eexists; split; first done.\n    econstructor.\n    + rewrite lookup_union_r; first by erewrite lookup_singleton.\n      eapply map_disjoint_Some_r. 1: eapply extended_to_trans_2; done.\n      apply lookup_singleton.\n    + eapply is_val_extended_to_weaken; done.\n  - destruct (IHv χMLold) as (χ1 & ζ1 & lv1 & Hext1 & Hlv1); first done.\n    epose (Bvblock (Immut,(_,[lv1]))) as blk.\n    edestruct (allocate_in_χ_priv χ1 blk) as (χ3 & γ & Hext3); first by eapply extended_to_inj.\n    eassert (extended_to χMLold _ χ3).\n    1: (eapply extended_to_trans; last done); done.\n    do 3 eexists; split; first done.\n    econstructor.\n    + rewrite lookup_union_r; first by erewrite lookup_singleton.\n      eapply map_disjoint_Some_r. 1: eapply extended_to_trans_2; done.\n      apply lookup_singleton.\n    + eapply is_val_extended_to_weaken; done.\nQed.\n\nLemma deserialize_ML_values χMLold vs :  \n  lloc_map_inj χMLold\n→ ∃ χC ζimm lvs,\n    extended_to χMLold ζimm χC\n  ∧ Forall2 (is_val χC ζimm) vs lvs.\nProof.\n  induction vs as [|v vs IH] in χMLold|-*; intros Hinj.\n  - eexists χMLold, ∅, _; split_and!; [by eapply extended_to_refl | econstructor ].\n  - destruct (deserialize_ML_value χMLold v Hinj) as (χ1 & ζ1 & lv & Hext1 & Hlv1).\n    destruct (IH χ1) as (χ2 & ζ2 & lvs & Hext2 & Hlv2); first by eapply extended_to_inj.\n    eassert (extended_to χMLold _ χ2) by by eapply extended_to_trans.\n    eexists _, _, (lv::lvs). split_and!; first done.\n    econstructor.\n    + by eapply is_val_extended_to_weaken.\n    + eapply Forall2_impl; first done.\n      intros v' lv' H1. eapply is_val_mono; last done; try done.\n      eapply map_union_subseteq_r, extended_to_trans; done.\nQed.\n\nLemma deserialize_ML_block χMLold vs :  \n  lloc_map_inj χMLold\n→ ∃ χC ζimm blk,\n    extended_to χMLold ζimm χC\n  ∧ is_heap_elt χC ζimm vs blk.\nProof.\n  intros H.\n  destruct (deserialize_ML_values χMLold vs H) as (χC & ζimm & lvs & H1 & H2).\n  by exists χC, ζimm, (Bvblock (Mut,(TagDefault,lvs))).\nQed.\n\n\nLemma is_store_blocks_mono_weaken χ1 χ2 ζ σ:\n  is_store_blocks χ1 ζ σ →\n  lloc_map_mono χ1 χ2 →\n  is_store_blocks χ2 ζ σ.\nProof.\n  intros (H1&H2) [Hsub H3]. split.\n  - intros x Hx. destruct (H1 x Hx) as [y Hy]; exists y.\n    eapply lookup_weaken; done.\n  - intros γ; destruct (H2 γ) as [H2L H2R]; split.\n    + intros H; destruct (H2L H) as (ℓ&Vs&HH1&HH2). do 2 eexists; repeat split; try done.\n      eapply lookup_weaken; done.\n    + intros (ℓ&Vs&HH1&HH2).\n      apply H2R. do 2 eexists; repeat split; try done.\n      destruct (H1 ℓ) as (γ2&Hγ2); first by eapply elem_of_dom_2.\n      rewrite <- Hγ2.\n      eapply lookup_weaken in Hγ2; last done.\n      f_equiv. eapply H3; done.\nQed.\n\nLemma is_heap_elt_weaken χ ζ vs blk ζ' χ' :\n  is_heap_elt χ ζ vs blk\n→ χ ⊆ χ'\n→ ζ ⊆ ζ'\n→ is_heap_elt χ' ζ' vs blk.\nProof.\n  intros H1 H2 H3.\n  inversion H1; subst.\n  econstructor. eapply Forall2_impl; first done.\n  intros x y H4; eapply is_val_mono; last done. all:done.\nQed.\n\nLemma is_heap_elt_weaken_2 χ ζ vs blk ζ' χ' :\n  is_heap_elt χ ζ vs blk\n→ extended_to χ' ζ χ\n→ dom ζ' ⊆ dom χ'\n→ is_heap_elt χ (ζ' ∪ ζ) vs blk.\nProof.\n  intros H1 H2 H3.\n  eapply is_heap_elt_weaken. 1: done.\n  1: done. eapply map_union_subseteq_r.\n  eapply map_disjoint_dom. eapply disjoint_weaken.\n  1: apply H2. 1-2:done.\nQed.\n\nLemma deserialize_ML_heap χMLold σ : \n  lloc_map_inj χMLold\n→ ∃ χC ζσ ζnewimm,\n    extended_to χMLold ζnewimm χC\n  ∧ is_store_blocks χC σ ζσ\n  ∧ is_store χC (ζσ ∪ ζnewimm) σ.\nProof.\n  revert χMLold.\n  induction σ as [|ℓ [vv|] σ Hin IH] using map_ind; intros χMLold HχMLold .\n  - exists χMLold, ∅, ∅; split_and!. 2: econstructor.\n    + by eapply extended_to_refl.\n    + intros γ; rewrite dom_empty_L; done.\n    + split; rewrite dom_empty_L. 1: done.\n      intros (ℓ & Vs & H1 & H2). exfalso. rewrite lookup_empty in H2. done.\n    + intros ℓ Vs γ blk Hc. exfalso. rewrite lookup_empty in Hc. done.\n  - destruct (IH χMLold) as (χ0 & ζσ & ζi0 & Hext & Hstbl & Hstore). 1: done.\n    destruct (ensure_in_χ_pub χ0 ℓ) as (χ1 & γ & Hχ1 & Hγ & Hold); first by eapply extended_to_inj.\n    apply extended_to_mono in Hχ1.\n    destruct (deserialize_ML_block χ1 vv) as (χ2 & ζi2 & lvs & Hext2 & Helt); first by eapply extended_to_inj.\n    edestruct (extended_to_trans) as (HextA&Hdisj1). 1: exact Hext. 1: eapply extended_to_trans; done.\n    rewrite map_empty_union in Hdisj1.\n    rewrite map_empty_union in HextA.\n    assert (is_store_blocks χ2 (<[ℓ:=Some vv]> σ) (<[γ:=lvs]> ζσ)) as Hstore2.\n    1: {eapply is_store_blocks_restore_loc.\n        * eapply is_store_blocks_mono_weaken; first done. eapply extended_to_trans; done.\n        * apply Hext2.\n        * eapply lookup_weaken. 1: done. apply Hext2.\n        * by right. }\n    assert (dom (<[γ:=lvs]> ζσ ∪ ζi0) ⊆ dom χ1) as Hsub3.\n    { rewrite dom_union_L. eapply union_subseteq. split.\n      * rewrite dom_insert_L. apply union_subseteq. split.\n        1: eapply singleton_subseteq_l; first by eapply elem_of_dom_2.\n        eapply elem_of_subseteq; intros k Hk.\n        destruct Hstbl as (HH1&HH2). apply HH2 in Hk. destruct Hk as (?&?&H1&H2).\n        eapply elem_of_dom_2. eapply lookup_weaken; first apply H1.\n        eapply Hχ1.\n      * etransitivity; last eapply subseteq_dom, Hχ1.\n        eapply extended_to_dom_subset; done. }\n    eexists χ2, (<[γ := lvs]> ζσ), (ζi0 ∪ ζi2). split_and!. 1-2:done.\n    intros ℓ' vs γ' blk H1 H2 H3.  destruct HextA as (HH1&HH2&HH3).\n    apply lookup_union_Some in H3. 1: destruct H3 as [H3|H3].\n    3: { eapply map_disjoint_dom; eapply elem_of_disjoint.\n         intros x Hx1 Hx2; specialize (HH3 x Hx2). destruct Hstore2 as [HHL HHR].\n         apply HHR in Hx1. destruct Hx1 as (l1 & Vs1 & ? & ?); congruence. }\n    2: { rewrite HH3 in H2; last by eapply elem_of_dom_2. congruence. }\n    apply lookup_insert_Some in H3. destruct H3 as [[? ?]|[Hne H3]].\n    + subst. rewrite map_union_assoc.\n      eapply lookup_weaken in Hγ. 2: eapply Hext2. rewrite Hγ in H2. injection H2; intros ->.\n      rewrite lookup_insert in H1. injection H1; intros ->.\n      by eapply is_heap_elt_weaken_2.\n    + eapply lookup_insert_Some in H1. destruct H1 as [[-> H]|[Hne1 H1]].\n      1: {exfalso. apply Hne. eapply HH1. 2,3: done. eapply lookup_weaken; first done. apply Hext2. }\n      assert (χ0 !! γ' = Some (LlocPublic ℓ')) as H2'.\n      1: {destruct Hstbl as [HHL HHR]. destruct (HHL ℓ') as (gg&Hgg); first by eapply elem_of_dom_2.\n          rewrite <- Hgg; f_equal. eapply HH1. 1,3: done. eapply lookup_weaken; first done.\n          etransitivity; last eapply Hext2; eapply Hχ1. }\n      eapply is_heap_elt_weaken.\n      1: eapply Hstore. 1: done. 3: etransitivity; first eapply Hχ1; last apply Hext2.\n      2: erewrite lookup_union_l; first done. 1: done.\n      1: eapply not_elem_of_dom; intros H; eapply Hext in H; congruence.\n      etransitivity; first eapply map_union_mono_l.\n      2: etransitivity; first eapply map_union_mono_r. 4: done.\n      1: eapply map_union_subseteq_l.\n      1: eapply is_store_blocks_is_private_blocks_disjoint; done.\n      eapply insert_subseteq, not_elem_of_dom.\n      intros H. destruct Hstbl as [HHL HHR]. eapply HHR in H.\n      destruct H as (?&?&Heq1&HeqF). eapply lookup_weaken in Heq1; first erewrite Hγ in Heq1. 2: apply Hχ1.\n      injection Heq1; intros ->; rewrite HeqF in Hin; congruence.\n  - destruct (IH χMLold) as (χ0 & ζσ & ζi0 & Hext & Hstbl & Hstore). 1: done.\n    destruct (ensure_in_χ_pub χ0 ℓ) as (χ1 & γ & Hχ1 & Hγ & Hold); first by eapply extended_to_inj.\n    edestruct (extended_to_trans) as (HextA&Hdisj1); first exact Hext. 1: eapply extended_to_mono, Hχ1.\n    exists χ1, ζσ, ζi0. split_and!. 2: destruct Hstbl as [HL HR]; split.\n    + rewrite map_union_empty in HextA. done.\n    + rewrite dom_insert_L. intros ℓ0 [->%elem_of_singleton|H]%elem_of_union.\n      1: eexists; done.\n      destruct (HL ℓ0 H) as (γ1&Hγ1). exists γ1; eapply lookup_weaken; first done.\n      eapply Hχ1.\n    + intros γ0; specialize (HR γ0) as (HRL&HRR). split.\n      1: intros H; destruct (HRL H) as (ℓ0 & Vs & H3 & H5); do 2 eexists;\n        split; first (eapply lookup_weaken; first done; eapply Hχ1);\n        rewrite lookup_insert_ne; first done;\n        intros ->; rewrite Hin in H5; congruence.\n      intros (ℓ0&Vs&HH1&HH2).\n      rewrite lookup_insert_Some in HH2; destruct HH2 as [[? ?]|[Hne HH2]].\n      1: congruence.\n      eapply HRR. eexists ℓ0, Vs. split; last done.\n      eapply elem_of_dom_2 in HH2.\n      destruct (HL ℓ0 HH2) as (γ1&Hγ1). rewrite <- Hγ1. f_equal.\n      eapply Hχ1; try done. eapply lookup_weaken, Hχ1; done.\n    + intros ℓ1 vs γ1 blk [[? ?]|[? H1]]%lookup_insert_Some H2 H3; try congruence.\n      eapply is_heap_elt_weaken. 1: eapply Hstore; try done.\n      3: done. 2: eapply Hχ1.\n      destruct Hstbl as [HHL HHR].\n      destruct (HHL ℓ1) as (k1&Hk1); first by eapply elem_of_dom_2.\n      rewrite <- Hk1. f_equal. eapply Hχ1; try done. eapply lookup_weaken, Hχ1; done.\nQed.\n\nLemma deserialize_ML_heap_extra ζMLold χMLold σ : \n  lloc_map_inj χMLold\n→ dom ζMLold ⊆ dom χMLold\n→ (map_Forall (fun _ ℓ => σ !! ℓ = Some None) (pub_locs_in_lstore χMLold ζMLold))\n→ ∃ χC ζσ ζnewimm,\n    extended_to χMLold ζnewimm χC\n  ∧ is_store_blocks χC σ ζσ\n  ∧ ζMLold ##ₘ (ζσ ∪ ζnewimm)\n  ∧ is_store χC (ζMLold ∪ ζσ ∪ ζnewimm) σ.\nProof.\n  intros H1 H2 H3.\n  destruct (deserialize_ML_heap χMLold σ) as (χC&ζσ&ζi&HA1&HA2&HA3). 1: apply H1.\n  assert (ζMLold ##ₘ ζσ ∪ ζi) as Hdisj.\n  1: eapply map_disjoint_union_r; split; last (eapply map_disjoint_dom, disjoint_weaken; first apply HA1; done).\n  1: { eapply map_disjoint_spec. intros γ b1 b2 HH1 HH2.\n       destruct HA2 as [_ HA2R]. eapply elem_of_dom_2 in HH2. apply HA2R in HH2.\n       destruct HH2 as (ℓ & Vs & HH7 & HH8).\n       erewrite (map_Forall_lookup_1 _ _ _ _ H3) in HH8.\n       2: { eapply elem_of_dom_2 in HH1. erewrite pub_locs_in_lstore_lookup; first done; first done.\n            eapply elem_of_weaken in H2; last done.\n            eapply elem_of_dom in H2; destruct H2 as [k Hk]. rewrite Hk. \n            eapply lookup_weaken in Hk; first erewrite HH7 in Hk. 2: eapply HA1. done. }\n       congruence. }\n  do 3 eexists; split_and!; try done.\n  - intros ℓ vs γ b He1 He2 He3.\n    eapply is_heap_elt_weaken. 1: eapply HA3; try done. 2: done.\n    + rewrite <- map_union_assoc in He3. eapply lookup_union_Some in He3; destruct He3; try done.\n      destruct (HA2) as [HL HR]. destruct (HR γ) as [HRL HRR]. eapply elem_of_dom in HRR.\n      2: do 2 eexists; done.\n      destruct HRR as [vv Hvv].\n      exfalso. erewrite map_disjoint_Some_r in H; try congruence. 1: done.\n      erewrite lookup_union_Some_l; last done; first done.\n    + erewrite <- map_union_assoc. eapply map_union_subseteq_r. done.\nQed.\n\n\nEnd ChiZetaConstruction.\n\nSection ThetaConstruction.\n\nLemma collect_dom_θ_vs (θdom : gset lloc) (vs : list lval) :\n  exists θdom' : gset lloc,\n    ∀ γ, Lloc γ ∈ vs ∨ γ ∈ θdom ↔ γ ∈ θdom'.\nProof.\n  induction vs as [|[|ℓ] vs (θdom1 & IH)].\n  - exists θdom. intros γ. split; last eauto. by intros [H%elem_of_nil|].\n  - exists θdom1. intros γ. etransitivity; last by eapply IH.\n    split; (intros [H|]; last by eauto); left.\n    + apply elem_of_cons in H as [|]; done.\n    + apply elem_of_cons; eauto.\n  - exists (θdom1 ∪ {[ ℓ ]}). intros γ. split.\n    + intros [[Hc|H]%elem_of_cons|?]; eapply elem_of_union.\n      1: right; eapply elem_of_singleton; congruence.\n      all: left; apply IH. 1: by left. by right.\n    + intros [[H|H]%IH| ->%elem_of_singleton]%elem_of_union.\n      1: left; by right. 1: by right.\n      left; by left.\nQed.\n\nLemma collect_dom_θ_block (θdom : gset lloc) (blk : block) :\n  exists θdom' : gset lloc,\n    ∀ γ, lval_in_block blk (Lloc γ) ∨ γ ∈ θdom ↔ γ ∈ θdom'.\nProof.\n  destruct blk as [[m [tg vs]]| |].\n  { (* Bvblock *)\n    destruct (collect_dom_θ_vs θdom vs) as (θdom' & H).\n    exists θdom'. intros γ. split.\n    - intros [HH|]; first inversion HH; subst; apply H; eauto.\n    - intros [?|?]%H; eauto. left; by constructor. }\n  { (* Bclosure *)\n    exists θdom. intros γ. split; eauto. intros [H|]; auto.\n    by inversion H. }\n  { (* Bforeign *)\n    exists θdom. intros γ. split; eauto. intros [H|]; auto.\n    by inversion H. }\nQed.\n\nLemma collect_dom_θ_ζ_blocks (θdom : gset lloc) (ζ : lstore) :\n  exists θdom' : gset lloc,\n    forall γ, ((exists γ1 blk, ζ !! γ1 = Some blk ∧ lval_in_block blk (Lloc γ))\n               ∨ γ ∈ θdom)\n              ↔ γ ∈ θdom'.\nProof.\n  induction ζ as [|k blk ζ Hne (θdom1 & Hdom1)] using map_ind.\n  - exists θdom; split; auto. intros [(γ1&blk&H1&_)|]; auto.\n    simplify_map_eq.\n  - destruct (collect_dom_θ_block θdom1 blk) as (θdom2 & Hdom2).\n    exists θdom2. intros γ; split.\n    + intros [(γ1&blk'&[[-> ->]|[Hne2 Hin]]%lookup_insert_Some&H2)|Hold].\n      { apply Hdom2; left; congruence. }\n      { apply Hdom2. right. apply Hdom1. left. by do 2 eexists. }\n      { apply Hdom2; right; apply Hdom1; right; done. }\n    + intros [H|[(γ1&blk'&H1&H2)|H]%Hdom1]%Hdom2.\n      1: left; do 2 eexists; split; first eapply lookup_insert; done.\n      2: by right.\n      left; do 2 eexists; split; last done; first rewrite lookup_insert_ne; first done.\n      intros ->; rewrite Hne in H1; congruence.\nQed.\n\nLemma collect_dom_θ_ζ (θdom : gset lloc) (ζ : lstore) :\n  exists θdom' : gset lloc,\n    forall γ, (γ ∈ dom ζ ∨ (exists γ1 blk, ζ !! γ1 = Some blk ∧ lval_in_block blk (Lloc γ))\n               ∨ γ ∈ θdom)\n              ↔ γ ∈ θdom'.\nProof.\n  destruct (collect_dom_θ_ζ_blocks θdom ζ) as (θdom1 & Hdom1).\n  exists (dom ζ ∪ θdom1). intros γ; split.\n  - (intros [H|H]; apply elem_of_union); first by left.\n    right; apply Hdom1; done.\n  - intros [H|H]%elem_of_union; first by left. right; by apply Hdom1.\nQed.\n\nLemma collect_dom_θ_roots (θdom : gset lloc) (roots : roots_map) : exists θdom' : gset lloc,\n    forall γ, ((exists k, roots !! k = Some (Lloc γ)) ∨ γ ∈ θdom) ↔ γ ∈ θdom'.\nProof.\n  induction roots as [|k [z|l] roots Hne (θdom1 & IH)] using map_ind.\n  - exists θdom. intros γ. split; last eauto. intros [[? H%lookup_empty_Some]|?]; done.\n  - exists θdom1. intros γ. split.\n    + intros [[k1 [[-> ?]|[H1 H2]]%lookup_insert_Some]|?]; try congruence; apply IH. 2: by right. left. by eexists.\n    + intros [[k' Hk]|H]%IH; last by right. left. exists k'. rewrite lookup_insert_ne; first done. intros ->; rewrite Hne in Hk; done.\n  - exists (θdom1 ∪ {[ l ]}). intros γ. split.\n    + intros [[k1 [[-> ?]|[H1 H2]]%lookup_insert_Some]|?]; try congruence; eapply elem_of_union. 1: right; eapply elem_of_singleton; congruence.\n      all: left; apply IH. 2: by right. left; by eexists.\n    + intros [[[k' Hk]|H]%IH| ->%elem_of_singleton]%elem_of_union. 2: by right. 2: left; exists k; by rewrite lookup_insert.\n      left; exists k'; rewrite lookup_insert_ne; first done. intros ->; rewrite Hne in Hk; congruence.\nQed.\n\nLemma injectivify_map (S : gset lloc) : exists M : addr_map, dom M = S ∧ gmap_inj M.\nProof.\n  induction S as [|s S Hne (M & <- & Hinj)] using set_ind_L.\n  - exists ∅; split; first by rewrite dom_empty_L. intros ??? H1; exfalso. rewrite lookup_empty in H1; done.\n  - exists (<[s := fresh (codom M)]> M). split.\n    1: by rewrite dom_insert_L.\n    apply gmap_inj_extend; try done.\n    intros k' v' H%codom_spec_2 <-. unshelve eapply is_fresh; last exact H. all: apply _.\nQed.\n\nEnd ThetaConstruction.\n\nLemma find_repr_lval_vv θ v :\n   (forall γ, Lloc γ = v → γ ∈ dom θ)\n → exists l, repr_lval θ v l.\nProof.\n  intros H. destruct v as [z|a].\n  - eexists; by econstructor.\n  - destruct (θ !! a) as [va|] eqn:Heq.\n    2: eapply not_elem_of_dom in Heq; exfalso; apply Heq; apply H; done.\n    eexists; econstructor; apply Heq.\nQed.\n\nLemma find_repr_lval_vs θ vs :\n   (forall γ, Lloc γ ∈ vs → γ ∈ dom θ)\n → exists ls, Forall2 (repr_lval θ) vs ls.\nProof.\n  intros H; induction vs as [|v vs IH] in H|-*.\n  - exists nil. econstructor.\n  - destruct IH as [ls IH]; first (intros γ Hγ; eapply H; right; done).\n    destruct (find_repr_lval_vv θ v) as [l Hl].\n    1: intros γ <-; apply H; by left.\n    eexists. econstructor; done.\nQed.\n\nLemma find_repr_roots θ roots privmem :\n   roots_are_live θ roots\n → dom privmem ## dom roots\n → exists mem, repr θ roots privmem mem.\nProof.\n  revert privmem. unfold repr.\n  induction roots as [|l a roots_m Hin IH] using map_ind; intros privmem Hlive Hdisj.\n  - exists privmem, ∅. split_and!.\n    + econstructor.\n    + eapply map_disjoint_empty_r.\n    + by rewrite map_empty_union.\n  - destruct (IH privmem) as (mem1 & memr1 & Hrepr1 & Hdisj1 & Heq1).\n    1: { intros a1 w1 H1; eapply Hlive; rewrite lookup_insert_ne; first done.\n         intros ->; rewrite Hin in H1; congruence. }\n    1: rewrite dom_insert_L in Hdisj; set_solver.\n    destruct (find_repr_lval_vv θ a) as (w & Hw).\n    1: intros γ <-; eapply Hlive; apply lookup_insert.\n    exists (<[l:=Storing w]> mem1), (<[l:=Storing w]> memr1). split_and!.\n    + econstructor. 1: done. 1:done. 2: erewrite <- repr_roots_dom; last apply Hrepr1. all: by eapply not_elem_of_dom.\n    + apply map_disjoint_dom in Hdisj1. apply map_disjoint_dom.\n      rewrite dom_insert_L. rewrite dom_insert_L in Hdisj. set_solver.\n    + erewrite Heq1. now rewrite insert_union_l.\nQed.\n", "meta": {"author": "logsem", "repo": "melocoton", "sha": "b77eecc3381f53db0eb3c4cf1314e881a8dc41b3", "save_path": "github-repos/coq/logsem-melocoton", "path": "github-repos/coq/logsem-melocoton/melocoton-b77eecc3381f53db0eb3c4cf1314e881a8dc41b3/theories/interop/basics_constructions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.24294714721202348}}
{"text": "Require Import Relations.\nRequire Import EquivDec.\nRequire Import Equality.\nRequire Import List.\nRequire Import Bool.\nRequire Import Lia.\nRequire Import NArith.\nRequire Import PArith.\nRequire Import ZArith.\nRequire Import FMapPositive.\nRequire Import FSetPositive.\nRequire Import sflib.\n\nRequire Import PromisingArch.lib.Basic.\nRequire Import PromisingArch.lib.Order.\nRequire Import PromisingArch.lib.Time.\nRequire Import PromisingArch.lib.Lang.\nRequire Import PromisingArch.promising.TsoPromising.\n\nSet Implicit Arguments.\n\n\nLemma rtc_state_step_state_exec\n      m1 m2\n      (WF: Machine.wf m1)\n      (STEP: rtc (Machine.step ExecUnit.state_step) m1 m2):\n  Machine.state_exec m1 m2.\nProof.\n  revert WF. induction STEP.\n  { econs; ss. ii. destruct (IdMap.find id (Machine.tpool x)); ss. econs. refl. }\n  i. exploit Machine.step_state_step_wf; eauto. i.\n  exploit IHSTEP; eauto. i. inv x0.\n  destruct x as [tpool1 mem1].\n  destruct y as [tpool2 mem2].\n  inv H. inversion STEP0. inv STEP1. ss. subst. econs; ss.\n  ii. specialize (TPOOL id). revert TPOOL.\n  rewrite IdMap.add_spec. condtac; ss. i.\n  inversion e0. inv TPOOL. rewrite FIND, <- H2. econs.\n  econs; eauto.\nQed.\n\nLemma state_exec_rtc_state_step\n      m1 m2\n      (STEP: Machine.state_exec m1 m2):\n  exists m2',\n    <<EXEC: rtc (Machine.step ExecUnit.state_step) m1 m2'>> /\\\n    <<EQUIV: Machine.equiv m2 m2'>>.\nProof.\n  inv STEP.\n  assert (IN: forall tid sl1\n                (FIND1: IdMap.find tid m1.(Machine.tpool) = Some sl1),\n             exists sl2,\n               IdMap.find tid m2.(Machine.tpool) = Some sl2 /\\\n               rtc (ExecUnit.state_step tid)\n                   (ExecUnit.mk (fst sl1) (snd sl1) m1.(Machine.mem))\n                   (ExecUnit.mk (fst sl2) (snd sl2) m1.(Machine.mem))).\n  { i. specialize (TPOOL tid). rewrite FIND1 in TPOOL. inv TPOOL. esplits; ss. }\n  assert (OUT: forall tid\n                 (FIND1: IdMap.find tid m1.(Machine.tpool) = None),\n             IdMap.find tid m1.(Machine.tpool) = IdMap.find tid m2.(Machine.tpool)).\n  { i. specialize (TPOOL tid). rewrite FIND1 in TPOOL. inv TPOOL. ss. }\n  assert (P: forall tid sl1\n               (FIND1: IdMap.find tid m1.(Machine.tpool) = Some sl1),\n             IdMap.find tid m1.(Machine.tpool) = Some sl1).\n  { ss. }\n  clear TPOOL.\n  setoid_rewrite IdMap.elements_spec in IN at 1.\n  setoid_rewrite IdMap.elements_spec in OUT at 1.\n  setoid_rewrite IdMap.elements_spec in P at 1.\n  generalize (IdMap.elements_3w m1.(Machine.tpool)). intro NODUP. revert NODUP.\n  revert IN OUT P. generalize (IdMap.elements (m1.(Machine.tpool))). intro ps.\n  revert m1 MEM. induction ps; ss.\n  { i. esplits; eauto. econs; ss. ii. rewrite OUT; ss. }\n\n  i. destruct a. inv NODUP.\n  exploit (IN k).\n  { destruct (equiv_dec k k); ss. congr. }\n  exploit (P k).\n  { destruct (equiv_dec k k); ss. congr. }\n  i. des. destruct p. ss.\n\n  cut (exists m2', rtc (Machine.step ExecUnit.state_step)\n                 (Machine.mk (IdMap.add k (fst sl2, snd sl2) m1.(Machine.tpool)) m1.(Machine.mem))\n                 m2' /\\\n             Machine.equiv m2 m2').\n  { i. des. esplits; [|by eauto]. etrans; [|by eauto].\n    eapply Machine.rtc_eu_step_step; [eauto|refl|eauto].\n  }\n  assert (TID: forall tid sl (FIND: SetoidList.findA (fun id' : IdMap.key => if equiv_dec tid id' then true else false) ps = Some sl), tid <> k).\n  { ii. subst. apply H1. revert FIND. clear. induction ps; ss.\n    destruct a. destruct (equiv_dec k k0); ss.\n    - inv e. i. inv FIND. left. ss.\n    - i. right. apply IHps. ss.\n  }\n  eapply IHps; ss.\n  - i. eapply IN. destruct (equiv_dec tid k); ss.\n    inv e. exfalso. eapply TID; eauto.\n  - i. rewrite IdMap.add_spec. condtac.\n    + inversion e. subst. rewrite x1. destruct sl2. ss.\n    + eapply OUT. destruct (equiv_dec tid k); ss.\n  - i. rewrite IdMap.add_spec. condtac.\n    + inversion e. subst. exfalso. eapply TID; eauto.\n    + eapply P. destruct (equiv_dec tid k); ss.\nQed.\n", "meta": {"author": "kaist-cp", "repo": "view-hw", "sha": "e41c8ab30119acd73b6b47cf95584f966ccb8e62", "save_path": "github-repos/coq/kaist-cp-view-hw", "path": "github-repos/coq/kaist-cp-view-hw/view-hw-e41c8ab30119acd73b6b47cf95584f966ccb8e62/src/promising/TsoStateExecFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.24294714136806156}}
{"text": "From iris.base_logic.lib Require Export invariants.\nFrom iris.bi.lib Require Import fractional.\nFrom iris.algebra Require Export frac.\nFrom iris.proofmode Require Import tactics.\nSet Default Proof Using \"Type\".\nImport uPred.\n\nClass cinvG Σ := cinv_inG :> inG Σ fracR.\nDefinition cinvΣ : gFunctors := #[GFunctor fracR].\n\nInstance subG_cinvΣ {Σ} : subG cinvΣ Σ → cinvG Σ.\nProof. solve_inG. Qed.\n\nSection defs.\n  Context `{invG Σ, cinvG Σ}.\n\n  Definition cinv_own (γ : gname) (p : frac) : iProp Σ := own γ p.\n\n  Definition cinv (N : namespace) (γ : gname) (P : iProp Σ) : iProp Σ :=\n    (∃ P', □ ▷ (P ↔ P') ∗ inv N (P' ∨ cinv_own γ 1%Qp))%I.\nEnd defs.\n\nInstance: Params (@cinv) 5.\n\nSection proofs.\n  Context `{invG Σ, cinvG Σ}.\n\n  Global Instance cinv_own_timeless γ p : Timeless (cinv_own γ p).\n  Proof. rewrite /cinv_own; apply _. Qed.\n\n  Global Instance cinv_contractive N γ : Contractive (cinv N γ).\n  Proof. solve_contractive. Qed.\n  Global Instance cinv_ne N γ : NonExpansive (cinv N γ).\n  Proof. exact: contractive_ne. Qed.\n  Global Instance cinv_proper N γ : Proper ((≡) ==> (≡)) (cinv N γ).\n  Proof. exact: ne_proper. Qed.\n\n  Global Instance cinv_persistent N γ P : Persistent (cinv N γ P).\n  Proof. rewrite /cinv; apply _. Qed.\n\n  Global Instance cinv_own_fractional γ : Fractional (cinv_own γ).\n  Proof. intros ??. by rewrite /cinv_own -own_op. Qed.\n  Global Instance cinv_own_as_fractional γ q :\n    AsFractional (cinv_own γ q) (cinv_own γ) q.\n  Proof. split. done. apply _. Qed.\n\n  Lemma cinv_own_valid γ q1 q2 : cinv_own γ q1 -∗ cinv_own γ q2 -∗ ✓ (q1 + q2)%Qp.\n  Proof. apply (own_valid_2 γ q1 q2). Qed.\n\n  Lemma cinv_own_1_l γ q : cinv_own γ 1 -∗ cinv_own γ q -∗ False.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct (cinv_own_valid with \"H1 H2\") as %[]%(exclusive_l 1%Qp).\n  Qed.\n\n  Lemma cinv_iff N γ P P' :\n    ▷ □ (P ↔ P') -∗ cinv N γ P -∗ cinv N γ P'.\n  Proof.\n    iIntros \"#HP' Hinv\". iDestruct \"Hinv\" as (P'') \"[#HP'' Hinv]\".\n    iExists _. iFrame \"Hinv\". iAlways. iNext. iSplit.\n    - iIntros \"?\". iApply \"HP''\". iApply \"HP'\". done.\n    - iIntros \"?\". iApply \"HP'\". iApply \"HP''\". done.\n  Qed.\n\n  Lemma cinv_alloc_strong (G : gset gname) E N :\n    (|={E}=> ∃ γ, ⌜ γ ∉ G ⌝ ∧ cinv_own γ 1 ∗ ∀ P, ▷ P ={E}=∗ cinv N γ P)%I.\n  Proof.\n    iMod (own_alloc_strong 1%Qp G) as (γ) \"[Hfresh Hγ]\"; first done.\n    iExists γ; iIntros \"!> {$Hγ $Hfresh}\" (P) \"HP\".\n    iMod (inv_alloc N _ (P ∨ own γ 1%Qp)%I with \"[HP]\"); first by eauto.\n    iIntros \"!>\". iExists P. iSplit; last done. iIntros \"!# !>\"; iSplit; auto.\n  Qed.\n\n  Lemma cinv_open_strong E N γ p P :\n    ↑N ⊆ E →\n    cinv N γ P -∗ cinv_own γ p ={E,E∖↑N}=∗\n    ▷ P ∗ cinv_own γ p ∗ (▷ P ∨ cinv_own γ 1 ={E∖↑N,E}=∗ True).\n  Proof.\n    iIntros (?) \"#Hinv Hγ\". iDestruct \"Hinv\" as (P') \"[#HP' Hinv]\".\n    iInv N as \"[HP | >Hγ']\" \"Hclose\".\n    - iIntros \"!> {$Hγ}\". iSplitL \"HP\".\n      + iNext. iApply \"HP'\". done.\n      + iIntros \"[HP|Hγ]\".\n        * iApply \"Hclose\". iLeft. iNext. by iApply \"HP'\".\n        * iApply \"Hclose\". iRight. by iNext.\n    - iDestruct (cinv_own_1_l with \"Hγ' Hγ\") as %[].\n  Qed.\n\n  Lemma cinv_alloc E N P : ▷ P ={E}=∗ ∃ γ, cinv N γ P ∗ cinv_own γ 1.\n  Proof.\n    iIntros \"HP\". iMod (cinv_alloc_strong ∅ E N) as (γ _) \"[Hγ Halloc]\".\n    iExists γ. iFrame \"Hγ\". by iApply \"Halloc\".\n  Qed.\n\n  Lemma cinv_cancel E N γ P : ↑N ⊆ E → cinv N γ P -∗ cinv_own γ 1 ={E}=∗ ▷ P.\n  Proof.\n    iIntros (?) \"#Hinv Hγ\".\n    iMod (cinv_open_strong with \"Hinv Hγ\") as \"($ & Hγ & H)\"; first done.\n    iApply \"H\". by iRight.\n  Qed.\n\n  Lemma cinv_open E N γ p P :\n    ↑N ⊆ E →\n    cinv N γ P -∗ cinv_own γ p ={E,E∖↑N}=∗ ▷ P ∗ cinv_own γ p ∗ (▷ P ={E∖↑N,E}=∗ True).\n  Proof.\n    iIntros (?) \"#Hinv Hγ\".\n    iMod (cinv_open_strong with \"Hinv Hγ\") as \"($ & $ & H)\"; first done.\n    iIntros \"!> HP\". iApply \"H\"; auto.\n  Qed.\n\n  Global Instance into_inv_cinv N γ P : IntoInv (cinv N γ P) N.\n\n  Global Instance into_acc_cinv E N γ P p :\n    IntoAcc (X:=unit) (cinv N γ P)\n            (↑N ⊆ E) (cinv_own γ p) (fupd E (E∖↑N)) (fupd (E∖↑N) E)\n            (λ _, ▷ P ∗ cinv_own γ p)%I (λ _, ▷ P)%I (λ _, None)%I.\n  Proof.\n    rewrite /IntoAcc /accessor. iIntros (?) \"#Hinv Hown\".\n    rewrite exist_unit -assoc.\n    iApply (cinv_open with \"Hinv\"); done.\n  Qed.\nEnd proofs.\n\nTypeclasses Opaque cinv_own cinv.\n", "meta": {"author": "izgzhen", "repo": "iris-coq", "sha": "4a1eb8a3d20789af6265b9011939be8274da042c", "save_path": "github-repos/coq/izgzhen-iris-coq", "path": "github-repos/coq/izgzhen-iris-coq/iris-coq-4a1eb8a3d20789af6265b9011939be8274da042c/theories/base_logic/lib/cancelable_invariants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.24294713552409944}}
{"text": "Require Import Ynot Basis.\nRequire Import UdpServer TcpServer SslServer.\nRequire Import IO Net FS.\nRequire Import Parsers.\nRequire Import Stream Parsec Charset.\nRequire Import List Ascii String.\n\nRequire Import RSep.\nImport STRING_INSTREAM.\nImport INSTREAM.\nImport Expressions.\n\nOpen Local Scope hprop_scope.\nOpen Local Scope stsepi_scope.\n\nSet Implicit Arguments.\n\nModule Type EVALPARAMS.\n\n  Variable t: Set.\n  Variable grammar : Term AsciiCharset t.\n  Variable parser  : parser_t grammar.\n  Variable e : list ascii.      (* error list ascii *)\n  Variable f : t -> list ascii. (* value serializer *)\n\nEnd EVALPARAMS.\n\nModule PrefixServer : EVALPARAMS.\n Import Expressions.\n Definition t := nat.\n Definition grammar : Term AsciiCharset nat := prefix.\n Definition parser := prefix_p.\n Require Import Ascii.\n Open Scope char_scope.\n\n Definition e : list ascii := str2la \"error\"%string.\n Definition f x := str2la (ntos x).\n\nEnd PrefixServer.\n\nModule UdpEvalServerParams (A : EVALPARAMS) : UdpServer.EXECPARAMS.\n  Export A.\n\n  Definition resp (CH : Charset) (r :reply_t CH t) := \n    match r with\n      | Okay _ a _ => f a \n      | Error _ => e \n    end.\n\n  Inductive ccorrect' (req : list ascii) : Trace -> Prop :=\n  | NilCorrect : ccorrect' req nil.\n  Definition ccorrect := ccorrect'.\n\n  Inductive reply' (req : list ascii) : list ascii -> Prop :=\n  | ReplyIdentity : forall v, parses grammar req v -> reply' req (resp v).\n  Definition reply := reply'.\n\n  Definition io : forall (req : list ascii) (tr : [Trace]),\n    STsep (tr ~~ traced tr)\n          (fun r:(list ascii * [Trace]) => tr ~~ tr' :~~ (snd r) in traced (tr' ++ tr) * [reply req (fst r)] * [ccorrect req tr']).\n    refine (fun req tr =>\n      is  <- instream_of_list_ascii req <@> _ ;\n      ans <- parser is (inhabits 0) <@> (tr ~~ elts :~~ (stream_elts is) in traced tr * [elts = req]);\n\n      close is <@> _ ;;\n      {{ Return (match ans with\n                   | ERROR _ _ =>  e\n                   | OKAY _ _ a => f a\n                 end, [nil]%inhabited) }}).\n    rsep fail auto.\n    rsep fail auto.\n    lazy zeta. rsep fail auto.\n    rsep fail auto.\n    solve [ unfold ans_str_correct, okaystr, errorstr;\n            instantiate (1 := tr ~~ \n              hprop_unpack (stream_elts is)\n              (fun elts => \n                traced tr * [elts = req] *\n                match ans with\n                  | OKAY c m v =>\n                    @okay AsciiCharset _ [0] is grammar c m v\n                  | ERROR c _ => @error AsciiCharset _ [0] is grammar c\n                end));\n            destruct ans; sep fail auto ].\n    solve [ sep fail auto ].\n    solve [ sep fail auto ].\n    unfold char, okay, error in *. rsep fail auto. subst; norm_prod. destruct ans. rsep ltac:(norm_list) auto. cut_pure.\n    pose (ReplyIdentity H1). simpl in *. unfold char in *. rewrite H in H0. rewrite <- (pack_injective H0); auto.\n\n    \n    rsep ltac:(norm_list) auto. cut_pure; try constructor; auto. unfold reply. pose (ReplyIdentity H1). simpl in *. unfold char in *. rewrite H in H0. rewrite <- (pack_injective H0); auto.\n  Qed.\n\nEnd UdpEvalServerParams.\n\nModule TcpEvalServerParams (A : EVALPARAMS).\n  Export A.\n\n  Ltac solver := auto.\n  \n  Definition resp (CH : Charset) (r :reply_t CH t) := \n    match r with\n      | Okay _ a _ => f a \n      | Error _ => e \n    end.\n\n  Inductive ccorrect' (local remote : SockAddr) (fd : File (BoundSocketModel local remote) (R :: W :: nil)) : Trace -> Prop :=\n  | DoneCorrect : forall past, ecorrect fd past -> ccorrect' fd (Flush fd :: ReadLine fd nil ++ past)\n  with ecorrect (local remote : SockAddr) (fd : File (BoundSocketModel local remote) (R :: W :: nil)) : Trace -> Prop :=\n  | NilCorrect : ecorrect fd nil\n  | ConsCorrect : forall s v past rep, s <> nil -> rep = resp v -> ecorrect fd past -> parses grammar s v ->\n    ecorrect fd (Flush fd :: WroteString fd rep ++ ReadLine fd s ++ past).\n  Definition ccorrect := ccorrect'.\n\n  Definition traceCombine (t1 t2 : [Trace]) := inhabit_unpack2 t1 t2 (fun t1 t2 => t1 ++ t2).\n  Definition traceAfter (t1 t2 : [Trace]) (f : Trace -> Trace) := inhabit_unpack2 t1 t2 (fun t1 t2 => f (t1 ++ t2)).\n\n  Definition empty_eq : forall T (a : list T), {a = nil} + {a <> nil}.\n    intros; destruct a; firstorder.\n  Qed.\n\n  Ltac rcombine := idtac;\n    match goal with\n      | [ H : traceCombine ?X ?Y = [_]%inhabited |- _ ] =>\n        rwpack X H; rwpack Y H; simpl in H; rewrite <- (pack_injective H) in *; clear H\n      | [ H : traceAfter ?X ?Y _ = [_]%inhabited |- _ ] =>\n        rwpack X H; rwpack Y H; simpl in H; rewrite <- (pack_injective H) in *; clear H\n      | [ H : (inhabit_unpack ?X _) = [_]%inhabited |- _ ] =>\n        rwpack X H; simpl in H; rewrite <- (pack_injective H)\n    end.\n\n  Definition io : forall (local remote : SockAddr) (fd : File (BoundSocketModel local remote) (R :: W :: nil)) (tr : [Trace]),\n    STsep (tr ~~ traced tr * handle fd)\n          (fun tr':[Trace] => tr ~~ tr' ~~ traced (tr' ++ tr) * [ccorrect fd tr']).\n    intros. refine (\n      lt <- Fix (fun tr' => tr ~~ tr' ~~ traced (tr' ++ tr) * [ecorrect fd tr'] * handle fd)\n                (fun _ tr' => tr ~~ tr' ~~ traced (tr' ++ tr) * [ccorrect fd tr'])\n                (fun self tr' =>\n                  str <- readline fd rw_readable (traceCombine tr' tr) <@> (tr' ~~ [ecorrect fd tr']);\n                  if empty_eq str then\n                    flush fd (traceAfter tr' tr (fun t => ReadLine fd str ++ t)) rw_writeable <@> \n                      (tr' ~~ [ecorrect fd tr']) ;;\n                    FS.close fd <@> (tr ~~ tr' ~~ [ecorrect fd tr'] * traced (Flush fd :: ReadLine fd str ++ tr' ++ tr)) ;;\n                    {{Return (tr' ~~~ Flush fd :: ReadLine fd str ++ tr')}}\n                  else\n                    is  <- instream_of_list_ascii str <@> _ ;\n                    ans <- parser is (inhabits 0) <@> _ ;\n                    close is <@> _ ;;\n                    let reply := match ans with\n                                   | ERROR _ _ =>  e\n                                   | OKAY _ _ a => f a\n                                 end in\n                    writeline fd reply rw_writeable (traceAfter tr' tr (fun t => ReadLine fd str ++ t)) <@> _;;\n                    flush fd (traceAfter tr' tr (fun t => WroteString fd reply ++ ReadLine fd str ++ t)) rw_writeable <@> _;;\n                    {{self (tr' ~~~ Flush fd :: WroteString fd reply ++ ReadLine fd str ++ tr')}})\n                [nil]%inhabited;\n      {{Return lt}}); try clear self; simpl char in *.\n    unfold traceAfter, traceCombine. rsep fail auto.\n    solve [ rsep fail auto ].\n    solve [ unfold traceAfter, traceCombine; rsep fail auto ].\n    solve [ unfold traceAfter, traceCombine; rsep fail auto ].\n    solve [ unfold traceAfter, traceCombine; rsep fail auto ].\n    solve [ unfold traceAfter, traceCombine; rsep fail auto ].\n    solve [ unfold traceAfter, traceCombine; rsep fail auto ].\n    solve [ unfold traceAfter, traceCombine, ccorrect; rsep ltac:(norm_list) auto; cut_pure; subst; constructor; auto ].\n    solve [ unfold traceAfter, traceCombine; rsep fail auto ].\n    solve [ unfold traceAfter, traceCombine; rsep fail auto ].\n    unfold traceAfter, traceCombine. rsep fail auto.\n    instantiate (1 := tr ~~ tr' ~~ x1 :~~ (stream_elts is) in [x1 = str] * handle fd * [ecorrect fd tr'] * traced (ReadLine fd x1 ++ tr' ++ tr)). sep fail auto. (** Should be able to solve this? **)\n    solve [ unfold traceAfter, traceCombine; rsep fail auto ].\n    rsep fail auto.\n    unfold ans_str_correct, okaystr, okay, errorstr, error.\n    instantiate (1 := tr ~~ tr' ~~ x1 :~~ (stream_elts is) in\n      traced (ReadLine fd x1 ++ tr' ++ tr) * handle fd * [ecorrect fd tr'] * [x1 = str] *\n        [parses grammar (nthtail x1 0) (match ans with\n                                          | OKAY c m v => @Okay AsciiCharset _ c v (nthtail x1 m)\n                                          | ERROR c _ => @Error AsciiCharset _ c\n                                        end)]).\n    cbv zeta. rsep fail auto. destruct ans; rsep fail auto. unfold Parsec.char in *. simpl char in *.\n    assert (n + 0 = n). omega. rewrite H6. rewrite H1 in H4. rewrite (pack_injective H4). sep fail auto. (** We don't handle Exists yet **)\n    unfold Parsec.char in *; simpl char in *. rewrite H1 in H4. rewrite (pack_injective H4). rsep fail auto.\n    (** Solvable with some additional instramentation, unfolding of char **)\n\n    solve [ unfold traceAfter, traceCombine; rsep fail auto ].\n    unfold traceAfter, traceCombine. rsep fail auto.\n    instantiate (1 := (tr' ~~ x1 :~~ (stream_elts is) in [ecorrect fd tr'] * [x1 = str] *\n      [parses grammar (nthtail x1 0) match ans with\n                                        | OKAY c m v => @Okay AsciiCharset _ c v (nthtail x1 m)\n                                        | ERROR c _ => @Error AsciiCharset _ c\n                                      end])%hprop).\n    cbv zeta. subst. rsep fail auto. \n    solve [ unfold traceAfter, traceCombine; rsep fail auto ].\n    solve [ unfold traceAfter, traceCombine; rsep fail auto ]. \n    solve [ unfold traceAfter, traceCombine; rsep fail auto ].\n    unfold traceAfter, traceCombine; rsep fail auto. \n    simpl. norm_list. rsep fail auto. cut_pure.\n      eapply ConsCorrect; auto. \n      instantiate (1 := match ans with\n                          | OKAY c m v => @Okay AsciiCharset _ c v (nthtail x0 m)\n                          | ERROR c _ => @Error AsciiCharset t c\n                        end). destruct ans; auto.\n      destruct ans; rewrite H2 in *; trivial.\n    solve [ unfold traceAfter, traceCombine; rsep fail auto ].\n    unfold traceAfter, traceCombine; rsep ltac:(norm_list) auto; cut_pure; constructor.\n    solve [ unfold traceCombine; rsep fail auto ].\n    solve [ unfold traceCombine; rsep fail auto ].\n    solve [ unfold traceCombine; rsep fail auto ].\n  Qed.\nEnd TcpEvalServerParams.\n\n\nModule uprefix_params := UdpEvalServerParams PrefixServer.\nModule tprefix_params := TcpEvalServerParams PrefixServer.\nModule sprefix_params := TcpEvalServerParams PrefixServer.\n\nModule umes  := UdpServer.ExecImpl uprefix_params.\nModule tmes' := TcpServer.ADD_STATE(tprefix_params).\nModule tmes  := TcpServer.ExecImpl(tmes').\nModule smes' := SslServer.ADD_STATE(sprefix_params).\nModule smes  := SslServer.ExecImpl(smes').\n\nDefinition udp := umes.main.\nDefinition tcp := tmes.main.\nDefinition ssl := smes.main.\n", "meta": {"author": "Ptival", "repo": "ynot", "sha": "cd6f28816c41bbef7464b644edeba099d397a01e", "save_path": "github-repos/coq/Ptival-ynot", "path": "github-repos/coq/Ptival-ynot/ynot-cd6f28816c41bbef7464b644edeba099d397a01e/examples/servers/EvalServer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24294049609699106}}
{"text": "(** * Iteration: Bounded Loops *)\n\n(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation, either version 2 of the License, or  *)\n(*  (at your option) any later version.  This file is also distributed *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n(* -------------------------------------------------------------------------- *\n *                     Vellvm - the Verified LLVM project                     *\n *                                                                            *\n *     Copyright (c) 2017 Steve Zdancewic <stevez@cis.upenn.edu>              *\n *                                                                            *\n *   This file is distributed under the terms of the GNU General Public       *\n *   License as published by the Free Software Foundation, either version     *\n *   3 of the License, or (at your option) any later version.                 *\n ---------------------------------------------------------------------------- *)\n\n\n(* ################################################################# *)\n(** * Bounded iterators *)\n\nRequire Import NArith FunctionalExtensionality.\n\nSet Implicit Arguments.\n\nModule Iter.\n\nSection ITERATION.\n\nVariables A B: Type.\nVariable step: A -> B + A.\n\nDefinition num_iterations := 1000000000000%N.\n\nOpen Scope N_scope.\n\nDefinition iter_step (x: N)\n                     (next: forall y, y < x -> A -> option B)\n                     (s: A) : option B :=\n  match N.eq_dec x N.zero with\n  | left EQ => None\n  | right NOTEQ =>\n      match step s with\n      | inl res => Some res\n      | inr s'  => next (N.pred x) (N.lt_pred_l x NOTEQ) s'\n      end\n  end.\n\n\nDefinition iter: N -> A -> option B := Fix N.lt_wf_0 _ iter_step.\nDefinition iterate := iter num_iterations.\n\nVariable P: A -> Prop.\nVariable Q: B -> Prop.\n\nHypothesis step_prop:\n  forall a : A, P a ->\n  match step a with inl b => Q b | inr a' => P a' end.\n\nLemma iter_prop:\n  forall n b a, P a -> iter n a = Some b -> Q b.\nProof.\n  intros n b. pattern n. apply (well_founded_ind N.lt_wf_0).\n  intros until 2. rewrite (Fix_eq N.lt_wf_0 _ iter_step). \n  unfold iter_step at 1. destruct (N.eq_dec _ _). \n  discriminate 1. specialize (step_prop H0).\n  destruct (step a).\n    inversion 1; subst b0; exact step_prop.\n    apply H; auto. apply N.lt_pred_l; auto.\n  intros. f_equal. \n  apply functional_extensionality_dep. intro. \n  apply functional_extensionality_dep. auto.\nQed.\n\nLemma iterate_prop:\n  forall a b, iterate a = Some b -> P a -> Q b.\nProof.\n  intros. apply iter_prop with num_iterations a; assumption.\nQed.\n\nEnd ITERATION.\n\nEnd Iter.\n\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/vminus/Iteration.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2429404898682933}}
{"text": "(** This file implements rewriting using lemmas.\n **)\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.PArith.BinPos.\nRequire Import Coq.Relations.Relations.\nRequire Import Coq.FSets.FMapPositive.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.List.\nRequire Import ExtLib.Data.HList.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.Lemma.\nRequire Import MirrorCore.VarsToUVars.\nRequire Import MirrorCore.Instantiate.\nRequire Import MirrorCore.Util.Forwardy.\nRequire Import MirrorCore.Util.Compat.\nRequire Import MirrorCore.RTac.CoreK.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.Lambda.ExprTac.\nRequire Import MirrorCore.Lambda.ExprUnify.\nRequire Import MirrorCore.Lambda.RewriteRelations.\nRequire Import MirrorCore.Lambda.Rewrite.Core.\n\nSet Implicit Arguments.\nSet Strict Implicit.\nSet Printing Universes.\n\nSet Suggest Proof Using.\n\n(** TODO(gmalecha): Move to EnvI or ExtLib.Data.HList **)\nPolymorphic Lemma nth_error_get_hlist_nth_appR'\n: forall {T : Type} (F : T -> Type) ls u v,\n    nth_error_get_hlist_nth F ls u = Some v ->\n    forall ls' : list T,\n    exists v' : hlist F (ls' ++ ls) -> F (projT1 v),\n      nth_error_get_hlist_nth F (ls' ++ ls) (u + length ls') = Some (existT _ (projT1 v) v') /\\\n      forall a b,\n        projT2 v a = v' (hlist_app b a).\nProof using.\n  induction ls'.\n  { simpl.\n    replace (u + 0) with u by omega.\n    destruct v. eexists; split; eauto.\n    simpl. intros.\n    rewrite (hlist_eta b). reflexivity. }\n  { simpl.\n    replace (u + S (length ls')) with (S (u + length ls')) by omega.\n    destruct IHls' as [ ? [ ? ? ] ].\n    rewrite H0. eexists; split; eauto.\n    simpl. intros.\n    rewrite (hlist_eta b). simpl. eauto. }\nQed.\n\n(** TODO: Move **)\nPolymorphic Lemma forall_hlist_nil : forall T (F : T -> Type) (P : hlist F nil -> Prop),\n    (forall x, P x) <-> P Hnil.\nProof using.\n  intros. split. eauto. intros. rewrite hlist_eta. assumption.\nQed.\n\n\nPolymorphic Lemma forall_hlist_cons : forall T (F : T -> Type) t ts (P : hlist F (t :: ts) -> Prop),\n    (forall x, P x) <-> (forall x xs, P (Hcons x xs)).\nProof using.\n  intros. split. eauto. intros. rewrite hlist_eta. eapply H.\nQed.\n\n\nSection setoid.\n  Context {typ : Set}.\n  Context {func : Set}.\n  Context {RType_typD : RType typ}.\n  Context {Typ2_Fun : Typ2 RType_typD RFun}.\n  Context {RSym_func : RSym func}.\n\n  (** Reasoning principles **)\n  Context {RTypeOk_typD : RTypeOk}.\n  Context {Typ2Ok_Fun : Typ2Ok Typ2_Fun}.\n  Context {RSymOk_func : RSymOk RSym_func}.\n  Context {Typ0_Prop : Typ0 _ Prop}.\n\n  (** TODO(gmalecha): This is not necessary *)\n  Context {RelDec_eq_typ : RelDec (@eq typ)}.\n  Context {RelDec_Correct_eq_typ : RelDec_Correct RelDec_eq_typ}.\n\n  Local Existing Instance Subst_ctx_subst.\n  Local Existing Instance SubstOk_ctx_subst.\n  Local Existing Instance SubstUpdate_ctx_subst.\n  Local Existing Instance SubstUpdateOk_ctx_subst.\n  Local Existing Instance Expr_expr.\n  Local Existing Instance ExprOk_expr.\n\n  (** TODO: Move **)\n  Lemma pctxD_iff : forall ctx (cs : ctx_subst ctx) cD P Q,\n      pctxD cs = Some cD ->\n      (forall us vs, P us vs <-> Q us vs) ->\n      forall us vs,\n        cD P us vs <-> cD Q us vs.\n  Proof using.\n    intros.\n    split; eapply Ap_pctxD; eauto; eapply Pure_pctxD; eauto; intros; eapply H0; eauto.\n  Qed.\n\n\n  (* TODO(gmalecha): Wrap all of this up in a type class?\n   * Why should it be different than Expr?\n   *)\n  Variable Rbase : Set.\n  Variable Rbase_eq : Rbase -> Rbase -> bool.\n  Hypothesis Rbase_eq_ok : forall a b, Rbase_eq a b = true -> a = b.\n\n  Local Notation \"'R'\" := (R typ Rbase).\n\n  Variable RbaseD : Rbase -> forall t : typ, option (typD t -> typD t -> Prop).\n\n  Hypothesis RbaseD_single_type\n  : forall r t1 t2 rD1 rD2,\n      RbaseD r t1 = Some rD1 ->\n      RbaseD r t2 = Some rD2 ->\n      t1 = t2.\n\n  Definition func_sdec (a b : func) : bool :=\n    match sym_eqb a b with\n    | Some x => x\n    | _ => false\n    end.\n\n  Definition expr_sdec : expr typ func -> expr typ func -> bool :=\n    @expr_eq_sdec typ func _ func_sdec.\n\n  Lemma expr_sdec_sound\n  : forall a b : expr typ func, expr_sdec a b = true -> a = b.\n  Proof using RSymOk_func RelDec_Correct_eq_typ.\n    eapply expr_eq_sdec_ok; eauto.\n    unfold func_sdec.\n    intros. generalize (sym_eqbOk a b); eauto with typeclass_instances.\n    destruct (sym_eqb a b); intros; subst; auto.\n    inversion H.\n  Qed.\n\n  Section core_rewrite.\n    (* This is the implementation of rewriting a single lemma *)\n\n    Require Import MirrorCore.RTac.SolveK.\n\n    (** TODO(gmalecha): This is not a nice interface because it is not\n     ** a standard rewriter for two reasons:\n     ** 1) It assumes that tvs' = nil, and\n     ** 2) It assumes that the relation is the same as the relation for\n     **    the lemma.\n     **)\n    Definition core_rewrite (lem : rw_lemma typ func Rbase)\n               (tac : rtacK typ (expr typ func))\n    : expr typ func ->\n      forall c : Ctx typ (expr typ func),\n        ctx_subst c -> option (expr typ func * ctx_subst c) :=\n        match typeof_expr nil lem.(vars) lem.(concl).(lhs) with\n        | None => fun _ _ _ => None\n        | Some t =>\n          fun e ctx cs =>\n           let ctx' := CExs ctx lem.(vars) in\n           let cs' : ctx_subst ctx' := ExsSubst cs (amap_empty _) in\n           let (tus,tvs) := getEnvs ctx in\n           let nus := length tus in\n           let tus' := tus ++ lem.(vars) in\n           match\n             exprUnify 10 tus' tvs 0 (vars_to_uvars 0 nus lem.(concl).(lhs))\n                       e t cs'\n           with\n           | None => None\n           | Some cs'' =>\n             let prems :=\n                 List.map (fun e => GGoal (vars_to_uvars 0 nus e)) lem.(premises)\n             in\n             match\n               (SOLVEK tac) ctx' cs'' (GConj_list prems)\n             with\n             | Solved cs''' =>\n               match cs''' in ctx_subst ctx\n                     return match ctx with\n                            | CExs z _ => option (expr typ func * ctx_subst z)\n                            | _ => unit\n                            end\n               with\n               | ExsSubst cs'''' sub =>\n\t\t if amap_is_full (length lem.(vars)) sub then\n                   let res :=\n                       instantiate (fun u => amap_lookup u sub) 0\n                                   (vars_to_uvars 0 nus lem.(concl).(rhs))\n                   in\n                   Some (res, cs'''')\n                 else\n                   None\n               | _ => tt\n               end\n             | _ => None\n             end\n           end\n        end.\n\n    (** TODO: Move **)\n    Lemma lambda_exprD_weakenV\n    : forall (tus tvs : tenv typ) (e : expr typ func) (t : typ)\n             (val : exprT tus tvs (typD t)) (tvs' : list typ),\n        lambda_exprD tus tvs t e = Some val ->\n        exists val' : exprT tus (tvs ++ tvs') (typD t),\n          lambda_exprD tus (tvs ++ tvs') t e = Some val' /\\\n          (forall (us : hlist typD tus) (vs : hlist typD tvs)\n                  (vs' : hlist typD tvs'),\n              val us vs = val' us (hlist_app vs vs')).\n    Proof using RSymOk_func RTypeOk_typD Typ2Ok_Fun.\n      intros.\n      generalize (@exprD_weakenV typ _ (expr typ func) _ _ tus tvs tvs' e t val H).\n      eauto.\n    Qed.\n\n    (** TODO: Move **)\n    Lemma lambda_exprD_weakenU\n    : forall (tus tvs : tenv typ) (e : expr typ func) (t : typ)\n             (val : exprT tus tvs (typD t)) (tus' : list typ),\n        lambda_exprD tus tvs t e = Some val ->\n        exists val' : exprT (tus ++ tus') tvs (typD t),\n          lambda_exprD (tus ++ tus') tvs t e = Some val' /\\\n          (forall (us : hlist typD tus) (vs : hlist typD tvs)\n                  (us' : hlist typD tus'),\n              val us vs = val' (hlist_app us us') vs).\n    Proof using RSymOk_func RTypeOk_typD Typ2Ok_Fun.\n      intros.\n      generalize (@exprD_weakenU typ _ (expr typ func) _ _ tus tus' tvs e t val H).\n      eauto.\n    Qed.\n\n    Local Instance Subst_amap T : Subst (amap T) T :=\n      FMapSubst.SUBST.Subst_subst T.\n    Local Instance SubstOk_amap : SubstOk (amap (expr typ func)) typ (expr typ func) :=\n      @FMapSubst.SUBST.SubstOk_subst typ _ (expr typ func) _.\n\n    Opaque instantiate.\n\n    Lemma core_rewrite_lemma\n    : forall (ctx : Ctx typ (expr typ func)) (t0 : typ)\n               (x12 : amap (expr typ func)) (x13 : ctx_subst ctx)\n               (l : list typ) (y0 : exprT (getUVars ctx) l (typD t0)),\n        WellFormed_entry x13 (length l) x12 ->\n        forall (e : expr typ func) (t : tenv typ)\n               (y3 : exprT (getUVars ctx ++ l) t Prop)\n               (x5 : hlist (fun t1 : typ => exprT (getUVars ctx) t (typD t1)) l),\n          amap_substD (getUVars ctx ++ l) t x12 = Some y3 ->\n          amap_is_full (length l) x12 = true ->\n          (forall (us : hlist typD (getUVars ctx)) (vs : hlist typD t),\n              let us' :=\n                  hlist_map\n                    (fun (t1 : typ) (x : exprT (getUVars ctx) t (typD t1)) => x us vs) x5\n              in\n              y3 (hlist_app us us') vs) ->\n          lambda_exprD (getUVars ctx) l t0 e = Some y0 ->\n          exists e'D : exprT (getUVars ctx) t (typD t0),\n            lambda_exprD (getUVars ctx) t t0\n                   (instantiate (fun u : ExprI.uvar => amap_lookup u x12) 0\n                                (vars_to_uvars 0 (length (getUVars ctx)) e)) =\n            Some e'D /\\\n            (forall (us : hlist typD (getUVars ctx)) (vs : hlist typD t),\n                e'D us vs =\n                y0 us\n                   (hlist_map\n                      (fun (t1 : typ) (x6 : exprT (getUVars ctx) t (typD t1)) =>\n                         x6 us vs) x5)).\n    Proof using RType_typD RTypeOk_typD RSymOk_func Typ2Ok_Fun.\n      intros ctx t0 x12 x13 l y0 H40 e t y3 x5 Hamap_substD H4 H H13.\n      generalize (@vars_to_uvars_sound typ (expr typ func) _ _ _ _ _ _ _ e nil t0 l _ H13).\n      destruct 1 as [ ? [ ? ? ] ].\n      eapply ExprI.exprD_weakenV with (tvs':=t) in H0; eauto with typeclass_instances.\n      destruct H0 as [ ? [ ? ? ] ].\n      destruct (@instantiate_sound typ (expr typ func) _ _ _ (getUVars ctx++l) t\n                                   (fun u : ExprI.uvar => amap_lookup u x12)\n                                   (vars_to_uvars 0 (length (getUVars ctx)) e) nil t0 x0 y3).\n      { generalize (@sem_preserves_if_substD (amap (expr typ func)) typ (expr typ func) RType_typD Expr_expr _ _).\n        simpl. intro. eapply H3.\n        2: eapply Hamap_substD.\n        eapply WellFormed_entry_WellFormed_pre_entry in H40.\n        destruct H40. assumption. }\n      { eassumption. }\n      { destruct H3.\n        eapply exprD_strengthenU_multi in H3.\n        2: eauto with typeclass_instances.\n        { destruct H3 as [ ? [ ? ? ] ].\n          eexists; split; try eassumption.\n          intros.\n          specialize (H us vs).\n          specialize (H5 _ _ Hnil H).\n          simpl in *.\n          symmetry.\n          etransitivity; [ eapply (H1 _ _ Hnil) | ].\n          etransitivity; [ eapply H2 | ].\n          etransitivity; [ eapply H5 | ].\n          eapply H6. }\n        { intros.\n          clear H2 H1 H3 H5 H.\n          match goal with\n          | |- ?X = _ => consider X; try reflexivity; intro\n          end.\n          exfalso.\n          eapply mentionsU_instantiate in H.\n          assert (amap_lookup (length (getUVars ctx) + u) x12 <> None).\n          { clear - H4 H40 H6.\n            destruct H40.\n            clear H0.\n            red in H.\n            destruct H as [ ? [ ? ? ] ].\n            clear H H1.\n            generalize dependent (length (getUVars ctx)).\n            generalize dependent (length l).\n            intros.\n            eapply pigeon_principle; eauto. }\n          destruct H.\n          { destruct H. eauto. }\n          { destruct H. destruct H. destruct H as [ ? [ ? ? ] ].\n            destruct H40.\n            consider (amap_lookup (length (getUVars ctx) + u) x12); intros; try congruence.\n            eapply FMapSubst.SUBST.normalized_fmapsubst in H1.\n            3: eapply H.\n            cut (true = false); [ clear; intros; congruence | ].\n            rewrite <- H3. rewrite <- H1. reflexivity.\n            destruct H5. assumption. } } }\n    Qed.\n\n    (* TODO(gmalecha): This is not a nice interface! *)\n    Theorem core_rewrite_sound\n    : forall ctx (cs : ctx_subst ctx),\n        let tus := getUVars ctx in\n        let tvs := getVars ctx in\n        forall l0 r0 e e' cs',\n          WellFormed_rtacK r0 ->\n          core_rewrite l0 r0 e cs = Some (e', cs') ->\n          WellFormed_ctx_subst cs ->\n          WellFormed_ctx_subst cs' /\\\n          (forall (Hlem : lemmaD (rw_conclD RbaseD) nil nil l0)\n                  (Hrtac :           rtacK_sound r0),\n           forall (t : typ) (rD : typD t -> typD t -> Prop),\n              RD RbaseD (rel (concl l0)) t = Some rD ->\n              match pctxD cs with\n              | Some _ =>\n                match lambda_exprD tus tvs t e with\n                | Some eD =>\n                  match pctxD cs' with\n                  | Some csD' =>\n                    match lambda_exprD tus tvs t e' with\n                    | Some eD' =>\n                      SubstMorphism cs cs' /\\\n                      (forall (us : hlist typD (getAmbientUVars ctx))\n                              (vs : hlist typD (getAmbientVars ctx)),\n                          csD'\n                            (fun (us0 : hlist typD (getUVars ctx))\n                                 (vs0 : hlist typD (getVars ctx)) =>\n                               rD (eD us0 vs0) (eD' us0 vs0)) us vs)\n                    | None => False\n                    end\n                  | None => False\n                  end\n                | None => True\n                end\n              | None => True\n              end).\n    Proof using RelDec_Correct_eq_typ RbaseD_single_type\n          RTypeOk_typD RSymOk_func Typ2Ok_Fun.\n      Opaque vars_to_uvars.\n      unfold core_rewrite. generalize dependent 10.\n      simpl.\n      intros.\n      consider (typeof_expr nil l0.(vars) l0.(concl).(lhs)); intros.\n      { rewrite getEnvs_getUVars_getVars in *.\n        match goal with\n        | H : match ?X with _ => _ end = _ |- _ =>\n          consider X; intros\n        end; try match goal with\n                 | H : None = Some _ |- _ => exfalso ; clear - H ; inversion H\n                 end.\n        assert (WellFormed_rtacK (SOLVEK r0)).\n        { apply WF_SOLVEK. assumption. }\n        clear H; rename H4 into H.\n        match goal with\n        | Hrt : WellFormed_rtacK ?X , _ : match ?X ?C ?CS ?G with _ => _ end = _ |- _ =>\n          specialize (@Hrt C CS G _ eq_refl)\n        end.\n        match goal with\n        | Hrt : rtacK_spec_wf _ _ ?X , H : match ?Y with _ => _ end = _ |- _ =>\n          replace Y with X in H ; [ destruct X eqn:?; intros | f_equal ]\n        end; try congruence.\n        rewrite (ctx_subst_eta c0) in H3.\n        repeat match goal with\n               | H : match ?X with _ => _ end = _ |- _ =>\n                 let H' := fresh in\n                 destruct X eqn:H'; [ | solve [ exfalso; clear - H3; inversion H3 ] ]\n               end.\n        inv_all. subst.\n        destruct (@exprUnify_sound (ctx_subst (CExs ctx (vars l0))) typ func _ _ _ _ _ _ _ _ _ _ n\n                                   _ _ _ _ _ _ _ nil H2).\n        { constructor; eauto using WellFormed_entry_amap_empty. }\n        split.\n        { red in H.\n          assert (WellFormed_Goal (getUVars (CExs ctx (vars l0)))\n                                  (getVars (CExs ctx (vars l0)))\n                                  (GConj_list\n                                     (map\n                                        (fun e : expr typ func =>\n                                           GGoal (vars_to_uvars 0 (length (getUVars ctx)) e))\n                                        (premises l0)))).\n          { eapply WellFormed_Goal_GConj_list. clear.\n            induction (premises l0); simpl.\n            - constructor.\n            - constructor; eauto. constructor. }\n          specialize (H H6 H3); clear H6.\n          rewrite (ctx_subst_eta c0) in H.\n          inv_all. auto. }\n        clear H. intro. intro H.\n        assert (rtacK_sound (SOLVEK r0)).\n        { apply SOLVEK_sound. assumption. }\n        clear H; rename H6 into H.\n        intros.\n        destruct (pctxD cs) eqn:HpctxDcs; trivial.\n        destruct (lambda_exprD (getUVars ctx) (getVars ctx) t0 e) eqn:Hlambda_exprDe; trivial.\n        simpl in *.\n        eapply lemmaD_lemmaD' in Hlem. forward_reason.\n        eapply lemmaD'_weakenU with (tus':=getUVars ctx) in H7;\n          eauto using ExprOk_expr, rw_concl_weaken.\n        simpl in H7. forward_reason.\n        unfold lemmaD' in H7.\n        forwardy. inv_all. subst.\n        unfold rw_conclD in H10.\n        forwardy. inv_all; subst.\n        assert (t0 = t).\n        { revert H0.\n          assert (y1 = t0).\n          { eapply RD_single_type; eauto. }\n          subst t0.\n          intro.\n          eapply ExprFacts.typeof_expr_weaken with (tus':=getUVars ctx) (tvs':=nil) in H0; eauto.\n          simpl in H0. rewrite H10 in H0. inv_all; auto. }\n        subst.\n        assert (y1 = t).\n        { revert H13. revert H6.\n          intros. eapply RD_single_type; eauto. }\n        subst t. rename y1 into t.\n        generalize (fun tus tvs e t => @ExprI.exprD_conv typ _ (expr typ func)\n                                          _ tus tus (tvs ++ nil) tvs e t eq_refl\n                                          (eq_sym (app_nil_r_trans _))). simpl.\n        intro Hlambda_exprD_conv.\n        rewrite Hlambda_exprD_conv in H12. autorewrite_with_eq_rw_in H12.\n        rewrite Hlambda_exprD_conv in H11. autorewrite_with_eq_rw_in H11.\n        forwardy. inv_all. subst.\n\n        generalize (@vars_to_uvars_sound typ (expr typ func) _ _ _ _ _ _ _ _ nil _ _ _ H11).\n        simpl. destruct 1 as [ ? [ Hlambda_exprDe_subst ? ] ].\n        eapply lambda_exprD_weakenV with (tvs':=getVars ctx) in Hlambda_exprDe_subst; eauto.\n        simpl in Hlambda_exprDe_subst. forward_reason.\n        intros; subst.\n        replace (length (getUVars ctx ++ t :: nil))\n           with (S (length (getUVars ctx))) in H15\n             by (rewrite app_length; simpl; omega).\n        eapply lambda_exprD_weakenU\n          with (tus':=l0.(vars)) in Hlambda_exprDe; eauto.\n        destruct (drop_exact_append_exact (vars l0) (getUVars ctx)) as [ ? [ Hx ? ] ].\n        rewrite Hx in *; clear Hx.\n        destruct (pctxD_substD H1 HpctxDcs) as [ ? [ Hx ? ] ].\n        rewrite Hx in *; clear Hx.\n        destruct Hlambda_exprDe as [ ? [ Hx ? ] ].\n        specialize (H5 _ _ _ H15 Hx eq_refl).\n        clear Hx.\n        forward_reason.\n        generalize (pctxD_SubstMorphism_progress H5).\n        simpl. rewrite HpctxDcs.\n        intro Hx; specialize (Hx _ eq_refl). destruct Hx.\n        red in H.\n        replace (getUVars ctx ++ vars l0)\n           with (getUVars (CExs ctx (vars l0)))\n             in Heqr\n             by reflexivity.\n        eapply (H (CExs ctx (vars l0))) in Heqr. red in Heqr.\n        destruct Heqr; eauto.\n        { clear. induction (premises l0); simpl. constructor.\n          destruct l; simpl. constructor.\n          constructor. constructor. eauto. }\n        rewrite H22 in *.\n        assert (exists Ps,\n                   goalD (getUVars ctx ++ vars l0) (getVars ctx)\n                         (GConj_list\n                            (map\n                               (fun e2 : expr typ func =>\n                                  GGoal (vars_to_uvars 0 (length (getUVars ctx)) e2))\n                               (premises l0))) = Some Ps /\\\n                   forall (us : hlist typD (getUVars ctx)) us' vs,\n                     Ps (hlist_app us us') vs <->\n                     Forall (fun y => y us (hlist_app us' Hnil)) y).\n        { revert H7.\n          destruct l0. simpl in *.\n          clear - RTypeOk_typD RSymOk_func Typ2Ok_Fun.\n          intros.\n          cut (exists Ps : exprT (getUVars ctx ++ vars) (getVars ctx) Prop,\n                  goalD (getUVars ctx ++ vars) (getVars ctx)\n                        (GConj_list_simple\n                           (map\n                              (fun e2 : expr typ func =>\n                                 GGoal (vars_to_uvars 0 (length (getUVars ctx)) e2))\n                              premises)) = Some Ps /\\\n                  (forall (us : hlist typD (getUVars ctx)) (us' : hlist typD vars)\n                          (vs : hlist typD (getVars ctx)),\n                      Ps (hlist_app us us') vs <->\n                      Forall\n                        (fun\n                            y0 : hlist typD (getUVars ctx) ->\n                                 hlist typD (vars ++ nil) -> Prop =>\n                            y0 us (hlist_app us' Hnil)) y)).\n          { destruct (goalD_GConj_list_GConj_list_simple\n                        (getUVars ctx ++ vars) (getVars ctx)\n                        (map (fun e2 : expr typ func =>\n                                GGoal (vars_to_uvars 0 (length (getUVars ctx)) e2))\n                           premises)).\n            { intros; forward_reason; congruence. }\n            { intros; forward_reason.\n              inv_all. subst. eexists; split; eauto.\n              intros.\n              rewrite <- H1. eapply H.\n              reflexivity. reflexivity. } }\n          revert H7. revert y.\n          induction premises; simpl; intros.\n          { eexists; split; eauto.\n            simpl. inv_all. subst.\n            split; eauto. }\n          { simpl in *.\n            forwardy. inv_all. subst.\n            unfold exprD_typ0 in H.\n            simpl in H. forwardy.\n            generalize (@vars_to_uvars_sound typ (expr typ func) _ _ _ _ _ _ _ _ nil _ _ _ H).\n            intro. forward_reason.\n            unfold propD, exprD_typ0.\n            simpl in H2.\n            eapply lambda_exprD_weakenV\n              with (tvs':=getVars ctx)\n                in H2; eauto.\n            forward_reason. simpl in H2.\n            generalize (@exprD_conv typ _ (expr typ func) _); eauto. simpl.\n            intro Hx.\n            rewrite Hx\n               with (pfu:=f_equal _ (eq_sym (app_nil_r_trans _))) (pfv:=eq_refl)\n                 in H2.\n            autorewrite_with_eq_rw_in H2.\n            forwardy.\n            rewrite H2.\n            specialize (IHpremises _ H0).\n            forward_reason. rewrite H6.\n            eexists; split; eauto. simpl.\n            intros.\n            inv_all. subst.\n            intros. rewrite Forall_cons_iff.\n            rewrite <- (H7 _ _ vs).\n            autorewrite with eq_rw.\n            specialize (H3 us (hlist_app us' Hnil) Hnil).\n            simpl in *.\n            rewrite H3; clear H3.\n            erewrite (H4 (hlist_app us (hlist_app us' Hnil)) Hnil vs); clear H4.\n            simpl. rewrite hlist_app_nil_r.\n            unfold f_equal.\n            autorewrite with eq_rw.\n            clear.\n            generalize (app_nil_r_trans vars).\n            generalize dependent (vars ++ nil).\n            intros; subst. reflexivity. } }\n        destruct H25 as [ ? [ Hx ? ] ].\n        change_rewrite Hx in H24; clear Hx.\n        forwardy.\n        rewrite (ctx_subst_eta c0) in H24.\n        simpl in H24.\n        forwardy. rewrite H27.\n        inv_all; subst.\n        destruct (amap_substD_amap_empty (getUVars ctx ++ vars l0)\n                                         (getVars ctx)) as [ ? [ Hx ? ] ].\n          change_rewrite Hx in H5; clear Hx.\n        rewrite HpctxDcs in H5.\n        simpl in *.\n        destruct (drop_exact_append_exact l0.(vars) (getUVars ctx)) as [ ? [ Hx ? ] ];\n          rewrite Hx in *; clear Hx.\n        destruct H26.\n        inv_all. subst.\n        forwardy.\n        repeat match goal with\n               | H : ?X = _ , H' : ?X = _ |- _ => rewrite H in H'\n               end.\n        forward_reason; inv_all; subst.\n        simpl in *.\n        rewrite H5 in *.\n        rewrite H3 in *.\n        rewrite H27 in *.\n        rewrite H24 in *.\n        inv_all.\n        forwardy.\n        generalize H24. intro Hamap_substD.\n        eapply subst_getInstantiation in H24;\n          eauto using WellFormed_entry_WellFormed_pre_entry\n                 with typeclass_instances.\n        destruct H24.\n        assert (exists e'D,\n                   lambda_exprD (getUVars ctx) (getVars ctx) t\n                          (instantiate (fun u : ExprI.uvar => amap_lookup u x12)\n                                       0 (vars_to_uvars 0 (length (getUVars ctx)) l0.(concl).(rhs))) = Some e'D /\\\n                   forall us vs,\n                     e'D us vs =\n                     y0 us (hlist_map\n                              (fun (t : typ) (x6 : exprT (getUVars ctx) (getVars ctx) (typD t)) =>\n                                 x6 us vs) x5)).\n        { eapply core_rewrite_lemma; eauto. }\n        destruct H20 as [ ? [ Hx ? ] ]; rewrite Hx; clear Hx.\n        split.\n        { etransitivity; eassumption. }\n        intros.\n        eapply pctxD_substD' with (us:=us) (vs:=vs) in H38; eauto with typeclass_instances.\n        gather_facts.\n        eapply pctxD_SubstMorphism; [ | | eauto | ]; eauto.\n        gather_facts.\n        eapply pctxD_SubstMorphism; [ | | eauto | ]; eauto.\n        gather_facts.\n        eapply Pure_pctxD; eauto. intros.\n        specialize (H20 us0 vs0).\n        specialize (H6 us0 vs0).\n        generalize dependent (hlist_map\n           (fun (t : typ) (x6 : exprT (getUVars ctx) (getVars ctx) (typD t)) =>\n            x6 us0 vs0) x5); simpl; intros.\n        rewrite H20; clear H20.\n        generalize H6.\n        eapply H24 in H6; clear H24.\n        specialize (H29 us0 h).\n        clear - H19 H16 H14 H17 H25 H28 H21 H9 H18 H22 H23 H26 H6 H8 H29.\n        eapply H9 in H8; clear H9.\n        rewrite foralls_sem in H8.\n        specialize (H8 h).\n        setoid_rewrite impls_sem in H8.\n        rewrite Quant._forall_sem in H26.\n        repeat match goal with\n               | H : (forall x : hlist _ _ , _) , H' : hlist _ _ |- _ =>\n                 specialize (H H')\n               end.\n        specialize (H16 (hlist_app us0 h) Hnil vs0).\n        specialize (H21 (hlist_app us0 h) vs0).\n        rewrite H19; clear H19.\n        rewrite H29 in *; clear H29.\n        destruct H21; auto.\n        specialize (H0 Hnil). simpl in H0.\n        rewrite <- H0; clear H0.\n        simpl in *.\n        rewrite <- H16; clear H16.\n        rewrite <- H14; clear H14.\n        simpl.\n        revert H8.\n        instantiate (1:= us0).\n        autorewrite_with_eq_rw.\n        rewrite hlist_app_nil_r.\n        autorewrite_with_eq_rw.\n        intros. apply H8; clear H8.\n        eapply List.Forall_map.\n        eapply H26 in H0; clear H26.\n        eapply H25 in H0; clear H25.\n        revert H0.\n        eapply Forall_impl. clear.\n        intros.\n        rewrite <- hlist_app_nil_r.\n        assumption. }\n      { exfalso; clear - H2; inversion H2. }\n    Time Qed.\n\n    Theorem core_rewrite_soundX\n    : forall ctx (cs : ctx_subst ctx),\n        let tus := getUVars ctx in\n        let tvs := getVars ctx in\n        forall l0 r0 e e' cs'\n          (Hlem  : lemmaD (rw_conclD RbaseD) nil nil l0)\n          (Hrtac : rtacK_sound r0),\n          core_rewrite l0 r0 e cs = Some (e', cs') ->\n          WellFormed_ctx_subst cs ->\n          WellFormed_ctx_subst cs' /\\\n          (forall (t : typ) (rD : typD t -> typD t -> Prop),\n              RD RbaseD (rel (concl l0)) t = Some rD ->\n              match pctxD cs with\n              | Some _ =>\n                match lambda_exprD tus tvs t e with\n                | Some eD =>\n                  match pctxD cs' with\n                  | Some csD' =>\n                    match lambda_exprD tus tvs t e' with\n                    | Some eD' =>\n                      SubstMorphism cs cs' /\\\n                      (forall (us : hlist typD (getAmbientUVars ctx))\n                              (vs : hlist typD (getAmbientVars ctx)),\n                          csD'\n                            (fun (us0 : hlist typD (getUVars ctx))\n                                 (vs0 : hlist typD (getVars ctx)) =>\n                               rD (eD us0 vs0) (eD' us0 vs0)) us vs)\n                    | None => False\n                    end\n                  | None => False\n                  end\n                | None => True\n                end\n              | None => True\n              end).\n    Proof using RelDec_Correct_eq_typ RbaseD_single_type\n          RTypeOk_typD RSymOk_func Typ2Ok_Fun.\n      Opaque vars_to_uvars.\n      intros.\n      eapply core_rewrite_sound in H; eauto using rtacK_sound_WellFormed_rtacK.\n      forward_reason.\n      split; eauto.\n    Qed.\n\n  End core_rewrite.\n\n  (* This section implements the re-indexing operation\n   * to run [rtac]'s from [mrw]. Note that the main thing to do\n   * is extend the context with any extra variables and re-index\n   * variables in the term since they are in the opposite order.\n   *)\n  Section reindexing.\n    (* This has to do with converting expressions for tactics *)\n    Let _lookupU (u : ExprI.uvar) : option (expr typ func) := None.\n    Let _lookupV (under : nat) (above : nat) (v : ExprI.var)\n    : option (expr typ func) :=\n      Some (Var (if v ?[ ge ] under\n                 then v - under\n                 else v + above)).\n\n    Definition expr_convert (u : nat) (above : nat)\n    : expr typ func -> expr typ func :=\n      expr_subst _lookupU (_lookupV u above) 0.\n\n\n    Lemma expr_convert_sound\n    : forall tus tvs tvs' e t eD,\n        lambda_exprD tus (tvs ++ tvs') t e = Some eD ->\n        exists eD',\n          lambda_exprD tus (tvs' ++ tvs) t (expr_convert (length tvs) (length tvs') e) = Some eD' /\\\n          forall a b c,\n            eD a (hlist_app b c) = eD' a (hlist_app c b).\n    Proof using RSymOk_func RTypeOk_typD Typ2Ok_Fun.\n      unfold expr_convert.\n      intros.\n      destruct (fun Hu Hv => @ExprI.expr_subst_sound\n                    typ _ (expr typ func) Expr_expr _\n                    _lookupU\n                    (_lookupV (length tvs) (length tvs'))\n                    0 e _ eq_refl nil\n                    tus (tvs ++ tvs') tus (tvs' ++ tvs)\n                    (fun us vs us' vs' =>\n                       us = us' /\\\n                       let (_vs,_vs') := hlist_split _ _ vs in\n                       let (__vs,__vs') := hlist_split _ _ vs' in\n                       _vs = __vs' /\\ _vs' = __vs) Hu Hv t _ eq_refl H).\n      { simpl. clear.\n        intros. eexists; split; eauto.\n        intros. destruct H1; subst; auto. }\n      { simpl. intros.\n        autorewrite with exprD_rw. simpl.\n        consider (u ?[ ge ] length tvs); intros.\n        { eapply nth_error_get_hlist_nth_appR in H1; eauto.\n          simpl in H1. forward_reason.\n          eapply nth_error_get_hlist_nth_weaken with (ls':=tvs) in H1.\n          simpl in H1.\n          forward_reason. rewrite H1.\n          rewrite type_cast_refl; eauto.\n          eexists; split; eauto.\n          unfold Rcast_val, Rcast, Relim. simpl.\n          intros.\n          revert H5.\n          rewrite <- (hlist_app_hlist_split _ _ vs).\n          rewrite <- (hlist_app_hlist_split _ _ vs').\n          rewrite hlist_split_hlist_app.\n          rewrite hlist_split_hlist_app.\n          destruct 1.\n          rewrite H3. rewrite <- H4.\n          f_equal. tauto. }\n        { assert (u < length tvs) by omega.\n          eapply nth_error_get_hlist_nth_appL in H3.\n          destruct H3. destruct H3.\n          rewrite H3 in H1.\n          assert (u + length tvs' >= length tvs') by omega.\n          destruct H4 as [ ? [ ? ? ] ].\n          eapply nth_error_get_hlist_nth_appR' in H4; simpl in H4.\n          destruct H4 as [ ? [ ? ? ] ].\n          rewrite H4.\n          inv_all. subst. simpl.\n          rewrite type_cast_refl; eauto.\n          eexists; split; eauto.\n          intros us vs us' vs'.\n          rewrite <- (hlist_app_hlist_split _ _ vs).\n          rewrite <- (hlist_app_hlist_split _ _ vs').\n          rewrite hlist_split_hlist_app.\n          rewrite hlist_split_hlist_app.\n          destruct 1.\n          simpl in *.\n          rewrite H6. rewrite <- H7.\n          unfold Rcast_val, Rcast; simpl. f_equal. tauto. } }\n      { simpl in H0.\n        destruct H0; eexists; split; eauto.\n        intros. apply (H1 a (hlist_app b c) a (hlist_app c b) Hnil).\n        split; auto.\n        do 2 rewrite hlist_split_hlist_app.\n        tauto. }\n    Qed.\n\n    (* This code starts to build the structure necessary for [rtac]\n     *)\n    Fixpoint wrap_tvs (tvs : tenv typ) (ctx : Ctx typ (expr typ func))\n    : Ctx typ (expr typ func) :=\n      match tvs with\n      | nil => ctx\n      | t :: tvs' => wrap_tvs tvs' (CAll ctx t)\n      end.\n\n    Fixpoint wrap_tvs_ctx_subst tvs ctx (cs : ctx_subst ctx)\n    : ctx_subst (wrap_tvs tvs ctx) :=\n      match tvs as tvs return ctx_subst (wrap_tvs tvs ctx) with\n      | nil => cs\n      | t :: tvs => wrap_tvs_ctx_subst _ (AllSubst cs)\n      end.\n\n    Fixpoint unwrap_tvs_ctx_subst T tvs ctx\n    : ctx_subst (wrap_tvs tvs ctx) -> (ctx_subst ctx -> T) -> T :=\n      match tvs as tvs\n            return ctx_subst (wrap_tvs tvs ctx) -> (ctx_subst ctx -> T) -> T\n      with\n      | nil => fun cs k => k cs\n      | t :: tvs => fun cs k =>\n        @unwrap_tvs_ctx_subst T tvs (CAll ctx t) cs (fun z => k (fromAll z))\n      end.\n\n    (* TODO(gmalecha): This does not have a stand-alone soundness theorem,\n     * which is problematic because it does some quite complex manipulation.\n     *)\n    Definition for_tactic\n               (m : expr typ func ->\n                    forall ctx : Ctx typ (expr typ func),\n                      ctx_subst ctx -> option (expr typ func * ctx_subst ctx))\n    : expr typ func -> mrw typ func (expr typ func) :=\n      fun e tvs' ctx cs =>\n        let under := length tvs' in\n        let nvs := countVars ctx in\n        let e' := expr_convert under nvs e in\n        match\n          m e' _ (@wrap_tvs_ctx_subst tvs' ctx cs)\n        with\n        | None => None\n        | Some (v,cs') =>\n          Some (expr_convert nvs under v,\n                @unwrap_tvs_ctx_subst _ tvs' ctx cs' (fun x => x))\n        end.\n\n    (* TODO(gmalecha): This should go in a new file that implements\n     * rewriting databases.\n     *)\n    Fixpoint using_rewrite_db'\n             (ls : list (rw_lemma typ func Rbase * rtacK typ (expr typ func)))\n    : expr typ func -> R ->\n      forall ctx, ctx_subst ctx -> option (expr typ func * ctx_subst ctx) :=\n      match ls with\n      | nil => fun _ _ _ _ => None\n      | (lem,tac) :: ls =>\n        let res := using_rewrite_db' ls in\n        let crw := core_rewrite lem tac in\n        fun e r ctx cs =>\n          if Req_dec Rbase_eq r lem.(concl).(rel) then\n            match crw e _ cs with\n            | None => res e r ctx cs\n            | X => X\n            end\n          else res e r ctx cs\n      end.\n\n    Lemma using_rewrite_db'_sound\n    : forall r ctx (cs : ctx_subst ctx),\n        let tus := getUVars ctx in\n        let tvs := getVars ctx in\n        forall hints : list (rw_lemma typ func Rbase * rtacK typ (expr typ func)),\n        Forall (fun lt =>\n                  lemmaD (rw_conclD RbaseD) nil nil (fst lt) /\\\n                  rtacK_sound (snd lt)) hints ->\n        forall e e' cs',\n          @using_rewrite_db' hints e r ctx cs = Some (e', cs') ->\n          WellFormed_ctx_subst cs ->\n          WellFormed_ctx_subst cs' /\\\n          (forall (t : typ) (rD : typD t -> typD t -> Prop),\n              RD RbaseD r t = Some rD ->\n              match pctxD cs with\n              | Some _ =>\n                match lambda_exprD tus tvs t e with\n                | Some eD =>\n                  match pctxD cs' with\n                  | Some csD' =>\n                    match lambda_exprD tus tvs t e' with\n                    | Some eD' =>\n                      SubstMorphism cs cs' /\\\n                      (forall (us : hlist typD (getAmbientUVars ctx))\n                              (vs : hlist typD (getAmbientVars ctx)),\n                          csD'\n                            (fun (us0 : hlist typD (getUVars ctx))\n                                 (vs0 : hlist typD (getVars ctx)) =>\n                                 rD (eD us0 vs0)\n                                    (eD' us0 vs0)) us vs)\n                    | None => False\n                    end\n                  | None => False\n                  end\n                | None => True\n                end\n              | None => True\n              end).\n    Proof using RSymOk_func RTypeOk_typD RbaseD_single_type Rbase_eq_ok RelDec_Correct_eq_typ Typ2Ok_Fun.\n      induction 1.\n      { simpl. inversion 1. }\n      { simpl. intros. destruct x.\n        assert (using_rewrite_db' l e r cs = Some (e',cs')\n             \\/ (r = l0.(concl).(rel) /\\\n                 core_rewrite l0 r0 e cs = Some (e',cs'))).\n        { generalize (Req_dec_ok Rbase_eq Rbase_eq_ok r l0.(concl).(rel)).\n          destruct (Req_dec Rbase_eq r l0.(concl).(rel)); eauto.\n          intros. destruct (core_rewrite l0 r0 e cs); eauto. }\n        clear H1. destruct H3; eauto.\n        destruct H1. subst. clear IHForall H0.\n        simpl in H. destruct H.\n        revert H2. revert H3. revert H. revert H0.\n        intros.\n        eapply core_rewrite_sound in H3; eauto using rtacK_sound_WellFormed_rtacK.\n        forward_reason. eauto. }\n    Qed.\n\n    Section using_prewrite_db.\n      Variable phints : expr typ func -> R -> list (rw_lemma typ func Rbase * rtacK typ (expr typ func)).\n\n      Definition using_prewrite_db' :=\n        fun e r => using_rewrite_db' (phints e r) e r.\n\n      Lemma using_prewrite_db_sound'\n      : forall r ctx (cs : ctx_subst ctx),\n          let tus := getUVars ctx in\n          let tvs := getVars ctx in\n          forall e e' cs',\n            @using_prewrite_db' e r ctx cs = Some (e', cs') ->\n            forall (Hrtac_wf : forall e r,\n                       Forall (fun lt => WellFormed_rtacK (snd lt)) (phints e r)),\n            WellFormed_ctx_subst cs ->\n            WellFormed_ctx_subst cs' /\\\n            ((forall e r tus tvs t eD,\n                 lambda_exprD tus tvs t e = Some eD ->\n                 Forall (fun lt =>\n                           lemmaD (rw_conclD RbaseD) nil nil (fst lt) /\\\n                           rtacK_sound (snd lt)) (phints e r)) ->\n             (forall (t : typ) (rD : typD t -> typD t -> Prop),\n                 RD RbaseD r t = Some rD ->\n                 match pctxD cs with\n                 | Some _ =>\n                   match lambda_exprD tus tvs t e with\n                   | Some eD =>\n                     match pctxD cs' with\n                     | Some csD' =>\n                       match lambda_exprD tus tvs t e' with\n                       | Some eD' =>\n                         SubstMorphism cs cs' /\\\n                         (forall (us : hlist typD (getAmbientUVars ctx))\n                                 (vs : hlist typD (getAmbientVars ctx)),\n                             csD'\n                               (fun (us0 : hlist typD (getUVars ctx))\n                                    (vs0 : hlist typD (getVars ctx)) =>\n                                  rD (eD us0 vs0)\n                                     (eD' us0 vs0)) us vs)\n                       | None => False\n                       end\n                     | None => False\n                     end\n                   | None => True\n                   end\n                 | None => True\n                 end)).\n      Proof using RSymOk_func RTypeOk_typD RbaseD_single_type\n            Rbase_eq_ok RelDec_Correct_eq_typ Typ2Ok_Fun.\n        simpl.\n        unfold using_prewrite_db'.\n        intros r ctx cs e. revert cs.\n        cut (forall (cs : ctx_subst ctx) (e' : expr typ func) (cs' : ctx_subst ctx),\n                using_rewrite_db' (phints e r) e r cs =\n                Some (e', cs') ->\n                (Forall\n                   (fun lt : rw_lemma typ func Rbase * rtacK typ (expr typ func) =>\n                      WellFormed_rtacK (snd lt)) (phints e r)) ->\n                WellFormed_ctx_subst cs ->\n                WellFormed_ctx_subst cs' /\\\n                ((forall (tus tvs : tenv typ)\n                         (t : typ) (eD : exprT tus tvs (typD t)),\n                     lambda_exprD tus tvs t e = Some eD ->\n                     Forall\n                       (fun\n                           lt : lemma typ (expr typ func) (rw_concl typ func Rbase) *\n                                rtacK typ (expr typ func) =>\n                           lemmaD (rw_conclD RbaseD) nil nil (fst lt) /\\ rtacK_sound (snd lt))\n                       (phints e r)) ->\n                 forall (t : typ) (rD : typD t -> typD t -> Prop),\n                   RD RbaseD r t = Some rD ->\n                   match pctxD cs with\n                   | Some _ =>\n                     match lambda_exprD (getUVars ctx) (getVars ctx) t e with\n                     | Some eD =>\n                       match pctxD cs' with\n                       | Some csD' =>\n                         match lambda_exprD (getUVars ctx) (getVars ctx) t e' with\n                         | Some eD' =>\n                           SubstMorphism cs cs' /\\\n                           (forall (us : hlist typD (getAmbientUVars ctx))\n                                   (vs : hlist typD (getAmbientVars ctx)),\n                               csD'\n                                 (fun (us0 : hlist typD (getUVars ctx))\n                                      (vs0 : hlist typD (getVars ctx)) =>\n                                    rD (eD us0 vs0) (eD' us0 vs0)) us vs)\n                         | None => False\n                         end\n                       | None => False\n                       end\n                     | None => True\n                     end\n                   | None => True\n                   end)).\n        { clear.\n          intros; forward_reason.\n          eapply H in H0; eauto.\n          forward_reason. split; eauto.\n          intros.\n          eapply H2; eauto. }\n        induction (phints e r).\n        { inversion 1. }\n        { simpl. intros.\n          destruct a.\n          assert (using_rewrite_db' l e r cs = Some (e',cs')\n                  \\/ (r = r0.(concl).(rel) /\\\n                      core_rewrite r0 r1 e cs = Some (e',cs'))).\n          { generalize (Req_dec_ok Rbase_eq Rbase_eq_ok r r0.(concl).(rel)).\n            destruct (Req_dec Rbase_eq r r0.(concl).(rel)); eauto.\n            intros. destruct (core_rewrite r0 r1 e cs); eauto. }\n          clear H.\n          destruct H2.\n          { eapply IHl in H; clear IHl; eauto.\n            forward_reason. split; eauto.\n            intros. eapply H2; eauto.\n            intros. eapply H3 in H5; eauto. inversion H5; eauto.\n            inversion H0; auto. }\n          { forward_reason. subst.\n            split.\n            { eapply core_rewrite_sound in H2; eauto.\n              forward_reason; eauto.\n              inversion H0; trivial. }\n            { intros. forward.\n              specialize (H _ _ _ _ H5).\n              inversion H; clear H; subst; forward_reason.\n              eapply core_rewrite_sound in H1; eauto.\n              forward_reason; eauto.\n              eapply H7 in H3.\n              revert H3.\n              Cases.rewrite_all_goal.\n              trivial.\n              inversion H0; trivial. } } }\n      Qed.\n\n    End using_prewrite_db.\n\n    Definition using_rewrite_db''\n               (ls : list (rw_lemma typ func Rbase * rtacK typ (expr typ func)))\n    : expr typ func -> R -> mrw typ func (expr typ func) :=\n      let rw_db := using_rewrite_db' ls in\n      fun e r => for_tactic (fun e => rw_db e r) e.\n\n    Definition using_prewrite_db''\n        (lems : expr typ func -> R -> list (rw_lemma typ func Rbase * rtacK typ (expr typ func)))\n    : expr typ func -> R -> mrw typ func (expr typ func) :=\n      fun e r =>\n        for_tactic (fun e => using_rewrite_db' (lems e r) e r) e.\n\n    Lemma getAmbientUVars_wrap_tvs : forall tvs ctx,\n        getAmbientUVars (wrap_tvs tvs ctx) = getAmbientUVars ctx.\n    Proof using.\n      induction tvs; simpl. reflexivity.\n      intros. rewrite IHtvs. reflexivity.\n    Defined.\n\n    Lemma getAmbientVars_wrap_tvs : forall tvs ctx,\n        getAmbientVars (wrap_tvs tvs ctx) = getAmbientVars ctx.\n    Proof using.\n      induction tvs; simpl. reflexivity.\n      intros. rewrite IHtvs. reflexivity.\n    Defined.\n\n    Lemma getVars_wrap_tvs : forall tvs' ctx,\n        getVars (wrap_tvs tvs' ctx) = getVars ctx ++ tvs'.\n    Proof using.\n      induction tvs'; simpl; eauto.\n      symmetry. eapply app_nil_r_trans.\n      simpl. intros. rewrite IHtvs'. simpl.\n      rewrite app_ass_trans. reflexivity.\n    Defined.\n\n    Lemma WellFormed_ctx_subst_unwrap_tvs\n    : forall tvs' ctx ctx' (cs : ctx_subst _)\n             (k : ctx_subst (Ctx_append ctx ctx') -> ctx_subst ctx),\n        (forall cs, WellFormed_ctx_subst cs -> WellFormed_ctx_subst (k cs)) ->\n        WellFormed_ctx_subst cs ->\n        WellFormed_ctx_subst\n          (@unwrap_tvs_ctx_subst (ctx_subst ctx) tvs' (Ctx_append ctx ctx') cs k).\n    Proof using.\n      induction tvs'; simpl; auto.\n      intros. specialize (IHtvs' ctx (CAll ctx' a) cs).\n      simpl in *. eapply IHtvs'; eauto.\n      intros. eapply H. rewrite (ctx_subst_eta cs0) in H1.\n      inv_all. assumption.\n    Qed.\n\n    Fixpoint unwrap_tvs_ctx_subst' (tvs : tenv typ) (ctx : Ctx typ (expr typ func))\n    : ctx_subst (wrap_tvs tvs ctx) -> ctx_subst ctx :=\n      match tvs as tvs return ctx_subst (wrap_tvs tvs ctx) -> ctx_subst ctx with\n      | nil => fun X => X\n      | t :: tvs => fun X => fromAll (unwrap_tvs_ctx_subst' tvs _ X)\n      end.\n\n    Theorem unwrap_tvs_ctx_subst_unwrap_tvs_ctx_subst'\n    : forall T tvs ctx cs (k : _ -> T),\n        k (@unwrap_tvs_ctx_subst' tvs ctx cs) =\n        unwrap_tvs_ctx_subst tvs cs k.\n    Proof using.\n      induction tvs; simpl. auto.\n      intros. rewrite <- IHtvs. reflexivity.\n    Qed.\n\n    Lemma getUVars_wrap_tvs\n    : forall tvs' ctx, getUVars (wrap_tvs tvs' ctx) = getUVars ctx.\n    Proof using.\n      induction tvs'; simpl; auto.\n      intros.  rewrite IHtvs'. reflexivity.\n    Defined.\n\n    Lemma WellFormed_ctx_subst_wrap_tvs : forall tvs' ctx (cs : ctx_subst ctx),\n        WellFormed_ctx_subst cs ->\n        WellFormed_ctx_subst (wrap_tvs_ctx_subst tvs' cs).\n    Proof using.\n      induction tvs'; simpl; auto.\n      intros. eapply IHtvs'. constructor. assumption.\n    Qed.\n\n    Lemma pctxD_unwrap_tvs_ctx_subst\n    : forall tvs ctx (cs : ctx_subst _) cD,\n        pctxD cs = Some cD ->\n        exists cD',\n          pctxD (@unwrap_tvs_ctx_subst _ tvs ctx cs (fun x => x)) = Some cD' /\\\n          forall (us : hlist typD _) (vs : hlist typD _) (P : exprT _ _ Prop),\n            cD' (fun us vs => forall vs', P us (hlist_app vs vs')) us vs <->\n            cD match eq_sym (getVars_wrap_tvs tvs ctx) in _ = V\n                   , eq_sym (getUVars_wrap_tvs tvs ctx) in _ = U\n                     return exprT U V Prop\n               with\n               | eq_refl , eq_refl => P\n               end\n               match eq_sym (getAmbientUVars_wrap_tvs tvs ctx) in _ = V\n                     return hlist _ V\n               with\n               | eq_refl => us\n               end\n               match eq_sym (getAmbientVars_wrap_tvs tvs ctx) in _ = V\n                     return hlist _ V\n               with\n               | eq_refl => vs\n               end.\n    Proof using RTypeOk_typD RSymOk_func Typ2Ok_Fun.\n      intros. rewrite <- unwrap_tvs_ctx_subst_unwrap_tvs_ctx_subst'.\n      generalize dependent cD. revert cs. revert ctx.\n      induction tvs.\n      { simpl. eauto.\n        eexists; split; eauto.\n        intros.\n        eapply pctxD_iff; eauto.\n        intros.\n        rewrite (@forall_hlist_nil@{Set Urefl}).\n        rewrite hlist_app_nil_r.\n        revert vs0.\n        refine\n          (match app_nil_r_trans (getVars ctx)  as Q in _ = t\n                 return forall vs0 : hlist typD _,\n               P us0\n                 match\n                   eq_sym Q in (_ = t) return (hlist typD t)\n                 with\n                 | eq_refl => vs0\n                 end <->\n               match\n                 eq_sym (eq_sym Q) in (_ = V)\n                 return (exprT (getUVars ctx) V Prop)\n               with\n               | eq_refl => P\n               end us0 vs0\n           with\n           | eq_refl => _\n           end).\n        reflexivity. }\n      { simpl; intros.\n        specialize (@IHtvs _ _ _ H).\n        forward_reason.\n        generalize dependent (unwrap_tvs_ctx_subst' tvs (CAll ctx a) cs).\n        intro. rewrite (ctx_subst_eta c); simpl.\n        intros; forwardy.\n        eexists; split; eauto.\n        inv_all. subst. intros.\n        specialize (H1 us vs\n                       match eq_sym (app_ass_trans (getVars ctx) (a::nil) _) in _ = X\n                             return exprT _ X Prop\n                       with\n                       | eq_refl => P\n                       end).\n        simpl in *.\n        etransitivity; [ etransitivity; [ | eapply H1 ] | ]; clear H1.\n        { eapply pctxD_iff; eauto.\n          intros.\n          rewrite forall_hlist_cons.\n          eapply Data.Prop.forall_iff; intros.\n          eapply Data.Prop.forall_iff; intros.\n          rewrite hlist_app_assoc.\n          clear. simpl.\n          generalize dependent (app_ass_trans (getVars ctx) (a :: nil) tvs).\n          simpl in *.\n          generalize dependent ((getVars ctx ++ a :: nil) ++ tvs).\n          intros; subst. reflexivity. }\n        { clear - H.\n          match goal with\n          | |- _ _ ?U ?V <-> _ _ ?U' ?V' =>\n            replace V with V' ; [ replace U with U' | ]\n          end.\n          { eapply pctxD_iff; eauto; clear.\n            revert P.\n            refine\n              match app_ass_trans (getVars ctx) (a :: nil) tvs\n                    as PF in _ = Z\n                    return\n                    forall (P : exprT _ Z Prop)\n                           (us : hlist typD (getUVars (wrap_tvs tvs (CAll ctx a))))\n                           (vs : hlist typD (getVars (wrap_tvs tvs (CAll ctx a)))),\n                      match\n                        eq_sym (getVars_wrap_tvs tvs (CAll ctx a)) in (_ = V)\n                        return (exprT (getUVars (wrap_tvs tvs (CAll ctx a))) V Prop)\n                      with\n                      | eq_refl =>\n                        match\n                          eq_sym (getUVars_wrap_tvs tvs (CAll ctx a)) in (_ = U)\n                          return (exprT U ((getVars ctx ++ a :: nil) ++ tvs) Prop)\n                        with\n                        | eq_refl =>\n                          match\n                            eq_sym PF in (_ = X)\n                            return (exprT (getUVars ctx) X Prop)\n                          with\n                          | eq_refl => P\n                          end\n                        end\n                      end us vs <->\n                      match\n                        eq_sym\n                          (eq_ind_r (fun t : tenv typ => t = Z)\n                                    (eq_ind_r (fun l : list typ => l = Z) eq_refl\n                                              PF)\n                                    (getVars_wrap_tvs tvs (CAll ctx a))) in (_ = V)\n                        return (exprT (getUVars (wrap_tvs tvs (CAll ctx a))) V Prop)\n                      with\n                      | eq_refl =>\n                        match\n                          eq_sym\n                            (eq_ind_r (fun t : tenv typ => t = getUVars ctx) eq_refl\n                                      (getUVars_wrap_tvs tvs (CAll ctx a))) in\n                          (_ = U) return (exprT U Z Prop)\n                        with\n                        | eq_refl => P\n                        end\n                      end us vs\n              with\n              | eq_refl => _\n              end.\n            generalize (getVars_wrap_tvs tvs (CAll ctx a)).\n            generalize (getUVars_wrap_tvs tvs (CAll ctx a)).\n            simpl.\n            intros;\n            repeat match goal with\n               | H : @eq (tenv typ) ?X ?Y |- _ =>\n                 first [ generalize dependent X | generalize dependent Y ] ; intros; subst\n               | H : @eq (list typ) ?X ?Y |- _ =>\n                 first [ generalize dependent X | generalize dependent Y ] ; intros; subst\n               end. reflexivity. }\n          { clear.\n            generalize (getAmbientUVars_wrap_tvs tvs (CAll ctx a)).\n            simpl in *. destruct e. reflexivity. }\n          { clear.\n            generalize (getAmbientVars_wrap_tvs tvs (CAll ctx a)).\n            simpl. destruct e. reflexivity. } } }\n    Qed.\n\n    Lemma pctxD_wrap_tvs_ctx_subst\n    : forall tvs ctx (cs : ctx_subst ctx) cD,\n        pctxD cs = Some cD ->\n        exists cD',\n          pctxD (wrap_tvs_ctx_subst tvs cs) = Some cD' /\\\n          forall us vs (P : exprT _ _ Prop),\n            cD (fun us vs => forall vs', P us (hlist_app vs vs')) us vs <->\n            cD' match eq_sym (getVars_wrap_tvs tvs ctx) in _ = V\n                                                           , eq_sym (getUVars_wrap_tvs tvs ctx) in _ = U\n                      return exprT U V Prop\n                with\n                | eq_refl , eq_refl => P\n                end\n                match eq_sym (getAmbientUVars_wrap_tvs tvs ctx) in _ = V\n                      return hlist _ V\n                with\n                | eq_refl => us\n                end\n                match eq_sym (getAmbientVars_wrap_tvs tvs ctx) in _ = V\n                      return hlist _ V\n                with\n                | eq_refl => vs\n                end.\n    Proof using.\n      induction tvs.\n      { simpl. eauto.\n        eexists; split; eauto.\n        intros; eapply pctxD_iff; eauto.\n        intros. rewrite forall_hlist_nil.\n        rewrite hlist_app_nil_r. clear.\n        autorewrite_with_eq_rw. reflexivity. }\n      { simpl. intros.\n        specialize (IHtvs (CAll ctx a) (AllSubst cs)).\n        simpl in IHtvs. rewrite H in IHtvs.\n        specialize (IHtvs _ eq_refl).\n        destruct IHtvs as [ ? [ ? ? ] ].\n        eexists; split; eauto.\n        intros.\n        specialize (H1 us vs\n                       match eq_sym (app_ass_trans (getVars ctx) (a::nil) _) in _ = X\n                             return exprT _ X Prop\n                       with\n                       | eq_refl => P\n                       end).\n        etransitivity; [ etransitivity; [ | eapply H1 ] | ]; clear H1.\n        { eapply pctxD_iff; eauto.\n          intros. rewrite forall_hlist_cons.\n          eapply Data.Prop.forall_iff; intro.\n          eapply Data.Prop.forall_iff; intro.\n          rewrite hlist_app_assoc.\n          clear.\n          generalize dependent (eq_sym (app_ass_trans (getVars ctx) (a :: nil) tvs)).\n          simpl in *. destruct e. reflexivity. }\n        { match goal with\n          | |- _ _ ?U ?V <-> _ _ ?U' ?V' =>\n            replace V with V' ; [ replace U with U' | ]\n          end.\n          { eapply pctxD_iff; eauto.\n            intros.\n            generalize (getVars_wrap_tvs tvs (CAll ctx a)).\n            generalize (getUVars_wrap_tvs tvs (CAll ctx a)).\n            simpl. clear.\n            intros;\n            repeat match goal with\n               | H : @eq (tenv typ) ?X ?Y |- _ =>\n                 first [ generalize dependent X | generalize dependent Y ] ; intros; subst\n               | H : @eq (list typ) ?X ?Y |- _ =>\n                 first [ generalize dependent X | generalize dependent Y ] ; intros; subst\n               end. simpl.\n            unfold eq_ind_r, eq_ind, eq_rect. simpl.\n            autorewrite_with_eq_rw.\n            revert vs0. revert P.\n            refine\n              match app_ass_trans (getVars ctx) (a :: nil) tvs\n                    as PF in _ = X\n                    return\n                    forall P (vs0 : hlist typD ((getVars ctx ++ a :: nil) ++ tvs)),\n                      P us0\n                        match\n                          PF in (_ = x)\n                          return (hlist typD x)\n                        with\n                        | eq_refl => vs0\n                        end <->\n                      P us0\n                        match\n                          match\n                            eq_sym PF in (_ = y)\n                            return (y = X)\n                          with\n                          | eq_refl => eq_refl\n                          end in (_ = x) return (hlist typD x)\n                        with\n                        | eq_refl => vs0\n                        end\n              with\n              | eq_refl => _\n              end.\n            reflexivity. }\n          { clear.\n            generalize (getAmbientUVars_wrap_tvs tvs (CAll ctx a)).\n            simpl in *. destruct e. reflexivity. }\n          { clear.\n            generalize (getAmbientVars_wrap_tvs tvs (CAll ctx a)).\n            simpl. destruct e. reflexivity. } } }\n    Qed.\n\n    Lemma SubstMorphism_wrap_tvs_ctx_subst\n    : forall tvs' ctx cs c,\n        SubstMorphism (wrap_tvs_ctx_subst tvs' cs) c ->\n        SubstMorphism cs\n                      (unwrap_tvs_ctx_subst tvs' c (fun x : ctx_subst ctx => x)).\n    Proof using.\n      intros.\n      rewrite <- unwrap_tvs_ctx_subst_unwrap_tvs_ctx_subst'.\n      revert H. revert ctx c cs.\n      induction tvs'.\n      { simpl. tauto. }\n      { simpl. intros.\n        eapply IHtvs' in H.\n        inv_all. rewrite H. assumption. }\n    Qed.\n\n    Definition using_rewrite_db\n               (hints : list (rw_lemma typ func Rbase * rtacK typ (expr typ func)))\n    : RwAction _ _ _ :=\n      fun e r => rw_bind (using_rewrite_db'' hints e r)\n                         (fun e => rw_ret (Progress e)).\n\n    Definition rewrite_db_sound hints : Prop :=\n      Forall\n        (fun\n            lt : Lemma.lemma typ (expr typ func) (rw_concl typ func Rbase) *\n                 CoreK.rtacK typ (expr typ func) =>\n            Lemma.lemmaD (rw_conclD RbaseD) nil nil (fst lt) /\\\n            CoreK.rtacK_sound (snd lt)) hints.\n\n    Theorem using_rewrite_db_sound\n    : forall hints,\n        rewrite_db_sound hints ->\n        setoid_rewrite_spec RbaseD (using_rewrite_db hints).\n    Proof using RSymOk_func RTypeOk_typD RbaseD_single_type\n          Rbase_eq_ok RelDec_Correct_eq_typ Typ2Ok_Fun.\n      unfold using_rewrite_db, using_rewrite_db''.\n      unfold for_tactic.\n      red. red. intros.\n      unfold rw_bind in H0.\n      forwardy. inv_all. subst.\n      destruct (fun Hx =>\n                    @using_rewrite_db'_sound r _ (wrap_tvs_ctx_subst tvs' cs) hints H\n                                             (expr_convert (length tvs') (length (getVars ctx)) e) e1 c0 Hx\n                                             (WellFormed_ctx_subst_wrap_tvs _ H1)).\n      { rewrite <- H0. f_equal.\n        rewrite countVars_getVars. reflexivity. }\n      clear H0. subst.\n      split.\n      { eapply WellFormed_ctx_subst_unwrap_tvs\n          with (ctx':=CTop nil nil); eauto. }\n      intros.\n      specialize (H3 _ _ H0); clear H0.\n      destruct (pctxD cs) eqn:HpctxD_cs; trivial.\n      destruct (@pctxD_wrap_tvs_ctx_subst tvs' _ _ _ HpctxD_cs) as [ ? [ ? ? ] ].\n      rewrite H0 in H3.\n      destruct (lambda_exprD (getUVars ctx) (tvs' ++ getVars ctx) t e) eqn:Hlambda_exprD_e; trivial.\n      generalize (@exprD_conv typ _ (expr typ func) _). simpl.\n      intro Hconv.\n      rewrite Hconv\n         with (tus':=getUVars ctx) (tvs':=getVars ctx++tvs')\n              (pfu:=eq_sym (getUVars_wrap_tvs tvs' ctx)) (pfv:=eq_sym (getVars_wrap_tvs tvs' ctx))\n           in H3.\n      clear Hconv.\n      eapply expr_convert_sound in Hlambda_exprD_e.\n      destruct Hlambda_exprD_e as [ ? [ Hx ? ] ].\n      rewrite Hx in *; clear Hx.\n      autorewrite_with_eq_rw_in H3.\n      forwardy.\n      destruct (pctxD_unwrap_tvs_ctx_subst _ _ _ H3) as [ ? [ HpctxD_x1 ? ] ].\n      rewrite HpctxD_x1.\n      generalize (@exprD_conv typ _ (expr typ func) _). simpl.\n      intro Hconv.\n      rewrite Hconv\n         with (pfu:=eq_sym (getUVars_wrap_tvs tvs' ctx)) (pfv:=eq_sym(getVars_wrap_tvs tvs' ctx))\n           in H6.\n      clear Hconv.\n      progress autorewrite_with_eq_rw_in H6.\n      forwardy; inv_all; subst.\n      eapply expr_convert_sound in H6.\n      rewrite <- countVars_getVars in *.\n      destruct H6 as [ ? [ Hx ? ] ]; rewrite Hx; clear Hx.\n      destruct H7.\n      split.\n      { clear H9 H8 H4.\n        eapply SubstMorphism_wrap_tvs_ctx_subst; eauto. }\n      { intros.\n        specialize (H9 match\n                        eq_sym (getAmbientUVars_wrap_tvs tvs' ctx) in (_ = V)\n                        return (hlist typD V)\n                      with\n                      | eq_refl => us\n                      end\n                       match\n                         eq_sym (getAmbientVars_wrap_tvs tvs' ctx) in (_ = V)\n                         return (hlist typD V)\n                       with\n                       | eq_refl => vs\n                       end).\n        specialize (H8 us vs\n                   (fun us0 vs0 =>\n                      rD (x0 us0 vs0) (y2 us0 vs0))).\n        simpl in H8.\n        generalize dependent (getVars_wrap_tvs tvs' ctx).\n        generalize dependent (getUVars_wrap_tvs tvs' ctx).\n        generalize dependent (getAmbientUVars_wrap_tvs tvs' ctx).\n        generalize dependent (getAmbientVars_wrap_tvs tvs' ctx).\n        generalize (Ap_pctxD _ HpctxD_x1).\n        generalize (Pure_pctxD _ HpctxD_x1).\n        revert H5 H6 H7. clear.\n        generalize dependent (getAmbientVars (wrap_tvs tvs' ctx)).\n        generalize dependent (getAmbientUVars (wrap_tvs tvs' ctx)).\n        generalize dependent (getUVars (wrap_tvs tvs' ctx)).\n        generalize dependent (getVars (wrap_tvs tvs' ctx)).\n        intros; subst; simpl in *.\n        eapply H8 in H9; clear H8.\n        revert H9. eapply H0; clear H0.\n        eapply H; clear H.\n        clear - H5 H6.\n        intros. rewrite H5. rewrite <- H6. eauto. }\n    Time Qed.\n\n    Definition using_prewrite_db\n               (hints : expr typ func -> R ->\n                        list (rw_lemma typ func Rbase * rtacK typ (expr typ func)))\n    : RwAction _ _ _ :=\n      fun e r => rw_bind (using_prewrite_db'' hints e r)\n                      (fun e => rw_ret (Progress e)).\n\n    (** TODO(gmalecha): This is almost identical to the above theorem *)\n    Theorem using_prewrite_db_sound\n    : forall hints : expr typ func -> R ->\n                     list (rw_lemma typ func Rbase * rtacK typ (expr typ func)),\n        (forall r e,\n            Forall (fun lt =>\n                      (forall tus tvs t eD,\n                          lambda_exprD tus tvs t e = Some eD ->\n                          lemmaD (rw_conclD RbaseD) nil nil (fst lt)) /\\\n                      rtacK_sound (snd lt)) (hints e r)) ->\n        setoid_rewrite_spec RbaseD (using_prewrite_db hints).\n    Proof using RSymOk_func RTypeOk_typD RbaseD_single_type Rbase_eq_ok\n          RelDec_Correct_eq_typ Typ2Ok_Fun.\n      intros.\n      unfold using_prewrite_db, using_prewrite_db''.\n      unfold for_tactic.\n      red. red. intros.\n      unfold rw_bind in H0.\n      forwardy. inv_all. subst.\n      destruct (@using_prewrite_db_sound' hints r _ (wrap_tvs_ctx_subst tvs' cs)\n                                          (expr_convert (length tvs') (length (getVars ctx)) e) e1 c0).\n      { rewrite <- H0.\n        unfold using_prewrite_db'.\n        rewrite countVars_getVars. reflexivity. }\n      { clear - H.\n        intros. specialize (H r e).\n        revert H.\n        eapply Forall_impl. intros. destruct H.\n        eauto using rtacK_sound_WellFormed_rtacK. }\n      { eauto using WellFormed_ctx_subst_wrap_tvs. }\n      clear H0. subst. split.\n      { eapply WellFormed_ctx_subst_unwrap_tvs\n          with (ctx':=CTop nil nil); eauto. }\n      intros.\n      specialize (fun Hx => H3 Hx _ _ H0); clear H0.\n      destruct (pctxD cs) eqn:HpctxD_cs; trivial.\n      destruct (@pctxD_wrap_tvs_ctx_subst tvs' _ _ _ HpctxD_cs) as [ ? [ ? ? ] ].\n      rewrite H0 in H3.\n      destruct (lambda_exprD (getUVars ctx) (tvs' ++ getVars ctx) t e) eqn:Hlambda_exprD_e; trivial.\n      generalize (@exprD_conv typ _ (expr typ func) _). simpl.\n      intro Hconv.\n      rewrite Hconv\n         with (tus':=getUVars ctx) (tvs':=getVars ctx++tvs')\n              (pfu:=eq_sym (getUVars_wrap_tvs tvs' ctx)) (pfv:=eq_sym (getVars_wrap_tvs tvs' ctx))\n           in H3.\n      clear Hconv.\n      eapply expr_convert_sound in Hlambda_exprD_e.\n      destruct Hlambda_exprD_e as [ ? [ Hx ? ] ].\n      rewrite Hx in *; clear Hx.\n      autorewrite_with_eq_rw_in H3.\n      match goal with\n      | H : ?X -> _ |- _ =>\n        match type of X with\n        | Prop =>\n          let H' := fresh in\n          assert (H' : X) ; [ clear H | specialize (H H'); clear H' ]\n        end\n      end.\n      { clear - H.\n        intros. generalize (H r e).\n        eapply Forall_impl. intros; forward_reason.\n        split; eauto. }\n      forwardy.\n      destruct (pctxD_unwrap_tvs_ctx_subst _ _ _ H3) as [ ? [ HpctxD_x1 ? ] ].\n      rewrite HpctxD_x1.\n      generalize (@exprD_conv typ _ (expr typ func) _). simpl.\n      intro Hconv.\n      rewrite Hconv\n         with (pfu:=eq_sym (getUVars_wrap_tvs tvs' ctx)) (pfv:=eq_sym(getVars_wrap_tvs tvs' ctx))\n           in H6.\n      clear Hconv.\n      autorewrite_with_eq_rw_in H6.\n      forwardy; inv_all; subst.\n      eapply expr_convert_sound in H6.\n      rewrite <- countVars_getVars in *.\n      destruct H6 as [ ? [ Hx ? ] ]; rewrite Hx; clear Hx.\n      destruct H7.\n      split.\n      { clear H9 H8 H4.\n        eapply SubstMorphism_wrap_tvs_ctx_subst; eauto. }\n      { intros.\n        specialize (H9 match\n                        eq_sym (getAmbientUVars_wrap_tvs tvs' ctx) in (_ = V)\n                        return (hlist typD V)\n                      with\n                      | eq_refl => us\n                      end\n                       match\n                         eq_sym (getAmbientVars_wrap_tvs tvs' ctx) in (_ = V)\n                         return (hlist typD V)\n                       with\n                       | eq_refl => vs\n                       end).\n        specialize (H8 us vs\n                   (fun us0 vs0 =>\n                      rD (x0 us0 vs0) (y2 us0 vs0))).\n        simpl in H8.\n        generalize dependent (getVars_wrap_tvs tvs' ctx).\n        generalize dependent (getUVars_wrap_tvs tvs' ctx).\n        generalize dependent (getAmbientUVars_wrap_tvs tvs' ctx).\n        generalize dependent (getAmbientVars_wrap_tvs tvs' ctx).\n        generalize (Ap_pctxD _ HpctxD_x1).\n        generalize (Pure_pctxD _ HpctxD_x1).\n        revert H5 H6 H7. clear.\n        generalize dependent (getAmbientVars (wrap_tvs tvs' ctx)).\n        generalize dependent (getAmbientUVars (wrap_tvs tvs' ctx)).\n        generalize dependent (getUVars (wrap_tvs tvs' ctx)).\n        generalize dependent (getVars (wrap_tvs tvs' ctx)).\n        intros; subst; simpl in *.\n        eapply H8 in H9; clear H8.\n        revert H9. eapply H0; clear H0.\n        eapply H; clear H.\n        clear - H5 H6.\n        intros. rewrite H5. rewrite <- H6. eauto. }\n    Qed.\n\n  End reindexing.\n\nEnd setoid.\n", "meta": {"author": "gmalecha", "repo": "mirror-core", "sha": "b962fbca15b0b5a4653f66d29d7115bb04ebd4f3", "save_path": "github-repos/coq/gmalecha-mirror-core", "path": "github-repos/coq/gmalecha-mirror-core/mirror-core-b962fbca15b0b5a4653f66d29d7115bb04ebd4f3/theories/Lambda/Rewrite/Rewrite.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24294048363959556}}
{"text": "Require Import floyd.proofauto.\nRequire Import progs.dead_if.\nRequire Import floyd.deadvars.\n\nInstance CompSpecs : compspecs.\nProof. make_compspecs prog. Defined.\n\nLocal Open Scope logic.\n\nDefinition f_spec :=\n DECLARE _f\n  WITH x : Z, y: Z, z: Z\n  PRE  [_x OF tint, _y OF tint, _z OF tint]\n    PROP ( ) LOCAL (temp _x (Vint (Int.repr x)); \n                    temp _y (Vint (Int.repr y)); temp _z (Vint (Int.repr z)))\n    SEP()\n  POST [ tint ] PROP() LOCAL() SEP().\n\nDefinition g_spec :=\n DECLARE _g\n  WITH x : Z, y: Z, z: Z\n  PRE  [_x OF tint, _y OF tint, _z OF tint]\n    PROP ( ) LOCAL (temp _x (Vint (Int.repr x)); \n                    temp _y (Vint (Int.repr y)); temp _z (Vint (Int.repr z)))\n    SEP()\n  POST [ tint ] PROP() LOCAL() SEP().\n\nDefinition Vprog : varspecs := nil.\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [g_spec]).\n\nLemma body_f:  semax_body Vprog Gprog f_f f_spec.\nProof.\nstart_function.\ndeadvars.  (* nothing dead here *)\ndo 3 forward.\ndeadvars.  (* dead *)\nforward.\ndeadvars.  (* nothing dead here *)\nforward_if (EX i:_, EX j:_, PROP ( )\n   LOCAL (temp _c (Vint (Int.repr i)); temp _b (Vint (Int.repr j)))  SEP ()).\ndeadvars.   (* dead *)\nforward.\nrewrite add_repr.\nExists 0 (x+y).\nentailer!.\ndeadvars.  (* dead *)\nforward.\nforward.\nExists z x.\nentailer!.\nIntros i j.\nforward.\nQed.\n\nLemma body_g:  semax_body Vprog Gprog f_g g_spec.\nProof.\nstart_function.\ndeadvars.  (* dead vars! *)\ndo 3 forward.\ndeadvars.  (* dead vars! *)\nforward.\nnormalize.\ndeadvars.  (* nothing dead here *)\nforward_while (EX i:_,\n   PROP() LOCAL (temp _a (Vint (Int.repr (x+1))); temp _x (Vint (Int.repr x));\n              temp _c (Vint (Int.repr 0)); temp _b (Vint (Int.repr i)))  SEP ()).\n* Exists 1. entailer!.\n* entailer!.\n*\ndeadvars.   (* dead vars! *)\nforward.\nExists x. entailer!.\n*\ndeadvars. (* dead vars! *)\nforward.\nQed.\n\n    \n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/progs/verif_dead_if.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24283530889206978}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Postorder renumbering of RTL control-flow graphs. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Postorder.\nRequire Import RTL.\n\n(** CompCert's dataflow analyses (module [Kildall]) are more precise\n  and run faster when the sequence [1, 2, 3, ...]  is a postorder\n  enumeration of the nodes of the control-flow graph.  This property\n  can be guaranteed when generating the CFG (module [RTLgen]), but\n  is, however, invalidated by further RTL optimization passes such as\n  [Inlining].  \n\n  In this module, we renumber the nodes of RTL control-flow graphs\n  to restore the postorder property given above.  In passing,\n  we also eliminate CFG nodes that are not reachable from the entry point:\n  these nodes are dead code. *)\n\nSection RENUMBER.\n\nVariable pnum: PTree.t positive.   (**r a postorder numbering *)\n\nDefinition renum_pc (pc: node) : node :=\n  match pnum!pc with\n  | Some pc' => pc'\n  | None => 1%positive          (**r impossible case, never exercised *)\n  end.\n\nDefinition renum_instr (i: instruction) : instruction :=\n  match i with\n  | Inop s => Inop (renum_pc s)\n  | Iop op args res s => Iop op args res (renum_pc s)\n  | Iload chunk addr args res s => Iload chunk addr args res (renum_pc s)\n  | Istore chunk addr args src s => Istore chunk addr args src (renum_pc s)\n  | Icall sg ros args res s => Icall sg ros args res (renum_pc s)\n  | Itailcall sg ros args => i\n  | Ibuiltin ef args res s => Ibuiltin ef args res (renum_pc s)\n  | Icond cond args s1 s2 => Icond cond args (renum_pc s1) (renum_pc s2)\n  | Ijumptable arg tbl => Ijumptable arg (List.map renum_pc tbl)\n  | Ireturn or => i\n  end.\n\nDefinition renum_node (c': code) (pc: node) (i: instruction) : code :=\n  match pnum!pc with\n  | None => c'\n  | Some pc' => PTree.set pc' (renum_instr i) c'\n  end.\n\nDefinition renum_cfg (c: code) : code :=\n  PTree.fold renum_node c (PTree.empty instruction).\n\nEnd RENUMBER.\n\nDefinition transf_function (f: function) : function :=\n  let pnum := postorder (successors_map f) f.(fn_entrypoint) in\n  mkfunction\n    f.(fn_sig)\n    f.(fn_params)\n    f.(fn_stacksize)\n    (renum_cfg pnum f.(fn_code))\n    (renum_pc pnum f.(fn_entrypoint)).\n\nDefinition transf_fundef (fd: fundef) : fundef :=\n  AST.transf_fundef transf_function fd.\n\nDefinition transf_program (p: program) : program :=\n  AST.transform_program transf_fundef p.\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/backend/Renumber.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.24283530210674156}}
{"text": "(* \n  Autor(s):\n    Andrej Dudenhefner (1) \n  Affiliation(s):\n    (1) Saarland University, Saarbrücken, Germany\n*)\n\n(* \n  Undecidability Result(s):\n    Provability in Hilbert-style calculi (HSC_PRV)\n    Recognizing axiomatizations of Hilbert-style calculi (HSC_AX)\n*)\n\nRequire Import Undecidability.Synthetic.Undecidability.\n\nRequire Import Undecidability.HilbertCalculi.HSC.\n\nRequire Undecidability.HilbertCalculi.Reductions.MPCPb_to_HSC_PRV.\nRequire Undecidability.HilbertCalculi.Reductions.MPCPb_to_HSC_AX.\n\nRequire Import Undecidability.PCP.PCP_undec.\n\n(* Hilbert-style Axiomatization of the Post Correspondenc Problem *)\nDefinition ΓPCP := MPCPb_to_HSC_PRV.Argument.ΓPCP.\n\n(* Undecidability of Provability in Hilbert-style Calculi with the Fixed Environment ΓPCP *)\nTheorem HSC_PRV_undec : undecidable (HSC_PRV ΓPCP).\nProof.\n  apply (undecidability_from_reducibility MPCPb_undec).\n  exact MPCPb_to_HSC_PRV.reduction.\nQed.\n\nCheck HSC_PRV_undec.\n\n(* Undecidability of Recognizing Axiomatizations of Hilbert-style Calculi *)\nTheorem HSC_AX_undec : undecidable HSC_AX.\nProof.\n  apply (undecidability_from_reducibility MPCPb_undec).\n  exact MPCPb_to_HSC_AX.reduction.\nQed.\n\nCheck HSC_AX_undec.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/HilbertCalculi/HSC_undec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056167854461, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.24277466660745384}}
{"text": "Require Import VST.floyd.base2.\nImport ListNotations.\n\nModule PosOrder <: Orders.TotalLeBool.\n  Definition t := positive.\n  Definition leb := Pos.leb.\n  Theorem leb_total : forall a1 a2, Pos.leb a1 a2 = true \\/ Pos.leb a2 a1 = true.\n  Proof.  intros. \n    pose proof (Pos.leb_spec a1 a2).\n    pose proof (Pos.leb_spec a2 a1).\n    inv H; inv H0; auto.\n    clear - H2 H3. \n    pose proof (Pos.lt_trans _ _ _ H2 H3).\n    apply Pos.lt_irrefl in H. contradiction.\n  Qed.\nEnd PosOrder.\nModule SortPos := Mergesort.Sort(PosOrder).\n\nModule CompOrder <: Orders.TotalLeBool.\n  Definition t := composite_definition.\n  Definition leb := fun x y => Pos.leb (name_composite_def x) (name_composite_def y).\n  Theorem leb_total : forall a1 a2, leb a1 a2 = true \\/ leb a2 a1 = true.\n  Proof.  intros. unfold leb. \n    pose proof (Pos.leb_spec (name_composite_def a1) (name_composite_def a2)).\n    pose proof (Pos.leb_spec (name_composite_def a2) (name_composite_def a1)).\n    inv H; inv H0; auto.\n    clear - H2 H3. \n    pose proof (Pos.lt_trans _ _ _ H2 H3).\n    apply Pos.lt_irrefl in H. contradiction.\n  Qed.\nEnd CompOrder.\nModule SortComp := Mergesort.Sort(CompOrder).\n\nModule GlobdefOrder <: Orders.TotalLeBool.\n  Definition t := (ident * globdef (fundef function) type)%type.\n  Definition leb := fun x y : (ident * globdef (fundef function) type)=> Pos.leb (fst x) (fst y).\n  Theorem leb_total : forall a1 a2, leb a1 a2 = true \\/ leb a2 a1 = true.\n  Proof.  intros. unfold leb. \n    pose proof (Pos.leb_spec (fst a1) (fst a2)).\n    pose proof (Pos.leb_spec (fst a2) (fst a1)).\n    inv H; inv H0; auto.\n    clear - H2 H3. \n    pose proof (Pos.lt_trans _ _ _ H2 H3).\n    apply Pos.lt_irrefl in H. contradiction.\n  Qed.\nEnd GlobdefOrder.\nModule SortGlobdef := Mergesort.Sort(GlobdefOrder).\n\nDefinition isnil {A} (al: list A) := \n   match al with nil => true | _ => false end.\n\nLemma prod_eq_dec {A B} (Ha: forall (a1 a2:A), {a1 = a2} + {a1<>a2})\n      (Hb: forall (b1 b2:B), {b1 = b2} + {b1<>b2}):\n      forall (x y : A * B), {x=y} + {x<>y}.\nProof. intros. destruct x as [a1 b1]. destruct y as [a2 b2].\ndestruct (Ha a1 a2); [ subst | right; congruence].\ndestruct (Hb b1 b2); [ subst; left; trivial | right; congruence].\nDefined. \n\nLemma function_eq_dec (f g: function): { f=g } + { f <> g }.\nProof.\ndestruct f as [rtF ccF paramsF varsF tempsF bodyF].\ndestruct g as [rtG ccG paramsG varsG tempsG bodyG].\ndestruct (type_eq rtF rtG); [ subst | right; congruence].\ndestruct (calling_convention_eq ccF ccG); [ subst | right; congruence].\ndestruct (list_eq_dec (prod_eq_dec ident_eq type_eq) paramsF paramsG); [ subst | right; congruence].\ndestruct (list_eq_dec (prod_eq_dec ident_eq type_eq) varsF varsG); [ subst | right; congruence].\ndestruct (list_eq_dec (prod_eq_dec ident_eq type_eq) tempsF tempsG); [ subst | right; congruence].\ndestruct (semax_lemmas.eq_dec_statement bodyF bodyG); [ subst; left; trivial | right; congruence].\nDefined.\n\nDefinition merge_globdef (g1 g2: globdef (fundef function) type) :=\n match g1, g2 with\n | Gfun (External _ _ _ _), Gfun (External _ _ _ _) => \n     Errors.OK g1  (* SHOULD CHECK g1=g2 *)\n | Gfun (External _ _ _ _), Gfun (Internal f2) => \n     Errors.OK g2  (* SHOULD CHECK TYPES MATCH *)\n | Gfun (Internal f1), Gfun (External _ _ _ _) =>\n    Errors.OK g1  (* SHOULD CHECK TYPES MATCH *)\n | Gfun (Internal f), Gfun (Internal g) => Errors.OK g1 (*this is OK \n      since VSU.ComponentJoin contains hypothesis Fundefs_match*) \n    (*Errors.Error [Errors.MSG \"internal function clash\"]*)\n   (* if function_eq_dec f g then Errors.OK g1\n    else Errors.Error [Errors.MSG \"internal function clash\"]*)\n | Gvar {| gvar_info := i1; gvar_init := l1; gvar_readonly := r1; gvar_volatile := v1 |},\n   Gvar {| gvar_info := i2; gvar_init := l2; gvar_readonly := r2; gvar_volatile := v2 |} =>\n   if (eqb_type i1 i2 &&\n      bool_eq r1 r2 &&\n      bool_eq v1 v2)%bool\n   then if isnil l1 \n           then Errors.OK g2 \n           else if isnil l2 then Errors.OK g1 \n           else Errors.Error [Errors.MSG \"Gvars both initialized\"]\n   else Errors.Error [Errors.MSG \"Gvar type/readonly/volatile clash\"]\n  | _, _ => Errors.Error [Errors.MSG \"Gvar versus Gfun\"]\n end.\n\nFunction merge_global_definitions'\n    (d1 d2: list (ident * globdef (fundef function) type))\n    (fuel: nat) :=\n match fuel with\n | O => Errors.Error [Errors.MSG \"out of fuel\"]\n | S fuel' => \n  match d1, d2 with\n  | nil, _ => Errors.OK d2\n  | _, nil => Errors.OK d1\n  | (i1,g1)::d1', (i2,g2)::d2' => \n     if Pos.ltb i1 i2 \n     then match merge_global_definitions' d1' d2 fuel' with\n            | Errors.OK dl => Errors.OK ((i1,g1)::dl)\n            | err => err\n            end\n     else if Pos.ltb i2 i1\n     then match merge_global_definitions' d1 d2' fuel' with\n            | Errors.OK dl => Errors.OK ((i2,g2)::dl)\n            | err => err\n            end\n    else match merge_globdef g1 g2 with\n           | Errors.OK g => match merge_global_definitions' d1' d2' fuel' with\n                     | Errors.OK dl => Errors.OK ((i1,g)::dl)\n                     | Errors.Error el => Errors.Error el\n                    end\n            | Errors.Error err => Errors.Error (Errors.POS i1 :: err)\n            end\n end end.\n\nDefinition merge_global_definitions\n    (d1 d2: list (ident * globdef (fundef function) type)) :=\n merge_global_definitions' d1 d2 (length d1 + length d2).\n\nFixpoint merge_prog_types' (e1 e2: list composite_definition)\n                 (fuel: nat) \n              : Errors.res (list composite_definition) :=\n match fuel with\n | O => Errors.Error [Errors.MSG \"ran out of fuel in composites\"]\n | S fuel' => \n match e1, e2 with\n | nil, _ => Errors.OK e2\n | _, nil => Errors.OK e1\n | (Composite i1 su1 m1 a1 as c1) :: e1', \n   (Composite i2 su2 m2 a2 as c2) :: e2' =>\n   if Pos.ltb i1 i2 \n   then Errors.bind (merge_prog_types' e1' e2 fuel')\n          (fun e => Errors.OK (c1::e))\n   else if Pos.ltb i2 i1 \n   then Errors.bind (merge_prog_types' e1 e2' fuel')\n          (fun e => Errors.OK (c2::e))\n   else if (eqb_su su1 su2 &&\n              eqb_list eqb_member m1 m2 &&\n              eqb_attr a1 a2)%bool\n   then Errors.bind (merge_prog_types' e1' e2' fuel')\n          (fun e => Errors.OK (c1::e))\n   else Errors.Error [Errors.MSG \"struct/union does not match:\"; Errors.POS i1]\n end\nend.\n\nDefinition merge_prog_types e1 e2 :=\n merge_prog_types' e1 e2 (S(length e1 + length e2)).\n \nDefinition link_progs (prog1 prog2 : Clight.program) : \n  Errors.res Clight.program :=\n match prog1, prog2 with\n  {|prog_defs := d1;\n    prog_public := p1;\n    prog_main := m1;\n    prog_types := t1;\n    prog_comp_env := e1;\n    prog_comp_env_eq := q1|},\n  {|prog_defs := d2;\n    prog_public := p2;\n    prog_main := m2;\n    prog_types := t2;\n    prog_comp_env := e2;\n    prog_comp_env_eq := q2|}  =>\n Errors.bind (merge_global_definitions \n               (SortGlobdef.sort d1) (SortGlobdef.sort d2)) (fun d =>\n Errors.bind (merge_prog_types (SortComp.sort t1) (SortComp.sort t2)) (fun t =>\n match build_composite_env t as e \n       return (build_composite_env t = e -> Errors.res Clight.program) with\n | Errors.Error err => fun _ => Errors.Error err\n | Errors.OK e =>  fun q => \n if negb (eqb_ident m1 m2) \n   then Errors.Error [Errors.MSG \"main identifiers differ\"]\n   else\n    Errors.OK {| prog_defs := d;\n    prog_public := SortPos.merge (SortPos.sort p1) (SortPos.sort p2);\n    prog_main := m2;\n    prog_types := t;\n    prog_comp_env := e;\n    prog_comp_env_eq := q|} \n   end eq_refl ))\nend.\n\nDefinition link_progs_list (pl: list Clight.program) : \n  Errors.res Clight.program :=\n match pl with\n | nil => Errors.Error [Errors.MSG \"no programs to link\"]\n | p::pl' => List.fold_left (fun q p =>\n                  match q with\n                  | Errors.Error e => q\n                  | Errors.OK q' => link_progs q' p\n                  end) pl' (Errors.OK p)\n  end.\n\nLtac link_progs_list pl :=\n let q := constr:(linking.link_progs_list pl) in\n let q := eval hnf in q in\n let q := eval cbv beta iota delta [linking.SortComp.sort] in q in\n let q := eval simpl in q in\n match q with\n | Errors.Error ?e => fail 1 e\n | Errors.OK ?q' => exact q'\n end.\n\n(*duplicate of lemma in globals_lemas*)\nLemma prog_defs_Clight_mkprogram:\n forall c g p m w,\n prog_defs (Clightdefs.mkprogram c g p m w) = g.\nProof.\nintros. unfold Clightdefs.mkprogram.\ndestruct ( build_composite_env' c w).\nreflexivity.\nQed.\n\nLemma prog_types_Clight_mkprogram:\n  forall (c : list composite_definition) (g : list (ident * globdef Clight.fundef type)) (p : list ident) \n    (m : ident) (w : wf_composites c), prog_types (Clightdefs.mkprogram c g p m w) = c.\nProof. intros. unfold prog_types. unfold Clightdefs.mkprogram.\ndestruct (build_composite_env' c w ); trivial.\nQed. \n\nModule NEW_LINK_PROGS.  (* Everything in this Module should perhaps be moved to floyd/linking.v *)\n\n(* All of this complexity is because the naturally computed proof whose type is\n     build_composite_env t12 = Errors.OK e12\n  blows up:  the nested environments explode exponentially.\n And that's a pity, because after all we have  proof irrelevance.  But I could not\n think of a better way than this to exploit proof irrelevance.  -- Andrew, 7/24/2020\n*)\nDefinition carefully_link_progs (prog1 prog2 : Clight.program) \n  (MAIN: prog_main prog1 = prog_main prog2)\n  (d12: list (ident * globdef (fundef function) type))\n  (Hd12: merge_global_definitions \n               (SortGlobdef.sort (prog_defs prog1)) (SortGlobdef.sort (prog_defs prog2)) = Errors.OK d12)\n  (t12: list composite_definition) \n  (Ht12: merge_prog_types (SortComp.sort (prog_types prog1)) (SortComp.sort (prog_types prog2)) = Errors.OK t12)\n  (e12: composite_env)\n  (He12: build_composite_env t12 = Errors.OK e12)\n  : Clight.program := \n {| prog_defs := d12;\n    prog_public := SortPos.merge (SortPos.sort (prog_public prog1)) (SortPos.sort (prog_public prog2));\n    prog_main := prog_main prog2;\n    prog_types := t12;\n    prog_comp_env := e12;\n    prog_comp_env_eq := He12|} .\n\nLemma Gt_neq_Lt: Gt = Lt -> False.\nProof. congruence. Qed.\n\nLemma prove_exists_align_attr:\n  forall d, two_power_nat (Z.to_nat (Z.log2 d)) = d ->\n    exists n, align_attr noattr d = two_power_nat n.\nProof.\nintros.\nexists (Z.to_nat (Z.log2 d)).\nrewrite H. reflexivity.\nQed.\n\nLemma prove_align_attr:\n  forall i j,  (j/i)*i=j -> (align_attr noattr i | j).\nProof. intros. exists (j/i). symmetry. apply H. Qed. \n\nLtac process_composite_definitions_step := \nrepeat\nmatch goal with\n|- Errors.bind match ?z with _ => _ end  _  = _ => \n  set (j := z); hnf in j; simpl in j; subst j; cbv beta iota\nend;\n match goal with |- context [Ctypes.composite_of_def_obligation_1 _ _ _ _] =>\n   set (x := Ctypes.composite_of_def_obligation_1 _ _ _ _);\n  simpl in x;\n  match type of x with ?t => \n    replace x with (Gt_neq_Lt : t) by apply proof_irr\n end; \n  clear x\nend;\n match goal with |- context [Ctypes.composite_of_def_obligation_2 _ _ _] =>\n   set (x := Ctypes.composite_of_def_obligation_2 _ _ _);\n  simpl in x;\n  match type of x with (exists i, align_attr noattr ?d = two_power_nat i) => \n    replace x with (prove_exists_align_attr d (eq_refl _)) by apply proof_irr\n end; \n  clear x\nend;\nrepeat\n  match goal with |- context [Ctypes.composite_of_def_obligation_3 _ _ _ _] =>\n   set (x := Ctypes.composite_of_def_obligation_3 _ _ _ _);\n  simpl in x;\n  match type of x with (align_attr noattr ?i | ?j)  => \n    replace x with (prove_align_attr i j (eq_refl _)) by apply proof_irr\n end; \n  clear x\nend;\nchange (Errors.bind (Errors.OK ?x) ?f) with (f x); cbv beta iota.\n\nLtac process_composite_definitions :=\n simpl;\n unfold build_composite_env; \n unfold add_composite_definitions, composite_of_def; \n simpl align; simpl align_attr; simpl rank_members;\n simpl PTree.set;\n repeat process_composite_definitions_step;\n reflexivity.\n\nLtac do_merge_global_definitions := \nmatch goal with |- context [SortGlobdef.sort ?x] =>\n set (j :=SortGlobdef.sort x); hnf in j; simpl in j; subst j\nend;\nmatch goal with |- context [SortGlobdef.sort ?x] =>\n set (j :=SortGlobdef.sort x); hnf in j; simpl in j; subst j\nend;\nmatch goal with |- ?A = _ =>\n set (j :=A); hnf in j; simpl in j; subst j\nend; reflexivity.\n\nLtac do_merge_prog_types := \nmatch goal with |- context [SortComp.sort ?x] =>\n set (j :=SortComp.sort x); hnf in j; simpl in j; subst j\nend;\nmatch goal with |- context [SortComp.sort ?x] =>\n set (j :=SortComp.sort x); hnf in j; simpl in j; subst j\nend;\nmatch goal with |- ?A = _ =>\n set (j :=A); hnf in j; simpl in j; subst j\nend; reflexivity.  \n\nLtac do_link_progs_step1 p1 p2 := \n  eapply (carefully_link_progs p1 p2 (eq_refl _));\n  [time \"merge_global\" do_merge_global_definitions\n  |time \"merge_types\" do_merge_prog_types\n  |time \"process_composites\" process_composite_definitions].\n\nLtac do_merge_global_definitions_unfold p1 p2 :=\n  unfold p1; try rewrite prog_defs_Clight_mkprogram;\n  unfold p2; try rewrite prog_defs_Clight_mkprogram;\n  do_merge_global_definitions.\n\nLtac do_merge_prog_types_unfold p1 p2 :=\n unfold p1; try rewrite prog_types_Clight_mkprogram;\n unfold p2; try rewrite prog_types_Clight_mkprogram;\n  do_merge_prog_types.\n\nLtac do_link_progs_step1_unfold p1 p2 := \n  eapply (carefully_link_progs p1 p2 (eq_refl _));\n  [time \"merge_global\" do_merge_global_definitions_unfold p1 p2\n  |time \"merge_types\" do_merge_prog_types_unfold p1 p2\n  |time \"process_composites\" process_composite_definitions].\n\nLtac do_link_progs_step2 p := \nlet x := eval hnf in p in\nmatch x with\n {| prog_defs := ?d;\n    prog_public := ?p;\n    prog_main := ?m;\n    prog_types := ?t;\n    prog_comp_env := ?e;\n    prog_comp_env_eq := _ |} =>\nrefine  {| prog_defs := d;\n    prog_public := p;\n    prog_main := m;\n    prog_types := t;\n    prog_comp_env := e;\n    prog_comp_env_eq := _ |} \nend;\nabstract (exact (prog_comp_env_eq p)).\n\nEnd NEW_LINK_PROGS.\n(* Now, to use NEW_LINK_PROGS, it is unfortunately necessary to do this in two steps*)\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/floyd/linking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.24277035394449056}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Constant propagation over RTL.  This is one of the optimizations\n  performed at RTL level.  It proceeds by a standard dataflow analysis\n  and the corresponding code rewriting. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Globalenvs.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import Lattice.\nRequire Import Kildall.\nRequire Import ConstpropOp.\n\n(** * Static analysis *)\n\n(** The type [approx] of compile-time approximations of values is\n  defined in the machine-dependent part [ConstpropOp]. *)\n\n(** We equip this type of approximations with a semi-lattice structure.\n  The ordering is inclusion between the sets of values denoted by\n  the approximations. *)\n\nModule Approx <: SEMILATTICE_WITH_TOP.\n  Definition t := approx.\n  Definition eq (x y: t) := (x = y).\n  Definition eq_refl: forall x, eq x x := (@refl_equal t).\n  Definition eq_sym: forall x y, eq x y -> eq y x := (@sym_equal t).\n  Definition eq_trans: forall x y z, eq x y -> eq y z -> eq x z := (@trans_equal t).\n  Lemma eq_dec: forall (x y: t), {x=y} + {x<>y}.\n  Proof.\n    decide equality.\n    apply Int.eq_dec.\n    apply Float.eq_dec.\n    apply Int.eq_dec.\n    apply ident_eq.\n    apply Int.eq_dec.\n  Qed.\n  Definition beq (x y: t) := if eq_dec x y then true else false.\n  Lemma beq_correct: forall x y, beq x y = true -> x = y.\n  Proof.\n    unfold beq; intros.  destruct (eq_dec x y). auto. congruence.\n  Qed.\n\n  Definition ge (x y: t) : Prop := x = Unknown \\/ y = Novalue \\/ x = y.\n\n  Lemma ge_refl: forall x y, eq x y -> ge x y.\n  Proof.\n    unfold eq, ge; tauto.\n  Qed.\n  Lemma ge_trans: forall x y z, ge x y -> ge y z -> ge x z.\n  Proof.\n    unfold ge; intuition congruence.\n  Qed.\n  Lemma ge_compat: forall x x' y y', eq x x' -> eq y y' -> ge x y -> ge x' y'.\n  Proof.\n    unfold eq, ge; intros; congruence.\n  Qed.\n  Definition bot := Novalue.\n  Definition top := Unknown.\n  Lemma ge_bot: forall x, ge x bot.\n  Proof.\n    unfold ge, bot; tauto.\n  Qed.\n  Lemma ge_top: forall x, ge top x.\n  Proof.\n    unfold ge, bot; tauto.\n  Qed.\n  Definition lub (x y: t) : t :=\n    if eq_dec x y then x else\n    match x, y with\n    | Novalue, _ => y\n    | _, Novalue => x\n    | _, _ => Unknown\n    end.\n  Lemma ge_lub_left: forall x y, ge (lub x y) x.\n  Proof.\n    unfold lub; intros.\n    case (eq_dec x y); intro.\n    apply ge_refl. apply eq_refl.\n    destruct x; destruct y; unfold ge; tauto.\n  Qed.\n  Lemma ge_lub_right: forall x y, ge (lub x y) y.\n  Proof.\n    unfold lub; intros.\n    case (eq_dec x y); intro.\n    apply ge_refl. subst. apply eq_refl.\n    destruct x; destruct y; unfold ge; tauto.\n  Qed.\nEnd Approx.\n\nModule D := LPMap Approx.\n\n(** We keep track of read-only global variables (i.e. \"const\" global\n  variables in C) as a map from their names to their initialization\n  data. *)\n\nDefinition global_approx : Type := PTree.t (list init_data).\n\n(** Given some initialization data and a byte offset, compute a static\n  approximation of the result of a memory load from a memory block\n  initialized with this data. *)\n\nFixpoint eval_load_init (chunk: memory_chunk) (pos: Z) (il: list init_data): approx :=\n  match il with\n  | nil => Unknown\n  | Init_int8 n :: il' =>\n      if zeq pos 0 then\n        match chunk with\n        | Mint8unsigned => I (Int.zero_ext 8 n)\n        | Mint8signed => I (Int.sign_ext 8 n)\n        | _ => Unknown\n        end\n      else eval_load_init chunk (pos - 1) il'\n  | Init_int16 n :: il' =>\n      if zeq pos 0 then\n        match chunk with\n        | Mint16unsigned => I (Int.zero_ext 16 n)\n        | Mint16signed => I (Int.sign_ext 16 n)\n        | _ => Unknown\n        end\n      else eval_load_init chunk (pos - 2) il'\n  | Init_int32 n :: il' =>\n      if zeq pos 0 \n      then match chunk with Mint32 => I n | _ => Unknown end\n      else eval_load_init chunk (pos - 4) il'\n  | Init_float32 n :: il' =>\n      if zeq pos 0\n      then match chunk with \n           | Mfloat32 => if propagate_float_constants tt then F (Float.singleoffloat n) else Unknown\n           | _ => Unknown\n           end\n      else eval_load_init chunk (pos - 4) il'\n  | Init_float64 n :: il' =>\n      if zeq pos 0 \n      then match chunk with\n           | Mfloat64 => if propagate_float_constants tt then F n else Unknown\n           | _ => Unknown\n           end\n      else eval_load_init chunk (pos - 8) il'\n  | Init_addrof symb ofs :: il' =>\n      if zeq pos 0\n      then match chunk with Mint32 => G symb ofs | _ => Unknown end\n      else eval_load_init chunk (pos - 4) il'\n  | Init_space n :: il' =>\n      eval_load_init chunk (pos - Zmax n 0) il'\n  end.\n\n(** Compute a static approximation for the result of a load at an address whose\n  approximation is known.  If the approximation points to a global variable,\n  and this global variable is read-only, we use its initialization data\n  to determine a static approximation.  Otherwise, [Unknown] is returned. *)\n\nDefinition eval_static_load (gapp: global_approx) (chunk: memory_chunk) (addr: approx) : approx :=\n  match addr with\n  | G symb ofs =>\n      match gapp!symb with\n      | None => Unknown\n      | Some il => eval_load_init chunk (Int.unsigned ofs) il\n      end\n  | _ => Unknown\n  end.\n\n(** The transfer function for the dataflow analysis is straightforward.\n  For [Iop] instructions, we set the approximation of the destination\n  register to the result of executing abstractly the operation.\n  For [Iload] instructions, we set the approximation of the destination\n  register to the result of [eval_static_load].\n  For [Icall] and [Ibuiltin], the destination register becomes [Unknown].\n  Other instructions keep the approximations unchanged, as they preserve\n  the values of all registers. *)\n\nDefinition approx_reg (app: D.t) (r: reg) := \n  D.get r app.\n\nDefinition approx_regs (app: D.t) (rl: list reg):=\n  List.map (approx_reg app) rl.\n\nDefinition transfer (gapp: global_approx) (f: function) (pc: node) (before: D.t) :=\n  match f.(fn_code)!pc with\n  | None => before\n  | Some i =>\n      match i with\n      | Iop op args res s =>\n          let a := eval_static_operation op (approx_regs before args) in\n          D.set res a before\n      | Iload chunk addr args dst s =>\n          let a := eval_static_load gapp chunk\n                     (eval_static_addressing addr (approx_regs before args)) in\n          D.set dst a before\n      | Icall sig ros args res s =>\n          D.set res Unknown before\n      | Ibuiltin ef args res s =>\n          D.set res Unknown before\n      | _ =>\n          before\n      end\n  end.\n\n(** The static analysis itself is then an instantiation of Kildall's\n  generic solver for forward dataflow inequations. [analyze f]\n  returns a mapping from program points to mappings of pseudo-registers\n  to approximations.  It can fail to reach a fixpoint in a reasonable\n  number of iterations, in which case we use the trivial mapping\n  (program point -> [D.top]) instead. *)\n\nModule DS := Dataflow_Solver(D)(NodeSetForward).\n\nDefinition analyze (gapp: global_approx) (f: RTL.function): PMap.t D.t :=\n  match DS.fixpoint (successors f) (transfer gapp f) \n                    ((f.(fn_entrypoint), D.top) :: nil) with\n  | None => PMap.init D.top\n  | Some res => res\n  end.\n\n(** * Code transformation *)\n\n(** The code transformation proceeds instruction by instruction.\n    Operators whose arguments are all statically known are turned\n    into ``load integer constant'', ``load float constant'' or\n    ``load symbol address'' operations.  Likewise for loads whose\n    result can be statically predicted.  Operators for which some\n    but not all arguments are known are subject to strength reduction,\n    and similarly for the addressing modes of load and store instructions.\n    Conditional branches and multi-way branches are statically resolved\n    into [Inop] instructions if possible. Other instructions are unchanged. *)\n\nDefinition transf_ros (app: D.t) (ros: reg + ident) : reg + ident :=\n  match ros with\n  | inl r =>\n      match D.get r app with\n      | G symb ofs => if Int.eq ofs Int.zero then inr _ symb else ros\n      | _ => ros\n      end\n  | inr s => ros\n  end.\n\nParameter generate_float_constants : unit -> bool.\n\nDefinition const_for_result (a: approx) : option operation :=\n  match a with\n  | I n => Some(Ointconst n)\n  | F n => if generate_float_constants tt then Some(Ofloatconst n) else None\n  | G symb ofs => Some(Oaddrsymbol symb ofs)\n  | S ofs => Some(Oaddrstack ofs)\n  | _ => None\n  end.\n\nDefinition transf_instr (gapp: global_approx) (app: D.t) (instr: instruction) :=\n  match instr with\n  | Iop op args res s =>\n      let a := eval_static_operation op (approx_regs app args) in\n      match const_for_result a with\n      | Some cop =>\n          Iop cop nil res s\n      | None =>\n          let (op', args') := op_strength_reduction op args (approx_regs app args) in\n          Iop op' args' res s\n      end\n  | Iload chunk addr args dst s =>\n      let a := eval_static_load gapp chunk\n                  (eval_static_addressing addr (approx_regs app args)) in\n      match const_for_result a with\n      | Some cop =>\n          Iop cop nil dst s\n      | None =>\n          let (addr', args') := addr_strength_reduction addr args (approx_regs app args) in\n          Iload chunk addr' args' dst s      \n      end\n  | Istore chunk addr args src s =>\n      let (addr', args') := addr_strength_reduction addr args (approx_regs app args) in\n      Istore chunk addr' args' src s      \n  | Icall sig ros args res s =>\n      Icall sig (transf_ros app ros) args res s\n  | Itailcall sig ros args =>\n      Itailcall sig (transf_ros app ros) args\n  | Ibuiltin ef args res s =>\n      let (ef', args') := builtin_strength_reduction ef args (approx_regs app args) in\n      Ibuiltin ef' args' res s\n  | Icond cond args s1 s2 =>\n      match eval_static_condition cond (approx_regs app args) with\n      | Some b =>\n          if b then Inop s1 else Inop s2\n      | None =>\n          let (cond', args') := cond_strength_reduction cond args (approx_regs app args) in\n          Icond cond' args' s1 s2\n      end\n  | Ijumptable arg tbl =>\n      match approx_reg app arg with\n      | I n =>\n          match list_nth_z tbl (Int.unsigned n) with\n          | Some s => Inop s\n          | None => instr\n          end\n      | _ => instr\n      end\n  | _ =>\n      instr\n  end.\n\nDefinition transf_code (gapp: global_approx) (app: PMap.t D.t) (instrs: code) : code :=\n  PTree.map (fun pc instr => transf_instr gapp app!!pc instr) instrs.\n\nDefinition transf_function (gapp: global_approx) (f: function) : function :=\n  let approxs := analyze gapp f in\n  mkfunction\n    f.(fn_sig)\n    f.(fn_params)\n    f.(fn_stacksize)\n    (transf_code gapp approxs f.(fn_code))\n    f.(fn_entrypoint).\n\nDefinition transf_fundef (gapp: global_approx) (fd: fundef) : fundef :=\n  AST.transf_fundef (transf_function gapp) fd.\n\nFixpoint make_global_approx (gapp: global_approx) (vars: list (ident * globvar unit)) : global_approx :=\n  match vars with\n  | nil => gapp\n  | (id, gv) :: vars' =>\n      let gapp1 :=\n        if gv.(gvar_readonly) && negb gv.(gvar_volatile)\n        then PTree.set id gv.(gvar_init) gapp\n        else PTree.remove id gapp in\n      make_global_approx gapp1 vars'\n  end.\n\nDefinition transf_program (p: program) : program :=\n  let gapp := make_global_approx (PTree.empty _) p.(prog_vars) in\n  transform_program (transf_fundef gapp) p.\n", "meta": {"author": "Ptival", "repo": "compcert-alias", "sha": "c839efb9cd2a4c27add46a1868fe0444d1dfdd9e", "save_path": "github-repos/coq/Ptival-compcert-alias", "path": "github-repos/coq/Ptival-compcert-alias/compcert-alias-c839efb9cd2a4c27add46a1868fe0444d1dfdd9e/backend/Constprop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.24277035394449056}}
{"text": "Require Import floyd.proofauto.\nRequire Import sha.sha.\nRequire Import sha.SHA256.\nRequire Import sha.spec_sha.\nRequire Import sha.sha_lemmas.\nLocal Open Scope logic.\n\nDefinition Delta_final_if1 : tycontext.\nsimplify_Delta_from\n (initialized _n  (initialized _p\n     (func_tycontext f_SHA256_Final Vprog Gtot))).\nDefined.\n\nDefinition Body_final_if1 := \n  (Ssequence\n              (Scall None\n                (Evar _memset (Tfunction\n                                (Tcons (tptr tvoid)\n                                  (Tcons tint (Tcons tuint Tnil)))\n                                (tptr tvoid) cc_default))\n                ((Ebinop Oadd (Etempvar _p (tptr tuchar)) (Etempvar _n tuint)\n                   (tptr tuchar)) :: (Econst_int (Int.repr 0) tint) ::\n                 (Ebinop Osub\n                   (Ebinop Omul (Econst_int (Int.repr 16) tint)\n                     (Econst_int (Int.repr 4) tint) tint) (Etempvar _n tuint)\n                   tuint) :: nil))\n              (Ssequence\n                (Sset _n (Econst_int (Int.repr 0) tint))\n                (Scall None\n                  (Evar _sha256_block_data_order (Tfunction\n                                                   (Tcons\n                                                     (tptr t_struct_SHA256state_st)\n                                                     (Tcons (tptr tvoid)\n                                                       Tnil)) tvoid cc_default))\n                  ((Etempvar _c (tptr t_struct_SHA256state_st)) ::\n                   (Etempvar _p (tptr tuchar)) :: nil)))).\n\nDefinition invariant_after_if1 hashed (dd: list Z) c md shmd  hi lo kv:= \n   (EX hashed':list int, EX dd': list Z, EX pad:Z,\n   PROP  (Forall isbyteZ dd';\n              pad=0%Z \\/ dd'=nil;\n              (length dd' + 8 <= CBLOCK)%nat;\n              (0 <= pad < 8)%Z;\n              (LBLOCKz | Zlength hashed')%Z;\n              intlist_to_Zlist hashed' ++ dd' =\n              intlist_to_Zlist hashed ++  dd \n                  ++ [128%Z] ++ list_repeat (Z.to_nat pad) 0)\n   LOCAL \n   (`(eq (Vint (Int.repr (Zlength dd')))) (eval_id _n);\n   `eq (eval_id _p)\n     (`(offset_val (Int.repr 40)) (`force_ptr (eval_id _c)));\n   `(eq md) (eval_id _md); `(eq c) (eval_id _c);\n                     `(eq kv) (eval_var _K256 (tarray tuint CBLOCKz)))\n   SEP  (`(array_at tuint Tsh (ZnthV tuint (map Vint (hash_blocks init_registers hashed'))) 0 8 c);\n   `(field_at Tsh t_struct_SHA256state_st [_Nl] (Vint lo) c);\n   `(field_at Tsh t_struct_SHA256state_st [_Nh] (Vint hi) c);\n   `(array_at tuchar Tsh (ZnthV tuchar (map Vint (map Int.repr dd'))) 0 64 \n                          (offset_val (Int.repr 40) c));\n   `(field_at_ Tsh t_struct_SHA256state_st [_num] c);\n   `(K_vector kv);\n   `(memory_block shmd (Int.repr 32) md))).\n\nLemma ifbody_final_if1:\n  forall (Espec : OracleKind) (hashed : list int) (md c : val) (shmd : share)\n  (hi lo : int) (dd : list Z) (kv: val)\n (H4: (LBLOCKz  | Zlength hashed))\n (H7: ((Zlength hashed * 4 + Zlength dd)*8 = hilo hi lo)%Z)\n (H3: Zlength dd < CBLOCKz)\n (DDbytes: Forall isbyteZ dd),\n  semax Delta_final_if1\n  (PROP  ()\n   LOCAL \n   (`(typed_true tint)\n      (eval_expr\n         (Ebinop Ogt (Etempvar _n tuint)\n            (Ebinop Osub\n               (Ebinop Omul (Econst_int (Int.repr 16) tint)\n                  (Econst_int (Int.repr 4) tint) tint)\n               (Econst_int (Int.repr 8) tint) tint) tint));\n   `(eq (Vint (Int.repr (Zlength dd + 1)))) (eval_id _n);\n   `(eq (offset_val (Int.repr 40) (force_ptr c))) (eval_id _p);\n   `(eq md) (eval_id _md); `(eq c) (eval_id _c);\n                     `(eq kv) (eval_var _K256 (tarray tuint CBLOCKz)))\n   SEP \n   (`(array_at tuint Tsh\n        (ZnthV tuint (map Vint (hash_blocks init_registers hashed))) 0 8 c);\n   `(field_at Tsh t_struct_SHA256state_st [_Nl] (Vint lo) c);\n   `(field_at Tsh t_struct_SHA256state_st [_Nh] (Vint hi) c);\n   `(array_at tuchar Tsh\n       (ZnthV tuchar (map Vint (map Int.repr dd) ++ [Vint (Int.repr 128)])) 0 64\n       (offset_val (Int.repr 40) c));\n   `(field_at Tsh t_struct_SHA256state_st [_num] (Vint (Int.repr (Zlength dd))) c);\n   `(K_vector kv);\n   `(memory_block shmd (Int.repr 32) md)))\n  Body_final_if1\n  (normal_ret_assert (invariant_after_if1 hashed dd c md shmd hi lo kv)).\nProof.\nassert (H:=True).\nname md_ _md.\nname c_ _c.\nname p _p.\nname n _n.\nname cNl _cNl.\nname cNh _cNh.\nintros.\nchange 40 with data_offset.\nassert (Hddlen: (0 <= Zlength dd < CBLOCKz)%Z) by Omega1.\nset (ddlen := Zlength dd) in *.\n unfold Delta_final_if1; simplify_Delta; unfold Body_final_if1; abbreviate_semax.\nchange CBLOCKz with 64 in Hddlen.\nrewrite (split_offset_array_at tuchar) with (lo := ddlen+1) (hi := 64); [|omega| simpl; omega | reflexivity].\nnormalize.\nrename H0 into H99; rename H1 into H98.\nforward_call (* memset (p+n,0,SHA_CBLOCK-n); *)\n   ((Tsh,\n     offset_val (Int.repr (ddlen + 1)) (offset_val (Int.repr data_offset) c)%Z, \n     (CBLOCKz - (ddlen + 1)))%Z,\n     Int.zero).\n  {\n  remember (array_at tuchar Tsh\n       (fun i : Z =>\n        ZnthV tuchar (map Vint (map Int.repr dd) ++ [Vint (Int.repr 128)])\n          (i + (ddlen + 1))) 0 (64 - (ddlen + 1))\n    (offset_val (Int.repr (data_offset + (ddlen + 1))) c))\n     as A.\n  entailer!.\n  change CBLOCKz with 64%Z; assert (Int.max_unsigned > 64%Z) by computable; omega.\n  change CBLOCKz with 64%Z.\n  normalize.\n   repeat rewrite <- sepcon_assoc;\n    pull_left (array_at tuchar Tsh\n     (fun i : Z =>\n      ZnthV tuchar (map Vint (map Int.repr dd) ++ [Vint (Int.repr 128)])\n        (i + (ddlen + 1))) 0 (64 - (ddlen + 1))\n     (offset_val (Int.repr (data_offset + (ddlen + 1))) c)).\n   repeat rewrite sepcon_assoc; apply sepcon_derives; [ | cancel].\n  destruct (zlt (ddlen+1) 64).\n  - rewrite memory_block_array_tuchar by Omega1.\n    replace (offset_val (Int.repr (data_offset + (ddlen+1))) c)%Z\n     with (offset_val (Int.repr (sizeof tuchar * (ddlen+1))) (offset_val (Int.repr 40) c))%Z\n     by (normalize; Omega1).\n    cancel.\n - replace (ddlen+1)%Z with 64%Z by omega. rewrite array_at_emp.\n    rewrite Z.sub_diag.\n   destruct c; try (contradiction Pc). simpl.   \n   rewrite memory_block_zero. normalize.\n}\nafter_call.\ngather_SEP 1%Z 0%Z.\npose (ddz := ((map Int.repr dd ++ [Int.repr 128]) ++ list_repeat (Z.to_nat (CBLOCKz-(ddlen+1))) Int.zero)).\nreplace_SEP 0%Z (  `(array_at tuchar Tsh\n        (ZnthV tuchar (map Vint ddz)) 0 64\n          (offset_val (Int.repr data_offset) c))).\n{\n replace (Int.repr (data_offset + (ddlen+1))) with (Int.add (Int.repr data_offset) (Int.repr (ddlen+1)))\n  by apply add_repr.\n entailer!.\n normalize in H2.\n change CBLOCKz with 64 in Hddlen.\n apply ltu_repr in H2; [ | Omega1 | Omega1].\n change (16*4)%Z with (CBLOCKz) in H2.\n rewrite (split_offset_array_at tuchar) with (lo := ddlen+1) (hi := 64); [| omega | simpl; omega | reflexivity].\n apply sepcon_derives.\n + entailer!. apply derives_refl'; apply equal_f; apply array_at_ext; intros.\n    unfold ZnthV. if_tac; try omega.\n    unfold ddz.\n    repeat rewrite map_app. simpl map.\n   set (dd1 :=  map Vint (map Int.repr dd) ++ [Vint (Int.repr 128)%Z]).\n   rewrite app_nth1. auto. \n   unfold dd1; rewrite app_length. \n   unfold ddlen in *; rewrite Zlength_correct in *;\n   rewrite map_length in *. simpl.\n    apply Nat2Z.inj_lt. rewrite Z2Nat.id by Omega1.\n  rewrite map_length; rewrite Nat2Z.inj_add; Omega1.\n +  clear - Pc_ Hddlen.\n assert (ddlen = Zlength dd) by reflexivity.\n  replace (Int.repr (data_offset+(ddlen+1))%Z)\n   with (Int.add  (Int.repr data_offset) (Int.repr (sizeof tuchar * (ddlen+1))))%Z\n  by normalize.\n rewrite <- offset_offset_val.\n change CBLOCKz with 64%Z.\n replace (ddlen + 1 + (64 - (ddlen + 1)))%Z with 64%Z by omega.\n apply derives_refl'; apply equal_f; apply array_at_ext; intros.\n symmetry.\n unfold ZnthV. rewrite if_false by omega.\n unfold ddz. clear ddz. rewrite map_app.\n rewrite app_nth2;  rewrite map_length; rewrite app_length.\n  rewrite (nth_map' Vint _ Int.zero).\n f_equal.\n apply nth_list_repeat.\n  simpl. rewrite map_length, length_list_repeat.\n change CBLOCKz with 64.\n replace (length dd + 1)%nat with (Z.to_nat (ddlen + 1)).\n rewrite <- Z2Nat.inj_sub by omega.\n apply Z2Nat.inj_lt; try omega. rewrite H.\n rewrite Z2Nat.inj_add; try omega.\n rewrite Zlength_correct, Nat2Z.id. auto.\n rewrite map_length; simpl. Omega1.\n}\npose (ddzw := Zlist_to_intlist (map Int.unsigned ddz)).\nassert (H0': length ddz = CBLOCK). {\nunfold ddz; repeat rewrite app_length.\nrewrite length_list_repeat by omega.\nrewrite Z2Nat.inj_sub by omega.\nrewrite Z2Nat.inj_add by omega.\nchange (Z.to_nat CBLOCKz) with CBLOCK.\nunfold ddlen; rewrite Zlength_correct. \nrewrite (Nat2Z.id).\nrewrite map_length; simpl length; change (Z.to_nat 1) with 1%nat.\nclear - Hddlen. unfold ddlen in Hddlen.\ndestruct Hddlen. \nrewrite Zlength_correct in H0.\nchange 64 with (Z.of_nat CBLOCK) in H0.\napply Nat2Z.inj_lt in H0. omega.\n}\nassert (H1: length ddzw = LBLOCK). {\nunfold ddzw.\napply length_Zlist_to_intlist. rewrite map_length. apply H0'.\n}\nassert (HU: map Int.unsigned ddz = intlist_to_Zlist ddzw). {\nunfold ddzw; rewrite Zlist_to_intlist_to_Zlist; auto.\nrewrite map_length, H0'; exists LBLOCK; reflexivity.\nunfold ddz; repeat rewrite map_app; repeat rewrite Forall_app; repeat split; auto.\napply Forall_isbyteZ_unsigned_repr; auto.\nconstructor. compute. clear; split; congruence.\nconstructor.\nrewrite map_list_repeat.\napply Forall_list_repeat.\nrewrite Int.unsigned_zero. split; clear; omega.\n}\nclear H0'.\nclearbody ddzw.\n forward.  (* n=0; *)\n forward_call (* sha256_block_data_order (c,p); *)\n  (hashed, ddzw, c, offset_val (Int.repr data_offset) c, Tsh, kv).\n {rewrite Zlength_correct, H1.\n  entailer!.\n repeat rewrite sepcon_assoc; apply sepcon_derives; [ | cancel].\n unfold data_block.\n simpl. apply andp_right.\n apply prop_right.\n apply isbyte_intlist_to_Zlist.\n apply derives_refl'; f_equal. \n unfold tuchars. f_equal. f_equal.\n rewrite <- HU.\n rewrite map_map.\n replace (fun x => Int.repr (Int.unsigned x)) with (@id int) by \n  (extensionality xx; rewrite Int.repr_unsigned; auto).\n symmetry; apply map_id.\n rewrite Zlength_correct;rewrite length_intlist_to_Zlist;\n  rewrite H1; reflexivity.\n}\nafter_call.\nunfold invariant_after_if1.\nchange 40%Z with data_offset.\n apply exp_right with (hashed ++ ddzw).\nset (pad := (CBLOCKz - (ddlen+1))%Z) in *.\n apply exp_right with (@nil Z).\n apply exp_right with pad.\nentailer.\nnormalize in H5.\napply ltu_repr in H5; [ | split; computable \n  | change CBLOCKz with 64 in Hddlen; Omega1].\nsimpl in H2.\nassert (0 <= pad < 8)%Z.\nunfold pad.\nchange (16*4)%Z with (CBLOCKz) in H5. \nchange (CBLOCKz) with CBLOCKz in H5|-*; omega.\nassert (length (list_repeat (Z.to_nat pad) 0) < 8)%nat.\nrewrite length_list_repeat.\napply Nat2Z.inj_lt.\nrewrite Z2Nat.id by omega.\nOmega1. \nentailer!.\n* clear; Omega1.\n* rewrite initial_world.Zlength_app.\n   apply Zlength_length in H1; [ | auto]. rewrite H1.\n clear - H4; destruct H4 as [n ?]; exists (n+1). \n  rewrite Z.mul_add_distr_r; omega.\n* rewrite <- app_nil_end.\n  rewrite intlist_to_Zlist_app.\n  f_equal.\n  rewrite <- HU.\n  unfold ddz.\n  repeat rewrite map_app.\n  repeat rewrite app_ass.\n f_equal.\n clear - DDbytes; induction dd; simpl.\n  auto.\n inv DDbytes; f_equal; auto.\n apply Int.unsigned_repr; unfold isbyteZ in H1; repable_signed.\n rewrite map_list_repeat.\n simpl.  f_equal.\n*\n unfold data_block.\n simpl. apply andp_left2.\n replace (Zlength (intlist_to_Zlist ddzw)) with 64%Z.\n apply array_at_array_at_.\n reflexivity.\n rewrite Zlength_correct; rewrite length_intlist_to_Zlist.\n rewrite H1;  reflexivity.\nQed.\n\nLemma nth_intlist_to_Zlist_eq:\n forall d (n i j k: nat) al, (i < n)%nat -> (i < j*4)%nat -> (i < k*4)%nat -> \n    nth i (intlist_to_Zlist (firstn j al)) d = nth i (intlist_to_Zlist (firstn k al)) d.\nProof.\n induction n; destruct i,al,j,k; simpl; intros; auto; try omega.\n destruct i; auto. destruct i; auto. destruct i; auto.\n apply IHn; omega.\nQed.\n\nDefinition final_loop :=\n (Ssequence (Sset _xn (Econst_int (Int.repr 0) tint))\n                 (Sloop\n                    (Ssequence\n                       (Sifthenelse\n                          (Ebinop Olt (Etempvar _xn tuint)\n                             (Ebinop Odiv (Econst_int (Int.repr 32) tint)\n                                (Econst_int (Int.repr 4) tint) tint) tint)\n                          Sskip Sbreak)\n                       (Ssequence\n                          (Sset _ll\n                             (Ederef\n                                (Ebinop Oadd\n                                   (Efield\n                                      (Ederef\n                                         (Etempvar _c\n                                            (tptr t_struct_SHA256state_st))\n                                         t_struct_SHA256state_st) _h\n                                      (tarray tuint 8)) (Etempvar _xn tuint)\n                                   (tptr tuint)) tuint))\n                          (Ssequence\n                             (Scall None\n                                (Evar ___builtin_write32_reversed\n                                   (Tfunction\n                                      (Tcons (tptr tuint) (Tcons tuint Tnil))\n                                      tvoid cc_default))\n                                [Ecast (Etempvar _md (tptr tuchar))\n                                   (tptr tuint), Etempvar _ll tuint])\n                             (Sset _md\n                                (Ebinop Oadd (Etempvar _md (tptr tuchar))\n                                   (Econst_int (Int.repr 4) tint)\n                                   (tptr tuchar))))))\n                    (Sset _xn\n                       (Ebinop Oadd (Etempvar _xn tuint)\n                          (Econst_int (Int.repr 1) tint) tuint)))).\n\nLemma nth_intlist_to_Zlist_first_hack:\n  forall  j i al, \n    (i*4 <= j)%nat ->\n    nth (j-i*4) (intlist_to_Zlist [nth i al Int.zero]) 0 =\n    nth j (intlist_to_Zlist (firstn (S i) al)) 0.\nProof.\nintros.\n assert (j= (j-i*4) + i*4)%nat by omega.\n rewrite H0 at 2.\n forget (j-i*4)%nat as n. clear.\n revert n al; induction i; intros.\n change (0*4)%nat with O.  \n rewrite NPeano.Nat.add_0_r.\n destruct al; try reflexivity.\n simpl firstn.\n rewrite (nth_overflow nil) by (simpl; auto).\n simpl intlist_to_Zlist.\n repeat (destruct n; try reflexivity).\n replace (n + S i * 4)%nat with (n+4 + i*4)%nat\n  by (simpl; omega).\n destruct al as [ | a al].\n rewrite (nth_overflow nil) by (simpl; clear; omega).\n simpl firstn. simpl intlist_to_Zlist.\n rewrite (nth_overflow nil) by (simpl; clear; omega).\n repeat (destruct n; try reflexivity).\n simpl nth at 2.\n replace (firstn (S (S i)) (a :: al)) with (a :: firstn (S i) al).\n unfold intlist_to_Zlist at 2; fold intlist_to_Zlist.\n rewrite IHi. clear IHi.\n replace (n + 4 + i*4)%nat with (S (S (S (S (n + i*4)))))%nat by omega.\n reflexivity.\n clear.\n forget (S i) as j.\n revert al; induction j; simpl; intros; auto.\nQed.\n\nLemma final_part4:\n forall (Espec: OracleKind) md c shmd hashedmsg kv,\n length hashedmsg = 8%nat ->\n writable_share shmd ->\nsemax\n  (initialized _cNl (initialized _cNh Delta_final_if1))\n  (PROP  ()\n   LOCAL  (`(eq md) (eval_id _md); `(eq c) (eval_id _c))\n   SEP \n   (`(array_at tuchar Tsh (fun _ : Z => Vint Int.zero) 0 64\n        (offset_val (Int.repr data_offset) c));\n   `(array_at tuint Tsh (tuints hashedmsg) 0 8 c);\n   `(K_vector kv);\n   `(field_at_ Tsh t_struct_SHA256state_st [_Nl] c);\n   `(field_at_ Tsh t_struct_SHA256state_st [_Nh] c);\n   `(field_at Tsh t_struct_SHA256state_st [_num] (Vint (Int.repr 0)) c);\n   `(memory_block shmd (Int.repr 32) md)))\n  (Ssequence final_loop (Sreturn None))\n  (function_body_ret_assert tvoid\n     (PROP  ()\n      LOCAL ()\n      SEP  (`(K_vector kv);\n      `(data_at_ Tsh t_struct_SHA256state_st c);\n      `(data_block shmd (intlist_to_Zlist hashedmsg) md)))).\nProof.\nintros.\nunfold final_loop; abbreviate_semax.\nrewrite memory_block_isptr.\nnormalize. rename H1 into Hmd.\nforward.  (* xn=0; *)\n\nDefinition part4_inv  c shmd hashedmsg md kv delta (i: nat) :=\n   (PROP  ((i <= 8)%nat)\n   LOCAL  (`(eq (Vint (Int.repr (Z.of_nat i - delta)))) (eval_id _xn);\n      `(eq (offset_val (Int.repr (Z.of_nat i * 4)) md)) (eval_id _md);\n   `(eq c) (eval_id _c))\n   SEP \n   (`(array_at tuchar Tsh (fun _ : Z => Vint Int.zero) 0 64\n        (offset_val (Int.repr data_offset) c));\n   `(array_at tuint Tsh (tuints hashedmsg) 0 8 c);\n   `(K_vector kv);\n   `(field_at_ Tsh t_struct_SHA256state_st [_Nl] c);\n   `(field_at_ Tsh t_struct_SHA256state_st [_Nh] c);\n   `(field_at Tsh t_struct_SHA256state_st [_num] (Vint (Int.repr 0)) c);\n   `(array_at tuchar shmd (tuchars (map Int.repr (intlist_to_Zlist (firstn i hashedmsg))))\n              0 32 md))).\n\nforward_for \n   (EX i:_, part4_inv c shmd hashedmsg md kv 0 i) \n   (EX i:_, part4_inv c shmd hashedmsg md kv 1 i) \n   (part4_inv c shmd hashedmsg md kv 0 8).\n* apply exp_right with 0%nat. unfold part4_inv; rewrite Z.sub_0_r.\n  entailer!.\n  change 32%Z with (sizeof (tarray tuchar 32)).\n  apply derives_trans with (data_at_ shmd (tarray tuchar 32) _id0).\n  rewrite <- memory_block_data_at_ by reflexivity.\n  unfold align_compatible.\n  simpl (alignof (tarray tuchar 32)).\n  simpl.\n  destruct _id0; inversion Hmd. assert (1 | Int.unsigned i) by apply Z.divide_1_l.\n  entailer!.\n  unfold data_at_.\n  unfold_data_at 1%nat.\n  normalize.\n* quick_typecheck.\n* unfold part4_inv.  repeat rewrite Z.sub_0_r.\n  rewrite (firstn_same _ 8) by omega.\n  entailer.\n  rewrite <- H2 in *.\n  simpl in H5.\n simpl_compare.\n change (Int.divs (Int.repr 32) (Int.repr 4)) with (Int.repr 8) in H5.\n apply ltu_repr_false in H5; try repable_signed; try omega.\n assert (i=8)%nat by omega.\n subst i. change (Z.of_nat 8) with 8%Z.\n entailer!.\n  rewrite (firstn_same _ 8) by omega. auto. \n* unfold part4_inv.\n rewrite insert_local.\n match goal with |- semax _ (PROPx _ (LOCALx (_:: ?Q) ?R)) _ _ =>\n   apply semax_pre with (PROP ((i<8)%nat) (LOCALx Q R))\n  end.\n rewrite Z.sub_0_r.\n entailer!.\n change (Int.divs (Int.repr 32) (Int.repr 4)) with (Int.repr 8) in H2.\n apply ltu_repr in H2; try repable_signed; try omega.\n normalize.\n rewrite Z.sub_0_r.\n forward. (* ll=(c)->h[xn]; *)\n  entailer!.\n  omega.\n  unfold tuints, ZnthV. rewrite if_false by omega.\n  rewrite Nat2Z.id.\n  rewrite (nth_map' Vint _ Int.zero).\n  apply I.\n  omega.\n pose (w := nth i hashedmsg Int.zero).\n pose (bytes := Basics.compose force_int (ZnthV tuchar (map Vint (map Int.repr (intlist_to_Zlist [w]))))).\n  forward_call (* builtin_write32_reversed *)\n     (offset_val (Int.repr (Z.of_nat i * 4)) md, shmd, bytes).\n entailer!.\n  rewrite Int.signed_repr in H3 by repable_signed.\n  auto.\n destruct md; try (contradiction Hmd); reflexivity.\n unfold tuints, ZnthV in H3.\n rewrite Int.signed_repr in H3 by repable_signed.\n  rewrite if_false in H3 by omega.\n rewrite Nat2Z.id in H3.\n rewrite (nth_map' _ _ Int.zero) in H3 by omega.\n inv H3.\n symmetry; unfold bytes, Basics.compose;\n replace (fun x : Z =>\n   force_int\n     (ZnthV tuchar\n        (map Vint (map Int.repr (intlist_to_Zlist [w]))) x))\n  with \n  (fun x : Z =>\n   force_int\n     (ZnthV tuchar\n        (map Vint (map Int.repr (intlist_to_Zlist [w]))) \n              (x + Z.of_nat O * 4)))\n by (extensionality j; repeat f_equal; simpl; apply Z.add_0_r).\n apply nth_big_endian_integer.\n reflexivity.\n{\n entailer.\n replace (memory_block shmd (Int.repr 4)) with ((fun p : val => !!align_compatible (tarray tuchar 4) p) && memory_block shmd (Int.repr (sizeof (tarray tuchar 4)))).\n Focus 2. {\n   extensionality p. simpl.\n   rewrite andp_comm, <- add_andp; auto.\n   apply prop_right; unfold align_compatible; simpl.\n   destruct p; auto; apply Z.divide_1_l.\n } Unfocus.\n  rewrite memory_block_data_at_ by reflexivity.\n  unfold data_at_.\n  unfold tarray.\n  erewrite data_at_array_at; [| reflexivity | simpl; omega | reflexivity].\n rewrite (split_array_at (Z.of_nat (S i) * 4)%Z tuchar _ _ _ 32 md)\n   by (rewrite inj_S; split; omega).\n assert (Z.of_nat (S i) * 4 = Z.of_nat i * 4 + 4)%Z.\n   rewrite inj_S. unfold Z.succ.\n   rewrite Z.mul_add_distr_r. reflexivity.\n erewrite (split_offset_array_at tuchar shmd) with (lo := (Z.of_nat i * 4)%Z);\n [| omega | simpl; omega | reflexivity].\n normalize.\n pull_left (array_at tuchar shmd\n     (fun i0 : Z =>\n      tuchars (map Int.repr (intlist_to_Zlist (firstn i hashedmsg)))\n        (i0 + Z.of_nat i * 4)) 0 (Z.of_nat (S i) * 4 - Z.of_nat i * 4)\n     (offset_val (Int.repr (Z.of_nat i * 4)) md)).\n repeat rewrite sepcon_assoc; apply sepcon_derives; [ | cancel_frame].\n replace (offset_val (Int.repr (Z.of_nat i * 4)))\n   with (offset_val (Int.repr (sizeof tuchar * (Z.of_nat i * 4))))\n  by (f_equal; f_equal; apply Z.mul_1_l).\n rewrite array_at_ZnthV_nil.\n\n rewrite H4.\n replace ((Z.of_nat i * 4 + 4 - Z.of_nat i * 4)) with 4 by omega.\n apply array_at_array_at_; reflexivity.\n}\n after_call.\n normalize.\n forward. (* md += 4; *)\n entailer!.\n unfold loop1_ret_assert;  simpl update_tycon.\n unfold part4_inv. apply exp_right with (S i). rewrite inj_S.\n{\n entailer!.\n f_equal; omega.\n destruct md; try (contradiction Hmd); simpl; f_equal.\n f_equal. f_equal.\n unfold Z.succ. rewrite Z.mul_add_distr_r. reflexivity.\n replace (match hashedmsg with\n               | [] => []\n               | a :: l => a :: firstn i l\n               end) with (firstn (S i) hashedmsg)\n  by (clear; destruct hashedmsg; auto).\n rewrite (split_array_at (Z.of_nat (S i) * 4)%Z tuchar _ _ 0 32 md)\n   by (rewrite inj_S; split; omega).\n assert (Z.of_nat (S i) * 4 = Z.of_nat i * 4 + 4)%Z as H99.\n   rewrite inj_S. unfold Z.succ.\n   rewrite Z.mul_add_distr_r. reflexivity.\n erewrite (split_offset_array_at tuchar shmd) with (lo := (Z.of_nat i * 4)%Z) (hi := (Z.of_nat (S i) * 4)%Z);\n [| omega | simpl; omega | reflexivity].\n repeat rewrite <- sepcon_assoc.\n pull_left (array_at tuchar shmd\n  (tuchars (map Int.repr (intlist_to_Zlist (firstn i hashedmsg)))) 0\n  (Z.of_nat i * 4) md).\n replace (Z.succ (Z.of_nat i)) with (Z.of_nat (S i)) by apply Nat2Z.inj_succ.\n rewrite (add_andp (array_at tuchar shmd\n     (tuchars (map Int.repr (intlist_to_Zlist (firstn i hashedmsg))))\n     (Z.of_nat (S i) * 4) 32 md) (!!offset_in_range (sizeof tuchar * (Z.of_nat (S i) * 4)) md)) by\n   (unfold array_at; normalize).\n rewrite (add_andp (array_at tuchar shmd\n     (tuchars (map Int.repr (intlist_to_Zlist (firstn i hashedmsg))))\n     (Z.of_nat (S i) * 4) 32 md) (!!offset_in_range (sizeof tuchar * 0) md)) by\n    ( apply prop_right; unfold offset_in_range; destruct md; auto;\n    pose proof Int.unsigned_range i0; omega).\n normalize.\n rename H3 into H98; rename H4 into H97.\n repeat apply sepcon_derives; auto.\n + \n apply derives_refl'; apply equal_f; apply array_at_ext; intros.\n unfold tuchars, ZnthV. rewrite if_false by omega.\n rewrite if_false by omega.\n rewrite map_map. rewrite map_map.\n rewrite (nth_map' _ _ 0%Z).\nFocus 2.\n clear - H3 H H1. rewrite length_intlist_to_Zlist. rewrite firstn_length.\n  rewrite min_l by omega. destruct H3.\n  apply Nat2Z.inj_lt. rewrite Z2Nat.id by omega.\n  rewrite Nat2Z.inj_mul; rewrite Z.mul_comm; auto.\n rewrite (nth_map' _ _ 0%Z).\nFocus 2. clear - H3 H H1. rewrite length_intlist_to_Zlist. rewrite firstn_length.\n  rewrite min_l by omega. destruct H3.\n  apply Nat2Z.inj_lt. rewrite Z2Nat.id by omega.\n  rewrite Nat2Z.inj_mul. \n rewrite Z.mul_comm; rewrite inj_S.\n unfold Z.succ; rewrite Z.mul_add_distr_r. \n change (1 * Z.of_nat 4) with 4.  change (Z.of_nat 4) with 4; omega.\n do 2 f_equal.\napply (nth_intlist_to_Zlist_eq _ (S (Z.to_nat i0))); try omega.\n apply Nat2Z.inj_lt. rewrite Z2Nat.id by (clear - H3; omega).\n  rewrite Nat2Z.inj_mul; apply H3.\n apply Nat2Z.inj_lt. rewrite Z2Nat.id by (clear - H3; omega).\n clear - H3; rewrite Nat2Z.inj_mul; rewrite inj_S;\n  unfold Z.succ; rewrite Z.mul_add_distr_r.\n  change (Z.of_nat 4) with 4; omega.\n+ rewrite H99.\n  replace (Z.of_nat i * 4 + 4 - Z.of_nat i * 4) with 4 by omega.\n apply derives_refl'; apply equal_f; apply array_at_ext; intros.\n unfold cVint, bytes, tuchars, ZnthV, Basics.compose.\n rewrite if_false by omega. rewrite if_false by omega.\n repeat rewrite map_map.\n rewrite (nth_map' _ _ 0).\nFocus 2.\n simpl. apply Nat2Z.inj_lt. rewrite Z2Nat.id by omega.\n change (Z.of_nat 4) with 4; omega.\n rewrite (nth_map' _ _ 0).\nFocus 2. clear - H99 H3 H H1. rewrite length_intlist_to_Zlist. \n rewrite firstn_length;  rewrite min_l by omega. destruct H3.\n  apply Nat2Z.inj_lt. rewrite Z2Nat.id by omega.\n  rewrite Nat2Z.inj_mul. \n rewrite Z.mul_comm; rewrite inj_S.\n unfold Z.succ. change (Z.of_nat 3 + 1) with 4. omega.\n unfold force_int. f_equal. f_equal.\n clear - H3.\n\n\n\n unfold w; clear w.\n  change 4 with (Z.of_nat 4). rewrite <- Nat2Z.inj_mul.  \n replace (Z.to_nat i0) with (Z.to_nat i0 + i * 4 - i * 4)%nat by omega.\n replace (Z.to_nat (i0 + Z.of_nat (i * 4))) with (Z.to_nat i0 + i * 4)%nat by \n   (rewrite Z2Nat.inj_add by omega; rewrite Nat2Z.id; reflexivity).\n apply nth_intlist_to_Zlist_first_hack; auto.\n omega. \n\n+\n rewrite inj_S.\n apply derives_refl'; apply equal_f; apply array_at_ext; intros.\n unfold tuchars, ZnthV. rewrite if_false by omega.\n rewrite if_false by omega.\n rewrite map_map. rewrite map_map.\n rewrite nth_overflow.\nFocus 2. {\n  rewrite map_length, length_intlist_to_Zlist, firstn_length.\n   rewrite min_l by omega.\n  unfold Z.succ in H3.\n  destruct H3 as [H4 _].\n apply Z2Nat.inj_le in H4; try omega.\n rewrite Z.mul_add_distr_r in H4.\n rewrite Z2Nat.inj_add in H4 by omega.\n change (Z.to_nat (1*4)) with 4%nat in H4.\n rewrite mult_comm.\n replace (i*4)%nat with (Z.to_nat (Z.of_nat i * 4)); [omega | ].\n clear. change 4 with (Z.of_nat 4); rewrite <- Nat2Z.inj_mul;\n  rewrite Nat2Z.id; auto.\n} Unfocus.\n rewrite nth_overflow; [reflexivity | ]. {\n rewrite map_length, length_intlist_to_Zlist, firstn_length.\n  rewrite min_l by omega.\n clear - H3 H H1.\n destruct H3 as [H4 _].\n apply Z2Nat.inj_le in H4; try omega.\n unfold Z.succ in H4.\n rewrite Z.mul_add_distr_r in H4.\n rewrite Z.mul_1_l in H4.\n change 4 with (Z.of_nat 4) in H4.\n rewrite <- Nat2Z.inj_mul, <- Nat2Z.inj_add in H4.\n rewrite Nat2Z.id in H4.\n rewrite mult_comm.\n replace (S i) with (i+1)%nat by omega.\n rewrite  NPeano.Nat.mul_add_distr_r.\n apply H4.\n}\n}\n* (* for-loop increment *)\n unfold part4_inv. apply extract_exists_pre; intro i.\n normalize.\n forward. (* xn++; *)\n apply exp_right with i.\n unfold part4_inv.\n rewrite Z.sub_0_r.\n entailer.\n apply prop_right. f_equal. omega.\n* (* after the loop *)\n unfold part4_inv. \n  rewrite (firstn_same _ 8) by omega.\n forward. (* return; *)\n unfold data_at_.\n unfold_data_at 1%nat.\n unfold_field_at 2%nat.\n unfold_field_at 4%nat.\n repeat rewrite array_at_ZnthV_nil.\n unfold at_offset.  unfold data_block.\n rewrite prop_true_andp with (P:= Forall isbyteZ (intlist_to_Zlist hashedmsg)) by apply isbyte_intlist_to_Zlist.\n replace (Zlength (intlist_to_Zlist hashedmsg)) with 32%Z.\n cancel.\n unfold field_at.\n simpl. entailer!.\n unfold at_offset.\n eapply derives_trans; [apply mapsto_mapsto_| auto].\n rewrite Zlength_correct; rewrite length_intlist_to_Zlist; rewrite H; reflexivity.\nQed.\n", "meta": {"author": "k-qy", "repo": "vst-crypto", "sha": "43532fbb3a3fc04f4ace993dddaae462908b75c0", "save_path": "github-repos/coq/k-qy-vst-crypto", "path": "github-repos/coq/k-qy-vst-crypto/vst-crypto-43532fbb3a3fc04f4ace993dddaae462908b75c0/other/verif_sha_final2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.61878043374385, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2427703539444905}}
{"text": "Require Import LambdaANF.cps LambdaANF.identifiers LambdaANF.ctx LambdaANF.set_util LambdaANF.state\n        LambdaANF.dead_param_elim LambdaANF.Ensembles_util LambdaANF.tactics LambdaANF.map_util\n        LambdaANF.hoisting.\nRequire Import compcert.lib.Coqlib Common.compM Common.Pipeline_utils.\nRequire Import Coq.Lists.List Coq.MSets.MSets Coq.MSets.MSetRBT Coq.Numbers.BinNums\n        Coq.NArith.BinNat Coq.PArith.BinPos Coq.Sets.Ensembles micromega.Lia\n        maps_util.\nRequire Import ExtLib.Structures.Monads ExtLib.Data.Monads.StateMonad.\nImport ListNotations Nnat.\n\n\nImport MonadNotation.\nOpen Scope monad_scope.\n\nOpen Scope ctx_scope.\nOpen Scope fun_scope.\nClose Scope Z_scope.\n\n\nInductive Dead_in_args (S : Ensemble var) : list var -> list bool -> Prop :=\n| Live_nil : Dead_in_args S [] []\n| ALive_cons_Dead :\n    forall (x : var) (xs : list var) (bs: list bool),\n      Dead_in_args S xs bs ->\n      Dead_in_args S (x :: xs) (false :: bs)\n| ALive_cons_Live :\n    forall (x : var) (xs : list var) (bs: list bool),\n      Dead_in_args S xs bs ->\n      ~ x \\in S -> \n      Dead_in_args S (x :: xs) (true :: bs).\n\n\nFixpoint dead_args (ys : list var) (bs : list bool) : list var := \n  match ys, bs with \n  | [], [] => ys\n  | y :: ys', b :: bs' => \n    if b then (dead_args ys' bs')\n    else y :: dead_args ys' bs'\n| _, _ => []\nend. \n\nInductive Dead (S : Ensemble var) (L : live_fun) : exp -> Prop :=\n| Live_Constr : \n    forall (x : var) (ys : list var) (ct : ctor_tag) (e : exp), \n      Disjoint _ (FromList ys) S -> \n      Dead S L e ->\n      Dead S L (Econstr x ct ys e)\n| Live_Prim_val : \n  forall (x : var) p (e : exp), \n    Dead S L e ->\n    Dead S L (Eprim_val x p e)\n| Live_Prim : \n  forall (x : var) (g : prim) (ys : list var) (e : exp), \n    Disjoint _ (FromList ys) S -> \n    Dead S L e ->\n    Dead S L (Eprim x g ys e)\n| Live_Proj : \n    forall (x : var) (ct : ctor_tag) (n : N) (y : var) (e : exp), \n      ~ y \\in S ->\n     Dead S L e ->\n     Dead S L (Eproj x ct n y e)\n| Live_Case: \n    forall (x : var) (ce : list (ctor_tag * exp)),\n      ~ x \\in S ->\n      Forall (fun p => Dead S L (snd p)) ce -> \n      Dead S L (Ecase x ce)\n| Live_Halt : \n    forall (x : var),\n      ~ x \\in S ->\n      Dead S L (Ehalt x)\n| Live_App_Unknown :\n    forall (f : var) (ys : list var) (ft : fun_tag),\n      ~ f \\in S ->\n      Disjoint _ (FromList ys) S -> \n      L ! f = None -> \n      Dead S L (Eapp f ft ys)\n| Live_App_Known :\n    forall (f : var) (ys : list var) (ft : fun_tag) (bs : list bool),\n      L ! f = Some bs ->\n      ~ f \\in S ->\n      Disjoint _ S (FromList (live_args ys bs)) ->\n      Dead S L (Eapp f ft ys)\n| Live_LetApp_Unknown :\n    forall (x f : var) (ys : list var) (ft : fun_tag) (e : exp),\n      ~ f \\in S ->\n      Disjoint _ (FromList ys) S -> \n      L ! f = None ->\n      Dead S L e ->          \n      Dead S L (Eletapp x f ft ys e)\n| Live_LetApp_Known :\n    forall (x f : var) (ys : list var) (ft : fun_tag) (e : exp) (bs : list bool),\n      L ! f = Some bs ->\n      ~ f \\in S ->\n      Disjoint _ S (FromList (live_args ys bs)) ->      \n      Dead S L e ->          \n      Dead S L (Eletapp x f ft ys e). \n  \n  \nDefinition live_map_sound (B : fundefs) (L : live_fun) :=\n  forall f ft xs e bs,\n    fun_in_fundefs B (f, ft, xs, e) ->\n    L ! f = Some bs -> \n    Dead (FromList (dead_args xs bs)) L e. \n\nDefinition live_fun_args (L : live_fun) (f : var) (xs : list var) :=\n  exists bs, L ! f = Some bs /\\ length xs = length bs. \n\nDefinition live_fun_consistent (L : live_fun) (B : fundefs) :=\n  forall f ft xs e,\n    fun_in_fundefs B (f, ft, xs, e) ->\n    live_fun_args L f xs.\n\n(* Lemmas about [live] *)\n\nLemma live_diff B L L' d :\n  live B L d = (L', false) ->\n  d = false.\nProof.\n  revert L L' d. induction B; simpl; intros L L' d Hl; eauto.\n  - destruct (update_live_fun L v l (live_expr L e PS.empty)) as [L'' d''].\n    eapply IHB in Hl. destruct d; eauto. destruct d''; eauto.\n  - inv Hl; eauto.\nQed.\n\nLemma update_live_fun_false L L' f xs S :\n  update_live_fun L f xs S = (L', false) ->\n  L = L' /\\\n  (forall bs,\n      get_fun_vars L f = Some bs ->\n      Disjoint _ (FromSet S) (FromList (dead_args xs bs))).\nProof.\n  intros Hl.\n  unfold update_live_fun in Hl.\n  destruct (get_fun_vars L f) eqn:Hf.\n  - unfold get_fun_vars in *.\n    destruct (update_bs S xs l) as [bs diff] eqn:Hupd.\n    inv Hl.\n    destruct diff. congruence. inv H0.\n    split. reflexivity.\n    intros bs' Hget. inv Hget.\n    \n    assert (Hsuff : Disjoint  positive (FromSet S) (FromList (dead_args xs bs'))).\n    { clear Hf. revert bs bs' Hupd.\n      induction xs; intros bs bs' Hupd.\n      - inv Hupd.\n        destruct bs; eauto; simpl; normalize_sets; sets.\n      - destruct bs'.\n        { simpl. normalize_sets; sets. }\n        simpl in *.\n        \n        destruct (update_bs S xs bs') eqn:Hup. \n        destruct b. inv Hupd.        \n        * eapply IHxs. eassumption.\n        * inv Hupd. \n          eapply orb_false_iff in H1. inv H1.\n          destruct (PS.mem a S) eqn:Hmem. now inv H. clear H.\n          specialize (IHxs l bs' Hup).\n          normalize_sets. eapply Union_Disjoint_r; [| eassumption ].\n          eapply Disjoint_Singleton_r.\n          intros Hc. eapply FromSet_sound in Hc; [| reflexivity ].\n          eapply PS.mem_spec in Hc. congruence. }\n    eassumption.\n\n  - inv Hl. split; eauto. congruence. \nQed.\n\n\nLemma add_fun_vars_subset L v l Q : \n  FromSet Q \\subset FromSet (add_fun_vars L v l Q).\nProof.\n  unfold add_fun_vars. \n  destruct (get_fun_vars L v); rewrite FromSet_union_list; sets.\nQed.\n        \n  \nLemma live_expr_subset L e Q :\n  FromSet Q \\subset FromSet (live_expr L e Q).\nProof.\n  revert Q; induction e using exp_ind'; intros Q; simpl;\n    try now (eapply Included_trans; [| eapply IHe ]; rewrite FromSet_union_list; sets).\n  - rewrite FromSet_add; sets.\n  - simpl in *. rewrite !FromSet_add. setoid_rewrite FromSet_add in IHe0.\n    eapply Included_trans; [| eapply IHe0 ].\n    eapply IHe.\n  - eapply Included_trans; [| eapply IHe ].\n    rewrite FromSet_add; sets.\n  - eapply Included_trans; [| eapply IHe ].\n    eapply Included_trans; [| eapply add_fun_vars_subset ].\n    rewrite !FromSet_add; sets.\n  - sets. \n  - eapply Included_trans; [| eapply add_fun_vars_subset ].\n    rewrite FromSet_add; sets.\n  - auto.\n  - rewrite FromSet_add; sets.  \nQed.\n\nLemma fold_left_live_expr_subset L S (P : list (ctor_tag * exp)) :\n  FromSet S \\subset FromSet (fold_left (fun (S : PS.t) '(_, e') => live_expr L e' S) P S).\nProof.\n  revert S. induction P; simpl; intros; sets.\n  destruct a. eapply Included_trans; [| eapply IHP ].\n  eapply live_expr_subset.\nQed.\n  \nLemma live_args_subset {A} (ys : list A) bs:\n  FromList (live_args ys bs) \\subset FromList ys.\nProof.\n  revert bs; induction ys; intros [ | [|] bs ]; simpl; sets.\n  - repeat normalize_sets. sets.\n  - repeat normalize_sets. sets.\nQed.  \n\n\nLemma live_expr_sound Q L e S :\n  no_fun e ->\n  Disjoint _ (FromSet (live_expr L e Q)) S ->\n  Dead S L e.\nProof.\n  revert Q; induction e using exp_ind'; intros Q; simpl; intros Hnf Hdis; inv Hnf.  \n  - econstructor.\n    + repeat normalize_bound_var_in_ctx. repeat normalize_occurs_free_in_ctx.\n      eapply Disjoint_Included_l; [| eassumption ].\n      eapply Included_trans; [| eapply live_expr_subset ].\n      rewrite FromSet_union_list. sets.\n    + eapply IHe; eauto.\n  - rewrite FromSet_add in *.\n    econstructor; eauto. intros Hc.\n    eapply Hdis. econstructor; eauto.\n  - rewrite FromSet_add in *. econstructor.\n    + intros Hc. eapply Hdis. econstructor; eauto.\n    + econstructor. eapply IHe; eauto.\n      * eapply Disjoint_Included_l; [| eassumption ].\n        eapply Included_Union_preserv_r.\n        eapply fold_left_live_expr_subset.\n      * assert (Hsuff : Dead S L (Ecase v l)).\n        { eapply IHe0; eauto.\n          eapply Disjoint_Included_l; [| eassumption ].\n          simpl. rewrite FromSet_add. sets. }\n        inv Hsuff. eassumption.\n  - econstructor.\n    + repeat normalize_bound_var_in_ctx. repeat normalize_occurs_free_in_ctx.\n      intros Hc. \n      eapply Hdis; eauto. econstructor; eauto. eapply live_expr_subset.\n      rewrite FromSet_add. sets.\n    + eapply IHe; eauto.\n  - destruct (L ! f) eqn:Heq.\n    + eapply Live_LetApp_Known. eassumption. \n      * intros Hc. eapply Hdis. constructor; eauto.\n        eapply live_expr_subset.\n        eapply add_fun_vars_subset. rewrite FromSet_add. sets.\n      * repeat normalize_bound_var_in_ctx. repeat normalize_occurs_free_in_ctx.\n        eapply Disjoint_sym. eapply Disjoint_Included_l; [| eassumption ].\n        eapply Included_trans; [| eapply live_expr_subset ].\n        unfold add_fun_vars, get_fun_vars. rewrite Heq.\n        rewrite FromSet_union_list.  sets.\n      * eapply IHe; eauto.\n    + eapply Live_LetApp_Unknown; eauto.\n      * intros Hc. eapply Hdis. constructor; eauto.\n        eapply live_expr_subset.\n        eapply add_fun_vars_subset. rewrite FromSet_add. sets.\n      * repeat normalize_bound_var_in_ctx. repeat normalize_occurs_free_in_ctx.\n        eapply Disjoint_Included_l; [| eassumption ].\n        eapply Included_trans; [| eapply live_expr_subset ].\n        unfold add_fun_vars. unfold get_fun_vars. rewrite Heq.\n        rewrite FromSet_union_list. sets.\n  - destruct (L ! v) eqn:Heq.\n    + eapply Live_App_Known. eassumption. \n      * intros Hc. eapply Hdis. constructor; eauto.\n        eapply add_fun_vars_subset. rewrite FromSet_add. sets.\n      * repeat normalize_bound_var_in_ctx. repeat normalize_occurs_free_in_ctx.\n        eapply Disjoint_sym. eapply Disjoint_Included_l; [| eassumption ].\n        unfold add_fun_vars, get_fun_vars. rewrite Heq.\n        rewrite FromSet_union_list.  sets.\n    + eapply Live_App_Unknown; eauto.\n      * intros Hc. eapply Hdis. constructor; eauto.\n        eapply add_fun_vars_subset. rewrite FromSet_add. sets.\n      * repeat normalize_bound_var_in_ctx. repeat normalize_occurs_free_in_ctx.\n        eapply Disjoint_Included_l; [| eassumption ].\n        unfold add_fun_vars. unfold get_fun_vars. rewrite Heq.\n        rewrite FromSet_union_list. sets.\n  - econstructor; eauto.\n  - econstructor.\n    + repeat normalize_bound_var_in_ctx. repeat normalize_occurs_free_in_ctx.\n      eapply Disjoint_Included_l; [| eassumption ].\n      eapply Included_trans; [| eapply live_expr_subset ].\n      rewrite FromSet_union_list. sets.\n    + eapply IHe; eauto.\n  - econstructor.\n    + repeat normalize_bound_var_in_ctx. repeat normalize_occurs_free_in_ctx.\n      intros Hc. eapply Hdis. constructor; eauto.\n      rewrite FromSet_add. now sets. \nQed. \n      \nLemma live_correct L L' B :\n  no_fun_defs B -> (* no nested functions in B *)\n  live B L false = (L', false) -> \n  L = L' /\\ live_map_sound B L.\nProof.\n  revert L L'; induction B; simpl; intros L L' Hnf Hl.\n  - destruct (update_live_fun L v l (live_expr L e PS.empty)) as [L'' b] eqn:Heq.\n    \n    assert (Hd := live_diff _ _ _ _ Hl). destruct b; inv Hd.\n    simpl in *. \n\n    edestruct update_live_fun_false; try eassumption.\n    \n    destructAll.\n    \n    eapply IHB in Hl. inv Hl.\n    \n    split. reflexivity.\n\n    { intro; intros. inv H.\n      - inv H3. eapply live_expr_sound. inv Hnf. eassumption.\n        unfold get_fun_vars in *. eapply H0. eassumption.\n      - eapply H1. eassumption. eassumption. } \n\n    inv Hnf. eassumption.\n\n  - inv Hl. split; eauto.\n    intro; intros. inv H.\nQed. \n\n\n(* Proof that a fixpoint is reached in n steps *)\n\nFixpoint bitsize (bs : list bool) :=\n  match bs with\n  | [] => 0\n  | b :: bs => if b then 1 + bitsize bs else bitsize bs\n  end.\n  \nDefinition map_size (L : live_fun) :=\n  fold_left (fun s '(_, bs) => s + bitsize bs) (M.elements L) 0.\n\nDefinition max_map_size (L : live_fun) :=\n  fold_left (fun s '(_, bs) => s + length bs) (M.elements L) 0.\n\n\nLemma update_bs_bitsize_leq S xs bs bs' diff :\n  update_bs S xs bs = (bs', diff) ->\n  bitsize bs <= bitsize bs'.\nProof.\n  revert S bs bs' diff. induction xs; simpl; intros S bs bs' diff Hupd.\n  - inv Hupd. reflexivity.\n  - destruct bs.\n    + inv Hupd. reflexivity.\n    + destruct (update_bs S xs bs) as [bs'' d] eqn:Hupd'.\n      destruct b.\n      * inv Hupd. simpl. eapply IHxs in Hupd'. lia.\n      * inv Hupd. eapply IHxs in Hupd'. simpl. \n        destruct (PS.mem a S); lia.\nQed.       \n\nLemma update_bs_bitsize S xs bs bs' :\n  update_bs S xs bs = (bs', true) ->\n  bitsize bs < bitsize bs'.\nProof.\n  revert S bs bs'. induction xs; simpl; intros S bs bs' Hupd.\n  - inv Hupd.\n  - destruct bs.\n    + inv Hupd.\n    + destruct (update_bs S xs bs) as [bs'' d] eqn:Hupd'.\n      destruct b.\n      * inv Hupd. simpl. eapply IHxs in Hupd'. lia.\n      * inv Hupd. simpl. \n        destruct (PS.mem a S).\n        -- eapply update_bs_bitsize_leq in Hupd'. lia.\n        -- simpl in H1. subst. eapply IHxs. eassumption.\nQed.\n\nLemma update_bs_length S xs bs bs' diff :\n  update_bs S xs bs = (bs', diff) ->\n  length bs = length bs'.\nProof.\n  revert S bs bs' diff. induction xs; simpl; intros S bs bs' diff Hupd.\n  - inv Hupd. reflexivity.\n  - destruct bs.\n    + inv Hupd. reflexivity.\n    + destruct (update_bs S xs bs) as [bs'' d] eqn:Hupd'.\n      destruct b.\n      * inv Hupd. simpl. eapply IHxs in Hupd'. lia.\n      * inv Hupd. simpl.\n        eapply IHxs in Hupd'. congruence.\nQed.\n\n\nLemma set_fun_vars_map_size L f l bs :\n  L ! f = Some l ->\n  length l = length bs ->\n  map_size L + bitsize bs =  map_size (set_fun_vars L f bs) + bitsize l.\nProof.\n  intros Heq Hlen. unfold set_fun_vars.\n  \n  unfold map_size.\n  edestruct elements_set_some. eassumption.\n  destructAll.\n  rewrite H, H0.\n  rewrite !fold_left_app. simpl.\n  rewrite <- (plus_O_n (fold_left _ _ _ + bitsize l)).\n  rewrite <- (plus_O_n (fold_left _ x 0 + bitsize bs)).\n  erewrite !List_util.fold_left_acc_plus. simpl. lia.\n\n  intros ? ? [? ? ]. lia.\n  intros ? ? [? ? ]. lia.\nQed.\n\n  \nLemma update_live_fun_size_leq L L' b f xs S :\n  update_live_fun L f xs S = (L', b) ->\n  map_size L <= map_size L'.\nProof.\n  intros Hl.\n  unfold update_live_fun in Hl.\n  destruct (get_fun_vars L f) eqn:Hf.\n  unfold get_fun_vars in *.\n  destruct (update_bs S xs l) as [bs diff] eqn:Hupd.\n  destruct diff.\n  \n  - inv Hl. assert (Hupd' := Hupd). eapply update_bs_bitsize in Hupd.\n    eapply set_fun_vars_map_size with (bs := bs) in Hf. lia.\n    eapply update_bs_length. eassumption.\n  - inv Hl. reflexivity.\n  - inv Hl. reflexivity. \nQed.\n\nLemma update_live_fun_size L L' f xs S :\n  update_live_fun L f xs S = (L', true) ->\n  map_size L < map_size L'.\nProof.\n  intros Hl.\n  unfold update_live_fun in Hl.\n  destruct (get_fun_vars L f) eqn:Hf; try congruence.\n  unfold get_fun_vars in *.\n  destruct (update_bs S xs l) as [bs diff] eqn:Hupd.\n  destruct diff.\n  \n  - inv Hl. assert (Hupd' := Hupd). eapply update_bs_bitsize in Hupd.\n    eapply set_fun_vars_map_size with (bs := bs) in Hf. lia.\n    eapply update_bs_length. eassumption.\n  - inv Hl.\nQed.\n\n\nLemma live_size_leq L L' d d' B :\n  live B L d = (L', d') ->\n  map_size L <= map_size L'.\nProof.\n  revert L L' d d'; induction B; simpl; intros L L' d d' Hl; subst.\n  - destruct (update_live_fun L v l (live_expr L e PS.empty)) as [L'' b] eqn:Heq.\n    destruct b; simpl in *.\n    + eapply le_trans.\n      eapply update_live_fun_size_leq. \n      eassumption.\n      eapply IHB. eassumption.\n    + edestruct update_live_fun_false. \n      eassumption. destructAll. \n      eapply IHB. eassumption.\n  - inv Hl. reflexivity.\nQed. \n\n\nLemma live_size L L' B :\n  live B L false = (L', true) ->\n  map_size L < map_size L'.\nProof.\n  assert (Heq : false = false) by reflexivity. revert Heq. generalize false at 1 3. \n  revert L L'; induction B; simpl; intros L L' d Heq Hl; subst.\n  - destruct (update_live_fun L v l (live_expr L e PS.empty)) as [L'' b] eqn:Heq.\n\n    destruct b; simpl in *.\n    + eapply lt_le_trans.\n      eapply update_live_fun_size. eassumption.\n      eapply live_size_leq. \n      eassumption.\n    + edestruct update_live_fun_false. \n      eassumption. destructAll. \n      eapply IHB. reflexivity. eassumption.\n  - inv Hl. \nQed. \n\n\nLemma find_live_helper_size B L n L' :\n  no_fun_defs B -> \n  find_live_helper B L n = Ret L' ->\n  (* either a fixpoint is reached *)\n  live_map_sound B L' \\/ \n  (* or the distance between L and L' is at least n *)\n  map_size L + n <= map_size L'.\nProof.\n  revert B L L'. induction n; intros.\n  - inv H0. right. lia.\n  - simpl in H0.\n    destruct (live B L false) as [L1 diff]  eqn:Hlive.\n    \n    destruct diff.\n\n    + eapply IHn in H0; eauto. inv H0. now left.\n      right.\n\n      eapply live_size in Hlive. lia.\n\n    + inv H0. eapply live_correct in Hlive; eauto.\n      destructAll. now left.\nQed. \n\n\n(* Lemmas about max_size *)\n\nLemma bitsize_leq bs :\n  bitsize bs <= Datatypes.length bs.\nProof.\n  induction bs; simpl; eauto. destruct a; lia.\nQed.\n  \nLemma max_map_size_leq L :\n  map_size L <= max_map_size L.\nProof.\n  unfold map_size, max_map_size.\n  eapply List_util.fold_left_monotonic; eauto.\n  intros. destruct x2. simpl.\n  assert (Hleq := bitsize_leq l). \n  lia.\nQed.\n\n\n      \nLemma max_map_size_empty :\n  max_map_size (M.empty (list bool)) = 0.\nProof. reflexivity. Qed.\n\n(* Proofs that max_max_size is preserved during liveness analysis *)\n\nLemma set_fun_vars_max_size L f l bs :\n  L ! f = Some l ->\n  length l = length bs ->\n  max_map_size (set_fun_vars L f bs) = max_map_size L.\nProof.\n  intros Heq Hlen. unfold set_fun_vars.\n\n  unfold map_size, max_map_size.\n  edestruct elements_set_some. eassumption.\n  destructAll.\n  rewrite H, H0.\n  rewrite !fold_left_app. simpl.\n  \n  rewrite <- (plus_O_n (fold_left _ _ _ + length bs)).\n  rewrite <- (plus_O_n (fold_left _ _ _  + length l)).\n  erewrite !List_util.fold_left_acc_plus. simpl. congruence.\n\n  intros ? ? [? ? ]. lia.\n  intros ? ? [? ? ]. lia.\nQed.\n\n\nLemma update_live_fun_max_size L L' b f xs S :\n  update_live_fun L f xs S = (L', b) ->\n  max_map_size L' = max_map_size L.\nProof.\n  intros Hl.\n  unfold update_live_fun in Hl.\n  destruct (get_fun_vars L f) eqn:Hf; try congruence.\n  unfold get_fun_vars in *.\n  destruct (update_bs S xs l) as [bs diff] eqn:Hupd.\n  destruct diff.\n  \n  - inv Hl.  eapply update_bs_length in Hupd.\n    assert (Hupd' := Hupd).\n    eapply set_fun_vars_max_size. eassumption. eassumption.\n\n  - inv Hl. reflexivity.\nQed.\n\n\nLemma live_max_size L L' d d' B :\n  live B L d = (L', d') ->\n  max_map_size L' = max_map_size L.\nProof.\n  revert L L' d d'; induction B; simpl; intros L L' d d' Hl; subst.\n  - destruct (update_live_fun L v l (live_expr L e PS.empty)) as [L'' b] eqn:Heq.\n    \n    eapply IHB in Hl. eapply update_live_fun_max_size in Heq. congruence.\n  - inv Hl. reflexivity. \nQed. \n\n\nLemma find_live_helper_max_size B L n L' :\n  no_fun_defs B -> \n  find_live_helper B L n = Ret L' ->\n  max_map_size L' = max_map_size L.\nProof.\n  revert B L L'. induction n; intros.\n  - inv H0. reflexivity.\n  - simpl in H0.\n    destruct (live B L false) as [L1 diff]  eqn:Hlive.\n    \n    destruct diff.\n\n    + eapply IHn in H0; eauto. eapply live_max_size in Hlive.\n      congruence.\n\n    + inv H0.\n      eapply live_max_size in Hlive. lia.\nQed. \n\nLemma set_fun_vars_max_size_None L f bs :\n  L ! f = None ->\n  max_map_size (set_fun_vars L f bs) = max_map_size L + length bs.\nProof.\n  intros Heq. unfold set_fun_vars.\n\n  unfold map_size, max_map_size.\n  edestruct elements_set_none. eassumption.\n  destructAll.\n  rewrite H, H0.\n  rewrite !fold_left_app. simpl.\n  \n  rewrite <- (plus_O_n (fold_left _ _ _ + length bs)).\n  rewrite <- (plus_O_n (fold_left _ x 0)).\n  erewrite !List_util.fold_left_acc_plus. simpl. lia.\n  intros ? ? [? ? ]. lia.\n  intros ? ? [? ? ]. lia.\nQed.\n\nLemma get_bool_false_length {A} (l : list A) :\n  length (get_bool_false l) = length l. \nProof.\n  induction l; simpl; eauto.\nQed.\n\nLemma get_bool_true_length {A} (l : list A) :\n  length (get_bool_true l) = length l. \nProof.\n  induction l; simpl; eauto.\nQed.\n\nLemma num_vars_acc B m n :\n  num_vars B (n + m) = num_vars B n + m.\nProof.\n  revert m n. induction B; intros; simpl; eauto.\n\n  rewrite <- plus_assoc. rewrite (plus_comm m). rewrite plus_assoc.\n  rewrite IHB. lia.\nQed. \n  \n\nLemma init_live_fun_aux_max_size L B L' m :\n  Disjoint _ (Dom_map L) (name_in_fundefs B) ->\n  unique_functions B ->\n  init_live_fun_aux L B = L' ->  \n  max_map_size L' + m = max_map_size L + num_vars B m.\nProof.\n  revert L L' m; induction B; simpl; intros L L' m Hdis Hun Hinit.\n  - eapply IHB in Hinit. \n    + rewrite Hinit. rewrite set_fun_vars_max_size_None.\n      rewrite get_bool_false_length, num_vars_acc. lia.\n      \n      destruct (L ! v) eqn:Heq; eauto. exfalso. eapply Hdis.\n      constructor; eauto. eexists; eauto.\n\n    + unfold set_fun_vars.\n      rewrite Dom_map_set. inv Hun. sets. \n      \n    + inv Hun. sets.\n\n  - congruence.\nQed.\n\n\nLemma init_live_fun_max_size L B :\n  unique_functions B ->\n  init_live_fun B = L ->  \n  max_map_size L = num_vars B 0.\nProof.\n  intros.\n  eapply init_live_fun_aux_max_size in H0; eauto.\n  rewrite max_map_size_empty in H0. simpl in H0. rewrite <- H0. lia.\n\n  rewrite Dom_map_empty. sets.\nQed.\n\nLemma remove_escaping_max_size L x :\n  max_map_size (remove_escaping L x) <= max_map_size L.\nProof.\n  unfold remove_escaping. destruct (get_fun_vars L x) eqn:Hget; subst; eauto.\n\n  unfold max_map_size.\n  edestruct cps.M.elements_remove. eassumption. \n  destructAll. rewrite H, H0.\n  rewrite !fold_left_app. simpl.\n  \n  rewrite <- (plus_O_n (fold_left _ x0 0)).\n  erewrite !List_util.fold_left_acc_plus. simpl. lia.\n  intros ? ? [? ? ]. lia.\n  intros ? ? [? ? ]. lia.\n  intros ? ? [? ? ]. lia.  \nQed.\n\n\nLemma remove_escapings_max_size L x :\n  max_map_size (remove_escapings L x) <= max_map_size L.\nProof.\n  revert L; induction x; simpl; intros L; subst; eauto.\n  specialize (IHx (remove_escaping L a)).\n  assert (Hleq := remove_escaping_max_size L a). lia.\nQed.\n\n\nLemma escaping_fun_fundefs_max_size_mut :  \n  (forall e L,\n      max_map_size (escaping_fun_exp e L) <= max_map_size L) /\\\n  (forall B L,\n      max_map_size (escaping_fun_fundefs B L) <= max_map_size L). \nProof.\n  exp_defs_induction IHe IHl IHB; simpl; intros; subst; eauto;\n    try (now eapply le_trans; [ eapply IHe | eapply remove_escapings_max_size ]);\n    try (now eapply le_trans; [ eapply IHe | eapply remove_escaping_max_size ]). \n  - simpl in IHl.\n    eapply le_trans. eapply IHl. eapply IHe.\n  - simpl in *.\n    eapply le_trans. eapply IHe. eapply IHB.\n  - eapply remove_escapings_max_size.\n  - eapply remove_escaping_max_size.\n  - simpl in *.\n    eapply le_trans. eapply IHB. eapply IHe.\nQed. \n\nLemma escaping_fun_exp_max_size :  \n  (forall e L,\n      max_map_size (escaping_fun_exp e L) <= max_map_size L).\nProof. eapply escaping_fun_fundefs_max_size_mut. Qed.\n\nLemma escaping_fun_fundefs_max_size :  \n  (forall B L,\n      max_map_size (escaping_fun_fundefs B L) <= max_map_size L).\nProof. eapply escaping_fun_fundefs_max_size_mut. Qed.\n\n\nLemma find_live_sound (B : fundefs) (e : exp) L :\n  no_fun_defs B -> (* no nested fundefs *)\n  unique_functions B -> (* unique bindings *)\n  find_live (Efun B e) = Ret L ->\n  live_map_sound B L.\nProof.\n  intros Hnf Hun Hl. unfold find_live in *.\n  assert (Hl' := Hl).\n  \n  eapply find_live_helper_size in Hl; eauto.\n  inv Hl; eauto.\n  eapply find_live_helper_max_size in Hl'; eauto.\n\n  assert (Hleq1 := escaping_fun_fundefs_max_size B (init_live_fun B)).\n  assert (Hleq2 := escaping_fun_exp_max_size e (escaping_fun_fundefs B (init_live_fun B))).\n  \n  erewrite init_live_fun_max_size  with (L := init_live_fun _) in *; eauto.\n  \n  assert (Hleq := max_map_size_leq L). lia.\nQed.\n  \n  \n(* Domain of live_fun is preserved *)\n\n\nLemma update_live_fun_dom L L' f xs S d :\n  update_live_fun L f xs S = (L', d) ->\n  Dom_map L <--> Dom_map L'.\nProof.\n  intros Hl.\n  unfold update_live_fun in Hl.\n  destruct (get_fun_vars L f) eqn:Hf; try congruence.\n  unfold get_fun_vars in *.\n  destruct (update_bs S xs l) as [bs diff] eqn:Hupd.\n  destruct diff.\n  \n  - inv Hl. unfold set_fun_vars.\n    rewrite Dom_map_set. rewrite (Union_Same_set [set f] (Dom_map L)). reflexivity.\n    eapply Singleton_Included. eexists; eauto.\n    \n  - inv Hl. reflexivity.\n  - inv Hl. reflexivity.\nQed.\n\n\nLemma live_dom L L' d d' B :\n  live B L d = (L', d') ->\n  Dom_map L <--> Dom_map L'.\nProof.\n  revert L L' d d'; induction B; simpl; intros L L' d d' Hl; subst.\n  - destruct (update_live_fun L v l (live_expr L e PS.empty)) as [L'' b] eqn:Heq.\n    destruct b; simpl in *.\n    + eapply IHB in Hl. rewrite <- Hl.\n      eapply update_live_fun_dom. eassumption.\n    + edestruct update_live_fun_false. \n      eassumption. destructAll. \n      eapply IHB. eassumption.\n  - inv Hl. reflexivity.\nQed. \n\nLemma find_live_helper_dom B L n L' :\n  find_live_helper B L n = Ret L' ->\n  Dom_map L <--> Dom_map L'.\nProof.\n  revert B L L'. induction n; intros.\n  - inv H. reflexivity.\n  - simpl in H.\n    destruct (live B L false) as [L1 diff] eqn:Hlive.\n    \n    destruct diff.\n\n    + eapply live_dom in Hlive.\n      rewrite Hlive. eauto.\n\n    + inv H.\n      eapply live_dom. eassumption.\nQed. \n  \n\nLemma init_live_fun_aux_dom L B L' :\n  init_live_fun_aux L B = L' ->  \n  Dom_map L' \\subset name_in_fundefs B :|: Dom_map L.\nProof.\n  revert L L'; induction B; simpl; intros L L' Hinit.\n  - rewrite IHB; eauto.\n    unfold set_fun_vars.\n    rewrite Dom_map_set. sets.\n  - subst. sets.\nQed.\n\n\nInductive Known_exp (S : Ensemble var) : exp -> Prop :=\n| Known_Constr : \n    forall (x : var) (ys : list var) (ct : ctor_tag) (e : exp), \n      Disjoint _ (FromList ys) S -> \n      Known_exp S e ->\n      Known_exp S (Econstr x ct ys e)\n| Known_Prim_val : \n  forall (x : var) p (e : exp), \n    Known_exp S e ->\n    Known_exp S (Eprim_val x p e)\n| Known_Prim : \n  forall (x : var) (g : prim) (ys : list var) (e : exp), \n    Disjoint _ (FromList ys) S -> \n    Known_exp S e ->\n    Known_exp S (Eprim x g ys e)\n| Known_Proj : \n    forall (x : var) (ct : ctor_tag) (n : N) (y : var) (e : exp), \n      ~ y \\in S ->\n     Known_exp S e ->\n     Known_exp S (Eproj x ct n y e)\n| Known_Case: \n    forall (x : var) (ce : list (ctor_tag * exp)),\n      Forall (fun p => Known_exp S (snd p)) ce -> \n      Known_exp S (Ecase x ce)\n| Known_Fun:\n    forall B e,\n      Known_fundefs S B ->\n      Known_exp S e ->\n      Known_exp S (Efun B e)      \n| Known_Halt : \n    forall (x : var),\n      ~ x \\in S ->\n      Known_exp S (Ehalt x)\n| Known_App :\n    forall (f : var) (ys : list var) (ft : fun_tag),\n      Disjoint _ (FromList ys) S -> \n      Known_exp S (Eapp f ft ys)\n| Known_LetApp :\n    forall (x f : var) (ys : list var) (ft : fun_tag) (e : exp),\n      Disjoint _ (FromList ys) S -> \n      Known_exp S e ->\n      Known_exp S (Eletapp x f ft ys e)\nwith Known_fundefs (S : Ensemble var) : fundefs -> Prop := \n| Known_Fcons :\n    forall f ft xs e B,\n      Known_exp S e ->\n      Known_fundefs S B ->\n      Known_fundefs S (Fcons f ft xs e B)      \n| Known_Fnil : \n    Known_fundefs S Fnil. \n\n\n(* Dom subset *)\n\nLemma remove_escaping_subset L x :\n  Dom_map (remove_escaping L x) \\subset Dom_map L.\nProof.\n  unfold remove_escaping. destruct (get_fun_vars L x) eqn:Hget; subst; sets.\n  rewrite Dom_map_remove. sets.\nQed.\n\nLemma remove_escapings_subset L x :\n  Dom_map (remove_escapings L x) \\subset Dom_map L.\nProof.\n  revert L; induction x; simpl; intros L; subst; sets.\n  eapply Included_trans. eapply IHx. eapply remove_escaping_subset.\nQed.\n\n\nLemma escaping_fun_subset_mut :  \n  (forall e L,\n      (Dom_map  (escaping_fun_exp e L)) \\subset Dom_map L) /\\\n  (forall B L,\n      (Dom_map (escaping_fun_fundefs B L)) \\subset Dom_map L). \nProof.\n  exp_defs_induction IHe IHl IHB; simpl; intros; subst; eauto; sets;\n  try now (eapply Included_trans; [ eapply IHe | ]; \n           eauto using remove_escaping_subset, remove_escapings_subset).\n  - simpl in *. eapply Included_trans. eapply IHl. eapply IHe.\n  - eapply remove_escapings_subset.\n  - eapply remove_escaping_subset.\n  - eapply Included_trans. eapply IHB. eapply IHe.\nQed. \n\nLemma escaping_fun_exp_subset : \n  (forall e L,\n      (Dom_map  (escaping_fun_exp e L)) \\subset Dom_map L).\nProof. eapply escaping_fun_subset_mut. Qed.\n\n\nLemma escaping_fun_fundefs_subset : \n  (forall e L,\n      (Dom_map (escaping_fun_fundefs e L)) \\subset Dom_map L).\nProof. eapply escaping_fun_subset_mut. Qed.\n\n  \n\nLemma remove_escaping_preserves_disjoint S L x :\n  Disjoint _ S (Dom_map L) -> \n  Disjoint _ S (Dom_map (remove_escaping L x)).\nProof.\n  intros Hc. eapply Disjoint_Included_r. eapply remove_escaping_subset. sets.\nQed.\n  \nLemma remove_escapings_preserves_disjoint S L x :\n  Disjoint _ S (Dom_map L) -> \n  Disjoint _ S (Dom_map (remove_escapings L x)).\nProof.\n  intros Hc. eapply Disjoint_Included_r. eapply remove_escapings_subset. sets.\nQed.\n\nLemma escaping_fun_exp_preserves_disjoint :  \n  forall e S L,\n    Disjoint _ S (Dom_map L) -> \n    Disjoint _ S (Dom_map  (escaping_fun_exp e L)).\nProof.\n  intros. eapply Disjoint_Included_r. eapply escaping_fun_exp_subset. sets.\nQed. \n\nLemma escaping_fun_fundefs_preserves_disjoint :  \n  forall B S L,\n    Disjoint _ S (Dom_map L) -> \n    Disjoint _ S (Dom_map  (escaping_fun_fundefs B L)).\nProof.\n  intros. eapply Disjoint_Included_r. eapply escaping_fun_fundefs_subset. sets.\nQed. \n\n\nLemma Known_exp_monotonic_mut :  \n  (forall e S1 S2,\n      Known_exp S1 e ->\n      S2 \\subset S1 ->\n      Known_exp S2 e) /\\\n  (forall B S1 S2,\n      Known_fundefs S1 B ->\n      S2 \\subset S1 ->\n      Known_fundefs S2 B).\nProof.\n  exp_defs_induction IHe IHl IHB; simpl; intros; subst; inv H; eauto; try (now econstructor; eauto; sets).\n  - inv H2. econstructor. econstructor.\n    now eauto.\n    assert (Hk : Known_exp S1 (Ecase v l)) by (econstructor; eassumption).\n    eapply IHl in Hk; eauto. inv Hk. eassumption.\nQed.\n\n\nCorollary Known_exp_monotonic : \n  forall e S1 S2,\n    Known_exp S1 e ->\n    S2 \\subset S1 ->\n    Known_exp S2 e.\nProof. eapply Known_exp_monotonic_mut. Qed.\n\nCorollary Known_fundefs_monotonic : \n  forall B S1 S2,\n    Known_fundefs S1 B ->\n    S2 \\subset S1 ->\n    Known_fundefs S2 B.\nProof. eapply Known_exp_monotonic_mut. Qed.\n\n\nLemma remove_escaping_disjoint L x :\n  ~ x \\in (Dom_map (remove_escaping L x)).\nProof.\n  unfold remove_escaping. destruct (get_fun_vars L x) eqn:Hget; subst; eauto.\n  rewrite Dom_map_remove. intros Hc. inv Hc. now eauto.\n  intros Hc. inv Hc. unfold get_fun_vars in *. congruence.\nQed.\n\nLemma remove_escapings_disjoint L x :\n  Disjoint _ (FromList x) (Dom_map (remove_escapings L x)).\nProof.\n  revert L; induction x; simpl; intros L; subst; eauto.\n  - normalize_sets. now sets.\n  - normalize_sets. assert (H := remove_escaping_disjoint L a).\n    specialize (IHx (remove_escaping L a)).\n    eapply Union_Disjoint_l; eauto.\n    eapply remove_escapings_preserves_disjoint. eapply Disjoint_Singleton_l. eassumption.\n Qed.\n\nLemma escaping_fun_fundefs_sound :  \n  (forall e L,\n      Known_exp (Dom_map (escaping_fun_exp e L)) e) /\\\n  (forall B L,\n      Known_fundefs (Dom_map (escaping_fun_fundefs B L)) B). \nProof.\n  exp_defs_induction IHe IHl IHB; simpl; intros; subst; eauto;\n    try (now econstructor; eauto; eapply escaping_fun_exp_preserves_disjoint; eapply remove_escapings_disjoint).\n  - econstructor. econstructor.\n    + simpl.\n      eapply Known_exp_monotonic. eapply IHe.\n      assert (Hsub := escaping_fun_exp_subset (Ecase v l) (escaping_fun_exp e L)). eassumption.\n    + simpl in *. \n      specialize (IHl (escaping_fun_exp e L)). inv IHl. eassumption.\n  - econstructor; eauto.\n    assert (Hdis : Disjoint _ [set v0] (Dom_map (escaping_fun_exp e (remove_escaping L v0)))).\n    { eapply escaping_fun_exp_preserves_disjoint. eapply Disjoint_Singleton_l.\n      eapply remove_escaping_disjoint. }\n    intros Hc. eapply Hdis; eauto.\n  - econstructor; eauto.\n    eapply Known_fundefs_monotonic. eapply IHB.\n    eapply escaping_fun_exp_subset.\n  - econstructor. eapply remove_escapings_disjoint.\n  - econstructor. eapply remove_escaping_disjoint.\n  - econstructor; eauto.\n    eapply Known_exp_monotonic. eapply IHe.\n    eapply escaping_fun_fundefs_subset.\nQed. \n\nLemma find_live_fun_map_dom B e L :\n  find_live (Efun B e) = Ret L ->\n  Dom_map L \\subset name_in_fundefs B /\\\n  Known_exp (Dom_map L) (Efun B e). \nProof.\n  intros Hf. unfold find_live in *.\n  eapply find_live_helper_dom in Hf.\n  rewrite <- !Hf at 1. split.\n\n  - eapply Included_trans. eapply escaping_fun_exp_subset.\n    eapply Included_trans. eapply escaping_fun_fundefs_subset.\n    eapply Included_trans. eapply init_live_fun_aux_dom. reflexivity.\n    rewrite Dom_map_empty. sets.\n\n  - eapply Known_exp_monotonic; [| eapply Hf ].\n    destruct escaping_fun_fundefs_sound.\n\n    econstructor.\n\n    + eapply Known_fundefs_monotonic. eapply H0.\n      eapply Included_trans. eapply escaping_fun_exp_subset. reflexivity.\n\n    + eapply H.\nQed.\n  \n(* Top-level theorem for liveness analysis *)\nCorollary find_live_sound_top (B : fundefs) (e : exp) L :\n  no_fun_defs B -> (* no nested fundefs *)\n  unique_functions B -> (* unique bindings *)\n  find_live (Efun B e) = Ret L ->\n  live_map_sound B L /\\\n  Dom_map L \\subset name_in_fundefs B /\\\n  Known_exp (Dom_map L) (Efun B e).\nProof.\n  intros Hnf Hun Hl.\n  edestruct find_live_fun_map_dom. eassumption.\n  split; eauto. eapply find_live_sound; eassumption.\nQed.\n\n\n(* is_hoisted is correct *)\n\nLemma is_hoisted_exp_correct e :\n  is_hoisted_exp e = true ->\n  no_fun e.\nProof.\n  induction e using exp_ind'; simpl; intros; eauto. \n  - simpl in *.\n    eapply andb_prop in H. destructAll.\n    econstructor; eauto.\n  - congruence.\nQed. \n\n\nLemma is_hoisted_fundefs_correct B :\n  is_hoisted_fundefs B = true ->\n  no_fun_defs B.\nProof.\n  induction B; simpl; intros; eauto.\n\n  eapply andb_prop in H. destructAll.  \n  econstructor; eauto.\n  eapply is_hoisted_exp_correct; eauto.\nQed. \n\n\nLemma is_hoisted_correct B e :\n  is_hoisted (Efun B e) = true ->\n  no_fun_defs B /\\ no_fun e.\nProof.\n  intros H. simpl in *.  eapply andb_prop in H.\n  destructAll. \n  split; eauto using is_hoisted_exp_correct, is_hoisted_fundefs_correct.\nQed.\n", "meta": {"author": "CertiCoq", "repo": "certicoq", "sha": "2405e1012e9c0a58e49002d9779bb65527d6c323", "save_path": "github-repos/coq/CertiCoq-certicoq", "path": "github-repos/coq/CertiCoq-certicoq/certicoq-2405e1012e9c0a58e49002d9779bb65527d6c323/theories/LambdaANF/dead_param_elim_util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24276020557110267}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import ssreflect.\nFrom MetaCoq.Template Require Import config utils.\nFrom MetaCoq.PCUIC Require Import PCUICTyping PCUICEquality PCUICAst PCUICAstUtils\n  PCUICWeakeningConv PCUICWeakeningTyp PCUICSubstitution PCUICGeneration PCUICArities\n  PCUICWcbvEval PCUICSR PCUICInversion\n  PCUICUnivSubstitutionConv PCUICUnivSubstitutionTyp\n  PCUICElimination PCUICSigmaCalculus PCUICContextConversion\n  PCUICUnivSubst PCUICWeakeningEnvConv PCUICWeakeningEnvTyp\n  PCUICCumulativity PCUICConfluence\n  PCUICInduction PCUICLiftSubst PCUICContexts PCUICSpine\n  PCUICConversion PCUICValidity PCUICInductives PCUICConversion\n  PCUICInductiveInversion PCUICNormal PCUICSafeLemmata\n  PCUICParallelReductionConfluence\n  PCUICWcbvEval PCUICClosed PCUICClosedTyp\n  PCUICReduction PCUICCSubst PCUICOnFreeVars PCUICWellScopedCumulativity PCUICCanonicity PCUICWcbvEval.\n\nFrom Equations Require Import Equations.\n\n\nLemma eval_tCase {cf : checker_flags} {Σ : global_env_ext}  ci p discr brs res T :\n  wf Σ ->\n  Σ ;;; [] |- tCase ci p discr brs : T ->\n  eval Σ (tCase ci p discr brs) res ->\n  ∑ c u args, red Σ [] (tCase ci p discr brs) (tCase ci p ((mkApps (tConstruct ci.(ci_ind) c u) args)) brs).\nProof.\n  intros wf wt H. depind H; try now (cbn in *; congruence).\n  - eapply inversion_Case in wt as (? & ? & ? & ? & cinv & ?); eauto.\n    eexists _, _, _. eapply red_case_c. eapply wcbeval_red. 2: eauto. eapply cinv.\n  - eapply inversion_Case in wt as wt'; eauto. destruct wt' as (? & ? & ? & ? & cinv & ?).\n    assert (Hred1 : Σ;;; [] |- tCase ip p discr brs ⇝* tCase ip p (mkApps fn args) brs). {\n      etransitivity. { eapply red_case_c. eapply wcbeval_red. 2: eauto. eapply cinv. }\n      econstructor. econstructor.\n      rewrite closed_unfold_cofix_cunfold_eq. eauto.\n      enough (closed (mkApps (tCoFix mfix idx) args)) as Hcl by (rewrite closedn_mkApps in Hcl; solve_all).\n      eapply eval_closed. eauto.\n      2: eauto. eapply @subject_closed with (Γ := []); eauto. eapply cinv. tea.\n    }\n    edestruct IHeval2 as (c & u & args0 & IH); eauto using subject_reduction.\n    exists c, u, args0. etransitivity; eauto.\nQed.\n\nLocal Existing Instance config.extraction_checker_flags.\n\nInductive typing_spine_pred {cf : checker_flags} Σ (Γ : context) (P : forall t T (H : Σ ;;; Γ |- t : T), Type) : term -> list term -> term -> Type :=\n| type_spine_pred_nil ty ty' (* s s' *) :\n    isType Σ Γ ty ->\n    isType Σ Γ ty' ->\n    (* forall H : Σ ;;; Γ |- ty : tSort s,\n    P ty (tSort s) H ->\n    forall H' : Σ ;;; Γ |- ty' : tSort s',\n    P ty' (tSort s') H' ->\n     *) Σ ;;; Γ ⊢ ty ≤ ty' ->\n    typing_spine_pred Σ Γ P ty [] ty'\n\n| type_spine_pred_cons ty hd tl na A B B' s' :\n    isType Σ Γ ty ->\n    forall H' : Σ ;;; Γ |- tProd na A B : tSort s',\n    P (tProd na A B) (tSort s') H' ->\n    Σ ;;; Γ ⊢ ty ≤ tProd na A B ->\n    forall H : Σ ;;; Γ |- hd : A,\n    P hd A H ->\n    typing_spine_pred Σ Γ P (subst10 hd B) tl B' ->\n    typing_spine_pred Σ Γ P ty (hd :: tl) B'.\n\nSection WfEnv.\n  Context {cf : checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ}.\n\n  Lemma typing_spine_pred_strengthen {Γ P T args U} :\n    typing_spine_pred Σ Γ P T args U ->\n    isType Σ Γ T ->\n    forall T',\n    isType Σ Γ T' ->\n    Σ ;;; Γ ⊢ T' ≤ T ->\n    typing_spine_pred Σ Γ P T' args U.\n  Proof using wfΣ.\n    induction 1 in |- *; intros T' isTy redT.\n    - constructor; eauto. transitivity ty; auto.\n    - specialize IHX with (T' := (B {0 := hd})).\n      assert (isType Σ Γ (B {0 := hd})) as HH. {\n        clear p.\n        eapply inversion_Prod in H' as (? & ? & ? & ? & ?); tea.\n        eapply isType_subst. econstructor. econstructor. rewrite subst_empty; eauto.\n        econstructor; cbn; eauto.\n      }\n      do 3 forward IHX by pcuic.\n      intros Hsub.\n      eapply type_spine_pred_cons; eauto.\n      etransitivity; eauto.\n  Qed.\n\nEnd WfEnv.\n\nLemma inversion_mkApps {cf : checker_flags} {Σ} {wfΣ :  wf Σ.1} {Γ f u T} s :\n  forall (H : Σ ;;; Γ |- mkApps f u : T) (HT : Σ ;;; Γ |- T : tSort s),\n  { A : term & { Hf : Σ ;;; Γ |- f : A & {s' & {HA : Σ ;;; Γ |- A : tSort s' &\n   typing_size Hf <= typing_size H ×\n   typing_size HA <= max (typing_size H) (typing_size HT) ×\n  typing_spine_pred Σ Γ (fun x ty Hx => typing_size Hx <= typing_size H) A u T}}}}.\nProof.\n  revert f T.\n  induction u; intros f T. simpl. intros.\n  { exists T, H, s, HT. intuition pcuic.\n    econstructor. eexists; eauto. eexists; eauto. eapply isType_ws_cumul_pb_refl. eexists; eauto. }\n  intros Hf Ht. simpl in Hf.\n  specialize (IHu (tApp f a) T).\n  epose proof (IHu Hf) as (T' & H' & s' & H1 & H2 & H3 & H4); tea.\n  edestruct @inversion_App_size with (H := H') as (na' & A' & B' & s_ & Hf' & Ha & HA & Hs1 & Hs2 & Hs3 & HA'''); tea.\n  exists (tProd na' A' B'). exists Hf'. exists s_. exists HA.\n  split. rewrite <- H2. lia.\n  split. rewrite <- Nat.le_max_l, <- H2. lia.\n\n  unshelve econstructor.\n  5: eauto. 1: eauto.\n  3:eapply isType_ws_cumul_pb_refl; eexists; eauto.\n  1: eexists; eauto.\n  1, 2: rewrite <- H2; lia.\n  eapply typing_spine_pred_strengthen; tea.\n  eexists; eauto. clear Hs3.\n  eapply inversion_Prod in HA as (? & ? & ? & ? & ?); tea.\n  eapply isType_subst. econstructor. econstructor. rewrite subst_empty; eauto.\n  econstructor;  cbn; eauto.\n  Unshelve. eauto.\nQed.\n\nLemma typing_ind_env_app_size `{cf : checker_flags} :\nforall (P : global_env_ext -> context -> term -> term -> Type)\n       (Pdecl := fun Σ Γ wfΓ t T tyT => P Σ Γ t T)\n       (PΓ : global_env_ext -> context -> Type),\n\n  (forall Σ (wfΣ : wf Σ.1)  (Γ : context) (wfΓ : wf_local Σ Γ),\n       All_local_env_over typing Pdecl Σ Γ wfΓ -> PΓ Σ Γ) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (n : nat) decl,\n      nth_error Γ n = Some decl ->\n      PΓ Σ Γ ->\n      P Σ Γ (tRel n) (lift0 (S n) decl.(decl_type))) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (u : Universe.t),\n      PΓ Σ Γ ->\n      wf_universe Σ u ->\n      P Σ Γ (tSort u) (tSort (Universe.super u))) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (n : aname) (t b : term) (s1 s2 : Universe.t),\n      PΓ Σ Γ ->\n      Σ ;;; Γ |- t : tSort s1 ->\n      P Σ Γ t (tSort s1) ->\n      Σ ;;; Γ,, vass n t |- b : tSort s2 ->\n      P Σ (Γ,, vass n t) b (tSort s2) -> P Σ Γ (tProd n t b) (tSort (Universe.sort_of_product s1 s2))) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (n : aname) (t b : term)\n          (s1 : Universe.t) (bty : term),\n      PΓ Σ Γ ->\n      Σ ;;; Γ |- t : tSort s1 ->\n      P Σ Γ t (tSort s1) ->\n      Σ ;;; Γ,, vass n t |- b : bty -> P Σ (Γ,, vass n t) b bty -> P Σ Γ (tLambda n t b) (tProd n t bty)) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (n : aname) (b b_ty b' : term)\n          (s1 : Universe.t) (b'_ty : term),\n      PΓ Σ Γ ->\n      Σ ;;; Γ |- b_ty : tSort s1 ->\n      P Σ Γ b_ty (tSort s1) ->\n      Σ ;;; Γ |- b : b_ty ->\n      P Σ Γ b b_ty ->\n      Σ ;;; Γ,, vdef n b b_ty |- b' : b'_ty ->\n      P Σ (Γ,, vdef n b b_ty) b' b'_ty -> P Σ Γ (tLetIn n b b_ty b') (tLetIn n b b_ty b'_ty)) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (t : term) T B L s,\n      PΓ Σ Γ ->\n      Σ ;;; Γ |- T : tSort s -> P Σ Γ T (tSort s) ->\n      forall (Ht : Σ ;;; Γ |- t : T), P Σ Γ t T ->\n\n      (* Give a stronger induction hypothesis allowing to crawl under applications *)\n      (forall t' T' (Ht' : Σ ;;; Γ |- t' : T'), typing_size Ht' <= typing_size Ht -> P Σ Γ t' T') ->\n      typing_spine_pred Σ Γ (fun u ty H => Σ ;;; Γ |- u : ty × P Σ Γ u ty) T L B ->\n\n      P Σ Γ (mkApps t L) B) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) cst u (decl : constant_body),\n      Forall_decls_typing P Σ.1 ->\n      PΓ Σ Γ ->\n      declared_constant Σ.1 cst decl ->\n      consistent_instance_ext Σ decl.(cst_universes) u ->\n      P Σ Γ (tConst cst u) (subst_instance u (cst_type decl))) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (ind : inductive) u\n        mdecl idecl (isdecl : declared_inductive Σ.1 ind mdecl idecl),\n      Forall_decls_typing P Σ.1 ->\n      PΓ Σ Γ ->\n      consistent_instance_ext Σ mdecl.(ind_universes) u ->\n      P Σ Γ (tInd ind u) (subst_instance u (ind_type idecl))) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (ind : inductive) (i : nat) u\n          mdecl idecl cdecl (isdecl : declared_constructor Σ.1 (ind, i) mdecl idecl cdecl),\n      Forall_decls_typing P Σ.1 ->\n      PΓ Σ Γ ->\n      consistent_instance_ext Σ mdecl.(ind_universes) u ->\n      P Σ Γ (tConstruct ind i u) (type_of_constructor mdecl cdecl (ind, i) u)) ->\n\n    (forall (Σ : global_env_ext) (wfΣ : wf Σ) (Γ : context) (wfΓ : wf_local Σ Γ),\n     forall (ci : case_info) p c brs indices ps mdecl idecl\n       (isdecl : declared_inductive Σ.1 ci.(ci_ind) mdecl idecl),\n       Forall_decls_typing P Σ.1 ->\n       PΓ Σ Γ ->\n       mdecl.(ind_npars) = ci.(ci_npar) ->\n       eq_context_upto_names p.(pcontext) (ind_predicate_context ci.(ci_ind) mdecl idecl) ->\n       let predctx := case_predicate_context ci.(ci_ind) mdecl idecl p in\n       wf_predicate mdecl idecl p ->\n       consistent_instance_ext Σ (ind_universes mdecl) p.(puinst) ->\n       forall pret : Σ ;;; Γ ,,, predctx |- p.(preturn) : tSort ps,\n       P Σ (Γ ,,, predctx) p.(preturn) (tSort ps) ->\n       wf_local Σ (Γ ,,, predctx) ->\n       PΓ Σ (Γ ,,, predctx) ->\n       is_allowed_elimination Σ idecl.(ind_kelim) ps ->\n       PCUICTyping.ctx_inst (Prop_conj typing P) Σ Γ (p.(pparams) ++ indices)\n         (List.rev (subst_instance p.(puinst) (mdecl.(ind_params) ,,, idecl.(ind_indices)))) ->\n       Σ ;;; Γ |- c : mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices) ->\n       P Σ Γ c (mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices)) ->\n       isCoFinite mdecl.(ind_finite) = false ->\n       let ptm := it_mkLambda_or_LetIn predctx p.(preturn) in\n       wf_branches idecl brs ->\n       All2i (fun i cdecl br =>\n         (eq_context_upto_names br.(bcontext) (cstr_branch_context ci mdecl cdecl)) ×\n         let brctxty := case_branch_type ci.(ci_ind) mdecl idecl p br ptm i cdecl in\n         (PΓ Σ (Γ ,,, brctxty.1) ×\n         (Prop_conj typing P Σ (Γ ,,, brctxty.1) br.(bbody) brctxty.2) ×\n         (Prop_conj typing P Σ (Γ ,,, brctxty.1) brctxty.2 (tSort ps)))) 0 idecl.(ind_ctors) brs ->\n       P Σ Γ (tCase ci p c brs) (mkApps ptm (indices ++ [c]))) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (p : projection) (c : term) u\n        mdecl idecl cdecl pdecl (isdecl : declared_projection Σ.1 p mdecl idecl cdecl pdecl) args,\n      Forall_decls_typing P Σ.1 -> PΓ Σ Γ ->\n      Σ ;;; Γ |- c : mkApps (tInd p.(proj_ind) u) args ->\n      P Σ Γ c (mkApps (tInd p.(proj_ind) u) args) ->\n      #|args| = ind_npars mdecl ->\n      P Σ Γ (tProj p c) (subst0 (c :: List.rev args) (pdecl.(proj_type)@[u]))) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (mfix : list (def term)) (n : nat) decl,\n      let types := fix_context mfix in\n      fix_guard Σ Γ mfix ->\n      nth_error mfix n = Some decl ->\n      PΓ Σ (Γ ,,, types) ->\n      All (on_def_type (lift_typing2 typing P Σ) Γ) mfix ->\n      All (on_def_body (lift_typing2 typing P Σ) types Γ) mfix ->\n      wf_fixpoint Σ.1 mfix ->\n      P Σ Γ (tFix mfix n) decl.(dtype)) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (mfix : list (def term)) (n : nat) decl,\n      let types := fix_context mfix in\n      cofix_guard Σ Γ mfix ->\n      nth_error mfix n = Some decl ->\n      PΓ Σ (Γ ,,, types) ->\n      All (on_def_type (lift_typing2 typing P Σ) Γ) mfix ->\n      All (on_def_body (lift_typing2 typing P Σ) types Γ) mfix ->\n      wf_cofixpoint Σ.1 mfix ->\n      P Σ Γ (tCoFix mfix n) decl.(dtype)) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (p : prim_val) prim_ty cdecl,\n    PΓ Σ Γ ->\n    primitive_constant Σ.1 (prim_val_tag p) = Some prim_ty ->\n    declared_constant Σ.1 prim_ty cdecl ->\n    primitive_invariants cdecl ->\n    P Σ Γ (tPrim p) (tConst prim_ty [])) ->\n\n  (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (t A B : term) s,\n      PΓ Σ Γ ->\n      Σ ;;; Γ |- t : A ->\n      P Σ Γ t A ->\n      Σ ;;; Γ |- B : tSort s ->\n      P Σ Γ B (tSort s) ->\n      Σ ;;; Γ |- A <=s B ->\n      P Σ Γ t B) ->\n\n     env_prop P PΓ.\nProof.\n intros P Pdecl PΓ.\n intros XΓ X X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 Σ wfΣ Γ t T H.\n eapply typing_ind_env_app_size; eauto. clear Σ wfΣ Γ t T H.\n intros Σ wfΣ Γ wfΓ t na A B u s HΓ Hprod IHprod Ht IHt IH Hu IHu.\n pose proof (mkApps_decompose_app t).\n destruct (decompose_app t) as [t1 L].\n subst. rename t1 into t. cbn in *.\n replace (tApp (mkApps t L) u) with (mkApps t (L ++ [u])) by now rewrite mkApps_app.\n\n pose proof (@inversion_mkApps cf) as Happs. specialize Happs with (H := Ht).\n forward Happs; eauto.\n destruct (Happs _ Hprod) as (A' & Hf & s' & HA & sz_f & sz_A & HL).\n destruct @inversion_Prod_size with (H := Hprod) as (s1 & s2 & H1 & H2 & Hs1 & Hs2 & Hsub); [ eauto | ].\n eapply X4. 6:eauto. 4: exact HA. all: eauto.\n - intros. eapply (IH _ _ Hf). lia.\n - Unshelve. 2:exact Hf. intros. eapply (IH _ _ Ht'). lia.\n - clear sz_A. induction L in A', Hf, (* HA, sz_A, *) Ht, HL, t, Hf, IH (*, s' *) |- *.\n   + inversion HL; subst. inversion X13. econstructor. econstructor; eauto. eauto. eauto. eauto. eauto. eauto.\n     econstructor. 1,2: eapply isType_apply; eauto. eapply ws_cumul_pb_refl.\n     eapply typing_closed_context; eauto. eapply type_is_open_term.\n     eapply type_App; eauto.\n   + cbn. inversion HL. subst. clear HL.\n     eapply inversion_Prod in H' as Hx; eauto. destruct Hx as (? & ? & ? & ? & ?).\n     econstructor.\n     7: unshelve eapply IHL.\n     now eauto. now eauto. split. now eauto. unshelve eapply IH. eauto. lia.\n     now eauto. now eauto. split. now eauto. unshelve eapply IH. eauto. lia.\n     2: now eauto. eauto.\n     econstructor; eauto. econstructor; eauto. now eapply cumulAlgo_cumulSpec in X14.\n     eauto.\nQed.\n\nLemma typing_ind_env `{cf : checker_flags} :\n  forall (P : global_env_ext -> context -> term -> term -> Type)\n         (Pdecl := fun Σ Γ wfΓ t T tyT => P Σ Γ t T)\n         (PΓ : global_env_ext -> context -> Type),\n\n    (forall Σ (wfΣ : wf Σ.1)  (Γ : context) (wfΓ : wf_local Σ Γ),\n         All_local_env_over typing Pdecl Σ Γ wfΓ -> PΓ Σ Γ) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (n : nat) decl,\n        nth_error Γ n = Some decl ->\n        PΓ Σ Γ ->\n        P Σ Γ (tRel n) (lift0 (S n) decl.(decl_type))) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (u : Universe.t),\n        PΓ Σ Γ ->\n        wf_universe Σ u ->\n        P Σ Γ (tSort u) (tSort (Universe.super u))) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (n : aname) (t b : term) (s1 s2 : Universe.t),\n        PΓ Σ Γ ->\n        Σ ;;; Γ |- t : tSort s1 ->\n        P Σ Γ t (tSort s1) ->\n        Σ ;;; Γ,, vass n t |- b : tSort s2 ->\n        P Σ (Γ,, vass n t) b (tSort s2) -> P Σ Γ (tProd n t b) (tSort (Universe.sort_of_product s1 s2))) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (n : aname) (t b : term)\n            (s1 : Universe.t) (bty : term),\n        PΓ Σ Γ ->\n        Σ ;;; Γ |- t : tSort s1 ->\n        P Σ Γ t (tSort s1) ->\n        Σ ;;; Γ,, vass n t |- b : bty -> P Σ (Γ,, vass n t) b bty -> P Σ Γ (tLambda n t b) (tProd n t bty)) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (n : aname) (b b_ty b' : term)\n            (s1 : Universe.t) (b'_ty : term),\n        PΓ Σ Γ ->\n        Σ ;;; Γ |- b_ty : tSort s1 ->\n        P Σ Γ b_ty (tSort s1) ->\n        Σ ;;; Γ |- b : b_ty ->\n        P Σ Γ b b_ty ->\n        Σ ;;; Γ,, vdef n b b_ty |- b' : b'_ty ->\n        P Σ (Γ,, vdef n b b_ty) b' b'_ty -> P Σ Γ (tLetIn n b b_ty b') (tLetIn n b b_ty b'_ty)) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (t : term) T B L s,\n        PΓ Σ Γ ->\n        Σ ;;; Γ |- T : tSort s -> P Σ Γ T (tSort s) ->\n        forall (Ht : Σ ;;; Γ |- t : T), P Σ Γ t T ->\n\n        (* Give a stronger induction hypothesis allowing to crawl under applications *)\n        typing_spine_pred Σ Γ (fun u ty H => Σ ;;; Γ |- u : ty × P Σ Γ u ty) T L B ->\n\n        P Σ Γ (mkApps t L) B) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) cst u (decl : constant_body),\n        Forall_decls_typing P Σ.1 ->\n        PΓ Σ Γ ->\n        declared_constant Σ.1 cst decl ->\n        consistent_instance_ext Σ decl.(cst_universes) u ->\n        P Σ Γ (tConst cst u) (subst_instance u (cst_type decl))) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (ind : inductive) u\n          mdecl idecl (isdecl : declared_inductive Σ.1 ind mdecl idecl),\n        Forall_decls_typing P Σ.1 ->\n        PΓ Σ Γ ->\n        consistent_instance_ext Σ mdecl.(ind_universes) u ->\n        P Σ Γ (tInd ind u) (subst_instance u (ind_type idecl))) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (ind : inductive) (i : nat) u\n            mdecl idecl cdecl (isdecl : declared_constructor Σ.1 (ind, i) mdecl idecl cdecl),\n        Forall_decls_typing P Σ.1 ->\n        PΓ Σ Γ ->\n        consistent_instance_ext Σ mdecl.(ind_universes) u ->\n        P Σ Γ (tConstruct ind i u) (type_of_constructor mdecl cdecl (ind, i) u)) ->\n\n    (forall (Σ : global_env_ext) (wfΣ : wf Σ) (Γ : context) (wfΓ : wf_local Σ Γ),\n    forall (ci : case_info) p c brs indices ps mdecl idecl\n      (isdecl : declared_inductive Σ.1 ci.(ci_ind) mdecl idecl),\n      Forall_decls_typing P Σ.1 ->\n      PΓ Σ Γ ->\n      mdecl.(ind_npars) = ci.(ci_npar) ->\n      eq_context_upto_names p.(pcontext) (ind_predicate_context ci.(ci_ind) mdecl idecl) ->\n      let predctx := case_predicate_context ci.(ci_ind) mdecl idecl p in\n      wf_predicate mdecl idecl p ->\n      consistent_instance_ext Σ (ind_universes mdecl) p.(puinst) ->\n      forall pret : Σ ;;; Γ ,,, predctx |- p.(preturn) : tSort ps,\n      P Σ (Γ ,,, predctx) p.(preturn) (tSort ps) ->\n      wf_local Σ (Γ ,,, predctx) ->\n      PΓ Σ (Γ ,,, predctx) ->\n      is_allowed_elimination Σ idecl.(ind_kelim) ps ->\n      PCUICTyping.ctx_inst (Prop_conj typing P) Σ Γ (p.(pparams) ++ indices)\n        (List.rev (subst_instance p.(puinst) (mdecl.(ind_params) ,,, idecl.(ind_indices)))) ->\n      Σ ;;; Γ |- c : mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices) ->\n      P Σ Γ c (mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices)) ->\n      isCoFinite mdecl.(ind_finite) = false ->\n      let ptm := it_mkLambda_or_LetIn predctx p.(preturn) in\n      wf_branches idecl brs ->\n      All2i (fun i cdecl br =>\n        (eq_context_upto_names br.(bcontext) (cstr_branch_context ci mdecl cdecl)) ×\n        let brctxty := case_branch_type ci.(ci_ind) mdecl idecl p br ptm i cdecl in\n        (PΓ Σ (Γ ,,, brctxty.1) ×\n          (Prop_conj typing P Σ (Γ ,,, brctxty.1) br.(bbody) brctxty.2) ×\n          (Prop_conj typing P) Σ (Γ ,,, brctxty.1) brctxty.2 (tSort ps))) 0 idecl.(ind_ctors) brs ->\n      P Σ Γ (tCase ci p c brs) (mkApps ptm (indices ++ [c]))) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (p : projection) (c : term) u\n          mdecl idecl cdecl pdecl (isdecl : declared_projection Σ.1 p mdecl idecl cdecl pdecl) args,\n        Forall_decls_typing P Σ.1 -> PΓ Σ Γ ->\n        Σ ;;; Γ |- c : mkApps (tInd p.(proj_ind) u) args ->\n        P Σ Γ c (mkApps (tInd p.(proj_ind) u) args) ->\n        #|args| = ind_npars mdecl ->\n        P Σ Γ (tProj p c) (subst0 (c :: List.rev args) (subst_instance u pdecl.(proj_type)))) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (mfix : list (def term)) (n : nat) decl,\n        let types := fix_context mfix in\n        fix_guard Σ Γ mfix ->\n        nth_error mfix n = Some decl ->\n        PΓ Σ (Γ ,,, types) ->\n        All (on_def_type (lift_typing2 typing P Σ) Γ) mfix ->\n        All (on_def_body (lift_typing2 typing P Σ) types Γ) mfix ->\n        wf_fixpoint Σ.1 mfix ->\n        P Σ Γ (tFix mfix n) decl.(dtype)) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (mfix : list (def term)) (n : nat) decl,\n        let types := fix_context mfix in\n        cofix_guard Σ Γ mfix ->\n        nth_error mfix n = Some decl ->\n        PΓ Σ (Γ ,,, types) ->\n        All (on_def_type (lift_typing2 typing P Σ) Γ) mfix ->\n        All (on_def_body (lift_typing2 typing P Σ) types Γ) mfix ->\n        wf_cofixpoint Σ.1 mfix ->\n        P Σ Γ (tCoFix mfix n) decl.(dtype)) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (p : prim_val) prim_ty cdecl,\n        PΓ Σ Γ ->\n        primitive_constant Σ.1 (prim_val_tag p) = Some prim_ty ->\n        declared_constant Σ.1 prim_ty cdecl ->\n        primitive_invariants cdecl ->\n        P Σ Γ (tPrim p) (tConst prim_ty [])) ->\n\n    (forall Σ (wfΣ : wf Σ.1) (Γ : context) (wfΓ : wf_local Σ Γ) (t A B : term) s,\n        PΓ Σ Γ ->\n        Σ ;;; Γ |- t : A ->\n        P Σ Γ t A ->\n        Σ ;;; Γ |- B : tSort s ->\n        P Σ Γ B (tSort s) ->\n        Σ ;;; Γ |- A <=s B ->\n        P Σ Γ t B) ->\n\n       env_prop P PΓ.\nProof.\n  intros P Pdecl PΓ; unfold env_prop.\n  intros XΓ X X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 Σ wfΣ Γ t T H.\n  apply typing_ind_env_app_size; eauto.\nQed.\n\nLocal Hint Constructors value red1 : wcbv.\n\nDefinition axiom_free Σ :=\n  forall c decl, declared_constant Σ c decl -> cst_body decl <> None. (* TODO: consolidate with PCUICConsistency *)\n\nLemma value_stuck_fix Σ mfix idx args : isStuckFix (tFix mfix idx) args -> All (value Σ) args -> value Σ (mkApps (tFix mfix idx) args).\nProof.\n  unfold isStuckFix; intros isstuck vargs.\n  eapply value_app => //.\n  destruct cunfold_fix as [[rarg fn]|] eqn:cunf => //.\n  econstructor; tea. now eapply Nat.leb_le.\nQed.\n\nLemma typing_spine_length {cf : checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ} Γ Δ ind u args args' T' :\n  typing_spine Σ Γ (it_mkProd_or_LetIn Δ (mkApps (tInd ind u) args)) args' T' ->\n  #|args'| <= context_assumptions Δ.\nProof.\n  intros hsp.\n  pose proof (typing_spine_more_inv _ _ _ _ _ _ _ _ hsp).\n  destruct (Compare_dec.le_dec #|args'| (context_assumptions Δ)). lia. lia.\nQed.\n\nLemma declared_constructor_ind_decl {cf : checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ} {ind c} {mdecl idecl cdecl} :\n  declared_constructor Σ (ind, c) mdecl idecl cdecl ->\n  inductive_ind ind < #|ind_bodies mdecl|.\nProof.\n  intros [[hm hi] hc]. now eapply nth_error_Some_length in hi.\nQed.\n\nImport PCUICGlobalEnv.\n\nLemma typing_constructor_arity_exact {cf : checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ} {ind c u u' args}\n  {mdecl idecl cdecl indices} :\n  declared_constructor Σ (ind, c) mdecl idecl cdecl ->\n  Σ ;;; [] |- mkApps (tConstruct ind c u) args : mkApps (tInd ind u') indices ->\n  #|args| = cstr_arity mdecl cdecl.\nProof.\n  intros declc hc.\n  eapply Construct_Ind_ind_eq in hc; tea.\n  intuition auto.\nQed.\n\nLemma typing_constructor_arity {cf : checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ} {ind c u args T} {mdecl idecl cdecl} :\n  declared_constructor Σ (ind, c) mdecl idecl cdecl ->\n  Σ ;;; [] |- mkApps (tConstruct ind c u) args : T ->\n  #|args| <= cstr_arity mdecl cdecl.\nProof.\n  intros declc hc.\n  pose proof (validity hc).\n  eapply PCUICSpine.inversion_mkApps_direct in hc as [A' [u' [s' [hs hsp]]]]; eauto.\n  eapply inversion_Construct in s' as [mdecl' [idecl' [cdecl' [wf [declc' [cu cum]]]]]]; tea.\n  destruct (PCUICGlobalEnv.declared_constructor_inj declc declc') as [? []]. subst mdecl' idecl' cdecl'.\n  clear declc'.\n  eapply typing_spine_strengthen in hsp. 3:exact cum.\n  2:{ eapply validity. econstructor; tea. }\n  unfold type_of_constructor in hsp.\n  destruct (on_declared_constructor declc) as [[] [cunivs [_ onc]]].\n  rewrite onc.(cstr_eq) in hsp.\n  rewrite <-it_mkProd_or_LetIn_app in hsp.\n  rewrite subst_instance_it_mkProd_or_LetIn subst_it_mkProd_or_LetIn in hsp.\n  epose proof (subst_cstr_concl_head ind u mdecl (cstr_args cdecl) (cstr_indices cdecl)). cbn in H.\n  unfold cstr_concl in hsp. cbn in hsp. len in hsp. rewrite H in hsp. clear H.\n  eapply (declared_constructor_ind_decl declc). clear H.\n  eapply typing_spine_length in hsp. len in hsp. unfold cstr_arity.\n  now rewrite (PCUICGlobalEnv.declared_minductive_ind_npars declc).\nQed.\n\nLemma value_mkApps_inv' Σ f args :\n  negb (isApp f) ->\n  value Σ (mkApps f args) ->\n  atom f × All (value Σ) args.\nProof.\n  intros napp. move/value_mkApps_inv => [] => //.\n  - intros [-> hf]. split => //.\n  - intros []. split; auto. destruct v; now constructor.\nQed.\n\nGlobal Hint Resolve All_app_inv : pcuic.\n\nLemma red1_mkApps_left {Σ f f' args} : red1 Σ f f' -> red1 Σ (mkApps f args) (mkApps f' args).\nProof.\n  induction args using rev_ind.\n  - auto.\n  - intros. rewrite !mkApps_app.\n    eapply red_app_left. now apply IHargs.\nQed.\n\nLemma typing_spine_sort {cf : checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ} Γ s args T :\n  typing_spine Σ Γ (tSort s) args T -> args = [].\nProof.\n  induction args => //.\n  intros sp. depelim sp.\n  now eapply ws_cumul_pb_Sort_Prod_inv in w.\nQed.\n\nLemma typing_spine_axiom {cf : checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ} Γ cst u cdecl args T :\n  declared_constant Σ cst cdecl ->\n  cdecl.(cst_body) = None ->\n  typing_spine Σ Γ (tConst cst u) args T -> args = [].\nProof.\n  intros hdecl hb.\n  induction args => //.\n  intros sp. depelim sp.\n  now eapply invert_cumul_axiom_prod in w.\nQed.\n\nLemma typing_value_head_napp {cf : checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ} fn args hd T :\n  negb (isApp fn) ->\n  Σ ;;; [] |- mkApps fn (args ++ [hd]) : T ->\n  value Σ hd -> closed hd ->\n  value Σ (mkApps fn args) ->\n  (∑ t' : term, red1 Σ (mkApps fn (args ++ [hd])) t') +\n  value Σ (mkApps fn (args ++ [hd])).\nProof.\n  intros napp ht vhd clhd vapp.\n  pose proof ht as ht'.\n  destruct (value_mkApps_inv' _ _ _ napp vapp).\n  eapply PCUICSpine.inversion_mkApps_direct in ht' as [A' [u [hfn [hhd hcum]]]]; tea.\n  2:{ now eapply validity. }\n  destruct fn => //.\n  * eapply inversion_Sort in hfn as [? [? cu]]; tea.\n    eapply typing_spine_strengthen in hcum. 3:tea. 2:{ eapply validity; econstructor; eauto. }\n    now eapply typing_spine_sort, app_tip_nil in hcum.\n  * eapply inversion_Prod in hfn as [? [? [? [? cu]]]]; tea.\n    eapply typing_spine_strengthen in hcum. 3:tea. 2:{ eapply validity. econstructor; eauto. }\n    now eapply typing_spine_sort, app_tip_nil in hcum.\n  * (* Lambda *) left. destruct args.\n    - cbn. eexists. now eapply red_beta.\n    - eexists. rewrite mkApps_app. rewrite (mkApps_app _ [t] args). do 2 eapply red1_mkApps_left.\n      cbn. eapply red_beta. now depelim a.\n  * (* Inductive *)\n    eapply inversion_Ind in hfn as [? [? [? [? [? cu]]]]]; tea.\n    eapply typing_spine_strengthen in hcum. 3:tea. 2:{ eapply validity. econstructor; eauto. }\n    right. eapply value_app. constructor. eauto with pcuic.\n  * (* constructor *)\n    right. eapply value_app; auto. 2:{ eapply All_app_inv; eauto. }\n    pose proof hfn as hfn'.\n    eapply inversion_Construct in hfn' as [mdecl [idecl [cdecl [wf [declc _]]]]]; tea.\n    eapply (typing_constructor_arity declc) in ht.\n    econstructor; tea.\n  * (* fix *)\n    destruct (isStuckFix (tFix mfix idx) (args ++ [hd])) eqn:E.\n    + right. eapply value_stuck_fix; eauto with pcuic.\n    + cbn in E.\n      eapply inversion_Fix in hfn as ([] & ? & Efix & ? & ? & ?); eauto.\n      unfold cunfold_fix in E. rewrite Efix in E. cbn in E.\n      len in E. cbn in E. assert (rarg = #|args|).\n      eapply stuck_fix_value_args in vapp; tea. 2:{ unfold cunfold_fix. now rewrite Efix. }\n      cbn in vapp. apply Nat.leb_gt in E. lia. subst rarg.\n      left. eexists. rewrite mkApps_app /=. eapply red_fix. eauto. eauto.\n      unfold unfold_fix. now rewrite Efix.\n      eapply fix_app_is_constructor in ht.\n      2:{ unfold unfold_fix. now rewrite Efix. }\n      cbn in ht. rewrite nth_error_app_ge // /= in ht.\n      replace (#|args| - #|args|) with 0 in ht by lia. cbn in ht. apply ht.\n      eapply value_axiom_free; eauto.\n      eapply value_whnf; eauto.\n  * (* cofix *)\n    right. eapply value_app; eauto with pcuic.\n    now constructor.\n  * (* primitive *)\n    cbn.\n    eapply inversion_Prim in hfn as [prim_ty [cdecl [hwf hp hdecl [s []]]]]; tea.\n    eapply typing_spine_strengthen in hcum. 3:tea. 2:{ eapply validity; econstructor; eauto. now exists s. }\n    now eapply typing_spine_axiom, app_tip_nil in hcum.\nQed.\n\nLemma typing_value_head {cf : checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ} fn args hd T :\n  Σ ;;; [] |- mkApps fn (args ++ [hd]) : T ->\n  value Σ hd -> closed hd ->\n  value Σ (mkApps fn args) ->\n  (∑ t' : term, red1 Σ (mkApps fn (args ++ [hd])) t') +\n  value Σ (mkApps fn (args ++ [hd])).\nProof.\n  destruct (decompose_app fn) eqn:da.\n  pose proof (decompose_app_notApp _ _ _ da).\n  rewrite (decompose_app_inv da).\n  rewrite -mkApps_app app_assoc.\n  intros; eapply typing_value_head_napp; tea. now rewrite H.\n  rewrite mkApps_app //.\nQed.\n\nLemma cstr_branch_context_assumptions ci mdecl cdecl :\n  context_assumptions (cstr_branch_context ci mdecl cdecl) =\n  context_assumptions (cstr_args cdecl).\nProof.\n  rewrite /cstr_branch_context /PCUICEnvironment.expand_lets_ctx\n    /PCUICEnvironment.expand_lets_k_ctx.\n  now do 2 rewrite !context_assumptions_subst_context ?context_assumptions_lift_context.\nQed.\n\nLemma progress `{cf : checker_flags}:\n  env_prop (fun Σ Γ t T => axiom_free Σ -> Γ = [] -> Σ ;;; Γ |- t : T -> {t' & red1 Σ t t'} + (value Σ t))\n           (fun _ _ => True).\nProof with eauto with wcbv; try congruence.\n  eapply typing_ind_env...\n  - intros Σ wfΣ Γ wfΓ n decl Hdecl _ Hax -> Hty.\n    destruct n; inv Hdecl.\n  - intros Σ wfΣ Γ _ n b b_ty b' s1 b'_ty _ Hb_ty IHb_ty Hb IHb Hb' IHb' Hax -> H.\n    destruct (IHb Hax eq_refl) as [ [t' IH] | IH]; eauto with wcbv.\n  - intros Σ wfΣ Γ _ t T B L s _ HT IHT Ht IHt HL Hax -> H.\n    clear HT IHT.\n    induction HL in H, t, Ht, IHt |- *.\n    + cbn. eauto.\n    + cbn. eapply IHHL.\n      2:{ do 2 (econstructor; eauto). now eapply cumulAlgo_cumulSpec in w. }\n      intros _ Happ.\n      destruct (IHt Hax eq_refl Ht) as [[t' IH] | IH]; eauto with wcbv.\n      assert (Ht' : Σ ;;; [] |- t : tProd na A B) by (econstructor; eauto; now eapply cumulAlgo_cumulSpec in w).\n      destruct p0 as [_ [[t' Hstep] | Hval]]; eauto using red1.\n      intros htapp.\n      pose proof (typing_value_head t [] hd _ htapp Hval).\n      forward X. now eapply subject_closed in H0. cbn in X.\n      specialize (X IH). exact X.\n      now cbn in H.\n  - intros Σ wf Γ _ cst u decl Hdecls _ Hdecl Hcons Hax -> H.\n    destruct (decl.(cst_body)) as [body | ] eqn:E.\n    + eauto with wcbv.\n    + red in Hax. eapply Hax in E; eauto.\n  - intros Σ wfΣ Γ _ ci p c brs indices ps mdecl idecl Hidecl Hforall _ Heq Heq_context predctx Hwfpred Hcon Hreturn IHreturn Hwfl _.\n    intros Helim Hctxinst Hc IHc Hcof ptm Hwfbranches Hall Hax -> H.\n    specialize (IHc Hax eq_refl) as [[t' IH] | IH]; eauto with wcbv.\n    pose proof IH as IHv.\n    eapply PCUICCanonicity.value_canonical in IH; eauto.\n    unfold head in IH.\n    rewrite (PCUICInduction.mkApps_decompose_app c) in H, Hc, IHv |- *.\n    destruct (decompose_app c) as [h l].\n    cbn - [decompose_app] in *.\n    destruct h; inv IH.\n    + eapply invert_Case_Construct in H as H_; sq; eauto. destruct H_ as (Eq & H_); subst.\n      left.\n      destruct (nth_error brs n) as [br | ] eqn:E.\n      2:{ exfalso. destruct H_ as [? []]; congruence. }\n      assert (#|l| = ci_npar ci + context_assumptions (bcontext br)) as Hl.\n      { destruct H_ as [? []]; auto. now noconf H0. }\n      clear H_. eapply Construct_Ind_ind_eq' in Hc as (? & ? & ? & ? & _); eauto.\n      eexists.\n      destruct (declared_inductive_inj d.p1 Hidecl); subst x x0.\n      eapply All2i_nth_error in Hall as [eqctx _]; tea; [|eapply d].\n      eapply PCUICCasesContexts.alpha_eq_context_assumptions in eqctx.\n      rewrite cstr_branch_context_assumptions in eqctx.\n      eapply red_iota; eauto.\n      { rewrite /cstr_arity Hl. rewrite -Heq. lia. }\n      eapply value_mkApps_inv in IHv as [[-> ]|[]]; eauto.\n\n    + eapply inversion_Case in H as (? & ? & ? & ? & [] & ?); eauto.\n      eapply PCUICValidity.inversion_mkApps in scrut_ty as (? & ? & ?); eauto.\n      eapply inversion_CoFix in t as (? & ? & ? & ? & ? & ? & ?); eauto.\n      left. eexists. eapply red_cofix_case. unfold cunfold_cofix. rewrite e. reflexivity.\n      eapply value_mkApps_inv in IHv as [[-> ]|[]]; eauto.\n  - intros Σ wfΣ Γ _ p c u mdecl idecl cdecl pdecl Hcon args Hargs _ Hc IHc\n           Hlen Hax -> H.\n    destruct (IHc Hax eq_refl) as [[t' IH] | IH]; eauto with wcbv; clear IHc.\n    pose proof IH as Hval.\n    eapply PCUICCanonicity.value_canonical in IH; eauto.\n    unfold head in IH.\n    rewrite (PCUICInduction.mkApps_decompose_app c) in H, Hc, Hval |- *.\n    destruct (decompose_app c) as [h l].\n    cbn - [decompose_app] in *.\n    destruct h; inv IH.\n    + eapply invert_Proj_Construct in H as H_; sq; eauto. destruct H_ as (<- & -> & Hl).\n      left. eapply nth_error_Some' in Hl as [x Hx].\n      eexists.\n      eapply red_proj; eauto.\n      now eapply (typing_constructor_arity_exact Hcon) in Hc.\n      eapply value_mkApps_inv in Hval as [[-> Hval] | [? ? Hval]]; eauto.\n    + left. eapply inversion_Proj in H as (? & ? & ? & ? & ? & ? & ? & ? & ? & ?); eauto.\n      eapply PCUICValidity.inversion_mkApps in t as (? & ? & ?); eauto.\n      eapply inversion_CoFix in t as (? & ? & ? & ? & ? & ? & ?); eauto.\n      eexists. eapply red_cofix_proj. unfold cunfold_cofix. rewrite e0. reflexivity.\n      eapply value_mkApps_inv in Hval as [[-> ]|[]]; eauto.\nQed.\n\nLemma red1_closed {cf : checker_flags} {Σ t t'} :\n  wf Σ ->\n  closed t -> red1 Σ t t' -> closed t'.\nProof.\n  intros Hwf Hcl Hred. induction Hred; cbn in *; solve_all.\n  all: eauto using closed_csubst, closed_def.\n  - eapply closed_iota; eauto. solve_all. unfold test_predicate_k in H. solve_all.\n    now rewrite e0 /cstr_arity -e1 -e2.\n  - eauto using closed_arg.\n  - rewrite !closedn_mkApps in H |- *. solve_all.\n    eapply closed_unfold_fix; tea.\n  - rewrite !closedn_mkApps in Hcl |- *. solve_all.\n    unfold cunfold_cofix in e. destruct nth_error as [d | ] eqn:E; inversion e.\n    eapply closed_unfold_cofix with (narg := narg); eauto.\n    unfold unfold_cofix. rewrite E. subst. repeat f_equal.\n    eapply closed_cofix_substl_subst_eq; eauto.\n  - rewrite !closedn_mkApps in H1 |- *. solve_all.\n    unfold cunfold_cofix in e. destruct nth_error as [d | ] eqn:E; inversion e.\n    eapply closed_unfold_cofix with (narg := narg); eauto.\n    unfold unfold_cofix. rewrite E. subst. repeat f_equal.\n    eapply closed_cofix_substl_subst_eq; eauto.\nQed.\n\nLemma red1_incl {cf : checker_flags} {Σ t t' } :\n  closed t ->\n  red1 Σ t t' -> PCUICReduction.red1 Σ [] t t'.\nProof.\n  intros Hcl Hred.\n  induction Hred. all: cbn in *; solve_all.\n  1-10: try econstructor; eauto using red1_closed.\n  1,2: now rewrite closed_subst; eauto; econstructor; eauto.\n  - now rewrite e0 /cstr_arity -e1 -e2.\n  - rewrite !tApp_mkApps -!mkApps_app. econstructor. eauto.\n    unfold is_constructor. now rewrite nth_error_app2 // Nat.sub_diag.\n  - unfold cunfold_cofix in e. destruct nth_error as [d | ] eqn:E; try congruence.\n    inversion e; subst.\n    econstructor. unfold unfold_cofix. rewrite E. repeat f_equal.\n    eapply closed_cofix_substl_subst_eq; eauto. rewrite closedn_mkApps in Hcl. solve_all.\n  - unfold cunfold_cofix in e. destruct nth_error as [d | ] eqn:E; try congruence.\n    inversion e; subst.\n    econstructor. unfold unfold_cofix. rewrite E. repeat f_equal.\n    eapply closed_cofix_substl_subst_eq; eauto. rewrite closedn_mkApps in H1. solve_all.\nQed.\n\nGlobal Hint Constructors value eval : wcbv.\nGlobal Hint Resolve value_final : wcbv.\n\n(* Lemma eval_tApp_Construct {Σ a b ind c u args a'}\n  eval Σ a\neval Σ (tApp a b) (mkApps (tConstruct ind c u) (args ++ [a']))\n *)\n\nLemma red1_eval {Σ : global_env_ext } t t' v : wf Σ ->\n  closed t ->\n  red1 Σ t t' -> eval Σ t' v -> eval Σ t v.\nProof.\n  intros Hwf Hty Hred Heval.\n  induction Hred in Heval, v, Hty |- *; eauto with wcbv.\n  - inversion Heval; subst; clear Heval. all:cbn in Hty; solve_all. 1-3,6:now econstructor; eauto with wcbv.\n    eapply eval_construct; tea. eauto. eapply eval_app_cong; eauto with wcbv.\n  - inversion Heval; subst; clear Heval. all:cbn in Hty; solve_all. 1-3,6: now econstructor; eauto with wcbv.\n    eapply eval_construct; tea. eauto. eapply eval_app_cong; eauto with wcbv.\n  - inversion Heval; subst; clear Heval. all:cbn in Hty; solve_all. all: now econstructor; eauto with wcbv.\n  - inversion Heval; subst; clear Heval. all:cbn in Hty; solve_all. all: try now econstructor; eauto with wcbv.\n  - eapply eval_iota. eapply eval_mkApps_Construct; tea. now econstructor. unfold cstr_arity. rewrite e0.\n    rewrite (PCUICGlobalEnv.declared_minductive_ind_npars d).\n    now rewrite -(declared_minductive_ind_npars d) /cstr_arity.\n    all:tea. eapply All_All2_refl. solve_all. now eapply value_final.\n  - inversion Heval; subst; clear Heval. all:cbn in Hty; solve_all. all: now econstructor; eauto with wcbv.\n  - all:cbn in Hty; solve_all. eapply eval_proj; tea.\n    eapply value_final. eapply value_app; auto. econstructor; tea. eapply d.\n    rewrite e; lia.\n  - eapply eval_fix; eauto.\n    + eapply value_final. eapply value_app; auto. econstructor.\n      rewrite <- closed_unfold_fix_cunfold_eq, e. reflexivity. 2:eauto.\n      cbn in Hty. rewrite closedn_mkApps in Hty. solve_all.\n    + eapply value_final; eauto.\n    + rewrite <- closed_unfold_fix_cunfold_eq, e. reflexivity.\n      cbn in Hty. rewrite closedn_mkApps in Hty. solve_all.\n      Unshelve. all: now econstructor.\n  - destruct p as [[] ?]. eapply eval_cofix_proj; tea.\n    eapply value_final, value_app. now constructor. auto.\n  - eapply eval_cofix_case; tea.\n    eapply value_final, value_app. now constructor. auto.\nQed.\n\nFrom MetaCoq Require Import PCUICSN.\n\nLemma WN {no:normalizing_flags} {Σ} {normalisation:NormalisationIn Σ} {t} : wf_ext Σ -> axiom_free Σ ->\n  welltyped Σ [] t  -> exists v, squash (eval Σ t v).\nProof.\n  intros Hwf Hax Hwt.\n  eapply PCUICSN.normalisation_in in Hwt as HSN; eauto.\n  induction HSN as [t H IH].\n  destruct Hwt as [A HA].\n  edestruct progress as [_ [_ [[t' Ht'] | Hval]]]; eauto.\n  - eapply red1_incl in Ht' as Hred. 2:{ change 0 with (#|@nil context_decl|). eapply subject_closed. eauto. }\n    edestruct IH as [v Hv]. econstructor. eauto.\n    econstructor. eapply subject_reduction; eauto.\n    exists v. sq. eapply red1_eval; eauto.\n    now eapply subject_closed in HA.\n  - exists t. sq. eapply value_final; eauto.\nQed.\n\nFrom MetaCoq Require Import PCUICFirstorder.\n\nLemma firstorder_value_irred Σ t t' :\n  firstorder_value Σ [] t ->\n  PCUICReduction.red1 Σ [] t t' -> False.\nProof.\n  intros H.\n  revert t'. pattern t. revert t H.\n  eapply firstorder_value_inds.\n  intros i n ui u args pandi Hty Hargs IH Hprop t' Hred.\n  eapply red1_mkApps_tConstruct_inv in Hred as (x & -> & Hone).\n  solve_all.\n  clear - IH Hone. induction IH as [ | ? ? []] in x, Hone |- *.\n  - invs Hone.\n  - invs Hone; eauto.\nQed.\n\nDefinition ws_empty f : ws_context f.\nProof.\n  unshelve econstructor.\n  exact nil.\n  reflexivity.\nDefined.\n\nLemma irred_equal Σ Γ t t' :\n  Σ ;;; Γ ⊢ t ⇝ t' ->\n  (forall v', PCUICReduction.red1 Σ Γ t v' -> False) ->\n  t = t'.\nProof.\n  intros Hred Hirred. destruct Hred.\n  clear clrel_ctx clrel_src.\n  induction clrel_rel.\n  - edestruct Hirred; eauto.\n  - reflexivity.\n  - assert (x = y) as <- by eauto. eauto.\nQed.\n\nLemma ws_wcbv_standardization {no:normalizing_flags} {Σ} {normalisation:NormalisationIn Σ} {i u args mind} {t v : ws_term (fun _ => false)} : wf_ext Σ -> axiom_free Σ ->\n  Σ ;;; [] |- t : mkApps (tInd i u) args ->\n  lookup_env Σ (i.(inductive_mind)) = Some (InductiveDecl mind) ->\n  @firstorder_ind Σ (firstorder_env Σ) i ->\n  closed_red Σ [] t v ->\n  (forall v', PCUICReduction.red1 Σ [] v v' -> False) ->\n  squash (eval Σ t v).\nProof.\n  intros Hwf Hax Hty Hdecl Hfo Hred Hirred.\n  destruct (@WN no Σ normalisation t) as (v' & Hv'); eauto.\n  1:{ eexists; eauto. }\n  sq.\n  assert (Σ;;; [] |- t ⇝* v') as Hred' by now eapply wcbeval_red.\n  eapply closed_red_confluence in Hred as Hred_. destruct Hred_ as (v'' & H1 & H2).\n  2:{ econstructor; eauto. eapply subject_is_open_term. eauto. }\n  destruct v as [v Hv].\n  assert (v = v'') as <- by (eapply irred_equal; eauto).\n  assert (firstorder_value Σ [] v'). {\n    eapply firstorder_value_spec; eauto.\n    eapply subject_reduction_eval; eauto.\n    eapply eval_to_value. eauto.\n  }\n  enough (v' = v) as -> by eauto.\n  eapply irred_equal. eauto.\n  intros. eapply firstorder_value_irred; eauto.\nQed.\n\nLemma wcbv_standardization {no:normalizing_flags} {Σ} {normalisation:NormalisationIn Σ} {i u args mind} {t v : term} : wf_ext Σ -> axiom_free Σ ->\n  Σ ;;; [] |- t : mkApps (tInd i u) args ->\n  lookup_env Σ (i.(inductive_mind)) = Some (InductiveDecl mind) ->\n  @firstorder_ind Σ (firstorder_env Σ) i ->\n  red Σ [] t v ->\n  (forall v', PCUICReduction.red1 Σ [] v v' -> False) ->\n  ∥ eval Σ t v ∥.\nProof.\n  intros Hwf Hax Hty Hdecl Hfo Hred Hirred.\n  unshelve edestruct @ws_wcbv_standardization.\n  1-6: shelve.\n  1: exists t; shelve.\n  1: exists v; shelve.\n  all: sq; eauto.\n  cbn.\n  econstructor; eauto.\n  eapply subject_is_open_term. eauto.\n  Unshelve.\n  all: rewrite -closed_on_free_vars_none.\n  - now eapply subject_closed in Hty.\n  - eapply @subject_closed with (Γ := []); eauto.\n    eapply subject_reduction; eauto.\nQed.\n", "meta": {"author": "SwampertX", "repo": "undergraduate-thesis", "sha": "b0c78984b94e56f1372a7195bd0babaab10fca8d", "save_path": "github-repos/coq/SwampertX-undergraduate-thesis", "path": "github-repos/coq/SwampertX-undergraduate-thesis/undergraduate-thesis-b0c78984b94e56f1372a7195bd0babaab10fca8d/final-report-new/code/v2/pcuic/theories/PCUICProgress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24276020557110267}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Facade.DFModule.\nRequire Import Platform.Facade.CompileDFacade.\nRequire Import Platform.Facade.DFacade.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Variable module : DFModule ADTValue.\n\n  Definition compile_func (f : DFFun) : FModule.FFunction := FModule.Build_FFunction (compile_op f) (compiled_syntax_ok f).\n\n  Require Import Platform.Cito.StringMap.\n  Import StringMap.\n  Require Import Platform.Cito.StringMapFacts.\n\n  Definition compile_to_fmodule : FModule.FModule ADTValue := FModule.Build_FModule (Imports module) (StringMap.map compile_func (Funs module)).\n\n  Require Import Coq.Strings.String.\n\n  Variable name : string.\n\n  Require Import Platform.Cito.NameDecoration.\n\n  Hypothesis good_name : is_good_module_name name = true.\n\n  Require Platform.Facade.CompileModule.\n\n  Definition compile_to_gmodule : GoodModule.GoodModule := CompileModule.compile_to_gmodule compile_to_fmodule name good_name.\n\nEnd ADTValue.", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Facade/CompileDFModule.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24276019912445274}}
{"text": "Require Import oeuf.Common.\n\nRequire Import oeuf.Utopia.\nRequire Import oeuf.Monads.\nRequire Import oeuf.ListLemmas.\nRequire Import oeuf.Metadata.\nRequire Import oeuf.HigherValue.\nRequire Import oeuf.AllValues.\nRequire Import oeuf.OpaqueOps.\nRequire oeuf.StepLib.\n\nDefinition function_name := nat.\n\n(* List containing a flag for each argument, `true` if Elim should recurse on\n   that argument, `false` if it shouldn't.  The length gives the number of\n   arguments. *)\nDefinition rec_info := list bool.\n\nInductive expr :=\n| Value (v : value)\n| Arg\n| UpVar (idx : nat)\n| Call (f : expr) (a : expr)\n| MkConstr (tag : nat) (args : list expr)\n| Elim (loop : expr) (cases : list (expr * rec_info)) (target : expr)\n| MkClose (f : function_name) (free : list expr)\n| OpaqueOp (op : opaque_oper_name) (args : list expr)\n.\n\nInductive is_value : expr -> Prop :=\n| IsValue : forall v, is_value (Value v).\n\nDefinition env := list expr.\n\nFixpoint unroll_elim (case : expr)\n                     (args : list value)\n                     (rec : rec_info)\n                     (mk_rec : expr -> expr) : option expr :=\n    match args, rec with\n    | [], [] => Some case\n    | arg :: args, r :: rec =>\n            let case := Call case (Value arg) in\n            let case := if r then Call case (mk_rec (Value arg)) else case in\n            unroll_elim case args rec mk_rec\n    | _, _ => None\n    end.\n\n\nInductive state :=\n| Run (e : expr) (l : list value) (k : value -> state)\n| Stop (v : value).\n\nInductive sstep (E : env) : state -> state -> Prop :=\n| SArg : forall l k v,\n        nth_error l 0 = Some v ->\n        sstep E (Run Arg l k) (k v)\n| SUpVar : forall n l k v,\n        nth_error l (S n) = Some v ->\n        sstep E (Run (UpVar n) l k) (k v)\n\n| SCloseStep : forall tag vs e es l k,\n        Forall is_value vs ->\n        ~ is_value e ->\n        sstep E (Run (MkClose tag (vs ++ [e] ++ es)) l k)\n                (Run e l (fun v => Run (MkClose tag (vs ++ [Value v] ++ es)) l k))\n| SCloseDone : forall tag vs l k,\n        let es := map Value vs in\n        sstep E (Run (MkClose tag es) l k) (k (Close tag vs))\n\n| SConstrStep : forall fname vs e es l k,\n        Forall is_value vs ->\n        ~ is_value e ->\n        sstep E (Run (MkConstr fname (vs ++ [e] ++ es)) l k)\n                (Run e l (fun v => Run (MkConstr fname (vs ++ [Value v] ++ es)) l k))\n| SConstrDone : forall fname vs l k,\n        let es := map Value vs in\n        sstep E (Run (MkConstr fname es) l k) (k (Constr fname vs))\n\n| SOpaqueOpStep : forall op vs e es l k,\n        Forall is_value vs ->\n        ~ is_value e ->\n        sstep E (Run (OpaqueOp op (vs ++ [e] ++ es)) l k)\n                (Run e l (fun v => Run (OpaqueOp op (vs ++ [Value v] ++ es)) l k))\n| SOpaqueOpDone : forall op vs l k v,\n        let es := map Value vs in\n        opaque_oper_denote_higher op vs = Some v ->\n        sstep E (Run (OpaqueOp op es) l k) (k v)\n\n| SCallL : forall e1 e2 l k,\n        ~ is_value e1 ->\n        sstep E (Run (Call e1 e2) l k)\n                (Run e1 l (fun v => Run (Call (Value v) e2) l k))\n| SCallR : forall e1 e2 l k,\n        is_value e1 ->\n        ~ is_value e2 ->\n        sstep E (Run (Call e1 e2) l k)\n                (Run e2 l (fun v => Run (Call e1 (Value v)) l k))\n| SMakeCall : forall fname free arg l k body,\n        nth_error E fname = Some body ->\n        sstep E (Run (Call (Value (Close fname free)) (Value arg)) l k)\n                (Run body (arg :: free) k)\n\n| SElimStepLoop : forall loop cases target l k,\n        ~ is_value loop ->\n        sstep E (Run (Elim loop cases target) l k)\n                (Run loop l (fun v => Run (Elim (Value v) cases target) l k))\n| SElimStep : forall loop cases target l k,\n        is_value loop ->\n        ~ is_value target ->\n        sstep E (Run (Elim loop cases target) l k)\n                (Run target l (fun v => Run (Elim loop cases (Value v)) l k))\n| SEliminate : forall loop cases tag args l k case rec e',\n        is_value loop ->\n        nth_error cases tag = Some (case, rec) ->\n        unroll_elim case args rec (fun x => Call loop x) = Some e' ->\n        sstep E (Run (Elim loop cases (Value (Constr tag args))) l k)\n                (Run e' l k)\n.\n\nDefinition sstar BE := StepLib.sstar (sstep BE).\nDefinition SStarNil := @StepLib.SStarNil state.\nDefinition SStarCons := @StepLib.SStarCons state.\n\nDefinition splus BE := StepLib.splus (sstep BE).\nDefinition SPlusOne := @StepLib.SPlusOne state.\nDefinition SPlusCons := @StepLib.SPlusCons state.\n\n\n\n\n(* Proofs *)\n\n(*\n * Mutual recursion/induction schemes for expr\n *)\n\nDefinition expr_rect_mut\n        (P : expr -> Type)\n        (Pl : list expr -> Type)\n        (Pp : expr * rec_info -> Type)\n        (Plp : list (expr * rec_info) -> Type)\n    (HValue :   forall v, P (Value v))\n    (HArg :     P Arg)\n    (HUpVar :   forall n, P (UpVar n))\n    (HCall :    forall f a, P f -> P a -> P (Call f a))\n    (HConstr :  forall tag args, Pl args -> P (MkConstr tag args))\n    (HElim :    forall loop cases target,\n        P loop -> Plp cases -> P target -> P (Elim loop cases target))\n    (HClose :   forall f free, Pl free -> P (MkClose f free))\n    (HOpaqueOp : forall o args, Pl args -> P (OpaqueOp o args))\n    (Hnil :     Pl [])\n    (Hcons :    forall e es, P e -> Pl es -> Pl (e :: es))\n    (Hpair :    forall e r, P e -> Pp (e, r))\n    (Hnil_p :   Plp [])\n    (Hcons_p :  forall p ps, Pp p -> Plp ps -> Plp (p :: ps))\n    (e : expr) : P e :=\n    let fix go e :=\n        let fix go_list es :=\n            match es as es_ return Pl es_ with\n            | [] => Hnil\n            | e :: es => Hcons e es (go e) (go_list es)\n            end in\n        let go_pair p :=\n            let '(e, r) := p in\n            Hpair e r (go e) in\n        let fix go_pair_list ps :=\n            match ps as ps_ return Plp ps_ with\n            | [] => Hnil_p\n            | p :: ps => Hcons_p p ps (go_pair p) (go_pair_list ps)\n            end in\n        match e as e_ return P e_ with\n        | Value v => HValue v\n        | Arg => HArg\n        | UpVar n => HUpVar n\n        | Call f a => HCall f a (go f) (go a)\n        | MkConstr tag args => HConstr tag args (go_list args)\n        | Elim loop cases target =>\n                HElim loop cases target (go loop) (go_pair_list cases) (go target)\n        | MkClose f free => HClose f free (go_list free)\n        | OpaqueOp o args => HOpaqueOp o args (go_list args)\n        end in go e.\n\nDefinition expr_rect_mut'\n        (P : expr -> Type)\n        (Pl : list expr -> Type)\n        (Pp : expr * rec_info -> Type)\n        (Plp : list (expr * rec_info) -> Type)\n    HValue HArg HUpVar HCall HConstr HElim HClose HOpaqueOp Hnil Hcons Hpair Hnil_p Hcons_p\n    : (forall e, P e) * (forall es, Pl es) * (forall p, Pp p) * (forall ps, Plp ps) :=\n    let go := expr_rect_mut P Pl Pp Plp\n        HValue HArg HUpVar HCall HConstr HElim HClose HOpaqueOp Hnil Hcons Hpair Hnil_p Hcons_p\n    in\n    let fix go_list es :=\n        match es as es_ return Pl es_ with\n        | [] => Hnil\n        | e :: es => Hcons e es (go e) (go_list es)\n        end in\n    let go_pair p :=\n        let '(e, r) := p in\n        Hpair e r (go e) in\n    let fix go_pair_list ps :=\n        match ps as ps_ return Plp ps_ with\n        | [] => Hnil_p\n        | p :: ps => Hcons_p p ps (go_pair p) (go_pair_list ps)\n        end in\n    (go, go_list, go_pair, go_pair_list).\n\n(* Useful wrapper for `expr_rect_mut with (Pl := Forall P)` *)\nDefinition expr_ind' (P : expr -> Prop) (Pp : (expr * rec_info) -> Prop)\n    (HValue :   forall v, P (Value v))\n    (HArg :     P Arg)\n    (HUpVar :   forall n, P (UpVar n))\n    (HCall :    forall f a, P f -> P a -> P (Call f a))\n    (HConstr :  forall c args, Forall P args -> P (MkConstr c args))\n    (HElim :    forall loop cases target,\n        P loop -> Forall Pp cases -> P target -> P (Elim loop cases target))\n    (HClose :   forall f free, Forall P free -> P (MkClose f free))\n    (HOpaqueOp : forall o args, Forall P args -> P (OpaqueOp o args))\n    (Hpair :    forall e r, P e -> Pp (e, r))\n    (e : expr) : P e :=\n    ltac:(refine (@expr_rect_mut P (Forall P) Pp (Forall Pp)\n        HValue HArg HUpVar HCall HConstr HElim HClose HOpaqueOp _ _ Hpair _ _ e); eauto).\n\n(* Useful wrapper for `expr_rect_mut with (Pl := Forall P)` *)\nDefinition expr_ind'' (P : expr -> Prop)\n    (HValue :   forall v, P (Value v))\n    (HArg :     P Arg)\n    (HUpVar :   forall n, P (UpVar n))\n    (HCall :    forall f a, P f -> P a -> P (Call f a))\n    (HConstr :  forall c args, Forall P args -> P (MkConstr c args))\n    (HElim :    forall loop cases target,\n        P loop ->\n        Forall (fun c => P (fst c)) cases ->\n        P target ->\n        P (Elim loop cases target))\n    (HClose :   forall f free, Forall P free -> P (MkClose f free))\n    (HOpaqueOp : forall o args, Forall P args -> P (OpaqueOp o args))\n    (e : expr) : P e :=\n    ltac:(refine (@expr_rect_mut P (Forall P) (fun c => P (fst c)) (Forall (fun c => P (fst c)))\n        HValue HArg HUpVar HCall HConstr HElim HClose HOpaqueOp _ _ _ _ _ e); eauto).\n\n\n(*\n * Misc lemmas\n *)\n\nLemma unroll_elim_length : forall case args rec mk_rec,\n    length args = length rec <-> unroll_elim case args rec mk_rec <> None.\nfirst_induction args; destruct rec; intros; split; simpl;\n  try solve [intro; congruence].\n\n- intro Hlen. simpl. eapply IHargs. congruence.\n- intro Hcall. f_equal. apply <- IHargs. eauto.\nQed.\n\nLemma length_unroll_elim : forall case args rec mk_rec,\n    length args = length rec ->\n    exists e, unroll_elim case args rec mk_rec = Some e.\nfirst_induction args; destruct rec; intros0 Hlen; simpl in Hlen; try discriminate Hlen.\n- eexists. reflexivity.\n- inv Hlen.\n  fwd eapply IHargs; try eassumption.\nQed.\n\n\nRequire oeuf.Semantics.\n\nDefinition prog_type : Type := list expr * list metadata.\nDefinition val_level := VlHigher.\nDefinition valtype := value_type val_level.\n\nDefinition initial_env (prog : prog_type) : env := fst prog.\n\nInductive is_callstate (prog : prog_type) : valtype -> valtype -> state -> Prop :=\n| IsCallstate : forall fname free av body,\n        nth_error (fst prog) fname = Some body ->\n        let fv := Close fname free in\n        HigherValue.public_value (snd prog) fv ->\n        HigherValue.public_value (snd prog) av ->\n        is_callstate prog fv av\n            (Run body (av :: free) Stop).\n\nInductive final_state (prog : prog_type) : state -> valtype -> Prop :=\n| FinalState : forall v,\n        HigherValue.public_value (snd prog) v ->\n        final_state prog (Stop v) v.\n\nDefinition semantics (prog : prog_type) : Semantics.semantics :=\n  @Semantics.Semantics_gen state env val_level\n                 (is_callstate prog)\n                 (sstep)\n                 (final_state prog)\n                 (initial_env prog).\n\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/ElimFunc2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24276019912445274}}
{"text": "Require ClassicalEpsilon.\nRequire Import Reals Psatz.\nFrom stdpp Require Import tactics.\nFrom mathcomp Require Import ssrfun ssreflect eqtype ssrbool seq fintype choice bigop.\nFrom discprob.basic Require Import base sval order monad bigop_ext nify.\nFrom discprob.prob Require Import prob countable finite stochastic_order.\nFrom discprob.monad.idxval Require Import pival_dist pival ival_dist ival ival_pair pidist_singleton idist_pidist_pair extrema.\n\nImport Lub.\n\n(* This is an inductive characterization of eq_ivd_prob, as is proved later *)\nInductive irrel_ivd : ∀ X, ivdist X → ivdist X → Prop :=\n  | irrel_ivd_refl X : ∀ (I: ivdist X), irrel_ivd X I I\n  | irrel_ivd_sym X : ∀ I1 I2, irrel_ivd X I1 I2 → irrel_ivd X I2 I1\n  | irrel_ivd_trans X : ∀ I1 I2 I3, irrel_ivd X I1 I2 → irrel_ivd X I2 I3 → irrel_ivd X I1 I3\n  | irrel_ivd_proper X :\n      ∀ I1 I1' I2 I2', eq_ivd I1 I1' → eq_ivd I2 I2' → irrel_ivd X I1 I2 → irrel_ivd X I1' I2'\n  | irrel_ivd_irrel X : ∀ {Y} I1 (I0: ivdist Y), irrel_ivd X I1 (x ← I0; I1)\n  | irrel_ivd_bind X Y: ∀ (I1 I2: ivdist X) (f1 f2: X → ivdist Y),\n      irrel_ivd X I1 I2 →\n      (∀ x, irrel_ivd Y (f1 x) (f2 x)) →\n      irrel_ivd Y (x ← I1; f1 x) (x ← I2; f2 x).\n\nArguments irrel_ivd {_}.\n\nDefinition le_pidist_irrel :=\n  λ {X : Type} (Is1 Is2 : pidist X), ∀ I : ivdist X, In (I: ival X) Is1 → ∃ I' : ivdist X, irrel_ivd I I' ∧ In (I': ival X) Is2.\n\nLemma le_pidist_irrel_refl {X: Type} (Is1: pidist X):\n  le_pidist_irrel Is1 Is1.\nProof.\n  intros I Hin. exists I; split; eauto. apply irrel_ivd_refl.\nQed.\n\nLemma irrel_ivd_support_coerce {X} (I1 I2: ivdist X) :\n  irrel_ivd I1 I2 →\n  ∀ x, (∃ i2, ind I2 i2 = x ∧ val I2 i2 > 0) ↔ (∃ i1, ind I1 i1 = x ∧ val I1 i1 > 0).\nProof.\n  induction 1.\n  - split; intros; auto.\n  - intros. by rewrite (IHirrel_ivd x).\n  - intros. by rewrite (IHirrel_ivd2 x).\n  - intros.\n    rewrite (eq_ival_support_coerce I1 I1'); eauto.\n    rewrite (eq_ival_support_coerce I2 I2'); eauto.\n  - intros.\n    * split.\n      ** intros ((i0&i1)&Heq&Hgt). exists i1.\n         rewrite //= in Heq Hgt.\n         split; auto. specialize (val_nonneg I0 i0); nra.\n      ** intros (i1&Heq&Hgt).\n         edestruct (ivd_support_idx I0) as (i0&Hgt').\n         exists (existT i0 i1); split => //=; nra.\n  - intros x. split.\n    * intros ((i2&if2)&Hind&Hval).\n      rewrite //= in Hind.\n      edestruct (IHirrel_ivd (ind I2 i2)) as (HI2&_).\n      edestruct (HI2) as (i1&Hindeq&?).\n      { eexists.  split; eauto. rewrite //= in Hval. specialize (val_nonneg (f2 (ind I2 i2)) if2).\n        nra. }\n      edestruct (H1 (ind I2 i2)) as (Hf2&_).\n      edestruct Hf2 as (if1&?&?).\n      { eexists.  split; eauto. rewrite //= in Hval.\n        specialize (val_nonneg I2 i2); nra. }\n      unshelve (eexists).\n      { exists i1. rewrite Hindeq; exact if1.  }\n      split => //=; destruct Hindeq.\n      ** rewrite /eq_rect_r//=.\n      ** rewrite /eq_rect_r//=. nra.\n    * intros ((i2&if2)&Hind&Hval).\n      rewrite //= in Hind.\n      edestruct (IHirrel_ivd (ind I1 i2)) as (_&HI2).\n      edestruct (HI2) as (i1&Hindeq&?).\n      { eexists.  split; eauto. rewrite //= in Hval. specialize (val_nonneg (f1 (ind I1 i2)) if2).\n        nra. }\n      edestruct (H1 (ind I1 i2)) as (_&Hf2).\n      edestruct Hf2 as (if1&?&?).\n      { eexists.  split; eauto. rewrite //= in Hval.\n        specialize (val_nonneg I1 i2); nra. }\n      unshelve (eexists).\n      { exists i1. rewrite Hindeq; exact if1.  }\n      split => //=; destruct Hindeq.\n      ** rewrite /eq_rect_r//=.\n      ** rewrite /eq_rect_r//=. nra.\nQed.\n\nLemma le_pidist_irrel_support_coerce_aux {X} (Is1 Is2: pidist X) :\n  le_pidist_irrel Is2 Is1 →\n  ∀ x, In_psupport x Is2 → In_psupport x Is1.\nProof.\n  intros Hle x (I2&i2&Hin2&?&Hval).\n  destruct (Hle {| ivd_ival := I2; val_sum1 := all_sum1 Is2 _ Hin2|}) as (I1&Heq&Hin1); eauto.\n  exists I1. edestruct (irrel_ivd_support_coerce _ _ Heq) as (i1&?&?).\n  { eauto. }\n  eexists; split; eauto.\nQed.\n\nGlobal Instance irrel_ivd_proper_instance {X} : Proper (@eq_ivd X ==> @eq_ivd X ==> iff) (@irrel_ivd X).\nProof.\n  intros I1 I1' Heq1 I2 I2' Heq2.\n  split; intros; eapply irrel_ivd_proper; eauto; try by symmetry.\nQed.\n\nGlobal Instance irrel_ivd_Transitivite {X}: Transitive (@irrel_ivd X).\nProof. intros ???. apply irrel_ivd_trans. Qed.\nGlobal Instance irrel_ivd_Reflexive {X}: Reflexive (@irrel_ivd X).\nProof. intros ?. apply irrel_ivd_refl. Qed.\nGlobal Instance irrel_ivd_Symmetry {X}: Symmetric (@irrel_ivd X).\nProof. intros ??. apply irrel_ivd_sym. Qed.\n\nLemma is_Ex_ival_irrel_proper_bind {X Y} f (f1 f2: X → ivdist Y) (I1 I2: ivdist X) v\n      (Hirrel_ivd : irrel_ivd I1 I2)\n      (Hall_irrel : ∀ x : X, irrel_ivd (f1 x) (f2 x))\n      (IHinner : ∀ (x : X) (f : Y → R) (v : R), is_Ex_ival f (f1 x) v ↔ is_Ex_ival f (f2 x) v)\n      (IHirrel_ivd : ∀ (f : X → R) (v : R), is_Ex_ival f I1 v ↔ is_Ex_ival f I2 v):\n  is_Ex_ival f (ivd_bind _ _ f1 I1) v → is_Ex_ival f (ivd_bind _ _ f2 I2) v.\nProof.\n  intros His.\n  assert (ex_Ex_ival f (ivd_bind _ _ f1 I1)).\n  { eapply is_Ex_ival_ex; eauto. }\n  rewrite -(is_Ex_ival_unique _ _ _ His).\n  feed pose proof (ex_Ex_ival_bind_post (λ x, Rabs (f x)) I1 f1) as Hex_I1.\n  { eapply ex_Ex_ival_to_Rabs, is_Ex_ival_ex. eauto. }\n  feed pose proof (ex_Ex_ival_bind_post f I1 f1) as Hex_I1'.\n  { eapply is_Ex_ival_ex. eauto. }\n  rewrite Ex_ival_bind_post //=.\n  assert (ex_Ex_ival f (ivd_bind _ _ f2 I2)).\n  {\n    apply ex_Ex_ival_from_Rabs, ex_Ex_ival_bind_post_inv; eauto using Rabs_pos, Rle_ge.\n    ** intros.\n       apply is_Ex_ival_ex, ex_Ex_ival_to_Rabs in His.\n       edestruct (irrel_ivd_support_coerce I1 I2) as (Hlr&Hrl); eauto.\n       edestruct Hlr as (i1&Heqi1&Hvali1); eauto.\n       eapply ex_Ex_ival_bind_inv in His; eauto.\n       eapply ex_Ex_ival_is in His as (v'&His).\n       rewrite -Heqi1.\n       eapply is_Ex_ival_ex. eapply IHinner; eauto.\n    ** apply ex_Ex_ival_is in Hex_I1 as (v'&His').\n       eapply is_Ex_ival_ex; eapply IHirrel_ivd.\n       eapply is_Ex_ival_proper_fun_support; eauto.\n       intros x Hsupport => //=.\n       symmetry.\n       apply is_Ex_ival_unique.\n       eapply IHinner.\n       eapply Ex_ival_correct. eapply (ex_Ex_ival_bind_inv (λ x, Rabs (f x)) f1 I1); eauto.\n       apply ex_Ex_ival_to_Rabs. eapply is_Ex_ival_ex; eauto.\n  }\n  cut (Ex_ival f (ivd_bind _ _ f2 I2) = (Ex_ival (λ x, Ex_ival f (f1 x)) I1)).\n  { intros HEx. rewrite -HEx. apply Ex_ival_correct; eauto. }\n  rewrite Ex_ival_bind_post //=.\n  apply is_Ex_ival_unique.\n  eapply IHirrel_ivd.\n  eapply is_Ex_ival_proper_fun_support; last first.\n  { eapply Ex_ival_correct. eauto. }\n  intros => //=.\n  symmetry.\n  apply is_Ex_ival_unique.\n  eapply IHinner.\n  eapply Ex_ival_correct. eapply (ex_Ex_ival_bind_inv f f1 I1); eauto.\nQed.\n\nLemma is_Ex_ival_irrel_proper {A} f (I I': ivdist A) v :\n  irrel_ivd I I' →\n  is_Ex_ival f I v ↔\n  is_Ex_ival f I' v.\nProof.\n  intros irrel_ivd.\n  revert v.\n  induction irrel_ivd; auto; intros.\n  - symmetry.  eapply IHirrel_ivd.\n  - rewrite IHirrel_ivd1. auto.\n  - rewrite /eq_ivd in H.\n    etransitivity; first etransitivity; try eapply IHirrel_ivd.\n    { split; apply is_Ex_ival_proper; eauto. by symmetry. }\n    { split; apply is_Ex_ival_proper; eauto. by symmetry. }\n  - split. apply is_Ex_ival_bind_irrel, val_sum1.\n    intros His. cut (ex_Ex_ival f I1).\n    { intros Hex. apply Ex_ival_correct in Hex.\n      cut (Ex_ival f I1 = v); intros; subst; eauto.\n      eapply is_Ex_ival_unique'; last eassumption.\n      apply is_Ex_ivd_bind_irrel; eauto.\n    }\n    apply is_Ex_ival_ex in His.\n    unshelve (eapply ex_Ex_ival_bind_inv in His; eauto).\n    { exact (sval (ivd_support_idx I0)). }\n    destruct (ivd_support_idx _) => //=.\n  - split; eapply is_Ex_ival_irrel_proper_bind; eauto; try (intros; by symmetry).\nQed.\n\nLemma ex_Ex_ival_irrel_proper {A} f (I I': ivdist A) :\n  irrel_ivd I I' →\n  ex_Ex_ival f I →\n  ex_Ex_ival f I'.\nProof.\n  intros Hirrel (v&His)%ex_Ex_ival_is.\n  eapply is_Ex_ival_ex.\n  eapply is_Ex_ival_irrel_proper; eauto.\n    by symmetry.\nQed.\n\n\nLemma Ex_ival_irrel_proper {A} f (I I': ivdist A) :\n  irrel_ivd I I' →\n  ex_Ex_ival f I →\n  Ex_ival f I = Ex_ival f I'.\nProof.\n  intros. symmetry. apply is_Ex_ival_unique.\n  eapply is_Ex_ival_irrel_proper; eauto.\n  * symmetry. eauto.\n  * apply Ex_ival_correct; eauto.\nQed.\n\nLemma irrel_ivd_to_eq_ivd_prob {X} (I1 I2: ivdist X):\n  irrel_ivd I1 I2 →\n  eq_ivd_prob I1 I2.\nProof.\n  intros Hirrel.\n  apply eq_ivd_prob_alt.\n  intros x.\n  transitivity ((Pr (λ v, v = x) I1)).\n  { rewrite /Ex_ival/idx_eq_ind//=. eapply SeriesC_ext; intros.\n    destruct ClassicalEpsilon.excluded_middle_informative => //=; nra.\n  }\n  transitivity ((Pr (λ v, v = x) I2)); last first.\n  { rewrite /Ex_ival/idx_eq_ind//=. eapply SeriesC_ext; intros.\n    destruct ClassicalEpsilon.excluded_middle_informative => //=; nra.\n  }\n  apply Ex_ival_irrel_proper; eauto.\n  apply ex_Pr.\nQed.\n\nLemma In_isupport_pr_gt_0 {X: Type} (I: ivdist X) (x: X):\n  In_isupport x I →\n  0 < Pr (eq ^~ x) I.\nProof.\n  rewrite /Pr/Ex_ival => Hin.\n  destruct Hin as (i&?&?).\n  eapply (Series_strict_pos _ (pickle i)).\n  { intros.  rewrite /countable_sum/oapp.\n    destruct pickle_inv; try nra.\n    destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra.\n    rewrite Rmult_1_l. apply val_nonneg.\n  }\n  { intros.  rewrite /countable_sum/oapp.\n    rewrite pickleK_inv.\n    destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra.\n  }\n  feed pose proof (ex_Pr (eq^~ x) I).\n  apply ex_Ex_ival_is in H1 as (v&?).\n  rewrite /is_Ex_ival in H1.\n  destruct H1 as (Hex&His).\n  eexists. eauto.\nQed.\n\nLemma pr_gt_0_In_isupport {X: Type} (I: ivdist X) (x: X):\n  0 < Pr (eq ^~ x) I →\n  In_isupport x I.\nProof.\n  rewrite /Pr/Ex_ival => Hin.\n  eapply (Series_strict_pos_inv) in Hin as (n&?).\n  {\n   destruct (@pickle_inv (idx I) n) as [i|] eqn:Heq.\n   - exists i. rewrite  //=/countable_sum//= Heq //= in H.\n    destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra.\n    * rewrite //= in H. split; eauto. nra.\n    * rewrite //= in H. nra.\n   - rewrite //=/countable_sum//= Heq //= in H ; nra.\n  }\n  intros n. rewrite /countable_sum. destruct pickle_inv => //=; last nra.\n    destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra.\n    rewrite Rmult_1_l. apply val_nonneg.\nQed.\n\n(* This is a kind of conditional distribution *)\nLemma ival_slice_proof1 (X : Type) (I : ivdist X) (x : X):\n  ∀ i : idx I, (if ClassicalEpsilon.excluded_middle_informative (In_isupport x I)\n                then\n                 (if ClassicalEpsilon.excluded_middle_informative (ind I i = x) then val I i else 0) /\n                 Pr (eq^~ x) I\n                else val I i) ≥ 0.\nProof.\n  intros i.\n  destruct ClassicalEpsilon.excluded_middle_informative; eauto; last apply val_nonneg.\n  apply Rle_ge, Rdiv_le_0_compat.\n  { destruct ClassicalEpsilon.excluded_middle_informative => //=; eauto; try nra.\n    apply Rge_le, val_nonneg. }\n  { apply In_isupport_pr_gt_0; eauto. }\nQed.\n\nDefinition ival_slice {X} (I: ivdist X) (x: X) : ival X.\n  refine {| idx := idx I;\n            ind := ind I;\n            val := λ i,\n                   if ClassicalEpsilon.excluded_middle_informative (In_isupport x I) then\n                   (if ClassicalEpsilon.excluded_middle_informative (ind I i = x) then\n                          val I i\n                        else\n                          0) / Pr (λ i, i = x) I\n                   else\n                     val I i|}.\n  apply ival_slice_proof1.\nDefined.\n\nLemma ival_slice_proof2 (X : Type) (I : ivdist X) (x : X):\n  is_series (countable_sum (val (ival_slice I x))) 1.\nProof.\n  rewrite //=. destruct ClassicalEpsilon.excluded_middle_informative; last apply val_sum1.\n  replace 1 with (Pr (eq^~ x) I */ Pr (eq^~ x) I); last first.\n  { field. apply Rgt_not_eq, In_isupport_pr_gt_0; auto. }\n  apply is_seriesC_scal_r.\n  rewrite /Pr/Ex_ival.\n  apply (is_seriesC_ext _ (λ i0 : idx I, (if is_left (ClassicalEpsilon.excluded_middle_informative (ind I i0 = x))\n                          then 1\n                          else 0) * val I i0)).\n  { intros.  destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra. }\n\n  {\n  feed pose proof (ex_Pr (eq^~ x) I) as Hpr.\n  apply ex_Ex_ival_is in Hpr as (v&Hpr).\n  rewrite /is_Ex_ival in Hpr.\n  destruct Hpr as (Hex&His).\n  eapply Series_correct; eexists; eauto. }\nQed.\n\n\nDefinition ivdist_slice {X} (I: ivdist X) (x: X) : ivdist X.\nProof.\n  exists (ival_slice I x).\n  apply ival_slice_proof2.\nDefined.\n\nLemma eq_ivd_prob_Pr_eq {X} (I1 I2: ivdist X) x:\n  eq_ivd_prob I1 I2 →\n  Pr (eq^~ x) I1 = Pr (eq^~ x) I2.\nProof.\n  rewrite /Pr/Ex_ival => Heq.\n  unshelve (eapply eq_ivd_prob_alt in Heq); first exact x.\n  rewrite /idx_eq_ind in Heq.\n  setoid_rewrite Rmult_if_distrib.\n  setoid_rewrite Rmult_0_l.\n  setoid_rewrite Rmult_1_l.\n  eauto.\nQed.\n\nLemma eq_ivd_prob_In_isupport {X: Type} I1 I2 (x: X):\n  eq_ivd_prob I1 I2 →\n  In_isupport x I1 →\n  In_isupport x I2.\nProof.\n  intros Heq Hin%In_isupport_pr_gt_0.\n  apply pr_gt_0_In_isupport.\n  erewrite <-eq_ivd_prob_Pr_eq; last eassumption.\n  eauto.\nQed.\n\nLemma eq_ivd_prob_to_irrel_ivd {X} (I1 I2: ivdist X):\n  eq_ivd_prob I1 I2 →\n  irrel_ivd I1 I2.\nProof.\n  intros Heq.\n  transitivity (x ← I1; _ ← ivdist_slice I2 x; mret x).\n  { transitivity (x ← I1; mret x).\n    { rewrite ivd_right_id. reflexivity. }\n    apply irrel_ivd_bind; first reflexivity.\n    intros x. apply irrel_ivd_irrel.\n  }\n  transitivity (x ← I2; _ ← ivdist_slice I1 x; mret x); last first.\n  { symmetry.\n    transitivity (x ← I2; mret x).\n    { rewrite ivd_right_id. reflexivity. }\n    apply irrel_ivd_bind; first reflexivity.\n    intros x. apply irrel_ivd_irrel.\n  }\n  cut (eq_ivd (I1 ≫= (λ x : X, ivdist_slice I2 x ≫= (λ _ : X, mret x)))\n    (I2 ≫= (λ x : X, ivdist_slice I1 x ≫= (λ _ : X, mret x)))).\n  { intros ->.  reflexivity. }\n\n  apply eq_ival_nondep_inj_surj_suffice.\n  apply eq_ival_nondep_inj_surj'_helper.\n  unshelve eexists.\n  { intros (i1&i2&?). exists i2. exists i1. exact tt. }\n  rewrite //=.\n  split_and!.\n  * intros (i1&i2&[]) (i1'&i2'&[]) _ _ => //=.\n    inversion 1; subst. auto.\n  * intros (i2&i1&[]).\n    unshelve (eexists).\n    { exists i1.  exists i2. exact tt. }\n    split_and!; eauto => //=.\n    repeat  destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra; try congruence.\n    ** intros Hgt. eapply Rge_gt_trans; last  eassumption.\n       right. rewrite //=.\n       cut (Pr (eq^~ (ind I2 i2)) I1 = Pr (eq^~ (ind I1 i1)) I2).\n       { intros ->.  nra. }\n       rewrite e0; eapply eq_ivd_prob_Pr_eq; eauto.\n    ** intros; exfalso. eapply n. rewrite e.\n       eapply eq_ivd_prob_In_isupport; eauto.\n    ** intros; exfalso. eapply n. rewrite e.\n       eapply eq_ivd_prob_In_isupport; eauto.\n       by symmetry.\n    ** cut (val I2 i2 = 0).\n       { intros ->. nra. }\n       destruct (val_nonneg I2 i2); last auto.\n       exfalso. eapply n.\n       eapply eq_ivd_prob_In_isupport; eauto.\n       { by symmetry. }\n       eexists; eauto.\n  * intros (i1&i2&[]) => //=.\n    repeat  destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra; try congruence.\n    cut (val I1 i1 = 0).\n    { intros ->.  nra. }\n    destruct (val_nonneg I1 i1); last auto.\n    exfalso. eapply n.\n    eapply eq_ivd_prob_In_isupport; eauto.\n    eexists; eauto.\n  * intros (i1&i2&[]) => //=.\n    repeat  destruct ClassicalEpsilon.excluded_middle_informative => //=; try nra; try congruence.\n    ** intros Hgt.\n       cut (Pr (eq^~ (ind I2 i2)) I1 = Pr (eq^~ (ind I1 i1)) I2).\n       { intros ->.  nra. }\n       rewrite e0; eapply eq_ivd_prob_Pr_eq; eauto.\n    ** intros; exfalso. eapply n. rewrite e.\n       eapply eq_ivd_prob_In_isupport; eauto.\n       by symmetry.\n    ** intros; exfalso. eapply n. rewrite e.\n       eapply eq_ivd_prob_In_isupport; eauto.\n    ** cut (val I1 i1 = 0).\n       { intros ->. nra. }\n       destruct (val_nonneg I1 i1); last auto.\n       exfalso. eapply n.\n       eapply eq_ivd_prob_In_isupport; eauto.\n       eexists; eauto.\nQed.\n\nLemma irrel_ivd_choice {X} (I1 I1' I2 I2': ivdist X) p Hpf Hpf':\n      irrel_ivd I1 I2 →\n      irrel_ivd I1' I2' →\n      irrel_ivd (ivdplus p Hpf I1 I1') (ivdplus p Hpf' I2 I2').\nProof.\n  intros Hirrel1 Hirrel2.\n  transitivity (b ← ivdplus p Hpf (mret true) (mret false);\n                if (b: bool) then I1 else I1').\n  { rewrite ivd_plus_bind ?ivd_left_id. reflexivity. }\n  transitivity (b ← ivdplus p Hpf' (mret true) (mret false);\n                if (b: bool) then I2 else I2'); last first.\n  { rewrite ivd_plus_bind ?ivd_left_id. reflexivity. }\n  apply irrel_ivd_bind.\n  { cut (eq_ivd (ivdplus p Hpf (mret true) (mret false)) (ivdplus p Hpf' (mret true) (mret false))).\n    { intros ->; reflexivity. }\n    apply ivdist_plus_proper; reflexivity.\n  }\n  intros [|]; eauto.\nQed.\n\nDefinition irrel_pidist {X: Type} (Is1 Is2: pidist X) :=\n  ∀ f, bounded_fun f → Rbar_le (Ex_min f Is2) (Ex_min f Is1).\n\nLemma irrel_pidist_Ex_max {X: Type} (Is1 Is2: pidist X) :\n    irrel_pidist Is1 Is2 → ∀ f, bounded_fun f → Rbar_le (Ex_max f Is1) (Ex_max f Is2).\nProof.\n  intros Hirrel f Hb.\n  rewrite ?Ex_max_neg_min.\n  apply Rbar_opp_le.\n  apply Hirrel.\n  destruct Hb as (c&?).\n  exists c => x. rewrite Rabs_Ropp; eauto.\nQed.\n\nLemma Ex_max_irrel_pidist {X: Type} (Is1 Is2: pidist X) :\n  (∀ f, bounded_fun f → Rbar_le (Ex_max f Is1) (Ex_max f Is2)) →\n  irrel_pidist Is1 Is2.\nProof.\n  intros Hirrel f Hb.\n  specialize (Hirrel (λ x, (- f x))).\n  rewrite ?Ex_max_neg_min in Hirrel.\n  apply Rbar_opp_le.\n  setoid_rewrite Ropp_involutive in Hirrel.\n  eapply Hirrel. destruct Hb as (c&?). exists c.\n  intros x. rewrite Rabs_Ropp; eauto.\nQed.\n\nLemma irrel_pidist_refl {X} : ∀ I, @irrel_pidist X I I.\nProof. intros f Hb; reflexivity. Qed.\n\nLemma irrel_pidist_trans {X} :\n   ∀ I1 I2 I3, @irrel_pidist X I1 I2 → @irrel_pidist X I2 I3 → @irrel_pidist X I1 I3.\nProof.\n  intros I1 I2 I3 Hi1 Hi2 f Hb.\n  specialize (Hi1 f Hb).\n  specialize (Hi2 f Hb).\n  etransitivity; eauto.\nQed.\n\nLemma bounded_supp_fun_le_pidist {A} f (Is Is': pidist A):\n  le_pidist Is Is' →\n  bounded_fun_on f (λ x, In_psupport x Is') →\n  bounded_fun_on f (λ x, In_psupport x Is).\nProof.\n  intros Hle Hbf.\n  eapply bounded_fun_on_anti; try eassumption.\n  intros a. eapply le_pidist_support_coerce_aux; eauto.\nQed.\n\nLemma Ex_min_le_pidist_irrel {X} (f: X → R) Is1 Is2:\n  le_pidist_irrel Is1 Is2 →\n  Rbar_le (Ex_min f Is2) (Ex_min f Is1).\nProof.\n  intros Hle.\n  rewrite /Ex_min.\n  destruct (Glb_Rbar_correct (Ex_pidist f Is1)) as (Hlb&Hglb).\n  apply Hglb. intros r Hex. destruct Hex as (I&Hin&Hex).\n  edestruct (Hle {| ivd_ival := I; val_sum1 := all_sum1 Is1 _ Hin |}) as (I2&Heq&Hin2).\n  { rewrite //=. }\n  { eapply (is_Ex_ival_irrel_proper f) in Heq; last eauto.\n    destruct (Glb_Rbar_correct (Ex_pidist f Is2)) as (Hlb2&Hglb2).\n    eapply Hlb2. eexists; split; eauto.\n    eapply Heq => //=.\n  }\nQed.\n\nLemma Ex_max_le_pidist_irrel {X} (f: X → R) Is1 Is2:\n  le_pidist_irrel Is1 Is2 →\n  Rbar_le (Ex_max f Is1) (Ex_max f Is2).\nProof.\n  rewrite ?Ex_max_neg_min.\n  intros Hle.\n  apply Rbar_opp_le.\n  apply Ex_min_le_pidist_irrel; eauto.\nQed.\n\nLemma irrel_pidist_proper_irrel {X} :\n  ∀ I1 I1' I2 I2', le_pidist_irrel I1' I1 → le_pidist_irrel I2 I2' →\n                   @irrel_pidist X I1 I2 → @irrel_pidist X I1' I2'.\nProof.\n  intros I1 I1' I2 I2' Hle1 Hle2 Hirrel12.\n  intros f Hb.\n  etransitivity.\n  { apply Ex_min_le_pidist_irrel; eauto. }\n  etransitivity.\n  { eapply Hirrel12; eauto. }\n  { apply Ex_min_le_pidist_irrel; eauto. }\nQed.\n\nLemma irrel_pidist_bind1 {X Y}: ∀ (I1 I2: pidist X) (f: X → pidist Y),\n      @irrel_pidist X I1 I2 →\n      @irrel_pidist Y (x ← I1; f x) (x ← I2; f x).\nProof.\n  intros I1 I2 f Hirrel.\n  intros g Hb.\n  rewrite ?Ex_min_bind_post;\n    eauto using Ex_min_bounded_is_bounded, ex_Ex_extrema_bounded_fun,\n    Ex_min_bounded_fun_finite.\nQed.\n\nLemma irrel_pidist_bind {X Y}: ∀ (I1 I2: pidist X) (f1 f2: X → pidist Y),\n      @irrel_pidist X I1 I2 →\n      (∀ x, @irrel_pidist Y (f1 x) (f2 x)) →\n      @irrel_pidist Y (x ← I1; f1 x) (x ← I2; f2 x).\nProof.\n  intros I1 I2 f1 f2 Hirrel Hirrelfun.\n  eapply irrel_pidist_trans.\n  { eapply irrel_pidist_bind1; eauto. }\n  intros f Hb. eapply Ex_min_bind_le;\n    eauto using Ex_min_bounded_is_bounded, ex_Ex_extrema_bounded_fun,\n    Ex_min_bounded_fun_finite.\n  intros a ?. eapply Hirrelfun; eauto.\nQed.\n\nLemma irrel_pidist_proper X :\n  ∀ (I1 I1' I2 I2': pidist X), le_pidist I1' I1 → le_pidist I2 I2'\n                               → irrel_pidist I1 I2 → irrel_pidist I1' I2'.\nProof.\n  intros ???? Hle1 Hle2. eapply irrel_pidist_proper_irrel.\n  { intros x Hin. edestruct (Hle1 x) as (x'&Heq&Hin'); eauto.\n    exists {| ivd_ival := x'; val_sum1 := all_sum1 I1 _ Hin'|}; split; auto.\n    eapply irrel_ivd_proper; eauto; last apply irrel_ivd_refl.\n    reflexivity.\n  }\n  { intros x Hin. edestruct (Hle2 x) as (x'&Heq&Hin'); eauto.\n    exists {| ivd_ival := x'; val_sum1 := all_sum1 I2' _ Hin'|}; split; auto.\n    eapply irrel_ivd_proper; eauto; last apply irrel_ivd_refl.\n    reflexivity.\n  }\nQed.\n\nGlobal Instance irrel_pidist_mono_instance {X} : Proper (@le_pidist X --> @le_pidist X ==> Coq.Program.Basics.impl) (@irrel_pidist X).\nProof.\n  intros I1 I1' Heq1 I2 I2' Heq2.\n  intros Hirrel. eapply irrel_pidist_proper; eauto.\nQed.\n\nGlobal Instance irrel_pidist_proper_instance {X} : Proper (@eq_pidist X ==> @eq_pidist X ==> iff) (@irrel_pidist X).\nProof.\n  intros I1 I1' Heq1 I2 I2' Heq2.\n  split; intros Hirrel; eapply irrel_pidist_proper; eauto;\n    try (setoid_rewrite Heq1; reflexivity);\n    try (setoid_rewrite Heq2; reflexivity).\nQed.\n\nGlobal Instance irrel_pidist_Transitivite {X}: Transitive (@irrel_pidist X).\nProof. intros ???. apply irrel_pidist_trans. Qed.\nGlobal Instance irrel_pidist_Reflexive {X}: Reflexive (@irrel_pidist X).\nProof. intros ?. apply irrel_pidist_refl. Qed.\n\n\n\nRecord irrel_couplingP {A1 A2} (I1: ivdist A1) (Is2: pidist A2) (P: A1 → A2 → Prop) : Type :=\n  { irrel_I : ivdist A1;\n    irrel_Is : pidist A2;\n    irrel_rel_I : irrel_ivd I1 irrel_I;\n    irrel_rel_Is : irrel_pidist irrel_Is Is2;\n    irrel_couple_wit :> idist_pidist_couplingP irrel_I irrel_Is P\n  }.\n\nDefinition lsupport {A1 A2 Is1 Is2 P} (Icouple: irrel_couplingP Is1 Is2 P) (y: A2) :=\n  { x : A1 |  ∃ i Hpf, ival.ind Icouple i = (exist _ (x, y) Hpf) ∧ ival.val Icouple i > 0 }.\nDefinition rsupport {A1 A2 Is1 Is2 P} (Icouple: irrel_couplingP Is1 Is2 P) (x: A1) :=\n  { y : A2 |  ∃ i Hpf, ival.ind Icouple i = (exist _ (x, y) Hpf) ∧ ival.val Icouple i > 0 }.\n\n\nDefinition irrel_coupling_propP {A1 A2} (I1: ivdist A1) (Is2: pidist A2) P : Prop :=\n  ∃ (ic: irrel_couplingP I1 Is2 P), True.\n\nLemma ic_wit_to_prop {A1 A2} (I1 : ivdist A1) (Is2: pidist A2) P :\n  irrel_couplingP I1 Is2 P →\n  irrel_coupling_propP I1 Is2 P.\nProof.\n  intros; eexists; eauto.\nQed.\n\nLemma ic_prop_to_wit {A1 A2} (I1 : ivdist A1) (Is2: pidist A2) P :\n  irrel_coupling_propP I1 Is2 P →\n  irrel_couplingP I1 Is2 P.\nProof.\n  intros (?&_)%ClassicalEpsilon.constructive_indefinite_description; auto.\nQed.\n\nLemma irrel_pidist_support_coerce {X} (I1 I2: pidist X) :\n  irrel_pidist I2 I1 →\n  ∀ x, In_psupport x I2 → In_psupport x I1.\nProof.\n  intros Hirrel x Hin.\n  destruct Hin as (I&i&Hin&Hind&Hval).\n  assert (0 < Pr (eq ^~ x) {| ivd_ival := I; val_sum1 := all_sum1 _ _ Hin|}).\n  {  eapply In_isupport_pr_gt_0.\n     eexists; eauto. }\n  assert (Rbar_lt 0 (Pr_max (eq^~ x) I1)) as Hmax.\n  {\n    apply (Rbar_lt_le_trans _ (Pr_max (eq^~ x) I2)); last first.\n    { eapply irrel_pidist_Ex_max; eauto.\n      exists 1. intros. destruct (is_left); rewrite Rabs_right; nra.\n    }\n    apply (Rbar_lt_le_trans _ (Pr (eq^~ x) {| ivd_ival := I; val_sum1 := all_sum1 I2 I Hin |}));\n      first done.\n    apply Ex_max_spec1' => //=.\n    eapply (ex_Pr (eq^~x) {| ivd_ival := I; val_sum1 := all_sum1 I2 I Hin |}).\n  }\n  assert (∃ I' : ivdist X, In (I': ival X) I1 ∧ 0 < Pr (eq^~x) I') as (I'&Hin'&Hpr').\n  {\n    apply Classical_Pred_Type.not_all_not_ex. intros Hneg.\n    apply Rbar_lt_not_le in Hmax. apply Hmax.\n    apply Ex_max_spec2.\n    intros r' (I'&Hin'&Heq).\n    apply Rbar_not_lt_le. intros Hlt.\n    exfalso; eapply (Hneg {| ivd_ival := I'; val_sum1 := all_sum1 _ _ Hin'|}).\n    split; first done.\n    rewrite /Pr. erewrite is_Ex_ival_unique; last eassumption.\n    auto.\n  }\n  exists I'. apply pr_gt_0_In_isupport in Hpr'.\n  destruct Hpr' as (?&?&?). eexists; split_and!; eauto.\nQed.\n\nLemma irrel_pidist_choice {X} (I1 I1' I2 I2': pidist X) p Hpf Hpf':\n      irrel_pidist I1 I2 →\n      irrel_pidist I1' I2' →\n      irrel_pidist (pidist_plus p Hpf I1 I1') (pidist_plus p Hpf' I2 I2').\nProof.\n  intros Hirrel1 Hirrel2.\n  transitivity (b ← pidist_plus p Hpf (mret true) (mret false);\n                if (b: bool) then I1 else I1').\n  { rewrite pidist_plus_bind ?pidist_left_id. reflexivity. }\n  transitivity (b ← pidist_plus p Hpf' (mret true) (mret false);\n                if (b: bool) then I2 else I2'); last first.\n  { rewrite pidist_plus_bind ?pidist_left_id. reflexivity. }\n  apply irrel_pidist_bind.\n  { cut (eq_pidist (pidist_plus p Hpf (mret true) (mret false))\n                   (pidist_plus p Hpf' (mret true) (mret false))).\n    { intros ->; reflexivity. }\n    apply pidist_plus_proper; reflexivity.\n  }\n  intros [|]; eauto.\nQed.\n\nLemma irrel_pidist_irrel {X Y}: ∀ I1 (I0: pidist Y), @irrel_pidist X (x ← I0; I1) I1.\nProof.\n  intros. intros f Hbounded.\n  rewrite Ex_min_bind_irrel //=; try reflexivity;\n    eauto using Ex_min_bounded_is_bounded, ex_Ex_extrema_bounded_fun,\n    Ex_min_bounded_fun_finite.\nQed.\n\nLemma irrel_coupling_proper {A1 A2} (I1 I2 : ivdist A1) (Is1 Is2: pidist A2) P:\n  eq_ivd I1 I2 →\n  eq_pidist Is1 Is2 →\n  irrel_couplingP I1 Is1 P →\n  irrel_couplingP I2 Is2 P.\nProof.\n  intros HeqI HeqIs [I1' Is1' HeqI1 HeqIs1 Hcouple].\n  exists I1' Is1'.\n  - setoid_rewrite <-HeqI. done.\n  - setoid_rewrite <-HeqIs. done.\n  - done.\nQed.\n\nLemma irrel_coupling_mono {A1 A2} (I1 I2 : ivdist A1) (Is1 Is2: pidist A2) P:\n  eq_ivd I1 I2 →\n  le_pidist Is1 Is2 →\n  irrel_couplingP I1 Is1 P →\n  irrel_couplingP I2 Is2 P.\nProof.\n  intros HeqI HeqIs [I1' Is1' HeqI1 HeqIs1 Hcouple].\n  exists I1' Is1'.\n  - setoid_rewrite <-HeqI. done.\n  - setoid_rewrite <-HeqIs. done.\n  - done.\nQed.\n\nLemma irrel_coupling_mono_irrel {A1 A2} (I1 I2 : ivdist A1) (Is1 Is2: pidist A2) P:\n  eq_ivd I1 I2 →\n  irrel_pidist Is1 Is2 →\n  irrel_couplingP I1 Is1 P →\n  irrel_couplingP I2 Is2 P.\nProof.\n  intros HeqI HeqIs [I1' Is1' HeqI1 HeqIs1 Hcouple].\n  exists I1' Is1'.\n  - setoid_rewrite <-HeqI. done.\n  - setoid_rewrite <-HeqIs. done.\n  - done.\nQed.\n\nLemma irrel_coupling_mono_irrel' {A1 A2} (I1 I2 : ivdist A1) (Is1 Is2: pidist A2) P:\n  irrel_ivd I1 I2 →\n  irrel_pidist Is1 Is2 →\n  irrel_couplingP I1 Is1 P →\n  irrel_couplingP I2 Is2 P.\nProof.\n  intros HeqI HeqIs [I1' Is1' HeqI1 HeqIs1 Hcouple].\n  exists I1' Is1'.\n  - setoid_rewrite <-HeqI. done.\n  - setoid_rewrite <-HeqIs. done.\n  - done.\nQed.\n\nGlobal Instance irrel_coupling_prop_Proper {A1 A2}:\n  Proper (@eq_ivd A1 ==> @le_pidist A2 ==> eq ==> impl) irrel_coupling_propP.\nProof.\n  intros ?? Heq ?? Hle ?? ->.\n  intros H%ic_prop_to_wit.\n  apply ic_wit_to_prop.\n  eapply irrel_coupling_mono; eauto.\nQed.\n\nGlobal Instance irrel_coupling_prop_irrel_Proper {A1 A2}:\n  Proper (@eq_ivd A1 ==> @irrel_pidist A2 ==> eq ==> impl) irrel_coupling_propP.\nProof.\n  intros ?? Heq ?? Hle ?? ->.\n  intros H%ic_prop_to_wit.\n  apply ic_wit_to_prop.\n  eapply irrel_coupling_mono_irrel; eauto.\nQed.\n\nLemma irrel_coupling_mret {A1 A2} (P: A1 → A2 → Prop) x y:\n  P x y →\n  irrel_couplingP (mret x) (mret y) P.\nProof.\n  intros HP. exists (mret x) (mret y); try reflexivity.\n  by apply ip_coupling_mret.\nQed.\n\nLemma irrel_coupling_prop_mret {A1 A2} (P: A1 → A2 → Prop) x y:\n  P x y →\n  irrel_coupling_propP (mret x) (mret y) P.\nProof.\n  intros; apply ic_wit_to_prop, irrel_coupling_mret; auto.\nQed.\n\nLemma irrel_coupling_bind {A1 A2 B1 B2} P (f1: A1 → ivdist B1) (f2: A2 → pidist B2)\n      I1 Is2 Q (Ic: irrel_couplingP I1 Is2 P):\n  (∀ x y, P x y → irrel_couplingP (f1 x) (f2 y) Q) →\n  irrel_couplingP (mbind f1 I1) (mbind f2 Is2) Q.\nProof.\n  intros Hfc.\n  destruct Ic as [I1' Is2' HeqI HeqIs Hcouple].\n  destruct Hcouple as [I2' ? [Ic ? ?]%ic_coupling_to_id].\n  unshelve (eexists).\n  - refine (xy ← Ic; _).\n     destruct xy as ((x&y)&HP).\n     destruct (Hfc _ _ HP).\n     exact irrel_I0.\n  - refine (xy ← singleton Ic; _).\n    destruct xy as ((x&y)&HP).\n    destruct (Hfc x y HP).\n    exact irrel_Is0.\n  - etransitivity.\n    { eapply irrel_ivd_bind.  eauto. reflexivity. }\n    etransitivity.\n    { eapply irrel_ivd_bind. setoid_rewrite idc_proj1. reflexivity. reflexivity.  }\n    setoid_rewrite ivd_assoc. eapply irrel_ivd_bind; first reflexivity.\n    intros ((x&y)&HP).\n    destruct (Hfc _ _ _) as [? ? ?]. rewrite /irrel_I.\n    rewrite /sval.  setoid_rewrite ivd_left_id. done.\n  - etransitivity; last first.\n    { eapply irrel_pidist_bind.\n      - etransitivity; last by eauto. eapply irrel_pidist_proper; first by eauto.\n        reflexivity. reflexivity.\n      - intros; reflexivity.\n    }\n    setoid_rewrite idc_proj2. setoid_rewrite singleton_bind.\n    setoid_rewrite pidist_assoc.\n    eapply irrel_pidist_bind; first reflexivity.\n    intros ((x&y)&HP).\n    destruct (Hfc _ _ _) as [? ? ?]. rewrite /irrel_I.\n    rewrite /sval. setoid_rewrite singleton_mret. setoid_rewrite pidist_left_id.\n    eauto.\n  - eapply (ip_coupling_bind _ _ _ _ (λ x y, x = y)).\n    * apply ip_coupling_singleton.\n    * intros ((?&?)&HP1) ((x&y)&HP2).\n      inversion 1; subst.\n      rewrite //=.\n      assert (HP1 = HP2). { apply classical_proof_irrelevance. }\n      subst.\n      destruct (Hfc x y HP2). eauto.\nQed.\n\nLemma irrel_coupling_prop_bind {A1 A2 B1 B2} P (f1: A1 → ivdist B1) (f2: A2 → pidist B2)\n      I1 Is2 Q (Ic: irrel_coupling_propP I1 Is2 P):\n  (∀ x y, P x y → irrel_coupling_propP (f1 x) (f2 y) Q) →\n  irrel_coupling_propP (mbind f1 I1) (mbind f2 Is2) Q.\nProof.\n  intros; eapply ic_wit_to_prop, irrel_coupling_bind; intros; apply ic_prop_to_wit; eauto.\nQed.\n\nLemma irrel_coupling_trivial {A1 A2} (I: ivdist A1) (Is: pidist A2):\n  irrel_couplingP I Is (λ x y, True).\nProof.\n  assert ({ I' : ivdist A2 | In (I': ival A2) Is}) as (I'&Hin).\n  { destruct Is as [(Is&Hne) Hall] => //=.\n    rewrite //= in Hall.\n    apply ClassicalEpsilon.constructive_indefinite_description in Hne as (I'&His).\n    exists {| ivd_ival := I'; val_sum1 := Hall _ His |}.\n    auto.\n  }\n  exists (x ← I'; I) (singleton (x ← I; I')).\n  { eapply irrel_ivd_irrel. }\n  { eapply irrel_pidist_proper_irrel; [| apply le_pidist_irrel_refl | reflexivity ].\n    intros I0 Hin'. inversion Hin' as [Heq].\n    exists I'; split; auto.\n    eapply (irrel_ivd_proper _ (x ← I; I')).\n    { rewrite /eq_ivd. rewrite -Heq //=. }\n    { reflexivity. }\n    symmetry. apply irrel_ivd_irrel.\n  }\n  exists (x ← I; I').\n  { intros ?. eapply In_pidist_le_singleton. eexists; split; first reflexivity.\n    rewrite /In/singleton//=. }\n  unshelve (eexists).\n  { refine (ivd_ival (x ← I; y ← I'; mret _)).\n    exists (x, y); done. }\n  - setoid_rewrite ival_bind_comm. setoid_rewrite ival_assoc.\n    eapply ival_bind_congr; first reflexivity.\n    intros.  setoid_rewrite ival_bind_mret_mret. setoid_rewrite ival_right_id. reflexivity.\n  - setoid_rewrite ival_assoc.\n    eapply ival_bind_congr; first reflexivity.\n    intros.  setoid_rewrite ival_bind_mret_mret. setoid_rewrite ival_right_id. reflexivity.\nQed.\n\nLemma irrel_coupling_prop_trivial {A1 A2} (I: ivdist A1) (Is: pidist A2):\n  irrel_coupling_propP I Is (λ x y, True).\nProof.\n  apply ic_wit_to_prop, irrel_coupling_trivial.\nQed.\n\nLemma irrel_coupling_conseq {A1 A2} (P1 P2: A1 → A2 → Prop) (I: ivdist A1) (Is: pidist A2):\n  (∀ x y, P1 x y → P2 x y) →\n  irrel_couplingP I Is P1 →\n  irrel_couplingP I Is P2.\nProof.\n  intros HP Hirrel.\n  destruct Hirrel as [I0 Is0 ? ? ?].\n  exists I0 Is0; auto.\n  eapply ip_coupling_conseq; eauto.\nQed.\n\nLemma irrel_coupling_plus {A1 A2} p Hpf p' Hpf'\n      (P : A1 → A2 → Prop) (Is1 Is1': ivdist A1) (Is2 Is2': pidist A2) :\n  p = p' →\n  irrel_couplingP Is1 Is2 P →\n  irrel_couplingP Is1' Is2' P →\n  irrel_couplingP (ivdplus p Hpf Is1 Is1') (pidist_plus p' Hpf' Is2 Is2') P.\nProof.\n  intros Hpeq Hic Hic'. subst.\n  destruct Hic as [I1i Is2i Hirrel1i Hirrel2i Hwit].\n  destruct Hic' as [I1i' Is2i' Hirrel1i' Hirrel2i' Hwit'].\n  exists (ivdplus p' Hpf I1i I1i') (pidist_plus p' Hpf' Is2i Is2i').\n  { eapply irrel_ivd_choice; eauto. }\n  { eapply irrel_pidist_choice; eauto. }\n  apply ip_coupling_plus; eauto.\nQed.\n\nLemma irrel_coupling_bind_condition {A1 B1 B2} (f1: A1 → ivdist B1) (f2: A1 → pidist B2)\n      I Is Q x:\n  (le_pidist (singleton I) Is ) →\n  (irrel_couplingP (f1 x) (f2 x) Q) →\n  irrel_couplingP (x ← I; y ← f1 x; mret (x, y))\n                  (x ← Is; y ← f2 x; mret (x, y))\n                  (λ xy1 xy2, fst xy1 = x → fst xy2 = x → Q (snd xy1) (snd xy2)).\nProof.\n  intros Hle Hc.\n  eapply (irrel_coupling_bind (λ x y, x = y)).\n  { exists I Is; try reflexivity.\n    exists I; eauto. apply ival_coupling_refl.\n  }\n  intros ? y ?; subst.\n  destruct (ClassicalEpsilon.excluded_middle_informative (x = y)).\n  - intros; subst. eapply irrel_coupling_bind; eauto.\n    intros. apply irrel_coupling_mret => ? //=.\n  - intros. eapply irrel_coupling_bind.\n    * apply irrel_coupling_trivial.\n    * intros. apply irrel_coupling_mret => ? //=. intros. congruence.\nQed.\n\nLemma irrel_coupling_support {X Y} I1 I2 (P: X → Y → Prop):\n  ∀ (Ic: irrel_couplingP I1 I2 P),\n  irrel_couplingP I1 I2 (λ x y, ∃ Hpf: P x y,  In_isupport x I1 ∧ In_psupport y I2 ∧\n                        In_isupport (exist _ (x, y) Hpf) Ic).\nProof.\n  intros [? ? Heq1 Heq2 Ic].\n  specialize (ip_coupling_support _ _ _ Ic).\n  eexists; eauto.\n  eapply ip_coupling_conseq; eauto.\n  intros x y (Hpf&Hin1&Hin2&?); exists Hpf; repeat split; auto.\n  -  edestruct Hin1 as (i&?&?).\n     edestruct (irrel_ivd_support_coerce _ _ Heq1) as (Hcoerce&_).\n     apply Hcoerce; eauto.\n  - eapply irrel_pidist_support_coerce; eauto.\nQed.\n\nLemma irrel_coupling_support_wit {X Y} I1 I2 (P: X → Y → Prop):\n  ∀ (Ic: irrel_couplingP I1 I2 P),\n    { xy : X * Y | ∃ Hpf : P (fst xy) (snd xy),\n        In_isupport (fst xy) I1 ∧ In_psupport (snd xy) I2 ∧ In_isupport (exist _ xy Hpf) Ic }.\nProof.\n  intros [? ? Heq1 Heq2 Ic].\n  specialize (ip_coupling_support_wit _ _ _ Ic).\n  rewrite //=.\n  intros ((x&y)&Hpf).\n  exists (x, y).\n  destruct Hpf as (Hpf&Hin1&Hin2&?).\n  exists Hpf; repeat split; auto.\n  -  edestruct Hin1 as (i&?&?).\n     edestruct (irrel_ivd_support_coerce _ _ Heq1) as (Hcoerce&_).\n     apply Hcoerce; eauto.\n  - eapply irrel_pidist_support_coerce; eauto.\nQed.\n\nLemma rsupport_support_right {X Y} (Ix: ivdist X) (x: X) Is (P: X → Y → Prop)\n      (Ic: irrel_couplingP Ix Is P)  (c: rsupport Ic x) :\n  In_psupport (proj1_sig c) Is.\nProof.\n  destruct c as (y'&ic&HP&Hind&Hgt).\n  rewrite //=. destruct Ic as [Ix' Is' Hirrel_ivd Hirrel_pidist Ic].\n  eapply irrel_pidist_support_coerce; eauto.\n  destruct Ic as [Iy Hle Ic].\n  rewrite //= in ic Hind Hgt.\n  clear Hirrel_pidist.\n\n  destruct (irrel_ivd_support_coerce _ _ Hirrel_ivd x) as (Hcoerce&_).\n  destruct (Hle Iy) as (Iy'&Heq&Hin); first by auto.\n  destruct Ic as [Ic Hproj1 Hproj2].\n  rewrite //= in ic Hind Hgt.\n\n  symmetry in Hproj2.\n  setoid_rewrite Heq in Hproj2.\n  destruct Hproj2 as (h1&h2&?&?&Hindic&Hvalic).\n\n\n  assert (val (x0 ← Ic; mret (sval x0).2) (existT ic tt) > 0) as Hgt'.\n  { rewrite //= Rmult_1_r //=. }\n  specialize (Hindic (coerce_supp _ _ Hgt')).\n  specialize (Hvalic (coerce_supp _ _ Hgt')).\n  rewrite //= in Hindic Hvalic.\n\n\n\n  exists Iy'.\n  exists (sval (h1 (coerce_supp _ _ Hgt'))).\n  repeat split; auto.\n  - rewrite Hindic Hind //=.\n  - rewrite Hvalic //=.\nQed.\n\nLemma rsupport_post {X Y} (Ix: ivdist X) (x: X) Is (P: X → Y → Prop)\n      (Ic: irrel_couplingP Ix Is P)  (c: rsupport Ic x) :\n  P x (proj1_sig c).\nProof.\n  destruct c as (y&I&i&Hind&?).\n  rewrite //=.\nQed.\n\nTransparent pidist_ret.\nLemma rsupport_mret_right {X Y} (Ix: ivdist X) (x: X) (y: Y) (P: X → Y → Prop)\n      (Ic: irrel_couplingP Ix (mret y) P)  (c: rsupport Ic x) :\n  proj1_sig c = y.\nProof.\n  edestruct (rsupport_support_right _ _ _ _ Ic c) as (Iy&iy&Hin&Hind&?).\n  subst; rewrite -Hind //=.\n  rewrite /In/mret/base.mret//= in Hin.\n  subst. destruct iy => //=.\nQed.\nOpaque pidist_ret.\n\n\nLemma ip_irrel_coupling {A1 A2} (I: ivdist A1) (Is: pidist A2) (P: A1 → A2 → Prop):\n  idist_pidist_couplingP I Is P →\n  irrel_couplingP I Is P.\nProof.\n  intros.\n  exists I Is; try reflexivity; eauto.\nQed.\n\n\nLemma irrel_bounded_supp_fun {A} f (Is Is': pidist A):\n  irrel_pidist Is Is' →\n  bounded_fun_on f (λ x, In_psupport x Is') →\n  bounded_fun_on f (λ x, In_psupport x Is).\nProof.\n  intros Hle Hbf.\n  eapply bounded_fun_on_anti; try eassumption.\n  eapply irrel_pidist_support_coerce; eauto.\nQed.\n\nLemma irrel_pidist_bounded_supp_Ex_max {A} f (Is Is': pidist A):\n  irrel_pidist Is Is' →\n  bounded_fun_on f (λ x, In_psupport x Is') →\n  Rbar_le (Ex_max f Is) (Ex_max f Is').\nProof.\n  intros Hi Hb1.\n  feed pose proof (irrel_bounded_supp_fun f Is Is') as Hb2; eauto.\n  assert (bounded_fun_on f (λ x, In_psupport x Is ∨ In_psupport x Is')) as Hb.\n  { destruct Hb1 as (c1&?).\n    destruct Hb2 as (c2&?).\n    exists (Rmax c1 c2).\n    intros x [Hin1|Hin2]; rewrite Rmax_Rle; intuition.\n  }\n  clear Hb1. clear Hb2.\n  edestruct (bounded_fun_on_to_bounded f) as (g'&Hb'&Heq); eauto.\n  feed pose proof (irrel_pidist_Ex_max Is Is' Hi g' Hb'); eauto.\n  erewrite (Ex_max_eq_ext_supp f g' Is'); eauto.\n  etransitivity; eauto.\n  erewrite (Ex_max_eq_ext_supp f g' Is); eauto; first reflexivity.\nQed.\n\nLemma Ex_min_irrel_anti {A} f (Is Is': pidist A) :\n  irrel_pidist Is Is' →\n  bounded_fun f →\n  Rbar_le (Ex_min f Is') (Ex_min f Is).\nProof. eauto. Qed.\n\nLemma irrel_coupling_eq_ex_Ex {A1 A2} f g (I: ivdist A1) (Is: pidist A2) :\n  irrel_couplingP I Is (λ x y, f x = g y) →\n  bounded_fun g →\n  ex_Ex_ival f I.\nProof.\n  intros [Is1_irrel Is2_irrel Hirrel_ivd Hirrel_pidst Ic] Hex.\n  assert (idist_pidist_couplingP (x ← Is1_irrel; mret (f x))\n                                 (x ← Is2_irrel; mret (g x))\n                                 (λ x y, x = y)) as Ic'.\n  { eapply ip_coupling_bind; eauto => ???.\n    apply ip_coupling_mret; auto. }\n\n  destruct Ic' as [I2 Hmem Ic'].\n  apply ival_coupling_eq in Ic'.\n  eapply ex_Ex_ival_irrel_proper.\n  { symmetry; eauto. }\n\n  rewrite (ex_Ex_ival_fmap id f).\n  setoid_rewrite Ic'.\n  cut (ex_Ex_extrema id (x ← Is2_irrel; mret (g x))).\n  { intros Hex'. edestruct (Hmem I2) as (I2'&Heq'&?); first done.\n    rewrite Heq'. eapply Hex'; eauto. }\n  rewrite -ex_Ex_extrema_fmap. eauto.\n  eapply ex_Ex_extrema_bounded_fun.\n  eauto.\nQed.\n\nLemma irrel_coupling_eq_Ex_min {A1 A2} f g (I: ivdist A1) (Is: pidist A2) :\n  irrel_couplingP I Is (λ x y, f x = g y) →\n  bounded_fun g →\n  Rbar_le (Ex_min g Is) (Ex_ival f I).\nProof.\n  intros Hirrel Hb.\n  feed pose proof (irrel_coupling_eq_ex_Ex f g I Is) as Hex; eauto.\n  destruct Hirrel as [Is1_irrel Is2_irrel Hirrel_ivd Hirrel_pidst Ic].\n  assert (idist_pidist_couplingP (x ← Is1_irrel; mret (f x))\n                                 (x ← Is2_irrel; mret (g x))\n                                 (λ x y, x = y)) as Ic'.\n  { eapply ip_coupling_bind; eauto => ???.\n    apply ip_coupling_mret; auto. }\n\n  destruct Ic' as [I2 Hmem Ic'].\n  apply ival_coupling_eq in Ic'.\n\n  etransitivity; first apply Ex_min_irrel_anti; eauto.\n  erewrite Ex_ival_irrel_proper; eauto.\n\n  transitivity (Ex_min (λ x, Ex_min id (mret (g x))) Is2_irrel).\n  { apply Ex_min_le_ext.\n    * intros. rewrite Ex_min_mret. reflexivity.\n    * eapply ex_Ex_extrema_bounded_fun; eauto.\n  }\n  assert (ex_Ex_ival f Is1_irrel).\n  { eapply ex_Ex_ival_irrel_proper; eauto. }\n  etransitivity; first eapply Ex_min_bind_post_aux2; last first.\n  - transitivity (Ex_ival (λ x, Ex_ival id (mret (f x))) Is1_irrel); last first.\n    { apply Ex_ival_mono.\n      * intros. rewrite Ex_ival_mret. reflexivity.\n      * setoid_rewrite Ex_ival_mret.\n        eapply ex_Ex_ival_irrel_proper; eauto.\n      * eapply ex_Ex_ival_irrel_proper; eauto.\n    }\n    rewrite -Ex_ival_bind_post; last first.\n    { rewrite -ex_Ex_ival_fmap. eauto. }\n    transitivity (Ex_ival id I2); last first.\n    { refl_right. f_equal. symmetry. eapply Ex_ival_proper; eauto.\n      rewrite -ex_Ex_ival_fmap. eauto. }\n\n    apply In_pidist_le_singleton in Hmem.\n    destruct Hmem as (I2'&Heq22'&?).\n    transitivity (Ex_ival id I2'); last first.\n    { refl_right. f_equal. symmetry. eapply Ex_ival_proper; eauto.\n      eapply ex_Ex_ival_proper; eauto.\n      rewrite -ex_Ex_ival_fmap. eauto. }\n    apply Ex_min_spec1'; auto.\n    eapply ex_Ex_ival_proper; eauto.\n    eapply ex_Ex_ival_proper; eauto.\n    rewrite -ex_Ex_ival_fmap. eauto.\n  - setoid_rewrite Ex_min_mret.\n    apply ex_Ex_extrema_bounded_fun; eauto.\n  - intros. setoid_rewrite Ex_min_mret. rewrite //=.\n  - apply Ex_min_bounded_fun_finite.\n    setoid_rewrite Ex_min_mret. eauto.\nQed.\n\nLemma irrel_coupling_eq_Ex_min' {A1 A2 A3} f g (h : A3 → R) (I: ivdist A1) (Is: pidist A2) :\n  irrel_couplingP I Is (λ x y, f x = g y) →\n  bounded_fun (λ x, h (g x)) →\n  Rbar_le (Ex_min (λ x, h (g x)) Is) (Ex_ival (λ x, h (f x)) I).\nProof.\n  intros Hic Hb.\n  eapply irrel_coupling_eq_Ex_min; eauto.\n  eapply irrel_coupling_conseq; eauto.\n  rewrite //=. intros x y ->. done.\nQed.\n\nLemma irrel_coupling_eq_Ex_max {A1 A2} f g (I: ivdist A1) (Is: pidist A2):\n  irrel_couplingP I Is (λ x y, f x = g y) →\n  bounded_fun g →\n  Rbar_le (Ex_ival f I) (Ex_max g Is).\nProof.\n  intros HIc Hb.\n  apply Rbar_opp_le.\n  rewrite Ex_max_neg_min Rbar_opp_involutive.\n  rewrite /Rbar_opp//=.\n  rewrite -Ex_ival_negate.\n  apply irrel_coupling_eq_Ex_min; eauto.\n  - eapply irrel_coupling_conseq; eauto => x y ?.\n    nra.\n  - destruct Hb as (c&Hb). exists c; intros x. specialize (Hb x).\n    move: Hb. do 2 apply Rabs_case; nra.\nQed.\n\n\nLemma irrel_coupling_eq_ex_Ex_supp {A1 A2} f g (I: ivdist A1) (Is: pidist A2) :\n  irrel_couplingP I Is (λ x y, f x = g y) →\n  bounded_fun_on g (λ x, In_psupport x Is) →\n  ex_Ex_ival f I.\nProof.\n  intros Hi Hex.\n  edestruct (bounded_fun_on_to_bounded g) as (g'&?Hb&Heq); eauto.\n  feed pose proof (irrel_coupling_eq_ex_Ex f g' I Is); eauto.\n  eapply irrel_coupling_conseq; last first.\n  { unshelve (eapply @irrel_coupling_support); last eapply Hi. }\n  rewrite //=. intros x y (Hpf&Hin&Hinp&?).\n  rewrite -Heq; eauto.\nQed.\n\nLemma irrel_coupling_eq_Ex_min_supp {A1 A2} f g (I: ivdist A1) (Is: pidist A2) :\n  irrel_couplingP I Is (λ x y, f x = g y) →\n  bounded_fun_on g (λ x, In_psupport x Is) →\n  Rbar_le (Ex_min g Is) (Ex_ival f I).\nProof.\n  intros Hi Hex.\n  edestruct (bounded_fun_on_to_bounded g) as (g'&?Hb&Heq); eauto.\n  feed pose proof (irrel_coupling_eq_Ex_min f g' I Is); eauto.\n  eapply irrel_coupling_conseq; last first.\n  { unshelve (eapply @irrel_coupling_support); last eapply Hi. }\n  rewrite //=. intros x y (Hpf&Hin&Hinp&?).\n  rewrite -Heq; eauto.\n  etransitivity; last eassumption.\n  refl_right.\n  eapply Ex_min_eq_ext_supp.\n  eauto.\nQed.\n\nLemma irrel_coupling_eq_Ex_max_supp {A1 A2} f g (I: ivdist A1) (Is: pidist A2):\n  irrel_couplingP I Is (λ x y, f x = g y) →\n  bounded_fun_on g (λ x, In_psupport x Is) →\n  Rbar_le (Ex_ival f I) (Ex_max g Is).\nProof.\n  intros HIc Hb.\n  apply Rbar_opp_le.\n  rewrite Ex_max_neg_min Rbar_opp_involutive.\n  rewrite /Rbar_opp//=.\n  rewrite -Ex_ival_negate.\n  apply irrel_coupling_eq_Ex_min_supp; eauto.\n  - eapply irrel_coupling_conseq; eauto => x y ?.\n    nra.\n  - destruct Hb as (c&Hb). exists c; intros x Hin. specialize (Hb x Hin).\n    move: Hb. do 2 apply Rabs_case; nra.\nQed.\n", "meta": {"author": "jtassarotti", "repo": "coq-proba", "sha": "11d69b2286940ff532421252a7d9b1384c2f674a", "save_path": "github-repos/coq/jtassarotti-coq-proba", "path": "github-repos/coq/jtassarotti-coq-proba/coq-proba-11d69b2286940ff532421252a7d9b1384c2f674a/theories/monad/idxval/irrel_equiv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24276019912445274}}
{"text": "Require Import Verse.\nImport VerseNotations.\nRequire Import Verse.Arch.C.\n\nRequire Import Vector.\nImport VectorNotations.\n\nDefinition iterType := Array 10 hostE Word16.\nSection TestFunction.\n\n  Variable variable : VariableT.\n  Arguments variable [k] _.\n  (* The parameters of the function *)\n  Variable num : variable Word16.\n  Variable arr      : variable (Array 3 littleE Word16).\n  Definition parameters := [Var num; Var arr].\n\n  (* The local variables *)\n\n  Definition locals : list (some type) := [ ]%list.\n\n  (* The temp register *)\n  Variable tmp       : variable Word16.\n  Variable double    : variable Word32.\n\n  Definition registers := [Var tmp; Var double].\n\n  Definition test : iterator iterType variable.\n    verse\n      {|\n        (* Try out all operators *)\n        setup   := [\n                    MOVE tmp TO arr[- 1 -];\n                    num ::= tmp + Ox \"abcd\";\n                      num ::= tmp - num ;\n                      num      ::= tmp      * arr[-1-] ;\n                      num      ::= arr[-1-] / tmp ;\n                      arr[-1-] ::= tmp      | num ;\n                      num      ::= tmp      & arr[-1-];\n                      num      ::= tmp      ^ num ;\n\n                      (* binary update *)\n                      num ::=+ tmp;\n                      num ::=- arr[-1-];\n                      num ::=* Ox \"1234\";\n                      num ::=/ tmp;\n                      num ::=| tmp;\n                      num ::=& tmp;\n                      num ::=^ tmp;\n\n                      (* Unary operators *)\n                      num      ::=~ tmp;\n                      tmp      ::=  arr[-1-] <<  42;\n                      tmp      ::=  arr[-1-] >>  42;\n                      num      ::=  tmp     <<< 42;\n                      arr[-1-] ::=  tmp     >>> 42;\n\n\n                      (* Unary update operators *)\n                      tmp      ::=<<  (42%nat);\n                      tmp      ::=>>  (42%nat);\n                      num      ::=<<< (42%nat);\n                      arr[-1-] ::=>>> (42%nat);\n                      double   ::=<<< (42%nat)\n                  ]%list;\n        process    := fun msg => [num ::=  tmp + msg[-1-] ]%list;\n        finalise := [ ]%list\n      |}.\n  Defined.\n\nEnd TestFunction.\n\nRequire Import String.\n\nDefinition regVars := (-cr uint16_t \"temp\", cr uint32_t \"double\"-).\n\nDefinition code : Doc + {Compile.CompileError}.\n  Compile.iterator iterType \"testFunction\" parameters locals registers.\n  assignRegisters regVars.\n  statements test.\nDefined.\n\nDefinition pgm : string := tryLayout code.\n", "meta": {"author": "raaz-crypto", "repo": "verse-coq", "sha": "621f86f4adc3bad53458186f0272425db13d2db7", "save_path": "github-repos/coq/raaz-crypto-verse-coq", "path": "github-repos/coq/raaz-crypto-verse-coq/verse-coq-621f86f4adc3bad53458186f0272425db13d2db7/test/TestIteratorCode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2427601926778028}}
{"text": "Require Import bedrock2.NotationsCustomEntry.\n\nImport Syntax Syntax.Coercions BinInt String List.ListNotations.\nLocal Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope list_scope.\n\nDefinition indirect_add := func! (a, b, c) {\n  store(a, load(b) + load(c))\n}.\n\nDefinition indirect_add_twice := func! (a, b) {\n  indirect_add(a, a, b);\n  indirect_add(a, a, b)\n}.\n\nRequire Import bedrock2.WeakestPrecondition.\nRequire Import coqutil.Word.Interface coqutil.Map.Interface bedrock2.Map.SeparationLogic.\nRequire Import coqutil.Tactics.fwd.\nRequire Import bedrock2.Map.DisjointUnion.\nRequire Import bedrock2.HeapletwiseHyps.\nRequire Import bedrock2.PurifySep.\nRequire Import bedrock2.Semantics bedrock2.FE310CSemantics.\n\nRequire bedrock2.WeakestPreconditionProperties.\nFrom coqutil.Tactics Require Import letexists eabstract.\nRequire Import bedrock2.ProgramLogic bedrock2.Scalars bedrock2.Array.\n\nSection WithParameters.\n  Context {word: word.word 32} {mem: map.map word Byte.byte}.\n  Context {word_ok: word.ok word} {mem_ok: map.ok mem}.\n\n  Definition f (a b : word) := word.add (word.add a b) b.\n\n  Local Notation \"m =* P\" := (P%sep m) (at level 70, only parsing). (* experiment *)\n  Instance spec_of_indirect_add : spec_of \"indirect_add\" :=\n    fnspec! \"indirect_add\" a b c / va Ra vb Rb vc Rc,\n    { requires t m :=\n        m =* scalar b vb * Rb /\\\n        m =* scalar c vc * Rc /\\\n        (* Note: the surviving frame needs to go last for heapletwise callers to work! *)\n        m =* scalar a va * Ra;\n      ensures t' m' :=\n        t = t' /\\\n        m' =* scalar a (word.add vb vc) * Ra }.\n  Instance spec_of_indirect_add_twice : spec_of \"indirect_add_twice\" :=\n    fnspec! \"indirect_add_twice\" a b / va vb R,\n    { requires t m := m =* scalar a va * scalar b vb * R;\n      ensures t' m' := t=t' /\\ m' =* scalar a (f va vb) * scalar b vb * R }.\n\n  Lemma indirect_add_ok : program_logic_goal_for_function! indirect_add.\n  Proof.\n    straightline.\n    straightline.\n    straightline.\n    straightline.\n    straightline.\n    straightline.\n    straightline.\n    straightline.\n    straightline.\n    straightline.\n    straightline.\n    repeat straightline.\n    eauto.\n    Qed.\n\n  Lemma indirect_add_twice_ok : program_logic_goal_for_function! indirect_add_twice.\n  Proof.\n    repeat straightline.\n    straightline_call.\n    { split; [ecancel_assumption|]. split; ecancel_assumption. }\n    repeat straightline.\n    straightline_call.\n    { split; [ecancel_assumption|]. split; ecancel_assumption. }\n    repeat straightline.\n    { cbv [f]. ecancel_assumption. }\n  Qed.\n\n  Example link_both : spec_of_indirect_add_twice ((\"indirect_add_twice\",indirect_add_twice)::(\"indirect_add\",indirect_add)::nil).\n  Proof. auto using indirect_add_twice_ok, indirect_add_ok. Qed.\n\n  (*\n  Require Import bedrock2.ToCString bedrock2.PrintString coqutil.Macros.WithBaseName.\n  Goal True. print_string (c_module &[,indirect_add_twice; indirect_add]). Abort.\n  *)\n\n  Definition indirect_add_three := func! (a, b, c) {\n    indirect_add(a, a, b);\n    indirect_add(a, a, c)\n  }.\n\n  Definition g (a b c : word) := word.add (word.add a b) c.\n  Instance spec_of_indirect_add_three : spec_of \"indirect_add_three\" :=\n    fnspec! \"indirect_add_three\" a b c / va vb vc Rb R,\n    { requires t m := m =* scalar a va * scalar c vc * R /\\ m =* scalar b vb * Rb;\n      ensures t' m' := t=t' /\\ m' =* scalar a (g va vb vc) * scalar c vc * R }.\n\n  Lemma indirect_add_three_ok : program_logic_goal_for_function! indirect_add_three.\n  Proof.\n    repeat straightline.\n    straightline_call.\n    { split; [ecancel_assumption|]. split; ecancel_assumption. }\n    repeat straightline.\n    straightline_call.\n    { split; [ecancel_assumption|]. split; ecancel_assumption. }\n    repeat straightline.\n    { cbv [g]. ecancel_assumption. }\n  Qed.\n\n  Definition indirect_add_three' := func! (out, a, b, c) {\n    stackalloc 4 as v;\n    indirect_add(v, a, b);\n    indirect_add(out, v, c)\n  }.\n\n  Instance spec_of_indirect_add_three' : spec_of \"indirect_add_three'\" :=\n    fnspec! \"indirect_add_three'\" out a b c / vout va vb vc Ra Rb Rc R,\n    { requires t m :=\n        m =* scalar out vout * R /\\\n        m =* scalar a va * Ra /\\\n        m =* scalar b vb * Rb /\\\n        m =* scalar c vc * Rc;\n      ensures t' m' := t=t' /\\ m' =* scalar out (g va vb vc) * R }.\n\n  Lemma indirect_add_three'_ok : program_logic_goal_for_function! indirect_add_three'.\n  Proof.\n    repeat straightline.\n    (* note: we want to introduce only one variable for stack contents\n     * and use it in a all separation-logic facts in the symbolic state *)\n\n    repeat match goal with\n           | H : _ |- _ =>\n               seprewrite_in_by scalar_of_bytes H\n                 ltac:(Lia.lia);\n                 let x := fresh \"x\" in\n                 set (word.of_Z _) as x in H; clearbody x; move x at top\n           end.\n    clear dependent mStack.\n\n    (*\nH1 : (scalar a0 x ⋆ (scalar out vout ⋆ R))%sep m2\nH2 : (scalar a0 x0 ⋆ (scalar a va ⋆ Ra))%sep m2\nH3 : (scalar a0 x1 ⋆ (scalar b vb ⋆ Rb))%sep m2\nH4 : (scalar a0 x2 ⋆ (scalar c vc ⋆ Rc))%sep m2\n     *)\n\n    straightline_call.\n    { split; [ecancel_assumption|].\n      split; [ecancel_assumption|].\n      exact H1. }\n\n    repeat straightline.\n    (*\nH15 : (scalar a0 (word.add va vb) ⋆ (scalar out vout ⋆ R))%sep a2\n     *)\n    (* H15 is an updated version of H1,\n       but we really wanted to carry over H2,H3, and H4 as well *)\n  Abort.\n\n  Lemma anybytes4_to_scalar: forall a (m: mem),\n      anybytes a 4 m -> exists v, with_mem m (scalar a v).\n  Proof.\n    intros.\n    eapply anybytes_to_array_1 in H. fwd.\n    eapply scalar_of_bytes in Hp0. 2: rewrite Hp1; reflexivity.\n    eauto.\n  Qed.\n\n  Lemma scalar_to_anybytes4: forall a (m: mem) v,\n      scalar a v m -> anybytes a 4 m.\n  Proof.\n    intros. eapply scalar_to_anybytes in H. exact H.\n  Qed.\n\n  Lemma sep_call: forall funs f t m args\n      (calleePre: Prop)\n      (calleePost callerPost: trace -> mem -> list word -> Prop),\n      (* definition-site format: *)\n      (calleePre -> call funs f t m args calleePost) ->\n      (* use-site format: *)\n      (calleePre /\\ forall t' m' rets, calleePost t' m' rets -> callerPost t' m' rets) ->\n      (* conclusion: *)\n      call funs f t m args callerPost.\n  Proof.\n    intros. destruct H0. eapply WeakestPreconditionProperties.Proper_call; eauto.\n  Qed.\n\n  Lemma purify_scalar: forall (a v: word), purify (scalar a v) True.\n  Proof. unfold purify. intros. constructor. Qed.\n  Hint Resolve purify_scalar: purify.\n\n  Ltac straightline_stackalloc ::= fail.\n  Ltac straightline_stackdealloc ::= fail.\n\n  Ltac straightline_call ::=\n    lazymatch goal with\n    | |- WeakestPrecondition.call ?functions ?callee _ _ _ _ =>\n        let callee_spec := lazymatch constr:(_:spec_of callee) with ?s => s end in\n        let Hcall := lazymatch goal with H: callee_spec functions |- _ => H end in\n        eapply sep_call; [ eapply Hcall | ]\n    end.\n\n  Ltac same_pred_and_addr P Q ::=\n    lazymatch P with\n    | ?pred ?addr ?val1 =>\n        lazymatch Q with\n        | pred addr ?val2 => idtac\n        end\n    end.\n\n  Ltac step := first [ heapletwise_step | straightline ].\n\n  (* trying again with non-separating conjunction *)\n  Lemma indirect_add_three'_ok : program_logic_goal_for_function! indirect_add_three'.\n  Proof.\n    repeat step.\n    lazymatch goal with\n    | H: anybytes _ _ _ |- _ => eapply anybytes4_to_scalar in H; destruct H as (? & H)\n    end.\n(*\nmCombined is the full memory, and its first split into mStack and the rest is unique,\nbut that rest can be split in 4 different ways:\n  H3 : m0 |= scalar out vout\n  H4 : m1 |= R\n  H5 : m2 |= scalar a va\n  H6 : m3 |= Ra\n  H2 : m6 |= scalar b vb\n  H9 : m7 |= Rb\n  H7 : m4 |= scalar c vc\n  H8 : m5 |= Rc\n  H1 : mStack |= scalar a0 x\n  H10 : (((m4 \\*/ m5) \\=/ (m6 \\*/ m7)) \\=/ ((m2 \\*/ m3) \\=/ (m0 \\*/ m1))) \\*/ mStack =\n        mCombined\n*)\n    straightline_call.\n\n    step. step. step. (* <-- note how this canceling step discards all aliased memory:\n       ((((m4 \\*/ m5) \\=/ (m6 \\*/ m7)) \\=/ ((m2 \\*/ m3) \\=/ (m0 \\*/ m1))) \\*/ mStack)\n       becomes\n       (m3 \\*/ mStack) *)\n    step. step. step. step. step. step. step. step. step. step. step.\n    repeat step.\n    straightline_call.\n    repeat step.\n    match goal with\n    | H: with_mem _ (scalar _ (word.add va vb)) |- _ => eapply scalar_to_anybytes4 in H\n    end.\n    (* TODO automate *)\n    rename D0 into Di.\n    rewrite (mmap.du_comm m9 m1) in Di.\n    rewrite <- mmap.du_assoc in Di.\n    pose proof Di as Dii.\n    unfold mmap.du in Di at 1. fwd.\n    do 2 eexists.\n    split; [eassumption | ].\n    split. {\n      eapply split_du. simpl. eassumption.\n    }\n    clear Di.\n    repeat step.\n    unfold g.\n    repeat step.\n  Qed.\n\n  (* let's see how this would look like with an alternate spec of [indirect_add] *)\n\n  Remove Hints spec_of_indirect_add : typeclass_instances.\n  Instance spec_of_indirect_add_gen : spec_of \"indirect_add\" :=\n    fnspec! \"indirect_add\" a b c / va Ra vb Rb vc Rc,\n    { requires t m := m =* scalar a va * Ra /\\ m =* scalar b vb * Rb /\\ m =* scalar c vc * Rc;\n      ensures t' m' := t=t' /\\\n        forall va Ra, m =* scalar a va * Ra -> m' =* scalar a (word.add vb vc) * Ra }.\n\n  Lemma indirect_add_gen_ok : program_logic_goal_for_function! indirect_add.\n  Proof.\n    repeat straightline.\n    (* This goal is unprovable as shown.\n       It could be made provable by revealing how the memory was updated\n         by modifying the straightline rule for store.\n       I don't know how I would do this systematically for non-leaf functions, though. *)\n Abort.\n\n  (* an potential alternative to changing this spec would be to\n     - prove  wp.call (post:=p) /\\ wp.call(post=q) -> wp.call (post:=p/\\q)\n     - instantiate the spec of indirect_add multiple times at the call site\n       (existentials in postcondition are duplicated for each instantiation)\n     but for now, let's prototype with changed spec:\n  *)\n\n  Lemma indirect_add_three'_ok' : program_logic_goal_for_function! indirect_add_three'.\n  Proof.\n    repeat straightline.\n    (* note: we want to introduce only one variable for stack contents\n     * and use it in a all separation-logic facts in the symbolic state.\n     * here we get away with doing it wrong anyway. *)\n\n    repeat match goal with\n           | H : _ |- _ =>\n               seprewrite_in_by scalar_of_bytes H\n                 ltac:(Lia.lia);\n                 let x := fresh \"x\" in\n                 set (word.of_Z _) as x in H; clearbody x; move x at top\n           end.\n    clear dependent mStack.\n\n    straightline_call.\n    (*\n    { split; [exact H1|split]; ecancel_assumption. }\n    repeat straightline.\n    rename a2 into m.\n    (*\nH15 : forall (va0 : word) (Ra : mem -> Prop),\n      (scalar a0 va0 ⋆ Ra)%sep m2 -> (scalar a0 (word.add va vb) ⋆ Ra)%sep m\n     *)\n    eapply H15 in H1.\n    eapply H15 in H2.\n    eapply H15 in H3.\n    eapply H15 in H4.\n    clear H15.\n\n    straightline_call.\n    { split; [>|split]; try ecancel_assumption. }\n    repeat straightline.\n    rename a3 into m'.\n    (*\nH15 : forall (va0 : word) (Ra : mem -> Prop),\n      (scalar out va0 ⋆ Ra)%sep m ->\n      (scalar out (word.add (word.add va vb) vc) ⋆ Ra)%sep m'\n     *)\n    specialize (H15 _ _ ltac:(ecancel_assumption)).\n\n    (* unrelated: stack deallocation proof, would need scalar-to-bytes lemma *)\n    *)\n  Abort.\n\nEnd WithParameters.\n", "meta": {"author": "mit-plv", "repo": "bedrock2", "sha": "7f2d764ed79f394fe715505a04301d0fb502407f", "save_path": "github-repos/coq/mit-plv-bedrock2", "path": "github-repos/coq/mit-plv-bedrock2/bedrock2-7f2d764ed79f394fe715505a04301d0fb502407f/bedrock2/src/bedrock2Examples/indirect_add_heapletwise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.2427577935532779}}
{"text": "Require Import Common Computation Ensembles.\nRequire Import ADT.ADTSig ADT.Core ADTRefinement.Core.\n\n(** Definitions for integrating [refineADT] into the setoid rewriting\n    framework. *)\n\nInstance refineConstructor_refl rep Dom\n: Reflexive (@refineConstructor rep rep eq Dom).\nProof.\n  intro; simpl; intros; subst; econstructor; eauto.\nQed.\n\nInstance refineMethod_refl rep Dom Cod\n: Reflexive (@refineMethod rep rep eq Dom Cod).\nProof.\n  intro; simpl; unfold refine; intros; subst;\n  repeat econstructor; try destruct v; eauto.\nQed.\n\nGlobal Instance refineADT_PreOrder Sig : PreOrderT (refineADT (Sig := Sig)).\nProof.\n  split; compute in *.\n  - intro x; destruct x.\n    econstructor 1 with\n    (AbsR := @eq Rep);\n      try reflexivity.\n  - intros x y z H H'.\n    destruct H as [AbsR ? ?].\n    destruct H' as [AbsR' ? ?]; simpl in *.\n    econstructor 1 with\n      (AbsR := fun x z => exists y, AbsR x y /\\ AbsR' y z);\n      simpl in *; intros.\n    + destruct_ex; intuition; rewrite_rev_hyp; eauto.\n      autorewrite with refine_monad; f_equiv; unfold pointwise_relation;\n      intros; econstructor; inversion_by computes_to_inv;\n      eauto.\n    + destruct_ex; intuition; rewrite_rev_hyp; eauto.\n      autorewrite with refine_monad; f_equiv; unfold pointwise_relation.\n      intros; rewrite refine_split_ex; autorewrite with refine_monad;\n      f_equiv; unfold pointwise_relation; intros;\n      autorewrite with refine_monad; simpl; f_equiv.\nQed.\n\n(*Add Parametric Relation Sig : (ADT Sig) refineADT\n    reflexivity proved by reflexivity\n    transitivity proved by transitivity\n      as refineADT_rel.*)\n\n(** Refining the representation type is a valid refinement, as long as\n    the new methods are valid refinements.\n\n    If we had dependent setoid relations in [Type], then we could\n    write\n\n<<\nAdd Parametric Morphism : @Build_ADT\n  with signature\n  (fun oldM newM => newM -> Comp oldM)\n    ==> arrow\n    ==> arrow\n    ==> (pointwise_relation _ (@refineConstructor _ _ _))\n    ==> (pointwise_relation _ (@refineMethod _ _ _))\n    ==> refineADT\n    as refineADT_Build_ADT.\nProof.\n  ...\nQed.\n>>\n\n    But, alas, Matthieu is still working on those.  So the rewrite\n    machinery won't work very well when we're switching reps, and\n    we'll instead have to use [etransitivity] and [apply] the\n    [refineADT_Build_ADT_Rep] lemma to switch representations.\n\n    The statement of [refineADT_Build_ADT_Rep] mimics the notation for\n    registering [Parametric Morphism]s so that it will be easy to\n    integrate if dependent setoid relations are added.\n\n *)\n\nLemma refineADT_Build_ADT_Rep Sig oldRep newRep\n      (AbsR : oldRep -> newRep -> Prop)\n:\n  (@respectful_heteroT\n     (forall idx, constructorType oldRep (ConstructorDom Sig idx))\n     (forall idx, constructorType newRep (ConstructorDom Sig idx))\n     (fun oldConstrs =>\n        (forall idx,\n           methodType oldRep (fst (MethodDomCod Sig idx)) (snd (MethodDomCod Sig idx)))\n        -> ADT Sig)\n     (fun newConstrs =>\n        (forall idx,\n           methodType newRep (fst (MethodDomCod Sig idx)) (snd (MethodDomCod Sig idx)))\n        -> ADT Sig)\n     (fun oldConstrs newConstrs =>\n        forall mutIdx,\n          @refineConstructor oldRep newRep AbsR\n                         _\n                         (oldConstrs mutIdx)\n                         (newConstrs mutIdx))\n     (fun x y => @respectful_heteroT\n                   (forall idx, methodType oldRep _ _)\n                   (forall idx, methodType newRep _ _)\n                   (fun _ => ADT Sig)\n                   (fun _ => ADT Sig)\n                   (fun obs obs' =>\n                      forall obsIdx : MethodIndex Sig,\n                        @refineMethod oldRep newRep AbsR\n                                        (fst (MethodDomCod Sig obsIdx))\n                                        (snd (MethodDomCod Sig obsIdx))\n                                        (obs obsIdx)\n                                        (obs' obsIdx))\n                   (fun obs obs' => refineADT)))\n    (@Build_ADT Sig oldRep)\n    (@Build_ADT Sig newRep).\nProof.\n  unfold Proper, respectful_heteroT; intros.\n  let A := match goal with |- refineADT ?A ?B => constr:(A) end in\n  let B := match goal with |- refineADT ?A ?B => constr:(B) end in\n  eapply (@refinesADT Sig A B AbsR);\n    unfold id, pointwise_relation in *; simpl in *; intros; eauto.\nQed.\n\n(** Thankfully, we can register a number of different refinements\n    which follow from [refineADT_Build_ADT_Rep] as [Parametric\n    Morphism]s... or we could, if [refineADT] were in [Prop]. *)\n\n(** Refining Methods is a valid ADT refinement. *)\n\nLemma refineADT_Build_ADT_Method rep Sig cs\n: forall ms ms',\n    (forall idx, @refineMethod _ _ eq\n                                 (fst (MethodDomCod Sig idx))\n                                 (snd (MethodDomCod Sig idx))\n                                 (ms idx) (ms' idx))\n    -> refineADT (@Build_ADT Sig rep cs ms) (@Build_ADT Sig rep cs ms').\nProof.\n  intros; eapply refineADT_Build_ADT_Rep; eauto; reflexivity.\nQed.\n\n(** Refining Constructors is also a valid ADT refinement. *)\n\nLemma refineADT_Build_ADT_Constructors rep Sig ms\n: forall cs cs',\n    (forall idx, @refineConstructor _ _ eq\n                                (ConstructorDom Sig idx)\n                                (cs idx) (cs' idx))\n    -> refineADT (@Build_ADT Sig rep cs ms) (@Build_ADT Sig rep cs' ms).\nProof.\n  intros; eapply refineADT_Build_ADT_Rep; eauto; reflexivity.\nQed.\n\n(** Refining observers and mutators at the same time is also a valid\n    refinement. [BD: I've come to the conclusion that smaller\n    refinement steps are better, so using the previous refinements\n    should be the preferred mode. ]*)\n\nLemma refineADT_Build_ADT_Both rep Sig\n: forall ms ms',\n    (forall idx, @refineMethod _ _ eq\n                                 (fst (MethodDomCod Sig idx))\n                                 (snd (MethodDomCod Sig idx))\n                                 (ms idx) (ms' idx))\n    -> forall cs cs',\n         (forall idx, @refineConstructor _ _ eq\n                                     (ConstructorDom Sig idx)\n                                     (cs idx) (cs' idx))\n         -> refineADT (@Build_ADT Sig rep cs ms) (@Build_ADT Sig rep cs' ms').\nProof.\n  intros; eapply refineADT_Build_ADT_Rep; eauto; reflexivity.\nQed.\n\n(* If [refineADT] lived in [Prop], we'd be able to register\n   refineADT_Build_ADT_Both as a morphism.\n\nAdd Parametric Morphism Sig rep\n: (@Build_ADT Sig rep)\n    with signature\n    (fun mut mut' =>\n       forall idx, @refineConstructor _ _ eq\n                                   (ConstructorDom Sig idx)\n                                   (mut idx) (mut' idx))\n      ==> (fun obs obs' =>\n       forall idx, @refineMethod _ _ eq\n                                   (fst (MethodDomCod Sig idx))\n                                   (snd (MethodDomCod Sig idx))\n                                   (obs idx) (obs' idx))\n      ==> refineADT\n      as refineADT_Build_ADT_Both.\nProof.\n  intros; eapply refineADT_Build_ADT_Rep; eauto; reflexivity.\nQed.*)\n", "meta": {"author": "JasonGross", "repo": "adt-synthesis", "sha": "30a5cd361af029f42864e103a5a604ffa9ee07a7", "save_path": "github-repos/coq/JasonGross-adt-synthesis", "path": "github-repos/coq/JasonGross-adt-synthesis/adt-synthesis-30a5cd361af029f42864e103a5a604ffa9ee07a7/src/ADTRefinement/SetoidMorphisms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24275779355327787}}
{"text": "Set Implicit Arguments.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Require Import Platform.Cito.Semantics.\n  Require Import Platform.Cito.SemanticsUtil.\n  Require Import Coq.Lists.List.\n\n  Notation make_triples := (@make_triples ADTValue).\n\n  Require Import Platform.Cito.WordMap.\n  Import WordMap.\n  Require Import Platform.Cito.WordMapFacts.\n\n  Lemma separated_Equal : forall h1 h2 a b,\n    WordMap.Equal h1 h2\n    -> Semantics.separated (ADTValue := ADTValue) h1 a b\n    -> Semantics.separated h2 a b.\n    unfold Semantics.separated; intuition.\n    right; intro; apply H1.\n    eapply In_m; eauto.\n  Qed.\n\n  Require Import Bedrock.sep.Locals.\n\n  Lemma good_inputs_Equal : forall A h1 h2 pairs,\n    WordMap.Equal (elt := A) h1 h2\n    -> Semantics.good_inputs h1 pairs\n    -> Semantics.good_inputs h2 pairs.\n    unfold Semantics.good_inputs; intuition.\n    eapply Forall_weaken; [ | eassumption ].\n    unfold Semantics.word_adt_match; intros.\n    destruct x; simpl in *.\n    destruct v; auto.\n    erewrite <- find_m; eauto.\n  Qed.    \n\n  Hint Constructors Semantics.RunsTo.\n\n  Lemma store_out_Equal : forall triples h1 h2,\n    WordMap.Equal h1 h2\n    -> WordMap.Equal\n    (fold_left (Semantics.store_out (ADTValue:=ADTValue)) triples h1)\n    (fold_left (Semantics.store_out (ADTValue:=ADTValue)) triples h2).\n    induction triples; simpl; intuition.\n    apply IHtriples.\n    unfold Semantics.store_out.\n    destruct a; simpl.\n    destruct ADTIn; auto.\n    destruct ADTOut; auto.\n    apply add_m; auto.\n    apply remove_m; auto.\n  Qed.\n\n  Notation heap_upd_option := (@heap_upd_option ADTValue).\n\n  Lemma heap_upd_option_Equal : forall h1 h2 a b,\n    WordMap.Equal h1 h2\n    -> WordMap.Equal (heap_upd_option h1 a b) (heap_upd_option h2 a b).\n    unfold Semantics.heap_upd_option; intros.\n    destruct b; auto.\n    apply add_m; auto.\n  Qed.\n\n  Ltac t :=\n    repeat match goal with\n             | [ x := _ |- _ ] => subst x\n             | [ H : forall h : WordMap.t _, _, H' : WordMap.Equal _ _ |- _ ] =>\n               apply H in H'; clear H;\n                 destruct H'; intuition\n           end; eauto.\n\n  Require Import Bedrock.Programming.\n\n  Lemma RunsTo_Equal : forall env s st st',\n    Semantics.RunsTo (ADTValue := ADTValue) env s st st'\n    -> forall h, WordMap.Equal (snd st) h\n      -> exists h', WordMap.Equal (snd st') h'\n        /\\ Semantics.RunsTo (ADTValue := ADTValue) env s (fst st, h) (fst st', h').\n    induction 1; intuition eauto.\n\n    t.\n    t.\n    t.\n    t.\n    t.\n\n    t.\n    simpl in *.\n    descend; eauto.\n    change (fst v) with (fst (fst v, h)) at 2.\n    eapply RunsToCallInternal; eauto.\n\n    t.\n    descend; eauto.\n    change (fst v) with (fst (fst v, h)) at 2.\n    eapply RunsToCallForeign; eauto.\n    simpl; eapply good_inputs_Equal; eauto.\n    simpl; eapply separated_Equal; eauto.\n    apply store_out_Equal; auto.\n    simpl.\n    apply heap_upd_option_Equal.\n    apply store_out_Equal; auto.\n\n    simpl.\n    descend; eauto.\n    change h with (snd (fst v, h)) at 2.\n    change (fst v) with (fst (fst v, h)) at 2.\n    eauto.\n\n    t.\n    descend; eauto; econstructor.\n  Qed.\n\n  Lemma Safe_Equal : forall env s vs h h',\n    Semantics.Safe (ADTValue := ADTValue) env s (vs, h)\n    -> WordMap.Equal h h'\n    -> Semantics.Safe env s (vs, h').\n    intros.\n    apply (Safe_coind (fun s st =>\n      exists h, WordMap.Equal h (snd st)\n        /\\ Semantics.Safe env s (fst st, h))); eauto; intuition idtac;\n    try match goal with\n          | [ H : Logic.ex _ |- _ ] => destruct H; intuition idtac\n        end.\n\n    inversion_clear H3; eauto.\n\n    inversion_clear H4.\n    eapply RunsTo_Equal in H2.\n    destruct H2; intuition idtac.\n    apply H5 in H6.\n    descend; eauto.\n    apply Equal_sym; auto.\n    apply Equal_sym; auto.\n\n    inversion_clear H3; simpl in *; intuition subst.\n    eauto.\n    eauto.\n\n    intros.\n    destruct H1; intuition.\n    inversion H3; clear H3.\n\n    subst loop0 loop1.\n    subst.\n    left; intuition.\n    eauto.\n    simpl in *.\n    eapply RunsTo_Equal in H1.\n    destruct H1; intuition idtac.\n    apply H8 in H4.\n    descend; eauto.\n    apply Equal_sym; auto.\n    apply Equal_sym; auto.\n\n    subst loop0 loop1.\n    subst.\n    right; intuition.\n\n    inversion_clear H3; simpl in *.\n    subst vs0 heap fs.\n    subst; simpl in *.\n    eauto 10.\n    subst vs0 heap fs.\n    subst; simpl in *.\n    right; descend; eauto.\n    eapply good_inputs_Equal; eauto.\n\n    inversion_clear H4.\n    tauto.\n  Qed.\n\n  Notation store_out := (@store_out ADTValue).\n\n  Lemma fold_weaken : forall k v ls h1 h2,\n    WordMap.MapsTo k v (fold_left store_out ls h1)\n    -> (forall k' v', WordMap.MapsTo k' v' h1 -> WordMap.MapsTo k' v' h2)\n    -> WordMap.MapsTo k v (fold_left store_out ls h2).\n    induction ls; simpl; intuition.\n    eapply IHls; eauto.\n    unfold Semantics.store_out; intros.\n    destruct a; simpl in *.\n    destruct ADTIn; auto.\n    destruct ADTOut; auto.\n    apply add_mapsto_iff;\n      apply add_mapsto_iff in H1; intuition subst.\n    eauto.\n\n    apply remove_mapsto_iff;\n      apply remove_mapsto_iff in H1; intuition subst.\n    eauto.\n  Qed.\n\n  Notation store_pair := (@store_pair ADTValue).\n\n  Lemma fold_fwd : forall k v ls h,\n    WordMap.MapsTo k v (fold_left store_pair ls h)\n    -> WordMap.MapsTo k v h\n    \\/ List.In (k, ADT v) ls.\n    induction ls; simpl; intuition.\n    apply IHls in H; intuition.\n    unfold SemanticsUtil.store_pair in H0; simpl in H0.\n    destruct b; simpl in *; auto.\n    apply add_mapsto_iff in H0; intuition subst.\n    eauto.\n  Qed.\n\n  Lemma foldp_bwd : forall k ls h,\n    WordMap.In k h \\/ (exists v, List.In (k, ADT v) ls)\n    -> WordMap.In k (fold_left store_pair ls h).\n    induction ls; simpl; intuition; try destruct b; intuition.\n    firstorder.\n    Focus 2.\n    destruct H0; intuition; try discriminate.\n    eauto.\n    eapply IHls.\n    unfold SemanticsUtil.store_pair; simpl.\n    simpl.\n    left.\n    apply add_in_iff.\n    auto.\n    destruct H0; intuition.\n    injection H0; clear H0; intros; subst.\n    apply IHls.\n    unfold SemanticsUtil.store_pair; simpl.\n    simpl.\n    left.\n    apply add_in_iff.\n    auto.\n    eauto.\n  Qed.\n\n  Lemma foldp_fwd : forall k ls h,\n    WordMap.In k (fold_left store_pair ls h)\n    -> WordMap.In k h \\/ (exists v, List.In (k, ADT v) ls).\n    induction ls; simpl; intuition.\n    apply IHls in H; clear IHls; intuition.\n    unfold SemanticsUtil.store_pair in H0; simpl in H0.\n    destruct b; simpl; auto.\n    simpl in H0.\n    apply add_in_iff in H0; intuition subst.\n    eauto.\n    destruct H0.\n    eauto.\n  Qed.\n\n  Require Import Platform.PreAutoSep.\n\n  Lemma fold_fwd' : forall k v ls h,\n    WordMap.MapsTo k v (fold_left store_out ls h)\n    -> (WordMap.MapsTo k v h /\\ forall a o, ~List.In {| Word := k; ADTIn := ADT a; ADTOut := o |} ls)\n    \\/ exists a, List.In {| Word := k; ADTIn := ADT a; ADTOut := Some v |} ls.\n    induction ls; simpl; intuition.\n    apply IHls in H; intuition.\n\n    unfold Semantics.store_out in H; simpl in H.\n    destruct a; simpl in *.\n    destruct ADTIn.\n    left; intuition eauto.\n    discriminate.\n    destruct ADTOut.\n    apply add_mapsto_iff in H; intuition subst.\n    eauto.\n    left; intuition.\n    eauto 2.\n    apply remove_mapsto_iff in H; intuition subst.\n    left; intuition.\n    eauto 2.\n    destruct H0.\n    eauto.\n  Qed.\n\n  Require Import Platform.Cito.WordMap.\n  Import WordMap.\n  Require Import Platform.Cito.WordMapFacts.\n\n  Lemma heap_merge_store_out : \n    forall h pairs outs, \n      good_inputs h pairs -> \n      let h1 := make_heap pairs in \n      let triples := make_triples pairs outs in\n      WordMap.Equal (update (diff h h1) (fold_left store_out triples h1))\n      (fold_left store_out triples h).\n    simpl; intros.\n    apply Equal_mapsto_iff; intuition.\n\n    apply update_mapsto_iff in H0; intuition.\n\n    eapply fold_weaken; eauto.\n    intros.\n    destruct H.\n    apply fold_fwd in H0; intuition.\n    apply empty_mapsto_iff in H3; tauto.\n    eapply Forall_forall in H; try apply H3.\n    hnf in H; simpl in H.\n    apply WordMap.find_2; auto.\n\n    apply diff_mapsto_iff in H0; intuition subst.\n\n    Lemma In_make_heap' : forall k pairs h,\n      WordMap.In (elt:=ADTValue) k (fold_left store_pair pairs h)\n      -> WordMap.In k h \\/ exists a, List.In (k, ADT a) pairs.\n      induction pairs; simpl; intuition.\n      apply IHpairs in H; intuition.\n      unfold SemanticsUtil.store_pair in H0; simpl in H0.\n      destruct b; auto.\n      apply add_in_iff in H0; intuition subst.\n      eauto.\n      destruct H0; intuition subst.\n      eauto.\n    Qed.\n\n    Lemma In_make_heap : forall k pairs,\n      WordMap.In (elt:=ADTValue) k (make_heap pairs)\n      -> exists a, List.In (k, ADT a) pairs.\n      intros.\n      apply In_make_heap' in H; intuition eauto.\n      apply empty_in_iff in H0; tauto.\n    Qed.\n\n    Lemma keep_when_agrees : forall k e pairs h outs,\n      ~WordMap.In k (make_heap pairs)\n      -> WordMap.MapsTo k e h\n      -> WordMap.MapsTo k e (fold_left store_out (make_triples pairs outs) h).\n      induction pairs; destruct outs; simpl; intuition.\n      apply IHpairs; clear IHpairs; intros.\n      apply H.\n      unfold make_heap.\n      apply foldp_bwd; right.\n      apply In_make_heap in H1; destruct H1; intuition subst.\n      simpl; eauto.\n      unfold Semantics.store_out; simpl.\n      destruct a; simpl in *.\n      destruct v; auto.\n      destruct o.\n      apply WordMap.add_2; auto.\n      intro; subst.\n      exfalso.\n      apply H.\n      apply foldp_bwd; simpl; eauto.\n      apply WordMap.remove_2; auto.\n      intro; subst.\n      exfalso.\n      apply H.\n      apply foldp_bwd; simpl; eauto.\n    Qed.\n\n    eapply keep_when_agrees; eauto.\n\n    apply fold_fwd' in H0; intuition idtac.\n\n    Focus 2.\n    destruct H1.\n    destruct H.\n\n    apply update_mapsto_iff; left.\n\n    Lemma get_pair : forall k x e pairs outs h,\n      Semantics.disjoint_ptrs pairs\n      -> List.In {| Word := k; ADTIn := ADT x; ADTOut := Some e |} (make_triples pairs outs)\n      -> WordMap.MapsTo k e (fold_left store_out (make_triples pairs outs) h).\n      induction pairs; destruct outs; simpl; intuition.\n      simpl in *; intuition.\n      injection H1; clear H1; intros; subst.\n      assert (WordMap.MapsTo k e (store_out h {| Word := k; ADTIn := ADT x; ADTOut := Some e |})).\n      unfold Semantics.store_out; simpl.\n      apply WordMap.add_1; auto.\n      generalize dependent (store_out h {| Word := k; ADTIn := ADT x; ADTOut := Some e |}).\n      assert (forall v, ~List.In (k, ADT v) pairs).\n      intuition.\n      hnf in H.\n      simpl in H.\n      inversion_clear H.\n      apply H1.\n      change k with (fst (k, ADT v)).\n      apply in_map.\n      apply filter_In; tauto.\n      generalize dependent H0.\n      clear.\n      generalize dependent outs.\n      induction pairs; destruct outs; simpl; intuition.\n      apply IHpairs; eauto.\n      unfold Semantics.store_out; simpl.\n      destruct a; simpl in *.\n      destruct v; auto.\n      destruct o.\n      apply WordMap.add_2; auto.\n      intro; subst; eauto.\n      apply WordMap.remove_2; auto.\n      intro; subst; eauto.\n\n      apply IHpairs.\n      hnf in H.\n      simpl in H.\n      destruct b; simpl in *; auto.\n      inversion H; auto.\n      auto.\n    Qed.\n\n    eapply get_pair; eauto.\n\n    case_eq (WordMap.mem k (make_heap pairs)); intros.\n\n    apply update_mapsto_iff; left; intuition.\n\n    Lemma get_pair' : forall k e pairs outs h,\n      Semantics.disjoint_ptrs pairs\n      -> WordMap.MapsTo k e h\n      -> (forall a o, ~List.In {| Word := k; ADTIn := ADT a; ADTOut := o |} (make_triples pairs outs))\n      -> WordMap.MapsTo k e (fold_left store_out (make_triples pairs outs) h).\n      induction pairs; destruct outs; simpl; intuition.\n      apply IHpairs.\n      hnf in H.\n      simpl in H.\n      destruct b; simpl in H; auto.\n      inversion H; auto.\n      simpl.\n      unfold Semantics.store_out; simpl.\n      destruct b; auto.\n      destruct o; simpl in *.\n      apply WordMap.add_2; auto.\n      intro; subst; eauto.\n      apply WordMap.remove_2; auto.\n      intro; subst; eauto.\n      simpl in *.\n      eauto.\n    Qed.\n      \n    apply get_pair'; auto.\n    destruct H; auto.\n    apply WordMap.mem_2 in H1.\n    apply In_make_heap in H1; destruct H1.\n    destruct H.\n    eapply Forall_forall in H; [ | eassumption ].\n    hnf in H; simpl in H.\n    apply WordMap.find_1 in H0.\n    rewrite H0 in H; injection H; clear H; intros; subst.\n\n    unfold make_heap.\n\n    Lemma grab_it : forall k x pairs h,\n      List.In (k, ADT x) pairs\n      -> Semantics.disjoint_ptrs pairs\n      -> WordMap.MapsTo k x (fold_left store_pair pairs h).\n      induction pairs; simpl; intuition; try destruct b; intuition.\n      injection H1; clear H1; intros; subst.\n      hnf in H0.\n      simpl in H0.\n      inversion_clear H0.\n      generalize dependent H.\n      clear IHpairs H1.\n      assert (WordMap.MapsTo k x (store_pair h (k, ADT x))).\n      unfold SemanticsUtil.store_pair; simpl.\n      apply WordMap.add_1; auto.\n      generalize dependent (store_pair h (k, ADT x)).\n      induction pairs; simpl in *; intuition; try destruct b; intuition.\n      simpl in *; intuition subst.\n      apply IHpairs.\n      unfold SemanticsUtil.store_pair; simpl.\n      apply WordMap.add_2; auto.\n      auto.\n\n      apply IHpairs; auto.\n      hnf in H0.\n      simpl in H0.\n      inversion_clear H0; auto.\n    Qed.\n\n    apply grab_it; auto.\n\n    apply update_mapsto_iff; right; intuition.\n    apply diff_mapsto_iff; intuition.\n    apply not_mem_in_iff in H3; tauto.\n    assert (~WordMap.In k (make_heap pairs)).\n    intro.\n    apply not_mem_in_iff in H4; tauto.\n    clear H1.\n    apply H4; clear H4.\n\n    Lemma i_didn't_do_it : forall k ls h,\n      (forall a o, ~List.In {| Word := k; ADTIn := ADT a; ADTOut := o |} ls)\n      -> WordMap.In k (fold_left store_out ls h)\n      -> WordMap.In k h.\n      induction ls; simpl; intuition.\n      apply IHls in H0; eauto.\n      unfold Semantics.store_out in H0.\n      destruct a; simpl in *.\n      destruct ADTIn; auto.\n      destruct ADTOut.\n      apply add_in_iff in H0; intuition subst.\n      exfalso; eauto.\n      apply remove_in_iff in H0; intuition subst.\n    Qed.\n\n    eapply i_didn't_do_it; eauto.\n  Qed.\n\n  Local Hint Constructors NoDup.\n\n  Theorem In_InA : forall A x ls,\n                     List.In x ls -> SetoidList.InA (WordMap.eq_key (elt:=A)) x ls.\n    induction ls; simpl; intuition.\n  Qed.\n\n  Theorem NoDupA_NoDup : forall A ls,\n                           SetoidList.NoDupA (WordMap.eq_key (elt:=A)) ls -> NoDup ls.\n    induction 1; eauto.\n    constructor; auto.\n    intro; apply H.\n    eauto using In_InA.\n  Qed.\n\n  Theorem In_InA' : forall A x ls,\n                      List.In x ls -> SetoidList.InA (WordMap.eq_key_elt (elt:=A)) x ls.\n    induction ls; simpl; intuition.\n    subst; constructor; hnf; auto.\n  Qed.\n\n  Theorem InA_In : forall A x ls,\n                     SetoidList.InA (WordMap.eq_key_elt (elt:=A)) x ls -> List.In x ls.\n    induction 1; simpl; intuition idtac.\n    destruct x, y; simpl in *.\n    hnf in H; simpl in *; intuition subst.\n    tauto.\n  Qed.\n\n  Lemma preserve_store : forall k v pairs h,\n    List.Forall (fun p => match snd p with\n                            | SCA _ => True\n                            | ADT _ => ~WordMap.In (fst p) h\n                          end) pairs\n    -> NoDup (List.map fst (List.filter (fun p => is_adt (snd p)) pairs))\n    -> WordMap.MapsTo k v h\n    -> WordMap.MapsTo k v (fold_left store_pair pairs h).\n    induction pairs; simpl in *; intuition.\n    destruct b as [w | a]; simpl in *.\n    inversion_clear H; simpl in *.\n    apply IHpairs; auto.\n\n    simpl in *.\n    inversion_clear H; simpl in *.\n    inversion_clear H0.\n    apply IHpairs; auto.\n    unfold SemanticsUtil.store_pair; simpl.\n    eapply Forall_forall; intros.\n    case_eq (snd x); intuition idtac.\n    eapply Forall_forall in H3; [ | eassumption ].\n    rewrite H5 in *.\n    apply add_in_iff in H6; intuition subst.\n    apply H.\n    apply in_map.\n    apply filter_In; intuition idtac.\n    unfold is_adt.\n    unfold WordMap.key in *.\n    rewrite H5; reflexivity.\n    unfold SemanticsUtil.store_pair; simpl.\n    apply add_mapsto_iff.\n    right; intuition subst.\n    apply H2.\n    exists v; auto.\n  Qed.\n\n  Lemma keep_key : forall w a1 pairs,\n    List.In (w, ADT a1) pairs\n    -> List.In w (List.map fst (List.filter\n      (fun p : W * Value ADTValue =>\n        match snd p with\n          | SCA _ => false\n          | ADT _ => true\n        end) pairs)).\n    induction pairs; simpl; intuition (subst; simpl in *); intuition idtac.\n    destruct b; simpl in *; intuition.\n  Qed.\n\n  Lemma store_keys : forall k v pairs h,\n    WordMap.MapsTo k v (fold_left store_pair pairs h)\n    -> List.In (k, ADT v) pairs \\/ WordMap.MapsTo k v h.\n    induction pairs; simpl; intuition idtac.\n    apply IHpairs in H; intuition idtac.\n    unfold SemanticsUtil.store_pair in H0; simpl in H0.\n    destruct b; auto.\n    apply add_mapsto_iff in H0; intuition subst; auto.\n  Qed.\n  \n  Lemma store_keys'' : forall k v pairs h,\n    WordMap.MapsTo k v h\n    -> ~ List.In k (List.map fst (List.filter (fun p => is_adt (snd p)) pairs))\n    -> WordMap.MapsTo k v (fold_left store_pair pairs h).\n    induction pairs; simpl; intuition (try discriminate; eauto);\n      unfold is_adt in *; simpl in *.\n\n    destruct b; auto.\n    simpl in *; intuition subst.\n    apply IHpairs; auto.\n    unfold SemanticsUtil.store_pair; simpl.\n    apply add_mapsto_iff; auto.\n  Qed.\n\n  Lemma store_keys' : forall k v pairs h,\n    List.In (k, ADT v) pairs\n    -> NoDup (List.map fst (List.filter (fun p => is_adt (snd p)) pairs))\n    -> WordMap.MapsTo k v (fold_left store_pair pairs h).\n    induction pairs; simpl; intuition (try discriminate; eauto); destruct b; intuition (try discriminate; eauto); \n      unfold is_adt in *; simpl in *.\n\n    injection H1; clear H1; intros; subst.\n    inversion_clear H0.\n    apply store_keys''; auto.\n    unfold SemanticsUtil.store_pair; simpl.\n    apply add_mapsto_iff; auto.\n\n    inversion_clear H0; eauto.\n  Qed.\n\nEnd ADTValue.", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Cito/SemanticsFacts5.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24275778754990232}}
{"text": "From Test Require Import tactic.\n\nSection FOFProblem.\n\nVariable Universe : Set.\nVariable UniverseElement : Universe.\n\nVariable wd_ : Universe -> Universe -> Prop.\nVariable col_ : Universe -> Universe -> Universe -> Prop.\n\n\nVariable col_swap1_1 : (forall A B C : Universe, (col_ A B C -> col_ B A C)).\nVariable col_swap2_2 : (forall A B C : Universe, (col_ A B C -> col_ B C A)).\nVariable col_triv_3 : (forall A B : Universe, col_ A B B).\nVariable wd_swap_4 : (forall A B : Universe, (wd_ A B -> wd_ B A)).\nVariable col_trans_5 : (forall P Q A B C : Universe, ((wd_ P Q /\\ (col_ P Q A /\\ (col_ P Q B /\\ col_ P Q C))) -> col_ A B C)).\n\nTheorem pipo_6 : (forall P Q A B C Dprime Pprime Cprime Dprimeprime Pprimeprime Z Zprime T : Universe, ((wd_ P Q /\\ (wd_ T Z /\\ (wd_ T Zprime /\\ (wd_ T Pprimeprime /\\ (wd_ B Cprime /\\ (wd_ Cprime Dprimeprime /\\ (wd_ B Dprimeprime /\\ (wd_ A B /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ Zprime Z /\\ (wd_ B Pprimeprime /\\ (wd_ B Z /\\ (wd_ Cprime Pprimeprime /\\ (wd_ B Pprime /\\ (wd_ Dprime B /\\ (wd_ Zprime B /\\ (wd_ Cprime C /\\ (wd_ A Dprime /\\ (wd_ Pprime Cprime /\\ (col_ A B Zprime /\\ (col_ Cprime Pprimeprime T /\\ (col_ Cprime Pprimeprime B /\\ (col_ B T Pprimeprime /\\ (col_ Zprime T Z /\\ (col_ B C Z /\\ (col_ Cprime Dprimeprime Pprimeprime /\\ (col_ B Cprime A /\\ col_ B Dprime Pprime)))))))))))))))))))))))))))) -> col_ B Cprime Dprimeprime)).\nProof.\n  time tac.\nQed.\n\nEnd FOFProblem.\n", "meta": {"author": "janicicpredrag", "repo": "Larus", "sha": "a095ca588fbb0e4a64a26d92946485bbf85e1e08", "save_path": "github-repos/coq/janicicpredrag-Larus", "path": "github-repos/coq/janicicpredrag-Larus/Larus-a095ca588fbb0e4a64a26d92946485bbf85e1e08/benchmarks/coq-problems/col-trans/col_trans_0577.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.24264248912822298}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Carriers.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Common.Equality.\n\nModule opt.\n  Section syntax.\n    Context {T : Type}.\n\n    Inductive item :=\n    | Terminal (_ : T)\n    | NonTerminal (nt : String.string) (_ : nat).\n\n    Definition production := list item.\n    Definition productions := list production.\n  End syntax.\n\n  Global Arguments item : clear implicits.\n  Global Arguments production : clear implicits.\n  Global Arguments productions : clear implicits.\n\n  Section semantics.\n    Context {Char : Type} {T : Type}.\n\n    Class compile_item_data :=\n      { on_terminal : (Char -> bool) -> T;\n        nonterminal_names : list String.string;\n        invalid_nonterminal : String.string }.\n\n    Context {cidata : compile_item_data}.\n    Definition compile_nonterminal nt\n      := List.first_index_default (string_beq nt) (List.length nonterminal_names) nonterminal_names.\n    Definition compile_item (expr : Core.item Char) : opt.item T\n      := match expr with\n         | Core.Terminal ch => Terminal (on_terminal ch)\n         | Core.NonTerminal nt => NonTerminal nt (compile_nonterminal nt)\n         end.\n\n    Definition compile_production (expr : Core.production Char) : opt.production T\n      := List.map compile_item expr.\n\n    Definition compile_productions (expr : Core.productions Char) : opt.productions T\n      := List.map compile_production expr.\n\n    Definition compile_grammar (G : pregrammar' Char) : list (productions T)\n      := List.map compile_productions (List.map snd (pregrammar_productions G)).\n  End semantics.\n\n  Global Arguments compile_item_data : clear implicits.\n\n  Lemma eq_compile_nonterminal {Char T} (G : pregrammar' Char)\n        {cidata : @compile_item_data Char T}\n        (Hci : nonterminal_names = pregrammar_nonterminals G)\n    : forall nt, compile_nonterminal nt = default_of_nonterminal (G:=G) nt.\n  Proof.\n    destruct cidata; simpl in *; subst; reflexivity.\n  Qed.\nEnd opt.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/ContextFreeGrammar/Precompute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.24253970262942712}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*              Object Primitives                                      *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AuxStateDataType.\nRequire Import FlatMemory.\nRequire Import AbstractDataType.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Constant.\nRequire Import RealParams.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import CalRealSMSPool.\nRequire Import CalRealProcModule.\nRequire Import CalRealIntelModule.\nRequire Import liblayers.compat.CompatGenSem.\n\nSection OBJ_EPT.\n\n  Context `{real_params: RealParams}.\n\n  (** primitive: set value of n-th entry of guest page table layer *)\n  (** construct nested page table, with the last layer mapping to undef addr *)\n  Function setEPML4_spec (pml4: Z) (adt: RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        if zle_le 0 pml4 (EPT_PML4_INDEX Int.max_unsigned) then\n          let ept' := ZMap.set pml4 (EPML4EValid (ZMap.init EPDPTEUndef)) (ept adt) in\n          Some adt {ept : ept'}\n        else None\n      | _ => None\n    end.\n\n  Function setEPDPTE_spec (pml4 pdpt: Z) (adt: RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        if zle_le 0 pml4 (EPT_PML4_INDEX Int.max_unsigned) then\n          if zle_le 0 pdpt (EPT_PDPT_INDEX Int.max_unsigned) then\n            match ZMap.get pml4 (ept adt) with\n              | EPML4EValid epdpt => \n                let pdpte' := ZMap.set pdpt (EPDPTEValid (ZMap.init EPDTEUndef)) epdpt in\n                let ept' := ZMap.set pml4 (EPML4EValid pdpte') (ept adt) in\n\t        Some adt {ept : ept'}\n              | _ => None\n            end\n          else None\n        else None\n      | _ => None\n    end.\n\n  Function setEPDTE_spec (pml4 pdpt pdir: Z) (adt: RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        if zle_le 0 pml4 (EPT_PML4_INDEX Int.max_unsigned) then\n          if zle_le 0 pdpt (EPT_PDPT_INDEX Int.max_unsigned) then\n            if zle_le 0 pdir (EPT_PDIR_INDEX Int.max_unsigned) then\n              match ZMap.get pml4 (ept adt) with\n                | EPML4EValid epdpt => \n                  match ZMap.get pdpt epdpt with\n                    | EPDPTEValid epdt => \n                      let epdt' := ZMap.set pdir (EPDTEValid (ZMap.init EPTEUndef)) epdt in\n                      let pdpte' := ZMap.set pdpt (EPDPTEValid epdt') epdpt in\n                      let ept' := ZMap.set pml4 (EPML4EValid pdpte') (ept adt) in\n\t              Some adt {ept : ept'}\n                    | _ => None\n                  end\n                    | _ => None\n                  end\n            else None\n          else None\n        else None\n      | _ => None\n    end.\n\n  Function getEPTE_spec (pml4 pdpt pdir ptab: Z) (adt: RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        if zle_le 0 pml4 (EPT_PML4_INDEX Int.max_unsigned) then\n          if zle_le 0 pdpt (EPT_PDPT_INDEX Int.max_unsigned) then\n            if zle_le 0 pdir (EPT_PDIR_INDEX Int.max_unsigned) then\n              if zle_le 0 ptab (EPT_PTAB_INDEX Int.max_unsigned) then\n                  match ZMap.get pml4 (ept adt) with\n                    | EPML4EValid epdpt => \n                      match ZMap.get pdpt epdpt with\n                        | EPDPTEValid epdt => \n                          match ZMap.get pdir epdt with\n                            | EPDTEValid eptab => \n                              match ZMap.get ptab eptab with\n                                | EPTEValid hpa => Some hpa\n                                | _ => None\n                              end\n                            | _ => None\n                          end\n                        | _ => None  \n                      end\n                    | _ => None\n                  end\n                else None\n              else None\n            else None\n          else None\n      | _ => None\n    end.  \n\n  Function setEPTE_spec (pml4 pdpt pdir ptab hpa: Z) (adt: RData): option RData :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) =>\n        if zle_le 0 pml4 (EPT_PML4_INDEX Int.max_unsigned) then\n          if zle_le 0 pdpt (EPT_PDPT_INDEX Int.max_unsigned) then\n            if zle_le 0 pdir (EPT_PDIR_INDEX Int.max_unsigned) then\n              if zle_le 0 ptab (EPT_PTAB_INDEX Int.max_unsigned) then\n                match ZMap.get pml4 (ept adt) with\n                  | EPML4EValid epdpt => \n                    match ZMap.get pdpt epdpt with\n                      | EPDPTEValid epdt => \n                        match ZMap.get pdir epdt with\n                          | EPDTEValid eptab => \n                            let eptab' := ZMap.set ptab (EPTEValid hpa) eptab in\n                            let epdt' := ZMap.set pdir (EPDTEValid eptab') epdt in\n                            let pdpte' := ZMap.set pdpt (EPDPTEValid epdt') epdpt in\n                            let ept' := ZMap.set pml4 (EPML4EValid pdpte') (ept adt) in\n                            Some adt {ept : ept'}\n                          | _ => None\n                        end\n                      | _ => None  \n                    end\n                  | _ => None\n                end\n              else None\n            else None\n          else None\n        else None\n      | _ => None\n    end.\n\n  Definition EPT_PTAB_INDEX' (i:Z) := i mod five_one_two.\n  Definition EPT_PDIR_INDEX' (i:Z) := (i/ five_one_two) mod five_one_two.\n  Definition EPT_PDPT_INDEX' (i:Z) := (i/ (five_one_two * five_one_two)) mod five_one_two.\n  Definition EPT_PML4_INDEX' (i:Z) := (i/ (five_one_two * five_one_two *\n                                           five_one_two)) mod five_one_two.\n\n(*\n/*\n * Get the last level's EPT page structure entry for the guest address gpa.\n */\nstatic gcc_inline uint64_t \nept_get_page_entry(uintptr_t gpa)\n{\n\treturn ept.ptab[EPT_PDPT_INDEX(gpa)][EPT_PDIR_INDEX(gpa)][EPT_PTAB_INDEX(gpa)];\n}*)\n\n  Function ept_get_page_entry_spec (gpa: Z) (adt: RData) : option Z :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) => \n        if zle_lt 0 gpa maxpage then\n          let pml4 := EPT_PML4_INDEX' gpa in\n          let pdpt := EPT_PDPT_INDEX' gpa in\n          let pdir := EPT_PDIR_INDEX' gpa in\n          let ptab := EPT_PTAB_INDEX' gpa in\n          match ZMap.get pml4 (ept adt) with\n            | EPML4EValid epdpt => \n              match ZMap.get pdpt epdpt with\n                | EPDPTEValid epdt => \n                  match ZMap.get pdir epdt with\n                    | EPDTEValid eptab => \n                      match ZMap.get ptab eptab with\n                        | EPTEValid hpa => Some hpa\n                        | _ => None\n                      end\n                    | _ => None\n                  end\n                | _ => None  \n              end\n            | _ => None\n          end\n        else None\n      | _ => None\n    end. \n\n(*\n/*\n * Set the last level's EPT page structure entry for the guest address gpa.\n */\nstatic gcc_inline void \nept_set_page_entry(uintptr_t gpa, uint64_t val)\n{\n\tept.ptab[EPT_PDPT_INDEX(gpa)][EPT_PDIR_INDEX(gpa)][EPT_PTAB_INDEX(gpa)] = val;\n}\n*)\n  Function ept_set_page_entry_spec (gpa hpa : Z) (adt: RData) : option RData :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) => \n        if zle_lt 0 gpa maxpage then\n          if zle_lt 0 hpa maxpage then\n            let pml4 := EPT_PML4_INDEX' gpa in\n            let pdpt := EPT_PDPT_INDEX' gpa in\n            let pdir := EPT_PDIR_INDEX' gpa in\n            let ptab := EPT_PTAB_INDEX' gpa in\n            match ZMap.get pml4 (ept adt) with\n              | EPML4EValid epdpt => \n                match ZMap.get pdpt epdpt with\n                  | EPDPTEValid epdt => \n                    match ZMap.get pdir epdt with\n                      | EPDTEValid eptab => \n                        let eptab' := ZMap.set ptab (EPTEValid hpa) eptab in\n                        let epdt' := ZMap.set pdir (EPDTEValid eptab') epdt in\n                        let pdpte' := ZMap.set pdpt (EPDPTEValid epdt') epdpt in\n                        let ept' := ZMap.set pml4 (EPML4EValid pdpte') (ept adt) in\n                        Some adt {ept: ept'}\n                      | _ => None\n                    end\n                  | _ => None  \n                end\n              | _ => None\n            end\n          else None\n        else None\n      | _ => None\n    end. \n\n(*\n/*\n * Add page structures which map the guest physical address gpa to the host\n * physical address hpa. \n */\nint\nept_add_mapping(uintptr_t gpa, uint64_t hpa, uint32_t mem_type) // I change the type of mem_type\n{\n    ept.ptab[EPT_PDPT_INDEX(gpa)][EPT_PDIR_INDEX(gpa)][EPT_PTAB_INDEX(gpa)] = (hpa & EPT_ADDR_MASK) |\n\t\t\tEPT_PG_IGNORE_PAT | EPT_PG_EX | EPT_PG_WR | EPT_PG_RD |\n\t\t\tEPT_PG_MEMORY_TYPE(mem_type);\n\n    EPT_DEBUG(\"Add 4KB mapping: gpa 0x%08x ==> hpa 0x%llx.\\n\", gpa, hpa);\n\n\treturn 0;\n}\n\n#define\tEPT_ADDR_MASK\t\t\t((uint32_t)-1 << 12)\n#define\tEPT_PG_RD\t\t\t(1 << 0)\n#define\tEPT_PG_WR\t\t\t(1 << 1)\n#define\tEPT_PG_EX\t\t\t(1 << 2)\n#define\tEPT_PG_IGNORE_PAT\t\t(1 << 6)\n#define\tEPT_PG_MEMORY_TYPE(x)\t\t((x) << 3)\n\n*)\n\n  Function ept_add_mapping_spec (gpa hpa : Z) (memtype: Z) (adt: RData) : option (RData * Z) :=\n    match (ikern adt, pg adt, ihost adt) with\n      | (true, true, true) => \n        if zle_lt 0 gpa maxpage then\n          if zle_lt 0 hpa maxpage then\n            if zle_lt 0 memtype 4096 then\n              let pml4 := EPT_PML4_INDEX' gpa in\n              let pdpt := EPT_PDPT_INDEX' gpa in\n              let pdir := EPT_PDIR_INDEX' gpa in\n              let ptab := EPT_PTAB_INDEX' gpa in\n              match ZMap.get pml4 (ept adt) with\n                | EPML4EValid epdpt => \n                  match ZMap.get pdpt epdpt with\n                    | EPDPTEValid epdt => \n                      match ZMap.get pdir epdt with\n                        | EPDTEValid eptab => \n                          let va := Z.lor (Z.lor (Z.land hpa EPT_ADDR_MASK) EPT_PG_IGNORE_PAT_or_PERM) \n                                          (Z.shiftl memtype EPT_PG_MEMORY_TYPE) in\n                          let eptab' := ZMap.set ptab (EPTEValid va) eptab in\n                          let epdt' := ZMap.set pdir (EPDTEValid eptab') epdt in\n                          let pdpte' := ZMap.set pdpt (EPDPTEValid epdt') epdpt in\n                          let ept' := ZMap.set pml4 (EPML4EValid pdpte') (ept adt) in\n                          Some (adt {ept: ept'}, 0)\n                        | _ => None\n                      end\n                    | _ => None  \n                  end\n                | _ => None\n              end\n            else None\n          else None\n        else None\n      | _ => None\n    end. \n\n(*\n\n/*\n * Invalidate the EPT TLB.\n */\nvoid\nept_invalidate_mappings(uint64_t pml4ept)\n{\n\tinvept(INVEPT_TYPE_SINGLE_CONTEXT, EPTP(pml4ept));\n}\n *)\n  Function ept_invalidate_mappings_spec (adt: RData) := \n    match (ikern adt, ihost adt) with\n      | (true, true) => Some 0\n      | _ => None\n    end.\n\n(*\n/*\n * Convert the guest physical address to the host physical address.\n */\n\n#define EPT_PAGE_OFFSET(gpa)\t\t((gpa) & EPT_ADDR_OFFSET_MASK)\n#define EPT_ADDR_OFFSET_MASK\t\t((1 << 12) - 1)\n\nuint64_t\nept_gpa_to_hpa(uintptr_t gpa)\n{\n    uint64_t entry;\n\n    entry = ept_get_page_entry(gpa);\n\n    if (!(entry & (EPT_PG_RD | EPT_PG_WR | EPT_PG_EX)))\n        return 0;\n\n    return ((entry & EPT_ADDR_MASK) | EPT_PAGE_OFFSET(gpa));\n}*)\n\n  Function ept_gpa_to_hpa_spec (gpa: Z) (adt: RData) : option Z :=\n    match ept_get_page_entry_spec gpa adt with\n      | Some hpa =>\n        if zle_le 0 hpa Int.max_unsigned then\n          if zeq (Z.land hpa EPTEPERM) 0 then (Some 0)\n          else let va := Z.lor (Z.land hpa EPT_ADDR_MASK)\n                             (Z.land gpa EPT_ADDR_OFFSET_MASK) in\n             Some va\n        else None\n      | _ => None\n    end. \n\n(*\nint\nept_mmap(uintptr_t gpa, uint64_t hpa, uint8_t mem_type)\n{\n\tuint64_t pg_entry;\n\n\t/*\n\t * XXX: ASSUME 4KB pages are used in both the EPT and the host page\n\t *      structures.\n\t */\n\tKERN_ASSERT(gpa == ROUNDDOWN(gpa, PAGESIZE));\n\tKERN_ASSERT(hpa == ROUNDDOWN(hpa, PAGESIZE));\n\n\tpg_entry = ept_get_page_entry(gpa);\n\n\tif (((pg_entry) & (EPT_PG_RD | EPT_PG_WR | EPT_PG_EX)))\n\t{\n\t\tKERN_WARN(\"Guest page 0x%08x is already mapped to 0x%llx.\\n\",\n\t\t\t  gpa, (pg_entry & EPT_ADDR_MASK));\n\t\treturn 1;\n\t}\n\n\treturn ept_add_mapping(gpa, hpa, mem_type);\n}*)\n\n  Function ept_mmap_spec (gpa hpa : Z) (memtype: Z) (adt: RData) : option (RData * Z) :=\n    match ept_get_page_entry_spec gpa adt with\n      | Some hpa' =>\n        if (zle_le 0 hpa' Int.max_unsigned) then\n              if zle_lt 0 memtype 4096 then\n\n                (if zeq (Z.land hpa' EPTEPERM) 0 \n                 then ept_add_mapping_spec gpa hpa memtype adt\n                 else Some (adt, 1))\n              else None\n        else None\n      | _ => None\n    end.\n\n(*\n/*\n * Set the access permission of the guest physical address gpa.\n */\nvoid\nept_set_permission(uintptr_t gpa, uint32_t perm): Change the type of perm\n{\n\tuint64_t entry;\n\n\tentry = ept_get_page_entry(gpa);\n\n\tept_set_page_entry(gpa, (entry & ~(uint64_t) 0x7) | (perm & 0x7));\n\n\treturn;\n}*)\n\n  Function ept_set_permission_spec (gpa perm: Z) (adt: RData) : option RData :=\n    match ept_get_page_entry_spec gpa adt with\n      | Some hpa' =>\n        if (zle_le 0 hpa' Int.max_unsigned) then\n        (let hpa := Z.lor (Z.land hpa' EPT_NO_PERM) \n                         (Z.land perm EPTEPERM) in\n        ept_set_page_entry_spec gpa hpa adt)\n        else None\n      | _ => None\n    end.\n\n  Function ept_init_spec (mbi_adr:Z) (adt: RData) : option RData :=\n    match (init adt, pg adt, ikern adt, ihost adt, ipt adt) with\n      | (false, false, true, true, true) => \n        Some adt {vmxinfo: real_vmxinfo} {pg: true} {LAT: real_LAT (LAT adt)} {nps: real_nps}\n             {AC: real_AC} {init: true} {PT: 0} {ptpool: real_pt (ptpool adt)}\n             {idpde: real_idpde (idpde adt)}\n             {smspool: real_smspool (smspool adt)}\n             {abtcb: ZMap.set 0 (AbTCBValid RUN (-1)) (real_abtcb (abtcb adt))}\n             {abq: real_abq (abq adt)} {cid: 0} {syncchpool: real_syncchpool (syncchpool adt)}\n             {ept: real_ept (ept adt)}\n      | _ => None\n    end.\n\nEnd OBJ_EPT.\n\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import CommonTactic.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import AuxLemma.\n\nSection OBJ_SIM.\n\n  Context `{data : CompatData RData}.\n  Context `{data0 : CompatData RData}.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Notation HDATAOps := (cdata (cdata_prf := data) RData).\n  Notation LDATAOps := (cdata (cdata_prf := data0) RData).\n\n  Context `{rel_prf: CompatRel _ (memory_model_ops:= memory_model_ops) _\n                               (stencil_ops:= stencil_ops) HDATAOps LDATAOps}.\n\n  Section EPT_GET_PAGE_ENTRY_SIM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ept}.\n\n    Lemma ept_get_page_entry_exist:\n      forall s habd labd gpa hpa f,\n        ept_get_page_entry_spec gpa habd = Some hpa\n        -> relate_AbData s f habd labd\n        -> ept_get_page_entry_spec gpa labd = Some hpa.\n    Proof.\n      unfold ept_get_page_entry_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ept_eq; eauto. intros.\n      revert H. subrewrite.\n    Qed.\n\n  End EPT_GET_PAGE_ENTRY_SIM.\n\n  Section EPT_SET_PAGE_ENTRY_SIM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ept}.\n\n    Lemma ept_set_page_entry_exist:\n      forall s habd habd' labd gpa hpa' f,\n        ept_set_page_entry_spec gpa hpa' habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', ept_set_page_entry_spec gpa hpa' labd = Some labd'\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold ept_set_page_entry_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ept_eq; eauto. intros.\n      revert H. subrewrite. subdestruct.\n      inv HQ; refine_split'; trivial.\n\n      apply relate_impl_ept_update. assumption.\n    Qed.\n\n  End EPT_SET_PAGE_ENTRY_SIM.\n\n  Section EPT_ADD_MAPPING_SIM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2 : relate_impl_ept}.\n\n    Lemma ept_add_mapping_exist:\n      forall s habd habd' labd gpa hpa' memtype n f,\n        ept_add_mapping_spec gpa hpa' memtype habd = Some (habd', n)\n        -> relate_AbData s f habd labd\n        -> exists labd', ept_add_mapping_spec gpa hpa' memtype labd = Some (labd', n)\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      Local Opaque Z.shiftl.\n\n      unfold ept_add_mapping_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ept_eq; eauto. intros.\n      revert H. subrewrite. subdestruct.\n      inv HQ; refine_split'; trivial.\n\n      apply relate_impl_ept_update. assumption.\n    Qed.\n\n    Context {mt1: match_impl_iflags}.\n    Context {mt2: match_impl_ept}.\n\n    Lemma ept_add_mapping_match:\n      forall s d d' m gpa hpa' memtype n f,\n        ept_add_mapping_spec gpa hpa' memtype d = Some (d', n)\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold ept_add_mapping_spec; intros. subdestruct; inv H; trivial.\n      eapply match_impl_ept_update. assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) ept_add_mapping_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) ept_add_mapping_spec}.\n\n    Lemma ept_add_mapping_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem ept_add_mapping_spec)\n            (id ↦ gensem ept_add_mapping_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit ept_add_mapping_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply ept_add_mapping_match; eauto.\n    Qed.\n\n  End EPT_ADD_MAPPING_SIM.\n\n  Section EPT_GPA_TO_HPA_SIM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2 : relate_impl_ept}.\n\n    Lemma ept_gpa_to_hpa_exist:\n      forall s habd labd gpa va f,\n        ept_gpa_to_hpa_spec gpa habd = Some va\n        -> relate_AbData s f habd labd\n        -> ept_gpa_to_hpa_spec gpa labd = Some va.\n    Proof.\n      Local Opaque Z.land Z.lor.\n\n      unfold ept_gpa_to_hpa_spec. intros.\n      destruct (ept_get_page_entry_spec gpa habd) eqn:Hdestruct; try discriminate.\n      exploit ept_get_page_entry_exist; eauto. intros.\n      revert H. subrewrite.\n    Qed.\n\n  End EPT_GPA_TO_HPA_SIM.\n\n  Section EPT_MMAP_SIM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2 : relate_impl_ept}.\n\n    Lemma ept_mmap_exist:\n      forall s habd habd' labd gpa hpa' memtype n f,\n        ept_mmap_spec gpa hpa' memtype habd = Some (habd', n)\n        -> relate_AbData s f habd labd\n        -> exists labd', ept_mmap_spec gpa hpa' memtype labd = Some (labd', n)\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      Local Opaque Z.land.\n\n      unfold ept_mmap_spec; intros.\n      destruct (ept_get_page_entry_spec gpa habd) eqn:Hdestruct; try discriminate.\n      exploit ept_get_page_entry_exist; eauto. intros.\n      revert H. subrewrite. subdestruct.\n\n      - eapply ept_add_mapping_exist; eassumption.\n      - inv HQ; refine_split'; trivial.\n    Qed.\n\n  End EPT_MMAP_SIM.\n\n  Section EPT_SET_PERMISSION_SIM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2 : relate_impl_ept}.\n\n    Lemma ept_set_permission_exist:\n      forall s habd habd' labd gpa perm f,\n        ept_set_permission_spec gpa perm habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', ept_set_permission_spec gpa perm labd = Some labd'\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      Local Opaque Z.land Z.lor.\n\n      unfold ept_set_permission_spec; intros.\n      destruct (ept_get_page_entry_spec gpa habd) eqn:Hdestruct; try discriminate.\n      exploit ept_get_page_entry_exist; eauto. intros.\n      subrewrite'. subdestruct.\n\n      eapply ept_set_page_entry_exist; eassumption.\n    Qed.\n\n  End EPT_SET_PERMISSION_SIM.\n\n  Section EPT_INIT_SIM.\n\n    Context `{real_params: RealParams}.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re3: relate_impl_LAT}.\n    Context {re4: relate_impl_nps}.\n    Context {re5: relate_impl_init}.\n    Context {re6: relate_impl_PT}.\n    Context {re7: relate_impl_ptpool}.\n    Context {re8: relate_impl_idpde}.\n    Context {re9: relate_impl_smspool}.\n    Context {re10: relate_impl_abtcb}.\n    Context {re11: relate_impl_abq}.\n    Context {re12: relate_impl_cid}.\n    Context {re13: relate_impl_syncchpool}.\n    Context {re14: relate_impl_vmxinfo}.\n    Context {re15: relate_impl_ept}.\n    Context {re16: relate_impl_AC}.\n\n    Lemma ept_init_exist:\n      forall s habd habd' labd mbi_adr f,\n        ept_init_spec mbi_adr habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', ept_init_spec mbi_adr labd = Some labd'\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold ept_init_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_init_eq; eauto.\n      exploit relate_impl_LAT_eq; eauto.\n      exploit relate_impl_ptpool_eq; eauto.\n      exploit relate_impl_idpde_eq; eauto.\n      exploit relate_impl_cid_eq; eauto.\n      exploit relate_impl_abq_eq; eauto.\n      exploit relate_impl_abtcb_eq; eauto.\n      exploit relate_impl_syncchpool_eq; eauto.\n      exploit relate_impl_vmxinfo_eq; eauto.\n      exploit relate_impl_smspool_eq; eauto.\n      exploit relate_impl_ept_eq; eauto. intros.\n      revert H. subrewrite. subdestruct.\n      inv HQ; refine_split'; trivial.\n\n      apply relate_impl_ept_update.\n      apply relate_impl_syncchpool_update.\n      apply relate_impl_cid_update.\n      apply relate_impl_abq_update.\n      apply relate_impl_abtcb_update.\n      apply relate_impl_smspool_update.\n      apply relate_impl_idpde_update.\n      apply relate_impl_ptpool_update.\n      apply relate_impl_PT_update.\n      apply relate_impl_init_update.\n      apply relate_impl_AC_update.\n      apply relate_impl_nps_update.\n      apply relate_impl_LAT_update.\n      apply relate_impl_pg_update.\n      apply relate_impl_vmxinfo_update.\n      assumption.\n    Qed.\n\n    Context {mt1: match_impl_iflags}.\n    Context {mt2: match_impl_ipt}.\n    Context {mt3: match_impl_LAT}.\n    Context {mt4: match_impl_nps}.\n    Context {mt5: match_impl_init}.\n    Context {mt6: match_impl_PT}.\n    Context {mt7: match_impl_ptpool}.\n    Context {mt8: match_impl_idpde}.\n    Context {mt9: match_impl_smspool}.\n    Context {mt10: match_impl_abtcb}.\n    Context {mt11: match_impl_abq}.\n    Context {mt12: match_impl_cid}.\n    Context {mt13: match_impl_syncchpool}.\n    Context {mt14: match_impl_vmxinfo}.\n    Context {mt15: match_impl_ept}.\n    Context {mt16: match_impl_AC}.\n\n    Lemma ept_init_match:\n      forall s d d' m  mbi_adr f,\n        ept_init_spec mbi_adr d = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold ept_init_spec; intros. subdestruct. inv H.\n      eapply match_impl_ept_update.\n      eapply match_impl_syncchpool_update.\n      eapply match_impl_cid_update.\n      eapply match_impl_abq_update.\n      eapply match_impl_abtcb_update.\n      eapply match_impl_smspool_update.\n      eapply match_impl_idpde_update.\n      eapply match_impl_ptpool_update.\n      eapply match_impl_PT_update.\n      eapply match_impl_init_update.\n      eapply match_impl_AC_update.\n      eapply match_impl_nps_update.\n      eapply match_impl_LAT_update.\n      eapply match_impl_pg_update.\n      eapply match_impl_vmxinfo_update.\n      assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) ept_init_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) ept_init_spec}.\n\n    Lemma ept_init_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem ept_init_spec)\n            (id ↦ gensem ept_init_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit ept_init_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply ept_init_match; eauto.\n    Qed.\n\n  End EPT_INIT_SIM.\n\n  Section EPT_INV_SIM.\n\n    Context {re1: relate_impl_iflags}.\n\n    Lemma ept_invalidate_mappings_exists:\n      forall habd labd z s f,\n        ept_invalidate_mappings_spec habd = Some z ->\n        relate_AbData s f habd labd ->\n        ept_invalidate_mappings_spec labd = Some z.\n    Proof.\n      unfold ept_invalidate_mappings_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      revert H. subrewrite. \n    Qed.\n\n    Lemma ept_invalidate_mappings_sim:\n      forall id,\n        sim (crel RData RData) (id ↦ gensem ept_invalidate_mappings_spec)\n            (id ↦ gensem ept_invalidate_mappings_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      match_external_states_simpl.\n      erewrite ept_invalidate_mappings_exists; eauto.\n      reflexivity.\n    Qed.\n\n  End EPT_INV_SIM.\n\nEnd OBJ_SIM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/objects/ObjEPT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.24245866726969195}}
{"text": "(* \n This is the definition of formal syntax for Dan Grossman's Thesis, \n  \"SAFE PROGRAMMING AT THE C LEVEL OF ABSTRACTION\". \n\n  Defining type safety, page 67.\n\n*)\n\nSet Implicit Arguments.\nRequire Export LanguageModuleDef.\nRequire Export StaticSemanticsKindingAndContextWellFormedness.\nRequire Export StaticSemanticsKindingAndContextWellFormednessLemmas.\nRequire Export TermWeakeningProof.\nRequire Export Tacticals.\n\n(* May need some lemmas from the 3 case. *)\n\nLemma A_3_Heap_Weakening_1_strengthen_quantification:\n  forall (u u' : Upsilon) (g g': Gamma),\n    U.extends u u' = true ->\n    G.extends g g' = true ->\n    WFC ddot u' g' ->\n    forall (h : Heap) (g'' : Gamma), \n      htyp u g h g'' ->\n      htyp u' g' h g''.\nProof.\n  intros u u' g g' uext gext WFCder h g'' htypder.\n  htyp_ind_cases (induction htypder) Case; try solve[crush].\n  Case \"htyp u g h ([(x, tau)] ++ g')\".\n   apply htyp_xv with (h':= h') (v:= v); try assumption.\n   apply IHhtypder in uext; try assumption.\n   apply A_2_Term_Weakening_3 with (u:= u') (g:= g') ; try assumption.\n   admit.\n   apply U.extends_refl.\n   admit.\n   apply G.extends_refl.\n   admit.\nAdmitted.\n\n(* Correct. *)\n\nLemma A_3_Heap_Weakening_2:\n  forall (u : Upsilon) (h : H),\n    refp h u ->\n    forall (h' : H),\n      refp (h ++ h') u.\nProof.\n  intros u h refpder.\n  refp_ind_cases (induction refpder) Case.\n  Case  \"refp h []\".\n   intros.\n   constructor.\n  Case \"refp h ([(x, p, tau')] ++ u)\".\n   intros.\n   apply refp_pack \n   with (tau:= tau) (alpha:= alpha) (k:= k) (v:= v) (v':= v'); try assumption.\n   apply getH_Some_weakening; try assumption.\n   apply refp_weakening; try assumption.\nQed.\n", "meta": {"author": "briangmilnes", "repo": "CycloneCoqSemantics", "sha": "190c0fc57d5aebfde244efb06a119f108de7a150", "save_path": "github-repos/coq/briangmilnes-CycloneCoqSemantics", "path": "github-repos/coq/briangmilnes-CycloneCoqSemantics/CycloneCoqSemantics-190c0fc57d5aebfde244efb06a119f108de7a150/3.1/HeapWeakeningProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.24238178604150765}}
{"text": "Require Import Coq.Structures.OrderedType.\nRequire Import Coq.Structures.OrderedTypeEx.\nRequire Import VST.floyd.functional_base.\nRequire Import common.\nRequire Import tactics.\nRequire Import DB.lemmas.\n\nRequire Import DB.functional.key.\nRequire Import DB.functional.cursored_kv.\nRequire Import DB.functional.keyslice.\nRequire Import DB.functional.bordernode.\n\nImport List.\nImport Lists.List.ListNotations.\n\nModule KeysliceType := Z_as_OT.\nModule KeysliceFacts := OrderedTypeFacts Z_as_OT.\n(* On going rewrite:\n * 1. support cursor\n * 2. add addresses into the data type.\n *)\n\nModule Trie (Node: FLATTENABLE_TABLE KeysliceType) (* <: FLATTENABLE_TABLE TrieKey *).\n  Definition key := TrieKey.t.\n\n  Module Flattened := SortedListTable TrieKey.\n  Module NodeFacts := FlattenableTableFacts KeysliceType Node.\n\n  Section Types.\n    Context {value: Type}.\n    (* Notes: reason for removing the [val] from the constructor:\n     *        originally the kvstore contains a cursor for it, therefore there is necessity for another struct,\n     *        it's not the case in final impl, and therefore we directly use the btree as pointer to a trienode *)\n    Inductive trie: Type :=\n    | trienode_of: val ->\n                   Node.table val -> (* The btree data *)\n                   Node.Flattened.table (val * BorderNode.table value trie) -> (* abstract data *)\n                   trie.\n    Definition table: Type := option trie.\n    Definition bordernode := BorderNode.table value trie.\n    Hint Constructors trie: trie.\n\n    (* this is only a pseudo height, cause we only care about termination *)\n    (* some random hack so that it pass subterm check *)\n    Definition bnode_height {trie_height: trie -> nat} (bnode: bordernode): nat :=\n      match bnode with\n      | (prefixes, Some (inr t')) =>\n        trie_height t'\n      | _ =>\n        O\n      end.\n    Fixpoint trie_height (t: trie): nat :=\n      match t with\n      | trienode_of _ _ listform =>\n        1 + fold_right Nat.max O (map (compose (@bnode_height trie_height) (compose snd snd)) listform)\n      end.\n\n    Lemma fold_max_le: forall x l, In x l -> (x <= fold_right Nat.max O l)%nat.\n    Proof.\n      intros.\n      induction l.\n      - inv H.\n      - inv H.\n        + simpl.\n          apply Nat.le_max_l.\n        + simpl.\n          specialize (IHl H0).\n          apply le_trans with (fold_right Nat.max 0 l)%nat.\n          * assumption.\n          * apply Nat.le_max_r.\n    Qed.\n\n    (* order of bordernode? *)\n    (* first the prefixes, then the suffix? *)\n    (* Placement of cursor:\n     * For keys that already existed in the store, just place at the place\n     * For keys that are not in the store, place them at the furtherest bordernode entry *)\n    Definition cursor: Type := list (trie * Node.cursor val * bordernode * BorderNode.cursor).\n\n    Definition empty (t: trie) :=\n      match t with\n      | trienode_of _ trieform listform =>\n        Node.empty trieform /\\ Node.Flattened.empty listform\n      end.\n\n    Fixpoint flatten_prefix_array (prefix: string) (keyslice: KeysliceType.t)\n             (prefixes: list (option value)) (idx: Z): Flattened.table value :=\n      match prefixes with\n      | Some v :: t =>\n        ((prefix ++ (reconstruct_keyslice (keyslice, idx))), v) :: flatten_prefix_array prefix keyslice t (idx + 1)\n      | None :: t =>\n        flatten_prefix_array prefix keyslice t (idx + 1)\n      | [] => []\n      end.\n\n    Definition flatten_bordernode {flatten_trie_aux: TrieKey.t -> trie -> Flattened.table value}\n             (prefix: string) (kv: KeysliceType.t * (val * bordernode)) :=\n      let (keyslice, augmented_bnode) := kv in\n      let (_, bnode) := augmented_bnode in\n      let (prefixes, suffix) := bnode in\n        flatten_prefix_array prefix keyslice prefixes 0 ++\n      match suffix with\n      | Some (inl (suffix_key, suffix_value)) => [(prefix ++ (reconstruct_keyslice (keyslice, keyslice_length)) ++ suffix_key, suffix_value)]\n      | Some (inr t') =>\n        flatten_trie_aux (prefix ++ (reconstruct_keyslice (keyslice, keyslice_length))) t'\n      | None =>\n        []\n      end.\n\n    Fixpoint flatten_aux (prefix: TrieKey.t) (t: trie) {struct t}: Flattened.table value :=\n      match t with\n      (* the tableform is of no interest here *)\n      | trienode_of _ _ listform =>\n        flat_map (@flatten_bordernode flatten_aux prefix) listform\n      end.\n\n    Definition flatten_bnode := @flatten_bordernode flatten_aux.\n\n    Definition flatten (t: trie): Flattened.table value := flatten_aux [] t.\n\n    Function strict_first_cursor (t: trie) {measure trie_height t}: option cursor :=\n      match t with\n      | trienode_of _ tableform listform =>\n        match Node.Flattened.get_value (Node.Flattened.first_cursor listform) listform with\n        | Some (_, bnode) =>\n          match BorderNode.next_cursor (BorderNode.before_prefix 1) bnode with\n          | BorderNode.before_prefix len =>\n            match (BorderNode.get_prefix len bnode) with\n            | Some _ =>\n              Some [(t, Node.first_cursor tableform, bnode, BorderNode.before_prefix len)]\n            | None => None\n            end\n          | BorderNode.before_suffix =>\n            match snd bnode with\n            | Some (inl _) =>\n              Some [(t, Node.first_cursor tableform, bnode, BorderNode.before_suffix)]\n            | Some (inr t') =>\n              match strict_first_cursor t' with\n              | Some c' => Some ((t, Node.first_cursor tableform, bnode, BorderNode.before_suffix) :: c')\n              | None => None\n              end\n            | None =>\n              None\n            end\n          | BorderNode.after_suffix => None\n          end\n        | None => None\n        end\n      end.\n    Proof.\n      intros.\n      simpl.\n      apply Nat.lt_succ_r.\n      apply fold_max_le.\n      subst.\n      destruct bnode.\n      simpl in teq3; subst.\n      unfold Node.Flattened.get_value in teq0.\n      match_tac in teq0; [ | congruence].\n      destruct p.\n      inv teq0.\n      apply Node.Flattened.get_in_weak in H.\n      match goal with\n      | |- context [map ?f' listform] => apply in_map with (f := f') in H\n      end.\n      simpl in H.\n      assumption.\n    Defined.\n\n    (* This [normalize_cursor] returns a cursor when the \"next\" kv locates,\n     * also, it tries to eliminate an [BorderNode.after_suffix] cursor position *)\n    Fixpoint normalize_cursor (c: cursor): option cursor :=\n      match c with\n      | [] => None (* given an empty cursor, we can never return the next cursor *)\n      | (trienode_of addr tableform listform, table_cursor, bnode, bnode_cursor) :: c' =>\n        let t := trienode_of addr tableform listform in\n        match normalize_cursor c' with\n        (* if the subcursor can go next, then there is no need for ourselves to move *)\n        | Some c'' => Some ((t, table_cursor, bnode, bnode_cursor) :: c'')\n        (* if the subcursor cannot go on, then we need to move the current to the next *)\n        | None =>\n          (* try move inside the bnode first *)\n          match BorderNode.next_cursor bnode_cursor bnode with\n          | BorderNode.before_prefix len =>\n            Some [(t, table_cursor, bnode, (BorderNode.before_prefix len))]\n          | BorderNode.before_suffix =>\n            match snd bnode with\n            | None => (* impossible *) None\n            | Some (inl _) =>\n              Some [(t, table_cursor, bnode, BorderNode.before_suffix)]\n            | Some (inr t') =>\n              match strict_first_cursor t' with\n              | Some c' =>\n                Some ((t, table_cursor, bnode, BorderNode.before_suffix) :: c')\n              | None =>\n                None\n              end\n            end\n          | BorderNode.after_suffix =>\n            (* try move to next cursor at node level *)\n            let table_cursor' := Node.next_cursor table_cursor tableform in\n            match Node.get_key table_cursor' tableform with\n            | Some key =>\n              match Node.Flattened.get_value (Node.Flattened.make_cursor key listform) listform with\n              | Some (_, bnode') =>\n                (* no need to repeatedly move to next if we have maintained the invariant that no dead end exists\n                 * in the trie *)\n                match BorderNode.next_cursor (BorderNode.before_prefix 1) bnode' with\n                | BorderNode.before_prefix len =>\n                  match (BorderNode.get_prefix len bnode') with\n                  | None => (* impossible *) None\n                  | Some _ => Some [(t, table_cursor', bnode', (BorderNode.before_prefix len))]\n                  end\n                | BorderNode.before_suffix =>\n                  match (snd bnode') with\n                  | None => (* impossible *) None\n                  | Some (inl _) => Some [(t, table_cursor', bnode', BorderNode.before_suffix)]\n                  | Some (inr t') =>\n                    match strict_first_cursor t' with\n                    | Some c' =>\n                      Some ((t, table_cursor', bnode', BorderNode.before_suffix) :: c')\n                    | None =>\n                      None\n                    end\n                  end\n                | BorderNode.after_suffix => None\n                end\n              | None => None (* we cannot handle it at this level *)\n              end\n            | None => None\n            end\n          end\n        end\n      end.\n\n    Function make_cursor (k: key) (t: trie) {measure length k}: cursor :=\n      let keyslice := get_keyslice k in\n      match t with\n      | trienode_of _ tableform listform =>\n        match Node.Flattened.get_exact keyslice listform with\n        | Some (_, bnode) =>\n          if (Z_le_dec (Zlength k) keyslice_length) then\n          (* prefix case, which we need only to return the current cursor *)\n            [(t, Node.make_cursor keyslice tableform, bnode, BorderNode.before_prefix (Zlength k))]\n          else\n            match snd bnode with\n            | None =>\n              [(t, Node.make_cursor keyslice tableform, bnode, BorderNode.after_suffix)]\n            | Some (inl (k', _)) =>\n              (* we need to compare the suffix here, if the key input is greater\n               * then we need to move to next here\n               * because the semantics of [get] need it *)\n              if (TrieKeyFacts.lt_dec k' (get_suffix k)) then\n                [(t, Node.make_cursor keyslice tableform, bnode, BorderNode.after_suffix)]\n              else\n                [(t, Node.make_cursor keyslice tableform, bnode, BorderNode.before_suffix)]\n            | Some (inr t') =>\n                (t, Node.make_cursor keyslice tableform, bnode, BorderNode.before_suffix) :: make_cursor (get_suffix k) t'\n            end\n        | None =>\n          (* either we get to the last cursor, or we does ont have a matched key *)\n          []\n        end\n      end.\n    Proof.\n      intros.\n      unfold get_suffix.\n      rewrite Nat2Z.inj_lt.\n      rewrite <- ?Zlength_correct.\n      assert (Zlength k > keyslice_length) by (apply Znot_le_gt; assumption).\n      rewrite Zlength_sublist by rep_lia.\n      rep_lia.\n    Defined.\n\n    Fixpoint get_raw (c: cursor): option (key * value) :=\n      match c with\n      | (trienode_of _ tableform _, table_cursor, bnode, bnode_cursor) :: c' =>\n        match Node.get_key table_cursor tableform with\n        | Some keyslice =>\n          match bnode_cursor with\n          | BorderNode.before_prefix len =>\n            match BorderNode.get_prefix len bnode with\n            | Some v => Some (reconstruct_keyslice (keyslice, len), v)\n            | None => None\n            end\n          | BorderNode.before_suffix =>\n            match (snd bnode) with\n            | Some (inl (k, v)) => Some (reconstruct_keyslice (keyslice, keyslice_length) ++ k, v)\n            | Some (inr t') =>\n              match get_raw c' with\n              | Some (k', v') => Some (reconstruct_keyslice (keyslice, keyslice_length) ++ k', v')\n              | None => None\n              end\n            | None => None\n            end\n          | BorderNode.after_suffix => None\n          end\n        | None => None\n        end\n      | [] => None\n      end.\n\n    Definition get (c: cursor) (t: trie): option (key * value) :=\n      match normalize_cursor c with\n      | Some c' =>\n        get_raw c'\n      | None => None\n      end.\n\n    Definition get_key (c: cursor) (t: trie): option key :=\n      match get c t with\n      | Some (k, _) => Some k\n      | None => None\n      end.\n\n    Definition get_value (c: cursor) (t: trie): option value :=\n      match get c t with\n      | Some (_, v) => Some v\n      | None => None\n      end.\n\n    (* for now, the put function ignore the cursor input *)\n    (* we might need some optimization later *)\n\n    Definition create_pair_aux_dec {A: Type}: forall k1 k2: list A,\n        {Zlength k1 <= keyslice_length \\/ Zlength k2 <= keyslice_length} +\n        {Zlength k1 > keyslice_length /\\ Zlength k2 > keyslice_length}.\n    Proof.\n      intros.\n      destruct (Z_le_gt_dec (Zlength k1) keyslice_length);\n        destruct (Z_le_gt_dec (Zlength k2) keyslice_length);\n        match goal with\n        | [H: _ <= _ |- _] => left; lia\n        | _ => right; lia\n        end.\n    Qed.\n\n    Inductive create_pair (k1 k2: key) (v1 v2: value): cursor -> trie -> Prop :=\n    | create_pair_case1: forall emptylist emptytable listform tableform listcursor tablecursor bnode_addr addr,\n        let keyslice1 := get_keyslice k1 in\n        let keyslice2 := get_keyslice k2 in\n        keyslice1 = keyslice2 ->\n        Zlength k1 <= keyslice_length \\/ Zlength k2 <= keyslice_length ->\n        let bnode := BorderNode.put_value k1 v1 BorderNode.empty in\n        let bnode := BorderNode.put_value k2 v2 bnode in\n        Node.Flattened.empty emptylist ->\n        Node.Flattened.put keyslice1 (bnode_addr, bnode)\n                           (Node.Flattened.first_cursor emptylist) emptylist\n                           listcursor listform ->\n        Node.empty emptytable ->\n        Node.put keyslice1 bnode_addr (Node.first_cursor emptytable) emptytable tablecursor tableform ->\n        create_pair k1 k2 v1 v2\n                    [(trienode_of addr tableform listform, tablecursor, bnode, BorderNode.length_to_cursor (Zlength k1))]\n                    (trienode_of addr tableform listform)\n    | create_pair_case2: forall emptylist emptytable listform tableform listcursor tablecursor bnode_addr c' t' addr,\n        let keyslice1 := get_keyslice k1 in\n        let keyslice2 := get_keyslice k2 in\n        keyslice1 = keyslice2 ->\n        Zlength k1 > keyslice_length /\\ Zlength k2 > keyslice_length ->\n        create_pair (get_suffix k1) (get_suffix k2) v1 v2 c' t' ->\n        let bnode := BorderNode.put_link t' BorderNode.empty in\n        Node.Flattened.empty emptylist ->\n        Node.Flattened.put keyslice1 (bnode_addr, bnode)\n                           (Node.Flattened.first_cursor emptylist) emptylist\n                           listcursor listform ->\n        Node.empty emptytable ->\n        Node.put keyslice1 bnode_addr (Node.first_cursor emptytable) emptytable tablecursor tableform ->\n        create_pair k1 k2 v1 v2\n                    ((trienode_of addr tableform listform, tablecursor, bnode, BorderNode.before_suffix) :: c')\n                    (trienode_of addr tableform listform)\n    | create_pair_case3: forall emptylist emptytable listform1 listform2 tableform1 tableform2 listcursor1 listcursor2 tablecursor1 tablecursor2 bnode_addr1 bnode_addr2 addr,\n        let keyslice1 := get_keyslice k1 in\n        let keyslice2 := get_keyslice k2 in\n        keyslice1 <> keyslice2 ->\n        let bnode1 := BorderNode.put_value k1 v1 BorderNode.empty in\n        let bnode2 := BorderNode.put_value k2 v2 BorderNode.empty in\n        Node.Flattened.empty emptylist ->\n        Node.Flattened.put keyslice2 (bnode_addr2, bnode2)\n                           (Node.Flattened.first_cursor emptylist) emptylist\n                           listcursor2 listform2 ->\n        Node.Flattened.put keyslice1 (bnode_addr1, bnode1)\n                           (Node.Flattened.first_cursor listform2) listform2\n                           listcursor1 listform1 ->\n        Node.empty emptytable ->\n        Node.put keyslice2 bnode_addr2 (Node.first_cursor emptytable) emptytable tablecursor2 tableform2 ->\n        Node.put keyslice1 bnode_addr1 (Node.first_cursor tableform2) tableform2 tablecursor1 tableform1 ->\n        create_pair k1 k2 v1 v2\n                    [(trienode_of addr tableform1 listform1, tablecursor1, bnode1, BorderNode.length_to_cursor (Zlength k1))]\n                    (trienode_of addr tableform1 listform1).\n\n    Inductive put (k: key) (v: value): cursor -> trie -> cursor -> trie -> Prop :=\n    | put_case1: forall tableform listform listform' listcursor listcursor' bnode_addr bnode c addr,\n        let keyslice := get_keyslice k in\n        Node.Flattened.get_exact keyslice listform = Some (bnode_addr, bnode) ->\n        Zlength k <= keyslice_length ->\n        let bnode := BorderNode.put_prefix (Zlength k) v bnode in\n        Node.Flattened.abs_rel listcursor listform ->\n        Node.Flattened.put keyslice (bnode_addr, bnode)\n                           listcursor listform\n                           listcursor' listform' ->\n        let tablecursor := Node.make_cursor keyslice tableform in\n        put k v c (trienode_of addr tableform listform)\n            [(trienode_of addr tableform listform', tablecursor, bnode, BorderNode.before_prefix (Zlength k))]\n            (trienode_of addr tableform listform')\n    | put_case2: forall tableform listform listform' listcursor listcursor' bnode_addr bnode c t' c' t'' c'' addr,\n        let keyslice := get_keyslice k in\n        Node.Flattened.get_exact keyslice listform = Some (bnode_addr, bnode) ->\n        Zlength k > keyslice_length ->\n        BorderNode.get_link bnode = Some t' ->\n        put (get_suffix k) v c' t' c'' t'' ->\n        let bnode := BorderNode.put_link t'' bnode in\n        Node.Flattened.abs_rel listcursor listform ->\n        Node.Flattened.put keyslice (bnode_addr, bnode)\n                           listcursor listform\n                           listcursor' listform' ->\n        let tablecursor := Node.make_cursor keyslice tableform in\n        put k v c (trienode_of addr tableform listform)\n            ((trienode_of addr tableform listform', tablecursor, bnode, BorderNode.before_suffix) :: c'')\n            (trienode_of addr tableform listform')\n    | put_case3: forall tableform listform listform' listcursor listcursor' bnode_addr bnode c addr,\n        let keyslice := get_keyslice k in\n        Node.Flattened.get_exact keyslice listform = Some (bnode_addr, bnode) ->\n        Zlength k > keyslice_length ->\n        snd bnode = None ->\n        let bnode := BorderNode.put_suffix (get_suffix k) v bnode in\n        Node.Flattened.abs_rel listcursor listform ->\n        Node.Flattened.put keyslice (bnode_addr, bnode)\n                           listcursor listform\n                           listcursor' listform' ->\n        let tablecursor := Node.make_cursor keyslice tableform in\n        put k v c (trienode_of addr tableform listform)\n            [(trienode_of addr tableform listform', tablecursor, bnode, BorderNode.before_suffix)]\n            (trienode_of addr tableform listform')\n    | put_case4: forall tableform listform listform' listcursor listcursor' bnode_addr bnode c addr,\n        let keyslice := get_keyslice k in\n        Node.Flattened.get_exact keyslice listform = Some (bnode_addr, bnode) ->\n        Zlength k > keyslice_length ->\n        BorderNode.test_suffix (get_suffix k) bnode = true ->\n        let bnode := BorderNode.put_suffix (get_suffix k) v bnode in\n        Node.Flattened.abs_rel listcursor listform ->\n        Node.Flattened.put keyslice (bnode_addr, bnode)\n                           listcursor listform\n                           listcursor' listform' ->\n        let tablecursor := Node.make_cursor keyslice tableform in\n        put k v c (trienode_of addr tableform listform)\n            [(trienode_of addr tableform listform', tablecursor, bnode, BorderNode.before_suffix)]\n            (trienode_of addr tableform listform')\n    | put_case5: forall tableform listform listform' listcursor listcursor' bnode_addr bnode c c' t' k' v' addr,\n        let keyslice := get_keyslice k in\n        Node.Flattened.get_exact keyslice listform = Some (bnode_addr, bnode) ->\n        Zlength k > keyslice_length ->\n        BorderNode.get_suffix_pair bnode = Some (k', v') ->\n        get_suffix k <> k' ->\n        create_pair (get_suffix k) k' v v' c' t' ->\n        let bnode := BorderNode.put_link t' bnode in\n        Node.Flattened.abs_rel listcursor listform ->\n        Node.Flattened.put keyslice (bnode_addr, bnode)\n                           listcursor listform\n                           listcursor' listform' ->\n        let tablecursor := Node.make_cursor keyslice tableform in\n        put k v c (trienode_of addr tableform listform)\n            ((trienode_of addr tableform listform', tablecursor, bnode, BorderNode.before_suffix) :: c')\n            (trienode_of addr tableform listform')\n    | put_case6: forall tableform tableform' listform listform' tablecursor tablecursor' listcursor listcursor' bnode_addr c addr,\n        let keyslice := get_keyslice k in\n        Node.Flattened.get_exact keyslice listform = None ->\n        let bnode := BorderNode.put_value k v BorderNode.empty in\n        Node.Flattened.abs_rel listcursor listform ->\n        Node.Flattened.put keyslice (bnode_addr, bnode)\n                           listcursor listform\n                           listcursor' listform' ->\n        Node.abs_rel tablecursor tableform ->\n        Node.put keyslice bnode_addr\n                           tablecursor tableform\n                           tablecursor' tableform' ->\n        put k v c (trienode_of addr tableform listform)\n            [(trienode_of addr tableform' listform', tablecursor', bnode, BorderNode.before_suffix)]\n            (trienode_of addr tableform' listform').\n\n    (* This strict_next_cursor does not necessarily produce a valid position([BorderNode.after_suffix]) *)\n    (* not sure if this work *)\n    Fixpoint strict_next_cursor (c: cursor): cursor :=\n      match c with\n      | [] => []\n      | [(trienode_of addr tableform listform, table_cursor, bnode, bnode_cursor)] =>\n        match bnode_cursor with\n        | BorderNode.before_prefix len =>\n          if Z_lt_dec len keyslice_length then\n            [(trienode_of addr tableform listform, table_cursor, bnode, BorderNode.before_prefix (len + 1))]\n          else\n            [(trienode_of addr tableform listform, table_cursor, bnode, BorderNode.after_suffix)]\n        | BorderNode.before_suffix => [(trienode_of addr tableform listform, table_cursor, bnode, BorderNode.after_suffix)]\n        | BorderNode.after_suffix =>\n          let table_cursor' := Node.next_cursor table_cursor tableform in\n          match Node.get_key table_cursor' tableform with\n          | Some key =>\n            match Node.Flattened.get_value (Node.Flattened.make_cursor key listform) listform with\n            | Some bnode' =>\n              [(trienode_of addr tableform listform, table_cursor, bnode, BorderNode.before_prefix 1)]\n            | None => []\n            end\n          | None => [] (* should not be the case in the only scenario of usage *)\n          end\n        end\n      | current_slice :: c' =>\n        current_slice :: (strict_next_cursor c')\n      end.\n\n    Definition next_cursor (c: cursor) (t: table): cursor :=\n      match normalize_cursor c with\n      | Some c' =>\n        strict_next_cursor c'\n      | None =>\n        []\n      end.\n\n    Definition prev_cursor (c: cursor) (t: table): cursor. Admitted.\n    Definition first_cursor (t: table): cursor. Admitted.\n    Definition last_cursor (t: table): cursor. Admitted.\n\n    Definition key_inrange (k: Z): Prop :=\n      0 <= k <= Ptrofs.max_unsigned.\n\n    (* optional invariant for table: there is no dead end in the trie\n     * question: does empty root node count as dead end?\n     * answer(informal): No. because it won't turn the result of any operation from\n     *                   valid cursor to an invalid one\n     *                   Dec. 4: I'm actually not sure about this now. *)\n    Inductive trie_correct: trie -> Prop :=\n    | table_correct_intro tableform listform: forall addr,\n        Node.table_correct tableform ->\n        Node.Flattened.table_correct listform ->\n        map fst (Node.flatten tableform) = map fst listform ->\n        map snd (Node.flatten tableform) = map (compose fst snd) listform ->\n        Forall (compose bordernode_correct (compose snd snd)) listform ->\n        Forall (compose key_inrange fst) listform ->\n        Zlength listform > 1 -> (* no dead end *)\n        trie_correct (trienode_of addr tableform listform)\n    with\n    bordernode_correct: bordernode -> Prop :=\n    | bordernode_correct_nil prefixes:\n        Zlength prefixes = keyslice_length -> (* no dead end *)\n        Exists (fun v => v <> None) prefixes ->\n        bordernode_correct (prefixes, None)\n    | bordernode_correct_ext prefixes k v:\n        Zlength prefixes = keyslice_length ->\n        0 < Zlength k ->\n        bordernode_correct (prefixes, Some (inl (k, v)))\n    | bordernode_correct_int prefixes t':\n        Zlength prefixes = keyslice_length ->\n        trie_correct t' ->\n        bordernode_correct (prefixes, Some (inr t')).\n    Hint Constructors trie_correct: trie.\n\n    Fixpoint cursor_correct_aux (c: cursor) (p: option trie): Prop :=\n      match c with\n      | (trienode_of addr tableform listform, table_cursor, bnode, bnode_cursor) :: c' =>\n        match p with (* that the previous pointer actually points to this cursor slice *)\n        | Some t => t = trienode_of addr tableform listform\n        | None => True\n        end /\\\n        (* trie_correct (trienode_of addr tableform listform) /\\ *) (* that cursor correct entails trie correct *)\n        Node.cursor_correct table_cursor /\\ (* that the two component-cursors are actually correct *)\n        BorderNode.cursor_correct bnode_cursor /\\\n        match Node.get_key table_cursor tableform with (* find the bordernode pointing to from the btree *)\n        | Some key =>\n          match Node.Flattened.get_value (Node.Flattened.make_cursor key listform) listform with\n          | Some (_, bnode') =>\n            bnode' = bnode /\\\n            match bnode_cursor with (* go to next level of btree *)\n            | BorderNode.before_prefix len =>\n              c' = []\n            | BorderNode.before_suffix =>\n              match snd bnode with\n              | Some (inr t') => cursor_correct_aux c' (Some t')\n              | _ => c' = []\n              end\n            | BorderNode.after_suffix => c' = []\n            end\n          | None => False (* should not be the case in the only scenario of usage *)\n          end\n        | None => False (* there should be no cursor with a table cursor pointing at the end of table *)\n        end\n      | [] => True\n      end.\n\n    Definition cursor_correct (c: cursor): Prop := cursor_correct_aux c None.\n\n    Definition cursor_trie_assoc (c: cursor) (t: trie): Prop :=\n      cursor_correct c /\\ trie_correct t /\\\n      match c with\n      | (t', _, _, _) :: _ =>\n        (* This should suffice because the [cursor_correct] regulates the structure *)\n        t' = t\n      | [] => True\n      end.\n\n    Definition key_rel (k: key) (c: cursor) (t: trie): Prop :=\n      normalize_cursor c = normalize_cursor (make_cursor k t).\n\n    Definition eq_cursor (c1 c2: cursor) (t: table): Prop. Admitted.\n\n    Ltac simplify :=\n      destruct_conjs;\n      destruct_exists;\n      repeat (match goal with\n              | var: _ * _ |- _ => destruct var\n              | H: (_, _) = (_, _) |- _ => inv H\n              | H: ?f _ = ?f _ |- _ => injection H; intros; subst; clear H\n              | H: ?f _ _ = ?f _ _ |- _ => injection H; intros; subst; clear H\n              | H: _ /\\ _ |- _ => destruct_conjs\n              | |- _ /\\ _ => split\n              | H: fst ?p = _ |- _ => destruct p; simpl in H; subst\n              | H: snd ?p = _ |- _ => destruct p; simpl in H; subst\n              | H: _ = fst ?p |- _ => destruct p; simpl in H; subst\n              | H: _ = snd ?p |- _ => destruct p; simpl in H; subst\n              | H: match _ with _ => _ end |- _ => match_tac in H; subst\n              | H: match _ with _ => _ end = _ |- _ => match_tac in H; subst\n              | H: _ = match _ with _ => _ end |- _ => match_tac in H; subst\n              | H: False |- _ => destruct H\n              end; simpl in *);\n      eauto;\n      try discriminates.\n\n    Lemma cursor_correct_aux_weaken: forall h c,\n        cursor_correct_aux c (Some h) ->\n        cursor_correct_aux c None.\n    Proof.\n      intros.\n      destruct c.\n      - firstorder.\n      - simpl in *.\n        destruct p as [[[[]]]].\n        simplify.\n    Qed.\n\n    Lemma cursor_correct_subcursor_correct: forall h c,\n        cursor_correct (h :: c) ->\n        cursor_correct c.\n    Proof.\n      intros.\n      unfold cursor_correct in H.\n      simpl in H.\n      simplify.\n      eapply cursor_correct_aux_weaken; eauto.\n    Qed.\n\n    Lemma trie_correct_subtrie_correct: forall p tableform listform k v l t' c,\n        trie_correct (trienode_of p tableform listform) ->\n        Node.Flattened.get c listform = Some (k, (v, (l, Some (inr t')))) ->\n        trie_correct t'.\n    Proof.\n      intros.\n      inv H.\n      apply Node.Flattened.get_in_weak in H0.\n      eapply Forall_forall in H8; [ | eauto].\n      simpl in H8.\n      inv H8.\n      assumption.\n    Qed.\n\n    Lemma cursor_correct_bnode_cursor_correct: forall t tc b bc c,\n        cursor_correct ((t, tc, b, bc) :: c) ->\n        BorderNode.cursor_correct bc.\n    Proof.\n      intros.\n      unfold cursor_correct in H.\n      simpl in H.\n      simplify.\n    Qed.\n\n    Lemma strict_first_cursor_normalized: forall t c,\n        trie_correct t ->\n        strict_first_cursor t = Some c ->\n        normalize_cursor c = Some c.\n    Proof.\n      intros.\n      remember (trie_height t).\n      generalize dependent t.\n      generalize dependent c.\n      induction n using (well_founded_induction lt_wf); intros.\n      destruct t.\n      rewrite strict_first_cursor_equation in H1.\n      simplify.\n      - simpl.\n        erewrite BorderNode.next_cursor_idempotent; [ | eassumption].\n        reflexivity.\n      - simpl.\n        erewrite BorderNode.next_cursor_idempotent; [ | eassumption].\n        repeat match_tac; simplify.\n        pose proof H2; unfold Node.Flattened.get_value in H2; simplify.\n        apply Node.Flattened.get_in_weak in H6.\n        apply H with (y := trie_height t1) in H4.\n        + rewrite H4 in H1.\n          simplify.\n        + apply in_map with (f := compose (@bnode_height trie_height) (compose snd snd)) in H6.\n          simpl in H6.\n          apply fold_max_le in H6.\n          unfold trie_height at 2.\n          apply le_lt_n_Sm.\n          assumption.\n        + inv H0.\n          eapply Forall_forall in H13; [ | eauto].\n          simpl in H13.\n          inv H13.\n          assumption.\n        + reflexivity.\n    Qed.\n\n    (* Lemma cursor_correct_bordernode_correct: forall t tc b bc c, *)\n    (*     cursor_correct ((t, tc, b, bc) :: c) -> *)\n    (*     bordernode_correct b. *)\n    (* Proof. *)\n    (*   intros. *)\n    (*   unfold cursor_correct in H. *)\n    (*   simpl in H. *)\n    (*   destruct t. *)\n    (*   rename v into addr. *)\n    (*   destruct H as [_ [? [_ [_ ?]]]]. *)\n    (*   destruct (Node.get_key tc t) eqn:Heqn; try contradiction. *)\n    (*   destruct (Node.Flattened.get_value (Node.Flattened.make_cursor k t0) t0) as [[] | ] eqn:Heqn'; *)\n    (*     try contradiction. *)\n    (*   inv H0. *)\n    (*   assert (exists k', Node.Flattened.get (Node.Flattened.make_cursor k t0) t0 = Some (k', (v, b))). { *)\n    (*     unfold Node.Flattened.get_value in Heqn'. *)\n    (*     destruct (Node.Flattened.get (Node.Flattened.make_cursor k t0) t0) eqn:Heqn''. *)\n    (*     - inv Heqn''. *)\n    (*       destruct p as [k' ?]. *)\n    (*       exists k'. *)\n    (*       inv Heqn'. *)\n    (*       assumption. *)\n    (*     - inv Heqn'. *)\n    (*   } *)\n    (*   destruct H0 as [k' ?]. *)\n    (*   inv H. *)\n    (*   apply Node.Flattened.get_in_weak in H0. *)\n    (*   rewrite Forall_forall in H9. *)\n    (*   apply H9 in H0. *)\n    (*   simpl in H0. *)\n    (*   assumption. *)\n    (* Qed. *)\n\n    Lemma cursor_correct_aux_trie_assoc: forall t c,\n        trie_correct t ->\n        cursor_correct_aux c (Some t) ->\n        cursor_trie_assoc c t.\n    Proof.\n      intros.\n      unfold cursor_trie_assoc.\n      repeat split.\n      - eapply cursor_correct_aux_weaken.\n        eauto.\n      - assumption.\n      - match_tac; simplify.\n        simpl in H0.\n        simplify.\n    Qed.\n\n    Lemma normalize_idempotent: forall c1 c2 t,\n        cursor_trie_assoc c1 t ->\n        cursor_trie_assoc c2 t ->\n        normalize_cursor c1 = Some c2 ->\n        normalize_cursor c2 = Some c2.\n    Proof.\n      intros.\n      generalize dependent t.\n      generalize dependent c2.\n      induction c1; intros.\n      - inv H1.\n      - inv H.\n        inv H0.\n        unfold cursor_correct in H2.\n        simpl in H2.\n        simpl in H1.\n        repeat (simplify; match_tac);\n          try match goal with\n              | H1: BorderNode.next_cursor ?bnode_cursor1 ?bnode = ?bnode_cursor2 |- _ =>\n                match goal with\n                | H2: BorderNode.next_cursor bnode_cursor2 bnode = ?bnode_cursor3 |- _ =>\n                  apply BorderNode.next_cursor_idempotent in H1; rewrite H1 in H2; simplify\n                end\n              end; (* kill 56 goals *)\n          try match goal with\n              | H: context [Node.Flattened.get_value] |- _ => unfold Node.Flattened.get_value in H; match_tac in H; simplify\n              end;\n          try match goal with\n              | H1: trie_correct (trienode_of _ _ ?listform) |- _ =>\n                match goal with\n                | H2: Node.Flattened.get _ listform = Some (_, (_, (_, Some (inr _)))) |- _ =>\n                  pose proof H2; eapply trie_correct_subtrie_correct in H2; [ | eauto]\n                end\n              end;\n          try match goal with\n              | H1: strict_first_cursor ?t = Some ?c1 |- _ =>\n                match goal with\n                | H2: normalize_cursor c1 = Some ?c2 |- _ =>\n                  eapply strict_first_cursor_normalized in H1; [ | eauto]; rewrite H1 in H2; simplify\n                end\n              end;\n          try match goal with\n              | H: cursor_correct (_ :: _) |- _ => unfold cursor_correct in H; simpl in H; simplify\n              end.\n        + specialize (IHc1 c3 eq_refl t ltac:(eapply cursor_correct_aux_trie_assoc; eauto) ltac:(eapply cursor_correct_aux_trie_assoc; eauto)).\n          rewrite IHc1 in H1.\n          simplify.\n        + specialize (IHc1 c3 eq_refl t ltac:(eapply cursor_correct_aux_trie_assoc; eauto) ltac:(eapply cursor_correct_aux_trie_assoc; eauto)).\n          rewrite IHc1 in H1.\n          simplify.\n        + specialize (IHc1 c3 eq_refl t ltac:(eapply cursor_correct_aux_trie_assoc; eauto) ltac:(eapply cursor_correct_aux_trie_assoc; eauto)).\n          rewrite IHc1 in H1.\n          simplify.\n    Qed.\n\n    (* [c1] associated with trie, [c2] associated with subtrie, [c3] associated with table *)\n    (* Lemma get_subtrie: forall tableform listform bnode t' c1 c2 c3 ks k e, *)\n    (*     cursor_correct c1 -> *)\n    (*     key_rel (reconstruct_keyslice (ks, keyslice_length) ++ k) c1 (trienode_of tableform listform) -> *)\n    (*     abs_rel c1 (trienode_of tableform listform) -> *)\n    (*     key_rel k c2 t' -> *)\n    (*     abs_rel c2 t' -> *)\n    (*     Node.Flattened.key_rel ks c3 listform -> *)\n    (*     Node.Flattened.abs_rel c3 listform -> *)\n    (*     Node.Flattened.get c3 listform = Some (ks, bnode) /\\ *)\n    (*     BorderNode.get_suffix None bnode = trie_of t' /\\ *)\n    (*     get_raw c2 = Some (k, e) *)\n    (*     <-> *)\n    (*     get_raw c1 = Some (reconstruct_keyslice (ks, keyslice_length) ++ k, e). *)\n    (* Proof. *)\n    (*   intros. *)\n    (*   remember (reconstruct_keyslice (ks, keyslice_length)) as prefix. *)\n    (*   assert (get_keyslice (prefix ++ k) = ks) by admit. *)\n    (*   assert (get_suffix (prefix ++ k) = k) by admit. (* for sure these is true *) *)\n    (*   split; intros. *)\n    (*   - destruct H8 as [? []]. *)\n    (*     unfold key_rel in H0. *)\n    (*     rewrite make_cursor_equation in H0. *)\n    (*     rewrite H6 in H0. *)\n    (*     unfold abs_rel in H1. *)\n    (*     unfold Node.Flattened.get_exact in H0. *)\n    (*     replace (Node.Flattened.get (Node.Flattened.make_cursor ks listform) listform) with *)\n    (*         (Node.Flattened.get c3 listform) in H0 by trie_crush. *)\n    (*     rewrite H8 in H0. *)\n    (*     rewrite if_true in H0 by auto. *)\n    (*     rewrite if_false in H0 by admit. *)\n    (*     destruct bnode as [[prefixes suffix_key] suffix_value]. *)\n    (*     simpl fst in H0. *)\n    (*     destruct suffix_key as [suffix_key | ]; simpl in H8; try solve [inv H9]. *)\n    (*     simpl in H9. *)\n    (*     subst. *)\n    (*     simpl BorderNode.get_suffix in H0. *)\n    (*     cbv iota beta in H0. *)\n    (*     rewrite H7 in H0. *)\n    (*     repeat eliminate_hyp; subst. *)\n    (*     + simpl in H0. *)\n    (*       eliminate_hyp. *)\n    (*       change (next_cursor_bnode BorderNode.before_suffix (prefixes, None, trie_of t') *)\n    (*                                 (Z.to_nat (keyslice_length + 2))) with BorderNode.before_suffix in H0. *)\n    (*       simpl in H0. *)\n    (*       (* [strict_first_cursor] should be [Some] *) *)\n    (*       admit. *)\n    (*     + rename c0 into tc. *)\n    (*       rename b into bc. *)\n    (*       rename t into b. *)\n    (*       simpl. *)\n    (* Admitted. *)\n\n\n    Ltac eliminate_hyp :=\n      match goal with\n      | [H: match ?e with _ => _ end |- _] =>\n        destruct e eqn:H; rewrite ?H in *; try congruence; try contradiction\n      | [H: _ = match ?e with _ => _ end |- _] =>\n        let H := fresh \"Heqn\" in\n        destruct e eqn:H; rewrite ?H in *; try congruence; try contradiction\n      | [H: match ?e with _ => _ end = _ |- _] =>\n        let H := fresh \"Heqn\" in\n        destruct e eqn:H; rewrite ?H in *; try congruence; try contradiction\n      | [H: _ /\\ _ |- _ ] => destruct H\n      | [H: Some _ = Some _ |- _ ] => inv H\n      | [H: trie_correct (trienode_of _ _ _) |- _ ] => inv H\n      | [|- context[if _ then _ else _] ] =>\n        first [\n              rewrite if_true by (first [solve [eauto with trie] | KeysliceFacts.order])\n            | rewrite if_false by (first [solve [eauto with trie] | KeysliceFacts.order])\n          ]\n      end.\n\n    Hint Resolve Node.Flattened.make_cursor_abs: trie.\n    Hint Resolve Node.Flattened.first_cursor_abs: trie.\n    Hint Resolve Node.Flattened.last_cursor_abs: trie.\n    Hint Resolve Node.Flattened.make_cursor_key: trie.\n    Hint Resolve Node.Flattened.eq_cursor_get: trie.\n    Hint Resolve Node.Flattened.key_rel_eq_cursor: trie.\n    Hint Resolve Node.Flattened.put_correct: trie.\n    Hint Resolve Node.Flattened.empty_correct: trie.\n    Hint Resolve Node.Flattened.simple_empty_correct: trie.\n    Hint Resolve Node.make_cursor_abs: trie.\n    Hint Resolve Node.first_cursor_abs: trie.\n    Hint Resolve Node.last_cursor_abs: trie.\n    Hint Resolve Node.make_cursor_key: trie.\n    Hint Resolve Node.eq_cursor_get: trie.\n    Hint Resolve Node.key_rel_eq_cursor: trie.\n    Hint Resolve Node.put_correct: trie.\n    Hint Resolve Node.empty_correct: trie.\n    Hint Resolve BorderNode.empty_invariant: trie.\n    Hint Resolve BorderNode.put_prefix_invariant: trie.\n    Hint Unfold Node.Flattened.get_key: trie.\n    Hint Unfold Node.Flattened.get_value: trie.\n    Hint Unfold Node.Flattened.get_exact: trie.\n\n    Ltac basic_trie_solve :=\n      autounfold with trie in *; repeat eliminate_hyp;\n      try first [ solve [eauto 10 with trie] | rep_lia | congruence].\n\n    Opaque Node.Flattened.put get_keyslice reconstruct_keyslice get_suffix.\n\n    Lemma get_exact_correct: forall {value: Type} k (t: Node.Flattened.table value) bnode,\n        Node.Flattened.get_exact k t = Some bnode ->\n        Node.Flattened.get (Node.Flattened.make_cursor k t) t = Some (k, bnode).\n    Proof.\n      intros.\n      basic_trie_solve; simplify.\n    Qed.\n\n    Lemma get_exact_correct_key: forall {value: Type} k (t: Node.Flattened.table value) bnode,\n        Node.Flattened.get_exact k t = Some bnode ->\n        Node.Flattened.get_key (Node.Flattened.make_cursor k t) t = Some k.\n    Proof.\n      intros.\n      basic_trie_solve; simplify.\n    Qed.\n\n    Lemma get_exact_correct_value: forall {value: Type} k (t: Node.Flattened.table value) bnode,\n        Node.Flattened.get_exact k t = Some bnode ->\n        Node.Flattened.get_value (Node.Flattened.make_cursor k t) t = Some bnode.\n    Proof.\n      intros.\n      basic_trie_solve; simplify.\n    Qed.\n\n    Lemma get_exact_correct_table_key: forall k addr tableform listform bnode,\n        trie_correct (trienode_of addr tableform listform) ->\n        Node.Flattened.get_exact k listform = Some bnode ->\n        Node.get_key (Node.make_cursor k tableform) tableform = Some k.\n    Proof.\n      intros.\n      basic_trie_solve.\n      simplify.\n      replace (Node.get_key (Node.make_cursor k0 tableform) tableform) with\n          (Node.Flattened.get_key (Node.Flattened.make_cursor k0 (Node.flatten tableform)) (Node.flatten tableform)).\n      - unfold Node.Flattened.get_key.\n        replace (Some k0) with\n            (Node.Flattened.get_key (Node.Flattened.make_cursor k0 listform) listform) by\n            (unfold Node.Flattened.get_key; match_tac; simplify).\n        pose proof (Node.flatten_invariant _ H3) as [? _].\n        apply Node.Flattened.same_key_result with k0; basic_trie_solve.\n      - symmetry.\n        unfold Node.get_key, Node.Flattened.get_key.\n        pose proof (Node.flatten_invariant _ H3) as [? ?].\n        specialize (H0 k0\n                       (Node.make_cursor k0 tableform)\n                       (Node.Flattened.make_cursor k0 (Node.flatten tableform))).\n        specialize (H0 ltac:(basic_trie_solve) ltac:(basic_trie_solve) ltac:(basic_trie_solve) ltac:(basic_trie_solve)).\n        rewrite H0.\n        reflexivity.\n    Qed.\n\n    Lemma table_key_list_key: forall k addr tableform listform,\n        trie_correct (trienode_of addr tableform listform) ->\n        Node.get_key (Node.make_cursor k tableform) tableform =\n        Node.Flattened.get_key (Node.Flattened.make_cursor k listform) listform.\n    Proof.\n      intros.\n      basic_trie_solve.\n      pose proof (@Node.flatten_invariant val).\n      specialize (H tableform ltac:(assumption)) as [? ?].\n      replace (Node.get_key (Node.make_cursor k tableform) tableform) with\n          (Node.Flattened.get_key (Node.Flattened.make_cursor k (Node.flatten tableform)) (Node.flatten tableform)).\n      2: {\n        unfold Node.Flattened.get_key, Node.get_key.\n        specialize (H0 k\n                       (Node.make_cursor k tableform)\n                       (Node.Flattened.make_cursor k (Node.flatten tableform))).\n        specialize (H0 ltac:(basic_trie_solve) ltac:(basic_trie_solve) ltac:(basic_trie_solve) ltac:(basic_trie_solve)).\n        rewrite H0.\n        reflexivity.\n      }\n      apply Node.Flattened.same_key_result with k; basic_trie_solve.\n    Qed.\n\n    (* Lemma table_addr_list_addr: forall k tableform listform, *)\n    (*     table_correct (trienode_of tableform listform) -> *)\n    (*     Node.get_key (Node.make_cursor k tableform) tableform = *)\n    (*     Node.Flattened.get_key (Node.Flattened.make_cursor k listform) listform -> *)\n    (*     Node.get_value (Node.make_cursor k tableform) tableform = *)\n    (*     match Node.Flattened.get_exact (Node.Flattened.make_cursor k listform) listform with *)\n    (*     | Some (addr, _) => Some addr *)\n    (*     | None => None *)\n    (*     end. *)\n    (* Proof. *)\n    (*   intros. *)\n    (*   unfold Node.get_key, Node.get_value, Node.Flattened.get_exact, Node.Flattened.get_key in *. *)\n    (*   basic_trie_solve. *)\n    (*   -  *)\n    (*   pose proof (@Node.flatten_invariant val). *)\n    (*   specialize (H tableform ltac:(assumption)) as [? ?]. *)\n    (*   replace (Node.get_key (Node.make_cursor k tableform) tableform) with *)\n    (*       (Node.Flattened.get_key (Node.Flattened.make_cursor k (Node.flatten tableform)) (Node.flatten tableform)). *)\n    (*   2: { *)\n    (*     unfold Node.Flattened.get_key, Node.get_key. *)\n    (*     specialize (H0 k *)\n    (*                    (Node.make_cursor k tableform) *)\n    (*                    (Node.Flattened.make_cursor k (Node.flatten tableform))). *)\n    (*     specialize (H0 ltac:(basic_trie_solve) ltac:(basic_trie_solve) ltac:(basic_trie_solve) ltac:(basic_trie_solve)). *)\n    (*     rewrite H0. *)\n    (*     reflexivity. *)\n    (*   } *)\n    (*   apply Node.Flattened.same_key_result with k; basic_trie_solve. *)\n    (* Qed. *)\n\n    Lemma leaves_correct_bordernode_correct: forall bnode listform c,\n        Forall (compose bordernode_correct snd) listform ->\n        Node.Flattened.get_value c listform = Some bnode ->\n        bordernode_correct bnode.\n    Proof.\n      intros.\n      unfold Node.Flattened.get_value in H0.\n      destruct (Node.Flattened.get c listform) as [[] | ] eqn:Heqn; try congruence.\n      inv H0.\n      pose proof (Node.Flattened.get_in_weak listform c k bnode Heqn).\n      rewrite Forall_forall in H.\n      apply H in H0.\n      simpl in H0.\n      assumption.\n    Qed.\n    Hint Resolve leaves_correct_bordernode_correct: trie.\n\n    Lemma leaves_correct_bordernode_correct': forall bnode listform k c v,\n        Forall (compose bordernode_correct (compose (@snd val _) snd)) listform ->\n        Node.Flattened.get c listform = Some (k, (v, bnode)) ->\n        bordernode_correct bnode.\n    Proof.\n      intros.\n      destruct (Node.Flattened.get c listform) as [[? []] | ] eqn:Heqn; try congruence.\n      inv H0.\n      pose proof (Node.Flattened.get_in_weak listform _ k (v, bnode) Heqn).\n      rewrite Forall_forall in H.\n      apply H in H0.\n      simpl in H0.\n      assumption.\n    Qed.\n    Hint Resolve leaves_correct_bordernode_correct': trie.\n\n    Lemma bordernode_correct_invariant: forall bnode,\n        bordernode_correct bnode -> BorderNode.invariant bnode.\n    Proof.\n      intros.\n      inv H; unfold BorderNode.invariant; simpl; list_solve.\n    Qed.\n    Hint Resolve bordernode_correct_invariant: trie.\n\n    Lemma bordernode_correct_subtrie_correct: forall prefixes t,\n        bordernode_correct (prefixes, Some (inr t)) ->\n        trie_correct t.\n    Proof.\n      intros.\n      inv H.\n      assumption.\n    Qed.\n    Hint Resolve bordernode_correct_subtrie_correct: trie.\n\n    Ltac trie_solve :=\n      repeat match goal with\n      | [|- context [Node.Flattened.get_key (Node.Flattened.make_cursor _ _) _]] =>\n        try solve [erewrite get_exact_correct_key by eauto];\n        idtac\n      | [|- context [Node.get_key (Node.make_cursor _ _) _]] =>\n        try solve [erewrite get_exact_correct_table_key by eauto];\n        idtac\n      | [|- context [BorderNode.get_prefix _ (BorderNode.put_prefix _ _ _)]] =>\n        try first [\n              rewrite BorderNode.get_put_prefix_same by basic_trie_solve\n            | rewrite BorderNode.get_put_prefix_diff by basic_trie_solve\n            ]\n      | [H: Node.Flattened.put _ _ _ _ _ ?l |- context [Node.Flattened.get _ ?l]] =>\n        try first [\n              erewrite Node.Flattened.get_put_same by basic_trie_solve\n            ]\n      | [H: Node.put _ _ _ _ _ ?l |- context [Node.get _ ?l]] =>\n        try first [\n              erewrite Node.get_put_same by basic_trie_solve\n            ]\n      end;\n      basic_trie_solve.\n\n    Lemma create_pair_normalized: forall k1 k2 v1 v2 c t,\n        0 < Zlength k1 ->\n        0 < Zlength k2 ->\n        k1 <> k2 ->\n        create_pair k1 k2 v1 v2 c t ->\n        normalize_cursor (make_cursor k1 t) =\n        Some (make_cursor k1 t).\n    Proof.\n      intros k1.\n      remember (length k1) as n.\n      generalize dependent k1.\n      induction n using (well_founded_induction lt_wf); intros.\n      inv H3;\n        unfold keyslice1, keyslice2 in *; clear keyslice1 keyslice2.\n      destruct (Z_le_gt_dec (Zlength k1) keyslice_length) as [Hmath1 | Hmath1];\n        destruct (Z_le_gt_dec (Zlength k2) keyslice_length) as [Hmath2 | Hmath2];\n        try lia; clear H5; subst bnode bnode0.\n      - assert (Zlength k1 <> Zlength k2) by admit.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        trie_solve.\n        unfold BorderNode.put_value.\n        trie_solve.\n        unfold normalize_cursor.\n        rewrite BorderNode.next_cursor_terminate_permute1 by\n            first [\n                solve [trie_solve]\n              | apply BorderNode.next_cursor_terminate; trie_solve ].\n        trie_solve.\n      - rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        trie_solve.\n        simpl.\n        unfold BorderNode.put_value.\n        trie_solve.\n        rewrite BorderNode.next_cursor_terminate_permute2 by\n            first [\n                solve [trie_solve]\n              | apply BorderNode.next_cursor_terminate; trie_solve ].\n        trie_solve.\n      - rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        trie_solve.\n        simpl.\n        rewrite ?if_false by auto.\n        unfold BorderNode.put_value.\n        trie_solve.\n        simpl.\n        rewrite if_false by TrieKeyFacts.order.\n        simpl.\n        change (BorderNode.next_cursor BorderNode.before_suffix\n                                       (upd_Znth (Zlength k2 - 1) (list_repeat (Z.to_nat keyslice_length) None) (Some v2), Some (inl (get_suffix k1, v1))))\n          with (BorderNode.before_suffix).\n        reflexivity.\n      - rewrite make_cursor_equation.\n        simpl.\n        unfold Node.Flattened.get_exact.\n        trie_solve.\n        simpl.\n        eapply H with (y := length (get_suffix k1)) in H6;\n          trie_solve;\n          change (get_suffix) with (fun (k: string) => sublist keyslice_length (Zlength k) k) in *;\n          simpl in *.\n        + rewrite H6.\n          reflexivity.\n        + rewrite <- ?ZtoNat_Zlength.\n          rewrite Zlength_sublist by rep_lia.\n          apply Z2Nat.inj_lt; rep_lia.\n        + rewrite Zlength_sublist; rep_lia.\n        + rewrite Zlength_sublist; rep_lia.\n        + admit.\n      - subst bnode1 bnode2.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        trie_solve.\n        if_tac.\n        + simpl.\n          unfold BorderNode.put_value.\n          rewrite ?if_true by auto.\n          rewrite BorderNode.next_cursor_terminate; trie_solve.\n        + unfold BorderNode.put_value.\n          rewrite ?if_false by auto.\n          simpl.\n          rewrite ?if_false by auto.\n          simpl.\n          change (BorderNode.next_cursor\n                    BorderNode.before_suffix\n                    (list_repeat (Z.to_nat keyslice_length) None, Some (inl (get_suffix k1, v1))))\n            with (BorderNode.before_suffix).\n          reflexivity.\n    Admitted.\n\n    Lemma make_cursor_put_normalized: forall k v c1 t1 c2 t2,\n        Zlength k <> 0 ->\n        trie_correct t1 ->\n        put k v c1 t1 c2 t2 ->\n        normalize_cursor (make_cursor k t2) = Some (make_cursor k t2).\n    Proof.\n      intros k.\n      remember (length k) as n.\n      generalize dependent k.\n      induction n using (well_founded_induction lt_wf); intros.\n      inv H2; inv H1.\n      - unfold keyslice in *; clear keyslice.\n        rewrite make_cursor_equation.\n        simpl.\n        unfold Node.Flattened.get_exact.\n        trie_solve.\n        simpl.\n        subst bnode0.\n        rewrite BorderNode.next_cursor_terminate; trie_solve.\n      - unfold keyslice in *; clear keyslice.\n        unfold bnode0 in *; clear bnode0.\n        unfold BorderNode.get_link in *.\n        destruct bnode as [? [[|]|]]; simplify.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        erewrite Node.Flattened.get_put_same by trie_solve.\n        trie_solve.\n        unfold BorderNode.get_suffix_pair.\n        simpl.\n        eapply H with (y := length (get_suffix k)) in H6; trie_solve.\n        * rewrite H6.\n          reflexivity.\n        * rewrite <- ?ZtoNat_Zlength.\n           change (get_suffix k) with (sublist keyslice_length (Zlength k) k).\n           rewrite Zlength_sublist by rep_lia.\n           apply Z2Nat.inj_lt; rep_lia.\n        * change (get_suffix k) with (sublist keyslice_length (Zlength k) k).\n          rewrite Zlength_sublist; rep_lia.\n      - unfold keyslice in *; clear keyslice.\n        unfold bnode0 in *; clear bnode0.\n        destruct bnode as [? [|]]; simpl in *; simplify.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        erewrite Node.Flattened.get_put_same by trie_solve.\n        trie_solve.\n        unfold BorderNode.get_suffix_pair.\n        simpl.\n        trie_solve.\n      - unfold keyslice in *; clear keyslice.\n        unfold bnode0 in *; clear bnode0.\n        unfold BorderNode.test_suffix in H5.\n        destruct bnode as [? [[|]|]]; simplify.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        erewrite Node.Flattened.get_put_same by trie_solve.\n        trie_solve.\n        unfold BorderNode.get_suffix_pair; simpl.\n        trie_solve.\n      - unfold keyslice in *; clear keyslice.\n        unfold bnode0 in *; clear bnode0.\n        destruct bnode as [? [[|]|]]; simplify.\n        rewrite make_cursor_equation.\n        simpl.\n        unfold Node.Flattened.get_exact.\n        trie_solve.\n        simpl.\n        eapply create_pair_normalized in H7; change get_suffix with (fun (k: string) => sublist keyslice_length (Zlength k) k) in *; simpl in *.\n        + rewrite H7.\n          reflexivity.\n        + rewrite Zlength_sublist; rep_lia.\n        + assert (bordernode_correct (l, Some (inl (s, v0)))) by trie_solve.\n          inv H1.\n          simplify.\n        + assumption.\n      - unfold keyslice in *; clear keyslice.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        erewrite Node.Flattened.get_put_same by trie_solve.\n        rewrite ?if_true by KeysliceFacts.order.\n        if_tac.\n        + simpl.\n          subst bnode.\n          unfold BorderNode.put_value.\n          rewrite ?if_true by auto.\n          rewrite BorderNode.next_cursor_terminate by trie_solve.\n          reflexivity.\n        + subst bnode.\n          unfold BorderNode.put_value.\n          rewrite ?if_false by auto.\n          unfold BorderNode.get_suffix_pair; simpl.\n          trie_solve.\n    Qed.\n\n    (* Lemma create_pair_correct: forall k1 k2 v1 v2 a, *)\n    (*     table_correct (fst (create_pair k1 k2 v1 v2 a)). *)\n    (* Proof. *)\n    (*   intros k1. *)\n    (*   remember (length k1) as n. *)\n    (*   generalize dependent k1. *)\n    (*   induction n using (well_founded_induction lt_wf); intros. *)\n    (*   rewrite create_pair_equation. *)\n    (*   destruct (@Node.empty val a) eqn:Heqn_empty. *)\n    (*   replace t with (fst (@Node.empty val a)) by (rewrite Heqn_empty; reflexivity). *)\n    (*   destruct (consume a0) eqn:Heqn_consume0. *)\n    (*   if_tac. *)\n    (*   destruct (Z_le_gt_dec (Zlength k1) keyslice_length) as [Hmath1 | Hmath1]; *)\n    (*     destruct (Z_le_gt_dec (Zlength k2) keyslice_length) as [Hmath2 | Hmath2]; *)\n    (*     try if_tac; try lia. *)\n    (*   - destruct (Node.put (get_keyslice k1) v (Node.first_cursor (fst (Node.empty a))) (fst (Node.empty a), l)) *)\n    (*       as [? []] eqn:Heqn_node_put. *)\n    (*     replace t0 with *)\n    (*       (fst (snd (Node.put (get_keyslice k1) v (Node.first_cursor (fst (Node.empty a))) (fst (Node.empty a), l)))) *)\n    (*       by (rewrite Heqn_node_put; reflexivity). *)\n    (*     simpl. *)\n    (*     constructor; trie_solve. *)\n    (*     + rewrite NodeFacts.simple_put_permute by trie_solve. *)\n    (*       rewrite NodeFacts.empty_flatten_empty. *)\n    (*       change (@Node.Flattened.put) with *)\n    (*           (fun (elt : Type) (k : Node.Flattened.key) (v : elt) (c : Node.Flattened.cursor elt) *)\n    (*              (table_with_allocator : Node.Flattened.table elt * Node.Flattened.allocator) => *)\n    (*              let (t, a) := table_with_allocator in (c, (Node.Flattened.put_aux k v t, a)) *)\n    (*           ). *)\n    (*       simpl. *)\n    (*       reflexivity. *)\n    (*     + change (@Node.Flattened.put) with *)\n    (*           (fun (elt : Type) (k : Node.Flattened.key) (v : elt) (c : Node.Flattened.cursor elt) *)\n    (*              (table_with_allocator : Node.Flattened.table elt * Node.Flattened.allocator) => *)\n    (*              let (t, a) := table_with_allocator in (c, (Node.Flattened.put_aux k v t, a)) *)\n    (*           ). *)\n    (*       simpl. *)\n    (*       repeat constructor. *)\n    (*       simpl. *)\n    (*       admit. *)\n    (*     + admit. *)\n    (*   - *)\n    (* Admitted. *)\n\n    (* Lemma create_pair_abs: forall k1 k2 v1 v2 a, *)\n    (*     0 < Zlength k1 -> *)\n    (*     0 < Zlength k2 -> *)\n    (*     k1 <> k2 -> *)\n    (*     abs_rel (make_cursor k1 (fst (create_pair k1 k2 v1 v2 a))) (fst (create_pair k1 k2 v1 v2 a)). *)\n    (* Proof. *)\n    (*   intros. *)\n\n    Lemma get_create_same1: forall k1 k2 c' v1 v2 c t,\n        0 < Zlength k1 ->\n        0 < Zlength k2 ->\n        k1 <> k2 ->\n        create_pair k1 k2 v1 v2 c t ->\n        cursor_trie_assoc c' t ->\n        key_rel k1 c' t ->\n        get c' t = Some (k1, v1).\n    Proof.\n      intros k1.\n      remember (length k1) as n.\n      generalize dependent k1.\n      induction n using (well_founded_induction lt_wf); intros.\n      unfold get.\n      unfold key_rel in H5.\n      rewrite H5.\n      inv H3.\n      destruct (Z_le_gt_dec (Zlength k1) keyslice_length) as [Hmath1 | Hmath1];\n        destruct (Z_le_gt_dec (Zlength k2) keyslice_length) as [Hmath2 | Hmath2];\n        try lia; clear H7; subst bnode bnode0.\n      - unfold keyslice1 in *; clear keyslice1.\n        assert (Zlength k1 <> Zlength k2) by admit.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        trie_solve.\n        simpl.\n        unfold BorderNode.put_value.\n        trie_solve.\n        rewrite BorderNode.next_cursor_terminate_permute1 by\n            first [\n                solve [trie_solve]\n              | apply BorderNode.next_cursor_terminate; trie_solve ].\n        trie_solve.\n        simpl.\n        unfold Node.get_key.\n        trie_solve.\n        rewrite upd_Znth_diff by (rewrite ?upd_Znth_Zlength; rewrite ?Zlength_list_repeat; rep_lia).\n        rewrite upd_Znth_same by (rewrite ?upd_Znth_Zlength; rewrite ?Zlength_list_repeat; rep_lia).\n        admit.\n      - unfold keyslice1, keyslice2 in *; clear keyslice1 keyslice2.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        trie_solve.\n        simpl.\n        unfold BorderNode.put_value.\n        trie_solve.\n        rewrite BorderNode.next_cursor_terminate_permute2 by\n            first [\n                solve [trie_solve]\n              | apply BorderNode.next_cursor_terminate; trie_solve ].\n        trie_solve.\n        simpl.\n        unfold Node.get_key.\n        trie_solve.\n        rewrite upd_Znth_same by (rewrite ?upd_Znth_Zlength; rewrite ?Zlength_list_repeat; rep_lia).\n        admit.\n      - unfold keyslice1, keyslice2 in *; clear keyslice1 keyslice2.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        trie_solve.\n        simpl.\n        rewrite ?if_false by auto.\n        unfold BorderNode.put_value.\n        trie_solve.\n        simpl.\n        rewrite if_false by TrieKeyFacts.order.\n        simpl.\n        change (BorderNode.next_cursor\n                  BorderNode.before_suffix\n                  (upd_Znth (Zlength k2 - 1) (list_repeat (Z.to_nat keyslice_length) None) (Some v2), Some (inl (get_suffix k1, v1))))\n          with (BorderNode.before_suffix).\n        simpl.\n        unfold Node.get_key.\n        trie_solve.\n        admit.\n      - unfold keyslice1, keyslice2 in *; clear keyslice1 keyslice2.\n        rewrite make_cursor_equation.\n        simpl.\n        unfold Node.Flattened.get_exact.\n        trie_solve.\n        simpl.\n        pose proof H8.\n        eapply create_pair_normalized in H8;\n          try solve [\n                change get_suffix with (fun (k: string) => sublist keyslice_length (Zlength k) k);\n                simpl;\n                rewrite ?Zlength_sublist; rep_lia].\n        2: { admit. } (* [get_suffix k1 <> get_suffix k2] *)\n        rewrite H8.\n        simpl.\n        unfold Node.get_key.\n        trie_solve.\n        unfold get in H.\n        assert (match normalize_cursor (make_cursor (get_suffix k1) t') with\n                | Some c'0 => get_raw c'0\n                | None => None\n                end = Some (get_suffix k1, v1)). {\n          eapply H with (y := length (get_suffix k1)) (k2 := (get_suffix k2)) (v2 := v2) in H13;\n          try solve [\n                change get_suffix with (fun (k: string) => sublist keyslice_length (Zlength k) k);\n                simpl;\n                rewrite <- ?ZtoNat_Zlength;\n                rewrite ?Zlength_sublist; rep_lia].\n          - apply H13.\n          - admit.\n          - admit. (* result of [make_cursor_abs] *)\n          - admit. (* result of [make_cursor_key] *)\n        }\n        eapply create_pair_normalized in H13;\n          try solve [\n                change get_suffix with (fun (k: string) => sublist keyslice_length (Zlength k) k);\n                simpl;\n                rewrite ?Zlength_sublist; rep_lia].\n        2: { admit. }\n        rewrite H13 in H14.\n        rewrite H14.\n        admit.\n      - unfold keyslice1, keyslice2 in *; clear keyslice1 keyslice2.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        trie_solve.\n        subst bnode1.\n        if_tac.\n        + simpl.\n          unfold BorderNode.put_value.\n          rewrite ?if_true by auto.\n          rewrite BorderNode.next_cursor_terminate; trie_solve.\n          simpl.\n          unfold Node.get_key.\n          trie_solve.\n          rewrite upd_Znth_same by (rewrite ?upd_Znth_Zlength; rewrite ?Zlength_list_repeat; rep_lia).\n          admit.\n        + unfold BorderNode.put_value.\n          rewrite ?if_false by auto.\n          simpl.\n          rewrite ?if_false by auto.\n          simpl.\n          change (BorderNode.next_cursor\n                    BorderNode.before_suffix\n                    (list_repeat (Z.to_nat keyslice_length) None, Some (inl (get_suffix k1, v1))))\n            with (BorderNode.before_suffix).\n          simpl.\n          unfold Node.get_key.\n          trie_solve.\n          admit.\n    Admitted.\n\n    Theorem get_put_same: forall t1 t2 c1 c2 c3 k v,\n        Zlength k <> 0 ->\n        put k v c1 t1 c2 t2 ->\n        cursor_trie_assoc c1 t1 ->\n        cursor_trie_assoc c3 t2 ->\n        key_rel k c3 t2 ->\n        get c3 t2 = Some (k, v).\n    Proof.\n      intros.\n      destruct H1 as [? []].\n      clear H1 H5.\n      remember (length k) as n.\n      generalize dependent t1.\n      generalize dependent t2.\n      generalize dependent c1.\n      generalize dependent c2.\n      generalize dependent c3.\n      generalize dependent v.\n      generalize dependent k.\n      induction n using (well_founded_induction lt_wf); intros.\n      unfold get.\n      unfold key_rel in H3.\n      rewrite H3.\n      inv H1.\n      - subst bnode0 keyslice.\n        inv H4.\n        simpl.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        erewrite Node.Flattened.get_put_same by trie_solve.\n        rewrite ?if_true by KeysliceFacts.order.\n        rewrite ?if_true by auto.\n        simpl.\n        rewrite BorderNode.next_cursor_terminate by trie_solve.\n        simpl.\n        erewrite get_exact_correct_table_key by eauto with trie.\n        rewrite BorderNode.get_put_prefix_same by trie_solve.\n        f_equal.\n        admit.\n      - subst keyslice bnode0.\n        unfold BorderNode.get_link in H7.\n        destruct bnode as [? [ [|] | ]]; simplify.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        erewrite Node.Flattened.get_put_same by trie_solve.\n        rewrite ?if_true by KeysliceFacts.order.\n        rewrite ?if_false by auto.\n        unfold BorderNode.get_suffix_pair, BorderNode.get_suffix.\n        simpl.\n        pose proof H8.\n        eapply make_cursor_put_normalized in H8;\n          try solve [ trie_solve\n                    | change (get_suffix) with (fun (k: string) => sublist keyslice_length (Zlength k) k);\n                     simpl; rewrite ?Zlength_sublist; rep_lia].\n        rewrite H8.\n        simpl.\n        erewrite get_exact_correct_table_key by eauto with trie.\n        unfold get in H.\n        assert (match normalize_cursor (make_cursor (get_suffix k) t'') with\n                | Some c' => get_raw c'\n                | None => None\n                end = Some (get_suffix k, v)). {\n          eapply H with\n              (y := (length (get_suffix k)))\n              (c3 := (make_cursor (get_suffix k) t'')) in H1;\n            try solve [ trie_solve\n                      | change (get_suffix) with (fun (k: string) => sublist keyslice_length (Zlength k) k);\n                        simpl; rewrite ?Zlength_sublist; rep_lia].\n          - change (get_suffix) with (fun (k: string) => sublist keyslice_length (Zlength k) k); simpl.\n            rewrite <- ?ZtoNat_Zlength.\n            rewrite Zlength_sublist by rep_lia.\n            apply Z2Nat.inj_lt; rep_lia.\n          - admit. (* result of [make_cursor_abs] *)\n        }\n        eapply make_cursor_put_normalized in H1;\n          try solve [ trie_solve\n                    | change (get_suffix) with (fun (k: string) => sublist keyslice_length (Zlength k) k);\n                     simpl; rewrite ?Zlength_sublist; rep_lia].\n        rewrite H1 in H7.\n        rewrite H7.\n        f_equal.\n        f_equal.\n        admit.\n      - subst keyslice bnode0.\n        destruct bnode as [? [ | ]]; simpl in *; simplify.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        erewrite Node.Flattened.get_put_same by trie_solve.\n        rewrite ?if_true by KeysliceFacts.order.\n        rewrite ?if_false by auto.\n        simpl.\n        rewrite ?if_false by auto.\n        simpl.\n        change (BorderNode.next_cursor BorderNode.before_suffix (l, Some (inl (get_suffix k, v)))) with\n            (BorderNode.before_suffix).\n        simpl.\n        erewrite get_exact_correct_table_key by eauto with trie.\n        f_equal.\n        admit.\n      - subst keyslice bnode0.\n        simpl.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        erewrite Node.Flattened.get_put_same by trie_solve.\n        rewrite ?if_true by KeysliceFacts.order.\n        rewrite ?if_false by auto.\n        destruct bnode as []; simplify.\n        simpl.\n        rewrite ?if_false by auto.\n        simpl.\n        change (BorderNode.next_cursor BorderNode.before_suffix (l, Some (inl (get_suffix k, v)))) with\n            (BorderNode.before_suffix).\n        simpl.\n        erewrite get_exact_correct_table_key by eauto with trie.\n        f_equal.\n        admit.\n      - subst keyslice bnode0.\n        destruct bnode as [? [ [|] | ]]; simplify.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        erewrite Node.Flattened.get_put_same by trie_solve.\n        rewrite ?if_true by KeysliceFacts.order.\n        rewrite ?if_false by auto.\n        simpl.\n        pose proof H5.\n        apply get_exact_correct in H5.\n        apply Node.Flattened.get_in_weak in H5.\n        pose proof H4.\n        inv H4.\n        eapply Forall_forall in H20; [ | solve [eauto]].\n        simpl in H20.\n        inv H20.\n        unfold BorderNode.get_suffix_pair in H7.\n        simplify.\n        pose proof H9.\n        eapply create_pair_normalized in H9;\n          try solve [ trie_solve\n                    | change (get_suffix) with (fun (k: string) => sublist keyslice_length (Zlength k) k);\n                      simpl; rewrite ?Zlength_sublist; rep_lia].\n        rewrite H9.\n        simpl.\n        erewrite get_exact_correct_table_key by eauto with trie.\n        eapply get_create_same1 in H4;\n          try solve [ trie_solve\n                    | change (get_suffix) with (fun (k: string) => sublist keyslice_length (Zlength k) k);\n                      simpl; rewrite ?Zlength_sublist; rep_lia].\n        + unfold get in H4.\n          rewrite H9 in H4.\n          rewrite H4.\n          f_equal.\n          admit.\n        + admit. (* result of [make_cursor_abs] *)\n        + admit. (* result of [make_cursor_key] *)\n      - subst keyslice bnode.\n        rewrite make_cursor_equation.\n        unfold Node.Flattened.get_exact.\n        erewrite Node.Flattened.get_put_same by trie_solve.\n        rewrite ?if_true by KeysliceFacts.order.\n        if_tac.\n        + simpl.\n          unfold BorderNode.put_value.\n          rewrite ?if_true by auto.\n          rewrite BorderNode.next_cursor_terminate by trie_solve.\n          simpl.\n          unfold Node.get_key.\n          erewrite Node.get_put_same by trie_solve.\n          rewrite upd_Znth_same by list_solve.\n          f_equal.\n          admit.\n        + unfold BorderNode.put_value.\n          rewrite ?if_false by auto.\n          simpl.\n          rewrite ?if_false by TrieKeyFacts.order.\n          simpl.\n          change (BorderNode.next_cursor BorderNode.before_suffix (list_repeat (Z.to_nat keyslice_length) None, Some (inl (get_suffix k, v))))\n            with (BorderNode.before_suffix).\n          simpl.\n          unfold Node.get_key.\n          erewrite Node.get_put_same by trie_solve.\n          f_equal.\n          admit.\n    Admitted.\n\n    Theorem table_exact_list_exact_none: forall addr tableform listform k,\n        trie_correct (trienode_of addr tableform listform) ->\n        Node.get_exact k tableform = None <->\n        Node.Flattened.get_exact k listform = None.\n    Proof.\n      intros.\n      inv H.\n      split; intros.\n      - rewrite NodeFacts.get_exact_eq in H by assumption.\n        unfold Node.Flattened.get_exact in *.\n        pose proof (Node.flatten_invariant tableform H3) as [? ?].\n        pose proof (Node.Flattened.same_key_result\n                      (Node.flatten tableform) listform\n                      (Node.Flattened.make_cursor k (Node.flatten tableform))\n                      (Node.Flattened.make_cursor k listform)\n                      k\n                      ltac:(assumption)\n                      ltac:(apply Node.Flattened.make_cursor_key; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_abs; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_key; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_abs; assumption)).\n        unfold Node.Flattened.get_key in H2.\n        destruct (Node.Flattened.get (Node.Flattened.make_cursor k (Node.flatten tableform)) (Node.flatten tableform)) as [[] | ] eqn:Heqn;\n          destruct (Node.Flattened.get (Node.Flattened.make_cursor k listform) listform) as [[? []] | ] eqn:Heqn'; try reflexivity.\n        + inv H2.\n          if_tac in H; congruence.\n        + inv H2.\n      - rewrite NodeFacts.get_exact_eq by assumption.\n        unfold Node.Flattened.get_exact in *.\n        pose proof (Node.flatten_invariant tableform H3) as [? ?].\n        pose proof (Node.Flattened.same_key_result\n                      (Node.flatten tableform) listform\n                      (Node.Flattened.make_cursor k (Node.flatten tableform))\n                      (Node.Flattened.make_cursor k listform)\n                      k\n                      ltac:(assumption)\n                      ltac:(apply Node.Flattened.make_cursor_key; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_abs; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_key; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_abs; assumption)).\n        unfold Node.Flattened.get_key in H2.\n        destruct (Node.Flattened.get (Node.Flattened.make_cursor k (Node.flatten tableform)) (Node.flatten tableform)) as [[] | ] eqn:Heqn;\n          destruct (Node.Flattened.get (Node.Flattened.make_cursor k listform) listform) as [[? []] | ] eqn:Heqn'; try reflexivity.\n        + inv H2.\n          if_tac in H; congruence.\n        + inv H2.\n    Qed.\n\n    Theorem table_exact_list_exact_some: forall addr tableform listform k bnode_addr,\n        trie_correct (trienode_of addr tableform listform) ->\n        Node.get_exact k tableform = Some bnode_addr <->\n        exists bnode: bordernode, Node.Flattened.get_exact k listform = Some (bnode_addr, bnode).\n    Proof.\n      intros.\n      inv H.\n      split; intros.\n      - rewrite NodeFacts.get_exact_eq in H by assumption.\n        unfold Node.Flattened.get_exact in *.\n        pose proof (Node.flatten_invariant tableform H3) as [? ?].\n        pose proof (Node.Flattened.same_key_result\n                      (Node.flatten tableform) listform\n                      (Node.Flattened.make_cursor k (Node.flatten tableform))\n                      (Node.Flattened.make_cursor k listform)\n                      k\n                      ltac:(assumption)\n                      ltac:(apply Node.Flattened.make_cursor_key; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_abs; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_key; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_abs; assumption)).\n        pose proof H2.\n        unfold Node.Flattened.get_key in H2.\n        destruct (Node.Flattened.get (Node.Flattened.make_cursor k (Node.flatten tableform)) (Node.flatten tableform)) as [[] | ] eqn:Heqn;\n          destruct (Node.Flattened.get (Node.Flattened.make_cursor k listform) listform) as [[? []] | ] eqn:Heqn'; try congruence.\n        inv H2.\n        if_tac in H; try congruence.\n        subst.\n        inv H.\n        pose proof (Node.Flattened.same_value_result\n                      (Node.flatten tableform) listform\n                      (Node.Flattened.make_cursor k1 (Node.flatten tableform))\n                      (Node.Flattened.make_cursor k1 listform)\n                      k1\n                      fst\n                      (v0, t)\n                      ltac:(assumption)\n                      ltac:(assumption)\n                      ltac:(apply Node.Flattened.make_cursor_key; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_abs; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_key; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_abs; assumption)\n                      ltac:(assumption)).\n        specialize (H ltac:(unfold Node.Flattened.get_value; rewrite Heqn'; reflexivity)).\n        simpl in H.\n        exists t.\n        unfold Node.Flattened.get_value in H.\n        rewrite Heqn in H.\n        inv H.\n        reflexivity.\n      - destruct H as [bnode ?].\n        rewrite NodeFacts.get_exact_eq by assumption.\n        unfold Node.Flattened.get_exact in *.\n        pose proof (Node.flatten_invariant tableform H3) as [? ?].\n        pose proof (Node.Flattened.same_key_result\n                      (Node.flatten tableform) listform\n                      (Node.Flattened.make_cursor k (Node.flatten tableform))\n                      (Node.Flattened.make_cursor k listform)\n                      k\n                      ltac:(assumption)\n                      ltac:(apply Node.Flattened.make_cursor_key; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_abs; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_key; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_abs; assumption)).\n        pose proof H2.\n        unfold Node.Flattened.get_key in H2.\n        destruct (Node.Flattened.get (Node.Flattened.make_cursor k (Node.flatten tableform)) (Node.flatten tableform)) as [[] | ] eqn:Heqn;\n          destruct (Node.Flattened.get (Node.Flattened.make_cursor k listform) listform) as [[? []] | ] eqn:Heqn'; try congruence.\n        inv H2.\n        if_tac in H; try congruence.\n        subst.\n        inv H.\n        pose proof (Node.Flattened.same_value_result\n                      (Node.flatten tableform) listform\n                      (Node.Flattened.make_cursor k1 (Node.flatten tableform))\n                      (Node.Flattened.make_cursor k1 listform)\n                      k1\n                      fst\n                      (bnode_addr, bnode)\n                      ltac:(assumption)\n                      ltac:(assumption)\n                      ltac:(apply Node.Flattened.make_cursor_key; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_abs; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_key; assumption)\n                      ltac:(apply Node.Flattened.make_cursor_abs; assumption)\n                      ltac:(assumption)).\n        specialize (H ltac:(unfold Node.Flattened.get_value; rewrite Heqn'; reflexivity)).\n        simpl in H.\n        unfold Node.Flattened.get_value in H.\n        rewrite Heqn in H.\n        inv H.\n        reflexivity.\n    Qed.\n  End Types.\n\n  Arguments bordernode: clear implicits.\n  Arguments trie: clear implicits.\n  Arguments cursor: clear implicits.\nEnd Trie.\n", "meta": {"author": "PrincetonUniversity", "repo": "DeepSpecDB", "sha": "a67d933b4288498bd04c70748b7fa28f676983c3", "save_path": "github-repos/coq/PrincetonUniversity-DeepSpecDB", "path": "github-repos/coq/PrincetonUniversity-DeepSpecDB/DeepSpecDB-a67d933b4288498bd04c70748b7fa28f676983c3/verif/trie/functional/trie.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2423817798824054}}
{"text": "From iris.base_logic.lib Require Export invariants.\nFrom iris.algebra Require Import auth gmap agree.\nFrom iris.base_logic Require Import big_op.\nFrom iris.proofmode Require Import tactics.\nSet Default Proof Using \"Type\".\nImport uPred.\n\n(** The CMRAs we need. *)\nClass boxG Σ :=\n  boxG_inG :> inG Σ (prodR\n    (authR (optionUR (exclR boolC)))\n    (optionR (agreeR (laterC (iPreProp Σ))))).\n\nDefinition boxΣ : gFunctors := #[ GFunctor (authR (optionUR (exclR boolC)) *\n                                            optionRF (agreeRF (▶ ∙)) ) ].\n\nInstance subG_stsΣ Σ : subG boxΣ Σ → boxG Σ.\nProof. solve_inG. Qed.\n\nSection box_defs.\n  Context `{invG Σ, boxG Σ} (N : namespace).\n\n  Definition slice_name := gname.\n\n  Definition box_own_auth (γ : slice_name) (a : auth (option (excl bool))) : iProp Σ :=\n    own γ (a, None).\n\n  Definition box_own_prop (γ : slice_name) (P : iProp Σ) : iProp Σ :=\n    own γ (ε, Some (to_agree (Next (iProp_unfold P)))).\n\n  Definition slice_inv (γ : slice_name) (P : iProp Σ) : iProp Σ :=\n    (∃ b, box_own_auth γ (● Excl' b) ∗ if b then P else True)%I.\n\n  Definition slice (γ : slice_name) (P : iProp Σ) : iProp Σ :=\n    (box_own_prop γ P ∗ inv N (slice_inv γ P))%I.\n\n  Definition box (f : gmap slice_name bool) (P : iProp Σ) : iProp Σ :=\n    (∃ Φ : slice_name → iProp Σ,\n      ▷ (P ≡ [∗ map] γ ↦ _ ∈ f, Φ γ) ∗\n      [∗ map] γ ↦ b ∈ f, box_own_auth γ (◯ Excl' b) ∗ box_own_prop γ (Φ γ) ∗\n                         inv N (slice_inv γ (Φ γ)))%I.\nEnd box_defs.\n\nInstance: Params (@box_own_prop) 3.\nInstance: Params (@slice_inv) 3.\nInstance: Params (@slice) 5.\nInstance: Params (@box) 5.\n\nSection box.\nContext `{invG Σ, boxG Σ} (N : namespace).\nImplicit Types P Q : iProp Σ.\n\nGlobal Instance box_own_prop_ne γ : NonExpansive (box_own_prop γ).\nProof. solve_proper. Qed.\nGlobal Instance box_own_prop_contractive γ : Contractive (box_own_prop γ).\nProof. solve_contractive. Qed.\n\nGlobal Instance box_inv_ne γ : NonExpansive (slice_inv γ).\nProof. solve_proper. Qed.\n\nGlobal Instance slice_ne γ : NonExpansive (slice N γ).\nProof. solve_proper. Qed.\nGlobal Instance slice_contractive γ : Contractive (slice N γ).\nProof. solve_contractive. Qed.\nGlobal Instance slice_proper γ : Proper ((≡) ==> (≡)) (slice N γ).\nProof. apply ne_proper, _. Qed.\n\nGlobal Instance slice_persistent γ P : Persistent (slice N γ P).\nProof. apply _. Qed.\n\nGlobal Instance box_contractive f : Contractive (box N f).\nProof. solve_contractive. Qed.\nGlobal Instance box_ne f : NonExpansive (box N f).\nProof. apply (contractive_ne _). Qed.\nGlobal Instance box_proper f : Proper ((≡) ==> (≡)) (box N f).\nProof. apply ne_proper, _. Qed.\n\nLemma box_own_auth_agree γ b1 b2 :\n  box_own_auth γ (● Excl' b1) ∗ box_own_auth γ (◯ Excl' b2) ⊢ ⌜b1 = b2⌝.\nProof.\n  rewrite /box_own_prop -own_op own_valid prod_validI /= and_elim_l.\n  by iDestruct 1 as % [[[] [=]%leibniz_equiv] ?]%auth_valid_discrete.\nQed.\n\nLemma box_own_auth_update γ b1 b2 b3 :\n  box_own_auth γ (● Excl' b1) ∗ box_own_auth γ (◯ Excl' b2)\n  ==∗ box_own_auth γ (● Excl' b3) ∗ box_own_auth γ (◯ Excl' b3).\nProof.\n  rewrite /box_own_auth -!own_op. apply own_update, prod_update; last done.\n  by apply auth_update, option_local_update, exclusive_local_update.\nQed.\n\nLemma box_own_agree γ Q1 Q2 :\n  box_own_prop γ Q1 ∗ box_own_prop γ Q2 ⊢ ▷ (Q1 ≡ Q2).\nProof.\n  rewrite /box_own_prop -own_op own_valid prod_validI /= and_elim_r.\n  rewrite option_validI /= agree_validI agree_equivI later_equivI /=.\n  iIntros \"#HQ\". iNext. rewrite -{2}(iProp_fold_unfold Q1).\n  iRewrite \"HQ\". by rewrite iProp_fold_unfold.\nQed.\n\nLemma box_alloc : box N ∅ True%I.\nProof.\n  iIntros; iExists (λ _, True)%I; iSplit; last done.\n  iNext. by rewrite big_opM_empty.\nQed.\n\nLemma slice_insert_empty E q f Q P :\n  ▷?q box N f P ={E}=∗ ∃ γ, ⌜f !! γ = None⌝ ∗\n    slice N γ Q ∗ ▷?q box N (<[γ:=false]> f) (Q ∗ P).\nProof.\n  iDestruct 1 as (Φ) \"[#HeqP Hf]\".\n  iMod (own_alloc_strong (● Excl' false ⋅ ◯ Excl' false,\n    Some (to_agree (Next (iProp_unfold Q)))) (dom _ f))\n    as (γ) \"[Hdom Hγ]\"; first done.\n  rewrite pair_split. iDestruct \"Hγ\" as \"[[Hγ Hγ'] #HγQ]\".\n  iDestruct \"Hdom\" as % ?%not_elem_of_dom.\n  iMod (inv_alloc N _ (slice_inv γ Q) with \"[Hγ]\") as \"#Hinv\".\n  { iNext. iExists false; eauto. }\n  iModIntro; iExists γ; repeat iSplit; auto.\n  iNext. iExists (<[γ:=Q]> Φ); iSplit.\n  - iNext. iRewrite \"HeqP\". by rewrite big_opM_fn_insert'.\n  - rewrite (big_opM_fn_insert (λ _ _ P',  _ ∗ _ _ P' ∗ _ _ (_ _ P')))%I //.\n    iFrame; eauto.\nQed.\n\nLemma slice_delete_empty E q f P Q γ :\n  ↑N ⊆ E →\n  f !! γ = Some false →\n  slice N γ Q -∗ ▷?q box N f P ={E}=∗ ∃ P',\n    ▷?q ▷ (P ≡ (Q ∗ P')) ∗ ▷?q box N (delete γ f) P'.\nProof.\n  iIntros (??) \"[#HγQ Hinv] H\". iDestruct \"H\" as (Φ) \"[#HeqP Hf]\".\n  iExists ([∗ map] γ'↦_ ∈ delete γ f, Φ γ')%I.\n  iInv N as (b) \"[>Hγ _]\" \"Hclose\".\n  iDestruct (big_opM_delete _ f _ false with \"Hf\")\n    as \"[[>Hγ' #[HγΦ ?]] ?]\"; first done.\n  iDestruct (box_own_auth_agree γ b false with \"[-]\") as %->; first by iFrame.\n  iMod (\"Hclose\" with \"[Hγ]\"); first iExists false; eauto.\n  iModIntro. iNext. iSplit.\n  - iDestruct (box_own_agree γ Q (Φ γ) with \"[#]\") as \"HeqQ\"; first by eauto.\n    iNext. iRewrite \"HeqP\". iRewrite \"HeqQ\". by rewrite -big_opM_delete.\n  - iExists Φ; eauto.\nQed.\n\nLemma slice_fill E q f γ P Q :\n  ↑N ⊆ E →\n  f !! γ = Some false →\n  slice N γ Q -∗ ▷ Q -∗ ▷?q box N f P ={E}=∗ ▷?q box N (<[γ:=true]> f) P.\nProof.\n  iIntros (??) \"#[HγQ Hinv] HQ H\"; iDestruct \"H\" as (Φ) \"[#HeqP Hf]\".\n  iInv N as (b') \"[>Hγ _]\" \"Hclose\".\n  iDestruct (big_opM_delete _ f _ false with \"Hf\")\n    as \"[[>Hγ' #[HγΦ Hinv']] ?]\"; first done.\n  iMod (box_own_auth_update γ b' false true with \"[$Hγ $Hγ']\") as \"[Hγ Hγ']\".\n  iMod (\"Hclose\" with \"[Hγ HQ]\"); first (iNext; iExists true; by iFrame).\n  iModIntro; iNext; iExists Φ; iSplit.\n  - by rewrite big_opM_insert_override.\n  - rewrite -insert_delete big_opM_insert ?lookup_delete //.\n    iFrame; eauto.\nQed.\n\nLemma slice_empty E q f P Q γ :\n  ↑N ⊆ E →\n  f !! γ = Some true →\n  slice N γ Q -∗ ▷?q box N f P ={E}=∗ ▷ Q ∗ ▷?q box N (<[γ:=false]> f) P.\nProof.\n  iIntros (??) \"#[HγQ Hinv] H\"; iDestruct \"H\" as (Φ) \"[#HeqP Hf]\".\n  iInv N as (b) \"[>Hγ HQ]\" \"Hclose\".\n  iDestruct (big_opM_delete _ f with \"Hf\")\n    as \"[[>Hγ' #[HγΦ Hinv']] ?]\"; first done.\n  iDestruct (box_own_auth_agree γ b true with \"[-]\") as %->; first by iFrame.\n  iFrame \"HQ\".\n  iMod (box_own_auth_update γ with \"[$Hγ $Hγ']\") as \"[Hγ Hγ']\".\n  iMod (\"Hclose\" with \"[Hγ]\"); first (iNext; iExists false; by repeat iSplit).\n  iModIntro; iNext; iExists Φ; iSplit.\n  - by rewrite big_opM_insert_override.\n  - rewrite -insert_delete big_opM_insert ?lookup_delete //.\n    iFrame; eauto.\nQed.\n\nLemma slice_insert_full E q f P Q :\n  ↑N ⊆ E →\n  ▷ Q -∗ ▷?q box N f P ={E}=∗ ∃ γ, ⌜f !! γ = None⌝ ∗\n    slice N γ Q ∗ ▷?q box N (<[γ:=true]> f) (Q ∗ P).\nProof.\n  iIntros (?) \"HQ Hbox\".\n  iMod (slice_insert_empty with \"Hbox\") as (γ ?) \"[#Hslice Hbox]\".\n  iExists γ. iFrame \"%#\". iMod (slice_fill with \"Hslice HQ Hbox\"); first done.\n  by apply lookup_insert. by rewrite insert_insert.\nQed.\n\nLemma slice_delete_full E q f P Q γ :\n  ↑N ⊆ E →\n  f !! γ = Some true →\n  slice N γ Q -∗ ▷?q box N f P ={E}=∗\n  ∃ P', ▷ Q ∗ ▷?q ▷ (P ≡ (Q ∗ P')) ∗ ▷?q box N (delete γ f) P'.\nProof.\n  iIntros (??) \"#Hslice Hbox\".\n  iMod (slice_empty with \"Hslice Hbox\") as \"[$ Hbox]\"; try done.\n  iMod (slice_delete_empty with \"Hslice Hbox\") as (P') \"[Heq Hbox]\"; first done.\n  { by apply lookup_insert. }\n  iExists P'. iFrame. rewrite -insert_delete delete_insert ?lookup_delete //.\nQed.\n\nLemma box_fill E f P :\n  ↑N ⊆ E →\n  box N f P -∗ ▷ P ={E}=∗ box N (const true <$> f) P.\nProof.\n  iIntros (?) \"H HP\"; iDestruct \"H\" as (Φ) \"[#HeqP Hf]\".\n  iExists Φ; iSplitR; first by rewrite big_opM_fmap.\n  rewrite internal_eq_iff later_iff big_opM_commute.\n  iDestruct (\"HeqP\" with \"HP\") as \"HP\".\n  iCombine \"Hf\" \"HP\" as \"Hf\".\n  rewrite -big_opM_opM big_opM_fmap; iApply (fupd_big_sepM _ _ f).\n  iApply (@big_sepM_impl with \"[$Hf]\").\n  iIntros \"!#\" (γ b' ?) \"[(Hγ' & #$ & #$) HΦ]\".\n  iInv N as (b) \"[>Hγ _]\" \"Hclose\".\n  iMod (box_own_auth_update γ with \"[Hγ Hγ']\") as \"[Hγ $]\"; first by iFrame.\n  iApply \"Hclose\". iNext; iExists true. by iFrame.\nQed.\n\nLemma box_empty E f P :\n  ↑N ⊆ E →\n  map_Forall (λ _, (true =)) f →\n  box N f P ={E}=∗ ▷ P ∗ box N (const false <$> f) P.\nProof.\n  iDestruct 1 as (Φ) \"[#HeqP Hf]\".\n  iAssert (([∗ map] γ↦b ∈ f, ▷ Φ γ) ∗\n    [∗ map] γ↦b ∈ f, box_own_auth γ (◯ Excl' false) ∗  box_own_prop γ (Φ γ) ∗\n      inv N (slice_inv γ (Φ γ)))%I with \"[> Hf]\" as \"[HΦ ?]\".\n  { rewrite -big_opM_opM -fupd_big_sepM. iApply (@big_sepM_impl with \"[$Hf]\").\n    iIntros \"!#\" (γ b ?) \"(Hγ' & #HγΦ & #Hinv)\".\n    assert (true = b) as <- by eauto.\n    iInv N as (b) \"[>Hγ HΦ]\" \"Hclose\".\n    iDestruct (box_own_auth_agree γ b true with \"[-]\") as %->; first by iFrame.\n    iMod (box_own_auth_update γ true true false with \"[$Hγ $Hγ']\") as \"[Hγ $]\".\n    iMod (\"Hclose\" with \"[Hγ]\"); first (iNext; iExists false; iFrame; eauto).\n    iFrame \"HγΦ Hinv\". by iApply \"HΦ\". }\n  iModIntro; iSplitL \"HΦ\".\n  - rewrite internal_eq_iff later_iff big_opM_commute. by iApply \"HeqP\".\n  - iExists Φ; iSplit; by rewrite big_opM_fmap.\nQed.\n\nLemma slice_iff E q f P Q Q' γ b :\n  ↑N ⊆ E → f !! γ = Some b →\n  ▷ □ (Q ↔ Q') -∗ slice N γ Q -∗ ▷?q box N f P ={E}=∗ ∃ γ' P',\n    ⌜delete γ f !! γ' = None⌝ ∗ ▷?q ▷ □ (P ↔ P') ∗\n    slice N γ' Q' ∗ ▷?q box N (<[γ' := b]>(delete γ f)) P'.\nProof.\n  iIntros (??) \"#HQQ' #Hs Hb\". destruct b.\n  - iMod (slice_delete_full with \"Hs Hb\") as (P') \"(HQ & Heq & Hb)\"; try done.\n    iDestruct (\"HQQ'\" with \"HQ\") as \"HQ'\".\n    iMod (slice_insert_full with \"HQ' Hb\") as (γ' ?) \"[#Hs' Hb]\"; try done.\n    iExists γ', _. iIntros \"{$∗ $# $%} !>\". do 2 iNext. iRewrite \"Heq\".\n    iAlways. by iSplit; iIntros \"[? $]\"; iApply \"HQQ'\".\n  - iMod (slice_delete_empty with \"Hs Hb\") as (P') \"(Heq & Hb)\"; try done.\n    iMod (slice_insert_empty with \"Hb\") as (γ' ?) \"[#Hs' Hb]\"; try done.\n    iExists γ', _. iIntros \"{$∗ $# $%} !>\". do 2 iNext. iRewrite \"Heq\".\n    iAlways. by iSplit; iIntros \"[? $]\"; iApply \"HQQ'\".\nQed.\n\nLemma slice_split E q f P Q1 Q2 γ b :\n  ↑N ⊆ E → f !! γ = Some b →\n  slice N γ (Q1 ∗ Q2) -∗ ▷?q box N f P ={E}=∗ ∃ γ1 γ2,\n    ⌜delete γ f !! γ1 = None⌝ ∗ ⌜delete γ f !! γ2 = None⌝ ∗ ⌜γ1 ≠ γ2⌝ ∗\n    slice N γ1 Q1 ∗ slice N γ2 Q2 ∗ ▷?q box N (<[γ2 := b]>(<[γ1 := b]>(delete γ f))) P.\nProof.\n  iIntros (??) \"#Hslice Hbox\". destruct b.\n  - iMod (slice_delete_full with \"Hslice Hbox\") as (P') \"([HQ1 HQ2] & Heq & Hbox)\"; try done.\n    iMod (slice_insert_full with \"HQ1 Hbox\") as (γ1 ?) \"[#Hslice1 Hbox]\"; first done.\n    iMod (slice_insert_full with \"HQ2 Hbox\") as (γ2 ?) \"[#Hslice2 Hbox]\"; first done.\n    iExists γ1, γ2. iIntros \"{$% $#} !>\". iSplit; last iSplit; try iPureIntro.\n    { by eapply lookup_insert_None. }\n    { by apply (lookup_insert_None (delete γ f) γ1 γ2 true). }\n    iNext. iApply (internal_eq_rewrite_contractive with \"[#] Hbox\").\n    iNext. iRewrite \"Heq\". iPureIntro. by rewrite assoc (comm _ Q2).\n  - iMod (slice_delete_empty with \"Hslice Hbox\") as (P') \"[Heq Hbox]\"; try done.\n    iMod (slice_insert_empty with \"Hbox\") as (γ1 ?) \"[#Hslice1 Hbox]\".\n    iMod (slice_insert_empty with \"Hbox\") as (γ2 ?) \"[#Hslice2 Hbox]\".\n    iExists γ1, γ2. iIntros \"{$% $#} !>\". iSplit; last iSplit; try iPureIntro.\n    { by eapply lookup_insert_None. }\n    { by apply (lookup_insert_None (delete γ f) γ1 γ2 false). }\n    iNext. iApply (internal_eq_rewrite_contractive with \"[#] Hbox\").\n    iNext. iRewrite \"Heq\". iPureIntro. by rewrite assoc (comm _ Q2).\nQed.\n\nLemma slice_combine E q f P Q1 Q2 γ1 γ2 b :\n  ↑N ⊆ E → γ1 ≠ γ2 → f !! γ1 = Some b → f !! γ2 = Some b →\n  slice N γ1 Q1 -∗ slice N γ2 Q2 -∗ ▷?q box N f P ={E}=∗ ∃ γ,\n    ⌜delete γ2 (delete γ1 f) !! γ = None⌝ ∗ slice N γ (Q1 ∗ Q2) ∗\n    ▷?q box N (<[γ := b]>(delete γ2 (delete γ1 f))) P.\nProof.\n  iIntros (????) \"#Hslice1 #Hslice2 Hbox\". destruct b.\n  - iMod (slice_delete_full with \"Hslice1 Hbox\") as (P1) \"(HQ1 & Heq1 & Hbox)\"; try done.\n    iMod (slice_delete_full with \"Hslice2 Hbox\") as (P2) \"(HQ2 & Heq2 & Hbox)\"; first done.\n    { by simplify_map_eq. }\n    iMod (slice_insert_full _ _ _ _ (Q1 ∗ Q2)%I with \"[$HQ1 $HQ2] Hbox\")\n      as (γ ?) \"[#Hslice Hbox]\"; first done.\n    iExists γ. iIntros \"{$% $#} !>\". iNext.\n    iApply (internal_eq_rewrite_contractive with \"[#] Hbox\").\n    iNext. iRewrite \"Heq1\". iRewrite \"Heq2\". by rewrite assoc.\n  - iMod (slice_delete_empty with \"Hslice1 Hbox\") as (P1) \"(Heq1 & Hbox)\"; try done.\n    iMod (slice_delete_empty with \"Hslice2 Hbox\") as (P2) \"(Heq2 & Hbox)\"; first done.\n    { by simplify_map_eq. }\n    iMod (slice_insert_empty with \"Hbox\") as (γ ?) \"[#Hslice Hbox]\".\n    iExists γ. iIntros \"{$% $#} !>\". iNext.\n    iApply (internal_eq_rewrite_contractive with \"[#] Hbox\").\n    iNext. iRewrite \"Heq1\". iRewrite \"Heq2\". by rewrite assoc.\nQed.\nEnd box.\n\nTypeclasses Opaque slice box.\n", "meta": {"author": "jtassarotti", "repo": "polaris", "sha": "c7873f05214351d54cacf3d8482625ee33ad3288", "save_path": "github-repos/coq/jtassarotti-polaris", "path": "github-repos/coq/jtassarotti-polaris/polaris-c7873f05214351d54cacf3d8482625ee33ad3288/theories/base_logic/lib/boxes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24230357322004992}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import RealParams.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\n\n(** * Example instance for [RealParams] *)\n\nInstance sample_realparams_ops: RealParamsOps :=\n  {\n    real_mm := ZMap.set 0 (MMValid 0 1073745920 MMUsable) (ZMap.init MMUndef);\n    real_size := 1;\n    real_vmxinfo := ZMap.init 0\n  }.\n\nGlobal Instance sample_realparams: RealParams.\nProof.\n  constructor.\n  - (*MM_valid real_mm real_size*)\n    unfold MM_valid, MM_range.\n    intros. simpl in *.\n    destruct (zeq i 0); subst.\n    + rewrite ZMap.gss.\n      refine_split'; try reflexivity.\n      omega.\n    + omega.\n  - (*MM_correct real_mm real_size*)\n    unfold MM_correct. \n    intros. simpl in *.\n    destruct (zeq i 0); subst.\n    + destruct (zeq j 0); subst.\n      * rewrite ZMap.gss in *.\n        inv H1. inv H2.\n        constructor.\n      * omega.\n    + omega.\n  - (*MM_kern real_mm real_size *)\n    unfold MM_kern, MM_kern_range.\n    intros.\n    unfold MM_kern_valid. simpl.\n    exists 0, 0, 1073745920.\n    split. omega.\n    split. rewrite ZMap.gss. reflexivity.\n    split. omega.\n    omega.\n  - (*0 < real_size <= Integers.Int.max_unsigned*)\n    simpl. rewrite int_max.\n    omega.\n  - intros.\n    simpl.\n    rewrite ZMap.gi.\n    unfold Integers.Int.max_unsigned.\n    simpl.\n    omega.\nQed.\n\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/driver/RealParamsImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24230356684122378}}
{"text": "Require Import\n        List.\nRequire Import\n        Events\n        LibModel\n        Maps\n        Messages\n        States\n        Types.\n\nModule OrderBook.\n\n  Section SubmitOrder.\n\n    Definition submitOrder_spec (sender: address) (order: Order) : FSpec :=\n      {|\n        fspec_require :=\n          fun wst =>\n            (sender = order_owner order \\/ sender = order_broker order) /\\\n            H2O.map.find (get_order_hash order)\n                         (ob_orders (wst_order_book_state wst))  = None\n        ;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            let hash := get_order_hash order in\n            let orders := ob_orders (wst_order_book_state wst) in\n            let orders' := H2O.upd orders hash order in\n            wst' = wst_update_order_book wst {| ob_orders := orders' |} /\\\n            retval = RetBytes32 hash\n        ;\n\n        fspec_events :=\n          fun wst events =>\n            events = EvtOrderSubmitted sender (get_order_hash order) :: nil\n        ;\n      |}.\n\n  End SubmitOrder.\n\n  Section GetOrderData.\n\n    Definition getOrderData_spec (sender: address) (hash: bytes32) : FSpec :=\n      {|\n        fspec_require :=\n          fun wst => True;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n            wst' = wst /\\\n            retval = RetOrder (H2O.get (ob_orders (wst_order_book_state wst))\n                                       hash);\n\n        fspec_events :=\n          fun wst events => events = nil;\n      |}.\n\n  End GetOrderData.\n\n  Definition get_spec (msg: OrderBookMsg) : FSpec :=\n    match msg with\n    | msg_submitOrder sender order =>\n      submitOrder_spec sender order\n\n    | msg_getOrderData sender hash =>\n      getOrderData_spec sender hash\n    end.\n\n  Definition model\n             (wst: WorldState)\n             (msg: OrderBookMsg)\n             (wst': WorldState)\n             (retval: RetVal)\n             (events: list Event)\n    : Prop :=\n    fspec_sat (get_spec msg) wst wst' retval events.\n\nEnd OrderBook.", "meta": {"author": "sec-bit", "repo": "loopring-protocol2-verification", "sha": "bfb2101faccbefd592a8f63d42e01aae41b06930", "save_path": "github-repos/coq/sec-bit-loopring-protocol2-verification", "path": "github-repos/coq/sec-bit-loopring-protocol2-verification/loopring-protocol2-verification-bfb2101faccbefd592a8f63d42e01aae41b06930/Models/OrderBook.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24230356684122373}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\n(* Contribution to the Coq Library   V6.3 (July 1999)                    *)\n\n(* ----                          machine.v                        ----- *)\n(*                                                                          *)\n(* Author: Pierre Casteran.                                                 *)\n(*    LABRI, URA CNRS 1304,                                                 *)\n(*    Departement d'Informatique, Universite Bordeaux I,                    *)\n(*    33405 Talence CEDEX,                                                  *)\n(*    e-mail:  casteran@labri.u-bordeaux.fr                                 *)\n\n\n(* \n   This file describes the implementation of our powering algorithm:\n*)\nRequire Import monoid.\nRequire Import Constants.\n\n(*  Let us imagine an abstract machine for computing on the monoid (M,o,u)\n  (see \"monoid.v\").\n    This machine has a register X and a stack S.\n*)\n\n\nInductive Instr : Set :=\n  | MUL : Instr\n  | SQR : Instr\n  | PUSH : Instr\n  | SWAP : Instr.       \n\n\n(* sequences of instructions *)\n\nInductive Code : Set :=\n  | End : Code\n  | seq : Instr -> Code -> Code.\n\n\n(* code appending *)\n\n(*Recursive Definition app:Code->Code->Code:=\n    End c' => c'\n  | (seq i  c) c' => (seq i ( app c  c')).\n*)\n\nFixpoint app (c : Code) : Code -> Code :=\n  fun c' : Code => match c with\n                   | End => c'\n                   | seq i c => seq i (app c c')\n                   end.\n\n(* semantics *)\n(*************)\n\nSection Monoid.\n Variable M : Set.\n Variable MO : monoid M.\n Let uM := u _ MO.\n Let oM := o _ MO.\n\n\n Inductive Stack : Set :=\n   | emptystack : Stack\n   | push : M -> Stack -> Stack.\n\n Definition top (s : Stack) :=\n   match s return M with\n   | emptystack => uM\n   | push m _ => m\n   end.\n Definition pop (s : Stack) :=\n   match s return Stack with\n   | emptystack => emptystack\n   | push _ r => r\n   end.\n\n\n(* configurations of the abstract machine *)\n(******************************************)\n\n\n Record Config : Set := config {config_X : M; config_S : Stack}.\n\n\n Lemma Config_inv :\n  forall (a a' : M) (s s' : Stack),\n  a = a' -> s = s' -> config a s = config a' s'.\n (****************************************************************************)\n Proof.\n  intros. rewrite H; rewrite H0; auto.\n Qed.\n \n Hint Resolve Config_inv: arith.\n\n\n\n\n(* Operational semantics of the elementary instructions *)\n\n Definition Exec1 (c : Instr) (v : Config) : Config :=\n   let (m, s) := v in\n   match c with\n   | MUL => config (oM m (top s)) (pop s) \n   | SQR => config (oM m m) s\n   | PUSH => config m (push m s)\n   | SWAP => config m (push (top (pop s)) (push (top s) (pop (pop s))))\n   end.\n (****************************************************************)\n\n\n\n(* Execution of a compound instruction *)\n\n\nFixpoint Exec (c : Code) : Config -> Config :=\n  fun v : Config =>\n  match c with\n  | End => v\n  | seq i c => Exec c (Exec1 i v)\n  end.\n\n (****************************************)\n\n (* Semantics of code   appending *)\n (*********************************)\n\n Lemma Exec_app :\n  forall (c c' : Code) (v : Config), Exec (app c c') v = Exec c' (Exec c v).\n (*******************************************************)\n Proof.\n  simple induction c; simpl in |- *.\n  auto.\n  intros; rewrite H; auto. \n Qed.\n\nEnd Monoid.\n\n", "meta": {"author": "coq-contribs", "repo": "additions", "sha": "0a2ba96483fcb424fa6ce7ebff1469956a0fa3a1", "save_path": "github-repos/coq/coq-contribs-additions", "path": "github-repos/coq/coq-contribs-additions/additions-0a2ba96483fcb424fa6ce7ebff1469956a0fa3a1/machine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.24221508947713932}}
{"text": "Require Import Logic.lib.Coqlib.\nRequire Import Logic.lib.Ensembles_ext.\nRequire Export Logic.lib.register_typeclass.\nRequire Import Logic.GeneralLogic.Base.\nRequire Import Logic.GeneralLogic.ProofTheory.TheoryOfSequentCalculus.\nRequire Import Logic.GeneralLogic.ProofTheory.BasicSequentCalculus.\nRequire Import Logic.MinimumLogic.Syntax.\nRequire Import Logic.MinimumLogic.ProofTheory.TheoryOfSequentCalculus.\nRequire Import Logic.MinimumLogic.ProofTheory.Minimum.\n\nInductive P2D_reg: Type :=.\nInductive D2P_reg: Type :=.\n\nLtac pose_proof_SC_instance n :=\n  let a := get_nth P2D_reg n in\n  match a with\n  | fun x: unit => ?T => \n    try pose_proof_instance_as T x\n  end.\n\nLtac pose_proof_AX_instance n :=\n  let a := get_nth D2P_reg n in\n  match a with\n  | fun x: unit => ?T => \n    try pose_proof_instance_as T x\n  end.\n\nLtac AddSequentCalculus :=\n  let AX := fresh \"AX\" in\n  let GammaD := fresh \"GammaD\" in\n  pose proof Provable2Derivable_Normal as AX;\n  set (GammaD := Provable2Derivable) in AX;\n  clearbody GammaD;\n  rec_from_n (0%nat) pose_proof_SC_instance.\n\nLtac AddAxiomatization :=\n  let SC := fresh \"SC\" in\n  let GammaP := fresh \"GammaP\" in\n  pose proof Derivable2Provable_Normal as SC;\n  set (GammaP := Derivable2Provable) in SC;\n  clearbody GammaP;\n  rec_from_n (0%nat) pose_proof_AX_instance.\n\nInstance reg_Axiomatization2SequentCalculus_SC:\n  RegisterClass P2D_reg (fun SC: unit => @Axiomatization2SequentCalculus_SC) 0.\nQed.\n\nInstance reg_Axiomatization2SequentCalculus_bSC:\n  RegisterClass P2D_reg (fun bSC: unit => @Axiomatization2SequentCalculus_bSC) 1.\nQed.\n\nInstance reg_Axiomatization2SequentCalculus_fwSC:\n  RegisterClass P2D_reg (fun fwSC: unit => @Axiomatization2SequentCalculus_fwSC) 2.\nQed.\n\nInstance reg_Axiomatization2SequentCalculus_minSC:\n  RegisterClass P2D_reg (fun minSC: unit => @Axiomatization2SequentCalculus_minSC) 3.\nQed.\n\nInstance reg_SequentCalculus2Axiomatization_AX:\n  RegisterClass D2P_reg (fun AX: unit => @SequentCalculus2Axiomatization_AX) 0.\nQed.\n\nInstance reg_SequentCalculus2Axiomatization_minAX:\n  RegisterClass D2P_reg (fun minAX: unit => @SequentCalculus2Axiomatization_minAX) 1.\nQed.\n\nSection Test_AddSC.\n\nContext {L: Language}\n        {minL: MinimumLanguage L}\n        {Gamma: Provable L}\n        {minAX: MinimumAxiomatization L Gamma}.\n\nLocal Open Scope logic_base.\nLocal Open Scope syntax.\n\nLemma provable_impp_refl': forall (x: expr), |-- x --> x.\nProof.\n  AddSequentCalculus.\nAbort.\n\nEnd Test_AddSC.\n\nSection Test_AddAX.\n\nContext {L: Language}\n        {minL: MinimumLanguage L}\n        {Gamma: Derivable L}\n        {bSC: BasicSequentCalculus L Gamma}\n        {minSC: MinimumSequentCalculus L Gamma}\n        {fwSC: FiniteWitnessedSequentCalculus L Gamma}.\n\nLocal Open Scope logic_base.\nLocal Open Scope syntax.\n\nLemma derivable_axiom2': forall Phi (x y z: expr), Phi |-- (x --> y --> z) --> (x --> y) --> (x --> z).\nProof.\n  AddAxiomatization.\nAbort.\n\nEnd Test_AddAX.\n", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/MinimumLogic/ProofTheory/ExtensionTactic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2422150894771393}}
{"text": "(* Full safety for DOT (WIP) *)\n\n(* this version is based on fsub2.v *)\n(* based on that, it adds self types *)\n\n(*\nTODO:\n- intersection types\n\n- stp2 trans + narrowing\n- stp/stp2 weakening and regularity\n*)\n\nRequire Export SfLib.\n\nRequire Export Arith.EqNat.\nRequire Export Arith.Le.\n\nModule FSUB.\n\nDefinition id := nat.\n\nInductive ty : Type :=\n  | TBool  : ty\n  | TBot   : ty\n  | TTop   : ty\n  | TFun   : ty -> ty -> ty\n  | TMem   : ty -> ty -> ty\n  | TSel   : id -> ty\n  | TSelH  : id -> ty\n  | TSelB  : id -> ty\n  | TAll   : ty -> ty -> ty\n  | TBind  : ty -> ty\n.\n\nInductive tm : Type :=\n  | ttrue  : tm\n  | tfalse : tm\n  | tvar   : id -> tm\n  | ttyp   : ty -> tm\n  | tapp   : tm -> tm -> tm (* f(x) *)\n  | tabs   : id -> id -> tm -> tm (* \\f x.y *)\n  | ttapp  : tm -> tm -> tm (* f[X] *)\n  | ttabs  : id -> ty -> tm -> tm (* \\f x.y *)\n.\n\nInductive vl : Type :=\n| vty   : list (id*vl) -> ty -> vl\n| vbool : bool -> vl\n| vabs  : list (id*vl) -> id -> id -> tm -> vl\n| vtabs : list (id*vl) -> id -> ty -> tm -> vl\n.\n\n\nDefinition tenv := list (id*ty).\nDefinition venv := list (id*vl).\nDefinition aenv := list (id*(venv*ty)).\n\nHint Unfold venv.\nHint Unfold tenv.\n\nFixpoint fresh {X: Type} (l : list (id * X)): nat :=\n  match l with\n    | [] => 0\n    | (n',a)::l' => 1 + n'\n  end.\n\nFixpoint index {X : Type} (n : id) (l : list (id * X)) : option X :=\n  match l with\n    | [] => None\n    | (n',a) :: l'  =>\n      if le_lt_dec (fresh l') n' then\n        if (beq_nat n n') then Some a else index n l'\n      else None\n  end.\n\nFixpoint indexr {X : Type} (n : id) (l : list (id * X)) : option X :=\n  match l with\n    | [] => None\n    | (n',a) :: l'  => (* DeBrujin *)\n      if (beq_nat n (length l')) then Some a else indexr n l'\n  end.\n\n\n(*\nFixpoint update {X : Type} (n : nat) (x: X)\n               (l : list X) { struct l }: list X :=\n  match l with\n    | [] => []\n    | a :: l'  => if beq_nat n (length l') then x::l' else a :: update n x l'\n  end.\n*)\n\n\n(* LOCALLY NAMELESS *)\n\nInductive closed_rec: nat -> nat -> ty -> Prop :=\n| cl_top: forall k l,\n    closed_rec k l TTop\n| cl_bot: forall k l,\n    closed_rec k l TBot\n| cl_bool: forall k l,\n    closed_rec k l TBool\n| cl_fun: forall k l T1 T2,\n    closed_rec k l T1 ->\n    closed_rec k l T2 ->\n    closed_rec k l (TFun T1 T2)\n| cl_mem: forall k l T1 T2,\n    closed_rec k l T1 ->\n    closed_rec k l T2 ->\n    closed_rec k l (TMem T1 T2)\n| cl_all: forall k l T1 T2,\n    closed_rec k l T1 ->\n    closed_rec (S k) l T2 ->\n    closed_rec k l (TAll T1 T2)\n| cl_bind: forall k l T2,\n    closed_rec (S k) l T2 ->\n    closed_rec k l (TBind T2)\n| cl_sel: forall k l x,\n    closed_rec k l (TSel x)\n| cl_selh: forall k l x,\n    l > x ->\n    closed_rec k l (TSelH x)\n| cl_selb: forall k l i,\n    k > i ->\n    closed_rec k l (TSelB i)\n.\n\nHint Constructors closed_rec.\n\nDefinition closed j l T := closed_rec j l T.\n\n\nFixpoint open_rec (k: nat) (u: ty) (T: ty) { struct T }: ty :=\n  match T with\n    | TSel x      => TSel x (* free var remains free. functional, so we can't check for conflict *)\n    | TSelH i     => TSelH i (*if beq_nat k i then u else TSelH i *)\n    | TSelB i     => if beq_nat k i then u else TSelB i\n    | TAll T1 T2  => TAll (open_rec k u T1) (open_rec (S k) u T2)\n    | TBind T2    => TBind (open_rec (S k) u T2)\n    | TTop        => TTop\n    | TBot        => TBot\n    | TBool       => TBool\n    | TMem T1 T2  => TMem (open_rec k u T1) (open_rec k u T2)\n    | TFun T1 T2  => TFun (open_rec k u T1) (open_rec k u T2)\n  end.\n\nDefinition open u T := open_rec 0 u T.\n\n(* sanity check *)\nExample open_ex1: open (TSel 9) (TAll TBool (TFun (TSelB 1) (TSelB 0))) =\n                      (TAll TBool (TFun (TSel 9) (TSelB 0))).\nProof. compute. eauto. Qed.\n\n\nFixpoint subst (U : ty) (T : ty) {struct T} : ty :=\n  match T with\n    | TTop         => TTop\n    | TBot         => TBot\n    | TBool        => TBool\n    | TMem T1 T2   => TMem (subst U T1) (subst U T2)\n    | TFun T1 T2   => TFun (subst U T1) (subst U T2)\n    | TSelB i      => TSelB i\n    | TSel i       => TSel i\n    | TSelH i      => if beq_nat i 0 then U else TSelH (i-1)\n    | TAll T1 T2   => TAll (subst U T1) (subst U T2)\n    | TBind T2     => TBind (subst U T2)\n  end.\n\nFixpoint nosubst (T : ty) {struct T} : Prop :=\n  match T with\n    | TTop         => True\n    | TBot         => True\n    | TBool        => True\n    | TMem T1 T2   => nosubst T1 /\\ nosubst T2\n    | TFun T1 T2   => nosubst T1 /\\ nosubst T2\n    | TSelB i      => True\n    | TSel i       => True\n    | TSelH i      => i <> 0\n    | TAll T1 T2   => nosubst T1 /\\ nosubst T2\n    | TBind T2     => nosubst T2\n  end.\n\n\nHint Unfold open.\nHint Unfold closed.\n\n\nInductive stp: tenv -> tenv -> ty -> ty -> Prop :=\n| stp_topx: forall G1 GH,\n    stp G1 GH TTop TTop\n| stp_botx: forall G1 GH,\n    stp G1 GH TBot TBot\n| stp_top: forall G1 GH T1,\n    stp G1 GH T1 T1 -> (* regularity *)\n    stp G1 GH T1 TTop\n| stp_bot: forall G1 GH T2,\n    stp G1 GH T2 T2 -> (* regularity *)\n    stp G1 GH TBot T2\n| stp_bool: forall G1 GH,\n    stp G1 GH TBool TBool\n| stp_fun: forall G1 GH T1 T2 T3 T4,\n    stp G1 GH T3 T1 ->\n    stp G1 GH T2 T4 ->\n    stp G1 GH (TFun T1 T2) (TFun T3 T4)\n| stp_mem: forall G1 GH T1 T2 T3 T4,\n    stp G1 GH T3 T1 ->\n    stp G1 GH T2 T4 ->\n    stp G1 GH (TMem T1 T2) (TMem T3 T4)\n| stp_sel1: forall G1 GH TX T2 x,\n    index x G1 = Some TX ->\n    closed 0 0 TX ->\n    stp G1 GH TX (TMem TBot T2) ->\n    stp G1 GH T2 T2 -> (* regularity of stp2 *)\n    stp G1 GH (TSel x) T2\n| stp_sel2: forall G1 GH TX T1 x,\n    index x G1 = Some TX ->\n    closed 0 0 TX ->\n    stp G1 GH TX (TMem T1 TTop) ->\n    stp G1 GH T1 T1 -> (* regularity of stp2 *)\n    stp G1 GH T1 (TSel x)\n| stp_selb1: forall G1 GH TX T2 x,\n    index x G1 = Some TX ->\n    stp G1 [] TX (TBind (TMem TBot T2)) ->   (* Note GH = [] *)\n    stp G1 GH (open (TSel x) T2) (open (TSel x) T2) -> (* regularity *)\n    stp G1 GH (TSel x) (open (TSel x) T2)\n| stp_selb2: forall G1 GH TX T1 x,\n    index x G1 = Some TX ->\n    stp G1 [] TX (TBind (TMem T1 TTop)) ->   (* Note GH = [] *)\n    stp G1 GH (open (TSel x) T1) (open (TSel x) T1) -> (* regularity *)\n    stp G1 GH (open (TSel x) T1) (TSel x)\n| stp_selx: forall G1 GH TX x,\n    index x G1 = Some TX ->\n    stp G1 GH (TSel x) (TSel x)\n| stp_sela1: forall G1 GH TX T2 x,\n    indexr x GH = Some TX ->\n    closed 0 x TX ->\n    stp G1 GH TX (TMem TBot T2) ->   (* not using self name for now *)\n    stp G1 GH T2 T2 -> (* regularity of stp2 *)\n    stp G1 GH (TSelH x) T2\n| stp_sela2: forall G1 GH TX T1 x,\n    indexr x GH = Some TX ->\n    closed 0 x TX ->\n    stp G1 GH TX (TMem T1 TTop) ->   (* not using self name for now *)\n    stp G1 GH T1 T1 -> (* regularity of stp2 *)\n    stp G1 GH T1 (TSelH x)\n| stp_selab1: forall G1 GH TX T2 T2' x,\n    indexr x GH = Some TX ->\n    stp G1 [] TX (TBind (TMem TBot T2)) ->   (* XXX Note GH = [] *)\n    T2' = (open (TSelH x) T2) ->\n    stp G1 GH T2' T2' -> (* regularity *)\n    stp G1 GH (TSelH x) T2'\n| stp_selab2: forall G1 GH TX T1 T1' x,\n    indexr x GH = Some TX ->\n    stp G1 [] TX (TBind (TMem T1 TTop)) ->   (* XXX Note GH = [] *)\n    T1' = (open (TSelH x) T1) ->\n    stp G1 GH T1' T1' -> (* regularity *)\n    stp G1 GH T1' (TSelH x)\n| stp_selax: forall G1 GH TX x,\n    indexr x GH = Some TX  ->\n    stp G1 GH (TSelH x) (TSelH x)\n| stp_all: forall G1 GH T1 T2 T3 T4 x,\n    stp G1 GH T3 T1 ->\n    x = length GH ->\n    closed 1 (length GH) T2 -> (* must not accidentally bind x *)\n    closed 1 (length GH) T4 ->\n    stp G1 ((0,T1)::GH) (open (TSelH x) T2) (open (TSelH x) T2) -> (* regularity *)\n    stp G1 ((0,T3)::GH) (open (TSelH x) T2) (open (TSelH x) T4) ->\n    stp G1 GH (TAll T1 T2) (TAll T3 T4)\n| stp_bindx: forall G1 GH T1 T2 x,\n    x = length GH ->\n    closed 1 (length GH) T1 -> (* must not accidentally bind x *)\n    closed 1 (length GH) T2 ->\n    stp G1 ((0,open (TSelH x) T2)::GH) (open (TSelH x) T2) (open (TSelH x) T2) -> (* regularity *)\n    stp G1 ((0,open (TSelH x) T1)::GH) (open (TSelH x) T1) (open (TSelH x) T2) ->\n    stp G1 GH (TBind T1) (TBind T2)\n.\n\n\n(*\nwith path_type: tenv -> tenv -> id -> ty -> Prop :=\n| pt_var: forall G1 GH TX x,\n    index x G1 = Some TX ->\n    path_type G1 GH x TX\n| pt_sub: forall G1 GH TX x,\n    path_type has_type env e T1 ->\n           stp env [] T1 T2 ->\n           has_type env e T2\n\nwith pathH_type: tenv -> tenv -> id -> ty -> Prop :=\n| pth_var: forall G1 GH TX T x,\n    indexr x GH = Some TX ->\n    stp G1 GH TX T ->\n    pathH_type G1 GH x T\n*)\n\n\nHint Constructors stp.\n\n(* TODO *)\n\nInductive has_type : tenv -> tm -> ty -> Prop :=\n| t_true: forall env,\n           has_type env ttrue TBool\n| t_false: forall env,\n           has_type env tfalse TBool\n| t_var: forall x env T1,\n           index x env = Some T1 ->\n           has_type env (tvar x) T1\n| t_var_pack: forall x env T1,\n           has_type env (tvar x) (open (TSel x) T1) ->\n           has_type env (tvar x) (TBind T1)\n| t_var_unpack: forall x env T1,\n           has_type env (tvar x) (TBind T1) ->\n           has_type env (tvar x) (open (TSel x) T1)\n| t_typ: forall env x T1 T1X,\n           fresh env = x ->\n           open (TSel x) T1 = T1X ->\n           stp ((x,TMem T1X T1X)::env) [] T1X T1X ->\n           has_type env (ttyp T1) (TBind (TMem T1 T1))\n| t_app: forall env f x T1 T2,\n           has_type env f (TFun T1 T2) ->\n           has_type env x T1 ->\n           has_type env (tapp f x) T2\n| t_abs: forall env f x y T1 T2,\n           has_type ((x,T1)::(f,TFun T1 T2)::env) y T2 ->\n           stp env [] (TFun T1 T2) (TFun T1 T2) ->\n           fresh env <= f ->\n           1+f <= x ->\n           has_type env (tabs f x y) (TFun T1 T2)\n| t_tapp: forall env f x T11 T12,\n           has_type env f (TAll T11 T12) ->\n           has_type env x T11 ->\n           stp env [] T12 T12 ->\n           has_type env (ttapp f x) T12\n(*\nNOTE: both the POPLmark paper and Cardelli's paper use this rule:\nDoes it make a difference? It seems like we can always widen f?\n\n| t_tapp: forall env f T2 T11 T12 ,\n           has_type env f (TAll T11 T12) ->\n           stp env T2 T11 ->\n           has_type env (ttapp f T2) (open T2 T12)\n\n*)\n| t_tabs: forall env x y T1 T2,\n           has_type ((x,T1)::env) y (open (TSel x) T2) ->\n           stp env [] (TAll T1 T2) (TAll T1 T2) ->\n           fresh env = x ->\n           has_type env (ttabs x T1 y) (TAll T1 T2)\n\n| t_sub: forall env e T1 T2,\n           has_type env e T1 ->\n           stp env [] T1 T2 ->\n           has_type env e T2\n.\n\n\nDefinition base (v:vl): venv :=\n  match v with\n    | vty GX _ => GX\n    | vbool _ => nil\n    | vabs GX _ _ _ => GX\n    | vtabs GX _ _ _ => GX\n  end.\n\n\nDefinition MAX := 2.\n\nInductive stp2: nat -> bool -> venv -> ty -> venv -> ty -> list (id*(venv*ty)) -> nat -> Prop :=\n| stp2_topx: forall m G1 G2 GH n1,\n    stp2 m true G1 TTop G2 TTop GH (S n1)\n| stp2_botx: forall m G1 G2 GH n1,\n    stp2 m true G1 TBot G2 TBot GH (S n1)\n| stp2_top: forall m G1 G2 GH T n1,\n    stp2 m true G1 T G1 T GH n1 -> (* regularity *)\n    stp2 m true G1 T G2 TTop GH (S n1)\n| stp2_bot: forall m G1 G2 GH T n1,\n    stp2 m true G2 T G2 T GH n1 -> (* regularity *)\n    stp2 m true G1 TBot G2 T GH (S n1)\n| stp2_bool: forall m G1 G2 GH n1,\n    stp2 m true G1 TBool G2 TBool GH (S n1)\n| stp2_fun: forall m G1 G2 T1 T2 T3 T4 GH n1 n2,\n    stp2 MAX false G2 T3 G1 T1 GH n1 ->\n    stp2 MAX false G1 T2 G2 T4 GH n2 ->\n    stp2 m true G1 (TFun T1 T2) G2 (TFun T3 T4) GH (S (n1+n2))\n| stp2_mem: forall G1 G2 T1 T2 T3 T4 GH n1 n2,\n    stp2 0 false G2 T3 G1 T1 GH n1 ->\n    stp2 0 true G1 T2 G2 T4 GH n2 ->\n    stp2 0 true G1 (TMem T1 T2) G2 (TMem T3 T4) GH (S (n1+n2))\n\n| stp2_mem2: forall m G1 G2 T1 T2 T3 T4 GH n1 n2,\n    stp2 (S m) false G2 T3 G1 T1 GH n1 ->\n    stp2 (S m) false G1 T2 G2 T4 GH n2 ->\n    stp2 (S m) true G1 (TMem T1 T2) G2 (TMem T3 T4) GH (S (n1+n2))\n\n\n(* strong version, with precise/invertible bounds *)\n| stp2_strong_sel1: forall G1 G2 GX TX x T2 GH n1,\n    index x G1 = Some (vty GX TX) ->\n(*  val_type GX (vty GX TX) (TMem TX TX) -> (* for downgrade *)*)\n    closed 0 0 TX ->\n    stp2 0 true GX TX G2 T2 GH n1 ->\n    stp2 0 true G1 (TSel x) G2 T2 GH (S n1)\n\n| stp2_strong_sel2: forall G1 G2 GX TX x T1 GH n1,\n    index x G2 = Some (vty GX TX) ->\n(*  val_type GX (vty GX TX) (TMem TX TX) -> (* for downgrade *)*)\n    closed 0 0 TX ->\n    stp2 0 false G1 T1 GX TX GH n1 ->\n    stp2 0 true G1 T1 G2 (TSel x) GH (S n1)\n\n| stp2_strong_selx: forall G1 G2 v x1 x2 GH n1,\n    index x1 G1 = Some v ->\n    index x2 G2 = Some v ->\n    stp2 0 true G1 (TSel x1) G2 (TSel x2) GH n1\n\n\n(* existing object, but imprecise type *)\n| stp2_sel1: forall m G1 G2 GX TX x T2 GH n1 n2 v,\n    index x G1 = Some v ->\n    val_type GX v TX ->\n    closed 0 0 TX ->\n    stp2 (S m) false GX TX G2 (TMem TBot T2) GH n1 ->\n    stp2 (S m) true G2 T2 G2 T2 GH n2 -> (* regularity *)\n    stp2 (S m) true G1 (TSel x) G2 T2 GH (S (n1+n2))\n\n| stp2_selb1: forall m G1 G2 GX TX x T2 GH n1 n2 v,\n    index x G1 = Some v ->\n    val_type GX v TX ->\n    closed 0 0 TX ->\n    stp2 (S (S m)) false GX TX G2 (TBind (TMem TBot T2)) [] n1 -> (* Note GH = [] *)\n    stp2 (S (S m)) true G2 (open (TSel x) T2) G2 (open (TSel x) T2) GH n2 -> (* regularity *)\n    stp2 (S (S m)) true G1 (TSel x) G2 (open (TSel x) T2) GH (S (n1+n2))\n\n\n| stp2_sel2: forall m G1 G2 GX TX x T1 GH n1 n2 v,\n    index x G2 = Some v ->\n    val_type GX v TX ->\n    closed 0 0 TX ->\n    stp2 (S m) false GX TX G1 (TMem T1 TTop) GH n1 ->\n    stp2 (S m) true G1 T1 G1 T1 GH n2 -> (* regularity *)\n    stp2 (S m) true G1 T1 G2 (TSel x) GH (S (n1+n2))\n\n| stp2_selx: forall m G1 G2 v x1 x2 GH n1,\n    index x1 G1 = Some v ->\n    index x2 G2 = Some v ->\n    stp2 (S m) true G1 (TSel x1) G2 (TSel x2) GH (S n1)\n\n(* hypothetical object *)\n| stp2_sela1: forall m G1 G2 GX TX x T2 GH n1 n2,\n    indexr x GH = Some (GX, TX) ->\n    closed 0 x TX ->\n    stp2 (S m) false GX TX G2 (TMem TBot T2) GH n1 ->\n    stp2 (S m) true G2 T2 G2 T2 GH n2 -> (* regularity *)\n    stp2 (S m) true G1 (TSelH x) G2 T2 GH (S (n1+n2))\n\n| stp2_selab1: forall m G1 G2 GX TX x T2 T2' GH n1 n2, (* XXX TODO *)\n    indexr x GH = Some (GX, TX) ->\n    (* closed 0 x TX -> *)\n    stp2 (S m) false GX TX G2 (TBind (TMem TBot T2)) [] n1 ->\n    T2' = (open (TSelH x) T2) ->\n    stp2 (S m) true G2 T2' G2 T2' GH n2 -> (* regularity *)\n    stp2 (S m) true G1 (TSelH x) G2 T2' GH (S (n1+n2))\n\n| stp2_sela2: forall m G1 G2 GX TX x T1 GH n1 n2,\n    indexr x GH = Some (GX, TX) ->\n    closed 0 x TX ->\n    stp2 (S m) false GX TX G2 (TMem T1 TTop) GH n1 ->\n    stp2 (S m) true G1 T1 G1 T1 GH n2 -> (* regularity *)\n    stp2 (S m) true G1 T1 G2 (TSelH x) GH (S (n1+n2))\n\n\n| stp2_selax: forall m G1 G2 GX TX x GH n1,\n    indexr x GH = Some (GX, TX) ->\n    stp2 (S m) true G1 (TSelH x) G2 (TSelH x) GH (S n1)\n\n\n| stp2_all: forall m G1 G2 T1 T2 T3 T4 GH n1 n1' n2,\n    stp2 MAX false G2 T3 G1 T1 GH n1 ->\n    closed 1 (length GH) T2 -> (* must not accidentally bind x *)\n    closed 1 (length GH) T4 ->\n    stp2 MAX false G1 (open (TSelH (length GH)) T2) G1 (open (TSelH (length GH)) T2) ((0,(G1, T1))::GH) n1' -> (* regularity *)\n    stp2 MAX false G1 (open (TSelH (length GH)) T2) G2 (open (TSelH (length GH)) T4) ((0,(G2, T3))::GH) n2 ->\n    stp2 m true G1 (TAll T1 T2) G2 (TAll T3 T4) GH (S (n1+n1'+n2))\n\n| stp2_bind: forall G1 G2 T1 T2 GH n1 n2,\n    closed 1 (length GH) T1 -> (* must not accidentally bind x *)\n    closed 1 (length GH) T2 ->\n    stp2 1 false G2 (open (TSelH (length GH)) T2) G2 (open (TSelH (length GH)) T2) ((0,(G2, open (TSelH (length GH)) T2))::GH) n2 -> (* regularity *)\n    stp2 1 false G1 (open (TSelH (length GH)) T1) G2 (open (TSelH (length GH)) T2) ((0,(G1, open (TSelH (length GH)) T1))::GH) n1 ->\n    stp2 0 true G1 (TBind T1) G2 (TBind T2) GH (S (n1+n2))\n\n| stp2_bindb: forall m G1 G2 T1 T2 GH n1 n2,\n    closed 1 (length GH) T1 -> (* must not accidentally bind x *)\n    closed 1 (length GH) T2 ->\n    stp2 (S m) false G2 (open (TSelH (length GH)) T2) G2 (open (TSelH (length GH)) T2) ((0,(G2, open (TSelH (length GH)) T2))::GH) n2 -> (* regularity *)\n    stp2 (S m) false G1 (open (TSelH (length GH)) T1) G2 (open (TSelH (length GH)) T2) ((0,(G1, open (TSelH (length GH)) T1))::GH) n1 ->\n    stp2 (S m) true G1 (TBind T1) G2 (TBind T2) GH (S (n1+n2))\n\n\n| stp2_wrapf: forall m G1 G2 T1 T2 GH n1,\n    stp2 m true G1 T1 G2 T2 GH n1 ->\n    stp2 m false G1 T1 G2 T2 GH (S n1)\n| stp2_transf: forall m G1 G2 G3 T1 T2 T3 GH n1 n2,\n    stp2 m true G1 T1 G2 T2 GH n1 ->\n    stp2 m false G2 T2 G3 T3 GH n2 ->\n    stp2 m false G1 T1 G3 T3 GH (S (n1+n2))\n\n\n\nwith wf_env : venv -> tenv -> Prop :=\n| wfe_nil : wf_env nil nil\n| wfe_cons : forall n v t vs ts,\n    val_type ((n,v)::vs) v t ->\n    wf_env vs ts ->\n    wf_env (cons (n,v) vs) (cons (n,t) ts)\n\nwith val_type : venv -> vl -> ty -> Prop :=\n| v_ty: forall env venv tenv T1 TE,\n    wf_env venv tenv -> (* T1 wf in tenv ? *)\n    (exists n, stp2 0 true venv (TMem T1 T1) env TE [] n)->\n    val_type env (vty venv T1) TE\n| v_bool: forall venv b TE,\n    (exists n, stp2 0 true [] TBool venv TE [] n) ->\n    val_type venv (vbool b) TE\n| v_abs: forall env venv tenv f x y T1 T2 TE,\n    wf_env venv tenv ->\n    has_type ((x,T1)::(f,TFun T1 T2)::tenv) y T2 ->\n    fresh venv <= f ->\n    1 + f <= x ->\n    (exists n, stp2 0 true venv (TFun T1 T2) env TE [] n)->\n    val_type env (vabs venv f x y) TE\n| v_tabs: forall env venv tenv x y T1 T2 TE,\n    wf_env venv tenv ->\n    has_type ((x,T1)::tenv) y (open (TSel x) T2) ->\n    fresh venv = x ->\n    (exists n, stp2 0 true venv (TAll T1 T2) env TE [] n) ->\n    val_type env (vtabs venv x T1 y) TE\n| v_pack: forall venv venv3 x v T T2 T3,\n    index x venv = Some v ->\n    val_type venv v T ->\n    open (TSel x) T2 = T ->\n    (exists n, stp2 0 true venv (TBind T2) venv3 T3 [] n) ->\n    val_type venv3 v T3\n.\n\n\nInductive wf_envh : venv -> aenv -> tenv -> Prop :=\n| wfeh_nil : forall vvs, wf_envh vvs nil nil\n| wfeh_cons : forall n t vs vvs ts,\n    wf_envh vvs vs ts ->\n    wf_envh vvs (cons (n,(vvs,t)) vs) (cons (n,t) ts)\n.\n\nInductive valh_type : venv -> aenv -> (venv*ty) -> ty -> Prop :=\n| v_tya: forall aenv venv T1,\n    valh_type venv aenv (venv, T1) T1\n.\n\n\n\nDefinition stpd2 b G1 T1 G2 T2 GH := exists n, stp2 MAX b G1 T1 G2 T2 GH n.\nDefinition atpd2 b G1 T1 G2 T2 GH := exists n, stp2 1 b G1 T1 G2 T2 GH n.\nDefinition sstpd2 b G1 T1 G2 T2 GH := exists n, stp2 0 b G1 T1 G2 T2 GH n.\n\n\n\n\n\n\nLtac ep := match goal with\n             | [ |- stp2 ?M1 ?M2 ?G1 ?T1 ?G2 ?T2 ?GH ?N ] => assert (exists (x:nat), stp2 M1 M2 G1 T1 G2 T2 GH x) as EEX\n           end.\n\nLtac eu := match goal with\n             | H: stpd2 _ _ _ _ _ _ |- _ => destruct H as [? H]\n             | H: atpd2 _ _ _ _ _ _ |- _ => destruct H as [? H]\n             | H: sstpd2 _ _ _ _ _ _ |- _ => destruct H as [? H]\n(*             | H: exists n: nat ,  _ |- _  =>\n               destruct H as [e P] *)\n           end.\n\nHint Constructors stp2.\nHint Unfold stpd2.\n\nLemma stpd2_topx: forall G1 G2 GH,\n    stpd2 true G1 TTop G2 TTop GH.\nProof. intros. repeat exists (S 0). eauto. Qed.\nLemma stpd2_botx: forall G1 G2 GH,\n    stpd2 true G1 TBot G2 TBot GH.\nProof. intros. repeat exists (S 0). eauto. Qed.\nLemma stpd2_top: forall G1 G2 GH T,\n    stpd2 true G1 T G1 T GH ->\n    stpd2 true G1 T G2 TTop GH.\nProof. intros. repeat eu. eauto. Qed.\nLemma stpd2_bot: forall G1 G2 GH T,\n    stpd2 true G2 T G2 T GH ->\n    stpd2 true G1 TBot G2 T GH.\nProof. intros. repeat eu. eauto. Qed.\nLemma stpd2_bool: forall G1 G2 GH,\n    stpd2 true G1 TBool G2 TBool GH.\nProof. intros. repeat exists (S 0). eauto. Qed.\nLemma stpd2_fun: forall G1 G2 GH T11 T12 T21 T22,\n    stpd2 false G2 T21 G1 T11 GH ->\n    stpd2 false G1 T12 G2 T22 GH ->\n    stpd2 true G1 (TFun T11 T12) G2 (TFun T21 T22) GH.\nProof. intros. repeat eu. eauto. Qed.\nLemma stpd2_mem: forall G1 G2 GH T11 T12 T21 T22,\n    stpd2 false G2 T21 G1 T11 GH ->\n    stpd2 false G1 T12 G2 T22 GH ->\n    stpd2 true G1 (TMem T11 T12) G2 (TMem T21 T22) GH.\nProof. intros. repeat eu. eauto. unfold stpd2. eexists. eapply stp2_mem2; eauto. Qed.\n\nLemma stpd2_sel1: forall G1 G2 GX TX x T2 GH v,\n    index x G1 = Some v ->\n    val_type GX v TX ->\n    closed 0 0 TX ->\n    stpd2 false GX TX G2 (TMem TBot T2) GH ->\n    stpd2 true G2 T2 G2 T2 GH ->\n    stpd2 true G1 (TSel x) G2 T2 GH.\nProof. intros. repeat eu. eexists. eapply stp2_sel1; eauto. Qed.\n\nLemma stpd2_selb1: forall G1 G2 GX TX x T2 GH v,\n    index x G1 = Some v ->\n    val_type GX v TX ->\n    closed 0 0 TX ->\n    stpd2 false GX TX G2 (TBind (TMem TBot T2)) [] -> (* Note GH = [] *)\n    stpd2 true G2 (open (TSel x) T2) G2 (open (TSel x) T2) GH ->\n    stpd2 true G1 (TSel x) G2 (open (TSel x) T2) GH.\nProof. intros. repeat eu. eexists. eapply stp2_selb1; eauto. Qed.\n\nLemma stpd2_sel2: forall G1 G2 GX TX x T1 GH v,\n    index x G2 = Some v ->\n    val_type GX v TX ->\n    closed 0 0 TX ->\n    stpd2 false GX TX G1 (TMem T1 TTop) GH ->\n    stpd2 true G1 T1 G1 T1 GH ->\n    stpd2 true G1 T1 G2 (TSel x) GH.\nProof. intros. repeat eu. eexists. eapply stp2_sel2; eauto. Qed.\n\nLemma stpd2_selx: forall G1 G2 x1 x2 GH v,\n    index x1 G1 = Some v ->\n    index x2 G2 = Some v ->\n    stpd2 true G1 (TSel x1) G2 (TSel x2) GH.\nProof. intros. eauto. exists (S 0). eapply stp2_selx; eauto. Qed.\n\nLemma stpd2_selab1: forall G1 G2 GX TX x T2 GH,\n    indexr x GH = Some (GX, TX) ->\n    (* closed 0 x TX -> *)\n    stpd2 false GX TX G2 (TBind (TMem TBot T2)) [] -> (* Note GH = [] *)\n    stpd2 true G2 (open (TSelH x) T2) G2 (open (TSelH x) T2) GH ->\n    stpd2 true G1 (TSelH x) G2 (open (TSelH x) T2) GH.\nProof. intros. repeat eu. eauto. eexists. eapply stp2_selab1; eauto. Qed.\n\nLemma stpd2_sela1: forall G1 G2 GX TX x T2 GH,\n    indexr x GH = Some (GX, TX) ->\n    closed 0 x TX ->\n    stpd2 false GX TX G2 (TMem TBot T2) GH ->\n    stpd2 true G2 T2 G2 T2 GH ->\n    stpd2 true G1 (TSelH x) G2 T2 GH.\nProof. intros. repeat eu. eauto. eexists. eapply stp2_sela1; eauto. Qed.\n\nLemma stpd2_sela2: forall G1 G2 GX TX x T1 GH,\n    indexr x GH = Some (GX, TX) ->\n    closed 0 x TX ->\n    stpd2 false GX TX G2 (TMem T1 TTop) GH ->\n    stpd2 true G1 T1 G1 T1 GH ->\n    stpd2 true G1 T1 G2 (TSelH x) GH.\nProof. intros. repeat eu. eauto. eexists. eapply stp2_sela2; eauto. Qed.\n\n\nLemma stpd2_selax: forall G1 G2 GX TX x GH,\n    indexr x GH = Some (GX, TX) ->\n    stpd2 true G1 (TSelH x) G2 (TSelH x) GH.\nProof. intros. exists (S 0). eauto. eapply stp2_selax; eauto. Qed.\n\n\nLemma stpd2_all: forall G1 G2 T1 T2 T3 T4 GH,\n    stpd2 false G2 T3 G1 T1 GH ->\n    closed 1 (length GH) T2 ->\n    closed 1 (length GH) T4 ->\n    stpd2 false G1 (open (TSelH (length GH)) T2) G1 (open (TSelH (length GH)) T2) ((0,(G1, T1))::GH) ->\n    stpd2 false G1 (open (TSelH (length GH)) T2) G2 (open (TSelH (length GH)) T4) ((0,(G2, T3))::GH) ->\n    stpd2 true G1 (TAll T1 T2) G2 (TAll T3 T4) GH.\nProof. intros. repeat eu. eauto. Qed.\n\nLemma stpd2_bind: forall G1 G2 T1 T2 GH,\n    closed 1 (length GH) T1 ->\n    closed 1 (length GH) T2 ->\n    stpd2 false G2 (open (TSelH (length GH)) T2) G2 (open (TSelH (length GH)) T2) ((0,(G2, open (TSelH (length GH)) T2))::GH) ->\n    stpd2 false G1 (open (TSelH (length GH)) T1) G2 (open (TSelH (length GH)) T2) ((0,(G1, open (TSelH (length GH)) T1))::GH) ->\n    stpd2 true G1 (TBind T1) G2 (TBind T2) GH.\nProof. intros. repeat eu. eauto. unfold stpd2. eexists. eapply stp2_bindb; eauto. Qed.\n\nLemma stpd2_wrapf: forall G1 G2 T1 T2 GH,\n    stpd2 true G1 T1 G2 T2 GH ->\n    stpd2 false G1 T1 G2 T2 GH.\nProof. intros. repeat eu. eauto. Qed.\nLemma stpd2_transf: forall G1 G2 G3 T1 T2 T3 GH,\n    stpd2 true G1 T1 G2 T2 GH ->\n    stpd2 false G2 T2 G3 T3 GH ->\n    stpd2 false G1 T1 G3 T3 GH.\nProof. intros. repeat eu. eauto. Qed.\n\n\nLemma sstpd2_wrapf: forall G1 G2 T1 T2 GH,\n    sstpd2 true G1 T1 G2 T2 GH ->\n    sstpd2 false G1 T1 G2 T2 GH.\nProof. intros. repeat eu. eexists. eapply stp2_wrapf. eauto. Qed.\nLemma sstpd2_transf: forall G1 G2 G3 T1 T2 T3 GH,\n    sstpd2 true G1 T1 G2 T2 GH ->\n    sstpd2 false G2 T2 G3 T3 GH ->\n    sstpd2 false G1 T1 G3 T3 GH.\nProof. intros. repeat eu. eexists. eapply stp2_transf; eauto. Qed.\n\n\nLemma atpd2_transf: forall G1 G2 G3 T1 T2 T3 GH,\n    atpd2 true G1 T1 G2 T2 GH ->\n    atpd2 false G2 T2 G3 T3 GH ->\n    atpd2 false G1 T1 G3 T3 GH.\nProof. intros. repeat eu. eexists. eapply stp2_transf; eauto. Qed.\n\n(*\nNone             means timeout\nSome None        means stuck\nSome (Some v))   means result v\n\nCould use do-notation to clean up syntax.\n *)\n\nFixpoint teval(n: nat)(env: venv)(t: tm){struct n}: option (option vl) :=\n  match n with\n    | 0 => None\n    | S n =>\n      match t with\n        | ttrue      => Some (Some (vbool true))\n        | tfalse     => Some (Some (vbool false))\n        | tvar x     => Some (index x env)\n        | tabs f x y => Some (Some (vabs env f x y))\n        | ttabs x T y  => Some (Some (vtabs env x T y))\n        | ttyp T     => Some (Some (vty env T))\n        | tapp ef ex   =>\n          match teval n env ex with\n            | None => None\n            | Some None => Some None\n            | Some (Some vx) =>\n              match teval n env ef with\n                | None => None\n                | Some None => Some None\n                | Some (Some (vbool _)) => Some None\n                | Some (Some (vty _ _)) => Some None\n                | Some (Some (vtabs _ _ _ _)) => Some None\n                | Some (Some (vabs env2 f x ey)) =>\n                  teval n ((x,vx)::(f,vabs env2 f x ey)::env2) ey\n              end\n          end\n        | ttapp ef ex   =>\n          match teval n env ex with\n            | None => None\n            | Some None => Some None\n            | Some (Some vx) =>\n              match teval n env ef with\n                | None => None\n                | Some None => Some None\n                | Some (Some (vbool _)) => Some None\n                | Some (Some (vty _ _)) => Some None\n                | Some (Some (vabs _ _ _ _)) => Some None\n                | Some (Some (vtabs env2 x T ey)) =>\n                  teval n ((x,vx)::env2) ey\n              end\n          end\n      end\n  end.\n\n\nHint Constructors ty.\nHint Constructors tm.\nHint Constructors vl.\n\nHint Constructors closed_rec.\nHint Constructors has_type.\nHint Constructors val_type.\nHint Constructors wf_env.\nHint Constructors stp.\nHint Constructors stp2.\n\nHint Constructors option.\nHint Constructors list.\n\nHint Unfold index.\nHint Unfold length.\nHint Unfold closed.\nHint Unfold open.\n\nHint Resolve ex_intro.\n\n\n\n(* ############################################################ *)\n(* Examples *)\n(* ############################################################ *)\n\n\n(*\nmatch goal with\n        | |- has_type _ (tvar _) _ =>\n          try solve [apply t_vara;\n                      repeat (econstructor; eauto)]\n          | _ => idtac\n      end;\n*)\n\nLtac crush_has_tp :=\n  try solve [eapply stp_selx; compute; eauto; crush_has_tp];\n  try solve [eapply stp_selax; compute; eauto; crush_has_tp];\n  try solve [eapply cl_selb; compute; eauto; crush_has_tp];\n  try solve [(econstructor; compute; eauto; crush_has_tp)].\n\nLtac crush2 :=\n  try solve [(eapply stp_selx; compute; eauto; crush2)];\n  try solve [(eapply stp_selax; compute; eauto; crush2)];\n  try solve [(eapply stp_sel1; compute; eauto; crush2)];\n  try solve [(eapply stp_sela1; compute; eauto; crush2)];\n  try solve [(eapply cl_selb; compute; eauto; crush2)];\n  try solve [(econstructor; compute; eauto; crush2)];\n  try solve [(eapply t_sub; eapply t_var; compute; eauto; crush2)].\n\n\n(* define polymorphic identity function *)\n\nDefinition polyId := TAll (TBind (TMem TBot TTop)) (TFun (TSelB 0) (TSelB 0)).\n\nExample ex1: has_type [] (ttabs 0 (TBind (TMem TBot TTop)) (tabs 1 2 (tvar 2))) polyId.\nProof.\n  crush2.\nQed.\n\n\n(* instantiate it to bool *)\n\nExample ex2: has_type [(0,polyId)] (ttapp (tvar 0) (ttyp TBool)) (TFun TBool TBool).\nProof.\n  eapply t_tapp. instantiate (1:= (TBind (TMem TBool TBool))).\n    { eapply t_sub.\n      { eapply t_var. simpl. eauto. }\n      { eapply stp_all; eauto. { eapply stp_bindx; crush2. } compute. eapply cl_fun; eauto.\n        eapply stp_fun. compute. eapply stp_selax; crush2. crush2.\n        eapply stp_fun. compute. eapply stp_selab2. crush2.\n        instantiate (1:=TBool). crush2. crush2. crush2.\n        simpl. eapply stp_selab1. crush2.\n        instantiate (1:=TBool). crush2. crush2. crush2.\n      }\n    }\n    { eapply t_typ; crush2. }\n    crush2.\nQed.\n\n\n\n(* define brand / unbrand client function *)\n\nDefinition brandUnbrand :=\n  TAll (TBind (TMem TBot TTop))\n       (TFun\n          (TFun TBool (TSelB 0)) (* brand *)\n          (TFun\n             (TFun (TSelB 0) TBool) (* unbrand *)\n             TBool)).\n\nExample ex3:\n  has_type []\n           (ttabs 0 (TBind (TMem TBot TTop))\n                  (tabs 1 2\n                        (tabs 3 4\n                              (tapp (tvar 4) (tapp (tvar 2) ttrue)))))\n           brandUnbrand.\nProof.\n  crush2.\nQed.\n\n\n(* instantiating it at bool is admissible *)\n\nExample ex4:\n  has_type [(1,TFun TBool TBool);(0,brandUnbrand)]\n           (tvar 0) (TAll (TBind (TMem TBool TBool)) (TFun (TFun TBool TBool) (TFun (TFun TBool TBool) TBool))).\nProof.\n  eapply t_sub. crush2. crush2. eapply stp_all; crush2. compute. eapply stp_fun. eapply stp_fun. crush2.\n  eapply stp_selab2. crush2. instantiate(1:=TBool). crush2. crush2. crush2.\n  eapply stp_fun. crush2. eapply stp_fun.\n  eapply stp_selab1. crush2. instantiate(1:=TBool). crush2. crush2. crush2.\n  crush2. crush2.\nQed.\n\nHint Resolve ex4.\n\n(* apply it to identity functions *)\n\nExample ex5:\n  has_type [(1,TFun TBool TBool);(0,brandUnbrand)]\n           (tapp (tapp (ttapp (tvar 0) (ttyp TBool)) (tvar 1)) (tvar 1)) TBool.\nProof.\n  crush2.\nQed.\n\n\n(* test expansion *)\n\nExample ex6:\n  has_type [(1,TSel 0);(0,TMem TBot (TBind (TFun TBool (TSelB 0))))]\n           (tvar 1) (TFun TBool (TSel 1)).\nProof.\n  remember (TFun TBool (TSel 1)) as T.\n  assert (T = open (TSel 1) (TFun TBool (TSelB 0))). compute. eauto.\n  rewrite H.\n  eapply t_var_unpack. eapply t_sub. eapply t_var. compute. eauto. crush2.\nQed.\n\n\nExample ex7:\n  stp [(1,TSel 0);(0,TMem TBot (TBind (TMem TBot (TFun TBool (TSelB 0)))))] []\n           (TSel 1) (TFun TBool(TSel 1)).\nProof.\n  remember (TFun TBool (TSel 1)) as T.\n  assert (T = open (TSel 1) (TFun TBool (TSelB 0))). compute. eauto.\n  rewrite H.\n  eapply stp_selb1. compute. eauto.\n  eapply stp_sel1. compute. eauto.\n  crush2.\n  eapply stp_mem. eauto.\n  eapply stp_bindx; crush2.\n  eapply stp_bindx; crush2.\n  crush2.\nQed.\n\n\n\n\n\n(* ############################################################ *)\n(* Proofs *)\n(* ############################################################ *)\n\n\n\n\n\nLemma wf_fresh : forall vs ts,\n                    wf_env vs ts ->\n                    (fresh vs = fresh ts).\nProof.\n  intros. induction H. auto.\n  compute. eauto.\nQed.\n\nHint Immediate wf_fresh.\n\n\nLemma wfh_length : forall vvs vs ts,\n                    wf_envh vvs vs ts ->\n                    (length vs = length ts).\nProof.\n  intros. induction H. auto.\n  compute. eauto.\nQed.\n\nHint Immediate wf_fresh.\n\nLemma index_max : forall X vs n (T: X),\n                       index n vs = Some T ->\n                       n < fresh vs.\nProof.\n  intros X vs. induction vs.\n  - Case \"nil\". intros. inversion H.\n  - Case \"cons\".\n    intros. inversion H. destruct a.\n    case_eq (le_lt_dec (fresh vs) i); intros ? E1.\n    + SCase \"ok\".\n      rewrite E1 in H1.\n      case_eq (beq_nat n i); intros E2.\n      * SSCase \"hit\".\n        eapply beq_nat_true in E2. subst n. compute. eauto.\n      * SSCase \"miss\".\n        rewrite E2 in H1.\n        assert (n < fresh vs). eapply IHvs. apply H1.\n        compute. omega.\n    + SCase \"bad\".\n      rewrite E1 in H1. inversion H1.\nQed.\n\nLemma indexr_max : forall X vs n (T: X),\n                       indexr n vs = Some T ->\n                       n < length vs.\nProof.\n  intros X vs. induction vs.\n  - Case \"nil\". intros. inversion H.\n  - Case \"cons\".\n    intros. inversion H. destruct a.\n    case_eq (beq_nat n (length vs)); intros E2.\n    + SSCase \"hit\".\n      eapply beq_nat_true in E2. subst n. compute. eauto.\n    + SSCase \"miss\".\n      rewrite E2 in H1.\n      assert (n < length vs). eapply IHvs. apply H1.\n      compute. eauto.\nQed.\n\n\n\nLemma le_xx : forall a b,\n                       a <= b ->\n                       exists E, le_lt_dec a b = left E.\nProof. intros.\n  case_eq (le_lt_dec a b). intros. eauto.\n  intros. omega.\nQed.\nLemma le_yy : forall a b,\n                       a > b ->\n                       exists E, le_lt_dec a b = right E.\nProof. intros.\n  case_eq (le_lt_dec a b). intros. omega.\n  intros. eauto.\nQed.\n\nLemma index_extend : forall X vs n n' x (T: X),\n                       index n vs = Some T ->\n                       fresh vs <= n' ->\n                       index n ((n',x)::vs) = Some T.\n\nProof.\n  intros.\n  assert (n < fresh vs). eapply index_max. eauto.\n  assert (n <> n'). omega.\n  assert (beq_nat n n' = false) as E. eapply beq_nat_false_iff; eauto.\n  assert (fresh vs <= n') as E2. omega.\n  elim (le_xx (fresh vs) n' E2). intros ? EX.\n  unfold index. unfold index in H. rewrite H. rewrite E. rewrite EX. reflexivity.\nQed.\n\nLemma indexr_extend : forall X vs n n' x (T: X),\n                       indexr n vs = Some T ->\n                       indexr n ((n',x)::vs) = Some T.\n\nProof.\n  intros.\n  assert (n < length vs). eapply indexr_max. eauto.\n  assert (beq_nat n (length vs) = false) as E. eapply beq_nat_false_iff. omega.\n  unfold indexr. unfold indexr in H. rewrite H. rewrite E. reflexivity.\nQed.\n\n\n(* splicing -- for stp_extend. not finished *)\n\nFixpoint splice n (T : ty) {struct T} : ty :=\n  match T with\n    | TTop         => TTop\n    | TBot         => TBot\n    | TBool        => TBool\n    | TMem T1 T2   => TMem (splice n T1) (splice n T2)\n    | TFun T1 T2   => TFun (splice n T1) (splice n T2)\n    | TSelB i      => TSelB i\n    | TSel i       => TSel i\n    | TSelH i      => if le_lt_dec n i  then TSelH (i+1) else TSelH i\n    | TAll T1 T2   => TAll (splice n T1) (splice n T2)\n    | TBind T2   => TBind (splice n T2)\n  end.\n\nDefinition splicett n (V: (id*ty)) :=\n  match V with\n    | (x,T) => (x,(splice n T))\n  end.\n\nDefinition spliceat n (V: (id*(venv*ty))) :=\n  match V with\n    | (x,(G,T)) => (x,(G,splice n T))\n  end.\n\nLemma splice_open_permute: forall {X} (G:list (id*X)) T n j k,\nn + k >= length G ->\n(open_rec j (TSelH (n + S k)) (splice (length G) T)) =\n(splice (length G) (open_rec j (TSelH (n + k)) T)).\nProof.\n  intros X G T. induction T; intros; simpl; eauto;\n  try rewrite IHT1; try rewrite IHT2; try rewrite IHT; eauto.\n\n  case_eq (le_lt_dec (length G) i); intros E LE; simpl; eauto.\n  case_eq (beq_nat j i); intros E; simpl; eauto.\n  case_eq (le_lt_dec (length G) (n + length G)); intros EL LE.\n  assert (n + S (length G) = n + length G + 1). omega.\n  case_eq (le_lt_dec (length G) (n+k)); intros E' LE'; simpl; eauto.\n  assert (n + S k=n + k + 1) as R by omega. rewrite R. reflexivity.\n  omega. omega.\nQed.\n\nLemma indexr_splice_hi: forall G0 G2 x0 x v1 T,\n    indexr x0 (G2 ++ G0) = Some T ->\n    length G0 <= x0 ->\n    indexr (x0 + 1) (map (splicett (length G0)) G2 ++ (x, v1) :: G0) = Some (splice (length G0) T).\nProof.\n  intros G0 G2. induction G2; intros.\n  - eapply indexr_max in H. simpl in H. omega.\n  - simpl in H. destruct a.\n    case_eq (beq_nat x0 (length (G2 ++ G0))); intros E.\n    + rewrite E in H. inversion H. subst. simpl.\n      rewrite app_length in E.\n      rewrite app_length. rewrite map_length. simpl.\n      assert (beq_nat (x0 + 1) (length G2 + S (length G0)) = true). eapply beq_nat_true_iff. eapply beq_nat_true_iff in E. omega.\n      rewrite H1. eauto.\n    + rewrite E in H.  eapply IHG2 in H. eapply indexr_extend. eapply H. eauto.\nQed.\n\nLemma indexr_spliceat_hi: forall G0 G2 x0 x v1 G T,\n    indexr x0 (G2 ++ G0) = Some (G, T) ->\n    length G0 <= x0 ->\n    indexr (x0 + 1) (map (spliceat (length G0)) G2 ++ (x, v1) :: G0) = Some (G, splice (length G0) T).\nProof.\n  intros G0 G2. induction G2; intros.\n  - eapply indexr_max in H. simpl in H. omega.\n  - simpl in H. destruct a.\n    case_eq (beq_nat x0 (length (G2 ++ G0))); intros E.\n    + rewrite E in H. inversion H. subst. simpl.\n      rewrite app_length in E.\n      rewrite app_length. rewrite map_length. simpl.\n      assert (beq_nat (x0 + 1) (length G2 + S (length G0)) = true). eapply beq_nat_true_iff. eapply beq_nat_true_iff in E. omega.\n      rewrite H1. eauto.\n    + rewrite E in H.  eapply IHG2 in H. destruct p. eapply indexr_extend. eapply H. eauto.\nQed.\n\nLemma plus_lt_contra: forall a b,\n  a + b < b -> False.\nProof.\n  intros a b H. induction a.\n  - simpl in H. apply lt_irrefl in H. assumption.\n  - simpl in H. apply IHa. omega.\nQed.\n\nLemma indexr_splice_lo0: forall {X} G0 G2 x0 (T:X),\n    indexr x0 (G2 ++ G0) = Some T ->\n    x0 < length G0 ->\n    indexr x0 G0 = Some T.\nProof.\n  intros X G0 G2. induction G2; intros.\n  - simpl in H. apply H.\n  - simpl in H. destruct a.\n    case_eq (beq_nat x0 (length (G2 ++ G0))); intros E.\n    + eapply beq_nat_true_iff in E. subst.\n      rewrite app_length in H0. apply plus_lt_contra in H0. inversion H0.\n    + rewrite E in H. apply IHG2. apply H. apply H0.\nQed.\n\nLemma indexr_extend_mult: forall {X} G0 G2 x0 (T:X),\n    indexr x0 G0 = Some T ->\n    indexr x0 (G2++G0) = Some T.\nProof.\n  intros X G0 G2. induction G2; intros.\n  - simpl. assumption.\n  - destruct a. simpl.\n    case_eq (beq_nat x0 (length (G2 ++ G0))); intros E.\n    + eapply beq_nat_true_iff in E.\n      apply indexr_max in H. subst.\n      rewrite app_length in H. apply plus_lt_contra in H. inversion H.\n    + apply IHG2. assumption.\nQed.\n\nLemma indexr_splice_lo: forall G0 G2 x0 x v1 T f,\n    indexr x0 (G2 ++ G0) = Some T ->\n    x0 < length G0 ->\n    indexr x0 (map (splicett f) G2 ++ (x, v1) :: G0) = Some T.\nProof.\n  intros.\n  assert (indexr x0 G0 = Some T). eapply indexr_splice_lo0; eauto.\n  eapply indexr_extend_mult. eapply indexr_extend. eauto.\nQed.\n\nLemma indexr_spliceat_lo: forall G0 G2 x0 x v1 G T f,\n    indexr x0 (G2 ++ G0) = Some (G, T) ->\n    x0 < length G0 ->\n    indexr x0 (map (spliceat f) G2 ++ (x, v1) :: G0) = Some (G, T).\nProof.\n  intros.\n  assert (indexr x0 G0 = Some (G, T)). eapply indexr_splice_lo0; eauto.\n  eapply indexr_extend_mult. eapply indexr_extend. eauto.\nQed.\n\n\nLemma fresh_splice_ctx: forall G n,\n  fresh G = fresh (map (splicett n) G).\nProof.\n  intros. induction G.\n  - simpl. reflexivity.\n  - destruct a. simpl. reflexivity.\nQed.\n\nLemma index_splice_ctx: forall G x T n,\n  index x G = Some T ->\n  index x (map (splicett n) G) = Some (splice n T).\nProof.\n  intros. induction G.\n  - simpl in H. inversion H.\n  - destruct a. simpl in H.\n    case_eq (le_lt_dec (fresh G) i); intros E LE; rewrite LE in H.\n    case_eq (beq_nat x i); intros Eq; rewrite Eq in H.\n    inversion H. simpl. erewrite <- (fresh_splice_ctx). rewrite LE.\n    rewrite Eq. reflexivity.\n    simpl. erewrite <- (fresh_splice_ctx). rewrite LE.\n    rewrite Eq. apply IHG. apply H.\n    inversion H.\nQed.\n\nLemma closed_splice: forall j l T n,\n  closed j l T ->\n  closed j (S l) (splice n T).\nProof.\n  intros. induction H; simpl; eauto.\n  case_eq (le_lt_dec n x); intros E LE.\n  unfold closed. apply cl_selh. omega.\n  unfold closed. apply cl_selh. omega.\nQed.\n\nLemma map_splice_length_inc: forall G0 G2 x v1,\n   (length (map (splicett (length G0)) G2 ++ (x, v1) :: G0)) = (S (length (G2 ++ G0))).\nProof.\n  intros. rewrite app_length. rewrite map_length. induction G2.\n  - simpl. reflexivity.\n  - simpl. eauto.\nQed.\n\nLemma map_spliceat_length_inc: forall G0 G2 x v1,\n   (length (map (spliceat (length G0)) G2 ++ (x, v1) :: G0)) = (S (length (G2 ++ G0))).\nProof.\n  intros. rewrite app_length. rewrite map_length. induction G2.\n  - simpl. reflexivity.\n  - simpl. eauto.\nQed.\n\nLemma closed_inc: forall j l T,\n  closed j l T ->\n  closed j (S l) T.\nProof.\n  intros. induction H; simpl; eauto.\n  unfold closed. apply cl_selh. omega.\nQed.\n\nLemma closed_inc_mult: forall j l l' T,\n  closed j l T ->\n  l' >= l ->\n  closed j l' T.\nProof.\n  intros j l l' T H LE. induction LE.\n  - assumption.\n  - apply closed_inc. assumption.\nQed.\n\nLtac sp :=\n  match goal with\n    | A : ?P, H : ?P -> _ |- _ => specialize (H A)\n  end.\n\nLemma closed_splice_idem: forall k l T n,\n                            closed k l T ->\n                            n >= l ->\n                            splice n T = T.\nProof.\n  intros. induction H; simpl; repeat sp; repeat (match goal with\n    | H: splice ?N ?T = ?T |- _ => rewrite H\n  end); eauto.\n  case_eq (le_lt_dec n x); intros E LE. omega. reflexivity.\nQed.\n\nLtac ev := repeat match goal with\n                    | H: exists _, _ |- _ => destruct H\n                    | H: _ /\\  _ |- _ => destruct H\n           end.\n\nLemma closed_upgrade: forall i j l T,\n closed_rec i l T ->\n j >= i ->\n closed_rec j l T.\nProof.\n intros. generalize dependent j. induction H; intros; eauto.\n Case \"TAll\". econstructor. eapply IHclosed_rec1. omega. eapply IHclosed_rec2. omega.\n Case \"TBind\". econstructor. eapply IHclosed_rec. omega.\n Case \"TSelB\". econstructor. omega.\nQed.\n\nLemma closed_upgrade_free: forall i l k T,\n closed_rec i l T ->\n k >= l ->\n closed_rec i k T.\nProof.\n intros. generalize dependent k. induction H; intros; eauto.\n Case \"TSelH\". econstructor. omega.\nQed.\n\n\nLemma closed_open: forall j n TX T, closed (j+1) n T -> closed j n TX -> closed j n (open_rec j TX T).\nProof.\n  intros. generalize dependent j. induction T; intros; inversion H; unfold closed; try econstructor; try eapply IHT1; eauto; try eapply IHT2; eauto; try eapply IHT; eauto. eapply closed_upgrade. eauto. eauto.\n\n  - Case \"TSelB\". simpl.\n    case_eq (beq_nat j i); intros E. eauto.\n\n    econstructor. eapply beq_nat_false_iff in E. omega.\n\n  - eauto.\n  - eapply closed_upgrade; eauto.\n  - eapply closed_upgrade; eauto.\nQed.\n\nLemma stp_closed : forall G GH T1 T2,\n                     stp G GH T1 T2 ->\n                     closed 0 (length GH) T1 /\\ closed 0 (length GH) T2.\nProof.\n  intros. induction H;\n    try solve [repeat ev; split; eauto using indexr_max];\n    try solve [try inversion IHstp; split; eauto; apply cl_selh; eapply indexr_max; eassumption];\n    try solve [inversion IHstp1 as [IH1 IH2]; inversion IH2; split; eauto; apply cl_selh; eapply indexr_max; eassumption].\nQed.\n\nLemma stp_closed2 : forall G1 GH T1 T2,\n                       stp G1 GH T1 T2 ->\n                       closed 0 (length GH) T2.\nProof.\n  intros. apply (proj2 (stp_closed G1 GH T1 T2 H)).\nQed.\n\nLemma stp_closed1 : forall G1 GH T1 T2,\n                       stp G1 GH T1 T2 ->\n                       closed 0 (length GH) T1.\nProof.\n  intros. apply (proj1 (stp_closed G1 GH T1 T2 H)).\nQed.\n\nLemma stp2_closed: forall G1 G2 T1 T2 GH s m n1,\n                     stp2 s m G1 T1 G2 T2 GH n1 ->\n                     closed 0 (length GH) T1 /\\ closed 0 (length GH) T2.\n  intros. induction H;\n    try solve [repeat ev; split; eauto];\n    try solve [try inversion IHstp2_1; try inversion IHstp2_2; split; eauto; apply cl_selh; eapply indexr_max; eassumption];\n    try solve [inversion IHstp2 as [IH1 IH2]; inversion IH2; split; eauto; apply cl_selh; eapply indexr_max; eassumption].\nQed.\n\nLemma stp2_closed2 : forall G1 G2 T1 T2 GH s m n1,\n                       stp2 s m G1 T1 G2 T2 GH n1 ->\n                       closed 0 (length GH) T2.\nProof.\n  intros. apply (proj2 (stp2_closed G1 G2 T1 T2 GH s m n1 H)).\nQed.\n\nLemma stp2_closed1 : forall G1 G2 T1 T2 GH s m n1,\n                       stp2 s m G1 T1 G2 T2 GH n1 ->\n                       closed 0 (length GH) T1.\nProof.\n  intros. apply (proj1 (stp2_closed G1 G2 T1 T2 GH s m n1 H)).\nQed.\n\nLemma stp_splice : forall GX G0 G1 T1 T2 x v1,\n   stp GX (G1++G0) T1 T2 ->\n   stp GX ((map (splicett (length G0)) G1) ++ (x,v1)::G0) (splice (length G0) T1) (splice (length G0) T2).\nProof.\n  intros GX G0 G1 T1 T2 x v1 H. remember (G1++G0) as G.\n  revert G0 G1 HeqG.\n  induction H; intros; subst GH; simpl; eauto.\n  - Case \"sel1\".\n    eapply stp_sel1. apply H. assumption.\n    assert (splice (length G0) TX=TX) as A. {\n      eapply closed_splice_idem. eassumption. omega.\n    }\n    rewrite <- A. apply IHstp1. reflexivity.\n    apply IHstp2. reflexivity.\n  - Case \"sel2\".\n    eapply stp_sel2. apply H. assumption.\n    assert (splice (length G0) TX=TX) as A. {\n      eapply closed_splice_idem. eassumption. omega.\n    }\n    rewrite <- A. apply IHstp1. reflexivity.\n    apply IHstp2. reflexivity.\n  - Case \"selb1\".\n    assert (splice (length G0) (open (TSel x0) T2)=(open (TSel x0) T2)) as A. {\n      eapply closed_splice_idem. apply stp_closed2 in H0. inversion H0. subst.\n      simpl in H5. inversion H5. subst.\n      eapply closed_open. simpl. eassumption. eauto.\n      omega.\n    }\n    rewrite A. eapply stp_selb1; eauto.\n    rewrite <- A. apply IHstp2; eauto.\n  - Case \"selb2\".\n    assert (splice (length G0) (open (TSel x0) T1)=(open (TSel x0) T1)) as A. {\n      eapply closed_splice_idem. apply stp_closed2 in H0. inversion H0. subst.\n      simpl in H5. inversion H5. subst.\n      eapply closed_open. simpl. eassumption. eauto.\n      omega.\n    }\n    rewrite A. eapply stp_selb2; eauto.\n    rewrite <- A. apply IHstp2; eauto.\n  - Case \"sela1\".\n    case_eq (le_lt_dec (length G0) x0); intros E LE.\n    + eapply stp_sela1. eapply indexr_splice_hi. eauto. eauto.\n      eapply closed_splice in H0. assert (S x0 = x0 +1) as A by omega.\n      rewrite <- A. eapply H0.\n      eapply IHstp1. eauto.\n      eapply IHstp2. eauto.\n    + eapply stp_sela1. eapply indexr_splice_lo. eauto. eauto. eauto. eauto.\n      assert (splice (length G0) TX=TX) as A. {\n        eapply closed_splice_idem. eassumption. omega.\n      }\n      rewrite <- A. eapply IHstp1. eauto.\n      eapply IHstp2. eauto.\n  - Case \"sela2\".\n    case_eq (le_lt_dec (length G0) x0); intros E LE.\n    + eapply stp_sela2. eapply indexr_splice_hi. eauto. eauto.\n      eapply closed_splice in H0. assert (S x0 = x0 +1) as A by omega.\n      rewrite <- A. eapply H0.\n      eapply IHstp1. eauto.\n      eapply IHstp2. eauto.\n    + eapply stp_sela2. eapply indexr_splice_lo. eauto. eauto. eauto. eauto.\n      assert (splice (length G0) TX=TX) as A. {\n        eapply closed_splice_idem. eassumption. omega.\n      }\n      rewrite <- A. eapply IHstp1. eauto.\n      eapply IHstp2. eauto.\n  - Case \"selab1\".\n    case_eq (le_lt_dec (length G0) x0); intros E LE.\n    + eapply stp_selab1.\n      eapply indexr_splice_hi; eauto.\n      instantiate (1:=T2).\n      assert (splice (length G0) TX=TX) as A. {\n        apply stp_closed1 in H0. simpl in H0.\n        eapply closed_splice_idem.\n        apply H0.\n        omega.\n      }\n      rewrite A. apply H0.\n      rewrite H1.\n      unfold open.\n      assert (TSelH x0=TSelH (x0+0)) as B. {\n        rewrite <- plus_n_O. reflexivity.\n      }\n      rewrite B. rewrite <- splice_open_permute.\n      assert (splice (length G0) T2=T2) as C. {\n        apply stp_closed2 in H0. simpl in H0. inversion H0; subst.\n        inversion H6; subst.\n        eapply closed_splice_idem. eassumption. omega.\n      }\n      rewrite C. reflexivity. omega.\n      apply IHstp2; eauto.\n    + eapply stp_selab1.\n      eapply indexr_splice_lo; eauto.\n      eassumption.\n      rewrite H1.\n      apply stp_closed2 in H0. simpl in H0. inversion H0; subst.\n      inversion H6; subst.\n      apply closed_upgrade_free with (k:=(length G0)) in H8.\n      eapply closed_splice_idem. eapply closed_open. eassumption. apply cl_selh.\n      omega. omega. omega.\n      apply IHstp2; eauto.\n  - Case \"selab2\".\n    case_eq (le_lt_dec (length G0) x0); intros E LE.\n    + eapply stp_selab2.\n      eapply indexr_splice_hi; eauto.\n      instantiate (1:=T1).\n      assert (splice (length G0) TX=TX) as A. {\n        apply stp_closed1 in H0. simpl in H0.\n        eapply closed_splice_idem.\n        apply H0.\n        omega.\n      }\n      rewrite A. apply H0.\n      rewrite H1.\n      unfold open.\n      assert (TSelH x0=TSelH (x0+0)) as B. {\n        rewrite <- plus_n_O. reflexivity.\n      }\n      rewrite B. rewrite <- splice_open_permute.\n      assert (splice (length G0) T1=T1) as C. {\n        apply stp_closed2 in H0. simpl in H0. inversion H0; subst.\n        inversion H6; subst.\n        eapply closed_splice_idem. eassumption. omega.\n      }\n      rewrite C. reflexivity. omega.\n      apply IHstp2; eauto.\n    + eapply stp_selab2.\n      eapply indexr_splice_lo; eauto.\n      eassumption.\n      rewrite H1.\n      apply stp_closed2 in H0. simpl in H0. inversion H0; subst.\n      inversion H6; subst.\n      apply closed_upgrade_free with (k:=(length G0)) in H7.\n      eapply closed_splice_idem. eapply closed_open. eassumption. apply cl_selh.\n      omega. omega. omega.\n      apply IHstp2; eauto.\n  - Case \"selax\".\n    case_eq (le_lt_dec (length G0) x0); intros E LE.\n    + eapply stp_selax. eapply indexr_splice_hi. eauto. eauto.\n    + eapply stp_selax. eapply indexr_splice_lo. eauto. eauto.\n  - Case \"all\".\n    eapply stp_all.\n    eapply IHstp1. eauto. eauto. eauto.\n\n    simpl. rewrite map_splice_length_inc. apply closed_splice. assumption.\n\n    simpl. rewrite map_splice_length_inc. apply closed_splice. assumption.\n\n    specialize IHstp2 with (G3:=G0) (G4:=(0, T1) :: G2).\n    simpl in IHstp2. rewrite app_length. rewrite map_length. simpl.\n    repeat rewrite splice_open_permute with (j:=0). subst x0.\n    rewrite app_length in IHstp2. simpl in IHstp2.\n    eapply IHstp2. eauto. omega.\n\n    specialize IHstp3 with (G3:=G0) (G4:=(0, T3) :: G2).\n    simpl in IHstp2. rewrite app_length. rewrite map_length. simpl.\n    repeat rewrite splice_open_permute with (j:=0). subst x0.\n    rewrite app_length in IHstp3. simpl in IHstp3.\n    eapply IHstp3. eauto. omega. omega.\n\n  - Case \"bind\".\n    eapply stp_bindx.\n    eauto.\n\n    rewrite map_splice_length_inc. apply closed_splice. assumption.\n    rewrite map_splice_length_inc. apply closed_splice. assumption.\n\n    rewrite app_length. rewrite map_length. simpl.\n    repeat rewrite splice_open_permute with (j:=0). subst x0.\n    specialize IHstp1 with (G3:=G0) (G4:=(0, (open (TSelH (length G2 + length G0)) T2))::G2).\n    rewrite app_length in IHstp1. simpl in IHstp1. unfold open in IHstp1.\n    eapply IHstp1. eauto. omega.\n\n    rewrite app_length. rewrite map_length. simpl.\n    repeat rewrite splice_open_permute with (j:=0). subst x0.\n    specialize IHstp2 with (G3:=G0) (G4:=(0, (open (TSelH (length G2 + length G0)) T1))::G2).\n    rewrite app_length in IHstp2. simpl in IHstp2. unfold open in IHstp2.\n    eapply IHstp2. eauto. omega. omega.\nQed.\n\nLemma stp2_splice : forall G1 T1 G2 T2 GH1 GH0 x v1 s m n1,\n   stp2 s m G1 T1 G2 T2 (GH1++GH0) n1 ->\n   stp2 s m G1 (splice (length GH0) T1) G2 (splice (length GH0) T2) ((map (spliceat (length GH0)) GH1) ++ (x,v1)::GH0) n1.\nProof.\n  intros G1 T1 G2 T2 GH1 GH0 x v1 s m n1 H. remember (GH1++GH0) as GH.\n  revert GH0 GH1 HeqGH.\n  induction H; intros; subst GH; simpl; eauto.\n  - Case \"strong_sel1\".\n    eapply stp2_strong_sel1. apply H. assumption. (*assumption.*)\n    assert (splice (length GH0) TX=TX) as A. {\n      eapply closed_splice_idem. eassumption. omega.\n    }\n    rewrite <- A. apply IHstp2.\n    reflexivity.\n  - Case \"strong_sel2\".\n    eapply stp2_strong_sel2. apply H. assumption. (*assumption.*)\n    assert (splice (length GH0) TX=TX) as A. {\n      eapply closed_splice_idem. eassumption. omega.\n    }\n    rewrite <- A. apply IHstp2.\n    reflexivity.\n  - Case \"sel1\".\n    eapply stp2_sel1. apply H. eassumption. assumption.\n    assert (splice (length GH0) TX=TX) as A. {\n      eapply closed_splice_idem. eassumption. omega.\n    }\n    rewrite <- A. apply IHstp2_1.\n    reflexivity.\n    apply IHstp2_2. reflexivity.\n\n  - Case \"selb1\".\n    assert (splice (length GH0) (open (TSel x0) T2)=(open (TSel x0) T2)) as A. {\n      eapply closed_splice_idem. apply stp2_closed2 in H2. inversion H2. subst.\n      simpl in H7. inversion H7. subst.\n      eapply closed_open. simpl. eassumption. eauto.\n      omega.\n    }\n    rewrite A. eapply stp2_selb1; eauto.\n    rewrite <- A. apply IHstp2_2; eauto.\n  - Case \"sel2\".\n    eapply stp2_sel2. apply H. eassumption. assumption.\n    assert (splice (length GH0) TX=TX) as A. {\n      eapply closed_splice_idem. eassumption. omega.\n    }\n    rewrite <- A. apply IHstp2_1.\n    reflexivity.\n    apply IHstp2_2. reflexivity.\n  - Case \"sela1\".\n    case_eq (le_lt_dec (length GH0) x0); intros E LE.\n    + eapply stp2_sela1. eapply indexr_spliceat_hi. apply H. eauto.\n      eapply closed_splice in H0. assert (S x0 = x0 +1) as EQ by omega. rewrite <- EQ.\n      eapply H0.\n      eapply IHstp2_1. eauto.\n      eapply IHstp2_2. eauto.\n    + eapply stp2_sela1. eapply indexr_spliceat_lo. apply H. eauto. eauto.\n      assert (splice (length GH0) TX=TX) as A. {\n        eapply closed_splice_idem. eassumption. omega.\n      }\n      rewrite <- A. eapply IHstp2_1. eauto. eapply IHstp2_2. eauto.\n\n  - Case \"selab1\".\n    case_eq (le_lt_dec (length GH0) x0); intros E LE.\n    + eapply stp2_selab1.\n      eapply indexr_spliceat_hi; eauto.\n      instantiate (1:=T2).\n      assert (splice (length GH0) TX=TX) as A. {\n        apply stp2_closed1 in H0. simpl in H0.\n        eapply closed_splice_idem.\n        apply H0.\n        omega.\n      }\n      rewrite A. apply H0.\n      rewrite H1.\n      unfold open.\n      assert (TSelH x0=TSelH (x0+0)) as B. {\n        rewrite <- plus_n_O. reflexivity.\n      }\n      rewrite B. rewrite <- splice_open_permute.\n      assert (splice (length GH0) T2=T2) as C. {\n        apply stp2_closed2 in H0. simpl in H0. inversion H0; subst.\n        inversion H6; subst.\n        eapply closed_splice_idem. eassumption. omega.\n      }\n      rewrite C. reflexivity. omega.\n      apply IHstp2_2; eauto.\n    + eapply stp2_selab1.\n      eapply indexr_spliceat_lo; eauto.\n      eassumption.\n      rewrite H1.\n      apply stp2_closed2 in H0. simpl in H0. inversion H0; subst.\n      inversion H6; subst.\n      apply closed_upgrade_free with (k:=(length GH0)) in H8.\n      eapply closed_splice_idem. eapply closed_open. eassumption. apply cl_selh.\n      omega. omega. omega.\n      apply IHstp2_2; eauto.\n  - Case \"sela2\".\n    case_eq (le_lt_dec (length GH0) x0); intros E LE.\n    + eapply stp2_sela2. eapply indexr_spliceat_hi. apply H. eauto.\n      eapply closed_splice in H0. assert (S x0 = x0 +1) as EQ by omega. rewrite <- EQ.\n      eapply H0.\n      eapply IHstp2_1. eauto.\n      eapply IHstp2_2. eauto.\n    + eapply stp2_sela2. eapply indexr_spliceat_lo. apply H. eauto. eauto.\n      assert (splice (length GH0) TX=TX) as A. {\n        eapply closed_splice_idem. eassumption. omega.\n      }\n      rewrite <- A. eapply IHstp2_1. eauto. eapply IHstp2_2. eauto.\n  - Case \"selax\".\n    case_eq (le_lt_dec (length GH0) x0); intros E LE.\n    + eapply stp2_selax.\n      eapply indexr_spliceat_hi. apply H. eauto.\n    + eapply stp2_selax.\n      eapply indexr_spliceat_lo. apply H. eauto.\n  - Case \"all\".\n    eapply stp2_all.\n    eapply IHstp2_1. reflexivity.\n\n    simpl. rewrite map_spliceat_length_inc. apply closed_splice. assumption.\n\n    simpl. rewrite map_spliceat_length_inc. apply closed_splice. assumption.\n\n    specialize IHstp2_2 with (GH2:=GH0) (GH3:=(0, (G1, T1)) :: GH1).\n    simpl in IHstp2_2. rewrite app_length. rewrite map_length. simpl.\n    repeat rewrite splice_open_permute with (j:=0).\n    rewrite app_length in IHstp2_2. simpl in IHstp2_2.\n    eapply IHstp2_2. reflexivity. omega.\n\n    specialize IHstp2_3 with (GH2:=GH0) (GH3:=(0, (G2, T3)) :: GH1).\n    simpl in IHstp2_3. rewrite app_length. rewrite map_length. simpl.\n    repeat rewrite splice_open_permute with (j:=0).\n    rewrite app_length in IHstp2_3. simpl in IHstp2_3.\n    eapply IHstp2_3. reflexivity. omega. omega.\n  - Case \"bind\".\n    eapply stp2_bind.\n\n    simpl. rewrite map_spliceat_length_inc. apply closed_splice. assumption.\n\n    simpl. rewrite map_spliceat_length_inc. apply closed_splice. assumption.\n\n    rewrite app_length. rewrite map_length. simpl.\n    repeat rewrite splice_open_permute with (j:=0).\n    specialize IHstp2_1 with (GH2:=GH0) (GH3:=(0, (G2,(open (TSelH (length GH1 + length GH0)) T2)))::GH1).\n    rewrite app_length in IHstp2_1. simpl in IHstp2_1. unfold open in IHstp2_1.\n    eapply IHstp2_1. eauto. omega.\n\n    rewrite app_length. rewrite map_length. simpl.\n    repeat rewrite splice_open_permute with (j:=0).\n    specialize IHstp2_2 with (GH2:=GH0) (GH3:=(0, (G1,(open (TSelH (length GH1 + length GH0)) T1)))::GH1).\n    rewrite app_length in IHstp2_2. simpl in IHstp2_2. unfold open in IHstp2_2.\n    eapply IHstp2_2. eauto. omega. omega.\n  - Case \"bindb\".\n    eapply stp2_bindb.\n\n    simpl. rewrite map_spliceat_length_inc. apply closed_splice. assumption.\n\n    simpl. rewrite map_spliceat_length_inc. apply closed_splice. assumption.\n\n    rewrite app_length. rewrite map_length. simpl.\n    repeat rewrite splice_open_permute with (j:=0).\n    specialize IHstp2_1 with (GH2:=GH0) (GH3:=(0, (G2,(open (TSelH (length GH1 + length GH0)) T2)))::GH1).\n    rewrite app_length in IHstp2_1. simpl in IHstp2_1. unfold open in IHstp2_1.\n    eapply IHstp2_1. eauto. omega.\n\n    rewrite app_length. rewrite map_length. simpl.\n    repeat rewrite splice_open_permute with (j:=0).\n    specialize IHstp2_2 with (GH2:=GH0) (GH3:=(0, (G1,(open (TSelH (length GH1 + length GH0)) T1)))::GH1).\n    rewrite app_length in IHstp2_2. simpl in IHstp2_2. unfold open in IHstp2_2.\n    eapply IHstp2_2. eauto. omega. omega.\nQed.\n\nLemma stp_extend : forall G1 GH T1 T2 x v1,\n                       stp G1 GH T1 T2 ->\n                       stp G1 ((x,v1)::GH) T1 T2.\nProof.\n  intros. induction H; eauto using indexr_extend.\n  - Case \"all\".\n  assert (splice (length GH) T2 = T2) as A2. {\n    eapply closed_splice_idem. apply H1. omega.\n  }\n  assert (splice (length GH) T4 = T4) as A4. {\n    eapply closed_splice_idem. apply H2. omega.\n  }\n  assert (TSelH (S (length GH)) = splice (length GH) (TSelH (length GH))) as AH. {\n    simpl. case_eq (le_lt_dec (length GH) (length GH)); intros E LE.\n    simpl. rewrite NPeano.Nat.add_1_r. reflexivity.\n    clear LE. apply lt_irrefl in E. inversion E.\n  }\n  assert (closed 0 (length GH) T1).  eapply stp_closed2. eauto.\n  assert (splice (length GH) T1 = T1) as A1. {\n    eapply closed_splice_idem. eauto. omega.\n  }\n  assert (closed 0 (length GH) T3). eapply stp_closed1. eauto.\n  assert (splice (length GH) T3 = T3) as A3. {\n    eapply closed_splice_idem. eauto. omega.\n  }\n  assert (map (splicett (length GH)) [(0,T1)] ++(x,v1)::GH =((0,T1)::(x,v1)::GH)) as HGX1. {\n    simpl. rewrite A1. eauto.\n  }\n  assert (map (splicett (length GH)) [(0,T3)] ++(x,v1)::GH =((0,T3)::(x,v1)::GH)) as HGX3. {\n    simpl. rewrite A3. eauto.\n  }\n  apply stp_all with (x:=length ((x,v1) :: GH)).\n  apply IHstp1.\n  reflexivity.\n  apply closed_inc. apply H1.\n  apply closed_inc. apply H2.\n  simpl.\n  rewrite <- A2. rewrite <- A2.\n  unfold open.\n  change (TSelH (S (length GH))) with (TSelH (0 + (S (length GH)))).\n  rewrite -> splice_open_permute.\n  rewrite <- HGX1.\n  apply stp_splice.\n  rewrite A2. simpl. unfold open in H3. rewrite <- H0. apply H3.\n  omega.\n  simpl.\n  rewrite <- A2. rewrite <- A4.\n  unfold open.\n  change (TSelH (S (length GH))) with (TSelH (0 + (S (length GH)))).\n  rewrite -> splice_open_permute. rewrite -> splice_open_permute.\n  rewrite <- HGX3.\n  apply stp_splice.\n  simpl. unfold open in H4. rewrite <- H0. apply H4.\n  omega. omega.\n\n  - Case \"bind\".\n  assert (splice (length GH) T2 = T2) as A2. {\n    eapply closed_splice_idem. apply H1. omega.\n  }\n  assert (splice (length GH) T1 = T1) as A1. {\n    eapply closed_splice_idem. eauto. omega.\n  }\n  apply stp_bindx with (x:=length ((x,v1) :: GH)).\n  reflexivity.\n  apply closed_inc. apply H0.\n  apply closed_inc. apply H1.\n  simpl.\n  unfold open.\n  rewrite <- A2.\n  change (TSelH (S (length GH))) with (TSelH (0 + (S (length GH)))).\n  rewrite -> splice_open_permute. simpl.\n  assert (\n      stp G1\n     ((map (splicett (length GH)) [(0, (open_rec 0 (TSelH (length GH)) T2))])++(x, v1)::GH)\n     (splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n     (splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n     ->\n     stp G1\n     ((0, splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n      :: (x, v1) :: GH)\n     (splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n     (splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n    ) as HGX1. {\n    simpl. intros A. apply A.\n  }\n  apply HGX1.\n  apply stp_splice.\n  simpl. unfold open in H2. rewrite <- H. apply H2.\n  simpl. apply le_refl.\n  rewrite <- A1. rewrite <- A2.\n  unfold open. simpl.\n  change (TSelH (S (length GH))) with (TSelH (0 + (S (length GH)))).\n  rewrite -> splice_open_permute. rewrite -> splice_open_permute.\n  assert (\n     (stp G1\n     ((map (splicett (length GH)) [(0, (open_rec 0 (TSelH (length GH)) T1))])++(x, v1)::GH)\n     (splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T1))\n     (splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T2)))\n     ->\n     (stp G1\n     ((0, splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T1))\n      :: (x, v1) :: GH)\n     (splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T1))\n     (splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T2)))\n    ) as HGX2. {\n    simpl. intros A. apply A.\n  }\n  apply HGX2.\n  apply stp_splice.\n  simpl. unfold open in H3. rewrite <- H. apply H3.\n  simpl. apply le_refl. simpl. apply le_refl.\nQed.\n\n\nLemma indexr_at_index: forall {A} x0 GH0 GH1 x (v:A),\n  beq_nat x0 (length GH1) = true ->\n  indexr x0 (GH0 ++ (x, v) :: GH1) = Some v.\nProof.\n  intros. apply beq_nat_true in H. subst.\n  induction GH0.\n  - simpl. rewrite <- beq_nat_refl. reflexivity.\n  - destruct a. simpl.\n    rewrite app_length. simpl. rewrite <- plus_n_Sm. rewrite <- plus_Sn_m.\n    rewrite false_beq_nat. assumption. omega.\nQed.\n\nLemma indexr_same: forall {A} x0 (v0:A) GH0 GH1 x (v:A) (v':A),\n  beq_nat x0 (length GH1) = false ->\n  indexr x0 (GH0 ++ (x, v) :: GH1) = Some v0 ->\n  indexr x0 (GH0 ++ (x, v') :: GH1) = Some v0.\nProof.\n  intros ? ? ? ? ? ? ? ? E H.\n  induction GH0.\n  - simpl. rewrite E. simpl in H. rewrite E in H. apply H.\n  - destruct a. simpl.\n    rewrite app_length. simpl.\n    case_eq (beq_nat x0 (length GH0 + S (length GH1))); intros E'.\n    simpl in H. rewrite app_length in H. simpl in H. rewrite E' in H.\n    rewrite H. reflexivity.\n    simpl in H. rewrite app_length in H. simpl in H. rewrite E' in H.\n    rewrite IHGH0. reflexivity. assumption.\nQed.\n\nInductive venv_ext : venv -> venv -> Prop :=\n| venv_ext_refl : forall G, venv_ext G G\n| venv_ext_cons : forall x T G1 G2, fresh G1 <= x -> venv_ext G1 G2 -> venv_ext ((x,T)::G1) G2.\n\nInductive aenv_ext : aenv -> aenv -> Prop :=\n| aenv_ext_nil : aenv_ext nil nil\n| aenv_ext_cons : forall x T G' G A A', aenv_ext A' A -> venv_ext G' G -> aenv_ext ((x,(G',T))::A') ((x,(G,T))::A).\n\nLemma aenv_ext_refl: forall GH, aenv_ext GH GH.\nProof.\n  intros. induction GH.\n  - apply aenv_ext_nil.\n  - destruct a. destruct p. apply aenv_ext_cons.\n    assumption.\n    apply venv_ext_refl.\nQed.\n\nLemma index_extend_mult : forall G G' x T,\n                       index x G = Some T ->\n                       venv_ext G' G ->\n                       index x G' = Some T.\nProof.\n  intros G G' x T H HV.\n  induction HV.\n  - assumption.\n  - apply index_extend. apply IHHV. apply H. assumption.\nQed.\n\nLemma aenv_ext__same_length:\n  forall GH GH',\n    aenv_ext GH' GH ->\n    length GH = length GH'.\nProof.\n  intros. induction H.\n  - simpl. reflexivity.\n  - simpl. rewrite IHaenv_ext. reflexivity.\nQed.\n\nLemma indexr_at_ext :\n  forall GH GH' x T G,\n    aenv_ext GH' GH ->\n    indexr x GH = Some (G, T) ->\n    exists G', indexr x GH' = Some (G', T) /\\ venv_ext G' G.\nProof.\n  intros GH GH' x T G Hext Hindex. induction Hext.\n  - simpl in Hindex. inversion Hindex.\n  - simpl. simpl in Hindex.\n    case_eq (beq_nat x (length A)); intros E.\n    rewrite E in Hindex.  inversion Hindex. subst.\n    rewrite <- (@aenv_ext__same_length A A'). rewrite E.\n    exists G'. split. reflexivity. assumption. assumption.\n    rewrite E in Hindex.\n    rewrite <- (@aenv_ext__same_length A A'). rewrite E.\n    apply IHHext. assumption. assumption.\nQed.\n\n\nLemma stp2_closure_extend_rec :\n  forall G1 G2 T1 T2 GH s m n1,\n    stp2 s m G1 T1 G2 T2 GH n1 ->\n    (forall G1' G2' GH',\n       aenv_ext GH' GH ->\n       venv_ext G1' G1 ->\n       venv_ext G2' G2 ->\n       stp2 s m G1' T1 G2' T2 GH' n1).\nProof.\n  intros G1 G2 T1 T2 GH s m n1 H.\n  induction H; intros; eauto;\n  try solve [inversion IHstp2_1; inversion IHstp2_2; eauto];\n  try solve [inversion IHstp2; eauto].\n  - Case \"strong_sel1\".\n    eapply stp2_strong_sel1. eapply index_extend_mult. apply H.\n    assumption. assumption. (* assumption. *)\n    apply IHstp2. assumption. apply venv_ext_refl. assumption.\n  - Case \"strong_sel2\".\n    eapply stp2_strong_sel2. eapply index_extend_mult. apply H.\n    assumption. assumption. (* assumption. *)\n    apply IHstp2. assumption. assumption. apply venv_ext_refl.\n  - Case \"strong_selx\".\n    eapply stp2_strong_selx.\n    eapply index_extend_mult. apply H. assumption.\n    eapply index_extend_mult. apply H0. assumption.\n  - Case \"sel1\".\n    eapply stp2_sel1. eapply index_extend_mult. apply H.\n    assumption. eassumption. assumption.\n    apply IHstp2_1. assumption. apply venv_ext_refl. assumption.\n    apply IHstp2_2. assumption. assumption. assumption.\n  - Case \"selb1\".\n    eapply stp2_selb1. eapply index_extend_mult. apply H.\n    assumption. eassumption. assumption.\n    apply IHstp2_1. apply aenv_ext_refl. apply venv_ext_refl. assumption.\n    apply IHstp2_2. assumption. assumption. assumption.\n  - Case \"sel2\".\n    eapply stp2_sel2. eapply index_extend_mult. apply H.\n    assumption. eassumption. assumption.\n    apply IHstp2_1. assumption. apply venv_ext_refl. assumption.\n    apply IHstp2_2. assumption. assumption. assumption.\n  - Case \"selx\".\n    eapply stp2_selx.\n    eapply index_extend_mult. apply H. assumption.\n    eapply index_extend_mult. apply H0. assumption.\n  - Case \"sela1\".\n    assert (exists GX', indexr x GH' = Some (GX', TX) /\\ venv_ext GX' GX) as A. {\n      apply indexr_at_ext with (GH:=GH); assumption.\n    }\n    inversion A as [GX' [H' HX]].\n    apply stp2_sela1 with (GX:=GX') (TX:=TX).\n    assumption. assumption.\n    apply IHstp2_1; assumption.\n    apply IHstp2_2; assumption.\n  - Case \"selab1\".\n    assert (exists GX', indexr x GH' = Some (GX', TX) /\\ venv_ext GX' GX) as A. {\n      apply indexr_at_ext with (GH:=GH); assumption.\n    }\n    inversion A as [GX' [H' HX]].\n    eapply stp2_selab1 with (GX:=GX') (TX:=TX).\n    assumption.\n    apply IHstp2_1; eauto. apply aenv_ext_refl.\n    assumption.\n    apply IHstp2_2; eauto.\n  - Case \"sela2\".\n    assert (exists GX', indexr x GH' = Some (GX', TX) /\\ venv_ext GX' GX) as A. {\n      apply indexr_at_ext with (GH:=GH); assumption.\n    }\n    inversion A as [GX' [H' HX]].\n    apply stp2_sela2 with (GX:=GX') (TX:=TX).\n    assumption. assumption.\n    apply IHstp2_1; assumption.\n    apply IHstp2_2; assumption.\n  - Case \"selax\".\n    assert (exists GX', indexr x GH' = Some (GX', TX) /\\ venv_ext GX' GX) as A. {\n      apply indexr_at_ext with (GH:=GH); assumption.\n    }\n    inversion A as [GX' [H' HX]].\n    apply stp2_selax with (GX:=GX') (TX:=TX).\n    assumption.\n  - Case \"all\".\n    assert (length GH = length GH') as A. {\n      apply aenv_ext__same_length. assumption.\n    }\n    apply stp2_all.\n    apply IHstp2_1; assumption.\n    subst. rewrite <- A. assumption.\n    subst. rewrite <- A. assumption.\n    subst. rewrite <- A.\n    apply IHstp2_2. apply aenv_ext_cons. assumption. assumption. assumption. assumption.\n    subst. rewrite <- A.\n    apply IHstp2_3. apply aenv_ext_cons. assumption. assumption. assumption. assumption.\n  - Case \"bind\".\n    assert (length GH = length GH') as A. {\n      apply aenv_ext__same_length. assumption.\n    }\n    apply stp2_bind.\n    subst. rewrite A in H. assumption.\n    subst. rewrite A in H0. assumption.\n    rewrite A in IHstp2_1. apply IHstp2_1. apply aenv_ext_cons. assumption. assumption. assumption. assumption.\n    subst.\n    rewrite A in IHstp2_2. apply IHstp2_2. apply aenv_ext_cons. assumption. assumption. assumption. assumption.\n  - Case \"bindb\".\n    assert (length GH = length GH') as A. {\n      apply aenv_ext__same_length. assumption.\n    }\n    apply stp2_bindb.\n    subst. rewrite A in H. assumption.\n    subst. rewrite A in H0. assumption.\n    rewrite A in IHstp2_1. apply IHstp2_1. apply aenv_ext_cons. assumption. assumption. assumption. assumption.\n    subst.\n    rewrite A in IHstp2_2. apply IHstp2_2. apply aenv_ext_cons. assumption. assumption. assumption. assumption.\n  - Case \"trans\".\n    eapply stp2_transf.\n    eapply IHstp2_1.\n    assumption. assumption. apply venv_ext_refl.\n    eapply IHstp2_2.\n    assumption. apply venv_ext_refl. assumption.\nQed.\n\n\nLemma stp2_closure_extend : forall G1 T1 G2 T2 GH GX T x v s m n1,\n                              stp2 s m G1 T1 G2 T2 ((0,(GX,T))::GH) n1 ->\n                              fresh GX <= x ->\n                              stp2 s m G1 T1 G2 T2 ((0,((x,v)::GX,T))::GH) n1.\nProof.\n  intros. eapply stp2_closure_extend_rec. apply H.\n  apply aenv_ext_cons. apply aenv_ext_refl. apply venv_ext_cons.\n  assumption. apply venv_ext_refl. apply venv_ext_refl. apply venv_ext_refl.\nQed.\n\n\nLemma stp2_extend : forall x v1 G1 G2 T1 T2 H s m n1,\n                      stp2 s m G1 T1 G2 T2 H n1 ->\n                      (fresh G1 <= x ->\n                       stp2 s m ((x,v1)::G1) T1 G2 T2 H n1) /\\\n                      (fresh G2 <= x ->\n                       stp2 s m G1 T1 ((x,v1)::G2) T2 H n1) /\\\n                      (fresh G1 <= x -> fresh G2 <= x ->\n                       stp2 s m ((x,v1)::G1) T1 ((x,v1)::G2) T2 H n1).\nProof.\n  intros. induction H0;\n    try solve [split; try split; repeat ev; intros; eauto using index_extend];\n    try solve [split; try split; intros; inversion IHstp2_1 as [? [? ?]]; inversion IHstp2_2 as [? [? ?]]; inversion IHstp2_3 as [? [? ?]]; constructor; eauto; apply stp2_closure_extend; eauto];\n    try solve [split; try split; intros; inversion IHstp2_1 as [? [? ?]]; inversion IHstp2_2 as [? [? ?]]; eapply stp2_bind; eauto; apply stp2_closure_extend; eauto];\n    try solve [split; try split; intros; inversion IHstp2_1 as [? [? ?]]; inversion IHstp2_2 as [? [? ?]]; eapply stp2_bindb; eauto; apply stp2_closure_extend; eauto].\nQed.\n\nLemma stp2_extend2 : forall x v1 G1 G2 T1 T2 H s m n1,\n                       stp2 s m G1 T1 G2 T2 H n1 ->\n                       fresh G2 <= x ->\n                       stp2 s m G1 T1 ((x,v1)::G2) T2 H n1.\nProof.\n  intros. apply (proj2 (stp2_extend x v1 G1 G2 T1 T2 H s m n1 H0)). assumption.\nQed.\n\nLemma stp2_extend1 : forall x v1 G1 G2 T1 T2 H s m n1,\n                       stp2 s m G1 T1 G2 T2 H n1 ->\n                       fresh G1 <= x ->\n                       stp2 s m ((x,v1)::G1) T1 G2 T2 H n1.\nProof.\n  intros. apply (proj1 (stp2_extend x v1 G1 G2 T1 T2 H s m n1 H0)). assumption.\nQed.\n\nLemma stp2_extendH : forall x v1 G1 G2 T1 T2 GH s m n1,\n                       stp2 s m G1 T1 G2 T2 GH n1 ->\n                       stp2 s m G1 T1 G2 T2 ((x,v1)::GH) n1.\nProof.\n  intros. induction H; eauto using indexr_extend.\n  - Case \"all\".\n  assert (splice (length GH) T2 = T2) as A2. {\n    eapply closed_splice_idem. apply H0. omega.\n  }\n  assert (splice (length GH) T4 = T4) as A4. {\n    eapply closed_splice_idem. apply H1. omega.\n  }\n  assert (TSelH (S (length GH)) = splice (length GH) (TSelH (length GH))) as AH. {\n    simpl. case_eq (le_lt_dec (length GH) (length GH)); intros E LE.\n    simpl. rewrite NPeano.Nat.add_1_r. reflexivity.\n    clear LE. apply lt_irrefl in E. inversion E.\n  }\n  assert (closed 0 (length GH) T1). eapply stp2_closed2. eauto.\n  assert (splice (length GH) T1 = T1) as A1. {\n    eapply closed_splice_idem. eauto. omega.\n  }\n  assert (map (spliceat (length GH)) [(0,(G1, T1))] ++(x,v1)::GH =((0, (G1, T1))::(x,v1)::GH)) as HGX1. {\n    simpl. rewrite A1. eauto.\n  }\n  assert (closed 0 (length GH) T3). eapply stp2_closed1. eauto.\n  assert (splice (length GH) T3 = T3) as A3. {\n    eapply closed_splice_idem. eauto. omega.\n  }\n  assert (map (spliceat (length GH)) [(0,(G2, T3))] ++(x,v1)::GH =((0, (G2, T3))::(x,v1)::GH)) as HGX3. {\n    simpl. rewrite A3. eauto.\n  }\n  eapply stp2_all.\n  apply IHstp2_1.\n  apply closed_inc. apply H0.\n  apply closed_inc. apply H1.\n  simpl.\n  unfold open.\n  rewrite <- A2.\n  unfold open.\n  change (TSelH (S (length GH))) with (TSelH (0 + (S (length GH)))).\n  rewrite -> splice_open_permute.\n  rewrite <- HGX1.\n  apply stp2_splice.\n  simpl. unfold open in H2. apply H2.\n  simpl. omega.\n  rewrite <- A2. rewrite <- A4.\n  unfold open. simpl.\n  change (TSelH (S (length GH))) with (TSelH (0 + (S (length GH)))).\n  rewrite -> splice_open_permute.\n  rewrite -> splice_open_permute.\n  rewrite <- HGX3.\n  apply stp2_splice.\n  simpl. unfold open in H3. apply H3.\n  omega. omega.\n\n  - Case \"bind\".\n  assert (splice (length GH) T2 = T2) as A2. {\n    eapply closed_splice_idem. eauto. omega.\n  }\n  assert (splice (length GH) T1 = T1) as A1. {\n    eapply closed_splice_idem. eauto. omega.\n  }\n  eapply stp2_bind.\n  apply closed_inc. eauto.\n  apply closed_inc. eauto.\n  simpl.\n  unfold open.\n  rewrite <- A2.\n  change (TSelH (S (length GH))) with (TSelH (0 + (S (length GH)))).\n  rewrite -> splice_open_permute. simpl.\n  assert (\n   stp2 1 false G2 (splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n     G2 (splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n     ((map (spliceat (length GH)) [(0, (G2, open_rec 0 (TSelH (length GH)) T2))])++((x, v1)::GH))\n      n2\n   ->\n   stp2 1 false G2 (splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n     G2 (splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n     ((0, (G2, splice (length GH) (open_rec 0 (TSelH (length GH)) T2)))\n      :: (x, v1) :: GH) n2\n    ) as HGX1. {\n    simpl. intros A. apply A.\n  }\n  apply HGX1.\n  apply stp2_splice.\n  simpl. unfold open in H1. apply H1.\n  simpl. apply le_refl.\n  rewrite <- A1. rewrite <- A2.\n  unfold open. simpl.\n  change (TSelH (S (length GH))) with (TSelH (0 + (S (length GH)))).\n  rewrite -> splice_open_permute. rewrite -> splice_open_permute.\n  assert (\n   stp2 1 false G1\n     (splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T1)) G2\n     (splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T2))\n     ((map (spliceat (length GH)) [(0, (G1, (open_rec 0 (TSelH (0 + length GH)) T1)))])++((x, v1) :: GH)) n1\n      ->\n   stp2 1 false G1\n     (splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T1)) G2\n     (splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T2))\n     ((0, (G1, splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T1)))\n        :: (x, v1) :: GH) n1\n   ) as HGX2. {\n    simpl. intros A. apply A.\n  }\n  apply HGX2.\n  apply stp2_splice.\n  simpl. unfold open in H2. apply H2.\n  simpl. apply le_refl. simpl. apply le_refl.\n\n  - Case \"bindb\".\n  assert (splice (length GH) T2 = T2) as A2. {\n    eapply closed_splice_idem. eauto. omega.\n  }\n  assert (splice (length GH) T1 = T1) as A1. {\n    eapply closed_splice_idem. eauto. omega.\n  }\n  eapply stp2_bindb.\n  apply closed_inc. eauto.\n  apply closed_inc. eauto.\n  simpl.\n  unfold open.\n  rewrite <- A2.\n  change (TSelH (S (length GH))) with (TSelH (0 + (S (length GH)))).\n  rewrite -> splice_open_permute. simpl.\n  assert (\n   stp2 (S m) false G2 (splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n     G2 (splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n     ((map (spliceat (length GH)) [(0, (G2, open_rec 0 (TSelH (length GH)) T2))])++((x, v1)::GH))\n      n2\n   ->\n   stp2 (S m) false G2 (splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n     G2 (splice (length GH) (open_rec 0 (TSelH (length GH)) T2))\n     ((0, (G2, splice (length GH) (open_rec 0 (TSelH (length GH)) T2)))\n      :: (x, v1) :: GH) n2\n    ) as HGX1. {\n    simpl. intros A. apply A.\n  }\n  apply HGX1.\n  apply stp2_splice.\n  simpl. unfold open in H1. apply H1.\n  simpl. apply le_refl.\n  rewrite <- A1. rewrite <- A2.\n  unfold open. simpl.\n  change (TSelH (S (length GH))) with (TSelH (0 + (S (length GH)))).\n  rewrite -> splice_open_permute. rewrite -> splice_open_permute.\n  assert (\n   stp2 (S m) false G1\n     (splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T1)) G2\n     (splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T2))\n     ((map (spliceat (length GH)) [(0, (G1, (open_rec 0 (TSelH (0 + length GH)) T1)))])++((x, v1) :: GH)) n1\n      ->\n   stp2 (S m) false G1\n     (splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T1)) G2\n     (splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T2))\n     ((0, (G1, splice (length GH) (open_rec 0 (TSelH (0 + length GH)) T1)))\n        :: (x, v1) :: GH) n1\n   ) as HGX2. {\n    simpl. intros A. apply A.\n  }\n  apply HGX2.\n  apply stp2_splice.\n  simpl. unfold open in H2. apply H2.\n  simpl. apply le_refl. simpl. apply le_refl.\nQed.\n\nLemma stp2_extendH_mult : forall G1 G2 T1 T2 H H2 s m n1,\n                       stp2 s m G1 T1 G2 T2 H n1->\n                       stp2 s m G1 T1 G2 T2 (H2++H) n1.\nProof. intros. induction H2.\n  simpl. eauto. destruct a.\n  simpl. eapply stp2_extendH. eauto.\nQed.\n\nLemma stp2_extendH_mult0 : forall G1 G2 T1 T2 H2 s m n1,\n                       stp2 s m G1 T1 G2 T2 [] n1 ->\n                       stp2 s m G1 T1 G2 T2 H2 n1.\nProof. intros. eapply stp2_extendH_mult with (H2:=H2) in H; eauto. rewrite app_nil_r in H. eauto. Qed.\n\nLemma stp2_reg  : forall G1 G2 T1 T2 GH s m n1,\n                    stp2 s m G1 T1 G2 T2 GH n1 ->\n                    (exists n0, stp2 s true G1 T1 G1 T1 GH n0) /\\\n                    (exists n0, stp2 s true G2 T2 G2 T2 GH n0).\nProof.\n  intros. induction H;\n    try solve [repeat ev; split; eexists; eauto].\n  Grab Existential Variables.\n  apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0.\n  apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0.\n  apply 0. apply 0.\nQed.\n\nLemma stp2_reg2 : forall G1 G2 T1 T2 GH s m n1,\n                       stp2 s m G1 T1 G2 T2 GH n1 ->\n                       (exists n0, stp2 s true G2 T2 G2 T2 GH n0).\nProof.\n  intros. apply (proj2 (stp2_reg G1 G2 T1 T2 GH s m n1 H)).\nQed.\n\nLemma stp2_reg1 : forall G1 G2 T1 T2 GH s m n1,\n                       stp2 s m G1 T1 G2 T2 GH n1 ->\n                       (exists n0, stp2 s true G1 T1 G1 T1 GH n0).\nProof.\n  intros. apply (proj1 (stp2_reg G1 G2 T1 T2 GH s m n1 H)).\nQed.\n\nLemma stp_reg  : forall G GH T1 T2,\n                    stp G GH T1 T2 ->\n                    stp G GH T1 T1 /\\ stp G GH T2 T2.\nProof.\n  intros. induction H;\n    try solve [repeat ev; split; eauto].\nQed.\n\nLemma stpd2_extend2 : forall x v1 G1 G2 T1 T2 H m,\n                       stpd2 m G1 T1 G2 T2 H ->\n                       fresh G2 <= x ->\n                       stpd2 m G1 T1 ((x,v1)::G2) T2 H.\nProof.\n  intros. inversion H0 as [n1 Hsub]. exists n1.\n  apply stp2_extend2; assumption.\nQed.\n\nLemma stpd2_extend1 : forall x v1 G1 G2 T1 T2 H m,\n                       stpd2 m G1 T1 G2 T2 H ->\n                       fresh G1 <= x ->\n                       stpd2 m ((x,v1)::G1) T1 G2 T2 H.\nProof.\n  intros. inversion H0 as [n1 Hsub]. exists n1.\n  apply stp2_extend1; assumption.\nQed.\n\nLemma stpd2_extendH : forall x v1 G1 G2 T1 T2 H m,\n                       stpd2 m G1 T1 G2 T2 H ->\n                       stpd2 m G1 T1 G2 T2 ((x,v1)::H).\nProof.\n  intros. inversion H0 as [n1 Hsub]. exists n1.\n  apply stp2_extendH; assumption.\nQed.\n\nLemma stpd2_extendH_mult : forall G1 G2 T1 T2 H H2 m,\n                       stpd2 m G1 T1 G2 T2 H->\n                       stpd2 m G1 T1 G2 T2 (H2++H).\nProof.\n  intros. inversion H0 as [n1 Hsub]. exists n1.\n  apply stp2_extendH_mult; assumption.\nQed.\n\nLemma stpd2_extendH_mult0 : forall G1 G2 T1 T2 H2 m,\n                       stpd2 m G1 T1 G2 T2 [] ->\n                       stpd2 m G1 T1 G2 T2 H2.\nProof.\n  intros. inversion H as [n1 Hsub]. exists n1.\n  apply stp2_extendH_mult0; assumption.\nQed.\n\n\nLemma stpd2_reg2 : forall G1 G2 T1 T2 H m,\n                       stpd2 m G1 T1 G2 T2 H ->\n                       stpd2 true G2 T2 G2 T2 H.\nProof.\n  intros. inversion H0 as [n1 Hsub].\n  eapply stp2_reg2; eassumption.\nQed.\n\nLemma stpd2_reg1 : forall G1 G2 T1 T2 H m,\n                       stpd2 m G1 T1 G2 T2 H ->\n                       stpd2 true G1 T1 G1 T1 H.\nProof.\n  intros. inversion H0 as [n1 Hsub].\n  eapply stp2_reg1; eassumption.\nQed.\n\n\nLemma stpd2_closed2 : forall G1 G2 T1 T2 H m,\n                       stpd2 m G1 T1 G2 T2 H ->\n                       closed 0 (length H) T2.\nProof.\n  intros. inversion H0 as [n1 Hsub].\n  eapply stp2_closed2; eassumption.\nQed.\n\nLemma stpd2_closed1 : forall G1 G2 T1 T2 H m,\n                       stpd2 m G1 T1 G2 T2 H ->\n                       closed 0 (length H) T1.\nProof.\n  intros. inversion H0 as [n1 Hsub].\n  eapply stp2_closed1; eassumption.\nQed.\n\n\n(* sstpd2 variants below *)\n\nLemma sstpd2_extend2 : forall x v1 G1 G2 T1 T2 H m,\n                       sstpd2 m G1 T1 G2 T2 H ->\n                       fresh G2 <= x ->\n                       sstpd2 m G1 T1 ((x,v1)::G2) T2 H.\nProof.\n  intros. inversion H0 as [n1 Hsub]. exists n1.\n  apply stp2_extend2; assumption.\nQed.\n\nLemma sstpd2_extend1 : forall x v1 G1 G2 T1 T2 H m,\n                       sstpd2 m G1 T1 G2 T2 H ->\n                       fresh G1 <= x ->\n                       sstpd2 m ((x,v1)::G1) T1 G2 T2 H.\nProof.\n  intros. inversion H0 as [n1 Hsub]. exists n1.\n  apply stp2_extend1; assumption.\nQed.\n\nLemma sstpd2_extendH : forall x v1 G1 G2 T1 T2 H m,\n                       sstpd2 m G1 T1 G2 T2 H ->\n                       sstpd2 m G1 T1 G2 T2 ((x,v1)::H).\nProof.\n  intros. inversion H0 as [n1 Hsub]. exists n1.\n  apply stp2_extendH; assumption.\nQed.\n\nLemma sstpd2_extendH_mult : forall G1 G2 T1 T2 H H2 m,\n                       sstpd2 m G1 T1 G2 T2 H->\n                       sstpd2 m G1 T1 G2 T2 (H2++H).\nProof.\n  intros. inversion H0 as [n1 Hsub]. exists n1.\n  apply stp2_extendH_mult; assumption.\nQed.\n\nLemma sstpd2_extendH_mult0 : forall G1 G2 T1 T2 H2 m,\n                       sstpd2 m G1 T1 G2 T2 [] ->\n                       sstpd2 m G1 T1 G2 T2 H2.\nProof.\n  intros. inversion H as [n1 Hsub]. exists n1.\n  apply stp2_extendH_mult0; assumption.\nQed.\n\nLemma sstpd2_reg2 : forall G1 G2 T1 T2 H m,\n                       sstpd2 m G1 T1 G2 T2 H ->\n                       sstpd2 true G2 T2 G2 T2 H.\nProof.\n  intros. inversion H0 as [n1 Hsub].\n  eapply stp2_reg2; eassumption.\nQed.\n\nLemma sstpd2_reg1 : forall G1 G2 T1 T2 H m,\n                       sstpd2 m G1 T1 G2 T2 H ->\n                       sstpd2 true G1 T1 G1 T1 H.\nProof.\n  intros. inversion H0 as [n1 Hsub].\n  eapply stp2_reg1; eassumption.\nQed.\n\nLemma sstpd2_closed2 : forall G1 G2 T1 T2 H m,\n                       sstpd2 m G1 T1 G2 T2 H ->\n                       closed 0 (length H) T2.\nProof.\n  intros. inversion H0 as [n1 Hsub].\n  eapply stp2_closed2; eassumption.\nQed.\n\nLemma sstpd2_closed1 : forall G1 G2 T1 T2 H m,\n                       sstpd2 m G1 T1 G2 T2 H ->\n                       closed 0 (length H) T1.\nProof.\n  intros. inversion H0 as [n1 Hsub].\n  eapply stp2_closed1; eassumption.\nQed.\n\nLemma valtp_extend : forall vs v x v1 T,\n                       val_type vs v T ->\n                       fresh vs <= x ->\n                       val_type ((x,v1)::vs) v T.\nProof.\n  intros. induction H; eauto; econstructor; eauto; eapply sstpd2_extend2; eauto.\nQed.\n\n\nLemma index_safe_ex: forall H1 G1 TF i,\n             wf_env H1 G1 ->\n             index i G1 = Some TF ->\n             exists v, index i H1 = Some v /\\ val_type H1 v TF.\nProof. intros. induction H.\n   - Case \"nil\". inversion H0.\n   - Case \"cons\". inversion H0.\n     case_eq (le_lt_dec (fresh ts) n); intros ? E1.\n     + SCase \"ok\".\n       rewrite E1 in H3.\n       assert ((fresh ts) <= n) as QF. eauto. rewrite <-(wf_fresh vs ts H1) in QF.\n       elim (le_xx (fresh vs) n QF). intros ? EX.\n\n       case_eq (beq_nat i n); intros E2.\n       * SSCase \"hit\".\n         assert (index i ((n, v) :: vs) = Some v). eauto. unfold index. rewrite EX. rewrite E2. eauto.\n         assert (t = TF).\n         unfold index in H0. rewrite E1 in H0. rewrite E2 in H0. inversion H0. eauto.\n         subst t. eauto.\n       * SSCase \"miss\".\n         rewrite E2 in H3.\n         assert (exists v0, index i vs = Some v0 /\\ val_type vs v0 TF) as HI. eapply IHwf_env. eauto.\n         inversion HI as [v0 HI1]. inversion HI1.\n         eexists. econstructor. eapply index_extend; eauto. eapply valtp_extend; eauto.\n     + SSCase \"bad\".\n       rewrite E1 in H3. inversion H3.\nQed.\n\n\nLemma index_safeh_ex: forall H1 H2 G1 GH TF i,\n             wf_env H1 G1 -> wf_envh H1 H2 GH ->\n             indexr i GH = Some TF ->\n             exists v, indexr i H2 = Some v /\\ valh_type H1 H2 v TF.\nProof. intros. induction H0.\n   - Case \"nil\". inversion H3.\n   - Case \"cons\". inversion H3.\n     case_eq (beq_nat i (length ts)); intros E2.\n     * SSCase \"hit\".\n       rewrite E2 in H2. inversion H2. subst. clear H2.\n       assert (length ts = length vs). symmetry. eapply wfh_length. eauto.\n       simpl. rewrite H1 in E2. rewrite E2.\n       eexists. split. eauto. econstructor.\n     * SSCase \"miss\".\n       rewrite E2 in H2.\n       assert (exists v : venv * ty,\n                 indexr i vs = Some v /\\ valh_type vvs vs v TF). eauto.\n       destruct H1. destruct H1.\n       eexists. split. eapply indexr_extend. eauto.\n       inversion H4. subst.\n       eapply v_tya. (* aenv is not constrained -- bit of a cheat?*)\nQed.\n\n\nInductive res_type: venv -> option vl -> ty -> Prop :=\n| not_stuck: forall venv v T,\n      val_type venv v T ->\n      res_type venv (Some v) T.\n\nHint Constructors res_type.\nHint Resolve not_stuck.\n\n\n\nLemma stpd2_trans_aux: forall n, forall G1 G2 G3 T1 T2 T3 H n1,\n  stp2 MAX false G1 T1 G2 T2 H n1 -> n1 < n ->\n  stpd2 false G2 T2 G3 T3 H ->\n  stpd2 false G1 T1 G3 T3 H.\nProof.\n  intros n. induction n; intros; try omega; repeat eu; subst; inversion H0.\n  - Case \"wrapf\". eapply stpd2_transf; eauto.\n  - Case \"transf\". eapply stpd2_transf. eauto. eapply IHn. eauto. omega. eauto.\nQed.\n\nLemma sstpd2_trans_axiom_aux: forall n, forall G1 G2 G3 T1 T2 T3 H n1,\n  stp2 0 false G1 T1 G2 T2 H n1 -> n1 < n ->\n  sstpd2 false G2 T2 G3 T3 H ->\n  sstpd2 false G1 T1 G3 T3 H.\nProof.\n  intros n. induction n; intros; try omega; repeat eu; subst; inversion H0.\n  - Case \"wrapf\". eapply sstpd2_transf. eexists. eauto. eexists. eauto.\n  - Case \"transf\". eapply sstpd2_transf. eexists. eauto. eapply IHn. eauto. omega. eexists. eauto.\nQed.\n\nLemma atpd2_trans_axiom_aux: forall n, forall G1 G2 G3 T1 T2 T3 H n1,\n  stp2 1 false G1 T1 G2 T2 H n1 -> n1 < n ->\n  atpd2 false G2 T2 G3 T3 H ->\n  atpd2 false G1 T1 G3 T3 H.\nProof.\n  intros n. induction n; intros; try omega; repeat eu; subst; inversion H0.\n  - Case \"wrapf\". eapply atpd2_transf. eexists. eauto. eexists. eauto.\n  - Case \"transf\". eapply atpd2_transf. eexists. eauto. eapply IHn. eauto. omega. eexists. eauto.\nQed.\n\nLemma stpd2_trans: forall G1 G2 G3 T1 T2 T3 H,\n  stpd2 false G1 T1 G2 T2 H ->\n  stpd2 false G2 T2 G3 T3 H ->\n  stpd2 false G1 T1 G3 T3 H.\nProof. intros. repeat eu. eapply stpd2_trans_aux; eauto. Qed.\n\nLemma sstpd2_trans_axiom: forall G1 G2 G3 T1 T2 T3 H,\n  sstpd2 false G1 T1 G2 T2 H ->\n  sstpd2 false G2 T2 G3 T3 H ->\n  sstpd2 false G1 T1 G3 T3 H.\nProof. intros. repeat eu.\n       eapply sstpd2_trans_axiom_aux; eauto.\n       eexists. eauto.\nQed.\n\nLemma atpd2_trans_axiom: forall G1 G2 G3 T1 T2 T3 H,\n  atpd2 false G1 T1 G2 T2 H ->\n  atpd2 false G2 T2 G3 T3 H ->\n  atpd2 false G1 T1 G3 T3 H.\nProof.\n  intros. repeat eu. eapply atpd2_trans_axiom_aux; eauto. eexists. eauto.\nQed.\n\nLemma stp2_narrow_aux: forall n, forall m G1 T1 G2 T2 GH n0,\n  stp2 MAX m G1 T1 G2 T2 GH n0 ->\n  n0 <= n ->\n  forall x GH1 GH0 GH' GX1 TX1 GX2 TX2,\n    GH=GH1++[(x,(GX2,TX2))]++GH0 ->\n    GH'=GH1++[(x,(GX1,TX1))]++GH0 ->\n    stpd2 false GX1 TX1 GX2 TX2 [] ->\n    stpd2 m G1 T1 G2 T2 GH'.\nProof.\n  intros n.\n  induction n.\n  - Case \"z\". intros. inversion H0. subst. inversion H; eauto.\n  - Case \"s n\". intros m G1 T1 G2 T2 GH n0 H NE. inversion H; subst;\n      intros x0 GH1 GH0 GH' GX1 TX1 GX2 TX2 EGH EGH' HX; eauto.\n    + SCase \"top\". eapply stpd2_top. eapply IHn; try eassumption. omega.\n    + SCase \"bot\". eapply stpd2_bot. eapply IHn; try eassumption. omega.\n    + SCase \"fun\". eapply stpd2_fun.\n      eapply IHn; try eassumption. omega.\n      eapply IHn; try eassumption. omega.\n    + SCase \"mem\". eapply stpd2_mem.\n      eapply IHn; try eassumption. omega.\n      eapply IHn; try eassumption. omega.\n    + SCase \"sel1\". eapply stpd2_sel1; try eassumption.\n      eapply IHn; try eassumption. omega.\n      eapply IHn; try eassumption. omega.\n    + SCase \"selb1\". eapply stpd2_selb1; try eassumption.\n      eexists; eassumption.\n      eapply IHn; try eassumption. omega.\n    + SCase \"sel2\". eapply stpd2_sel2; try eassumption.\n      eapply IHn; try eassumption. omega.\n      eapply IHn; try eassumption. omega.\n    + SCase \"selx\". eapply stpd2_selx; try eassumption.\n    + SCase \"sela1\".\n      case_eq (beq_nat x (length GH0)); intros E.\n      * assert (indexr x ([(x0, (GX2, TX2))]++GH0) = Some (GX2, TX2)) as A2. {\n          simpl. rewrite E. reflexivity.\n        }\n        assert (indexr x GH = Some (GX2, TX2)) as A2'. {\n          rewrite EGH. eapply indexr_extend_mult. apply A2.\n        }\n        rewrite A2' in H1. inversion H1. subst.\n        inversion HX as [nx HX'].\n        eapply stpd2_sela1.\n        eapply indexr_extend_mult. simpl. rewrite E. reflexivity.\n        apply beq_nat_true in E. rewrite E. eapply stp2_closed1. eapply stp2_extendH_mult0. eassumption.\n        eapply stpd2_trans.\n        eexists. eapply stp2_extendH_mult0. eassumption.\n        eapply IHn; try eassumption. omega.\n        reflexivity. reflexivity.\n        eapply IHn; try eassumption. omega.\n        reflexivity. reflexivity.\n      * assert (indexr x GH' = Some (GX, TX)) as A. {\n          subst.\n          eapply indexr_same. apply E. eassumption.\n        }\n        eapply stpd2_sela1. eapply A. assumption.\n        eapply IHn; try eassumption. omega.\n        eapply IHn; try eassumption. omega.\n    + SCase \"selab1\".\n      case_eq (beq_nat x (length GH0)); intros E.\n      * assert (indexr x ([(x0, (GX2, TX2))]++GH0) = Some (GX2, TX2)) as A2. {\n          simpl. rewrite E. reflexivity.\n        }\n        assert (indexr x GH = Some (GX2, TX2)) as A2'. {\n          rewrite EGH. eapply indexr_extend_mult. apply A2.\n        }\n        assert (Some (GX2,TX2) = Some (GX, TX)) as E2. {\n          rewrite A2' in H1. apply H1.\n        }\n        inversion E2. subst.\n        eapply stpd2_selab1.\n        eapply indexr_extend_mult. simpl. rewrite E. reflexivity.\n        eapply stpd2_trans. eassumption. eexists. eassumption.\n        eapply IHn; try eassumption. omega.\n        reflexivity. reflexivity.\n      * assert (indexr x GH' = Some (GX, TX)) as A. {\n          subst.\n          eapply indexr_same. apply E. eassumption.\n        }\n        eapply stpd2_selab1. eapply A.\n        eexists. eassumption.\n        eapply IHn; try eassumption. omega.\n    + SCase \"sela2\".\n      case_eq (beq_nat x (length GH0)); intros E.\n      * assert (indexr x ([(x0, (GX2, TX2))]++GH0) = Some (GX2, TX2)) as A2. {\n          simpl. rewrite E. reflexivity.\n        }\n        assert (indexr x GH = Some (GX2, TX2)) as A2'. {\n          rewrite EGH. eapply indexr_extend_mult. apply A2.\n        }\n        rewrite A2' in H1. inversion H1. subst.\n        inversion HX as [nx HX'].\n        eapply stpd2_sela2.\n        eapply indexr_extend_mult. simpl. rewrite E. reflexivity.\n        apply beq_nat_true in E. rewrite E. eapply stp2_closed1. eapply stp2_extendH_mult0. eassumption.\n        eapply stpd2_trans.\n        eexists. eapply stp2_extendH_mult0. eassumption.\n        eapply IHn; try eassumption. omega.\n        reflexivity. reflexivity.\n        eapply IHn; try eassumption. omega.\n        reflexivity. reflexivity.\n      * assert (indexr x GH' = Some (GX, TX)) as A. {\n          subst.\n          eapply indexr_same. apply E. eassumption.\n        }\n        eapply stpd2_sela2. eapply A. assumption.\n        eapply IHn; try eassumption. omega.\n        eapply IHn; try eassumption. omega.\n    + SCase \"selax\".\n      case_eq (beq_nat x (length GH0)); intros E.\n      * assert (indexr x ([(x0, (GX2, TX2))]++GH0) = Some (GX2, TX2)) as A2. {\n          simpl. rewrite E. reflexivity.\n        }\n        assert (indexr x GH = Some (GX2, TX2)) as A2'. {\n          rewrite EGH. eapply indexr_extend_mult. apply A2.\n        }\n        rewrite A2' in H1. inversion H1. subst.\n        inversion HX as [nx HX'].\n        eapply stpd2_selax.\n        eapply indexr_extend_mult. simpl. rewrite E. reflexivity.\n      * assert (indexr x GH' = Some (GX, TX)) as A. {\n          subst.\n          eapply indexr_same. apply E. eassumption.\n        }\n        eapply stpd2_selax. eapply A.\n    + SCase \"all\".\n      assert (length GH = length GH') as A. {\n        subst. clear.\n        induction GH1.\n        - simpl. reflexivity.\n        - simpl. simpl in IHGH1. rewrite IHGH1. reflexivity.\n      }\n      eapply stpd2_all.\n      eapply IHn; try eassumption. omega.\n      rewrite <- A. assumption. rewrite <- A. assumption.\n      rewrite <- A. subst.\n      eapply IHn with (GH1:=(0, (G1, T0)) :: GH1); try eassumption. omega.\n      simpl. reflexivity. simpl. reflexivity.\n      rewrite <- A. subst.\n      eapply IHn with (GH1:=(0, (G2, T4)) :: GH1); try eassumption. omega.\n      simpl. reflexivity. simpl. reflexivity.\n    + SCase \"bind\".\n      assert (length GH = length GH') as A. {\n        subst. clear.\n        induction GH1.\n        - simpl. reflexivity.\n        - simpl. simpl in IHGH1. rewrite IHGH1. reflexivity.\n      }\n      eapply stpd2_bind.\n      assert (closed 1 (length GH) T0 -> closed 1 (length GH') T0) as C0. {\n        rewrite A. intros P. apply P.\n      }\n      apply C0; assumption.\n      assert (closed 1 (length GH) T3 -> closed 1 (length GH') T3) as C3. {\n        rewrite A. intros P. apply P.\n      }\n      apply C3; assumption.\n      assert (\n          stpd2 false G2 (open (TSelH (length GH)) T3) G2\n                (open (TSelH (length GH)) T3)\n                ((0, (G2, open (TSelH (length GH)) T3)) :: GH')\n                ->\n          stpd2 false G2 (open (TSelH (length GH')) T3) G2\n                (open (TSelH (length GH')) T3)\n                ((0, (G2, open (TSelH (length GH')) T3)) :: GH')) as CS1. {\n        rewrite A. intros P. apply P.\n      }\n      apply CS1. eapply IHn. eassumption. omega.\n      instantiate (5:=(0, (G2, open (TSelH (length GH)) T3)) :: GH1).\n      subst. simpl. reflexivity. subst. simpl. reflexivity.\n      assumption.\n      assert (\n          stpd2 false G1 (open (TSelH (length GH)) T0) G2\n                (open (TSelH (length GH)) T3)\n                ((0, (G1, open (TSelH (length GH)) T0)) :: GH')\n                ->\n          stpd2 false G1 (open (TSelH (length GH')) T0) G2\n                (open (TSelH (length GH')) T3)\n                ((0, (G1, open (TSelH (length GH')) T0)) :: GH')\n        ) as CS2. {\n        rewrite A. intros P. apply P.\n      }\n      apply CS2. eapply IHn. eassumption. omega.\n      instantiate (5:=(0, (G1, open (TSelH (length GH)) T0)) :: GH1).\n      subst. simpl. reflexivity. subst. simpl. reflexivity.\n      assumption.\n    + SCase \"wrapf\".\n      eapply stpd2_wrapf.\n      eapply IHn; try eassumption. omega.\n    + SCase \"transf\".\n      eapply stpd2_transf.\n      eapply IHn; try eassumption. omega.\n      eapply IHn; try eassumption. omega.\nGrab Existential Variables.\napply 0. apply 0. apply 0.\nQed.\n\nLemma stpd2_narrow: forall x G1 G2 G3 G4 T1 T2 T3 T4,\n  stpd2 false G1 T1 G2 T2 [] -> (* careful about H! *)\n  stpd2 false G3 T3 G4 T4 ((x,(G2,T2))::[]) ->\n  stpd2 false G3 T3 G4 T4 ((x,(G1,T1))::[]).\nProof.\n  intros. inversion H0 as [n H'].\n  eapply (stp2_narrow_aux n) with (GH1:=[]) (GH0:=[]). eapply H'. omega.\n  simpl. reflexivity. reflexivity.\n  assumption.\nQed.\n\n\n\nLemma atpd2_narrow: forall x G1 G2 G3 G4 T1 T2 T3 T4 H,\n  atpd2 false G1 T1 G2 T2 ((x,(G1,T1))::H) -> (* careful about H! *)\n  atpd2 false G3 T3 G4 T4 ((x,(G2,T2))::H) ->\n  atpd2 false G3 T3 G4 T4 ((x,(G1,T1))::H).\nProof. admit. Qed.\n\n\nLemma sstpd2_trans_aux: forall n, forall m G1 G2 G3 T1 T2 T3 n1,\n  stp2 0 m G1 T1 G2 T2 nil n1 -> n1 < n ->\n  sstpd2 true G2 T2 G3 T3 nil ->\n  sstpd2 true G1 T1 G3 T3 nil.\nProof.\n  intros n. induction n; intros; try omega. eu.\n  inversion H.\n  - Case \"topx\". subst. inversion H1.\n    + SCase \"topx\". eexists. eauto.\n    + SCase \"top\". eexists. eauto.\n    + SCase \"sel2\". eexists. eapply stp2_strong_sel2; eauto.\n  - Case \"botx\". subst. inversion H1.\n    + SCase \"botx\". eexists. eauto.\n    + SCase \"top\". eexists. eauto.\n    + SCase \"?\". eexists. eauto.\n    + SCase \"sel2\". eexists. eapply stp2_strong_sel2; eauto.\n  - Case \"top\". subst. inversion H1.\n    + SCase \"topx\". eexists. eauto.\n    + SCase \"top\". eexists. eauto.\n    + SCase \"sel2\". eexists. eapply stp2_strong_sel2; eauto.\n  - Case \"bot\". subst.\n    apply stp2_reg2 in H1. inversion H1 as [n1' H1'].\n    exists (S n1'). apply stp2_bot. apply H1'.\n  - Case \"bool\". subst. inversion H1.\n    + SCase \"top\". eexists. eauto.\n    + SCase \"bool\". eexists. eauto.\n    + SCase \"sel2\". eexists. eapply stp2_strong_sel2; eauto.\n  - Case \"fun\". subst. inversion H1.\n    + SCase \"top\".\n      assert (stpd2 false G1 T0 G1 T0 []) as A0 by solve [eapply stpd2_wrapf; eapply stp2_reg2; eassumption].\n      inversion A0 as [na0 HA0].\n      assert (stpd2 false G1 T4 G1 T4 []) as A4 by solve [eapply stpd2_wrapf; eapply stp2_reg1; eassumption].\n      inversion A4 as [na4 HA4].\n      eexists. eapply stp2_top. subst. eapply stp2_fun.\n      eassumption. eassumption.\n    + SCase \"fun\". subst.\n      assert (stpd2 false G3 T7 G1 T0 []) as A by solve [eapply stpd2_trans; eauto].\n      inversion A as [na A'].\n      assert (stpd2 false G1 T4 G3 T8 []) as B by solve [eapply stpd2_trans; eauto].\n      inversion B as [nb B'].\n      eexists. eapply stp2_fun. apply A'. apply B'.\n    + SCase \"sel2\". eexists. eapply stp2_strong_sel2. eauto. eauto. eauto.\n  - Case \"mem\". subst. inversion H1.\n    + SCase \"top\".\n      apply stp2_reg1 in H. inversion H. eexists. eapply stp2_top. eassumption.\n    + SCase \"mem\". subst.\n      assert (sstpd2 false G3 T7 G1 T0 []) as A. {\n        eapply sstpd2_trans_axiom; eexists; eauto.\n      }\n      inversion A as [na A'].\n      assert (sstpd2 true G1 T4 G3 T8 []) as B. {\n        eapply IHn. eassumption. omega. eexists. eassumption.\n      }\n      inversion B as [nb B'].\n      eexists. eapply stp2_mem. apply A'. apply B'.\n    + SCase \"sel2\". eexists. eapply stp2_strong_sel2; eauto.\n  - Case \"ssel1\".\n    assert (sstpd2 true GX TX G3 T3 []). eapply IHn. eauto. omega. eexists. eapply H1.\n    eu. eexists. eapply stp2_strong_sel1; eauto.\n  - Case \"ssel2\". subst. inversion H1.\n    + SCase \"top\". subst.\n      apply stp2_reg1 in H4. inversion H4.\n      eexists. eapply stp2_top. eassumption.\n    + SCase \"ssel1\".  (* interesting one *)\n      subst. rewrite H6 in H2. inversion H2. subst.\n      eapply IHn. eapply H4. omega. eexists. eauto.\n    + SCase \"ssel2\".\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"sselx\".\n      subst. rewrite H2 in H6. inversion H6. subst.\n      eexists. eapply stp2_strong_sel2; eauto.\n  - Case \"sselx\". subst. inversion H1.\n    + SCase \"top\". subst.\n      apply stp2_reg1 in H. inversion H.\n      eexists. eapply stp2_top. eassumption.\n    + SCase \"ssel1\".\n      subst. rewrite H5 in H3. inversion H3. subst.\n      eexists. eapply stp2_strong_sel1; eauto.\n    + SCase \"ssel2\". eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"sselx\".\n      subst. rewrite H5 in H3. inversion H3. subst.\n      eexists. eapply stp2_strong_selx. eauto. eauto.\n  - Case \"all\". subst. inversion H1.\n    + SCase \"top\".\n      apply stp2_reg1 in H. inversion H.\n      eexists. eapply stp2_top. eassumption.\n    + SCase \"ssel2\".\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"all\".\n      subst.\n      assert (stpd2 false G3 T7 G1 T0 []). eapply stpd2_trans. eauto. eauto.\n      assert (stpd2 false G1 (open (TSelH (length ([]:aenv))) T4)\n                          G3 (open (TSelH (length ([]:aenv))) T8)\n                          [(0, (G3, T7))]).\n        eapply stpd2_trans. eapply stpd2_narrow. eexists. eapply H9. eauto. eauto.\n      repeat eu. eexists. eapply stp2_all. eauto. eauto. eauto. eauto. eapply H8.\n  - Case \"bind\". subst. inversion H1; subst.\n    + SCase \"top\".\n      apply stp2_reg1 in H. inversion H.\n      eexists. eapply stp2_top. eassumption.\n    + SCase \"ssel2\".\n      eexists. eapply stp2_strong_sel2; eauto.\n    + SCase \"bind\".\n      subst.\n      assert (atpd2 false G1 (open (TSelH 0) T0) G3 (open (TSelH 0) T2)\n                    [(0, (G1, open (TSelH 0) T0))]) as A. {\n        simpl in H5. simpl in H10.\n        eapply atpd2_trans_axiom.\n        eexists; eauto.\n        change ([(0, (G1, open (TSelH 0) T0))]) with ((0, (G1, open (TSelH 0) T0))::[]).\n        eapply atpd2_narrow. eexists. eassumption. eexists. eassumption.\n      }\n      inversion A.\n      eexists. eapply stp2_bind; try eassumption.\n  - Case \"wrapf\". subst. eapply IHn. eapply H2. omega. eexists. eauto.\n  - Case \"transf\". subst. eapply IHn. eapply H2. omega. eapply IHn. eapply H3. omega. eexists. eauto.\n\nGrab Existential Variables.\napply 0. apply 0. apply 0. apply 0. apply 0. apply 0. apply 0.\nQed.\n\nLemma sstpd2_trans: forall G1 G2 G3 T1 T2 T3,\n  sstpd2 true G1 T1 G2 T2 nil ->\n  sstpd2 true G2 T2 G3 T3 nil ->\n  sstpd2 true G1 T1 G3 T3 nil.\nProof. intros. repeat eu. eapply sstpd2_trans_aux; eauto. eexists. eauto. Qed.\n\n\nLemma sstpd2_untrans_aux: forall n, forall G1 G2 T1 T2 n1,\n  stp2 0 false G1 T1 G2 T2 nil n1 -> n1 < n ->\n  sstpd2 true G1 T1 G2 T2 nil.\nProof.\n  intros n. induction n; intros; try omega.\n  inversion H; subst.\n  - Case \"wrapf\". eexists. eauto.\n  - Case \"transf\". eapply sstpd2_trans_aux. eapply H1. eauto. eapply IHn. eauto. omega.\nQed.\n\nLemma sstpd2_untrans: forall G1 G2 T1 T2,\n  sstpd2 false G1 T1 G2 T2 nil ->\n  sstpd2 true G1 T1 G2 T2 nil.\nProof. intros. repeat eu. eapply sstpd2_untrans_aux; eauto. Qed.\n\n\n\nLemma valtp_widen: forall vf H1 H2 T1 T2,\n  val_type H1 vf T1 ->\n  sstpd2 true H1 T1 H2 T2 [] ->\n  val_type H2 vf T2.\nProof.\n  intros. inversion H; econstructor; eauto; eapply sstpd2_trans; eauto.\nQed.\n\nLemma restp_widen: forall vf H1 H2 T1 T2,\n  res_type H1 vf T1 ->\n  sstpd2 true H1 T1 H2 T2 [] ->\n  res_type H2 vf T2.\nProof.\n  intros. inversion H. eapply not_stuck. eapply valtp_widen; eauto.\nQed.\n\nLemma invert_typ: forall venv vx T1 T2,\n  val_type venv vx (TMem T1 T2) ->\n  exists GX TX,\n    vx = (vty GX TX) /\\\n    sstpd2 false venv T1 GX TX [] /\\\n    sstpd2 true GX TX venv T2 [].\nProof.\n  intros. inversion H; ev; try solve by inversion. inversion H1.\n  subst.\n  assert (sstpd2 false venv0 T1 venv1 T0 []) as E1. {\n    eexists. eassumption.\n  }\n  assert (sstpd2 true venv1 T0 venv0 T2 []) as E2. {\n    eexists. eassumption.\n  }\n  repeat eu. repeat eexists; eauto.\nQed.\n\n\n\nLemma stpd2_to_sstpd2_aux1: forall n, forall G1 G2 T1 T2 m n1,\n  stp2 1 m G1 T1 G2 T2 nil n1 -> n1 < n ->\n  sstpd2 m G1 T1 G2 T2 nil.\nProof.\n  intros n. induction n; intros; try omega.\n  inversion H.\n  - Case \"topx\". eexists. eauto.\n  - Case \"botx\". eexists. eauto.\n  - Case \"top\". subst.\n    eapply IHn in H1. inversion H1. eexists. eauto. omega.\n  - Case \"bot\". subst.\n    eapply IHn in H1. inversion H1. eexists. eauto. omega.\n  - Case \"bool\". eexists. eauto.\n  - Case \"fun\". eexists. eapply stp2_fun. eauto. eauto.\n  - Case \"mem\".\n    eapply IHn in H2. eapply sstpd2_untrans in H2. eu.\n    eapply IHn in H3. eapply sstpd2_untrans in H3. eu.\n    eexists. eapply stp2_mem. eauto. eauto. omega. omega.\n  - Case \"sel1\".\n    eapply IHn in H5. eapply sstpd2_untrans in H5. eapply valtp_widen with (2:=H5) in H3.\n    eapply invert_typ in H3. ev. repeat eu. subst.\n    assert (closed 0 (length ([]:aenv)) x1). eapply stp2_closed2; eauto.\n    eexists. eapply stp2_strong_sel1. eauto. eauto. eauto. omega.\n  - Case \"sel2\".\n    eapply IHn in H5. eapply sstpd2_untrans in H5. eapply valtp_widen with (2:=H5) in H3.\n    eapply invert_typ in H3. ev. repeat eu. subst.\n    assert (closed 0 (length ([]:aenv)) x1). eapply stp2_closed2; eauto.\n    eexists. eapply stp2_strong_sel2. eauto. eauto. eauto. omega.\n  - Case \"selx\".\n    eexists. eapply stp2_strong_selx. eauto. eauto.\n  - Case \"sela1\". inversion H2.\n  - Case \"selab1\". inversion H2.\n  - Case \"sela2\". inversion H2.\n  - Case \"selax\". inversion H2.\n  - Case \"all\". eexists. eapply stp2_all. eauto. eauto. eauto. eauto. eauto.\n  - Case \"bind\". eexists. eapply stp2_bind. eauto. eauto. eauto. eauto.\n  - Case \"wrapf\". eapply IHn in H1. eu. eexists. eapply stp2_wrapf. eauto. omega.\n  - Case \"transf\". eapply IHn in H1. eapply IHn in H2. eu. eu. eexists.\n    eapply stp2_transf. eauto. eauto. omega. omega.\n    Grab Existential Variables.\n    apply 0. apply 0. apply 0. apply 0.\nQed.\n\nLemma stpd2_to_sstpd2_aux2: forall n, forall G1 G2 GH T1 T2 m n1,\n  stp2 2 m G1 T1 G2 T2 GH n1 -> n1 < n ->\n  exists n2, stp2 1 m G1 T1 G2 T2 GH n2.\nProof.\n  intros n. induction n; intros; try omega.\n  inversion H.\n  - Case \"topx\". eexists. eauto.\n  - Case \"botx\". eexists. eauto.\n  - Case \"top\". subst.\n    eapply IHn in H1. inversion H1. eexists. eauto. omega.\n  - Case \"bot\". subst.\n    eapply IHn in H1. inversion H1. eexists. eauto. omega.\n  - Case \"bool\". eexists. eauto.\n  - Case \"fun\". eexists. eapply stp2_fun. eauto. eauto.\n  - Case \"mem\".\n    eapply IHn in H2. ev. eapply IHn in H3. ev.\n    eexists. eapply stp2_mem2; eauto. omega. omega.\n  - Case \"sel1\". subst.\n    eapply IHn in H5. eapply IHn in H6. ev. ev.\n    eexists. eapply stp2_sel1; eauto. omega. omega.\n  - Case \"selb1\". subst.\n    eapply IHn in H5. eapply IHn in H6. ev. ev. eapply stpd2_to_sstpd2_aux1 in H5. eapply sstpd2_untrans in H5. eapply valtp_widen with (2:=H5) in H3.\n    (* now invert base on TBind knowledge -- TODO: helper lemma*)\n    inversion H3; ev. subst.\n    inversion H7. subst.\n    inversion H6. subst.\n    inversion H10.\n    inversion H9. (* 1 case left *)\n    subst. inversion H9. subst.\n    assert (stp2 1 false venv0 (open (TSel x2) T2)\n                 G2 (open (TSel x) (TMem TBot T0)) [] n1) as ST.\n    admit. (* get this from substitute *)\n\n    (* NOTE: this crucially depends on the result of inverting stp_bind having\n       level 1, so we don't need to do induction on it.\n\n       Right now, this is quite a limitation: we cannot use level 2 derivations inside binds.\n\n       - We cannot lower levels in hypothetical contexts, because we need to untrans above.\n\n         So we cannot change the bind's body elsewhere, before inverting here.\n\n         (UPDATE: actually that's what we're doing now. We get away with it\n         because GH = [], which means that we may not be able to  unfold nontrivial\n         binds for selections on hypothetical vars)\n\n       - Doing induction on ST here would be difficult, because the size is wrong.\n\n         We're inverting from valtp, which does not count towards our own size.\n         It may seem that it should. But then it needs to be inserted by stp_substitute,\n         ergo stp_substitute will no longer keep things at const size, and will\n         return larger terms.\n\n         That makes it seem unlikely that we'd be able to use IHn on the result.\n\n         We know the size of what we're putting into ST. But we have the same problem\n         as previously in narrowing: we do not know how many times the added term\n         is used, so we cannot bound the result size.\n    *)\n    assert (closed 0 (length (nil:aenv)) (open (TSel x2) T2)) as C. eapply stp2_closed1. eauto. simpl in C.\n    eexists. eapply stp2_sel1. eauto. eapply H7. eauto.\n    eapply stp2_extendH_mult0. eauto. eauto. eauto. omega. omega.\n  - Case \"sel2\". subst.\n    eapply IHn in H5. eapply IHn in H6. ev. ev.\n    eexists. eapply stp2_sel2; eauto. omega. omega.\n  - Case \"selx\". subst.\n    eexists. eapply stp2_selx. eauto. eauto.\n  - Case \"sela1\". subst. eapply IHn in H4. eapply IHn in H5. ev. ev.\n    eexists. eapply stp2_sela1; eauto. omega. omega.\n  - Case \"selab1\".\n    (* THIS ONE WILL NOT WORK AT LEVEL 2 (no way to remove *)\n    (* so we use it at level 1, and translate during subst *)\n    (* restriction GH = [] ensures that level 2 terms are already removed *)\n    eapply IHn in H3. eapply IHn in H5. ev. ev.\n    eexists. eapply stp2_selab1; eauto. omega. omega.\n  - Case \"sela2\". eapply IHn in H4. eapply IHn in H5. ev. ev.\n    eexists. eapply stp2_sela2; eauto. omega. omega.\n  - Case \"selhx\". eexists. eapply stp2_selax. eauto.\n  - Case \"all\". eexists. eapply stp2_all. eauto. eauto. eauto. eapply H4. eapply H5.\n  - Case \"bind\".\n    eapply IHn in H4. eapply IHn in H5. ev. ev.\n    eexists. eapply stp2_bindb. eauto. eauto. eauto. eauto. omega. omega.\n  - Case \"wrapf\". eapply IHn in H1. ev. eexists. eapply stp2_wrapf. eauto. omega.\n  - Case \"transf\". eapply IHn in H1. eapply IHn in H2. ev. ev. eexists.\n    eapply stp2_transf. eauto. eauto. omega. omega.\n    Grab Existential Variables.\n    apply 0. apply 0. apply 0. apply 0. apply 0.\nQed.\n\n\n\nLemma stpd2_to_sstpd2: forall G1 G2 T1 T2 m,\n  stpd2 m G1 T1 G2 T2 nil ->\n  sstpd2 m G1 T1 G2 T2 nil.\nProof.\n  intros. eu.\n  eapply stpd2_to_sstpd2_aux2 in H. ev.\n  eapply stpd2_to_sstpd2_aux1; eauto. eauto.\nQed.\n\n\nLemma stpd2_upgrade: forall G1 G2 T1 T2,\n  stpd2 false G1 T1 G2 T2 nil ->\n  sstpd2 true G1 T1 G2 T2 nil.\nProof.\n  intros.\n  eapply sstpd2_untrans. eapply stpd2_to_sstpd2. eauto.\nQed.\n\n(* not essential *)\nLemma sstpd2_downgrade: forall G1 G2 T1 T2 H,\n  sstpd2 true G1 T1 G2 T2 H ->\n  stpd2 false G1 T1 G2 T2 H.\nProof.\n  admit.\nQed.\n\nLemma index_miss {X}: forall x x1 (B:X) A G,\n  index x ((x1,B)::G) = A ->\n  fresh G <= x1 ->\n  x <> x1 ->\n  index x G = A.\nProof.\n  intros.\n  unfold index in H.\n  elim (le_xx (fresh G) x1 H0). intros.\n  rewrite H2 in H.\n  assert (beq_nat x x1 = false). eapply beq_nat_false_iff. eauto.\n  rewrite H3 in H. eapply H.\nQed.\n\nLemma index_hit {X}: forall x x1 (B:X) A G,\n  index x ((x1,B)::G) = Some A ->\n  fresh G <= x1 ->\n  x = x1 ->\n  B = A.\nProof.\n  intros.\n  unfold index in H.\n  elim (le_xx (fresh G) x1 H0). intros.\n  rewrite H2 in H.\n  assert (beq_nat x x1 = true). eapply beq_nat_true_iff. eauto.\n  rewrite H3 in H. inversion H. eauto.\nQed.\n\nLemma index_hit2 {X}: forall x x1 (B:X) A G,\n  fresh G <= x1 ->\n  x = x1 ->\n  B = A ->\n  index x ((x1,B)::G) = Some A.\nProof.\n  intros.\n  unfold index.\n  elim (le_xx (fresh G) x1 H). intros.\n  rewrite H2.\n  assert (beq_nat x x1 = true). eapply beq_nat_true_iff. eauto.\n  rewrite H3. rewrite H1. eauto.\nQed.\n\n\nLemma indexr_miss {X}: forall x x1 (B:X) A G,\n  indexr x ((x1,B)::G) = A ->\n  x <> (length G)  ->\n  indexr x G = A.\nProof.\n  intros.\n  unfold indexr in H.\n  assert (beq_nat x (length G) = false). eapply beq_nat_false_iff. eauto.\n  rewrite H1 in H. eauto.\nQed.\n\nLemma indexr_hit {X}: forall x x1 (B:X) A G,\n  indexr x ((x1,B)::G) = Some A ->\n  x = length G ->\n  B = A.\nProof.\n  intros.\n  unfold indexr in H.\n  assert (beq_nat x (length G) = true). eapply beq_nat_true_iff. eauto.\n  rewrite H1 in H. inversion H. eauto.\nQed.\n\n\nLemma indexr_hit0: forall GH (GX0:venv) (TX0:ty),\n      indexr 0 (GH ++ [(0,(GX0, TX0))]) =\n      Some (GX0, TX0).\nProof.\n  intros GH. induction GH.\n  - intros. simpl. eauto.\n  - intros. simpl. destruct a. simpl. rewrite app_length. simpl.\n    assert (length GH + 1 = S (length GH)). omega. rewrite H.\n    eauto.\nQed.\n\n\n\n\n\nHint Resolve beq_nat_true_iff.\nHint Resolve beq_nat_false_iff.\n\n\nLemma closed_no_open: forall T x l j,\n  closed_rec j l T ->\n  T = open_rec j x T.\nProof.\n  intros. induction H; intros; eauto;\n  try solve [compute; compute in IHclosed_rec; rewrite <-IHclosed_rec; auto];\n  try solve [compute; compute in IHclosed_rec1; compute in IHclosed_rec2; rewrite <-IHclosed_rec1; rewrite <-IHclosed_rec2; auto].\n\n  Case \"TSelB\".\n    unfold open_rec. assert (k <> i). omega.\n    apply beq_nat_false_iff in H0.\n    rewrite H0. auto.\nQed.\n\n\nLemma open_subst_commute: forall T2 TX (n:nat) x j,\nclosed j n TX ->\n(open_rec j (TSelH x) (subst TX T2)) =\n(subst TX (open_rec j (TSelH (x+1)) T2)).\nProof.\n  intros T2 TX n. induction T2; intros; eauto.\n  -  simpl. rewrite IHT2_1. rewrite IHT2_2. eauto. eauto. eauto.\n  -  simpl. rewrite IHT2_1. rewrite IHT2_2. eauto. eauto. eauto.\n  -  simpl. case_eq (beq_nat i 0); intros E. symmetry. eapply closed_no_open. eauto. simpl. eauto.\n  - simpl. case_eq (beq_nat j i); intros E. simpl.\n    assert (x+1<>0). omega. eapply beq_nat_false_iff in H0.\n    assert (x=x+1-1). unfold id. omega.\n    rewrite H0. eauto.\n    simpl. eauto.\n  -  simpl. rewrite IHT2_1. rewrite IHT2_2. eauto. eapply closed_upgrade. eauto. eauto. eauto.\n  -  simpl. rewrite IHT2. eauto. eapply closed_upgrade. eauto. eauto.\nQed.\n\n\n\n\nLemma closed_no_subst: forall T j TX,\n   closed_rec j 0 T ->\n   subst TX T = T.\nProof.\n  intros T. induction T; intros; inversion H; simpl; eauto;\n    try rewrite (IHT (S j) TX); eauto;\n    try rewrite (IHT2 (S j) TX); eauto;\n    try rewrite (IHT j TX); eauto;\n    try rewrite (IHT1 j TX); eauto;\n    try rewrite (IHT2 j TX); eauto.\n\n  eapply closed_upgrade. eauto. eauto.\n  eapply closed_upgrade. eauto. eauto.\n  subst. omega.\nQed.\n\nLemma closed_subst: forall j n TX T, closed j (n+1) T -> closed 0 n TX -> closed j (n) (subst TX T).\nProof.\n  intros. generalize dependent j. induction T; intros; inversion H; unfold closed; try econstructor; try eapply IHT1; eauto; try eapply IHT2; eauto; try eapply IHT; eauto.\n\n  - Case \"TSelH\". simpl.\n    case_eq (beq_nat i 0); intros E. eapply closed_upgrade. eapply closed_upgrade_free. eauto. omega. eauto. omega.\n    econstructor. assert (i > 0). eapply beq_nat_false_iff in E. omega. omega.\nQed.\n\n\nLemma subst_open_commute_m: forall j n m TX T2, closed (j+1) (n+1) T2 -> closed 0 m TX ->\n    subst TX (open_rec j (TSelH (n+1)) T2) = open_rec j (TSelH n) (subst TX T2).\nProof.\n  intros. generalize dependent j. generalize dependent n.\n  induction T2; intros; inversion H; simpl; eauto;\n          try rewrite IHT2_1; try rewrite IHT2_2; try rewrite IHT2; eauto.\n\n  - Case \"TSelH\". simpl. case_eq (beq_nat i 0); intros E.\n    eapply closed_no_open. eapply closed_upgrade. eauto. omega.\n    eauto.\n  - Case \"TSelB\". simpl. case_eq (beq_nat j i); intros E.\n    simpl. case_eq (beq_nat (n+1) 0); intros E2. eapply beq_nat_true_iff in E2. omega.\n    assert (n+1-1 = n). omega. eauto.\n    eauto.\nQed.\n\nLemma subst_open_commute: forall j n TX T2, closed (j+1) (n+1) T2 -> closed 0 0 TX ->\n    subst TX (open_rec j (TSelH (n+1)) T2) = open_rec j (TSelH n) (subst TX T2).\nProof.\n  intros. eapply subst_open_commute_m; eauto.\nQed.\n\nLemma subst_open_zero: forall j k TX T2, closed k 0 T2 ->\n    subst TX (open_rec j (TSelH 0) T2) = open_rec j TX T2.\nProof.\n  intros. generalize dependent k. generalize dependent j. induction T2; intros; inversion H; simpl; eauto; try rewrite (IHT2_1 _ k); try rewrite (IHT2_2 _ (S k)); try rewrite (IHT2_2 _ (S k)); try rewrite (IHT2 _ (S k)); try rewrite (IHT2 _ k); eauto.\n\n  eapply closed_upgrade; eauto.\n  eapply closed_upgrade; eauto.\n\n  case_eq (beq_nat i 0); intros E. omega. omega.\n\n  case_eq (beq_nat j i); intros E. eauto. eauto.\nQed.\n\n\n\nLemma Forall2_length: forall A B f (G1:list A) (G2:list B),\n                        Forall2 f G1 G2 -> length G1 = length G2.\nProof.\n  intros. induction H.\n  eauto.\n  simpl. eauto.\nQed.\n\n\nLemma nosubst_intro: forall j T, closed j 0 T -> nosubst T.\nProof.\n  intros. generalize dependent j. induction T; intros; inversion H; simpl; eauto.\n  omega.\nQed.\n\nLemma nosubst_open: forall j TX T2, nosubst TX -> nosubst T2 -> nosubst (open_rec j TX T2).\nProof.\n  intros. generalize dependent j. induction T2; intros; try inversion H0; simpl; eauto.\n\n  case_eq (beq_nat j i); intros E. eauto. eauto.\nQed.\n\nLemma nosubst_open_rev: forall j TX T2, nosubst (open_rec j TX T2) -> nosubst TX -> nosubst T2.\nProof.\n  intros. generalize dependent j. induction T2; intros; try inversion H; simpl in H; simpl; eauto.\nQed.\n\nLemma nosubst_zero_closed: forall j T2, nosubst (open_rec j (TSelH 0) T2) -> closed_rec (j+1) 0 T2 -> closed_rec j 0 T2.\nProof.\n  intros. generalize dependent j. induction T2; intros; simpl in H; try destruct H; inversion H0; eauto.\n\n  omega.\n  econstructor.\n\n  case_eq (beq_nat j i); intros E. rewrite E in H. destruct H. eauto.\n  eapply beq_nat_false_iff in E. omega.\nQed.\n\n\n\n\n(* substitution for one-env stp. not necessary, but good sanity check *)\n\nDefinition substt (UX: ty) (V: (id*ty)) :=\n  match V with\n    | (x,T) => (x-1,(subst UX T))\n  end.\n\nLemma indexr_subst: forall GH0 x TX TX',\n   indexr x (GH0 ++ [(0, TX)]) = Some (TX') ->\n   x = 0 /\\ TX = TX' \\/\n   x > 0 /\\ indexr (x-1) (map (substt TX) GH0) = Some (subst TX TX').\nProof.\n  intros GH0. induction GH0; intros.\n  - simpl in H. case_eq (beq_nat x 0); intros E.\n    + rewrite E in H. inversion H.\n      left. split. eapply beq_nat_true_iff. eauto. eauto.\n    + rewrite E in H. inversion H.\n  -  destruct a. unfold id in H. remember ((length (GH0 ++ [(0, TX)]))) as L.\n     case_eq (beq_nat x L); intros E.\n     + assert (x = L). eapply beq_nat_true_iff. eauto.\n       eapply indexr_hit in H.\n       right. split. rewrite app_length in HeqL. simpl in HeqL. omega.\n       assert ((x - 1) = (length (map (substt TX) GH0))).\n       rewrite map_length. rewrite app_length in HeqL. simpl in HeqL. unfold id. omega.\n       simpl.\n       eapply beq_nat_true_iff in H1. unfold id in H1. unfold id. rewrite H1. subst. eauto. eauto. subst. eauto.\n     + assert (x <> L). eapply beq_nat_false_iff. eauto.\n       eapply indexr_miss in H. eapply IHGH0 in H.\n       inversion H. left. eapply H1.\n       right. inversion H1. split. eauto.\n       simpl.\n       assert ((x - 1) <> (length (map (substt TX) GH0))).\n       rewrite app_length in HeqL. simpl in HeqL. rewrite map_length.\n       unfold not. intros. subst L. unfold id in H0. unfold id in H2. unfold not in H0. eapply H0. unfold id in H4. rewrite <-H4. omega.\n       eapply beq_nat_false_iff in H4. unfold id in H4. unfold id. rewrite H4.\n       eauto. subst. eauto.\nQed.\n\n(*\nwhen and how we can replace with multiple environments:\n\nstp2 G1 T1 G2 T2 (GH0 ++ [(0,vtya GX TX)])\n\n1) T1 closed\n\n   stp2 G1 T1 G2' T2' (subst GH0)\n\n2) G1 contains (GX TX) at some index x1\n\n   index x1 G1 = (GX TX)\n   stp2 G (subst (TSel x1) T1) G2' T2'\n\n3) G1 = GX <----- valid for Fsub, but not for DOT !\n\n   stp2 G1 (subst TX T1) G2' T2'\n\n4) G1 and GX unrelated\n\n   stp2 ((GX,TX) :: G1) (subst (TSel (length G1)) T1) G2' T2'\n\n*)\n\n\n\n\n\n\n(* ---- two-env substitution. first define what 'compatible' types mean. ---- *)\n\n\nDefinition compat (GX:venv) (TX: ty) (V: option vl) (G1:venv) (T1:ty) (T1':ty) :=\n  (exists x1 v, index x1 G1 = Some v /\\ V = Some v /\\ GX = GX /\\ val_type GX v TX /\\ T1' = (subst (TSel x1) T1)) \\/\n  (*  (G1 = GX /\\ T1' = (subst TX T1)) \\/ *)   (* this is doesn't work for DOT *)\n  (* ((forall TA TB, TX <> TMem TA TB) /\\ T1' = subst TTop T1) \\/ *)(* can remove all term-only bindings -- may not be necessary after all since it applies nosubst *)\n  (closed_rec 0 0 T1 /\\ T1' = T1) \\/ (* this one is for convenience: redundant with next *)\n  (nosubst T1 /\\ T1' = subst TTop T1).\n\n\nDefinition compat2 (GX:venv) (TX: ty) (V: option vl) (p1:id*(venv*ty)) (p2:id*(venv*ty)) :=\n  match p1, p2 with\n      (n1,(G1,T1)), (n2,(G2,T2)) => n1=n2(*+1 disregarded*) /\\ G1 = G2 /\\ compat GX TX V G1 T1 T2\n  end.\n\n\nLemma closed_compat: forall GX TX V GXX TXX TXX' j k,\n  compat GX TX V GXX TXX TXX' ->\n  closed 0 k TX ->\n  closed j (k+1) TXX ->\n  closed j k TXX'.\nProof.\n  intros. inversion H;[|destruct H2;[|destruct H2]].\n  - destruct H2. destruct H2. destruct H2. destruct H2. destruct H3.\n    destruct H3. destruct H3. destruct H4. rewrite H4.\n    eapply closed_subst. eauto. eauto.\n  - destruct H2. rewrite H3.\n    eapply closed_upgrade. eapply closed_upgrade_free. eauto. omega. omega.\n  - rewrite H3.\n    eapply closed_subst. eauto. eauto.\nQed.\n\nLemma indexr_compat_miss0: forall GH GH' GX TX V (GXX:venv) (TXX:ty) n,\n      Forall2 (compat2 GX TX V) GH GH' ->\n      indexr (n+1) (GH ++ [(0,(GX, TX))]) = Some (GXX,TXX) ->\n      exists TXX', indexr n GH' = Some (GXX,TXX') /\\ compat GX TX V GXX TXX TXX'.\nProof.\n  intros. revert n H0. induction H.\n  - intros. simpl. eauto. simpl in H0. assert (n+1 <> 0). omega. eapply beq_nat_false_iff in H. rewrite H in H0. inversion H0.\n  - intros. simpl. destruct y.\n    case_eq (beq_nat n (length l')); intros E.\n    + simpl in H1. destruct x. rewrite app_length in H1. simpl in H1.\n      assert (n = length l'). eapply beq_nat_true_iff. eauto.\n      assert (beq_nat (n+1) (length l + 1) = true). eapply beq_nat_true_iff.\n      rewrite (Forall2_length _ _ _ _ _ H0). omega.\n      rewrite H3 in H1. destruct p. destruct p0. inversion H1. subst. simpl in H.\n      destruct H. destruct H2. subst. inversion H1. subst.\n      eexists. eauto.\n    + simpl in H1. destruct x.\n      assert (n <> length l'). eapply beq_nat_false_iff. eauto.\n      assert (beq_nat (n+1) (length l + 1) = false). eapply beq_nat_false_iff.\n      rewrite (Forall2_length _ _ _ _ _ H0). omega.\n      rewrite app_length in H1. simpl in H1.\n      rewrite H3 in H1.\n      eapply IHForall2. eapply H1.\nQed.\n\n\n\nLemma compat_top: forall GX TX V G1 T1',\n  compat GX TX V G1 TTop T1' -> closed 0 0 TX -> T1' = TTop.\nProof.\n  intros ? ? ? ? ? CC CLX. repeat destruct CC as [|CC]; ev; eauto.\nQed.\n\nLemma compat_bot: forall GX TX V G1 T1',\n  compat GX TX V G1 TBot T1' -> closed 0 0 TX -> T1' = TBot.\nProof.\n  intros ? ? ? ? ? CC CLX. repeat destruct CC as [|CC]; ev; eauto.\nQed.\n\n\nLemma compat_bool: forall GX TX V G1 T1',\n  compat GX TX V G1 TBool T1' -> closed 0 0 TX -> T1' = TBool.\nProof.\n  intros ? ? ? ? ? CC CLX. repeat destruct CC as [|CC]; ev; eauto.\nQed.\n\nLemma compat_mem: forall GX TX V G1 T1 T2 T1',\n    compat GX TX V G1 (TMem T1 T2) T1' ->\n    closed 0 0 TX ->\n    exists TA TB, T1' = TMem TA TB /\\\n                  compat GX TX V G1 T1 TA /\\\n                  compat GX TX V G1 T2 TB.\nProof.\n  intros ? ? ? ? ? ? ? CC CLX. repeat destruct CC as [|CC].\n  - ev. repeat eexists; eauto. + left. repeat eexists; eauto. + left. repeat eexists; eauto.\n  - ev. repeat eexists; eauto. + right. left. inversion H. eauto. + right. left. inversion H. eauto.\n  - ev. repeat eexists; eauto. + right. right. inversion H. eauto. + right. right. inversion H. eauto.\nQed.\n\n\nLemma compat_mem_fwd2: forall GX TX V G1 T2 T2',\n    compat GX TX V G1 T2 T2' ->\n    compat GX TX V G1 (TMem TBot T2) (TMem TBot T2').\nProof.\n  intros. repeat destruct H as [|H].\n  - ev. repeat eexists; eauto. + left. repeat eexists; eauto. rewrite H3. eauto.\n  - ev. repeat eexists; eauto. + right. left. subst. eauto.\n  - ev. repeat eexists; eauto. + right. right. subst. simpl. eauto.\nQed.\n\nLemma compat_mem_fwd1: forall GX TX V G1 T2 T2',\n    compat GX TX V G1 T2 T2' ->\n    compat GX TX V G1 (TMem T2 TTop) (TMem T2' TTop).\nProof.\n  intros. repeat destruct H as [|H].\n  - ev. repeat eexists; eauto. + left. repeat eexists; eauto. rewrite H3. eauto.\n  - ev. repeat eexists; eauto. + right. left. subst. eauto.\n  - ev. repeat eexists; eauto. + right. right. subst. simpl. eauto.\nQed.\n\nLemma compat_mem_fwdx: forall GX TX V G1 T2 T2',\n    compat GX TX V G1 T2 T2' ->\n    compat GX TX V G1 (TMem T2 T2) (TMem T2' T2').\nProof.\n  intros. repeat destruct H as [|H].\n  - ev. repeat eexists; eauto. + left. repeat eexists; eauto. rewrite H3. eauto.\n  - ev. repeat eexists; eauto. + right. left. subst. eauto.\n  - ev. repeat eexists; eauto. + right. right. subst. simpl. eauto.\nQed.\n\n\nLemma compat_fun: forall GX TX V G1 T1 T2 T1',\n    compat GX TX V G1 (TFun T1 T2) T1' ->\n    closed_rec 0 0 TX ->\n    exists TA TB, T1' = TFun TA TB /\\\n                  compat GX TX V G1 T1 TA /\\\n                  compat GX TX V G1 T2 TB.\nProof.\n  intros ? ? ? ? ? ? ? CC CLX. repeat destruct CC as [|CC].\n  - ev. repeat eexists; eauto. + left. repeat eexists; eauto. + left. repeat eexists; eauto.\n  - ev. repeat eexists; eauto. + right. left. inversion H. eauto. + right. left. inversion H. eauto.\n  - ev. repeat eexists; eauto. + right. right. inversion H. eauto. + right. right. inversion H. eauto.\nQed.\n\n\nLemma compat_sel: forall GX TX V G1 T1' (GXX:venv) (TXX:ty) x v,\n    compat GX TX V G1 (TSel x) T1' ->\n    closed 0 0 TX ->\n    closed 0 0 TXX ->\n    index x G1 = Some v ->\n    val_type GXX v TXX ->\n    exists TXX', T1' = (TSel x) /\\ TXX' = TXX /\\ compat GX TX V GXX TXX TXX'\n.\nProof.\n  intros ? ? ? ? ? ? ? ? ? CC CL CL1 IX. repeat destruct CC as [|CC].\n  - ev. repeat eexists; eauto. + right. left. simpl in H0. eauto.\n  - ev. repeat eexists; eauto. + right. left. simpl in H0. eauto.\n  - ev. repeat eexists; eauto. + right. left. simpl in H0. eauto.\nQed.\n\n\n\nLemma compat_selh: forall GX TX V G1 T1' GH0 GH0' (GXX:venv) (TXX:ty) x,\n    compat GX TX V G1 (TSelH x) T1' ->\n    closed 0 0 TX ->\n    indexr x (GH0 ++ [(0, (GX, TX))]) = Some (GXX, TXX) ->\n    Forall2 (compat2 GX TX V) GH0 GH0' ->\n    (x = 0 /\\ GXX = GX /\\ TXX = TX) \\/\n    exists TXX',\n      x > 0 /\\ T1' = TSelH (x-1) /\\\n      indexr (x-1) GH0' = Some (GXX, TXX') /\\\n      compat GX TX V GXX TXX TXX'\n.\nProof.\n  intros ? ? ? ? ? ? ? ? ? ? CC CL IX FA.\n  unfold id in x.\n  case_eq (beq_nat x 0); intros E.\n  - left. assert (x = 0). eapply beq_nat_true_iff. eauto. subst x. rewrite indexr_hit0 in IX. inversion IX. eauto.\n  - right. assert (x <> 0). eapply beq_nat_false_iff. eauto.\n    assert (x > 0). omega. remember (x-1) as y. assert (x = y+1) as Y. omega. subst x.\n    eapply (indexr_compat_miss0 GH0 GH0' _ _ _ _ _ _ FA) in IX.\n    repeat destruct CC as [|CC].\n    + ev. simpl in H7. rewrite E in H7. rewrite <-Heqy in H7. eexists. eauto.\n    + ev. inversion H1. omega.\n    + ev. simpl in H4. rewrite E in H4. rewrite <-Heqy in H4. eexists. eauto.\nQed.\n\n\nLemma compat_all: forall GX TX V G1 T1 T2 T1' n,\n    compat GX TX V G1 (TAll T1 T2) T1' ->\n    closed 0 0 TX ->\n    closed 1 (n+1) T2 ->\n    exists TA TB, T1' = TAll TA TB /\\\n                  closed 1 n TB /\\\n                  compat GX TX V G1 T1 TA /\\\n                  compat GX TX V G1 (open_rec 0 (TSelH (n+1)) T2) (open_rec 0 (TSelH n) TB).\nProof.\n  intros ? ? ? ? ? ? ? ? CC CLX CL2. repeat destruct CC as [|CC].\n\n  - ev. simpl in H0. repeat eexists; eauto. eapply closed_subst; eauto.\n    + unfold compat. left. repeat eexists; eauto.\n    + unfold compat. left. repeat eexists; eauto. rewrite subst_open_commute; eauto.\n\n  - ev. simpl in H0. inversion H. repeat eexists; eauto. eapply closed_upgrade_free; eauto. omega.\n    + unfold compat. right. right. split. eapply nosubst_intro; eauto. symmetry. eapply closed_no_subst; eauto.\n    + unfold compat. right. right. split.\n      * eapply nosubst_open. simpl. omega. eapply nosubst_intro. eauto.\n      * rewrite subst_open_commute.  assert (T2 = subst TTop T2) as E. symmetry. eapply closed_no_subst; eauto. rewrite <-E. eauto. eauto. eauto.\n\n  - ev. simpl in H0. destruct H. repeat eexists; eauto. eapply closed_subst; eauto. eauto.\n    + unfold compat. right. right. eauto.\n    + unfold compat. right. right. split.\n      * eapply nosubst_open. simpl. omega. eauto.\n      * rewrite subst_open_commute; eauto.\nQed.\n\n\nLemma compat_bind: forall GX TX V G1 T2 T1' n,\n    compat GX TX V G1 (TBind T2) T1' ->\n    closed 0 0 TX ->\n    closed 1 (n+1) T2 ->\n    exists TB, T1' = TBind TB /\\\n                  closed 1 n TB /\\\n                  compat GX TX V G1 (open_rec 0 (TSelH (n+1)) T2) (open_rec 0 (TSelH n) TB).\nProof.\n  intros ? ? ? ? ? ? ? CC CLX CL2. repeat destruct CC as [|CC].\n\n  - ev. simpl in H0. repeat eexists; eauto. eapply closed_subst; eauto.\n    + unfold compat. left. repeat eexists; eauto. rewrite subst_open_commute; eauto.\n\n  - ev. simpl in H0. inversion H. repeat eexists; eauto. eapply closed_upgrade_free; eauto. omega.\n    + unfold compat. right. right. split.\n      * eapply nosubst_open. simpl. omega. eapply nosubst_intro. eauto.\n      * rewrite subst_open_commute.  assert (T2 = subst TTop T2) as E. symmetry. eapply closed_no_subst; eauto. rewrite <-E. eauto. eauto. eauto.\n\n  - ev. simpl in H0. simpl in H. repeat eexists; eauto. eapply closed_subst; eauto. eauto.\n    + unfold compat. right. right. split.\n      * eapply nosubst_open. simpl. omega. eauto.\n      * rewrite subst_open_commute; eauto.\nQed.\n\n\n(* can be called on level >= 1 *)\n\nLemma stp2_substitute_aux: forall n, forall d m G1 G2 T1 T2 GH n1,\n   stp2 (S d) m G1 T1 G2 T2 GH n1 -> n1 < n ->\n   forall GH0 GH0' GX TX T1' T2' V,\n     GH = (GH0 ++ [(0,(GX, TX))]) ->\n     closed 0 0 TX ->\n     compat GX TX V G1 T1 T1' ->\n     compat GX TX V G2 T2 T2' ->\n     Forall2 (compat2 GX TX V) GH0 GH0' ->\n     stp2 (S d) m G1 T1' G2 T2' GH0' n1.\nProof.\n  intros n. induction n; intros d m G1 G2 T1 T2 GH n1 H ?. inversion H0.\n  inversion H; subst.\n  - Case \"topx\".\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n    eapply compat_top in IX1.\n    eapply compat_top in IX2.\n    subst. eapply stp2_topx. eauto. eauto.\n\n  - Case \"botx\".\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n    eapply compat_bot in IX1.\n    eapply compat_bot in IX2.\n    subst. eapply stp2_botx. eauto. eauto.\n\n  - Case \"top\".\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n    eapply compat_top in IX2.\n    subst. eapply stp2_top. eapply IHn; eauto. omega.\n    eauto.\n\n  - Case \"bot\".\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n    eapply compat_bot in IX1.\n    subst. eapply stp2_bot. eapply IHn; eauto. omega.\n    eauto.\n\n  - Case \"bool\".\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n    eapply compat_bool in IX1.\n    eapply compat_bool in IX2.\n    subst. eapply stp2_bool; eauto.\n    eauto. eauto.\n\n  - Case \"fun\".\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n    eapply compat_fun in IX1. repeat destruct IX1 as [? IX1].\n    eapply compat_fun in IX2. repeat destruct IX2 as [? IX2].\n    subst. eapply stp2_fun. eapply IHn; eauto. omega. eapply IHn; eauto. omega.\n    eauto. eauto.\n\n  - Case \"mem\".\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n    eapply compat_mem in IX1. repeat destruct IX1 as [? IX1].\n    eapply compat_mem in IX2. repeat destruct IX2 as [? IX2].\n    subst. eapply stp2_mem2. eapply IHn; eauto. omega. eapply IHn; eauto. omega.\n    eauto. eauto.\n\n  - Case \"sel1\".\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n\n    assert (length GH = length GH0 + 1). subst GH. eapply app_length.\n    assert (length GH0 = length GH0') as EL. eapply Forall2_length. eauto.\n\n    eapply (compat_sel GXX TXX V G1 T1' GX TX) in IX1. repeat destruct IX1 as [? IX1].\n\n    assert (compat GXX TXX V GX TX TX) as CPX. right. left. eauto.\n\n    subst.\n    eapply stp2_sel1. eauto. eauto. eauto.\n    eapply IHn. eauto. omega. eauto. eauto. eauto.\n    eapply compat_mem_fwd2. eauto. eauto.\n    eapply IHn; eauto; try omega.\n    eauto. eauto. eauto. eauto.\n\n  - Case \"selb1\".\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n\n    assert (closed 0 (length ([]:aenv)) (TBind (TMem TBot T0))). eapply stp2_closed2; eauto.\n    simpl in  H6. unfold closed in H7. inversion H7. subst. inversion H11. subst.\n\n    admit. (* eapply stp2_selb1. arg has GH = [] so nothing to be done (inversion IX2 and then a couple simplifications *)\n\n  - Case \"sel2\".\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n\n    assert (length GH = length GH0 + 1). subst GH. eapply app_length.\n    assert (length GH0 = length GH0') as EL. eapply Forall2_length. eauto.\n\n    eapply (compat_sel GXX TXX V G2 T2' GX TX) in IX2. repeat destruct IX2 as [? IX2].\n\n    assert (compat GXX TXX V GX TX TX) as CPX. right. left. eauto.\n\n    subst.\n    eapply stp2_sel2. eauto. eauto. eauto.\n    eapply IHn. eauto. omega. eauto. eauto. eauto.\n    eapply compat_mem_fwd1. eauto. eauto.\n    eapply IHn; eauto; try omega.\n    eauto. eauto. eauto. eauto.\n\n  - Case \"selx\".\n\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n\n    assert (length GH = length GH0 + 1). subst GH. eapply app_length.\n    assert (length GH0 = length GH0') as EL. eapply Forall2_length. eauto.\n\n    assert (T1' = TSel x1). destruct IX1. ev. eauto. destruct H5. ev. auto. ev. eauto.\n    assert (T2' = TSel x2). destruct IX2. ev. eauto. destruct H6. ev. auto. ev. eauto.\n\n    subst.\n    eapply stp2_selx. eauto. eauto.\n\n  - Case \"sela1\".\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n\n    assert (length GH = length GH0 + 1). subst GH. eapply app_length.\n    assert (length GH0 = length GH0') as EL. eapply Forall2_length. eauto.\n\n    assert (compat GXX TXX V G1 (TSelH x) T1') as IXX. eauto.\n\n    eapply (compat_selh GXX TXX V G1 T1' GH0 GH0' GX TX) in IX1. repeat destruct IX1 as [? IX1].\n\n    destruct IX1.\n    + SCase \"x = 0\".\n      repeat destruct IXX as [|IXX]; ev.\n      * subst. simpl.\n        eapply stp2_sel1. eauto. eauto. eauto.\n        eapply IHn. eauto. omega. eauto. eauto. right. left. eauto.\n        eapply compat_mem_fwd2. eauto.\n        eauto.\n        eapply IHn; eauto; try omega.\n      * subst. inversion H8. omega.\n      * subst. destruct H8. eauto.\n    + SCase \"x > 0\".\n      ev. subst.\n      eapply stp2_sela1. eauto.\n\n      assert (x-1+1=x) as A by omega.\n      remember (x-1) as x1. rewrite <- A in H3.\n      eapply closed_compat. eauto. eapply closed_upgrade_free. eauto. omega. eauto.\n\n      eapply IHn; eauto. omega. eauto. eapply compat_mem_fwd2. eauto.\n      eapply IHn; eauto; try omega.\n    (* remaining obligations *)\n    + eauto. + subst GH. eauto. + eauto.\n\n\n  - Case \"selab1\".\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n\n    assert (length GH = length GH0 + 1). subst GH. eapply app_length.\n    assert (length GH0 = length GH0') as EL. eapply Forall2_length. eauto.\n\n    assert (compat GXX TXX V G1 (TSelH x) T1') as IXX. eauto.\n\n    eapply (compat_selh GXX TXX V G1 T1' GH0 GH0' GX TX) in IX1. repeat destruct IX1 as [? IX1].\n\n    destruct IX1.\n    + SCase \"x = 0\".\n      assert (d = 0). admit. (* either we are called with m = 1 (from 2->1) or with m = 2, in which case we can call 2->1 *)\n      subst d.\n      admit. (* TODO! *)\n        (*\n          Do basically what 2->1 does. Create a sel1 node.\n         *)\n    + SCase \"x > 0\".\n      ev. subst.\n      admit. (* miss case, eapply stp2_selab1 *)\n    (* remaining obligations *)\n    + eauto. + subst GH. eauto. + eauto.\n\n  - Case \"sela2\". admit. (* just like sela1 *)\n\n  - Case \"selax\".\n\n    intros GH0 GH0' GXX TXX T1' T2' V ? CX IX1 IX2 FA.\n\n    assert (length GH = length GH0 + 1). subst GH. eapply app_length.\n    assert (length GH0 = length GH0') as EL. eapply Forall2_length. eauto.\n\n    assert (compat GXX TXX V G1 (TSelH x) T1') as IXX1. eauto.\n    assert (compat GXX TXX V G2 (TSelH x) T2') as IXX2. eauto.\n\n    eapply (compat_selh GXX TXX V G1 T1' GH0 GH0' GX TX) in IX1. repeat destruct IX1 as [? IX1].\n    eapply (compat_selh GXX TXX V G2 T2' GH0 GH0' GX TX) in IX2. repeat destruct IX2 as [? IX2].\n    assert (not (nosubst (TSelH 0))). unfold not. intros. simpl in H1. eauto.\n    assert (not (closed 0 0 (TSelH 0))). unfold not. intros. inversion H5. omega.\n\n    destruct x; destruct IX1; ev; try omega; destruct IX2; ev; try omega; subst.\n    + SCase \"x = 0\".\n      repeat destruct IXX1 as [IXX1|IXX1]; ev; try contradiction.\n      repeat destruct IXX2 as [IXX2|IXX2]; ev; try contradiction.\n      * SSCase \"sel-sel\".\n        subst. inversion H15. subst.\n        simpl. eapply stp2_selx. eauto. eauto.\n    + SCase \"x > 0\".\n      destruct IXX1; destruct IXX2; ev; subst; eapply stp2_selax; eauto.\n    (* leftovers *)\n    + eauto. + subst. eauto. + eauto. + eauto. + subst. eauto. + eauto.\n\n  - Case \"all\".\n    intros GH0 GH0' GX TX T1' T2' V ? CX IX1 IX2 FA.\n\n    assert (length GH = length GH0 + 1). subst GH. eapply app_length.\n    assert (length GH0 = length GH0') as EL. eapply Forall2_length. eauto.\n\n    eapply compat_all in IX1. repeat destruct IX1 as [? IX1].\n    eapply compat_all in IX2. repeat destruct IX2 as [? IX2].\n\n    subst.\n\n    eapply stp2_all.\n    + eapply IHn. eauto. omega. eauto. eauto. eauto. eauto. eauto.\n    + eauto.\n    + eauto.\n    + subst.\n      eapply IHn. eauto. omega.\n      change ((0, (G1, T0)) :: GH0 ++ [(0, (GX, TX))]) with\n      (((0, (G1, T0)) :: GH0) ++ [(0, (GX, TX))]).\n      reflexivity.\n      eauto.\n      rewrite app_length. simpl. rewrite EL. eauto.\n      rewrite app_length. simpl. rewrite EL. eauto.\n      eapply Forall2_cons. simpl. eauto. eauto.\n    + subst.\n      (* specialize (IHn) with (GH0 := (0, (G2, T4))::GH0). *)\n      eapply IHn. eauto. omega.\n      instantiate (3:= (0, (G2, T4))::GH0).\n      reflexivity.\n      eauto.\n      rewrite app_length. simpl. rewrite EL. eauto.\n      rewrite app_length. simpl. rewrite EL. eauto.\n      eapply Forall2_cons. simpl. eauto. eauto.\n    + eauto.\n    + eauto. subst GH. rewrite <-EL. eapply closed_upgrade_free. eauto. omega.\n    + eauto.\n    + eauto. subst GH. rewrite <-EL. eapply closed_upgrade_free. eauto. omega.\n\n  - Case \"bind\".\n    intros GH0 GH0' GX TX T1' T2' V ? CX IX1 IX2 FA.\n\n    assert (length GH = length GH0 + 1). subst GH. eapply app_length.\n    assert (length GH0 = length GH0') as EL. eapply Forall2_length. eauto.\n\n    eapply compat_bind in IX1. repeat destruct IX1 as [? IX1].\n    eapply compat_bind in IX2. repeat destruct IX2 as [? IX2].\n\n    subst.\n\n    eapply stp2_bindb.\n    + eauto.\n    + eauto.\n    + subst.\n      eapply IHn. eauto. omega.\n      change\n        ((0, (G2, open (TSelH (length (GH0 ++ [(0, (GX, TX))]))) T3))\n           :: GH0 ++ [(0, (GX, TX))]) with\n      (((0, (G2, open (TSelH (length (GH0 ++ [(0, (GX, TX))]))) T3))\n          :: GH0) ++ [(0, (GX, TX))]).\n      reflexivity.\n      eauto.\n      rewrite app_length. simpl. rewrite EL. eauto.\n      rewrite app_length. simpl. rewrite EL. eauto.\n      eapply Forall2_cons. simpl. eauto. eauto. repeat split. rewrite app_length. simpl. rewrite EL. eapply IX2. eauto.\n    + subst.\n(*\n      specialize (IHstp2 H2) with (GH1 := (0, (G1,  open (TSelH (length (GH0 ++ [(0, (GX, TX))]))) T1))::GH0). *)\n      eapply IHn. eauto. omega.\n      instantiate (3:=(0, (G1,  open (TSelH (length (GH0 ++ [(0, (GX, TX))]))) T0))::GH0).\n      reflexivity.\n      eauto.\n      rewrite app_length. simpl. rewrite EL. eauto.\n      rewrite app_length. simpl. rewrite EL. eauto.\n      eapply Forall2_cons. simpl. eauto. eauto. repeat split. rewrite app_length. simpl. rewrite EL. eapply IX1. eauto.\n    + eauto.\n    + eauto. subst GH. fold id. rewrite <- EL.\n      eapply closed_upgrade_free. eauto. unfold id in H5.\n      rewrite app_length. simpl. omega.\n    + eauto.\n    + eauto. subst GH. fold id. rewrite <-EL.\n      eapply closed_upgrade_free. eauto. unfold id in H5.\n      rewrite app_length. simpl. omega.\n\n  - Case \"wrapf\".\n    intros. subst. eapply stp2_wrapf. eapply IHn; eauto. omega.\n  - Case \"transf\".\n    intros. subst.\n\n    assert (exists vx T3',\n              compat GX TX (Some vx) G1 T1 T1' /\\\n              compat GX TX (Some vx) G2 T2 T2' /\\\n              compat GX TX (Some vx) ((fresh G3,vx)::G3) T3 T3' /\\\n              Forall2 (compat2 GX TX (Some vx)) GH0 GH0').\n    {\n      (* TODO: If V is None, use vx = vty GX TX. (may need to pass in val_type evidence\n               If V is Some v, use v. However v might never actually be used.\n               In that case, process as with V = None. *)\n      admit.\n    }\n    ev.\n\n    assert (stp2 (S d) true G1 T1 ((fresh G3,x)::G3) T3 (GH0 ++ [(0, (GX, TX))]) n0) as S1.\n    eapply stp2_extend2; eauto.\n    assert (stp2 (S d) false ((fresh G3,x)::G3) T3 G2 T2 (GH0 ++ [(0, (GX, TX))]) n2) as S2.\n    eapply stp2_extend1; eauto.\n\n    eapply stp2_transf.\n    eapply IHn. eauto. omega. eauto. eauto. eauto. eauto. eauto.\n    eapply IHn. eauto. omega. eauto. eauto. eauto. eauto. eauto.\nQed.\n\n\nLemma stpd2_substitute: forall m G1 G2 T1 T2 GH,\n   stpd2 m G1 T1 G2 T2 GH ->\n   forall GH0 GH0' GX TX T1' T2' V,\n     GH = (GH0 ++ [(0,(GX, TX))]) ->\n     closed 0 0 TX ->\n     compat GX TX V G1 T1 T1' ->\n     compat GX TX V G2 T2 T2' ->\n     Forall2 (compat2 GX TX V) GH0 GH0' ->\n     stpd2 m G1 T1' G2 T2' GH0'.\nProof. intros. repeat eu. eexists. eapply stp2_substitute_aux; eauto. Qed.\n\n\n(* --------------------------------- *)\n\nLemma valtp_closed: forall G v T,\n  val_type G v T -> closed 0 0 T.\nProof.\n  intros. inversion H; subst; repeat ev;\n  match goal with\n      [ H : stp2 ?s ?m ?G1 ?T1 G T [] ?n |- _ ] =>\n      eapply stp2_closed2 in H; simpl in H; apply H\n  end.\nQed.\n\nHint Constructors wf_envh.\n\nLemma stp_to_stp2: forall G1 GH T1 T2,\n  stp G1 GH T1 T2 ->\n  forall GX GY, wf_env GX G1 -> wf_envh GX GY GH ->\n  stpd2 false GX T1 GX T2 GY.\nProof with stpd2_wrapf.\n  intros G1 G2 T1 T2 ST. induction ST; intros GX GY WX WY; eapply stpd2_wrapf.\n  - Case \"topx\". eapply stpd2_topx.\n  - Case \"botx\". eapply stpd2_botx.\n  - Case \"top\". eapply stpd2_top.\n    specialize (IHST GX GY WX WY).\n    apply stpd2_reg2 in IHST.\n    apply IHST.\n  - Case \"bot\". eapply stpd2_bot.\n    specialize (IHST GX GY WX WY).\n    apply stpd2_reg2 in IHST.\n    apply IHST.\n  - Case \"bool\". eapply stpd2_bool; eauto.\n  - Case \"fun\". eapply stpd2_fun; eauto.\n  - Case \"mem\". eapply stpd2_mem; eauto.\n  - Case \"sel1\".\n    assert (exists v : vl, index x GX = Some v /\\ val_type GX v TX) as A.\n    eapply index_safe_ex. eauto. eauto.\n    destruct A as [? [? VT]].\n    eapply stpd2_sel1. eauto. eauto. eapply valtp_closed; eauto. eauto.\n    specialize (IHST2 GX GY WX WY).\n    apply stpd2_reg2 in IHST2.\n    apply IHST2.\n  - Case \"sel2\".\n    assert (exists v : vl, index x GX = Some v /\\ val_type GX v TX) as A.\n    eapply index_safe_ex. eauto. eauto.\n    destruct A as [? [? VT]].\n    eapply stpd2_sel2. eauto. eauto. eapply valtp_closed; eauto. eauto.\n    specialize (IHST2 GX GY WX WY).\n    apply stpd2_reg2 in IHST2.\n    apply IHST2.\n  - Case \"selb1\".\n    assert (exists v : vl, index x GX = Some v /\\ val_type GX v TX) as A.\n    eapply index_safe_ex. eauto. eauto.\n    destruct A as [? [? VT]].\n    eapply stpd2_selb1. eauto. eauto. eapply valtp_closed; eauto. eauto.\n    specialize (IHST2 GX GY WX WY).\n    apply stpd2_reg2 in IHST2.\n    apply IHST2.\n  - Case \"selb2\". admit.\n  - Case \"selx\".\n    assert (exists v : vl, index x GX = Some v /\\ val_type GX v TX) as A.\n    eapply index_safe_ex. eauto. eauto. ev.\n    eapply stpd2_selx. eauto. eauto.\n  - Case \"sela1\". eauto.\n    assert (exists v, indexr x GY = Some v /\\ valh_type GX GY v TX) as A.\n    eapply index_safeh_ex. eauto. eauto. eauto.\n    destruct A as [? [? VT]]. destruct x0.\n    inversion VT. subst.\n    eapply stpd2_sela1. eauto. eauto. eapply IHST1. eauto. eauto.\n    specialize (IHST2 _ _ WX WY).\n    apply stpd2_reg2 in IHST2.\n    apply IHST2.\n  - Case \"sela2\".\n    assert (exists v, indexr x GY = Some v /\\ valh_type GX GY v TX) as A.\n    eapply index_safeh_ex. eauto. eauto. eauto.\n    destruct A as [? [? VT]]. destruct x0.\n    inversion VT. subst.\n    eapply stpd2_sela2. eauto. eauto. eapply IHST1. eauto. eauto.\n    specialize (IHST2 _ _ WX WY).\n    apply stpd2_reg2 in IHST2.\n    apply IHST2.\n  - Case \"selab1\".\n    assert (exists v, indexr x GY = Some v /\\ valh_type GX GY v TX) as A.\n    eapply index_safeh_ex. eauto. eauto. eauto.\n    destruct A as [? [? VT]].\n    inversion VT. subst.\n    eapply stpd2_selab1. eauto. eapply IHST1. eauto. econstructor.\n    specialize (IHST2 _ _ WX WY).\n    apply stpd2_reg2 in IHST2.\n    apply IHST2.\n  - Case \"selab2\". admit.\n  - Case \"selax\". eauto.\n    assert (exists v, indexr x GY = Some v /\\ valh_type GX GY v TX) as A.\n    eapply index_safeh_ex. eauto. eauto. eauto. ev. destruct x0.\n    eapply stpd2_selax. eauto.\n  - Case \"all\".\n    subst x. assert (length GY = length GH). eapply wfh_length; eauto.\n    eapply stpd2_all. eauto. rewrite H. eauto. rewrite H.  eauto.\n    rewrite H.\n    eapply IHST2. eauto. eapply wfeh_cons. eauto.\n    rewrite H. apply IHST3; eauto.\n  - Case \"bind\".\n    subst x. assert (length GY = length GH). eapply wfh_length; eauto. unfold id in H.\n    eapply stpd2_bind. rewrite H. eauto. rewrite H. eauto.\n    rewrite H.\n    eapply IHST1. eauto. eapply wfeh_cons. eauto.\n    rewrite H. eapply IHST2; eauto.\nQed.\n\n\n\n\nLemma invert_abs: forall venv vf T1 T2,\n  val_type venv vf (TFun T1 T2) ->\n  exists env tenv f x y T3 T4,\n    vf = (vabs env f x y) /\\\n    fresh env <= f /\\\n    1 + f <= x /\\\n    wf_env env tenv /\\\n    has_type ((x,T3)::(f,TFun T3 T4)::tenv) y T4 /\\\n    sstpd2 true venv T1 env T3 [] /\\\n    sstpd2 true env T4 venv T2 [].\nProof.\n  intros. inversion H; repeat ev; try solve by inversion. inversion H4.\n  assert (stpd2 false venv0 T1 venv1 T0 []) as E1. eauto.\n  assert (stpd2 false venv1 T3 venv0 T2 []) as E2. eauto.\n  eapply stpd2_upgrade in E1. eapply stpd2_upgrade in E2.\n  repeat eu. repeat eexists; eauto.\nQed.\n\n\nLemma inv_vtp_half: forall G v T GH,\n  val_type G v T ->\n  exists T0, val_type (base v) v T0 /\\ closed 0 0 T0 /\\ stpd2 false (base v) T0 G T GH.\nProof.\n  intros. induction H.\n  - eexists. split; try split.\n    + simpl. econstructor. eassumption. ev. eapply stp2_reg1 in H0. apply H0.\n    + ev. eapply stp2_closed1 in H0. simpl in H0. apply H0.\n    + eapply sstpd2_downgrade. ev. eexists. simpl.\n      eapply stp2_extendH_mult0. eassumption.\n  - eexists. split; try split.\n    + simpl. econstructor. ev. eapply stp2_reg1 in H. apply H.\n    + ev. eapply stp2_closed1 in H. simpl in H. apply H.\n    + eapply sstpd2_downgrade. ev. eexists. simpl.\n      eapply stp2_extendH_mult0. eassumption.\n  - eexists. split; try split.\n    + simpl. econstructor; try eassumption. ev. eapply stp2_reg1 in H3. apply H3.\n    + ev. eapply stp2_closed1 in H3. simpl in H3. apply H3.\n    + eapply sstpd2_downgrade. ev. eexists. simpl.\n      eapply stp2_extendH_mult0. eassumption.\n  - eexists. split; try split.\n    + simpl. subst. econstructor; try eassumption. reflexivity. ev. eapply stp2_reg1 in H1. apply H1.\n    + ev. eapply stp2_closed1 in H2. simpl in H2. apply H2.\n    + eapply sstpd2_downgrade. ev. eexists. simpl.\n      eapply stp2_extendH_mult0. eassumption.\n  - repeat ev. eexists. split; try split; try eassumption.\n    + admit.\nQed.\n\nLemma invert_tabs: forall venv vf vx T1 T2,\n  val_type venv vf (TAll T1 T2) ->\n  val_type venv vx T1 ->\n  sstpd2 true venv T2 venv T2 [] ->\n  exists env tenv x y T3 T4,\n    vf = (vtabs env x T3 y) /\\\n    fresh env = x /\\\n    wf_env env tenv /\\\n    has_type ((x,T3)::tenv) y (open (TSel x) T4) /\\\n    sstpd2 true venv T1 env T3 [] /\\\n    sstpd2 true ((x,vx)::env) (open (TSel x) T4) venv T2 []. (* (open T1 T2) []. *)\nProof.\n  intros venv0 vf vx T1 T2 VF VX STY. inversion VF; ev; try solve by inversion. inversion H2. subst.\n  eexists. eexists. eexists. eexists. eexists. eexists.\n  repeat split; eauto.\n  remember (fresh venv1) as x.\n  remember (x + fresh venv0) as xx.\n\n  eapply stpd2_upgrade; eauto.\n\n  (* -- new goal: result -- *)\n\n  (* inversion of TAll < TAll *)\n  assert (stpd2 false venv0 T1 venv1 T0 []) as ARG. eauto.\n  assert (stpd2 false venv1 (open (TSelH 0) T3) venv0 (open (TSelH 0) T2) [(0,(venv0, T1))]) as KEY. {\n    eauto.\n  }\n  eapply stpd2_upgrade in ARG.\n\n  (* need reflexivity *)\n  assert (stpd2 false venv0 T1 venv0 T1 []). eapply stpd2_wrapf. eapply stpd2_reg1. eauto.\n  assert (closed 0 0 T1). eapply stpd2_closed1 in H1. simpl in H1. eauto.\n\n  (* now rename *)\n\n  assert (stpd2 false ((fresh venv1,vx) :: venv1) (open_rec 0 (TSel (fresh venv1)) T3) venv0 (T2) []). { (* T2 was open T1 T2 *)\n\n    (* now that sela1/sela2 can use subtyping, it is better to dispatch on the\n       valtp evidence (instead of the type, as before) *)\n\n    eapply inv_vtp_half in VX. ev.\n\n    assert (closed 0 (length ([]:aenv)) T2). eapply sstpd2_closed1; eauto.\n    assert (open (TSelH 0) T2 = T2) as OP2. symmetry. eapply closed_no_open; eauto.\n\n\n    eapply stpd2_substitute with (GH0:=nil).\n    eapply stpd2_extend1. eapply stpd2_narrow. eapply H6. eapply KEY.\n    eauto. simpl. eauto. eauto.\n    left. repeat eexists. eapply index_hit2. eauto. eauto. eauto. eauto.\n    rewrite (subst_open_zero 0 1). eauto. eauto.\n    right. left. split. rewrite OP2. eauto. eauto. eauto.\n  }\n  eapply stpd2_upgrade in H4.\n\n  (* done *)\n  subst. eauto.\nQed.\n\n\n\n(* if not a timeout, then result not stuck and well-typed *)\n\nTheorem full_safety : forall n e tenv venv res T,\n  teval n venv e = Some res -> has_type tenv e T -> wf_env venv tenv ->\n  res_type venv res T.\n\nProof.\n  intros n. induction n.\n  (* 0 *)   intros. inversion H.\n  (* S n *) intros. destruct e; inversion H.\n\n  - Case \"True\".\n    remember (ttrue) as e. induction H0; inversion Heqe; subst.\n    + eapply not_stuck. eapply v_bool; eauto.\n    + eapply restp_widen. eapply IHhas_type; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n  - Case \"False\".\n    remember (tfalse) as e. induction H0; inversion Heqe; subst.\n    + eapply not_stuck. eapply v_bool; eauto.\n    + eapply restp_widen. eapply IHhas_type; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n  - Case \"Var\".\n    remember (tvar i) as e. induction H0; inversion Heqe; subst.\n    + destruct (index_safe_ex venv0 env T1 i) as [v [I V]]; eauto.\n      rewrite I. eapply not_stuck. eapply V.\n\n    + SCase \"pack\". admit.\n    + SCase \"unpack\". admit.\n\n    + eapply restp_widen. eapply IHhas_type; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n  - Case \"Typ\".\n    remember (ttyp t) as e. induction H0; inversion Heqe; subst.\n    + admit. (* TODO: insert v_pack! *) (*eapply not_stuck. eapply v_pack. eapply v_ty; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto. econstructor. *)\n    + eapply restp_widen. eapply IHhas_type; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n  - Case \"App\".\n    remember (tapp e1 e2) as e. induction H0; inversion Heqe; subst.\n    +\n      remember (teval n venv0 e1) as tf.\n      remember (teval n venv0 e2) as tx.\n\n\n      destruct tx as [rx|]; try solve by inversion.\n      assert (res_type venv0 rx T1) as HRX. SCase \"HRX\". subst. eapply IHn; eauto.\n      inversion HRX as [? vx].\n\n      destruct tf as [rf|]; subst rx; try solve by inversion.\n      assert (res_type venv0 rf (TFun T1 T2)) as HRF. SCase \"HRF\". subst. eapply IHn; eauto.\n      inversion HRF as [? vf].\n\n      destruct (invert_abs venv0 vf T1 T2) as\n          [env1 [tenv [f0 [x0 [y0 [T3 [T4 [EF [FRF [FRX [WF [HTY [STX STY]]]]]]]]]]]]]. eauto.\n      (* now we know it's a closure, and we have has_type evidence *)\n\n      assert (res_type ((x0,vx)::(f0,vf)::env1) res T4) as HRY.\n        SCase \"HRY\".\n          subst. eapply IHn. eauto. eauto.\n          (* wf_env f x *) econstructor. eapply valtp_widen; eauto. eapply sstpd2_extend2. eapply sstpd2_extend2. eauto. eauto. eauto.\n          (* wf_env f   *) econstructor. eapply v_abs; eauto. eapply sstpd2_extend2.\n          eapply sstpd2_downgrade in STX. eapply sstpd2_downgrade in STY. repeat eu.\n          assert (stpd2 false env1 T3 env1 T3 []) as A3. {\n            eapply stpd2_wrapf. eapply stpd2_reg2. eauto.\n          }\n          inversion A3 as [na3 HA3].\n          assert (stpd2 false env1 T4 env1 T4 []) as A4 by solve [eapply stpd2_wrapf; eapply stpd2_reg1; eauto].\n          inversion A4 as [na4 HA4].\n          eexists. eapply stp2_fun. eassumption. eassumption. eauto. eauto.\n          (* TODO: sstpd2_fun constructor *)\n\n      inversion HRY as [? vy].\n\n      eapply not_stuck. eapply valtp_widen; eauto. eapply sstpd2_extend1. eapply sstpd2_extend1. eauto. eauto. eauto.\n\n    + eapply restp_widen. eapply IHhas_type; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n\n  - Case \"Abs\".\n    remember (tabs i i0 e) as xe. induction H0; inversion Heqxe; subst.\n    + eapply not_stuck. eapply v_abs; eauto. rewrite (wf_fresh venv0 env H1). eauto. eapply stpd2_upgrade. eapply stp_to_stp2. eauto. eauto. econstructor.\n    + eapply restp_widen. eapply IHhas_type; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n  - Case \"TApp\".\n    remember (ttapp e1 e2) as e. induction H0; inversion Heqe; subst.\n    +\n      remember (teval n venv0 e1) as tf.\n      remember (teval n venv0 e2) as tx.\n\n      destruct tx as [rx|]; try solve by inversion.\n      assert (res_type venv0 rx T11) as HRX. SCase \"HRX\". subst. eapply IHn; eauto.\n      inversion HRX as [? vx].\n\n      subst rx.\n\n      destruct tf as [rf|]; try solve by inversion.\n      assert (res_type venv0 rf (TAll T11 T12)) as HRF. SCase \"HRF\". subst. eapply IHn; eauto.\n      inversion HRF as [? vf].\n\n      destruct (invert_tabs venv0 vf vx T11 T12) as\n          [env1 [tenv [x0 [y0 [T3 [T4 [EF [FRX [WF [HTY [STX STY]]]]]]]]]]].\n      eauto. eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n      (* now we know it's a closure, and we have has_type evidence *)\n\n      assert (res_type ((x0,vx)::env1) res (open (TSel x0) T4)) as HRY.\n        SCase \"HRY\".\n          subst. eapply IHn. eauto. eauto.\n          (* wf_env x *) econstructor. eapply valtp_widen; eauto. eapply sstpd2_extend2. eauto. eauto. eauto.\n      inversion HRY as [? vy].\n\n      eapply not_stuck. eapply valtp_widen. eauto. eauto.\n\n    + eapply restp_widen. eapply IHhas_type; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n  - Case \"TAbs\".\n    remember (ttabs i t e) as xe. induction H0; inversion Heqxe; subst.\n    + eapply not_stuck. eapply v_tabs; eauto. subst i. eauto. rewrite (wf_fresh venv0 env H1). eauto. eapply stpd2_upgrade. eapply stp_to_stp2. eauto. eauto. econstructor.\n    +  eapply restp_widen. eapply IHhas_type; eauto. eapply stpd2_upgrade. eapply stp_to_stp2; eauto.\n\n       Grab Existential Variables. apply 0. apply 0.\nQed.\n\nEnd FSUB.", "meta": {"author": "TiarkRompf", "repo": "minidot", "sha": "57f6f31e21d61122d0f48b74fad2247074fa3cf8", "save_path": "github-repos/coq/TiarkRompf-minidot", "path": "github-repos/coq/TiarkRompf-minidot/minidot-57f6f31e21d61122d0f48b74fad2247074fa3cf8/dev2015/dot10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2422150894771393}}
{"text": "(** This file is a tutorial to learn how to use the Cerise Program Logic within Coq.\n    We will specify a simple program and explain how to use the tactics of the\n    Cerise Proofmode to prove the specification.\n\n    Prerequisites:\n    We assume the user already knows how to use Iris and the Iris Proofmode,\n    for instance with Heaplang. Learning material for Iris is available\n    at this URL: https://iris-project.org/ *)\n\nFrom iris.proofmode Require Import tactics.\nFrom cap_machine Require Import rules proofmode macros_helpers.\nFrom cap_machine Require Import contiguous.\nOpen Scope Z_scope.\n\n(** The imports correspond to the following:\n    - the Iris tactics and the Iris proofmode\n    - the WP rules of the Cerise program logic\n    - the automated tactics of the Cerise proofmode\n    - some additional tactics for the Cerise proofmode\n\n    We recommand to check the documentation of the proofmode of Cerise:\n    https://github.com/logsem/cerise/blob/main/proofmode.md *)\n\nSection base_program.\n  (** Iris requires the ressources in the context. The resources of our machine\n      are the registers and the memory. Moreover, we need the machine parameters\n      in the context, which abstract the encoding and the decoding function\n      (for instance, to encode the instructions). *)\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n          `{MP: MachineParameters}.\n\n  (** The program is a list of instructions. As the machine has a Von Neumann\n      architecture, the instructions are encoded data. The function\n      `encodeInstrsW` transforms a list of instructions into integers.\n      The encoding does not matter, as we always manipulate the encoded\n      instructions with the decoding function. *)\n\n  (** The program we will study in this file moves a pointer in a buffer and\n      stores a value at this new location. More precisely, we assumes that the\n      register `r1` of the machine contains a capability pointing to a memory\n      buffer of size >= 1. The program derives a capability to the next address,\n      and stores the value of the register `r2` at this address. *)\n\n  Definition prog_instrs : list Word :=\n    encodeInstrsW [\n      Lea r_t1 1 ;    (* load effective address 1 into `r1` *)\n      Store r_t1 r_t2 (* store value from `r2` at address specified by `r1` *)\n    ].\n\n  (** We use the program logic to specify the program. In the program logic,\n      there is 2 types of ressources:\n      - the register /reg/ maps to the word /w/, reg ↦ᵣ w\n      - the address /a/ maps to the word /w/, a ↦ₐ w.\n      The notation [[a1, a2]] ↦ₐ [[lw]] maps the list of words /lw/ to the\n      contiguous fragment of memory between the adresses /a1/ and /a2/.\n\n      To write the specification, we need to have the separation logic\n      assertion that describe all the resources required throughout the\n      execution. In this case, we need the ownership of:\n      - the fragment of the memory with the instructions of the program,\n        stored between the adresses `a_prog` and `a_prog + len(prog)`\n      - the memory buffer on which the program stores the new value,\n        between the addresses `b_mem` and `b_mem + 2`\n      - the PC contains a capability pointing to the first addresse of the\n        program `a_prog`, with all the required permissions\n        (i.e. validity range and executable)\n      - the registers `r1` and `r2`, where `r1` contains the capability to the\n        buffer and `r2` contains the new data (in our case, 42)\n\n      The usual way to specify a program in Cerise in Coq is to use the\n      weakest-precondition (WP) with a Continuation Passing Style, instead of\n      the Hoare Triples.\n      The CPS style is defined as follows:\n\n      {P} e {Q} ≡ ∀ ϕ, (P ∗ ▷(Q -∗ WP e { ϕ })) -∗ WP e { ϕ }\n\n      It is important to notice that, for a such low-level programming language,\n      there is no notion of expression. The semantic only describes how the\n      state of the machine changes at each execution step, as soon as the machine\n      is in a Running state.\n      However, the WP property requires an expression. In this way, an\n      expression in the Cerise program logic encodes only the execution state of\n      the machine (Running, Halted or Failed) (1).\n      Thus, the WP rules only describes how the resources of the machine evolve\n      at each execution step.\n\n\n      (1) For technical purpose, an expression in actually either a (non-atomic)\n          Sequence of instructions, or an (atomic) Instruction. *)\n\n  (** The following lemma `prog_spec_instr` is a specification of the program\n      previously defined.\n\n      The SL assertion for the fragment of code is `codefrag a_prog prog_instr`.\n\n      The PCC (PC Capability) has the permission `pc_p`, which has, at least,\n      the execution permission: `ExecPCPerm p_pc`.\n      The validity range of the PCC, between the addresses `pc_b` and `pc_e`,\n      is larger than the actual range of the code fragment. Indeed, for\n      modular purposes, the program we are specifying may be a part of a larger\n      program. Thus, we need to ensure the fragment of the code is included in\n      the PCC range, i.e. `SubBounds b_pc e_pc a_prog e_prog`.\n\n      Because we work with addresses, which are actually finite integers,\n      we need to assume the addresses are always valid when we do addresses\n      arithmetic operations (for instance, there is no overflow of the memory).\n      In particular, the memory buffer is a contiguous region of memory where\n      all the addresses are in the bounds of the memory.\n\n      For simplicity, we assume the buffer is filled with 0.\n\n      When the whole program is a list of instructions, it is required to\n      manually get some helping facts before reasoning on the instructions,\n      using the tactic `codefrag_facts \"Hprog\"`. This tactic has to be used\n      when the `codefrag` assertion is used. It allows to get some additionnal\n      facts about the memory addresses containing the code. It is a boilerplate.\n\n      To prove the specification, the idea is to manipulate the resources, such\n      that we have all the required assertion that fit with the corresponding\n      WP rule. Once all the resource are ready, the tactic `iInstr \"Hprog\"`\n      steps through one instruction, automatically finds the appropriate rule,\n      and tries to discharge as much goal as possible (e.g. side-condition\n      about the PC). It only remains some side-condition to prove manually,\n      such as address arithmetic.\n      We can use the tactic `solve_addr` to solve automatically the address\n      arithmetic goals. It sometimes requires to transform the goal or\n      hypotheses a bit to work.\n\n      We advice to read carefully the following specification and to try to\n      understand each statement in the lemma.\n      Then, we urge to execute the proof step by step, and to understand\n      each time what happens to the proof state and why we are doing it. *)\n\n  Lemma prog_spec_instr\n    p_pc b_pc e_pc a_prog (* pc *)\n    b_mem (* mem *)\n    φ :\n\n    let e_mem := (b_mem ^+ 2)%a in (* end of memory buffer at b_mem+2 *)\n    let e_prog := (a_prog ^+ length prog_instrs)%a in (* end of program at a_prog + length of instructions *)\n\n    ExecPCPerm p_pc -> (* p_pc has at least the executable permission*)\n    SubBounds b_pc e_pc a_prog e_prog -> (* [b_pc : e_pc) contains [a_prog : e_prog) *)\n    ContiguousRegion b_mem 2 → (* addresses in [b_mem : b_mem+2) are valid *)\n\n    ⊢ ( PC ↦ᵣ WCap p_pc b_pc e_pc a_prog (* PC points to the prog *)\n        ∗ codefrag a_prog prog_instrs (* the prog instruction start at a_prog *)\n        ∗ r_t1 ↦ᵣ WCap RW b_mem e_mem b_mem (* r1 points to the allocated memory *)\n        ∗ [[b_mem, e_mem]] ↦ₐ [[ [WInt 0; WInt 0] ]] (* memory buffer, filled with 0 *)\n        ∗ r_t2 ↦ᵣ WInt 42 (* new value 42 *)\n         ∗ ▷ ( (* everything under the later `▷` and before the wand `-*` is our postcondition *)\n                PC ↦ᵣ WCap p_pc b_pc e_pc e_prog (* PC has reached the end of the program *)\n                ∗ r_t1 ↦ᵣ WCap RW b_mem e_mem (b_mem ^+1)%a (* r1 points to b_mem + 1*)\n                ∗ r_t2 ↦ᵣ WInt 42 (* unchanged *)\n                ∗ codefrag a_prog prog_instrs (* unchanged *)\n                ∗ [[b_mem, e_mem]] ↦ₐ [[ [WInt 0; WInt 42] ]] (* our memory buffer now contains 42 *)\n               -∗ WP Seq (Instr Executable) {{ φ }}))\n       -∗ WP Seq (Instr Executable) {{ φ }}%I.\n  Proof.\n    intros * Hpc_perm Hpc_bounds Hmem_bounds.\n    unfold ContiguousRegion in Hmem_bounds.\n    iIntros \"(HPC& Hprog& Hr1& Hmem& Hr2& Hcont)\".\n\n    (* 1 - prepare the assertions for the proof *)\n    subst e_mem e_prog; simpl. (* replace e_mem and e_prog with their known values *)\n    (* Derives the facts from the codefrag *)\n    codefrag_facts \"Hprog\".\n    simpl in *.\n\n    (* 2 - wp rules for each instructions *)\n    (* Lea *)\n    iInstr \"Hprog\".\n\n    (* Store requires the resource (b_mem ^+ 1), we need to\n       destruct the region_mapsto.\n       This essentially the same as destructing a list into (first element)::(rest of list).\n       We do it twice since we need the second element (b_mem ^+ 1). *)\n    iDestruct (region_mapsto_cons with \"Hmem\") as \"(Hmem0& Hmem1)\".\n    { transitivity (Some (b_mem ^+1)%a) ; auto ; by solve_addr.  }\n    { by solve_addr. }\n    iDestruct (region_mapsto_single with \"Hmem1\") as \"Hmem1\".\n    { transitivity (Some (b_mem ^+(1+1))%a) ; auto ; by solve_addr. }\n    iDestruct \"Hmem1\" as (v) \"(Hmem1& %Hr)\".\n    injection Hr ; intro Hr' ; subst ; clear Hr.\n\n    (* Store *)\n    iInstr \"Hprog\".\n\n    (* 3 - Continuation *)\n    iApply \"Hcont\".\n    iFrame.\n    iApply region_mapsto_cons.\n    { transitivity (Some (b_mem ^+1)%a) ; auto ; by solve_addr.  }\n    { by solve_addr. }\n    iFrame.\n    iApply region_mapsto_cons.\n    { transitivity (Some (b_mem ^+(1+1))%a) ; auto ; by solve_addr.  }\n    { by solve_addr. }\n    iFrame.\n    replace (b_mem ^+ (1 + 1))%a with (b_mem ^+ 2)%a by solve_addr.\n    unfold region_mapsto.\n    rewrite finz_seq_between_empty ; last solve_addr.\n    done.\n  Qed.\n\n\n  (** The tactic `iGo \"Hprog\"` steps through multiple instructions,\n     until a side-condition needs to be prove manually. *)\n\n  (** **** Exercise 1 --- More automation with iGo\n      Prove the specification of the previous example using the automated\n      tactic `iGo`. In order to leverage the strengh of the tactic, the memory\n      resources should be ready before the execution of the tactic, in\n      particular, the memory buffer should be split at the beginning of the\n      proof: it will allows the tactic `iGo` to step through multiple\n      instructions at once.\n\n      Tips: take inspiration on the proof of the previous exercise, but we\n            recommend to try to manipulate the SL resources and the address\n            arithmetic by yourself.\n            Indeed, address arithmetic is a very common side-condition,\n            and the lemmas often require you to manipulate the PL resources\n            in order to make them fit with the hypothesis. *)\n\n  Lemma prog_spec_igo\n    p_pc b_pc e_pc a_prog (* pc *)\n    b_mem (* mem *)\n    φ :\n\n    let e_mem := (b_mem ^+ 2)%a in\n    let e_prog := (a_prog ^+ length prog_instrs)%a in\n\n    ExecPCPerm p_pc ->\n    SubBounds b_pc e_pc a_prog e_prog ->\n    ContiguousRegion b_mem 2 →\n\n    ⊢ ( PC ↦ᵣ WCap p_pc b_pc e_pc a_prog\n        ∗ codefrag a_prog prog_instrs\n        ∗ r_t1 ↦ᵣ WCap RW b_mem e_mem b_mem\n        ∗ [[b_mem, e_mem]] ↦ₐ [[ [WInt 0; WInt 0] ]]\n        ∗ r_t2 ↦ᵣ WInt 42\n         ∗ ▷ ( PC ↦ᵣ WCap p_pc b_pc e_pc e_prog\n                ∗ r_t1 ↦ᵣ WCap RW b_mem e_mem (b_mem ^+1)%a\n                ∗ r_t2 ↦ᵣ WInt 42\n                ∗ codefrag a_prog prog_instrs\n                ∗ [[b_mem, e_mem]] ↦ₐ [[ [WInt 0; WInt 42] ]]\n               -∗ WP Seq (Instr Executable) {{ φ }}))\n       -∗ WP Seq (Instr Executable) {{ φ }}%I.\n  Proof.\n    intros * Hpc_perm Hpc_bounds Hmem_bounds.\n    unfold ContiguousRegion in Hmem_bounds.\n    iIntros \"(HPC& Hprog& Hr1& Hmem& Hr2& Hcont)\".\n    subst e_mem e_prog; simpl.\n\n    (* Derive the facts from the codefrag *)\n    (* FILL IN HERE *)\n\n    (* Prepare the memory resource for the Store *)\n    (* FILL IN HERE *)\n\n    (* 2 - step through multiple instructions *)\n    (* FILL IN HERE *)\n\n    (* 3 - Continuation *)\n    (* FILL IN HERE *)\n    Admitted.\n\n\n  (** The tactics `iInstr` and `iGo` automatically lookup the PC, find the\n      corresponding instruction in the `codefrag` instruction, find the\n      right WP rule to apply accordingly with the instruction, instantiate\n      the lemma and try to prove as much precondition as possible.\n\n      However, in order to get a better understanding of the way to use the\n      WP rules in Cerise, we propose to prove the previous lemma using the\n      fully detailed tactics.\n      It is also useful if the assertion that embeds the code is not the\n      `codefrag` predicate, but for instance, the big conjonction separation\n      `[∗ list]` --- even though it is usually possible to rewrite the one\n      in term of the other. *)\n\n  (** **** Exercise 2 --- Manual detailled proofs\n        For this exercise, we propose to re-do the proof of the previous\n        specification, using the manual WP rules.\n        We explain the different steps for the first instruction `Lea`.\n        Complete the proof.\n   *)\n\n  Lemma prog_spec_detailed\n    p_pc b_pc e_pc (* pc *)\n    a_prog a\n    b_mem (* mem *)\n    φ :\n\n    let e_mem := (b_mem ^+ 2)%a in\n    let e_prog := (a_prog ^+ length prog_instrs)%a in\n\n    ExecPCPerm p_pc ->\n    SubBounds b_pc e_pc a_prog e_prog ->\n    contiguous_between a a_prog (e_prog) →\n    ContiguousRegion b_mem 2 →\n\n    ⊢ ( PC ↦ᵣ WCap p_pc b_pc e_pc a_prog\n        ∗ ([∗ list] a_i;w ∈ a;prog_instrs, a_i ↦ₐ w)%I\n        ∗ r_t1 ↦ᵣ WCap RW b_mem e_mem b_mem\n        ∗ [[b_mem, e_mem]] ↦ₐ [[ [WInt 0; WInt 0] ]]\n        ∗ r_t2 ↦ᵣ WInt 42\n         ∗ ▷ ( PC ↦ᵣ WCap p_pc b_pc e_pc e_prog\n                ∗ r_t1 ↦ᵣ WCap RW b_mem e_mem (b_mem ^+1)%a\n                ∗ r_t2 ↦ᵣ WInt 42\n               ∗ ([∗ list] a_i;w ∈ a;prog_instrs, a_i ↦ₐ w)%I\n                ∗ [[b_mem, e_mem]] ↦ₐ [[ [WInt 0; WInt 42] ]]\n               -∗ WP Seq (Instr Executable) {{ φ }}))\n       -∗ WP Seq (Instr Executable) {{ φ }}%I.\n  Proof.\n    intros * Hpc_perm Hpc_bounds Hprog_addr Hmem_bounds.\n    iIntros \"(HPC& Hprog& Hr1& Hmem& Hr2& Hcont)\".\n    subst e_mem e_prog; simpl in *.\n    (* In order to use the tactic `iCorrectPC` that solves the side-condition\n       about the PC, we need this assertion, equivalent to\n       `Hpc_perm /\\ Hpc_bounds` *)\n    assert (Hpc_correct : isCorrectPC_range p_pc b_pc e_pc a_prog (a_prog ^+ 2)%a).\n    { unfold isCorrectPC_range. intros.\n      apply isCorrectPC_ExecPCPerm_InBounds ; auto ; solve_addr.\n    }\n\n\n    (* 2 - step through instructions *)\n    (* 2.1 - Lea *)\n    (* Prepare the resources\n       Destruct the list of addresses of the code fragment *)\n    iDestruct (big_sepL2_length with \"Hprog\") as %Hlength_prog.\n    destruct_list a.\n    pose proof (contiguous_between_cons_inv_first _ _ _ _ Hprog_addr) as ->.\n    (* Focus to the atomic expression (regarding the operational semantic) *)\n    iDestruct \"Hprog\" as \"[Hi Hprog]\".\n    iApply (wp_bind (fill [SeqCtx])).\n    (* Apply the WP rule corresponding to the instruction\n       and prove the preconditions of the rule *)\n    iApply (wp_lea_success_z with \"[$HPC $Hi $Hr1]\").\n    { apply decode_encode_instrW_inv. }\n    { iCorrectPC a_prog (a_prog ^+ 2)%a. }\n    { iContiguous_next Hprog_addr 0%nat. }\n    { transitivity (Some (b_mem ^+ 1 )%a) ; auto ; solve_addr. }\n    { auto. }\n    (* Introduce the postconditions of the rule and re-focus the expression. *)\n    iNext; iIntros \"(HPC& Hdone& Hr1)\"; iSimpl.\n    iApply wp_pure_step_later;auto;iNext.\n\n    (* 2.2 - Store *)\n    (* Destruct the list of addresses of the code fragment *)\n    pose proof (contiguous_between_last _ _ _ a Hprog_addr eq_refl) as Hlast.\n\n    (* Prepare the memory resource for the Store *)\n    (* FILL IN HERE *)\n\n    (* Focus to the atomic expression (regarding the operational semantic) *)\n    (* FILL IN HERE *)\n\n    (* Apply the WP rule corresponding to the instruction\n       and prove the preconditions of the rule *)\n    (* FILL IN HERE *)\n\n    (* Introduce the postconditions of the rule and re-focus the expression. *)\n    (* FILL IN HERE *)\n\n    (* 3 - Continuation *)\n    (* FILL IN HERE *)\n\n    Admitted.\n\n\n  (** The next step to learn how to use the Cerise Proofmode is to leverage\n      the modularity of program logic to define macros and use their\n      specification inside bigger programs.\n      The next part of the tutorial \"cerise_modularity.v\" will learn you how\n      to define, specify and use user-defined macros, and present you the main\n      macros already defined in Cerise.\n   *)\n\nEnd base_program.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/exercises/cerise_tutorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2422150894771393}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.floyd.library.\nRequire Import VST.progs.list_dt.  Import LsegSpecial.\nRequire Import VST.progs.queue2.\n\nOpen Scope logic.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition t_struct_elem := Tstruct _elem noattr.\nDefinition t_struct_fifo := Tstruct _fifo noattr.\n\nInstance QS: listspec _elem _next (fun sh => malloc_token Ews t_struct_elem).\nProof. eapply mk_listspec; reflexivity. Defined.\n\nLemma isnil: forall {T: Type} (s: list T), {s=nil}+{s<>nil}.\nProof. intros. destruct s; [left|right]; auto. intro Hx; inv Hx. Qed.\n\nLemma field_at_list_cell:\n  forall sh i v p,\n  data_at sh t_struct_elem (i,v) p\n  = list_cell QS sh i p *\n  field_at sh t_struct_elem [StructField _next] v p.\nProof.\nintros.\nunfold_data_at (data_at _ _ _ _).\nf_equal.\nunfold field_at, list_cell.\nautorewrite with gather_prop.\nf_equal.\napply ND_prop_ext.\nrewrite field_compatible_cons; simpl.\nintuition.\nleft; auto.\nQed.\n\nDefinition surely_malloc_spec :=\n  DECLARE _surely_malloc\n   WITH t:type, gv: globals\n   PRE [ tuint ]\n       PROP (0 <= sizeof t <= Int.max_unsigned;\n                complete_legal_cosu_type t = true;\n                natural_aligned natural_alignment t = true)\n       PARAMS (Vint (Int.repr (sizeof t))) GLOBALS (gv)\n       SEP (mem_mgr gv)\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       RETURN (p)\n       SEP (mem_mgr gv; malloc_token Ews t p * data_at_ Ews t p).\n\nDefinition fifo_body (contents: list val) (hd tl : val) :=\n     (if isnil contents\n      then (!!(hd=nullval) && emp)\n      else (EX prefix: list val, EX last: val,\n              !!(contents = prefix++last::nil)\n            &&  (lseg QS Ews prefix hd tl\n                   * malloc_token Ews t_struct_elem tl\n                   * data_at Ews t_struct_elem (last, nullval) tl)))%logic.\n\nDefinition fifo (contents: list val) (p: val) : mpred :=\n  EX ht: (val*val), let (hd,tl) := ht in\n      !! is_pointer_or_null hd && !! is_pointer_or_null tl &&\n      data_at Ews t_struct_fifo (hd, tl) p * malloc_token Ews t_struct_fifo p *\n      fifo_body contents hd tl.\n\nDefinition fifo_new_spec :=\n DECLARE _fifo_new\n  WITH gv: globals\n  PRE  [  ]\n       PROP() PARAMS() GLOBALS (gv) SEP (mem_mgr gv)\n  POST [ (tptr t_struct_fifo) ]\n    EX v:val, PROP() RETURN (v) SEP (mem_mgr gv; fifo nil v).\n\nDefinition fifo_put_spec :=\n DECLARE _fifo_put\n  WITH q: val, contents: list val, p: val, last: val\n  PRE  [ tptr t_struct_fifo , tptr t_struct_elem ]\n          PROP () PARAMS (q; p)\n          SEP (fifo contents q;\n                 malloc_token Ews t_struct_elem p;\n                 data_at Ews t_struct_elem (last,Vundef) p)\n  POST [ tvoid ]\n          PROP() RETURN() SEP (fifo (contents++(last :: nil)) q).\n\nDefinition fifo_empty_spec :=\n DECLARE _fifo_empty\n  WITH q: val, contents: list val\n  PRE  [ tptr t_struct_fifo ]\n     PROP() PARAMS (q) SEP(fifo contents q)\n  POST [ tint ]\n      PROP ()\n      RETURN (if isnil contents then Vtrue else Vfalse)\n      SEP (fifo (contents) q).\n\nDefinition fifo_get_spec :=\n DECLARE _fifo_get\n  WITH q: val, contents: list val, first: val\n  PRE  [ tptr t_struct_fifo ]\n       PROP() PARAMS(q) SEP (fifo (first :: contents) q)\n  POST [ (tptr t_struct_elem) ]\n      EX p:val,\n       PROP ()\n       RETURN (p)\n       SEP (fifo contents q;\n              malloc_token Ews t_struct_elem p;\n              data_at Ews t_struct_elem (first,Vundef) p).\n\nDefinition make_elem_spec :=\n DECLARE _make_elem\n  WITH i: int, gv: globals\n  PRE  [ tint ]\n        PROP() PARAMS (Vint i) GLOBALS (gv) SEP(mem_mgr gv)\n  POST [ (tptr t_struct_elem) ]\n    EX p:val,\n       PROP()\n       RETURN (p)\n       SEP (mem_mgr gv; \n              malloc_token Ews t_struct_elem p;\n              data_at Ews t_struct_elem (Vint i, Vundef) p).\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv: globals\n  PRE  [] main_pre prog tt gv\n  POST [ tint ]\n       PROP() RETURN (Vint (Int.repr 1)) SEP(TT).\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog\n    [surely_malloc_spec; fifo_new_spec; fifo_put_spec;\n     fifo_empty_spec; fifo_get_spec; make_elem_spec;\n     main_spec]).\n\nLemma body_surely_malloc: semax_body Vprog Gprog f_surely_malloc surely_malloc_spec.\nProof.\n  start_function.\n  forward_call (* p = malloc(n); *)\n     (t,gv).\n  Intros p.\n  forward_if\n  (PROP ( )\n   LOCAL (temp _p p)\n   SEP (mem_mgr gv; malloc_token Ews t p * data_at_ Ews t p)).\n*\n  if_tac.\n    subst p. entailer!.\n    entailer!.\n*\n    forward_call 1.\n    contradiction.\n*\n    if_tac.\n    + forward. subst p. congruence.\n    + Intros. forward. entailer!.\n*\n  forward. Exists p; entailer!.\nQed.\n\nLemma fifo_isptr: forall al q, fifo al q |-- !! isptr q.\nProof.\nintros.\n unfold fifo, fifo_body.\n Intros ht; destruct ht; Intros.\n if_tac.  entailer!.  Intros prefix; entailer!.\nQed.\n\n#[export] Hint Resolve fifo_isptr : saturate_local.\n\nLemma body_fifo_empty: semax_body Vprog Gprog f_fifo_empty fifo_empty_spec.\nProof.\nstart_function.\nunfold fifo.\nIntros ht; destruct ht as [hd tl].\nIntros.\nforward. (* h = Q->head; *)\nforward. (* return (h == NULL); *)\n{\nunfold fifo, fifo_body.\ndestruct (isnil contents).\n+ Intros. subst. auto with valid_pointer.\n+ entailer!.\n  destruct hd; inv PNhd; entailer!.\n}\nunfold fifo, fifo_body.\nExists (hd,tl).\ndestruct (isnil contents).\n* entailer!.\n* Intros prefix last.\nExists prefix last.\n  assert_PROP (isptr hd).\n    destruct prefix.\n    rewrite @lseg_nil_eq; entailer!.\n    rewrite @lseg_cons_eq by auto. Intros y.\n    entailer!.\n destruct hd; try contradiction.\n entailer!.\nQed.\n\nLemma body_fifo_new: semax_body Vprog Gprog f_fifo_new fifo_new_spec.\nProof.\n  start_function.\n\n  forward_call (* Q = surely_malloc(sizeof ( *Q)); *)\n     (t_struct_fifo, gv).\n  Intros q.\n  assert_PROP (field_compatible t_struct_fifo [] q).\n   entailer!.\n  forward. (* Q->head = NULL; *)\n  forward. (* Q->tail = NULL; *)\n  forward. (* return Q; *)\n  Exists q. unfold fifo, fifo_body. Exists (nullval,nullval).\n  rewrite if_true by auto.\n  simpl sizeof.\n  entailer!.\nQed.\n\nLemma body_fifo_put: semax_body Vprog Gprog f_fifo_put fifo_put_spec.\nProof.\nstart_function.\nunfold fifo at 1.\nIntros ht; destruct ht as [hd tl].\nIntros.\nforward. (* p->next = NULL; *)\nforward. (*   h = Q->head; *)\nforward_if\n  (PROP() LOCAL () SEP (fifo (contents ++ last :: nil) q))%assert.\n* unfold fifo_body; if_tac. entailer!. Intros prefix last0; entailer!.\n* (* then clause *)\n  subst.\n  forward. (* Q->head=p; *)\n  forward. (* Q->tail=p; *)\n  entailer!.\n  unfold fifo, fifo_body.\n  destruct (isnil contents).\n  + subst. Exists (p,p).\n     simpl. rewrite if_false by congruence.\n     Exists (@nil val) last.\n      rewrite @lseg_nil_eq by auto.\n      entailer!.\n   + Intros prefix last0.\n      destruct prefix;\n      entailer!.\n      rewrite @lseg_cons_eq by auto. simpl.\n      Intros y.\n      entailer!.\n* (* else clause *)\n  forward. (*  t = Q->tail; *)\n  unfold fifo_body.\n  destruct (isnil contents).\n  + Intros. contradiction H; auto.\n  + Intros prefix last0.\n     forward. (*  t->next=p; *)\n     forward. (* Q->tail=p; *)\n     entailer!.\n     unfold fifo, fifo_body. Exists (hd, p).\n     rewrite if_false by (clear; destruct prefix; simpl; congruence).\n     Exists  (prefix ++ last0 :: nil) last.\n     entailer.   (* not entailer!, which would cancel *)\n     rewrite (field_at_list_cell Ews last0 p).\n     unfold_data_at (@data_at CompSpecs Ews t_struct_elem (last,nullval) p).\n     unfold_data_at (data_at _ _ _ p).\n     simpl sizeof.\n     match goal with\n     | |- _ |-- _ * _ * (_ * ?AA) => remember AA as A\n     end.     (* prevent it from canceling! *)\n     cancel. subst A.\n     eapply derives_trans;\n        [ | apply (lseg_cons_right_neq QS Ews prefix hd last0 tl nullval p ); auto].\n     simpl sizeof.  cancel.\nQed.\n\nLemma body_fifo_get: semax_body Vprog Gprog f_fifo_get fifo_get_spec.\nProof.\nstart_function.\nunfold fifo at 1, fifo_body.\nIntros ht; destruct ht as [hd tl].\nrewrite if_false by congruence.\nIntros prefix last.\nforward.  (*   h = Q->head; *)\ndestruct prefix; inversion H; clear H.\n+\n   rewrite @lseg_nil_eq by auto.\n   Intros.\n   subst_any.\n   forward. (*  n=h->next; *)\n   forward. (* Q->head=n; *)\n   forward. (* return p; *)\n   unfold fifo, fifo_body. Exists tl (nullval, tl).\n   rewrite if_true by congruence.\n   entailer!. simpl sizeof.\n   do 2 unfold_data_at (data_at _ _ _ _). cancel.\n+ rewrite @lseg_cons_eq by auto.\n    Intros x.\n    simpl @valinject. (* can we make this automatic? *)\n    subst_any.\n    forward. (*  n=h->next; *)\n    forward. (* Q->head=n; *)\n    forward. (* return p; *)\n    Exists hd. unfold fifo, fifo_body. Exists (x, tl).\n    rewrite if_false by (destruct prefix; simpl; congruence).\n    Exists prefix last.\n    entailer!.\n    rewrite field_at_list_cell. simpl sizeof. cancel.\nQed.\n\nLemma body_make_elem: semax_body Vprog Gprog f_make_elem make_elem_spec.\nProof.\nstart_function.\nforward_call (*  p = surely_malloc(sizeof ( *p));  *)\n    (t_struct_elem, gv).\nIntros p.\nforward.  (*  p->data=i; *)\nsimpl.\nforward. (* return p; *)\nExists p.\nentailer!.\nQed.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nsep_apply (create_mem_mgr gv).\nforward_call (* Q = fifo_new(); *)  gv.\nIntros q.\n\nforward_call  (*  p = make_elem(1); *)\n     (Int.repr 1, gv).\nIntros p'.\nforward_call (* fifo_put(Q,p);*)\n    ((q, @nil val),p', Vint (Int.repr 1)).\n\nforward_call  (*  p = make_elem(2); *)\n     (Int.repr 2, gv).\nIntros p2.\nsimpl app.\n forward_call  (* fifo_put(Q,p); *)\n    (((q,[Vint (Int.repr 1)]),p2), Vint (Int.repr 2)).\nsimpl app.\nforward_call  (*   p' = fifo_get(Q); p = p'; *)\n    ((q,[Vint (Int.repr 2)]), Vint (Int.repr 1)).\nIntros p3.\nforward. (*   i = p->data;  *)\nforward_call (*  free(p); *)\n   (t_struct_elem, p3, gv).\nassert_PROP (isptr p3); [entailer! | rewrite if_false by (intro; subst; contradiction) ]; cancel.\nforward. (* return i; *)\nQed.\n\nExisting Instance NullExtension.Espec.\n\nLemma prog_correct:\n  semax_prog prog tt Vprog Gprog.\nProof.\n  prove_semax_prog.\n  semax_func_cons body_malloc. apply semax_func_cons_malloc_aux.\n  semax_func_cons body_free.\n  semax_func_cons body_exit.\n  semax_func_cons body_surely_malloc.\n  semax_func_cons body_fifo_new.\n  semax_func_cons body_fifo_put.\n  semax_func_cons body_fifo_empty.\n  semax_func_cons body_fifo_get.\n  semax_func_cons body_make_elem.\n  semax_func_cons body_main.\nQed.\n\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/progs/verif_queue2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.24221508947713924}}
{"text": "Require Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.SmartMap.\nRequire Import Crypto.Compilers.Named.Syntax.\n\nModule Export Named.\n  Section language.\n    Context {base_type_code : Type}\n            {interp_base_type : base_type_code -> Type}\n            {op : flat_type base_type_code -> flat_type base_type_code -> Type}\n            {Name : Type}.\n\n    (** [SmartVar] is like [Var], except that it inserts\n          pair-projections and [Pair] as necessary to handle\n          [flat_type], and not just [base_type_code] *)\n    Definition SmartVar {t} : interp_flat_type (fun _ => Name) t -> @exprf base_type_code op Name t\n      := smart_interp_flat_map (f:=fun _ => Name) (g:=@exprf _ _ _) (fun t => Var) TT (fun A B x y => Pair x y).\n  End language.\nEnd Named.\n\nGlobal Arguments SmartVar {_ _ _ _} _.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Compilers/Named/SmartMap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2422150828213735}}
{"text": "Require Import CSet Le ListUpdateAt Coq.Classes.RelationClasses.\n\nRequire Import Plus Util AllInRel Map Terminating ContextMap.\nRequire Import Val Var Envs IL Annotation AnnotationLattice.\nRequire Import Infra.Lattice DecSolve LengthEq MoreList Status AllInRel OptionR.\nRequire Import Keep Subterm Analysis.\nRequire Import FiniteFixpointIteration.\n\nSet Implicit Arguments.\n\nDefinition forwardF (sT:stmt) (Dom:stmt->Type) `{JoinSemiLattice (Dom sT)}\n           (forward: forall s (ST:subTerm s sT),\n               ctxmap (Dom sT) -> ann (Dom sT) -> ann (Dom sT) * ctxmap (Dom sT))\n           (F:list (params * stmt))\n           (ST:forall n s, get F n s -> subTerm (snd s) sT)\n           (AL:ctxmap (Dom sT)) (anF:list (ann (Dom sT)))\n  : list (ann (Dom sT)) * ctxmap (Dom sT).\n  revert AL F anF ST.\n  fix g 2. intros.\n  destruct F as [|Zs F'].\n  - eapply (nil, AL).\n  - destruct anF as [|a anF'].\n    + eapply (nil, AL).\n    + pose proof (forward (snd Zs) (ST 0 Zs ltac:(eauto using get)) AL a).\n      pose proof (g (snd X) F' anF' ltac:(eauto using get)).\n      eapply (fst X :: fst X0, snd X0).\nDefined.\n\nArguments forwardF [sT] [Dom] {H} {H0} forward F ST AL anF.\n\nFixpoint forwardF_length (sT:stmt) (Dom:stmt->Type) `{JoinSemiLattice (Dom sT)} forward         (F:list (params * stmt))\n         (ST:forall n s, get F n s -> subTerm (snd s) sT)\n         AL (anF:list (ann (Dom sT)))\n         {struct F}\n  : length (fst (forwardF forward F ST AL anF)) = min (length F) (length anF).\nProof.\n  destruct F as [|Zs F'], anF; simpl; eauto.\nQed.\n\nSmpl Add\n     match goal with\n     | [ |- context [ ❬fst (@forwardF ?sT ?Dom ?H ?JSL ?f ?F ?ST ?AL ?anF)❭ ] ] =>\n       rewrite (@forwardF_length sT Dom H JSL f F ST AL anF)\n     | [ H : context [ ❬fst (@forwardF ?sT ?Dom ?H ?JSL ?f ?F ?ST ?AL ?anF)❭ ] |- _ ] =>\n       rewrite (@forwardF_length sT Dom H JSL f F ST AL anF) in H\n     end : len.\n\nLemma forwardF_length_ass (sT:stmt) (Dom:stmt->Type) `{JoinSemiLattice (Dom sT)}\n      forward AL F anF ST k\n  : length F = k\n    -> length F = length anF\n    -> length (fst (forwardF forward F ST AL anF)) = k.\nProof.\n  intros. rewrite forwardF_length, <- H2.\n  repeat rewrite Nat.min_idempotent; eauto.\nQed.\n\nHint Resolve @forwardF_length_ass : len.\n\n\n\nFixpoint forward (sT:stmt) (Dom: stmt -> Type)\n         `{JoinSemiLattice (Dom sT)}\n         `{@LowerBounded (Dom sT) H}\n           (ftransform :\n              forall sT, ctxmap params ->\n                    forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n           (ZL:ctxmap params)\n           (st:stmt) (ST:subTerm st sT)\n           (AL:ctxmap (Dom sT)) (a:ann (Dom sT)) {struct st}\n  :  ann (Dom sT) * ctxmap (Dom sT)\n  := match st as st', a return st = st' -> ann (Dom sT) * ctxmap (Dom sT) with\n    | stmtLet x e s as st, ann1 d ans =>\n      fun EQ =>\n        let d' := getAnni d (ftransform sT ZL st ST d) in\n        let (ans', AL) := forward Dom ftransform ZL (subTerm_EQ_Let EQ ST)\n                                 AL (setTopAnn ans d') in\n        (ann1 d ans', AL)\n\n    | stmtIf x s t, ann2 d ans ant =>\n      fun EQ =>\n        let an := ftransform sT ZL st ST d in\n        let d1 := (getAnniLeft d an) in\n        let d2 := (getAnniRight d an) in\n        let (ans', AL') := forward Dom ftransform ZL (subTerm_EQ_If1 EQ ST)\n                                  AL (setTopAnn ans d1) in\n        let (ant', AL'') := forward Dom ftransform ZL (subTerm_EQ_If2 EQ ST)\n                                   AL' (setTopAnn ant d2) in\n        (ann2 d ans' ant', AL'')\n\n    | stmtApp f Y as st, ann0 d as an =>\n      fun EQ =>\n        let an := ftransform sT ZL st ST d in\n        (ann0 d, ctxmap_join_at AL (counted f) (getAnni d an))\n\n    | stmtReturn x as st, ann0 d as an =>\n      fun EQ => (ann0 d, AL)\n\n    | stmtFun F t as st, annF d anF ant =>\n      fun EQ =>\n        let ZL' := ctxmap_app (List.map fst F) ZL in\n        let AL' := ctxmap_extend AL (length F) in\n        let (ant', ALt) := forward Dom ftransform ZL' (subTerm_EQ_Fun1 EQ ST)\n                                  AL' (setTopAnn ant d) in\n        let (anF', AL'') := forwardF (forward Dom ftransform ZL') F (subTerm_EQ_Fun2 EQ ST)\n                                    ALt anF in\n        (annF d (MoreList.mapi (fun i a => setTopAnn a (ctxmap_at_def AL'' i)) anF') ant',\n         ctxmap_drop ❬F❭ AL'')\n    | _, an => fun EQ => (an, AL)\n  end eq_refl.\n\n(*\nLemma get_forwardF  (sT:stmt) (Dom:stmt->Type) `{JoinSemiLattice (Dom sT)}\n           (forward: forall s (ST:subTerm s sT) (a:ann (Dom sT)),\n                       ann (Dom sT) * list (Dom sT))\n           (F:list (params * stmt)) (anF:list (ann (Dom sT)))\n           (ST:forall n s, get F n s -> subTerm (snd s) sT) n Zs a\n  :get F n Zs\n   -> get anF n a\n   -> { ST' | get (forwardF forward F anF ST) n (forward (snd Zs) ST' a) }.\nProof.\n  intros GetF GetAnF.\n  eapply get_getT in GetF.\n  eapply get_getT in GetAnF.\n  general induction GetAnF; destruct Zs as [Z s]; inv GetF; simpl.\n  - eexists; econstructor.\n  - edestruct IHGetAnF; eauto using get.\nQed.\n\n\nLtac inv_get_step_analysis_forward :=\n  match goal with\n  | [ H: get (@forwardF ?sT ?Dom ?PO ?BSL ?f ?F ?anF ?ST) ?n ?x |- _ ]\n    => eapply (@forwardF_get sT Dom PO BSL f F anF ST x n) in H;\n      destruct H as [? [? [? [? [? ]]]]]\n  end.\n\nSmpl Add inv_get_step_analysis_forward : inv_get.\n *)\n\n\nLemma forwardF_monotone' (sT:stmt) (Dom : stmt -> Type)\n      `{JoinSemiLattice (Dom sT)}\n      (forward: forall s (ST:subTerm s sT),\n          ctxmap (Dom sT) -> ann (Dom sT) -> ann (Dom sT) * ctxmap (Dom sT))\n      F\n      (forward_mon: forall AL AL', poLe AL AL' -> forall n Zs, get F n Zs -> forall (ST:subTerm (snd Zs) sT),\n          forall (a b : ann (Dom sT)), a ⊑ b ->\n                                  forward _ ST AL a ⊑ forward _ ST AL' b)\n  : forall AL AL', poLe AL AL' -> forall ST,\n    forall anF bnF, anF ⊑ bnF ->\n               forwardF forward F ST AL anF ⊑ forwardF forward F ST AL' bnF.\nProof.\n  intros. general induction H2; destruct F; simpl; eauto 20 using get.\nQed.\n\nLemma snd_forwardF_exp' (sT:stmt) (Dom : stmt -> Type)\n      `{JoinSemiLattice (Dom sT)}\n      (forward: forall s (ST:subTerm s sT),\n          ctxmap (Dom sT) -> ann (Dom sT) -> ann (Dom sT) * ctxmap (Dom sT))\n      F\n      (forward_exp: forall AL AL' n Zs, get F n Zs -> forall (ST:subTerm (snd Zs) sT),\n          forall (a : ann (Dom sT)), AL ⊑ AL' -> AL ⊑ snd (forward _ ST AL' a))\n  : forall AL AL' ST anF, AL ⊑ AL' -> AL ⊑ snd (forwardF forward F ST AL' anF).\nProof.\n  intros. general induction anF; destruct F; simpl; eauto using get.\nQed.\n\nLemma forwardF_ext' (sT:stmt) (Dom : stmt -> Type)\n      `{JoinSemiLattice (Dom sT)}\n      (forward: forall s (ST:subTerm s sT),\n          ctxmap (Dom sT) -> ann (Dom sT) -> ann (Dom sT) * ctxmap (Dom sT))\n      F\n      (forward_mon: forall AL AL', AL ≣ AL' -> forall n Zs, get F n Zs -> forall (ST:subTerm (snd Zs) sT),\n              forall (a b : ann (Dom sT)), a ≣ b ->\n                                      forward _ ST AL a ≣ forward _ ST AL' b)\n  : forall AL AL', AL ≣ AL' -> forall ST,\n    forall anF bnF, anF ≣ bnF ->\n               forwardF forward F ST AL anF ≣ forwardF forward F ST AL' bnF.\nProof.\n  intros. general induction H2; destruct F; simpl; eauto 20 using get.\nQed.\n\n(*\nLemma forward_length_ass\n      (sT:stmt) (Dom : stmt -> Type) `{JoinSemiLattice (Dom sT)} `{@LowerBounded (Dom sT) H}\n      (f: forall sT, list params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n  : forall (s : stmt) (ST:subTerm s sT) (ZL:list params) k,\n    forall (a : ann (Dom sT)), ❬ZL❭ = k -> ❬snd (forward Dom f ZL ST a)❭ = k.\nProof.\n  intros. rewrite forward_length; eauto.\nQed.\n\nLemma forward_length_le_ass\n      (sT:stmt) (Dom : stmt -> Type)\n      `{JoinSemiLattice (Dom sT)} `{@LowerBounded (Dom sT) H}\n      (f: forall sT, list params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n  : forall (s : stmt) (ST:subTerm s sT) (ZL:list params) k,\n    forall (a : ann (Dom sT)), ❬ZL❭ <= k -> ❬snd (forward Dom f ZL ST a)❭ <= k.\nProof.\n  intros. rewrite forward_length; eauto.\nQed.\n\nLemma forward_length_le_ass_right\n      (sT:stmt) (Dom : stmt -> Type)\n      `{JoinSemiLattice (Dom sT)} `{@LowerBounded (Dom sT) H}\n      (f: forall sT, list params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n  : forall (s : stmt) (ST:subTerm s sT) (ZL:list params) k,\n    forall (a : ann (Dom sT)), k <= ❬ZL❭ -> k <= ❬snd (forward Dom f ZL ST a)❭.\nProof.\n  intros. rewrite forward_length; eauto.\nQed.\n\n\nHint Resolve @forward_length_ass forward_length_le_ass forward_length_le_ass_right : len.\n *)\n\nLemma forwardF_ann  (sT:stmt) (Dom:stmt->Type) `{JoinSemiLattice (Dom sT)}\n      (forward: forall s (ST:subTerm s sT),\n          ctxmap (Dom sT) -> ann (Dom sT) -> ann (Dom sT) * ctxmap (Dom sT))\n           (F:list (params * stmt)) (anF:list (ann (Dom sT))) AL\n           (ST:forall n s, get F n s -> subTerm (snd s) sT) aa n\n           (GetBW:get (fst (forwardF forward F ST AL anF)) n aa) Zs\n           (Get: get F n Zs)\n           (IH: forall AL Zs ST  a, get F n Zs -> get anF n a ->\n                             annotation (snd Zs) (fst (forward (snd Zs) ST AL a)))\n      : annotation (snd Zs) aa.\nProof.\n  eapply get_getT in GetBW.\n  general induction anF; destruct F as [|[Z s] F']; inv GetBW.\n  - inv_get. simpl. exploit IH; eauto using get.\n  - eapply IHanF; eauto using get.\nQed.\n\nLemma forward_annotation sT (Dom:stmt->Type)\n      `{JoinSemiLattice (Dom sT)} s `{@LowerBounded (Dom sT) H}\n      (f: forall sT, ctxmap params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n  : forall AL ZL a (ST:subTerm s sT), annotation s a\n               -> annotation s (fst (forward Dom f ZL ST AL a)).\nProof.\n  induction s using stmt_ind'; intros AL ZL a ST Ann; inv Ann; simpl;\n    repeat let_pair_case_eq; subst; eauto 20 using @annotation, setTopAnn_annotation.\n  - econstructor; eauto using setTopAnn_annotation.\n    + len_simpl; eauto.\n    + intros. inv_get.\n      eapply forwardF_ann in H3; eauto.\n      * eauto using setTopAnn_annotation, setAnn_annotation.\nQed.\n\nLemma forward_getAnn' (sT:stmt) (Dom : stmt -> Type)\n      `{JoinSemiLattice (Dom sT)} `{@LowerBounded (Dom sT) H}\n      (f: forall sT, ctxmap params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT)) s (ST:subTerm s sT) ZL AL an\n  : getAnn (fst (@forward sT Dom _ _ _ f ZL s ST AL an)) = getAnn an.\nProof.\n  intros. destruct s, an; simpl in *; eauto;\n  repeat let_pair_case_eq; simpl; eauto.\nQed.\n\n(*\nLemma forward_getAnn (sT:stmt) (Dom : stmt -> Type)\n      `{JoinSemiLattice (Dom sT)} `{@LowerBounded (Dom sT) H}\n      (f: forall sT, list params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT)) s (ST:subTerm s sT) ZL a an\n  : ann_R eq (fst (@forward sT Dom _ _ _ f ZL s ST an)) an\n    -> getAnn an = a.\nProof.\n  intros. eapply ann_R_get in H2.\n  rewrite forward_getAnn' in H2. eauto.\nQed.\n *)\n\n(*\nLtac simpl_forward_setTopAnn :=\n  repeat match goal with\n         | [H : poEq (fst (forward ?reachability_transform ?ZL\n                                       ?s ?ST ?a ?sa)) ?sa |- _ ] =>\n           let X := fresh \"H\" in\n           match goal with\n           | [ H' : getAnn sa = a |- _ ] => fail 1\n           | _ => exploit (forward_getAnn _ _ _ _ _ H) as X\n           end\n         end; subst; try eassumption.\n\nSmpl Add 130\n    match goal with\n    | [H : poEq (fst (forward ?reachability_transform ?ZL\n                              ?s ?ST ?a ?sa)) ?sa |- _ ] =>\n      let X := fresh \"H\" in\n      match goal with\n      | [ H' : getAnn sa = a |- _ ] => fail 1\n      | _ =>\n        first [ unify a (getAnn sa); fail 1\n              | exploit (forward_getAnn _ _ _ _ _ H) as X; subst ]\n      end\n    end : inv_trivial.\n *)\n\n\nLtac fold_po :=\n  repeat match goal with\n         | [ H : context [ @ann_R ?A ?A (@poLe ?A ?I) ] |- _ ] =>\n           change (@ann_R A A (@poLe A I)) with (@poLe (@ann A) _) in H\n         | [ H : context [ PIR2 poLe ?x ?y ] |- _ ] =>\n           change (PIR2 poLe x y) with (poLe x y) in H\n         | [ |- context [ ann_R poLe ?x ?y ] ] =>\n           change (ann_R poLe x y) with (poLe x y)\n  end.\n\nLtac PI_simpl :=\n  match goal with\n    [ H : subTerm ?s ?t, H' : subTerm ?s ?t |- _ ]\n    => assert (H = H') by eapply subTerm_PI; try subst H'; try subst H\n  end.\n\n\nLemma poLe_mapi D `{PartialOrder D} D' `{PartialOrder D'} (f g:nat -> D -> D') (L L':list D)\n      (LEf:forall i a b, poLe a b -> poLe (f i a) (g i b))\n      (LE: poLe L L') n\n  : poLe (mapi_impl f n L) (mapi_impl g n L').\nProof.\n  general induction LE; simpl; eauto.\nQed.\n\nLemma poEq_mapi D `{PartialOrder D} D' `{PartialOrder D'} (f g:nat -> D -> D') (L L':list D)\n      (LEf:forall i a b, poEq a b -> poEq (f i a) (g i b))\n      (LE: poEq L L') n\n  : poEq (mapi_impl f n L) (mapi_impl g n L').\nProof.\n  general induction LE; simpl; eauto.\nQed.\n\nLemma forward_monotone (sT:stmt) (Dom : stmt -> Type)\n      `{JoinSemiLattice (Dom sT)} `{@LowerBounded (Dom sT) H}\n      (f: forall sT, ctxmap params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n      (fMon:forall s (ST:subTerm s sT) ZL,\n          forall a b, a ⊑ b -> f sT ZL s ST a ⊑ f sT ZL s ST b)\n  : forall (s : stmt) (ST:subTerm s sT) ZL,\n    forall AL AL', poLe AL AL' ->\n        forall (a b : ann (Dom sT)), a ⊑ b ->\n                                forward Dom f ZL ST AL a ⊑ forward Dom f ZL ST AL' b.\nProof with eauto using poLe_setTopAnn, poLe_getAnni.\n  intros s.\n  induction s using stmt_ind'; intros ST ZL AL AL' ALLE a b LE; simpl forward; inv LE;\n    simpl forward; repeat let_pair_case_eq; subst; eauto.\n  - eauto 100.\n  - eauto 100.\n  - clear_trivial_eqs. eapply PIR2_get in H5; eauto.\n    eapply poLe_struct; eauto.\n    + eapply annF_poLe; eauto.\n      * eapply poLe_mapi; eauto 20 using forwardF_monotone'.\n    + eapply ctxmap_drop_poLe.\n      eapply forwardF_monotone'; eauto.\nQed.\n\n\nLemma forward_exp (sT:stmt) (Dom : stmt -> Type)\n      `{JoinSemiLattice (Dom sT)} `{@LowerBounded (Dom sT) H}\n      (f: forall sT, ctxmap params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n  : forall (s : stmt) (ST:subTerm s sT) ZL,\n    forall AL AL', poLe AL AL' ->\n        forall a, AL ⊑ snd (forward Dom f ZL ST AL' a).\nProof with eauto using poLe_setTopAnn, poLe_getAnni.\n  intros s.\n  induction s using stmt_ind'; intros ST ZL AL AL' ALLE a; destruct a; simpl forward;\n    simpl forward; repeat let_pair_case_eq; subst; eauto.\n  - simpl. rewrite <- ctxmap_join_at_exp; eauto.\n  - simpl. etransitivity; eauto.\n    rewrite <- ctxmap_drop_eta at 1.\n    eapply ctxmap_drop_poLe.\n    eapply snd_forwardF_exp'; eauto.\nQed.\n\nLemma snd_forwardF_exp (sT:stmt) (Dom : stmt -> Type)\n      `{JoinSemiLattice (Dom sT)} `{@LowerBounded (Dom sT) H}\n      f ZL F\n  : forall AL ST anF, AL ⊑ snd (forwardF (@forward sT Dom _ _ _ f ZL) F ST AL anF).\nProof.\n  intros. eapply snd_forwardF_exp'; eauto.\n  intros. eapply forward_exp; eauto.\nQed.\n\nHint Resolve ann_R_setTopAnn_poEq.\n\nLemma forwardF_monotone (sT:stmt) (Dom : stmt -> Type)\n      `{PartialOrder (Dom sT)}\n      `{@JoinSemiLattice (Dom sT) H} `{@LowerBounded (Dom sT) H}\n      (f: forall sT, ctxmap params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n      (fMon:forall s (ST:subTerm s sT) ZL,\n          forall a b, a ⊑ b -> f sT ZL s ST a ⊑ f sT ZL s ST b)\n      F\n  : forall AL AL', poLe AL AL' -> forall ST ZL,\n    forall anF bnF, anF ⊑ bnF ->\n               forwardF (@forward sT Dom _ _ _ f ZL) F ST AL anF\n                        ⊑ forwardF (@forward sT Dom _ _ _ f ZL) F ST AL' bnF.\nProof.\n  intros.\n  general induction H3; destruct F; simpl; eauto 20 using get, forward_monotone.\nQed.\n\nLemma forward_ext (sT:stmt) (Dom : stmt -> Type)\n      `{JoinSemiLattice (Dom sT)} `{@LowerBounded (Dom sT) H}\n      (f: forall sT, ctxmap params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n      (fMon:forall s (ST:subTerm s sT) ZL,\n          forall a b, a ≣ b -> f sT ZL s ST a ≣ f sT ZL s ST b)\n  : forall (s : stmt) (ST:subTerm s sT) ZL,\n    forall AL AL', poEq AL AL' ->\n    forall (a b : ann (Dom sT)), a ≣ b ->\n                            forward Dom f ZL ST AL a ≣ forward Dom f ZL ST AL' b.\nProof with eauto using poLe_setTopAnn, poLe_getAnni.\n  intros s.\n  induction s using stmt_ind'; intros ST ZL AL AL' ALLE a b LE; simpl forward; inv LE;\n    simpl forward; repeat let_pair_case_eq; subst; eauto.\n  - eauto 100.\n  - eauto 100.\n  - clear_trivial_eqs. eapply PIR2_get in H5; eauto.\n    eapply poEq_struct; eauto.\n    + eapply annF_poEq; eauto.\n      * eapply poEq_mapi; eauto 20 using forwardF_ext'.\n    + eapply ctxmap_drop_poEq.\n      eapply forwardF_ext'; eauto.\nQed.\n\nLemma forwardF_ext (sT:stmt) (Dom : stmt -> Type) `{H:PartialOrder (Dom sT)}\n      `{@JoinSemiLattice (Dom sT) H} `{@LowerBounded (Dom sT) H}\n      (f: forall sT, ctxmap params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n      (fMon:forall s (ST:subTerm s sT) ZL,\n          forall a b, a ≣ b -> f sT ZL s ST a ≣ f sT ZL s ST b)\n      F\n  : forall ZL AL AL', AL ≣ AL' -> forall ST,\n      forall anF bnF, anF ≣ bnF ->\n                 forwardF (@forward sT Dom H _ _ f ZL) F ST AL anF\n                          ≣ forwardF (@forward sT Dom _ _ _ f ZL) F ST AL' bnF.\nProof.\n  intros. eapply forwardF_ext'; eauto.\n  intros. eapply forward_ext; eauto.\nQed.\n\nInstance forwardF_proper (sT:stmt) (Dom : stmt -> Type) `{H:PartialOrder (Dom sT)}\n      `{@JoinSemiLattice (Dom sT) H} `{@LowerBounded (Dom sT) H}\n      (f: forall sT, ctxmap params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n      (fMon:forall s (ST:subTerm s sT) ZL,\n          forall a b, a ≣ b -> f sT ZL s ST a ≣ f sT ZL s ST b) ZL F ST\n  : Proper (poEq ==> poEq ==> poEq)\n           (forwardF (@forward sT Dom H _ _ f ZL) F ST).\nProof.\n  unfold Proper, respectful.\n  intros. eapply forwardF_ext; eauto.\nQed.\n\nInstance forwardF_proper' (sT:stmt) (Dom : stmt -> Type) `{H:PartialOrder (Dom sT)}\n      `{@JoinSemiLattice (Dom sT) H} `{@LowerBounded (Dom sT) H}\n      (f: forall sT, ctxmap params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n      (fMon:forall s (ST:subTerm s sT) ZL,\n          forall a b, a ⊑ b -> f sT ZL s ST a ⊑ f sT ZL s ST b) ZL F ST\n  : Proper (poLe ==> poLe ==> poLe)\n           (forwardF (@forward sT Dom H _ _ f ZL) F ST).\nProof.\n  unfold Proper, respectful.\n  intros. eapply forwardF_monotone; eauto.\nQed.\n\n\nLemma forward_length (sT:stmt) (Dom : stmt -> Type) `{JoinSemiLattice (Dom sT)}\n      `{@LowerBounded (Dom sT) H}\n      (f: forall sT, ctxmap params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n  : forall (s : stmt) (ST:subTerm s sT) ZL AL\n    (a : ann (Dom sT)), ctxmap_len (snd (forward Dom f ZL ST AL a)) = ctxmap_len AL.\nProof.\n  induction s using stmt_ind'; destruct a; simpl; eauto with len;\n    repeat let_pair_case_eq; subst; simpl in *; eauto.\n  - setoid_rewrite IHs2.\n    setoid_rewrite IHs1. reflexivity.\n  - rewrite <- snd_forwardF_exp'; eauto; try reflexivity.\n    rewrite IHs.\n    + len_simpl. omega.\n    + intros. eapply forward_exp; eauto.\nQed.\n\nSmpl Add\n     match goal with\n     | [ |- context [ ctxmap_len (snd (@forward ?sT ?Dom ?H ?JSL ?LB ?f ?ZL ?s ?ST ?AL ?a)) ] ] =>\n       setoid_rewrite (@forward_length sT Dom H JSL LB f s ST ZL AL a)\n     end : len.\n\nLemma snd_forwardF_length (sT:stmt) (Dom : stmt -> Type) `{JoinSemiLattice (Dom sT)}\n      `{@LowerBounded (Dom sT) H}\n      (f: forall sT, ctxmap params ->\n                forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n  : forall ZL F ST AL anF,\n    ctxmap_len (snd (forwardF (@forward sT Dom H _ _ f ZL) F ST AL anF))\n    = ctxmap_len AL.\nProof.\n  intros.\n  general induction F; destruct anF; simpl; eauto.\n  rewrite IHF. eauto with len.\nQed.\n\nSmpl Add\n     match goal with\n     | [ |- context [ ctxmap_len (snd\n                                   (@forwardF ?sT ?Dom ?H ?JSL\n                                              (@forward ?sT ?Dom ?H ?JSL ?LB ?f ?ZL)\n                                              ?F ?ST ?AL ?anF)) ] ] =>\n       setoid_rewrite (@snd_forwardF_length sT Dom H JSL LB f ZL F ST AL anF)\n     end : len.\n\nLemma forwardF_get  (sT:stmt) (Dom:stmt->Type) `{JoinSemiLattice (Dom sT)}\n      `{@LowerBounded (Dom sT) H}\n           (F:list (params * stmt)) (anF:list (ann (Dom sT))) AL\n           (ST:forall n s, get F n s -> subTerm (snd s) sT) aa n f ZL\n           (GetBW:get (fst (forwardF (@forward sT Dom H _ _ f ZL) F ST AL anF)) n aa)\n      :\n        { Zs : params * stmt & {GetF : get F n Zs &\n        { a : ann (Dom sT) & { getAnF : get anF n a & { AL' : ctxmap (Dom sT) |\n        { ST' : subTerm (snd Zs) sT |\n          fst (@forward sT Dom H _ _ f ZL (snd Zs) ST' AL' a) = aa\n          /\\ poLe (snd (@forward sT Dom H _ _ f ZL (snd Zs) ST' AL'  a))\n                 (snd (forwardF (@forward sT Dom H _ _ f ZL) F ST AL anF))\n        } } } } } }.\nProof.\n  eapply get_getT in GetBW.\n  general induction anF; destruct F as [|[Z s] F']; inv GetBW.\n  - exists (Z, s). simpl. do 5 (eexists; eauto 20 using get).\n    split. reflexivity. eapply snd_forwardF_exp.\n  - edestruct IHanF as [Zs [? [? [? ]]]]; eauto; dcr; subst.\n    exists Zs. do 5 (eexists; eauto 20 using get).\nQed.\n\nInstance makeForwardAnalysis (Dom:stmt -> Type)\n         (PO:forall s, PartialOrder (Dom s))\n         (BSL:forall s, JoinSemiLattice (Dom s))\n         (LB:forall s, @LowerBounded (Dom s) (PO s))\n         (f: forall sT, ctxmap params ->\n                   forall s, subTerm s sT -> Dom sT -> anni (Dom sT))\n         (fMon:forall sT s (ST:subTerm s sT) ZL,\n             forall a b, a ⊑ b -> f sT ZL s ST a ⊑ f sT ZL s ST b)\n         (Trm: forall s, Terminating (Dom s) poLt)\n\n  : forall s (i:Dom s), Iteration { a : ann (Dom s) | annotation s a } :=\n  {\n    step := fun X : {a : ann (Dom s) | annotation s a} =>\n                      exist (fun a0 : ann (Dom s) => annotation s a0)\n                            (fst (forward Dom f (ctxmap_emp _)\n                                          (subTerm_refl _) (ctxmap_emp _) (proj1_sig X)))\n                                 (forward_annotation Dom f (ctxmap_emp _) (ctxmap_emp _) (subTerm_refl _) _);\n    initial_value :=\n      exist (fun a : ann (Dom s) => annotation s a)\n            (setTopAnn (setAnn bottom s) i)\n            (setTopAnn_annotation _ (setAnn_annotation bottom s))\n  }.\nProof.\n  - destruct X; eauto.\n  - eapply ann_R_setTopAnn_left.\n    + simpl. rewrite forward_getAnn'. rewrite getAnn_setTopAnn. reflexivity.\n    + eapply ann_bottom.\n      eapply forward_annotation; eauto.\n      eapply setTopAnn_annotation.\n      eapply setAnn_annotation.\n  - intros [a Ann] [b Bnn] LE; simpl in *.\n    eapply (forward_monotone Dom f (fMon s)); eauto.\nDefined.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Analysis/AnalysisForward.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24214893705561955}}
{"text": "From Undecidability Require Import TM.Util.TM_facts TM.Basic.Mono TM.Combinators.Combinators TM.Compound.Multi.\nRequire Import List.\nFrom Undecidability Require Import TMTac.\nFrom Coq Require Import List.\n\nSet Default Proof Using \"Type\".\n\n(* Useful for running time stuff *)\nLocal Arguments plus : simpl never.\nLocal Arguments mult : simpl never.\n\n\n(* The correctness and definition of [WriteString] is non-standard, because it is defined (and verified) by recursion (or induction). *)\nSection Write_String.\n\n  Variable sig : finType.\n  Variable D : move.\n\n  Fixpoint WriteString (l : list sig) : pTM sig unit 1 :=\n    match l with\n    | [] => Nop\n    | [x] => Write x\n    | x :: xs => WriteMove x D;; WriteString xs\n    end.\n\n  Fixpoint WriteString_Fun (sig' : Type) (t : tape sig') (str : list sig') :=\n    match str with\n    | nil => t\n    | [x] => tape_write t (Some x)\n    | x :: str' => WriteString_Fun (doAct t (Some x, D)) str'\n    end.\n\n  Lemma WriteString_Fun_eq (sig' : Type) (t : tape sig') (str : list sig') :\n    WriteString_Fun t str =\n    match str with\n    | nil => t\n    | [x] => tape_write t (Some x)\n    | x :: str' => WriteString_Fun (doAct t (Some x, D)) str'\n    end.\n  Proof. destruct str; auto. Qed.\n\n  Lemma Write_String_nil (sig' : Type) (t : tape sig') :\n    WriteString_Fun t nil = t.\n  Proof. destruct t; cbn; auto. Qed.\n\n  Fixpoint WriteString_sem_fix (str : list sig) : pRel sig unit 1 :=\n    match str with\n    | nil => Nop_Rel\n    | [x] => Write_Rel x\n    | x :: str' =>\n      WriteMove_Rel x D |_tt ∘ WriteString_sem_fix str'\n    end.\n\n  Definition WriteString_steps l :=\n    2 * l - 1.\n    \n  Lemma WriteString_fix_Sem (str : list sig) :\n    WriteString str ⊨c(WriteString_steps (length str)) (WriteString_sem_fix str).\n  Proof.\n    induction str as [ | s [ | s' str'] IH ].\n    - cbn. change (2 * 0 - 1) with 0. TM_Correct.\n    - cbn. change (2 * 1 - 1) with 1. TM_Correct.\n    - change (WriteString (s :: s' :: str')) with (WriteMove s D;; WriteString (s' :: str')).\n      eapply RealiseIn_monotone.\n      { TM_Correct. TM_Correct. apply IH. }\n      { unfold WriteString_steps. cbn. lia. }\n      { intros t1 t3 H. destruct H as (()&t2&H1&H2).\n        change (WriteString_sem_fix (s :: s' :: str')) with (WriteMove_Rel s D |_tt ∘ WriteString_sem_fix (s' :: str')).\n        exists t2. split; auto.\n      }\n  Qed.\n  \n\n  Definition WriteString_Rel str : Rel (tapes sig 1) (unit * tapes sig 1) :=\n    Mono.Mk_R_p (ignoreParam (fun tin tout => tout = WriteString_Fun tin str)).\n\n  Lemma WriteString_Sem str :\n    WriteString str ⊨c(WriteString_steps (length str)) (WriteString_Rel str).\n  Proof.\n    eapply RealiseIn_monotone.\n    { apply WriteString_fix_Sem. }\n    { reflexivity. }\n    { induction str as [ | s [ | s' str'] IH]; intros tin (yout, tout) H.\n      - cbn. now TMSimp.\n      - cbn. now TMSimp.\n      - change (WriteString_sem_fix (s :: s' :: str')) with ((WriteMove_Rel s D |_tt ∘ WriteString_sem_fix (s' :: str'))) in H.\n        destruct H as (tmid&H1&H2). hnf in H1. apply IH in H2.\n        (* cbv [WriteString_Rel Mk_R_p ignoreParam].\n        change (WriteString_Fun tin[@Fin0] (s :: s' :: str')) with (WriteString_Fun (tape_move_mono tin[@Fin0] (Some s, D)) (s' :: str')). *)\n        now TMSimp.\n    }\n  Qed.\n\nEnd Write_String.\n\nArguments WriteString : simpl never.\nArguments WriteString_Rel {sig} (D) (str) x y/.\n\nLemma skipn_S (X : Type) (xs : list X) (n : nat) :\n  skipn (S n) xs = tl (skipn n xs).\nProof.\n  revert xs. induction n as [ | n IH]; intros; cbn in *.\n  - destruct xs; auto.\n  - destruct xs; auto.\nQed.\n\n(*\nCompute skipn 3 (tl [1;2;3;4;5;6;7]).\nCompute tl (skipn 3 [1;2;3;4;5;6;7]).\n*)\n\nLemma skipn_tl (X : Type) (xs : list X) (n : nat) :\n  skipn n (tl xs) = tl (skipn n xs).\nProof.\n  revert xs. induction n as [ | n IH]; intros; cbn in *.\n  - destruct xs; auto.\n  - destruct xs; cbn; auto.\n    replace (match xs with\n             | [] => []\n             | _ :: l => skipn n l\n             end)\n      with (skipn n (tl xs)); auto.\n    destruct xs; cbn; auto. apply skipn_nil.\nQed.\n\n\nLemma WriteString_L_local (sig : Type) (str : list sig) t :\n  str <> nil ->\n  tape_local (WriteString_Fun Lmove t str) = rev str ++ right t.\nProof.\n  revert t. induction str as [ | s [ | s' str'] IH]; intros; cbn in *.\n  - tauto.\n  - reflexivity.\n  - rewrite IH. 2: congruence. simpl_tape. rewrite <- !app_assoc. reflexivity.\nQed.\n\n(*\nSection Test.\n  Let t : tape nat := midtape [3;2;1] 4 [5;6;7].\n  Let str := [3;2;1].\n  Compute WriteString_Fun Lmove t str.\n  Compute (left t).\n  Compute (left (WriteString_Fun Lmove t str)).\n  Compute (skipn (length str - 1) (left t)).\nEnd Test.\n*)\n\nLemma WriteString_L_left (sig : Type) (str : list sig) t :\n  left (WriteString_Fun Lmove t str) = skipn (pred (length str)) (left t).\nProof.\n  revert t. induction str as [ | s [ | s' str'] IH]; intros; cbn -[skipn] in *.\n  - reflexivity.\n  - reflexivity.\n  - rewrite IH. simpl_tape. now rewrite skipn_S, skipn_tl.\nQed.\n\nLemma WriteString_L_right (sig : Type) (str : list sig) t :\n   right (WriteString_Fun Lmove t str) = tl (rev str) ++ right t.\nProof.\n  revert t. induction str as [ | s [ | s' str'] IH]; intros; cbn in *.\n  - tauto.\n  - reflexivity.\n  - rewrite IH. simpl_tape. rewrite tl_app with (ys:=[s]),<- !app_assoc. reflexivity. intros (?&[=])%app_eq_nil.\nQed.\n\nLemma WriteString_L_current (sig : Type) (str : list sig) t :\n   current (WriteString_Fun Lmove t str) = hd None (map Some (rev str ++ tape_local t)).\nProof.\n  revert t. induction str as [ | s [ | s' str'] IH]; intros; cbn in *.\n  - now destruct t.\n  - reflexivity.\n  - rewrite IH. autorewrite with list. setoid_rewrite app_assoc at 1 2.\n    rewrite !hd_app with (xs:=(map Some (rev str') ++ map Some [s'])). easy. all:intros (?&[=])%app_eq_nil.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/TM/Compound/WriteString.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2421161706759958}}
{"text": "From compcert Require Import common.Separation.\nFrom compcert Require Import common.Values.\nFrom compcert Require common.Errors.\nFrom compcert Require Import cfrontend.Ctypes.\nFrom compcert Require Import lib.Maps.\nFrom compcert Require Import lib.Coqlib.\nFrom compcert Require Import lib.Integers.\n\nFrom Velus Require Import Common.\nFrom Velus Require Import VelusMemory.\nFrom Velus Require Import Common.CompCertLib.\n\nFrom Coq Require Import List.\nFrom Coq Require Import ZArith.BinInt.\n\nFrom Coq Require Import Program.Tactics.\nFrom Coq Require Sorting.Permutation.\n\nOpen Scope list.\nOpen Scope sep_scope.\nOpen Scope Z.\n\nNotation \"m -*> m'\" := (massert_imp m m') (at level 70, no associativity) : sep_scope.\nNotation \"m <-*-> m'\" := (massert_eqv m m') (at level 70, no associativity) : sep_scope.\n\nLemma sepconj_eqv:\n  forall P P' Q Q',\n    P <-*-> P' ->\n    Q <-*->  Q' ->\n    (P ** Q) <-*-> (P' ** Q').\nProof.\n  intros * HP HQ.\n  rewrite HP. rewrite HQ.\n  reflexivity.\nQed.\n\nLemma pure_imp:\n  forall P Q,\n    (pure P -*> pure Q) <-> (P -> Q).\nProof.\n  split; intro Imp.\n  - eapply Imp.\n  - split; auto.\n  Grab Existential Variables.\n  exact Memory.Mem.empty.\nQed.\n\nLemma pure_eqv:\n  forall P Q,\n    (pure P <-*-> pure Q) <-> (P <-> Q).\nProof.\n  split; intro Eqv; destruct Eqv.\n  - split; now rewrite <-pure_imp.\n  - split; now rewrite pure_imp.\nQed.\n\nLemma disjoint_footprint_sepconj:\n  forall P Q R,\n    disjoint_footprint R (P ** Q) <-> disjoint_footprint R P /\\ disjoint_footprint R Q.\nProof.\n  intros.\n  split; intro H.\n  - split; intros b ofs; specialize (H b ofs); intros HfR HfP; apply H; auto.\n    + now left.\n    + now right.\n  - destruct H as [HfP HfQ].\n    intros b ofs.\n    specialize (HfP b ofs).\n    specialize (HfQ b ofs).\n    intros HfR HPQ.\n    destruct HPQ.\n    + now apply HfP.\n    + now apply HfQ.\nQed.\n\n(* * * * * * * * Separating Wand * * * * * * * * * * * * * * *)\n\nFrom compcert Require Import common.Memory.\nFrom Coq Require Import Morphisms.\n\nDefinition wand_footprint (P Q: massert) (b: block) (ofs: Z) : Prop :=\n  ~m_footprint P b ofs /\\ m_footprint Q b ofs.\n\nProgram Definition sepwand (P Q: massert) : massert := {|\n  m_pred := fun m =>\n              (forall m', Mem.unchanged_on (wand_footprint P Q) m m' ->\n                          m' |= P -> m' |= Q)\n              /\\ (forall b ofs, wand_footprint P Q b ofs -> Mem.valid_block m b);\n  m_footprint := wand_footprint P Q\n|}.\nNext Obligation.\n  rename H into HPQ, H1 into Hval, H0 into Hun1.\n  repeat split.\n  - intros m'' Hun2 HP.\n    apply Mem.unchanged_on_trans with (1:=Hun1) in Hun2.\n    now apply HPQ with (1:=Hun2) (2:=HP).\n  - intros b ofs Hwfoot.\n    apply Mem.valid_block_unchanged_on with (1:=Hun1).\n    apply Hval with (1:=Hwfoot).\nQed.\n\nInfix \"-*\" := sepwand (at level 65, right associativity) : sep_scope.\n\nDefinition decidable_footprint (P: massert) : Prop :=\n  forall b ofs, Decidable.decidable (m_footprint P b ofs).\n\nInstance decidable_footprint_Proper:\n  Proper (massert_eqv ==> iff) decidable_footprint.\nProof.\n  intros P Q HPQ.\n  unfold decidable_footprint, Decidable.decidable.\n  split; intros.\n  now rewrite <-HPQ.\n  now rewrite HPQ.\nQed.\n\nLemma decidable_footprint_sepconj:\n  forall P Q,\n    decidable_footprint P ->\n    decidable_footprint Q ->\n    decidable_footprint (P ** Q).\nProof.\n  intros P Q HP HQ b ofs.\n  specialize (HP b ofs).\n  specialize (HQ b ofs).\n  simpl; intuition.\nQed.\n\nHint Resolve decidable_footprint_sepconj.\n\nLemma decidable_ident_eq:\n  forall (b b': AST.ident), Decidable.decidable (b = b').\nProof.\n  intros b b'. unfold Decidable.decidable.\n  destruct (peq b' b); intuition.\nQed.\n\nLemma decidable_footprint_range:\n  forall {f} b lo hi,\n    decidable_footprint (range' f b lo hi).\nProof.\n  unfold decidable_footprint.\n  intros.\n  apply Decidable.dec_and.\n  apply decidable_ident_eq.\n  apply Decidable.dec_and.\n  apply Z.le_decidable.\n  apply Z.lt_decidable.\nQed.\n\nHint Resolve decidable_footprint_range.\n\nLemma decidable_footprint_contains:\n  forall {f} chunk b ofs spec,\n    decidable_footprint (contains' f chunk b ofs spec).\nProof.\n  unfold decidable_footprint.\n  intros.\n  apply Decidable.dec_and.\n  apply decidable_ident_eq.\n  apply Decidable.dec_and.\n  apply Z.le_decidable.\n  apply Z.lt_decidable.\nQed.\n\nHint Resolve decidable_footprint_contains.\n\nLemma sep_unwand:\n  forall P Q,\n    decidable_footprint P ->\n    (P ** (P -* Q)) -*> Q.\nProof.\n  intros P Q Hdec.\n  split.\n  - intros m HPPQ.\n    destruct HPPQ as (HP & HW & Hdj).\n    destruct HW as [Hu ?].\n    apply Hu.\n    apply Mem.unchanged_on_refl.\n    assumption.\n  - intros b ofs HfQ.\n    destruct (Hdec b ofs); [now left|right].\n    split; intuition.\nQed.\n\nLemma disjoint_sepwand:\n  forall P Q, disjoint_footprint P (P -* Q).\nProof.\n  intros P Q b ofs HfP HfPQ.\n  destruct HfPQ as [HfnP HfQ].\n  intuition.\nQed.\n\nLemma merge_disjoint:\n  forall P Q R m,\n    disjoint_footprint P Q ->\n    m |= P ** R ->\n    m |= Q ** R ->\n    m |= P ** Q ** R.\nProof.\n  intros P Q R m HdPQ HPR HQR.\n  rewrite <-sep_assoc.\n  repeat split.\n  - apply sep_proj1 with (1:=HPR).\n  - apply sep_proj1 with (1:=HQR).\n  - assumption.\n  - apply sep_proj2 with (1:=HPR).\n  - intros b ofs Hfw HfR.\n    destruct Hfw as [HfP|HfPQ].\n    + destruct HPR as [? [? HdPR]].\n      unfold disjoint_footprint in HdPR.\n      apply HdPR with (1:=HfP) (2:=HfR).\n    + destruct HQR as [? [? HdQR]].\n      unfold disjoint_footprint in HdQR.\n      apply HdQR with (1:=HfPQ) (2:=HfR).\nQed.\n\nLemma merge_sepwand:\n  forall P Q R m,\n    m |= P ** R ->\n    m |= (P -* Q) ** R ->\n    m |= P ** (P -* Q) ** R.\nProof.\n  intros. apply merge_disjoint; try assumption.\n  now apply disjoint_sepwand.\nQed.\n\nLemma sepwand_mp:\n  forall m P Q,\n    m |= P ->\n    m |= P -* Q ->\n    m |= Q.\nProof.\n  intros m P Q HP HPQ.\n  apply HPQ; [|assumption].\n  apply Mem.unchanged_on_refl.\nQed.\n\nInstance wand_footprint_massert_imp_Proper:\n  Proper (massert_imp ==> massert_imp --> eq ==> eq ==> Basics.impl)\n         wand_footprint.\nProof.\n  intros P Q HPQ R S HRS b' b Hbeq ofs' ofs Hoeq.\n  subst.\n  unfold wand_footprint.\n  now rewrite HPQ, HRS.\nQed.\n\nInstance wand_footprint_massert_eqv_Proper:\n  Proper (massert_eqv ==> massert_eqv ==> eq ==> eq ==> iff) wand_footprint.\nProof.\n  intros P Q HPQ R S HRS b' b Hbeq ofs' ofs Hoeq.\n  subst.\n  unfold wand_footprint.\n  rewrite HPQ, HRS. reflexivity.\nQed.\n\nInstance sepwand_massert_Proper:\n  Proper (massert_eqv ==> massert_eqv ==> massert_eqv) sepwand.\nProof.\n  intros P Q HPQ R S HRS.\n  split; [split|split].\n  - intros m HPR.\n    destruct HPR as [HPR1 HPR2].\n    split.\n    + intros m' Hun HQ.\n      rewrite <-HRS.\n      rewrite <-HPQ in HQ.\n      apply HPR1 with (2:=HQ).\n      apply Mem.unchanged_on_implies with (1:=Hun).\n      intros b ofs HfW Hv.\n      now rewrite HPQ, HRS in HfW.\n    + intros b ofs.\n      rewrite <-HPQ, <-HRS.\n      apply HPR2.\n  - intros b ofs Hf.\n    simpl in Hf.\n    now rewrite <-HPQ, <-HRS in Hf.\n  - intros m HQS.\n    destruct HQS as [HQS1 HQS2].\n    split.\n    + intros m' Hun HP.\n      rewrite HPQ in HP.\n      rewrite HRS.\n      apply HQS1 with (2:=HP).\n      apply Mem.unchanged_on_implies with (1:=Hun).\n      intros b ofs HfW Hv.\n      now rewrite HPQ, HRS.\n    + intros b ofs.\n      rewrite HPQ, HRS.\n      apply HQS2.\n  - intros b ofs Hf.\n    simpl in Hf. rewrite HPQ, HRS in Hf.\n    assumption.\nQed.\n\nLemma hide_in_sepwand:\n  forall P Q R,\n    decidable_footprint Q ->\n    P <-*-> (Q ** R) ->\n    P <-*-> (Q ** (Q -* P)).\nProof.\n  intros P Q R HQdec HPQR.\n  rewrite HPQR at 2.\n  split; [split|].\n  - intros m HP.\n    apply HPQR in HP.\n    split; [|split].\n    + apply sep_proj1 with (1:=HP).\n    + split.\n      * intros m' Hun HQ'.\n        destruct HP as (HQ & HR & Hdj).\n        repeat split; try assumption.\n        apply m_invar with (1:=HR).\n        apply Mem.unchanged_on_implies with (1:=Hun).\n        intros b ofs HfR Hv.\n        destruct (HQdec b ofs).\n        now (exfalso; apply Hdj with (2:=HfR)).\n        split; [assumption|now right].\n      * intros b ofs.\n        destruct 1 as [HnfQ [|HfR]]; [contradiction|].\n        apply sep_proj2 in HP.\n        apply m_valid with (1:=HP) (2:=HfR).\n    + apply disjoint_sepwand.\n  - intros b ofs Hf.\n    rewrite HPQR.\n    destruct Hf as [|Hf]; [now left|].\n    destruct Hf as [HfQ [|HfR]]; [now left|].\n    now right.\n  - rewrite sep_unwand with (1:=HQdec).\n    rewrite HPQR. reflexivity.\nQed.\n\nLemma sepwand_out:\n  forall P Q,\n    decidable_footprint P ->\n    (P ** Q) <-*-> (P ** (P -* (P ** Q))).\nProof.\n  split.\n  - now rewrite <-hide_in_sepwand.\n  - now rewrite sep_unwand.\nQed.\n\nLemma pure_wand_footprint:\n  forall (P: Prop) Q b ofs,\n    wand_footprint (pure P) Q b ofs <-> m_footprint Q b ofs.\nProof.\n  split.\n  - inversion 1; auto.\n  - split; auto.\nQed.\n\nLemma unchanged_on_imp:\n  forall P (Q: block -> Z -> Prop) m m',\n    Mem.unchanged_on P m m' ->\n    (forall b ofs, Q b ofs -> P b ofs) ->\n    Mem.unchanged_on Q m m'.\nProof.\n  intros * Hun Hpq.\n  inversion_clear Hun.\n  constructor; auto.\nQed.\n\nLemma pure_sepwand:\n  forall (P: Prop) Q,\n    P -> (pure P -* Q) <-*-> Q.\nProof.\n  intros P Q HH.\n  constructor.\n  - constructor.\n    + inversion_clear 1 as (Hun & Hf).\n      apply Hun; auto using Mem.unchanged_on_refl.\n    + constructor; auto.\n  - constructor.\n    + intros m Hq. constructor.\n      * intros m' Hun Hmp.\n        apply m_invar with (1:=Hq).\n        apply unchanged_on_imp with (1:=Hun).\n        apply pure_wand_footprint.\n      * intros * Hwf.\n        apply pure_wand_footprint in Hwf.\n        eauto using m_valid.\n    + simpl. intros * Hf.\n      now apply pure_wand_footprint in Hf.\nQed.\n\n(* Reynold's \"rules capturing the adjunctive relationship between separating\n   conjunction and separating implication\". *)\n\nLemma reynolds1:\n  forall P1 P2 P3,\n    (P1 ** P2) -*> P3 ->\n    (forall b ofs, m_footprint P1 b ofs -> wand_footprint P2 P3 b ofs) ->\n    P1 -*> (P2 -* P3).\nProof.\n  intros P1 P2 P3 HH Hfi.\n  split.\n  - intros m HP1.\n    split.\n    + intros m' Hun HP2.\n      apply HH.\n      split; [|split].\n      * apply m_invar with (1:=HP1).\n        apply Mem.unchanged_on_implies with (1:=Hun).\n        intros; now apply Hfi.\n      * assumption.\n      * intros b ofs HfP1 HfP2.\n        apply Hfi in HfP1.\n        destruct HfP1. contradiction.\n    + intros b ofs.\n      destruct 1 as [HnfP2 HfP3].\n      destruct HH as [HHm HHf].\n      apply HHf in HfP3.\n      destruct HfP3 as [HfP1|]; [|contradiction].\n      apply m_valid with (1:=HP1) (2:=HfP1).\n  - intros b ofs.\n    destruct 1 as [HnfP2 HfP3].\n    destruct HH as [HHm HHf].\n    apply HHf in HfP3.\n    destruct HfP3; intuition.\nQed.\n\nLemma reynolds2:\n  forall P1 P2 P3,\n    decidable_footprint P2 ->\n    P1 -*> (P2 -* P3) ->\n    (P1 ** P2) -*> P3.\nProof.\n  intros P1 P2 P3 HD2 HH.\n  rewrite HH. rewrite sep_comm.\n  rewrite sep_unwand with (1:=HD2).\n  reflexivity.\nQed.\n\nDefinition footprint_perm' (p: permission) (P: massert) (b: block) (lo hi: Z) : Prop :=\n  (forall m, m |= P ->\n             (forall i k, m_footprint P b i ->\n                          lo <= i < hi ->\n                          Mem.perm m b i k p)).\n\nNotation footprint_perm := (footprint_perm' Freeable).\nNotation footprint_perm_w := (footprint_perm' Writable).\n\nLemma footprint_perm_sepconj:\n  forall p P Q b lo hi,\n    footprint_perm' p P b lo hi ->\n    footprint_perm' p Q b lo hi ->\n    footprint_perm' p (P ** Q) b lo hi.\nProof.\n  intros f P Q b lo hi HfpP HfpQ.\n  intros m HPQ i k Hf Hi.\n  destruct HPQ as (HP & HQ & Hdj).\n  destruct Hf as [HfP|HfQ].\n  - now apply HfpP.\n  - now apply HfpQ.\nQed.\n\nLemma footprint_perm_range:\n  forall p b lo hi b' lo' hi',\n    footprint_perm' p (range' p b lo hi) b' lo' hi'.\nProof.\n  intros p b lo hi b' lo' hi' m Hm i k Hf Hi.\n  destruct Hf. subst.\n  destruct Hm as (Hlo & Hhi & Hp).\n  now apply Hp.\nQed.\n\nLemma footprint_perm_contains:\n  forall p chunk b ofs spec b' lo hi,\n    footprint_perm' p (contains' p chunk b ofs spec) b' lo hi.\nProof.\n  intros p chunk b ofs spec b' lo hi m Hm i k Hf Hi.\n  destruct Hf. subst.\n  destruct Hm as (Hlo & Hhi & Hv & Hl).\n  destruct Hv as (Hperm & j & Hofs).\n  apply Mem.perm_cur.\n  now apply Hperm.\nQed.\n\nHint Resolve footprint_perm_sepconj\n             footprint_perm_range\n             footprint_perm_contains.\n\nLemma range_imp_with_wand:\n  forall p P b lo hi,\n    (range' p b lo hi) -*> P ->\n    decidable_footprint P ->\n    footprint_perm' p P b lo hi ->\n    (range' p b lo hi) <-*-> (P ** (P -* range' p b lo hi)).\nProof.\n  intros p P b lo hi HRP HPfdec HPperm.\n  split; [|now rewrite sep_unwand].\n  split.\n  - intros m HR.\n    split; [|split].\n    + now apply HRP.\n    + split.\n      * intros m' Hun HP.\n        assert (HR':=HR).\n        destruct HR' as (Hlo & Hhi & Hperm).\n        repeat split; try assumption.\n        intros i k Hi.\n        destruct (HPfdec b i) as [HfPi|HnfPi].\n        now apply HPperm with (1:=HP) (2:=HfPi) (3:=Hi).\n        apply Mem.perm_unchanged_on with (1:=Hun).\n        split; [assumption|simpl; now intuition].\n        now apply Hperm.\n      * intros b' ofs.\n        destruct 1 as [? HfR].\n        assert (b = b') by (simpl in HfR; intuition).\n        subst. apply (m_valid _ _ _ _ HR HfR).\n    + intros b' ofs HfP HfPR.\n      destruct HfPR. contradiction.\n  - intros b' ofs Hf.\n    destruct HRP as [HRP HfPR].\n    destruct Hf as [|Hf]; [now apply HfPR|].\n    now destruct Hf.\nQed.\n\nDefinition subseteq_footprint (P Q: massert) :=\n  (forall b ofs, m_footprint P b ofs -> m_footprint Q b ofs).\n\nInstance subseteq_footprint_footprint_Proper:\n  Proper (subseteq_footprint ==> eq ==> eq ==> Basics.impl) m_footprint.\nProof.\n  intros P Q Hsub b b' Heqb ofs ofs' Heqofs HP.\n  subst. apply Hsub with (1:=HP).\nQed.\n\nLemma subseteq_footprint_refl:\n  forall P, subseteq_footprint P P.\nProof.\n  now unfold subseteq_footprint.\nQed.\n\nLemma subseteq_footprint_trans:\n  forall P Q R, subseteq_footprint P Q ->\n                subseteq_footprint Q R ->\n                subseteq_footprint P R.\nProof.\n  unfold subseteq_footprint. intuition.\nQed.\n\nAdd Parametric Relation: massert subseteq_footprint\n    reflexivity proved by subseteq_footprint_refl\n    transitivity proved by subseteq_footprint_trans\n      as subseteq_footprint_rel.\n\nInstance subseteq_footprint_massert_imp_Proper:\n  Proper (massert_imp ==> massert_imp --> Basics.impl) subseteq_footprint.\nProof.\n  intros P Q HPQ R S HSR HPsR b ofs HfQ.\n  apply HPQ in HfQ.\n  specialize (HPsR b ofs HfQ).\n  now apply HSR in HPsR.\nQed.\n\nInstance subseteq_footprint_massert_eqv_Proper:\n  Proper (massert_eqv ==> massert_eqv ==> iff) subseteq_footprint.\nProof.\n  intros P Q HPQ R S HSR.\n  destruct HPQ as [HPQ HQP].\n  destruct HSR as [HSR HRS].\n  split; intro HH.\n  - rewrite HPQ in HH; now rewrite HRS.\n  - rewrite HQP in HH. now rewrite HSR.\nQed.\n\nLemma subseteq_footprint_sepconj:\n  forall P Q R S,\n    subseteq_footprint P Q ->\n    subseteq_footprint R S ->\n    subseteq_footprint (P ** R) (Q ** S).\nProof.\n  intros P Q R S HPQ HRS.\n  intros b ofs.\n  destruct 1 as [HP|HR].\n  - left; now apply HPQ.\n  - right; now apply HRS.\nQed.\n\nLemma unify_distinct_wands:\n  forall P Q R S,\n    disjoint_footprint R S ->\n    subseteq_footprint P R ->\n    subseteq_footprint Q S ->\n    (P -* R) ** (Q -* S)\n    -*> (P ** Q) -* (R ** S).\nProof.\n  intros P Q R S HdjRS HsPR HsQS.\n  split.\n  - intros m HH.\n    split.\n    + intros m' Hun.\n      destruct HH as (HPR & HQS & Hdj).\n      destruct 1 as (HP & HQ & HdjPQ).\n      repeat split.\n      * apply m_invar with (m':=m') in HPR.\n        now apply sepwand_mp with (1:=HP) in HPR.\n        apply Mem.unchanged_on_implies with (1:=Hun).\n        intros b ofs HfPR Hv.\n        destruct HfPR as (HnfP & HfR).\n        split.\n        destruct 1 as [HfP|HfQ]; [contradiction|].\n        apply HdjRS with (1:=HfR).\n        apply HsQS with (1:=HfQ).\n        now left.\n      * apply m_invar with (m':=m') in HQS.\n        now apply sepwand_mp with (1:=HQ) in HQS.\n        apply Mem.unchanged_on_implies with (1:=Hun).\n        intros b ofs HfQS Hv.\n        destruct HfQS as (HnfQ & HfS).\n        split.\n        destruct 1 as [HfP|HfQ]; [|contradiction].\n        apply HdjRS with (2:=HfS).\n        apply HsPR with (1:=HfP).\n        now right.\n      * assumption.\n    + intros b ofs Hfw.\n      apply (m_valid _ _ _ ofs HH).\n      destruct Hfw as [HnfPQ [HfR|HfS]]; [left|right]; split;\n        try (intro; apply HnfPQ; simpl); intuition.\n  - intros b ofs.\n    destruct 1 as [HnfPQ [HfR|HfS]]; [left|right]; split;\n      try (intro; apply HnfPQ; simpl); intuition.\nQed.\n\n(* * * * * * * * sepall * * * * * * * * * * * * * * *)\n\nProgram Definition sepemp: massert :=  pure True.\n\nLemma sepemp_disjoint:\n  forall P, disjoint_footprint P sepemp.\nProof.\n  unfold disjoint_footprint. auto.\nQed.\n\nLemma sepemp_trivial:\n  forall m, m |= sepemp.\nProof.\n  split.\nQed.\nHint Resolve sepemp_trivial.\n\nLemma sepemp_right:\n  forall P,\n    P <-*-> (P ** sepemp).\nProof.\n  split; split; simpl; try (auto using sepemp_disjoint); intuition.\nQed.\n\nLemma sepemp_left:\n  forall P,\n    P <-*-> (sepemp ** P).\nProof.\n  intros. rewrite sep_comm. rewrite <-sepemp_right. reflexivity.\nQed.\n\nLemma wandwand_sepemp:\n  forall P, massert_eqv (P -* P) sepemp.\nProof.\n  firstorder.\nQed.\n\nLemma wand_footprint_sepemp:\n  forall P b ofs,\n    wand_footprint sepemp P b ofs <-> m_footprint P b ofs.\nProof.\n  firstorder.\nQed.\n\nLemma sepemp_wand:\n  forall P,\n    sepemp -* P <-*-> P.\nProof.\n  split; split.\n  - inversion 1 as [Hun Hv].\n    apply Hun.\n    apply Mem.unchanged_on_refl.\n    now simpl.\n  - now split.\n  - intros m HP. split.\n    + intros m' Hun He.\n      apply m_invar with (1:=HP).\n      apply Mem.unchanged_on_implies with (1:=Hun).\n      intros; now apply wand_footprint_sepemp.\n    + intros b ofs Hw.\n      rewrite wand_footprint_sepemp in Hw.\n      apply m_valid with (1:=HP) (2:=Hw).\n  - intros b ofs Hf.\n    simpl in Hf.\n    now apply wand_footprint_sepemp in Hf.\nQed.\n\nLemma decidable_footprint_sepemp:\n  decidable_footprint sepemp.\nProof.\n  unfold decidable_footprint. simpl.\n  intros; apply Decidable.dec_False.\nQed.\n\nLemma footprint_perm_sepemp:\n  forall p b lo hi, footprint_perm' p sepemp b lo hi.\nProof.\n  intros lo hi m. inversion 2.\nQed.\n\nHint Resolve decidable_footprint_sepemp footprint_perm_sepemp.\n\nLemma empty_range:\n  forall {f} b lo hi,\n    hi <= lo ->\n    0 <= lo ->\n    hi <= Ptrofs.modulus ->\n    sepemp <-*-> (range' f b lo hi).\nProof.\n  intros b lo hi Hgt.\n  split; [split|split].\n  - simpl. intuition.\n  - inversion 1. intuition.\n  - intros; exact I.\n  - inversion 1.\nQed.\n\nDefinition sepfalse := pure False.\n\nLemma decidable_footprint_sepfalse:\n  decidable_footprint sepfalse.\nProof.\n  unfold decidable_footprint. simpl.\n  intros; apply Decidable.dec_False.\nQed.\n\nLemma footprint_perm_sepfalse:\n  forall p b lo hi, footprint_perm' p sepfalse b lo hi.\nProof.\n  intros p b lo hi m Hm. inversion Hm.\nQed.\n\nHint Resolve decidable_footprint_sepfalse footprint_perm_sepfalse.\n\nSection MassertPredEqv.\n  Context {A: Type}.\n\n  Definition massert_pred_eqv (P: A -> massert) (Q: A -> massert) : Prop :=\n    forall x, massert_eqv (P x) (Q x).\n\n  Lemma massert_pred_eqv_refl:\n    forall P, massert_pred_eqv P P.\n  Proof.\n    now unfold massert_pred_eqv.\n  Qed.\n\n  Lemma massert_pred_eqv_sym:\n    forall P Q, massert_pred_eqv P Q -> massert_pred_eqv Q P.\n  Proof.\n    unfold massert_pred_eqv. intros P Q HPQ x. now rewrite (HPQ x).\n  Qed.\n\n  Lemma massert_pred_eqv_trans:\n    forall P Q R,\n      massert_pred_eqv P Q ->\n      massert_pred_eqv Q R ->\n      massert_pred_eqv P R.\n  Proof.\n    unfold massert_pred_eqv. intros P Q R HPQ HQR x.\n    now rewrite (HPQ x), (HQR x).\n  Qed.\n\n  Lemma massert_pred_eqv_inst:\n    forall P Q x,\n      massert_pred_eqv P Q ->\n      massert_eqv (P x) (Q x).\n  Proof.\n    intros P Q x HPQ. apply HPQ.\n  Qed.\n\nEnd MassertPredEqv.\n\nAdd Parametric Relation (A: Type) : (A -> massert) massert_pred_eqv\n    reflexivity proved by massert_pred_eqv_refl\n    symmetry proved by massert_pred_eqv_sym\n    transitivity proved by massert_pred_eqv_trans\nas massert_pred_eqv_prel.\n\nSection Sepall.\n  Context {A: Type}.\n\n  Definition sepall (p: A -> massert): list A -> massert :=\n    fold_right (fun x => sepconj (p x)) sepemp.\n\n  Lemma sepall_permutation:\n    forall p xs ys,\n      Permutation.Permutation xs ys ->\n      (sepall p xs) <-*-> (sepall p ys).\n  Proof.\n    intros p xs ys Hperm.\n    induction Hperm.\n    - reflexivity.\n    - simpl. now rewrite IHHperm.\n    - simpl.\n      rewrite sep_swap; reflexivity.\n    - rewrite IHHperm1, <-IHHperm2.\n      clear Hperm1 Hperm2 IHHperm1 IHHperm2.\n      now induction l'.\n  Qed.\n\n  Lemma sepall_app:\n    forall p xs ys,\n      sepall p (xs ++ ys) <-*-> sepall p xs ** sepall p ys.\n  Proof.\n    intros.\n    induction xs.\n    - intros.\n      rewrite sep_comm.\n      rewrite <-sepemp_right.\n      reflexivity.\n    - intros.\n      simpl.\n      rewrite sep_assoc.\n      rewrite IHxs.\n      reflexivity.\n  Qed.\n\n  Lemma sepall_cons:\n    forall p x xs,\n      sepall p (x::xs) <-*-> p x ** sepall p xs.\n  Proof.\n    constructor; constructor; trivial.\n  Qed.\n\n  Lemma sepall_breakout:\n    forall ys ws x xs p,\n      ys = ws ++ x :: xs ->\n      sepall p ys <-*-> p x ** sepall p (ws ++ xs).\n  Proof.\n    intros * Hys.\n    rewrite sepall_app.\n    rewrite sep_swap.\n    rewrite <-sepall_cons.\n    rewrite <-sepall_app.\n    rewrite <-Hys.\n    reflexivity.\n  Qed.\n\n  Lemma sepall_in:\n    forall x ys,\n      In x ys ->\n      exists ws xs,\n        ys = ws ++ x :: xs\n        /\\ (forall p,\n              sepall p ys <-*-> p x ** sepall p (ws ++ xs)).\n  Proof.\n    intros x ys Hin.\n    apply in_split in Hin.\n    destruct Hin as [ws [xs Hys]].\n    exists ws, xs.\n    split; auto.\n    intro p. apply sepall_breakout with (1:=Hys).\n  Qed.\n\n  Lemma sepall_wandout:\n    forall p x xs,\n      decidable_footprint (p x) ->\n      In x xs ->\n      (sepall p xs) <-*-> (p x ** (p x -* sepall p xs)).\n  Proof.\n    intros p x xs Hdec Hin.\n    apply in_split in Hin.\n    destruct Hin as (ws & ys & Hin).\n    rewrite sepall_breakout with (1:=Hin).\n    now apply sepwand_out.\n  Qed.\n\n  Lemma sepall_sepfalse:\n    forall m p xs,\n      m |= sepall p xs ->\n      (forall x, In x xs -> p x <> sepfalse).\n  Proof.\n    intros m p xs Hall x Hin Hp.\n    apply sepall_in in Hin.\n    destruct Hin as [ws [ys [Hys Heq]]].\n    rewrite Heq in Hall.\n    apply sep_comm in Hall.\n    apply sep_drop in Hall.\n    rewrite Hp in Hall.\n    destruct Hall.\n  Qed.\n\n  Lemma sepall_weakenp:\n    forall P P' xs,\n      (forall x, In x xs -> (P x) -*> (P' x)) ->\n      (sepall P xs) -*> (sepall P' xs).\n  Proof.\n    intros P P' xs Hx.\n    induction xs.\n    reflexivity.\n    simpl. apply sep_imp'.\n    - apply Hx. apply in_eq.\n    - rewrite IHxs. reflexivity.\n      intros x Hin.\n      apply Hx. apply in_cons with (1:=Hin).\n  Qed.\n\n  Lemma sepall_swapp:\n    forall P P' xs,\n      (forall x, In x xs -> P x <-*-> P' x) ->\n      sepall P xs <-*-> sepall P' xs.\n  Proof.\n    intros P P' xs Hx.\n    induction xs.\n    reflexivity.\n    simpl. apply sepconj_eqv.\n    - rewrite Hx. reflexivity. apply in_eq.\n    - rewrite IHxs. reflexivity.\n      intros x Hin.\n      apply Hx. apply in_cons with (1:=Hin).\n  Qed.\n\n  Lemma decidable_footprint_sepall:\n    forall P xs,\n      (forall x, decidable_footprint (P x)) ->\n      decidable_footprint (sepall P xs).\n  Proof.\n    induction xs as [|x xs IH].\n    now (intros; apply decidable_footprint_sepemp).\n    intro HPx.\n    simpl. apply decidable_footprint_sepconj.\n    - apply HPx.\n    - apply IH with (1:=HPx).\n  Qed.\n\n  Lemma footprint_perm_sepall:\n    forall p P xs b lo hi,\n      (forall x b lo hi, footprint_perm' p (P x) b lo hi) ->\n      footprint_perm' p (sepall P xs) b lo hi.\n  Proof.\n    induction xs as [|x xs IH].\n    now (intros; apply footprint_perm_sepemp).\n    intros b lo hi Hfp.\n    simpl. apply footprint_perm_sepconj.\n    - apply Hfp.\n    - apply IH with (1:=Hfp).\n  Qed.\n\n  Hint Resolve decidable_footprint_sepall footprint_perm_sepall.\n\n  Lemma sepall_unwand:\n  forall xs P Q,\n    (forall x, decidable_footprint (P x)) ->\n    (sepall P xs ** sepall (fun x => P x -* Q x) xs) -*> sepall Q xs.\n  Proof.\n    induction xs; simpl; intros * Hdec.\n    - now rewrite sepemp_left.\n    - rewrite sep_assoc, sep_swap23, <-sep_assoc.\n      apply sep_imp'.\n      + apply sep_unwand.\n        apply Hdec.\n      + apply IHxs; auto.\n  Qed.\n\n  Lemma subseteq_footprint_sepall:\n    forall p q xs,\n      (forall x, In x xs -> subseteq_footprint (p x) (q x)) ->\n      subseteq_footprint (sepall p xs) (sepall q xs).\n  Proof.\n    intros p q xs Hsub.\n    induction xs as [|x xs IH].\n    now apply subseteq_footprint_refl.\n    simpl. apply subseteq_footprint_sepconj.\n    now (apply Hsub; constructor).\n    apply IH.\n    intros x' Hin.\n    apply Hsub. now apply in_cons.\n  Qed.\n\n  Lemma sepall_outwand_cons:\n    forall p q x xs,\n      (forall x, decidable_footprint (p x)) ->\n      (forall x, subseteq_footprint (p x) (q x)) ->\n      (p x ** (p x -* q x)) ** sepall p xs ** (sepall p xs -* sepall q xs)\n      -*> sepall p (x::xs) ** (sepall p (x::xs) -* sepall q (x::xs)).\n  Proof.\n    intros p q x xs Hdec Hsub.\n    rewrite sep_assoc.\n    split.\n    - intros m Hm.\n      rewrite sep_swap23 in Hm.\n      rewrite unify_distinct_wands in Hm.\n      + Opaque sepconj. simpl. Transparent sepconj. now rewrite sep_assoc.\n      + rewrite sep_swap23 in Hm.\n        rewrite <-sep_assoc in Hm.\n        rewrite sep_unwand in Hm; [|now auto].\n        rewrite sep_unwand in Hm; [|now auto].\n        apply Hm.\n      + apply Hsub.\n      + apply subseteq_footprint_sepall.\n        intros.\n        apply Hsub.\n    - intros b ofs Hf.\n      rewrite sep_unwand; [|now auto].\n      rewrite <-sep_assoc, sep_unwand; [|now auto].\n      destruct Hf as [Hfp|Hf].\n      + now rewrite subseteq_footprint_sepall with (q:=q) in Hfp.\n      + now destruct Hf.\n  Qed.\n\nEnd Sepall.\n\nHint Resolve decidable_footprint_sepall footprint_perm_sepall.\n\nInstance sepall_massert_pred_eqv_permutation_eqv_Proper A:\n  Proper (massert_pred_eqv ==> @Permutation.Permutation A ==> massert_eqv)\n         sepall.\nProof.\n  intros p q Heq xs ys Hperm.\n  rewrite sepall_permutation with (1:=Hperm).\n  induction Hperm.\n  - reflexivity.\n  - simpl. now rewrite IHHperm, (massert_pred_eqv_inst _ _ _ Heq).\n  - simpl.\n    repeat rewrite (massert_pred_eqv_inst _ _ _ Heq).\n    repeat apply sepconj_eqv; try reflexivity.\n    induction l; [reflexivity|].\n    simpl.\n    now rewrite IHl, (massert_pred_eqv_inst _ _ _ Heq).\n  - now rewrite IHHperm2.\nQed.\n\n(* * * * * * * * Ranges * * * * * * * * * * * * * * *)\n\nSection SplitRange.\n  Variable env: composite_env.\n  Variable id: ident.\n  Variable co: composite.\n\n  Hypothesis Henv: Ctypes.composite_env_consistent env.\n  Hypothesis Hco: env!id = Some co.\n  Hypothesis Hstruct: co_su co = Struct.\n\n  Definition field_range' (p: permission) (flds: list (AST.ident * type))\n             (b: block) (lo: Z) (fld: AST.ident * type) : massert :=\n    let (id, ty) := fld in\n    match field_offset env id flds with\n      | Errors.OK ofs  => range' p b (lo + ofs) (lo + ofs + sizeof env ty)\n      | Errors.Error _ => sepfalse\n    end.\n\n  Lemma decidable_footprint_field_range:\n    forall p lo b flds,\n      decidable_footprint (sepall (field_range' p flds b lo) flds).\n  Proof.\n    intros.\n    apply decidable_footprint_sepall.\n    intro fld. destruct fld as [x ty].\n    simpl. destruct (field_offset env x flds); auto.\n  Qed.\n\n  Lemma footprint_perm_field_range:\n    forall p flds b pos x b' lo hi,\n      footprint_perm' p (field_range' p flds b pos x) b' lo hi.\n  Proof.\n    intros p flds b pos x b' lo hi.\n    destruct x as [x ty].\n    simpl. destruct (field_offset env x flds); auto.\n  Qed.\n\n  Lemma split_range_fields':\n    forall p b lo flds,\n      NoDupMembers flds ->\n      massert_imp (range' p b lo (lo + sizeof_struct env 0 flds))\n                  (sepall (field_range' p flds b lo) flds).\n  Proof.\n    intros p b lo flds Hndup.\n    cut (forall cur,\n            massert_imp\n              (range' p b (lo + cur)\n                       (lo + sizeof_struct env cur flds))\n              (sepall (fun fld : AST.ident * type =>\n                         let (id0, ty) := fld in\n                         match field_offset_rec env id0 flds cur with\n                         | Errors.OK ofs =>\n                             range' p b (lo + ofs) (lo + ofs + sizeof env ty)\n                         | Errors.Error _ => sepfalse\n                         end) flds)).\n    - intro HH.\n      specialize HH with 0. rewrite Z.add_0_r in HH.\n      apply HH.\n    - induction flds as [|x xs IH]; [now constructor|].\n      destruct x as [id' ty'].\n      apply nodupmembers_cons in Hndup.\n      destruct Hndup as [Hnin Hndup].\n      specialize (IH Hndup).\n      intro cur.\n      Opaque sepconj. simpl.\n      rewrite peq_true.\n      erewrite sepall_swapp.\n      + rewrite range_split'\n        with (mid:=lo + (align cur (alignof env ty') + sizeof env ty')).\n        * apply sep_imp'.\n          2:now apply IH.\n          rewrite range_split'\n          with (mid:=lo + align cur (alignof env ty')).\n          rewrite sep_drop. rewrite Z.add_assoc. reflexivity.\n          split.\n          now apply Z.add_le_mono_l; apply align_le; apply alignof_pos.\n          apply Z.add_le_mono_l.\n          rewrite <-Z.add_0_r at 1. apply Z.add_le_mono_l.\n          apply Z.ge_le. apply sizeof_pos.\n        * split.\n          2:now apply Z.add_le_mono_l; apply sizeof_struct_incr.\n          apply Z.add_le_mono_l.\n          rewrite <-Z.add_0_r at 1. apply Z.add_le_mono.\n          apply align_le. apply alignof_pos.\n          apply Z.ge_le. apply sizeof_pos.\n      + intros fld Hin.\n        destruct fld.\n        rewrite peq_false.\n        reflexivity.\n        intro Heq; subst.\n        apply Hnin.\n        eapply In_InMembers; eassumption.\n  Qed.\n\n  Lemma split_range_fields:\n    forall p b lo,\n      NoDupMembers (co_members co) ->\n      massert_imp (range' p b lo (lo + co_sizeof co))\n                  (sepall (field_range' p (co_members co) b lo) (co_members co)).\n  Proof.\n    intros p b lo Hndup.\n    apply Henv in Hco.\n    rewrite (co_consistent_sizeof _ _ Hco).\n    rewrite (co_consistent_alignof _ _ Hco).\n    rewrite Hstruct.\n    simpl.\n    rewrite range_split'\n    with (mid:=lo + sizeof_struct env 0 (co_members co)).\n    + rewrite split_range_fields' with (1:=Hndup).\n      now rewrite sep_comm, sep_drop.\n    + split.\n      * rewrite <-Z.add_0_r at 1.\n        apply Z.add_le_mono_l.\n        apply sizeof_struct_incr.\n      * apply Z.add_le_mono_l.\n        apply align_le.\n        apply alignof_composite_pos.\n  Qed.\n\nEnd SplitRange.\n\nNotation field_range ge := (field_range' ge Freeable).\nNotation field_range_w ge := (field_range' ge Writable).\n\n(* * * * * * * * Initial memory * * * * * * * * * * * * * * *)\n\nImport Globalenvs.\nImport AST.\nImport Clight.\n\nSection Galloc.\n\n  (* Variables F V : Type. *)\n  Variable p : program (* (fundef F) V *).\n\n  Definition grange (idg : ident * globdef fundef type) :=\n    let (id, g) := idg in\n    match Genv.find_symbol (Genv.globalenv p) id with\n    | None => sepfalse\n    | Some b =>\n      match g with\n      | Gfun f => range' Nonempty b 0 1\n      | Gvar v =>\n        pure (init_data_list_size (gvar_init v) <= Ptrofs.modulus)\n             -* range' (Genv.perm_globvar v) b 0\n                       (init_data_list_size v.(gvar_init))\n      end\n    end.\n\n  Lemma init_grange:\n    forall m0,\n      NoDupMembers p.(prog_defs) ->\n      Genv.init_mem p = Some m0 ->\n      m0 |= sepall grange p.(prog_defs).\n  Proof.\n    pose proof (eq_refl p.(prog_defs)) as Hps.\n    revert Hps. generalize p.(prog_defs) at 2 4.\n    intros ps Hps' m0 Hndups Hinit.\n    assert (exists ps', p.(prog_defs) = ps' ++ ps) as Hps\n        by (exists nil; auto).\n    clear Hps'.\n    induction ps; auto.\n    destruct a as (id, g).\n    destruct Hps as (ps' & Hps).\n    assert (m0 |= sepall grange ps) as IH\n        by (apply IHps; exists (ps' ++ (id, g)::nil);\n            now rewrite <- List_shift_first).\n    clear IHps.\n    assert ((prog_defmap p) ! id = Some g) as Hpdm\n        by (apply prog_defmap_norepet;\n            [now apply NoDup_norepet, fst_NoDupMembers|\n             rewrite Hps; intuition]).\n    apply Genv.find_def_symbol in Hpdm.\n    destruct Hpdm as (b & Hfs & Hfd).\n    apply sepall_cons.\n    repeat constructor; auto.\n    - (* m0 |= grange (id, g) *)\n      simpl. rewrite Hfs.\n      destruct g.\n      + (* g = Gfun f *)\n        apply Genv.find_funct_ptr_iff in Hfd.\n        apply Genv.init_mem_characterization_2 with (2:=Hinit) in Hfd.\n        destruct Hfd as (Hperm & Hperm').\n        repeat constructor.\n        * omega.\n        * rewrite Z.one_succ; apply Zlt_le_succ, Z.gt_lt, two_power_nat_pos.\n        * intros * HH. assert (i = 0) by omega.\n          subst. now apply Mem.perm_cur.\n      + (* g = Gvar v *)\n        apply Genv.find_var_info_iff in Hfd.\n        eapply Genv.init_mem_characterization with (2:=Hinit) in Hfd.\n        destruct Hfd as (Hrp & Hfd).\n        repeat constructor; auto.\n        * reflexivity.\n        * intros i k Hi.\n          apply Mem.perm_cur.\n          unfold wand_footprint in H.\n          apply Mem.perm_unchanged_on with (1:=H); simpl; auto.\n        * inversion_clear 1 as (? & Hf). simpl in *.\n          destruct Hf as (Hb & Hf). subst.\n          eapply Mem.perm_valid_block; eauto.\n    - (* disjoint_footprint (grange (id, g)) (sepall grange ids) *)\n      rewrite Hps in Hndups.\n      apply NoDupMembers_app_cons in Hndups.\n      destruct Hndups as (Hndups1 & Hndups2).\n      apply NotInMembers_app in Hndups1.\n      apply proj1 in Hndups1.\n      clear Hndups2 Hinit Hps Hfd ps'.\n      induction ps; auto using sepemp_disjoint.\n      destruct a as (id' & g').\n      apply NotInMembers_cons in Hndups1.\n      destruct Hndups1 as (Hndups & Hnid').\n      apply sepall_cons in IH.\n      specialize (IHps Hndups (sep_proj2 _ _ _ IH)).\n      apply sep_proj1 in IH.\n      rewrite sepall_cons.\n      apply disjoint_footprint_sepconj.\n      split; auto. clear IHps.\n      intros b' ofs' Hf1 Hf2.\n      simpl in *.\n      rewrite Hfs in Hf1.\n      destruct (Genv.find_symbol (Genv.globalenv p) id') eqn:Hfs'; [|inv IH].\n      apply Genv.global_addresses_distinct with (1:=Hnid') (2:=Hfs) in Hfs'.\n      apply Hfs'.\n      destruct g, g'; inversion_clear Hf1; inversion_clear Hf2;\n        simpl in *; subst; intuition; now subst b b0.\n  Qed.\n\nEnd Galloc.\n\nLemma sep_swap56:\n  forall P Q R S T U V, (P ** Q ** R ** S ** T ** U ** V) <-*-> (P ** Q ** R ** S ** U ** T ** V).\nProof.\n  intros. rewrite (sep_swap T). reflexivity.\nQed.\n\nLemma sep_swap67:\n  forall P Q R S T U V W, (P ** Q ** R ** S ** T ** U ** V ** W) <-*-> (P ** Q ** R ** S ** T ** V ** U ** W).\nProof.\n  intros. rewrite (sep_swap U). reflexivity.\nQed.\n\nLemma sep_swap78:\n  forall P Q R S T U V W X, (P ** Q ** R ** S ** T ** U ** V ** W ** X) <-*-> (P ** Q ** R ** S ** T ** U ** W ** V ** X).\nProof.\n  intros. rewrite (sep_swap V). reflexivity.\nQed.\n", "meta": {"author": "INRIA", "repo": "velus", "sha": "116a88bc71f3608ff43ed967895743e8b9a340e0", "save_path": "github-repos/coq/INRIA-velus", "path": "github-repos/coq/INRIA-velus/velus-116a88bc71f3608ff43ed967895743e8b9a340e0/src/ObcToClight/MoreSeparation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2421161706759958}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import Epsilon.\nRequire Import Init_ext ssrZ ZArith_ext seq_ext uniq_tac machine_int.\nRequire Import multi_int encode_decode integral_type.\nImport MachineInt.\nRequire Import mips_bipl mips_seplog mips_tactics mips_syntax mips_mint.\nImport mips_bipl.expr_m.\nRequire Import simu.\nImport simu.simu_m.\nRequire Import multi_one_u_prg multi_one_u_triple multi_zero_u_safe_termination.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope assoc_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope mips_expr_scope.\nLocal Open Scope mips_cmd_scope.\nLocal Open Scope zarith_ext_scope.\n\nLemma safe_termination_one_u a0 a1 rx x rk d : uniq(rk, rx, a0, a1, r0) ->\n  safe_termination\n  (fun st s h => state_mint (x |=> unsign rk rx \\U+ d) st s h /\\\n                 (0 < '|u2Z ([rk ]_ s)|)%nat)\n  (multi_one_u rk rx a0 a1).\nProof.\nmove=> Hset.\nrewrite /safe_termination.\nmove=> st s h st_s_h.\nset code := multi_one_u _ _ _ _.\nhave [x0 Htermi] : {x0 | Some (s, h) -- code ---> x0}.\n  have [sf Htermi] : {x0 | Some (s, h) -- code ---> x0 /\\ forall s, x0 = Some s -> True}.\n    rewrite /code /multi_one_u.\n    apply exists_seq_P with (fun s => forall s', s = Some s' -> True).\n      apply constructive_indefinite_description.\n      move: (multi_zero_u_safe_termination a0 a1 rx x rk d Hset).\n      case/(_ _ _ _ (proj1 st_s_h)) => sf Htermi_zero_u.\n      by exists (Some sf).\n    destruct si as [[sti hi]|].\n    move=> HP.\n    eapply exists_addiu_seq_P.\n    repeat Reg_upd.\n    rewrite add0i.\n    exists_sw1 l_idx H_l_idx z_idx H_z_idx => //.\n    move=> HP.\n    exists None.\n    split=> //; exact: while.exec_none.\n  exists sf.\n  by case: Htermi.\nhave H1 : u2Z ([ rx ]_ s) + 4 * Z_of_nat '|u2Z ([rk ]_ s)| < \\B^1.\n  apply state_mint_head_unsign_fit with x d st h.\n  by apply st_s_h.\nhave H3 : size (Z2ints 32 '|u2Z ([ rk ]_ s)| ([ x ]_st)%pseudo_expr) =\n  '|u2Z ([rk ]_ s)|.\n  by rewrite size_Z2ints.\nhave Hnk : (0 < '|u2Z ([ rk ]_ s)|)%nat by tauto.\nmove: (multi_one_u_triple _ _ _ _ Hset _ _ _ Hnk H3 H1) => triple_hoare.\napply constructive_indefinite_description'.\napply (triple_exec_precond _ _ _ triple_hoare _ _ _ Htermi\n  (seq.iota '|u2Z ([rx ]_ s) / 4| '|u2Z ([rk ]_ s)|)).\nsplit; first by [].\nsplit.\n- rewrite Z_of_nat_Zabs_nat //; exact: min_u2Z.\n- case: st_s_h => st_s_h _.\n  apply (state_mint_var_mint _ _ _ _ x (unsign rk rx)) in st_s_h; last by assoc_get_Some.\n  by apply st_s_h.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/begcd/multi_one_u_safe_termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.24209872836375476}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonDefinitions.\nRequire Import VerdiRaft.TraceUtil.\n\nSection AppliedImpliesInputInterface.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Section inner.\n    Variable client : clientId.\n    Variable id : nat.\n    Variable i : input.\n\n    Definition correct_entry (e : entry) : Prop :=\n      eClient e = client /\\\n      eId e = id /\\\n      eInput e = i.\n\n    Definition applied_implies_input_state (net : network) : Prop :=\n      exists e,\n        correct_entry e /\\\n        ((exists h, In e (log (nwState net h))) \\/\n         (exists p entries, In p (nwPackets net) /\\\n                            mEntries (pBody p) = Some entries /\\\n                            In e entries)).\n\n  End inner.\n\n  Class applied_implies_input_interface : Prop :=\n    {\n      applied_implies_input :\n        forall client id failed net tr e,\n          step_failure_star step_failure_init (failed, net) tr ->\n          eClient e = client ->\n          eId e = id ->\n          applied_implies_input_state client id (eInput e) net ->\n          in_input_trace client id (eInput e) tr\n    }.\nEnd AppliedImpliesInputInterface.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft/AppliedImpliesInputInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891307678321, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2420987224313393}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.funcptr.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nLocal Open Scope Z.\nLocal Open Scope logic.\n\nDefinition myspec :=\n  WITH i: Z\n  PRE [ tint ]\n          PROP (Int.min_signed <= i < Int.max_signed)\n          PARAMS (Vint (Int.repr i))\n          SEP ()\n  POST [ tint ]\n         PROP() RETURN (Vint (Int.repr (i+1)))\n          SEP().\n\nDefinition myfunc_spec := DECLARE _myfunc myspec.\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre prog tt gv\n  POST [ tint ] main_post prog gv.\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [\n    myfunc_spec; main_spec]).\n\nLemma body_myfunc: semax_body Vprog Gprog f_myfunc myfunc_spec.\nProof.\nunfold myfunc_spec.\nunfold myspec.\nstart_function.\nforward.\nQed.\n\nLemma body_main: semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function. fold cc_default noattr tint.\nmake_func_ptr _myfunc.\nforward.\n\nforward_call 3.\nforward.\nQed.\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/progs/verif_funcptr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24209872243133926}}
{"text": "(* PREAMBLE *)\n\nFrom compcert.cfrontend  Require Csyntax Csem.\nFrom Coq                 Require Bool.\nFrom trancert.lib        Require Algebraic Decidability Tac.\nFrom trancert.properties Require AST.\n\nImport Bool Csyntax Csem Decidability Algebraic AST Tac.\n\n(** *Subexpressions analysis *)\n\nSection Predicate.\n\n  Variable P: expr -> Prop.\n\n  Inductive subexpr_cond:  expr -> Prop :=\n  | ecs_field: forall f ty l,\n      subexpr_cond l  ->\n      subexpr_cond (Efield l f ty)\n  | ecs_valof: forall ty l ,\n      subexpr_cond l ->\n      subexpr_cond (Evalof l  ty)\n  | ecs_deref: forall ty l,\n      subexpr_cond l ->\n      subexpr_cond (Ederef l  ty)\n  | ecs_addrof: forall ty l,\n      subexpr_cond l ->\n      subexpr_cond (Eaddrof l  ty)\n  | ecs_unop: forall ty l op,\n      subexpr_cond l ->\n      subexpr_cond (Eunop op l  ty)\n  | ecs_binop: forall ty l r op,\n      subexpr_cond l \\/ subexpr_cond r->\n      subexpr_cond (Ebinop op l r ty)\n  | ecs_cast: forall ty l ,\n      subexpr_cond l ->\n      subexpr_cond (Ecast  l  ty)\n  | ecs_seqand: forall ty l r ,\n      subexpr_cond l \\/ subexpr_cond r ->\n      subexpr_cond (Eseqand l r ty)\n  | ecs_seqor: forall ty l r ,\n      subexpr_cond l \\/ subexpr_cond r ->\n      subexpr_cond (Eseqor l r ty)\n  | ecs_condition: forall ty c l r ,\n      subexpr_cond c \\/ subexpr_cond l \\/ subexpr_cond r ->\n      subexpr_cond (Econdition c l r ty)\n  | ecs_assign: forall ty l r ,\n      subexpr_cond l \\/ subexpr_cond r->\n      subexpr_cond (Eassign l r ty)\n  | ecs_assignop:\n      forall ty1 ty2 l r op ,\n        subexpr_cond l \\/ subexpr_cond r ->\n        subexpr_cond (Eassignop op l r ty1 ty2)\n  | ecs_postincr: forall id l ty,\n        subexpr_cond l ->\n        subexpr_cond (Epostincr id l ty)\n  | ecs_comma: forall ty l r ,\n      subexpr_cond l \\/ subexpr_cond r ->\n      subexpr_cond (Ecomma l r ty)\n  | ecs_paren:\n      forall ty1 ty2 r ,\n        subexpr_cond r ->\n        subexpr_cond (Eparen r ty1 ty2)\n  | ecs_call: forall ty r rargs,\n      subexpr_cond r \\/ subexprlist_cond rargs ->\n      subexpr_cond (Ecall r rargs ty)\n  | ecs_builtin: forall rargs tyargs ty ef,\n      subexprlist_cond rargs ->\n      subexpr_cond (Ebuiltin ef tyargs rargs ty)\n  | ecs_found: forall e, P e -> subexpr_cond e\n  with subexprlist_cond: exprlist -> Prop :=\n  | elcs_econs: forall e es,\n      subexpr_cond e \\/ subexprlist_cond es ->\n      subexprlist_cond (Econs e es).\n\n  Hypothesis Hdec: forall e, dec (P e).\n\n  Local Hint Constructors sumbool: subexpr.\n  Local Hint Constructors subexpr_cond: subexpr.\n  Local Hint Constructors subexprlist_cond: subexpr.\n\n  Theorem subexpr_cond_dec :\n    forall e, dec (subexpr_cond e)\n    with subexprlist_cond_dec:\n           forall e, dec (subexprlist_cond e)\n  .\n  Proof.\n    {\n      clear subexpr_cond_dec.\n      unfold dec in *.\n\n      induction e; intros;\n        try solve [\n              match goal with\n                      | [ |- context [subexpr_cond ?x]] =>\n                        destruct (Hdec x);\n                        try destruct IHe;\n                        try destruct IHe1;\n                        try destruct IHe2;\n                        try destruct IHe3\n                      end; auto with subexpr;\n              constructor 2; inversion_clear 1; decomp; contradiction\n            ].\n      - match goal with\n        | [ |- context [subexpr_cond ?x]] =>\n          destruct (Hdec x), IHe, (subexprlist_cond_dec rargs); auto with subexpr\n        end.\n        constructor 2; inversion_clear 1; decomp; contradiction.\n      - match goal with\n        | [ |- context [subexpr_cond ?x]] =>\n          destruct (Hdec x), (subexprlist_cond_dec rargs); auto with subexpr\n        end.\n        constructor 2; inversion_clear 1; contradiction.\n    }\n    {\n      clear subexprlist_cond_dec.\n      unfold dec in *.\n      induction e.\n      - right. inversion 1.\n      - destruct (Hdec r1), IHe, (subexpr_cond_dec r1); auto with subexpr.\n        constructor 2; inversion_clear 1; decomp; contradiction.\n    }\n  Defined.\n\nEnd Predicate.\n\n\n\n(*\n\n  Inductive subexpr_cond:  expr -> expr -> Prop :=\n| ecs_found: forall e, P e -> subexpr_cond e e\n| ecs_field: forall f ty l e,\n    subexpr_cond l e ->\n    subexpr_cond (Efield l f ty) e\n| ecs_valof: forall ty l e,\n    subexpr_cond l e ->\n    subexpr_cond (Evalof l  ty) e\n| ecs_deref: forall ty l e,\n    subexpr_cond l e ->\n    subexpr_cond (Ederef l  ty) e\n| ecs_addrof: forall ty l e,\n    subexpr_cond l e ->\n    subexpr_cond (Eaddrof l  ty) e\n| ecs_unop: forall ty l e op,\n    subexpr_cond l e ->\n    subexpr_cond (Eunop op l  ty) e\n| ecs_binop_l: forall ty l r e op,\n    subexpr_cond l e ->\n    subexpr_cond (Ebinop op l r ty) e\n| ecs_binop_r: forall ty l r e op,\n    subexpr_cond r e ->\n    subexpr_cond (Ebinop op l r ty) e\n| ecs_cast: forall ty l e ,\n    subexpr_cond l e ->\n    subexpr_cond (Ecast  l  ty) e\n| ecs_seqand_l: forall ty l r e ,\n    subexpr_cond l e ->\n    subexpr_cond (Eseqand l r ty) e\n| ecs_seqand_r: forall ty l r e ,\n    subexpr_cond r e ->\n    subexpr_cond (Eseqand l r ty) e\n| ecs_seqor_l: forall ty l r e ,\n    subexpr_cond l e ->\n    subexpr_cond (Eseqor l r ty) e\n| ecs_seqor_r: forall ty l r e ,\n    subexpr_cond r e ->\n    subexpr_cond (Eseqor l r ty) e\n| ecs_condition_c:\n    forall ty c l r e , subexpr_cond c e ->\n    subexpr_cond (Econdition c l r ty) e\n| ecs_condition_l:\n    forall ty c l r e , subexpr_cond l e ->\n    subexpr_cond (Econdition c l r ty) e\n| ecs_condition_r:\n    forall ty c l r e, subexpr_cond r e ->\n    subexpr_cond (Econdition c l r ty) e\n| ecs_assign_l:\n    forall ty l r e , subexpr_cond l e ->\n    subexpr_cond (Eassign l r ty) e\n| ecs_assign_r:\n    forall ty l r e , subexpr_cond r e ->\n    subexpr_cond (Eassign l r ty) e\n| ecs_assignop_l:\n    forall ty1 ty2 l r e op , subexpr_cond l e ->\n    subexpr_cond (Eassignop op l r ty1 ty2) e\n| ecs_assignop_r:\n    forall ty1 ty2 l r e op , subexpr_cond r e ->\n    subexpr_cond (Eassignop op l r ty1 ty2) e\n| ecs_postincr:\n    forall id l ty e, subexpr_cond l e ->\n    subexpr_cond (Epostincr id l ty) e\n| ecs_comma_l:\n    forall ty l r e , subexpr_cond l e ->\n    subexpr_cond (Ecomma l r ty) e\n| ecs_comma_r:\n    forall ty l r e , subexpr_cond r e ->\n    subexpr_cond (Ecomma l r ty) e\n| ecs_paren:\n    forall ty1 ty2 r e , subexpr_cond r e ->\n    subexpr_cond (Eparen r ty1 ty2) e\n| ecs_call_r:\n    forall ty r e rargs, subexpr_cond r e ->\n    subexpr_cond (Ecall r rargs ty) e\n| ecs_call_l:\n    forall ty r e rargs, subexprlist_cond rargs e ->\n    subexpr_cond (Ecall r rargs ty) e\n| ecs_builtin:\n    forall e rargs tyargs ty ef, subexprlist_cond rargs e ->\n    subexpr_cond (Ebuiltin ef tyargs rargs ty) e\nwith subexprlist_cond: exprlist ->expr -> Prop :=\n     | elcs_econs_l:\n         forall e e' es, subexpr_cond e e' ->\n         subexprlist_cond (Econs e es) e'\n     | elcs_econs_r:\n         forall e e' es, subexprlist_cond es e' ->\n         subexprlist_cond (Econs e es) e' .\n\n*)\n", "meta": {"author": "sayon", "repo": "trancert", "sha": "eb5c94c75067782158522f61bdd7cc902bf74185", "save_path": "github-repos/coq/sayon-trancert", "path": "github-repos/coq/sayon-trancert/trancert-eb5c94c75067782158522f61bdd7cc902bf74185/analysis/Subexpr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24209871649892373}}
{"text": "(* Open Source License *)\n(* Copyright (c) 2019 Nomadic Labs. <contact@nomadic-labs.com> *)\n\n(* Permission is hereby granted, free of charge, to any person obtaining a *)\n(* copy of this software and associated documentation files (the \"Software\"), *)\n(* to deal in the Software without restriction, including without limitation *)\n(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)\n(* and/or sell copies of the Software, and to permit persons to whom the *)\n(* Software is furnished to do so, subject to the following conditions: *)\n\n(* The above copyright notice and this permission notice shall be included *)\n(* in all copies or substantial portions of the Software. *)\n\n(* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *)\n(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)\n(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)\n(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *)\n(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)\n(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)\n(* DEALINGS IN THE SOFTWARE. *)\n\n\n(* Finite maps implemented as finite sets of pairs. *)\n\nRequire set.\nRequire Import error.\nImport error.Notations.\n\nSection map.\n\n  Variable A : Set.\n  Variable B : Set.\n  Variable compare : A -> A -> comparison.\n\n  Hypothesis compare_eq_iff : forall a b, compare a b = Eq <-> a = b.\n  Hypothesis lt_trans : Relations_1.Transitive (fun a b => compare a b = Lt).\n  Hypothesis gt_trans : Relations_1.Transitive (fun a b => compare a b = Gt).\n\n  Lemma compare_refl a : compare a a = Eq.\n  Proof.\n    apply (compare_eq_iff a a).\n    reflexivity.\n  Qed.\n\n  Lemma compare_diff : forall a b, compare a b = Lt \\/ compare a b = Gt <-> a <> b.\n  Proof.\n    intros. split.\n    - (* -> *)\n      intros [Hdiff|Hdiff] contra;\n      rewrite <- compare_eq_iff in contra; rewrite Hdiff in contra; discriminate contra.\n    - (* <- *)\n      intro Hdiff. destruct (compare a b) eqn:Hab.\n      + apply compare_eq_iff in Hab. contradiction.\n      + left. reflexivity.\n      + right. reflexivity.\n  Qed.\n\n  Definition map_compare (x_ y_ : A * B) :=\n    match x_, y_ with (x, _), (y, _) => compare x y end.\n\n  Definition map := set.set (A * B) map_compare.\n\n  Fixpoint list_mem (x : A) (l : list (A * B)) : bool :=\n    match l with\n    | nil => false\n    | cons y l =>\n      let (k, v) := y in\n      match compare x k with\n      | Lt => false\n      | Eq => true\n      | Gt => list_mem x l\n      end\n    end.\n\n  Definition mem (x : A) (m : map) : bool :=\n    let (l, _) := m in list_mem x l.\n\n  Fixpoint list_remove (x : A) (l : list (A * B)) : list (A * B) :=\n    match l with\n    | nil => nil\n    | cons y l =>\n      let (k, v) := y in\n      match compare x k with\n      | Lt => cons y l\n      | Eq => l\n      | Gt => cons y (list_remove x l)\n      end\n    end.\n\n  Lemma remove_in x v y l : List.In (x, v) (list_remove y l) -> List.In (x, v) l.\n  Proof.\n    induction l as [|(z, v') l]; simpl.\n    - auto.\n    - case_eq (compare y z).\n      + intuition.\n      + intros Hlt Hin.\n        simpl in Hin.\n        assumption.\n      + intros Hgt Hin.\n        simpl in Hin.\n        intuition.\n  Qed.\n\n  Fixpoint list_replace (x : A) (v : B) (l : list (A * B)) : list (A * B) :=\n    match l with\n    | nil => cons (x, v) nil\n    | cons y l =>\n      let (k, _) := y in\n      match compare x k with\n      | Lt => cons (x, v) (cons y l)\n      | Eq => cons (x, v) l\n      | Gt => cons y (list_replace x v l)\n      end\n    end.\n\n  Lemma list_replace_same x v v' l :\n    Sorted.StronglySorted (set.lt _ map_compare) l ->\n    List.In (x, v) (list_replace x v' l) <-> v = v'.\n  Proof.\n    induction l as [|(y, v'') l].\n    - simpl.\n      intuition congruence.\n    - simpl.\n      case_eq (compare x y).\n      + intros He Hs.\n        apply Sorted.StronglySorted_inv in Hs.\n        destruct Hs as (Hs, Hf).\n        rewrite compare_eq_iff in He.\n        simpl.\n        split.\n        * intros [He2|Hin].\n          {\n            congruence.\n          }\n          {\n            rewrite List.Forall_forall in Hf.\n            specialize (Hf (x, v) Hin).\n            unfold set.lt, map_compare in Hf.\n            symmetry in He.\n            rewrite <- compare_eq_iff in He.\n            congruence.\n          }\n        * intro; left; congruence.\n      + intros Hlt Hs.\n        apply Sorted.StronglySorted_inv in Hs.\n        destruct Hs as (Hs, Hf).\n        simpl.\n        split.\n        * intros [He2|Hin].\n          {\n            congruence.\n          }\n          {\n            rewrite List.Forall_forall in Hf.\n            specialize (Hf (x, v)).\n            unfold set.lt, map_compare in Hf.\n            simpl in Hin.\n            destruct Hin as [He|Hin].\n            - injection He.\n              intros _ He2.\n              symmetry in He2.\n              rewrite <- compare_eq_iff in He2.\n              congruence.\n            - specialize (Hf Hin).\n              assert (compare x x = Lt) by (apply (lt_trans x y x); assumption).\n              assert (compare x x = Eq) by (apply (compare_eq_iff x x); reflexivity).\n              congruence.\n          }\n        * intro He.\n          destruct He.\n          left; reflexivity.\n      + simpl.\n        intros Hgt Hs.\n        rewrite IHl.\n        * split; [|intuition].\n          intros [He|He]; [|auto].\n          injection He.\n          intros _ He2.\n          symmetry in He2.\n          rewrite <- compare_eq_iff in He2.\n          congruence.\n        * inversion Hs.\n          assumption.\n  Qed.\n\n  Lemma list_replace_diff x v y v' l :\n    Sorted.StronglySorted (set.lt _ map_compare) l ->\n    x <> y ->\n    List.In (x, v) (list_replace y v' l) <-> List.In (x, v) l.\n  Proof.\n    induction l as [|(z, v'') l]; simpl.\n    - intuition congruence.\n    - intros Hs Hd.\n      case_eq (compare y z).\n      + intro He.\n        simpl.\n        rewrite compare_eq_iff in He.\n        destruct He.\n        intuition congruence.\n      + intro Hlt.\n        simpl.\n        intuition congruence.\n      + intro Hgt.\n        simpl.\n        rewrite IHl.\n        * intuition congruence.\n        * inversion Hs.\n          assumption.\n        * assumption.\n  Qed.\n\n  Lemma list_replace_in x v y v' l :\n    Sorted.StronglySorted (set.lt _ map_compare) l ->\n    List.In (x, v) (list_replace y v' l) <->\n      (match compare x y with Eq => v = v' | _ => List.In (x, v) l end).\n  Proof.\n    case_eq (compare x y).\n    - intro He.\n      apply compare_eq_iff in He.\n      destruct He.\n      apply list_replace_same.\n    - intros Hlt Hs.\n      apply list_replace_diff.\n      + assumption.\n      + intro He.\n        rewrite <- compare_eq_iff in He.\n        congruence.\n    - intros Hgt Hs.\n      apply list_replace_diff.\n      + assumption.\n      + intro He.\n        rewrite <- compare_eq_iff in He.\n        congruence.\n  Qed.\n\n  Definition list_update (x : A) (vo : option B) (l : list (A * B)) : list (A * B) :=\n    match vo with\n    | None => list_remove x l\n    | Some v => list_replace x v l\n    end.\n\n  Program Definition update (x : A) (vo : option B) (m : map) : map :=\n    let (l, _) := m in\n    exist _ (list_update x vo l) _.\n  Next Obligation.\n    destruct vo as [v|]; simpl.\n    - induction l as [|(k, v') l]; simpl.\n      + constructor.\n        * assumption.\n        * constructor.\n      + apply Sorted.StronglySorted_inv in H.\n        destruct H as (Hl, Hf).\n        specialize (IHl Hl).\n        case_eq (compare x k).\n        * intro He.\n          apply compare_eq_iff in He.\n          destruct He.\n          constructor.\n          {\n            assumption.\n          }\n          {\n            rewrite List.Forall_forall.\n            intros (z, v'') Hin.\n            rewrite List.Forall_forall in Hf.\n            specialize (Hf (z, v'') Hin).\n            generalize Hf.\n            unfold set.lt, map_compare.\n            auto.\n          }\n        * intro Hxk.\n          constructor.\n          {\n            constructor; assumption.\n          }\n          {\n            apply List.Forall_forall.\n            intros (z, v'') Hin.\n            rewrite List.Forall_forall in Hf.\n            specialize (Hf (z, v'')).\n            simpl in Hin.\n            destruct Hin as [He | Hin].\n            - injection He.\n              intros _ He2.\n              destruct He2.\n              exact Hxk.\n            - apply (lt_trans _ k).\n              + assumption.\n              + apply Hf.\n                assumption.\n          }\n        * intro Hgt.\n          constructor; try assumption.\n          apply List.Forall_forall.\n          intros (y,  v'').\n          rewrite list_replace_in; try assumption.\n          case_eq (compare y x).\n          {\n            intro He.\n            rewrite compare_eq_iff in He.\n            destruct He.\n            intros _.\n            unfold set.lt, map_compare.\n            apply set.compare_gt_lt; assumption.\n          }\n          {\n            intro Hlt.\n            rewrite List.Forall_forall in Hf.\n            exact (Hf (y, v'')).\n          }\n          {\n            intros Hgt2 _.\n            unfold set.lt, map_compare.\n            apply set.compare_gt_lt; try assumption.\n            apply (gt_trans _ x); assumption.\n          }\n    - induction l as [|(k, v') l]; simpl.\n      + assumption.\n      + case_eq (compare x k).\n        * intros _.\n          inversion H.\n          assumption.\n        * intros _.\n          assumption.\n        * apply Sorted.StronglySorted_inv in H.\n          destruct H as (Hs, Hf).\n          intro Hgt.\n          constructor.\n          {\n            auto.\n          }\n          {\n            apply List.Forall_forall.\n            intros (y, v'').\n            intro Hy.\n            apply remove_in in Hy.\n            rewrite List.Forall_forall in Hf.\n            exact (Hf _ Hy).\n          }\n  Qed.\n\n  Program Definition empty : map :=\n    exist _ nil _.\n  Next Obligation.\n    constructor.\n  Defined.\n\n  Fixpoint list_get (x : A) (l : list (A * B)) : option B :=\n    match l with\n    | nil => None\n    | cons y l =>\n      let (k, v) := y in\n      match compare x k with\n      | Lt => None\n      | Eq => Some v\n      | Gt => list_get x l\n      end\n    end.\n\n  Definition get (x : A) (m : map) : option B :=\n    let (l, _) := m in list_get x l.\n\n  Lemma StronglySorted_inv_iff (A' : Type) (R : A' -> A' -> Prop) (a : A')\n        (l : list A') :\n       Sorted.StronglySorted R (a :: l) <->\n       Sorted.StronglySorted R l /\\ List.Forall (R a) l.\n  Proof.\n    split.\n    - apply Sorted.StronglySorted_inv.\n    - generalize Sorted.SSorted_cons.\n      intuition.\n  Qed.\n\n  Lemma forall_cons (A' : Type) (P : A' -> Prop) (a : A') (l : list A') :\n    List.Forall P (cons a l) <-> (P a /\\ List.Forall P l).\n  Proof.\n    split.\n    - intro H.\n      inversion H.\n      split; assumption.\n    - intros (HPa, Hf).\n      constructor; assumption.\n  Qed.\n\n  Lemma list_sorted_map_fst (l : list (A * B)) :\n    Sorted.StronglySorted (fun x y => map_compare x y = Lt) l <->\n    Sorted.StronglySorted (fun x y => compare x y = Lt) (List.map fst l).\n  Proof.\n    induction l as [|(x, v) l]; simpl.\n    - split; constructor.\n    - rewrite StronglySorted_inv_iff.\n      rewrite StronglySorted_inv_iff.\n      rewrite IHl.\n      clear IHl.\n      assert (List.Forall (fun y : A * B => map_compare (x, v) y = Lt) l <->\n              List.Forall (fun y : A => compare x y = Lt) (List.map fst l)) as H.\n      + induction l as [|(y, v') l]; simpl.\n        * split; constructor.\n        * rewrite forall_cons.\n          rewrite forall_cons.\n          rewrite IHl.\n          intuition.\n      + rewrite H.\n        intuition.\n  Qed.\n\n  Definition size (m : map) : nat :=\n    let (l, _) := m in List.length l.\n\n  Lemma list_get_lt a b l :\n    List.Forall (fun y => map_compare (a, b) y = Lt) l ->\n    Sorted.StronglySorted (fun x y => map_compare x y = Lt) l ->\n    list_get a l = None.\n  Proof.\n    intros Hf Hl.\n    destruct l as [|(a2, b2) l].\n    - reflexivity.\n    - simpl.\n      rewrite List.Forall_forall in Hf.\n      specialize (Hf (a2, b2) (or_introl eq_refl)).\n      simpl in Hf.\n      rewrite Hf.\n      reflexivity.\n  Qed.\n\n  Lemma extensionality (m1 m2 : map) :\n    (forall x, get x m1 = get x m2) -> m1 = m2.\n  Proof.\n    destruct m1 as (l1, H1).\n    destruct m2 as (l2, H2).\n    simpl.\n    intro Hf.\n    assert (l1 = l2).\n    - generalize l2 H2 Hf; clear l2 H2 Hf; induction l1 as [|(a1, b1) l1]; intros [|(a2, b2) l2] H2 Hf.\n      + reflexivity.\n      + exfalso.\n        specialize (Hf a2).\n        simpl in Hf.\n        rewrite compare_refl in Hf.\n        discriminate.\n      + exfalso.\n        specialize (Hf a1).\n        simpl in Hf.\n        rewrite compare_refl in Hf.\n        discriminate.\n      + assert (a1 = a2 /\\ b1 = b2).\n        * generalize (Hf a1); intro Ha1.\n          simpl in Ha1.\n          rewrite compare_refl in Ha1.\n          generalize (Hf a2); intro Ha2.\n          simpl in Ha2.\n          rewrite compare_refl in Ha2.\n          case_eq (compare a1 a2).\n          -- intro He.\n             rewrite compare_eq_iff in He.\n             split; [assumption|].\n             subst a2.\n             rewrite compare_refl in Ha1.\n             injection Ha1.\n             auto.\n          -- intro Hlt.\n             rewrite Hlt in Ha1.\n             discriminate.\n          -- intro Hgt.\n             rewrite Hgt in Ha1.\n             rewrite <- set.compare_gt_lt in Hgt;\n               [|assumption|assumption|assumption].\n             rewrite Hgt in Ha2.\n             discriminate.\n        * destruct H; subst a2; subst b2.\n          f_equal.\n          apply IHl1.\n          -- inversion H1.\n             assumption.\n          -- inversion H2.\n             assumption.\n          -- intro a3.\n             specialize (Hf a3).\n             simpl in Hf.\n             case_eq (compare a3 a1).\n             ** intro Heq.\n                rewrite compare_eq_iff in Heq.\n                subst a3.\n                rewrite (list_get_lt a1 b1 l1); [|inversion H1; assumption|inversion H1; assumption].\n                rewrite (list_get_lt a1 b1 l2); [|inversion H2; assumption|inversion H2; assumption].\n                reflexivity.\n             ** intro Hlt.\n                rewrite (list_get_lt a3 b1 l1);\n                  [rewrite (list_get_lt a3 b1 l2)| |].\n                --- reflexivity.\n                --- apply (@List.Forall_impl _ (fun y => map_compare (a1, b1) y = Lt)); [|inversion H2; assumption].\n                    intros (a4, b4).\n                    simpl.\n                    apply lt_trans.\n                    assumption.\n                --- inversion H2; assumption.\n                --- apply (@List.Forall_impl _ (fun y => map_compare (a1, b1) y = Lt)); [|inversion H1; assumption].\n                    intros (a4, b4).\n                    simpl.\n                    apply lt_trans.\n                    assumption.\n                --- inversion H1; assumption.\n             ** intro Hgt.\n                rewrite Hgt in Hf.\n                exact Hf.\n    - destruct H.\n      f_equal.\n      apply set.sorted_irrel.\n  Qed.\n\n  (* Interesting lemmas to use when working with maps *)\n\n  Lemma map_getmem : forall k m v, \n      get k m = Some v -> mem k m.\n  Proof.\n    intros.\n    destruct m as [l]. simpl. simpl in H.\n    induction l.\n    - (* nil *)\n      simpl in H. inversion H.\n    - (* h :: t *)\n      simpl. simpl in H.\n      destruct a as [k' v']. destruct (compare k k').\n      + (* Eq *) constructor.\n      + (* Lt *) inversion H.\n      + (* Gt *) apply IHl. inversion s. assumption. assumption.\n  Qed.\n\n  Lemma map_memget : forall k m,\n      mem k m -> exists v, get k m = Some v.\n  Proof.\n    intros.\n    destruct m as [l]. simpl. simpl in H.\n    induction l.\n    - (* nil *)\n      exfalso. simpl in H. inversion H.\n    - (* h :: t *)\n      inversion s; subst.\n      specialize (IHl H2).\n      simpl in H. simpl.\n      destruct a as [k' v']. destruct (compare k k').\n      + (* Eq *) exists v'. reflexivity.\n      + (* Lt *) inversion H.\n      + (* Gt *)\n        specialize (IHl H). destruct IHl as [v'' IHl].\n        exists v''. assumption.\n  Qed.\n\n  Lemma map_updateeq : forall k m v,\n      get k (update k (Some v) m) = (Some v).\n  Proof.\n    intros.\n    destruct m as [l]. unfold get, update.\n    assert ((compare k k) = Eq) as Hkk by (apply compare_eq_iff; reflexivity).\n    induction l.\n    - (* nil *)\n      simpl. rewrite Hkk. reflexivity.\n    - (* h :: t *)\n      simpl. inversion s; subst.\n      specialize (IHl H1). simpl in IHl.\n      destruct a as [k' v'].\n      destruct (compare k k') eqn:Hkk'; simpl.\n      + (* Eq *) simpl. rewrite Hkk. reflexivity.\n      + (* Lt *) simpl. rewrite Hkk. reflexivity.\n      + (* Gt *) rewrite Hkk'. assumption.\n  Qed.\n\n  Lemma map_updateneq : forall k k' m v,\n      k <> k' ->\n      get k' (update k (Some v) m) =\n      get k' m.\n  Proof.\n    intros.\n    destruct m as [l]. unfold get, update; simpl.\n    induction l; simpl.\n    - (* nil *)\n      destruct (compare k' k) eqn:Hcp; try reflexivity.\n      apply compare_eq_iff in Hcp. symmetry in Hcp. contradiction.\n    - (* h :: t *)\n      inversion s; subst.\n      specialize (IHl H2). simpl in IHl.\n      destruct a as [k'' v''].\n      destruct (compare k k'') eqn:Hkk''; destruct (compare k' k'') eqn:Hk'k''; simpl;\n        try apply compare_eq_iff in Hkk''; try apply compare_eq_iff in Hk'k''; subst;\n          assert (compare k'' k'' = Eq) as Hk'' by (apply compare_eq_iff; reflexivity);\n          try (rewrite Hk'k''; auto).\n      + contradiction.\n      + rewrite Hk''. apply set.compare_gt_lt in Hkk''; try assumption.\n        rewrite Hkk''. reflexivity.\n      + destruct (compare k' k) eqn:Hk'k; try reflexivity.\n        apply compare_eq_iff in Hk'k. symmetry in Hk'k. contradiction.\n      + apply set.compare_gt_lt in Hkk''; try assumption.\n        unfold Relations_1.Transitive in gt_trans.\n        assert (compare k' k = Gt) as Hk'k by (eapply gt_trans; eassumption).\n        rewrite Hk'k. reflexivity.\n      + rewrite Hk''. reflexivity.\n  Qed.\n\n  Lemma map_updateSome_spec : forall k v m nm,\n      nm = update k (Some v) m <->\n      (get k nm = (Some v) /\\\n       (forall k', k <> k' -> map.get k' nm = map.get k' m)).\n  Proof.\n    intros. split.\n    - (* -> *)\n      intros Hnm. subst. split.\n      apply map_updateeq. intros k' Hdiff. apply map_updateneq. assumption.\n    - (* <- *)\n      intros [HSame HDiff].\n      apply map.extensionality; try assumption.\n      intro k'.\n      specialize (compare_diff k k') as HKeyDiff.\n      destruct (compare k k') eqn:Hkk'.\n      + (* Eq *)\n        apply compare_eq_iff in Hkk'; subst.\n        rewrite HSame. symmetry. apply map_updateeq.\n      + (* Lt *)\n        assert (k <> k') by (apply HKeyDiff; left; reflexivity).\n        assert (k <> k') as H2 by assumption.\n        apply HDiff in H. rewrite H. symmetry.\n        apply map_updateneq. assumption.\n      + (* Gt *)\n        assert (k <> k') by (apply HKeyDiff; right; reflexivity).\n        assert (k <> k') as H2 by assumption.\n        apply HDiff in H. rewrite H. symmetry.\n        apply map_updateneq. assumption.\n  Qed.\n\n  Lemma map_updatemem : forall k m v,\n      mem k m ->\n      forall k', mem k (map.update k' (Some v) m).\n  Proof.\n    intros.\n    destruct m as [l]. unfold get, update. simpl. simpl in H.\n    induction l; simpl; simpl in H.\n    - (* nil *) inversion H.\n    - (* h :: t *)\n      inversion s; subst. specialize (IHl H2).\n      destruct a as [k'' v''].\n      destruct (compare k k'') eqn:Hkk''; destruct (compare k' k'') eqn:Hk'k'';\n        simpl in H; simpl;\n          try rewrite compare_eq_iff in Hkk''; try rewrite compare_eq_iff in Hk'k''; subst;\n            assert (compare k'' k'' = Eq) as Hk'' by (apply compare_eq_iff; reflexivity);\n            try inversion H;\n            try rewrite Hk''; try rewrite Hkk''; try exact ITT.\n      + constructor.\n      + apply set.compare_gt_lt in Hk'k''; try assumption.\n        rewrite Hk'k''.\n        constructor.\n      + constructor.\n      + assumption.\n      + apply set.compare_gt_lt in Hk'k''; try assumption.\n        rewrite (gt_trans _ _ _ Hkk'' Hk'k'').\n        assumption.\n      + apply IHl; assumption.\n  Qed.\n\n  Ltac comparison_case k1 k2 H Hmem :=\n    case_eq (compare k1 k2); intro H; simpl in Hmem; try rewrite H in Hmem;\n    [ rewrite compare_eq_iff in H; try assumption | | ].\n\n  Lemma map_updatemem_rev : forall k k' m v,\n      k <> k' ->\n      mem k (map.update k' (Some v) m) ->\n      mem k m.\n  Proof.\n    intros k k' m v Hkk' Hmem.\n    destruct m as [l].\n    simpl in *.\n    induction l as [|(k'', v'') l]; simpl in *.\n    - (* nil *)\n      comparison_case k k' H Hmem.\n      + congruence.\n      + inversion Hmem.\n      + inversion Hmem.\n    - (* h :: t *)\n      comparison_case k' k'' Hk'k'' Hmem;\n        [ subst k'' | comparison_case k k'' Hkk'' Hmem | comparison_case k k'' Hkk'' Hmem ]; simpl in Hmem; comparison_case k k' Hckk' Hmem;\n          try constructor; simpl in *; try (exact Hmem); try (destruct Hmem);\n            try congruence;\n            inversion s; apply IHl; assumption.\n  Qed.\n\nEnd map.\n\nFixpoint list_map (B B' : Set) (f : B -> M B') (l : list B) : M (list B') :=\n  match l with\n  | nil => Return nil\n  | cons x l =>\n    let! b' := f x in\n    let! l' := list_map _ _ f l in\n    Return (cons b' l')\n  end.\n\nDefinition list_map_pair (A B B' : Set) (f : (A * B) -> M B') :\n  list (A * B) -> M (list (A * B')) :=\n  list_map (A * B) (A * B')\n           (fun ab => let! b' := f ab in Return (fst ab, b')).\n\nLemma list_map_fst A B B' f l l' :\n  list_map_pair A B B' f l = Return l' ->\n  List.map fst l = List.map fst l'.\nProof.\n  generalize l'. clear l'.\n  induction l as [|(x, v) l].\n  - simpl.\n    intros l' H.\n    injection H.\n    intro He.\n    destruct He.\n    reflexivity.\n  - simpl.\n    intro l'.\n    unfold list_map_pair.\n    simpl.\n    case_eq (f (x, v)); simpl; try congruence.\n    intros b' He.\n    case_eq (list_map (A * B) (A * B') (fun ab : A * B =>\n        let! b'0 : B' := f ab in Return (fst ab, b'0)) l); simpl; try congruence.\n    intros l'' He2.\n    specialize (IHl l'').\n    intro H3.\n    injection H3.\n    intro Hl'.\n    destruct Hl'.\n    simpl.\n    f_equal.\n    apply IHl.\n    assumption.\nQed.\n\nProgram Definition map_fun_aux (A B B' : Set) compare (f : A * B -> M B') (l : list (A * B))\n        (H : Sorted.StronglySorted (fun x y => map_compare _ _ compare x y = Lt) l): M (map A B' compare) :=\n  match (list_map_pair _ _ _ f l) with\n  | Return l' => Return (exist _ l' _)\n  | Failed _ e => Failed _ e\n  end.\nNext Obligation.\n  unfold set.lt.\n  rewrite list_sorted_map_fst.\n  rewrite <- (list_map_fst _ _ _ f l).\n  + apply list_sorted_map_fst.\n    assumption.\n  + symmetry.\n    assumption.\nDefined.\n\nDefinition map_fun (A B B' : Set) comp\n  (f : A * B -> M B')\n  (m : map A B comp) : M (map A B' comp) :=\n  let (l, H) := m in\n  map_fun_aux _ _ _ comp f l H.\n", "meta": {"author": "spruceid", "repo": "mi-cho-coq", "sha": "eb5a0b469c45472afa87335abee5c1644eb10349", "save_path": "github-repos/coq/spruceid-mi-cho-coq", "path": "github-repos/coq/spruceid-mi-cho-coq/mi-cho-coq-eb5a0b469c45472afa87335abee5c1644eb10349/src/michocoq/map.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24201280108417803}}
{"text": "From mathcomp Require Import ssreflect.\nFrom mathcomp Require order.\nFrom stdpp Require Import gmap.\nFrom iris.algebra Require Import agree auth gset gmap namespace_map.\nFrom iris.base_logic.lib Require Import invariants saved_prop.\nFrom iris.heap_lang Require Import notation proofmode.\nFrom iris.heap_lang.lib Require Import nondet_bool.\nFrom cryptis Require Import lib term cryptis.\nFrom cryptis.primitives Require Import notations comp.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDefinition nondet_int_loop : val := rec: \"loop\" \"n\" :=\n  if: nondet_bool #() then \"n\" else \"loop\" (\"n\" + #1).\n\nDefinition nondet_int : val := λ: <>,\n  let: \"n\" := nondet_int_loop #0 in\n  if: nondet_bool #() then \"n\" else - \"n\".\n\nDefinition send : val := λ: \"c\", Fst \"c\".\nDefinition recv : val := λ: \"c\", Snd \"c\" #().\n\nDefinition tint : val := λ: \"n\",\n  (#TInt_tag, \"n\").\n\nDefinition to_int : val := λ: \"t\",\n  if: Fst \"t\" = #TInt_tag then SOME (Snd \"t\")\n  else NONE.\n\nDefinition tuple : val := λ: \"t1\" \"t2\",\n  (#TPair_tag, (\"t1\", \"t2\")).\n\nDefinition untuple : val := λ: \"t\",\n  if: Fst \"t\" = #TPair_tag then SOME (Snd \"t\")\n  else NONE.\n\nDefinition list_of_term : val := rec: \"loop\" \"t\" :=\n  if: Fst \"t\" = #TInt_tag then\n    if: Snd \"t\" = #0 then SOMEV NONEV else NONEV\n  else if: Fst \"t\" = #TPair_tag then\n    let: \"t\" := Snd \"t\" in\n    bind: \"l\" := \"loop\" (Snd \"t\") in\n    SOME (SOME (Fst \"t\", \"l\"))\n  else NONE.\n\nDefinition term_of_list : val := rec: \"loop\" \"l\" :=\n  match: \"l\" with NONE => (#TInt_tag, #0)\n  | SOME \"p\" => tuple (Fst \"p\") (\"loop\" (Snd \"p\"))\n  end.\n\nDefinition tag (N : namespace) : val := λ: \"t\",\n  tuple (TInt (Zpos (encode N))) \"t\".\n\nDefinition untag (N : namespace) : val := λ: \"t\",\n  bind: \"t\" := untuple \"t\" in\n  bind: \"tag\" := to_int (Fst \"t\") in\n  if: \"tag\" = #(Zpos (encode N))then SOME (Snd \"t\") else NONE.\n\nDefinition mknonce : val := λ: <>,\n  let: <>  := ref #() in\n  let: \"n\" := ref #() in\n  (#TNonce_tag, \"n\").\n\nDefinition is_key : val := λ: \"t\",\n  if: Fst \"t\" = #TKey_tag then SOME (Fst (Snd \"t\"))\n  else NONE.\n\nDefinition enc : val := λ: \"k\" \"t\",\n  if: (Fst \"k\" = #TKey_tag) &&\n      (Fst (Snd \"k\") = #(int_of_key_type Enc)) then\n    (#TEnc_tag, (Snd (Snd \"k\"), \"t\"))\n  else \"t\".\n\nDefinition hash : val := λ: \"t\", (#THash_tag, \"t\").\n\nDefinition dec : val := λ: \"k\" \"t\",\n  if: (Fst \"k\" = #TKey_tag)\n      && (Fst (Snd \"k\") = #(int_of_key_type Dec))\n      && (Fst \"t\" = #TEnc_tag)\n      && (eq_term (Snd (Snd \"k\")) (Fst (Snd \"t\"))) then\n    SOME (Snd (Snd \"t\"))\n  else\n    NONE.\n\nDefinition tenc c : val := λ: \"k\" \"t\",\n  enc \"k\" (tag c \"t\").\n\nDefinition tdec c : val := λ: \"k\" \"t\",\n  bind: \"t\" := dec \"k\" \"t\" in\n  untag c \"t\".\n\nDefinition mkkey : val := λ: \"k\",\n  ((#TKey_tag, (#(int_of_key_type Enc), \"k\")),\n   (#TKey_tag, (#(int_of_key_type Dec), \"k\"))).\n\nDefinition tgroup : val := λ: \"t\",\n  (#TExp_tag, (\"t\", NONEV)).\n\nDefinition to_ek : val := λ: \"t\",\n  bind: \"kt\" := is_key \"t\" in\n  assert: (\"kt\" = repr Enc) in\n  SOME \"t\".\n\nDefinition to_dk : val := λ: \"t\",\n  bind: \"kt\" := is_key \"t\" in\n  assert: (\"kt\" = repr Dec) in\n  SOME \"t\".\n\nSection Proofs.\n\nContext `{!heapG Σ, !cryptisG Σ}.\nNotation nonce := loc.\n\nImplicit Types E : coPset.\nImplicit Types a : nonce.\nImplicit Types t : term.\nImplicit Types v : val.\nImplicit Types Φ : prodO locO termO -n> iPropO Σ.\nImplicit Types Ψ : val → iProp Σ.\nImplicit Types N : namespace.\n\nLemma wp_nondet_int_loop Ψ (m : Z) :\n  (∀ n : Z, Ψ #n) -∗\n  WP nondet_int_loop #m {{ Ψ }}.\nProof.\niIntros \"post\"; iLöb as \"IH\" forall (m); wp_rec.\nwp_bind (nondet_bool _).\niApply nondet_bool_spec => //.\niIntros \"!> %b _\"; case: b; wp_if; first by iApply \"post\".\nby wp_pures; iApply \"IH\".\nQed.\n\nLemma wp_nondet_int Ψ :\n  (∀ n : Z, Ψ #n) -∗\n  WP nondet_int #() {{ Ψ }}.\nProof.\niIntros \"post\"; rewrite /nondet_int; wp_pures.\nwp_bind (nondet_int_loop _); iApply wp_nondet_int_loop.\niIntros \"%n\"; wp_pures; wp_bind (nondet_bool _).\niApply nondet_bool_spec => //.\niIntros \"!> %b _\"; case: b; wp_if; first by iApply \"post\".\nby wp_pures; iApply \"post\".\nQed.\n\nDefinition channel c : iProp Σ :=\n  ∃ (sf rf : val), ⌜c = (sf, rf)%V⌝ ∗\n    □ (∀ E t Ψ, ⌜↑cryptisN ⊆ E⌝ -∗ pterm t -∗ Ψ #() -∗\n                WP sf t @ E {{ Ψ }}) ∗\n    □ (∀ E Ψ, ⌜↑cryptisN ⊆ E⌝ -∗ (∀ t, pterm t -∗ Ψ t) -∗\n              WP rf #() @ E {{ Ψ }}).\n\nGlobal Instance channel_persistent c : Persistent (channel c).\nProof. apply _. Qed.\n\nLemma wp_send E c t Ψ :\n  ↑cryptisN ⊆ E →\n  channel c -∗\n  ▷ pterm t -∗\n  Ψ #() -∗\n  WP send c t @ E {{ Ψ }}.\nProof.\nmove=> sub; iDestruct 1 as (sf cf) \"#(-> & H & _)\".\niIntros \"#??\"; rewrite /send; wp_pures.\nby iApply \"H\".\nQed.\n\nLemma wp_recv E c Ψ :\n  ↑cryptisN ⊆ E →\n  channel c -∗\n  (∀ t, pterm t -∗ Ψ t) -∗\n  WP recv c @ E {{ Ψ }}.\nProof.\nmove=> sub; iDestruct 1 as (sf cf) \"#(-> & _ & H)\".\niIntros \"?\"; rewrite /recv; wp_pures.\nby iApply \"H\".\nQed.\n\nLemma twp_tint E Ψ n : Ψ (TInt n) -∗ WP tint #n @ E [{ Ψ }].\nProof.\nby rewrite /tint val_of_term_eq; iIntros \"Hpost\"; wp_pures.\nQed.\n\nLemma wp_tint E Ψ n : Ψ (TInt n) -∗ WP tint #n @ E {{ Ψ }}.\nProof. by iIntros \"?\"; iApply twp_wp; iApply twp_tint. Qed.\n\nLemma twp_to_int E t Ψ :\n  Ψ (repr (Spec.to_int t)) -∗\n  WP to_int t @ E [{ Ψ }].\nProof.\nrewrite /to_int val_of_term_eq; iIntros \"Hpost\"; wp_pures.\ncase: t; by move=> *; wp_pures; eauto.\nQed.\n\nLemma wp_to_int E t Ψ :\n  Ψ (repr (Spec.to_int t)) -∗\n  WP to_int t @ E {{ Ψ }}.\nProof.\nby iIntros \"?\"; iApply twp_wp; iApply twp_to_int.\nQed.\n\nLemma twp_tuple E t1 t2 Ψ :\n  Ψ (TPair t1 t2) -∗\n  WP tuple t1 t2 @ E [{ Ψ }].\nProof.\nrewrite val_of_term_eq /tuple; by iIntros \"?\"; wp_pures.\nQed.\n\nLemma wp_tuple E t1 t2 Ψ :\n  Ψ (TPair t1 t2) -∗\n  WP tuple t1 t2 @ E {{ Ψ }}.\nProof.\nby iIntros \"?\"; iApply twp_wp; iApply twp_tuple.\nQed.\n\nLemma twp_untuple E t Ψ :\n  Ψ (repr (Spec.untuple t)) -∗\n  WP untuple t @ E [{ Ψ }].\nProof.\niIntros \"post\".\nrewrite /Spec.untuple /untuple /= val_of_term_eq.\ncase: t; by move=> *; wp_pures; iApply \"post\".\nQed.\n\nLemma wp_untuple E t Ψ :\n  Ψ (repr (Spec.untuple t)) -∗\n  WP untuple t @ E {{ Ψ }}.\nProof.\nby iIntros \"?\"; iApply twp_wp; iApply twp_untuple.\nQed.\n\nLemma twp_term_of_list E ts Ψ :\n  Ψ (repr (Spec.of_list ts)) -∗\n  WP term_of_list (repr ts) @ E [{ Ψ }].\nProof.\nrewrite /= [in repr_list ts]repr_list_eq Spec.of_list_eq.\nelim: ts Ψ => [|t ts IH] Ψ /=; iIntros \"post\"; wp_rec; wp_pures.\n  by rewrite val_of_term_eq.\nwp_bind (term_of_list _); iApply IH; wp_pures.\nby iApply twp_tuple.\nQed.\n\nLemma wp_term_of_list E ts Ψ :\n  Ψ (repr (Spec.of_list ts)) -∗\n  WP term_of_list (repr ts) @ E {{ Ψ }}.\nProof.\nby iIntros \"?\"; iApply twp_wp; iApply twp_term_of_list.\nQed.\n\nLemma twp_list_of_term E t Ψ :\n  Ψ (repr (Spec.to_list t)) -∗\n  WP list_of_term t @ E [{ Ψ }].\nProof.\nrewrite val_of_term_eq /= repr_list_eq.\nelim/term_ind': t Ψ;\ntry by move=> *; iIntros \"post\"; wp_rec; wp_pures; iApply \"post\".\n  move=> n Ψ /=; iIntros \"post\"; wp_rec; wp_pures.\n  case: bool_decide_reflect => [[->]|]; first by wp_pures.\n  case: n => *; by wp_pures.\nmove=> thead _ trest IH Ψ /=; iIntros \"post\".\nwp_rec; wp_pures; wp_bind (list_of_term _); iApply IH.\ncase: (Spec.to_list trest) => [ts|] /=; wp_pures; eauto.\nby rewrite -val_of_term_eq.\nQed.\n\nLemma wp_list_of_term E t Ψ :\n  Ψ (repr (Spec.to_list t)) -∗\n  WP list_of_term t @ E {{ Ψ }}.\nProof.\nby iIntros \"?\"; iApply twp_wp; iApply twp_list_of_term.\nQed.\n\nLemma twp_list `{!Repr A} (xs : list A) E Ψ :\n  Ψ (repr xs) -∗\n  WP list_to_expr xs @ E [{ Ψ }].\nProof.\nelim: xs Ψ => [|x xs IH] /= Ψ; iIntros \"post\".\n  by iApply (@twp_nil A _).\nwp_bind (list_to_expr _); iApply IH.\nby iApply (@twp_cons A).\nQed.\n\nLemma wp_list `{!Repr A} (xs : list A) E Ψ :\n  Ψ (repr xs) -∗\n  WP list_to_expr xs @ E {{ Ψ }}.\nProof. by iIntros \"?\"; iApply twp_wp; iApply twp_list. Qed.\n\nLemma twp_tag E N t Ψ :\n  Ψ (repr (Spec.tag N t)) -∗\n  WP tag N t @ E [{ Ψ }].\nProof.\niIntros \"post\".\nby rewrite Spec.tag_eq /tag; wp_pures; iApply twp_tuple.\nQed.\n\nLemma wp_tag E N t Ψ :\n  Ψ (repr (Spec.tag N t)) -∗\n  WP tag N t @ E {{ Ψ }}.\nProof.\niIntros \"post\".\nby rewrite Spec.tag_eq /tag; wp_pures; iApply wp_tuple.\nQed.\n\nLemma twp_untag E N t Ψ :\n  Ψ (repr (Spec.untag N t)) -∗\n  WP untag N t @ E [{ Ψ }].\nProof.\niIntros \"post\".\nrewrite Spec.untag_eq /untag /=; wp_pures.\nwp_bind (untuple _); iApply twp_untuple.\ncase: t; try by [move=> *; wp_pures; iApply \"post\"].\nmove=> t1 t2; wp_pures.\nwp_bind (to_int _); iApply twp_to_int.\ncase: t1; try by [move=> *; wp_pures; iApply \"post\"].\nmove=> n'; wp_pures.\ncase: bool_decide_reflect => [[->]|ne]; wp_pures.\n  by rewrite decide_left.\ncase: n' ne; try by move=> *; iApply \"post\".\nmove=> n' ne; case: decide => e; try iApply \"post\".\ncongruence.\nQed.\n\nLemma wp_untag E N t Ψ :\n  Ψ (repr (Spec.untag N t)) -∗\n  WP untag N t @ E {{ Ψ }}.\nProof.\nby iIntros \"?\"; iApply twp_wp; iApply twp_untag.\nQed.\n\nLemma twp_mknonce E (P Q : term → iProp Σ) Ψ :\n  (∀ t, sterm t -∗\n        □ (pterm t ↔ ▷ □ P t) -∗\n        □ (∀ t', dh_pred t t' ↔ ▷ □ Q t') -∗\n        nonce_meta_token t ⊤ -∗\n        Ψ t) -∗\n  WP mknonce #()%V @ E [{ Ψ }].\nProof.\nrewrite /mknonce; iIntros \"post\".\nwp_pures; wp_bind (ref _)%E; iApply twp_alloc=> //.\niIntros (a') \"[_ token]\"; wp_pures.\nwp_pures; wp_bind (ref _)%E; iApply twp_alloc=> //.\niIntros (a) \"[_ token']\".\niMod (saved_pred_alloc P) as (γP) \"#own_P\".\niMod (saved_pred_alloc Q) as (γQ) \"#own_Q\".\nrewrite (meta_token_difference a (↑nroot.@\"nonce\")) //.\niDestruct \"token'\" as \"[nonce token']\".\niMod (meta_set _ _ γP with \"nonce\") as \"#nonce\"; eauto.\nrewrite (meta_token_difference a (↑nroot.@\"dh\")); last solve_ndisj.\niDestruct \"token'\" as \"[dh token']\".\niMod (meta_set _ _ γQ with \"dh\") as \"#dh\"; eauto.\niMod (meta_set _ _ a' (nroot.@\"meta\") with \"token'\") as \"#meta\"; eauto.\n  solve_ndisj.\niSpecialize (\"post\" $! (TNonce a)).\nrewrite val_of_term_eq /=.\nwp_pures; iApply (\"post\" with \"[] [] [] [token]\"); eauto.\n- rewrite sterm_TNonce; iExists _; eauto.\n- rewrite pterm_TNonce; iModIntro; iSplit.\n  + iDestruct 1 as (γP' P') \"(#meta_γP' & #own_P' & ?)\".\n    iPoseProof (meta_agree with \"nonce meta_γP'\") as \"->\".\n    iPoseProof (saved_pred_agree _ _ _ (TNonce a) with \"own_P own_P'\") as \"e\".\n    by iModIntro; iRewrite \"e\".\n  + iIntros \"#?\"; iExists γP, P; eauto.\n- iIntros (t'); iModIntro; iSplit.\n  + iDestruct 1 as (γQ' Q') \"(#meta_γQ' & #own_Q' & ?)\".\n    iPoseProof (meta_agree with \"dh meta_γQ'\") as \"->\".\n    iPoseProof (saved_pred_agree _ _ _ t' with \"own_Q own_Q'\") as \"e\".\n    by iModIntro; iRewrite \"e\".\n  + by iIntros \"#?\"; iExists _, _; eauto.\nQed.\n\nLemma wp_mknonce E P Q Ψ :\n  (∀ t, sterm t -∗\n        □ (pterm t ↔ ▷ □ P t) -∗\n        □ (∀ t', dh_pred t t' ↔ ▷ □ Q t') -∗\n        nonce_meta_token t ⊤ -∗\n        Ψ t) -∗\n  WP mknonce #()%V @ E {{ Ψ }}.\nProof. by iIntros \"?\"; iApply twp_wp; iApply twp_mknonce. Qed.\n\nLemma twp_mkkey E (k : term) Ψ :\n  Ψ (TKey Enc k, TKey Dec k)%V -∗\n  WP mkkey k @ E [{ Ψ }].\nProof.\nrewrite val_of_term_eq /= /mkkey.\nby iIntros \"post\"; wp_pures.\nQed.\n\nLemma wp_mkkey E (k : term) Ψ :\n  Ψ (TKey Enc k, TKey Dec k)%V -∗\n  WP mkkey k @ E {{ Ψ }}.\nProof.\nby iIntros \"post\"; iApply twp_wp; iApply twp_mkkey.\nQed.\n\nLemma twp_enc E t1 t2 Ψ :\n  Ψ (repr (Spec.enc t1 t2)) -∗\n  WP enc t1 t2 @ E [{ Ψ }].\nProof.\nrewrite /repr /repr_option /repr /repr_term !val_of_term_eq /enc.\niIntros \"H\".\ncase: t1; try by move=> *; wp_pures; eauto.\ncase; try by move=> *; wp_pures; eauto.\nQed.\n\nLemma wp_enc E t1 t2 Ψ :\n  Ψ (repr (Spec.enc t1 t2)) -∗\n  WP enc t1 t2 @ E {{ Ψ }}.\nProof. by iIntros \"?\"; iApply twp_wp; iApply twp_enc. Qed.\n\nLemma twp_hash E t Ψ : Ψ (THash t) -∗ WP hash t @ E [{ Ψ }].\nProof.\nby rewrite /hash val_of_term_eq; iIntros \"?\"; wp_pures.\nQed.\n\nLemma wp_hash E t Ψ : Ψ (THash t) -∗ WP hash t @ E {{ Ψ }}.\nProof. by iIntros \"?\"; iApply twp_wp; iApply twp_hash. Qed.\n\nLemma twp_dec E t1 t2 Ψ :\n  Ψ (repr (Spec.dec t1 t2)) -∗\n  WP dec t1 t2 @ E [{ Ψ }].\nProof.\nrewrite /repr /repr_option /repr /repr_term !val_of_term_eq /dec.\niIntros \"H\".\nwp_pures.\ncase: t1; try by move=> /= *; wp_pures.\ncase; try by move=> /= *; wp_pures.\nmove=> tk; wp_pures.\ncase: t2; try by move=> /= *; wp_pures.\nmove=> tk' t; wp_pures; rewrite -val_of_term_eq.\nwp_bind (eq_term _ _); iApply twp_eq_term.\nby rewrite bool_decide_decide /=; case: decide => [<-|e]; wp_pures.\nQed.\n\nLemma wp_dec E t1 t2 Ψ :\n  Ψ (repr (Spec.dec t1 t2)) -∗\n  WP dec t1 t2 @ E {{ Ψ }}.\nProof. by iIntros \"?\"; iApply twp_wp; iApply twp_dec. Qed.\n\nLemma twp_tenc E N k t Ψ :\n  Ψ (repr (Spec.tenc N k t)) -∗\n  WP tenc N k t @ E [{ Ψ }].\nProof.\niIntros \"post\"; rewrite /tenc; wp_pures.\nwp_bind (tag _ _); iApply twp_tag.\nby iApply twp_enc.\nQed.\n\nLemma wp_tenc E N k t Ψ :\n  Ψ (repr (Spec.tenc N k t)) -∗\n  WP tenc N k t @ E {{ Ψ }}.\nProof. by iIntros \"?\"; iApply twp_wp; iApply twp_tenc. Qed.\n\nLemma twp_tdec E N k t Ψ :\n  Ψ (repr (Spec.tdec N k t)) -∗\n  WP tdec N k t @ E [{ Ψ }].\nProof.\niIntros \"post\"; rewrite /tdec; wp_pures.\nwp_bind (dec _ _); iApply twp_dec.\nrewrite /Spec.tdec.\ncase e: (Spec.dec _ _) => [t'|]; wp_pures => //.\nby iApply twp_untag.\nQed.\n\nLemma wp_tdec E N k t Ψ :\n  Ψ (repr (Spec.tdec N k t)) -∗\n  WP tdec N k t @ E {{ Ψ }}.\nProof. by iIntros \"?\"; iApply twp_wp; iApply twp_tdec. Qed.\n\nLemma twp_is_key E t Ψ :\n  Ψ (repr (Spec.is_key t)) -∗\n  WP is_key t @ E [{ Ψ }].\nProof.\nrewrite /repr /repr_option val_of_term_eq /is_key.\niIntros \"?\"; by case: t=> *; wp_pures.\nQed.\n\nLemma wp_is_key E t Ψ :\n  Ψ (repr (Spec.is_key t)) -∗\n  WP is_key t @ E {{ Ψ }}.\nProof. by iIntros \"?\"; iApply twp_wp; iApply twp_is_key. Qed.\n\nLemma twp_tgroup E t Ψ :\n  Ψ (TExp t []) -∗\n  WP tgroup t @ E [{ Ψ }].\nProof.\niIntros \"post\".\nrewrite /tgroup -val_of_pre_term_unfold; wp_pures.\nrewrite val_of_pre_term_eq /= unfold_TExp /=.\nby rewrite -val_of_pre_term_eq val_of_pre_term_unfold repr_list_eq.\nQed.\n\nLemma wp_tgroup E t Ψ :\n  Ψ (TExp t []) -∗\n  WP tgroup t @ E {{ Ψ }}.\nProof. by iIntros \"?\"; iApply twp_wp; iApply twp_tgroup. Qed.\n\nLemma wp_to_ek E t Ψ :\n  Ψ (repr (Spec.to_ek t)) -∗\n  WP to_ek t @ E {{ Ψ }}.\nProof.\nrewrite /to_ek; iIntros \"post\".\nwp_pures; wp_bind (is_key _); iApply wp_is_key.\ncase: t => /=; try by move=> *; wp_pures => //.\ncase; try by move => *; wp_pures.\nQed.\n\nLemma wp_to_dk E t Ψ :\n  Ψ (repr (Spec.to_dk t)) -∗\n  WP to_dk t @ E {{ Ψ }}.\nProof.\nrewrite /to_dk; iIntros \"post\".\nwp_pures; wp_bind (is_key _); iApply wp_is_key.\ncase: t => /=; try by move=> *; wp_pures => //.\ncase; try by move => *; wp_pures.\nQed.\n\nEnd Proofs.\n\nArguments channel {Σ _ _} c.\n", "meta": {"author": "arthuraa", "repo": "cryptis", "sha": "056d1fb93b8d8395b0c19639edb961d4919c63f6", "save_path": "github-repos/coq/arthuraa-cryptis", "path": "github-repos/coq/arthuraa-cryptis/cryptis-056d1fb93b8d8395b0c19639edb961d4919c63f6/primitives/simple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24201280108417803}}
{"text": "(* Copyright (c) 2017, the Dart project authors.  Please see the AUTHORS file\n * for details. All rights reserved. Use of this source code is governed by a\n * BSD-style license that can be found in the LICENSE file. *)\n\nRequire Import Utf8.\nRequire Import InvariantVoidnessPreservation.\nRequire Import FunctionTestTypes.\n\nModule MyVoidnessPreservation :=\n  InvariantVoidnessPreservation.VoidnessPreservationBase Dynamics.NormalDynamics.\nImport MyVoidnessPreservation.\n\n(* void Function(void) f = func<dynamic, dynamic>; // Yes *)\nGoal VoidnessPreserves dt_fun_dynamic_dynamic dt_fun_void_void.\n  apply vp_function; auto.\nQed.\n\n(* void Function(void) f = func<dynamic, void>; // Yes *)\nGoal VoidnessPreserves dt_fun_dynamic_void dt_fun_void_void.\n  apply vp_function; auto.\nQed.\n\n(* void Function(void) f = func<void, dynamic>; // Yes *)\nGoal VoidnessPreserves dt_fun_void_dynamic dt_fun_void_void.\n  apply vp_function; auto.\nQed.\n\n(* void Function(void) f = func<Object, Object>; // No *)\nGoal ~(VoidnessPreserves dt_fun_Object_Object dt_fun_void_void).\n  intro H. inversion H. inversion H5. inversion H9.\nQed.\n\n(* void Function(void) f = func<Object, void>; // No *)\nGoal ~(VoidnessPreserves dt_fun_Object_void dt_fun_void_void).\n  intro H. inversion H. inversion H5. inversion H9.\nQed.\n\n(* void Function(void) f = func<void, Object>; // Yes *)\nGoal VoidnessPreserves dt_fun_void_Object dt_fun_void_void.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(dynamic) g = func<void, void>; // Yes *)\nGoal VoidnessPreserves dt_fun_void_void dt_fun_dynamic_dynamic.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(dynamic) g = func<dynamic, void>; // Yes *)\nGoal VoidnessPreserves dt_fun_dynamic_void dt_fun_dynamic_dynamic.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(dynamic) g = func<void, dynamic>; // Yes *)\nGoal VoidnessPreserves dt_fun_void_dynamic dt_fun_dynamic_dynamic.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(dynamic) g = func<Object, Object>; // Yes *)\nGoal VoidnessPreserves dt_fun_Object_Object dt_fun_dynamic_dynamic.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(dynamic) g = func<Object, void>; // Yes *)\nGoal VoidnessPreserves dt_fun_Object_void dt_fun_dynamic_dynamic.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(dynamic) g = func<void, Object>; // Yes *)\nGoal VoidnessPreserves dt_fun_void_Object dt_fun_dynamic_dynamic.\n  apply vp_function; auto.\nQed.\n\n(* Object Function(Object) h = func<void, void>; // No *)\nGoal ~(VoidnessPreserves dt_fun_void_void dt_fun_Object_Object).\n  intro H. inversion H. inversion H3.\nQed.\n\n(* Object Function(Object) h = func<dynamic, void>; // No *)\nGoal ~(VoidnessPreserves dt_fun_dynamic_void dt_fun_Object_Object).\n  intro H. inversion H. inversion H3.\nQed.\n\n(* Object Function(Object) h = func<void, dynamic>; // Yes *)\nGoal VoidnessPreserves dt_fun_void_dynamic dt_fun_Object_Object.\n  apply vp_function; auto.\nQed.\n\n(* Object Function(Object) h = func<Object, Object>; // Yes *)\nGoal VoidnessPreserves dt_fun_Object_Object dt_fun_Object_Object.\n  apply vp_function.\n  - apply vp_class. apply vctsp_cons; auto.\n    apply vctp_some. apply vctps_first; auto.\n  - apply vpp_cons; auto. apply vp_class. apply vctsp_cons; auto.\n    apply vctp_some. apply vctps_first; auto.\nQed.\n\n(* Object Function(Object) h = func<Object, void>; // No *)\nGoal ~(VoidnessPreserves dt_fun_Object_void dt_fun_Object_Object).\n  intro H. inversion H. inversion H3.\nQed.\n\n(* Object Function(Object) h = func<void, Object>; // Yes *)\nGoal VoidnessPreserves dt_fun_void_Object dt_fun_Object_Object.\n  apply vp_function; auto.\n  apply vp_class. apply vctsp_cons; auto.\n  apply vctp_some. apply vctps_first; auto.\nQed.\n\n(* Object Function(void) h = func<Object, Object>; // No *)\nGoal ~(VoidnessPreserves dt_fun_Object_Object dt_fun_void_Object).\n  intro H. inversion H. inversion H5. inversion H9.\nQed.\n\n(* dynamic Function(void Function(void)) f = func<dynamic Function(dynamic), dynamic>; // Yes *)\nGoal VoidnessPreserves dt_fun2_dynamic_dynamic dt_fun2_void_void.\n  apply vp_function; auto.\n  apply vpp_cons; auto.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(void Function(void)) f = func<Object Function(dynamic), dynamic>; // No *)\nGoal ~(VoidnessPreserves dt_fun2_dynamic_Object dt_fun2_void_void).\n  intro H. inversion H. inversion H5.\n  inversion H9. inversion H12. inversion H15.\nQed.\n\n(* dynamic Function(void Function(void)) f = func<dynamic Function(Object), dynamic>; // Yes *)\nGoal VoidnessPreserves dt_fun2_Object_dynamic dt_fun2_void_void.\n  apply vp_function; auto.\n  apply vpp_cons; auto.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(void Function(void)) f = func<Object Function(Object), dynamic>; // No *)\nGoal ~(VoidnessPreserves dt_fun2_Object_Object dt_fun2_void_void).\n  intro H. inversion H. inversion H5. \n  inversion H9. inversion H12. inversion H15.\nQed.\n\n(* dynamic Function(dynamic Function(dynamic)) f = func<void Function(void), dynamic>; // Yes *)\nGoal VoidnessPreserves dt_fun2_void_void dt_fun2_dynamic_dynamic.\n  apply vp_function; auto.\n  apply vpp_cons; auto.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(dynamic Function(dynamic)) f = func<Object Function(void), dynamic>; // Yes *)\nGoal VoidnessPreserves dt_fun2_void_Object dt_fun2_dynamic_dynamic.\n  apply vp_function; auto.\n  apply vpp_cons; auto.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(dynamic Function(dynamic)) f = func<void Function(Object), dynamic>; // Yes *)\nGoal VoidnessPreserves dt_fun2_Object_void dt_fun2_dynamic_dynamic.\n  apply vp_function; auto.\n  apply vpp_cons; auto.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(dynamic Function(dynamic)) f = func<Object Function(Object), dynamic>; // Yes *)\nGoal VoidnessPreserves dt_fun2_Object_Object dt_fun2_dynamic_dynamic.\n  apply vp_function; auto.\n  apply vpp_cons; auto.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(Object Function(Object)) f = func<void Function(void), dynamic>; // No *)\nGoal ~(VoidnessPreserves dt_fun2_void_void dt_fun2_Object_Object).\n  intro H. inversion H. inversion H5. \n  inversion H9. inversion H17. inversion H21.\nQed.\n\n(* dynamic Function(Object Function(Object)) f = func<dynamic Function(void), dynamic>; // No *)\nGoal ~(VoidnessPreserves dt_fun2_void_dynamic dt_fun2_Object_Object).\n  intro H. inversion H. inversion H5.\n  inversion H9. inversion H17. inversion H21.\nQed.\n\n(* dynamic Function(Object Function(Object)) f = func<void Function(dynamic), dynamic>; // Yes *)\nGoal VoidnessPreserves dt_fun2_dynamic_void dt_fun2_Object_Object.\n  apply vp_function; auto.\n  apply vpp_cons; auto.\n  apply vp_function; auto.\nQed.\n\n(* dynamic Function(Object Function(Object)) f = func<dynamic Function(dynamic), dynamic>; // Yes *)\nGoal VoidnessPreserves dt_fun2_dynamic_dynamic dt_fun2_Object_Object.\n  apply vp_function; auto.\n  apply vpp_cons; auto.\n  apply vp_function; auto.\nQed.\n", "meta": {"author": "eernstg", "repo": "coq-voidness", "sha": "727d326633a7759ed4d6f6d7ae26eae900485d01", "save_path": "github-repos/coq/eernstg-coq-voidness", "path": "github-repos/coq/eernstg-coq-voidness/coq-voidness-727d326633a7759ed4d6f6d7ae26eae900485d01/FunctionInvariantNormalTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24201280108417803}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Export Arith.\n\nSection Time_Clocks.\n\n(*** Temporal notions for discrete time ***)\n\n  Definition Instant := nat.   \n  Definition Clock := nat.\n \n  Definition lt_Ck := lt.              (* <  *)\n  Definition le_Ck := le.              (* <= *)\n  Definition gt_Ck := gt.              (* >  *)\n  Definition ge_Ck := ge.              (* >= *)\n  Definition eq_Ck (x y : Clock) := x = y. (* =  *)\n \n  Definition Ini_Ck : Instant := 0.\n  Definition tick : Instant := 1.\n  Definition plus_Ck := plus.            (* +  *)\n  Definition Inc (x : Clock) := plus_Ck x tick.\n  Definition Reset : Instant := 0.\n  Definition time0 : Instant := 0.\n\nEnd Time_Clocks.", "meta": {"author": "coq-contribs", "repo": "ctltctl", "sha": "51b7096482ac402d8e0ba2eeb932432a2f2489fc", "save_path": "github-repos/coq/coq-contribs-ctltctl", "path": "github-repos/coq/coq-contribs-ctltctl/ctltctl-51b7096482ac402d8e0ba2eeb932432a2f2489fc/time_clocks.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.24187998375596864}}
{"text": "Require Import PreAutoSep Wrap Conditional.\n\nImport DefineStructured.\n\nSet Implicit Arguments.\n\n\n(** Simple notation for parsing streams of machine words *)\n\nInductive pattern0 :=\n| Const_ (_ : W)\n(* Match this exact word. *)\n| Var_ (_ : string)\n(* Match anything and stash it in this local variable. *).\n\nDefinition pattern := list pattern0.\n(* Match a prefix of the stream against these individual word patterns. *)\n\nDefinition Const w : pattern := Const_ w :: nil.\nDefinition Var x : pattern := Var_ x :: nil.\n\nCoercion Const : W >-> pattern.\nCoercion Var : string >-> pattern.\n\nFixpoint matches (p : pattern) (ws : list W) : Prop :=\n  match p, ws with\n    | nil, _ => True\n    | Const_ w :: p', w' :: ws' => w = w' /\\ matches p' ws'\n    | Var_ _ :: p', _ :: ws' => matches p' ws'\n    | _, _ => False\n  end.\n\nFixpoint binds (p : pattern) (ws : list W) : list (string * W) :=\n  match p, ws with\n    | Const_ _ :: p', _ :: ws' => binds p' ws'\n    | Var_ s :: p', w :: ws' => (s, w) :: binds p' ws'\n    | _, _ => nil\n  end.\n\nSection Parse.\n  Hint Extern 1 (Mem _ = Mem _) =>\n    eapply scratchOnlyMem; [ | eassumption ];\n      simpl; intuition congruence.\n  Hint Extern 1 (Mem _ = Mem _) =>\n    symmetry; eapply scratchOnlyMem; [ | eassumption ];\n      simpl; intuition congruence.\n\n  Hint Resolve evalInstrs_app sepFormula_Mem.\n\n  Hint Extern 2 (interp ?specs2 (![ _ ] (?stn2, ?st2))) =>\n    match goal with\n      | [ _ : interp ?specs1 (![ _ ] (?stn1, ?st1)) |- _ ] =>\n        solve [ equate specs1 specs2; equate stn1 stn2; equate st1 st2; step auto_ext ]\n    end.\n\n  Variable stream : string.\n  (* Name of local variable containing an array to treat as the stream of words *)\n  Variable size : string.\n  (* Name of local variable containing the stream length in words *)\n  Variable pos : string.\n  (* Name of local variable containing the current stream position in words *)\n\n  Variable p : pattern.\n  (* We will try to match a prefix of the stream against this pattern. *)\n\n  Variable imports : LabelMap.t assert.\n  Hypothesis H : importsGlobal imports.\n  Variable modName : string.\n\n  Variables Then Else : cmd imports modName.\n  (* Code to run when a single pattern matches or fails, respectively. *)\n\n  Variable ns : list string.\n  (* Local variable names *)\n\n  (* Does the pattern match? *)\n  Fixpoint guard (p : pattern) (offset : nat) : bexp :=\n    match p with\n      | nil =>\n        Test Rv Le (variableSlot size ns)\n        (* Is there enough space left in the stream? *)\n      | Const_ w :: p' =>\n        And (guard p' (S offset))\n        (Test (LvMem (Indir Rp (4 * offset))) IL.Eq w)\n      | Var_ _ :: p' => guard p' (S offset)\n    end.\n\n  (* Once we know that the pattern matches, we set the appropriate pattern variables with this function. *)\n  Fixpoint reads (p : pattern) (offset : nat) : list instr :=\n    match p with\n      | nil => nil\n      | Const_ _ :: p' => reads p' (S offset)\n      | Var_ x :: p' => Assign (variableSlot x ns) (LvMem (Indir Rp (4 * offset))) :: reads p' (S offset)\n    end.\n\n  Fixpoint suffix (n : nat) (ws : list W) : list W :=\n    match n with\n      | O => ws\n      | S n' => match ws with\n                  | nil => nil\n                  | w :: ws' => suffix n' ws'\n                end\n    end.\n\n  Lemma suffix_remains : forall n ws,\n    (n < length ws)%nat\n    -> suffix n ws = selN ws n :: suffix (S n) ws.\n    induction n; destruct ws; simpl; intuition.\n    rewrite IHn; auto.\n  Qed.\n\n  Fixpoint patternBound (p : pattern) : Prop :=\n    match p with\n      | nil => True\n      | Const_ _ :: p' => patternBound p'\n      | Var_ x :: p' => In x ns /\\ patternBound p'\n    end.\n\n  Fixpoint okVarName (x : string) (p : pattern) : Prop :=\n    match p with\n      | nil => True\n      | Const_ _ :: p' => okVarName x p'\n      | Var_ x' :: p' => if string_dec x x' then False else okVarName x p'\n    end.\n\n  Definition ThenPre (pre : assert) : assert :=\n    (fun stn_st => let (stn, st) := stn_st in\n      Ex st', pre (stn, st')\n      /\\ (AlX, Al V, Al ws, Al r,\n        ![ ^[array ws (sel V stream) * locals (\"rp\" :: ns) V r (Regs st' Sp)] * #0] (stn, st')\n        /\\ [| sel V size = length ws |]\n        ---> [| matches p (suffix (wordToNat (sel V pos)) ws)\n          /\\ exists st'', Mem st'' = Mem st'\n            /\\ Regs st'' Sp = Regs st' Sp\n            /\\ evalInstrs stn st'' (map (fun p => Assign (variableSlot (fst p) ns) (RvImm (snd p)))\n              (binds p (suffix (wordToNat (sel V pos)) ws))\n              ++ Binop (variableSlot pos ns) (variableSlot pos ns) Plus (length p)\n              :: nil) = Some st |]))%PropX.\n\n  Definition ElsePre (pre : assert) : assert :=\n    (fun stn_st => let (stn, st) := stn_st in\n      Ex st', pre (stn, st')\n      /\\ (AlX, Al V, Al ws, Al r,\n        ![ ^[array ws (sel V stream) * locals (\"rp\" :: ns) V r (Regs st Sp)] * #0] (stn, st')\n        /\\ [| sel V size = length ws |]\n        ---> [| ~matches p (suffix (wordToNat (sel V pos)) ws) |])\n      /\\ [| Regs st Sp = Regs st' Sp /\\ Mem st = Mem st' |])%PropX.\n\n  (* Here's the raw parsing command, which we will later wrap with nicer VCs. *)\n  Definition Parse1_ : cmd imports modName := fun pre =>\n    Seq_ H (Straightline_ _ _ (Binop Rv (variableSlot pos ns) Plus (length p)\n      :: Binop Rp 4 Times (variableSlot pos ns)\n      :: Binop Rp (variableSlot stream ns) Plus Rp\n      :: nil))\n    (Cond_ _ H _ (guard p O)\n      (Seq_ H\n        (Straightline_ _ _ (reads p O\n          ++ Binop (variableSlot pos ns) (variableSlot pos ns) Plus (length p)\n          :: nil))\n        (Seq_ H\n          (Structured.Assert_ _ _ (ThenPre pre))\n          Then))\n      (Seq_ H\n        (Structured.Assert_ _ _ (ElsePre pre))\n        Else))\n    pre.\n\n  Hint Rewrite wordToN_nat wordToNat_natToWord_idempotent using assumption : N.\n  Require Import Arith.\n\n  Hint Resolve goodSize_weaken.\n\n  Opaque mult.\n\n  Lemma bexpTrue_bound : forall specs stn st ws V r fr,\n    interp specs\n    (![array ws (sel V stream) * locals (\"rp\" :: ns) V r (Regs st Sp) * fr] (stn, st))\n    -> In size ns\n    -> ~In \"rp\" ns\n    -> forall p' offset, bexpTrue (guard p' offset) stn st\n      -> Regs st Rv <= sel V size.\n    clear H; induction p' as [ | [ ] ]; simpl; intuition eauto.\n\n    prep_locals; evaluate auto_ext; tauto.\n  Qed.\n\n  Lemma bexpSafe_guard : forall specs stn st ws V r fr,\n    interp specs\n    (![array ws (sel V stream) * locals (\"rp\" :: ns) V r (Regs st Sp) * fr] (stn, st))\n    -> In size ns\n    -> ~In \"rp\" ns\n    -> Regs st Rp = sel V stream ^+ $4 ^* sel V pos\n    -> sel V size = $(length ws)\n    -> forall p' offset,\n      Regs st Rv = $(offset + wordToNat (sel V pos) + length p')\n      -> goodSize (offset + wordToNat (sel V pos) + Datatypes.length p')\n      -> bexpSafe (guard p' offset) stn st.\n    clear H; induction p' as [ | [ ] ]; simpl; intuition.\n\n    prep_locals; evaluate auto_ext.\n\n    apply IHp'.\n    rewrite H4; f_equal; omega.\n    eauto.\n\n    replace (evalCond (LvMem (Rp + 4 * offset)%loc) IL.Eq w stn st)\n      with (evalCond (LvMem (Imm (sel V stream ^+ $4 ^* $(offset + wordToNat (sel V pos))))) IL.Eq w stn st)\n        in *.\n    assert (goodSize (length ws)) by eauto.\n    assert (natToW (offset + wordToNat (sel V pos)) < $(length ws)).\n    specialize (bexpTrue_bound _ H H0 H1 _ _ H6).\n    rewrite H3, H4.\n    intros.\n    apply wle_goodSize in H9; auto; eauto.\n\n    prep_locals; evaluate auto_ext.\n\n    unfold evalCond; simpl.\n    rewrite H2.\n    match goal with\n      | [ |- match ReadWord _ _ ?X with None => _ | _ => _ end\n        = match ReadWord _ _ ?Y with None => _ | _ => _ end ] => replace Y with X; auto\n    end.\n    rewrite mult_comm; rewrite natToW_times4.\n    rewrite natToW_plus.\n    unfold natToW.\n    rewrite natToWord_wordToNat.\n    W_eq.\n\n    apply IHp'; eauto.\n    rewrite H4; f_equal; omega.\n  Qed.\n\n  Lemma bexpTrue_matches : forall specs stn st ws V r fr,\n    interp specs\n    (![array ws (sel V stream) * locals (\"rp\" :: ns) V r (Regs st Sp) * fr] (stn, st))\n    -> In size ns\n    -> ~In \"rp\" ns\n    -> Regs st Rp = sel V stream ^+ $4 ^* sel V pos\n    -> forall p' offset, bexpTrue (guard p' offset) stn st\n      -> Regs st Rv = $(offset + wordToNat (sel V pos) + length p')\n      -> (offset + wordToNat (sel V pos) <= length ws)%nat\n      -> sel V size = $(length ws)\n      -> goodSize (offset + wordToNat (sel V pos) + length p')\n      -> matches p' (suffix (offset + wordToNat (sel V pos)) ws).\n    clear H; induction p' as [ | [ ] ]; simpl; intuition.\n\n    specialize (bexpTrue_bound _ H H0 H1 _ _ H8).\n    rewrite H4; intros.\n    replace (evalCond (LvMem (Rp + 4 * offset)%loc) IL.Eq w stn st)\n      with (evalCond (LvMem (Imm (sel V stream ^+ $4 ^* $(offset + wordToNat (sel V pos))))) IL.Eq w stn st)\n        in *.\n    rewrite H6 in H3.\n    eapply wle_goodSize in H3.\n    rewrite suffix_remains in * by auto.\n    assert (natToW (offset + wordToNat (sel V pos)) < natToW (length ws))\n      by (apply lt_goodSize; eauto).\n    prep_locals; evaluate auto_ext.\n\n    split.\n    subst.\n    unfold Array.sel.\n    rewrite wordToNat_natToWord_idempotent; auto.\n    change (goodSize (offset + wordToNat (sel V pos))); eauto.\n    change (S (offset + wordToNat (sel V pos))) with (S offset + wordToNat (sel V pos)).\n    apply IHp'; auto.\n    rewrite H4; f_equal; omega.\n    eauto.\n    eauto.\n    eauto.\n\n    unfold evalCond; simpl.\n    rewrite H2.\n    match goal with\n      | [ |- match ?E with None => _ | _ => _ end = match ?E' with None => _ | _ => _ end ] =>\n        replace E with E'; auto\n    end.\n    f_equal.\n    rewrite natToW_plus.\n    rewrite mult_comm; rewrite natToW_times4.\n    unfold natToW.\n    rewrite natToWord_wordToNat.\n    W_eq.\n\n\n    specialize (bexpTrue_bound _ H H0 H1 _ _ H3).    \n    rewrite H4; intros.\n    rewrite H6 in H8.\n    eapply wle_goodSize in H8.\n    rewrite suffix_remains in * by auto.\n    change (S (offset + wordToNat (sel V pos))) with (S offset + wordToNat (sel V pos)).\n    apply IHp'; auto.\n    rewrite H4; f_equal; omega.\n    eauto.\n    eauto.\n    eauto.\n  Qed.\n\n  Lemma suffix_none : forall n ls,\n    (n >= length ls)%nat\n    -> suffix n ls = nil.\n    induction n; destruct ls; simpl; intuition.\n  Qed.\n\n  Lemma bexpFalse_not_matches : forall specs stn st ws V r fr,\n    interp specs\n    (![array ws (sel V stream) * locals (\"rp\" :: ns) V r (Regs st Sp) * fr] (stn, st))\n    -> In size ns\n    -> ~In \"rp\" ns\n    -> Regs st Rp = sel V stream ^+ $4 ^* sel V pos\n    -> sel V size = $(length ws)\n    -> forall p' offset, bexpFalse (guard p' offset) stn st\n      -> Regs st Rv = $(offset + wordToNat (sel V pos) + length p')\n      -> (offset + wordToNat (sel V pos) <= length ws)%nat\n      -> goodSize (offset + wordToNat (sel V pos) + length p')\n      -> ~matches p' (suffix (offset + wordToNat (sel V pos)) ws).\n    clear H; induction p' as [ | [ ] ]; simpl; intuition.\n\n    prep_locals; evaluate auto_ext.\n    rewrite H3 in *.\n    apply lt_goodSize' in H13.\n    omega.\n    eauto.\n    eauto.\n\n\n    destruct (le_lt_dec (length ws) (offset + wordToNat (sel V pos))).\n    rewrite suffix_none in *; auto.\n    rewrite suffix_remains in * by auto.\n    assert (natToW (offset + wordToNat (sel V pos)) < natToW (length ws))\n      by (apply lt_goodSize; eauto).\n    prep_locals; evaluate auto_ext.\n    eapply IHp'; eauto.\n    rewrite H5; f_equal; omega.\n\n    specialize (bexpTrue_bound _ H H0 H1 _ _ H4).\n    rewrite H5; intros.\n    destruct (le_lt_dec (length ws) (offset + wordToNat (sel V pos))).\n    rewrite suffix_none in *; auto.\n    rewrite suffix_remains in * by auto.\n    replace (evalCond (LvMem (Rp + 4 * offset)%loc) IL.Eq w stn st)\n      with (evalCond (LvMem (Imm (sel V stream ^+ $4 ^* $(offset + wordToNat (sel V pos))))) IL.Eq w stn st)\n        in *.\n    assert (natToW (offset + wordToNat (sel V pos)) < natToW (length ws))\n      by (apply lt_goodSize; eauto).\n    prep_locals; evaluate auto_ext.\n    subst.\n    apply H16.\n    unfold Array.sel.\n    rewrite wordToNat_natToWord_idempotent; auto.\n    change (goodSize (offset + wordToNat (sel V pos))); eauto.\n\n    unfold evalCond; simpl.\n    rewrite H2.\n    match goal with\n      | [ |- match ?E with None => _ | _ => _ end = match ?E' with None => _ | _ => _ end ] =>\n        replace E with E'; auto\n    end.\n    f_equal.\n    rewrite natToW_plus.\n    rewrite mult_comm; rewrite natToW_times4.\n    unfold natToW.\n    rewrite natToWord_wordToNat.\n    W_eq.\n\n    destruct (le_lt_dec (length ws) (offset + wordToNat (sel V pos))).\n    rewrite suffix_none in *; auto.\n    rewrite suffix_remains in * by auto.\n    intuition; subst.\n    eapply IHp'; eauto.\n    rewrite H5; f_equal; omega.\n  Qed.\n\n  Transparent evalInstrs.\n  Opaque evalInstr.\n\n  Lemma reads_nocrash : forall specs stn ws r fr,\n    ~In \"rp\" ns\n    -> forall p' offset st V, patternBound p'\n      -> interp specs (![array ws (sel V stream) * locals (\"rp\" :: ns) V r (Regs st Sp) * fr] (stn, st))\n      -> Regs st Rp = sel V stream ^+ $4 ^* sel V pos\n      -> (offset + wordToNat (sel V pos) + length p' <= length ws)%nat\n      -> okVarName stream p'\n      -> okVarName pos p'\n      -> evalInstrs stn st (reads p' offset) = None\n      -> False.\n    clear H; induction p' as [ | [ ] ]; simpl; intuition.\n\n    eapply IHp'; eauto.\n    match goal with\n      | [ H : (?U <= ?X)%nat |- (?V <= ?X)%nat ] => replace V with U; auto; omega\n    end.\n\n    destruct (string_dec stream s); try tauto.\n    destruct (string_dec pos s); try tauto.\n\n    case_eq (evalInstr stn st (Assign (variableSlot s ns) (LvMem (Rp + 4 * offset)%loc))); intros;\n      match goal with\n        | [ H : _ = _ |- _ ] => rewrite H in *\n      end.\n\n    replace (evalInstr stn st (Assign (variableSlot s ns) (LvMem (Rp + 4 * offset)%loc)))\n      with (evalInstr stn st (Assign (variableSlot s ns)\n        (LvMem (Imm (sel V stream ^+ $4 ^* $(offset + wordToNat (sel V pos))))))) in *.\n    generalize dependent H6; prep_locals.\n    assert (natToW (offset + wordToNat (sel V pos)) < $(length ws)).\n    apply lt_goodSize; eauto.\n    prep_locals.\n    rewrite evalInstr_evalInstrs in H0.\n    evaluate auto_ext.\n    intros.\n    eapply IHp'.\n    eauto.\n    instantiate (1 := s0).\n    step auto_ext.\n    reflexivity.\n    repeat rewrite sel_upd_ne by congruence.\n    assumption.\n    instantiate (1 := S offset).\n    repeat rewrite sel_upd_ne by congruence.    \n    match goal with\n      | [ H : (?U <= ?X)%nat |- (?V <= ?X)%nat ] => replace V with U; auto; omega\n    end.\n    assumption.\n    assumption.\n    assumption.\n    Transparent evalInstr.\n    simpl.\n    match goal with\n      | [ |- match ?E with None => _ | _ => _ end = match ?E' with None => _ | _ => _ end ] =>\n        replace E with E'; auto\n    end.\n    f_equal.\n    rewrite H2.\n    rewrite natToW_plus.\n    rewrite mult_comm; rewrite natToW_times4.\n    unfold natToW.\n    rewrite natToWord_wordToNat.\n    W_eq.\n\n    replace (evalInstr stn st (Assign (variableSlot s ns) (LvMem (Rp + 4 * offset)%loc)))\n      with (evalInstr stn st (Assign (variableSlot s ns)\n        (LvMem (Imm (sel V stream ^+ $4 ^* $(offset + wordToNat (sel V pos))))))) in *.\n    generalize dependent H6; prep_locals.\n    assert (natToW (offset + wordToNat (sel V pos)) < $(length ws)).\n    apply lt_goodSize; eauto.\n    prep_locals.\n    rewrite evalInstr_evalInstrs in H0.\n    evaluate auto_ext.\n\n    simpl.\n    match goal with\n      | [ |- match ?E with None => _ | _ => _ end = match ?E' with None => _ | _ => _ end ] =>\n        replace E with E'; auto\n    end.\n    f_equal.\n    rewrite H2.\n    rewrite natToW_plus.\n    rewrite mult_comm; rewrite natToW_times4.\n    unfold natToW.\n    rewrite natToWord_wordToNat.\n    W_eq.\n  Qed.\n\n  Opaque evalInstr.\n\n  Lemma reads_exec' : forall specs stn ws r fr,\n    ~In \"rp\" ns\n    -> forall p' offset st st' V, patternBound p'\n      -> interp specs (![array ws (sel V stream) * locals (\"rp\" :: ns) V r (Regs st Sp) * fr] (stn, st))\n      -> Regs st Rp = sel V stream ^+ $4 ^* sel V pos\n      -> (offset + wordToNat (sel V pos) + length p' <= length ws)%nat\n      -> okVarName stream p'\n      -> okVarName pos p'\n      -> evalInstrs stn st (reads p' offset) = Some st'\n      -> exists V',\n        interp specs (![array ws (sel V stream) * locals (\"rp\" :: ns) V' r (Regs st Sp) * fr] (stn, st'))\n        /\\ Regs st' Sp = Regs st Sp.\n    clear H; induction p' as [ | [ ] ]; simpl; intuition.\n\n    injection H6; intros; subst.\n    eauto.\n\n    eapply IHp'; eauto.\n    match goal with\n      | [ H : (?U <= ?X)%nat |- (?V <= ?X)%nat ] => replace V with U; auto; omega\n    end.\n\n    destruct (string_dec stream s); try tauto.\n    destruct (string_dec pos s); try tauto.\n\n    case_eq (evalInstr stn st (Assign (variableSlot s ns) (LvMem (Rp + 4 * offset)%loc))); intros;\n      match goal with\n        | [ H : _ = _ |- _ ] => rewrite H in *\n      end.\n\n    replace (evalInstr stn st (Assign (variableSlot s ns) (LvMem (Rp + 4 * offset)%loc)))\n      with (evalInstr stn st (Assign (variableSlot s ns)\n        (LvMem (Imm (sel V stream ^+ $4 ^* $(offset + wordToNat (sel V pos))))))) in *.\n    generalize dependent H6; prep_locals.\n    assert (natToW (offset + wordToNat (sel V pos)) < $(length ws)).\n    apply lt_goodSize; eauto.\n    prep_locals.\n    rewrite evalInstr_evalInstrs in H0.\n    evaluate auto_ext.\n    intros.\n    eapply (IHp' _ _ _ (upd V s (Array.sel ws (offset + wordToNat (sel V pos))))) in H13.\n    rewrite <- H1.\n    rewrite sel_upd_ne in H13 by congruence.\n    assumption.\n    eauto.\n    step auto_ext.\n    reflexivity.\n    rewrite H10.\n    repeat rewrite sel_upd_ne by congruence.\n    W_eq.\n    repeat rewrite sel_upd_ne by congruence.\n    match goal with\n      | [ H : (?U <= ?X)%nat |- (?V <= ?X)%nat ] => replace V with U; auto; omega\n    end.\n    assumption.\n    assumption.\n    Transparent evalInstr.\n    simpl.\n    match goal with\n      | [ |- match ?E with None => _ | _ => _ end = match ?E' with None => _ | _ => _ end ] =>\n        replace E with E'; auto\n    end.\n    f_equal.\n    rewrite H2.\n    rewrite natToW_plus.\n    rewrite mult_comm; rewrite natToW_times4.\n    unfold natToW.\n    rewrite natToWord_wordToNat.\n    W_eq.\n\n    replace (evalInstr stn st (Assign (variableSlot s ns) (LvMem (Rp + 4 * offset)%loc)))\n      with (evalInstr stn st (Assign (variableSlot s ns)\n        (LvMem (Imm (sel V stream ^+ $4 ^* $(offset + wordToNat (sel V pos))))))) in *.\n    generalize dependent H6; prep_locals.\n    assert (natToW (offset + wordToNat (sel V pos)) < $(length ws)).\n    apply lt_goodSize; eauto.\n    prep_locals.\n    rewrite evalInstr_evalInstrs in H0.\n    evaluate auto_ext.\n\n    simpl.\n    match goal with\n      | [ |- match ?E with None => _ | _ => _ end = match ?E' with None => _ | _ => _ end ] =>\n        replace E with E'; auto\n    end.\n    f_equal.\n    rewrite H2.\n    rewrite natToW_plus.\n    rewrite mult_comm; rewrite natToW_times4.\n    unfold natToW.\n    rewrite natToWord_wordToNat.\n    W_eq.\n  Qed.\n\n  Lemma reads_exec : forall stn st p' offset st',\n    evalInstrs stn st (reads p' offset) = Some st'\n    -> ~In \"rp\" ns\n    -> forall specs ws r fr V, patternBound p'\n      -> interp specs (![array ws (sel V stream) * locals (\"rp\" :: ns) V r (Regs st Sp) * fr] (stn, st))\n      -> Regs st Rp = sel V stream ^+ $4 ^* sel V pos\n      -> (offset + wordToNat (sel V pos) + length p' <= length ws)%nat\n      -> okVarName stream p'\n      -> okVarName pos p'\n\n      -> exists V',\n        interp specs (![array ws (sel V stream) * locals (\"rp\" :: ns) V' r (Regs st Sp) * fr] (stn, st'))\n        /\\ Regs st' Sp = Regs st Sp.\n    eauto using reads_exec'.\n  Qed.\n\n  Opaque evalInstrs.\n\n  Lemma unify_V : forall specs stn st ws V r sp fr ws' V' r' fr',\n    interp specs (![array ws (sel V stream) * locals (\"rp\" :: ns) V r sp * fr] (stn, st))\n    -> sel V size = length ws\n    -> sel V' size = length ws'\n    -> interp specs (![array ws' (sel V' stream) * locals (\"rp\" :: ns) V' r' sp * fr'] (stn, st)\n       ---> [| forall x, In x ns -> sel V' x = sel V x |])%PropX.\n    clear H; intros.\n    assert (Hlocals : exists FR, interp specs (![array (toArray (\"rp\" :: ns) V) sp * FR] (stn, st)))\n      by (eexists; unfold locals in H; step auto_ext); destruct Hlocals as [ FR Hlocals ].\n    assert (Hlocals' : exists FR', himp specs\n      (array ws' (sel V' stream) * locals (\"rp\" :: ns) V' r' sp * fr')%Sep\n      (array (toArray (\"rp\" :: ns) V') sp * FR')%Sep)\n      by (eexists; unfold locals; step auto_ext); destruct Hlocals' as [ FR' Hlocals' ].\n    eapply Imply_trans; try (rewrite sepFormula_eq; apply Hlocals').\n    simpl.\n    replace ((array (V' \"rp\" :: toArray ns V') sp * FR')%Sep stn (memoryIn (Mem st)))\n      with (![array (V' \"rp\" :: toArray ns V') sp * FR'] (stn, st))%PropX\n        by (rewrite sepFormula_eq; reflexivity).\n    eapply Imply_trans.\n    eapply array_equals; eauto.\n    simpl; repeat rewrite length_toArray in *; apply inj_imply; intuition.\n    injection H3; clear H3; intros.\n    eauto using toArray_sel.\n  Qed.\n\n  Lemma unify_ws : forall specs stn st ws V r sp fr ws' V' r' fr' streamV,\n    interp specs (![array ws streamV * locals (\"rp\" :: ns) V r sp * fr] (stn, st))\n    -> length ws' = length ws\n    -> interp specs (![array ws' streamV * locals (\"rp\" :: ns) V' r' sp * fr'] (stn, st)\n       ---> [| ws' = ws |])%PropX.\n    clear H; intros.\n    assert (Hlocals : interp specs (![array ws streamV * (locals (\"rp\" :: ns) V r sp * fr)] (stn, st)))\n       by step auto_ext.\n    assert (Hlocals' : himp specs\n      (array ws' streamV * locals (\"rp\" :: ns) V' r' sp * fr')%Sep\n      (array ws' streamV * (locals (\"rp\" :: ns) V' r' sp * fr'))%Sep)\n      by step auto_ext.\n    eapply Imply_trans; try (rewrite sepFormula_eq; apply Hlocals').\n    simpl.\n    replace ((array ws' streamV * (locals (\"rp\" :: ns) V' r' sp * fr'))%Sep stn\n      (memoryIn (Mem st)))\n      with (![array ws' streamV * (locals (\"rp\" :: ns) V' r' sp * fr')] (stn, st))%PropX\n        by (rewrite sepFormula_eq; reflexivity).\n    eapply Imply_trans.\n    eapply array_equals; eauto.\n    apply inj_imply; intuition.\n  Qed.\n\n  Transparent mult.\n\n  Theorem unify : forall specs stn st ws V r sp fr ws' V' r' fr',\n    interp specs (![array ws (sel V stream) * locals (\"rp\" :: ns) V r sp * fr] (stn, st))\n    -> sel V size = length ws\n    -> In stream ns\n    -> In size ns\n    -> In pos ns\n    -> interp specs (![array ws' (sel V' stream) * locals (\"rp\" :: ns) V' r' sp * fr'] (stn, st)\n       /\\ [| sel V' size = length ws' |]\n       ---> [| ws' = ws /\\ sel V' stream = sel V stream /\\ sel V' size = sel V size /\\ sel V' pos = sel V pos |])%PropX.\n    intros.\n    apply Imply_I.\n    eapply Inj_E; [ eapply And_E2; apply Env; simpl; eauto | ]; intro.\n    eapply Inj_E.\n    eapply Imply_E.\n    apply interp_weaken; eapply unify_V; eauto.\n    eapply And_E1; apply Env; simpl; eauto.\n    intro.\n    apply Inj_E with (goodSize (length ws')).\n    rewrite sepFormula_eq; unfold sepFormula_def, starB, star.\n    eapply Exists_E; [ eapply And_E1; apply Env; simpl; eauto | cbv beta; intro ].\n    eapply Exists_E; [ apply Env; simpl; left; eauto | cbv beta; intro ].\n    eapply Exists_E; [ eapply And_E1; eapply And_E2; apply Env; simpl; left; eauto | cbv beta; intro ].\n    eapply Exists_E; [ apply Env; simpl; left; eauto | cbv beta; intro ].\n    eapply Imply_E.\n    apply interp_weaken; apply containsArray_goodSizex'.\n    Focus 2.\n    eapply And_E1; eapply And_E2; apply Env; simpl; eauto.\n    eauto.\n    intro.\n    repeat rewrite H6 in * by assumption.\n    eapply Inj_E.\n    eapply Imply_E.\n    apply interp_weaken; eapply unify_ws.\n    eassumption.\n    2: eapply And_E1; apply Env; simpl; eauto.\n    apply natToW_inj; congruence || eauto.\n    intro.\n    apply Inj_I; intuition.\n  Qed.\n\n  Theorem splessReads : forall p' offset,\n    spless (reads p' offset).\n    induction p' as [ | [ ] ]; simpl; intuition.\n  Qed.\n\n  Hint Resolve splessReads.\n\n  Opaque evalInstr mult.\n  Transparent evalInstrs.\n\n  Lemma simplify_reads : forall st' ws r fr stn specs p' offset st V,\n    interp specs (![array ws (sel V stream) * locals (\"rp\" :: ns) V r (Regs st Sp) * fr] (stn, st))\n    -> evalInstrs stn st (reads p' offset) = Some st'\n    -> (offset + wordToNat (sel V pos) + length p' <= length ws)%nat\n    -> patternBound p'\n    -> ~In \"rp\" ns\n    -> Regs st Rp = sel V stream ^+ $4 ^* sel V pos\n    -> okVarName stream p'\n    -> okVarName pos p'\n    -> goodSize (offset + wordToNat (sel V pos) + length p')\n    -> evalInstrs stn st (map (fun p0 =>\n      Assign\n      (LvMem (Sp + S (S (S (S (variablePosition ns (fst p0))))))%loc)\n      (RvImm (snd p0))) (binds p' (suffix (offset + wordToNat (sel V pos)) ws))) = Some st'.\n    clear H; induction p' as [ | [ ] ]; simpl; intuition;\n      rewrite suffix_remains by auto;\n        change (S (offset + wordToNat (sel V pos))) with (S offset + wordToNat (sel V pos)); eauto; simpl.\n\n    match goal with\n      | [ _ : match ?E with None => _ | _ => _ end = _ |- _ ] => case_eq E; intros\n    end; match goal with\n           | [ H : _ = _ |- _ ] => rewrite H in *\n         end; try discriminate.\n\n    destruct (string_dec stream s); try tauto.\n    destruct (string_dec pos s); try tauto.\n    assert (evalInstrs stn st (Assign (variableSlot s ns) (LvMem (Rp + 4 * offset)%loc) :: nil) = Some s0)\n      by (simpl; rewrite H2; reflexivity).\n    clear H2.\n    replace (evalInstrs stn st\n      (Assign (variableSlot s ns)\n        (LvMem (Rp + 4 * offset)%loc) :: nil))\n      with (evalInstrs stn st\n         (Assign (variableSlot s ns)\n            (LvMem (Imm (sel V stream ^+ $4 ^* $(offset + wordToNat (sel V pos))))) :: nil)) in H10.\n    assert (natToW (offset + wordToNat (sel V pos)) < $(length ws)) by (apply lt_goodSize; eauto).\n    prep_locals.\n    generalize dependent H0; evaluate auto_ext; intro.\n    case_eq (evalInstrs stn s0 (Assign Rv (variableSlot s ns) :: nil)); intros; prep_locals; evaluate auto_ext.\n    rewrite sel_upd_eq in H17 by auto.\n    unfold evalInstrs in H10, H15.\n    repeat (match goal with\n              | [ _ : match ?E with None => _ | _ => _ end = _ |- _ ] => case_eq E; intros\n            end; match goal with\n                   | [ H : _ = _ |- _ ] => rewrite H in *\n                 end; try discriminate).\n    unfold variablePosition in H19, H20; fold variablePosition in H19, H20.\n    destruct (string_dec \"rp\" s); try congruence.\n    simpl in *.\n    replace (evalInstr stn st\n      (Assign (LvMem (Sp + S (S (S (S (variablePosition ns s)))))%loc)\n        (selN ws (offset + wordToNat (sel V pos))))) with (Some s3).\n    change (match ws with\n              | nil => nil\n              | _ :: ws' => suffix (offset + wordToNat (sel V pos)) ws'\n            end) with (suffix (S offset + wordToNat (sel V pos)) ws).\n    replace (sel V pos) with (sel (upd V s (Array.sel ws (offset + wordToNat (sel V pos)))) pos).\n    injection H10; clear H10; intros; subst.\n    injection H15; clear H15; intros; subst.\n    eapply IHp'.\n    rewrite sel_upd_ne by auto.\n    apply sepFormula_Mem with s1.\n    step auto_ext.\n    assert (evalInstrs stn s0\n      (Assign Rv (LvMem (Sp + S (S (S (S (variablePosition ns s)))))%loc) :: nil) =\n      Some s1).\n    simpl; rewrite H19; reflexivity.\n    symmetry; eapply scratchOnlyMem; [ | eassumption ].\n    simpl; intuition congruence.\n    assumption.\n    rewrite sel_upd_ne; auto.\n    assumption.\n    assumption.\n    repeat rewrite sel_upd_ne by auto; assumption.\n    assumption.\n    assumption.\n    repeat rewrite sel_upd_ne by auto; eauto.\n    repeat rewrite sel_upd_ne by auto; reflexivity.\n    rewrite <- H20.\n    \n    injection H15; clear H15; intros; subst.\n    injection H10; clear H10; intros; subst.\n    assert (evalInstrs stn s0\n      (Assign Rv (LvMem (Sp + S (S (S (S (variablePosition ns s)))))%loc) :: nil) =\n      Some s1) by (simpl; rewrite H19; reflexivity).\n    eapply sepFormula_Mem in H18.\n    2: symmetry; eapply scratchOnlyMem; eauto; simpl; intuition.\n    change (S (S (S (S (variablePosition ns s))))) with (4 + variablePosition ns s) in *.\n    prep_locals.\n    evaluate auto_ext.\n    rewrite sel_upd_eq in H22 by auto.\n    unfold Array.sel in H22.\n    unfold natToW in H22; rewrite wordToNat_natToWord_idempotent in H22.\n    generalize H19 H20 H22; clear; intros.\n    Transparent evalInstr.\n\n    apply evalAssign_rhs.\n    simpl.\n    unfold evalInstr, evalRvalue, evalLvalue, evalLoc in *.\n\n    match goal with\n      | [ _ : context[match ?E with None => _ | _ => _ end] |- _ ] =>\n        match E with\n          | context[match _ with None => _ | _ => _ end] => fail 1\n          | _ => destruct E; try discriminate\n        end\n    end.\n    match goal with\n      | [ _ : context[match ?E with None => _ | _ => _ end] |- _ ] =>\n        match E with\n          | context[match _ with None => _ | _ => _ end] => fail 1\n          | _ => case_eq E; intros; match goal with\n                                      | [ H : _ = _ |- _ ] => rewrite H in *\n                                    end; try discriminate\n        end\n    end.\n    injection H20; clear H20; intros; subst; simpl Regs in *; simpl Mem in *.\n    match goal with\n      | [ _ : context[match ?E with None => _ | _ => _ end] |- _ ] =>\n        match E with\n          | context[match _ with None => _ | _ => _ end] => fail 1\n          | _ => case_eq E; intros; match goal with\n                                      | [ H : _ = _ |- _ ] => rewrite H in *\n                                    end; try discriminate\n        end\n    end.\n    injection H19; clear H19; intros; subst; simpl Mem in *; simpl Regs in *.\n    eapply ReadWriteEq in H.\n    rewrite H in H0.\n    rewrite <- H22.\n    unfold rupd; simpl.\n    assumption.\n\n    change (goodSize (offset + wordToNat (sel V pos))); eauto.\n\n    generalize H4; clear; intros.\n    simpl.\n    rewrite H4.\n    match goal with\n      | [ |- match match ?E1 with None => _ | _ => _ end with None => _ | _ => _ end\n        = match match ?E2 with None => _ | _ => _ end with None => _ | _ => _ end ] =>\n      replace E2 with E1; auto\n    end.\n    f_equal.\n    rewrite natToW_plus.\n    rewrite mult_comm; rewrite natToW_times4.\n    unfold natToW; rewrite natToWord_wordToNat.\n    W_eq.\n  Qed.\n\n  Opaque evalInstrs.\n\n  Lemma Rv_preserve : forall rv posV len,\n    rv = posV ^+ $(len)\n    -> rv = natToW (0 + wordToNat posV + len).\n    simpl; intros; subst.\n    rewrite natToW_plus.\n    f_equal.\n    symmetry; apply natToWord_wordToNat.\n  Qed.\n\n  Lemma guard_says_safe : forall stn st specs V ws r fr,\n    bexpTrue (guard p 0) stn st\n    -> Regs st Rv = sel V pos ^+ $(length p)\n    -> interp specs (![array ws (sel V stream) * locals (\"rp\" :: ns) V r (Regs st Sp) * fr] (stn, st))\n    -> In size ns\n    -> ~In \"rp\" ns\n    -> sel V size = $(length ws)\n    -> goodSize (wordToNat (sel V pos) + Datatypes.length p)\n    -> (0 + wordToNat (sel V pos) + length p <= length ws)%nat.\n    simpl; intros.\n    apply wle_goodSize.\n    rewrite natToW_plus.\n    unfold natToW; rewrite natToWord_wordToNat.\n    rewrite <- H1.\n    rewrite <- H5.\n    eapply bexpTrue_bound; eauto.\n    eauto.\n    eauto.\n  Qed.\n\n  Opaque variablePosition.\n\n  Hint Resolve Rv_preserve bexpSafe_guard guard_says_safe bexpFalse_not_matches simplify_reads.\n  Hint Immediate sym_eq.\n\n  Ltac wrap := wrap0; post; wrap1.\n\n  Definition Parse1 : cmd imports modName.\n    refine (Wrap _ H _ Parse1_\n      (fun pre x => Postcondition (Then (ThenPre pre)) x\n        \\/ Postcondition (Else (ElsePre pre)) x)%PropX\n      (fun pre =>\n        In stream ns\n        :: In size ns\n        :: In pos ns\n        :: (~In \"rp\" ns)\n        :: patternBound p\n        :: okVarName stream p\n        :: okVarName pos p\n        :: (forall stn st specs,\n          interp specs (pre (stn, st))\n          -> interp specs (ExX, Ex V, Ex ws, Ex r,\n            ![ ^[array ws (sel V stream) * locals (\"rp\" :: ns) V r (Regs st Sp)] * #0] (stn, st)\n            /\\ [| sel V size = length ws\n              /\\ goodSize (wordToNat (sel V pos) + length p)\n              /\\ (wordToNat (sel V pos) <= length ws)%nat |]))%PropX\n        :: VerifCond (Then (ThenPre pre))\n        ++ VerifCond (Else (ElsePre pre)))\n      _ _); abstract (wrap;\n        try match goal with\n              | [ H : context[reads] |- _ ] => generalize dependent H\n            end; evaluate auto_ext; intros; eauto;\n        repeat match goal with\n                 | [ H : evalInstrs _ _ (_ ++ _) = None |- _ ] =>\n                   apply evalInstrs_app_fwd_None in H; destruct H as [ | [ ? [ ? ] ] ]; intuition\n                 | [ H : evalInstrs _ _ (_ ++ _) = Some _ |- _ ] =>\n                   apply evalInstrs_app_fwd in H; destruct H as [ ? [ ] ]\n                 | [ H : evalInstrs _ _ (reads _ _) = Some _ |- _ ] =>\n                   edestruct (reads_exec _ _ H) as [V' [ ] ]; eauto; evaluate auto_ext\n               end;\n        try match goal with\n              | [ |- exists x, _ /\\ _ ] => eexists; split; [ solve [ eauto ] | try split; intros ];\n                try (autorewrite with sepFormula; simpl; eapply Imply_trans; [\n                  eapply unify; eauto\n                  | apply inj_imply; intuition; subst; simpl in * ] )\n              | _ => solve [ eapply reads_nocrash; eauto ]\n            end;\n        repeat match goal with\n                 | _ => solve [ eauto ]\n                 | [ H : _ = _ |- _ ] => rewrite H in *\n                 | [ |- context[suffix ?N _] ] =>\n                   match N with\n                     | 0 + _ => fail 1\n                     | _ =>\n                       change N with (0 + N)\n                   end\n                 | [ H : matches ?a (suffix ?b ?c) |- False ] =>\n                   assert (~matches a (suffix (0 + b) c)); try tauto; clear H\n                 | [ _ : evalInstrs _ ?x (reads _ _) = Some _ |- _ ] => exists x; split; eauto\n                 | _ => solve [ eapply bexpTrue_matches; eauto ]\n               end).\n  Defined.\n\nEnd Parse.\n\nDefinition ParseOne (stream size pos : string) (p : pattern) (Then Else : chunk) : chunk := fun ns res =>\n  Structured nil (fun _ _ H => Parse1 stream size pos p H (toCmd Then _ H ns res) (toCmd Else _ H ns res) ns).\n\nInfix \"++\" := (fun p1 p2 : pattern => app p1 p2) : pattern_scope.\nDelimit Scope pattern_scope with pattern.\n\nNotation \"'Match1' stream 'Size' size 'Position' pos 'Pattern' p { c1 } 'else' { c2 }\" :=\n  (ParseOne stream size pos p%pattern c1 c2)\n  (no associativity, at level 95, stream at level 0, size at level 0, pos at level 0, p at level 0) : SP_scope.\n\nLtac parse0 := try solve [ intuition congruence ].\n\nLtac especialize H :=\n  repeat match type of H with\n           | forall x : ?T, _ =>\n             let v := fresh in evar (v : T); let v' := eval unfold v in v in clear v; specialize (H v')\n         end.\n\nLtac parse1 solver :=\n  match goal with\n    | [ H : forall (a : _ -> _), _ |- _ ] =>\n      especialize H; post;\n      match goal with\n        | [ H : interp ?specs (?P ---> ?Q)%PropX |- _ ] =>\n          let H' := fresh in assert (H' : interp specs P) by (propxFo; step auto_ext || solver);\n            specialize (Imply_sound H H'); clear H H'; intro H\n      end; propxFo; autorewrite with StreamParse in *; simpl in *\n\n    | [ H : interp _ (![ _ ] _) |- _ ] => eapply Wrap.sepFormula_Mem in H; [ | eassumption ]\n  end.\n\nLtac reveal_slots :=\n  repeat match goal with\n           | [ H : evalInstrs _ _ _ = _ |- _ ] =>\n             progress unfold variableSlot in H; simpl in H\n         end.\n\nHint Rewrite roundTrip_0 sel_upd_eq sel_upd_ne using congruence : StreamParse.\n\nHint Extern 1 (_ <= _)%nat => omega : StreamParse.\n\nLtac parse2 := autorewrite with StreamParse; auto with StreamParse.\n\nDefinition ParseOne' stream size pos (pr : pattern * chunk) :=\n  ParseOne stream size pos (fst pr) (snd pr).\n\nNotation \"'Case' p c 'end'\" := (p%pattern, c)\n  (no associativity, at level 0, p at level 0, c at level 95, only parsing) : Case_scope.\nDelimit Scope Case_scope with Case_.\n\nNotation \"'Match' stream 'Size' size 'Position' pos { case1 ;; .. ;; caseN }\" :=\n  (fun c : chunk => ParseOne' stream size pos case1%Case_ (..\n    (ParseOne' stream size pos caseN%Case_\n      c) ..))\n  (no associativity, at level 95, stream at level 0, size at level 0, pos at level 0,\n    case1 at next level, caseN at next level) : SP_scope.\n\nNotation \"'Default' { c }\" := c (at level 0, c at level 95, no associativity, only parsing) : SP_scope.\n", "meta": {"author": "csgordon", "repo": "bedrock", "sha": "debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12", "save_path": "github-repos/coq/csgordon-bedrock", "path": "github-repos/coq/csgordon-bedrock/bedrock-debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12/examples/StreamParse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.24187998375596864}}
{"text": "Require Import Crypto.Reflection.Syntax.\nRequire Import Crypto.Reflection.Wf.\nRequire Import Crypto.Reflection.InlineInterp.\nRequire Import Crypto.Reflection.Z.Syntax.\nRequire Import Crypto.Reflection.Z.Inline.\n\nDefinition InterpInlineConst {interp_base_type interp_op} {t} (e : Expr base_type op t) (Hwf : Wf e)\n  : forall x, Interp interp_op (InlineConst e) x = Interp interp_op e x\n  := @InterpInlineConst _ interp_base_type _ _ _ t e Hwf.\n\nHint Rewrite @InterpInlineConst using solve [ eassumption | eauto with wf ] : reflective_interp.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_crypto_defined/src/Reflection/Z/InlineInterp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.24187998375596856}}
{"text": "(**\n CoqTL user theorem: Relational_name_definedness\n Def: if all objects in the source model have name defined,\n      then the target objects generated in the target model\n      have name defined. \n **)\n\nRequire Import String.\nRequire Import Coq.Logic.Eqdep_dec.\nRequire Import Arith.\nRequire Import Coq.Arith.Gt.\nRequire Import Coq.Arith.EqNat.\nRequire Import List.\n\nRequire Import core.utils.Utils.\nRequire Import core.SyntaxCertification.\nRequire Import core.Metamodel.\nRequire Import core.Model.\nRequire Import core.Syntax.\nRequire Import core.Engine.\n\nRequire Import transformations.Class2Relational.Class2Relational.\nRequire Import transformations.Class2Relational.ClassMetamodel.\nRequire Import transformations.Class2Relational.RelationalMetamodel.\n\n(*Ltac unfoldTransformationIn Tr Ht := \n  unfold Tr in Ht;\n  unfold ConcreteSyntax.parse in Ht; \n  unfold ConcreteSyntax.parseRule in Ht;\n  unfold ConcreteSyntax.parseOutputPatternElement in Ht;\n  unfold ConcreteSyntax.parseOutputPatternLink in Ht;\n  unfold Expressions.makeGuard in Ht;\n  unfold Expressions.makeElement in Ht;\n  unfold Expressions.makeIterator in Ht;\n  unfold Expressions.makeLink in Ht;\n  repeat (unfold Expressions.wrapOptionElement in Ht);\n  repeat (unfold Expressions.wrapOptionLink in Ht);\n  repeat (unfold Expressions.wrapOption in Ht);\n  simpl in Ht.\n\nLtac unfoldTransformation Tr := \n  unfold Tr;\n  unfold ConcreteSyntax.parse; \n  unfold ConcreteSyntax.parseRule;\n  unfold ConcreteSyntax.parseOutputPatternElement;\n  unfold ConcreteSyntax.parseOutputPatternLink;\n  unfold Expressions.makeGuard;\n  unfold Expressions.makeElement;\n  unfold Expressions.makeIterator;\n  unfold Expressions.makeLink;\n  repeat (unfold Expressions.wrapOptionElement);\n  repeat (unfold Expressions.wrapOptionLink);\n  repeat (unfold Expressions.wrapOption);\n  simpl.*)\n\nTheorem Relational_name_definedness:\nforall (te: TransformationEngine CoqTLSyntax) (cm : ClassModel) (rm : RelationalModel),\n  (* transformation *) rm = @execute _ _ te Class2Relational cm ->\n  (* precondition *)   (forall (c1 : ClassMetamodel_Object), In c1 (allModelElements cm) -> (ClassMetamodel_getName c1 <> \"\"%string)) ->\n  (* postcondition *)  (forall (t1 : RelationalMetamodel_Object), In t1 (allModelElements rm) -> (RelationalMetamodel_getName t1 <> \"\"%string)). \nProof.\n  intros.\n  rewrite H in H1.\n  rewrite (@tr_execute_in_elements _ _ te Class2Relational) in H1.\n  do 2 destruct H1.\n  destruct x as [| c]. (* Case analysis on source pattern *)\n  - rewrite (@tr_instantiatePattern_in _ _ te Class2Relational) in H2.\n    do 2 destruct H2.\n    rewrite (@tr_matchPattern_in _ _ te Class2Relational) in H2.\n    destruct H2.\n    rewrite (@tr_matchRuleOnPattern_leaf _ _ te Class2Relational) in H4.\n    simpl in H2.\n    destruct H2.\n    + rewrite <- H2 in H4.\n      simpl in H4.\n      inversion H4.\n    + destruct H2.\n      rewrite <- H2 in H4.\n      simpl in H4.\n      inversion H4.\n      contradiction H2.\n  - destruct x as [| c0].\n    + (* Singleton *) specialize (H0 c). \n      apply allTuples_incl in H1.\n      unfold incl in H1.\n      specialize (H1 c).\n      assert (In c [c]). { left. reflexivity. }\n      specialize (H0 (H1 H3)).\n      do 2 destruct c. (* Case analysis on source element type *)\n      * (* [Class] *) \n        rewrite (@tr_instantiatePattern_in _ _ te Class2Relational) in H2.\n        do 2 destruct H2.\n        rewrite (@tr_matchPattern_in _ _ te Class2Relational) in H2.\n        destruct H2.\n        rewrite (@tr_matchRuleOnPattern_leaf _ _ te Class2Relational) in H5.\n        simpl in H2.\n        rewrite (@tr_instantiateRuleOnPattern_in _ _ te Class2Relational) in H4.\n        do 2 destruct H4.\n        apply tr_instantiateIterationOnPattern_in in H6.\n        do 2 destruct H6.\n        rewrite tr_instantiateElementOnPattern_leaf in H7.\n        destruct H2.\n        ** (* Class2Table *) \n           rewrite <- H2 in H6.\n           simpl in H6.\n           destruct H6.\n           *** rewrite <- H6 in H7.\n               simpl in H7.\n               inversion H7.\n               simpl. \n               apply H0.\n           *** contradiction H6.\n        ** destruct H2.\n           ***  (* Attribute2Column contradict *)\n                rewrite <- H2 in H6.\n                simpl in H6.\n                destruct H6.\n                **** rewrite <- H6 in H7. simpl in H7. \n                     inversion H7.\n                **** contradiction H6.\n           *** contradiction H2.\n      * (* [Attribute] *) destruct c0.\n        destruct b.\n        -- (* derived *) \n           rewrite (@tr_instantiatePattern_in _ _ te Class2Relational) in H2.\n           do 2 destruct H2.\n           rewrite (@tr_matchPattern_in _ _ te Class2Relational) in H2.\n           destruct H2.\n           rewrite (@tr_matchRuleOnPattern_leaf _ _ te Class2Relational) in H5.\n           simpl in H2. \n           destruct H2.\n           ** rewrite <- H2 in H5.\n              simpl in H5.\n              inversion H5.\n           ** destruct H2.\n              *** rewrite <- H2 in H5.\n                  simpl in H5.\n                  inversion H5.\n              *** contradiction H2.\n        -- (* not derived *) \n            rewrite (@tr_instantiatePattern_in _ _ te Class2Relational) in H2.\n            do 2 destruct H2.\n            rewrite (@tr_matchPattern_in _ _ te Class2Relational) in H2.\n            destruct H2.\n            rewrite (@tr_matchRuleOnPattern_leaf _ _ te Class2Relational) in H5.\n            simpl in H2.\n            rewrite (@tr_instantiateRuleOnPattern_in _ _ te Class2Relational) in H4.\n            do 2 destruct H4.\n            apply tr_instantiateIterationOnPattern_in in H6.\n            do 2 destruct H6.\n            rewrite tr_instantiateElementOnPattern_leaf in H7.\n            destruct H2.\n            **  (* Class2Table contradict *)\n                 rewrite <- H2 in H6.\n                 simpl in H6.\n                 destruct H6.\n                 *** rewrite <- H6 in H7. simpl in H7. \n                      inversion H7.\n                 *** contradiction H6.\n            ** (* Attribute2Column *) \n               destruct H2.\n               *** rewrite <- H2 in H6.\n                   simpl in H6.\n                   destruct H6.\n                   **** rewrite <- H6 in H7.\n                        simpl in H7.\n                        inversion H7.\n                        simpl. \n                        apply H0.\n                   **** contradiction H6.\n               *** contradiction H2.\n    + (* Other patterns *) do 2 destruct c.\n      * destruct c0. \n        rewrite (@tr_instantiatePattern_in _ _ te Class2Relational) in H2.\n        do 2 destruct H2.\n        rewrite (@tr_matchPattern_in _ _ te Class2Relational) in H2.\n        destruct H2.\n        rewrite (@tr_matchRuleOnPattern_leaf _ _ te Class2Relational) in H4.\n        simpl in H2.\n        destruct H2.\n        ** rewrite <- H2 in H4.\n          simpl in H4.\n          inversion H4.\n        ** destruct H2.\n          rewrite <- H2 in H4.\n          simpl in H4.\n          inversion H4.\n          contradiction H2.\n      * destruct c0. \n        rewrite (@tr_instantiatePattern_in _ _ te Class2Relational) in H2.\n        do 2 destruct H2.\n        rewrite (@tr_matchPattern_in _ _ te Class2Relational) in H2.\n        destruct H2.\n        rewrite (@tr_matchRuleOnPattern_leaf _ _ te Class2Relational) in H4.\n        simpl in H2.\n        destruct H2.\n        ** rewrite <- H2 in H4.\n          simpl in H4.\n          inversion H4.\n        ** destruct H2.\n          rewrite <- H2 in H4.\n          simpl in H4.\n          inversion H4.\n          contradiction H2.\nQed.\n\n(* Alternative for (* [Attribute] *):\n      unfold instantiatePattern in H2. \n      unfold matchPattern in H2.\n      unfold matchRuleOnPattern in H2. simpl in H2.\n      destruct (negb (getAttributeDerived c0)). \n      -- simpl in H2. destruct H2. \n        ++ rewrite <- H2. simpl. simpl in H0. assumption.\n        ++ contradiction H2. \n      --  contradiction H2.*)\n\n(* Alternative for (* Other patterns *): \n      apply maxArity_length with (sp:=c::c0::x) (tr:=Class2Relational) (sm:=cm).\n      * unfold maxArity. simpl. omega.\n      * assumption. *)\n\n(*Ltac destructPattern sp tr sm h := \n  destruct sp;\n  [> contradiction | \n     repeat\n      destruct sp;\n       [> \n          | exfalso;\n            apply maxArity_length with (sp:=c::c0::x) (tr:=tr) (sm:=sm);\n            [> \n              parseTransformationInGoal tr; unfold maxArity; simpl; omega |\n              assumption \n            ]\n            +\n            destruct sp;\n       ]  \n  ].*)\n  \n\nLtac destruct_execute Hexecute sp Hin Hinstantiate :=\n  apply tr_execute_in_elements in Hexecute;\n  destruct Hexecute as [sp [Hin Hinstantiate]].\n\nLtac destruct_instantiatePattern Hinstantiate rule Hrule HinstRule :=\n  apply tr_instantiatePattern_in in Hinstantiate;\n  destruct Hinstantiate as [rule [Hrule HinstRule]].\n\nLtac destruct_matchPattern Hrule Hr Hmatch :=\n  apply tr_matchPattern_in in Hrule;\n  destruct Hrule as [Hr Hmatch].\n\nLtac destruct_rule Hrule :=\n  repeat (destruct Hrule as [Hrule | Hrule]; try contradiction Hrule); destruct Hrule.\n\nLtac destruct_pattern Hinst sp :=\n  repeat (let se := fresh \"se\" in\n          destruct sp as [ | se sp ];\n          [ | destruct se as [[] ?] eqn:?];\n          try contradiction Hinst);\n  destruct Hinst as [Hinst | []]; simpl in Hinst.\n\n(* \n\nTheorem Relational_name_definedness':\nforall (cm : ClassModel) (rm : RelationalModel),\n  (* transformation *) rm = execute Class2Relational cm ->\n  (* precondition *)   (forall (c1 : ClassMetamodel_Object), In c1 (allModelElements cm) -> (ClassMetamodel_getName c1 <> \"\"%string)) ->\n  (* postcondition *)  (forall (t1 : RelationalMetamodel_Object), In t1 (allModelElements rm) -> (RelationalMetamodel_getName t1 <> \"\"%string)).\nProof.\n  intros. subst rm.\n  destruct_execute H1 sp Hin Hinst. (* t1 comes from a pattern sp *)\n  apply allTuples_incl in Hin. (* sp is made of source model elements *)\n  destruct_instantiatePattern Hinst r Hr Hinst. (* sp matches a rule r *)\n  destruct_matchPattern Hr Hr Hmatch. (* r comes from the transformation *)\n  clear Hmatch. (* Hmatch is not used for this proof *)\n  destruct_rule Hr; (* case analysis on rules *)\n    destruct_pattern Hinst sp. (* retrieve the source pattern for each rule *)\n  - (* Class2Table *) specialize (H0 se). crush.\n  - (* Attribute2Column *) specialize (H0 se). crush.\nQed.\n\n*)", "meta": {"author": "atlanmod", "repo": "coqtl", "sha": "5daf5d915b66328ae5ec48f55c44731372563c87", "save_path": "github-repos/coq/atlanmod-coqtl", "path": "github-repos/coq/atlanmod-coqtl/coqtl-5daf5d915b66328ae5ec48f55c44731372563c87/transformations/Class2Relational/theorems/Relational_name_definedness_spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2418660890923268}}
{"text": "Require Import UFO.Lang.BindingsFacts.\nRequire Import UFO.Lang.Static.\nRequire Import UFO.Rel.Definitions.\nRequire Import UFO.Rel.BasicFacts.\nRequire Import UFO.Rel.Monotone.\nRequire Import UFO.Rel.Compat_bind_LV.\nRequire Import UFO.Util.Subset.\nRequire Import UFO.Util.Postfix.\nSet Implicit Arguments.\n\nSection section_ccompat_tm_app_lbl.\nContext (n : nat).\nContext (EV LV : Set).\nContext (Ξ : XEnv EV LV).\nContext (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig).\nContext (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig).\nContext (σ : ms ∅ EV (inc LV) ∅) (ℓ ℓ' : lbl LV ∅) (E : eff ∅ EV LV ∅).\nContext (Wf_ℓ : wf_lbl Ξ ℓ).\nContext (ξ₁ ξ₂ : list var).\nContext (t₁ t₂ : tm0).\nContext (Hξ : n ⊨ (𝜩 Ξ ξ₁ ξ₂)ᵢ).\nContext (Hρ₁ρ₂ : n ⊨ (ρ₁ρ₂_are_closed ξ₁ ξ₂ ρ₁ ρ₂)ᵢ).\n\nLemma ccompat_tm_app_lbl :\nn ⊨ 𝓣⟦ Ξ ⊢ (ty_ms (ms_lv σ) ℓ') # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ →\nn ⊨ 𝓣⟦ Ξ ⊢ (ty_ms (LV_subst_ms ℓ σ) ℓ') # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ\n    ξ₁ ξ₂\n    (tm_app_lbl t₁ (LV_bind_lbl ρ₁ ℓ))\n    (tm_app_lbl t₂ (LV_bind_lbl ρ₂ ℓ)).\nProof.\nintro Ht.\nchange (tm_app_lbl t₁ (LV_bind_lbl ρ₁ ℓ))\nwith (ktx_plug (ktx_app_lbl ktx_hole (LV_bind_lbl ρ₁ ℓ)) t₁).\nchange (tm_app_lbl t₂ (LV_bind_lbl ρ₂ ℓ))\nwith (ktx_plug (ktx_app_lbl ktx_hole (LV_bind_lbl ρ₂ ℓ)) t₂).\neapply plug0 ; simpl ; eauto using postfix_refl.\nclear t₁ t₂ Ht.\n\niintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂' ;\niintro v₁ ; iintro v₂ ; iintro Hv ; simpl.\ndestruct v₁ as [ | | | m₁ [ | X₁' ] | m₁ [ | X₁' ] ], v₂ as [ | | | m₂ [ | X₂' ] | m₂ [ | X₂' ] ] ; simpl 𝓥_Fun in Hv ;\nidestruct Hv as m₁' Hv ; idestruct Hv as m₂' Hv ;\nidestruct Hv as X₁'' Hv ; idestruct Hv as X₂'' Hv ;\nidestruct Hv as Hv Hr ; ielim_prop Hv ; destruct Hv as [Hv₁ Hv₂] ;\ninversion Hv₁ ; inversion Hv₂ ; clear Hv₁ Hv₂ ; subst m₁' m₂' X₁'' X₂''.\n\nidestruct Hr as HX₁'X₂' Hr ; idestruct Hr as m₁' Hr ; idestruct Hr as m₂' Hr ;\nidestruct Hr as Hm Hr ; ielim_prop Hm ; destruct Hm ; subst m₁ m₂.\neapply 𝓣_step_r ; [ apply step_app_lbl | ].\neapply 𝓣_step_l ; [ apply step_app_lbl | ].\niintro_later.\napply 𝓥_in_𝓣.\nsimpl 𝓥_Fun.\nrepeat ieexists ; repeat isplit ; [ iintro_prop ; crush | apply HX₁'X₂' | ].\nclear HX₁'X₂'.\n\nielim_vars Hr ; [ | apply postfix_refl | apply postfix_refl ].\ndestruct (LV_bind_lbl ρ₁ ℓ) as [ | [ | X₁ ] ] eqn:HX₁ ; [ auto | auto | ].\ndestruct (LV_bind_lbl ρ₂ ℓ) as [ | [ | X₂ ] ] eqn:HX₂ ; [ auto | auto | ].\nispecialize Hr X₁.\nispecialize Hr X₂.\nispecialize Hr (𝓣𝓵⟦ Ξ ⊢ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ).\n\nispecialize Hr.\n{ clear Hr.\n  apply postfix_is_subset in Hξ₁' ; apply postfix_is_subset in Hξ₂'.\n  destruct ℓ as [ α | [ | X ] ] ; [ | auto | ] ; simpl in HX₁, HX₂.\n  + ielim_prop Hρ₁ρ₂ ; specialize (Hρ₁ρ₂ α) ; rewrite HX₁, HX₂ in Hρ₁ρ₂.\n    iintro_prop ; split.\n    - destruct (Hρ₁ρ₂ X₁) as [? _] ; auto.\n    - destruct (Hρ₁ρ₂ X₂) as [_ ?] ; auto.\n  + inversion HX₁ ; inversion HX₂ ; subst X₁ X₂.\n    inversion Wf_ℓ ; subst.\n    ielim_prop Hξ ; destruct Hξ as [Hξ₁ Hξ₂].\n    iintro_prop ; crush.\n}\n\nreplace Ξ with (LV_subst_XEnv ℓ (LV_shift_XEnv Ξ))\nby (erewrite LV_bind_map_XEnv, LV_bind_XEnv_id, LV_map_XEnv_id ; crush).\nreplace ℓ' with (LV_subst_lbl ℓ (LV_shift_lbl ℓ'))\nby (erewrite LV_bind_map_lbl, LV_bind_lbl_id, LV_map_lbl_id ; crush).\nerewrite <- I_iff_elim_M ; [ apply Hr | clear Hr ].\napply LV_bind_𝓜.\n+ crush.\n+ crush.\n+ iintro α ; destruct α as [ | α ] ; repeat iintro ; simpl.\n  - erewrite LV_bind_map_XEnv, LV_map_XEnv_id, LV_bind_XEnv_id ;\n    try reflexivity ; try auto_contr.\n  - auto_contr.\n+ erewrite LV_bind_map_XEnv, LV_map_XEnv_id, LV_bind_XEnv_id ; try reflexivity.\n  intro α ; destruct α as [ | α ] ; simpl ; [ assumption | constructor ].\nQed.\n\nEnd section_ccompat_tm_app_lbl.\n\n\nSection section_compat_tm_app_lbl.\nContext (EV LV V : Set).\nContext (Ξ : XEnv EV LV).\nContext (Γ : V → ty ∅ EV LV ∅).\nContext (σ : ms ∅ EV (inc LV) ∅) (ℓ ℓ' : lbl LV ∅) (E : eff ∅ EV LV ∅).\nContext (Wf_ℓ : wf_lbl Ξ ℓ).\n\nLemma compat_tm_app_lbl n t₁ t₂ :\nn ⊨ ⟦ Ξ Γ ⊢ t₁ ≼ˡᵒᵍ t₂ : (ty_ms (ms_lv σ) ℓ') # E ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ (tm_app_lbl t₁ ℓ) ≼ˡᵒᵍ (tm_app_lbl t₂ ℓ) :\n      (ty_ms (LV_subst_ms ℓ σ) ℓ') # E ⟧.\nProof.\nintro Ht.\niintro ξ₁ ; iintro ξ₂ ;\niintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ;\niintro γ₁ ; iintro γ₂ ;\niintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.\nsimpl subst_tm.\napply ccompat_tm_app_lbl ; try assumption.\n\niespecialize Ht ; repeat (ispecialize Ht ; [ eassumption | ]).\napply Ht.\nQed.\n\nLemma compat_ktx_app_lbl n T_hole E_hole K₁ K₂ :\nn ⊨ ⟦ Ξ Γ ⊢ K₁ ≼ˡᵒᵍ K₂ :\n      T_hole # E_hole ⇢ (ty_ms (ms_lv σ) ℓ') # E ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ (ktx_app_lbl K₁ ℓ) ≼ˡᵒᵍ (ktx_app_lbl K₂ ℓ) :\n      T_hole # E_hole ⇢ (ty_ms (LV_subst_ms ℓ σ) ℓ') # E ⟧.\nProof.\nintro HK.\niintro ξ₁ ; iintro ξ₂ ;\niintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ;\niintro γ₁ ; iintro γ₂.\niintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.\niintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂' ;\niintro t₁ ; iintro t₂ ; iintro Ht.\niespecialize HK.\nispecialize HK ; [ eassumption | ].\nispecialize HK ; [ eassumption | ].\nispecialize HK ; [ eassumption | ].\nispecialize HK ; [ eassumption | ].\nielim_vars HK ; [ | eassumption | eassumption ].\niespecialize HK.\nispecialize HK ; [ eassumption | ].\nsimpl ktx_plug.\napply ccompat_tm_app_lbl ; try apply HK.\n- assumption.\n- iintro_prop ; eapply 𝜩_monotone ; eauto.\n- iintro_prop ; eapply ρ₁ρ₂_are_closed_monotone ; eauto.\nQed.\n\nEnd section_compat_tm_app_lbl.\n", "meta": {"author": "yizhouzhang", "repo": "olaf-coq", "sha": "03090a5e60e739dfa45ad60322d848c18faad48d", "save_path": "github-repos/coq/yizhouzhang-olaf-coq", "path": "github-repos/coq/yizhouzhang-olaf-coq/olaf-coq-03090a5e60e739dfa45ad60322d848c18faad48d/coq-src/UFO/Rel/Compat_tm_app_lbl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2418660890923267}}
{"text": "Require Import Thread0 Connect Bootstrap.\n\n\nModule Type S.\n  Parameter heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nModule M'.\n  Definition globalSched : W := ((heapSize + 50) * 4)%nat.\n\n  Definition inbuf_size := 40.\n\n  Theorem inbuf_size_lower : (inbuf_size >= 2)%nat.\n    unfold inbuf_size; auto.\n  Qed.\n\n  Theorem inbuf_size_upper : (N_of_nat (inbuf_size * 4) < Npow2 32)%N.\n    reflexivity.\n  Qed.\nEnd M'.\n\nImport M'.\n\nModule E := Connect.Make(M').\nImport E.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 1.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 1.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"connect\"!\"main\" @ [E.mainS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREmain[_] globalSched =?> 1 * 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREmain[_] globalSched =?> 1 * mallocHeap 0];;\n\n        Goto \"connect\"!\"main\"\n      end\n    }}.\n\n  Ltac t := unfold globalSched, localsInvariantMain, M'.globalSched; genesis.\n\n  Theorem ok0 : moduleOk boot.\n    vcgen; abstract t.\n  Qed.\n\n  Definition m1 := link Buffers.m boot.\n  Definition m2 := link E.m m1.\n  Definition m := link m2 E.T.T.m.\n\n  Lemma ok1 : moduleOk m1.\n    link Buffers.ok ok0.\n  Qed.\n\n  Lemma ok2 : moduleOk m2.\n    link E.ok ok1.\n  Qed.\n\n  Theorem ok : moduleOk m.\n    link ok2 E.T.T.ok.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n  \n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, $(size * 4) <= w -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/tests/ConnectDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.3775406617944891, "lm_q1q2_score": 0.24186608460553335}}
{"text": "Require Import floyd.proofauto.\nRequire Import Coqlib.\nRequire Import Recdef.\nExisting Instance NullExtension.Espec.\nRequire Import progs.switch.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition twice_spec :=\n  DECLARE _twice\n    WITH n : Z\n    PRE [ _n OF tint ]\n      PROP  (0 <= n+n <= Int.max_unsigned)\n      LOCAL (temp _n (Vint (Int.repr n)))\n      SEP ()\n    POST [ tint ]\n      PROP ()\n      LOCAL (temp ret_temp (Vint (Int.repr (n+n))))\n      SEP ().\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [twice_spec]).\n\nLemma body_twice: semax_body Vprog Gprog f_twice twice_spec.\nProof.\nstart_function.\nforward_if (PROP() LOCAL(temp _n (Vint (Int.repr (n+n)))) SEP()).\nrepeat forward; entailer!.\nrepeat forward; entailer!.\nrepeat forward; entailer!.\nrepeat forward; entailer!.\nrepeat forward; entailer!.\nQed.\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/progs/verif_switch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24186162614190215}}
{"text": "(** * Context Reduction Basics *)\n\n(** Reformulation of de Boer and Bonsangue's basic setup in the context-reduction setting *)\n\nFrom Coq Require Import String Bool Datatypes Relations Program.Equality.\nFrom Coq Require Import Classes.RelationClasses.\nFrom Coq Require Import Logic.FunctionalExtensionality. (* for equality of substitutions *)\n\nFrom SymEx Require Import Expr.\nImport BasicExpr.\n\nFrom SymEx Require Import Maps.\nImport BasicMaps.\n\nFrom SymEx Require Import Parallel.\n\nFrom SymEx Require Import ContextReduction.\n\nInductive head_red__S: relation (sub * Bexpr * Stmt) :=\n| SAsgn_step: forall x e sig phi,\n    head_red__S (sig, phi, <{x := e}>) ((x !-> Aapply sig e; sig), phi, SSkip)\n| SIfTrue_step: forall b s1 s2 sig phi,\n    head_red__S (sig, phi, <{if b {s1} {s2}}>) (sig, BAnd phi (Bapply sig b), s1)\n| SIfFalse_step: forall b s1 s2 sig phi,\n    head_red__S (sig, phi, <{if b {s1} {s2}}>) (sig, BAnd phi (BNot (Bapply sig b)), s2)\n| SWhileTrue_step: forall b s sig phi,\n    head_red__S (sig, phi, <{while b {s}}>) (sig, BAnd phi (Bapply sig b), <{s ; while b {s}}>)\n| SWhileFalse_step: forall b s sig phi,\n    head_red__S (sig, phi, <{while b {s}}>) (sig, BAnd phi (BNot (Bapply sig b)), SSkip)\n| SSeq_skip: forall s sig phi,\n    head_red__S (sig, phi, <{skip ; s}>) (sig, phi, s)\n| SPar_left_skip: forall s sig phi,\n    head_red__S (sig, phi, <{skip || s}>) (sig, phi, s)\n| SPar_right_skip: forall s sig phi,\n    head_red__S (sig, phi, <{s || skip}>) (sig, phi, s)\n.\n\nDefinition Sstep: relation (sub * Bexpr * Stmt) := context_red is_context head_red__S.\nDefinition multi_Sstep := clos_refl_trans_n1 _ Sstep.\n\nNotation \" c '->s' c'\" := (Sstep c c') (at level 40).\nNotation \" c '->*' c'\" := (multi_Sstep c c') (at level 40).\n\nInductive head_red__C: relation (Valuation * Stmt) :=\n| CAsgn_step: forall x e V,\n    head_red__C (V, <{x := e}>) ((x !-> Aeval V e ; V), SSkip)\n| CIfTrue_step: forall b s1 s2 V,\n    Beval V b = true ->\n    head_red__C (V, <{if b {s1} {s2}}>) (V, s1)\n| CIfFalse_step: forall b s1 s2 V,\n    Beval V b = false ->\n    head_red__C (V, <{if b {s1} {s2}}>) (V, s2)\n| CWhileTrue_step: forall b s V,\n    Beval V b = true ->\n    head_red__C (V, <{while b {s}}>) (V, <{s ; while b {s}}>)\n| CWhileFalse_step: forall b s V,\n    Beval V b = false ->\n    head_red__C (V, <{while b {s}}>) (V, SSkip)\n| CSeq_skip: forall s V,\n    head_red__C (V, <{skip ; s}>) (V, s)\n| CPar_left_skip: forall s V,\n    head_red__C (V, <{skip || s}>) (V, s)\n| CPar_right_skip: forall s V,\n    head_red__C (V, <{s || skip}>) (V, s)\n.\n\nDefinition Cstep: relation (Valuation * Stmt) := context_red is_context head_red__C.\nDefinition multi_Cstep := clos_refl_trans_n1 _ Cstep.\n\nNotation \" c '=>c' c'\" := (Cstep c c') (at level 40).\nNotation \" c '=>*' c'\" := (multi_Cstep c c') (at level 40).\n\nTheorem correctness : forall s s' sig phi V,\n    (id_sub, BTrue, s) ->* (sig, phi, s') ->\n    Beval V phi = true ->\n    (V, s) =>* (Comp V sig, s').\nProof.\n  intros. dependent induction H.\n  - rewrite comp_id. constructor.\n  - dependent destruction H. destruct x as [sig0 phi0]. dependent destruction H; econstructor;\n      (* simplify path condition for use in the concrete step *)\n      try (simpl in H2; apply andb_true_iff in H2; destruct H2; try (apply negb_true_iff in H2);\n        rewrite <- comp_subB in H2).\n    + constructor.\n      * rewrite asgn_sound. constructor.\n      * assumption.\n    + eapply IHclos_refl_trans_n1; try reflexivity; assumption.\n    + constructor.\n      * constructor. apply H2.\n      * assumption.\n    + eapply IHclos_refl_trans_n1; try reflexivity; assumption.\n    + constructor.\n      * apply CIfFalse_step. apply H2.\n      * assumption.\n    + eapply IHclos_refl_trans_n1; try reflexivity; assumption.\n    + constructor.\n      * apply CWhileTrue_step. apply H2.\n      * assumption.\n    + eapply IHclos_refl_trans_n1; try reflexivity; assumption.\n    + constructor.\n      * apply CWhileFalse_step. apply H2.\n      * assumption.\n    + eapply IHclos_refl_trans_n1; try reflexivity; assumption.\n    + constructor.\n      * apply CSeq_skip.\n      * assumption.\n    + eapply IHclos_refl_trans_n1; try reflexivity; assumption.\n    + constructor.\n      * apply CPar_left_skip.\n      * assumption.\n    + eapply IHclos_refl_trans_n1; try reflexivity; assumption.\n    + constructor.\n      * apply CPar_right_skip.\n      * assumption.\n    + eapply IHclos_refl_trans_n1; try reflexivity; assumption.\nQed.\n\nLtac splits := repeat (try split).\n\nTheorem completeness : forall s s' V0 V,\n    (V0, s) =>* (V, s') ->\n    exists sig phi, (id_sub, BTrue, s) ->* (sig, phi, s') /\\ Beval V0 phi = true /\\ V = Comp V0 sig.\nProof.\n  intros. dependent induction H.\n  - exists id_sub. exists BTrue. splits. constructor.\n  - dependent destruction H. dependent destruction H.\n    + destruct (IHclos_refl_trans_n1 s (C <{x0 := e}>) V0 x) as [sig [phi [IHcomp [IHval IHupd]]]];\n        try reflexivity.\n      eexists. eexists. splits.\n      * econstructor.\n        ** constructor; [apply SAsgn_step\n                        | assumption].\n        ** apply IHcomp.\n      * assumption.\n      * rewrite asgn_sound. rewrite IHupd. reflexivity.\n    + destruct (IHclos_refl_trans_n1 s (C <{if b {s'0}{s2}}>) V0 V) as [sig [phi [IHcomp [IHval IHupd]]]];\n        try reflexivity.\n      eexists. eexists. splits.\n      * econstructor.\n        ** constructor; [apply SIfTrue_step\n                        | assumption].\n        ** apply IHcomp.\n      * simpl. apply andb_true_iff. split.\n        ** assumption.\n        ** rewrite <- comp_subB. rewrite <- IHupd. assumption.\n      * assumption.\n    + destruct (IHclos_refl_trans_n1 s (C <{if b {s1}{s'0}}>) V0 V) as [sig [phi [IHcomp [IHval IHupd]]]];\n        try reflexivity.\n      eexists. eexists. splits.\n      * econstructor.\n        ** constructor; [apply SIfFalse_step\n                        | assumption].\n        ** apply IHcomp.\n      * simpl. apply andb_true_iff. split.\n        ** assumption.\n        ** rewrite <- comp_subB. rewrite <- IHupd. apply negb_true_iff. assumption.\n      * assumption.\n    + destruct (IHclos_refl_trans_n1 s (C <{while b {s1}}>) V0 V) as [sig [phi [IHcomp [IHval IHupd]]]];\n        try reflexivity.\n      eexists. eexists. splits.\n      * econstructor.\n        ** constructor; [apply SWhileTrue_step\n                        | assumption].\n        ** apply IHcomp.\n      * simpl. apply andb_true_iff. split.\n        ** assumption.\n        ** rewrite <- comp_subB. rewrite <- IHupd. assumption.\n      * assumption.\n    + destruct (IHclos_refl_trans_n1 s (C <{while b {s1}}>) V0 V) as [sig [phi [IHcomp [IHval IHupd]]]];\n        try reflexivity.\n      eexists. eexists. splits.\n      * econstructor.\n        ** constructor; [apply SWhileFalse_step\n                        | assumption].\n        ** apply IHcomp.\n      * simpl. apply andb_true_iff. split.\n        ** assumption.\n        ** rewrite <- comp_subB. rewrite <- IHupd. apply negb_true_iff. assumption.\n      * assumption.\n    + destruct (IHclos_refl_trans_n1 s (C <{skip ; s'0}>) V0 V) as [sig [phi [IHcomp [IHval IHupd]]]];\n        try reflexivity.\n      exists sig. exists phi. splits; try assumption.\n      econstructor.\n      * constructor; [apply SSeq_skip | assumption].\n      *  apply IHcomp.\n    + destruct (IHclos_refl_trans_n1 s (C <{skip || s'0}>) V0 V) as [sig [phi [IHcomp [IHval IHupd]]]];\n        try reflexivity.\n      exists sig. exists phi. splits; try assumption.\n      econstructor.\n      * constructor; [apply SPar_left_skip | assumption].\n      *  apply IHcomp.\n    + destruct (IHclos_refl_trans_n1 s (C <{s'0 || skip}>) V0 V) as [sig [phi [IHcomp [IHval IHupd]]]];\n        try reflexivity.\n      exists sig. exists phi. splits; try assumption.\n      econstructor.\n      * constructor; [apply SPar_right_skip | assumption].\n      *  apply IHcomp.\nQed.\n", "meta": {"author": "Aqissiaq", "repo": "symex-formally-formalized", "sha": "3fa3e8e527bfb9419fabaa906707d4d1f54c52cb", "save_path": "github-repos/coq/Aqissiaq-symex-formally-formalized", "path": "github-repos/coq/Aqissiaq-symex-formally-formalized/symex-formally-formalized-3fa3e8e527bfb9419fabaa906707d4d1f54c52cb/BasicContextReduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24186162614190215}}
{"text": "\n\nRequire Export List.\nExport ListNotations.\nSet Implicit Arguments.\n\nFrom Coq Require Import ssreflect.\n\n(* Add LoadPath \"../modal\".\nAdd LoadPath \"../tense-lns\". *)\nRequire Import gen genT ddT gen_tacs.\nRequire Import gstep.\nRequire Import List_lemmasT swappedT existsT.\nRequire Import Coq.Program.Basics.\n\nInductive rlsmap U W (f : U -> W) (rls : rlsT U) : rlsT W :=\n  | rmI : forall ps c, rls ps c -> rlsmap f rls (map f ps) (f c).\n\nLemma rmI_eq U W (f : U -> W) (rls : rlsT U) ps c mps mc :\n  rls ps c -> mps = map f ps -> mc = f c -> rlsmap f rls mps mc.\nProof. intros. subst. apply rmI ; assumption. Qed.\n\nInductive relmap U W (f : U -> W) (rel : relationT U) : relationT W :=\n  | rlI : forall p c, rel p c -> relmap f rel (f p) (f c).\n\nLemma rlI_eq U W (f : U -> W) (rel : relationT U) p c mp mc :\n  rel p c -> mp = f p -> mc = f c -> relmap f rel mp mc.\nProof. intros. subst. apply rlI ; assumption. Qed.\n\n(** seqext, seqrule, extending sequent and rule with left- and right-contexts\n  in antecedent and consequent **)\nDefinition seqext (W : Type) Γ1 Γ2 Δ1 Δ2 (seq : rel (list W)) :=\n  match seq with | pair U V => pair (Γ1 ++ U ++ Γ2) (Δ1 ++ V ++ Δ2) end.\n\nLemma seqext_seqext: forall V (Γ1 Γ2 Δ1 Δ2 Φ1 Φ2 Ψ1 Ψ2 : list V) seq,\n  seqext Γ1 Γ2 Δ1 Δ2 (seqext Φ1 Φ2 Ψ1 Ψ2 seq) =\n  seqext (Γ1 ++ Φ1) (Φ2 ++ Γ2) (Δ1 ++ Ψ1) (Ψ2 ++ Δ2) seq.\nProof. intros. unfold seqext. destruct seq.\nrewrite !app_assoc. reflexivity. Qed.  \n\nLemma map_seqext_seqext: forall V (Γ1 Γ2 Δ1 Δ2 Φ1 Φ2 Ψ1 Ψ2 : list V) seqs,\n  map (seqext Γ1 Γ2 Δ1 Δ2) (map (seqext Φ1 Φ2 Ψ1 Ψ2) seqs) =\n  map (seqext (Γ1 ++ Φ1) (Φ2 ++ Γ2) (Δ1 ++ Ψ1) (Ψ2 ++ Δ2)) seqs.\nProof. induction seqs. tauto. \nsimpl. rewrite IHseqs. rewrite seqext_seqext. reflexivity. Qed.  \n\nInductive seqrule (W : Type) (pr : rlsT (rel (list W))) : \n    rlsT (rel (list W)) := \n  | Sctxt : forall ps c Φ1 Φ2 Ψ1 Ψ2, pr ps c -> \n    seqrule pr (map (seqext Φ1 Φ2 Ψ1 Ψ2) ps) (seqext Φ1 Φ2 Ψ1 Ψ2 c).\n\nLemma seqext_def : forall (W : Type) Φ1 Φ2 Ψ1 Ψ2 U V,\n      @seqext W Φ1 Φ2 Ψ1 Ψ2 (U,V) = (Φ1 ++ U ++ Φ2, Ψ1 ++ V ++ Ψ2).\nProof. reflexivity. Qed.\n\nLemma Sctxt_e: forall (W : Type) (pr : rlsT (rel (list W))) ps U V Φ1 Φ2 Ψ1 Ψ2,\n  pr ps (U, V) ->\n  seqrule pr (map (seqext Φ1 Φ2 Ψ1 Ψ2) ps) (Φ1 ++ U ++ Φ2, Ψ1 ++ V ++ Ψ2).\nProof.\n  intros until 0. intros H. rewrite <- seqext_def.\n  apply Sctxt. exact H.\nQed.\n\nLemma Sctxt_eq: forall (W : Type) pr ps mps (ca cs U V Φ1 Φ2 Ψ1 Ψ2 : list W),\n  pr ps (U, V) -> ca = Φ1 ++ U ++ Φ2 -> cs = Ψ1 ++ V ++ Ψ2 ->\n  mps = map (seqext Φ1 Φ2 Ψ1 Ψ2) ps -> seqrule pr mps (ca, cs).\nProof. intros.  subst. apply Sctxt_e. exact X. Qed.  \n\nLemma seqrule_id (W : Type) (pr : rlsT (rel (list W))) :\n  forall ps c, pr ps c -> seqrule pr ps c.\nProof. intros. destruct c as [ca cs].\napply (Sctxt_eq pr ps ca cs [] [] [] []). assumption.\nsimpl. rewrite app_nil_r.  reflexivity.\nsimpl. rewrite app_nil_r.  reflexivity.\nclear X. induction ps.  simpl.  reflexivity.\nsimpl. rewrite <- IHps.\ndestruct a. unfold seqext. simpl.  rewrite !app_nil_r.\nreflexivity. Qed.\n\nLemma seqrule_seqrule (W : Type) (pr : rlsT (rel (list W))) :\n  rsub (seqrule (seqrule pr)) (seqrule pr).\nProof. unfold rsub. intros. inversion X. subst. clear X. \ninversion X0.  subst. clear X0.\nrewrite seqext_seqext.\ndestruct c0 as [ca cs].\neapply Sctxt_eq. exact X. \nreflexivity.  reflexivity.\nclear X. induction ps0.  simpl.  reflexivity.\nsimpl. rewrite IHps0.  rewrite seqext_seqext. reflexivity. Qed.\n\nDefinition seqrule_seqrule' (W : Type) pr :=\n  rsubD (@seqrule_seqrule W pr).\n \nLemma derl_seqrule'' (W : Type) (rules : rlsT (rel (list W))) :\n  forall Φ1 Φ2 Ψ1 Ψ2, (forall ps c, derl rules ps c -> \n   derl (seqrule rules) (map (seqext Φ1 Φ2 Ψ1 Ψ2) ps) (seqext Φ1 Φ2 Ψ1 Ψ2 c)) * \n  (forall ps cs, dersl rules ps cs -> \n    dersl (seqrule rules) (map (seqext Φ1 Φ2 Ψ1 Ψ2) ps) \n    (map (seqext Φ1 Φ2 Ψ1 Ψ2)cs)).\nProof. intros Φ1 Φ2 Ψ1 Ψ2.\neapply (derl_dersl_rect_mut (rules := rules)\n  (fun ps c => fun _ => derl (seqrule rules)\n    (map (seqext Φ1 Φ2 Ψ1 Ψ2) ps) (seqext Φ1 Φ2 Ψ1 Ψ2 c))\n  (fun ps cs : list _ => fun _ => dersl (seqrule rules)\n    (map (seqext Φ1 Φ2 Ψ1 Ψ2) ps) (map (seqext Φ1 Φ2 Ψ1 Ψ2) cs))).\n- simpl. intros. apply asmI.\n- intros. eapply dtderI.  apply Sctxt. eassumption.  assumption. \n- simpl. apply dtNil.\n- intros. rewrite map_app. simpl. apply dtCons ; assumption. Qed.\n \nDefinition derl_seqrule' W rules Φ1 Φ2 Ψ1 Ψ2 := \n  fst (@derl_seqrule'' W rules Φ1 Φ2 Ψ1 Ψ2).\nDefinition dersl_seqrule' W rules Φ1 Φ2 Ψ1 Ψ2 := \n  snd (@derl_seqrule'' W rules Φ1 Φ2 Ψ1 Ψ2).\n \nLemma derl_seqrule (W : Type) (rules : rlsT (rel (list W))) :\n  rsub (seqrule (derl rules)) (derl (seqrule rules)).\nProof.  unfold rsub.  intros.  destruct X.  \napply derl_seqrule'. assumption. Qed.\n\nLemma seqrule_derl_seqrule (W : Type) (rules : rlsT (rel (list W))) :\n  rsub (seqrule (derl (seqrule rules))) (derl (seqrule rules)).\nProof.  eapply rsub_trans. apply derl_seqrule.\n unfold rsub.  intros.  eapply derl_mono. 2: eassumption.\n apply seqrule_seqrule. Qed.\n\nDefinition seqrule_derl_seqrule' W rules :=\n  rsubD (@seqrule_derl_seqrule W rules).\n\n(* seqrule_s ps c qs d means that d is a sequent extension of c \n  and that each q in qs is a corresponding sequent extension of the\n  corresponding p in ps *)\nInductive seqrule_s (W : Type) (ps : list (rel (list W))) (c : rel (list W)) : \n    rlsT (rel (list W)) := \n  | Sctxt_s : forall Φ1 Φ2 Ψ1 Ψ2, \n    seqrule_s ps c (map (seqext Φ1 Φ2 Ψ1 Ψ2) ps) (seqext Φ1 Φ2 Ψ1 Ψ2 c).\n\nInductive seqrule' (W : Type) (pr : rlsT (rel (list W))) : \n    rlsT (rel (list W)) := \n  | Sctxt' : forall ps c pse ce,\n    pr ps c -> seqrule_s ps c pse ce -> seqrule' pr pse ce.\n\nCheck (Sctxt' _ _ (Sctxt_s _ _ _ _ _ _)). \n\n(* Check, get same as Sctxt but for seqrule' *)\nLemma Sctxt_alt : forall (W : Type) (pr : rlsT (rel (list W))) ps c Φ1 Φ2 Ψ1 Ψ2,\n    pr ps c -> seqrule' pr (map (seqext Φ1 Φ2 Ψ1 Ψ2) ps) (seqext Φ1 Φ2 Ψ1 Ψ2 c).\nProof.\n  intros until 0. intros H.\n  eapply Sctxt'. exact H. apply Sctxt_s.\nQed.\n\nLemma Sctxt_e': forall (W : Type) (pr : rlsT (rel (list W))) ps U V Φ1 Φ2 Ψ1 Ψ2,\n  pr ps (U, V) ->\n  seqrule pr (map (seqext Φ1 Φ2 Ψ1 Ψ2) ps) ((Φ1 ++ U) ++ Φ2, Ψ1 ++ V ++ Ψ2).\nProof.\n  intros until 0. intros H.\n  rewrite <- app_assoc. apply Sctxt_e. exact H.\nQed.  \n\nLemma seqext_defp : forall (W : Type) Φ1 Φ2 Ψ1 Ψ2 seq,\n      @seqext W Φ1 Φ2 Ψ1 Ψ2 seq =\n        let (U, V) := seq in (Φ1 ++ U ++ Φ2, Ψ1 ++ V ++ Ψ2).\nProof. reflexivity. Qed.\n\nLemma seqrule_same: forall (W : Type) pr ps (c c' : rel (list W)),\n  seqrule pr ps c -> c = c' -> seqrule pr ps c'.\nProof. intros. subst. assumption. Qed.  \n\nLemma seqrule_mono X (rulesa rulesb : rlsT (rel (list X))) :\n  rsub rulesa rulesb -> rsub (seqrule rulesa) (seqrule rulesb).\nProof. unfold rsub. intros. destruct X1. apply Sctxt. firstorder. Qed.\n\nDefinition seqrule_mono' X rulesa rulesb rs :=\n  rsubD (@seqrule_mono X rulesa rulesb rs).\n\nLemma Sctxt_nil: forall (W : Type) pr c Γ1 Γ2 Δ1 Δ2, (pr [] c : Type) ->\n  @seqrule W pr [] (seqext Γ1 Γ2 Δ1 Δ2 c).\nProof.\n  intros until 0.  intros H. eapply Sctxt in H.\n  simpl in H. exact H.\nQed.\n\nLemma InT_seqextL : forall {W : Type} Γ Δ A,\n    InT A Γ ->\n    existsT2 Φ1 Φ2, @seqext W Φ1 Φ2 Δ [] ([A], []) = (Γ, Δ).\nProof.\n  induction Γ; intros Δ A Hin.\n  inversion Hin.\n  inversion Hin. subst.\n  repeat eexists. unfold seqext.\n  do 2 rewrite app_nil_r. erewrite app_nil_l.\n     reflexivity.\n  subst. destruct (IHΓ  Δ _ X) as [H1 [H2 H3]].\n  unfold seqext in *.\n  inversion H3.\n  repeat rewrite app_nil_r.\n  repeat eexists. rewrite app_comm_cons. reflexivity.\nQed.\n\nLemma InT_seqextR : forall {W : Type} Γ Δ B,\n    InT B Δ ->\n    existsT2 Ψ1 Ψ2, @seqext W Γ [] Ψ1 Ψ2 ([], [B]) = (Γ, Δ).\nProof.\n  induction Δ; intros A Hin.\n  inversion Hin.\n  inversion Hin. subst.\n  repeat eexists. unfold seqext.\n  do 2 rewrite app_nil_r. erewrite app_nil_l.\n     reflexivity.\n  subst. destruct (IHΔ _ X) as [H1 [H2 H3]].\n  unfold seqext in *.\n  inversion H3.\n  repeat rewrite app_nil_r.\n  repeat eexists. rewrite app_comm_cons. reflexivity.\nQed.\n\nLemma InT_seqext : forall {W : Type} Γ Δ A B,\n    InT A Γ ->\n    InT B Δ ->\n    existsT2 Φ1 Φ2 Ψ1 Ψ2, @seqext W Φ1 Φ2 Ψ1 Ψ2 ([A], [B]) = (Γ, Δ).\nProof.\n  intros until 0. intros Hin1 Hin2.\n  destruct (@InT_seqextL _ _ Δ _ Hin1) as [H1 [H2 H3]].\n  destruct (@InT_seqextR _ Γ _ _ Hin2) as [J1 [J2 J3]].\n  unfold seqext in *.\n  repeat rewrite app_nil_r in H3.\n  repeat rewrite app_nil_r in J3.\n  inversion H3. inversion J3.\n  subst. repeat eexists.\nQed.\n\n(* fmlsext copied from ../ll/fmlsext.v *)\nDefinition fmlsext (W : Type) Γ1 Γ2 (fmls : (list W)) := (Γ1 ++ fmls ++ Γ2).\n\nLemma fmlsext_fmlsext: forall V (Γ1 Γ2 Φ1 Φ2 : list V) seq,\n  fmlsext Γ1 Γ2 (fmlsext Φ1 Φ2 seq) = fmlsext (Γ1 ++ Φ1) (Φ2 ++ Γ2) seq.\nProof. intros. unfold fmlsext.  rewrite !app_assoc. reflexivity. Qed.\n\nLemma map_fmlsext_fmlsext: forall V (Γ1 Γ2 Φ1 Φ2 : list V) seqs,\n  map (fmlsext Γ1 Γ2) (map (fmlsext Φ1 Φ2) seqs) =\n  map (fmlsext (Γ1 ++ Φ1) (Φ2 ++ Γ2)) seqs.\nProof. induction seqs. tauto.\nsimpl. rewrite IHseqs. rewrite fmlsext_fmlsext. reflexivity. Qed.\n\nLemma fmlsext_def : forall (W : Type) Φ1 Φ2 U,\n      @fmlsext W Φ1 Φ2 U = (Φ1 ++ U ++ Φ2).\nProof. reflexivity. Qed.\n\nDefinition apfst U V W (f : U -> V) (p : U * W) := let (x, y) := p in (f x, y).\nDefinition apsnd U V W (f : U -> V) (p : W * U) := let (x, y) := p in (x, f y).\n\n(** fst_ext_rls - adding left- and right-context \n  to the antecedent of a sequent rule *)\nInductive fst_ext_rls U W rls : rlsT (list U * W) :=\n  | fextI : forall Γ1 Γ2 ps c, \n    rlsmap (apfst (fmlsext Γ1 Γ2)) rls ps c -> fst_ext_rls rls ps c.\n\nInductive snd_ext_rls U W rls : rlsT (U * list W) :=\n  | sextI : forall Γ1 Γ2 ps c, \n    rlsmap (apsnd (fmlsext Γ1 Γ2)) rls ps c -> snd_ext_rls rls ps c.\n\nDefinition fextI' U W rls Γ1 Γ2 ps c rpc :=\n  @fextI U W rls Γ1 Γ2 _ _ (rmI _ _ ps c rpc).\n\nLemma fextI_eq' U W rls Γ1 Γ2 ps (c : list U * W) mps mc :\n  rls ps c -> mps = map (apfst (fmlsext Γ1 Γ2)) ps ->\n  mc = apfst (fmlsext Γ1 Γ2) c -> fst_ext_rls rls mps mc.\nProof. intros. subst. apply fextI'. exact X. Qed.\n\nDefinition fextI_eqc' U W rls Γ1 Γ2 ps (c : list U * W) mc rpc :=\n  @fextI_eq' U W rls Γ1 Γ2 ps (c : list U * W) _ mc rpc eq_refl.\n\nLemma fst_snd_ext W (rls : rlsT (list W * list W)) :\n  req (seqrule rls) (fst_ext_rls (snd_ext_rls rls)).\nProof. split ; intros ps c.\n- intro sr. destruct sr. eapply fextI. eapply rmI_eq.\neapply sextI. apply rmI. exact r.\n2: destruct c.  2: simpl.  2: unfold fmlsext.  2: reflexivity.\nclear r. induction ps. reflexivity.\ndestruct a. simpl.  rewrite - IHps. unfold fmlsext. reflexivity.\n- intro fs. destruct fs. inversion r. clear r. subst.\ndestruct X. inversion r. clear r. subst.\ndestruct c0. simpl. unfold fmlsext.\neapply Sctxt_eq. exact X. reflexivity. reflexivity.\nclear X.  induction ps0. reflexivity.\ndestruct a. simpl.  rewrite IHps0. reflexivity. Qed.\n\nLemma snd_fst_ext W (rls : rlsT (list W * list W)) :\n  req (seqrule rls) (snd_ext_rls (fst_ext_rls rls)).\nProof. split ; intros ps c.\n- intro sr. destruct sr. eapply sextI. eapply rmI_eq.\neapply fextI. apply rmI. exact r.\n2: destruct c.  2: simpl.  2: unfold fmlsext.  2: reflexivity.\nclear r. induction ps. reflexivity.\ndestruct a. simpl.  rewrite - IHps. unfold fmlsext. reflexivity.\n- intro fs. destruct fs. inversion r. clear r. subst.\ndestruct X. inversion r. clear r. subst.\ndestruct c0. simpl. unfold fmlsext.\neapply Sctxt_eq. exact X. reflexivity. reflexivity.\nclear X.  induction ps0. reflexivity.\ndestruct a. simpl.  rewrite IHps0. reflexivity. Qed.\n\nLemma rm_mono U W (f : U -> W) rlsa rlsb : \n  rsub rlsa rlsb -> rsub (rlsmap f rlsa) (rlsmap f rlsb).\nProof. intros rab ps c ra.\ndestruct ra.   pose (rab _ _ r).\napply rmI. apply r0. Qed.\n\nLemma fer_mono U W (rlsa rlsb : rlsT (list U * W)) :\n  rsub rlsa rlsb -> rsub (fst_ext_rls rlsa) (fst_ext_rls rlsb).\nProof. intros rab ps c fea.\ndestruct fea.  destruct r.  pose (rab _ _ r).\neapply fextI. apply rmI. apply r0. Qed.\n  \nLemma ser_mono U W (rlsa rlsb : rlsT (U * list W)) :\n  rsub rlsa rlsb -> rsub (snd_ext_rls rlsa) (snd_ext_rls rlsb).\nProof. intros rab ps c sea.\ndestruct sea.  destruct r.  pose (rab _ _ r).\neapply sextI. apply rmI. apply r0. Qed.\n  \n(* derl_fst_ext_rls - similar for seqrule above *)\nLemma fst_ext_rls_fst_ext_rls (U W : Type) (pr : rlsT (list U * W)) :\n  rsub (fst_ext_rls (fst_ext_rls pr)) (fst_ext_rls pr).\nProof. unfold rsub. intros. inversion X. subst. clear X. \ninversion X0.  subst. clear X0. destruct X. destruct r.\ndestruct c. simpl.  rewrite fmlsext_fmlsext.\neapply fextI' in p.  simpl in p.\neapply arg1_cong_imp. 2: exact p.  clear p.\ninduction ps ; simpl. reflexivity.\nrewrite IHps.  destruct a. simpl. rewrite fmlsext_fmlsext. reflexivity. Qed.\n\nDefinition fst_ext_rls_fst_ext_rls' (U W : Type) pr :=\n  rsubD (@fst_ext_rls_fst_ext_rls U W pr).\n \nLemma derl_fst_ext_rls'' (U W : Type) (rules : rlsT (list U * W)) :\n  forall Φ1 Φ2, (forall ps c, derl rules ps c -> \n   derl (fst_ext_rls rules) \n     (map (apfst (fmlsext Φ1 Φ2)) ps) (apfst (fmlsext Φ1 Φ2) c)) * \n  (forall ps cs, dersl rules ps cs -> \n    dersl (fst_ext_rls rules) (map (apfst (fmlsext Φ1 Φ2)) ps) \n    (map (apfst (fmlsext Φ1 Φ2)) cs)).\nProof. intros Φ1 Φ2.\neapply (derl_dersl_rect_mut (rules := rules)\n  (fun ps c => fun _ => derl (fst_ext_rls rules)\n    (map (apfst (fmlsext Φ1 Φ2)) ps) (apfst (fmlsext Φ1 Φ2) c))\n  (fun ps cs : list _ => fun _ => dersl (fst_ext_rls rules)\n    (map (apfst (fmlsext Φ1 Φ2)) ps) (map (apfst (fmlsext Φ1 Φ2)) cs))).\n- simpl. intros. apply asmI.\n- intros. eapply dtderI. eapply fextI. apply rmI. eassumption.  assumption. \n- simpl. apply dtNil.\n- intros. rewrite map_app. simpl. apply dtCons ; assumption. Qed.\n \nDefinition derl_fst_ext_rls' U W rules Φ1 Φ2 := \n  fst (@derl_fst_ext_rls'' U W rules Φ1 Φ2).\nDefinition dersl_fst_ext_rls' U W rules Φ1 Φ2 := \n  snd (@derl_fst_ext_rls'' U W rules Φ1 Φ2).\n \nLemma derl_fst_ext_rls (U W : Type) (rules : rlsT (list U * W)) :\n  rsub (fst_ext_rls (derl rules)) (derl (fst_ext_rls rules)).\nProof.  unfold rsub.  intros.  destruct X.  destruct r.\napply derl_fst_ext_rls'. assumption. Qed.\n\nLemma fst_ext_rls_derl_fst_ext_rls (U W : Type) (rules : rlsT (list U * W)) :\n  rsub (fst_ext_rls (derl (fst_ext_rls rules))) (derl (fst_ext_rls rules)).\nProof.  eapply rsub_trans. apply derl_fst_ext_rls.\n unfold rsub.  intros.  eapply derl_mono. 2: eassumption.\n apply fst_ext_rls_fst_ext_rls. Qed.\n\nDefinition fst_ext_rls_derl_fst_ext_rls' U W rules :=\n  rsubD (@fst_ext_rls_derl_fst_ext_rls U W rules).\n\n(* simple version of weakening, new stuff added at beginning or end,\n  could do more complicated, but why bother, have exchange *)\nDefinition wkL_valid V W rules (cl : list V) cr :=\n  forall Γ1 Γ2, derrec rules (@emptyT _) (fmlsext Γ1 Γ2 cl, cr : W).\nDefinition wkL_valid' V W rules seq := @wkL_valid V W rules (fst seq) (snd seq).\n\nDefinition can_wkL V W rules seq :=\n  derrec rules emptyT seq -> @wkL_valid' V W rules seq.\n\nLemma can_wkL_req V W rlsa rlsb seq : req rlsa rlsb ->\n  @can_wkL V W rlsa seq -> can_wkL rlsb seq.\nProof. unfold can_wkL. unfold wkL_valid'. unfold wkL_valid.\nintros rab da derb *.\nspecialize (da (derrec_rmono (snd rab) derb)).\nexact (derrec_rmono (fst rab) (da Γ1 Γ2)). Qed.\n\nLemma weakeningL: forall V W seq rules, @can_wkL V W (fst_ext_rls rules) seq.\nProof. unfold can_wkL. intros.\neapply derrec_all_rect in X. exact X.\nintros. contradiction H.\nintros ps concl ljpc dsps fwk.  destruct ljpc.  inversion r.\ndestruct c0. unfold wkL_valid'. unfold wkL_valid. simpl. subst. clear r.\nintros *.  rewrite fmlsext_fmlsext.\neapply derI. eapply fextI. eapply rmI_eq. apply X0.\nreflexivity.  reflexivity.\napply dersrecI_forall. intros c0 incm.\napply InT_mapE in incm. cD.\neapply ForallTD_forall in fwk.\n2: apply InT_map.  2: exact incm1.\nsimpl in incm0. destruct incm0. simpl in fwk.\nunfold wkL_valid' in fwk.  unfold wkL_valid in fwk.  simpl in fwk.\nrewrite - fmlsext_fmlsext. apply fwk.  Qed.\n\nPrint Implicit weakeningL.\n\n(** exchange **)\n(* properties can exchange adjacent sublists, and resulting sequent\n  is derivable (not conditional on unexchanged version being derivable *)\nDefinition can_exchL W Y rules seq :=\n  forall (Γ Γs : list W) (Δ : Y), seq = pair Γ Δ -> swapped Γ Γs ->\n  derrec rules (@emptyT _) (pair Γs Δ).\n\nDefinition can_exchR W Y rules seq :=\n  forall (Γ : Y) (Δ Δs : list W), seq = pair Γ Δ -> swapped Δ Δs ->\n  derrec rules (@emptyT _) (pair Γ Δs).\n\nInductive sing_empty X : list X -> Type :=\n  | se_empty : sing_empty []\n  | se_single : forall a, sing_empty [a].\n\nLemma sing_empty_app X (xs ys : list X):\n  sing_empty (xs ++ ys) -> sum (xs = []) (ys = []).\nProof. intro. inversion X0. destruct xs. tauto.\nsimpl in H0. discriminate H0.\ndestruct xs. tauto.\ninjection H0 as. destruct xs. simpl in H0. subst. tauto.\nsimpl in H0. discriminate H0.  Qed.\n\nLemma sing_empty_app_cons X z (xs ys : list X):\n  sing_empty (xs ++ z :: ys) -> (xs = []) * (ys = []).\nProof. intro se. inversion se.\nlist_eq_ncT. inversion H0.  list_eq_ncT. sD. inversion H1. tauto.\nlist_eq_ncT. Qed.\n\nInductive fst_rel (A B : Type) (R : relationT A) : relationT (A * B) :=\n  fst_relI : forall x y z, R x y -> @fst_rel A B R (x, z : B) (y, z).\n\nInductive snd_rel (A B : Type) (R : relationT A) : relationT (B * A) :=\n  snd_relI : forall x y z, R x y -> @snd_rel A B R (z : B, x) (z, y).\n\nLemma fext_e: forall (U W : Type) (pr : rlsT (list U * W)) ps cl cr Φ1 Φ2,\n  pr ps (cl, cr) ->\n  fst_ext_rls pr (map (apfst (fmlsext Φ1 Φ2)) ps) (Φ1 ++ cl ++ Φ2, cr).\nProof.  intros * H. rewrite <- fmlsext_def.\n  eapply fextI. eapply rmI_eq. exact H. reflexivity.  reflexivity.  Qed.\n\nLemma sext_e: forall (U W : Type) (pr : rlsT (U * list W)) ps cl cr Φ1 Φ2,\n  pr ps (cl, cr) ->\n  snd_ext_rls pr (map (apsnd (fmlsext Φ1 Φ2)) ps) (cl, Φ1 ++ cr ++ Φ2).\nProof.  intros * H. rewrite <- fmlsext_def.\n  eapply sextI. eapply rmI_eq. exact H. reflexivity.  reflexivity.  Qed.\n\nLtac concl_in_app X0 r sea :=\n  pose X0 as r ; apply sea in r ;\n  destruct r ; subst ; rewrite ?app_nil_r ; rewrite ?app_nil_l ;\n  simpl in X0 ; rewrite ?app_nil_r in X0.\n\nLtac fwl_tac mid := eexists ; split ;\n  [> assoc_mid mid ; apply fext_e ; eassumption |\n    apply ForallTI_forall ; intros x inms ; apply InT_mapE in inms ;\n    destruct inms as [x0 p] ; destruct p as [sex int] ;\n    destruct x0 ; simpl in sex ; unfold fmlsext in sex ; destruct sex ;\n    eexists ; split ;\n      [> eapply InT_map ; eassumption |\n      simpl ; unfold fmlsext ; apply fst_relI ; swap_tac ]].\n\nLtac fwr_tac mid := eexists ; split ;\n  [> assoc_mid mid ; apply sext_e ; eassumption |\n    apply ForallTI_forall ; intros x inms ; apply InT_mapE in inms ;\n    destruct inms as [x0 p] ; destruct p as [sex int] ;\n    destruct x0 ; simpl in sex ; unfold fmlsext in sex ; destruct sex ;\n    eexists ; split ;\n      [> eapply InT_map ; eassumption |\n      simpl ; unfold fmlsext ; apply snd_relI ; swap_tac ]].\n\nLemma exchL_std_rule: forall U W (rules : rlsT (list U * W)),\n  (forall ps U S, rules ps (U, S) -> sing_empty U) ->\n  forall ps c, fst_ext_rls rules ps c ->\n    can_trf_rules (fst_rel (@swapped _)) (fst_ext_rls rules) ps c.\nProof. unfold can_trf_rules.\nintros U W rules se ps c sqr c' fr.  \npose (fun ps xs ys S rps => \n  sing_empty_app xs ys (se ps (xs ++ ys) S rps)) as sea.\ninversion fr. subst. clear fr.\ninversion sqr. clear sqr. subst.\ninversion X0. destruct c as [pl pr].\nsimpl in H1. unfold fmlsext in H1.\ninversion H1. subst. clear H1. clear X0.\ninversion X. subst.\nacacD'T2 ; subst.\n- concl_in_app X1 r sea.  + fwl_tac H3.  + fwl_tac H1.\n- concl_in_app X1 r sea.  concl_in_app X1 r sea.\n+ fwl_tac H5.  + fwl_tac C.\n+ list_eq_nc. destruct e. subst. rewrite ?app_nil_r. rewrite ?app_nil_l.\nsimpl in X1. rewrite ?app_nil_r in X1.\nfwl_tac H1.\n- fwl_tac pl.\n- concl_in_app X1 r sea.  + fwl_tac H5.  + fwl_tac H3.\n- fwl_tac pl.\n- fwl_tac pl.\n- concl_in_app X1 r sea.  + fwl_tac H1.  + fwl_tac H.\n- concl_in_app X1 r sea.  concl_in_app X1 r sea.\n+ fwl_tac H3.  + fwl_tac B.\n+ list_eq_ncT. destruct e. subst. rewrite ?app_nil_r. rewrite ?app_nil_l.\n  simpl in X1 ; rewrite ?app_nil_r in X1.\nfwl_tac H.\n- concl_in_app X1 r sea.  concl_in_app X1 r sea. concl_in_app X1 r sea.\n+ fwl_tac H5.  + fwl_tac C.\n+ list_eq_ncT. destruct e. subst. rewrite ?app_nil_r. rewrite ?app_nil_l.\n  simpl in X1 ; rewrite ?app_nil_r in X1.\nfwl_tac B.\n+ list_eq_nc. destruct e.  list_eq_nc. destruct H1. subst.\nrewrite ?app_nil_r. rewrite ?app_nil_l.\n  simpl in X1 ; rewrite ?app_nil_r in X1.\nfwl_tac H.\n- fwl_tac pl.\nQed.\n\nPrint Implicit exchL_std_rule.\n\nLemma exchR_std_rule: forall U W (rules : rlsT (U * list W)),\n  (forall ps U S, rules ps (U, S) -> sing_empty S) ->\n  forall ps c, snd_ext_rls rules ps c ->\n    can_trf_rules (snd_rel (@swapped _)) (snd_ext_rls rules) ps c.\nProof. unfold can_trf_rules.\nintros U W rules se ps c sqr c' fr.  \npose (fun ps xs ys U rps => \n  sing_empty_app xs ys (se ps U (xs ++ ys) rps)) as sea.\ninversion fr. subst. clear fr.\ninversion sqr. clear sqr. subst.\ninversion X0. destruct c as [pl pr].\nsimpl in H1. unfold fmlsext in H1.\ninversion H1. subst. clear H1. clear X0.\ninversion X. subst.\nacacD'T2 ; subst.\n- concl_in_app X1 r sea.  + fwr_tac H3.  + fwr_tac H1.\n- concl_in_app X1 r sea.  concl_in_app X1 r sea.\n+ fwr_tac H5.  + fwr_tac C.\n+ list_eq_nc. destruct e. subst. rewrite ?app_nil_r. rewrite ?app_nil_l.\nsimpl in X1. rewrite ?app_nil_r in X1.\nfwr_tac H1.\n- fwr_tac pr.\n- concl_in_app X1 r sea.  + fwr_tac H5.  + fwr_tac H3.\n- fwr_tac pr.\n- fwr_tac pr.\n- concl_in_app X1 r sea.  + fwr_tac H1.  + fwr_tac H.\n- concl_in_app X1 r sea.  concl_in_app X1 r sea.\n+ fwr_tac H3.  + fwr_tac B.\n+ list_eq_ncT. destruct e. subst. rewrite ?app_nil_r. rewrite ?app_nil_l.\n  simpl in X1 ; rewrite ?app_nil_r in X1.\nfwr_tac H.\n- concl_in_app X1 r sea.  concl_in_app X1 r sea. concl_in_app X1 r sea.\n+ fwr_tac H5.  + fwr_tac C.\n+ list_eq_ncT. destruct e. subst. rewrite ?app_nil_r. rewrite ?app_nil_l.\n  simpl in X1 ; rewrite ?app_nil_r in X1.\nfwr_tac B.\n+ list_eq_nc. destruct e.  list_eq_nc. destruct H1. subst.\nrewrite ?app_nil_r. rewrite ?app_nil_l.\n  simpl in X1 ; rewrite ?app_nil_r in X1.\nfwr_tac H.\n- fwr_tac pr.\nQed.\n\nPrint Implicit exchR_std_rule.\n\nDefinition rev_pair {U W} (p : U * W) := let (x, y) := p in (y, x).\n\nLemma sext_rev_fext U W (rules : rlsT (U * list W)) ps c :\n  snd_ext_rls rules ps c ->\n  fst_ext_rls (rlsmap rev_pair rules) (map rev_pair ps) (rev_pair c).\nProof. intro ser. destruct ser.  inversion r. destruct c0.\nclear r. subst. simpl.\neapply fextI.  eapply rmI_eq. apply rmI. exact X.\n2: reflexivity.\nclear X.  induction ps0. reflexivity.\nsimpl. rewrite IHps0.  destruct a. reflexivity. Qed.\n\nPrint Implicit sext_rev_fext.\n\n\n(*\nthis is not going to be worthwhile without a bunch more lemmas \nsuch as sext_rev_fext above, and more\n\nLemma exchR_std_rule: forall U W (rules : rlsT (U * list W)),\n  (forall ps U S, rules ps (U, S) -> sing_empty S) ->\n  forall ps c, snd_ext_rls rules ps c ->\n    can_trf_rules (snd_rel (@swapped _)) (snd_ext_rls rules) ps c.\nProof. intros * se * ser.\npose (rlsmap rev_pair rules) as rrules.\npose (@exchL_std_rule _ _ rrules).\nrequire c0.\n{ intros * rr.  inversion rr. destruct c1. simpl in H1. inversion H1. subst.\neapply se. subst rrules. exact X. }\nspecialize (c0 (map rev_pair ps) (rev_pair c)).\nrequire c0.  { subst rrules. exact (sext_rev_fext ser). }\n\ndestruct ser.\neapply fextI. inversion r.\n\n*)\n\n(* we may also want to refer to rules individually *)\nInductive Idrule (W : Type) : rlsT (rel (list W)) :=\n  | Idrule_I : forall A, Idrule [] (pair [A] [A]).\n\nLemma sr_Id_alt X (A : X) ant suc: InT A ant -> InT A suc ->\n  seqrule (@Idrule X) [] (ant, suc).\nProof. intros. apply InT_split in X1.\napply InT_split in X0. cD. subst. \neapply Sctxt_eq. apply (Idrule_I A).\nsimpl. reflexivity.  simpl. reflexivity.  simpl. reflexivity. Qed.\n\n", "meta": {"author": "ianshil", "repo": "CE_GLS", "sha": "3dd86195e5dfb3e9c8e1db450512840ab407b688", "save_path": "github-repos/coq/ianshil-CE_GLS", "path": "github-repos/coq/ianshil-CE_GLS/CE_GLS-3dd86195e5dfb3e9c8e1db450512840ab407b688/general/gen_seq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24186162614190215}}
{"text": "(** * Functors involving coproduct categories *)\nRequire Import Category.Sum Functor.Core Functor.Composition.Core Functor.Identity.\nRequire Import Functor.Paths HoTT.Tactics Types.Forall.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\n(** We save [inl] and [inr] so we can use them to refer to the functors, too.  Outside of the [Categories/] directory, they should always be referred to as [Functor.inl] and [Functor.inr], after a [Require Functor].  Outside of this file, but in the [Categories/] directory, if you do not want to depend on all of [Functor] (for e.g., speed reasons), they should be referred to as [Functor.Sum.inl] and [Functor.Sum.inr] after a [Require Functor.Sum]. *)\nLocal Notation type_inl := inl.\nLocal Notation type_inr := inr.\n\n(** ** Injections [inl : C → C + D] and [inr : D → C + D] *)\nSection sum_functors.\n  Variables C D : PreCategory.\n\n  Definition inl : Functor C (C + D)\n    := Build_Functor C (C + D)\n                     (@inl _ _)\n                     (fun _ _ m => m)\n                     (fun _ _ _ _ _ => idpath)\n                     (fun _ => idpath).\n\n  Definition inr : Functor D (C + D)\n    := Build_Functor D (C + D)\n                     (@inr _ _)\n                     (fun _ _ m => m)\n                     (fun _ _ _ _ _ => idpath)\n                     (fun _ => idpath).\nEnd sum_functors.\n\n(** ** Coproduct of functors [F + F' : C + C' → D] *)\nSection sum.\n  Variables C C' D : PreCategory.\n\n  Definition sum (F : Functor C D) (F' : Functor C' D)\n  : Functor (C + C') D.\n  Proof.\n    refine (Build_Functor\n              (C + C') D\n              (fun cc'\n               => match cc' with\n                    | type_inl c => F c\n                    | type_inr c' => F' c'\n                  end)\n              (fun s d\n               => match s, d with\n                    | type_inl cs, type_inl cd\n                      => fun m : morphism _ cs cd => F _1 m\n                    | type_inr c's, type_inr c'd\n                      => fun m : morphism _ c's c'd => F' _1 m\n                    | _, _ => fun m => match m with end\n                  end%morphism)\n              _\n              _);\n    abstract (\n        repeat (intros [] || intro);\n        simpl in *;\n          auto with functor\n      ).\n  Defined.\nEnd sum.\n\n(** ** swap : [C + D → D + C] *)\nSection swap_functor.\n  Definition swap C D\n  : Functor (C + D) (D + C)\n    := sum (inr _ _) (inl _ _).\n\n  Local Open Scope functor_scope.\n\n  Definition swap_involutive_helper {C D} c\n  : (swap C D) ((swap D C) c)\n    = c\n    := match c with type_inl _ => idpath | type_inr _ => idpath end.\n\n  Lemma swap_involutive `{Funext} C D\n  : swap C D o swap D C = 1.\n  Proof.\n    path_functor.\n    exists (path_forall _ _ swap_involutive_helper).\n    repeat (apply (@path_forall _); intro).\n    repeat match goal with\n               | [ |- context[transport (fun x' => forall y, @?C x' y) ?p ?f ?x] ]\n                 => simpl rewrite (@transport_forall_constant _ _ C _ _ p f x)\n           end.\n    transport_path_forall_hammer.\n      by repeat match goal with\n                  | [ H : Empty |- _ ] => destruct H\n                  | [ H : (_ + _)%type |- _ ] => destruct H\n                  | _ => progress hnf in *\n                end.\n  Qed.\nEnd swap_functor.\n\nModule Export FunctorSumNotations.\n  Notation \"F + G\" := (sum F G) : functor_scope.\nEnd FunctorSumNotations.\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Categories/Functor/Sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.2418616261419021}}
{"text": "(**********************************************************************************\n * The PEDANTIC (Proof Engine for Deductive Automation using Non-deterministic\n * Traversal of Instruction Code) verification framework\n *\n * Developed by Kenneth Roe\n * For more information, check out www.cs.jhu.edu/~roe\n *\n * SatSolverAux1.v\n * This file contains the proof of correctness of a tree traversal algorithm using\n * the PEDANTIC verification framework.\n *\n **********************************************************************************)\n\nRequire Import Omega.\nRequire Export SfLib.\nRequire Export SfLibExtras.\nRequire Export ImpHeap.\nRequire Export AbsState.\nRequire Export AbsExecute.\nRequire Export AbsStateInstance.\nRequire Export Simplify.\nRequire Export Eqdep.\nRequire Export StateImplication.\nRequire Export Classical.\nRequire Export Unfold.\nRequire Export Fold.\nRequire Export merge.\nRequire Export ProgramTactics.\nRequire Export SatSolverDefs.\nRequire Export UpdateHelper.\nRequire Export ClosureHelper.\nRequire Export MagicWandExistsHelper.\nRequire Export StateHypHelper.\nOpaque haveVarInvariant.\n\nSet Printing Depth 200.\n\nTheorem precond1Core :\n    (exists st, realizeState\n        ([!!(backtrack)] **\n         AbsClosure (invariant ** ([#0 <<<< v(2)] *\\/* [v(5) ==== #0]))\n           (!!(clauses)\n            :: !!(assignments_to_do_head)\n               :: !!(stack) :: !!(assignments) :: !!(watches) :: nil)) nil\n        st) ->\n    (exists st, realizeState (AbsMagicWand\n        ([!!(backtrack)] **\n         AbsClosure (invariant ** ([#0 <<<< v(2)] *\\/* [v(5) ==== #0]))\n           (!!(clauses)\n            :: !!(assignments_to_do_head)\n               :: !!(stack) :: !!(assignments) :: !!(watches) :: nil))\n        (AbsExistsT\n           (AbsExistsT\n              (AbsExistsT\n                 (AbsExistsT\n                    (!!(stack) ++++ #3 |-> v(3) **\n                     !!(stack) ++++ #2 |-> v(2) **\n                     !!(stack) ++++ #1 |-> v(1) ** !!(stack) |-> v(0)))))))\n     nil st).\nProof.\n    (*intros. destruct H.\n    eapply ex_intro.\n    eapply breakTopClosureThm1. unfold invariant. unfold invariantCore.\n    unfold invariantCoreNoTail. compute. reflexivity.\n    eapply breakTopClosureThm2 in H. Focus 2. unfold invariant. unfold invariantCore.\n    unfold invariantCoreNoTail. compute. reflexivity.\n    eapply breakTopClosureThm1. compute. reflexivity.\n    simplify. propagateExists. propagateExists. propagateExists. propagateExists.\n    propagateExists.\n    eapply unfold_rs1.\n    unfoldHeap (@AbsVar unit eq_unit (@basicEval unit) stack).\n    eapply breakTopClosureThm2 in H. Focus 2. compute. reflexivity.\n    simplifyHyp H. propagateExistsHyp H. propagateExistsHyp H. propagateExistsHyp H.\n    propagateExistsHyp H. propagateExistsHyp H. eapply unfold_rs2 in H. Focus 2.\n    unfoldHeap (@AbsVar unit eq_unit (@basicEval unit) stack).\n    simplify. simplifyHyp H. simplify. simplifyHyp H.\n \n\n    eapply magicWandStateExists. simpl. reflexivity. eapply ex_intro.\n    apply H. simpl. reflexivity. simpl. reflexivity.\n    simpl. reflexivity.\n    eapply propagateInExistsSimp. compute. reflexivity.\n    eapply propagateInExistsSimp. compute. reflexivity.\n    eapply propagateInExistsSimp. compute. reflexivity.\n    eapply propagateInExistsSimp. compute. reflexivity.\n    eapply propagateInExistsSimp. compute. reflexivity.\n    eapply propagateInExistsSimp. compute. reflexivity.\n    eapply propagateInExistsId. reflexivity.\n    compute. reflexivity.\n\n    Grab Existential Variables. apply x.*)\n    admit.\nAdmitted.\n\nTheorem preCond1 : forall x0,\n    realizeState\n         (AbsUpdateWithLoc\n            (AbsUpdateWithLoc\n               (AbsUpdateWithLoc\n                  (AbsUpdateVar\n                     ([!! (backtrack)] **\n                      AbsUpdateVar ([# 1] ** loopInvariant) have_var # 0)\n                     backtrack # 0) varx !! (stack) ++++ # stack_var_offset)\n               valuex !! (stack) ++++ # stack_val_offset) \n            ssss !! (stack) ++++ # next_offset) nil x0 ->\n    exists s : state,\n    realizeState\n      (AbsMagicWand\n         (AbsUpdateWithLoc\n            (AbsUpdateWithLoc\n               (AbsUpdateWithLoc\n                  (AbsUpdateVar\n                     ([!! (backtrack)] **\n                      AbsUpdateVar ([# 1] ** loopInvariant) have_var # 0)\n                     backtrack # 0) varx !! (stack) ++++ # stack_var_offset)\n               valuex !! (stack) ++++ # stack_val_offset) \n            ssss !! (stack) ++++ # next_offset)\n         (AbsExistsT\n            (AbsExistsT\n               (AbsExistsT\n                  (AbsExistsT\n                     (AbsExistsT\n                        (v( 0) ++++ # 3 |-> v( 4) **\n                         v( 0) ++++ # 2 |-> v( 3) **\n                         v( 0) ++++ # 1 |-> v( 2) **\n                         v( 0) ++++ # 0 |-> v( 1) ** [!! (stack) ==== v( 0)])))))))\n      nil s.\nProof.\n    (*intros.\n    decomposeUpdates.\n    simplifyTheHyp H.\n    decomposeUpdates.\n\n    eapply simplifyExists. compute. reflexivity.\n    eapply simplifyExists. compute. reflexivity.\n    eapply simplifyExists. compute. reflexivity.\n    eapply simplifyExists. compute. reflexivity.\n    eapply simplifyExists. compute. reflexivity.\n\n    eapply existsWithLoc.\n    eapply existsWithLoc.\n    eapply existsWithLoc.\n    eapply existsVar.\n    eapply existsVar.\n    eapply precond1Core.\n    eapply ex_intro.\n    apply H.\n\n\nGrab Existential Variables.\n    apply x4. apply 0. apply x4. apply 0.*)\n    admit.\nAdmitted.\n\nOpaque numericRange.\nOpaque rangeSet.\nOpaque Rmember.\nOpaque In.\nOpaque nth.\n\nTheorem dumb1: forall x, x + 2 = S (S x).\nProof.\n    admit.\nAdmitted.\n\nTheorem dumb2: forall x, x + 2 + 1 = x + 3.\nProof.\n    admit.\nAdmitted.\n\nTheorem dumb3 : forall x n, S x <= n -> x < n. Proof. admit. Admitted.\n\n\nTheorem preCond2: forall (s : state) (n : nat) (b : id -> nat), realizeState\n        (AbsUpdateVar\n           (AbsUpdateVar\n              (AbsMagicWand\n                 (AbsUpdateWithLoc\n                    (AbsUpdateWithLoc\n                       (AbsUpdateWithLoc\n                          (AbsUpdateVar\n                             ([!! (backtrack)] **\n                              AbsUpdateVar ([# 1] ** loopInvariant) \n                                have_var # 0) backtrack \n                             # 0) varx !! (stack) ++++ # stack_var_offset)\n                       valuex !! (stack) ++++ # stack_val_offset) \n                    ssss !! (stack) ++++ # next_offset)\n                 (AbsExistsT\n                    (AbsExistsT\n                       (AbsExistsT\n                          (AbsExistsT\n                             (AbsExistsT\n                                (v( 0) ++++ # 3 |-> v( 4) **\n                                 v( 0) ++++ # 2 |-> v( 3) **\n                                 v( 0) ++++ # 1 |-> v( 2) **\n                                 v( 0) ++++ # 0 |-> v( 1) **\n                                 [!! (stack) ==== v( 0)]))))))) \n              stack !! (ssss)) have_var # 1) nil s ->\n       NatValue n =\n       basicEval AbsPlusId\n         (NatValue (env_p s assignments) :: @NatValue unit (env_p s varx) :: nil) -> heap_p s n <> None.\nProof.\n    (*intros. eapply breakTopClosureThm2 in H. Focus 2. unfold loopInvariant. unfold invariant.\n    unfold invariantCore. unfold invariantCoreNoTail. compute. reflexivity.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n    \n    eapply breakTopClosureThm2 in H. Focus 2. compute. reflexivity.\n    eapply propagateExistsEquiv1 in H. Focus 2. compute. reflexivity.\n    eapply propagateExistsEquiv1 in H. Focus 2. compute. reflexivity.\n    eapply propagateExistsEquiv1 in H. Focus 2. compute. reflexivity.\n    eapply propagateExistsEquiv1 in H. Focus 2. compute. reflexivity.\n    eapply propagateExistsEquiv1 in H. Focus 2. compute. reflexivity.\n\n    eapply unfold_rs2 in H. Focus 2.\n    unfoldHeap (@AbsVar unit eq_unit (@basicEval unit) stack).\n    Transparent nth.\n    simplifyTheHyp H.\n\n    eapply localizeExistsThm2 in H. Focus 2. compute. reflexivity.\n    eapply localizeExistsThm2 in H. Focus 2. compute. reflexivity.\n    eapply localizeExistsThm2 in H. Focus 2. compute. reflexivity.\n    eapply localizeExistsThm2 in H. Focus 2. compute. reflexivity.\n    eapply localizeExistsThm2 in H. Focus 2. compute. reflexivity.\n    eapply localizeExistsThm2 in H. Focus 2. compute. reflexivity.\n    eapply localizeExistsThm2 in H. Focus 2. compute. reflexivity.\n    eapply localizeExistsThm2 in H. Focus 2. compute. reflexivity.\n\n    eapply clearMagicWandUpdateWithLocThm in H. Focus 2. compute. reflexivity.\n    eapply removeMagicWandThm in H. Focus 2. compute. reflexivity.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n    simplifyTheHyp H.\n\n    eapply stateAssertionThm in H. compute in H.\n    crunch. \n\n    destruct x3. eapply dumb3 in H27. Transparent basicEval. simpl in H0.\n    inversion H0; subst; clear H0. rewrite <- glue1.\n    destruct x0. inversion H26. inversion H26; subst; clear H26.\n\n    assert (exists nv, (x14 (((let (x, _) := s in x) assignments)+((let (x, _) := s in x) varx)) = Some nv /\\ nth (((let (x, _) := s in x) varx)+1) l NoValue = NatValue nv)).\n\n        eapply heapMap. apply H0. inversion H13; subst; clear H13. apply H27.\n\n    inversion H3; subst; clear H3.\n\n    assert(exists x, heap_p s ((let (x3, _) := s in x3) assignments + (let (x3, _) := s in x3) varx)=Some x).\n        eapply ex_intro. eapply H2. eapply H4.\n\n    inversion H3; subst; clear H3.\n\n    rewrite H5. intro X. inversion X.\n\n    inversion H26. inversion H26.\n\n    inversion H27. inversion H27. inversion H27.\n\n    clear H.\n    compute. intros.\n    eapply stateAssertionThm in H. compute in H. crunch.\n\n    remember ((let (x4, _) := s0 in x4) stack). destruct n0. inversion H15.\n   \n    eapply ex_intro. simpl. reflexivity.*)\n    admit.\n\nAdmitted.\n\nOpaque basicEval.\n\n\n\n\n\nTransparent haveVarInvariant.\n\nTheorem mergeTheorem1 :\n\n mergeStates\n    (AbsUpdateVar\n       (AbsUpdateVar\n          ([!! (ssss) ==== # 0] **\n           AbsUpdateWithLoc\n             ([~~ # var_count <<<< !! (iiii)] ** haveVarInvariant) \n             ssss !! (assignments) ++++ !! (iiii)) \n          varx !! (iiii)) have_var # 1)\n    ([~~ !! (ssss) ==== # 0] **\n     AbsUpdateWithLoc ([~~ # var_count <<<< !! (iiii)] ** haveVarInvariant)\n       ssss !! (assignments) ++++ !! (iiii)) haveVarInvariant.\nProof.\n    (*eapply mergeReductionUpdateVarLeft.\n    eapply mergeReductionUpdateVarLeft2.\n    eapply removeCondLeftLeft.\n    eapply removeCondRightLeft.\n    eapply mergeReductionUpdateWithLocLeft.\n    eapply mergeReductionUpdateWithLocRight.\n    eapply removeCondLeftLeft.\n    eapply removeCondRightLeft.\n    eapply mergeSame.\n\n    unfold haveVarInvariant. unfold invariantCore. unfold haveVarComponent.\n    unfold invariantCoreNoTail. compute. reflexivity.\n\n    compute. reflexivity.\n\n    unfold haveVarInvariant. unfold invariantCore. unfold haveVarComponent.\n    unfold invariantCoreNoTail.\n    compute. reflexivity.\n\n    compute. reflexivity.\n\n    unfold haveVarInvariant. unfold invariantCore. \n    unfold invariantCoreNoTail. unfold haveVarComponent. intros.\n    eapply breakTopClosureThm2 in H.  Focus 2. compute. reflexivity.\n    eapply breakTopClosureThm2 in H.  Focus 2. compute. reflexivity.\n    eapply breakTopClosureThm1. compute. reflexivity.\n    eapply breakTopClosureThm1. compute. reflexivity.\n    eapply stripUpdateVarHyp in H. Focus 2. compute. reflexivity.\n        propagateExists. propagateExists. propagateExists. propagateExists.\n        propagateExists. propagateExists.\n        propagateExistsHyp H. propagateExistsHyp H. propagateExistsHyp H.\n        propagateExistsHyp H. propagateExistsHyp H. propagateExistsHyp H.\n        eapply stateImplication. apply H. compute. reflexivity. compute. reflexivity.\n        prove_implication. compute. reflexivity. compute. reflexivity. clear H.\n\n    intros.\n    destruct b0. compute in H. inversion H. destruct b0. compute in H. inversion H.\n    destruct b0. compute in H. inversion H. destruct b0. compute in H. inversion H.\n    destruct b0. compute in H. inversion H. destruct b0. compute in H. inversion H.\n    destruct b0. Focus 2. simpl in H.\n    inversion H. compute.\n    eapply stateAssertionThm in H0. simpl in H0. crunch.\n    eapply realizeStateSimplify. compute. reflexivity.\n    inversion H19; subst; clear H19. unfold override in H4. compute in H4.\n    eapply RSOrComposeL. eapply RSR. compute.\n    inversion H4; subst; clear H4. rewrite H5. Transparent basicEval. simpl.\n    reflexivity.\n    eapply BTStatePredicate. intro X. inversion X. compute. reflexivity.\n    Transparent nth. Opaque basicEval. simpl in H4. simpl in H3. unfold override in H2.\n    simpl in H2. rewrite H0 in H3.\n    eapply RSOrComposeR. eapply RSR. Transparent basicEval. Opaque nth. simpl.\n    Transparent nth. simpl. Opaque nth. Transparent basicEval. simpl in H4.\n    assert (match v2 with\n    | NatValue _ => NoValue\n    | ListValue l => nth (e varx + 1) l NoValue\n    | NoValue => NoValue\n    | OtherValue _ => NoValue\n    end=NatValue 0).\n    destruct v2. inversion H4. inversion H5.\n \n\n    erewrite H3. reflexivity. omega. reflexivity. reflexivity. rewrite H1. reflexivity.\n    inversion H4. inversion H5.\n    inversion H4. inversion H5.\n    rewrite H5. simpl. reflexivity.\n    eapply BTStatePredicate. intro X. inversion X.\n    simpl. reflexivity.\n\n    compute. reflexivity.\n\n    compute. reflexivity.*)\n    admit.\nAdmitted.\n\n\nTheorem noResult1 : forall x0 st st' f,\n        ceval f st\n        (CIf (!ssss === A0) (varx ::= !iiii; have_var ::= A1) (SKIP))\n        st' x0 -> x0 = NoResult.\nProof.\n    (*intros x0 st st' f H.\n    inversion H; subst; clear H. inversion H8; subst; clear H8.\n    inversion H6; subst; clear H6. reflexivity. inversion H5; subst; clear H5.\n    inversion H5; subst; clear H5. inversion H8; subst; clear H8. reflexivity.*)\n admit.\nAdmitted.\n\nTheorem entailment1 : forall s : state,\n   realizeState (AbsUpdateVar haveVarInvariant iiii !!(iiii) ++++ #1) nil s ->\n   realizeState haveVarInvariant nil s.\nProof.\n    (*intros.\n    eapply entailmentUnusedUpdated. apply H.\n    Transparent haveVarInvariant. unfold haveVarInvariant. unfold invariantCore.\n    unfold invariantCoreNoTail. unfold haveVarComponent. compute. reflexivity.*)\n    admit.\nAdmitted.\n\n\nTheorem entailment2 : forall x0 : state,\nforall x0 : state,\n  realizeState\n    (AbsUpdateVar\n       (AbsUpdateVar\n          ([~~ !! (backtrack)] **\n           AbsUpdateVar ([# 1] ** loopInvariant) have_var # 0) \n          valuex # 1) iiii # 0) nil x0 ->\n  realizeState haveVarInvariant nil x0.\nProof.\n    (*intros.\n    eapply stripUpdateVarHyp in H. Focus 2. compute. reflexivity.\n    eapply stripUpdateVarHyp in H. Focus 2. compute. reflexivity.\n    eapply stripUpdateVarHyp in H. Focus 2. compute. reflexivity.\n    propagateExistsHyp H. propagateExistsHyp H. propagateExistsHyp H.\n    propagateExistsHyp H. propagateExistsHyp H. propagateExistsHyp H.\n    propagateExistsHyp H. propagateExistsHyp H. propagateExistsHyp H.\n    eapply breakTopClosureThm2 in H.  Focus 2. compute. reflexivity.\n    eapply breakTopClosureThm2 in H.  Focus 2. compute. reflexivity.\n    Transparent haveVarInvariant. unfold haveVarInvariant.\n    unfold invariantCore. unfold haveVarComponent. unfold invariantCoreNoTail.\n    eapply breakTopClosureThm1. compute. reflexivity.\n    eapply breakTopClosureThm1. compute. reflexivity.\n\n    eapply stateImplication. apply H. compute. reflexivity. compute. reflexivity.\n    prove_implication. compute. reflexivity. compute. reflexivity. clear H.\n\n    intros. eapply stateAssertionThm in H0. simpl in H0. crunch.\n    eapply realizeStateSimplify. compute. reflexivity.\n\n    eapply RSOrComposeL.  eapply RSR. compute. Transparent basicEval. unfold basicEval.\n    rewrite H3. simpl. reflexivity.\n    eapply BTStatePredicate. omega. unfold empty_heap. simpl. reflexivity.*)\n    admit.\nAdmitted.\n\nOpaque basicEval.\n\nFixpoint findArray v (e : absState) :=\n    match e with\n    | AbsStar l r => match findArray v l with\n                     | Some (x,l') => Some (x,AbsStar l' r)\n                     | None => match findArray v r with\n                               | Some (x,r') => Some (x,AbsStar l r')\n                               | None => None\n                               end\n                     end\n    | AbsUpdateVar s vv r => match findArray v s with\n                             | Some (a,s') => if hasVarState a vv then None else Some (a,AbsUpdateVar s' vv r)\n                             | None => None\n                             end\n    | AbsUpdateWithLoc s vv r => match findArray v s with\n                                 | Some (a,s') => if hasVarState a vv then None else Some (a,AbsUpdateWithLoc s' vv r)\n                                 | None => None\n                                 end\n    | (ARRAY(l,#c,m)) => if beq_absExp l v then Some (ARRAY(l,#c,m),AbsEmpty) else None\n    | _ => None\n    end.\n\nFunction  stripUpdateLoc (s : absState) :=\n    match s with\n    | AbsUpdateLoc ss (i++++o) v => match findArray i ss with\n                                    | Some (ARRAY(a,b,v(c)),ss') => Some ([nth(v(c),o)====v] ** (AbsExistsT ((replaceStateVar (S c) (replacenth(v(S c),(addExpVar 1 o),v(0))) (addStateVar 1 ss') ** ARRAY(addExpVar 1 a,addExpVar 1 b,v(S(c)))))),ss,(o<<<<b))\n                                    | _ => match stripUpdateLoc ss with\n                                           | Some (ss,t,p) => Some (AbsUpdateLoc ss (i++++o) v,t,p)\n                                           | None => None\n                                           end\n                                    end\n    | AbsExistsT x => match stripUpdateLoc x with\n                      | Some (x,t,p) => Some (AbsExistsT x,t,p)\n                      | _ => None\n                      end\n    | AbsMagicWand l r => match stripUpdateLoc l with\n                          | Some (l,t,p) => Some (AbsMagicWand l r,t,p)\n                          | None => None\n                          end\n    | AbsStar l r => match stripUpdateLoc r return option (absState * absState  * absExp) with\n                     | Some (r,t,p) => Some (AbsStar l r,t,p)\n                     | None => match stripUpdateLoc l with\n                               | Some (l,t,p) => Some (AbsStar l r,t,p)\n                               | None => None\n                               end\n                     end\n    | x => None\n    end.\n\nTheorem removeUpdateLocLeft : forall l l' r m a b,\n    Some (l',a,b) = stripUpdateLoc l ->\n    (forall bind s, realizeState a bind s -> exists q, absEval (fst s) bind b = NatValue (S q)) ->\n    mergeStates l' r m ->\n    mergeStates l r m.\nProof.\n    admit.\nAdmitted.\n\n\n\nTheorem mergeTheorem2Index : forall bind s, realizeState\n        ((([!! (ssss) ==== nth( v( 7), # 0)] **\n           [!! (valuex) ==== v( 9)] **\n           [!! (varx) ==== v( 8)] **\n           ((((((TREE( !! (clauses), v( 0), # 21, # 0 :: nil) **\n                 TREE( !! (assignments_to_do_head), v( 1), # 4, # 0 :: nil) **\n                 TREE( nth( v( 7), # 0), v( 7), # 4, # 0 :: nil) **\n                 ARRAY( !! (assignments), # 4, v( 2)) **\n                 ARRAY( !! (watches), # 4, v( 3))) **\n                ((([!! (varx) <<<< # 4] **\n                   AbsAll TreeRecords( v( 7))\n                     ([nth( find( v( 8), v( 0)), # 2) <<<< # 4])) **\n                  (([!! (valuex) ==== # 1] *\\/* [!! (valuex) ==== # 2]) **\n                   AbsAll TreeRecords( v( 7))\n                     ([nth( find( v( 8), v( 0)), # 3) ==== # 1] *\\/*\n                      [nth( find( v( 8), v( 0)), # 3) ==== # 2])) **\n                  ([nth( v( 2), !! (varx)) ==== !! (valuex)] **\n                   AbsAll TreeRecords( v( 7))\n                     ([nth( v( 3), nth( find( v( 8), v( 0)), # 2)) ====\n                       nth( find( v( 8), v( 0)), # 3)])) **\n                  AbsAll TreeRecords( v( 7))\n                    ([~~ !! (varx) ==== nth( find( v( 8), v( 0)), # 2)]) **\n                  AbsAll TreeRecords( v( 7))\n                    (AbsAll TreeRecords( nth( find( v( 8), v( 0)), # 1))\n                       ([~~\n                         nth( find( v( 9), v( 1)), # 2) ====\n                         nth( find( nth( find( v( 9), v( 1)), # 1), v( 0)),\n                         # 2)]))) **\n                 AbsAll range( # 0, # 4)\n                   ([nth( v( 3), v( 0)) ==== # 0] *\\/*\n                    [!! (varx) ==== v( 0)] *\\/*\n                    AbsExists TreeRecords( v( 8))\n                      ([nth( find( v( 9), v( 0)), # 2) ==== v( 1)] **\n                       [nth( find( v( 9), v( 0)), # 3) ====\n                        nth( v( 4), v( 1))]))) **\n                AbsAll TreeRecords( v( 1))\n                  ([--( v( 2), v( 0) )---> # 1 ==== # 0] **\n                   [nth( v( 2), v( 0)) ==== v( 0)] *\\/*\n                   [--( v( 2), v( 0) )---> # 1 inTree v( 0)] **\n                   [--( v( 2), --( v( 2), v( 0) )---> # 1 )---> # 0 ====\n                    v( 0)]) **\n                AbsEach range( # 0, # 4)\n                  (AbsExistsT\n                     (Path( nth( list( v( 7)\n                                       :: v( 9)\n                                          :: !! (varx)\n                                             :: !! (valuex) :: v( 12) :: nil),\n                            v( 4)), v( 0), v( 5), \n                      # 21, # 13 ++++ v( 4) :: nil) **\n                      AbsAll TreeRecords( v( 5))\n                        ([--( v( 6), v( 0) )---> (# 17 ++++ v( 3)) ==== # 0] **\n                         [nth( v( 6), v( 0)) ==== v( 0)] *\\/*\n                         [--( v( 6), v( 0) )---> (# 17 ++++ v( 3))\n                          inTree v( 0)] **\n                         [--( v( 6), --( v( 6), v( 0) )---> (# 17 ++++ v( 3))\n                          )---> (# 13 ++++ v( 3)) ==== \n                          v( 0)]) **\n                      AbsAll TreeRecords( v( 0))\n                        (AbsExists range( # 0, # 4)\n                           ([--( v( 1),\n                             list( v( 9)\n                                   :: v( 11)\n                                      :: !! (varx)\n                                         :: !! (valuex) :: v( 14) :: nil)\n                             )---> (# 1 ++++ v( 0))] **\n                            ([nth( v( 4), v( 0)) ==== # 2] *\\/*\n                             [nth( v( 4), v( 0)) ==== # 0]) *\\/*\n                            [--( v( 1),\n                             list( v( 9)\n                                   :: v( 11)\n                                      :: !! (varx)\n                                         :: !! (valuex) :: v( 14) :: nil)\n                             )---> (# 5 ++++ v( 2))] **\n                            ([nth( v( 4), v( 0)) ==== # 1] *\\/*\n                             [nth( v( 4), v( 0)) ==== # 0]))) **\n                      AbsAll range( # 0, # 4)\n                        (([--( v( 0), v( 1) )---> (# 9 ++++ v( 0)) ==== # 0] *\\/*\n                          [--( v( 0), v( 1) )---> (# 1 ++++ v( 0))]) *\\/*\n                         [--( v( 0), v( 1) )---> (# 5 ++++ v( 0))]) **\n                      AbsAll range( # 0, # 4)\n                        ([# 0 <<<< --( v( 1), v( 5) )---> (# 9 ++++ v( 0))] **\n                         ([# 0 <<<< --( v( 1), v( 5) )---> (# 17 ++++ v( 0))] *\\/*\n                          [nth( v( 0), v( 2)) ==== v( 1)]) *\\/*\n                         ([--( v( 1), v( 5) )---> (# 9 ++++ v( 0)) ==== # 0] **\n                          [--( v( 1), v( 5) )---> (# 17 ++++ v( 0)) ==== # 0]) **\n                         [~~ nth( v( 4), v( 0)) ==== v( 5)]) **\n                      SUM( range( # 0, # 4),\n                      # 0 <<<< --( v( 0), v( 4) )---> (# 9 ++++ v( 0)), \n                      # 2) **\n                      (SUM( range( # 0, # 4),\n                       (--( v( 4), v( 3) )---> (# 1 ++++ v( 0)) \\\\//\n                        --( v( 4), v( 3) )---> (# 5 ++++ v( 0))) //\\\\\n                       nth( v( 3), v( 0)) ==== # 0, \n                       # 1) **\n                       AbsAll range( # 0, # 4)\n                         ([# 0 <<<< --( v( 1), v( 5) )---> (# 9 ++++ v( 0))] **\n                          [nth( v( 5), v( 0)) ==== # 0] *\\/*\n                          [# 0 <<<< nth( v( 5), v( 0))] *\\/*\n                          [--( v( 1), v( 5) )---> (# 1 ++++ v( 0)) ==== # 0] **\n                          [--( v( 1), v( 5) )---> (# 5 ++++ v( 0)) ==== # 0]) **\n                       AbsAll range( # 0, # 4)\n                         (AbsAll range( # 0, # 4)\n                            ((((([--( v( 2), v( 6) )---> (# 9 ++++ v( 0))] *\\/*\n                                 [--( v( 2), v( 6) )---> (# 1 ++++ v( 0)) ====\n                                  # 0] **\n                                 [--( v( 2), v( 6) )---> (# 5 ++++ v( 0)) ====\n                                  # 0]) *\\/*\n                                [~~ --( v( 2), v( 6) )---> (# 9 ++++ v( 1))]) *\\/*\n                               [nth( v( 5), v( 1)) ==== # 0]) *\\/*\n                              [v( 0) ==== v( 1)]) *\\/*\n                             AbsExists TreeRecords( v( 4))\n                               ([nth( find( v( 5), v( 0)), # 2) ==== v( 2)] **\n                                AbsExists TreeRecords( find( v( 5), v( 0)))\n                                  ([nth( find( v( 6), v( 0)), # 2) ==== v( 1)])))) *\\/*\n                       AbsExists range( # 0, # 4)\n                         ([--( v( 1), v( 5) )---> (# 1 ++++ v( 0))] **\n                          [nth( v( 4), v( 0)) ==== # 2] *\\/*\n                          [--( v( 1), v( 5) )---> (# 5 ++++ v( 0))] **\n                          [nth( v( 1), v( 5)) ==== # 1]) **\n                       AbsAll range( # 0, # 4)\n                         ([# 0 ==== nth( v( 4), v( 0))] *\\/*\n                          [--( v( 1), v( 5) )---> (# 9 ++++ v( 0)) ==== # 0] **\n                          [# 0 <<<< nth( v( 4), v( 0))] *\\/*\n                          AbsExists TreeRecords( v( 3))\n                            ([nth( find( v( 4), v( 0)), # 2) ==== v( 1)]) **\n                          AbsExists TreeRecords( find( v( 0), v( 0)))\n                            ([# 0 <<<<\n                              --( v( 2), v( 6)\n                              )---> (# 1 ++++ nth( find( v( 4), v( 0)), # 2))] **\n                             [nth( find( v( 4), v( 0)), # 3) ==== # 2] *\\/*\n                             [# 0 <<<<\n                              --( v( 2), v( 6)\n                              )---> (# 5 ++++ nth( find( v( 4), v( 0)), # 2))] **\n                             [nth( find( v( 4), v( 0)), # 3) ==== # 1])) *\\/*\n                       AbsAll range( # 0, # 4)\n                         ([--( v( 1), v( 5) )---> (# 9 ++++ v( 0)) ==== # 0] *\\/*\n                          [nth( v( 4), v( 0)) ==== # 0]))))) **\n               [!! (assignments_to_do_head) inTree v( 1)] **\n               [nth( find( !! (assignments_to_do_head), v( 1)), # 1) ==== # 0]) **\n              [# 0 <<<< v( 5)]) ** [v( 6) ==== # 0]) ** \n            [v( 4)]) ** [!! (backtrack) ==== # 0]) **\n          [!! (stack) ==== !! (ssss)]) ** [!! (have_var) ==== # 1]) bind s ->\nexists q : nat, absEval\n    (fst s) bind !! (varx) <<<< # 4 = NatValue (S q).\nProof.\n    intros bind s H.\n    admit.\nAdmitted.\n\nTheorem mergeImplies : forall l r m,\n    (exists m', mergeStates l r m' /\\ (forall s, realizeState m' nil s -> realizeState m nil s)) ->\n    mergeStates l r m.\nProof.\n    admit.\nAdmitted.\n\nTheorem mergePredicateTheorem1 :\nforall (eee : env) (hhh : heap) (bbb : list Value),\n  length bbb = 12 ->\n  realizeState\n    (([nth( v( 4), !! (varx)) ==== # 0] **\n      ((([!! (ssss) ==== nth( v( 8), # 0)] **\n         [!! (valuex) ==== v( 10)] **\n         [!! (varx) ==== v( 9)] **\n         ((((((AbsEmpty ** AbsEmpty ** AbsEmpty ** AbsEmpty) **\n              ((([!! (varx) <<<< # 4] ** AbsEmpty) **\n                (([!! (valuex) ==== # 1] *\\/* [!! (valuex) ==== # 2]) **\n                 AbsEmpty) **\n                ([v( 0) ==== !! (valuex)] **\n                 AbsAll TreeRecords( v( 8))\n                   ([nth( replacenth( v( 5), !! (varx), !! (valuex)),\n                     nth( find( v( 9), v( 0)), # 2)) ====\n                     nth( find( v( 9), v( 0)), # 3)])) ** AbsEmpty) **\n               AbsAll range( # 0, # 4)\n                 ([nth( v( 5), v( 0)) ==== # 0] *\\/*\n                  [!! (varx) ==== v( 0)] *\\/*\n                  AbsExists TreeRecords( v( 9))\n                    ([nth( find( v( 10), v( 0)), # 2) ==== v( 1)] **\n                     [nth( find( v( 10), v( 0)), # 3) ==== nth( v( 6), v( 1))]))) **\n              AbsEmpty **\n              AbsEach range( # 0, # 4)\n                (AbsExistsT\n                   (Path( nth( list( v( 9)\n                                     :: v( 10)\n                                        :: !! (varx)\n                                           :: !! (valuex) :: v( 13) :: nil),\n                          replacenth( v( 6), !! (varx), !! (valuex))), \n                    v( 0), v( 7), # 21,\n                    # 13 ++++ replacenth( v( 6), !! (varx), !! (valuex))\n                    :: nil) **\n                    AbsAll TreeRecords( v( 7))\n                      ([--( v( 8), v( 0) )---> (# 17 ++++ !! (valuex)) ====\n                        # 0] ** [nth( v( 8), v( 0)) ==== v( 0)] *\\/*\n                       [--( v( 8), v( 0) )---> (# 17 ++++ !! (valuex))\n                        inTree v( 0)] **\n                       [--( v( 8),\n                        --( v( 8), v( 0) )---> (# 17 ++++ !! (valuex))\n                        )---> (# 13 ++++ !! (valuex)) ==== \n                        v( 0)]) **\n                    AbsAll TreeRecords( v( 0))\n                      (AbsExists range( # 0, # 4)\n                         ([--( v( 1),\n                           list( v( 11)\n                                 :: v( 12)\n                                    :: !! (varx)\n                                       :: !! (valuex) :: v( 15) :: nil)\n                           )---> (# 1 ++++ v( 0))] **\n                          ([nth( !! (valuex), v( 0)) ==== # 2] *\\/*\n                           [nth( !! (valuex), v( 0)) ==== # 0]) *\\/*\n                          [--( v( 1),\n                           list( v( 11)\n                                 :: v( 12)\n                                    :: !! (varx)\n                                       :: !! (valuex) :: v( 15) :: nil)\n                           )---> (# 5 ++++ v( 2))] **\n                          ([nth( !! (valuex), v( 0)) ==== # 1] *\\/*\n                           [nth( !! (valuex), v( 0)) ==== # 0]))) **\n                    AbsAll range( # 0, # 4)\n                      (([--( v( 0), v( 1) )---> (# 9 ++++ v( 0)) ==== # 0] *\\/*\n                        [--( v( 0), v( 1) )---> (# 1 ++++ v( 0))]) *\\/*\n                       [--( v( 0), v( 1) )---> (# 5 ++++ v( 0))]) **\n                    AbsAll range( # 0, # 4)\n                      ([# 0 <<<<\n                        --( v( 1), replacenth( v( 7), !! (varx), !! (valuex))\n                        )---> (# 9 ++++ v( 0))] **\n                       ([# 0 <<<<\n                         --( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 17 ++++ v( 0))] *\\/*\n                        [nth( v( 0), v( 2)) ==== v( 1)]) *\\/*\n                       ([--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 9 ++++ v( 0)) ==== \n                         # 0] **\n                        [--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 17 ++++ v( 0)) ==== \n                         # 0]) **\n                       [~~\n                        nth( v( 5), v( 0)) ====\n                        replacenth( v( 7), !! (varx), !! (valuex))]) **\n                    SUM( range( # 0, # 4),\n                    # 0 <<<<\n                    --( v( 0), replacenth( v( 6), !! (varx), !! (valuex))\n                    )---> (# 9 ++++ v( 0)), # 2) **\n                    (SUM( range( # 0, # 4),\n                     (--( replacenth( v( 6), !! (varx), !! (valuex)), \n                      v( 4) )---> (# 1 ++++ v( 0)) \\\\//\n                      --( replacenth( v( 6), !! (varx), !! (valuex)), \n                      v( 4) )---> (# 5 ++++ v( 0))) //\\\\\n                     nth( v( 4), v( 0)) ==== # 0, \n                     # 1) **\n                     AbsAll range( # 0, # 4)\n                       ([# 0 <<<<\n                         --( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 9 ++++ v( 0))] **\n                        [nth( replacenth( v( 7), !! (varx), !! (valuex)),\n                         v( 0)) ==== # 0] *\\/*\n                        [# 0 <<<<\n                         nth( replacenth( v( 7), !! (varx), !! (valuex)),\n                         v( 0))] *\\/*\n                        [--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 1 ++++ v( 0)) ==== \n                         # 0] **\n                        [--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 5 ++++ v( 0)) ==== \n                         # 0]) **\n                     AbsAll range( # 0, # 4)\n                       (AbsAll range( # 0, # 4)\n                          ((((([--( v( 2),\n                                replacenth( v( 8), !! (varx), !! (valuex))\n                                )---> (# 9 ++++ v( 0))] *\\/*\n                               [--( v( 2),\n                                replacenth( v( 8), !! (varx), !! (valuex))\n                                )---> (# 1 ++++ v( 0)) ==== \n                                # 0] **\n                               [--( v( 2),\n                                replacenth( v( 8), !! (varx), !! (valuex))\n                                )---> (# 5 ++++ v( 0)) ==== \n                                # 0]) *\\/*\n                              [~~\n                               --( v( 2),\n                               replacenth( v( 8), !! (varx), !! (valuex))\n                               )---> (# 9 ++++ v( 1))]) *\\/*\n                             [nth( v( 6), v( 1)) ==== # 0]) *\\/*\n                            [v( 0) ==== v( 1)]) *\\/*\n                           AbsExists (AbsConstVal (ListValue nil))\n                             (AbsExists\n                                TreeRecords( find( !! (valuex), v( 0)))\n                                ([nth( find( !! (valuex), v( 1)), # 2) ====\n                                  v( 3)] **\n                                 [nth( find( !! (valuex), v( 0)), # 2) ====\n                                  v( 1)])))) *\\/*\n                     AbsExists range( # 0, # 4)\n                       (([--( v( 1),\n                          replacenth( v( 7), !! (varx), !! (valuex))\n                          )---> (# 1 ++++ v( 0))] **\n                         [nth( v( 5), v( 0)) ==== # 2] *\\/*\n                         [--( v( 1),\n                          replacenth( v( 7), !! (varx), !! (valuex))\n                          )---> (# 5 ++++ v( 0))] **\n                         [nth( v( 1),\n                          replacenth( v( 7), !! (varx), !! (valuex))) ====\n                          # 1]) **\n                        AbsAll range( # 0, # 4)\n                          ([# 0 ==== nth( v( 6), v( 0))] *\\/*\n                           [--( v( 2),\n                            replacenth( v( 8), !! (varx), !! (valuex))\n                            )---> (# 9 ++++ v( 0)) ==== \n                            # 0] ** [# 0 <<<< nth( v( 6), v( 0))] *\\/*\n                           AbsExists (AbsConstVal (ListValue nil))\n                             ([nth( find( !! (valuex), v( 0)), # 2) ====\n                               v( 1)] **\n                              AbsExists TreeRecords( find( v( 1), v( 1)))\n                                ([# 0 <<<<\n                                  --( v( 4),\n                                  replacenth( v( 10), !! (varx), !! (valuex))\n                                  )---> (# 1 ++++\n                                         nth( find( !! (valuex), v( 0)), # 2))] **\n                                 [nth( find( !! (valuex), v( 0)), # 3) ====\n                                  # 2] *\\/*\n                                 [# 0 <<<<\n                                  --( v( 4),\n                                  replacenth( v( 10), !! (varx), !! (valuex))\n                                  )---> (# 5 ++++\n                                         nth( find( !! (valuex), v( 0)), # 2))] **\n                                 [nth( find( !! (valuex), v( 0)), # 3) ====\n                                  # 1])))) *\\/*\n                     AbsAll range( # 0, # 4)\n                       ([--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 9 ++++ v( 0)) ==== \n                         # 0] *\\/* [nth( v( 5), v( 0)) ==== # 0]))))) **\n             AbsEmpty ** AbsEmpty) **\n            ([# 0 <<<< v( 7)] *\\/* [v( 6) ==== # 0])) ** \n           [!! (valuex)]) ** [v( 3) ==== # 0]) ** \n         [!! (backtrack) ==== # 0]) ** [!! (stack) ==== !! (ssss)]) **\n       [!! (have_var) ==== # 1]) ** AbsEmpty) **\n     (ARRAY( !! (assignments), # 4, v( 4)) **\n      [nth( find( !! (assignments_to_do_head), v( 2)), # 1) ==== # 0] **\n      [!! (assignments_to_do_head) inTree v( 2)] **\n      AbsAll TreeRecords( v( 2))\n        ([--( v( 3), v( 0) )---> # 1 ==== # 0] **\n         [nth( v( 3), v( 0)) ==== v( 0)] *\\/*\n         [--( v( 3), v( 0) )---> # 1 inTree v( 0)] **\n         [--( v( 3), --( v( 3), v( 0) )---> # 1 )---> # 0 ==== v( 0)]) **\n      AbsAll TreeRecords( v( 8))\n        (AbsAll TreeRecords( nth( find( v( 9), v( 0)), # 2))\n           ([~~\n             nth( find( v( 10), v( 1)), # 2) ====\n             nth( find( nth( find( v( 10), v( 1)), # 2), v( 0)), # 2)])) **\n      AbsAll TreeRecords( v( 8))\n        ([nth( find( v( 9), v( 0)), # 3) ==== # 1] *\\/*\n         [nth( find( v( 9), v( 0)), # 3) ==== # 2]) **\n      AbsAll TreeRecords( v( 8)) ([nth( find( v( 9), v( 0)), # 2) <<<< # 4]) **\n      ARRAY( !! (watches), # 4, v( 5)) **\n      TREE( !! (stack), v( 8), # 4, # 0 :: nil) **\n      TREE( !! (assignments_to_do_head), v( 2), # 4, # 0 :: nil) **\n      TREE( !! (clauses), v( 0), # 21, # 0 :: nil) ** AbsEmpty) **\n     build_equivs\n       ((!! (have_var) :: # 1 :: nil)\n        :: (!! (varx) :: v( 9) :: nil)\n           :: (v( 10) :: v( 0) :: !! (valuex) :: nil)\n              :: (nth( v( 8), # 0) :: !! (stack) :: !! (ssss) :: nil)\n                 :: (nth( v( 4), !! (varx))\n                     :: nth( find( !! (assignments_to_do_head), v( 2)), # 1)\n                        :: v( 3) :: !! (backtrack) :: # 0 :: nil) :: nil))\n    bbb (eee, hhh) ->\n  realizeState\n    (AbsAll TreeRecords( v( 8))\n       ([nth( v( 5), nth( find( v( 9), v( 0)), # 2)) ====\n         nth( find( v( 9), v( 0)), # 3)])) bbb (eee, empty_heap).\nProof.\n    admit.\nAdmitted.\n\nTheorem mergePredicateTheorem2 :\nforall (eee : env) (hhh : heap) (bbb : list Value),\n  length bbb = 12 ->\n  realizeState\n    (([nth( v( 4), !! (varx)) ==== # 0] **\n      ((([!! (ssss) ==== nth( v( 8), # 0)] **\n         [!! (valuex) ==== v( 10)] **\n         [!! (varx) ==== v( 9)] **\n         ((((((AbsEmpty ** AbsEmpty ** AbsEmpty ** AbsEmpty) **\n              ((([!! (varx) <<<< # 4] ** AbsEmpty) **\n                (([!! (valuex) ==== # 1] *\\/* [!! (valuex) ==== # 2]) **\n                 AbsEmpty) **\n                ([v( 0) ==== !! (valuex)] **\n                 AbsAll TreeRecords( v( 8))\n                   ([nth( replacenth( v( 5), !! (varx), !! (valuex)),\n                     nth( find( v( 9), v( 0)), # 2)) ====\n                     nth( find( v( 9), v( 0)), # 3)])) ** AbsEmpty) **\n               AbsAll range( # 0, # 4)\n                 ([nth( v( 5), v( 0)) ==== # 0] *\\/*\n                  [!! (varx) ==== v( 0)] *\\/*\n                  AbsExists TreeRecords( v( 9))\n                    ([nth( find( v( 10), v( 0)), # 2) ==== v( 1)] **\n                     [nth( find( v( 10), v( 0)), # 3) ==== nth( v( 6), v( 1))]))) **\n              AbsEmpty **\n              AbsEach range( # 0, # 4)\n                (AbsExistsT\n                   (Path( nth( list( v( 9)\n                                     :: v( 10)\n                                        :: !! (varx)\n                                           :: !! (valuex) :: v( 13) :: nil),\n                          replacenth( v( 6), !! (varx), !! (valuex))), \n                    v( 0), v( 7), # 21,\n                    # 13 ++++ replacenth( v( 6), !! (varx), !! (valuex))\n                    :: nil) **\n                    AbsAll TreeRecords( v( 7))\n                      ([--( v( 8), v( 0) )---> (# 17 ++++ !! (valuex)) ====\n                        # 0] ** [nth( v( 8), v( 0)) ==== v( 0)] *\\/*\n                       [--( v( 8), v( 0) )---> (# 17 ++++ !! (valuex))\n                        inTree v( 0)] **\n                       [--( v( 8),\n                        --( v( 8), v( 0) )---> (# 17 ++++ !! (valuex))\n                        )---> (# 13 ++++ !! (valuex)) ==== \n                        v( 0)]) **\n                    AbsAll TreeRecords( v( 0))\n                      (AbsExists range( # 0, # 4)\n                         ([--( v( 1),\n                           list( v( 11)\n                                 :: v( 12)\n                                    :: !! (varx)\n                                       :: !! (valuex) :: v( 15) :: nil)\n                           )---> (# 1 ++++ v( 0))] **\n                          ([nth( !! (valuex), v( 0)) ==== # 2] *\\/*\n                           [nth( !! (valuex), v( 0)) ==== # 0]) *\\/*\n                          [--( v( 1),\n                           list( v( 11)\n                                 :: v( 12)\n                                    :: !! (varx)\n                                       :: !! (valuex) :: v( 15) :: nil)\n                           )---> (# 5 ++++ v( 2))] **\n                          ([nth( !! (valuex), v( 0)) ==== # 1] *\\/*\n                           [nth( !! (valuex), v( 0)) ==== # 0]))) **\n                    AbsAll range( # 0, # 4)\n                      (([--( v( 0), v( 1) )---> (# 9 ++++ v( 0)) ==== # 0] *\\/*\n                        [--( v( 0), v( 1) )---> (# 1 ++++ v( 0))]) *\\/*\n                       [--( v( 0), v( 1) )---> (# 5 ++++ v( 0))]) **\n                    AbsAll range( # 0, # 4)\n                      ([# 0 <<<<\n                        --( v( 1), replacenth( v( 7), !! (varx), !! (valuex))\n                        )---> (# 9 ++++ v( 0))] **\n                       ([# 0 <<<<\n                         --( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 17 ++++ v( 0))] *\\/*\n                        [nth( v( 0), v( 2)) ==== v( 1)]) *\\/*\n                       ([--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 9 ++++ v( 0)) ==== \n                         # 0] **\n                        [--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 17 ++++ v( 0)) ==== \n                         # 0]) **\n                       [~~\n                        nth( v( 5), v( 0)) ====\n                        replacenth( v( 7), !! (varx), !! (valuex))]) **\n                    SUM( range( # 0, # 4),\n                    # 0 <<<<\n                    --( v( 0), replacenth( v( 6), !! (varx), !! (valuex))\n                    )---> (# 9 ++++ v( 0)), # 2) **\n                    (SUM( range( # 0, # 4),\n                     (--( replacenth( v( 6), !! (varx), !! (valuex)), \n                      v( 4) )---> (# 1 ++++ v( 0)) \\\\//\n                      --( replacenth( v( 6), !! (varx), !! (valuex)), \n                      v( 4) )---> (# 5 ++++ v( 0))) //\\\\\n                     nth( v( 4), v( 0)) ==== # 0, \n                     # 1) **\n                     AbsAll range( # 0, # 4)\n                       ([# 0 <<<<\n                         --( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 9 ++++ v( 0))] **\n                        [nth( replacenth( v( 7), !! (varx), !! (valuex)),\n                         v( 0)) ==== # 0] *\\/*\n                        [# 0 <<<<\n                         nth( replacenth( v( 7), !! (varx), !! (valuex)),\n                         v( 0))] *\\/*\n                        [--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 1 ++++ v( 0)) ==== \n                         # 0] **\n                        [--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 5 ++++ v( 0)) ==== \n                         # 0]) **\n                     AbsAll range( # 0, # 4)\n                       (AbsAll range( # 0, # 4)\n                          ((((([--( v( 2),\n                                replacenth( v( 8), !! (varx), !! (valuex))\n                                )---> (# 9 ++++ v( 0))] *\\/*\n                               [--( v( 2),\n                                replacenth( v( 8), !! (varx), !! (valuex))\n                                )---> (# 1 ++++ v( 0)) ==== \n                                # 0] **\n                               [--( v( 2),\n                                replacenth( v( 8), !! (varx), !! (valuex))\n                                )---> (# 5 ++++ v( 0)) ==== \n                                # 0]) *\\/*\n                              [~~\n                               --( v( 2),\n                               replacenth( v( 8), !! (varx), !! (valuex))\n                               )---> (# 9 ++++ v( 1))]) *\\/*\n                             [nth( v( 6), v( 1)) ==== # 0]) *\\/*\n                            [v( 0) ==== v( 1)]) *\\/*\n                           AbsExists (AbsConstVal (ListValue nil))\n                             (AbsExists\n                                TreeRecords( find( !! (valuex), v( 0)))\n                                ([nth( find( !! (valuex), v( 1)), # 2) ====\n                                  v( 3)] **\n                                 [nth( find( !! (valuex), v( 0)), # 2) ====\n                                  v( 1)])))) *\\/*\n                     AbsExists range( # 0, # 4)\n                       (([--( v( 1),\n                          replacenth( v( 7), !! (varx), !! (valuex))\n                          )---> (# 1 ++++ v( 0))] **\n                         [nth( v( 5), v( 0)) ==== # 2] *\\/*\n                         [--( v( 1),\n                          replacenth( v( 7), !! (varx), !! (valuex))\n                          )---> (# 5 ++++ v( 0))] **\n                         [nth( v( 1),\n                          replacenth( v( 7), !! (varx), !! (valuex))) ====\n                          # 1]) **\n                        AbsAll range( # 0, # 4)\n                          ([# 0 ==== nth( v( 6), v( 0))] *\\/*\n                           [--( v( 2),\n                            replacenth( v( 8), !! (varx), !! (valuex))\n                            )---> (# 9 ++++ v( 0)) ==== \n                            # 0] ** [# 0 <<<< nth( v( 6), v( 0))] *\\/*\n                           AbsExists (AbsConstVal (ListValue nil))\n                             ([nth( find( !! (valuex), v( 0)), # 2) ====\n                               v( 1)] **\n                              AbsExists TreeRecords( find( v( 1), v( 1)))\n                                ([# 0 <<<<\n                                  --( v( 4),\n                                  replacenth( v( 10), !! (varx), !! (valuex))\n                                  )---> (# 1 ++++\n                                         nth( find( !! (valuex), v( 0)), # 2))] **\n                                 [nth( find( !! (valuex), v( 0)), # 3) ====\n                                  # 2] *\\/*\n                                 [# 0 <<<<\n                                  --( v( 4),\n                                  replacenth( v( 10), !! (varx), !! (valuex))\n                                  )---> (# 5 ++++\n                                         nth( find( !! (valuex), v( 0)), # 2))] **\n                                 [nth( find( !! (valuex), v( 0)), # 3) ====\n                                  # 1])))) *\\/*\n                     AbsAll range( # 0, # 4)\n                       ([--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 9 ++++ v( 0)) ==== \n                         # 0] *\\/* [nth( v( 5), v( 0)) ==== # 0]))))) **\n             AbsEmpty ** AbsEmpty) **\n            ([# 0 <<<< v( 7)] *\\/* [v( 6) ==== # 0])) ** \n           [!! (valuex)]) ** [v( 3) ==== # 0]) ** \n         [!! (backtrack) ==== # 0]) ** [!! (stack) ==== !! (ssss)]) **\n       [!! (have_var) ==== # 1]) ** AbsEmpty) **\n     (ARRAY( !! (assignments), # 4, v( 4)) **\n      [nth( find( !! (assignments_to_do_head), v( 2)), # 1) ==== # 0] **\n      [!! (assignments_to_do_head) inTree v( 2)] **\n      AbsAll TreeRecords( v( 2))\n        ([--( v( 3), v( 0) )---> # 1 ==== # 0] **\n         [nth( v( 3), v( 0)) ==== v( 0)] *\\/*\n         [--( v( 3), v( 0) )---> # 1 inTree v( 0)] **\n         [--( v( 3), --( v( 3), v( 0) )---> # 1 )---> # 0 ==== v( 0)]) **\n      AbsAll TreeRecords( v( 8))\n        (AbsAll TreeRecords( nth( find( v( 9), v( 0)), # 2))\n           ([~~\n             nth( find( v( 10), v( 1)), # 2) ====\n             nth( find( nth( find( v( 10), v( 1)), # 2), v( 0)), # 2)])) **\n      AbsAll TreeRecords( v( 8))\n        ([nth( find( v( 9), v( 0)), # 3) ==== # 1] *\\/*\n         [nth( find( v( 9), v( 0)), # 3) ==== # 2]) **\n      AbsAll TreeRecords( v( 8)) ([nth( find( v( 9), v( 0)), # 2) <<<< # 4]) **\n      ARRAY( !! (watches), # 4, v( 5)) **\n      TREE( !! (stack), v( 8), # 4, # 0 :: nil) **\n      TREE( !! (assignments_to_do_head), v( 2), # 4, # 0 :: nil) **\n      TREE( !! (clauses), v( 0), # 21, # 0 :: nil) ** AbsEmpty) **\n     build_equivs\n       ((!! (have_var) :: # 1 :: nil)\n        :: (!! (varx) :: v( 9) :: nil)\n           :: (v( 10) :: v( 0) :: !! (valuex) :: nil)\n              :: (nth( v( 8), # 0) :: !! (stack) :: !! (ssss) :: nil)\n                 :: (nth( v( 4), !! (varx))\n                     :: nth( find( !! (assignments_to_do_head), v( 2)), # 1)\n                        :: v( 3) :: !! (backtrack) :: # 0 :: nil) :: nil))\n    bbb (eee, hhh) ->\n  realizeState\n    (AbsAll range( # 0, # 4)\n       ([nth( v( 5), v( 0)) ==== # 0] *\\/*\n        AbsExists TreeRecords( v( 9))\n          ([nth( find( v( 10), v( 0)), # 2) ==== v( 1)] **\n           [nth( find( v( 10), v( 0)), # 3) ==== nth( v( 6), v( 1))]))) bbb\n    (eee, empty_heap).\nProof.\n    admit.\nAdmitted.\n\nTransparent nth.\n\nTheorem mergeFinalImplication1: forall s,\nrealizeState\n        (AbsExistsT\n           (AbsExistsT\n              (AbsExistsT\n                 (AbsExistsT\n                    (AbsExistsT\n                       (AbsExistsT\n                          (AbsExistsT\n                             (AbsExistsT\n                                (AbsExistsT\n                                   (AbsExistsT\n                                      (AbsExistsT\n                                         (AbsExistsT\n                                            (TREE( \n                                             !! (clauses), \n                                             v( 0), \n                                             # 21, \n                                             # 0 :: nil) **\n                                             TREE( \n                                             !! (assignments_to_do_head),\n                                             v( 2), \n                                             # 4, \n                                             # 0 :: nil) **\n                                             TREE( \n                                             !! (stack), \n                                             v( 8), \n                                             # 4, \n                                             # 0 :: nil) **\n                                             ARRAY( !! (watches), # 4, v( 5)) **\n                                             AbsAll \n                                               TreeRecords( v( 8))\n                                               ([nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 2) <<<< \n                                                 # 4]) **\n                                             AbsAll \n                                               TreeRecords( v( 8))\n                                               ([nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 3) ==== \n                                                 # 1] *\\/*\n                                                [nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 3) ==== \n                                                 # 2]) **\n                                             AbsAll \n                                               TreeRecords( v( 8))\n                                               (AbsAll\n                                                 TreeRecords( \n                                                 nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 2))\n                                                 ([\n                                                 ~~\n                                                 nth( \n                                                 find( v( 10), v( 1)), \n                                                 # 2) ====\n                                                 nth( \n                                                 find( \n                                                 nth( \n                                                 find( v( 10), v( 1)), \n                                                 # 2), \n                                                 v( 0)), \n                                                 # 2)])) **\n                                             AbsAll \n                                               TreeRecords( v( 2))\n                                               ([--( v( 3), v( 0) )---> # 1 ====\n                                                 # 0] **\n                                                [nth( v( 3), v( 0)) ====\n                                                 v( 0)] *\\/*\n                                                [--( v( 3), v( 0) )---> # 1\n                                                 inTree \n                                                 v( 0)] **\n                                                [--( \n                                                 v( 3),\n                                                 --( v( 3), v( 0) )---> # 1\n                                                 )---> \n                                                 # 0 ==== \n                                                 v( 0)]) **\n                                             [!! (assignments_to_do_head)\n                                              inTree \n                                              v( 2)] **\n                                             [nth( \n                                              find( \n                                              !! (assignments_to_do_head),\n                                              v( 2)), \n                                              # 1) ==== \n                                              # 0] **\n                                             ARRAY( \n                                             !! (assignments), \n                                             # 4, \n                                             v( 4)) **\n                                             AbsAll \n                                               TreeRecords( v( 8))\n                                               ([nth( \n                                                 v( 5),\n                                                 nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 2)) ====\n                                                 nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 3)]) **\n                                             AbsAll \n                                               range( # 0, # 4)\n                                               ([nth( v( 5), v( 0)) ==== # 0] *\\/*\n                                                AbsExists \n                                                 TreeRecords( v( 9))\n                                                 ([\n                                                 nth( \n                                                 find( v( 10), v( 0)), \n                                                 # 2) ==== \n                                                 v( 1)] **\n                                                 [\n                                                 nth( \n                                                 find( v( 10), v( 0)), \n                                                 # 3) ==== \n                                                 nth( v( 6), v( 1))])) **\n                                             AbsEach \n                                               range( # 0, # 4)\n                                               (AbsExistsT\n                                                 (Path( \n                                                 nth( v( 10), v( 6)), \n                                                 v( 0), \n                                                 v( 7), \n                                                 # 21,\n                                                 # 13 ++++ v( 6) :: nil) **\n                                                 AbsAll \n                                                 TreeRecords( v( 7))\n                                                 ([\n                                                 --( \n                                                 v( 8), \n                                                 v( 0)\n                                                 )---> \n                                                 (# 17 ++++ v( 3)) ==== \n                                                 # 0] **\n                                                 [\n                                                 nth( v( 8), v( 0)) ====\n                                                 v( 0)] *\\/*\n                                                 [\n                                                 --( \n                                                 v( 8), \n                                                 v( 0)\n                                                 )---> \n                                                 (# 17 ++++ v( 3))\n                                                 inTree \n                                                 v( 0)] **\n                                                 [\n                                                 --( \n                                                 v( 8),\n                                                 --( \n                                                 v( 8), \n                                                 v( 0)\n                                                 )---> \n                                                 (# 17 ++++ v( 3))\n                                                 )---> \n                                                 (# 13 ++++ v( 3)) ==== \n                                                 v( 0)]) **\n                                                 AbsAll \n                                                 TreeRecords( v( 0))\n                                                 (AbsExists \n                                                 range( # 0, # 4)\n                                                 ([\n                                                 --( \n                                                 v( 1), \n                                                 v( 12)\n                                                 )---> \n                                                 (# 1 ++++ v( 0))] **\n                                                 ([\n                                                 nth( v( 4), v( 0)) ==== \n                                                 # 2] *\\/*\n                                                 [\n                                                 nth( v( 4), v( 0)) ==== # 0]) *\\/*\n                                                 [\n                                                 --( \n                                                 v( 1), \n                                                 v( 12)\n                                                 )---> \n                                                 (# 5 ++++ v( 2))] **\n                                                 ([\n                                                 nth( v( 4), v( 0)) ==== \n                                                 # 1] *\\/*\n                                                 [\n                                                 nth( v( 4), v( 0)) ==== # 0]))) **\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 (([\n                                                 --( \n                                                 v( 0), \n                                                 v( 1) )---> \n                                                 (# 9 ++++ v( 0)) ==== \n                                                 # 0] *\\/*\n                                                 [\n                                                 --( \n                                                 v( 0), \n                                                 v( 1) )---> \n                                                 (# 1 ++++ v( 0))]) *\\/*\n                                                 [\n                                                 --( \n                                                 v( 0), \n                                                 v( 1) )---> \n                                                 (# 5 ++++ v( 0))]) **\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 ([\n                                                 # 0 <<<<\n                                                 --( \n                                                 v( 1), \n                                                 v( 7) )---> \n                                                 (# 9 ++++ v( 0))] **\n                                                 ([\n                                                 # 0 <<<<\n                                                 --( \n                                                 v( 1), \n                                                 v( 7)\n                                                 )---> \n                                                 (# 17 ++++ v( 0))] *\\/*\n                                                 [\n                                                 nth( v( 0), v( 2)) ====\n                                                 v( 1)]) *\\/*\n                                                 ([\n                                                 --( \n                                                 v( 1), \n                                                 v( 7) )---> \n                                                 (# 9 ++++ v( 0)) ==== \n                                                 # 0] **\n                                                 [\n                                                 --( \n                                                 v( 1), \n                                                 v( 7)\n                                                 )---> \n                                                 (# 17 ++++ v( 0)) ==== \n                                                 # 0]) **\n                                                 [\n                                                 ~~\n                                                 nth( v( 5), v( 0)) ====\n                                                 v( 7)]) **\n                                                 SUM( \n                                                 range( # 0, # 4),\n                                                 # 0 <<<<\n                                                 --( \n                                                 v( 0), \n                                                 v( 6) )---> \n                                                 (# 9 ++++ v( 0)), \n                                                 # 2) **\n                                                 (SUM( \n                                                 range( # 0, # 4),\n                                                 (--( \n                                                 v( 6), \n                                                 v( 4) )---> \n                                                 (# 1 ++++ v( 0)) \\\\//\n                                                 --( \n                                                 v( 6), \n                                                 v( 4) )---> \n                                                 (# 5 ++++ v( 0))) //\\\\\n                                                 nth( v( 4), v( 0)) ==== # 0,\n                                                 # 1) **\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 ([\n                                                 # 0 <<<<\n                                                 --( \n                                                 v( 1), \n                                                 v( 7) )---> \n                                                 (# 9 ++++ v( 0))] **\n                                                 [\n                                                 nth( v( 7), v( 0)) ==== # 0] *\\/*\n                                                 [\n                                                 # 0 <<<< nth( v( 7), v( 0))] *\\/*\n                                                 [\n                                                 --( \n                                                 v( 1), \n                                                 v( 7) )---> \n                                                 (# 1 ++++ v( 0)) ==== \n                                                 # 0] **\n                                                 [\n                                                 --( \n                                                 v( 1), \n                                                 v( 7) )---> \n                                                 (# 5 ++++ v( 0)) ==== \n                                                 # 0]) **\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 (AbsAll \n                                                 range( # 0, # 4)\n                                                 ((((([\n                                                 --( \n                                                 v( 2), \n                                                 v( 8) )---> \n                                                 (# 9 ++++ v( 0))] *\\/*\n                                                 [\n                                                 --( \n                                                 v( 2), \n                                                 v( 8) )---> \n                                                 (# 1 ++++ v( 0)) ==== \n                                                 # 0] **\n                                                 [\n                                                 --( \n                                                 v( 2), \n                                                 v( 8) )---> \n                                                 (# 5 ++++ v( 0)) ==== \n                                                 # 0]) *\\/*\n                                                 [\n                                                 ~~\n                                                 --( \n                                                 v( 2), \n                                                 v( 8) )---> \n                                                 (# 9 ++++ v( 1))]) *\\/*\n                                                 [\n                                                 nth( v( 6), v( 1)) ==== # 0]) *\\/*\n                                                 [v( 0) ==== v( 1)]) *\\/*\n                                                 AbsExists\n                                                 TreeRecords( v( 4))\n                                                 (AbsExists\n                                                 TreeRecords( \n                                                 find( \n                                                 v( 5), \n                                                 v( 0)))\n                                                 ([\n                                                 nth( \n                                                 find( v( 6), v( 1)), \n                                                 # 2) ==== \n                                                 v( 3)] **\n                                                 [\n                                                 nth( \n                                                 find( v( 6), v( 0)), \n                                                 # 2) ==== \n                                                 v( 1)])))) *\\/*\n                                                 AbsExists \n                                                 range( # 0, # 4)\n                                                 (([\n                                                 --( \n                                                 v( 1), \n                                                 v( 7) )---> \n                                                 (# 1 ++++ v( 0))] **\n                                                 [\n                                                 nth( v( 5), v( 0)) ==== # 2] *\\/*\n                                                 [\n                                                 --( \n                                                 v( 1), \n                                                 v( 7) )---> \n                                                 (# 5 ++++ v( 0))] **\n                                                 [\n                                                 nth( v( 1), v( 7)) ==== # 1]) **\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 ([\n                                                 # 0 ==== \n                                                 nth( v( 6), v( 0))] *\\/*\n                                                 [\n                                                 --( \n                                                 v( 2), \n                                                 v( 8) )---> \n                                                 (# 9 ++++ v( 0)) ==== \n                                                 # 0] **\n                                                 [\n                                                 # 0 <<<< nth( v( 6), v( 0))] *\\/*\n                                                 AbsExists\n                                                 TreeRecords( v( 4))\n                                                 (AbsExists\n                                                 TreeRecords( \n                                                 find( \n                                                 v( 1), \n                                                 v( 1)))\n                                                 ([\n                                                 nth( \n                                                 find( v( 6), v( 1)), \n                                                 # 2) ==== \n                                                 v( 2)] **\n                                                 ([\n                                                 # 0 <<<<\n                                                 --( \n                                                 v( 4), \n                                                 v( 10)\n                                                 )---> \n                                                 (# 1 ++++\n                                                 nth( \n                                                 find( v( 6), v( 0)), \n                                                 # 2))] **\n                                                 [\n                                                 nth( \n                                                 find( v( 6), v( 0)), \n                                                 # 3) ==== \n                                                 # 2] *\\/*\n                                                 [\n                                                 # 0 <<<<\n                                                 --( \n                                                 v( 4), \n                                                 v( 10)\n                                                 )---> \n                                                 (# 5 ++++\n                                                 nth( \n                                                 find( v( 6), v( 0)), \n                                                 # 2))] **\n                                                 [\n                                                 nth( \n                                                 find( v( 6), v( 0)), \n                                                 # 3) ==== \n                                                 # 1]))))) *\\/*\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 ([\n                                                 --( \n                                                 v( 1), \n                                                 v( 7) )---> \n                                                 (# 9 ++++ v( 0)) ==== \n                                                 # 0] *\\/*\n                                                 [\n                                                 nth( v( 5), v( 0)) ==== # 0])))) **\n                                             AbsEmpty))))))))))))) nil s ->\nrealizeState\n    (AbsExistsT\n       (AbsExistsT\n          (AbsExistsT\n             (AbsExistsT\n                (AbsExistsT\n                   (((TREE( !! (clauses), v( 0), # 21, # 0 :: nil) **\n                      TREE( !! (assignments_to_do_head), \n                      v( 1), # 4, # 0 :: nil) **\n                      TREE( !! (stack), v( 2), # 4, # 0 :: nil) **\n                      ARRAY( !! (assignments), # 4, v( 3)) **\n                      ARRAY( !! (watches), # 4, v( 4))) **\n                     (AbsAll TreeRecords( v( 2))\n                        ([nth( find( v( 3), v( 0)), # 2) <<<< # 4] **\n                         ([nth( find( v( 3), v( 0)), # 3) ==== # 1] *\\/*\n                          [nth( find( v( 3), v( 0)), # 3) ==== # 2]) **\n                         [nth( v( 4), nth( find( v( 3), v( 0)), # 2)) ====\n                          nth( find( v( 3), v( 0)), # 3)] **\n                         AbsAll TreeRecords( nth( find( v( 3), v( 0)), # 2))\n                           ([~~\n                             nth( find( v( 4), v( 1)), # 2) ====\n                             nth( find( nth( find( v( 4), v( 1)), # 2),\n                                  v( 0)), # 2)])) **\n                      AbsAll range( # 0, # 4)\n                        ([nth( v( 4), v( 0)) ==== # 0] *\\/*\n                         AbsExists TreeRecords( v( 3))\n                           ([nth( find( v( 4), v( 0)), # 2) ==== v( 1) //\\\\\n                             nth( find( v( 4), v( 0)), # 3) ====\n                             nth( v( 5), v( 1))]))) **\n                     AbsAll TreeRecords( v( 1))\n                       ([--( v( 2), v( 0) )---> # 1 ==== # 0 //\\\\\n                         nth( v( 2), v( 0)) ==== v( 0) \\\\//\n                         --( v( 2), v( 0) )---> # 1 inTree v( 0) //\\\\\n                         --( v( 2), --( v( 2), v( 0) )---> # 1 )---> # 0 ====\n                         v( 0)]) **\n                     AbsEach range( # 0, # 4)\n                       (AbsExistsT\n                          (Path( nth( v( 4), v( 5)), \n                           v( 0), v( 6), # 21, # 13 ++++ v( 5) :: nil) **\n                           AbsAll TreeRecords( v( 6))\n                             ([--( v( 7), v( 0) )---> (# 17 ++++ v( 3)) ====\n                               # 0 //\\\\ nth( v( 7), v( 0)) ==== v( 0) \\\\//\n                               --( v( 7), v( 0) )---> (# 17 ++++ v( 3))\n                               inTree v( 0) //\\\\\n                               --( v( 7),\n                               --( v( 7), v( 0) )---> (# 17 ++++ v( 3))\n                               )---> (# 13 ++++ v( 3)) ==== \n                               v( 0)]) **\n                           AbsAll TreeRecords( v( 0))\n                             (AbsExists range( # 0, # 4)\n                                ([--( v( 1), v( 6) )---> (# 1 ++++ v( 0)) //\\\\\n                                  (nth( v( 4), v( 0)) ==== # 2 \\\\//\n                                   nth( v( 4), v( 0)) ==== # 0) \\\\//\n                                  --( v( 1), v( 6) )---> (# 5 ++++ v( 2)) //\\\\\n                                  (nth( v( 4), v( 0)) ==== # 1 \\\\//\n                                   nth( v( 4), v( 0)) ==== # 0)])) **\n                           AbsAll range( # 0, # 4)\n                             ([(--( v( 0), v( 1) )---> (# 9 ++++ v( 0)) ====\n                                # 0 \\\\//\n                                --( v( 0), v( 1) )---> (# 1 ++++ v( 0))) \\\\//\n                               --( v( 0), v( 1) )---> (# 5 ++++ v( 0))]) **\n                           AbsAll range( # 0, # 4)\n                             ([~~\n                               --( v( 1), v( 6) )---> (# 9 ++++ v( 0)) ====\n                               # 0 //\\\\\n                               (~~\n                                --( v( 1), v( 6) )---> (# 17 ++++ v( 0)) ====\n                                # 0 \\\\// nth( v( 0), v( 2)) ==== v( 1)) \\\\//\n                               (--( v( 1), v( 6) )---> (# 9 ++++ v( 0)) ====\n                                # 0 //\\\\\n                                --( v( 1), v( 6) )---> (# 17 ++++ v( 0)) ====\n                                # 0) //\\\\ ~~ nth( v( 4), v( 0)) ==== v( 6)]) **\n                           SUM( range( # 0, # 4),\n                           ite( --( v( 0), v( 5) )---> (# 9 ++++ v( 0)), \n                           # 1, # 0), # 2) **\n                           (SUM( range( # 0, # 4),\n                            (--( v( 5), v( 3) )---> (# 1 ++++ v( 0)) \\\\//\n                             --( v( 5), v( 3) )---> (# 5 ++++ v( 0))) //\\\\\n                            (ite( nth( v( 3), v( 0)) ==== # 0, # 1, # 0)),\n                            # 1) **\n                            AbsAll range( # 0, # 4)\n                              ([# 0 <<<<\n                                --( v( 1), v( 6) )---> (# 9 ++++ v( 0)) //\\\\\n                                nth( v( 6), v( 0)) ==== # 0 \\\\//\n                                (# 0 <<<< nth( v( 6), v( 0)) \\\\//\n                                 --( v( 1), v( 6) )---> (# 1 ++++ v( 0)) ====\n                                 # 0 //\\\\\n                                 --( v( 1), v( 6) )---> (# 5 ++++ v( 0)) ====\n                                 # 0)]) **\n                            AbsAll range( # 0, # 4)\n                              (AbsAll range( # 0, # 4)\n                                 ([((((--( v( 2), \n                                       v( 7) )---> \n                                       (# 9 ++++ v( 0)) \\\\//\n                                       --( v( 2), \n                                       v( 7) )---> \n                                       (# 1 ++++ v( 0)) ==== \n                                       # 0 //\\\\\n                                       --( v( 2), \n                                       v( 7) )---> \n                                       (# 5 ++++ v( 0)) ==== \n                                       # 0) \\\\//\n                                      ~~\n                                      --( v( 2), v( 7) )---> (# 9 ++++ v( 1))) \\\\//\n                                     nth( v( 5), v( 1)) ==== # 0) \\\\//\n                                    nth( v( 5), v( 1)) ==== # 0) \\\\//\n                                   v( 0) ==== v( 1)] *\\/*\n                                  AbsExists TreeRecords( v( 4))\n                                    ([nth( find( v( 5), v( 0)), # 2) ====\n                                      v( 2)] **\n                                     AbsExists\n                                       TreeRecords( find( v( 5), v( 0)))\n                                       ([nth( find( v( 6), v( 0)), # 2) ====\n                                         v( 1)])))) *\\/*\n                            AbsExists range( # 0, # 4)\n                              ([--( v( 1), v( 6) )---> (# 1 ++++ v( 0)) //\\\\\n                                nth( v( 4), v( 0)) ==== # 2 \\\\//\n                                --( v( 1), v( 6) )---> (# 5 ++++ v( 0)) //\\\\\n                                nth( v( 1), v( 6)) ==== # 1]) **\n                            AbsAll range( # 0, # 4)\n                              ([# 0 ==== nth( v( 4), v( 0))] *\\/*\n                               [--( v( 1), v( 6) )---> (# 9 ++++ v( 0)) ====\n                                # 0] ** [# 0 <<<< nth( v( 4), v( 0))] *\\/*\n                               AbsExists TreeRecords( v( 3))\n                                 ([nth( find( v( 4), v( 0)), # 2) ==== v( 1)]) **\n                               AbsExists TreeRecords( find( v( 0), v( 0)))\n                                 ([# 0 <<<<\n                                   --( v( 2), v( 7)\n                                   )---> (# 1 ++++\n                                          nth( find( v( 4), v( 0)), # 2)) //\\\\\n                                   nth( find( v( 4), v( 0)), # 3) ==== # 2 \\\\//\n                                   # 0 <<<<\n                                   --( v( 2), v( 7)\n                                   )---> (# 5 ++++\n                                          nth( find( v( 4), v( 0)), # 2)) //\\\\\n                                   nth( find( v( 4), v( 0)), # 3) ==== # 1])) *\\/*\n                            AbsAll range( # 0, # 4)\n                              ([--( v( 1), v( 6) )---> (# 9 ++++ v( 0)) ====\n                                # 0 \\\\// nth( v( 4), v( 0)) ==== # 0]))))) **\n                    [!! (assignments_to_do_head) inTree v( 1)] **\n                    [nth( find( !! (assignments_to_do_head), v( 1)), # 1) ====\n                     # 0])))))) nil s.\nProof.\n    intros.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity.\n    eapply simplifyEquiv2. compute. reflexivity. propagateExists. propagateExists.\n    propagateExists.\n    simplifyHyp H. simplifyHyp H. simplifyHyp H. simplifyHyp H.\n    simplifyHyp H. simplifyHyp H. simplifyHyp H. simplifyHyp H. propagateExistsHyp H.\n\n eapply stateImplication.\n        apply H. compute. reflexivity. compute. reflexivity.\n        prove_implication.\n        compute. reflexivity. compute. reflexivity.\n        intros. simpl. eapply emptyRealizeState. simpl. reflexivity. \nAdmitted.\n\nTheorem mergePredicateTheorem3 :\nforall (eee : env) (hhh : heap) (bbb : list Value),\n  length bbb = 12 ->\n  realizeState\n    (([nth( v( 4), !! (varx)) ==== # 0] **\n      ((([!! (ssss) ==== nth( v( 8), # 0)] **\n         [!! (valuex) ==== v( 10)] **\n         [!! (varx) ==== v( 9)] **\n         ((((((AbsEmpty ** AbsEmpty ** AbsEmpty ** AbsEmpty) **\n              ((([!! (varx) <<<< # 4] ** AbsEmpty) **\n                (([!! (valuex) ==== # 1] *\\/* [!! (valuex) ==== # 2]) **\n                 AbsEmpty) **\n                ([v( 0) ==== !! (valuex)] **\n                 AbsAll TreeRecords( v( 8))\n                   ([nth( replacenth( v( 5), !! (varx), !! (valuex)),\n                     nth( find( v( 9), v( 0)), # 2)) ====\n                     nth( find( v( 9), v( 0)), # 3)])) ** AbsEmpty) **\n               AbsAll range( # 0, # 4)\n                 ([nth( v( 5), v( 0)) ==== # 0] *\\/*\n                  [!! (varx) ==== v( 0)] *\\/*\n                  AbsExists TreeRecords( v( 9))\n                    ([nth( find( v( 10), v( 0)), # 2) ==== v( 1)] **\n                     [nth( find( v( 10), v( 0)), # 3) ==== nth( v( 6), v( 1))]))) **\n              AbsEmpty **\n              AbsEach range( # 0, # 4)\n                (AbsExistsT\n                   (Path( nth( list( v( 9)\n                                     :: v( 10)\n                                        :: !! (varx)\n                                           :: !! (valuex) :: v( 13) :: nil),\n                          replacenth( v( 6), !! (varx), !! (valuex))), \n                    v( 0), v( 7), # 21,\n                    # 13 ++++ replacenth( v( 6), !! (varx), !! (valuex))\n                    :: nil) **\n                    AbsAll TreeRecords( v( 7))\n                      ([--( v( 8), v( 0) )---> (# 17 ++++ !! (valuex)) ====\n                        # 0] ** [nth( v( 8), v( 0)) ==== v( 0)] *\\/*\n                       [--( v( 8), v( 0) )---> (# 17 ++++ !! (valuex))\n                        inTree v( 0)] **\n                       [--( v( 8),\n                        --( v( 8), v( 0) )---> (# 17 ++++ !! (valuex))\n                        )---> (# 13 ++++ !! (valuex)) ==== \n                        v( 0)]) **\n                    AbsAll TreeRecords( v( 0))\n                      (AbsExists range( # 0, # 4)\n                         ([--( v( 1),\n                           list( v( 11)\n                                 :: v( 12)\n                                    :: !! (varx)\n                                       :: !! (valuex) :: v( 15) :: nil)\n                           )---> (# 1 ++++ v( 0))] **\n                          ([nth( !! (valuex), v( 0)) ==== # 2] *\\/*\n                           [nth( !! (valuex), v( 0)) ==== # 0]) *\\/*\n                          [--( v( 1),\n                           list( v( 11)\n                                 :: v( 12)\n                                    :: !! (varx)\n                                       :: !! (valuex) :: v( 15) :: nil)\n                           )---> (# 5 ++++ v( 2))] **\n                          ([nth( !! (valuex), v( 0)) ==== # 1] *\\/*\n                           [nth( !! (valuex), v( 0)) ==== # 0]))) **\n                    AbsAll range( # 0, # 4)\n                      (([--( v( 0), v( 1) )---> (# 9 ++++ v( 0)) ==== # 0] *\\/*\n                        [--( v( 0), v( 1) )---> (# 1 ++++ v( 0))]) *\\/*\n                       [--( v( 0), v( 1) )---> (# 5 ++++ v( 0))]) **\n                    AbsAll range( # 0, # 4)\n                      ([# 0 <<<<\n                        --( v( 1), replacenth( v( 7), !! (varx), !! (valuex))\n                        )---> (# 9 ++++ v( 0))] **\n                       ([# 0 <<<<\n                         --( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 17 ++++ v( 0))] *\\/*\n                        [nth( v( 0), v( 2)) ==== v( 1)]) *\\/*\n                       ([--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 9 ++++ v( 0)) ==== \n                         # 0] **\n                        [--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 17 ++++ v( 0)) ==== \n                         # 0]) **\n                       [~~\n                        nth( v( 5), v( 0)) ====\n                        replacenth( v( 7), !! (varx), !! (valuex))]) **\n                    SUM( range( # 0, # 4),\n                    # 0 <<<<\n                    --( v( 0), replacenth( v( 6), !! (varx), !! (valuex))\n                    )---> (# 9 ++++ v( 0)), # 2) **\n                    (SUM( range( # 0, # 4),\n                     (--( replacenth( v( 6), !! (varx), !! (valuex)), \n                      v( 4) )---> (# 1 ++++ v( 0)) \\\\//\n                      --( replacenth( v( 6), !! (varx), !! (valuex)), \n                      v( 4) )---> (# 5 ++++ v( 0))) //\\\\\n                     nth( v( 4), v( 0)) ==== # 0, \n                     # 1) **\n                     AbsAll range( # 0, # 4)\n                       ([# 0 <<<<\n                         --( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 9 ++++ v( 0))] **\n                        [nth( replacenth( v( 7), !! (varx), !! (valuex)),\n                         v( 0)) ==== # 0] *\\/*\n                        [# 0 <<<<\n                         nth( replacenth( v( 7), !! (varx), !! (valuex)),\n                         v( 0))] *\\/*\n                        [--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 1 ++++ v( 0)) ==== \n                         # 0] **\n                        [--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 5 ++++ v( 0)) ==== \n                         # 0]) **\n                     AbsAll range( # 0, # 4)\n                       (AbsAll range( # 0, # 4)\n                          ((((([--( v( 2),\n                                replacenth( v( 8), !! (varx), !! (valuex))\n                                )---> (# 9 ++++ v( 0))] *\\/*\n                               [--( v( 2),\n                                replacenth( v( 8), !! (varx), !! (valuex))\n                                )---> (# 1 ++++ v( 0)) ==== \n                                # 0] **\n                               [--( v( 2),\n                                replacenth( v( 8), !! (varx), !! (valuex))\n                                )---> (# 5 ++++ v( 0)) ==== \n                                # 0]) *\\/*\n                              [~~\n                               --( v( 2),\n                               replacenth( v( 8), !! (varx), !! (valuex))\n                               )---> (# 9 ++++ v( 1))]) *\\/*\n                             [nth( v( 6), v( 1)) ==== # 0]) *\\/*\n                            [v( 0) ==== v( 1)]) *\\/*\n                           AbsExists (AbsConstVal (ListValue nil))\n                             (AbsExists\n                                TreeRecords( find( !! (valuex), v( 0)))\n                                ([nth( find( !! (valuex), v( 1)), # 2) ====\n                                  v( 3)] **\n                                 [nth( find( !! (valuex), v( 0)), # 2) ====\n                                  v( 1)])))) *\\/*\n                     AbsExists range( # 0, # 4)\n                       (([--( v( 1),\n                          replacenth( v( 7), !! (varx), !! (valuex))\n                          )---> (# 1 ++++ v( 0))] **\n                         [nth( v( 5), v( 0)) ==== # 2] *\\/*\n                         [--( v( 1),\n                          replacenth( v( 7), !! (varx), !! (valuex))\n                          )---> (# 5 ++++ v( 0))] **\n                         [nth( v( 1),\n                          replacenth( v( 7), !! (varx), !! (valuex))) ====\n                          # 1]) **\n                        AbsAll range( # 0, # 4)\n                          ([# 0 ==== nth( v( 6), v( 0))] *\\/*\n                           [--( v( 2),\n                            replacenth( v( 8), !! (varx), !! (valuex))\n                            )---> (# 9 ++++ v( 0)) ==== \n                            # 0] ** [# 0 <<<< nth( v( 6), v( 0))] *\\/*\n                           AbsExists (AbsConstVal (ListValue nil))\n                             ([nth( find( !! (valuex), v( 0)), # 2) ====\n                               v( 1)] **\n                              AbsExists TreeRecords( find( v( 1), v( 1)))\n                                ([# 0 <<<<\n                                  --( v( 4),\n                                  replacenth( v( 10), !! (varx), !! (valuex))\n                                  )---> (# 1 ++++\n                                         nth( find( !! (valuex), v( 0)), # 2))] **\n                                 [nth( find( !! (valuex), v( 0)), # 3) ====\n                                  # 2] *\\/*\n                                 [# 0 <<<<\n                                  --( v( 4),\n                                  replacenth( v( 10), !! (varx), !! (valuex))\n                                  )---> (# 5 ++++\n                                         nth( find( !! (valuex), v( 0)), # 2))] **\n                                 [nth( find( !! (valuex), v( 0)), # 3) ====\n                                  # 1])))) *\\/*\n                     AbsAll range( # 0, # 4)\n                       ([--( v( 1),\n                         replacenth( v( 7), !! (varx), !! (valuex))\n                         )---> (# 9 ++++ v( 0)) ==== \n                         # 0] *\\/* [nth( v( 5), v( 0)) ==== # 0]))))) **\n             AbsEmpty ** AbsEmpty) **\n            ([# 0 <<<< v( 7)] *\\/* [v( 6) ==== # 0])) ** \n           [!! (valuex)]) ** [v( 3) ==== # 0]) ** \n         [!! (backtrack) ==== # 0]) ** [!! (stack) ==== !! (ssss)]) **\n       [!! (have_var) ==== # 1]) ** AbsEmpty) **\n     (ARRAY( !! (assignments), # 4, v( 4)) **\n      [nth( find( !! (assignments_to_do_head), v( 2)), # 1) ==== # 0] **\n      [!! (assignments_to_do_head) inTree v( 2)] **\n      AbsAll TreeRecords( v( 2))\n        ([--( v( 3), v( 0) )---> # 1 ==== # 0] **\n         [nth( v( 3), v( 0)) ==== v( 0)] *\\/*\n         [--( v( 3), v( 0) )---> # 1 inTree v( 0)] **\n         [--( v( 3), --( v( 3), v( 0) )---> # 1 )---> # 0 ==== v( 0)]) **\n      AbsAll TreeRecords( v( 8))\n        (AbsAll TreeRecords( nth( find( v( 9), v( 0)), # 2))\n           ([~~\n             nth( find( v( 10), v( 1)), # 2) ====\n             nth( find( nth( find( v( 10), v( 1)), # 2), v( 0)), # 2)])) **\n      AbsAll TreeRecords( v( 8))\n        ([nth( find( v( 9), v( 0)), # 3) ==== # 1] *\\/*\n         [nth( find( v( 9), v( 0)), # 3) ==== # 2]) **\n      AbsAll TreeRecords( v( 8)) ([nth( find( v( 9), v( 0)), # 2) <<<< # 4]) **\n      ARRAY( !! (watches), # 4, v( 5)) **\n      TREE( !! (stack), v( 8), # 4, # 0 :: nil) **\n      TREE( !! (assignments_to_do_head), v( 2), # 4, # 0 :: nil) **\n      TREE( !! (clauses), v( 0), # 21, # 0 :: nil) ** AbsEmpty) **\n     build_equivs\n       ((!! (have_var) :: # 1 :: nil)\n        :: (!! (varx) :: v( 9) :: nil)\n           :: (v( 10) :: v( 0) :: !! (valuex) :: nil)\n              :: (nth( v( 8), # 0) :: !! (stack) :: !! (ssss) :: nil)\n                 :: (nth( v( 4), !! (varx))\n                     :: nth( find( !! (assignments_to_do_head), v( 2)), # 1)\n                        :: v( 3) :: !! (backtrack) :: # 0 :: nil) :: nil))\n    bbb (eee, hhh) ->\n  realizeState\n    (AbsEach range( # 0, # 4)\n       (AbsExistsT\n          (Path( nth( v( 10), v( 6)), v( 0), v( 7), \n           # 21, # 13 ++++ v( 6) :: nil) **\n           AbsAll TreeRecords( v( 7))\n             ([--( v( 8), v( 0) )---> (# 17 ++++ v( 3)) ==== # 0] **\n              [nth( v( 8), v( 0)) ==== v( 0)] *\\/*\n              [--( v( 8), v( 0) )---> (# 17 ++++ v( 3)) inTree v( 0)] **\n              [--( v( 8), --( v( 8), v( 0) )---> (# 17 ++++ v( 3))\n               )---> (# 13 ++++ v( 3)) ==== v( 0)]) **\n           AbsAll TreeRecords( v( 0))\n             (AbsExists range( # 0, # 4)\n                ([--( v( 1), v( 12) )---> (# 1 ++++ v( 0))] **\n                 ([nth( v( 4), v( 0)) ==== # 2] *\\/*\n                  [nth( v( 4), v( 0)) ==== # 0]) *\\/*\n                 [--( v( 1), v( 12) )---> (# 5 ++++ v( 2))] **\n                 ([nth( v( 4), v( 0)) ==== # 1] *\\/*\n                  [nth( v( 4), v( 0)) ==== # 0]))) **\n           AbsAll range( # 0, # 4)\n             (([--( v( 0), v( 1) )---> (# 9 ++++ v( 0)) ==== # 0] *\\/*\n               [--( v( 0), v( 1) )---> (# 1 ++++ v( 0))]) *\\/*\n              [--( v( 0), v( 1) )---> (# 5 ++++ v( 0))]) **\n           AbsAll range( # 0, # 4)\n             ([# 0 <<<< --( v( 1), v( 7) )---> (# 9 ++++ v( 0))] **\n              ([# 0 <<<< --( v( 1), v( 7) )---> (# 17 ++++ v( 0))] *\\/*\n               [nth( v( 0), v( 2)) ==== v( 1)]) *\\/*\n              ([--( v( 1), v( 7) )---> (# 9 ++++ v( 0)) ==== # 0] **\n               [--( v( 1), v( 7) )---> (# 17 ++++ v( 0)) ==== # 0]) **\n              [~~ nth( v( 5), v( 0)) ==== v( 7)]) **\n           SUM( range( # 0, # 4),\n           # 0 <<<< --( v( 0), v( 6) )---> (# 9 ++++ v( 0)), \n           # 2) **\n           (SUM( range( # 0, # 4),\n            (--( v( 6), v( 4) )---> (# 1 ++++ v( 0)) \\\\//\n             --( v( 6), v( 4) )---> (# 5 ++++ v( 0))) //\\\\\n            nth( v( 4), v( 0)) ==== # 0, # 1) **\n            AbsAll range( # 0, # 4)\n              ([# 0 <<<< --( v( 1), v( 7) )---> (# 9 ++++ v( 0))] **\n               [nth( v( 7), v( 0)) ==== # 0] *\\/*\n               [# 0 <<<< nth( v( 7), v( 0))] *\\/*\n               [--( v( 1), v( 7) )---> (# 1 ++++ v( 0)) ==== # 0] **\n               [--( v( 1), v( 7) )---> (# 5 ++++ v( 0)) ==== # 0]) **\n            AbsAll range( # 0, # 4)\n              (AbsAll range( # 0, # 4)\n                 ((((([--( v( 2), v( 8) )---> (# 9 ++++ v( 0))] *\\/*\n                      [--( v( 2), v( 8) )---> (# 1 ++++ v( 0)) ==== # 0] **\n                      [--( v( 2), v( 8) )---> (# 5 ++++ v( 0)) ==== # 0]) *\\/*\n                     [~~ --( v( 2), v( 8) )---> (# 9 ++++ v( 1))]) *\\/*\n                    [nth( v( 6), v( 1)) ==== # 0]) *\\/* \n                   [v( 0) ==== v( 1)]) *\\/*\n                  AbsExists TreeRecords( v( 4))\n                    (AbsExists TreeRecords( find( v( 5), v( 0)))\n                       ([nth( find( v( 6), v( 1)), # 2) ==== v( 3)] **\n                        [nth( find( v( 6), v( 0)), # 2) ==== v( 1)])))) *\\/*\n            AbsExists range( # 0, # 4)\n              (([--( v( 1), v( 7) )---> (# 1 ++++ v( 0))] **\n                [nth( v( 5), v( 0)) ==== # 2] *\\/*\n                [--( v( 1), v( 7) )---> (# 5 ++++ v( 0))] **\n                [nth( v( 1), v( 7)) ==== # 1]) **\n               AbsAll range( # 0, # 4)\n                 ([# 0 ==== nth( v( 6), v( 0))] *\\/*\n                  [--( v( 2), v( 8) )---> (# 9 ++++ v( 0)) ==== # 0] **\n                  [# 0 <<<< nth( v( 6), v( 0))] *\\/*\n                  AbsExists TreeRecords( v( 4))\n                    (AbsExists TreeRecords( find( v( 1), v( 1)))\n                       ([nth( find( v( 6), v( 1)), # 2) ==== v( 2)] **\n                        ([# 0 <<<<\n                          --( v( 4), v( 10)\n                          )---> (# 1 ++++ nth( find( v( 6), v( 0)), # 2))] **\n                         [nth( find( v( 6), v( 0)), # 3) ==== # 2] *\\/*\n                         [# 0 <<<<\n                          --( v( 4), v( 10)\n                          )---> (# 5 ++++ nth( find( v( 6), v( 0)), # 2))] **\n                         [nth( find( v( 6), v( 0)), # 3) ==== # 1]))))) *\\/*\n            AbsAll range( # 0, # 4)\n              ([--( v( 1), v( 7) )---> (# 9 ++++ v( 0)) ==== # 0] *\\/*\n               [nth( v( 5), v( 0)) ==== # 0]))))) bbb \n    (eee, empty_heap).\nProof.\n    admit.\nAdmitted.\n\n\nTheorem mergeMergeTheorem2 :\nmergeStates\n    (AbsExistsT\n       (AbsExistsT\n          (AbsExistsT\n             (AbsExistsT\n                (AbsExistsT\n                   (AbsExistsT\n                      (AbsExistsT\n                         (AbsExistsT\n                            (AbsExistsT\n                               (AbsExistsT\n                                  (AbsExistsT\n                                     ([nth( v( 2), !! (varx)) ==== # 0] **\n                                      AbsExistsT\n                                        (((([!! (ssss) ==== nth( v( 8), # 0)] **\n                                            [!! (valuex) ==== v( 10)] **\n                                            [!! (varx) ==== v( 9)] **\n                                            ((((((TREE( \n                                                 !! (clauses), \n                                                 v( 0), \n                                                 # 21, \n                                                 # 0 :: nil) **\n                                                 TREE( \n                                                 !! \n                                                 (assignments_to_do_head),\n                                                 v( 2), \n                                                 # 4, \n                                                 # 0 :: nil) **\n                                                 TREE( \n                                                 nth( v( 8), # 0), \n                                                 v( 8), \n                                                 # 4, \n                                                 # 0 :: nil) **\n                                                 AbsEmpty **\n                                                 ARRAY( \n                                                 !! (watches), \n                                                 # 4, \n                                                 v( 4))) **\n                                                 ((([!! (varx) <<<< # 4] **\n                                                 AbsAll \n                                                 TreeRecords( v( 8))\n                                                 ([\n                                                 nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 2) <<<< \n                                                 # 4])) **\n                                                 (([!! (valuex) ==== # 1] *\\/*\n                                                 [!! (valuex) ==== # 2]) **\n                                                 AbsAll \n                                                 TreeRecords( v( 8))\n                                                 ([\n                                                 nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 3) ==== \n                                                 # 1] *\\/*\n                                                 [\n                                                 nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 3) ==== \n                                                 # 2])) **\n                                                 ([\n                                                 nth( \n                                                 replacenth( \n                                                 v( 3), \n                                                 !! (varx), \n                                                 v( 0)), \n                                                 !! (varx)) ==== \n                                                 !! (valuex)] **\n                                                 AbsAll \n                                                 TreeRecords( v( 8))\n                                                 ([\n                                                 nth( \n                                                 replacenth( \n                                                 v( 4), \n                                                 !! (varx), \n                                                 v( 1)),\n                                                 nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 2)) ====\n                                                 nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 3)])) **\n                                                 AbsAll \n                                                 TreeRecords( v( 8))\n                                                 ([\n                                                 ~~\n                                                 !! (varx) ====\n                                                 nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 2)]) **\n                                                 AbsAll \n                                                 TreeRecords( v( 8))\n                                                 (AbsAll\n                                                 TreeRecords( \n                                                 nth( \n                                                 find( v( 9), v( 0)), \n                                                 # 1))\n                                                 ([\n                                                 ~~\n                                                 nth( \n                                                 find( v( 10), v( 1)), \n                                                 # 2) ====\n                                                 nth( \n                                                 find( \n                                                 nth( \n                                                 find( v( 10), v( 1)), \n                                                 # 1), \n                                                 v( 0)), \n                                                 # 2)]))) **\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 ([\n                                                 nth( \n                                                 replacenth( \n                                                 v( 4), \n                                                 !! (varx), \n                                                 v( 1)), \n                                                 v( 0)) ==== \n                                                 # 0] *\\/*\n                                                 [!! (varx) ==== v( 0)] *\\/*\n                                                 AbsExists\n                                                 TreeRecords( v( 9))\n                                                 ([\n                                                 nth( \n                                                 find( v( 10), v( 0)), \n                                                 # 2) ==== \n                                                 v( 1)] **\n                                                 [\n                                                 nth( \n                                                 find( v( 10), v( 0)), \n                                                 # 3) ====\n                                                 nth( \n                                                 replacenth( \n                                                 v( 5), \n                                                 !! (varx), \n                                                 v( 2)), \n                                                 v( 1))]))) **\n                                                 AbsAll \n                                                 TreeRecords( v( 2))\n                                                 ([\n                                                 --( v( 3), v( 0) )---> # 1 ====\n                                                 # 0] **\n                                                 [\n                                                 nth( v( 3), v( 0)) ====\n                                                 v( 0)] *\\/*\n                                                 [\n                                                 --( v( 3), v( 0) )---> # 1\n                                                 inTree \n                                                 v( 0)] **\n                                                 [\n                                                 --( \n                                                 v( 3),\n                                                 --( v( 3), v( 0) )---> # 1\n                                                 )---> \n                                                 # 0 ==== \n                                                 v( 0)]) **\n                                                 AbsEach \n                                                 range( # 0, # 4)\n                                                 (AbsExistsT\n                                                 (Path( \n                                                 nth( \n                                                 list( \n                                                 v( 8)\n                                                 :: \n                                                 v( 10)\n                                                 :: \n                                                 !! (varx)\n                                                 :: \n                                                 !! (valuex) :: \n                                                 v( 13) :: nil),\n                                                 replacenth( \n                                                 v( 5), \n                                                 !! (varx), \n                                                 v( 2))), \n                                                 v( 0), \n                                                 v( 6), \n                                                 # 21,\n                                                 # 13 ++++\n                                                 replacenth( \n                                                 v( 5), \n                                                 !! (varx), \n                                                 v( 2)) :: nil) **\n                                                 AbsAll \n                                                 TreeRecords( v( 6))\n                                                 ([\n                                                 --( \n                                                 v( 7), \n                                                 v( 0)\n                                                 )---> \n                                                 (# 17 ++++ v( 3)) ==== \n                                                 # 0] **\n                                                 [\n                                                 nth( v( 7), v( 0)) ====\n                                                 v( 0)] *\\/*\n                                                 [\n                                                 --( \n                                                 v( 7), \n                                                 v( 0)\n                                                 )---> \n                                                 (# 17 ++++ v( 3))\n                                                 inTree \n                                                 v( 0)] **\n                                                 [\n                                                 --( \n                                                 v( 7),\n                                                 --( \n                                                 v( 7), \n                                                 v( 0)\n                                                 )---> \n                                                 (# 17 ++++ v( 3))\n                                                 )---> \n                                                 (# 13 ++++ v( 3)) ==== \n                                                 v( 0)]) **\n                                                 AbsAll \n                                                 TreeRecords( v( 0))\n                                                 (AbsExists \n                                                 range( # 0, # 4)\n                                                 ([\n                                                 --( \n                                                 v( 1),\n                                                 list( \n                                                 v( 10)\n                                                 :: \n                                                 v( 12)\n                                                 :: \n                                                 !! (varx)\n                                                 :: \n                                                 !! (valuex) :: \n                                                 v( 15) :: nil)\n                                                 )---> \n                                                 (# 1 ++++ v( 0))] **\n                                                 ([\n                                                 nth( v( 4), v( 0)) ==== \n                                                 # 2] *\\/*\n                                                 [\n                                                 nth( v( 4), v( 0)) ==== # 0]) *\\/*\n                                                 [\n                                                 --( \n                                                 v( 1),\n                                                 list( \n                                                 v( 10)\n                                                 :: \n                                                 v( 12)\n                                                 :: \n                                                 !! (varx)\n                                                 :: \n                                                 !! (valuex) :: \n                                                 v( 15) :: nil)\n                                                 )---> \n                                                 (# 5 ++++ v( 2))] **\n                                                 ([\n                                                 nth( v( 4), v( 0)) ==== \n                                                 # 1] *\\/*\n                                                 [\n                                                 nth( v( 4), v( 0)) ==== # 0]))) **\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 (([\n                                                 --( \n                                                 v( 0), \n                                                 v( 1) )---> \n                                                 (# 9 ++++ v( 0)) ==== \n                                                 # 0] *\\/*\n                                                 [\n                                                 --( \n                                                 v( 0), \n                                                 v( 1) )---> \n                                                 (# 1 ++++ v( 0))]) *\\/*\n                                                 [\n                                                 --( \n                                                 v( 0), \n                                                 v( 1) )---> \n                                                 (# 5 ++++ v( 0))]) **\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 ([\n                                                 # 0 <<<<\n                                                 --( \n                                                 v( 1),\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))\n                                                 )---> \n                                                 (# 9 ++++ v( 0))] **\n                                                 ([\n                                                 # 0 <<<<\n                                                 --( \n                                                 v( 1),\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))\n                                                 )---> \n                                                 (# 17 ++++ v( 0))] *\\/*\n                                                 [\n                                                 nth( v( 0), v( 2)) ====\n                                                 v( 1)]) *\\/*\n                                                 ([\n                                                 --( \n                                                 v( 1),\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))\n                                                 )---> \n                                                 (# 9 ++++ v( 0)) ==== \n                                                 # 0] **\n                                                 [\n                                                 --( \n                                                 v( 1),\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))\n                                                 )---> \n                                                 (# 17 ++++ v( 0)) ==== \n                                                 # 0]) **\n                                                 [\n                                                 ~~\n                                                 nth( v( 5), v( 0)) ====\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))]) **\n                                                 SUM( \n                                                 range( # 0, # 4),\n                                                 # 0 <<<<\n                                                 --( \n                                                 v( 0),\n                                                 replacenth( \n                                                 v( 5), \n                                                 !! (varx), \n                                                 v( 2))\n                                                 )---> \n                                                 (# 9 ++++ v( 0)), \n                                                 # 2) **\n                                                 (SUM( \n                                                 range( # 0, # 4),\n                                                 (--(\n                                                 replacenth( \n                                                 v( 5), \n                                                 !! (varx), \n                                                 v( 2)), \n                                                 v( 4) )---> \n                                                 (# 1 ++++ v( 0)) \\\\//\n                                                 --(\n                                                 replacenth( \n                                                 v( 5), \n                                                 !! (varx), \n                                                 v( 2)), \n                                                 v( 4) )---> \n                                                 (# 5 ++++ v( 0))) //\\\\\n                                                 nth( v( 4), v( 0)) ==== # 0,\n                                                 # 1) **\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 ([\n                                                 # 0 <<<<\n                                                 --( \n                                                 v( 1),\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))\n                                                 )---> \n                                                 (# 9 ++++ v( 0))] **\n                                                 [\n                                                 nth( \n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3)), \n                                                 v( 0)) ==== \n                                                 # 0] *\\/*\n                                                 [\n                                                 # 0 <<<<\n                                                 nth( \n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3)), \n                                                 v( 0))] *\\/*\n                                                 [\n                                                 --( \n                                                 v( 1),\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))\n                                                 )---> \n                                                 (# 1 ++++ v( 0)) ==== \n                                                 # 0] **\n                                                 [\n                                                 --( \n                                                 v( 1),\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))\n                                                 )---> \n                                                 (# 5 ++++ v( 0)) ==== \n                                                 # 0]) **\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 (AbsAll \n                                                 range( # 0, # 4)\n                                                 ((((([\n                                                 --( \n                                                 v( 2),\n                                                 replacenth( \n                                                 v( 7), \n                                                 !! (varx), \n                                                 v( 4))\n                                                 )---> \n                                                 (# 9 ++++ v( 0))] *\\/*\n                                                 [\n                                                 --( \n                                                 v( 2),\n                                                 replacenth( \n                                                 v( 7), \n                                                 !! (varx), \n                                                 v( 4))\n                                                 )---> \n                                                 (# 1 ++++ v( 0)) ==== \n                                                 # 0] **\n                                                 [\n                                                 --( \n                                                 v( 2),\n                                                 replacenth( \n                                                 v( 7), \n                                                 !! (varx), \n                                                 v( 4))\n                                                 )---> \n                                                 (# 5 ++++ v( 0)) ==== \n                                                 # 0]) *\\/*\n                                                 [\n                                                 ~~\n                                                 --( \n                                                 v( 2),\n                                                 replacenth( \n                                                 v( 7), \n                                                 !! (varx), \n                                                 v( 4))\n                                                 )---> \n                                                 (# 9 ++++ v( 1))]) *\\/*\n                                                 [\n                                                 nth( v( 6), v( 1)) ==== # 0]) *\\/*\n                                                 [v( 0) ==== v( 1)]) *\\/*\n                                                 AbsExists\n                                                 TreeRecords( v( 4))\n                                                 ([\n                                                 nth( \n                                                 find( v( 5), v( 0)), \n                                                 # 2) ==== \n                                                 v( 2)] **\n                                                 AbsExists\n                                                 TreeRecords( \n                                                 find( \n                                                 v( 5), \n                                                 v( 0)))\n                                                 ([\n                                                 nth( \n                                                 find( v( 6), v( 0)), \n                                                 # 2) ==== \n                                                 v( 1)])))) *\\/*\n                                                 AbsExists \n                                                 range( # 0, # 4)\n                                                 ([\n                                                 --( \n                                                 v( 1),\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))\n                                                 )---> \n                                                 (# 1 ++++ v( 0))] **\n                                                 [\n                                                 nth( v( 5), v( 0)) ==== # 2] *\\/*\n                                                 [\n                                                 --( \n                                                 v( 1),\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))\n                                                 )---> \n                                                 (# 5 ++++ v( 0))] **\n                                                 [\n                                                 nth( \n                                                 v( 1),\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))) ==== \n                                                 # 1]) **\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 ([\n                                                 # 0 ==== \n                                                 nth( v( 5), v( 0))] *\\/*\n                                                 [\n                                                 --( \n                                                 v( 1),\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))\n                                                 )---> \n                                                 (# 9 ++++ v( 0)) ==== \n                                                 # 0] **\n                                                 [\n                                                 # 0 <<<< nth( v( 5), v( 0))] *\\/*\n                                                 AbsExists\n                                                 TreeRecords( v( 3))\n                                                 ([\n                                                 nth( \n                                                 find( v( 4), v( 0)), \n                                                 # 2) ==== \n                                                 v( 1)]) **\n                                                 AbsExists\n                                                 TreeRecords( \n                                                 find( \n                                                 v( 0), \n                                                 v( 0)))\n                                                 ([\n                                                 # 0 <<<<\n                                                 --( \n                                                 v( 2),\n                                                 replacenth( \n                                                 v( 7), \n                                                 !! (varx), \n                                                 v( 4))\n                                                 )---> \n                                                 (# 1 ++++\n                                                 nth( \n                                                 find( v( 4), v( 0)), \n                                                 # 2))] **\n                                                 [\n                                                 nth( \n                                                 find( v( 4), v( 0)), \n                                                 # 3) ==== \n                                                 # 2] *\\/*\n                                                 [\n                                                 # 0 <<<<\n                                                 --( \n                                                 v( 2),\n                                                 replacenth( \n                                                 v( 7), \n                                                 !! (varx), \n                                                 v( 4))\n                                                 )---> \n                                                 (# 5 ++++\n                                                 nth( \n                                                 find( v( 4), v( 0)), \n                                                 # 2))] **\n                                                 [\n                                                 nth( \n                                                 find( v( 4), v( 0)), \n                                                 # 3) ==== \n                                                 # 1])) *\\/*\n                                                 AbsAll \n                                                 range( # 0, # 4)\n                                                 ([\n                                                 --( \n                                                 v( 1),\n                                                 replacenth( \n                                                 v( 6), \n                                                 !! (varx), \n                                                 v( 3))\n                                                 )---> \n                                                 (# 9 ++++ v( 0)) ==== \n                                                 # 0] *\\/*\n                                                 [\n                                                 nth( v( 5), v( 0)) ==== # 0]))))) **\n                                                [!! (assignments_to_do_head)\n                                                 inTree \n                                                 v( 2)] **\n                                                [nth( \n                                                 find( \n                                                 !! \n                                                 (assignments_to_do_head),\n                                                 v( 2)), \n                                                 # 1) ==== \n                                                 # 0]) ** \n                                               [# 0 <<<< v( 6)]) **\n                                              [v( 7) ==== # 0]) ** \n                                             [v( 5)]) **\n                                            [!! (backtrack) ==== # 0]) **\n                                           [!! (stack) ==== !! (ssss)]) **\n                                          [!! (have_var) ==== # 1]) **\n                                         ARRAY( !! (assignments), # 4, v( 3)))))))))))))))\n    ([~~ (convertToAbsExp (! iiii <<= ANum var_count))] ** haveVarInvariant)\n    invariant\n.\nProof.\n    (*unfold haveVarInvariant. unfold invariant. unfold invariantCore. \n    unfold invariantCoreNoTail. unfold validTail.\n    unfold validBackPointers. unfold assignmentConsistent.\n    unfold watchVariablesExists. unfold watchVariablesLinkedIffSet.\n    unfold twoWatchVariables. unfold allButOneAssigned. unfold satisfyingAssignmentMade.\n    unfold watchAfterSatisfyingAssignment.\n    unfold watchesUnassigned.\n    unfold haveVarComponent.\n    unfold onlyOneUnassigned. unfold unassignedVariablesAreWatches.\n    unfold mostRecentAssignedIsWatch.\n    unfold coreStructures.\n    eapply breakRightClosureThm. simpl. reflexivity.\n    eapply breakRightClosureThm. simpl. reflexivity.\n    eapply breakRightClosureThm. simpl. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    eapply mergeSimplifyRight. compute. reflexivity.\n    mergePropagateExistsRight.\n    eapply mergePropagateLeft. compute. reflexivity.\n    eapply mergeImplies. eapply ex_intro. split.\n\n    startMerge.\n\n    doMergeStates.\n    eapply DMImplyPredicates1.\n    eapply PESComposeRight. eapply PESComposeLeft. eapply PESComposeLeft. eapply PESComposeRight. eapply PESComposeLeft. eapply PESComposeLeft. eapply PESComposeRight.  eapply PESComposeRight. eapply PESComposeLeft. eapply PESAll.\n    compute. reflexivity.\n    apply mergePredicateTheorem1.\n    eapply DMImplyPredicates1.\n    eapply PESComposeRight. eapply PESComposeLeft. eapply PESComposeLeft. eapply PESComposeRight. eapply PESComposeLeft. eapply PESComposeRight. eapply PESAll.\n    compute. reflexivity.\n    apply mergePredicateTheorem2.\n    eapply DMImplyPredicates1.\n    eapply PESComposeRight. eapply PESComposeLeft. eapply PESComposeLeft. eapply PESComposeRight. eapply PESComposeRight. eapply PESComposeRight. eapply PESEach.\n    compute. reflexivity.\n    apply mergePredicateTheorem3.\n    eapply DMFinish. solveAllPredicates. solveAllPredicates.\n    intros.\n    eapply breakTopClosureThm1. compute. reflexivity.\n    eapply breakTopClosureThm1. compute. reflexivity.\n    apply mergeFinalImplication1. apply H.*)\n    admit.\nAdmitted.\n\nTheorem mergeTheorem2UnfoldNotNull :\n  forall (s : (id -> nat) * (nat -> option nat)) (bindings : list Value),\n  realizeState\n        (([v( 8) ==== # 0] **\n          [v( 6)] **\n          [!! (backtrack) ==== # 0] **\n          [!! (stack) ==== !! (ssss)] ** [!! (have_var) ==== # 1] ** AbsEmpty) **\n         (((TREE( !! (clauses), v( 0), # 21, # 0 :: nil) **\n            TREE( !! (assignments_to_do_head), v( 1), # 4, # 0 :: nil) **\n            TREE( v( 7), v( 2), # 4, # 0 :: nil) **\n            ARRAY( !! (assignments), # 4, v( 3)) **\n            ARRAY( !! (watches), # 4, v( 4))) **\n           (AbsAll TreeRecords( v( 2))\n              ([nth( find( v( 3), v( 0)), # 2) <<<< # 4] **\n               ([nth( find( v( 3), v( 0)), # 3) ==== # 1] *\\/*\n                [nth( find( v( 3), v( 0)), # 3) ==== # 2]) **\n               [nth( v( 4), nth( find( v( 3), v( 0)), # 2)) ====\n                nth( find( v( 3), v( 0)), # 3)] **\n               AbsAll TreeRecords( nth( find( v( 3), v( 0)), # 1))\n                 ([~~\n                   nth( find( v( 4), v( 1)), # 2) ====\n                   nth( find( nth( find( v( 4), v( 1)), # 1), v( 0)), # 2)])) **\n            AbsAll range( # 0, # 4)\n              ([nth( v( 4), v( 0)) ==== # 0] *\\/*\n               AbsExists TreeRecords( v( 3))\n                 ([nth( find( v( 4), v( 0)), # 2) ==== v( 1) //\\\\\n                   nth( find( v( 4), v( 0)), # 3) ==== nth( v( 5), v( 1))]))) **\n           AbsAll TreeRecords( v( 1))\n             ([--( v( 2), v( 0) )---> # 1 ==== # 0 //\\\\\n               nth( v( 2), v( 0)) ==== v( 0) \\\\//\n               --( v( 2), v( 0) )---> # 1 inTree v( 0) //\\\\\n               --( v( 2), --( v( 2), v( 0) )---> # 1 )---> # 0 ==== v( 0)]) **\n           AbsEach range( # 0, # 4)\n             (AbsExistsT\n                (Path( nth( v( 4), v( 5)), v( 0), \n                 v( 6), # 21, # 13 ++++ v( 5) :: nil) **\n                 AbsAll TreeRecords( v( 6))\n                   ([--( v( 7), v( 0) )---> (# 17 ++++ v( 3)) ==== # 0 //\\\\\n                     nth( v( 7), v( 0)) ==== v( 0) \\\\//\n                     --( v( 7), v( 0) )---> (# 17 ++++ v( 3)) inTree v( 0) //\\\\\n                     --( v( 7), --( v( 7), v( 0) )---> (# 17 ++++ v( 3))\n                     )---> (# 13 ++++ v( 3)) ==== \n                     v( 0)]) **\n                 AbsAll TreeRecords( v( 0))\n                   (AbsExists range( # 0, # 4)\n                      ([--( v( 1), v( 6) )---> (# 1 ++++ v( 0)) //\\\\\n                        (nth( v( 4), v( 0)) ==== # 2 \\\\//\n                         nth( v( 4), v( 0)) ==== # 0) \\\\//\n                        --( v( 1), v( 6) )---> (# 5 ++++ v( 2)) //\\\\\n                        (nth( v( 4), v( 0)) ==== # 1 \\\\//\n                         nth( v( 4), v( 0)) ==== # 0)])) **\n                 AbsAll range( # 0, # 4)\n                   ([(--( v( 0), v( 1) )---> (# 9 ++++ v( 0)) ==== # 0 \\\\//\n                      --( v( 0), v( 1) )---> (# 1 ++++ v( 0))) \\\\//\n                     --( v( 0), v( 1) )---> (# 5 ++++ v( 0))]) **\n                 AbsAll range( # 0, # 4)\n                   ([# 0 <<<< --( v( 1), v( 6) )---> (# 9 ++++ v( 0)) //\\\\\n                     (# 0 <<<< --( v( 1), v( 6) )---> (# 17 ++++ v( 0)) \\\\//\n                      nth( v( 0), v( 2)) ==== v( 1)) \\\\//\n                     (--( v( 1), v( 6) )---> (# 9 ++++ v( 0)) ==== # 0 //\\\\\n                      --( v( 1), v( 6) )---> (# 17 ++++ v( 0)) ==== # 0) //\\\\\n                     ~~ nth( v( 4), v( 0)) ==== v( 6)]) **\n                 SUM( range( # 0, # 4),\n                 # 0 <<<< --( v( 0), v( 5) )---> (# 9 ++++ v( 0)), \n                 # 2) **\n                 (SUM( range( # 0, # 4),\n                  (--( v( 5), v( 3) )---> (# 1 ++++ v( 0)) \\\\//\n                   --( v( 5), v( 3) )---> (# 5 ++++ v( 0))) //\\\\\n                  nth( v( 3), v( 0)) ==== # 0, # 1) **\n                  AbsAll range( # 0, # 4)\n                    ([# 0 <<<< --( v( 1), v( 6) )---> (# 9 ++++ v( 0)) //\\\\\n                      nth( v( 6), v( 0)) ==== # 0 \\\\//\n                      (# 0 <<<< nth( v( 6), v( 0)) \\\\//\n                       --( v( 1), v( 6) )---> (# 1 ++++ v( 0)) ==== # 0 //\\\\\n                       --( v( 1), v( 6) )---> (# 5 ++++ v( 0)) ==== # 0)]) **\n                  AbsAll range( # 0, # 4)\n                    (AbsAll range( # 0, # 4)\n                       ([((((--( v( 2), v( 7) )---> (# 9 ++++ v( 0)) \\\\//\n                             --( v( 2), v( 7) )---> (# 1 ++++ v( 0)) ==== # 0 //\\\\\n                             --( v( 2), v( 7) )---> (# 5 ++++ v( 0)) ==== # 0) \\\\//\n                            ~~ --( v( 2), v( 7) )---> (# 9 ++++ v( 1))) \\\\//\n                           nth( v( 5), v( 1)) ==== # 0) \\\\//\n                          nth( v( 5), v( 1)) ==== # 0) \\\\// \n                         v( 0) ==== v( 1)] *\\/*\n                        AbsExists TreeRecords( v( 4))\n                          (AbsExists TreeRecords( find( v( 5), v( 0)))\n                             ([nth( find( v( 6), v( 1)), # 2) ==== v( 3)] **\n                              [nth( find( v( 6), v( 0)), # 2) ==== v( 1)])))) *\\/*\n                  AbsExists range( # 0, # 4)\n                    ([--( v( 1), v( 6) )---> (# 1 ++++ v( 0)) //\\\\\n                      nth( v( 4), v( 0)) ==== # 2 \\\\//\n                      --( v( 1), v( 6) )---> (# 5 ++++ v( 0)) //\\\\\n                      nth( v( 1), v( 6)) ==== # 1] **\n                     AbsAll range( # 0, # 4)\n                       ([# 0 ==== nth( v( 5), v( 0))] *\\/*\n                        [--( v( 2), v( 7) )---> (# 9 ++++ v( 0)) ==== # 0] **\n                        [# 0 <<<< nth( v( 5), v( 0))] *\\/*\n                        AbsExists TreeRecords( v( 4))\n                          (AbsExists TreeRecords( find( v( 1), v( 1)))\n                             ([nth( find( v( 6), v( 1)), # 2) ==== v( 2)] **\n                              [# 0 <<<<\n                               --( v( 4), v( 9)\n                               )---> (# 1 ++++ nth( find( v( 6), v( 0)), # 2)) //\\\\\n                               nth( find( v( 6), v( 0)), # 3) ==== # 2 \\\\//\n                               # 0 <<<<\n                               --( v( 4), v( 9)\n                               )---> (# 5 ++++ nth( find( v( 6), v( 0)), # 2)) //\\\\\n                               nth( find( v( 6), v( 0)), # 3) ==== # 1])))) *\\/*\n                  AbsAll range( # 0, # 4)\n                    ([--( v( 1), v( 6) )---> (# 9 ++++ v( 0)) ==== # 0 \\\\//\n                      nth( v( 4), v( 0)) ==== # 0]))))) **\n          [!! (assignments_to_do_head) inTree v( 1)] **\n          [nth( find( !! (assignments_to_do_head), v( 1)), # 1) ==== # 0]) **\n         ([# 0 <<<< v( 7)] *\\/* [v( 6) ==== # 0])) bindings s\n ->\n     exists v : nat, nth 7 bindings NoValue = NatValue (S v).\nProof.\n    (*intros. Opaque nth.\n    simplifyHyp H.\n    eapply stateAssertionThm in H. compute in H. crunch.\n    remember (nth 7 bindings NoValue). destruct y. destruct n. omega. exists n.\n    reflexivity. inversion H18. inversion H18. inversion H18.*)\n    admit.\nAdmitted.\n\nTheorem stripUpdateVarLeftp\n    : forall left right m,\n      mergeStates (stripUpdateVar left) right m -> mergeStates left right m.\nProof.\n    admit.\nAdmitted.\n\nTheorem breakLeftClosureThmp\n    : forall left right m,\n      mergeStates (breakTopClosure left) right m -> mergeStates left right m.\nProof.\n    admit.\nAdmitted.\n\nTheorem mergePropagateLeftp\n    : forall P1 P2 P,\n      mergeStates (propagateExists nil P1) P2 P -> mergeStates P1 P2 P.\nProof.\n    admit.\nAdmitted.\n\nTheorem mergeSimplifyLeftp\n    : forall P1 P2 P,\n      mergeStates (simplifyState nil P1) P2 P -> mergeStates P1 P2 P.\nProof.\n    admit.\nAdmitted.\n\nTheorem stripUpdateWithLocLeftp\n    : forall P1 P2 P,\n      mergeStates (stripUpdateWithLoc P1) P2 P -> mergeStates P1 P2 P.\nProof.\n    admit.\nAdmitted.\n\nTheorem localizeExistsLeftp\n    : forall P1 P2 P,\n      mergeStates (localizeExists P1 0) P2 P -> mergeStates P1 P2 P.\nProof.\n    admit.\nAdmitted.\n\nLtac compute_left :=\nmatch goal with\n|- mergeStates ?L ?R ?M  =>\n   let l' := eval vm_compute in L in\n   replace L with l' ; [idtac | vm_cast_no_check (refl_equal l')]\nend.\n\nLtac compute_right :=\nmatch goal with\n|- mergeStates ?L ?R ?M  =>\n   let r' := eval vm_compute in R in\n   replace R with r' ; [idtac | vm_cast_no_check (refl_equal r')]\nend.\n\n\nTheorem mergeTheorem2 :\nmergeStates\n    (AbsUpdateLoc\n       (AbsUpdateVar\n          (AbsUpdateVar\n             (AbsMagicWand\n                (AbsUpdateWithLoc\n                   (AbsUpdateWithLoc\n                      (AbsUpdateWithLoc\n                         (AbsUpdateVar\n                            ([!! (backtrack)] **\n                             AbsUpdateVar ([# 1] ** loopInvariant) \n                               have_var # 0) backtrack \n                            # 0) varx !! (stack) ++++ # stack_var_offset)\n                      valuex !! (stack) ++++ # stack_val_offset) \n                   ssss !! (stack) ++++ # next_offset)\n                (AbsExistsT\n                   (AbsExistsT\n                      (AbsExistsT\n                         (AbsExistsT\n                            (AbsExistsT\n                               (v( 0) ++++ # 3 |-> v( 4) **\n                                v( 0) ++++ # 2 |-> v( 3) **\n                                v( 0) ++++ # 1 |-> v( 2) **\n                                v( 0) ++++ # 0 |-> v( 1) **\n                                [!! (stack) ==== v( 0)]))))))) \n             stack !! (ssss)) have_var # 1) !! (assignments) ++++ !! (varx)\n       # 0)\n    ([~~ (convertToAbsExp (! iiii <<= ANum var_count))] ** haveVarInvariant)\n    invariant.\nProof.\n    eapply stripUpdateVarLeftp. compute_left.\n    eapply breakLeftClosureThmp. compute_left.\n    eapply breakLeftClosureThmp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply unfold_merge1.  \n\n    unfoldHeap (AbsQVar 7).\n\n    Transparent nth.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply stripUpdateWithLocLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply mergePropagateLeftp. compute_left.\n    eapply localizeExistsLeftp. compute_left.\n    eapply localizeExistsLeftp. compute_left.\n    eapply localizeExistsLeftp. compute_left.\n    eapply localizeExistsLeftp. compute_left.\n    eapply localizeExistsLeftp. compute_left.\n    eapply localizeExistsLeftp. compute_left.\n    eapply removeMagicWandLeft. compute. reflexivity.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n    eapply mergeSimplifyLeftp. compute_left.\n\n    eapply removeUpdateLocLeft. compute. reflexivity.\n\n    intros.\n    eapply mergeTheorem2Index. apply H.\n\n    apply mergeMergeTheorem2.  Opaque nth.\n\n    compute. intros.\n    eapply mergeTheorem2UnfoldNotNull. apply H.\n    admit.\n\n\n\nAdmitted.\n\n\n\n\nTheorem validRefTheorem1 : forall s n b, id -> nat -> realizeState\n        (AbsExistsT\n           (AbsExistsT\n              (AbsExistsT\n                 (AbsExistsT\n                    (AbsExistsT\n                       (AbsExistsT\n                          (v(0) ++++ #4 |-> v(5) **\n                           v(0) ++++ #3 |-> v(4) **\n                           v(0) ++++ #2 |-> v(3) **\n                           v(0) ++++ #1 |-> v(2) **\n                           v(0) ++++ #0 |-> v(1) **\n                           [!!(todo) ==== v(0)] **\n                           AbsExistsT\n                             ([~~ !!(have_var) ==== #0] **\n                              pushAbsVarState\n                                (pushAbsVarState\n                                   (pushAbsVarState\n                                      (pushAbsVarState\n                                         (pushAbsVarState\n                                            (pushAbsVarState\n                                               (quantifyAbsVarState invariant\n                                                  todo)))))))))))))) nil s -> NatValue n =\n       basicEval AbsPlusId\n         (NatValue (b todo) :: @NatValue unit next_offset :: nil) -> heap_p s n <> None.\nProof.\n admit.\nAdmitted.\n\n\nTheorem validRefTheorem2 : forall s n b, id -> nat -> realizeState\n        (AbsUpdateLoc\n           (AbsExistsT\n              (AbsExistsT\n                 (AbsExistsT\n                    (AbsExistsT\n                       (AbsExistsT\n                          (AbsExistsT\n                             (v(0) ++++ #4 |-> v(5) **\n                              v(0) ++++ #3 |-> v(4) **\n                              v(0) ++++ #2 |-> v(3) **\n                              v(0) ++++ #1 |-> v(2) **\n                              v(0) ++++ #0 |-> v(1) **\n                              [!!(todo) ==== v(0)] **\n                              AbsExistsT\n                                ([~~ !!(have_var) ==== #0] **\n                                 pushAbsVarState\n                                   (pushAbsVarState\n                                      (pushAbsVarState\n                                         (pushAbsVarState\n                                            (pushAbsVarState\n                                               (pushAbsVarState\n                                                  (quantifyAbsVarState\n                                                  invariant \n                                                  todo))))))))))))))\n           !!(todo) ++++ #next_offset !!(assignments_to_do_head)) nil s -> NatValue n =\n       basicEval AbsPlusId\n         (NatValue (b todo) :: @NatValue unit prev_offset :: nil) -> heap_p s n <> None.\nProof.\n    admit.\nAdmitted.\n\n\nTheorem validRefTheorem3 : forall s n b, id -> nat -> realizeState\n        ([~~ !!(assignments_to_do_tail) ==== #0] **\n         AbsUpdateLoc\n           (AbsUpdateLoc\n              (AbsExistsT\n                 (AbsExistsT\n                    (AbsExistsT\n                       (AbsExistsT\n                          (AbsExistsT\n                             (AbsExistsT\n                                (v(0) ++++ #4 |-> v(5) **\n                                 v(0) ++++ #3 |-> v(4) **\n                                 v(0) ++++ #2 |-> v(3) **\n                                 v(0) ++++ #1 |-> v(2) **\n                                 v(0) ++++ #0 |-> v(1) **\n                                 [!!(todo) ==== v(0)] **\n                                 AbsExistsT\n                                   ([~~ !!(have_var) ==== #0] **\n                                    pushAbsVarState\n                                      (pushAbsVarState\n                                         (pushAbsVarState\n                                            (pushAbsVarState\n                                               (pushAbsVarState\n                                                  (pushAbsVarState\n                                                  (quantifyAbsVarState\n                                                  invariant \n                                                  todo))))))))))))))\n              !!(todo) ++++ #next_offset !!(assignments_to_do_head))\n           !!(todo) ++++ #prev_offset #0) nil s -> NatValue n =\n       basicEval AbsPlusId\n         (NatValue (b assignments_to_do_head) :: @NatValue unit prev_offset :: nil) -> heap_p s n <> None.\nProof.\n    admit.\nAdmitted.\n\n\nTheorem mergeTheorem3 : mergeStates\n     (AbsUpdateVar\n        ([!!(assignments_to_do_tail) ==== #0] **\n         AbsUpdateLoc\n           (AbsUpdateLoc\n              (AbsExistsT\n                 (AbsExistsT\n                    (AbsExistsT\n                       (AbsExistsT\n                          (AbsExistsT\n                             (AbsExistsT\n                                (v(0) ++++ #4 |-> v(5) **\n                                 v(0) ++++ #3 |-> v(4) **\n                                 v(0) ++++ #2 |-> v(3) **\n                                 v(0) ++++ #1 |-> v(2) **\n                                 v(0) ++++ #0 |-> v(1) **\n                                 [!!(todo) ==== v(0)] **\n                                 AbsExistsT\n                                   ([~~ !!(have_var) ==== #0] **\n                                    pushAbsVarState\n                                      (pushAbsVarState\n                                         (pushAbsVarState\n                                            (pushAbsVarState\n                                               (pushAbsVarState\n                                                  (pushAbsVarState\n                                                  (quantifyAbsVarState\n                                                  invariant \n                                                  todo))))))))))))))\n              !!(todo) ++++ #next_offset !!(assignments_to_do_head))\n           !!(todo) ++++ #prev_offset #0) assignments_to_do_tail \n        !!(todo))\n     (AbsUpdateLoc\n        ([~~ !!(assignments_to_do_tail) ==== #0] **\n         AbsUpdateLoc\n           (AbsUpdateLoc\n              (AbsExistsT\n                 (AbsExistsT\n                    (AbsExistsT\n                       (AbsExistsT\n                          (AbsExistsT\n                             (AbsExistsT\n                                (v(0) ++++ #4 |-> v(5) **\n                                 v(0) ++++ #3 |-> v(4) **\n                                 v(0) ++++ #2 |-> v(3) **\n                                 v(0) ++++ #1 |-> v(2) **\n                                 v(0) ++++ #0 |-> v(1) **\n                                 [!!(todo) ==== v(0)] **\n                                 AbsExistsT\n                                   ([~~ !!(have_var) ==== #0] **\n                                    pushAbsVarState\n                                      (pushAbsVarState\n                                         (pushAbsVarState\n                                            (pushAbsVarState\n                                               (pushAbsVarState\n                                                  (pushAbsVarState\n                                                  (quantifyAbsVarState\n                                                  invariant \n                                                  todo))))))))))))))\n              !!(todo) ++++ #next_offset !!(assignments_to_do_head))\n           !!(todo) ++++ #prev_offset #0)\n        !!(assignments_to_do_head) ++++ #prev_offset \n        !!(todo)) invariant.\nProof.\n    admit.\nAdmitted.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "kendroe", "repo": "CoqPIE", "sha": "946009445e532dd4632a11a58a64f72a1dd28304", "save_path": "github-repos/coq/kendroe-CoqPIE", "path": "github-repos/coq/kendroe-CoqPIE/CoqPIE-946009445e532dd4632a11a58a64f72a1dd28304/PEDANTIC/SatSolverAux1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.241795524570533}}
{"text": "(** \n Verified SAR-BP: A verified C implementation of SAR backprojection\n with a certified absolute error bound.\n \n Version 1.0 (2015-12-04)\n \n Copyright (C) 2015 Reservoir Labs Inc.\n All rights reserved.\n \n This file is free software. You can redistribute it and/or modify it\n under the terms of the GNU General Public License as published by the\n Free Software Foundation, either version 3 of the License (GNU GPL\n v3), or (at your option) any later version.  A verbatim copy of the\n GNU GPL v3 is included in gpl-3.0.txt.\n \n This file is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See LICENSE for\n more details about the use and redistribution of this file and the\n whole Verified SAR-BP library.\n \n This work is sponsored in part by DARPA MTO as part of the Power\n Efficiency Revolution for Embedded Computing Technologies (PERFECT)\n program (issued by DARPA/CMO under Contract No: HR0011-12-C-0123). The\n views and conclusions contained in this work are those of the authors\n and should not be interpreted as representing the official policies,\n either expressly or implied, of the DARPA or the\n U.S. Government. Distribution Statement \"A\" (Approved for Public\n Release, Distribution Unlimited.)\n \n \n If you are using or modifying Verified SAR-BP in your work, please\n consider citing the following paper:\n \n Tahina Ramananandro, Paul Mountcastle, Benoit Meister and Richard\n Lethin.\n A Unified Coq Framework for Verifying C Programs with Floating-Point\n Computations.\n In CPP (5th ACM/SIGPLAN conference on Certified Programs and Proofs)\n 2016.\n \n \n Verified SAR-BP derives from prior work listed in ACKS along with\n their copyright and licensing information.\n \n Verified SAR-BP requires third-party libraries listed in ACKS along\n with their copyright information.\n*)\n(**\nAuthor: Tahina Ramananandro <ramananandro@reservoir.com>\n\nBounds for medium images. Those bounds have been extracted from the\nDARPA PERFECT suite ( http://hpc.pnl.gov/PERFECT/ )\n*)\n\nRequire Import ZArith RAux.\nRequire Flocq.Core.Fcore_Raux.\nDefinition abs_data_border: R := (715249/268435456)%R .\nDefinition abs_data_min: R := (12006781/36028797018963968)%R .\nDefinition abs_data_max: R := (4211015/4194304)%R .\nDefinition abs_data_dist: R := (5771023/33554432)%R .\n\nDefinition platpos_x_min: R := (14455539/2048)%R .\nDefinition platpos_x_max: R := (14481547/2048)%R. \n\nDefinition platpos_y_min: R := (0)%R .\nDefinition platpos_y_max: R := (6940197/16384)%R. \n\nDefinition platpos_z_min: R := (14481547/2048)%R .\nDefinition platpos_z_max: R := (14481547/2048)%R. \n\nDefinition dxdy := Eval compute in (4503599627370496 * / Fcore_Raux.Z2R (2 ^ 54))%R. \nDefinition dR := Eval compute in (4503599627370496 * / Fcore_Raux.Z2R (2 ^ 57))%R.\nDefinition N_PULSES := (1024)%nat .\nDefinition N_RANGE := (1024)%Z .\nDefinition N_RANGE_UPSAMPLED := (8192)%Z .\nDefinition BP_NPIX_Y := (1024)%nat .\nDefinition BP_NPIX_X := (1024)%nat .\nDefinition ku := Eval compute in (7368997658362958 * / Fcore_Raux.Z2R (2 ^ 45))%R.\n(*\nDefinition z0 := Eval compute in (0 * / Fcore_Raux.Z2R (2 ^ 1074))%R. \n*)\nDefinition z0_low := 0%R.\nDefinition z0_high := 0%R.\nDefinition R0 := Eval compute in (5427189394702336 * / Fcore_Raux.Z2R (2 ^ 39))%R.\n", "meta": {"author": "wuweh", "repo": "vsarbp", "sha": "8e4ca028ec8a73eb7f2fd27892a69971384cada5", "save_path": "github-repos/coq/wuweh-vsarbp", "path": "github-repos/coq/wuweh-vsarbp/vsarbp-8e4ca028ec8a73eb7f2fd27892a69971384cada5/sar_sizes/medium/SARBounds.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.24163472009736578}}
{"text": "From Coq Require Import RelationClasses.\nFrom Mon Require Import SPropBase.\nSet Warnings \"-notation-overridden,-ambiguous-paths\".\nFrom mathcomp Require Import all_ssreflect.\nSet Warnings \"notation-overridden,ambiguous-paths\".\nFrom Relational Require Import OrderEnrichedCategory OrderEnrichedRelativeMonadExamples.\nFrom Crypt Require Import ChoiceAsOrd OrderEnrichedRelativeAdjunctions OrderEnrichedRelativeAdjunctionsExamples TransformingLaxMorph SubDistr Theta_dens LaxFunctorsAndTransf UniversalFreeMap FreeProbProg StateTransformingLaxMorph LaxComp.\n\nImport SPropNotations.\n\n(*\nIn this file we state transform this morphism\nθdens : Frp → Sdistr\ninto\nStT(θdens) : StT(Frp) → StT(SDistr)\n\nWe also subsequently make its domain free\nθFstd : FrStP → StT(Frp) → stT(SDistr)\n*)\n\nSection GetDomainAndCodomain.\n  Context {C D1 D2 : ord_category} {J1 : ord_functor C D1} {J12 : ord_functor D1 D2} {J2 : ord_functor C D2}\n          {phi : natIso J2 (ord_functor_comp J1 J12)} (psi := ni_inv phi)\n          {M1 : ord_relativeMonad J1} {M2: ord_relativeMonad J2}.\n\n\n  Definition rlmm_domain (smTheta :  relativeLaxMonadMorphism J12 phi M1 M2)\n    : ord_relativeMonad J1\n    := M1.\n  Definition rlmm_codomain (smTheta :  relativeLaxMonadMorphism J12 phi M1 M2)\n    : ord_relativeMonad J2\n    := M2.\n\nEnd GetDomainAndCodomain.\n\n\nSection StT_unaryThetaDens.\n  Context {probE : Type -> Type}. (*an interface for probabilistic events*)\n  Context {choice_type : Type}\n          {chElement : choice_type -> choiceType}.\n  Context (prob_handler : forall (T:choiceType),\n    probE T -> SDistr T).\n\n  Context {S : choiceType}.\n\n  (*we wish to transform this monad morphism*)\n  Let θdens_filled :=\n  @unary_theta_dens.\n\n  (*domain and codomain*)\n  Let Frp := rlmm_domain θdens_filled.\n  (* Eval hnf in rlmm_codomain θdens_filled. (*SDistr*) *)\n\n\n\n  (*state transform the domain*)\n\n  Program Definition unaryStateTingAdj :\n  leftAdjunctionSituation choice_incl\n         (ord_functor_comp (unaryTimesS1 S) choice_incl)\n         (ToTheS S) :=\n    mkNatIso _ _ _ _ _ _ _.\n  Next Obligation.\n    move=> [A X]. unshelve econstructor.\n      simpl. move=> g a s. exact (g (a,s)).\n      move=> g g'. simpl in g. simpl in g'.\n      move=> Hg. unfold extract_ord. simpl.\n      move=> a.\n      unfold extract_ord in Hg. simpl in Hg.\n      apply boolp.funext. move=> s.\n      apply Hg.\n  Defined.\n  Next Obligation.\n    move=> [A X]. unshelve econstructor.\n      simpl. move=> g. move=> [a s]. exact (g a s).\n      simpl. move => g g'.\n      unfold extract_ord. simpl.\n      move=> Hg. move=> [a s].\n      specialize (Hg a). destruct Hg.\n      reflexivity.\n  Defined.\n  Next Obligation.\n    move=> [A X] [A' X']. move=> [fA fX]. simpl in *.\n    apply sig_eq. simpl. apply boolp.funext. move=> g.\n    apply boolp.funext. move=> a'. apply boolp.funext. move=> s.\n    simpl.\n    rewrite /OrderEnrichedRelativeAdjunctionsExamples.ToTheS_obligation_1.\n    reflexivity.\n  Qed.\n  Next Obligation.\n    move=> [A X].\n    apply sig_eq. simpl. apply boolp.funext. move=> g.\n    simpl. apply boolp.funext. move=> a. reflexivity.\n  Qed.\n  Next Obligation.\n    move=> [A X].\n    apply sig_eq. simpl. apply boolp.funext. move=> g.\n    simpl. apply boolp.funext. move=> [a s]. reflexivity.\n  Qed.\n\n  Program Definition unaryStateBeta' :\n  lnatTrans (lord_functor_comp\n                      (strict2laxFunc (ToTheS S))\n                      (strict2laxFunc (ord_functor_id TypeCat)))\n            (lord_functor_comp\n                      (strict2laxFunc (ord_functor_id TypeCat))\n                      (strict2laxFunc (ToTheS S))) :=\n    mkLnatTrans _ _.\n\n  Program Definition stT_thetaDens_adj :=\n  Transformed_lmla θdens_filled unaryStateTingAdj unaryStateTingAdj unaryStateBeta' _ _.\n  Next Obligation.\n    move=> A Y. move=> g.\n    apply boolp.funext. move=> [ a s]. cbv. reflexivity.\n  Qed.\n\n  Definition stT_thetaDens :=  rlmm_from_lmla stT_thetaDens_adj.\n\nEnd StT_unaryThetaDens.\n\n\n\nSection MakeTheDomainFree.\n  Context {probE : Type -> Type}. (*an interface for probabilistic events*)\n  Context {choice_type : Type}\n          {chElement : choice_type -> choiceType}.\n  Context {prob_handler : forall (T:choiceType),\n    probE T -> SDistr T}.\n\n  Context {S : choiceType}.\n\n  Let unaryIntState_filled :=\n  @unaryIntState S.\n\n  Let stT_thetaDens_filled :=\n  @stT_thetaDens S.\n\n\n\n  (*an auxiliary morphism to connect the dots*)\n  Program Definition bridgg :\n  relativeMonadMorphism (ord_functor_id _) (trivialChi)\n     (rlmm_codomain unaryIntState_filled)\n     (rlmm_domain stT_thetaDens_filled) :=\n    mkRelMonMorph _ _ _ _ _ _ _.\n\n  (*now... unaryIntState_filled ; bridgg = ppre*)\n  Let ppre := rlmm_comp _ _ _ _ _ _ _ (unaryIntState_filled) bridgg.\n\n  (*and then ppre ; stT_thetaDens_filled*)\n  Definition thetaFstd := rlmm_comp _ _ _ _ _ _ _ ppre stT_thetaDens_filled.\n\n\nEnd MakeTheDomainFree.\n", "meta": {"author": "SSProve", "repo": "ssprove", "sha": "5dce3e2eae195fc466035e314ef4463d956c9c6a", "save_path": "github-repos/coq/SSProve-ssprove", "path": "github-repos/coq/SSProve-ssprove/ssprove-5dce3e2eae195fc466035e314ef4463d956c9c6a/theories/Crypt/rhl_semantics/state_prob/StateTransfThetaDens.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.241611906339603}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*                 Xavier Leroy, INRIA Paris                           *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Instruction selection for 64-bit integer operations *)\n\nRequire Import Coqlib.\nRequire Import Compopts.\nRequire Import AST Integers Floats.\nRequire Import Op CminorSel.\nRequire Import SelectOp SplitLong.\n\nLocal Open Scope cminorsel_scope.\nLocal Open Scope string_scope.\n\nSection SELECT.\n\nContext {hf: helper_functions}.\n\nDefinition longconst (n: int64) : expr :=\n  if Archi.splitlong then SplitLong.longconst n else Eop (Olongconst n) Enil.\n\nDefinition is_longconst (e: expr) :=\n  if Archi.splitlong then SplitLong.is_longconst e else\n  match e with\n  | Eop (Olongconst n) Enil => Some n\n  | _ => None\n  end.\n\nDefinition intoflong (e: expr) :=\n  if Archi.splitlong then SplitLong.intoflong e else\n  match is_longconst e with\n  | Some n => Eop (Ointconst (Int.repr (Int64.unsigned n))) Enil\n  | None =>  Eop Olowlong (e ::: Enil)\n  end.\n\nDefinition longofint (e: expr) :=\n  if Archi.splitlong then SplitLong.longofint e else\n  match is_intconst e with\n  | Some n => longconst (Int64.repr (Int.signed n))\n  | None =>  Eop Ocast32signed (e ::: Enil)\n  end.\n\nDefinition longofintu (e: expr) :=\n  if Archi.splitlong then SplitLong.longofintu e else\n  match is_intconst e with\n  | Some n => longconst (Int64.repr (Int.unsigned n))\n  | None =>  Eop Ocast32unsigned (e ::: Enil)\n  end.\n\n(** Original definition:\n<<\nNondetfunction notl (e: expr) :=\n  if Archi.splitlong then SplitLong.notl e else\n  match e with\n  | Eop (Olongconst n) Enil => longconst (Int64.not n)\n  | Eop Onotl (t1:::Enil) => t1\n  | _ => Eop Onotl (e:::Enil)\n  end.\n>>\n*)\n\nInductive notl_cases: forall (e: expr), Type :=\n  | notl_case1: forall n, notl_cases (Eop (Olongconst n) Enil)\n  | notl_case2: forall t1, notl_cases (Eop Onotl (t1:::Enil))\n  | notl_default: forall (e: expr), notl_cases e.\n\nDefinition notl_match (e: expr) :=\n  match e as zz1 return notl_cases zz1 with\n  | Eop (Olongconst n) Enil => notl_case1 n\n  | Eop Onotl (t1:::Enil) => notl_case2 t1\n  | e => notl_default e\n  end.\n\nDefinition notl (e: expr) :=\n if Archi.splitlong then SplitLong.notl e else match notl_match e with\n  | notl_case1 n => (* Eop (Olongconst n) Enil *) \n      longconst (Int64.not n)\n  | notl_case2 t1 => (* Eop Onotl (t1:::Enil) *) \n      t1\n  | notl_default e =>\n      Eop Onotl (e:::Enil)\n  end.\n\n\n(** Original definition:\n<<\nNondetfunction andlimm (n1: int64) (e2: expr) := \n  if Int64.eq n1 Int64.zero then longconst Int64.zero else\n  if Int64.eq n1 Int64.mone then e2 else\n  match e2 with\n  | Eop (Olongconst n2) Enil =>\n      longconst (Int64.and n1 n2)\n  | Eop (Oandlimm n2) (t2:::Enil) =>\n      Eop (Oandlimm (Int64.and n1 n2)) (t2:::Enil)\n  | _ =>\n      Eop (Oandlimm n1) (e2:::Enil)\n  end.\n>>\n*)\n\nInductive andlimm_cases: forall (e2: expr), Type :=\n  | andlimm_case1: forall n2, andlimm_cases (Eop (Olongconst n2) Enil)\n  | andlimm_case2: forall n2 t2, andlimm_cases (Eop (Oandlimm n2) (t2:::Enil))\n  | andlimm_default: forall (e2: expr), andlimm_cases e2.\n\nDefinition andlimm_match (e2: expr) :=\n  match e2 as zz1 return andlimm_cases zz1 with\n  | Eop (Olongconst n2) Enil => andlimm_case1 n2\n  | Eop (Oandlimm n2) (t2:::Enil) => andlimm_case2 n2 t2\n  | e2 => andlimm_default e2\n  end.\n\nDefinition andlimm (n1: int64) (e2: expr) :=\n if Int64.eq n1 Int64.zero then longconst Int64.zero else if Int64.eq n1 Int64.mone then e2 else match andlimm_match e2 with\n  | andlimm_case1 n2 => (* Eop (Olongconst n2) Enil *) \n      longconst (Int64.and n1 n2)\n  | andlimm_case2 n2 t2 => (* Eop (Oandlimm n2) (t2:::Enil) *) \n      Eop (Oandlimm (Int64.and n1 n2)) (t2:::Enil)\n  | andlimm_default e2 =>\n      Eop (Oandlimm n1) (e2:::Enil)\n  end.\n\n\n(** Original definition:\n<<\nNondetfunction andl (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.andl e1 e2 else\n  match e1, e2 with\n  | Eop (Olongconst n1) Enil, t2 => andlimm n1 t2\n  | t1, Eop (Olongconst n2) Enil => andlimm n2 t1\n  | _, _ => Eop Oandl (e1:::e2:::Enil)\n  end.\n>>\n*)\n\nInductive andl_cases: forall (e1: expr) (e2: expr), Type :=\n  | andl_case1: forall n1 t2, andl_cases (Eop (Olongconst n1) Enil) (t2)\n  | andl_case2: forall t1 n2, andl_cases (t1) (Eop (Olongconst n2) Enil)\n  | andl_default: forall (e1: expr) (e2: expr), andl_cases e1 e2.\n\nDefinition andl_match (e1: expr) (e2: expr) :=\n  match e1 as zz1, e2 as zz2 return andl_cases zz1 zz2 with\n  | Eop (Olongconst n1) Enil, t2 => andl_case1 n1 t2\n  | t1, Eop (Olongconst n2) Enil => andl_case2 t1 n2\n  | e1, e2 => andl_default e1 e2\n  end.\n\nDefinition andl (e1: expr) (e2: expr) :=\n if Archi.splitlong then SplitLong.andl e1 e2 else match andl_match e1 e2 with\n  | andl_case1 n1 t2 => (* Eop (Olongconst n1) Enil, t2 *) \n      andlimm n1 t2\n  | andl_case2 t1 n2 => (* t1, Eop (Olongconst n2) Enil *) \n      andlimm n2 t1\n  | andl_default e1 e2 =>\n      Eop Oandl (e1:::e2:::Enil)\n  end.\n\n\n(** Original definition:\n<<\nNondetfunction orlimm (n1: int64) (e2: expr) :=\n  if Int64.eq n1 Int64.zero then e2 else\n  if Int64.eq n1 Int64.mone then longconst Int64.mone else\n  match e2 with\n  | Eop (Olongconst n2) Enil => longconst (Int64.or n1 n2)\n  | Eop (Oorlimm n2) (t2:::Enil) => Eop (Oorlimm (Int64.or n1 n2)) (t2:::Enil)\n  | _ => Eop (Oorlimm n1) (e2:::Enil)\n  end.\n>>\n*)\n\nInductive orlimm_cases: forall (e2: expr), Type :=\n  | orlimm_case1: forall n2, orlimm_cases (Eop (Olongconst n2) Enil)\n  | orlimm_case2: forall n2 t2, orlimm_cases (Eop (Oorlimm n2) (t2:::Enil))\n  | orlimm_default: forall (e2: expr), orlimm_cases e2.\n\nDefinition orlimm_match (e2: expr) :=\n  match e2 as zz1 return orlimm_cases zz1 with\n  | Eop (Olongconst n2) Enil => orlimm_case1 n2\n  | Eop (Oorlimm n2) (t2:::Enil) => orlimm_case2 n2 t2\n  | e2 => orlimm_default e2\n  end.\n\nDefinition orlimm (n1: int64) (e2: expr) :=\n if Int64.eq n1 Int64.zero then e2 else if Int64.eq n1 Int64.mone then longconst Int64.mone else match orlimm_match e2 with\n  | orlimm_case1 n2 => (* Eop (Olongconst n2) Enil *) \n      longconst (Int64.or n1 n2)\n  | orlimm_case2 n2 t2 => (* Eop (Oorlimm n2) (t2:::Enil) *) \n      Eop (Oorlimm (Int64.or n1 n2)) (t2:::Enil)\n  | orlimm_default e2 =>\n      Eop (Oorlimm n1) (e2:::Enil)\n  end.\n\n\n(** Original definition:\n<<\nNondetfunction orl (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.orl e1 e2 else\n  match e1, e2 with\n  | Eop (Olongconst n1) Enil, t2 => orlimm n1 t2\n  | t1, Eop (Olongconst n2) Enil => orlimm n2 t1\n  | Eop (Oshllimm n1) (t1:::Enil), Eop (Oshrluimm n2) (t2:::Enil) =>\n      if Int.eq (Int.add n1 n2) Int64.iwordsize' && same_expr_pure t1 t2\n      then Eop (Ororlimm n2) (t1:::Enil)\n      else Eop Oorl (e1:::e2:::Enil)\n  | Eop (Oshrluimm n2) (t2:::Enil), Eop (Oshllimm n1) (t1:::Enil) =>\n      if Int.eq (Int.add n1 n2) Int64.iwordsize' && same_expr_pure t1 t2\n      then Eop (Ororlimm n2) (t1:::Enil)\n      else Eop Oorl (e1:::e2:::Enil)\n  | _, _ =>\n      Eop Oorl (e1:::e2:::Enil)\n  end.\n>>\n*)\n\nInductive orl_cases: forall (e1: expr) (e2: expr), Type :=\n  | orl_case1: forall n1 t2, orl_cases (Eop (Olongconst n1) Enil) (t2)\n  | orl_case2: forall t1 n2, orl_cases (t1) (Eop (Olongconst n2) Enil)\n  | orl_case3: forall n1 t1 n2 t2, orl_cases (Eop (Oshllimm n1) (t1:::Enil)) (Eop (Oshrluimm n2) (t2:::Enil))\n  | orl_case4: forall n2 t2 n1 t1, orl_cases (Eop (Oshrluimm n2) (t2:::Enil)) (Eop (Oshllimm n1) (t1:::Enil))\n  | orl_default: forall (e1: expr) (e2: expr), orl_cases e1 e2.\n\nDefinition orl_match (e1: expr) (e2: expr) :=\n  match e1 as zz1, e2 as zz2 return orl_cases zz1 zz2 with\n  | Eop (Olongconst n1) Enil, t2 => orl_case1 n1 t2\n  | t1, Eop (Olongconst n2) Enil => orl_case2 t1 n2\n  | Eop (Oshllimm n1) (t1:::Enil), Eop (Oshrluimm n2) (t2:::Enil) => orl_case3 n1 t1 n2 t2\n  | Eop (Oshrluimm n2) (t2:::Enil), Eop (Oshllimm n1) (t1:::Enil) => orl_case4 n2 t2 n1 t1\n  | e1, e2 => orl_default e1 e2\n  end.\n\nDefinition orl (e1: expr) (e2: expr) :=\n if Archi.splitlong then SplitLong.orl e1 e2 else match orl_match e1 e2 with\n  | orl_case1 n1 t2 => (* Eop (Olongconst n1) Enil, t2 *) \n      orlimm n1 t2\n  | orl_case2 t1 n2 => (* t1, Eop (Olongconst n2) Enil *) \n      orlimm n2 t1\n  | orl_case3 n1 t1 n2 t2 => (* Eop (Oshllimm n1) (t1:::Enil), Eop (Oshrluimm n2) (t2:::Enil) *) \n      if Int.eq (Int.add n1 n2) Int64.iwordsize' && same_expr_pure t1 t2 then Eop (Ororlimm n2) (t1:::Enil) else Eop Oorl (e1:::e2:::Enil)\n  | orl_case4 n2 t2 n1 t1 => (* Eop (Oshrluimm n2) (t2:::Enil), Eop (Oshllimm n1) (t1:::Enil) *) \n      if Int.eq (Int.add n1 n2) Int64.iwordsize' && same_expr_pure t1 t2 then Eop (Ororlimm n2) (t1:::Enil) else Eop Oorl (e1:::e2:::Enil)\n  | orl_default e1 e2 =>\n      Eop Oorl (e1:::e2:::Enil)\n  end.\n\n\n(** Original definition:\n<<\nNondetfunction xorlimm (n1: int64) (e2: expr) :=\n  if Int64.eq n1 Int64.zero then e2 else\n  if Int64.eq n1 Int64.mone then notl e2 else\n  match e2 with\n  | Eop (Olongconst n2) Enil => longconst (Int64.xor n1 n2)\n  | Eop (Oxorlimm n2) (t2:::Enil) => Eop (Oxorlimm (Int64.xor n1 n2)) (t2:::Enil)\n  | Eop Onotl (t2:::Enil) => Eop (Oxorlimm (Int64.not n1)) (t2:::Enil)\n  | _ => Eop (Oxorlimm n1) (e2:::Enil)\n  end.\n>>\n*)\n\nInductive xorlimm_cases: forall (e2: expr), Type :=\n  | xorlimm_case1: forall n2, xorlimm_cases (Eop (Olongconst n2) Enil)\n  | xorlimm_case2: forall n2 t2, xorlimm_cases (Eop (Oxorlimm n2) (t2:::Enil))\n  | xorlimm_case3: forall t2, xorlimm_cases (Eop Onotl (t2:::Enil))\n  | xorlimm_default: forall (e2: expr), xorlimm_cases e2.\n\nDefinition xorlimm_match (e2: expr) :=\n  match e2 as zz1 return xorlimm_cases zz1 with\n  | Eop (Olongconst n2) Enil => xorlimm_case1 n2\n  | Eop (Oxorlimm n2) (t2:::Enil) => xorlimm_case2 n2 t2\n  | Eop Onotl (t2:::Enil) => xorlimm_case3 t2\n  | e2 => xorlimm_default e2\n  end.\n\nDefinition xorlimm (n1: int64) (e2: expr) :=\n if Int64.eq n1 Int64.zero then e2 else if Int64.eq n1 Int64.mone then notl e2 else match xorlimm_match e2 with\n  | xorlimm_case1 n2 => (* Eop (Olongconst n2) Enil *) \n      longconst (Int64.xor n1 n2)\n  | xorlimm_case2 n2 t2 => (* Eop (Oxorlimm n2) (t2:::Enil) *) \n      Eop (Oxorlimm (Int64.xor n1 n2)) (t2:::Enil)\n  | xorlimm_case3 t2 => (* Eop Onotl (t2:::Enil) *) \n      Eop (Oxorlimm (Int64.not n1)) (t2:::Enil)\n  | xorlimm_default e2 =>\n      Eop (Oxorlimm n1) (e2:::Enil)\n  end.\n\n\n(** Original definition:\n<<\nNondetfunction xorl (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.xorl e1 e2 else\n  match e1, e2 with\n  | Eop (Olongconst n1) Enil, t2 => xorlimm n1 t2\n  | t1, Eop (Olongconst n2) Enil => xorlimm n2 t1\n  | _, _ => Eop Oxorl (e1:::e2:::Enil)\n  end.\n>>\n*)\n\nInductive xorl_cases: forall (e1: expr) (e2: expr), Type :=\n  | xorl_case1: forall n1 t2, xorl_cases (Eop (Olongconst n1) Enil) (t2)\n  | xorl_case2: forall t1 n2, xorl_cases (t1) (Eop (Olongconst n2) Enil)\n  | xorl_default: forall (e1: expr) (e2: expr), xorl_cases e1 e2.\n\nDefinition xorl_match (e1: expr) (e2: expr) :=\n  match e1 as zz1, e2 as zz2 return xorl_cases zz1 zz2 with\n  | Eop (Olongconst n1) Enil, t2 => xorl_case1 n1 t2\n  | t1, Eop (Olongconst n2) Enil => xorl_case2 t1 n2\n  | e1, e2 => xorl_default e1 e2\n  end.\n\nDefinition xorl (e1: expr) (e2: expr) :=\n if Archi.splitlong then SplitLong.xorl e1 e2 else match xorl_match e1 e2 with\n  | xorl_case1 n1 t2 => (* Eop (Olongconst n1) Enil, t2 *) \n      xorlimm n1 t2\n  | xorl_case2 t1 n2 => (* t1, Eop (Olongconst n2) Enil *) \n      xorlimm n2 t1\n  | xorl_default e1 e2 =>\n      Eop Oxorl (e1:::e2:::Enil)\n  end.\n\n\n(** Original definition:\n<<\nNondetfunction shllimm (e1: expr) (n: int) :=\n  if Archi.splitlong then SplitLong.shllimm e1 n else\n  if Int.eq n Int.zero then e1 else\n  if negb (Int.ltu n Int64.iwordsize') then\n    Eop Oshll (e1:::Eop (Ointconst n) Enil:::Enil)\n  else\n    match e1 with\n    | Eop (Olongconst n1) Enil =>\n        Eop (Olongconst(Int64.shl' n1 n)) Enil\n    | Eop (Oshllimm n1) (t1:::Enil) =>\n        if Int.ltu (Int.add n n1) Int64.iwordsize'\n        then Eop (Oshllimm (Int.add n n1)) (t1:::Enil)\n        else Eop (Oshllimm n) (e1:::Enil)\n    | Eop (Oleal (Aindexed n1)) (t1:::Enil) =>\n        if shift_is_scale n\n        then Eop (Oleal (Ascaled (Int64.unsigned (Int64.shl' Int64.one n))\n                                 (Int64.unsigned (Int64.shl' (Int64.repr n1) n)))) (t1:::Enil)\n        else Eop (Oshllimm n) (e1:::Enil)\n    | _ =>\n        if shift_is_scale n\n        then Eop (Oleal (Ascaled (Int64.unsigned (Int64.shl' Int64.one n)) 0)) (e1:::Enil)\n        else Eop (Oshllimm n) (e1:::Enil)\n    end.\n>>\n*)\n\nInductive shllimm_cases: forall (e1: expr) , Type :=\n  | shllimm_case1: forall n1, shllimm_cases (Eop (Olongconst n1) Enil)\n  | shllimm_case2: forall n1 t1, shllimm_cases (Eop (Oshllimm n1) (t1:::Enil))\n  | shllimm_case3: forall n1 t1, shllimm_cases (Eop (Oleal (Aindexed n1)) (t1:::Enil))\n  | shllimm_default: forall (e1: expr) , shllimm_cases e1.\n\nDefinition shllimm_match (e1: expr)  :=\n  match e1 as zz1 return shllimm_cases zz1 with\n  | Eop (Olongconst n1) Enil => shllimm_case1 n1\n  | Eop (Oshllimm n1) (t1:::Enil) => shllimm_case2 n1 t1\n  | Eop (Oleal (Aindexed n1)) (t1:::Enil) => shllimm_case3 n1 t1\n  | e1 => shllimm_default e1\n  end.\n\nDefinition shllimm (e1: expr) (n: int) :=\n if Archi.splitlong then SplitLong.shllimm e1 n else if Int.eq n Int.zero then e1 else if negb (Int.ltu n Int64.iwordsize') then Eop Oshll (e1:::Eop (Ointconst n) Enil:::Enil) else match shllimm_match e1 with\n  | shllimm_case1 n1 => (* Eop (Olongconst n1) Enil *) \n      Eop (Olongconst(Int64.shl' n1 n)) Enil\n  | shllimm_case2 n1 t1 => (* Eop (Oshllimm n1) (t1:::Enil) *) \n      if Int.ltu (Int.add n n1) Int64.iwordsize' then Eop (Oshllimm (Int.add n n1)) (t1:::Enil) else Eop (Oshllimm n) (e1:::Enil)\n  | shllimm_case3 n1 t1 => (* Eop (Oleal (Aindexed n1)) (t1:::Enil) *) \n      if shift_is_scale n then Eop (Oleal (Ascaled (Int64.unsigned (Int64.shl' Int64.one n)) (Int64.unsigned (Int64.shl' (Int64.repr n1) n)))) (t1:::Enil) else Eop (Oshllimm n) (e1:::Enil)\n  | shllimm_default e1 =>\n      if shift_is_scale n then Eop (Oleal (Ascaled (Int64.unsigned (Int64.shl' Int64.one n)) 0)) (e1:::Enil) else Eop (Oshllimm n) (e1:::Enil)\n  end.\n\n\n(** Original definition:\n<<\nNondetfunction shrluimm (e1: expr) (n: int) :=\n  if Archi.splitlong then SplitLong.shrluimm e1 n else\n  if Int.eq n Int.zero then e1 else\n  if negb (Int.ltu n Int64.iwordsize') then\n    Eop Oshrlu (e1:::Eop (Ointconst n) Enil:::Enil)\n  else\n    match e1 with\n    | Eop (Olongconst n1) Enil =>\n        Eop (Olongconst(Int64.shru' n1 n)) Enil\n    | Eop (Oshrluimm n1) (t1:::Enil) =>\n        if Int.ltu (Int.add n n1) Int64.iwordsize'\n        then Eop (Oshrluimm (Int.add n n1)) (t1:::Enil)\n        else Eop (Oshrluimm n) (e1:::Enil)\n    | _ =>\n        Eop (Oshrluimm n) (e1:::Enil)\n    end.\n>>\n*)\n\nInductive shrluimm_cases: forall (e1: expr) , Type :=\n  | shrluimm_case1: forall n1, shrluimm_cases (Eop (Olongconst n1) Enil)\n  | shrluimm_case2: forall n1 t1, shrluimm_cases (Eop (Oshrluimm n1) (t1:::Enil))\n  | shrluimm_default: forall (e1: expr) , shrluimm_cases e1.\n\nDefinition shrluimm_match (e1: expr)  :=\n  match e1 as zz1 return shrluimm_cases zz1 with\n  | Eop (Olongconst n1) Enil => shrluimm_case1 n1\n  | Eop (Oshrluimm n1) (t1:::Enil) => shrluimm_case2 n1 t1\n  | e1 => shrluimm_default e1\n  end.\n\nDefinition shrluimm (e1: expr) (n: int) :=\n if Archi.splitlong then SplitLong.shrluimm e1 n else if Int.eq n Int.zero then e1 else if negb (Int.ltu n Int64.iwordsize') then Eop Oshrlu (e1:::Eop (Ointconst n) Enil:::Enil) else match shrluimm_match e1 with\n  | shrluimm_case1 n1 => (* Eop (Olongconst n1) Enil *) \n      Eop (Olongconst(Int64.shru' n1 n)) Enil\n  | shrluimm_case2 n1 t1 => (* Eop (Oshrluimm n1) (t1:::Enil) *) \n      if Int.ltu (Int.add n n1) Int64.iwordsize' then Eop (Oshrluimm (Int.add n n1)) (t1:::Enil) else Eop (Oshrluimm n) (e1:::Enil)\n  | shrluimm_default e1 =>\n      Eop (Oshrluimm n) (e1:::Enil)\n  end.\n\n\n(** Original definition:\n<<\nNondetfunction shrlimm (e1: expr) (n: int) :=\n  if Archi.splitlong then SplitLong.shrlimm e1 n else\n  if Int.eq n Int.zero then e1 else\n  if negb (Int.ltu n Int64.iwordsize') then\n    Eop Oshrl (e1:::Eop (Ointconst n) Enil:::Enil)\n  else\n  match e1 with\n  | Eop (Olongconst n1) Enil =>\n      Eop (Olongconst(Int64.shr' n1 n)) Enil\n  | Eop (Oshrlimm n1) (t1:::Enil) =>\n      if Int.ltu (Int.add n n1) Int64.iwordsize'\n      then Eop (Oshrlimm (Int.add n n1)) (t1:::Enil)\n      else Eop (Oshrlimm n) (e1:::Enil)\n  | _ =>\n      Eop (Oshrlimm n) (e1:::Enil)\n  end.\n>>\n*)\n\nInductive shrlimm_cases: forall (e1: expr) , Type :=\n  | shrlimm_case1: forall n1, shrlimm_cases (Eop (Olongconst n1) Enil)\n  | shrlimm_case2: forall n1 t1, shrlimm_cases (Eop (Oshrlimm n1) (t1:::Enil))\n  | shrlimm_default: forall (e1: expr) , shrlimm_cases e1.\n\nDefinition shrlimm_match (e1: expr)  :=\n  match e1 as zz1 return shrlimm_cases zz1 with\n  | Eop (Olongconst n1) Enil => shrlimm_case1 n1\n  | Eop (Oshrlimm n1) (t1:::Enil) => shrlimm_case2 n1 t1\n  | e1 => shrlimm_default e1\n  end.\n\nDefinition shrlimm (e1: expr) (n: int) :=\n if Archi.splitlong then SplitLong.shrlimm e1 n else if Int.eq n Int.zero then e1 else if negb (Int.ltu n Int64.iwordsize') then Eop Oshrl (e1:::Eop (Ointconst n) Enil:::Enil) else match shrlimm_match e1 with\n  | shrlimm_case1 n1 => (* Eop (Olongconst n1) Enil *) \n      Eop (Olongconst(Int64.shr' n1 n)) Enil\n  | shrlimm_case2 n1 t1 => (* Eop (Oshrlimm n1) (t1:::Enil) *) \n      if Int.ltu (Int.add n n1) Int64.iwordsize' then Eop (Oshrlimm (Int.add n n1)) (t1:::Enil) else Eop (Oshrlimm n) (e1:::Enil)\n  | shrlimm_default e1 =>\n      Eop (Oshrlimm n) (e1:::Enil)\n  end.\n\n\nDefinition shll (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.shll e1 e2 else\n  match is_intconst e2 with\n  | Some n2 => shllimm e1 n2\n  | None => Eop Oshll (e1:::e2:::Enil)\n  end.\n\nDefinition shrl (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.shrl e1 e2 else\n  match is_intconst e2 with\n  | Some n2 => shrlimm e1 n2\n  | None => Eop Oshrl (e1:::e2:::Enil)\n  end.\n\nDefinition shrlu (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.shrlu e1 e2 else\n  match is_intconst e2 with\n  | Some n2 => shrluimm e1 n2\n  | _ => Eop Oshrlu (e1:::e2:::Enil)\n  end.\n\n(** Original definition:\n<<\nNondetfunction addlimm (n: int64) (e: expr) :=\n  if Int64.eq n Int64.zero then e else\n  match e with\n  | Eop (Olongconst m) Enil => longconst (Int64.add n m)\n  | Eop (Oleal addr) args   => Eop (Oleal (offset_addressing_total addr (Int64.signed n))) args\n  | _                       => Eop (Oleal (Aindexed (Int64.signed n))) (e ::: Enil)\n  end.\n>>\n*)\n\nInductive addlimm_cases: forall (e: expr), Type :=\n  | addlimm_case1: forall m, addlimm_cases (Eop (Olongconst m) Enil)\n  | addlimm_case2: forall addr args, addlimm_cases (Eop (Oleal addr) args)\n  | addlimm_default: forall (e: expr), addlimm_cases e.\n\nDefinition addlimm_match (e: expr) :=\n  match e as zz1 return addlimm_cases zz1 with\n  | Eop (Olongconst m) Enil => addlimm_case1 m\n  | Eop (Oleal addr) args => addlimm_case2 addr args\n  | e => addlimm_default e\n  end.\n\nDefinition addlimm (n: int64) (e: expr) :=\n if Int64.eq n Int64.zero then e else match addlimm_match e with\n  | addlimm_case1 m => (* Eop (Olongconst m) Enil *) \n      longconst (Int64.add n m)\n  | addlimm_case2 addr args => (* Eop (Oleal addr) args *) \n      Eop (Oleal (offset_addressing_total addr (Int64.signed n))) args\n  | addlimm_default e =>\n      Eop (Oleal (Aindexed (Int64.signed n))) (e ::: Enil)\n  end.\n\n\n(** Original definition:\n<<\nNondetfunction addl (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.addl e1 e2 else\n  match e1, e2 with\n  | Eop (Olongconst n1) Enil, t2 => addlimm n1 t2\n  | t1, Eop (Olongconst n2) Enil => addlimm n2 t1\n  | Eop (Oleal (Aindexed n1)) (t1:::Enil), Eop (Oleal (Aindexed n2)) (t2:::Enil) =>\n      Eop (Oleal (Aindexed2 (n1 + n2))) (t1:::t2:::Enil)\n  | Eop (Oleal (Aindexed n1)) (t1:::Enil), Eop (Oleal (Ascaled sc n2)) (t2:::Enil) =>\n      Eop (Oleal (Aindexed2scaled sc (n1 + n2))) (t1:::t2:::Enil)\n  | Eop (Oleal (Ascaled sc n1)) (t1:::Enil), Eop (Oleal (Aindexed n2)) (t2:::Enil) =>\n      Eop (Oleal (Aindexed2scaled sc (n1 + n2))) (t2:::t1:::Enil)\n  | Eop (Oleal (Ascaled sc n)) (t1:::Enil), t2 =>\n      Eop (Oleal (Aindexed2scaled sc n)) (t2:::t1:::Enil)\n  | t1, Eop (Oleal (Ascaled sc n)) (t2:::Enil) =>\n      Eop (Oleal (Aindexed2scaled sc n)) (t1:::t2:::Enil)\n  | Eop (Oleal (Aindexed n)) (t1:::Enil), t2 =>\n      Eop (Oleal (Aindexed2 n)) (t1:::t2:::Enil)\n  | t1, Eop (Oleal (Aindexed n)) (t2:::Enil) =>\n      Eop (Oleal (Aindexed2 n)) (t1:::t2:::Enil)\n  | _, _ =>\n      Eop (Oleal (Aindexed2 0)) (e1:::e2:::Enil)\n  end.\n>>\n*)\n\nInductive addl_cases: forall (e1: expr) (e2: expr), Type :=\n  | addl_case1: forall n1 t2, addl_cases (Eop (Olongconst n1) Enil) (t2)\n  | addl_case2: forall t1 n2, addl_cases (t1) (Eop (Olongconst n2) Enil)\n  | addl_case3: forall n1 t1 n2 t2, addl_cases (Eop (Oleal (Aindexed n1)) (t1:::Enil)) (Eop (Oleal (Aindexed n2)) (t2:::Enil))\n  | addl_case4: forall n1 t1 sc n2 t2, addl_cases (Eop (Oleal (Aindexed n1)) (t1:::Enil)) (Eop (Oleal (Ascaled sc n2)) (t2:::Enil))\n  | addl_case5: forall sc n1 t1 n2 t2, addl_cases (Eop (Oleal (Ascaled sc n1)) (t1:::Enil)) (Eop (Oleal (Aindexed n2)) (t2:::Enil))\n  | addl_case6: forall sc n t1 t2, addl_cases (Eop (Oleal (Ascaled sc n)) (t1:::Enil)) (t2)\n  | addl_case7: forall t1 sc n t2, addl_cases (t1) (Eop (Oleal (Ascaled sc n)) (t2:::Enil))\n  | addl_case8: forall n t1 t2, addl_cases (Eop (Oleal (Aindexed n)) (t1:::Enil)) (t2)\n  | addl_case9: forall t1 n t2, addl_cases (t1) (Eop (Oleal (Aindexed n)) (t2:::Enil))\n  | addl_default: forall (e1: expr) (e2: expr), addl_cases e1 e2.\n\nDefinition addl_match (e1: expr) (e2: expr) :=\n  match e1 as zz1, e2 as zz2 return addl_cases zz1 zz2 with\n  | Eop (Olongconst n1) Enil, t2 => addl_case1 n1 t2\n  | t1, Eop (Olongconst n2) Enil => addl_case2 t1 n2\n  | Eop (Oleal (Aindexed n1)) (t1:::Enil), Eop (Oleal (Aindexed n2)) (t2:::Enil) => addl_case3 n1 t1 n2 t2\n  | Eop (Oleal (Aindexed n1)) (t1:::Enil), Eop (Oleal (Ascaled sc n2)) (t2:::Enil) => addl_case4 n1 t1 sc n2 t2\n  | Eop (Oleal (Ascaled sc n1)) (t1:::Enil), Eop (Oleal (Aindexed n2)) (t2:::Enil) => addl_case5 sc n1 t1 n2 t2\n  | Eop (Oleal (Ascaled sc n)) (t1:::Enil), t2 => addl_case6 sc n t1 t2\n  | t1, Eop (Oleal (Ascaled sc n)) (t2:::Enil) => addl_case7 t1 sc n t2\n  | Eop (Oleal (Aindexed n)) (t1:::Enil), t2 => addl_case8 n t1 t2\n  | t1, Eop (Oleal (Aindexed n)) (t2:::Enil) => addl_case9 t1 n t2\n  | e1, e2 => addl_default e1 e2\n  end.\n\nDefinition addl (e1: expr) (e2: expr) :=\n if Archi.splitlong then SplitLong.addl e1 e2 else match addl_match e1 e2 with\n  | addl_case1 n1 t2 => (* Eop (Olongconst n1) Enil, t2 *) \n      addlimm n1 t2\n  | addl_case2 t1 n2 => (* t1, Eop (Olongconst n2) Enil *) \n      addlimm n2 t1\n  | addl_case3 n1 t1 n2 t2 => (* Eop (Oleal (Aindexed n1)) (t1:::Enil), Eop (Oleal (Aindexed n2)) (t2:::Enil) *) \n      Eop (Oleal (Aindexed2 (n1 + n2))) (t1:::t2:::Enil)\n  | addl_case4 n1 t1 sc n2 t2 => (* Eop (Oleal (Aindexed n1)) (t1:::Enil), Eop (Oleal (Ascaled sc n2)) (t2:::Enil) *) \n      Eop (Oleal (Aindexed2scaled sc (n1 + n2))) (t1:::t2:::Enil)\n  | addl_case5 sc n1 t1 n2 t2 => (* Eop (Oleal (Ascaled sc n1)) (t1:::Enil), Eop (Oleal (Aindexed n2)) (t2:::Enil) *) \n      Eop (Oleal (Aindexed2scaled sc (n1 + n2))) (t2:::t1:::Enil)\n  | addl_case6 sc n t1 t2 => (* Eop (Oleal (Ascaled sc n)) (t1:::Enil), t2 *) \n      Eop (Oleal (Aindexed2scaled sc n)) (t2:::t1:::Enil)\n  | addl_case7 t1 sc n t2 => (* t1, Eop (Oleal (Ascaled sc n)) (t2:::Enil) *) \n      Eop (Oleal (Aindexed2scaled sc n)) (t1:::t2:::Enil)\n  | addl_case8 n t1 t2 => (* Eop (Oleal (Aindexed n)) (t1:::Enil), t2 *) \n      Eop (Oleal (Aindexed2 n)) (t1:::t2:::Enil)\n  | addl_case9 t1 n t2 => (* t1, Eop (Oleal (Aindexed n)) (t2:::Enil) *) \n      Eop (Oleal (Aindexed2 n)) (t1:::t2:::Enil)\n  | addl_default e1 e2 =>\n      Eop (Oleal (Aindexed2 0)) (e1:::e2:::Enil)\n  end.\n\n\nDefinition negl (e: expr) :=\n  if Archi.splitlong then SplitLong.negl e else\n  match is_longconst e with\n  | Some n => longconst (Int64.neg n)\n  | None =>  Eop Onegl (e ::: Enil)\n  end.\n\n(** Original definition:\n<<\nNondetfunction subl (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.subl e1 e2 else\n  match e1, e2 with\n  | t1, Eop (Olongconst n2) Enil => addlimm (Int64.neg n2) t1\n  | Eop (Oleal (Aindexed n1)) (t1:::Enil), Eop (Oleal (Aindexed n2)) (t2:::Enil) =>\n      addlimm (Int64.repr (n1 - n2)) (Eop Osubl (t1:::t2:::Enil))\n  | Eop (Oleal (Aindexed n1)) (t1:::Enil), t2 =>\n      addlimm (Int64.repr n1) (Eop Osubl (t1:::t2:::Enil))\n  | t1, Eop (Oleal (Aindexed n2)) (t2:::Enil) =>\n      addlimm (Int64.repr (- n2)) (Eop Osubl (t1:::t2:::Enil))\n  | _, _ =>\n      Eop Osubl (e1:::e2:::Enil)\n  end.\n>>\n*)\n\nInductive subl_cases: forall (e1: expr) (e2: expr), Type :=\n  | subl_case1: forall t1 n2, subl_cases (t1) (Eop (Olongconst n2) Enil)\n  | subl_case2: forall n1 t1 n2 t2, subl_cases (Eop (Oleal (Aindexed n1)) (t1:::Enil)) (Eop (Oleal (Aindexed n2)) (t2:::Enil))\n  | subl_case3: forall n1 t1 t2, subl_cases (Eop (Oleal (Aindexed n1)) (t1:::Enil)) (t2)\n  | subl_case4: forall t1 n2 t2, subl_cases (t1) (Eop (Oleal (Aindexed n2)) (t2:::Enil))\n  | subl_default: forall (e1: expr) (e2: expr), subl_cases e1 e2.\n\nDefinition subl_match (e1: expr) (e2: expr) :=\n  match e1 as zz1, e2 as zz2 return subl_cases zz1 zz2 with\n  | t1, Eop (Olongconst n2) Enil => subl_case1 t1 n2\n  | Eop (Oleal (Aindexed n1)) (t1:::Enil), Eop (Oleal (Aindexed n2)) (t2:::Enil) => subl_case2 n1 t1 n2 t2\n  | Eop (Oleal (Aindexed n1)) (t1:::Enil), t2 => subl_case3 n1 t1 t2\n  | t1, Eop (Oleal (Aindexed n2)) (t2:::Enil) => subl_case4 t1 n2 t2\n  | e1, e2 => subl_default e1 e2\n  end.\n\nDefinition subl (e1: expr) (e2: expr) :=\n if Archi.splitlong then SplitLong.subl e1 e2 else match subl_match e1 e2 with\n  | subl_case1 t1 n2 => (* t1, Eop (Olongconst n2) Enil *) \n      addlimm (Int64.neg n2) t1\n  | subl_case2 n1 t1 n2 t2 => (* Eop (Oleal (Aindexed n1)) (t1:::Enil), Eop (Oleal (Aindexed n2)) (t2:::Enil) *) \n      addlimm (Int64.repr (n1 - n2)) (Eop Osubl (t1:::t2:::Enil))\n  | subl_case3 n1 t1 t2 => (* Eop (Oleal (Aindexed n1)) (t1:::Enil), t2 *) \n      addlimm (Int64.repr n1) (Eop Osubl (t1:::t2:::Enil))\n  | subl_case4 t1 n2 t2 => (* t1, Eop (Oleal (Aindexed n2)) (t2:::Enil) *) \n      addlimm (Int64.repr (- n2)) (Eop Osubl (t1:::t2:::Enil))\n  | subl_default e1 e2 =>\n      Eop Osubl (e1:::e2:::Enil)\n  end.\n\n\nDefinition mullimm_base (n1: int64) (e2: expr) :=\n  match Int64.one_bits' n1 with\n  | i :: nil =>\n      shllimm e2 i\n  | i :: j :: nil =>\n      Elet e2 (addl (shllimm (Eletvar 0) i) (shllimm (Eletvar 0) j))\n  | _ =>\n      Eop (Omullimm n1) (e2:::Enil)\n  end.\n\n(** Original definition:\n<<\nNondetfunction mullimm (n1: int64) (e2: expr) :=\n  if Archi.splitlong then SplitLong.mullimm n1 e2\n  else if Int64.eq n1 Int64.zero then longconst Int64.zero\n  else if Int64.eq n1 Int64.one then e2\n  else match e2 with\n  | Eop (Olongconst n2) Enil => longconst (Int64.mul n1 n2)\n  | Eop (Oleal (Aindexed n2)) (t2:::Enil) => addlimm (Int64.mul n1 (Int64.repr n2)) (mullimm_base n1 t2)\n  | _ => mullimm_base n1 e2\n  end.\n>>\n*)\n\nInductive mullimm_cases: forall (e2: expr), Type :=\n  | mullimm_case1: forall n2, mullimm_cases (Eop (Olongconst n2) Enil)\n  | mullimm_case2: forall n2 t2, mullimm_cases (Eop (Oleal (Aindexed n2)) (t2:::Enil))\n  | mullimm_default: forall (e2: expr), mullimm_cases e2.\n\nDefinition mullimm_match (e2: expr) :=\n  match e2 as zz1 return mullimm_cases zz1 with\n  | Eop (Olongconst n2) Enil => mullimm_case1 n2\n  | Eop (Oleal (Aindexed n2)) (t2:::Enil) => mullimm_case2 n2 t2\n  | e2 => mullimm_default e2\n  end.\n\nDefinition mullimm (n1: int64) (e2: expr) :=\n if Archi.splitlong then SplitLong.mullimm n1 e2 else if Int64.eq n1 Int64.zero then longconst Int64.zero else if Int64.eq n1 Int64.one then e2 else match mullimm_match e2 with\n  | mullimm_case1 n2 => (* Eop (Olongconst n2) Enil *) \n      longconst (Int64.mul n1 n2)\n  | mullimm_case2 n2 t2 => (* Eop (Oleal (Aindexed n2)) (t2:::Enil) *) \n      addlimm (Int64.mul n1 (Int64.repr n2)) (mullimm_base n1 t2)\n  | mullimm_default e2 =>\n      mullimm_base n1 e2\n  end.\n\n\n(** Original definition:\n<<\nNondetfunction mull (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.mull e1 e2 else\n  match e1, e2 with\n  | Eop (Olongconst n1) Enil, t2 => mullimm n1 t2\n  | t1, Eop (Olongconst n2) Enil => mullimm n2 t1\n  | _, _ => Eop Omull (e1:::e2:::Enil)\n  end.\n>>\n*)\n\nInductive mull_cases: forall (e1: expr) (e2: expr), Type :=\n  | mull_case1: forall n1 t2, mull_cases (Eop (Olongconst n1) Enil) (t2)\n  | mull_case2: forall t1 n2, mull_cases (t1) (Eop (Olongconst n2) Enil)\n  | mull_default: forall (e1: expr) (e2: expr), mull_cases e1 e2.\n\nDefinition mull_match (e1: expr) (e2: expr) :=\n  match e1 as zz1, e2 as zz2 return mull_cases zz1 zz2 with\n  | Eop (Olongconst n1) Enil, t2 => mull_case1 n1 t2\n  | t1, Eop (Olongconst n2) Enil => mull_case2 t1 n2\n  | e1, e2 => mull_default e1 e2\n  end.\n\nDefinition mull (e1: expr) (e2: expr) :=\n if Archi.splitlong then SplitLong.mull e1 e2 else match mull_match e1 e2 with\n  | mull_case1 n1 t2 => (* Eop (Olongconst n1) Enil, t2 *) \n      mullimm n1 t2\n  | mull_case2 t1 n2 => (* t1, Eop (Olongconst n2) Enil *) \n      mullimm n2 t1\n  | mull_default e1 e2 =>\n      Eop Omull (e1:::e2:::Enil)\n  end.\n\n\nDefinition mullhu (e1: expr) (n2: int64) :=\n  if Archi.splitlong then SplitLong.mullhu e1 n2 else\n  Eop Omullhu (e1 ::: longconst n2 ::: Enil).\n\nDefinition mullhs (e1: expr) (n2: int64) :=\n  if Archi.splitlong then SplitLong.mullhs e1 n2 else\n  Eop Omullhs (e1 ::: longconst n2 ::: Enil).\n\nDefinition shrxlimm (e: expr) (n: int) :=\n  if Archi.splitlong then SplitLong.shrxlimm e n else\n  if Int.eq n Int.zero then e else Eop (Oshrxlimm n) (e ::: Enil).\n\nDefinition divlu_base (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.divlu_base e1 e2 else Eop Odivlu (e1:::e2:::Enil).\nDefinition modlu_base (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.modlu_base e1 e2 else Eop Omodlu (e1:::e2:::Enil).\nDefinition divls_base (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.divls_base e1 e2 else Eop Odivl (e1:::e2:::Enil).\nDefinition modls_base (e1: expr) (e2: expr) :=\n  if Archi.splitlong then SplitLong.modls_base e1 e2 else Eop Omodl (e1:::e2:::Enil).\n\nDefinition cmplu (c: comparison) (e1 e2: expr) :=\n  if Archi.splitlong then SplitLong.cmplu c e1 e2 else\n  match is_longconst e1, is_longconst e2 with\n  | Some n1, Some n2 =>\n      Eop (Ointconst (if Int64.cmpu c n1 n2 then Int.one else Int.zero)) Enil\n  | Some n1, None => Eop (Ocmp (Ccompluimm (swap_comparison c) n1)) (e2:::Enil)\n  | None, Some n2 => Eop (Ocmp (Ccompluimm c n2)) (e1:::Enil)\n  | None, None => Eop (Ocmp (Ccomplu c)) (e1:::e2:::Enil)\n  end.\n\nDefinition cmpl (c: comparison) (e1 e2: expr) :=\n  if Archi.splitlong then SplitLong.cmpl c e1 e2 else\n  match is_longconst e1, is_longconst e2 with\n  | Some n1, Some n2 =>\n      Eop (Ointconst (if Int64.cmp c n1 n2 then Int.one else Int.zero)) Enil\n  | Some n1, None => Eop (Ocmp (Ccomplimm (swap_comparison c) n1)) (e2:::Enil)\n  | None, Some n2 => Eop (Ocmp (Ccomplimm c n2)) (e1:::Enil)\n  | None, None => Eop (Ocmp (Ccompl c)) (e1:::e2:::Enil)\n  end.\n\nDefinition longoffloat (e: expr) :=\n  if Archi.splitlong then SplitLong.longoffloat e else \n  Eop Olongoffloat (e:::Enil).\n\nDefinition floatoflong (e: expr) := \n  if Archi.splitlong then SplitLong.floatoflong e else \n  Eop Ofloatoflong (e:::Enil).\n\nDefinition longofsingle (e: expr) := \n  if Archi.splitlong then SplitLong.longofsingle e else \n  Eop Olongofsingle (e:::Enil).\n\nDefinition singleoflong (e: expr) := \n  if Archi.splitlong then SplitLong.singleoflong e else \n  Eop Osingleoflong (e:::Enil).\n\nEnd SELECT.\n", "meta": {"author": "Aurele-Barriere", "repo": "JIThm", "sha": "ad3ae5a3d6759a070195815e321df1b372d982b9", "save_path": "github-repos/coq/Aurele-Barriere-JIThm", "path": "github-repos/coq/Aurele-Barriere-JIThm/JIThm-ad3ae5a3d6759a070195815e321df1b372d982b9/coqjit/compcert_coq/x86/SelectLong.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213070736461, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.24152627202049473}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.CorrectnessBaseTypes.\nRequire Import Fiat.Common.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ValidReflective.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Fiat.Parsers.MinimalParseOfParse.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nSection recursive_descent_parser.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char}\n          {G : pregrammar' Char}.\n\n  Context (Hvalid : is_true (grammar_rvalid G)).\n\n  Let predata := @rdp_list_predata _ G.\n  Local Existing Instance predata.\n\n  Let rdata' : @parser_removal_dataT' _ G predata := rdp_list_rdata'.\n  Local Existing Instance rdata'.\n\n  Context {splitdata : @split_dataT Char _ _}.\n  Let data : boolean_parser_dataT :=\n    {| split_data := splitdata |}.\n  Context {splitdata_correct : @boolean_parser_completeness_dataT' _ _ _ G data}.\n\n  Local Instance optsplitdata : @split_dataT Char _ _\n    := { split_string_for_production p_idx str offset len\n         := match to_production p_idx with\n              | nil => 0::nil\n              | _::nil => len::nil\n              | it::_\n                => match it with\n                     | Terminal _ => 1::nil\n                     | _ => @split_string_for_production _ _ _ splitdata p_idx str offset len\n                   end\n            end }.\n  Let optdata : boolean_parser_dataT :=\n    {| split_data := optsplitdata |}.\n\n  Local Arguments minus !_ !_.\n  Local Arguments min !_ !_.\n\n  Local Instance optsplitdata_correct : @boolean_parser_completeness_dataT' _ _ _ G optdata\n    := { split_string_for_production_complete := _ }.\n  Proof.\n    pose proof (@split_string_for_production_complete _ _ _ _ _ splitdata_correct) as H.\n    repeat (let x := fresh in intro x; specialize (H x)).\n    revert H.\n    apply ForallT_impl, ForallT_all; intro.\n    apply Forall_tails_impl, Forall_tails_all; intros [|??];\n    [ exact (fun x => x) | ].\n    intro H;\n      repeat (let x := fresh in intro x; specialize (H x));\n      revert H.\n    simpl in *.\n    repeat match goal with\n           | _ => assumption\n           | [ |- ?R ?x ?x ] => reflexivity\n           | [ H : S _ = 0 |- _ ] => clear -H; congruence\n           | [ H : 0 = S _ |- _ ] => clear -H; congruence\n           | [ H : nil = _::_ |- _ ] => clear -H; congruence\n           | [ H : _::_ = nil |- _ ] => clear -H; congruence\n           | [ H : _::_ = _::_ |- _ ] => inversion H; clear H\n           | _ => progress subst\n           | [ |- ?T -> ?T ] => exact (fun x => x)\n           | [ |- context[match ?e with Terminal _ => _ | _ => _ end] ]\n             => destruct e eqn:?\n           | [ |- context[match ?e with nil => _ | _ => _ end] ]\n             => destruct e eqn:?\n           | _ => progress simpl\n           | _ => rewrite Min.min_0_r\n           | _ => intro\n           | [ |- context[0 = min _ _] ] => exists 0\n           | [ |- ?x = ?x ] => reflexivity\n           | [ |- _ \\/ False ] => left\n           | _ => progress destruct_head @sigT\n           | _ => progress destruct_head @prod\n           | [ H : MinimalParse.minimal_parse_of_item _ _ (take _ (substring _ 0 _)) (Terminal _) |- _ ]\n             => exfalso; inversion H; clear H\n           | [ H : is_true (take _ (substring _ 0 _) ~= [_]) |- _ ]\n             => apply length_singleton in H\n           | [ H : length (take _ (substring _ 0 _)) = S _ |- _ ]\n             => rewrite take_length, substring_length, <- Nat.sub_min_distr_r, Nat.add_sub, !Min.min_0_r in H\n           | [ H : MinimalParse.minimal_parse_of_production _ _ _ nil |- _ ] => inversion H; clear H\n           | [ |- MinimalParse.minimal_parse_of_production _ _ _ nil ] => constructor\n           | [ H : MinimalParse.minimal_parse_of_item _ _ _ (Terminal _) |- _ ]\n             => inversion H; clear H\n           | [ |- MinimalParse.minimal_parse_of_item _ _ _ (Terminal _) ]\n             => econstructor; [ eassumption | ]\n           | [ H : length (drop _ (substring _ _ _)) = 0 |- _ ] => rewrite drop_length, substring_length in H\n           | [ |- length (drop _ (substring _ _ _)) = 0 ] => rewrite drop_length, substring_length\n           | [ H : ?x = 0 \\/ ?T |- _ ]\n             => let H' := fresh in\n                destruct (Compare_dec.zerop x) as [H'|H'];\n                  [ clear H\n                  | assert T by (clear -H H'; destruct H; try assumption; try omega); clear H ]\n           | [ |- (_ * _)%type ] => split\n           | [ |- { _ : nat & _ } ] => eexists; repeat split; [ left; reflexivity | .. ]\n           | [ H : ?x + ?y <= _ |- context[(?y + ?x)%nat] ]\n             => not constr_eq x y; rewrite (Plus.plus_comm y x)\n           | [ H : ?x + ?y <= _, H' : context[(?y + ?x)%nat] |- _ ]\n             => not constr_eq x y; rewrite (Plus.plus_comm y x) in H'\n           | [ H : context[(?x + 1)%nat] |- _ ] => rewrite (Plus.plus_comm x 1) in H; simpl plus in H\n           | [ H : context[min ?x ?y], H' : ?y <= ?x |- _ ] => rewrite (Min.min_r x y) in H by assumption\n           | [ H' : ?y <= ?x |- context[min ?x ?y] ] => rewrite (Min.min_r x y) by assumption\n           | [ H : _ - _ = 0 |- _ ] => apply Nat.sub_0_le in H\n           | [ |- _ - _ = 0 ] => apply Nat.sub_0_le\n           | [ H : _ |- _ ] => progress rewrite ?Nat.add_sub, ?Minus.minus_plus in H\n           | _ => progress rewrite ?Nat.add_sub, ?Minus.minus_plus, ?Minus.minus_diag, ?Min.min_idempotent\n           | [ |- is_true (is_char (take ?x (take ?x _)) _) ]\n             => rewrite take_take\n           | [ H : is_true (is_char (take ?n ?str) ?ch) |- is_true (is_char ?str ?ch) ]\n             => rewrite (take_long str)\n               in H\n               by (rewrite substring_length, Plus.plus_comm, Min.min_r by assumption; omega)\n           | [ H : is_true (is_char (take ?n ?str) ?ch) |- is_true (is_char (take 1 ?str) ?ch) ]\n             => apply take_n_1_singleton in H\n           | [ |- MinimalParse.minimal_parse_of_production _ _ _ (_::_) ]\n             => eapply @MinimalParseOfParse.expand_minimal_parse_of_production_beq;\n               [ try assumption.. | eassumption ]\n           | [ |- MinimalParse.minimal_parse_of_item _ _ (take 0 _) _ ]\n             => eapply @MinimalParseOfParse.expand_minimal_parse_of_item_beq;\n               [ try assumption.. | eassumption ]\n           | [ |- MinimalParse.minimal_parse_of_item _ _ _ _ ]\n             => eapply @MinimalParseOfParse.expand_minimal_parse_of_item_beq;\n               [ try assumption.. | eassumption ]\n           | [ H : is_true (is_char (take ?x _) _) |- ?R (drop ?x _) (drop 1 _) ]\n             => apply length_singleton in H; rewrite take_length, substring_length in H\n           | [ H : min ?x ?y = 1\n               |- ?R (drop ?x (substring _ ?y _)) (drop 1 (substring _ ?y _)) ]\n             => revert H; apply Min.min_case_strong; intros; subst;\n                try reflexivity;\n                apply bool_eq_empty\n           | [ |- context[S ?x - ?x] ]\n             => rewrite <- Nat.add_1_r, Minus.minus_plus\n           | [ |- context[take ?x (take 0 _)] ]\n             => rewrite take_take\n           | [ |- context[min _ ?x - ?x] ]\n             => rewrite <- Nat.sub_min_distr_r\n           | [ H : ?y <= ?x |- context[take ?x (substring ?z ?y ?str)] ]\n             => rewrite (take_long (substring z y str))\n               by (rewrite substring_length, Plus.plus_comm, Min.min_r by assumption; omega)\n           | [ |- context[take ?x (substring ?z ?x ?str)] ]\n             => rewrite (take_long (substring z x str))\n               by (rewrite substring_length, Plus.plus_comm, Min.min_r by assumption; omega)\n           end.\n  Qed.\nEnd recursive_descent_parser.\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/Parsers/RecognizerPreOptimized.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.24152354185269542}}
{"text": "(* En este archivo se incluye la representación del sistema de seguridad de\n * Android y la definición de las propiedades que debe cumplir\n * para ser considerado válido *)\nRequire Import DefBasicas.\nRequire Import EqTheorems.\nRequire Import Maps.\nRequire Export List.\n\n\nSection Estado.\n\n(* Parte estática del estado del sistema *)\nRecord Environment := env {\n                            (* Para cada aplicación instalada por el usuario, retorna su manifiesto *)\n                            manifest: mapping idApp Manifest;\n                            (* Para cada aplicación instalada por el usuario, retorna el certificado con el que fue firmada *)\n                            cert: mapping idApp Cert;\n                            (* Para cada aplicación instalada por el usuario, retorna la lista de permisos que ella define *)\n                            defPerms: mapping idApp (list Perm);\n                            (* Reúne la lista de aplicaciones preinstaldas de fábrica *)\n                            systemImage: list SysImgApp\n                           }.\n\n(* Parte dinámica del estado del sistema *)\nRecord State := st { \n                    (* La lista de aplicaciones instaladas por el usuario *)\n                     apps: list idApp;\n                     (* Las aplicaciones que ya fueron ejecutadas alguna vez *)\n                     (* NOTE: alreadyVerified \\subset apps podría ser un invariante nuevo *)\n                     alreadyVerified: list idApp;\n                    (* Para cada aplicación instalada, retorna la lista de grupos de permisos para los cuales \n                     * la aplicación posee algùn permiso otorgado *)\n                     grantedPermGroups : mapping idApp (list idGrp);\n                    (* Para cada aplicación instalada, retorna la lista de permisos a ella individualmente otorgados *)\n                     perms: mapping idApp (list Perm);\n                     (* Mapa que indica de qué componente es una instancia cada módulo en ejecución *)\n                     running: mapping iCmp Cmp;\n                     (* Mapa que indica a qué recursos tiene qué tipo de derecho permanentemente otorgados cada aplicación *)\n                     delPPerms: mapping (idApp * CProvider * uri) PType;\n                     (* Mapa que indica a qué recursos tiene qué tipo de derecho temporalmente otorgados cada módulo en ejecución *)\n                     delTPerms: mapping (iCmp * CProvider * uri) PType;\n                     (* Mapa que indica, dado un recurso de una aplicación, qué valor posee *)\n                     resCont: mapping (idApp * res) Val;\n                    (* La lista de intents que han sido enviados, junto con su remitente *)\n                     sentIntents: list (iCmp*Intent) \n                    }.\n\n(* Estado del sistema *)\nRecord System := sys {\n                       (* Conformado por una parte estática *)\n                       state: State;\n                       (* y una dinámica *)\n                       environment: Environment \n                     }.\n\nEnd Estado.\n\n\n\nSection EstadoValido.\n\n(* La aplicación a forma parte del sistema *)\nDefinition isAppInstalled (a:idApp) (s:System) : Prop :=\n    (* si fue instalada por el usuario *)\n    In a (apps (state s)) \\/\n    (* o estaba preinstalada de fábrica *)\n    (exists sysapp:SysImgApp,\n    In sysapp (systemImage (environment s)) /\\\n    idSI sysapp = a).\n\n(* Predicado para verificar si un componente pertence a una aplicación instalada *)\nDefinition inApp (c:Cmp)(a:idApp)(s:System) : Prop := \nexists (m:Manifest),\n(* si existe una aplicación instalada por el usuario *)\n(map_apply idApp_eq (manifest (environment s)) a = Value idApp m \\/\n(* o una preinstalada de fábrica con id a *)\n(exists sysapp:SysImgApp,\n    In sysapp (systemImage (environment s)) /\\\n    idSI sysapp = a /\\\n    manifestSI sysapp=m)\n) /\\\n(* y c pertenece a ella *)\nIn c (cmp m).\n\n(* Predicado para verificar si el componente que toma como parámetro es un\n * content provider *)\nDefinition isCProvider (c : Cmp) : Prop :=\nmatch c with\n   | cmpCP _ => True\n   | _ => False\nend.\n\n(* Predicado para verificar si en s existe el recurso apuntado por el URI u en\n * el content provider cp *)\nDefinition existsRes (cp : CProvider)(u:uri)(s:System) : Prop := \nexists (a:idApp),\ninApp (cmpCP cp) a s /\\\nexists r:res, map_apply uri_eq (map_res cp) u = Value uri r /\\\nexists v:Val, (map_apply rescontdomeq (resCont (state s))) (a, r) = Value (idApp*res) v.\n\n(* Función que devuelve el id de un componente *)\nDefinition getCmpId (c:Cmp) : idCmp :=\nmatch c with\n   | cmpAct a => idA a\n   | cmpSrv s => idS s\n   | cmpBR br => idB br\n   | cmpCP cp => idC cp\nend.\n\n(* Predicado que indica si un permiso es de sistema *)\nParameter isSystemPerm : Perm -> Prop.\n\n(* Predicado para verificar si un permiso fue definido por el usuario en un estado *)\nDefinition usrDefPerm (p:Perm)(s:System) : Prop := \n(exists (a:idApp) (l: list Perm),\nmap_apply idApp_eq (defPerms (environment s)) a = Value idApp l /\\\nIn p l) \\/ (* Si es definido por una app instalada o *)\n(exists sysapp:SysImgApp, In sysapp (systemImage (environment s)) /\\ \nIn p (defPermsSI sysapp)). (* es definido por una app de sistema *)\n\n\n(* Predicado que indica si un permiso existe en el sistema *)\nDefinition permExists (p:Perm)(s:System) : Prop := \n    isSystemPerm p \\/ usrDefPerm p s. (* Un permiso existe si es de sistema o lo define alguna app *)\n\nVariable s:System.\n\n(* No hay dos componentes pertenecientes a aplicaciones instaladas que tengan el mismo identificador *)\nDefinition allCmpDifferent : Prop := \nforall (c1 c2:Cmp)(a1 a2:idApp),\ninApp c1 a1 s -> \ninApp c2 a2 s ->\ngetCmpId c1 = getCmpId c2 -> c1 = c2.\n\n(* Un mismo componente no está asociado a dos aplicaciones distintas *)\nDefinition notRepeatedCmps : Prop := \nforall (c:Cmp)(a1 a2:idApp),\ninApp c a1 s ->\ninApp c a2 s ->\na1 = a2.\n\n(* Si un componente está corriendo, éste no puede ser un content provider *)\nDefinition notCPrunning : Prop := \nforall (ic:iCmp)(c:Cmp),\nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c ->  \n~isCProvider c.\n\n(* Si una delegación sobre un content provider que se realizó a través de intents\n * está vigente, entonces la instancia que recibió dicha delegación está ejecutándose \n * y el content provider en cuestión está instalado *)\nDefinition delTmpRun : Prop := \nforall (ic:iCmp)(cp:CProvider)(u:uri)(pt:PType),\nmap_apply deltpermsdomeq (delTPerms (state s)) (ic, cp, u) = Value (iCmp*CProvider*uri) pt ->\n(exists a1: idApp, inApp (cmpCP cp) a1 s) /\\\nexists c:Cmp, exists a:idApp, inApp c a s /\\ \nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c.\n\n(* Si una instancia está corriendo, el componente del cual es una\n * instancia, está instalado *)\nDefinition cmpRunAppIns : Prop := \nforall (ic:iCmp)(c:Cmp), \nmap_apply iCmp_eq (running (state s)) ic = Value iCmp c -> \nexists a:idApp, inApp c a s.\n\n(* Todo recurso en el sistema pertenece a una aplicación instalada *)\nDefinition resContAppInst : Prop := \nforall (a:idApp)(r:res)(v:Val),\nmap_apply rescontdomeq (resCont (state s)) (a, r) = Value (idApp*res) v -> \nisAppInstalled a s.\n\n(* Dada una aplicación y una lista de permisos, indica si esta lista es la de los permisos\n * definidos por la aplicación *)\nDefinition defPermsForApp (a:idApp) (l:list Perm) : Prop :=\n    map_apply idApp_eq (defPerms (environment s)) a = Value idApp l \\/\n    (exists sysapp:SysImgApp, In sysapp (systemImage (environment s)) /\\ defPermsSI sysapp = l /\\ idSI sysapp = a).\n\n(* Si dos recursos definidos tienen igual id, son el mismo de la misma aplicación *)\nDefinition notDupPerm : Prop :=\nforall (a a':idApp) (p p':Perm) (l l':list Perm),\ndefPermsForApp a l ->\ndefPermsForApp a' l' ->\nIn p l ->\nIn p' l' ->\nidP p = idP p' ->\n(p=p' /\\ a=a').\n\n(* Los permisos individualmente otorgados existen *)\nDefinition grantedPermsExist : Prop:=\n    forall (a:idApp) (p:Perm) (l:list Perm), map_apply idApp_eq (perms (state s)) a = Value idApp l -> In p l -> permExists p s.\n\n(* Solo las aplicaciones instalada tienen definido un manifesto, un certificado \n * y un conjunto de recursos *)\nDefinition statesConsistency : Prop :=\nforall (a:idApp),\n(In a (apps (state s)) <->\n(exists m:Manifest, map_apply idApp_eq (manifest (environment s)) a = Value idApp m)) /\\\n(In a (apps (state s)) <->\n(exists c:Cert, map_apply idApp_eq (cert (environment s)) a = Value idApp c)) /\\\n(In a (apps (state s)) <->\n(exists l:list Perm, map_apply idApp_eq (defPerms (environment s)) a = Value idApp l)) /\\\n(In a (apps (state s)) \\/ (exists sysapp:SysImgApp, In sysapp (systemImage (environment s)) /\\ idSI sysapp = a) <->\n(exists l:list Perm, (map_apply idApp_eq (perms (state s)) a = Value idApp l))) /\\\n(In a (apps (state s)) \\/ (exists sysapp:SysImgApp, In sysapp (systemImage (environment s)) /\\ idSI sysapp = a) <->\n(exists l:list idGrp, map_apply idApp_eq (grantedPermGroups (state s)) a = Value idApp l)).\n\n(* Si una aplicación figura como instalada por el usuario, no existe una aplicación\n * preinstalada con el mismo identificador *)\nDefinition notDupApp : Prop :=\n    forall (a:idApp),\n    (In a (apps (state s)) -> ~(exists sysapp:SysImgApp,\n    In sysapp (systemImage (environment s)) /\\\n    idSI sysapp = a)).\n\n(* Todas las aplicaciones instaladas tienen identificadores diferentes *)\nDefinition notDupSysApp : Prop :=\n    forall (s1 s2 : SysImgApp),\n    In s1 (systemImage (environment s)) /\\\n    In s2 (systemImage (environment s)) /\\\n    idSI s1 = idSI s2 -> s1 = s2.\n\n(* Todos los maps representan funciones parciales *)\nDefinition allMapsCorrect : Prop :=\n    map_correct (manifest (environment s)) /\\\n    map_correct (cert (environment s)) /\\\n    map_correct (defPerms (environment s)) /\\\n    map_correct (grantedPermGroups (state s)) /\\\n    map_correct (perms (state s)) /\\\n    map_correct (running (state s)) /\\\n    map_correct (delPPerms (state s)) /\\\n    map_correct (delTPerms (state s)) /\\\n    map_correct (resCont (state s)).\n\n(* No existen intents distintos con igual identificador *)\nDefinition noDupSentIntents : Prop :=\n    forall (i i': Intent) (ic ic' : iCmp),\n        In (ic,i) (sentIntents (state s)) ->\n        In (ic',i') (sentIntents (state s)) ->\n        idI i = idI i' ->\n        ic=ic' /\\ i=i'.\n\n(* Esta proposición vale si y sólo si el estado es válido *)\nDefinition validstate  : Prop := allCmpDifferent /\\\n                                 notRepeatedCmps /\\\n                                 notCPrunning /\\\n                                 delTmpRun /\\\n                                 cmpRunAppIns /\\\n                                 resContAppInst /\\\n                                 statesConsistency /\\\n                                 notDupApp /\\\n                                 notDupSysApp /\\\n                                 notDupPerm /\\\n                                 allMapsCorrect /\\\n                                 grantedPermsExist /\\\n                                 noDupSentIntents.\n\nEnd EstadoValido.\n", "meta": {"author": "g-deluca", "repo": "android-coq-model", "sha": "fd89432c39c043e1ca9d3d90e5702fd8cf536167", "save_path": "github-repos/coq/g-deluca-android-coq-model", "path": "github-repos/coq/g-deluca-android-coq-model/android-coq-model-fd89432c39c043e1ca9d3d90e5702fd8cf536167/src/Estado.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.24148626263568676}}
{"text": "From Equations Require Import Equations.\nRequire Import Equations.Prop.Subterm.\n\nRequire Import Psatz.\n\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\n\nRequire Export SystemFR.PolarityLemmas.\n\nOpaque makeFresh.\nOpaque PeanoNat.Nat.eq_dec.\nOpaque reducible_values.\n\nDefinition subset_rc (rc1 rc2: tree -> Prop) := forall v, rc1 v -> rc2 v.\n\nFixpoint respect_polarities pols (ρ1 ρ2: interpretation) :=\n  match ρ1, ρ2 with\n  | nil, nil => True\n  | (X, rc1) :: ρ1', (Y, rc2) :: ρ2' =>\n    X = Y /\\\n    (~((X, Positive) ∈ pols) -> subset_rc rc2 rc1) /\\\n    (~((X, Negative) ∈ pols) -> subset_rc rc1 rc2) /\\\n    respect_polarities pols ρ1' ρ2'\n  | _, _ => False\n  end.\n\nLemma respect_polarities_refl:\n  forall pols ρ,\n    respect_polarities pols ρ ρ.\nProof.\n  induction ρ; steps.\nQed.\n\nLemma invert_twice:\n  forall pol, invert_polarity (invert_polarity (pol)) = pol.\nProof.\n  destruct pol; steps.\nQed.\n\nLemma pair_in_invert:\n  forall (pols : list (nat * polarity)) (x : nat) pol,\n    (x, invert_polarity pol) ∈ pols ->\n    (x, pol) ∈ invert_polarities pols.\nProof.\n  induction pols; repeat step || rewrite invert_twice.\nQed.\n\nLemma respect_polarities_invert:\n  forall pols ρ1 ρ2,\n    respect_polarities pols ρ1 ρ2 ->\n    respect_polarities (invert_polarities pols) ρ2 ρ1.\nProof.\n  induction ρ1; repeat step || apply_any || apply pair_in_invert.\nQed.\n\nLtac t_respect_polarities_invert :=\n  match goal with\n  | H: respect_polarities _ _ _ |- _ =>\n    poseNew (Mark 0 \"respect_polarities_invert\");\n    pose proof (respect_polarities_invert _ _ _ H)\n  end.\n\nDefinition polarity_variance_prop T: Prop :=\n  forall pols ρ1 ρ2 v,\n    has_polarities T pols ->\n    is_erased_type T ->\n    wf T 0 ->\n    pfv T term_var = nil ->\n    respect_polarities pols ρ1 ρ2 ->\n    valid_interpretation ρ1 ->\n    valid_interpretation ρ2 ->\n    [ ρ1 ⊨ v : T ]v ->\n    [ ρ2 ⊨ v : T ]v.\n\nLemma use_respect_polarities:\n  forall (pols : list (nat * polarity)) (ρ1 ρ2 : interpretation) (n : nat) (v : tree) P1 P2,\n    respect_polarities pols ρ1 ρ2 ->\n    ((n, Negative) ∈ pols -> False) ->\n    lookup PeanoNat.Nat.eq_dec ρ1 n = Some P1 ->\n    lookup PeanoNat.Nat.eq_dec ρ2 n = Some P2 ->\n    P1 v ->\n    P2 v.\nProof.\n  induction ρ1; steps; eauto with eapply_any.\nQed.\n\nLemma respect_polarities_some_none:\n  forall (n : nat) (pols : list (nat * polarity)) (ρ1 ρ2 : interpretation) P,\n    respect_polarities pols ρ1 ρ2 ->\n    lookup PeanoNat.Nat.eq_dec ρ1 n = Some P ->\n    lookup PeanoNat.Nat.eq_dec ρ2 n = None ->\n    False.\nProof.\n  induction ρ1; steps; eauto.\nQed.\n\nLemma polarity_variance_fvar: forall m n f, prop_at polarity_variance_prop m (fvar n f).\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop;\n    repeat step || destruct_tag || simp_red || step_inversion has_polarities;\n    eauto using respect_polarities_some_none.\n  eapply use_respect_polarities; eauto 1; steps.\nQed.\n\n#[export]\nHint Immediate polarity_variance_fvar: b_polarity_variance.\n\nLemma polarity_variance_induction:\n  forall T n o pols ρ1 ρ2 v,\n    prop_until polarity_variance_prop (n, o) ->\n    respect_polarities pols ρ1 ρ2 ->\n    has_polarities T pols ->\n    type_nodes T < n ->\n    is_erased_type T ->\n    wf T 0 ->\n    pfv T term_var = nil ->\n    valid_interpretation ρ1 ->\n    valid_interpretation ρ2 ->\n    [ ρ1 ⊨ v : T ]v ->\n    [ ρ2 ⊨ v : T ]v.\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop; intros.\n  eapply_any; eauto 1; repeat step || apply left_lex.\nQed.\n\nLemma polarity_variance_induction_invert:\n  forall T n o pols ρ1 ρ2 v,\n    prop_until polarity_variance_prop (n, o) ->\n    respect_polarities pols ρ1 ρ2 ->\n    has_polarities T (invert_polarities pols) ->\n    type_nodes T < n ->\n    is_erased_type T ->\n    wf T 0 ->\n    pfv T term_var = nil ->\n    valid_interpretation ρ1 ->\n    valid_interpretation ρ2 ->\n    [ ρ2 ⊨ v : T ]v ->\n    [ ρ1 ⊨ v : T ]v.\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop; intros.\n  eapply H with _ (invert_polarities pols) ρ2; eauto 1; repeat step || apply left_lex;\n    eauto using respect_polarities_invert.\nQed.\n\nLemma polarity_variance_induction_open:\n  forall T a n o pols ρ1 ρ2 v,\n    prop_until polarity_variance_prop (n, o) ->\n    respect_polarities pols ρ1 ρ2 ->\n    has_polarities T pols ->\n    type_nodes T < n ->\n    is_erased_type T ->\n    wf T 1 ->\n    pfv T term_var = nil ->\n    is_erased_term a ->\n    wf a 0 ->\n    pfv a term_var = nil ->\n    valid_interpretation ρ1 ->\n    valid_interpretation ρ2 ->\n    is_erased_type T ->\n    [ ρ1 ⊨ v : open 0 T a ]v ->\n    [ ρ2 ⊨ v : open 0 T a ]v.\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop; intros.\n  eapply_any; eauto 1;\n    repeat step || apply left_lex || autorewrite with bsize in * ||\n           apply polarity_open;\n    eauto with erased fv wf.\nQed.\n\nLemma polarity_variance_arrow:\n  forall m T1 T2, prop_until polarity_variance_prop m -> prop_at polarity_variance_prop m (T_arrow T1 T2).\nProof.\n  unfold get_measure, prop_at; intros; unfold polarity_variance_prop;\n    repeat step || simp_red || step_inversion has_polarities || list_utils || t_reduces_to2 || apply_any;\n    try solve [ eapply polarity_variance_induction_invert; try eassumption; steps; eauto with lia ];\n    try solve [ eapply polarity_variance_induction_open; try eassumption; steps; eauto with lia ].\nQed.\n\n#[export]\nHint Immediate polarity_variance_arrow: b_polarity_variance.\n\nLemma polarity_variance_prod:\n  forall m T1 T2, prop_until polarity_variance_prop m -> prop_at polarity_variance_prop m (T_prod T1 T2).\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop;\n    repeat step || simp_red || list_utils ||\n           step_inversion has_polarities || t_reduces_to2 || apply_any || find_exists;\n    try solve [ eapply polarity_variance_induction; try eassumption; steps; eauto with lia ];\n    try solve [ eapply polarity_variance_induction_open; try eassumption; steps; eauto with lia ].\nQed.\n\n#[export]\nHint Immediate polarity_variance_prod: b_polarity_variance.\n\nLemma polarity_variance_sum:\n  forall m T1 T2, prop_until polarity_variance_prop m -> prop_at polarity_variance_prop m (T_sum T1 T2).\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop;\n    repeat step || simp_red || list_utils || step_inversion has_polarities || find_exists;\n    try solve [ eapply polarity_variance_induction; try eassumption; steps; eauto with lia ].\nQed.\n\n#[export]\nHint Immediate polarity_variance_sum: b_polarity_variance.\n\nLemma polarity_variance_refine:\n  forall m T b, prop_until polarity_variance_prop m -> prop_at polarity_variance_prop m (T_refine T b).\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop;\n    repeat step || simp_red || list_utils || step_inversion has_polarities || find_exists;\n    try solve [ eapply polarity_variance_induction; try eassumption; steps; eauto with lia ].\nQed.\n\n#[export]\nHint Immediate polarity_variance_refine: b_polarity_variance.\n\nLemma polarity_variance_type_refine:\n  forall m T1 T2,\n    prop_until polarity_variance_prop m ->\n    prop_at polarity_variance_prop m (T_type_refine T1 T2).\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop;\n    repeat step || simp_red || step_inversion has_polarities || list_utils || exists p;\n    try solve [ eapply polarity_variance_induction; try eassumption; steps; eauto with lia ];\n    try solve [ eapply polarity_variance_induction_open; try eassumption; steps;\n                eauto with lia erased fv wf ].\nQed.\n\n#[export]\nHint Immediate polarity_variance_type_refine: b_polarity_variance.\n\nLemma polarity_variance_intersection:\n  forall m T1 T2, prop_until polarity_variance_prop m -> prop_at polarity_variance_prop m (T_intersection T1 T2).\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop;\n    repeat step || simp_red || list_utils || step_inversion has_polarities;\n    try solve [ eapply polarity_variance_induction; try eassumption; steps;\n                eauto with lia erased fv wf ].\nQed.\n\n#[export]\nHint Immediate polarity_variance_intersection: b_polarity_variance.\n\nLtac reducibility_choice2 :=\n  match goal with\n  | H: [ _ ⊨ ?v : ?T ]v |- [ _ ⊨ ?v : ?T ]v \\/ _ => left\n  | H: [ _ ⊨ ?v : ?T ]v |- _ \\/ [ _ ⊨ ?v : ?T ]v => right\n  end.\n\nLemma polarity_variance_union:\n  forall m T1 T2, prop_until polarity_variance_prop m -> prop_at polarity_variance_prop m (T_union T1 T2).\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop;\n    repeat step || simp_red || step_inversion has_polarities || list_utils || reducibility_choice2;\n    try solve [ eapply polarity_variance_induction; try eassumption; steps;\n                eauto with lia erased fv erased ].\nQed.\n\n#[export]\nHint Immediate polarity_variance_union: b_polarity_variance.\n\nLemma polarity_variance_forall:\n  forall m T1 T2,\n    prop_until polarity_variance_prop m ->\n    prop_at polarity_variance_prop m (T_forall T1 T2).\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop;\n    repeat step || simp_red || step_inversion has_polarities || list_utils.\n  eapply polarity_variance_induction_open; eauto 1; repeat step || apply leq_lt_measure || apply_any;\n    try lia;\n    try solve [ eapply polarity_variance_induction_invert; try eassumption; steps; eauto with lia erased ].\nQed.\n\n#[export]\nHint Immediate polarity_variance_forall: b_polarity_variance.\n\nLemma polarity_variance_exists:\n  forall m T1 T2, prop_until polarity_variance_prop m -> prop_at polarity_variance_prop m (T_exists T1 T2).\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop;\n    repeat step || simp_red || step_inversion has_polarities || list_utils || exists a;\n    try solve [ eapply polarity_variance_induction; try eassumption; steps; eauto with lia erased ];\n    try solve [ eapply polarity_variance_induction_open; try eassumption; steps; eauto with lia erased ].\nQed.\n\n#[export]\nHint Immediate polarity_variance_exists: b_polarity_variance.\n\nLemma respect_polarities_support:\n  forall (pols : list (nat * polarity)) (ρ1 ρ2 : interpretation) X,\n    respect_polarities pols ρ1 ρ2 ->\n    ~(X ∈ support ρ1) ->\n    X ∈ support ρ2 ->\n    False.\nProof.\n  induction ρ1; steps; eauto.\nQed.\n\nLemma polarity_variance_abs:\n  forall m T, prop_until polarity_variance_prop m -> prop_at polarity_variance_prop m (T_abs T).\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop;\n    repeat step || simp_red || step_inversion has_polarities.\n  exists (makeFresh ((X :: nil) :: support pols :: support ρ2 :: pfv T type_var :: nil));\n    repeat step; try finisher.\n\n  repeat step || t_instantiate_rc || t_reduces_to.\n\n  lazymatch goal with\n  | H: [ _ ⊨ _ : _ ]v |- [ (?M,?RC) :: _ ⊨ _ : _ ]v =>\n    apply (reducible_rename_one _ _ _ _ _ M) in H\n  end; repeat step || finisher.\n\n  lazymatch goal with\n  | |- [ (?M,?RC) :: _ ⊨ _ : _ ]v =>\n    eapply polarity_variance_induction with _ _ pols ((M,RC) :: ρ1); eauto 1\n  end;\n    repeat step || autorewrite with bsize in * ||\n           apply has_polarities_topen; try finisher;\n      eauto 2 with wf fv erased step_tactic.\nQed.\n\n#[export]\nHint Immediate polarity_variance_abs: b_polarity_variance.\n\nLtac t_dangerous_rec_choice :=\n  match goal with\n  | H: _ ~>* zero   |- _ => left\n  | H: _ ~>* succ _ |- _ => right\n  end.\n\nLemma respect_polarities_cons:\n  forall (pols : list (nat * polarity)) (ρ1 ρ2 : interpretation) X pol,\n    respect_polarities pols ρ1 ρ2 ->\n    respect_polarities ((X, pol) :: pols) ρ1 ρ2.\nProof.\n  induction ρ1; steps.\nQed.\n\nLemma polarity_variance_rec:\n  forall m tn T0 Ts, prop_until polarity_variance_prop m -> prop_at polarity_variance_prop m (T_rec tn T0 Ts).\nProof.\n  unfold prop_at; intros; unfold polarity_variance_prop;\n    repeat step || simp_red || list_utils ||\n           step_inversion has_polarities || t_dangerous_rec_choice || find_exists;\n    try solve [ eapply polarity_variance_induction; try eassumption; steps;\n                eauto with lia erased fv wf].\n\n  define m (makeFresh (pfv T0 type_var :: pfv Ts type_var :: support pols :: support ρ1 :: support ρ2 :: nil)).\n  exists n', m;\n    repeat step; try finisher.\n\n  define m (makeFresh (pfv T0 type_var :: pfv Ts type_var :: support pols :: support ρ1 :: support ρ2 :: nil)).\n  apply (reducible_rename_one _ _ _ _ _ m) in H17;\n    repeat step;\n      eauto using reducibility_is_candidate;\n      try finisher.\n\n  define m (makeFresh (pfv T0 type_var :: pfv Ts type_var :: support pols :: support ρ1 :: support ρ2 :: nil)).\n  eapply (polarity_variance_induction _ _ _ ((m, Positive) :: pols) ((m, fun t : tree => [ ρ1 ⊨ t : T_rec n' T0 Ts ]v) :: ρ1)); eauto 1;\n    repeat step || list_utils || apply respect_polarities_cons || unfold subset_rc ||\n           apply reducibility_is_candidate || autorewrite with bsize in *;\n    try finisher;\n    try solve [ eapply has_polarities_rename_one; eauto 1; steps; try finisher ];\n    eauto with lia;\n    eauto with wf fv erased;\n    eauto 2 with wf fv erased step_tactic.\n\n  eapply H; eauto 1;\n    repeat step || list_utils || apply right_lex || apply PolRec || apply reducibility_is_candidate;\n    eauto using lt_index_step;\n    eauto 2 with erased fv wf.\nQed.\n\n#[export]\nHint Immediate polarity_variance_rec: b_polarity_variance.\n\nLemma polarity_variance_aux: forall (m: measure_domain) T, prop_at polarity_variance_prop m T.\nProof.\n  induction m using measure_induction; destruct T;\n    eauto 2 with b_polarity_variance;\n    try solve [ unfold prop_at; intros; unfold polarity_variance_prop in *;\n                repeat step || step_inversion has_polarities || simp_red ].\nQed.\n\nLemma polarity_variance: forall T, polarity_variance_prop T.\nProof.\n  intros; eapply polarity_variance_aux; eauto.\nQed.\n\nLemma positive_grow:\n  forall ρ X rc1 rc2 v T pols,\n    has_polarities (topen 0 T (fvar X type_var)) ((X, Positive) :: pols) ->\n    [ (X, rc1) :: ρ ⊨ v : topen 0 T (fvar X type_var) ]v ->\n    subset_rc rc1 rc2 ->\n    is_erased_type T ->\n    wf T 0 ->\n    pfv T term_var = nil ->\n    valid_interpretation ρ ->\n    reducibility_candidate rc1 ->\n    reducibility_candidate rc2 ->\n    [ (X, rc2) :: ρ ⊨ v : topen 0 T (fvar X type_var) ]v.\nProof.\n  intros.\n  eapply (polarity_variance _ _ ((X,rc1) :: ρ)); eauto 1; steps;\n    eauto 2 using respect_polarities_refl;\n    eauto 2 with erased fv wf step_tactic.\nQed.\n", "meta": {"author": "epfl-lara", "repo": "SystemFR", "sha": "a68d12d6360f395958506deea66112c46be492a0", "save_path": "github-repos/coq/epfl-lara-SystemFR", "path": "github-repos/coq/epfl-lara-SystemFR/SystemFR-a68d12d6360f395958506deea66112c46be492a0/PolarityLemma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24147948942250047}}
{"text": "(** This file contains the Encoding Relation for the Deflate bit\nformat. It is the core component of the verified implementation. It is\n_axiomatic_, and therefore the single point of failure: It specifies a\ncompression format, but there is no guarantee that the specified\nformat is actually what the world understands as \"deflate\". We refer\nto RFC 1951 in this file. *)\n\nRequire Import Coq.Logic.Decidable.\nRequire Import Coq.Arith.Compare_dec.\n\nRequire Import Coq.Numbers.NatInt.NZOrder.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Coq.Vectors.Vector.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Vectors.Fin.\nRequire Import Coq.Arith.Div2.\n\nRequire Import Coq.NArith.BinNatDef.\nRequire Import Coq.NArith.BinNat.\nRequire Import Coq.PArith.BinPos.\nRequire Import NArith.\nRequire Import Coq.QArith.QArith_base.\nRequire Import Coq.Strings.String.\nRequire Import Ascii.\nRequire Import Program.\n\nRequire Import Shorthand.\nRequire Import DeflateCoding.\nRequire Import KraftVec.\nRequire Import KraftList.\nRequire Import Combi.\nRequire Import Transports.\nRequire Import Prefix.\nRequire Import LSB.\nRequire Import Repeat.\nRequire Import Backreferences.\nRequire Import StrongDec.\n\nLocal Open Scope nat_scope.\n\n(** See RFC 1951, section 3.2.5. *)\nDefinition repeatCodeExtraBits : list nat :=\n  [ d\"0\" ; d\"0\" ; d\"0\" ; d\"0\" ; d\"0\" ; d\"0\" ; d\"0\" ; d\"0\" ;\n    d\"1\" ; d\"1\" ; d\"1\" ; d\"1\" ;\n    d\"2\" ; d\"2\" ; d\"2\" ; d\"2\" ;\n    d\"3\" ; d\"3\" ; d\"3\" ; d\"3\" ;\n    d\"4\" ; d\"4\" ; d\"4\" ; d\"4\" ;\n    d\"5\" ; d\"5\" ; d\"5\" ; d\"5\" ;\n    d\"0\" ].\n\n(** See RFC 1951, section 3.2.5. *)\nDefinition repeatCodeBase : list nat :=\n  [ d\"3\" ; d\"4\" ; d\"5\" ; d\"6\" ; d\"7\" ; d\"8\" ; d\"9\" ; d\"10\" ;\n    d\"11\" ; d\"13\" ; d\"15\" ; d\"17\" ;\n    d\"19\" ; d\"23\" ; d\"27\" ; d\"31\" ;\n    d\"35\" ; d\"43\" ; d\"51\" ; d\"59\" ;\n    d\"67\" ; d\"83\" ; d\"99\" ; d\"115\" ;\n    d\"131\" ; d\"163\" ; d\"195\" ; d\"227\" ;\n    d\"258\" ].\n\n(** See RFC 1951, section 3.2.5. *)\nDefinition repeatCodeMax : list nat :=\n  [ d\"3\"; d\"4\"; d\"5\"; d\"6\"; d\"7\"; d\"8\"; d\"9\"; d\"10\";\n    d\"12\"; d\"14\"; d\"16\"; d\"18\";\n    d\"22\"; d\"26\"; d\"30\"; d\"34\";\n    d\"42\"; d\"50\"; d\"58\"; d\"66\";\n    d\"82\"; d\"98\"; d\"114\"; d\"130\";\n    d\"162\"; d\"194\"; d\"226\"; d\"257\";\n    d\"258\" ].\n\n(** See RFC 1951, section 3.2.5. *)\nDefinition distCodeExtraBits :=\n  [ d\"0\"  ;  d\"0\"  ; d\"0\"  ; d\"0\" ;\n    d\"1\"  ;  d\"1\"  ; d\"2\"  ; d\"2\" ;\n    d\"3\"  ;  d\"3\"  ; d\"4\"  ; d\"4\" ;\n    d\"5\"  ;  d\"5\"  ; d\"6\"  ; d\"6\" ;\n    d\"7\"  ;  d\"7\"  ; d\"8\"  ; d\"8\" ;\n    d\"9\"  ;  d\"9\"  ; d\"10\" ; d\"10\" ;\n    d\"11\" ; d\"11\"  ; d\"12\" ; d\"12\" ;\n    d\"13\" ; d\"13\" ].\n\n(** See RFC 1951, section 3.2.5. Notice that these numbers are large,\nand may cause warnings by Coq when actually evaluated.  *)\nDefinition distCodeBase :=\n  [ d\"1\"     ; d\"2\"     ; d\"3\"     ; d\"4\"     ;\n    d\"5\"     ; d\"7\"     ; d\"9\"     ; d\"13\"    ;\n    d\"17\"    ; d\"25\"    ; d\"33\"    ; d\"49\"    ;\n    d\"65\"    ; d\"97\"    ; d\"129\"   ; d\"193\"   ;\n    d\"257\"   ; d\"385\"   ; d\"513\"   ; d\"769\"   ;\n    d\"1025\"  ; d\"1537\"  ; d\"2049\"  ; d\"3073\"  ;\n    d\"4097\"  ; d\"6145\"  ; d\"8193\"  ; d\"12289\" ;\n    d\"16385\" ; d\"24577\" ].\n\n(** See RFC 1951, section 3.2.5. Notice that these numbers are large,\nand may cause warnings by Coq when actually evaluated.  *)\nDefinition distCodeMax :=\n  [ d\"1\"     ; d\"2\"     ; d\"3\"     ; d\"4\"     ;\n    d\"6\"     ; d\"8\"     ; d\"12\"    ; d\"16\"    ;\n    d\"24\"    ; d\"32\"    ; d\"48\"    ; d\"64\"    ;\n    d\"96\"    ; d\"128\"   ; d\"192\"   ; d\"256\"   ;\n    d\"384\"   ; d\"512\"   ; d\"768\"   ; d\"1024\"  ;\n    d\"1536\"  ; d\"2048\"  ; d\"3072\"  ; d\"4096\"  ;\n    d\"6144\"  ; d\"8192\"  ; d\"12288\" ; d\"16384\" ;\n    d\"24576\" ; d\"32768\" ].\n\n(* FIXED1 *)\n(** See RFC 1951, section 3.2.6. *)\nDefinition vector_for_fixed_lit_code : vec nat 288 :=\n  of_list ((repeat 144 8) ++ (repeat (255 - 143) 9) ++\n     (repeat (279 - 255) 7) ++ (repeat (287 - 279) 8)).\n\n(** See RFC 1951, section 3.2.6. *)\nDefinition vector_for_fixed_dist_code : vec nat 32 :=\n   of_list (repeat 32 5).\n(* FIXED2 *)\n\n(** For the constant codings, we use our already proved uniqueness and existence predicates *)\nDefinition fixed_lit_code_ex : { D : deflateCoding 288 | vector_for_fixed_lit_code = Vmap lb (C 288 D)}.\nProof.\n  apply existence.\n  compute.\n  intros Q.\n  inversion Q.\nDefined.\n\n(** For the constant codings, we use our already proved uniqueness and existence predicates *)\nDefinition fixed_dist_code_ex : { D : deflateCoding 32 | vector_for_fixed_dist_code = Vmap lb (C 32 D)}.\nProof.\n  apply existence.\n  compute.\n  intros Q.\n  inversion Q.\nDefined.\n\nDefinition fixed_lit_code := proj1_sig fixed_lit_code_ex.\nDefinition fixed_dist_code := proj1_sig fixed_dist_code_ex.\n\n(* HCLENSNAT1 *)\n(** See RFC 1951, section 3.2.7. *)\nDefinition HCLensNat :=\n  [16; 17; 18; 0;  8; 7;  9; 6; 10; 5;\n   11;  4; 12; 3; 13; 2; 14; 1; 15].\n(* HCLENSNAT2 *)\n\n(* ONEBIT1 *)\nInductive OneBit : bool -> LB -> Prop :=\n| oneBit : forall b, OneBit b [b].\n(* ONEBIT2 *)\n\n(* NBITS1 *)\t\t\t\t\nDefinition nBits (n : nat) : LB -> LB -> Prop :=\n  nTimesCons n OneBit.\n(* NBITS2 *)\n\t\t\t\t\t\n(* NBITSVEC1 *)\nDefinition nBitsVec (n : nat) (vb : vec bool n) (l : LB)\n: Prop := nBits n (to_list vb) l.\n(* NBITSVEC2 *)\n\n(** [nBytesDirect n S L] means that [S] is a sequence of the [n] Bytes\nin the bit sequence [L] without back references *)\n\n(* ONEBYTE1 *)\t\t\t\t\t\nDefinition OneByte : (Byte + nat*nat)%type -> LB -> Prop :=\n  AppCombine (nBitsVec 8) inl.\n(* ONEBYTE2 *)\n\n(* NBYTESDIRECT1 *)\t\t\t\t\t\nDefinition nBytesDirect (n : nat)\n: SequenceWithBackRefs Byte -> LB -> Prop :=\n  nTimesCons n OneByte.\n(* NBYTESDIRECT2 *)\n\t\t\t\t\t\n(** [readBitsLSB length n l] means that the list [l] of given [length]\nencodes the number [n] in least-significant-first bit-order. *)\n\nDefinition readBitsLSB (length : nat) : nat -> LB -> Prop :=\n  AppCombine (nTimesCons length OneBit) ListToNat.\n\n(** Uncompressed block, no padding. Padding is done in\n[OneBlockWithPadding]. See RFC 1951, section 3.2.4. *)\n\n(* UCBD1 *)\nDefinition UncompressedBlockDirect\n  : SequenceWithBackRefs Byte -> LB -> Prop :=\n  (readBitsLSB 16) >>=\n  fun len  => (readBitsLSB 16) >>=\n  fun nlen =>\n    (fun swbr lb => len + nlen = 2 ^ 16 - 1 /\\\n                    nBytesDirect len swbr lb).\n(* UCBD2 *)\n\n(** header parsing for dynamically compressed blocks *)\n\n(** [CodingOfSequence l dc] means that the list of natural numbers [l]\nis the list of lengths of the coding [dc], ordered by the encoded\ncharacters. For further detail, see [DeflateCoding]. *)\n\n(* CODINGOFSEQUENCE1 *)\nInductive CodingOfSequence {n : nat} (l : list nat)\n          (dc : deflateCoding n) :=\n| makeCodingOfSequence : forall (eq : ll l = n),\n    Vmap lb (C _ dc) = vec_id eq (of_list l) ->\n    CodingOfSequence l dc.\n(* CODINGOFSEQUENCE2 *)\n\n(** The code length code. *)\n\n(** Raw code length code - a list of [hclen] bit-triples, which encode code lengths from 0 to 7. *)\n\n(* CLCHEADERRAW1 *)\nInductive CLCHeaderRaw\n  : forall (hclen : nat) (input : LB) (output : list nat), Prop :=\n| zeroCLCHeaderRaw : CLCHeaderRaw 0 nil nil\n| succCLCHeaderRaw : forall n i o j m, CLCHeaderRaw n i o ->\n   ll m = 3 -> LSBnat m j -> CLCHeaderRaw (S n) (m ++ i) (j :: o).\n(* CLCHEADERRAW2 *)\n\n(** Pad the raw header with zeroes, so its length is 19. *)\n\n(* CLCHEADERPADDED1 *)\nInductive CLCHeaderPadded\n  (hclen : nat) (input : LB) (output : list nat) : Prop :=\n| makeCLCHeaderPadded : forall m output1,\n                         CLCHeaderRaw hclen input output1 ->\n                         output = output1 ++ repeat m 0 ->\n                         ll output = 19 ->\n                         CLCHeaderPadded hclen input output.\n(* CLCHEADERPADDED2 *)\n\n(** Apply the permutation to the padded header. *)\n\n(* CLCHEADERPERMUTED1 *)\nInductive CLCHeaderPermuted\n    (hclen : nat) (input : LB) (output : list nat) : Prop :=\n| makeCLCHeaderPermuted :\n   forall output1,\n        CLCHeaderPadded hclen input output1 ->\n        (forall m, nth_error output (nth m HCLensNat 19) =\n\t           nth_error output1 m) ->\n         CLCHeaderPermuted hclen input output.\n(* CLCHEADERPERMUTED2*)\n\n(** [CLCHeader hclen output input] means that the code length coding [output] is encoded in thee [hclen]*3 bits (see above) from [input]. *)\n\n(* CLCHEADER1 *)\nInductive CLCHeader\n  (hclen : nat) (output : deflateCoding 19) (input : LB) : Prop :=\n| makeCLCHeader : forall cooked,\n                    CLCHeaderPermuted hclen input cooked ->\n                    CodingOfSequence cooked output ->\n                    CLCHeader hclen output input.\n(* CLCHEADER2 *)\n\n(** This definition is rather complicated, but it makes later\ndefinitions easier, and encodes a pattern that occurs in multiple\nplaces: A code from a coding is followed by some suffix bits, and\nencodes a value which must be in a given range.\n\nLet [coding] be a given Deflate coding, [mincode] be a natural number\ndenoting the minimal encoded code which is allowed, [xbitnums] the\nnumbers of extra bits for a given encoded code, starting from the\nextra bits for [mincode], [bases] the corresponding minimal encoded\nvalues, and [maxs] the corresponding maximal values. Then\n[CompressedWithExtraBits coding mincode xbitnums bases maxs n l] means\nthat the bit list [l] encodes the value [n], according to these\nrules. *)\n\n(* CWEB1 *)\t\t\t\t\t      \nInductive CompressedWithExtraBits\n       {m : nat} (coding : deflateCoding m)\n       (mincode : nat) (xbitnums bases maxs : list nat)\n       : nat -> LB -> Prop :=\n| complength\n  : forall (base extra code max xbitnum : nat) (bbits xbits : LB),\n     dc_enc coding (mincode + code) bbits -> (* code >= mincode *)\n     nth_error xbitnums code = Some xbitnum -> (* # of addit. bits*)\n     nth_error bases code = Some base -> (* base *)\n     nth_error maxs code = Some max -> (* maximum *)\n     ll xbits = xbitnum -> (* addit. bits have specified length *)\n     LSBnat xbits extra -> (* binary number made by xbits *)\n     base + extra <= max -> \n     CompressedWithExtraBits coding mincode xbitnums\n                   bases maxs (base + extra) (bbits ++ xbits).\n(* CWEB2 *)\t\t\t\t\t      \n\n(** A sequence of code lengths, encoded with the given code length\ncoding. See RFC 1951 section 3.2.7. We encode into a sequence with\nbackreferences, because some codes encode repetitions. *)\n\n(* CCLSWBR1 *)\nInductive CommonCodeLengthsSWBR (clc : deflateCoding 19)\n  : nat -> SequenceWithBackRefs nat -> LB -> Prop :=\n| cswbr0 : CommonCodeLengthsSWBR clc 0 [] []\n| cswbrc :\n    forall m n brs lb1 input,\n      CommonCodeLengthsSWBR clc n brs lb1 ->\n      m < 16 ->\n      dc_enc clc m input ->\n      CommonCodeLengthsSWBR clc (n + 1) (inl m :: brs)\n                            (input ++ lb1)\n| cswbr16 :\n    forall m n brs lb1 input,\n      CommonCodeLengthsSWBR clc n brs lb1 ->\n      CompressedWithExtraBits clc 16 [2] [3] [6] m input ->\n      CommonCodeLengthsSWBR clc (n + m) (inr (m, 1) :: brs)\n                            (input ++ lb1)\n| cswbr17 :\n    forall m n brs lb1 input,\n      CommonCodeLengthsSWBR clc n brs lb1 ->\n      CompressedWithExtraBits clc 17 [3] [3 - 1] [10 - 1] m input ->\n      CommonCodeLengthsSWBR clc (n + m + 1) (inl 0 :: inr (m, 1) :: brs)\n                            (input ++ lb1)\n| cswbr18 :\n    forall m n brs lb1 input,\n      CommonCodeLengthsSWBR clc n brs lb1 ->\n      CompressedWithExtraBits clc 18 [7] [11 - 1] [138 - 1] m input ->\n      CommonCodeLengthsSWBR clc (n + m + 1) (inl 0 :: inr (m, 1) :: brs)\n                            (input ++ lb1).\n(* CCLSWBR2 *)\n\n(** A sequence of code lengths, encoded with the given code length\ncoding. Backreferences will be resolved, so only code lengths 0\nthrough 15 remain. *)\n\n(* CCLN1 *)\nInductive CommonCodeLengthsN (clc : deflateCoding 19) (n : nat)\n          (B : list nat) (A : LB) : Prop := \n| ccl : forall C, CommonCodeLengthsSWBR clc n C A ->\n                  ResolveBackReferences C B ->\n                  CommonCodeLengthsN clc n B A.\n(* CCLN2 *)\n\n(** After the code lengths are read and repeated, they are split and\nthen parsed into a literal/lengt and a distance code lengths . *)\n\n(* SCL1 *)\nInductive SplitCodeLengths (clc : deflateCoding 19) (hlit hdist : nat)\n          (litlen : vec nat 288) (dist : vec nat 32) (input : LB)\n  : Prop :=\n| makeSplitCodeLengths :\n    forall litlenL distL lm ld,\n      ll litlenL = hlit ->\n      ll distL = hdist ->\n      to_list litlen = litlenL ++ repeat lm 0 ->\n      to_list dist = distL ++ repeat ld 0 ->\n      CommonCodeLengthsN clc (hlit + hdist) (litlenL ++ distL) input ->\n      SplitCodeLengths clc hlit hdist litlen dist input.\n(* SCL2 *)\n\n(** From the vector of lengths, encode codings *)\n\n(* LLD1 *)\nInductive LitLenDist (clc : deflateCoding 19) (hlit hdist : nat)\n          (litlen : deflateCoding 288) (dist : deflateCoding 32)\n          (input : LB) : Prop :=\n| makeLitLenDist :\n    SplitCodeLengths clc hlit hdist\n                     (Vmap lb (C 288 litlen))\n                     (Vmap lb (C 32 dist)) input ->\n    LitLenDist clc hlit hdist litlen dist input.\n(* LLD2 *)\n\n\n(* LENDIST1 *)\nFunction CompressedLength (litlen : deflateCoding 288) :=\n CompressedWithExtraBits\n   litlen 257 repeatCodeExtraBits repeatCodeBase repeatCodeMax.\nFunction CompressedDist (dist : deflateCoding 32) :=\n CompressedWithExtraBits \n  dist 0 distCodeExtraBits distCodeBase distCodeMax.\n(* LENDIST2 *)\n\n(* CSWBR1 *)\nInductive CompressedSWBR\n (litlen : deflateCoding 288) (dist : deflateCoding 32)\n : SequenceWithBackRefs Byte -> LB -> Prop :=\n| cswbr_end : forall l, dc_enc litlen 256 l ->\n                          CompressedSWBR litlen dist [] l\n| cswbr_direct : forall prev_swbr prev_lb l n,\n                   dc_enc litlen (ByteToNat n) l ->\n                   CompressedSWBR litlen dist prev_swbr prev_lb ->\n                   CompressedSWBR litlen dist ((inl n) :: prev_swbr)\n\t\t                              (l ++ prev_lb)\n| cswbr_backref : forall prev_swbr prev_lb l d lbits dbits,\n                    CompressedSWBR litlen dist prev_swbr prev_lb ->\n                    CompressedLength litlen l lbits ->\n                    CompressedDist dist d dbits ->\n                    CompressedSWBR litlen dist\n\t\t                   ((inr (l, d)) :: prev_swbr)\n\t\t                   (lbits ++ dbits ++ prev_lb).\n(* CSWBR2 *)\n\n(* DCH1 *)\nDefinition DynamicallyCompressedHeader\n  : (deflateCoding 288 * deflateCoding 32) -> LB -> Prop :=\n  (readBitsLSB 5)\n    >>= fun hlit => (readBitsLSB 5)\n    >>= fun hdist => (readBitsLSB 4)\n    >>= fun hclen => (CLCHeader (hclen + 4))\n    >>= fun clc lld =>\n          LitLenDist clc (hlit + 257) (hdist + 1) (fst lld) (snd lld).\n(* DCH2 *)\n\n(* DCB1 *)\nDefinition DynamicallyCompressedBlock\n  : SequenceWithBackRefs Byte -> LB -> Prop :=\n  DynamicallyCompressedHeader\n    >>= fun lld => CompressedSWBR (fst lld) (snd lld).\n(* DCB2 *)\n\n(** A statically compressed block is a block with defined static codings *)\n\n(* STATIC1 *)\nInductive StaticallyCompressedBlock\n             (output : SequenceWithBackRefs Byte) : LB -> Prop :=\n| makeSCB :\n    forall input,\n      CompressedSWBR fixed_lit_code fixed_dist_code output input ->\n      StaticallyCompressedBlock output input.\n(* STATIC2 *)\n\n(** The natural argument denotes the bits that have already been\nread. Padding is assured by making the bit count a multiple of\neight. *)\n\n(* TOPLEVEL5 *)\nInductive OneBlockWithPadding\n  (out : SequenceWithBackRefs Byte) : nat -> LB -> Prop :=\n| obwpDCB : forall dcb n,\n  DynamicallyCompressedBlock out dcb ->\n   OneBlockWithPadding out n (false :: true :: dcb)\n| obwpSCB : forall scb n, StaticallyCompressedBlock out scb ->\n   OneBlockWithPadding out n (true :: false :: scb)\n| obwpUCB : forall ucb n m pad,\n   UncompressedBlockDirect out ucb ->\n   n + ll (false :: false :: pad) = 8 * m ->\n   ll pad < 8 ->\n   OneBlockWithPadding out n (false :: false :: pad ++ ucb).\n(* TOPLEVEL6 *)\n\t\t\t\t\t\t     \n(* TOPLEVEL3 *)\nInductive ManyBlocks : nat -> SequenceWithBackRefs Byte\n\t\t\t\t\t  -> LB -> Prop :=\n| lastBlock : forall n inp out,\n                OneBlockWithPadding out (n + 1) inp ->\n                ManyBlocks n out (true :: inp)\n| middleBlock : forall n inp1 inp2 out1 out2,\n    OneBlockWithPadding out1 (n + 1) inp1 ->\n    ManyBlocks (n + 1 + ll inp1) out2 inp2 ->\n    ManyBlocks n (out1 ++ out2) (false :: inp1 ++ inp2).\n(* TOPLEVEL4 *)\n\n(* TOPLEVEL1 *)\nInductive DeflateEncodes (out : LByte) (inp : LB) : Prop :=\n| deflateEncodes : forall swbr,\n                     ManyBlocks 0 swbr inp ->\n                     ResolveBackReferences swbr out ->\n                     DeflateEncodes out inp.\n(* TOPLEVEL2 *)\n", "meta": {"author": "dasuxullebt", "repo": "DampFnudeL", "sha": "6b0496d0ed5af23199bf0a03e04dbb9bb0373873", "save_path": "github-repos/coq/dasuxullebt-DampFnudeL", "path": "github-repos/coq/dasuxullebt-DampFnudeL/DampFnudeL-6b0496d0ed5af23199bf0a03e04dbb9bb0373873/EncodingRelation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24147948942250042}}
{"text": "Require Import erasure. \nRequire Import IndependenceCommon. \nRequire Import stepWF. \n\nFixpoint specTerm (t:ptrm) := \n  match t with\n      |pfvar x => fvar x\n      |pbvar x => bvar x\n      |punit => unit\n      |ppair e1 e2 => pair_ (specTerm e1) (specTerm e2)\n      |plambda e => lambda (specTerm e)\n      |papp e1 e2 => AST.app (specTerm e1) (specTerm e2)\n      |pret e => ret (specTerm e)\n      |pbind e1 e2 => bind (specTerm e1) (specTerm e2)\n      |pfork e => fork (specTerm e)\n      |pnew => new\n      |pput e1 e2 => put (specTerm e1) (specTerm e2)\n      |pget e => get (specTerm e)\n      |praise e => raise (specTerm e)\n      |phandle e1 e2 => handle (specTerm e1) (specTerm e2)\n      |pfst e => fst (specTerm e)\n      |psnd e => snd (specTerm e)\n      |pspec e1 e2 => spec (specTerm e1) (specTerm e2)\n      |pspecRun e1 e2 => specRun (specTerm e1) (specTerm e2)\n      |pspecJoin e1 e2 => specJoin (specTerm e1) (specTerm e2)\n      |pdone e => done (specTerm e)\n  end. \n\nInductive gather : ptrm -> pool -> Prop :=\n|gFVar : forall x, gather (pfvar x) (Empty_set thread)\n|gBVar : forall x, gather (pbvar x) (Empty_set thread)\n|gUnit : gather punit (Empty_set thread)\n|gPair : forall e1 e2 T1 T2, gather e1 T1 -> gather e2 T2 -> \n                           gather (ppair e1 e2) (tUnion T1 T2)\n|gLam : forall e T, gather e T -> gather (plambda e) T\n|gApp : forall e1 e2 T1 T2, gather e1 T1 -> gather e2 T2 ->\n                          gather (papp e1 e2) (tUnion T1 T2)\n|gRet : forall e T, gather e T -> gather (pret e) T\n|gBind : forall e1 e2 T1 T2, gather e1 T1 -> gather e2 T2 ->\n                           gather (pbind e1 e2) (tUnion T1 T2)\n|gFork : forall e T, gather e T -> gather (pfork e) T\n|gNew : gather pnew (Empty_set thread)\n|gPut : forall e1 e2 T1 T2, gather e1 T1 -> gather e2 T2 ->\n                          gather (pput e1 e2) (tUnion T1 T2)\n|gGet : forall e T, gather e T -> gather (pget e) T\n|gRaise : forall e T, gather e T -> \n                            gather (praise e) T\n|gHandle : forall e1 e2 T1 T2, gather e1 T1 -> gather e2 T2 ->\n                             gather (phandle e1 e2) (tUnion T1 T2)\n|gFST : forall e T, gather e T -> gather (pfst e) T\n|gSND : forall e T, gather e T -> gather (psnd e) T\n|gSpec : forall e1 e2 T1 T2, gather e1 T1 -> gather e2 T2 ->\n                           gather (pspec e1 e2) (tUnion T1 T2)\n|gSpecJoin : forall e1 e2 T1 T2, gather e1 T1 -> gather e2 T2 ->\n                               gather (pspecJoin e1 e2) (tUnion T1 T2)\n|gDone : forall e T, gather e T -> gather (pdone e) T\n|gSpecRun : forall e1 e2 T1 T2 tid, \n            gather e1 T1 -> gather e2 T2 -> \n            gather (pspecRun e1 e2) \n                   (tUnion (tUnion T1 T2)\n                           (tSingleton(tid,specStack [] (specTerm e2), nil, specTerm e2))).\n\nInductive speculate : pPool -> pool -> Prop :=\n|specCons : forall t Ts Ts' tid s2 T,\n              speculate Ts Ts' -> gather t T ->\n              speculate (t::Ts) (tUnion T ((tid,unlocked nil,s2,specTerm t)::Ts'))\n|specNil : speculate nil nil.\n\nInductive raw_specHeap : rawHeap pivar_state -> rawHeap ivar_state -> Prop :=\n|specConsFull : forall i tid M H H',\n                  raw_specHeap H H' -> \n                  raw_specHeap ((i, pfull M)::H) ((i, sfull COMMIT nil COMMIT tid (specTerm M))::H')\n|specConsEmpty : forall i H H', raw_specHeap H H' -> \n                                raw_specHeap((i, pempty)::H) ((i, sempty COMMIT)::H')\n|specHeapNil : raw_specHeap nil nil. \n\nTheorem specUnique : forall H S H',\n                       unique pivar_state S H -> raw_specHeap H H' ->\n                       unique ivar_state S H'. \nProof.\n  intros. generalize dependent S. induction H1; intros; auto; inv H0; auto. \nQed. \n\nInductive specHeap : pHeap -> sHeap -> Prop :=\n|specHeap' : forall h h' proof (p':raw_specHeap h h'), \n               specHeap (heap_ pivar_state h proof)\n                        (heap_ ivar_state h' (specUnique h (Ensembles.Empty_set AST.id) h' proof p')). \n\nTheorem raw_specHeapReplaceFull : forall x tid M H H',\n              raw_specHeap H H' -> raw_heap_lookup x H = Some pempty ->\n              raw_specHeap (raw_replace x (pfull M) H) (raw_replace x (sfull COMMIT nil COMMIT tid (specTerm M)) H').         \nProof.\n  intros. genDeps{x; tid; M}. induction H0; intros. \n  {simpl. destruct (beq_nat x i) eqn:eq. \n   {constructor. auto. }\n   {constructor. simpl in *. rewrite eq in H1. eauto. }\n  }\n  {simpl in *. destruct (beq_nat x i) eqn:eq. \n   {constructor. auto. }\n   {constructor. auto. }\n  }\n  {constructor. }\nQed. \n\nTheorem specHeapReplaceFull : forall x tid M H H',\n              specHeap H H' -> heap_lookup x H = Some pempty ->\n              specHeap (replace x (pfull M) H) (replace x (sfull COMMIT nil COMMIT tid (specTerm M)) H').         \nProof.\n  intros. destruct H. simpl. destruct H'. simpl. erewrite rawHeapsEq; auto. \n  erewrite (rawHeapsEq ivar_state); auto. apply specHeap'. \n  Grab Existential Variables. eapply raw_specHeapReplaceFull; auto. inv H0. auto. \n  apply replacePreservesUniqueness. auto. \nQed. \n\nTheorem UnionEqR' : forall (U:Type) (T T1 T2:multiset U), T1 = T2 -> Union U T T1 = Union U T T2. \nProof.\n  intros. subst; auto. \nQed. \n\nTheorem UnionEqL' : forall U (T T1 T2:multiset U), T1 = T2 -> Union U T1 T = Union U T2 T. \nProof.\n  intros. subst; auto. \nQed. \n\nTheorem specUnionComm : forall T1 T2 T,\n                          speculate (pUnion T1 T2) T ->\n                          exists T1' T2', (speculate T1) T1' /\\ (speculate T2) T2' /\\\n                          T = tUnion T1' T2' . \nProof.\n  induction T1; intros. \n  {simpl in *. econstructor. econstructor. split; eauto. constructor. \n   split; eauto. }\n  {simpl in *. inv H.  \n   {eapply IHT1 in H2. invertHyp. econstructor. econstructor. split. \n    econstructor. eauto. eauto. split; eauto. unfoldTac.\n    rewrite <- Union_associative. simpl. auto. }\n  }\nQed. \n\nTheorem singleton : forall (t:thread), [t] = tSingleton t. auto. Qed. \n\n\nTheorem specUnionL : forall T1 T2 T1' T2', \n                       speculate T1 T1' -> speculate T2 T2' ->\n                       speculate (pUnion T1 T2) (tUnion T1' T2'). \nProof.\n  induction T1; intros. \n  {simpl. inv H. simpl. auto. }\n  {inv H. eapply IHT1 in H0; eauto. simpl. unfoldTac. rewrite <- Union_associative.  \n   eapply specCons. eassumption. auto. }\nQed. \n\nFixpoint specCtxt E := \n  match E with\n      |pbindCtxt E e => bindCtxt (specCtxt E) (specTerm e)\n      |phandleCtxt E e => handleCtxt (specCtxt E) (specTerm e)\n      |pappCtxt E e => appCtxt (specCtxt E) (specTerm e)\n      |pappValCtxt E e => appValCtxt (specCtxt E) (specTerm e)\n      |ppairCtxt E e => pairCtxt (specCtxt E) (specTerm e)\n      |ppairValCtxt E e => pairValCtxt (specCtxt E) (specTerm e)\n      |pfstCtxt E => fstCtxt (specCtxt E)\n      |psndCtxt E => sndCtxt (specCtxt E)\n      |pspecRunCtxt E e => specRunCtxt (specCtxt E) (specTerm e)\n      |pspecJoinCtxt E e => specJoinCtxt (specCtxt E) (specTerm e)\n      |pholeCtxt => holeCtxt\n  end. \n\nTheorem consNil : forall (T:Type) (a:T), [a] = a::nil. auto. Qed. \n\nTheorem eSpecTerm : forall e, exists e', specTerm e' = e. \nProof.\n  induction e; intros; try invertHyp. \n  {exists (pfvar i). auto. }\n  {exists (pbvar i). auto. }\n  {exists punit; auto. }\n  {exists (ppair x0 x). auto. }\n  {exists (plambda x); auto. }\n  {exists (papp x0 x); auto. }\n  {exists (pret x); auto. }\n  {exists (pbind x0 x); auto. }\n  {exists (pfork x); auto. }\n  {exists pnew; auto. }\n  {exists (pput x0 x); auto. }\n  {exists (pget x); auto. }\n  {exists (praise x); auto. }\n  {exists (phandle x0 x); auto. }\n  {exists (pspec x0 x); auto. }\n  {exists (pspecRun x0 x); auto. }\n  {exists (pspecJoin x0 x); auto. }\n  {exists (pfst x); auto. }\n  {exists (psnd x); auto. }\n  {exists (pdone x); auto. }\nQed.  \n\nTheorem specFill : forall E e, specTerm (pfill E e) = fill (specCtxt E) (specTerm e). \nProof.\n  induction E; intros; try solve[simpl; erewrite IHE; eauto]. \n  simpl. auto. \nQed. \n\nTheorem gatherTotal : forall e, exists T, gather e T.\nProof.\n  induction e; try solve[repeat econstructor]; \n  try solve[invertHyp; econstructor; econstructor; eauto]. \n  Grab Existential Variables. constructor. \nQed. \n\nTheorem UnionSwapL: forall (X : Type) (T1 T2 T3 : multiset X),\n                      Union X (Union X T1 T2) T3 = Union X (Union X T3 T2) T1.\nProof.\n  intros. rewrite (Union_commutative X T1). rewrite UnionSwap. \n  rewrite (Union_commutative X T2). auto. Qed. \n\nTheorem specOpen : forall e e' n, \n                     specTerm (popen n e e') = open n (specTerm e) (specTerm e').\nProof.\n  induction e'; intros; auto; try solve[simpl;rewrite IHe'1; rewrite IHe'2; eauto];\n  try solve[simpl; rewrite IHe'; eauto]. \n  {simpl. destruct (beq_nat n i); auto. }\nQed. \n\n\nTheorem specUnionComm' : forall T1 T1' T2 T2', \n                           speculate T1 T1' -> speculate T2 T2' ->\n                           speculate (pUnion T1 T2) (tUnion T1' T2'). \nProof.\n  induction T1; intros. \n  {inv H. auto. }\n  {inv H. simpl. unfoldTac. rewrite <- Union_associative. constructor; eauto. }\nQed. \n\nInductive gatherCtxt : pctxt -> pool -> Prop :=\n|gBindCtxt : forall E t T1 T2, gather t T1 -> gatherCtxt E T2 ->\n                         gatherCtxt (pbindCtxt E t) (tUnion T1 T2)\n|gHandleCtxt : forall E t T1 T2, gather t T1 -> gatherCtxt E T2 ->\n                                 gatherCtxt(phandleCtxt E t) (tUnion T1 T2)\n|gAppCtxt : forall E t T1 T2, gather t T1 -> gatherCtxt E T2 ->\n                              gatherCtxt(pappCtxt E t) (tUnion T1 T2)\n|gAppValCtxt : forall E t T1 T2, gather t T1 -> gatherCtxt E T2 ->\n                                 gatherCtxt (pappValCtxt E t) (tUnion T1 T2)\n|gFstCtxt : forall E T, gatherCtxt E T -> gatherCtxt (pfstCtxt E) T\n|gSndCtxt : forall E T, gatherCtxt E T -> gatherCtxt (psndCtxt E) T\n|gPairCtxt : forall E t T1 T2, gatherCtxt E T1 -> gather t T2 ->\n                               gatherCtxt (ppairCtxt E t) (tUnion T1 T2)\n|gPairValCtxt : forall E t T1 T2, gatherCtxt E T1 -> gather t T2 ->\n                                  gatherCtxt (ppairValCtxt E t) (tUnion T1 T2)\n|gSpecRunCtxt : forall E t T1 T2 tid, \n                  gatherCtxt E T1 -> gather t T2 ->\n                  gatherCtxt (pspecRunCtxt E t) (tUnion (tUnion T1 T2)\n                                                        (tSingleton(tid,specStack [] (specTerm t), nil, specTerm t)))\n|gSpecJoinCtxt : forall E t T1 T2, gatherCtxt E T1 -> gather t T2 ->\n                                   gatherCtxt (pspecJoinCtxt E t) (tUnion T1 T2)\n|gHoleCtxt : gatherCtxt pholeCtxt (Empty_set thread). \n\nTheorem raw_specHeapLookupFull : forall x H M H',\n                               raw_heap_lookup x H = Some(pfull M) -> raw_specHeap H H' -> exists tid,\n                               raw_heap_lookup x H' = Some(sfull COMMIT nil COMMIT tid (specTerm M)).\nProof.\n  induction H; intros. \n  {inv H. }\n  {simpl in *. destruct a. destruct (beq_nat x i) eqn:eq. \n   {inv H0. inv H1. simpl. rewrite eq. eauto. }\n   {destruct p; auto. inv H1. simpl. rewrite eq; auto. inv H1. simpl. rewrite eq; auto. }\n  }\nQed. \n\nTheorem specHeapLookupFull : forall x H M H',\n                               heap_lookup x H = Some(pfull M) -> specHeap H H' -> \n                               exists tid, heap_lookup x H' = Some(sfull COMMIT nil COMMIT tid (specTerm M)). \nProof.\n  intros. destruct H. simpl in *. inv H1. eapply raw_specHeapLookupFull in H0; eauto. \nQed. \n\nTheorem appSingle : forall (T:Type) (a:T) b, a::b = [a]++b. reflexivity. Qed. \n\nTheorem gatherCtxtTotal : forall E, exists T, gatherCtxt E T.\nProof.\n  induction E; intros; try( \n  match goal with\n      |t:ptrm |- _ => assert(exists T, gather t T) by apply gatherTotal\n  end); try invertHyp; econstructor; econstructor; eauto. \n  Grab Existential Variables. constructor. \nQed. \n\nLtac gatherTac e := try(assert(exists T, gather e T) by apply gatherTotal; invertHyp);\n                   try(assert(exists T, gatherCtxt e T) by apply gatherCtxtTotal; invertHyp). \n\nLtac gatherTac' es :=\n  match es with\n      |HNil => idtac\n      |HCons ?e ?es' => gatherTac e; gatherTac' es'\n  end. \n\nHint Constructors gather gatherCtxt. \n\nTheorem gatherDecomp : forall E t e T, \n                           pdecompose t E e ->\n                           gather t T -> exists T1 T2, gatherCtxt E T1 /\\\n                                                       gather e T2 /\\\n                                                       T = tUnion T1 T2. \nProof.\n  induction E; intros. \n  {inv H; inv H0. eapply IHE in H6; eauto. invertHyp. econstructor. econstructor. \n   split. constructor; eauto. split; eauto. unfoldTac. rewrite UnionSwap. \n   rewrite (Union_commutative thread x). auto. }\n  {inv H; inv H0. eapply IHE in H6; eauto. invertHyp. econstructor. econstructor. \n   split. constructor; eauto. split; eauto. unfoldTac. rewrite UnionSwap. \n   rewrite (Union_commutative thread x). auto. }\n  {inv H; inv H0. eapply IHE in H6; eauto. invertHyp. econstructor. econstructor. \n   split. constructor; eauto. split; eauto. unfoldTac. rewrite UnionSwapL. \n   rewrite UnionSwap. auto. }\n  {inv H; inv H0. eapply IHE in H7; eauto. invertHyp. econstructor. econstructor. \n   split; eauto. split; eauto. unfoldTac. rewrite Union_associative. auto. }\n  {inv H; inv H0. eapply IHE in H6; eauto. invertHyp. econstructor. econstructor. \n   split; eauto. split; eauto. unfoldTac. rewrite UnionSwap. auto. }\n  {inv H; inv H0. eapply IHE in H7; eauto. invertHyp. econstructor. econstructor. \n   split; eauto. split; eauto. unfoldTac. rewrite Union_associative. \n   rewrite (Union_commutative thread T1). auto. }\n  {inv H. inv H0. eapply IHE in H4; eauto. invertHyp. econstructor. eauto. }\n  {inv H. inv H0. eapply IHE in H4; eauto. invertHyp. econstructor. eauto. }\n  {inv H; inv H0. eapply IHE in H6; eauto. invertHyp. econstructor. econstructor. \n   split. constructor; eauto. split; eauto. unfoldTac. rewrite UnionSwap. \n   repeat rewrite <- Union_associative. apply UnionEqR'. rewrite Union_commutative. \n   repeat rewrite Union_associative. apply UnionEqL'. rewrite Union_commutative. auto. }\n  {inv H; inv H0. eapply IHE in H7; eauto. invertHyp. econstructor. econstructor. \n   split. eauto. split; eauto. unfoldTac. rewrite Union_associative. \n   rewrite (Union_commutative thread T1). auto. }\n  {inv H; econstructor; econstructor; eauto. }\nQed. \n\nTheorem gatherFill : forall E e T1 T2,\n                       gatherCtxt E T1 -> gather e T2 ->\n                       gather (pfill E e) (tUnion T1 T2). \nProof.\n  induction E; intros. \n  {inv H. eapply IHE in H5. Focus 2. eapply H0. simpl. unfoldTac. rewrite UnionSwapL.  \n   constructor; auto. rewrite Union_commutative. auto. }\n  {inv H. eapply IHE in H5. Focus 2. eapply H0. simpl. unfoldTac. rewrite UnionSwapL.  \n   constructor; auto. rewrite Union_commutative. auto. }\n  {inv H. eapply IHE in H5. Focus 2. eapply H0. simpl. unfoldTac. rewrite UnionSwapL. \n   constructor; auto. rewrite Union_commutative. auto. }\n  {inv H. eapply IHE in H5. Focus 2. eapply H0. simpl. unfoldTac.\n   rewrite <- Union_associative. constructor; auto. }\n  {inv H. eapply IHE in H3. Focus 2. eapply H0. simpl. unfoldTac. rewrite UnionSwap. \n   constructor; auto. }\n  {inv H. eapply IHE in H3. Focus 2. eapply H0. simpl. unfoldTac. \n   rewrite (Union_commutative thread T0). rewrite <- Union_associative. constructor; \n   auto. }\n  {inv H. eapply IHE in H2; eauto. simpl. constructor. auto. }\n  {inv H. eapply IHE in H2; eauto. simpl. constructor. auto. }\n  {inv H. eapply IHE in H3. Focus 2. eapply H0. simpl. unfoldTac.\n   rewrite UnionSwap. rewrite (UnionSwap thread T0). constructor; auto. }\n  {inv H. eapply IHE in H3. Focus 2. eapply H0. simpl. unfoldTac. rewrite UnionSwap. \n   rewrite Union_commutative. constructor; auto. }\n  {inv H. simpl. auto. }\nQed. \n\nTheorem listToSingle : forall (t:thread), [t] = Single thread t. auto. Qed. \n \nTheorem specVal : forall t, pval t <-> val (specTerm t).\nProof.\n  induction t; intros; split; intros; try solveByInv; inv H; try solve[ \n  repeat match goal with\n      |H:pval ?t <-> val ?t', H':pval ?t |- _ => apply H in H'\n  end; simpl; constructor; auto]. apply IHt1 in H2. apply IHt2 in H3.\n  constructor; auto. \nQed. \n\nTheorem notSpecVal : forall t, ~pval t <-> ~val (specTerm t). \nProof.\n  induction t; intros; split; intros; try solve[introsInv]; introsInv; try solve[apply H; \n  repeat match goal with\n           |H:val(specTerm ?t) |- _ => apply specVal in H\n         end; auto].  \n  {apply H. simpl. apply specVal in H3. apply specVal in H4. auto. }\n  {apply H. simpl. constructor. }\n  {apply H. simpl; auto.  }\n  {apply H. simpl; auto. }\nQed. \n\nTheorem decomposeSpec : forall t E e, \n                          pdecompose t E e ->\n                          decompose (specTerm t) (specCtxt E) (specTerm e). \nProof.\n  induction t; intros; try solveByInv; try solve[inv H; constructor]. \n  {inv H. eapply IHt1 in H5; eauto. simpl. constructor. apply notSpecVal; auto. \n   eauto. simpl. constructor. apply specVal; auto. apply notSpecVal; auto. \n   eapply IHt2 in H6; eauto. }\n  {inv H. eapply IHt1 in H5; eauto. simpl. constructor. apply notSpecVal; auto. \n   eauto. simpl. constructor. apply specVal; auto. apply notSpecVal; auto. \n   eapply IHt2 in H6; eauto. simpl. constructor. apply specVal; auto. apply specVal; auto. }\n  {inv H. eapply IHt1 in H5; eauto. simpl. constructor. apply notSpecVal; auto. \n   eauto. simpl. constructor. apply specVal; auto. }\n  {inv H. eapply IHt1 in H5; eauto. simpl. constructor. apply notSpecVal; auto. \n   eauto. simpl. constructor. apply specVal; auto. }\n  {inv H. eapply IHt in H2; eauto. simpl. constructor; eauto. apply notSpecVal; eauto. \n   simpl. constructor. apply specVal ;auto. }\n  {inv H. eapply IHt in H2; eauto. simpl. constructor; eauto. apply notSpecVal; eauto. \n   simpl. constructor. apply specVal ;auto. }\n  {inv H. eapply IHt1 in H5; eauto. simpl. constructor. apply notSpecVal; auto. \n   eauto. simpl. constructor. apply specVal; auto. }\n  {inv H. eapply IHt2 in H6; eauto. simpl. constructor. apply specVal; auto. \n   apply notSpecVal; auto. eauto. simpl; constructor. apply specVal; auto. \n   apply specVal; auto. }\nQed. \n\nTheorem AddUnion : forall (X:Type) T e, Add X T e = Union X T (Single X e). auto. Qed. \n\nFixpoint psourceProg t :=\n  match t with\n      |pfvar x => True\n      |pbvar x => True\n      |punit => True\n      |ppair e1 e2 => psourceProg e1 /\\ psourceProg e2\n      |plambda e => psourceProg e\n      |papp e1 e2 => psourceProg e1 /\\ psourceProg e2\n      |pret e => psourceProg e\n      |pbind e1 e2 => psourceProg e1 /\\ psourceProg e2\n      |pfork e => psourceProg e\n      |pnew => True\n      |pput e1 e2 => psourceProg e1 /\\ psourceProg e2\n      |pget e => psourceProg e\n      |praise e => psourceProg e\n      |phandle e1 e2 => psourceProg e1 /\\ psourceProg e2\n      |pspec e1 e2 => psourceProg e1 /\\ psourceProg e2\n      |pspecRun e1 e2 => False\n      |pspecJoin e1 e2 => False\n      |pfst e => psourceProg e\n      |psnd e => psourceProg e\n      |pdone e => psourceProg e\n  end. \n\nTheorem pval_dec : forall t, (pval t) + (~pval t). \nProof.\n  induction t; intros; try solve[left; auto]; try solve[right; introsInv]. \n  {inv IHt1; inv IHt2. left; auto. right. introsInv. contradiction.\n   right. introsInv. contradiction. right. introsInv. contradiction. }\nQed. \n\nFixpoint ptermWF t :=\n  match t with\n      |pfvar x => True\n      |pbvar x => True\n      |punit => True\n      |ppair e1 e2 => if pval_dec e1\n                      then if pval_dec e2\n                           then psourceProg e1 /\\ psourceProg e2\n                           else ptermWF e1 /\\ ptermWF e2\n                      else ptermWF e1 /\\ ptermWF e2\n      |plambda e => psourceProg e\n      |papp e1 e2 => ptermWF e1 /\\ ptermWF e2\n      |pret e => psourceProg e\n      |pbind e1 e2 => ptermWF e1 /\\ psourceProg e2\n      |pfork e => psourceProg e\n      |pnew => True\n      |pput e1 e2 => ptermWF e1 /\\ psourceProg e2\n      |pget e => ptermWF e\n      |praise e => psourceProg e\n      |phandle e1 e2 => ptermWF e1 /\\ psourceProg e2\n      |pspec e1 e2 => psourceProg e1 /\\ psourceProg e2\n      |pspecRun e1 e2 => ptermWF e1 /\\ psourceProg e2\n      |pspecJoin e1 e2 => ptermWF e1 /\\ ptermWF e2\n      |pfst e => ptermWF e\n      |psnd e => ptermWF e\n      |pdone e => psourceProg e\n  end. \n\nFixpoint PoolWF (T:pPool) :=\n  match T with\n      |t::ts => ptermWF t /\\ PoolWF ts\n      |nil => True\n  end. \n\nTheorem poolWFComm : forall T1 T2, PoolWF (pUnion T1 T2) <-> (PoolWF T1 /\\ PoolWF T2). \nProof.\n  induction T1; intros; split; intros. \n  {simpl in *. auto. }\n  {simpl in *. invertHyp; auto. }\n  {simpl in *. invertHyp. apply IHT1 in H1. invertHyp. auto. }\n  {simpl in *. invertHyp. split; auto. apply IHT1. auto. }\nQed. \n\nTheorem sourceProgWF : forall t, psourceProg t -> ptermWF t. \nProof.\n  induction t; intros; auto; \n  simpl in *; try invertHyp;  auto. \n  destruct (pval_dec t1). \n  {destruct (pval_dec t2). \n   {split; auto. }\n   {split; eauto. }\n  }\n  {split; auto. }\n  {contradiction. }\n  {contradiction. }\nQed.  \n\nTheorem ptrmDecomposeWF : forall t E e, pdecompose t E e -> ptermWF t -> ptermWF e. \nProof.\n  intros. induction H; eauto; try solve[ inv H0; auto]. \n  {simpl in *. destruct (pval_dec M). contradiction. invertHyp. eauto. }\n  {simpl in *. Hint Resolve sourceProgWF. destruct (pval_dec M); destruct (pval_dec N); \n   invertHyp; apply IHpdecompose; auto. }\nQed. \n\nHint Constructors gather. \n\nTheorem gatherSourceProg : forall M T, psourceProg M -> gather M T -> T = Empty_set thread. \nProof.\n  induction M; intros; try solve[inv H0; auto].\n  {inv H. inv H0. eapply IHM1 in H1;[idtac|eauto]. \n   eapply IHM2 in H2;[idtac|eauto]. subst. auto. }\n  {inv H. inv H0. eapply IHM1 in H1;[idtac|eauto]. \n   eapply IHM2 in H2;[idtac|eauto]. subst. auto. }\n  {inv H. inv H0. eapply IHM1 in H1;[idtac|eauto]. \n   eapply IHM2 in H2;[idtac|eauto]. subst. auto. }\n  {inv H. inv H0. eapply IHM1 in H1;[idtac|eauto]. \n   eapply IHM2 in H2;[idtac|eauto]. subst. auto. }\n  {inv H. inv H0. eapply IHM1 in H1;[idtac|eauto]. \n   eapply IHM2 in H2;[idtac|eauto]. subst. auto. }\n  {inv H. inv H0. eapply IHM1 in H1;[idtac|eauto]. \n   eapply IHM2 in H2;[idtac|eauto]. subst. auto. }\n  {inv H. }\n  {inv H. }\nQed.\n\nFixpoint raw_heapWF (H:rawHeap pivar_state) :=\n  match H with\n      |(_, pempty)::H' => raw_heapWF H'\n      |(_, pfull M)::H' => psourceProg M /\\ raw_heapWF H'\n      |[] => True\n  end. \n\nDefinition heapWF H :=\n  match H with\n      |heap_ h p => raw_heapWF h\n  end. \n\nTheorem raw_lookupSourceProg : forall x H M, \n                             raw_heapWF H -> raw_heap_lookup x H = Some(pfull M) ->\n                             psourceProg M. \nProof.\n  induction H; intros. \n  {inv H0. }\n  {simpl in *. destruct a. destruct (beq_nat x i) eqn:eq. \n   {inv H1. invertHyp. auto. }\n   {destruct p. apply IHlist; auto. invertHyp. apply IHlist; auto. }\n  }\nQed. \n\nTheorem lookupSourceProg : forall x H M, \n                             heapWF H -> heap_lookup x H = Some(pfull M) ->\n                             psourceProg M. \nProof.\n  intros. destruct H. eapply raw_lookupSourceProg; eauto. \nQed. \n\nTheorem raw_specHeapLookupEmpty : forall x H H',\n                               raw_heap_lookup x H = Some pempty -> raw_specHeap H H' -> \n                               raw_heap_lookup x H' = Some(sempty COMMIT).\nProof.\n  induction H; intros. \n  {inv H. }\n  {simpl in *. destruct a. destruct (beq_nat x i) eqn:eq. \n   {inv H0. inv H1. simpl. rewrite eq. auto. }\n   {inv H1. simpl. rewrite eq. eauto. simpl. rewrite eq. eauto. }\n  }\nQed. \n\nTheorem specHeapLookupEmpty : forall x H H',\n                               heap_lookup x H = Some pempty -> specHeap H H' ->\n                               heap_lookup x H' = Some(sempty COMMIT).\nProof.\n  intros. destruct H. simpl. inv H1. eapply raw_specHeapLookupEmpty in H0; eauto. \nQed. \n\nTheorem specHeapExtend : forall x H H' p p',\n                           heap_lookup x H = None -> specHeap H H' ->\n                           specHeap(Heap.extend x pempty H p) (Heap.extend x (sempty COMMIT) H' p'). \nProof.\n  intros. destruct H. simpl in *. erewrite rawHeapsEq; eauto. destruct H'. simpl. \n  erewrite (rawHeapsEq ivar_state). constructor. auto.  \n  Grab Existential Variables. unfold raw_extend. constructor. inv H1. auto. \n  apply extendPreservesUniqueness with(prf := u). simpl. assumption. assumption. \nQed. \n\nTheorem raw_specHeapLookupNone : forall H H' x, \n                               raw_specHeap H H' -> raw_heap_lookup x H = None ->\n                               raw_heap_lookup x H' = None. \nProof.\n  induction H; intros. \n  {inv H. auto. }\n  {simpl in *. destruct a. destruct (beq_nat x i) eqn:eq. \n   {solveByInv. }\n   {inv H0. simpl. rewrite eq. eauto. simpl. rewrite eq. auto. }\n  }\nQed. \n\nTheorem specHeapLookupNone : forall H H' x, \n                               specHeap H H' -> heap_lookup x H = None ->\n                               heap_lookup x H' = None. \nProof.\n  intros. destruct H. simpl in *. inv H0. simpl. eapply raw_specHeapLookupNone; eauto. \nQed. \n\n\nTheorem simBasicStep : forall t t', \n                         pbasic_step t t' ->\n                         basic_step (specTerm t) (specTerm t'). \nProof.\n  intros. inv H. \n  {rewrite specFill. rewrite specOpen. eapply basicBeta. apply decomposeSpec in H0. \n   eauto. }\n  {rewrite specFill. eapply basicProjL. apply decomposeSpec in H0. simpl in *; eauto. }\n  {rewrite specFill. eapply basicProjR. apply decomposeSpec in H0. simpl in *; eauto. }\n  {rewrite specFill. eapply basicBind. apply decomposeSpec in H0. eauto. }\n  {rewrite specFill. eapply basicBindRaise. apply decomposeSpec in H0. eauto. }\n  {rewrite specFill. apply basicHandle. apply decomposeSpec in H0. eauto. }\n  {rewrite specFill. eapply basicHandleRet. apply decomposeSpec in H0. eauto. }\n  {rewrite specFill. eapply specJoinRaise. apply decomposeSpec in H0. simpl in *. eauto. }\n  {rewrite specFill. eapply specJoinRet. apply decomposeSpec in H0. simpl in *. eauto. }\nQed. \n\nTheorem pvalSourceProg : forall t, ptermWF t -> pval t -> psourceProg t. \nProof.\n  induction t; intros; try solveByInv; auto.  \n  {inv H0. simpl in *. destruct (pval_dec t1); try contradiction. \n   destruct (pval_dec t2); try contradiction. auto. }\nQed. \n\nTheorem pdecomposeApp : forall E t e N, pdecompose t E (papp (plambda e) N) -> ptermWF t ->\n                                     psourceProg e /\\ psourceProg N.\nProof. \n  induction E; intros; try solve[inv H; eauto]. \n  {inv H. inv H0. eapply IHE. eauto. auto. }\n  {inv H. inv H0. eapply IHE. eauto. auto. }\n  {inv H. inv H0. eapply IHE. eauto. auto. }\n  {inv H. inv H0. eapply IHE. eauto. auto. }\n  {inv H. simpl in *. destruct (pval_dec M). contradiction. invertHyp. \n   eauto. }\n  {inv H. simpl in *. destruct (pval_dec p). destruct (pval_dec N0). \n   contradiction. invertHyp. eauto. contradiction. }\n  {inv H. inv H0. eauto. }\n  {inv H. inv H0. eauto. }\n  {inv H. inv H0. simpl in *. apply pvalSourceProg in H1; auto. }\nQed. \nHint Resolve sourceProgWF.\n\nTheorem UnionEqEmpty : forall A T1 T2, Union A T1 T2 = Empty_set A -> T1 = Empty_set A /\\\n                                                                      T2 = Empty_set A. \nProof.\n  intros. destruct T1; destruct T2; auto; simpl in *; inv H.  Qed. \n\n\nTheorem gatherOpen : forall e' n e, gather e (Empty_set thread) -> gather e' (Empty_set thread) ->\n                                      gather (popen n e e') (Empty_set thread).\nProof.\n  induction e'; intros; auto; try solve[simpl in *; inv H0; eauto];\n  try solve[simpl; inv H0; apply UnionEqEmpty in H3; invertHyp; constructor; auto]. \n  {simpl. destruct (beq_nat n i); auto. }\n  {inv H0. unfoldTac. rewrite Union_commutative in H3. inv H3. }\nQed. \n\nTheorem pdecomposeFST : forall E t e, pdecompose t E (pfst e) -> ptermWF t ->\n                                      gather e (Empty_set thread). \nProof.\n  induction E; intros; try solve[inv H; inv H0; eauto]. \n  {inv H. simpl in *. destruct (pval_dec M); try contradiction. invertHyp. eauto. }\n  {inv H. simpl in *. destruct (pval_dec p); try contradiction. \n   destruct (pval_dec N); try contradiction. invertHyp. eauto. }\n  {inv H. simpl in *. eauto. }\n  {inv H. simpl in *. eauto. }\n  {inv H. apply pvalSourceProg in H3; auto. gatherTac e. copy H1.  \n   eapply gatherSourceProg in H1; eauto. subst. auto. }\nQed. \n\nTheorem pdecomposeSND : forall E t e, pdecompose t E (psnd e) -> ptermWF t ->\n                                      gather e (Empty_set thread). \nProof.\n  induction E; intros; try solve[inv H; inv H0; eauto]. \n  {inv H. simpl in *. destruct (pval_dec M); try contradiction. invertHyp. eauto. }\n  {inv H. simpl in *. destruct (pval_dec p); try contradiction. \n   destruct (pval_dec N); try contradiction. invertHyp. eauto. }\n  {inv H. simpl in *. eauto. }\n  {inv H. simpl in *. eauto. }\n  {inv H. apply pvalSourceProg in H3; auto. gatherTac e. copy H1.  \n   eapply gatherSourceProg in H1; eauto. subst. auto. }\nQed. \n\nTheorem gatherEmptyUnique : forall t T, gather t (Empty_set thread) -> gather t T ->\n                                        T = Empty_set thread. \nProof.\n  induction t; intros; try solve[inv H0; auto]; try solve[inv H; inv H0; eauto]. \n  {inv H. inv H0. apply UnionEqEmpty in H3. invertHyp. eapply IHt1 in H2; auto. \n   eapply IHt2 in H7; auto. subst. auto. }\n  {inv H. inv H0. apply UnionEqEmpty in H3. invertHyp. eapply IHt1 in H2; auto. \n   eapply IHt2 in H7; auto. subst. auto. }\n  {inv H. inv H0. apply UnionEqEmpty in H3. invertHyp. eapply IHt1 in H2; auto. \n   eapply IHt2 in H7; auto. subst. auto. }\n  {inv H. inv H0. apply UnionEqEmpty in H3. invertHyp. eapply IHt1 in H2; auto. \n   eapply IHt2 in H7; auto. subst. auto. }\n  {inv H. inv H0. apply UnionEqEmpty in H3. invertHyp. eapply IHt1 in H2; auto. \n   eapply IHt2 in H7; auto. subst. auto. }\n  {inv H. inv H0. apply UnionEqEmpty in H3. invertHyp. eapply IHt1 in H2; auto. \n   eapply IHt2 in H7; auto. subst. auto. }\n  {inv H. unfoldTac. rewrite Union_commutative in H3. inv H3. }\n  {inv H. inv H0. apply UnionEqEmpty in H3. invertHyp. eapply IHt1 in H2; auto. \n   eapply IHt2 in H7; auto. subst. auto. }\nQed. \n\n\nTheorem decomposeSpecJoin : forall E t N M, pdecompose t E (pspecJoin N M) -> ptermWF t ->\n                                            gather N (Empty_set thread). \nProof.\n  induction E; intros; try solve[inv H; eauto]; try solve[inv H; inv H0; eauto]. \n  {inv H. simpl in *. destruct (pval_dec M0); try contradiction. invertHyp. eauto. }\n  {inv H. simpl in *. destruct (pval_dec p); try contradiction. \n   destruct (pval_dec N0); try contradiction. invertHyp. eauto. }\n  {inv H. simpl in H0. invertHyp. eapply pvalSourceProg in H4; auto. gatherTac N.\n   copy H2. eapply gatherSourceProg in H2; eauto. subst. auto. }\nQed. \n\nTheorem basicStepGather : forall t t' T, \n                            pbasic_step t t' -> ptermWF t -> \n                            gather t T -> gather t' T. \nProof.\n  intros. inv H. \n  {copy H2. eapply gatherDecomp in H2; eauto. invertHyp. copy H.  \n   apply pdecomposeApp in H; eauto. invertHyp. inv H2.\n   eapply gatherSourceProg in H6; eauto. subst. unfoldTac. apply gatherFill. \n   auto. copy H8. apply gatherSourceProg in H8; auto. subst. simpl. apply gatherOpen; auto. \n   inv H. auto. }\n  {copy H2. eapply gatherDecomp in H2; eauto. invertHyp. copy H. apply gatherFill; auto. \n   apply pdecomposeFST in H4; auto. inv H4. apply UnionEqEmpty in H7. invertHyp. \n   inv H2. inv H5. eapply gatherEmptyUnique in H6; auto. subst.\n   apply gatherEmptyUnique in H10; auto. subst. simpl. auto. }\n  {copy H2. eapply gatherDecomp in H2; eauto. invertHyp. copy H. apply gatherFill; auto. \n   apply pdecomposeSND in H4; auto. inv H4. apply UnionEqEmpty in H7. invertHyp. \n   inv H2. inv H5. eapply gatherEmptyUnique in H6; auto. subst.\n   apply gatherEmptyUnique in H10; auto. subst. simpl. auto. }\n  {copy H2. eapply gatherDecomp in H2; eauto. invertHyp. copy H. apply gatherFill; auto.\n   inv H2. unfoldTac. rewrite Union_commutative. constructor; auto. inv H7. auto. }\n  {copy H2. eapply gatherDecomp in H2; eauto. invertHyp. copy H. apply gatherFill; auto.\n   inv H2. eapply ptrmDecomposeWF in H0; eauto. inv H0. eapply gatherSourceProg in H5; eauto. \n   subst. unfoldTac. rewrite union_empty_r. auto. }\n  {copy H2. eapply gatherDecomp in H2; eauto. invertHyp. copy H. apply gatherFill; auto.\n   inv H2. unfoldTac. rewrite Union_commutative. constructor; auto. inv H7; auto. }\n  {copy H2. eapply gatherDecomp in H2; eauto. invertHyp. copy H. apply gatherFill; auto.\n   inv H2. eapply ptrmDecomposeWF in H0; eauto. inv H0. eapply gatherSourceProg in H5; eauto. \n   subst. unfoldTac. rewrite union_empty_r. auto. }\n  {copy H2. apply decomposeSpecJoin in H2; auto. inv H2. eapply gatherDecomp in H; eauto. \n   invertHyp. apply gatherFill; auto. inv H. inv H6. eapply gatherEmptyUnique in H3; eauto. \n   subst. simpl. auto. }\n  {copy H2. eapply gatherDecomp in H2; eauto. invertHyp. copy H. apply gatherFill; auto.\n   inv H2. unfoldTac. constructor; auto. constructor. inv H7. auto. inv H9; auto. }\nQed. \n \nTheorem fillWF : forall t E e e', pdecompose t E e -> ptermWF (pfill E e) -> ptermWF e' ->\n                                  ptermWF (pfill E e'). \nProof.\n  intros. generalize dependent e'. induction H; intros; try solve[\n  simpl in *; invertHyp; eauto]; try solve[simpl in *; eauto]. \n  {simpl in *. destruct (pval_dec (pfill E M')). copy H1. \n   apply pdecomposeEq in H1. subst. contradiction. invertHyp.\n   destruct (pval_dec (pfill E e')). \n   {destruct (pval_dec N); eauto. apply pvalSourceProg in p0; auto. split; auto. \n    apply pvalSourceProg in p; auto. }\n   {destruct (pval_dec N); eauto. }\n  }\n  {simpl in *. destruct (pval_dec M); try contradiction. destruct (pval_dec (pfill E N')). \n   apply pdecomposeEq in H2. subst. contradiction. invertHyp.\n   destruct (pval_dec(pfill E e')); eauto. apply pvalSourceProg in p0; auto. split; auto. \n   apply pvalSourceProg in H; auto. }\nQed. \n\nTheorem openSourceProg : forall e' n e, psourceProg e -> psourceProg e' ->\n                                        psourceProg (popen n e e'). \nProof.\n  induction e'; intros; auto; try solve[simpl in *; try invertHyp; eauto]. \n  {simpl. destruct (beq_nat n i); auto. }\nQed. \n\nTheorem raw_replaceSourceProg : forall x H M, \n                              raw_heapWF H -> psourceProg M -> raw_heapWF (raw_replace x (pfull M) H).\nProof.\n  induction H; intros. \n  {constructor. }\n  {simpl in *. destruct a. destruct (beq_nat x i) eqn:eq. \n   {simpl. split. auto. destruct p. auto. invertHyp; auto. }\n   {simpl. destruct p. eauto. invertHyp.  split; eauto. }\n  }\nQed. \n\nTheorem replaceSourceProg : forall x H M, \n                              heapWF H -> psourceProg M -> heapWF (replace x (pfull M) H).\nProof.\n  intros. destruct H. simpl. eapply raw_replaceSourceProg; eauto. \nQed. \n\nTheorem pstepWF : forall H T t H' t', \n                    PoolWF (pUnion T t) -> pstep H T t (pOK H' T t') -> heapWF H ->\n                    PoolWF (pUnion T t') /\\ heapWF H'. \nProof.\n  intros. inv H1. \n  {rewrite poolWFComm in *. invertHyp. split; auto. inv H7. \n   {simpl in *. invertHyp. repeat split; auto. copy H0. eapply fillWF; eauto. \n    apply pdecomposeEq in H1. subst. auto. apply sourceProgWF.\n    apply pdecomposeApp in H0; auto. invertHyp. apply openSourceProg; auto. }\n   {simpl in *. invertHyp. repeat split; auto. copy H0. eapply fillWF; eauto. \n    apply pdecomposeEq in H1. subst. auto. apply ptrmDecomposeWF in H0; auto.\n    simpl in H0. destruct (pval_dec V1); destruct (pval_dec V2); invertHyp; auto. }\n   {simpl in *. invertHyp. repeat split; auto. copy H0. eapply fillWF; eauto. \n    apply pdecomposeEq in H1. subst. auto. apply ptrmDecomposeWF in H0; auto.\n    simpl in H0. destruct (pval_dec V1); destruct (pval_dec V2); invertHyp; auto. }\n   {simpl in *. invertHyp. repeat split; auto. copy H0. eapply fillWF; eauto. \n    apply pdecomposeEq in H1. subst. auto. apply ptrmDecomposeWF in H0; auto.\n    inv H0. constructor. auto. simpl in H4. auto. }\n   {simpl in *. invertHyp. repeat split; auto. copy H0. eapply fillWF; eauto. \n    apply pdecomposeEq in H1. subst. auto. apply ptrmDecomposeWF in H0; auto.\n    inv H0. simpl in *. auto. }\n   {simpl in *. invertHyp. repeat split; auto. copy H0. eapply fillWF; eauto. \n    apply pdecomposeEq in H1. subst. auto. apply ptrmDecomposeWF in H0; auto.\n    inv H0. simpl in *. auto. }\n   {simpl in *. invertHyp. repeat split; auto. copy H0. eapply fillWF; eauto. \n    apply pdecomposeEq in H1. subst. auto. apply ptrmDecomposeWF in H0; auto.\n    inv H0. simpl in *. auto. }\n   {simpl in *. invertHyp. repeat split; auto. copy H0. eapply fillWF; eauto. \n    apply pdecomposeEq in H1. subst. auto. apply ptrmDecomposeWF in H0; auto.\n    inv H0. simpl in *. auto. }\n   {simpl in *. invertHyp. repeat split; auto. copy H0. eapply fillWF; eauto. \n    apply pdecomposeEq in H1. subst. auto. apply ptrmDecomposeWF in H0; auto. }\n  }\n  {rewrite poolWFComm in *. simpl in *. invertHyp. repeat split; auto. \n   copy H7. apply ptrmDecomposeWF in H7; auto. inv H7. eapply fillWF; eauto.\n   apply pdecomposeEq in H1. subst. auto. constructor; auto.  }\n  {rewrite poolWFComm in *. simpl in *. invertHyp. repeat split; auto. \n   copy H7. apply ptrmDecomposeWF in H7; auto. inv H7. eapply fillWF; eauto.\n   apply pdecomposeEq in H1. subst. auto. constructor; auto.  }\n  {rewrite poolWFComm in *. simpl in *. invertHyp. repeat split; auto. \n   copy H7. apply ptrmDecomposeWF in H7; auto. inv H7. eapply fillWF; eauto.\n   apply pdecomposeEq in H1. subst. auto. }\n  {rewrite poolWFComm in *. simpl in *. invertHyp. repeat split; auto. \n   copy H7. apply ptrmDecomposeWF in H7; auto. simpl in *. eapply fillWF; eauto. \n   apply pdecomposeEq in H1; subst; auto. apply ptrmDecomposeWF in H7; auto. }\n  {rewrite poolWFComm in *. simpl in *. invertHyp. repeat split; auto. \n   copy H9. apply ptrmDecomposeWF in H9; auto. eapply fillWF; eauto.\n   apply pdecomposeEq in H1. subst. auto. simpl. eapply lookupSourceProg; eauto. }\n  {rewrite poolWFComm in *. simpl in *. invertHyp. repeat split; auto. \n   copy H5. apply ptrmDecomposeWF in H5; auto. inv H5. eapply fillWF; eauto.\n   apply pdecomposeEq in H3. subst. auto. apply ptrmDecomposeWF in H5; eauto. \n   simpl in *. invertHyp. apply replaceSourceProg; auto. }\n  {rewrite poolWFComm in *. simpl in *. invertHyp. repeat split; auto. \n   copy H8. apply ptrmDecomposeWF in H8; auto. inv H8. eapply fillWF; eauto.\n   apply pdecomposeEq in H3. subst. auto. unfold Heap.extend. unfold heapWF. \n   simpl. unfold raw_extend. destruct H. simpl. auto. }\nQed. \n\nTheorem pmultistepWF : forall H T H' T', \n                         PoolWF T -> heapWF H -> pmultistep H T (Some(H', T')) -> \n                         PoolWF T' /\\ heapWF H'. \nProof.\n  intros. remember (Some(H',T')). induction H2. \n  {inv Heqo. auto. }\n  {subst. apply pstepWF in H2; auto. invertHyp. eapply IHpmultistep; eauto. }\n  {inv Heqo. }\nQed. \n\nInductive stepPlus : sHeap -> pool -> option (sHeap * pool) -> Prop :=\n| plus_step : forall (H H' : sHeap) c (T t t' : pool),\n                 step H T t (OK H' T t') ->\n                 multistep H' (tUnion T t') c -> stepPlus H (tUnion T t) c\n| smulti_error : forall (H : sHeap) (T t : pool),\n                   step H T t Spec.Error -> stepPlus H (tUnion T t) None.\n\nTheorem nonspecImpliesSpec : forall PH PH' PT pt pt' T H,\n        pstep PH PT pt (pOK PH' PT pt') -> \n        speculate (pUnion PT pt) T -> PoolWF (pUnion PT pt) -> heapWF PH -> specHeap PH H ->\n        exists T' H', stepPlus H T (Some(H', T')) /\\\n                   speculate (pUnion PT pt') T' /\\ specHeap PH' H'. \nProof.\n  intros. inv H0. \n  {apply specUnionComm in H1. invertHyp. inv H1. inv H7. econstructor. econstructor. \n   split. unfoldTac. rewrite Union_associative. econstructor. \n   eapply simBasicStep in H9. eapply BasicStep. eauto. constructor. split; auto. \n   apply poolWFComm in H2. simpl in H2. invertHyp. eapply basicStepGather in H9; eauto. \n   unfoldTac. rewrite <- Union_associative. apply specUnionComm'. auto. \n   constructor. constructor. auto. }\n  {copy H9. apply specUnionComm in H1. invertHyp. inv H1. inv H8.\n   eapply gatherDecomp in H0; eauto. invertHyp. econstructor. econstructor. split. \n   unfoldTac. rewrite Union_associative. econstructor.\n   eapply Spec.Spec with(M:=specTerm M)(N:=specTerm N)(E:=specCtxt E). \n   eapply multi_step. eapply PopSpec. rewrite app_nil_l. simpl. auto. constructor. \n   split. unfoldTac. rewrite <- Union_associative. apply specUnionComm'. auto.\n   rewrite couple_swap. rewrite coupleUnion. repeat rewrite Union_associative. \n   replace (specRun(specTerm M)(specTerm N)) with (specTerm(pspecRun M N)); auto.  \n   rewrite <- specFill. constructor. constructor. rewrite <- Union_associative. \n   apply gatherFill; auto. inv H0. constructor; auto. auto. }\n  {copy H9. apply specUnionComm in H1. invertHyp. inv H1. inv H8. \n   eapply gatherDecomp in H0; eauto. invertHyp. inv H0. unfoldTac. \n   repeat rewrite <- Union_associative. rewrite listToSingle. rewrite <- coupleUnion. \n   rewrite couple_swap. repeat rewrite Union_associative. econstructor. econstructor. split.\n   econstructor. eapply SpecJoin with (N0:=specTerm M)\n                          (M:=specTerm M)(N1:=specTerm N)(E:=specCtxt E); eauto. \n   simpl. constructor. split. unfoldTac. repeat rewrite <- Union_associative. apply specUnionComm'. \n   auto. rewrite (Union_associative thread x0).\n   rewrite (Union_associative thread (Union thread x0 T1)). \n   replace (specJoin(ret(specTerm N)) (specTerm M)) with (specTerm (pspecJoin (pret N) M)); auto. \n   rewrite <- specFill. constructor. constructor. rewrite <- Union_associative. \n   apply gatherFill. auto. constructor; auto. auto. }\n  {copy H9. apply specUnionComm in H1. invertHyp. inv H1. inv H8. \n   eapply gatherDecomp in H0; eauto. invertHyp. inv H0. unfoldTac. \n   repeat rewrite <- Union_associative. rewrite listToSingle. rewrite <- coupleUnion. \n   repeat rewrite Union_associative. rewrite <- Union_associative. econstructor. econstructor. split.  \n   econstructor. apply decomposeSpec in H9.\n   eapply SpecRB with (E:=specTerm N)(E':=specCtxt E)(N0:=specTerm M). eassumption. \n   auto. auto. eapply RBDone. unfold tAdd. unfold Add. unfoldTac. unfold In. \n   apply in_app_iff. right. simpl. left; eauto. eauto.\n   constructor. split. unfoldTac. repeat rewrite <- Union_associative. apply specUnionComm'. \n   auto. replace (raise (specTerm N)) with (specTerm (praise N)); auto. rewrite <- specFill.\n   apply gatherSourceProg in H12. Focus 2. apply poolWFComm in H2. simpl in H2. invertHyp.\n   apply ptrmDecomposeWF in H9; auto. inv H9. auto. subst. unfold Add. simpl. \n   rewrite Union_associative. constructor. constructor. apply gatherFill; auto. auto. }\n  {copy H9. apply specUnionComm in H1. invertHyp. inv H1. inv H8. \n   eapply gatherDecomp in H0; eauto. invertHyp. inv H0. copy H9. rewrite poolWFComm in H2. \n   simpl in H2. invertHyp. apply ptrmDecomposeWF in H9; auto. simpl in H9. \n   unfoldTac. rewrite Union_associative. econstructor. econstructor. split. econstructor. \n   eapply Fork with (M:=specTerm M)(E:=specCtxt E). eauto. eapply multi_step. eapply PopFork. \n   rewrite app_nil_l. simpl. auto. auto. constructor. unfoldTac. rewrite <- Union_associative. \n   split. apply specUnionComm'. auto. copy H7. apply gatherSourceProg in H7; auto. rewrite H7. \n   rewrite union_empty_r. rewrite coupleUnion. unfold pCouple. unfold Couple. simpl. \n   replace (ret unit) with (specTerm (pret punit)); auto. rewrite <- specFill. constructor. \n   rewrite <- union_empty_l. constructor. constructor. subst. eauto. \n   rewrite <- union_empty_r. apply gatherFill. auto. repeat constructor. auto. }\n  {copy H11. apply specUnionComm in H1. invertHyp. inv H1. inv H8. copy H10. \n   eapply specHeapLookupFull in H10; eauto. invertHyp. \n   eapply gatherDecomp in H0; eauto. invertHyp. \n   econstructor. econstructor. split. unfoldTac. rewrite Union_associative. econstructor. \n   eapply Get with (N:=specTerm M)(E:=specCtxt E). eauto. auto. eapply multi_step. eapply PopRead. \n   rewrite app_nil_l. simpl; auto. rewrite app_nil_r. rewrite app_nil_l. auto. introsInv. \n   erewrite HeapLookupReplace; eauto. auto. rewrite replaceOverwrite. rewrite replaceSame. \n   constructor. eauto. unfoldTac. rewrite Union_associative. repeat rewrite <- Union_associative. \n   split. apply specUnionComm'. auto. inv H0. inv H9. simpl. \n   replace (ret(specTerm M)) with (specTerm(pret M)); auto. rewrite <- specFill. \n   constructor. constructor. rewrite <- union_empty_r. apply gatherFill. auto. constructor.\n   gatherTac M. copy H8. apply gatherSourceProg in H8; eauto. subst. auto. Focus 2. auto.\n   eapply lookupSourceProg; eauto. } \n  {apply specUnionComm in H1. invertHyp. inv H1. inv H8. copy H7. \n   eapply gatherDecomp in H7; eauto. invertHyp. rewrite poolWFComm in H2. simpl in H2. \n   invertHyp. econstructor. econstructor. split. unfoldTac. rewrite Union_associative. \n   econstructor. eapply Put with (N:=specTerm M)(E:=specCtxt E).\n   eapply specHeapLookupEmpty; eauto. auto. eapply multi_step. \n   eapply PopWrite. rewrite app_nil_l. simpl; auto. erewrite HeapLookupReplace; eauto. \n   eapply specHeapLookupEmpty; eauto. auto. rewrite replaceOverwrite. constructor. \n   split. unfoldTac. rewrite <- Union_associative. apply specUnionComm'. auto. \n   inv H6. inv H13. unfoldTac. simpl in *. copy H1. apply ptrmDecomposeWF in H6; auto. inv H6. \n   eapply gatherSourceProg in H15; eauto. subst. rewrite union_empty_r in *.  \n   replace (ret unit) with (specTerm (pret punit)); auto. rewrite <- specFill. constructor. \n   constructor. rewrite <- union_empty_r. apply gatherFill. auto. repeat constructor. \n   apply specHeapReplaceFull; auto. }\n  {apply specUnionComm in H1. invertHyp. inv H1. inv H7. copy H10. \n   eapply gatherDecomp in H10; eauto. invertHyp. rewrite poolWFComm in H2. simpl in H2. \n   invertHyp. econstructor. econstructor. split. unfoldTac. rewrite Union_associative. \n   econstructor. copy p. eapply specHeapLookupNone in H8; eauto.\n   eapply New with (E:=specCtxt E)(x:=x). auto. eapply multi_step. \n   eapply PopNewEmpty.  rewrite app_nil_l. simpl; auto. rewrite lookupExtend. auto. \n   auto. erewrite replaceExtendOverwrite; eauto. constructor. unfoldTac.\n   rewrite <- Union_associative. apply specUnionComm'. auto. \n   replace (ret(fvar x)) with (specTerm(pret(pfvar x))); auto. rewrite <- specFill. \n   constructor. constructor. apply gatherFill; auto. constructor. inv H6. constructor. \n   apply specHeapExtend; auto. }\n  Grab Existential Variables. \n  {eapply specHeapLookupNone; eauto. }\n  {apply decomposeSpec in H1. auto. }\n  {eapply specHeapLookupNone; eauto. }\n  {apply decomposeSpec in H1; auto. }\n  {apply decomposeSpec in H11. auto. }\n  {apply decomposeSpec in H0. auto. }\n  {apply decomposeSpec in H9; auto. }\n  {apply decomposeSpec in H9; auto. }\nQed. \n\nTheorem nonspecImpliesSpecStar : forall PH PH' PT H PT' T,\n        pmultistep PH PT (Some(PH', PT')) -> \n        speculate PT T -> PoolWF PT -> heapWF PH -> specHeap PH H ->\n        exists T' H', multistep H T (Some(H', T')) /\\\n                   speculate PT' T' /\\ specHeap PH' H'. \nProof.\n  intros. remember (Some(PH',PT')). genDeps{H; T}. induction H0; intros.  \n  {inv Heqo. eauto. }\n  {intros. subst. copy H0. eapply nonspecImpliesSpec in H0; eauto. invertHyp.\n   copy H7. apply pstepWF in H7; auto. invertHyp. \n   eapply IHpmultistep in H10; eauto. invertHyp. econstructor. econstructor. split.\n   inv H8. eapply multi_step. eauto. eapply multi_trans; eauto. eauto. }\n  {inv Heqo. }\nQed. \n\n\n\n\n\n\n\n\n\n", "meta": {"author": "lexxx320", "repo": "PersonalProjects", "sha": "bc83fb250467b013d9db9fe535ff7bd314632d4c", "save_path": "github-repos/coq/lexxx320-PersonalProjects", "path": "github-repos/coq/lexxx320-PersonalProjects/PersonalProjects-bc83fb250467b013d9db9fe535ff7bd314632d4c/newest/nonspeculativeImpliesSpeculative.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24147948289856724}}
{"text": "(**********************************************************************************\n * The PEDANTIC (Proof Engine for Deductive Automation using Non-deterministic\n * Traversal of Instruction Code) verification framework\n *\n * Developed by Kenneth Roe\n * For more information, check out www.cs.jhu.edu/~roe\n *\n * TreeTraversal.v\n * This file contains the proof of correctness of a tree traversal algorithm using\n * the PEDANTIC verification framework.\n *\n **********************************************************************************)\n\nRequire Export SfLib.\nRequire Export SfLibExtras.\nRequire Export ImpHeap.\nRequire Export AbsState.\nRequire Export AbsExecute.\nRequire Export AbsStateInstance.\nRequire Export Simplify.\nRequire Export Eqdep.\nRequire Export StateImplication.\nRequire Export Classical.\nRequire Export Unfold.\nRequire Export Fold.\nRequire Export merge.\nRequire Export ProgramTactics.\nRequire Export SatSolverDefs.\nRequire Export SatSolverMergeTheorem1P1.\nOpaque basicEval.\n\nTheorem mergeTheorem1Aux9b : forall v v0 v1 v2 l v4 x x0 eee e x1 x2 x3,\n     @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n        ([--( v(2), v(6) )---> (#2 ++++ v(7))] **\n         ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #2] *\\/*\n          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]) *\\/*\n         [--( v(2), v(6) )---> (#6 ++++ v(7))] **\n         ([nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #1] *\\/*\n          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(7)) ==== #0]))\n        (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n        (eee, empty_heap) ->\n      (forall x1 : Value,\n       NatValue 0 = x1 \\/\n       NatValue 1 = x1 \\/ NatValue 2 = x1 \\/ NatValue 3 = x1 \\/ False ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         (([--( v(2), v(6) )---> (#10 ++++ v(8)) ==== #0] *\\/*\n           [--( v(2), v(6) )---> (#2 ++++ v(8))]) *\\/*\n          [--( v(2), v(6) )---> (#6 ++++ v(8))])\n         (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: nil)\n         (eee, empty_heap)) ->\n      In x0 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n      NatValue 0 = nth (eee varx) l NoValue ->\n      e <> 0 ->\n      NatValue e =\n       (if match eee varx with\n           | 0 => false\n           | 1 => false\n           | 2 => false\n           | 3 => false\n           | S (S (S (S _))) => true\n           end\n        then NatValue 0\n        else @NatValue unit 1) ->\n       (forall x1 : Value,\n       In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         (AbsAll range(#0, #4)\n                      (((((([--( v(2), v(6) )---> (#10 ++++ v(8))] *\\/*\n                            [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n                            [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0]) *\\/*\n                           [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n                          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ====\n                           #0]) *\\/*\n                         [nth(replacenth(v(4), !!(varx), !!(valuex)), v(9)) ====\n                          #0]) *\\/* [v(8) ==== v(9)]) *\\/*\n                       ([!!(varx) ==== v(9)] ** [!!(varx) ==== v(8)] *\\/*\n                        AbsExists TreeRecords(v(0))\n                          ([!!(varx) ==== v(9)] **\n                           [nth(find(v(0), v(10)), #3) ==== v(8)])) *\\/*\n                       AbsExists TreeRecords(v(0))\n                         (AbsExists TreeRecords(find(v(0), v(10)))\n                            ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                             [nth(find(v(0), v(11)), #3) ==== v(8)]))))\n          ((v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) ++\n          x1 :: nil) (eee, empty_heap)) ->\n       (forall x1 : Value,\n       In x1 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))] **\n          [nth(replacenth(v(4), !!(varx), !!(valuex)), v(8)) ==== #0] *\\/*\n          [#0 <<<< nth(replacenth(v(4), !!(varx), !!(valuex)), v(8))] *\\/*\n          [--( v(2), v(6) )---> (#2 ++++ v(8)) ==== #0] **\n          [--( v(2), v(6) )---> (#6 ++++ v(8)) ==== #0])\n         ((v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil) ++\n          x1 :: nil) (eee, empty_heap)) ->\n       true =\n       validPredicate\n         (@absEval unit eq_unit (@basicEval unit) eee\n            (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: nil)\n            (#0 ==== --( v(2), v(6) )---> (#10 ++++ !!(varx)))) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n       ([!!(valuex) ==== #1] *\\/* [!!(valuex) ==== #2])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n          (eee, empty_heap) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (AbsAll range(#0, #4)\n             ([nth(v(4), v(6)) ==== #0] *\\/*\n              [!!(varx) ==== v(6)] *\\/*\n              AbsExists TreeRecords(v(0))\n                ([nth(find(v(0), v(7)), #3) ==== v(6)] **\n                 [nth(find(v(0), v(7)), #4) ==== nth(v(4), v(6))])))\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n          (eee, empty_heap) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (AbsAll TreeRecords(v(0))\n             ([~~ (!!(varx) ==== nth(find(v(0), v(6)), #3))]))\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: nil) \n          (eee, empty_heap) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (SUM(range(!!(varx) ++++ #1, #4),\n           #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(10)) //\\\\\n           ((--( v(2), v(6) )---> (#2 ++++ v(10)) \\\\//\n             --( v(2), v(6) )---> (#6 ++++ v(10))) //\\\\\n            nth(v(4), v(10)) ==== #0), v(9)))\n          (v\n           :: v0\n              :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n          (eee, fun _ : nat => None) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n  ([#1 ==== v(8) ++++ v(9)])\n          (v\n           :: v0\n              :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n          (eee, fun _ : nat => None) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          (SUM(range(#0, #4),\n           #0 <<<< --( v(2), v(6) )---> (#10 ++++ v(10)) //\\\\\n           nth(v(4), v(10)) ==== #0, #1))\n          (v\n           :: v0\n              :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x1 :: x2 :: nil)\n          (eee, fun _ : nat => None) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n         (((((([--( v(2), v(6) )---> (#10 ++++ !!(varx))] *\\/*\n               [--( v(2), v(6) )---> (#2 ++++ !!(varx)) ==== #0] **\n               [--( v(2), v(6) )---> (#6 ++++ !!(varx)) ==== #0]) *\\/*\n              [~~ --( v(2), v(6) )---> (#10 ++++ v(9))]) *\\/*\n             [nth(replacenth(v(4), !!(varx), !!(valuex)), !!(varx)) ==== #0]) *\\/*\n            [nth(replacenth(v(4), !!(varx), !!(valuex)), v(9)) ==== #0]) *\\/*\n           [!!(varx) ==== v(9)]) *\\/*\n          ([!!(varx) ==== v(9)] ** [!!(varx) ==== (!!(varx))] *\\/*\n           AbsExists TreeRecords(v(0))\n             ([!!(varx) ==== v(9)] **\n              [nth(find(v(0), v(10)), #3) ==== (!!(varx))])) *\\/*\n          AbsExists TreeRecords(v(0))\n            (AbsExists TreeRecords(find(v(0), v(10)))\n               ([nth(find(v(0), v(10)), #3) ==== v(9)] **\n                [nth(find(v(0), v(11)), #3) ==== (!!(varx))])))\n         ((v\n           :: v0\n              :: v1\n                 :: v2\n                    :: ListValue l\n                       :: v4 :: x :: x0 :: NatValue (eee varx) :: nil) ++\n          x3 :: nil) (eee, empty_heap) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n   ([#0 <<<< nth(v(4), v(8))])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x3 :: nil)\n          (eee, empty_heap) ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n          ([#0 <<<< --( v(2), v(6) )---> (#10 ++++ v(8))])\n          (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: x0 :: x3 :: nil)\n          (eee, empty_heap) ->\n    In x3 (NatValue 0 :: NatValue 1 :: NatValue 2 :: NatValue 3 :: nil) ->\n    length l = 4 ->\n       @realizeState unit eq_unit (@basicEval unit) (@basicState unit) (@basicAccumulate unit eq_unit (@basicEval unit))\n  ([--( v(2), v(6) )---> (#2 ++++ !!(varx)) ==== #0] **\n      [--( v(2), v(6) )---> (#6 ++++ !!(varx)) ==== #0])\n     (v :: v0 :: v1 :: v2 :: ListValue l :: v4 :: x :: nil) \n     (eee, empty_heap).\nProof.\n    admit.\nQed.\n\n", "meta": {"author": "kendroe", "repo": "CoqPIE", "sha": "946009445e532dd4632a11a58a64f72a1dd28304", "save_path": "github-repos/coq/kendroe-CoqPIE", "path": "github-repos/coq/kendroe-CoqPIE/CoqPIE-946009445e532dd4632a11a58a64f72a1dd28304/PEDANTIC/SatSolverMergeTheorem1P2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2414589773369685}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\n\nSection AppendEntriesRequestTermSanity.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Definition append_entries_request_term_sanity net :=\n    forall p t n pli plt es ci e,\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      In e es ->\n      eTerm e >= plt.\n\n\n  Class append_entries_request_term_sanity_interface : Prop :=\n    {\n      append_entries_request_term_sanity_invariant :\n        forall net,\n          refined_raft_intermediate_reachable net ->\n          append_entries_request_term_sanity net\n    }.\n\nEnd AppendEntriesRequestTermSanity.", "meta": {"author": "ahmet-celik", "repo": "pverdi", "sha": "dc88c4a5fd7d90b5bb48e583bd8286097f983f81", "save_path": "github-repos/coq/ahmet-celik-pverdi", "path": "github-repos/coq/ahmet-celik-pverdi/pverdi-dc88c4a5fd7d90b5bb48e583bd8286097f983f81/raft/AppendEntriesRequestTermSanityInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24145897733696844}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.structcopy.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nLocal Open Scope logic.\n\nDefinition tfoo := Tstruct _foo noattr.\n\nDefinition f_spec :=\n DECLARE _f\n  WITH p: val, i: Z, j: Z\n  PRE  [ tptr tfoo]\n      PROP  ( )\n      PARAMS (p)\n      SEP (data_at Ews tfoo (Vint (Int.repr i), Vint (Int.repr j)) p)\n  POST [ tuint ]\n      PROP() RETURN(Vint (Int.repr (i+j)))\n      SEP (data_at Ews tfoo (Vint (Int.repr i), Vint (Int.repr j)) p).\n\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [f_spec ]).\n\nLemma body_f:  semax_body Vprog Gprog f_f f_spec.\nProof.\nFail  start_function.\nAbort.\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/progs/verif_structcopy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2414129012529524}}
{"text": "(** * Exact categories *)\n\n(** ** Contents\n\n  - Preliminaries\n    - Diagram chasing lemmas\n\n  - The definition of exact category\n    - Equivalence with Quillen's definition\n    - The exact category structure induced on X by\n      a function X -> ob M, where M is an exact category.\n\n *)\n\nRequire Export UniMath.Foundations.All.\nRequire Export UniMath.MoreFoundations.Notations.\nRequire Export UniMath.MoreFoundations.PartA.\n\nRequire Export UniMath.Algebra.BinaryOperations.\nRequire Export UniMath.Algebra.Monoids.\nRequire Import UniMath.Algebra.Groups.\nRequire Export UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Export UniMath.CategoryTheory.Core.Functors.\nRequire Export UniMath.CategoryTheory.Core.NaturalTransformations.\n\nRequire Export UniMath.CategoryTheory.Monics.\nRequire Export UniMath.CategoryTheory.Epis.\nRequire Export UniMath.CategoryTheory.limits.zero.\nRequire Export UniMath.CategoryTheory.limits.kernels.\nRequire Export UniMath.CategoryTheory.limits.cokernels.\nRequire Export UniMath.CategoryTheory.limits.binproducts.\nRequire Export UniMath.CategoryTheory.limits.bincoproducts.\nRequire Export UniMath.CategoryTheory.limits.pullbacks.\nRequire Export UniMath.CategoryTheory.limits.pushouts.\nRequire Export UniMath.CategoryTheory.limits.BinDirectSums.\nRequire Export UniMath.CategoryTheory.limits.Opp.\nRequire Export UniMath.CategoryTheory.CategoriesWithBinOps.\nRequire Export UniMath.CategoryTheory.opp_precat.\nRequire Export UniMath.CategoryTheory.PrecategoriesWithAbgrops.\nRequire Export UniMath.CategoryTheory.PreAdditive.\nRequire Export UniMath.CategoryTheory.Morphisms.\nRequire Export UniMath.CategoryTheory.Additive.\nRequire Export UniMath.CategoryTheory.Subcategory.Full.\n\nRequire Export UniMath.MoreFoundations.Propositions.\n\nLocal Arguments grinv {_}.\n\nLocal Open Scope logic.\nLocal Open Scope cat.\n\nLocal Definition hom (C:precategory_data) : ob C -> ob C -> UU := λ c c', precategory_morphisms c c'.\nLocal Definition Hom (C : category) : ob C -> ob C -> hSet := λ c c', make_hSet _ (homset_property C c c').\nLocal Definition Hom_add (C : PreAdditive) : ob C -> ob C -> abgr := λ c c', (@to_abgr C c c').\n\n(* move upstream, when ready *)\n\nSection InvestigateNotations.\n  Context (M : PreAdditive) (x y z:M) (f g : hom M x y) (h k : Hom_add M y z).\n  Local Open Scope abgrcat.\n  Goal empty.\n    set (Q := h+k).\n    set (r := -g).\n    set (t := f-g).\n    set (p := f·h + (h∘f) · 1).\n    set (o := (h + h) · 1 = h).\n    set (s := f+g).\n    set (u := f·1).\n    set (v := f·0·h).\n    (* Set Printing All. *)\n  Abort.\nEnd InvestigateNotations.\n\nSection Categories.\n  Definition isPushout' {M:category} {a b c d : M} (f : a --> b) (g : a --> c)\n             (in1 : b --> d) (in2 : c --> d) : hProp.\n  Proof.\n    exists (∑ (H : f · in1 = g · in2), isPushout f g in1 in2 H).\n    abstract (                  (* this abstraction is important! *)\n        apply isaproptotal2 ;\n        [ intros H; apply isaprop_isPushout\n        | intros H H' po po'; apply homset_property ]) using _P_.\n  Defined.\n  Definition isPullback' {M:category} {a b c d : M} (f : b --> a) (g : c --> a)\n             (p1 : d --> b) (p2 : d --> c) : hProp.\n  Proof.\n    exists (∑ (H : p1 · f = p2· g), isPullback (*f g p1 p2*) H).\n    exact (_P_ (oppositeCategory M) a b c d f g p1 p2).\n  Defined.\n  Lemma isPullback'_up_to_z_iso {M:category} {a b c d d' : M}\n        (f : b --> a) (g : c --> a) (p1 : d --> b) (p2 : d --> c)\n        (i : z_iso d' d) :\n    isPullback' f g p1 p2 -> isPullback' f g (i·p1) (i·p2).\n  Proof.\n    intros [e pb]. use tpair.\n    - abstract (rewrite 2 assoc'; apply maponpaths; exact e) using _P_.\n    - cbn beta. intros T r s eq.\n      assert (Q := pb T r s eq).\n      use (iscontrweqf _ Q); clear Q.\n      use weqtotal2.\n      { apply z_iso_comp_left_weq. exact (z_iso_inv i). }\n      { intros h. cbn beta. apply weqiff.\n        { cbn.\n          rewrite 2 (assoc' h). rewrite 2 (assoc _ i).\n          rewrite z_iso_after_z_iso_inv. rewrite 2 id_left.\n          apply isrefl_logeq. }\n        { apply isapropdirprod; apply homset_property. }\n        { apply isapropdirprod; apply homset_property. }\n        }\n  Defined.\n  Lemma isPushout'_up_to_z_iso {M:category} {a b c d d' : M}\n        (f : a --> b) (g : a --> c) (in1 : b --> d) (in2 : c --> d)\n        (i : z_iso d d') :\n    isPushout' f g in1 in2 -> isPushout' f g (i∘in1) (i∘in2).\n  Proof.\n    exact (isPullback'_up_to_z_iso (M:=oppositeCategory M) f g in1 in2 (opp_z_iso i)).\n  Qed.\n  (* Section bottleneck. *)\n  (*   Context {M:category} {a b c d : M} (f : b --> a) (g : c --> a) *)\n  (*            (p1 : d --> b) (p2 : d --> c) (pb : isPullback' f g p1 p2). *)\n  (*   Time Check (pb : @isPushout' (oppositeCategory M) a b c d f g p1 p2). *)\n  (*   (* without the abstraction above, this would be too slow, 13.5 seconds *) *)\n  (* End bottleneck. *)\n  Lemma Pushout_to_isPushout' {M:category} {a b c : M} (f : a --> b) (g : a --> c)\n        (po : Pushout f g) :\n    isPushout' f g (PushoutIn1 po) (PushoutIn2 po).\n  Proof.\n    use tpair.\n    - apply PushoutSqrCommutes.\n    - cbn beta. apply isPushout_Pushout.\n  Qed.\n  Lemma Pullback_to_isPullback' {M:category} {a b c : M} (f : b --> a) (g : c --> a)\n        (pb : Pullback f g) :\n    isPullback' f g (PullbackPr1 pb) (PullbackPr2 pb).\n  Proof.\n    use tpair.\n    - apply PullbackSqrCommutes.\n    - cbn beta. apply isPullback_Pullback.\n  Qed.\nEnd Categories.\n\nSection MorphismPairs.\n  Goal ∏ (M : precategory) (P Q : MorphismPair M) (f:MorphismPairIsomorphism P Q),\n       InverseMorphismPairIsomorphism (InverseMorphismPairIsomorphism f) = f.\n  Proof.\n    (* Because this fails, we will have two (dual) properties in the definition\n       of exact category, so we can get duality to work better. *)\n    Fail reflexivity.\n  Abort.\nEnd MorphismPairs.\n\nSection Pullbacks.              (* move upstream *)\n\n  Local Open Scope type.\n\n  Definition IsoArrowTo {M : category}     {A A' B:M} (g : A --> B) (g' : A' --> B) := ∑ i : z_iso A A', i · g' = g.\n  Coercion IsoArrowTo_pr1 {M : category}   {A A' B:M} (g : A --> B) (g' : A' --> B) : IsoArrowTo g g' -> z_iso A A' := pr1.\n\n  Definition IsoArrowFrom {M : category}   {A B B':M} (g : A --> B) (g' : A --> B') := ∑ i : z_iso B B', g · i  = g'.\n  Coercion IsoArrowFrom_pr1 {M : category} {A B B':M} (g : A --> B) (g' : A --> B') : IsoArrowFrom g g' -> z_iso B B' := pr1.\n  (* this definition of IsoArrow is asymmetric *)\n\n  Definition IsoArrow {M : category}       {A A' B B':M} (g : A --> B) (g' : A' --> B') := ∑ (i : z_iso A A') (j : z_iso B B'), i · g' = g · j.\n\n  Definition pullbackiso1 {M : category} {A B C:M} {f : A --> C} {g : B --> C}\n        (pb : Pullback f g) (pb' : Pullback f g)\n    : IsoArrowTo (PullbackPr1 pb) (PullbackPr1 pb')\n    := pr1 (pullbackiso _ pb pb'),,pr12 (pullbackiso _ pb pb').\n\n  Definition pullbackiso2 {M : category} {A B C:M} {f : A --> C} {g : B --> C}\n        (pb : Pullback f g) (pb' : Pullback f g)\n    : IsoArrowTo (PullbackPr2 pb) (PullbackPr2 pb')\n    := pr1 (pullbackiso _ pb pb'),,pr22 (pullbackiso _ pb pb').\n\n  Section OppositeIsoArrows.\n\n    Definition opposite_IsoArrowTo {M:category} {A A' B:M} {g : A --> B} {g' : A' --> B} :\n      IsoArrowTo g g' -> IsoArrowFrom (M:=M^op) g' g.\n    Proof.\n      intros i.\n      Fail exact i.\n      use tpair.\n      - exact (opp_z_iso (pr1 i)).\n      - cbn. exact (pr2 i).\n    Defined.\n    Definition opposite_IsoArrowFrom {M:category} {A B B':M} {g : A --> B} {g' : A --> B'} :\n      IsoArrowFrom g g' -> IsoArrowTo (M:=M^op) g' g.\n    Proof.\n      intros i. use tpair.\n      - exact (opp_z_iso (pr1 i)).\n      - cbn. exact (pr2 i).\n    Defined.\n    Definition opposite_IsoArrow {M:category} {A A' B B':M} (g : A --> B) (g' : A' --> B') :\n      IsoArrow g g' -> IsoArrow (M:=M^op) (opp_mor g') (opp_mor g).\n    Proof.\n      intros i.\n      exists (opp_z_iso (pr12 i)).\n      exists (opp_z_iso (pr1 i)).\n      exact (! pr22 i).\n    Defined.\n  End OppositeIsoArrows.\n  Lemma IsoArrowTo_isaprop (M : category) {A A' B:M} (g : A --> B) (g' : A' --> B) :\n    isMonic g' -> isaprop (IsoArrowTo g g').\n  Proof.\n    intros i. apply invproofirrelevance; intros k k'. apply subtypePath.\n    - intro. apply homset_property.\n    - induction k as [[k K] e], k' as [[k' K'] e']; cbn; cbn in e, e'.\n      induction (i A k k' (e @ !e')). apply maponpaths. apply isaprop_is_z_isomorphism.\n  Qed.\n  Lemma IsoArrowFrom_isaprop (M : category) {A B B':M} (g : A --> B) (g' : A --> B') :\n     isEpi g -> isaprop (IsoArrowFrom g g').\n  Proof.\n    intros i. apply invproofirrelevance; intros k k'. apply subtypePath.\n    { intros j. apply homset_property. }\n    induction k as [[k K] e], k' as [[k' K'] e']; cbn; cbn in e, e'.\n    apply subtypePath; cbn.\n    { intros f. apply isaprop_is_z_isomorphism. }\n    use i. exact (e @ !e').\n  Qed.\nEnd Pullbacks.\n\nLocal Open Scope abgrcat.\n\n(* This exactly duplicates definitions upstream, but Import doesn't get the ones overridden,\n   which are useful (mysteriously) for printing: *)\nLocal Notation \"0\"     := (unel (grtomonoid (abgrtogr _))) : abgrcat.\nLocal Notation \"0\"     := (unel (grtomonoid (abgrtogr (to_abgr _ _)))) : abgrcat.\nLocal Notation \"f + g\" := (@op (pr1monoid (grtomonoid (abgrtogr _))) f g) : abgrcat.\nLocal Notation \"f + g\" := (@op (pr1monoid (grtomonoid (abgrtogr (to_abgr _ _)))) f g) : abgrcat.\nLocal Notation \"  - g\" := (@grinv (abgrtogr _) g) : abgrcat.\nLocal Notation \"  - g\" := (@grinv (abgrtogr (to_abgr _ _)) g) : abgrcat.\nLocal Notation \"f - g\" := (@op (pr1monoid (grtomonoid (abgrtogr _))) f (@grinv (abgrtogr (to_abgr _ _)) g)) : abgrcat.\nLocal Notation \"f - g\" := (@op (pr1monoid (grtomonoid (abgrtogr (to_abgr _ _)))) f (@grinv (abgrtogr (to_abgr _ _)) g)) : abgrcat.\n\nSection PreAdditive.\n  (** Reprove some standard facts in additive categories with the 0 map (the zero element of the\n      group) replacing the zero map (defined by composing maps to and from the zero object). *)\n  Lemma ThroughZeroIsZero {M:PreAdditive} (a b:M) (Z : Zero M) (f : a --> Z) (g : Z --> b) : f · g = 0.\n  Proof.\n    intermediate_path ((0:a-->Z) · g).\n    - apply (maponpaths (postcomp_with g)). apply ArrowsToZero.\n    - apply to_postmor_unel'.\n  Qed.\n  Definition elem21 {M:PreAdditive} {A B:M} (AB : BinDirectSum A B) (f:A-->B) : AB-->AB := 1 + π₁·f·ι₂.\n  Section Foo.                  (* because we open scopes *)\n    Definition elem21_isiso {M:PreAdditive} {A B:M} (AB : BinDirectSum A B) (f:A-->B) : is_z_isomorphism (elem21 AB f).\n    Proof.\n      exists (1 - π₁·f·ι₂).\n      unfold elem21. split.\n      - rewrite leftDistribute, 2 rightDistribute. rewrite id_left. refine (_ @ runax (Hom_add _ _ _) _).\n        rewrite assocax. apply maponpaths. rewrite id_right, id_left. rewrite rightMinus.\n        rewrite <- assocax. rewrite grlinvax. rewrite lunax. rewrite assoc'. rewrite <- (assoc π₁ f ι₂).\n        rewrite (assoc ι₂). rewrite DirectSumIn2Pr1. rewrite zeroLeft. rewrite zeroRight.\n        rewrite grinvunel. reflexivity.\n      - rewrite leftDistribute, 2 rightDistribute. rewrite id_left. refine (_ @ runax (Hom_add _ _ _) _).\n        rewrite assocax. apply maponpaths. rewrite id_right, id_left. rewrite leftMinus.\n        rewrite <- assocax. rewrite grrinvax. rewrite lunax. rewrite assoc'. rewrite <- (assoc π₁ f ι₂).\n        rewrite (assoc ι₂). rewrite DirectSumIn2Pr1. rewrite zeroLeft. rewrite zeroRight.\n        rewrite grinvunel. reflexivity.\n    Defined.\n  End Foo.\n  Definition elem12 {M:PreAdditive} {A B:M} (AB : BinDirectSum A B) (f:B-->A) : AB-->AB := 1 + π₂·f·ι₁.\n  Definition elem12_isiso {M:PreAdditive} {A B:M} (AB : BinDirectSum A B) (f:B-->A) : is_z_isomorphism (elem12 AB f).\n  Proof.\n    exists (1 - π₂·f·ι₁). unfold elem12. split.\n    - rewrite leftDistribute, 2 rightDistribute. rewrite id_left. refine (_ @ runax (Hom_add _ _ _) _).\n      rewrite assocax. apply maponpaths. rewrite id_right, id_left. rewrite rightMinus.\n      rewrite <- assocax. rewrite grlinvax. rewrite lunax. rewrite assoc'. rewrite <- (assoc _ f _).\n      rewrite 2 (assoc ι₁). rewrite DirectSumIn1Pr2. rewrite zeroLeft. rewrite zeroLeft.\n      rewrite 2 zeroRight.\n      use grinvunel.\n    - rewrite leftDistribute, 2 rightDistribute. rewrite id_left. refine (_ @ runax (Hom_add _ _ _) _).\n      rewrite assocax. apply maponpaths. rewrite id_right, id_left. rewrite leftMinus.\n      rewrite <- assocax. rewrite grrinvax. rewrite lunax. rewrite assoc'. rewrite <- (assoc _ f _).\n      rewrite (assoc ι₁). rewrite (assoc ι₁). rewrite DirectSumIn1Pr2. rewrite 2 zeroLeft.\n      rewrite 2 zeroRight. use grinvunel.\n  Defined.\n\n  Definition isKernel' {M:PreAdditive} {x y z : M} (f : x --> y) (g : y --> z) : hProp :=\n    f · g = 0 ∧ ∀ (w : M) (h : w --> y), h · g = 0 ⇒ ∃! φ : w --> x, φ · f = h.\n  Definition hasKernel {M:PreAdditive} {y z : M} (g : y --> z) : hProp :=\n    ∃ x (f:x-->y), isKernel' f g.\n  Lemma isKernel_iff {M:PreAdditive} {x y z : M} (Z:Zero M) (f : x --> y) (g : y --> z) :\n    isKernel' f g <-> ∑ e : f · g = ZeroArrow Z x z, isKernel Z f g e.\n  Proof.\n    split.\n    { intros [e' ik].\n      use tpair.\n      { refine (e' @ _). apply PreAdditive_unel_zero. }\n      intros T h e.\n      exact (ik T h (e @ ! PreAdditive_unel_zero _ _ _ _)). }\n    { intros [e ik]. use tpair.\n      { refine (e @ ! _). apply PreAdditive_unel_zero. }\n      cbn beta. intros T h e'.\n      exact (ik T h (e' @ PreAdditive_unel_zero _ _ _ _)). }\n  Qed.\n  Definition isKernel'_to_Kernel {M:PreAdditive} (Z:Zero M) {x y z : M} (f : x --> y) (g : y --> z) :\n    isKernel' f g -> Kernel Z g.\n  Proof.\n    intros co. exists (x,,f). now apply isKernel_iff.\n  Defined.\n  Definition isCokernel' {M:PreAdditive} {x y z : M} (f : x --> y) (g : y --> z) : hProp :=\n    f · g = 0 ∧ ∀ (w : M) (h : y --> w), f · h = 0 ⇒ ∃! φ : z --> w, g · φ = h.\n  Definition hasCokernel {M:PreAdditive} {x y : M} (f : x --> y) : hProp :=\n    ∃ z (g:y-->z), isCokernel' f g.\n  Lemma isCokernel_iff {M:PreAdditive} {x y z : M} (Z:Zero M) (f : x <-- y) (g : y <-- z) :\n    isCokernel' g f <-> ∑ e : f ∘ g = ZeroArrow Z z x, isCokernel Z g f e.\n  Proof.\n    split.\n    { intros [e' ik].\n      use tpair.\n      { refine (e' @ _). apply PreAdditive_unel_zero. }\n      intros T h e.\n      exact (ik T h (e @ ! PreAdditive_unel_zero _ _ _ _)). }\n    { intros [e ik]. use tpair.\n      { refine (e @ ! _). apply PreAdditive_unel_zero. }\n      cbn beta. intros T h e'.\n      exact (ik T h (e' @ PreAdditive_unel_zero _ _ _ _)). }\n  Qed.\n  Definition isCokernel'_to_Cokernel {M:PreAdditive} (Z:Zero M) {x y z : M} (f : x --> y) (g : y --> z) :\n    isCokernel' f g -> Cokernel Z f.\n  Proof.\n    intros co. exists (z,,g). now apply isCokernel_iff.\n  Defined.\n  Section Tmp.\n    Lemma PushoutCokernel {M:PreAdditive} {A B C D E:M} (i:A-->B) (p:B-->C)\n          (j:B-->D) (p':D-->E) (j':C-->E) :\n      isCokernel' i p -> isPushout' (M:=M) j p p' j' -> isCokernel' (i·j) p'.\n    Proof.\n      intros [b co] [e po].\n      (* We show the universal property of the cokernel by showing uniqueness\n         and existence simultaneously, i.e., by working with equivalences to show\n         a type is contractible. *)\n      split.\n      - rewrite assoc'.\n        (* ambiguous coercions!\n           (category_to_precategory (categoryWithAbgrops_category _))\n           (precategoryWithBinOps_precategory (categoryWithAbgrops_precategoryWithBinOps _))\n         *)\n        rewrite e.\n(*        unfold  category_to_precategory, pr1 in e.\n        rewrite e.\n*)\n        rewrite assoc. rewrite b. apply zeroLeft.\n      - intros T h v. rewrite assoc' in v.\n        assert (Q := co T (j·h) v); cbn in Q. generalize Q; clear Q.\n        apply iscontrweqb. use make_weq.\n        + intros [k w]; exists (j'·k). rewrite assoc. rewrite <- e. rewrite assoc'.\n          rewrite w. reflexivity.\n        + cbn beta. intros [l w]; unfold hfiber. assert (PO := po T h l (!w)); clear po.\n          generalize PO; clear PO. apply iscontrweqb.\n          refine (weqcomp (weqtotal2asstor _ _) _). apply weqfibtototal; intros m. cbn.\n          apply weqiff.\n          { split.\n            - intros [x y]. split.\n              + exact x.\n              + exact (maponpaths pr1 y).\n            - intros [x y]. exists x. induction y. apply maponpaths, to_has_homsets.\n            }\n          { apply isofhleveltotal2.\n              - apply to_has_homsets.\n              - intros u. refine ((_:isofhlevel 2 _) _ _). apply isofhleveltotal2.\n                + apply to_has_homsets.\n                + intros n. apply hlevelntosn. apply to_has_homsets. }\n          { apply isapropdirprod; apply to_has_homsets. }\n    Qed.\n  End Tmp.\n  Lemma PullbackKernel {M:PreAdditive} {A B C D E:M} (i:A<--B) (p:B<--C)\n        (j:B<--D) (p':D<--E) (j':C<--E) :\n    isKernel' p i -> isPullback' (M:=M) j p p' j' -> isKernel' p' (i∘j).\n  Proof.\n    exact (@PushoutCokernel (oppositePreAdditive M) A B C D E i p j p' j').\n  Defined.\n  Lemma KernelIsMonic {M:PreAdditive} {x y z:M} (f : x --> y) (g : y --> z) : isKernel' f g -> isMonic f.\n  Proof.\n    intros [t i] w p q e.\n    set (T := ∑ r : w --> x, r · f = q · f). assert (ic : ∏ t1 t2 : T, t1 = t2).\n    { apply proofirrelevancecontr.\n      use i. rewrite assoc'. rewrite t. apply zeroRight. }\n    set (t1 := (p,,e) : T). set (t2 := (q,,idpath _) : T).\n    assert (Q := ic t1 t2). exact (maponpaths pr1 Q).\n  Qed.\n  Lemma CokernelIsEpi {M:PreAdditive} {x y z:M} (f : x --> y) (g : y --> z) : isCokernel' f g -> isEpi g.\n  Proof.\n    exact (KernelIsMonic (M:=oppositePreAdditive M) g f).\n  Qed.\n  Definition makeMonicKernel {M:PreAdditive} {x y z : M} (f : x --> y) (g : y --> z) :\n    isMonic f -> f · g = 0 ->\n    (∏ (w : M) (h : w --> y), h · g = 0 -> ∑ φ : w --> x, φ · f = h) ->\n    isKernel' f g.\n  Proof.\n    intros im eq ex. exists eq. intros w h e.\n    apply iscontraprop1.\n    - apply invproofirrelevance; intros [r R] [s S].\n      Unset Printing Notations. Arguments paths _ _ _ : clear implicits.\n      try assumption.\n      refine (@subtypePath_prop _ _ (_,,_) (_,,_) _); simpl. apply im. exact (R@!S).\n    - apply ex. exact e.\n  Qed.\n  Definition makeEpiCokernel {M:PreAdditive} {x y z : M} (f : x --> y) (g : y --> z) :\n    isEpi g -> f · g = 0 ->\n    (∏ (w : M) (h : y --> w), f · h = 0 -> ∑ φ : z --> w, g · φ = h) ->\n    isCokernel' f g.\n  Proof.\n    exact (makeMonicKernel (M:=oppositePreAdditive M) g f).\n  Qed.\n  Lemma IsoWithKernel {M:PreAdditive} {x y z z':M} (f : x --> y) (g : y --> z) (h : z --> z') :\n    isKernel' f g -> is_z_isomorphism h -> isKernel' f (g·h).\n  Proof.\n    intros i j.\n    apply makeMonicKernel.\n    - exact (KernelIsMonic _ _ i).\n    - exact (assoc _ _ _ @ maponpaths (postcomp_with _) (pr1 i) @ zeroLeft h).\n    - intros w k e. apply (pr2 i).\n      refine (post_comp_with_iso_is_inj _ _ h (is_iso_from_is_z_iso h j) _ _ _ _).\n      refine (! assoc _ _ _ @ e @ ! zeroLeft _).\n  Qed.\n  Lemma IsoWithCokernel {M:PreAdditive} {x x' y z:M} (f : x --> y) (g : y --> z) (h : x' --> x) :\n    isCokernel' f g -> is_z_isomorphism h -> isCokernel' (h·f) g.\n  Proof.\n    exact (λ c i, IsoWithKernel (M:=oppositePreAdditive M) g f h c (opp_is_z_isomorphism h i)).\n  Qed.\n  Lemma KernelOfZeroMapIsIso {M:PreAdditive} {x y z:M} (g : x --> y) : isKernel' g (0 : y --> z) -> is_z_isomorphism g.\n  (* compare with KernelofZeroArrow_is_iso *)\n  Proof.\n    intros [_ ke]. use (is_z_iso_from_is_iso' M). intros T h. exact (ke _ _ (zeroRight _)).\n  Defined.\n  Lemma CokernelOfZeroMapIsIso {M:PreAdditive} {x y z:M} (g : y --> z) : isCokernel' (0 : x --> y) g -> is_z_isomorphism g.\n  (* compare with CokernelofZeroArrow_is_iso *)\n  Proof.\n    intros [_ co]. use is_z_iso_from_is_iso. intros T h. exact (co _ _ (zeroLeft _)).\n  Defined.\n  Lemma KernelUniqueness {M:PreAdditive} {x x' y z : M} {f : x --> y} {f' : x' --> y} {g : y --> z} :\n    isKernel' f g -> isKernel' f' g -> iscontr (IsoArrowTo f f').\n  Proof.\n    intros i j. apply iscontraprop1.\n    - exact (IsoArrowTo_isaprop M f f' (KernelIsMonic f' g j)).\n    - induction (iscontrpr1 (pr2 j _ f (pr1 i))) as [p P].\n      induction (iscontrpr1 (pr2 i _ f' (pr1 j))) as [q Q].\n      use tpair.\n      + exists p. exists q. split.\n        * apply (KernelIsMonic _ _ i). rewrite assoc'. rewrite Q. rewrite P. rewrite id_left. reflexivity.\n        * apply (KernelIsMonic _ _ j). rewrite assoc'. rewrite P. rewrite Q. rewrite id_left. reflexivity.\n      + cbn. exact P.\n  Defined.\n  Lemma CokernelUniqueness {M:PreAdditive} {x y z z' : M} {f : x --> y} {g : y --> z} {g' : y --> z'} :\n    isCokernel' f g -> isCokernel' f g' -> iscontr (IsoArrowFrom g g').\n  Proof.\n    intros i j.\n    (*\n      The dual proof would go like this:\n      assert (Q := KernelUniqueness (M:=oppositePreAdditive M) i j).\n      generalize Q.\n      Now we would need this: weq (IsoArrowTo g g') (IsoArrowFrom g g')\n     *)\n    apply iscontraprop1.\n    - exact (IsoArrowFrom_isaprop M g g' (CokernelIsEpi f g i)).\n    - induction (iscontrpr1 (pr2 j _ g (pr1 i))) as [p P].\n      induction (iscontrpr1 (pr2 i _ g' (pr1 j))) as [q Q].\n      use tpair.\n      + exists q. exists p. split.\n        * apply (CokernelIsEpi _ _ i). rewrite assoc. rewrite Q. rewrite P. rewrite id_right. reflexivity.\n        * apply (CokernelIsEpi _ _ j). rewrite assoc. rewrite P. rewrite Q. rewrite id_right. reflexivity.\n      + cbn. exact Q.\n  Defined.\n  Lemma DirectSumToPullback {M:PreAdditive} {A B:M} (S : BinDirectSum A B) (Z : Zero M) :\n    Pullback (0 : A --> Z) (0 : B --> Z).\n  Proof.\n    use tpair.\n    - exists S. exact (to_Pr1 S,, to_Pr2 S).\n    - cbn. use tpair.\n      + apply ArrowsToZero.\n      + cbn. intros T f g e. exact (to_isBinProduct M S T f g).\n  Defined.\n  Lemma DirectSumToPushout {M:PreAdditive} {A B:M} (S : BinDirectSum A B) (Z : Zero M) :\n    Pushout (0 : Z --> A) (0 : Z --> B).\n  Proof.\n    use tpair.\n    - exists S. exact (to_In1 S,, to_In2 S).\n    - cbn. use tpair.\n      + apply ArrowsFromZero.\n      + cbn. intros T f g e. exact (to_isBinCoproduct M S T f g).\n  Defined.\n  Definition directSumMap {M:PreAdditive} {a b c d:M} (ac : BinDirectSum a c) (bd : BinDirectSum b d) (f : a --> b) (g : c --> d) : ac --> bd\n    := BinDirectSumIndAr f g _ _.\n  Lemma directSumMapEqPr1 {M:PreAdditive} {a b c d:M} {ac : BinDirectSum a c} {bd : BinDirectSum b d} {f : a --> b} {g : c --> d} :\n    directSumMap ac bd f g · π₁ = π₁ · f.\n  Proof.\n    apply BinDirectSumPr1Commutes.\n  Qed.\n  Lemma directSumMapEqPr2 {M:PreAdditive} {a b c d:M} {ac : BinDirectSum a c} {bd : BinDirectSum b d} {f : a --> b} {g : c --> d} :\n    directSumMap ac bd f g · π₂ = π₂ · g.\n  Proof.\n    apply BinDirectSumPr2Commutes.\n  Qed.\n  Lemma directSumMapEqIn1 {M:PreAdditive} {a b c d:M} {ac : BinDirectSum a c} {bd : BinDirectSum b d} {f : a --> b} {g : c --> d} :\n    ι₁ · directSumMap ac bd f g = f · ι₁.\n  Proof.\n    unfold directSumMap. rewrite BinDirectSumIndArEq. apply BinDirectSumIn1Commutes.\n  Qed.\n  Lemma directSumMapEqIn2 {M:PreAdditive} {a b c d:M} {ac : BinDirectSum a c} {bd : BinDirectSum b d} {f : a --> b} {g : c --> d} :\n    ι₂ · directSumMap ac bd f g = g · ι₂.\n  Proof.\n    unfold directSumMap. rewrite BinDirectSumIndArEq. apply BinDirectSumIn2Commutes.\n  Qed.\n  (* One of these should replace to_BinOpId upstream.  Also fix ToBinDirectSumFormula and FromBinDirectSumFormula. *)\n  Definition to_BinOpId' {M:PreAdditive} {a b co : M} {i1 : a --> co} {i2 : b --> co} {p1 : co --> a} {p2 : co --> b}\n             (B : isBinDirectSum i1 i2 p1 p2) :\n    p1 · i1 + p2 · i2 = identity co := to_BinOpId B.\n  Definition to_BinOpId'' {M:PreAdditive} {a b : M} (ab : BinDirectSum a b)\n             : (to_Pr1 ab · to_In1 ab) + (to_Pr2 ab · to_In2 ab) = 1\n    := to_BinOpId ab.\n  Definition ismonoidfun_prop {G H:abgr} (f:G->H) : hProp := make_hProp (ismonoidfun f) (isapropismonoidfun f).\n  Definition PreAdditive_functor (M N:PreAdditive) :=\n    ∑ F : M ⟶ N, ∀ A B:M, ismonoidfun_prop (@functor_on_morphisms M N F A B : A --> B -> F A --> F B).\n  Coercion PreAdditive_functor_to_functor {M N:PreAdditive} : PreAdditive_functor M N -> functor M N := pr1.\n  Definition functor_on_morphisms_add {C C' : PreAdditive} (F : PreAdditive_functor C C') { a b : C}\n    : monoidfun (a --> b) (F a --> F b)\n    := monoidfunconstr (pr2 F a b).\n  Local Notation \"# F\" := (functor_on_morphisms_add F) : abgrcat.\n  Lemma add_functor_comp {M N:PreAdditive} (F : PreAdditive_functor M N) {A B C:M} (f:A --> B) (g:B --> C) :\n    # F (f · g) = # F f · # F g.\n  Proof.\n    exact (functor_comp F f g).\n  Qed.\n  Lemma add_functor_add {M N:PreAdditive} (F : PreAdditive_functor M N) {A B:M} (f g:A --> B) :\n    # F (f+g) = # F f + # F g.\n  Proof.\n    exact (ismonoidfunisbinopfun (pr2 F A B) f g).\n  Qed.\n  Lemma add_functor_zero {M N:PreAdditive} (F : PreAdditive_functor M N) (A B:M) :\n    functor_on_morphisms_add (a:=A) (b:=B) F 0 = 0.\n  Proof.\n    exact (ismonoidfununel (pr2 F A B)).\n  Qed.\n  Lemma add_functor_sub {M N:PreAdditive} (F : PreAdditive_functor M N) {A B:M} (g:A --> B) :\n    # F (-g) = - # F g.\n  Proof.\n    exact (grinvandmonoidfun _ _ (pr2 F A B) g).\n  Qed.\n  Lemma zeroCriterion {M:PreAdditive} {Z:M} : identity Z = 0 <-> isZero Z.\n  Proof.\n    split.\n    { intros e. split.\n      - intros T. exists 0. intros h. refine (! id_left h @ _). induction (!e); clear e. apply zeroLeft.\n      - intros T. exists 0. intros h. refine (! id_right h @ _). induction (!e); clear e. apply zeroRight. }\n    { intros i. apply (isapropifcontr (pr1 i Z)). }\n  Qed.\n  Lemma applyFunctorToIsZero {M N:PreAdditive} (F : PreAdditive_functor M N) (Z : M) :\n    isZero Z -> isZero (F Z).\n  Proof.\n    exact (λ i, pr1 zeroCriterion (! functor_id F Z @ maponpaths (#F) (pr2 zeroCriterion i) @ add_functor_zero F Z Z)).\n  Qed.\n  Definition applyFunctorToZero {M N:PreAdditive} (F : PreAdditive_functor M N) : Zero M -> Zero N.\n  Proof.\n    intros Z. exact (F Z,, applyFunctorToIsZero F Z (pr2 Z)).\n  Defined.\n  Definition applyFunctorToIsBinDirectSum {M N:PreAdditive} (F : PreAdditive_functor M N)\n             (A B S : M) (i1 : A --> S) (i2 : B --> S) (p1 : S --> A) (p2 : S --> B) :\n    isBinDirectSum i1 i2 p1 p2 -> isBinDirectSum (# F i1) (# F i2) (# F p1) (# F p2).\n  Proof.\n    intros ds.\n    repeat split.\n    - rewrite <- add_functor_comp. rewrite (to_IdIn1 ds). apply functor_id.\n    - rewrite <- add_functor_comp. rewrite (to_IdIn2 ds). apply functor_id.\n    - rewrite <- add_functor_comp. rewrite (to_Unel1 ds); unfold to_unel. use ismonoidfununel. use (pr2 F).\n    - rewrite <- add_functor_comp. rewrite (to_Unel2 ds); unfold to_unel. use ismonoidfununel. use (pr2 F).\n    - rewrite <- 2 add_functor_comp. rewrite <- add_functor_add. rewrite (to_BinOpId' ds). apply functor_id.\n  Qed.\n  Definition applyFunctorToBinDirectSum {M N:PreAdditive} (F : PreAdditive_functor M N) {A B:M} :\n    BinDirectSum A B -> BinDirectSum (F A) (F B)\n    := λ S, make_BinDirectSum _ _ _ _ _ _ _ _ (applyFunctorToIsBinDirectSum F A B S ι₁ ι₂ π₁ π₂ (pr2 S)).\n  Definition induced_PreAdditive_incl (M : PreAdditive) {X:Type} (j : X -> ob M) :\n    PreAdditive_functor (induced_PreAdditive M j) M.\n  Proof.\n    exists (induced_precategory_incl j). intros A B. split.\n    + intros f g. reflexivity.\n    + reflexivity.\n  Defined.\n  Definition SwitchMap {M:PreAdditive} (a b:M) (ab : BinDirectSum a b) (ba : BinDirectSum b a) : ab --> ba := π₁ · ι₂ + π₂ · ι₁.\n  Lemma SwitchMapEqn {M:PreAdditive} {a b:M} (ab : BinDirectSum a b) (ba : BinDirectSum b a) : SwitchMap a b ab ba · SwitchMap b a ba ab = 1.\n  Proof.\n    unfold SwitchMap.\n    rewrite <- to_BinOpId''.\n    rewrite leftDistribute, 2 rightDistribute.\n    rewrite assoc', (assoc ι₂). rewrite DirectSumIn2Pr1.\n    rewrite zeroLeft, zeroRight, lunax.\n    rewrite assoc', (assoc ι₂). rewrite (to_IdIn2 ba), id_left.\n    apply maponpaths.\n    rewrite assoc', (assoc ι₁). rewrite (to_IdIn1 ba), id_left.\n    rewrite assoc', (assoc ι₁). rewrite DirectSumIn1Pr2.\n    rewrite zeroLeft, zeroRight, runax.\n    reflexivity.\n  Defined.\n  Definition SwitchIso {M:PreAdditive} (a b:M) (ab : BinDirectSum a b) (ba : BinDirectSum b a) : z_iso ab ba.\n  Proof.\n    exists (SwitchMap _ _ _ _). exists (SwitchMap _ _ _ _). split; apply SwitchMapEqn.\n  Defined.\n  Lemma SwitchMapEqnTo {M:PreAdditive} {a b c:M} (bc : BinDirectSum b c) (cb : BinDirectSum c b) (f:a-->b) (g:a-->c) :\n    ToBinDirectSum bc f g · SwitchMap b c bc cb = ToBinDirectSum cb g f.\n  Proof.\n    unfold SwitchMap. apply ToBinDirectSumsEq.\n    - rewrite rightDistribute. rewrite 2 assoc.\n      rewrite 2 BinDirectSumPr1Commutes, BinDirectSumPr2Commutes.\n      rewrite leftDistribute. rewrite 2 assoc'.\n      rewrite (to_Unel2 cb).\n      unfold to_unel.           (* fix to_Unel2! *)\n      rewrite zeroRight. rewrite lunax.\n      rewrite (to_IdIn1 cb). rewrite id_right. reflexivity.\n    - rewrite assoc'. rewrite leftDistribute. rewrite (assoc' π₂ _ π₂).\n      rewrite (to_Unel1 cb). unfold to_unel. rewrite zeroRight. rewrite runax.\n      rewrite 2 assoc. rewrite BinDirectSumPr1Commutes, BinDirectSumPr2Commutes.\n      rewrite assoc'. rewrite (to_IdIn2 cb). rewrite id_right. reflexivity.\n  Qed.\n  Lemma SwitchMapMapEqn {M:PreAdditive} {a b c d:M}\n        (ac : BinDirectSum a c) (ca : BinDirectSum c a)\n        (bd : BinDirectSum b d) (db : BinDirectSum d b)\n        (f : a --> b) (g : c --> d) :\n    SwitchMap c a ca ac · directSumMap ac bd f g = directSumMap ca db g f · SwitchMap d b db bd.\n  Proof.\n    unfold SwitchMap.\n    rewrite leftDistribute.\n    rewrite assoc'. rewrite directSumMapEqIn2. rewrite assoc.\n    rewrite rightDistribute. rewrite assoc. rewrite directSumMapEqPr1.\n    apply maponpaths.\n    rewrite assoc'. rewrite directSumMapEqIn1. rewrite assoc.\n    rewrite assoc. rewrite directSumMapEqPr2.\n    reflexivity.\n  Qed.\n  Definition directSumMapSwitch {M:PreAdditive} {a b c d:M}\n        (ac : BinDirectSum a c) (ca : BinDirectSum c a)\n        (bd : BinDirectSum b d) (db : BinDirectSum d b)\n        (f : a --> b) (g : c --> d) :\n    IsoArrow (directSumMap ac bd f g) (directSumMap ca db g f).\n  Proof.\n    exists (SwitchIso _ _ _ _). exists (SwitchIso _ _ _ _). apply SwitchMapMapEqn.\n  Defined.\n  Lemma opposite_directSumMap {M:PreAdditive} {a b c d:M}\n        (ac : BinDirectSum a c) (bd : BinDirectSum b d)\n        (f : a --> b) (g : c --> d) :\n    directSumMap (M:=oppositePreAdditive M) (oppositeBinDirectSum bd) (oppositeBinDirectSum ac) (opp_mor f) (opp_mor g)\n    =\n    opp_mor (directSumMap ac bd f g).\n  Proof.\n    apply BinDirectSumIndArEq.\n  Qed.\n  Lemma opposite_directSumMap' {M:PreAdditive} {a b c d:M}\n        (ac : BinDirectSum a c) (bd : BinDirectSum b d)\n        (f : a --> b) (g : c --> d) :\n    opp_mor (directSumMap (M:=oppositePreAdditive M) (oppositeBinDirectSum bd) (oppositeBinDirectSum ac) (opp_mor f) (opp_mor g))\n    =\n    directSumMap ac bd f g.\n  Proof.\n    apply (maponpaths opp_mor). apply opposite_directSumMap.\n  Qed.\n  Lemma SumOfKernels {M:PreAdditive} {x y z X Y Z : M}\n        (xX : BinDirectSum x X) (yY : BinDirectSum y Y) (zZ : BinDirectSum z Z)\n        (f : x --> y) (g : y --> z) (f' : X --> Y) (g' : Y --> Z) :\n    isKernel' f g -> isKernel' f' g' -> isKernel' (directSumMap xX yY f f') (directSumMap yY zZ g g').\n  Proof.\n    intros i i'. split.\n    { refine (BinDirectSumIndArComp _ _ _ _ _ _ _ _ @ ! _).\n      apply ToBinDirectSumUnique.\n      - exact (zeroLeft _ @ ! zeroRight _ @ maponpaths _ (! pr1 i)).\n      - exact (zeroLeft _ @ ! zeroRight _ @ maponpaths _ (! pr1 i')). }\n    intros w h e. apply iscontraprop1.\n    2:{\n      assert (e1 := ! assoc _ _ _\n                      @ ! maponpaths (precomp_with _) directSumMapEqPr1\n                      @ assoc _ _ _\n                      @ maponpaths (postcomp_with _) e\n                      @ zeroLeft _).\n      assert (e2 := ! assoc _ _ _\n                      @ ! maponpaths (precomp_with _) directSumMapEqPr2\n                      @ assoc _ _ _\n                      @ maponpaths (postcomp_with _) e\n                      @ zeroLeft _).\n      induction (iscontrpr1 (pr2 i  w (h · π₁) e1)) as [h1 H1].\n      induction (iscontrpr1 (pr2 i' w (h · π₂) e2)) as [h2 H2].\n      exists (ToBinDirectSum _ h1 h2).\n      apply ToBinDirectSumsEq.\n      + refine (! assoc _ _ _ @ _ @ H1).\n        refine (maponpaths (precomp_with _) directSumMapEqPr1 @ _).\n        unfold precomp_with.\n        refine (assoc _ _ _ @ _).\n        apply (maponpaths (postcomp_with _)).\n        apply BinDirectSumPr1Commutes.\n      + refine (! assoc _ _ _ @ _ @ H2).\n        refine (maponpaths (precomp_with _) directSumMapEqPr2 @ _).\n        unfold precomp_with.\n        refine (assoc _ _ _ @ _).\n        apply (maponpaths (postcomp_with _)).\n        apply BinDirectSumPr2Commutes. }\n    apply invproofirrelevance.\n    intros [k K] [k' K'].\n    apply subtypePath_prop; cbn.\n    apply ToBinDirectSumsEq.\n    - refine (KernelIsMonic _ _ i _ _ _ _).\n      exact (! assoc _ _ _\n               @ ! maponpaths (precomp_with k) directSumMapEqPr1\n               @ assoc _ _ _\n               @ maponpaths (postcomp_with _) (K @ !K')\n               @ ! assoc _ _ _\n               @ maponpaths (precomp_with k') directSumMapEqPr1\n               @ assoc _ _ _).\n    - refine (KernelIsMonic _ _ i' _ _ _ _).\n      exact (! assoc _ _ _\n               @ ! maponpaths (precomp_with k) directSumMapEqPr2\n               @ assoc _ _ _\n               @ maponpaths (postcomp_with _) (K @ !K')\n               @ ! assoc _ _ _\n               @ maponpaths (precomp_with k') directSumMapEqPr2\n               @ assoc _ _ _).\n  Qed.\n  Lemma SumOfCokernels {M:PreAdditive} {x y z X Y Z : M}\n        (xX : BinDirectSum x X) (yY : BinDirectSum y Y) (zZ : BinDirectSum z Z)\n        (f : x --> y) (g : y --> z) (f' : X --> Y) (g' : Y --> Z) :\n    isCokernel' f g -> isCokernel' f' g' -> isCokernel' (directSumMap xX yY f f') (directSumMap yY zZ g g').\n  Proof.\n    intros i i'.\n    rewrite <- (opposite_directSumMap' xX yY f f').\n    rewrite <- (opposite_directSumMap' yY zZ g g').\n    exact (SumOfKernels (M:=oppositePreAdditive M) (oppositeBinDirectSum zZ) (oppositeBinDirectSum yY) (oppositeBinDirectSum xX) g f g' f' i i').\n  Qed.\n  Lemma inducedMapReflectsKernels (M : PreAdditive) {X:Type} (j : X -> ob M)\n        {A B C:induced_PreAdditive M j} (i:A-->B) (p:B-->C) :\n    isKernel' (# (induced_PreAdditive_incl M j) i)\n              (# (induced_PreAdditive_incl M j) p)\n    ->\n    isKernel' i p.\n  Proof.\n    exact (λ k, pr1 k,,λ T h e, pr2 k (j T) h e).\n  Qed.\n  Lemma inducedMapReflectsCokernels (M : PreAdditive) {X:Type} (j : X -> ob M)\n        {A B C:induced_PreAdditive M j} (i:A-->B) (p:B-->C) :\n    isCokernel' (# (induced_PreAdditive_incl M j) i)\n              (# (induced_PreAdditive_incl M j) p)\n    ->\n    isCokernel' i p.\n  Proof.\n    exact (λ k, pr1 k,,λ T h e, pr2 k (j T) h e).\n  Qed.\nEnd PreAdditive.\nSection KernelCokernelPairs.\n  Definition isKernelCokernelPair {M :PreAdditive} {A B C:M} (i : A --> B) (p: B --> C) : hProp\n    := isKernel' i p ∧ isCokernel' i p.\n  Definition PairToKernel {M :PreAdditive} {A B C:M} {i : A --> B} {p: B --> C} :\n    isKernelCokernelPair i p -> isKernel' i p := pr1.\n  Definition PairToCokernel {M :PreAdditive} {A B C:M} {i : A --> B} {p: B --> C} :\n    isKernelCokernelPair i p -> isCokernel' i p := pr2.\n  Lemma inducedMapReflectsKernelCokernelPairs (M : PreAdditive) {X:Type} (j : X -> ob M)\n        {A B C:induced_PreAdditive M j} (i:A-->B) (p:B-->C) :\n    isKernelCokernelPair\n      (# (induced_PreAdditive_incl M j) i)\n      (# (induced_PreAdditive_incl M j) p)\n    ->\n    isKernelCokernelPair i p.\n  Proof.\n    intros [k c]. split.\n    - now apply inducedMapReflectsKernels.\n    - now apply inducedMapReflectsCokernels.\n  Qed.\n  Definition opposite_isKernelCokernelPair {M:PreAdditive} {A B C:M} {i : A --> B} {p: B --> C} :\n    isKernelCokernelPair i p -> isKernelCokernelPair (M:=oppositePreAdditive M) p i.\n  Proof.\n    intros s.\n    split.\n    - exact (PairToCokernel s).\n    - exact (PairToKernel s).\n  Defined.\n  Lemma PairUniqueness1 {M :PreAdditive} {A A' B C:M} (i : A --> B) (i' : A' --> B) (p: B --> C) :\n    isKernelCokernelPair i p -> isKernelCokernelPair i' p -> iscontr (IsoArrowTo i i').\n  Proof.\n    intros [k _] [k' _]. exact (KernelUniqueness k k').\n  Defined.\n  Lemma PairUniqueness2 {M :PreAdditive} {A B C C':M} (i : A --> B) (p: B --> C) (p': B --> C') :\n    isKernelCokernelPair i p -> isKernelCokernelPair i p' -> iscontr (IsoArrowFrom p p').\n  Proof.\n    intros [_ c] [_ c']. exact (CokernelUniqueness c c').\n  Defined.\n  Lemma kerCokerDirectSum {M :PreAdditive} {A B:M} (S:BinDirectSum A B) : isKernelCokernelPair (to_In1 S) (to_Pr2 S).\n  Proof.\n    assert (E := BinDirectSum_isBinDirectSum M S).\n    split.\n    - exists (to_Unel1 S). intros T h H. use unique_exists; cbn beta.\n      + exact (h · to_Pr1 S).\n      + refine (! assoc _ _ _ @ _ @ id_right _). rewrite <- (to_BinOpId' S).\n        rewrite rightDistribute. rewrite (assoc h (to_Pr2 S) (to_In2 S)).\n        rewrite H; clear H. rewrite zeroLeft. apply pathsinv0. apply (runax (T-->S)).\n      + intros k. apply to_has_homsets.\n      + clear H. intros k e. induction e. rewrite assoc'.\n        rewrite (to_IdIn1 S). apply pathsinv0, id_right.\n    - exists (to_Unel1 S). intros T h H. use unique_exists; cbn beta.\n      + exact (ι₂ · h).\n      + refine (assoc _ _ _ @ _ @ id_left h). rewrite <- (to_BinOpId' S).\n        rewrite leftDistribute.\n        rewrite <- (assoc (to_Pr1 S) (to_In1 S) h). rewrite H; clear H.\n        rewrite zeroRight. apply pathsinv0. apply (lunax (S-->T)).\n      + intros k. apply to_has_homsets.\n      + clear H. intros k e. induction e. rewrite assoc. rewrite (to_IdIn2 S).\n        exact (! id_left _).\n  Qed.\n  Lemma kerCoker10 {M :PreAdditive} (Z:Zero M) (A:M) : isKernelCokernelPair (identity A) (0 : A --> Z).\n  Proof.\n    exact (kerCokerDirectSum (TrivialDirectSum Z A)).\n  Qed.\n  Lemma kerCoker01 {M :PreAdditive} (Z:Zero M) (A:M) : isKernelCokernelPair (0 : Z --> A) (identity A).\n  Proof.\n    exact (kerCokerDirectSum (TrivialDirectSum' Z A)).\n  Qed.\n  Lemma PairPushoutMap {M :PreAdditive} {A B C A':M} {i : A --> B} {p : B --> C}\n        (pr : isKernelCokernelPair i p)\n        (r : A --> A') (po : Pushout i r) :\n    ∑ (q : po --> C), PushoutIn1 po · q = p × PushoutIn2 po · q = 0.\n  Proof.\n    refine (iscontrpr1 (isPushout_Pushout po C p 0 _)).\n    refine (pr1 (PairToCokernel pr) @ ! _). apply zeroRight.\n  Qed.\n  Lemma PairPullbackMap {M :PreAdditive} {A B C A':M} {i : A <-- B} {p : B <-- C}\n        (pr : isKernelCokernelPair p i)\n        (r : A <-- A') (pb : Pullback i r) :\n    ∑ (q : pb <-- C), PullbackPr1 pb ∘ q = p × PullbackPr2 pb ∘ q = 0.\n  Proof.\n    (* giving the dual proof here helps later! *)\n    exact (PairPushoutMap (M:=oppositePreAdditive M) (opposite_isKernelCokernelPair pr) r pb).\n  Defined.\n  Lemma PairPushoutCokernel {M :PreAdditive} {A B C A':M} (i : A --> B) (p : B --> C)\n        (pr : isKernelCokernelPair i p)\n        (r : A --> A') (po : Pushout i r)\n        (j := PushoutIn2 po)\n        (pp := PairPushoutMap pr r po) :\n    isCokernel' j (pr1 pp).\n  Proof.\n    set (s := PushoutIn1 po).\n    induction pp as [q [e1 e2]]; change (isCokernel' j q);\n      change (hProptoType (s · q = p)) in e1;\n      change (hProptoType (j · q = 0)) in e2.\n    exists e2.\n    intros T h e.\n    assert (L : i · (s · h) = 0).\n    { refine (assoc _ _ _ @ _).\n      intermediate_path (r · j · h).\n      { apply (maponpaths (λ s, s · h)). exact (PushoutSqrCommutes po). }\n      refine (! assoc _ _ _ @ _).\n      induction (!e).\n      apply zeroRight. }\n    assert (V := iscontrpr1 ((pr22 pr) T (s · h) L)); clear L.\n    induction V as [k e3].\n    use iscontraprop1.\n    { apply invproofirrelevance; intros φ φ'.\n      apply subtypePath_prop.\n      induction φ as [φ e4]; induction φ' as [φ' e5]; cbn.\n      use (_ : isEpi q).\n      { apply (isEpi_precomp M s q). rewrite e1. apply (CokernelIsEpi i p). apply pr. }\n      exact (e4 @ ! e5). }\n    exists  k.\n    use (MorphismsOutofPushoutEqual (isPushout_Pushout po)); fold s j.\n    { refine (assoc _ _ _ @ _ @ e3). apply (maponpaths (λ s, s · k)). exact e1. }\n    { refine (assoc _ _ _ @ _ @ ! e). rewrite e2. apply zeroLeft. }\n  Qed.\n  Lemma PairPullbackKernel {M : PreAdditive} {A B C A':M} (i : A <-- B) (p : B <-- C)\n        (pr : isKernelCokernelPair p i)\n        (r : A <-- A') (pb : Pullback i r)\n        (j := PullbackPr2 pb)\n        (pp := PairPullbackMap pr r pb) :\n    isKernel' (pr1 pp) j.\n  Proof.\n    (* Here's where giving the right proof of PairPullbackMap above helped us give this dual proof here. *)\n    exact (PairPushoutCokernel (M:=oppositePreAdditive M) i p (opposite_isKernelCokernelPair pr) r pb).\n  Defined.\n  Lemma SumOfKernelCokernelPairs {M : PreAdditive} {x y z X Y Z : M}\n        (xX : BinDirectSum x X) (yY : BinDirectSum y Y) (zZ : BinDirectSum z Z)\n        {f : x --> y} {g : y --> z} {f' : X --> Y} {g' : Y --> Z}\n    : isKernelCokernelPair f g -> isKernelCokernelPair f' g' -> isKernelCokernelPair (directSumMap xX yY f f') (directSumMap yY zZ g g').\n  Proof.\n    intros i i'.\n    exists (SumOfKernels   _ _ _ f g f' g' (pr1 i) (pr1 i')).\n    exact  (SumOfCokernels _ _ _ f g f' g' (pr2 i) (pr2 i')).\n  Qed.\nEnd KernelCokernelPairs.\n\nSection theDefinition.\n  Definition ExactCategoryData := ∑ M:AdditiveCategory, MorphismPair M -> hProp. (* properties added below *)\n  Coercion ExactCategoryDataToAdditiveCategory (ME : ExactCategoryData) : AdditiveCategory := pr1 ME.\n  Definition isExact {M : ExactCategoryData} (E : MorphismPair M) : hProp := pr2 M E.\n  Definition isExact2 {M : ExactCategoryData} {A B C:M} (f:A-->B) (g:B-->C) := isExact (make_MorphismPair f g).\n  Definition isAdmissibleMonomorphism {M : ExactCategoryData} {A B:M} (i : A --> B) : hProp :=\n    ∃ C (p : B --> C), isExact2 i p.\n  Definition AdmissibleMonomorphism {M : ExactCategoryData} (A B:M) : Type :=\n    ∑ (i : A --> B), isAdmissibleMonomorphism i.\n  Coercion AdmMonoToMap  {M : ExactCategoryData} {A B:M} : AdmissibleMonomorphism A B ->  A --> B := pr1.\n  Coercion AdmMonoToMap' {M : ExactCategoryData} {A B:M} : AdmissibleMonomorphism A B -> (A --> B)%cat := pr1.\n  Definition isAdmissibleEpimorphism {M : ExactCategoryData} {B C:M} (p : B --> C) : hProp :=\n    ∃ A (i : A --> B), isExact2 i p.\n  Definition AdmissibleEpimorphism {M : ExactCategoryData} (B C:M) : Type :=\n    ∑ (p : B --> C), isAdmissibleEpimorphism p.\n  Coercion AdmEpiToMap  {M : ExactCategoryData} {B C:M} : AdmissibleEpimorphism B C ->  B --> C := pr1.\n  Coercion AdmEpiToMap' {M : ExactCategoryData} {B C:M} : AdmissibleEpimorphism B C -> (B --> C)%cat := pr1.\n  Lemma ExactToAdmMono {M : ExactCategoryData} {A B C:M} {i : A --> B} {p : B --> C} : isExact2 i p -> isAdmissibleMonomorphism i.\n  Proof.\n    intros e. exact (hinhpr(C,,p,,e)).\n  Qed.\n  Lemma ExactToAdmEpi {M : ExactCategoryData} {A B C:M} {i : A --> B} {p : B --> C} : isExact2 i p -> isAdmissibleEpimorphism p.\n  Proof.\n    intros e. exact (hinhpr(A,,i,,e)).\n  Qed.\n  (** The following definition is definition 2.1 from the paper of Bühler. *)\n  Local Definition ExactCategoryProperties (M : ExactCategoryData) : hProp :=\n      ((∀ (P Q : MorphismPair M), MorphismPairIsomorphism P Q ⇒ isExact P ⇒ isExact Q) ∧\n       (∀ (P Q : MorphismPair M), MorphismPairIsomorphism Q P ⇒ isExact P ⇒ isExact Q)) ∧\n      ((∀ A:M, isAdmissibleMonomorphism (identity A)) ∧\n       (∀ A:M, isAdmissibleEpimorphism (identity A))) ∧\n      (∀ P : MorphismPair M, isExact P ⇒ isKernelCokernelPair (Mor1 P) (Mor2 P)) ∧\n      ((∀ (A B C:M) (f : A --> B) (g : B --> C),\n          isAdmissibleMonomorphism f ⇒ isAdmissibleMonomorphism g ⇒\n          isAdmissibleMonomorphism (f · g)) ∧\n       (∀ (A B C:M) (f : A --> B) (g : B --> C),\n          isAdmissibleEpimorphism f ⇒ isAdmissibleEpimorphism g ⇒\n          isAdmissibleEpimorphism (f · g))) ∧\n      ((∀ (A B C:M) (f : A --> B) (g : C --> B),\n          isAdmissibleEpimorphism f ⇒\n          ∃ (PB : Pullback f g), isAdmissibleEpimorphism (PullbackPr2 PB)) ∧\n       (∀ (A B C:M) (f : B --> A) (g : B --> C),\n          isAdmissibleMonomorphism f ⇒\n          ∃ (PO : Pushout f g), isAdmissibleMonomorphism (PushoutIn2 PO))).\n  (** The following definition is from Higher Algebraic K-theory I, by Quillen.\n      We prove below that the two definitions are equivalent. *)\n  Local Definition ExactCategoryProperties_Quillen (M : ExactCategoryData) : hProp :=\n      (∀ (P Q:MorphismPair M), MorphismPairIsomorphism P Q ⇒ isExact P ⇒ isExact Q) ∧\n      (∀ (A B:M) (AB:BinDirectSum A B), isExact2 (to_In1 AB) (to_Pr2 AB)) ∧\n      (∀ P : MorphismPair M, isExact P ⇒ isKernel' (Mor1 P) (Mor2 P) ∧ isCokernel' (Mor1 P) (Mor2 P)) ∧\n      ((∀ (A B C:M) (f : A --> B) (g : B --> C),\n          isAdmissibleMonomorphism f ⇒ isAdmissibleMonomorphism g ⇒\n          isAdmissibleMonomorphism (f · g)) ∧\n       (∀ (A B C:M) (f : A --> B) (g : B --> C),\n          isAdmissibleEpimorphism f ⇒ isAdmissibleEpimorphism g ⇒\n          isAdmissibleEpimorphism (f · g))) ∧\n      ((∀ (A B C:M) (f : A --> B) (g : C --> B),\n          isAdmissibleEpimorphism f ⇒\n          ∃ (PB : Pullback f g), isAdmissibleEpimorphism (PullbackPr2 PB)) ∧\n       (∀ (A B C:M) (f : B --> A) (g : B --> C),\n          isAdmissibleMonomorphism f ⇒\n          ∃ (PO : Pushout f g), isAdmissibleMonomorphism (PushoutIn2 PO))) ∧\n       ((∀ (A B C:M) (i:A-->B) (j:B-->C),\n          hasCokernel i ⇒ isAdmissibleMonomorphism (i·j) ⇒ isAdmissibleMonomorphism i) ∧\n        (∀ (A B C:M) (i:A-->B) (j:B-->C),\n          hasKernel j ⇒ isAdmissibleEpimorphism (i·j) ⇒ isAdmissibleEpimorphism j)).\n  Definition ExactCategory := ∑ (ME:ExactCategoryData), ExactCategoryProperties ME.\n  Coercion ExactCategoryToData (M:ExactCategory) : ExactCategoryData := pr1 M.\n  Definition make_ExactCategory (ME:ExactCategoryData) (p : ExactCategoryProperties ME) : ExactCategory := ME,,p.\n  Definition isExactFunctor {M N:ExactCategory} (F : M ⟶ N) : hProp\n    := ∀ (P : MorphismPair M), isExact P ⇒ isExact (applyFunctorToPair F P).\n  Definition ExactFunctor (M N:ExactCategory)\n    := ∑ F : M ⟶ N, isExactFunctor F.\n  (* TO DO : show an exact functor is additive, or else include that as a condition.\n     That includes showing it induces monoid functions on Hom groups.\n     Start by defining preadditive functors and additive functors. *)\n  Coercion ExactFunctorToFunctor {M N:ExactCategory}\n    : ExactFunctor M N -> (M ⟶ N)\n    := pr1.\n  Definition ShortExactSequence (M:ExactCategory) := ∑ (P : MorphismPair M), isExact P.\n  Coercion ShortExactSequenceToMorphismPair {M:ExactCategory} (P : ShortExactSequence M)\n    : MorphismPair M\n    := pr1 P.\n  Definition ShortExactSequenceMap {M:ExactCategory} (P Q:ShortExactSequence M) := MorphismPairMap P Q.\n  Definition applyFunctorToShortExactSequence {M N:ExactCategory} (F : ExactFunctor M N) :\n    ShortExactSequence M -> ShortExactSequence N.\n  Proof.\n    intros E. exists (applyFunctorToPair F E).\n    induction E as [E iE]. unfold ShortExactSequenceToMorphismPair,pr1.\n    exact (pr2 F E iE).\n  Defined.\n  Definition composeExactFunctors {L M N:ExactCategory} : ExactFunctor L M -> ExactFunctor M N -> ExactFunctor L N.\n  Proof.\n    intros F G. exists (F ∙ G). exact (λ E e, pr2 G _ (pr2 F E e)).\n  Defined.\nEnd theDefinition.\n\nDeclare Scope excat.\nDelimit Scope excat with excat.\nLocal Open Scope excat.\nNotation \"A ↣ B\" := (AdmissibleMonomorphism A B) : excat.\nNotation \"B ↠ C\" := (AdmissibleEpimorphism  B C) : excat.\nNotation \"F ∙ G\" := (composeExactFunctors F G) : excat.\nNotation \"M ⟶ N\" := (ExactFunctor M N) : excat.\n\nSection ExactCategoryAccessFunctions.\n  Context {M:ExactCategory}.\n  Definition EC_IsomorphicToExact {P Q:MorphismPair M}\n    : MorphismPairIsomorphism P Q ⇒ isExact P ⇒ isExact Q\n    := pr112 M P Q.\n  Definition EC_IsomorphicToExact' {P Q:MorphismPair M}\n    : MorphismPairIsomorphism Q P ⇒ isExact P ⇒ isExact Q\n    := pr212 M P Q.\n  Definition EC_IdentityIsMono (A:M) : isAdmissibleMonomorphism (identity A)\n    := pr1 (pr122 M) A.\n  Definition IdentityMono (A:M) : AdmissibleMonomorphism A A\n    := identity A,, EC_IdentityIsMono A.\n  Definition EC_IdentityIsEpi (A:M) : isAdmissibleEpimorphism (identity A)\n    := pr2 (pr122 M) A.\n  Definition IdentityEpi (A:M) : AdmissibleEpimorphism A A\n    := identity A,, EC_IdentityIsEpi A.\n  Definition EC_ExactToKernelCokernel {P : MorphismPair M} :\n    isExact P ⇒ isKernelCokernelPair (Mor1 P) (Mor2 P)\n    := pr12 (pr22 M) P.\n  Definition EC_ExactToKernel {P : MorphismPair M} :\n    isExact P ⇒ isKernel' (Mor1 P) (Mor2 P)\n    := λ i, (pr1 (EC_ExactToKernelCokernel i)).\n  Definition EC_ExactToCokernel {P : MorphismPair M} :\n    isExact P ⇒ isCokernel' (Mor1 P) (Mor2 P)\n    := λ i, (pr2 (EC_ExactToKernelCokernel i)).\n  Definition EC_ComposeMono {A B C:M} (f : A --> B) (g : B --> C) :\n    isAdmissibleMonomorphism f -> isAdmissibleMonomorphism g ->\n    isAdmissibleMonomorphism (f · g)\n    := pr112 (pr222 M) A B C f g.\n  Definition EC_ComposeEpi {A B C:M} (f : A --> B) (g : B --> C) :\n    isAdmissibleEpimorphism f ⇒ isAdmissibleEpimorphism g ⇒\n    isAdmissibleEpimorphism (f · g)\n    := pr212 (pr222 M) A B C f g.\n  Definition EC_PullbackEpi {A B C:M} (f : A --> B) (g : C --> B) :\n    isAdmissibleEpimorphism f ⇒\n    ∃ (PB : Pullback f g), isAdmissibleEpimorphism (PullbackPr2 PB)\n    := pr122 (pr222 M) A B C f g.\n  Definition EC_PushoutMono {A B C:M} (f : B --> A) (g : B --> C) :\n    isAdmissibleMonomorphism f ⇒\n    ∃ (PO : Pushout f g), isAdmissibleMonomorphism (PushoutIn2 PO)\n    := pr222 (pr222 M) A B C f g.\nEnd ExactCategoryAccessFunctions.\n\nSection OppositeExactCategory.\n  Definition oppositeExactCategoryData (M:ExactCategoryData) : ExactCategoryData.\n  Proof.\n    exists (oppositeAdditiveCategory M). exact (λ p, @isExact M (opp_MorphismPair p)).\n  Defined.\n  Definition oppositeExactCategory (M:ExactCategory) : ExactCategory.\n  Proof.\n    use (make_ExactCategory (oppositeExactCategoryData M)).\n    split.\n    { split;intros P Q f.\n      - exact (EC_IsomorphicToExact' (opp_MorphismPairIsomorphism f)).\n      - exact (EC_IsomorphicToExact (opp_MorphismPairIsomorphism f)). }\n    split.\n    { split.\n      - exact EC_IdentityIsEpi.\n      - exact EC_IdentityIsMono. }\n    split.\n    { intros P i. exact (opposite_isKernelCokernelPair (EC_ExactToKernelCokernel i)). }\n    split.\n    { split.\n      { intros A B C f g i j. exact (@EC_ComposeEpi M C B A g f j i). }\n      { intros A B C f g i j. exact (@EC_ComposeMono M C B A g f j i). } }\n    { split.\n      { exact (@EC_PushoutMono M). }\n      { exact (@EC_PullbackEpi M). } }\n  Defined.\nEnd OppositeExactCategory.\n\nNotation \"C '^op'\" := (oppositeExactCategory C) (at level 3, format \"C ^op\") : excat.\n\nSection ExactCategoryFacts.\n  Lemma ExactToMono {M : ExactCategory} {A B C:M} {i : A --> B} {p : B --> C} : isExact2 i p -> isMonic i.\n  Proof.\n    intros e. exact (KernelIsMonic i p (EC_ExactToKernel e)).\n  Qed.\n  Lemma ExactToEpi {M : ExactCategory} {A B C:M} {i : A --> B} {p : B --> C} : isExact2 i p -> isEpi p.\n  Proof.\n    intros e. refine (CokernelIsEpi i p (EC_ExactToCokernel e)).\n  Qed.\n  Lemma ExactSequenceFromMono {M : ExactCategory} {A B C:M} (i : A --> B) (p : B --> C) :\n    isCokernel' i p -> isAdmissibleMonomorphism i -> isExact2 i p.\n  Proof.\n    intros co mo. apply (squash_to_hProp mo); clear mo; intros [C' [p' e]].\n    assert (co' := pr2 (EC_ExactToKernelCokernel e) : isCokernel' i p').\n    assert (R := iscontrpr1 (CokernelUniqueness co' co)). induction R as [R r].\n    use (EC_IsomorphicToExact _ e).\n    exists (identity_z_iso _). exists (identity_z_iso _). exists R.\n    split.\n    - split.\n      + exact (id_left _ @ ! id_right _).\n      + exact (id_right _ @ ! id_left _).\n    - split.\n      + exact (id_left _ @ ! r).\n      + exact (r @ !id_left _).\n  Qed.\n  Lemma ExactSequenceFromEpi {M : ExactCategory} {A B C:M} (i : A --> B) (p : B --> C) :\n    isKernel' i p -> isAdmissibleEpimorphism p -> isExact2 i p.\n  Proof.\n    exact (ExactSequenceFromMono (M:=M^op) p i).\n  Defined.\n  Lemma ExactSequence10 {M : ExactCategory} (A:M) (Z:Zero M) : isExact2 (identity A) (0 : A --> Z).\n  Proof.\n    exact (ExactSequenceFromMono _ _ (pr2 (kerCoker10 Z A)) (EC_IdentityIsMono A)).\n  Qed.\n  Lemma ExactSequence01 {M : ExactCategory} (A:M) (Z:Zero M) : isExact2 (0 : Z --> A) (identity A).\n  Proof.\n    exact (ExactSequenceFromEpi _ _ (pr1 (kerCoker01 Z A)) (EC_IdentityIsEpi A)).\n  Qed.\n  Lemma FromZeroIsMono {M : ExactCategory} (Z:Zero M) (A:M) : isAdmissibleMonomorphism (0 : Z --> A).\n  Proof.\n    apply hinhpr. exists A. exists (identity A). use ExactSequence01.\n  Defined.\n  Definition MonoFromZero {M : ExactCategory} (Z:Zero M) (A:M) : Z ↣ A\n    := (0 : Z --> A),,FromZeroIsMono Z A.\n  Lemma ToZeroIsEpi {M : ExactCategory} (A:M) (Z:Zero M) : isAdmissibleEpimorphism (0 : A --> Z).\n  Proof.\n    apply hinhpr. exists A. exists (identity A). use ExactSequence10.\n  Defined.\n  Definition EpiToZero {M : ExactCategory} (A:M) (Z:Zero M) : A ↠ Z\n    := (0 : A --> Z),,ToZeroIsEpi A Z.\n  Goal ∏ (M:ExactCategory) (A:M) (Z:Zero M), EpiToZero A Z = MonoFromZero (M:=M^op) (Zero_opp M Z) A.\n  Abort.\n  Lemma IsomMono1 {M : ExactCategory} {A B B':M} (f : A --> B) (f' : A --> B') :\n    IsoArrowFrom f f' -> isAdmissibleMonomorphism f -> isAdmissibleMonomorphism f'.\n  Proof.\n    intros [i I] E. apply (squash_to_hProp E); clear E; intros [C [p E]].\n    apply hinhpr. exists C. exists (z_iso_inv i · p). use (EC_IsomorphicToExact _ E).\n    exists (identity_z_iso A). exists i. exists (identity_z_iso C). split; cbn.\n    - split.\n      + exact (id_left _ @ ! I).\n      + exact (I @ ! id_left _).\n    - split.\n      + refine (assoc _ _ _ @ _ @ id_left _ @ ! id_right _).\n        apply (maponpaths (λ k, k · p)). apply z_iso_inv_after_z_iso.\n      + apply pathsinv0.\n        refine (assoc _ _ _ @ _ @ id_left _ @ ! id_right _).\n        apply (maponpaths (λ k, k · p)). apply z_iso_inv_after_z_iso.\n  Qed.\n  Lemma IsomEpi1 {M : ExactCategory} {A A' B:M} (f : A --> B) (f' : A' --> B) :\n    IsoArrowTo f' f -> isAdmissibleEpimorphism f -> isAdmissibleEpimorphism f'.\n  Proof.\n    intros i e.\n    exact (IsomMono1 (M:=M^op) f f' (opposite_IsoArrowTo i) e).\n  Defined.\n  Lemma IsomMono {M : ExactCategory} {A A' B B':M} (f : A --> B) (f' : A' --> B') :\n    IsoArrow f f' -> isAdmissibleMonomorphism f -> isAdmissibleMonomorphism f'.\n  Proof.\n    intros [g [h e]] i. apply (squash_to_hProp i); clear i; intros [C [p E]].\n    apply hinhpr. exists C. exists (z_iso_inv h · p). use (EC_IsomorphicToExact _ E).\n    simple refine (make_MorphismPairIsomorphism\n                     (make_MorphismPair f p) (make_MorphismPair f' (z_iso_inv h · p))\n                     g h (identity_z_iso C) e _).\n    refine (assoc _ _ _ @ maponpaths (postcomp_with p) _ @ id_left p @ ! id_right p).\n    apply z_iso_inv_after_z_iso.\n  Qed.\n  Lemma IsomEpi {M : ExactCategory} {A A' B B':M} (f : A --> B) (f' : A' --> B') :\n    IsoArrow f' f -> isAdmissibleEpimorphism f -> isAdmissibleEpimorphism f'.\n  Proof.\n    intros i.\n    exact (IsomMono (M:=M^op) f f' (opposite_IsoArrow _ _ i)).\n  Defined.\n  Lemma PullbackEpiIsEpi {M : ExactCategory} {A B C:M} (f : A --> B) (g : C --> B)\n        (pb : Pullback f g) :\n    isAdmissibleEpimorphism f -> isAdmissibleEpimorphism (PullbackPr2 pb).\n  (* dual needed *)\n  Proof.\n    intros fepi.\n    assert (qb := EC_PullbackEpi f g fepi).\n    apply (squash_to_hProp qb); clear qb; intros [qb epi2].\n    assert (I := pullbackiso2 pb qb).\n    apply (IsomEpi1 _ _ I). exact epi2.\n  Qed.\n  Lemma IsPullbackEpiIsEpi {M : ExactCategory} {P A B C:M} {f : A --> B} {g : C --> B}\n        {h : P --> A} {k : P --> C} :\n    isPullback' (M:=M) f g h k -> isAdmissibleEpimorphism f -> isAdmissibleEpimorphism k.\n  (* dual needed *)\n  Proof.\n    intros pb. exact (PullbackEpiIsEpi f g (make_Pullback _ (pr2 pb))).\n  Qed.\n  Lemma IsIsoIsMono {M : ExactCategory} {A B:M} (f:A-->B) :\n    is_z_isomorphism f -> isAdmissibleMonomorphism f.\n  Proof.\n    intros i.\n    use (IsomMono1 (identity A)).\n    - use tpair.\n      + exact (f,,i).\n      + cbn. apply id_left.\n    - apply EC_IdentityIsMono.\n  Qed.\n  Lemma IsoIsMono {M : ExactCategory} {A B:M} (f:z_iso A B) : isAdmissibleMonomorphism (z_iso_mor f).\n  Proof.\n    use IsIsoIsMono. apply f.\n  Qed.\n  Definition IsoToAdmMono {M : ExactCategory} {A B:M} (f:z_iso A B) : AdmissibleMonomorphism A B\n    := z_iso_mor f,,IsoIsMono f.\n  Lemma IsoIsEpi {M : ExactCategory} {A B:M} (f:z_iso A B) : isAdmissibleEpimorphism (z_iso_mor f).\n  Proof.\n    exact (IsoIsMono (M:=M^op) (opp_z_iso f)).\n  Defined.\n  Definition IsoToAdmEpi {M : ExactCategory} {A B:M} (f:z_iso A B) : AdmissibleEpimorphism A B\n    := z_iso_mor f,,IsoIsEpi f.\n  Lemma DirectSumToExact {M : ExactCategory} {A B:M} (S:BinDirectSum A B) : isExact2 (to_In1 S) (to_Pr2 S).\n  Proof.\n    use ExactSequenceFromEpi.\n    { exact (PairToKernel (kerCokerDirectSum S)). }\n    apply (squash_to_hProp (to_hasZero M)); intros Z.\n    set (pb := DirectSumToPullback S Z).\n    change (isAdmissibleEpimorphism (PullbackPr2 pb)).\n    assert (Q := EC_PullbackEpi (0 : A --> Z) (0 : B --> Z) (ToZeroIsEpi A Z)).\n    apply (squash_to_hProp Q); clear Q; intros [pb' R'].\n    exact (IsomEpi1 (PullbackPr2 pb') (PullbackPr2 pb) (pullbackiso2 pb pb') R').\n  Qed.\n  Lemma DirectSumToExact' {M : ExactCategory} {A B:M} (S:BinDirectSum A B) : isExact2 (to_In2 S) (to_Pr1 S).\n  Proof.\n    exact (DirectSumToExact (reverseBinDirectSum S)).\n  Qed.\n  Lemma In1IsAdmMono {M : ExactCategory} {A B:M} (S:BinDirectSum A B) : isAdmissibleMonomorphism (ι₁ : A --> S).\n  Proof.\n    exact (hinhpr (B,,to_Pr2 S,,DirectSumToExact S)).\n  Qed.\n  Lemma In2IsAdmMono {M : ExactCategory} {A B:M} (S:BinDirectSum A B) : isAdmissibleMonomorphism (ι₂ : B --> S).\n  Proof.\n    exact (hinhpr (A,,to_Pr1 S,,DirectSumToExact' S)).\n  Qed.\n  Lemma Pr1IsAdmEpi {M : ExactCategory} {A B:M} (S:BinDirectSum A B) : isAdmissibleEpimorphism (π₁ : S --> A).\n  Proof.\n    exact (hinhpr (B,,to_In2 S,,DirectSumToExact' S)).\n  Qed.\n  Lemma Pr2IsAdmEpi {M : ExactCategory} {A B:M} (S:BinDirectSum A B) : isAdmissibleEpimorphism (π₂ : S --> B).\n  Proof.\n    exact (hinhpr (A,,to_In1 S,,DirectSumToExact S)).\n  Qed.\n  Definition In1AdmMono {M : ExactCategory} {A B:M} (S:BinDirectSum A B) : AdmissibleMonomorphism A S := ι₁ ,, In1IsAdmMono S.\n  Definition In2AdmMono {M : ExactCategory} {A B:M} (S:BinDirectSum A B) : AdmissibleMonomorphism B S := ι₂ ,, In2IsAdmMono S.\n  Definition Pr1AdmEpi {M : ExactCategory} {A B:M} (S:BinDirectSum A B) : AdmissibleEpimorphism S A := π₁ ,, Pr1IsAdmEpi S.\n  Definition Pr2AdmEpi {M : ExactCategory} {A B:M} (S:BinDirectSum A B) : AdmissibleEpimorphism S B := π₂ ,, Pr2IsAdmEpi S.\n  Definition TrivialExactSequence {M : ExactCategory} (A:M) (Z:Zero M) : ShortExactSequence M.\n  Proof.\n    assert (Q := DirectSumToExact (TrivialDirectSum Z A)).\n    exact (make_MorphismPair ι₁ π₂,, Q).\n  Defined.\n  Definition TrivialExactSequence' {M : ExactCategory} (Z:Zero M) (A:M) : ShortExactSequence M.\n  Proof.\n    assert (Q := DirectSumToExact (TrivialDirectSum' Z A)).\n    exact (make_MorphismPair ι₁ π₂,, Q).\n  Defined.\n  Lemma ExactPushout {M : ExactCategory} {A B C A':M} (i : A --> B) (p : B --> C)\n        (pr : isExact2 i p) (r : A --> A') :\n    ∃ (po : Pushout i r),\n      isExact2 (PushoutIn2 po) (pr1 (PairPushoutMap (EC_ExactToKernelCokernel pr) r po)).\n  Proof.\n    assert (I := ExactToAdmMono pr).\n    assert (R := EC_PushoutMono i r I).\n    apply (squash_to_hProp R); clear R; intros [po J]; apply hinhpr.\n    exists po. use ExactSequenceFromMono.\n    { exact (PairPushoutCokernel i p (EC_ExactToKernelCokernel pr) r po). }\n    exact J.\n  Qed.\n  Lemma ExactPushout' {M : ExactCategory} {A B C A':M} (i : A --> B) (p : B --> C)\n        (pr : isExact2 i p) (r : A --> A') :\n    ∃ (B':M) (i':A'-->B') (s:B-->B') (p':B'-->C),\n       s·p' = p ∧ isPushout' (M:=M) i r s i' ∧ isExact2 i' p'.\n  Proof.\n    assert (I := ExactToAdmMono pr). assert (R := EC_PushoutMono i r I).\n    use (hinhfun _ R); clear R; intros [po J].\n    set (pomap := PairPushoutMap (EC_ExactToKernelCokernel pr) r po).\n    set (p' := pr1 pomap).\n    exists po. exists (PushoutIn2 po). exists (PushoutIn1 po). exists p'.\n    split.\n    { exact (pr12 pomap). }\n    split.\n    { apply Pushout_to_isPushout'. }\n    { use ExactSequenceFromMono.\n      { exact (PairPushoutCokernel i p (EC_ExactToKernelCokernel pr) r po). }\n      exact J. }\n  Qed.\n  Lemma ExactPullback {M : ExactCategory} {A B C A':M} (i : A <-- B) (p : B <-- C)\n        (pr : isExact2 p i)\n        (r : A <-- A') :\n    ∃ (pb : Pullback i r),\n      isExact2 (pr1 (PairPullbackMap (EC_ExactToKernelCokernel pr) r pb)) (PullbackPr2 pb).\n  Proof.\n    assert (I := hinhpr (C ,, p ,, pr) : isAdmissibleEpimorphism i).\n    assert (R := EC_PullbackEpi i r I).\n    apply (squash_to_hProp R); clear R; intros [pb J]; apply hinhpr.\n    exists pb. use ExactSequenceFromEpi.\n    { exact (PairPullbackKernel i p (EC_ExactToKernelCokernel pr) r pb). }\n    exact J.\n  Qed.\n  Lemma ExactPullback' {M : ExactCategory} {A B C A':M} (i : A <-- B) (p : B <-- C)\n        (pr : isExact2 p i) (r : A <-- A') :\n    ∃ (B':M) (i':A'<--B') (s:B<--B') (p':B'<--C),\n      s∘p' = p ∧ isPullback' (M:=M) i r s i' ∧ isExact2 p' i'.\n  Proof.\n    assert (I := ExactToAdmEpi pr). assert (R := EC_PullbackEpi i r I).\n    use (hinhfun _ R); clear R; intros [pb J].\n    set (pbmap := PairPullbackMap (EC_ExactToKernelCokernel pr) r pb).\n    set (p' := pr1 pbmap).\n    exists pb. exists (PullbackPr2 pb). exists (PullbackPr1 pb). exists p'.\n    split.\n    { exact (pr12 pbmap). }\n    split.\n    { apply Pullback_to_isPullback'. }\n    { use ExactSequenceFromEpi.\n      { exact (PairPullbackKernel i p (EC_ExactToKernelCokernel pr) r pb). }\n      exact J. }\n  Qed.\n  Lemma MonicAdmEpiIsIso {M : ExactCategory} {A B:M} (p : A ↠ B) : isMonic p -> is_z_isomorphism p.\n  Proof.\n    induction p as [p E]. cbn. intros I. apply (squash_to_prop E).\n    { apply (isaprop_is_z_isomorphism (C:=M)). }\n    clear E; intros [K [i E]].\n    assert (Q := EC_ExactToKernelCokernel E); clear E.\n    induction Q as [ke co];\n      change (hProptoType (isKernel' i p)) in ke;\n      change (hProptoType (isCokernel' i p)) in co.\n    assert (Q : i = 0).\n    { use (I K i 0). exact (pr1 ke @ ! zeroLeft _). }\n    clear I ke. induction (!Q); clear Q. exact (CokernelOfZeroMapIsIso p co).\n  Qed.\n  Lemma EpiAdmMonoIsIso {M : ExactCategory} {A B:M} (i : A ↣ B) : isEpi i -> is_z_isomorphism i.\n  Proof.\n    intros e.\n    exact (opp_is_z_isomorphism _ (MonicAdmEpiIsIso (M:=M^op) i e)).\n  Defined.\n  Lemma MonoPlusIdentity {M : ExactCategory} {A B:M}\n        (f:A-->B) (C:M) (AC : BinDirectSum A C) (BC : BinDirectSum B C) :\n    isAdmissibleMonomorphism f -> isAdmissibleMonomorphism (directSumMap AC BC f (identity C)).\n  Proof.\n    (* see Bühler's 2.9 *)\n    intro i. apply (squash_to_hProp i). intros [D [p j]].\n    apply hinhpr. exists D. exists (π₁ · p). apply ExactSequenceFromEpi.\n    2:{ apply EC_ComposeEpi.\n        - apply Pr1IsAdmEpi.\n        - exact (hinhpr(A,,f,,j)). }\n    apply (squash_to_hProp (to_hasZero M)); intros Z.\n    apply (squash_to_hProp (to_hasBinDirectSums D Z)); intros DZ.\n    assert (m := pr1 (SumOfKernelCokernelPairs AC BC DZ\n                   (EC_ExactToKernelCokernel j : isKernelCokernelPair f p)\n                   (kerCoker10 Z C : isKernelCokernelPair (identity C) 0))).\n    assert (R : directSumMap BC DZ p 0 · to_Pr1 DZ = to_Pr1 BC · p).\n    { apply directSumMapEqPr1. }\n    induction R. apply IsoWithKernel.\n    { exact m. }\n    exists (ι₁). split.\n    { refine (! runax (_ --> _) _ @ ! _ @ to_BinOpId'' _). apply maponpaths. apply ThroughZeroIsZero. }\n    { refine (to_IdIn1 DZ). }\n  Qed.\n  Lemma EpiPlusIdentity {M : ExactCategory} {A B:M} (f:A-->B) (C:M) (AC : BinDirectSum A C) (BC : BinDirectSum B C) :\n    isAdmissibleEpimorphism f -> isAdmissibleEpimorphism (directSumMap AC BC f (identity C)).\n  Proof.\n    intro i. rewrite <- opposite_directSumMap'.\n    exact (MonoPlusIdentity (M:=M^op) f C (oppositeBinDirectSum BC) (oppositeBinDirectSum AC) i).\n  Defined.\n  Lemma IdentityPlusMono {M : ExactCategory} {B C:M} (A:M) (f:B-->C)\n         (AB : BinDirectSum A B) (AC : BinDirectSum A C) :\n    isAdmissibleMonomorphism f -> isAdmissibleMonomorphism (directSumMap AB AC (identity A) f).\n  Proof.\n    intros i. use (IsomMono (directSumMap (reverseBinDirectSum AB) (reverseBinDirectSum AC) f (identity A)) (directSumMap AB AC (identity A) f)).\n    - exists (SwitchIso _ _ _ _). exists (SwitchIso _ _ _ _). apply SwitchMapMapEqn.\n    - apply MonoPlusIdentity. exact i.\n  Defined.\n  Lemma IdentityPlusEpi {M : ExactCategory} {B C:M} (A:M) (f:B-->C)\n        (AB : BinDirectSum A B) (AC : BinDirectSum A C) :\n    isAdmissibleEpimorphism f -> isAdmissibleEpimorphism (directSumMap AB AC (identity A) f).\n  Proof.\n    intros i. use (IsomEpi (directSumMap (reverseBinDirectSum AB) (reverseBinDirectSum AC) f (identity A)) (directSumMap AB AC (identity A) f)).\n    - exists (SwitchIso _ _ _ _). exists (SwitchIso _ _ _ _). apply SwitchMapMapEqn.\n    - apply EpiPlusIdentity. exact i.\n  Defined.\n  Lemma SumOfExactSequences {M:ExactCategory} {A B C A' B' C':M}\n        (AA' : BinDirectSum A A') (BB' : BinDirectSum B B') (CC' : BinDirectSum C C')\n        {f : A --> B} {g : B --> C} {f' : A' --> B'} {g' : B' --> C'} :\n    isExact2 f g -> isExact2 f' g' -> isExact2 (directSumMap AA' BB' f f') (directSumMap BB' CC' g g').\n  Proof.\n    (* see Bühler's 2.9 *)\n    intros i i'. apply ExactSequenceFromMono.\n    { use SumOfCokernels.\n      - exact (EC_ExactToCokernel i).\n      - exact (EC_ExactToCokernel i'). }\n    apply (squash_to_hProp (to_hasBinDirectSums A B')); intros AB'.\n    set (j := directSumMap AB' BB' f (identity B')).\n    set (k := directSumMap AA' AB' (identity A) f').\n    assert (kj : k · j = directSumMap AA' BB' f f').\n    { apply ToBinDirectSumUnique.\n      - refine (! assoc _ _ _ @ _). intermediate_path (k · (π₁ · f)).\n        + apply maponpaths. apply directSumMapEqPr1.\n        + refine (assoc _ _ _ @ _). apply (maponpaths (postcomp_with _)).\n          exact (directSumMapEqPr1 @ id_right _).\n      - refine (! assoc _ _ _ @ _). intermediate_path (k · (π₂ · (identity B'))).\n        + apply maponpaths. apply directSumMapEqPr2.\n        + refine (assoc _ _ _ @ id_right _ @ _). apply directSumMapEqPr2. }\n    induction kj. use (EC_ComposeMono k j).\n    - apply IdentityPlusMono. exact (ExactToAdmMono i').\n    - apply MonoPlusIdentity. exact (ExactToAdmMono i).\n  Qed.\n  Lemma AdmMonoEnlargement {M:ExactCategory} {A B C:M}\n        (BC : BinDirectSum B C) (i:A-->B) (f:A-->C) :\n    isAdmissibleMonomorphism i -> isAdmissibleMonomorphism (ToBinDirectSum BC i f).\n  Proof.\n    (* see Bühler's 2.12 *)\n    intros I.\n    (* write the map as a composite of three maps *)\n    apply (squash_to_hProp (to_hasBinDirectSums A C)); intros AC.\n    assert (e : ToBinDirectSum BC i f  = ι₁ · (1 + π₁·f·ι₂) · (directSumMap AC _ i 1)).\n    { apply ToBinDirectSumsEq.\n      - rewrite BinDirectSumPr1Commutes. rewrite assoc'. unfold directSumMap.\n        unfold BinDirectSumIndAr. rewrite BinDirectSumPr1Commutes.\n        rewrite assoc. rewrite rightDistribute. rewrite 2 leftDistribute.\n        rewrite id_right. rewrite (to_IdIn1 AC). rewrite id_left.\n        refine (! runax (A-->B) _ @ _). apply maponpaths. rewrite assoc.\n        rewrite (assoc' _ _ π₁). rewrite (to_Unel2 AC). unfold to_unel.\n        rewrite zeroRight, zeroLeft. reflexivity.\n      - rewrite BinDirectSumPr2Commutes. rewrite assoc'. unfold directSumMap.\n        unfold BinDirectSumIndAr. rewrite BinDirectSumPr2Commutes.\n        rewrite assoc. rewrite rightDistribute. rewrite 2 leftDistribute.\n        rewrite 2 id_right. rewrite (to_Unel1 AC). unfold to_unel.\n        rewrite lunax. rewrite id_right. rewrite 2 assoc.\n        rewrite (to_IdIn1 AC). rewrite id_left.\n        rewrite assoc'. rewrite (to_IdIn2 AC). rewrite id_right. reflexivity. }\n    induction (!e); clear e.\n    apply EC_ComposeMono.\n    - apply EC_ComposeMono.\n      + apply In1IsAdmMono.\n      + apply IsIsoIsMono. apply elem21_isiso.\n    - now apply MonoPlusIdentity.\n  Qed.\n  Lemma SumOfAdmissibleEpis {M:ExactCategory} {A B A' B':M}\n        (AA' : BinDirectSum A A') (BB' : BinDirectSum B B')\n        (f : A --> B) (f' : A' --> B') :\n    isAdmissibleEpimorphism f -> isAdmissibleEpimorphism f' -> isAdmissibleEpimorphism (directSumMap AA' BB' f f').\n  Proof.\n    intros e e'.\n    apply (squash_to_hProp e); clear e; intros [C [g e]].\n    apply (squash_to_hProp e'); clear e'; intros [C' [g' e']].\n    apply (squash_to_hProp (to_hasBinDirectSums C C')); intros CC'.\n    exact (ExactToAdmEpi (SumOfExactSequences CC' _ _ e e')).\n  Qed.\n  Lemma SumOfAdmissibleMonos {M:ExactCategory} {A B A' B':M}\n        (AA' : BinDirectSum A A') (BB' : BinDirectSum B B')\n        (f : A --> B) (f' : A' --> B') :\n    isAdmissibleMonomorphism f -> isAdmissibleMonomorphism f' -> isAdmissibleMonomorphism (directSumMap AA' BB' f f').\n  Proof.\n    intros e e'.\n    apply (squash_to_hProp e); clear e; intros [C [g e]].\n    apply (squash_to_hProp e'); clear e'; intros [C' [g' e']].\n    apply (squash_to_hProp (to_hasBinDirectSums C C')); intros CC'.\n    exact (ExactToAdmMono (SumOfExactSequences _ _ CC' e e')).\n  Qed.\n  Lemma MapPlusIdentityToCommSq {M:ExactCategory} {A B:M}\n        (f:A-->B) (C:M)\n        (AC : BinDirectSum A C) (BC : BinDirectSum B C) :\n    f · ι₁ = ι₁ · (directSumMap AC BC f (identity C)).\n  Proof.\n    apply ToBinDirectSumsEq.\n    - rewrite assoc'. rewrite (to_IdIn1 BC). rewrite id_right. unfold directSumMap.\n      unfold BinDirectSumIndAr. rewrite assoc'. rewrite BinDirectSumPr1Commutes.\n      rewrite assoc. rewrite (to_IdIn1 AC). rewrite id_left. reflexivity.\n    - rewrite assoc'. rewrite (to_Unel1 BC). unfold to_unel. rewrite zeroRight.\n      unfold directSumMap, BinDirectSumIndAr. rewrite assoc'.\n      rewrite BinDirectSumPr2Commutes. rewrite id_right. apply pathsinv0.\n      use (to_Unel1 AC).\n  Qed.\n  Lemma KernelPlusIdentity {M:ExactCategory} {A B C:M}\n        (f:A-->B) (g:B-->C) (D:M)\n        (BD : BinDirectSum B D) (CD : BinDirectSum C D) :\n    isKernel' (f · ι₁) (directSumMap BD CD g (identity D)) -> isKernel' f g.\n  Proof.\n    intros K. apply makeMonicKernel.\n    - exact (isMonic_postcomp _ _ _ (KernelIsMonic _ _ K)).\n    - use (to_In1_isMonic _ CD). rewrite zeroLeft. rewrite assoc'.\n      assert (Q := pr1 K); simpl in Q. rewrite assoc' in Q.\n      rewrite directSumMapEqIn1 in Q. exact Q.\n    - intros T h eqn.\n      assert (E : h · ι₁ · directSumMap BD CD g (identity D) = 0).\n      { rewrite assoc'. rewrite directSumMapEqIn1. rewrite assoc.\n        refine (maponpaths (λ r, r·ι₁) eqn @ _). apply zeroLeft. }\n      assert (Q := iscontrpr1 (pr2 K T (h·ι₁) E)); simpl in Q.\n      induction Q as [p e].\n      exists p.\n      rewrite assoc in e.\n      apply (to_In1_isMonic _ _ _ _ _ e).\n  Qed.\n  Lemma CokernelPlusIdentity {M:ExactCategory} {A B C:M} (f:A-->B) (g:B-->C) (D:M)\n        (BD : BinDirectSum B D) (CD : BinDirectSum C D):\n    isCokernel' f g ->\n    isCokernel' (f · ι₁) (directSumMap BD CD g (identity D)).\n  Proof.\n    intros ic.\n    split.\n    { rewrite assoc'. rewrite directSumMapEqIn1. rewrite assoc. rewrite (pr1 ic). apply zeroLeft. }\n    intros T h u.\n    apply iscontraprop1.\n    { apply invproofirrelevance. intros [r r'] [s s']. apply subtypePath_prop; cbn.\n      assert (Q := r' @ ! s'); clear r' s' u h. apply FromBinDirectSumsEq.\n      - assert (L := maponpaths (λ w, ι₁ · w) Q); clear Q. simpl in L. rewrite 2 assoc in L.\n        rewrite directSumMapEqIn1 in L.\n        rewrite 2 assoc' in L. exact (CokernelIsEpi _ g ic _ _ _ L).\n      - assert (L := maponpaths (λ w, ι₂ · w) Q); clear Q. simpl in L. rewrite 2 assoc in L.\n        rewrite directSumMapEqIn2 in L.\n        rewrite 2 assoc' in L. rewrite 2 id_left in L. exact L. }\n    assert (Q := iscontrpr1 (pr2 ic _ _ (assoc _ _ _ @ u))).\n    induction Q as [q Q].\n    exists (π₁ · q + π₂ · ι₂ · h).\n    rewrite rightDistribute.\n    rewrite assoc. rewrite assoc. rewrite assoc.\n    unfold directSumMap. unfold BinDirectSumIndAr. rewrite BinDirectSumPr1Commutes,BinDirectSumPr2Commutes.\n    rewrite id_right.\n    rewrite assoc'. rewrite Q. rewrite assoc.\n    rewrite <- leftDistribute.\n    refine (_ @ id_left _).\n    apply (maponpaths (λ w, w·h)).\n    use to_BinOpId''.\n  Qed.\n  Lemma MapPlusIdentityToPullback {M:ExactCategory} {A B:M} (f:A-->B) (C:M)\n        (AC : BinDirectSum A C) (BC : BinDirectSum B C) :\n    isPullback (MapPlusIdentityToCommSq f C AC BC).\n  Proof.\n    intros T g h e. apply iscontraprop1.\n    - apply invproofirrelevance. intros [p [P P']] [q [Q Q']].\n      apply subtypePath.\n      { intros r. apply isapropdirprod; apply to_has_homsets. }\n      cbn. clear P Q.\n      refine (! id_right _ @ _ @ id_right _).\n      rewrite <- (to_IdIn1 AC). rewrite 2 assoc. induction (!P'), (!Q'). reflexivity.\n    - exists (h · π₁).\n      split.\n      + refine (_ @ id_right _). rewrite <- (to_IdIn1 BC).\n        rewrite (assoc g). rewrite e. rewrite (assoc' h _ π₁).\n        unfold directSumMap. unfold BinDirectSumIndAr. rewrite BinDirectSumPr1Commutes.\n        rewrite assoc. reflexivity.\n      + refine (_ @ id_right _). rewrite <- (to_BinOpId' AC).\n        rewrite rightDistribute. rewrite assoc. refine (! runax (Hom_add _ _ _) _ @ _).\n        apply maponpaths. rewrite assoc. apply pathsinv0.\n        assert (K : h · π₂ = 0).\n        { refine ( _ @ maponpaths (λ w, w · π₂) (!e) @ _ ).\n          - rewrite assoc'.\n            unfold directSumMap. unfold BinDirectSumIndAr. rewrite BinDirectSumPr2Commutes.\n            rewrite id_right. reflexivity.\n          - rewrite assoc'. rewrite (to_Unel1 BC). unfold to_unel.\n            apply zeroRight. }\n        rewrite K. apply zeroLeft.\n  Qed.\n  (** The \"obscure\" axiom c of Quillen. *)\n  Lemma AdmMonoFromComposite {M:ExactCategory} {A B C:M} (i:A-->B) (j:B-->C) :\n    hasCokernel i -> isAdmissibleMonomorphism (i·j) -> isAdmissibleMonomorphism i.\n  Proof.\n    (* see Bühler's 2.16 *)\n    intros hc im.\n    apply (squash_to_hProp (to_hasBinDirectSums C B)); intros CB.\n    apply (squash_to_hProp (to_hasBinDirectSums B C)); intros BC.\n    set (q := ToBinDirectSum CB (i · j) i).\n    assert (s := AdmMonoEnlargement _ (i·j) i im : isAdmissibleMonomorphism q); clear im.\n    assert (e : q · elem12 _ (grinv j) = ToBinDirectSum CB 0 i).\n    { apply ToBinDirectSumsEq.\n      - rewrite BinDirectSumPr1Commutes. unfold elem12. rewrite rightDistribute, leftDistribute.\n        rewrite id_right. rewrite (assoc' π₂). rewrite (assoc q). rewrite (assoc (q · π₂)).\n        rewrite (assoc' _ _ π₁). rewrite (to_IdIn1 CB). rewrite id_right.\n        rewrite rightMinus. unfold q. rewrite BinDirectSumPr1Commutes, BinDirectSumPr2Commutes.\n        apply (grrinvax (Hom_add _ _ _)).\n      - rewrite BinDirectSumPr2Commutes. unfold elem12. rewrite rightDistribute, leftDistribute.\n        rewrite id_right. rewrite assoc. rewrite (assoc' _ _ π₂).\n        rewrite (to_Unel1 CB); unfold to_unel. rewrite zeroRight. rewrite runax.\n        unfold q. rewrite BinDirectSumPr2Commutes. reflexivity. }\n    assert (e' : q · elem12 _ (grinv j) · SwitchMap _ _ _ _ = ToBinDirectSum BC i 0).\n    { rewrite e. apply SwitchMapEqnTo. }\n    assert (l : isAdmissibleMonomorphism (ToBinDirectSum BC i 0)).\n    { induction e'. apply EC_ComposeMono.\n      - apply EC_ComposeMono.\n        + exact s.\n        + apply IsIsoIsMono. apply elem12_isiso.\n      - apply IsIsoIsMono. apply (SwitchIso C B). }\n    clear e' e s q.\n    apply (squash_to_hProp hc); clear hc; intros [D [k ic]].\n    apply (squash_to_hProp (to_hasBinDirectSums D C)); intros DC.\n    assert (PB := is_symmetric_isPullback _ (MapPlusIdentityToPullback k C BC DC)).\n    assert (co := CokernelPlusIdentity i k C BC DC ic).\n    assert (es := ExactSequenceFromMono _ _ co); clear co.\n    assert (t : i · to_In1 BC = ToBinDirectSum BC i 0).\n    { rewrite <- ToBinDirectSumFormulaUnique. unfold ToBinDirectSumFormula.\n      rewrite rewrite_op. rewrite zeroLeft, runax. reflexivity. }\n    assert (l' : isAdmissibleMonomorphism (i · to_In1 BC)).\n    { induction (!t). exact l. }\n    clear l t.\n    assert (ee := es l'); clear es l'.\n    use (ExactToAdmMono (p:=k)). use (ExactSequenceFromEpi i k).\n    - use KernelPlusIdentity. 4: exact (EC_ExactToKernel ee).\n    - use (IsPullbackEpiIsEpi (_,,PB)). exact (ExactToAdmEpi ee).\n  Qed.\n  Lemma AdmEpiFromComposite {M:ExactCategory} {A B C:M} (i:A-->B) (j:B-->C) :\n    hasKernel j -> isAdmissibleEpimorphism (i·j) -> isAdmissibleEpimorphism j.\n  Proof.\n    exact (AdmMonoFromComposite (M:=M^op) j i).\n  Qed.\n  Section Tmp.\n    Lemma CokernelSequence {M:ExactCategory} {A B C P R:M}\n          (i : A --> B) (j : B --> C) (p : B --> P) (q : C --> R) :\n      isExact2 i p -> isExact2 j q ->\n      ∃ Q (s : C --> Q) (k : P --> Q) (r : Q --> R),\n        isExact2 (i·j) s ∧ isExact2 k r ∧ isPushout' (M:=M) j p s k ∧ s · r = q.\n    Proof.\n      intros ip jq.\n      assert (co := EC_ExactToCokernel ip : isCokernel' i p).\n      assert (b := EC_ExactToCokernel jq : isCokernel' j q).\n      assert (I := ExactToAdmMono ip).\n      assert (J := ExactToAdmMono jq).\n      assert (IJ := EC_ComposeMono _ _ I J).\n      induction b as [a co'].\n      assert (ijq : i · (j · q) = 0).\n      { rewrite a. apply zeroRight. }\n      assert (po := EC_PushoutMono j p (ExactToAdmMono jq)).\n      use (hinhfun _ po); clear po; intros [[[Q [s k]] [e1 po]] K].\n      change (isPushout j p s k e1) in po;\n        change (hProptoType (isAdmissibleMonomorphism k)) in K;\n        change (hProptoType (j · s = p · k)) in e1.\n      assert (L := PushoutCokernel _ _ _ _ _ co (_,,po)).\n      exists Q. exists s. exists k.\n      assert (e2 : j · q = p · 0).\n      { rewrite a. now rewrite zeroRight. }\n      assert (PO := iscontrpr1 (po R q 0 e2)).\n      induction PO as [u [e3 e4]].\n      exists u.\n      assert (ijs := ExactSequenceFromMono (i·j) s L IJ).\n      exists ijs.\n      split.\n      { use (ExactSequenceFromMono k u _ K). exists e4. intros T h e0.\n        assert (e5 : j · (s · h) = 0).\n        { rewrite assoc. rewrite e1. rewrite assoc'. rewrite e0. now rewrite zeroRight. }\n        assert (W := co' T (s·h) e5); cbn in W.\n        use (iscontrweqf _ W). apply weqfibtototal; intros l. apply weqiff.\n        rewrite <- e3. rewrite assoc'.\n        split.\n        { intros e. now apply (CokernelIsEpi (i·j) s (EC_ExactToCokernel ijs)). }\n        { intros e. now apply maponpaths. }\n        + apply to_has_homsets.\n        + apply to_has_homsets. }\n      split.\n      - exists e1. exact po.\n      - exact e3.\n    Defined.\n  End Tmp.\n\n\n\n  Lemma KernelSequence {M:ExactCategory} {A B C P R:M}\n        (i : B --> A) (j : C --> B) (p : P --> B) (q : R --> C) :\n    isExact2 p i -> isExact2 q j ->\n    ∃ Q (s : Q --> C) (k : Q --> P) (r : R --> Q),\n      isExact2 s (j·i) ∧ isExact2 r k ∧ isPullback' (M:=M) j p s k ∧ r · s = q.\n  Proof.\n    exact (CokernelSequence (M := oppositeExactCategory M) i j p q).\n  Defined.\n\n\n  Lemma ExactIso3 {M:ExactCategory} {A B C C':M} (i:A-->B) (p:B-->C) (t:z_iso C C') :\n    isExact2 i p -> isExact2 i (p·t).\n  Proof.\n    intros ex. use (EC_IsomorphicToExact _ ex).\n    exists (identity_z_iso A). exists (identity_z_iso B). exists t. repeat split;cbn.\n    - now rewrite id_left, id_right.\n    - now rewrite id_left, id_right.\n    - apply id_left.\n    - apply pathsinv0, id_left.\n  Qed.\n  Lemma ExactIso2 {M:ExactCategory} {A B C B':M} (i:A-->B) (p:B-->C) (t:z_iso B B') :\n    isExact2 i p -> isExact2 (i · t) (z_iso_inv t · p).\n  Proof.\n    intros ex. use (EC_IsomorphicToExact _ ex).\n    exists (identity_z_iso A). exists t. exists (identity_z_iso C). repeat split;cbn.\n    - exact (id_left _).\n    - exact (! id_left _).\n    - rewrite assoc. rewrite z_iso_inv_after_z_iso. rewrite id_left, id_right. reflexivity.\n    - rewrite assoc. rewrite z_iso_inv_after_z_iso. rewrite id_left, id_right. reflexivity.\n  Qed.\n  Lemma ExactIso1 {M:ExactCategory} {A' A B C:M} (t:z_iso A' A) (i:A-->B) (p:B-->C) :\n    isExact2 i p -> isExact2 (t·i) p.\n  Proof.\n    exact (ExactIso3 (M:=oppositeExactCategory M) p i (opp_z_iso t)).\n  Defined.\nEnd ExactCategoryFacts.\n\nSection EquivalenceOfTwoDefinitions.\n  Theorem EquivalenceOfTwoDefinitions (D:ExactCategoryData) :\n    ExactCategoryProperties D ⇔ ExactCategoryProperties_Quillen D.\n  Proof.\n    split.\n    { intros prop.\n      set (M := (D,,prop) : ExactCategory).\n      split.\n      { exact (@EC_IsomorphicToExact M). }\n      split.\n      { exact (@DirectSumToExact M). }\n      split.\n      { exact (@EC_ExactToKernelCokernel M). }\n      split.\n      { split.\n        { exact (@EC_ComposeMono M). }\n        { exact (@EC_ComposeEpi M). } }\n      split.\n      { split.\n        { exact (@EC_PullbackEpi M). }\n        { exact (@EC_PushoutMono M). } }\n      { split.\n        { exact (@AdmMonoFromComposite M). }\n        { exact (@AdmEpiFromComposite M). } } }\n    { intros [P1 [P2 [P3 [[P4 P4'] [[P5 P5'] [P6 P7]]]]]].\n      split.\n      { split.\n        { exact P1. }\n        { intros P Q i. exact (P1 P Q (InverseMorphismPairIsomorphism i)). } }\n      { split.\n        { split.\n          { intros A. apply (squash_to_hProp (to_hasZero D)); intros Z. apply hinhpr.\n            exists Z. set (Q := TrivialDirectSum Z A). exists (to_Pr2 Q).\n            exact (P2 A Z Q). }\n          { intros A. apply (squash_to_hProp (to_hasZero D)); intros Z. apply hinhpr.\n            exists Z. set (Q := TrivialDirectSum' Z A). exists (to_In1 Q).\n            exact (P2 Z A Q). } }\n        split.\n        { exact P3. }\n        split.\n        { split.\n          { exact P4. }\n          { exact P4'. } }\n        split.\n        { exact P5. }\n        { exact P5'. } } }\n  Defined.\nEnd EquivalenceOfTwoDefinitions.\n\nSection SplitSequences.\n  Definition isSplit2 {M:PreAdditive} {A B C:M} (i:A-->B) (q:B-->C) : hProp :=\n    ∃ (p:A<--B) (j:B<--C), isBinDirectSum i j p q.\n  Lemma commax_hom {M:PreAdditive} {A B:M} (f g:A-->B) : f+g = g+f.\n  Proof.\n    exact (commax (A-->B) f g).\n  Qed.\n  Section Foo.\n    Goal ∏ {M:PreAdditive} {A B C:M} (i:A-->B) (p:B-->C),\n      isSplit2 (M:=M) i p = isSplit2 (M := oppositePreAdditive M) p i.\n    Proof.\n      Fail reflexivity.\n      intros M A B C k r.\n      unfold isSplit2, isBinDirectSum; cbn; rewrite rewrite_op.\n      (* do we need this? *)\n    Abort.\n  End Foo.\n  Lemma opposite_isSplit2 {M:PreAdditive} {A B C:M} (i:A-->B) (p:B-->C) :\n    isSplit2 i p -> isSplit2 (M := oppositePreAdditive M) p i.\n  Proof.\n    intros s.\n    Fail exact s.               (* sigh *)\n    use (hinhfun _ s); intros [q [j jq]]. exists j. exists q.\n    exists (to_IdIn2 jq). exists (to_IdIn1 jq).\n    exists (to_Unel1 jq). exists (to_Unel2 jq).\n    rewrite commax_hom. exact (to_BinOpId' jq).\n  Qed.\n  Definition isSplit {M:PreAdditive} (P : MorphismPair M) : hProp := isSplit2 (Mor1 P) (Mor2 P).\n  Lemma opposite_isSplit {M:PreAdditive} (P : MorphismPair M) :\n    isSplit P -> isSplit (M:=oppositePreAdditive M) (MorphismPair_opp P).\n  Proof.\n    exact (opposite_isSplit2 _ _).\n  Qed.\n  Definition isSplitMonomorphism {M:PreAdditive} {A B:M} (i : A --> B) : hProp :=\n    ∃ C (p : B --> C), isSplit2 i p.\n  Definition isSplitEpimorphism {M:PreAdditive} {B C:M} (p : B --> C) : hProp :=\n    ∃ A (i : A --> B), isSplit2 i p.\n  Lemma opposite_isSplitMonomorphism {M:PreAdditive} {A B:M} (i : A --> B) :\n    isSplitMonomorphism i -> isSplitEpimorphism (M:=oppositePreAdditive M) i.\n  Proof.\n    intros s. use (hinhfun _ s); clear s. intros [C [p s]].\n    exists C. exists p. exact (opposite_isSplit2 _ _ s).\n  Qed.\n  Lemma opposite_isSplitEpimorphism {M:PreAdditive} {A B:M} (p : A --> B) :\n    isSplitEpimorphism p -> isSplitMonomorphism (M:=oppositePreAdditive M) p.\n  Proof.\n    intros s. use (hinhfun _ s); clear s. intros [C [i s]].\n    exists C. exists i. exact (opposite_isSplit2 _ _ s).\n  Qed.\n  Lemma DirectSumToSplit {M:PreAdditive} {A B:M} (AB : BinDirectSum A B) : isSplit2 (to_In1 AB) (to_Pr2 AB).\n  Proof.\n    exact (hinhpr (π₁,, ι₂,, BinDirectSum_isBinDirectSum M AB)).\n  Qed.\n  Lemma DirectSumToSplit' {M:PreAdditive} {A B:M} (AB : BinDirectSum A B) : isSplit2 (to_In2 AB) (to_Pr1 AB).\n  Proof.\n    exact (hinhpr(π₂,,ι₁,,BinDirectSum_isBinDirectSum M (reverseBinDirectSum AB))).\n  Qed.\n  Lemma IsomorphicToSplit {M:PreAdditive} (P Q : MorphismPair M) :\n    MorphismPairIsomorphism P Q ⇒ isSplit P ⇒ isSplit Q.\n  Proof.\n    intros [f' [f [f'' [[e _] [e' _]]]]] ex.\n    apply (squash_to_hProp ex); clear ex; intros [q [j su]]; apply hinhpr.\n    exists (z_iso_inv f · q · f').\n    exists (z_iso_inv f'' · j · f).\n    split.\n    { intermediate_path (z_iso_inv f' · Mor1 P · q · f').\n      { rewrite 2 assoc. apply (maponpaths (λ k, k·f')).\n        apply (maponpaths (λ k, k·q)). apply pathsinv0.\n        apply z_iso_inv_on_right. rewrite assoc. apply z_iso_inv_on_left. exact e. }\n      { rewrite 2 assoc'. rewrite (assoc _ q _).\n        intermediate_path (z_iso_inv f' · (identity _ · f')).\n        { apply maponpaths. apply (maponpaths (λ k, k·f')). exact (to_IdIn1 su). }\n        { rewrite id_left. apply z_iso_after_z_iso_inv. } } }\n    split.\n    { rewrite assoc'. rewrite e'.  rewrite assoc. rewrite (assoc' _ j _).\n      apply wrap_inverse. apply (to_IdIn2 su). }\n    split.\n    { assert (r := to_Unel1 su); unfold to_unel in r.\n      assert (r' := maponpaths (λ t, t · f'') r); cbn in r'; clear r.\n      rewrite assoc' in r'. rewrite <- e' in r'. rewrite assoc in r'.\n      rewrite <- e in r'. assert (r'' := maponpaths (λ t, z_iso_inv f' · t) r'); clear r'; cbn in r''.\n      rewrite 2 assoc in r''. rewrite z_iso_after_z_iso_inv in r''.\n      rewrite assoc' in r''. rewrite id_left in r''. rewrite zeroLeft,zeroRight in r''.\n      exact r''. }\n    split.\n    { rewrite 2 assoc. rewrite (assoc' _ f _). rewrite z_iso_inv_after_z_iso.\n      rewrite id_right. rewrite (assoc' _ j _). rewrite (to_Unel2 su).\n      unfold to_unel. rewrite zeroRight, zeroLeft. reflexivity. }\n    { apply (cancel_z_iso' f). rewrite id_right. rewrite rightDistribute.\n      rewrite 3 (assoc f). rewrite z_iso_inv_after_z_iso, id_left.\n      rewrite assoc'. rewrite e. rewrite assoc.\n      rewrite (assoc f). rewrite e'. rewrite (assoc' _ f'').\n      rewrite 2 (assoc f''). rewrite z_iso_inv_after_z_iso, id_left. rewrite assoc.\n      rewrite <- leftDistribute. rewrite (to_BinOpId' su). rewrite id_left. reflexivity. }\n  Qed.\n  Lemma DirectSumToKernel {M:PreAdditive} {A B:M} (AB : BinDirectSum A B) : isKernel' (to_In1 AB) (to_Pr2 AB).\n  Proof.\n    apply makeMonicKernel.\n    - apply to_In1_isMonic.\n    - exact (to_Unel1 AB).\n    - intros T h e. exists (h · π₁). refine (_ @ id_right _).\n      rewrite <- (to_BinOpId AB). rewrite rewrite_op. rewrite rightDistribute.\n      rewrite assoc'. rewrite (assoc _ π₂ _). rewrite e. rewrite zeroLeft. rewrite runax. reflexivity.\n  Defined.\n  Lemma DirectSumToCokernel {M:PreAdditive} {A B:M} (AB : BinDirectSum A B) : isCokernel' (to_In1 AB) (to_Pr2 AB).\n  Proof.\n    apply makeEpiCokernel.\n    - apply to_Pr2_isEpi.\n    - exact (to_Unel1 AB).\n    - intros T h e. exists (ι₂ · h). refine (_ @ id_left _).\n      rewrite <- (to_BinOpId AB). rewrite rewrite_op. rewrite leftDistribute.\n      rewrite assoc. rewrite (assoc' _ ι₁ _). rewrite e. rewrite zeroRight. rewrite lunax. reflexivity.\n  Defined.\n  Lemma isSplitToKernelCokernelPair {M:PreAdditive} {A B C:M} (i:A-->B) (p:B-->C) :\n    isSplit2 i p -> isKernelCokernelPair i p.\n  Proof.\n    intros sp.\n    apply (squash_to_hProp sp); clear sp; intros [j [q issum]].\n    set (S := make_BinDirectSum _ _ _ _ _ _ _ _ issum).\n    exact (DirectSumToKernel S,,DirectSumToCokernel S).\n  Qed.\n  Lemma ComposeSplitMono {M:AdditiveCategory} {A B C : M} (i : A --> B) (j : B --> C) :\n    isSplitMonomorphism i ⇒ isSplitMonomorphism j ⇒ isSplitMonomorphism (i · j).\n  Proof.\n    intros s t.\n    apply (squash_to_hProp s); clear s; intros [P [p ip]];cbn in P.\n    apply (squash_to_hProp ip); clear ip; intros [p' [i' ip]].\n    change (hProptoType (isBinDirectSum i i' p' p)) in ip.\n    apply (squash_to_hProp t); clear t; intros [Q [q jq]];cbn in Q.\n    apply (squash_to_hProp jq); clear jq; intros [q' [j' jq]].\n    change (hProptoType (isBinDirectSum j j' q' q)) in jq.\n    apply (squash_to_hProp (to_hasBinDirectSums P Q)); intros PQ.\n    apply hinhpr;unfold ExactCategoryDataToAdditiveCategory,pr1.\n    exists PQ.\n    exists (q' · p · ι₁ + q · ι₂).\n    apply hinhpr.\n    exists (q' · p').\n    exists (π₁ · i' · j + π₂ · j').\n    repeat split; rewrite ? rewrite_op.\n    { rewrite assoc'. rewrite (assoc j). rewrite (to_IdIn1 jq). rewrite id_left.\n      rewrite (to_IdIn1 ip). reflexivity. }\n    { rewrite rightDistribute, 2 leftDistribute.\n      rewrite (assoc' q'). rewrite (assoc' _ j).\n      rewrite (assoc j). rewrite (to_IdIn1 jq). rewrite id_left.\n      rewrite assoc'. rewrite (assoc i'). rewrite (to_IdIn2 ip). rewrite id_left.\n      rewrite (assoc _ q'). rewrite (assoc' _ j'). rewrite (to_Unel2 jq); unfold to_unel.\n      rewrite zeroRight, zeroLeft, runax.\n      rewrite (assoc' _ j). rewrite (assoc j). rewrite (to_Unel1 jq). unfold to_unel.\n      rewrite zeroLeft, zeroRight, lunax. rewrite assoc'.\n      rewrite (assoc j'). rewrite (to_IdIn2 jq). rewrite id_left. apply (to_BinOpId PQ). }\n    { rewrite rightDistribute. rewrite assoc'. rewrite (assoc' q').\n      rewrite (assoc j). rewrite (to_IdIn1 jq). rewrite id_left.\n      rewrite assoc. rewrite (to_Unel1 ip); unfold to_unel.\n      rewrite zeroLeft. rewrite lunax. rewrite assoc'.\n      rewrite (assoc j). rewrite (to_Unel1 jq); unfold to_unel.\n      rewrite zeroLeft, zeroRight. reflexivity. }\n    { rewrite leftDistribute. rewrite assoc'. rewrite (assoc j).\n      rewrite (to_IdIn1 jq). rewrite id_left. rewrite (assoc' _ i').\n      rewrite (to_Unel2 ip); unfold to_unel.\n      rewrite zeroRight. rewrite lunax. rewrite assoc'.\n      rewrite (assoc j'). rewrite (to_Unel2 jq);unfold to_unel.\n      rewrite zeroLeft, zeroRight. reflexivity. }\n    { rewrite rightDistribute, 2 leftDistribute. rewrite assoc.\n      rewrite (assoc' _ i'). rewrite (assoc' _ ι₁). rewrite (assoc ι₁).\n      rewrite (to_IdIn1 PQ). rewrite id_left. rewrite assoc.\n      rewrite (assoc' q). rewrite (assoc _ _ (i' · j)).\n      rewrite (to_Unel2 PQ); unfold to_unel. rewrite zeroLeft, zeroRight, runax.\n      rewrite <- assocax. rewrite <- (leftDistribute _ _ j).\n      rewrite 2 (assoc' q'). rewrite <- (rightDistribute q').\n      rewrite (to_BinOpId' ip). rewrite id_right.\n      rewrite (assoc' _ ι₁). rewrite (assoc ι₁). rewrite (to_Unel1 PQ); unfold to_unel.\n      rewrite zeroLeft, zeroRight, lunax. rewrite (assoc' q).\n      rewrite (assoc ι₂). rewrite (to_IdIn2 PQ).\n      rewrite id_left. exact (to_BinOpId' jq). }\n  Qed.\n  Lemma ComposeSplitEpi {M:AdditiveCategory} {A B C : M} (p : A --> B) (q : B --> C) :\n    isSplitEpimorphism p ⇒ isSplitEpimorphism q ⇒ isSplitEpimorphism (p · q).\n  Proof.\n    intros r s.\n    exact (opposite_isSplitMonomorphism _\n             (ComposeSplitMono (M:=oppositeAdditiveCategory M)\n                               _ _ (opposite_isSplitEpimorphism _ s) (opposite_isSplitEpimorphism _ r))).\n  Qed.\n  Lemma PullbackSplitEpi {M:AdditiveCategory} {A A'' C : M} (q : A --> A'') (g : C --> A'') :\n    isSplitEpimorphism q -> ∃ PB : Pullback q g, isSplitEpimorphism (PullbackPr2 PB).\n  Proof.\n    intros s.\n    apply (squash_to_hProp s); clear s; intros [A' [i e]].\n    apply (squash_to_hProp e); clear e; intros [p [j e]].\n    apply (squash_to_hProp (to_hasBinDirectSums A' C)); intros A'C.\n    apply hinhpr.\n    use tpair.\n    - use tpair.\n      + exists A'C. exists (π₁ · i + π₂ · g · j). exact π₂.\n      + simpl. rewrite rewrite_op.\n        use tpair.\n        * rewrite leftDistribute. rewrite (assoc' _ j q). rewrite (to_IdIn2 e).\n          rewrite id_right. rewrite (assoc' _ i q). rewrite (to_Unel1 e); unfold to_unel.\n          rewrite zeroRight, lunax. reflexivity.\n        * intros T r s eqn. apply iscontraprop1.\n          { apply invproofirrelevance. intros h k.\n            apply subtypePath.\n            { intros l. apply isapropdirprod;apply to_has_homsets. }\n            induction h as [h [H H']], k as [k [K K']]. simpl.\n            rewrite <- (id_right h), <- (id_right k). rewrite <- (to_BinOpId' A'C).\n            rewrite 2 rightDistribute. rewrite 4 assoc. rewrite H', K'.\n            apply (maponpaths (λ z, z + s · ι₂)). rewrite rightDistribute in H, K.\n            rewrite 3 assoc in H, K. rewrite H' in H. rewrite K' in K.\n            apply (maponpaths (λ z, z · ι₁)).\n            apply (to_In1_isMonic _ (make_BinDirectSum _ _ _ _ _ _ _ _ e)).\n            change (h · π₁ · i = k · π₁ · i). apply (grrcan (T-->A) (s · g · j)).\n            exact (H @ !K). }\n          exists (r · p · ι₁ + s · ι₂).\n          split.\n          { rewrite leftDistribute, 2 rightDistribute.\n            rewrite assoc'. rewrite (assoc _ _ i). rewrite (to_IdIn1 A'C). rewrite id_left.\n            rewrite (assoc' (r · p)). rewrite 2 (assoc ι₁).\n            rewrite (to_Unel1 A'C); unfold to_unel. rewrite 2 zeroLeft, zeroRight, runax.\n            rewrite (assoc' s). rewrite (assoc ι₂). rewrite (to_Unel2 A'C); unfold to_unel.\n            rewrite zeroLeft, zeroRight, lunax. rewrite 2 assoc. rewrite (assoc' s).\n            rewrite (to_IdIn2 A'C). rewrite id_right. rewrite (!eqn).\n            rewrite 2 assoc'. rewrite <- (rightDistribute r). rewrite (to_BinOpId' e).\n            apply id_right. }\n          { rewrite leftDistribute. rewrite (assoc' (r · p)). rewrite (to_Unel1 A'C); unfold to_unel.\n            rewrite zeroRight, lunax. rewrite assoc'. rewrite (to_IdIn2 A'C).\n            apply id_right. }\n    - cbn. exact (hinhpr(A',,ι₁,, hinhpr (π₁,,ι₂,,BinDirectSum_isBinDirectSum _ A'C))).\n  Qed.\n  Lemma PushoutSplitMono {M:AdditiveCategory} {A A' C : M} (i : A' --> A) (g : A' --> C) :\n    isSplitMonomorphism i ⇒ ∃ PO : Pushout i g, isSplitMonomorphism (PushoutIn2 PO).\n  Proof.\n    intros s.\n    assert (Q := @PullbackSplitEpi (oppositeAdditiveCategory M) _ _ _ i g (opposite_isSplitMonomorphism _ s)).\n    use (hinhfun _ Q); clear Q; intros [A''C epi].\n    exists (A''C).\n    exact (opposite_isSplitEpimorphism _ epi).\n  Qed.\nEnd SplitSequences.\n\nSection AdditiveToExact.\n  Lemma AdditiveExactnessProperties (M:AdditiveCategory) : ExactCategoryProperties (M,,isSplit).\n  Proof.\n    split;unfold ExactCategoryDataToAdditiveCategory,pr1.\n    - split.\n      { intros P Q. apply IsomorphicToSplit. }\n      { intros P Q i e. use IsomorphicToSplit.\n        2 : { exact (InverseMorphismPairIsomorphism i). }\n        exact e. }\n    - split.\n      { split.\n        { intros A. apply (squash_to_hProp (to_hasZero M)); intros Z.\n          apply hinhpr. exists Z. set (Q := TrivialDirectSum Z A).\n          exact (to_Pr2 Q,, DirectSumToSplit Q). }\n        { intros A. apply (squash_to_hProp (to_hasZero M)); intros Z.\n          apply hinhpr. exists Z. set (Q := TrivialDirectSum' Z A).\n          exact (to_In1 Q,, DirectSumToSplit Q). } }\n      split.\n      { intros P. exact (isSplitToKernelCokernelPair (Mor1 P) (Mor2 P)). }\n      split.\n      { split.\n        { exact (@ComposeSplitMono M). }\n        { exact (@ComposeSplitEpi M). } }\n      { split.\n        { exact (@PullbackSplitEpi M). }\n        { exact (@PushoutSplitMono M). } }\n  Defined.\n  Definition AdditiveToExact : AdditiveCategory -> ExactCategory\n    := λ M, make_ExactCategory (M,,isSplit) (AdditiveExactnessProperties M).\n  Lemma additive_exact_opposite {M:AdditiveCategory} :\n    AdditiveToExact (oppositeAdditiveCategory M) = oppositeExactCategory (AdditiveToExact M).\n  Proof.\n    intros. apply subtypePath_prop. apply pair_path_in2.\n    apply funextsec; intros P. apply hPropUnivalence.\n    * exact (opposite_isSplit P).\n    * exact (opposite_isSplit (MorphismPair_opp P)).\n  Qed.\nEnd AdditiveToExact.\n\nSection InducedExactCategory.\n  Definition exts_lift (M:ExactCategory) {X:Type} (j : X -> ob M) :=\n    zero_lifts M j ∧ ∀ a B c (i : j a --> B) (p : B --> j c), isExact2 i p ⇒ ∃ b, z_iso (j b) B.\n  Definition exts_lift_sums (M:ExactCategory) {X:Type} (j : X -> ob M) :\n    exts_lift M j -> sums_lift M j.\n  Proof.\n    intros el. exists (pr1 el). exact (λ a c S, pr2 el a S c ι₁ π₂ (DirectSumToExact S)).\n  Defined.\n  Definition induced_ExactCategoryData {M:ExactCategory} {X:Type}\n             (j : X -> ob M) : exts_lift M j -> ExactCategoryData.\n  Proof.\n    intros el. exists (induced_Additive M j (exts_lift_sums M j el)).\n    exact (λ P, isExact2 (Mor1 P) (Mor2 P)).\n  Defined.\n  Definition opp_exts_lift {M:ExactCategory} {X:Type} (j : X -> ob M) :\n    exts_lift M j -> exts_lift (oppositeExactCategory M) j.\n  Proof.\n    intros [hz ce]. exists (opp_zero_lifts j hz).\n    intros a B c i p ex. generalize (ce c B a p i ex). apply hinhfun.\n    intros [b t]. exists b. exact (z_iso_inv (opp_z_iso t)).\n  Defined.\n  Lemma opp_sums_exts_lift (M:ExactCategory) {X:Type} (j : X -> ob M) (ce : exts_lift M j ):\n    opp_sums_lift M j (exts_lift_sums M j ce) =\n    exts_lift_sums M^op j (opp_exts_lift j ce).\n  Proof.\n    apply pair_path_in2.\n    apply funextsec; intro a.\n    apply funextsec; intro b.\n    apply funextsec; intro S.\n    apply isapropishinh.\n  Qed.\n\n\n  Goal ∏ {M:ExactCategory} {X:Type} (j : X -> ob M) (ce : exts_lift M j),\n    oppositeExactCategoryData (induced_ExactCategoryData j ce) =\n    induced_ExactCategoryData (M:=oppositeExactCategory M) j (opp_exts_lift j ce).\n  Proof.\n    intros.\n    simple refine (total2_paths2_f _ _).\n    - refine (induced_opposite_Additive j (exts_lift_sums M j ce) @ _).\n      apply maponpaths. apply opp_sums_exts_lift.\n    - apply funextsec; intros P. apply hPropUnivalence.\n      (* Getting this to work would be good, because then some proofs below\n         could be shortened by using duality. *)\n      + intros ex. admit.\n      + intros ex. admit.\n  Abort.\n\n  Definition induced_ExactCategoryProperties {M:ExactCategory} {X:Type}\n             (j : X -> ob M) (ce : exts_lift M j) :\n    ExactCategoryProperties (induced_ExactCategoryData j ce).\n  Proof.\n    set (N := induced_ExactCategoryData j ce).\n    induction ce as [hz ce].\n    transparent assert (J : (PreAdditive_functor N M)).\n    { exact (induced_PreAdditive_incl M j). }\n    split.\n    + split;intros P Q t.\n      * exact (EC_IsomorphicToExact  (applyFunctorToPairIsomorphism J _ _ t)).\n      * exact (EC_IsomorphicToExact' (applyFunctorToPairIsomorphism J _ _ t)).\n    + split.\n      * apply (squash_to_hProp hz). intros [_Z iz]. set (zM := make_Zero (j _Z) iz).\n        assert (izz : @isZero N _Z).\n        { split; intros a; apply iz. }\n        set (zN := @make_Zero N _Z izz). (* J zN = zM judgmentally *)\n        split.\n        { intros A. use ExactToAdmMono.\n          3 : { exact (pr2 (TrivialExactSequence (J A) zM)). } }\n        { intros A. use ExactToAdmEpi.\n          3 : { exact (pr2 (TrivialExactSequence' zM (J A))). } }\n      * split;unfold ExactCategoryDataToAdditiveCategory,pr1.\n        { intros P iP. apply inducedMapReflectsKernelCokernelPairs.\n          exact (EC_ExactToKernelCokernel iP). }\n        split.\n        { split.\n          { intros A B C f g mf mg.\n            apply (squash_to_hProp mf); clear mf; intros [P [p fp]].\n            apply (squash_to_hProp mg); clear mg; intros [R [q gq]].\n            assert (cs := CokernelSequence _ _ _ _ fp gq).\n            apply (squash_to_hProp cs); clear cs; intros [T [s [k [r [fgs [kr _]]]]]].\n            apply (squash_to_hProp (ce P T R k r kr)); intros [U α].\n            apply hinhpr. exists U. exists (s · z_iso_inv α).\n            exact (ExactIso3 (f·g) s (z_iso_inv α) fgs). }\n          { intros A B C f g mf mg.\n            apply (squash_to_hProp mf); clear mf; intros [P [p fp]].\n            apply (squash_to_hProp mg); clear mg; intros [R [q gq]].\n            assert (cs := KernelSequence _ _ _ _ gq fp).\n            apply (squash_to_hProp cs); clear cs; intros [T [s [k [r [fgs [kr _]]]]]].\n            apply (squash_to_hProp (ce P T R r k kr)); intros [U α].\n            apply hinhpr. exists U. exists (α · s).\n            exact (ExactIso1 α s (f·g) fgs). } }\n        split.\n        { intros A A'' B'' p f'' ep.\n          apply (squash_to_hProp ep); clear ep; intros [A' [i ex]].\n          assert (Q := ExactPullback' p i ex f'').\n          use (squash_to_hProp Q); clear Q; intros [B [p' [f [i' [eq [pb ex']]]]]].\n          assert (Q := ce A' B B'' i' p' ex').\n          apply (squash_to_hProp Q); clear Q; intros [_B t].\n          assert (t' := z_iso_inv t); clear t.\n          set (i'' := i' · t'). set (p'' := z_iso_inv t' · p').\n          assert (ex'' := ExactIso2 (M:=M) _ _ t' ex' : isExact2 i'' p'').\n          assert (pb' : isPullback' (M:=M) p f'' (z_iso_inv t'·f) p'').\n          { exact (isPullback'_up_to_z_iso (M:=M) _ _ _ _ (z_iso_inv t') pb). }\n          induction pb' as [eq2 pb']. apply hinhpr. use tpair.\n          - use tpair.\n            + exists _B. exists (z_iso_inv t'·f). exact p''.\n            + cbn. exists eq2. now apply induced_precategory_reflects_pullbacks.\n          - cbn beta. exact (ExactToAdmEpi (M:=N) ex''). }\n        { intros A A'' B'' p f'' ep.\n          apply (squash_to_hProp ep); clear ep; intros [A' [i ex]].\n          assert (Q := ExactPushout' p i ex f'').\n          use (squash_to_hProp Q); clear Q; intros [B [p' [f [i' [eq [pb ex']]]]]].\n          assert (Q := ce B'' B A' p' i' ex').\n          apply (squash_to_hProp Q); clear Q; intros [_B t].\n          set (i'' := i' ∘ t). set (p'' := z_iso_inv t ∘ p').\n          assert (ex'' := ExactIso2 (M:=M) _ _ _ ex' : isExact2 p'' i'').\n          assert (pb' : isPushout' (M:=M) p f'' (z_iso_inv t∘f) p'').\n          { exact (isPushout'_up_to_z_iso (M:=M) _ _ _ _ _ pb). }\n          induction pb' as [eq2 pb']. apply hinhpr. use tpair.\n          - use tpair.\n            + exists _B. exists (z_iso_inv t∘f). exact p''.\n            + cbn. exists eq2. now apply induced_precategory_reflects_pushouts.\n          - cbn beta. exact (ExactToAdmMono (M:=N) ex''). }\n  Qed.\n  Definition induced_ExactCategory {M:ExactCategory} {X:Type}\n             (j : X -> ob M) (ce : exts_lift M j) : ExactCategory\n    := make_ExactCategory (induced_ExactCategoryData j ce)\n                        (induced_ExactCategoryProperties j ce).\nEnd InducedExactCategory.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/ExactCategories/ExactCategories.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2414128953916976}}
{"text": "Require Import ClassicalDescription Lia.\n\nFrom hahn Require Import Hahn.\nRequire Import Events.\nRequire Import Execution.\nRequire Import Prog.\nRequire Import ProgToExecution.\nRequire Import ProgToExecutionProperties.\nRequire Import RMWinstrProps.\n\nSet Implicit Arguments.\n\n(******************************************************************************)\n(** **  *)\n(******************************************************************************)\n\nLemma ectrl_ctrl_step (tid : thread_id) \n         s s' (STEP : step tid s s')\n         MOD (ECTRL: exists a, (MOD ∩₁ ectrl s') a)\n        (NCTRL: MOD ∩₁ dom_rel ((ctrl (G s'))) ⊆₁ ∅) :\n         (G s) = (G s').\nProof using.\ndestruct STEP; desc.\nred in H; desc.\ndestruct ISTEP0; try done.\nall: exfalso; eapply NCTRL.\nall: revert ECTRL;  unfolder; splits; try edone.\nall: desc; eauto; exists (ThreadEvent tid (eindex s)).\nall: rewrite UG; unfold add; ins; rewrite <- UECTRL; basic_solver.\nQed.\n\n\nLemma TWF_helper tid s1 (TWF : thread_wf tid s1): \n~ acts_set (G s1) (ThreadEvent tid ((eindex s1))).\nProof using.\nred in TWF.\nintro.\nspecialize (TWF (ThreadEvent tid (eindex s1)) H); desf.\nlia.\nQed.\n\nLemma TWF_helper_rmw tid s1 (TWF : thread_wf tid s1): \n~ acts_set (G s1) (ThreadEvent tid ((eindex s1) + 1)).\nProof using.\nred in TWF.\nintro.\nspecialize (TWF (ThreadEvent tid (eindex s1 +1)) H); desf.\nlia.\nQed.\n\n\nLemma acts_increasing (tid : thread_id) s s' (STEP : step tid s s') :\n  (acts_set (G s)) ⊆₁ (acts_set (G s')).\nProof using.\ndestruct STEP; desc.\nred in H; desc.\ndestruct ISTEP0.\nall: rewrite UG; try done.\nall: unfold add, add_rmw, acts_set; ins.\nall: unfolder; ins; desc; eauto.\nQed.\n\nLemma is_r_ex_increasing (tid : thread_id) s s' (STEP : step tid s s') (TWF : thread_wf tid s):\n  (acts_set (G s)) ∩₁ R_ex (lab (G s)) ⊆₁ R_ex (lab (G s')).\nProof using.\ndestruct STEP; desc.\nred in H; desc.\ndestruct ISTEP0.\nall: rewrite UG; try done.\nall: unfold add, add_rmw, R_ex; ins.\nall: unfolder; ins; desc; eauto.\nall: rewrite !updo; try done.\nall: try by (intro; subst; eapply TWF_helper; edone).\nall: try by (intro; subst; eapply TWF_helper_rmw; edone).\nQed.\n\nLemma is_r_increasing (tid : thread_id) s s' (STEP : step tid s s') (TWF : thread_wf tid s):\n  (acts_set (G s)) ∩₁ is_r (lab (G s)) ⊆₁ is_r (lab (G s')).\nProof using.\ndestruct STEP; desc.\nred in H; desc.\ndestruct ISTEP0.\nall: rewrite UG; try done.\nall: unfold add, add_rmw, is_r; ins.\nall: unfolder; ins; desc; eauto.\nall: rewrite !updo; try done.\nall: try by (intro; subst; eapply TWF_helper; edone).\nall: try by (intro; subst; eapply TWF_helper_rmw; edone).\nQed.\n\n\nLemma is_w_increasing (tid : thread_id) s s' (STEP : step tid s s') (TWF : thread_wf tid s):\n  (acts_set (G s)) ∩₁ is_w (lab (G s)) ⊆₁ is_w (lab (G s')).\nProof using.\ndestruct STEP; desc.\nred in H; desc.\ndestruct ISTEP0.\nall: rewrite UG; try done.\nall: unfold add, add_rmw, is_w; ins.\nall: unfolder; ins; desc; eauto.\nall: rewrite !updo; try done.\nall: try by (intro; subst; eapply TWF_helper; edone).\nall: try by (intro; subst; eapply TWF_helper_rmw; edone).\nQed.\n\n(******************************************************************************)\n(** **  *)\n(******************************************************************************)\n\nLemma regf_expr_helper regf regf' depf MOD expr\n  (REGF : forall reg, RegFun.find reg regf = RegFun.find reg regf' \\/ \n           (exists a, RegFun.find reg depf a /\\ MOD a))\n  (NDEP: forall a (IN: MOD a), ~ DepsFile.expr_deps depf expr a):\n  RegFile.eval_expr regf expr = RegFile.eval_expr regf' expr.\nProof using.\nunfold DepsFile.expr_deps, DepsFile.val_deps in NDEP.\nunfold RegFile.eval_expr, RegFile.eval_value.\ndestruct expr.\n- destruct val; [by vauto| specialize (REGF reg); desf].\n  exfalso; eapply NDEP; edone.\n- destruct op0; [by vauto| specialize (REGF reg); desf].\n  rewrite REGF; auto.\n  exfalso; eapply NDEP; edone.\n- destruct op1, op2.\n* by vauto.\n* specialize (REGF reg); desf; [rewrite REGF|]; eauto.\n  exfalso; eapply NDEP; [edone| basic_solver].\n* specialize (REGF reg); desf; [rewrite REGF|]; eauto. \n  exfalso; eapply NDEP; [edone| basic_solver].\n* generalize (REGF reg0); intro REGF0. \n  specialize (REGF reg).\n  desf.\n  by rewrite REGF, REGF0; auto.\n  all: exfalso; eapply NDEP; [edone| basic_solver].\nQed.\n\nLemma regf_lexpr_helper regf regf' depf MOD expr\n  (REGF : forall reg, RegFun.find reg regf = RegFun.find reg regf' \\/ \n            (exists a, RegFun.find reg depf a /\\ MOD a))\n  (NDEP: forall a (IN: MOD a), ~ DepsFile.lexpr_deps depf expr a):\n  RegFile.eval_lexpr regf expr = RegFile.eval_lexpr regf' expr.\nProof using.\nunfold DepsFile.lexpr_deps in NDEP.\nunfold RegFile.eval_lexpr.\ndesf; exfalso; apply n; erewrite regf_expr_helper; eauto.\nins; specialize (REGF reg); desf; eauto.\nQed.\n\n(******************************************************************************)\n(** **  *)\n(******************************************************************************)\n\nDefinition sim_execution G G' MOD :=\n      ⟪ ACTS : (acts_set G) = (acts_set G') ⟫ /\\\n      ⟪ TS: threads_set G ≡₁ threads_set G'⟫ /\\\n      ⟪ SAME : same_lab_u2v (lab G') (lab G) ⟫ /\\\n      ⟪ OLD_VAL : forall a (NIN: ~ MOD a), val ((lab G')) a = val ((lab G)) a ⟫ /\\\n      ⟪ RMW  : (rmw G)  ≡ (rmw G')  ⟫ /\\\n      ⟪ DATA : (data G) ≡ (data G') ⟫ /\\\n      ⟪ ADDR : (addr G) ≡ (addr G') ⟫ /\\\n      ⟪ CTRL : (ctrl G) ≡ (ctrl G') ⟫ /\\\n      ⟪ FRMW : (rmw_dep G) ≡ (rmw_dep G') ⟫ /\\\n      ⟪ RRF : (rf G) ≡ (rf G') ⟫ /\\\n      ⟪ RCO : (co G) ≡ (co G') ⟫.\n\nDefinition sim_state s s' MOD (new_rfi : relation actid) new_val := \n      ⟪ INSTRS  : (instrs s) = (instrs s') ⟫ /\\\n      ⟪ PC  : (pc s) = (pc s') ⟫ /\\\n      ⟪ EXEC : sim_execution (G s) (G s') MOD ⟫ /\\\n      ⟪ EINDEX  : (eindex s) = (eindex s') ⟫ /\\\n      ⟪ REGF  : forall reg, RegFun.find reg (regf s) = RegFun.find reg (regf s') \\/ \nexists a, (RegFun.find reg (depf s)) a /\\ MOD a ⟫ /\\\n      ⟪ DEPF  : (depf s) = (depf s') ⟫ /\\\n      ⟪ ECTRL  : (ectrl s) = (ectrl s') ⟫ /\\\n      ⟪ NEW_VAL1 : forall r w (RF: new_rfi w r) (INr: (acts_set (G s')) r) \n(INw: (acts_set (G s')) w) (READ: is_r (lab (G s')) r) (WRITE: is_w (lab (G s')) w) (IN_MOD: MOD r), \n                     val ((lab (G s'))) r = val ((lab (G s'))) w ⟫ /\\\n      ⟪ NEW_VAL2 : forall r (READ: is_r (lab (G s')) r) (IN_MOD: MOD r) \n                     (IN: (acts_set (G s')) r) (NIN_NEW_RF: ~ (codom_rel new_rfi) r), \n                     val ((lab (G s'))) r = Some (new_val r) ⟫.\n\nLemma sim_execution_same_r G G' MOD (EXEC: sim_execution G G' MOD) :\nis_r (lab G') ≡₁ is_r (lab G).\nProof using.\nred in EXEC; desf.\neby erewrite same_lab_u2v_is_r.\nQed.\n\nLemma sim_execution_same_w G G' MOD (EXEC: sim_execution G G' MOD) :\nis_w (lab G') ≡₁ is_w (lab G).\nProof using.\nred in EXEC; desf.\neby erewrite same_lab_u2v_is_w.\nQed.\n\nLemma sim_execution_same_acts G G' MOD (EXEC: sim_execution G G' MOD) :\nacts_set G ≡₁ acts_set G'.\nProof using.\nred in EXEC; desf. by rewrite ACTS.\nQed.\n\n(******************************************************************************)\n(** **  *)\n(******************************************************************************)\n\nLemma receptiveness_sim_assign (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (reg : Reg.t) (expr : Instr.expr)\n  (ISTEP : Some (Instr.assign reg expr) = nth_error (instrs s1) (pc s1))\n  (UPC : pc s2 = pc s1 + 1) (UG : G s2 = G s1)\n  (UINDEX : eindex s2 = eindex s1)\n  (UREGS : regf s2 = RegFun.add reg (RegFile.eval_expr (regf s1) expr) (regf s1))\n  (UDEPS : depf s2 = RegFun.add reg (DepsFile.expr_deps (depf s1) expr) (depf s1))\n  (UECTRL : ectrl s2 = ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\ndo 7 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eby eexists; splits; [ rewrite <- INSTRS, <- PC| eapply assign; reflexivity].\n  * ins; congruence.\n  * ins; congruence.\n  * ins; congruence.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf.\n    destruct (classic ((exists a : actid, DepsFile.expr_deps (depf s1) expr a /\\ MOD a))) as [A|A].\n    by auto.\n    by left; apply (regf_expr_helper (regf s1) (regf s1') (depf s1) MOD expr REGF); eauto.\n  * ins; congruence.\n  * ins; congruence.\n  * by ins; apply NEW_VAL1; try done; rewrite <- UG.\n  * by ins; apply NEW_VAL2; try done; rewrite <- UG.\nQed.\n\nLemma receptiveness_sim_if_else (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (expr : Instr.expr) (shift : nat)\n  (e : RegFile.eval_expr (regf s1) expr = 0)\n  (ISTEP : Some (Instr.ifgoto expr shift) = nth_error (instrs s1) (pc s1))\n  (UPC : pc s2 = pc s1 + 1) (UG : G s2 = G s1)\n  (UINDEX : eindex s2 = eindex s1)\n  (UREGS : regf s2 = regf s1)\n  (UDEPS : depf s2 = depf s1)\n  (UECTRL : ectrl s2 = DepsFile.expr_deps (depf s1) expr ∪₁ ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  (NCTRL : MOD ∩₁ ectrl s2 ⊆₁ ∅)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\neexists.\n  exists (if Const.eq_dec (RegFile.eval_expr (regf s1') expr) 0\n        then pc s1' + 1 else shift).\n  do 5 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC|].\n    eapply if_; try reflexivity; ins; desf.\n  * ins; congruence.\n  * ins.\n    erewrite <- regf_expr_helper with (regf:= regf s1).\n    desf; congruence.\n    eauto.\n    ins; intro; eapply NCTRL; rewrite UECTRL; basic_solver.\n  * ins; congruence.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS; eauto.\n  * ins; congruence.\n  * ins; congruence.\n  * by ins; apply NEW_VAL1; try done; rewrite <- UG.\n  * by ins; apply NEW_VAL2; try done; rewrite <- UG.\nQed.\n\nLemma receptiveness_sim_if_then (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (expr : Instr.expr) (shift : nat)\n  (n : RegFile.eval_expr (regf s1) expr <> 0)\n  (ISTEP : Some (Instr.ifgoto expr shift) = nth_error (instrs s1) (pc s1))\n  (UPC : pc s2 = shift) (UG : G s2 = G s1)\n  (UINDEX : eindex s2 = eindex s1)\n  (UREGS : regf s2 = regf s1)\n  (UDEPS : depf s2 = depf s1)\n  (UECTRL : ectrl s2 = DepsFile.expr_deps (depf s1) expr ∪₁ ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  (NCTRL : MOD ∩₁ ectrl s2 ⊆₁ ∅)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\n eexists.\n  exists (if Const.eq_dec (RegFile.eval_expr (regf s1') expr) 0\n        then pc s1' + 1 else shift).\n  do 5 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC|].\n    eapply if_; try reflexivity; ins; desf.\n  * ins; congruence.\n  * ins.\n    erewrite <- regf_expr_helper with (regf:= regf s1).\n    desf; congruence.\n    eauto.\n    ins; intro; eapply NCTRL; rewrite UECTRL; basic_solver.\n  * ins; congruence.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS; eauto.\n  * ins; congruence.\n  * ins; congruence.\n  * by ins; apply NEW_VAL1; try done; rewrite <- UG.\n  * by ins; apply NEW_VAL2; try done; rewrite <- UG.\nQed.\n\nDefinition new_rfi_ex (new_rfi :relation actid) :=\nnew_rfi ∪ ⦗ set_compl (codom_rel new_rfi) ⦘.\n\nLemma new_rfi_unique (new_rfi : relation actid)\n      (new_rfif : functional new_rfi⁻¹):\nforall r, exists ! w, (new_rfi_ex new_rfi)⁻¹  r w.\nProof using.\nins.\ndestruct (classic ((codom_rel new_rfi) r)) as [X|X].\n- unfolder in X; desf.\nexists x; red; splits.\nunfold new_rfi_ex; basic_solver 12.\nunfold new_rfi_ex; unfolder; ins; desf.\neapply new_rfif; basic_solver.\nexfalso; eauto.\n- exists r; red; splits.\nunfold new_rfi_ex; basic_solver 12.\nunfold new_rfi_ex; unfolder; ins; desf.\nunfolder in X; exfalso; eauto.\nQed.\n\nDefinition new_write new_rfi new_rfif := \n  unique_choice (new_rfi_ex new_rfi)⁻¹ (@new_rfi_unique new_rfi new_rfif).\n\nDefinition get_val (v: option value) := \n  match v with | Some v => v | _ => 0 end.\n\nLemma RFI_index_helper tid s new_rfi (TWF : thread_wf tid s)\n   (RFI_INDEX : new_rfi ⊆ ext_sb)\n   w r (RFI: new_rfi w r) \n  (IN: ThreadEvent tid (eindex s) = r \\/ (acts_set (G s)) r) :\n   w <> ThreadEvent tid ((eindex s)).\nProof using.\nintro; subst; desf.\napply RFI_INDEX in RFI.\neby eapply ext_sb_irr.\nspecialize (TWF r IN); desf.\napply RFI_INDEX in RFI.\nunfold sb, ext_sb in RFI; unfolder in RFI; desf; lia.\nQed.\n\nLemma receptiveness_sim_load (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (ord : mode) (reg : Reg.t)\n  (lexpr : Instr.lexpr) (ISTEP : Some (Instr.load ord reg lexpr) = nth_error (instrs s1) (pc s1))\n  (val_ : value) (UPC : pc s2 = pc s1 + 1)\n  (UG : G s2 =\n     add (G s1) tid (eindex s1)\n       (Aload false ord (RegFile.eval_lexpr (regf s1) lexpr) val_) \n       ∅ (DepsFile.lexpr_deps (depf s1) lexpr) (ectrl s1) \n       ∅)\n  (UINDEX : eindex s2 = eindex s1 + 1)\n  (UREGS : regf s2 = RegFun.add reg val_ (regf s1))\n  (UDEPS : depf s2 = RegFun.add reg (eq (ThreadEvent tid (eindex s1))) (depf s1))\n  (UECTRL : ectrl s2 = ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  (NADDR : MOD ∩₁ dom_rel ((addr (G s2))) ⊆₁ ∅)\n  (RFI_INDEX : new_rfi ⊆ ext_sb)\n  (TWF : thread_wf tid s1)\n  (new_rfif : functional new_rfi⁻¹)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\ngeneralize (@new_write new_rfi new_rfif); intro F; destruct F as [new_w F].\nred in SIM; desc.\n\nassert (SAME_LOC: RegFile.eval_lexpr (regf s1) lexpr = RegFile.eval_lexpr (regf s1') lexpr).\n{ ins; eapply regf_lexpr_helper; eauto.\nins; intro; eapply NADDR; unfolder; splits; eauto.\nexists (ThreadEvent tid (eindex s1)).\nrewrite UG; unfold add; basic_solver. } \n\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\n\ndo 7 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply load with (val := \n      if excluded_middle_informative (MOD (ThreadEvent tid (eindex s1'))) \n      then if excluded_middle_informative ((codom_rel new_rfi) (ThreadEvent tid (eindex s1'))) \n           then (get_val (val (lab (G s1')) (new_w (ThreadEvent tid (eindex s1')))))\n           else (new_val (ThreadEvent tid (eindex s1')))\n      else val_);\n    reflexivity.\n  * ins; congruence.\n  * ins; congruence.\n  * ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG.\n    red in EXEC; desc.\n    red; splits; ins.\n    + by rewrite EINDEX, ACTS.\n    + by rewrite TS. \n    + rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      { by subst; rewrite !upds. }\n      ins. rewrite !updo; auto.\n    + rewrite EINDEX.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))).\n      by desf; unfold val; rewrite !upds.\n      unfold val; rewrite !updo; [|intro; desf|intro; desf].\n      by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN.\n    + by rewrite DATA, EINDEX.\n    + by rewrite ADDR, EINDEX, DEPF.\n    + by rewrite CTRL, EINDEX, ECTRL.\n    + by rewrite FRMW, EINDEX.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto.\n  * eby ins; rewrite <- DEPF, <- EINDEX.\n  * ins; congruence.\n  * simpl; ins.\n     unfold add, acts_set in INw; ins.\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    + exfalso; eapply RFI_index_helper.\n      edone.\n      eapply RFI_INDEX.\n      edone.\n      unfold add, acts_set in INr; ins.\n      rewrite EINDEX; destruct INr; [eauto|].\n      right; eapply sim_execution_same_acts; eauto.\n      by rewrite EINDEX.\n    + destruct INw as [X|INw]; [desf|].\n      destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n      -- unfold val in *; rewrite !upds.\n         rewrite !updo; try done.\n         destruct (excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))); [|desf].\n         destruct (excluded_middle_informative (codom_rel new_rfi (ThreadEvent tid (eindex s1')))).\n         2: by exfalso; apply n0; basic_solver 12.\n         assert (w = new_w (ThreadEvent tid (eindex s1'))).\n         { assert (U: exists ! w1 : actid, (new_rfi_ex new_rfi)⁻¹ (ThreadEvent tid (eindex s1')) w1).\n           apply new_rfi_unique, new_rfif.\n           eapply unique_existence with \n           (P:= fun x => (@new_rfi_ex new_rfi)⁻¹ (ThreadEvent tid (eindex s1')) x) in U; desc.\n           eapply U0.\n           unfold new_rfi_ex.\n           basic_solver.\n           apply F. }\n         unfold is_w in WRITE; rewrite updo in WRITE; desf.\n      -- unfold val in *; rewrite !updo; try done.\n         eapply NEW_VAL1; try edone.\n         { unfolder in INr. desf. }\n         { by unfold is_r in *; rewrite updo in READ. }\n           by unfold is_w in *; rewrite updo in WRITE.\n  * simpl; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    + destruct (excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))); [subst|desf].\n      destruct (excluded_middle_informative (codom_rel new_rfi (ThreadEvent tid (eindex s1')))); [desf|].\n      by unfold val in *; rewrite !upds.\n    + unfold val in *; rewrite !updo; try done.\n      apply NEW_VAL2; try done.\n      { by unfold is_r in *; rewrite updo in READ. }\n        by unfolder in IN; unfold add in IN; ins; desf.\nQed.\n\nLemma receptiveness_sim_store (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (ord : mode) (reg : Reg.t)\n  (lexpr : Instr.lexpr) (expr : Instr.expr)\n  (ISTEP : Some (Instr.store ord lexpr expr) = nth_error (instrs s1) (pc s1))\n  (UPC : pc s2 = pc s1 + 1)\n  (UG : G s2 = add (G s1) tid (eindex s1)\n         (Astore Xpln ord (RegFile.eval_lexpr (regf s1) lexpr) (RegFile.eval_expr (regf s1) expr)) \n         (DepsFile.expr_deps (depf s1) expr) (DepsFile.lexpr_deps (depf s1) lexpr) (ectrl s1) ∅) \n  (UINDEX : eindex s2 = eindex s1 + 1)\n  (UREGS : regf s2 = regf s1)\n  (UDEPS : depf s2 = depf s1)\n  (UECTRL : ectrl s2 = ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  (NADDR : MOD ∩₁ dom_rel ((addr (G s2))) ⊆₁ ∅)\n  (NDATA: ⦗MOD⦘ ⨾ (data (G s2)) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂)\n   (RFI_INDEX : new_rfi ⊆ ext_sb)\n  (TWF : thread_wf tid s1)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\n\nassert (SAME_LOC: RegFile.eval_lexpr (regf s1) lexpr = RegFile.eval_lexpr (regf s1') lexpr).\n{ ins; eapply regf_lexpr_helper; eauto.\nins; intro; eapply NADDR; unfolder; splits; eauto.\nexists (ThreadEvent tid (eindex s1)).\nrewrite UG; unfold add; basic_solver. } \n\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\n\n do 7 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply store; reflexivity.\n  * ins; congruence.\n  * ins; congruence.\n  * ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG.\n    red in EXEC; desc.\n    red; splits; ins.\n    + by rewrite EINDEX, ACTS.\n    + by rewrite TS. \n    + rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      { by subst; rewrite !upds. }\n      rewrite !updo; auto.\n    + rewrite EINDEX.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))); subst.\n      -- desf; unfold val; rewrite !upds.\n         erewrite regf_expr_helper; try edone.\n         intro reg0; specialize (REGF reg0); desf; eauto.\n         ins; intro DEPS; eapply NDATA; unfolder; splits; eauto.\n         by rewrite EINDEX.\n      -- unfold val;  rewrite !updo; try done.\n         by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN.\n    + by rewrite DATA, EINDEX, DEPF.\n    + by rewrite ADDR, EINDEX, DEPF.\n    + by rewrite CTRL, EINDEX, ECTRL.\n    + by rewrite FRMW, EINDEX.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto.\n  * by ins; rewrite <- DEPF, <- UDEPS.\n  * ins; congruence.\n  * simpl; ins.\n    unfold add, acts_set in INw; ins.\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    + exfalso; eapply RFI_index_helper.\n      edone.\n      eapply RFI_INDEX.\n      edone.\n      unfold add, acts_set in INr; ins.\n      rewrite EINDEX; destruct INr; [eauto|].\n      right; eapply sim_execution_same_acts; eauto.\n      by rewrite EINDEX.\n    + destruct INw as [X|INw]; [desf|].\n      destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n      by unfold is_r in *; rewrite !upds in READ; desf.\n      unfold val in *; rewrite !updo; try done.\n      eapply NEW_VAL1; try edone.\n      { unfolder in INr; desf. }\n      { by unfold is_r in *; rewrite updo in READ. }\n        by unfold is_w in *; rewrite updo in WRITE.\n  * simpl; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    by unfold is_r in *; rewrite upds in READ; desf.\n    unfold val; rewrite updo; try done.\n    apply NEW_VAL2; try done.\n    unfold is_r in *; rewrite updo in READ; try done.\n    unfolder in IN. desf.\nQed.\n\nLemma receptiveness_sim_fence (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (ord : mode) \n  (ISTEP : Some (Instr.fence ord) = nth_error (instrs s1) (pc s1))\n  (UPC : pc s2 = pc s1 + 1)\n  (UG : G s2 = add (G s1) tid (eindex s1) (Afence ord) ∅ ∅ (ectrl s1) ∅)\n  (UINDEX : eindex s2 = eindex s1 + 1)\n  (UREGS : regf s2 = regf s1)\n  (UDEPS : depf s2 = depf s1)\n  (UECTRL : ectrl s2 = ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\n\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\n\ndo 7 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply fence; reflexivity.\n  * ins; congruence.\n  * ins; congruence.\n  * ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG.\n    red in EXEC; desc.\n    red; splits; ins.\n    + by rewrite EINDEX, ACTS.\n    + by rewrite TS. \n    + rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      { by subst; rewrite !upds. }\n      rewrite !updo; auto.\n    + rewrite EINDEX.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))).\n      by desf; unfold val; rewrite !upds.\n      unfold val; rewrite !updo; [|intro; desf|intro; desf].\n      by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN.\n    + by rewrite DATA, EINDEX.\n    + by rewrite ADDR, EINDEX.\n    + by rewrite CTRL, EINDEX, ECTRL.\n    + by rewrite FRMW, EINDEX.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto.\n  * by ins; rewrite <- DEPF, <- UDEPS.\n  * ins; congruence.\n  * ins.\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    by unfold is_w in WRITE; rewrite upds in WRITE; desf.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    by unfold is_r in READ; rewrite upds in READ; desf.\n    unfold val; rewrite !updo; try done.\n    eapply NEW_VAL1; try edone.\n    { unfolder in INr; desf. }\n    { unfolder in INw; desf. }\n    { unfold is_r in *; rewrite updo in READ; try edone. }\n    unfold is_w in *; rewrite updo in WRITE; try edone.\n  * simpl; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    by unfold is_r in *; rewrite upds in READ; desf.\n    unfold val; rewrite updo; try done.\n    apply NEW_VAL2; try done.\n    unfold is_r in *; rewrite updo in READ; try done.\n    unfolder in IN; desf.\nQed.\n\nLemma receptiveness_sim_cas_fail (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (CASREX : cas_produces_R_ex_instrs (instrs s1))\n  (expr_old expr_new : Instr.expr)\n  rexmod\n  xmod\n  (ordr ordw : mode)\n  (reg : Reg.t)\n  (lexpr : Instr.lexpr)\n  (ISTEP : Some (Instr.update (Instr.cas expr_old expr_new) rexmod xmod ordr ordw reg lexpr) =\n           nth_error (instrs s1) (pc s1))\n  (val_ : value)\n  (NEXPECTED : val_ <> RegFile.eval_expr (regf s1) expr_old)\n  (UPC : pc s2 = pc s1 + 1)\n  (UG : G s2 =\n        add (G s1) tid (eindex s1)\n            (Aload rexmod ordr (RegFile.eval_lexpr (regf s1) lexpr) val_) \n            ∅ (DepsFile.lexpr_deps (depf s1) lexpr) (ectrl s1)\n            (DepsFile.expr_deps (depf s1) expr_old))\n  (UINDEX : eindex s2 = eindex s1 + 1)\n  (UREGS : regf s2 = RegFun.add reg val_ (regf s1))\n  (UDEPS : depf s2 = RegFun.add reg (eq (ThreadEvent tid (eindex s1))) (depf s1))\n  (UECTRL : ectrl s2 = ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  (NFRMW: MOD ∩₁ dom_rel ((rmw_dep (G s2))) ⊆₁ ∅)\n  (NADDR : MOD ∩₁ dom_rel ((addr (G s2))) ⊆₁ ∅)\n  (NREX:  MOD ∩₁ (acts_set (G s2)) ∩₁ (R_ex (lab (G s2))) ⊆₁ ∅) \n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n  exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\nassert (rexmod = true); subst.\n{ clear -ISTEP CASREX. red in CASREX.\n  set (AA:=ISTEP).\n  symmetry in AA. apply nth_error_In in AA.\n  apply CASREX in AA. red in AA. desf. }\n\nassert (SAME_LOC: RegFile.eval_lexpr (regf s1) lexpr = RegFile.eval_lexpr (regf s1') lexpr).\n{ eapply regf_lexpr_helper; eauto.\nins; intro; eapply NADDR; unfolder; splits; eauto.\nexists (ThreadEvent tid (eindex s1)).\nrewrite UG; unfold add; basic_solver. } \n\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\n\ndo 7 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply cas_un with (val := val_); try reflexivity.\n    erewrite <- regf_expr_helper with (regf := (regf s1)); try edone.\n    ins; intro;  eapply NFRMW; rewrite UG; unfold add; ins; basic_solver.\n  * ins; congruence.\n  * ins; congruence.\n  * ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG.\n    red in EXEC; desc.\n    red; splits; ins.\n    + by rewrite EINDEX, ACTS.\n    + by rewrite TS. \n    + rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      { by subst; rewrite !upds; rewrite SAME_LOC. }\n      rewrite !updo; auto.\n    + rewrite EINDEX.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))).\n      rewrite SAME_LOC.\n      by desf; unfold val; rewrite !upds.\n      unfold val; rewrite !updo; [|intro; desf|intro; desf].\n      by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN.\n    + by rewrite DATA, EINDEX.\n    + by rewrite ADDR, EINDEX, DEPF.\n    + by rewrite CTRL, EINDEX, ECTRL.\n    + by rewrite FRMW, EINDEX, DEPF.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto.\n  * eby ins; rewrite <- DEPF, <- EINDEX.\n  * ins; congruence.\n  * ins.\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    by unfold is_w in WRITE; rewrite upds in WRITE; desf.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    + exfalso.\n      eapply NREX; split; [eauto|].\n      { rewrite UG; unfold add; ins. split; eauto.\n        rewrite EINDEX; basic_solver. }\n      rewrite UG; unfold add; unfold R_ex; ins.\n        by rewrite EINDEX, upds.\n    + unfold val; rewrite !updo; try done.\n      eapply NEW_VAL1; try edone.\n      { unfolder in INr. desf. }\n      { unfolder in INw. desf. }\n      { unfold is_r in *; rewrite updo in READ; try edone. }\n      unfold is_w in *; rewrite updo in WRITE; try edone.\n  * simpl; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    + exfalso.\n      eapply NREX; split; [eauto|].\n      { rewrite UG; unfold add; ins. split; eauto.\n        rewrite EINDEX; basic_solver. }\n      rewrite UG; unfold add; unfold R_ex; ins.\n      by rewrite EINDEX, upds.\n    + unfold val; rewrite updo; try done.\n      apply NEW_VAL2; try done.\n      unfold is_r in *; rewrite updo in READ; try done.\n      unfolder in IN. desf.\nQed.\n\nLemma receptiveness_sim_cas_suc (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (CASREX : cas_produces_R_ex_instrs (instrs s1))\n  (expr_old expr_new : Instr.expr)\n  rexmod xmod\n  (ordr ordw : mode)\n  (reg : Reg.t)\n  (lexpr : Instr.lexpr)\n  (ISTEP : Some (Instr.update (Instr.cas expr_old expr_new) rexmod xmod ordr ordw reg lexpr) =\n           nth_error (instrs s1) (pc s1))\n  (UPC : pc s2 = pc s1 + 1)\n  (UG : G s2 =\n        add_rmw (G s1) tid (eindex s1)\n                (Aload rexmod ordr (RegFile.eval_lexpr (regf s1) lexpr)\n                       (RegFile.eval_expr (regf s1) expr_old))\n                (Astore xmod ordw (RegFile.eval_lexpr (regf s1) lexpr)\n                        (RegFile.eval_expr (regf s1) expr_new))\n                (DepsFile.expr_deps (depf s1) expr_new)\n                (DepsFile.lexpr_deps (depf s1) lexpr) (ectrl s1)\n                (DepsFile.expr_deps (depf s1) expr_old))\n  (UINDEX : eindex s2 = eindex s1 + 2)\n  (UREGS : regf s2 = RegFun.add reg (RegFile.eval_expr (regf s1) expr_old) (regf s1))\n  (UDEPS : depf s2 = RegFun.add reg (eq (ThreadEvent tid (eindex s1))) (depf s1))\n  (UECTRL : ectrl s2 = ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  (NFRMW: MOD ∩₁ dom_rel ((rmw_dep (G s2))) ⊆₁ ∅)\n  (NADDR : MOD ∩₁ dom_rel ((addr (G s2))) ⊆₁ ∅)\n  (NREX:  MOD ∩₁ (acts_set (G s2)) ∩₁ (R_ex (lab (G s2))) ⊆₁ ∅) \n  (NDATA: ⦗MOD⦘ ⨾ (data (G s2)) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂)\n  (RFI_INDEX : new_rfi ⊆ ext_sb)\n  (TWF : thread_wf tid s1)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n  exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\n\nassert (rexmod = true); subst.\n{ clear -ISTEP CASREX. red in CASREX.\n  set (AA:=ISTEP).\n  symmetry in AA. apply nth_error_In in AA.\n  apply CASREX in AA. red in AA. desf. }\n\nassert (SAME_LOC: RegFile.eval_lexpr (regf s1) lexpr = RegFile.eval_lexpr (regf s1') lexpr).\n{ ins; eapply regf_lexpr_helper; eauto.\nins; intro; eapply NADDR; unfolder; splits; eauto.\nexists (ThreadEvent tid (eindex s1)).\nrewrite UG; unfold add_rmw; basic_solver. } \n\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\n\ndo 7 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply cas_suc; try reflexivity.\n  * ins; congruence.\n  * ins; congruence.\n  * ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG; ins.\n    unfold acts_set, R_ex in NREX; ins.\n    red in EXEC; desc.\n    red; splits; ins.\n    + by rewrite EINDEX, ACTS.\n    + by rewrite TS. \n    + rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1' + 1))).\n      by subst; rewrite !upds; rewrite SAME_LOC.\n      rewrite updo; try done.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      by subst; rewrite !upds; rewrite updo; [| by desf]; rewrite upds; rewrite SAME_LOC.\n      rewrite !updo; auto.\n    + rewrite EINDEX.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1' + 1))).\n      -- subst; rewrite SAME_LOC.\n         unfold val; rewrite !upds.\n         erewrite regf_expr_helper; try edone.\n         intro reg0; specialize (REGF reg0); desf; eauto.\n         ins; intro DEPS; eapply NDATA; unfolder; splits; eauto.\n         by rewrite EINDEX.\n      -- unfold val; rewrite updo; [|done].\n         destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))).\n         ** subst; rewrite SAME_LOC.\n            rewrite !upds.\n            rewrite updo; [|intro; desf; lia].\n            rewrite !upds.\n            erewrite regf_expr_helper; try edone.\n            intro reg0; specialize (REGF reg0); desf; eauto.\n            ins; intro DEPS; eapply NFRMW; unfolder; splits; eauto.\n         ** rewrite !updo; try done.\n            by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN.\n    + by rewrite RMW, EINDEX.\n    + by rewrite DATA, EINDEX, DEPF.\n    + by rewrite ADDR, EINDEX, DEPF.\n    + by rewrite CTRL, EINDEX, ECTRL.\n    + by rewrite FRMW, EINDEX, DEPF.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto.\n    erewrite regf_expr_helper; eauto.\n    ins; intro; eapply NFRMW.\n    rewrite UG; ins; basic_solver.\n  * eby ins; rewrite <- DEPF, <- EINDEX.\n  * ins; congruence.\n  * ins; unfold acts_set, is_r, is_w in INr, INw, READ, WRITE; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'+1))); subst.\n    by rewrite upds in READ; desf.\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    rewrite updo in WRITE; [| intro; desf; lia].\n    by rewrite upds in WRITE; desf.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    + exfalso.\n      eapply NREX; split; [eauto|].\n      { rewrite UG; unfold add; ins. split; eauto.\n        rewrite EINDEX; basic_solver. }\n      rewrite UG; unfold add; unfold R_ex; ins.\n      by rewrite updo; [| intro; desf; lia]; rewrite EINDEX, upds.\n    + unfold val; rewrite updo; [|done].\n      rewrite updo; [|done].\n      destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'+1))); subst.\n      -- exfalso.\n         apply RFI_INDEX in RF; unfold ext_sb in RF.\n         destruct r; [eauto|]; desc.\n         destruct INr as [[X|X]|INr]; try by desf.\n         apply sim_execution_same_acts in EXEC.\n         apply EXEC in INr.\n         apply TWF in INr; desc.\n         rewrite <- EINDEX in RF0.\n         desf; lia.\n      -- rewrite !updo; try done.\n         eapply NEW_VAL1; try edone.\n         { unfolder in INr; desf. }\n         { unfolder in INw; desf. }\n         { by rewrite !updo in READ; try edone. }\n           by rewrite !updo in WRITE; try edone.\n  * simpl; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'+1))); subst.\n    by unfold is_r in READ; rewrite upds in READ; desf.\n    unfold val; rewrite updo; [|done].\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    + exfalso.\n      eapply NREX; split; [eauto|].\n      { rewrite UG; unfold add; unfold acts_set; ins. split; eauto.\n        rewrite EINDEX; basic_solver. }\n      rewrite UG; unfold add; unfold R_ex; ins.\n      by rewrite updo; [| intro; desf; lia]; rewrite EINDEX, upds.\n    + unfold val; rewrite updo; try done.\n      apply NEW_VAL2; try done.\n      unfold is_r in *; rewrite !updo in READ; try done.\n      unfolder in IN; desf.\nQed.\n\nLemma receptiveness_sim_inc (tid : thread_id)\n      s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n      (expr_add : Instr.expr)\n      rexmod xmod\n      (ordr ordw : mode)\n      (reg : Reg.t)\n      (lexpr : Instr.lexpr)\n      (ISTEP : Some (Instr.update\n                       (Instr.fetch_add expr_add) rexmod xmod ordr ordw reg lexpr) =\n               nth_error (instrs s1) (pc s1))\n      (val_ : nat)\n      (UPC : pc s2 = pc s1 + 1)\n      (UG : G s2 =\n            add_rmw (G s1) tid (eindex s1)\n                    (Aload rexmod ordr\n                           (RegFile.eval_lexpr (regf s1) lexpr) val_)\n                    (Astore xmod ordw (RegFile.eval_lexpr (regf s1) lexpr)\n                            (val_ + RegFile.eval_expr (regf s1) expr_add))\n                    ((eq (ThreadEvent tid (eindex s1))) ∪₁\n                     (DepsFile.expr_deps (depf s1) expr_add))\n                    (DepsFile.lexpr_deps (depf s1) lexpr)\n                    (ectrl s1) ∅)\n      (UINDEX : eindex s2 = eindex s1 + 2)\n      (UREGS : regf s2 = RegFun.add reg val_ (regf s1))\n      (UDEPS : depf s2 = RegFun.add reg (eq (ThreadEvent tid (eindex s1))) (depf s1))\n      (UECTRL : ectrl s2 = ectrl s1)\n      MOD (new_rfi : relation actid) new_val\n      (NFRMW: MOD ∩₁ dom_rel ((rmw_dep (G s2))) ⊆₁ ∅)\n      (NADDR : MOD ∩₁ dom_rel ((addr (G s2))) ⊆₁ ∅)\n      (NREX:  MOD ∩₁ (acts_set (G s2)) ∩₁ (R_ex (lab (G s2))) ⊆₁ ∅) \n      (NDATA: ⦗MOD⦘ ⨾ (data (G s2)) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂)\n      (TWF : thread_wf tid s1)\n      (RFI_INDEX : new_rfi ⊆ ext_sb)\n      (new_rfif : functional new_rfi⁻¹)\n      s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\n  generalize (@new_write new_rfi new_rfif); intro F; destruct F as [new_w F].\n  red in SIM; desc.\n  assert (SAME_LOC : RegFile.eval_lexpr (regf s1) lexpr =\n                     RegFile.eval_lexpr (regf s1') lexpr).\n  { ins; eapply regf_lexpr_helper; eauto.\n    ins; intro; eapply NADDR; unfolder; splits; eauto.\n    exists (ThreadEvent tid (eindex s1)).\n    rewrite UG; unfold add_rmw; basic_solver. } \n\n  cut (exists instrs pc G_ eindex regf depf ectrl, \n          step tid s1' (Build_state instrs pc G_ eindex regf depf ectrl) /\\ \n          (sim_state s2 (Build_state instrs pc G_ eindex regf depf ectrl)\n                     MOD new_rfi new_val)).\n  { ins; desc; eauto. }\n  do 7 eexists; splits; red; splits.\n  { eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply inc with (val := \n      if excluded_middle_informative (MOD (ThreadEvent tid (eindex s1'))) \n      then if excluded_middle_informative ((codom_rel new_rfi) (ThreadEvent tid (eindex s1'))) \n           then (get_val (val (lab (G s1')) (new_w (ThreadEvent tid (eindex s1')))))\n           else (new_val (ThreadEvent tid (eindex s1')))\n      else val_);\n    reflexivity. }\n  1,2,4,7: ins; congruence.\n  { ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG.\n    red in EXEC; desc.\n    red; splits; ins.\n    { by rewrite EINDEX, ACTS. }\n    {  by rewrite TS. }\n    { rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      { subst.\n        rewrite updo; [|intros HH; clear -HH; inv HH; lia]. \n        rewrite !upds. unfold same_label_u2v.\n        rewrite updo; [|intros HH; clear -HH; inv HH; lia]. \n        rewrite upds; auto. }\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1' + 1))).\n      { subst.\n        rewrite !upds. unfold same_label_u2v; auto. }\n      ins. rewrite !updo; auto. }\n    { rewrite EINDEX.\n      unfold val.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1' + 1))).\n      { subst.\n        destruct (excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))) as [MN|NMN].\n        { exfalso.\n          eapply NDATA. \n          apply seq_eqv_lr. splits; eauto.\n          basic_solver 10. }\n        assert (SAME_VAL : RegFile.eval_expr (regf s1 ) expr_add =\n                           RegFile.eval_expr (regf s1') expr_add).\n        { ins; eapply regf_expr_helper; eauto.\n          ins; intro; eapply NDATA; unfolder; splits; eauto.\n            by rewrite EINDEX. }\n        rewrite !upds. by rewrite SAME_VAL. }\n      rewrite updo; auto.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))).\n      { subst.\n        rewrite !upds.\n        destruct (excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))) as [MN|NMN].\n        { exfalso. eauto. }\n        rewrite updo; [|intros HH; clear -HH; inv HH; lia]. \n          by rewrite upds. }\n      rewrite !updo; auto.\n      by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN. }\n    { by rewrite RMW, EINDEX. }\n    { by rewrite DATA, EINDEX, DEPF. }\n    { by rewrite ADDR, EINDEX, DEPF. }\n    { by rewrite CTRL, EINDEX, ECTRL. }\n      by rewrite FRMW, EINDEX. }\n  { ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto. }\n  { eby ins; rewrite <- DEPF, <- EINDEX. }\n  { ins; unfold acts_set, is_r, is_w in INr, INw, READ, WRITE; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'+1))); subst.\n    { by rewrite upds in READ; desf. }\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    rewrite updo in WRITE; [| intro; desf; lia].\n    { by rewrite upds in WRITE; desf. }\n\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1' + 1))); subst.\n    { exfalso.\n      apply RFI_INDEX in RF; unfold ext_sb in RF.\n      destruct INr as [[INr|INr]|INr]; subst.\n      1,2: clear -RF; lia.\n      destruct r; [eauto|]; desc.\n      apply sim_execution_same_acts in EXEC.\n      apply EXEC in INr.\n      apply TWF in INr; desc.\n      rewrite <- EINDEX in RF0.\n      inv EE. clear -RF0 LT. lia. }\n\n    assert (is_w (lab (G s1')) w) as WW'.\n    { rewrite !updo in WRITE; edone. }\n\n    unfold val.\n    rewrite updo; auto.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    { rewrite !upds.\n      destruct (excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))) as [MN|NMN].\n      2: eby exfalso.\n      rewrite !updo; auto.\n      destruct (excluded_middle_informative\n                  (codom_rel new_rfi (ThreadEvent tid (eindex s1')))) as [|XX].\n      2: { exfalso. apply XX. generalize RF. clear. basic_solver. }\n      assert (w = new_w (ThreadEvent tid (eindex s1'))); subst.\n      { edestruct new_rfi_unique with\n            (r:=ThreadEvent tid (eindex s1')) as [wu [_ HH]]; eauto.\n        transitivity wu.\n        2: by apply HH.\n        symmetry. apply HH. do 2 red. generalize RF. clear. basic_solver. }\n      unfold get_val.\n      clear -WW'. unfold is_w in WW'. desf. }\n    rewrite !updo; auto.\n    eapply NEW_VAL1; try edone.\n    { unfolder in INr; desf. }\n    { unfolder in INw; desf. }\n      by rewrite !updo in READ; try edone. }\n  simpl; ins.\n  destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'+1))); subst.\n  { by unfold is_r in READ; rewrite upds in READ; desf. }\n  unfold val; rewrite updo; [|done].\n  destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n  { rewrite upds. desf. }\n  unfold val; rewrite updo; try done.\n  apply NEW_VAL2; try done.\n  unfold is_r in *; rewrite !updo in READ; try done.\n  unfolder in IN; desf.\nQed.\n\nLemma receptiveness_sim_exchange\n      (tid : thread_id)\n      s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n      (new_expr : Instr.expr)\n      rexmod xmod\n      (ordr ordw : mode)\n      (reg : Reg.t)\n      (lexpr : Instr.lexpr)\n      (ISTEP : Some (Instr.update\n                       (Instr.exchange new_expr)\n                       rexmod xmod ordr ordw reg lexpr) = nth_error (instrs s1) (pc s1))\n      (val_ : nat)\n      (UPC : pc s2 = pc s1 + 1)\n      (UG : G s2 = add_rmw (G s1) tid (eindex s1)\n                           (Aload rexmod ordr (RegFile.eval_lexpr (regf s1) lexpr)\n                                  val_)\n                           (Astore xmod ordw (RegFile.eval_lexpr (regf s1) lexpr)\n                                   (RegFile.eval_expr (regf s1) new_expr))\n                           (DepsFile.expr_deps (depf s1) new_expr)\n                           (DepsFile.lexpr_deps (depf s1) lexpr)\n                           (ectrl s1) ∅)\n      (UINDEX : eindex s2 = eindex s1 + 2)\n      (UREGS : regf s2 = RegFun.add reg val_ (regf s1))\n      (UDEPS : depf s2 = RegFun.add reg (eq (ThreadEvent tid (eindex s1)))\n                                    (depf s1))\n      (UECTRL : ectrl s2 = ectrl s1)\n      MOD (new_rfi : relation actid) new_val\n      (NFRMW: MOD ∩₁ dom_rel ((rmw_dep (G s2))) ⊆₁ ∅)\n      (NADDR : MOD ∩₁ dom_rel ((addr (G s2))) ⊆₁ ∅)\n      (NREX:  MOD ∩₁ (acts_set (G s2)) ∩₁ (R_ex (lab (G s2))) ⊆₁ ∅) \n      (NDATA: ⦗MOD⦘ ⨾ (data (G s2)) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂)\n      (TWF : thread_wf tid s1)\n      (RFI_INDEX : new_rfi ⊆ ext_sb)\n      (new_rfif : functional new_rfi⁻¹)\n      s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n  exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\n  generalize (@new_write new_rfi new_rfif); intro F; destruct F as [new_w F].\n  red in SIM; desc.\n  assert (SAME_LOC : RegFile.eval_lexpr (regf s1) lexpr =\n                     RegFile.eval_lexpr (regf s1') lexpr).\n  { ins; eapply regf_lexpr_helper; eauto.\n    ins; intro; eapply NADDR; unfolder; splits; eauto.\n    exists (ThreadEvent tid (eindex s1)).\n    rewrite UG; unfold add_rmw; basic_solver. } \n\n  cut (exists instrs pc G_ eindex regf depf ectrl, \n          step tid s1' (Build_state instrs pc G_ eindex regf depf ectrl) /\\ \n          (sim_state s2 (Build_state instrs pc G_ eindex regf depf ectrl)\n                     MOD new_rfi new_val)).\n  { ins; desc; eauto. }\n  do 7 eexists; splits; red; splits.\n  { eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply exchange with (val :=\n      if excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))\n      then if excluded_middle_informative ((codom_rel new_rfi) (ThreadEvent tid (eindex s1')))\n           then (get_val (val (lab (G s1')) (new_w (ThreadEvent tid (eindex s1')))))\n           else (new_val (ThreadEvent tid (eindex s1')))\n      else val_);\n    reflexivity. }\n  1,2,4,7: ins; congruence.\n  { ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG.\n    red in EXEC; desc.\n    red; splits; ins.\n    { by rewrite EINDEX, ACTS. }\n    { by rewrite TS. }\n    { rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      { subst.\n        rewrite updo; [|intros HH; clear -HH; inv HH; lia]. \n        rewrite !upds. unfold same_label_u2v.\n        rewrite updo; [|intros HH; clear -HH; inv HH; lia]. \n        rewrite upds; auto. }\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1' + 1))).\n      { subst.\n        rewrite !upds. unfold same_label_u2v; auto. }\n      ins. rewrite !updo; auto. }\n    { rewrite EINDEX.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1' + 1))).\n      { subst; rewrite SAME_LOC.\n        unfold val; rewrite !upds.\n        erewrite regf_expr_helper; try edone.\n        intro reg0; specialize (REGF reg0); desf; eauto.\n        ins; intro DEPS; eapply NDATA; unfolder; splits; eauto.\n        by rewrite EINDEX. } \n      unfold val; rewrite updo; [|done].\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))).\n      { subst; rewrite SAME_LOC.\n         rewrite !upds.\n         rewrite updo; [|intro; desf; lia].\n         rewrite !upds. desf. }\n      rewrite !updo; try done.\n      by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN. }\n    { by rewrite RMW, EINDEX. }\n    { by rewrite DATA, EINDEX, DEPF. }\n    { by rewrite ADDR, EINDEX, DEPF. }\n    { by rewrite CTRL, EINDEX, ECTRL. }\n      by rewrite FRMW, EINDEX. }\n  { ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto. }\n  { eby ins; rewrite <- DEPF, <- EINDEX. }\n  { ins; unfold acts_set, is_r, is_w in INr, INw, READ, WRITE; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'+1))); subst.\n    { by rewrite upds in READ; desf. }\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    rewrite updo in WRITE; [| intro; desf; lia].\n    { by rewrite upds in WRITE; desf. }\n\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1' + 1))); subst.\n    { exfalso.\n      apply RFI_INDEX in RF; unfold ext_sb in RF.\n      destruct INr as [[INr|INr]|INr]; subst.\n      1,2: clear -RF; lia.\n      destruct r; [eauto|]; desc.\n      apply sim_execution_same_acts in EXEC.\n      apply EXEC in INr.\n      apply TWF in INr; desc.\n      rewrite <- EINDEX in RF0.\n      inv EE. clear -RF0 LT. lia. }\n\n    assert (is_w (lab (G s1')) w) as WW'.\n    { rewrite !updo in WRITE; edone. }\n\n    unfold val.\n    rewrite updo; auto.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    { rewrite !upds.\n      destruct (excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))) as [MN|NMN].\n      2: eby exfalso.\n      rewrite !updo; auto.\n      destruct (excluded_middle_informative\n                  (codom_rel new_rfi (ThreadEvent tid (eindex s1')))) as [|XX].\n      2: { exfalso. apply XX. generalize RF. clear. basic_solver. }\n      assert (w = new_w (ThreadEvent tid (eindex s1'))); subst.\n      { edestruct new_rfi_unique with\n            (r:=ThreadEvent tid (eindex s1')) as [wu [_ HH]]; eauto.\n        transitivity wu.\n        2: by apply HH.\n        symmetry. apply HH. do 2 red. generalize RF. clear. basic_solver. }\n      unfold get_val.\n      clear -WW'. unfold is_w in WW'. desf. }\n    rewrite !updo; auto.\n    eapply NEW_VAL1; try edone.\n    { unfolder in INr; desf. }\n    { unfolder in INw; desf. }\n      by rewrite !updo in READ; try edone. }\n  simpl; ins.\n  destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'+1))); subst.\n  { by unfold is_r in READ; rewrite upds in READ; desf. }\n  unfold val; rewrite updo; [|done].\n  destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n  { rewrite upds. desf. }\n  unfold val; rewrite updo; try done.\n  apply NEW_VAL2; try done.\n  { unfold is_r in *; rewrite !updo in READ; done. }\n  unfolder in IN; desf.\nQed.\n\nLemma receptiveness_sim_step (tid : thread_id)\n  s1 s2\n  (STEP : (step tid) s1 s2) \n  (CASREX : cas_produces_R_ex_instrs (instrs s1))\n  MOD (new_rfi : relation actid) new_val\n  (NCTRL : MOD ∩₁ ectrl s2 ⊆₁ ∅)\n  (NFRMW: MOD ∩₁ dom_rel ((rmw_dep (G s2))) ⊆₁ ∅)\n  (NADDR : MOD ∩₁ dom_rel ((addr (G s2))) ⊆₁ ∅)\n  (NREX:  MOD ∩₁ (acts_set (G s2)) ∩₁ (R_ex (lab (G s2))) ⊆₁ ∅) \n  (NDATA: ⦗MOD⦘ ⨾ (data (G s2)) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂)\n  (new_rfif : functional new_rfi⁻¹)\n   (RFI_INDEX : new_rfi ⊆ ext_sb)\n  (TWF : thread_wf tid s1)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\ndestruct STEP; red in H; desf.\ndestruct ISTEP0; desf.\n- eby eapply receptiveness_sim_assign.\n- eby eapply receptiveness_sim_if_else.\n- eby eapply receptiveness_sim_if_then.\n- eby eapply receptiveness_sim_load.\n- eby eapply receptiveness_sim_store.\n- eby eapply receptiveness_sim_fence.\n- eby eapply receptiveness_sim_cas_fail.\n- eby eapply receptiveness_sim_cas_suc.\n- eby eapply receptiveness_sim_inc.\n- eby eapply receptiveness_sim_exchange. \nQed.\n\nLemma receptiveness_sim (tid : thread_id)\n  s1 s2\n  (STEPS : (step tid)＊ s1 s2)\n  (CASREX : cas_produces_R_ex_instrs (instrs s1))\n  MOD (new_rfi : relation actid) new_val\n  (NCTRL : MOD ∩₁ ectrl s2 ⊆₁ ∅)\n  (NFRMW: MOD ∩₁ dom_rel ((rmw_dep (G s2))) ⊆₁ ∅)\n  (NADDR : MOD ∩₁ dom_rel ((addr (G s2))) ⊆₁ ∅)\n  (NREX:  MOD ∩₁ (acts_set (G s2)) ∩₁ (R_ex (lab (G s2))) ⊆₁ ∅) \n  (NDATA: ⦗MOD⦘ ⨾ (data (G s2)) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂)\n  (new_rfif : functional new_rfi⁻¹)\n   (RFI_INDEX : new_rfi ⊆ ext_sb)\n  (TWF : thread_wf tid s1)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid)＊ s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\n  apply clos_rt_rtn1 in STEPS.\n  induction STEPS.\n  { by eexists; vauto. }\n  exploit IHSTEPS.\n  { unfolder; splits; ins; eauto; desf.\n    eapply ectrl_increasing in H1; eauto.\n    eapply NCTRL; basic_solver. }\n  { unfolder; splits; ins; eauto; desf.\n    eapply rmw_dep_increasing in H1; eauto.\n    eapply NFRMW; basic_solver. }\n  { unfolder; splits; ins; eauto; desf.\n    eapply addr_increasing in H1; eauto.\n    eapply NADDR; basic_solver. }\n  { unfolder; splits; ins; eauto; desf. \n    eapply NREX; split; [split; [eauto |] |].\n    eapply acts_increasing; edone.\n    eapply is_r_ex_increasing; eauto.\n    eapply thread_wf_steps; try edone. \n    { by apply clos_rtn1_rt. }\n    basic_solver. }\n  { unfolder; splits; ins; eauto; desf.\n    eapply data_increasing in H1; eauto.\n    eapply NDATA; basic_solver. }\n  intro; desc.\n  eapply receptiveness_sim_step in x0; eauto; desf.\n  { exists s2'0; splits; eauto. \n      by eapply rt_trans; [eauto | econs]. }\n  { arewrite (instrs y = instrs s1); auto.\n    apply clos_rtn1_rt in STEPS.\n    eapply steps_preserve_instrs; eauto. }\n  eapply thread_wf_steps; try edone.\n    by apply clos_rtn1_rt.\nQed.\n\nLemma receptiveness_helper (tid : thread_id)\n      s_init s\n      (CASREX : cas_produces_R_ex_instrs (instrs s_init))\n      (GPC : wf_thread_state tid s_init)\n      (new_val : actid -> value)\n      (new_rfi : relation actid)\n      (MOD: actid -> Prop)\n      (STEPS : (step tid)＊ s_init s)\n      (new_rfiE : new_rfi ≡ ⦗(acts_set (G s))⦘ ⨾ new_rfi ⨾ ⦗(acts_set (G s))⦘)\n      (new_rfiD : new_rfi ≡ ⦗is_w (lab (G s))⦘ ⨾ new_rfi ⨾ ⦗is_r (lab (G s))⦘)\n      (new_rfif : functional new_rfi⁻¹)\n      (RFI_INDEX : new_rfi ⊆ ext_sb)\n      (NCTRL : MOD ∩₁ ectrl s ⊆₁ ∅) \n      (NFRMW: MOD ∩₁ dom_rel ((rmw_dep (G s))) ⊆₁ ∅)\n      (NADDR : MOD ∩₁ dom_rel ((addr (G s))) ⊆₁ ∅)\n      (NREX:  MOD ∩₁ (acts_set (G s)) ∩₁ (R_ex (lab (G s))) ⊆₁ ∅) \n      (NDATA: ⦗MOD⦘ ⨾ (data (G s)) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂) \n      (new_rfiMOD : codom_rel new_rfi ⊆₁ MOD)\n      (NMODINIT: MOD ∩₁ (acts_set (ProgToExecution.G s_init)) ⊆₁ ∅)\n      (EMOD : MOD ⊆₁ (acts_set (ProgToExecution.G s))) :\n    exists s',\n      ⟪ STEPS' : (step tid)＊ s_init s' ⟫ /\\\n      ⟪ EXEC : sim_execution (G s) (G s') MOD ⟫ /\\\n      ⟪ NEW_VAL1 : forall r w (RF: new_rfi w r), val ((lab (G s'))) r = val ((lab (G s'))) w ⟫ /\\\n      ⟪ NEW_VAL2 : forall r (RR : is_r (lab (G s')) r) (IN: MOD r) (NIN: ~ (codom_rel new_rfi) r),\n          val ((lab (G s'))) r = Some (new_val r) ⟫ /\\\n      ⟪ OLD_VAL : forall a (NIN: ~ MOD a), val ((lab (G s'))) a = val ((lab (G s))) a ⟫.\nProof using.\napply receptiveness_sim with (s1':= s_init) (MOD:=MOD) (new_rfi:=new_rfi) (new_val:=new_val) in STEPS.\nall: try done.\n- desc.\n  red in STEPS0; desc.\n  exists s2'; splits; eauto.\n  * ins; eapply NEW_VAL1; try done.\n    + hahn_rewrite new_rfiE in RF; unfolder in RF; desf.\n      apply sim_execution_same_acts in EXEC.\n      revert EXEC; basic_solver.\n    + hahn_rewrite new_rfiE in RF; unfolder in RF; desf.\n      apply sim_execution_same_acts in EXEC.\n      revert EXEC; basic_solver.\n    + hahn_rewrite new_rfiD in RF; unfolder in RF; desf.\n      apply sim_execution_same_r in EXEC.\n      revert EXEC; basic_solver.\n    + hahn_rewrite new_rfiD in RF; unfolder in RF; desf.\n      apply sim_execution_same_w in EXEC.\n      revert EXEC; basic_solver.\n    + revert new_rfiMOD; basic_solver.\n  * ins; eapply NEW_VAL2; try done.\n    apply sim_execution_same_acts in EXEC.\n    revert EXEC; basic_solver.\n  * ins; red in EXEC; desc.\n    by eapply OLD_VAL.\n- red; apply (acts_rep GPC).\n- red; splits; eauto.\n  { red; splits; eauto; red; red; ins; red; eauto; desf. }\n  ins; exfalso; revert NMODINIT; basic_solver.\n  ins; exfalso; unfolder in *; basic_solver.\nQed.\n\nLemma receptiveness_ectrl_helper (tid : thread_id) \n      s_init s \n      (GPC : wf_thread_state tid s_init)\n      (STEPS : (step tid)＊ s_init s)\n      MOD (NCTRL: MOD ∩₁ dom_rel ((ctrl (G s))) ⊆₁ ∅) \n      (NMODINIT: MOD ∩₁ (acts_set (G s_init)) ⊆₁ ∅):\n      exists s', (step tid)＊ s_init s' /\\\n                 (MOD ∩₁ ectrl s' ⊆₁ ∅) /\\ (G s') = (G s).\nProof using.\napply clos_rt_rtn1 in STEPS.\ninduction STEPS.\n- exists s_init; splits; vauto.\n  by rewrite (wft_ectrlE GPC).\n- assert (A: MOD ∩₁ dom_rel (ctrl (G y)) ⊆₁ ∅).\n  generalize (ctrl_increasing H).\n  revert NCTRL; basic_solver 12.\n  apply IHSTEPS in A.\n  desc.\n  destruct  (classic (MOD ∩₁ ectrl z ⊆₁ ∅)).\n  * exists z; splits; eauto.\n    eapply rt_trans.\n    eby apply clos_rtn1_rt.\n    by apply rt_step.\n  * exists s'; splits; eauto.\n    transitivity (G y); [done|].\n    eapply ectrl_ctrl_step; try edone.\n    destruct (classic (exists a : actid, (MOD ∩₁ ectrl z) a)); auto.\n    exfalso; apply H0; unfolder; ins; eapply H1; basic_solver.\nQed.\n\nLemma receptiveness_full (tid : thread_id)\n      s_init s\n      (new_val : actid -> value)\n      (new_rfi : relation actid)\n      (MOD: actid -> Prop)\n      (GPC : wf_thread_state tid s_init)\n      (CASREX : cas_produces_R_ex_instrs (instrs s_init))\n      (STEPS : (step tid)＊ s_init s)\n      (new_rfiE : new_rfi ≡ ⦗(acts_set (G s))⦘ ⨾ new_rfi ⨾ ⦗(acts_set (G s))⦘)\n      (new_rfiD : new_rfi ≡ ⦗is_w (lab (G s))⦘ ⨾ new_rfi ⨾ ⦗is_r (lab (G s))⦘)\n      (new_rfif : functional new_rfi⁻¹)\n      (RFI_INDEX : new_rfi ⊆ ext_sb)\n      (new_rfiMOD : codom_rel new_rfi ⊆₁ MOD)\n      (EMOD : MOD ⊆₁ (acts_set (ProgToExecution.G s)))\n      (NMODINIT: MOD ∩₁ (acts_set (ProgToExecution.G s_init)) ⊆₁ ∅)\n      (NFRMW: MOD ∩₁ dom_rel ((rmw_dep (G s))) ⊆₁ ∅)\n      (NADDR : MOD ∩₁ dom_rel ((addr (G s))) ⊆₁ ∅)\n      (NREX:  MOD ∩₁ (acts_set (G s)) ∩₁(R_ex (lab (G s))) ⊆₁ ∅) \n      (NCTRL: MOD ∩₁ dom_rel ((ctrl (G s))) ⊆₁ ∅)\n      (NDATA: ⦗MOD⦘ ⨾ (data (G s)) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂) :\n    exists s',\n      ⟪ STEPS' : (step tid)＊ s_init s' ⟫ /\\\n      ⟪ RACTS : (acts_set (G s)) = (acts_set (G s')) ⟫ /\\\n      ⟪ RTS: threads_set (G s) ≡₁ threads_set (G s')⟫ /\\\n      ⟪ RRMW  : (rmw (G s))  ≡ (rmw (G s'))  ⟫ /\\\n      ⟪ RDATA : (data (G s)) ≡ (data (G s')) ⟫ /\\\n      ⟪ RADDR : (addr (G s)) ≡ (addr (G s')) ⟫ /\\\n      ⟪ RCTRL : (ctrl (G s)) ≡ (ctrl (G s')) ⟫  /\\\n      ⟪ RFAILRMW : (rmw_dep (G s)) ≡ (rmw_dep (G s')) ⟫  /\\\n      ⟪ SAME : same_lab_u2v ((lab (G s'))) ((lab (G s)))⟫ /\\\n      ⟪ NEW_VAL1 : forall r w (RF: new_rfi w r), val ((lab (G s'))) r = val ((lab (G s'))) w ⟫ /\\\n      ⟪ NEW_VAL2 : forall r (RR : is_r (lab (G s')) r) (IN: MOD r) (NIN: ~ (codom_rel new_rfi) r),\n          val ((lab (G s'))) r = Some (new_val r) ⟫ /\\\n      ⟪ OLD_VAL : forall a (NIN: ~ MOD a), val ((lab (G s'))) a = val ((lab (G s))) a ⟫.\nProof using.\nforward (apply receptiveness_ectrl_helper); try edone.\n\nins; desc.\nrewrite <- H1 in *.\nclear STEPS H1 s.\nforward (eapply receptiveness_helper with (new_rfi:=new_rfi)); ins; eauto.\ndesc.\nred in EXEC; desc.\neexists; splits; eauto.\nQed.\n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/basic/Receptiveness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.2413690888081073}}
{"text": "Theorem Euclides : ∀ a b  : Z, b > 0 -> ∃ r q  : Z, (a=b*q + r) ∧ (0 < r ∨ 0=r)  ∧ r< b .\nProof.\nintros.\nset (S := {  l  : Z | ∃ q : Z, l=a - b*q +1 ∧ l>0 }).\npose proof ( W1 S).\nassert (S≠ ∅).\n{\ncase (classic (a > 0)).\ncase (classic (S = ∅)).\nintros.\nassert ( a +1 ∈ S ).\n{\nunfold In.\nunfold S.\nexists 0.\nrewrite M1.\nrewrite A1P6 .\nrewrite G .\nrewrite PORRA.\nrewrite A3.\npose proof (R3 0 a (a+1)).\ncase (classic (0 < a+1)).\nintros.\ntauto.\npose proof H2 as H1945.\nintros.\npose proof (I778 ).\napply (O1 0 1 a) in H5.\nrewrite A1P1 in H5.\nrewrite A1 in H5.\ntauto. }\nrewrite H1 in H3.\ncontradiction.\nintros.\nexact H1.\nintros.\ndestruct (T a) as [[H3 [H4 H5]] | [[H3 [H4 H5]] | [H3 [H4 H5]]]].\ntauto.\nassert (1 ∈ S).\nunfold S, In.\nexists 0.\nrewrite M1, A1P6 .\n\nrewrite G, PORRA, A3.\nrewrite H4, A1P1.\npose proof I778.\ntauto.\ncase (classic (S = ∅)).\nintros.\nrewrite H6 in H2.\ncontradiction.\nintros.\ntauto.\ncase (classic (S = ∅)).\nintros.\nassert (((-a)*b + a + 1) ∈ S) .\nunfold S, In.\nexists a.\nsplit. \nrewrite G.\nrewrite (A1 a (- (b * a) )).\nrewrite (M1 b a), <-A1P7.\nrewrite <-(A1P7 (a*b)).\nrewrite M2.\ntauto.\napply Davi in H.\ndestruct H.\nrewrite H.\nrewrite M3, A1P2.\nrewrite A1P1.\npose proof I778.\ntauto.\npose proof H as H8.\npose proof (O2 1 b (-a) ).\napply H6 in H.\nrewrite M1, M3 in H.\nrewrite M1 in H.\npose proof (R3 (-a) ((-a)*b) (((-a)*b) + a +1)).\nrewrite <-A1P7 .\nrewrite M2.\nrewrite (M1 a b).\nrewrite <-M2.\nrewrite <-(M3 a) at 2.\nrewrite (M1 a 1).\nrewrite M1, <-M2.\nrewrite NOW.\nrewrite A1P3.\nrewrite <-(A1P5 a) at 2.\nrewrite <-NOW at 2.\nrewrite <-(NOW (a * (-1))).\nrewrite NOW.\nrewrite (M1 a (-1)).\nrewrite <-(A1P7 ((-1) * a) ) .\nrewrite (A1P7 a) .\nrewrite M1 at 1.\nrewrite <-D1.\nrewrite <-G.\napply (O1 1 b (-1)) in H8.\nrewrite A4 in H8.\nrewrite <-G in H8.\npose proof (O2 0 (b-1) (-a)).\napply H9 in H8.\nrewrite A1P6 in H8.\npose proof (R3 0  ((b - 1) * (- a))  ((b - 1) * (- a) + 1)).\npose proof (I778).\napply (O1 0 1 ((b - 1) * (- a))) in H11.\nrewrite A1 in H11.\nrewrite A3 in H11.\nrewrite A1 in H11.\ntauto.\napply I3 in H5.\nrewrite PORRA in H5.\nexact H5.\napply I3 in H5.\nrewrite PORRA in H5.\nexact H5.\nrewrite H2 in H6.\nunfold In in H6.\ntauto.\ntauto.   }\napply H0 in H1.\ndestruct H1.\npose proof I778 as H2.\ndestruct H1.\npose proof H1 as H67.\nunfold S in H1.\nunfold In in H1.\ndestruct H1.\ndestruct H1.\n\ncase (classic ( x<b+1 )).\nintros.\nexists (x-1).\nexists x0.\napply (S1 x (a- (b*x0)+1) (b*x0)) in H1.\nrewrite M1 in H1.\nrewrite G in H1.\nrewrite A2 in H1.\nrewrite A2 in H1.\nrewrite (A1 (-(x0 * b)) (1 +  (x0*b))) in H1.\nrewrite A2 in H1.\nrewrite A4 in H1.\nrewrite A3 in H1.\napply (S1 (x+ (x0*b) ) (a+1) (-1)) in H1.\nrewrite A1 in H1.\nrewrite (A2 a 1 (-1)) in H1.\nrewrite A4 in H1.\nrewrite A3 in H1.\nsymmetry in H1.\nrewrite <-A2 in H1.\nrewrite M1 in H1.\nrewrite (A1 (-1) x) in H1.\nrewrite A1 in H1.\nrewrite <-G in H1.\nsplit.\ntauto.\nsplit.\nunfold S in H67.\nunfold In in H67.\ndestruct H67.\ndestruct H6.\n\napply (O1 0 (x) (-1)) in H7.\n\nrewrite A1P1 in H7.\nrewrite <-G in H7.\npose proof (Sena2 (-1) (x-1)).\ndestruct H8.\nexact H7.\nright.\napply (O1 (-1) (x-1) 1)in H7.\nrewrite A1P2 in H7.\nrewrite G in H7. \nrewrite A2 in H7.\nrewrite A1P2 in H7.\nrewrite A3 in H7.\napply (S1 (-1) (x-1-1) 1) in H8.\nrewrite A1P2 in H8.\nrewrite G in H8.\nrewrite A2 in H8.\nrewrite A1P2 in H8.\nrewrite A3 in H8.\ntauto.\napply Sena in H7.\ndestruct H7.\nrewrite A1P2 in H7.\nsymmetry in H7.\ntauto.\nrewrite A1P2 in H7 .\ntauto.\napply ( O1 (x) (b+1) (-1)) in H5.\nrewrite A2 in H5.\nrewrite A4 in H5.\nrewrite A3 in H5.\nrewrite <-G in H5.\ntauto.  \nintros.\ncase (classic (x=b)).\nintros.\nexists (x-1).\nexists x0.\nauto.\napply (S1 x ( a - (b*x0) + 1) ( (b*x0) + (- 1))) in H1.\nrewrite A2 in H1.\nrewrite (A1 (b*x0) (-1) ) in H1.\nrewrite <-( A2 1 (-1) (b*x0)) in H1.\nrewrite A4 in H1.\nrewrite A1P1 in H1.\nrewrite G in H1.\nrewrite A2 in H1.\nrewrite A1P2 in H1.\nrewrite A3 in H1.\nrewrite A1 in H1.\nrewrite (A1 (-1) (b*x0)) in H1.\nrewrite A2 in H1.\nrewrite (A1 (-1) (x)) in H1.\nsplit.\nsymmetry in H1.\ntauto.\nsplit.\napply Sena2 in H4.\ntauto.\nrewrite H6.\npose  proof (I778).\napply (O1 0 1 (b-1)) in H7.\nrewrite A1P1 in H7.\n\nrewrite G in H7.\nrewrite A1 in H7 at 2.\nrewrite <-A2 in H7.\nrewrite A4 in H7.\nrewrite <-G in H7.\nrewrite A1P1 in H7.\ntauto.\nintros.\n destruct (Y x b) as [[H7 [H8 H9]] | [[H7 [H8 H9]] | [H7 [H8 H9]]]].\napply Sena2 in H7.\ndestruct H7.\nassert ( (x-b) ∈ S ).\nunfold In.\nunfold S.\nexists (x0 +1).\nsplit.\nrewrite G.\napply (S1 x  (a -( b * x0) + 1) (-b)) in H1.\nrewrite <-G in H1.\nrewrite (G a (b*x0)) in H1.\nrewrite A2 in H1.\nrewrite (A1 1 (-b)) in H1.\nrewrite <-A2 in H1.\nrewrite <-(A1P7 b) in H1.\nrewrite M1 in H1.\nrewrite (M1 (-1) b) in H1.\nrewrite <-NOW in H1.\nrewrite M2 in H1.\nrewrite <-M2 in H1.\nrewrite A1 in H1.\nrewrite A2 in H1.\n\nrewrite <-(D1 (x0*b) b (-1)) in H1.\nrewrite NOW in H1.\nrewrite <-(A1P3 b) in H1 at 3.\nrewrite <-D1 in H1.\nrewrite M1 in H1.\nrewrite A1 in H1.\ntauto.\napply (S1 b (x - 1) (-b +1)) in H7.\nrewrite G in H7.\nrewrite <-A2 in H7.\nrewrite A4 in H7.\nrewrite A1P1 in H7.\nrewrite A2 in H7.\nrewrite A1 in H7.\nrewrite (A1 (-b) 1) in H7.\nrewrite <-(A2 (-1) 1  (- b)) in H7.\nrewrite A1P2 in H7.\nrewrite A1P1 in H7.\nrewrite A1 in H7.\nrewrite <-G in H7.\nrewrite <-H7.\npose proof I778.\n\ntauto.\napply H3 in H10.\ndestruct H10.\napply (O1 x (x-b) (-x)) in H10.\nrewrite A4 in H10.\nrewrite A1 in H10.\nrewrite G in H10.\nrewrite <-A2 in H10.\nrewrite A1P2 in H10.\nrewrite A1P1 in H10.\napply I3 in H10.\nrewrite A1P5 in H10.\nrewrite PORRA in H10.\napply I7 in H10.\ntauto.\napply (S1 x (x-b) (-x)) in H10.\nrewrite A4 in H10.\nrewrite A1 in H10.\nrewrite G in H10.\nrewrite <-A2 in H10.\nrewrite A1P2 in H10.\nrewrite A1P1 in H10.\napply (S2 0 (-b) (-1)) in H10.\nrewrite A1P6 in H10.\nrewrite NOW in H10.\nrewrite A1P5 in H10.\npose proof (I8 b).\napply I9 in H10.\ntauto.\nassert ( (x-b) ∈ S ).\nunfold In.\nunfold S.\nexists (x0 +1).\nsplit.\nrewrite G.\napply (S1 x  (a -( b * x0) + 1) (-b)) in H1.\nrewrite <-G in H1.\nrewrite (G a (b*x0)) in H1.\nrewrite A2 in H1.\nrewrite (A1 1 (-b)) in H1.\nrewrite <-A2 in H1.\nrewrite <-(A1P7 b) in H1.\nrewrite M1 in H1.\nrewrite (M1 (-1) b) in H1.\nrewrite <-NOW in H1.\nrewrite M2 in H1.\nrewrite <-M2 in H1.\nrewrite A1 in H1.\nrewrite A2 in H1.\n\nrewrite <-(D1 (x0*b) b (-1)) in H1.\nrewrite NOW in H1.\nrewrite <-(A1P3 b) in H1 at 3.\nrewrite <-D1 in H1.\nrewrite M1 in H1.\nrewrite A1 in H1.\ntauto.\napply (O1 b (x - 1) (-b +1)) in H7.\nrewrite G in H7.\nrewrite <-A2 in H7.\nrewrite A4 in H7.\nrewrite A1P1 in H7.\nrewrite A2 in H7.\nrewrite A1 in H7.\nrewrite (A1 (-b) 1) in H7.\nrewrite <-(A2 (-1) 1  (- b)) in H7.\nrewrite A1P2 in H7.\nrewrite A1P1 in H7.\nrewrite A1 in H7.\nrewrite <-G in H7.\npose proof I778.\npose proof (R3 0 1 (x-b)).\npose proof (conj H10 H7).\napply H11 in H12.\nexact H12.\napply H3 in H10.\ndestruct H10.\napply (O1 x (x-b) (-x)) in H10.\nrewrite A4 in H10.\nrewrite A1 in H10.\nrewrite G in H10.\nrewrite <-A2 in H10.\nrewrite A1P2 in H10.\nrewrite A1P1 in H10.\napply I3 in H10.\nrewrite A1P5 in H10.\nrewrite PORRA in H10.\napply I7 in H10.\ntauto.\napply (S1 x (x-b) (-x)) in H10.\nrewrite A4 in H10.\nrewrite A1 in H10.\nrewrite G in H10.\nrewrite <-A2 in H10.\nrewrite A1P2 in H10.\nrewrite A1P1 in H10.\napply (S2 0 (-b) (-1)) in H10.\nrewrite A1P6 in H10.\nrewrite NOW in H10.\nrewrite A1P5 in H10.\npose proof (I8 b).\napply I9 in H10.\ntauto.\ntauto.\npose proof (Sena x 0).\nexists (x-1).\nexists x0.\napply (S1 x (a - (b * x0) + 1) ((b * x0) - 1)) in H1.\nrewrite (G a (b*x0)) in H1.\nrewrite A2  in H1.\nrewrite (G (b*x0) (1)) in H1.\nrewrite (A1 (b * x0) (- 1)) in H1.\nrewrite <-(A2 1 (-1) (b*x0)) in H1.\nrewrite A4 in H1.\nrewrite A1P1 in H1.\nrewrite A2 in H1.\nrewrite A1P2 in H1.\nrewrite A3 in H1.\nrewrite <-A2 in H1.\nrewrite A1 in H1.\nsymmetry in H1.\nsplit.\ntauto.\nsplit.\napply H10 in H4.\nrewrite A1P1 in H4.\ndestruct H4.\napply (S1 x 1 (-1)) in H4.\nrewrite <-G in H4.\nrewrite A4 in H4.\nsymmetry in H4.\ntauto.\napply (O1 1 x (-1)) in H4.\nrewrite A4 in H4.\nrewrite <-G in H4.\ntauto.\npose proof (R3 (x-1) x b).\npose proof I778.\napply I3 in H12.\nrewrite PORRA in H12.\napply (O1 (-1) 0 x) in H12.\nrewrite A1P1 in H12.\nrewrite A1 in H12.\nrewrite <-G in H12.\ntauto.\nunfold Included.\nunfold S.\nunfold In at 1.\nintros.\ndestruct H2.\ndestruct H2.\n\napply lt_N_elt.\ntauto.\nQed.\n", "meta": {"author": "dgwarlug47", "repo": "Coq-Elementary-Number-Theory", "sha": "d2482f9bbfe1ff3ad06590d965c6c61fc2ac9666", "save_path": "github-repos/coq/dgwarlug47-Coq-Elementary-Number-Theory", "path": "github-repos/coq/dgwarlug47-Coq-Elementary-Number-Theory/Coq-Elementary-Number-Theory-d2482f9bbfe1ff3ad06590d965c6c61fc2ac9666/euclides.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.24130592957813504}}
{"text": "From iris.base_logic Require Export invariants.\nFrom iris.algebra Require Import agree frac.\nFrom iris.proofmode Require Import tactics.\nFrom fae_gtlc_mu.stlc_mu Require Export lang.\nImport uPred.\n\n(* Name for invariant that supervises the static side *)\nDefinition specN := nroot .@ \"gradual\".\n\n(* Iris resources for keeping track of static side *)\nCanonical Structure exprO := leibnizO expr.\n\nDefinition specR := prodR fracR (agreeR exprO).\n\nClass specG Σ := SpecG { specR_inG :> inG Σ specR; spec_name : gname }.\n\nDefinition currently `{specG Σ} (e : expr) : iProp Σ :=\n  own spec_name ((1%Qp , to_agree e) : specR).\n\nDefinition currently_half `{specG Σ} (e : expr) : iProp Σ :=\n  own spec_name (((1 / 2)%Qp , to_agree e) : specR).\n\n(* Invariant body to keep track of static side *)\nDefinition initially_body `{specG Σ} (ei' : expr) : iProp Σ :=\n  (∃ e', (currently_half e')\n            ∗ ⌜rtc erased_step ([ei'] , tt) ([e'] , tt)⌝)%I.\n\n(* Invariant to keep track of static side *)\nDefinition initially_inv `{specG Σ} `{invG Σ} (ei' : expr) : iProp Σ :=\n  inv specN (initially_body ei').\n\nSection cfg.\n  Context `{!specG Σ}.\n  Context `{!invG Σ}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types Φ : val → iProp Σ.\n  Implicit Types e : expr.\n  Implicit Types v : val.\n\n  Local Hint Resolve to_of_val : core.\n\n  (* uninteresting technical lemma *)\n  Lemma step_insert_no_fork K e σ e' σ' :\n    head_step e σ [] e' σ' [] → erased_step ([fill K e], σ) ([fill K e'], σ').\n  Proof. intros Hst. exists []. eapply (step_atomic _ _ _ _ _ _ _ [] [] []); eauto.\n         by apply: Ectx_step.\n  Qed.\n\n  (* Updating the static side with a head step under an evaluation context *)\n  Lemma step_pure E ei' K e1' e2' σ :\n    (head_step e1' σ [] e2' σ []) →\n    nclose specN ⊆ E →\n    initially_inv ei' ∗ currently_half (fill K e1') ={E}=∗ currently_half (fill K e2').\n  Proof.\n    iIntros (??) \"[Hinv Hj]\".\n    rewrite /initially_inv /initially_body.\n    iInv specN as \">Hinit\" \"Hclose\".\n    iDestruct \"Hinit\" as (ef') \"[Hown %]\".\n    (** fill K e1' = ef' *)\n    rewrite /currently_half.\n    iDestruct (own_valid_2 with \"Hown Hj\") as \"#eee\".\n    rewrite -pair_op frac_op' Qp_half_half.\n    iDestruct \"eee\" as %[_ ->%agree_op_inv'%leibniz_equiv]%pair_valid.\n    (** update *)\n    (* bring together *)\n    iDestruct (equiv_entails_sym _ _ (own_op _ _ _) with \"[Hj Hown]\") as \"HOwnOne\".\n    iFrame.\n    (* actually update *)\n    rewrite -pair_op frac_op' Qp_half_half.\n    iMod (own_update _ _ (1%Qp, to_agree (fill K e2')) with \"HOwnOne\") as \"HOwnOne\".\n    rewrite agree_idemp.\n    { apply cmra_update_exclusive. done. }\n    rewrite -Qp_half_half -frac_op' -(agree_idemp (to_agree (fill K e2'))).\n    iDestruct \"HOwnOne\" as \"[Hown1 Hown2]\".\n    rewrite frac_op' Qp_half_half (agree_idemp (to_agree (fill K e2'))).\n    (** close invariant *)\n    iApply fupd_wand_r. iSplitL \"Hclose Hown1\". iApply (\"Hclose\" with \"[Hown1]\").\n    iNext. iExists (fill K e2'). iFrame.\n    iPureIntro.\n    eapply rtc_r, step_insert_no_fork; eauto.\n    destruct σ. by simpl in H. iFrame \"Hown2\". done.\n  Qed.\n\n  (* uninteresting technical lemmas *)\n  Lemma nsteps_pure_step_ctx n e1' e2' K :\n    nsteps pure_step n e1' e2' → nsteps pure_step n (fill K e1') (fill K e2').\n  Proof.\n    revert e2'. revert e1'.\n    induction n.\n    - intros e1 e2 H. inversion H. simplify_eq. constructor.\n    - intros e1 e2 H. inversion H. econstructor.\n      apply (pure_step_ctx (fill K)).\n      apply H1. by apply IHn.\n  Qed.\n\n  Lemma pure_step_prim_step e e' : pure_step e e' → prim_step e tt [] e' tt [].\n    intro Pstp. destruct Pstp. destruct (pure_step_safe tt).\n    destruct H as [σ [ls Hprim]]. destruct σ.\n    by destruct (pure_step_det tt [] x tt ls Hprim) as [_ [ _ [-> ->]]].\n  Qed.\n\n  Lemma pure_step_erased_step e e' : pure_step e e' → erased_step ([e], ()) ([e'],()).\n  Proof. intros Pst. exists []. eapply (step_atomic _ _ _ _ _ _ _ [] [] []); eauto. by apply pure_step_prim_step. Qed.\n\n  Lemma nsteps_pure_step_prim_step n e e' : nsteps pure_step n e e' → nsteps erased_step n ([e], ()) ([e'], ()).\n  Proof.\n    intros.\n    cut (nsteps erased_step n ((fun e => ([e], ())) e) ((fun e => ([e], ())) e')). by simpl.\n    eapply nsteps_congruence; eauto.\n    intros. by apply pure_step_erased_step.\n  Qed.\n\n  (* Update static side with arbitrary amount of steps under an evaluation context *)\n  Lemma steps_pure E ei' K e1' e2' n :\n    (nsteps pure_step n e1' e2') →\n    nclose specN ⊆ E →\n    initially_inv ei' ∗ currently_half (fill K e1') ={E}=∗ currently_half (fill K e2').\n  Proof.\n    iIntros (??) \"[Hinv Hj]\".\n    rewrite /initially_inv /initially_body.\n    iInv specN as \">Hinit\" \"Hclose\".\n    iDestruct \"Hinit\" as (ef') \"[Hown %]\".\n    (** fill K e1' = ef' *)\n    rewrite /currently_half.\n    iDestruct (own_valid_2 with \"Hown Hj\") as \"#eee\".\n    rewrite -pair_op frac_op' Qp_half_half.\n    iDestruct \"eee\" as %[_ ->%agree_op_inv'%leibniz_equiv]%pair_valid.\n    (** update *)\n    (* bring together *)\n    iDestruct (equiv_entails_sym _ _ (own_op _ _ _) with \"[Hj Hown]\") as \"HOwnOne\".\n    iFrame.\n    (* actually update *)\n    rewrite -pair_op frac_op' Qp_half_half.\n    iMod (own_update _ _ (1%Qp, to_agree (fill K e2')) with \"HOwnOne\") as \"HOwnOne\".\n    rewrite agree_idemp.\n    { apply cmra_update_exclusive. done. }\n    rewrite -Qp_half_half -frac_op' -(agree_idemp (to_agree (fill K e2'))).\n    iDestruct \"HOwnOne\" as \"[Hown1 Hown2]\".\n    rewrite frac_op' Qp_half_half (agree_idemp (to_agree (fill K e2'))).\n    (** close invariant *)\n    iApply fupd_wand_r. iSplitL \"Hclose Hown1\". iApply (\"Hclose\" with \"[Hown1]\").\n    iNext. iExists (fill K e2'). iFrame.\n    iPureIntro. eapply rtc_transitive. apply H1.\n    apply (nsteps_rtc n).\n    apply nsteps_pure_step_prim_step. by apply nsteps_pure_step_ctx.\n    iFrame \"Hown2\". done.\n  Qed.\n\n  (* Different instantiations of step_pure *)\n  Lemma step_fst E ei' K e1' e2' :\n    AsVal e1' → AsVal e2' →\n    nclose specN ⊆ E →\n    initially_inv ei' ∗ currently_half (fill K (Fst (Pair e1' e2'))) ={E}=∗ currently_half (fill K e1').\n  Proof. intros [? <-] [? <-]. apply step_pure with (σ := tt); econstructor; eauto. Qed.\n\n  Lemma step_snd E ei' K e1' e2' :\n    AsVal e1' → AsVal e2' → nclose specN ⊆ E →\n    initially_inv ei' ∗ currently_half (fill K (Snd (Pair e1' e2'))) ={E}=∗ currently_half (fill K e2').\n  Proof. intros [? <-] [? <-]. apply step_pure with (σ := tt); econstructor; eauto. Qed.\n\n  Lemma step_lam E ei' K e1' e2' :\n    AsVal e2' → nclose specN ⊆ E →\n    initially_inv ei' ∗ currently_half (fill K (App (Lam e1') e2'))\n    ={E}=∗ currently_half (fill K (e1'.[e2'/])).\n  Proof. intros [? <-]; apply step_pure with (σ := tt); econstructor; eauto. Qed.\n\n  Lemma step_Fold E ei' K e' :\n    AsVal e' → nclose specN ⊆ E →\n    initially_inv ei' ∗ currently_half (fill K (Unfold (Fold e'))) ={E}=∗ currently_half (fill K e').\n  Proof. intros [? <-]; apply step_pure with (σ := tt); econstructor; eauto. Qed.\n\n  Lemma step_case_inl E ei' K e0' e1' e2' :\n    AsVal e0' → nclose specN ⊆ E →\n    initially_inv ei' ∗ currently_half (fill K (Case (InjL e0') e1' e2'))\n      ={E}=∗ currently_half (fill K (e1'.[e0'/])).\n  Proof. intros [? <-]; apply step_pure with (σ := tt); econstructor; eauto. Qed.\n\n  Lemma step_case_inr E ei' K e0' e1' e2' :\n    AsVal e0' → nclose specN ⊆ E →\n    initially_inv ei' ∗ currently_half (fill K (Case (InjR e0') e1' e2'))\n      ={E}=∗ currently_half (fill K (e2'.[e0'/])).\n  Proof. intros [? <-]; apply step_pure with (σ := tt); econstructor; eauto. Qed.\n\nEnd cfg.\n", "meta": {"author": "scaup", "repo": "fae-gtlc-mu", "sha": "6c6e64f0844327d55059b97c7aefab023385973e", "save_path": "github-repos/coq/scaup-fae-gtlc-mu", "path": "github-repos/coq/scaup-fae-gtlc-mu/fae-gtlc-mu-6c6e64f0844327d55059b97c7aefab023385973e/theories/refinements/gradual_static/resources_right.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24130592333619966}}
{"text": "Variables S1 S2 : Set.\n\nGoal @eq Type S1 S2 -> @eq Type S1 S2.\nintro H.\nFail tauto.\nassumption.\nQed.\n\n(*This is in 8.5pl1, and Matthieq Sozeau says: \"That's a regression in tauto indeed, which now requires exact equality of the universes, through a non linear goal pattern matching:\nmatch goal with ?X1 |- ?X1 forces both instances of X1 to be convertible,\nwith no additional universe constraints currently, but the two types are\ninitially different. This can be fixed easily to allow the same flexibility\nas in 8.4 (or assumption) to unify the universes as well.\"*)\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/opened/4721.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24130556349315269}}
{"text": "(* \n This is the definition of formal syntax for Dan Grossman's Thesis, \n  \"SAFE PROGRAMMING AT THE C LEVEL OF ABSTRACTION\". \n\n  Defining type safety, page 67.\n\n*)\n\nSet Implicit Arguments.\nSet Implicit Arguments.\nRequire Export Cyclone_Formal_Syntax Cyclone_Static_Semantics_Kinding_And_Context_Well_Formedness.\nRequire Export Cyclone_Static_Semantics_Typing_Heap_Objects.\nRequire Export Cyclone_Classes Cyclone_Inductions.\nRequire Export Cyclone_LN_Tactics Cyclone_LN_Extra_Lemmas_And_Automation.\nClose Scope list_scope.\nImport LibEnvNotations.\nImport LVPE.LibVarPathEnvNotations.\n\nLemma A_2_Term_Weakening_1 :\n  forall (d: Delta) (u u' : Upsilon) (g g' : Gamma)\n         (x : var) (p p' : Path) (tau tau' : Tau),\n    LVPE.extends u u' ->\n    extends g g' ->\n    WFC d u g -> \n    WFC d u' g' ->\n    gettype u  x p tau p' tau' ->\n    gettype u' x p tau p' tau'.\nProof.\n  intros.\n  induction H3; auto.\n  apply gettype_etype with (tau'':= tau''); auto.\nQed.\n\nFunction A_2_Term_Weakening_prop (In : Type) (H : TypJudgement In) \n         (d : Delta) (u : Upsilon) (g : Gamma) (s : In) (t : Tau)\n         (st : typ' d u g s t) := \n    typ' d u g s t ->\n    WFC d u g -> \n      forall (u' : Upsilon) (g' : Gamma),\n        WFC d u' g' ->\n        LVPE.extends u u' ->\n        extends g g' ->\n        typ' d u' g' s t.\nHint Unfold A_2_Term_Weakening_prop.\n\n\nLtac solve_typ := \n match goal with \n | |- (styp _ _ _ (letx _ _) _)          \n\t=> idtac \"1\"; apply_fresh_from styp_let_3_6 with fv_of_static_goal\n | |- (styp _ _ _ (openx _ _) _)         \n\t=> idtac \"2\"; apply_fresh_from styp_open_3_7 with fv_of_static_goal\n | |- (styp _ _ _ (openstar _ _) _)      \n\t=> idtac \"3\"; apply_fresh_from styp_openstar_3_8 with fv_of_static_goal\n | |- (rtyp _ _ _ (pack _ _ _) _)       \n\t=> idtac \"4\"; apply_fresh_from SR_3_12 with fv_of_static_goal\n | |- (rtyp _ _ _ (f_e (ufun _ _)) _)    \n\t=> idtac \"5\"; apply_fresh_from SR_3_14 with fv_of_static_goal\n | |- (rtyp _ _ _ (f_e (dfun _ _ _ )) _) \n\t=> idtac \"6\"; apply_fresh_from SR_3_13 with fv_of_static_goal\n | |- (ltyp _ _ _ (p_e _ _) _) =>\n   idtac \"12\"; applys SL_3_1\n | |- (rtyp ?a ?b ?c (p_e ?d ?e) ?f) =>\n   idtac \"13 a b c d e f\"; applys SR_3_1\n | |- (ltyp _ _ _  (dot (p_e _ _) zero_pe) _) =>\n   idtac \"14\"; applys SL_3_3\n | |- (ltyp _ _ _ (dot (p_e _ _) one_pe)  _)  =>\n   idtac \"15\"; applys SL_3_4\n | |- (rtyp _ _ _ (dot _ zero_pe) _)          =>\n   idtac \"16\"; applys SR_3_3\n | |- (rtyp _ _ _ (dot _ one_pe)  _)          =>\n   idtac \"17\"; applys SR_3_4\n | |- (styp _ _ _ (e_s _) _)                  =>\n   idtac \"18\"; applys styp_e_3_1\n | |- (rtyp _ _ _ (appl _ _) _)               =>\n   idtac \"19\"; applys SR_3_9\nend.\n\nLemma gettype_weakening:\n  forall u u' x tau' p tau,\n  gettype u x nil tau' p tau ->\n  LVPE.extends u u' ->\n  gettype u' x nil tau' p tau.\nAdmitted.\n\n\nLemma A_2_Term_Weakening_2:\n  forall (d : Delta) (u : Upsilon) (g : Gamma) (s : E) (t : Tau) (ty : typ' d u g s t),\n   A_2_Term_Weakening_prop LtypJudgement d u g s t ty.\nProof.\n  intros.\n  Typ_Induction ltyp_ind_mutual A_2_Term_Weakening_prop; intros; auto.\n  admit.\n  admit.\n  admit.\n  apply SL_3_1 with (tau':=tau'); auto.\n  apply gettype_weakening with (u:= u0); auto.\n  apply SL_3_3 with (t1:= t1); auto.\n  apply SL_3_4 with (t0:= t0); auto.\n  apply SR_3_1 with (tau':= tau'); auto.\n  apply gettype_weakening with (u:= u0); auto.\n  apply SR_3_3 with (t1:= t1); auto.\n  apply SR_3_4 with (t0:= t0); auto.\n  apply SR_3_9 with (tau':= tau'); auto.\n  apply SR_3_11 with (k:=k) (tau':= tau'); auto.\n  admit.\n  apply SR_3_13 with (L:=        ((((((((((((((L \\u T.fv t) \\u T.fv tau) \\u T.fv tau') \\u TM.fv_st s0) \\u TM.fv_e s) \\u\n                TTM.fv_st s0) \\u TTM.fv_e s) \\u fv_delta d) \\u \n             fv_delta d0) \\u fv_gamma g) \\u fv_gamma g0) \\u fv_gamma g') \\u \n         fv_upsilon u) \\u fv_upsilon u0) \\u fv_upsilon u'). auto.\n  \n  \n  apply styp_let_3_6 with (tau':= tau') (L:= \n((((((((((((((((L \\u T.fv t) \\u T.fv tau) \\u T.fv tau') \\u TM.fv_st s0) \\u\n                   TM.fv_e s) \\u TM.fv_e e) \\u TTM.fv_st s0) \\u \n                TTM.fv_e s) \\u TTM.fv_e e) \\u fv_delta d) \\u fv_delta d0) \\u \n            fv_gamma g) \\u fv_gamma g0) \\u fv_gamma g') \\u fv_upsilon u) \\u \n        fv_upsilon u0) \\u fv_upsilon u').\n  intros.\n  auto.\n  apply_fresh_from styp_let_3_6 with fv_of_static_goal.\n  solve_typ.\n\n  admit.\n  admit.\n  admit.\n\n  admit.\n  apply SL_3_3 with (t1:= t1); auto.\n  apply SL_3_4 with (t0:= t0); auto.\n\n  \n\nbarrier .\n\n\n\nLemma A_2_Term_Weakening_3:\n  forall (d: Delta) (u : Upsilon) (g : Gamma)  (e : E) (tau : Tau),\n    rtyp d u g e tau ->\n    WFC d u g -> \n      forall (u' : Upsilon) (g' : Gamma),\n        WFC d u' g' ->\n        U.extends u u' = true ->\n        G.extends g g' = true ->\n        WFC d u g' ->\n        rtyp d u' g' e tau.\nProof.\n(*\n  intros d u g e tau ltypder.\n  apply (rtyp_ind_mutual\n           (fun (d : Delta) (u : Upsilon) (g : Gamma) (t : Tau) (s : St)\n                (st : styp d u g t s) => \n              WFC d u g -> \n              forall (u' : Upsilon) (g' : Gamma),\n                WFC d u' g' ->\n                WFC d (u ++ u') (g ++ g') ->\n                styp d (u ++ u') (g ++ g') t s)\n           (fun (d : Delta) (u : Upsilon) (g : Gamma) (e : E) (t : Tau) \n                (lt : ltyp d u g  e t) =>\n              WFC d u g -> \n              forall (u' : Upsilon) (g' : Gamma),\n                WFC d u' g' ->\n                WFC d (u ++ u') (g ++ g') ->\n                ltyp d (u ++ u') (g ++ g') e t)\n           (fun (d : Delta) (u : Upsilon) (g : Gamma) (e : E) (t : Tau) \n                (rt : rtyp d u g e t) =>\n              WFC d u g -> \n              forall (u' : Upsilon) (g' : Gamma),\n                WFC d u' g' ->\n                WFC d (u ++ u') (g ++ g') ->\n                rtyp d (u ++ u') (g ++ g') e t)).\n(*\n  Case \"styp_e_3_1\".\n   intros.\n   constructor.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n  Case \"styp_return_3_2\".\n   intros.\n   constructor.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n  Case \"styp_seq_3_3\".\n   intros.\n   constructor.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n  Case \"styp_while_3_4\".\n   intros.\n   constructor.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n  Case \"styp_if_3_5\".\n   intros.\n   constructor.\n   apply H with (u':= u') (g':= g') in H2; try assumption.\n   apply H0 with (u':= u') (g':= g') in H2; try assumption.\n   apply H1 with (u':= u') (g':= g') in H2; try assumption.\n  Case \"styp_let_3_6\".\n   intros.\n   apply styp_let_3_6 with (tau':=tau'); try assumption.\n   AdmitAlphaConversion.\n   inversion H2; try assumption.\n   assert (Z: WFC d0 u0 ([(x, tau')] ++ g0)). (* How do I get this ? *)\n   constructor; try assumption.\n   constructor; try assumption.\n   admit.\n   admit.\n   admit.\n   admit.\n   admit.\n   (* \n   apply H with (u':= u') (g':= g') in Z; try assumption.\n   admit.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n   *)\n  Case \"styp_open_3_7\".\n   admit. (* Will have the similar problems with let. *)\n  Case \"styp_openstar_3_8\".\n   admit. (* Will have the similar problems with let. *)\n  Case \"SL_3_1\".\n  (* Should use the previous theorem.\n   intros.\n   apply SL_3_1 with (tau':= tau0); try assumption.\n   apply getG_Some_Weakening; try assumption.\n   apply gettype_weakening; try assumption.\n   inversion H; try assumption.\n   inversion H1; try assumption.\n   *)\n  admit.\n  Case \"SL_3_2\".\n   intros.\n   admit. (* constructor; try assumption. *)\n   (* apply H with (u':= u') (g':= g') in H0; try assumption. *)\n  Case \"SL_3_3\".\n   intros.\n   apply SL_3_3 with (t1:= t1); try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SL_3_4\".\n   intros.\n   apply SL_3_4 with (t0:= t0); try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SR_3_1\".\n   intros.\n   apply SR_3_1 with (tau':= tau'); try assumption.\n   apply getG_Some_Weakening; try assumption.\n   apply gettype_weakening; try assumption.\n   inversion H; try assumption.\n   inversion H1; try assumption.\n  Case \"SR_3_2\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SR_3_3\".\n   intros.\n   apply SR_3_3 with (t1:= t1); try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SR_3_4\".\n   intros.\n   apply SR_3_4 with (t0:= t0); try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SR_3_5\".\n   intros.\n   constructor; try assumption.\n  Case \"SR_3_6\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SR_3_7\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n  Case \"SR_3_8\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n  Case \"SR_3_9\".\n   intros.\n   apply SR_3_9 with (tau':= tau'); try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n  Case \"SR_3_10\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n  Case \"SR_3_11\".\n   intros.\n   apply SR_3_11 with (k:=k); try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n  Case \"SR_3_12\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n  Case \"SR_3_13\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   AdmitAlphaConversion.\n   admit.\n   admit.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   admit.\n   admit.\n  Case \"SR_3_14\".\n   admit.\n  Case \"base\".\n   assumption.\nQed.\n*)\n*)\nAdmitted.\n\nLemma A_2_Term_Weakening_4:\n  forall (d: Delta) (u : Upsilon) (g : Gamma)  (s : St) (tau : Tau),\n    styp d u g tau s ->\n    WFC d u g -> \n      forall (u' : Upsilon) (g' : Gamma),\n        WFC d u' g' ->\n        U.extends u u' = true ->\n        G.extends g g' = true ->\n        WFC d u' g' ->\n        styp d u' g' tau s.\nProof.\n(*\n  intros d u g e tau ltypder.\n  apply (styp_ind_mutual\n           (fun (d : Delta) (u : Upsilon) (g : Gamma) (t : Tau) (s : St)\n                (st : styp d u g t s) => \n              WFC d u g -> \n              forall (u' : Upsilon) (g' : Gamma),\n                WFC d u' g' ->\n                WFC d (u ++ u') (g ++ g') ->\n                styp d (u ++ u') (g ++ g') t s)\n           (fun (d : Delta) (u : Upsilon) (g : Gamma) (e : E) (t : Tau) \n                (lt : ltyp d u g  e t) =>\n              WFC d u g -> \n              forall (u' : Upsilon) (g' : Gamma),\n                WFC d u' g' ->\n                WFC d (u ++ u') (g ++ g') ->\n                ltyp d (u ++ u') (g ++ g') e t)\n           (fun (d : Delta) (u : Upsilon) (g : Gamma) (e : E) (t : Tau) \n                (rt : rtyp d u g e t) =>\n              WFC d u g -> \n              forall (u' : Upsilon) (g' : Gamma),\n                WFC d u' g' ->\n                WFC d (u ++ u') (g ++ g') ->\n                rtyp d (u ++ u') (g ++ g') e t)).\n  Case \"styp_e_3_1\".\n   intros.\n   apply styp_e_3_1 with (tau':= tau').\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n  Case \"styp_return_3_2\".\n   intros.\n   constructor.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n  Case \"styp_seq_3_3\".\n   intros.\n   constructor.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n  Case \"styp_while_3_4\".\n   intros.\n   constructor.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n  Case \"styp_if_3_5\".\n   intros.\n   constructor.\n   apply H with (u':= u') (g':= g') in H2; try assumption.\n   apply H0 with (u':= u') (g':= g') in H2; try assumption.\n   apply H1 with (u':= u') (g':= g') in H2; try assumption.\n  Case \"styp_let_3_6\".\n   admit.\n   (* \n   intros.\n   apply styp_let_3_6 with (tau':=tau'); try assumption.\n   AdmitAlphaConversion.\n   inversion H2; try assumption.\n   assert (Z: WFC d0 u0 ([(x, tau')] ++ g0)). (* How do I get this ? *)\n   constructor; try assumption.\n   constructor; try assumption.\n\n   apply H with (u':= u') (g':= g') in Z; try assumption.\n   admit.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n    *)\n  Case \"styp_open_3_7\".\n   admit. (* Will have the similar problems with let. *)\n  Case \"styp_openstar_3_8\".\n   admit. (* Will have the similar problems with let. *)\n  Case \"SL_3_1\".\n   intros.\n   apply SL_3_1 with (tau':=tau'); try assumption.\n   apply getG_Some_Weakening; try assumption.\n   apply gettype_weakening; try assumption.\n   inversion H; try assumption.\n   inversion H1; try assumption.\n  Case \"SL_3_2\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SL_3_3\".\n   intros.\n   apply SL_3_3 with (t1:= t1); try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SL_3_4\".\n   intros.\n   apply SL_3_4 with (t0:= t0); try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SR_3_1\".\n   intros.\n   apply SR_3_1 with (tau':= tau'); try assumption.\n   apply getG_Some_Weakening; try assumption.\n   apply gettype_weakening; try assumption.\n   inversion H; try assumption.\n   inversion H1; try assumption.\n  Case \"SR_3_2\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SR_3_3\".\n   intros.\n   apply SR_3_3 with (t1:= t1); try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SR_3_4\".\n   intros.\n   apply SR_3_4 with (t0:= t0); try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SR_3_5\".\n   intros.\n   constructor; try assumption.\n  Case \"SR_3_6\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H0; try assumption.\n  Case \"SR_3_7\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n  Case \"SR_3_8\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n  Case \"SR_3_9\".\n   intros.\n   apply SR_3_9 with (tau':= tau'); try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   apply H0 with (u':= u') (g':= g') in H1; try assumption.\n  Case \"SR_3_10\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n  Case \"SR_3_11\".\n   intros.\n   apply SR_3_11 with (k:=k); try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n  Case \"SR_3_12\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n  Case \"SR_3_13\".\n   intros.\n   constructor; try assumption.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   AdmitAlphaConversion.\n   admit.\n   admit.\n   apply H with (u':= u') (g':= g') in H1; try assumption.\n   admit.\n   admit.\n  Case \"SR_3_14\".\n   admit.\n  Case \"base\".\n   assumption.\n*)\nAdmitted.\n", "meta": {"author": "briangmilnes", "repo": "CycloneCoqSemantics", "sha": "190c0fc57d5aebfde244efb06a119f108de7a150", "save_path": "github-repos/coq/briangmilnes-CycloneCoqSemantics", "path": "github-repos/coq/briangmilnes-CycloneCoqSemantics/CycloneCoqSemantics-190c0fc57d5aebfde244efb06a119f108de7a150/4.4/TermWeakeningProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24130556349315269}}
{"text": "(*** Boolean Utility Lemmas and Databases *)\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Classes.Morphisms.\n\n(* We would use [Scheme Minimality for bool Sort Type.], but we want\n   [bool_rect_nodep] to unfold directly to [bool_rect] so that\n   unification doesn't have a hard time unifying [bool_rect] and\n   [bool_rect_nodep] on large arguments. *)\nDefinition bool_rect_nodep {P} := @bool_rect (fun _ => P).\nGlobal Instance bool_rect_nodep_Proper {P}\n  : Proper (eq ==> eq ==> eq ==> eq) (@bool_rect_nodep P) | 10.\nProof. repeat intro; subst; reflexivity. Qed.\nModule Thunked.\n  Definition bool_rect P (t f : Datatypes.unit -> P) (b : bool) : P\n    := Datatypes.bool_rect (fun _ => P) (t tt) (f tt) b.\n  Global Instance bool_rect_Proper {P}\n    : Proper ((eq ==> eq) ==> (eq ==> eq) ==> eq ==> eq) (@bool_rect P) | 10.\n  Proof. cbv; intros ??? ??? [] ??; subst; eauto. Qed.\nEnd Thunked.\n(** Strongly prefer unfolding these versions of [bool_rect] to the\n    underlying [bool_rect] principle.  Possibly -1 would suffice rather\n    than expand, but I don't think there's harm in [expand] because\n    [bool_rect] ought not be much more complicated than any of these *)\nGlobal Strategy expand [bool_rect_nodep Thunked.bool_rect].\n\n(** For equalities of booleans *)\nCreate HintDb bool_congr discriminated.\n(** For properties of booleans, with, e.g., [iff] *)\nCreate HintDb bool_congr_setoid discriminated.\n(** For generic simplifications of things involving booleans, e.g., if-statements *)\nCreate HintDb boolsimplify discriminated.\n\n#[global] Hint Extern 1 => progress autorewrite with boolsimplify in * : boolsimplify.\n#[global] Hint Extern 1 => progress autorewrite with bool_congr in * : bool_congr.\n#[global] Hint Extern 1 => progress autorewrite with bool_congr_setoid in * : bool_congr_setoid.\n#[global] Hint Extern 2 => progress rewrite_strat topdown hints bool_congr_setoid : bool_congr_setoid.\n\n#[global] Hint Rewrite Bool.andb_diag Bool.orb_diag Bool.eqb_reflx Bool.negb_involutive Bool.eqb_negb1 Bool.eqb_negb2 Bool.orb_true_r Bool.orb_true_l Bool.orb_false_r Bool.orb_false_l Bool.orb_negb_r Bool.andb_false_r Bool.andb_false_l Bool.andb_true_r Bool.andb_false_r Bool.andb_negb_r Bool.xorb_false_r Bool.xorb_false_l Bool.xorb_true_r Bool.xorb_true_l Bool.xorb_nilpotent : bool_congr.\n#[global] Hint Rewrite Bool.negb_if : boolsimplify.\n#[global] Hint Rewrite <- Bool.andb_if Bool.andb_lazy_alt Bool.orb_lazy_alt : boolsimplify.\n#[global] Hint Rewrite Bool.not_true_iff_false Bool.not_false_iff_true Bool.eqb_true_iff Bool.eqb_false_iff Bool.negb_true_iff Bool.negb_false_iff Bool.orb_true_iff Bool.orb_false_iff Bool.andb_true_iff Bool.andb_false_iff Bool.xorb_negb_negb : bool_congr_setoid.\n\nCreate HintDb push_orb discriminated.\nCreate HintDb pull_orb discriminated.\nCreate HintDb push_andb discriminated.\nCreate HintDb pull_andb discriminated.\nCreate HintDb push_negb discriminated.\nCreate HintDb pull_negb discriminated.\n#[global] Hint Extern 1 => progress autorewrite with push_orb in * : push_orb.\n#[global] Hint Extern 1 => progress autorewrite with pull_orb in * : pull_orb.\n#[global] Hint Extern 1 => progress autorewrite with push_andb in * : push_andb.\n#[global] Hint Extern 1 => progress autorewrite with pull_andb in * : pull_andb.\n#[global] Hint Extern 1 => progress autorewrite with push_negb in * : push_negb.\n#[global] Hint Extern 1 => progress autorewrite with pull_negb in * : pull_negb.\n#[global] Hint Rewrite Bool.negb_orb Bool.negb_andb : push_negb.\n#[global] Hint Rewrite Bool.xorb_negb_negb : pull_negb.\n#[global] Hint Rewrite <- Bool.negb_orb Bool.negb_andb Bool.negb_xorb_l Bool.negb_xorb_r : pull_negb.\n#[global] Hint Rewrite Bool.andb_orb_distrib_r Bool.andb_orb_distrib_l : push_andb.\n#[global] Hint Rewrite <- Bool.orb_andb_distrib_r Bool.orb_andb_distrib_l : push_andb.\n#[global] Hint Rewrite Bool.orb_andb_distrib_r Bool.orb_andb_distrib_l : pull_andb.\n#[global] Hint Rewrite <- Bool.andb_orb_distrib_r Bool.andb_orb_distrib_l : pull_andb.\n#[global] Hint Rewrite Bool.orb_andb_distrib_r Bool.orb_andb_distrib_l : push_orb.\n#[global] Hint Rewrite <- Bool.andb_orb_distrib_r Bool.andb_orb_distrib_l : push_orb.\n#[global] Hint Rewrite <- Bool.orb_andb_distrib_r Bool.orb_andb_distrib_l : pull_orb.\n#[global] Hint Rewrite Bool.andb_orb_distrib_r Bool.andb_orb_distrib_l : pull_orb.\n\nDefinition pull_bool_if_dep {A B} (f : forall b : bool, A b -> B b) (b : bool) (x : A true) (y : A false)\n  : (if b return B b then f _ x else f _ y) = f b (if b return A b then x else y)\n  := if b return ((if b return B b then f _ x else f _ y) = f b (if b return A b then x else y))\n     then eq_refl\n     else eq_refl.\n\nDefinition pull_bool_if {A B} (f : A -> B) (b : bool) (x : A) (y : A)\n  : (if b then f x else f y) = f (if b then x else y)\n  := @pull_bool_if_dep (fun _ => A) (fun _ => B) (fun _ => f) b x y.\n\nDefinition reflect_iff_gen {P b} : reflect P b -> forall b' : bool, (if b' then P else ~P) <-> b = b'.\nProof.\n  intros H; apply reflect_iff in H; intro b'; destruct b, b';\n    intuition congruence.\nQed.\n\nDefinition andb_prop : forall a b : bool, a && b = true -> a = true /\\ b = true. (* transparent version *)\nProof. destruct a, b; simpl; split; try reflexivity; assumption. Defined.\n\nDefinition andb_true_intro : forall a b : bool, a = true /\\ b = true -> a && b = true. (* transparent version *)\nProof. destruct a, b; simpl; try reflexivity; intros [? ?]; assumption. Defined.\n\nDefinition andb_true_rect {a b : bool} (P : a && b = true -> Type) (f : forall p q, P (andb_true_intro a b (conj p q)))\n  : forall p, P p.\nProof.\n  destruct a, b; try specialize (f eq_refl eq_refl); cbn in *; intro p;\n    first [ refine match p with eq_refl => f end\n          | refine match p with eq_refl => I end ].\nDefined.\nDefinition andb_true_rec {a b : bool} (P : a && b = true -> Set) := @andb_true_rect a b P.\nDefinition andb_true_ind {a b : bool} (P : a && b = true -> Prop) := @andb_true_rec a b P.\n\nDefinition andb_is_true_intro : forall a b : bool, is_true a /\\ is_true b -> is_true (a && b)\n  := andb_true_intro.\n\nDefinition andb_is_true_rect {a b : bool} (P : is_true (a && b) -> Type) (f : forall p q, P (andb_is_true_intro a b (conj p q)))\n  : forall p, P p\n  := @andb_true_rect a b P f.\nDefinition andb_is_true_rec {a b : bool} (P : is_true (a && b) -> Set) := @andb_is_true_rect a b P.\nDefinition andb_is_true_ind {a b : bool} (P : is_true (a && b) -> Prop) := @andb_is_true_rec a b P.\n\nLtac split_andb_step :=\n  match goal with\n  | [ H : andb _ _ = true |- _ ] => induction H using (@andb_true_rect _ _)\n  | [ H : is_true (andb _ _) |- _ ] => induction H using (@andb_is_true_rect _ _)\n  end.\nLtac split_andb := repeat split_andb_step.\nLtac split_andb_in_context_step :=\n  match goal with\n  | _ => split_andb_step\n  | [ H : context[andb ?x ?y = true] |- _ ]\n    => rewrite (Bool.andb_true_iff x y) in H\n  | [ H : context[is_true (andb ?x ?y)] |- _ ]\n    => change (is_true (andb x y)) with (andb x y = true) in H;\n       rewrite Bool.andb_true_iff in H;\n       change (x = true /\\ y = true) with (is_true x /\\ is_true y) in H\n  end.\nLtac split_andb_in_context := repeat split_andb_in_context_step.\n\nLemma if_const A (b : bool) (x : A) : (if b then x else x) = x.\nProof. case b; reflexivity. Qed.\n\nLemma ex_bool_iff_or P : @ex bool P <-> (or (P true) (P false)).\nProof.\n  split; [ intros [ [] ? ] | intros [?|?]; eexists ]; eauto.\nQed.\n\nLemma eqb_true_l x : Bool.eqb x true = x. Proof. now destruct x. Qed.\nLemma eqb_true_r x : Bool.eqb true x = x. Proof. now destruct x. Qed.\nLemma eqb_false_l x : Bool.eqb x false = negb x. Proof. now destruct x. Qed.\nLemma eqb_false_r x : Bool.eqb false x = negb x. Proof. now destruct x. Qed.\n#[global] Hint Rewrite eqb_true_l eqb_true_r eqb_false_l eqb_false_r : boolsimplify.\n", "meta": {"author": "mit-plv", "repo": "rewriter", "sha": "77c76a43689ce532921ccfa200b44083bc52dc21", "save_path": "github-repos/coq/mit-plv-rewriter", "path": "github-repos/coq/mit-plv-rewriter/rewriter-77c76a43689ce532921ccfa200b44083bc52dc21/src/Rewriter/Util/Bool.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24130556349315269}}
{"text": "From Coq Require Import String List Psatz Peano Program.Equality.\nFrom DanTrick Require Import DanTrickLanguage StackLanguage EnvToStack StackLangTheorems.\nFrom DanTrick Require Import DanTrickSemanticsMutInd ImpVarMap ImpVarMapTheorems.\nFrom DanTrick Require Import LogicTranslationBase DanImpHigherOrderRel DanImpHigherOrderRelTheorems.\nFrom DanTrick Require Import FunctionWellFormed CompilerCorrectHelpers CompilerCorrectMoreHelpers.\nFrom DanTrick Require Import StackFrame.\n\nLocal Open Scope nat_scope.\nLocal Open Scope string_scope.\nLocal Open Scope list_scope.\n\nLocal Definition P_compiler_sound (funcs: list fun_Dan) (i: imp_Dan) (dbenv: list nat) (fenv: fun_env) (nenv nenv': nat_env): Prop :=\n  forall (i_stk: imp_stack) (stk stk' rho: stack) (num_args: nat) (idents: list ident),\n  forall (fenv_s: fun_env_stk),\n  forall (FUN_WF: fun_app_imp_well_formed fenv funcs i),\n  forall (FENV_WF: fenv_well_formed' funcs fenv),\n    fenv_s = compile_fenv fenv ->\n    List.length dbenv = num_args ->\n    state_to_stack idents nenv dbenv stk ->\n    state_to_stack idents nenv' dbenv stk' ->\n    imp_rec_rel (var_map_wf_wrt_imp idents) i ->\n    i_stk = compile_imp i (fun x => one_index_opt x idents) (List.length idents) ->\n    imp_stack_sem i_stk fenv_s (stk ++ rho) (stk' ++ rho).\n\nLocal Definition P0_compiler_sound (funcs: list fun_Dan) (a: aexp_Dan) (dbenv: list nat) (fenv: fun_env) (nenv: nat_env) (n: nat): Prop :=\n  forall (a_stk: aexp_stack) (stk rho: stack) (num_args: nat) (idents: list ident),\n  forall (fenv_s: fun_env_stk),\n  forall (FUN_WF: fun_app_well_formed fenv funcs a),\n  forall (FENV_WF: fenv_well_formed' funcs fenv),\n    fenv_s = compile_fenv fenv ->\n    List.length dbenv = num_args ->\n    state_to_stack idents nenv dbenv stk ->\n    var_map_wf_wrt_aexp idents a ->\n    a_stk = compile_aexp a (fun x => one_index_opt x idents) (List.length idents) ->\n    aexp_stack_sem a_stk fenv_s (stk ++ rho) (stk ++ rho, n).\n\nLocal Definition P1_compiler_sound (funcs: list fun_Dan) (b: bexp_Dan) (dbenv: list nat) (fenv: fun_env) (nenv: nat_env) (v: bool): Prop :=\n  forall (b_stk: bexp_stack) (stk rho: stack) (num_args: nat) (idents: list ident),\n  forall (fenv_s: fun_env_stk),\n  forall (FUN_WF: fun_app_bexp_well_formed fenv funcs b),\n  forall (FENV_WF: fenv_well_formed' funcs fenv),\n    fenv_s = compile_fenv fenv ->\n    List.length dbenv = num_args ->\n    state_to_stack idents nenv dbenv stk ->\n    var_map_wf_wrt_bexp idents b ->\n    b_stk = compile_bexp b (fun x => one_index_opt x idents) (List.length idents) ->\n    bexp_stack_sem b_stk fenv_s (stk ++ rho) (stk ++ rho, v).\n\nLocal Definition P2_compiler_sound (funcs: list fun_Dan) (args: list aexp_Dan) (dbenv: list nat) (fenv: fun_env) (nenv: nat_env) (vals: list nat): Prop :=\n  forall (args_stk: list aexp_stack) (stk rho: stack) (num_args: nat) (idents: list ident),\n  forall (fenv_s: fun_env_stk),\n  forall (FUN_WF: fun_app_args_well_formed fenv funcs args),\n  forall (FENV_WF: fenv_well_formed' funcs fenv),\n    fenv_s = compile_fenv fenv ->\n    List.length dbenv = num_args ->\n    state_to_stack idents nenv dbenv stk ->\n    Forall (var_map_wf_wrt_aexp idents) args ->\n    args_stk = map (fun a => compile_aexp a (fun x => one_index_opt x idents) (List.length idents)) args ->\n    args_stack_sem args_stk fenv_s (stk ++ rho) (stk ++ rho, vals).\n\n\n\n\nLemma big_step_away_pushes (funcs: list fun_Dan)\n      (dbenv : list nat)\n      (fenv : DanTrickLanguage.ident -> fun_Dan)\n      (nenv nenv'' : nat_env)\n      (func : fun_Dan)\n      (aexps : list aexp_Dan)\n      (ns : list nat)\n      (ret : nat)\n      (f : DanTrickLanguage.ident)\n      (FUN_WF: fun_app_well_formed fenv funcs (APP_Dan f aexps))\n      (FENV_WF: fenv_well_formed' funcs fenv)\n      (e : fenv f = func)\n      (e0 : DanTrickLanguage.Args func = Datatypes.length aexps)\n      (i : i_Dan (DanTrickLanguage.Body func) ns fenv init_nenv nenv'')\n      (H0 : forall (i_stk : imp_stack) (stk stk' rho : stack) \n         (num_args : nat) (idents : list ident) (fenv_s : fun_env_stk),\n          fun_app_imp_well_formed fenv funcs (DanTrickLanguage.Body func) ->\n          fenv_well_formed' funcs fenv ->\n          fenv_s = compile_fenv fenv ->\n          Datatypes.length ns = num_args ->\n          state_to_stack idents init_nenv ns stk ->\n          state_to_stack idents nenv'' ns stk' ->\n          imp_rec_rel (var_map_wf_wrt_imp idents)\n                      (DanTrickLanguage.Body func) ->\n          i_stk =\n            compile_imp (DanTrickLanguage.Body func)\n                        (fun x : ident => one_index_opt x idents)\n                        (Datatypes.length idents) ->\n          imp_stack_sem i_stk fenv_s (stk ++ rho) (stk' ++ rho))\n      (stk rho : stack)\n      (num_args : nat)\n      (idents : list ident)\n      (fenv_s : fun_env_stk)\n      (H1 : fenv_s = compile_fenv fenv)\n      (H2 : Datatypes.length dbenv = num_args)\n      (H3 : state_to_stack idents nenv dbenv stk)\n      (H4 : var_map_wf_wrt_aexp idents (APP_Dan f aexps))\n      (func' COMPD : fun_stk)\n      (fidents : list ident)\n      (Heqfidents : fidents = construct_trans (DanTrickLanguage.Body func))\n      (HeqCOMPD : COMPD =\n                    {|\n                      Name := DanTrickLanguage.Name func;\n                      Args := Datatypes.length aexps;\n                      Body := fst (compile_code (DanTrickLanguage.Body func));\n                      Return_expr :=\n                      Var_Stk (stack_mapping (DanTrickLanguage.Body func) (Ret func));\n                      Return_pop := Datatypes.length fidents\n                    |})\n      (Heqfunc' : func' =\n                    {|\n                      Name := DanTrickLanguage.Name func;\n                      Args := Datatypes.length aexps;\n                      Body :=\n                      prepend_push\n                        (compile_imp (DanTrickLanguage.Body func)\n                                     (stack_mapping (DanTrickLanguage.Body func))\n                                     (Datatypes.length fidents))\n                        (Datatypes.length fidents);\n                      Return_expr :=\n                       Var_Stk (stack_mapping (DanTrickLanguage.Body func) (Ret func));\n                      Return_pop := Datatypes.length fidents\n                    |})\n      (Hfunc' : func' = fenv_s f):\n  imp_stack_sem\n    (prepend_push\n       (compile_imp (DanTrickLanguage.Body func)\n                    (stack_mapping (DanTrickLanguage.Body func))\n                    (Datatypes.length fidents)) (Datatypes.length fidents)) fenv_s\n    (ns ++ stk ++ rho) ((map nenv'' fidents ++ ns) ++ stk ++ rho).\nProof.\n  remember (Datatypes.length fidents) as fidents_len.\n  revert Heqfidents_len. revert Heqfidents.\n  remember (compile_imp (DanTrickLanguage.Body func) (stack_mapping (DanTrickLanguage.Body func)) fidents_len) as body_s.\n  revert i.\n  revert H0. revert ns.\n  inversion FUN_WF.\n  subst fenv0 wf_funcs f0 args.\n  unfold fenv_well_formed' in FENV_WF. destruct FENV_WF as (FENV_WF & FENV_WF').\n  \n  induction fidents_len; intros.\n  - simpl.\n    eapply H0.\n    + symmetry in e.\n      apply FENV_WF' in e. destruct e as (_ & FUN_APP_BODY & _).\n      assumption.\n    + unfold fenv_well_formed'; split; assumption.\n    + assumption.\n    + ereflexivity.\n    + assert (state_to_stack nil init_nenv ns ns).\n      constructor. eassumption.\n    + destruct fidents. simpl. econstructor.\n      simpl in Heqfidents_len. invs Heqfidents_len.\n    + unfold_wf_aexp_in H4.\n      destruct fidents.\n      symmetry in Heqfidents.\n      eapply var_map_wf_imp_nil_trivial. assumption.\n      simpl in Heqfidents_len. invs Heqfidents_len.\n    + simpl.\n      rewrite Heqbody_s.\n      unfold stack_mapping.\n      rewrite <- Heqfidents.\n      destruct fidents.\n      simpl. reflexivity.\n      simpl in Heqfidents_len. invs Heqfidents_len.\n  - simpl. destruct fidents.\n    simpl in Heqfidents_len. invs Heqfidents_len. simpl in *.\n    rewrite app_comm_cons. simpl. rewrite prepend_push_commutes. econstructor.\n    + econstructor. ereflexivity.\n    + rewrite app_comm_cons. rewrite app_comm_cons. eapply remove_prepend_push. rewrite app_assoc.\n      eapply H0.\n      * symmetry in e. apply FENV_WF' in e. destruct e as (_ & FUN_APP_BODY & _). assumption.\n      * unfold fenv_well_formed'; split; assumption.\n      * assumption.\n      * ereflexivity.\n      * assert (0 :: ns = 0 :: nil ++ ns) by (reflexivity).\n        rewrite H. rewrite app_comm_cons. rewrite app_assoc. rewrite repeat_add_last. rewrite Heqfidents_len. change (S (Datatypes.length fidents)) with (Datatypes.length (i0 :: fidents)). rewrite <- init_fenv_map_is_repeat_0 with (idents := i0 :: fidents). econstructor.\n      * rewrite app_comm_cons. rewrite <- map_cons. econstructor.\n      * eapply var_map_wf_imp_self_imp_rec_rel. symmetry. assumption.\n      * rewrite Heqbody_s. simpl. rewrite <- Heqfidents_len. unfold stack_mapping. rewrite <- Heqfidents. simpl. reflexivity.\nQed.\n\nLemma nth_error_map_commute_kinda :\n  forall (A B: Type) (alist: list A) (a: A) (f: A -> B) (n: nat),\n    nth_error alist n = Some a ->\n    nth_error (map f alist) n = Some (f a).\nProof.\n  induction alist; intros.\n  - destruct n; simpl in H; invs H.\n  - destruct n; simpl in H.\n    + invs H. simpl. reflexivity.\n    + simpl. apply IHalist. assumption.\nQed.\n                                     \n\nTheorem compiler_sound_mut_ind :\n  forall (funcs: list fun_Dan),\n    dantrick_sem_mut_ind_theorem (P_compiler_sound funcs) (P0_compiler_sound funcs) (P1_compiler_sound funcs) (P2_compiler_sound funcs).\nProof.\n  unfold dantrick_sem_mut_ind_theorem, P_compiler_sound, P0_compiler_sound, P1_compiler_sound, P2_compiler_sound.\n  intros funcs.\n  dantrick_sem_mutual_induction' P P0 P1 P2 (P_compiler_sound funcs) (P0_compiler_sound funcs) (P1_compiler_sound funcs) (P2_compiler_sound funcs) P_compiler_sound P0_compiler_sound P1_compiler_sound P2_compiler_sound; intros.\n  - simpl in H4. subst. invs H1. invs H2.\n    constructor.\n  - simpl in H6. subst. invs FUN_WF. eapply Stack_if_true.\n    + eapply H.\n      assumption. assumption.\n      reflexivity. ereflexivity. eassumption.\n      apply imp_rec_rel_self in H5.\n      unfold_wf_imp_in H5.\n      invs WF'. assumption. reflexivity.\n    + eapply H0; eauto. invs H5. assumption.\n  - simpl in H6. rewrite H6. clear H6. clear i_stk. inversion FUN_WF. subst fenv0 wf_funcs b0 i0 i3. eapply Stack_if_false.\n    + eapply H; eauto. eapply imp_rec_rel_self in H5. unfold_wf_imp_in H5. invs WF'. assumption.\n    + eapply H0; eauto. invs H5. assumption.\n  - simpl in H5. rewrite H5. clear H5. clear i_stk.\n    eapply imp_rec_rel_self in H4. unfold_wf_imp_in H4.\n    inversion FUN_WF. subst fenv0 wf_funcs x0 a1.\n    assert (In x idents).\n    {\n      eapply WF''. constructor. eapply String.eqb_eq. reflexivity.\n    }\n    econstructor.\n    + apply one_index_opt_always_geq_1.\n    + remember (one_index_opt x idents) as index.\n      assert (imp_has_variable x (ASSIGN_Dan x a)).\n      constructor. eapply String.eqb_eq. reflexivity.\n      apply WF'' in H5.\n      eapply inside_implies_within_range' with (index := index) in H5.\n      invs H2. rewrite app_length. rewrite app_length. rewrite map_length.\n      eapply Plus.le_plus_trans.\n      eapply Plus.le_plus_trans. assumption.\n      symmetry. assumption.\n    + eapply H. assumption. assumption.\n      assumption. eassumption. eassumption.\n      invs WF'. assumption.\n      reflexivity.\n    + invs H3. invs H2. eapply stack_mutated_prefix_OK.\n      pose proof (inside_implies_within_range').\n      specialize (H0 idents x (one_index_opt x idents) H4 eq_refl).\n      rewrite app_length. rewrite map_length. eapply Plus.le_plus_trans. assumption.\n      eapply stack_mutated_prefix_OK.\n      rewrite map_length. apply inside_implies_within_range' with (x := x).\n      assumption. reflexivity.\n      eapply stack_mutated_at_index_of_update. assumption. destruct WF as (WF & _). assumption.\n  - simpl in H5. rewrite H5. clear H5. clear i_stk.\n    pose proof (H5 := H4).\n    eapply imp_rec_rel_self in H5. unfold_wf_imp_in H5.\n    constructor.\n    invs FUN_WF.\n    invs H2. invs H3. eapply H; eauto.\n    invs WF'. assumption.\n  - simpl in H7. rewrite H7. clear H7. clear i_stk.\n    revert H2. revert H3.\n    invc H6.\n    unfold_wf_imp_in H9. invs FUN_WF. intros.\n    eapply Stack_while_step.\n    + eapply H; eauto. invs WF'. assumption.\n    + eapply H0; eauto. econstructor.\n    + eapply H1; eauto.\n      * econstructor.\n      * econstructor. assumption.\n        unfold_wf_imp; assumption.\n  - simpl in H6. rewrite H6. clear H6. clear i_stk.\n    revert H2. revert H3.\n    invc H5.\n    invs FUN_WF.\n    unfold_wf_imp_in H9. intros.\n    econstructor; [ eapply H | eapply H0 ]; eauto.\n    + econstructor.\n    + econstructor.\n  - simpl in H3. rewrite H3. constructor.\n  - simpl in H3. rewrite H3.\n    unfold_wf_aexp_in H2.\n    constructor.\n    eapply one_index_opt_always_geq_1. invs H1.\n    repeat rewrite app_length. rewrite map_length. repeat eapply Plus.le_plus_trans.\n    \n    eapply inside_implies_within_range'.\n    eapply A. ereflexivity. simpl. left. reflexivity. reflexivity.\n    invs H1.\n    destruct WF as (NODUP & FIND_OPT & IN & _).\n    assert (In x idents).\n    {\n      eapply A. reflexivity. simpl. left. reflexivity.\n    }\n    specialize (find_index_rel_in_stronger idents x H NODUP). intros.\n    destruct H0.\n    specialize (find_index_rel_within_range idents x x0 H0). intros.\n    specialize (FIND_OPT x x0 H2). destruct FIND_OPT as (FIND_OPT & _).\n    specialize (FIND_OPT H0). rewrite FIND_OPT.\n    rewrite <- app_assoc.\n    rewrite successor_minus_one_same.\n    specialize (in_map nenv idents x H). intros.\n    apply In_nth_error in H. destruct H.\n    apply nth_error_vs_find_index_rel in H0. destruct H0.\n    pose proof (map_length).\n    specialize (H5 string nat nenv idents).\n    erewrite <- map_length in H2.\n    erewrite nth_error_app1.\n    eapply map_nth_error with (f := nenv) in H0. assumption.\n    destruct H2. eassumption.\n  - simpl in H3. rewrite H3.\n    clear H3. clear a_stk. constructor.\n    lia.\n    rewrite app_length. invs H1. rewrite app_length. rewrite map_length.\n    repeat rewrite <- PeanoNat.Nat.add_assoc.\n    eapply Plus.plus_le_compat_l.\n    lia.\n    invs H1. rewrite <- app_assoc.\n    erewrite nth_error_app2.\n    rewrite map_length.\n    remember ((Nat.sub\n             (Nat.add (Nat.add (@Datatypes.length ident idents) n) (S O))\n             (S O))) as SUB.\n    remember (Nat.add (@Datatypes.length ident idents) n) as ADD.\n    rewrite PeanoNat.Nat.add_comm in HeqSUB.\n    erewrite Minus.minus_plus in HeqSUB.\n    rewrite HeqADD in HeqSUB. rewrite HeqSUB.\n    erewrite Minus.minus_plus.\n    rewrite nth_error_app1. assumption.\n    destruct a. assumption.\n    rewrite PeanoNat.Nat.add_sub. rewrite map_length. apply PeanoNat.Nat.le_add_r.\n  - simpl in H5. rewrite H5. clear H5. clear a_stk.\n    eapply var_map_wf_plus_dan_forwards in H4. destruct H4.\n    inversion FUN_WF.\n    subst fenv0 wf_funcs a3 a4.\n    econstructor.\n    + eapply H; eauto.\n    + eapply H0; eauto.\n  - simpl in H5. rewrite H5. clear H5. clear a_stk.\n    eapply var_map_wf_minus_dan_forwards in H4. destruct H4.\n    inversion FUN_WF. subst fenv0 wf_funcs a3 a4.\n    econstructor.\n    + eapply H; eauto.\n    + eapply H0; eauto.\n  - simpl in H5. rewrite H5. clear H5. clear a_stk.\n    remember (fenv_s f) as func'.\n    pose proof (Hfunc' := Heqfunc').\n    rewrite H1 in Heqfunc'. unfold compile_fenv in Heqfunc'. unfold compile_function in Heqfunc'. rewrite e in Heqfunc'.\n    remember (pre_compile_function func) as COMPD.\n    unfold pre_compile_function in HeqCOMPD.\n    rewrite e0 in HeqCOMPD.\n    rewrite HeqCOMPD in Heqfunc'. simpl in Heqfunc'.\n    remember (construct_trans (DanTrickLanguage.Body func)) as fidents.\n    assert (imp_stack_sem\n    (prepend_push\n       (compile_imp (DanTrickLanguage.Body func)\n          (stack_mapping (DanTrickLanguage.Body func))\n          (Datatypes.length fidents)) (Datatypes.length fidents)) fenv_s\n    (ns ++ stk ++ rho) (((map nenv'' fidents) ++ ns) ++ stk ++ rho)) by (eapply big_step_away_pushes; eassumption).\n    inversion FUN_WF. subst fenv0 wf_funcs f0 args.\n    econstructor.\n    + symmetry in Hfunc'. eassumption.\n    + rewrite Heqfunc'. simpl. ereflexivity.\n    + rewrite Heqfunc'. simpl. ereflexivity.\n    + rewrite Heqfunc'. simpl. ereflexivity.\n    + rewrite map_length. apply args_Dan_preserves_length in a.\n      rewrite a. reflexivity. \n    + eapply H; eauto.\n      induction aexps.\n      * constructor.\n      * eapply var_map_wf_app_dan_args_all. eassumption.\n    + rewrite Heqfunc'. simpl.\n      eapply H5.\n    + assert (func0 = func) by (rewrite H9, e; reflexivity).\n      subst func0. rewrite H6 in H10, H15, H14, H11.\n      eapply free_vars_in_imp_has_variable in H14; [ | eauto ].\n      assert (In (Ret func) (construct_trans (DanTrickLanguage.Body func))).\n      {\n        unfold construct_trans. eapply fold_left_containment_helper.\n        assumption.\n      } \n      econstructor.\n      * unfold stack_mapping. eapply one_index_opt_always_geq_1.\n      * unfold stack_mapping. repeat rewrite app_length. rewrite map_length. rewrite Heqfidents.\n\n        pose proof (inside_implies_within_range).\n        specialize (H9 (construct_trans (DanTrickLanguage.Body func)) (Ret func) (Nat.pred (one_index_opt (Ret func) (construct_trans (DanTrickLanguage.Body func)))) H7).\n        assert (one_index_opt (Ret func) (construct_trans (DanTrickLanguage.Body func)) =\n                  S (Nat.pred (one_index_opt (Ret func) (construct_trans (DanTrickLanguage.Body func))))).\n        rewrite <- Lt.S_pred_pos. reflexivity.\n        specialize (one_index_opt_always_geq_1 (Ret func) (construct_trans (DanTrickLanguage.Body func))).\n        intros.\n        lia.\n        apply H9 in H12. destruct H12. apply PeanoNat.Nat.lt_pred_le in H13.\n        rewrite <- PeanoNat.Nat.add_assoc.\n        apply Plus.le_plus_trans. assumption.\n      * unfold stack_mapping.\n        pose proof (IN := H7).\n        eapply in_idents_one_index_opt in H7; [ | eapply nodup_construct_trans ].\n        destruct H7.\n        specialize (one_index_opt_always_geq_1 (Ret func) fidents).\n        intros.\n        rewrite Heqfidents in H9. assert (1 <= x) by (rewrite <- H7; assumption).\n        destruct x; [ invs H12 | ].\n        rewrite H7. rewrite successor_minus_one_same.\n        pose proof (INSIDE := inside_implies_within_range).\n        specialize (INSIDE (construct_trans (DanTrickLanguage.Body func)) (Ret func) x IN H7).\n        rewrite <- Heqfidents in INSIDE.\n        erewrite <- map_length with (f := nenv'') in INSIDE.\n        erewrite nth_error_app1.\n        rewrite nth_error_app1.\n        2: destruct INSIDE; assumption.\n        2: destruct INSIDE; rewrite app_length; apply Plus.lt_plus_trans; assumption.\n        rewrite nth_error_map.\n        rewrite map_length in INSIDE. rewrite Heqfidents in INSIDE.\n        destruct INSIDE.\n        eapply one_index_opt_vs_nth_error in H7; [ | try lia; try assumption .. ].\n        rewrite Heqfidents.\n        rewrite <- nth_error_map.\n        apply nth_error_map_commute_kinda with (B := nat) (f := nenv'') in H7.\n        rewrite e1 in H7. assumption.\n    + enough ((Datatypes.length aexps + Datatypes.length fidents) = Datatypes.length (map nenv'' fidents ++ ns)).\n      -- apply (same_after_popping_length1 (stk ++ rho) ((map nenv'' fidents ++ ns)) (stk ++ rho) (Datatypes.length aexps + Datatypes.length fidents)).\n        symmetry; assumption. reflexivity.  \n      -- rewrite app_length. rewrite map_length. rewrite PeanoNat.Nat.add_comm. \n        eapply args_Dan_preserves_length in a. rewrite a. reflexivity. \n  - rewrite H3. simpl. econstructor.\n  - rewrite H3. simpl. econstructor.\n  - rewrite H4. simpl. econstructor.\n    inversion FUN_WF. subst fenv0 wf_funcs b1.\n    + eapply H; eauto.\n      eapply var_map_wf_neg_dan; eauto.\n    + reflexivity.\n  - rewrite H5. simpl. eapply var_map_wf_and_or_dan_forwards in H4. destruct H4. inversion FUN_WF. subst fenv0 wf_funcs b3 b4.  econstructor.\n    + eapply H. assumption. assumption. assumption. eassumption. eassumption. eapply H4. reflexivity.\n    + eapply H0. assumption. assumption. assumption. eassumption. eassumption. eassumption. reflexivity.\n    + reflexivity.\n    + left. reflexivity.\n  - rewrite H5. simpl. eapply var_map_wf_and_or_dan_forwards in H4. destruct H4. inversion FUN_WF. subst fenv0 wf_funcs b3 b4. econstructor.\n    + eapply H. assumption. assumption. assumption. eassumption. eassumption. eapply H4. reflexivity.\n    + eapply H0. assumption. assumption. assumption. eassumption. eassumption. eassumption. reflexivity.\n    + reflexivity.\n    + right. reflexivity.\n  - rewrite H5. simpl. eapply var_map_wf_leq_dan_forwards in H4. destruct H4. inversion FUN_WF. subst fenv0 wf_funcs a3 a4. econstructor.\n    + eapply H. assumption. assumption. assumption. eassumption. eassumption. eapply H4. reflexivity.\n    + eapply H0. assumption. assumption. assumption. eassumption. eassumption. eassumption. reflexivity.\n    + reflexivity.\n    + reflexivity.\n  - rewrite H3. simpl. econstructor.\n  - rewrite H5. simpl. inversion FUN_WF. subst fenv0 wf_funcs arg args. econstructor.\n    + eapply H; eauto. invs H4. assumption.\n    + eapply H0; eauto. invs H4. assumption.\nQed.\n\n    \nTheorem compiler_sound :\n  forall n_args idents fenv_d fenv_s func_list,\n    fenv_well_formed' func_list fenv_d ->\n    fenv_s = compile_fenv fenv_d -> \n    (forall aD aS,\n        aS = compile_aexp\n               aD\n               (fun x => one_index_opt x idents)\n               (List.length idents) ->\n        fun_app_well_formed fenv_d func_list aD ->\n        var_map_wf_wrt_aexp idents aD ->\n        forall nenv dbenv stk n rho, \n          List.length dbenv = n_args -> \n          state_to_stack idents nenv dbenv stk ->\n          a_Dan aD dbenv fenv_d nenv n -> \n          aexp_stack_sem aS fenv_s (stk ++ rho) (stk ++ rho, n)) /\\\n      (forall bD bS,\n          bS = compile_bexp\n                 bD\n                 (fun x => one_index_opt x idents)\n                 (List.length idents) ->\n          fun_app_bexp_well_formed fenv_d func_list bD ->\n          var_map_wf_wrt_bexp idents bD ->\n          forall nenv dbenv stk bl rho, \n            List.length dbenv = n_args -> \n            state_to_stack idents nenv dbenv stk -> \n            b_Dan bD dbenv fenv_d nenv bl -> \n            bexp_stack_sem bS fenv_s (stk ++ rho) (stk ++ rho, bl)).\nProof.\n  pose proof (SOUND := compiler_sound_mut_ind).\n  intros.\n  unfold dantrick_sem_mut_ind_theorem, P_compiler_sound, P0_compiler_sound, P1_compiler_sound, P2_compiler_sound in SOUND. specialize (SOUND func_list).\n  destruct SOUND as (_ & AEXP & BEXP & _).\n  split; intros.\n  - eapply AEXP; try eassumption.\n  - eapply BEXP; try eassumption.\nQed.\n\nLemma aexp_compiler_sound :\n  forall n_args idents fenv_d fenv_s func_list,\n    fenv_well_formed' func_list fenv_d ->\n    fenv_s = compile_fenv fenv_d -> \n    forall aD aS,\n        aS = compile_aexp\n               aD\n               (fun x => one_index_opt x idents)\n               (List.length idents) ->\n        fun_app_well_formed fenv_d func_list aD ->\n        var_map_wf_wrt_aexp idents aD ->\n        forall nenv dbenv stk n rho, \n          List.length dbenv = n_args -> \n          state_to_stack idents nenv dbenv stk ->\n          a_Dan aD dbenv fenv_d nenv n -> \n          aexp_stack_sem aS fenv_s (stk ++ rho) (stk ++ rho, n).\nProof.\n  pose proof (SOUND := compiler_sound).\n  intros.\n  specialize (SOUND n_args idents fenv_d fenv_s func_list H H0).\n  destruct SOUND as (AEXP & _).\n  eapply AEXP; eassumption.\nQed.\n\nLemma bexp_compiler_sound :\n  forall n_args idents fenv_d fenv_s func_list,\n    fenv_well_formed' func_list fenv_d ->\n    fenv_s = compile_fenv fenv_d -> \n    forall bD bS,\n      bS = compile_bexp\n             bD\n             (fun x => one_index_opt x idents)\n             (List.length idents) ->\n      fun_app_bexp_well_formed fenv_d func_list bD ->\n      var_map_wf_wrt_bexp idents bD ->\n      forall nenv dbenv stk bl rho, \n        List.length dbenv = n_args -> \n        state_to_stack idents nenv dbenv stk -> \n        b_Dan bD dbenv fenv_d nenv bl -> \n        bexp_stack_sem bS fenv_s (stk ++ rho) (stk ++ rho, bl).\nProof.\n  pose proof (SOUND := compiler_sound).\n  intros. specialize (SOUND n_args idents fenv_d fenv_s func_list H H0).\n  destruct SOUND as (_ & BEXP).\n  eapply BEXP; eassumption.\nQed.\n     \n  \n", "meta": {"author": "uwplse", "repo": "potpie", "sha": "d4814d315ff9d450a8d91ed77b22340b0ff35690", "save_path": "github-repos/coq/uwplse-potpie", "path": "github-repos/coq/uwplse-potpie/potpie-d4814d315ff9d450a8d91ed77b22340b0ff35690/CompilerCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24118198136642008}}
{"text": "(*===========================================================================\n    Anti-frame rule for registers\n\n    This rule allows removing a register from the footprint of a program even\n    though the program reads and writes it, as long as the value is restored at\n    the end. This captures the common (PUSH r;; c;; POP r) pattern.\n  ===========================================================================*)\nRequire Import ssreflect ssrbool ssrfun ssrnat eqtype tuple seq fintype.\nRequire Import procstate SPred spec pointsto reader safe septac.\nRequire Import triple (* for toPState *).\nRequire Import Setoid CSetoid Morphisms.\nRequire Import FunctionalExtensionality.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Transparent ILPre_Ops PStateSepAlgOps sepILogicOps ILFun_Ops.\n\nDefinition regNotFree (r: AnyReg) (P: SPred) :=\n  (P ** ltrue) //\\\\ (r?  ** ltrue) |-- P ** r? ** ltrue.\n\nLemma regAny_sub (r: AnyReg) s:\n  (r? ** ltrue) s -> exists v, s Registers r = Some v.\nProof.\n  move => [sr [strue [Hs1 [[v Hsr] _]]]].\n  move/stateSplitsAsIncludes: Hs1 => [Hs1 _].\n  simpl in Hsr. rewrite <-Hsr in Hs1.\n  exists v. apply Hs1. by rewrite /= eq_refl.\nQed.\n\nTheorem antiframe_register (r: AnyReg) P S:\n  regNotFree r P ->\n  AtContra S ->\n  (forall v, S @ (r~=v) |-- safe @ (P ** r~=v)) ->\n  S |-- safe @ P.\nProof.\n  move => HPr Hcontra H k R HS. move => s Hps.\n  specialize (H (s.(registers) r)).\n  rewrite ->lentails_eq, ->sepSPA, <-lentails_eq in Hps.\n  destruct Hps as [sP [s' [Hsp [HsP Hs']]]].\n\n  (* Without loss of generality, we can assume that register r is in s' (not\n     sP). Otherwise, we can \"move\" it to s': regNotFree lets us isolate it in sP,\n     and it can be added to s' because the ltrue assertion can absorb it. *)\n  without loss : sP s' HsP Hsp Hs' / s' Registers r = (toPState s) Registers r.\n  { edestruct stateSplitsAs_reg_or with (r:=r) as [HrP | HrQ];\n      first apply Hsp; last first.\n    { apply; try eassumption. }\n    destruct (HPr sP) as [sP' [sr [HsP_split [HsP' Hsr]]]].\n    { split.\n      - by rewrite ->lentails_eq, <-(ltrueR empSP), empSPR, <-lentails_eq.\n      - exists (addRegToPState emptyPState r (s.(registers) r)).\n        exists (removeRegFromPState sP r).\n        split; last split.\n      - rewrite /removeRegFromPState /restrictState /matchRegInPStateDom.\n        move => [] r'; try (destruct (sP _ r'); tauto); [].\n        simpl. case Hr': (r == r') => /=.\n        + rewrite -(eqP Hr') HrP /=. by left.\n        + destruct (sP Registers r'); tauto.\n      - exists (s.(registers) r). by rewrite /=.\n      - done.\n    }\n    apply sa_mulC in Hsp.\n    destruct (sa_mulA Hsp HsP_split) as [s'' [Hsp' Hs'']].\n    move/(_ sP' s''). apply; try assumption.\n    - destruct Hs' as [sR [strue [Hs' [HsR _]]]].\n      exists sR. apply sa_mulC in Hs''.\n      destruct (sa_mulA Hs'' Hs') as [sr' [Hs''_sr Hsr']]. by exists sr'.\n    - rewrite <- HrP.\n      move/stateSplitsAsIncludes: Hs'' => [_ Hsr_s''].\n      move/stateSplitsAsIncludes: HsP_split => [_ Hsr_sP].\n      move/regAny_sub: Hsr => [v Hsr].\n      move/(_ _ _ _ Hsr): Hsr_s'' => ->.\n      move/(_ _ _ _ Hsr): Hsr_sP => ->. done.\n  }\n\n  move => HsPr.\n  specialize (H k (eq_pred (removeRegFromPState s' r))). simpl in H. apply H.\n  { assert (regIs r (s.(registers) r) ** eq_pred (removeRegFromPState s' r)\n            |-- R ** ltrue) as HRtrue.\n    { rewrite ->lentails_eq in Hs'. rewrite <-Hs'. apply stateSplitsAs_eq.\n      erewrite <-matchRegInPStateDom_addRegToPState; last eassumption.\n      by apply stateSplitsOn. }\n    rewrite ->HRtrue. rewrite sepSPC. by apply spec_frame. }\n  rewrite ->lentails_eq, ->!sepSPA, <-lentails_eq.\n  do 2 eexists. do 2 (split; first eassumption).\n  clear - HsPr.\n  exists (addRegToPState emptyPState r (s.(registers) r)).\n  exists (removeRegFromPState s' r).\n  split.\n  - erewrite <-matchRegInPStateDom_addRegToPState; last eassumption.\n    by apply stateSplitsOn.\n  - split.\n    + simpl. reflexivity.\n    + do 2 eexists. split; first by apply sa_unitI. simpl. done.\nQed.\n\n(* More concise formulation. Probably not very useful with the tactics in this\n   development. *)\nCorollary antiframe_register_spec_reads (r: AnyReg) P S:\n  regNotFree r P ->\n  AtContra S ->\n  |-- (S -->> safe @ P) <@ r? ->\n  S |-- safe @ P.\nProof.\n  rewrite /stateIsAny. rewrite <-spec_reads_ex.\n  move => HPr Hcontra H. apply: antiframe_register; first eassumption.\n  move => v. lforwardR H.\n  { apply lforallL with v. rewrite ->spec_reads_entails_at; last by apply _.\n    autorewrite with push_at. reflexivity. }\n  by apply limplValid.\nQed.\n\n\n(* Now follows lemmas for proving regNotFree. *)\n\nInstance regNotFree_lequiv r:\n  Proper (lequiv --> Basics.impl) (regNotFree r).\nProof.\n  rewrite /regNotFree /Basics.flip. by move => P P' ->.\nQed.\n\nLemma stateSplitsAs_move_register r v s:\n  s Registers r = Some v ->\n  stateSplitsAs s (addRegToPState emptyPState r v) (removeRegFromPState s r).\nProof.\n  move => Hsr.\n  rewrite /removeRegFromPState /restrictState /matchRegInPStateDom.\n  move => [] r'; try (destruct (s _ r'); tauto); [].\n  simpl. case Hr': (r == r') => /=.\n  + rewrite -(eqP Hr') Hsr /=. tauto.\n  + destruct (s Registers r'); tauto.\nQed.\n\n(* A predicate, here \"r?\", is _atomic_ when it cannot be divided across sepSP *)\nLemma stateAny_atomic (r: AnyReg) P Q:\n  (P ** Q) //\\\\ (r? ** ltrue) |--\n  (P //\\\\ (r? ** ltrue)) ** Q \\\\// P ** (Q //\\\\ (r? ** ltrue)).\nProof.\n  move => s [HPQ Hrtrue].\n  destruct HPQ as [sP [sQ [Hs_PQ [HsP HsQ]]]].\n  without loss : P Q sP sQ Hs_PQ HsP HsQ / sP Registers r = s Registers r.\n  { edestruct stateSplitsAs_reg_or with (r:=r) as [HrP | HrQ];\n      first apply Hs_PQ.\n    { apply; try eassumption. }\n    move/(_ Q P sQ sP). apply sa_mulC in Hs_PQ. move/(_ Hs_PQ HsQ HsP HrQ).\n    rewrite ->!lentails_eq. etransitivity; first eassumption. apply lorL.\n    - apply lorR2. by rewrite sepSPC.\n    - apply lorR1. by rewrite sepSPC.\n  }\n  move => HrP. left. exists sP, sQ. split; first done. split; last done.\n  split; first done. destruct Hrtrue as [sr [strue [Hs_r [[v Hsr] _]]]].\n  simpl in Hsr. exists sr. exists (removeRegFromPState sP r).\n  split; last first.\n  { split; last done. exists v. assumption. }\n  rewrite <-Hsr. apply stateSplitsAs_move_register. rewrite HrP.\n  move/stateSplitsAsIncludes: Hs_r => [Hs_r _].\n  erewrite <- Hs_r; first reflexivity. rewrite <-Hsr. by rewrite /= eq_refl.\nQed.\n\nLemma regNotFree_sepSP r P Q:\n  regNotFree r P -> regNotFree r Q -> regNotFree r (P ** Q).\nProof.\n  rewrite /regNotFree => HrNotInP HrNotInQ.\n  rewrite ->stateAny_atomic.\n  apply lorL; last first.\n  - rewrite ![(P ** Q) ** _]sepSPA. cancel2. cancel2. by apply landL2.\n  - rewrite ->stateAny_atomic. rewrite lor_sepSP. apply lorL.\n    + rewrite -{1}[P]empSPR. rewrite ->(ltrueR empSP).\n      rewrite ->HrNotInP. by ssimpl.\n    + rewrite -{1}[Q]empSPR. rewrite ->(ltrueR empSP).\n      rewrite ->HrNotInQ. by ssimpl.\nQed.\nHint Resolve regNotFree_sepSP : reg_not_in.\n\nLemma regNotFree_or r P Q:\n  regNotFree r P -> regNotFree r Q -> regNotFree r (P \\\\// Q).\nProof.\n  rewrite /regNotFree => HrNotInP HrNotInQ. rewrite lor_sepSP.\n  apply landAdj; apply lorL; apply limplAdj.\n  - rewrite lor_sepSP. by apply lorR1.\n  - rewrite lor_sepSP. by apply lorR2.\nQed.\nHint Resolve regNotFree_or : reg_not_in.\n\nLemma regNotFree_exists r T (P: T -> SPred):\n  (forall t, regNotFree r (P t)) -> regNotFree r (lexists P).\nProof.\n  rewrite /regNotFree => HrNotInP.\n  apply landAdj. sdestruct => t. apply limplAdj. ssplit. apply HrNotInP.\nQed.\nHint Resolve regNotFree_exists : reg_not_in.\n\n(* This definition is stronger than regNotFree but is often easier to prove.\n   It does not hold for P=ltrue. *)\nDefinition regMissingIn (r: AnyReg) (P: SPred) :=\n  P //\\\\ (r?  ** ltrue) |-- lfalse.\n\nLemma regMissingIn_regNotFree r P:\n  regMissingIn r P -> regNotFree r P.\nProof.\n  rewrite /regMissingIn /regNotFree => H.\n  rewrite ->stateAny_atomic. rewrite ->H.\n  apply lorL; first by ssimpl.\n  cancel2. by apply landL2.\nQed.\nHint Immediate regMissingIn_regNotFree : reg_not_in.\n\n(* This morphism is not available for regNotFree, and it makes an important\n   difference when dealing for spec_reads, whose definition contains lentails.\n *)\nInstance regMissingIn_lentails r:\n  Proper (lentails --> Basics.impl) (regMissingIn r).\nProof.\n  rewrite /regMissingIn /Basics.flip => P P' HP H. by rewrite ->HP.\nQed.\n\nInstance regMissingIn_lequiv r:\n  Proper (lequiv ==> iff) (regMissingIn r).\nProof.\n  move => P P' [HP HP']. split.\n  - by rewrite ->HP'.\n  - by rewrite <-HP.\nQed.\n\nLemma regMissingIn_empSP r:\n  regMissingIn r empSP.\nProof.\n  move => s [Hemp Hrtrue]. move/regAny_sub: Hrtrue => [vr Hsr].\n  rewrite /empSP /sepLogicOps /SABIOps /= in Hemp. destruct Hemp as [Hs _].\n  rewrite <-Hs in Hsr. discriminate.\nQed.\nHint Resolve regMissingIn_empSP : reg_not_in.\n\nLemma regMissingIn_false r:\n  regMissingIn r lfalse.\nProof.\n  by apply landL1.\nQed.\nHint Resolve regMissingIn_false : reg_not_in.\n\nLemma regNotFree_true r:\n  regNotFree r ltrue.\nProof.\n  rewrite /regNotFree. apply landL2. rewrite <-(ltrueR empSP) at 2. by ssimpl.\nQed.\nHint Resolve regNotFree_true : reg_not_in.\n\nLemma regNotFree_propand r p P:\n  regNotFree r P -> regNotFree r (p /\\\\ P).\nProof.\n  move => H. by apply regNotFree_exists.\nQed.\nHint Resolve regNotFree_propand : reg_not_in.\n\n(* I have not found modular proofs of regNotFree for lforall, //\\\\, -* and -->>.\n   Proofs exist for lforall and //\\\\ for a stronger definition: P is closed\n   under removal of r from its states: [P //\\\\ (r?  ** ltrue) |-- P ** r?].\n *)\n\nLemma regMissingIn_sepSP r P Q:\n  regMissingIn r P -> regMissingIn r Q -> regMissingIn r (P ** Q).\nProof.\n  rewrite /regMissingIn => HP HQ. rewrite ->stateAny_atomic. apply lorL.\n  - rewrite ->HP. by ssimpl.\n  - rewrite ->HQ. by ssimpl.\nQed.\nHint Resolve regMissingIn_sepSP : reg_not_in.\n\nLemma regMissingIn_exists r T (P: T -> SPred):\n  (forall t, regMissingIn r (P t)) -> regMissingIn r (lexists P).\nProof.\n  rewrite /regMissingIn => H. apply landAdj. apply lexistsL => t.\n  by apply limplAdj.\nQed.\nHint Resolve regMissingIn_exists : reg_not_in.\n\nLemma regMissingIn_propand r p P:\n  regMissingIn r P -> regMissingIn r (p /\\\\ P).\nProof.\n  move => H. by apply regMissingIn_exists.\nQed.\nHint Resolve regMissingIn_propand : reg_not_in.\n\nLemma regMissingIn_flag r (f: Flag) (v: FlagVal):\n  regMissingIn r (f ~= v).\nProof.\n  move => s [Hfv Hrtrue]. move/regAny_sub: Hrtrue => [vr Hsr].\n  simpl in Hfv. rewrite <-Hfv in Hsr. discriminate.\nQed.\nHint Resolve regMissingIn_flag : reg_not_in.\n\nLemma regMissingIn_byte r i v:\n  regMissingIn r (byteIs i v).\nProof.\n  move => s [Hiv Hrtrue]. move/regAny_sub: Hrtrue => [vr Hsr].\n  simpl in Hiv. rewrite <-Hiv in Hsr. discriminate.\nQed.\nHint Resolve regMissingIn_byte : reg_not_in.\n\nLemma regMissingIn_flagAny r (f: Flag):\n  regMissingIn r (f?).\nProof.\n  rewrite /stateIsAny. by auto with reg_not_in.\nQed.\nHint Resolve regMissingIn_flagAny : reg_not_in.\n\nLemma regMissingIn_reg (r r': AnyReg) (v: DWORD):\n  r != r' -> regMissingIn r (r' ~= v).\nProof.\n  move => Hrr' s [Hfv Hrtrue]. move/regAny_sub: Hrtrue => [vr Hsr].\n  simpl in Hfv. rewrite <-Hfv in Hsr. rewrite /addRegToPState in Hsr.\n  rewrite ifN_eqC in Hsr; last assumption. discriminate.\nQed.\nHint Resolve regMissingIn_reg : reg_not_in.\n\n(* Needed because the regMissingIn_reg is cost 1 and won't apply after Hint\n   Immediate. *)\nLemma regNotFree_reg (r r': AnyReg) (v: DWORD):\n  r != r' -> regNotFree r (r' ~= v).\nProof.\n  move => H. apply regMissingIn_regNotFree. auto with reg_not_in.\nQed.\nHint Resolve regNotFree_reg : reg_not_in.\n\nLemma regMissingIn_regAny r (r': AnyReg):\n  r != r' -> regMissingIn r (r'?).\nProof.\n  move => Hr'. rewrite /stateIsAny. by auto with reg_not_in.\nQed.\nHint Resolve regMissingIn_regAny : reg_not_in.\n\n(* Unfortunately we cannot prove this for general memIs since the memIs\n   definition does not limit the SPred predicate in any way. *)\nLemma regMissingIn_reader R {reader: Reader R} r i j (v: R) :\n  regMissingIn r (i -- j :-> v).\nProof.\n  rewrite readerMemIsSimpl. move: i j. induction reader => i j.\n  - rewrite /interpReader. by eauto with reg_not_in.\n  - rewrite /interpReader. destruct i; by eauto with reg_not_in.\n  - rewrite /interpReader. destruct i; by eauto with reg_not_in.\n  - rewrite /interpReader. by eauto with reg_not_in.\nQed.\nHint Resolve regMissingIn_reader : reg_not_in.\n\n(* TODO: prove base cases of regNotFree simpler *)\n(* TODO: extend antiframe to flags *)\n(* TODO: reg_not_in hints for forall, -->>, -*, ->> *)\n(* TODO: is the theorem strong enough to easily extend to multiple registers? *)\n(* TODO: corollary for basic *)\n(* TODO: extend to other RHS than [safe @ P]? The only property of [safe] we're\n   really using here is that it adds [** ltrue] _and nothing more_ to the frame.\n *)\n", "meta": {"author": "jbj", "repo": "x86proved", "sha": "d314fa6d23c064a2be4bf686ac7da16a591fda01", "save_path": "github-repos/coq/jbj-x86proved", "path": "github-repos/coq/jbj-x86proved/x86proved-d314fa6d23c064a2be4bf686ac7da16a591fda01/src/antiframe.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24118198136642008}}
{"text": "Require Import HoareDef IntroHeader IntroF1 IntroF2 SimModSem.\nImport Sep.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import Relation_Definitions.\n\n(*** TODO: export these in Coqlib or Universe ***)\nRequire Import Relation_Operators.\nRequire Import RelationPairs.\nFrom ITree Require Import\n     Events.MapDefault.\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Maps\n     Data.Map.FMapAList.\n\nRequire Import HTactics ProofMode.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\n\n\nSection SIMMODSEM.\n\n  Context `{Σ: GRA.t}.\n  Context `{@GRA.inG IRA.t Σ}.\n\n  Let W: Type := Any.t * Any.t.\n\n  Let wf: _ -> W -> Prop :=\n    @mk_wf\n      _\n      unit\n      (fun _ _ _ => ⌜True⌝%I)\n  .\n\n  Theorem correct: refines2 [IntroF1.F] [IntroF2.F].\n  Proof.\n    eapply adequacy_local2. econs; ss.\n    i. econstructor 1 with (wf:=wf) (le:=top2); et; swap 2 3.\n    { ss. }\n    { esplits. econs; ss. eapply to_semantic. iIntros \"H\". iSplits; ss. }\n\n    econs; ss. init. harg. mDesAll.\n    des; clarify. unfold fF, ccallU. steps. astart 10. force_r. exists x. steps. force_r; ss. steps.\n    unfold Ncall. steps. des_ifs.\n    - unfold ccallU. steps. acatch. des. hcall _ _ with \"*\"; auto.\n      { esplits; ss; et. }\n      steps. astop. ss. steps. mDesAll; clarify. rewrite Any.upcast_downcast. ss. steps.\n      force_r; ss. steps. force_l. esplits. steps. hret _; ss.\n    - steps. astop. steps. force_l. esplits. steps.\n      hret _; ss.\n  Unshelve. all: ss. all: try exact 0.\n  Qed.\n\nEnd SIMMODSEM.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/intro/IntroF12proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.24118198136642005}}
{"text": "Require Export VST.concurrency.paco.src.paconotation VST.concurrency.paco.src.pacotac VST.concurrency.paco.src.pacodef VST.concurrency.paco.src.pacotacuser.\nSet Implicit Arguments.\n\n(** ** Predicates of Arity 7\n*)\n\n(** 1 Mutual Coinduction *)\n\nSection Arg7_1.\n\nDefinition monotone7 T0 T1 T2 T3 T4 T5 T6 (gf: rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6) :=\n  forall x0 x1 x2 x3 x4 x5 x6 r r' (IN: gf r x0 x1 x2 x3 x4 x5 x6) (LE: r <7= r'), gf r' x0 x1 x2 x3 x4 x5 x6.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.\nVariable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.\nVariable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.\nVariable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.\nVariable gf : rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6.\nArguments gf : clear implicits.\n\nTheorem paco7_acc: forall\n  l r (OBG: forall rr (INC: r <7= rr) (CIH: l <_paco_7= rr), l <_paco_7= paco7 gf rr),\n  l <7= paco7 gf r.\nProof.\n  intros; assert (SIM: paco7 gf (r \\7/ l) x0 x1 x2 x3 x4 x5 x6) by eauto.\n  clear PR; repeat (try left; do 8 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco7_mon: monotone7 (paco7 gf).\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_mult_strong: forall r,\n  paco7 gf (upaco7 gf r) <7= paco7 gf r.\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco7_mult: forall r,\n  paco7 gf (paco7 gf r) <7= paco7 gf r.\nProof. intros; eapply paco7_mult_strong, paco7_mon; eauto. Qed.\n\nTheorem paco7_fold: forall r,\n  gf (upaco7 gf r) <7= paco7 gf r.\nProof. intros; econstructor; [ |eauto]; eauto. Qed.\n\nTheorem paco7_unfold: forall (MON: monotone7 gf) r,\n  paco7 gf r <7= gf (upaco7 gf r).\nProof. unfold monotone7; intros; destruct PR; eauto. Qed.\n\nEnd Arg7_1.\n\nHint Unfold monotone7.\nHint Resolve paco7_fold.\n\nArguments paco7_acc            [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_mon            [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_mult           [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_fold           [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_unfold         [ T0 T1 T2 T3 T4 T5 T6 ].\n\nInstance paco7_inst  T0 T1 T2 T3 T4 T5 T6 (gf : rel7 T0 T1 T2 T3 T4 T5 T6->_) r x0 x1 x2 x3 x4 x5 x6 : paco_class (paco7 gf r x0 x1 x2 x3 x4 x5 x6) :=\n{ pacoacc    := paco7_acc gf;\n  pacomult   := paco7_mult gf;\n  pacofold   := paco7_fold gf;\n  pacounfold := paco7_unfold gf }.\n\n(** 2 Mutual Coinduction *)\n\nSection Arg7_2.\n\nDefinition monotone7_2 T0 T1 T2 T3 T4 T5 T6 (gf: rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6) :=\n  forall x0 x1 x2 x3 x4 x5 x6 r_0 r_1 r'_0 r'_1 (IN: gf r_0 r_1 x0 x1 x2 x3 x4 x5 x6) (LE_0: r_0 <7= r'_0)(LE_1: r_1 <7= r'_1), gf r'_0 r'_1 x0 x1 x2 x3 x4 x5 x6.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.\nVariable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.\nVariable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.\nVariable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.\nVariable gf_0 gf_1 : rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6.\nArguments gf_0 : clear implicits.\nArguments gf_1 : clear implicits.\n\nTheorem paco7_2_0_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_0 <7= rr) (CIH: l <_paco_7= rr), l <_paco_7= paco7_2_0 gf_0 gf_1 rr r_1),\n  l <7= paco7_2_0 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco7_2_0 gf_0 gf_1 (r_0 \\7/ l) r_1 x0 x1 x2 x3 x4 x5 x6) by eauto.\n  clear PR; repeat (try left; do 8 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco7_2_1_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_1 <7= rr) (CIH: l <_paco_7= rr), l <_paco_7= paco7_2_1 gf_0 gf_1 r_0 rr),\n  l <7= paco7_2_1 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco7_2_1 gf_0 gf_1 r_0 (r_1 \\7/ l) x0 x1 x2 x3 x4 x5 x6) by eauto.\n  clear PR; repeat (try left; do 8 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco7_2_0_mon: monotone7_2 (paco7_2_0 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_2_1_mon: monotone7_2 (paco7_2_1 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_2_0_mult_strong: forall r_0 r_1,\n  paco7_2_0 gf_0 gf_1 (upaco7_2_0 gf_0 gf_1 r_0 r_1) (upaco7_2_1 gf_0 gf_1 r_0 r_1) <7= paco7_2_0 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_2_1_mult_strong: forall r_0 r_1,\n  paco7_2_1 gf_0 gf_1 (upaco7_2_0 gf_0 gf_1 r_0 r_1) (upaco7_2_1 gf_0 gf_1 r_0 r_1) <7= paco7_2_1 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco7_2_0_mult: forall r_0 r_1,\n  paco7_2_0 gf_0 gf_1 (paco7_2_0 gf_0 gf_1 r_0 r_1) (paco7_2_1 gf_0 gf_1 r_0 r_1) <7= paco7_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco7_2_0_mult_strong, paco7_2_0_mon; eauto. Qed.\n\nCorollary paco7_2_1_mult: forall r_0 r_1,\n  paco7_2_1 gf_0 gf_1 (paco7_2_0 gf_0 gf_1 r_0 r_1) (paco7_2_1 gf_0 gf_1 r_0 r_1) <7= paco7_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco7_2_1_mult_strong, paco7_2_1_mon; eauto. Qed.\n\nTheorem paco7_2_0_fold: forall r_0 r_1,\n  gf_0 (upaco7_2_0 gf_0 gf_1 r_0 r_1) (upaco7_2_1 gf_0 gf_1 r_0 r_1) <7= paco7_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco7_2_1_fold: forall r_0 r_1,\n  gf_1 (upaco7_2_0 gf_0 gf_1 r_0 r_1) (upaco7_2_1 gf_0 gf_1 r_0 r_1) <7= paco7_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco7_2_0_unfold: forall (MON: monotone7_2 gf_0) (MON: monotone7_2 gf_1) r_0 r_1,\n  paco7_2_0 gf_0 gf_1 r_0 r_1 <7= gf_0 (upaco7_2_0 gf_0 gf_1 r_0 r_1) (upaco7_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone7_2; intros; destruct PR; eauto. Qed.\n\nTheorem paco7_2_1_unfold: forall (MON: monotone7_2 gf_0) (MON: monotone7_2 gf_1) r_0 r_1,\n  paco7_2_1 gf_0 gf_1 r_0 r_1 <7= gf_1 (upaco7_2_0 gf_0 gf_1 r_0 r_1) (upaco7_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone7_2; intros; destruct PR; eauto. Qed.\n\nEnd Arg7_2.\n\nHint Unfold monotone7_2.\nHint Resolve paco7_2_0_fold.\nHint Resolve paco7_2_1_fold.\n\nArguments paco7_2_0_acc            [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_2_1_acc            [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_2_0_mon            [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_2_1_mon            [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_2_0_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_2_1_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_2_0_mult           [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_2_1_mult           [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_2_0_fold           [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_2_1_fold           [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_2_0_unfold         [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_2_1_unfold         [ T0 T1 T2 T3 T4 T5 T6 ].\n\nInstance paco7_2_0_inst  T0 T1 T2 T3 T4 T5 T6 (gf_0 gf_1 : rel7 T0 T1 T2 T3 T4 T5 T6->_) r_0 r_1 x0 x1 x2 x3 x4 x5 x6 : paco_class (paco7_2_0 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3 x4 x5 x6) :=\n{ pacoacc    := paco7_2_0_acc gf_0 gf_1;\n  pacomult   := paco7_2_0_mult gf_0 gf_1;\n  pacofold   := paco7_2_0_fold gf_0 gf_1;\n  pacounfold := paco7_2_0_unfold gf_0 gf_1 }.\n\nInstance paco7_2_1_inst  T0 T1 T2 T3 T4 T5 T6 (gf_0 gf_1 : rel7 T0 T1 T2 T3 T4 T5 T6->_) r_0 r_1 x0 x1 x2 x3 x4 x5 x6 : paco_class (paco7_2_1 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3 x4 x5 x6) :=\n{ pacoacc    := paco7_2_1_acc gf_0 gf_1;\n  pacomult   := paco7_2_1_mult gf_0 gf_1;\n  pacofold   := paco7_2_1_fold gf_0 gf_1;\n  pacounfold := paco7_2_1_unfold gf_0 gf_1 }.\n\n(** 3 Mutual Coinduction *)\n\nSection Arg7_3.\n\nDefinition monotone7_3 T0 T1 T2 T3 T4 T5 T6 (gf: rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6) :=\n  forall x0 x1 x2 x3 x4 x5 x6 r_0 r_1 r_2 r'_0 r'_1 r'_2 (IN: gf r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6) (LE_0: r_0 <7= r'_0)(LE_1: r_1 <7= r'_1)(LE_2: r_2 <7= r'_2), gf r'_0 r'_1 r'_2 x0 x1 x2 x3 x4 x5 x6.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.\nVariable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.\nVariable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.\nVariable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.\nVariable gf_0 gf_1 gf_2 : rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6.\nArguments gf_0 : clear implicits.\nArguments gf_1 : clear implicits.\nArguments gf_2 : clear implicits.\n\nTheorem paco7_3_0_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_0 <7= rr) (CIH: l <_paco_7= rr), l <_paco_7= paco7_3_0 gf_0 gf_1 gf_2 rr r_1 r_2),\n  l <7= paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco7_3_0 gf_0 gf_1 gf_2 (r_0 \\7/ l) r_1 r_2 x0 x1 x2 x3 x4 x5 x6) by eauto.\n  clear PR; repeat (try left; do 8 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco7_3_1_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_1 <7= rr) (CIH: l <_paco_7= rr), l <_paco_7= paco7_3_1 gf_0 gf_1 gf_2 r_0 rr r_2),\n  l <7= paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco7_3_1 gf_0 gf_1 gf_2 r_0 (r_1 \\7/ l) r_2 x0 x1 x2 x3 x4 x5 x6) by eauto.\n  clear PR; repeat (try left; do 8 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco7_3_2_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_2 <7= rr) (CIH: l <_paco_7= rr), l <_paco_7= paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 rr),\n  l <7= paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 (r_2 \\7/ l) x0 x1 x2 x3 x4 x5 x6) by eauto.\n  clear PR; repeat (try left; do 8 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco7_3_0_mon: monotone7_3 (paco7_3_0 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_3_1_mon: monotone7_3 (paco7_3_1 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_3_2_mon: monotone7_3 (paco7_3_2 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_3_0_mult_strong: forall r_0 r_1 r_2,\n  paco7_3_0 gf_0 gf_1 gf_2 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_3_1_mult_strong: forall r_0 r_1 r_2,\n  paco7_3_1 gf_0 gf_1 gf_2 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_3_2_mult_strong: forall r_0 r_1 r_2,\n  paco7_3_2 gf_0 gf_1 gf_2 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco7_3_0_mult: forall r_0 r_1 r_2,\n  paco7_3_0 gf_0 gf_1 gf_2 (paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco7_3_0_mult_strong, paco7_3_0_mon; eauto. Qed.\n\nCorollary paco7_3_1_mult: forall r_0 r_1 r_2,\n  paco7_3_1 gf_0 gf_1 gf_2 (paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco7_3_1_mult_strong, paco7_3_1_mon; eauto. Qed.\n\nCorollary paco7_3_2_mult: forall r_0 r_1 r_2,\n  paco7_3_2 gf_0 gf_1 gf_2 (paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco7_3_2_mult_strong, paco7_3_2_mon; eauto. Qed.\n\nTheorem paco7_3_0_fold: forall r_0 r_1 r_2,\n  gf_0 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco7_3_1_fold: forall r_0 r_1 r_2,\n  gf_1 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco7_3_2_fold: forall r_0 r_1 r_2,\n  gf_2 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco7_3_0_unfold: forall (MON: monotone7_3 gf_0) (MON: monotone7_3 gf_1) (MON: monotone7_3 gf_2) r_0 r_1 r_2,\n  paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 <7= gf_0 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone7_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco7_3_1_unfold: forall (MON: monotone7_3 gf_0) (MON: monotone7_3 gf_1) (MON: monotone7_3 gf_2) r_0 r_1 r_2,\n  paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 <7= gf_1 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone7_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco7_3_2_unfold: forall (MON: monotone7_3 gf_0) (MON: monotone7_3 gf_1) (MON: monotone7_3 gf_2) r_0 r_1 r_2,\n  paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 <7= gf_2 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone7_3; intros; destruct PR; eauto. Qed.\n\nEnd Arg7_3.\n\nHint Unfold monotone7_3.\nHint Resolve paco7_3_0_fold.\nHint Resolve paco7_3_1_fold.\nHint Resolve paco7_3_2_fold.\n\nArguments paco7_3_0_acc            [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_1_acc            [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_2_acc            [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_0_mon            [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_1_mon            [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_2_mon            [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_0_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_1_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_2_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_0_mult           [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_1_mult           [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_2_mult           [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_0_fold           [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_1_fold           [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_2_fold           [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_0_unfold         [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_1_unfold         [ T0 T1 T2 T3 T4 T5 T6 ].\nArguments paco7_3_2_unfold         [ T0 T1 T2 T3 T4 T5 T6 ].\n\nInstance paco7_3_0_inst  T0 T1 T2 T3 T4 T5 T6 (gf_0 gf_1 gf_2 : rel7 T0 T1 T2 T3 T4 T5 T6->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6 : paco_class (paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6) :=\n{ pacoacc    := paco7_3_0_acc gf_0 gf_1 gf_2;\n  pacomult   := paco7_3_0_mult gf_0 gf_1 gf_2;\n  pacofold   := paco7_3_0_fold gf_0 gf_1 gf_2;\n  pacounfold := paco7_3_0_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco7_3_1_inst  T0 T1 T2 T3 T4 T5 T6 (gf_0 gf_1 gf_2 : rel7 T0 T1 T2 T3 T4 T5 T6->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6 : paco_class (paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6) :=\n{ pacoacc    := paco7_3_1_acc gf_0 gf_1 gf_2;\n  pacomult   := paco7_3_1_mult gf_0 gf_1 gf_2;\n  pacofold   := paco7_3_1_fold gf_0 gf_1 gf_2;\n  pacounfold := paco7_3_1_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco7_3_2_inst  T0 T1 T2 T3 T4 T5 T6 (gf_0 gf_1 gf_2 : rel7 T0 T1 T2 T3 T4 T5 T6->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6 : paco_class (paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6) :=\n{ pacoacc    := paco7_3_2_acc gf_0 gf_1 gf_2;\n  pacomult   := paco7_3_2_mult gf_0 gf_1 gf_2;\n  pacofold   := paco7_3_2_fold gf_0 gf_1 gf_2;\n  pacounfold := paco7_3_2_unfold gf_0 gf_1 gf_2 }.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/concurrency/paco_old/src/paco7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.2411481104900351}}
{"text": "\nCoInductive cotrue : Set := \n| d : cotrue -> cotrue.\n\nAxiom loop : cotrue -> cotrue -> cotrue.\n\nLemma test : cotrue.\nProof.\n  refine (cofix x (a : cotrue) : cotrue := (d (loop (d (x a)) (d (x a))))).\nDefined. ", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/Loop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.24114810143793997}}
{"text": "(* =========================================================== *)\n(* Static interpretation relation and the proof of termination *)\n(* (the normalisation part of the Proposition 6.1)             *)\n(* =========================================================== *)\n\nRequire Import String.\nRequire Import Vector.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Program.Wf Coq.Program.Program Coq.Program.Tactics.\nRequire Import ProofIrrelevance FunctionalExtensionality.\n\nRequire Import Basics.\nRequire Import Syntax.\nRequire Import SemObjects.\nRequire Import Target.\nRequire Import IntObjects.\nRequire Import ElabCore.\nRequire Import MiniElab.\nRequire Import CpdtTactics.\nRequire Import CompCore.\nRequire Import CustomTactics.\n\nRequire Import NomEnv.\n\nImport PermIEnvLabel.\n\nOpen Scope IEnv_scope.\n\n(* -------------------------------------------------------------------- *)\n(* Static interpretation rules for modules expressions and declarations *)\n(* -------------------------------------------------------------------- *)\n\n(* Some issues related to bound variables are left for further development *)\nInductive Mexp_int : IEnv -> mexp -> TSet -> IMod -> c -> Prop :=\n| Bra_mexp_int : forall IE mdec N IE' c,\n    Mdec_int IE mdec N IE' c ->\n    Mexp_int IE (Bra_mexp mdec) N (INonParamMod IE') c\n| Mid_mexp_int : forall IE mid IM,\n    lookMidIE mid IE = Some IM ->\n    Mexp_int IE (Mid_mexp mid) emptyTSet IM Emp_c\n| Prj_mexp_int : forall IE mexp mid N c IE' IM,\n    Mexp_int IE mexp N (INonParamMod IE') c ->\n    lookMidIE mid IE' = Some IM ->\n    Mexp_int IE (Prj_mexp mexp mid) N IM c\n| Funct_mexp_int : forall IE0 mid mty mexp E0 M E,\n    erasure_IEnv IE0 E0 ->\n    Mty_melab E0 mty (MSigma emptyTSet (NonParamMod E)) ->\n    Mexp_melab (addEnvMid mid (NonParamMod E) E0) mexp emptyTSet M ->\n    Mexp_int IE0 (Funct_mexp mid mty mexp)\n             emptyTSet (IFtor IE0 emptyTSet E (MSigma emptyTSet M) mid mexp) Emp_c\n| App_mexp_int : forall IE0 longmid mexp mexp' IE IE' IE'' IE''' N N' c c' E' E'' mid,\n    lookLongIMid longmid IE = Some (IFtor IE0 emptyTSet E' (MSigma emptyTSet (NonParamMod E'')) mid mexp') ->\n    Mexp_int IE mexp N (INonParamMod IE') c ->\n    filtering_IEnv IE' E' IE'' ->\n    Mexp_int (addIEnvMid mid (INonParamMod IE'') IE0) mexp' N' IE''' c' ->\n    Mexp_int IE (App_mexp longmid mexp) (unionTSet N N') IE''' (Seq_c c c')\nwith Mdec_int : IEnv -> mdec -> TSet -> IEnv -> c -> Prop :=\n| Dec_mdec_int : forall IE dec N IE' c,\n    Dec_comp IE dec N IE' c ->\n    Mdec_int IE (Dec_mdec dec) N IE' c\n| Type_mdec_int : forall IE tid ty Ty E,\n    erasure_IEnv IE E ->\n    Ty_elab E ty Ty ->\n    Mdec_int IE (Type_mdec tid ty) emptyTSet (addIEnvTid tid Ty emptyIEnv) Emp_c\n| Mod_mdec_int : forall IE mid mexp N IM c,\n    Mexp_int IE mexp N IM c ->\n    Mdec_int IE (Mod_mdec mid mexp) N (addIEnvMid mid IM emptyIEnv) c\n| ModTyp_mdec_int : forall E IE mtid mty S,\n    Mty_melab E mty S ->\n    erasure_IEnv IE E ->\n    Mdec_int IE (ModTyp_mdec mtid mty) emptyTSet (addIEnvTmid mtid S emptyIEnv) Emp_c\n| Open_mdec_int : forall IE mexp N IE' c,\n    Mexp_int IE mexp N (INonParamMod IE') c ->\n    Mdec_int IE (Open_mdec mexp) N IE' c\n| Seq_mdec_int : forall IE mdec1 mdec2 N1 N2 IE1 IE2 c1 c2,\n    Mdec_int IE mdec1 N1 IE1 c1 ->\n    Mdec_int (plusIEnvIEnv IE IE1) mdec2 N2 IE2 c2 ->\n    (* (N1 # N2)%S -> *)\n    (* (N1 # .fvs E)%S -> *)\n    Mdec_int IE (Seq_mdec mdec1 mdec2) (unionTSet N1 N2) (plusIEnvIEnv IE1 IE2) (Seq_c c1 c2)\n| IEmp_mdec_int : forall IE,\n    Mdec_int IE Emp_mdec emptyTSet emptyIEnv Emp_c.\n\nScheme int_mexp_mut :=\n  Induction for Mexp_int Sort Prop\n  with int_mdec_mut := Induction for Mdec_int Sort Prop.\n\nCombined Scheme int_mut from int_mexp_mut, int_mdec_mut.\n\nHint Resolve erasure_IEnv_tid_extend erasure_IEnv_tid_extend erasure_IEnv_empty.\n\nImport EnvMod.\n\n(* ----------------------------------------------------------- *)\n(* Consistency relation between elaboration environments and   *)\n(* interpretation environments.                                *)\n(* ----------------------------------------------------------- *)\n\nDefinition consistent_IVEnv (VE:VEnv) (IVE:IVEnv) : Prop :=\n   forall k t, (forall l, look k IVE = Some (l,t) -> look k VE = Some t) /\\\n               (look k VE = Some t -> exists l, look k IVE = Some (l,t)).\n\nNotation Vec := Vector.t.\nImport VectorNotations.\nModule VE := EnvMod.VecEnv.\n\nLocal Coercion _to {A} := SemObjects.EnvMod.VecEnv._to (A:=A).\nLocal Coercion _from {A} := SemObjects.EnvMod.VecEnv._from (A:=A).\n\n(** Consistency logical relation is defined by mutual recursion on\n    the structure of the elaboration environments (semantic objects) *)\nFixpoint consistent_IEnv (E:Env) (IE:IEnv) : Prop :=\n  match E, IE with\n    EnvCtr TE VE ME MTE, IEnvCtr TE' IVE IME MTE' =>\n    TE = TE' /\\ consistent_IVEnv VE IVE /\\ consistent_IMEnv ME IME /\\ MTE = MTE'\n  end\nwith consistent_IMEnv (ME:MEnv) (IME:IMEnv) : Prop :=\n  match ME, IME with\n    MEnvCtr me, IMEnvCtr ime =>\n    dom (SemObjects.VE._to me) = dom (SemObjects.VE._to ime) /\\\n    match me,ime with\n      (* NOTE : instead of forcing two vectors to be of the same length we\n         just return False in case if vectors are not aligned *)\n      VecEnv.mkVecEnv _  nn (exist _ ks _) vs,\n      VecEnv.mkVecEnv _  nn' (exist _ ks' _) vs' =>\n      (* We would like to use [VecEnv.Foralls.Forall2_fix consistent_IMod nn nn' vs vs']\n         here, but unfortunately, this doesn't work in this situation.\n         Probably, Coq doesn't unfold [Forall2_fix] here to see, that the\n         argument is decreasing. Though, sometimes Coq does that, see\n         definition of [ntsize] in Section 2.8 of CPDT *)\n      (fix con_step {n n'} (l : Vec Mod n) (ll : Vec IMod n') : Prop :=\n         match l,ll with\n         | [],[] => True\n         | m :: tl, im :: tl'  =>\n           con_step tl tl' /\\  consistent_IMod m im\n         | _,_ => False\n         end) nn nn' vs vs'\n    end\n  end\nwith consistent_IMod (M:Mod) (IM:IMod) : Prop :=\n  match M with\n    NonParamMod E =>\n    match IM with\n      INonParamMod IE => consistent_IEnv E IE\n    | IFtor _ _ _ _ _ _ => False\n    end\n  | Ftor T0 E (MSigma T M) =>\n    exists IE0 mid mexp,\n    IM = IFtor IE0 T0 E (MSigma T M) mid mexp\n    /\\ forall IE, consistent_IEnv E IE ->\n                  exists N IM c,\n                    (Mexp_int (addIEnvMid mid (INonParamMod IE) IE0) mexp N IM c\n                     /\\ consistent_IMod M IM)\n  end.\n\nImport VecEnv.Foralls.\n\n\n(* ----------------------- *)\n(* Facts about consistency *)\n(* ----------------------- *)\n\nLemma consistent_look_mid': forall mid IME ME M,\n    consistent_IMEnv ME IME ->\n    (lookMid mid ME = Some M) ->\n    exists IM, lookIMid mid IME = Some IM /\\ consistent_IMod M IM.\nProof.\n  intros until M. intros Hcim Hmid. destruct ME, IME. simpl in *.\n  destruct v0. destruct v.\n  destruct keys,keys0. simpl in *.\n  unfold dom,En.elements,En.Raw.elements in Hcim. simpl in *.\n  generalize dependent x.  generalize dependent vals.\n  generalize dependent v_size. generalize dependent v_size0.\n  induction vals0; intros; dependent destruction x0.\n  - crush. tryfalse.\n  - destruct vals; dependent destruction x.\n    + simpl in *. destruct Hcim. tryfalse.\n    + destruct Hcim as [Hdom Tl]. destruct Tl as [Heq Hcm].\n      unfold look,En.find in *. simpl in *.\n      inversion Hdom. subst.\n      remember (Key.compare mid h2) as mid_comp.\n      destruct mid_comp.\n      * tryfalse.\n      * inversion Hmid. subst.\n        exists h1;crush.\n      * inversion v0. dependent destruction H2.\n        inversion v. dependent destruction H2.\n        apply IHvals0 with (x0:=x0); auto.\nQed.\n\nLemma consistent_look_mid: forall IE E M mid,\n    consistent_IEnv E IE ->\n    (lookMidE mid E = Some M) ->\n    exists IM, lookMidIE mid IE = Some IM /\\ consistent_IMod M IM.\nProof.\n  intros.\n  destruct E,IE. simpl in *.\n  destruct H as [Heq Tl]. destruct Tl as [Hciv Tl]. destruct Tl as [Hcm Hmeq]. subst.\n  eapply consistent_look_mid'; eauto.\nQed.\n\nLemma consistent_look_longvid: forall IE E t longvid,\n    consistent_IEnv E IE ->\n    (lookLongVid longvid E = Some t) ->\n    exists l, lookLongIVid longvid IE = Some (l,t).\nProof.\n  intros.\n  generalize dependent IE. generalize dependent E.\n  induction longvid.\n  - intros. unfold consistent_IEnv in H. destruct E. destruct IE.\n    destruct H as [eq H]. destruct H as [H2 x].\n    clear x. unfold consistent_IVEnv in H2. subst.\n    rename t1 into s.\n    rename t0 into t.\n    assert (H2':=H2 s t). destruct H2'. clear H.\n    crush.\n  - intros. simpl in *.\n    destruct E, IE. simpl in *.\n    rename t1 into s.\n    remember (lookMid s m) as opt_mod. destruct opt_mod as [mod | ];tryfalse.\n    destruct mod; tryfalse.\n    destruct H as [Heqt tl]. destruct tl as [Hciv tl]. destruct tl as [Hcim Heqm]. subst.\n    symmetry in Heqopt_mod.\n    assert (H' : exists IM, lookIMid s i0 = Some IM /\\ consistent_IMod (NonParamMod e) IM).\n    intros. eapply consistent_look_mid'; eauto.\n    destruct H' as [IM Hc]. destruct Hc as [Hmid Hcmod]. rewrite Hmid. destruct IM;tryfalse.\n    simpl in Hcmod.\n    eapply IHlongvid;eauto.\nQed.\n\n\nLemma consistent_look_longmid: forall IE E M longmid,\n    consistent_IEnv E IE ->\n    (lookLongMid longmid E = Some M) ->\n    exists IM, lookLongIMid longmid IE = Some IM /\\ consistent_IMod M IM.\nProof.\n  intros.\n  generalize dependent E. generalize dependent IE.\n  induction longmid.\n  - intros.\n    destruct E. destruct IE. simpl in *.\n    destruct H as [Heqt H]. destruct H as [H2 x].\n    destruct x as [Hcim Heqm].\n    eapply consistent_look_mid';eauto.\n  - intros. simpl in *.\n    destruct E. destruct IE. simpl in *.\n    destruct H as [Heqt H]. destruct H as [H2 x].\n    destruct x as [Hcim Heqm]. subst.\n    destruct (lookMid t0 m) eqn:Hlook; tryfalse. destruct m0;tryfalse.\n    assert (H' : exists IM, lookIMid t0 i0 = Some IM /\\ consistent_IMod (NonParamMod e) IM).\n    eapply consistent_look_mid'; eauto.\n    destruct H' as [IM Hc]. destruct Hc as [Hmid Hcmod]. rewrite Hmid. destruct IM;tryfalse.\n    eapply IHlongmid;eauto.\nQed.\n\nLemma consistent_IEnv_extend: forall IE E t l s,\n  consistent_IEnv E IE -> consistent_IEnv (addEnvVid s t E) (addIEnvVid s (l,t) IE).\nProof.\n  intros.\n  destruct E,IE. crush.\n  destruct v,i; simpl in *. unfold consistent_IVEnv in *.\n  intros. split.\n  + intros l0 H0. unfold look in *.\n    rewrite FM.P.F.add_o in H0.\n    destruct (FM.P.F.eq_dec s k).\n    * inversion H0. subst.\n      apply add_lookup.\n    * destruct (H k t1) as [Hl Hr].\n      rewrite FM.P.F.add_neq_o;auto. eapply Hl;eauto.\n  + rewrite FM.P.F.add_o.\n    destruct (FM.P.F.eq_dec s k).\n    * exists l. subst. rewrite add_lookup in *. inversion H0.\n      subst. reflexivity.\n    * intros H'. unfold look in *. destruct (H k t1) as [Hl Hr].\n       rewrite FM.P.F.add_neq_o;auto.\nQed.\n\nLemma consistent_IEnv_tid_extend: forall IE E t s,\n  consistent_IEnv E IE -> consistent_IEnv (addEnvTid s t E) (addIEnvTid s t IE).\nProof.\n  intros.\n  destruct E,IE. crush.\nQed.\n\nLemma consistent_IEnv_mtid_extend: forall IE E t s,\n  consistent_IEnv E IE -> consistent_IEnv (addEnvMtid s t E) (addIEnvTmid s t IE).\nProof.\n  intros.\n  destruct E,IE. crush.\nQed.\n\n\nSet Printing Coercions.\n\n(* NOTE : We prevent functions back and forth between environment the representations\n   from unfolding and try just to use the fact that it is an isomorphism *)\nArguments SemObjects.VE._from A oe : simpl never.\nArguments SemObjects.VE._to A ve : simpl never.\nArguments SemObjects.VE.fromOrdEnv A oe : simpl never.\nArguments SemObjects.VE.toOrdEnv A ve : simpl never.\n\nLemma consistent_IEnv_mid_extend: forall IE E M IM s,\n    consistent_IEnv E IE -> consistent_IMod M IM ->\n    consistent_IEnv (addEnvMid s M E) (addIEnvMid s IM IE).\nProof.\n  intros.\n  destruct E,IE. destruct m,i0. simpl in *.\n  destruct H as [Ht Htl]. destruct Htl as [Hc Htl].\n  destruct Htl as [Ht' Htl'].\n  rewrite <- (Forall2_fix_fold_unfold consistent_IMod) in *.\n  rewrite <- (ForallEnv2_fold_unfold consistent_IMod) in *.\n  (* NOTE : here we use an alternative variant of Lemma ForallEnv2_fold_unfold,\n     because pattern-matching gets reduced. *)\n  erewrite <- (ForallEnv2_fold_unfold' consistent_IMod);eauto.\n  rewrite SemObjects.VE.Foralls.ForallEnv2_fix_EnvRel_iff in *;auto.\n  rewrite SemObjects.VE.Foralls.ForallEnv2_fix_EnvRel_iff';eauto; try reflexivity.\n  intuition;auto.\n  repeat (rewrite VecEnv.toOrdEnv_fromOrdEnv_inv).\n  unfold EnvRel.\n  intuition;subst;simpl in *.\n  + inversion Ht'. destruct (H1 k) as [L R].\n    rewrite FM.P.F.add_in_iff in *. intuition;auto.\n  + inversion Ht'. destruct (H1 k) as [L R].\n    rewrite FM.P.F.add_in_iff in *. intuition;auto.\n  + inversion Ht'.\n    rename s into k'.\n    rewrite FM.P.F.add_o in *.\n    destruct (FM.P.F.eq_dec k' k).\n    * assert (M = v2) by congruence. assert (IM = v') by congruence. subst. assumption.\n    * apply (H3 k);auto.\nQed.\n\nLemma consistent_IEnv_empty: consistent_IEnv emptyEnv emptyIEnv.\nProof.\n  constructor. constructor. split.\n  - unfold consistent_IVEnv; crush;tryfalse.\n  - crush. unfold emptyMTEnv. f_equal. unfold SemObjects.VE.ve_empty. compute. f_equal.\n    f_equal. apply proof_irrelevance.\nQed.\n\nLemma consistent_IVEnv_plus e e' ie ie' :\n  consistent_IVEnv e ie -> consistent_IVEnv e' ie'\n  -> consistent_IVEnv (e ++ e') (ie ++ ie').\nProof.\n  intros H1 H2.\n  unfold consistent_IVEnv in *.\n  split.\n  + intros l Ht0.\n    rewrite <- FM.P.F.find_mapsto_iff in *.\n    rewrite FM.P.update_mapsto_iff in *.\n    destruct Ht0.\n    * destruct (H2 k t0). rewrite FM.P.F.find_mapsto_iff in *. left. eauto.\n    * right. destruct H. split.\n      ** destruct (H1 k t0). rewrite FM.P.F.find_mapsto_iff in *. eauto.\n      ** unfold not. intro He'. apply H0.\n         inversion He' as [v Hv].\n         assert (Hv' : En.MapsTo k v e') by auto.\n         rewrite FM.P.F.find_mapsto_iff in Hv'.\n         destruct (H2 k v) as [L R].\n         assert (Hex := R Hv'). destruct Hex as [l' Hlv].\n         apply En.find_2 in Hlv. apply MapsTo_In in Hlv. assumption.\n  + intros Ht0.\n    rewrite <- FM.P.F.find_mapsto_iff in *.\n    rewrite FM.P.update_mapsto_iff in *.\n    destruct Ht0.\n    * rewrite FM.P.F.find_mapsto_iff in *.\n      destruct (H2 k t0) as [L R]. destruct (R H) as [l Hlt0].\n      exists l.\n      rewrite <- FM.P.F.find_mapsto_iff in *.\n      rewrite FM.P.update_mapsto_iff in *.\n      left. auto.\n    * destruct H as [He Hne'].\n      rewrite FM.P.F.find_mapsto_iff in *.\n      destruct (H1 k t0) as [L R]. destruct (R He) as [l Hlt0].\n      exists l.\n      rewrite <- FM.P.F.find_mapsto_iff in *.\n      rewrite FM.P.update_mapsto_iff in *.\n      right. split.\n      ** assumption.\n      ** unfold not. intro He'. apply Hne'.\n         inversion He' as [v Hv].\n         assert (Hv' : En.MapsTo k v ie') by auto.\n         rewrite FM.P.F.find_mapsto_iff in Hv'.\n         destruct v as [l' t'].\n         destruct (H2 k t') as [L' R'].\n         assert (Ht' := L' _ Hv').\n         rewrite <- FM.P.F.find_mapsto_iff in Ht'. apply MapsTo_In in Ht'.\n         assumption.\nQed.\n\nLemma consistent_IEnv_plus: forall IE1 E1 IE2 E2,\n    consistent_IEnv E1 IE1 -> consistent_IEnv E2 IE2 ->\n    consistent_IEnv (plusEnvEnv E1 E2) (plusIEnvIEnv IE1 IE2).\nProof.\n  intros.\n  destruct E1,IE1,E2,IE2. destruct m,m0,m2,m3,i0,m1,i2,m4. simpl in *.\n  destruct H0 as [Ht Htl]. destruct Htl as [Hc Htl].\n  destruct H as [Ht' Htl']. destruct Htl' as [Hc' Htl'].\n  split. congruence.\n  split. apply consistent_IVEnv_plus; auto.\n  (* We are switching to the \"extensional\" representation to be able to\n     use properties of environments in abstract way, without\n     looking on the concrete representation *)\n  rewrite <- (Forall2_fix_fold_unfold consistent_IMod) in *.\n  rewrite <- (ForallEnv2_fold_unfold consistent_IMod) in *.\n  rewrite ForallEnv2_fix_EnvRel_iff in *.\n  repeat (rewrite VecEnv.toOrdEnv_fromOrdEnv_inv).\n  (* ------------------------------------------------------ *)\n  unfold EnvRel in *.\n  intuition; subst.\n  + inversion H0. inversion H2. subst. clear H0. clear H2.\n    rewrite FM.P.update_in_iff in *.\n    destruct H1.\n    * left. rewrite <- H3. auto.\n    * right. rewrite <- H. auto.\n  + inversion H0. inversion H2. subst. clear H0. clear H2.\n    rewrite FM.P.update_in_iff in *.\n    destruct H1.\n    * left. rewrite H3. auto.\n    * right. rewrite H. auto.\n  + inversion H0. inversion H2. subst. clear H0. clear H2.\n    apply En.find_2 in H1. apply En.find_2 in H6.\n    rewrite FM.P.update_mapsto_iff in *.\n    destruct H1,H6.\n    * apply (H5 k); apply En.find_1; assumption.\n    * destruct H1. apply (H5 k).\n      ** apply En.find_1. assumption.\n      ** destruct (H k) as [L R].\n         assert (H' := L (MapsTo_In H0)). exfalso. auto.\n    * destruct H0. apply (H4 k).\n      ** apply En.find_1. assumption.\n      ** destruct (H k) as [L R].\n         assert (H' := R (MapsTo_In H1)). exfalso. auto.\n    * destruct H0,H1; apply (H4 k); auto.\n  + inversion H0. inversion H2. subst. clear H0. clear H2. reflexivity.\nQed.\n\nLemma consistent_ienv_imod_lem : forall ie e,\n    consistent_IEnv e ie -> consistent_IMod (NonParamMod e) (INonParamMod ie).\nProof.\n  crush.\nQed.\n\nLemma consistent_imod_ienv_lem : forall ie e,\n    consistent_IMod (NonParamMod e) (INonParamMod ie) -> consistent_IEnv e ie.\nProof.\n  crush.\nQed.\n\nLemma consistent_imod_uniform : forall x E,\n  consistent_IMod (NonParamMod E) x  -> exists IE, x = INonParamMod IE.\nProof.\n  intros. destruct x; exists i; crush.\nQed.\n\nLemma consistent_imod_uniform_ftor : forall T IM E MS,\n  consistent_IMod (Ftor T E MS) IM  -> exists IE T' E' MS' mid mexp, IM = IFtor IE T' E' MS' mid mexp.\nProof.\n  intros. destruct IM.\n  - destruct MS. simpl in *. do 4 destruct H. tryfalse.\n  - destruct MS. simpl in *. do 4 destruct H. inversion H; subst. repeat eexists; eauto.\nQed.\n\nLemma EnvRel_unmatched_size {A B} (ve : VecEnv.VecEnv B) (P : A -> B -> Prop) :\n  ve <> empty -> ~ EnvRel P empty ve.\nProof.\n  intro Hneq.\n  remember (_to ve) as E.\n  destruct ve. destruct keys. simpl in *.\n  unfold not. intro.\n  destruct vals.\n  * apply Hneq. f_equal. dependent destruction x. f_equal. apply proof_irrelevance.\n  * unfold EnvRel in *. destruct H. dependent destruction x.\n    destruct (H h) as [L R].\n    assert (Hin : In B h E). subst. unfold In,En.In. simpl. unfold to_list.\n    unfold En.Raw.PX.In. eexists. econstructor. eauto.\n    assert (Hfail := R Hin). inversion Hfail as [a Hfail']. unfold empty in *. simpl in *.\n    inversion Hfail'.\nQed.\n\nLemma Forall_look_nested_Forall2 {n A B} (vs : Vec A n) (vs' : Vec B n)\n      (P : A -> B -> Prop) :\n  Forall (fun v => Forall (P v) vs') vs ->\n  Forall2 P vs vs'.\nProof.\n  intro H.\n    generalize dependent vs'.\n    dependent induction vs.\n    * dependent destruction vs'; constructor.\n    * intros vs' H. dependent destruction vs'.\n      constructor.\n      ** inversion H. dependent destruction H2. inversion H3.\n         *** subst. auto.\n      ** apply IHvs. inversion H. dependent destruction H2.\n         inversion H3. dependent destruction H2.\n         eapply Forall_nested_cons. eauto.\nQed.\n\nLemma consistent_to_erasure : forall E IE,\n    consistent_IEnv E IE -> erasure_IEnv IE E.\nProof.\n  (* We do not introduce last hypothesis, otherwise\n     application of the mutual induction principle fails *)\n  intros E IE.\n  (* It's important to keep E abstracted *)\n  generalize dependent E.\n  induction IE using IEnv_mut with\n      (P0 := fun ime => forall me', consistent_IMEnv (MEnvCtr me') ime\n                        -> erasure_IMEnv ime (MEnvCtr me'))\n      (P1 := fun im => forall m, consistent_IMod m im ->\n                 erasure_IMod im m); intro E.\n  + crush. destruct E as [te ve me mte]. simpl in H. intuition. subst.\n    destruct me. constructor; auto.\n  + intro Hc.\n    assert (Hc' := Hc). simpl in *.\n    destruct Hc as [Hdom Hfix].\n    assert (HH : EnvRel (fun (im : IMod) (m : Mod)  =>\n                            consistent_IMod m im -> erasure_IMod im m)\n           (_to t0) (_to E)).\n    apply (Forall_EnvRel (eq_sym Hdom)).\n    apply H.\n    (*TODO: move rewrites below to a custom tactic *)\n    rewrite <- (Forall2_fix_fold_unfold consistent_IMod) in Hc'.\n    rewrite <- (ForallEnv2_fold_unfold consistent_IMod) in Hc'.\n    rewrite ForallEnv2_fix_EnvRel_iff in Hc'.\n    destruct t0. destruct E. destruct keys,keys0.\n    constructor. simpl in *.\n    destruct HH as [Hin He].\n    split;auto.\n    intros. apply He with (k:=k); auto.\n    destruct Hc' as [Hin' Hcon]. apply Hcon with (k:=k); auto.\n  + intros Hc. destruct E.\n    * constructor. simpl in Hc. apply IHIE;auto.\n    * simpl in *. destruct m. destruct Hc. destruct H. destruct H. destruct H. tryfalse.\n  + intros Hc. destruct E.\n    * tryfalse.\n    * simpl in Hc. destruct m1.\n      destruct Hc. destruct H. destruct H. destruct H.\n      inversion H. subst. constructor.\nQed.\n\nLemma consistent_imod_uniform_ftor2 : forall T T' IM E M,\n    consistent_IMod (Ftor T E (MSigma T' M)) IM ->\n    exists IE mid mexp, IM = IFtor IE T E (MSigma T' M) mid mexp /\\\n                        forall IE',\n                          consistent_IEnv E IE' ->\n                          exists N IM' c, Mexp_int (addIEnvMid mid (INonParamMod IE') IE) mexp N IM' c /\\\n                                         consistent_IMod M IM'.\nProof.\n  intros. simpl in *. do 4 destruct H. eauto.\nQed.\n\n(** The filtering function satisfies the filtering relation, provided that\n    environments are consistent *)\nLemma filt_IVEnv_fun_spec ive' ve' ve :\n    consistent_IVEnv ve' ive' -> env_ext ve' ve ->\n    filt_IVEnv ive' ve (filt_fun ive' ve).\nProof.\n  intros Hc Hex.\n  constructor.\n  + unfold env_ext. intros e p H.\n    apply En.find_1. apply En.find_2 in H. unfold filt_fun,restrict in H.\n    apply FM.P.filter_iff in H; intuition.\n  + constructor.\n    * intros l H. apply En.find_1. apply En.find_2 in H. unfold filt_fun,restrict in H.\n      apply FM.P.filter_iff in H; intuition.\n      unfold consistent_IVEnv in Hc. unfold env_ext in *.\n      destruct (Hc k t0) as [L R]. apply En.find_1 in H0.\n      assert (HH := L l H0). apply En.find_2. apply En.mem_2 in H1.\n      destruct H1 as [t1 Ht1]. apply En.find_1 in Ht1.\n      assert (HH' := Hex _ _ Ht1).\n      assert (t0 = t1) by congruence.\n      subst. auto.\n    * intro H.\n      unfold consistent_IVEnv in Hc. unfold env_ext in *.\n      destruct (Hc k t0) as [L R].\n      assert (HH := R (Hex _ _ H)).\n      destruct HH as [l Hl]. exists l.\n      apply En.find_1. unfold filt_fun,restrict.\n      rewrite FM.P.filter_iff;intuition. apply En.mem_1.\n      apply En.find_2 in H. eapply MapsTo_In;eauto.\nQed.\n\nLemma env_ext_filt_fun_eq {A : Type} (e' e : AEnv A) :\n  env_ext e' e -> filt_fun e' e = e.\nProof.\n  intro H.\n  unfold filt_fun,restrict. apply env_extensionality_alt.\n  intros k v.\n  split.\n  + intros. apply En.find_2 in H0.\n    rewrite FM.P.filter_iff in H0; intuition.\n    apply En.mem_2 in H2.\n    destruct H2 as [v1 Hv1]. apply En.find_1 in Hv1.\n    assert (HH' := H _ _ Hv1).\n    apply En.find_1 in H1. unfold look in *.\n    assert (v = v1) by congruence;subst;auto.\n  + intros Hl. apply En.find_1. rewrite FM.P.filter_iff; intuition.\n    apply En.find_2 in Hl. apply En.mem_1. eapply MapsTo_In;eauto.\nQed.\n\nLemma filt_fun_env_ext {A B : Type} (e' : AEnv A) (e : AEnv B) :\n  env_ext e' (filt_fun e' e).\nProof.\n  unfold env_ext.\n  intros k v Hv. unfold filt_fun,restrict in *. intros. apply En.find_2 in Hv.\n  rewrite FM.P.filter_iff in Hv; intuition.\nQed.\n\nLemma filt_TEnv_fun_spec ite' te' :\n  env_ext ite' te' ->\n  filt_ITEnv ite' te' (filt_fun ite' te').\nProof.\n  intros H.\n  constructor.\n  + unfold env_ext in *.\n    intros k e Hl. apply En.find_1. apply En.find_2 in Hl. unfold filt_fun,restrict in Hl.\n    apply FM.P.filter_iff in Hl; intuition.\n  + apply env_ext_filt_fun_eq; auto.\nQed.\n\nDefinition restrict_map {A B} (f : A -> B -> A) (e : AEnv A) (e' : AEnv B) :=\n  En.map2 (fun oe oe' =>\n             match oe,oe' with\n             | Some v, None => None\n             | None, Some v => None\n             | Some v, Some v' => Some (f v v')\n             | None,None => None\n             end)\n          e e'.\n\n(* Filtering relation, defined in more \"algorithmic\" style *)\nInductive flt_Env_rel : IEnv -> Env -> IEnv -> Prop :=\n  flt_Env_r :\n    forall TE' TE IVE VE IME' ME IME MTE,\n      flt_IMEnv_rel IME' ME IME ->\n      flt_Env_rel (IEnvCtr TE' IVE IME' MTE)\n                  (EnvCtr TE VE ME  emptyMTEnv)\n                  (IEnvCtr (filt_fun TE' TE) (filt_fun IVE VE) IME emptyMTEnv)\n   with\n   flt_IMEnv_rel : IMEnv -> MEnv -> IMEnv -> Prop :=\n     flt_IMEnv_r : forall (ime' : VE.VecEnv IMod) (me : VE.VecEnv Mod) ime,\n       RestrictionRel flt_IMod_rel (_to ime') (_to me) (_to ime) ->\n       flt_IMEnv_rel (IMEnvCtr ime')\n                     (MEnvCtr me)\n                     (IMEnvCtr ime)\n   with\n   flt_IMod_rel :  IMod -> Mod -> IMod -> Prop :=\n   | flt_IMod_nmp_r : forall ie' ie e,\n       flt_Env_rel ie' e ie ->\n       flt_IMod_rel (INonParamMod ie') (NonParamMod e) (INonParamMod ie)\n   | flt_IMod_ftor_r : forall IE0 T E' E G G' mid mexp,\n       E' = E ->\n       G' = G ->\n       (* enriches E' E -> *)\n       (* enrichesModType G' G -> *)\n       flt_IMod_rel (IFtor IE0 T E G' mid mexp) (Ftor T E' G) (IFtor IE0 T E' G mid mexp).\n\nScheme flt_mut :=\n  Induction for flt_Env_rel Sort Prop\n  with\n    Induction for flt_IMEnv_rel Sort Prop\n  with\n    Induction for flt_IMod_rel Sort Prop.\n\nLemma flt_consistent ie' ie e' e :\n  enriches e' e ->\n  consistent_IEnv e' ie' ->\n  flt_Env_rel ie' e ie ->\n  consistent_IEnv e ie.\nProof.\n  generalize dependent e. generalize dependent e'. generalize dependent ie.\n  induction ie' using IEnv_mut\n    with (P0 := fun ime' => forall me' me ime,\n                    enrichesM me' me ->\n                    consistent_IMEnv me' ime' ->\n                    flt_IMEnv_rel ime' me ime ->\n                    consistent_IMEnv me ime)\n         (P1 := fun im' => forall m' m im,\n                 enrichesMod m' m ->\n                 consistent_IMod m' im' ->\n                 flt_IMod_rel im' m im ->\n                 consistent_IMod m im).\n  + intros ie e' e Hen Hc.\n    inversion Hen as [ve' ve te' te me' me mte' mte Hvext Htext Henm H2 H3]. subst.\n    simpl in *. intuition. subst.\n    rename t0 into te'. rename i into ive'. rename i0 into ime'.\n    destruct ie.\n    inversion_clear H.\n    unfold consistent_IVEnv in H2.\n    intuition.\n    ** symmetry. apply env_ext_filt_fun_eq;auto.\n    ** unfold consistent_IVEnv in *. intros.\n       destruct (H2 k t1) as [Ht Hl].\n         split.\n         *** intros l Ht0. apply En.find_2 in Ht0.\n             apply FM.P.filter_iff in Ht0. destruct Ht0.\n             apply En.find_1 in H.\n             assert (HH := Ht _ H). unfold env_ext in *.\n             apply En.mem_2 in H3. destruct H3 as [t2 Ht2].\n             apply En.find_1 in Ht2.\n             assert (Ht1' := Hvext _ _ Ht2). assert (t1 = t2) by congruence. subst. auto.\n             intuition.\n         *** intros Ht0. assert (HH := Hl (Hvext _ _ Ht0)). destruct HH as [l Hl'].\n             exists l. apply En.find_1. unfold filt_fun,restrict. rewrite FM.P.filter_iff.\n             split. apply En.find_2. assumption. apply En.mem_1. eapply MapsTo_In;eauto.\n             intuition.\n    ** eapply IHie';eauto.\n  + intros me0' me0 ime0 Hen Hc Hflt.\n    inversion Hen as [me' me Hdom He Heq0 Heq1]. subst.\n    rename t0 into ime'. simpl in *.\n    rewrite <- (Forall2_fix_fold_unfold consistent_IMod) in *.\n    rewrite <- (ForallEnv2_fold_unfold consistent_IMod) in *.\n    rewrite ForallEnv2_fix_EnvRel_iff in *.\n    inversion_clear Hc as [Hd Hcim].\n    destruct ime0. inversion_clear Hflt as [? ? ? Hr].\n    split.\n    ** rewrite dom_extensionality in Hd. unfold _to in Hdom.\n       eapply RestrictionRel_dom_eq; eauto.\n       eapply domain_eq_r;eauto.\n    ** rewrite <- (ForallEnv2_fold_unfold consistent_IMod).\n       rename v into ime.\n       assert (Hfa : dom (_to me) = dom ime /\\\n                     ForallEnv2_fix consistent_IMod me ime).\n       rewrite ForallEnv2_fix_EnvRel_iff.\n       unfold EnvRel.\n       split.\n       *** intros k'. apply dom_extensionality.\n           rewrite dom_extensionality in Hd. unfold _to in Hdom.\n           eapply RestrictionRel_dom_eq; eauto.\n           eapply domain_eq_r;eauto.\n       *** intros k v v' Hv Hv'.\n           assert (HH : exists v v'',\n                      look k ime' = Some v'' /\\ look k me = Some v /\\ flt_IMod_rel v'' v v') by\n               (apply (RestrictionRel_spec Hr Hv');auto).\n           destruct HH as [v0 Htmp]. destruct Htmp as [v'' Htmp].\n           destruct Htmp as [Hv'' Htmp]. destruct Htmp as [Hv0 Hflt].\n           unfold _to in *.\n           assert (v = v0) by congruence. subst.\n           assert (Hin_me := MapsTo_In (En.find_2 Hv)).\n           assert (Hin_me' := Hdom _ Hin_me).\n           inversion Hin_me' as [m' Hm']. apply En.find_1 in Hm'.\n           assert (H' := Forall_forall_vals H). simpl in *.\n           eapply H';eauto.\n       *** destruct Hfa. auto.\n  + intros. destruct m;destruct m';  destruct im; inversion H1; inversion H; subst.\n    simpl in *. eapply IHie'; eauto.\n  + intros m' m'' im Hen Hc Hflt.\n    destruct m';destruct m''; inversion_clear Hen; inversion Hflt; subst;tryfalse.\n    simpl in *.  destruct m2. destruct Hc.\n    do 3 destruct H. inversion_clear H.\n    exists x,x0,x1.\n    split;auto.\nQed.\n\nLemma flt_exists ie' e' e :\n  enriches e' e ->\n  consistent_IEnv e' ie' ->\n  exists ie, flt_Env_rel ie' e ie.\nProof.\n  generalize dependent e. generalize dependent e'.\n  induction ie' using IEnv_mut\n    with (P0 := fun ime' => forall me' me,\n                    enrichesM me' me ->\n                    consistent_IMEnv me' ime' ->\n                    exists ime, flt_IMEnv_rel ime' me ime)\n         (P1 := fun im' => forall m' m,\n                 enrichesMod m' m ->\n                 consistent_IMod m' im' ->\n                 exists im, flt_IMod_rel im' m im).\n  + intros e' e Hen Hc.\n    inversion Hen as [ve' ve te' te me' me mte' mte Hvext Htext Henm H2 H3]. subst.\n    simpl in *. intuition. subst.\n    rename t0 into te'. rename i into ive'. rename i0 into ime'.\n    destruct (IHie' _ _ Henm H0) as [ime Hime].\n    exists (IEnvCtr (filt_fun te' te) (filt_fun ive' ve) ime emptyMTEnv).\n    constructor;auto.\n  + intros me0' me0 Hen Hc.\n    inversion Hen as [me' me Hdom He Heq0 Heq1]. subst.\n    rename t0 into ime'. simpl in *.\n    rewrite <- (Forall2_fix_fold_unfold consistent_IMod) in *.\n    rewrite <- (ForallEnv2_fold_unfold consistent_IMod) in *.\n    rewrite ForallEnv2_fix_EnvRel_iff in *.\n    inversion Hc as [Hd Hcim].\n\n    assert (Hex : exists ime, RestrictionRel flt_IMod_rel (_to ime') (_to me) ime).\n    assert (H' := Forall_forall_vals H). simpl in *.\n    apply RestrictionRel_exists. intros v k Hv v' Hv'.\n    assert (Hin_me := MapsTo_In (En.find_2 Hv)).\n    assert (Hin_me' := Hdom _ Hin_me).\n    inversion Hin_me' as [m' Hm']. apply En.find_1 in Hm'.\n    eapply (H' k _ Hv' m');eauto.\n\n    destruct Hex as [ime Hime]. exists (IMEnvCtr (_from ime)).\n    constructor. rewrite VE.toOrdEnv_fromOrdEnv_inv. assumption.\n  + intros. destruct m;destruct m'; inversion H; subst.\n    * simpl in *. destruct (IHie' _ e H3 H0) as [ie Hie].\n      exists (INonParamMod ie). constructor. assumption.\n    * simpl in *. destruct m. do 4 destruct H0.\n      inversion H0.\n  + intros m' m'' Hen Hc.\n    destruct m';destruct m''; inversion Hen; tryfalse. subst.\n    simpl in *. destruct m2. destruct Hc.\n    inversion Hen. subst.\n    do 3 destruct H. inversion_clear H.\n    exists (IFtor x t2 e1 (MSigma t1 m1) x0 x1).\n    apply flt_IMod_ftor_r;auto.\nQed.\n\n(* NOTE : That's how the function, implementing filtering could look like. *)\n(* Of course, this implementation doesn't work, because Coq's restriction on fixpoint. *)\n(* [Program] tactic doesn't help here, because measure cannot be used with the mutual definitions *)\n\n(* Program Fixpoint flt_Env_fun (ie : IEnv) (e : Env) {measure env_measure}: IEnv := *)\n(*   match ie,e with *)\n(*     IEnvCtr TE' IVE IME MTE', EnvCtr TE VE ME MTE => *)\n(*     IEnvCtr (filt_fun TE' TE) (filt_fun IVE VE) (flt_IMEnv_fun IME ME) MTE *)\n(*   end *)\n(* with *)\n(* flt_IMEnv_fun (ime' : IMEnv) (me : MEnv) := *)\n(*   match ime', me with *)\n(*   | IMEnvCtr ve', MEnvCtr ve => *)\n(*     IMEnvCtr (restrict_map flt_IMod_fun (_to ve') (_to ve)) *)\n(*   end *)\n(* with *)\n(* flt_IMod_fun (im' : IMod) (m : Mod) : IMod := *)\n(*   match im',m with *)\n(*   | INonParamMod ie, NonParamMod e => INonParamMod (flt_Env_fun ie e) *)\n(*   | IFtor IE0 T E G mid mexp, Ftor T' E' G' => IFtor IE0 T E G mid mexp *)\n(*   | IFtor IE0 T E G mid mexp, NonParamMod e => im' *)\n(*   | INonParamMod ie, Ftor T' E' G' => im' *)\n(*   end. *)\n\n\nDefinition filt_IMEnv_fun (ime' : IMEnv) (me : MEnv) :=\n  match ime', me with\n  | IMEnvCtr ve', MEnvCtr ve => IMEnvCtr (restrict (_to ve') (_to ve))\n  end.\n\nDefinition filt_IEnv (ie : IEnv) (e : Env) :=\n  match ie,e with\n    IEnvCtr TE' IVE IME MTE', EnvCtr TE VE ME MTE =>\n    IEnvCtr (filt_fun TE' TE) (filt_fun IVE VE) (filt_IMEnv_fun IME ME) (MTE')\n  end.\n\nLemma flt_Env_rel_to_filtering_IEnv ie' e' e ie :\n  enriches e' e ->\n  consistent_IEnv e' ie' ->\n  flt_Env_rel ie' e ie -> filtering_IEnv ie' e ie.\nProof.\n revert ie. revert e. revert e'.\n induction ie' using IEnv_mut with\n      (P0 := fun ime' => forall me ime me',\n               enrichesM me' me ->\n               consistent_IMEnv me' ime' ->\n               flt_IMEnv_rel ime' me ime ->\n               filtering_IMEnv ime' me ime)\n      (P1 := fun im' => forall m im m',\n               enrichesMod m' m ->\n               consistent_IMod m' im' ->\n               flt_IMod_rel im' m im ->\n               filtering_IMod im' m im).\n + intros e' e ie He Hc Hflt. destruct e',ie,e; simpl in *; inversion He; intuition; subst.\n   inversion_clear Hflt.\n   constructor.\n   * eapply filt_IVEnv_fun_spec;eauto.\n   * eapply filt_TEnv_fun_spec;eauto.\n   * eapply IHie';eauto.\n + intros me ime me' He Hc Hflt.\n   destruct me',ime,me; inversion He; simpl in *. intuition; subst.\n   inversion Hflt. subst.\n   constructor.\n   * eapply RestrictionRel_dom_subset;eauto.\n   * symmetry. eapply RestrictionRel_dom_eq;eauto. eapply domain_eq_r; eauto.\n   * intros k im' m im Him' Hm Him.\n     rename t0 into ime'. rename v1 into me. rename v0 into ime. rename v into me'.\n     assert (HH : exists m0 im0',\n                look k ime' = Some im0' /\\ look k me = Some m0 /\\ flt_IMod_rel im0' m0 im) by\n         (apply (RestrictionRel_spec H7 Him);auto).\n     destruct HH as [v0 Htmp]. destruct Htmp as [v'' Htmp].\n     destruct Htmp as [Hv'' Htmp]. destruct Htmp as [Hv0 Hflt'].\n     unfold _to in *.\n     assert (v'' = im') by congruence.\n     assert (v0 = m) by congruence. subst.\n     eapply Forall_forall_vals in H;eauto.\n     assert (Hem' : exists m', look k me' = Some m') by\n         (apply En.find_2 in Hm; apply MapsTo_In in Hm; destruct (H2 _ Hm) as [m' Hm'];\n          apply En.find_1 in Hm'; eexists;eauto).\n     destruct Hem' as [m' Hm'].\n     eapply H;eauto.\n     rewrite <- (Forall2_fix_fold_unfold consistent_IMod) in *.\n     rewrite <- (ForallEnv2_fold_unfold consistent_IMod) in *.\n     assert (Hfa : EnvRel consistent_IMod me' ime') by\n         (rewrite <- ForallEnv2_fix_EnvRel_iff; intuition).\n     inversion Hfa as [Hdom Hcm]. eauto.\n + intros m im m' He Hc Hflt.\n   destruct m,im,m'; inversion_clear Hflt; inversion_clear He.\n   constructor. eauto.\n + rename m into t.\n   intros m im m' He Hc Hflt.\n   destruct m,im,m'; inversion_clear Hflt; inversion_clear He.\n   constructor; eauto.\nQed.\n\nLemma consistent_enrich_to_filtering: forall E IE' E',\n    enriches E' E ->\n    consistent_IEnv E' IE' ->\n    exists IE, filtering_IEnv IE' E IE /\\ consistent_IEnv E IE.\nProof.\n  intros e ie' e' He Hc.\n  assert (Hie_ex : exists ie, flt_Env_rel ie' e ie) by (eapply flt_exists;eauto).\n  destruct Hie_ex as [ie Hie].\n  exists ie. split.\n  + eapply flt_Env_rel_to_filtering_IEnv;eauto.\n  + eapply flt_consistent;eauto.\nQed.\n\n\n(* -------------------------------------- *)\n(* Main proposition (see Proposition 6.1) *)\n(* -------------------------------------- *)\n\nHint Resolve consistent_IEnv_extend consistent_IEnv_empty.\n\nLemma comp_consistent_dec: forall dec E E' IE,\n    Dec_elab E dec E' -> consistent_IEnv E IE ->\n    exists N IE' c, Dec_comp IE dec N IE' c  /\\ consistent_IEnv E' IE'.\nProof.\n  crush.\n  pose (AtomN.Atom_inf (PermIEnvLabel.supp IE)) as fresh_l.\n  destruct fresh_l as [l Hfresh].\n  exists (addTSet l emptyTSet).\n\n  inversion H. subst.\n  apply consistent_to_erasure in H0.\n  apply comp_exp with (IE := IE) in H1.\n  - destruct H1. remember (Val_c l x) as c.\n    exists (addIEnvVid v (l,t0) emptyIEnv). exists c.\n    split.\n    + remember (Val_dec v e) as dec.\n      rename v into vid. rename x into ex. rename e into exp. subst dec c.\n      clear H H0 E. constructor;auto.\n    + apply consistent_IEnv_extend. apply consistent_IEnv_empty.\n  - crush.\nQed.\n\nLemma interp :\n  (forall E mexp T M,\n      Mexp_melab E mexp T M -> forall IE,\n      consistent_IEnv E IE ->\n      exists N IM c, Mexp_int IE mexp N IM c /\\ consistent_IMod M IM) /\\\n  (forall E mdec T E',\n      Mdec_melab E mdec T E' -> forall IE,\n      consistent_IEnv E IE ->\n      exists N IE' c, Mdec_int IE mdec N IE' c /\\ consistent_IEnv E' IE').\nProof.\n  apply melab_mut; intros; tryfalse.\n  - assert (H1 := H IE H0). crush. exists x. exists (INonParamMod x0). exists x1. split.\n    + constructor; eauto.\n    + auto.\n  - exists emptyTSet. apply consistent_look_mid with (M:=M) (mid:=mid) in H; auto.\n    destruct H. destruct H. exists x. exists Emp_c. split.\n    + constructor. eauto.\n    + assumption.\n  - assert (H1:=H IE H0). clear H. destruct H1 as [N H1]. destruct H1. destruct H. destruct H.\n    exists N. rename x0 into c. assert (H2:=H1). apply consistent_imod_uniform in H1. destruct H1. subst.\n    apply consistent_imod_ienv_lem in H2.\n    apply consistent_look_mid with (M:=M) (mid:=mid) in H2;auto.\n    destruct H2. destruct H1. exists x. exists c. split.\n    + clear E m e H0 E' H2 M. rename x into IM.\n      rename x0 into IE'. apply Prj_mexp_int with (IE':=IE'); auto.\n    + auto.\n  - exists emptyTSet. exists (IFtor IE emptyTSet E (MSigma emptyTSet E') mid mexp). exists Emp_c.\n    split.\n    + apply consistent_to_erasure in H0. clear H. apply Funct_mexp_int with (E0:=E0); auto.\n    + crush. exists IE. exists mid. exists mexp. split.\n      * reflexivity.\n      * intros IE' H1.\n        apply consistent_IEnv_mid_extend\n          with (M:=NonParamMod E) (IM:=INonParamMod IE') (s:=mid) (IE:=IE) (E:=E0)\n                in H1.\n        rename H into IH.\n        apply IH;auto. auto.\n  - remember (Ftor emptyTSet E' (MSigma emptyTSet (NonParamMod E''))) as M.\n    assert (H1:=H0).\n    apply consistent_look_longmid with (M:=M) (longmid:=longmid) in H0;auto.\n    destruct H0 as [IM H0]. destruct H0.\n    assert (H':=H IE H1).\n    destruct H' as [N1 H']. destruct H' as [IM1 H']. destruct H' as [c1 H'].\n    + subst M. assert (H3:=H2). apply consistent_imod_uniform_ftor2 in H2.\n      destruct H2 as [IE1 H2]. destruct H2 as [mid H2]. destruct H2 as [mexp1 H2]. destruct H2.\n      destruct H'. assert (H6':=H6). apply consistent_imod_uniform in H6.\n      destruct H6 as [IE' HeqIE']. subst.\n      apply consistent_imod_ienv_lem in H6'.\n      apply consistent_enrich_to_filtering with (IE':=IE') in e0; auto.\n      destruct e0 as [IE'' H2]. destruct H2 as [Hflt H6].\n      assert (H4' := H4 IE'' H6).\n      destruct H4' as [N2 H4']. destruct H4' as [IM2 H4']. destruct H4' as [c2 H4']. destruct H4'.\n      exists (unionTSet N1 N2). exists IM2. exists (Seq_c c1 c2). split.\n      * apply App_mexp_int with (IE0:=IE1) (mexp' := mexp1) (IE' := IE')\n                                (IE'' := IE'') (E'' := E'') (E':=E') (mid:=mid); auto.\n      * auto.\n  - assert (H1:=H). apply consistent_to_erasure in H. apply comp_consistent_dec with (IE:=IE) in d; auto.\n    + destruct d as [N H0]. destruct H0 as [IE' H0]. destruct H0 as [c H0].\n      destruct H0 as [L R]. exists N. exists IE'. exists c. split.\n      * constructor. auto.\n      * auto.\n  - exists emptyTSet. exists (addIEnvTid tid Ty emptyIEnv). exists Emp_c. split.\n    + econstructor; eauto. apply consistent_to_erasure. auto.\n    + apply consistent_IEnv_tid_extend. apply consistent_IEnv_empty.\n  - assert (H':=H IE H0). destruct H' as [N H']. destruct H' as [IM H']. destruct H' as [c H']. destruct H' as [L R].\n    exists N. exists (addIEnvMid mid IM emptyIEnv). exists c. split.\n    + constructor; auto.\n    + apply consistent_IEnv_mid_extend; auto.\n  - exists emptyTSet, (addIEnvTmid mtid S emptyIEnv), Emp_c.\n    split.\n    + assert (He : erasure_IEnv IE E ) by (apply consistent_to_erasure;auto).\n      apply ModTyp_mdec_int with (E:=E);auto.\n    + apply consistent_IEnv_mtid_extend. apply consistent_IEnv_empty.\n  - assert (H':=H IE H0). destruct H' as [N H']. destruct H' as [IM H']. destruct H' as [c H']. destruct H' as [L R].\n    exists N.\n    assert (R2:=R). apply consistent_imod_uniform in R. destruct R. subst.\n    exists x. exists c. split.\n    + constructor; auto.\n    + apply consistent_imod_ienv_lem; auto.\n  - assert (H':=H IE H1). destruct H' as [N1 H']. destruct H' as [IE1 H']. destruct H' as [c1 H'].\n    destruct H' as [INT1 ERA1]. apply consistent_IEnv_plus with (IE2:=IE1) (E2:=E1) in H1; auto.\n    assert (H0':=H0 (plusIEnvIEnv IE IE1) H1).\n    destruct H0' as [N2 H0']. destruct H0' as [IE2 H0']. destruct H0' as [c2 H0'].\n    destruct H0' as [INT2 ERA2].\n    exists (unionTSet N1 N2). exists (plusIEnvIEnv IE1 IE2). exists (Seq_c c1 c2). split.\n    + constructor; auto.\n    + apply consistent_IEnv_plus; auto.\n  - exists emptyTSet. exists emptyIEnv. exists Emp_c. split.\n    + constructor; auto.\n    + auto.\nQed.\n", "meta": {"author": "diku-dk", "repo": "futhark-icfp18", "sha": "0506410738cf75fdc47f3931b06469640234910c", "save_path": "github-repos/coq/diku-dk-futhark-icfp18", "path": "github-repos/coq/diku-dk-futhark-icfp18/futhark-icfp18-0506410738cf75fdc47f3931b06469640234910c/MiniInt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24106884987393443}}
{"text": "Set Implicit Arguments.\n\nRequire Import Bedrock.Platform.AutoSep.\nRequire Import Bedrock.Platform.Facade.examples.QsADTs.\nImport Adt.\nRequire Import Bedrock.Platform.Cito.RepInv.\n\nRequire Import Bedrock.Platform.Facade.examples.ListSeqF Bedrock.Platform.Facade.examples.ArrayTupleF Bedrock.Platform.Facade.examples.TupleListF Bedrock.Platform.Facade.examples.Tuples0F Bedrock.Platform.Facade.examples.Tuples1F Bedrock.Platform.Facade.examples.Tuples2F.\n\nDefinition rep_inv p adtvalue : HProp :=\n  match adtvalue with\n    | Tuple t => tuple t p\n    | WordList ts => ListSeqF.Adt.lseq ts p\n    | TupleList ts => lseq ts p\n    | Tuples0 len ts => tuples0 len ts p\n    | Tuples1 len key ts => tuples1 len key ts p\n    | Tuples2 len key1 key2 ts => tuples2 len key1 key2 ts p\n  end.\n\nModule Ri <: RepInv QsADTs.Adt.\n\n  Definition RepInv := W -> ADTValue -> HProp.\n\n  Definition rep_inv := rep_inv.\n\n  Lemma rep_inv_ptr : forall p a, rep_inv p a ===> p =?> 1 * any.\n  Proof.\n    destruct a; simpl.\n\n    eapply Himp_trans; [ apply tuple_fwd | ].\n    sepLemmaLhsOnly.\n    fold (@length W) in *.\n    Transparent Malloc.freeable.\n    unfold Malloc.freeable in H0.\n    destruct t; simpl in *; intuition (try omega).\n    destruct t; simpl in *; intuition (try omega).\n    unfold array; simpl.\n    sepLemma; apply any_easy.\n\n    eapply Himp_trans; [ apply ListSeqF.Adt.lseq_fwd | sepLemma ]; apply any_easy.\n\n    eapply Himp_trans; [ apply lseq_fwd | sepLemma ]; apply any_easy.\n\n    unfold tuples0; sepLemma; apply any_easy.\n\n    eapply Himp_trans; [ apply tuples1_fwd | sepLemma ]; apply any_easy.\n\n    eapply Himp_trans; [ apply tuples2_fwd | sepLemma ]; apply any_easy.\n  Qed.\n\nEnd Ri.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Platform/Facade/examples/QsRepInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24106884341669138}}
{"text": "(* ========================= *)\n(* ===== CH10_CHI_CH.v ===== *)\n(* ========================= *)\n\nRequire Export CH09_planar.\n\nOpen Scope nat_scope.\n\n(* ========================== *)\n(* ======= ########## ======= *)\n(* ========================== *)\n\nLemma inv_hmap_CH2 :\n  forall (d1:dart)(t1:tag)(p1:point)(d2:dart)(t2:tag)(p2:point)(max:dart),\n  d1 <> d2 -> d1 <> nil -> d2 <> nil -> d1 <= max -> d2 <= max ->\n  inv_hmap (CH2 d1 t1 p1 d2 t2 p2 max).\nProof.\nintros d1 t1 p1 d2 t2 p2 max HA1 HB1 HB2 HC1 HC2.\nassert (HB3 : max+1 <> nil).\n apply neq_le_trans with max; [idtac|lia].\n apply neq_le_trans with d1; try assumption.\nassert (HB4 : max+2 <> nil).\n apply neq_le_trans with max; [idtac|lia].\n apply neq_le_trans with d1; try assumption.\nassert (HA2 : d1 <> max+1); [lia|idtac].\nassert (HA3 : d2 <> max+1); [lia|idtac].\nassert (HA4 : d1 <> max+2); [lia|idtac].\nassert (HA5 : d2 <> max+2); [lia|idtac].\nassert (HA6 : max+1 <> max+2); [lia|idtac].\nsimpl; unfold prec_I, prec_L; simpl;\nrepeat split; unfold succ, pred; simpl;\nelimeqdartdec; try intuition.\nQed.\n\nLemma inv_poly_CH2 :\n  forall (d1:dart)(t1:tag)(p1:point)(d2:dart)(t2:tag)(p2:point)(max:dart),\n  d1 <> d2 -> d1 <> nil -> d2 <> nil -> d1 <= max -> d2 <= max ->\n  inv_poly (CH2 d1 t1 p1 d2 t2 p2 max).\nProof.\nintros d1 t1 p1 d2 t2 p2 max HA1 HB1 HB2 HC1 HC2.\nassert (HB3 : max+1 <> nil).\n apply neq_le_trans with max; [idtac|lia].\n apply neq_le_trans with d1; try assumption.\nassert (HB4 : max+2 <> nil).\n apply neq_le_trans with max; [idtac|lia].\n apply neq_le_trans with d1; try assumption.\nassert (HA2 : d1 <> max+1); [lia|idtac].\nassert (HA3 : d2 <> max+1); [lia|idtac].\nassert (HA4 : d1 <> max+2); [lia|idtac].\nassert (HA5 : d2 <> max+2); [lia|idtac].\nassert (HA6 : max+1 <> max+2); [lia|idtac].\nunfold inv_poly; simpl; intros d H.\nrepeat (elim H; clear H; intro H; try subst d).\n(* max+2 *)\nright; right; unfold red_dart, succ, pred; simpl;\nrepeat split; elimeqdartdec; intuition.\n(* max+1 *)\nright; right; unfold red_dart, succ, pred; simpl;\nrepeat split; elimeqdartdec; intuition.\n(* d2 *)\nright; left; unfold blue_dart, succ, pred; simpl;\nrepeat split; elimeqdartdec; intuition.\n(* d1 *)\nright; left; unfold blue_dart, succ, pred; simpl;\nrepeat split; elimeqdartdec; intuition.\nQed.\n\nLemma planar_CH2 :\n  forall (d1:dart)(t1:tag)(p1:point)(d2:dart)(t2:tag)(p2:point)(max:dart),\n  d1 <> d2 -> d1 <> nil -> d2 <> nil -> d1 <= max -> d2 <= max ->\n  planar (CH2 d1 t1 p1 d2 t2 p2 max).\nProof.\nintros d1 t1 p1 d2 t2 p2 max HA1 HB1 HB2 HC1 HC2.\nassert (HB3 : max+1 <> nil).\n apply neq_le_trans with max; [idtac|lia].\n apply neq_le_trans with d1; try assumption.\nassert (HB4 : max+2 <> nil).\n apply neq_le_trans with max; [idtac|lia].\n apply neq_le_trans with d1; try assumption.\nassert (HA2 : d1 <> max+1); [lia|idtac].\nassert (HA3 : d2 <> max+1); [lia|idtac].\nassert (HA4 : d1 <> max+2); [lia|idtac].\nassert (HA5 : d2 <> max+2); [lia|idtac].\nassert (HA6 : max+1 <> max+2); [lia|idtac].\nunfold CH2.\napply <- planarity_criterion_0.\nright; simpl; elimeqdartdec; unfold expf; split.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\nunfold MF.expo; split. simpl; intuition.\nexists 1; simpl; unfold MF.f, McF.f, cF.\nsimpl; elimeqdartdec; trivial.\napply <- planarity_criterion_0.\nleft; simpl; intro h; intuition.\napply <- planarity_criterion_1.\nleft; simpl; intro h; intuition.\napply planar_I.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\napply <- planarity_criterion_1.\nleft; simpl; intro h; intuition.\napply planar_I.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\napply planar_I.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\napply planar_I.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\napply plf_planar; simpl; trivial.\nunfold prec_I; simpl; intuition.\nunfold prec_I; simpl; intuition.\nunfold prec_I; simpl; intuition.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\nunfold prec_I; simpl; intuition.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\nunfold inv_hmap, prec_I, prec_L, succ, pred.\nsimpl; elimeqdartdec; repeat split; try intuition.\nQed.\n\nLemma well_emb_CH2 :\n  forall (d1:dart)(t1:tag)(p1:point)(d2:dart)(t2:tag)(p2:point)(max:dart),\n  d1 <> d2 -> d1 <> nil -> d2 <> nil -> d1 <= max -> d2 <= max -> p1 <> p2 ->\n  well_emb (CH2 d1 t1 p1 d2 t2 p2 max).\nProof.\nintros d1 t1 p1 d2 t2 p2 max HA1 HB1 HB2 HC1 HC2 HP1.\nassert (HB3 : max+1 <> nil).\n apply neq_le_trans with max; [idtac|lia].\n apply neq_le_trans with d1; try assumption.\nassert (HB4 : max+2 <> nil).\n apply neq_le_trans with max; [idtac|lia].\n apply neq_le_trans with d1; try assumption.\nassert (HA2 : d1 <> max+1); [lia|idtac].\nassert (HA3 : d2 <> max+1); [lia|idtac].\nassert (HA4 : d1 <> max+2); [lia|idtac].\nassert (HA5 : d2 <> max+2); [lia|idtac].\nassert (HA6 : max+1 <> max+2); [lia|idtac].\nassert (HP2 : p2 <> p1); [apply neq_sym_point; assumption | idtac].\nunfold well_emb; simpl; intros d H.\nrepeat (elim H; clear H; intro H; try subst d; repeat split;\n unfold succ, pred; simpl; elimeqdartdec; try tauto).\n intros d H; repeat (elim H; clear H; intro H; try subst d; elimeqdartdec; try tauto).\n intros d H; repeat (elim H; clear H; intro H; try subst d; elimeqdartdec; try tauto).\n intros d H; repeat (elim H; clear H; intro H; try subst d; elimeqdartdec; try tauto).\n intros d H; repeat (elim H; clear H; intro H; try subst d; elimeqdartdec; try tauto).\nQed.\n\nLemma convex_CH2 :\n  forall (d1:dart)(t1:tag)(p1:point)(d2:dart)(t2:tag)(p2:point)(max:dart),\n  d1 <> d2 -> d1 <> nil -> d2 <> nil -> d1 <= max -> d2 <= max -> p1 <> p2 ->\n  convex (CH2 d1 t1 p1 d2 t2 p2 max).\nProof.\nintros d1 t1 p1 d2 t2 p2 max HA1 HB1 HB2 HC1 HC2 HP1.\nassert (HB3 : max+1 <> nil).\n apply neq_le_trans with max; [idtac|lia].\n apply neq_le_trans with d1; try assumption.\nassert (HB4 : max+2 <> nil).\n apply neq_le_trans with max; [idtac|lia].\n apply neq_le_trans with d1; try assumption.\nassert (HA2 : d1 <> max+1); [lia|idtac].\nassert (HA3 : d2 <> max+1); [lia|idtac].\nassert (HA4 : d1 <> max+2); [lia|idtac].\nassert (HA5 : d2 <> max+2); [lia|idtac].\nassert (HA6 : max+1 <> max+2); [lia|idtac].\nunfold convex; simpl; intros d H.\nrepeat (elim H; clear H; intro H; try subst d; unfold blue_dart, succ, pred; simpl).\n elimeqdartdec; try tauto.\n elimeqdartdec; try tauto.\n intro H; clear H; intros d H.\n repeat (elim H; clear H; intro H; try subst d; elimeqdartdec; try tauto).\n intro H; clear H; intros d H.\n repeat (elim H; clear H; intro H; try subst d; elimeqdartdec; try tauto).\nQed.\n\n(* ========================== *)\n(* ======= ########## ======= *)\n(* ========================== *)\n\nLemma inv_hmap_inv_poly_planar_well_emb_convex_CHI :\n  forall (m1:fmap)(m2:fmap)(max:dart),\n  inv_hmap m1 -> linkless m1 -> well_emb m1 -> noalign m1 ->\n  inv_hmap m2 -> inv_poly m2 -> planar m2 -> well_emb m2 -> convex m2 ->\n  (forall (d:dart), max <= d -> d <> nil) ->\n  (forall (d:dart), exd m1 d -> ~ exd m2 d) ->\n  (forall (d:dart), max <= d -> ~ exd m1 d /\\ ~ exd m2 d) ->\n  (forall (d1:dart)(d2:dart), exd m1 d1 -> exd m2 d2 -> (fpoint m1 d1) <> (fpoint m2 d2)) ->\n  (forall (d1:dart)(d2:dart)(d3:dart), exd m1 d1 -> exd m1 d2 -> exd m2 d3 ->\n   (fpoint m1 d1) <> (fpoint m1 d2) -> ~ align (fpoint m1 d1) (fpoint m1 d2) (fpoint m2 d3)) ->\n  (forall (d1:dart)(d2:dart)(d3:dart), exd m1 d1 -> exd m2 d2 -> exd m2 d3 ->\n   (fpoint m2 d2) <> (fpoint m2 d3) -> ~ align (fpoint m1 d1) (fpoint m2 d2) (fpoint m2 d3)) ->\n  inv_hmap (CHI m1 m2 max) /\\ inv_poly (CHI m1 m2 max) /\\ planar (CHI m1 m2 max) /\\ well_emb (CHI m1 m2 max) /\\ convex (CHI m1 m2 max).\nProof.\ninduction m1.\n (* Case 1 : m = V *)\n intros m2 max Hm11 Hm12 Hm13 Hm14 Hm21 Hm22 Hm23 Hm24 Hm25 Hw0 Hw1 Hw5 Hp1 Hp2 Hp3.\n simpl in *; intuition.\n (* Case 2 : m = I *)\n intros m2 max Hm11 Hm12 Hm13 Hm14 Hm21 Hm22 Hm23 Hm24 Hm25 Hw0 Hw1 Hw5 Hp1 Hp2 Hp3.\n simpl in *; unfold prec_I in *.\n destruct Hm11 as [Hm11 [Hneq Hexd]].\n(**)\nassert (Hw2 : forall (d0:dart), d = d0 \\/ exd m1 d0 -> d0 < max).\n intros d0 Hd0.\n elim Hd0; clear Hd0; intro Hd0; try subst d.\n  elim (le_lt_dec max d0); intro H.\n   generalize (Hw5 d0 H); intuition.\n   assumption.\n  elim (le_lt_dec max d0); intro H.\n   generalize (Hw5 d0 H); intuition.\n   assumption.\nassert (Hw3 : forall (d0:dart), exd m2 d0 -> ~ exd m1 d0).\n intros d0 Hd0; elim (exd_dec m1 d0).\n  intro H; generalize (Hw1 d0); intuition.\n  intro H; assumption.\nassert (Hw4 : forall (d0:dart), exd m2 d0 -> d0 < max).\n intros d0 Hd0; elim (le_lt_dec max d0).\n  intro H; generalize (Hw5 d0 H); intuition.\n  intro H; assumption.\nmove Hw1 after Hp3; move Hw0 after Hp3; move Hw5 after Hw4.\n(**)\nassert (Hp4 : forall (da:dart), exd m1 da -> fpoint m1 da <> p).\n intros da Hda.\n assert (H0 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n generalize (Hm13 d H0); unfold well_emb; simpl.\n intros [H1 [H2 [H3 [H4 H5]]]]; clear H0 H1 H2 H3 H4.\n assert (H0 : exd (I m1 d t p) da); [simpl;tauto|idtac].\n generalize (H5 da H0); elimeqdartdec; clear H0 H5.\n elim (eq_dart_dec d da); intro Heq; [subst d; contradiction | idtac].\n intro H0; apply neq_sym_point; apply H0; try assumption.\n apply neq_sym; assumption.\n rewrite not_exd_A_nil; try assumption.\n apply exd_not_nil with m1; try assumption.\n rewrite not_exd_A_1_nil; try assumption.\n apply exd_not_nil with m1; try assumption.\n(**)\n apply IHm1; clear IHm1; try assumption.\n (* well_emb m1 /\\ noalign m1 *)\n apply well_emb_I with d t p; try assumption.\n simpl; unfold prec_I; repeat split; assumption.\n apply noalign_I with d t p; try assumption.\n simpl; unfold prec_I; repeat split; assumption.\n (* inv_hmap CHID *)\n apply inv_hmap_CHID; try assumption.\n apply submap_2_submap; try assumption.\n apply submap_2_refl.\n unfold inv_noalign_point.\n  intros da db Hda Hdb Hp0.\n  assert (H0 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n  generalize (Hp3 d da db H0 Hda Hdb Hp0); clear H0.\n  elimeqdartdec; intro H0; auto with myorientation.\n apply (Hw0 max (le_refl max)).\n generalize (Hw2 d); intuition.\n apply Hw1; left; trivial.\n generalize (Hw5 max (le_refl max)); intuition.\n (* inv_poly CHID *)\n apply inv_poly_CHID; try assumption.\n unfold inv_noalign_point.\n  intros da db Hda Hdb Hp0.\n  assert (H0 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n  generalize (Hp3 d da db H0 Hda Hdb Hp0); clear H0.\n  elimeqdartdec; intro H0; auto with myorientation.\n apply (Hw0 max (le_refl max)).\n generalize (Hw2 d); intuition.\n apply Hw1; left; trivial.\n generalize (Hw5 max (le_refl max)); intuition.\n (* planar CHID *)\n apply planar_CHID; try assumption.\n apply submap_2_submap; try assumption.\n apply submap_2_refl.\n unfold inv_noalign_point.\n  intros da db Hda Hdb Hp0.\n  assert (H0 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n  generalize (Hp3 d da db H0 Hda Hdb Hp0); clear H0.\n  elimeqdartdec; intro H0; auto with myorientation.\n apply (Hw0 max (le_refl max)).\n generalize (Hw2 d); intuition.\n apply Hw1; left; trivial.\n generalize (Hw5 max (le_refl max)); intuition.\n (* well_emb CHID *)\n apply well_emb_CHID; try assumption.\n unfold inv_noalign_point.\n  intros da db Hda Hdb Hp0.\n  assert (H0 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n  generalize (Hp3 d da db H0 Hda Hdb Hp0); clear H0.\n  elimeqdartdec; intro H0; auto with myorientation.\n apply (Hw0 max (le_refl max)).\n generalize (Hw2 d); intuition.\n apply Hw1; left; trivial.\n generalize (Hw5 max (le_refl max)); intuition.\n intros da Hda; apply neq_sym_point.\n assert (H0 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n generalize (Hp1 d da H0 Hda); clear H0.\n elimeqdartdec; trivial.\n (* convex CHID *)\n apply inv_convex_CHID; try assumption.\n unfold inv_noalign_point.\n  intros da db Hda Hdb Hp0.\n  assert (H0 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n  generalize (Hp3 d da db H0 Hda Hdb Hp0); clear H0.\n  elimeqdartdec; intro H0; auto with myorientation.\n apply (Hw0 max (le_refl max)).\n generalize (Hw2 d); intuition.\n apply Hw1; left; trivial.\n generalize (Hw5 max (le_refl max)); intuition.\n (* Hw0 *)\n intros d0 Hd0; apply Hw0; lia.\n (* Hw1 *)\n intros d0 Hd0; apply not_exd_CHID.\n  apply Hw1; right; assumption.\n  apply exd_not_exd_neq with m1; assumption.\n  generalize (Hw2 d0); intuition.\n (* Hw5 *)\n intros d0 Hd0; split.\n  assert (H : max <= d0); [lia|idtac].\n  generalize (Hw5 d0 H); intuition.\n  apply not_exd_CHID; try lia.\n  assert (H : max <= d0); [lia|idtac].\n  generalize (Hw5 d0 H); intuition.\n  assert (H : max <= d0); [lia|idtac].\n  generalize (Hw5 d0 H); intuition.\n (* Hp1 *)\n intros da db Hda Hdb.\n generalize Hdb; intro Hdb2.\n apply exd_CHID_exd_m_or_x_or_max in Hdb2.\n elim Hdb2; clear Hdb2; intro Hdb2.\n  rewrite <- inv_fpoint_CHID; try assumption.\n  assert (H0 : exd (I m1 d t p) da); [simpl;tauto|idtac].\n  generalize (Hp1 da db H0 Hdb2); clear H0.\n  elim (eq_dart_dec d da); trivial.\n   intro Heq; subst d; contradiction.\n  apply exd_not_exd_neq with m2; try assumption.\n  apply Hw1; left; trivial.\n  generalize (Hw4 db Hdb2); intuition.\n elim Hdb2; clear Hdb2; intro Hdb2; subst db.\n  rewrite fpoint_x; try assumption.\n  apply Hp4; assumption.\n  apply Hw1; left; trivial.\n  rewrite fpoint_max; try assumption.\n  apply Hp4; assumption.\n  generalize (Hw5 max (le_refl max)); intuition.\n (* Hp2 *)\n intros da db dc Hda Hdb Hdc Hp0.\n generalize Hdc; intro Hdc2.\n apply exd_CHID_exd_m_or_x_or_max in Hdc2.\n elim Hdc2; clear Hdc2; intro Hdc2.\n  rewrite <- inv_fpoint_CHID; try assumption.\n  assert (H01 : exd (I m1 d t p) da); [simpl;tauto|idtac].\n  assert (H02 : exd (I m1 d t p) db); [simpl;tauto|idtac].\n  generalize (Hp2 da db dc H01 H02 Hdc2); clear H01 H02.\n  elim (eq_dart_dec d da).\n   intro Heq; subst d; contradiction.\n  elim (eq_dart_dec d db).\n   intro Heq; subst d; contradiction.\n  intros H1 H2 H0; apply H0; assumption.\n  apply exd_not_exd_neq with m2; try assumption.\n  apply Hw1; left; trivial.\n  generalize (Hw4 dc Hdc2); intuition.\n elim Hdc2; clear Hdc2; intro Hdc2; subst dc.\n  rewrite fpoint_x; try assumption.\n  assert (H01 : exd (I m1 d t p) da); [simpl;tauto|idtac].\n  assert (H02 : exd (I m1 d t p) db); [simpl;tauto|idtac].\n  assert (H03 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n  generalize (Hm14 da db d H01 H02 H03); clear H01 H02 H03.\n  simpl; elimeqdartdec.\n  elim (eq_dart_dec d da).\n   intro Heq; subst d; contradiction.\n  elim (eq_dart_dec d db).\n   intro Heq; subst d; contradiction.\n  intros H1 H2 H0; apply H0; try assumption.\n  apply Hp4; assumption.\n  apply Hp4; assumption.\n  apply Hw1; left; trivial.\n  rewrite fpoint_max; try assumption.\n  assert (H01 : exd (I m1 d t p) da); [simpl;tauto|idtac].\n  assert (H02 : exd (I m1 d t p) db); [simpl;tauto|idtac].\n  assert (H03 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n  generalize (Hm14 da db d H01 H02 H03); clear H01 H02 H03.\n  simpl; elimeqdartdec.\n  elim (eq_dart_dec d da).\n   intro Heq; subst d; contradiction.\n  elim (eq_dart_dec d db).\n   intro Heq; subst d; contradiction.\n  intros H1 H2 H0; apply H0; try assumption.\n  apply Hp4; assumption.\n  apply Hp4; assumption.\n  generalize (Hw5 max (le_refl max)); intuition.\n (* Hp3 *)\n intros d1 d2 d3 Hd1 Hd2 Hd3 Hp0.\n generalize Hd2; intro Hd20.\n apply exd_CHID_exd_m_or_x_or_max in Hd20.\n elim Hd20; clear Hd20; intro Hd20.\n assert (H1 : fpoint m2 d2 = fpoint (CHID m2 m2 d t p max) d2).\n  apply inv_fpoint_CHID; try assumption.\n  apply exd_not_exd_neq with m2; try assumption.\n  apply Hw1; left; trivial.\n  generalize (Hw4 d2 Hd20); intuition.\n rewrite <- H1 in *.\n generalize Hd3; intro Hd30.\n apply exd_CHID_exd_m_or_x_or_max in Hd30.\n elim Hd30; clear Hd30; intro Hd30.\n assert (H2 : fpoint m2 d3 = fpoint (CHID m2 m2 d t p max) d3).\n  apply inv_fpoint_CHID; try assumption.\n  apply exd_not_exd_neq with m2; try assumption.\n  apply Hw1; left; trivial.\n  generalize (Hw4 d3 Hd30); intuition.\n rewrite <- H2 in *.\n assert (H3 : exd (I m1 d t p) d1); [simpl;tauto|idtac].\n generalize (Hp3 d1 d2 d3 H3 Hd20 Hd30 Hp0); clear H3.\n elim (eq_dart_dec d d1); trivial.\n  intro Heq; subst d; contradiction.\n elim Hd30; clear Hd30; intro Hd30; subst d3.\n assert (H2 : fpoint (CHID m2 m2 d t p max) d = p).\n  apply fpoint_x; try assumption.\n  apply Hw1; left; trivial.\n rewrite H2 in *.\n assert (H3 : exd (I m1 d t p) d1); [simpl;tauto|idtac].\n assert (H4 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n generalize (Hp2 d1 d d2 H3 H4 Hd20); clear H3 H4.\n simpl; elimeqdartdec.\n elim (eq_dart_dec d d1).\n  intro Heq; subst d; contradiction.\n  generalize (Hp4 d1 Hd1); intros H Heq H0.\n  generalize (H0 H); auto with myorientation.\n assert (H2 : fpoint (CHID m2 m2 d t p max) max = p).\n  apply fpoint_max; try assumption.\n  generalize (Hw5 max (le_refl max)); intuition.\n rewrite H2 in *.\n assert (H3 : exd (I m1 d t p) d1); [simpl;tauto|idtac].\n assert (H4 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n generalize (Hp2 d1 d d2 H3 H4 Hd20); clear H3 H4.\n simpl; elimeqdartdec.\n elim (eq_dart_dec d d1).\n  intro Heq; subst d; contradiction.\n  generalize (Hp4 d1 Hd1); intros H Heq H0.\n  generalize (H0 H); auto with myorientation.\n elim Hd20; clear Hd20; intro Hd20; subst d2.\n assert (H1 : fpoint (CHID m2 m2 d t p max) d = p).\n  apply fpoint_x; try assumption.\n  apply Hw1; left; trivial.\n rewrite H1 in *.\n generalize Hd3; intro Hd30.\n apply exd_CHID_exd_m_or_x_or_max in Hd30.\n elim Hd30; clear Hd30; intro Hd30.\n assert (H2 : fpoint m2 d3 = fpoint (CHID m2 m2 d t p max) d3).\n  apply inv_fpoint_CHID; try assumption.\n  apply exd_not_exd_neq with m2; try assumption.\n  apply Hw1; left; trivial.\n  generalize (Hw4 d3 Hd30); intuition.\n rewrite <- H2 in *.\n assert (H3 : exd (I m1 d t p) d1); [simpl;tauto|idtac].\n assert (H4 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n generalize (Hp2 d1 d d3 H3 H4 Hd30); clear H3 H4.\n simpl; elimeqdartdec.\n elim (eq_dart_dec d d1).\n  intro Heq; subst d; contradiction.\n  generalize (Hp4 d1 Hd1); intros H Heq H0.\n  generalize (H0 H); auto with myorientation.\n elim Hd30; clear Hd30; intro Hd30; subst d3.\n assert (H2 : fpoint (CHID m2 m2 d t p max) d = p).\n  apply fpoint_x; try assumption.\n  apply Hw1; left; trivial.\n rewrite H2 in *; tauto.\n assert (H2 : fpoint (CHID m2 m2 d t p max) max = p).\n  apply fpoint_max; try assumption.\n  generalize (Hw5 max (le_refl max)); intuition.\n rewrite H2 in *; tauto.\n assert (H1 : fpoint (CHID m2 m2 d t p max) max = p).\n  apply fpoint_max; try assumption.\n   generalize (Hw5 max (le_refl max)); intuition.\n rewrite H1 in *.\n generalize Hd3; intro Hd30.\n apply exd_CHID_exd_m_or_x_or_max in Hd30.\n elim Hd30; clear Hd30; intro Hd30.\n assert (H2 : fpoint m2 d3 = fpoint (CHID m2 m2 d t p max) d3).\n  apply inv_fpoint_CHID; try assumption.\n  apply exd_not_exd_neq with m2; try assumption.\n  apply Hw1; left; trivial.\n  generalize (Hw4 d3 Hd30); intuition.\n rewrite <- H2 in *.\n assert (H3 : exd (I m1 d t p) d1); [simpl;tauto|idtac].\n assert (H4 : exd (I m1 d t p) d); [simpl;tauto|idtac].\n generalize (Hp2 d1 d d3 H3 H4 Hd30); clear H3 H4.\n simpl; elimeqdartdec.\n elim (eq_dart_dec d d1).\n  intro Heq; subst d; contradiction.\n  generalize (Hp4 d1 Hd1); intros H Heq H0.\n  generalize (H0 H); auto with myorientation.\n elim Hd30; clear Hd30; intro Hd30; subst d3.\n assert (H2 : fpoint (CHID m2 m2 d t p max) d = p).\n  apply fpoint_x; try assumption.\n  apply Hw1; left; trivial.\n rewrite H2 in *; tauto.\n assert (H2 : fpoint (CHID m2 m2 d t p max) max = p).\n  apply fpoint_max; try assumption.\n  generalize (Hw5 max (le_refl max)); intuition.\n rewrite H2 in *; tauto.\n (* Case 3 : m = L *)\n intros m2 max Hm11 Hm12 Hm13 Hm14 Hm21 Hm22 Hm23 Hm24 Hm25 Hw0 Hw1 Hw5 Hp1 Hp2 Hp3.\n simpl in *; intuition.\nQed.\n\n(* ========================== *)\n(* ======= ########## ======= *)\n(* ========================== *)\n\nLemma inv_hmap_inv_poly_planar_well_emb_convex_CH :\n  forall (m:fmap), prec_CH m ->\n  inv_hmap (CH m) /\\ inv_poly (CH m) /\\ planar (CH m) /\\ well_emb (CH m) /\\ convex (CH m).\nProof.\ninduction m.\n (* Case 1 : m = V *)\n intros [Hmap [Hless [Hemb Halign]]].\n simpl in *; intuition.\n unfold inv_poly; simpl; intuition.\n apply plf_planar; simpl; trivial.\n unfold convex; simpl; intuition.\n clear IHm.\n (* Case 2 : m = I *)\n induction m.\n  (* Case 2.1 : m = I V *)\n  intros [Hmap [Hless [Hemb Halign]]].\n  simpl in *; unfold prec_I in *; simpl in *.\n  destruct Hmap as [Hmap [H1 H2]].\n  split; [idtac|split; [idtac|split]].\n  repeat split; try assumption.\n  unfold inv_poly; simpl.\n  intros da Hda.\n  elim Hda; clear Hda; intro Hda; try subst da; try tauto.\n  left; unfold black_dart, succ, pred; simpl; tauto.\n  apply plf_planar; simpl; try trivial.\n  unfold prec_I; simpl; repeat split; trivial.\n  simpl in *; intuition.\n  unfold convex; simpl in *.\n  intros da Hda1 Hda2 db Hdb.\n  elim Hda1; clear Hda1; intro Hda1; try subst da; try tauto.\n  elim Hdb; clear Hdb; intro Hdb; try subst db; try tauto.\n  clear IHm.\n  (* Case 2.2 : m = I I *)\n  intros [Hmap [Hless [Hemb Halign]]].\n  simpl in *; unfold prec_I in *; simpl in *.\n  destruct Hmap as [[Hmap [H1 H2]] [H3 H4]].\n  rewritenotorandnot H4 H4 H5.\n  move H3 after H1; move H5 after H2;\n  move H4 after H3; move Hless after H4.\n(**)\nassert (Hp1 : p <> p0).\n assert (H0 : exd (I (I m d0 t0 p0) d t p) d); [simpl;tauto|idtac].\n generalize (Hemb d H0); unfold well_emb; simpl.\n intros [Hw1 [Hw2 [Hw3 [Hw4 Hw5]]]]; clear H0 Hw1 Hw2 Hw3 Hw4.\n assert (H0 : exd (I (I m d0 t0 p0) d t p) d0); [simpl;tauto|idtac].\n generalize (Hw5 d0 H0); elimeqdartdec; clear H0 Hw5.\n intro H0; apply H0; try assumption.\n rewrite not_exd_A_nil; try assumption.\n rewrite not_exd_A_1_nil; try assumption.\nassert (Hp2 : forall (d:dart), exd m d -> p <> fpoint m d).\n intros da Hda.\n assert (Hneq1 : da <> d). apply exd_not_exd_neq with m ; try assumption.\n assert (Hneq2 : da <> d0). apply exd_not_exd_neq with m ; try assumption.\n assert (H0 : exd (I (I m d0 t0 p0) d t p) d); [simpl;tauto|idtac].\n generalize (Hemb d H0); unfold well_emb; simpl.\n intros [Hw1 [Hw2 [Hw3 [Hw4 Hw5]]]]; clear H0 Hw1 Hw2 Hw3 Hw4.\n assert (H0 : exd (I (I m d0 t0 p0) d t p) da); [simpl;tauto|idtac].\n generalize (Hw5 da H0); elimeqdartdec; clear H0 Hw5.\n intro H0; apply H0; try assumption.\n rewrite not_exd_A_nil; try assumption.\n apply exd_not_nil with m; try assumption.\n rewrite not_exd_A_1_nil; try assumption.\n apply exd_not_nil with m; try assumption.\nassert (Hp3 : forall (d:dart), exd m d -> p0 <> fpoint m d).\n intros da Hda.\n assert (Hneq1 : da <> d). apply exd_not_exd_neq with m ; try assumption.\n assert (Hneq2 : da <> d0). apply exd_not_exd_neq with m ; try assumption.\n assert (H0 : exd (I (I m d0 t0 p0) d t p) d0); [simpl;tauto|idtac].\n generalize (Hemb d0 H0); unfold well_emb; simpl.\n intros [Hw1 [Hw2 [Hw3 [Hw4 Hw5]]]]; clear H0 Hw1 Hw2 Hw3 Hw4.\n assert (H0 : exd (I (I m d0 t0 p0) d t p) da); [simpl;tauto|idtac].\n generalize (Hw5 da H0); elimeqdartdec; clear H0 Hw5.\n intro H0; apply H0; try assumption.\n rewrite not_exd_A_nil; try assumption.\n apply exd_not_nil with m; try assumption.\n rewrite not_exd_A_1_nil; try assumption.\n apply exd_not_nil with m; try assumption.\nassert (Hp4 : forall (da:dart)(db:dart), exd m da -> exd m db -> da <> db -> fpoint m da <> fpoint m db).\n intros da db Hda Hdb Hneq.\n assert (Hneq1 : da <> d). apply exd_not_exd_neq with m ; try assumption.\n assert (Hneq2 : da <> d0). apply exd_not_exd_neq with m ; try assumption.\n assert (Hneq3 : db <> d). apply exd_not_exd_neq with m ; try assumption.\n assert (Hneq4 : db <> d0). apply exd_not_exd_neq with m ; try assumption.\n assert (H0 : exd (I (I m d0 t0 p0) d t p) da); [simpl;tauto|idtac].\n generalize (Hemb da H0); unfold well_emb; simpl.\n intros [Hw1 [Hw2 [Hw3 [Hw4 Hw5]]]]; clear H0 Hw1 Hw2 Hw3 Hw4.\n assert (H0 : exd (I (I m d0 t0 p0) d t p) db); [simpl;tauto|idtac].\n generalize (Hw5 db H0); elimeqdartdec; clear H0 Hw5.\n intro H0; apply H0; try assumption.\n apply neq_sym; assumption.\n rewrite linkless_A_nil; try assumption.\n apply exd_not_nil with m; try assumption.\n rewrite linkless_A_1_nil; try assumption.\n apply exd_not_nil with m; try assumption.\n(**)\nelim (le_lt_dec d0 (max_dart m)).\n elim (le_lt_dec d (max_dart m)).\n  (* 1 / 4 *)\n  intros Hmax1 Hmax2.\n  apply inv_hmap_inv_poly_planar_well_emb_convex_CHI; try assumption.\napply well_emb_I with d0 t0 p0; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; assumption.\napply well_emb_I with d t p; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; try assumption.\napply and_not_not_or; split; assumption.\napply noalign_I with d0 t0 p0; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; assumption.\napply noalign_I with d t p; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; try assumption.\napply and_not_not_or; split; assumption.\n  apply inv_hmap_CH2; try assumption.\n  apply inv_poly_CH2; try assumption.\n  apply planar_CH2; try assumption.\n  apply well_emb_CH2; try assumption.\n   apply neq_sym_point; assumption.\n  apply convex_CH2; try assumption.\n   apply neq_sym_point; assumption.\n(* Hw0 *)\nintros da Hda;\napply neq_le_trans with d; [assumption|lia].\n(* Hw1 *)\nintros da Hda; simpl.\napply and_not_not_or; split.\napply exd_le_max_dart in Hda; lia.\napply and_not_not_or; split.\napply exd_le_max_dart in Hda; lia.\napply and_not_not_or; split.\napply neq_sym; apply exd_not_exd_neq with m; assumption.\napply and_not_not_or; split; try tauto.\napply neq_sym; apply exd_not_exd_neq with m; assumption.\n(* Hw5 *)\nintros da Hda; split; simpl.\napply gt_max_dart_not_exd; lia.\napply and_not_not_or; split; [lia|idtac].\napply and_not_not_or; split; [lia|idtac].\napply and_not_not_or; split; [lia|idtac].\napply and_not_not_or; split; [lia|tauto].\n(* Hp1 *)\nintros da db Hda Hdb; simpl in *.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelimeqdartdec; apply neq_sym_point; apply Hp2; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim eq_dart_dec; intro Heq; [lia|idtac].\nelimeqdartdec; apply neq_sym_point; apply Hp3; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim eq_dart_dec; intro Heq1; [lia|idtac].\nelim eq_dart_dec; intro Heq2; [lia|idtac].\nelimeqdartdec; apply neq_sym_point; apply Hp2; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db; try tauto.\nelim eq_dart_dec; intro Heq1; [lia|idtac].\nelim eq_dart_dec; intro Heq2; [lia|idtac].\nelim eq_dart_dec; intro Heq3; [intuition|idtac].\nelimeqdartdec; apply neq_sym_point; apply Hp3; assumption.\n(* Hp2 *)\nintros da db dc Hda Hdb Hdc Hp0; simpl in *.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\ngeneralize (Halign da db d H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp2; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da db d0 H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp3; assumption.\napply neq_sym_point; apply Hp3; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\ngeneralize (Halign da db d H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp2; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da db d0 H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp3; assumption.\napply neq_sym_point; apply Hp3; assumption.\n(* Hp3 *)\nintros da db dc Hda Hdb Hdc; simpl in *.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq2; subst d0; contradiction.\nintros Heq1 Heq2.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec; tauto.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp3; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp3; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|tauto].\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdb; clear Hdb; intro Hdb; try subst db; try tauto.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\n  (* 2 / 4 *)\n  intros Hmax1 Hmax2.\n  apply inv_hmap_inv_poly_planar_well_emb_convex_CHI; try assumption.\napply well_emb_I with d0 t0 p0; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; assumption.\napply well_emb_I with d t p; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; try assumption.\napply and_not_not_or; split; assumption.\napply noalign_I with d0 t0 p0; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; assumption.\napply noalign_I with d t p; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; try assumption.\napply and_not_not_or; split; assumption.\n  apply inv_hmap_CH2; try assumption; lia.\n  apply inv_poly_CH2; try assumption; lia.\n  apply planar_CH2; try assumption; lia.\n  apply well_emb_CH2; try assumption; try lia.\n   apply neq_sym_point; assumption.\n  apply convex_CH2; try assumption; try lia.\n   apply neq_sym_point; assumption.\n(* Hw0 *)\nintros da Hda.\napply neq_le_trans with d; [assumption|lia].\n(* Hw1 *)\nintros da Hda; simpl.\napply and_not_not_or; split.\napply exd_le_max_dart in Hda; lia.\napply and_not_not_or; split.\napply exd_le_max_dart in Hda; lia.\napply and_not_not_or; split.\napply neq_sym; apply exd_not_exd_neq with m; assumption.\napply and_not_not_or; split; try tauto.\napply neq_sym; apply exd_not_exd_neq with m; assumption.\n(* Hw5 *)\nintros da Hda; split; simpl.\napply gt_max_dart_not_exd; lia.\napply and_not_not_or; split; [lia|idtac].\napply and_not_not_or; split; [lia|idtac].\napply and_not_not_or; split; [lia|idtac].\napply and_not_not_or; split; [lia|tauto].\n(* Hp1 *)\nintros da db Hda Hdb; simpl in *.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelimeqdartdec; apply neq_sym_point; apply Hp2; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim eq_dart_dec; intro Heq; [lia|idtac].\nelimeqdartdec; apply neq_sym_point; apply Hp3; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim eq_dart_dec; intro Heq1; [lia|idtac].\nelim eq_dart_dec; intro Heq2; [lia|idtac].\nelimeqdartdec; apply neq_sym_point; apply Hp2; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db; try tauto.\nelim eq_dart_dec; intro Heq1; [lia|idtac].\nelim eq_dart_dec; intro Heq2; [lia|idtac].\nelim eq_dart_dec; intro Heq3; [intuition|idtac].\nelimeqdartdec; apply neq_sym_point; apply Hp3; assumption.\n(* Hp2 *)\nintros da db dc Hda Hdb Hdc Hp0; simpl in *.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\ngeneralize (Halign da db d H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp2; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da db d0 H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp3; assumption.\napply neq_sym_point; apply Hp3; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\ngeneralize (Halign da db d H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp2; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da db d0 H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp3; assumption.\napply neq_sym_point; apply Hp3; assumption.\n(* Hp3 *)\nintros da db dc Hda Hdb Hdc; simpl in *.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq2; subst d0; contradiction.\nintros Heq1 Heq2.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec; tauto.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp3; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp3; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|tauto].\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdb; clear Hdb; intro Hdb; try subst db; try tauto.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\n elim (le_lt_dec d d0).\n  (* 3 / 4 *)\n  intros Hmax1 Hmax2.\n  apply inv_hmap_inv_poly_planar_well_emb_convex_CHI; try assumption.\napply well_emb_I with d0 t0 p0; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; assumption.\napply well_emb_I with d t p; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; try assumption.\napply and_not_not_or; split; assumption.\napply noalign_I with d0 t0 p0; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; assumption.\napply noalign_I with d t p; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; try assumption.\napply and_not_not_or; split; assumption.\n  apply inv_hmap_CH2; try assumption; lia.\n  apply inv_poly_CH2; try assumption; lia.\n  apply planar_CH2; try assumption; lia.\n  apply well_emb_CH2; try assumption; try lia.\n   apply neq_sym_point; assumption.\n  apply convex_CH2; try assumption; try lia.\n   apply neq_sym_point; assumption.\n(* Hw0 *)\nintros da Hda.\napply neq_le_trans with d; [assumption|lia].\n(* Hw1 *)\nintros da Hda; simpl.\napply and_not_not_or; split.\napply exd_le_max_dart in Hda; lia.\napply and_not_not_or; split.\napply exd_le_max_dart in Hda; lia.\napply and_not_not_or; split.\napply neq_sym; apply exd_not_exd_neq with m; assumption.\napply and_not_not_or; split; try tauto.\napply neq_sym; apply exd_not_exd_neq with m; assumption.\n(* Hw5 *)\nintros da Hda; split; simpl.\napply gt_max_dart_not_exd; lia.\napply and_not_not_or; split; [lia|idtac].\napply and_not_not_or; split; [lia|idtac].\napply and_not_not_or; split; [lia|idtac].\napply and_not_not_or; split; [lia|tauto].\n(* Hp1 *)\nintros da db Hda Hdb; simpl in *.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelimeqdartdec; apply neq_sym_point; apply Hp2; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim eq_dart_dec; intro Heq; [lia|idtac].\nelimeqdartdec; apply neq_sym_point; apply Hp3; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim eq_dart_dec; intro Heq1; [lia|idtac].\nelim eq_dart_dec; intro Heq2; [lia|idtac].\nelimeqdartdec; apply neq_sym_point; apply Hp2; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db; try tauto.\nelim eq_dart_dec; intro Heq1; [lia|idtac].\nelim eq_dart_dec; intro Heq2; [lia|idtac].\nelim eq_dart_dec; intro Heq3; [intuition|idtac].\nelimeqdartdec; apply neq_sym_point; apply Hp3; assumption.\n(* Hp2 *)\nintros da db dc Hda Hdb Hdc Hp0; simpl in *.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\ngeneralize (Halign da db d H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp2; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da db d0 H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp3; assumption.\napply neq_sym_point; apply Hp3; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\ngeneralize (Halign da db d H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp2; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da db d0 H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp3; assumption.\napply neq_sym_point; apply Hp3; assumption.\n(* Hp3 *)\nintros da db dc Hda Hdb Hdc; simpl in *.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq2; subst d0; contradiction.\nintros Heq1 Heq2.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec; tauto.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp3; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp3; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|tauto].\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdb; clear Hdb; intro Hdb; try subst db; try tauto.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\n  (* 4 / 4 *)\n  intros Hmax1 Hmax2.\n  apply inv_hmap_inv_poly_planar_well_emb_convex_CHI; try assumption.\napply well_emb_I with d0 t0 p0; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; assumption.\napply well_emb_I with d t p; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; try assumption.\napply and_not_not_or; split; assumption.\napply noalign_I with d0 t0 p0; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; assumption.\napply noalign_I with d t p; try assumption.\nsimpl; unfold prec_I; simpl; repeat split; try assumption.\napply and_not_not_or; split; assumption.\n  apply inv_hmap_CH2; try assumption; lia.\n  apply inv_poly_CH2; try assumption; lia.\n  apply planar_CH2; try assumption; lia.\n  apply well_emb_CH2; try assumption; try lia.\n   apply neq_sym_point; assumption.\n  apply convex_CH2; try assumption; try lia.\n   apply neq_sym_point; assumption.\n(* Hw0 *)\nintros da Hda.\napply neq_le_trans with d; [assumption|lia].\n(* Hw1 *)\nintros da Hda; simpl.\napply and_not_not_or; split.\napply exd_le_max_dart in Hda; lia.\napply and_not_not_or; split.\napply exd_le_max_dart in Hda; lia.\napply and_not_not_or; split.\napply neq_sym; apply exd_not_exd_neq with m; assumption.\napply and_not_not_or; split; try tauto.\napply neq_sym; apply exd_not_exd_neq with m; assumption.\n(* Hw5 *)\nintros da Hda; split; simpl.\napply gt_max_dart_not_exd; lia.\napply and_not_not_or; split; [lia|idtac].\napply and_not_not_or; split; [lia|idtac].\napply and_not_not_or; split; [lia|idtac].\napply and_not_not_or; split; [lia|tauto].\n(* Hp1 *)\nintros da db Hda Hdb; simpl in *.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelimeqdartdec; apply neq_sym_point; apply Hp2; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim eq_dart_dec; intro Heq; [lia|idtac].\nelimeqdartdec; apply neq_sym_point; apply Hp3; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim eq_dart_dec; intro Heq1; [lia|idtac].\nelim eq_dart_dec; intro Heq2; [lia|idtac].\nelimeqdartdec; apply neq_sym_point; apply Hp2; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db; try tauto.\nelim eq_dart_dec; intro Heq1; [lia|idtac].\nelim eq_dart_dec; intro Heq2; [lia|idtac].\nelim eq_dart_dec; intro Heq3; [intuition|idtac].\nelimeqdartdec; apply neq_sym_point; apply Hp3; assumption.\n(* Hp2 *)\nintros da db dc Hda Hdb Hdc Hp0; simpl in *.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\ngeneralize (Halign da db d H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp2; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da db d0 H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp3; assumption.\napply neq_sym_point; apply Hp3; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\ngeneralize (Halign da db d H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp2; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) db); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da db d0 H01 H02 H03); simpl; elimeqdartdec.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d db).\n intro Heq2; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq3; subst d0; contradiction.\nelim (eq_dart_dec d0 db).\n intro Heq4; subst d0; contradiction.\nintros Heq1 Heq2 Heq3 Heq4.\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp3; assumption.\napply neq_sym_point; apply Hp3; assumption.\n(* Hp3 *)\nintros da db dc Hda Hdb Hdc; simpl in *.\nelim (eq_dart_dec d da).\n intro Heq1; subst d; contradiction.\nelim (eq_dart_dec d0 da).\n intro Heq2; subst d0; contradiction.\nintros Heq1 Heq2.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec; tauto.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp3; assumption.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\nintro H; apply H; try assumption.\napply neq_sym_point; apply Hp2; assumption.\napply neq_sym_point; apply Hp3; assumption.\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|tauto].\nelim Hdb; clear Hdb; intro Hdb; try subst db.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdb; clear Hdb; intro Hdb; try subst db; try tauto.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|tauto].\nelim Hdc; clear Hdc; intro Hdc; try subst dc.\nelimeqdartdec.\nelim eq_dart_dec; intro Heq3; [lia|idtac].\nelim eq_dart_dec; intro Heq4; [lia|idtac].\nelim eq_dart_dec; intro Heq5; [lia|idtac].\nelim eq_dart_dec; intro Heq6; [lia|idtac].\nassert (H01 : exd (I (I m d0 t0 p0) d t p) da); [simpl; tauto | idtac].\nassert (H02 : exd (I (I m d0 t0 p0) d t p) d); [simpl; tauto | idtac].\nassert (H03 : exd (I (I m d0 t0 p0) d t p) d0); [simpl; tauto | idtac].\ngeneralize (Halign da d d0 H01 H02 H03); simpl; elimeqdartdec.\ngeneralize (neq_sym_point p0 (fpoint m da) (Hp3 da Hda)).\ngeneralize (neq_sym_point p (fpoint m da) (Hp2 da Hda)).\nauto with myorientation.\nelim Hdc; clear Hdc; intro Hdc; try subst dc; try tauto.\n  clear IHm.\n  (* Case 2.3 : m = I L *)\n  intros [Hmap [Hless [Hemb Halign]]].\n  simpl in *; intuition.\n  clear IHm.\n (* Case 3 : m = L *)\n intros [Hmap [Hless [Hemb Halign]]].\n simpl in *; intuition.\nQed.\n\n(* ========================== *)\n(* ======= ########## ======= *)\n(* ========================== *)\n\nTheorem inv_hmap_CH : forall (m:fmap),\n  prec_CH m -> inv_hmap (CH m).\nProof.\nintros m H; generalize (inv_hmap_inv_poly_planar_well_emb_convex_CH m H); intuition.\nQed.\n\nTheorem inv_poly_CH : forall (m:fmap),\n  prec_CH m -> inv_poly (CH m).\nProof.\nintros m H; generalize (inv_hmap_inv_poly_planar_well_emb_convex_CH m H); intuition.\nQed.\n\nTheorem planar_CH : forall (m:fmap),\n  prec_CH m -> planar (CH m).\nProof.\nintros m H; generalize (inv_hmap_inv_poly_planar_well_emb_convex_CH m H); intuition.\nQed.\n\nTheorem well_emb_CH : forall (m:fmap),\n  prec_CH m -> well_emb (CH m).\nProof.\nintros m H; generalize (inv_hmap_inv_poly_planar_well_emb_convex_CH m H); intuition.\nQed.\n\nTheorem convex_CH : forall (m:fmap),\n  prec_CH m -> convex (CH m).\nProof.\nintros m H; generalize (inv_hmap_inv_poly_planar_well_emb_convex_CH m H); intuition.\nQed.\n", "meta": {"author": "magaud", "repo": "ConvexHullV1", "sha": "25c4f9e2989c5c41ee31097a164014c0a6727498", "save_path": "github-repos/coq/magaud-ConvexHullV1", "path": "github-repos/coq/magaud-ConvexHullV1/ConvexHullV1-25c4f9e2989c5c41ee31097a164014c0a6727498/CH10_CHI_CH.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24106883695944822}}
{"text": "(* PREAMBLE *)\n\nFrom compcert.common    Require AST.\nFrom compcert.lib       Require Coqlib.\nFrom compcert.cfrontend Require Csyntax Csem.\nFrom trancert.lib       Require Decidability Tac.\nFrom trancert.analysis  Require Subexpr.\n\nImport AST Csyntax Csem Tac Coqlib Decidability Subexpr.\n\n\nSection ExistsVar.\n\n  Variable P: common.AST.ident -> Prop.\n\n  Definition expr_is_var e : Prop := exists v ty, e = Evar v ty /\\ P v.\n\n  Definition exists_var_in_expr e:  Prop := subexpr_cond expr_is_var e.\n  Definition exists_var_in_exprlist el:  Prop := subexprlist_cond expr_is_var el.\n\n  Definition exists_var_in_ctx (C: expr->expr): Prop := (exists k1 k2, context k1 k2 C ) -> forall e, exists_var_in_expr (C e).\n  Definition exists_var_in_ctxlist (C: expr->exprlist): Prop := (exists k, contextlist k C ) -> forall e, exists_var_in_exprlist (C e).\n\n  Section Decidability.\n    Import lib.Decidability.\n    Hypothesis Hdec: forall v, dec (P v).\n\n    Lemma expr_is_var_dec:\n      forall e : expr, dec (expr_is_var e).\n    Proof.\n      unfold dec, expr_is_var in *.\n      intros []; try solve [\n                       constructor 2;\n                       inversion 1;\n                       repeat destruct_exists;\n                       repeat destruct_and;\n                       discriminate].\n      - destruct (Hdec x).\n        repeat constructor. eauto.\n        constructor 2. inversion 1. decomp. inv H. contradiction.\n    Defined.\n\n    Theorem exists_var_in_expr_dec: forall e, dec (exists_var_in_expr e).\n    Proof.\n        apply subexpr_cond_dec. apply expr_is_var_dec.\n    Defined.\n\n    Theorem exists_var_in_exprlist_dec: forall e, dec (exists_var_in_exprlist e).\n    Proof.\n        apply subexprlist_cond_dec.\n        apply expr_is_var_dec.\n    Defined.\n\n  End Decidability.\n\n  (** It's hard to generalize this for [subexpr_cond]: an arbitrary [P] might\n  only hold for complex subexpressions that might be cut in pieces when an\n  expression is split onto a context and a subexpression.\n   *)\n\n  Hint Constructors subexpr_cond: subexpr.\n  Hint Constructors or: subexpr.\n  Hint Constructors and: subexpr.\n  Hint Constructors ex: subexpr.\n  Hint Extern 1 => decomp: subexpr.\n\n  Lemma exists_var_context_split:\n    forall C k1 k2,\n      context k1 k2 C ->\n      forall e, exists_var_in_expr (C e) -> (exists_var_in_expr e \\/ exists_var_in_ctx C)\n  with exists_var_contextlist_split:\n         forall C k, contextlist k C ->\n                forall e, exists_var_in_exprlist (C e) ->\n                     ( exists_var_in_expr e \\/ exists_var_in_ctxlist C ).\n  Proof.\n    {\n      clear exists_var_context_split.\n      unfold exists_var_in_ctx, exists_var_in_expr in *.\n      induction 1; auto;\n        try solve [\n              inversion_clear 1;\n              solve\n                [\n                  match goal with [H: subexpr_cond _ _|-_] => eapply IHcontext in H end;\n                  decomp; auto;\n                  solve [left; eauto with subexpr| right; eauto with subexpr]\n                |\n                match goal with [H: expr_is_var _|-_] => inversion_clear H end ;\n                eauto with subexpr]\n            | auto |\n            inversion_clear 1; decomp; eauto with subexpr;\n            [match goal with [H: subexpr_cond _ _|-_] => eapply IHcontext in H end; decomp;\n             right; intros; constructor; eauto|\n             match goal with [H: expr_is_var _|-_] => inversion_clear H end ;\n             eauto with subexpr]\n            ].\n      - inversion_clear 1; decomp; eauto with subexpr.\n        + eapply exists_var_contextlist_split in H1; [|eassumption].\n          decomp; eauto.\n          right. intros. decomp. apply ecs_call. right. apply H1. eauto.\n        + inv H1. decomp.\n      - inversion_clear 1.\n        + eapply exists_var_contextlist_split in H1; [|eassumption].\n          decomp; eauto.\n          right. intros. decomp. apply ecs_builtin. apply H1. eauto.\n        + inv H1. decomp.\n    }\n    {\n      clear exists_var_contextlist_split.\n      induction 1.\n      - inversion_clear 1; decomp.\n        eapply exists_var_context_split in H1; decomp; eauto.\n        right.\n        constructor; auto. left. apply H1; eauto.\n        right.\n        constructor. auto.\n      - inversion_clear 1; decomp.\n        + right. constructor; eauto; decomp.\n        + eapply IHcontextlist in H1; decomp; eauto. \n          right. constructor; auto. right. apply H1.\n          decomp.\n          inv H0; eauto.\n    }\n  Defined.\n\n\n\nEnd ExistsVar.\n\n\nSection AllPointers.\n  Import common.Values Integers.Ptrofs.\n\n  Variable P: block -> int  -> Prop.\n(* FIXME we can probably rewrite it with subexpr_cond. *)\n  Inductive forall_pointers_in_expr : expr -> Prop :=\n  | aep_val : forall b ofs ty, P b ofs -> forall_pointers_in_expr (Eval (Vptr b ofs) ty)\n  | aep_loc: forall b ofs ty, P b ofs -> forall_pointers_in_expr (Eloc b ofs ty)\n\n  (* boilerplate*)\n  | aep_var : forall x ty, forall_pointers_in_expr (Evar x ty)\n  | aep_sizeof: forall x ty, forall_pointers_in_expr (Esizeof x ty)\n  | aep_alignof: forall x ty, forall_pointers_in_expr (Ealignof x ty)\n  | aep_field : forall l f ty, forall_pointers_in_expr l -> forall_pointers_in_expr (Efield l f ty)\n  | aep_valof : forall l ty, forall_pointers_in_expr l -> forall_pointers_in_expr (Evalof l ty)\n  | aep_deref : forall r ty, forall_pointers_in_expr r -> forall_pointers_in_expr (Ederef r ty)\n  | aep_addrof: forall l ty, forall_pointers_in_expr l -> forall_pointers_in_expr (Eaddrof l ty)\n  | aep_unop: forall op r ty, forall_pointers_in_expr r -> forall_pointers_in_expr (Eunop op r ty)\n  | aep_binop: forall op r1 r2 ty,\n      forall_pointers_in_expr r1 ->\n      forall_pointers_in_expr r2 ->\n      forall_pointers_in_expr (Ebinop op r1 r2 ty)\n  | aep_cast: forall r ty, forall_pointers_in_expr r -> forall_pointers_in_expr (Ecast r ty)\n  | aep_seqand: forall r1 r2 ty,\n      forall_pointers_in_expr r1 ->\n      forall_pointers_in_expr r2 ->\n      forall_pointers_in_expr (Eseqand r1 r2 ty)\n  | aep_seqor: forall r1 r2 ty,\n      forall_pointers_in_expr r1 ->\n      forall_pointers_in_expr r2 ->\n      forall_pointers_in_expr (Eseqor r1 r2 ty)\n  | aep_condition: forall r1 r2 r3 ty,\n      forall_pointers_in_expr r1 ->\n      forall_pointers_in_expr r2 ->\n      forall_pointers_in_expr r3 ->\n      forall_pointers_in_expr (Econdition r1 r2 r3 ty)\n  | aep_assign: forall l r ty,\n      forall_pointers_in_expr l ->\n      forall_pointers_in_expr r ->\n      forall_pointers_in_expr (Eassign l r ty)\n  | aep_assignop: forall op l r tyres ty,\n      forall_pointers_in_expr l ->\n      forall_pointers_in_expr r ->\n      forall_pointers_in_expr (Eassignop op l r tyres ty)\n  | aep_postincr: forall i l ty, forall_pointers_in_expr l -> forall_pointers_in_expr (Epostincr i l ty)\n  | aep_comma: forall r1 r2 ty,\n      forall_pointers_in_expr r1 ->\n      forall_pointers_in_expr r2 ->\n      forall_pointers_in_expr (Ecomma r1 r2 ty)\n  | aep_call: forall r1 rargs ty,\n      forall_pointers_in_expr r1  ->\n      forall_pointers_in_exprlist rargs  ->\n      forall_pointers_in_expr (Ecall r1 rargs ty)\n  | aep_builtin: forall ef tyargs rargs ty,\n      forall_pointers_in_exprlist rargs ->\n      forall_pointers_in_expr (Ebuiltin ef tyargs rargs ty)\n  | ep_paren: forall r tc ty, forall_pointers_in_expr r -> forall_pointers_in_expr (Eparen r tc ty)\n  with forall_pointers_in_exprlist : exprlist-> Prop :=\n  | aepl_first : forall_pointers_in_exprlist Enil\n  | aepl_rest : forall e es,\n      forall_pointers_in_expr e ->\n      forall_pointers_in_exprlist es -> forall_pointers_in_exprlist (Econs e es)\n  .\n\n  Hypothesis Hdec: forall b ofs, dec (P b ofs).\n  Theorem forall_pointers_in_expr_dec:\n    forall e, dec (forall_pointers_in_expr e)\n    with forall_pointers_in_exprlist_dec:\n           forall e, dec (forall_pointers_in_exprlist e).\n  Proof.\n    {\n      clear forall_pointers_in_expr_dec.\n      induction e; try solve [\n                         left; constructor\n                       | try destruct IHe;\n                         try destruct IHe1;\n                         try destruct IHe2;\n                         try destruct IHe3;\n                         [left; constructor|right; inversion_clear 1..]; auto\n                       ].\n      - destruct v; try solve [right; inversion_clear 1].\n        destruct (Hdec b i); [left|right].\n        + constructor; auto.\n        + inversion 1. contradiction.\n      - destruct (forall_pointers_in_exprlist_dec rargs), IHe;\n          [ left; constructor| right; inversion_clear 1..]; eauto.\n      - destruct (forall_pointers_in_exprlist_dec rargs);\n          [ left; constructor| right; inversion_clear 1..]; eauto.\n      - destruct (Hdec b ofs); [left|right].\n        + constructor; auto.\n        + inversion 1. contradiction.\n    }\n    {\n      clear forall_pointers_in_exprlist_dec.\n      induction e.\n      - left. repeat constructor.\n      - destruct (forall_pointers_in_expr_dec r1), IHe;\n          [ left; repeat constructor | right; inversion_clear 1..]; eauto.\n    }\n  Defined.\n\n\nEnd AllPointers.\n", "meta": {"author": "sayon", "repo": "trancert", "sha": "eb5c94c75067782158522f61bdd7cc902bf74185", "save_path": "github-repos/coq/sayon-trancert", "path": "github-repos/coq/sayon-trancert/trancert-eb5c94c75067782158522f61bdd7cc902bf74185/analysis/ExprQuant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24106883695944822}}
{"text": "Add LoadPath \"PLC\".\nAdd LoadPath \"../metatheory\".\nAdd LoadPath \"../lib\".\nRequire PLC_confluence.\nRequire Export F_soundness.\n\nLtac gather_atoms ::=\n  let A := gather_atoms_with (fun x : vars => x) in\n  let B := gather_atoms_with (fun x : var => {{ x }}) in\n  let C := gather_atoms_with (fun x : typing_env => dom x) in\n  let D1 := gather_atoms_with (fun x => fv_term x) in\n  let D2 := gather_atoms_with (fun x => ftv_typ x) in\n  let D3 := gather_atoms_with (fun x => ftv_term x) in\n  let D4 := gather_atoms_with (fun x => PLC_ott.fv_term x) in\n  constr:(A \\u B \\u C \\u D1 \\u D2 \\u D3 \\u D4).\n\n\nInductive erase : term -> PLC_ott.term -> Prop :=\n| erase_var : forall (x: termvar),\n  erase (term_var_f x) (PLC_ott.term_var_f x)\n| erase_abs : forall L τ e e',\n  lc_typ τ ->\n  (forall (x: termvar), x ∉ L ->\n  erase (open_term_wrt_term e (term_var_f x)) (PLC_ott.open_term_wrt_term e' (PLC_ott.term_var_f x))) ->\n  erase (term_abs τ e) (PLC_ott.term_abs e')\n| erase_app : forall e₁ e₁' e₂ e₂',\n  erase e₁ e₁' ->\n  erase e₂ e₂' ->\n  erase (term_app e₁ e₂) (PLC_ott.term_app e₁' e₂')\n| erase_gen : forall L e e',\n  (forall (x: termvar), x `notin` L ->\n  erase (open_term_wrt_typ e (typ_var_f x)) (PLC_ott.open_term_wrt_term e' (PLC_ott.term_var_f x))) ->\n  erase (term_gen e) (PLC_ott.term_abs e')\n| erase_TApp : forall τ e e',\n  lc_typ τ ->\n  erase e e' ->\n  erase (term_inst e τ) (PLC_ott.term_app e' (PLC_ott.term_abs (PLC_ott.term_var_b 0)))\n.\nHint Constructors erase.\n\nLemma id_regular : PLC_ott.lc_term (PLC_ott.term_abs (PLC_ott.term_var_b 0)).\nProof.\nconstructor; intros;\nunfold PLC_ott.open_term_wrt_term; simpl; auto.\nQed.\nHint Immediate id_regular.\n\nLemma erase_regular1 : forall e e',\n  erase e e' → lc_term e.\nProof.\nintros e e' H.\ninduction H; auto.\nQed.\n\nLemma erase_regular2 : forall e e',\n  erase e e' → PLC_ott.lc_term e'.\nProof.\nintros e e' H.\ninduction H; auto.\nQed.\nHint Resolve erase_regular1 erase_regular2.\n\nLemma erase_subst : forall e₁ e₂ e₁' e₂' x,\n  erase e₁ e₁' → erase e₂ e₂' →\n  erase (subst_term e₂ x e₁) (PLC_ott.subst_term e₂' x e₁').\nProof.\nintros e₁ e₂ e₁' e₂' x H1 H2.\ninduction H1; simpl in *; auto.\nCase \"var\".\nunfold termvar in *; unfold PLC_ott.termvar in *.\ndestruct (x0 == x); auto.\nCase \"abs\".\npick fresh y. apply erase_abs with (L := L ∪ {{x}}); intros; auto.\nreplace (term_var_f x0) with (subst_term e₂ x (term_var_f x0)).\nrewrite <- subst_term_open_term_wrt_term; eauto.\nreplace (PLC_ott.term_var_f x0) with (PLC_ott.subst_term e₂' x (PLC_ott.term_var_f x0)).\nrewrite <- PLC_inf.subst_term_open_term_wrt_term; eauto.\nautorewrite with lngen; reflexivity.\nautorewrite with lngen; reflexivity.\nCase \"gen\".\npick fresh y. apply erase_gen with (L := L ∪ {{x}}); intros; auto.\nrewrite <- subst_term_open_term_wrt_typ; eauto.\nreplace (PLC_ott.term_var_f x0) with (PLC_ott.subst_term e₂' x (PLC_ott.term_var_f x0)).\nrewrite <- PLC_inf.subst_term_open_term_wrt_term; eauto.\nautorewrite with lngen; reflexivity.\nQed.\nHint Resolve erase_subst.\n\nLemma erase_tsubst : forall e e' τ a,\n  lc_typ τ → erase e e' → erase (tsubst_term τ a e) e'.\nProof.\nintros e e' τ a Hlc H.\ninduction H; simpl in *; auto with lngen.\nCase \"abs\".\npick fresh x. apply erase_abs with (L := L ∪ {{a}}); intros; auto with lngen.\nreplace (term_var_f x0) with (tsubst_term τ a (term_var_f x0)) by reflexivity.\nrewrite <- tsubst_term_open_term_wrt_term; eauto.\nCase \"gen\".\npick fresh x. apply erase_gen with (L := L ∪ {{a}}); intros; auto.\nreplace (typ_var_f x0) with (tsubst_typ τ a (typ_var_f x0)).\nrewrite <- tsubst_term_open_term_wrt_typ; eauto.\nautorewrite with lngen; auto.\nQed.\nHint Resolve erase_tsubst.\n\nLemma erase_fv : forall e e',\n  erase e e' → fv_term e [=] PLC_ott.fv_term e'.\nProof.\nintros e e' H. induction H; simpl in *; try fsetdec.\nCase \"abs\".\npick fresh x.\nassert (PLC_ott.fv_term (PLC_ott.open_term_wrt_term e' (PLC_ott.term_var_f x)) [<=] PLC_ott.fv_term (PLC_ott.term_var_f x) ∪ PLC_ott.fv_term e') by auto with lngen.\nassert (PLC_ott.fv_term e' [<=] PLC_ott.fv_term (PLC_ott.open_term_wrt_term e' (PLC_ott.term_var_f x))) by auto with lngen.\nassert (fv_term (open_term_wrt_term e (term_var_f x)) [<=] fv_term (term_var_f x) ∪ fv_term e) by auto with lngen.\nassert (fv_term e [<=] fv_term (open_term_wrt_term e (term_var_f x))) by auto with lngen.\nassert (fv_term (open_term_wrt_term e (term_var_f x)) [=] PLC_ott.fv_term (PLC_ott.open_term_wrt_term e' (PLC_ott.term_var_f x))) by auto.\nsimpl in *.\nfsetdec.\nCase \"gen\".\npick fresh x.\nassert (PLC_ott.fv_term (PLC_ott.open_term_wrt_term e' (PLC_ott.term_var_f x)) [<=] PLC_ott.fv_term (PLC_ott.term_var_f x) ∪ PLC_ott.fv_term e') by auto with lngen.\nassert (PLC_ott.fv_term e' [<=] PLC_ott.fv_term (PLC_ott.open_term_wrt_term e' (PLC_ott.term_var_f x))) by auto with lngen.\nassert (fv_term (open_term_wrt_typ e (typ_var_f x)) [<=] fv_term e) by auto with lngen.\nassert (fv_term e [<=] fv_term (open_term_wrt_typ e (typ_var_f x))) by auto with lngen.\nassert (fv_term (open_term_wrt_typ e (typ_var_f x)) [=] PLC_ott.fv_term (PLC_ott.open_term_wrt_term e' (PLC_ott.term_var_f x))) by auto.\nsimpl in *.\nfsetdec.\nQed.\n\nLemma erase_uniqueness : forall e e₁ e₂,\n  erase e e₁ → erase e e₂ → e₁ = e₂.\nProof.\nintros e e1 e2 H1 H2.\ngeneralize dependent e2.\ninduction H1; intros e2 H2; inversion H2; subst; f_equal; auto.\nCase \"abs\". pick fresh x.\napply PLC_inf.open_term_wrt_term_inj with (x1 := x); auto.\nCase \"gen\". pick fresh x.\napply PLC_inf.open_term_wrt_term_inj with (x1 := x); auto.\nQed.\n\nLemma erase_exists : forall e, lc_term e → exists e', erase e e'.\nProof.\nintros e H.\ninduction H; eauto.\nCase \"abs\". pick fresh x.\ndestruct (H1 x) as [e' H2].\nexists (PLC_ott.term_abs (PLC_inf.close_term_wrt_term x e')).\napply erase_abs with (L := PLC_ott.fv_term e' ∪ {{x}}); intros; auto.\nrewrite <- PLC_inf.subst_term_spec.\nrewrite (subst_term_intro x); auto.\nCase \"app\".\ndestruct IHlc_term1 as [e1' H1].\ndestruct IHlc_term2 as [e2' H2].\neauto.\nCase \"gen\". pick fresh x.\ndestruct (H0 x) as [e' H1].\nexists (PLC_ott.term_abs (PLC_inf.close_term_wrt_term x e')).\napply erase_gen with (L := PLC_ott.fv_term e' ∪ {{x}}); intros; auto.\nrewrite <- PLC_inf.subst_term_spec.\nrewrite (tsubst_term_intro x); auto.\nassert (x ∉ PLC_ott.fv_term e').\nassert (fv_term (open_term_wrt_typ e (typ_var_f x)) [=] PLC_ott.fv_term e') by auto using erase_fv.\nassert (fv_term (open_term_wrt_typ e (typ_var_f x)) [<=] fv_term e). auto with lngen.\nfsetdec.\nautorewrite with lngen. auto.\nCase \"inst\". destruct IHlc_term as [e' H1]. eauto.\nQed.\n\nLemma erase_red0 : forall e₁ e₂ e₁' e₂',\n  red0 e₁ e₂ → erase e₁ e₁' →\n  erase e₂ e₂' → PLC_ott.red0 e₁' e₂'.\nProof.\nintros e₁ e₂ e₁' e₂' Hred H1 H2.\ninversion Hred; subst; inversion H1; subst.\nCase \"beta\".\ninversion H6; subst. assert (e₂' = PLC_ott.open_term_wrt_term e' e₂'0).\neapply erase_uniqueness; eauto.\npick fresh x. rewrite (subst_term_intro x); auto.\nrewrite (PLC_inf.subst_term_intro x); auto.\nsubst; eauto.\nCase \"beta_t\".\ninversion H7; subst. assert (e₂' = PLC_ott.open_term_wrt_term e'0 (PLC_ott.term_abs (PLC_ott.term_var_b 0))).\neapply erase_uniqueness; eauto.\npick fresh x. rewrite (tsubst_term_intro x); auto.\nrewrite (PLC_inf.subst_term_intro x); auto.\nassert (x ∉ PLC_ott.fv_term (PLC_ott.open_term_wrt_term e'0 (PLC_ott.term_var_f x))).\nassert (fv_term (open_term_wrt_typ e (typ_var_f x)) [=] PLC_ott.fv_term (PLC_ott.open_term_wrt_term e'0 (PLC_ott.term_var_f x))) by eauto using erase_fv.\nassert (fv_term (open_term_wrt_typ e (typ_var_f x)) [<=] fv_term e) by auto with lngen.\nfsetdec.\nautorewrite with lngen. auto.\nsubst; eauto.\nQed.\n\nLemma erase_red1 : forall e₁ e₂ e₁' e₂',\n  e₁ ⇝ e₂ → erase e₁ e₁' →\n  erase e₂ e₂' → PLC_ott.red1 e₁' e₂'.\nProof.\nintros e₁ e₂ e₁' e₂' Hred Herase1 Herase2.\ngeneralize dependent e₁'. generalize dependent e₂'.\ninduction Hred; intros.\nCase \"empty\". eauto using erase_red0.\nCase \"appL\". inversion Herase1; subst; inversion Herase2; subst.\nreplace e₂'1 with e₂'0 by eauto using erase_uniqueness; eauto.\nCase \"appR\". inversion Herase1; subst; inversion Herase2; subst.\nreplace e₁' with e₁'0 by eauto using erase_uniqueness; eauto.\nCase \"abs\". inversion Herase1; subst; inversion Herase2; subst.\npick fresh x.\napply PLC_ott.red1_abs with (L := L ∪ L0 ∪ L1 ∪ {{x}}); intros; eauto.\nCase \"inst\". inversion Herase1; subst; inversion Herase2; subst; eauto.\nCase \"gen\". inversion Herase1; subst; inversion Herase2; subst.\npick fresh x.\napply PLC_ott.red1_abs with (L := L ∪ L0 ∪ L1 ∪ {{x}}); intros; eauto.\nQed.\n\nLemma erase_red0_inv : forall Γ τ e₁' e₂' e₁,\n  PLC_ott.red0 e₁' e₂' →\n  erase e₁ e₁' →\n  wfterm Γ e₁ τ →\n  exists e₂, red0 e₁ e₂.\nProof.\nintros Γ τ e₁' e₂' e₁ Hred Herase Hwfterm.\ninversion Hred; subst.\ninversion Herase; subst.\nCase \"app\". inversion H4; subst.\nSCase \"abs\". eauto.\nSCase \"gen\". inversion Hwfterm; subst. inversion H7.\nCase \"inst\". inversion H5; subst.\nSCase \"abs\". inversion Hwfterm; subst. inversion H10.\nSCase \"gen\". eauto.\nQed.\n\nLemma erase_id :\nerase (term_abs (typ_forall (typ_var_b 0)) (term_var_b 0))\n     (PLC_ott.term_abs (PLC_ott.term_var_b 0)).\nProof.\npick fresh x. apply erase_abs with (L := {{x}}); intros.\nconstructor; intros; unfold open_typ_wrt_typ; simpl; auto.\nunfold open_term_wrt_term; unfold PLC_ott.open_term_wrt_term; simpl.\nauto.\nQed.\nHint Immediate erase_id.\n\nLemma wftyp_id : forall Γ, wfenv Γ → wftyp Γ (typ_forall (typ_var_b 0)).\nProof.\nintros Γ H. apply wftyp_forall with (L := dom Γ); intros.\nunfold open_typ_wrt_typ; simpl; simpl_env; auto.\nQed.\nHint Immediate wftyp_id.\n\nLemma wfterm_id : forall Γ, wfenv Γ →\nwfterm Γ (term_abs (typ_forall (typ_var_b 0)) (term_var_b 0)) (typ_arrow (typ_forall (typ_var_b 0)) (typ_forall (typ_var_b 0))).\nProof.\nintros Γ H.\napply wfterm_abs with (L := dom Γ); intros.\nunfold open_term_wrt_term; simpl; simpl_env; auto.\nQed.\nHint Resolve wfterm_id.\n\nLemma erase_red1_inv : forall Γ τ e₁' e₂' e₁,\n  PLC_ott.red1 e₁' e₂' →\n  erase e₁ e₁' →\n  wfterm Γ e₁ τ →\n  exists e₂, e₁ ⇝ e₂.\nProof.\nintros Γ τ e₁' e₂' e₁ Hred Herase Hwfterm.\ngeneralize dependent e₁. generalize dependent τ. generalize dependent Γ.\ninduction Hred; intros.\nCase \"empty\". edestruct erase_red0_inv; eauto.\nCase \"appL\". inversion Herase; subst; inversion Hwfterm; subst; edestruct IHHred; eauto.\nCase \"appR\". inversion Herase; subst; inversion Hwfterm; subst.\nSCase \"app\". edestruct IHHred; eauto.\nSCase \"inst\". edestruct IHHred with (e₁ := term_abs (typ_forall (typ_var_b 0)) (term_var_b 0)); eauto.\ninversion H0; subst. inversion H1. pick fresh x. assert (term_var_b 0 ^ x ⇝ e' ^ x) as H1 by auto.\nunfold open_term_wrt_term in H1; simpl in H1; inversion H1; subst. inversion H2.\nCase \"abs\". inversion Herase; subst; inversion Hwfterm; subst.\nSCase \"abs\". pick fresh x. edestruct (H0 x); eauto.\nexists (term_abs τ0 (close_term_wrt_term x x0)).\napply red1_abs with (L := {{x}}); intros; auto.\nrewrite <- subst_term_spec.\nrewrite (subst_term_intro x); auto.\nSCase \"gen\". pick fresh x. edestruct (H0 x); eauto.\nexists (term_gen (close_term_wrt_typ x x0)).\napply red1_gen with (L := {{x}}); intros; auto.\nrewrite <- tsubst_term_spec.\nrewrite (tsubst_term_intro x); auto.\nQed.\n\nLemma simulation : forall Γ τ e₁ e₁',\n  wfterm Γ e₁ τ →\n  erase e₁ e₁' →\n  ((exists e₂, e₁ ⇝ e₂) ↔ (exists e₂', PLC_ott.red1 e₁' e₂')).\nProof.\nintros Γ τ e₁ e₁' Hwfterm Herase; split; intros [e H].\ndestruct (erase_exists e); eauto using erase_red1.\nedestruct erase_red1_inv; eauto.\nQed.\n", "meta": {"author": "esope", "repo": "fzip_coq", "sha": "ec2ba801c18bba2201eff4c9678bed16974e69e2", "save_path": "github-repos/coq/esope-fzip_coq", "path": "github-repos/coq/esope-fzip_coq/fzip_coq-ec2ba801c18bba2201eff4c9678bed16974e69e2/F/F_sim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.2410557374350882}}
{"text": "Require Import Coq.ZArith.ZArith. Open Scope Z_scope.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import Coq.Logic.PropExtensionality.\nRequire Import Coq.micromega.Lia.\n\nDefinition allDistinct{A: Type}(l: list A): Prop :=\n  forall i j e1 e2, nth_error l i = Some e1 -> nth_error l j = Some e2 -> e1 = e2 -> i = j.\n\n(* Structure *)\n\nNotation \"'(check-sat)'\" := False (only parsing).\nNotation \"'(assert' P ')' Q\" := (P -> Q) (only parsing, at level 10).\n\nNotation \"'(declare-fun' f '()' T ')' Q\" := (forall (f: T), Q)\n  (only parsing, at level 10, f at level 0, T at level 200, Q at level 0).\nNotation \"'(declare-fun' f '(' A1 ')' T ')' Q\" := (forall (f: A1 -> T), Q)\n  (only parsing, at level 10, f at level 0, T at level 0, Q at level 0, A1 at level 0).\nNotation \"'(declare-fun' f '(' A1 A2 ')' T ')' Q\" := (forall (f: A1 -> A2 -> T), Q)\n  (only parsing, at level 10, f at level 0, T at level 0, Q at level 0,\n   A1 at level 0, A2 at level 0).\nNotation \"'(declare-fun' f '(' A1 A2 A3 ')' T ')' Q\" := (forall (f: A1 -> A2 -> A3 -> T), Q)\n  (only parsing, at level 10, f at level 0, T at level 0, Q at level 0,\n   A1 at level 0, A2 at level 0, A3 at level 0).\nNotation \"'(declare-fun' f '(' A1 A2 A3 A4 ')' T ')' Q\" :=\n  (forall (f: A1 -> A2 -> A3 -> A4 -> T), Q)\n  (only parsing, at level 10, f at level 0, T at level 0, Q at level 0,\n   A1 at level 0, A2 at level 0, A3 at level 0, A4 at level 0).\n\n(* TODO a recursive notation over nat could also support \"Type -> Type -> Type -> ...\" etc *)\nNotation \"'(declare-sort' T '0' ')' Q\" := (forall (T: Type), Q)\n  (only parsing, at level 10, Q at level 0, T at level 0).\n\nNotation \"'(forall' '(' '(' x1 T1 ')' ')' P ')'\" :=\n  ( forall (x1: T1), P)\n  (only parsing, at level 0, x1 at level 0, T1 at level 0,\n   P at level 0).\n\nNotation \"'(forall' '(' '(' x1 T1 ')' '(' x2 T2 ')' ')' P ')'\" :=\n  ( forall (x1: T1) (x2: T2), P)\n  (only parsing, at level 0, x1 at level 0, T1 at level 0, x2 at level 0, T2 at level 0,\n   P at level 0).\nNotation \"'(forall' '(' '(' x1 T1 ')' '(' x2 T2 ')' '(' x3 T3 ')' ')' P ')'\" :=\n  ( forall (x1: T1) (x2: T2) (x3: T3), P)\n    (only parsing, at level 0,\n     x1 at level 0, T1 at level 0,\n     x2 at level 0, T2 at level 0,\n     x3 at level 0, T3 at level 0,\n   P at level 0).\nNotation \"'(forall' '(' '(' x1 T1 ')' '(' x2 T2 ')' '(' x3 T3 ')' '(' x4 T4 ')' ')' P ')'\" :=\n  ( forall (x1: T1) (x2: T2) (x3: T3) (x4: T4), P)\n    (only parsing, at level 0,\n     x1 at level 0, T1 at level 0,\n     x2 at level 0, T2 at level 0,\n     x3 at level 0, T3 at level 0,\n     x4 at level 0, T4 at level 0,\n   P at level 0).\nNotation \"'(forall' '(' '(' x1 T1 ')' '(' x2 T2 ')' '(' x3 T3 ')' '(' x4 T4 ')' '(' x5 T5 ')' ')' P ')'\" :=\n  ( forall (x1: T1) (x2: T2) (x3: T3) (x4: T4) (x5: T5), P)\n    (only parsing, at level 0,\n     x1 at level 0, T1 at level 0,\n     x2 at level 0, T2 at level 0,\n     x3 at level 0, T3 at level 0,\n     x4 at level 0, T4 at level 0,\n     x5 at level 0, T5 at level 0,\n   P at level 0).\nNotation \"'(forall' '(' '(' x1 T1 ')' '(' x2 T2 ')' '(' x3 T3 ')' '(' x4 T4 ')' '(' x5 T5 ')' '(' x6 T6 ')' ')' P ')'\" :=\n  ( forall (x1: T1) (x2: T2) (x3: T3) (x4: T4) (x5: T5) (x6: T6), P)\n    (only parsing, at level 0,\n     x1 at level 0, T1 at level 0,\n     x2 at level 0, T2 at level 0,\n     x3 at level 0, T3 at level 0,\n     x4 at level 0, T4 at level 0,\n     x5 at level 0, T5 at level 0,\n     x6 at level 0, T6 at level 0,\n   P at level 0).\n\nNotation \"'(let' '(' '(' v1 t1 ')' ')' u ')'\" :=\n  (let v1 := t1 in u)\n    (only parsing, at level 0,\n     v1 at level 0, t1 at level 0,\n     u at level 0).\nNotation \"'(let' '(' '(' v1 t1 ')' '(' v2 t2 ')' ')' u ')'\" :=\n  ( let v1 := t1 in let v2 := t2 in u)\n    (only parsing, at level 0,\n     v1 at level 0, t1 at level 0,\n     v2 at level 0, t2 at level 0,\n     u at level 0).\nNotation \"'(let' '(' '(' v1 t1 ')' '(' v2 t2 ')' '(' v3 t3 ')' ')' u ')'\" :=\n  ( let v1 := t1 in let v2 := t2 in let v3 := t3 in u)\n    (only parsing, at level 0,\n     v1 at level 0, t1 at level 0,\n     v2 at level 0, t2 at level 0,\n     v3 at level 0, t3 at level 0,\n     u at level 0).\nNotation \"'(let' '(' '(' v1 t1 ')' '(' v2 t2 ')' '(' v3 t3 ')' '(' v4 t4 ')' ')' u ')'\" :=\n  ( let v1 := t1 in let v2 := t2 in let v3 := t3 in let v4 := t4 in u)\n    (only parsing, at level 0,\n     v1 at level 0, t1 at level 0,\n     v2 at level 0, t2 at level 0,\n     v3 at level 0, t3 at level 0,\n     v4 at level 0, t4 at level 0,\n     u at level 0).\nNotation \"'(let' '(' '(' v1 t1 ')' '(' v2 t2 ')' '(' v3 t3 ')' '(' v4 t4 ')' '(' v5 t5 ')' ')' u ')'\" :=\n  ( let v1 := t1 in let v2 := t2 in let v3 := t3 in let v4 := t4 in let v5 := t5 in u)\n    (only parsing, at level 0,\n     v1 at level 0, t1 at level 0,\n     v2 at level 0, t2 at level 0,\n     v3 at level 0, t3 at level 0,\n     v4 at level 0, t4 at level 0,\n     v5 at level 0, t5 at level 0,\n     u at level 0).\n\n\n(* ignores the pattern *)\nDefinition with_pattern{P T: Type}(pat: P)(t: T): T := t.\n\nNotation \"P ':pattern' '(' x y .. z ')'\" :=\n  (with_pattern x (with_pattern y .. (with_pattern z P) .. ))\n  (only parsing, at level 10, x at level 0).\nNotation \"P ':pattern' '(' x ')'\" :=\n  (with_pattern x P)\n  (only parsing, at level 10, x at level 0).\nNotation \"'(!' P ')'\" := P (only parsing, at level 0, P at level 10).\n\n(* Operations *)\nNotation \"'(<=' a b ')'\" := (a <= b) (only parsing, a at level 0, b at level 0).\nNotation \"'(<' a b ')'\" := (a < b) (only parsing, a at level 0, b at level 0).\nNotation \"'(>=' a b ')'\" := (a >= b) (only parsing, a at level 0, b at level 0).\nNotation \"'(>' a b ')'\" := (a > b) (only parsing, a at level 0, b at level 0).\nNotation \"'(=' a b ')'\" := (a = b) (only parsing, a at level 0, b at level 0).\nNotation \"'(+' a b ')'\" := (a + b) (only parsing, a at level 0, b at level 0).\nNotation \"'(-' a b ')'\" := (a - b) (only parsing, a at level 0, b at level 0).\n(* Note: if we omit the space, it becomes a Coq comment! *)\nNotation \"'(' '*' a b ')'\" := (a * b) (only parsing, a at level 0, b at level 0).\n\n(* Logic operators *)\nNotation \"'(=>' a b ')'\" := (a -> b) (only parsing, a at level 0, b at level 0).\nNotation \"'(and' a b ')'\" := (a /\\ b) (only parsing, a at level 0, b at level 0).\nNotation \"'(and' a b c ')'\" := (a /\\ b /\\ c) (only parsing, a at level 0, b at level 0, c at level 0).\nNotation \"'(and' a b c d ')'\" := (a /\\ b /\\ c /\\ d) (only parsing, a at level 0, b at level 0, c at level 0, d at level 0).\nNotation \"'(and' a b c d e ')'\" := (a /\\ b /\\ c /\\ d /\\ e) (only parsing, a at level 0, b at level 0, c at level 0, d at level 0, e at level 0).\nNotation \"'(and' a b c d e f ')'\" := (a /\\ b /\\ c /\\ d /\\ e /\\ f) (only parsing, a at level 0, b at level 0, c at level 0, d at level 0, e at level 0, f at level 0).\nNotation \"'(or' a b ')'\" := (a \\/ b) (only parsing, a at level 0, b at level 0).\nNotation \"'(or' a b c ')'\" := (a \\/ b \\/ c) (only parsing, a at level 0, b at level 0, c at level 0).\nNotation \"'(or' a b c d ')'\" := (a \\/ b \\/ c \\/ d) (only parsing, a at level 0, b at level 0, c at level 0, d at level 0).\nNotation \"'(or' a b c d e ')'\" := (a \\/ b \\/ c \\/ d \\/ e) (only parsing, a at level 0, b at level 0, c at level 0, d at level 0, e at level 0).\nNotation \"'(or' a b c d e f ')'\" := (a \\/ b \\/ c \\/ d \\/ e \\/ f) (only parsing, a at level 0, b at level 0, c at level 0, d at level 0, e at level 0, f at level 0).\nNotation \"'(not' a ')'\" := (~ a) (only parsing, a at level 0).\n\n(* Misc logic hack\nNotation \"'(=' a 'true)'\" := (a: Prop) (only parsing, a at level 0).\nNotation \"'(=>' 'true' 'true)'\" := True (only parsing, at level 0).\n*)\n\n(* Datatypes *)\nNotation Int := Z (only parsing).\nNotation Bool := Prop (only parsing).\nNotation true := True (only parsing).\nNotation false := False (only parsing).\n(* TODO sometimes \"bool\" might be more appropriate *)\n\n(* Misc *)\nNotation \"'(distinct' x y .. z ')'\" := (allDistinct (cons x (cons y .. (cons z nil) ..)))\n  (only parsing, at level 10, x at level 0, y at level 0, z at level 0).\n(*\ncoq/theories/Lists/List.v:\nNotation \"[ x ; y ; .. ; z ]\" :=  (cons x (cons y .. (cons z nil) ..)) : list_scope.\n*)\n\nGoal\n  (* from https://www.starexec.org/starexec/secure/details/benchmark.jsp?id=7239749 *)\n  (declare-sort S1 0)\n  (declare-fun f1 () S1)\n  (declare-fun f2 () S1)\n  (declare-fun f3 () Int)\n  (assert (not (= f1 f2)))\n  (assert (not (<= (+ ( * 4 f3) 1) 1)))\n  (assert (<= f3 0))\n  (assert (<= f3 0))\n  (check-sat)\n.\nProof.\n  intros.\n  lia.\nQed.\n\nLemma True_implies: forall (P: Prop), (True -> P) <-> P.\nProof. tauto. Qed.\n\nLemma implies_True: forall (P: Prop), (P -> True) <-> True.\nProof. tauto. Qed.\n\nLemma and_True: forall (P: Prop), (P /\\ True) <-> P.\nProof. tauto. Qed.\n\nLemma equals_True: forall (P: Prop), (P = True) <-> P.\nProof.\n  intros. split; intros.\n  - subst. constructor.\n  - apply propositional_extensionality. tauto.\nQed.\n\nGoal\n(*\nUFLIA example from boogie from SMT competition\nhttps://www.starexec.org/starexec/services/benchmarks/7158337/contents?limit=-1\npreprocessed with preprocess.sh\n*)\n(declare-fun boolIff (Int Int) Int)\n(declare-fun PeerGroupPlaceholder_ () Int)\n(declare-fun intGreater (Int Int) Int)\n(declare-fun IfThenElse_ (Int Int Int) Int)\n(declare-fun CONCVARSYM (Int) Int)\n(declare-fun SharingMode_Unshared_ () Int)\n(declare-fun System_dot_Reflection_dot_IReflect () Int)\n(declare-fun int_m2147483648 () Int)\n(declare-fun System_dot_Int32 () Int)\n(declare-fun intAtMost (Int Int) Int)\n(declare-fun multiply (Int Int) Int)\n(declare-fun Is_ (Int Int) Int)\n(declare-fun Smt_dot_true () Int)\n(declare-fun Bag () Int)\n(declare-fun ElementType_ (Int) Int)\n(declare-fun divide (Int Int) Int)\n(declare-fun int_m9223372036854775808 () Int)\n(declare-fun divides (Int Int) Int)\n(declare-fun select1 (Int Int) Int)\n(declare-fun store1 (Int Int Int) Int)\n(declare-fun select2 (Int Int Int) Int)\n(declare-fun nullObject () Int)\n(declare-fun store2 (Int Int Int Int) Int)\n(declare-fun modulo (Int Int) Int)\n(declare-fun ownerRef_ () Int)\n(declare-fun StructSet_ (Int Int Int) Int)\n(declare-fun AsDirectSubClass (Int Int) Int)\n(declare-fun System_dot_Collections_dot_ICollection () Int)\n(declare-fun System_dot_Boolean () Int)\n(declare-fun shl_ (Int Int) Int)\n(declare-fun DimLength_ (Int Int) Int)\n(declare-fun anyEqual (Int Int) Int)\n(declare-fun System_dot_Array () Int)\n(declare-fun System_dot_Reflection_dot_ICustomAttributeProvider () Int)\n(declare-fun SharingMode_LockProtected_ () Int)\n(declare-fun IsMemberlessType_ (Int) Int)\n(declare-fun System_dot_UInt16 () Int)\n(declare-fun ClassRepr (Int) Int)\n(declare-fun System_dot_Runtime_dot_InteropServices_dot__Type () Int)\n(declare-fun boolNot (Int) Int)\n(declare-fun Microsoft_dot_Contracts_dot_ICheckedException () Int)\n(declare-fun System_dot_Exception () Int)\n(declare-fun System_dot_Runtime_dot_InteropServices_dot__MemberInfo () Int)\n(declare-fun block6086_correct () Int)\n(declare-fun boolAnd (Int Int) Int)\n(declare-fun boolImplies (Int Int) Int)\n(declare-fun Unbox (Int) Int)\n(declare-fun intAtLeast (Int Int) Int)\n(declare-fun ownerFrame_ () Int)\n(declare-fun int_4294967295 () Int)\n(declare-fun IsAllocated (Int Int) Int)\n(declare-fun TypeName (Int) Int)\n(declare-fun AsPeerField (Int) Int)\n(declare-fun int_9223372036854775807 () Int)\n(declare-fun AsRepField (Int Int) Int)\n(declare-fun System_dot_Reflection_dot_MemberInfo () Int)\n(declare-fun ArrayCategoryValue_ () Int)\n(declare-fun is (Int Int) Int)\n(declare-fun Microsoft_dot_Contracts_dot_GuardException () Int)\n(declare-fun InRange (Int Int) Bool)\n(declare-fun AsOwner (Int Int) Int)\n(declare-fun System_dot_Int64 () Int)\n(declare-fun System_dot_Runtime_dot_InteropServices_dot__Exception () Int)\n(declare-fun _or_ (Int Int) Int)\n(declare-fun As_ (Int Int) Int)\n(declare-fun exposeVersion_ () Int)\n(declare-fun System_dot_Type () Int)\n(declare-fun intLess (Int Int) Int)\n(declare-fun AsImmutable_ (Int) Int)\n(declare-fun NonNullFieldsAreInitialized_ () Int)\n(declare-fun LBound_ (Int Int) Int)\n(declare-fun System_dot_Object () Int)\n(declare-fun Bag_dot_a () Int)\n(declare-fun System_dot_UInt32 () Int)\n(declare-fun localinv_ () Int)\n(declare-fun inv_ () Int)\n(declare-fun Bag_dot_n () Int)\n(declare-fun entry_correct () Int)\n(declare-fun FirstConsistentOwner_ () Int)\n(declare-fun UnboxedType (Int) Int)\n(declare-fun AsRefField (Int Int) Int)\n(declare-fun System_dot_Byte () Int)\n(declare-fun int_2147483647 () Int)\n(declare-fun ArrayCategoryRef_ () Int)\n(declare-fun Heap_ () Int)\n(declare-fun Length_ (Int) Int)\n(declare-fun System_dot_Runtime_dot_Serialization_dot_ISerializable () Int)\n(declare-fun AsNonNullRefField (Int Int) Int)\n(declare-fun IsHeap (Int) Int)\n(declare-fun UBound_ (Int Int) Int)\n(declare-fun System_dot_String () Int)\n(declare-fun System_dot_Collections_dot_IList () Int)\n(declare-fun System_dot_String_dot_IsInterned_System_dot_String_notnull_ (Int) Int)\n(declare-fun Rank_ (Int) Int)\n(declare-fun UnknownRef_ () Int)\n(declare-fun RefArraySet (Int Int Int) Int)\n(declare-fun ValueArraySet (Int Int Int) Int)\n(declare-fun boolOr (Int Int) Int)\n(declare-fun sharingMode_ () Int)\n(declare-fun subtypes (Int Int) Bool)\n(declare-fun System_dot_String_dot_Equals_System_dot_String_System_dot_String_ (Int Int) Int)\n(declare-fun anyNeq (Int Int) Int)\n(declare-fun IsStaticField (Int) Int)\n(declare-fun IsNotNull_ (Int Int) Int)\n(declare-fun typeof_ (Int) Int)\n(declare-fun ArrayCategoryNonNullRef_ () Int)\n(declare-fun RefArrayGet (Int Int) Int)\n(declare-fun ValueArrayGet (Int Int) Int)\n(declare-fun TypeObject (Int) Int)\n(declare-fun _and_ (Int Int) Int)\n(declare-fun BoxTester (Int Int) Int)\n(declare-fun Microsoft_dot_Contracts_dot_ObjectInvariantException () Int)\n(declare-fun IsValueType_ (Int) Int)\n(declare-fun AsRangeField (Int Int) Int)\n(declare-fun System_dot_SByte () Int)\n(declare-fun BeingConstructed_ () Int)\n(declare-fun FieldDependsOnFCO_ (Int Int Int) Int)\n(declare-fun NonNullRefArray (Int Int) Int)\n(declare-fun RefArray (Int Int) Int)\n(declare-fun ArrayCategory_ (Int) Int)\n(declare-fun AsPureObject_ (Int) Int)\n(declare-fun System_dot_String_dot_Equals_System_dot_String_ (Int Int) Int)\n(declare-fun System_dot_Int16 () Int)\n(declare-fun AsMutable_ (Int) Int)\n(declare-fun System_dot_Char () Int)\n(declare-fun block6069_correct () Int)\n(declare-fun System_dot_UInt64 () Int)\n(declare-fun StructGet_ (Int Int) Int)\n(declare-fun OneClassDown (Int Int) Int)\n(declare-fun ArrayIndex (Int Int Int Int) Int)\n(declare-fun Box (Int Int) Int)\n(declare-fun int_18446744073709551615 () Int)\n(declare-fun shr_ (Int Int) Int)\n(declare-fun System_dot_ICloneable () Int)\n(declare-fun IsDirectlyModifiableField (Int) Int)\n(declare-fun StringLength_ (Int) Int)\n(declare-fun allocated_ () Int)\n(declare-fun BaseClass_ (Int) Int)\n(declare-fun ValueArray (Int Int) Int)\n(declare-fun Smt_dot_false () Int)\n(declare-fun IsImmutable_ (Int) Int)\n(declare-fun elements_ () Int)\n(declare-fun DeclType (Int) Int)\n(declare-fun System_dot_Collections_dot_IEnumerable () Int)\n(declare-fun ReallyLastGeneratedExit_correct () Int)\n(assert (distinct allocated_ elements_ inv_ localinv_ exposeVersion_ sharingMode_ SharingMode_Unshared_ SharingMode_LockProtected_ ownerRef_ ownerFrame_ PeerGroupPlaceholder_ ArrayCategoryValue_ ArrayCategoryRef_ ArrayCategoryNonNullRef_ System_dot_Array System_dot_Object System_dot_Type BeingConstructed_ NonNullFieldsAreInitialized_ System_dot_String FirstConsistentOwner_ System_dot_SByte System_dot_Byte System_dot_Int16 System_dot_UInt16 System_dot_Int32 System_dot_UInt32 System_dot_Int64 System_dot_UInt64 System_dot_Char int_m2147483648 int_2147483647 int_4294967295 int_m9223372036854775808 int_9223372036854775807 int_18446744073709551615 UnknownRef_ Bag_dot_a Bag_dot_n Microsoft_dot_Contracts_dot_ObjectInvariantException System_dot_Collections_dot_IEnumerable System_dot_Boolean System_dot_ICloneable System_dot_Reflection_dot_ICustomAttributeProvider System_dot_Runtime_dot_Serialization_dot_ISerializable System_dot_Exception System_dot_Reflection_dot_IReflect System_dot_Runtime_dot_InteropServices_dot__Exception System_dot_Collections_dot_ICollection Microsoft_dot_Contracts_dot_ICheckedException Bag Microsoft_dot_Contracts_dot_GuardException System_dot_Runtime_dot_InteropServices_dot__MemberInfo System_dot_Collections_dot_IList System_dot_Runtime_dot_InteropServices_dot__Type System_dot_Reflection_dot_MemberInfo))\n(assert (= (DeclType exposeVersion_) System_dot_Object))\n(assert (forall ((c0 Int) (c1 Int)) (! (=> (not (= c0 c1)) (not (= (ClassRepr c0) (ClassRepr c1)))) :pattern ((ClassRepr c0) (ClassRepr c1)) )))\n(assert (forall ((T Int)) (not (subtypes (typeof_ (ClassRepr T)) System_dot_Object))))\n(assert (forall ((T Int)) (not (= (ClassRepr T) nullObject))))\n(assert (forall ((T Int) (h Int)) (! (=> (= (IsHeap h) Smt_dot_true) (= (select2 h (ClassRepr T) ownerFrame_) PeerGroupPlaceholder_)) :pattern ((select2 h (ClassRepr T) ownerFrame_)) )))\n(assert (not (= (IsDirectlyModifiableField allocated_) Smt_dot_true)))\n(assert (= (IsDirectlyModifiableField elements_) Smt_dot_true))\n(assert (not (= (IsDirectlyModifiableField inv_) Smt_dot_true)))\n(assert (not (= (IsDirectlyModifiableField localinv_) Smt_dot_true)))\n(assert (not (= (IsDirectlyModifiableField ownerRef_) Smt_dot_true)))\n(assert (not (= (IsDirectlyModifiableField ownerFrame_) Smt_dot_true)))\n(assert (not (= (IsDirectlyModifiableField exposeVersion_) Smt_dot_true)))\n(assert (not (= (IsStaticField allocated_) Smt_dot_true)))\n(assert (not (= (IsStaticField elements_) Smt_dot_true)))\n(assert (not (= (IsStaticField inv_) Smt_dot_true)))\n(assert (not (= (IsStaticField localinv_) Smt_dot_true)))\n(assert (not (= (IsStaticField exposeVersion_) Smt_dot_true)))\n(assert (forall ((A Int) (i Int) (x Int)) (= (ValueArrayGet (ValueArraySet A i x) i) x)))\n(assert (forall ((A Int) (i Int) (j Int) (x Int)) (=> (not (= i j)) (= (ValueArrayGet (ValueArraySet A i x) j) (ValueArrayGet A j)))))\n(assert (forall ((A Int) (i Int) (x Int)) (= (RefArrayGet (RefArraySet A i x) i) x)))\n(assert (forall ((A Int) (i Int) (j Int) (x Int)) (=> (not (= i j)) (= (RefArrayGet (RefArraySet A i x) j) (RefArrayGet A j)))))\n(assert (forall ((a Int) (d Int) (x Int) (y Int) (_x'_ Int) (_y'_ Int)) (! (=> (= (ArrayIndex a d x y) (ArrayIndex a d _x'_ _y'_)) (and (= x _x'_) (= y _y'_))) :pattern ((ArrayIndex a d x y) (ArrayIndex a d _x'_ _y'_)) )))\n(assert (forall ((a Int) (T Int) (i Int) (r Int) (heap Int)) (! (=> (and (= (IsHeap heap) Smt_dot_true) (subtypes (typeof_ a) (RefArray T r))) (= (Is_ (RefArrayGet (select2 heap a elements_) i) T) Smt_dot_true)) :pattern ((subtypes (typeof_ a) (RefArray T r)) (RefArrayGet (select2 heap a elements_) i)) )))\n(assert (forall ((a Int) (T Int) (i Int) (r Int) (heap Int)) (! (=> (and (= (IsHeap heap) Smt_dot_true) (subtypes (typeof_ a) (NonNullRefArray T r))) (= (IsNotNull_ (RefArrayGet (select2 heap a elements_) i) T) Smt_dot_true)) :pattern ((subtypes (typeof_ a) (NonNullRefArray T r)) (RefArrayGet (select2 heap a elements_) i)) )))\n(assert (forall ((a Int)) (<= 1 (Rank_ a))))\n(assert (forall ((a Int) (T Int) (r Int)) (! (=> (and (not (= a nullObject)) (subtypes (typeof_ a) (RefArray T r))) (= (Rank_ a) r)) :pattern ((subtypes (typeof_ a) (RefArray T r))) )))\n(assert (forall ((a Int) (T Int) (r Int)) (! (=> (and (not (= a nullObject)) (subtypes (typeof_ a) (NonNullRefArray T r))) (= (Rank_ a) r)) :pattern ((subtypes (typeof_ a) (NonNullRefArray T r))) )))\n(assert (forall ((a Int) (T Int) (r Int)) (! (=> (and (not (= a nullObject)) (subtypes (typeof_ a) (ValueArray T r))) (= (Rank_ a) r)) :pattern ((subtypes (typeof_ a) (ValueArray T r))) )))\n(assert (forall ((a Int)) (! (<= 0 (Length_ a)) :pattern ((Length_ a)) )))\n(assert (forall ((a Int) (i Int)) (<= 0 (DimLength_ a i))))\n(assert (forall ((a Int)) (! (=> (= (Rank_ a) 1) (= (DimLength_ a 0) (Length_ a))) :pattern ((DimLength_ a 0)) )))\n(assert (forall ((a Int) (i Int)) (! (= (LBound_ a i) 0) :pattern ((LBound_ a i)) )))\n(assert (forall ((a Int) (i Int)) (! (= (UBound_ a i) (- (DimLength_ a i) 1)) :pattern ((UBound_ a i)) )))\n(assert (forall ((T Int) (ET Int) (r Int)) (! (=> (subtypes T (ValueArray ET r)) (= (ArrayCategory_ T) ArrayCategoryValue_)) :pattern ((subtypes T (ValueArray ET r))) )))\n(assert (forall ((T Int) (ET Int) (r Int)) (! (=> (subtypes T (RefArray ET r)) (= (ArrayCategory_ T) ArrayCategoryRef_)) :pattern ((subtypes T (RefArray ET r))) )))\n(assert (forall ((T Int) (ET Int) (r Int)) (! (=> (subtypes T (NonNullRefArray ET r)) (= (ArrayCategory_ T) ArrayCategoryNonNullRef_)) :pattern ((subtypes T (NonNullRefArray ET r))) )))\n(assert (subtypes System_dot_Array System_dot_Object))\n(assert (forall ((T Int) (r Int)) (! (subtypes (ValueArray T r) System_dot_Array) :pattern ((ValueArray T r)) )))\n(assert (forall ((T Int) (r Int)) (! (subtypes (RefArray T r) System_dot_Array) :pattern ((RefArray T r)) )))\n(assert (forall ((T Int) (r Int)) (! (subtypes (NonNullRefArray T r) System_dot_Array) :pattern ((NonNullRefArray T r)) )))\n(assert (forall ((T Int) (U Int) (r Int)) (=> (subtypes U T) (subtypes (RefArray U r) (RefArray T r)))))\n(assert (forall ((T Int) (U Int) (r Int)) (=> (subtypes U T) (subtypes (NonNullRefArray U r) (NonNullRefArray T r)))))\n(assert (forall ((A Int) (r Int)) (= (ElementType_ (ValueArray A r)) A)))\n(assert (forall ((A Int) (r Int)) (= (ElementType_ (RefArray A r)) A)))\n(assert (forall ((A Int) (r Int)) (= (ElementType_ (NonNullRefArray A r)) A)))\n(assert (forall ((A Int) (r Int) (T Int)) (! (let ((v_0 (ElementType_ T))) (=> (subtypes T (RefArray A r)) (and (= T (RefArray v_0 r)) (subtypes v_0 A)))) :pattern ((subtypes T (RefArray A r))) )))\n(assert (forall ((A Int) (r Int) (T Int)) (! (let ((v_0 (ElementType_ T))) (=> (subtypes T (NonNullRefArray A r)) (and (= T (NonNullRefArray v_0 r)) (subtypes v_0 A)))) :pattern ((subtypes T (NonNullRefArray A r))) )))\n(assert (forall ((A Int) (r Int) (T Int)) (let ((v_0 (ValueArray A r))) (=> (subtypes T v_0) (= T v_0)))))\n(assert (forall ((A Int) (r Int) (T Int)) (let ((v_0 (ElementType_ T))) (=> (subtypes (RefArray A r) T) (or (subtypes System_dot_Array T) (and (= T (RefArray v_0 r)) (subtypes A v_0)))))))\n(assert (forall ((A Int) (r Int) (T Int)) (let ((v_0 (ElementType_ T))) (=> (subtypes (NonNullRefArray A r) T) (or (subtypes System_dot_Array T) (and (= T (NonNullRefArray v_0 r)) (subtypes A v_0)))))))\n(assert (forall ((A Int) (r Int) (T Int)) (let ((v_0 (ValueArray A r))) (=> (subtypes v_0 T) (or (subtypes System_dot_Array T) (= T v_0))))))\n(assert (forall ((s Int) (f Int) (x Int)) (= (StructGet_ (StructSet_ s f x) f) x)))\n(assert (forall ((s Int) (f Int) (_f'_ Int) (x Int)) (=> (not (= f _f'_)) (= (StructGet_ (StructSet_ s f x) _f'_) (StructGet_ s _f'_)))))\n(assert (forall ((A Int) (B Int) (C Int)) (! (=> (subtypes C (AsDirectSubClass B A)) (= (OneClassDown C A) B)) :pattern ((subtypes C (AsDirectSubClass B A))) )))\n(assert (forall ((T Int)) (=> (= (IsValueType_ T) Smt_dot_true) (and (forall ((U Int)) (=> (subtypes T U) (= T U))) (forall ((U Int)) (=> (subtypes U T) (= T U)))))))\n(assert (subtypes System_dot_Type System_dot_Object))\n(assert (forall ((T Int)) (! (= (IsNotNull_ (TypeObject T) System_dot_Type) Smt_dot_true) :pattern ((TypeObject T)) )))\n(assert (forall ((T Int)) (! (= (TypeName (TypeObject T)) T) :pattern ((TypeObject T)) )))\n(assert (forall ((o Int) (T Int)) (! (= (= (Is_ o T) Smt_dot_true) (or (= o nullObject) (subtypes (typeof_ o) T))) :pattern ((Is_ o T)) )))\n(assert (forall ((o Int) (T Int)) (! (= (= (IsNotNull_ o T) Smt_dot_true) (and (not (= o nullObject)) (= (Is_ o T) Smt_dot_true))) :pattern ((IsNotNull_ o T)) )))\n(assert (forall ((o Int) (T Int)) (=> (= (Is_ o T) Smt_dot_true) (= (As_ o T) o))))\n(assert (forall ((o Int) (T Int)) (=> (not (= (Is_ o T) Smt_dot_true)) (= (As_ o T) nullObject))))\n(assert (forall ((h Int) (o Int)) (! (let ((v_0 (typeof_ o))) (=> (and (= (IsHeap h) Smt_dot_true) (not (= o nullObject)) (subtypes v_0 System_dot_Array)) (and (= (select2 h o inv_) v_0) (= (select2 h o localinv_) v_0)))) :pattern ((select2 h o inv_)) )))\n(assert (forall ((h Int) (o Int) (f Int)) (! (=> (and (= (IsHeap h) Smt_dot_true) (= (select2 h o allocated_) Smt_dot_true)) (= (IsAllocated h (select2 h o f)) Smt_dot_true)) :pattern ((IsAllocated h (select2 h o f))) )))\n(assert (forall ((h Int) (o Int) (f Int)) (! (=> (and (= (IsHeap h) Smt_dot_true) (= (select2 h o allocated_) Smt_dot_true)) (= (select2 h (select2 h o f) allocated_) Smt_dot_true)) :pattern ((select2 h (select2 h o f) allocated_)) )))\n(assert (forall ((h Int) (s Int) (f Int)) (! (=> (= (IsAllocated h s) Smt_dot_true) (= (IsAllocated h (StructGet_ s f)) Smt_dot_true)) :pattern ((IsAllocated h (StructGet_ s f))) )))\n(assert (forall ((h Int) (e Int) (i Int)) (! (=> (= (IsAllocated h e) Smt_dot_true) (= (IsAllocated h (RefArrayGet e i)) Smt_dot_true)) :pattern ((IsAllocated h (RefArrayGet e i))) )))\n(assert (forall ((h Int) (e Int) (i Int)) (! (=> (= (IsAllocated h e) Smt_dot_true) (= (IsAllocated h (ValueArrayGet e i)) Smt_dot_true)) :pattern ((IsAllocated h (ValueArrayGet e i))) )))\n(assert (forall ((h Int) (o Int)) (! (=> (= (IsAllocated h o) Smt_dot_true) (= (select2 h o allocated_) Smt_dot_true)) :pattern ((select2 h o allocated_)) )))\n(assert (forall ((h Int) (c Int)) (! (=> (= (IsHeap h) Smt_dot_true) (= (select2 h (ClassRepr c) allocated_) Smt_dot_true)) :pattern ((select2 h (ClassRepr c) allocated_)) )))\n(assert (forall ((f Int) (T Int)) (! (=> (= (AsNonNullRefField f T) f) (= (AsRefField f T) f)) :pattern ((AsNonNullRefField f T)) )))\n(assert (forall ((h Int) (o Int) (f Int) (T Int)) (! (=> (= (IsHeap h) Smt_dot_true) (= (Is_ (select2 h o (AsRefField f T)) T) Smt_dot_true)) :pattern ((select2 h o (AsRefField f T))) )))\n(assert (forall ((h Int) (o Int) (f Int) (T Int)) (! (=> (and (= (IsHeap h) Smt_dot_true) (not (= o nullObject)) (or (not (= o BeingConstructed_)) (= (= (select2 h BeingConstructed_ NonNullFieldsAreInitialized_) Smt_dot_true) true))) (not (= (select2 h o (AsNonNullRefField f T)) nullObject))) :pattern ((select2 h o (AsNonNullRefField f T))) )))\n(assert (forall ((h Int) (o Int) (f Int) (T Int)) (! (=> (= (IsHeap h) Smt_dot_true) (InRange (select2 h o (AsRangeField f T)) T)) :pattern ((select2 h o (AsRangeField f T))) )))\n(assert (forall ((o Int)) (! (not (= (IsMemberlessType_ (typeof_ o)) Smt_dot_true)) :pattern ((IsMemberlessType_ (typeof_ o))) )))\n(assert (not (= (IsImmutable_ System_dot_Object) Smt_dot_true)))\n(assert (forall ((T Int) (U Int)) (! (=> (subtypes U (AsImmutable_ T)) (and (= (IsImmutable_ U) Smt_dot_true) (= (AsImmutable_ U) U))) :pattern ((subtypes U (AsImmutable_ T))) )))\n(assert (forall ((T Int) (U Int)) (! (=> (subtypes U (AsMutable_ T)) (and (not (= (IsImmutable_ U) Smt_dot_true)) (= (AsMutable_ U) U))) :pattern ((subtypes U (AsMutable_ T))) )))\n(assert (forall ((o Int) (T Int)) (! (=> (and (not (= o nullObject)) (not (= o BeingConstructed_)) (subtypes (typeof_ o) (AsImmutable_ T))) (forall ((h Int)) (! (let ((v_0 (typeof_ o))) (=> (= (IsHeap h) Smt_dot_true) (and (= (select2 h o inv_) v_0) (= (select2 h o localinv_) v_0) (= (select2 h o ownerFrame_) PeerGroupPlaceholder_) (= (AsOwner o (select2 h o ownerRef_)) o) (forall ((t Int)) (! (=> (= (AsOwner o (select2 h t ownerRef_)) o) (or (= t o) (not (= (select2 h t ownerFrame_) PeerGroupPlaceholder_)))) :pattern ((AsOwner o (select2 h t ownerRef_))) ))))) :pattern ((IsHeap h)) ))) :pattern ((subtypes (typeof_ o) (AsImmutable_ T))) )))\n(assert (forall ((s Int)) (! (<= 0 (StringLength_ s)) :pattern ((StringLength_ s)) )))\n(assert (forall ((h Int) (o Int) (f Int) (T Int)) (! (let ((v_0 (select2 h o (AsRepField f T)))) (=> (and (= (IsHeap h) Smt_dot_true) (not (= v_0 nullObject))) (and (= (select2 h v_0 ownerRef_) o) (= (select2 h v_0 ownerFrame_) T)))) :pattern ((select2 h o (AsRepField f T))) )))\n(assert (forall ((h Int) (o Int) (f Int)) (! (let ((v_0 (select2 h o (AsPeerField f)))) (=> (and (= (IsHeap h) Smt_dot_true) (not (= v_0 nullObject))) (and (= (select2 h v_0 ownerRef_) (select2 h o ownerRef_)) (= (select2 h v_0 ownerFrame_) (select2 h o ownerFrame_))))) :pattern ((select2 h o (AsPeerField f))) )))\n(assert (forall ((h Int) (o Int)) (let ((v_0 (select2 h o ownerFrame_)) (v_1 (select2 h o ownerRef_)) (v_2 (typeof_ o))) (=> (and (= (IsHeap h) Smt_dot_true) (not (= v_0 PeerGroupPlaceholder_)) (subtypes (select2 h v_1 inv_) v_0) (not (= (select2 h v_1 localinv_) (BaseClass_ v_0)))) (and (= (select2 h o inv_) v_2) (= (select2 h o localinv_) v_2))))))\n(assert (forall ((o Int) (f Int) (h Int)) (! (let ((v_0 (select2 h o ownerFrame_)) (v_1 (select2 h o ownerRef_))) (=> (and (= (IsHeap h) Smt_dot_true) (not (= o nullObject)) (= (= (select2 h o allocated_) Smt_dot_true) true) (not (= v_0 PeerGroupPlaceholder_)) (subtypes (select2 h v_1 inv_) v_0) (not (= (select2 h v_1 localinv_) (BaseClass_ v_0)))) (= (select2 h o f) (FieldDependsOnFCO_ o f (select2 h (select2 h o FirstConsistentOwner_) exposeVersion_))))) :pattern ((select2 h (AsPureObject_ o) f)) )))\n(assert (forall ((o Int) (h Int)) (! (let ((v_0 (select2 h o ownerFrame_)) (v_1 (select2 h o ownerRef_)) (v_2 (select2 h o FirstConsistentOwner_))) (let ((v_3 (select2 h v_2 ownerFrame_)) (v_4 (select2 h v_2 ownerRef_))) (=> (and (= (IsHeap h) Smt_dot_true) (not (= o nullObject)) (= (= (select2 h o allocated_) Smt_dot_true) true) (not (= v_0 PeerGroupPlaceholder_)) (subtypes (select2 h v_1 inv_) v_0) (not (= (select2 h v_1 localinv_) (BaseClass_ v_0)))) (and (not (= v_2 nullObject)) (= (= (select2 h v_2 allocated_) Smt_dot_true) true) (or (= v_3 PeerGroupPlaceholder_) (not (subtypes (select2 h v_4 inv_) v_3)) (= (select2 h v_4 localinv_) (BaseClass_ v_3))))))) :pattern ((select2 h o FirstConsistentOwner_)) )))\n(assert (forall ((x Int) (p Int)) (! (= (Unbox (Box x p)) x) :pattern ((Unbox (Box x p))) )))\n(assert (forall ((p Int)) (! (=> (= (IsValueType_ (UnboxedType p)) Smt_dot_true) (forall ((heap Int) (x Int)) (let ((v_0 (Box x p))) (let ((v_1 (typeof_ v_0))) (=> (= (IsHeap heap) Smt_dot_true) (and (= (select2 heap v_0 inv_) v_1) (= (select2 heap v_0 localinv_) v_1))))))) :pattern ((IsValueType_ (UnboxedType p))) )))\n(assert (forall ((x Int) (p Int)) (let ((v_0 (Box x p))) (=> (and (subtypes (UnboxedType v_0) System_dot_Object) (= v_0 p)) (= x p)))))\n(assert (forall ((p Int) (typ Int)) (! (= (= (UnboxedType p) typ) (not (= (BoxTester p typ) nullObject))) :pattern ((BoxTester p typ)) )))\n(assert (= (IsValueType_ System_dot_SByte) Smt_dot_true))\n(assert (= (IsValueType_ System_dot_Byte) Smt_dot_true))\n(assert (= (IsValueType_ System_dot_Int16) Smt_dot_true))\n(assert (= (IsValueType_ System_dot_UInt16) Smt_dot_true))\n(assert (= (IsValueType_ System_dot_Int32) Smt_dot_true))\n(assert (= (IsValueType_ System_dot_UInt32) Smt_dot_true))\n(assert (= (IsValueType_ System_dot_Int64) Smt_dot_true))\n(assert (= (IsValueType_ System_dot_UInt64) Smt_dot_true))\n(assert (= (IsValueType_ System_dot_Char) Smt_dot_true))\n(assert (< int_m9223372036854775808 int_m2147483648))\n(assert (< int_m2147483648 (- 0 100000)))\n(assert (< 100000 int_2147483647))\n(assert (< int_2147483647 int_4294967295))\n(assert (< int_4294967295 int_9223372036854775807))\n(assert (< int_9223372036854775807 int_18446744073709551615))\n(assert (forall ((i Int)) (= (InRange i System_dot_SByte) (and (<= (- 0 128) i) (< i 128)))))\n(assert (forall ((i Int)) (= (InRange i System_dot_Byte) (and (<= 0 i) (< i 256)))))\n(assert (forall ((i Int)) (= (InRange i System_dot_Int16) (and (<= (- 0 32768) i) (< i 32768)))))\n(assert (forall ((i Int)) (= (InRange i System_dot_UInt16) (and (<= 0 i) (< i 65536)))))\n(assert (forall ((i Int)) (= (InRange i System_dot_Int32) (and (<= int_m2147483648 i) (<= i int_2147483647)))))\n(assert (forall ((i Int)) (= (InRange i System_dot_UInt32) (and (<= 0 i) (<= i int_4294967295)))))\n(assert (forall ((i Int)) (= (InRange i System_dot_Int64) (and (<= int_m9223372036854775808 i) (<= i int_9223372036854775807)))))\n(assert (forall ((i Int)) (= (InRange i System_dot_UInt64) (and (<= 0 i) (<= i int_18446744073709551615)))))\n(assert (forall ((i Int)) (= (InRange i System_dot_Char) (and (<= 0 i) (< i 65536)))))\n(assert (forall ((b Int) (x Int) (y Int)) (! (=> (= b Smt_dot_true) (= (IfThenElse_ b x y) x)) :pattern ((IfThenElse_ b x y)) )))\n(assert (forall ((b Int) (x Int) (y Int)) (! (=> (not (= b Smt_dot_true)) (= (IfThenElse_ b x y) y)) :pattern ((IfThenElse_ b x y)) )))\n(assert (forall ((x Int) (y Int)) (! (= (modulo x y) (- x (multiply (divide x y) y))) :pattern ((modulo x y))  :pattern ((divide x y)) )))\n(assert (forall ((x Int) (y Int)) (! (let ((v_0 (modulo x y))) (=> (and (<= 0 x) (< 0 y)) (and (<= 0 v_0) (< v_0 y)))) :pattern ((modulo x y)) )))\n(assert (forall ((x Int) (y Int)) (! (let ((v_0 (modulo x y))) (=> (and (<= 0 x) (< y 0)) (and (<= 0 v_0) (< v_0 (- 0 y))))) :pattern ((modulo x y)) )))\n(assert (forall ((x Int) (y Int)) (! (let ((v_0 (modulo x y))) (=> (and (<= x 0) (< 0 y)) (and (< (- 0 y) v_0) (<= v_0 0)))) :pattern ((modulo x y)) )))\n(assert (forall ((x Int) (y Int)) (! (let ((v_0 (modulo x y))) (=> (and (<= x 0) (< y 0)) (and (< y v_0) (<= v_0 0)))) :pattern ((modulo x y)) )))\n(assert (forall ((x Int) (y Int)) (=> (and (<= 0 x) (<= 0 y)) (= (modulo (+ x y) y) (modulo x y)))))\n(assert (forall ((x Int) (y Int)) (=> (and (<= 0 x) (<= 0 y)) (= (modulo (+ y x) y) (modulo x y)))))\n(assert (forall ((x Int) (y Int)) (let ((v_0 (- x y))) (=> (and (<= 0 v_0) (<= 0 y)) (= (modulo v_0 y) (modulo x y))))))\n(assert (forall ((a Int) (b Int) (d Int)) (! (=> (and (<= 2 d) (= (modulo a d) (modulo b d)) (< a b)) (<= (+ a d) b)) :pattern ((modulo a d) (modulo b d)) )))\n(assert (forall ((x Int) (y Int)) (! (=> (or (<= 0 x) (<= 0 y)) (<= 0 (_and_ x y))) :pattern ((_and_ x y)) )))\n(assert (forall ((x Int) (y Int)) (! (let ((v_0 (_or_ x y))) (=> (and (<= 0 x) (<= 0 y)) (and (<= 0 v_0) (<= v_0 (+ x y))))) :pattern ((_or_ x y)) )))\n(assert (forall ((i Int)) (! (= (shl_ i 0) i) :pattern ((shl_ i 0)) )))\n(assert (forall ((i Int) (j Int)) (=> (<= 0 j) (= (shl_ i (+ j 1)) ( * (shl_ i j) 2)))))\n(assert (forall ((i Int)) (! (= (shr_ i 0) i) :pattern ((shr_ i 0)) )))\n(assert (forall ((i Int) (j Int)) (=> (<= 0 j) (= (shr_ i (+ j 1)) (divide (shr_ i j) 2)))))\n(assert (forall ((a Int) (b Int)) (! (= (= (System_dot_String_dot_Equals_System_dot_String_ a b) Smt_dot_true) (= (System_dot_String_dot_Equals_System_dot_String_System_dot_String_ a b) Smt_dot_true)) :pattern ((System_dot_String_dot_Equals_System_dot_String_ a b)) )))\n(assert (forall ((a Int) (b Int)) (! (= (= (System_dot_String_dot_Equals_System_dot_String_System_dot_String_ a b) Smt_dot_true) (= (System_dot_String_dot_Equals_System_dot_String_System_dot_String_ b a) Smt_dot_true)) :pattern ((System_dot_String_dot_Equals_System_dot_String_System_dot_String_ a b)) )))\n(assert (forall ((a Int) (b Int)) (! (=> (and (not (= a nullObject)) (not (= b nullObject)) (= (System_dot_String_dot_Equals_System_dot_String_System_dot_String_ a b) Smt_dot_true)) (= (System_dot_String_dot_IsInterned_System_dot_String_notnull_ a) (System_dot_String_dot_IsInterned_System_dot_String_notnull_ b))) :pattern ((System_dot_String_dot_Equals_System_dot_String_System_dot_String_ a b)) )))\n(assert (not (= (IsStaticField Bag_dot_n) Smt_dot_true)))\n(assert (= (IsDirectlyModifiableField Bag_dot_n) Smt_dot_true))\n(assert (= (DeclType Bag_dot_n) Bag))\n(assert (= (AsRangeField Bag_dot_n System_dot_Int32) Bag_dot_n))\n(assert (not (= (IsStaticField Bag_dot_a) Smt_dot_true)))\n(assert (= (IsDirectlyModifiableField Bag_dot_a) Smt_dot_true))\n(assert (= (AsRepField Bag_dot_a Bag) Bag_dot_a))\n(assert (= (DeclType Bag_dot_a) Bag))\n(assert (= (AsNonNullRefField Bag_dot_a (ValueArray System_dot_Int32 1)) Bag_dot_a))\n(assert (subtypes Bag Bag))\n(assert (= (BaseClass_ Bag) System_dot_Object))\n(assert (subtypes Bag (BaseClass_ Bag)))\n(assert (= (AsDirectSubClass Bag (BaseClass_ Bag)) Bag))\n(assert (not (= (IsImmutable_ Bag) Smt_dot_true)))\n(assert (= (AsMutable_ Bag) Bag))\n(assert (forall ((oi_ Int) (h_ Int)) (! (let ((v_0 (select2 h_ oi_ Bag_dot_n))) (=> (and (= (IsHeap h_) Smt_dot_true) (subtypes (select2 h_ oi_ inv_) Bag) (not (= (select2 h_ oi_ localinv_) System_dot_Object))) (and (<= 0 v_0) (<= v_0 (Length_ (select2 h_ oi_ Bag_dot_a)))))) :pattern ((subtypes (select2 h_ oi_ inv_) Bag)) )))\n(assert (forall ((U_ Int)) (! (=> (subtypes U_ System_dot_Boolean) (= U_ System_dot_Boolean)) :pattern ((subtypes U_ System_dot_Boolean)) )))\n(assert (subtypes Microsoft_dot_Contracts_dot_ObjectInvariantException Microsoft_dot_Contracts_dot_ObjectInvariantException))\n(assert (subtypes Microsoft_dot_Contracts_dot_GuardException Microsoft_dot_Contracts_dot_GuardException))\n(assert (subtypes System_dot_Exception System_dot_Exception))\n(assert (= (BaseClass_ System_dot_Exception) System_dot_Object))\n(assert (subtypes System_dot_Exception (BaseClass_ System_dot_Exception)))\n(assert (= (AsDirectSubClass System_dot_Exception (BaseClass_ System_dot_Exception)) System_dot_Exception))\n(assert (not (= (IsImmutable_ System_dot_Exception) Smt_dot_true)))\n(assert (= (AsMutable_ System_dot_Exception) System_dot_Exception))\n(assert (subtypes System_dot_Runtime_dot_Serialization_dot_ISerializable System_dot_Object))\n(assert (= (IsMemberlessType_ System_dot_Runtime_dot_Serialization_dot_ISerializable) Smt_dot_true))\n(assert (subtypes System_dot_Exception System_dot_Runtime_dot_Serialization_dot_ISerializable))\n(assert (subtypes System_dot_Runtime_dot_InteropServices_dot__Exception System_dot_Object))\n(assert (= (IsMemberlessType_ System_dot_Runtime_dot_InteropServices_dot__Exception) Smt_dot_true))\n(assert (subtypes System_dot_Exception System_dot_Runtime_dot_InteropServices_dot__Exception))\n(assert (= (BaseClass_ Microsoft_dot_Contracts_dot_GuardException) System_dot_Exception))\n(assert (subtypes Microsoft_dot_Contracts_dot_GuardException (BaseClass_ Microsoft_dot_Contracts_dot_GuardException)))\n(assert (= (AsDirectSubClass Microsoft_dot_Contracts_dot_GuardException (BaseClass_ Microsoft_dot_Contracts_dot_GuardException)) Microsoft_dot_Contracts_dot_GuardException))\n(assert (not (= (IsImmutable_ Microsoft_dot_Contracts_dot_GuardException) Smt_dot_true)))\n(assert (= (AsMutable_ Microsoft_dot_Contracts_dot_GuardException) Microsoft_dot_Contracts_dot_GuardException))\n(assert (= (BaseClass_ Microsoft_dot_Contracts_dot_ObjectInvariantException) Microsoft_dot_Contracts_dot_GuardException))\n(assert (subtypes Microsoft_dot_Contracts_dot_ObjectInvariantException (BaseClass_ Microsoft_dot_Contracts_dot_ObjectInvariantException)))\n(assert (= (AsDirectSubClass Microsoft_dot_Contracts_dot_ObjectInvariantException (BaseClass_ Microsoft_dot_Contracts_dot_ObjectInvariantException)) Microsoft_dot_Contracts_dot_ObjectInvariantException))\n(assert (not (= (IsImmutable_ Microsoft_dot_Contracts_dot_ObjectInvariantException) Smt_dot_true)))\n(assert (= (AsMutable_ Microsoft_dot_Contracts_dot_ObjectInvariantException) Microsoft_dot_Contracts_dot_ObjectInvariantException))\n(assert (subtypes System_dot_Array System_dot_Array))\n(assert (= (BaseClass_ System_dot_Array) System_dot_Object))\n(assert (subtypes System_dot_Array (BaseClass_ System_dot_Array)))\n(assert (= (AsDirectSubClass System_dot_Array (BaseClass_ System_dot_Array)) System_dot_Array))\n(assert (not (= (IsImmutable_ System_dot_Array) Smt_dot_true)))\n(assert (= (AsMutable_ System_dot_Array) System_dot_Array))\n(assert (subtypes System_dot_ICloneable System_dot_Object))\n(assert (= (IsMemberlessType_ System_dot_ICloneable) Smt_dot_true))\n(assert (subtypes System_dot_Array System_dot_ICloneable))\n(assert (subtypes System_dot_Collections_dot_IList System_dot_Object))\n(assert (subtypes System_dot_Collections_dot_ICollection System_dot_Object))\n(assert (subtypes System_dot_Collections_dot_IEnumerable System_dot_Object))\n(assert (= (IsMemberlessType_ System_dot_Collections_dot_IEnumerable) Smt_dot_true))\n(assert (subtypes System_dot_Collections_dot_ICollection System_dot_Collections_dot_IEnumerable))\n(assert (= (IsMemberlessType_ System_dot_Collections_dot_ICollection) Smt_dot_true))\n(assert (subtypes System_dot_Collections_dot_IList System_dot_Collections_dot_ICollection))\n(assert (subtypes System_dot_Collections_dot_IList System_dot_Collections_dot_IEnumerable))\n(assert (= (IsMemberlessType_ System_dot_Collections_dot_IList) Smt_dot_true))\n(assert (subtypes System_dot_Array System_dot_Collections_dot_IList))\n(assert (subtypes System_dot_Array System_dot_Collections_dot_ICollection))\n(assert (subtypes System_dot_Array System_dot_Collections_dot_IEnumerable))\n(assert (= (IsMemberlessType_ System_dot_Array) Smt_dot_true))\n(assert (subtypes System_dot_Type System_dot_Type))\n(assert (subtypes System_dot_Reflection_dot_MemberInfo System_dot_Reflection_dot_MemberInfo))\n(assert (= (BaseClass_ System_dot_Reflection_dot_MemberInfo) System_dot_Object))\n(assert (subtypes System_dot_Reflection_dot_MemberInfo (BaseClass_ System_dot_Reflection_dot_MemberInfo)))\n(assert (= (AsDirectSubClass System_dot_Reflection_dot_MemberInfo (BaseClass_ System_dot_Reflection_dot_MemberInfo)) System_dot_Reflection_dot_MemberInfo))\n(assert (= (IsImmutable_ System_dot_Reflection_dot_MemberInfo) Smt_dot_true))\n(assert (= (AsImmutable_ System_dot_Reflection_dot_MemberInfo) System_dot_Reflection_dot_MemberInfo))\n(assert (subtypes System_dot_Reflection_dot_ICustomAttributeProvider System_dot_Object))\n(assert (= (IsMemberlessType_ System_dot_Reflection_dot_ICustomAttributeProvider) Smt_dot_true))\n(assert (subtypes System_dot_Reflection_dot_MemberInfo System_dot_Reflection_dot_ICustomAttributeProvider))\n(assert (subtypes System_dot_Runtime_dot_InteropServices_dot__MemberInfo System_dot_Object))\n(assert (= (IsMemberlessType_ System_dot_Runtime_dot_InteropServices_dot__MemberInfo) Smt_dot_true))\n(assert (subtypes System_dot_Reflection_dot_MemberInfo System_dot_Runtime_dot_InteropServices_dot__MemberInfo))\n(assert (= (IsMemberlessType_ System_dot_Reflection_dot_MemberInfo) Smt_dot_true))\n(assert (= (BaseClass_ System_dot_Type) System_dot_Reflection_dot_MemberInfo))\n(assert (subtypes System_dot_Type (BaseClass_ System_dot_Type)))\n(assert (= (AsDirectSubClass System_dot_Type (BaseClass_ System_dot_Type)) System_dot_Type))\n(assert (= (IsImmutable_ System_dot_Type) Smt_dot_true))\n(assert (= (AsImmutable_ System_dot_Type) System_dot_Type))\n(assert (subtypes System_dot_Runtime_dot_InteropServices_dot__Type System_dot_Object))\n(assert (= (IsMemberlessType_ System_dot_Runtime_dot_InteropServices_dot__Type) Smt_dot_true))\n(assert (subtypes System_dot_Type System_dot_Runtime_dot_InteropServices_dot__Type))\n(assert (subtypes System_dot_Reflection_dot_IReflect System_dot_Object))\n(assert (= (IsMemberlessType_ System_dot_Reflection_dot_IReflect) Smt_dot_true))\n(assert (subtypes System_dot_Type System_dot_Reflection_dot_IReflect))\n(assert (= (IsMemberlessType_ System_dot_Type) Smt_dot_true))\n(assert (subtypes Microsoft_dot_Contracts_dot_ICheckedException System_dot_Object))\n(assert (= (IsMemberlessType_ Microsoft_dot_Contracts_dot_ICheckedException) Smt_dot_true))\n(assert (forall ((A Int) (i Int) (v Int)) (= (select1 (store1 A i v) i) v)))\n(assert (forall ((A Int) (i Int) (j Int) (v Int)) (=> (not (= i j)) (= (select1 (store1 A i v) j) (select1 A j)))))\n(assert (forall ((A Int) (o Int) (f Int) (v Int)) (= (select2 (store2 A o f v) o f) v)))\n(assert (forall ((A Int) (o Int) (f Int) (p Int) (g Int) (v Int)) (=> (not (= o p)) (= (select2 (store2 A o f v) p g) (select2 A p g)))))\n(assert (forall ((A Int) (o Int) (f Int) (p Int) (g Int) (v Int)) (=> (not (= f g)) (= (select2 (store2 A o f v) p g) (select2 A p g)))))\n(assert (forall ((x Int) (y Int)) (= (= (boolIff x y) Smt_dot_true) (= (= x Smt_dot_true) (= y Smt_dot_true)))))\n(assert (forall ((x Int) (y Int)) (= (= (boolImplies x y) Smt_dot_true) (=> (= x Smt_dot_true) (= y Smt_dot_true)))))\n(assert (forall ((x Int) (y Int)) (= (= (boolAnd x y) Smt_dot_true) (and (= x Smt_dot_true) (= y Smt_dot_true)))))\n(assert (forall ((x Int) (y Int)) (= (= (boolOr x y) Smt_dot_true) (or (= x Smt_dot_true) (= y Smt_dot_true)))))\n(assert (forall ((x Int)) (! (= (= (boolNot x) Smt_dot_true) (not (= x Smt_dot_true))) :pattern ((boolNot x)) )))\n(assert (forall ((x Int) (y Int)) (= (= (anyEqual x y) Smt_dot_true) (= x y))))\n(assert (forall ((x Int) (y Int)) (! (= (= (anyNeq x y) Smt_dot_true) (not (= x y))) :pattern ((anyNeq x y)) )))\n(assert (forall ((x Int) (y Int)) (= (= (intLess x y) Smt_dot_true) (< x y))))\n(assert (forall ((x Int) (y Int)) (= (= (intAtMost x y) Smt_dot_true) (<= x y))))\n(assert (forall ((x Int) (y Int)) (= (= (intAtLeast x y) Smt_dot_true) (>= x y))))\n(assert (forall ((x Int) (y Int)) (= (= (intGreater x y) Smt_dot_true) (> x y))))\n(assert (distinct Smt_dot_false Smt_dot_true))\n(assert (forall ((t Int)) (! (subtypes t t) :pattern ((subtypes t t)) )))\n(assert (forall ((t Int) (u Int) (v Int)) (! (=> (and (subtypes t u) (subtypes u v)) (subtypes t v)) :pattern ((subtypes t u) (subtypes u v)) )))\n(assert (forall ((t Int) (u Int)) (! (=> (and (subtypes t u) (subtypes u t)) (= t u)) :pattern ((subtypes t u) (subtypes u t)) )))\n(assert (let ((v_0 (forall ((o_ Int)) (let ((v_5 (select2 Heap_ o_ ownerRef_)) (v_6 (select2 Heap_ o_ ownerFrame_))) (=> (and (not (= o_ nullObject)) (= (= (select2 Heap_ o_ allocated_) Smt_dot_true) true)) (and (= v_5 v_5) (= v_6 v_6)))))) (v_1 (= ReallyLastGeneratedExit_correct Smt_dot_true)) (v_2 (= block6086_correct Smt_dot_true)) (v_3 (= block6069_correct Smt_dot_true)) (v_4 (= entry_correct Smt_dot_true))) (not (=> (=> (=> true (=> (= (IsHeap Heap_) Smt_dot_true) (=> (= BeingConstructed_ nullObject) (=> true (=> true (=> (=> (=> true (=> true (=> true (=> (=> (=> true (=> true (=> true (=> (=> (=> true (and v_0 (=> v_0 (=> true true)))) v_1) v_1)))) v_2) v_2)))) v_3) v_3)))))) v_4) v_4))))\n(check-sat)\n.\n  intros.\n  (* cbv beta delta [with_pattern] in *. *)\n  cbv [with_pattern] in *.\n\n  rewrite! True_implies in H244.\n  rewrite! implies_True in H244.\n  rewrite! and_True in H244.\n  setoid_rewrite equals_True in H244.\n  apply H244; clear H244.\n  intro P. apply P. clear P.\n  intros P1 P2 P3.\n  apply P3; clear P3.\n  intro P; apply P; clear P.\n  intro P; apply P; clear P.\n  intros *.\n  intro P3. destruct P3 as [P3 P4].\n  split; reflexivity. (* turns out to be a trivial goal *)\nQed.\n\n(* https://www.starexec.org/starexec/secure/details/benchmark.jsp?id=6920515\n(amortized queues in leon) declares datatypes, and these cannot be parsed as a goal\n*)\n", "meta": {"author": "samuelgruetter", "repo": "ltac-sat", "sha": "96447a3f627e5e8d8f29e6eff4353cf75d4e82ff", "save_path": "github-repos/coq/samuelgruetter-ltac-sat", "path": "github-repos/coq/samuelgruetter-ltac-sat/ltac-sat-96447a3f627e5e8d8f29e6eff4353cf75d4e82ff/ParseSMT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24077694898629712}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef2.Spec.\nRequire Import TableDataOpsRef3.Specs.table_map3.\nRequire Import TableDataOpsRef3.LowSpecs.table_map3.\nRequire Import TableDataOpsRef3.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       table_map_spec\n       table_map2_spec\n    .\n\n  Lemma table_map3_spec_exists:\n    forall habd habd'  labd g_rd map_addr level res\n           (Hspec: table_map3_spec g_rd map_addr level habd = Some (habd', res))\n            (Hrel: relate_RData habd labd),\n    exists labd', table_map3_spec0 g_rd map_addr level labd = Some (labd', res) /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque peq ptr_eq.\n    intros. duplicate Hrel. destruct D. clear hrepl lrepl. destruct g_rd.\n    unfold table_map3_spec, table_map3_spec0 in *.\n    unfold Assertion in *. rm_bind Hspec; rm_bind'. simpl in *.\n    unfold Assertion; rm_bind'; grewrite.\n    repeat simpl_hyp Hspec; extract_prop_dec; simpl_query_oracle; rm_bind'; grewrite.\n    - rewrite_oracle_rel rel_oracle C5.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold map_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec; clear H0; grewrite;\n        (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C5.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold map_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec; clear H0; grewrite;\n        (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C5.\n      repeat (grewrite; try simpl_htarget; simpl). inversion Hspec.\n      (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C5.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n    - rewrite_oracle_rel rel_oracle C5.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef3/RefProof/table_map3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24077694898629712}}
{"text": "\n(** Basic concepts **)\nParameter object : Type.\n(** Categories **)\nDefinition S:= Prop.\n\nDefinition ADV := (object -> Prop) -> (object -> Prop).\n\n(*Definition VeridicalAdvStrong := { adv : (object -> Prop) -> (object -> Prop) &\n                          forall (x : object) (v : object -> Prop) (f : (object -> Prop) -> (object -> Prop)), f (adv v) x -> f v x}. (**) FIXME: probably too strong; consider eg. the case where f is \"not\". This would probably be OK for co-variant f's though. *)\nDefinition AdV := ADV.\nDefinition Adv := ADV.\n\nDefinition VeridicalAdv :=\n  { adv : (object -> Prop) -> (object -> Prop)\n    & prod (forall (x : object) (v : object -> Prop), (adv v) x -> v x)\n           (forall (v w : object -> Prop), (forall x, v x -> w x) -> forall (x : object), adv v x -> adv w x)\n    }.\n\nDefinition WkVeridical : VeridicalAdv -> Adv\n                       := fun adv => projT1 adv.\nCoercion WkVeridical : VeridicalAdv >-> Adv.\n(* Theorem WkADV : VeridicalAdvStrong -> VeridicalAdv. cbv. intro adv. destruct adv as [adv cov]. exists adv. intros. apply cov with (f := fun p => p). exact H. Qed. *)\n(* Coercion WkADV : VeridicalAdvStrong >-> VeridicalAdv. *)\nParameter CAdv : Set.\nParameter IAdv : Set.\nParameter IDet : Set.\nParameter IP : Set.\nParameter IQuant : Set.\nParameter PConj : Set.\nDefinition QCl := Prop.\nDefinition QS := Prop.\nDefinition Subj := Prop -> Prop -> Prop.\nDefinition CN:= object->Prop.\nDefinition VP:= forall (subjectClass : CN), object -> Prop. (* subject *)\nDefinition SC := VP.\nDefinition V := object -> Prop.\nDefinition V2S := object -> S -> object -> Prop.\nDefinition V2V := object -> VP -> object -> Prop.\nDefinition V3 := object -> object -> object -> Prop. (* indirect object, direct object, subject *)\nDefinition V2 := object->object->Prop. (* Object first, subject second. *)\nDefinition VV := VP -> object -> Prop.\nDefinition VPS := VP.\nParameter VQ : Set.\nDefinition VS := S -> VP.\nParameter RP : Set.\n\nInductive Conj : Type :=\n  Associative : (Prop -> Prop -> Prop) -> Conj |\n  EitherOr : Conj.\nDefinition A := (object -> Prop) -> (object -> Prop).\nDefinition A2 := object -> A.\nDefinition IntersectiveA := object -> Prop.\nDefinition wkIntersectiveA\n            : IntersectiveA -> A\n            := fun a cn (x:object) => a x /\\ cn x.\nCoercion wkIntersectiveA : IntersectiveA >-> A.\n\nInductive SubsectiveA : Type :=\n  mkSubsective : ((object -> Prop) -> (object -> Prop)) -> SubsectiveA.\nAdd Printing Let SubsectiveA.\n\nDefinition apSubsectiveA\n            : SubsectiveA -> A\n            := fun a cn (x:object) => let (aa) := a in\n                 aa cn x /\\ cn x .\nDefinition getSubsectiveA : SubsectiveA -> A.\nintro. destruct X. exact P. Defined.\nCoercion apSubsectiveA : SubsectiveA >-> A.\n\nInductive ExtensionalSubsectiveA : Type :=\n  mkExtensionalSubsective : forall (a : (object -> Prop) -> (object -> Prop)),\n     (forall (p q:object -> Prop), (forall x, p x -> q x) -> (forall x, q x -> p x) ->  forall x, a p x -> a q x)\n     -> ExtensionalSubsectiveA.\n\nAdd Printing Let ExtensionalSubsectiveA.\n\nDefinition apExtensionalSubsectiveA\n            : ExtensionalSubsectiveA -> A\n            := fun a cn (x:object) => let (aa,_) := a in\n                 aa cn x /\\ cn x .\nCoercion apExtensionalSubsectiveA : ExtensionalSubsectiveA >-> A.\n\nInductive PrivativeA : Type :=\n  mkPrivativeA : ((object -> Prop) -> (object -> Prop)) -> PrivativeA.\nAdd Printing Let PrivativeA.\nDefinition wkPrivativeA : PrivativeA -> A\n            := fun aa cn (x:object) => let (a) := aa in a cn x /\\ not (cn x).\nCoercion wkPrivativeA : PrivativeA >-> A.\nDefinition NonCommitalA := A.\n\n\nDefinition AP:= A.\nDefinition N:= object->Prop.\nDefinition N2 := object -> object -> Prop.\nInductive Num : Type :=\n  singular : Num |\n  plural   : Num |\n  unknownNum : Num |\n  moreThan : Num -> Num |\n  cardinal : nat -> Num.\nDefinition Card := Num.\nDefinition AdN : Type := Num -> Num.\n\nParameter LOTS_OF : CN -> CN. (* \"lots of\" is treated like an adjective *)\nParameter MANY : nat.\nParameter A_FEW : nat.\nParameter SOME : nat. (* the plural number *)\nParameter SEVERAL : nat.\n\nFixpoint interpAtLeast (num:Num) (x:nat) :=\n  match num with\n  | singular => x >= 1\n  | plural   => x >= SOME\n  | unknownNum => True\n  | moreThan n => interpAtLeast n x\n  | cardinal n => x >= n\n  end.\n\nDefinition interpAtMost : Num -> nat -> Prop :=\n  fun num x => match num with\n  | singular => x <= 1\n  | plural   => x <= SOME\n  | unknownNum => True\n  | moreThan _ => True\n  | cardinal n => x <= n\n  end.\n\nDefinition interpExactly : Num -> nat -> Prop :=\n  fun num x => match num with\n  | singular => x = 1\n  | plural   => True\n  | unknownNum => True\n  | moreThan n => interpAtLeast n x\n  | cardinal n => x = n\n  end.\n\nDefinition Numeral := nat.\nDefinition NP0 := VP ->Prop.\nDefinition NP1 := (object -> Prop) ->Prop.\n\nDefinition Quant := Num -> CN -> NP0.\nDefinition Det := prod Num Quant.\n\nInductive Prep : Type :=\n\n  mkPrep : forall (prep : NP1 -> (object -> Prop) -> (object -> Prop)),\n           (forall (prepArg : NP1) (v : object -> Prop) (subject : object), prep prepArg v subject -> v subject) -> (* veridical *)\n           (forall (prepArg : NP1) (v w : object -> Prop), (forall x, v x -> w x) -> forall (subject : object), prep prepArg v subject -> prep prepArg w subject) -> Prep. (* covariant in verb *)\n\nAdd Printing Let Prep.\n\nInductive NP : Type :=\n  mkNP : Num -> Quant -> CN -> NP.\nDefinition npClass (np:NP) := let (_,_,cn) := np in cn.\nDefinition apNP : NP -> NP0.\ncbv. intro np. destruct np as [num quant cn]. apply quant. exact num. exact cn. Defined.\nDefinition VPSlash:=object -> VP.\nDefinition Pron := NP.\nInductive PN : Type := mkPN : forall (x:object) (cn : CN), cn x -> PN.\nDefinition Cl:=Prop.\nDefinition Pol:= Prop->Prop. (* Polarity *)\nDefinition Temp:= Prop -> Prop. (* temporal information *)\nDefinition Phr:= Prop.\nDefinition Ord:=A.\nDefinition Comp := VP. (* complement of copula*)\nDefinition Predet := NP -> NP.\nDefinition AdA := A -> A.\nDefinition ClSlash := VP. (* the parameter is the direct object of the verb *)\n\nDefinition RCl := VP. (* relative clause *)\nDefinition RS := RCl.\n\n\n(** Constructors **)\n\n\n(* Adv *)\n(* Parameter AdAdv : AdA -> Adv -> Adv . *)\n(* Parameter ComparAdvAdj : CAdv -> A -> NP -> Adv . *)\n(* Parameter ComparAdvAdjS : CAdv -> A -> S -> Adv . *)\n(* Parameter ConjAdv : Conj -> ListAdv -> Adv . *)\nParameter PositAdvAdj : A -> Adv .\n\n(* Definition VeridicalAdv := { adv : (object -> Prop) -> (object -> Prop) & forall (x : object) (v : object -> Prop), (adv v) x -> v x}. *)\n\nDefinition apNP1 : NP -> NP1 := fun np => (fun k => apNP np (fun xClass x => k x)).\n\nDefinition PrepNP : Prep -> NP -> VeridicalAdv.\nintros prepRecord np.\ndestruct prepRecord as [prep prepVerid prepVeridCov].\ncbv.\nexists (prep (apNP1 np)).\nsplit.\nintros. apply prepVerid with (prepArg := apNP1 np). assumption.\nintros. apply prepVeridCov with (prepArg := apNP1 np) (v:=v). assumption. assumption.\nDefined.\nDefinition SubjS : Subj -> S -> Adv := fun subj s vp x => subj s (vp x).\n\n\n\n(* Card *)\nDefinition AdNum : AdN -> Card -> Card := fun f => f.\n(* Parameter NumDigits : Digits -> Card . *)\nDefinition NumNumeral : Numeral -> Card := fun x => cardinal x.\n(* Parameter digits2numeral : Card -> Card . *)\nParameter half_a_Card : Card .\n\n(* Num *)\nDefinition NumSg:= singular.\nDefinition NumPl:= plural.\nDefinition NumCard : Card -> Num := fun x => x.\n\n(* CN *)\nDefinition UseN: N->CN := fun n:N=>n.\nDefinition AdjCN: AP->CN->CN:= fun a o x => a o x.\nDefinition RelCN: CN->RS->CN:= fun cn rs x => cn x /\\ rs cn x. (* GF FIXME: Relative clauses should apply to NPs. See 013, 027, 044.  *)\n\nDefinition AdvCN : CN -> Adv -> CN := fun cn adv => adv cn.\nDefinition ComplN2 : N2 -> NP -> CN\n                   := fun n2 np x => apNP np (fun _class y => n2 y x).\n\nDefinition apConj2 : Conj -> Prop -> Prop -> Prop := fun c => match c with\n  Associative c => c |\n  EitherOr => fun p q => (p /\\ not q ) \\/ (not p /\\ q)\n  end .\n\nDefinition ConjCN2 : Conj -> CN -> CN -> CN\n                   := fun c n1 n2 o => apConj2 c (n1 o) (n2 o).\n\n(* Parameter PartNP : CN -> NP -> CN . *)\nParameter SentCN : CN -> SC -> CN .\nParameter elliptic_CN : CN .\n(* Parameter ApposCN : CN -> NP -> CN . *)\n(* Parameter ConjCN : Conj -> ListCN -> CN . *)\n(* Parameter PossNP : CN -> NP -> CN . *)\n(* Parameter UseN2 : N2 -> CN . *)\n\n(* SC *)\nParameter EmbedPresPart : VP -> SC .\n(* Parameter EmbedQS : QS -> SC . *)\nDefinition EmbedS : S -> SC := fun s _ _ => s.\n  (* Used in cases such as \"it is true/likely/false/... that <clause>\"\n     So we have a copula. Thus \"x\" is \"it\". (no info, can be ignored)\n     Likewise for the 'noun class' of it.\n     *)\n\nDefinition EmbedVP : VP -> SC := fun vp => vp.\n\n(* NP *)\nDefinition DetCN: Det->CN->NP:= fun det cn=> mkNP (fst det) (snd det) cn.\nDefinition UsePN: PN->NP:=\n  \n  fun pn => let (o,oClass,_) := pn in mkNP singular (fun (num : Num) (cn : CN) (vp : VP) => vp cn o) oClass.\nDefinition PredetNP: Predet -> NP -> NP\n                   := fun predet np => predet np.\n\nDefinition   AdvNP : NP -> Adv -> NP\n := fun np adv => let (num,q,cn) := np in mkNP num (fun cn' k => q cn' (adv k)) cn. (* CHECK *)\n(* Parameter ConjNP : Conj -> ListNP -> NP . *)\n\n\nDefinition apConj3 : Conj -> Prop -> Prop -> Prop -> Prop := fun c => match c with\n  Associative c => fun p q r => c (c p q) r |\n  EitherOr => fun p q r => (p /\\ not q /\\ not r)\\/ (not p /\\ q /\\ not r)\\/ (not p /\\ not q /\\ r)\n  end .\n\n\nDefinition ConjNP2 : Conj -> NP -> NP -> NP\n                   := fun c np1 np2 => let (num1, q1,cn1) := np1 in\n                                       let (num2, q2,cn2) := np2 in\n                                         mkNP (num1) (* FIXME add numbers? min? max? *)\n                                              (fun num' cn' vp => apConj2 c (q1 num' cn' vp) (q2 num' cn' vp))\n                                              (fun x => (cn1 x) \\/ (cn2 x) ).\n\nDefinition ConjNP3 : Conj -> NP -> NP -> NP -> NP\n                   := fun c np1 np2 np3 =>\n                         let (num1, q1,cn1) := np1 in\n                         let (num2, q2,cn2) := np2 in\n                         let (num3, q3,cn3) := np3 in\n                              mkNP (num1) (* FIXME add numbers? min? max? *)\n                                   (fun num' cn' vp => apConj3 c (q1 num' cn' vp) (q2 num' cn' vp) (q3 num' cn' vp))\n                                   (fun x => (cn1 x) \\/ (cn2 x) \\/ (cn3 x)).\n(* Parameter CountNP : Det -> NP -> NP . *)\nParameter DetNP : Det -> NP .\n(* Parameter ExtAdvNP : NP -> Adv -> NP . *)\nDefinition MassNP : CN -> NP\n           := fun cn => mkNP singular (fun num cn' p => exists x, cn' x /\\ p cn' x) cn. (* TODO: Check *)\n\nDefinition PPartNP : NP -> V2 -> NP  (* Word of warning: in FraCas partitives always behave like intersection, which is probably not true in general *)\n          := fun np v2 => let (num,q,cn) := np in\n                          mkNP num q (fun x => cn x /\\ exists subject, v2 x subject).\n(* Parameter RelNP : NP -> RS -> NP . *)\nDefinition RelNPa : NP -> RS -> NP\n                 := fun np rs => let (num,q,cn) := np\n                                 in mkNP num q (fun x => cn x /\\ rs cn x).\n(* Parameter SelfNP : NP -> NP . *)\nDefinition UsePron : Pron -> NP := fun pron => pron.\n(* AP *)\nDefinition PositA: A -> A := fun x:A=>x.\n\n(* In GF this is PositA : A -> AP; however this type does the conversion from the adjectival subclass to generic adjectives, which is wrong *)\nDefinition AdAP:AdA->AP->AP:= fun ad a => ad a.\n\nParameter AdvAP0 : AP -> Adv -> object -> Prop . (* We want to ignore the class here *)\nDefinition AdvAP : AP -> Adv -> AP\n  := fun adj adv cn x => AdvAP0 adj adv x.\n\nDefinition ComparA : A -> NP -> AP\n := fun a np cn x => apNP np (fun _class y =>    (a cn y -> a cn x)\n                                              /\\ (not (a cn x) -> not (a cn y))).\n(* Remark: most of the time, the comparatives are used in a copula, and in that case the category comes from the NP.  *)\n (* x is faster than y  *)\n \nDefinition ComparAsAs : A -> NP -> AP\n := fun a np cn x => apNP np (fun _class y => a cn x <-> a cn y).\nDefinition ComplA2 : A2 -> NP -> AP := fun a2 np cn x => apNP np (fun yClass y => a2 y cn x).\nParameter PartVP : VP -> AP .\nDefinition SentAP : AP -> SC -> AP\n  := fun ap clause cn x => ap (fun y => clause cn y /\\ cn y) x.\nParameter UseComparA : A -> AP.\nDefinition UseComparA_prefix : A -> AP := fun adj cn x => adj cn x.\n(* Parameter UseA2 : A2 -> AP . *)\n(* Parameter ConjAP : Conj -> ListAP -> AP . *)\n(* Parameter ReflA2 : A2 -> AP . *)\n(* Parameter AdjOrd : Ord -> AP . *)\n(* Parameter CAdvAP : CAdv -> AP -> NP -> AP . *)\n\n(* Quant *)\nParameter environment : (object -> Prop) -> object.\nParameter OF : object -> object -> Prop.\nDefinition GenNP: NP -> Quant := (* Genitive *)\n  fun np num cn vp => apNP np (fun ownerClass owner =>\n    let o := environment (fun x => OF owner x /\\ cn x)\n    in vp cn o /\\ OF owner o /\\ cn o).\n\n\nParameter CARD: CN -> nat.\nParameter MOSTPART: nat -> nat.\nDefinition CARD_MOST := fun x => MOSTPART (CARD x).\n\nVariable MOST_ineq : forall x, MOSTPART x <= x.\nVariable CARD_monotonous : forall a b:CN, (forall x, a x -> b x) -> CARD a <= CARD b.\nParameter le_trans : forall x y z, x <= y -> y <= z -> x <= z.\nLemma most_card_mono1 : forall a b:CN, (forall x, a x -> b x) -> MOSTPART (CARD a) <= CARD b.\nintros. cbv. apply le_trans with (y := CARD a). apply MOST_ineq. apply CARD_monotonous. assumption.\nQed.\n\nDefinition IndefArt:Quant:= fun (num : Num) (P:CN)=> fun Q:VP=> match num with\n  cardinal n => CARD (fun x => P x /\\ Q P x) = n |\n  moreThan n => interpAtLeast n (CARD (fun x => P x /\\ Q P x)) | (* FIXME: add one here *)\n  _ => exists x, P x/\\Q P x end. \nDefinition DefArt:Quant:= fun (num : Num) (P:CN)=> fun Q:VP=> match num with\n   plural => (forall x, P x -> Q P x) /\\ Q P (environment P) /\\ P (environment P) |\n             (* The above implements definite plurals *)\n   _ => Q P (environment P) /\\ P (environment P) end.\n\n\n\n(**Definition DefArt:Quant:= fun P:CN=> fun Q:object->Prop=>exists x,  P x/\\ Q x.**)\n  (* JP: \"exists!\" fails to identify that we refer to a thing outside the current NP ??? *)\n\nParameter PossPron : Pron -> Quant .\nDefinition  no_Quant : Quant:= fun num P Q=> forall x, not (P x -> Q P x) .\n(* Parameter that_Quant : Quant . *)\nParameter the_other_Q : Quant .\nParameter this_Quant : Quant .\n\n(* Det *)\nDefinition DetQuant: Quant -> Num -> Det:= fun (q:Quant) (n : Num) => (n,q). \nDefinition DetQuantOrd: Quant->Num->Ord->Det:= fun q n o =>(n,q). (* Ignoring the ord for now *)\n(* Parameter ConjDet : Conj -> ListDet -> Det . *)\n\n(* VPSlash *)\nDefinition SlashV2a: V2->VPSlash:= fun v dobj sClass s => v dobj s.\n\n(* Parameter AdVVPSlash : AdV -> VPSlash -> VPSlash . *)\n(* Parameter AdvVPSlash : VPSlash -> Adv -> VPSlash . *)\n(* Parameter SlashV2A : V2A -> AP -> VPSlash . *)\n(* Parameter SlashV2Q : V2Q -> QS -> VPSlash . *)\n(* Parameter SlashV2VNP : V2V -> NP -> VPSlash -> VPSlash . *)\n(* Parameter VPSlashPrep : VP -> Prep -> VPSlash . *)\nDefinition Slash2V3 : V3 -> NP -> VPSlash\n                    := fun v np indirectObject subjectClass subject => apNP np (fun class directObject => v indirectObject directObject subject).\nDefinition Slash3V3 : V3 -> NP -> VPSlash\n                    := fun v np directObject subjectClass subject => apNP np (fun _class indirectObject => v indirectObject directObject subject).\nDefinition SlashV2S : V2S -> S -> VPSlash\n                   := fun v2s s directObject subjectClass subject => v2s directObject s subject.\nDefinition SlashV2V : V2V -> VP -> VPSlash\n                    := fun v2v vp directObject subjectClass subject => v2v directObject vp subject.\nDefinition SlashVV : VV -> VPSlash -> VPSlash\n                   := fun vv v2 directObject subjectClass subject => vv (fun xClass x => v2 directObject xClass x) subject.\nParameter elliptic_VPSlash : VPSlash .\n\n(* AdV *)\n\n\n(* QS *)\n(* Parameter ConjQS : Conj -> ListQS -> QS . *)\nDefinition ConjQS2 : Conj -> QS -> QS -> QS\n                   := fun c => apConj2 c.\n(* Parameter ExtAdvQS : Adv -> QS -> QS . *)\nParameter UseQCl : Temp -> Pol -> QCl -> QS .\n\n(* QCl *)\n(* Parameter ExistIP : IP -> QCl . *)\n(* Parameter ExistIPAdv : IP -> Adv -> QCl . *)\nDefinition QuestCl : Cl -> QCl := fun c => c.\nParameter QuestIAdv : IAdv -> Cl -> QCl .\n(* Parameter QuestIComp : IComp -> NP -> QCl . *)\n(* Parameter QuestQVP : IP -> QVP -> QCl . *)\n(* Parameter QuestSlash : IP -> ClSlash -> QCl . *)\nParameter QuestVP : IP -> VP -> QCl .\n\n\n(* IQuant *)\nParameter which_IQuant : IQuant .\n\n(* IDet *)\n\nParameter IdetQuant : IQuant -> Num -> IDet .\nParameter how8many_IDet : IDet .\n\n(* IP *)\n(* Parameter AdvIP : IP -> Adv -> IP . *)\nParameter IdetCN : IDet -> CN -> IP .\n(* Parameter IdetIP : IDet -> IP . *)\n\n(* IAdv *)\n\n(* Parameter AdvIAdv : IAdv -> Adv -> IAdv . *)\n(* Parameter ConjIAdv : Conj -> ListIAdv -> IAdv . *)\n(* Parameter PrepIP : Prep -> IP -> IAdv . *)\n\n(* VP *)\nDefinition ComplSlash: VPSlash->NP->VP:=fun v2 dobject subjectClass subject=> apNP dobject(fun oClass o => v2 o subjectClass subject).\nDefinition UseComp: Comp -> VP (* be ... *)\n                  := fun p => p.\nDefinition ComplVV: VV -> VP -> VP\n                  := fun vv vp xClass x => vv vp x.\n\nDefinition AdVVP : AdV -> VP -> VP\n                 := fun adV vp xClass x => adV (fun y => vp xClass y) x.\n                 (* can inherit the class of x, because the new VP applies to x anyway *)\n\n\n\nDefinition  AdvVP : VP -> Adv -> VP:= fun vp adV xClass x => adV (fun y => vp xClass y) x.\n(* Parameter ComplBareVS : VS -> S -> VP . *)\nParameter ComplVQ : VQ -> QS -> VP .\nDefinition ComplVS : VS -> S -> VP\n                   := fun vs s => vs s.\nDefinition ComplVSa : VS -> S -> VP := ComplVS. (* FIXME: what is the difference from ComplVS? *)\n(* Parameter ExtAdvVP : VP -> Adv -> VP . *)\nParameter PassV2 : V2 -> VP .\nParameter PassV2s : V2 -> VP .\nParameter PassVPSlash : VPSlash -> VP .\n(* Parameter ProgrVP : VP -> VP . *)\nParameter ProgrVPa : VP -> VP .\nDefinition ReflVP : VPSlash -> VP\n                 := fun v2 subjectClass subject => v2 subject subjectClass subject.\n(* Parameter SelfAdVVP : VP -> VP . *)\n(* Parameter SelfAdvVP : VP -> VP . *)\n(* Parameter UseCopula : VP . *)\nDefinition UseV : V -> VP\n                := fun v xClass x => v x.\nParameter elliptic_VP : VP .\n\n(* Comp -- complement of copula*)\nDefinition CompCN: CN -> Comp (* be a thing given by the CN *)\n                 := fun cn xClass x => cn x.\nDefinition CompNP: NP -> Comp (* be the thing given by the NP *)\n                 := fun np oClass o => apNP np (fun o'Class o' => o = o').\n\nDefinition CompAP: AP -> Comp (* have property given by the AP *)\n                 := fun ap xClass x => ap xClass x.\n\nDefinition CompAdv : Adv -> Comp := fun adv xClass x => adv (fun _ => True) x.\n(* In the above we ignore the class, because test cases 027 and 044 seem to suggest that adverbs do not depend on the class of the object that they are applied to. This makes intuitive sense as adverbs to not expect a noun class, but rather a VP. (Actually, we could propagate the class and make use of it if it were not for relative clauses being applied to common nouns instead of NPs. See RelCN above.) *)\n\n\n(* Temp *)\nDefinition Past : Temp  := fun p => p .\nDefinition Present : Temp := fun p => p .\n\nDefinition Conditional : Temp := fun p => p.\nDefinition Future : Temp := fun p => p.\nDefinition FuturePerfect : Temp := fun p => p.\nDefinition PastPerfect : Temp := fun p => p.\nDefinition PresentPerfect : Temp := fun p => p.\n\n(* fun TTAnt : Tense -> Ant -> Temp ; *)\n\n(* Cl *)\nDefinition PredVP: NP->VP->Cl:= fun np vp=> apNP np vp.\nDefinition ExistNP: NP->Cl:= fun n=>apNP n (fun x xClass => True).\nParameter IMPERSONAL : object.\nDefinition ImpersCl : VP -> Cl := fun vp => vp (fun x => True) IMPERSONAL.\nParameter SoDoI : NP -> Cl .\nParameter elliptic_Cl : Cl .\n(* Parameter CleftAdv : Adv -> S -> Cl . *)\n(* Parameter CleftNP : NP -> RS -> Cl . *)\n(* Parameter ExistNPAdv : NP -> Adv -> Cl . *)\n(* Parameter GenericCl : VP -> Cl . *)\n(* Parameter PredSCVP : SC -> VP -> Cl . *)\n(* Parameter active2passive : Cl -> Cl . *)\n\n(* ClSlash *)\n(* Parameter AdvSlash : ClSlash -> Adv -> ClSlash . *)\n(* Parameter SlashPrep : Cl -> Prep -> ClSlash . *)\n(* Parameter SlashVS : NP -> VS -> SSlash -> ClSlash . *)\nDefinition SlashVP : NP -> VPSlash -> ClSlash\n                   := fun np vp dobjectClass dobject => apNP np (fun subjectClass subject => vp dobject subjectClass subject).\n\n(* RCl *)\nDefinition RelVP: RP->VP->RCl:= fun relativePronounIgnored => fun p => p.\n\nParameter EmptyRelSlash : ClSlash -> RCl .\n(* Parameter RelCl : Cl -> RCl . *)\nDefinition RelSlash : RP -> ClSlash -> RCl := fun rpIgnored cl => cl. (* TODO: Check *)\nDefinition StrandRelSlash : RP -> ClSlash -> RCl := fun rp cl => cl.\n\n(* RS *)\nDefinition UseRCl: Temp->Pol->RCl->RS:=fun t p r xClass x => p (r xClass x).\n\n(* RP *)\n(* Parameter FunRP : Prep -> NP -> RP -> RP . *)\nParameter IdRP : RP .\nParameter that_RP : RP .\n\n(* Pol *)\nDefinition PPos:Pol:= fun p=>p.\nDefinition UncNeg : Pol := fun p => not p.\nDefinition PNeg : Pol := UncNeg.\n\n(* VPS *)\n\n(* Parameter ConjVPS : Conj -> ListVPS -> VPS . *)\nDefinition ConjVPS2 : Conj -> Temp -> Pol -> VP -> Temp -> Pol -> VP -> VPS\n  := fun conj _t1 pol1 vp1 _t2 pol2 vp2 xClass x => apConj2 conj (pol1 (vp1 xClass x)) (pol2 (vp2 xClass x)).\n\n(* Parameter MkVPS : Temp -> Pol -> VP -> VPS . *)\n\n\n(* S *)\nDefinition UseCl: Temp -> Pol -> Cl -> S := fun temp pol cl => temp (pol cl).\nParameter AdvS : Adv -> S -> S .\n(* Parameter ConjS : Conj -> ListS -> S . *)\nDefinition ConjS2 : Conj -> S -> S -> S\n                  := fun c s1 s2 => apConj2 c s1 s2.\nDefinition ExtAdvS : Adv -> S -> S := fun adv s => adv (fun _ => s) IMPERSONAL.\nDefinition PredVPS : NP -> VPS -> S := fun np vp => apNP np vp.\n\n(* Parameter RelS : S -> RS -> S . *)\n(* Parameter SSubjS : S -> Subj -> S -> S . *)\n\n(* PConj *)\n(* Parameter NoPConj : PConj . *)\n(* Parameter PConjConj : Conj -> PConj . *)\n\n(* Phr *)\nDefinition Sentence: S->Phr:= fun sentence=> sentence.\n\nParameter Adverbial : Adv -> Phr .\nParameter Nounphrase : NP -> Phr .\nParameter PAdverbial : PConj -> Adv -> Phr .\nParameter PNounphrase : PConj -> NP -> Phr .\n(* Parameter PQuestion : PConj -> QS -> Phr . *)\nParameter PSentence : PConj -> S -> Phr .\n(* Parameter PhrUtt : PConj -> Utt -> Voc -> Phr . *)\nParameter Question : QS -> Phr .\n\n(* Ord *)\nDefinition  OrdSuperl: A->Ord:= fun a=>a.\n\n(* Parameter OrdDigits : Digits -> Ord . *)\nParameter OrdNumeral : Numeral -> Ord .\n(* Parameter OrdNumeralSuperl : Numeral -> A -> Ord . *)\n\n(* N2 *)\n(* Parameter ComplN3 : N3 -> NP -> N2 . *)\n(* Parameter Use2N3 : N3 -> N2 . *)\n(* Parameter Use3N3 : N3 -> N2 . *)\n\n\n(** Lexicon **)\n\nParameter person_N : N .\n\n\nParameter whatPl_IP : IP .\nParameter whatSg_IP : IP .\nParameter whoPl_IP : IP .\nParameter whoSg_IP : IP .\nParameter how8much_IAdv : IAdv .\nParameter how_IAdv : IAdv .\nParameter when_IAdv : IAdv .\nParameter where_IAdv : IAdv .\nParameter why_IAdv : IAdv .\n\n(* VQ *)\nParameter know_VQ : VQ .\nParameter come_cheap_VP : VP .\n\nParameter and_PConj : PConj .\nParameter but_PConj : PConj .\nParameter otherwise_PConj : PConj .\nParameter that_is_PConj : PConj .\nParameter then_PConj : PConj .\nParameter therefore_PConj : PConj .\n\nDefinition all_AdV : AdV := fun vp x => vp x . (* Adds no info *)\nParameter already_AdV : AdV .\nParameter also_AdV : AdV .\nParameter always_AdV : AdV .\nParameter currently_AdV : AdV .\nParameter ever_AdV : AdV .\nParameter never_AdV : AdV .\nParameter now_AdV : AdV .\nParameter still_AdV : AdV .\n\n(*Definition a_few_Det : Det := (cardinal A_FEW, fun (num:Num) (cn : CN) (vp : VP) => (exists x, cn x /\\ vp x)).*)\nDefinition a_few_Det : Det := (cardinal A_FEW, fun (num:Num) (cn : CN) (vp : VP) =>\n   A_FEW = CARD (fun x => cn x /\\ vp cn x) /\\ exists x, cn x /\\ vp cn x).\n\nDefinition all_Quant : Quant :=fun (num:Num) (cn : CN) (vp : VP) => forall x, cn x->vp cn x.\n\nDefinition  a_lot_of_Det : Det:= (singular, fun num cn vp => (exists x, cn x /\\ LOTS_OF cn x /\\ vp cn x)) . (* Because this is used for \"a lot of\" is a mass; it's still singular. *)\nParameter another_Det : Det .\nParameter anyPl_Det : Det .\nDefinition  both_Det :  Det:= (cardinal 2, fun num P Q=> exists x y, (P x /\\ Q P x) /\\ (P y /\\ Q P y) /\\ not(x = y)).\nDefinition each_Det : Det := (unknownNum, all_Quant) .\nDefinition anySg_Det : Det := each_Det.\nParameter either_Det : Det .\nDefinition  every_Det : Det:= each_Det.\nDefinition  all_Det : Det:= every_Det.\nDefinition few_Det : Det:= (cardinal A_FEW, fun num P Q => CARD (fun x => P x /\\ Q P x) <= A_FEW). (* Some tests seem to suggest that \"few\" does not imply existence, see eg. 044, 076. *)\n(* DOUBLE NUM: Note that we ignore the cardinality in the Quantifier part, because \"a few three men\" make no sense. *)\nSet Implicit Arguments. \n\nDefinition  many_Det : Det:= (cardinal MANY, fun num P Q=> (exists x, P x /\\ Q P x) /\\ (CARD (fun x => P x /\\ Q P x) >= MANY)). (* See DOUBLE NUM: above *)\nParameter much_Det : Det .\nDefinition neither_Det :  Det:= (cardinal 2, fun num P Q=> exists x y, P x /\\ not (Q P x) /\\ P y /\\ not (Q P y) /\\ not (x = y)). \nParameter one_or_more_Det : Det.\nDefinition somePl_Det : Det:= (plural, fun num P Q=> (exists x,  P x /\\ Q P x)) .\n(* One would prefer, in this case, to have the cardinality informtion as well, as follows:\n  Definition somePl_Det : Det:= (plural, fun num P Q=> (exists x,  P x /\\ Q P x) /\\ CARD ((fun x =>  P x /\\ Q P x)) > 1) .\n  This information is tested in 109. But then again, 107 contradicts this interpretation, so we leave the simplest definition for the time being.\n*)\nDefinition someSg_Det : Det:= (singular, fun num P Q=> exists x,  P x /\\ Q P x ).\nDefinition several_Det: Det:= (cardinal SEVERAL, fun num P Q=> (exists x,  P x /\\ Q P x) /\\ (CARD (fun x => P x /\\ Q P x) >= SEVERAL)). (* See DOUBLE NUM: above *)\nParameter twice_as_many_Det : Det .\n\nParameter elliptic_NP_Pl : NP .\nParameter elliptic_NP_Sg : NP .\nParameter everybody_NP : NP .\nParameter everything_NP : NP .\nParameter nobody_NP : NP .\nParameter nothing_NP : NP .\nParameter somebody_NP : NP .\nParameter something_NP : NP .\n\n(* AdA *)\nParameter almost_AdA : AdA .\nParameter quite_Adv : AdA .\nParameter really_AdA : AdA .\nParameter so_AdA : AdA .\nParameter too_AdA : AdA .\nParameter very_AdA : AdA .\n\n(* Pron *)\nParameter anyone_Pron : Pron .\nDefinition everyone_Pron : Pron := mkNP unknownNum (fun num (cn : CN) (vp : VP) => forall x, cn x -> vp cn x) person_N.\nParameter heRefl_Pron : Pron .\nParameter he_Pron : Pron .\nParameter i_Pron : Pron .\nParameter itRefl_Pron : Pron .\nParameter it_Pron : Pron .\nDefinition no_one_Pron : Pron := mkNP unknownNum (fun num (cn : CN) (vp : VP) => forall x, cn x -> not (vp cn x)) person_N.\nParameter nobody_Pron : Pron .\nParameter sheRefl_Pron : Pron .\nParameter she_Pron : Pron .\nDefinition someone_Pron:Pron:= mkNP singular (fun num (cn : CN) (vp : VP) => exists x, cn x /\\ (vp cn x)) person_N.\nParameter theyRefl_Pron : Pron .\nParameter they_Pron : Pron .\nParameter we_Pron : Pron .\nParameter youPl_Pron : Pron .\nParameter youPol_Pron : Pron .\nParameter youSg_Pron : Pron .\n\n(* Predet *)\nDefinition all_Predet : Predet\n  := fun np => let (num,qIGNORED,cn) := np\n               in mkNP num all_Quant cn.\n\nDefinition at_least_Predet : Predet\n  := fun np => let (num,qIGNORED,cn) := np\n               in mkNP num (fun num cn vp => interpAtLeast num (CARD (fun x => cn x /\\ vp cn x))) cn.\nDefinition at_most_Predet : Predet := fun np => let (num,qIGNORED,cn) := np\n               in mkNP num (fun num cn vp => interpAtMost num (CARD (fun x => cn x /\\ vp cn x))) cn.\nDefinition exactly_Predet : Predet := fun np => let (num,qIGNORED,cn) := np\n               in mkNP num (fun num cn vp => interpExactly num (CARD (fun x => cn x /\\ vp cn x))) cn.\nDefinition just_Predet : Predet := exactly_Predet.\n\nDefinition MOST_Quant : Quant :=\n    fun num (cn : CN) (vp : VP) => CARD (fun x => cn x /\\ vp cn x) >= CARD_MOST cn /\\ exists x, cn x /\\ vp cn x.\n\nDefinition  most_Predet : Predet\n  := fun np => let (num,qIGNORED,cn0) := np\n               in mkNP num MOST_Quant cn0.\nParameter most_of_Predet : Predet .\nParameter not_Predet : Predet .\nParameter only_Predet : Predet .\n\n(* Subj *)\n\nParameter after_Subj : Subj .\nParameter although_Subj : Subj .\nParameter because_Subj : Subj .\nParameter before_Subj : Subj .\nDefinition if_Subj : Subj := fun p q => p -> q.\nParameter since_Subj : Subj .\nParameter than_Subj : Subj .\nParameter that_Subj : Subj .\nParameter until_Subj : Subj .\nParameter when_Subj : Subj .\nParameter while_Subj : Subj .\n\n(* Prep *)\n\nParameter above_Prep : Prep .\nParameter after_Prep : Prep .\nParameter at_Prep : Prep .\nParameter before_Prep : Prep .\nParameter behind_Prep : Prep .\nParameter between_Prep : Prep .\nParameter by8agent_Prep : Prep .\nParameter by8means_Prep : Prep .\nParameter during_Prep : Prep .\nParameter except_Prep : Prep .\nParameter for_Prep : Prep .\nParameter from_Prep : Prep .\n\nParameter in8front_Prep : Prep .\nParameter in_Prep : Prep .\nParameter on_Prep : Prep .\nParameter out_of_Prep : Prep .\nParameter outside_Prep : Prep .\nParameter part_Prep : Prep .\nParameter possess_Prep : Prep .\nParameter than_Prep : Prep .\nParameter through_Prep : Prep .\nParameter to_Prep : Prep .\nParameter under_Prep : Prep .\nParameter with_Prep : Prep .\nParameter within_Prep : Prep .\nParameter without_Prep : Prep .\n\n(* CAdv *)\nParameter as_CAdv : CAdv .\nParameter less_CAdv : CAdv .\nParameter more_CAdv : CAdv .\n\nParameter allow_V2V : V2V .\nParameter bring_V2V : V2V .\nParameter elliptic_V2V : V2V .\nParameter see_V2V : V2V .\nParameter take_V2V : V2V .\n\nParameter suggest_to_V2S : V2S .\n\nParameter believe_VS : VS .\nParameter claim_VS : VS .\nParameter discover_VS : VS .\nParameter know_VS : VS .\nParameter say_VS : VS .\n\nParameter less_than_AdN : AdN .\nDefinition more_than_AdN : AdN := moreThan .\n\nParameter impressed_by_A2 : A2 .\n\nDefinition andSg_Conj : Conj := Associative (fun p q => p /\\ q).\nDefinition and_Conj : Conj := Associative (fun p q => p /\\ q).\n(* Parameter both7and_DConj : Conj . *)\nParameter comma_and_Conj : Conj .\nDefinition either7or_DConj : Conj := EitherOr.\nParameter if_comma_then_Conj : Conj .\n(* Parameter if_then_Conj : Conj . *)\nDefinition or_Conj : Conj  := Associative (fun p q => p \\/ q).\nParameter semicolon_and_Conj : Conj .\n\nParameter can8know_VV : VV .\nParameter can_VV : VV .\nParameter do_VV : VV .\nParameter finish_VV : VV .\nParameter going_to_VV : VV .\nParameter manage_VV : VV .\nParameter must_VV : VV .\nParameter need_VV : VV .\nParameter shall_VV : VV .\nParameter start_VV : VV .\nParameter try_VV : VV .\nParameter use_VV : VV .\nParameter want_VV : VV .\nParameter chairman_N2 : N2.\nDefinition chairman_N : N :=  fun o => exists institution, chairman_N2 institution o.\nParameter group_N2 : N2 .\nParameter inhabitant_N2 : N2 .\nParameter nobel_prize_N2 : N2 .\nParameter resident_in_N2 : N2 .\nParameter resident_on_N2 : N2 .\n\nParameter N_10 : Numeral .\nParameter N_100 : Numeral .\nParameter N_13 : Numeral .\nParameter N_14 : Numeral .\nParameter N_15 : Numeral .\nParameter N_150 : Numeral .\nParameter N_2 : Numeral .\nDefinition N_2500 : Numeral := 2500.\nDefinition N_3000 : Numeral := 3000.\nDefinition N_4 : Numeral := 4.\nDefinition N_500 : Numeral := 500.\nDefinition N_5500 : Numeral := 5500.\nParameter N_8 : Numeral .\nParameter N_99 : Numeral .\nParameter N_eight : Numeral .\nDefinition N_eleven : Numeral := 11 .\nParameter N_five : Numeral .\nParameter N_fortyfive : Numeral .\nParameter N_four : Numeral .\nDefinition N_one : Numeral := 1.\nDefinition N_six : Numeral := 6.\nDefinition N_sixteen : Numeral := 16.\nDefinition N_ten : Numeral := 10.\nDefinition N_three : Numeral := 3.\nDefinition N_twenty : Numeral := 20.\nDefinition N_two : Numeral := 2.\n(* Parameter digits2num : Digits -> Numeral . *)\n(* Parameter num : Sub1000000 -> Numeral . *)\nParameter beat_V : V .\nParameter come_in_V : V .\nParameter continue_V : V .\nParameter crash_V : V .\nParameter elliptic_V : V .\nParameter exist_V : V .\nParameter expand_V : V .\nParameter gamble_V : V .\nParameter go8travel_V : V .\nParameter go8walk_V : V .\nParameter graduate_V : V .\nParameter increase_V : V .\nParameter leave_V : V .\nParameter live_V : V .\nParameter meet_V : V .\nParameter start_V : V .\nParameter stop_V : V .\nParameter swim_V : V .\nParameter travel_V : V .\nParameter work_V : V .\n\nParameter award_V3 : V3 .\nParameter contribute_to_V3 : V3 .\nParameter deliver_V3 : V3 .\nParameter obtain_from_V3 : V3 .\nParameter put_in_V3 : V3 .\nParameter rent_from_V3 : V3 .\nParameter tell_about_V3 : V3 .\n\nParameter anywhere_Adv : Adv .\nParameter at_8_am_Adv : Adv .\nParameter at_a_quarter_past_five_Adv : Adv .\nParameter at_five_oclock_Adv : Adv .\nParameter at_four_oclock_Adv : Adv .\nParameter at_home_Adv : VeridicalAdv .\nParameter at_least_four_times : Adv .\nParameter at_some_time_Adv : Adv .\nParameter at_the_same_time_Adv : Adv .\nParameter by_11_am_Adv : Adv .\nParameter ever_since_Adv : Adv .\nParameter every_month_Adv : Adv .\nParameter every_week_Adv : Adv .\nParameter everywhere_Adv : Adv .\nParameter for_8_years_Adv : Adv .\nParameter for_a_total_of_15_years_or_more_Adv : Adv .\nParameter for_a_year_Adv : Adv .\nParameter for_an_hour_Adv : Adv .\nParameter for_exactly_a_year_Adv : Adv .\nParameter for_more_than_10_years_Adv : Adv .\nParameter for_more_than_two_years_Adv : Adv .\nParameter for_three_days_Adv : Adv .\nParameter for_two_hours_Adv : Adv .\nParameter for_two_years_Adv : VeridicalAdv .\nParameter friday_13th_Adv : Adv .\nParameter from_1988_to_1992_Adv : Adv .\nParameter here7from_Adv : Adv .\nParameter here7to_Adv : Adv .\nParameter here_Adv : Adv .\nParameter in_1990_Adv : VeridicalAdv .\nParameter in_1991_Adv : VeridicalAdv .\nParameter in_1992_Adv : VeridicalAdv .\nParameter in_1993_Adv : VeridicalAdv .\nParameter in_1994_Adv : VeridicalAdv .\nParameter in_a_few_weeks_Adv : Adv .\nParameter in_a_months_time_Adv : Adv .\nParameter in_july_1994_Adv : Adv .\nParameter in_march_1993_Adv : Adv .\nParameter in_march_Adv : Adv .\nParameter in_one_hour_Adv : Adv .\nParameter in_the_coming_year_Adv : Adv .\nParameter in_the_past_Adv : Adv .\nParameter in_two_hours_Adv : Adv .\nParameter last_week_Adv : Adv .\nParameter late_Adv : Adv .\nParameter long_Adv : Adv .\nParameter on_friday_Adv : Adv .\nParameter on_july_4th_1994_Adv : Adv .\nParameter on_july_8th_1994_Adv : Adv .\nParameter on_monday_Adv : Adv .\nParameter on_the_5th_of_may_1995_Adv : Adv .\nParameter on_the_7th_of_may_1995_Adv : Adv .\nParameter on_thursday_Adv : Adv .\nParameter on_time_Adv : VeridicalAdv .\nParameter on_tuesday_Adv : Adv .\nParameter on_wednesday_Adv : Adv .\nParameter over_Adv : Adv .\nParameter part_time_Adv : Adv .\nParameter saturday_july_14th_Adv : Adv .\nParameter since_1992_Adv : Adv .\nParameter somewhere_Adv : Adv .\nParameter the_15th_of_may_1995_Adv : Adv .\nParameter there7from_Adv : Adv .\nParameter there7to_Adv : Adv .\nParameter there_Adv : Adv .\nParameter together_Adv : Adv .\nParameter too_Adv : Adv .\nParameter twice_Adv : Adv .\nParameter two_years_from_now_Adv : Adv .\nParameter year_1996_Adv : Adv .\nParameter yesterday_Adv : Adv .\n\nParameter alan_PN : PN .\nParameter anderson_PN : PN .\nParameter apcom_PN : PN .\nParameter berlin_PN : PN .\nParameter bill_PN : PN .\nParameter birmingham_PN : PN .\nParameter bt_PN : PN .\nParameter bug_32985_PN : PN .\nParameter cambridge_PN : PN .\nParameter carl_PN : PN .\nParameter europe_PN : PN .\nParameter fido_PN : PN .\nParameter florence_PN : PN .\nParameter frank_PN : PN .\nParameter gfi_PN : PN .\nParameter helen_PN : PN .\nParameter icm_PN : PN .\nParameter itel_PN : PN .\nParameter john_PN : PN .\nParameter katmandu_PN : PN .\nParameter luxembourg_PN : PN .\nParameter mary_PN : PN .\nParameter mfi_PN : PN .\nParameter mtalk_PN : PN .\nParameter paris_PN : PN .\nParameter pavarotti_PN : PN .\nParameter peter_PN : PN .\nParameter portugal_PN : PN .\nParameter r95103_PN : PN .\nParameter scandinavia_PN : PN .\nParameter southern_europe_PN : PN .\nParameter sue_PN : PN .\nParameter sweden_PN : PN .\nParameter the_cia_PN : PN .\nParameter the_m25_PN : PN .\n\nParameter ambitious_A : A .\nParameter ancient_A : A .\nParameter asleep_A : A .\nParameter blue_A : A .\nParameter british_A : IntersectiveA .\nParameter broke_A : A .\nParameter canadian_A : A .\nParameter clever_A : SubsectiveA .\nParameter competent_A : SubsectiveA .\nParameter crucial_A : A .\nParameter dedicated_A : A .\nParameter different_A : A .\nParameter employed_A : A .\nParameter excellent_A : SubsectiveA .\nParameter false_A : PrivativeA.\nParameter fast_A : SubsectiveA .\nParameter fat_A : ExtensionalSubsectiveA .\nParameter female_A : IntersectiveA .\nParameter former_A : PrivativeA .\nParameter fourlegged_A : IntersectiveA .\nParameter free_A : A .\nParameter furious_A : A .\nParameter genuine_A : IntersectiveA .\nParameter german_A : IntersectiveA .\nParameter great_A : SubsectiveA .\nParameter important_A : A .\nParameter indispensable_A : SubsectiveA .\nParameter interesting_A : IntersectiveA .\nParameter irish_A : IntersectiveA .\nParameter italian_A : IntersectiveA .\nParameter known_A : A .\nParameter large_A : SubsectiveA .\nParameter leading_A : SubsectiveA .\nParameter legal_A : A .\nParameter likely_A : SubsectiveA .\nParameter major_A : SubsectiveA .\nParameter male_A : IntersectiveA .\nParameter many_A : IntersectiveA .\nParameter missing_A : A .\nParameter modest_A : A .\nParameter national_A : A .\nParameter new_A : A .\nParameter north_american_A : IntersectiveA .\nParameter noted_A : A .\nParameter own_A : A .\nParameter poor8bad_A : A .\nParameter poor8penniless_A : A .\nParameter portuguese_A : IntersectiveA .\nParameter present8attending_A : A .\nParameter present8current_A : A .\nParameter previous_A : A .\nParameter red_A : A .\nParameter resident_A : A .\nParameter scandinavian_A : A .\nParameter serious_A : A .\nParameter slow_A : SubsectiveA .\nParameter small_A : SubsectiveA .\nParameter successful_A : SubsectiveA .\nParameter swedish_A : IntersectiveA .\nParameter true_A : IntersectiveA.\nParameter unemployed_A : A .\nParameter western_A : A .\n\nParameter accountant_N : N .\nParameter agenda_N : N .\nParameter animal_N : N .\nParameter apcom_contract_N : N .\nParameter apcom_manager_N : N .\nParameter auditor_N : N .\nParameter authority_N : N .\nParameter board_meeting_N : N .\nParameter boss_N : N .\nParameter business_N : N .\nParameter businessman_N : N .\nParameter car_N : N .\nParameter case_N : N .\nParameter chain_N : N .\nParameter charity_N : N .\nParameter clause_N : N .\nParameter client_N : N .\nParameter colleague_N : N .\nParameter commissioner_N : N .\nParameter committee_N : N .\nParameter committee_member_N : N .\nParameter company_N : N .\nParameter company_car_N : N .\nParameter company_director_N : N .\nParameter computer_N : N .\nParameter concert_N : N .\nParameter conference_N : N .\nParameter continent_N : N .\nParameter contract_N : N .\nParameter copy_N : N .\nParameter country_N : N .\nParameter cover_page_N : N .\nParameter customer_N : N .\nParameter day_N : N .\nParameter delegate_N : N .\nParameter demonstration_N : N .\nParameter department_N : N .\nParameter desk_N : N .\nParameter diamond_N : N .\nParameter editor_N : N .\nParameter elephant_N : N .\nParameter european_N : N .\nParameter executive_N : N .\nParameter factory_N : N .\nParameter fee_N : N .\nParameter file_N : N .\nParameter greek_N : N .\nParameter hard_disk_N : N .\nParameter heart_N : N .\nParameter hour_N : N .\nParameter house_N : N .\nParameter individual_N : N .\nParameter invoice_N : N .\nParameter irishman_N : N .\nParameter italian_N : N .\nParameter itel_computer_N : N .\nParameter itelxz_N : N .\nParameter itelzx_N : N .\nParameter itelzy_N : N .\nParameter item_N : N .\nParameter job_N : N .\nParameter labour_mp_N : N .\nParameter laptop_computer_N : N .\nParameter law_lecturer_N : N .\nParameter lawyer_N : N .\nParameter line_N : N .\nParameter literature_N : N .\nParameter lobby_N : N .\nParameter loss_N : N .\nParameter machine_N : N .\nParameter mammal_N : N .\nParameter man_N : N .\nParameter meeting_N : N .\nParameter member_N : N .\nParameter member_state_N : N .\nParameter memoir_N : N .\nParameter mips_N : N .\nParameter moment_N : N .\nParameter mortgage_interest_N : N .\nParameter mouse_N : N .\nParameter newspaper_N : N .\nDefinition nobel_prize_N : N := fun o => exists x, nobel_prize_N2 x o.\nParameter note_N : N .\nParameter novel_N : N .\nParameter office_building_N : N .\nParameter one_N : N .\nParameter order_N : N .\nParameter paper_N : N .\nParameter payrise_N : N .\nParameter pc6082_N : N .\nParameter performance_N : N .\nParameter philosopher_N : N .\nParameter phone_N : N .\nParameter politician_N : N .\nParameter popular_music_N : N .\nParameter program_N : N .\nParameter progress_report_N : N .\nParameter project_proposal_N : N .\nParameter proposal_N : N .\nParameter report_N : N .\nParameter representative_N : N .\nParameter resident_N : N .\nParameter result_N : N .\nParameter right_N : N .\nParameter sales_department_N : N .\nParameter scandinavian_N : N .\nParameter secretary_N : N .\nParameter service_contract_N : N .\nParameter shore_N : N .\nParameter software_fault_N : N .\nParameter species_N : N .\nParameter station_N : N .\nParameter stockmarket_trader_N : N .\nParameter story_N : N .\nParameter student_N : N .\nParameter survey_N : N .\nParameter swede_N : N .\nParameter system_N : N .\nParameter system_failure_N : N .\nParameter taxi_N : N .\nParameter temper_N : N .\nParameter tenor_N : N .\nParameter time_N : N .\nParameter today_N : N .\nParameter traffic_N : N .\nParameter train_N : N .\nParameter university_graduate_N : N .\nParameter university_student_N : N .\nParameter week_N : N .\nParameter wife_N : N .\nParameter woman_N : N .\nParameter workstation_N : N .\nParameter world_N : N .\nParameter year_N : N .\n\nParameter MICKEY : object.\nParameter MICKEY_ANIM : animal_N MICKEY.\nDefinition mickey_PN := mkPN MICKEY animal_N MICKEY_ANIM  .\nParameter DUMBO : object.\nParameter DUMBO_ANIM : animal_N DUMBO.\nDefinition dumbo_PN := mkPN DUMBO animal_N DUMBO_ANIM .\nParameter jones : object.\nParameter jones_PERSON : person_N jones.\nDefinition jones_PN := mkPN jones person_N jones_PERSON.\n\nParameter SMITH : object.\nParameter SMITH_PERSON : person_N SMITH.\nDefinition smith_PN := mkPN SMITH person_N SMITH_PERSON.\n\nParameter KIM : object.\nParameter KIM_PERSON : person_N KIM.\nDefinition kim_PN := mkPN KIM person_N KIM_PERSON.\n\nParameter PC6082 : object.\nParameter PC6082_COMPY : computer_N PC6082.\nDefinition pc_6082_PN := mkPN PC6082 computer_N PC6082_COMPY.\n\nParameter ITEL_XZ : object.\nParameter ITEL_XZ_COMPY : computer_N ITEL_XZ.\nDefinition itel_xz_PN := mkPN ITEL_XZ computer_N ITEL_XZ_COMPY.\n(* Syntactic replacement FIXME: it could also be possible to add environment (pc6082_N) = itel_xz_PN ; but then we also need environment to return a default class. *)\n(* Definition the_pc6082_NP : NP := (DetCN (DetQuant (DefArt) (NumSg)) (UseN (pc6082_N))). *)\nDefinition the_pc6082_NP : NP := UsePN pc_6082_PN.\n\n(* Definition the_itel_xz_NP : NP := (DetCN (DetQuant (DefArt) (NumSg)) (UseN (itelxz_N))). *)\nDefinition the_itel_xz_NP : NP := UsePN itel_xz_PN.\n\nParameter accept_V2 : V2 .\nParameter answer_V2 : V2 .\nParameter appoint_V2 : V2 .\nParameter arrive_in_V2 : V2 .\nParameter attend_V2 : V2 .\nParameter award_and_be_awarded_V2 : V2 .\nParameter become_V2 : V2 .\nParameter blame1_V2 : V2 .\nParameter blame2_V2 : V2 .\nParameter build_V2 : V2 .\nParameter buy_V2 : V2 .\nParameter catch_V2 : V2 .\nParameter chair_V2 : V2 .\nParameter cost_V2 : V2 .\nParameter cross_out_V2 : V2 .\nParameter deliver_V2 : V2 .\nParameter destroy_V2 : V2 .\nParameter develop_V2 : V2 .\nParameter discover_V2 : V2 .\nParameter dupe_V2 : V2 .\nParameter find_V2 : V2 .\nParameter finish_V2 : V2 .\nParameter found_V2 : V2 .\nParameter get_V2 : V2 .\nParameter hate_V2 : V2 .\nParameter have_V2 : V2 .\nParameter hurt_V2 : V2 .\nParameter last_V2 : V2 .\nParameter leave_V2 : V2 .\nParameter like_V2 : V2 .\nParameter lose_V2 : V2 .\nParameter maintain_V2 : V2 .\nParameter make8become_V2 : V2 .\nParameter make8do_V2 : V2 .\nParameter need_V2 : V2 .\nParameter open_V2 : V2 .\nParameter own_V2 : V2 .\nParameter pay_V2 : V2 .\nParameter publish_V2 : V2 .\nParameter read_V2 : V2 .\nParameter read_out_V2 : V2 .\nParameter remove_V2 : V2 .\nParameter represent_V2 : V2 .\nParameter revise_V2 : V2 .\nParameter run_V2 : V2 .\nParameter sell_V2 : V2 .\nParameter send_V2 : V2 .\nParameter sign_V2 : V2 .\nParameter sing_V2 : V2 .\nParameter speak_to_V2 : V2 .\nParameter spend_V2 : V2 .\nParameter take_V2 : V2 .\nParameter take_part_in_V2 : V2 .\nParameter update_V2 : V2 .\nParameter use_V2 : V2 .\nParameter vote_for_V2 : V2 .\nParameter win_V2 : V2 .\nParameter work_in_V2 : V2 .\nParameter write_V2 : V2 .\nParameter write_to_V2 : V2 .\n\n(** Knowledge **)\nParameter wantCovariant_K : forall p q:VP, forall s, (forall xClass x, p xClass x -> q xClass x) -> want_VV q s -> want_VV p s.\n\nVariable  person_K: forall x:object, chairman_N(x)-> person_N(x). \nVariable  committee_member_person_K : forall x, committee_member_N x -> person_N x.\n\nVariable Not_stop_means_continue_K : forall x, stop_V x /\\ continue_V x -> False.\n\nVariable small_and_large_disjoint_K : forall cn o, getSubsectiveA small_A cn o /\\ getSubsectiveA large_A cn o -> False.\n\n(** Treebank **)\nDefinition s_001_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (italian_N))) (ComplSlash (SlashV2a (become_V2)) (DetCN (DetQuantOrd (GenNP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (world_N)))) (NumSg) (OrdSuperl (great_A))) (UseN (tenor_N))))))).\nDefinition s_001_3_h := (Sentence (UseCl (Past) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumSg)) (RelCN (UseN (italian_N)) (UseRCl (Past) (PPos) (RelVP (IdRP) (ComplSlash (SlashV2a (become_V2)) (DetCN (DetQuantOrd (GenNP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (world_N)))) (NumSg) (OrdSuperl (great_A))) (UseN (tenor_N))))))))))).\nDefinition s_002_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (AdjCN (PositA (italian_A)) (UseN (man_N)))) (ComplVV (want_VV) (UseComp (CompCN (AdjCN (PositA (great_A)) (UseN (tenor_N))))))))).\nDefinition s_002_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (somePl_Det) (AdjCN (PositA (italian_A)) (UseN (man_N)))) (UseComp (CompCN (AdjCN (PositA (great_A)) (UseN (tenor_N)))))))).\nDefinition s_002_4_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (AdjCN (PositA (italian_A)) (UseN (man_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (ComplVV (want_VV) (UseComp (CompNP (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (great_A)) (UseN (tenor_N)))))))))))))).\nDefinition s_003_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (italian_A)) (UseN (man_N))))) (ComplVV (want_VV) (UseComp (CompNP (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (great_A)) (UseN (tenor_N)))))))))).\nEval cbv in ( (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (italian_A)) (UseN (man_N))))).\nDefinition s_003_2_p := s_002_2_p.\nDefinition s_003_4_h := s_002_4_h.\nDefinition s_004_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (each_Det) (AdjCN (PositA (italian_A)) (UseN (tenor_N)))) (ComplVV (want_VV) (UseComp (CompAP (PositA (great_A)))))))).\nDefinition s_004_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (somePl_Det) (AdjCN (PositA (italian_A)) (UseN (tenor_N)))) (UseComp (CompAP (PositA (great_A))))))).\nDefinition s_004_4_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (AdjCN (PositA (italian_A)) (UseN (tenor_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (ComplVV (want_VV) (UseComp (CompAP (PositA (great_A)))))))))))).\nDefinition s_005_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (AdjCN (AdAP (really_AdA) (PositA (ambitious_A))) (UseN (tenor_N)))) (UseComp (CompAP (PositA (italian_A))))))).\nDefinition s_005_3_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (AdjCN (AdAP (really_AdA) (PositA (ambitious_A))) (UseN (tenor_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (PositA (italian_A))))))))))).\nDefinition s_006_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (no_Quant) (NumPl)) (AdjCN (AdAP (really_AdA) (PositA (great_A))) (UseN (tenor_N)))) (UseComp (CompAP (PositA (modest_A))))))).\nDefinition s_006_3_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (AdjCN (AdAP (really_AdA) (PositA (great_A))) (UseN (tenor_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (PositA (modest_A))))))))))).\nDefinition s_007_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (somePl_Det) (AdjCN (PositA (great_A)) (UseN (tenor_N)))) (UseComp (CompAP (PositA (swedish_A))))))).\nDefinition s_007_3_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (AdjCN (PositA (great_A)) (UseN (tenor_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (PositA (swedish_A))))))))))).\nDefinition s_008_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (many_Det) (AdjCN (PositA (great_A)) (UseN (tenor_N)))) (UseComp (CompAP (PositA (german_A))))))).\nDefinition s_008_3_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (AdjCN (PositA (great_A)) (UseN (tenor_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (PositA (german_A))))))))))).\nDefinition s_009_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (several_Det) (AdjCN (PositA (great_A)) (UseN (tenor_N)))) (UseComp (CompAP (PositA (british_A))))))).\nDefinition s_009_3_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (AdjCN (PositA (great_A)) (UseN (tenor_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (PositA (british_A))))))))))).\nDefinition s_010_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (most_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (great_A)) (UseN (tenor_N))))) (UseComp (CompAP (PositA (italian_A))))))).\nDefinition s_010_3_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (AdjCN (PositA (great_A)) (UseN (tenor_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (PositA (italian_A))))))))))).\nDefinition s_011_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (a_few_Det) (AdjCN (PositA (great_A)) (UseN (tenor_N)))) (ComplSlash (SlashV2a (sing_V2)) (MassNP (UseN (popular_music_N))))))).\nDefinition s_011_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (somePl_Det) (AdjCN (PositA (great_A)) (UseN (tenor_N)))) (ComplSlash (SlashV2a (like_V2)) (MassNP (UseN (popular_music_N))))))).\nDefinition s_011_4_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (AdjCN (PositA (great_A)) (UseN (tenor_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (ComplSlash (SlashV2a (sing_V2)) (MassNP (UseN (popular_music_N))))))))))).\nDefinition s_012_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (few_Det) (AdjCN (PositA (great_A)) (UseN (tenor_N)))) (UseComp (CompAP (PositA (poor8penniless_A))))))).\nDefinition s_012_3_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (AdjCN (PositA (great_A)) (UseN (tenor_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (PositA (poor8penniless_A))))))))))).\nDefinition s_013_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (both_Det) (AdjCN (PositA (leading_A)) (UseN (tenor_N)))) (UseComp (CompAP (PositA (excellent_A))))))).\nDefinition s_013_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (AdjCN (PositA (leading_A)) (UseN (tenor_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (PositA (excellent_A)))))))) (UseComp (CompAP (PositA (indispensable_A))))))).\nDefinition s_013_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (both_Det) (AdjCN (PositA (leading_A)) (UseN (tenor_N)))) (UseComp (CompAP (PositA (indispensable_A))))))).\nDefinition s_014_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (neither_Det) (AdjCN (PositA (leading_A)) (UseN (tenor_N)))) (come_cheap_VP)))).\nDefinition s_014_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (AdvNP (DetNP (DetQuant (IndefArt) (NumSg))) (PrepNP (part_Prep) (DetCN (DetQuant (DefArt) (NumPl)) (AdjCN (PositA (leading_A)) (UseN (tenor_N)))))) (UseComp (CompNP (UsePN (pavarotti_PN))))))).\nDefinition s_014_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (pavarotti_PN)) (UseComp (CompCN (RelCN (AdjCN (PositA (leading_A)) (UseN (tenor_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (come_cheap_VP))))))))).\nDefinition s_015_1_p := (Sentence (UseCl (Future) (PPos) (PredVP (PredetNP (at_least_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_three)))) (UseN (tenor_N)))) (ComplSlash (SlashV2a (take_part_in_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (concert_N))))))).\nDefinition s_015_3_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (UseN (tenor_N)) (UseRCl (Future) (PPos) (RelVP (IdRP) (ComplSlash (SlashV2a (take_part_in_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (concert_N))))))))))).\nDefinition s_016_1_p := (Sentence (UseCl (Future) (PPos) (PredVP (PredetNP (at_most_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (UseN (tenor_N)))) (ComplSlash (Slash3V3 (contribute_to_V3) (MassNP (UseN (charity_N)))) (DetCN (DetQuant (PossPron (theyRefl_Pron)) (NumPl)) (UseN (fee_N))))))).\nDefinition s_016_3_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (UseN (tenor_N)) (UseRCl (Future) (PPos) (RelVP (IdRP) (ComplSlash (Slash3V3 (contribute_to_V3) (MassNP (UseN (charity_N)))) (DetCN (DetQuant (PossPron (theyRefl_Pron)) (NumPl)) (UseN (fee_N))))))))))).\nDefinition s_017_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (irishman_N))) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (ComplN2 (nobel_prize_N2) (MassNP (UseN (literature_N))))))))).\nDefinition s_017_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (irishman_N))) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (nobel_prize_N))))))).\nDefinition s_018_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (UseN (european_N))) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (SentCN (UseN (right_N)) (EmbedVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (europe_PN))))))))))).\nDefinition s_018_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (UseN (european_N))) (UseComp (CompCN (UseN (person_N))))))).\nDefinition s_018_3_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (RelCN (UseN (person_N)) (UseRCl (Present) (PPos) (RelVP (IdRP) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (SentCN (UseN (right_N)) (EmbedVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (europe_PN)))))))))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_018_5_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (UseN (european_N))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_019_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (european_N)))) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (SentCN (UseN (right_N)) (EmbedVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (europe_PN))))))))))).\nDefinition s_019_2_p := s_018_2_p.\nDefinition s_019_3_p := s_018_3_p.\nDefinition s_019_5_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (european_N)))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_020_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (each_Det) (UseN (european_N))) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (SentCN (UseN (right_N)) (EmbedVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (europe_PN))))))))))).\nDefinition s_020_2_p := s_018_2_p.\nDefinition s_020_3_p := s_018_3_p.\nDefinition s_020_5_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (each_Det) (UseN (european_N))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_021_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (ComplN2 (resident_in_N2) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (member_state_N))))) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (SentCN (UseN (right_N)) (EmbedVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (europe_PN))))))))))).\nDefinition s_021_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (ComplN2 (resident_in_N2) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (member_state_N)))))) (UseComp (CompCN (UseN (individual_N))))))).\nDefinition s_021_3_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (RelCN (UseN (individual_N)) (UseRCl (Present) (PPos) (RelVP (IdRP) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (SentCN (UseN (right_N)) (EmbedVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (europe_PN)))))))))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_021_5_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (ComplN2 (resident_in_N2) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (member_state_N))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_022_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (no_Quant) (NumSg)) (UseN (delegate_N))) (AdvVP (ComplSlash (SlashV2a (finish_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (report_N)))) (on_time_Adv))))).\nDefinition s_022_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (no_Quant) (NumSg)) (UseN (delegate_N))) (ComplSlash (SlashV2a (finish_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (report_N))))))).\nDefinition s_023_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (somePl_Det) (UseN (delegate_N))) (AdvVP (ComplSlash (SlashV2a (finish_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (survey_N)))) (on_time_Adv))))).\nDefinition s_023_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (somePl_Det) (UseN (delegate_N))) (ComplSlash (SlashV2a (finish_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (survey_N))))))).\nDefinition s_024_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (many_Det) (UseN (delegate_N))) (ComplSlash (Slash3V3 (obtain_from_V3) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (survey_N)))) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (interesting_A)) (UseN (result_N)))))))).\nDefinition s_024_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (many_Det) (UseN (delegate_N))) (ComplSlash (Slash3V3 (obtain_from_V3) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (survey_N)))) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (result_N))))))).\nDefinition s_025_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (several_Det) (UseN (delegate_N))) (AdvVP (ComplSlash (SlashV2a (get_V2)) (PPartNP (DetCN (DetQuant (DefArt) (NumPl)) (UseN (result_N))) (publish_V2))) (PrepNP (in_Prep) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (major_A)) (AdjCN (PositA (national_A)) (UseN (newspaper_N)))))))))).\nDefinition s_025_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (several_Det) (UseN (delegate_N))) (ComplSlash (SlashV2a (get_V2)) (PPartNP (DetCN (DetQuant (DefArt) (NumPl)) (UseN (result_N))) (publish_V2)))))).\nDefinition s_026_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (most_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (european_N)))) (UseComp (CompAP (AdvAP (PositA (resident_A)) (PrepNP (in_Prep) (UsePN (europe_PN))))))))).\nDefinition s_026_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (european_N)))) (UseComp (CompCN (UseN (person_N))))))).\nDefinition s_026_3_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (UseN (person_N)) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (AdvAP (PositA (resident_A)) (PrepNP (in_Prep) (UsePN (europe_PN))))))))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_026_5_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (most_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (european_N)))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_027_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (a_few_Det) (UseN (committee_member_N))) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (sweden_PN)))))))).\nDefinition s_027_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (committee_member_N)))) (UseComp (CompCN (UseN (person_N))))))).\nDefinition s_027_3_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (UseN (person_N)) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (sweden_PN)))))))))) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (scandinavia_PN)))))))).\nDefinition s_027_5_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (at_least_Predet) (DetCN (a_few_Det) (UseN (committee_member_N)))) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (scandinavia_PN)))))))).\nDefinition s_028_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (few_Det) (UseN (committee_member_N))) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (portugal_PN)))))))).\nDefinition s_028_2_p := s_027_2_p.\nDefinition s_028_3_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (UseN (person_N)) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (portugal_PN)))))))))) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (southern_europe_PN)))))))).\nDefinition s_028_5_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (few_Det) (AdvCN (UseN (committee_member_N)) (PrepNP (from_Prep) (UsePN (southern_europe_PN)))))))).\nDefinition s_029_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (both_Det) (UseN (commissioner_N))) (ComplVV (use_VV) (UseComp (CompCN (AdjCN (PositA (leading_A)) (UseN (businessman_N))))))))).\nDefinition s_029_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (both_Det) (UseN (commissioner_N))) (ComplVV (use_VV) (UseComp (CompCN (UseN (businessman_N)))))))).\nDefinition s_030_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (neither_Det) (UseN (commissioner_N))) (AdvVP (ComplSlash (SlashV2a (spend_V2)) (DetCN (a_lot_of_Det) (UseN (time_N)))) (at_home_Adv))))).\nDefinition s_030_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (neither_Det) (UseN (commissioner_N))) (AdvVP (ComplSlash (SlashV2a (spend_V2)) (MassNP (UseN (time_N)))) (at_home_Adv))))).\nDefinition s_031_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (at_least_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_three)))) (UseN (commissioner_N)))) (AdvVP (ComplSlash (SlashV2a (spend_V2)) (DetCN (a_lot_of_Det) (UseN (time_N)))) (at_home_Adv))))).\nDefinition s_031_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (at_least_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_three)))) (UseN (commissioner_N)))) (AdvVP (ComplSlash (SlashV2a (spend_V2)) (MassNP (UseN (time_N)))) (at_home_Adv))))).\nDefinition s_032_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (at_most_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_ten)))) (UseN (commissioner_N)))) (AdvVP (ComplSlash (SlashV2a (spend_V2)) (DetCN (a_lot_of_Det) (UseN (time_N)))) (at_home_Adv))))).\nDefinition s_032_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (at_most_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_ten)))) (UseN (commissioner_N)))) (AdvVP (ComplSlash (SlashV2a (spend_V2)) (MassNP (UseN (time_N)))) (at_home_Adv))))).\nDefinition s_033_1_p := s_017_3_h.\nDefinition s_033_3_h := s_017_1_p.\nDefinition s_034_1_p := s_018_5_h.\nDefinition s_034_2_p := s_018_2_p.\nDefinition s_034_3_p := s_018_3_p.\nDefinition s_034_5_h := s_018_1_p.\nDefinition s_035_1_p := s_019_5_h.\nDefinition s_035_2_p := s_018_2_p.\nDefinition s_035_3_p := s_018_3_p.\nDefinition s_035_5_h := s_019_1_p.\nDefinition s_036_1_p := s_020_5_h.\nDefinition s_036_2_p := s_018_2_p.\nDefinition s_036_3_p := s_018_3_p.\nDefinition s_036_5_h := s_020_1_p.\nDefinition s_037_1_p := s_021_5_h.\nDefinition s_037_2_p := s_021_2_p.\nDefinition s_037_3_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (RelCN (UseN (individual_N)) (UseRCl (Present) (PPos) (RelVP (IdRP) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (SentCN (UseN (right_N)) (EmbedVP (AdvVP (AdvVP (UseV (live_V)) (anywhere_Adv)) (PrepNP (in_Prep) (UsePN (europe_PN)))))))))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_037_5_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (ComplN2 (resident_in_N2) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (member_state_N))))) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (SentCN (UseN (right_N)) (EmbedVP (AdvVP (AdvVP (UseV (live_V)) (anywhere_Adv)) (PrepNP (in_Prep) (UsePN (europe_PN))))))))))).\nDefinition s_038_1_p := s_022_3_h.\nDefinition s_038_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (someSg_Det) (UseN (delegate_N))) (AdvVP (ComplSlash (SlashV2a (finish_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (report_N)))) (on_time_Adv))))).\nDefinition s_039_1_p := s_023_3_h.\nDefinition s_039_3_h := s_023_1_p.\nDefinition s_040_1_p := s_024_3_h.\nDefinition s_040_3_h := s_024_1_p.\nDefinition s_041_1_p := s_025_3_h.\nDefinition s_041_3_h := s_025_1_p.\nDefinition s_042_1_p := s_026_5_h.\nDefinition s_042_2_p := s_026_2_p.\nDefinition s_042_3_p := s_026_3_p.\nDefinition s_042_5_h := s_026_1_p.\nDefinition s_043_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (a_few_Det) (UseN (committee_member_N))) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (scandinavia_PN)))))))).\nDefinition s_043_2_p := s_027_2_p.\nDefinition s_043_3_p := s_027_3_p.\nDefinition s_043_5_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (at_least_Predet) (DetCN (a_few_Det) (UseN (committee_member_N)))) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (sweden_PN)))))))).\nDefinition s_044_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (few_Det) (UseN (committee_member_N))) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (southern_europe_PN)))))))).\nDefinition s_044_2_p := s_027_2_p.\nDefinition s_044_3_p := s_028_3_p.\nDefinition s_044_5_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (few_Det) (AdvCN (UseN (committee_member_N)) (PrepNP (from_Prep) (UsePN (portugal_PN)))))))).\nDefinition s_045_1_p := s_029_3_h.\nDefinition s_045_3_h := s_029_1_p.\nDefinition s_046_1_p := s_030_3_h.\nDefinition s_046_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (AdvNP (DetNP (DetQuant (IndefArt) (NumSg))) (PrepNP (part_Prep) (DetCN (DetQuant (DefArt) (NumPl)) (UseN (commissioner_N))))) (AdvVP (ComplSlash (SlashV2a (spend_V2)) (DetCN (a_lot_of_Det) (UseN (time_N)))) (at_home_Adv))))).\nDefinition s_047_1_p := s_031_3_h.\nDefinition s_047_3_h := s_031_1_p.\nDefinition s_048_1_p := s_032_3_h.\nDefinition s_048_3_h := s_032_1_p.\nDefinition s_049_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (swede_N))) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (nobel_prize_N))))))).\nDefinition s_049_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (UseN (swede_N))) (UseComp (CompCN (UseN (scandinavian_N))))))).\nDefinition s_049_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (scandinavian_N))) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (nobel_prize_N))))))).\nDefinition s_050_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (AdjCN (PositA (canadian_A)) (UseN (resident_N)))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_050_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (AdjCN (PositA (canadian_A)) (UseN (resident_N)))) (UseComp (CompCN (ComplN2 (resident_on_N2) (DetCN (DetQuant (DefArt) (NumSg)) (AdjCN (PositA (north_american_A)) (UseN (continent_N)))))))))).\nDefinition s_050_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (ComplN2 (resident_on_N2) (DetCN (DetQuant (DefArt) (NumSg)) (AdjCN (PositA (north_american_A)) (UseN (continent_N)))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_051_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (canadian_A)) (UseN (resident_N))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_051_2_p := s_050_2_p.\nDefinition s_051_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (ComplN2 (resident_on_N2) (DetCN (DetQuant (DefArt) (NumSg)) (AdjCN (PositA (north_american_A)) (UseN (continent_N))))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_052_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (each_Det) (AdjCN (PositA (canadian_A)) (UseN (resident_N)))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_052_2_p := s_050_2_p.\nDefinition s_052_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (each_Det) (ComplN2 (resident_on_N2) (DetCN (DetQuant (DefArt) (NumSg)) (AdjCN (PositA (north_american_A)) (UseN (continent_N)))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_053_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (ComplN2 (resident_in_N2) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (major_A)) (AdjCN (PositA (western_A)) (UseN (country_N))))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_053_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (ComplN2 (resident_in_N2) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (major_A)) (AdjCN (PositA (western_A)) (UseN (country_N)))))))) (UseComp (CompCN (ComplN2 (resident_in_N2) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (western_A)) (UseN (country_N)))))))))).\nDefinition s_053_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (ComplN2 (resident_in_N2) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (western_A)) (UseN (country_N)))))) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (SentCN (UseN (right_N)) (EmbedVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (europe_PN))))))))))).\nDefinition s_054_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (no_Quant) (NumSg)) (AdjCN (PositA (scandinavian_A)) (UseN (delegate_N)))) (AdvVP (ComplSlash (SlashV2a (finish_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (report_N)))) (on_time_Adv))))).\nDefinition s_054_3_h := s_038_3_h.\nDefinition s_055_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (somePl_Det) (AdjCN (PositA (irish_A)) (UseN (delegate_N)))) (AdvVP (ComplSlash (SlashV2a (finish_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (survey_N)))) (on_time_Adv))))).\nDefinition s_055_3_h := s_023_1_p.\nDefinition s_056_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (many_Det) (AdjCN (PositA (british_A)) (UseN (delegate_N)))) (ComplSlash (Slash3V3 (obtain_from_V3) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (survey_N)))) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (interesting_A)) (UseN (result_N)))))))).\nDefinition s_056_3_h := s_024_1_p.\nDefinition s_057_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (several_Det) (AdjCN (PositA (portuguese_A)) (UseN (delegate_N)))) (AdvVP (ComplSlash (SlashV2a (get_V2)) (PPartNP (DetCN (DetQuant (DefArt) (NumPl)) (UseN (result_N))) (publish_V2))) (PrepNP (in_Prep) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (major_A)) (AdjCN (PositA (national_A)) (UseN (newspaper_N)))))))))).\nDefinition s_057_3_h := s_025_1_p.\nDefinition s_058_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (most_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (UseN (european_N)) (UseRCl (Present) (PPos) (RelVP (IdRP) (AdvVP (UseComp (CompAP (PositA (resident_A)))) (PrepNP (in_Prep) (UsePN (europe_PN))))))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_058_3_h := s_026_5_h.\nDefinition s_059_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (a_few_Det) (AdjCN (PositA (female_A)) (UseN (committee_member_N)))) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (scandinavia_PN)))))))).\nDefinition s_059_3_h := s_027_5_h.\nDefinition s_060_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (few_Det) (AdjCN (PositA (female_A)) (UseN (committee_member_N)))) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (southern_europe_PN)))))))).\nDefinition s_060_3_h := s_044_1_p.\nDefinition s_061_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (both_Det) (AdjCN (PositA (female_A)) (UseN (commissioner_N)))) (ComplVV (use_VV) (UseComp (CompAdv (PrepNP (in_Prep) (MassNP (UseN (business_N)))))))))).\nDefinition s_061_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (both_Det) (UseN (commissioner_N))) (ComplVV (use_VV) (UseComp (CompAdv (PrepNP (in_Prep) (MassNP (UseN (business_N)))))))))).\nDefinition s_062_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (neither_Det) (AdjCN (PositA (female_A)) (UseN (commissioner_N)))) (AdvVP (ComplSlash (SlashV2a (spend_V2)) (DetCN (a_lot_of_Det) (UseN (time_N)))) (at_home_Adv))))).\nDefinition s_062_3_h := s_046_3_h.\nDefinition s_063_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (at_least_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_three)))) (AdjCN (PositA (female_A)) (UseN (commissioner_N))))) (AdvVP (ComplSlash (SlashV2a (spend_V2)) (MassNP (UseN (time_N)))) (at_home_Adv))))).\nDefinition s_063_3_h := s_031_3_h.\nDefinition s_064_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (at_most_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_ten)))) (AdjCN (PositA (female_A)) (UseN (commissioner_N))))) (AdvVP (ComplSlash (SlashV2a (spend_V2)) (MassNP (UseN (time_N)))) (at_home_Adv))))).\nDefinition s_064_3_h := s_032_3_h.\nDefinition s_065_1_p := s_049_4_h.\nDefinition s_065_2_p := s_049_2_p.\nDefinition s_065_4_h := s_049_1_p.\nDefinition s_066_1_p := s_050_4_h.\nDefinition s_066_2_p := s_050_2_p.\nDefinition s_066_4_h := s_050_1_p.\nDefinition s_067_1_p := s_051_4_h.\nDefinition s_067_2_p := s_050_2_p.\nDefinition s_067_4_h := s_051_1_p.\nDefinition s_068_1_p := s_052_4_h.\nDefinition s_068_2_p := s_050_2_p.\nDefinition s_068_4_h := s_052_1_p.\nDefinition s_069_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (ComplN2 (resident_in_N2) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (western_A)) (UseN (country_N)))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_069_2_p := s_053_2_p.\nDefinition s_069_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (ComplN2 (resident_in_N2) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (major_A)) (AdjCN (PositA (western_A)) (UseN (country_N))))))) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (SentCN (UseN (right_N)) (EmbedVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (europe_PN))))))))))).\nDefinition s_070_1_p := s_022_1_p.\nDefinition s_070_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (someSg_Det) (AdjCN (PositA (scandinavian_A)) (UseN (delegate_N)))) (AdvVP (ComplSlash (SlashV2a (finish_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (report_N)))) (on_time_Adv))))).\nDefinition s_071_1_p := s_023_1_p.\nDefinition s_071_3_h := s_055_1_p.\nDefinition s_072_1_p := s_024_1_p.\nDefinition s_072_3_h := s_056_1_p.\nDefinition s_073_1_p := s_025_1_p.\nDefinition s_073_3_h := s_057_1_p.\nDefinition s_074_1_p := s_026_5_h.\nDefinition s_074_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (most_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (UseN (european_N)) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (AdvAP (PositA (resident_A)) (PrepNP (outside_Prep) (UsePN (europe_PN))))))))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\nDefinition s_075_1_p := s_043_1_p.\nDefinition s_075_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (at_least_Predet) (DetCN (a_few_Det) (AdjCN (PositA (female_A)) (UseN (committee_member_N))))) (UseComp (CompAdv (PrepNP (from_Prep) (UsePN (scandinavia_PN)))))))).\nDefinition s_076_1_p := s_044_1_p.\nDefinition s_076_3_h := s_060_1_p.\nDefinition s_077_1_p := s_061_3_h.\nDefinition s_077_3_h := s_061_1_p.\nDefinition s_078_1_p := s_030_1_p.\nDefinition s_078_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (AdvNP (DetNP (DetQuant (IndefArt) (NumSg))) (PrepNP (part_Prep) (DetCN (DetQuant (DefArt) (NumPl)) (AdjCN (PositA (female_A)) (UseN (commissioner_N)))))) (AdvVP (ComplSlash (SlashV2a (spend_V2)) (DetCN (a_lot_of_Det) (UseN (time_N)))) (at_home_Adv))))).\nDefinition s_079_1_p := s_031_3_h.\nDefinition s_079_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (at_least_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_three)))) (AdjCN (PositA (male_A)) (UseN (commissioner_N))))) (AdvVP (ComplSlash (SlashV2a (spend_V2)) (MassNP (UseN (time_N)))) (at_home_Adv))))).\nDefinition s_080_1_p := s_032_3_h.\nDefinition s_080_3_h := s_064_1_p.\nDefinition s_081_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (ConjNP3 (and_Conj) (UsePN (smith_PN)) (UsePN (jones_PN)) (UsePN (anderson_PN))) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))))).\nDefinition s_081_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))))).\nDefinition s_082_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (ConjNP3 (and_Conj) (UsePN (smith_PN)) (UsePN (jones_PN)) (DetCN (several_Det) (UseN (lawyer_N)))) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))))).\nDefinition s_082_3_h := s_081_3_h.\nDefinition s_083_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (ConjNP3 (either7or_DConj) (UsePN (smith_PN)) (UsePN (jones_PN)) (UsePN (anderson_PN))) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))))).\nDefinition s_083_3_h := s_081_3_h.\nDefinition s_084_1_p := s_083_1_p.\nDefinition s_084_3_h := (Sentence (ExtAdvS (SubjS (if_Subj) (UseCl (Past) (UncNeg) (PredVP (ConjNP2 (and_Conj) (UsePN (smith_PN)) (UsePN (anderson_PN))) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))))) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))))))).\nDefinition s_085_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (PredetNP (exactly_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (UseN (lawyer_N)))) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_three)))) (UseN (accountant_N)))) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))))).\nDefinition s_085_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_six)))) (UseN (lawyer_N))) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))))).\nDefinition s_086_1_p := s_085_1_p.\nDefinition s_086_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_six)))) (UseN (accountant_N))) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))))).\nDefinition s_087_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (every_Det) (ConjCN2 (and_Conj) (UseN (representative_N)) (UseN (client_N)))) (UseComp (CompAdv (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))))).\nDefinition s_087_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (every_Det) (UseN (representative_N))) (UseComp (CompAdv (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))))).\nDefinition s_088_1_p := s_087_1_p.\nDefinition s_088_3_h := s_087_3_h.\nDefinition s_089_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (every_Det) (ConjCN2 (or_Conj) (UseN (representative_N)) (UseN (client_N)))) (UseComp (CompAdv (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))))).\nDefinition s_089_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (ConjNP2 (andSg_Conj) (DetCN (every_Det) (UseN (representative_N))) (DetCN (every_Det) (UseN (client_N)))) (UseComp (CompAdv (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))))).\nDefinition s_090_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (chairman_N))) (ComplSlash (SlashV2a (read_out_V2)) (DetCN (DetQuant (DefArt) (NumPl)) (AdvCN (UseN (item_N)) (PrepNP (on_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (agenda_N)))))))))).\nDefinition s_090_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (chairman_N))) (ComplSlash (SlashV2a (read_out_V2)) (DetCN (every_Det) (AdvCN (UseN (item_N)) (PrepNP (on_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (agenda_N)))))))))).\nDefinition s_091_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (RelCN (UseN (person_N)) (UseRCl (Past) (PPos) (RelVP (IdRP) (UseComp (CompAdv (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N)))))))))) (ComplSlash (SlashV2a (vote_for_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (new_A)) (UseN (chairman_N)))))))).\nDefinition s_091_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (AdvNP (UsePron (everyone_Pron)) (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))) (ComplSlash (SlashV2a (vote_for_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (new_A)) (UseN (chairman_N)))))))).\nDefinition s_092_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (DefArt) (NumPl)) (RelCN (UseN (person_N)) (UseRCl (Past) (PPos) (RelVP (IdRP) (UseComp (CompAdv (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))))))) (ComplSlash (SlashV2a (vote_for_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (new_A)) (UseN (chairman_N)))))))).\nDefinition s_092_3_h := s_091_3_h.\nDefinition s_093_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (RelCN (UseN (person_N)) (UseRCl (Past) (PPos) (RelVP (IdRP) (UseComp (CompAdv (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N)))))))))) (AdVVP (all_AdV) (ComplSlash (SlashV2a (vote_for_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (new_A)) (UseN (chairman_N))))))))).\nDefinition s_093_3_h := s_091_3_h.\nDefinition s_094_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (ComplN2 (inhabitant_N2) (UsePN (cambridge_PN)))) (ComplSlash (SlashV2a (vote_for_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (labour_mp_N))))))).\nDefinition s_094_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (every_Det) (ComplN2 (inhabitant_N2) (UsePN (cambridge_PN)))) (ComplSlash (SlashV2a (vote_for_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (labour_mp_N))))))).\nDefinition s_095_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (AdjCN (PositA (ancient_A)) (UseN (greek_N)))) (UseComp (CompCN (AdjCN (PositA (noted_A)) (UseN (philosopher_N)))))))).\nDefinition s_095_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (every_Det) (AdjCN (PositA (ancient_A)) (UseN (greek_N)))) (UseComp (CompCN (AdjCN (PositA (noted_A)) (UseN (philosopher_N)))))))).\nDefinition s_096_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (AdjCN (PositA (ancient_A)) (UseN (greek_N)))) (AdVVP (all_AdV) (UseComp (CompCN (AdjCN (PositA (noted_A)) (UseN (philosopher_N))))))))).\nDefinition s_096_3_h := s_095_3_h.\nDefinition s_097_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (software_fault_N))) (AdvVP (PassV2s (blame1_V2)) (PrepNP (for_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (system_failure_N)))))))).\nDefinition s_097_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (system_failure_N))) (AdvVP (PassV2s (blame2_V2)) (PrepNP (on_Prep) (DetCN (one_or_more_Det) (UseN (software_fault_N)))))))).\nDefinition s_098_1_p := s_097_1_p.\nDefinition s_098_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bug_32985_PN)) (UseComp (CompCN (AdjCN (PositA (known_A)) (UseN (software_fault_N)))))))).\nDefinition s_098_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bug_32985_PN)) (AdvVP (PassV2s (blame1_V2)) (PrepNP (for_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (system_failure_N)))))))).\nDefinition s_099_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumPl)) (AdvCN (UseN (client_N)) (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (demonstration_N)))))) (AdVVP (all_AdV) (UseComp (CompAP (ComplA2 (impressed_by_A2) (DetCN (DetQuant (GenNP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (system_N)))) (NumSg)) (UseN (performance_N)))))))))).\nDefinition s_099_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (UseComp (CompCN (AdvCN (UseN (client_N)) (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (demonstration_N)))))))))).\nDefinition s_099_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (UseComp (CompAP (ComplA2 (impressed_by_A2) (DetCN (DetQuant (GenNP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (system_N)))) (NumSg)) (UseN (performance_N))))))))).\nDefinition s_100_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumPl)) (AdvCN (UseN (client_N)) (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (demonstration_N)))))) (UseComp (CompAP (ComplA2 (impressed_by_A2) (DetCN (DetQuant (GenNP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (system_N)))) (NumSg)) (UseN (performance_N))))))))).\nDefinition s_100_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (PredetNP (most_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (AdvCN (UseN (client_N)) (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (demonstration_N))))))) (UseComp (CompAP (ComplA2 (impressed_by_A2) (DetCN (DetQuant (GenNP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (system_N)))) (NumSg)) (UseN (performance_N))))))))).\nDefinition s_101_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (university_graduate_N))) (ComplSlash (SlashV2a (make8become_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (poor8bad_A)) (UseN (stockmarket_trader_N)))))))).\nDefinition s_101_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (smith_PN)) (UseComp (CompCN (UseN (university_graduate_N))))))).\nDefinition s_101_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (smith_PN)) (UseComp (CompAP (SentAP (PositA (likely_A)) (EmbedVP (ComplSlash (SlashV2a (make8become_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (poor8bad_A)) (UseN (stockmarket_trader_N)))))))))))).\nDefinition s_102_1_p := s_101_1_p.\nDefinition s_102_2_p := s_101_2_p.\nDefinition s_102_4_h := (Sentence (UseCl (Future) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (make8become_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (poor8bad_A)) (UseN (stockmarket_trader_N)))))))).\nDefinition s_103_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (apcom_manager_N)))) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (company_car_N))))))).\nDefinition s_103_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (jones_PN)) (UseComp (CompCN (UseN (apcom_manager_N))))))).\nDefinition s_103_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (company_car_N))))))).\nDefinition s_104_1_p := s_103_1_p.\nDefinition s_104_2_p := s_103_2_p.\nDefinition s_104_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumCard (AdNum (more_than_AdN) (NumNumeral (N_one))))) (UseN (company_car_N))))))).\nDefinition s_105_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (PredetNP (just_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_one)))) (UseN (accountant_N)))) (ComplSlash (SlashV2a (attend_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))).\nDefinition s_105_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (no_Quant) (NumPl)) (UseN (accountant_N))) (ComplSlash (SlashV2a (attend_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))).\nDefinition s_106_1_p := s_105_1_p.\nDefinition s_106_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (no_Quant) (NumSg)) (UseN (accountant_N))) (ComplSlash (SlashV2a (attend_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))).\nDefinition s_107_1_p := s_105_1_p.\nDefinition s_107_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (somePl_Det) (UseN (accountant_N))) (ComplSlash (SlashV2a (attend_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))).\nDefinition s_108_1_p := s_105_1_p.\nDefinition s_108_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (someSg_Det) (UseN (accountant_N))) (ComplSlash (SlashV2a (attend_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))).\nDefinition s_109_1_p := s_105_1_p.\nDefinition s_109_3_h := s_107_3_h.\nDefinition s_110_1_p := s_105_1_p.\nDefinition s_110_3_h := s_108_3_h.\nDefinition s_111_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_one)))) (UseN (contract_N))))))).\nDefinition s_111_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (sign_V2)) (DetCN (another_Det) (UseN (contract_N))))))).\nDefinition s_111_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (UsePN (smith_PN)) (UsePN (jones_PN))) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (UseN (contract_N))))))).\nDefinition s_112_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (UseN (contract_N))))))).\nDefinition s_112_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (UseN (contract_N))))))).\nDefinition s_112_4_h := s_111_4_h.\nDefinition s_113_1_p := s_112_1_p.\nDefinition s_113_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdVVP (also_AdV) (ComplSlash (SlashV2a (sign_V2)) (UsePron (they_Pron))))))).\nDefinition s_113_4_h := s_111_4_h.\nDefinition s_114_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (mary_PN)) (ComplSlash (SlashV2a (use_V2)) (DetCN (DetQuant (PossPron (sheRefl_Pron)) (NumSg)) (UseN (workstation_N))))))).\nDefinition s_114_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (GenNP (UsePN (mary_PN))) (NumSg)) (UseN (workstation_N))) (PassV2s (use_V2))))).\nDefinition s_115_1_p := s_114_1_p.\nDefinition s_115_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mary_PN)) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (workstation_N))))))).\nDefinition s_116_1_p := s_114_1_p.\nDefinition s_116_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mary_PN)) (UseComp (CompAP (PositA (female_A))))))).\nDefinition s_117_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (every_Det) (UseN (student_N))) (ComplSlash (SlashV2a (use_V2)) (DetCN (DetQuant (PossPron (sheRefl_Pron)) (NumSg)) (UseN (workstation_N))))))).\nDefinition s_117_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mary_PN)) (UseComp (CompCN (UseN (student_N))))))).\nDefinition s_117_4_h := s_114_1_p.\nDefinition s_118_1_p := s_117_1_p.\nDefinition s_118_2_p := s_117_2_p.\nDefinition s_118_4_h := s_115_3_h.\nDefinition s_119_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (no_Quant) (NumSg)) (UseN (student_N))) (ComplSlash (SlashV2a (use_V2)) (DetCN (DetQuant (PossPron (sheRefl_Pron)) (NumSg)) (UseN (workstation_N))))))).\nDefinition s_119_2_p := s_117_2_p.\nDefinition s_119_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (mary_PN)) (ComplSlash (SlashV2a (use_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (workstation_N))))))).\nDefinition s_120_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (attend_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (meeting_N))))))).\nDefinition s_120_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePron (she_Pron)) (ComplSlash (SlashV2a (chair_V2)) (UsePron (it_Pron)))))).\nDefinition s_120_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (chair_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (meeting_N))))))).\nDefinition s_121_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (deliver_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))) (PrepNP (to_Prep) (UsePN (itel_PN))))))).\nDefinition s_121_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePron (she_Pron)) (AdVVP (also_AdV) (ComplSlash (Slash2V3 (deliver_V3) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (invoice_N)))) (UsePron (they_Pron))))))).\nDefinition s_121_3_p := (PSentence (and_PConj) (UseCl (Past) (PPos) (PredVP (UsePron (she_Pron)) (ComplSlash (Slash2V3 (deliver_V3) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (project_proposal_N)))) (UsePron (they_Pron)))))).\nDefinition s_121_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (deliver_V2)) (ConjNP3 (and_Conj) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N))) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (invoice_N))) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (project_proposal_N))))) (PrepNP (to_Prep) (UsePN (itel_PN))))))).\nDefinition s_122_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (UseN (committee_N))) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (chairman_N))))))).\nDefinition s_122_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePron (he_Pron)) (AdvVP (PassV2s (appoint_V2)) (PrepNP (by8agent_Prep) (DetCN (DetQuant (PossPron (it_Pron)) (NumPl)) (UseN (member_N)))))))).\nDefinition s_122_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (UseN (committee_N))) (ComplSlash (SlashV2a (have_V2)) (AdvNP (PPartNP (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (chairman_N))) (appoint_V2)) (PrepNP (by8agent_Prep) (DetCN (DetQuant (IndefArt) (NumPl)) (AdvCN (UseN (member_N)) (PrepNP (possess_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (committee_N)))))))))))).\nDefinition s_123_1_p := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (send_V2)) (PredetNP (most_of_Predet) (DetCN (DetQuant (DefArt) (NumPl)) (RelCN (UseN (report_N)) (UseRCl (Present) (PPos) (EmptyRelSlash (SlashVP (UsePN (smith_PN)) (SlashV2a (need_V2)))))))))))).\nDefinition s_123_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePron (they_Pron)) (UseComp (CompAdv (PrepNP (on_Prep) (DetCN (DetQuant (PossPron (she_Pron)) (NumSg)) (UseN (desk_N))))))))).\nDefinition s_123_4_h := (Sentence (UseCl (Present) (PPos) (ExistNP (AdvNP (DetCN (somePl_Det) (AdvCN (UseN (report_N)) (PrepNP (from_Prep) (UsePN (itel_PN))))) (PrepNP (on_Prep) (DetCN (DetQuant (GenNP (UsePN (smith_PN))) (NumSg)) (UseN (desk_N)))))))).\nDefinition s_124_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (AdvNP (DetNP (DetQuant (IndefArt) (NumCard (NumNumeral (N_two))))) (PrepNP (out_of_Prep) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_ten)))) (UseN (machine_N))))) (UseComp (CompAP (PositA (missing_A))))))).\nDefinition s_124_2_p := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (UsePron (they_Pron)) (PassV2s (remove_V2))))).\nDefinition s_124_4_h := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (UseN (machine_N))) (PassV2s (remove_V2))))).\nDefinition s_125_1_p := s_124_1_p.\nDefinition s_125_2_p := s_124_2_p.\nDefinition s_125_4_h := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_eight)))) (UseN (machine_N))) (PassV2s (remove_V2))))).\nDefinition s_126_1_p := s_124_1_p.\nDefinition s_126_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePron (they_Pron)) (AdvVP (AdVVP (all_AdV) (UseComp (CompAdv (here_Adv)))) (yesterday_Adv))))).\nDefinition s_126_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_ten)))) (UseN (machine_N))) (AdvVP (UseComp (CompAdv (here_Adv))) (yesterday_Adv))))).\nDefinition s_127_1_p := (Sentence (ConjS2 (comma_and_Conj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (take_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (machine_N)))) (on_tuesday_Adv)))) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (ComplSlash (SlashV2a (take_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (machine_N)))) (on_wednesday_Adv)))))).\nDefinition s_127_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePron (they_Pron)) (ComplSlash (Slash3V3 (put_in_V3) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (lobby_N)))) (UsePron (they_Pron)))))).\nDefinition s_127_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (UsePN (smith_PN)) (UsePN (jones_PN))) (ComplSlash (Slash3V3 (put_in_V3) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (lobby_N)))) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (UseN (machine_N))))))).\nDefinition s_128_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (UsePN (john_PN)) (DetCN (DetQuant (PossPron (he_Pron)) (NumPl)) (UseN (colleague_N)))) (AdvVP (UseV (go8walk_V)) (PrepNP (to_Prep) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (meeting_N)))))))).\nDefinition s_128_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePron (they_Pron)) (ComplSlash (SlashV2a (hate_V2)) (UsePron (it_Pron)))))).\nDefinition s_128_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (GenNP (UsePN (john_PN))) (NumPl)) (UseN (colleague_N))) (ComplSlash (SlashV2a (hate_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))).\nDefinition s_129_1_p := s_128_1_p.\nDefinition s_129_2_p := s_128_2_p.\nDefinition s_129_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (hate_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))).\nDefinition s_130_1_p := s_128_1_p.\nDefinition s_130_2_p := s_128_2_p.\nDefinition s_130_4_h := s_129_4_h.\nDefinition s_131_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (each_Det) (UseN (department_N))) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (dedicated_A)) (UseN (line_N)))))))).\nDefinition s_131_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePron (they_Pron)) (ComplSlash (Slash3V3 (rent_from_V3) (UsePN (bt_PN))) (UsePron (they_Pron)))))).\nDefinition s_131_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (UseN (department_N))) (ComplSlash (Slash3V3 (rent_from_V3) (UsePN (bt_PN))) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (line_N))))))).\nDefinition s_132_1_p := s_131_1_p.\nDefinition s_132_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (sales_department_N))) (ComplSlash (Slash3V3 (rent_from_V3) (UsePN (bt_PN))) (UsePron (it_Pron)))))).\nDefinition s_132_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (sales_department_N))) (ComplSlash (Slash3V3 (rent_from_V3) (UsePN (bt_PN))) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (line_N))))))).\nDefinition s_133_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (gfi_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (several_Det) (UseN (computer_N))))))).\nDefinition s_133_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (maintain_V2)) (UsePron (they_Pron)))))).\nDefinition s_133_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (maintain_V2)) (PredetNP (all_Predet) (DetCN (DetQuant (DefArt) (NumPl)) (RelCN (UseN (computer_N)) (UseRCl (Present) (PPos) (RelSlash (that_RP) (SlashVP (UsePN (gfi_PN)) (SlashV2a (own_V2)))))))))))).\nDefinition s_134_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (RelCN (UseN (customer_N)) (UseRCl (Present) (PPos) (RelVP (IdRP) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (computer_N)))))))) (AdvVP (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (service_contract_N)))) (PrepNP (for_Prep) (UsePron (it_Pron))))))).\nDefinition s_134_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mfi_PN)) (UseComp (CompCN (RelCN (UseN (customer_N)) (UseRCl (Present) (PPos) (RelVP (that_RP) (ComplSlash (SlashV2a (own_V2)) (PredetNP (exactly_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_one)))) (UseN (computer_N))))))))))))).\nDefinition s_134_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mfi_PN)) (AdvVP (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (service_contract_N)))) (PrepNP (for_Prep) (PredetNP (all_Predet) (DetCN (DetQuant (PossPron (itRefl_Pron)) (NumPl)) (UseN (computer_N))))))))).\nDefinition s_135_1_p := s_134_1_p.\nDefinition s_135_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mfi_PN)) (UseComp (CompCN (RelCN (UseN (customer_N)) (UseRCl (Present) (PPos) (RelVP (that_RP) (ComplSlash (SlashV2a (own_V2)) (DetCN (several_Det) (UseN (computer_N)))))))))))).\nDefinition s_135_4_h := s_134_4_h.\nDefinition s_136_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (every_Det) (RelCN (UseN (executive_N)) (UseRCl (Past) (PPos) (RelVP (IdRP) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (laptop_computer_N)))))))) (ComplSlash (SlashV2V (bring_V2V) (AdvVP (ComplSlash (SlashV2a (take_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (note_N)))) (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N)))))) (UsePron (it_Pron)))))).\nDefinition s_136_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (smith_PN)) (UseComp (CompCN (RelCN (UseN (executive_N)) (UseRCl (Present) (PPos) (RelVP (IdRP) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_five)))) (AdjCN (PositA (different_A)) (UseN (laptop_computer_N))))))))))))).\nDefinition s_136_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (take_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_five)))) (UseN (laptop_computer_N)))) (PrepNP (to_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N)))))))).\nDefinition s_137_1_p := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_100)))) (UseN (company_N)))))).\nDefinition s_137_2_p := (Sentence (PredVPS (UsePN (icm_PN)) (ConjVPS2 (and_Conj) (Present) (PPos) (UseComp (CompNP (AdvNP (DetNP (DetQuant (IndefArt) (NumCard (NumNumeral (N_one))))) (PrepNP (part_Prep) (DetCN (DetQuant (DefArt) (NumPl)) (UseN (company_N))))))) (Present) (PPos) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_150)))) (UseN (computer_N))))))).\nDefinition s_137_3_p := (Sentence (UseCl (Present) (UncNeg) (PredVP (UsePron (it_Pron)) (AdvVP (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (service_contract_N)))) (PrepNP (for_Prep) (AdvNP (DetNP (anySg_Det)) (PrepNP (part_Prep) (DetCN (DetQuant (PossPron (itRefl_Pron)) (NumPl)) (UseN (computer_N)))))))))).\nDefinition s_137_4_p := (Sentence (UseCl (Present) (PPos) (PredVP (AdvNP (DetNP (each_Det)) (PrepNP (part_Prep) (DetCN (DetQuant (the_other_Q) (NumCard (NumNumeral (N_99)))) (UseN (company_N))))) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_one)))) (UseN (computer_N))))))).\nDefinition s_137_5_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePron (they_Pron)) (AdvVP (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (service_contract_N)))) (PrepNP (for_Prep) (UsePron (they_Pron))))))).\nDefinition s_137_7_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (most_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (UseN (company_N)) (UseRCl (Present) (PPos) (RelVP (that_RP) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (computer_N))))))))) (AdvVP (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (service_contract_N)))) (PrepNP (for_Prep) (UsePron (it_Pron))))))).\nDefinition s_138_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (UseN (report_N))) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (cover_page_N))))))).\nDefinition s_138_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (r95103_PN)) (UseComp (CompCN (UseN (report_N))))))).\nDefinition s_138_3_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (cover_page_N))))))).\nDefinition s_138_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (AdvCN (UseN (cover_page_N)) (PrepNP (possess_Prep) (UsePN (r95103_PN))))))))).\nDefinition s_139_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (company_director_N))) (ReflVP (Slash3V3 (award_V3) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (large_A)) (UseN (payrise_N))))))))).\nDefinition s_139_3_h := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (company_director_N))) (ComplSlash (SlashV2a (award_and_be_awarded_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (payrise_N))))))).\nDefinition s_140_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplVSa (say_VS) (UseCl (PastPerfect) (PPos) (PredVP (UsePN (bill_PN)) (ReflVP (SlashV2a (hurt_V2))))))))).\nDefinition s_140_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplVSa (say_VS) (UseCl (PastPerfect) (PPos) (PredVP (UsePN (bill_PN)) (PassV2s (hurt_V2)))))))).\nDefinition s_141_1_p := s_140_1_p.\nDefinition s_141_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePron (someone_Pron)) (ComplVSa (say_VS) (UseCl (PastPerfect) (PPos) (PredVP (UsePN (john_PN)) (PassV2s (hurt_V2)))))))).\nDefinition s_142_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN)))))).\nDefinition s_142_2_p := (Sentence (UseCl (Past) (PPos) (SoDoI (UsePN (bill_PN))))).\nDefinition s_142_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN)))))).\nDefinition s_143_1_p := s_142_1_p.\nDefinition s_143_2_p := s_142_2_p.\nDefinition s_143_3_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (AdvVP (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN))) (at_four_oclock_Adv))))).\nDefinition s_143_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN))) (at_four_oclock_Adv))))).\nDefinition s_144_1_p := s_143_3_p.\nDefinition s_144_2_p := s_142_2_p.\nDefinition s_144_4_h := s_143_5_h.\nDefinition s_145_1_p := s_143_3_p.\nDefinition s_145_2_p := (PSentence (and_PConj) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (ComplVV (do_VV) (elliptic_VP)) (at_five_oclock_Adv))))).\nDefinition s_145_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN))) (at_five_oclock_Adv))))).\nDefinition s_146_1_p := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN)))))).\nDefinition s_146_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bill_PN)) (ProgrVPa (ComplVV (going_to_VV) (elliptic_VP)))))).\nDefinition s_146_4_h := (Sentence (UseCl (Future) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN)))))).\nDefinition s_147_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (AdvVP (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN))) (on_monday_Adv))))).\nDefinition s_147_2_p := (Sentence (UseCl (Past) (PNeg) (PredVP (UsePN (bill_PN)) (elliptic_VP)))).\nDefinition s_147_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN))) (on_monday_Adv))))).\nDefinition s_148_1_p := (Question (UseQCl (PresentPerfect) (PPos) (QuestCl (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN))))))).\nDefinition s_148_2_p := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (bill_PN)) (elliptic_VP)))).\nDefinition s_148_4_h := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN)))))).\nDefinition s_149_1_p := s_146_1_p.\nDefinition s_149_2_p := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (UseN (student_N))) (AdvVP (elliptic_VP) (too_Adv))))).\nDefinition s_149_4_h := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (UseN (student_N))) (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN)))))).\nDefinition s_150_1_p := (Sentence (ConjS2 (comma_and_Conj) (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (AdvVP (AdvVP (UseV (go8travel_V)) (PrepNP (to_Prep) (UsePN (paris_PN)))) (PrepNP (by8means_Prep) (MassNP (UseN (car_N))))))) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (elliptic_VP) (PrepNP (by8means_Prep) (MassNP (UseN (train_N))))))))).\nDefinition s_150_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (AdvVP (UseV (go8travel_V)) (PrepNP (to_Prep) (UsePN (paris_PN)))) (PrepNP (by8means_Prep) (MassNP (UseN (train_N)))))))).\nDefinition s_151_1_p := (Sentence (ConjS2 (comma_and_Conj) (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (AdvVP (AdvVP (UseV (go8travel_V)) (PrepNP (to_Prep) (UsePN (paris_PN)))) (PrepNP (by8means_Prep) (MassNP (UseN (car_N))))))) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (AdvVP (elliptic_VP) (PrepNP (by8means_Prep) (MassNP (UseN (train_N))))) (PrepNP (to_Prep) (UsePN (berlin_PN)))))))).\nDefinition s_151_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (AdvVP (UseV (go8travel_V)) (PrepNP (to_Prep) (UsePN (berlin_PN)))) (PrepNP (by8means_Prep) (MassNP (UseN (train_N)))))))).\nDefinition s_152_1_p := (Sentence (ConjS2 (comma_and_Conj) (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (AdvVP (AdvVP (UseV (go8travel_V)) (PrepNP (to_Prep) (UsePN (paris_PN)))) (PrepNP (by8means_Prep) (MassNP (UseN (car_N))))))) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (elliptic_VP) (PrepNP (to_Prep) (UsePN (berlin_PN)))))))).\nDefinition s_152_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (AdvVP (UseV (go8travel_V)) (PrepNP (to_Prep) (UsePN (berlin_PN)))) (PrepNP (by8means_Prep) (MassNP (UseN (car_N)))))))).\nDefinition s_153_1_p := (Sentence (ConjS2 (comma_and_Conj) (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (AdvVP (AdvVP (ProgrVPa (UseV (go8travel_V))) (PrepNP (to_Prep) (UsePN (paris_PN)))) (PrepNP (by8means_Prep) (MassNP (UseN (car_N))))))) (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (UseN (student_N))) (AdvVP (elliptic_VP) (PrepNP (by8means_Prep) (MassNP (UseN (train_N))))))))).\nDefinition s_153_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (UseN (student_N))) (AdvVP (AdvVP (ProgrVPa (UseV (go8travel_V))) (PrepNP (to_Prep) (UsePN (paris_PN)))) (PrepNP (by8means_Prep) (MassNP (UseN (train_N)))))))).\nDefinition s_154_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (AdvVP (AdvVP (UseV (go8travel_V)) (PrepNP (to_Prep) (UsePN (paris_PN)))) (PrepNP (by8means_Prep) (MassNP (UseN (car_N)))))))).\nDefinition s_154_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (elliptic_VP) (PrepNP (by8means_Prep) (MassNP (UseN (train_N)))))))).\nDefinition s_154_4_h := s_150_3_h.\nDefinition s_155_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (car_N))))))).\nDefinition s_155_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (ComplSlash (SlashV2a (own_V2)) (DetNP (DetQuant (IndefArt) (NumSg)))) (too_Adv))))).\nDefinition s_155_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (car_N))))))).\nDefinition s_156_1_p := s_155_1_p.\nDefinition s_156_2_p := s_155_2_p.\nDefinition s_156_4_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumSg)) (RelCN (UseN (car_N)) (UseRCl (Present) (PPos) (RelSlash (that_RP) (SlashVP (ConjNP2 (and_Conj) (UsePN (john_PN)) (UsePN (bill_PN))) (SlashV2a (own_V2)))))))))).\nDefinition s_157_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (red_A)) (UseN (car_N)))))))).\nDefinition s_157_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (blue_A)) (UseN (one_N)))))))).\nDefinition s_157_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (blue_A)) (UseN (car_N)))))))).\nDefinition s_158_1_p := s_157_1_p.\nDefinition s_158_2_p := s_157_2_p.\nDefinition s_158_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (red_A)) (UseN (car_N)))))))).\nDefinition s_159_1_p := s_157_1_p.\nDefinition s_159_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (fast_A)) (UseN (one_N)))))))).\nDefinition s_159_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (fast_A)) (UseN (car_N)))))))).\nDefinition s_160_1_p := s_157_1_p.\nDefinition s_160_2_p := s_159_2_p.\nDefinition s_160_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (fast_A)) (AdjCN (PositA (red_A)) (UseN (car_N))))))))).\nDefinition s_161_1_p := s_157_1_p.\nDefinition s_161_2_p := s_159_2_p.\nDefinition s_161_4_h := s_160_4_h.\nDefinition s_162_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (fast_A)) (AdjCN (PositA (red_A)) (UseN (car_N))))))))).\nDefinition s_162_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (slow_A)) (UseN (one_N)))))))).\nDefinition s_162_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (slow_A)) (AdjCN (PositA (red_A)) (UseN (car_N))))))))).\nDefinition s_163_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (have_V2)) (PPartNP (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (UseN (paper_N))) (accept_V2)))))).\nDefinition s_163_2_p := (Sentence (UseCl (Present) (PNeg) (PredVP (UsePN (bill_PN)) (ComplVQ (know_VQ) (UseQCl (Past) (PPos) (QuestIAdv (why_IAdv) (elliptic_Cl))))))).\nDefinition s_163_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (bill_PN)) (ComplVQ (know_VQ) (UseQCl (Past) (PPos) (QuestIAdv (why_IAdv) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (have_V2)) (PPartNP (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (UseN (paper_N))) (accept_V2)))))))))).\nDefinition s_164_1_p := s_142_1_p.\nDefinition s_164_2_p := (PAdverbial (and_PConj) (PrepNP (to_Prep) (UsePN (sue_PN)))).\nDefinition s_164_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (sue_PN)))))).\nDefinition s_165_1_p := s_142_1_p.\nDefinition s_165_2_p := (Adverbial (on_friday_Adv)).\nDefinition s_165_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (AdvVP (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN))) (on_friday_Adv))))).\nDefinition s_166_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (AdvVP (ComplSlash (SlashV2a (speak_to_V2)) (UsePN (mary_PN))) (on_thursday_Adv))))).\nDefinition s_166_2_p := (PAdverbial (and_PConj) (on_friday_Adv)).\nDefinition s_166_4_h := s_165_4_h.\nDefinition s_167_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_twenty)))) (UseN (man_N))) (ComplSlash (SlashV2a (work_in_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (sales_department_N))))))).\nDefinition s_167_2_p := (PNounphrase (but_PConj) (PredetNP (only_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_one)))) (UseN (woman_N))))).\nDefinition s_167_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (UseN (woman_N))) (ComplSlash (SlashV2a (work_in_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (sales_department_N))))))).\nDefinition s_168_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_five)))) (UseN (man_N))) (AdvVP (UseV (work_V)) (part_time_Adv))))).\nDefinition s_168_2_p := (PNounphrase (and_PConj) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_fortyfive)))) (UseN (woman_N)))).\nDefinition s_168_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_fortyfive)))) (UseN (woman_N))) (AdvVP (UseV (work_V)) (part_time_Adv))))).\nDefinition s_169_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (AdvVP (ComplSlash (SlashV2a (find_V2)) (UsePN (mary_PN))) (PrepNP (before_Prep) (UsePN (bill_PN))))))).\nDefinition s_169_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (AdvVP (ComplSlash (SlashV2a (find_V2)) (UsePN (mary_PN))) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (find_V2)) (UsePN (mary_PN)))))))))).\nDefinition s_170_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (find_V2)) (AdvNP (UsePN (mary_PN)) (PrepNP (before_Prep) (UsePN (bill_PN)))))))).\nDefinition s_170_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (AdvVP (ComplSlash (SlashV2a (find_V2)) (UsePN (mary_PN))) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (find_V2)) (UsePN (bill_PN)))))))))).\nDefinition s_171_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (ComplVV (want_VV) (ComplVQ (know_VQ) (UseQCl (Present) (PPos) (QuestVP (IdetCN (how8many_IDet) (UseN (man_N))) (AdvVP (UseV (work_V)) (part_time_Adv))))))))).\nDefinition s_171_2_p := (PNounphrase (and_PConj) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (woman_N)))).\nDefinition s_171_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (ComplVV (want_VV) (ComplVQ (know_VQ) (UseQCl (Present) (PPos) (QuestVP (IdetCN (how8many_IDet) (UseN (woman_N))) (AdvVP (UseV (work_V)) (part_time_Adv))))))))).\nDefinition s_172_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (ComplVV (want_VV) (ComplVQ (know_VQ) (ConjQS2 (comma_and_Conj) (UseQCl (Present) (PPos) (QuestVP (IdetCN (how8many_IDet) (UseN (man_N))) (AdvVP (UseV (work_V)) (part_time_Adv)))) (UseQCl (Present) (PPos) (QuestVP (IdetCN (IdetQuant (which_IQuant) (NumPl)) (elliptic_CN)) (elliptic_VP))))))))).\nDefinition s_172_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (ComplVV (want_VV) (ComplVQ (know_VQ) (UseQCl (Present) (PPos) (QuestVP (IdetCN (IdetQuant (which_IQuant) (NumPl)) (UseN (man_N))) (AdvVP (UseV (work_V)) (part_time_Adv))))))))).\nDefinition s_173_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (speak_to_V2)) (RelNPa (UsePron (everyone_Pron)) (UseRCl (Past) (PPos) (StrandRelSlash (that_RP) (SlashVP (UsePN (john_PN)) (SlashVV (do_VV) (elliptic_VPSlash)))))))))).\nDefinition s_173_2_p := s_142_1_p.\nDefinition s_173_4_h := s_142_4_h.\nDefinition s_174_1_p := s_173_1_p.\nDefinition s_174_2_p := s_142_4_h.\nDefinition s_174_4_h := s_142_1_p.\nDefinition s_175_1_p := (Sentence (ConjS2 (comma_and_Conj) (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplVSa (say_VS) (UseCl (Past) (PPos) (PredVP (UsePN (mary_PN)) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N))))))))) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (ComplVV (do_VV) (elliptic_VP)) (too_Adv)))))).\nDefinition s_175_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (ComplVSa (say_VS) (UseCl (Past) (PPos) (PredVP (UsePN (mary_PN)) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))))))))).\nDefinition s_176_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplVSa (say_VS) (ConjS2 (comma_and_Conj) (UseCl (Past) (PPos) (PredVP (UsePN (mary_PN)) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))))) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (ComplVV (do_VV) (elliptic_VP)) (too_Adv))))))))).\nDefinition s_176_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplVSa (say_VS) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))))))))).\nDefinition s_177_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplVS (say_VS) (PredVPS (UsePN (mary_PN)) (ConjVPS2 (comma_and_Conj) (Past) (PPos) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))) (Past) (PPos) (ComplVS (say_VS) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (ComplVV (do_VV) (elliptic_VP)) (too_Adv))))))))))).\nDefinition s_177_3_h := s_175_3_h.\nDefinition s_178_1_p := (Sentence (ConjS2 (comma_and_Conj) (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))))) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (ComplVSa (say_VS) (UseCl (Past) (PPos) (PredVP (UsePN (peter_PN)) (ComplVV (do_VV) (elliptic_VP))))) (too_Adv)))))).\nDefinition s_178_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (ComplVSa (say_VS) (UseCl (Past) (PPos) (PredVP (UsePN (peter_PN)) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))))))))).\nDefinition s_179_1_p := (Sentence (ConjS2 (if_comma_then_Conj) (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))))) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (AdvVP (ComplVV (do_VV) (elliptic_VP)) (too_Adv)))))).\nDefinition s_179_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N))))))).\nDefinition s_179_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N))))))).\nDefinition s_180_1_p := (Sentence (ConjS2 (comma_and_Conj) (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplVV (want_VV) (ComplSlash (SlashV2a (buy_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (car_N))))))) (UseCl (Past) (PPos) (PredVP (UsePron (he_Pron)) (ComplVV (do_VV) (elliptic_VP)))))).\nDefinition s_180_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (buy_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (car_N))))))).\nDefinition s_181_1_p := (Sentence (ConjS2 (comma_and_Conj) (UseCl (Past) (PPos) (PredVP (UsePN (john_PN)) (ComplVV (need_VV) (ComplSlash (SlashV2a (buy_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (car_N))))))) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (ComplVV (do_VV) (elliptic_VP)))))).\nDefinition s_181_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2a (buy_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (car_N))))))).\nDefinition s_182_1_p := (Sentence (ConjS2 (and_Conj) (UseCl (Present) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (represent_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (UseN (company_N)))))) (UseCl (Present) (PPos) (SoDoI (UsePN (jones_PN)))))).\nDefinition s_182_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (represent_V2)) (DetCN (DetQuant (GenNP (UsePN (jones_PN))) (NumSg)) (UseN (company_N))))))).\nDefinition s_183_1_p := s_182_1_p.\nDefinition s_183_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (represent_V2)) (DetCN (DetQuant (GenNP (UsePN (smith_PN))) (NumSg)) (UseN (company_N))))))).\nDefinition s_184_1_p := s_182_1_p.\nDefinition s_184_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (represent_V2)) (DetCN (DetQuant (GenNP (UsePN (jones_PN))) (NumSg)) (UseN (company_N))))))).\nDefinition s_185_1_p := (Sentence (ConjS2 (and_Conj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplVSa (claim_VS) (UseCl (PastPerfect) (PPos) (PredVP (UsePron (he_Pron)) (ComplSlash (SlashV2a (cost_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (UseN (proposal_N))))))))) (UseCl (Past) (PPos) (SoDoI (UsePN (jones_PN)))))).\nDefinition s_185_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplVSa (claim_VS) (UseCl (PastPerfect) (PPos) (PredVP (UsePron (he_Pron)) (ComplSlash (SlashV2a (cost_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (AdjCN (PositA (own_A)) (UseN (proposal_N))))))))))).\nDefinition s_186_1_p := s_185_1_p.\nDefinition s_186_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplVSa (claim_VS) (UseCl (PastPerfect) (PPos) (PredVP (UsePron (he_Pron)) (ComplSlash (SlashV2a (cost_V2)) (DetCN (DetQuant (GenNP (UsePN (smith_PN))) (NumSg)) (UseN (proposal_N)))))))))).\nDefinition s_187_1_p := s_185_1_p.\nDefinition s_187_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplVSa (claim_VS) (UseCl (PastPerfect) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (cost_V2)) (DetCN (DetQuant (GenNP (UsePN (smith_PN))) (NumSg)) (UseN (proposal_N)))))))))).\nDefinition s_188_1_p := s_185_1_p.\nDefinition s_188_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplVSa (claim_VS) (UseCl (PastPerfect) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (cost_V2)) (DetCN (DetQuant (GenNP (UsePN (jones_PN))) (NumSg)) (UseN (proposal_N)))))))))).\nDefinition s_189_1_p := (Sentence (ConjS2 (and_Conj) (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (UseComp (CompCN (UseN (man_N)))))) (UseCl (Present) (PPos) (PredVP (UsePN (mary_PN)) (UseComp (CompCN (UseN (woman_N)))))))).\nDefinition s_189_2_p := (Sentence (ConjS2 (and_Conj) (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (represent_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (UseN (company_N)))))) (UseCl (Present) (PPos) (SoDoI (UsePN (mary_PN)))))).\nDefinition s_189_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mary_PN)) (ComplSlash (SlashV2a (represent_V2)) (DetCN (DetQuant (PossPron (sheRefl_Pron)) (NumSg)) (AdjCN (PositA (own_A)) (UseN (company_N)))))))).\nDefinition s_190_1_p := s_189_1_p.\nDefinition s_190_2_p := s_189_2_p.\nDefinition s_190_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mary_PN)) (ComplSlash (SlashV2a (represent_V2)) (DetCN (DetQuant (GenNP (UsePN (john_PN))) (NumSg)) (UseN (company_N))))))).\nDefinition s_191_1_p := (Sentence (ConjS2 (comma_and_Conj) (UseCl (Past) (PPos) (PredVP (UsePN (bill_PN)) (ComplSlash (SlashV2S (suggest_to_V2S) (UseCl (Past) (PPos) (PredVP (UsePron (they_Pron)) (ComplVV (shall_VV) (AdvVP (AdvVP (UseV (go8walk_V)) (PrepNP (to_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))) (together_Adv)))))) (DetCN (DetQuant (GenNP (UsePN (frank_PN))) (NumSg)) (UseN (boss_N)))))) (UseCl (Past) (PPos) (PredVP (UsePN (carl_PN)) (AdvVP (elliptic_VP) (PrepNP (to_Prep) (DetCN (DetQuant (GenNP (UsePN (alan_PN))) (NumSg)) (UseN (wife_N))))))))).\nDefinition s_191_3_h := (Sentence (ExtAdvS (SubjS (if_Subj) (UseCl (Past) (PPos) (ImpersCl (PassVPSlash (SlashV2S (suggest_to_V2S) (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (UsePN (bill_PN)) (UsePN (frank_PN))) (ComplVV (shall_VV) (AdvVP (UseV (go8walk_V)) (together_Adv)))))))))) (UseCl (Past) (PPos) (ImpersCl (PassVPSlash (SlashV2S (suggest_to_V2S) (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (UsePN (carl_PN)) (UsePN (alan_PN))) (ComplVV (shall_VV) (AdvVP (UseV (go8walk_V)) (together_Adv))))))))))).\nDefinition s_192_1_p := s_191_1_p.\nDefinition s_192_3_h := (Sentence (ExtAdvS (SubjS (if_Subj) (UseCl (Past) (PPos) (ImpersCl (PassVPSlash (SlashV2S (suggest_to_V2S) (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (UsePN (bill_PN)) (UsePN (frank_PN))) (ComplVV (shall_VV) (AdvVP (UseV (go8walk_V)) (together_Adv)))))))))) (UseCl (Past) (PPos) (ImpersCl (PassVPSlash (SlashV2S (suggest_to_V2S) (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (UsePN (carl_PN)) (DetCN (DetQuant (GenNP (UsePN (alan_PN))) (NumSg)) (UseN (wife_N)))) (ComplVV (shall_VV) (AdvVP (UseV (go8walk_V)) (together_Adv))))))))))).\nDefinition s_193_1_p := s_191_1_p.\nDefinition s_193_3_h := (Sentence (ExtAdvS (SubjS (if_Subj) (UseCl (Past) (PPos) (ImpersCl (PassVPSlash (SlashV2S (suggest_to_V2S) (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (UsePN (bill_PN)) (DetCN (DetQuant (GenNP (UsePN (frank_PN))) (NumSg)) (UseN (boss_N)))) (ComplVV (shall_VV) (AdvVP (UseV (go8walk_V)) (together_Adv)))))))))) (UseCl (Past) (PPos) (ImpersCl (PassVPSlash (SlashV2S (suggest_to_V2S) (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (UsePN (carl_PN)) (DetCN (DetQuant (GenNP (UsePN (alan_PN))) (NumSg)) (UseN (wife_N)))) (ComplVV (shall_VV) (AdvVP (UseV (go8walk_V)) (together_Adv))))))))))).\nDefinition s_194_1_p := s_191_1_p.\nDefinition s_194_3_h := (Sentence (ExtAdvS (SubjS (if_Subj) (UseCl (Past) (PPos) (ImpersCl (PassVPSlash (SlashV2S (suggest_to_V2S) (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (UsePN (bill_PN)) (DetCN (DetQuant (GenNP (UsePN (frank_PN))) (NumSg)) (UseN (boss_N)))) (ComplVV (shall_VV) (AdvVP (UseV (go8walk_V)) (together_Adv)))))))))) (UseCl (Past) (PPos) (ImpersCl (PassVPSlash (SlashV2S (suggest_to_V2S) (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (UsePN (carl_PN)) (UsePN (alan_PN))) (ComplVV (shall_VV) (AdvVP (UseV (go8walk_V)) (together_Adv))))))))))).\nDefinition s_195_1_p := s_191_1_p.\nDefinition s_195_3_h := (Sentence (ExtAdvS (SubjS (if_Subj) (UseCl (Past) (PPos) (ImpersCl (PassVPSlash (SlashV2S (suggest_to_V2S) (UseCl (Past) (PPos) (PredVP (ConjNP3 (and_Conj) (UsePN (bill_PN)) (UsePN (frank_PN)) (DetCN (DetQuant (GenNP (UsePN (frank_PN))) (NumSg)) (UseN (boss_N)))) (ComplVV (shall_VV) (AdvVP (UseV (go8walk_V)) (together_Adv)))))))))) (UseCl (Past) (PPos) (ImpersCl (PassVPSlash (SlashV2S (suggest_to_V2S) (UseCl (Past) (PPos) (PredVP (ConjNP3 (and_Conj) (UsePN (carl_PN)) (UsePN (alan_PN)) (DetCN (DetQuant (GenNP (UsePN (alan_PN))) (NumSg)) (UseN (wife_N)))) (ComplVV (shall_VV) (AdvVP (UseV (go8walk_V)) (together_Adv))))))))))).\nDefinition s_196_1_p := (Sentence (ConjS2 (comma_and_Conj) (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (lawyer_N))) (ComplSlash (SlashV2a (sign_V2)) (DetCN (every_Det) (UseN (report_N)))))) (UseCl (Past) (PPos) (SoDoI (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (auditor_N))))))).\nDefinition s_196_2_p := (PSentence (that_is_PConj) (UseCl (Past) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_one)))) (RelCN (UseN (lawyer_N)) (UseRCl (Past) (PPos) (RelVP (IdRP) (ComplSlash (SlashV2a (sign_V2)) (PredetNP (all_Predet) (DetCN (DetQuant (DefArt) (NumPl)) (UseN (report_N)))))))))))).\nDefinition s_196_4_h := (Sentence (UseCl (Past) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_one)))) (RelCN (UseN (auditor_N)) (UseRCl (Past) (PPos) (RelVP (IdRP) (ComplSlash (SlashV2a (sign_V2)) (PredetNP (all_Predet) (DetCN (DetQuant (DefArt) (NumPl)) (UseN (report_N)))))))))))).\nDefinition s_197_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (genuine_A)) (UseN (diamond_N)))))))).\nDefinition s_197_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (diamond_N))))))).\nDefinition s_198_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (UseComp (CompCN (AdjCN (PositA (former_A)) (UseN (university_student_N)))))))).\nDefinition s_198_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (UseComp (CompCN (UseN (university_student_N))))))).\nDefinition s_199_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (UseComp (CompCN (AdjCN (PositA (successful_A)) (AdjCN (PositA (former_A)) (UseN (university_student_N))))))))).\nDefinition s_199_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (UseComp (CompAP (PositA (successful_A))))))).\nDefinition s_200_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (UseComp (CompCN (AdjCN (PositA (former_A)) (AdjCN (PositA (successful_A)) (UseN (university_student_N))))))))).\nDefinition s_200_3_h := s_199_3_h.\nDefinition s_201_1_p := s_200_1_p.\nDefinition s_201_3_h := s_198_3_h.\nDefinition s_202_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (UseN (mammal_N))) (UseComp (CompCN (UseN (animal_N))))))).\nDefinition s_202_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (every_Det) (AdjCN (PositA (fourlegged_A)) (UseN (mammal_N)))) (UseComp (CompCN (AdjCN (PositA (fourlegged_A)) (UseN (animal_N)))))))).\nDefinition s_203_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (dumbo_PN)) (UseComp (CompCN (AdjCN (PositA (fourlegged_A)) (UseN (animal_N)))))))).\nDefinition s_203_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (dumbo_PN)) (UseComp (CompAP (PositA (fourlegged_A))))))).\nDefinition s_204_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mickey_PN)) (UseComp (CompCN (AdjCN (PositA (small_A)) (UseN (animal_N)))))))).\nDefinition s_204_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mickey_PN)) (UseComp (CompCN (AdjCN (PositA (large_A)) (UseN (animal_N)))))))).\nDefinition s_205_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (dumbo_PN)) (UseComp (CompCN (AdjCN (PositA (large_A)) (UseN (animal_N)))))))).\nDefinition s_205_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (dumbo_PN)) (UseComp (CompCN (AdjCN (PositA (small_A)) (UseN (animal_N)))))))).\nDefinition s_206_1_p := (Sentence (UseCl (Present) (UncNeg) (PredVP (UsePN (fido_PN)) (UseComp (CompCN (AdjCN (PositA (small_A)) (UseN (animal_N)))))))).\nDefinition s_206_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (fido_PN)) (UseComp (CompCN (AdjCN (PositA (large_A)) (UseN (animal_N)))))))).\nDefinition s_207_1_p := (Sentence (UseCl (Present) (UncNeg) (PredVP (UsePN (fido_PN)) (UseComp (CompCN (AdjCN (PositA (large_A)) (UseN (animal_N)))))))).\nDefinition s_207_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (fido_PN)) (UseComp (CompCN (AdjCN (PositA (small_A)) (UseN (animal_N)))))))).\nDefinition s_208_1_p := s_204_1_p.\nDefinition s_208_2_p := s_205_1_p.\nDefinition s_208_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mickey_PN)) (UseComp (CompAP (ComparA (small_A) (UsePN (dumbo_PN)))))))).\nDefinition s_209_1_p := s_204_1_p.\nDefinition s_209_2_p := s_205_1_p.\nDefinition s_209_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mickey_PN)) (UseComp (CompAP (ComparA (large_A) (UsePN (dumbo_PN)))))))).\nDefinition s_210_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (mouse_N)))) (UseComp (CompCN (AdjCN (PositA (small_A)) (UseN (animal_N)))))))).\nDefinition s_210_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mickey_PN)) (UseComp (CompCN (AdjCN (PositA (large_A)) (UseN (mouse_N)))))))).\nDefinition s_210_4_h := s_204_3_h.\nDefinition s_211_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (elephant_N)))) (UseComp (CompCN (AdjCN (PositA (large_A)) (UseN (animal_N)))))))).\nDefinition s_211_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (dumbo_PN)) (UseComp (CompCN (AdjCN (PositA (small_A)) (UseN (elephant_N)))))))).\nDefinition s_211_4_h := s_205_3_h.\nDefinition s_212_1_p := s_210_1_p.\nDefinition s_212_2_p := s_211_1_p.\nDefinition s_212_3_p := s_210_2_p.\nDefinition s_212_4_p := s_211_2_p.\nDefinition s_212_6_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (dumbo_PN)) (UseComp (CompAP (ComparA (large_A) (UsePN (mickey_PN)))))))).\nDefinition s_213_1_p := s_210_1_p.\nDefinition s_213_2_p := s_210_2_p.\nDefinition s_213_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (mickey_PN)) (UseComp (CompAP (PositA (small_A))))))).\nDefinition s_214_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (legal_A)) (UseN (authority_N))))) (UseComp (CompCN (UseN (law_lecturer_N))))))).\nDefinition s_214_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (law_lecturer_N)))) (UseComp (CompCN (AdjCN (PositA (legal_A)) (UseN (authority_N)))))))).\nDefinition s_214_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (fat_A)) (AdjCN (PositA (legal_A)) (UseN (authority_N)))))) (UseComp (CompCN (AdjCN (PositA (fat_A)) (UseN (law_lecturer_N)))))))).\nDefinition s_215_1_p := s_214_1_p.\nDefinition s_215_2_p := s_214_2_p.\nDefinition s_215_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (competent_A)) (AdjCN (PositA (legal_A)) (UseN (authority_N)))))) (UseComp (CompCN (AdjCN (PositA (competent_A)) (UseN (law_lecturer_N)))))))).\nDefinition s_216_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (UseComp (CompCN (AdvCN (AdjCN (UseComparA_prefix (fat_A)) (UseN (politician_N))) (PrepNP (than_Prep) (UsePN (bill_PN))))))))).\nDefinition s_216_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (UseComp (CompAP (ComparA (fat_A) (UsePN (bill_PN)))))))).\nDefinition s_217_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (UseComp (CompCN (AdvCN (AdjCN (UseComparA_prefix (clever_A)) (UseN (politician_N))) (PrepNP (than_Prep) (UsePN (bill_PN))))))))).\nDefinition s_217_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (john_PN)) (UseComp (CompAP (ComparA (clever_A) (UsePN (bill_PN)))))))).\nDefinition s_218_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (kim_PN)) (UseComp (CompCN (AdjCN (PositA (clever_A)) (UseN (person_N)))))))).\nDefinition s_218_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (kim_PN)) (UseComp (CompAP (PositA (clever_A))))))).\nDefinition s_219_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (kim_PN)) (UseComp (CompCN (AdjCN (PositA (clever_A)) (UseN (politician_N)))))))).\nDefinition s_219_3_h := s_218_3_h.\n\n\nDefinition s_220_1_p := (Sentence (UseCl (Present) (PPos) (PredVP the_pc6082_NP (UseComp (CompAP (ComparA (fast_A) the_itel_xz_NP)))))).\nDefinition s_220_2_p := (Sentence (UseCl (Present) (PPos) (PredVP the_itel_xz_NP (UseComp (CompAP (PositA (fast_A))))))).\nDefinition s_220_4_h := (Sentence (UseCl (Present) (PPos) (PredVP the_pc6082_NP (UseComp (CompAP (PositA (fast_A))))))).\nDefinition s_221_1_p := s_220_1_p.\nDefinition s_221_3_h := s_220_4_h.\nDefinition s_222_1_p := s_220_1_p.\nDefinition s_222_2_p := s_220_4_h.\nDefinition s_222_4_h := s_220_2_p.\nDefinition s_223_1_p := s_220_1_p.\nDefinition s_223_2_p := (Sentence (UseCl (Present) (PPos) (PredVP the_pc6082_NP (UseComp (CompAP (PositA (slow_A))))))).\nDefinition s_223_4_h := s_220_2_p.\nDefinition s_224_1_p := (Sentence (UseCl (Present) (PPos) (PredVP the_pc6082_NP (UseComp (CompAP (ComparAsAs (fast_A) the_itel_xz_NP)))))).\nDefinition s_224_2_p := s_220_2_p.\nDefinition s_224_4_h := s_220_4_h.\nDefinition s_225_1_p := s_224_1_p.\nDefinition s_225_3_h := s_220_4_h.\nDefinition s_226_1_p := s_224_1_p.\nDefinition s_226_2_p := s_220_4_h.\nDefinition s_226_4_h := s_220_2_p.\nDefinition s_227_1_p := s_224_1_p.\nDefinition s_227_2_p := s_223_2_p.\nDefinition s_227_4_h := s_220_2_p.\nDefinition s_228_1_p := s_224_1_p.\nDefinition s_228_3_h := s_220_1_p.\nDefinition s_229_1_p := s_224_1_p.\nDefinition s_229_3_h := (Sentence (UseCl (Present) (PPos) (PredVP the_pc6082_NP (UseComp (CompAP (ComparA (slow_A) the_itel_xz_NP)))))).\nDefinition s_230_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (AdvCN (AdjCN (UseComparA_prefix (many_A)) (UseN (order_N))) (SubjS (than_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (apcom_PN)) (ComplVV (do_VV) (elliptic_VP))))))))))).\nDefinition s_230_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (win_V2)) (DetCN (somePl_Det) (UseN (order_N))))))).\nDefinition s_231_1_p := s_230_1_p.\nDefinition s_231_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (apcom_PN)) (ComplSlash (SlashV2a (win_V2)) (DetCN (somePl_Det) (UseN (order_N))))))).\nDefinition s_232_1_p := s_230_1_p.\nDefinition s_232_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (apcom_PN)) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_ten)))) (UseN (order_N))))))).\nDefinition s_232_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (win_V2)) (PredetNP (at_least_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_eleven)))) (UseN (order_N)))))))).\nDefinition s_233_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (AdvCN (AdjCN (UseComparA_prefix (many_A)) (UseN (order_N))) (PrepNP (than_Prep) (UsePN (apcom_PN))))))))).\nDefinition s_233_3_h := s_230_3_h.\nDefinition s_234_1_p := s_233_1_p.\nDefinition s_234_3_h := s_231_3_h.\nDefinition s_235_1_p := s_233_1_p.\nDefinition s_235_2_p := s_232_2_p.\nDefinition s_235_4_h := s_232_4_h.\nDefinition s_236_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (AdvCN (AdjCN (UseComparA_prefix (many_A)) (UseN (order_N))) (PrepNP (than_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (apcom_contract_N)))))))))).\nDefinition s_236_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (apcom_contract_N))))))).\nDefinition s_237_1_p := s_236_1_p.\nDefinition s_237_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (IndefArt) (NumCard (AdNum (more_than_AdN) (NumNumeral (N_one))))) (UseN (order_N))))))).\nDefinition s_238_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (win_V2)) (DetCN (twice_as_many_Det) (AdvCN (UseN (order_N)) (PrepNP (than_Prep) (UsePN (apcom_PN))))))))).\nDefinition s_238_2_p := s_232_2_p.\nDefinition s_238_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_twenty)))) (UseN (order_N))))))).\nDefinition s_239_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (AdvCN (AdjCN (UseComparA_prefix (many_A)) (UseN (order_N))) (SubjS (than_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (apcom_PN)) (ComplSlash (SlashV2a (lose_V2)) (elliptic_NP_Pl))))))))))).\nDefinition s_239_3_h := s_230_3_h.\nDefinition s_240_1_p := s_239_1_p.\nDefinition s_240_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (apcom_PN)) (ComplSlash (SlashV2a (lose_V2)) (DetCN (somePl_Det) (UseN (order_N))))))).\nDefinition s_241_1_p := s_239_1_p.\nDefinition s_241_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (apcom_PN)) (ComplSlash (SlashV2a (lose_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_ten)))) (UseN (order_N))))))).\nDefinition s_241_4_h := s_232_4_h.\nDefinition s_242_1_p := (Sentence (UseCl (Present) (PPos) (PredVP the_pc6082_NP (UseComp (CompAP (ComparA (fast_A) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_500)))) (UseN (mips_N))))))))).\nDefinition s_242_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (itelzx_N))) (UseComp (CompAP (ComparA (slow_A) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_500)))) (UseN (mips_N))))))))).\nDefinition s_242_4_h := (Sentence (UseCl (Present) (PPos) (PredVP the_pc6082_NP (UseComp (CompAP (ComparA (fast_A) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (itelzx_N))))))))).\nDefinition s_243_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (sell_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_3000)))) (AdvCN (AdjCN (UseComparA_prefix (many_A)) (UseN (computer_N))) (PrepNP (than_Prep) (UsePN (apcom_PN))))))))).\nDefinition s_243_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (apcom_PN)) (ComplSlash (SlashV2a (sell_V2)) (PredetNP (exactly_Predet) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_2500)))) (UseN (computer_N)))))))).\nDefinition s_243_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (sell_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_5500)))) (UseN (computer_N))))))).\nDefinition s_244_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (apcom_PN)) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdvCN (AdjCN (UseComparA_prefix (important_A)) (UseN (customer_N))) (PrepNP (than_Prep) (UsePN (itel_PN))))))))).\nDefinition s_244_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (apcom_PN)) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdvCN (AdjCN (UseComparA_prefix (important_A)) (UseN (customer_N))) (SubjS (than_Subj) (UseCl (Present) (PPos) (PredVP (UsePN (itel_PN)) (UseComp (CompNP (elliptic_NP_Sg)))))))))))).\nDefinition s_245_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (apcom_PN)) (AdvVP (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (UseComparA_prefix (important_A)) (UseN (customer_N))))) (PrepNP (than_Prep) (UsePN (itel_PN))))))).\nDefinition s_245_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (apcom_PN)) (AdvVP (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (UseComparA_prefix (important_A)) (UseN (customer_N))))) (SubjS (than_Subj) (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (itel_PN)) (elliptic_VP)))))))).\nDefinition s_246_1_p := (Sentence (UseCl (Present) (PPos) (PredVP the_pc6082_NP (UseComp (CompAP (ComparA (fast_A) (DetCN (every_Det) (UseN (itel_computer_N))))))))).\nDefinition s_246_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (itelzx_N))) (UseComp (CompCN (UseN (itel_computer_N))))))).\nDefinition s_246_4_h := s_242_4_h.\nDefinition s_247_1_p := (Sentence (UseCl (Present) (PPos) (PredVP the_pc6082_NP (UseComp (CompAP (ComparA (fast_A) (DetCN (someSg_Det) (UseN (itel_computer_N))))))))).\nDefinition s_247_2_p := s_246_2_p.\nDefinition s_247_4_h := s_242_4_h.\nDefinition s_248_1_p := (Sentence (UseCl (Present) (PPos) (PredVP the_pc6082_NP (UseComp (CompAP (ComparA (fast_A) (DetCN (anySg_Det) (UseN (itel_computer_N))))))))).\nDefinition s_248_2_p := s_246_2_p.\nDefinition s_248_4_h := s_242_4_h.\nDefinition s_249_1_p := (Sentence (UseCl (Present) (PPos) (PredVP the_pc6082_NP (UseComp (CompAP (ComparA (fast_A) (ConjNP2 (and_Conj) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (itelzx_N))) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (itelzy_N)))))))))).\nDefinition s_249_3_h := s_242_4_h.\nDefinition s_250_1_p := (Sentence (UseCl (Present) (PPos) (PredVP the_pc6082_NP (UseComp (CompAP (ComparA (fast_A) (ConjNP2 (or_Conj) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (itelzx_N))) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (itelzy_N)))))))))).\nDefinition s_250_3_h := s_242_4_h.\nDefinition s_251_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (factory_N)))) (PrepNP (in_Prep) (UsePN (birmingham_PN))))))).\nDefinition s_251_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (itel_PN)) (AdVVP (currently_AdV) (AdvVP (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (factory_N)))) (PrepNP (in_Prep) (UsePN (birmingham_PN)))))))).\nDefinition s_252_1_p := (Sentence (AdvS (since_1992_Adv) (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (itel_PN)) (UseComp (CompAdv (PrepNP (in_Prep) (UsePN (birmingham_PN))))))))).\nDefinition s_252_2_p := (Sentence (UseCl (Present) (PPos) (ImpersCl (AdVVP (now_AdV) (UseComp (CompAdv (year_1996_Adv))))))).\nDefinition s_252_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (UseComp (CompAdv (PrepNP (in_Prep) (UsePN (birmingham_PN))))) (in_1993_Adv))))).\nDefinition s_253_1_p := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (develop_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (new_A)) (UseN (editor_N))))) (since_1992_Adv))))).\nDefinition s_253_2_p := s_252_2_p.\nDefinition s_253_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (develop_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (new_A)) (UseN (editor_N))))) (in_1993_Adv))))).\nDefinition s_254_1_p := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (UseV (expand_V)) (since_1992_Adv))))).\nDefinition s_254_2_p := s_252_2_p.\nDefinition s_254_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (UseV (expand_V)) (in_1993_Adv))))).\nDefinition s_255_1_p := (Sentence (AdvS (since_1992_Adv) (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (make8do_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (loss_N)))))))).\nDefinition s_255_2_p := s_252_2_p.\nDefinition s_255_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (make8do_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (loss_N)))) (in_1993_Adv))))).\nDefinition s_256_1_p := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (make8do_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (loss_N)))) (since_1992_Adv))))).\nDefinition s_256_2_p := s_252_2_p.\nDefinition s_256_4_h := s_255_4_h.\nDefinition s_257_1_p := s_256_1_p.\nDefinition s_257_2_p := s_252_2_p.\nDefinition s_257_4_h := s_255_4_h.\nDefinition s_258_1_p := (Sentence (AdvS (in_march_1993_Adv) (UseCl (Past) (PPos) (PredVP (UsePN (apcom_PN)) (ComplSlash (SlashV2a (found_V2)) (UsePN (itel_PN))))))).\nDefinition s_258_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (UseV (exist_V)) (in_1992_Adv))))).\nDefinition s_259_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (conference_N))) (AdvVP (UseV (start_V)) (on_july_4th_1994_Adv))))).\nDefinition s_259_2_p := (Sentence (UseCl (Past) (PPos) (ImpersCl (ComplSlash (SlashV2a (last_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_2)))) (UseN (day_N))))))).\nDefinition s_259_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (conference_N))) (AdvVP (UseComp (CompAdv (over_Adv))) (on_july_8th_1994_Adv))))).\nDefinition s_260_1_p := (Sentence (AdvS (yesterday_Adv) (UseCl (Past) (PPos) (PredVP (UsePN (apcom_PN)) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))))))).\nDefinition s_260_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (MassNP (UseN (today_N))) (UseComp (CompAdv (saturday_july_14th_Adv)))))).\nDefinition s_260_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (apcom_PN)) (AdvVP (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))) (friday_13th_Adv))))).\nDefinition s_261_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseV (leave_V)) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (UseV (leave_V))))))))).\nDefinition s_261_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (UseV (leave_V)) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (anderson_PN)) (UseV (leave_V))))))))).\nDefinition s_261_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseV (leave_V)) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (anderson_PN)) (UseV (leave_V))))))))).\nDefinition s_262_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseV (leave_V)) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (UseV (leave_V))))))))).\nDefinition s_262_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (UseV (leave_V)) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (anderson_PN)) (UseV (leave_V))))))))).\nDefinition s_262_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseV (leave_V)) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (anderson_PN)) (UseV (leave_V))))))))).\nDefinition s_263_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseComp (CompAP (PositA (present8attending_A)))) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (UseV (leave_V))))))))).\nDefinition s_263_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (UseV (leave_V)) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (anderson_PN)) (UseComp (CompAP (PositA (present8attending_A))))))))))).\nDefinition s_263_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseComp (CompAP (PositA (present8attending_A)))) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (anderson_PN)) (UseComp (CompAP (PositA (present8attending_A))))))))))).\nDefinition s_264_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (UseV (leave_V))))).\nDefinition s_264_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (UseV (leave_V))))).\nDefinition s_264_3_p := s_261_1_p.\nDefinition s_264_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (UseV (leave_V)) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (UseV (leave_V))))))))).\nDefinition s_265_1_p := s_264_1_p.\nDefinition s_265_2_p := s_264_2_p.\nDefinition s_265_3_p := s_262_1_p.\nDefinition s_265_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (UseV (leave_V)) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (UseV (leave_V))))))))).\nDefinition s_266_1_p := s_264_1_p.\nDefinition s_266_2_p := s_264_2_p.\nDefinition s_266_3_p := s_265_5_h.\nDefinition s_266_5_h := s_262_1_p.\nDefinition s_267_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (revise_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))))).\nDefinition s_267_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (revise_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))))).\nDefinition s_267_3_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (ComplSlash (SlashV2a (revise_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplVV (do_VV) (elliptic_VP))))))))).\nDefinition s_267_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (revise_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplVV (do_VV) (elliptic_VP))))))))).\nDefinition s_268_1_p := s_267_1_p.\nDefinition s_268_2_p := s_267_2_p.\nDefinition s_268_3_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (ComplSlash (SlashV2a (revise_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplVV (do_VV) (elliptic_VP))))))))).\nDefinition s_268_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (revise_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplVV (do_VV) (elliptic_VP))))))))).\nDefinition s_269_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (UseV (swim_V))))).\nDefinition s_269_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (UseV (swim_V))))).\nDefinition s_269_3_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseV (swim_V)) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (UseV (swim_V))))))))).\nDefinition s_269_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (UseV (swim_V)) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (UseV (swim_V))))))))).\nDefinition s_270_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseV (swim_V)) (PrepNP (to_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (shore_N)))))))).\nDefinition s_270_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (UseV (swim_V)) (PrepNP (to_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (shore_N)))))))).\nDefinition s_270_3_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (AdvVP (UseV (swim_V)) (PrepNP (to_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (shore_N))))) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (UseV (swim_V)) (PrepNP (to_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (shore_N)))))))))))).\nDefinition s_270_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (AdvVP (UseV (swim_V)) (PrepNP (to_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (shore_N))))) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseV (swim_V)) (PrepNP (to_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (shore_N)))))))))))).\nDefinition s_271_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (UseComp (CompAP (PositA (present8attending_A))))))).\nDefinition s_271_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (UseComp (CompAP (PositA (present8attending_A))))))).\nDefinition s_271_3_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseComp (CompAP (PositA (present8attending_A)))) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (UseComp (CompAP (PositA (present8attending_A))))))))))).\nDefinition s_271_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (UseComp (CompAP (PositA (present8attending_A)))) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (UseComp (CompAP (PositA (present8attending_A))))))))))).\nDefinition s_272_1_p := s_271_1_p.\nDefinition s_272_2_p := s_271_2_p.\nDefinition s_272_3_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseComp (CompAP (PositA (present8attending_A)))) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (UseComp (CompAP (PositA (present8attending_A))))))))))).\nDefinition s_272_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (UseComp (CompAP (PositA (present8attending_A)))) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (UseComp (CompAP (PositA (present8attending_A))))))))))).\nDefinition s_273_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ProgrVPa (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))))))).\nDefinition s_273_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ProgrVPa (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))))))).\nDefinition s_273_3_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ProgrVPa (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N))))) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ProgrVPa (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))))))))))).\nDefinition s_273_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (ProgrVPa (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N))))) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ProgrVPa (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))))))))))).\nDefinition s_274_1_p := s_273_1_p.\nDefinition s_274_2_p := s_273_2_p.\nDefinition s_274_3_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ProgrVPa (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N))))) (SubjS (after_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ProgrVPa (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))))))))))).\nDefinition s_274_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (ProgrVPa (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N))))) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ProgrVPa (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))))))))))).\nDefinition s_275_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (leave_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N)))) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePron (he_Pron)) (ComplSlash (SlashV2a (lose_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (UseN (temper_N))))))))))).\nDefinition s_275_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (lose_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (UseN (temper_N))))))).\nDefinition s_276_1_p := (Sentence (ExtAdvS (SubjS (when_Subj) (UseCl (Past) (PPos) (PredVP (UsePron (they_Pron)) (ComplSlash (SlashV2a (open_V2)) (UsePN (the_m25_PN)))))) (UseCl (Past) (PPos) (PredVP (MassNP (UseN (traffic_N))) (UseV (increase_V)))))).\nDefinition s_277_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (birmingham_PN)))) (in_1991_Adv))))).\nDefinition s_277_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (birmingham_PN)))) (in_1992_Adv))))).\nDefinition s_278_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuantOrd (PossPron (heRefl_Pron)) (NumSg) (OrdNumeral (N_one))) (UseN (novel_N)))) (in_1991_Adv))))).\nDefinition s_278_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuantOrd (PossPron (heRefl_Pron)) (NumSg) (OrdNumeral (N_one))) (UseN (novel_N)))) (in_1992_Adv))))).\nDefinition s_279_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (novel_N)))) (in_1991_Adv))))).\nDefinition s_279_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (write_V2)) (UsePron (it_Pron))) (in_1992_Adv))))).\nDefinition s_280_1_p := s_279_1_p.\nDefinition s_280_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (novel_N)))) (in_1992_Adv))))).\nDefinition s_281_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ProgrVPa (ComplSlash (SlashV2a (run_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (business_N))))) (in_1991_Adv))))).\nDefinition s_281_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ProgrVPa (ComplSlash (SlashV2a (run_V2)) (UsePron (it_Pron)))) (in_1992_Adv))))).\nDefinition s_282_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (discover_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (new_A)) (UseN (species_N))))) (in_1991_Adv))))).\nDefinition s_282_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (discover_V2)) (UsePron (it_Pron))) (in_1992_Adv))))).\nDefinition s_283_1_p := s_282_1_p.\nDefinition s_283_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (discover_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (new_A)) (UseN (species_N))))) (in_1992_Adv))))).\nDefinition s_284_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))) (in_two_hours_Adv))))).\nDefinition s_284_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplVV (start_VV) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (report_N))))) (at_8_am_Adv))))).\nDefinition s_284_4_h := (Sentence (UseCl (PastPerfect) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplVV (finish_VV) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (report_N))))) (by_11_am_Adv))))).\nDefinition s_285_1_p := s_284_1_p.\nDefinition s_285_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (spend_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (AdjCN (PartVP (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (report_N))))) (UseN (hour_N)))))))).\nDefinition s_286_1_p := s_284_1_p.\nDefinition s_286_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (spend_V2)) (DetCN (DetQuant (IndefArt) (NumCard (AdNum (more_than_AdN) (NumNumeral (N_two))))) (AdjCN (PartVP (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (report_N))))) (UseN (hour_N)))))))).\nDefinition s_287_1_p := s_284_1_p.\nDefinition s_287_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))) (in_one_hour_Adv))))).\nDefinition s_288_1_p := s_284_1_p.\nDefinition s_288_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N))))))).\nDefinition s_289_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (discover_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (new_A)) (UseN (species_N))))) (in_two_hours_Adv))))).\nDefinition s_289_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (spend_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (SentCN (UseN (hour_N)) (EmbedPresPart (ComplSlash (SlashV2a (discover_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (AdjCN (PositA (new_A)) (UseN (species_N)))))))))))).\nDefinition s_290_1_p := s_289_1_p.\nDefinition s_290_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (discover_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (new_A)) (UseN (species_N)))))))).\nDefinition s_291_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (discover_V2)) (DetCN (many_Det) (AdjCN (PositA (new_A)) (UseN (species_N))))) (in_two_hours_Adv))))).\nDefinition s_291_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (spend_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (SentCN (UseN (hour_N)) (EmbedPresPart (ComplSlash (SlashV2a (discover_V2)) (MassNP (AdjCN (PositA (new_A)) (UseN (species_N)))))))))))).\nDefinition s_292_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ProgrVPa (ComplSlash (SlashV2a (run_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (AdjCN (PositA (own_A)) (UseN (business_N)))))) (PrepNP (in_Prep) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (UseN (year_N)))))))).\nDefinition s_292_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (spend_V2)) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (SentCN (UseN (year_N)) (EmbedPresPart (ComplSlash (SlashV2a (run_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (AdjCN (PositA (own_A)) (UseN (business_N)))))))))))).\nDefinition s_293_1_p := s_292_1_p.\nDefinition s_293_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (spend_V2)) (DetCN (DetQuant (IndefArt) (NumCard (AdNum (more_than_AdN) (NumNumeral (N_two))))) (SentCN (UseN (year_N)) (EmbedPresPart (ComplSlash (SlashV2a (run_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (AdjCN (PositA (own_A)) (UseN (business_N)))))))))))).\nDefinition s_294_1_p := s_292_1_p.\nDefinition s_294_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (run_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (AdjCN (PositA (own_A)) (UseN (business_N)))))))).\nDefinition s_295_1_p := (Sentence (AdvS (PrepNP (in_Prep) (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_two)))) (UseN (year_N)))) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdvCN (UseN (chain_N)) (PrepNP (part_Prep) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (business_N))))))))))).\nDefinition s_295_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdvCN (UseN (chain_N)) (PrepNP (part_Prep) (MassNP (UseN (business_N))))))) (for_two_years_Adv))))).\nDefinition s_296_1_p := s_295_1_p.\nDefinition s_296_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdvCN (UseN (chain_N)) (PrepNP (part_Prep) (MassNP (UseN (business_N))))))) (for_more_than_two_years_Adv))))).\nDefinition s_297_1_p := s_295_1_p.\nDefinition s_297_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (own_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdvCN (UseN (chain_N)) (PrepNP (part_Prep) (MassNP (UseN (business_N)))))))))).\nDefinition s_298_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (birmingham_PN)))) (for_two_years_Adv))))).\nDefinition s_298_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (birmingham_PN)))) (for_a_year_Adv))))).\nDefinition s_299_1_p := s_298_1_p.\nDefinition s_299_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (birmingham_PN)))) (for_exactly_a_year_Adv))))).\nDefinition s_300_1_p := s_298_1_p.\nDefinition s_300_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (birmingham_PN))))))).\nDefinition s_301_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (run_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (AdjCN (PositA (own_A)) (UseN (business_N))))) (for_two_years_Adv))))).\nDefinition s_301_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (run_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (AdjCN (PositA (own_A)) (UseN (business_N))))) (for_a_year_Adv))))).\nDefinition s_302_1_p := s_301_1_p.\nDefinition s_302_3_h := s_294_3_h.\nDefinition s_303_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))) (for_two_hours_Adv))))).\nDefinition s_303_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (report_N)))) (for_an_hour_Adv))))).\nDefinition s_304_1_p := s_303_1_p.\nDefinition s_304_3_h := s_288_3_h.\nDefinition s_305_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (discover_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (new_A)) (UseN (species_N))))) (for_an_hour_Adv))))).\nDefinition s_306_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (discover_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (new_A)) (UseN (species_N))))) (for_two_years_Adv))))).\nDefinition s_306_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (discover_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (new_A)) (UseN (species_N)))))))).\nDefinition s_307_1_p := (Sentence (AdvS (in_1994_Adv) (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (send_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (progress_report_N)))) (every_month_Adv)))))).\nDefinition s_307_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (send_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (progress_report_N)))) (in_july_1994_Adv))))).\nDefinition s_308_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (write_to_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (representative_N)))) (every_week_Adv))))).\nDefinition s_308_3_h := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumSg)) (AdvCN (RelCN (UseN (representative_N)) (UseRCl (Past) (PPos) (StrandRelSlash (that_RP) (SlashVP (UsePN (smith_PN)) (SlashV2a (write_to_V2)))))) (every_week_Adv)))))).\nDefinition s_309_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (leave_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (house_N)))) (at_a_quarter_past_five_Adv))))).\nDefinition s_309_2_p := (Sentence (PredVPS (UsePron (she_Pron)) (ConjVPS2 (and_Conj) (Past) (PPos) (ComplSlash (SlashV2a (take_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdvCN (UseN (taxi_N)) (PrepNP (to_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (station_N))))))) (Past) (PPos) (ComplSlash (SlashV2a (catch_V2)) (DetCN (DetQuantOrd (DefArt) (NumSg) (OrdNumeral (N_one))) (AdvCN (UseN (train_N)) (PrepNP (to_Prep) (UsePN (luxembourg_PN))))))))).\nDefinition s_310_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (lose_V2)) (DetCN (somePl_Det) (UseN (file_N))))))).\nDefinition s_310_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePron (they_Pron)) (AdvVP (PassV2s (destroy_V2)) (SubjS (when_Subj) (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (PossPron (she_Pron)) (NumSg)) (UseN (hard_disk_N))) (UseV (crash_V))))))))).\nDefinition s_311_1_p := (Sentence (UseCl (PastPerfect) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (leave_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (house_N)))) (at_a_quarter_past_five_Adv))))).\nDefinition s_311_2_p := (PSentence (then_PConj) (UseCl (Past) (PPos) (PredVP (UsePron (she_Pron)) (ComplSlash (SlashV2a (take_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (AdvCN (UseN (taxi_N)) (PrepNP (to_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (station_N)))))))))).\nDefinition s_311_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a (leave_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (house_N)))) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePron (she_Pron)) (AdvVP (ComplSlash (SlashV2a (take_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (taxi_N)))) (PrepNP (to_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (station_N)))))))))))).\nDefinition s_312_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (itel_PN)) (AdVVP (always_AdV) (AdvVP (ComplSlash (SlashV2a (deliver_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (report_N)))) (late_Adv)))))).\nDefinition s_312_2_p := (Sentence (AdvS (in_1993_Adv) (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (ComplSlash (SlashV2a (deliver_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (report_N)))))))).\nDefinition s_312_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (AdvVP (ComplSlash (SlashV2a (deliver_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (report_N)))) (late_Adv)) (in_1993_Adv))))).\nDefinition s_313_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (itel_PN)) (AdVVP (never_AdV) (AdvVP (ComplSlash (SlashV2a (deliver_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (report_N)))) (late_Adv)))))).\nDefinition s_313_2_p := s_312_2_p.\nDefinition s_313_4_h := s_312_4_h.\nDefinition s_314_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ComplSlash (SlashV2a arrive_in_V2) (UsePN (paris_PN))) (on_the_5th_of_may_1995_Adv))))).\nDefinition s_314_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (MassNP (UseN (today_N))) (UseComp (CompAdv (the_15th_of_may_1995_Adv)))))).\nDefinition s_314_3_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePron (she_Pron)) (AdVVP (still_AdV) (UseComp (CompAdv (PrepNP (in_Prep) (UsePN (paris_PN))))))))).\nDefinition s_314_5_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseComp (CompAdv (PrepNP (in_Prep) (UsePN (paris_PN))))) (on_the_7th_of_may_1995_Adv))))).\nDefinition s_315_1_p := (Sentence (AdvS (SubjS (when_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a arrive_in_V2) (UsePN (katmandu_PN)))))) (UseCl (PastPerfect) (PPos) (PredVP (UsePron (she_Pron)) (AdvVP (ProgrVPa (UseV (travel_V))) (for_three_days_Adv)))))).\nDefinition s_315_3_h := (Sentence (UseCl (PastPerfect) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (ProgrVPa (UseV (travel_V))) (PrepNP (on_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (AdvCN (UseN (day_N)) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePron (she_Pron)) (ComplSlash (SlashV2a arrive_in_V2) (UsePN (katmandu_PN))))))))))))).\nDefinition s_316_1_p := (Sentence (PredVPS (UsePN (jones_PN)) (ConjVPS2 (and_Conj) (Past) (PPos) (AdvVP (UseV (graduate_V)) (in_march_Adv)) (PresentPerfect) (PPos) (AdvVP (UseComp (CompAP (PositA (employed_A)))) (ever_since_Adv))))).\nDefinition s_316_2_p := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (UseComp (CompAP (PositA (unemployed_A)))) (in_the_past_Adv))))).\nDefinition s_316_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (AdvVP (AdvVP (UseComp (CompAP (PositA (unemployed_A)))) (at_some_time_Adv)) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePron (he_Pron)) (UseV (graduate_V))))))))).\nDefinition s_317_1_p := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (DetCN (every_Det) (UseN (representative_N))) (ComplSlash (SlashV2a (read_V2)) (DetCN (DetQuant (this_Quant) (NumSg)) (UseN (report_N))))))).\nDefinition s_317_2_p := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (DetCN (DetQuant (no_Quant) (NumCard (NumNumeral (N_two)))) (UseN (representative_N))) (AdvVP (ComplSlash (SlashV2a (read_V2)) (UsePron (it_Pron))) (at_the_same_time_Adv))))).\nDefinition s_317_3_p := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (no_Quant) (NumSg)) (UseN (representative_N))) (ComplSlash (SlashV2V (take_V2V) (ComplSlash (SlashV2a (read_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (report_N))))) (DetCN (DetQuant (IndefArt) (NumCard (AdNum (less_than_AdN) (half_a_Card)))) (UseN (day_N))))))).\nDefinition s_317_4_p := (Sentence (UseCl (Present) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumCard (NumNumeral (N_sixteen)))) (UseN (representative_N)))))).\nDefinition s_317_6_h := (Sentence (UseCl (Past) (PPos) (ImpersCl (ComplSlash (SlashV2V (take_V2V) (ComplSlash (SlashV2a (read_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (report_N))))) (DetCN (DetQuant (DefArt) (NumPl)) (AdjCN (ComparA (many_A) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (week_N)))) (UseN (representative_N)))))))).\nDefinition s_318_1_p := (Sentence (ExtAdvS (SubjS (while_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ProgrVPa (ComplSlash (SlashV2a (update_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (program_N)))))))) (PredVPS (UsePN (mary_PN)) (ConjVPS2 (and_Conj) (Past) (PPos) (UseV (come_in_V)) (Past) (PPos) (ComplSlash (Slash3V3 (tell_about_V3) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (board_meeting_N)))) (UsePron (he_Pron))))))).\nDefinition s_318_2_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePron (she_Pron)) (AdvVP (ComplVV (finish_VV) (elliptic_VP)) (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePron (he_Pron)) (ComplVV (do_VV) (elliptic_VP))))))))).\nDefinition s_319_1_p := (Sentence (ExtAdvS (SubjS (before_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (apcom_PN)) (ComplSlash (SlashV2a (buy_V2)) (DetCN (DetQuant (PossPron (itRefl_Pron)) (NumSg)) (AdjCN (PositA (present8current_A)) (UseN (office_building_N)))))))) (UseCl (PastPerfect) (PPos) (ImpersCl (AdvVP (AdvVP (ProgrVPa (ComplSlash (SlashV2a (pay_V2)) (MassNP (UseN (mortgage_interest_N))))) (PrepNP (on_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (AdjCN (PositA (previous_A)) (UseN (one_N)))))) (for_8_years_Adv)))))).\nDefinition s_319_2_p := (Sentence (AdvS (SubjS (since_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (apcom_PN)) (ComplSlash (SlashV2a (buy_V2)) (DetCN (DetQuant (PossPron (itRefl_Pron)) (NumSg)) (AdjCN (PositA (present8current_A)) (UseN (office_building_N)))))))) (UseCl (PresentPerfect) (PPos) (ImpersCl (AdvVP (AdvVP (ProgrVPa (ComplSlash (SlashV2a (pay_V2)) (MassNP (UseN (mortgage_interest_N))))) (PrepNP (on_Prep) (UsePron (it_Pron)))) (for_more_than_10_years_Adv)))))).\nDefinition s_319_4_h := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (apcom_PN)) (AdvVP (ProgrVPa (ComplSlash (SlashV2a (pay_V2)) (MassNP (UseN (mortgage_interest_N))))) (for_a_total_of_15_years_or_more_Adv))))).\nDefinition s_320_1_p := (Sentence (ExtAdvS (SubjS (when_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (get_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (AdvCN (UseN (job_N)) (PrepNP (at_Prep) (UsePN (the_cia_PN))))))))) (UseCl (Past) (PPos) (PredVP (UsePron (he_Pron)) (ComplVS (know_VS) (UseCl (Conditional) (PPos) (PredVP (UsePron (he_Pron)) (AdVVP (never_AdV) (PassVPSlash (SlashV2V (allow_V2V) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumPl)) (UseN (memoir_N)))))))))))))).\nDefinition s_320_3_h := (Sentence (UseCl (Present) (PPos) (ImpersCl (AdvVP (UseComp (CompNP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (case_N))))) (SubjS (that_Subj) (PredVPS (UsePN (jones_PN)) (ConjVPS2 (and_Conj) (Present) (UncNeg) (PassVPSlash (elliptic_VPSlash)) (Future) (PPos) (AdVVP (never_AdV) (PassVPSlash (SlashV2V (allow_V2V) (ComplSlash (SlashV2a (write_V2)) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumPl)) (UseN (memoir_N)))))))))))))).\nDefinition s_321_1_p := (Sentence (UseCl (PresentPerfect) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (AdvVP (UseComp (CompAdv (PrepNP (to_Prep) (UsePN (florence_PN))))) (twice_Adv)) (in_the_past_Adv))))).\nDefinition s_321_2_p := (Sentence (UseCl (Future) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (AdvVP (AdvVP (UseV (go8travel_V)) (PrepNP (to_Prep) (UsePN (florence_PN)))) (twice_Adv)) (in_the_coming_year_Adv))))).\nDefinition s_321_4_h := (Sentence (AdvS (two_years_from_now_Adv) (UseCl (FuturePerfect) (PPos) (PredVP (UsePN (smith_PN)) (AdvVP (UseComp (CompAdv (PrepNP (to_Prep) (UsePN (florence_PN))))) (at_least_four_times)))))).\nDefinition s_322_1_p := (Sentence (AdvS (last_week_Adv) (UseCl (Past) (PPos) (PredVP (UsePron (i_Pron)) (AdVVP (already_AdV) (ComplVS (know_VS) (ExtAdvS (SubjS (when_Subj) (ExtAdvS (in_a_months_time_Adv) (UseCl (Conditional) (PPos) (PredVP (UsePN (smith_PN)) (ComplVS (discover_VS) (UseCl (PastPerfect) (PPos) (PredVP (UsePron (she_Pron)) (PassV2 (dupe_V2))))))))) (UseCl (Conditional) (PPos) (PredVP (UsePron (she_Pron)) (UseComp (CompAP (PositA (furious_A))))))))))))).\nDefinition s_322_3_h := (Sentence (UseCl (Future) (PPos) (ImpersCl (AdvVP (UseComp (CompNP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (case_N))))) (SubjS (that_Subj) (ConjS2 (semicolon_and_Conj) (AdvS (in_a_few_weeks_Adv) (UseCl (Future) (PPos) (PredVP (UsePN (smith_PN)) (ComplVS (discover_VS) (UseCl (PresentPerfect) (PPos) (PredVP (UsePron (she_Pron)) (PassV2 (dupe_V2)))))))) (UseCl (Future) (PPos) (PredVP (UsePron (she_Pron)) (UseComp (CompAP (PositA (furious_A)))))))))))).\nDefinition s_323_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (RelNPa (UsePron (no_one_Pron)) (UseRCl (Present) (PPos) (RelVP (IdRP) (AdvVP (ProgrVPa (UseV (gamble_V))) (PositAdvAdj (serious_A)))))) (AdvVP (UseV (stop_V)) (SubjS (until_Subj) (UseCl (Present) (PPos) (PredVP (UsePron (he_Pron)) (UseComp (CompAP (PositA (broke_A))))))))))).\nDefinition s_323_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePron (no_one_Pron)) (ComplVV (can_VV) (AdvVP (UseV (gamble_V)) (SubjS (when_Subj) (UseCl (Present) (PPos) (PredVP (UsePron (he_Pron)) (UseComp (CompAP (PositA (broke_A)))))))))))).\nDefinition s_323_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (RelNPa (UsePron (everyone_Pron)) (UseRCl (Present) (PPos) (RelVP (IdRP) (ComplVV (start_VV) (AdvVP (UseV (gamble_V)) (PositAdvAdj (serious_A))))))) (AdvVP (UseV (stop_V)) (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (AdvCN (UseN (moment_N)) (SubjS (when_Subj) (UseCl (Present) (PPos) (PredVP (UsePron (he_Pron)) (UseComp (CompAP (PositA (broke_A)))))))))))))).\nDefinition s_324_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (RelNPa (UsePron (no_one_Pron)) (UseRCl (Present) (PPos) (RelVP (IdRP) (ComplVV (start_VV) (AdvVP (UseV (gamble_V)) (PositAdvAdj (serious_A))))))) (AdvVP (UseV (stop_V)) (SubjS (until_Subj) (UseCl (Present) (PPos) (PredVP (UsePron (he_Pron)) (UseComp (CompAP (PositA (broke_A))))))))))).\nDefinition s_324_3_h := (Sentence (UseCl (Present) (PPos) (PredVP (RelNPa (UsePron (everyone_Pron)) (UseRCl (Present) (PPos) (RelVP (IdRP) (ComplVV (start_VV) (AdvVP (UseV (gamble_V)) (PositAdvAdj (serious_A))))))) (AdvVP (UseV (continue_V)) (SubjS (until_Subj) (UseCl (Present) (PPos) (PredVP (UsePron (he_Pron)) (UseComp (CompAP (PositA (broke_A))))))))))).\nDefinition s_325_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (RelNPa (UsePron (nobody_Pron)) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (PositA (asleep_A))))))) (AdVVP (ever_AdV) (ComplVS (know_VS) (UseCl (Present) (PPos) (PredVP (UsePron (he_Pron)) (UseComp (CompAP (PositA (asleep_A))))))))))).\nDefinition s_325_2_p := (PSentence (but_PConj) (UseCl (Present) (PPos) (PredVP (DetCN (somePl_Det) (UseN (person_N))) (AdvVP (ComplVS (know_VS) (UseCl (PresentPerfect) (PPos) (PredVP (UsePron (they_Pron)) (UseComp (CompAP (PositA (asleep_A))))))) (SubjS (after_Subj) (UseCl (PresentPerfect) (PPos) (PredVP (UsePron (they_Pron)) (UseComp (CompAP (PositA (asleep_A))))))))))).\nDefinition s_325_4_h := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (somePl_Det) (UseN (person_N))) (ComplVS (discover_VS) (UseCl (PresentPerfect) (PPos) (PredVP (UsePron (they_Pron)) (UseComp (CompAP (PositA (asleep_A)))))))))).\nDefinition s_326_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (build_V2)) (UsePN (mtalk_PN))) (in_1993_Adv))))).\nDefinition s_326_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (finish_V2)) (UsePN (mtalk_PN))) (in_1993_Adv))))).\nDefinition s_327_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ProgrVPa (ComplSlash (SlashV2a (build_V2)) (UsePN (mtalk_PN)))) (in_1993_Adv))))).\nDefinition s_327_3_h := s_326_3_h.\nDefinition s_328_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (AdvVP (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))) (PrepNP (from_Prep) (UsePN (apcom_PN)))) (in_1993_Adv))))).\nDefinition s_328_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (contract_N)))) (in_1993_Adv))))).\nDefinition s_329_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (AdvVP (ProgrVPa (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))) (PrepNP (from_Prep) (UsePN (apcom_PN)))) (in_1993_Adv))))).\nDefinition s_329_3_h := s_328_3_h.\nDefinition s_330_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (own_V2)) (UsePN (apcom_PN))) (from_1988_to_1992_Adv))))).\nDefinition s_330_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (own_V2)) (UsePN (apcom_PN))) (in_1990_Adv))))).\nDefinition s_331_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (ConjNP2 (and_Conj) (UsePN (smith_PN)) (UsePN (jones_PN))) (ComplSlash (SlashV2a (leave_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))).\nDefinition s_331_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2a (leave_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))).\nDefinition s_332_1_p := s_331_1_p.\nDefinition s_332_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (leave_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (meeting_N))))))).\nDefinition s_333_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (ConjNP3 (and_Conj) (UsePN (smith_PN)) (UsePN (anderson_PN)) (UsePN (jones_PN))) (UseV (meet_V))))).\nDefinition s_333_3_h := (Sentence (UseCl (Past) (PPos) (ExistNP (DetCN (DetQuant (IndefArt) (NumSg)) (RelCN (ComplN2 group_N2 (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (person_N)))) (UseRCl (Past) (PPos) (RelVP (that_RP) (UseV (meet_V))))))))).\nDefinition s_334_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplVS (know_VS) (UseCl (PastPerfect) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))) (in_1992_Adv)))))))).\nDefinition s_334_3_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))) (in_1992_Adv))))).\nDefinition s_335_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplVS (believe_VS) (UseCl (PastPerfect) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))) (in_1992_Adv)))))))).\nDefinition s_335_3_h := s_334_3_h.\nDefinition s_336_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplVV (manage_VV) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))) (in_1992_Adv))))).\nDefinition s_336_3_h := s_334_3_h.\nDefinition s_337_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplVV (try_VV) (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))) (in_1992_Adv))))).\nDefinition s_337_3_h := s_334_3_h.\nDefinition s_338_1_p := (Sentence (UseCl (Present) (PPos) (ImpersCl (UseComp (CompAP (SentAP (PositA (true_A)) (EmbedS (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))) (in_1992_Adv))))))))))).\nDefinition s_338_3_h := s_334_3_h.\nDefinition s_339_1_p := (Sentence (UseCl (Present) (PPos) (ImpersCl (UseComp (CompAP (SentAP (PositA (false_A)) (EmbedS (UseCl (Past) (PPos) (PredVP (UsePN (itel_PN)) (AdvVP (ComplSlash (SlashV2a (win_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N)))) (in_1992_Adv))))))))))).\nDefinition s_339_3_h := s_334_3_h.\nDefinition s_340_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2V (see_V2V) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))) (UsePN (jones_PN)))))).\nDefinition s_340_2_p := (Sentence (ExtAdvS (SubjS (if_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))))) (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (PossPron (he_Pron)) (NumSg)) (UseN (heart_N))) (ProgrVPa (UseV (beat_V))))))).\nDefinition s_340_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2V (see_V2V) (UseV (beat_V))) (DetCN (DetQuant (GenNP (UsePN (jones_PN))) (NumSg)) (UseN (heart_N))))))).\nDefinition s_341_1_p := s_340_1_p.\nDefinition s_341_2_p := (Sentence (ExtAdvS (SubjS (when_Subj) (UseCl (Past) (PPos) (PredVP (UsePN (jones_PN)) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))))) (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (PossPron (he_Pron)) (NumSg)) (UseN (heart_N))) (ProgrVPa (UseV (beat_V))))))).\nDefinition s_341_4_h := s_340_4_h.\nDefinition s_342_1_p := s_341_1_p.\nDefinition s_342_3_h := s_081_3_h.\nDefinition s_343_1_p := s_341_1_p.\nDefinition s_343_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (UsePN (jones_PN)) (UseComp (CompNP (DetCN (DetQuant (DefArt) (NumSg)) (ComplN2 (chairman_N2) (UsePN (itel_PN))))))))).\nDefinition s_343_4_h := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (smith_PN)) (ComplSlash (SlashV2V (see_V2V) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))) (DetCN (DetQuant (DefArt) (NumSg)) (ComplN2 (chairman_N2) (UsePN (itel_PN)))))))).\nDefinition s_344_1_p := (Sentence (UseCl (Past) (PPos) (PredVP (UsePN (helen_PN)) (ComplSlash (SlashV2V (see_V2V) (ComplSlash (SlashV2a (answer_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (phone_N))))) (DetCN (DetQuant (DefArt) (NumSg)) (ComplN2 (chairman_N2) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (department_N))))))))).\nDefinition s_344_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumSg)) (ComplN2 (chairman_N2) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (department_N))))) (UseComp (CompCN (UseN (person_N))))))).\nDefinition s_344_4_h := (Sentence (UseCl (Present) (PPos) (ExistNP (RelNPa (UsePron (someone_Pron)) (UseRCl (Past) (PPos) (StrandRelSlash (IdRP) (SlashVP (UsePN (helen_PN)) (SlashV2V (see_V2V) (ComplSlash (SlashV2a (answer_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (phone_N)))))))))))).\nDefinition s_345_1_p := (Sentence (PredVPS (UsePN (smith_PN)) (ConjVPS2 (and_Conj) (Past) (PPos) (ComplSlash (SlashV2V (see_V2V) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))) (UsePN (jones_PN))) (Past) (PPos) (ComplSlash (SlashV2V (elliptic_V2V) (ComplSlash (SlashV2a (make8do_V2)) (DetCN (DetQuant (IndefArt) (NumSg)) (UseN (copy_N))))) (DetCN (DetQuant (PossPron (heRefl_Pron)) (NumSg)) (UseN (secretary_N))))))).\nDefinition s_345_3_h := s_340_1_p.\nDefinition s_346_1_p := (Sentence (PredVPS (UsePN (smith_PN)) (ConjVPS2 (or_Conj) (Past) (PPos) (ComplSlash (SlashV2V (see_V2V) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))) (UsePN (jones_PN))) (Past) (PPos) (ComplSlash (SlashV2V (elliptic_V2V) (ComplSlash (SlashV2a (cross_out_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (AdjCN (PositA (crucial_A)) (UseN (clause_N)))))) (elliptic_NP_Sg))))).\nDefinition s_346_3_h := (Sentence (PredVPS (UsePN (smith_PN)) (ConjVPS2 (either7or_DConj) (Past) (PPos) (ComplSlash (SlashV2V (see_V2V) (ComplSlash (SlashV2a (sign_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (contract_N))))) (UsePN (jones_PN))) (Past) (PPos) (ComplSlash (SlashV2V (see_V2V) (ComplSlash (SlashV2a (cross_out_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (AdjCN (PositA (crucial_A)) (UseN (clause_N)))))) (UsePN (jones_PN)))))).\n\n\n(** Theorems **)\n\n\nTheorem FraCaS001: s_001_1_p->s_001_3_h.\ncbv.\nfirstorder.\nQed.\n\nTheorem FraCaS002: (s_002_1_p/\\s_002_2_p)->s_002_4_h.\ncbv.\nfirstorder.\nexists x.\ndestruct great_A as [great].\nfirstorder.\nassert (H' := H x (conj H0 H2)).\ngeneralize H'.\napply wantCovariant_K.\nintros tenor' t gt.\nsplit.\ndestruct gt as [greatTenor' p].\ndestruct p as [p eq].\nrewrite -> eq.\nfirstorder.\ndestruct gt as [greatTenor' p].\ndestruct p as [p eq].\nrewrite -> eq.\nfirstorder.\nQed.\n\n\nDefinition s_003_1_p_fixed := (Sentence (UseCl (Present) (PPos)\n   (PredVP (DetCN (all_Det) (UseN (man_N)))\n           (ComplVV (want_VV) (UseComp (CompNP (DetCN (DetQuant (IndefArt) (NumSg)) (AdjCN (PositA (great_A)) (UseN (tenor_N)))))))))).\n\nTheorem FraCaS003: (s_003_1_p_fixed/\\s_003_2_p)->s_003_4_h. cbv. \ndestruct great_A as [great].\nfirstorder.\nQed.\n\nTheorem FraCaS004: (s_004_1_p/\\s_004_2_p)->s_004_4_h. cbv. firstorder. Qed.\n\nTheorem FraCaS005: s_005_1_p->(s_005_3_h). cbv.  firstorder. Qed.\n\nTheorem FraCaS006: (s_006_1_p)->not(s_006_3_h). cbv. intro.  firstorder. Qed.\n\nTheorem FraCaS007: (s_007_1_p)->(s_007_3_h). cbv. intro.  firstorder. Qed.\n\nTheorem FraCaS008: (s_008_1_p)->(s_008_3_h). cbv. intro.  firstorder. Qed.\n\nTheorem FraCaS009: (s_009_1_p)->(s_009_3_h). cbv. intro.  firstorder. Qed.\n\nTheorem FraCaS010: (s_010_1_p)->(s_010_3_h). cbv. intro. firstorder. Qed.\n\nTheorem FraCaS011: ((s_011_1_p)/\\(s_011_2_p))->(s_011_4_h). cbv. firstorder. Qed.\nTheorem FraCaS012: (s_012_1_p)->(s_012_3_h). cbv. firstorder. destruct great_A as [great]. firstorder. Abort All. (**this is undefined in the FraCaS, having the answer \"not many\". In principle, the conclusion should follow only if \"few\" implies existence. See the definition of a_few_Det above. **)\n\nDefinition s_013_2a_p := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (each_Det)(RelCN (AdjCN (PositA (leading_A)) (UseN (tenor_N))) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (PositA (excellent_A)))))))) (UseComp (CompAP (PositA (indispensable_A))))))).\n\n\nTheorem FraCaS013: ((s_013_1_p)/\\(s_013_2a_p))->(s_013_4_h).\ncbv.\ndestruct leading_A as [leading].\ndestruct indispensable_A as [indispensable].\ndestruct excellent_A as [excellent].\nfirstorder. exists x. exists x0. firstorder.\n\n(* FIXME: we're missing indispensable (excellent x) => indispensable x.\nRelCN works at the CN level, not at the NP, so it is difficult to fix.\n*)\n\n\nTheorem FraCaS014: (s_014_1_p) -> (s_014_2_p)->not(s_014_4_h). cbv.\nintros. destruct leading_A as [leading]. Abort All.\n(** FIXME: Anaphora. this cannot be proven at the moment, the problem is the numeral one, \"one of the\" has an anaphoric existential interpretation, has to pick one of the two existentials introduced by neither. This is not what we get.**)\n\nLemma le_mono : forall n, forall (p q : CN), (forall x, p x -> q x) -> n <= CARD p -> n <= CARD q.\nintros.\napply le_trans with (y := CARD p).\nassumption.\napply CARD_monotonous.\nassumption.\nQed.\n\nLemma le_mono' : forall n, forall (p q : CN), (forall x, q x -> p x) -> CARD p <= n -> CARD q <= n.\nintros.\napply le_trans with (y := CARD p).\napply CARD_monotonous.\nassumption.\nassumption.\nQed.\n\nVariable CARD_exists : forall P:(object -> Prop), 1 <= CARD P -> exists x, P x.\nTheorem FraCaS015: s_015_1_p->s_015_3_h.\ncbv. intro P1.\napply CARD_exists.\napply le_trans with (y := 3).\nfirstorder.\ngeneralize P1.\napply le_mono.\nfirstorder. Qed.\n\nTheorem FraCaS016: s_016_1_p->s_016_3_h. cbv. firstorder. Abort All.\n(**this has the answer \"at most two\" which pretty much means yes, it is one of the strangest cases, not well defined, Maccartney who did the XML marks these cases as undefined. If we were to implement this here we'd need the conclusion to be exactly the same statement as P1. **)\n\n\n\n(* End of subsection 1.1, 12/14 *)\n(* SEC 1.2*)\n\nTheorem FraCaS017: (s_017_1_p)->(s_017_3_h). cbv. intro.  firstorder. Qed.\n\nTheorem FraCaS018: s_018_1_p -> s_018_2_p -> s_018_3_p-> s_018_5_h. cbv.\ndestruct in_Prep as [inP inV inC].\ndestruct within_Prep as [withinP withinV withinC].\ndestruct europe_PN as [europe regionN].\nintros P1 P2 P3.\nfirstorder.\nQed.\n\nDefinition s_019_1_p_fixed := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (DefArt) (NumPl)) (UseN (european_N)))) (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (SentCN (UseN (right_N)) (EmbedVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (europe_PN))))))))))).\nDefinition s_019_5_h_fixed := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (DefArt) (NumPl)) (UseN (european_N)))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))).\n\nTheorem FraCaS019_fixed: (s_019_1_p_fixed/\\s_019_2_p/\\s_019_3_p)->(s_019_5_h_fixed). cbv. intros.\nfirstorder. Qed.\n\n(**all is a predeterminer and the parse tree involves an indefart\nwhich gives an existential rather than a universal quantifier for\nall. In this way, sentences with all have existential force contrary\nto fact**)\n\nTheorem FraCaS019: (s_019_1_p/\\s_019_2_p/\\s_019_3_p)->(s_019_5_h). cbv. intros. \nfirstorder. Qed.\n\nTheorem FraCaS020: (s_020_1_p/\\s_020_2_p/\\s_020_3_p)->(s_020_5_h).  cbv. firstorder. Qed.\n\nTheorem FraCaS021: s_021_1_p -> s_021_2_p -> s_021_3_p->(s_021_5_h). cbv.\ndestruct in_Prep as [inP inV inC].\n destruct within_Prep as [within withinVerid withinCov].\ndestruct europe_PN as [europe regionN].\nintros P1 P2 P3.\n firstorder.\n apply P3.\nfirstorder.\n Qed.\n\n  \nTheorem FraCaS022: s_022_1_p->(s_022_3_h).  cbv. intros.  firstorder. Abort All. (**UNK example**)\n\nTheorem FraCaS023: s_023_1_p->(s_023_3_h).\ncbv. intro. destruct on_time_Adv. firstorder.\nQed.\n\n\nTheorem FraCaS024: s_024_1_p->(s_024_3_h).  cbv. intros. firstorder.\ngeneralize H0.\napply le_mono.\nfirstorder.\nQed.\n\nTheorem FraCaS025: s_025_1_p->(s_025_3_h).  cbv. intros.\ndestruct major_A as [major] eqn:majorEq.\ndestruct in_Prep as [inPrep inVerid inVeridCov].\nfirstorder.\nexists x.\nfirstorder.\napply inVerid with (prepArg := (fun k : object -> Prop =>\n          exists x : object,\n            (major (fun x0 : object => national_A newspaper_N x0) x /\\\n             national_A newspaper_N x) /\\ k x)).\napply inVeridCov with (v := (fun y : object =>\n          (forall x : object,\n           result_N x /\\ (exists subject : object, publish_V2 x subject) ->\n           get_V2 x y) /\\\n          get_V2\n            (environment\n               (fun x : object =>\n                result_N x /\\\n                (exists subject : object, publish_V2 x subject))) y /\\\n          result_N\n            (environment\n               (fun x : object =>\n                result_N x /\\\n                (exists subject : object, publish_V2 x subject))) /\\\n          (exists subject : object,\n             publish_V2\n               (environment\n                  (fun x : object =>\n                   result_N x /\\\n                   (exists subject0 : object, publish_V2 x subject0)))\n               subject))).\nfirstorder.\nassumption.\ngeneralize H0.\napply le_mono.\nintro.\nintro.\nsplit.\nfirstorder.\ndestruct H2 as [delegx0 x0publInMNP].\nsplit.\napply inVerid with (prepArg := (apNP1 (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (mkSubsective major)) (AdjCN (PositA (national_A)) (UseN (newspaper_N))))))) (subject := x0).\napply  inVeridCov with (v := ((ComplSlash (SlashV2a (get_V2)) (PPartNP (DetCN (DetQuant (DefArt) (NumPl)) (UseN (result_N))) (publish_V2))) ) (fun x => True)).\nfirstorder.\ncbv.\nassumption.\nfirstorder.\nQed.\n\n\n(* Definition s_026_1_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (most_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (european_N)))) (UseComp (CompAP (AdvAP (PositA (resident_A)) (PrepNP (in_Prep) (UsePN (europe_PN))))))))). *)\n(* Definition s_026_2_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (UseN (european_N)))) (UseComp (CompCN (UseN (person_N))))))). *)\n(* Definition s_026_3_p := (Sentence (UseCl (Present) (PPos) (PredVP (PredetNP (all_Predet) (DetCN (DetQuant (IndefArt) (NumPl)) (RelCN (UseN (person_N)) (UseRCl (Present) (PPos) (RelVP (IdRP) (UseComp (CompAP (AdvAP (PositA (resident_A)) (PrepNP (in_Prep) (UsePN (europe_PN))))))))))) (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN)))))))). *)\n\nDefinition european_travel x := european_N x /\\ (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN))))) european_N x.\n\n\nTheorem FraCaS026: s_026_1_p/\\s_026_2_p/\\s_026_3_p->s_026_5_h.\ncbv.\ndestruct europe_PN as [europe regionN].\ndestruct in_Prep as [inP inVerid inCov].\ndestruct within_Prep as [within withinVerid withinCov].\nintros.\ncut (forall x,\n         european_N x /\\\n         AdvAP resident_A\n           (inP (fun k : object -> Prop => k europe)) european_N\n           x -> european_N x /\\\n     can_VV\n       (fun (_ : object -> Prop) (x0 : object) =>\n        within (fun k : object -> Prop => k europe)\n          (fun y : object => PositAdvAdj free_A (fun y0 : object => travel_V y0) y) x0) x).\nintro. firstorder.\ngeneralize H.\napply le_mono.\nfirstorder.\nfirstorder.\nQed.\n\nTheorem FraCaS027: s_027_1_p -> s_027_2_p -> s_027_3_p -> s_027_5_h.\ncbv.\ndestruct from_Prep as [from fromVerid fromVeridCov].\ndestruct sweden_PN as [sweden countryN].\ndestruct scandinavia_PN as [scandinavia regionN].\nintros P1 P2 P3.\nfirstorder.\nrewrite -> H.\napply CARD_monotonous.\nfirstorder.\nQed.\n\n Theorem FraCaS028: s_028_1_p/\\s_028_2_p/\\s_028_3_p->s_028_5_h.\ncbv. destruct from_Prep as [from fromVerid]. firstorder. (** UNK **) Abort All.\n\n\nVariable usedToBeCov_K : forall (p q : VP), (forall x xClass, p xClass x -> q xClass x) -> forall x , use_VV p x -> use_VV q x.\nTheorem FraCaS029: s_029_1_p->(s_029_3_h). cbv.\nfirstorder. destruct leading_A as [leading].\nfirstorder. \nexists x. exists x0. \nfirstorder.\napply usedToBeCov_K with (p := (fun xClass x => leading businessman_N x /\\ businessman_N x)).\nfirstorder. assumption.\napply usedToBeCov_K with (p := (fun xClass x => leading businessman_N x /\\ businessman_N x)).\nfirstorder. assumption.\nQed.\n\n\n\nTheorem FraCaS030: s_030_1_p->(s_030_3_h).  cbv. intros. destruct at_home_Adv. firstorder.\nexists x0. exists x1. firstorder. apply H0. (* UNK *)  Abort All.\n\nTheorem FraCaS031: s_031_1_p->(s_031_3_h).  cbv. firstorder.\n\ndestruct at_home_Adv as [atHome atHomeVerid].\ndestruct atHomeVerid as [atHomeVerid atHomeVeridCov].\ngeneralize H. apply le_mono. firstorder.\ngeneralize H1. apply atHomeVeridCov. firstorder.\nQed.\n\nTheorem FraCaS032: s_032_1_p->(s_032_3_h). cbv. destruct at_home_Adv. firstorder.  (** UNK **) Abort All.\n      (** End of sec 2.2 16/16  \\o/ )**)\n\n(* SEC 1.3 *)\n\n      (* FraCaS033 -> 037 UNK *)\n\n Theorem FraCaS033: s_033_1_p->(s_033_3_h). cbv. \n                                            firstorder.       (**UNK**)\n\n\n Theorem FraCaS034: s_034_1_p/\\ s_034_2_p/\\ s_034_3_p->(s_034_5_h). cbv. \ndestruct in_Prep as [inPrep inVerid].\ndestruct in_Prep as [within withinVerid].\nfirstorder. Abort all. (*UNK*)\n\n Theorem FraCaS035: s_035_1_p/\\ s_035_2_p/\\ s_035_3_p->(s_035_5_h). cbv. \ndestruct in_Prep as [inPrep inVerid].\ndestruct in_Prep as [within withinVerid].\nfirstorder. Abort all. (*UNK*)\n\n Theorem FraCaS036: s_036_1_p/\\ s_036_2_p/\\ s_036_3_p->(s_036_5_h). cbv. \ndestruct in_Prep as [inPrep inVerid].\ndestruct in_Prep as [within withinVerid].\nfirstorder. Abort all. (*UNK*)\n\n  Theorem FraCaS037: s_037_1_p/\\ s_037_2_p/\\ s_037_3_p->(s_037_5_h). cbv. \ndestruct in_Prep as [inPrep inVerid].\ndestruct in_Prep as [within withinVerid].\nfirstorder. Abort all. (*UNK*)\n\nTheorem FraCaS038: s_038_1_p->not(s_038_3_h).  cbv. destruct on_time_Adv. firstorder. Qed.\n\nTheorem FraCaS039: s_039_1_p->(s_039_3_h).  cbv. destruct on_time_Adv. firstorder. Abort all. (**UNK**)\n\nTheorem FraCaS040: s_040_1_p->s_040_3_h. cbv.\nfirstorder.\nexists x.\nfirstorder.\nexists x0.\nfirstorder. (* UNK *)\nAbort All.\n\nTheorem FraCaS041: s_041_1_p->s_041_3_h. cbv.  firstorder. destruct in_Prep as [inPrep inVerid]. destruct in_Prep as [within withinVerid]. firstorder. \n(**UNK**) Abort All. \n\nTheorem FraCaS042: (s_042_1_p/\\s_042_2_p/\\s_042_3_p)->(s_042_5_h).  cbv. destruct in_Prep as [inPrep inVerid].\ndestruct in_Prep as [within withinVerid].\n\nfirstorder. Abort All.  (**UNK**)\n\nTheorem FraCaS043: (s_043_1_p/\\s_043_2_p/\\s_043_3_p)->(s_043_5_h). cbv. destruct in_Prep as [inPrep inVerid]. destruct in_Prep as [within withinVerid]. firstorder. \n(**UNK**) Abort All.\n\n\nTheorem FraCaS044: s_044_1_p -> s_044_2_p -> s_044_3_p -> s_044_5_h.\ncbv.\nintros P1  P2  P3.\ndestruct from_Prep as [from fromVerid fromVeridCov].\ndestruct southern_europe_PN as [southernEurope regionN].\ndestruct portugal_PN as [portugal countryN].\ngeneralize P1. apply le_mono'. firstorder.\napply P3.\nfirstorder.\nQed.\n\nTheorem FraCaS045: s_045_1_p->(s_045_3_h).\ncbv.\ndestruct leading_A.\nfirstorder.\n(* UNK *) Abort All. \n\nTheorem FraCaS046: s_046_1_p->not(s_046_3_h).\ncbv. destruct at_home_Adv as [atHome atHomeVerid].\ndestruct atHomeVerid as [atHomeVerid atHomeVeridCov].  \nfirstorder. (**cannot prove this, FIXME: One anaphora**)Abort all. \n\nTheorem FraCaS047: s_047_1_p->s_047_3_h.\ncbv. intros P1.\ngeneralize P1. apply le_mono. firstorder.\n(* UNK *) Abort All.\n\nTheorem FraCaS048: s_048_1_p->(s_048_3_h). cbv. \ndestruct at_home_Adv as [atHome atHomeVerid].\ndestruct atHomeVerid as [atHomeVerid atHomeVeridCov].\nintros.\ngeneralize H. apply le_mono'. firstorder.\ngeneralize H1. apply atHomeVeridCov. firstorder.\nQed.\n(** End of Sec 1.3 15/16 for this section**)\n\n(* SEC 1.4 *)\n\nTheorem FraCaS049: (s_049_1_p/\\s_049_2_p)->(s_049_4_h).  cbv.\nfirstorder. Qed.\n\nTheorem FraCaS050: (s_050_1_p/\\s_050_2_p)->(s_050_4_h).\ncbv.  destruct within_Prep as [withinPrep inVerid]. firstorder.  \n(* UNK *) Abort All.\n\n\nTheorem FraCaS051: (s_051_1_p/\\s_051_2_p)->(s_051_4_h).\ncbv. destruct within_Prep as [withinPrep inVerid].\nfirstorder. \n(*UNK*) Abort all. \n\nTheorem FraCaS052: (s_052_1_p/\\s_052_2_p)->(s_052_4_h).\ncbv. destruct within_Prep as [withinPrep inVerid].\nfirstorder. \n(*UNK*) Abort all.\n\n\nTheorem FraCaS053: (s_053_1_p/\\s_053_2_p)->(s_053_4_h).\ncbv.\ndestruct in_Prep as [inPrep inVerid].\nfirstorder. (*UNK*)\n\nTheorem FraCaS054: s_054_1_p->(s_054_3_h).\ncbv. \ndestruct on_time_Adv.\nfirstorder.\n(*UNK*) Abort All.\n\nTheorem FraCaS055: (s_055_1_p)->(s_055_3_h).  cbv. firstorder.\nQed.\n\nTheorem FraCaS056: (s_056_1_p)->(s_056_3_h).  cbv.             \nfirstorder. (*UNK*) Abort All.\n\nTheorem FraCaS057: (s_057_1_p)->(s_057_3_h).\ncbv.\nintro P.\ndestruct major_A as [major].\ndestruct in_Prep as [inPrep inVerid inCov].\nfirstorder.\ngeneralize H0. apply le_mono. firstorder.\nQed.\n\n\nTheorem FraCaS058: (s_058_1_p)->(s_058_3_h).  cbv. destruct in_Prep as [inPrep inVerid].\ndestruct in_Prep as [within withinVerid].\nfirstorder. Abort All. (* 058 UNK *)\n\nTheorem FraCaS059: (s_059_1_p)->(s_059_3_h).\ncbv.\ndestruct from_Prep as [from fromVerid fromCov].\nfirstorder.\nrewrite -> H.\napply CARD_monotonous.\nfirstorder.\nQed.\n\nTheorem FraCaS060: (s_060_1_p)->(s_060_3_h).  cbv.\ndestruct from_Prep as [from fromVerid fromCov].\ndestruct southern_europe_PN as [southernEurope regionN].\nintros P1.\ngeneralize P1. apply le_mono'. firstorder.\nAbort All. (* UNK *)\n\nTheorem FraCaS061: (s_061_1_p)->(s_061_3_h).  cbv. firstorder. Qed.\n\nTheorem FraCaS062: (s_062_1_p)->not (s_062_3_h).\ncbv.\ndestruct part_Prep as [part partVerid partCov].\nfirstorder. (* FIXME: check the definition of 'neither' *) Abort All.\n\n\nTheorem FraCaS063: (s_063_1_p)->(s_063_3_h).\ncbv.\nintro P1.\ngeneralize P1. apply le_mono. firstorder.\nQed.\n\nTheorem FraCaS064: (s_064_1_p)->(s_064_3_h).  cbv.  destruct at_home_Adv. destruct at_home_Adv.  firstorder. (* UNK *)\n\n(* End of sec. 1.4 15/15 *)\n\n(* Sec. 1.5 *)\n\nTheorem FraCaS065: (s_065_1_p/\\s_065_2_p)->(s_065_4_h).  cbv. firstorder. (* UNK *)\n\nTheorem FraCaS066: s_066_1_p -> s_066_2_p -> s_066_4_h.\ncbv.\ndestruct europe_PN as [europe regionN].\ndestruct within_Prep as [within withinV withinC].\nintros P1 P2.\nfirstorder.\nQed.\n\nTheorem FraCaS067: (s_067_1_p/\\s_067_2_p)->(s_067_4_h). cbv.\ndestruct in_Prep as [inPrep inVerid].\ndestruct within_Prep as [within withinVerid].\nfirstorder.\nQed.\n\nTheorem FraCaS068: (s_068_1_p/\\s_068_2_p)->(s_068_4_h).  cbv. firstorder. Qed.\n\n\nVariable s_069_p_extra : forall cn x, (ComplVV (can_VV) (AdvVP (AdvVP (UseV (travel_V)) (PositAdvAdj (free_A))) (PrepNP (within_Prep) (UsePN (europe_PN))))) cn x -> (ComplSlash (SlashV2a (have_V2)) (DetCN (DetQuant (DefArt) (NumSg)) (SentCN (UseN (right_N)) (EmbedVP (AdvVP (UseV (live_V)) (PrepNP (in_Prep) (UsePN (europe_PN)))))))) cn x.\n\nTheorem FraCaS069: s_069_1_p -> s_069_2_p->(s_069_4_h).\nassert (P0 := s_069_p_extra).\ncbv in P0.\ncbv.\ndestruct in_Prep as [inPrep inVerid].\ndestruct within_Prep as [within withinVerid].\ndestruct major_A as [major].\ndestruct europe_PN as [europe countryN].\nintros [P1 [P1' [co0 [wcCo0 theResidentResidesinCo0]]]] P2.\nsplit.\nintro r.\nintros [co [[majorCo Co] rResidesInCo]].\napply (P0 (fun _ => True)).\napply P1.\nexists co.\nsplit.\nassumption.\nassumption.\nsplit.\napply (P0 (fun _ => True)).\napply P1.\nexists co0.\nsplit.\nassumption.\n(* FIXME: definite plural for the conclusion means that there must exist resident of major western countries. *) Abort All.\n\nTheorem FraCaS070: s_070_1_p->not(s_070_3_h). cbv. firstorder. Qed.\n\nTheorem FraCaS071: (s_071_1_p)->(s_071_3_h).  cbv. destruct on_time_Adv. firstorder. (* UNK *)\n\nTheorem FraCaS072: (s_072_1_p)->(s_072_3_h).  cbv. firstorder. (* UNK *)\n\nTheorem FraCaS073: (s_073_1_p)->(s_073_3_h).  cbv. destruct major_A as [major].\ndestruct in_Prep as [inPrep inVerid inVeridCov]. firstorder. (* UNK *)\n\nTheorem FraCaS074: s_074_1_p->not(s_074_3_h). cbv.\ndestruct outside_Prep as [outside outsideVerid].\ndestruct within_Prep as [within withinVerid].\nfirstorder. Abort All. (**UNK**)\n\nTheorem FraCaS075: s_075_1_p->(s_075_3_h). cbv.\ndestruct from_Prep as [from fromVerid fromCov].\nintro P1.\ndestruct P1.\nrewrite -> H.\napply CARD_monotonous.\nfirstorder.\n(* UNK *)\nAbort All.\n\nTheorem FraCaS076: s_076_1_p-> (s_076_3_h). cbv.\ndestruct from_Prep as [from fromVerid fromVeridCov].\ndestruct southern_europe_PN as [southernEurope regionN].\nintro P.\ngeneralize P. apply le_mono'. firstorder.\nQed.\n\nTheorem FraCaS077: s_077_1_p-> (s_077_3_h). cbv.\ndestruct in_Prep as [inPrep inVerid inVeridCov].\nintro.\nfirstorder.\nexists x. exists x0.\nfirstorder.\nAbort All.\n\nTheorem FraCaS078: s_078_1_p-> not(s_078_3_h). cbv.\ndestruct part_Prep as [inPrep inVerid inVeridCov].\nintro.\nfirstorder.\nAbort All.\n\nTheorem FraCaS079: s_079_1_p-> (s_079_3_h).\ncbv.\nintro P.\ngeneralize P. apply le_mono. firstorder.\n(* UNK *)\nAbort All.\n\nTheorem FraCaS080: (s_080_1_p)-> (s_080_3_h). cbv.\napply le_mono'. firstorder.\nQed.\n\n(* End of sec 1.5  13/14 in. *)\n(* End of sec 1.  71/75 in. *)\n\n(* SEC 2.1 Conjoined *)\n\n\nTheorem FraCaS081: (s_081_1_p)-> (s_081_3_h). cbv.\ndestruct jones_PN.\ndestruct smith_PN as [smith person'].\ndestruct anderson_PN as [anderson person''].\nfirstorder.\nQed.\n\nTheorem FraCaS082: (s_082_1_p)-> (s_082_3_h). cbv.\ndestruct jones_PN as [jones person].\ndestruct smith_PN as [smith person'].\nintro P1.\nfirstorder. Qed.\n\nTheorem FraCaS083: (s_083_1_p)-> (s_083_3_h).\ncbv.\ndestruct anderson_PN as [anderson person''].\nfirstorder.\nAbort All. \n(* UNK *)\n\nTheorem FraCaS084: (s_084_1_p)-> (s_084_3_h).\ncbv.\ndestruct jones_PN.\ndestruct smith_PN.\ndestruct anderson_PN as [andersson].\nintros P1 subj.\ndestruct P1 as [[S [nJ nA]] | H].\nfirstorder.\n(* FIXME: The reading of 'and' in the subjunctive clause is dual to what we need. *)\nAbort All.\n\nTheorem FraCaS085: (s_085_1_p)-> not(s_085_3_h). cbv.\nintros P1 H.\ndestruct P1 as [P].\n cut  (CARD\n        (fun x : object =>\n         lawyer_N x /\\ sign_V2 (environment contract_N) x /\\ contract_N (environment contract_N))\n    <= CARD\n         (fun x : object =>\n          (lawyer_N x \\/ accountant_N x) /\\\n          sign_V2 (environment contract_N) x /\\ contract_N (environment contract_N))).\n          intro Q.\nrewrite -> H0 in Q.\nrewrite -> H in Q.\nFocus 2.\napply CARD_monotonous.\nfirstorder.\n(* FIXME: Coq *)\n\nTheorem FraCaS086: (s_086_1_p)-> not(s_086_3_h). cbv.\nintros P1 H.\ndestruct P1 as [P].\n cut  (CARD\n        (fun x : object =>\n         accountant_N x /\\ sign_V2 (environment contract_N) x /\\ contract_N (environment contract_N))\n    <= CARD\n         (fun x : object =>\n          (lawyer_N x \\/ accountant_N x) /\\\n          sign_V2 (environment contract_N) x /\\ contract_N (environment contract_N))).\n          intro Q.\nrewrite -> H0 in Q.\nrewrite -> H in Q.\nFocus 2.\napply CARD_monotonous.\nfirstorder.\n(* FIXME: Coq *)\n\nTheorem FraCaS087: (s_087_1_p)-> (s_087_3_h). cbv.\ndestruct at_Prep as [atPrep atVerid].\nfirstorder. Abort All.\n(*\nFIXME\nEvery representative and client in this reading means\n\"Every representative and every client\"\nbut it seems that the parse tree says something else. Tricky.\n*)\n\nTheorem FraCaS088: (s_088_1_p)-> (s_088_3_h). cbv.\ndestruct at_Prep as [atPrep atVerid atCov].\nintro P1.\nintro x.\nassert (P1' := (P1 x)).\nintro isRepr.\nAbort All. (* UNK *)\n\nTheorem FraCaS089: (s_089_1_p)-> (s_089_3_h). cbv. firstorder. Qed.\n\n(* End of sec 2.1 7/9 *)\n\n(* SEC 2.2*)\n\n\nTheorem FraCaS090: (s_090_1_p)-> (s_090_3_h). cbv. firstorder.\nQed.\n\nTheorem FraCaS091: (s_091_1_p)-> (s_091_3_h). cbv.\ndestruct at_Prep as [atPrep atVerid atCov].\nfirstorder.\nexists x0.\nfirstorder.\nAbort All. (* UNK *)\n\nTheorem FraCaS092: (s_092_1_p) -> (s_092_3_h). cbv.\ndestruct at_Prep as [atPrep atVerid atCov].\nintro P1.\nintros x xAtMeeting.\napply P1.\nsplit.\ngeneralize xAtMeeting.\napply atVerid.\napply atCov with (v := person_N).\nintuition.\nassumption.\nQed.\n\nTheorem FraCaS093: (s_093_1_p) -> (s_093_3_h). cbv.\ndestruct at_Prep as [atPrep atVerid atCov].\nintro P1.\nintros x xAtMeeting.\napply P1.\nsplit.\ngeneralize xAtMeeting.\napply atVerid.\napply atCov with (v := person_N).\nintuition.\nassumption.\nQed.\n\nTheorem FraCaS094: (s_094_1_p) -> (s_094_3_h).\ncbv.\nfirstorder.\nQed. (* FIXME: definite plural has the wrong interpretation here. *)\n\nTheorem FraCaS095: (s_095_1_p) -> (s_095_3_h).\ncbv.\nfirstorder.\nQed. (* FIXME: definite plural has the wrong interpretation here. *)\n\nTheorem FraCaS096: s_096_1_p -> s_096_3_h.\ncbv.\nintro P1.\nfirstorder.\nQed.\n\n(* End of Sec 2.2 5/7 *)\n\n(* SEC 2.3 *)\n\nTheorem FraCaS097: (s_097_1_p) -> (s_097_3_h).  cbv. (* FIXME on_Prep must for_Prep be unrelated via passive voice; very hard. *) Abort All.\n\nTheorem FraCaS098: (s_098_1_p) -> (s_098_2_p) -> (s_098_4_h).\ncbv.\ndestruct for_Prep as [forPrep forVerid forCov].\ndestruct bug_32985_PN.\nfirstorder.\ngeneralize H1.\nAbort All. (* UNK *)\n\nDefinition s_099_1_p_fixed := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (AdvCN (UseN (client_N)) (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (demonstration_N)))))) (AdVVP (all_AdV) (UseComp (CompAP (ComplA2 (impressed_by_A2) (DetCN (DetQuant (GenNP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (system_N)))) (NumSg)) (UseN (performance_N)))))))))).\n\nVariable Impressed_cov_K : forall (impressor:object) (p q:CN), (forall x, p x -> q x) -> forall x, impressed_by_A2 impressor p x -> impressed_by_A2 impressor q x.\n\nVariable client_people_K : forall x, client_N x -> person_N x.\nTheorem FraCaS099: s_099_1_p_fixed -> (s_099_2_p) -> (s_099_4_h).\ncbv.\ndestruct at_Prep as [atPrep atVerid atCov].\ndestruct smith_PN.\nintros [P1 P1'] P2.\nassert (smithImpressed := P1 SMITH P2).\ndestruct smithImpressed as [[smithImpressed [ofSystem performance]] isSystem].\nsplit.\nsplit.\ngeneralize smithImpressed.\napply Impressed_cov_K.\nintro client.\nintro clientAtDemo.\napply client_people_K.\ngeneralize clientAtDemo.\napply atVerid.\nsplit.\nassumption.\nassumption.\nassumption.\nQed.\n\nDefinition s_100_1_p_fixed := (Sentence (UseCl (Past) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (AdvCN (UseN (client_N)) (PrepNP (at_Prep) (DetCN (DetQuant (DefArt) (NumSg)) (UseN (demonstration_N)))))) (UseComp (CompAP (ComplA2 (impressed_by_A2) (DetCN (DetQuant (GenNP (DetCN (DetQuant (DefArt) (NumSg)) (UseN (system_N)))) (NumSg)) (UseN (performance_N))))))))).\n\n\nTheorem FraCaS100: (s_100_1_p_fixed) -> (s_100_3_h). cbv.\ndestruct at_Prep as [atPrep atVerid atCov].\nintro P1.\ndestruct P1 as [clientImpressed clientAtDemo].\nsplit.\napply most_card_mono1.\nfirstorder.\nexists (environment\n          (atPrep\n             (fun k : object -> Prop =>\n                k (environment demonstration_N) /\\\n                demonstration_N (environment demonstration_N))\n             client_N)).\nfirstorder.\nQed.\n\n\nDefinition s_101_1_p_fixed := (Sentence (UseCl (Present) (PPos) (PredVP (DetCN (DetQuant (DefArt) (NumPl)) (UseN (university_graduate_N))) (ComplSlash (SlashV2a (make8become_V2)) (DetCN (DetQuant (IndefArt) (NumPl)) (AdjCN (PositA (poor8bad_A)) (UseN (stockmarket_trader_N)))))))). (* Use a definite article here. *)\n\nVariable likely_weakening_K : forall (p:CN) (x:object), p x -> apSubsectiveA likely_A p x.\n\nTheorem FraCaS101: s_101_1_p_fixed -> s_101_2_p -> (s_101_4_h).\ncbv.\ndestruct smith_PN.\nintros P1 P2.\napply likely_weakening_K.\nfirstorder.\nexact SMITH_PERSON.\nQed.\n\nTheorem FraCaS102: s_102_1_p -> s_102_2_p -> s_102_4_h.\ncbv.\nfirstorder.\nAbort All. (* UNK *)\n\n(* End of Sec 2.3 5/6 *)\n\n(* SEC 2.4 *)\n\n\nTheorem FraCaS103: s_103_1_p -> s_103_2_p -> (s_103_4_h).  cbv.\ndestruct jones_PN as [jones person].\ndestruct on_Prep as [on onVerid onCov].\nfirstorder. Qed.\n\nTheorem FraCaS104: s_104_1_p -> s_104_2_p -> s_104_4_h.\ncbv.\ndestruct jones_PN as [jones person].\nfirstorder.\nAbort All.\n(* UNK *)\n\n(* End of Sec 2.4 2/2 *)\n\n(* SEC 2.5 *)\n\nTheorem FraCaS105: s_105_1_p -> not s_105_3_h.\ncbv. firstorder.\ncut (exists x,\n         accountant_N x /\\\n         attend_V2 (environment meeting_N) x /\\ meeting_N (environment meeting_N)).\nintro ex.\nfirstorder.\napply CARD_exists.\nrewrite -> H.\nintuition.\nQed.\n\n\nTheorem FraCaS106: s_106_1_p -> not s_106_3_h. cbv. firstorder.\ncut (exists x,\n         accountant_N x /\\\n         attend_V2 (environment meeting_N) x /\\ meeting_N (environment meeting_N)).\nfirstorder.\napply CARD_exists.\nrewrite -> H.\nintuition.\nQed.\n\nTheorem FraCaS107: s_107_1_p -> s_107_3_h. cbv. firstorder.\napply CARD_exists.\nrewrite -> H.\nintuition.\nQed.\n\nTheorem FraCaS108: s_108_1_p -> s_108_3_h. cbv. firstorder.\napply CARD_exists.\nrewrite -> H.\nintuition.\nQed.\n\nTheorem FraCaS109: s_109_1_p -> s_109_3_h. cbv. firstorder.\nAbort All. (* FIXME: see comment in somePl_Det *)\n\nTheorem FraCaS110: s_110_1_p -> s_110_3_h. cbv. firstorder.\napply CARD_exists.\nrewrite -> H.\nintuition.\nQed.\n\n(* End of Sec 2.5 5/6 *)\n\n(* SEC 2.6 *)\n\nTheorem FraCaS111: s_111_1_p -> s_111_2_p -> s_111_4_h. cbv.\n(* FIXME: Anaphora: impossible *)\nAbort All.\n\nTheorem FraCaS112: s_112_1_p -> s_112_2_p -> s_112_4_h. cbv.\ndestruct jones_PN as [jones person].\ndestruct smith_PN as [smith person'].\nfirstorder.\nQed.\n\n(* 103 FIXME: Anaphora: impossible *)\n\n(* End of Sec 2.6 1/3 *)\n(* End of Sec 2. 25/33 *)\n\n(* SEC 5.1 *)\n\nTheorem FraCas197:s_197_1_p -> s_197_3_h. cbv.\ndestruct john_PN as [john person].\nfirstorder. Qed.\n\nTheorem FraCas198:s_198_1_p -> not s_198_3_h. cbv.\ndestruct john_PN as [john person].\ndestruct former_A as [former]. firstorder. Qed.\n\nTheorem FraCas199:s_199_1_p -> s_199_3_h. cbv. destruct successful_A as [successful].  destruct former_A as [former]. firstorder. (** FIXME: This is YES in the suite, but is says \"yes for a former university student\", which is not what the conclusion actually says. If we were to fix the conclusion then the example becomes trivial.\"**) Abort All.\n\nTheorem FraCas200:s_200_1_p -> s_200_3_h. cbv. firstorder.  destruct successful_A as [successful]. destruct former_A as [former]. firstorder. Abort All.  (**UNK**)\n\nTheorem FraCas201:s_201_1_p -> s_201_3_h. cbv. firstorder.  destruct successful_A as [successful]. destruct former_A as [former].  Abort All. (**UNK**)\n\n(* End of Sec 5.1 4/4, excluding 199 *)\n\nTheorem FraCas202:s_202_1_p -> s_202_3_h. cbv.  firstorder. Qed.\n\nTheorem FraCas203:s_203_1_p -> s_203_3_h. cbv. firstorder. Qed.\n\n(* End of Sec 5.2 2/2 *)\n\nTheorem FraCas204:s_204_1_p -> not s_204_3_h. cbv. intros.\napply small_and_large_disjoint_K with (cn := animal_N) (o := MICKEY).\ndestruct small_A.\ndestruct large_A.\nfirstorder. Qed.\n\nTheorem FraCas205:s_205_1_p -> not s_205_3_h. cbv. intros.\napply small_and_large_disjoint_K with (cn := animal_N) (o := DUMBO).\ndestruct small_A.\ndestruct large_A.\nfirstorder. Qed.\n\nTheorem FraCas206:s_206_1_p -> s_206_3_h. cbv. intros. Abort All. (* UNK *)\n\nTheorem FraCas207:s_207_1_p -> s_207_3_h. cbv. intros. Abort All. (* UNK *)\n\nTheorem FraCas208:s_208_1_p -> s_208_2_p -> s_208_4_h.\nassert (slK := small_and_large_disjoint_K).\ncbv.\ndestruct small_A as [small].\ndestruct large_A as [large].\nintros P1 P2.\nsplit.\ncbv in slK.\nfirstorder.\nintros NH SD.\nfirstorder.\nQed.\n\n\nTheorem FraCas209:s_209_1_p -> s_209_2_p -> not s_209_4_h. cbv.\nintros P1 P2 NH.\napply small_and_large_disjoint_K with (cn := animal_N) (o := MICKEY).\ndestruct small_A as [small].\ndestruct large_A as [large].\ncbv.\nfirstorder.\nQed.\n\n(* End of Sec 5.3 6/6 *)\n\nTheorem FraCas210:s_210_1_p -> s_210_2_p -> not s_210_4_h. cbv. intros.\napply small_and_large_disjoint_K with (cn := animal_N) (o := MICKEY).\ndestruct small_A.\ndestruct large_A.\nfirstorder.\nQed.\n\nTheorem FraCas211:s_211_1_p -> s_211_2_p -> not s_211_4_h.\ncbv.\nintros.\napply small_and_large_disjoint_K with (cn := animal_N) (o := DUMBO).\ndestruct small_A as [small].\ndestruct large_A as [large].\ncbv.\nfirstorder.\nQed.\n\nTheorem FraCas212:s_212_1_p -> s_212_2_p -> s_212_3_p -> s_212_4_p -> s_212_6_h.\nassert (slK := small_and_large_disjoint_K).\ncbv. cbv in slK.\ndestruct small_A as [small].\ndestruct large_A as [large].\nintros.\nfirstorder.\nQed.\n(* apply slK with (cn := animal_N) (o := MICKEY). *)\n\nTheorem FraCas213:s_213_1_p -> s_213_2_p -> s_213_4_h.\ncbv.\ndestruct small_A as [small].\ndestruct large_A as [large].\nintros.\nfirstorder.\nQed.\n\n(* End of Sec 5.4 3/3 *)\n\nTheorem FraCas214:s_214_1_p -> s_214_2_p -> s_214_4_h.\ncbv.\nintros.\ndestruct fat_A as [fat fatP].\nfirstorder.\nQed.\n\nTheorem FraCas215:s_215_1_p -> s_215_2_p -> s_215_4_h.\ncbv.\nintros P1 P2.\ndestruct competent_A as [competent].\nfirstorder.\n(* UNK *)\nAbort All.\n\nTheorem FraCas216:s_216_1_p -> s_216_3_h.\ncbv.\nintros P1.\ndestruct fat_A as [fat fatP].\ndestruct bill_PN as [bill].\ndestruct john_PN as [john].\ndestruct than_Prep as [than].\nfirstorder.\n(* FIXME: syntax wrong: should be\n   john is (fatter politician than bill)\n not\n   (john is fatter politician) than bill\n *)\nAbort All.\n\nTheorem FraCas217:s_217_1_p -> s_217_3_h.\ncbv.\n(* FIXME: syntax wrong, see 216 *)\nAbort All.\n\n(* End of Sec 5.5 3/4 *)\n\nTheorem FraCas218:s_218_1_p -> s_218_3_h. cbv.\ndestruct kim_PN as [kim person].\ndestruct clever_A.\nfirstorder.\nQed.\n\nTheorem FraCas219:s_219_1_p -> s_219_3_h. cbv.\ndestruct kim_PN as [kim person].\ndestruct clever_A.\nfirstorder.\nAbort All. (* UNK *)\n\n(* End of Sec 5.6 2/2 *)\n(* End of Sec 5 20/21 *)\n\nTheorem FraCas220: s_220_1_p -> s_220_2_p -> s_220_4_h.\ndestruct fast_A as [fast].\nfirstorder.\nQed.\n\nTheorem FraCas221:s_221_1_p -> s_221_3_h. cbv.\ndestruct fast_A as [fast].\nfirstorder.\nAbort All. (* UNK *)\n\nTheorem FraCas222: s_222_1_p -> s_222_2_p -> s_222_4_h.\ncbv.\ndestruct fast_A as [fast].\nfirstorder.\nAbort All. (* UNK *)\n\nVariable slow_and_fast_disjoint_K : forall cn o, getSubsectiveA slow_A cn o /\\ getSubsectiveA fast_A cn o -> False.\n\nTheorem FraCas223: s_223_1_p -> s_223_2_p -> not s_223_4_h.\ncbv.\nintros.\napply slow_and_fast_disjoint_K with (cn := computer_N) (o := PC6082).\ndestruct fast_A as [fast].\ndestruct slow_A as [slow].\ncbv.\nfirstorder.\nQed.\n\nTheorem FraCas224: s_224_1_p -> s_224_2_p -> s_224_4_h.\ncbv.\ndestruct fast_A as [fast].\nfirstorder.\nQed.\n\nTheorem FraCas225: s_225_1_p -> s_225_3_h.\ncbv.\ndestruct fast_A as [fast].\nfirstorder.\nAbort All. (* UNK *)\n\nTheorem FraCas226: s_226_1_p -> s_226_2_p -> s_226_4_h.\ncbv.\ndestruct fast_A as [fast].\nfirstorder.\nAbort All. (* UNK *)\n\nTheorem FraCas227: s_227_1_p -> s_227_2_p -> not s_227_4_h.\ncbv.\nintros.\napply slow_and_fast_disjoint_K with (cn := computer_N) (o := PC6082).\ndestruct fast_A as [fast].\ndestruct slow_A as [slow].\ncbv.\nfirstorder.\nQed.\n\nTheorem FraCas228: s_228_1_p -> s_228_3_h.\ncbv.\ndestruct fast_A as [fast].\nintro P1.\nfirstorder.\nAbort All. (* UNK *)\n\nInductive SpeedDec (o : object) : Type :=\n  isFast : getSubsectiveA fast_A computer_N o ->\n           not (getSubsectiveA slow_A computer_N o) -> SpeedDec o |\n  isSlow : not (getSubsectiveA fast_A computer_N o) ->\n           (getSubsectiveA slow_A computer_N o) -> SpeedDec o |\n  isNeither : not (getSubsectiveA fast_A computer_N o) ->\n              not (getSubsectiveA slow_A computer_N o) -> SpeedDec o.\n\nVariable decideSpeed_K : forall o, SpeedDec o.\n\nLemma slow_not_fast : forall cn o, apSubsectiveA slow_A cn o -> apSubsectiveA fast_A cn o -> False.\ncbv.\nintros.\napply slow_and_fast_disjoint_K with (cn := cn) (o := o).\ndestruct fast_A as [fast] eqn:fst.\ndestruct slow_A as [slow] eqn:slw.\ncbv.\nfirstorder.\nQed.\n\nTheorem FraCas229: s_229_1_p -> not s_229_3_h.\ncbv.\nintros P1 [NH1 NH2].\nassert (snf := slow_not_fast computer_N).\ncbv in snf.\ndestruct fast_A as [fast] eqn:fst.\ndestruct slow_A as [slow] eqn:slw.\ndestruct P1 as [P1a P1b].\napply NH2.\nintro slowPC.\nassert (notFastPC := (snf _ slowPC)).\n\n(* FIXME: ??? *)\n\nTheorem FraCaS230: s_230_1_p -> s_230_3_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\nintro P.\ndestruct P as [contract wonWhat].\nexists contract.\nfirstorder.\n(*FIXME *)\nAbort All.\n\nTheorem FraCaS231: s_231_1_p -> s_231_3_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\nintro P.\n(* UNK *)\nAbort All.\n\nTheorem FraCaS232: s_232_1_p -> s_232_2_p -> s_232_4_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\nintros P1 P2.\n(*FIXME: than_Subj; elliptic_VP missing *)\nAbort All.\n\nTheorem FraCaS233: s_233_1_p -> s_233_3_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\ndestruct than_Prep as [than thanVerid thanCov].\nintro P.\ndestruct P as [order [moreThanApcom wonWhat]].\nexists order.\nsplit.\nassert (H := (thanVerid _ _ _ moreThanApcom )).\ncbv in H.\ndestruct H.\nassumption.\nassumption.\nQed.\n\nTheorem FraCaS234: s_234_1_p -> s_234_3_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\ndestruct than_Prep as [than thanVerid thanCov].\nintro P.\ndestruct P as [order [moreThanApcom wonWhat]].\nexists order.\nsplit.\nassert (H := (thanVerid _ _ _ moreThanApcom )).\ncbv in H.\ndestruct H.\nassumption.\nAbort All. (* UNK *)\n\nTheorem FraCaS235: s_235_1_p -> s_235_2_p -> s_235_4_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\ndestruct than_Prep as [than thanVerid thanCov].\n(* FIXME: than_Prep not correctly handled *)\nAbort All.\n\nTheorem FraCaS236: s_236_1_p -> s_236_3_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\ndestruct than_Prep as [than thanVerid thanCov].\nintro P.\ndestruct P as [order [moreThanApcom wonWhat]].\nsplit.\n(* FIXME: syntax of \"more than \" not precise enough *)\nAbort All.\n\nVariable exists_CARD : forall P:(object -> Prop), (exists x, P x) -> 1 <= CARD P.\n\nTheorem FraCaS237: s_237_1_p -> s_237_3_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\ndestruct than_Prep as [than thanVerid thanCov].\nintro P.\ndestruct P as [order [moreThanApcom wonWhat]].\nassert (H := (thanVerid _ _ _ moreThanApcom )).\ncbv in H.\napply exists_CARD.\nfirstorder.\nQed.\n\nTheorem FraCaS238: s_238_1_p -> s_238_2_p -> s_238_4_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\ndestruct than_Prep as [than thanVerid thanCov].\nintro.\n(* FIXME: syntax of \"more than \" not precise enough *)\nAbort All.\n\n(* End of sec 6.1 13/19 *)\n\nTheorem FraCaS239: s_239_1_p -> s_239_3_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\nintro P.\nAbort All. (* FIXME: Than is elliptic *)\n\nTheorem FraCaS240: s_240_1_p -> s_240_3_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\nintro P.\nAbort All. (* UNK *)\n\nTheorem FraCaS241: s_241_1_p -> s_241_2_p -> s_241_4_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\nintros P1 P2.\n(* FIXME: We could not get the P2 to be used as an equality. But the real problem is that we do not get the implication\n CARD (fun x : object => order_N x /\\ win_V2 x itel) > CARD (fun x : object => order_N x /\\ lose_V2 x apcom) \n*)\nAbort All.\n\n(* End of sec 6.2 1/3 *)\n\nTheorem FraCaS242: s_242_1_p -> s_242_2_p -> s_242_4_h.\ncbv.\ndestruct slow_A as [slow].\ndestruct fast_A as [fast].\nintro P1.\nintro P2.\n(* FIXME: Completely wrong semantics: the 500 is interpreted as a definite plural. (Then there are more real problems even if that would be fixed.) *)\nAbort All.\n\n(* End of sec 6.3 0/1 *)\n\nTheorem FraCaS243: s_243_1_p -> s_243_2_p -> s_243_4_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\nintros P1 P2.\ndestruct than_Prep as [than].\n(* FIXME: we would need a specific semantics for the prep. \"than\" when applied to a \"many\" CN. More realistic: fix the syntax. *)\nAbort All.\n\n(* End of sec 6.4 0/1 *)\n\nTheorem FraCaS244: s_244_1_p->s_244_3_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\nintro P1.\ndestruct than_Prep as [than].\n(* FIXME: we would need a specific semantics for the prep. \"than\" when applied to a \"many\" CN. More realistic: fix the syntax. Also more problems: than_Subj, elliptic. *)\nAbort All.\n\nTheorem FraCaS245: s_245_1_p->s_245_3_h.\ncbv.\ndestruct itel_PN as [itel].\ndestruct apcom_PN as [apcom].\nintro P1.\ndestruct than_Prep as [than].\n(* FIXME: we would need a specific semantics for the prep. \"than\" when applied to a \"many\" CN. More realistic: fix the syntax. Also more problems: than_Subj, elliptic. *)\nAbort All.\n\n(* End of sec 6.5 0/2 *)\n\n(* SEC 6.6 *)\n\nTheorem FraCaS246: s_246_1_p -> s_246_2_p -> s_246_4_h.\ncbv.\ndestruct fast_A as [fast] eqn:fst.\nintros.\nfirstorder.\nQed.\n\nTheorem FraCaS247: s_247_1_p -> s_247_2_p -> s_247_4_h.\ncbv.\ndestruct fast_A as [fast] eqn:fst.\nfirstorder.\nAbort All. (* UNK *)\n\nTheorem FraCaS248: s_248_1_p -> s_248_2_p -> s_248_4_h.\ncbv.\nintros.\ndestruct fast_A as [fast] eqn:fst.\nfirstorder.\nQed.\n\nTheorem FraCaS249: s_249_1_p -> s_249_3_h.\ncbv.\nintros.\ndestruct fast_A as [fast] eqn:fst.\ndestruct H as [zx zy].\nfirstorder.\nAbort All.\n(* FIXME: wrong semantics for 'and' in combination with 'the' *)\n\nTheorem FraCaS250: s_250_1_p -> s_250_3_h.\ncbv.\ndestruct fast_A as [fast] eqn:fst.\n(* FIXME: try this *)\n\n(* End of sec 6.6 3/5 *)\n(* End of sec 6 17/31 *)\n\n(* SEC 7\nTheorem FraCaS306: s_306_1_p  -> s_306_3_h.\ncbv.\ndestruct smith_PN as [smith person'].\ndestruct for_two_years_Adv. firstorder.\nQed.\n*)\n\n(* SEC 8 *)\n\nTheorem FraCaS326: s_326_1_p -> s_326_3_h. cbv.\ndestruct itel_PN.\ndestruct mtalk_PN.\ndestruct in_1993_Adv as [in93].\n(* FIXME: handling tense at the proposition level is difficult. Additionally, the Q has an anaphoric ellpsis (we mean finish building, not (say) finish destroying.) *)\n\nTheorem FraCaS327: s_327_1_p -> s_327_3_h. cbv.\ndestruct itel_PN.\ndestruct mtalk_PN.\ndestruct in_1993_Adv as [in93].\n(* Progressive prevents getting to the conclusion. *)\n(* UNK *)\nAbort All.\n\nTheorem FraCaS328: s_328_1_p -> s_328_3_h. cbv.\ndestruct from_Prep as [from fromVerid fromCov].\ndestruct in_1993_Adv as [in93 [in93Verid in93Covariant]].\ndestruct itel_PN as [itel corpN itelIsCorp].\ndestruct apcom_PN as [apcom corpN' apcomIsCorp].\napply in93Covariant.\nintro contract.\nintro fromApcom.\nassert (H := (fromVerid _ _ _ fromApcom )).\nfirstorder.\nQed.\n\nTheorem FraCaS329: s_329_1_p -> s_329_3_h. cbv.\ndestruct itel_PN.\ndestruct mtalk_PN.\ndestruct in_1993_Adv as [in93].\ndestruct apcom_PN as [apcom corpN' apcomIsCorp].\ndestruct from_Prep as [from fromVerid fromCov].\n(* Progressive prevents getting to the conclusion. *)\n(* UNK *)\nAbort All.\n\n\nVariable year90_included_in_88_to_92_K : forall (p:object -> Prop) (x:object), from_1988_to_1992_Adv p x -> (let (a, _) := in_1990_Adv in a) p x.\n\nTheorem FraCaS330: s_330_1_p -> s_330_3_h. cbv.\ndestruct itel_PN.\ndestruct mtalk_PN.\ndestruct apcom_PN as [apcom corpN' apcomIsCorp].\napply year90_included_in_88_to_92_K.\nQed.\n\nTheorem FraCaS331: s_331_1_p -> s_331_3_h. cbv.\nfirstorder.\nQed.\n\nTheorem FraCaS332: s_332_1_p -> s_332_3_h. cbv. destruct jones_PN as [jones person].\ndestruct smith_PN as [smith person'].\n intros. firstorder.\nQed.\n\nTheorem FraCaS333: s_333_1_p -> s_333_3_h.\n(* FIXME: no notion of group*)\nAbort All.\n\n(* End of SEC 8: 6/8 *)\n\n(* SEC 9.1 *)\n\nVariable know_veridical_K : forall (x:object) (xClass:CN) (p:S), know_VS p xClass x -> p.\n\nTheorem FraCaS334: s_334_1_p -> s_334_3_h.\ncbv.\ndestruct jones_PN as [jones person].\ndestruct smith_PN as [smith person'].\ndestruct itel_PN as [itel corpN].\napply know_veridical_K.\nQed.\n\nTheorem FraCaS335: s_335_1_p -> s_335_3_h.\ncbv.\nAbort All. (* UNK *)\n\nVariable manageTo_veridical_K : forall (x:object) (xClass:CN) (p:VP), manage_VV p x -> p xClass x.\n\nTheorem FraCaS336: s_336_1_p -> s_336_3_h.\ncbv.\ndestruct in_1992_Adv as [in92].\ndestruct itel_PN as [itel corpN]. \n(* FIXME: adverbs not covariant. *)\nAbort All.\n\n\nTheorem FraCaS337: s_337_1_p -> s_337_3_h.\ncbv.\ndestruct itel_PN as [itel corpN]. \nfirstorder.\nAbort all. (*UNK*)\n\nTheorem FraCaS338: s_338_1_p -> s_338_3_h.\ncbv.\ndestruct itel_PN as [itel corpN].\nfirstorder.\nQed.\n\nTheorem FraCaS339: s_339_1_p -> not s_339_3_h.\ncbv.\ndestruct itel_PN as [itel corpN].\ndestruct false_A as [false].\nfirstorder.\nQed.\n\nVariable see_veridical_K : forall (dobject subject :object) (p:VP), see_V2V dobject p subject -> p (fun _ => True) dobject. (* IMPROVEMENT: not excellent because we lost the class of dobject. *)\n\n\nTheorem FraCaS340: s_340_1_p/\\s_340_2_p -> s_340_4_h.\n cbv.\n destruct jones_PN as [jones person].\n destruct smith_PN as [smith person'].\n firstorder.\nAbort all. (*UNK*)\n\n\nTheorem FraCaS341: s_341_1_p/\\s_341_2_p -> s_341_4_h.\n cbv.\n destruct jones_PN as [jones person].\n destruct smith_PN as [smith person'].\n firstorder.\nAbort all. (*UNK*)\n\n\nTheorem FraCaS342: s_342_1_p -> s_342_3_h.\ncbv.\ndestruct jones_PN as [jones person].\ndestruct smith_PN as [smith person'].\ndestruct itel_PN as [itel corpN].\napply see_veridical_K.\nQed.\n\nTheorem FraCaS343: ((s_343_1_p)/\\(s_343_2_p))->(s_343_4_h).\ncbv.\ndestruct jones_PN as [jones person].\ndestruct smith_PN as [smith person'].\ndestruct itel_PN as [itel corporation].\nfirstorder.\nrewrite <- H0.\nfirstorder.\nQed.\n\nTheorem FraCaS344: ((s_344_1_p)/\\(s_344_2_p))->(s_344_4_h).\ncbv.\ndestruct helen_PN as [helen person].\nfirstorder.\nQed.\n\nTheorem FraCaS345: s_345_1_p -> s_345_3_h.\ncbv.\ndestruct smith_PN as [smith person'].\ndestruct jones_PN as [jones person].\nfirstorder.\nQed.\n\nTheorem FraCaS346: s_346_1_p -> s_346_3_h.\ncbv.\n(* FIXME: the syntax has an ellipsis, and additionally the semantics for \"either\" do not match the semantics for \"or\" *)\nAbort All.\n\n(* end of sec 9. 11/13 *)\n", "meta": {"author": "StergiosCha", "repo": "CoqNL", "sha": "cb1c929ac45d4b447de66b6a8bc90d5da06c6c9c", "save_path": "github-repos/coq/StergiosCha-CoqNL", "path": "github-repos/coq/StergiosCha-CoqNL/CoqNL-cb1c929ac45d4b447de66b6a8bc90d5da06c6c9c/Code/Tutorial3_FraCoq_and_more/FraCoq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.24070064830150537}}
{"text": "(** Heavily annotated for a tutorial introduction. *)\n\n(** First, import the entire Floyd proof automation system, which includes\n ** the VeriC program logic and the MSL theory of separation logic**)\nRequire Import VST.floyd.proofauto.\n\n(** Import the [reverse.v] file, which is produced by CompCert's clightgen\n ** from reverse.c.   The file reverse.v defines abbreviations for identifiers\n ** (variable names, etc.) of the C program, such as _head, _reverse.\n ** It also defines \"prog\", which is the entire abstract syntax tree\n ** of the C program *)\nRequire Import VST.progs.reverse.\n\n(* The C programming language has a special namespace for struct\n** and union identifiers, e.g., \"struct foo {...}\".  Some type-based operators\n** in the program logic need access to an interpretation of this namespace,\n** i.e., the meaning of each struct-identifier such as \"foo\".  The next\n** line (which looks identical for any program) builds this\n** interpretation, called \"CompSpecs\" *)\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\n\n(** Calculate the \"types-of-global-variables\" specification\n ** directly from the program *)\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n(** A convenience definition *)\nDefinition t_struct_list := Tstruct _list noattr.\n\n(** Inductive definition of linked lists *)\nFixpoint listrep (sigma: list val) (x: val) : mpred :=\n match sigma with\n | h::hs => \n    EX y:val, \n      data_at Tsh t_struct_list (h,y) x  *  listrep hs y\n | nil => \n    !! (x = nullval) && emp\n end.\n\nFixpoint lsegrec (sigma: list val) (x z: val) : mpred :=\n match sigma with\n | h::hs => \n    EX y:val, \n      data_at Tsh t_struct_list (h,y) x  *  lsegrec hs y z\n | nil => \n    !! (x = z) && emp\n end.\n\n(* This file is only to demonstrate object language induction. *)\n\n(* induction rule *)\n\nLemma list_ind_in_logc: forall {A: Type} (P: mpred) (Q: list A -> mpred),\n  (P |-- Q nil) ->\n  (P |-- ALL a: A, (ALL l: list A, Q l --> Q (a :: l))) ->\n  P |-- ALL l: list A, Q l.\nProof.\n  intros.\n  apply allp_right; intro l.\n  induction l; auto.\n  rewrite (add_andp _ _ IHl), (add_andp _ _ H0).\n  apply imp_andp_adjoint.\n  apply andp_left2.\n  apply (allp_left _ a).\n  apply (allp_left _ l).\n  auto.\nQed.\n\n(* application *)\n\nLemma listrep2lsegrec: forall l x,\n  listrep l x |-- lsegrec l x nullval.\nProof.\n  assert (emp |-- ALL l: list val, (ALL x: val, listrep l x -* lsegrec l x nullval)).\n  + apply list_ind_in_logc.\n    - apply allp_right; intros.\n      apply wand_sepcon_adjoint.\n      rewrite emp_sepcon.\n      simpl.\n      apply derives_refl.\n    - apply allp_right; intros a.\n      apply allp_right; intros l.\n      apply imp_andp_adjoint.\n      apply allp_right; intros x.\n      apply andp_left2.\n      apply wand_sepcon_adjoint.\n      simpl.\n      Intros y.\n      Exists y.\n      apply wand_sepcon_adjoint.\n      apply (allp_left _ y).\n      apply wand_sepcon_adjoint.\n      cancel.\n      apply wand_sepcon_adjoint.\n      apply derives_refl.\n  + intros.\n    rewrite <- (emp_sepcon (listrep _ _)).\n    apply wand_sepcon_adjoint.\n    eapply derives_trans; [exact H | clear H].\n    apply (allp_left _ l).\n    apply (allp_left _ x).\n    apply derives_refl.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/verif_reverse3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24070064830150534}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom extructures Require Import ord fset fmap.\nFrom CoqUtils Require Import hseq word.\n\nRequire Import lib.utils.\nRequire Import common.types.\nRequire Import concrete.concrete.\nRequire Import concrete.exec.\nRequire Import symbolic.symbolic.\nRequire Import symbolic.exec.\nRequire Import symbolic.rules.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nHint Constructors restricted_exec.\nHint Unfold exec.\nHint Resolve restricted_exec_trans.\n\nSection Refinement.\n\nContext {mt : machine_types}\n        {ops : machine_ops mt}\n        {opss : machine_ops_spec ops}\n        {sp : Symbolic.params}\n        {e : encodable mt Symbolic.ttypes}.\n\nDefinition refine_memory (amem : Symbolic.memory mt _) (cmem : Concrete.memory mt) :=\n  (forall w x ctg atg,\n     decode Symbolic.M cmem ctg = Some (User atg) ->\n     cmem w = Some x@ctg ->\n     amem w = Some x@atg) /\\\n  (forall w x atg,\n     amem w = Some x@atg ->\n     exists2 ctg,\n       decode Symbolic.M cmem ctg = Some (User atg) &\n       cmem w = Some x@ctg).\n\nDefinition refine_registers (areg : Symbolic.registers mt _)\n                            (creg : Concrete.registers mt)\n                            (cmem : Concrete.memory mt) :=\n  (forall r x ctg atg,\n     decode Symbolic.R cmem ctg = Some atg ->\n     creg r = Some x@ctg ->\n     areg r = Some x@atg) /\\\n  (forall r x atg,\n     areg r = Some x@atg ->\n     exists2 ctg,\n       decode Symbolic.R cmem ctg = Some atg &\n       creg r = Some x@ctg).\n\nDefinition in_monitor (st : Concrete.state mt) :=\n  Concrete.is_monitor_tag (Concrete.pct st).\nHint Unfold in_monitor.\n\nDefinition in_user st : bool :=\n  decode Symbolic.P (Concrete.mem st) (Concrete.pct st).\nHint Unfold in_user.\n\nDefinition cache_correct cache cmem :=\n  forall cmvec crvec,\n    Concrete.cache_lookup cache masks cmvec = Some crvec ->\n    decode Symbolic.P cmem (Concrete.ctpc cmvec) ->\n    exists ivec ovec,\n      [/\\ decode_ivec e cmem cmvec = Some ivec,\n          decode_ovec e (Symbolic.op ivec) cmem crvec = Some ovec &\n          Symbolic.transfer ivec = Some ovec ].\n\nDefinition in_mvec addr := addr \\in Concrete.mvec_fields mt.\n\nDefinition mvec_in_monitor (cmem : Concrete.memory mt) :=\n  forall addr,\n    in_mvec addr ->\n    exists w : mword mt, cmem addr = Some w@Concrete.TMonitor.\n\nLemma store_mvec_mvec_in_monitor cmem mvec :\n  mvec_in_monitor (Concrete.store_mvec cmem mvec).\nProof.\nmove=> k; rewrite /Concrete.store_mvec unionmE.\nset m := mkfmap _.\nrewrite -mem_domm domm_mkfmap /in_mvec /Concrete.mvec_fields.\nmove=> E; rewrite E; have: k \\in domm m by rewrite domm_mkfmap.\nrewrite mem_domm {E}; case E: (m k) => [v|] // _.\nmove/mkfmap_Some: E; rewrite !inE.\ndo !(case/orP=> [/eqP [_ ->]|]; eauto).\nby move/eqP => [_ ->]; eauto.\nQed.\n\n(* CH: I find the way the \"monitor invariant\" is stated rather\n   indirect. Is there no direct way to define this? *)\n(* AAA: We need to add the cache as an argument here, since we don't\n   assume anything about ground rules right now *)\n\nRecord monitor_invariant : Type := {\n  monitor_invariant_statement :> Concrete.memory mt ->\n                                Concrete.registers mt ->\n                                Concrete.rules mt ->\n                                Symbolic.internal_state -> Prop;\n\n  monitor_invariant_upd_mem :\n    forall regs mem1 mem2 cache addr w1 ct ut w2 int\n           (MINV : monitor_invariant_statement mem1 regs cache int)\n           (GET : mem1 addr = Some w1@ct)\n           (DEC : decode Symbolic.M mem1 ct = Some (User ut))\n           (UPD : updm mem1 addr w2 = Some mem2),\n      monitor_invariant_statement mem2 regs cache int;\n\n  monitor_invariant_upd_reg :\n    forall mem regs1 regs2 cache r w1 ct1 ut1 w2 ct2 ut2 int\n           (MINV : monitor_invariant_statement mem regs1 cache int)\n           (GET : regs1 r = Some w1@ct1)\n           (DEC1 : decode Symbolic.R mem ct1 = Some ut1)\n           (UPD : updm regs1 r w2@ct2 = Some regs2)\n           (DEC2 : decode Symbolic.R mem ct2 = Some ut2),\n      monitor_invariant_statement mem regs2 cache int;\n\n  monitor_invariant_store_mvec :\n    forall mem mvec regs cache int\n           (MINV : monitor_invariant_statement mem regs cache int),\n      monitor_invariant_statement (Concrete.store_mvec mem mvec)\n                                 regs cache int\n}.\n\nHint Resolve monitor_invariant_upd_mem.\nHint Resolve monitor_invariant_upd_reg.\nHint Resolve monitor_invariant_store_mvec.\n\nVariable mi : monitor_invariant.\n\nLemma in_user_in_monitor :\n  forall st, in_user st -> ~~ in_monitor st.\nProof.\n  move=> st.\n  rewrite /in_user /in_monitor /Concrete.is_monitor_tag.\n  apply contraTN=> /eqP ->.\n  by rewrite decode_monitor_tag.\nQed.\n\nVariable table : Symbolic.syscall_table mt.\n\nDefinition is_nop (i : mword mt) : bool :=\n  match decode_instr i with\n  | Some Nop => true\n  | _ => false\n  end.\n\nLemma is_nopP : forall i, is_nop i <-> decode_instr i = Some (Nop _).\nProof.\n  rewrite /is_nop.\n  move => i.\n  by case: (decode_instr i) => [[]|] //=.\nQed.\n\nDefinition wf_entry_points (cmem : Concrete.memory mt) :=\n  forall addr t,\n    (exists2 sc, table addr = Some sc &\n                 Symbolic.entry_tag sc = t) <->\n    is_true match cmem addr with\n            | Some i@it => is_nop i && (decode Symbolic.M cmem it == Some (Entry t))\n            | None => false\n            end.\n\nLemma wf_entry_points_if cmem addr sc :\n  wf_entry_points cmem ->\n  table addr = Some sc ->\n  exists i it,\n  [/\\ cmem addr = Some i@it,\n      decode Symbolic.M cmem it = Some (Entry (Symbolic.entry_tag sc)) &\n      is_nop i ].\nProof.\n  move => WFENTRYPOINTS GETCALL.\n  have: exists2 sc', table addr = Some sc' &\n                     Symbolic.entry_tag sc' = Symbolic.entry_tag sc by eauto.\n  move/WFENTRYPOINTS.\n  case: (cmem addr) => [[i it]|] //.\n  move/andP => [H1 H2]. exists i, it.\n  split; trivial.\n  by apply/eqP.\nQed.\n\nLemma wf_entry_points_only_if cmem addr i it t :\n  wf_entry_points cmem ->\n  cmem addr = Some i@it ->\n  decode Symbolic.M cmem it = Some (Entry t) ->\n  is_nop i ->\n  exists2 sc,\n    table addr = Some sc &\n    Symbolic.entry_tag sc = t.\nProof.\n  move => WF GET DEC ISNOP.\n  apply/WF.\n  by rewrite GET DEC eqxx andbT.\nQed.\n\nLemma entry_point_undefined cmem smem addr v it t :\n  refine_memory smem cmem ->\n  cmem addr = Some v@it ->\n  decode Symbolic.M cmem it = Some (Entry t) ->\n  smem addr = None.\nProof.\n  move => REFM GET DEC.\n  case GET': (smem addr) => [[v' t']|] //.\n  move/(proj2 REFM): GET'.\n  rewrite GET. case=> it' H1 [? ?]. subst v' it'. congruence.\nQed.\n\nInductive refine_state (sst : Symbolic.state mt) (cst : Concrete.state mt) : Prop := RefineState {\n  rs_pc : Symbolic.pcv sst = Concrete.pcv cst;\n  rs_pct : decode Symbolic.P (Concrete.mem cst) (Concrete.pct cst) =\n           Some (Symbolic.pct sst);\n  rs_refm : refine_memory (Symbolic.mem sst) (Concrete.mem cst);\n  rs_refr : refine_registers (Symbolic.regs sst) (Concrete.regs cst) (Concrete.mem cst);\n  rs_cache : cache_correct (Concrete.cache cst) (Concrete.mem cst);\n  rs_mvec : mvec_in_monitor (Concrete.mem cst);\n  rs_entry_points : wf_entry_points (Concrete.mem cst);\n  rs_minv : mi (Concrete.mem cst) (Concrete.regs cst)\n               (Concrete.cache cst) (Symbolic.internal sst)\n}.\n\nLemma refine_state_in_user sst cst :\n  refine_state sst cst ->\n  in_user cst.\nProof.\n  case=> ? DEC *.\n  by rewrite /in_user DEC.\nQed.\n\nLemma refine_memory_upd cache aregs cregs amem cmem cmem' addr v v' ct t ct' t' :\n  cache_correct cache cmem ->\n  refine_registers aregs cregs cmem ->\n  refine_memory amem cmem ->\n  cmem addr = Some v@ct ->\n  decode Symbolic.M cmem ct = Some (User t) ->\n  updm cmem addr v'@ct' = Some cmem' ->\n  decode Symbolic.M cmem ct' = Some (User t') ->\n  exists amem',\n    [/\\ updm amem addr v'@t' = Some amem',\n        cache_correct cache cmem',\n        refine_registers aregs cregs cmem' &\n        refine_memory amem' cmem'].\nProof.\n  move=> Hcache Hregs Hmem Hget Hdec Hupd Hdec'.\n  have Hget' := proj1 Hmem _ _ _ _ Hdec Hget.\n  move: Hupd; rewrite /updm Hget Hget' /= => - [<-].\n  have Hdec_eq := decode_monotonic v' _ Hget Hdec Hdec'.\n  eexists; split; trivial.\n  - move=> cmvec crvec Hlookup.\n    case Hdec_pc: (decode _ _ _) => [pct|] //= Hpct_user.\n    rewrite Hdec_eq in Hdec_pc.\n    have := Hcache cmvec crvec Hlookup.\n    rewrite Hdec_pc => /(_ Hpct_user) [ivec [ovec [Hdec_ivec Hdec_ovec Htrans]]].\n    rewrite -(decode_ivec_monotonic v' Hget Hdec Hdec') in Hdec_ivec.\n    rewrite -(decode_ovec_monotonic _ v' Hget Hdec Hdec') in Hdec_ovec.\n    by eauto using And3.\n  - split.\n    + move=> w x ct'' st'' Hdec_ct' Hget''.\n      rewrite Hdec_eq in Hdec_ct'.\n      by eapply (proj1 Hregs); eauto.\n    + move=> w x st'' /(proj2 Hregs _ _ _) [ct'' Hdec_ct'' Hget''].\n      rewrite -Hdec_eq in Hdec_ct''.\n      by eauto.\n  - split.\n    + move=> w x ct'' st'' Hdec_ct' Hget''.\n      rewrite Hdec_eq in Hdec_ct'.\n      move: Hget''; rewrite !setmE.\n      have [Heq|Hneq] := w =P addr.\n      * subst w; move=> [? ?]; subst.\n        by move: Hdec_ct'; rewrite Hdec' => -[->].\n      * by eapply (proj1 Hmem); eauto.\n    + move=> w x st Hget''; move: Hget'' Hdec_eq; rewrite /updm !setmE.\n      have [_ {w}|Hneq] := altP (w =P addr).\n        move => [-> Ht]; eexists ct'=> //.\n        by rewrite Hdec_eq Hdec' Ht.\n      move=> Hget''.\n      have [ct'' Hdec_ct'' Hget_ct''] := proj2 Hmem _ _ _ Hget''.\n      rewrite Hget_ct''=> Hdec''; eexists ct''=> //.\n      by rewrite Hdec''.\nQed.\n\nLemma wf_entry_points_user_upd cmem cmem' addr v v' ct t ct' t' :\n  wf_entry_points cmem ->\n  cmem addr = Some v@ct ->\n  decode Symbolic.M cmem ct = Some (User t) ->\n  updm cmem addr v'@ct' = Some cmem' ->\n  decode Symbolic.M cmem ct' = Some (User t') ->\n  wf_entry_points cmem'.\nProof.\nmove=> Hwf Hget Hdec Hupd Hdec' addr' t''; rewrite Hwf.\nhave := decode_monotonic _ _ Hget Hdec Hdec'.\nmove: Hupd; rewrite /updm Hget /= => - [<-] {cmem'} Hmono.\nrewrite setmE.\nhave [-> {addr'}|_] := altP (addr' =P addr).\n  by rewrite Hget !Hmono Hdec Hdec' !andbF.\ncase: (cmem addr') => [[i ti]|] //.\n  by rewrite Hmono.\nQed.\n\nLemma mvec_in_monitor_user_upd cmem cmem' addr v v' ct t ct' t' :\n  mvec_in_monitor cmem ->\n  cmem addr = Some v@ct ->\n  decode Symbolic.M cmem ct = Some (User t) ->\n  updm cmem addr v'@ct' = Some cmem' ->\n  decode Symbolic.M cmem ct' = Some (User t') ->\n  mvec_in_monitor cmem'.\nProof.\n  intros MVEC GET DEC UPD DEC'.\n  intros addr' H.\n  specialize (MVEC addr' H). destruct MVEC as [w' KER].\n  assert (NEQ : addr' <> addr).\n  { intros E. subst addr'.\n    have CONTRA : Concrete.TMonitor = ct by congruence. subst ct.\n    by rewrite decode_monitor_tag in DEC. }\n  move: UPD; rewrite /updm GET /= => - [<-].\n  by rewrite setmE (introF eqP NEQ) KER; eauto.\nQed.\n\nLemma mvec_in_monitor_monitor_upd cmem cmem' addr w :\n  mvec_in_monitor cmem ->\n  updm cmem addr w@Concrete.TMonitor = Some cmem' ->\n  mvec_in_monitor cmem'.\nProof.\nintros MVEC UPD addr' IN.\nmove: UPD; rewrite /updm; case: (cmem _) => //= _ [<-].\nrewrite setmE.\nby have [?|/eqP NEQ] := altP (addr' =P addr); simpl in *; subst; eauto.\nQed.\n\nLemma refine_memory_upd' cache aregs cregs amem amem' cmem addr v ct t :\n  cache_correct cache cmem ->\n  refine_registers aregs cregs cmem ->\n  refine_memory amem cmem ->\n  updm amem addr v@t = Some amem' ->\n  decode Symbolic.M cmem ct = Some (User t) ->\n  exists cmem',\n    [/\\ updm cmem addr v@ct = Some cmem',\n        cache_correct cache cmem',\n        refine_registers aregs cregs cmem' &\n        refine_memory amem' cmem' ].\nProof.\n  move=> Hcache Hregs Hmem Hupd Hdec.\n  have [[x t'] Hget] : exists a, amem addr = Some a.\n    by move: Hupd; rewrite /updm; case: (amem _); eauto.\n  have [ct' Hdec' Hget'] := proj2 Hmem _ _ _ Hget.\n  have Hupd' : updm cmem addr v@ct = Some (setm cmem addr v@ct).\n    by rewrite /updm Hget'.\n  have Hdec_eq := decode_monotonic v _ Hget' Hdec' Hdec.\n  rewrite Hupd'. eexists. split; eauto.\n  - move=> cmvec crvec Hlookup.\n    rewrite Hdec_eq.\n    move=> /(Hcache _ _ Hlookup) [ivec [ovec [Hdec_i Hdec_o Htrans]]].\n    rewrite -(decode_ivec_monotonic v Hget' Hdec' Hdec) in Hdec_i.\n    rewrite -(decode_ovec_monotonic _ v Hget' Hdec' Hdec) in Hdec_o.\n    by eauto using And3.\n  - split.\n    + move=> r x'' ct'' st'' Hdec_ct'' Hget''.\n      rewrite Hdec_eq in Hdec_ct''.\n      by apply (proj1 Hregs _ _ _ _ Hdec_ct'' Hget'').\n    + move=> r x'' st'' /(proj2 Hregs) [ct'' Hdec_ct'' Hget''].\n      rewrite -Hdec_eq in Hdec_ct''.\n      by eauto.\n  - move: Hupd; rewrite /updm Hget=> - [<-] {amem'}; split.\n    + move=> w x'' ct'' st''.\n      rewrite Hdec_eq !setmE.\n      have [_ {w}|_] := altP (w =P addr).\n        move=> Hdec_ct'' [Hv Hct]. move: Hv Hct Hdec_ct'' => <- <- {x'' ct''}.\n        by rewrite Hdec; move => [->].\n      by apply (proj1 Hmem).\n    + move=> w x' st'.\n      rewrite !setmE.\n      case: (w == addr) => [{w} [<- <-] {x' st'}|].\n        exists ct=> //.\n        by rewrite Hdec_eq.\n      move=> /(proj2 Hmem) [ct'' Hdec_ct'' Hget''].\n      exists ct''=> //.\n      by rewrite Hdec_eq.\nQed.\n\nLemma refine_registers_upd areg creg creg' cmem r v v' ct t ct' t' :\n  refine_registers areg creg cmem ->\n  creg r = Some v@ct ->\n  decode Symbolic.R cmem ct = Some t ->\n  updm creg r v'@ct' = Some creg' ->\n  decode Symbolic.R cmem ct' = Some t' ->\n  exists2 areg',\n    updm areg r v'@t' = Some areg' &\n    refine_registers areg' creg' cmem.\nProof.\n  move=> Hregs Hget Hdec Hupd Hdec'.\n  have Hget' := proj1 Hregs _ _ _ _ Hdec Hget.\n  have Hupd' : updm areg r v'@t' = Some (setm areg r v'@t').\n    by rewrite /updm Hget'.\n  move: Hupd; rewrite {1}/updm Hget /= => - [<-].\n  rewrite Hupd'; eexists => //; split.\n  - move=> r' x ct'' st''.\n    rewrite !setmE.\n    case: (r' == r) => [Hdec'' [Hx Hct'']|].\n      move: Hx Hct'' Hdec'' => <- <-.\n      by rewrite Hdec'=> [[->]].\n    by apply (proj1 Hregs).\n  - move=> r' x st''.\n    rewrite !setmE.\n    case: (r' == r) => [[<- <-] {x st''}|]; first by eauto.\n    by apply (proj2 Hregs).\nQed.\n\nLemma refine_registers_upd' areg areg' creg cmem r v ct t :\n  refine_registers areg creg cmem ->\n  updm areg r v@t = Some areg' ->\n  decode Symbolic.R cmem ct = Some t ->\n  exists2 creg',\n    updm creg r v@ct = Some creg' &\n    refine_registers areg' creg' cmem.\nProof.\n  rewrite /updm; case Hget: (areg r)=> [[v0 t0]|] //= Hregs [<-] Hdec.\n  have [ct0 Hdec' Hget'] := proj2 Hregs _ _ _ Hget.\n  rewrite Hget' /=.\n  eexists=> //; split.\n  - move=> r' x ct' st'; rewrite !setmE.\n    case: (r' == r) => [Hdec_ct' [Hx Hct']|].\n      move: Hx Hct' Hdec_ct' => <- <- {x ct'}.\n      by rewrite Hdec => [[<-]].\n    by apply (proj1 Hregs).\n  - move=> r' x st'; rewrite !setmE.\n    case: (r' == r) => [[<- <-] {x st'}|]; first by rewrite -Hdec; eauto.\n    by apply (proj2 Hregs).\nQed.\n\nInductive hit_step cst cst' : Prop :=\n| hs_intro (USER : in_user cst)\n           (USER' : in_user cst')\n           (STEP : Concrete.step _ masks cst cst').\n\nDefinition monitor_exec kst kst' :=\n  restricted_exec (Concrete.step _ masks)\n                  (fun s => in_monitor s)\n                  kst kst'.\nHint Unfold monitor_exec.\n\nDefinition monitor_user_exec kst st : Prop :=\n  exec_until (Concrete.step _ masks)\n             (fun s => in_monitor s)\n             (fun s => ~~ in_monitor s)\n             kst st.\n\nInductive user_monitor_user_step cst cst' : Prop :=\n| ukus_intro kst\n             (USER : in_user cst)\n             (STEP : Concrete.step _ masks cst kst)\n             (EXEC : monitor_user_exec kst cst').\n\nLemma user_monitor_user_step_weaken cst cst' :\n  user_monitor_user_step cst cst' ->\n  exec (Concrete.step _ masks) cst cst'.\nProof.\n  move => [cst'' ? ? ?].\n  eapply re_step; trivial; try eassumption.\n  eapply exec_until_weaken; eassumption.\nQed.\n\nDefinition user_step cst cst' :=\n  hit_step cst cst' \\/ user_monitor_user_step cst cst'.\n\nLemma analyze_cache cache cmem cmvec crvec :\n  cache_correct cache cmem ->\n  Concrete.cache_lookup cache masks cmvec = Some crvec ->\n  decode Symbolic.P cmem (Concrete.ctpc cmvec) ->\n  let op := Concrete.cop cmvec in\n  if Symbolic.privileged_op op then False else\n  exists tpc : Symbolic.tag_type Symbolic.ttypes Symbolic.P, decode Symbolic.P cmem (Concrete.ctpc cmvec) = Some tpc /\\\n  ((exists (ti : Symbolic.tag_type Symbolic.ttypes Symbolic.M)\n           (ts : hseq (Symbolic.tag_type Symbolic.ttypes) (Symbolic.inputs op))\n           (rtpc : Symbolic.tag_type Symbolic.ttypes Symbolic.P)\n           (rt : Symbolic.type_of_result Symbolic.ttypes (Symbolic.outputs op)),\n    let ovec := Symbolic.OVec rtpc rt in\n    [/\\ decode Symbolic.M cmem (Concrete.cti cmvec) = Some (User ti) ,\n        decode_ovec e op cmem crvec = Some ovec ,\n        Symbolic.transfer (Symbolic.IVec op tpc ti ts) = Some ovec &\n        decode_fields e _ cmem (Concrete.ct1 cmvec, Concrete.ct2 cmvec, Concrete.ct3 cmvec) =\n        Some (hmap (fun k x => Some (wtag_of_tag x)) ts) ]) \\/\n   exists t : Symbolic.entry_tag_type Symbolic.ttypes,\n     [/\\ op = NOP ,\n         decode Symbolic.M cmem (Concrete.cti cmvec) = Some (Entry t) &\n         Concrete.ctrpc crvec = Concrete.TMonitor ]).\nProof.\n  case: cmvec => op tpc ti t1 t2 t3 /= CACHE LOOKUP INUSER.\n  case: (CACHE _ crvec LOOKUP INUSER) =>\n  [[[op'|] tpc' ti' ts] /= [ovec /= [/decode_ivec_inv /= E1 E2 E3]]]; last first.\n    case: E1 => [? ? ->]. subst op.\n    move: E2 => /=.\n    have [-> _| //] := (Concrete.ctrpc _ =P _).\n    by eauto 11 using And3.\n  case: E1 => [? Hpriv -> ->]. subst op' => ->.\n  rewrite (negbTE Hpriv). eexists. split; eauto.\n  case: ovec E2 E3 => trpc tr /=.\n  case: (decode _ cmem _) => [trpc'|] //= DEC.\n  by eauto 11 using And4.\nQed.\n\nLemma miss_state_not_user st mvec :\n  ~~ (in_user (Concrete.miss_state st mvec)).\nProof.\n  apply/negP=> INUSER.\n  apply in_user_in_monitor in INUSER.\n  unfold Concrete.miss_state in INUSER.\n  unfold in_monitor, Concrete.is_monitor_tag in INUSER.\n  by rewrite /= eqxx in INUSER.\nQed.\n\nLemma valid_initial_user_instr_tags cst cst' v ti :\n  cache_correct (Concrete.cache cst) (Concrete.mem cst) ->\n  in_user cst ->\n  in_user cst' ->\n  Concrete.step _ masks cst cst' ->\n  Concrete.mem cst (Concrete.pcv cst) = Some v@ti ->\n  oapp (fun x => is_user x) false (decode Symbolic.M (Concrete.mem cst) ti).\nProof.\n  move=> Hcache Huser Huser' Hstep Hget.\n  have [cmvec [Hcmvec]] := step_lookup_success_or_fault Hstep.\n  case Hlookup: (Concrete.cache_lookup _ _ _) => [crvec|].\n    have := Hcache _ _ Hlookup.\n    rewrite (build_cmvec_ctpc Hcmvec) => /(_ Huser) [ivec [ovec [Hdec_i Hdec_o Htrans]]] Hpc_cst'.\n    have := build_cmvec_cop_cti Hcmvec.\n    rewrite Hget => [[i [instr [[<- -> {i}] _ _]]]].\n    have := decode_ivec_inv Hdec_i.\n    case: ivec ovec {Hdec_i} Hdec_o Htrans => [[op'|] tpc' ti' ts'] /= ovec Hdec_o Htrans.\n      by move=> [? ? ? -> ?].\n    move=> [_ _ _].\n    move: ovec Huser' {Htrans} Hdec_o.\n    rewrite /in_user /= -{}Hpc_cst' => [[]].\n    have [->|//] := (_ =P _).\n    by rewrite decode_monitor_tag.\n  rewrite /= => Hcst'.\n  move: Huser'.\n  by rewrite /in_user {}Hcst' /= decode_monitor_tag.\nQed.\n\nLemma valid_pcs st st' :\n  Concrete.step _ masks st st' ->\n  cache_correct (Concrete.cache st) (Concrete.mem st) ->\n  in_user st ->\n  (exists t,\n     decode Symbolic.P (Concrete.mem st') (Concrete.pct st') = Some t) \\/\n  Concrete.pct st' = Concrete.TMonitor.\nProof.\n  move=> Hstep Hcache Huser.\n  have [cmvec [Hcmvec]] := step_lookup_success_or_fault Hstep.\n  case Hlookup: (Concrete.cache_lookup _ _ _) => [crvec|].\n    have := Hcache _ _ Hlookup.\n    rewrite (build_cmvec_ctpc Hcmvec) => /(_ Huser) [ivec [ovec [Hdec_i Hdec_o Htrans]]] Hpc_st'.\n    have := decode_ivec_inv Hdec_i.\n    case: ivec ovec Hdec_i Hdec_o Htrans=> [[op|] tpc ti ts] ovec Hdec_i Hdec_o Htrans.\n      move=> [Hop Hpriv _ _ _].\n      move: ti ts ovec {Htrans} Hdec_i Hdec_o.\n      rewrite Hop /= -{}Hpc_st' => ti ts ovec.\n      case Hdec: (decode Symbolic.P (Concrete.mem st) _) => [st''|] //= Hdec_i Hdec_o.\n      suff : @decode _ _ e Symbolic.P (Concrete.mem st') =1\n             @decode _ _ e Symbolic.P (Concrete.mem st).\n        move=> E. rewrite -E in Hdec. by eauto.\n      move/concrete.exec.stepP: Hstep Hcmvec Hdec_i Hdec_o.\n      rewrite /step /build_cmvec {1}(Concrete.state_eta st) /=.\n      case Hget: (getm _ (Concrete.pcv _)) => [[i cti]|] //=.\n      case Hdec_i: (decode_instr i) => [instr|] //=.\n      destruct instr; move=> Hstep; match_inv; try by []; move => [?]; subst cmvec;\n      unfold Concrete.next_state_reg, Concrete.next_state_pc,\n             Concrete.next_state_reg_and_pc, Concrete.next_state in *;\n      simpl in *;\n      match goal with\n      | H : match _ with _ => _ end = Some _ |- _ =>\n        rewrite Hlookup in H\n      end; match_inv;\n      repeat match goal with\n      | H : Some _ = Some _ |- _ => inv H; simpl in *\n      end; trivial.\n      rewrite /decode_ivec /= => ?.\n      match_inv; simpl in *;\n      repeat match goal with\n      | H : hshead _ = _ |- _ => rewrite /hshead /hnth eq_axiomK /= in H\n      | a : atom _ _ |- _ => destruct a\n      | H : OP _ = OP _ |- _ => inversion H; subst; clear H\n      end; simpl in *; subst.\n      move=> H /=; match_inv.\n      move: E1; rewrite /updm; case: (getm _ _) => /= [_|] // [<-].\n      by eapply decode_monotonic; eauto.\n    rewrite {}Hpc_st'.\n    case=> [_ _ _].\n    move: ovec {Htrans} Hdec_o.\n    rewrite /= => [[]].\n    by have [->|//] := _ =P Concrete.TMonitor; auto.\n  by rewrite /= => ->; auto.\nQed.\n\nHint Unfold Symbolic.next_state.\nHint Unfold Symbolic.next_state_reg_and_pc.\nHint Unfold Symbolic.next_state_pc.\nHint Unfold Symbolic.next_state_reg.\n\nDefinition user_tags_unchanged cmem cmem' :=\n  forall ctg tk stg,\n    decode tk cmem ctg = Some stg <->\n    decode tk cmem' ctg = Some stg.\n\nDefinition user_mem_unchanged (cmem cmem' : Concrete.memory mt) :=\n  forall addr (w : mword mt) ct t,\n    decode Symbolic.M cmem ct = Some t ->\n    (cmem addr = Some w@ct <->\n     cmem' addr = Some w@ct).\n\nDefinition user_regs_unchanged (cregs cregs' : Concrete.registers mt) cmem :=\n  forall r (w : mword mt) ct t,\n    decode Symbolic.R cmem ct = Some t ->\n    (cregs r = Some w@ct <->\n     cregs' r = Some w@ct).\n\nLemma get_mem_no_user smem mem addr v ctg t :\n  refine_memory smem mem ->\n  getm smem addr = None ->\n  getm mem addr = Some v@ctg ->\n  decode Symbolic.M mem ctg = Some t ->\n  exists ut, t = Entry ut.\nProof.\n  intros REF SGET GET DEC.\n  destruct t.\n  - move: (proj1 REF addr v ctg s DEC GET).\n    by rewrite SGET.\n  - eexists; reflexivity.\nQed.\n\n(* Returns true iff our machine is at the beginning of a system call\nand the cache says it is allowed to execute. To simplify this\ndefinition, we assume that system calls are only allowed to begin with\nNop, which is consistent with how we've defined our symbolic handler\nin rules.v. *)\nDefinition cache_allows_syscall (cst : Concrete.state mt) : bool :=\n  match table (Concrete.pcv cst) with\n  | Some _ =>\n    match build_cmvec cst with\n    | Some cmvec => Concrete.cache_lookup (Concrete.cache cst) masks cmvec\n    | None => false\n    end\n  | None => false\n  end.\n\nClass monitor_code_fwd_correctness : Prop := {\n\n(* BCP: Added some comments -- please check! *)\n  handler_correct_allowed_case_fwd :\n  forall mem cmvec ivec ovec reg cache old_pc int,\n    (* If monitor invariant holds... *)\n    mi mem reg cache int ->\n    (* and calling the handler on the current m-vector succeeds and returns rvec... *)\n    decode_ivec e mem cmvec = Some ivec ->\n    Symbolic.transfer ivec = Some ovec ->\n    (* and storing the concrete representation of the m-vector yields new memory mem'... *)\n    let mem' := Concrete.store_mvec mem cmvec in\n    (* and the concrete rule cache is correct (in the sense that every\n       rule it holds is exactly the concrete representations of\n       some (mvec,rvec) pair in the relation defined by the [handler]\n       function) ... *)\n    cache_correct cache mem ->\n    (* THEN if we start the concrete machine in monitor mode (i.e.,\n       with the PC tagged TMonitor) at the beginning of the fault\n       handler (and with the current memory, and with the current PC\n       in the return-addr register epc)) and let it run until it\n       reaches a user-mode state st'... *)\n    exists st' crvec,\n      monitor_user_exec\n        (Concrete.State mem' reg cache\n                          (Concrete.fault_handler_start _)@Concrete.TMonitor\n                          old_pc)\n        st' /\\\n      (* then the new cache is still correct... *)\n      cache_correct (Concrete.cache st') (Concrete.mem st') /\\\n      (* and the new cache now contains a rule mapping mvec to rvec... *)\n      Concrete.cache_lookup (Concrete.cache st') masks cmvec = Some crvec /\\\n      decode_ovec e (Symbolic.op ivec) (Concrete.mem st') crvec = Some ovec /\\\n      (* and the mvec has been tagged as monitor data (BCP: why is this important??) *)\n      mvec_in_monitor (Concrete.mem st') /\\\n      (* and we've arrived at the return address that was in epc with\n         unchanged user memory and registers... *)\n      user_tags_unchanged mem (Concrete.mem st') /\\\n      user_mem_unchanged mem (Concrete.mem st') /\\\n      user_regs_unchanged reg (Concrete.regs st') mem /\\\n      Concrete.pc st' = old_pc /\\\n      (* and the system call entry points are all tagged ENTRY (BCP:\n         Why do we care, and if we do then why isn't this part of the\n         monitor invariant?  Could user code possibly change it?) *)\n      wf_entry_points (Concrete.mem st') /\\\n      (* and the monitor invariant still holds. *)\n      mi (Concrete.mem st') (Concrete.regs st') (Concrete.cache st') int;\n\n  syscalls_correct_allowed_case_fwd :\n  forall amem areg apc atpc int\n         amem' areg' apc' atpc' int'\n         cmem creg cache ctpc epc sc,\n    (* and the monitor invariant holds... *)\n    mi cmem creg cache int ->\n    (* and the USER-tagged portion of the concrete memory cmem\n       corresponds to the abstract (symbolic??) memory amem... *)\n    refine_memory amem cmem ->\n    (* and the USER-tagged concrete registers in creg correspond to\n       the abstract register set areg... *)\n    refine_registers areg creg cmem ->\n    (* and the rule cache is correct... *)\n    cache_correct cache cmem ->\n    (* and the mvec has been tagged as monitor data (BCP: again, why is this\n       important... and why is it now part of the premises whereas\n       upstairs it was part of the conclusion??) *)\n    mvec_in_monitor cmem ->\n    (* and the symbolic system call at addr is the function\n       sc... (BCP: This would make more sense after the next\n       hypothesis) *)\n    table apc = Some sc ->\n    (* and running sc on the current abstract machine state reaches a\n       new state with primes on everything... *)\n    Symbolic.run_syscall sc (Symbolic.State amem areg apc@atpc int) = Some (Symbolic.State amem' areg' apc'@atpc' int') ->\n    decode Symbolic.P cmem ctpc = Some atpc ->\n    let cst := Concrete.State cmem\n                                creg\n                                cache\n                                apc@ctpc epc in\n\n    cache_allows_syscall cst ->\n\n    (* THEN if we start the concrete machine in monitor mode at the\n       beginning of the corresponding system call code and let it run\n       until it reaches a user-mode state with primes on everything... *)\n\n    exists cmem' creg' cache' ctpc' epc',\n      user_monitor_user_step cst\n                            (Concrete.State cmem' creg' cache'\n                                              apc'@ctpc' epc') /\\\n\n      (* then the new concrete state is in the same relation as before\n         with the new abstract state and the same invariants\n         hold (BCP: Plus one more about ra!). *)\n      decode Symbolic.P cmem' ctpc' = Some atpc' /\\\n      refine_memory amem' cmem' /\\\n      refine_registers areg' creg' cmem' /\\\n      cache_correct cache' cmem' /\\\n      mvec_in_monitor cmem' /\\\n      wf_entry_points cmem' /\\\n      mi cmem' creg' cache' int'\n\n}.\n\nClass monitor_code_bwd_correctness : Prop := {\n\n  handler_correct_allowed_case_bwd :\n  forall mem cmvec reg cache old_pc int st',\n    mi mem reg cache int ->\n    let mem' := Concrete.store_mvec mem cmvec in\n    cache_correct cache mem ->\n    monitor_user_exec\n        (Concrete.State mem' reg cache\n                          (Concrete.fault_handler_start _)@Concrete.TMonitor\n                          old_pc)\n        st' ->\n    exists ivec ovec,\n      decode_ivec e mem cmvec = Some ivec /\\\n      Symbolic.transfer ivec = Some ovec /\\\n      cache_correct (Concrete.cache st') (Concrete.mem st') /\\\n      mvec_in_monitor (Concrete.mem st') /\\\n      user_tags_unchanged mem (Concrete.mem st') /\\\n      user_mem_unchanged mem (Concrete.mem st') /\\\n      user_regs_unchanged reg (Concrete.regs st') mem /\\\n      Concrete.pc st' = old_pc /\\\n      wf_entry_points (Concrete.mem st') /\\\n      mi (Concrete.mem st') (Concrete.regs st') (Concrete.cache st') int;\n\n  handler_correct_disallowed_case :\n  forall mem cmvec reg cache old_pc int st',\n    (* If monitor invariant holds... *)\n    mi mem reg cache int ->\n    (* and calling the handler on mvec FAILS... *)\n    match decode_ivec e mem cmvec with\n    | Some ivec => ~~ Symbolic.transfer ivec\n    | None => true\n    end ->\n    (* and storing the concrete representation of the m-vector yields new memory mem'... *)\n    let mem' := Concrete.store_mvec mem cmvec in\n    (* then if we start the concrete machine in monitor mode and let it\n       run, it will never reach a user-mode state. *)\n    ~~ in_monitor st' ->\n    ~ exec (Concrete.step _ masks)\n      (Concrete.State mem' reg cache\n                        (Concrete.fault_handler_start _)@Concrete.TMonitor\n                        old_pc)\n      st';\n\n  syscalls_correct_allowed_case_bwd :\n  forall amem areg apc atpc int\n         cmem creg cache ctpc epc\n         cmem' creg' cache' cpc' ctpc' epc' sc,\n    mi cmem creg cache int ->\n    refine_memory amem cmem ->\n    refine_registers areg creg cmem ->\n    cache_correct cache cmem ->\n    mvec_in_monitor cmem ->\n    table apc = Some sc ->\n    decode Symbolic.P cmem ctpc = Some atpc ->\n    let cst := Concrete.State cmem\n                                creg\n                                cache\n                                apc@ctpc epc in\n    cache_allows_syscall cst ->\n    user_monitor_user_step cst\n                          (Concrete.State cmem' creg' cache'\n                                            cpc'@ctpc' epc') ->\n    exists amem' areg' atpc' int',\n      Symbolic.run_syscall sc (Symbolic.State amem areg apc@atpc int) =\n      Some (Symbolic.State amem' areg' cpc'@atpc' int') /\\\n      decode Symbolic.P cmem' ctpc' = Some atpc' /\\\n      refine_memory amem' cmem' /\\\n      refine_registers areg' creg' cmem' /\\\n      cache_correct cache' cmem' /\\\n      mvec_in_monitor cmem' /\\\n      wf_entry_points cmem' /\\\n      mi cmem' creg' cache' int'\n\n}.\n\nEnd Refinement.\n", "meta": {"author": "micro-policies", "repo": "micro-policies-coq", "sha": "28163163c88387fc24475ed219f5705f9e0d4fc6", "save_path": "github-repos/coq/micro-policies-micro-policies-coq", "path": "github-repos/coq/micro-policies-micro-policies-coq/micro-policies-coq-28163163c88387fc24475ed219f5705f9e0d4fc6/symbolic/refinement_common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.24067603738798496}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export cequiv_seq_util.\nRequire Export sequents_tacs2.\n(*Require Export per_props4.*)\nRequire Export per_can.\nRequire Export per_props_atom.\nRequire Export per_props_ffatom.\nRequire Export per_props_squash.\nRequire Export per_props_nat2.\n\n\n(* !!MOVE *)\nLemma member_mkc_squash {p} :\n  forall lib (T : @CTerm p),\n    member lib mkc_axiom (mkc_squash T)\n    <=> inhabited_type lib T.\nProof.\n  intros.\n  rw @equality_in_mkc_squash.\n  split; intro h; repnd; dands; auto; spcast;\n  apply computes_to_valc_refl; eauto 3 with slow.\nQed.\n\nLemma tequality_natk2nat_nat {o} :\n  forall lib n,\n    @tequality o lib (natk2nat (mkc_nat n)) (natk2nat (mkc_nat n)).\nProof.\n  introv.\n  apply tequality_natk2nat.\n  exists (Z.of_nat n) (Z.of_nat n).\n  dands; spcast; try (apply computes_to_valc_refl; eauto 3 with slow).\n  introv ltk.\n  destruct (Z_lt_le_dec k (Z.of_nat n)); sp.\nQed.\nHint Resolve tequality_natk2nat_nat : slow.\n\nLemma equality_in_nout {o} :\n  forall lib (a b : @CTerm o),\n    equality lib a b mkc_nout\n    <=> {u : CTerm\n         , noutokensc u\n         # ccequivc lib a u\n         # ccequivc lib b u}.\nProof.\n  introv.\n  unfold mkc_nout.\n  rw @equality_in_set.\n  split; intro h; repnd.\n\n  - allrw @mkcv_ffatoms_substc.\n    allrw @mkc_var_substc.\n    apply inhabited_free_from_atoms in h; exrepnd.\n    allrw @equality_in_base_iff; spcast.\n    exists u; dands; spcast; auto.\n    eapply cequivc_trans;[|eauto].\n    apply cequivc_sym; auto.\n\n  - exrepnd.\n    dands.\n\n    + introv equ.\n      allrw @equality_in_base_iff; spcast.\n      allrw @mkcv_ffatoms_substc.\n      allrw @mkc_var_substc.\n      unfold mkc_ffatoms.\n      apply tequality_free_from_atoms; dands; eauto 3 with slow.\n      apply equality_in_base_iff; spcast; auto.\n\n    + spcast.\n      apply equality_in_base_iff; spcast; auto.\n      eapply cequivc_trans;[eauto|].\n      apply cequivc_sym; auto.\n\n    + spcast.\n      allrw @mkcv_ffatoms_substc.\n      allrw @mkc_var_substc.\n      unfold mkc_ffatoms.\n      apply inhabited_free_from_atoms.\n      exists u; dands; eauto 3 with slow.\n\n      * apply tequality_base.\n\n      * apply equality_in_base_iff; spcast; auto.\nQed.\n\nLemma type_mkc_nout {o} :\n  forall lib, @type o lib mkc_nout.\nProof.\n  introv.\n  unfold mkc_nout.\n  apply tequality_set; dands; auto.\n  introv eb.\n  allrw @mkcv_ffatoms_substc.\n  allrw @mkc_var_substc.\n  unfold mkc_ffatoms.\n  apply tequality_free_from_atoms; dands; eauto 3 with slow.\nQed.\nHint Resolve type_mkc_nout : slow.\n\nLemma tequality_natk2nout {o} :\n  forall lib (a b : @CTerm o),\n    tequality lib (natk2nout a) (natk2nout b)\n     <=> {k1 : Z\n          , {k2 : Z\n          , (a) ===>(lib) (mkc_integer k1)\n          # (b) ===>(lib) (mkc_integer k2)\n          # (forall k : Z,\n               (0 <= k)%Z ->\n               ((k < k1)%Z # (k < k2)%Z){+}(k1 <= k)%Z # (k2 <= k)%Z)}}.\nProof.\n  introv.\n  unfold natk2nout.\n  rw @tequality_mkc_fun.\n  rw @tequality_mkc_natk.\n  split; intro k; exrepnd; dands; eauto 3 with slow.\n\n  - spcast; exists k1 k0; dands; spcast; auto.\n\n  - spcast; exists k1 k2; dands; spcast; auto.\n\n  - introv inh; apply type_mkc_nout.\nQed.\n\nLemma tequality_natk2nout_nat {o} :\n  forall lib n,\n    @tequality o lib (natk2nout (mkc_nat n)) (natk2nout (mkc_nat n)).\nProof.\n  introv.\n  apply tequality_natk2nout.\n  exists (Z.of_nat n) (Z.of_nat n).\n  dands; spcast; try (apply computes_to_valc_refl; eauto 3 with slow).\n  introv ltk.\n  destruct (Z_lt_le_dec k (Z.of_nat n)); sp.\nQed.\nHint Resolve tequality_natk2nout_nat : slow.\n\nLemma type_nat2nout {o} :\n  forall (lib : @library o), type lib nat2nout.\nProof.\n  introv.\n  unfold nat2nout.\n  apply type_mkc_fun; dands; eauto 3 with slow.\nQed.\nHint Resolve type_nat2nout : slow.\n\n(* ========================== *)\n\nLemma implies_equality_natk2nat {o} :\n  forall lib (f g : @CTerm o) n,\n    (forall m,\n       m < n\n       -> {k : nat\n           & computes_to_valc lib (mkc_apply f (mkc_nat m)) (mkc_nat k)\n           # computes_to_valc lib (mkc_apply g (mkc_nat m)) (mkc_nat k)})\n    -> equality lib f g (natk2nat (mkc_nat n)).\nProof.\n  introv imp.\n  apply equality_in_fun; dands; eauto 3 with slow.\n\n  { apply type_mkc_natk.\n    exists (Z.of_nat n); spcast.\n    apply computes_to_valc_refl; eauto 3 with slow. }\n\n  introv e.\n  apply equality_in_natk in e; exrepnd; spcast.\n\n  eapply equality_respects_cequivc_left;\n    [apply implies_cequivc_apply;\n      [apply cequivc_refl\n      |apply cequivc_sym;\n        apply computes_to_valc_implies_cequivc;\n        exact e0]\n    |].\n\n  eapply equality_respects_cequivc_right;\n    [apply implies_cequivc_apply;\n      [apply cequivc_refl\n      |apply cequivc_sym;\n        apply computes_to_valc_implies_cequivc;\n        exact e2]\n    |].\n\n  clear dependent a.\n  clear dependent a'.\n\n  apply computes_to_valc_isvalue_eq in e3; eauto 3 with slow.\n  rw @mkc_nat_eq in e3; ginv.\n\n  assert (m < n) as ltm by omega.\n  clear e1.\n\n  apply equality_in_tnat.\n  pose proof (imp m ltm) as h; exrepnd.\n  exists k; dands; spcast; auto.\nQed.\n\nLemma implies_member_natk2nat {o} :\n  forall lib (f : @CTerm o) n,\n    (forall m,\n       m < n\n       -> {k : nat & computes_to_valc lib (mkc_apply f (mkc_nat m)) (mkc_nat k)})\n    -> member lib f (natk2nat (mkc_nat n)).\nProof.\n  introv imp.\n  apply implies_equality_natk2nat.\n  introv ltm.\n  apply imp in ltm; exrepnd.\n  exists k; auto.\nQed.\n\nLemma equality_natk2nat_implies {o} :\n  forall lib m (f g : @CTerm o) n,\n    m < n\n    -> equality lib f g (natk2nat (mkc_nat n))\n    -> {k : nat\n        & computes_to_valc lib (mkc_apply f (mkc_nat m)) (mkc_nat k)\n        # computes_to_valc lib (mkc_apply g (mkc_nat m)) (mkc_nat k)}.\nProof.\n  introv ltm mem.\n  apply equality_in_fun in mem; repnd.\n  clear mem0 mem1.\n  pose proof (mem (mkc_nat m) (mkc_nat m)) as h; clear mem.\n  autodimp h hyp.\n\n  { apply equality_in_natk.\n    exists m (Z.of_nat n); dands; spcast; try omega;\n    try (apply computes_to_valc_refl; eauto 2 with slow). }\n\n  apply equality_in_tnat in h.\n  apply equality_of_nat_imp_tt in h.\n  unfold equality_of_nat_tt in h; exrepnd.\n  exists k; auto.\nQed.\n\nLemma member_natk2nat_implies {o} :\n  forall lib m (f : @CTerm o) n,\n    m < n\n    -> member lib f (natk2nat (mkc_nat n))\n    -> {k : nat & computes_to_valc lib (mkc_apply f (mkc_nat m)) (mkc_nat k)}.\nProof.\n  introv ltm mem.\n  eapply equality_natk2nat_implies in mem;[|exact ltm].\n  exrepnd.\n  exists k; auto.\nQed.\n\n(* ========================== *)\n\n\nDefinition eq_kseq {o} lib (s1 s2 : @CTerm o) (n : nat) :=\n  equality lib s1 s2 (natk2nat (mkc_nat n)).\n\nLemma eq_kseq_left {o} :\n  forall lib (seq1 seq2 : @CTerm o) k,\n    eq_kseq lib seq1 seq2 k\n    -> eq_kseq lib seq1 seq1 k.\nProof.\n  introv e.\n  apply equality_refl in e; auto.\nQed.\n\nDefinition fun_sim_eq {o} lib s1 H (t : @NTerm o) w (u : CTerm) :=\n  {s2 : CSub\n   & {c2 : cover_vars t s2\n   & similarity lib s1 s2 H\n   # u = lsubstc t w s2 c2}}.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/per/seq_util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.24062990457402492}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Logic.GeneralLogic.Base.\nRequire Import Logic.GeneralLogic.ProofTheory.BasicSequentCalculus.\nRequire Import Logic.MinimumLogic.Syntax.\nRequire Import Logic.MinimumLogic.ProofTheory.Minimum.\nRequire Import Logic.MinimumLogic.ProofTheory.RewriteClass.\nRequire Import Logic.PropositionalLogic.Syntax.\nRequire Import Logic.PropositionalLogic.ProofTheory.Intuitionistic.\nRequire Import Logic.PropositionalLogic.ProofTheory.Classical.\nRequire Import Logic.PropositionalLogic.ProofTheory.DeMorgan.\nRequire Import Logic.PropositionalLogic.ProofTheory.GodelDummett.\nRequire Import Logic.PropositionalLogic.ProofTheory.RewriteClass.\nRequire Import SeparationLogic.Syntax.\nRequire Import SeparationLogic.ProofTheory.SeparationLogic.\nRequire Import SeparationLogic.ProofTheory.RewriteClass.\nRequire Import SeparationLogic.ProofTheory.IterSepcon.\nRequire Import SeparationLogic.ProofTheory.TheoryOfSeparationAxioms.\n\nRequire Import Logic.LogicGenerator.Utils.\nRequire Import Logic.LogicGenerator.ConfigDenot.\nRequire Import Logic.LogicGenerator.ConfigCompute.\nRequire Logic.LogicGenerator.ConfigLang.\n\nRequire Config.\n\nSection Generate.\nContext {L: Language}\n        {minL: MinimumLanguage L}\n        {pL: PropositionalLanguage L}\n        {sepconL : SepconLanguage L}\n        {wandL : WandLanguage L}\n        {empL: EmpLanguage L}\n        {iter_sepcon_L: IterSepconLanguage L}\n        {GammaP: Provable L}\n        {GammaD: Derivable L}\n        {iter_sepcon_Def: NormalIterSepcon L}\n        {AX: NormalAxiomatization L GammaP GammaD}\n        {SC : NormalSequentCalculus L GammaP GammaD}\n        {minAX: MinimumAxiomatization L GammaP}\n        {ipAX: IntuitionisticPropositionalLogic L GammaP}\n        {cpAX: ClassicalPropositionalLogic L GammaP}\n        {dmpAX: DeMorganPropositionalLogic L GammaP}\n        {gdpAX: GodelDummettPropositionalLogic L GammaP}\n        {sepconAX: SepconAxiomatization L GammaP}\n        {wandAX: WandAxiomatization L GammaP}\n        {empAX: EmpAxiomatization L GammaP}\n        {sepcon_orp_AX: SepconOrAxiomatization L GammaP}\n        {sepcon_falsep_AX: SepconFalseAxiomatization L GammaP}\n        {sepconAX_weak: SepconAxiomatization_weak L GammaP}\n        {sepconAX_weak_iffp: SepconAxiomatization_weak_iffp L GammaP}\n        {sepcon_mono_AX: SepconMonoAxiomatization L GammaP}\n        {empAX_iffp: EmpAxiomatization_iffp L GammaP}\n        {extAX: ExtSeparationLogic L GammaP}\n        {nseAX: NonsplitEmpSeparationLogic L GammaP}\n        {deAX: DupEmpSeparationLogic L GammaP}\n        {mfAX: MallocFreeSeparationLogic L GammaP}\n        {gcAX: GarbageCollectSeparationLogic L GammaP}\n        {bSC : BasicSequentCalculus L GammaD}\n        {fwSC : FiniteWitnessedSequentCalculus L GammaD}\n        {minSC: MinimumSequentCalculus L GammaD}\n        {ipSC: IntuitionisticPropositionalSequentCalculus L GammaD}\n        {cpSC: ClassicalPropositionalSequentCalculus L GammaD}\n        .\n        \nImport NameListNotations.\n\nDefinition foo :=\n  ltac:(\n    let res := eval compute in\n    (ConfigCompute.result\n       Config.how_connectives\n       Config.how_judgements\n       Config.transparent_names\n       Config.primitive_rule_classes)\n    in exact res).\n\nDefinition primitive_types: list Name :=\n  map_with_hint\n    (ConfigDenot.D.types, ConfigDenot.S.types)\n    (ConfigLang.Output.primitive_types foo).\n\nDefinition transparent_types: list Name :=\n  map_with_hint\n    (ConfigDenot.D.types, ConfigDenot.S.types)\n    (ConfigLang.Output.transparent_types foo).\n  \nDefinition derived_types: list Name :=\n  map_with_hint\n    (ConfigDenot.D.how_types, ConfigDenot.S.how_types)\n    (ConfigLang.Output.derived_types foo).\n  \nDefinition primitive_connectives: list Name :=\n  map_with_hint\n    (ConfigDenot.D.connectives, ConfigDenot.S.connectives)\n    (ConfigLang.Output.primitive_connectives foo).\n\nDefinition transparent_connectives: list Name :=\n  map_with_hint\n    (ConfigDenot.D.connectives, ConfigDenot.S.connectives)\n    (ConfigLang.Output.transparent_connectives foo).\n\nDefinition derived_connectives: list Name :=\n  map_with_hint\n    (ConfigDenot.D.how_connectives, ConfigDenot.S.how_connectives)\n    (ConfigLang.Output.derived_connectives foo).\n\nDefinition primitive_judgements: list Name :=\n  map_with_hint\n    (ConfigDenot.D.judgements, ConfigDenot.S.judgements)\n    (ConfigLang.Output.primitive_judgements foo).\n\nDefinition transparent_judgements: list Name :=\n  map_with_hint\n    (ConfigDenot.D.judgements, ConfigDenot.S.judgements)\n    (ConfigLang.Output.transparent_judgements foo).\n\nDefinition derived_judgements: list Name :=\n  map_with_hint\n    (ConfigDenot.D.how_judgements, ConfigDenot.S.how_judgements)\n    (ConfigLang.Output.derived_judgements foo).\n\nDefinition aux_primitive_instances: list Name :=\n  map_with_hint\n    (ConfigDenot.D.classes, ConfigDenot.S.instances_build)\n    (ConfigLang.Output.primitive_classes foo).\n\nDefinition aux_refl_instances_for_derivation: list Name :=\n  map_with_hint\n    (ConfigDenot.D.refl_classes, ConfigDenot.S.refl_instances)\n    (ConfigLang.Output.refl_classes_for_derivation foo).\n\nDefinition aux_derived_instances: list Name :=\n  map_with_hint\n    (ConfigDenot.S.D_instance_transitions, ConfigDenot.S.instance_transitions)\n    (ConfigLang.Output.how_derive_classes foo).\n\nDefinition primary_rules: list Name :=\n  map_with_hint\n    (ConfigDenot.S.D_primary_rules, ConfigDenot.S.primary_rules)\n    (ConfigLang.Output.primary_rules foo).\n\nLet derived_rules': list Name :=\n  (map_with_hint\n    (ConfigDenot.S.D_primary_rules, ConfigDenot.S.primary_rules)\n    (ConfigLang.Output.derived_primary_rules foo)) ++\n  map_with_hint\n    (ConfigDenot.S.D_derived_rules, ConfigDenot.S.derived_rules)\n    (ConfigLang.Output.derived_derived_rules foo).\n\nDefinition derived_rules : list Name :=\n  ltac:(let res0 := eval unfold derived_rules' in derived_rules' in\n        let res1 := eval unfold app at 1 in res0 in\n            exact res1).\n\nDefinition derived_rules_as_instance :=\n  map_with_hint\n    (ConfigDenot.S.D_derived_rules, ConfigDenot.S.derived_rules)\n    (ConfigLang.Output.derived_rules_as_instance foo).\n\nImport ListNotations.\n\nInductive PrintType := IPar (Inline_list: list Name) | Axm | Der | Def | AIns | DIns.\n\nLtac print prt name :=\n  match name with\n  | BuildName ?n =>\n    match type of n with\n    | ?T =>\n      match prt with\n      | IPar ?l =>\n        let l := eval hnf in l in\n        let should_inline := in_name_list n l in\n        match should_inline with\n        | true => idtac \"  Parameter Inline\" n \":\" T \".\"\n        | false => idtac \"  Parameter\" n \":\" T \".\"\n        end\n      | Axm => idtac \"  Axiom\" n \":\" T \".\"\n      | Der => match n with\n               | (?n0, ?n1) => idtac \"  Definition\" n0 \":=\" n1 \".\"\n               end\n      | Def => idtac \"  Definition\" n \":\" T \":=\" n \".\"\n      | AIns => match n with\n                | (?n0, ?n1) =>\n                  match type of n0 with\n                  | ?T0 => idtac \"  Instance\" n0 \":\" T0 \":=\" n1 \".\"\n                  end\n                end\n      | DIns => idtac \"  Existing Instance\" n \".\"\n      end\n    end\n  end.\n\nLtac newline := idtac \"\".\n\nSet Printing Width 1000.\n\nLtac two_stage_print :=\n  idtac \"Require Import Coq.Lists.List.\";\n  idtac \"Require Import Coq.Sets.Ensembles.\";\n  idtac \"Import ListNotations.\";\n\n  newline;\n\n  idtac \"Module Type LanguageSig.\";\n  dolist (print (IPar transparent_types)) primitive_types;\n  dolist (print Der) derived_types;\n  dolist (print (IPar transparent_judgements)) primitive_judgements;\n  dolist (print (IPar transparent_connectives)) primitive_connectives;\n  idtac \"End LanguageSig.\";\n\n  newline;\n\n  idtac \"Module DerivedNames (Names: LanguageSig).\";\n  idtac \"  Import Names.\";\n  dolist (print Der) derived_connectives;\n  dolist (print Der) derived_judgements;\n  idtac \"End DerivedNames.\";\n\n  newline;\n\n  idtac \"Module Type PrimitiveRuleSig (Names: LanguageSig).\";\n  idtac \"Import Names.\";\n  idtac \"Include DerivedNames (Names).\";\n  dolist (print Axm) primary_rules;\n  idtac \"End PrimitiveRuleSig.\";\n\n  newline;\n\n  idtac \"Module Type LogicTheoremSig (Names: LanguageSig) (Rules: PrimitiveRuleSig Names).\";\n  idtac \"  Include Rules.\";\n  idtac \"  Import Names Rules.\";\n  dolist (print Axm) derived_rules;\n  dolist (print DIns) derived_rules_as_instance;\n  idtac \"End LogicTheoremSig.\";\n\n  newline;\n\n  idtac \"Require Import Logic.GeneralLogic.Base.\";\n  idtac \"Require Import Logic.GeneralLogic.ProofTheory.BasicSequentCalculus.\";\n  idtac \"Require Import Logic.MinimumLogic.Syntax.\";\n  idtac \"Require Import Logic.MinimumLogic.ProofTheory.Minimum.\";\n  idtac \"Require Import Logic.MinimumLogic.ProofTheory.RewriteClass.\";\n  idtac \"Require Import Logic.PropositionalLogic.Syntax.\";\n  idtac \"Require Import Logic.PropositionalLogic.ProofTheory.Intuitionistic.\";\n  idtac \"Require Import Logic.PropositionalLogic.ProofTheory.DeMorgan.\";\n  idtac \"Require Import Logic.PropositionalLogic.ProofTheory.GodelDummett.\";\n  idtac \"Require Import Logic.PropositionalLogic.ProofTheory.Classical.\";\n  idtac \"Require Import Logic.PropositionalLogic.ProofTheory.RewriteClass.\";\n  idtac \"Require Import Logic.SeparationLogic.Syntax.\";\n  idtac \"Require Import Logic.SeparationLogic.ProofTheory.SeparationLogic.\";\n  idtac \"Require Import Logic.SeparationLogic.ProofTheory.RewriteClass.\";\n  idtac \"Require Import SeparationLogic.ProofTheory.TheoryOfSeparationAxioms.\";\n  idtac \"Require Import SeparationLogic.ProofTheory.IterSepcon.\";\n\n  newline;\n\n  idtac \"Module LogicTheorem (Names: LanguageSig) (Rules: PrimitiveRuleSig Names): LogicTheoremSig Names Rules.\";\n  idtac \"  Import Names Rules.\";\n  idtac \"  Include Rules.\";\n  dolist (print AIns) aux_primitive_instances;\n  dolist (print AIns) aux_refl_instances_for_derivation;\n  dolist (print AIns) aux_derived_instances;\n  dolist (print Def) derived_rules;\n  dolist (print DIns) derived_rules_as_instance;\n  idtac \"End LogicTheorem.\";\n\n  newline;\n\n  idtac \"Require Logic.PropositionalLogic.DeepEmbedded.Solver.\";\n  idtac \"Module IPSolver (Names: LanguageSig).\";\n  idtac \"  Import Names.\";\n  idtac \"  Ltac ip_solve :=\";\n  idtac \"    change expr with Base.expr;\";\n  idtac \"    change provable with Base.provable;\";\n  idtac \"    change impp with Syntax.impp;\";\n  idtac \"    change andp with Syntax.andp;\";\n  idtac \"    intros; Solver.SolverSound.ipSolver.\";\n  idtac \"End IPSolver.\";\n\n\n\n  \n  idtac.\n  \nGoal False.\n  two_stage_print.\nAbort.\n\nEnd Generate.\n", "meta": {"author": "QinxiangCao", "repo": "UnifySL", "sha": "cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d", "save_path": "github-repos/coq/QinxiangCao-UnifySL", "path": "github-repos/coq/QinxiangCao-UnifySL/UnifySL-cf4eec5d0d9f76b864d92a9e6df5bc3e8bb43d9d/LogicGenerator/Generate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.2405414500418005}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli & Mark Bickford\n\n *)\n\nRequire Export per_props_atom.\n\n\nLemma tequality_free_from_atom {o} :\n  forall lib (T1 T2 : @CTerm o) x1 x2 a1 a2,\n    tequality\n      lib\n      (mkc_free_from_atom T1 x1 a1)\n      (mkc_free_from_atom T2 x2 a2)\n      <=> (tequality lib T1 T2\n           # equality lib x1 x2 T1\n           # equality lib a1 a2 mkc_uatom).\nProof.\n  introv.\n  sp_iff Case.\n\n  - Case \"->\".\n    intros teq.\n    unfold tequality, nuprl in teq; exrepnd.\n    inversion teq0; subst; try not_univ.\n    allunfold_per.\n    computes_to_value_isvalue.\n    unfold tequality; dands; tcsp.\n\n    + exists eqa; auto.\n\n    + exists eqa; dands; auto.\n      allapply @nuprl_refl; auto.\n\n    + rw @equality_in_uatom_iff.\n      exists u; dands; spcast; auto.\n\n  - Case \"<-\".\n    introv e; exrepnd.\n    rename e0 into teq.\n    rename e1 into eqx.\n    rename e into equ.\n    unfold tequality in teq; exrepnd.\n    allrw @equality_in_uatom_iff; exrepnd; spcast.\n    exists (per_ffatom_eq lib eq a x1).\n    apply CL_ffatom.\n    unfold per_ffatom.\n    exists T1 T2 x1 x2 a1 a2 eq a.\n\n    dands; spcast; auto;\n    try (complete (spcast; apply computes_to_valc_refl;\n                   try (apply iscvalue_mkc_free_from_atom))).\n    eapply equality_eq1 in teq0; apply teq0; auto.\nQed.\n\nHint Resolve iscvalue_mkc_uatom : slow.\n\nLemma equality_free_from_atom_in_uni {o} :\n  forall lib (T1 T2 : @CTerm o) x1 x2 a1 a2 i,\n    equality\n      lib\n      (mkc_free_from_atom T1 x1 a1)\n      (mkc_free_from_atom T2 x2 a2)\n      (mkc_uni i)\n      <=> (equality lib T1 T2 (mkc_uni i)\n           # equality lib x1 x2 T1\n           # equality lib a1 a2 mkc_uatom).\nProof.\n  introv.\n  sp_iff Case.\n\n  - Case \"->\".\n    intros teq.\n    unfold equality, nuprl in teq; exrepnd.\n    inversion teq1; subst; try not_univ.\n    duniv j h.\n    allrw @univi_exists_iff; exrepd.\n    computes_to_value_isvalue; GC.\n    discover; exrepnd.\n    rename eqa into eqi.\n    ioneclose; subst; try not_univ.\n\n    unfold per_ffatom in *; exrepnd; spcast.\n    computes_to_value_isvalue; GC.\n    dands.\n\n    {\n      exists eq; sp.\n      allrw.\n      exists eqa; sp.\n    }\n\n    {\n      exists eqa; sp.\n      allfold (@nuprli o lib j0).\n      apply nuprli_implies_nuprl with (i := j0); sp.\n      allapply @nuprli_refl; sp.\n    }\n\n    {\n      exists (equality_of_uatom lib).\n      dands; auto.\n      - apply CL_uatom; unfold per_uatom; dands; spcast; auto;\n          apply computes_to_valc_refl; eauto 2 with slow.\n      - exists u; dands; spcast; auto.\n    }\n\n  - Case \"<-\".\n    intro eqs.\n    destruct eqs as [eqa eqb].\n    destruct eqb as [eqb eqc].\n\n    unfold equality in eqb; exrepnd.\n    rename eq into eqT.\n    apply equality_in_uatom_iff in eqc; exrepnd; spcast.\n\n    unfold equality in eqa; exrepnd.\n    rename eq into eqi.\n\n    exists eqi; dands; auto.\n    inversion eqa1; subst; try not_univ;[].\n    duniv j h.\n    allrw @univi_exists_iff; exrepd; spcast.\n    computes_to_value_isvalue; GC.\n    discover; exrepnd.\n\n    allrw.\n    exists (per_ffatom_eq lib eqT a x1).\n    apply CL_ffatom.\n    unfold per_ffatom.\n    exists T1 T2 x1 x2 a1 a2 eqT a.\n\n    dands; spcast; auto;\n    try (complete (spcast; apply computes_to_valc_refl;\n                   try (apply iscvalue_mkc_free_from_atom))).\n\n    fold (nuprli lib j0) in *.\n    applydup @nuprli_implies_nuprl in h0.\n    pose proof (nuprl_uniquely_valued lib T1 eqT eqa) as q.\n    repeat (autodimp q hyp);[eapply nuprl_refl; eauto|].\n    eapply nuprli_ext;[exact h0|].\n    apply eq_term_equals_sym; auto.\nQed.\n\nLemma tequality_free_from_atoms {o} :\n  forall lib (T1 T2 : @CTerm o) x1 x2,\n    tequality\n      lib\n      (mkc_free_from_atoms T1 x1)\n      (mkc_free_from_atoms T2 x2)\n      <=> (tequality lib T1 T2\n           # equality lib x1 x2 T1).\nProof.\n  introv.\n  sp_iff Case.\n\n  - Case \"->\".\n    intros teq.\n    unfold tequality, nuprl in teq; exrepnd.\n    inversion teq0; subst; try not_univ.\n    allunfold_per.\n    computes_to_value_isvalue.\n    unfold tequality; dands; tcsp.\n\n    + exists eqa; auto.\n\n    + exists eqa; dands; auto.\n      allapply @nuprl_refl; auto.\n\n  - Case \"<-\".\n    introv e; exrepnd.\n    rename e0 into teq.\n    rename e into eqx.\n    unfold tequality in teq; exrepnd.\n    allrw @equality_in_uatom_iff; exrepnd; spcast.\n    exists (per_ffatoms_eq lib eq x1).\n    apply CL_ffatoms.\n    unfold per_ffatoms.\n    exists T1 T2 x1 x2 eq.\n\n    dands; spcast; auto;\n    try (complete (spcast; apply computes_to_valc_refl;\n                   try (apply iscvalue_mkc_free_from_atoms))).\n    eapply equality_eq1 in teq0; apply teq0; auto.\nQed.\n\nDefinition name_not_in_upto_eq {o} lib (a x T : @CTerm o) :=\n  {u : get_patom_set o\n   , {y : CTerm\n   , a ===>(lib) (mkc_utoken u)\n   # equality lib x y T\n   # !LIn u (getc_utokens y)}}.\n\nLemma name_not_in_utpo_iff_eq {o} :\n  forall lib (A1 A2 : @CTerm o) eqa a x,\n    nuprl lib A1 A2 eqa\n    -> (name_not_in_upto lib a x eqa <=> name_not_in_upto_eq lib a x A1).\nProof.\n  introv n.\n  unfold name_not_in_upto.\n  unfold name_not_in_upto_eq.\n  split; intro h; exrepnd.\n\n  - exists u y; dands; auto.\n    eapply equality_eq1 in n; apply n; auto.\n\n  - exists u y; dands; auto.\n    eapply equality_eq1 in n; apply n; auto.\nQed.\n\nLemma tequality_efree_from_atom {o} :\n  forall lib (T1 T2 : @CTerm o) x1 x2 a1 a2,\n    tequality\n      lib\n      (mkc_efree_from_atom T1 x1 a1)\n      (mkc_efree_from_atom T2 x2 a2)\n      <=> (tequality lib T1 T2\n           # (name_not_in_upto_eq lib a1 x1 T1 <=> name_not_in_upto_eq lib a2 x2 T2)).\nProof.\n  introv.\n  sp_iff Case.\n\n  - Case \"->\".\n    intros teq.\n    unfold tequality, nuprl in teq; exrepnd.\n    inversion teq0; subst; try not_univ.\n    allunfold_per.\n    computes_to_value_isvalue.\n    unfold tequality; dands; tcsp.\n\n    + exists eqa; auto.\n\n    + pose proof (name_not_in_utpo_iff_eq lib A1 A2 eqa a0 x0) as i1.\n      autodimp i1 hyp.\n      pose proof (name_not_in_utpo_iff_eq lib A2 A1 eqa a3 x3) as i2.\n      autodimp i2 hyp.\n      { apply nuprl_sym; auto. }\n      rw <- i1; rw <- i2; auto.\n\n  - Case \"<-\".\n    introv e; exrepnd.\n    rename e0 into teq.\n    rename e into eqx.\n    unfold tequality in teq; exrepnd.\n    exists (per_effatom_eq lib eq a1 x1).\n    apply CL_effatom.\n    unfold per_effatom.\n    exists T1 T2 x1 x2 a1 a2 eq.\n\n    dands; spcast; auto;\n    try (complete (spcast; apply computes_to_valc_refl;\n                   try (apply iscvalue_mkc_efree_from_atom))).\n    pose proof (name_not_in_utpo_iff_eq lib T1 T2 eq a1 x1) as i1.\n    autodimp i1 hyp.\n    pose proof (name_not_in_utpo_iff_eq lib T2 T1 eq a2 x2) as i2.\n    autodimp i2 hyp.\n    { apply nuprl_sym; auto. }\n    rw i1; rw i2; auto.\nQed.\n\nLemma equality_in_free_from_atom {o} :\n  forall lib (t1 t2 T t a : @CTerm o),\n    equality lib t1 t2 (mkc_free_from_atom T t a)\n    <=> {y : CTerm\n         , {u : get_patom_set o\n         , t1 ===>(lib) mkc_axiom\n         # t2 ===>(lib) mkc_axiom\n         # a ===>(lib) (mkc_utoken u)\n         # type lib T\n         # equality lib t y T\n         # !LIn u (getc_utokens y)}}.\nProof.\n  introv.\n  sp_iff Case.\n\n  - Case \"->\".\n    introv equ.\n    unfold equality, nuprl in equ; exrepnd.\n    inversion equ1; subst; try not_univ.\n    match goal with\n      | [ H : per_ffatom _ _ _ _ _ |- _ ] => rename H into h\n    end.\n    unfold per_ffatom in h; exrepnd; spcast.\n    allfold (@nuprl o lib).\n    computes_to_value_isvalue.\n    apply h1 in equ0.\n    unfold per_ffatom_eq in equ0; exrepnd.\n    exists y u; dands; spcast; auto.\n\n    + exists eqa; auto.\n\n    + eapply equality_eq in h3; apply h3; auto.\n\n  - Case \"<-\".\n    introv equ; repnd; spcast.\n    unfold member, equality in equ; exrepnd; spcast.\n\n    exists (per_ffatom_eq lib eq u t).\n    dands.\n\n    + apply CL_ffatom.\n      exists T T t t a a eq u; dands; auto; spcast; auto;\n      try (apply computes_to_valc_refl; try (apply iscvalue_mkc_free_from_atom)).\n      eapply equality_eq_refl; eauto.\n\n    + unfold per_ffatom_eq; dands; spcast; auto.\n      exists y.\n      dands; auto.\nQed.\n\nLemma equality_in_free_from_atoms {o} :\n  forall lib (a b T t : @CTerm o),\n    equality lib a b (mkc_free_from_atoms T t)\n    <=> {u : CTerm\n         , a ===>(lib) mkc_axiom\n         # b ===>(lib) mkc_axiom\n         # type lib T\n         # equality lib t u T\n         # noutokensc u}.\nProof.\n  introv.\n  sp_iff Case.\n\n  - Case \"->\".\n    introv equ.\n    unfold equality, nuprl in equ; exrepnd.\n    inversion equ1; subst; try not_univ.\n    match goal with\n      | [ H : per_ffatoms _ _ _ _ _ |- _ ] => rename H into h\n    end.\n    unfold per_ffatoms in h; exrepnd; spcast.\n    allfold (@nuprl o lib).\n    computes_to_value_isvalue.\n    apply h0 in equ0.\n    unfold per_ffatoms_eq in equ0; exrepnd.\n    exists y; dands; auto.\n\n    + exists eqa; auto.\n\n    + eapply equality_eq in h3; apply h3; auto.\n\n  - Case \"<-\".\n    introv equ; repnd; spcast.\n    unfold member, equality in equ; exrepnd.\n\n    exists (per_ffatoms_eq lib eq t).\n    dands.\n\n    + apply CL_ffatoms.\n      exists T T t t eq; dands; auto; spcast;\n      try (apply computes_to_valc_refl; try (apply iscvalue_mkc_free_from_atoms)).\n      eapply equality_eq_refl; eauto.\n\n    + unfold per_ffatoms_eq; dands; spcast; auto.\n      exists u.\n      dands; auto.\nQed.\n\nLemma inhabited_free_from_atoms {o} :\n  forall lib (T t : @CTerm o),\n    inhabited_type lib (mkc_free_from_atoms T t)\n    <=> {u : CTerm\n         , type lib T\n         # equality lib t u T\n         # noutokensc u}.\nProof.\n  introv.\n  unfold inhabited_type.\n  sp_iff Case; introv h; exrepnd.\n  - apply equality_in_free_from_atoms in h0; exrepnd.\n    exists u; dands; auto.\n  - exists (@mkc_axiom o).\n    apply equality_in_free_from_atoms.\n    exists u; dands; spcast; auto;\n    try (apply computes_to_valc_refl; try (apply iscvalue_mkc_axiom)).\nQed.\n\nLemma equality_in_efree_from_atom {o} :\n  forall lib (t1 t2 T t a : @CTerm o),\n    equality lib t1 t2 (mkc_efree_from_atom T t a)\n    <=> {y : CTerm\n         , {u : get_patom_set o\n         , t1 ===>(lib) mkc_axiom\n         # t2 ===>(lib) mkc_axiom\n         # a ===>(lib) (mkc_utoken u)\n         # type lib T\n         # equality lib t y T\n         # !LIn u (getc_utokens y)}}.\nProof.\n  introv.\n  sp_iff Case.\n\n  - Case \"->\".\n    introv equ.\n    unfold equality, nuprl in equ; exrepnd.\n    inversion equ1; subst; try not_univ.\n    match goal with\n      | [ H : per_effatom _ _ _ _ _ |- _ ] => rename H into h\n    end.\n    unfold per_effatom in h; exrepnd; spcast.\n    allfold (@nuprl o lib).\n    computes_to_value_isvalue.\n    apply h0 in equ0.\n    unfold per_effatom_eq in equ0; exrepnd.\n    allunfold @name_not_in_upto; exrepnd.\n    exists y u; dands; spcast; auto.\n\n    + exists eqa; auto.\n\n    + eapply equality_eq in h3; apply h3; auto.\n\n  - Case \"<-\".\n    introv equ; repnd; spcast.\n    unfold member, equality in equ; exrepnd; spcast.\n\n    exists (per_effatom_eq lib eq a t).\n    dands.\n\n    + apply CL_effatom.\n      exists T T t t a a eq; dands; auto; spcast; auto;\n      try (apply computes_to_valc_refl; try (apply iscvalue_mkc_efree_from_atom)).\n\n    + unfold per_effatom_eq; dands; spcast; auto.\n      exists u y.\n      dands; spcast; auto.\nQed.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/per/per_props_ffatom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2404692925384661}}
{"text": "From Coq Require Import Lists.List.\nFrom Coq Require Import BinNums.\nFrom Coq Require Import ZArith.BinInt.\nFrom Coq Require Import ZArith.BinIntDef.\nFrom Coq Require Import ZArith.Zdigits.\nFrom Coq Require Import ZArith Psatz.\nImport ListNotations.\n\nOpen Scope Z_scope.\n\nInductive MMove :=\n  | MX \n  | MY\n  | MZ\n.\n\nInductive EMove :=\n  | EA\n  | EB\n  | EC\n.\n\nInductive Rule :=\n  | R : EMove -> MMove -> Rule\n.\n\nDefinition input : list Rule := [\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EC MY;\n  R EA MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EB MX;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MX;\n  R EC MZ;\n  R EB MX;\n  R EB MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MY;\n  R EC MY;\n  R EB MX;\n  R EA MZ;\n  R EB MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MX;\n  R EB MY;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MX;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MY;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EB MY;\n  R EB MX;\n  R EB MX;\n  R EA MX;\n  R EB MX;\n  R EA MZ;\n  R EB MX;\n  R EA MY;\n  R EA MX;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EA MY;\n  R EB MX;\n  R EA MY;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MY;\n  R EA MX;\n  R EA MZ;\n  R EA MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MX;\n  R EB MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EB MZ;\n  R EA MX;\n  R EA MZ;\n  R EB MX;\n  R EC MY;\n  R EC MZ;\n  R EB MX;\n  R EC MY;\n  R EC MY;\n  R EA MZ;\n  R EB MX;\n  R EC MY;\n  R EC MY;\n  R EA MZ;\n  R EC MX;\n  R EB MX;\n  R EB MY;\n  R EC MY;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EB MX;\n  R EB MX;\n  R EC MY;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MY;\n  R EB MY;\n  R EB MX;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EA MY;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EC MX;\n  R EB MX;\n  R EA MX;\n  R EB MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EB MX;\n  R EC MX;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EC MZ;\n  R EA MY;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MX;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MY;\n  R EC MZ;\n  R EA MX;\n  R EC MX;\n  R EC MY;\n  R EA MZ;\n  R EC MX;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MX;\n  R EC MZ;\n  R EB MX;\n  R EC MY;\n  R EB MX;\n  R EA MX;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EA MX;\n  R EB MX;\n  R EA MY;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EB MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MX;\n  R EC MY;\n  R EA MZ;\n  R EB MX;\n  R EB MX;\n  R EC MZ;\n  R EB MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MY;\n  R EB MX;\n  R EC MY;\n  R EA MZ;\n  R EA MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MY;\n  R EA MX;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EA MX;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MY;\n  R EA MZ;\n  R EB MX;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EB MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EB MY;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EA MZ;\n  R EC MZ;\n  R EA MY;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MZ;\n  R EB MX;\n  R EC MZ;\n  R EB MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EC MY;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MY;\n  R EC MY;\n  R EA MZ;\n  R EC MY;\n  R EB MZ;\n  R EB MY;\n  R EC MX;\n  R EB MX;\n  R EC MX;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EB MY;\n  R EC MY;\n  R EC MY;\n  R EC MX;\n  R EA MZ;\n  R EC MX;\n  R EC MZ;\n  R EB MZ;\n  R EB MX;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MY;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MY;\n  R EB MX;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EC MY;\n  R EA MZ;\n  R EC MY;\n  R EC MY;\n  R EA MX;\n  R EA MZ;\n  R EB MX;\n  R EA MZ;\n  R EB MY;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EB MX;\n  R EC MY;\n  R EB MZ;\n  R EC MY;\n  R EC MX;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EB MY;\n  R EB MY;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EB MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MX;\n  R EA MX;\n  R EA MY;\n  R EC MY;\n  R EC MY;\n  R EC MY;\n  R EA MZ;\n  R EB MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MX;\n  R EB MX;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EB MX;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EB MX;\n  R EB MX;\n  R EC MY;\n  R EC MX;\n  R EB MX;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EB MX;\n  R EC MX;\n  R EC MY;\n  R EC MZ;\n  R EA MX;\n  R EA MX;\n  R EA MY;\n  R EC MX;\n  R EC MY;\n  R EB MX;\n  R EC MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MY;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MZ;\n  R EA MY;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MY;\n  R EA MX;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MY;\n  R EB MY;\n  R EA MZ;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EB MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EC MY;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MY;\n  R EB MX;\n  R EC MZ;\n  R EA MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EC MY;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EB MX;\n  R EA MX;\n  R EA MZ;\n  R EC MZ;\n  R EB MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EB MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EA MY;\n  R EB MX;\n  R EC MY;\n  R EC MZ;\n  R EA MY;\n  R EC MY;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MY;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EA MX;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MX;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EB MZ;\n  R EC MX;\n  R EC MY;\n  R EC MY;\n  R EC MY;\n  R EA MZ;\n  R EC MX;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EA MX;\n  R EA MX;\n  R EC MZ;\n  R EA MX;\n  R EB MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EB MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EA MZ;\n  R EC MX;\n  R EC MY;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MX;\n  R EA MY;\n  R EB MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MX;\n  R EB MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EA MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MX;\n  R EA MX;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EA MY;\n  R EC MZ;\n  R EB MY;\n  R EC MX;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EB MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MY;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MX;\n  R EB MX;\n  R EC MZ;\n  R EB MY;\n  R EC MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MY;\n  R EA MZ;\n  R EB MY;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MY;\n  R EC MX;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EA MX;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EA MX;\n  R EB MY;\n  R EB MX;\n  R EB MX;\n  R EC MZ;\n  R EB MX;\n  R EC MY;\n  R EA MX;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EA MX;\n  R EB MY;\n  R EA MX;\n  R EA MZ;\n  R EB MY;\n  R EC MX;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EB MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EA MY;\n  R EA MZ;\n  R EA MX;\n  R EB MX;\n  R EB MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EA MZ;\n  R EB MX;\n  R EC MY;\n  R EB MX;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EB MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MX;\n  R EB MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MY;\n  R EB MX;\n  R EB MY;\n  R EA MZ;\n  R EA MY;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MX;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EB MX;\n  R EB MX;\n  R EC MY;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EB MX;\n  R EB MY;\n  R EA MX;\n  R EB MX;\n  R EA MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EC MZ;\n  R EB MY;\n  R EA MZ;\n  R EA MX;\n  R EB MX;\n  R EC MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EB MY;\n  R EC MY;\n  R EA MZ;\n  R EC MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EC MX;\n  R EC MX;\n  R EC MY;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EB MY;\n  R EC MY;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EB MZ;\n  R EB MY;\n  R EA MY;\n  R EB MX;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MY;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EA MZ;\n  R EA MY;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MY;\n  R EA MY;\n  R EC MY;\n  R EA MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MY;\n  R EB MY;\n  R EA MZ;\n  R EA MZ;\n  R EB MX;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MY;\n  R EA MX;\n  R EC MY;\n  R EA MX;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MY;\n  R EA MZ;\n  R EB MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MZ;\n  R EC MY;\n  R EB MY;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MX;\n  R EC MY;\n  R EB MX;\n  R EC MY;\n  R EC MY;\n  R EB MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EB MX;\n  R EB MY;\n  R EB MX;\n  R EB MX;\n  R EC MY;\n  R EA MZ;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EB MX;\n  R EB MX;\n  R EC MY;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MX;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MX;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MX;\n  R EC MY;\n  R EA MX;\n  R EA MZ;\n  R EC MX;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EA MX;\n  R EB MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MX;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MZ;\n  R EB MX;\n  R EB MY;\n  R EC MY;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EB MY;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MY;\n  R EA MX;\n  R EB MZ;\n  R EC MY;\n  R EB MX;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MX;\n  R EB MX;\n  R EB MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MX;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EC MY;\n  R EB MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EA MX;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EB MX;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MX;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EB MZ;\n  R EB MX;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EB MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EB MX;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EB MZ;\n  R EC MZ;\n  R EA MY;\n  R EB MX;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EC MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EC MY;\n  R EB MX;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MX;\n  R EB MX;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MX;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EB MZ;\n  R EA MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EB MY;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EB MX;\n  R EB MX;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MX;\n  R EA MZ;\n  R EC MY;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EB MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EB MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MY;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MX;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EB MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EB MX;\n  R EB MX;\n  R EA MZ;\n  R EB MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MX;\n  R EC MX;\n  R EC MZ;\n  R EA MX;\n  R EC MY;\n  R EA MX;\n  R EB MX;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MY;\n  R EA MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EB MX;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EB MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EB MX;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EB MZ;\n  R EB MX;\n  R EA MZ;\n  R EA MZ;\n  R EB MY;\n  R EB MY;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EB MX;\n  R EB MX;\n  R EA MX;\n  R EC MZ;\n  R EA MX;\n  R EA MX;\n  R EA MZ;\n  R EC MY;\n  R EC MX;\n  R EA MX;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EB MY;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MX;\n  R EA MX;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MY;\n  R EA MX;\n  R EA MZ;\n  R EC MX;\n  R EB MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MX;\n  R EA MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EB MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MZ;\n  R EA MX;\n  R EB MX;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MY;\n  R EB MY;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EB MY;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EB MX;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EB MX;\n  R EC MX;\n  R EA MY;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MY;\n  R EA MX;\n  R EB MY;\n  R EA MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MY;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EB MY;\n  R EA MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MY;\n  R EC MZ;\n  R EA MX;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MY;\n  R EA MX;\n  R EA MZ;\n  R EC MY;\n  R EB MX;\n  R EB MX;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MY;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EB MZ;\n  R EB MY;\n  R EB MX;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EA MX;\n  R EC MX;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MY;\n  R EA MY;\n  R EB MY;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MY;\n  R EC MZ;\n  R EA MY;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EB MX;\n  R EC MX;\n  R EB MX;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EB MX;\n  R EC MX;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EB MX;\n  R EB MX;\n  R EC MX;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MX;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MZ;\n  R EB MX;\n  R EB MX;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MY;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EA MZ;\n  R EA MZ;\n  R EA MZ;\n  R EC MY;\n  R EB MY;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MX;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MY;\n  R EB MX;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MX;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MY;\n  R EB MX;\n  R EA MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EC MY;\n  R EC MX;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MX;\n  R EC MY;\n  R EB MY;\n  R EA MX;\n  R EB MZ;\n  R EB MX;\n  R EA MX;\n  R EA MX;\n  R EA MX;\n  R EB MY;\n  R EC MY;\n  R EC MZ;\n  R EB MX;\n  R EC MY;\n  R EC MX;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MX;\n  R EB MX;\n  R EC MY;\n  R EA MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EB MY;\n  R EC MY;\n  R EB MX;\n  R EA MZ;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EB MX;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EB MX;\n  R EB MX;\n  R EA MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EB MY;\n  R EA MX;\n  R EC MY;\n  R EC MY;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EB MZ;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MY;\n  R EB MX;\n  R EC MY;\n  R EC MZ;\n  R EC MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EA MZ;\n  R EA MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MZ;\n  R EA MX;\n  R EC MY;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MX;\n  R EC MZ;\n  R EB MX;\n  R EB MZ;\n  R EC MY;\n  R EC MZ;\n  R EA MX;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EA MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MY;\n  R EC MY;\n  R EA MY;\n  R EB MX;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EC MZ;\n  R EC MY;\n  R EA MX;\n  R EA MZ;\n  R EC MY;\n  R EB MX;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EB MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MX;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MX;\n  R EC MZ;\n  R EC MX;\n  R EC MY;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EB MY;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EB MX;\n  R EA MZ;\n  R EA MX;\n  R EA MZ;\n  R EA MX;\n  R EC MY;\n  R EB MX;\n  R EA MZ;\n  R EC MY;\n  R EA MZ;\n  R EC MZ;\n  R EB MX;\n  R EB MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EC MY;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MX;\n  R EA MX;\n  R EB MZ;\n  R EC MY;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MY;\n  R EB MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MY;\n  R EC MY;\n  R EC MZ;\n  R EA MY;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EC MY;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EB MX;\n  R EA MZ;\n  R EB MX;\n  R EC MZ;\n  R EC MX;\n  R EA MX;\n  R EC MZ;\n  R EC MZ;\n  R EC MZ;\n  R EC MX;\n  R EA MZ;\n  R EA MZ;\n  R EB MX;\n  R EA MZ;\n  R EC MZ;\n  R EC MZ;\n  R EA MZ\n  ]\n.\n\nDefinition score_e (r : EMove) :=\n  match r with\n  | EA => 3\n  | EB => 0\n  | EC => 6\n  end.\n\nDefinition score_m (m : MMove) :=\n  match m with\n  | MX => 0\n  | MY => 4\n  | MZ => 8\n  end.\n\nDefinition score (r : Rule) :=\n  match r with\n  | R e m => ((score_e e) + (score_m m)) mod 9 + 1\n  end.\n\nFixpoint zsum (l : list Z) :=\n  match l with\n  | nil => 0\n  | (x :: t) => x + zsum t\n  end.\n\nCompute (zsum (map score [R EA MY;R EB MX;R EC MZ])).\nCompute (zsum (map score input)).\n\nDefinition score_res (r : Rule) :=\n  match r with\n  | R EA m => match m with\n    | MX => MZ\n    | MY => MX\n    | MZ => MY\n    end\n  | R EB m => match m with\n    | MX => MX\n    | MY => MY\n    | MZ => MZ\n    end\n  | R EC m => match m with\n    | MX => MY\n    | MY => MZ\n    | MZ => MX\n    end\n  end.\n\nDefinition score_2 (r : Rule) :=\n  match r with\n  | R EA m => score (R EA (score_res r))\n  | R EB m => score (R EB (score_res r))\n  | R EC m => score (R EC (score_res r))\n  end.\n\nCompute (zsum (map score_2 [R EA MY;R EB MX;R EC MZ])).\nCompute (zsum (map score_2 input)).", "meta": {"author": "MarcusVoelker", "repo": "AoC2022", "sha": "33f67bc9a0df5354bf111c3247f87375ee6399e3", "save_path": "github-repos/coq/MarcusVoelker-AoC2022", "path": "github-repos/coq/MarcusVoelker-AoC2022/AoC2022-33f67bc9a0df5354bf111c3247f87375ee6399e3/Day2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2404692925384661}}
{"text": "Require Import Omega.\n\nRequire Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Axioms.\nRequire Import Basic.\nRequire Import DataStructure.\nRequire Import DenseOrder.\nRequire Import Language.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import PromiseConsistent.\nRequire Import ReorderPromise.\n\nSet Implicit Arguments.\n\n\nLemma steps_pf_steps_aux\n      lang\n      n e1 e3\n      (STEPS: rtcn (@Thread.all_step lang) n e1 e3)\n      (CONS: Local.promise_consistent (Thread.local e3))\n      (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n      (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n      (MEM1: Memory.closed (Thread.memory e1)):\n  exists n' e2,\n    <<N: n' <= n>> /\\\n    <<STEPS1: rtcn (union (Thread.step true)) n' e1 e2>> /\\\n    <<STEPS2: rtc (union (Thread.step false)) e2 e3>>.\nProof.\n  revert_until n. induction n using strong_induction; i.\n  inv STEPS.\n  { esplits; eauto. }\n  inv A12. inv USTEP. exploit Thread.step_future; eauto. i. des.\n  destruct pf.\n  { exploit Thread.step_future; eauto. i. des.\n    exploit IH; eauto. i. des.\n    esplits; cycle 1.\n    + econs 2; eauto.\n    + auto.\n    + omega.\n  }\n  exploit IH; try exact A23; try refl; eauto. i. des.\n  assert (CONS2: Local.promise_consistent (Thread.local e2)).\n  { exploit rtcn_rtc; try exact A0; eauto. i.\n    exploit rtc_implies; [|exact x0|i].\n    { apply union_mon. apply Thread.allpf. }\n    exploit Thread.rtc_all_step_future; eauto. i. des.\n    eapply rtc_all_step_promise_consistent; try exact CONS; eauto.\n    eapply rtc_implies; try exact STEPS2; eauto.\n    apply union_mon. apply Thread.allpf.\n  }\n  inv STEPS1.\n  { esplits; cycle 1.\n    - eauto.\n    - econs; eauto.\n    - omega.\n  }\n  inversion A12. exploit Thread.step_future; eauto. i. des.\n  exploit reorder_nonpf_pf; eauto.\n  { exploit rtcn_rtc; try exact A0; eauto. i.\n    eapply rtc_all_step_promise_consistent; try exact CONS; eauto.\n    etrans.\n    - eapply rtc_implies; [|exact x0]. apply union_mon. apply Thread.allpf.\n    - eapply rtc_implies; [|exact STEPS2]. apply union_mon. apply Thread.allpf.\n  }\n  i. des.\n  - subst. esplits; cycle 1; eauto. omega.\n  - assert (STEPS: rtcn (@Thread.all_step lang) (S n) e1 e2).\n    { econs 2.\n      - econs. econs. eauto.\n      - eapply rtcn_imply; [|exact A0]. apply union_mon. apply Thread.allpf.\n    }\n    exploit IH; try exact STEPS; eauto.\n    { omega. }\n    i. des. esplits; cycle 1; eauto.\n    + etrans; eauto.\n    + omega.\n  - assert (STEPS: rtcn (@Thread.all_step lang) (S n) th1' e2).\n    { econs 2.\n      - econs. econs 1. eauto.\n      - eapply rtcn_imply; [|exact A0]. apply union_mon. apply Thread.allpf.\n    }\n    exploit Thread.step_future; eauto. i. des.\n    exploit IH; try exact STEPS; eauto.\n    { omega. }\n    i. des. esplits; cycle 1.\n    + econs 2; eauto.\n    + etrans; eauto.\n    + omega.\nQed.\n\nLemma steps_pf_steps\n      lang\n      e1 e3\n      (STEPS: rtc (@Thread.all_step lang) e1 e3)\n      (CONS: Local.promise_consistent (Thread.local e3))\n      (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n      (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n      (MEM1: Memory.closed (Thread.memory e1)):\n  exists e2,\n    <<STEPS1: rtc (union (Thread.step true)) e1 e2>> /\\\n    <<STEPS2: rtc (union (Thread.step false)) e2 e3>>.\nProof.\n  apply rtc_rtcn in STEPS. des.\n  exploit steps_pf_steps_aux; eauto. i. des.\n  exploit rtcn_rtc; eauto.\nQed.\n\nLemma tau_steps_pf_tau_steps_aux\n      lang\n      n e1 e3\n      (STEPS: rtcn (@Thread.tau_step lang) n e1 e3)\n      (CONS: Local.promise_consistent (Thread.local e3))\n      (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n      (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n      (MEM1: Memory.closed (Thread.memory e1)):\n  exists n' e2,\n    <<N: n' <= n>> /\\\n    <<STEPS1: rtcn (tau (Thread.step true)) n' e1 e2>> /\\\n    <<STEPS2: rtc (tau (Thread.step false)) e2 e3>>.\nProof.\n  revert_until n. induction n using strong_induction; i.\n  inv STEPS.\n  { esplits; eauto. }\n  inv A12. inv TSTEP. exploit Thread.step_future; eauto. i. des.\n  destruct pf.\n  { exploit Thread.step_future; eauto. i. des.\n    exploit IH; eauto. i. des.\n    esplits; cycle 1.\n    + econs 2; eauto.\n    + auto.\n    + omega.\n  }\n  exploit IH; try exact A23; try refl; eauto. i. des.\n  assert (CONS2: Local.promise_consistent (Thread.local e2)).\n  { exploit rtcn_rtc; try exact A0; eauto. i.\n    exploit rtc_implies; [|exact x0|i].\n    { apply tau_mon. apply Thread.allpf. }\n    exploit Thread.rtc_tau_step_future; eauto. i. des.\n    eapply rtc_all_step_promise_consistent; try exact CONS; eauto.\n    eapply rtc_implies; try exact STEPS2; eauto.\n    i. apply tau_union. eapply tau_mon; [|eauto]. apply Thread.allpf.\n  }\n  inv STEPS1.\n  { esplits; cycle 1.\n    - eauto.\n    - econs; eauto.\n    - omega.\n  }\n  inversion A12. exploit Thread.step_future; eauto. i. des.\n  exploit reorder_nonpf_pf; eauto.\n  { exploit rtcn_rtc; try exact A0; eauto. i.\n    eapply rtc_all_step_promise_consistent; try exact CONS; eauto.\n    etrans.\n    - eapply rtc_implies; [|exact x0]. i. apply tau_union. eapply tau_mon; [|eauto]. apply Thread.allpf.\n    - eapply rtc_implies; [|exact STEPS2]. i. apply tau_union. eapply tau_mon; [|eauto]. apply Thread.allpf.\n  }\n  i. des.\n  - subst. esplits; cycle 1; eauto. omega.\n  - assert (STEPS: rtcn (@Thread.tau_step lang) (S n) e1 e2).\n    { econs 2.\n      - econs. econs; eauto. unguardH EVENT1. by destruct e2', e0; des.\n      - eapply rtcn_imply; [|exact A0]. apply tau_mon. apply Thread.allpf.\n    }\n    exploit IH; try exact STEPS; eauto.\n    { omega. }\n    i. des. esplits; cycle 1; eauto.\n    + etrans; eauto.\n    + omega.\n  - assert (STEPS: rtcn (@Thread.tau_step lang) (S n) th1' e2).\n    { econs 2.\n      - econs.\n        + econs. econs 1. eauto.\n        + inv STEP2. ss.\n      - eapply rtcn_imply; [|exact A0]. apply tau_mon. apply Thread.allpf.\n    }\n    exploit Thread.step_future; eauto. i. des.\n    exploit IH; try exact STEPS; eauto.\n    { omega. }\n    i. des. esplits; cycle 1.\n    + econs 2; eauto. econs; eauto. unguardH EVENT1. by destruct e2', e0; des.\n    + etrans; eauto.\n    + omega.\nQed.\n\nLemma tau_steps_pf_tau_steps\n      lang\n      e1 e3\n      (STEPS: rtc (@Thread.tau_step lang) e1 e3)\n      (CONS: Local.promise_consistent (Thread.local e3))\n      (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n      (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n      (MEM1: Memory.closed (Thread.memory e1)):\n  exists e2,\n    <<STEPS1: rtc (tau (Thread.step true)) e1 e2>> /\\\n    <<STEPS2: rtc (tau (Thread.step false)) e2 e3>>.\nProof.\n  apply rtc_rtcn in STEPS. des.\n  exploit tau_steps_pf_tau_steps_aux; eauto. i. des.\n  exploit rtcn_rtc; eauto.\nQed.\n\nLemma steps_pf_steps_state\n      lang\n      e1 e3\n      (STEPS: rtc (@Thread.all_step lang) e1 e3)\n      (CONS: Local.promise_consistent (Thread.local e3))\n      (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n      (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n      (MEM1: Memory.closed (Thread.memory e1)):\n  exists e2,\n    <<STEPS1: rtc (union (Thread.step true)) e1 e2>> /\\\n    <<STATE: (Thread.state e3) = (Thread.state e2)>>.\nProof.\n  exploit steps_pf_steps; eauto. i. des.\n  esplits; eauto.\n  exploit Thread.rtc_all_step_future; try eapply rtc_implies; try exact STEPS1; eauto.\n  { i. inv H. econs. econs. eauto. }\n  i. des.\n  exploit Thread.rtc_step_nonpf_future; try exact STEPS2; eauto. i. des. ss.\nQed.\n\nLemma tau_steps_pf_tau_steps_state\n      lang\n      e1 e3\n      (STEPS: rtc (@Thread.tau_step lang) e1 e3)\n      (CONS: Local.promise_consistent (Thread.local e3))\n      (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n      (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n      (MEM1: Memory.closed (Thread.memory e1)):\n  exists e2,\n    <<STEPS1: rtc (tau (Thread.step true)) e1 e2>> /\\\n    <<STATE: (Thread.state e3) = (Thread.state e2)>>.\nProof.\n  exploit tau_steps_pf_tau_steps; eauto. i. des.\n  esplits; eauto.\n  exploit Thread.rtc_all_step_future; try eapply rtc_implies; try exact STEPS1; eauto.\n  { i. inv H. econs. econs. eauto. }\n  i. des.\n  exploit Thread.rtc_step_nonpf_future; try eapply rtc_implies; try exact STEPS2; eauto.\n  { i. inv H. econs. eauto. }\n  i. des. ss.\nQed.\n\n\nLemma nonpf_steps_failure\n      lang\n      pf e1 e2 e3\n      (STEPS: rtc (union (@Thread.step lang false)) e1 e2)\n      (FAILURE: Thread.step pf ThreadEvent.failure e2 e3)\n      (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n      (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n      (MEM1: Memory.closed (Thread.memory e1)):\n  exists e2', <<FAILURE: Thread.step true ThreadEvent.failure e1 e2'>>.\nProof.\n  revert_until STEPS. revert e3. induction STEPS; i.\n  { dup FAILURE. inv FAILURE0; inv STEP. eauto. }\n  inv H. exploit Thread.step_future; try exact USTEP; eauto. i. des.\n  exploit IHSTEPS; eauto. i. des.\n  inv FAILURE0; try by inv STEP.\n  exploit reorder_nonpf_program; try exact USTEP; eauto.\n  { inv STEP. inv LOCAL. inv LOCAL0. ss. }\n  i. unguard. des.\n  - subst. esplits. econs 2; eauto.\n  - esplits. econs 2; eauto.\nQed.\n\nLemma nonpf_tau_steps_failure\n      lang\n      pf e1 e2 e3\n      (STEPS: rtc (tau (@Thread.step lang false)) e1 e2)\n      (FAILURE: Thread.step pf ThreadEvent.failure e2 e3)\n      (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n      (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n      (MEM1: Memory.closed (Thread.memory e1)):\n  exists e2', <<FAILURE: Thread.step true ThreadEvent.failure e1 e2'>>.\nProof.\n  exploit rtc_implies; try apply tau_union; eauto. i.\n  eapply nonpf_steps_failure; eauto.\nQed.\n\nLemma steps_failure_pf_steps_failure\n      lang\n      pf e1 e2 e3\n      (STEPS: rtc (@Thread.all_step lang) e1 e2)\n      (FAILURE: Thread.step pf ThreadEvent.failure e2 e3)\n      (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n      (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n      (MEM1: Memory.closed (Thread.memory e1)):\n  exists e2' e3',\n    <<STEPS': rtc (union (@Thread.step lang true)) e1 e2'>> /\\\n    <<FAILURE': Thread.step true ThreadEvent.failure e2' e3'>> /\\\n    <<STATE: (Thread.state e2) = (Thread.state e2')>>.\nProof.\n  exploit steps_pf_steps; try exact STEPS; eauto.\n  { inv FAILURE; inv STEP. inv LOCAL. inv LOCAL0. ss. }\n  i. des.\n  exploit Thread.rtc_all_step_future; try eapply rtc_implies; try exact STEPS1; eauto.\n  { i. inv H. econs. econs. eauto. }\n  i. des.\n  exploit nonpf_steps_failure; try exact STEPS2; eauto. i. des.\n  esplits; eauto.\n  exploit Thread.rtc_step_nonpf_future; try exact STEPS2; eauto. i. des. ss.\nQed.\n\nLemma tau_steps_failure_pf_tau_steps_failure\n      lang\n      pf e1 e2 e3\n      (STEPS: rtc (@Thread.tau_step lang) e1 e2)\n      (FAILURE: Thread.step pf ThreadEvent.failure e2 e3)\n      (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n      (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n      (MEM1: Memory.closed (Thread.memory e1)):\n  exists e2' e3',\n    <<STEPS': rtc (tau (@Thread.step lang true)) e1 e2'>> /\\\n    <<FAILURE': Thread.step true ThreadEvent.failure e2' e3'>> /\\\n    <<STATE: (Thread.state e2) = (Thread.state e2')>>.\nProof.\n  exploit tau_steps_pf_tau_steps; try exact STEPS; eauto.\n  { inv FAILURE; inv STEP. inv LOCAL. inv LOCAL0. ss. }\n  i. des.\n  exploit Thread.rtc_tau_step_future; try eapply rtc_implies; try exact STEPS1; eauto.\n  { i. inv H. econs; eauto. econs. eauto. }\n  i. des.\n  exploit nonpf_tau_steps_failure; try exact STEPS2; eauto. i. des.\n  esplits; eauto.\n  exploit Thread.rtc_step_nonpf_future; try eapply rtc_implies; try exact STEPS2; eauto.\n  { i. inv H. econs. eauto. }\n  i. des. ss.\nQed.\n\n\nLemma union_step_nonpf_bot\n      lang e1 e2\n      (STEP: union (@Thread.step lang false) e1 e2)\n      (PROMISE: (Local.promises (Thread.local e2)) = Memory.bot):\n  False.\nProof.\n  inv STEP. inv USTEP. inv STEP. inv LOCAL. ss. subst. inv PROMISE0; ss.\n  - exploit (@Memory.add_o Memory.bot (Local.promises lc1) loc from to msg loc to)\n    ; try exact PROMISES; eauto. condtac; ss; [|des; congr].\n    rewrite Memory.bot_get. congr.\n  - exploit (@Memory.split_o Memory.bot (Local.promises lc1) loc from to ts3 msg msg3 loc to)\n    ; try exact PROMISES; eauto. condtac; ss; [|des; congr].\n    rewrite Memory.bot_get. congr.\n  - exploit (@Memory.lower_o Memory.bot (Local.promises lc1) loc from to msg0 msg loc to)\n    ; try exact PROMISES; eauto. condtac; ss; [|des; congr].\n    rewrite Memory.bot_get. congr.\nQed.\n\nLemma rtc_union_step_nonpf_bot\n      lang e1 e2\n      (STEP: rtc (union (@Thread.step lang false)) e1 e2)\n      (PROMISE: (Local.promises (Thread.local e2)) = Memory.bot):\n  e1 = e2.\nProof.\n  exploit rtc_tail; eauto. i. des; ss.\n  exfalso. eapply union_step_nonpf_bot; eauto.\nQed.\n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/promising/prop/ReorderPromises.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.24046923658977595}}
{"text": "\nRequire Export Iron.Language.SystemF2Cap.Type.\nRequire Export Iron.Language.SystemF2Cap.Value.\nRequire Export Iron.Language.SystemF2Cap.Step.Pure.\nRequire Export Iron.Language.SystemF2Cap.Store.Prop.\n\n\n(********************************************************************)\n(* Frames *)\nInductive frame : Set :=\n (* Holds the continuation of a let-expression while the right\n    of the binding is being evaluated. *)\n | FLet   : ty  -> exp      -> frame\n\n (* Private region.\n    If the first argument is some region identifier then this new\n    private region will be merged with that one when leaving its scope, \n    otherwise the region is deallocated.\n    The second argument lists the effects permitted on the region. *)\n | FPriv  : option nat -> nat -> list ty -> frame.\nHint Constructors frame.\n\n\nDefinition isFPriv (p2 : nat) (f : frame)\n := exists p1 ts, f = FPriv p1 p2 ts.\nHint Unfold isFPriv.\n\n\n(* Frame stacks *)\nDefinition stack := list frame.\nHint Unfold stack.\n\n\n(********************************************************************)\n(* Context sensitive reductions. *)\nInductive \n StepF :  store -> stprops -> stack -> exp \n       -> store -> stprops -> stack -> exp \n       -> Prop :=\n\n (* Pure evaluation *****************************)\n (* Pure evaluation in a context. *)\n | SfStep\n   :  forall ss sp fs x x'\n   ,  StepP           x           x'\n   -> StepF  ss sp fs x  ss sp fs x'\n\n (* Let contexts ********************************)\n (* Push the continuation for a let-expression onto the stack. *)\n | SfLetPush\n   :  forall ss sp fs t x1 x2\n   ,  StepF  ss sp  fs               (XLet t x1 x2)\n             ss sp (fs :> FLet t x2)  x1\n\n (* Substitute value of the bound variable into the let body. *)\n | SfLetPop\n   :  forall ss sp  fs t v1 x2\n   ,  StepF  ss sp (fs :> FLet t x2) (XVal v1)\n             ss sp  fs               (substVX 0 v1 x2)\n\n (* Region operators ****************************)\n (* Create a private region. *)\n | SfPrivatePush\n   :  forall ss sp fs ts x p\n   ,  p = allocRegion sp\n   -> StepF  ss sp                   fs                     (XPrivate ts x)\n             ss (SRegion p <: sp)   (fs :> FPriv None p ts) (substTX 0 (TRgn p) x)\n\n (* Pop the frame for a private region and delete it from the heap. *)\n | SfPrivatePop\n   :  forall ss sp fs ts v1 p\n   ,  StepF  ss                         sp (fs :> FPriv None p ts) (XVal v1)\n             (map (deallocRegion p) ss) sp  fs                     (XVal v1)\n\n (* Begin extending an existing region. *)\n | SfExtendPush\n   :  forall ss sp fs x p1 p2\n   ,  p2 = allocRegion sp\n   -> StepF ss sp                  fs                            (XExtend   (TRgn p1) x)\n            ss (SRegion p2 <: sp) (fs :> FPriv (Some p1) p2 nil) (substTX 0 (TRgn p2) x)\n\n (* Pop the frame for a region extension and merge it with the existing one. *)\n | SfExtendPop\n   :  forall ss sp fs ts p1 p2 v1\n   ,  StepF  ss                      sp (fs :> FPriv (Some p1) p2 ts) (XVal v1)\n             (map (mergeB p1 p2) ss) sp fs              (XVal (mergeV p1 p2 v1))\n\n (* Run a suspended computation *****************)\n | SfRun\n   :  forall ss sp fs x\n   ,  StepF  ss sp fs (XRun (VBox x))\n             ss sp fs x\n\n (* Store operators *****************************)\n (* Allocate a reference. *) \n | SfStoreAlloc\n   :  forall ss sp fs p1 v1\n   ,  StepF  ss                    sp  fs (XAlloc (TRgn p1) v1)\n             (StValue p1 v1 <: ss) sp  fs (XVal (VLoc (length ss)))\n\n (* Read from a reference. *)\n | SfStoreRead\n   :  forall ss sp fs l v p\n   ,  get l ss = Some (StValue p v)\n   -> StepF ss                     sp  fs (XRead (TRgn p)  (VLoc l)) \n            ss                     sp  fs (XVal v)\n\n (* Write to a reference. *)\n | SfStoreWrite\n   :  forall ss sp fs l p v1 v2 \n   ,  get l ss = Some (StValue p v1)\n   -> StepF  ss sp fs                 (XWrite (TRgn p) (VLoc l) v2)\n             (update l (StValue p v2) ss) sp fs (XVal (VConst CUnit)).\n\nHint Constructors StepF.\n\n\n\n(********************************************************************)\nLemma stepF_extends_stprops\n :  forall  ss1 sp1 fs1 x1  ss2 sp2 fs2 x2\n ,  StepF   ss1 sp1 fs1 x1  ss2 sp2 fs2 x2\n -> extends sp2 sp1.\nProof.\n intros. \n induction H; eauto.\nQed.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/devel/Iron/Language/SystemF2Cap/Step/Frame.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.24046923658977595}}
{"text": "Require Import Arith.\nRequire Import List.\nRequire Import String.\nRequire Import Ascii.\nRequire Import PipeGraph.Debug.\nRequire Import PipeGraph.Util.\nRequire Import PipeGraph.StringUtil.\nRequire Import PipeGraph.Instruction.\nRequire Import PipeGraph.Graph.\nRequire Import PipeGraph.FOLPredicate.\nRequire Import PipeGraph.GraphvizCompressed.\nRequire Import PipeGraph.ISAEdge.\n\nOpen Scope string_scope.\n\nImport ListNotations.\n\nDefinition beq_edge\n  (a b : GraphEdge)\n  : bool :=\n  match (a, b) with\n  | ((a1, a2, a3, a4), (b1, b2, b3, b4)) =>\n      andb (beq_node a1 b1) (beq_node a2 b2)\n  end.\n\nDefinition GetISAEdge\n  (a : string)\n  : ISAEdge :=\n  if beq_string a \"po\" then EdgePO\n  else if beq_string a \"co\" then EdgeCO\n  else if beq_string a \"rf\" then EdgeRF\n  else if beq_string a \"fr\" then EdgeFR\n  else if beq_string a \"rfe\" then EdgeRFE\n  else if beq_string a \"fre\" then EdgeFRE\n  else if beq_string a \"po_loc\" then EdgePO_loc\n  else if beq_string a \"po_plus\" then EdgePO_plus\n  else if beq_string a \"po_loc_plus\" then EdgePO_loc_plus\n  else if beq_string a \"fence\" then EdgeFence\n  else if beq_string a \"to_fence\" then EdgeToFence\n  else if beq_string a \"from_fence\" then EdgeFromFence\n  else if beq_string a \"fence_plus\" then EdgeFence_plus\n  else if beq_string a \"FencePO_plus\" then EdgeFencePO_plus\n  else if beq_string a \"POFence_plus\" then EdgePOFence_plus\n  else if beq_string a \"ppo\" then EdgePPO\n  else if beq_string a \"ppo_plus\" then EdgePPO_plus\n  else if beq_string a \"FencePPO_plus\" then EdgeFencePPO_plus\n  else if beq_string a \"PPOFence_plus\" then EdgePPOFence_plus\n  else Warning EdgePO [\"Got a dependency I can't handle: \"; a].\n\nDefinition beq_pred\n  (a b : FOLSymPred)\n  : bool :=\n  match (a, b) with\n  | (SymPredIsRead a, SymPredIsRead a')\n  | (SymPredIsWrite a, SymPredIsWrite a')\n  | (SymPredIsFence a, SymPredIsFence a')\n  | (SymPredKnownData a, SymPredKnownData a')\n  | (SymPredDataFromPAInitial a, SymPredDataFromPAInitial a')\n  | (SymPredDataFromPAFinal a, SymPredDataFromPAFinal a') =>\n      beq_uop a a'\n  | (SymPredIsAPICAccess a b, SymPredIsAPICAccess a' b')\n  | (SymPredAccessType a b, SymPredAccessType a' b') =>\n      andb (beq_uop a a') (beq_string b b')\n  | (SymPredOnCore a b, SymPredOnCore a' b')\n  | (SymPredOnThread a b, SymPredOnThread a' b') =>\n      andb (beq_uop a a') (beq_nat b b')\n  | (SymPredSameCore a b, SymPredSameCore a' b')\n  | (SymPredSameIntraInstID a b, SymPredSameIntraInstID a' b')\n  | (SymPredSameThread a b, SymPredSameThread a' b')\n  | (SymPredSameVirtualAddress a b, SymPredSameVirtualAddress a' b')\n  | (SymPredSamePhysicalAddress a b, SymPredSamePhysicalAddress a' b')\n  | (SymPredSameVirtualTag a b, SymPredSameVirtualTag a' b')\n  | (SymPredSamePhysicalTag a b, SymPredSamePhysicalTag a' b')\n  | (SymPredSameIndex a b, SymPredSameIndex a' b')\n  | (SymPredSameData a b, SymPredSameData a' b')\n  | (SymPredSamePAasPTEforVA a b, SymPredSamePAasPTEforVA a' b') =>\n      (* Allow symmetry *)\n      orb (andb (beq_uop a a') (beq_uop b b'))\n          (andb (beq_uop a b') (beq_uop b a'))\n  | (SymPredProgramOrder a b, SymPredProgramOrder a' b')\n  | (SymPredConsec a b, SymPredConsec a' b') =>\n      (* No symmetry *)\n      andb (beq_uop a a') (beq_uop b b')\n  | (SymPredHasDependency a b c, SymPredHasDependency a' b' c') =>\n      (* No symmetry *)\n      andb (andb (beq_uop a a') (beq_uop b b')) (beq_isa_edge c c')\n  | _ => false\n  end.\n\n\nInductive ScenarioTree : Set :=\n| ScenarioName : string -> ScenarioTree -> ScenarioTree\n| ScenarioConflict : ScenarioTree -> ScenarioTree\n| ScenarioAnd : ScenarioTree -> ScenarioTree -> ScenarioTree\n| ScenarioOr : ScenarioTree -> ScenarioTree -> ScenarioTree\n| ScenarioEdgeLeaf : list GraphEdge -> ScenarioTree\n| ScenarioNotEdgeLeaf : list GraphEdge -> ScenarioTree\n| ScenarioNodeLeaf : list GraphNode -> ScenarioTree\n| ScenarioNotNodeLeaf : list GraphNode -> ScenarioTree\n| ScenarioPred : FOLSymPred -> ScenarioTree\n| ScenarioNotPred : FOLSymPred -> ScenarioTree\n| ScenarioTrue : ScenarioTree\n| ScenarioFalse : ScenarioTree.\n\nFixpoint FlipEdgesHelper\n  (l r : list GraphEdge)\n  : list GraphEdge :=\n  match l with\n  | (s, d, label, c) :: t =>\n      FlipEdgesHelper t ((d, s, label, c) :: r)\n  | [] => r\n  end.\n\nDefinition FlipEdges\n  (l : list GraphEdge)\n  : list GraphEdge :=\n  FlipEdgesHelper l [].\n\nFixpoint PrintLabelsHelper\n  (l : list string)\n  (r : string)\n  : string :=\n  match l with\n  | h::t => PrintLabelsHelper t (StringOf [h; \"\\n\"; r])\n  | [] => r\n  end.\n\nDefinition PrintLabels\n  (l : option (list string))\n  : string :=\n  match l with\n  | Some l' => PrintLabelsHelper l' EmptyString\n  | None => EmptyString\n  end.\n\nDefinition PrintEdgeLabels\n  (l : list GraphEdge)\n  : string :=\n  match l with\n  | h::t =>\n    fold_left (fun a b => StringOf [a; \"\\n\"; ShortStringOfGraphEdge b]) t\n      (ShortStringOfGraphEdge h)\n  | [] => \"-\"\n  end.\n\nDefinition PrintNodeLabels\n  (l : list GraphNode)\n  : string :=\n  match l with\n  | h::t =>\n    fold_left (fun a b => StringOf [a; \"\\n\"; ShortStringOfGraphNode b]) t\n      (ShortStringOfGraphNode h)\n  | [] => \"-\"\n  end.\n\nDefinition PrintPredicate\n  (p : FOLSymPred)\n  : list string :=\n  match p with\n  | SymPredHasDependency a b c => [\"HasDependency \"; stringOfNat (globalID a); \" \";\n      stringOfNat (globalID b);  PrintISAEdge c]\n  | SymPredIsRead a => [\"IsAnyRead \"; stringOfNat (globalID a)] \n  | SymPredIsWrite a => [\"IsAnyWrite \"; stringOfNat (globalID a)]\n  | SymPredIsAPICAccess a b => [\"IsAPICAccess \"; stringOfNat (globalID a); \" \"; b]\n  | SymPredIsFence a => [\"IsAnyFence \"; stringOfNat (globalID a)]\n  | SymPredAccessType a b => [\"AccessType \"; stringOfNat (globalID a); \" \"; b]\n  | SymPredSameCore a b => [\"SameCore \"; stringOfNat (globalID a); \" \"; stringOfNat (globalID b)]\n  | SymPredSameIntraInstID a b => [\"SameIntraInstID \"; stringOfNat (globalID a); \" \"; stringOfNat (globalID b)]\n  | SymPredSameThread a b => [\"SameThread \"; stringOfNat (globalID a); \" \"; stringOfNat (globalID b)]\n  | SymPredOnCore a b => [\"OnCore \"; stringOfNat (globalID a); \" \"; stringOfNat b]\n  | SymPredOnThread a b => [\"OnThread \"; stringOfNat (globalID a); \" \"; stringOfNat b]\n  | SymPredSameVirtualAddress a b => [\"SameVirtualAddress \"; stringOfNat (globalID a); \" \"; stringOfNat (globalID b)]\n  | SymPredSamePhysicalAddress a b => [\"SamePhysicalAddress \"; stringOfNat (globalID a); \" \"; stringOfNat (globalID b)]\n  | SymPredSameVirtualTag a b => [\"SameVirtualTag \"; stringOfNat (globalID a); \" \"; stringOfNat (globalID b)]\n  | SymPredSamePhysicalTag a b => [\"SamePhysicalTag \"; stringOfNat (globalID a); \" \"; stringOfNat (globalID b)]\n  | SymPredSameIndex a b => [\"SameIndex \"; stringOfNat (globalID a); \" \"; stringOfNat (globalID b)]\n  | SymPredKnownData a => [\"KnownData \"; stringOfNat (globalID a)]\n  | SymPredSameData a b => [\"SameData \"; stringOfNat (globalID a); \" \"; stringOfNat (globalID b)]\n  | SymPredDataFromPAInitial a => [\"DataFromPAInitial \"; stringOfNat (globalID a)]\n  | SymPredDataFromPAFinal a => [\"DataFromPAFinal \"; stringOfNat (globalID a)]\n  | SymPredSamePAasPTEforVA a b => [\"SamePAasPTEforVA \"; stringOfNat (globalID a); \" \"; stringOfNat (globalID b)]\n  | SymPredProgramOrder a b => [\"ProgramOrder \"; stringOfNat (globalID a); \" \"; stringOfNat (globalID b)]\n  | SymPredConsec a b => [\"ConsecutiveMicroops \"; stringOfNat (globalID a); \" \"; stringOfNat (globalID b)]\n  end.\n\nFixpoint ScenarioTreeEdgeCountGraphHelper\n  (ac : bool) (* all conjunctions *)\n  (t : ScenarioTree)\n  (id : nat)\n  (n : option (list string))\n  : nat * nat :=\n  match t with\n  | ScenarioName n'' t' =>\n     match n with\n     | Some n' => ScenarioTreeEdgeCountGraphHelper ac t' id (Some (n'' :: n'))\n     | None => ScenarioTreeEdgeCountGraphHelper ac t' id (Some [n''])\n     end\n  | ScenarioConflict t' =>\n     match n with\n     | Some n' => ScenarioTreeEdgeCountGraphHelper ac t' id (Some (\"Conflict\" :: n'))\n     | None => ScenarioTreeEdgeCountGraphHelper ac t' id (Some [\"Conflict\"])\n     end\n  | ScenarioEdgeLeaf l =>\n      let result := (1, id) in\n      Println result [\"  n\"; stringOfNat id; \" [shape=\";\n        if ac then \"box\" else \"oval\"; \",label=\"\"\";\n        PrintLabels n;\n        stringOfNat (List.length l); \" edges\\n\";\n        PrintEdgeLabels l; \"\"\"];\"]\n  | ScenarioNotEdgeLeaf l =>\n      let result := (1, id) in\n      Println result [\"  n\"; stringOfNat id; \" [shape=\";\n        if ac then \"box\" else \"oval\"; \",label=\"\"\";\n        PrintLabels n;\n        stringOfNat (List.length l); \" edges\\nNot all of:\\n\";\n        PrintEdgeLabels l; \"\"\"];\"]\n  | ScenarioNodeLeaf l =>\n      let result := (1, id) in\n      Println result [\"  n\"; stringOfNat id; \" [shape=\";\n        if ac then \"box\" else \"oval\"; \",label=\"\"\";\n        PrintLabels n;\n        stringOfNat (List.length l); \" nodes\";\n        PrintNodeLabels l; \"\"\"];\"]\n  | ScenarioNotNodeLeaf l =>\n      let result := (1, id) in\n      Println result [\"  n\"; stringOfNat id; \" [shape=\";\n        if ac then \"box\" else \"oval\"; \",label=\"\"\";\n        PrintLabels n;\n        stringOfNat (List.length l); \" nodes\\nNot all of:\\n\";\n        PrintNodeLabels l; \"\"\"];\"]\n  | ScenarioPred p =>\n      let result := (1, id) in\n      Println result [\"  n\"; stringOfNat id; \" [shape=\";\n        if ac then \"box\" else \"oval\"; \",label=\"\"\";\n        StringOf (PrintPredicate p); \"\"\"];\"]\n  | ScenarioNotPred p =>\n      let result := (1, id) in\n      Println result [\"  n\"; stringOfNat id; \" [shape=\";\n        if ac then \"box\" else \"oval\"; \",label=\"\"NOT \";\n        StringOf (PrintPredicate p); \"\"\"];\"]\n  | ScenarioAnd a b =>\n      let (a_count, a_id) := ScenarioTreeEdgeCountGraphHelper ac a id None in\n      let (b_count, b_id) := ScenarioTreeEdgeCountGraphHelper ac b (S a_id) None in\n      let count := a_count * b_count in\n      let color :=\n        if andb (blt_nat 1 a_count) (blt_nat 1 b_count)\n        then \"green\"\n        else \"black\" in\n      let result := (count, S b_id) in\n      let result :=\n        Println result [\"  n\"; stringOfNat (S b_id); \" [shape=\";\n        if ac then \"box\" else \"oval\"; \",color=\";\n          color; \";label=\"\"\";\n        PrintLabels n;\n        \"AND\"\"];\"] in\n      let result := Println result [\"  n\"; stringOfNat (S b_id); \" -> n\";\n        stringOfNat a_id; \";\"] in\n      let result := Println result [\"  n\"; stringOfNat (S b_id); \" -> n\";\n        stringOfNat b_id; \";\"] in\n      result\n  | ScenarioOr a b =>\n      let (a_count, a_id) := ScenarioTreeEdgeCountGraphHelper false a id None in\n      let (b_count, b_id) := ScenarioTreeEdgeCountGraphHelper false b (S a_id) None in\n      let count := a_count + b_count in\n      let color :=\n        if andb (blt_nat 0 a_count) (blt_nat 0 b_count)\n        then \"blue\"\n        else \"black\" in\n      let result := (count, S b_id) in\n      let result :=\n        Println result [\"  n\"; stringOfNat (S b_id); \" [shape=\";\n        if ac then \"box\" else \"oval\"; \",color=blue;label=\"\"\";\n        PrintLabels n;\n        \"OR\"\"];\"] in\n      let result := Println result [\"  n\"; stringOfNat (S b_id); \" -> n\";\n        stringOfNat a_id; \";\"] in\n      let result := Println result [\"  n\"; stringOfNat (S b_id); \" -> n\";\n        stringOfNat b_id; \";\"] in\n      result\n  | ScenarioTrue =>\n      let result := (1, id) in\n      Println result [\"  n\"; stringOfNat id; \" [shape=\";\n        if ac then \"box\" else \"oval\"; \",label=\"\"TRUE\"\"];\"]\n  | ScenarioFalse => \n      let result := (1, id) in\n      Println result [\"  n\"; stringOfNat id; \" [shape=\";\n        if ac then \"box\" else \"oval\"; \",color=red,label=\"\"FALSE\"\"];\"]\n  end.\n\nDefinition ScenarioTreeEdgeCountGraphHelper1\n  (t : ScenarioTree)\n  (n : string)\n  : ScenarioTree :=\n  let t := Println t [\"digraph \"; n; \" {\"] in\n  let t := Println t [tab; \"label=\"\"\"; n; \"\"\";\"] in\n  let t := Println t [tab; \"layout=dot;\"] in\n  let t := Println t [tab; \"rankdir=LR;\"] in\n  let (count, _) := ScenarioTreeEdgeCountGraphHelper true t 0 None in\n  Println t [\"}\"; newline; \"// \"; stringOfNat count; \" scenarios\"; newline].\n\nDefinition ScenarioTreeEdgeCountGraph\n  (f : nat)\n  (t : ScenarioTree)\n  (n : string)\n  : ScenarioTree :=\n  if PrintFlag f\n  then ScenarioTreeEdgeCountGraphHelper1 t n\n  else t.\n\nFixpoint ReducesToTrue\n  (t : ScenarioTree)\n  : bool :=\n  match t with\n  | ScenarioName _ t'\n  | ScenarioConflict t' => ReducesToTrue t'\n  | ScenarioEdgeLeaf [] => true\n  | ScenarioEdgeLeaf _ => false\n  | ScenarioNotEdgeLeaf [] => true\n  | ScenarioNotEdgeLeaf _ => false\n  | ScenarioNodeLeaf [] => true\n  | ScenarioNodeLeaf _ => false\n  | ScenarioNotNodeLeaf [] => true\n  | ScenarioNotNodeLeaf _ => false\n  | ScenarioPred _ => false\n  | ScenarioNotPred _ => false\n  | ScenarioAnd a b => andb (ReducesToTrue a) (ReducesToTrue b)\n  | ScenarioOr a b => orb (ReducesToTrue a) (ReducesToTrue b)\n  | ScenarioTrue => true\n  | ScenarioFalse => false\n  end.\n\nFixpoint ReducesToFalse\n  (t : ScenarioTree)\n  : bool :=\n  match t with\n  | ScenarioName _ t'\n  | ScenarioConflict t' => ReducesToFalse t'\n  | ScenarioEdgeLeaf _ => false\n  | ScenarioNotEdgeLeaf _ => false\n  | ScenarioNodeLeaf _ => false\n  | ScenarioNotNodeLeaf _ => false\n  | ScenarioPred _ => false\n  | ScenarioNotPred _ => false\n  | ScenarioAnd a b => orb (ReducesToFalse a) (ReducesToFalse b)\n  | ScenarioOr a b => andb (ReducesToFalse a) (ReducesToFalse b)\n  | ScenarioTrue => false\n  | ScenarioFalse => true\n  end.\n\nFixpoint SimplifyScenarioTree\n  (t : ScenarioTree)\n  : ScenarioTree :=\n  match t with\n  | ScenarioName n t' =>\n      match SimplifyScenarioTree t' with\n      | ScenarioTrue => ScenarioTrue\n      | ScenarioFalse => ScenarioFalse\n      | t'' => ScenarioName n t''\n      end\n  | ScenarioConflict t' =>\n      match SimplifyScenarioTree t' with\n      | ScenarioTrue => ScenarioTrue\n      | ScenarioFalse => ScenarioFalse\n      | t'' => ScenarioConflict t''\n      end\n  | ScenarioEdgeLeaf [] => ScenarioTrue\n  | ScenarioNotEdgeLeaf [] => ScenarioTrue\n  | ScenarioNodeLeaf [] => ScenarioTrue\n  | ScenarioNotNodeLeaf [] => ScenarioTrue\n  | ScenarioEdgeLeaf l => t\n  | ScenarioNotEdgeLeaf l => t\n  | ScenarioNodeLeaf l => t\n  | ScenarioNotNodeLeaf l => t\n  | ScenarioPred _ => t\n  | ScenarioNotPred _ => t\n  | ScenarioAnd a b =>\n      let a' := SimplifyScenarioTree a in\n      let b' := SimplifyScenarioTree b in\n      if ReducesToFalse a' then ScenarioFalse else\n      if ReducesToFalse b' then ScenarioFalse else\n      if ReducesToTrue a' then b' else\n      if ReducesToTrue b' then a' else\n      ScenarioAnd a' b'\n  | ScenarioOr a b =>\n      let a' := SimplifyScenarioTree a in\n      let b' := SimplifyScenarioTree b in\n      if ReducesToTrue a' then ScenarioTrue else\n      if ReducesToTrue b' then ScenarioTrue else\n      if ReducesToFalse a' then b' else\n      if ReducesToFalse b' then a' else\n      ScenarioOr a' b'\n  | ScenarioTrue => t\n  | ScenarioFalse => t\n  end.\n\nFixpoint GuaranteedEdges\n  (s : ScenarioTree)\n  : (list GraphNode * list GraphNode * list GraphEdge * list GraphEdge * list FOLSymPred * list FOLSymPred) :=\n  match s with\n  | ScenarioName _ s\n  | ScenarioConflict s => GuaranteedEdges s\n  | ScenarioNodeLeaf l => (l, [], [], [], [], [])\n  | ScenarioNotNodeLeaf l => ([], l, [], [], [], [])\n  | ScenarioEdgeLeaf l => ([], [], l, [], [], [])\n  | ScenarioNotEdgeLeaf l => ([], [], [], l, [], [])\n  | ScenarioPred p => ([], [], [], [], [p], [])\n  | ScenarioNotPred p => ([], [], [], [], [], [p])\n  | ScenarioAnd a b =>\n      match (GuaranteedEdges a, GuaranteedEdges b) with\n      | ((a1, a2, a3, a4, a5, a6), (b1, b2, b3, b4, b5, b6)) =>\n          (app_rev a1 b1, app_rev a2 b2, app_rev a3 b3, app_rev a4 b4, app_rev a5 b5, app_rev a6 b6)\n      end\n  (* YM: This could maybe be optimized by checking what is common between both branches of the OR... *)\n  | ScenarioOr _ _ => ([], [], [], [], [], [])\n  | ScenarioTrue => ([], [], [], [], [], [])\n  | ScenarioFalse => Warning ([], [], [], [], [], [])\n      [\"Shouldn't try to calculate the GuaranteedEdges of FALSE\"]\n  end.\n\nFixpoint ContainsOnlyEdges\n  (t: ScenarioTree)\n  : bool :=\n  match t with\n  | ScenarioName _ s\n  | ScenarioConflict s => ContainsOnlyEdges s\n  | ScenarioEdgeLeaf _ => true\n  | ScenarioNotEdgeLeaf _ => true\n  | ScenarioNodeLeaf _ => true\n  | ScenarioNotNodeLeaf _ => true\n  | ScenarioPred _ => false\n  | ScenarioNotPred _ => false\n  | ScenarioAnd a b => andb (ContainsOnlyEdges a) (ContainsOnlyEdges b)\n  | ScenarioOr a b => andb (ContainsOnlyEdges a) (ContainsOnlyEdges b)\n  | ScenarioTrue => true\n  | ScenarioFalse => true\n  end.\n\nFixpoint ContainsOnlyPreds\n  (t: ScenarioTree)\n  : bool :=\n  match t with\n  | ScenarioName _ s\n  | ScenarioConflict s => ContainsOnlyPreds s\n  | ScenarioEdgeLeaf _ => false\n  | ScenarioNotEdgeLeaf _ => false\n  | ScenarioNodeLeaf _ => false\n  | ScenarioNotNodeLeaf _ => false\n  | ScenarioPred _ => true\n  | ScenarioNotPred _ => true\n  | ScenarioAnd a b => andb (ContainsOnlyPreds a) (ContainsOnlyPreds b)\n  | ScenarioOr a b => andb (ContainsOnlyPreds a) (ContainsOnlyPreds b)\n  | ScenarioTrue => true\n  | ScenarioFalse => true\n  end.\n\nFixpoint ListContainsOnlyEdges\n  (l: list ScenarioTree)\n  : bool :=\n  match l with\n  | [] => true\n  | h::t => if ContainsOnlyEdges h then ListContainsOnlyEdges t else false\n  end.\n\nFixpoint ListContainsOnlyPreds\n  (l: list ScenarioTree)\n  : bool :=\n  match l with\n  | [] => true\n  | h::t => if ContainsOnlyPreds h then ListContainsOnlyPreds t else false\n  end.\n\nFixpoint SortPredsHelper\n  (l: list ScenarioTree)\n  (l1: list ScenarioTree)\n  (l2: list ScenarioTree)\n  (l3: list ScenarioTree)\n  : list ScenarioTree :=\n  match l with\n  | [] => app_tail l3 (app_tail l2 l1)\n  | h::t => match h with\n            | ScenarioPred (SymPredHasDependency _ _ _)\n            | ScenarioNotPred (SymPredHasDependency _ _ _) => SortPredsHelper t (h::l1) l2 l3\n            | ScenarioPred (SymPredIsRead _ )\n            | ScenarioPred (SymPredIsWrite _ )\n            | ScenarioPred (SymPredSameCore _ _)\n            | ScenarioPred (SymPredSamePhysicalAddress _ _)\n            | ScenarioPred (SymPredSameData _ _) => SortPredsHelper t l1 (h::l2) l3\n            | _ => SortPredsHelper t l1 l2 (h::l3)\n            end\n  end.\n\nFixpoint ScoreOfTree\n  (t : ScenarioTree)\n  : nat :=\n  match t with\n  | ScenarioName _ s\n  | ScenarioConflict s => ScoreOfTree s\n  | ScenarioEdgeLeaf l\n  | ScenarioNotEdgeLeaf l\n  | ScenarioNodeLeaf l\n  | ScenarioNotNodeLeaf l => List.length l\n  | ScenarioPred _ => 1\n  | ScenarioNotPred _ => 1\n  | ScenarioAnd a b => (ScoreOfTree a) + (ScoreOfTree b)\n  | ScenarioOr a b => Warning (ScoreOfTree a) [\"An OR in ScoreOfTree?\"]\n  | ScenarioTrue => 0\n  | ScenarioFalse => 0\n  end.\n\nFixpoint InsertInto\n  (sorted : list (nat * ScenarioTree))\n  (elem : nat * ScenarioTree)\n  : list (nat * ScenarioTree) :=\n  let (score, t) := elem in\n  match sorted with\n  | [] => [elem]\n  | h::t => let (score', t') := h in\n            if blt_nat score score' then\n              h::(InsertInto t elem)\n            else\n              elem::sorted\n  end.\n\n\nFixpoint InsertionSort\n  (sorted to_sort : list (nat * ScenarioTree))\n  : list (nat * ScenarioTree) :=\n  match to_sort with\n  | [] => sorted\n  | h::t => InsertionSort (InsertInto sorted h) t\n  end.\n\nDefinition SortPreds\n  (l : list ScenarioTree)\n  : list ScenarioTree :=\n  let f x := (ScoreOfTree x, x) in\n  let g x := snd x in\n  Map g (InsertionSort [] (Map f l)).\n\nFixpoint SortChoicesHelper\n  (l: list ScenarioTree)\n  (l1: list ScenarioTree)\n  (l2: list ScenarioTree)\n  (l3: list ScenarioTree)\n  : list ScenarioTree :=\n  match l with\n  | [] => app_tail (app_tail (SortPreds l2) l1) l3\n  | h::t => if ContainsOnlyEdges h then\n              SortChoicesHelper t (h::l1) l2 l3\n            else if ContainsOnlyPreds h then\n              SortChoicesHelper t l1 (h::l2) l3\n            else\n              SortChoicesHelper t l1 l2 (h::l3)\n  end.\n\nFixpoint SortChoices\n  (l: list ScenarioTree)\n  : list ScenarioTree :=\n  SortChoicesHelper l [] [] [].\n\nFixpoint ScenarioTreeCrossProductHelper\n  (a : ScenarioTree)\n  (b : list ScenarioTree)\n  : list ScenarioTree :=\n  let f x := ScenarioAnd a x in\n  Map f b.\n\nFixpoint ScenarioTreeCrossProduct\n  (a : list ScenarioTree)\n  (b : list ScenarioTree)\n  (c : list ScenarioTree)\n  : list ScenarioTree :=\n  match a with\n  | [] => c\n  | h::t => ScenarioTreeCrossProduct t b (app_rev (ScenarioTreeCrossProductHelper h b) c)\n  end.\n\nDefinition ListContainsOnlyMatching\n  (f : ScenarioTree -> bool)\n  (l : list ScenarioTree)\n  : bool :=\n  fold_left andb (Map f l) true.\n\nDefinition ListContainsOnlyHasDeps\n  (l : list ScenarioTree)\n  : bool :=\n  let f x :=\n    match x with\n    | ScenarioPred (SymPredHasDependency _ _ _) => true\n    | ScenarioNotPred (SymPredHasDependency _ _ _) => true\n    | _ => false\n    end\n  in\n  ListContainsOnlyMatching f l.\n\nDefinition ListContainsOnlyNotEdges\n  (l : list ScenarioTree)\n  : bool :=\n  let f x :=\n    match x with\n    | ScenarioNotEdgeLeaf _ => true\n    | _ => false\n    end\n  in\n  ListContainsOnlyMatching f l.\n\nDefinition BelowCPThresholdInternal (n : nat) := false.\n\nDefinition BelowCrossThreshold\n  (l : list ScenarioTree)\n  : bool :=\n  BelowCPThresholdInternal (List.length l).\n\nDefinition MostCommonPreds\n  (p : FOLSymPred)\n  : bool :=\n  match p with\n  | SymPredIsRead _\n  | SymPredIsWrite _\n  | SymPredSamePhysicalAddress _ _\n  | SymPredSameCore _ _\n  | SymPredProgramOrder _ _\n  | SymPredHasDependency _ _ _ => true\n  | _ => false\n  end.\n\nFixpoint PredicateScore\n  (f : FOLSymPred -> bool)\n  (t : ScenarioTree)\n  : nat :=\n  match t with\n  | ScenarioName _ s => PredicateScore f s\n  | ScenarioConflict s => 5 * (PredicateScore f s) (* This better be enough... *)\n  | ScenarioEdgeLeaf l\n  | ScenarioNotEdgeLeaf l\n  | ScenarioNodeLeaf l\n  | ScenarioNotNodeLeaf l => 2 * (List.length l)\n  | ScenarioPred p\n  | ScenarioNotPred p => if (f p) then 1 else 0\n  | ScenarioAnd a b => (PredicateScore f a) + (PredicateScore f b)\n  | ScenarioOr a b => Warning 0 [\"OR in a choice in PredicateScore???\"]\n  | ScenarioTrue => 0\n  | ScenarioFalse => 0\n  end.\n\nDefinition ListPredicateScore\n  (l : list ScenarioTree)\n  : nat :=\n  fold_left plus (Map (PredicateScore MostCommonPreds) l) 0.\n\nInductive BranchingStrategy : Set :=\n| DefaultStrat : BranchingStrategy\n| HasDepStrat : bool -> BranchingStrategy\n| NotEdgeStrat : bool -> BranchingStrategy.\n\nInductive BranchingChoice : Set :=\n| RegularChoice : list ScenarioTree -> BranchingChoice\n| ConflictChoice : list ScenarioTree -> BranchingChoice.\n\nFixpoint FindBranchingChoices\n  (strat : BranchingStrategy)\n  (s : ScenarioTree)\n  : option BranchingChoice :=\n  match s with\n  | ScenarioName _ s => FindBranchingChoices strat s\n  | ScenarioConflict s =>\n      match FindBranchingChoices strat s with\n      | None => Warning None [\"No branching choices inside a conflict clause?\"]\n      | Some (RegularChoice l)\n      | Some (ConflictChoice l) => Some (ConflictChoice l)\n      end\n  | ScenarioEdgeLeaf [] => None\n  | ScenarioEdgeLeaf l => Some (RegularChoice [s])\n  | ScenarioNotEdgeLeaf [] => None\n  | ScenarioNotEdgeLeaf l => Some (RegularChoice [s])\n  | ScenarioNodeLeaf [] => None\n  | ScenarioNodeLeaf l => Some (RegularChoice [s])\n  | ScenarioNotNodeLeaf [] => None\n  | ScenarioNotNodeLeaf l => Some (RegularChoice [s])\n  | ScenarioPred p => Some (RegularChoice [s])\n  | ScenarioNotPred p => Some (RegularChoice [s])\n  | ScenarioAnd a b =>\n      match FindBranchingChoices strat a with\n      | None => FindBranchingChoices strat b\n      | Some a' =>\n          match a' with\n          | RegularChoice a''\n          | ConflictChoice a'' =>\n              match FindBranchingChoices strat b with\n              | None => Some a'\n              | Some b' => \n                  match b' with\n                  | RegularChoice b''\n                  | ConflictChoice b'' =>\n                           match strat with\n                           | DefaultStrat =>\n                              (* Are we dealing with small lists? *)\n                              if andb (BelowCrossThreshold a'') (BelowCrossThreshold b'') then\n                                (* The lists are already bound to a'' and b'' above, so we don't create new variables here... *)\n                                match (a', b') with\n                                | (ConflictChoice _, ConflictChoice _) =>\n                                    Some (ConflictChoice (ScenarioTreeCrossProduct a'' b'' []))\n                                | _ =>\n                                    Some (RegularChoice (ScenarioTreeCrossProduct a'' b'' []))\n                                end\n                              else\n                                (* The lists are already bound to a'' and b'' above, so we don't create new variables here... *)\n                                match (a', b') with\n                                | (RegularChoice _, RegularChoice _)\n                                | (ConflictChoice _, ConflictChoice _) =>\n                                  (* Just pick the largest of the ORs; try and eliminate as much of the ScenarioTree as possible *)\n                                  if bgt_nat (List.length a'') (List.length b'') then\n                                    Some a'\n                                  else\n                                    Some b'\n                                | (ConflictChoice _, _) => Some (ConflictChoice a'')\n                                | (_, ConflictChoice _) => Some (ConflictChoice b'')\n                                end\n                           | HasDepStrat first =>\n                              if first then\n                                if bgt_nat (List.length a'') (List.length b'') then\n                                  if ListContainsOnlyHasDeps a'' then Some a'\n                                  else if ListContainsOnlyHasDeps b'' then Some b'\n                                  else Some a'\n                                else\n                                  if ListContainsOnlyHasDeps b'' then Some b'\n                                  else if ListContainsOnlyHasDeps a'' then Some a'\n                                  else Some b'\n                              else\n                                (* Are we dealing with small lists? *)\n                                if andb (BelowCrossThreshold a'') (BelowCrossThreshold b'') then\n                                  match (a', b') with\n                                  | (ConflictChoice _, ConflictChoice _) =>\n                                      Some (ConflictChoice (ScenarioTreeCrossProduct a'' b'' []))\n                                  | _ =>\n                                      Some (RegularChoice (ScenarioTreeCrossProduct a'' b'' []))\n                                  end\n                                else\n                                  (* The lists are already bound to a'' and b'' above, so we don't create new variables here... *)\n                                  match (a', b') with\n                                  | (RegularChoice _, RegularChoice _)\n                                  | (ConflictChoice _, ConflictChoice _) =>\n                                    (* Just pick the largest of the ORs; try and eliminate as much of the ScenarioTree as possible *)\n                                    if bgt_nat (List.length a'') (List.length b'') then\n                                      Some a'\n                                    else\n                                      Some b'\n                                  | (ConflictChoice _, _) => Some (ConflictChoice a'')\n                                  | (_, ConflictChoice _) => Some (ConflictChoice b'')\n                                  end\n                           | NotEdgeStrat first =>\n                              if first then\n                                if bgt_nat (List.length a'') (List.length b'') then\n                                  if ListContainsOnlyNotEdges a'' then Some a'\n                                  else if ListContainsOnlyNotEdges b'' then Some b'\n                                  else Some a'\n                                else\n                                  if ListContainsOnlyNotEdges b'' then Some b'\n                                  else if ListContainsOnlyNotEdges a'' then Some a'\n                                  else Some b'\n                              else\n                                (* Are we dealing with small lists? *)\n                                if andb (BelowCrossThreshold a'') (BelowCrossThreshold b'') then\n                                  match (a', b') with\n                                  | (ConflictChoice _, ConflictChoice _) =>\n                                      Some (ConflictChoice (ScenarioTreeCrossProduct a'' b'' []))\n                                  | _ =>\n                                      Some (RegularChoice (ScenarioTreeCrossProduct a'' b'' []))\n                                  end\n                                else\n                                  (* The lists are already bound to a'' and b'' above, so we don't create new variables here... *)\n                                  match (a', b') with\n                                  | (RegularChoice _, RegularChoice _)\n                                  | (ConflictChoice _, ConflictChoice _) =>\n                                      if bgt_nat (List.length a'') (List.length b'') then\n                                        Some a'\n                                      else\n                                        Some b'\n                                  | (ConflictChoice _, _) => Some (ConflictChoice a'')\n                                  | (_, ConflictChoice _) => Some (ConflictChoice b'')\n                                  end\n                           end\n                  end\n              end\n          end\n      end\n  | ScenarioOr a b =>\n      match FindBranchingChoices strat a with\n      | None => FindBranchingChoices strat b\n      | Some (RegularChoice l) =>\n          match FindBranchingChoices strat b with\n          | None => Some (RegularChoice l)\n          | Some (RegularChoice l') => Some (RegularChoice (app_rev l l'))\n          | Some (ConflictChoice l') => Warning (Some (ConflictChoice (app_rev l l'))) [\"Conflict clause ORed with something?\"]\n          end\n      | Some (ConflictChoice l) =>\n          let l := Warning l [\"Conflict clause ORed with something?\"] in\n          match FindBranchingChoices strat b with\n          | None => Some (ConflictChoice l)\n          | Some (RegularChoice l')\n          | Some (ConflictChoice l') => Some (ConflictChoice (app_rev l l'))\n          end\n      end\n  | ScenarioTrue => None\n  | ScenarioFalse => None\n  end.\n\nInductive FOLTerm : Set :=\n| IntTerm : string -> nat -> FOLTerm\n| StageNameTerm : string -> nat -> FOLTerm\n| MicroopTerm : string -> Microop -> FOLTerm\n| NodeTerm : string -> GraphNode -> FOLTerm\n| EdgeTerm : string -> GraphEdge -> FOLTerm\n| MacroArgTerm : string -> StringOrInt -> FOLTerm.\n\nDefinition FOLTermName\n  (t : FOLTerm)\n  : string :=\n  match t with\n  | IntTerm n _ => n\n  | StageNameTerm n _ => n\n  | MicroopTerm n _ => n\n  | NodeTerm n _ => n\n  | EdgeTerm n _ => n\n  | MacroArgTerm n _ => n\n  end.\n\nDefinition AddTerm\n  (l : list FOLTerm)\n  (t : FOLTerm)\n  : list FOLTerm :=\n  match find (fun x => beq_string (FOLTermName x) (FOLTermName t)) l with\n  | Some _ => Warning (t::l) [\"Shadowing term '\"; FOLTermName t; \"'\"]\n  | None => t::l\n  end.\n\nDefinition stringOfFOLTermValue\n  (t : FOLTerm)\n  : string :=\n  match t with\n  | IntTerm _ n => stringOfNat n\n  | StageNameTerm _ n => stringOfNat n\n  | MicroopTerm _ uop => StringOf [\"inst \"; stringOfNat (globalID uop); \" \";\n      stringOfNat (coreID uop); \" \"; stringOfNat (threadID uop); \" \";\n      stringOfNat (intraInstructionID uop)]\n  | NodeTerm _ n => GraphvizShortStringOfGraphNode n\n  | EdgeTerm _ e => StringOfGraphEdge e\n  | MacroArgTerm _ n => StringOfSoI n\n  end.\n\nDefinition stringOfFOLTerm\n  (t : FOLTerm)\n  : string :=\n  StringOf [FOLTermName t; \" = (\"; stringOfFOLTermValue t; \")\"].\n\nFixpoint GetFOLTermHelper\n  (name : string)\n  (l : list FOLTerm)\n  (depth : nat)\n  : option FOLTerm :=\n  match (depth, l) with\n  | (S d, StageNameTerm s n::t) =>\n      if beq_string s name\n      then Some (IntTerm s n)\n      else GetFOLTermHelper name t d\n  | (S d, MacroArgTerm s1 s2::t) =>\n      match s2 with\n      | SoIString s2' =>\n        if beq_string name s1\n        then (if beq_string s1 s2'\n          then GetFOLTermHelper name t d\n          else GetFOLTermHelper s2' t d)\n        else GetFOLTermHelper name t d\n      | SoIInt n =>\n        if beq_string s1 name\n        then Some (IntTerm name n)\n        else GetFOLTermHelper name t d\n      | _ => Warning None [\"Unexpected macro argument type\"]\n      end\n  | (S d, h::t) =>\n      if beq_string (FOLTermName h) name\n      then Some h\n      else GetFOLTermHelper name t d\n  | (S d, []) => Warning None [\"Could not find term \"; name]\n  | (O, _) => Warning None [\"Term search recursion depth exceeded!\"]\n  end.\n\nDefinition GetFOLTerm\n  (name : string)\n  (l : list FOLTerm)\n  : option FOLTerm :=\n  let result := GetFOLTermHelper name l 1000 in\n  match result with\n  | Some r => if PrintFlag 8 then Comment result [\"GetFOLTerm \"; name; \" returned \"; stringOfFOLTerm r] else result\n  | None => if PrintFlag 8 then Comment result [\"GetFOLTerm \"; name; \" returned None\"] else result\n  end.\n\nRecord FOLState := mkFOLState {\n  stateNodes     : list GraphNode;\n  stateNotNodes  : list GraphNode;\n  stateEdgeNodes : list GraphNode;\n  stateEdges     : list GraphEdge;\n  stateNotEdges  : list GraphEdge;\n  statePreds     : list FOLSymPred;\n  stateNotPreds  : list FOLSymPred;\n  stateUops      : list Microop;\n  stateInitial   : list BoundaryCondition;\n  stateFinal     : list BoundaryCondition;\n  stateArchEdges : list ArchitectureLevelEdge\n}.\n\nFixpoint UpdateFOLState\n  (check_dups : bool)\n  (s : FOLState)\n  (t : ScenarioTree)\n  : FOLState :=\n  let f a b :=\n    if find (beq_edge b) a\n    then a\n    else b::a\n  in\n  let g a b :=\n    if find (beq_node b) a\n    then a\n    else b::a\n  in\n  match t with\n  | ScenarioName n t' => Warning s [\"Shouldn't be trying to choose ScenarioName!\"]\n  | ScenarioConflict t' => UpdateFOLState check_dups s t'\n  | ScenarioAnd a b => UpdateFOLState check_dups (UpdateFOLState check_dups s a) b\n  | ScenarioOr a b => Warning s [\"Shouldn't be trying to choose ScenarioOr!\"]\n  | ScenarioEdgeLeaf l =>\n      let new_edges :=\n        if check_dups\n        then fold_left f l (stateEdges s)\n        else app_rev (stateEdges s) l\n      in\n      let new_nodes := NodesFromEdges new_edges in\n      mkFOLState (stateNodes s) (stateNotNodes s) new_nodes new_edges (stateNotEdges s)\n        (statePreds s) (stateNotPreds s)\n        (stateUops s) (stateInitial s) (stateFinal s) (stateArchEdges s)\n  | ScenarioNotEdgeLeaf l =>\n      let new_not_edges :=\n        if check_dups\n        then fold_left f l (stateNotEdges s)\n        else app_rev (stateNotEdges s) l\n      in\n      mkFOLState (stateNodes s) (stateNotNodes s) (stateEdgeNodes s) (stateEdges s) new_not_edges\n        (statePreds s) (stateNotPreds s)\n        (stateUops s) (stateInitial s) (stateFinal s) (stateArchEdges s)\n  | ScenarioNodeLeaf l =>\n      let new_nodes := \n        if check_dups\n        then fold_left g l (stateNodes s)\n        else app_rev (stateNodes s) l\n      in\n      mkFOLState new_nodes (stateNotNodes s) (stateEdgeNodes s) (stateEdges s) (stateNotEdges s)\n        (statePreds s) (stateNotPreds s)\n        (stateUops s) (stateInitial s) (stateFinal s) (stateArchEdges s)\n  | ScenarioNotNodeLeaf l =>\n      let new_not_nodes := \n        if check_dups\n        then fold_left g l (stateNotNodes s)\n        else app_rev (stateNotNodes s) l\n      in\n      mkFOLState (stateNodes s) new_not_nodes (stateEdgeNodes s) (stateEdges s) (stateNotEdges s)\n        (statePreds s) (stateNotPreds s)\n        (stateUops s) (stateInitial s) (stateFinal s) (stateArchEdges s)\n  | ScenarioPred p =>\n      let new_preds := \n        if check_dups then\n          if find (beq_pred p) (statePreds s) then\n            statePreds s\n          else\n            p::(statePreds s)\n        else p::(statePreds s)\n      in\n      mkFOLState (stateNodes s) (stateNotNodes s) (stateEdgeNodes s) (stateEdges s) (stateNotEdges s)\n        new_preds (stateNotPreds s)\n        (stateUops s) (stateInitial s) (stateFinal s) (stateArchEdges s)\n  | ScenarioNotPred p =>\n      let new_not_preds := \n        if check_dups then\n          if find (beq_pred p) (stateNotPreds s) then\n            stateNotPreds s\n          else\n            p::(stateNotPreds s)\n        else p::(stateNotPreds s)\n      in\n      mkFOLState (stateNodes s) (stateNotNodes s) (stateEdgeNodes s) (stateEdges s) (stateNotEdges s)\n        (statePreds s) new_not_preds\n        (stateUops s) (stateInitial s) (stateFinal s) (stateArchEdges s)\n  | ScenarioTrue => Warning s [\"Shouldn't be trying to choose ScenarioTrue!\"]\n  | ScenarioFalse => Warning s [\"Shouldn't be trying to choose ScenarioFalse!\"]\n  end.\n\nFixpoint blt_string\n  (a b : string)\n  : bool :=\n  match (a, b) with\n  | (String a1 a2, String b1 b2) =>\n      if blt_nat (nat_of_ascii a1) (nat_of_ascii b1)\n      then true\n      else if beq_nat (nat_of_ascii a1) (nat_of_ascii b1)\n      then blt_string a2 b2\n      else false\n  | (String a1 a2, EmptyString) => false\n  | (EmptyString, String b1 b2) => true\n  | (EmptyString, EmptyString) => false\n  end.\n\nDefinition FOLStateReplaceEdges\n  (s : FOLState)\n  (n n' : list GraphNode)\n  (l l': list GraphEdge)\n  (p p': list FOLSymPred)\n  : FOLState :=\n  let nodes := NodesFromEdges l in\n  mkFOLState n n' nodes l l' p p' (stateUops s) (stateInitial s)\n    (stateFinal s) (stateArchEdges s).\n\nFixpoint GetSoIFOLTerm\n  (t : StringOrInt)\n  (l : list FOLTerm)\n  : option FOLTerm :=\n  let result :=\n  match t with\n  | SoISum a b =>\n      match (GetSoIFOLTerm a l, GetSoIFOLTerm b l) with\n      | (Some (IntTerm _ a'), Some (IntTerm _ b')) =>\n          Some (IntTerm \"\" (a' + b'))\n      | _ => None\n      end\n  | SoIString s => GetFOLTerm s l\n  | SoIInt n => Some (IntTerm \"\" n)\n  | SoICoreID s =>\n      match GetFOLTerm s l with\n      | Some (MicroopTerm _ uop) => Some (IntTerm \"\" (coreID uop))\n      | _ => None\n      end\n  end in\n  match result with\n  | Some r => if PrintFlag 8 then Comment result [\"GetSoIFOLTerm \"; StringOfSoI t; \" returned \"; stringOfFOLTerm r] else result\n  | None => if PrintFlag 8 then Comment result [\"GetSoIFOLTerm \"; StringOfSoI t; \" returned None\"] else result\n  end.\n\nFixpoint FoldInstantiateGraphEdge\n  (s : FOLState)\n  (l : list FOLTerm)\n  (r : option (list GraphEdge))\n  (e : PredGraphEdge)\n  : option (list GraphEdge) :=\n  match e with\n  | ((uop1name, (p1, l1)), (uop2name, (p2, l2)), label, color) =>\n      match (GetFOLTerm uop1name l, GetFOLTerm uop2name l,\n             GetSoIFOLTerm p1 l, GetSoIFOLTerm p2 l,\n             GetSoIFOLTerm l1 l, GetSoIFOLTerm l2 l) with\n      | (Some (MicroopTerm _ uop1), Some (MicroopTerm _ uop2),\n         Some (IntTerm _ p1'), Some (IntTerm _ p2'),\n         Some (IntTerm _ l1'), Some (IntTerm _ l2')) =>\n          let e  := ((uop1, (p1', l1')), (uop2, (p2', l2')), label, color) in\n          match r with\n          | Some r' => Some (e :: r')\n          | None => None\n          end\n      | _ => Warning None [\"Could not find microop terms \"; uop1name;\n          \" and/or \"; uop2name]\n      end\n  end.\n\nFixpoint FoldInstantiateGraphNode\n  (s : FOLState)\n  (l : list FOLTerm)\n  (r : option (list GraphNode))\n  (n : PredGraphNode)\n  : option (list GraphNode) :=\n  match n with\n  | (uopname, (p1, l1)) =>\n      match (GetFOLTerm uopname l, GetSoIFOLTerm p1 l, GetSoIFOLTerm l1 l) with\n      | (Some (MicroopTerm _ uop), Some (IntTerm _ p'), Some (IntTerm _ l')) =>\n          let n := (uop, (p', l')) in\n          match r with\n          | Some r' => Some (n :: r')\n          | None => None\n          end\n      | _ => Warning None [\"Could not find term \"; uopname]\n      end\n  end.\n\nFixpoint GetInitialCondition\n  (conditions : list BoundaryCondition)\n  (pa : PhysicalAddress)\n  : Data :=\n  match conditions with\n  | (a, d) :: t =>\n      if beq_paddr a pa\n      then d\n      else GetInitialCondition t pa\n  | [] =>\n      let result := NormalData 0 in\n      if PrintFlag 6\n      then Comment result\n        [\"Using implicit initial condition data=0 for PA: \";\n        GraphvizStringOfPhysicalAddress pa]\n      else result\n  end.\n\nFixpoint GetFinalCondition\n  (conditions : list BoundaryCondition)\n  (pa : PhysicalAddress)\n  : option Data :=\n  match conditions with\n  | (a, d) :: t =>\n      if beq_paddr a pa\n      then Some d\n      else GetFinalCondition t pa\n  | [] => None\n  end.\n\nFixpoint HasDependency\n  (l : list ArchitectureLevelEdge)\n  (src dst : nat)\n  (label : string)\n  : bool :=\n  match l with\n  | (h1, h2, h3)::t =>\n      if andb (andb (beq_nat h1 src) (beq_nat h2 dst))\n        (beq_string label h3)\n      then true\n      else HasDependency t src dst label\n  | [] => false\n  end.\n\nDefinition EvaluatePredicate\n  (stage_names : list (list string))\n  (p : FOLPredicateType)\n  (l : list FOLTerm)\n  (s : FOLState)\n  : option (list GraphNode * list GraphEdge) :=\n  let result := match p with\n  | PredDebug a => Some ([], [])\n  | PredHasDependency a b c =>\n      match (GetFOLTerm b l, GetFOLTerm c l) with\n      | (Some (MicroopTerm _ b'), Some (MicroopTerm _ c')) =>\n          if HasDependency (stateArchEdges s) (globalID b') (globalID c') a\n          then Some ([], [])\n          else None\n      | _ => None\n      end\n  | PredIsRead t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          match access t' with\n          | Read _ _ _ _ => Some ([], [])\n          | _ => None\n          end\n      | _ => None\n      end\n  | PredIsAPICAccess n t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          match access t' with\n          | Read _ _ (PA (APICTag s' _) _) _ =>\n              if beq_string n s' then Some ([], []) else None\n          | Write _ _ (PA (APICTag s' _) _) _ =>\n              if beq_string n s' then Some ([], []) else None\n          | _ => None\n          end\n      | _ => None\n      end\n  | PredIsWrite t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          match access t' with\n          | Write _ _ _ _ => Some ([], [])\n          | _ => None\n          end\n      | _ => None\n      end\n  | PredIsFence t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          match access t' with\n          | Fence _ => Some ([], [])\n          | FenceVA _ _ => Some ([], [])\n          | _ => None\n          end\n      | _ => None\n      end\n  | PredAccessType t1 t2 =>\n      match GetFOLTerm t2 l with\n      | Some (MicroopTerm _ t2') =>\n          match access t2' with\n          | Read t1' _ _ _ =>\n              if find_string t1 t1'\n              then Some ([], [])\n              else None\n          | Write t1' _ _ _ =>\n              if find_string t1 t1'\n              then Some ([], [])\n              else None\n          | Fence t1' =>\n              if find_string t1 t1'\n              then Some ([], [])\n              else None\n          | FenceVA t1' _ =>\n              if find_string t1 t1'\n              then Some ([], [])\n              else None\n          end\n      | _ => None\n      end\n  | PredSameUop t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if beq_uop t1' t2' then Some ([], []) else None\n      | _ => None\n      end\n  | PredSameCore t1 t2 =>\n      match (GetSoIFOLTerm t1 l, GetSoIFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if beq_nat (coreID t1') (coreID t2')\n          then Some ([], [])\n          else None\n      | (Some (IntTerm _ t1'), Some (IntTerm _ t2')) =>\n          if beq_nat t1' t2'\n          then Some ([], [])\n          else None\n      | _ => None\n      end\n  | PredOnCore t1 t2 =>\n      match (GetSoIFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (IntTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if beq_nat t1' (coreID t2')\n          then Some ([], [])\n          else None\n      | _ => Warning None [\"Could not find term \"; StringOfSoI t1; \" and/or \"; t2]\n      end\n  | PredSameThread t1 t2 =>\n      match (GetSoIFOLTerm t1 l, GetSoIFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if beq_nat (coreID t1') (coreID t2')\n          then Some ([], [])\n          else None\n      | (Some (IntTerm _ t1'), Some (IntTerm _ t2')) =>\n          if beq_nat t1' t2'\n          then Some ([], [])\n          else None\n      | _ => None\n      end\n  | PredSmallerGlobalID t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if blt_nat (globalID t1') (globalID t2')\n          then Some ([], [])\n          else None\n      | _ => None\n      end\n  | PredSameGlobalID t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if beq_nat (globalID t1') (globalID t2')\n          then Some ([], [])\n          else None\n      | _ => None\n      end\n  | PredSameIntraInstID t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if beq_nat (intraInstructionID t1') (intraInstructionID t2')\n          then Some ([], [])\n          else None\n      | _ => None\n      end\n  | PredOnThread t1 t2 =>\n      match (GetSoIFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (IntTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if beq_nat t1' (threadID t2')\n          then Some ([], [])\n          else None\n      | _ => Warning None [\"Could not find term \"; StringOfSoI t1; \" and/or \"; t2]\n      end\n  | PredSameNode t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (NodeTerm _ t1'), Some (NodeTerm _ t2')) =>\n          if beq_node t1' t2' then Some ([], []) else None\n      | _ => None\n      end\n  | PredSameVirtualAddress t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if SameVirtualAddress t1' t2' then Some ([], []) else None\n      | _ => None\n      end\n  | PredSamePhysicalAddress t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if SamePhysicalAddress t1' t2' then Some ([], []) else None\n      | _ => None\n      end\n  | PredSameVirtualTag t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if SameVirtualTag t1' t2' then Some ([], []) else None\n      | _ => None\n      end\n  | PredSamePhysicalTag t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if SamePhysicalTag t1' t2' then Some ([], []) else None\n      | _ => None\n      end\n  | PredSameIndex t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if SameIndex t1' t2' then Some ([], []) else None\n      | _ => None\n      end\n  | PredKnownData t1 =>\n      match (GetFOLTerm t1 l) with\n      | Some (MicroopTerm _ t1') =>\n          match access t1' with\n          | Read _ _ _ UnknownData => None\n          | _ => Some ([], [])\n          end\n      | _ => None\n      end\n  | PredSameData t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if SameData t1' t2' then Some ([], []) else None\n      | _ => None\n      end\n  | PredSamePAasPTEforVA t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          match (GetPhysicalAddress t1', GetVirtualTag t2') with\n          | (Some p1, Some v2) =>\n              if beq_paddr p1 (PA (PTETag v2) 0)\n              then Some ([], [])\n              else None\n          | _ => None\n          end\n      | _ => None\n      end\n  | PredDataIsCorrectTranslation a' d' t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          match (GetData t1', GetVirtualTag t2', GetPhysicalTag t2') with\n          | (Some d, Some v, Some p) =>\n              if beq_pte d v p a' d'\n              then Some ([], [])\n              else None\n          | _ => None\n          end\n      | _ => None\n      end\n  | PredTranslationMatchesInitialState a' d' t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          match (GetVirtualTag t', GetPhysicalTag t') with\n          | (Some v, Some p) =>\n              let ic :=\n                GetInitialCondition (stateInitial s) (PA (PTETag v) 0) in\n              if beq_pte ic v p a' d'\n              then Some ([], [])\n              else None\n          | _ => None\n          end\n      | _ => None\n      end\n  | PredDataFromPAInitial t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          match (GetData t', GetPhysicalAddress t') with\n          | (Some d, Some pa) =>\n              if beq_data d (GetInitialCondition (stateInitial s) pa)\n              then Some ([], [])\n              else None\n          | _ => None\n          end\n      | _ => None\n      end\n  | PredDataFromPAFinal t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          match (GetData t', GetPhysicalAddress t') with\n          | (Some d, Some pa) =>\n              match GetFinalCondition (stateFinal s) pa with\n              | Some d' =>\n                if beq_data d d'\n                then Some ([], [])\n                else None\n              | None => None\n              end\n          | _ => None\n          end\n      | _ => None\n      end\n  | PredConsec t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if andb (beq_nat (S (globalID t1')) (globalID t2'))\n            (andb (beq_nat (threadID t1') (threadID t2'))\n              (beq_nat (coreID t1') (coreID t2')))\n          then Some ([], [])\n          else None\n      | _ => None\n      end\n  | PredProgramOrder t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ b'), Some (MicroopTerm _ c')) =>\n          if HasDependency (stateArchEdges s) (globalID b') (globalID c') \"po\"\n          then Some ([], [])\n          else None\n      | _ => None\n      end\n  | PredAddEdges e\n  | PredEdgesExist e =>\n      match fold_left (FoldInstantiateGraphEdge s l) e (Some []) with\n      | Some l' => Some ([], l')\n      | None => None\n      end\n  | PredNodesExist n =>\n      match fold_left (FoldInstantiateGraphNode s l) n (Some []) with\n      | Some l' => Some (l', [])\n      | None => None\n      end\n  | PredTrue => Some ([], [])\n  | PredFalse => None\n  | PredHasID g c t i n =>\n      match GetFOLTerm n l with\n      | Some (MicroopTerm _ uop) =>\n          match uop with\n          | mkMicroop g' c' t' i' _ =>\n              if andb\n                (andb (beq_nat g g') (beq_nat c c'))\n                (andb (beq_nat t t') (beq_nat i i'))\n              then Some ([], [])\n              else None\n          end\n      | _ => None\n      end\n  | PredHasGlobalID g n =>\n      match GetFOLTerm n l with\n      | Some (MicroopTerm _ uop) =>\n          match uop with\n          | mkMicroop g' _ _ _ _ =>\n              if beq_nat g g'\n              then Some ([], [])\n              else None\n          end\n      | _ => None\n      end\n  end in\n  if PrintFlag 8\n  then Comment result [tab; \"// EvaluatePredicate \"; stringOfPredicate false p; \" returned \";\n    match result with\n    | Some (l1, l2) => StringOf [\"sat(\"; stringOfNat (List.length l1); \" nodes, \";\n        stringOfNat (List.length l2); \" edges)\"]\n    | None => \"unsat\"\n    end]\n  else result.\n\nDefinition FOLQuantifier := FOLState -> list FOLTerm -> (string * list FOLTerm).\n\nDefinition MicroopQuantifier\n  (name : string)\n  : FOLQuantifier :=\n  fun (s : FOLState) (l : list FOLTerm) =>\n  let uops := stateUops s in\n  (name, Map (fun x => MicroopTerm name x) uops).\n\nDefinition NodeQuantifier\n  (name : string)\n  : FOLQuantifier :=\n  fun (s : FOLState) (l : list FOLTerm) =>\n  let nodes := stateNodes s in\n  (name, Map (fun x => NodeTerm name x) nodes).\n\n(* Dummy quantifier for a single uop. *)\nDefinition DummyQuantifier\n  (name : string)\n  (a : Microop)\n  : FOLQuantifier :=\n  fun (s : FOLState) (l : list FOLTerm) =>\n    (name, [MicroopTerm name a]).\n\nFixpoint numCores\n  (l : list Microop)\n  (n : nat)\n  : nat :=\n  match l with\n  | h::t => numCores t (max n (S (coreID h)))\n  | [] => n\n  end.\n\nDefinition CoreQuantifier\n  (name : string)\n  : FOLQuantifier :=\n  fun (s : FOLState) (l : list FOLTerm) =>\n  let cores := numCores (stateUops s) 0 in\n  (name, Map (fun x => IntTerm name x) (Range cores)).\n\nFixpoint numThreads\n  (l : list Microop)\n  (n : nat)\n  : nat :=\n  match l with\n  | h::t => numThreads t (max n (S (threadID h)))\n  | [] => n\n  end.\n\nDefinition ThreadQuantifier\n  (name : string)\n  : FOLQuantifier :=\n  fun (s : FOLState) (l : list FOLTerm) =>\n  let cores := numThreads (stateUops s) 0 in\n  (name, Map (fun x => IntTerm name x) (Range cores)).\n\nInductive FOLFormula :=\n| FOLName : string -> FOLFormula -> FOLFormula\n| FOLExpandMacro : string -> list StringOrInt -> FOLFormula\n| FOLPredicate : FOLPredicateType -> FOLFormula\n| FOLNot : FOLFormula -> FOLFormula\n| FOLOr : FOLFormula -> FOLFormula -> FOLFormula\n| FOLAnd : FOLFormula -> FOLFormula -> FOLFormula\n| FOLForAll : FOLQuantifier -> FOLFormula -> FOLFormula\n| FOLExists : FOLQuantifier -> FOLFormula -> FOLFormula\n| FOLLet : FOLTerm -> FOLFormula -> FOLFormula.\n\nFixpoint stringOfFOLFormulaHelper\n  (n : nat)\n  (depth : nat)\n  (f : FOLFormula)\n  : string :=\n  match n with\n  | S n' =>\n      match f with\n      | FOLName s f => StringOf [\"(\"; s; \":(\";\n          stringOfFOLFormulaHelper n' (S depth) f; \"))\"]\n      | FOLExpandMacro s l => StringOf [\"ExpandMacro \"; s]\n      | FOLPredicate p => stringOfPredicate false p\n      | FOLNot f' => StringOf [\"~(\"; stringOfNat depth; \")(\";\n          stringOfFOLFormulaHelper n' (S depth) f'; \")\"]\n      | FOLOr a b =>\n          StringOf [\"(\"; stringOfFOLFormulaHelper n' (S depth) a; \") \\\";\n            stringOfNat depth ; \"/ (\";\n            stringOfFOLFormulaHelper n' (S depth) b; \")\"]\n      | FOLAnd a b =>\n          StringOf [\"(\"; stringOfFOLFormulaHelper n' (S depth) a; \") /\";\n            stringOfNat depth; \"\\ (\";\n            stringOfFOLFormulaHelper n' (S depth) b; \")\"]\n      | FOLForAll q f' =>\n          StringOf [\"forall(\"; stringOfNat depth; \") (...), (\";\n            stringOfFOLFormulaHelper n' (S depth) f'; \")\"]\n      | FOLExists q f' =>\n          StringOf [\"exists(\"; stringOfNat depth; \") (...), (\";\n            stringOfFOLFormulaHelper n' (S depth) f'; \")\"]\n      | FOLLet t f' =>\n          StringOf [\"let(\"; stringOfNat depth; \") \"; stringOfFOLTerm t;\n            \" in (\"; stringOfFOLFormulaHelper n' (S depth) f'; \")\"]\n      end\n  | O =>\n      match f with\n      | FOLName s f' => s\n      | FOLExpandMacro s l => StringOf [\"ExpandMacro \"; s]\n      | FOLPredicate p => stringOfPredicate false p\n      | FOLNot f' => \"~(...)\"\n      | FOLOr a b => \"(...) \\/ (...)\"\n      | FOLAnd a b => \"(...) /\\ (...)\"\n      | FOLForAll q f' => \"forall (...), (...)\"\n      | FOLExists q f' => \"exists (...), (...)\"\n      | FOLLet t f' => StringOf [\"let \"; stringOfFOLTerm t; \" in (...)\"]\n      end\n  end.\n\nDefinition stringOfFOLFormula\n  (depth : nat)\n  (f : FOLFormula)\n  : string :=\n  stringOfFOLFormulaHelper 3 depth f.\n\nFixpoint PrintGraphvizStringOfFOLFormulaHelper\n  (id : nat)\n  (f : FOLFormula)\n  : nat :=\n  match f with\n  | FOLName s f' =>\n      let id' := PrintGraphvizStringOfFOLFormulaHelper id f' in\n      let result := S id' in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" -> n\"; stringOfNat id'; \";\"] in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" [color=red,shape=box,label=\"\"\"; s; \"\"\"];\"] in\n      result\n  | FOLExpandMacro s l =>\n      Println id [\"  n\"; stringOfNat id; \" [label=\"\"\"; s; \"\"\"];\"]\n  | FOLPredicate p =>\n      Println id\n        [\"  n\"; stringOfNat id; \" [label=\"\"\"; stringOfPredicate true p; \"\"\"];\"]\n  | FOLNot f' =>\n      let id' := PrintGraphvizStringOfFOLFormulaHelper id f' in\n      let result := S id' in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" -> n\"; stringOfNat id'; \";\"] in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" [label=\"\"NOT\"\"];\"] in\n      result\n  | FOLOr a b =>\n      let a_id := PrintGraphvizStringOfFOLFormulaHelper      id  a in\n      let b_id := PrintGraphvizStringOfFOLFormulaHelper (S a_id) b in\n      let result := S b_id in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" -> n\"; stringOfNat a_id; \";\"] in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" -> n\"; stringOfNat b_id; \";\"] in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" [label=\"\"OR\"\"];\"] in\n      result\n  | FOLAnd a b =>\n      let a_id := PrintGraphvizStringOfFOLFormulaHelper      id  a in\n      let b_id := PrintGraphvizStringOfFOLFormulaHelper (S a_id) b in\n      let result := S b_id in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" -> n\"; stringOfNat a_id; \";\"] in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" -> n\"; stringOfNat b_id; \";\"] in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" [label=\"\"AND\"\"];\"] in\n      result\n  | FOLForAll q f' =>\n      let id' := PrintGraphvizStringOfFOLFormulaHelper id f' in\n      let result := S id' in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" -> n\"; stringOfNat id'; \";\"] in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" [label=\"\"forall ...\"\"];\"] in\n      result\n  | FOLExists q f' =>\n      let id' := PrintGraphvizStringOfFOLFormulaHelper id f' in\n      let result := S id' in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" -> n\"; stringOfNat id'; \";\"] in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" [label=\"\"exists ...\"\"];\"] in\n      result\n  | FOLLet t f' =>\n      let id' := PrintGraphvizStringOfFOLFormulaHelper id f' in\n      let result := S id' in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" -> n\"; stringOfNat id'; \";\"] in\n      let result := Println result\n        [\"  n\"; stringOfNat result; \" [color=green,shape=box,label=\"\"\"; stringOfFOLTerm t; \"\"\"];\"] in\n      result\n  end.\n\nDefinition PrintGraphvizStringOfFOLFormula\n  (f : FOLFormula)\n  : FOLFormula :=\n  if PrintFlag 5\n  then\n    let f := Println f [\"digraph Axioms {\"] in\n    let f := Println f [tab; \"layout=dot;\"] in\n    let result := PrintGraphvizStringOfFOLFormulaHelper 0 f in\n    Println f [\"} // \"; stringOfNat result; \" nodes\"; newline]\n  else f.\n\nDefinition FOLImplies\n  (a b : FOLFormula)\n  : FOLFormula :=\n  FOLOr (FOLNot a) b.\n\nDefinition FOLIff\n  (a b : FOLFormula)\n  : FOLFormula :=\n  FOLAnd (FOLImplies a b) (FOLImplies b a).\n\nDefinition FoldFlipEdge\n  (is_neg : bool)\n  (t : ScenarioTree)\n  (e : GraphEdge)\n  : ScenarioTree :=\n  match e with\n  | (s, d, l, c) =>\n      let l' :=\n        if string_prefix \"NOT_\" l\n        then substr 4 l\n        else append \"NOT_\" l in\n      if beq_node s d\n      then ScenarioOr t ScenarioTrue\n      else\n        if is_neg then\n          ScenarioOr t (ScenarioEdgeLeaf [e])\n        else\n          ScenarioOr t (ScenarioNotEdgeLeaf [e])\n      (* else ScenarioOr t\n        (ScenarioOr\n          (ScenarioOr (ScenarioNotNodeLeaf [s]) (ScenarioNotNodeLeaf [d]))\n          (ScenarioEdgeLeaf [(d, s, l', c)])) *)\n  end.\n\nDefinition FoldFlipNode\n  (is_neg : bool)\n  (t : ScenarioTree)\n  (n : GraphNode)\n  : ScenarioTree :=\n  if is_neg then\n      ScenarioOr t (ScenarioNodeLeaf [n])\n  else\n      ScenarioOr t (ScenarioNotNodeLeaf [n]).\n\nDefinition CreateSymbolicScenarioTree\n  (p : FOLPredicateType)\n  (l : list FOLTerm)\n  (s : FOLState)\n  : ScenarioTree :=\n  match p with\n  | PredDebug a => ScenarioTrue\n  | PredHasDependency a b c =>\n      match (GetFOLTerm b l, GetFOLTerm c l) with\n      | (Some (MicroopTerm _ b'), Some (MicroopTerm _ c')) =>\n            ScenarioPred (SymPredHasDependency b' c' (GetISAEdge a))\n      | _ => ScenarioFalse\n      end\n  | PredIsRead t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          ScenarioPred (SymPredIsRead t')\n      | _ => ScenarioFalse\n      end\n  | PredIsWrite t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          ScenarioPred (SymPredIsWrite t')\n      | _ => ScenarioFalse\n      end\n  | PredIsAPICAccess n t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          ScenarioPred (SymPredIsAPICAccess t' n)\n      | _ => ScenarioFalse\n      end\n  | PredIsFence t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          ScenarioPred (SymPredIsFence t')\n      | _ => ScenarioFalse\n      end\n  | PredAccessType t1 t2 =>\n      match GetFOLTerm t2 l with\n      | Some (MicroopTerm _ t2') =>\n          ScenarioPred (SymPredAccessType t2' t1)\n      | _ => ScenarioFalse\n      end\n  | PredSameUop t1 t2 =>\n      (* This one is actually evaluated to true or false...*)\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if beq_uop t1' t2' then ScenarioTrue else ScenarioFalse\n      | _ => ScenarioFalse\n      end\n      (* as is this one... *)\n  | PredSameNode t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (NodeTerm _ t1'), Some (NodeTerm _ t2')) =>\n          if beq_node t1' t2' then ScenarioTrue else ScenarioFalse\n      | _ => ScenarioFalse\n      end\n      (* I've never seen SameCore used with ints, so I'm not covering that case...*)\n  | PredSameCore t1 t2 =>\n      match (GetSoIFOLTerm t1 l, GetSoIFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredSameCore t1' t2')\n      | _ => ScenarioFalse\n      end\n  (* These next two can be evaluated to true/false as well, since\n     they only use the global ID of the microops. *)\n  | PredSmallerGlobalID t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if blt_nat (globalID t1') (globalID t2')\n          then ScenarioTrue\n          else ScenarioFalse\n      | _ => ScenarioFalse\n      end\n  | PredSameGlobalID t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          if beq_nat (globalID t1') (globalID t2')\n          then ScenarioTrue\n          else ScenarioFalse\n      | _ => ScenarioFalse\n      end\n  | PredSameIntraInstID t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredSameIntraInstID t1' t2')\n      | _ => ScenarioFalse\n      end\n      (* SameThread with int terms is also not covered. *)\n  | PredSameThread t1 t2 =>\n      match (GetSoIFOLTerm t1 l, GetSoIFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredSameThread t1' t2')\n      | _ => ScenarioFalse\n      end\n  | PredOnCore t1 t2 =>\n      match (GetSoIFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (IntTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredOnCore t2' t1')\n      | _ => Warning ScenarioFalse [\"Could not find term \"; StringOfSoI t1; \" and/or \"; t2]\n      end\n  | PredOnThread t1 t2 =>\n      match (GetSoIFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (IntTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredOnThread t2' t1')\n      | _ => Warning ScenarioFalse [\"Could not find term \"; StringOfSoI t1; \" and/or \"; t2]\n      end\n  | PredSameVirtualAddress t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredSameVirtualAddress t1' t2')\n      | _ => ScenarioFalse\n      end\n  | PredSamePhysicalAddress t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredSamePhysicalAddress t1' t2')\n      | _ => ScenarioFalse\n      end\n  | PredSameVirtualTag t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredSameVirtualTag t1' t2')\n      | _ => ScenarioFalse\n      end\n  | PredSamePhysicalTag t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredSamePhysicalTag t1' t2')\n      | _ => ScenarioFalse\n      end\n  | PredSameIndex t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredSameIndex t1' t2')\n      | _ => ScenarioFalse\n      end\n  (* KnownData doesn't need to be used, but it could be useful.\n     We can set it to true for anything with an rf, and false otherwise. *)\n  | PredKnownData t1 =>\n      match (GetFOLTerm t1 l) with\n      | Some (MicroopTerm _ t1') =>\n          ScenarioPred (SymPredKnownData t1')\n      | _ => ScenarioFalse\n      end\n  | PredSameData t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredSameData t1' t2')\n      | _ => ScenarioFalse\n      end\n  | PredDataFromPAInitial t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          ScenarioPred (SymPredDataFromPAInitial t')\n      | _ => ScenarioFalse\n      end\n  | PredDataFromPAFinal t =>\n      match GetFOLTerm t l with\n      | Some (MicroopTerm _ t') =>\n          ScenarioPred (SymPredDataFromPAFinal t')\n      | _ => ScenarioFalse\n      end\n  | PredSamePAasPTEforVA t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredSamePAasPTEforVA t1' t2')\n      | _ => ScenarioFalse\n      end\n  | PredProgramOrder t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ b'), Some (MicroopTerm _ c')) =>\n          ScenarioPred (SymPredProgramOrder b' c')\n      | _ => ScenarioFalse\n      end\n  | PredConsec t1 t2 =>\n      match (GetFOLTerm t1 l, GetFOLTerm t2 l) with\n      | (Some (MicroopTerm _ t1'), Some (MicroopTerm _ t2')) =>\n          ScenarioPred (SymPredConsec t1' t2')\n      | _ => ScenarioFalse\n      end\n  | PredTrue => ScenarioTrue\n  | PredFalse => ScenarioFalse\n  | PredDataIsCorrectTranslation _ _ _ _ => Warning ScenarioFalse [\"Symbolic DataIsCorrectTranslation is unsupported\"]\n  | PredTranslationMatchesInitialState _ _ _ => Warning ScenarioFalse [\"Symbolic TranslationMatchesInitialState is unsupported\"]\n  | PredAddEdges _ => Warning ScenarioFalse [\"Symbolic AddEdges is unsupported\"]\n  | PredEdgesExist _ => Warning ScenarioFalse [\"Symbolic EdgesExist is unsupported\"]\n  | PredNodesExist _ => Warning ScenarioFalse [\"Symbolic NodesExist is unsupported\"]\n  | PredHasID _ _ _ _ _ => Warning ScenarioFalse [\"Symbolic HasID is unsupported\"]\n  | PredHasGlobalID _ _ => Warning ScenarioFalse [\"Symbolic HasGlobalID is unsupported\"]\n  end.\n\nFixpoint EliminateQuantifiersHelper\n  (symbolic : bool)\n  (over_approx : bool)\n  (demorgan : bool)\n  (stage_names : list (list string))\n  (s : FOLState)\n  (f : FOLFormula)\n  (l : list FOLTerm)\n  : ScenarioTree :=\n  match f with\n  | FOLName n f =>\n      ScenarioName n (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s f l)\n  | FOLExpandMacro m _ => Warning ScenarioFalse\n      [\"Internal error: macro \"; m; \" should have been expanded!\"]\n  | FOLPredicate p  =>\n    if symbolic then\n      match p with\n      | PredAddEdges p'\n      | PredEdgesExist p'\n      | PredNodesExist p' =>\n        match (demorgan, EvaluatePredicate stage_names p l s) with\n        | (false, Some (l1, l2)) =>\n            ScenarioAnd (ScenarioNodeLeaf l1) (ScenarioEdgeLeaf l2)\n        | (false, None) => ScenarioFalse\n        | (true, Some (l1, l2)) =>\n            let n := fold_left (FoldFlipNode false) l1 ScenarioFalse in\n            let e := fold_left (FoldFlipEdge false) l2 ScenarioFalse in\n            ScenarioOr n e\n        | (true, None) => ScenarioTrue\n        end\n      | _ => let t := CreateSymbolicScenarioTree p l s in\n             match t with\n             | ScenarioPred p' => if demorgan then ScenarioNotPred p' else t\n             | ScenarioTrue => if demorgan then ScenarioFalse else t\n             | ScenarioFalse => if demorgan then ScenarioTrue else t\n             | _ => Warning ScenarioFalse [\"Symbolic scenario tree returned something other than pred/true/false!\"]\n             end\n      end\n    else\n      match (demorgan, EvaluatePredicate stage_names p l s) with\n      | (false, Some (l1, l2)) =>\n          ScenarioAnd (ScenarioNodeLeaf l1) (ScenarioEdgeLeaf l2)\n      | (false, None) => ScenarioFalse\n      | (true, Some (l1, l2)) =>\n          let n := fold_left (FoldFlipNode false) l1 ScenarioFalse in\n          let e := fold_left (FoldFlipEdge false) l2 ScenarioFalse in\n          ScenarioOr n e\n      | (true, None) => ScenarioTrue\n      end\n  | FOLNot f' =>\n      EliminateQuantifiersHelper symbolic over_approx (negb demorgan) stage_names s f' l\n  | FOLOr a b =>\n      if demorgan\n      then\n        match (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s a l) with\n        | ScenarioFalse => ScenarioFalse\n        | ScenarioTrue =>\n          (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s b l)\n        | a' =>\n          match (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s b l) with\n          | ScenarioFalse => ScenarioFalse\n          | ScenarioTrue => a'\n          | b' => ScenarioAnd a' b'\n          end\n        end\n      else\n        match (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s a l) with\n        | ScenarioTrue => ScenarioTrue\n        | ScenarioFalse =>\n          (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s b l)\n        | a' =>\n          match (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s b l) with\n          | ScenarioTrue => ScenarioTrue\n          | ScenarioFalse => a'\n          | b' => ScenarioOr a' b'\n          end\n        end\n  | FOLAnd a b =>\n      if negb demorgan\n      then\n        match (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s a l) with\n        | ScenarioFalse => ScenarioFalse\n        | ScenarioTrue =>\n          (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s b l)\n        | a' =>\n          match (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s b l) with\n          | ScenarioFalse => ScenarioFalse\n          | ScenarioTrue => a'\n          | b' => ScenarioAnd a' b'\n          end\n        end\n      else\n        match (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s a l) with\n        | ScenarioTrue => ScenarioTrue\n        | ScenarioFalse =>\n          (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s b l)\n        | a' =>\n          match (EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s b l) with\n          | ScenarioTrue => ScenarioTrue\n          | ScenarioFalse => a'\n          | b' => ScenarioOr a' b'\n          end\n        end\n  | FOLForAll t f'  =>\n    if andb (over_approx) (demorgan) then\n      ScenarioTrue\n    else\n      let (term_name, terms) := t s l in\n      let case x y :=\n        if demorgan\n        then\n          match x with\n          | ScenarioTrue => ScenarioTrue\n          | ScenarioFalse =>\n            let y' := EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s f' (AddTerm l y) in\n            ScenarioName (stringOfFOLTerm y) y'\n          | _ =>\n            match EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s f' (AddTerm l y) with\n            | ScenarioTrue => ScenarioTrue\n            | ScenarioFalse => x\n            | y' => ScenarioOr x (ScenarioName (stringOfFOLTerm y) y')\n            end\n          end\n        else\n          match x with\n          | ScenarioFalse => ScenarioFalse\n          | ScenarioTrue =>\n            let y' := EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s f' (AddTerm l y) in\n            ScenarioName (stringOfFOLTerm y) y'\n          | _ =>\n            match EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s f' (AddTerm l y) with\n            | ScenarioFalse => ScenarioFalse\n            | ScenarioTrue => x\n            | y' => ScenarioAnd x (ScenarioName (stringOfFOLTerm y) y')\n            end\n          end in\n      fold_left case terms (if demorgan then ScenarioFalse else ScenarioTrue)\n  | FOLExists t f'  =>\n    if andb (over_approx) (negb demorgan) then\n      ScenarioTrue\n    else\n      let (term_name, terms) := t s l in\n      let case x y :=\n        if negb demorgan\n        then\n          match x with\n          | ScenarioTrue => ScenarioTrue\n          | ScenarioFalse =>\n            let y' := EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s f' (AddTerm l y) in\n            ScenarioName (stringOfFOLTerm y) y'\n          | _ =>\n            match EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s f' (AddTerm l y) with\n            | ScenarioTrue => ScenarioTrue\n            | ScenarioFalse => x\n            | y' => ScenarioOr x (ScenarioName (stringOfFOLTerm y) y')\n            end\n          end\n        else\n          match x with\n          | ScenarioFalse => ScenarioFalse\n          | ScenarioTrue =>\n            let y' := EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s f' (AddTerm l y) in\n            ScenarioName (stringOfFOLTerm y) y'\n          | _ =>\n            match EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s f' (AddTerm l y) with\n            | ScenarioFalse => ScenarioFalse\n            | ScenarioTrue => x\n            | y' => ScenarioAnd x (ScenarioName (stringOfFOLTerm y) y')\n            end\n          end in\n      fold_left case terms (if demorgan then ScenarioTrue else ScenarioFalse)\n  | FOLLet t f' =>\n      let t' := EliminateQuantifiersHelper symbolic over_approx demorgan stage_names s f' (AddTerm l t) in\n      ScenarioName (stringOfFOLTerm t) t'\n  end.\n\nFixpoint SetIntersectionIsEmpty\n  (a b : list GraphEdge)\n  : bool :=\n  match a with\n  | h::t =>\n      if find (beq_edge h) b\n      then false\n      else SetIntersectionIsEmpty t b\n  | [] => true\n  end.\n\nFixpoint PredSetIntersectionIsEmpty\n  (a b : list FOLSymPred)\n  : bool :=\n  match a with\n  | h::t =>\n      if find (beq_pred h) b\n      then false\n      else PredSetIntersectionIsEmpty t b\n  | [] => true\n  end.\n\nFixpoint SetIntersectionHelper\n  (a b : list GraphEdge)\n  (r : list GraphEdge)\n  : list GraphEdge :=\n  match a with\n  | h::t =>\n      if find (beq_edge h) b\n      then SetIntersectionHelper t b (h::r)\n      else SetIntersectionHelper t b r\n  | [] => r\n  end.\n\nDefinition SetIntersection\n  (a b : list GraphEdge)\n  : list GraphEdge :=\n  SetIntersectionHelper a b [].\n\n(** If a match is found, then pick which to keep according to the following\nlist of priorities:\n1) Labeled edges\n2) TC\n3) Flipped edges\n*)\nFixpoint SDFindEdge\n  (e : GraphEdge)\n  (l : list GraphEdge)\n  : option GraphEdge :=\n  match l with\n  | h::t =>\n      if beq_edge h e\n      then\n        match (h, e) with\n        | ((hs, hd, hl, hc), (es, ed, el, ec)) =>\n          match (beq_string \"TC\" hl, string_prefix \"NOT_\" hl,\n            beq_string \"TC\" el, string_prefix \"NOT_\" el) with\n          | (true, true, _, _) => Warning None\n              [\"TC and NOT_ simultaneously?\"]\n          | (_, _, true, true) => Warning None\n              [\"TC and NOT_ simultaneously?\"]\n          | (false, false, _, _) => None\n          | (true, _, false, false) => Some e\n          | (true, _, _, _) => None\n          | (_, true, false, true) => None\n          | (_, true, _, false) => Some e\n          end\n        end\n      else SDFindEdge e t\n  | [] => Some e\n  end.\n\nFixpoint SetDifferenceHelper\n  (a b r : list GraphEdge)\n  : list GraphEdge :=\n  match a with\n  | h::t =>\n      match SDFindEdge h b with\n      | Some e => SetDifferenceHelper t b (e::r)\n      | None => SetDifferenceHelper t b r\n      end\n  | [] => r\n  end.\n\nDefinition SetDifference\n  (a b : list GraphEdge)\n  : list GraphEdge :=\n  SetDifferenceHelper a b [].\n\nFixpoint NodeSetIntersectionIsEmpty\n  (a b : list GraphNode)\n  : bool :=\n  match a with\n  | h::t =>\n      if find (beq_node h) b\n      then false\n      else NodeSetIntersectionIsEmpty t b\n  | [] => true\n  end.\n\nFixpoint NodeSetIntersectionHelper\n  (a b : list GraphNode)\n  (r : list GraphNode)\n  : list GraphNode :=\n  match a with\n  | h::t =>\n      if find (beq_node h) b\n      then NodeSetIntersectionHelper t b (h::r)\n      else NodeSetIntersectionHelper t b r\n  | [] => r\n  end.\n\nFixpoint NodeSetIntersection\n  (a b : list GraphNode)\n  : list GraphNode :=\n  NodeSetIntersectionHelper a b [].\n\nFixpoint NodeSetDifferenceHelper\n  (a b r : list GraphNode)\n  : list GraphNode :=\n  match a with\n  | h::t =>\n      if find (beq_node h) b\n      then NodeSetDifferenceHelper t b r\n      else NodeSetDifferenceHelper t b (h::r)\n  | [] => r\n  end.\n\nDefinition NodeSetDifference\n  (a b : list GraphNode)\n  : list GraphNode :=\n  NodeSetDifferenceHelper a b [].\n\nFixpoint ScenarioTreeKeepIfFalse\n  (s : FOLState)\n  (t : ScenarioTree)\n  : option ScenarioTree :=\n  match t with\n  | ScenarioName n t' =>\n      match ScenarioTreeKeepIfFalse s t' with\n      | Some t'' => Some (ScenarioName n t'')\n      | None => None\n      end\n  | ScenarioConflict t' =>\n      match ScenarioTreeKeepIfFalse s t' with\n      | Some t'' => Some (ScenarioConflict t'')\n      | None => None\n      end\n  | ScenarioEdgeLeaf l =>\n      match (SetIntersection (FlipEdges l) (stateEdges s), SetIntersection l (stateNotEdges s)) with\n      | ([], []) => None\n      | (l', []) => Some (ScenarioEdgeLeaf (FlipEdges l'))\n      | ([], l') => Some (ScenarioEdgeLeaf l')\n      | (l1, l2) => Some (ScenarioEdgeLeaf (app_rev (FlipEdges l1) l2))\n      end\n  | ScenarioNotEdgeLeaf l =>\n      match SetIntersection l (stateEdges s) with\n      | [] => None\n      | l' => Some (ScenarioNotEdgeLeaf l')\n      end\n  | ScenarioNodeLeaf l =>\n      match NodeSetIntersection l (stateNotNodes s) with\n      | [] => None\n      | l' => Some (ScenarioNodeLeaf l')\n      end\n  | ScenarioNotNodeLeaf l =>\n      match (NodeSetIntersection l (stateNodes s),\n        NodeSetIntersection l (stateEdgeNodes s)) with\n      | ([], []) => None\n      | (l', []) => Some (ScenarioNotNodeLeaf l')\n      | ([], l') => Some (ScenarioNotNodeLeaf l')\n      | (l1, l2) => Some (ScenarioNotNodeLeaf (app_rev l1 l2))\n      end\n  | ScenarioPred p => None\n  | ScenarioNotPred p => None\n  | ScenarioAnd a b =>\n      match (ScenarioTreeKeepIfFalse s a, ScenarioTreeKeepIfFalse s b) with\n      | (Some a', Some b') => Some (ScenarioAnd a' b')\n      | (None, Some b') => Some b'\n      | (Some a', None) => Some a'\n      | (None, None) => None\n      end\n  | ScenarioOr a b =>\n      match (ScenarioTreeKeepIfFalse s a, ScenarioTreeKeepIfFalse s b) with\n      | (Some a', Some b') => Some (ScenarioOr a' b')\n      | (None, Some b') => None\n      | (Some a', None) => None\n      | (None, None) => None\n      end\n  | ScenarioTrue => None\n  | ScenarioFalse => Some ScenarioFalse\n  end.\n\nDefinition EliminateQuantifiers\n  (symbolic : bool)\n  (over_approx : bool)\n  (stage_names : list (list string))\n  (s : FOLState)\n  (f : FOLFormula)\n  (l : list FOLTerm)\n  : ScenarioTree :=\n  let t := EliminateQuantifiersHelper symbolic over_approx false stage_names s f l in\n  let t' := SimplifyScenarioTree t in\n  let t' := ScenarioTreeEdgeCountGraph 5 t' \"QuantifiersRemovedAndSimplified\" in\n  if PrintFlag 0\n  then\n    if ReducesToFalse t'\n    then\n      let t'' :=\n        match (ScenarioTreeKeepIfFalse s t) with\n        | Some t''' => ScenarioTreeEdgeCountGraph 0 t''' \"TriviallyFalse\"\n        | None => Warning ScenarioFalse [\"Doesn't reduce to false? (EQ)\"]\n        end in\n      match t'' with\n      | ScenarioTrue => Comment t' [\"ScenarioTree unsatisfiable?\"]\n      | _ => Comment t' [\"ScenarioTree unsatisfiable\"]\n      end\n    else t'\n  else t'.\n\nModule STBFwdExample.\n\nDefinition STBFwdPartial : FOLFormula :=\n  FOLAnd (FOLNot (FOLPredicate (PredSameUop \"i\" \"uop\")))\n   (FOLAnd (FOLPredicate (PredSameVirtualAddress \"i\" \"uop\"))\n     (FOLAnd (FOLPredicate (PredSameData \"i\" \"uop\"))\n       (FOLPredicate (PredAddEdges [\n         ((\"i\", (SoIInt 0, SoIInt 3)), (\"uop\", (SoIInt 0, SoIInt 3)), \"STBFwd\", \"red\");\n         ((\"uop\", (SoIInt 0, SoIInt 3)), (\"i\", (SoIInt 0, SoIInt 7)), \"STBFwd\", \"red\")])\n       )\n     )\n   ).\n\nDefinition STBFwd : FOLFormula :=\n  FOLExists (MicroopQuantifier \"i\") STBFwdPartial.\n\nDefinition i0 := mkMicroop 0 0 0 0 (Write [] (VA 0 0) (PA (PTag 0) 0) (NormalData 1)).\nDefinition i1 := mkMicroop 1 0 0 0 (Write [] (VA 0 0) (PA (PTag 0) 0) (NormalData 1)).\nDefinition i2 := mkMicroop 2 0 0 0 (Read  [] (VA 0 0) (PA (PTag 0) 0) (NormalData 1)).\nDefinition eState : FOLState := mkFOLState\n  [] [] [(i0, (0, 0)); (i1, (0, 0)); (i2, (0, 0))]\n  [((i0, (0, 0)), (i1, (0, 0)), \"PO\", \"blue\");\n   ((i1, (0, 0)), (i2, (0, 0)), \"PO\", \"blue\")]\n  [] [] [] [i0; i1; i2] [] [] [].\nDefinition eTerms := [MicroopTerm \"uop\" i2].\n\nExample e0 : EliminateQuantifiers false false [] eState\n  (FOLPredicate (PredAddEdges [((\"uop\", (SoIInt 0, SoIInt 0)), (\"uop\", (SoIInt 0, SoIInt 1)), \"label\", \"red\")]))\n  eTerms =\n  ScenarioEdgeLeaf ([((i2, (0, 0)), (i2, (0, 1)), \"label\", \"red\")]).\nProof.\n  auto.\nQed.\n\nExample e1 : EliminateQuantifiers false false [] eState STBFwdPartial\n    [MicroopTerm \"uop\" i2; MicroopTerm \"i\" i1] =\n    ScenarioEdgeLeaf [\n      ((i2, (0, 3)), (i1, (0, 7)), \"STBFwd\", \"red\");\n      ((i1, (0, 3)), (i2, (0, 3)), \"STBFwd\", \"red\")].\nProof.\n  auto.\nQed.\n\nExample e2 : stateUops eState = [i0; i1; i2].\nProof.\n  auto.\nQed.\n\nExample e3 : EliminateQuantifiers false false [] eState STBFwd eTerms =\n  ScenarioOr\n    (ScenarioName \"i = (inst 0 0 0 0)\"\n      (ScenarioEdgeLeaf [\n        ((i2, (0, 3)), (i0, (0, 7)), \"STBFwd\", \"red\");\n        ((i0, (0, 3)), (i2, (0, 3)), \"STBFwd\", \"red\")]))\n    (ScenarioName \"i = (inst 1 0 0 0)\"\n      (ScenarioEdgeLeaf [\n        ((i2, (0, 3)), (i1, (0, 7)), \"STBFwd\", \"red\");\n        ((i1, (0, 3)), (i2, (0, 3)), \"STBFwd\", \"red\")])).\nProof.\n  auto.\nQed.\n\nEnd STBFwdExample.\n\nModule BeforeOrAfterExample.\n\nDefinition BeforeOrAfter : FOLFormula :=\n  FOLForAll (MicroopQuantifier \"i1\")\n    (FOLForAll (MicroopQuantifier \"i2\")\n      (FOLImplies (FOLNot (FOLPredicate (PredSameUop \"i1\" \"i2\")))\n        (FOLOr\n          (FOLPredicate (PredAddEdges [((\"i1\", (SoIInt 0, SoIInt 0)), (\"i2\", (SoIInt 0, SoIInt 0)), \"x\", \"red\")]))\n          (FOLPredicate (PredAddEdges [((\"i2\", (SoIInt 0, SoIInt 0)), (\"i1\", (SoIInt 0, SoIInt 0)), \"x\", \"red\")]))\n        )\n      )\n    ).\n\nDefinition i0 := mkMicroop 0 0 0 0 (Write [] (VA 0 0) (PA (PTag 0) 0) (NormalData 1)).\nDefinition i1 := mkMicroop 1 0 0 0 (Write [] (VA 0 0) (PA (PTag 0) 0) (NormalData 1)).\nDefinition i2 := mkMicroop 2 0 0 0 (Read  [] (VA 0 0) (PA (PTag 0) 0) (NormalData 1)).\nDefinition eState : FOLState := mkFOLState\n  [] [] [(i0, (0, 0)); (i1, (0, 0)); (i2, (0, 0))]\n  [((i0, (0, 0)), (i1, (0, 0)), \"x\", \"red\");\n   ((i0, (0, 0)), (i2, (0, 0)), \"x\", \"red\")]\n  [] [] [] [i0; i1; i2] [] [] [].\nDefinition eTerms : list FOLTerm := [].\n\nExample e0 :\n  EliminateQuantifiers false false [] eState BeforeOrAfter eTerms =\n  ScenarioAnd\n    (ScenarioName \"i1 = (inst 1 0 0 0)\"\n      (ScenarioName \"i2 = (inst 2 0 0 0)\"\n        (ScenarioOr (ScenarioEdgeLeaf [(i1, (0, 0), (i2, (0, 0)), \"x\", \"red\")])\n           (ScenarioEdgeLeaf [(i2, (0, 0), (i1, (0, 0)), \"x\", \"red\")]))))\n    (ScenarioName \"i1 = (inst 2 0 0 0)\"\n      (ScenarioName \"i2 = (inst 1 0 0 0)\"\n        (ScenarioOr (ScenarioEdgeLeaf [(i2, (0, 0), (i1, (0, 0)), \"x\", \"red\")])\n           (ScenarioEdgeLeaf [(i1, (0, 0), (i2, (0, 0)), \"x\", \"red\")])))).\nProof.\nAbort.\n\nEnd BeforeOrAfterExample.\n\nFixpoint ReevaluateScenarioTree\n  (s : FOLState)\n  (t : ScenarioTree)\n  : ScenarioTree :=\n  match t with\n  | ScenarioName n t' => ScenarioName n (ReevaluateScenarioTree s t')\n  | ScenarioConflict t' => ScenarioConflict (ReevaluateScenarioTree s t')\n  | ScenarioEdgeLeaf l =>\n      (* If there's nothing that would cause a cycle by its addition (first branch of the and),\n         and none of the edges being added are required to not exist (second branch of the and),\n         and if none of the nodes used by these edges are required to not exist (third branch of and),\n         then add the difference of the two sets. Otherwise it's just false. *)\n      if andb (andb\n        (SetIntersectionIsEmpty (FlipEdges l) (stateEdges s))\n        (SetIntersectionIsEmpty l (stateNotEdges s)))\n        (NodeSetIntersectionIsEmpty (NodesFromEdges l) (stateNotNodes s))\n      then ScenarioEdgeLeaf (SetDifference l (stateEdges s))\n      else ScenarioFalse\n  | ScenarioNotEdgeLeaf l =>\n      (* If the edges here clash with any of the edges we're already required\n         to have, then this is just false. Otherwise, if the forbidding of the edges\n         is subsumed by the nodes we are already forbidding (since edges require their\n         source and dest nodes), then this is just true. Otherwise, just add any new\n         edges that must be forbidden. *)\n      (* NotEdgeLeaf l means that *everything* in l must not exist. This is correct because\n         NotEdgeLeaf instances come about from DeMorganing EdgesExist sets, so the proper\n         ORs will already have been inserted at a higher level of the hierarchy.\n         (NotEdgeLeaf instances will probably all be sets of single forbidden edges as a result.) *)\n      if (SetIntersectionIsEmpty l (stateEdges s))\n      then\n        if (NodeSetIntersectionIsEmpty (NodesFromEdges l) (stateNotNodes s))\n        then\n          ScenarioNotEdgeLeaf (SetDifference l (stateNotEdges s))\n        else\n          ScenarioTrue\n      else ScenarioFalse\n  | ScenarioNodeLeaf l =>\n      (* If we're not adding nodes that are required to not exist,\n         then go ahead and add them. It's ok if the nodes we're adding intersect with the nodes\n         of edges that must not exist; those nodes can exist. As long as those edges don't exist,\n         we're fine. *)\n      if NodeSetIntersectionIsEmpty l (stateNotNodes s)\n      then ScenarioNodeLeaf (NodeSetDifference l (stateNodes s))\n      else ScenarioFalse\n  | ScenarioNotNodeLeaf l =>\n      if andb\n        (NodeSetIntersectionIsEmpty l (stateNodes s))\n        (NodeSetIntersectionIsEmpty l (stateEdgeNodes s))\n      then\n        match NodeSetDifference l (stateNotNodes s) with\n        | [] =>\n          (* all nodes in l are already added to the list of forbidden nodes,\n           * so we can eliminate this leaf safely *)\n          ScenarioTrue\n        | l' => ScenarioNotNodeLeaf l'\n        end\n      else ScenarioFalse\n  | ScenarioPred p =>\n      if (find (beq_pred p) (statePreds s)) then ScenarioTrue\n      else if (find (beq_pred p) (stateNotPreds s)) then ScenarioFalse\n      else t\n  | ScenarioNotPred p =>\n      if (find (beq_pred p) (statePreds s)) then ScenarioFalse\n      else if (find (beq_pred p) (stateNotPreds s)) then ScenarioTrue\n      else t\n  | ScenarioAnd a b =>\n      ScenarioAnd (ReevaluateScenarioTree s a) (ReevaluateScenarioTree s b)\n  | ScenarioOr a b =>\n      ScenarioOr (ReevaluateScenarioTree s a) (ReevaluateScenarioTree s b)\n  | ScenarioTrue => t\n  | ScenarioFalse => t\n  end.\n\nFixpoint ScenarioTreeAssignLeaves\n  (s : FOLState)\n  (t : ScenarioTree)\n  : ScenarioTree :=\n  match t with\n  | ScenarioName n t' => ScenarioName n (ScenarioTreeAssignLeaves s t')\n  | ScenarioConflict t' => ScenarioConflict (ScenarioTreeAssignLeaves s t')\n  | ScenarioEdgeLeaf l =>\n      if andb\n      (SetIntersectionIsEmpty (FlipEdges l) (stateEdges s))\n      (SetIntersectionIsEmpty l (stateNotEdges s))\n      then ScenarioTrue\n      else ScenarioFalse\n  | ScenarioNotEdgeLeaf l =>\n      if SetIntersectionIsEmpty l (stateEdges s)\n      then ScenarioTrue\n      else ScenarioFalse\n  | ScenarioNodeLeaf l =>\n      if NodeSetIntersectionIsEmpty l (stateNotNodes s)\n      then ScenarioTrue\n      else ScenarioFalse\n  | ScenarioNotNodeLeaf l =>\n      if andb (NodeSetIntersectionIsEmpty l (stateNodes s))\n        (NodeSetIntersectionIsEmpty l (stateEdgeNodes s))\n      then ScenarioTrue\n      else ScenarioFalse\n  | ScenarioPred p =>\n      if find (beq_pred p) (stateNotPreds s)\n      then ScenarioFalse\n      else ScenarioTrue\n  | ScenarioNotPred p =>\n      if find (beq_pred p) (statePreds s)\n      then ScenarioFalse\n      else ScenarioTrue\n  | ScenarioAnd a b =>\n      ScenarioAnd (ScenarioTreeAssignLeaves s a) (ScenarioTreeAssignLeaves s b)\n  | ScenarioOr a b =>\n      ScenarioOr (ScenarioTreeAssignLeaves s a) (ScenarioTreeAssignLeaves s b)\n  | ScenarioTrue => ScenarioTrue\n  | ScenarioFalse => ScenarioFalse\n  end.\n\nDefinition FOLMacro := (string * list string * FOLFormula) % type.\n\nFixpoint FindMacro\n  (name : string)\n  (l : list FOLMacro)\n  : option (list string * FOLFormula) :=\n  match l with\n  | (h_name, h_args, h_formula)::t =>\n      if beq_string name h_name\n      then Some (h_args, h_formula)\n      else FindMacro name t\n  | [] => Warning None [\"Could not find macro \"; name]\n  end.\n\nFixpoint ArgsZipHelper\n  {A B : Type}\n  (a : list A)\n  (b : list B)\n  (r : list (A * B))\n  : list (A * B) :=\n  match (a, b) with\n  | (h_a::t_a, h_b::t_b) => ArgsZipHelper t_a t_b ((h_a, h_b) :: r)\n  | ([], []) => r\n  | _ => Warning r [\"Macro argument length mismatch!\"]\n  end.\n\nDefinition ArgsZip\n  {A B : Type}\n  (a : list A)\n  (b : list B)\n  : list (A * B) :=\n  ArgsZipHelper a b [].\n\nFixpoint FOLExpandMacros\n  (d : nat) (* depth *)\n  (l : list FOLMacro)\n  (f : FOLFormula)\n  : FOLFormula :=\n  match d with\n  | S d' =>\n      match f with\n      | FOLName s f' => FOLName s (FOLExpandMacros d' l f')\n      | FOLExpandMacro s given_args =>\n          match FindMacro s l with\n          | Some (old_args, m) =>\n              let f' := fold_left\n                (fun x y => FOLLet (MacroArgTerm (fst y) (snd y)) x)\n                (ArgsZip old_args given_args) m in\n              FOLName s (FOLExpandMacros d' l f')\n          | None => Warning (FOLPredicate PredFalse) [\"Macro \"; s; \" not found!\"]\n          end\n      | FOLPredicate p => FOLPredicate p\n      | FOLNot f' => FOLNot (FOLExpandMacros d' l f')\n      | FOLOr a b => FOLOr (FOLExpandMacros d' l a) (FOLExpandMacros d' l b)\n      | FOLAnd a b => FOLAnd (FOLExpandMacros d' l a) (FOLExpandMacros d' l b)\n      | FOLForAll q f' => FOLForAll q (FOLExpandMacros d' l f')\n      | FOLExists q f' => FOLExists q (FOLExpandMacros d' l f')\n      | FOLLet t f' => FOLLet t (FOLExpandMacros d' l f')\n      end\n  | O => Warning (FOLPredicate PredFalse) [\"Recursion depth exceeded!\"]\n  end.\n\nFixpoint SubsetOf\n  (l l' : list GraphEdge)\n  : bool :=\n  match l with\n  | [] => true\n  | h::t => if find (beq_edge h) l' then SubsetOf t l' else false\n  end.\n\nFixpoint ISASubsetOf\n  (l l' : list ISAEdge)\n  : bool :=\n  match l with\n  | [] => true\n  | h::t => if find (beq_isa_edge h) l' then ISASubsetOf t l' else false\n  end.\n\nDefinition CheckFinalState\n  (stage_names : list (list string))\n  (arch_edges : list ArchitectureLevelEdge)\n  (req_edges : list GraphEdge)\n  (check_nodes : bool)\n  (s : FOLState)\n  : bool :=\n  match Topsort (stateEdges s) with\n  | ReverseTotalOrder _ =>\n    let nodes := NodesFromEdges (stateEdges s) in\n    if negb (NodeSetIntersectionIsEmpty (stateNotNodes s) nodes)\n    then\n      let result := false in\n      if PrintFlag 3\n      then Comment result [\"ScenarioTree converged, but forbidden nodes were used\"]\n      else result\n    else\n    if negb (SetIntersectionIsEmpty (stateNotEdges s) (stateEdges s))\n    then\n      let result := false in\n      if PrintFlag 3\n      then Comment result [\"ScenarioTree converged, but forbidden edges were used\"]\n      else result\n    else\n    if negb (SubsetOf req_edges (stateEdges s))\n    then\n      let result := false in\n      if PrintFlag 3\n      then Comment result [\"ScenarioTree converged, but required edges were missing\"]\n      else result\n    else\n    if check_nodes\n    then\n      match NodeSetDifference (stateNodes s) (NodesFromEdges (stateEdges s)) with\n      | _::_  =>\n          let result := false in\n          if PrintFlag 3\n          then Comment result [\"ScenarioTree converged, but required nodes were missing\"]\n          else result\n      | [] =>\n          let result := true in\n          if PrintFlag 3\n          then Comment result [\"ScenarioTree converged\"]\n          else result\n      end\n    else\n      let result := true in\n      if PrintFlag 3\n      then Comment result [\"ScenarioTree converged\"]\n      else result\n  | _ =>\n    let result := false in\n    if PrintFlag 3\n    then Comment result\n      (\"ScenarioTree converged, but graph is cyclic\" :: newline ::\n        (GraphvizCompressedGraph \"DeadEnd\" stage_names (stateEdges s) [] arch_edges))\n    else result\n  end.\n\n(* YM: I don't like this function. I don't use it anymore either...\n   apart from its use in error debugging. *)\nFixpoint ScenarioTreeCheckNodes\n  (s : FOLState)\n  (t : ScenarioTree)\n  : ScenarioTree :=\n  match t with\n  | ScenarioName n t' =>\n      match ScenarioTreeCheckNodes s t' with\n      | ScenarioTrue => ScenarioTrue\n      | ScenarioFalse => ScenarioFalse\n      | t'' => ScenarioName n (t'')\n      end\n  | ScenarioConflict t' =>\n      match ScenarioTreeCheckNodes s t' with\n      | ScenarioTrue => ScenarioTrue\n      | ScenarioFalse => ScenarioFalse\n      | t'' => ScenarioConflict (t'')\n      end\n  | ScenarioEdgeLeaf [] => ScenarioTrue\n  | ScenarioNotEdgeLeaf [] => ScenarioTrue\n  | ScenarioNodeLeaf [] => ScenarioTrue\n  | ScenarioNotNodeLeaf [] => ScenarioTrue\n  | ScenarioEdgeLeaf l => t\n  | ScenarioNotEdgeLeaf l => t\n  | ScenarioNodeLeaf l => ScenarioTrue\n  | ScenarioNotNodeLeaf l => ScenarioTrue\n  | ScenarioPred _ => ScenarioTrue\n  | ScenarioNotPred _ => ScenarioTrue\n  | ScenarioAnd a b =>\n      ScenarioAnd (ScenarioTreeCheckNodes s a) (ScenarioTreeCheckNodes s b)\n  | ScenarioOr a b =>\n      ScenarioOr (ScenarioTreeCheckNodes s a) (ScenarioTreeCheckNodes s b)\n  | ScenarioTrue => ScenarioTrue\n  | ScenarioFalse => ScenarioFalse\n  end.\n\nDefinition FOLStateIsConsistent\n  (s : FOLState)\n  : bool :=\n  if andb (andb (andb\n    (NodeSetIntersectionIsEmpty (stateNodes s) (stateNotNodes s))\n    (NodeSetIntersectionIsEmpty (stateEdgeNodes s) (stateNotNodes s)))\n    (SetIntersectionIsEmpty (stateEdges s) (stateNotEdges s)))\n    (PredSetIntersectionIsEmpty (statePreds s) (stateNotPreds s))\n  then true else false.\n\nFixpoint ReevaluateScenarioTreeIterator\n  (n : nat)\n  (stage_names : list (list string))\n  (arch_edges : list ArchitectureLevelEdge)\n  (req_edges : list GraphEdge)\n  (s : FOLState)\n  (t : ScenarioTree)\n  (strat : BranchingStrategy)\n  : FOLState * ScenarioTree :=\n  (* Re-evaluate the constraints given the current graph, and prune out\n   * any which are no longer valid *)\n  let t'' := ReevaluateScenarioTree s t in\n  let t'' := ScenarioTreeEdgeCountGraph 5 t'' \"ScenarioCounts_StillIterating_NotSimplified\" in\n  (* Simplify the remaining tree *)\n  let t' := SimplifyScenarioTree t'' in\n  let t' := ScenarioTreeEdgeCountGraph 3 t' \"ScenarioCounts_StillIterating_Simplified\" in\n  (* Check if this is a dead end *)\n  if ReducesToFalse t'\n  then\n    let result := (s, ScenarioFalse) in\n    if PrintFlag 3\n    then\n      let t'' :=\n        match (ScenarioTreeKeepIfFalse s t) with\n        | Some t''' =>\n          let t''' :=\n            if PrintFlag 3\n            then\n              let t''' := Comment t''' (\"Reached dead end\" :: newline ::\n              (GraphvizCompressedGraph \"DeadEnd\" stage_names (stateEdges s) [] arch_edges)) in\n              match FindBranchingChoices strat t''' with\n              | Some (RegularChoice cases)\n              | Some (ConflictChoice cases) =>\n                let f a b :=\n                  match b with\n                  | ScenarioEdgeLeaf b' =>\n                      let g' := app_rev (stateEdges s) b' in\n                      Printf a (StringOf\n                        (GraphvizCompressedGraph \"DeadEndBranch\" stage_names g' [] arch_edges))\n                  | _ => Printf a (StringOf [newline; \"//DeadEndBranch had a branching choice other than an edge\"; newline])\n                  end in\n                fold_left f cases t'''\n              | None => Comment t''' [\"No branching edges at dead end?\"]\n              end\n            else t''' in\n            ScenarioTreeEdgeCountGraph 1 t''' \"ReducesToFalse\"\n        | None => Warning ScenarioFalse [\"Doesn't reduce to false?\"]\n        end in\n      match t'' with\n      | ScenarioTrue => Comment result [\"ScenarioTree unsatisfiable?\"]\n      | _ => Comment result [\"ScenarioTree unsatisfiable\"]\n      end\n    else result\n  else\n  (* Not FALSE; need to keep evaluating *)\n  match GuaranteedEdges t' with\n  | (n1, n2, e1, e2, p1, p2) =>\n    (* Take transitive closure and add any new edges that may have arisen. *)\n    match TransitiveClosure (app_rev (stateEdges s) e1) with\n    | TC x =>\n        (* Still no cycle; so recurse to continue unit propagation *)\n        let e1' := EdgesFromAdjacencyList x in\n        let e2' := app_rev (stateNotEdges s) e2 in\n        let n1' := app_rev (stateNodes s) n1 in\n        let n2' := app_rev (stateNotNodes s) n2 in\n        let p1' := app_rev (statePreds s) p1 in\n        let p2' := app_rev (stateNotPreds s) p2 in\n        let s' := FOLStateReplaceEdges s n1' n2' e1' e2' p1' p2' in\n        if negb (FOLStateIsConsistent s')\n        then\n          let result := (s', ScenarioFalse) in\n          if PrintFlag 3\n          then Comment result [\"FOL state inconsistent during ScenarioTree convergence\"]\n          else result\n        else\n        let s' :=\n          if PrintFlag 6\n          then Comment s' [stringOfNat (List.length n1'); \" required nodes\"]\n          else s' in\n        let s' :=\n          if PrintFlag 6\n          then Comment s' [stringOfNat (List.length n2'); \" forbidden nodes\"]\n        else s' in\n        (* Check if the unit propagation has converged *)\n        match (n1, n2, e1, e2) with\n        | ([], [], [], []) =>\n          (* Re-evaluate and simplify one last time. *)\n          let t' := ReevaluateScenarioTree s' t' in\n          let t' := ScenarioTreeEdgeCountGraph 5 t' \"ScenarioCounts_StillIterating_NotSimplified\" in\n          (* Simplify the remaining tree *)\n          let t' := SimplifyScenarioTree t' in\n          let t' := ScenarioTreeEdgeCountGraph 3 t' \"ScenarioCounts_StillIterating_Simplified\" in\n          (* Check if this is a valid solution *)\n            if ReducesToTrue t' then\n              if CheckFinalState stage_names arch_edges req_edges true s'\n              then\n                let result := (s', ScenarioTrue) in\n                if PrintFlag 3\n                then Comment result [\"ScenarioTree converged and completed\"]\n                else result\n              else\n                let result := (s', ScenarioFalse) in\n                if PrintFlag 3\n                then Comment result [\"ReevaluateScenarioTree converged, but graph is invalid\"]\n                else result\n            else\n              let result := (s', t') in\n              if PrintFlag 3\n              then Comment result [\"ReevaluateScenarioTree converged but not completed\"]\n              else result\n        | _ =>\n          (* Recurse *)\n          match n with\n          | S n' =>\n              let s' :=\n                if PrintFlag 3\n                then Comment s'\n                  (\"ReevaluateScenarioTreeIterator iterating\" :: newline ::\n                  (GraphvizCompressedGraph \"Iterating\" stage_names\n                    (stateEdges s') (SetDifference (stateEdges s') (stateEdges s'))\n                    arch_edges))\n                else s' in\n              ReevaluateScenarioTreeIterator n' stage_names arch_edges req_edges s' t' strat\n           | 0 => Warning (s', ScenarioFalse)\n               [\"ReevaluateScenarioTree Iteration limit exceeded!\"]\n          end\n        end\n    | TCError e' =>\n        (* Adding these edges would form a cycle: fail *)\n        let result := (UpdateFOLState true s (ScenarioEdgeLeaf e'), ScenarioFalse) in\n        if PrintFlag 3\n        then\n          let f a b := Comment a [StringOfGraphEdge b] in\n          let result := fold_left f e' result in\n          Comment result (\"Graph is now cyclic; pruning.\" :: newline ::\n            (GraphvizCompressedGraph \"DeadEnd\" stage_names\n              (stateEdges (fst result)) [] arch_edges))\n        else result\n    end\n  end.\n\nFixpoint StringOfCase\n  (t : ScenarioTree)\n  : string :=\n    match t with\n    | ScenarioEdgeLeaf l => \n        fold_left (fun a b => StringOf [a; newline; \"// \"; StringOfGraphEdge b]) l\n        (StringOf [newline; \"// Case: \"])\n    | ScenarioNotEdgeLeaf l =>\n        fold_left (fun a b => StringOf [a; newline; \"// \"; StringOfGraphEdge b]) l\n        (StringOf [newline; \"// Case: Not all of edges: \"])\n    | ScenarioNodeLeaf l =>\n        fold_left (fun a b => StringOf [a; newline; \"// \"; GraphvizShortStringOfGraphNode b]) l\n        (StringOf [newline; \"// Case: \"])\n    | ScenarioNotNodeLeaf l =>\n        fold_left (fun a b => StringOf [a; newline; \"// \"; GraphvizShortStringOfGraphNode b]) l\n        (StringOf [newline; \"// Case: Not all of nodes: \"])\n    | ScenarioPred p =>\n        StringOf [newline; \"// Case: \"; StringOf (PrintPredicate p)]\n    | ScenarioNotPred p =>\n        StringOf [newline; \"// Case: NotPred \"; StringOf (PrintPredicate p)]\n    | ScenarioAnd a b =>\n        StringOf [newline; \"//Case: AND of \"; StringOfCase a; newline; \" AND \"; newline; StringOfCase b]\n    | _ => Warning (StringOf [newline; \"//Case is something mysterious!\"; newline]) [\"Case is indecipherable!\"]\n    end.\n\nFixpoint StringOfDPLLState\n  (h : nat * nat)\n  : string :=\n  let (h1, h2) := h in\n  StringOf [\" (\"; stringOfNat h1; \"/\"; stringOfNat h2; \")\"].\n\nFixpoint PrintISAChainHelper2\n  (first : bool)\n  (l : list ISAEdge)\n  (l' : list string)\n  : list string :=\n  match l with\n  | [] => l'\n  | h::[] => if first then\n              let f x :=\n               match x with\n               | EdgePO => \"po;\"\n               | EdgeCO => \"co;\"\n               | EdgeRF => \"rf;\"\n               | EdgeFR => \"fr;\"\n               | EdgeRFE => \"rfe;\"\n               | EdgeFRE => \"fre;\"\n               | EdgePO_loc => \"po_loc;\"\n               | EdgePO_plus => \"po+;\"\n               | EdgePO_loc_plus => \"po_loc+;\"\n               | EdgeFence => \"fence;\"\n               | EdgeToFence => \"to_fence;\"\n               | EdgeFromFence => \"from_fence;\"\n               | EdgeFence_plus => \"fence+;\"\n               | EdgeFencePO_plus => \"fence_po+;\"\n               | EdgePOFence_plus => \"po_fence+;\"\n               | EdgePPO => \"ppo;\"\n               | EdgePPO_plus => \"ppo+;\"\n               | EdgePPOFence_plus => \"ppo_fence+;\"\n               | EdgeFencePPO_plus => \"fence_ppo+;\"\n               end in\n               ((f h)::l')\n             else\n              let f x :=\n               match x with\n               | EdgePO => \"po);\"\n               | EdgeCO => \"co);\"\n               | EdgeRF => \"rf);\"\n               | EdgeFR => \"fr);\"\n               | EdgeRFE => \"rfe);\"\n               | EdgeFRE => \"fre);\"\n               | EdgePO_loc => \"po_loc);\"\n               | EdgePO_plus => \"po+);\"\n               | EdgePO_loc_plus => \"po_loc+);\"\n               | EdgeFence => \"fence);\"\n               | EdgeToFence => \"to_fence);\"\n               | EdgeFromFence => \"from_fence);\"\n               | EdgeFence_plus => \"fence+);\"\n               | EdgeFencePO_plus => \"fence_po+);\"\n               | EdgePOFence_plus => \"po_fence+);\"\n               | EdgePPO => \"ppo);\"\n               | EdgePPO_plus => \"ppo+);\"\n               | EdgePPOFence_plus => \"ppo_fence+);\"\n               | EdgeFencePPO_plus => \"fence_ppo+);\"\n               end in\n               ((f h)::l')\n  | h::t => if first then \n              let f x :=\n              match x with\n              | EdgePO => \"(po & \"\n              | EdgeCO => \"(co & \"\n              | EdgeRF => \"(rf & \"\n              | EdgeFR => \"(fr & \"\n              | EdgeRFE => \"(rfe & \"\n              | EdgeFRE => \"(fre & \"\n              | EdgePO_loc => \"(po_loc & \"\n              | EdgePO_plus => \"(po+ & \"\n              | EdgePO_loc_plus => \"(po_loc+ &\"\n              | EdgeFence => \"(fence &\"\n              | EdgeToFence => \"(to_fence &\"\n              | EdgeFromFence => \"(from_fence &\"\n              | EdgeFence_plus => \"(fence+ &\"\n              | EdgeFencePO_plus => \"(fence_po+ &\"\n              | EdgePOFence_plus => \"(po_fence+ &\"\n              | EdgePPO => \"(ppo &\"\n              | EdgePPO_plus => \"(ppo+ &\"\n              | EdgePPOFence_plus => \"(ppo_fence+ &\"\n              | EdgeFencePPO_plus => \"(fence_ppo+ &\"\n              end in\n              (PrintISAChainHelper2 false t ((f h)::l'))\n            else\n              let f x :=\n              match x with\n              | EdgePO => \"po & \"\n              | EdgeCO => \"co & \"\n              | EdgeRF => \"rf & \"\n              | EdgeFR => \"fr & \"\n              | EdgeRFE => \"rfe & \"\n              | EdgeFRE => \"fre & \"\n              | EdgePO_loc => \"po_loc & \"\n              | EdgePO_plus => \"po+ & \"\n              | EdgePO_loc_plus => \"po_loc+ &\"\n              | EdgeFence => \"fence &\"\n              | EdgeToFence => \"to_fence &\"\n              | EdgeFromFence => \"from_fence &\"\n              | EdgeFence_plus => \"fence+ &\"\n              | EdgeFencePO_plus => \"fence_po+ &\"\n              | EdgePOFence_plus => \"po_fence+ &\"\n              | EdgePPO => \"ppo &\"\n              | EdgePPO_plus => \"ppo+ &\"\n              | EdgePPOFence_plus => \"ppo_fence+ &\"\n              | EdgeFencePPO_plus => \"fence_ppo+ &\"\n              end in\n              (PrintISAChainHelper2 false t ((f h)::l'))\n  end.\n\nFixpoint PrintISAChainHelper\n  (l : list (list ISAEdge))\n  (l' : list string)\n  : list string :=\n  match l with\n  | [] => rev l'\n  | h::t => PrintISAChainHelper t (PrintISAChainHelper2 true h l')\n  end.\n\nDefinition PrintISAChain\n  (l : list (list ISAEdge))\n  : list string :=\n  PrintISAChainHelper l [].\n\nDefinition ReplaceISAEdges\n  (path : list (nat * nat * option (list ISAEdge)))\n  (e : list ISAEdge)\n  : list (nat * nat * option (list ISAEdge)) :=\n  match path with\n  | [] => Warning [] [\"Replacing ISA edges on an empty path?\"]\n  | h::t => let '(h1, h2, h3) := h in\n              match h3 with\n              | None => ((h1, h2, Some e)::t)\n              | Some s => Comment ((h1, h2, Some e)::t) ([\"Replacing real ISA edges \"] ++ (PrintISAChain [s])\n                                        ++ [\" with \"] ++ (PrintISAChain [e]) ++ [\"; should be an invariant case.\"])\n              end\n  end.\n\nDefinition StringOfPiProofState\n  (h : nat * nat * option (list (list ISAEdge)))\n  : string :=\n  let '(h1, h2, h3) := h in\n  match h3 with\n  | None => StringOf [\" (\"; stringOfNat h1; \"/\"; stringOfNat h2; \")\"]\n  | Some h3' => StringOf ([\" (\"; stringOfNat h1; \"/\"; stringOfNat h2; \", \"] ++ (PrintISAChain h3') ++ [\")\"])\n  end.\n\nFixpoint NegateScenarioTree\n  (t : ScenarioTree)\n  : ScenarioTree :=\n  match t with\n  | ScenarioName s t' => ScenarioName s (NegateScenarioTree t')\n  | ScenarioConflict t' => ScenarioConflict (NegateScenarioTree t')\n  | ScenarioAnd a b =>\n      ScenarioOr (NegateScenarioTree a) (NegateScenarioTree b)\n  | ScenarioOr a b =>\n      ScenarioAnd (NegateScenarioTree a) (NegateScenarioTree b)\n  | ScenarioEdgeLeaf l => fold_left (FoldFlipEdge false) l ScenarioFalse\n  | ScenarioNotEdgeLeaf l => fold_left (FoldFlipEdge true) l ScenarioFalse\n  | ScenarioNodeLeaf l => fold_left (FoldFlipNode false) l ScenarioFalse\n  | ScenarioNotNodeLeaf l => fold_left (FoldFlipNode true) l ScenarioFalse\n  | ScenarioPred p => ScenarioNotPred p\n  | ScenarioNotPred p => ScenarioPred p\n  | ScenarioTrue => ScenarioFalse\n  | ScenarioFalse => ScenarioTrue\n  end.\n\nFixpoint TabList\n  (n : nat)\n  (l : list string)\n  : list string :=\n  match n with\n  | O => l\n  | S n' => TabList n' (tab::l)\n  end.\n\nFixpoint PrintBranchingChoice\n  {A : Type}\n  (s : A)\n  (n : nat)\n  (t : ScenarioTree)\n  : A :=\n  match t with\n  | ScenarioName _ t' => PrintBranchingChoice s n t'\n  | ScenarioConflict t' => let t' := Comment t' ((TabList n [newline]) ++ [\"Conflict choice:\"]) in\n                              PrintBranchingChoice s n t'\n  | ScenarioAnd a b =>\n      let s := PrintBranchingChoice s (n + 1) a in\n      let s := Comment s ((TabList n [newline]) ++ [\"AND\"]) in\n      PrintBranchingChoice s (n + 1) b\n  | ScenarioOr a b =>\n      let s := PrintBranchingChoice s (n + 1) a in\n      let s := Comment s ((TabList n [newline]) ++ [\"OR\"]) in\n      PrintBranchingChoice s (n + 1) b\n  | ScenarioEdgeLeaf l => Comment s (rev (fold_left (fun x y => y::newline::x) (Map (fun x => StringOf ((TabList n []) ++ [ShortStringOfGraphEdge x])) l) [newline]))\n  | ScenarioNotEdgeLeaf l => Comment s (rev (\")\"::(fold_left (fun x y => y::newline::x) (Map (fun x => StringOf ((TabList n []) ++ [ShortStringOfGraphEdge x])) l) [newline; \"NOT:(\"])))\n  | ScenarioNodeLeaf l => Comment s (rev (fold_left (fun x y => y::newline::x) (Map (fun x => StringOf ((TabList n []) ++ [ShortStringOfGraphNode x])) l) [newline]))\n  | ScenarioNotNodeLeaf l => Comment s (rev (\")\"::(fold_left (fun x y => y::newline::x) (Map (fun x => StringOf ((TabList n []) ++ [ShortStringOfGraphNode x])) l) [newline; \"NOT:(\"])))\n  | ScenarioPred p => Comment s (PrintPredicate p)\n  | ScenarioNotPred p => Comment s ((\"NOT:(\"::(PrintPredicate p)) ++ [\")\"])\n  | ScenarioTrue => Comment s [\"TRUE\"]\n  | ScenarioFalse => Comment s [\"FALSE\"]\n  end.\n\nFixpoint FOL_DPLL\n  (n : nat)\n  (arch_edges : list ArchitectureLevelEdge)\n  (req_edges : list GraphEdge)\n  (path : list (nat * nat))\n  (stage_names : list (list string))\n  (s : FOLState)\n  (t : ScenarioTree)\n  (strat : BranchingStrategy)\n  : option FOLState :=\n  match n with\n  | S n' =>\n    (* Depending on the backend, print a status update every once in a while *)\n    let s :=\n      if orb (PrintFlag 5) (TimeForStatusUpdate 1)\n      then CommentFlush s (\"Progress: \" :: Map StringOfDPLLState (rev_append path []))\n      else s in\n    (* Evaluate one step *)\n    match ReevaluateScenarioTreeIterator 100 stage_names arch_edges req_edges s t strat with\n    | (s', t') =>\n      (* Debug output *)\n      let t' := ScenarioTreeEdgeCountGraph 3 t' \"ScenarioCounts\" in\n      let t' :=\n        if PrintFlag 3\n        then Comment t' (\"Graph is:\" :: newline ::\n          (GraphvizCompressedGraph\n            (StringOf (\"Converged: \" ::\n              (Map StringOfDPLLState (rev_append path []))))\n            stage_names\n            (stateEdges s') [] arch_edges))\n        else t' in\n      (* Check if the graph reduces to TRUE or FALSE *)\n      let t'' := t' in\n      let t'' := ScenarioTreeEdgeCountGraph 3 (SimplifyScenarioTree t'')\n        \"BranchingEdges\" in\n      if ReducesToTrue  t'' then Some s' else\n      if ReducesToFalse t''\n      then\n        if PrintFlag 3\n        then\n          (* Debug: find and display the constraints that caused the problem *)\n          let t := ScenarioTreeEdgeCountGraph 5 (ScenarioTreeAssignLeaves s' t')\n            \"PreUnsatisfiableConstraints\" in\n          let t''' :=\n          match ScenarioTreeKeepIfFalse s t with\n          | Some t''' =>\n              ScenarioTreeEdgeCountGraph 3 t''' \"UnsatisfiableConstraints\"\n          | None =>\n              match Topsort (stateEdges s') with\n              | ReverseTotalOrder _ => Warning\n                  (ScenarioTreeEdgeCountGraph 1 t' \"UnsatisfiableConstraints\")\n                  [\"Disagreement on whether tree reduces to false?\"]\n              | _ => ScenarioName \"Cyclic\" ScenarioFalse\n              end\n          end in\n          match t''' with\n          | ScenarioTrue => Warning None [\"Tree reduced to false?\"]\n          | _ =>\n              if PrintFlag 2\n              then Comment None [\"Tree reduced to false\"]\n              else None\n          end\n        else None\n      else\n      (* Neither TRUE nor FALSE: find a set of branching choices *)\n      let t'' :=\n      match strat with\n      | NotEdgeStrat _ => if PrintFlag 2 then ScenarioTreeEdgeCountGraph 1 t'' \"BeforeBranching\" else t''\n      | _ => t''\n      end\n      in\n      match FindBranchingChoices strat t'' with\n      | Some (RegularChoice cases)\n      | Some (ConflictChoice cases) =>\n        (* Only try not edges for the first branching decision; that's all we need... *)\n        let strat :=\n        match strat with\n        | NotEdgeStrat _ => NotEdgeStrat false\n        | HasDepStrat _ => HasDepStrat false\n        | _ => strat\n        end\n        in\n        let cases := SortChoices cases in\n        let cases :=\n          if PrintFlag 3\n          then\n            Comment cases [\"DPLL Found \";\n            stringOfNat (List.length cases); \" to consider\";\n            StringOf (Map StringOfCase cases)]\n          else cases in\n        (* For each branching choice, recursively evaluate the graph with\n         * this choice added.  If a branch doesn't work, add the opposite\n         * of that choice as a learned conflict term. *)\n        let f_fold\n          (a : option FOLState * ScenarioTree * nat) (b : ScenarioTree) :=\n          let '(a1, a2, a3) := a in\n          match a1 with\n          | Some _ =>\n              (* Found a solution down a previous branch: return it, and don't\n               * evaluate further *)\n              (a1, ScenarioFalse, S a3)\n          | None =>\n              (* Add the choice to the current graph *)\n              let s'' := UpdateFOLState false s' b in\n              let new_path := ((a3, List.length cases) :: path) in\n              (* Debug output *)\n              let s'' :=\n                if PrintFlag 3\n                then\n                  let s'' := Comment s'' [\"Considering case:\"; newline] in\n                  Comment (PrintBranchingChoice s'' 0 b) [newline]\n                else s'' in\n              (* Add the current conflict clauses to the scenario tree *)\n              let new_tree := ScenarioAnd a2 t' in\n              (* Add the negation of the current branch as a conflict clause for\n                 future branches if this branch should fail to work *)\n              let new_conflict := (ScenarioAnd a2\n                (NegateScenarioTree b)) in\n              if (negb (FOLStateIsConsistent s'')) then\n                (None, new_conflict, S a3)\n              else\n                (* Recurse *)\n                (FOL_DPLL n' arch_edges req_edges new_path stage_names s'' new_tree strat, new_conflict, S a3)\n          end in\n        (* Loop over each branch in the branching set *)\n        fst (fst (fold_left f_fold cases (None, ScenarioTrue, 0)))\n      | None =>\n        Warning None [\"DPLL could not find branching edges!\"]\n      end\n    end\n  | 0 =>\n      (* Oops!  Recursed too deep! *)\n      let t := ScenarioTreeEdgeCountGraph 3 t \"ScenarioCounts\" in\n      let t := ScenarioTreeEdgeCountGraph 1\n        (SimplifyScenarioTree (ScenarioTreeCheckNodes s t))\n        \"BranchingEdges\" in\n      match t with\n      | ScenarioTrue => Warning (Some s) [\"FOL_DPLL iteration limit reached TRUE!\"]\n      | _ => Warning (Some s) [\"FOL_DPLL iteration limit reached!\"]\n      end\n  end.\n\nInductive FOLStatement : Set :=\n| FOLAxiom : FOLFormula -> FOLStatement\n| FOLMacroDefinition : FOLMacro -> FOLStatement\n| FOLContextTerm : FOLTerm -> FOLStatement.\n\nFixpoint AddContext\n  (core : nat)\n  (c : list FOLTerm)\n  (f : FOLFormula)\n  : FOLFormula :=\n  match c with\n  | h::t => FOLLet h (AddContext core t f)\n  | [] => f\n  end.\n\nFixpoint EvaluateFOLStatementsHelper\n  (core : nat)\n  (m : list FOLMacro)\n  (c : list FOLTerm)\n  (f : FOLFormula)\n  (l : list FOLStatement)\n  : FOLFormula :=\n  match l with\n  | (FOLAxiom f')::t => EvaluateFOLStatementsHelper core m c (FOLAnd f f') t\n  | (FOLMacroDefinition m')::t => EvaluateFOLStatementsHelper core (m' :: m) c f t\n  | (FOLContextTerm c')::t => EvaluateFOLStatementsHelper core m (AddTerm c c') f t\n  | [] => FOLExpandMacros MacroExpansionDepth m (AddContext core c f)\n  end.\n\nDefinition EvaluateFOLStatements\n  (c : nat)\n  (l : list FOLStatement)\n  : FOLFormula :=\n  EvaluateFOLStatementsHelper c [] [IntTerm \"c\" c] (FOLPredicate PredTrue) l.\n\nDefinition MicroarchitecturalComponent := list FOLStatement.\n\nDefinition Microarchitecture := list MicroarchitecturalComponent.\n\nFixpoint BuildMicroarchitectureHelper\n  (l : list MicroarchitecturalComponent)\n  (c : nat)\n  : FOLFormula :=\n  match l with\n  | [] => FOLPredicate PredFalse\n  | [h] =>\n      let result := EvaluateFOLStatements c h in\n      PrintGraphvizStringOfFOLFormula result\n  | h::t =>\n      let result := EvaluateFOLStatements c h in\n      let result := PrintGraphvizStringOfFOLFormula result in\n      FOLAnd result (BuildMicroarchitectureHelper t (S c))\n  end.\n\nFixpoint BuildMicroarchitecture\n  (m : Microarchitecture)\n  : FOLFormula :=\n  BuildMicroarchitectureHelper m 0.\n\nFixpoint SetNth\n  {A : Type}\n  (n : nat)\n  (l : list (option A))\n  (a : A)\n  : list (option A) :=\n  match (n, l) with\n  | (S n', h::t) => h      :: SetNth n' t  a\n  | (S n', []  ) => None   :: SetNth n' [] a\n  | (O   , h::t) => Some a :: t\n  | (O   , []  ) => [Some a]\n  end.\n\nFixpoint StageNamesRemoveOptions\n  (l : list (option string))\n  : list string :=\n  match l with\n  | Some h :: t => h         :: StageNamesRemoveOptions t\n  | None   :: t => \"Unknown\" :: StageNamesRemoveOptions t\n  | []          => []\n  end.\n\nFixpoint StageNamesHelper\n  (m : MicroarchitecturalComponent)\n  (l : list (option string))\n  : list string :=\n  match m with\n  | FOLContextTerm (StageNameTerm s n)::t =>\n      StageNamesHelper t (SetNth n l s)\n  | _::t => StageNamesHelper t l\n  | [] => StageNamesRemoveOptions l\n  end.\n\nFixpoint StageNames\n  (m : Microarchitecture)\n  : list (list string) :=\n  match m with\n  | h::t => StageNamesHelper h [] :: StageNames t\n  | [] => []\n  end.\n\nFixpoint MakeISAChainList\n  (l : list ISAEdge)\n  : list (list ISAEdge) :=\n  match l with\n  | [] => []\n  | h::t => [h]::(MakeISAChainList t)\n  end.\n\nFixpoint FilterUspecHelper\n  (m : list FOLStatement)\n  (axioms : list FOLStatement)\n  (mapping : list FOLStatement)\n  (theory : list FOLStatement)\n  (inv : list FOLStatement)\n  : (list FOLStatement * list FOLStatement * list FOLStatement * list FOLStatement) :=\n  match m with\n  | [] => (axioms, mapping, theory, inv)\n  | h::t => match h with\n            | FOLAxiom (FOLName n _)\n            | FOLMacroDefinition (n, _, _) =>\n                if string_prefix \"Mapping\" n then\n                  FilterUspecHelper t axioms (h::mapping) theory inv\n                else if string_prefix \"Theory\" n then\n                  FilterUspecHelper t axioms mapping (h::theory) inv\n                else if string_prefix \"Invariant\" n then\n                  FilterUspecHelper t axioms mapping theory (h::inv)\n                else\n                  FilterUspecHelper t (h::axioms) mapping theory inv\n            | FOLContextTerm c' => FilterUspecHelper t (h::axioms) (h::mapping) (h::theory) (h::inv)\n            | _ => Warning ([], [], [], []) [\"Found a nameless axiom or macro!\"]\n            end\n  end.\n\nFixpoint FilterUspecInput\n  (m : list MicroarchitecturalComponent)\n  (axioms : list FOLStatement)\n  (mapping : list FOLStatement)\n  (theory : list FOLStatement)\n  (inv : list FOLStatement)\n  : (list FOLStatement * list FOLStatement * list FOLStatement * list FOLStatement) :=\n  match m with\n  | [] => (axioms, mapping, theory, inv)\n  | h::t => match FilterUspecHelper h axioms mapping theory inv with\n            | (axioms', mapping', theory', inv') => FilterUspecInput t axioms' mapping' theory' inv'\n            end\n  end.\n\nFixpoint AllConnectionsHelper2\n  (a b : Microop)\n  (n : nat)\n  (l' : list nat)\n  (r : list GraphEdge)\n  : list GraphEdge :=\n  match l' with\n  | [] => r\n  | h::t => AllConnectionsHelper2 a b n t (app_rev r [((a, (coreID a, n)), ((b, (coreID b, h))), \"\", \"\")])\n  end.\n\nFixpoint AllConnectionsHelper\n  (a b : Microop)\n  (l l' : list nat)\n  (r : list GraphEdge)\n  : list GraphEdge :=\n  match l with\n  | [] => r\n  | h::t => AllConnectionsHelper a b t l' (AllConnectionsHelper2 a b h l' r)\n  end.\n\nDefinition AllConnections\n  (a b : Microop)\n  (l l' : list nat)\n  : list GraphEdge :=\n  AllConnectionsHelper a b l l' [].\n\nDefinition FoldISAEdge\n  (a b : Microop)\n  (tree : ScenarioTree)\n  (edge : ISAEdge)\n  : ScenarioTree :=\n  ScenarioAnd tree (ScenarioPred (SymPredHasDependency a b edge)).\n\nDefinition FoldISAEdges\n  (a b : Microop)\n  (tree : ScenarioTree)\n  (edges : list ISAEdge)\n  : ScenarioTree :=\n  match edges with\n  | [] => tree\n  | h::t =>\n      ScenarioOr tree (fold_left (FoldISAEdge a b) edges ScenarioTrue)\n  end.\n\nDefinition ISAEdgeDisjunction\n  (a b : Microop)\n  (isa_edges : list (list ISAEdge))\n  : ScenarioTree :=\n  fold_left (FoldISAEdges a b) isa_edges ScenarioFalse.\n\nDefinition ISAEdgeInvifiedDisjunction\n  (a b : Microop)\n  : ScenarioTree :=\n  ScenarioOr (ScenarioOr (ScenarioOr\n    (ScenarioPred (SymPredHasDependency a b EdgePO_plus))\n    (ScenarioPred (SymPredHasDependency a b EdgeCO)))\n    (ScenarioPred (SymPredHasDependency a b EdgeRF)))\n    (ScenarioPred (SymPredHasDependency a b EdgeFR)).\n\nFixpoint GetLocationsHelper\n  (m : MicroarchitecturalComponent)\n  (l : list nat)\n  : list nat :=\n  match m with\n  | [] => l\n  | h::t => match h with\n            | (FOLContextTerm (StageNameTerm _ n)) => GetLocationsHelper t (n::l)\n            | _ => GetLocationsHelper t l\n            end\n  end.\n\nFixpoint GetLocations\n  (m : Microarchitecture)\n  (l : list nat)\n  : list nat :=\n  match m with\n  | [] => l\n  | h::t => GetLocations t (GetLocationsHelper h l)\n  end.\n\n(* Create an axioms-mapping-theory-invariants (AMTI) ScenarioTree for the microarchitecture and state. *)\nDefinition CreateAMTITree\n  (s : FOLState)\n  (amti : FOLFormula * FOLFormula * FOLFormula * FOLFormula)\n  (stage_names : list (list string))\n  : ScenarioTree :=\n  let '(axioms, mapping, theory, inv) := amti in\n  let axioms_tree := EliminateQuantifiers true true stage_names s axioms [] in\n  let mapping_tree := EliminateQuantifiers true true stage_names s mapping [] in\n  let theory_tree := EliminateQuantifiers true true stage_names s theory [] in\n  let inv_tree := EliminateQuantifiers true true stage_names s inv [] in\n  ScenarioAnd (ScenarioAnd (ScenarioAnd axioms_tree mapping_tree) theory_tree) inv_tree.\n\nFixpoint CreateLayersTree\n  (flip : bool)\n  (l : list (list ISAEdge))\n  (l' : list Microop)\n  : ScenarioTree :=\n  match (l, l') with\n  | ([], _) => ScenarioTrue \n  | (h::t, h'::t') => match t' with\n                      | [] => Warning ScenarioFalse [\"Reached end of microops before ISA chain constructed!\"]\n                      | h''::t'' =>\n                          (* It's ok to call ISAEdgeDisjunction here, because [h] is always a single-element list\n                             at the top level. So it will just return <all edges in h> \\/ False, which is just\n                             <all edges in h>, which is exactly what we want. *)\n                          if flip then\n                            ScenarioAnd (ISAEdgeDisjunction h'' h' [h]) (CreateLayersTree flip t t')\n                          else\n                            ScenarioAnd (ISAEdgeDisjunction h' h'' [h]) (CreateLayersTree flip t t')\n                      end\n  | (h::t, []) => Warning ScenarioFalse [\"Reached end of microops before ISA chain constructed!\"]\n  end.\n\nFixpoint FilterTranConnsHelper\n  (tran_conns : list GraphEdge)\n  (s : FOLState)\n  (tree : ScenarioTree)\n  (stage_names : list (list string))\n  (ret : list GraphEdge)\n  : list GraphEdge :=\n  match tran_conns with\n  | [] => ret\n  | h::t => let tree' := ScenarioAnd tree (ScenarioEdgeLeaf [h]) in\n              match FOL_DPLL 1000 [] [] [] stage_names s tree' (NotEdgeStrat true) with\n              | Some _ => let t :=\n                            if PrintFlag 2 then\n                              Comment t [\"Eliminated the following transitive connection:\"; newline; GraphvizStringOfGraphEdge [] \"\" h]\n                            else\n                              t\n                          in\n                          FilterTranConnsHelper t s tree stage_names ret\n              | None => let h :=\n                          if PrintFlag 2 then\n                            Comment h [\"This transitive connection satisfies required edges:\"; newline; GraphvizStringOfGraphEdge [] \"\" h]\n                          else\n                            h\n                        in\n                        FilterTranConnsHelper t s tree stage_names (h::ret)\n              end\n  end.\n\nFixpoint CoveredBy\n  (s : FOLState)\n  (tree : ScenarioTree)\n  (stage_names : list (list string))\n  (cov_conns : list GraphEdge)\n  (conn : GraphEdge)\n  : bool :=\n  match cov_conns with\n  | [] => false\n  | h::t => let tree' := ScenarioAnd tree (ScenarioAnd (ScenarioEdgeLeaf [conn]) (ScenarioNotEdgeLeaf [h])) in (* A /\\ ~B *)\n              match FOL_DPLL 1000 [] [] [] stage_names s tree' DefaultStrat with\n              | Some _ => CoveredBy s tree stage_names t conn\n              | None => let result := Comment true [GraphvizStringOfGraphEdge [] \"\" conn; \" is covered by \"; GraphvizStringOfGraphEdge [] \"\" h] in\n                        result\n              end\n  end.\n\nInductive CoverSet : Set :=\n| ConnSet : GraphEdge -> list GraphEdge -> CoverSet.\n\n(* Returns:\n\n   -(Some true) if e is covered by e'\n   -(Some false) if e' is covered by e\n   -None if the two are incompatible\n*)\nDefinition CheckCoverage\n  (s : FOLState)\n  (tree : ScenarioTree)\n  (stage_names : list (list string))\n  (e e' : GraphEdge)\n  : option bool :=\n  let tree' := ScenarioAnd tree (ScenarioAnd (ScenarioEdgeLeaf [e]) (ScenarioNotEdgeLeaf [e'])) in (* A /\\ ~B *)\n  let tree'' := ScenarioAnd tree (ScenarioAnd (ScenarioEdgeLeaf [e']) (ScenarioNotEdgeLeaf [e])) in (* B /\\ ~A *)\n  let covered_by := FOL_DPLL 1000 [] [] [] stage_names s tree' DefaultStrat in\n  let covers := FOL_DPLL 1000 [] [] [] stage_names s tree'' DefaultStrat in\n  match (covered_by, covers) with\n  | (None, _) => (Some true)\n  | (_, None) => (Some false)\n  | _ => None\n  end.\n\nFixpoint GetNextCoveringSet\n  (s : FOLState)\n  (tree : ScenarioTree)\n  (stage_names : list (list string))\n  (remain : list GraphEdge)\n  (conns : list GraphEdge)\n  (set : CoverSet)\n  : (CoverSet * list GraphEdge) :=\n  match conns with\n  | [] => (set, remain)\n  | h::t => match set with\n            | ConnSet set_rep elems =>\n                let result := CheckCoverage s tree stage_names h set_rep in\n                let '(remain, set_rep, elems) :=\n                  match result with\n                  | Some true =>\n                      let elems :=\n                        if PrintFlag 2 then\n                          Comment elems [GraphvizStringOfGraphEdge [] \"\" h; \" is covered by \"; GraphvizStringOfGraphEdge [] \"\" set_rep]\n                        else\n                          elems\n                      in\n                      (remain, set_rep, (h::elems))\n                  | Some false =>\n                      let elems :=\n                        if PrintFlag 2 then\n                          Comment elems [GraphvizStringOfGraphEdge [] \"\" set_rep; \" is covered by \"; GraphvizStringOfGraphEdge [] \"\" h]\n                        else\n                          elems\n                      in\n                      (remain, h, (set_rep::elems))\n                  | None => ((h::remain), set_rep, elems)\n                  end\n                in\n                GetNextCoveringSet s tree stage_names remain t (ConnSet set_rep elems)\n            end\n  end.\n\nFixpoint MergeCoveringSets\n  (s : FOLState)\n  (tree : ScenarioTree)\n  (stage_names : list (list string))\n  (checked_sets : list CoverSet)\n  (cov_sets : list CoverSet)\n  (new_set : CoverSet)\n  : list CoverSet :=\n  match cov_sets with\n  | [] => (new_set::checked_sets)\n  | h::t =>\n      match (h, new_set) with\n      | (ConnSet h' h_elems, ConnSet nset' n_elems) =>\n          match CheckCoverage s tree stage_names h' nset' with\n          | Some true => app_tail ((ConnSet nset' (app_tail (h'::h_elems) n_elems))::checked_sets) t\n          | Some false => app_tail ((ConnSet h' (app_tail h_elems (nset'::n_elems)))::checked_sets) t\n          | None => MergeCoveringSets s tree stage_names (h::checked_sets) t new_set\n          end\n      end\n  end.\n\n(* For the moment, we are just focusing on making the minimal number of covering sets, not on ensuring that\n   each covering set is complete (i.e. everything that the top element covers is in its \"descendants\"). The\n   former should be enough for our purposes (at least for the moment) because I hypothesize that uarches follow a pattern of\n   having 1 coverer for all connections that won't be torched by required edge requirements. *)\nFixpoint GetCoveringSets\n  (n : nat)\n  (s : FOLState)\n  (tree : ScenarioTree)\n  (stage_names : list (list string))\n  (cov_sets : list CoverSet)\n  (poss_conns : list GraphEdge)\n  : list CoverSet :=\n  match n with\n  | S n' =>\n      match poss_conns with\n      | [] => cov_sets\n      | h::t => let (new_set, remain) := GetNextCoveringSet s tree stage_names [] t (ConnSet h []) in\n                 let cov_sets := MergeCoveringSets s tree stage_names [] cov_sets new_set in\n                 GetCoveringSets n' s tree stage_names cov_sets remain\n      end\n  | O => Warning [] [\"Recursed too far in GetCoveringSets!\"]\n  end.\n\nDefinition Coverify\n  (l : list GraphEdge)\n  : list CoverSet :=\n  let f x :=\n    ConnSet x []\n  in\n  Map f l.\n\nInductive FilterStrategy : Set :=\n| FilterAndCover : FilterStrategy\n| FilterOnly : FilterStrategy\n| CoverOnly : FilterStrategy\n| DoNothing : FilterStrategy.\n\nDefinition FilterTranConns\n  (strat : FilterStrategy)\n  (tran_conns : list GraphEdge)\n  (s : FOLState)\n  (t : ScenarioTree)\n  (rt : ScenarioTree)\n  (stage_names : list (list string))\n  : list CoverSet :=\n  let s := PrintTimestamp s \"Filter_start\" in\n  let req_filtered :=\n    match strat with\n    | FilterAndCover\n    | FilterOnly => FilterTranConnsHelper tran_conns s (ScenarioAnd t rt) stage_names []\n    | CoverOnly\n    | DoNothing => tran_conns\n    end\n  in\n  let result :=\n    match strat with\n    | FilterAndCover\n    | CoverOnly => GetCoveringSets 100 s t stage_names [] req_filtered\n    | FilterOnly\n    | DoNothing => Coverify req_filtered\n    end\n  in\n  PrintTimestamp result \"Filter_end\".\n\nFixpoint PrintMicroopChain\n  {A : Type}\n  (s : A)\n  (l : list Microop)\n  : A :=\n  match l with\n  | [] => s\n  | h::t => let t := Comment t [\"Instr \"; stringOfNat (globalID h); \";\"] in\n              PrintMicroopChain s t\n  end.\n\nFixpoint PrintEdgeList\n  {A : Type}\n  (s : A)\n  (l : list GraphEdge)\n  : A :=\n  match l with\n  | [] => s\n  | h::t => let t := Comment t [GraphvizStringOfGraphEdge [] \"\" h; newline] in\n            PrintEdgeList s t\n  end.\n\nFixpoint FindISADependencies\n  (a b : Microop)\n  (s : FOLState)\n  : list ISAEdge :=\n  let f x :=\n    match x with\n    | SymPredHasDependency a' b' c' => andb (beq_uop a a') (beq_uop b b')\n    | _ => false\n    end\n  in\n  let g x y :=\n    match y with\n    | SymPredHasDependency a' b' c' => (c'::x)\n    | _ => Warning x [\"FindISADependencies: filter function not working properly...\"]\n    end\n  in\n  fold_left g (filter f (statePreds s)) [].\n\nFixpoint ConvertToISAChainHelper\n  (l : list Microop)\n  (s : FOLState)\n  (l' : list (list ISAEdge))\n  : list (list ISAEdge) :=\n  match l with\n  | [] => rev l'\n  | h::t => match t with\n            | [] => l'\n            | h'::t' => ConvertToISAChainHelper t s ((FindISADependencies h h' s)::l')\n            end\n  end.\n\nFixpoint ConvertToISAChain\n  (l : list Microop)\n  (s : FOLState)\n  : list (list ISAEdge) :=\n  ConvertToISAChainHelper l s [].\n\nDefinition StartChain\n  (l : list Microop)\n  : option Microop :=\n  match l with\n  | [] => Comment None [\"Finding start of an empty chain?\"]\n  | h::t => Some h\n  end.\n\nFixpoint EndChain\n  (l : list Microop)\n  : option Microop :=\n  match l with\n  | [] => Comment None [\"Finding end of an empty chain?\"]\n  | h::[] => Some h\n  | h::t => EndChain t\n  end.\n\nFixpoint TryISAPattern\n  (n : nat)\n  (inv_uop : Microop)\n  (inv_edge : ISAEdge)\n  (ret : bool * list (list ISAEdge) * list Microop)\n  (choice : list ISAEdge * option ISAPattern)\n  : (bool * list (list ISAEdge) * list Microop) :=\n  match n with\n  | S n' =>\n      let '(changed, l, inter) := ret in\n      if changed then\n        (* We already succeeded down another path, just return what we already have. *)\n        ret\n      else\n        (* Get the current step. *)\n        match (l, inter) with\n        | (h::t, h''::t'') =>\n            let (edges, rem) := choice in\n            (* Does the current step match with what the inv requires? *)\n            if ISASubsetOf edges h then\n              (* Is this the end of the pattern? *)\n              match rem with\n              | None =>\n                  let t :=\n                  if PrintFlag 2 then\n                    Comment t [\"Reached base case of TryISAPattern for \"; PrintISAEdge inv_edge]\n                  else\n                    t\n                  in\n                  (true, ([inv_edge]::t), inv_uop::t'')\n              | Some rem' =>\n                  (* Check the rest of the path. *)\n                  let choices := GetInitialEdge true 100 rem' in\n                  let '(changed', l', inter') := fold_left (TryISAPattern n' inv_uop inv_edge) choices (changed, t, t'') in\n                  if changed' then (changed', l', inter') else ret (* Only return the new result if we succeeded. *)\n              end\n            else\n              (* Nothing to see here, move along. *)\n              ret\n        | _ => \n          if PrintFlag 2 then\n            Comment ret [\"Ran out of steps before we could get to the end of the invariant.\"] \n          else\n            ret\n        end\n  | O => Warning (false, [], []) [\"Recursed too far in TryISAPattern!\"]\n  end.\n  \nFixpoint ReplaceWithInvariantsHelper\n  (changed : bool)\n  (l : list (list ISAEdge))\n  (inter : list Microop)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : (bool * list (list ISAEdge) * list Microop) :=\n  match StartChain inter with\n  | None => (changed, l, inter)\n  | Some inv_uop =>\n      match inv_patterns with\n      | [] => (changed, l, inter)\n      | h::t => let (pat, inv_edge) := h in\n                let choices := GetInitialEdge true 100 pat in\n                let '(changed', l', inter') := fold_left (TryISAPattern 100 inv_uop inv_edge) choices (false, l, inter) in\n                if orb changed changed' then\n                  ReplaceWithInvariantsHelper true l' inter' t\n                else\n                  ReplaceWithInvariantsHelper false l' inter' t\n      end\n  end.\n\nFixpoint ReplaceWithInvariantsInner\n  (n : nat)\n  (changed : bool)\n  (l : list (list ISAEdge))\n  (inter : list Microop)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : (list (list ISAEdge) * list Microop) :=\n  match n with\n  | S n' =>\n      let ret := ReplaceWithInvariantsHelper false l inter inv_patterns in\n      let '(changed', l', inter') := ret in\n      if changed' then\n        ReplaceWithInvariantsInner n' true l' inter' inv_patterns\n      else\n        (l', inter')\n  | O => Warning ([], []) [\"Recursed too far in ReplaceWithInvariantsInner!\"]\n  end.\n\nDefinition ReplaceWithInvariants\n  (l : list (list ISAEdge))\n  (inter : list Microop)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : (list (list ISAEdge) * list Microop) :=\n  ReplaceWithInvariantsInner 100 false l inter inv_patterns.\n\nFixpoint ReplaceWithInvariantsOuter\n  (l : list (list ISAEdge))\n  (inter : list Microop)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : (list (list ISAEdge) * list Microop) :=\n  match (l, inter) with\n  | ([], h::[]) => (l, inter)\n  | (h::t, h'::t') =>\n      let (l', inter') := ReplaceWithInvariantsOuter t t' inv_patterns in\n      ReplaceWithInvariants (h::l') (h'::inter') inv_patterns\n  | _ => Warning ([], []) [\"Unexpected pattern in ReplaceWithInvariantsOuter!\"]\n  end.\n\nDefinition InvPatterns :=\n  [\n    ((Rel EdgePO), EdgePO_plus);\n    ((Rel EdgePPO), EdgePPO_plus);\n    ((Rel EdgePO_loc), EdgePO_loc_plus);\n    ((Rel EdgeFence), EdgeFence_plus);\n    (Chain (Rel EdgeFence_plus) (Rel EdgePO_plus), EdgeFencePO_plus);\n    (Chain (Rel EdgePO_plus) (Rel EdgeFence_plus), EdgePOFence_plus);\n    (Chain (Rel EdgeFence_plus) (Rel EdgePPO_plus), EdgeFencePPO_plus);\n    (Chain (Rel EdgePPO_plus) (Rel EdgeFence_plus), EdgePPOFence_plus)\n  ].\n\nDefinition InvariantifyChain\n  (l : list (list ISAEdge))\n  : list (list ISAEdge) :=\n  (* Make dummy chains for the rest of the parameters to ReplaceWithInvariants.\n     We don't care about their values here. *)\n  let l := \n    if PrintFlag 2 then\n      Comment l ([\"Invariantifying the chain \"] ++ (PrintISAChain l))\n    else\n      l\n  in\n  let inter := Map (fun x => mkMicroop 0 0 0 0 (Fence [])) ([]::l) in\n  let '(chain, _) := ReplaceWithInvariantsOuter l inter InvPatterns in\n  let chain :=\n    if PrintFlag 2 then\n      Comment chain ([\"Invariantified chain is \"] ++ (PrintISAChain chain))\n    else\n      chain\n  in\n  chain.\n\nDefinition TransformISAEdge\n  (e : list ISAEdge)\n  : list (list ISAEdge) :=\n  match e with\n  | _ => [e]\n  end.\n\nDefinition GetInvEdges\n  (l : list (ISAPattern * ISAEdge))\n  : list ISAEdge :=\n  let f x :=\n    match x with\n    | (y, z) => z\n    end\n  in\n  Map f l.\n\nDefinition GetInvPatterns\n  (l : list (ISAPattern * ISAEdge))\n  : list ISAPattern :=\n  let f x :=\n    match x with\n    | (y, z) => y\n    end\n  in\n  Map f l.\n\nFixpoint InvCoveredByHelper2\n  (peel_left : bool)\n  (e : ISAEdge)\n  (l : list ISAEdge)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : bool :=\n  match l with\n  | [] => false\n  | h::t => match find (fun x => beq_isa_edge h (snd x)) inv_patterns with\n            | None => InvCoveredByHelper2 peel_left e t inv_patterns\n            | Some (pat, _) =>\n                let pat := Comment pat ([\"Found pattern \"] ++ (PrintISAPattern pat) ++ [\" for \"; PrintISAEdge h; \" in inv_patterns when filtering peeling choices.\"]) in\n                let choices :=\n                  if peel_left then\n                    GetISAEdges (GetFinalEdge 100 pat)\n                  else\n                    GetISAEdges (GetInitialEdge false 100 pat)\n                in\n                let f x :=\n                  if find (beq_isa_edge e) x then true else false\n                in\n                if fold_left andb (Map f choices) true then\n                  true\n                else\n                  InvCoveredByHelper2 peel_left e t inv_patterns\n            end\n  end.\n\nDefinition InvCoveredByHelper\n  (peel_left : bool)\n  (e : ISAEdge)\n  (l : list ISAEdge)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : bool :=\n  match (find (beq_isa_edge e) l, find (fun x => beq_isa_edge e (snd x)) inv_patterns) with\n  | (Some _, Some _) => true (* This is the simple case. The invified edge matches the end of the current chain. *)\n  | _ =>\n      InvCoveredByHelper2 peel_left e l inv_patterns (* Check whether the innards of invariantified edges ending chains could eat up our choice \"e\". *)\n  end.\n\nFixpoint InvCoveredBy\n  (peel_left : bool)\n  (l l' : list ISAEdge)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : bool :=\n  match l with\n  | [] => true\n  | h::t => if InvCoveredByHelper peel_left h l' inv_patterns then InvCoveredBy peel_left t l' inv_patterns else false\n  end.\n\nDefinition ChopHead\n  (l : list (list ISAEdge))\n  : list (list ISAEdge) * list ISAEdge :=\n  match l with\n  | [] => Warning ([], []) [\"Chopping head of an empty list?\"]\n  | h::t => (t, h)\n  end.\n\nDefinition ChopTail\n  (l : list (list ISAEdge))\n  : list (list ISAEdge) * list ISAEdge :=\n  let l' := rev l in\n  match l' with\n  | [] => Warning ([], []) [\"Chopping tail of an empty list?\"]\n  | h::t => (rev t, h)\n  end.\n\nFixpoint ChopNumHelper\n  {A : Type}\n  (flip : bool)\n  (n : nat)\n  (l : list A)\n  : list A :=\n  match n with\n  | O => if flip then rev l else l\n  | S n' => match l with\n            | [] => Warning [] [\"Chopping an empty list?\"]\n            | h::t => ChopNumHelper flip n' t\n            end\n  end.\n\nDefinition ChopHeadNum\n  {A : Type}\n  (n : nat)\n  (l : list A)\n  : list A :=\n  ChopNumHelper false n l.\n\nDefinition ChopTailNum\n  {A : Type}\n  (n : nat)\n  (l : list A)\n  : list A :=\n  ChopNumHelper true n (rev l).\n\n(* This function checks if an initial subchain (check_chain) can be subsumed within the rest of the chain (rest_chain). It's essentially\n   checking whether the edge added to a chain by the peeling \"completes the pattern\" of an invariant which is right next to it (and thus\n   should subsume it). In this case, the function returns false, indicating that this choice ought to be tossed.\n\n   Example: fence+; ppo_fence+\n\n   If we add ppo (and thus ppo+) to this chain, we'd get \"ppo+; fence+; ppo_fence+\". CheckChoiceHelper would first check \"ppo+\" against \"fence+; ppo_fence+\"\n   and come up empty. It would then check \"ppo+; fence+\" against \"ppo_fence+\". It first invariantifies \"ppo+; fence+\" (the call to InvariantifyChain below)\n   into \"ppo_fence+\", which can be subsumed into the rest_chain of \"ppo_fence+\", so we return false.\n\n   If no initial subchain can be subsumed within the rest of the chain, the function returns true, indicating that this choice is a valid choice.\n*)\nFixpoint CheckChoiceHelper\n  (n : nat)\n  (peel_left : bool)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  (check_chain : list (list ISAEdge))\n  (rest_chain : list (list ISAEdge))\n  : bool :=\n  match n with\n  | S n' =>\n      let check_chain' := InvariantifyChain check_chain in\n      let check_chain' :=\n      if PrintFlag 2 then\n        Comment check_chain' ([\"Checking \"] ++ (PrintISAChain check_chain') ++ [\" against \"] ++ (PrintISAChain rest_chain))\n      else\n        check_chain'\n      in\n      match rest_chain with\n      | [] =>\n          if PrintFlag 2 then\n            Comment true [\"Reached the end of rest_chain without a match...\"]\n          else\n            true\n      | h'::t' =>\n        match check_chain' with\n        | [h] =>\n            if peel_left then\n              let (rest_start, rest_tail) := ChopTail rest_chain in\n              if InvCoveredBy peel_left h rest_tail inv_patterns then\n                if PrintFlag 2 then\n                  Comment false [\"check_chain is covered, tossing.\"]\n                else\n                  false\n              else \n                CheckChoiceHelper n' peel_left inv_patterns (rest_tail::check_chain) rest_start\n            else\n              if InvCoveredBy peel_left h h' inv_patterns then\n                if PrintFlag 2 then\n                  Comment false [\"check_chain is covered, tossing.\"]\n                else\n                  false\n              else \n                CheckChoiceHelper n' peel_left inv_patterns (app_tail check_chain [h']) t'\n        | _ =>\n            if peel_left then\n              let (rest_start, rest_tail) := ChopTail rest_chain in\n              CheckChoiceHelper n' peel_left inv_patterns (rest_tail::check_chain) rest_start\n            else\n              CheckChoiceHelper n' peel_left inv_patterns (app_tail check_chain [h']) t'\n        end\n      end\n  | O => Warning false [\"Recursed too far in CheckChoiceHelper!\"]\n  end.\n\nFixpoint EdgesAreExcluded\n  (edges : list ISAEdge)\n  (excluded_edges : list (list ISAEdge))\n  : bool :=\n  match excluded_edges with\n  | [] => false\n  | h::t => if ISASubsetOf edges h then true else EdgesAreExcluded edges t\n  end.\n\nDefinition CheckChoice\n  (peel_left : bool)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  (rest_chain : list (list ISAEdge))\n  (excluded_edges : list (list ISAEdge))\n  (choice : list ISAEdge * option ISAPattern)\n  : (bool * list ISAEdge * option ISAPattern) :=\n  let (edges, rem) := choice in\n  if EdgesAreExcluded edges excluded_edges then\n    (false, edges, rem)\n  else\n    let check_chain := [edges] in\n    let matched := CheckChoiceHelper 100 peel_left inv_patterns check_chain rest_chain in\n    (matched, edges, rem).\n\nDefinition FilterNextChoices\n  (peel_left : bool)\n  (chain : list (list ISAEdge))\n  (next : list (list ISAEdge * option ISAPattern))\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  (excluded_edges : list (list ISAEdge))\n  : list (list ISAEdge * option ISAPattern) :=\n  let f x y :=\n    match y with\n    | (true, a, b) => ((a, b)::x)\n    | _ => x\n    end\n  in\n  fold_left f (Map (CheckChoice peel_left inv_patterns chain excluded_edges) next) [].\n\nFixpoint FilterISAPeelChoicesHelper\n  (l ret : list ((list ISAEdge) * option ISAPattern))\n  (exclude_last : bool)\n  : list ((list ISAEdge) * option ISAPattern) :=\n  match l with\n  | [] => ret\n  | h::t => match h with\n            | ([], None) => let t := \n                              if PrintFlag 2 then\n                                Comment t [\"Tossing an empty choice...\"]\n                              else\n                                t\n                            in\n                            FilterISAPeelChoicesHelper t ret exclude_last\n            | (rel, None) => if exclude_last then\n                               let t :=\n                                 if PrintFlag 2 then\n                                   Comment t ([\"Tossing (( \"] ++ (PrintISAChain [rel]) ++\n                                   [\" ), (None)), a choice with no part of the axiom left (should have been tried in concretization/base case)...\"])\n                                 else\n                                   t\n                               in\n                               FilterISAPeelChoicesHelper t ret exclude_last\n                             else\n                               let t :=\n                                 if PrintFlag 2 then\n                                   Comment t ([\"Found a choice with no part of the axiom left: (( \"] ++ (PrintISAChain [rel])\n                                   ++ [\" ), (None)). Adding it to the list.\"])\n                                 else\n                                   t\n                               in\n                               FilterISAPeelChoicesHelper t (h::ret) exclude_last\n            | ([], Some rem) => let t := Warning t ([\"Found a nothing choice with (\"] ++ (PrintISAPattern rem) ++ [\") still left after it!\"]) in\n                              FilterISAPeelChoicesHelper t ret exclude_last\n            | (rel, Some rem) => let t :=\n                                  if PrintFlag 2 then\n                                    Comment t ([\"Found a right and proper choice: (( \"] ++ (PrintISAChain [rel]) ++ [\" ), ( \"] ++ (PrintISAPattern rem)\n                                     ++ [\" )). Adding it to the list.\"])\n                                  else\n                                    t\n                                 in\n                             FilterISAPeelChoicesHelper t (h::ret) exclude_last\n            end\n  end.\n\nDefinition FilterISAPeelChoices\n  (l : list ((list ISAEdge) * option ISAPattern))\n  (exclude_last : bool)\n  : list ((list ISAEdge) * option ISAPattern) :=\n  FilterISAPeelChoicesHelper l [] exclude_last.\n\nFixpoint FilterReqEdges\n  (uops : list Microop)\n  (l : list GraphEdge)\n  : list GraphEdge :=\n  match l with\n  | [] => []\n  | h::t => \n      match h with\n      | ((src, loc1), (dest, loc2), _, _) =>\n            if find (beq_uop src) uops then\n              if find (beq_uop dest) uops then\n                h::(FilterReqEdges uops t)\n              else\n                FilterReqEdges uops t\n            else\n              FilterReqEdges uops t\n      end\n  end.\n\n(* Extracted to a function in BackendLinux.ml. *)\nDefinition IsFilterStrat (n : nat) := false.\n\nFixpoint TCInductiveCaseRunOne\n  (m n : nat)\n  (path : list (nat * nat * option (list (list ISAEdge))))\n  (remain : option ISAPattern)\n  (amti : FOLFormula * FOLFormula * FOLFormula * FOLFormula)\n  (stage_names : list (list string))\n  (locations : list nat)\n  (chain : list (list ISAEdge))\n  (a : Microop)\n  (uop_chain : list Microop)\n  (req_edges : list GraphEdge)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : option (list (list ISAEdge)) :=\n  match m with\n  | S m' =>\n    let '(axioms, mapping, theory, inv) := amti in\n    match remain with\n    | None => Warning None [\"An empty remaining pattern passed to TCInductiveCaseRunOne?\"]\n    | Some pat =>\n        let s := (mkFOLState [] [] [] [] [] [] [] (a::uop_chain) [] [] []) in\n        let s := Printf s (StringOf [newline; \"//TCInductiveCaseRunOne (g_fold) start, depth \"; stringOfNat n; \";\"; newline]) in\n        let s := Comment s ([\"Remaining ISA pattern is: \"] ++ (PrintISAPattern pat)) in\n        let s := Comment s ([\"Current Path is: \"] ++ (Map StringOfPiProofState (rev path))) in\n        let s := Comment s [\"Current instructions are:\"] in\n        let s := PrintMicroopChain s (a::uop_chain) in\n        let chain := Comment chain ([\"ISA chain is \"] ++ (PrintISAChain chain)) in\n        let poss_b' := StartChain uop_chain in\n        let poss_c := EndChain uop_chain in\n        match (poss_b', poss_c) with\n        | (Some b', Some c) =>\n            let amti_tree := CreateAMTITree s amti stage_names in\n            let layers := CreateLayersTree false chain uop_chain in\n            let property := ScenarioNotEdgeLeaf (AllConnections a c locations locations) in\n            let tran_conns := AllConnections a b' locations locations in\n            let tran_conns := Comment tran_conns [\"There are \"; stringOfNat (List.length tran_conns);\n                                \" possible transitive connections.\"] in\n            let req_edges_tree := fold_left (FoldFlipEdge false) req_edges ScenarioFalse in\n            let filter_tree := ScenarioAnd amti_tree layers in\n            let (filt_strat_1, filt_strat_2) :=\n              if IsFilterStrat 0 then\n                let res := Comment (FilterOnly, FilterOnly) [\"Strat was 0\"] in res\n              else if IsFilterStrat 1 then\n                let res := Comment (DoNothing, FilterOnly) [\"Strat was 1\"] in res\n              else if IsFilterStrat 2 then\n                let res := Comment (DoNothing, FilterAndCover) [\"Strat was 2\"] in res\n              else\n                let res := Comment (FilterAndCover, FilterAndCover) [\"Strat was 3\"] in res\n            in\n            let tran_conns_filt := FilterTranConns filt_strat_1 tran_conns s filter_tree req_edges_tree stage_names in\n            let (chain, uop_chain) := ReplaceWithInvariants chain uop_chain inv_patterns in\n            let s := (mkFOLState [] [] [] [] [] [] [] (a::uop_chain) [] [] []) in\n            let chain := Comment chain ([\"New ISA chain is \"] ++ (PrintISAChain chain)) in\n            let uop_chain := Comment uop_chain [\"New instructions are:\"] in\n            let s := PrintMicroopChain s (a::uop_chain) in\n            let amti_tree := CreateAMTITree s amti stage_names in\n            let layers := CreateLayersTree false chain uop_chain in\n            let filter_tree := ScenarioAnd amti_tree layers in\n            let req_edges := FilterReqEdges (a::uop_chain) req_edges in\n            let req_edges_tree := fold_left (FoldFlipEdge false) req_edges ScenarioFalse in\n            let f x :=\n              match x with\n              | ConnSet x' _ => x'\n              end\n            in\n            let tran_conns :=\n              match (filt_strat_1, filt_strat_2) with\n              | (FilterOnly, CoverOnly) => Map f tran_conns_filt (* the covered sets will be empty because no covering was done - see FilterTranConns *)\n              | _ => tran_conns\n              end\n            in\n            let tran_conns_inv := FilterTranConns filt_strat_2 tran_conns s filter_tree req_edges_tree stage_names in\n            let tran_conns :=\n              match (filt_strat_1, filt_strat_2) with\n              | (FilterAndCover, FilterAndCover) =>\n                  if orb (negb (SubsetOf (Map f tran_conns_filt) (Map f tran_conns_inv))) (negb (SubsetOf (Map f tran_conns_inv) (Map f tran_conns_filt))) then\n                    Warning tran_conns_inv [\"Filtered transitive connections did NOT match for inv and non-inv versions!\"]\n                  else\n                    Comment tran_conns_inv [\"Filtered transitive connections matched for inv and non-inv versions!\"]\n              | _ => tran_conns_inv\n              end\n            in\n            let tran_conns := Comment tran_conns [\"After filtering, there are \"; stringOfNat (List.length tran_conns);\n                                \" possible transitive connections.\"] in\n            let tran_conns := Comment tran_conns [\"Recursing over all those transitive connections...\"] in\n            let partial_tree := ScenarioAnd (ScenarioAnd amti_tree layers) property in\n            (* Get peeling choices. *)\n            let isa_choices := FilterISAPeelChoices (GetFinalEdge 100 pat) true in\n            let isa_choices := FilterNextChoices false chain isa_choices inv_patterns [] in\n            let g_fold (prev : option (list (list ISAEdge)) * nat * nat) (covset : CoverSet) :=\n              let (conn, covered) :=\n                match covset with\n                | ConnSet conn' covered' => (conn', covered')\n                end\n              in\n              let '(prev_soln, cur_index, num_choices) := prev in\n              let path := ((cur_index, num_choices, Some chain)::path) in\n              let s := Comment s ([\"Checking Path: \"] ++ (Map StringOfPiProofState (rev path))) in\n              match prev_soln with\n              | Some s' => (prev_soln, S cur_index, num_choices) (* Return the existing soln... *)\n              | None =>\n                  let cur_tree := ScenarioAnd partial_tree (ScenarioEdgeLeaf [conn]) in\n                  let cur_tree := Printf cur_tree (StringOf [\"//Adding edge \"; GraphvizStringOfGraphEdge [] \"\" conn]) in\n                  match FOL_DPLL 1000 [] req_edges [] stage_names s cur_tree (DefaultStrat) with\n                  | None => Comment (None, S cur_index, num_choices) [\"TCInductiveCaseRunOne depth \"; stringOfNat n; \" returned UNSAT!\"]\n                  | Some s' =>\n                      let partial_tree := Comment partial_tree [\"Abstract counterexample found; \";\n                        \"TCInductiveCaseRunOne depth \"; stringOfNat n; \" returned SAT!\"] in\n                      let concr_choices := GetSingleEdgeChoices pat in\n                      let concr_tree := ScenarioAnd partial_tree (ISAEdgeDisjunction a b' concr_choices) in\n                      let req_edges := PrintTimestamp req_edges \"Concr_start\" in\n                      match FOL_DPLL 1000 [] req_edges [] stage_names s concr_tree (HasDepStrat true) with\n                      | Some s' => Comment (Some (ConvertToISAChain (a::uop_chain) s'), S cur_index, num_choices) [\"Concretized with \"; stringOfNat n; \" instrs!\"]\n                      | None => let req_edges := Comment req_edges [\"Could not concretize with \"; stringOfNat n; \" instrs. Peeling off layer.\"] in\n                          (* Now we peel off a layer and repeat the process. *)\n                          (* First, add the current transitive connection to the required edges. *)\n                          let req_edges := PrintTimestamp req_edges \"Concr_end\" in\n                          let req_edges := (conn::req_edges) in\n                          (* Now create the new uop and add it to the chain. *)\n                          let uop_b'' := mkMicroop n 0 0 0 (Fence []) in\n                          let uop_chain := (uop_b''::uop_chain) in\n                          (* And now call the solver once for each possible ISA-level edge that we could be\n                             peeling off the chain. *)\n                          let h_fold (prev_soln' : option (list (list ISAEdge))) (choice : list ISAEdge * option ISAPattern) :=\n                            match prev_soln' with\n                            | Some _ => prev_soln'\n                            | None => \n                                let (edges', remain') := choice in\n                                  (TCInductiveCaseRunOne m' (S n) path remain' amti stage_names locations (edges'::chain) a uop_chain req_edges inv_patterns)\n                            end\n                          in\n                          (fold_left h_fold isa_choices None, S cur_index, num_choices)\n                      end\n                  end\n              end\n            in\n            fst (fst (fold_left g_fold tran_conns (None, 1, List.length tran_conns)))\n        | _ => Warning None [\"Couldn't pull start/end of chain?\"]\n        end\n    end\n  | O => Warning None [\"Recursed too deep in transitive chain case!\"]\n  end.\n\nFixpoint TCInductiveCase\n  (n : nat)\n  (amti : FOLFormula * FOLFormula * FOLFormula * FOLFormula)\n  (stage_names : list (list string))\n  (locations : list nat)\n  (a : Microop)\n  (b : Microop)\n  (c : Microop)\n  (pats : list ISAPattern)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : option (list (list ISAEdge)) :=\n  match pats with\n  | [] => None\n  | h::t => let h := Comment h ([\"Checking TC for ISA pattern: \"] ++ (PrintISAPattern h)) in\n            let fold_choices := FilterISAPeelChoices (GetInitialEdge false 100 h) true in\n            let k_fold (prev_soln : option (list (list ISAEdge))) (choice : list ISAEdge * option ISAPattern) :=\n              match prev_soln with\n              | Some _ => prev_soln\n              | None => \n                  let (edges, left) := choice in\n                  TCInductiveCaseRunOne 100 n [] left amti stage_names locations [edges] a [b; c] [] inv_patterns\n              end\n            in\n            match fold_left k_fold fold_choices None with\n            | None =>\n                let n := Comment n [\"Passed Transitive Chain Inductive Case for an ISA pattern.\"] in\n                TCInductiveCase n amti stage_names locations a b c t inv_patterns\n            | Some s => Comment (Some s) [\"Transitive Chain Inductive Case found a counterexample for an ISA pattern; returning.\"]\n            end\n  end.\n\nFixpoint SplitInvariantsHelper\n  (invs : list FOLStatement)\n  (inv_list : list FOLStatement)\n  (other_list : list FOLStatement)\n  : list (list FOLStatement) :=\n  match invs with\n  | [] => let f x := (x::other_list) in\n          Map f inv_list\n  | h::t => match h with\n            | FOLAxiom _ => SplitInvariantsHelper t (h::inv_list) other_list\n            | FOLMacroDefinition _ => SplitInvariantsHelper t inv_list (h::other_list)\n            | FOLContextTerm _ => SplitInvariantsHelper t inv_list (h::other_list)\n            end\n  end.\n\nDefinition SplitInvariants\n  (invs : list FOLStatement)\n  : list (list FOLStatement) :=\n  SplitInvariantsHelper invs [] [].\n\nFixpoint CreateInvProperty\n  (pq : bool) (* Are we inside the quantifiers that need replacing? *)\n  (uop_a : Microop) (* First microop of pair *)\n  (uop_b : Microop) (* Second microop of pair *)\n  (inv_name : string)\n  (inv : FOLFormula)\n  : FOLFormula :=\n  match inv with\n  (* The main implication. At present there can only be one of these in the invariant.\n     i.e. You can only have HasDependency po+ i j => <something not containing HasDep po+>. *)\n  | FOLOr (FOLNot a) b => match a with\n                          | FOLPredicate (PredHasDependency s _ _) =>\n                              if beq_string s inv_name then\n                                (* Drop the dependency *)\n                                Comment b [\"Found invariant property!\"]\n                              else FOLOr\n                                    (FOLNot (CreateInvProperty pq uop_a uop_b inv_name a))\n                                    (CreateInvProperty pq uop_a uop_b inv_name b)\n                          | _ => FOLOr\n                                  (FOLNot (CreateInvProperty pq uop_a uop_b inv_name a))\n                                  (CreateInvProperty pq uop_a uop_b inv_name b)\n                          end\n  | FOLName n f => FOLName n (CreateInvProperty pq uop_a uop_b inv_name f)\n  | FOLExpandMacro _ _ => inv\n  | FOLPredicate _ => inv\n  | FOLNot f => FOLNot (CreateInvProperty pq uop_a uop_b inv_name f)\n  | FOLOr a b => FOLOr (CreateInvProperty pq uop_a uop_b inv_name a) (CreateInvProperty pq uop_a uop_b inv_name b)\n  | FOLAnd a b => FOLAnd (CreateInvProperty pq uop_a uop_b inv_name a) (CreateInvProperty pq uop_a uop_b inv_name b)\n  (* Replace the first 2 microop quantifiers with just the single pair of uops that we want to check. *)\n  | FOLForAll q f =>\n      if pq then\n        (* Quantifiers have already been replaced, move along. *)\n        FOLForAll q (CreateInvProperty pq uop_a uop_b inv_name f)\n      else\n        match f with\n        | FOLForAll q' f' =>\n            (* Replace quantifiers and continue. *)\n            (* A dummy FOL state... *)\n            let s := (mkFOLState [] [] [] [] [] [] [] [] [] [] []) in\n            let name_a := fst (q s []) in\n            let name_b := fst (q' s []) in\n            let quant_a := DummyQuantifier name_a uop_a in\n            let quant_b := DummyQuantifier name_b uop_b in\n            let quant_b := Comment quant_b [\"Found quantifiers to replace...\"] in\n              FOLForAll quant_a (FOLForAll quant_b (CreateInvProperty true uop_a uop_b inv_name f'))\n        | _ => (* We haven't yet found our quantifiers to replace. *)\n          FOLForAll q (CreateInvProperty pq uop_a uop_b inv_name f)\n        end\n  | FOLExists q f => FOLForAll q (CreateInvProperty pq uop_a uop_b inv_name f)\n  | FOLLet t f => FOLLet t (CreateInvProperty pq uop_a uop_b inv_name f)\n  end.\n\nFixpoint GetInvEdge\n  (inv : FOLFormula)\n  : option ISAEdge :=\n  match inv with\n  (* The main implication. At present there can only be one of these in the invariant.\n     i.e. You can only have HasDependency po+ i j => <something not containing HasDep po+>. *)\n  | FOLOr (FOLNot a) b => match a with\n                          | FOLPredicate (PredHasDependency s _ _) =>\n                              Some (GetISAEdge s)\n                          | _ => Warning None [\"Implication\"]\n                          end\n  | FOLName n f => GetInvEdge f\n  | FOLExpandMacro _ _ => Warning None [\"Macro\"]\n  | FOLPredicate _ => None\n  | FOLNot f => GetInvEdge f\n  | FOLOr a b\n  | FOLAnd a b => \n      match (GetInvEdge a, GetInvEdge b) with\n      | (Some e1, Some e2) => Warning (Some e1) [\"Found an edge on both branches?\"]\n      | (Some e1, None) => Some e1\n      | (None, Some e2) => Some e2\n      | _ => Warning None [\"And/or\"]\n      end\n  | FOLForAll q f\n  | FOLExists q f =>\n      GetInvEdge f\n  | FOLLet t f => GetInvEdge f\n  end.\n\nFixpoint FindInv\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  (inv : FOLFormula)\n  : option (ISAPattern * ISAEdge) :=\n  let inv_patterns := Comment inv_patterns [stringOfFOLFormula 100 inv] in\n  match inv_patterns with\n  | [] => None\n  | h::t =>\n      let (pat, edge) := h in\n      match GetInvEdge inv with\n      | None => Warning None [\"Could not find inv edge!\"]\n      | Some inv_edge => if beq_isa_edge edge inv_edge then Some h else FindInv t inv\n      end\n  end.\n\nFixpoint GetPatternCases\n  (n : nat)\n  (pat : option ISAPattern)\n  (existing : list (list ISAEdge))\n  : list (list (list ISAEdge)) :=\n  let f n'' x := \n    match x with\n    | (y, z) => GetPatternCases n'' z (existing ++ [y])\n    end\n  in\n  match n with\n  | O => Warning [] [\"Recursed too far in GetPatternCases!\"]\n  | S n' =>\n      match pat with\n      | None => [existing]\n      | Some pat' =>\n          let choices := GetInitialEdge false 100 pat' in\n          let choices := Map (f n') choices in\n          fold_left app_tail choices []\n      end\n  end.\n\nFixpoint GenUops\n  (size : nat)\n  : list Microop :=\n  match size with\n  | O => []\n  | S n => (mkMicroop n 0 0 0 (Fence []))::(GenUops n)\n  end.\n\nDefinition ProveInvBaseCase\n  (m : Microarchitecture)\n  (amti : FOLFormula * FOLFormula * FOLFormula * FOLFormula)\n  (inv : FOLFormula)\n  (inv_edge : ISAEdge)\n  (chain : list (list ISAEdge))\n  : bool :=\n  (* Generate n+1 uops for the n edges... *)\n  let uops := GenUops (S (List.length chain)) in\n  (* Create the base case's chain... *)\n  let layers_tree := CreateLayersTree false chain uops in\n  let poss_uop_a := StartChain uops in\n  let poss_uop_b := EndChain uops in\n  match (poss_uop_a, poss_uop_b) with\n  | (Some uop_a, Some uop_b) =>\n      (* Create the invariant property that must be true for the invified abstraction (like po+). *)\n      let inv_prop := CreateInvProperty false uop_a uop_b (GetISAEdgeString inv_edge) inv in\n      (* A FOL state... *)\n      let s := (mkFOLState [] [] [] [] [] [] [] uops [] [] []) in\n      let amti_tree := CreateAMTITree s amti (StageNames m) in\n      let inv_prop_tree := EliminateQuantifiers true true (StageNames m) s inv_prop [] in\n      let inv_prop_tree := NegateScenarioTree inv_prop_tree in\n      let amti_tree := ScenarioTreeEdgeCountGraph 5 amti_tree \"amti\" in\n      let inv_prop_tree := ScenarioTreeEdgeCountGraph 5 inv_prop_tree \"neg_inv_prop_tree\" in\n      let layers_tree := ScenarioTreeEdgeCountGraph 5 layers_tree \"layers_tree\" in\n      let final_tree := ScenarioAnd (ScenarioAnd amti_tree inv_prop_tree) layers_tree in\n      let final_tree := Comment final_tree [\"Checking Invariant Base Case:\"] in\n      let result := FOL_DPLL 1000 [] [] [] (StageNames m) s final_tree DefaultStrat in\n      match result with\n      | Some s' => Warning false [\"Invariant base case could not be proven!\"]\n      | None => let result := Comment true [\"Inv base case for \"; PrintISAEdge inv_edge; \" passed!\"] in result\n      end\n  | _ => Warning false [\"Could not find start or end of chain when proving Inv base case!\"]\n  end.\n\nDefinition ProveInvIndCase\n  (m : Microarchitecture)\n  (amti : FOLFormula * FOLFormula * FOLFormula * FOLFormula)\n  (inv : FOLFormula)\n  (inv_edge : ISAEdge)\n  (chain : list (list ISAEdge))\n  : bool :=\n  (* Generate n+1 uops for the n edges... *)\n  let chain_len := S (List.length chain) in\n  let uops := GenUops chain_len in\n  (* And now the last uop for the inv edge from the IH. *)\n  let uop_c := mkMicroop (S chain_len) 0 0 0 (Fence []) in\n  (* Create the chain... *)\n  let layers_tree := CreateLayersTree false chain uops in\n  let poss_uop_a := StartChain uops in\n  let poss_uop_b := EndChain uops in\n  let uops := app_tail uops [uop_c] in\n  match (poss_uop_a, poss_uop_b) with\n  | (Some uop_a, Some uop_b) =>\n      (* And the property that must hold, this time between a and c... *)\n      let inv_prop := CreateInvProperty false uop_a uop_c (GetISAEdgeString inv_edge) inv in\n      (* And the FOL state...*)\n      let s := (mkFOLState [] [] [] [] [] [] [] uops [] [] []) in\n      let amti_tree := CreateAMTITree s amti (StageNames m) in\n      let inv_tree := EliminateQuantifiers true true (StageNames m) s inv [] in\n      let inv_prop_tree := EliminateQuantifiers true true (StageNames m) s inv_prop [] in\n      let inv_prop_tree := NegateScenarioTree inv_prop_tree in\n      let concr_prop_tree := ScenarioAnd layers_tree\n        (ScenarioPred (SymPredHasDependency uop_b uop_c inv_edge))\n      in\n      let amti_tree := ScenarioTreeEdgeCountGraph 5 amti_tree \"amti\" in\n      let inv_tree := ScenarioTreeEdgeCountGraph 5 inv_tree \"inv_tree\" in\n      let inv_prop_tree := ScenarioTreeEdgeCountGraph 5 inv_prop_tree \"neg_inv_prop_tree\" in\n      let concr_prop_tree := ScenarioTreeEdgeCountGraph 5 concr_prop_tree \"concr_prop_tree\" in\n      let final_tree := ScenarioAnd (ScenarioAnd (ScenarioAnd amti_tree inv_tree)\n                          inv_prop_tree) concr_prop_tree in\n      let final_tree := Comment final_tree [\"Checking Invariant Inductive Case:\"] in\n      let result := FOL_DPLL 1000 [] [] [] (StageNames m) s final_tree DefaultStrat in\n      match result with\n      | None => Comment true [\"Hooray! Invariant passed!\"]\n      | _ => Comment false [\"Invariant inductive case failed!\"]\n      end\n  | _ => Warning false [\"Could not find start or end of chain when proving Inv inductive case!\"]\n  end.\n\nDefinition ProveInvariant\n  (m : Microarchitecture)\n  (amt : FOLFormula * FOLFormula * FOLFormula)\n  (other_invs : FOLFormula)\n  (inv : FOLFormula)\n  : bool :=\n  let amti := (amt, other_invs) in\n  match FindInv InvPatterns inv with\n  | None => Warning false [\"Could not find invariant!\"]\n  | Some (pat, inv_edge) =>\n      let pat := Comment pat [\"Found invariant for \"; PrintISAEdge inv_edge] in\n      let base_cases := GetPatternCases 100 (Some pat) [] in\n      let base_results := Map (ProveInvBaseCase m amti inv inv_edge) base_cases in\n      if fold_left andb base_results true then\n        (* Ok, now the inductive case. *)\n        let ind_results := Map (ProveInvIndCase m amti inv inv_edge) base_cases in\n        let result := fold_left andb ind_results true in\n        let result := Comment result [\"Inductive case for invariant \"; PrintISAEdge inv_edge; \" returned \"; (if result then \"true\" else \"false\")] in\n        result\n      else\n        Warning false [\"Could not prove invariant for \"; PrintISAEdge inv_edge]\n  end.\n\nDefinition FoldInvs\n  (l : list FOLFormula)\n  : FOLFormula :=\n  let f x y := FOLAnd x y in\n  fold_left f l (FOLPredicate PredTrue).\n\nFixpoint ProveInvariantsHelper\n  (n : nat)\n  (m : Microarchitecture)\n  (amt : FOLFormula * FOLFormula * FOLFormula)\n  (invs : list FOLFormula)\n  : bool :=\n  match n with\n  | O => true\n  | S n' => match invs with\n            | [] => Warning false [\"nonzero invariants but empty list?\"]\n            | h::t => if ProveInvariant m amt (FoldInvs t) h then ProveInvariantsHelper n' m amt (t ++ [h]) else false\n            end\n  end.\n\nDefinition ProveInvariants\n  (m : Microarchitecture)\n  (amt : FOLFormula * FOLFormula * FOLFormula)\n  (invs : list FOLStatement)\n  : bool :=\n  let invs := SplitInvariants invs in\n  let invs := Map (fun x => [x]) invs in\n  let invs := Map BuildMicroarchitecture invs in\n  ProveInvariantsHelper (List.length invs) m amt invs.\n\nFixpoint GenISAEdgeTree\n  (a : Microop)\n  (b : Microop)\n  (edges : list ISAEdge)\n  : ScenarioTree :=\n  match edges with\n  | [] => ScenarioTrue\n  | h::t => ScenarioAnd (ScenarioPred (SymPredHasDependency a b h)) (GenISAEdgeTree a b t)\n  end.\n\nDefinition ISAChainFold\n  (ret : ScenarioTree * list Microop * nat)\n  (isa_edges : list ISAEdge)\n  : ScenarioTree * list Microop * nat :=\n  let '(tree, uops, gid) := ret in\n  let last_uop := EndChain uops in\n  match last_uop with\n  | None => Warning (tree, uops, gid) [\"No last uop in the chain?\"]\n  | Some last_uop' =>\n      let new_uop := mkMicroop gid 0 0 0 (Fence []) in\n      (ScenarioAnd tree (GenISAEdgeTree last_uop' new_uop isa_edges), (app_tail uops [new_uop]), S gid)\n  end.\n\nDefinition FoldMicroopChain\n  (ret : ScenarioTree * Microop)\n  (cur_uop : Microop)\n  : ScenarioTree * Microop :=\n  let (tree, prev_uop) := ret in\n  (ScenarioAnd tree (ISAEdgeInvifiedDisjunction prev_uop cur_uop), cur_uop).\n\nDefinition FoldMaxGid\n  (n : nat)\n  (a : Microop)\n  : nat :=\n  if (blt_nat n (globalID a)) then (globalID a) else n.\n\nDefinition GenCex\n  (amti : FOLFormula * FOLFormula * FOLFormula * FOLFormula)\n  (stage_names : list (list string))\n  (left_uops : list Microop)\n  (right_uops : list Microop)\n  (tc_cex : list (list ISAEdge))\n  : option (list (list ISAEdge)) :=\n  let left_tree :=\n    match left_uops with\n    | [] => ScenarioTrue\n    | h::t => fst (fold_left FoldMicroopChain t (ScenarioTrue, h))\n    end\n  in\n  let right_tree :=\n    match right_uops with\n    | [] => ScenarioTrue\n    | h::t => fst (fold_left FoldMicroopChain t (ScenarioTrue, h))\n    end\n  in\n  let (mid_tree, all_uops) :=\n    match (rev tc_cex) with\n    | [] => (* There is no tran chain. If there are left and right components, add an ISAEdgeInvifiedDisjunction\n               between them and move along. *)\n            match (EndChain left_uops, StartChain right_uops) with\n            | (Some cs, Some ce) => (ISAEdgeInvifiedDisjunction cs ce, app_tail left_uops right_uops)\n            | _ => (ScenarioTrue, app_tail left_uops right_uops)\n            end\n    | h::t => (* The final i.e. \"h\" case needs to be handled manually. Rev back the t and pass it to the\n                 fold below. *)\n        let max_gid := fold_left FoldMaxGid left_uops 0 in\n        let max_gid := fold_left FoldMaxGid right_uops max_gid in\n        let max_gid := S max_gid in\n        let (left_uops, chain_start) :=\n          match EndChain left_uops with\n          | None => let uop := (mkMicroop max_gid 0 0 0 (Fence [])) in\n                      Comment ([uop], uop) [\"No instrs in the left chain\"]\n          | Some cs => (left_uops, cs)\n          end\n        in\n        (* Increment by one if we had to create a uop... *)\n        let max_gid := if beq_nat max_gid (globalID chain_start) then S max_gid else max_gid in\n        let (right_uops, chain_end) :=\n          match StartChain right_uops with\n          | None => let uop := (mkMicroop max_gid 0 0 0 (Fence [])) in\n                      Comment ([uop], uop) [\"No instrs in the right chain\"]\n          | Some ce => (right_uops, ce)\n          end\n        in\n        let max_gid := if beq_nat max_gid (globalID chain_end) then S max_gid else max_gid in\n        let '(tc_cex_tree, tc_cex_uops, _) := fold_left ISAChainFold (rev t) (ScenarioTrue, [chain_start], max_gid) in\n        let tc_cex_uops :=\n          match tc_cex_uops with\n          | [] => Warning [] [\"tc_cex_uops is empty?\"]\n          | h::t => t (* Drop chain_start from the beginning as it's already in left_uops, one way or another... *)\n          end\n        in\n        let last_gen_uop :=\n          match EndChain tc_cex_uops with\n          | None => chain_start (* There was only one edge in the chain i.e. t was empty. Just add the edge between chain_start and chain_end. *)\n          | Some e => e\n          end\n        in\n        let tc_cex_tree := ScenarioAnd tc_cex_tree (GenISAEdgeTree last_gen_uop chain_end h) in\n        (tc_cex_tree, app_tail (app_tail left_uops tc_cex_uops) right_uops)\n    end\n  in\n  match (StartChain all_uops, EndChain all_uops) with\n  | (Some dest, Some src) =>\n      let total_tree := ScenarioAnd (ScenarioAnd (ScenarioAnd\n                          (left_tree) (right_tree)) (mid_tree))\n                          (ISAEdgeInvifiedDisjunction src dest)\n      in\n      (* Now, finally, pass this to the solver. *)\n      let s := (mkFOLState [] [] [] [] [] [] [] all_uops [] [] []) in\n      let amti_tree := CreateAMTITree s amti stage_names in\n      let final_tree := ScenarioAnd amti_tree total_tree in\n      let final_tree := Comment final_tree [\"Checking candidate counterexample\"] in\n      match FOL_DPLL 1000 [] [] [] stage_names s final_tree DefaultStrat with\n      | None => None (* This isn't the cex we're looking for. *)\n      | Some s' => (* Hooray! We have our cex. *)\n          Some (ConvertToISAChain (all_uops ++ [dest]) s')\n      end\n  | _ => Warning None [\"No uops in all_uops?\"]\n  end.\n\nFixpoint GenCex2\n  (steps_left : nat)\n  (amti : FOLFormula * FOLFormula * FOLFormula * FOLFormula)\n  (stage_names : list (list string))\n  (chain : list (list ISAEdge))\n  (pat : option ISAPattern)\n  : option (list (list ISAEdge)) :=\n  let f n'' x :=\n    match x with\n    | (y, z) => GenCex2 n'' amti stage_names (app_tail chain [y]) z\n    end\n  in\n  let g x y :=\n    match x with\n    | Some _ => x\n    | None => y\n    end\n  in\n  match steps_left with\n  | O => \n      (* We've added as much as we're supposed to. Now let's add the loopback edge and be done with it. *)\n      match pat with\n      | None => None (* We're out of axiom. *)\n      | Some pat' =>\n          let loops := GetSingleEdgeChoices pat' in\n          (* Create the uops we need. *)\n          let uops := GenUops (S (List.length chain)) in\n          let poss_cycle_start := EndChain uops in\n          let poss_cycle_end := StartChain uops in\n          match (poss_cycle_start, poss_cycle_end) with\n          | (Some cycle_start, Some cycle_end) =>\n              let s := (mkFOLState [] [] [] [] [] [] [] uops [] [] []) in\n              let amti_tree := CreateAMTITree s amti stage_names in\n              let layers_tree := CreateLayersTree false chain uops in\n              (* Now try all possibilities for the loopback edge. *)\n              let l_fold (prev_soln : option (list (list ISAEdge))) (loop_edges : list ISAEdge) :=\n                match prev_soln with\n                | Some _ => prev_soln\n                | None => let cex_tree := ScenarioAnd (ScenarioAnd amti_tree layers_tree) (ISAEdgeDisjunction cycle_start cycle_end [loop_edges]) in\n                          match FOL_DPLL 1000 [] [] [] stage_names s cex_tree DefaultStrat with\n                          | None => None\n                          | Some s' => Some (ConvertToISAChain (app_tail uops [cycle_end]) s')\n                          end\n                end\n              in\n              fold_left l_fold loops None\n          | _ => Warning None [\"Created uops but couldn't get start/end of chain?\"]\n          end\n      end\n  | S n' =>\n      match pat with\n      | None => None (* We ran out of steps. *)\n      | Some pat' =>\n          (* Generate all possible next steps in the cycle. *)\n          let choices := GetInitialEdge false 100 pat' in\n          let results := Map (f n') choices in\n          fold_left g results None\n      end\n  end.\n\n(* Extracted to a function in BackendLinux.ml. *)\nDefinition LowerThanBound (n : nat) := false.\n\nFixpoint FindCex\n  (n : nat)\n  (pat : ISAPattern)\n  (amti : FOLFormula * FOLFormula * FOLFormula * FOLFormula)\n  (stage_names : list (list string))\n  (cur_size : nat)\n  : option (list (list ISAEdge)) :=\n  match n with\n  | S n' =>\n      if LowerThanBound cur_size then\n        let amti := Comment amti [\"Checking for cycle cex of size \"; stringOfNat (S cur_size)] in\n        match GenCex2 cur_size amti stage_names [] (Some pat) with\n        | None => FindCex n' pat amti stage_names (S cur_size)\n        | Some cex => Some cex\n        end\n      else\n        None\n  | _ => Warning None [\"Recursed too deep in FindCex.\"]\n  end.\n\nDefinition Invariantify\n  (e : ISAEdge)\n  : ISAEdge :=\n  match e with\n  | EdgePO => EdgePO_plus\n  | _ => e\n  end.\n\nDefinition FoldEdgeChoices\n  (edges : list ISAEdge)\n  (new_choices : list (list ISAEdge))\n  (choice : list ISAEdge)\n  : list (list ISAEdge) :=\n  app_tail new_choices (Map (fun x => (x::choice)) edges).\n\nFixpoint GenAdditionsList\n  (depth : nat)\n  (edges : list ISAEdge)\n  (additions : list (list ISAEdge))\n  : list (list ISAEdge) :=\n  match depth with\n  | O => additions\n  | S n' =>\n      let additions :=\n        match edges with\n        | [] => Warning additions [\"Could not find any edges to add to the choices!\"]\n        | _ => fold_left (FoldEdgeChoices edges) additions []\n        end\n      in\n      GenAdditionsList n' edges additions\n  end.\n\nFixpoint GenCexGrow\n  (max_depth : nat)\n  (cur_depth : nat) (* number of edges in a choice - 1 *)\n  (amti : FOLFormula * FOLFormula * FOLFormula * FOLFormula)\n  (stage_names : list (list string))\n  (chain : list (list ISAEdge))\n  (remnants : list (option ISAPattern))\n  : list (list ISAEdge) :=\n  let f x y :=\n    match x with\n    | Some _ => x\n    | None => y\n    end\n  in\n  match max_depth with\n  | O => Warning [] [\"Could not concretize TC Cex!\"]\n  | S n' =>\n      let results := Map (GenCex2 cur_depth amti stage_names chain) remnants in\n      match fold_left f results None with\n      | None =>\n          (* Try again with a higher depth. *)\n          GenCexGrow n' (S cur_depth) amti stage_names chain remnants\n      | Some s => s\n      end\n  end.\n\nFixpoint GetRemainingPatterns\n  (pat : option ISAPattern)\n  (l : list (list ISAEdge))\n  : list (option ISAPattern) :=\n  let f x y z :=\n    match z with\n    | (a, b) =>\n        let a := Comment a ([\"Checking \"] ++ (PrintISAChain [a]) ++ [\" against \"] ++ (PrintISAChain [x])) in\n        let invified := InvariantifyChain [a] in\n        match invified with\n        | [a'] =>\n            if orb (ISASubsetOf a x) (ISASubsetOf a' x) then GetRemainingPatterns b y else []\n        | _ => Warning [] [\"Non-single-element list when invariantifying to get remaining patterns...\"]\n        end\n    end\n  in\n  match l with\n  | [] => [pat]\n  | h::t =>\n      match pat with\n      | None => []\n      | Some pat' =>\n          let pat' := Comment pat' ([\"pat' is \"] ++ (PrintISAPattern pat')) in\n          let choices := FilterISAPeelChoices (GetInitialEdge false 100 pat') false in\n          let results := Map (f h t) choices in\n          fold_left app_tail results []\n      end\n  end.\n\n(* Extracted to a function in BackendLinux.ml. *)\nDefinition DoGenCex (b : bool) := false.\n\nDefinition GenCounterexample\n  (pat : ISAPattern)\n  (amti : FOLFormula * FOLFormula * FOLFormula * FOLFormula)\n  (stage_names : list (list string))\n  (chain : list (list ISAEdge))\n  : list (list ISAEdge) :=\n  (* First, see if the user wants to search for a cyclic counterexample. *)\n  if DoGenCex true then\n    let amti := Comment amti [\"Checking for cyclic counterexamples...\"] in\n    match FindCex 100 pat amti stage_names 0 with\n    | Some cex => cex\n    | None =>\n          Warning [] [\"Could not find cyclic cex within bound\"]\n    end\n  else\n    [].\n\nDefinition BuildBaseCasePropertyTree\n  (a b : Microop)\n  (l : list nat)\n  (pat : ISAPattern)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : ScenarioTree :=\n  let init_edges := GetISAEdges (GetInitialEdge false 100 pat) in\n  let f x := \n    match fst (ReplaceWithInvariants [x] [a; b] inv_patterns) with\n    | [h] => h\n    | _ => Warning x [\"Lists are messed up in TC check base case...\"]\n    end\n  in\n  let init_edges := Map f init_edges in\n  let init_edges := Comment init_edges ([\"TC base case choices are: \"] ++ (PrintISAChain init_edges)) in\n  ScenarioAnd (ISAEdgeDisjunction a b init_edges) (ScenarioNotEdgeLeaf (AllConnections a b l l)).\n\nDefinition TransitiveChain\n  (max_depth : nat)\n  (m : Microarchitecture)\n  (pattern : ISAAxiom)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : option (list (list ISAEdge)) :=\n  match (pattern, FilterUspecInput m [] [] [] []) with\n  | (Irr pat, (axioms, mapping, theory, inv)) =>\n      let axioms := BuildMicroarchitecture [axioms] in\n      let mapping := BuildMicroarchitecture [mapping] in\n      let theory := BuildMicroarchitecture [theory] in\n      let axioms := PrintTimestamp axioms \"Inv_proof_start\" in\n      if negb (ProveInvariants m (axioms, mapping, theory) inv) then\n        let result := Some [] in\n        let result := PrintTimestamp result \"Inv_proof_end_failure\" in\n        Warning result [\"Invariants could not be proven! Aborting.\"]\n      else\n      (* Begin with the base case. 2 instructions, A and B. The params of the uop have\n         no meaning besides the global ID, since everything else will be a variable.\n         Fences are the easiest to create so I've made them both fences. *)\n      let inv := PrintTimestamp inv \"Inv_proof_end_success\" in\n      let inv := BuildMicroarchitecture [inv] in\n      let uop_a := mkMicroop 0 0 0 0 (Fence []) in\n      let uop_b := mkMicroop 1 0 0 0 (Fence []) in\n      let s := (mkFOLState [] [] [] [] [] [] [] [uop_a; uop_b] [] [] []) in\n      let locations := GetLocations m [] in\n      let property_tree := BuildBaseCasePropertyTree uop_a uop_b locations pat inv_patterns in\n      let amti := (axioms, mapping, theory, inv) in\n      let amti_tree := CreateAMTITree s amti (StageNames m) in\n      let final_tree := ScenarioAnd amti_tree property_tree in\n      let final_tree := Comment final_tree [\"Checking Transitive Chain Base Case:\"] in\n      let result := FOL_DPLL max_depth [] [] [] (StageNames m) s final_tree DefaultStrat in\n      match result with\n      | Some s' => let s' := Comment s' [\"Transitive Chain Base Case returned SAT! Failing fragment is:\"] in\n                   let fail_frag := ConvertToISAChain [uop_a; uop_b] s' in\n                   let fail_frag := Comment fail_frag (PrintISAChain fail_frag) in\n                    Some (GenCounterexample pat amti (StageNames m) fail_frag)\n      | None => let result := Comment result [\"Transitive Chain Base Case returned UNSAT\"] in\n                let result := Comment result [\"Checking Transitive Chain Inductive Case:\"] in\n                (* Now the inductive case. *)\n                (* The third instruction. *)\n                let uop_c := mkMicroop 2 0 0 0 (Fence []) in\n                (* Rip the last part off the pattern to give us all possible TCs. *)\n                let tchains := GetAllTranChains pat in\n                let tchains := Comment tchains ([\"The tranchains are: \"] ++ (PrintISAPatterns tchains)) in\n                let tchains := Comment tchains [\"Length of GetAllTranChains is \"; stringOfNat (List.length tchains)] in\n                let tchains := Map (GetAllSubchains 100 []) tchains in\n                let tchains := fold_left FoldISAChains tchains [] in\n                let tchains := Comment tchains ([\"The folded tranchains are: \"] ++ (PrintISAPatterns tchains)) in\n                let tchains := Comment tchains [\"Length of folded ISA chains is \"; stringOfNat (List.length tchains)] in\n                match TCInductiveCase 3 amti (StageNames m) locations uop_a uop_b uop_c tchains inv_patterns with\n                | Some s'' => let s'' := Comment s'' (\"TC failing fragment is \"::(PrintISAChain (rev s''))) in\n                    Comment (Some (GenCounterexample pat amti (StageNames m) s'')) [\"Transitive Chain Inductive Case returned SAT!\"]\n                | None => Comment None [\"Transitive Chain Inductive Case returned UNSAT.\"]\n                end\n      end\n  end.\n\n(* Checks if everything in l is in l'. This equates to checking if the new scenario is just a more constrained version of the older one. *)\nFixpoint ISAListCoveredBy\n  (l l' : list ISAEdge)\n  : bool :=\n  match l with\n  | [] => true\n  | h::t => if find (beq_isa_edge h) l' then ISAListCoveredBy t l' else false\n  end.\n\nFixpoint ISAEdgesMatch\n  (edges edges' : list (list ISAEdge))\n  : bool :=\n  match (edges, edges') with\n  | ([], []) => true\n  | (h::t, h'::t') => if ISAListCoveredBy h h' then ISAEdgesMatch t t' else false\n  | _ => Warning false [\"ISA cycle lengths don't match?\"]\n  end.\n\nDefinition beq_tran_conn\n  (tc tc' : GraphEdge)\n  : bool :=\n  match (tc, tc') with\n  | (((_, (_, src)), (_, (_, dest)), _, _), ((_, (_, src')), (_, (_, dest')), _, _)) =>\n      andb (beq_nat src src') (beq_nat dest dest')\n  end.\n\nDefinition ReplaceUops\n  (left_tc right_tc : Microop)\n  (e : GraphEdge)\n  : GraphEdge :=\n  match e with\n  | ((_, (_, s)), ((_, (_, d))), _, _) => ((left_tc, (coreID left_tc, s)), ((right_tc, (coreID right_tc, d))), \"\", \"\")\n  end.\n\nDefinition ConjoinNegatedTranConns\n  (left_tc right_tc : Microop)\n  (l : list GraphEdge)\n  (tree : ScenarioTree)\n  : ScenarioTree :=\n  match l with\n  | [] => tree\n  | _ => let l := Map (ReplaceUops left_tc right_tc) l in\n         ScenarioAnd tree (ScenarioNotEdgeLeaf l)\n  end.\n\nDefinition ISACycleMatch\n  (check_req_edges : bool)\n  (checked : list (list ISAEdge) * (list GraphEdge))\n  (case : list (list ISAEdge) * GraphEdge)\n  (params : FOLState * ScenarioTree * list (list string))\n  (left_tc right_tc : option Microop)\n  : bool :=\n  let (edges, conns) := checked in\n  let (edges', conn') := case in\n  (* A peephole optimization... *)\n  if beq_nat (List.length edges) (List.length edges') then\n    let edges :=\n      if PrintFlag 2 then\n        Comment edges [\"Edge lists are the same length...\"]\n      else\n        edges\n      in\n      if ISAEdgesMatch edges edges' then\n        let conns := Comment conns [\"ISA chains match:\"; newline] in\n        let conns := Comment conns ([\"ISACycle1: \"] ++ (PrintISAChain edges) ++ [newline; \"   ISACycle2: \"] ++ (PrintISAChain edges')) in\n        let conns := Comment conns [\"Conn is \"; GraphvizStringOfGraphEdge [] \"\" conn'] in\n        let conns := PrintEdgeList conns conns in\n        if check_req_edges then\n          (* Check if our current scenario is a decomposition of the case checked earlier. *)\n          match (left_tc, right_tc) with\n          | (Some left_tc', Some right_tc') =>\n              let '(s, cur_tree, stage_names) := params in\n              let cur_tree := ScenarioAnd cur_tree (ConjoinNegatedTranConns left_tc' right_tc' conns ScenarioTrue) in\n              match FOL_DPLL 1000 [] [] [] stage_names s cur_tree (DefaultStrat) with\n              | None => true\n              | Some _ => false\n              end\n          | _ => Warning false [\"No TC ends when checking req edges for memoization?\"]\n          end\n        else\n          (* Just compare the conns. *)\n          (* beq_tran_conn takes symmetry into account... *)\n          if find (beq_tran_conn conn') conns then\n            let result :=\n              if PrintFlag 2 then\n                Comment true [\"Tran conn found...\"]\n              else\n                true\n              in\n            result\n          else\n            false\n      else\n        false\n  else\n    false.\n\n\nFixpoint ISACycleInHelper\n  (check_req_edges : bool)\n  (checked_cases : list (list (list ISAEdge) * (list GraphEdge)))\n  (case : list (list ISAEdge) * GraphEdge)\n  (params : FOLState * ScenarioTree * list (list string))\n  (left_tc right_tc : option Microop)\n  : bool :=\n  match checked_cases with\n  | [] => false\n  | h::t => if ISACycleMatch check_req_edges h case params left_tc right_tc then\n              true\n            else\n              ISACycleInHelper check_req_edges t case params left_tc right_tc\n  end.\n\nDefinition Canonicalise\n  (e : ISAEdge)\n  : list (list ISAEdge) :=\n  match e with\n  | EdgeFencePO_plus => [[EdgeFence_plus]; [EdgePO_plus]]\n  | EdgePOFence_plus => [[EdgePO_plus]; [EdgeFence_plus]]\n  | EdgeFencePPO_plus => [[EdgeFence_plus]; [EdgePPO_plus]]\n  | EdgePPOFence_plus => [[EdgePPO_plus]; [EdgeFence_plus]]\n  | _ => [[e]]\n  end.\n\nFixpoint CanonicaliseChainHelper\n  (chain ret : list (list ISAEdge))\n  : list (list ISAEdge) :=\n  match chain with\n  | [] => ret\n  | h::t => match h with\n            | [edge] => CanonicaliseChainHelper t (ret ++ (Canonicalise edge))\n            | _ => Warning [] [\"Found multiple edges when trying to canonicalise chain!\"]\n            end\n  end.\n\nFixpoint MergeIdenticalInvs\n  (chain : list (list ISAEdge))\n  : list (list ISAEdge) :=\n  match chain with\n  | [] => []\n  | h::t => match t with\n            | [] => chain\n            | h'::t' =>\n                match (h, h') with\n                | ([EdgePO_plus], [EdgePO_plus])\n                | ([EdgePO_loc_plus], [EdgePO_loc_plus])\n                | ([EdgeFence_plus], [EdgeFence_plus])\n                | ([EdgePPO_plus], [EdgePPO_plus]) => h::(MergeIdenticalInvs t')\n                | _ => h::(MergeIdenticalInvs t)\n                end\n            end\n  end.\n\nDefinition CanonicaliseChain\n  (chain : list (list ISAEdge))\n  : list (list ISAEdge) :=\n  CanonicaliseChainHelper chain [].\n\n(* How many elements from either end do we toss when trying to find memoized matches? *)\n(* This function is implemented in BackendLinux.ml. *)\nDefinition BelowMemoThreshold (n : nat) := false.\n\nDefinition ISACycleInChop\n  (checked_cases : list (list (list ISAEdge) * (list GraphEdge)))\n  (chain : list (list ISAEdge))\n  (conn : GraphEdge)\n  (uops : list Microop)\n  (params : FOLState * ScenarioTree * list (list string))\n  (n : nat) (* How much to chop from the head or the tail *)\n  : bool :=\n  if bgt_nat (List.length chain) n then\n    let uops' := ChopTailNum n uops in\n    let chain' := ChopTailNum n chain in\n    (* Only check required edges if you're chopping things off the chain (i.e. checking decompositions). *)\n    if ISACycleInHelper (bgt_nat n 0) checked_cases (chain', conn) params (EndChain uops') (StartChain uops') then\n      true\n    else if bgt_nat n 0 then (* If n = 0, the chopHead and chopTail cases do the same thing, so don't check again... *)\n      let uops' := ChopHeadNum n uops in\n      let chain' := ChopHeadNum n chain in\n      ISACycleInHelper true checked_cases (chain', conn) params (EndChain uops') (StartChain uops')\n    else\n      false\n  else\n    false.\n\nFixpoint ISACycleIn\n  (m : nat)\n  (checked_cases : list (list (list ISAEdge) * (list GraphEdge)))\n  (chain : list (list ISAEdge))\n  (conn : GraphEdge)\n  (uops : list Microop)\n  (params : FOLState * ScenarioTree * list (list string))\n  (n : nat) (* How much are we chopping off this time? *)\n  : bool :=\n  match m with\n  | S m' =>\n    if BelowMemoThreshold n then\n      if ISACycleInChop checked_cases chain conn uops params n then\n        true\n      else\n        ISACycleIn m' checked_cases chain conn uops params (S n)\n    else\n      false\n  | O => Warning false [\"Recursed too far in ISACycleIn!\"]\n  end.\n\nDefinition ReverseEdge\n  (e : ISAEdge)\n  : ISAEdge :=\n  match e with\n  | EdgeFencePO_plus => EdgePOFence_plus\n  | EdgePOFence_plus => EdgeFencePO_plus\n  | EdgeFencePPO_plus => EdgePPOFence_plus\n  | EdgePPOFence_plus => EdgeFencePPO_plus\n  | _ => e\n  end.\n\nDefinition ReverseEdgeList\n  (l : list ISAEdge)\n  : list ISAEdge :=\n  Map ReverseEdge l.\n\nDefinition ReverseChain\n  (l : list (list ISAEdge))\n  : list (list ISAEdge) :=\n  let l := rev l in\n  Map ReverseEdgeList l.\n\n(* Extracted to an fn in BackendLinux.ml... *)\nDefinition UseISASym (n : nat) := false.\n\n(* TC is the loopback... *)\nFixpoint CycleCheckSolveOne\n  (m n : nat)\n  (peel_left : bool)\n  (path : list (nat * nat * option (list (list ISAEdge))))\n  (uops : list Microop)\n  (chain : list (list ISAEdge))\n  (remain : option ISAPattern)\n  (amti : FOLFormula * FOLFormula * FOLFormula * FOLFormula)\n  (stage_names : list (list string))\n  (locations : list nat)\n  (req_edges : list GraphEdge)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  (checked_cases : list (list (list ISAEdge) * (list GraphEdge)))\n  (excluded_edges : list (list ISAEdge))\n  : option (list (list ISAEdge)) * list (list (list ISAEdge) * (list GraphEdge)) :=\n  match m with\n  | S m' =>\n    match remain with\n    | Some pat =>\n    let s := (mkFOLState [] [] [] [] [] [] [] uops [] [] []) in\n    let s := Printf s (StringOf [newline; \"//CycleCheckSolveOne (g_fold) start, depth \"; stringOfNat n; \";\"; newline]) in\n    let s := Comment s ([\"Remaining ISA pattern is: \"] ++ (PrintISAPattern pat)) in\n    let s := Comment s ([\"Current Path is: \"] ++ (Map StringOfPiProofState (rev path))) in\n    let s := Comment s [\"Current instructions are:\"] in\n    let s := PrintMicroopChain s uops in\n    let s := Comment s ([\"ISA chain is \"] ++ (PrintISAChain chain)) in\n    let amti_tree := CreateAMTITree s amti stage_names in\n    let layers := CreateLayersTree false chain uops in\n    let left_tc := EndChain uops in\n    let right_tc := StartChain uops in\n    (* There is no \"property\" here, it's just whether or not you can get a SAT assignment. *)\n    match (left_tc, right_tc) with\n    | (Some left_tc', Some right_tc') =>\n        let left_tc := left_tc' in\n        let right_tc := right_tc' in\n        let tran_conns := AllConnections left_tc right_tc locations locations in\n        let tran_conns := Comment tran_conns [\"There are \"; stringOfNat (List.length tran_conns);\n                            \" possible transitive connections.\"] in\n        let req_edges_tree := fold_left (FoldFlipEdge false) req_edges ScenarioFalse in\n        let filter_tree := ScenarioAnd amti_tree layers in\n        let (filt_strat_1, filt_strat_2) :=\n          if IsFilterStrat 0 then\n            let res := Comment (FilterOnly, FilterOnly) [\"Strat was 0\"] in res\n          else if IsFilterStrat 1 then\n            let res := Comment (DoNothing, FilterOnly) [\"Strat was 1\"] in res\n          else if IsFilterStrat 2 then\n            let res := Comment (DoNothing, FilterAndCover) [\"Strat was 2\"] in res\n          else\n            let res := Comment (FilterAndCover, FilterAndCover) [\"Strat was 3\"] in res\n        in\n        let tran_conns_filt := FilterTranConns filt_strat_1 tran_conns s filter_tree req_edges_tree stage_names in\n        (* If we have an invariant that can be applied from the left and from the right, and they're mutually exclusive, we'll prefer the left. *)\n        let '(chain, uops) := ReplaceWithInvariantsOuter chain uops inv_patterns in\n        let chain := Comment chain ([\"New ISA chain is \"] ++ (PrintISAChain chain)) in\n        let s := (mkFOLState [] [] [] [] [] [] [] uops [] [] []) in\n        let s := Comment s [\"New instructions are:\"] in\n        let s := PrintMicroopChain s uops in\n        let amti_tree := CreateAMTITree s amti stage_names in\n        let layers := CreateLayersTree false chain uops in\n        let filter_tree := ScenarioAnd amti_tree layers in\n        let req_edges := FilterReqEdges uops req_edges in\n        let req_edges_tree := fold_left (FoldFlipEdge false) req_edges ScenarioFalse in\n        let f x :=\n          match x with\n          | ConnSet x' _ => x'\n          end\n        in\n        let tran_conns :=\n          match (filt_strat_1, filt_strat_2) with\n          | (FilterOnly, CoverOnly) => Map f tran_conns_filt (* the covered sets will be empty because no covering was done - see FilterTranConns *)\n          | _ => tran_conns\n          end\n        in\n        let tran_conns_inv := FilterTranConns filt_strat_2 tran_conns s filter_tree req_edges_tree stage_names in\n        let tran_conns :=\n          match (filt_strat_1, filt_strat_2) with\n          | (FilterAndCover, FilterAndCover) =>\n              if orb (negb (SubsetOf (Map f tran_conns_filt) (Map f tran_conns_inv))) (negb (SubsetOf (Map f tran_conns_inv) (Map f tran_conns_filt))) then\n                Warning tran_conns_inv [\"Filtered transitive connections did NOT match for inv and non-inv versions!\"]\n              else\n                Comment tran_conns_inv [\"Filtered transitive connections matched for inv and non-inv versions!\"]\n          | _ => tran_conns_inv\n          end\n        in\n        let tran_conns := Comment tran_conns [\"After filtering, there are \"; stringOfNat (List.length tran_conns);\n                            \" possible transitive connections.\"] in\n        let tran_conns := Comment tran_conns [\"Recursing over all those transitive connections...\"] in\n        let partial_tree := ScenarioAnd amti_tree layers in\n        (* Peeling off choices... *)\n        let isa_choices :=\n          if peel_left then\n            FilterNextChoices peel_left chain (FilterISAPeelChoices (GetInitialEdge false 100 pat) true) inv_patterns excluded_edges\n          else\n            FilterNextChoices peel_left chain (FilterISAPeelChoices (GetFinalEdge 100 pat) true) inv_patterns excluded_edges\n        in\n        let g_fold (prev : option (list (list ISAEdge)) * list (list (list ISAEdge) * (list GraphEdge)) * nat * nat) (covset : CoverSet) :=\n          let (conn, covered) :=\n            match covset with\n            | ConnSet conn' covered' => (conn', covered')\n            end\n          in\n          let '(prev_soln, checked_cases', cur_index, num_choices) := prev in\n          let path := ((cur_index, num_choices, Some chain)::path) in\n          let s := Comment s ([\"Checking Path: \"]\n            ++ (Map StringOfPiProofState (rev path))\n          ) in\n          match prev_soln with\n          | Some s' => (prev_soln, checked_cases', S cur_index, num_choices) (* Return the existing soln... *)\n          | None =>\n              let cur_tree := ScenarioAnd partial_tree (ScenarioEdgeLeaf [conn]) in\n              let cur_tree := Printf cur_tree (StringOf [\"//Adding edge \"; GraphvizStringOfGraphEdge [] \"\" conn]) in\n              (* Prepare the current case to add to our list of checked scenarios later if this branch is successfully verified. *)\n              let case_to_add := (CanonicaliseChain chain, (conn::covered)) in\n              match FOL_DPLL 1000 [] req_edges [] stage_names s cur_tree DefaultStrat with\n              | None =>\n                  Comment (None, checked_cases', S cur_index, num_choices) [\"CycleCheckSolveOne depth \"; stringOfNat n; \" returned UNSAT!\"]\n              | Some s' =>\n                  let partial_tree := Comment partial_tree [\"Abstract counterexample found; \";\n                    \"CycleCheckSolveOne depth \"; stringOfNat n; \" returned SAT!\"] in\n                  let concr_choices := GetSingleEdgeChoices pat in\n                  (* Ok, first let's try and concretize with the current number of instructions. *)\n                  let concr_tree := ScenarioAnd partial_tree (ISAEdgeDisjunction left_tc right_tc concr_choices) in\n                  let req_edges := PrintTimestamp req_edges \"concr_start\" in\n                  match FOL_DPLL 1000 [] req_edges [] stage_names s concr_tree (HasDepStrat true) with\n                  | Some s' =>\n                      match StartChain uops with\n                      | None => Warning (None, checked_cases', S cur_index, num_choices) [\"Concretized but couldn't pull the start of the uop chain?\"]\n                      | Some chain_start_uop =>\n                          Comment (Some (ConvertToISAChain (uops ++ [chain_start_uop]) s'), checked_cases',\n                            S cur_index, num_choices) [\"Concretized with \"; stringOfNat n; \" instrs!\"]\n                      end\n                  | None => let req_edges := Comment req_edges [\"Could not concretize with \"; stringOfNat n; \" instrs. Peeling off layer.\"] in\n                      (* Now we peel off a layer and repeat the process. *)\n                      (* First, add the current transitive connection to the required edges. *)\n                      let req_edges := PrintTimestamp req_edges \"concr_end\" in\n                      let req_edges := (conn::req_edges) in\n                      (* Now create the new uop and add it to the chain. *)\n                      let uop_b'' := mkMicroop n 0 0 0 (Fence []) in\n                      let uops :=\n                        if peel_left then\n                          app_tail uops [uop_b'']\n                        else\n                          (uop_b''::uops)\n                      in\n                      (* And now call the solver once for each possible ISA-level edge that we could be\n                         peeling off the chain. *)\n                      let h_fold (prev_soln' : option (list (list ISAEdge)) * list (list (list ISAEdge) * (list GraphEdge))) (choice : list ISAEdge * option ISAPattern) :=\n                        let prev_soln' := Comment prev_soln' [\"In h_fold\"] in\n                        match prev_soln' with\n                        | (Some _, _) => prev_soln'\n                        | (None, checked_cases'') => \n                            let (edges', remain') := choice in\n                            let chain :=\n                              if peel_left then\n                                app_tail chain [edges']\n                              else\n                                (edges'::chain)\n                            in\n                              (CycleCheckSolveOne m' (S n) (negb peel_left) path uops chain remain'\n                                amti stage_names locations req_edges inv_patterns checked_cases'' excluded_edges)\n                        end\n                      in\n                      let (result, checked_cases_ret) := fold_left h_fold isa_choices (None, checked_cases') in\n                      match result with\n                      | None =>\n                          (result, checked_cases_ret, S cur_index, num_choices)\n                      | Some _ => (result, checked_cases_ret, S cur_index, num_choices)\n                      end\n                  end\n              end\n          end\n        in\n        fst (fst (fold_left g_fold tran_conns (None, checked_cases, 1, List.length tran_conns)))\n      | _ => Warning (None, []) [\"No ops in one or both chains???\"]\n      end\n    | None => Warning (None, []) [\"An empty remaining pattern passed to CycleCheckSolveOne?\"]\n    end\n    | O => Warning (None, []) [\"Recursed too deep in cycle check case!\"]\n    end.\n\nFixpoint CycleCheckSolve\n  (n : nat)\n  (amti : FOLFormula * FOLFormula * FOLFormula * FOLFormula)\n  (stage_names : list (list string))\n  (locations : list nat)\n  (pat : ISAPattern)\n  (uops : list Microop)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : option (list (list ISAEdge)) :=\n  let pat := Comment pat ([\"Checking cycles for ISA pattern: \"] ++ (PrintISAPattern pat)) in\n  let fold_choices := FilterISAPeelChoices (GetFinalEdge 100 pat) true in\n  let k_fold (prev_soln : option (list (list ISAEdge)) * list (list (list ISAEdge) * (list GraphEdge)) * list (list ISAEdge) * bool) (choice : list ISAEdge * option ISAPattern) :=\n    match prev_soln with\n    | (Some _, _, _, _) => prev_soln\n    | (None, checked_cases, excluded_edges, peel_left) => \n        let (edges, left) := choice in\n        let excluded_edges' :=\n          if UseISASym 1 then\n            Comment (edges::excluded_edges) [\"Using Ultimate ISA-level symmetry!\"]\n          else\n            excluded_edges\n        in\n        (CycleCheckSolveOne 100 n peel_left [] uops [edges] left amti stage_names locations [] inv_patterns checked_cases excluded_edges,\n            excluded_edges', negb peel_left)\n    end\n  in\n  match fold_left k_fold fold_choices (None, [], [], false) with\n  | (None, _, _, _) => Comment None [\"Passed Cycle check for an ISA level pattern.\"]\n  | (Some s, _, _, _) => Comment (Some s) [\"Cycle Check found a counterexample for an ISA pattern; returning.\"]\n  end.\n  \nDefinition CycleCheck\n  (max_depth : nat)\n  (m : Microarchitecture)\n  (pattern : ISAAxiom)\n  (inv_patterns : list (ISAPattern * ISAEdge))\n  : option (list (list ISAEdge)) :=\n  match (pattern, FilterUspecInput m [] [] [] []) with\n  | (Irr pat, (axioms, mapping, theory, inv)) =>\n      let axioms := BuildMicroarchitecture [axioms] in\n      let mapping := BuildMicroarchitecture [mapping] in\n      let theory := BuildMicroarchitecture [theory] in\n      (* Invariants should already have been proven... *)\n      let inv := BuildMicroarchitecture [inv] in\n      (* First the \"base case\", an instruction with a cycle to itself. *)\n      let uop := mkMicroop 0 0 0 0 (Fence []) in\n      let s := (mkFOLState [] [] [] [] [] [] [] [uop] [] [] []) in\n      let locations := GetLocations m [] in\n      let chain := GetSingleEdgeChoices pat in\n      let uops := [uop; uop] in\n      let f x := \n        match fst (ReplaceWithInvariants [x] uops inv_patterns) with\n        | [h] => h\n        | _ => Warning x [\"Lists are messed up in cycle check base case...\"]\n        end\n      in\n      let chain := Map f chain in\n      let property_tree := ISAEdgeDisjunction uop uop chain in\n      let amti_tree := CreateAMTITree s (axioms, mapping, theory, inv) (StageNames m) in\n      let final_tree := ScenarioAnd amti_tree property_tree in\n      let final_tree := Comment final_tree [\"Checking cycle base case:\"] in\n      let result := FOL_DPLL max_depth [] [] [] (StageNames m) s final_tree DefaultStrat in\n      match result with\n      | Some s' => let s' := Comment s' [\"Cycle check base case returned SAT; returning\"] in\n                    Some (ConvertToISAChain [uop; uop] s')\n      | None => \n          (* Now for all other cycles. *)\n          (* Begin with 2 instructions, A and B. The params of the uop have\n             no meaning besides the global ID, since everything else will be a variable.\n             Fences are the easiest to create so I've made them both fences. *)\n          let uop_a := mkMicroop 0 0 0 0 (Fence []) in\n          let uop_b := mkMicroop 1 0 0 0 (Fence []) in\n          let locations := GetLocations m [] in\n          match CycleCheckSolve 2 (axioms, mapping, theory, inv) (StageNames m) locations pat [uop_a; uop_b] inv_patterns with\n          | Some s'' => Comment (Some s'') [\"Cycle check returned SAT, returning.\"]\n          | None => Comment None [\"Cycle check returned UNSAT.\"]\n          end\n      end\n  end.\n\nDefinition SeqConst :=\n  [\n    Acyclic (Union (Union (Union (Rel EdgeRF) (Rel EdgeFR)) (Rel EdgeCO)) (Rel EdgePO))\n  ].\n\nDefinition TSO :=\n  [\n    Acyclic (Union (Union (Union (Union (Rel EdgePPO) (Rel EdgeCO)) (Rel EdgeRFE)) (Rel EdgeFR)) (Rel EdgeFence));\n    Acyclic (Union (Union (Union (Rel EdgePO_loc) (Rel EdgeRF)) (Rel EdgeCO)) (Rel EdgeFR))\n  ].\n\nDefinition ISAMcm := list ISAAxiom.\n\nFixpoint CheckAxioms\n  (max_depth : nat)\n  (m : Microarchitecture)\n  (l : list ISAAxiom)\n  : option (list (list ISAEdge)) :=\n  match l with\n  | [] => None\n  | h::t =>\n      let h := PrintTimestamp h \"Axiom_start\" in\n      match h with\n      | Irr pat =>\n          let max_depth := PrintTimestamp max_depth \"TC_start\" in\n          match TransitiveChain max_depth m h InvPatterns with\n          | None =>\n              let h := PrintTimestamp h \"TC_end_success\" in\n              let h := Comment h ([\"Transitive chain passed successfully for \"] ++ (PrintISAPattern pat)) in\n                      let h := PrintTimestamp h \"CycleCheck_start\" in\n                      match CycleCheck max_depth m h InvPatterns with\n                      | None => \n                          let t := PrintTimestamp t \"CycleCheck_end_success\" in\n                          let t := PrintTimestamp t \"Axiom_end_success\" in\n                          let t := Comment t ([\"Cycle check passed successfully for \"] ++ (PrintISAPattern pat)) in\n                                CheckAxioms max_depth m t\n                      | Some l =>\n                          let l := PrintTimestamp l \"CycleCheck_end_failure\" in\n                          let l := PrintTimestamp l \"Axiom_end_failure\" in\n                          let result := Some l in\n                          let result := Comment result ([\"CycleCheck failed for \"] ++ (PrintISAPattern pat)) in\n                          Comment result (PrintISAChain l)\n                      end\n          | Some l =>\n              let l := PrintTimestamp l \"TC_end_failure\" in\n              let l := PrintTimestamp l \"Axiom_end_failure\" in\n              let result := Some l in\n              let result := Comment result ([\"Transitive chain failed for \"] ++ (PrintISAPattern pat)) in\n              Comment result ([\"Counterexample below if generation requested:\"; newline] ++ (PrintISAChain l))\n          end\n      end\n  end.\n\nFixpoint EvaluateUHBGraphs\n  (max_depth : nat)\n  (m : Microarchitecture)\n  (isa_mcm : ISAMcm)\n  : option (list GraphEdge * list ArchitectureLevelEdge) :=\n  let max_depth := PrintTimestamp max_depth \"Total_Start\" in\n  let result :=\n    match CheckAxioms max_depth m isa_mcm with\n    | None => None\n    | Some _ => Some ([], []) (* Doesn't matter what the fn returns, only if it's None/Some...*)\n    end\n  in\n  PrintTimestamp result \"Total_End\".\n\nInductive ExpectedResult : Set :=\n  Permitted | Forbidden | Required | Unobserved.\n", "meta": {"author": "ymanerka", "repo": "pipeproof", "sha": "351505845fa1d0e4afc02b746b9469651c32e120", "save_path": "github-repos/coq/ymanerka-pipeproof", "path": "github-repos/coq/ymanerka-pipeproof/pipeproof-351505845fa1d0e4afc02b746b9469651c32e120/src/FOL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.24046923112572427}}
{"text": "Require Import Reals.\nRequire ClassicalEpsilon.\n(** An axiomatization of languages based on evaluation context items, including\n    a proof that these are instances of general ectx-based languages. *)\nFrom iris.algebra Require Export base.\nFrom iris.program_logic Require Import language prob_language ectx_language.\nFrom mathcomp Require Import ssreflect bigop choice fintype finset ssrbool eqtype.\nFrom discprob Require Import bigop_ext.\nFrom discprob.prob Require Import prob countable.\nSet Default Proof Using \"Type\".\n\n(* TAKE CARE: When you define an [ectxiLanguage] canonical structure for your\nlanguage, you need to also define a corresponding [language] and [ectxLanguage]\ncanonical structure for canonical structure inference to work properly. You\nshould use the coercion [EctxLanguageOfEctxi] and [LanguageOfEctx] for that, and\nnot [ectxi_lang] and [ectxi_lang_ectx], otherwise the canonical projections will\nnot point to the right terms.\n\nA full concrete example of setting up your language can be found in [heap_lang].\nBelow you can find the relevant parts:\n\n  Module heap_lang.\n    (* Your language definition *)\n\n    Lemma heap_lang_mixin : EctxiLanguageMixin of_val to_val fill_item head_step.\n    Proof. (* ... *) Qed.\n  End heap_lang.\n\n  Canonical Structure heap_ectxi_lang := EctxiLanguage heap_lang.heap_lang_mixin.\n  Canonical Structure heap_ectx_lang := EctxLanguageOfEctxi heap_ectxi_lang.\n  Canonical Structure heap_lang := LanguageOfEctx heap_ectx_lang.\n*)\n\nSection ectxi_language_mixin.\n  Context {expr val ectx_item state : Type}.\n  Context (of_val : val → expr).\n  Context (to_val : expr → option val).\n  Context (fill_item : ectx_item → expr → expr).\n  Context (head_step : expr → state → expr → state → list expr → Prop).\n  Context (head_step_prob : expr → state → expr → state → list expr → R).\n\n  Record EctxiLanguageMixin := {\n    mixin_to_of_val v : to_val (of_val v) = Some v;\n    mixin_of_to_val e v : to_val e = Some v → of_val v = e;\n    mixin_val_stuck e1 σ1 e2 σ2 efs : head_step e1 σ1 e2 σ2 efs → to_val e1 = None;\n\n    mixin_fill_item_inj Ki : Inj (=) (=) (fill_item Ki);\n    mixin_fill_item_val Ki e : is_Some (to_val (fill_item Ki e)) → is_Some (to_val e);\n    mixin_fill_item_no_val_inj Ki1 Ki2 e1 e2 :\n      to_val e1 = None → to_val e2 = None →\n      fill_item Ki1 e1 = fill_item Ki2 e2 → Ki1 = Ki2;\n\n    mixin_head_ctx_step_val Ki e σ1 e2 σ2 efs :\n      head_step (fill_item Ki e) σ1 e2 σ2 efs → is_Some (to_val e);\n\n    mixin_head_step_count e σ: \n      Countable.class_of { esf: expr * state * list expr |\n                           head_step e σ (esf.1.1) (esf.1.2) (esf.2) };\n    mixin_head_step_sum1 e σ:\n        (∃ e' σ' efs, head_step e σ e' σ' efs) →\n        is_series (countable_sum (λ t : Countable.Pack (mixin_head_step_count e σ)\n                                        { esf: expr * state * list expr |\n                                          head_step e σ (esf.1.1) (esf.1.2) (esf.2) },\n                                    head_step_prob e σ\n                                                   (fst (fst (sval t)))\n                                                   (snd (fst (sval t)))\n                                                   (snd (sval t)))) 1;\n    mixin_head_step_nonneg : ∀ e1 σ1 e2 σ2 efs, (head_step_prob e1 σ1 e2 σ2 efs >= 0)%R;\n    mixin_head_step_strict_gt :\n    ∀ e1 σ1 e2 σ2 efs, head_step e1 σ1 e2 σ2 efs ↔ (head_step_prob e1 σ1 e2 σ2 efs > 0)%R\n\n  }.\nEnd ectxi_language_mixin.\n\nStructure ectxiLanguage := EctxiLanguage {\n  expr : Type;\n  val : Type;\n  ectx_item : Type;\n  state : Type;\n\n  of_val : val → expr;\n  to_val : expr → option val;\n  fill_item : ectx_item → expr → expr;\n  head_step : expr → state → expr → state → list expr → Prop;\n  head_step_prob : expr → state → expr → state → list expr → R;\n  ectxi_language_mixin :\n    EctxiLanguageMixin of_val to_val fill_item head_step head_step_prob\n}.\n\nArguments EctxiLanguage {_ _ _ _ _ _ _ _ _} _.\nArguments of_val {_} _%V.\nArguments to_val {_} _%E.\nArguments fill_item {_} _ _%E.\nArguments head_step {_} _%E _ _%E _ _.\nArguments head_step_prob {_} _%E _ _%E _ _.\n\nLemma filter_ssr_filter {A} (P: A → Prop) (f: ∀ x, Decision (P x)) (l: list A):\n  filter f l = seq.filter (λ x, is_left (f x)) l.\nProof.\n  induction l => //=.\n  rewrite /filter//=.\n  destruct (f a) => //=.\n  f_equal; eauto.\nQed.\n\nLemma fin_sum1_helper expr state\n  (head_step_prob : expr → state → expr → state → list expr → R)\n  (head_step : expr → state → expr → state → list expr → Prop)\n  (head_step_nonneg : ∀ e1 σ1 e2 σ2 efs, (head_step_prob e1 σ1 e2 σ2 efs >= 0)%R)\n  (head_step_strict_gt :\n    ∀ e1 σ1 e2 σ2 efs, head_step e1 σ1 e2 σ2 efs ↔ (head_step_prob e1 σ1 e2 σ2 efs > 0)%R):\n  (∀ e1 σ1, ∃ l, NoDup l ∧\n        (∀ e2 σ2 efs, head_step e1 σ1 e2 σ2 efs → In (e2, σ2, efs) l ∧\n         \\big[Rplus/0%R]_(t <- l) (head_step_prob e1 σ1 (fst (fst t)) (snd (fst t)) (snd t)) = 1%R))\n  →\n  ∀ e1 σ1, ∃ l, NoDup l ∧\n        (∀ e2 σ2 efs, head_step e1 σ1 e2 σ2 efs ↔ In (e2, σ2, efs) l) ∧\n        (l ≠ nil →\n         \\big[Rplus/0%R]_(t <- l) (head_step_prob e1 σ1 (fst (fst t)) (snd (fst t)) (snd t)) = 1%R).\nProof.\n  intros Halt e1 σ1.\n  destruct (ClassicalEpsilon.excluded_middle_informative (∃ e2 σ2 efs,\n                                                             head_step e1 σ1 e2 σ2 efs))\n    as [(e2&σ2&efs&Hstep)|Hnostep].\n  - specialize (Halt e1 σ1). destruct Halt as (l&NoDup&Hlspec); eauto.\n    set (f := λ esl,(*  match esl with *)\n                 (* | (e2, σ2, efs) =>  *)\n              ClassicalEpsilon.excluded_middle_informative (head_step e1 σ1\n                                   (fst (fst esl)) (snd (fst esl)) (snd esl))).\n    exists (filter f l).\n    split_and!; auto.\n    * by apply NoDup_filter.\n    * intros. split.\n      ** intros Hstep'. rewrite -elem_of_list_In.\n         rewrite elem_of_list_filter; split.\n         *** rewrite /f. destruct ClassicalEpsilon.excluded_middle_informative as [?|n]; auto.\n             rewrite //= in n *.\n         *** rewrite elem_of_list_In. apply Hlspec; eauto.\n      ** rewrite -elem_of_list_In elem_of_list_filter. rewrite /f.\n         destruct ClassicalEpsilon.excluded_middle_informative as [h|n].\n         rewrite //=; auto.\n         intros (?&?) => //=.\n    * intros. rewrite filter_ssr_filter big_filter. \n      rewrite (@big_mkcond R R0 Rplus_monoid _ l (λ x, is_left (f x))\n                              (λ i, head_step_prob e1 σ1 ((i.1).1) ((i.1).2) (i.2))).\n      edestruct Hlspec as (Hin&<-); eauto. \n      rewrite //=. eapply eq_bigr => i ?.\n      destruct (f i) as [?|n] => //=.\n      edestruct (head_step_nonneg); eauto.\n      exfalso. apply n.\n      by apply head_step_strict_gt.\n  - exists []. split_and!; auto.\n    * econstructor.\n    * split; intros HP.\n      ** exfalso. apply Hnostep; eauto.\n      ** inversion HP.\n    * congruence.\nQed.\n\nSection ectxi_language.\n  Context {Λ : ectxiLanguage}.\n  Implicit Types (e : expr Λ) (Ki : ectx_item Λ).\n  Notation ectx := (list (ectx_item Λ)).\n\n  (* Only project stuff out of the mixin that is not also in ectxLanguage *)\n  Global Instance fill_item_inj Ki : Inj (=) (=) (fill_item Ki).\n  Proof. apply ectxi_language_mixin. Qed.\n  Lemma fill_item_val Ki e : is_Some (to_val (fill_item Ki e)) → is_Some (to_val e).\n  Proof. apply ectxi_language_mixin. Qed.\n  Lemma fill_item_no_val_inj Ki1 Ki2 e1 e2 :\n    to_val e1 = None → to_val e2 = None →\n    fill_item Ki1 e1 = fill_item Ki2 e2 → Ki1 = Ki2.\n  Proof. apply ectxi_language_mixin. Qed.\n  Lemma head_ctx_step_val Ki e σ1 e2 σ2 efs :\n    head_step (fill_item Ki e) σ1 e2 σ2 efs → is_Some (to_val e).\n  Proof. apply ectxi_language_mixin. Qed.\n\n  Definition fill (K : ectx) (e : expr Λ) : expr Λ := foldl (flip fill_item) e K.\n\n  Lemma fill_app (K1 K2 : ectx) e : fill (K1 ++ K2) e = fill K2 (fill K1 e).\n  Proof. apply foldl_app. Qed.\n\n  (* When something does a step, and another decomposition of the same expression\n  has a non-val [e] in the hole, then [K] is a left sub-context of [K'] - in\n  other words, [e] also contains the reducible expression *)\n  Lemma step_by_val_prefix K K' e1 e1' σ1 e2 σ2 efs :\n    fill K e1 = fill K' e1' → to_val e1 = None → head_step e1' σ1 e2 σ2 efs →\n    exists K'', K' = K'' ++ K. (* K `prefix_of` K' *)\n  Proof.\n    assert (fill_val : ∀ K e, is_Some (to_val (fill K e)) → is_Some (to_val e)).\n    { clear. intros K. induction K as [|Ki K IH]=> e //=. by intros ?%IH%fill_item_val. }\n    assert (fill_not_val : ∀ K e, to_val e = None → to_val (fill K e) = None).\n    { clear -fill_val. intros K e. rewrite !eq_None_not_Some. eauto. }\n    - intros Hfill Hred Hstep; revert K' Hfill.\n      induction K as [|Ki K IH] using rev_ind=> /= K' Hfill; eauto using app_nil_r.\n      destruct K' as [|Ki' K' _] using @rev_ind; simplify_eq/=.\n      { rewrite fill_app in Hstep. apply head_ctx_step_val in Hstep.\n        apply fill_val in Hstep. by apply not_eq_None_Some in Hstep. }\n      rewrite !fill_app /= in Hfill.\n      assert (Ki = Ki') as ->.\n      { eapply fill_item_no_val_inj, Hfill; eauto using val_head_stuck.\n        apply fill_not_val. revert Hstep. apply ectxi_language_mixin. }\n      simplify_eq. destruct (IH K') as [K'' ->]; auto.\n      exists K''. by rewrite assoc.\n  Qed.\n\n  Lemma step_by_val_eq K K' e1 e1' σ1 e2 e2' σ2 σ2' efs efs' :\n    fill K e1 = fill K' e1' → head_step e1 σ1 e2 σ2 efs → head_step e1' σ1 e2' σ2' efs' →\n    K = K'. \n  Proof.\n    intros Hfill Hstep1 Hstep2.\n    edestruct (step_by_val_prefix K K' e1 e1') as (Kl&HeqKl); eauto.\n    { eapply ectxi_language_mixin; eauto. }\n    edestruct (step_by_val_prefix K' K e1' e1) as (Kl'&HeqKl'); eauto.\n    { eapply ectxi_language_mixin; eauto. }\n    rewrite HeqKl in HeqKl'.\n    apply (f_equal length) in HeqKl'.\n    rewrite ?app_length in HeqKl'.\n    destruct (Kl); rewrite //= in HeqKl HeqKl'; auto; try omega.\n  Qed.\n\n  Definition ectxi_lang_ectx_mixin :\n    EctxLanguageMixin of_val to_val [] (flip (++)) fill head_step head_step_prob.\n  Proof.\n    assert (fill_val : ∀ K e, is_Some (to_val (fill K e)) → is_Some (to_val e)).\n    { intros K. induction K as [|Ki K IH]=> e //=. by intros ?%IH%fill_item_val. }\n    assert (fill_not_val : ∀ K e, to_val e = None → to_val (fill K e) = None).\n    { intros K e. rewrite !eq_None_not_Some. eauto. }\n    unshelve (econstructor). \n    - apply ectxi_language_mixin.\n    - apply ectxi_language_mixin.\n    - apply ectxi_language_mixin.\n    - apply ectxi_language_mixin.\n    - done.\n    - intros K1 K2 e. by rewrite /fill /= foldl_app.\n    - intros K; induction K as [|Ki K IH]; rewrite /Inj; naive_solver.\n    - done.\n    - by intros [] [].\n    - apply step_by_val_prefix.\n    - apply step_by_val_eq.\n    - apply ectxi_language_mixin.\n    - apply ectxi_language_mixin.\n    - apply ectxi_language_mixin.\n  Qed.\n\n  Canonical Structure ectxi_lang_ectx := EctxLanguage ectxi_lang_ectx_mixin.\n  Canonical Structure ectxi_prob_lang := ProbLanguageOfEctx ectxi_lang_ectx.\n  Canonical Structure ectxi_lang := LanguageOfProb ectxi_prob_lang.\n\n  Lemma fill_not_val K e : to_val e = None → to_val (fill K e) = None.\n  Proof. rewrite !eq_None_not_Some. eauto using fill_val. Qed.\n\n  Lemma ectxi_language_sub_redexes_are_values e :\n    (∀ Ki e', e = fill_item Ki e' → is_Some (to_val e')) →\n    sub_redexes_are_values e.\n  Proof.\n    intros Hsub K e' ->. destruct K as [|Ki K _] using @rev_ind=> //=.\n    intros []%eq_None_not_Some. eapply fill_val, Hsub. by rewrite /= fill_app.\n  Qed.\n\n  Instance ectxi_lang_ctx_item Ki :\n    LanguageCtx (fill_item Ki).\n  Proof. change (LanguageCtx (fill (Ki :: nil))). apply _. Qed.\n\n  Global Instance ectxi_lang_ctx_prob_item Ki :\n    ProbLanguageCtx (fill_item Ki).\n  Proof. change (ProbLanguageCtx (fill (Ki :: nil))). apply _. Qed.\nEnd ectxi_language.\n\nArguments fill {_} _ _%E.\nArguments ectxi_lang_ectx : clear implicits.\nArguments ectxi_prob_lang: clear implicits.\nArguments ectxi_lang : clear implicits.\nCoercion ectxi_lang_ectx : ectxiLanguage >-> ectxLanguage.\nCoercion ectxi_prob_lang : ectxiLanguage >-> probLanguage.\nCoercion ectxi_lang : ectxiLanguage >-> language.\n\nDefinition EctxLanguageOfEctxi (Λ : ectxiLanguage) : ectxLanguage :=\n  let '@EctxiLanguage E V C St of_val to_val fill head head_prob mix := Λ in\n  @EctxLanguage E V (list C) St of_val to_val _ _ _ _ _\n    (@ectxi_lang_ectx_mixin (@EctxiLanguage E V C St of_val to_val fill head head_prob mix)).\n", "meta": {"author": "jtassarotti", "repo": "polaris", "sha": "c7873f05214351d54cacf3d8482625ee33ad3288", "save_path": "github-repos/coq/jtassarotti-polaris", "path": "github-repos/coq/jtassarotti-polaris/polaris-c7873f05214351d54cacf3d8482625ee33ad3288/theories/program_logic/ectxi_language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.24046923112572427}}
{"text": "From iris.program_logic Require Export weakestpre adequacy.\nFrom iris.program_logic Require Import ectx_lifting.\nFrom iris.base_logic Require Export invariants.\nFrom iris.algebra Require Import auth frac agree gmap.\nFrom iris_io Require Export lang rules proph_erasure full_erasure.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic Require Export gen_heap.\n\nClass heapIPreG Σ := HeapIPreG {\n  heapI_invG :> invPreG Σ;\n  heapI_gen_heapG :> gen_heapPreG loc val Σ;\n  prophI_gen_heapG :> gen_heapPreG loc (Stream val) Σ;\n  ioI_exclG :> inG Σ io_monoid;\n}.\n\nClass heapIPreIOG Σ := HeapIPreIOG {\n  heapI_invPreIOG :> invG Σ;\n  heapI_gen_heapPreIOG :> gen_heapG loc val Σ;\n  prophI_gen_heapPreIOG :> gen_heapG loc (Stream val) Σ;\n  ioI_exclPreIOG :> inG Σ io_monoid;\n}.\n\nDefinition make_heapIG `{heapIPreIOG Σ} γio : heapIG Σ := {| γio := γio |}.\n\nDefinition IoΣ := #[invΣ; gen_heapΣ loc val; gen_heapΣ loc (Stream val);\n                      GFunctor io_monoid].\n\nGlobal Instance subG_io_monoid Σ : subG IoΣ Σ → inG Σ io_monoid.\nProof. solve_inG. Qed.\n\nGlobal Instance subG_heapIPreG Σ : subG IoΣ Σ → heapIPreG Σ.\nProof. solve_inG. Qed.\n\nTheorem adequacy_instrumented Σ `{heapIPreG Σ} e Φ M :\n  (∀ `{Hig : heapIPreIOG Σ},\n      (|={⊤}=> ∃ γio, let _ := make_heapIG γio in\n             FullIO M ∗ WP e @ NotStuck; ⊤ {{ Φ }})%I) → safe e M.\nProof.\n  intros Hwp.\n  cut (adequate NotStuck e {| Heap := ∅; Proph := ∅; ioState := M |} (λ _, True)).\n  { intros [Hrc Hns]; simpl in *.\n    intros th2 σ2 Hrtc e' He'.\n    specialize (Hns th2 σ2 e' eq_refl Hrtc He'); eauto. }\n  eapply wp_adequacy; first apply _.\n  iIntros (Hinv) \"\".\n  iMod (gen_heap_init (∅ : gmap loc val)) as (Hheap) \"Hheap\".\n  iMod (gen_heap_init (∅ : gmap loc (Stream val))) as (Hproph) \"Hproph\".\n  pose ({| heapI_invPreIOG := _ |}).\n  iMod (Hwp _) as (γio) \"[HFIO Hwp]\".\n  pose ({| γio := γio |}).\n  iModIntro.\n  iExists heapIG_stateI.\n  iSplitR \"Hwp\"; first by iFrame.\n  iApply (wp_mono); last by iApply \"Hwp\".\n  eauto.\nQed.\n\nTheorem adequacy Σ `{heapIPreG Σ} (e : expr) Φ M :\n  prefix_closed M →\n  (∀ `{Hig : heapIPreIOG Σ},\n      (|={⊤}=> ∃ γio, let _ := make_heapIG γio in\n                     FullIO M ∗ WP e @ NotStuck; ⊤ {{ Φ }})%I) →\n  fully_erased_safe e M.\nProof.\n  intros HPC Hig.\n  apply soundness_io; eauto.\n  apply soundness_prophecies.\n  eapply adequacy_instrumented; eauto.\nQed.\n", "meta": {"author": "amintimany", "repo": "iris-io", "sha": "f6d3404ea1c8afcba715890c2b502719a8fe1fc6", "save_path": "github-repos/coq/amintimany-iris-io", "path": "github-repos/coq/amintimany-iris-io/iris-io-f6d3404ea1c8afcba715890c2b502719a8fe1fc6/adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757646140788307, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.2404200743823308}}
{"text": "Require Import ListAux.\nLemma stream3bound_Cons0 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(list_once  il_0 u_1)/\\(not (list_order  il_0 u_0 u_1))/\\(not (list_member  il_0 u_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (u_0 = i_0))/\\(u_1 = i_0)/\\(list_member  il_0 u_1)/\\(list_once  il_1 u_1)/\\(list_once  il_1 u_0)/\\(list_order  il_1 u_0 u_1)) -> (not (list_once  il_0 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons1 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(list_once  il_0 u_1)/\\(not (list_order  il_0 u_0 u_1))/\\(not (list_member  il_0 u_0))/\\(not (list_order  il_1 u_1 u_0))/\\(u_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(not (u_1 = i_0))/\\(list_member  il_0 u_1)/\\(list_once  il_1 u_1)/\\(list_once  il_1 u_0)/\\(list_order  il_1 u_0 u_1)) -> (not (list_order  il_0 u_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons2 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(not (u_0 = i_0))/\\(not (list_once  il_0 i_0))/\\(u_1 = i_0)/\\(list_member  il_0 u_0)/\\(list_once  il_0 u_0)/\\(not (list_member  il_0 u_1))/\\(list_once  il_1 u_1)/\\(list_once  il_1 u_0)/\\(list_order  il_1 u_0 u_1)) -> (not (list_order  il_0 u_0 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons3 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(u_0 = i_0)/\\(not (u_1 = i_0))/\\(list_member  il_0 u_0)/\\(list_once  il_0 u_0)/\\(not (list_member  il_0 u_1))/\\(list_once  il_1 u_1)/\\(list_once  il_1 u_0)/\\(list_order  il_1 u_0 u_1)) -> (not (list_once  il_0 u_1))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons4 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(u_1 = i_0)/\\(not (u_0 = i_0))/\\(not (list_once  il_0 i_0))/\\(list_order  il_0 i_0 u_0)/\\(not (list_member  il_0 u_0))/\\(list_once  il_0 u_0)/\\(not (list_member  il_0 u_1))/\\(list_once  il_1 u_1)/\\(list_once  il_1 u_0)/\\(list_order  il_1 u_0 u_1)) -> (list_order  il_0 u_0 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons5 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(u_1 = i_0)/\\(not (u_0 = i_0))/\\(not (list_once  il_0 i_0))/\\(list_order  il_0 i_0 u_0)/\\(not (list_member  il_0 u_0))/\\(list_once  il_0 u_0)/\\(not (list_member  il_0 u_1))/\\(list_once  il_1 u_1)/\\(list_once  il_1 u_0)/\\(list_order  il_1 u_0 u_1)) -> (list_order  il_1 i_0 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons6 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(u_1 = i_0)/\\(not (u_0 = i_0))/\\(not (list_once  il_0 i_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 u_0))/\\(list_once  il_0 u_0)/\\(not (list_member  il_0 u_1))/\\(list_once  il_1 u_1)/\\(list_once  il_1 u_0)/\\(list_order  il_1 u_0 u_1)) -> (not (list_order  il_0 u_0 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons7 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(not (u_1 = i_0))/\\(u_0 = i_0)/\\(list_once  il_0 u_1)/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_member  il_0 u_1))/\\(list_once  il_1 u_1)/\\(list_once  il_1 u_0)/\\(list_order  il_1 u_0 u_1)) -> (list_order  il_1 u_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons8 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(not (u_1 = i_0))/\\(u_0 = i_0)/\\(list_once  il_0 u_1)/\\(not (list_member  il_0 i_0))/\\(list_order  il_0 u_1 i_0)/\\(not (list_once  il_0 u_0))/\\(not (list_member  il_0 u_1))/\\(list_once  il_1 u_1)/\\(list_once  il_1 u_0)/\\(list_order  il_1 u_0 u_1)) -> (not (list_order  il_0 i_0 u_1))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons9 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(not (u_1 = i_0))/\\(u_0 = i_0)/\\(list_once  il_0 u_1)/\\(not (list_member  il_0 i_0))/\\(not (list_order  il_0 u_1 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_member  il_0 u_1))/\\(list_once  il_1 u_1)/\\(list_once  il_1 u_0)/\\(list_order  il_1 u_0 u_1)) -> (list_order  il_0 i_0 u_1)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons10 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(u_1 = i_0)/\\(not (u_0 = i_0))/\\(list_once  il_0 u_0)/\\(list_member  il_0 i_0)/\\(not (list_member  il_0 u_0))/\\(not (list_order  il_1 i_0 u_0))/\\(not (list_once  il_1 u_1))/\\(list_once  il_1 u_0)/\\(list_order  il_1 u_0 u_1)) -> (list_once  il_0 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons11 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(u_1 = i_0)/\\(not (u_0 = i_0))/\\(list_once  il_0 u_0)/\\(list_member  il_0 i_0)/\\(not (list_member  il_0 u_0))/\\(not (list_order  il_1 i_0 u_0))/\\(not (list_once  il_1 u_1))/\\(list_once  il_1 u_0)/\\(list_order  il_1 u_0 u_1)) -> (list_order  il_0 u_0 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons12 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_0 = i_0))/\\(u_1 = u_0)/\\(list_once  il_0 u_0)/\\(list_member  il_0 u_0)/\\(not (list_once  il_1 u_0))/\\(list_order  il_1 u_0 u_1)) -> (not (list_order  il_1 u_0 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons13 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = i_0))/\\(u_0 = i_0)/\\(list_once  il_0 u_1)/\\(not (list_member  il_0 u_1))/\\(not (u_1 = u_0))/\\(list_once  il_0 u_0)/\\(list_member  il_0 u_0)/\\(not (list_once  il_1 u_0))/\\(list_order  il_1 u_0 u_1)) -> (not (list_once  il_1 u_1))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons14 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_1 = u_0))/\\(not (u_1 = i_0))/\\(u_0 = i_0)/\\(list_once  il_0 u_1)/\\(not (list_member  il_0 u_1))/\\(not (list_once  il_0 u_0))/\\(list_member  il_0 u_0)/\\(not (list_once  il_1 u_0))/\\(list_order  il_1 u_0 u_1)) -> (not (list_once  il_1 u_1))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons15 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (list_member  il_0 u_0))/\\(not (list_once  il_1 u_0))/\\(list_order  il_1 u_0 u_1)) -> (not (u_1 = u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons16 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_member  il_0 u_0))/\\(not (u_0 = i_0))/\\(not (list_once  il_1 u_0))/\\(list_order  il_0 u_0 u_0)/\\(list_once  il_0 u_0)/\\(u_1 = u_0)/\\(list_order  il_1 u_1 u_0)/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons17 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_member  il_0 u_0))/\\(not (u_0 = i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 u_0))/\\(list_once  il_0 u_0)/\\(u_1 = u_0)/\\(list_order  il_1 u_1 u_0)/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons18 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_member  il_0 u_0))/\\(not (u_0 = i_0))/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 u_0))/\\(u_1 = u_0)/\\(list_order  il_1 u_1 u_0)/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons19 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_member  il_0 u_1))/\\(list_once  il_1 u_1)/\\(list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(not (u_0 = i_0))/\\(not (list_once  il_0 i_0))/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(list_member  il_0 u_0)/\\(u_1 = i_0)/\\(not (u_1 = u_0))/\\(list_order  il_1 u_1 u_0)/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_once  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons20 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_member  il_0 u_1))/\\(list_once  il_1 u_1)/\\(list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(u_0 = i_0)/\\(list_once  il_0 u_1)/\\(list_order  il_0 u_1 i_0)/\\(list_once  il_0 i_0)/\\(not (u_1 = i_0))/\\(not (u_1 = u_0))/\\(list_order  il_1 u_1 u_0)/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_0 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons21 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_member  il_0 u_1))/\\(list_once  il_1 u_1)/\\(list_member  il_1 u_1)/\\(list_member  il_1 u_0)/\\(u_0 = i_0)/\\(list_once  il_0 u_1)/\\(not (list_order  il_0 u_1 i_0))/\\(not (list_order  il_0 i_0 u_1))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_0 i_0))/\\(not (u_1 = i_0))/\\(not (u_1 = u_0))/\\(list_order  il_1 u_1 u_0)/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_once  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons22 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(list_once  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons23 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(i_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(list_once  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons24 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(i_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(list_once  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons25 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (i_0 = i_0))/\\(not (list_once  il_0 i_0))/\\(list_once  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons26 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(list_member  il_1 u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons27 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(i_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(list_member  il_1 u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons28 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(i_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(list_member  il_1 u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons29 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (i_0 = i_0))/\\(not (list_once  il_0 i_0))/\\(list_member  il_1 u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons30 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(u_0 = i_0)/\\(not (list_member  il_1 u_0))/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons31 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_once  il_1 i_0)/\\(i_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(u_0 = i_0)/\\(not (list_member  il_1 u_0))/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons32 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_1 i_0))/\\(i_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(u_0 = i_0)/\\(not (list_member  il_1 u_0))/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons33 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_1 i_0))/\\(not (i_0 = i_0))/\\(not (list_once  il_0 i_0))/\\(u_0 = i_0)/\\(not (list_member  il_1 u_0))/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons34 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((i_0 = u_0)/\\(not (u_0 = i_0))/\\(not (list_member  il_1 u_0))/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_0 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons35 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(list_once  il_1 u_0)/\\(list_member  il_0 u_0)/\\(i_0 = u_0)/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons36 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 u_0)/\\(i_0 = u_0)/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons37 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(list_once  il_1 u_0)/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons38 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_once  il_1 u_0))/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons39 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = u_0))/\\(not (list_once  il_1 u_0))/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons40 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(list_once  il_0 i_0)/\\(not (i_0 = u_0))/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons41 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(not (i_0 = u_0))/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons42 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_once  il_0 i_0))/\\(not (i_0 = u_0))/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons43 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 u_0)/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons44 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(list_once  il_1 u_0)/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons45 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = u_0))/\\(list_once  il_1 u_0)/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons46 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_once  il_1 u_0))/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons47 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_member  il_0 i_0)/\\(not (i_0 = u_0))/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons48 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(not (list_member  il_0 i_0))/\\(not (i_0 = u_0))/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons49 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_member  il_0 i_0))/\\(not (i_0 = u_0))/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons50 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_once  il_1 i_0)/\\(i_0 = i_0)/\\(u_0 = i_0)/\\(list_member  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons51 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_1 i_0))/\\(i_0 = i_0)/\\(u_0 = i_0)/\\(list_member  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons52 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_1 i_0))/\\(not (i_0 = i_0))/\\(u_0 = i_0)/\\(list_member  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons53 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((i_0 = u_0)/\\(not (u_0 = i_0))/\\(list_member  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_0 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons54 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(i_0 = i_0)/\\(not (list_member  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons55 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(i_0 = i_0)/\\(not (list_member  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons56 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (i_0 = i_0))/\\(not (list_member  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons57 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = u_0))/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(not (list_member  il_0 i_0))/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons58 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (i_0 = u_0))/\\(not (list_member  il_0 i_0))/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons59 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(i_0 = i_0)/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons60 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(i_0 = i_0)/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons61 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (i_0 = i_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons62 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(list_order  il_0 i_0 u_0)/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons63 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(list_once  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons64 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(i_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(list_once  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons65 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(i_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(list_once  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons66 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (i_0 = i_0))/\\(not (list_once  il_0 i_0))/\\(list_once  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons67 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(list_member  il_1 u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons68 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(i_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(list_member  il_1 u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons69 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(i_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(list_member  il_1 u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons70 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (i_0 = i_0))/\\(not (list_once  il_0 i_0))/\\(list_member  il_1 u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons71 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(u_0 = i_0)/\\(not (list_member  il_1 u_0))/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons72 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_once  il_1 i_0)/\\(i_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(u_0 = i_0)/\\(not (list_member  il_1 u_0))/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons73 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_1 i_0))/\\(i_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(u_0 = i_0)/\\(not (list_member  il_1 u_0))/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons74 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_1 i_0))/\\(not (i_0 = i_0))/\\(not (list_once  il_0 i_0))/\\(u_0 = i_0)/\\(not (list_member  il_1 u_0))/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons75 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((i_0 = u_0)/\\(not (u_0 = i_0))/\\(not (list_member  il_1 u_0))/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_0 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons76 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(list_once  il_1 u_0)/\\(list_member  il_0 u_0)/\\(i_0 = u_0)/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons77 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 u_0)/\\(i_0 = u_0)/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons78 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(list_once  il_1 u_0)/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons79 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_once  il_1 u_0))/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons80 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = u_0))/\\(not (list_once  il_1 u_0))/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons81 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(list_once  il_0 i_0)/\\(not (i_0 = u_0))/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons82 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(not (i_0 = u_0))/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons83 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_once  il_0 i_0))/\\(not (i_0 = u_0))/\\(not (list_member  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons84 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 u_0)/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons85 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(list_once  il_1 u_0)/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons86 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = u_0))/\\(list_once  il_1 u_0)/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons87 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_once  il_1 u_0))/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons88 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_member  il_0 i_0)/\\(not (i_0 = u_0))/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons89 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(not (list_member  il_0 i_0))/\\(not (i_0 = u_0))/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons90 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_member  il_0 i_0))/\\(not (i_0 = u_0))/\\(list_once  il_0 i_0)/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons91 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_once  il_1 i_0)/\\(i_0 = i_0)/\\(u_0 = i_0)/\\(list_member  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons92 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_1 i_0))/\\(i_0 = i_0)/\\(u_0 = i_0)/\\(list_member  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons93 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_1 i_0))/\\(not (i_0 = i_0))/\\(u_0 = i_0)/\\(list_member  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons94 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((i_0 = u_0)/\\(not (u_0 = i_0))/\\(list_member  il_1 u_0)/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_0 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons95 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(i_0 = i_0)/\\(not (list_member  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons96 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(i_0 = i_0)/\\(not (list_member  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons97 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (i_0 = i_0))/\\(not (list_member  il_1 u_0))/\\(list_member  il_0 i_0)/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons98 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = u_0))/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(not (list_member  il_0 i_0))/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons99 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (i_0 = u_0))/\\(not (list_member  il_0 i_0))/\\(list_once  il_1 u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons100 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(i_0 = i_0)/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons101 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(i_0 = i_0)/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons102 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (i_0 = i_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons103 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_once  il_0 i_0))/\\(not (list_once  il_0 u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_order  il_0 u_0 i_0)/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons104 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_member  il_0 u_0))/\\(list_once  il_0 u_0)/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(list_order  il_0 i_0 u_0)/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons105 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_member  il_0 u_0))/\\(u_0 = u_0)/\\(not (list_once  il_0 u_0))/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(list_order  il_0 i_0 u_0)/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons106 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_member  il_0 u_0))/\\(not (u_0 = u_0))/\\(not (list_once  il_0 u_0))/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(list_order  il_0 i_0 u_0)/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons107 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_member  il_0 i_0)/\\(not (i_0 = u_0))/\\(list_once  il_0 i_0)/\\(list_order  il_0 i_0 u_0)/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons108 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(not (list_member  il_0 i_0))/\\(not (i_0 = u_0))/\\(list_once  il_0 i_0)/\\(list_order  il_0 i_0 u_0)/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons109 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_member  il_0 i_0))/\\(not (i_0 = u_0))/\\(list_once  il_0 i_0)/\\(list_order  il_0 i_0 u_0)/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons110 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_1 u_0)/\\(u_0 = u_0)/\\(list_member  il_0 u_0)/\\(i_0 = u_0)/\\(not (list_once  il_0 i_0))/\\(list_order  il_0 i_0 u_0)/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_once  il_0 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons111 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = u_0))/\\(not (list_once  il_0 u_0))/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(not (list_once  il_0 i_0))/\\(list_order  il_0 i_0 u_0)/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons112 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(list_member  il_0 i_0)/\\(not (i_0 = u_0))/\\(not (list_once  il_0 i_0))/\\(list_order  il_0 i_0 u_0)/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons113 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_member  il_0 i_0)/\\(not (i_0 = u_0))/\\(not (list_once  il_0 i_0))/\\(list_order  il_0 i_0 u_0)/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons114 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_member  il_0 i_0))/\\(not (i_0 = u_0))/\\(not (list_once  il_0 i_0))/\\(list_order  il_0 i_0 u_0)/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons115 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_member  il_0 u_0))/\\(list_once  il_0 u_0)/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons116 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_member  il_0 u_0))/\\(u_0 = u_0)/\\(not (list_once  il_0 u_0))/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons117 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_member  il_0 u_0))/\\(not (u_0 = u_0))/\\(not (list_once  il_0 u_0))/\\(i_0 = u_0)/\\(list_once  il_0 i_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons118 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_member  il_0 i_0)/\\(not (i_0 = u_0))/\\(list_once  il_0 i_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons119 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(not (list_member  il_0 i_0))/\\(not (i_0 = u_0))/\\(list_once  il_0 i_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons120 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_member  il_0 i_0))/\\(not (i_0 = u_0))/\\(list_once  il_0 i_0)/\\(not (list_order  il_0 i_0 u_0))/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons121 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_once  il_0 u_0))/\\(list_member  il_0 u_0)/\\(i_0 = u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons122 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = u_0))/\\(not (list_once  il_0 u_0))/\\(not (list_member  il_0 u_0))/\\(i_0 = u_0)/\\(not (list_once  il_0 i_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons123 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(list_member  il_0 i_0)/\\(not (i_0 = u_0))/\\(not (list_once  il_0 i_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons124 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_member  il_0 i_0)/\\(not (i_0 = u_0))/\\(not (list_once  il_0 i_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons125 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_member  il_0 i_0))/\\(not (i_0 = u_0))/\\(not (list_once  il_0 i_0))/\\(not (list_order  il_0 i_0 u_0))/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons126 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(list_once  il_0 u_0)/\\(i_0 = u_0)/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons127 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_member  il_0 u_0))/\\(not (u_0 = u_0))/\\(list_once  il_0 u_0)/\\(i_0 = u_0)/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons128 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(list_member  il_0 u_0)/\\(list_order  il_0 u_0 u_0)/\\(not (list_once  il_0 u_0))/\\(i_0 = u_0)/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons129 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_member  il_0 u_0))/\\(list_order  il_0 u_0 u_0)/\\(not (list_once  il_0 u_0))/\\(i_0 = u_0)/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons130 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(list_member  il_0 u_0)/\\(not (list_order  il_0 u_0 u_0))/\\(not (list_once  il_0 u_0))/\\(i_0 = u_0)/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons131 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_member  il_0 u_0))/\\(not (list_order  il_0 u_0 u_0))/\\(not (list_once  il_0 u_0))/\\(i_0 = u_0)/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons132 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons133 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(list_order  il_0 i_0 i_0)/\\(not (list_once  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons134 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_order  il_0 i_0 i_0)/\\(not (list_once  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons135 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(not (list_order  il_0 i_0 i_0))/\\(not (list_once  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons136 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_order  il_0 i_0 i_0))/\\(not (list_once  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons137 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_0 i_0))/\\(u_0 = i_0)/\\(list_member  il_1 i_0)/\\(list_order  il_0 i_0 u_0)/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_once  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons138 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_0 u_0)/\\(not (list_member  il_1 u_0))/\\(not (u_0 = i_0))/\\(list_member  il_1 i_0)/\\(list_order  il_0 i_0 u_0)/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_once  il_0 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons139 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_0 u_0)/\\(not (list_member  il_1 u_0))/\\(not (u_0 = i_0))/\\(list_member  il_1 i_0)/\\(list_order  il_0 i_0 u_0)/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_once  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons140 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_member  il_1 i_0))/\\(list_order  il_0 i_0 u_0)/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_once  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons141 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons142 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_0 u_0)/\\(u_0 = i_0)/\\(list_member  il_1 i_0)/\\(not (list_once  il_0 i_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_once  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons143 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_member  il_0 u_0)/\\(not (list_once  il_1 i_0))/\\(not (u_0 = i_0))/\\(list_member  il_1 i_0)/\\(not (list_once  il_0 i_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons144 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_member  il_1 i_0))/\\(not (list_once  il_0 i_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(list_member  il_0 i_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_once  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons145 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(list_member  il_0 u_0)/\\(list_once  il_0 u_0)/\\(i_0 = u_0)/\\(list_order  il_0 i_0 u_0)/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons146 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_member  il_0 u_0))/\\(list_once  il_0 u_0)/\\(i_0 = u_0)/\\(list_order  il_0 i_0 u_0)/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons147 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = u_0))/\\(not (list_member  il_0 u_0))/\\(list_once  il_0 u_0)/\\(i_0 = u_0)/\\(list_order  il_0 i_0 u_0)/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons148 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_once  il_0 u_0))/\\(i_0 = u_0)/\\(list_order  il_0 i_0 u_0)/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons149 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(list_once  il_0 i_0)/\\(not (i_0 = u_0))/\\(list_order  il_0 i_0 u_0)/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons150 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(not (i_0 = u_0))/\\(list_order  il_0 i_0 u_0)/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons151 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_once  il_0 i_0))/\\(not (i_0 = u_0))/\\(list_order  il_0 i_0 u_0)/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons152 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(list_member  il_0 u_0)/\\(list_once  il_0 u_0)/\\(i_0 = u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons153 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_member  il_0 u_0))/\\(list_once  il_0 u_0)/\\(i_0 = u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons154 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = u_0))/\\(not (list_member  il_0 u_0))/\\(list_once  il_0 u_0)/\\(i_0 = u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons155 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = u_0)/\\(not (list_once  il_0 u_0))/\\(i_0 = u_0)/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons156 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(list_once  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (i_0 = u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons157 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(list_once  il_0 u_0)/\\(not (i_0 = u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons158 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_once  il_0 i_0))/\\(list_once  il_0 u_0)/\\(not (i_0 = u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons159 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(list_once  il_0 i_0)/\\(list_member  il_0 u_0)/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons160 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(list_member  il_0 u_0)/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons161 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_1 i_0))/\\(u_0 = i_0)/\\(not (list_once  il_0 i_0))/\\(list_member  il_0 u_0)/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons162 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((list_once  il_1 i_0)/\\(list_member  il_1 i_0)/\\(not (u_0 = i_0))/\\(not (list_once  il_0 i_0))/\\(list_member  il_0 u_0)/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons163 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(list_once  il_1 i_0)/\\(list_once  il_0 i_0)/\\(not (list_member  il_0 u_0))/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons164 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(list_once  il_0 i_0)/\\(not (list_member  il_0 u_0))/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons165 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((u_0 = i_0)/\\(not (list_once  il_1 i_0))/\\(not (list_once  il_0 i_0))/\\(not (list_member  il_0 u_0))/\\(not (list_once  il_0 u_0))/\\(not (i_0 = u_0))/\\(not (list_order  il_0 i_0 u_0))/\\(not (list_member  il_0 i_0))/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 i_0))/\\(u_1 = i_0)/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons166 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = i_0))/\\(list_once  il_0 u_0)/\\(not (list_once  il_1 u_0))/\\(list_member  il_0 u_0)/\\(u_1 = u_0)/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons167 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = i_0))/\\(not (list_once  il_0 u_0))/\\(list_once  il_1 u_0)/\\(list_order  il_0 u_0 u_0)/\\(not (list_member  il_0 u_0))/\\(u_1 = u_0)/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons168 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = i_0))/\\(list_once  il_0 u_0)/\\(not (list_once  il_1 u_0))/\\(list_order  il_0 u_0 u_0)/\\(not (list_member  il_0 u_0))/\\(u_1 = u_0)/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons169 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = i_0))/\\(not (list_once  il_0 u_0))/\\(list_once  il_1 u_0)/\\(not (list_order  il_0 u_0 u_0))/\\(not (list_member  il_0 u_0))/\\(u_1 = u_0)/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_member  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons170 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (u_0 = i_0))/\\(list_once  il_0 u_0)/\\(not (list_once  il_1 u_0))/\\(not (list_order  il_0 u_0 u_0))/\\(not (list_member  il_0 u_0))/\\(u_1 = u_0)/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_member  il_1 u_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons171 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_0 u_1))/\\(not (list_once  il_1 u_1))/\\(not (list_member  il_1 u_1))/\\(list_member  il_1 u_0)/\\(list_member  il_0 u_1)/\\(list_member  il_0 i_0)/\\(list_once  il_0 i_0)/\\(u_0 = i_0)/\\(not (u_1 = u_0))/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_order  il_0 u_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons172 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_0 u_1))/\\(not (list_once  il_1 u_1))/\\(not (list_member  il_1 u_1))/\\(list_member  il_1 u_0)/\\(list_member  il_0 u_1)/\\(list_member  il_0 i_0)/\\(list_once  il_0 i_0)/\\(u_0 = i_0)/\\(not (u_1 = u_0))/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_order  il_0 i_0 u_1)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons173 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_0 u_1))/\\(not (list_once  il_1 u_1))/\\(not (list_member  il_1 u_1))/\\(list_member  il_1 u_0)/\\(list_member  il_0 u_1)/\\(list_member  il_0 i_0)/\\(list_order  il_0 u_1 i_0)/\\(list_order  il_0 i_0 u_1)/\\(not (list_once  il_0 i_0))/\\(u_0 = i_0)/\\(not (u_1 = u_0))/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_once  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons174 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_0 u_1))/\\(not (list_once  il_1 u_1))/\\(not (list_member  il_1 u_1))/\\(list_member  il_1 u_0)/\\(list_member  il_0 u_1)/\\(not (list_member  il_0 i_0))/\\(list_order  il_0 u_1 i_0)/\\(list_order  il_0 i_0 u_1)/\\(not (list_once  il_0 i_0))/\\(u_0 = i_0)/\\(not (u_1 = u_0))/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_once  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons175 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_0 u_1))/\\(not (list_once  il_1 u_1))/\\(not (list_member  il_1 u_1))/\\(list_member  il_1 u_0)/\\(list_member  il_0 u_1)/\\(not (list_member  il_0 i_0))/\\(not (list_order  il_0 u_1 i_0))/\\(list_order  il_0 i_0 u_1)/\\(not (list_once  il_0 i_0))/\\(u_0 = i_0)/\\(not (u_1 = u_0))/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_once  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons176 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_0 u_1))/\\(not (list_once  il_1 u_1))/\\(not (list_member  il_1 u_1))/\\(list_member  il_1 u_0)/\\(list_member  il_0 u_1)/\\(list_order  il_0 u_1 i_0)/\\(list_member  il_0 i_0)/\\(not (list_order  il_0 i_0 u_1))/\\(not (list_once  il_0 i_0))/\\(u_0 = i_0)/\\(not (u_1 = u_0))/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (list_once  il_1 i_0)).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons177 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_0 u_1))/\\(not (list_once  il_1 u_1))/\\(not (list_member  il_1 u_1))/\\(list_member  il_1 u_0)/\\(list_member  il_0 u_1)/\\(list_order  il_0 u_1 i_0)/\\(not (list_member  il_0 i_0))/\\(not (list_order  il_0 i_0 u_1))/\\(not (list_once  il_0 i_0))/\\(u_0 = i_0)/\\(not (u_1 = u_0))/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_once  il_1 i_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\nLemma stream3bound_Cons178 (i_0:nat) (il_0:list nat) (il_1:list nat) (u_0:nat) (u_1:nat) : (push_spec  i_0 il_0 il_1) -> (((not (list_once  il_0 u_1))/\\(not (list_once  il_1 u_1))/\\(not (list_member  il_1 u_1))/\\(list_member  il_1 u_0)/\\(list_once  il_0 u_0)/\\(list_order  il_0 u_0 u_1)/\\(not (list_member  il_0 u_1))/\\(list_member  il_0 u_0)/\\(not (u_0 = i_0))/\\(not (u_1 = u_0))/\\(not (u_1 = i_0))/\\(not (list_order  il_1 u_1 u_0))/\\(not (list_order  il_1 u_0 u_1))) -> (not (list_once  il_1 u_0))).\nProof. solve_push; try (assert (u_0 = u_1); subst; eauto). Qed.\n\n", "meta": {"author": "zhezhouzz", "repo": "OOPSLA-21-SuppementalMaterial", "sha": "c749024c525eeefc4e4eca29a2cdde8bf6f32675", "save_path": "github-repos/coq/zhezhouzz-OOPSLA-21-SuppementalMaterial", "path": "github-repos/coq/zhezhouzz-OOPSLA-21-SuppementalMaterial/OOPSLA-21-SuppementalMaterial-c749024c525eeefc4e4eca29a2cdde8bf6f32675/proof/Verifystream3boundCons.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.24040369492151845}}
{"text": "From Perennial.goose_lang Require Import notation proofmode typing.\nFrom Perennial.goose_lang Require Import wpc_proofmode.\nFrom Perennial.goose_lang.lib Require Import typed_mem.\nFrom Perennial.goose_lang.lib Require Import\n     slice.slice slice.typed_slice into_val.\n\n\nSet Default Proof Using \"Type\".\n\nSection goose_lang.\nContext `{ffi_sem: ffi_semantics} `{!ffi_interp ffi} `{!heapGS Σ}.\nContext {ext_ty: ext_types ext}.\n\nContext `{!IntoVal V}.\n\nImplicit Types (v:V) (vs: list V).\n\nLemma wpc_slice_len stk E1 s Φ Φc :\n  Φc ∧ Φ #(Slice.sz s) -∗\n  WPC slice.len (slice_val s) @ stk; E1 {{ v, Φ v }} {{ Φc }}.\nProof.\n  iIntros \"HΦ\".\n  rewrite /slice.len.\n  wpc_pures.\n  { by iDestruct \"HΦ\" as \"[$ _]\". }\n  { by iDestruct \"HΦ\" as \"[_ $]\". }\nQed.\n\nLemma wpc_SliceGet stk E1 s t q vs (i: u64) v0 :\n  {{{ is_slice_small s t q vs ∗ ⌜ vs !! int.nat i = Some v0 ⌝ }}}\n    SliceGet t (slice_val s) #i @ stk; E1\n  {{{ RET (to_val v0); is_slice_small s t q vs }}}\n  {{{ True }}}.\nProof.\n  iIntros (Φ Φc) \"[Hs %] HΦ\".\n  rewrite /SliceGet.\n  wpc_pures; first auto.\n  { by crash_case. }\n  wpc_pures.\n  { by crash_case. }\n  wpc_frame \"HΦ\".\n  { by crash_case. }\n  iApply (wp_SliceGet_body with \"[$Hs]\").\n  { rewrite /list.untype list_lookup_fmap.\n    rewrite H //. }\n  iIntros \"!> [Hs %] HΦ\". iNamed \"HΦ\".\n  iRight in \"HΦ\".\n  iApply \"HΦ\".\n  auto.\nQed.\n\nTheorem wpc_forSlice (I: u64 -> iProp Σ) Φc' stk E1 s t q (vs: list V) (body: val) :\n  □ (∀ x, I x -∗ Φc') -∗\n  (∀ (i: u64) (x: V),\n      {{{ I i ∗ ⌜(int.nat i < length vs)%nat⌝ ∗\n                ⌜vs !! int.nat i = Some x⌝ }}}\n        body #i (to_val x) @ stk; E1\n      {{{ RET #(); I (word.add i (U64 1)) }}}\n      {{{ Φc' }}}) -∗\n    {{{ I (U64 0) ∗ is_slice_small s t q vs }}}\n      forSlice t body (slice_val s) @ stk; E1\n    {{{ RET #(); I s.(Slice.sz) ∗ is_slice_small s t q vs }}}\n    {{{ Φc' }}}.\nProof.\n  iIntros \"#HΦcI #Hind\".\n  iIntros (Φ Φc) \"!> [Hi0 Hs] HΦ\".\n  rewrite /forSlice.\n  wpc_pures.\n  { iSpecialize (\"HΦcI\" with \"[$]\"). iLeft in \"HΦ\". iApply \"HΦ\". eauto. }\n  wpc_pures.\n  { iSpecialize (\"HΦcI\" with \"[$]\"). iLeft in \"HΦ\". iApply \"HΦ\". eauto. }\n  wpc_apply wpc_slice_len.\n  iSplit.\n  { iSpecialize (\"HΦcI\" with \"[$]\"). iLeft in \"HΦ\". iApply \"HΦ\". eauto. }\n  wpc_pures.\n  { iSpecialize (\"HΦcI\" with \"[$]\"). iLeft in \"HΦ\". iApply \"HΦ\". eauto. }\n  remember 0 as z.\n  iRename \"Hi0\" into \"Hiz\".\n  assert (0 <= z <= int.Z s.(Slice.sz)) by word.\n  iDestruct (is_slice_small_sz with \"Hs\") as %Hslen.\n  autorewrite with len in Hslen.\n  clear Heqz; generalize dependent z.\n  intros z Hzrange.\n  assert (int.Z (U64 z) = z) by (rewrite /U64; word).\n  (iLöb as \"IH\" forall (z Hzrange H)).\n  wpc_if_destruct.\n  - wpc_pures.\n    { iSpecialize (\"HΦcI\" with \"[$]\"). iLeft in \"HΦ\". iApply \"HΦ\". eauto. }\n    destruct (list_lookup_Z_lt vs z) as [xz Hlookup]; first word.\n    wpc_apply (wpc_SliceGet with \"[$Hs] [HΦ Hiz]\").\n    { replace (int.Z z); eauto. }\n    { iSplit.\n      - iSpecialize (\"HΦcI\" with \"[$]\"). iLeft in \"HΦ\".\n        iIntros \"_\".\n        iApply (\"HΦ\" with \"[$]\").\n      - iIntros \"!> Hs\".\n        wpc_pures.\n        { iSpecialize (\"HΦcI\" with \"[$]\"). iLeft in \"HΦ\". iApply \"HΦ\". eauto. }\n        wpc_apply (\"Hind\" with \"[Hiz]\").\n        + iFrame.\n          iPureIntro.\n          split; try lia.\n          replace (int.nat z) with (Z.to_nat z) by lia; auto.\n        + iSplit; crash_case.\n          { iLeft in \"HΦ\"; iFrame. }\n          iIntros \"!> Hiz1\".\n          wpc_pures.\n          { iSpecialize (\"HΦcI\" with \"[$]\"). iLeft in \"HΦ\". iApply \"HΦ\". eauto. }\n          assert (int.Z (z + 1) = int.Z z + 1) by word.\n          replace (word.add z 1) with (U64 (z + 1)) by word.\n          iSpecialize (\"IH\" $! (z+1) with \"[] []\").\n          { iPureIntro; word. }\n          { iPureIntro; word. }\n          wpc_apply (\"IH\" with \"[$] [$] [$]\"). }\n  - assert (z = int.Z s.(Slice.sz)) by lia; subst z.\n    wpc_pures; swap 2 3.\n    { iSpecialize (\"HΦcI\" with \"[$]\"). iLeft in \"HΦ\". iApply \"HΦ\". eauto. }\n    { iSpecialize (\"HΦcI\" with \"[$]\"). iLeft in \"HΦ\". iApply \"HΦ\". eauto. }\n    iRight in \"HΦ\".\n    replace (U64 (int.Z s.(Slice.sz))) with s.(Slice.sz); last first.\n    { rewrite /U64 word.of_Z_unsigned //. }\n    iApply (\"HΦ\" with \"[$]\").\nQed.\n\nEnd goose_lang.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/goose_lang/lib/slice/crash_slice.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2401973822680529}}
{"text": "Require Import Coqlib.\nRequire Import ITreelib.\nRequire Import ImpPrelude.\nRequire Import STS.\nRequire Import Behavior.\nRequire Import ModSem.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import HoareDef STB IPM.\nRequire Import MapHeader.\n\nSet Implicit Arguments.\n\n\n(*** module A Map\nprivate map := (fun k => 0)\n\ndef init(sz: int) ≡\n  skip\n\ndef get(k: int): int ≡\n  return map[k]\n\ndef set(k: int, v: int) ≡\n  map := map[k ← v]\n\ndef set_by_user(k: int) ≡\n  set(k, input())\n***)\n\nSection A.\n  Context `{@GRA.inG MapRA0 Σ}.\n  Context `{@GRA.inG MapRA1 Σ}.\n\n  Let Es := (hAPCE +' Es).\n\n  Definition initF: list val -> itree Es val :=\n    fun varg =>\n      ;;;\n      Ret Vundef\n  .\n\n  Definition setF: list val -> itree Es val :=\n    fun varg =>\n      '(k, v) <- (pargs [Tint; Tint] varg)?;;\n      f <- pget;;\n      _ <- pput (fun n => if Z.eq_dec n k then v else f n);;;\n      Ret Vundef\n  .\n\n  Definition getF: list val -> itree Es val :=\n    fun varg =>\n      k <- (pargs [Tint] varg)?;;\n      f <- pget;;;\n      Ret (Vint (f k))\n  .\n\n  Definition set_by_userF: list val -> itree Es val :=\n    fun varg =>\n      k <- (pargs [Tint] varg)?;;\n      v <- trigger (Syscall \"input\" (([]: list Z)↑) (fun _ => True));; v <- v↓?;;\n      ccallU \"set\" [Vint k; Vint v]\n  .\n\n  Definition MapSbtb: list (string * fspecbody) :=\n    [(\"init\", mk_specbody init_spec (cfunU initF));\n     (\"get\", mk_specbody get_spec (cfunU getF));\n     (\"set\", mk_specbody set_spec (cfunU setF));\n     (\"set_by_user\", mk_specbody set_by_user_spec (cfunU set_by_userF))].\n\n  Definition SMapSem: SModSem.t := {|\n    SModSem.fnsems := MapSbtb;\n    SModSem.mn := \"Map\";\n    SModSem.initial_mr := GRA.embed (Excl.unit, Auth.excl ((fun _ => Excl.just 0%Z): @URA.car (Z ==> (Excl.t Z))%ra) ((fun _ => Excl.just 0%Z): @URA.car (Z ==> (Excl.t Z))%ra));\n    SModSem.initial_st := (fun (_: Z) => 0%Z)↑;\n  |}\n  .\n\n  Definition SMap: SMod.t := {|\n    SMod.get_modsem := fun _ => SMapSem;\n    SMod.sk := [(\"init\", Sk.Gfun); (\"get\", Sk.Gfun); (\"set\", Sk.Gfun); (\"set_by_user\", Sk.Gfun)];\n  |}\n  .\n\n  Variable GlobalStb: Sk.t -> gname -> option fspec.\n  Definition Map: Mod.t := (SMod.to_tgt GlobalStb SMap).\nEnd A.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/map/MapA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2401973761644582}}
{"text": "From Perennial.program_proof Require Import grove_prelude.\nFrom iris.base_logic Require Export lib.ghost_var.\nFrom Perennial.program_proof.grove_shared Require Import urpc_proof urpc_spec.\nFrom Goose.github_com.mit_pdos.gokv Require Import tutorial.\n\nModule decision.\n  Inductive t := Unknown | Commit | Abrt.\n  Definition is_byte (x:t) (b: u8) :=\n    match x with\n    | Unknown => b = U8 0\n    | Commit => b = U8 1\n    | Abrt => b = U8 2\n    end.\nEnd decision.\n\n(* PLAN:\n\n- start by giving the participant a spec\n- will have a single piece of ghost state for the global preferences\n\nOne gname for each participant\nparticipant ghost state is a single agree(bool) for its preference\n\nalso a global decision ghost variable that reflects all of the preferences\n\nThree parallel lists at the coordinator:\n- physical list of decisions\n- physical list of participant clerks\n- ghost list of participant gnames\n\ncoordinator's one-shot decision\n\n *)\n\nModule global_names.\n  Record t :=\n    mk { decision: gname; }.\nEnd global_names.\n\nModule participant_names.\n  Record t :=\n    mk { preference: gname;\n         urpc: server_chan_gnames; }.\nEnd participant_names.\n\nModule coordinator_names.\n  Record t :=\n    mk { participants: list gname;\n         globals: global_names.t;\n        }.\nEnd coordinator_names.\n\nSection iris.\n  Context `{!heapGS Σ}.\n  Context `{!urpcregG Σ}.\n  Context `{inG Σ (agreeR boolO)}.\n\n  Definition is_preference (γ: participant_names.t) (pref: bool) : iProp Σ :=\n    own γ.(participant_names.preference) (to_agree pref).\n\n  Definition is_decision (γ: coordinator_names.t) (decision: bool) : iProp Σ :=\n    own γ.(coordinator_names.globals).(global_names.decision) (to_agree decision).\n\n  Program Definition GetPreference_spec (γ: participant_names.t)\n    : list u8 → (list u8 -d> iProp Σ) -d> iProp Σ :=\n    λ reqData, λne (Φ: list u8 -d> iPropO Σ),\n      (* ignore request *)\n      (∀ (pref: bool), is_preference γ pref -∗\n      Φ (if pref then [U8 1] else [U8 0]))%I.\n  Next Obligation. solve_proper. Defined.\n\n  Definition is_participant_host (γ: participant_names.t) (host:u64) : iProp Σ :=\n    \"#H0\" ∷ handler_spec γ.(participant_names.urpc) host (U64 0) (GetPreference_spec γ) ∗\n    \"#Hdom\" ∷ handlers_dom γ.(participant_names.urpc) {[ (U64 0) ]}.\n\n  Definition is_participant_clerk (ck: loc) (γ: participant_names.t) : iProp Σ :=\n    ∃ (cl:loc) host,\n      \"#client\" ∷ readonly (ck ↦[ParticipantClerk :: \"client\"] #cl) ∗\n      \"#Hhost\" ∷ is_participant_host γ host ∗\n      \"#His_cl\" ∷ is_uRPCClient cl host.\n\n  Lemma wp_byteToPref (n: u8) :\n    {{{ True }}}\n      byteToPref #n\n    {{{ (pref: bool), RET #pref; ⌜if decide (int.Z n = 1)%Z then pref = true else pref = false⌝ }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\".\n    wp_lam.\n    wp_pures.\n    iModIntro.\n    iApply \"HΦ\".\n    iPureIntro.\n    destruct (decide _); subst.\n    - rewrite bool_decide_eq_true //.\n      f_equal.\n      f_equal.\n      admit.\n    - rewrite bool_decide_eq_false //.\n      admit.\n  Admitted.\n\n  Lemma wp_ParticipantClerk_GetPreference ck γ :\n    is_participant_clerk ck γ -∗\n    {{{ True }}}\n      ParticipantClerk__GetPreference #ck\n    {{{ (pref: bool), RET #pref;\n        is_preference γ pref\n    }}}.\n  Proof.\n    iIntros \"#Hclerk\".\n    iIntros (Φ) \"!> _ HΦ\".\n\n    wp_lam.\n\n    wp_apply (wp_frame_wand with \"HΦ\").\n\n    wp_apply wp_NewSlice. iIntros (req_s) \"Hreq\".\n    wp_pures.\n    wp_apply wp_NewSlice. iIntros (reply_s) \"Hreply\".\n    rewrite replicate_0.\n    wp_apply wp_ref_to.\n    { val_ty. }\n    iIntros (reply_l) \"Hreply_l\".\n    wp_pures.\n    iNamed \"Hclerk\".\n    wp_loadField.\n\n    wp_apply (wp_Client__Call2 with \"[] [] [Hreq] Hreply_l\").\n    { iFrame \"#\". }\n    { iNamed \"Hhost\".\n      iFrame \"#\". }\n    { iApply (is_slice_to_small with \"Hreq\"). }\n    - iIntros \"!> !>\".\n      cbn.\n      iIntros (pref) \"#Hpref _\".\n      iIntros (?) \"reply_l Hrep_s\".\n      wp_step.\n      wp_apply wp_Assume.\n      iIntros \"_\". (* already true? *)\n      wp_step.\n      wp_load.\n      wp_apply (wp_SliceGet _ _ _ _ _ _ _ (U8 (if pref then 1 else 0)%Z) with \"[$Hrep_s]\").\n      { iPureIntro.\n        destruct pref; reflexivity. }\n      iIntros \"Hrep_s\".\n      wp_pures.\n\n      wp_apply wp_byteToPref.\n      iIntros (pref').\n      iIntros (Hpref').\n      iIntros \"HΦ\".\n      iApply \"HΦ\".\n\n      assert (pref = pref').\n      { (* U8/word nonsense *)\n        revert Hpref'. destruct (decide _), pref; auto; exfalso.\n        - admit. (* word failure; contradiction with e (after compute) *)\n        - admit. (* word failure; contradiction with e (after compute) *)\n      }\n\n      subst; iFrame \"#\".\n  Admitted.\n\n  Definition is_coord_clerk (ck: loc) (γ: coordinator_names.t) : iProp Σ := True.\n\n  Lemma wp_CoordinatorClerk_GetDecision ck γ :\n    is_coord_clerk ck γ -∗\n    {{{ True }}}\n      CoordinatorClerk__GetDecision #ck\n    {{{ (decision: decision.t) (b: u8), RET #b;\n        ⌜decision.is_byte decision b⌝ ∗\n        match decision with\n        | decision.Commit => is_decision γ true\n        | decision.Abrt => is_decision γ false\n        | decision.Unknown => True\n        end\n    }}}.\n  Proof.\n  Admitted.\n\nEnd iris.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/atomic_commit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.24019737616445813}}
{"text": "From isla Require Import opsem.\n\nDefinition a7428 : isla_trace :=\n  Smt (DeclareConst 0%Z (Ty_BitVec 16%N)) Mk_annot :t:\n  Smt (DefineConst 150%Z (Manyop (Bvmanyarith Bvor) [Val (Val_Bits (BV 64%N 0x0%Z)) Mk_annot; Unop (ZeroExtend 48%N) (Val (Val_Symbolic 0%Z) Mk_annot) Mk_annot] Mk_annot)) Mk_annot :t:\n  WriteReg \"R6\" [] (RegVal_Base (Val_Symbolic 150%Z)) Mk_annot :t:\n  Smt (DeclareConst 151%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 151%Z)) Mk_annot :t:\n  Smt (DefineConst 152%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 151%Z) Mk_annot; Val (Val_Bits (BV 64%N 0x4%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n  WriteReg \"_PC\" [] (RegVal_Base (Val_Symbolic 152%Z)) Mk_annot :t:\n  tnil\n.\n", "meta": {"author": "rems-project", "repo": "islaris", "sha": "fcc5791c74a2f791dee9080263cd64e42e73bc39", "save_path": "github-repos/coq/rems-project-islaris", "path": "github-repos/coq/rems-project-islaris/islaris-fcc5791c74a2f791dee9080263cd64e42e73bc39/pkvm_handler/a7428.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24019737006086328}}
{"text": "Require Import Recdef.\nRequire Import VST.floyd.proofauto.\nLocal Open Scope logic.\nRequire Import List. Import ListNotations.\nRequire Import sha.general_lemmas.\nRequire Import ZArith.\nRequire Import tweetnacl20140427.Salsa20.\nRequire Import tweetnacl20140427.tweetNaclBase.\nRequire Import tweetnacl20140427.verif_salsa_base.\n\nRequire Import tweetnacl20140427.tweetnaclVerifiableC.\nRequire Import tweetnacl20140427.Snuffle.\nRequire Import VST.floyd.library.\n\nDefinition CoreInSEP (data : SixteenByte * SixteenByte * (SixteenByte * SixteenByte))\n                     (v: val * val * val) : mpred :=\n  match data with (Nonce, C, K) =>\n  match v with (n, c, k) =>\n   (SByte Nonce n) * (SByte C c) * (ThirtyTwoByte K k)\n  end end.\n\nDefinition prepare_data\n           (data : SixteenByte * SixteenByte * (SixteenByte * SixteenByte)) :=\nmatch data with ((Nonce, C), K) =>\n  match Nonce with (N1, N2, N3, N4) =>\n  match C with (C1, C2, C3, C4) =>\n  match K with ((K1, K2, K3, K4), (L1, L2, L3, L4)) =>\n      map littleendian [C1; K1; K2; K3; K4; C2; N1; N2; N3; N4; C3; L1; L2; L3; L4; C4]\n  end end end\nend.\n\nLemma prepare_data_length x: length (prepare_data x) = 16%nat.\nProof. destruct x as [[s0 s1] [s2 s3]]. simpl.\n  destruct s0 as [[[? ?] ?] ?].\n  destruct s1 as [[[? ?] ?] ?].\n  destruct s2 as [[[? ?] ?] ?].\n  destruct s3 as [[[? ?] ?] ?]. reflexivity.\nQed.\n\nDefinition sumlist := combinelist _ Int.add.\n\nDefinition sumlist_Some:= combinelist _ Int.add.\n\nDefinition sumlist_SomeInv:= combinelist_SomeInv _ Int.add.\n\nDefinition sumlist_length:= combinelist_length _ Int.add.\n\nDefinition sumlist_symm:= combinelist_symm _ Int.add Int.add_commut.\n\nDefinition sumlist_char_nth:= combinelist_char_nth _ Int.add.\n\nDefinition sumlist_char_Znth:= combinelist_char_Znth _ Int.add.\n\nDefinition Snuffle20 x := bind (Snuffle 20 x) (fun y => sumlist y x).\n\nLemma Snuffle20_length s l: Snuffle20 s = Some l -> length s = 16%nat -> length l = 16%nat.\nProof. unfold Snuffle20, bind; intros. remember (Snuffle 20 s).\n  destruct o; simpl.\n    symmetry in Heqo. symmetry in H; rewrite sumlist_symm in H.\n      rewrite (sumlist_length _ _ _ H).\n      apply (Snuffle_length _ _ _ Heqo H0). inv H.\nQed.\n\nDefinition fcore_result h data l :=\n  match Snuffle20 (prepare_data data)\n  with None => False\n     | Some x =>\n             if Int.eq (Int.repr h) Int.zero\n             then l=QuadChunks2ValList (map littleendian_invert x)\n             else match data with ((Nonce, C), K) =>\n                    match Nonce with (N1, N2, N3, N4) =>\n                    match C with (C1, C2, C3, C4) =>\n                    l = QuadByte2ValList (littleendian_invert (Int.sub (Znth 0 x)  (littleendian C1))) ++\n                    QuadByte2ValList (littleendian_invert (Int.sub (Znth 5 x)  (littleendian C2))) ++\n                    QuadByte2ValList (littleendian_invert (Int.sub (Znth 10 x) (littleendian C3))) ++\n                    QuadByte2ValList (littleendian_invert (Int.sub (Znth 15 x) (littleendian C4))) ++\n                    QuadByte2ValList (littleendian_invert (Int.sub (Znth 6 x)  (littleendian N1))) ++\n                    QuadByte2ValList (littleendian_invert (Int.sub (Znth 7 x)  (littleendian N2))) ++\n                    QuadByte2ValList (littleendian_invert (Int.sub (Znth 8 x)  (littleendian N3))) ++\n                    QuadByte2ValList (littleendian_invert (Int.sub (Znth 9 x)  (littleendian N4)))\n                    end end end\n  end.\n\nDefinition OutLen h := if Int.eq (Int.repr h) Int.zero then 64 else 32.\n\nDefinition fcorePOST_SEP h data d l out :=\n  CoreInSEP data d *\n  data_at Tsh (tarray tuchar (OutLen h)) l out.\n\nDefinition f_core_POST d out h (data: SixteenByte * SixteenByte * (SixteenByte * SixteenByte) ) :=\nEX l:_,\n   PROP (fcore_result h data l)\n   LOCAL ()\n   SEP (fcorePOST_SEP h data d l out).\n\nDefinition core_spec :=\n  DECLARE _core\n   WITH c : val, k:val, h:Z,\n        nonce:val, out:val, OUT:list val,\n        data : SixteenByte * SixteenByte * (SixteenByte * SixteenByte)\n   PRE [ _out OF tptr tuchar,\n         _in OF tptr tuchar,\n         _k OF tptr tuchar,\n         _c OF tptr tuchar,\n         _h OF tint ]\n      PROP ()\n      LOCAL (temp _in nonce; temp _out out;\n             temp _c c; temp _k k; temp _h (Vint (Int.repr h)))\n      SEP (CoreInSEP data (nonce, c, k);\n           data_at Tsh (tarray tuchar (OutLen h)) OUT out)\n  POST [ tvoid ] (f_core_POST (nonce, c, k) out h data).\n\nDefinition ld32_spec :=\n  DECLARE _ld32\n   WITH x : val, B:QuadByte\n   PRE [ _x OF tptr tuchar ]\n      PROP ()\n      LOCAL (temp _x x)\n      SEP (data_at Tsh (tarray tuchar 4) (QuadByte2ValList B) x)\n  POST [ tuint ] \n     PROP ()\n     LOCAL (temp ret_temp (Vint (littleendian B)))\n     SEP (QByte B x).\n\nDefinition st32_spec :=\n  DECLARE _st32\n   WITH x : val, u:int\n   PRE [ _x OF tptr tuchar, _u OF tuint ]\n      PROP ()\n      LOCAL (temp _x x; temp _u (Vint u))\n      SEP (data_at_ Tsh (tarray tuchar 4) x)\n  POST [ tvoid ] \n     PROP ()\n     LOCAL ()\n     SEP (QByte (littleendian_invert u) x).\n\nDefinition L32_spec :=\n  DECLARE _L32\n   WITH x : int, c: int\n   PRE [ _x OF tuint, _c OF tint ]\n      PROP (0 < Int.signed c < 32) (*yes, c=Int.zero needs to be ruled out - it leads to undefined behaviour in the shift-right operation*)\n      LOCAL (temp _x (Vint x); temp _c (Vint c))\n      SEP ()\n  POST [ tuint ]\n     PROP ()\n     LOCAL (temp ret_temp (Vint (Int.rol x c)))\n     SEP ().\n\nDefinition bigendian64 (b c:QuadByte): int64 :=\n  match b, c with (b0, b1, b2, b3), (c0, c1, c2, c3) =>\n  Int64.repr\n   (       Byte.unsigned c3 +\n    2^8  * Byte.unsigned c2 +\n    2^16 * Byte.unsigned c1 +\n    2^24 * Byte.unsigned c0 +\n    2^32 * Byte.unsigned b3 +\n    2^40 * Byte.unsigned b2 +\n    2^48 * Byte.unsigned b1 +\n    2^56 * Byte.unsigned b0\n    )\n  end.\n\nDefinition dl64_spec :=\n  DECLARE _dl64\n   WITH x : val, B:QuadByte, C: QuadByte\n   PRE [ _x OF tptr tuchar ]\n      PROP ()\n      LOCAL (temp _x x)\n      SEP (data_at Tsh (tarray tuchar 8) (QuadByte2ValList B++QuadByte2ValList C) x)\n  POST [ tulong ] \n     PROP ()\n     LOCAL (temp ret_temp (Vlong (bigendian64 B C)))\n     SEP (data_at Tsh (tarray tuchar 8) (QuadByte2ValList B++QuadByte2ValList C) x).\n\nDefinition bigendian64_invert (w:int64) : QuadByte * QuadByte:=\n    let w3 := Int64.unsigned w in\n  let b3 := w3 / (2^56) in \n    let w2 := Z.modulo w3 (2^56) in\n  let b2 := w2 / (2^48) in \n    let w1 := Z.modulo w2 (2^48) in\n  let b1 := w1 / (2^40) in \n    let w0 := Z.modulo w1 (2^40) in\n  let b0 := w0 / (2^32) in \n    let u3 := Z.modulo w0 (2^32) in\n  let c3 := u3 / (2^24) in \n    let u2 := Z.modulo u3 (2^24) in\n  let c2 := u2 / (2^16) in \n    let u1 := Z.modulo u2 (2^16) in\n  let c1 := u1 / (2^8) in\n    let c0 := Z.modulo u1 (2^8) in\n  ((Byte.repr b3, Byte.repr b2, Byte.repr b1, Byte.repr b0), \n   (Byte.repr c3, Byte.repr c2, Byte.repr c1, Byte.repr c0)).\n\nLemma bigendian64_inv: forall b c: QuadByte, bigendian64_invert (bigendian64 b c) = (b,c).\nProof. destruct b as [[[b3 b2] b1] b0]. destruct c as [[[c3 c2] c1] c0].\n  unfold bigendian64_invert, bigendian64.\n  destruct (Byte.unsigned_range_2 b0). destruct (Byte.unsigned_range_2 b1).\n  destruct (Byte.unsigned_range_2 b2). destruct (Byte.unsigned_range_2 b3).\n  destruct (Byte.unsigned_range_2 c0). destruct (Byte.unsigned_range_2 c1).\n  destruct (Byte.unsigned_range_2 c2). destruct (Byte.unsigned_range_2 c3).\n  assert (2 ^ 8 * Byte.unsigned c1 <= 2 ^ 8 * Byte.max_unsigned).\n               apply Zmult_le_compat_l; trivial.\n  assert (2 ^ 16 * Byte.unsigned c2 <= 2 ^ 16 * Byte.max_unsigned).\n               apply Zmult_le_compat_l; trivial.\n  assert (2 ^ 24 * Byte.unsigned c3 <= 2 ^ 24 * Byte.max_unsigned).\n               apply Zmult_le_compat_l; trivial.\n  assert (2 ^ 32 * Byte.unsigned b0 <= 2 ^ 32 * Byte.max_unsigned).\n               apply Zmult_le_compat_l; trivial.\n  assert (2 ^ 40 * Byte.unsigned b1 <= 2 ^ 40 * Byte.max_unsigned).\n               apply Zmult_le_compat_l; trivial.\n  assert (2 ^ 48 * Byte.unsigned b2 <= 2 ^ 48 * Byte.max_unsigned).\n               apply Zmult_le_compat_l; trivial.\n  assert (2 ^ 56 * Byte.unsigned b3 <= 2 ^ 56 * Byte.max_unsigned).\n               apply Zmult_le_compat_l; trivial.\n  assert (0 <= 2 ^ 8 * Byte.unsigned c1). apply Z.mul_nonneg_cancel_l; trivial.\n  assert (0 <= 2 ^ 16 * Byte.unsigned c2). apply Z.mul_nonneg_cancel_l; trivial.\n  assert (0 <= 2 ^ 24 * Byte.unsigned c3). apply Z.mul_nonneg_cancel_l; trivial. \n  assert (0 <= 2 ^ 32 * Byte.unsigned b0). apply Z.mul_nonneg_cancel_l; trivial.\n  assert (0 <= 2 ^ 40 * Byte.unsigned b1). apply Z.mul_nonneg_cancel_l; trivial.\n  assert (0 <= 2 ^ 48 * Byte.unsigned b2). apply Z.mul_nonneg_cancel_l; trivial. \n  assert (0 <= 2 ^ 56 * Byte.unsigned b3). apply Z.mul_nonneg_cancel_l; trivial. \n  rewrite Int64.unsigned_repr.\n  2:{ split. clear H0 H2 H4 H6 H8 H10 H12 H14.\n             apply OMEGA2; trivial.\n             apply OMEGA2; trivial.\n             apply OMEGA2; trivial.\n             apply OMEGA2; trivial.\n             apply OMEGA2; trivial.\n             apply OMEGA2; trivial.\n             apply OMEGA2; trivial.\n            eapply Z.le_trans. apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption.\n              apply Z.add_le_mono; try eassumption.  \n              apply Z.add_le_mono; eassumption.\n            unfold Int64.max_unsigned; simpl. omega.\n  }\n  assert (0 <= Byte.unsigned c0 + 2 ^ 8 * Byte.unsigned c1 + 2 ^ 16 * Byte.unsigned c2 +\n          2 ^ 24 * Byte.unsigned c3 + 2 ^ 32 * Byte.unsigned b0 + 2 ^ 40 * Byte.unsigned b1 +\n          2 ^ 48 * Byte.unsigned b2 < 2 ^ 56). \n              split. apply OMEGA2; trivial. apply OMEGA2; trivial. apply OMEGA2; trivial. apply OMEGA2; trivial. apply OMEGA2; trivial. apply OMEGA2; trivial.\n              assert (Byte.unsigned c0 + 2 ^ 8 * Byte.unsigned c1 + 2 ^ 16 * Byte.unsigned c2 \n                      + 2 ^ 24 * Byte.unsigned c3 + 2 ^ 32 * Byte.unsigned b0 \n                      + 2 ^ 40 * Byte.unsigned b1 + 2 ^ 48 * Byte.unsigned b2 <= 2 ^ 56 -1). 2: omega.\n              eapply Z.le_trans. apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption. apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption. apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption. simpl. omega.\n  erewrite (Zmod_unique _ (2^56) (Byte.unsigned b3)); try eassumption.\n     2:{ rewrite (Z.mul_comm (2^56)). rewrite Z.add_comm. reflexivity. }\n  assert (0 <= Byte.unsigned c0 + 2 ^ 8 * Byte.unsigned c1 + 2 ^ 16 * Byte.unsigned c2 +\n          2 ^ 24 * Byte.unsigned c3 + 2 ^ 32 * Byte.unsigned b0 + 2 ^ 40 * Byte.unsigned b1 < 2 ^ 48). \n              split. apply OMEGA2; trivial. apply OMEGA2; trivial. apply OMEGA2; trivial. apply OMEGA2; trivial. apply OMEGA2; trivial. \n              assert (Byte.unsigned c0 + 2 ^ 8 * Byte.unsigned c1 + 2 ^ 16 * Byte.unsigned c2 \n                      + 2 ^ 24 * Byte.unsigned c3 + 2 ^ 32 * Byte.unsigned b0 \n                      + 2 ^ 40 * Byte.unsigned b1 <= 2 ^ 48 -1). 2: omega.\n              eapply Z.le_trans. apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption. apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption. apply Z.add_le_mono; try eassumption. simpl. omega. \n  erewrite (Zmod_unique _ (2^48) (Byte.unsigned b2)); try eassumption.\n     2:{ rewrite (Z.mul_comm (2^48)). rewrite Z.add_comm. reflexivity. }\n  assert (0 <= Byte.unsigned c0 + 2 ^ 8 * Byte.unsigned c1 + 2 ^ 16 * Byte.unsigned c2 +\n          2 ^ 24 * Byte.unsigned c3 + 2 ^ 32 * Byte.unsigned b0 < 2 ^ 40). \n              split. apply OMEGA2; trivial. apply OMEGA2; trivial.  apply OMEGA2; trivial.  apply OMEGA2; trivial.\n              assert (Byte.unsigned c0 + 2 ^ 8 * Byte.unsigned c1 + 2 ^ 16 * Byte.unsigned c2 \n                      + 2 ^ 24 * Byte.unsigned c3 + 2 ^ 32 * Byte.unsigned b0 <= 2 ^ 40 -1). 2: omega.\n              eapply Z.le_trans. apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption. apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption. simpl. omega.\n  erewrite (Zmod_unique _ (2^40) (Byte.unsigned b1)); try eassumption.\n     2:{ rewrite (Z.mul_comm (2^40)). rewrite Z.add_comm. reflexivity. }\n  assert (0 <= Byte.unsigned c0 + 2 ^ 8 * Byte.unsigned c1 + 2 ^ 16 * Byte.unsigned c2 +\n          2 ^ 24 * Byte.unsigned c3 < 2 ^ 32). \n              split. apply OMEGA2; trivial. apply OMEGA2; trivial. apply OMEGA2; trivial.\n              assert (Byte.unsigned c0 + 2 ^ 8 * Byte.unsigned c1 + 2 ^ 16 * Byte.unsigned c2 \n                      + 2 ^ 24 * Byte.unsigned c3 <= 2 ^ 32 -1). 2: omega.\n              eapply Z.le_trans. apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption. apply Z.add_le_mono; try eassumption. simpl. omega.\n  erewrite (Zmod_unique _ (2^32) (Byte.unsigned b0)); try eassumption.\n     2:{ rewrite (Z.mul_comm (2^32)). rewrite Z.add_comm. reflexivity. }\n  assert (0 <= Byte.unsigned c0 + 2 ^ 8 * Byte.unsigned c1 + 2 ^ 16 * Byte.unsigned c2 < 2 ^ 24). \n              split. apply OMEGA2; trivial. apply OMEGA2; trivial.\n              assert (Byte.unsigned c0 + 2 ^ 8 * Byte.unsigned c1 + 2 ^ 16 * Byte.unsigned c2 <= 2 ^ 24 -1). 2: omega.\n              eapply Z.le_trans. apply Z.add_le_mono; try eassumption. \n              apply Z.add_le_mono; try eassumption. simpl. omega.\n  erewrite (Zmod_unique _ (2^24) (Byte.unsigned c3)); try eassumption.\n     2:{ rewrite (Z.mul_comm (2^24)). rewrite Z.add_comm. reflexivity. }\n  assert (0 <= Byte.unsigned c0 + 2 ^ 8 * Byte.unsigned c1 < 2 ^ 16).\n             split. apply OMEGA2; trivial.\n              assert (Byte.unsigned c0 + 2 ^ 8 * Byte.unsigned c1 <= 2 ^ 16 -1). 2: omega.\n              eapply Z.le_trans. apply Z.add_le_mono; try eassumption. \n              simpl. omega.\n  erewrite (Zmod_unique _ (2^16) (Byte.unsigned c2)); try eassumption.\n     2:{ rewrite (Z.mul_comm (2^16)). rewrite Z.add_comm. reflexivity. }\n  erewrite (Zmod_unique _ (2^8) (Byte.unsigned c1)).\n     2:{ rewrite (Z.mul_comm (2^8)). rewrite Z.add_comm. reflexivity. }\n     2: apply Byte.unsigned_range. \n  erewrite (Zdiv_unique _ _ (Byte.unsigned b3));\n       [  | rewrite (Z.mul_comm (2^56)), Z.add_comm; reflexivity\n          | assumption ]. \n  rewrite Byte.repr_unsigned. \n  erewrite (Zdiv_unique _ _ (Byte.unsigned b2));\n       [  | rewrite (Z.mul_comm (2^48)), Z.add_comm; reflexivity\n          | assumption ]. \n  rewrite Byte.repr_unsigned. \n  erewrite (Zdiv_unique _ _ (Byte.unsigned b1));\n       [  | rewrite (Z.mul_comm (2^40)), Z.add_comm; reflexivity\n          | assumption ]. \n  rewrite Byte.repr_unsigned. \n  erewrite (Zdiv_unique _ _ (Byte.unsigned b0));\n       [  | rewrite (Z.mul_comm (2^32)), Z.add_comm; reflexivity\n          | assumption ]. \n  rewrite Byte.repr_unsigned. \n  erewrite (Zdiv_unique _ _ (Byte.unsigned c3));\n       [  | rewrite (Z.mul_comm (2^24)), Z.add_comm; reflexivity\n          | assumption ].\n  rewrite Byte.repr_unsigned. \n  erewrite (Zdiv_unique _ _ (Byte.unsigned c2));\n       [  | rewrite (Z.mul_comm (2^16)), Z.add_comm; reflexivity\n          | assumption ]. \n  rewrite Byte.repr_unsigned. \n  erewrite (Zdiv_unique _ _ (Byte.unsigned c1));\n       [  | rewrite (Z.mul_comm (2^8)), Z.add_comm; reflexivity\n          | ]. \n  rewrite Byte.repr_unsigned. \n  rewrite Byte.repr_unsigned. trivial.\n  apply Byte.unsigned_range. \nQed.\n\n\nDefinition ts64_spec :=\n  DECLARE _ts64\n   WITH x : val, u:int64\n   PRE [ _x OF tptr tuchar, _u OF tulong ]\n      PROP ()\n      LOCAL (temp _x x; temp _u (Vlong u))\n      SEP (data_at_ Tsh (tarray tuchar 8) x)\n  POST [ tvoid ] \n     PROP ()\n     LOCAL ()\n     SEP (let (B, C) := bigendian64_invert u in\n          data_at Tsh (tarray tuchar 8) (QuadByte2ValList B++QuadByte2ValList C) x).\n\n\nDefinition crypto_core_salsa20_spec :=\n  DECLARE _crypto_core_salsa20_tweet\n   WITH c : val, k:val,\n        nonce:val, out:val,\n        data : SixteenByte * SixteenByte * (SixteenByte * SixteenByte)\n   PRE [ _out OF tptr tuchar,\n         _in OF tptr tuchar,\n         _k OF tptr tuchar,\n         _c OF tptr tuchar ]\n      PROP ()\n      LOCAL (temp _in nonce; temp _out out;\n             temp _c c; temp _k k)\n      SEP ( CoreInSEP data (nonce, c, k);\n            data_at_ Tsh (tarray tuchar 64) out)\n  POST [ tint ]\n       EX res:_,\n       PROP (Snuffle20 (prepare_data data) = Some res)\n       LOCAL (temp ret_temp (Vint (Int.repr 0)))\n       SEP (CoreInSEP data (nonce, c, k);\n            data_at Tsh (tarray tuchar 64) (QuadChunks2ValList (map littleendian_invert res)) out).\n\nDefinition hSalsaOut x :=\n           QuadByte2ValList (littleendian_invert (Znth 0  x)) ++\n           QuadByte2ValList (littleendian_invert (Znth 5  x)) ++\n           QuadByte2ValList (littleendian_invert (Znth 10 x)) ++\n           QuadByte2ValList (littleendian_invert (Znth 15 x)) ++\n           QuadByte2ValList (littleendian_invert (Znth 6  x)) ++\n           QuadByte2ValList (littleendian_invert (Znth 7  x)) ++\n           QuadByte2ValList (littleendian_invert (Znth 8  x)) ++\n           QuadByte2ValList (littleendian_invert (Znth 9  x)).\n\nDefinition crypto_core_hsalsa20_spec :=\n  DECLARE _crypto_core_hsalsa20_tweet\n   WITH c : val, k:val,\n        nonce:val, out:val, OUT: list val,\n        data : SixteenByte * SixteenByte * (SixteenByte * SixteenByte)\n   PRE [ _out OF tptr tuchar,\n         _in OF tptr tuchar,\n         _k OF tptr tuchar,\n         _c OF tptr tuchar ]\n      PROP ()\n      LOCAL (temp _in nonce; temp _out out;\n             temp _c c; temp _k k)\n      SEP (CoreInSEP data (nonce, c, k);\n           data_at Tsh (tarray tuchar 32) OUT out)\n  POST [ tint ]\n       EX res:list int,\n       PROP (Snuffle 20 (prepare_data data) = Some res)\n       LOCAL (temp ret_temp (Vint (Int.repr 0)))\n       SEP (CoreInSEP data (nonce, c, k); data_at Tsh (tarray tuchar 32) (hSalsaOut res) out).\n\nParameter SIGMA: SixteenByte.\nDefinition Sigma_vector : val -> mpred :=\n  data_at Tsh (tarray tuchar 16) (SixteenByte2ValList SIGMA).\n\nFixpoint ZZ (zbytes: list byte) (n: nat): int * list byte :=\n  match n with\n   O => (Int.one, zbytes)\n  | S k => match ZZ zbytes k with (u,zb) =>\n             let v := (Int.unsigned u + (Byte.unsigned (Znth (Z.of_nat k+8) zb)))\n             in (Int.shru (Int.repr v) (Int.repr 8),\n                 upd_Znth (Z.of_nat k+8) zb (Byte.repr (Z.modulo v 256))) end\n\n  end.\n\nFixpoint ZCont (r: nat) (zcont: list byte): list byte :=\n  match r with\n     O => zcont\n   | S n => let zb := ZCont n zcont in\n            let zz := ZZ zb (8:nat) in snd zz\n  end.\n\nLemma ZCont0 bytes: ZCont O bytes = bytes. reflexivity. Qed.\nLemma ZContS bytes n: ZCont (S n) bytes = snd (ZZ (ZCont n bytes) 8). reflexivity. Qed.\n\nDefinition bytes_at x q i mbytes :=\nmatch x with\n  Vint _ => list_repeat (Z.to_nat i) (Byte.zero)\n| _ => sublist q (q+i) mbytes\nend.\n\n\nLemma Zlength_bytes_at x q i mbytes : 0<=q -> 0 <= i ->\n  q + i <= Zlength mbytes -> Zlength (bytes_at x q i mbytes) = i.\nProof. intros. destruct x; simpl; try rewrite Zlength_sublist; try omega.\n  rewrite Zlength_list_repeat; omega.\nQed.\n\nDefinition bxorlist := combinelist _ Byte.xor.\nDefinition Bl2VL (l: list byte) := map Vint (map Int.repr (map Byte.unsigned l)).\n\nDefinition message_at (mCont: list byte) (m:val): mpred :=\n  match m with\n    Vint i => !!(i=Int.zero) && emp\n  | Vptr b z => data_at Tsh (tarray tuchar (Zlength mCont)) (Bl2VL mCont) m\n  | _ => FF\n  end.\n\nInductive CONTENT SIGMA K (mInit:val) (mCont zbytes:list byte): nat -> list byte -> list byte -> Prop :=\n  CONT_zero: CONTENT SIGMA K mInit mCont  zbytes O zbytes nil\n| CONT_succ: forall n zN resN ,\n             CONTENT SIGMA K mInit mCont zbytes n zN resN ->\n             forall d,\n             SixteenByte2ValList d = Bl2VL (ZCont n zbytes) ->\n             forall snuff srbytes Xor,\n             Snuffle20 (prepare_data (d, SIGMA, K)) = Some snuff ->\n             QuadChunks2ValList (map littleendian_invert snuff) =\n                map Vint (map Int.repr (map Byte.unsigned srbytes)) ->\n             bxorlist (bytes_at mInit (Z.of_nat n * 64) 64 mCont) srbytes = Some Xor ->\n             CONTENT SIGMA K mInit mCont zbytes (S n) (snd (ZZ zN (8:nat))) (resN++Xor).\n\nLemma CONT_Zlength SIGMA K mInit mCont zbytes:\n  forall n zB x,\n   CONTENT SIGMA K mInit mCont zbytes n zB x ->\n   Zlength x = (Z.of_nat n * 64)%Z.\nProof.\n  induction n; intros; inv H. reflexivity.\n  rewrite Zlength_app. erewrite IHn. 2: eassumption.\n  unfold bxorlist in H5.\n  apply combinelist_Zlength in H5. destruct H5. rewrite H, <- H0; clear H H0.\n  apply Snuffle20_length in H3.\n  specialize (QuadChunk2ValList_ZLength(map littleendian_invert snuff)).\n  rewrite H4; clear H4. repeat rewrite Zlength_map. intros H; rewrite H; clear H.\n  rewrite Zlength_correct, H3; clear H3. simpl.\n  rewrite Pos2Z.inj_mul, Zpos_P_of_succ_nat, <- Zmult_succ_l_reverse. trivial.\n  apply prepare_data_length.\nQed.\n\nLemma CONTCONT SIGMA K mInit mCont zbytes:\n  forall n zB x,\n   CONTENT SIGMA K mInit mCont zbytes n zB x ->\n   ZCont n zbytes = zB.\nProof.\n  induction n; intros; inv H.\n  apply ZCont0.\n  rewrite ZContS. erewrite IHn. 2: eassumption. trivial.\nQed.\n\nLemma ZZ_Zlength: forall n zbytes u U, ZZ zbytes n = (u,U) ->\n      Zlength zbytes=16 -> Z.of_nat n <= 8 -> Zlength U = 16.\nProof. induction n; simpl; intros.\n+ inv H. trivial.\n+ remember (ZZ zbytes n). destruct p. symmetry in Heqp. inv H.\n  rewrite Zpos_P_of_succ_nat in H1.\n  apply IHn in Heqp; trivial; clear IHn.\n  rewrite upd_Znth_Zlength; trivial.\n  omega.\n  omega.\nQed.\n\nLemma Zlength_ZCont: forall n zbytes, Zlength zbytes = 16 -> Zlength (ZCont n zbytes) = 16.\nProof.\n  induction n; intros. rewrite ZCont0. trivial.\n  rewrite ZContS. specialize (ZZ_Zlength 8 (ZCont n zbytes)); intros.\n  remember (ZZ (ZCont n zbytes) 8). destruct p; simpl.\n  apply (H0 _ _ (eq_refl _ )).\n  apply IHn; trivial. simpl; omega.\nQed.\n\nLemma SixteenByte2ValList_exists bytes: Zlength bytes = 16 ->\n  exists d, SixteenByte2ValList d = map Vint (map Int.repr (map Byte.unsigned bytes)).\nProof. intros.\n  apply listD16 in H.\n  destruct H as [v0 [v1 [v2 [v3 [v4 [v5 [v6 [v7 [v8\n        [v9 [v10 [v11 [v12 [v13 [v14 [v15 V]]]]]]]]]]]]]]]].\n  subst; simpl.\n  exists ((v0, v1, v2, v3), (v4, v5, v6, v7), (v8, v9, v10, v11), (v12, v13, v14, v15)).\n  rewrite SixteenByte2ValList_char. reflexivity.\nQed.\n\nDefinition ContSpec bInit SIGMA K mInit mCont zbytes  srbytes :=\n    let n:= (Int64.unsigned bInit) / 64 in\n    if zeq ((Int64.unsigned bInit) mod 64) 0\n    then exists zbytesR, CONTENT SIGMA K mInit mCont zbytes (Z.to_nat n) zbytesR srbytes\n    else exists zN resN d snuff bytes lastbytes(*zbytes*),\n         CONTENT SIGMA K mInit mCont zbytes (Z.to_nat n) zN resN /\\\n             SixteenByte2ValList d = Bl2VL (ZCont (Z.to_nat n) zbytes) /\\\n             Snuffle20 (prepare_data (d, SIGMA, K)) = Some snuff /\\\n             QuadChunks2ValList (map littleendian_invert snuff) =\n                map Vint (map Int.repr (map Byte.unsigned bytes)) /\\\n             bxorlist (bytes_at mInit (n * 64) ((Int64.unsigned bInit) mod 64) mCont)\n                                (sublist 0 ((Int64.unsigned bInit) mod 64) bytes) = Some lastbytes /\\\n             (*zbytesR = (snd (ZZ zN (8:nat)))/\\*) srbytes = (resN++lastbytes).\n\n(*TODO: refine non-zero-case of this spec, relating COUT to mCont and K and Nonce*)\nDefinition crypto_stream_xor_postsep b (Nonce:SixteenByte) K mCont cLen nonce c m :=\n  (if Int64.eq b Int64.zero\n   then data_at_ Tsh (Tarray tuchar cLen noattr) c\n   else (EX COUT:_, !!(exists zbytes, match Nonce with (Nnc0, Nnc1, _, _) =>\n                SixteenByte2ValList\n                  (Nnc0, Nnc1, (Byte.zero, Byte.zero, Byte.zero, Byte.zero),\n                           (Byte.zero, Byte.zero, Byte.zero, Byte.zero)) =\n                map Vint (map Int.repr (map Byte.unsigned zbytes))\n                /\\  ContSpec b SIGMA K m mCont zbytes COUT end)\n           && data_at Tsh (Tarray tuchar cLen noattr) (Bl2VL COUT) c))\n                    * SByte Nonce nonce\n                    * message_at mCont m.\n\n(*Precondition length mCont = Int64.unsigned b comes from textual spec in\n  https://download.libsodium.org/doc/advanced/salsa20.html\n  TODO: support the following part of the tetxual spec:\n      m and c can point to the same address (in-place encryption/decryption).\n     If they don't, the regions should not overlap.*)\nDefinition crypto_stream_salsa20_xor_spec :=\n  DECLARE _crypto_stream_salsa20_tweet_xor\n   WITH c : val, k:val, m:val, nonce:val, b:int64,\n        Nonce : SixteenByte, K: SixteenByte * SixteenByte,\n        mCont: list byte, gv: globals\n   PRE [ _c OF tptr tuchar, _m OF tptr tuchar, _b OF tulong,\n         _n OF tptr tuchar, _k OF tptr tuchar]\n      PROP (Zlength mCont = Int64.unsigned b)\n      LOCAL (temp _c c; temp _m m; temp _b (Vlong b);\n             temp _n nonce; temp _k k; gvars gv)\n      SEP ( SByte Nonce nonce;\n            data_at_ Tsh (Tarray tuchar (Int64.unsigned b) noattr) c;\n            ThirtyTwoByte K k;\n            Sigma_vector (gv _sigma);\n            message_at mCont m\n            (*data_at Tsh (tarray tuchar (Zlength mCont)) (Bl2VL mCont) m*))\n  POST [ tint ]\n       PROP ()\n       LOCAL (temp ret_temp (Vint (Int.repr 0)))\n       SEP (Sigma_vector (gv _sigma); ThirtyTwoByte K k;\n            crypto_stream_xor_postsep b Nonce K mCont (Int64.unsigned b) nonce c m).\n\nDefinition f_crypto_stream_xsalsa20_tweet_xor_spec := \n  DECLARE _crypto_stream_salsa20_tweet_xor\n   WITH c : val, k:val, nonce:val, m:val, d:int64, mCont: list byte,\n        Nonce : SixteenByte, Nonce2 : SixteenByte, K: SixteenByte * SixteenByte,\n        gv: globals\n   PRE [ _c OF tptr tuchar, _m OF tptr tuchar,  _d OF tulong,\n         _n OF tptr tuchar, _k OF tptr tuchar]\n      PROP (Zlength mCont = Int64.unsigned d)\n      LOCAL (temp _c c; temp _m m; temp _d (Vlong d);\n             temp _n nonce; temp _k k; gvars gv)\n      SEP ( SByte Nonce nonce; SByte Nonce2 (offset_val 16 nonce);\n            data_at_ Tsh (Tarray tuchar (Int64.unsigned d) noattr) c;\n            ThirtyTwoByte K k;\n            message_at mCont m;\n            Sigma_vector (gv _sigma)\n            (*data_at Tsh (tarray tuchar (Zlength mCont)) (Bl2VL mCont) m*))\n  POST [ tint ]\n       PROP ()\n       LOCAL (temp ret_temp (Vint (Int.repr 0)))\n       SEP (Sigma_vector (gv _sigma);\n            EX HSalsaRes:_, crypto_stream_xor_postsep d Nonce2 HSalsaRes\n              mCont (Int64.unsigned d)\n              (offset_val 16 nonce) c m;\n            data_at Tsh (Tarray tuchar 16 noattr) (SixteenByte2ValList Nonce) nonce;\n            ThirtyTwoByte K k).\n\nDefinition f_crypto_stream_xsalsa20_tweet_spec :=\n  DECLARE _crypto_stream_xsalsa20_tweet\n   WITH c : val, k:val, nonce:val, d:int64,\n        Nonce : SixteenByte, Nonce2 : SixteenByte, K: SixteenByte * SixteenByte,\n        gv: globals\n   PRE [ _c OF tptr tuchar,  _d OF tulong,\n         _n OF tptr tuchar, _k OF tptr tuchar]\n      PROP ()\n      LOCAL (temp _c c; (*temp _m m;*) temp _d (Vlong d);\n             temp _n nonce; temp _k k; gvars gv)\n      SEP ( SByte Nonce nonce; SByte Nonce2 (offset_val 16 nonce);\n            data_at_ Tsh (Tarray tuchar (Int64.unsigned d) noattr) c;\n            ThirtyTwoByte K k;\n            Sigma_vector (gv _sigma)\n            (*data_at Tsh (tarray tuchar (Zlength mCont)) (Bl2VL mCont) m*))\n  POST [ tint ]\n       PROP ()\n       LOCAL (temp ret_temp (Vint (Int.repr 0)))\n       SEP (Sigma_vector (gv _sigma);\n            EX HSalsaRes:_, crypto_stream_xor_postsep d Nonce2 HSalsaRes\n              (list_repeat (Z.to_nat (Int64.unsigned d)) Byte.zero) (Int64.unsigned d)\n              (offset_val 16 nonce) c nullval;\n            data_at Tsh (Tarray tuchar 16 noattr) (SixteenByte2ValList Nonce) nonce;\n            ThirtyTwoByte K k).\n(*            crypto_stream_xor_postsep d Nonce K (list_repeat (Z.to_nat (Int64.unsigned d)) Byte.zero) (Int64.unsigned d) nonce c k nullval). *)\n\n(*TODO: support the following part of the tetxual spec:\n      m and c can point to the same address (in-place encryption/decryption). \n     If they don't, the regions should not overlap.*)\nDefinition f_crypto_stream_salsa20_tweet_spec := \n  DECLARE _crypto_stream_salsa20_tweet\n   WITH c : val, k:val, nonce:val, d:int64,\n        Nonce : SixteenByte, K: SixteenByte * SixteenByte,\n        (*mCont: list byte, *) gv: globals\n   PRE [ _c OF tptr tuchar, (*_m OF tptr tuchar,*) _d OF tulong,\n         _n OF tptr tuchar, _k OF tptr tuchar]\n      PROP ((*Zlength mCont = Int64.unsigned b*))\n      LOCAL (temp _c c; (*temp _m m;*) temp _d (Vlong d);\n             temp _n nonce; temp _k k; gvars gv)\n      SEP ( SByte Nonce nonce;\n            data_at_ Tsh (Tarray tuchar (Int64.unsigned d) noattr) c;\n            ThirtyTwoByte K k;\n            Sigma_vector (gv _sigma)\n            (*data_at Tsh (tarray tuchar (Zlength mCont)) (Bl2VL mCont) m*))\n  POST [ tint ] \n       PROP ()\n       LOCAL (temp ret_temp (Vint (Int.repr 0)))\n       SEP (Sigma_vector (gv _sigma);\n            ThirtyTwoByte K k;\n            crypto_stream_xor_postsep d Nonce K (list_repeat (Z.to_nat (Int64.unsigned d)) Byte.zero) (Int64.unsigned d) nonce c nullval). \n\nDefinition vn_spec :=\n  DECLARE _vn\n  WITH x:val, y:val, n:Z, xsh: share, ysh: share, xcont:list byte, ycont:list byte\n  PRE [_x OF tptr tuchar, _y OF tptr tuchar, _n OF tint]\n    PROP (readable_share xsh; readable_share ysh; 0<=n<= Int.max_unsigned)\n    LOCAL (temp _x x; temp _y y; temp _n (Vint (Int.repr n)))\n    SEP (data_at xsh (Tarray tuchar n noattr) (map Vint (map Int.repr (map Byte.unsigned xcont))) x;\n         data_at ysh (Tarray tuchar n noattr) (map Vint (map Int.repr (map Byte.unsigned ycont))) y)\n  POST [tint]\n    PROP ()\n    LOCAL (temp ret_temp (Vint (Int.repr (if list_eq_dec Byte.eq_dec xcont ycont then 0 else -1))))\n    SEP (data_at xsh (Tarray tuchar n noattr) (map Vint (map Int.repr (map Byte.unsigned xcont))) x;\n         data_at ysh (Tarray tuchar n noattr) (map Vint (map Int.repr (map Byte.unsigned ycont))) y). \n    \nDefinition verify16_spec :=\n  DECLARE _crypto_verify_16_tweet\n  WITH x:val, y:val, n:Z, xsh: share, ysh: share, xcont:list byte, ycont:list byte\n  PRE [_x OF tptr tuchar, _y OF tptr tuchar]\n    PROP (readable_share xsh; readable_share ysh)\n    LOCAL (temp _x x; temp _y y)\n    SEP (data_at xsh (Tarray tuchar 16 noattr) (map Vint (map Int.repr (map Byte.unsigned xcont))) x;\n         data_at ysh (Tarray tuchar 16 noattr) (map Vint (map Int.repr (map Byte.unsigned ycont))) y)\n  POST [tint]\n    PROP ()\n    LOCAL (temp ret_temp (Vint (Int.repr (if list_eq_dec Byte.eq_dec xcont ycont then 0 else -1))))\n    SEP (data_at xsh (Tarray tuchar 16 noattr) (map Vint (map Int.repr (map Byte.unsigned xcont))) x;\n         data_at ysh (Tarray tuchar 16 noattr) (map Vint (map Int.repr (map Byte.unsigned ycont))) y).\n       \nDefinition verify32_spec :=\n  DECLARE _crypto_verify_32_tweet\n  WITH x:val, y:val, n:Z, xsh: share, ysh: share, xcont:list byte, ycont:list byte\n  PRE [_x OF tptr tuchar, _y OF tptr tuchar]\n    PROP (readable_share xsh; readable_share ysh)\n    LOCAL (temp _x x; temp _y y)\n    SEP (data_at xsh (Tarray tuchar 32 noattr) (map Vint (map Int.repr (map Byte.unsigned xcont))) x;\n         data_at ysh (Tarray tuchar 32 noattr) (map Vint (map Int.repr (map Byte.unsigned ycont))) y)\n  POST [tint]\n    PROP ()\n    LOCAL (temp ret_temp (Vint (Int.repr (if list_eq_dec Byte.eq_dec xcont ycont then 0 else -1))))\n    SEP (data_at xsh (Tarray tuchar 32 noattr) (map Vint (map Int.repr (map Byte.unsigned xcont))) x;\n         data_at ysh (Tarray tuchar 32 noattr) (map Vint (map Int.repr (map Byte.unsigned ycont))) y).       \n\nDefinition SalsaVarSpecs : varspecs := (_sigma, tarray tuchar 16)::nil.\n\nDefinition SalsaFunSpecs : funspecs := \n  ltac:(with_library prog (core_spec :: ld32_spec :: L32_spec::st32_spec::dl64_spec::ts64_spec::\n                           crypto_core_salsa20_spec::crypto_core_hsalsa20_spec::\n                           crypto_stream_salsa20_xor_spec::f_crypto_stream_salsa20_tweet_spec::\n                           verify32_spec::verify16_spec::vn_spec::nil)).\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/tweetnacl20140427/spec_salsa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.2401788863360567}}
{"text": "Require Export veric.base.\nRequire Import veric.rmaps.\nRequire Import veric.compcert_rmaps.\nRequire Import veric.res_predicates.\nRequire Import veric.shares.\nRequire Import veric.tycontext.\nRequire Import veric.expr2.\n\nDefinition GHOSTspec (A: Type) (x: A) : spec :=\n  fun sh loc =>\n   allp (jam (eq_dec loc) (fun loc' => \n    yesat (SomeP (ConstType (A -> Prop)) (fun _ y => y = x)) \n             (FUN (nil,Tvoid) cc_default) sh loc') noat).\n\nDefinition ghostp {A: Type} (sh: share) (loc: address) (x: A) : mpred :=\n  GHOSTspec A x sh loc.\n\n\nLemma ghostp_unique_sepcon:\n    forall {A: Type} sh1 sh2 loc (x1 x2: A),\n     ghostp sh1 loc x1 * ghostp sh2 loc x2 |-- |> !! (x1=x2).\nProof.\nintros.\nunfold ghostp, GHOSTspec.\nintros w [w1 [w2 [? [? ?]]]].\nintros w' ?.\nsimpl in H2.\napply laterR_level in H2.\ngeneralize (join_level _ _ _ H); intros [? ?].\ndestruct (level w). inv H2.\nhnf.\nrename H2 into Hw'.\nspecialize (H0 loc). specialize (H1 loc).\nrewrite jam_true in H0 by auto.\nrewrite jam_true in H1 by auto.\ndestruct H0 as [p ?]. destruct H1 as [p' ?].\nhnf in H0,H1.\napply (resource_at_join _ _ _ loc) in H.\nrewrite H0 in H; rewrite H1 in H.\nsimpl in H.\n(*rewrite H3 in H. rewrite H4 in H. *)\nassert (SomeP (ConstType (A -> Prop))\n            (fun (_ : list Type) (y : A) => y = x1) =\n          SomeP (ConstType (A -> Prop))\n            (fun (_ : list Type) (y : A) => y = x2))%pred.\nclear - H.\nmatch goal with |- ?B = ?C => forget B as b; forget C as c end.\ninversion H; auto.\nclear H.\napply SomeP_inj in H2.\npose proof (@equal_f A Prop _ _ (@equal_f (list Type) (A->Prop) _ _ H2 nil) x1).\nsimpl in H.\nrewrite <- H; auto.\nQed.\n\nLemma ghostp_unique_andp:\n    forall {A: Type} sh loc (x1 x2: A),\n     ghostp sh loc x1 && ghostp sh loc x2 |-- |> !! (x1=x2).\nProof.\nintros.\nunfold ghostp, GHOSTspec.\nintros w [? ?].\nrename H0 into H1; rename H into H0.\nspecialize (H0 loc). specialize (H1 loc).\nrewrite jam_true in H0 by auto.\nrewrite jam_true in H1 by auto.\ndestruct H0 as [p H0]. destruct H1 as [p' H1].\nhnf in H0,H1.\nrewrite H0 in H1.\nsimpl in H1.\nintros w' H2.\nsimpl in H2.\napply laterR_level in H2.\ndestruct (level w). inv H2.\nhnf.\nrename H2 into Hw'.\nassert (SomeP (ConstType (A -> Prop))\n            (fun (_ : list Type) (y : A) => y = x1) =\n          SomeP (ConstType (A -> Prop))\n            (fun (_ : list Type) (y : A) => y = x2))%pred.\nclear - H1.\nmatch goal with |- ?B = ?C => forget B as b; forget C as c end.\ninversion H1; auto.\nclear - H.\napply SomeP_inj in H.\npose proof (@equal_f A Prop _ _ (@equal_f (list Type) (A->Prop) _ _ H nil) x1).\nrewrite <- H0; auto.\nQed.\n\n\nDefinition make_GHOSTspec:\n  forall A (sh : share) (rsh: readable_share sh) loc (x: A) (lev: nat),\n   exists m: rmap, GHOSTspec A x sh loc m /\\ level m =  lev.\nProof.\n intros.\nunfold GHOSTspec.\n assert (AV.valid (res_option oo \n  (fun l => if eq_dec l loc \n   then YES sh rsh (FUN(nil,Tvoid) cc_default)\n             (SomeP (ConstType (A -> Prop)) \n                  (fun _ y => (y = x)))\n   else NO Share.bot bot_unreadable))).\n intros b ofs.\n unfold res_option, compose.\n if_tac; auto.\n destruct (make_rmap _ H lev) as [phi [? ?]].\n extensionality l.\n unfold compose, resource_fmap; simpl.\n if_tac; auto.\n exists phi.\n split; auto.\n hnf.\n intro l.\n hnf.\n if_tac.\n subst l.\n hnf. exists rsh.\n hnf.\n rewrite H1. rewrite if_true. f_equal. \n auto.\n do 3 red. rewrite H1.\n rewrite if_false by auto.\n apply NO_identity.\nQed.\n\n\nLemma make_ghostp:\n  forall A (x: A)  loc (lev: nat),\n  exists m : rmap, ghostp Share.top loc x m /\\ level m = lev.\nProof.\nintros.\nunfold ghostp.\ndestruct (make_GHOSTspec A Share.top readable_share_top loc x lev) as [m [? ?]].\nexists m; split; auto.\nQed.\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/veric/ghost.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24016288257973506}}
{"text": "From iris.algebra Require Import excl.\nFrom iris.base_logic.lib Require Import invariants.\nFrom aneris.aneris_lang Require Import proofmode.\nFrom aneris.prelude Require Import time.\nFrom aneris.examples.rcb Require Import spec.\nFrom aneris.examples.rcb.examples.broadcast_1_2 Require Import prog.\n\nSection Resources.\n  Context `{!anerisG Mdl Σ, inG Σ (exclR unitO), !RCB_events, !RCB_resources Mdl Σ}.\n\n  Definition token (γ : gname) : iProp Σ := own γ (Excl ()).\n\n  Lemma exclusive_token γ : token γ -∗ token γ -∗ False.\n  Proof. iIntros \"H1 H2\". by iDestruct (own_valid_2 with \"H1 H2\") as %?. Qed.\n\n  Definition Nsys := nroot.@\"sys\".\n\n  (* The invariant satisfied by the two nodes.\n     Only one node is broadcasting. The two broadcast messages are e1 and e2.\n     Broadcasting each message requires tokens γS1 and γS2, respectively. *)\n  Definition inv_sys γS1 γS2 : iProp Σ :=\n    ∃ h, OwnGlobal h ∗\n      (* Case 0: no message has been sent *)\n      ((⌜ h = ∅ ⌝)\n      (* Case 1: one message e1 has been sent, along with the token γS1. This token is used so that\n         the message e1 is sent once. Conversely, while a user own the token, it knows that the\n         message e1 has not yet been sent. *)\n       ∨ (∃ e1, ⌜ h = {[ e1 ]} ⌝ ∗ ⌜ GE_payload e1 = #1 ⌝ ∗ token γS1)\n      (* Case 1: another message e2 has been sent, along with the token γS2. This token is used so\n         that the message e1 is sent once. Conversly, while a user own the token, it knows that the\n         message e2 has not yet been sent. *)\n       ∨ (∃ e1 e2, ⌜ h = {[ e1; e2 ]} ⌝ ∗\n                   token γS1 ∗ token γS2 ∗\n                   ⌜ GE_payload e1 = #1 ⌝ ∗ ⌜ GE_payload e2 = #2 ⌝ ∗\n                   ⌜ vector_clock_lt (GE_vc e1) (GE_vc e2) ⌝)).\nEnd Resources.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/rcb/examples/broadcast_1_2/proof_resources.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24016287625726418}}
{"text": "Require Export WellFormedness.\nRequire Import SyntaxProp.\nRequire Import TypesProp.\nRequire Import Shared.\n\n(*\n========================\nField and method lookup\n========================\n*)\n\n\nLemma wfProgram_wfMethodDecl :\n  forall P t' c ms m mtd,\n    wfProgram P t' ->\n    methods P (TClass c) = Some ms ->\n    methodLookup ms m = Some mtd ->\n    wfMethodDecl P c mtd.\nProof with auto.\n  introv wfP Hmethods mLookup.\n  inv wfP.\n  unfold methods in Hmethods.\n  remember (classLookup (cds, ids, e) c) as cLookup.\n  symmetry in HeqcLookup.\n  destruct cLookup as [[c' i fs ms'] |]...\n  inv_eq.\n  assert (Heq : c = c') by\n      (unfold classLookup in HeqcLookup;\n       apply find_true in HeqcLookup;\n       apply eqb_class_id_eq; auto).    (*!!changed beq_nat_eq to eqb_class_id_eq*)\n  subst.\n  lookup_forall as wfCls.\n  inv wfCls.\n  lookup_forall mtd as wfMtd...\nQed.\n\n\nCorollary dyn_wfFieldLookup :\n  forall P Gamma c F fs f t,\n    wfFields P Gamma c F ->\n    fields P (TClass c) = Some fs ->\n    fieldLookup fs f = Some (Field f t) ->\n    exists v, F f = Some v /\\ P; Gamma |- (EVal v) \\in t.\nProof with eauto.\n  introv wfF Hfields fLookup.\n  inv wfF. rewrite_and_invert...\nQed.\n\nHint Immediate dyn_wfFieldLookup.\n\n(*\n------------\nMethod sigs\n------------\n*)\n\nHint Constructors methodSigs.\n\nLemma extractSigs_sound :\n  forall mtds m x t t',\n    (exists e, methodLookup mtds m = Some (Method m (x, t) t' e)) <->\n    methodSigLookup (extractSigs mtds) m = Some (MethodSig m (x, t) t').\nProof with eauto.\n  intros. split.\n  + gen t t' m x.\n    induction mtds as [|[m [x t] t' e]]; simpl;\n    introv H; inv H as [e' Hsigs]...\n    cases_if... inv_eq.\n  + gen t t' m x.\n    induction mtds as [|[m [x t] t' e]]; simpl;\n    introv mLookup; inv mLookup...\n    cases_if; crush...\nQed.\n\nLemma methodSigs_deterministic :\n  forall P t msigs1 msigs2,\n    methodSigs P t msigs1 ->\n    methodSigs P t msigs2 ->\n    msigs1 = msigs2.\nProof with eauto.\n  introv Hsigs1 Hsigs2.\n  gen msigs2.\n  induction Hsigs1; introv Hsigs2;\n  inv Hsigs2; try(rewrite_and_invert)...\n  rewrite IHHsigs1_1 with msigs3...\n  rewrite IHHsigs1_2 with msigs4...\nQed.\n\nLemma methodSigs_wfType_exists :\n  forall P t' t,\n    wfProgram P t' ->\n    (wfType P t <->\n     exists msigs, methodSigs P t msigs).\nProof with eauto.\n  introv [? ? ? wfCds wfIds wfExpr].\n  split.\n  + intros wfT.\n    inv wfT as [c cLookup|i iLookup|]...\n    - apply classLookup_not_none in cLookup as [i [fs [ms]]]...\n    - apply interfaceLookup_not_none in iLookup.\n      inv iLookup as [[msigs]|[i1 [i2]]]...\n      * intros. lookup_forall as wfId. inv wfId...\n  + intros Hex. destruct Hex as [msigs Hsigs].\n    destruct t; inv Hsigs; constructor; crush.\nQed.\n\nLemma methodSigs_sub :\n  forall P t t1 t2 m msigs1 msigs2 msig,\n    wfProgram P t ->\n    subtypeOf P t1 t2 ->\n    methodSigs P t1 msigs1 ->\n    methodSigs P t2 msigs2 ->\n    methodSigLookup msigs2 m = Some msig ->\n    methodSigLookup msigs1 m = Some msig.\nProof with eauto using\n                 methodSigs_deterministic,\n                 methodSigs_wfType_exists,\n                 subtypeOf_wfTypeSub,\n                 subtypeOf_wfTypeSup.\n  introv [? ? ? ? wfCds wfIds wfExpr] Hsub\n         Hsigs1 Hsigs2 Hsig.\n  gen msigs1 msigs2 msig.\n  subtypeOf_cases(induction Hsub) Case; intros.\n  + Case \"Sub_Class\".\n    lookup_forall as wfCd. inv wfCd.\n    assert (msigs2 = (extractSigs ms))...\n    subst. inv Hsigs1; rewrite_and_invert.\n  + Case \"Sub_InterfaceLeft\".\n    inv Hsigs1; rewrite_and_invert.\n    assert (msigs0 = msigs2)...\n    subst. apply find_app...\n  + inv Hsigs1; rewrite_and_invert.\n    assert (msigs2 = msigs3)...\n    subst. apply find_app2...\n    lookup_forall as wfId.\n    inverts wfId as Hsigs3 Hsigs4 sigsDisjoint1 sigsDisjoint2.\n    assert (msigs0 = msigs1)...\n    assert (msigs2 = msigs3)...\n    subst. fold (methodSigLookup msigs1 m).\n    eapply sigsDisjoint2...\n  + asserts_rewrite (msigs1 = msigs2)...\n  + rename msigs2 into msigs3.\n    rename Hsigs2 into Hsigs3.\n    assert (wfT1: wfType (cds, ids, e) t1)...\n    assert (wfT2: wfType (cds, ids, e) t2)...\n    eapply methodSigs_wfType_exists in wfT2 as []...\n(*  + inv Hsigs2. inv Hsig.*)\nQed.\n\n(*\n==============\nConfiguration\n==============\n*)\n\n(*\n---------\nwfFields\n---------\n*)\n\nLemma wfFields_declsToFields :\n  forall P t' c i fs ms Gamma,\n    wfProgram P t' ->\n    wfEnv P Gamma ->\n    classLookup P c = Some (Cls c i fs ms) ->\n    wfFields P Gamma c (declsToFields fs).\nProof with eauto using\n                 fields_wfFieldDecl,\n                 declsToFields_null.\n  introv wfProgram wfEnv Hlookup.\n  assert (fields P (TClass c) = Some fs)\n    by (unfolds; rewrite Hlookup; auto).\n  assert (Forall (wfFieldDecl P) fs)...\n  econstructor...\n  intros.\n  lookup_forall as wfF. inv wfF...\nQed.\n\nLemma wfFields_extend :\n  forall P Gamma c fs f t F v,\n    fields P (TClass c) = Some fs ->\n    fieldLookup fs f = Some (Field f t) ->\n    wfFields P Gamma c F ->\n    P; Gamma |- EVal v \\in t ->\n    wfFields P Gamma c (extend F f v).\nProof with eauto with env.\n  introv Hfields fLookup wfF hasType.\n  econstructor...\n  introv fLookup'.\n  inv wfF.\n  case_extend; repeat rewrite_and_invert...\nQed.\n\nLemma wfFields_envExtend :\n  forall P t' Gamma c F l c',\n    wfProgram P t' ->\n    wfFields P Gamma c F ->\n    wfEnv P Gamma ->\n    fresh Gamma (env_loc l) ->\n    wfType P (TClass c') ->\n    wfFields P (extend Gamma (env_loc l) (TClass c')) c F.\nProof with eauto using hasType_extend_loc.\n  introv wfP wfF wfGamma Hfresh wfT.\n  inverts wfF as Hfields wfFlds.\n  econstructor...\n  introv Hlookup.\n  apply wfFlds in Hlookup as (v & Heq & hasType)...\nQed.\n\nLemma wfFields_invariance :\n  forall P t' c Gamma Gamma' F,\n    wfProgram P t' ->\n    (forall l, Gamma (env_loc l) = Gamma' (env_loc l)) ->\n    wfEnv P Gamma' ->\n    wfFields P Gamma c F ->\n    wfFields P Gamma' c F.\nProof with eauto using hasType_wfType.\n  introv wfP envSub wfGamma' wfF.\n  inverts wfF as Hfields wfFld.\n  econstructor...\n  introv fLookup.\n  apply wfFld in fLookup as (v & Ff & hasType).\n  exists v. split...\n  destruct v...\n  + inv hasType.\n    econstructor...\n    rewrite <- envSub...\nQed.\n\nLemma wfHeap_wfObject :\n  forall P Gamma H l c F L,\n    wfHeap P Gamma H ->\n    heapLookup H l = Some (c, F, L) ->\n    wfFields P Gamma c F.\nProof with eauto.\n  introv wfH Hlookup.\n  inverts wfH as _ envModelsHeap heapMirrorsEnv.\n  assert (Hl: heapLookup H l <> None) by crush.\n  apply heapMirrorsEnv in Hl.\n  destruct Hl as [c' envLookup].\n  apply envModelsHeap in envLookup as (F' & L' & ? & ?).\n  rewrite_and_invert.\nQed.\n\nLemma wfHeap_wfFields :\n  forall P Gamma H l c F RL,\n    wfHeap P Gamma H ->\n    heapLookup H l = Some (c, F, RL) ->\n    wfFields P Gamma c F.\nProof with eauto.\n  introv wfH Hlookup.\n  eapply wfHeap_wfObject in Hlookup as []...\n  constructors...\nQed.\n\n(*\n-------\nwfHeap\n-------\n*)\n\nHint Constructors wfHeap.\n\nLemma wfHeap_fresh :\n  forall P Gamma H l,\n    wfHeap P Gamma H ->\n    heapLookup H l = None ->\n    fresh Gamma (env_loc l).\nProof with eauto.\n  introv wfH Hlookup.\n  inverts wfH as wfGamma envModelsHeap heapMirrorsEnv.\n  unfold fresh. remember (Gamma (env_loc l)) as t...\n  destruct t...\n  symmetry in Heqt.\n  assert (tClass: exists c, t = TClass c) by (inv wfGamma; eauto).\n  inv tClass as [c''].\n  apply envModelsHeap in Heqt.\n  inv Heqt as [F' [RL [contra]]]. rewrite_and_invert.\nQed.\n\nLemma wfHeap_extend :\n  forall P t' Gamma H c F L,\n    wfProgram P t' ->\n    wfHeap P Gamma H ->\n    wfType P (TClass c) ->\n    wfFields P Gamma c F ->\n    wfHeap P (extend Gamma (env_loc (length H)) (TClass c)) (heapExtend H (c, F, L)).\nProof with eauto with env.\n  introv wfP wfH wfT wfF.\n  inverts wfH as wfGamma envModelsHeap heapMirrorsEnv.\n  constructor...\n  + introv envLookup.\n    destruct (id_eq_dec l (length H)).\n    - subst. simpl_extend_hyp. inv_eq.\n      rewrite heapExtend_lookup_len.\n      eexists; eexists; split...\n      eapply wfFields_envExtend...\n      eapply wfHeap_fresh...\n      apply heapLookup_ge...\n    - rewrite extend_neq in envLookup...\n      rewrite heapExtend_lookup_nlen...\n      apply envModelsHeap in envLookup as (F' & RL' & Hlookup & wfF')...\n      eexists; eexists; split...\n      eapply wfFields_envExtend...\n      eapply wfHeap_fresh...\n      apply heapLookup_ge...\n  + introv Hlookup.\n    destruct (id_eq_dec l (length H))...\n    rewrite heapExtend_lookup_nlen in Hlookup...\nQed.\n\nLemma wfHeap_update :\n  forall P Gamma H l c F RL RL' F',\n    wfHeap P Gamma H ->\n    heapLookup H l = Some (c, F, RL) ->\n    wfFields P Gamma c F' ->\n    wfHeap P Gamma (heapUpdate H l (c, F', RL')).\nProof with eauto.\n  introv wfH Hlookup wfF'.\n  inverts wfH as wfGamma envModelsHeap heapMirrorsEnv.\n  constructor...\n  + introv envLookup.\n    destruct (id_eq_dec l l0).\n    - subst.\n      rewrite lookup_heapUpdate_eq\n        by (apply heapLookup_lt; eauto).\n      apply envModelsHeap in envLookup as (F'' & RL'' & Hlookup' & wfF'').\n      rewrite_and_invert...\n    - rewrite lookup_heapUpdate_neq...\n  + introv Hlookup'.\n    apply heapMirrorsEnv.\n    destruct (id_eq_dec l l0).\n    - subst.\n      rewrite heapLookup_not_none...\n    - rewrite lookup_heapUpdate_neq in Hlookup'...\nQed.\n\nLemma wfHeap_invariance :\n  forall P t' Gamma Gamma' H,\n    wfProgram P t' ->\n    (forall l, Gamma (env_loc l) = Gamma' (env_loc l)) ->\n    wfEnv P Gamma' ->\n    wfHeap P Gamma H ->\n    wfHeap P Gamma' H.\nProof with eauto using wfFields_invariance.\n  introv wfP envEquiv wfGamma' wfH.\n  inverts wfH as wfGamma envModelsHeap heapMirrorsEnv.\n  constructor...\n  + introv envLookup. rewrite <- envEquiv in envLookup.\n    apply envModelsHeap in envLookup.\n    inv envLookup as (F & RL & Hlookup & wfF)...\n  + introv Hlookup. rewrite <- envEquiv...\nQed.\n\n(*\n--------\nwfVars\n--------\n*)\n\nHint Constructors wfVars.\n\nLemma wfVars_invariance :\n  forall P t' Gamma Gamma' fsyms V,\n    wfProgram P t' ->\n    (forall x, Gamma x = Gamma' x) ->\n    wfEnv P Gamma' ->\n    wfVars P Gamma fsyms V ->\n    wfVars P Gamma' fsyms V.\nProof with eauto.\n  introv wfP envEquiv wfGamma' wfV.\n  inverts wfV as wfGamma envModelsVars varsMirrorEnv Hfresh.\n  constructor...\n  + introv Vlookup.\n    rewrite <- envEquiv in Vlookup.\n    apply envModelsVars in Vlookup as (v & Vlookup & hasType).\n    eapply hasType_subsumption with (Gamma' := Gamma') in hasType; crush...\n  + introv. rewrite <- envEquiv...\nQed.\n\nLemma wfVars_extend :\n  forall P t' Gamma n m V v t,\n    wfProgram P t' ->\n    wfVars P Gamma n V ->\n    P; Gamma |- EVal v \\in t ->\n    m < n ->\n    wfVars P (extend Gamma (env_var (DV (DVar m))) t)\n           n (extend V (DVar m) v).\nProof with eauto with env.\n  introv wfP wfV hasType Hlt.\n  inverts wfV as wfGamma envModelsVars varsMirrorEnv Hfresh.\n  constructor; eauto 3 with env.\n  + introv envLookup.\n    destruct (id_eq_dec (DVar m) x).\n    - subst. simpl_extend_hyp.\n      inv_eq.\n      exists v.\n      split...\n      inv hasType...\n    - rewrite extend_neq in envLookup...\n      apply envModelsVars in envLookup as (v' & Vlookup & hasType').\n      exists v'.\n      split...\n      inv hasType'...\n  + introv Hle. unfold fresh.\n    assert (m < n')\n        by omega.\n    case_extend; [inv_eq | apply Hfresh]; omega.\nQed.\n\nLemma wfVars_heapExtend :\n  forall Gamma P t' n V l c,\n    wfProgram P t' ->\n    wfVars P Gamma n V ->\n    fresh Gamma (env_loc l) ->\n    wfType P (TClass c) ->\n    wfVars P (extend Gamma (env_loc l) (TClass c)) n V.\nProof with eauto with env.\n  introv wfP wfV Hfresh wfT.\n  inverts wfV as wfGamma envModelsVars varsMirrorEnv freshVars.\n  constructor...\n  + introv envLookup.\n    simpl_extend_hyp.\n    apply envModelsVars in envLookup as (v & Vlookup & hasType).\n    exists v.\n    split...\n    inv hasType...\nQed.\n\nLemma wfVars_ge :\n  forall P Gamma n V m,\n    wfVars P Gamma n V ->\n    n <= m ->\n    wfVars P Gamma m V.\nProof with eauto.\n  introv wfV Hge.\n  inverts wfV as wfGamma envModels varsMirror Hfresh.\n  econstructor...\n  introv Hle.\n  assert (n <= n') by omega...\nQed.\n\n(*\n----------\nwfLocking\n----------\n*)\n\nHint Constructors wfHeldLocks.\nHint Constructors wfLocks.\nHint Constructors disjointLocks.\nHint Constructors wfLocking.\n\nLemma wfHeldLocks_heapExtend :\n  forall H Ls c F RL,\n    wfHeldLocks H Ls ->\n    wfHeldLocks (heapExtend H (c, F, RL)) Ls.\nProof with eauto.\n  introv wfLs.\n  constructor.\n  induction wfLs as [wfLs]...\n  rewrite Forall_forall in wfLs.\n  apply Forall_forall.\n  introv HIn.\n  apply wfLs in HIn as [].\n  assert (Hlt: l < length H) by\n      (eapply heapLookup_lt; eauto)...\n  econstructor...\n  rewrite heapExtend_lookup_nlen...\n  omega.\nQed.\n\nLemma wfLocking_heapExtend :\n  forall H T c F RL,\n    wfLocking H T ->\n    wfLocking (heapExtend H (c, F, RL)) T.\nProof with eauto using wfHeldLocks_heapExtend.\n  introv wfL.\n  induction wfL...\nQed.\n\nLemma wfHeldLocks_heapUpdate :\n  forall H Ls l c F F' L L',\n    wfHeldLocks H Ls ->\n    heapLookup H l = Some (c, F, L) ->\n    (In l Ls -> L' = LLocked) ->\n    wfHeldLocks (heapUpdate H l (c, F', L')) Ls.\nProof with eauto.\n  introv wfLs Hlookup HRL'.\n  induction wfLs as [wfLs]...\n  rewrite Forall_forall in wfLs.\n  constructors.\n  apply Forall_forall.\n  introv HIn.\n  assert(wfL: wfLock H x)...\n  inverts wfL as Hlookup' HRL.\n  destruct (id_eq_dec l x).\n  + subst. rewrite_and_invert.\n    apply HRL' in HIn. subst.\n    apply WF_Lock with c0 F'...\n    rewrite lookup_heapUpdate_eq...\n    apply heapLookup_lt...\n  + econstructor...\n    rewrite lookup_heapUpdate_neq...\nQed.\n\nLemma wfLocking_heapUpdate :\n  forall H T l c F F' L L',\n    wfLocking H T ->\n    heapLookup H l = Some (c, F, L) ->\n    (In l (heldLocks T) -> L' = LLocked) ->\n    wfLocking (heapUpdate H l (c, F', L')) T.\nProof with eauto using wfHeldLocks_heapUpdate.\n  introv wfL Hlookup HL.\n  induction wfL; simpls...\n  crush.\nQed.\n\nLemma wfHeldLocks_taken :\n  forall H Ls l c L F,\n    wfHeldLocks H Ls ->\n    In l Ls ->\n    heapLookup H l = Some (c, F, L) ->\n    L = LLocked.\nProof with eauto.\n  introv wfLs HIn Hlookup.\n  induction wfLs as [wfLs]...\n  rewrite Forall_forall in wfLs.\n  apply wfLs in HIn. inv HIn.\n  rewrite_and_invert...\nQed.\n\nLemma wfLocks_econtext :\n  forall Ls e ctx,\n    is_econtext ctx ->\n    wfLocks Ls (ctx e) ->\n    wfLocks Ls e.\nProof with eauto using in_or_app.\n  introv Hctx wfL.\n  inv Hctx;\n    inverts wfL as Hlocks Hdup;\n    simpl in *...\n  + eapply NoDup_app in Hdup as []...\n  + inv Hdup...\nQed.\n\nLemma wfLocking_econtext :\n  forall ctx H Ls e,\n    is_econtext ctx ->\n    wfLocking H (T_Thread Ls (ctx e)) ->\n    wfLocking H (T_Thread Ls e).\nProof with eauto using wfLocks_econtext.\n  introv Hctx wfL.\n  inv wfL...\nQed.\n\nLemma wfLocking_subst :\n  forall H Ls e x y,\n    wfLocking H (T_Thread Ls e) ->\n    wfLocking H (T_Thread Ls (subst x y e)).\nProof with eauto.\n  introv wfL.\n  inverts wfL as wfLs Hdup wfL wfRl.\n  econstructor...\n  econstructor...\n  + rewrite <- locks_subst...\n    inv wfL...\n  + rewrite <- locks_subst...\n    inv wfL...\nQed.\n\nLemma locks_static :\n  forall e,\n    exprStatic e ->\n    locks e = nil.\nProof with eauto using app_eq_nil.\n  introv Hstatic.\n  induction Hstatic; simpl...\n  apply app_eq_nil...\nQed.\n\nLemma wfLocking_static :\n  forall H Ls e,\n    wfHeldLocks H Ls ->\n    NoDup Ls ->\n    exprStatic e ->\n    wfLocking H (T_Thread Ls e).\nProof with eauto using locks_static.\n  introv wfLs Hdup Hstatic.\n  assert (HL: locks e = nil)...\n  econstructor...\n  econstructor; rewrite HL...\n  introv HIn... inv HIn.\nQed.\n\nLemma disjointLocks_commutative :\n  forall T1 T2,\n    disjointLocks T1 T2 ->\n    disjointLocks T2 T1.\nProof with eauto.\n  introv Hdisj.\n  inv Hdisj. constructors...\nQed.\n\nLemma disjointLocks_async :\n  forall T T1 T2 e,\n    disjointLocks T1 T /\\\n    disjointLocks T2 T\n     <->\n    disjointLocks (T_Async T1 T2 e) T.\nProof with eauto using in_or_app.\n  split.\n  + introv Hdisj.\n    inverts Hdisj as Hdisj1 Hdisj2.\n    inverts Hdisj1. inverts Hdisj2.\n    constructor; simpl.\n    - introv HIn.\n      apply in_app_or in HIn as [|HIn]...\n    - introv HIn.\n      apply not_in_app...\n  + introv Hdisj.\n    inverts Hdisj as Hdisj1 Hdisj2.\n    simpls.\n    splits.\n    - constructor...\n      introv HIn.\n      apply Hdisj2 in HIn...\n    - constructor...\n      introv HIn.\n      apply Hdisj2 in HIn.\n      eapply not_in_app in HIn as []...\nQed.\n\nLemma disjointLocks_leftmost :\n  forall T1 T2,\n    disjointLocks T1 T2 ->\n    disjointLocks (T_EXN (leftmost_locks T1)) T2.\nProof with eauto using in_or_app.\n  introv Hdisj.\n  induction T1; simpls; inv Hdisj...\n  apply IHT1_1.\n  econstructor; crush...\nQed.\n\nLemma wfHeldLocks_app :\n  forall H Ls1 Ls2,\n    (wfHeldLocks H Ls1 /\\ wfHeldLocks H Ls2 <-> wfHeldLocks H (Ls1 ++ Ls2)).\nProof with eauto using in_eq, in_cons.\n  split.\n  + introv wfLs.\n    inverts wfLs as wfLs1 wfLs2.\n    constructor.\n    apply Forall_app...\n    inv wfLs1...\n    inv wfLs2...\n  + introv wfLs.\n    induction Ls1 as [|l]; simpls...\n    inverts wfLs as wfLs.\n    inverts wfLs as wfL wfLs'.\n    assert(wfLs: wfHeldLocks H (Ls1 ++ Ls2))...\n    apply IHLs1 in wfLs as [wfLs1 wfLs2]...\n    split...\n    econstructor...\n    econstructor...\n    apply Forall_forall.\n    rewrite Forall_forall in wfLs'.\n    introv HIn.\n    assert (HIn': In x (Ls1 ++ Ls2))\n      by eauto using in_or_app...\nQed.\n\nLemma wfHeldLocks_cons :\n  forall H Ls l,\n    wfHeldLocks H Ls ->\n    wfLock H l ->\n    wfHeldLocks H (l :: Ls).\nProof with eauto.\n  introv wfLs wfL.\n  inv wfLs...\nQed.\n\nLemma wfHeldLocks_leftmost :\n  forall H T,\n    wfLocking H T ->\n    wfHeldLocks H (leftmost_locks T).\nProof with eauto.\n  introv wfL.\n  induction T; inv wfL...\nQed.\n\nLemma wfHeldLocks_remove :\n  forall H Ls L eq_dec,\n    wfHeldLocks H Ls ->\n    wfHeldLocks H (remove eq_dec L Ls).\nProof with eauto using wfHeldLocks_cons.\n  introv wfLs.\n  induction Ls as [| l]...\n  inverts wfLs as wfLs.\n  inverts wfLs.\n  simpl. cases_if...\nQed.\n\nCorollary wfLocking_wfHeldLocks :\n  forall H T,\n    wfLocking H T ->\n    wfHeldLocks H (heldLocks T).\nProof with eauto.\n  introv wfL.\n  induction T; simpls; inv wfL...\n  apply wfHeldLocks_app...\nQed.\n\n(*\n----------\nwfThreads\n----------\n*)\n\nHint Constructors wfThreads.\n\nCorollary wfThreads_wfEnv :\n  forall P t' Gamma T t,\n    wfProgram P t' ->\n    wfThreads P Gamma T t ->\n    wfEnv P Gamma.\nProof with eauto with env.\n  introv wfP wfT. inv wfT...\nQed.\n\nHint Immediate wfThreads_wfEnv.\n\nLemma wfThreads_invariance :\n  forall P t' Gamma Gamma' T t,\n    wfProgram P t' ->\n    (forall x, Gamma x = Gamma' x) ->\n    wfThreads P Gamma T t ->\n    wfThreads P Gamma' T t.\nProof with eauto using hasType_subsumption,\n                       wfEnv_equiv with env.\n  introv wfP Hequiv wfT.\n  induction wfT...\nQed.\n\nLemma wfThreads_subsumption :\n  forall P t' Gamma Gamma' T t,\n    wfProgram P t' ->\n    wfSubsumption Gamma Gamma' ->\n    wfEnv P Gamma' ->\n    wfThreads P Gamma T t ->\n    wfThreads P Gamma' T t.\nProof with eauto using hasType_subsumption with env.\n  introv wfP wfEnv' Hsub wfT.\n  induction wfT...\nQed.\n\nLemma wfThreads_heapExtend :\n  forall P t' Gamma T t c l,\n    wfProgram P t' ->\n    wfType P (TClass c) ->\n    fresh Gamma (env_loc l) ->\n    wfThreads P Gamma T t ->\n    wfThreads P (extend Gamma (env_loc l) (TClass c)) T t.\nProof with eauto using hasType_extend_loc with env.\n  introv wfP wfTy Hfresh wfT.\n  generalize dependent t.\n  induction T; intros; inv wfT...\nQed.\n\n(*\n----------------\nwfConfiguration\n----------------\n*)\n\nHint Constructors wfConfiguration.\n\nLemma wfConfiguration_substitution :\n  forall P Gamma H V n Ls e e' t,\n    freeVars e' = nil ->\n    P; Gamma |- e' \\in t ->\n    wfLocking H (T_Thread Ls e') ->\n    wfConfiguration P Gamma (H, V, n, T_Thread Ls e) t ->\n    wfConfiguration P Gamma (H, V, n, T_Thread Ls e') t.\nProof with eauto.\n  introv Hfree hasType wfL wfCfg.\n  inverts wfCfg...\nQed.\n\nLemma wfConfiguration_heapExtend :\n  forall P t' Gamma H V n T t c F L,\n    wfProgram P t' ->\n    wfConfiguration P Gamma (H, V, n, T) t ->\n    wfType P (TClass c) ->\n    wfFields P Gamma c F ->\n    wfConfiguration P (extend Gamma (env_loc (length H)) (TClass c))\n                    ((heapExtend H (c, F, L)), V, n, T) t.\nProof with eauto 6 using\n                 wfHeap_extend,\n                 wfVars_heapExtend,\n                 wfThreads_heapExtend,\n                 wfLocking_heapExtend with env.\n  introv wfP wfCfg wfTy wfF.\n  inverts wfCfg.\n  assert(fresh Gamma (env_loc (length H)))\n    by eauto using wfHeap_fresh, heapLookup_ge...\nQed.\n\nLemma wfConfiguration_heapUpdate :\n  forall P t' Gamma H V n T t l c F L L' F',\n    wfProgram P t' ->\n    wfConfiguration P Gamma (H, V, n, T) t ->\n    heapLookup H l = Some (c, F, L) ->\n    wfFields P Gamma c F' ->\n    (In l (heldLocks T) -> L' = LLocked) ->\n    wfConfiguration P Gamma\n                    ((heapUpdate H l (c, F', L')), V, n, T) t.\nProof with eauto using\n                 wfHeap_update,\n                 wfLocking_heapUpdate.\n  introv wfP wfCfg HLookup wfF' HL.\n  inverts wfCfg...\nQed.\n", "meta": {"author": "beatrizagf", "repo": "RC3-Coq", "sha": "1df7e85168938c08c93c04ed4174c4eb53e175ca", "save_path": "github-repos/coq/beatrizagf-RC3-Coq", "path": "github-repos/coq/beatrizagf-RC3-Coq/RC3-Coq-1df7e85168938c08c93c04ed4174c4eb53e175ca/Stage 1 - strip/WellFormednessProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24016287625726418}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Bool.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import ZArith NArith Nnat Ndec Ndigits.\nFrom IntMap Require Import Allmaps.\nRequire Import Wf_nat.\n\nRequire Import BDDvar_ad_nat.\nRequire Import bdd1.\nRequire Import bdd2.\nRequire Import bdd3.\nRequire Import bdd4.\nRequire Import bdd5_1.\nRequire Import bdd5_2.\nRequire Import bdd6.\nRequire Import bdd7.\nRequire Import BDDdummy_lemma_2.\nRequire Import BDDdummy_lemma_3.\nRequire Import BDDdummy_lemma_4.\nRequire Import bdd8.\nRequire Import bdd9.\n\nDefinition BDDneg (cfg : BDDconfig) (memo : BDDneg_memo) \n  (node : ad) :=\n  match BDDneg_1_1 cfg memo node (S (nat_of_N (var cfg node))) with\n  | ((cfg', node'), memo') => (cfg', (node', memo'))\n  end.\n\nDefinition BDDor (cfg : BDDconfig) (memo : BDDor_memo) \n  (node1 node2 : ad) :=\n  BDDor_1_1 cfg memo node1 node2\n    (S (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)))).\n\nDefinition BDDand (cfg : BDDconfig) (negm : BDDneg_memo) \n  (orm : BDDor_memo) (node1 node2 : ad) :=\n  match BDDneg cfg negm node1 with\n  | (cfg', (node1', negm')) =>\n      match BDDneg cfg' negm' node2 with\n      | (cfg'', (node2', negm'')) =>\n          match BDDor cfg'' orm node1' node2' with\n          | (cfg''', (node, orm')) =>\n              match BDDneg cfg''' negm'' node with\n              | (cfg'''', (node', negm''')) =>\n                  (cfg'''', (node', (negm''', orm')))\n              end\n          end\n      end\n  end.\n\nLemma nodes_preserved_orm_OK :\n forall (cfg cfg' : BDDconfig) (orm : BDDor_memo),\n BDDconfig_OK cfg ->\n BDDconfig_OK cfg' ->\n nodes_preserved cfg cfg' -> BDDor_memo_OK cfg orm -> BDDor_memo_OK cfg' orm.\nProof.\n  intros.  unfold BDDor_memo_OK in |- *.  intros.  unfold BDDor_memo_OK in H2.  cut (config_node_OK cfg node1).\n  cut (config_node_OK cfg node2).  cut (config_node_OK cfg node).  intros.\n  cut\n   (BDDvar_le (var cfg node) (BDDvar_max (var cfg node1) (var cfg node2)) =\n    true).\n  intro.  cut\n   (bool_fun_eq (bool_fun_of_BDD cfg node)\n      (bool_fun_or (bool_fun_of_BDD cfg node1) (bool_fun_of_BDD cfg node2))).\n  intro.  split.  apply nodes_preserved_2 with (cfg := cfg).  assumption.  assumption.\n  split.  apply nodes_preserved_2 with (cfg := cfg).  assumption.  assumption.  split.\n  apply nodes_preserved_2 with (cfg := cfg).  assumption.  assumption.  split.\n  cut (var cfg' node = var cfg node).  cut (var cfg' node1 = var cfg node1).\n  cut (var cfg' node2 = var cfg node2).  intros.  rewrite H9.  rewrite H10.\n  rewrite H11.  assumption.  apply nodes_preserved_var_1.  assumption.  assumption.\n  assumption.  assumption.  apply nodes_preserved_var_1.  assumption.  assumption.\n  assumption.  assumption.  apply nodes_preserved_var_1.  assumption.  assumption.\n  assumption.  assumption.  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfg node).\n  apply nodes_preserved_3.  assumption.  assumption.  assumption.  assumption.\n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_or (bool_fun_of_BDD cfg node1)\n                (bool_fun_of_BDD cfg node2)).\n  assumption.  apply bool_fun_eq_symm.  apply bool_fun_or_preserves_eq.  apply nodes_preserved_3.\n  assumption.  assumption.  assumption.  assumption.  apply nodes_preserved_3.\n  assumption.  assumption.  assumption.  assumption.  exact (proj2 (proj2 (proj2 (proj2 (H2 node1 node2 node H3))))).\n  exact (proj1 (proj2 (proj2 (proj2 (H2 node1 node2 node H3))))).  \n  exact (proj1 (proj2 (proj2 (H2 node1 node2 node H3)))).  \n  exact (proj1 (proj2 (H2 node1 node2 node H3))).\n  exact (proj1 (H2 node1 node2 node H3)).\nQed.\n\nLemma nodes_preserved_negm_OK :\n forall (cfg cfg' : BDDconfig) (negm : BDDneg_memo),\n BDDconfig_OK cfg ->\n BDDconfig_OK cfg' ->\n nodes_preserved cfg cfg' ->\n BDDneg_memo_OK_2 cfg negm -> BDDneg_memo_OK_2 cfg' negm.\nProof.\n  intros.  unfold BDDneg_memo_OK_2 in |- *.  unfold BDDneg_memo_OK_2 in H2.  intros.\n  cut (is_internal_node cfg node -> nat_of_N (var cfg node) < bound).  intro.\n  cut (config_node_OK cfg node).  cut (BDDneg_2 cfg node bound = (cfg, node')).\n  intros.  cut (config_node_OK cfg node').  intro.  cut (config_node_OK cfg' node).\n  cut (config_node_OK cfg' node').  intros.  split.  assumption.  apply BDDneg_memo_OK_1_lemma_1_1_1.\n  assumption.  assumption.  assumption.  assumption.  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfg node').\n  apply nodes_preserved_3.  assumption.  assumption.  assumption.  assumption.  \n  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_of_BDD cfg node)).\n  replace (bool_fun_of_BDD cfg node') with\n   (bool_fun_of_BDD (fst (BDDneg_2 cfg node bound))\n      (snd (BDDneg_2 cfg node bound))).\n  refine (proj2 (proj2 (proj2 (proj2 (BDDneg_2_lemma _ _ _ _ _ _))))).\n  assumption.  assumption.  assumption.  rewrite H6.  reflexivity.  apply bool_fun_eq_symm.\n  apply bool_fun_eq_neg_1.  apply nodes_preserved_3.  assumption.  assumption.  \n  assumption.  assumption.  apply nodes_preserved_2 with (cfg := cfg).  assumption. \n  assumption.  apply nodes_preserved_2 with (cfg := cfg).  assumption.  assumption.\n  replace cfg with (fst (BDDneg_2 cfg node bound)).  replace node' with (snd (BDDneg_2 cfg node bound)).  refine (proj1 (proj2 (proj2 (proj2 (BDDneg_2_lemma _ _ _ _ _ _))))).\n  assumption.  assumption.  assumption.  rewrite H6; reflexivity.  rewrite H6; reflexivity.\n  exact (proj2 (H2 node node' bound H3 H5)).  exact (proj1 (H2 node node' bound H3 H5)).  \n  intro.  cut (var cfg' node = var cfg node).  intro.  rewrite <- H6.  apply H4.\n  inversion H5.  inversion H7.  inversion H8.  split with x.  split with x0.\n  split with x1.  apply H1.  assumption.  apply nodes_preserved_var.  assumption.\n  assumption.\nQed.\n\nLemma BDDneg_keeps_config_OK :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (node : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n config_node_OK cfg node -> BDDconfig_OK (fst (BDDneg cfg negm node)).\nProof.\n  intros.  unfold BDDneg in |- *.  elim\n   (prod_sum _ _ (BDDneg_1_1 cfg negm node (S (nat_of_N (var cfg node))))).\n  intro.  elim x; clear x.  intros cfg' node'.  intro.  elim H2; clear H2.\n  intros negm' H2.  rewrite H2.  simpl in |- *.  rewrite (BDDneg_1_1_eq_1 (S (nat_of_N (var cfg node))) cfg negm node)\n    in H2.\n  cut\n   (is_internal_node cfg node ->\n    nat_of_N (var cfg node) < S (nat_of_N (var cfg node))).\n  intro.  replace cfg' with\n   (fst (fst (BDDneg_1 (cfg, node, negm) (S (nat_of_N (var cfg node)))))).\n  rewrite\n   (proj1\n      (BDDneg_1_lemma' (S (nat_of_N (var cfg node))) \n         (cfg, node, negm) H H1 H0 H3)).\n  exact (proj1 (BDDneg_2_lemma _ _ _ H H1 H3)).  rewrite H2.  reflexivity.\n  intro.  unfold lt in |- *.  apply le_n.\nQed.\n\nLemma BDDneg_node_OK :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (node : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n config_node_OK cfg node ->\n config_node_OK (fst (BDDneg cfg negm node))\n   (fst (snd (BDDneg cfg negm node))).\nProof.\n  intros.  unfold BDDneg in |- *.  elim\n   (prod_sum _ _ (BDDneg_1_1 cfg negm node (S (nat_of_N (var cfg node))))).\n  intro.  elim x; clear x.  intros cfg' node'.  intro.  elim H2; clear H2.\n  intros negm' H2.  rewrite H2.  simpl in |- *.  rewrite (BDDneg_1_1_eq_1 (S (nat_of_N (var cfg node))) cfg negm node)\n    in H2.\n  cut\n   (is_internal_node cfg node ->\n    nat_of_N (var cfg node) < S (nat_of_N (var cfg node))).  intro.  replace cfg' with\n   (fst (fst (BDDneg_1 (cfg, node, negm) (S (nat_of_N (var cfg node)))))).\n  replace node' with\n   (snd (fst (BDDneg_1 (cfg, node, negm) (S (nat_of_N (var cfg node)))))).\n  rewrite\n   (proj1\n      (BDDneg_1_lemma' (S (nat_of_N (var cfg node))) \n         (cfg, node, negm) H H1 H0 H3)).\n  exact\n   (proj1\n      (proj2\n         (proj2\n            (proj2\n               (BDDneg_2_lemma (S (nat_of_N (var cfg node))) cfg node H H1\n                  H3))))).\n  rewrite H2; reflexivity.  rewrite H2; reflexivity.  intro.  unfold lt in |- *.  apply le_n.\nQed.\n\nLemma BDDneg_preserves_nodes :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (node : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n config_node_OK cfg node -> nodes_preserved cfg (fst (BDDneg cfg negm node)).\nProof.\n  intros.  unfold BDDneg in |- *.  elim\n   (prod_sum _ _ (BDDneg_1_1 cfg negm node (S (nat_of_N (var cfg node))))).\n  intro.  elim x; clear x.  intros cfg' node'.  intro.  elim H2; clear H2.\n  intros negm' H2.  rewrite H2.  simpl in |- *.  rewrite (BDDneg_1_1_eq_1 (S (nat_of_N (var cfg node))) cfg negm node)\n    in H2.\n  cut\n   (is_internal_node cfg node ->\n    nat_of_N (var cfg node) < S (nat_of_N (var cfg node))).  intro.  replace cfg' with\n   (fst (fst (BDDneg_1 (cfg, node, negm) (S (nat_of_N (var cfg node)))))).\n  unfold nodes_preserved in |- *.  rewrite\n   (proj1\n      (BDDneg_1_lemma' (S (nat_of_N (var cfg node))) \n         (cfg, node, negm) H H1 H0 H3)).\n  exact (proj1 (proj2 (BDDneg_2_lemma _ _ _ H H1 H3))).  rewrite H2; reflexivity.\n  intro.  unfold lt in |- *.  apply le_n.\nQed.\n\nLemma BDDneg_keeps_neg_memo_OK :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (node : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n config_node_OK cfg node ->\n BDDneg_memo_OK_2 (fst (BDDneg cfg negm node))\n   (snd (snd (BDDneg cfg negm node))).\nProof.\n  intros.  unfold BDDneg in |- *.  elim\n   (prod_sum _ _ (BDDneg_1_1 cfg negm node (S (nat_of_N (var cfg node))))).\n  intro.  elim x; clear x.  intros cfg' node'.  intro.  elim H2; clear H2.\n  intros negm' H2.  rewrite H2.  simpl in |- *.  rewrite (BDDneg_1_1_eq_1 (S (nat_of_N (var cfg node))) cfg negm node)\n    in H2.\n  cut\n   (is_internal_node cfg node ->\n    nat_of_N (var cfg node) < S (nat_of_N (var cfg node))).\n  intro.  replace cfg' with\n   (fst (fst (BDDneg_1 (cfg, node, negm) (S (nat_of_N (var cfg node)))))).\n  replace negm' with\n   (snd (BDDneg_1 (cfg, node, negm) (S (nat_of_N (var cfg node))))).\n  refine (proj2 (BDDneg_1_lemma' _ _ _ _ _ _)).  assumption.  assumption.\n  assumption.  assumption.  rewrite H2; reflexivity.  rewrite H2; reflexivity.\n  intro.  unfold lt in |- *.  apply le_n.\nQed.  \nLemma BDDneg_keeps_or_memo_OK :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (orm : BDDor_memo) (node : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n config_node_OK cfg node ->\n BDDor_memo_OK cfg orm -> BDDor_memo_OK (fst (BDDneg cfg negm node)) orm.\nProof.\n  intros.  apply nodes_preserved_orm_OK with (cfg := cfg).  assumption.  apply BDDneg_keeps_config_OK.\n  assumption.  assumption.  assumption.  apply BDDneg_preserves_nodes.  assumption.\n  assumption.  assumption.  assumption.\nQed.\n\nLemma BDDneg_keeps_node_OK :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (node : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n config_node_OK cfg node ->\n forall node' : ad,\n config_node_OK cfg node' ->\n config_node_OK (fst (BDDneg cfg negm node)) node'.\nProof.\n  intros.  apply nodes_preserved_2 with (cfg := cfg).  assumption.  apply BDDneg_preserves_nodes.\n  assumption.  assumption.  assumption.\nQed.\n\nLemma BDDneg_preserves_bool_fun :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (node : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n config_node_OK cfg node ->\n forall node' : ad,\n config_node_OK cfg node' ->\n bool_fun_eq (bool_fun_of_BDD (fst (BDDneg cfg negm node)) node')\n   (bool_fun_of_BDD cfg node').\nProof.\n  intros.  apply nodes_preserved_3.  assumption.  apply BDDneg_keeps_config_OK.\n  assumption.  assumption.  assumption.  apply BDDneg_preserves_nodes.  assumption.\n  assumption.  assumption.  assumption.\nQed.\n\nLemma BDDneg_is_neg :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (node : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n config_node_OK cfg node ->\n bool_fun_eq\n   (bool_fun_of_BDD (fst (BDDneg cfg negm node))\n      (fst (snd (BDDneg cfg negm node))))\n   (bool_fun_neg (bool_fun_of_BDD cfg node)).\nProof.\n  intros.  unfold BDDneg in |- *.  elim\n   (prod_sum _ _ (BDDneg_1_1 cfg negm node (S (nat_of_N (var cfg node))))).\n  intro.  elim x; clear x.  intros cfg' node'.  intro.  elim H2; clear H2.\n  intros negm' H2.  rewrite H2.  simpl in |- *.  rewrite (BDDneg_1_1_eq_1 (S (nat_of_N (var cfg node))) cfg negm node)\n    in H2.\n  cut\n   (is_internal_node cfg node ->\n    nat_of_N (var cfg node) < S (nat_of_N (var cfg node))).\n  intro.  replace cfg' with\n   (fst (fst (BDDneg_1 (cfg, node, negm) (S (nat_of_N (var cfg node)))))).\n  replace node' with\n   (snd (fst (BDDneg_1 (cfg, node, negm) (S (nat_of_N (var cfg node)))))).\n  rewrite\n   (proj1\n      (BDDneg_1_lemma' (S (nat_of_N (var cfg node))) \n         (cfg, node, negm) H H1 H0 H3)).\n  exact (proj2 (proj2 (proj2 (proj2 (BDDneg_2_lemma _ _ _ H H1 H3))))).\n  rewrite H2; reflexivity.  rewrite H2; reflexivity.  intro.  unfold lt in |- *.  apply le_n.\nQed.\n\nLemma BDDor_keeps_config_OK :\n forall (cfg : BDDconfig) (orm : BDDor_memo) (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 -> BDDconfig_OK (fst (BDDor cfg orm node1 node2)).\nProof.\n  intros.  unfold BDDor in |- *.  rewrite\n   (BDDor_1_1_eq_1\n      (S (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)))) cfg\n      orm node1 node2).\n  cut\n   (is_internal_node cfg node1 ->\n    is_internal_node cfg node2 ->\n    max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)) <\n    S (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)))).\n  intros.  refine (proj1 (BDDor_1_lemma _ _ _ _ _ _ _ _ _ _)).  assumption.\n  assumption.  assumption.  assumption.  assumption.  intros.  unfold lt in |- *.  apply le_n.\nQed.\n\nLemma BDDor_node_OK :\n forall (cfg : BDDconfig) (orm : BDDor_memo) (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n config_node_OK (fst (BDDor cfg orm node1 node2))\n   (fst (snd (BDDor cfg orm node1 node2))).\nProof.\n  intros.  unfold BDDor in |- *.  rewrite\n   (BDDor_1_1_eq_1\n      (S (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)))) cfg\n      orm node1 node2).\n  cut\n   (is_internal_node cfg node1 ->\n    is_internal_node cfg node2 ->\n    max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)) <\n    S (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)))).\n  intros.  refine (proj1 (proj2 (proj2 (BDDor_1_lemma _ _ _ _ _ _ _ _ _ _)))).\n  assumption.  assumption.  assumption.  assumption.  assumption.  intros.\n  unfold lt in |- *.  apply le_n.\nQed.\n\nLemma BDDor_keeps_or_memo_OK :\n forall (cfg : BDDconfig) (orm : BDDor_memo) (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n BDDor_memo_OK (fst (BDDor cfg orm node1 node2))\n   (snd (snd (BDDor cfg orm node1 node2))).\nProof.\n  intros.  unfold BDDor in |- *.  rewrite\n   (BDDor_1_1_eq_1\n      (S (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)))) cfg\n      orm node1 node2).\n  cut\n   (is_internal_node cfg node1 ->\n    is_internal_node cfg node2 ->\n    max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)) <\n    S (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)))).\n  intros.  refine (proj1 (proj2 (BDDor_1_lemma _ _ _ _ _ _ _ _ _ _))).  \n  assumption.  assumption.  assumption.  assumption.  assumption.  intros.\n  unfold lt in |- *.  apply le_n.\nQed.\n\nLemma BDDor_preserves_nodes :\n forall (cfg : BDDconfig) (orm : BDDor_memo) (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n nodes_preserved cfg (fst (BDDor cfg orm node1 node2)).\nProof.\n  intros.  unfold BDDor in |- *.  rewrite\n   (BDDor_1_1_eq_1\n      (S (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)))) cfg\n      orm node1 node2).\n  cut\n   (is_internal_node cfg node1 ->\n    is_internal_node cfg node2 ->\n    max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)) <\n    S (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)))).\n  intros.  refine (proj1 (proj2 (proj2 (proj2 (BDDor_1_lemma _ _ _ _ _ _ _ _ _ _))))).\n  assumption.  assumption.  assumption.  assumption.  assumption.  intros.  unfold lt in |- *.\n  apply le_n.\nQed.\n\nLemma BDDor_keeps_node_OK :\n forall (cfg : BDDconfig) (orm : BDDor_memo) (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n forall node : ad,\n config_node_OK cfg node ->\n config_node_OK (fst (BDDor cfg orm node1 node2)) node.\nProof.\n  intros.  apply nodes_preserved_2 with (cfg := cfg).  assumption.  apply BDDor_preserves_nodes.\n  assumption.  assumption.  assumption.  assumption.\nQed.\n\nLemma BDDor_preserves_bool_fun :\n forall (cfg : BDDconfig) (orm : BDDor_memo) (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n forall node : ad,\n config_node_OK cfg node ->\n bool_fun_eq (bool_fun_of_BDD (fst (BDDor cfg orm node1 node2)) node)\n   (bool_fun_of_BDD cfg node).\nProof.\n  intros.  apply nodes_preserved_3.  assumption.  apply BDDor_keeps_config_OK.\n  assumption.  assumption.  assumption.  assumption.  apply BDDor_preserves_nodes.\n  assumption.  assumption.  assumption.  assumption.  assumption.\nQed.\n\nLemma BDDor_keeps_neg_memo_OK :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (orm : BDDor_memo)\n   (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n BDDneg_memo_OK_2 cfg negm ->\n BDDneg_memo_OK_2 (fst (BDDor cfg orm node1 node2)) negm.\nProof.\n  intros.  apply nodes_preserved_negm_OK with (cfg := cfg).  assumption.  apply BDDor_keeps_config_OK.\n  assumption.  assumption.  assumption.  assumption.  apply BDDor_preserves_nodes.\n  assumption.  assumption.  assumption.  assumption.  assumption.\nQed.\n\nLemma BDDor_is_or :\n forall (cfg : BDDconfig) (orm : BDDor_memo) (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n bool_fun_eq\n   (bool_fun_of_BDD (fst (BDDor cfg orm node1 node2))\n      (fst (snd (BDDor cfg orm node1 node2))))\n   (bool_fun_or (bool_fun_of_BDD cfg node1) (bool_fun_of_BDD cfg node2)).\nProof.\n  intros.  unfold BDDor in |- *.  rewrite\n   (BDDor_1_1_eq_1\n      (S (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)))) cfg\n      orm node1 node2).\n  cut\n   (is_internal_node cfg node1 ->\n    is_internal_node cfg node2 ->\n    max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)) <\n    S (max (nat_of_N (var cfg node1)) (nat_of_N (var cfg node2)))).\n  intros.  refine\n   (proj2 (proj2 (proj2 (proj2 (proj2 (BDDor_1_lemma _ _ _ _ _ _ _ _ _ _)))))).\n  assumption.  assumption.  assumption.  assumption.  assumption.  intros.  unfold lt in |- *.\n  apply le_n.\nQed.\n\nLemma BDDand_keeps_config_OK :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (orm : BDDor_memo)\n   (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n BDDconfig_OK (fst (BDDand cfg negm orm node1 node2)).\nProof.\n\n  intros.  unfold BDDand in |- *.  elim (prod_sum _ _ (BDDneg cfg negm node1)).  intros cfg' H4.\n  elim H4; clear H4.  intro.  elim x; clear x.  intros node1' negm' H4.  rewrite H4.\n  elim (prod_sum _ _ (BDDneg cfg' negm' node2)).  intros cfg'' H5.  elim H5; clear H5.\n  intro.  elim x; clear x.  intros node2' negm'' H5.  rewrite H5.  elim (prod_sum _ _ (BDDor cfg'' orm node1' node2')).\n  intros cfg''' H6.  elim H6; clear H6.  intro.  elim x; clear x.  intros node orm' H6.\n  rewrite H6.  elim (prod_sum _ _ (BDDneg cfg''' negm'' node)).  intros cfg'''' H7.\n  elim H7; clear H7.  intro.  elim x; clear x.  intros node' negm''' H7.  rewrite H7.\n  simpl in |- *.  cut (BDDconfig_OK cfg').  cut (config_node_OK cfg' node1').  cut (config_node_OK cfg' node2).\n  cut (BDDneg_memo_OK_2 cfg' negm').  cut (BDDor_memo_OK cfg' orm).  intros.\n  cut (BDDconfig_OK cfg'').  cut (config_node_OK cfg'' node2').  cut (config_node_OK cfg'' node1').\n  cut (BDDneg_memo_OK_2 cfg'' negm'').  cut (BDDor_memo_OK cfg'' orm).  intros.\n  cut (BDDconfig_OK cfg''').  cut (config_node_OK cfg''' node).  cut (BDDneg_memo_OK_2 cfg''' negm'').\n  cut (BDDor_memo_OK cfg''' orm').  intros.\n\n\n  replace cfg'''' with (fst (BDDneg cfg''' negm'' node)).\napply BDDneg_keeps_config_OK.\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H7; reflexivity.\n\n\n\n\n  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).  replace orm' with (snd (snd (BDDor cfg'' orm node1' node2'))).\n  apply BDDor_keeps_or_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H6; reflexivity.  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  apply BDDor_keeps_neg_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  assumption.  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  replace node with (fst (snd (BDDor cfg'' orm node1' node2'))).  apply BDDor_node_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H6; reflexivity.\n  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  apply BDDor_keeps_config_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H6; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  apply BDDneg_keeps_or_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H5; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  replace negm'' with (snd (snd (BDDneg cfg' negm' node2))).  apply BDDneg_keeps_neg_memo_OK.\n  assumption.  assumption.  assumption.  rewrite H5; reflexivity.  rewrite H5; reflexivity.\n  replace cfg'' with (fst (BDDneg cfg' negm' node2)).  apply BDDneg_keeps_node_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H5; reflexivity.\n  replace cfg'' with (fst (BDDneg cfg' negm' node2)).  replace node2' with (fst (snd (BDDneg cfg' negm' node2))).  apply BDDneg_node_OK.  assumption.  assumption.\n  assumption.  rewrite H5; reflexivity.  rewrite H5; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  apply BDDneg_keeps_config_OK.  assumption.  assumption.  assumption.  rewrite H5; reflexivity.\n\n  replace cfg' with (fst (BDDneg cfg negm node1)).  apply BDDneg_keeps_or_memo_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n  replace cfg' with (fst (BDDneg cfg negm node1)).  replace negm' with (snd (snd (BDDneg cfg negm node1))).\n  apply BDDneg_keeps_neg_memo_OK.  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n  rewrite H4; reflexivity.  replace cfg' with (fst (BDDneg cfg negm node1)).\n  apply BDDneg_keeps_node_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H4; reflexivity.  replace cfg' with (fst (BDDneg cfg negm node1)).\n  replace node1' with (fst (snd (BDDneg cfg negm node1))).  apply BDDneg_node_OK.\n  assumption.  assumption.  assumption.  rewrite H4; reflexivity.  rewrite H4; reflexivity.\n  replace cfg' with (fst (BDDneg cfg negm node1)).  apply BDDneg_keeps_config_OK.\n  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n\n\nQed.\n\nLemma BDDand_node_OK :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (orm : BDDor_memo)\n   (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n config_node_OK (fst (BDDand cfg negm orm node1 node2))\n   (fst (snd (BDDand cfg negm orm node1 node2))).\nProof.\n\n\n  intros.  unfold BDDand in |- *.  elim (prod_sum _ _ (BDDneg cfg negm node1)).  intros cfg' H4.\n  elim H4; clear H4.  intro.  elim x; clear x.  intros node1' negm' H4.  rewrite H4.\n  elim (prod_sum _ _ (BDDneg cfg' negm' node2)).  intros cfg'' H5.  elim H5; clear H5.\n  intro.  elim x; clear x.  intros node2' negm'' H5.  rewrite H5.  elim (prod_sum _ _ (BDDor cfg'' orm node1' node2')).\n  intros cfg''' H6.  elim H6; clear H6.  intro.  elim x; clear x.  intros node orm' H6.\n  rewrite H6.  elim (prod_sum _ _ (BDDneg cfg''' negm'' node)).  intros cfg'''' H7.\n  elim H7; clear H7.  intro.  elim x; clear x.  intros node' negm''' H7.  rewrite H7.\n  simpl in |- *.  cut (BDDconfig_OK cfg').  cut (config_node_OK cfg' node1').  cut (config_node_OK cfg' node2).\n  cut (BDDneg_memo_OK_2 cfg' negm').  cut (BDDor_memo_OK cfg' orm).  intros.\n  cut (BDDconfig_OK cfg'').  cut (config_node_OK cfg'' node2').  cut (config_node_OK cfg'' node1').\n  cut (BDDneg_memo_OK_2 cfg'' negm'').  cut (BDDor_memo_OK cfg'' orm).  intros.\n  cut (BDDconfig_OK cfg''').  cut (config_node_OK cfg''' node).  cut (BDDneg_memo_OK_2 cfg''' negm'').\n  cut (BDDor_memo_OK cfg''' orm').  intros.\n\n\nreplace cfg'''' with (fst (BDDneg cfg''' negm'' node)).\nreplace node' with (fst (snd (BDDneg cfg''' negm'' node))).\napply BDDneg_node_OK.\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H7; reflexivity.\n\nrewrite H7; reflexivity.\n\n\n\n  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).  replace orm' with (snd (snd (BDDor cfg'' orm node1' node2'))).\n  apply BDDor_keeps_or_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H6; reflexivity.  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  apply BDDor_keeps_neg_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  assumption.  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  replace node with (fst (snd (BDDor cfg'' orm node1' node2'))).  apply BDDor_node_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H6; reflexivity.\n  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  apply BDDor_keeps_config_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H6; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  apply BDDneg_keeps_or_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H5; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  replace negm'' with (snd (snd (BDDneg cfg' negm' node2))).  apply BDDneg_keeps_neg_memo_OK.\n  assumption.  assumption.  assumption.  rewrite H5; reflexivity.  rewrite H5; reflexivity.\n  replace cfg'' with (fst (BDDneg cfg' negm' node2)).  apply BDDneg_keeps_node_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H5; reflexivity.\n  replace cfg'' with (fst (BDDneg cfg' negm' node2)).  replace node2' with (fst (snd (BDDneg cfg' negm' node2))).  apply BDDneg_node_OK.  assumption.  assumption.\n  assumption.  rewrite H5; reflexivity.  rewrite H5; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  apply BDDneg_keeps_config_OK.  assumption.  assumption.  assumption.  rewrite H5; reflexivity.\n\n  replace cfg' with (fst (BDDneg cfg negm node1)).  apply BDDneg_keeps_or_memo_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n  replace cfg' with (fst (BDDneg cfg negm node1)).  replace negm' with (snd (snd (BDDneg cfg negm node1))).\n  apply BDDneg_keeps_neg_memo_OK.  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n  rewrite H4; reflexivity.  replace cfg' with (fst (BDDneg cfg negm node1)).\n  apply BDDneg_keeps_node_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H4; reflexivity.  replace cfg' with (fst (BDDneg cfg negm node1)).\n  replace node1' with (fst (snd (BDDneg cfg negm node1))).  apply BDDneg_node_OK.\n  assumption.  assumption.  assumption.  rewrite H4; reflexivity.  rewrite H4; reflexivity.\n  replace cfg' with (fst (BDDneg cfg negm node1)).  apply BDDneg_keeps_config_OK.\n  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n\nQed.\n\nLemma BDDand_preserves_nodes :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (orm : BDDor_memo)\n   (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n nodes_preserved cfg (fst (BDDand cfg negm orm node1 node2)).\nProof.\n\n  intros.  unfold BDDand in |- *.  elim (prod_sum _ _ (BDDneg cfg negm node1)).  intros cfg' H4.\n  elim H4; clear H4.  intro.  elim x; clear x.  intros node1' negm' H4.  rewrite H4.\n  elim (prod_sum _ _ (BDDneg cfg' negm' node2)).  intros cfg'' H5.  elim H5; clear H5.\n  intro.  elim x; clear x.  intros node2' negm'' H5.  rewrite H5.  elim (prod_sum _ _ (BDDor cfg'' orm node1' node2')).\n  intros cfg''' H6.  elim H6; clear H6.  intro.  elim x; clear x.  intros node orm' H6.\n  rewrite H6.  elim (prod_sum _ _ (BDDneg cfg''' negm'' node)).  intros cfg'''' H7.\n  elim H7; clear H7.  intro.  elim x; clear x.  intros node' negm''' H7.  rewrite H7.\n  simpl in |- *.  cut (BDDconfig_OK cfg').  cut (config_node_OK cfg' node1').  cut (config_node_OK cfg' node2).\n  cut (BDDneg_memo_OK_2 cfg' negm').  cut (BDDor_memo_OK cfg' orm).  intros.\n  cut (BDDconfig_OK cfg'').  cut (config_node_OK cfg'' node2').  cut (config_node_OK cfg'' node1').\n  cut (BDDneg_memo_OK_2 cfg'' negm'').  cut (BDDor_memo_OK cfg'' orm).  intros.\n  cut (BDDconfig_OK cfg''').  cut (config_node_OK cfg''' node).  cut (BDDneg_memo_OK_2 cfg''' negm'').\n  cut (BDDor_memo_OK cfg''' orm').  intros.\n\n\napply nodes_preserved_trans with (cfg2 := cfg').\nreplace cfg' with (fst (BDDneg cfg negm node1)).\napply BDDneg_preserves_nodes.\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H4; reflexivity.\n\napply nodes_preserved_trans with (cfg2 := cfg'').\nreplace cfg'' with (fst (BDDneg cfg' negm' node2)).\napply BDDneg_preserves_nodes.\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H5; reflexivity.\n\napply nodes_preserved_trans with (cfg2 := cfg''').\nreplace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\napply BDDor_preserves_nodes.\nassumption.\n\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H6; reflexivity.\n\nreplace cfg'''' with (fst (BDDneg cfg''' negm'' node)).\napply BDDneg_preserves_nodes.\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H7; reflexivity.\n\n\n  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).  replace orm' with (snd (snd (BDDor cfg'' orm node1' node2'))).\n  apply BDDor_keeps_or_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H6; reflexivity.  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  apply BDDor_keeps_neg_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  assumption.  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  replace node with (fst (snd (BDDor cfg'' orm node1' node2'))).  apply BDDor_node_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H6; reflexivity.\n  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  apply BDDor_keeps_config_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H6; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  apply BDDneg_keeps_or_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H5; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  replace negm'' with (snd (snd (BDDneg cfg' negm' node2))).  apply BDDneg_keeps_neg_memo_OK.\n  assumption.  assumption.  assumption.  rewrite H5; reflexivity.  rewrite H5; reflexivity.\n  replace cfg'' with (fst (BDDneg cfg' negm' node2)).  apply BDDneg_keeps_node_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H5; reflexivity.\n  replace cfg'' with (fst (BDDneg cfg' negm' node2)).  replace node2' with (fst (snd (BDDneg cfg' negm' node2))).  apply BDDneg_node_OK.  assumption.  assumption.\n  assumption.  rewrite H5; reflexivity.  rewrite H5; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  apply BDDneg_keeps_config_OK.  assumption.  assumption.  assumption.  rewrite H5; reflexivity.\n\n  replace cfg' with (fst (BDDneg cfg negm node1)).  apply BDDneg_keeps_or_memo_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n  replace cfg' with (fst (BDDneg cfg negm node1)).  replace negm' with (snd (snd (BDDneg cfg negm node1))).\n  apply BDDneg_keeps_neg_memo_OK.  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n  rewrite H4; reflexivity.  replace cfg' with (fst (BDDneg cfg negm node1)).\n  apply BDDneg_keeps_node_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H4; reflexivity.  replace cfg' with (fst (BDDneg cfg negm node1)).\n  replace node1' with (fst (snd (BDDneg cfg negm node1))).  apply BDDneg_node_OK.\n  assumption.  assumption.  assumption.  rewrite H4; reflexivity.  rewrite H4; reflexivity.\n  replace cfg' with (fst (BDDneg cfg negm node1)).  apply BDDneg_keeps_config_OK.\n  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n\nQed.\n\nLemma BDDand_keeps_node_OK :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (orm : BDDor_memo)\n   (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n forall node : ad,\n config_node_OK cfg node ->\n config_node_OK (fst (BDDand cfg negm orm node1 node2)) node.\nProof.\n  intros.  apply nodes_preserved_2 with (cfg := cfg).  assumption.  apply BDDand_preserves_nodes.\n  assumption.  assumption.  assumption.  assumption.  assumption.\nQed.\n\nLemma BDDand_preserves_bool_fun :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (orm : BDDor_memo)\n   (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n forall node : ad,\n config_node_OK cfg node ->\n bool_fun_eq (bool_fun_of_BDD (fst (BDDand cfg negm orm node1 node2)) node)\n   (bool_fun_of_BDD cfg node).\nProof.\n  intros.  apply nodes_preserved_3.  assumption.  apply BDDand_keeps_config_OK.\n  assumption.  assumption.  assumption.  assumption.  assumption.  apply BDDand_preserves_nodes.\n  assumption.  assumption.  assumption.  assumption.  assumption.  assumption.\nQed.\n\nLemma BDDand_keeps_neg_memo_OK :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (orm : BDDor_memo)\n   (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n BDDneg_memo_OK_2 (fst (BDDand cfg negm orm node1 node2))\n   (fst (snd (snd (BDDand cfg negm orm node1 node2)))).\nProof.\n\n  intros.  unfold BDDand in |- *.  elim (prod_sum _ _ (BDDneg cfg negm node1)).  intros cfg' H4.\n  elim H4; clear H4.  intro.  elim x; clear x.  intros node1' negm' H4.  rewrite H4.\n  elim (prod_sum _ _ (BDDneg cfg' negm' node2)).  intros cfg'' H5.  elim H5; clear H5.\n  intro.  elim x; clear x.  intros node2' negm'' H5.  rewrite H5.  elim (prod_sum _ _ (BDDor cfg'' orm node1' node2')).\n  intros cfg''' H6.  elim H6; clear H6.  intro.  elim x; clear x.  intros node orm' H6.\n  rewrite H6.  elim (prod_sum _ _ (BDDneg cfg''' negm'' node)).  intros cfg'''' H7.\n  elim H7; clear H7.  intro.  elim x; clear x.  intros node' negm''' H7.  rewrite H7.\n  simpl in |- *.  cut (BDDconfig_OK cfg').  cut (config_node_OK cfg' node1').  cut (config_node_OK cfg' node2).\n  cut (BDDneg_memo_OK_2 cfg' negm').  cut (BDDor_memo_OK cfg' orm).  intros.\n  cut (BDDconfig_OK cfg'').  cut (config_node_OK cfg'' node2').  cut (config_node_OK cfg'' node1').\n  cut (BDDneg_memo_OK_2 cfg'' negm'').  cut (BDDor_memo_OK cfg'' orm).  intros.\n  cut (BDDconfig_OK cfg''').  cut (config_node_OK cfg''' node).  cut (BDDneg_memo_OK_2 cfg''' negm'').\n  cut (BDDor_memo_OK cfg''' orm').  intros.\n\n\nreplace cfg'''' with (fst (BDDneg cfg''' negm'' node)).\nreplace negm''' with (snd (snd (BDDneg cfg''' negm'' node))).\napply BDDneg_keeps_neg_memo_OK.\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H7; reflexivity.\n\nrewrite H7; reflexivity.\n\n\n\n  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).  replace orm' with (snd (snd (BDDor cfg'' orm node1' node2'))).\n  apply BDDor_keeps_or_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H6; reflexivity.  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  apply BDDor_keeps_neg_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  assumption.  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  replace node with (fst (snd (BDDor cfg'' orm node1' node2'))).  apply BDDor_node_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H6; reflexivity.\n  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  apply BDDor_keeps_config_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H6; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  apply BDDneg_keeps_or_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H5; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  replace negm'' with (snd (snd (BDDneg cfg' negm' node2))).  apply BDDneg_keeps_neg_memo_OK.\n  assumption.  assumption.  assumption.  rewrite H5; reflexivity.  rewrite H5; reflexivity.\n  replace cfg'' with (fst (BDDneg cfg' negm' node2)).  apply BDDneg_keeps_node_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H5; reflexivity.\n  replace cfg'' with (fst (BDDneg cfg' negm' node2)).  replace node2' with (fst (snd (BDDneg cfg' negm' node2))).  apply BDDneg_node_OK.  assumption.  assumption.\n  assumption.  rewrite H5; reflexivity.  rewrite H5; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  apply BDDneg_keeps_config_OK.  assumption.  assumption.  assumption.  rewrite H5; reflexivity.\n\n  replace cfg' with (fst (BDDneg cfg negm node1)).  apply BDDneg_keeps_or_memo_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n  replace cfg' with (fst (BDDneg cfg negm node1)).  replace negm' with (snd (snd (BDDneg cfg negm node1))).\n  apply BDDneg_keeps_neg_memo_OK.  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n  rewrite H4; reflexivity.  replace cfg' with (fst (BDDneg cfg negm node1)).\n  apply BDDneg_keeps_node_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H4; reflexivity.  replace cfg' with (fst (BDDneg cfg negm node1)).\n  replace node1' with (fst (snd (BDDneg cfg negm node1))).  apply BDDneg_node_OK.\n  assumption.  assumption.  assumption.  rewrite H4; reflexivity.  rewrite H4; reflexivity.\n  replace cfg' with (fst (BDDneg cfg negm node1)).  apply BDDneg_keeps_config_OK.\n  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n\nQed.\n\nLemma BDDand_keeps_or_memo_OK :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (orm : BDDor_memo)\n   (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n BDDor_memo_OK (fst (BDDand cfg negm orm node1 node2))\n   (snd (snd (snd (BDDand cfg negm orm node1 node2)))).\nProof.\n\n  intros.  unfold BDDand in |- *.  elim (prod_sum _ _ (BDDneg cfg negm node1)).  intros cfg' H4.\n  elim H4; clear H4.  intro.  elim x; clear x.  intros node1' negm' H4.  rewrite H4.\n  elim (prod_sum _ _ (BDDneg cfg' negm' node2)).  intros cfg'' H5.  elim H5; clear H5.\n  intro.  elim x; clear x.  intros node2' negm'' H5.  rewrite H5.  elim (prod_sum _ _ (BDDor cfg'' orm node1' node2')).\n  intros cfg''' H6.  elim H6; clear H6.  intro.  elim x; clear x.  intros node orm' H6.\n  rewrite H6.  elim (prod_sum _ _ (BDDneg cfg''' negm'' node)).  intros cfg'''' H7.\n  elim H7; clear H7.  intro.  elim x; clear x.  intros node' negm''' H7.  rewrite H7.\n  simpl in |- *.  cut (BDDconfig_OK cfg').  cut (config_node_OK cfg' node1').  cut (config_node_OK cfg' node2).\n  cut (BDDneg_memo_OK_2 cfg' negm').  cut (BDDor_memo_OK cfg' orm).  intros.\n  cut (BDDconfig_OK cfg'').  cut (config_node_OK cfg'' node2').  cut (config_node_OK cfg'' node1').\n  cut (BDDneg_memo_OK_2 cfg'' negm'').  cut (BDDor_memo_OK cfg'' orm).  intros.\n  cut (BDDconfig_OK cfg''').  cut (config_node_OK cfg''' node).  cut (BDDneg_memo_OK_2 cfg''' negm'').\n  cut (BDDor_memo_OK cfg''' orm').  intros.\n\n\nreplace cfg'''' with (fst (BDDneg cfg''' negm'' node)).\napply BDDneg_keeps_or_memo_OK.\nassumption.\n\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H7; reflexivity.\n\n\n\n\n  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).  replace orm' with (snd (snd (BDDor cfg'' orm node1' node2'))).\n  apply BDDor_keeps_or_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H6; reflexivity.  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  apply BDDor_keeps_neg_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  assumption.  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  replace node with (fst (snd (BDDor cfg'' orm node1' node2'))).  apply BDDor_node_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H6; reflexivity.\n  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  apply BDDor_keeps_config_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H6; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  apply BDDneg_keeps_or_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H5; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  replace negm'' with (snd (snd (BDDneg cfg' negm' node2))).  apply BDDneg_keeps_neg_memo_OK.\n  assumption.  assumption.  assumption.  rewrite H5; reflexivity.  rewrite H5; reflexivity.\n  replace cfg'' with (fst (BDDneg cfg' negm' node2)).  apply BDDneg_keeps_node_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H5; reflexivity.\n  replace cfg'' with (fst (BDDneg cfg' negm' node2)).  replace node2' with (fst (snd (BDDneg cfg' negm' node2))).  apply BDDneg_node_OK.  assumption.  assumption.\n  assumption.  rewrite H5; reflexivity.  rewrite H5; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  apply BDDneg_keeps_config_OK.  assumption.  assumption.  assumption.  rewrite H5; reflexivity.\n\n  replace cfg' with (fst (BDDneg cfg negm node1)).  apply BDDneg_keeps_or_memo_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n  replace cfg' with (fst (BDDneg cfg negm node1)).  replace negm' with (snd (snd (BDDneg cfg negm node1))).\n  apply BDDneg_keeps_neg_memo_OK.  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n  rewrite H4; reflexivity.  replace cfg' with (fst (BDDneg cfg negm node1)).\n  apply BDDneg_keeps_node_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H4; reflexivity.  replace cfg' with (fst (BDDneg cfg negm node1)).\n  replace node1' with (fst (snd (BDDneg cfg negm node1))).  apply BDDneg_node_OK.\n  assumption.  assumption.  assumption.  rewrite H4; reflexivity.  rewrite H4; reflexivity.\n  replace cfg' with (fst (BDDneg cfg negm node1)).  apply BDDneg_keeps_config_OK.\n  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n\nQed.\n\nDefinition bool_fun_and (bf1 bf2 : bool_fun) : bool_fun :=\n  fun vb : var_binding => bf1 vb && bf2 vb.\n\nLemma bool_fun_and_is_neg_or_neg_neg :\n forall bf1 bf2 : bool_fun,\n bool_fun_eq (bool_fun_and bf1 bf2)\n   (bool_fun_neg (bool_fun_or (bool_fun_neg bf1) (bool_fun_neg bf2))).\nProof.\n  intros.  unfold bool_fun_eq, bool_fun_neg, bool_fun_or, bool_fun_and in |- *.  unfold bool_fun_eval in |- *.\n  intro.  elim (bf1 vb).  elim (bf2 vb).  reflexivity.  reflexivity.  reflexivity.\nQed.\n\nLemma BDDand_is_and :\n forall (cfg : BDDconfig) (negm : BDDneg_memo) (orm : BDDor_memo)\n   (node1 node2 : ad),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg negm ->\n BDDor_memo_OK cfg orm ->\n config_node_OK cfg node1 ->\n config_node_OK cfg node2 ->\n bool_fun_eq\n   (bool_fun_of_BDD (fst (BDDand cfg negm orm node1 node2))\n      (fst (snd (BDDand cfg negm orm node1 node2))))\n   (bool_fun_and (bool_fun_of_BDD cfg node1) (bool_fun_of_BDD cfg node2)).\nProof.\n\n  intros.  unfold BDDand in |- *.  elim (prod_sum _ _ (BDDneg cfg negm node1)).  intros cfg' H4.\n  elim H4; clear H4.  intro.  elim x; clear x.  intros node1' negm' H4.  rewrite H4.\n  elim (prod_sum _ _ (BDDneg cfg' negm' node2)).  intros cfg'' H5.  elim H5; clear H5.\n  intro.  elim x; clear x.  intros node2' negm'' H5.  rewrite H5.  elim (prod_sum _ _ (BDDor cfg'' orm node1' node2')).\n  intros cfg''' H6.  elim H6; clear H6.  intro.  elim x; clear x.  intros node orm' H6.\n  rewrite H6.  elim (prod_sum _ _ (BDDneg cfg''' negm'' node)).  intros cfg'''' H7.\n  elim H7; clear H7.  intro.  elim x; clear x.  intros node' negm''' H7.  rewrite H7.\n  simpl in |- *.  cut (BDDconfig_OK cfg').  cut (config_node_OK cfg' node1').  cut (config_node_OK cfg' node2).\n  cut (BDDneg_memo_OK_2 cfg' negm').  cut (BDDor_memo_OK cfg' orm).  intros.\n  cut (BDDconfig_OK cfg'').  cut (config_node_OK cfg'' node2').  cut (config_node_OK cfg'' node1').\n  cut (BDDneg_memo_OK_2 cfg'' negm'').  cut (BDDor_memo_OK cfg'' orm).  intros.\n  cut (BDDconfig_OK cfg''').  cut (config_node_OK cfg''' node).  cut (BDDneg_memo_OK_2 cfg''' negm'').\n  cut (BDDor_memo_OK cfg''' orm').  intros.\n\n\n\napply\n bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_of_BDD cfg''' node)).\nreplace cfg'''' with (fst (BDDneg cfg''' negm'' node)).\nreplace node' with (fst (snd (BDDneg cfg''' negm'' node))).\napply BDDneg_is_neg.\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H7; reflexivity.\n\nrewrite H7; reflexivity.\n\napply\n bool_fun_eq_trans\n  with\n    (bf2 := bool_fun_neg\n              (bool_fun_or (bool_fun_of_BDD cfg'' node1')\n                 (bool_fun_of_BDD cfg'' node2'))).\napply bool_fun_eq_neg_1.\nreplace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\nreplace node with (fst (snd (BDDor cfg'' orm node1' node2'))).\napply BDDor_is_or.\nassumption.\n\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H6; reflexivity.\n\nrewrite H6; reflexivity.\n\napply\n bool_fun_eq_trans\n  with\n    (bf2 := bool_fun_neg\n              (bool_fun_or (bool_fun_neg (bool_fun_of_BDD cfg node1))\n                 (bool_fun_neg (bool_fun_of_BDD cfg node2)))).\napply bool_fun_eq_neg_1.\napply bool_fun_or_preserves_eq.\napply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfg' node1').\nreplace cfg'' with (fst (BDDneg cfg' negm' node2)).\napply BDDneg_preserves_bool_fun.\nassumption.\n\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H5; reflexivity.\n\nreplace cfg' with (fst (BDDneg cfg negm node1)).\nreplace node1' with (fst (snd (BDDneg cfg negm node1))).\napply BDDneg_is_neg.\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H4; reflexivity.\n\nrewrite H4; reflexivity.\n\napply\n bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_of_BDD cfg' node2)).\nreplace cfg'' with (fst (BDDneg cfg' negm' node2)).\nreplace node2' with (fst (snd (BDDneg cfg' negm' node2))).\napply BDDneg_is_neg.\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H5; reflexivity.\n\nrewrite H5; reflexivity.\n\nreplace cfg' with (fst (BDDneg cfg negm node1)).\napply bool_fun_eq_neg_1.\napply BDDneg_preserves_bool_fun.\nassumption.\n\nassumption.\n\nassumption.\n\nassumption.\n\nrewrite H4; reflexivity.\n\napply bool_fun_eq_symm.\napply bool_fun_and_is_neg_or_neg_neg.\n\n\n  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).  replace orm' with (snd (snd (BDDor cfg'' orm node1' node2'))).\n  apply BDDor_keeps_or_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H6; reflexivity.  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  apply BDDor_keeps_neg_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  assumption.  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  replace node with (fst (snd (BDDor cfg'' orm node1' node2'))).  apply BDDor_node_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H6; reflexivity.\n  rewrite H6; reflexivity.  replace cfg''' with (fst (BDDor cfg'' orm node1' node2')).\n  apply BDDor_keeps_config_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H6; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  apply BDDneg_keeps_or_memo_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H5; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  replace negm'' with (snd (snd (BDDneg cfg' negm' node2))).  apply BDDneg_keeps_neg_memo_OK.\n  assumption.  assumption.  assumption.  rewrite H5; reflexivity.  rewrite H5; reflexivity.\n  replace cfg'' with (fst (BDDneg cfg' negm' node2)).  apply BDDneg_keeps_node_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H5; reflexivity.\n  replace cfg'' with (fst (BDDneg cfg' negm' node2)).  replace node2' with (fst (snd (BDDneg cfg' negm' node2))).  apply BDDneg_node_OK.  assumption.  assumption.\n  assumption.  rewrite H5; reflexivity.  rewrite H5; reflexivity.  replace cfg'' with (fst (BDDneg cfg' negm' node2)).\n  apply BDDneg_keeps_config_OK.  assumption.  assumption.  assumption.  rewrite H5; reflexivity.\n\n  replace cfg' with (fst (BDDneg cfg negm node1)).  apply BDDneg_keeps_or_memo_OK.\n  assumption.  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n  replace cfg' with (fst (BDDneg cfg negm node1)).  replace negm' with (snd (snd (BDDneg cfg negm node1))).\n  apply BDDneg_keeps_neg_memo_OK.  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n  rewrite H4; reflexivity.  replace cfg' with (fst (BDDneg cfg negm node1)).\n  apply BDDneg_keeps_node_OK.  assumption.  assumption.  assumption.  assumption.\n  rewrite H4; reflexivity.  replace cfg' with (fst (BDDneg cfg negm node1)).\n  replace node1' with (fst (snd (BDDneg cfg negm node1))).  apply BDDneg_node_OK.\n  assumption.  assumption.  assumption.  rewrite H4; reflexivity.  rewrite H4; reflexivity.\n  replace cfg' with (fst (BDDneg cfg negm node1)).  apply BDDneg_keeps_config_OK.\n  assumption.  assumption.  assumption.  rewrite H4; reflexivity.\n\nQed.", "meta": {"author": "coq-contribs", "repo": "bdds", "sha": "2a66529afca7c780fa18d21ecd4f6c8d55182a6d", "save_path": "github-repos/coq/coq-contribs-bdds", "path": "github-repos/coq/coq-contribs-bdds/bdds-2a66529afca7c780fa18d21ecd4f6c8d55182a6d/bdd10.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24016286993479335}}
{"text": "(*\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(** Imp with the Json data model *)\n\nRequire Import String.\nRequire Import List.\nRequire Import ZArith.\nRequire Import Utils.\nRequire Import BrandRelation.\nRequire Import ForeignEJson.\nRequire Import EJson.\nRequire Import EJsonGroupBy.\nRequire Import EJsonSortBy.\nRequire Import ForeignEJsonRuntime.\n\nSection EJsonRuntimeOperators.\n  Local Open Scope string.\n\n  Context {foreign_ejson_model:Set}.\n  Context {fejson:foreign_ejson foreign_ejson_model}.\n  Context {foreign_ejson_runtime_op : Set}.\n\n  Section Syntax.\n    Inductive ejson_runtime_op :=\n    (* Generic *)\n    | EJsonRuntimeEqual : ejson_runtime_op\n    | EJsonRuntimeCompare : ejson_runtime_op\n    | EJsonRuntimeToString : ejson_runtime_op\n    | EJsonRuntimeToText : ejson_runtime_op\n    (* Record *)\n    | EJsonRuntimeRecConcat : ejson_runtime_op\n    | EJsonRuntimeRecMerge : ejson_runtime_op\n    | EJsonRuntimeRecRemove: ejson_runtime_op\n    | EJsonRuntimeRecProject: ejson_runtime_op\n    | EJsonRuntimeRecDot : ejson_runtime_op\n    (* Array *)\n    | EJsonRuntimeArray : ejson_runtime_op\n    | EJsonRuntimeArrayLength : ejson_runtime_op\n    | EJsonRuntimeArrayPush : ejson_runtime_op\n    | EJsonRuntimeArrayAccess : ejson_runtime_op\n    (* Sum *)\n    | EJsonRuntimeEither : ejson_runtime_op\n    | EJsonRuntimeToLeft: ejson_runtime_op\n    | EJsonRuntimeToRight: ejson_runtime_op\n    (* Brand *)\n    | EJsonRuntimeUnbrand : ejson_runtime_op\n    | EJsonRuntimeCast : ejson_runtime_op\n    (* Collection *)\n    | EJsonRuntimeDistinct : ejson_runtime_op\n    | EJsonRuntimeSingleton : ejson_runtime_op\n    | EJsonRuntimeFlatten : ejson_runtime_op\n    | EJsonRuntimeUnion : ejson_runtime_op\n    | EJsonRuntimeMinus : ejson_runtime_op\n    | EJsonRuntimeMin : ejson_runtime_op\n    | EJsonRuntimeMax : ejson_runtime_op\n    | EJsonRuntimeNth : ejson_runtime_op\n    | EJsonRuntimeCount : ejson_runtime_op\n    | EJsonRuntimeContains : ejson_runtime_op\n    | EJsonRuntimeSort : ejson_runtime_op\n    | EJsonRuntimeGroupBy : ejson_runtime_op\n    (* String *)\n    | EJsonRuntimeLength : ejson_runtime_op\n    | EJsonRuntimeSubstring : ejson_runtime_op\n    | EJsonRuntimeSubstringEnd : ejson_runtime_op\n    | EJsonRuntimeStringJoin : ejson_runtime_op\n    | EJsonRuntimeLike : ejson_runtime_op\n    (* Integer *)\n    | EJsonRuntimeNatLt : ejson_runtime_op\n    | EJsonRuntimeNatLe : ejson_runtime_op\n    | EJsonRuntimeNatPlus : ejson_runtime_op\n    | EJsonRuntimeNatMinus : ejson_runtime_op\n    | EJsonRuntimeNatMult : ejson_runtime_op\n    | EJsonRuntimeNatDiv : ejson_runtime_op\n    | EJsonRuntimeNatRem : ejson_runtime_op\n    | EJsonRuntimeNatAbs : ejson_runtime_op\n    | EJsonRuntimeNatLog2 : ejson_runtime_op\n    | EJsonRuntimeNatSqrt : ejson_runtime_op\n    | EJsonRuntimeNatMinPair : ejson_runtime_op\n    | EJsonRuntimeNatMaxPair : ejson_runtime_op\n    | EJsonRuntimeNatSum : ejson_runtime_op\n    | EJsonRuntimeNatMin : ejson_runtime_op\n    | EJsonRuntimeNatMax : ejson_runtime_op\n    | EJsonRuntimeNatArithMean : ejson_runtime_op\n    | EJsonRuntimeFloatOfNat : ejson_runtime_op\n    (* Float *)\n    | EJsonRuntimeFloatSum : ejson_runtime_op\n    | EJsonRuntimeFloatArithMean : ejson_runtime_op\n    | EJsonRuntimeFloatMin : ejson_runtime_op\n    | EJsonRuntimeFloatMax : ejson_runtime_op\n    | EJsonRuntimeNatOfFloat : ejson_runtime_op\n    (* Foreign *)\n    | EJsonRuntimeForeign (fop:foreign_ejson_runtime_op) : ejson_runtime_op\n    .\n\n  End Syntax.\n\n  Context {fejruntime:foreign_ejson_runtime foreign_ejson_runtime_op}.\n\n  Section Util.\n    Local Open Scope string.\n\n    Definition string_of_ejson_runtime_op (op: ejson_runtime_op) :=\n      match op with\n      (* Generic *)\n      | EJsonRuntimeEqual => \"equal\"\n      | EJsonRuntimeCompare => \"compare\"\n      | EJsonRuntimeToString => \"toString\"\n      | EJsonRuntimeToText => \"toText\"\n      (* Record *)\n      | EJsonRuntimeRecConcat => \"recConcat\"\n      | EJsonRuntimeRecMerge => \"recMerge\"\n      | EJsonRuntimeRecRemove=> \"recRemove\"\n      | EJsonRuntimeRecProject=> \"recProject\"\n      | EJsonRuntimeRecDot => \"recDot\"\n      (* Array *)\n      | EJsonRuntimeArray => \"array\"\n      | EJsonRuntimeArrayLength => \"arrayLength\"\n      | EJsonRuntimeArrayPush => \"arrayPush\"\n      | EJsonRuntimeArrayAccess => \"arrayAccess\"\n      (* Sum *)\n      | EJsonRuntimeEither => \"either\"\n      | EJsonRuntimeToLeft=> \"getLeft\"\n      | EJsonRuntimeToRight=> \"getRight\"\n      (* Brand *)\n      | EJsonRuntimeUnbrand => \"unbrand\"\n      | EJsonRuntimeCast => \"cast\"\n      (* Collection *)\n      | EJsonRuntimeDistinct => \"distinct\"\n      | EJsonRuntimeSingleton => \"singleton\"\n      | EJsonRuntimeFlatten => \"flatten\"\n      | EJsonRuntimeUnion => \"union\"\n      | EJsonRuntimeMinus => \"minus\"\n      | EJsonRuntimeMin => \"min\"\n      | EJsonRuntimeMax => \"max\"\n      | EJsonRuntimeNth => \"nth\"\n      | EJsonRuntimeCount => \"count\"\n      | EJsonRuntimeContains => \"contains\"\n      | EJsonRuntimeSort => \"sort\"\n      | EJsonRuntimeGroupBy => \"groupBy\"\n      (* String *)\n      | EJsonRuntimeLength => \"length\"\n      | EJsonRuntimeSubstring => \"substring\"\n      | EJsonRuntimeSubstringEnd => \"substringEnd\"\n      | EJsonRuntimeStringJoin => \"stringJoin\"\n      | EJsonRuntimeLike => \"like\"\n      (* Integer *)\n      | EJsonRuntimeNatLt => \"natLt\"\n      | EJsonRuntimeNatLe => \"natLe\"\n      | EJsonRuntimeNatPlus => \"natPlus\"\n      | EJsonRuntimeNatMinus => \"natMinus\"\n      | EJsonRuntimeNatMult => \"natMult\"\n      | EJsonRuntimeNatDiv => \"natDiv\"\n      | EJsonRuntimeNatRem => \"natRem\"\n      | EJsonRuntimeNatAbs => \"natAbs\"\n      | EJsonRuntimeNatLog2 => \"natLog2\"\n      | EJsonRuntimeNatSqrt => \"natSqrt\"\n      | EJsonRuntimeNatMinPair => \"natMinPair\"\n      | EJsonRuntimeNatMaxPair => \"natMaxPair\"\n      | EJsonRuntimeNatMin => \"natMin\"\n      | EJsonRuntimeNatMax => \"natMax\"\n      | EJsonRuntimeNatSum => \"natSum\"\n      | EJsonRuntimeNatArithMean => \"natArithMean\"\n      | EJsonRuntimeFloatOfNat => \"floatOfNat\"\n      (* Float *)\n      | EJsonRuntimeFloatSum => \"floatSum\"\n      | EJsonRuntimeFloatArithMean => \"floatArithMean\"\n      | EJsonRuntimeFloatMin => \"floatMin\"\n      | EJsonRuntimeFloatMax => \"floatMax\"\n      | EJsonRuntimeNatOfFloat => \"natOfFloat\"\n      (* Foreign *)\n      | EJsonRuntimeForeign fop => toString fop\n      end.\n\n    Definition ejson_runtime_op_of_string (opname:string) : option ejson_runtime_op :=\n      match opname with\n      (* Generic *)\n      | \"equal\" => Some EJsonRuntimeEqual\n      | \"compare\" => Some EJsonRuntimeCompare\n      | \"toString\" => Some EJsonRuntimeToString\n      | \"toText\" => Some EJsonRuntimeToText\n      (* Record *)\n      | \"recConcat\" => Some EJsonRuntimeRecConcat\n      | \"recMerge\" => Some EJsonRuntimeRecMerge\n      | \"recRemove\" => Some EJsonRuntimeRecRemove\n      | \"recProject\" => Some EJsonRuntimeRecProject\n      | \"recDot\" => Some EJsonRuntimeRecDot\n      (* Array *)\n      | \"array\" => Some EJsonRuntimeArray\n      | \"arrayLength\" => Some EJsonRuntimeArrayLength\n      | \"arrayPush\" => Some EJsonRuntimeArrayPush\n      | \"arrayAccess\" => Some EJsonRuntimeArrayAccess\n      (* Sum *)\n      | \"either\" => Some EJsonRuntimeEither\n      | \"toLeft\" => Some EJsonRuntimeToLeft\n      | \"toRight\" => Some EJsonRuntimeToRight\n      (* Brand *)\n      | \"unbrand\" => Some EJsonRuntimeUnbrand\n      | \"cast\" => Some EJsonRuntimeCast\n      (* Collection *)\n      | \"distinct\" => Some EJsonRuntimeDistinct\n      | \"singleton\" => Some EJsonRuntimeSingleton\n      | \"flatten\" => Some EJsonRuntimeFlatten\n      | \"union\" => Some EJsonRuntimeUnion\n      | \"minus\" => Some EJsonRuntimeMinus\n      | \"min\" => Some EJsonRuntimeMin\n      | \"max\" => Some EJsonRuntimeMax\n      | \"nth\" => Some EJsonRuntimeNth\n      | \"count\" => Some EJsonRuntimeCount\n      | \"contains\" => Some EJsonRuntimeContains\n      | \"sort\" => Some EJsonRuntimeSort\n      | \"groupBy\" => Some EJsonRuntimeGroupBy\n      (* String *)\n      | \"length\" => Some EJsonRuntimeLength\n      | \"substring\" => Some EJsonRuntimeSubstring\n      | \"substringEnd\" => Some EJsonRuntimeSubstringEnd\n      | \"stringJoin\" => Some EJsonRuntimeStringJoin\n      | \"like\" => Some EJsonRuntimeLike\n      (* Integer *)\n      | \"natLt\" => Some EJsonRuntimeNatLt\n      | \"natLe\" => Some EJsonRuntimeNatLe\n      | \"natPlus\" => Some EJsonRuntimeNatPlus\n      | \"natMinus\" => Some EJsonRuntimeNatMinus\n      | \"natMult\" => Some EJsonRuntimeNatMult\n      | \"natDiv\" => Some EJsonRuntimeNatDiv\n      | \"natRem\" => Some EJsonRuntimeNatRem\n      | \"natAbs\" => Some EJsonRuntimeNatAbs\n      | \"natLog2\" => Some EJsonRuntimeNatLog2\n      | \"natSqrt\" => Some EJsonRuntimeNatSqrt\n      | \"natMinPair\" => Some EJsonRuntimeNatMinPair\n      | \"natMaxPair\" => Some EJsonRuntimeNatMaxPair\n      | \"natMin\" => Some EJsonRuntimeNatMin\n      | \"natMax\" => Some EJsonRuntimeNatMax\n      | \"natSum\" => Some EJsonRuntimeNatSum\n      | \"natArithMean\" => Some EJsonRuntimeNatArithMean\n      | \"floatOfNat\" => Some EJsonRuntimeFloatOfNat\n      (* Float *)\n      | \"floatSum\" => Some EJsonRuntimeFloatSum\n      | \"floatArithMean\" => Some EJsonRuntimeFloatArithMean\n      | \"floatMin\" => Some EJsonRuntimeFloatMin\n      | \"floatMax\" => Some EJsonRuntimeFloatMax\n      | \"natOfFloat\" => Some EJsonRuntimeNatOfFloat\n      (* Foreign *)\n      | _ => lift EJsonRuntimeForeign (foreign_ejson_runtime_fromstring opname)\n      end.\n\n  Fixpoint defaultEJsonToString (j:@ejson foreign_ejson_model) : string\n    := match j with\n       | ejnull => \"unit\"%string\n       | ejbigint n => toString n\n       | ejnumber n => toString n\n       | ejbool b => toString b\n       | ejstring s => stringToString s\n       | ejarray l => string_bracket \n                        \"[\"%string\n                        (String.concat \", \"%string\n                                       (map defaultEJsonToString l))\n                        \"]\"%string\n       | ejobject ((s1,j')::nil) =>\n         if (string_dec s1 \"$left\") then\n           string_bracket\n             \"Left(\"%string\n             (defaultEJsonToString j')\n             \")\"%string\n         else if (string_dec s1 \"$right\") then\n                string_bracket\n                  \"Right(\"%string\n                  (defaultEJsonToString j')\n                  \")\"%string\n              else\n                string_bracket\n                  \"{\"%string\n                  (String.concat \", \"%string \n                                 (map (fun xy => let '(x,y):=xy in \n                                                 (append (stringToString (key_decode x)) (append \"->\"%string\n                                                                                                 (defaultEJsonToString y)))\n                                      ) ((s1,j')::nil)))\n                  \"}\"%string\n      | ejobject ((s1,ejarray j1)::(s2,j2)::nil) =>\n        if (string_dec s1 \"$class\") then\n          if (string_dec s2 \"$data\") then\n            match (ejson_brands j1) with\n            | Some br =>\n              (string_bracket\n                 \"<\"\n                 (append (@toString _ ToString_brands br) (append \":\" (defaultEJsonToString j2)))\n                 \">\")\n            | None =>\n                string_bracket\n                  \"{\"%string\n                  (String.concat \", \"%string\n                                 ((append (stringToString (key_decode s1))\n                                          (append \"->\"%string (string_bracket \n                                                                 \"[\"%string (String.concat \", \"%string (map defaultEJsonToString j1)) \"]\"%string)))\n                                    :: (append (stringToString (key_decode s2)) (append \"->\"%string (defaultEJsonToString j2)))\n                                    :: nil))\n                  \"}\"%string\n            end\n          else\n            string_bracket\n              \"{\"%string\n              (String.concat \", \"%string\n                             ((append (stringToString (key_decode s1))\n                                      (append \"->\"%string (string_bracket \"[\"%string (String.concat \", \"%string (map defaultEJsonToString j1)) \"]\"%string)))\n                                :: (append (stringToString (key_decode s2)) (append \"->\"%string (defaultEJsonToString j2)))\n                                :: nil))\n              \"}\"%string\n        else\n          string_bracket\n            \"{\"%string\n            (String.concat \", \"%string\n                           ((append (stringToString (key_decode s1))\n                                    (append \"->\"%string (string_bracket \"[\"%string (String.concat \", \"%string (map defaultEJsonToString j1)) \"]\"%string)))\n                              :: (append (stringToString (key_decode s2)) (append \"->\"%string (defaultEJsonToString j2)))\n                              :: nil))\n            \"}\"%string\n      | ejobject r =>\n        string_bracket\n          \"{\"%string\n          (String.concat \", \"%string\n                         (map (fun xy => let '(x,y):=xy in\n                                         (append (stringToString (key_decode x)) (append \"->\"%string (defaultEJsonToString y)))\n                              ) r))\n          \"}\"%string\n       | ejforeign fd => toString fd\n       end.\n    \n  End Util.\n\n  Section Evaluation.\n    (* XXX We should try and compile the hierarchy in. Currenty it is still used in cast for sub-branding check *)\n    Context (h:brand_relation_t).\n    Definition ejson_runtime_eval (rt:ejson_runtime_op) (dl:list ejson) : option ejson :=\n      match rt with\n      (* Generic *)\n      | EJsonRuntimeEqual =>\n        apply_binary (fun d1 d2 => if ejson_eq_dec d1 d2 then Some (ejbool true) else Some (ejbool false)) dl\n      | EJsonRuntimeCompare =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejnumber n1, ejnumber n2 =>\n               if float_lt n1 n2\n               then\n                 Some (ejnumber float_one)\n               else if float_gt n1 n2\n                    then\n                      Some (ejnumber float_neg_one)\n                    else\n                      Some (ejnumber float_zero)\n             | ejbigint n1, ejbigint n2 =>\n               if Z_lt_dec n1 n2\n               then\n                 Some (ejnumber float_one)\n               else if Z_gt_dec n1 n2\n                    then\n                      Some (ejnumber float_neg_one)\n                    else\n                      Some (ejnumber float_zero)\n             | _, _ => None\n             end) dl\n      | EJsonRuntimeToString =>\n        apply_unary\n          (fun d =>\n             Some (ejstring (foreign_ejson_runtime_tostring d))\n          ) dl\n      | EJsonRuntimeToText =>\n        apply_unary\n          (fun d =>\n             Some (ejstring (foreign_ejson_runtime_totext d))\n          ) dl\n      (* Record *)\n      | EJsonRuntimeRecConcat =>\n        apply_binary\n          (fun d1 d2 =>\n             match ejson_is_record d1, ejson_is_record d2 with\n             | Some r1, Some r2 => Some (ejobject (rec_sort (r1++r2)))\n             | _, _ => None\n             end) dl\n      | EJsonRuntimeRecMerge =>\n        apply_binary\n          (fun d1 d2 =>\n             match ejson_is_record d1, ejson_is_record d2 with\n             | Some r1, Some r2 =>\n               match @merge_bindings ejson _ ejson_eq_dec r1 r2 with\n               | Some x => Some (ejarray ((ejobject x) :: nil))\n               | None => Some (ejarray nil)\n               end\n             | _, _ => None\n             end) dl\n      | EJsonRuntimeRecRemove =>\n        apply_binary\n          (fun d1 d2 =>\n             match ejson_is_record d1 with\n             | Some r =>\n               match d2 with\n               | ejstring s =>\n                 Some (ejobject (rremove r s))\n               | _ => None\n               end\n             | _ => None\n             end) dl\n      | EJsonRuntimeRecProject =>\n        apply_binary\n          (fun d1 d2 =>\n             match ejson_is_record d1 with\n             | Some r =>\n               match d2 with\n               | ejarray sl =>\n                 lift ejobject\n                      (lift (rproject r)\n                            (of_string_list sl))\n               | _ => None\n               end\n             | _ => None\n             end) dl\n      | EJsonRuntimeRecDot =>\n        apply_binary\n          (fun d1 d2 =>\n             match ejson_is_record d1 with\n             | Some r =>\n               match d2 with\n               | ejstring s =>\n                 edot r s\n               | _ => None\n               end\n             | _ => None\n             end) dl\n      (* Array *)\n      | EJsonRuntimeArray =>\n        Some (ejarray dl) (* XXX n-ary *)\n      | EJsonRuntimeArrayLength =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray ja => Some (ejbigint (Z_of_nat (List.length ja)))\n             | _ => None\n             end) dl\n      | EJsonRuntimeArrayPush =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1 with\n             | ejarray ja => Some (ejarray (ja ++ (d2::nil)))\n             | _ => None\n             end) dl\n      | EJsonRuntimeArrayAccess =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejarray ja, ejbigint n =>\n               let natish := ZToSignedNat n in\n               if (fst natish) then\n                 match List.nth_error ja (snd natish) with\n                 | None => None\n                 | Some d => Some d\n                 end\n               else None\n             | _, _ => None\n             end) dl\n      (* Sum *)\n      | EJsonRuntimeEither =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejobject ((\"$left\", _)::nil) => Some (ejbool true)\n             | ejobject ((\"$right\",_)::nil) => Some (ejbool false)\n             | _ => None\n             end) dl\n      | EJsonRuntimeToLeft =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejobject ((\"$left\", d)::nil) => Some d\n             | _ => None\n             end) dl\n      | EJsonRuntimeToRight =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejobject ((\"$right\", d)::nil) => Some d\n             | _ => None\n             end) dl\n      (* Brand *)\n      | EJsonRuntimeUnbrand =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejobject ((s,ejarray jl)::(s',j')::nil) =>\n               if (string_dec s \"$class\") then\n                 if (string_dec s' \"$data\") then\n                   match ejson_brands jl with\n                   | Some _ => Some j'\n                   | None => None\n                   end\n                 else None\n               else None\n             | _ => None\n             end) dl\n      | EJsonRuntimeCast =>\n        apply_binary\n          (fun d1 d2 : ejson =>\n             match d1 with\n             | ejarray jl1 =>\n               match ejson_brands jl1 with\n               | Some b1 =>\n                 match d2 with\n                 | ejobject ((s,ejarray jl2)::(s',_)::nil) =>\n                   if (string_dec s \"$class\") then\n                     if (string_dec s' \"$data\") then\n                       match ejson_brands jl2 with\n                       | Some b2 =>\n                         if (sub_brands_dec h b2 b1)\n                         then\n                           Some (ejobject ((\"$left\"%string,d2)::nil))\n                         else\n                           Some (ejobject ((\"$right\"%string,ejnull)::nil))\n                       | None => None\n                       end\n                     else None\n                   else None\n                 | _ => None\n                 end\n               | None => None\n               end\n             | _ => None\n             end) dl\n\n      (* Collection *)\n      | EJsonRuntimeDistinct =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray l =>\n               Some (ejarray (@bdistinct ejson ejson_eq_dec l))\n             | _ => None\n             end)\n          dl\n      | EJsonRuntimeSingleton =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray (d::nil) => Some (ejobject ((\"$left\",d)::nil))\n             | ejarray _ => Some (ejobject ((\"$right\",ejnull)::nil))\n             | _ => None\n             end) dl\n      | EJsonRuntimeFlatten =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray l =>\n               lift ejarray (jflatten l)\n             | _ => None\n             end) dl\n      | EJsonRuntimeUnion =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejarray l1, ejarray l2 =>\n               Some (ejarray (bunion l1 l2))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeMinus =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejarray l1, ejarray l2 =>\n               Some (ejarray (bminus l2 l1))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeMin =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejarray l1, ejarray l2 =>\n               Some (ejarray (bmin l1 l2))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeMax =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejarray l1, ejarray l2 =>\n               Some (ejarray (bmax l1 l2))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeNth =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | (ejarray c), (ejbigint n) =>\n               let natish := ZToSignedNat n in\n               if (fst natish) then\n                 match List.nth_error c (snd natish) with\n                 | Some d => Some (ejobject ((\"$left\",d)::nil))\n                 | None => Some (ejobject ((\"$right\",ejnull)::nil))\n                 end\n               else Some (ejobject ((\"$right\",ejnull)::nil))\n             | _, _ => None\n             end) dl\n      | EJsonRuntimeCount =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray l => Some (ejbigint (Z_of_nat (bcount l)))\n             | _ => None\n             end) dl\n      | EJsonRuntimeContains =>\n        apply_binary\n          (fun d1 d2 =>\n             match d2 with\n             | ejarray l =>\n               if in_dec ejson_eq_dec d1 l\n               then Some (ejbool true) else Some (ejbool false)\n             | _ => None\n             end) dl\n      | EJsonRuntimeSort =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1 with\n             | ejarray l1 =>\n               ejson_sort l1 d2\n             | _ => None\n             end) dl\n      | EJsonRuntimeGroupBy =>\n        apply_ternary\n          (fun d1 d2 d3 =>\n             match d3 with\n             | ejarray l =>\n               match d1 with\n               | ejstring g =>\n                 match d2 with\n                 | ejarray sl =>\n                   match of_string_list sl with\n                   | Some kl =>\n                     lift ejarray (ejson_group_by_nested_eval_table g kl l)\n                   | None => None\n                   end\n                 | _ => None\n                 end\n               | _ => None\n               end\n             | _ => None\n             end) dl\n      (* String *)\n      | EJsonRuntimeLength =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejstring s => Some (ejbigint (Z_of_nat (String.length s)))\n             | _ => None\n             end) dl\n      | EJsonRuntimeSubstring =>\n        apply_ternary\n          (fun d1 d2 d3 =>\n             match d1, d2, d3 with\n             | ejstring s, ejbigint start, ejbigint len =>              \n               let real_start :=\n                   (match start with\n                    | 0%Z => 0\n                    | Z.pos p => Pos.to_nat p\n                    | Z.neg n => (String.length s) - (Pos.to_nat n)\n                    end) in\n               let real_len :=\n                   match len with\n                   | 0%Z => 0\n                   | Z.pos p => Pos.to_nat p\n                   | Z.neg n => 0\n                   end\n               in\n               Some (ejstring (substring real_start real_len s))\n             | _, _, _ => None\n             end) dl\n      | EJsonRuntimeSubstringEnd =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejstring s, ejbigint start =>              \n               let real_start :=\n                   (match start with\n                    | 0%Z => 0\n                    | Z.pos p => Pos.to_nat p\n                    | Z.neg n => (String.length s) - (Pos.to_nat n)\n                    end) in\n               let real_len := (String.length s) - real_start in\n               Some (ejstring (substring real_start real_len s))\n             | _, _ => None\n             end) dl\n      | EJsonRuntimeStringJoin =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejstring sep, ejarray l =>\n               match ejson_strings l with\n               | Some sl => Some (ejstring (String.concat sep sl))\n               | None => None\n               end\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeLike =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejstring sreg, ejstring starget =>\n               Some (ejbool (string_like starget sreg None))\n             | _, _ => None\n             end\n          ) dl\n      (* Integer *)\n      | EJsonRuntimeNatLt =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejbigint n1, ejbigint n2 =>\n               Some (ejbool (if Z_lt_dec n1 n2 then true else false))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeNatLe =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejbigint n1, ejbigint n2 =>\n               Some (ejbool (if Z_le_dec n1 n2 then true else false))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeNatPlus =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejbigint n1, ejbigint n2 =>\n               Some (ejbigint (Z.add n1 n2))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeNatMinus =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejbigint n1, ejbigint n2 =>\n               Some (ejbigint (Z.sub n1 n2))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeNatMult =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejbigint n1, ejbigint n2 =>\n               Some (ejbigint (Z.mul n1 n2))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeNatDiv =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejbigint n1, ejbigint n2 =>\n               Some (ejbigint (Z.quot n1 n2))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeNatRem =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejbigint n1, ejbigint n2 =>\n               Some (ejbigint (Z.rem n1 n2))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeNatAbs =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejbigint z => Some (ejbigint (Z.abs z))\n             | _ => None\n             end) dl\n      | EJsonRuntimeNatLog2 =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejbigint z => Some (ejbigint (Z.log2 z))\n             | _ => None\n             end) dl\n      | EJsonRuntimeNatSqrt =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejbigint z => Some (ejbigint (Z.sqrt z))\n             | _ => None\n             end) dl\n      | EJsonRuntimeNatMinPair =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejbigint n1, ejbigint n2 =>\n               Some (ejbigint (Z.min n1 n2))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeNatMaxPair =>\n        apply_binary\n          (fun d1 d2 =>\n             match d1, d2 with\n             | ejbigint n1, ejbigint n2 =>\n               Some (ejbigint (Z.max n1 n2))\n             | _, _ => None\n             end\n          ) dl\n      | EJsonRuntimeNatSum =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray l =>\n               match ejson_bigints l with\n               | Some zl =>\n                 Some (ejbigint (fold_right Zplus 0%Z zl))\n               | None => None\n               end\n             | _ => None\n             end) dl\n      | EJsonRuntimeNatMin =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray l =>\n               match ejson_bigints l with\n               | Some zl =>\n                 Some (ejbigint (bnummin zl))\n               | None => None\n               end\n             | _ => None\n             end) dl\n      | EJsonRuntimeNatMax =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray l =>\n               match ejson_bigints l with\n               | Some zl =>\n                 Some (ejbigint (bnummax zl))\n               | None => None\n               end\n             | _ => None\n             end) dl\n      | EJsonRuntimeNatArithMean =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray l =>\n               let length := List.length l in\n               match ejson_bigints l with\n               | Some zl =>\n                 Some (ejbigint (Z.quot (fold_right Zplus 0%Z zl) (Z_of_nat length)))\n               | None => None\n               end\n             | _ => None\n             end) dl\n      | EJsonRuntimeFloatOfNat =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejbigint n => Some (ejnumber (float_of_int n))\n             | _ => None\n             end) dl\n      (* Float *)\n      | EJsonRuntimeFloatSum =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray l =>\n               match ejson_numbers l with\n               | Some nl =>\n                 Some (ejnumber (float_list_sum nl))\n               | None => None\n               end\n             | _ => None\n             end) dl\n      | EJsonRuntimeFloatArithMean =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray l =>\n               match ejson_numbers l with\n               | Some nl =>\n                 Some (ejnumber (float_list_arithmean nl))\n               | None => None\n               end\n             | _ => None\n             end) dl\n      | EJsonRuntimeFloatMin =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray l =>\n               match ejson_numbers l with\n               | Some nl =>\n                 Some (ejnumber (float_list_min nl))\n               | None => None\n               end\n             | _ => None\n             end) dl\n      | EJsonRuntimeFloatMax =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejarray l =>\n               match ejson_numbers l with\n               | Some nl =>\n                 Some (ejnumber (float_list_max nl))\n               | None => None\n               end\n             | _ => None\n             end) dl\n      | EJsonRuntimeNatOfFloat =>\n        apply_unary\n          (fun d =>\n             match d with\n             | ejnumber f => Some (ejbigint (float_truncate f))\n             | _ => None\n             end) dl\n      (* Foreign *)\n      | EJsonRuntimeForeign fop =>\n        foreign_ejson_runtime_op_interp fop dl\n      end.\n  End Evaluation.\nEnd EJsonRuntimeOperators.\n\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/EJson/Operators/EJsonRuntimeOperators.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.24015142691958244}}
{"text": "From Coq Require Import List Lia String ZArith Program.Equality.\nFrom WiSE Require Import streams lang.imp symbolic.symex implem.bugfinder.\nImport ListNotations.\nImport LTL.\n\n(** * Correctness proof of the bugfinder *)\n\n(** ** Soundness and Completness of [expand] w.r.t [sym_step] *)\n\nLemma map_in:\n  forall A B (f : A -> B) (l : list A) b,\n    In b (List.map f l) -> exists a, In a l /\\ b = f a.\nProof.\n  intros. induction l; try easy.\n  destruct H as [<- | H].\n  - repeat econstructor.\n  - specialize (IHl H) as (a' & Ha' & ->).\n    exists a'. split; auto. now right.\nQed.\n\n(** [expand] is a sound implementation of [sym_step] *)\nTheorem expand_sound:\n  forall path env prog t,\n    In t (expand path env prog) -> sym_step ((path, env), prog) t.\nProof.\n  intros path env prog [[path' env'] prog'] Hin.\n  induction prog in path', env', prog', Hin |-*; subst; try easy.\n  - destruct Hin as [[=<-<-<-] | [ [=<-<-<-] | [] ]]; constructor.\n  - destruct prog1; try easy.\n    + destruct Hin as [[=<-<-<-] | []]. now econstructor.\n    + pose proof (map_in _ _ _ _ _ Hin) as ([[path2 env2] prog3] & [H1 [=->->->]]).\n      specialize (IHprog1 _ _ _ H1).\n      now constructor.\n    + pose proof (map_in _ _ _ _ _ Hin) as ([[path2 env2] prog3] & [H1 [=->->->]]).\n      specialize (IHprog1 _ _ _ H1).\n      now constructor.\n    + pose proof (map_in _ _ _ _ _ Hin) as ([[path2 env2] prog3] & [H1 [=->->->]]).\n      specialize (IHprog1 _ _ _ H1).\n      now constructor.\n    + pose proof (map_in _ _ _ _ _ Hin) as ([[path2 env2] prog3] & [H1 [=->->->]]).\n      specialize (IHprog1 _ _ _ H1).\n      now constructor.\n  - destruct Hin as [[=<-<-<-] | []]. now constructor.\n  - destruct Hin as [[=<-<-<-] | [[=<-<-<-]| []]]; now constructor.\nQed.\n\n(** [expand] is a complete implementation of [sym_step] *)\nTheorem expand_complete:\n  forall path env prog t,\n    sym_step ((path, env), prog) t ->\n    In t (expand path env prog).\nProof.\n  intros * Ht.\n  dependent induction Ht; intros; simpl.\n  - now econstructor.\n  - change (π2, s2, Seq c2 c3) with (then_do c3 (π2, s2, c2)).\n    destruct c1; try easy.\n    all: eapply in_map, IHHt; eauto.\n  - now left.\n  - now left.\n  - now (right; left).\n  - now left.\n  - now (right; left).\nQed.\n\n(** [expand] spawns 0, 1 or 2 tasks *)\nTheorem expand_inv:\n  forall path env prog,\n    (expand path env prog = []) \\/\n    (exists s, expand path env prog = [s]) \\/\n    (exists s1 s2, expand path env prog = [s1; s2]).\nProof.\n  intros. induction prog.\n  - now left.\n  - now right; right; repeat econstructor.\n  - destruct IHprog1 as [IH | [(s & Hs) | (s1 & s2 & Hs)]].\n    + destruct prog1; simpl in *; try easy.\n      now right; left; repeat econstructor. rewrite IH.\n      now left.\n      now left.\n    + destruct prog1; simpl in *; try easy.\n      right. repeat econstructor. now rewrite Hs.\n      right. repeat econstructor.\n    + destruct prog1; simpl in *; try easy.\n      now right; right; repeat econstructor.\n      now right; right; repeat econstructor; rewrite Hs.\n      right; right; repeat econstructor; rewrite Hs.\n  - now right; left; repeat econstructor.\n  - now left.\n  - now right; right; repeat econstructor.\nQed.\n\n(** ** Eager model of [run] *)\n(** The [run] function that executes the main loop of the bugfinder\n    generates a lazy stream. Lazy streams are defined co-inductively\n    which make them somwhat hard to reason about. To ease the proofs, we\n    provide an eager implementation [run_n] of [run] that simulates the behavior of\n    [run] for [n] steps of computation. We then relate the 2 functions by a theorem [run_run_n].\n*)\n\n(** [run_eq] can be used to destruct applications of the cofixpoint [run] *)\nTheorem run_eq:\n  forall l path env prog,\n    run ((path, env, prog)::l) = scons (Some (path, env, prog)) (run (l ++ expand path env prog)).\nProof.\n  intros. now rewrite <- force_id at 1.\nQed.\n\n(** the [run []] is a fixpoint for [shift] i.e.\n    once the task list is empty, [run] loops indefinitely\n    in a state where the task list remains empty\n*)\nLemma run_nil:\n  forall n, shift n (run []) = run [].\nProof.\n  now induction n.\nQed.\n\n(** Relation between [run] and its eager model [run_n].\n    [run_n n l] computes the task list after [n] iterations [run l]\n*)\nLemma run_run_n:\n  forall n l, shift n (run l) = run (run_n n l).\nProof.\n  intros. induction n in l |-*; try easy.\n  destruct l as [| [[path env] prog] l] .\n  - apply run_nil.\n  - rewrite run_eq. simpl. now rewrite IHn.\nQed.\n\nLemma run_n_nil:\n  forall n, run_n n [] = [].\nProof.\n  now induction n.\nQed.\n\n(** After [List.length l1] iterations, the task list of [run (l1 ++ l2)]\n    starts with [l2]\n*)\nTheorem run_n_length:\n  forall l1 l2,\n    exists l3,\n      run_n (List.length l1) (l1 ++ l2) = l2 ++ l3.\nProof.\n  intros. induction l1 as [|[[path env] prog] l1 IH] in l2 |-*.\n  - simpl. exists []. now rewrite app_nil_r.\n  - simpl. rewrite <- List.app_assoc.\n    specialize (IH (l2 ++ expand path env prog)) as [l3 Hl3].\n    rewrite Hl3. rewrite <- List.app_assoc. now eexists.\nQed.\n\n(** After [1 + List.length l1] iterations, the task list of [run (t::l1 ++ l2)]\n    starts with [l2] followed with the task spawed by executing [t]\n*)\nTheorem run_n_S_length:\n  forall l1 l2 path env prog,\n    exists l3,\n      run_n (S (List.length l1)) ((path, env, prog)::l1 ++ l2) = l2 ++ (expand path env prog) ++ l3.\nProof.\n  intros. induction l1 as [|[[path1 env1] prog1] l1 IH] in l2, path, env, prog |-*.\n  - simpl. exists []. now rewrite app_nil_r.\n  - simpl. do 2 rewrite <- List.app_assoc. simpl in IH.\n    specialize (IH (l2 ++ expand path env prog) path1 env1 prog1).\n    simpl in IH. edestruct IH as [l3 Hl3]. eexists.\n    repeat rewrite <- List.app_assoc in Hl3. apply Hl3.\nQed.\n\n(** ** LTL Specification Predicates\n\n    In the remainder of this file, we will use a shallow embedding of the [LTL]\n    logic to write specifications over lazy streams.\n    We start by defining some usefull [LTL] predicates.\n*)\n\n(** The current state in the stream is [sym_steps] reachable from a state in [l] *)\nDefinition reachable_from (tasks : list sym_state) : LTL.t :=\n  now (fun s =>\n    match s with\n    | None => True\n    | Some s => exists s0, In s0 tasks /\\ sym_steps s0 s\n    end\n  ).\n\n(** The current state in the stream is [s] *)\nDefinition here (s : sym_state) : LTL.t :=\n  now (fun st =>\n    match st with\n    | Some s' => s' = s\n    | None => False\n    end\n  ).\nNotation \"! x\" := (here x).\n\nDefinition bug_found s : LTL.t :=\n  now (fun (st : status) => \n    match st with\n    | BugFound s' => s' = s\n    | _ => False\n    end\n  ).\nNotation \"!! x\" := (bug_found x).\n\nDefinition potential_bug p : LTL.t :=\n  now (fun (st : status) =>\n    match st with\n    | BugFound s' => potential_bug (Bcst true, id, p) s'\n    | _ => True\n    end\n  ).\n\nDefinition none : LTL.t :=\n  now (fun (st : option sym_state) =>\n    match st with\n    | None => True\n    | _ => False\n    end\n  ).\n\nDefinition done : LTL.t :=\n  now (fun (st : status) =>\n    match st with\n    | Finished => True\n    | _ => False\n    end\n  ).\n\n(** ** Soundess of [run] *)\n\n(** [run] is sound with respect to [sym_exec]:\n    all states generate by the stream [run l],\n    are reachable from [l]\n*)\nTheorem run_sound:\n  forall l,\n    run l ⊨ □ reachable_from l.\nProof.\n  intros l n. rewrite run_run_n.\n  induction n in l |-*.\n  - simpl in *. destruct l as [| [[path env] prog]]; try easy.\n    repeat econstructor.\n  - destruct l as [| [[path env] prog] l]; try easy.\n    specialize (IHn (l ++ expand path env prog)).\n    simpl. destruct run_n as [| [[path1 env1] prog1]] eqn:Heq; try easy.\n    destruct IHn as [[[path2 env2] prog2] [[H | H]%in_app_iff Hsteps]].\n    + eexists. split; eauto. now right.\n    + pose proof (expand_sound _ _ _ _ H).\n      eexists. split. now left.\n      econstructor; eauto.\nQed.\n\n(** ** Completeness of [run] *)\n\n(** [run] is complete for [sym_step]:\n    if [s] is the next value generated by [run l], then\n    all the direct sucessors of [s] are eventually generated\n*)\nTheorem run_step_complete:\n  forall l s s',\n    sym_step s s' ->\n    run l ⊨ (!s → ◊!s').\nProof.\n  intros * Hstep H.\n  destruct l as [| [[path env] prog]]; try easy.\n  cbn in H. subst.\n  apply expand_complete in Hstep.\n  destruct (expand_inv path env prog) as [Htask | [[s Htask] | (s1 & s2 & Htask)]].\n  - now rewrite Htask in Hstep.\n  - rewrite run_eq, Htask in *. inversion Hstep; subst; try easy.\n    exists (S (List.length l)). simpl.\n    rewrite run_run_n.\n    pose proof (run_n_length l [s']) as [l3 Hl3].\n    replace (run_n (Datatypes.length l) (l ++ [s'])) with ([s'] ++ l3) at 1.\n    now destruct s' as [[a b] c].\n  - rewrite run_eq, Htask in *. destruct Hstep as [-> | [ -> | []]].\n    + exists (S (List.length l)). simpl.\n      rewrite run_run_n.\n      pose proof (run_n_length l [s'; s2]) as [l3 Hl3].\n      replace (run_n (Datatypes.length l) (l ++ [s'; s2])) with ([s'; s2] ++ l3) at 1.\n      simpl. now destruct s' as [[a b] c].\n    + exists (S (S (List.length l))). rewrite shift_eq.\n      rewrite run_run_n.\n      replace (l ++ [s1; s']) with ((l ++ [s1]) ++ [s']) at 1 by now rewrite <- List.app_assoc.\n      pose proof (run_n_length (l ++ [s1]) [s']) as [l3 Hl3].\n      replace (Datatypes.length (l ++ [s1])) with (S (Datatypes.length l)) in Hl3.\n      replace (run_n (S (Datatypes.length l)) ((l ++ [s1]) ++ [s'])) with ([s'] ++ l3) at 1.\n      now destruct s' as [[a b] c].\n      rewrite List.app_length. simpl. lia.\nQed.\n\n(** [run [s]] immediately generates [s] *)\nTheorem run_here:\n  forall s,\n    run [s] ⊨ here s.\nProof.\n  now intros [[path env] prog].\nQed.\n\n(** [run] is complete for [sym_steps]:\n    At any point in time, if [s] is generated by [run l], then\n    all the [sym_steps] sucessors of [s] are eventually generated\n*)\nTheorem run_steps_complete:\n  forall s s',\n    sym_steps s s' ->\n    forall l,\n      run l ⊨ □ (!s → ◊!s').\nProof.\n  intros s s' H.\n  dependent induction H.\n  - intros l n Hn. now exists 0.\n  - intros l n Hn. rewrite run_run_n in *.\n    pose proof (run_step_complete (run_n n l) _ _ H Hn) as [m Hm]. simpl in Hm.\n    specialize (IHstar _ _ Hm) as [k Hk].\n    rewrite shift_shift, run_run_n in Hk.\n    eexists (k + m). now rewrite run_run_n.\nQed.\n\n(** [run] is a complete wau to compute the [sym_steps] sucessors\n    of any state [s]:\n    starting with the task [[s]], [run [s]] eventually generates\n    all [sym_steps] sucessors of [s]\n*)\nTheorem run_complete:\n  forall s s',\n    sym_steps s s' -> run [s] ⊨ ◊!s'.\nProof.\n  intros.\n  now pose proof (run_steps_complete _ _ H [s] 0 (run_here s)).\nQed.\n\nTheorem run_finished_nil:\n  forall l,\n    run l ⊨ none -> l = [].\nProof.\n  now intros [|[[path env] prog]].\nQed.\n\nTheorem run_finished:\n  forall l,\n    run l ⊨ □ (none → □ none).\nProof.\n  intros l n Hn m.\n  rewrite run_run_n in Hn.\n  apply run_finished_nil in Hn.\n  rewrite run_run_n, Hn.\n  now rewrite run_nil.\nQed.\n\n(** [fin_bugs] is sound:\n    For any program [p], [find_bugs p]\n    emits warnings ONLY if it found a bug in [p]\n*)\nTheorem find_bugs_sound:\n  forall p,\n    find_bugs p ⊨ □ (potential_bug p).\nProof.\n  intros. unfold find_bugs.\n  pose proof (run_sound (init p)).\n  intros n. specialize (H n).\n  unfold potential_bug, reachable_from, now in *.\n  rewrite get_shift in *. simpl get in *.\n  rewrite get_map in *. destruct display eqn:Heq1; try easy.\n  destruct get as [[[path env] prog]|] eqn:Heq2; simpl in Heq1; try easy.\n  destruct (is_error prog) eqn:Heq3.\n  apply is_error_correct in Heq3. injection Heq1 as <-.\n  now destruct H as [[[path0 env0] prog0] [[[=->->->]|] H2]].\n  now destruct is_skip.\nQed.\n\n(** [fin_bugs] is complete:\n    For any program [p], if it has a bug,\n    [find_bugs p] will eventually find it\n*)\nTheorem find_bugs_complete:\n  forall p s',\n    symex.potential_bug (Bcst true, id, p) s' ->\n    find_bugs p ⊨ ◊ (bug_found s').\nProof.\n  intros p [[path env] prog] [H1 H2].\n  pose proof (run_complete _ _ H1) as [n Hn].\n  exists n. unfold find_bugs, bug_found, here, now in *.\n  rewrite get_shift in *. simpl in *.\n  rewrite get_map. unfold init.\n  destruct get eqn:Heq1; subst; try easy.\n  unfold display.\n  destruct is_error eqn:Heq2; try easy.\n  destruct prog; try easy.\n  apply is_error_correct in H2.\n  now rewrite H2 in Heq2.\nQed.\n\n(** A symbolic state denotes a valid bug in\n    [p] if all states in its concretization are bugs\n*)\nDefinition ValidBug p σ' :=\n  forall σ, Concrete σ' σ -> imp.IsBug p σ.\n\n(** A status message is valid wrt prog [p] \n    if it is a [BugFound] message reporting a [ValidBug]\n    or any other kind of status message\n*)\nDefinition ValidStatus p :=\n  now (fun st =>\n    match st with\n    | BugFound σ' => ValidBug p σ'\n    | _ => True\n    end\n  ).\n\nDefinition Symbolic σ :=\n  now (fun st =>\n    match st with\n    | BugFound σ' => Concrete σ' σ\n    | _ => False\n    end\n  ).\n\nTheorem relative_completeness:\n  forall p σ,\n    imp.IsBug p σ -> find_bugs p ⊨ ◊ Symbolic σ.\nProof.\n  intros * [(V0 & σ' & [Hsteps Hequiv])%Reach_complete H].\n  pose proof (run_complete _ _ Hsteps) as [n Hn].\n  exists n.\n  unfold find_bugs, Symbolic, bug_found, here, now in *.\n  rewrite get_shift in *. simpl in *.\n  rewrite get_map. unfold init, display.\n  destruct get as [[[π senv] p']|]; auto.\n  rewrite <- Hn in Hequiv. destruct σ as [V ?].\n  destruct (is_error p') eqn:Herr.\n  - now exists V0.\n  - destruct Hequiv as [_ [-> ->]].\n    apply is_error_Stuck in H.\n    now rewrite H in Herr.\nQed.\n\nTheorem relative_soundness:\n  forall p,\n    find_bugs p ⊨ □ ValidStatus p.\nProof.\n  intros p n.\n  pose proof (find_bugs_sound p n).\n  unfold ValidStatus, potential_bug, now, get in *.\n  destruct (shift) eqn:Heq.\n  destruct x as [ [[φ senv] p'] | | ]; auto.\n  intros [V p''] (V0 & HV0).\n  destruct H as [H2 H3].\n  split.\n  - apply symex.Reach_sound.\n    now exists V0, (φ, senv, p').\n  - destruct HV0 as  [_ [_ <-]].\n    now apply is_error_Stuck, is_error_correct.\nQed.\n\n\n(** \"termination\" of the bugfinding loop:\n    If at any point in time [find_bugs p] emits\n    a [Finished] token, then the exploration of [p]\n    terminated. We encode this property by\n    asserting that after the first [Finished] token,\n    the only message that the loop will ever send is [Finished]\n    (i.e. it cannot find new bugs afterward)\n*)\nTheorem sound_termination:\n  forall p,\n    find_bugs p ⊨ □ (done → □ done).\nProof.\n  intros p. unfold find_bugs.\n  pose proof (run_finished (init p)).\n  intros n Hn m.\n  assert (Hnone : none (shift n (run (init p)))).\n  { unfold none, done, now in Hn |-*. rewrite get_shift in *.\n    simpl in *. rewrite get_map in Hn.\n    destruct get as [[[path env] prog]|] eqn:Heq1; try easy.\n    simpl in Hn. destruct is_error eqn:Heq2; try easy.\n  }\n  specialize (H n Hnone m). clear Hn Hnone.\n  rewrite shift_shift in *.\n  unfold done, none, now in *.\n  rewrite get_shift in *. simpl in *.\n  rewrite get_map. now destruct get eqn:Heq.\nQed.", "meta": {"author": "acorrenson", "repo": "WiSE", "sha": "7faabb31b45a9a98ac618ab3728ff7b178bda596", "save_path": "github-repos/coq/acorrenson-WiSE", "path": "github-repos/coq/acorrenson-WiSE/WiSE-7faabb31b45a9a98ac618ab3728ff7b178bda596/src/implem/bugfinder_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061556288288, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.24015141981842558}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\n\nSet Implicit Arguments.\n\n\nModule MemoryReorder.\n  Lemma add_add\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 from2 to2 msg2\n        mem2\n        (ADD1: Memory.add mem0 loc1 from1 to1 msg1 mem1)\n        (ADD2: Memory.add mem1 loc2 from2 to2 msg2 mem2):\n    exists mem1',\n      <<ADD1: Memory.add mem0 loc2 from2 to2 msg2 mem1'>> /\\\n      <<ADD2: Memory.add mem1' loc1 from1 to1 msg1 mem2>> /\\\n      <<LOCTS: (loc1, to1) <> (loc2, to2)>>.\n  Proof.\n    exploit (@Memory.add_exists mem0 loc2 from2 to2).\n    { i. inv ADD2. inv ADD. eapply DISJOINT.\n      etrans; [eapply Memory.add_o; eauto|]. condtac; ss; eauto.\n      des. subst. exploit Memory.add_get0; eauto. i. des. congr.\n    }\n    { inv ADD2. inv ADD. auto. }\n    { inv ADD2. inv ADD. eauto. }\n    i. des.\n    exploit (@Memory.add_exists mem3 loc1 from1 to1).\n    { i. revert GET2. erewrite Memory.add_o; eauto. condtac; ss.\n      - des. subst. i. inv GET2.\n        exploit Memory.add_get0; try exact ADD2; eauto.\n        inv ADD2. inv ADD. symmetry. eapply DISJOINT.\n        etrans; [eapply Memory.add_o; eauto|]. condtac; ss. des; congr.\n      - guardH o. i. inv ADD1. inv ADD. eapply DISJOINT; eauto.\n    }\n    { inv ADD1. inv ADD. auto. }\n    { inv ADD1. inv ADD. eauto. }\n    i. des.\n    esplits; eauto; cycle 1.\n    { ii. inv H.\n      exploit Memory.add_get0; try exact ADD2; eauto.\n      erewrite Memory.add_o; eauto. condtac; s; i; des; congr.\n    }\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    setoid_rewrite Memory.add_o; cycle 1; eauto.\n    erewrite (@Memory.add_o mem3); eauto. erewrite (@Memory.add_o mem1); eauto.\n    repeat (condtac; ss). des. subst.\n    exploit Memory.add_get0; try exact ADD1; eauto. i. des.\n    exploit Memory.add_get0; try exact ADD2; eauto. i. des.\n    congr.\n  Qed.\n\n  Lemma add_remove\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 from2 to2 msg2\n        mem2\n        (LOCTS1: (loc1, to1) <> (loc2, to2))\n        (ADD1: Memory.add mem0 loc1 from1 to1 msg1 mem1)\n        (REMOVE2: Memory.remove mem1 loc2 from2 to2 msg2 mem2):\n    exists mem1',\n      <<REMOVE1: Memory.remove mem0 loc2 from2 to2 msg2 mem1'>> /\\\n      <<ADD2: Memory.add mem1' loc1 from1 to1 msg1 mem2>>.\n  Proof.\n    exploit (@Memory.remove_exists mem0 loc2 from2 to2).\n    { hexploit Memory.remove_get0; eauto.\n      erewrite Memory.add_o; eauto. condtac; ss; i; des; subst; eauto. congr.\n    }\n    i. des.\n    exploit (@Memory.add_exists mem3 loc1 from1 to1);\n      try by inv ADD1; inv ADD; eauto.\n    { i. revert GET2. erewrite Memory.remove_o; eauto. condtac; ss.\n      inv ADD1. inv ADD. eauto.\n    }\n    i. des.\n    cut (mem4 = mem2); [by i; subst; eauto|].\n    apply Memory.ext. i.\n    erewrite Memory.add_o; eauto. erewrite Memory.remove_o; eauto.\n    erewrite (@Memory.remove_o mem2); eauto. erewrite (@Memory.add_o mem1); eauto.\n    repeat (condtac; ss). des. repeat subst. congr.\n  Qed.\n\n  Lemma add_remove_same\n        mem0 loc1 from1 to1 msg1\n        mem1 from2 msg2\n        mem2\n        (ADD1: Memory.add mem0 loc1 from1 to1 msg1 mem1)\n        (REMOVE2: Memory.remove mem1 loc1 from2 to1 msg2 mem2):\n    from1 = from2 /\\ msg1 = msg2 /\\ mem0 = mem2.\n  Proof.\n    exploit Memory.add_get0; eauto. i. des.\n    exploit Memory.remove_get0; eauto. i. des.\n    rewrite GET0 in *. inv GET1. splits; auto.\n    apply Memory.ext. i.\n    erewrite (@Memory.remove_o mem2); eauto. condtac; ss.\n    - des. subst. ss.\n    - erewrite (@Memory.add_o mem1); eauto. condtac; ss.\n  Qed.\n\n  Lemma remove_add\n        mem0 loc1 from1 to1 msg1\n        mem1 loc2 from2 to2 msg2\n        mem2\n        (REMOVE1: Memory.remove mem0 loc1 from1 to1 msg1 mem1)\n        (ADD2: Memory.add mem1 loc2 from2 to2 msg2 mem2)\n        (TS: Time.lt from1 to1)\n        (LOCTS: loc1 <> loc2 \\/ Interval.disjoint (from1, to1) (from2, to2)):\n    exists mem1',\n      <<ADD1: Memory.add mem0 loc2 from2 to2 msg2 mem1'>> /\\\n      <<REMOVE2: Memory.remove mem1' loc1 from1 to1 msg1 mem2>>.\n  Proof.\n    guardH LOCTS.\n    exploit (@Memory.add_exists mem0 loc2 from2 to2 msg2).\n    { i. exploit Memory.remove_get1; try exact GET2; eauto. i. des.\n      { subst. unguard. des; ss. symmetry. ss. }\n      exploit Memory.add_get1; try exact x0; eauto. i.\n      exploit Memory.add_get0; eauto. i. des.\n      exploit Memory.get_disjoint; [exact GET0|exact x1|]. i. des; ss. subst. congr.\n    }\n    { exploit Memory.add_ts; eauto. }\n    { inv ADD2. inv ADD. ss. }\n    i. des.\n    esplits; eauto.\n    exploit Memory.remove_get0; eauto. i. des.\n    exploit Memory.add_get1; try exact GET; eauto. i.\n    exploit Memory.remove_exists; try exact x1. i. des.\n    cut (mem4 = mem2); try congr.\n    apply Memory.ext. i.\n    erewrite (@Memory.remove_o mem4); eauto.\n    erewrite (@Memory.add_o mem3); eauto.\n    erewrite (@Memory.add_o mem2); eauto.\n    erewrite (@Memory.remove_o mem1); eauto.\n    repeat (condtac; ss). des. subst. exfalso.\n    unguard. des; ss.\n    exploit Memory.add_ts; eauto. i.\n    apply (LOCTS to2); econs; ss; refl.\n  Qed.\n\n  Lemma remove_remove\n        promises0 loc1 from1 to1 msg1\n        promises1 loc2 from2 to2 msg2\n        promises2\n        (REMOVE1: Memory.remove promises0 loc1 from1 to1 msg1 promises1)\n        (REMOVE2: Memory.remove promises1 loc2 from2 to2 msg2 promises2):\n    exists promises1',\n      <<REMOVE1: Memory.remove promises0 loc2 from2 to2 msg2 promises1'>> /\\\n      <<REMOVE2: Memory.remove promises1' loc1 from1 to1 msg1 promises2>>.\n  Proof.\n    exploit Memory.remove_get0; try apply REMOVE2; eauto. i. des.\n    revert GET. erewrite Memory.remove_o; eauto. condtac; ss. guardH o. i.\n    exploit Memory.remove_exists; eauto. i. des.\n    hexploit Memory.remove_get0; try apply REMOVE1; eauto. i. des.\n    exploit (@Memory.remove_exists mem2 loc1 from1 to1 msg1); eauto.\n    { erewrite Memory.remove_o; eauto. condtac; ss. des. subst. congr. }\n    i. des.\n    esplits; eauto.\n    cut (mem0 = promises2); [by i; subst|].\n    apply Memory.ext. i.\n    erewrite Memory.remove_o; eauto. erewrite Memory.remove_o; eauto.\n    erewrite (@Memory.remove_o promises2); eauto. erewrite (@Memory.remove_o promises1); eauto.\n    repeat (condtac; ss).\n  Qed.\nEnd MemoryReorder.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/prop/MemoryReorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24013295030566634}}
{"text": "\nFrom LogRel.AutoSubst Require Import core unscoped Ast Extra.\nFrom LogRel Require Import Utils BasicAst Notations Context NormalForms Weakening GenericTyping LogicalRelation DeclarativeInstance Validity.\nFrom LogRel.LogicalRelation Require Import Irrelevance Reflexivity Transitivity.\n\nSet Universe Polymorphism.\n\nSection Irrelevances.\nContext `{GenericTypingProperties}.\n\n\nLemma VRirrelevant Γ {vsubst vsubst' veqsubst veqsubst'}\n  (vr : VR Γ vsubst veqsubst) (vr' : VR Γ vsubst' veqsubst') :\n  (forall Δ σ wfΔ wfΔ', vsubst Δ σ wfΔ <~> vsubst' Δ σ wfΔ') ×\n  (forall Δ σ σ' wfΔ wfΔ' vs vs', veqsubst Δ σ σ' wfΔ vs <~> veqsubst' Δ σ σ' wfΔ' vs').\nProof.\n  revert vsubst' veqsubst' vr'.  pattern Γ, vsubst, veqsubst, vr.\n  apply VR_rect; clear Γ vsubst veqsubst vr.\n  - intros ?? h. inversion h. split; reflexivity.\n  - intros ?????? ih ?? h. inversion h.\n    specialize (ih _ _ VΓad0); destruct ih as [ih1 ih2].\n    split.\n    + intros. split; intros []; unshelve econstructor.\n      1,2: eapply ih1; eassumption.\n      1,2: irrelevance.\n    + intros; split; intros []; unshelve econstructor.\n      1,3: eapply ih2; eassumption.\n      1,2: irrelevance.\nQed.\n\nLemma irrelevanceSubst {Γ} (VΓ VΓ' : [||-v Γ]) {σ Δ} (wfΔ wfΔ' : [|- Δ]) :\n  [Δ ||-v σ : Γ | VΓ | wfΔ] -> [Δ ||-v σ : Γ | VΓ' | wfΔ'].\nProof.\n  apply (fst (VRirrelevant Γ VΓ.(VAd.adequate) VΓ'.(VAd.adequate))).\nQed.\n\nLemma irrelevanceSubstEq {Γ} (VΓ VΓ' : [||-v Γ]) {σ σ' Δ} (wfΔ wfΔ' : [|- Δ])\n  (Vσ : [Δ ||-v σ : Γ | VΓ | wfΔ]) (Vσ' : [Δ ||-v σ : Γ | VΓ' | wfΔ']) :\n  [Δ ||-v σ ≅ σ' : Γ | VΓ | wfΔ | Vσ] -> [Δ ||-v σ ≅ σ' : Γ | VΓ' | wfΔ' | Vσ'].\nProof.\n  apply (snd (VRirrelevant Γ VΓ.(VAd.adequate) VΓ'.(VAd.adequate))).\nQed.\n\nSet Printing Primitive Projection Parameters.\n\nLemma reflSubst {Γ} (VΓ : [||-v Γ]) : forall {σ Δ} (wfΔ : [|- Δ])\n  (Vσ : [Δ ||-v σ : Γ | VΓ | wfΔ]),\n  [Δ ||-v σ ≅ σ : Γ | VΓ | wfΔ | Vσ].\nProof.\n  pattern Γ, VΓ; apply validity_rect; clear Γ VΓ.\n  - constructor.\n  - intros * ih. unshelve econstructor.\n    1: apply ih.\n    apply LREqTermRefl_. exact (validHead Vσ).\nQed.\n\nLemma symmetrySubstEq {Γ} (VΓ VΓ' : [||-v Γ]) : forall {σ σ' Δ} (wfΔ wfΔ' : [|- Δ])\n  (Vσ : [Δ ||-v σ : Γ | VΓ | wfΔ]) (Vσ' : [Δ ||-v σ' : Γ | VΓ' | wfΔ']),\n  [Δ ||-v σ ≅ σ' : Γ | VΓ | wfΔ | Vσ] -> [Δ ||-v σ' ≅ σ : Γ | VΓ' | wfΔ' | Vσ'].\nProof.\n  revert VΓ'; pattern Γ, VΓ; apply validity_rect; clear Γ VΓ.\n  - intros VΓ'. rewrite (invValidityEmpty VΓ'). constructor.\n  - intros * ih VΓ'. pose proof (x := invValiditySnoc VΓ').\n    destruct x as [lA'[ VΓ'' [VA' ->]]].\n    intros ????? [tl hd] [tl' hd'] [tleq hdeq].\n    unshelve econstructor.\n    1: now eapply ih.\n    eapply LRTmEqSym. cbn in *.\n    revert hdeq. apply LRTmEqRedConv.\n    eapply validTyExt. 2:eassumption.\n    eapply irrelevanceSubst; eassumption.\nQed.\n\nLemma transSubstEq {Γ} (VΓ : [||-v Γ]) :\n  forall {σ σ' σ'' Δ} (wfΔ : [|- Δ])\n    (Vσ : [Δ ||-v σ : Γ | VΓ | wfΔ])\n    (Vσ' : [Δ ||-v σ' : Γ | VΓ | wfΔ]),\n    [Δ ||-v σ ≅ σ' : Γ | VΓ | wfΔ | Vσ] ->\n    [Δ ||-v σ' ≅ σ'' : Γ | VΓ | wfΔ | Vσ'] ->\n    [Δ ||-v σ ≅ σ'' : Γ | VΓ | wfΔ | Vσ].\nProof.\n  pattern Γ, VΓ; apply validity_rect; clear Γ VΓ.\n  - constructor.\n  - intros * ih * [] []; unshelve econstructor.\n    1: now eapply ih.\n    eapply transEqTerm; tea.\n    eapply LRTmEqRedConv; tea.\n    unshelve eapply LRTyEqSym; tea.\n    2: unshelve eapply validTyExt.\n    7: eassumption.\n    1: tea.\n    now eapply validTail.\nQed.\n\nLemma irrelevanceValidity {Γ} : forall (VΓ VΓ' : [||-v Γ]) {l A},\n  [Γ ||-v<l> A | VΓ] -> [Γ ||-v<l> A | VΓ'].\nProof.\n  intros VΓ VΓ' l A [VA VAext]; unshelve econstructor; intros.\n  - unshelve eapply VA. 2: eapply irrelevanceSubst. all:eassumption.\n  - eapply VAext; [eapply irrelevanceSubst| eapply irrelevanceSubstEq]; eassumption.\nQed.\n\n\nLemma irrelevanceLift {l A F G Γ} (VΓ : [||-v Γ])\n  (VF: [Γ ||-v<l> F | VΓ]) (VG: [Γ ||-v<l> G | VΓ])\n  (VFeqG : [Γ ||-v<l> F ≅ G | VΓ | VF]) :\n  [Γ ,, F ||-v<l> A | validSnoc VΓ VF] ->\n  [Γ ,, G ||-v<l> A | validSnoc VΓ VG].\nProof.\n  intros [VA VAext]; unshelve econstructor.\n  - intros ??? [hd tl]. eapply VA.\n    unshelve econstructor. 1: eassumption.\n    eapply LRTmRedConv. 2: eassumption.\n    eapply LRTyEqSym; unshelve eapply VFeqG; eassumption.\n  - intros ???? [??] [??] [??]. eapply VAext.\n    + unshelve econstructor. 1: eassumption.\n      eapply LRTmRedConv. 2: eassumption.\n      eapply LRTyEqSym; unshelve eapply VFeqG; eassumption.\n    + unshelve econstructor. 1: eassumption.\n      eapply LRTmEqRedConv. 2: eassumption.\n      eapply LRTyEqSym; unshelve eapply VFeqG; eassumption.\nQed.\n\nLemma irrelevanceEq {Γ l A B} (VΓ VΓ' : [||-v Γ]) (VA : [Γ ||-v<l> A | VΓ]) (VA' : [Γ||-v<l> A | VΓ']) :\n  [Γ ||-v< l > A ≅ B | VΓ | VA] -> [Γ ||-v< l > A ≅ B | VΓ' | VA'].\nProof.\n  intros [h]; constructor; intros.\n  irrelevanceRefl.\n  unshelve apply h. 1:eassumption.\n  eapply irrelevanceSubst; eassumption.\nQed.\n\nLemma irrelevanceEq' {Γ l A A' B} (VΓ VΓ' : [||-v Γ]) (VA : [Γ ||-v<l> A | VΓ]) (VA' : [Γ||-v<l> A' | VΓ']) : A = A' ->\n  [Γ ||-v< l > A ≅ B | VΓ | VA] -> [Γ ||-v< l > A' ≅ B | VΓ' | VA'].\nProof.\n  intros ->; now eapply irrelevanceEq.\nQed.\n\nLemma symValidEq {Γ l A B} {VΓ : [||-v Γ]} {VA : [Γ ||-v<l> A | VΓ]} (VB : [Γ ||-v<l> B | VΓ]) :\n  [Γ ||-v<l> A ≅ B | VΓ | VA] -> [Γ ||-v<l> B ≅ A | VΓ | VB].\nProof.\n  intros; constructor; intros.\n  eapply LRTyEqSym; now eapply validTyEq.\n  Unshelve. all: tea.\nQed.\n\nLemma transValidEq {Γ l A B C} {VΓ : [||-v Γ]}\n  {VA : [Γ ||-v<l> A | VΓ]} {VB : [Γ ||-v<l> B | VΓ]} (VC : [Γ ||-v<l> C | VΓ]):\n  [Γ ||-v<l> A ≅ B | VΓ | VA] -> [Γ ||-v<l> B ≅ C | VΓ | VB] -> [Γ ||-v<l> A ≅ C | VΓ | VA].\nProof.\n  constructor; intros; eapply transEq; now eapply validTyEq.\n  Unshelve. all: tea. now eapply validTy.\nQed.\n\nLemma irrelevanceTm {Γ l t A} (VΓ VΓ' : [||-v Γ]) (VA : [Γ ||-v<l> A | VΓ]) (VA' : [Γ||-v<l> A | VΓ']) :\n  [Γ ||-v<l> t : A | VΓ | VA] -> [Γ ||-v<l> t : A | VΓ' | VA'].\nProof.\n  intros [h1 h2]; unshelve econstructor.\n  - intros. irrelevanceRefl.\n    unshelve apply h1. 1:eassumption.\n    eapply irrelevanceSubst; eassumption.\n  - intros. irrelevanceRefl.\n    unshelve eapply h2. 1: eassumption.\n    1,2: eapply irrelevanceSubst; eassumption.\n    eapply irrelevanceSubstEq; eassumption.\nQed.\n\nLemma irrelevanceTm' {Γ l t A A'} (VΓ VΓ' : [||-v Γ]) (VA : [Γ ||-v<l> A | VΓ]) (VA' : [Γ||-v<l> A' | VΓ']) :\n  A = A' -> [Γ ||-v<l> t : A | VΓ | VA] -> [Γ ||-v<l> t : A' | VΓ' | VA'].\nProof.\n  intros ->; now eapply irrelevanceTm.\nQed.\n\nLemma irrelevanceTmLift {l t A F G Γ} (VΓ : [||-v Γ])\n  (VF: [Γ ||-v<l> F | VΓ]) (VG: [Γ ||-v<l> G | VΓ])\n  (VFeqG : [Γ ||-v<l> F ≅ G | VΓ | VF])\n  (VA : [Γ ,, F ||-v<l> A | validSnoc VΓ VF])\n  (VA' : [Γ ,, G ||-v<l> A | validSnoc VΓ VG])  :\n  [Γ ,, F ||-v<l> t : A | validSnoc VΓ VF | VA] ->\n  [Γ ,, G ||-v<l> t : A | validSnoc VΓ VG | VA'].\nProof.\n  intros [Vt Vtext]; unshelve econstructor.\n  - intros ??? [hd tl]. irrelevanceRefl. \n    unshelve eapply Vt; tea.\n    unshelve econstructor; tea.\n    eapply LRTmRedConv; tea.\n    eapply LRTyEqSym; unshelve eapply VFeqG; eassumption.\n  - intros ???? [??] [??] [??]. irrelevanceRefl. \n    unshelve eapply Vtext; tea.\n    + unshelve econstructor; tea.\n      eapply LRTmRedConv; tea.\n      eapply LRTyEqSym; unshelve eapply VFeqG; eassumption.\n    + unshelve econstructor; tea.\n      eapply LRTmRedConv; tea.\n      eapply LRTyEqSym; unshelve eapply VFeqG; eassumption.\n    + unshelve econstructor; tea.\n      eapply LRTmEqRedConv; tea.\n      eapply LRTyEqSym; unshelve eapply VFeqG; eassumption.\nQed.\n\nLemma irrelevanceTmEq {Γ l t u A} (VΓ VΓ' : [||-v Γ]) (VA : [Γ ||-v<l> A | VΓ]) (VA' : [Γ||-v<l> A | VΓ']) :\n  [Γ ||-v<l> t ≅ u : A | VΓ | VA] -> [Γ ||-v<l> t ≅ u : A | VΓ' | VA'].\nProof.\n  intros [h]; constructor; intros; irrelevanceRefl.\n  unshelve apply h; tea.\n  eapply irrelevanceSubst; eassumption.\nQed.\n\nLemma irrelevanceTmEq' {Γ l t u A A'} (VΓ VΓ' : [||-v Γ]) (VA : [Γ ||-v<l> A | VΓ]) (VA' : [Γ||-v<l> A' | VΓ']) :\n  A = A' -> [Γ ||-v<l> t ≅ u : A | VΓ | VA] -> [Γ ||-v<l> t ≅ u : A' | VΓ' | VA'].\nProof.\n  intros ->; now eapply irrelevanceTmEq.\nQed.\n\nLemma symValidTmEq {Γ l t u A} {VΓ : [||-v Γ]} {VA : [Γ ||-v<l> A | VΓ]} :\n  [Γ ||-v<l> t ≅ u : A| VΓ | VA] -> [Γ ||-v<l> u ≅ t : A | VΓ | VA].\nProof.\n  intros; constructor; intros.\n  eapply LRTmEqSym; now eapply validTmEq.\nQed.\n\nLemma transValidTmEq {Γ l t u v A} {VΓ : [||-v Γ]}\n  {VA : [Γ ||-v<l> A | VΓ]} :\n  [Γ ||-v<l> t ≅ u : A | VΓ | VA] -> \n  [Γ ||-v<l> u ≅ v : A | VΓ | VA] -> \n  [Γ ||-v<l> t ≅ v : A | VΓ | VA].\nProof.\n  constructor; intros; eapply transEqTerm; now eapply validTmEq.\nQed.\n\nLemma irrelevanceSubstExt {Γ} (VΓ : [||-v Γ]) {σ σ' Δ} (wfΔ : [|- Δ]) :\n  σ =1 σ' -> [Δ ||-v σ : Γ | VΓ | wfΔ] -> [Δ ||-v σ' : Γ | VΓ | wfΔ].\nProof.\n  revert σ σ'; pattern Γ, VΓ; apply validity_rect; clear Γ VΓ.\n  - constructor.\n  - intros ????? ih ?? eq.  unshelve econstructor.\n    + eapply ih. 2: now eapply validTail.\n      now rewrite eq.\n    + rewrite <- (eq var_zero).\n      pose proof (validHead X).\n      irrelevance. now rewrite eq.\nQed.\n\nLemma irrelevanceSubstEqExt {Γ} (VΓ : [||-v Γ]) {σ1 σ1' σ2 σ2' Δ}\n  (wfΔ : [|- Δ]) (eq1 : σ1 =1 σ1') (eq2 : σ2 =1 σ2')\n  (Vσ1 : [Δ ||-v σ1 : Γ | VΓ | wfΔ]) :\n  [Δ ||-v σ1 ≅ σ2 : Γ | VΓ | wfΔ | Vσ1] ->\n  [Δ ||-v σ1' ≅ σ2' : Γ | VΓ | wfΔ | irrelevanceSubstExt VΓ wfΔ eq1 Vσ1].\nProof.\n  revert σ1 σ1' σ2 σ2' eq1 eq2 Vσ1; pattern Γ, VΓ; apply validity_rect; clear Γ VΓ.\n  - constructor.\n  - intros ????? ih ???? eq1 eq2 ? X. unshelve econstructor.\n    + eapply irrelevanceSubstEq.\n      unshelve eapply ih.\n      6: now eapply eqTail.\n      all: now (rewrite eq1 + rewrite eq2).\n    + rewrite <- (eq1 var_zero); rewrite <- (eq2 var_zero).\n      pose proof (eqHead X).\n      irrelevance.\n      rewrite eq1; reflexivity.\nQed.\n\nEnd Irrelevances.\n\nLtac irrValid :=\n  match goal with\n  | [_ : _ |- [||-v _]] => idtac\n  | [_ : _ |- [ _ ||-v _ : _ | _ | _]] => eapply irrelevanceSubst\n  | [_ : _ |- [ _ ||-v _ ≅ _ : _ | _ | _ | _]] => eapply irrelevanceSubstEq\n  | [_ : _ |- [_ ||-v<_> _ | _]] => eapply irrelevanceValidity\n  | [_ : _ |- [_ ||-v<_> _ ≅ _ | _ | _]] => eapply irrelevanceEq\n  | [_ : _ |- [_ ||-v<_> _ : _ | _ | _]] => eapply irrelevanceTm\n  | [_ : _ |- [_ ||-v<_> _ ≅ _ : _ | _ | _]] => eapply irrelevanceTmEq\n  end; eassumption.", "meta": {"author": "CoqHott", "repo": "logrel-coq", "sha": "b9077b14125be083024e979e9eb9c357a648caed", "save_path": "github-repos/coq/CoqHott-logrel-coq", "path": "github-repos/coq/CoqHott-logrel-coq/logrel-coq-b9077b14125be083024e979e9eb9c357a648caed/theories/Substitution/Irrelevance.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2401329437071153}}
{"text": "Require Import VST.msl.seplog.\nRequire Import VST.msl.log_normalize.\nRequire Import CertiGraph.lib.Coqlib.\nRequire Import CertiGraph.lib.Ensembles_ext.\nRequire Import CertiGraph.lib.EquivDec_ext.\nRequire Import Coq.Lists.List.\nRequire Import CertiGraph.msl_ext.ramification_lemmas.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.path_lemmas.\nRequire Import CertiGraph.graph.graph_gen.\nRequire Import CertiGraph.graph.graph_relation.\nRequire Import CertiGraph.graph.subgraph2.\nRequire Import CertiGraph.graph.reachable_ind.\nRequire Import CertiGraph.graph.spanning_tree.\nRequire Import CertiGraph.graph.BinGraph.\nRequire Import CertiGraph.graph.MathGraph.\nRequire Import CertiGraph.graph.FiniteGraph.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import CertiGraph.msl_application.GraphBin.\nRequire Import CertiGraph.msl_application.GraphBin_Mark.\nRequire CertiGraph.graph.weak_mark_lemmas.\nImport CertiGraph.graph.weak_mark_lemmas.WeakMarkGraph.\n\n(* TODO: Put some pure lemmas into some file like: graph/bi_spanning. *)\n\n#[export] Instance MGS: MarkGraphSetting bool.\n  apply (Build_MarkGraphSetting bool\n          (eq true));\n  intros.\n  + destruct x; [left | right]; congruence.\nDefined.\n\nSection SPATIAL_GRAPH_DISPOSE_BIN.\n\n  Context {pSGG_Bin: pPointwiseGraph_Graph_Bin}.\n  Context {sSGG_Bin: sPointwiseGraph_Graph_Bin bool unit}.\n\n  Existing Instances maGraph binGraph finGraph.\n\n  Local Open Scope logic.\n  Local Coercion Graph_LGraph: Graph >-> LGraph.\n  Local Coercion LGraph_SGraph: LGraph >-> SGraph.\n  Local Identity Coercion Graph_GeneralGraph: Graph >-> GeneralGraph.\n  Local Identity Coercion LGraph_LabeledGraph: LGraph >-> LabeledGraph.\n  Local Identity Coercion SGraph_PointwiseGraph: SGraph >-> PointwiseGraph.\n  Local Coercion pg_lg: LabeledGraph >-> PreGraph.\n\n  Notation Graph := (@Graph pSGG_Bin bool unit unit).\n\n  Lemma vgamma_is_true: forall (g : Graph) (x l r : addr), vgamma g x = (true, l, r) -> marked g x.\n  Proof. intros. simpl in H. simpl. destruct (vlabel g x) eqn:? . auto. inversion H. Qed.\n  \n  Lemma vgamma_is_false: forall (g : Graph) (x l r : addr), vgamma g x = (false, l, r) -> unmarked g x.\n  Proof.\n    intros. simpl in H. hnf. unfold Ensembles.In. simpl. intro.\n    destruct (vlabel g x) eqn:? . inversion H. simpl in H0. inversion H0.\n  Qed.\n  \n  Lemma edge_spanning_tree_left_null:\n    forall (g: Graph) x d l r, vvalid g x -> vgamma g x = (d, l, r) -> (marked g) l ->\n                               edge_spanning_tree g (x, L) (Graph_gen_left_null g x).\n  Proof.\n    intros. assert (l = dst g (x, L)) by (simpl in H0; inversion H0; auto).\n    hnf. change (lg_gg g) with (g: LGraph). destruct (node_pred_dec (marked g) (dst g (x, L))). 2: subst l; exfalso; auto.\n    split.\n    + hnf. simpl. split; [| split; [|split; [| split]]]; [tauto | tauto | tauto | | ].\n      - intros. unfold updateEdgeFunc.\n        destruct (equiv_dec (x, L) e); intuition.\n      - right. unfold updateEdgeFunc.\n        destruct (equiv_dec (x, L) (x, L)); intuition.\n        * apply (valid_not_null g) in H3; auto. reflexivity.\n        * apply (@left_valid _ _ _ _ _ _ g (binGraph g)) in H; auto.\n    + simpl. tauto.\n  Qed.\n\n  Lemma graph_gen_left_null_ramify:\n    forall (g: Graph) (x : addr) d (l r : addr),\n      vvalid g x -> vgamma g x = (d, l, r) ->\n      (reachable_vertices_at x g : pred) |-- vertex_at x (d, l, r) * (vertex_at x (d, null, r) -* vertices_at (reachable g x) (Graph_gen_left_null g x)).\n  Proof.\n    intros.\n    replace (@vertex_at _ _ _ _ _ SGP x (d, l, r)) with (graph_vcell g x).\n    2: {\n      unfold graph_vcell; simpl.\n      simpl in H0; rewrite H0; auto.\n    }\n    replace (@vertex_at _ _ _ _ _ SGP x (d, null, r)) with (graph_vcell (Graph_gen_left_null g x) x).\n    2: {\n      unfold graph_vcell; simpl.\n      unfold updateEdgeFunc.\n      destruct_eq_dec (x, L) (x, L). 2: exfalso; auto.\n      destruct_eq_dec (x, L) (x, R). inversion H2.\n      simpl in H0; inversion H0; auto.\n    }\n    apply vertices_at_ramif_1; auto.\n    eexists; split; [| split].\n    + apply Ensemble_join_Intersection_Complement.\n      - unfold Included, Ensembles.In; intros; subst; apply reachable_by_refl; auto.\n      - intros; destruct_eq_dec x x0; auto.\n    + apply Ensemble_join_Intersection_Complement.\n      - unfold Included, Ensembles.In; intros; subst; apply reachable_by_refl; auto.\n      - intros; destruct_eq_dec x x0; auto.\n    + rewrite vertices_identical_spec.\n      simpl; intros.\n      change (lg_gg g) with (g: LGraph).\n      rewrite Intersection_spec in H1.\n      destruct H1; unfold Complement, Ensembles.In in H2.\n      simpl. unfold updateEdgeFunc.\n      destruct_eq_dec (x, L) (x0, L).\n      - inversion H3. exfalso; auto.\n      - destruct_eq_dec (x, L) (x0, R). inversion H4. auto.\n  Qed.\n\n  Lemma graph_gen_left_null_ramify_weak:\n    forall (g: Graph) (x : addr) d (l r : addr),\n      vvalid g x -> vgamma g x = (d, l, r) ->\n      (reachable_vertices_at x g : pred) |-- vertex_at x (d, l, r) * (vertex_at x (d, null, r) -* (reachable_vertices_at x (Graph_gen_left_null g x) * TT)).\n  Proof.\n    intros. pose proof (graph_gen_left_null_ramify g x d l r H H0).\n    apply log_normalize.sepcon_weaken with (vertex_at x (d, null, r) -* vertices_at (reachable g x) (Graph_gen_left_null g x)); auto.\n    apply wand_derives; auto. unfold reachable_vertices_at.\n    cut ((vertices_at (reachable g x) (Graph_gen_left_null g x) : pred)\n                     |-- vertices_at (reachable (Graph_gen_left_null g x) x)\n                     (Graph_gen_left_null g x) * TT). auto. unfold vertices_at.\n    apply iter_sepcon.pred_sepcon_prop_true_weak.\n    - apply Graph_reachable_dec, weak_valid_vvalid_dec. right.\n      unfold Graph_gen_left_null. simpl. apply H.\n    - intro y. unfold Graph_gen_left_null. simpl.\n      apply is_partial_graph_reachable, pregraph_gen_dst_is_partial_graph.\n      apply invalid_null.\n  Qed.\n\n  Lemma graph_ramify_aux1_left: forall (g: Graph) x d l r,\n      vvalid g x -> vgamma g x = (d, l, r) ->\n      (reachable_vertices_at x g : pred) |-- reachable_vertices_at l g *\n      (ALL  g' : Graph , !!spanning_tree g l g' --> (vertices_at (reachable g l) g' -* vertices_at (reachable g x) g')).\n  Proof.\n    intros. eapply vertices_at_ramif_xQ; auto.\n    eexists; split; [| split].\n    + eapply Prop_join_reachable_left; eauto.\n    + intros. eapply Prop_join_reachable_left; eauto.\n    + intros; rewrite vertices_identical_spec.\n      intros.\n      rewrite Intersection_spec in H2. unfold Complement, Ensembles.In in H2.\n      destruct H2. simpl. f_equal; [f_equal |].\n      - apply vlabel_eq. destruct H1. specialize (H1 x0).\n        pose proof reachable_by_is_reachable g l x0 (unmarked g).\n        tauto.\n      - destruct H1 as [_ [? _]]. hnf in H1. simpl in H1.\n        unfold predicate_weak_evalid in H1. destruct H1 as [_ [? [_ ?]]].\n        specialize (H1 (x0, L)). specialize (H4 (x0, L)).\n        assert (src g (x0, L) = x0)\n          by (apply (@left_sound _ _ _ _ _ _ g (binGraph g) x0); apply reachable_foot_valid in H2; auto).\n        change (lg_gg g) with (g: LGraph) in *.\n        rewrite H5 in *.\n        assert (evalid g (x0, L) /\\ ~ g |= l ~o~> x0 satisfying (unmarked g)). {\n          split.\n          + apply reachable_foot_valid in H2.\n            apply (@left_valid _ _ _ _ _ _ g (binGraph g)); auto.\n          + intro; apply H3; apply reachable_by_is_reachable in H6; auto.\n        } apply H4; intuition.\n      - destruct H1 as [_ [? _]]. hnf in H1. simpl in H1.\n        unfold predicate_weak_evalid in H1. destruct H1 as [_ [? [_ ?]]].\n        specialize (H1 (x0, R)). specialize (H4 (x0, R)).\n        assert (src g (x0, R) = x0)\n          by (apply (@right_sound _ _ _ _ _ _ g (binGraph g) x0); apply reachable_foot_valid in H2; auto).\n        change (lg_gg g) with (g: LGraph) in *.\n        rewrite H5 in *.\n        assert (evalid g (x0, R) /\\ ~ g |= l ~o~> x0 satisfying (unmarked g)). {\n          split.\n          + apply reachable_foot_valid in H2.\n            apply (@right_valid _ _ _ _ _ _ g (binGraph g)); auto.\n          + intro; apply H3; apply reachable_by_is_reachable in H6; auto.\n        } apply H4; intuition.\n  Qed.\n\n  Lemma totally_unmarked_root_ST_reachable_eq: forall (g1 g2: Graph) root,\n      totally_unmarked g1 root -> spanning_tree g1 root g2 ->\n      vertices_at (reachable g1 root) g2 = reachable_vertices_at root g2.\n  Proof.\n    intros. apply vertices_at_Same_set. rewrite Same_set_spec. hnf.\n    apply spanning_tree_totally_unmarked_root_reachable; auto. intros.\n    apply Graph_reachable_by_dec, weak_valid_vvalid_dec; right; auto.\n  Qed.\n\n  Lemma totally_unmarked_parent_ST_reachable_eq: forall (g1 g2: Graph) x l r,\n      vvalid g1 x -> vgamma g1 x = (true, l, r) -> totally_unmarked g1 l ->\n      spanning_tree g1 l g2 ->\n      vertices_at (reachable g1 x) g2 = reachable_vertices_at x g2.\n  Proof.\n    intros. apply vertices_at_Same_set. rewrite Same_set_spec. hnf.\n    assert (l = dst (lg_gg g1) (x, L)) by (simpl in H0; inversion H0; auto).\n    apply spanning_tree_totally_unmarked_parent_reachable with (e := (x, L));\n      auto; try rewrite <- H3; auto.\n      - hnf. split.\n        + apply (@left_valid _ _ _ _ _ _ g1 (binGraph g1)); auto.\n        + apply (@left_sound _ _ _ _ _ _ g1 (binGraph g1) x); auto.\n      - apply vgamma_is_true in H0. auto.\n      - intros; apply Graph_reachable_by_dec, weak_valid_vvalid_dec; right; auto.\n  Qed.\n(*\n  Lemma graph_ramify_aux1_left_weak: forall (g: Graph) x l r,\n      vvalid g x -> vgamma g x = (true, l, r) -> totally_unmarked g l ->\n      (reachable_vertices_at x g : pred) |-- reachable_vertices_at l g *\n      (ALL  g' : Graph , !!spanning_tree g l g' --> (reachable_vertices_at l g' -* reachable_vertices_at x g')).\n  Proof.\n    intros. pose proof (@graph_ramify_aux1_left g x true l r H H0).\n    eapply log_normalize.sepcon_weaken. 2: apply H2. clear H2.\n    apply allp_derives. intros p. destruct p as [? g2]. simpl.\n    rewrite <- imp_andp_adjoint. apply derives_extract_prop'. intros.\n    rewrite prop_imp; auto. apply wand_derives.\n    - rewrite <- totally_unmarked_root_ST_reachable_eq; auto.\n    - rewrite (totally_unmarked_parent_ST_reachable_eq _ _ _ l r); auto.\n  Qed.\n*)\n  Lemma edge_spanning_tree_left_vvalid: forall (g1 g2: Graph) x n,\n      vvalid g1 x -> edge_spanning_tree g1 (x, L) g2 -> (vvalid g1 n <-> vvalid g2 n).\n  Proof.\n    intros. apply (edge_spanning_tree_vvalid g1 g2 (x, L) n); auto.\n  Qed.\n\n  Lemma edge_spanning_tree_right_vvalid: forall (g1 g2: Graph) x n,\n      vvalid g1 x -> edge_spanning_tree g1 (x, R) g2 -> (vvalid g1 n <-> vvalid g2 n).\n  Proof.\n    intros. apply (edge_spanning_tree_vvalid g1 g2 (x, R) n); auto.\n  Qed.\n\n  Lemma edge_spanning_tree_left_reachable_vvalid: forall (g1 g2: Graph) x d l r,\n      vvalid g1 x -> vgamma g1 x = (d, l, r) -> edge_spanning_tree g1 (x, L) g2 -> Included (reachable g1 x) (vvalid g2).\n  Proof.\n    intros. assert (x = src g1 (x, L)) by (symmetry; apply (@left_sound _ _ _ _ _ _ g1 (binGraph g1) x); auto).\n    rewrite H2. apply edge_spanning_tree_reachable_vvalid; auto.\n  Qed.\n\n  Lemma edge_spanning_tree_left_vgamma: forall (g1 g2: Graph) x l r,\n      vvalid g1 x -> vgamma g1 x = (true, l, r) -> edge_spanning_tree g1 (x, L) g2 -> exists l', vgamma g2 x = (true, l', r).\n  Proof.\n    intros. simpl. exists (dst g2 (x, L)).\n    assert (Hvg2: vvalid g2 x) by (rewrite <- edge_spanning_tree_left_vvalid; eauto).\n    unfold edge_spanning_tree in H1.\n    change (lg_gg g1) with (g1: LGraph) in H1.\n    destruct (node_pred_dec (marked g1) (dst g1 (x, L))).\n    + destruct H1 as [[_ [_ [_ [? _]]]] ?]. simpl in H0, H2. inversion H0.\n      rewrite H4. symmetry in H4. rewrite H2 in H4.\n      change (lg_gg g2) with (g2: LGraph) in H4.\n      rewrite <- H4. f_equal. symmetry. apply H1.\n      - intro. inversion H3.\n      - apply (@right_valid _ _ _ _ _ _ g1 (binGraph g1)) in H; auto.\n      - apply (@right_valid _ _ _ _ _ _ g2 (binGraph g2)) in Hvg2; auto.\n    + destruct H1 as [? [[_ [_ [_ ?]]] _]].\n      assert (marked g1 x) by (simpl in *; inversion H0; auto).\n      assert (~ g1 |= dst g1 (x, L) ~o~> x satisfying (unmarked g1)) by (intro HS; apply reachable_by_foot_prop in HS; auto).\n      assert (marked g2 x) by (specialize (H1 x); tauto).\n      simpl in H5. rewrite <- H5. f_equal.\n      simpl in H2. unfold predicate_weak_evalid in H2.\n      simpl in H0. inversion H0. symmetry.\n      change (lg_gg g1) with (g1: LGraph) in *.\n      change (lg_gg g2) with (g2: LGraph) in *.\n      apply H2; split.\n      - apply (@right_valid _ _ _ _ _ _ g1 (binGraph g1) x); auto.\n      - rewrite (@right_sound _ _ _ _ _ _ g1 (binGraph g1) x); auto.\n      - apply (@right_valid _ _ _ _ _ _ g2 (binGraph g2) x); auto.\n      - rewrite (@right_sound _ _ _ _ _ _ g2 (binGraph g2) x); auto.\n  Qed.\n\n  Lemma spanning_tree_left_reachable:\n    forall (g1 g2: Graph) x l r,\n      vvalid g1 x -> vgamma g1 x = (true, l, r) ->\n      spanning_tree g1 l g2 -> Included (reachable g2 r) (reachable g1 x).\n  Proof.\n    intros. intro v. unfold Ensembles.In . intros.\n    assert (X: ReachDecidable g1 l (unmarked g1)). {\n      apply Graph_reachable_by_dec.\n      apply weak_valid_vvalid_dec.\n      apply (gamma_left_weak_valid g1 x true l r); auto.\n    } destruct (X v).\n    + apply reachable_by_is_reachable in r0. apply edge_reachable_by with l; auto.\n      split; [|split]; auto.\n      - apply reachable_head_valid in r0. auto.\n      - simpl in H0. inversion H0. exists (x, L); auto.\n        * apply (@left_valid _ _ _ _ _ _ g1 (binGraph g1)); auto.\n        * apply (@left_sound _ _ _ _ _ _ g1 (binGraph g1)); auto.\n    + apply edge_reachable_by with r; auto.\n      - split; [|split]; auto.\n        * apply reachable_head_valid in H2.\n          rewrite (spanning_tree_vvalid g1 l g2); auto.\n        * rewrite (gamma_step g1 x true l r); auto.\n      - apply (spanning_tree_not_reachable g1 l g2 r v) in H2; auto.\n        rewrite reachable_by_eq_partialgraph_reachable in H2.\n        destruct H1 as [? [? ?]]. rewrite <- H3 in H2.\n        rewrite <- reachable_by_eq_partialgraph_reachable in H2.\n        apply reachable_by_is_reachable in H2. apply H2.\n  Qed.\n\n  Lemma edge_spanning_tree_left_reachable:\n    forall (g1 g2: Graph) x l r,\n      vvalid g1 x -> vgamma g1 x = (true, l, r) ->\n      edge_spanning_tree g1 (x, L) g2 -> Included (reachable g2 r) (reachable g1 x).\n  Proof.\n    intros. assert (Hv: vvalid g2 r -> vvalid g1 r). {\n      intros. rewrite (edge_spanning_tree_left_vvalid g1 g2 x r); auto.\n    } hnf in H1.\n    assert (l = dst g1 (x, L))\n      by (simpl in H0; inversion H0; auto).\n    change (lg_gg g1) with (g1: LGraph) in *.\n    rewrite <- H2 in H1. destruct (node_pred_dec (marked g1) l).\n    + destruct H1 as [[? [? [? [? ?]]]] ?]. intro v. unfold Ensembles.In .\n      intros. apply edge_reachable_by with r; auto.\n      - split; [|split]; auto.\n        * apply Hv. apply reachable_head_valid in H8; auto.\n        * rewrite (gamma_step g1 x true l r); auto.\n      - change (g1 |= r ~o~> v satisfying (fun _ : addr => True))\n        with (reachable g1 r v).\n        rewrite reachable_ind_reachable in H8. clear H0. induction H8.\n        * rewrite reachable_ind_reachable. constructor. rewrite H1; auto.\n        * destruct H0 as [? [? ?]]. apply edge_reachable with y.\n          apply IHreachable. rewrite H1; auto.\n          split; [|split]; [rewrite H1; auto .. |]. rewrite step_spec in H10 |- *.\n          destruct H10 as [e [? [? ?]]]. exists e.\n          assert (e <> (x, L)) by (intro; subst; destruct H6; [|destruct H2]; auto).\n          specialize (H3 _ H13). specialize (H4 _ H13). specialize (H5 _ H13).\n          subst x0. subst y. intuition.\n    + apply (spanning_tree_left_reachable g1 g2 x l r); auto.\n  Qed.\n\n  Lemma Prop_join_EST_right: forall (g1 g2: Graph) x l r,\n      vvalid g1 x -> vgamma g1 x = (true, l, r) ->\n      edge_spanning_tree g1 (x, L) g2 ->\n      Prop_join (reachable g2 r)\n                (Intersection _ (reachable g1 x) (Complement addr (reachable g2 r)))\n                (reachable g1 x).\n  Proof.\n    intros. apply Ensemble_join_Intersection_Complement.\n    + eapply edge_spanning_tree_left_reachable; eauto.\n    + intros.\n      destruct (edge_spanning_tree_left_vgamma g1 g2 x l r H H0 H1) as [l' ?].\n      apply gamma_right_weak_valid in H2.\n      - apply decidable_prop_decidable, Graph_reachable_dec,\n        weak_valid_vvalid_dec; auto.\n      - apply (edge_spanning_tree_left_reachable_vvalid g1 g2 x true l r); auto.\n        unfold Ensembles.In . apply reachable_by_refl; auto.\n  Qed.\n\n  Lemma graph_ramify_aux1_right: forall (g1 g2: Graph) x l r,\n      vvalid g1 x -> vgamma g1 x = (true, l, r) ->\n      edge_spanning_tree g1 (x, L) g2 ->\n      (vertices_at (reachable g1 x) g2: pred) |-- reachable_vertices_at r g2 *\n      (ALL  g' : Graph ,\n                !!spanning_tree g2 r g' -->\n                  (vertices_at (reachable g2 r) g' -*\n                               vertices_at (reachable g1 x) g')).\n  Proof.\n    intros. eapply vertices_at_ramif_xQ; auto.\n    eexists; split; [| split].\n    + eapply Prop_join_EST_right; eauto.\n    + intros. eapply Prop_join_EST_right; eauto.\n    + intros; rewrite vertices_identical_spec.\n      intros. simpl.\n      rewrite Intersection_spec in H3; unfold Complement, Ensembles.In in H3.\n      destruct H3. f_equal; [f_equal |].\n      - apply vlabel_eq. destruct H2 as [? _]. specialize (H2 x0).\n        pose proof reachable_by_is_reachable g2 r x0 (unmarked g2).\n        tauto.\n      - destruct H2 as [_ [? _]]. hnf in H2. simpl in H2.\n        unfold predicate_weak_evalid in H2. destruct H2 as [_ [? [_ ?]]].\n        specialize (H2 (x0, L)). specialize (H5 (x0, L)).\n        assert (src g2 (x0, L) = x0).\n        1: {\n          apply (@left_sound _ _ _ _ _ _ g2 (binGraph g2) x0).\n          rewrite <- (edge_spanning_tree_left_vvalid g1 g2 x x0 H H1).\n          apply reachable_foot_valid in H3; auto.\n        }\n        change (lg_gg g2) with (g2: LGraph) in *.\n        rewrite H6 in *.\n        assert (evalid g2 (x0, L) /\\ ~ g2 |= r ~o~> x0 satisfying (unmarked g2)). {\n          split.\n          + apply reachable_foot_valid in H3.\n            apply (@left_valid _ _ _ _ _ _ g2 (binGraph g2)).\n            rewrite <- (edge_spanning_tree_left_vvalid g1 g2 x); eauto.\n          + intro; apply H4; apply reachable_by_is_reachable in H7; auto.\n        } apply H5; intuition.\n      - destruct H2 as [_ [? _]]. hnf in H2. simpl in H2.\n        unfold predicate_weak_evalid in H2. destruct H2 as [_ [? [_ ?]]].\n        specialize (H2 (x0, R)). specialize (H5 (x0, R)).\n        assert (src g2 (x0, R) = x0).\n        1: {\n          apply (@right_sound _ _ _ _ _ _ g2 (binGraph g2) x0).\n          rewrite <- (edge_spanning_tree_left_vvalid g1 g2 x x0 H H1).\n          apply reachable_foot_valid in H3; auto.\n        }\n        change (lg_gg g2) with (g2: LGraph) in *.\n        rewrite H6 in *.\n        assert (evalid g2 (x0, R) /\\ ~ g2 |= r ~o~> x0 satisfying (unmarked g2)). {\n          split.\n          + apply reachable_foot_valid in H3.\n            apply (@right_valid _ _ _ _ _ _ g2 (binGraph g2)).\n            rewrite <- (edge_spanning_tree_left_vvalid g1 g2 x); eauto.\n          + intro; apply H4; apply reachable_by_is_reachable in H7; auto.\n        } apply H5; intuition.\n  Qed.\n\n  Lemma graph_gen_right_null_ramify: forall (g1 g2: Graph) (x : addr) d (l r : addr),\n      vvalid g1 x -> vgamma g2 x = (d, l, r) ->\n      (vertices_at (reachable g1 x) g2 : pred) |--\n                  vertex_at x (d, l, r) * (vertex_at x (d, l, null) -* vertices_at (reachable g1 x) (Graph_gen_right_null g2 x)).\n  Proof.\n    intros.\n    replace (@vertex_at _ _ _ _ _ SGP x (d, l, r)) with (graph_vcell g2 x).\n    2: {\n      unfold graph_vcell; simpl.\n      simpl in H0; rewrite H0; auto.\n    }\n    replace (@vertex_at _ _ _ _ _ SGP x (d, l, null)) with (graph_vcell (Graph_gen_right_null g2 x) x).\n    2: {\n      unfold graph_vcell; simpl.\n      unfold updateEdgeFunc.\n      destruct_eq_dec (x, R) (x, L). inversion H1.\n      destruct_eq_dec (x, R) (x, R). 2: exfalso; apply H2; auto.\n      simpl in H0; inversion H0; auto.\n    }\n    apply vertices_at_ramif_1; auto.\n    eexists; split; [| split].\n    + apply Ensemble_join_Intersection_Complement.\n      - unfold Included, Ensembles.In; intros; subst; apply reachable_by_refl; auto.\n      - intros; destruct_eq_dec x x0; auto.\n    + apply Ensemble_join_Intersection_Complement.\n      - unfold Included, Ensembles.In; intros; subst; apply reachable_by_refl; auto.\n      - intros; destruct_eq_dec x x0; auto.\n    + rewrite vertices_identical_spec.\n      simpl; intros.\n      change (lg_gg g2) with (g2: LGraph).\n      rewrite Intersection_spec in H1.\n      destruct H1; unfold Complement, Ensembles.In in H2.\n      simpl. unfold updateEdgeFunc.\n      destruct_eq_dec (x, R) (x0, L).\n      - inversion H3.\n      - destruct_eq_dec (x, R) (x0, R).\n        * inversion H4. exfalso; auto.\n        * auto.\n  Qed.\n\n  Lemma graph_gen_right_null_ramify_weak: forall (g2: Graph) (x : addr) d (l r : addr),\n      vvalid g2 x -> vgamma g2 x = (d, l, r) ->\n      (reachable_vertices_at x g2 : pred) |-- vertex_at x (d, l, r) * (vertex_at x (d, l, null) -* (reachable_vertices_at x (Graph_gen_right_null g2 x) * TT)).\n  Proof.\n    intros. pose proof (graph_gen_right_null_ramify g2 g2 x d l r H H0).\n    apply log_normalize.sepcon_weaken with (vertex_at x (d, l, null) -* vertices_at (reachable g2 x) (Graph_gen_right_null g2 x)); auto.\n    apply wand_derives; auto. unfold reachable_vertices_at.\n    cut ((vertices_at (reachable g2 x) (Graph_gen_right_null g2 x): pred)\n           |-- vertices_at (reachable (Graph_gen_right_null g2 x) x)\n           (Graph_gen_right_null g2 x) * TT). auto. unfold vertices_at.\n    apply iter_sepcon.pred_sepcon_prop_true_weak.\n    - apply Graph_reachable_dec, weak_valid_vvalid_dec. right.\n      unfold Graph_gen_left_null. simpl. apply H.\n    - intro y. unfold Graph_gen_left_null. simpl.\n      apply is_partial_graph_reachable, pregraph_gen_dst_is_partial_graph.\n      apply invalid_null.\n  Qed.\n\n  Lemma edge_spanning_tree_right_null:\n    forall (g: Graph) x d l r, vvalid g x -> vgamma g x = (d, l, r) -> (marked g) r ->\n                               edge_spanning_tree g (x, R) (Graph_gen_right_null g x).\n  Proof.\n    intros. assert (r = dst g (x, R)) by (simpl in H0; inversion H0; auto).\n    hnf.\n    change (lg_gg g) with (g: LGraph). destruct (node_pred_dec (marked g) (dst g (x, R))). 2: subst r; exfalso; auto.\n    split.\n    + hnf. simpl. split; [| split; [|split; [| split]]]; [tauto | tauto | tauto | | ].\n      - intros. unfold updateEdgeFunc.\n        destruct (equiv_dec (x, R) e); intuition.\n      - right. split; auto. unfold updateEdgeFunc.\n        destruct (equiv_dec (x, R) (x, R)); intuition.\n        * apply (valid_not_null g) in H3; auto. reflexivity.\n        * split; auto. apply (@right_valid _ _ _ _ _ _ g (binGraph g)) in H; auto.\n    + simpl. tauto.\n  Qed.\n\n  Lemma edge_spanning_tree_spanning_tree: forall (g g1 g2 g3 : Graph) x l r,\n      vvalid g x -> vvalid g1 x -> vvalid g2 x ->\n      vgamma g x = (false, l, r) ->\n      vgamma g1 x = (true, l, r) ->\n      mark1 x g g1 ->\n      edge_spanning_tree g1 (x, L) g2 ->\n      edge_spanning_tree g2 (x, R) g3 ->\n      spanning_tree g x g3.\n  Proof.\n    intros.\n    apply (spanning_list_spanning_tree2 _ g1 _ _ (x, L) (x, R)); auto; intros.\n    + intro. inversion H7.\n    + pose proof (only_two_edges x e H). simpl in H7 |-* .\n      split; intros.\n      - destruct H8 as [? | [? | ?]]; [subst e..|exfalso; auto].\n        * split; [|intuition]. apply (@left_valid _ _ _ _ _ _ g (binGraph g)); auto.\n        * split; [|intuition]. apply (@right_valid _ _ _ _ _ _ g (binGraph g)); auto.\n      - destruct H8. intuition.\n    + apply Graph_reachable_by_dec. apply weak_valid_vvalid_dec. pose proof H3.\n      simpl in H3. inversion H3. subst l.\n      apply (gamma_left_weak_valid g1 x true (dst g1 (x, L)) r); auto.\n    + unfold unmarked. rewrite negateP_spec. unfold marked. simpl. simpl in H2.\n      inversion H2.\n      change (lg_gg g) with (g: LGraph).\n      rewrite H8. intuition.\n    + apply spanning_list_cons with g2; auto.\n      apply spanning_list_cons with g3; auto.\n      apply spanning_list_nil. auto.\n  Qed.\n\nEnd SPATIAL_GRAPH_DISPOSE_BIN.\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/data_structure/spatial_graph_dispose_bin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.38121957328625583, "lm_q1q2_score": 0.24008241239916492}}
{"text": "Require Import HoareDef MutHeader MutMain0 MutMain1 SimModSem.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import Relation_Definitions.\n\n(*** TODO: export these in Coqlib or Universe ***)\nRequire Import Relation_Operators.\nRequire Import RelationPairs.\nFrom ITree Require Import\n     Events.MapDefault.\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Maps\n     Data.Map.FMapAList.\n\nRequire Import HTactics ProofMode.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\n\n\n\nSection SIMMODSEM.\n\n  Context `{Σ: GRA.t}.\n\n  Let W: Type := Any.t * Any.t.\n\n  Let wf: _ -> W -> Prop :=\n    mk_wf (fun (_: unit) _ _ => (True: iProp)%I).\n\n  Theorem correct: refines2 [MutMain0.Main] [MutMain1.Main].\n  Proof.\n    eapply adequacy_local2. econs; ss.\n    i. econstructor 1 with (wf:=wf) (le:=top2); et.\n    { ss. }\n    2: { exists tt. red. econs; ss. rr. uipropall. }\n    econs; ss. init.\n    unfold mainF, mainBody. harg.\n    mDesAll. des; clarify. steps.\n    astart 10. acatch. hcall _ tt with \"*\"; ss.\n    { iPureIntro. esplits; eauto.\n      { instantiate (1:=10). ss. }\n      { unfold mut_max. lia. }\n    }\n    steps. astop. mDesAll. des; clarify. steps.\n    hret tt; ss.\n    Unshelve. all: ss. all: try exact 0.\n  Qed.\n\nEnd SIMMODSEM.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/mutsum/MutMain01proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630722, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.23996229838720096}}
{"text": "Require Import include_frm.\nRequire Import math_rewrite.\nRequire Import int_auto.\n\nLocal Open Scope int_scope.\nLocal Open Scope Z_scope.\n\n(* the following lemmas if for strut_type_vallist_match tactic *)\nLemma isptr_is_definitely_ptr :\n  forall x, isptr x ->  match x with\n   | Vundef => false\n   | Vnull => true\n   | Vint32 _ => false\n   | Vptr _ => true\n   end = true.\nProof.\n  intros.\n  destruct x;\n  destruct H;\n  simpljoin;\n  tryfalse.\nQed.\n\nLemma le255_and_le255 :\n  forall x v'37,\n    Int.unsigned x<=255 -> Int.unsigned (x &ᵢ v'37) <= 255.\nProof.\n  intros.\n  set (Int.and_le x v'37).\n  omega.\nQed.\n\nLemma ptr_isptr : forall x, isptr (Vptr x).\n  intros.\n  unfolds.\n  right; eexists; eauto.\nQed.\n\nLemma Vnull_is_ptr : isptr Vnull.\nProof.\n  unfolds; auto.\nQed.\n\nHint Resolve le255_and_le255                    : struct_type_match_side_lib.\nHint Resolve ptr_isptr                          : struct_type_match_side_lib.\nHint Resolve Vnull_is_ptr                       : struct_type_match_side_lib.\nHint Resolve isptr_is_definitely_ptr            : struct_type_match_side_lib.\n\nLtac struct_single_condition_solver :=\n  let H := fresh in\n  try math_simpl H;\n    try solve [ auto with struct_type_match_side_lib\n                            (* here just bsimpl*r* just to compat with old version *)\n               |math prove neg H; bsimplr; auto with struct_type_match_side_lib; omega].\n\nLtac struct_type_match_solver_new :=\n  match goal with\n    | |- struct_type_vallist_match ?a _ => unfold a\n  end;\n  unfold struct_type_vallist_match; simpl; repeat splits ; struct_single_condition_solver. \n\nLtac struct_type_match_solver := struct_type_match_solver_new.\n\n(* Require Import os_ucos_h.\n * \n * Lemma struct_type_vallist_match_os_tcb :\n *   forall xx v'82 v'80 v'37 v'75 v'76 v'77 v'78 v'79 xxx yyy flag,\n *     isptr xxx ->\n *     isptr yyy ->\n *     isptr v'82 -> \n *     isptr v'80 ->\n *     Int.unsigned v'37 <= 255 ->\n *     Int.unsigned v'75 <= 255 ->\n *     Int.unsigned v'76 <= 255 ->\n *     Int.unsigned v'77 <= 255 ->\n *     Int.unsigned v'78 <= 255 ->\n *     Int.unsigned v'79 <= 255 ->\n *     Int.unsigned xx <= 65535-> \n *     Int.unsigned flag <= 255 ->\n *     struct_type_vallist_match OS_TCB\n *                               (v'82\n *                                  :: v'80\n *                                  :: xxx\n *                                  :: yyy\n *                                  :: Vint32 xx\n *                                  :: Vint32 (v'37 &ᵢ v'75)\n *                                  :: Vint32 v'75\n *                                  :: Vint32 v'76\n *                                  :: Vint32 v'77\n *                                  :: Vint32 v'78 :: Vint32 v'79 :: Vint32 flag::  nil).\n * Proof.\n *   intros.\n *   struct_type_match_solver_new.\n * Qed. *)\n\n(* Lemma struct_type_vallist_match_os_event_mbox:  forall v'51 v'52 v'49 v'50 v'55, isptr v'50 -> isptr v'51 -> Int.unsigned v'52 <= 255 -> Int.unsigned v'49 <= 65535-> struct_type_vallist_match OS_EVENT (V$OS_EVENT_TYPE_MBOX\n *       :: Vint32 v'52 :: Vint32 v'49 :: v'50 :: v'55 :: v'51 :: nil).\n *   intros.\n *   pauto.\n * Qed. *)\n\n(* Lemma struct_type_vallist_match_os_event:  forall v'51 v'52 v'49 v'50 v'55 xx, isptr v'50 -> isptr v'51 ->Int.unsigned xx <=255 -> Int.unsigned v'52 <= 255 -> Int.unsigned v'49 <= 65535-> struct_type_vallist_match OS_EVENT (Vint32 xx\n *       :: Vint32 v'52 :: Vint32 v'49 :: v'50 :: v'55 :: v'51 :: nil).\n * Proof.\n *   intros.\n *   struct_type_match_solver_new.\n * Qed. *)\n\n\n(* Ltac const_le_solver := match goal with \n * | |- Int.unsigned  ($ ?e ) <= _ => try solve [clear; unfold e; int auto]\n * end.\n * \n * Ltac struct_type_match_solver := match goal with\n * | |- struct_type_vallist_match OS_EVENT _ =>  apply  struct_type_vallist_match_os_event\n * | |- struct_type_vallist_match OS_TCB _   =>  apply  struct_type_vallist_match_os_tcb\n * end; try solve [ auto 3 with struct_type_match_side_lib | unfolds; auto 3 with struct_type_match_side_lib | const_le_solver]. *)\n\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/tactics/pure/struct_type_match_solver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2399622926687481}}
{"text": "(** * Properties about Context Free Grammars *)\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Fiat.Parsers.StringLike.Core Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Fiat.Common Fiat.Common.UIP.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Properties Fiat.Parsers.ContextFreeGrammar.Transfer.\n\nSet Implicit Arguments.\n\nLocal Open Scope list_scope.\n\nSection cfg.\n  Context {Char} {HSLM1 HSLM2 : StringLikeMin Char}\n          {HSL1 : @StringLike Char HSLM1}\n          {HSL2 : @StringLike Char HSLM2}\n          {G : grammar Char}\n          {R : @String Char HSLM1 -> @String Char HSLM2 -> Prop}\n          {TR : transfer_respectful R}.\n  Context {P : String.string -> Type}.\n\n  Definition transfer_forall_parse_of_item'\n        (transfer_forall_parse_of\n         : forall str1 str2 it (HR : R str1 str2) p,\n             @Forall_parse_of Char _ _ G (fun _ => P) str1 it p\n             -> @Forall_parse_of Char _ _ G (fun _ => P) str2 it (transfer_parse_of HR p))\n        {str1 str2 it}\n        (HR : R str1 str2)\n        {p}\n  : @Forall_parse_of_item' Char _ HSL1 G (fun _ => P) (@Forall_parse_of _ _ _ _ (fun _ => P)) str1 it p\n    -> @Forall_parse_of_item' Char _ HSL2 G (fun _ => P) (@Forall_parse_of _ _ _ _ (fun _ => P)) str2 it (transfer_parse_of_item HR p)\n    := match\n        p in (parse_of_item _ _ it)\n        return\n        (@Forall_parse_of_item' Char _ HSL1 G (fun _ => P) (@Forall_parse_of _ _ _ _ (fun _ => P)) str1 it p\n         -> @Forall_parse_of_item' Char _ HSL2 G (fun _ => P) (@Forall_parse_of _ _ _ _ (fun _ => P)) str2 it (transfer_parse_of_item HR p))\n      with\n        | ParseTerminal _ _ _ _ => fun x => x\n        | ParseNonTerminal _ H' p' => fun xy => (fst xy, transfer_forall_parse_of _ _ _ _ p' (snd xy))\n      end.\n\n  Fixpoint transfer_forall_parse_of\n           str1 str2 pats\n           (HR : R str1 str2)\n           {p}\n           {struct p}\n  : @Forall_parse_of Char _ HSL1 G (fun _ => P) str1 pats p\n    -> @Forall_parse_of Char _ HSL2 G (fun _ => P) str2 pats (transfer_parse_of HR p)\n    := match\n        p in (parse_of _ _ pats)\n        return\n        (@Forall_parse_of Char _ HSL1 G (fun _ => P) str1 pats p\n         -> @Forall_parse_of Char _ HSL2 G (fun _ => P) str2 pats (transfer_parse_of HR p))\n      with\n        | ParseHead _ _ p' => @transfer_forall_parse_of_production _ _ _ _ p'\n        | ParseTail _ _ p' => @transfer_forall_parse_of _ _ _ _ p'\n      end\n  with transfer_forall_parse_of_production\n         str1 str2 pat\n         (HR : R str1 str2)\n         {p}\n         {struct p}\n       : @Forall_parse_of_production Char _ HSL1 G (fun _ => P) str1 pat p\n         -> @Forall_parse_of_production Char _ HSL2 G (fun _ => P) str2 pat (transfer_parse_of_production HR p)\n       := match\n           p in (parse_of_production _ _ pat)\n           return\n           (@Forall_parse_of_production Char _ HSL1 G (fun _ => P) str1 pat p\n            -> @Forall_parse_of_production Char _ HSL2 G (fun _ => P) str2 pat (transfer_parse_of_production HR p))\n         with\n           | ParseProductionNil _ => fun x => x\n           | ParseProductionCons _ _ _ p0 p1\n             => fun xy\n                => (@transfer_forall_parse_of_item' (@transfer_forall_parse_of) _ _ _ _ p0 (fst xy),\n                    @transfer_forall_parse_of_production _ _ _ _ p1 (snd xy))\n         end.\n\n  Global Arguments transfer_forall_parse_of {_ _ _} HR {_} _.\n  Global Arguments transfer_forall_parse_of_production {_ _ _} HR {_} _.\n\n  Definition transfer_forall_parse_of_item\n             {str1 str2 it}\n             (HR : R str1 str2)\n             {p}\n  : @Forall_parse_of_item Char _ HSL1 G (fun _ => P) str1 it p\n    -> @Forall_parse_of_item Char _ HSL2 G (fun _ => P) str2 it (transfer_parse_of_item HR p)\n    := @transfer_forall_parse_of_item' (@transfer_forall_parse_of) str1 str2 it HR p.\nEnd cfg.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_simpl_example/src/Parsers/ContextFreeGrammar/TransferProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2399622926687481}}
{"text": "From mathcomp Require Import ssreflect.\nFrom stdpp Require Import gmap.\nFrom iris.algebra Require Import agree auth gset gmap.\nFrom iris.base_logic.lib Require Import invariants.\nFrom iris.heap_lang Require Import notation proofmode.\nFrom iris.proofmode Require Import base environments.\nFrom cryptis Require Import lib term cryptis primitives.\nImport bi.\nImport env_notations.\n\nSection Proofs.\n\nContext `{!heapG Σ, !cryptisG Σ}.\n\nImplicit Types E : coPset.\nImplicit Types l : loc.\nImplicit Types t : term.\nImplicit Types v : val.\nImplicit Types Φ : prodO locO termO -n> iPropO Σ.\nImplicit Types Ψ : val → iProp Σ.\n\nLemma tac_wp_cons `{!Repr A} Γ E K (x : A) (xs : list A) Ψ :\n  envs_entails Γ (WP fill K (Val (repr (x :: xs)%list)) @ E {{ Ψ }}) →\n  envs_entails Γ (WP fill K (repr x :: repr xs) @ E {{ Ψ }}).\nProof.\nrewrite envs_entails_eq => post.\nby rewrite -wp_bind -wp_cons.\nQed.\n\nLemma tac_wp_cons1 `{!Repr A} Γ E K (x : A) Ψ :\n  envs_entails Γ (WP fill K (Val (repr [x]%list)) @ E {{ Ψ }}) →\n  envs_entails Γ (WP fill K (repr x :: []%V) @ E {{ Ψ }}).\nProof.\nrewrite (_ : NILV = repr (@nil A)) /=; first by apply: tac_wp_cons.\nby rewrite repr_list_eq /=.\nQed.\n\nLemma tac_wp_list_match `{!Repr A} Γ E K vars vs k Ψ :\n  nforall_eq (length vars) vs (\n    λ vs', envs_entails Γ (WP fill K (nsubst vars (map repr vs') k) @ E {{ Ψ }})) →\n  (length vars ≠ length vs →\n    envs_entails Γ (WP fill K NONEV @ E {{ Ψ }})) →\n  envs_entails Γ (WP fill K (list_match vars (repr vs) k) @ E {{ Ψ }}).\nProof.\nrewrite envs_entails_eq => /nforallP hyes hno.\nrewrite -wp_bind -wp_list_match.\ncase: decide => [e_len|ne_len]; last by iApply hno.\nby rewrite -wp_bind_inv; iApply hyes.\nQed.\n\nLemma tac_wp_hash Γ E K t Ψ :\n  envs_entails Γ (WP fill K (Val (THash t)) @ E {{ Ψ }}) →\n  envs_entails Γ (WP fill K (hash t) @ E {{ Ψ }}).\nProof.\nrewrite envs_entails_eq => post.\nby rewrite -wp_bind -wp_hash.\nQed.\n\nLemma tac_wp_tag Γ E K N t Ψ :\n  envs_entails Γ (WP fill K (Val (Spec.tag N t)) @ E {{ Ψ }}) →\n  envs_entails Γ (WP fill K (tag N t) @ E {{ Ψ }}).\nProof.\nrewrite envs_entails_eq => ?.\nby rewrite -wp_bind -wp_tag.\nQed.\n\nLemma tac_twp_untag Γ E K n t Ψ :\n  (∀ t', t = Spec.tag n t' →\n         envs_entails Γ (WP fill K (Val (repr (Some t'))) @ E [{ Ψ }])) →\n  (Spec.untag n t = None →\n   envs_entails Γ (WP fill K (Val NONEV) @ E [{ Ψ }])) →\n  envs_entails Γ (WP fill K (untag n t) @ E [{ Ψ }]).\nProof.\nrewrite envs_entails_eq => HSome HNone.\nrewrite -twp_bind -twp_untag.\ncase e: Spec.untag => [t'|].\n- by move/Spec.untagK in e; apply: HSome.\n- exact: HNone.\nQed.\n\nLemma tac_wp_untag Γ E K n t Ψ :\n  (∀ t', t = Spec.tag n t' →\n         envs_entails Γ (WP fill K (Val (repr (Some t'))) @ E {{ Ψ }})) →\n  (Spec.untag n t = None →\n   envs_entails Γ (WP fill K (Val NONEV) @ E {{ Ψ }})) →\n  envs_entails Γ (WP fill K (untag n t) @ E {{ Ψ }}).\nProof.\nrewrite envs_entails_eq => HSome HNone.\nrewrite -wp_bind -wp_untag.\ncase e: Spec.untag => [t'|].\n- by move/Spec.untagK in e; apply: HSome.\n- exact: HNone.\nQed.\n\nLemma tac_twp_dec Γ E K k t Ψ :\n  (∀ t', t = TEnc k t' →\n         envs_entails Γ (WP fill K (Val (SOMEV t')) @ E [{ Ψ }])) →\n  (Spec.dec (TKey Dec k) t = None →\n   envs_entails Γ (WP fill K (Val NONEV) @ E [{ Ψ }])) →\n  envs_entails Γ (WP fill K (dec (TKey Dec k) t) @ E [{ Ψ }]).\nProof.\nrewrite envs_entails_eq => HSome HNone.\nrewrite -twp_bind -twp_dec.\ncase: t HSome HNone; eauto => k' /=.\nby case: decide => [<-|]; eauto.\nQed.\n\nLemma tac_wp_dec Γ E K k t Ψ :\n  (∀ t', t = TEnc k t' →\n         envs_entails Γ (WP fill K (Val (SOMEV t')) @ E {{ Ψ }})) →\n  (Spec.dec (TKey Dec k) t = None →\n   envs_entails Γ (WP fill K (Val NONEV) @ E {{ Ψ }})) →\n  envs_entails Γ (WP fill K (dec (TKey Dec k) t) @ E {{ Ψ }}).\nProof.\nrewrite envs_entails_eq => HSome HNone.\nrewrite -wp_bind -wp_dec.\ncase: t HSome HNone; eauto => k' /=.\nby case: decide => [<-|]; eauto.\nQed.\n\nLemma tac_wp_tenc Γ E K c t1 t2 Ψ :\n  envs_entails Γ (WP fill K (Val (Spec.tenc c t1 t2)) @ E {{ Ψ }}) →\n  envs_entails Γ (WP fill K (tenc c t1 t2) @ E {{ Ψ }}).\nProof.\nrewrite envs_entails_eq => H.\nby rewrite -wp_bind -wp_tenc.\nQed.\n\n(* MOVE *)\nLemma tdecK c k t t' :\n  Spec.tdec c (TKey Dec k) t = Some t' →\n  t = TEnc k (Spec.tag c t').\nProof.\nrewrite /Spec.tdec /=.\ncase: t => [] //= k' t.\nby case: decide => //= <- /Spec.untagK ->.\nQed.\n(* /MOVE *)\n\nLemma tac_wp_tdec Γ E K c k t Ψ :\n  (∀ t', t = TEnc k (Spec.tag c t') →\n         envs_entails Γ (WP fill K (Val (SOMEV t')) @ E {{ Ψ }})) →\n  (Spec.tdec c (TKey Dec k) t = None →\n   envs_entails Γ (WP fill K (Val NONEV) @ E {{ Ψ }})) →\n  envs_entails Γ (WP fill K (tdec c (TKey Dec k) t) @ E {{ Ψ }}).\nProof.\nrewrite envs_entails_eq => HSome HNone.\nrewrite -wp_bind -wp_tdec.\ncase e: Spec.tdec => [t'|]; eauto.\nby apply: HSome; apply: tdecK.\nQed.\n\nLemma tac_wp_list Γ E K (ts : list term) Ψ :\n  envs_entails Γ (WP fill K (Val (repr ts)) @ E {{ Ψ }}) →\n  envs_entails Γ (WP fill K (list_to_expr ts) @ E {{ Ψ }}).\nProof.\nrewrite envs_entails_eq => post.\nby rewrite -wp_bind -wp_list.\nQed.\n\nLemma tac_twp_list_of_term Γ E K t Ψ :\n  (∀ ts, t = Spec.of_list ts →\n         envs_entails Γ (WP fill K (Val (SOMEV (repr ts))) @ E [{ Ψ }])) →\n  (Spec.to_list t = None →\n   envs_entails Γ (WP fill K NONEV @ E [{ Ψ }])) →\n  envs_entails Γ (WP fill K (list_of_term t) @ E [{ Ψ }]).\nProof.\nrewrite envs_entails_eq => HSome HNone.\nrewrite -twp_bind -twp_list_of_term.\ncase e: Spec.to_list => [ts|]; eauto.\nmove/Spec.to_listK in e; subst t; eauto.\nQed.\n\nLemma tac_wp_list_of_term Γ E K t Ψ :\n  (∀ ts, t = Spec.of_list ts →\n         envs_entails Γ (WP fill K (Val (SOMEV (repr ts))) @ E {{ Ψ }})) →\n  (Spec.to_list t = None →\n   envs_entails Γ (WP fill K NONEV @ E {{ Ψ }})) →\n  envs_entails Γ (WP fill K (list_of_term t) @ E {{ Ψ }}).\nProof.\nrewrite envs_entails_eq => HSome HNone.\nrewrite -wp_bind -wp_list_of_term.\ncase e: Spec.to_list => [ts|]; eauto.\nmove/Spec.to_listK in e; subst t; eauto.\nQed.\n\n(* TODO:\n- Generalize to other instances of Repr\n- rename get_list -> lookup *)\nLemma tac_twp_lookup Γ E K ts (n : Z) Ψ :\n  (0 <= n)%Z →\n  (∀ t, (ts !! Z.to_nat n)%stdpp = Some t →\n        envs_entails Γ (WP fill K (Val (SOMEV t)) @ E [{ Ψ }])) →\n  ((ts !! Z.to_nat n)%stdpp = None →\n   envs_entails Γ (WP fill K (Val NONEV) @ E [{ Ψ }])) →\n  envs_entails Γ (WP fill K (repr ts !! #n)%E @ E [{ Ψ }]).\nProof.\nmove=> npos; rewrite -[in #n](Z2Nat.id n) //.\nmove: (Z.to_nat _)=> {npos} n.\nrewrite envs_entails_eq => HSome HNone.\nrewrite -twp_bind -twp_get_list.\nby case e: (_ !! n)%stdpp => [t|]; eauto.\nQed.\n\nLemma tac_wp_lookup Γ E K ts (n : Z) Ψ :\n  (0 <= n)%Z →\n  (∀ t, (ts !! Z.to_nat n)%stdpp = Some t →\n        envs_entails Γ (WP fill K (Val (SOMEV t)) @ E {{ Ψ }})) →\n  ((ts !! Z.to_nat n)%stdpp = None →\n   envs_entails Γ (WP fill K (Val NONEV) @ E {{ Ψ }})) →\n  envs_entails Γ (WP fill K (repr ts !! #n)%E @ E {{ Ψ }}).\nProof.\nmove=> npos; rewrite -[in #n](Z2Nat.id n) //.\nmove: (Z.to_nat _)=> {npos} n.\nrewrite envs_entails_eq => HSome HNone.\nrewrite -wp_bind -wp_get_list.\nby case e: (_ !! n)%stdpp => [t|]; eauto.\nQed.\n\nLemma tac_wp_eq_term Γ E K t1 t2 Ψ :\n  (t1 = t2 →\n   envs_entails Γ (WP fill K (Val #true) @ E {{ Ψ }})) →\n  (t1 ≠ t2 →\n   envs_entails Γ (WP fill K (Val #false) @ E {{ Ψ }})) →\n  envs_entails Γ (WP fill K (eq_term t1 t2) @ E {{ Ψ }}).\nProof.\nrewrite envs_entails_eq => HSome HNone.\nrewrite -wp_bind -wp_eq_term.\nby case: bool_decide_reflect; eauto.\nQed.\n\nLemma tac_wp_is_key Γ E K t Ψ :\n  (∀ kt k, t = TKey kt k →\n           envs_entails Γ (WP fill K (Val (SOMEV (repr kt))) @ E {{ Ψ }})) →\n  (Spec.is_key t = None →\n   envs_entails Γ (WP fill K (Val NONEV) @ E {{ Ψ }})) →\n  envs_entails Γ (WP fill K (is_key t) @ E {{ Ψ }}).\nProof.\nrewrite envs_entails_eq => HSome HNone.\nrewrite -wp_bind -wp_is_key.\ncase: t HSome HNone; eauto.\nby move=> kt k HSome _ /=; eapply HSome.\nQed.\n\nEnd Proofs.\n\nTactic Notation \"wp_cons\" :=\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' =>\n      lazymatch e' with\n      | App (App (Val CONS) (Val (?f ?x))) (Val ?e'') =>\n        lazymatch e'' with\n        | InjLV (LitV LitUnit) =>\n          let A := type of x in\n          first\n            [eapply (@tac_wp_cons1 _ _ A _ _ _ K x _); wp_finish\n            |fail 1 \"wp_cons: Cannot decode\"]\n        | _ =>\n          first\n            [eapply (tac_wp_cons _ _ K x _ _); wp_finish\n            |fail 1 \"wp_cons: Cannot decode\"]\n        end\n      end)\n  end.\n\nTactic Notation \"wp_list\" := repeat wp_cons.\n\nTactic Notation \"wp_list_match\" :=\n  wp_pures;\n  do ?[rewrite subst_list_match /=];\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' =>\n      lazymatch e' with\n      | list_match ?vars (Val (?f ?xs)) ?k =>\n        lazymatch type of xs with\n        | list ?A =>\n          first\n            [eapply (@tac_wp_list_match _ _ A _ _ E K vars xs k); simpl\n            |fail 1 \"wp_list_match: Cannot decode\"]\n        end\n      end)\n  end.\n\nTactic Notation \"wp_term_of_list\" :=\n  wp_pures; try wp_bind (term_of_list _); iApply wp_term_of_list.\n\nTactic Notation \"wp_enc\" :=\n  wp_pures; try wp_bind (enc _ _); iApply wp_enc.\n\nTactic Notation \"wp_tenc\" :=\n  wp_pures; try wp_bind (tenc _ _ _); iApply wp_tenc.\n\nTactic Notation \"wp_hash\" :=\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' =>\n      first\n        [eapply (tac_wp_hash _ _ K _ _); wp_finish\n        |fail 1 \"wp_hash: Cannot decode\"])\n  end.\n\nTactic Notation \"wp_dec_eq\" ident(t) ident(H) :=\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' =>\n      first\n        [eapply (tac_wp_dec _ _ K _ _);\n         [intros t H|intros H];\n         wp_finish\n        |fail 1 \"wp_dec: Cannot decode\"])\n  end.\n\nTactic Notation \"wp_dec\" ident(t) :=\n  let tf := fresh \"tf\" in\n  let H := fresh \"H\" in\n  wp_dec_eq tf H; [\n    first [revert t tf H; intros _ t ->\n          |revert tf H; intros _ t ->\n          |revert tf H; intros t _]\n  | clear H].\n\nTactic Notation \"wp_tdec_eq\" ident(t) ident(H) :=\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' =>\n      first\n        [eapply (tac_wp_tdec _ _ K _ _);\n         [intros t H|intros H];\n         wp_finish\n        |fail 1 \"wp_tdec: Cannot decode\"])\n  end.\n\nTactic Notation \"wp_tdec\" ident(t) :=\n  let tf := fresh \"tf\" in\n  let H := fresh \"H\" in\n  wp_tdec_eq tf H; [\n    first [revert t tf H; intros _ t ->\n          |revert tf H; intros _ t ->\n          |revert tf H; intros t _]\n  | clear H].\n\nTactic Notation \"wp_list_of_term_eq\" ident(t) ident(H) :=\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' =>\n      first\n        [eapply (tac_wp_list_of_term _ _ K _ _);\n         [intros t H|intros H];\n         wp_finish\n        |fail 1 \"wp_dec: Cannot decode\"])\n  end.\n\nTactic Notation \"wp_list_of_term\" ident(t) :=\n  let tf := fresh \"tf\" in\n  let H := fresh \"H\" in\n  wp_list_of_term_eq tf H; [\n    first [revert t tf H; intros _ t ->\n          |revert tf H; intros _ t ->\n          |revert tf H; intros t _]\n  | clear H].\n\nTactic Notation \"wp_lookup\" ident(t) ident(H) :=\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' =>\n      first\n        [eapply (tac_wp_lookup _ _ K _ _);\n         [lia|intros t H|intros H];\n         wp_finish\n        |fail 1 \"wp_lookup: Cannot decode\"])\n  end.\n\nTactic Notation \"wp_eq_term\" ident(H) :=\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' =>\n      first\n        [eapply (tac_wp_eq_term _ _ K _ _); intros H; wp_finish\n        |fail 1 \"wp_eq_term: Cannot decode\"])\n  end.\n\nTactic Notation \"wp_tag\" :=\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' =>\n      first\n        [eapply (tac_wp_tag _ _ K _ _); wp_finish\n        |fail 1 \"wp_tag: Cannot decode\"])\n  end.\n\nTactic Notation \"wp_untag_eq\" ident(t) ident(H) :=\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' =>\n      first\n        [eapply (tac_wp_untag _ _ K _ _);\n         [intros t H|intros H];\n         wp_finish\n        |fail 1 \"wp_untag_eq: Cannot decode\"])\n  end.\n\nTactic Notation \"wp_untag\" ident(t) :=\n  let tf := fresh \"tf\" in\n  let H := fresh \"H\" in\n  wp_untag_eq tf H; [\n    first [revert t tf H; intros _ t ->\n          |revert tf H; intros _ t ->\n          |revert tf H; intros t _]\n  | clear H].\n\nTactic Notation \"wp_is_key_eq\" ident(kt) ident(k) ident(H) :=\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' =>\n      first\n        [eapply (tac_wp_is_key _ _ K _ _);\n         [intros kt k H|intros H];\n         wp_finish\n        |fail 1 \"wp_untag_eq: Cannot decode\"])\n  end.\n", "meta": {"author": "arthuraa", "repo": "cryptis", "sha": "056d1fb93b8d8395b0c19639edb961d4919c63f6", "save_path": "github-repos/coq/arthuraa-cryptis", "path": "github-repos/coq/arthuraa-cryptis/cryptis-056d1fb93b8d8395b0c19639edb961d4919c63f6/tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2399622926687481}}
{"text": "Require Import Ensembles.\nRequire Import syntax.\nRequire Import infrastructure.\nRequire Import infrastructure_props.\nRequire Import analysis.\nRequire Import typings.\nRequire Import static.\nRequire Import List.\nRequire Import Arith.\nRequire Import tactics.\nRequire Import monad.\nRequire Import events.\nRequire Import Metatheory.\nRequire Import genericvalues.\nRequire Import alist.\nRequire Import Memory.\nRequire Import Integers.\nRequire Import Coqlib.\nRequire Import targetdata.\nRequire Import AST.\nRequire Import Maps.\nRequire Import maps_ext.\nRequire Import opsem.\nRequire Import vellvm_tactics.\nRequire Import util.\n\n(***********************************************************)\n(* This file proves the properties of operational semantics. *)\n\nModule OpsemProps. Section OpsemProps.\n\nExport Opsem.\n\n(***********************************************************)\n(* Properties of sop_star *)\n\nLemma sop_star_trans : forall cfg state1 state2 state3 tr12 tr23,\n  sop_star cfg state1 state2 tr12 ->\n  sop_star cfg state2 state3 tr23 ->\n  sop_star cfg state1 state3 (Eapp tr12 tr23).\nProof.\n  intros cfg state1 state2 state3 tr12 tr23 Hdsop12 Hdsop23.\n  generalize dependent state3.\n  generalize dependent tr23.\n  induction Hdsop12; intros; auto.\n    rewrite Eapp_assoc. eauto.\nQed.\n\n(***********************************************************)\n(* Properties of sop_plus *)\nLemma sop_plus__implies__sop_star : forall cfg state state' tr,\n  sop_plus cfg state state' tr ->\n  sop_star cfg state state' tr.\nProof.\n  intros cfg state state' tr Hdsop_plus.\n  inversion Hdsop_plus; subst; eauto.\nQed.\n\nHint Resolve sop_plus__implies__sop_star.\n\n(***********************************************************)\n(* Properties of sop_diverges *)\nLtac app_inv :=\n  match goal with\n  | [ H: ?f _ _ _ _ _ _ = ?f _ _ _ _ _ _ |- _ ] => inv H\n  | [ H: ?f _ _ _ _ _ = ?f _ _ _ _ _ |- _ ] => inv H\n  | [ H: ?f _ _ = ?f _ _ |- _ ] => inv H\n  end.\n\n(***********************************************************)\n(* Inversion of operations *)\nLemma BOP_inversion : forall TD lc gl b s v1 v2 gv2,\n  BOP TD lc gl b s v1 v2 = Some gv2 ->\n  exists gvs1, exists gvs2,\n    getOperandValue TD v1 lc gl = Some gvs1 /\\\n    getOperandValue TD v2 lc gl = Some gvs2 /\\\n    (mbop TD b s) gvs1 gvs2 = Some gv2.\nProof.\n  intros TD lc gl b s v1 v2 gv2 HBOP.\n  unfold BOP in HBOP.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HBOP].\n  remember (getOperandValue TD v2 lc gl) as ogv2.\n  destruct ogv2; inv HBOP.\n  eauto.\nQed.\n\nLemma FBOP_inversion : forall TD lc gl b fp v1 v2 gv,\n  FBOP TD lc gl b fp v1 v2 = Some gv ->\n  exists gv1, exists gv2,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    getOperandValue TD v2 lc gl = Some gv2 /\\\n    (mfbop TD b fp) gv1 gv2 = Some gv.\nProof.\n  intros TD lc gl b fp v1 v2 gv HFBOP.\n  unfold FBOP in HFBOP.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HFBOP].\n  remember (getOperandValue TD v2 lc gl) as ogv2.\n  destruct ogv2; inv HFBOP.\n  eauto.\nQed.\n\nLemma CAST_inversion : forall TD lc gl op t1 v1 t2 gv,\n  CAST TD lc gl op t1 v1 t2 = Some gv ->\n  exists gv1,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    (mcast TD op t1 t2) gv1 = Some gv.\nProof.\n  intros TD lc gl op t1 v1 t2 gv HCAST.\n  unfold CAST in HCAST.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; inv HCAST.\n  eauto.\nQed.\n\nLemma TRUNC_inversion : forall TD lc gl op t1 v1 t2 gv,\n  TRUNC TD lc gl op t1 v1 t2 = Some gv ->\n  exists gv1,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    (mtrunc TD op t1 t2) gv1 = Some gv.\nProof.\n  intros TD lc gl op t1 v1 t2 gv HTRUNC.\n  unfold TRUNC in HTRUNC.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; inv HTRUNC.\n  eauto.\nQed.\n\nLemma EXT_inversion : forall TD lc gl op t1 v1 t2 gv,\n  EXT TD lc gl op t1 v1 t2 = Some gv ->\n  exists gv1,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    (mext TD op t1 t2) gv1 = Some gv.\nProof.\n  intros TD lc gl op t1 v1 t2 gv HEXT.\n  unfold EXT in HEXT.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; inv HEXT.\n  eauto.\nQed.\n\nLemma ICMP_inversion : forall TD lc gl cond t v1 v2 gv,\n  ICMP TD lc gl cond t v1 v2 = Some gv ->\n  exists gv1, exists gv2,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    getOperandValue TD v2 lc gl = Some gv2 /\\\n    (micmp TD cond t) gv1 gv2 = Some gv.\nProof.\n  intros TD lc gl cond0 t v1 v2 gv HICMP.\n  unfold ICMP in HICMP.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HICMP].\n  remember (getOperandValue TD v2 lc gl) as ogv2.\n  destruct ogv2; inv HICMP.\n  eauto.\nQed.\n\nLemma FCMP_inversion : forall TD lc gl cond fp v1 v2 gv,\n  FCMP TD lc gl cond fp v1 v2 = Some gv ->\n  exists gv1, exists gv2,\n    getOperandValue TD v1 lc gl = Some gv1 /\\\n    getOperandValue TD v2 lc gl = Some gv2 /\\\n    (mfcmp TD cond fp) gv1 gv2 = Some gv.\nProof.\n  intros TD lc gl cond0 fp v1 v2 gv HFCMP.\n  unfold FCMP in HFCMP.\n  remember (getOperandValue TD v1 lc gl) as ogv1.\n  destruct ogv1; try solve [inversion HFCMP].\n  remember (getOperandValue TD v2 lc gl) as ogv2.\n  destruct ogv2; inv HFCMP.\n  eauto.\nQed.\n\n(***********************************************************)\n(* Equivalence of operations *)\nLemma const2GV_eqAL : forall c gl1 gl2 TD,\n  eqAL _ gl1 gl2 ->\n  const2GV TD gl1 c = const2GV TD gl2 c.\nProof.\n  intros. unfold const2GV.\n  destruct const2GV_eqAL_aux.\n  erewrite H0; eauto.\nQed.\n\nLemma getOperandValue_eqAL : forall lc1 gl lc2 v TD,\n  eqAL _ lc1 lc2 ->\n  getOperandValue TD v lc1 gl = getOperandValue TD v lc2 gl.\nProof.\n  intros lc1 gl lc2 v TD HeqAL.\n  unfold getOperandValue in *.\n  destruct v; auto.\nQed.\n\nLemma BOP_eqAL : forall lc1 gl lc2 bop0 sz0 v1 v2 TD,\n  eqAL _ lc1 lc2 ->\n  BOP TD lc1 gl bop0 sz0 v1 v2 = BOP TD lc2 gl bop0 sz0 v1 v2.\nProof.\n  intros lc1 gl lc2 bop0 sz0 v1 v2 TD HeqEnv.\n  unfold BOP in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v2); auto.\nQed.\n\nLemma FBOP_eqAL : forall lc1 gl lc2 fbop0 fp0 v1 v2 TD,\n  eqAL _ lc1 lc2 ->\n  FBOP TD lc1 gl fbop0 fp0 v1 v2 = FBOP TD lc2 gl fbop0 fp0 v1 v2.\nProof.\n  intros lc1 gl lc2 fbop0 fp0 v1 v2 TD HeqEnv.\n  unfold FBOP in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v2); auto.\nQed.\n\nLemma CAST_eqAL : forall lc1 gl lc2 op t1 v1 t2 TD,\n  eqAL _ lc1 lc2 ->\n  CAST TD lc1 gl op t1 v1 t2 = CAST TD lc2 gl op t1 v1 t2.\nProof.\n  intros lc1 gl lc2 op t1 v1 t2 TD HeqAL.\n  unfold CAST in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\nQed.\n\nLemma TRUNC_eqAL : forall lc1 gl lc2 op t1 v1 t2 TD,\n  eqAL _ lc1 lc2 ->\n  TRUNC TD lc1 gl op t1 v1 t2 = TRUNC TD lc2 gl op t1 v1 t2.\nProof.\n  intros lc1 gl lc2 op t1 v1 t2 TD HeqAL.\n  unfold TRUNC in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\nQed.\n\nLemma EXT_eqAL : forall lc1 gl lc2 op t1 v1 t2 TD,\n  eqAL _ lc1 lc2 ->\n  EXT TD lc1 gl op t1 v1 t2 = EXT TD lc2 gl op t1 v1 t2.\nProof.\n  intros lc1 gl lc2 op t1 v1 t2 TD HeqAL.\n  unfold EXT in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\nQed.\n\nLemma ICMP_eqAL : forall lc1 gl lc2 cond t v1 v2 TD,\n  eqAL _ lc1 lc2 ->\n  ICMP TD lc1 gl cond t v1 v2 = ICMP TD lc2 gl cond t v1 v2.\nProof.\n  intros lc1 gl lc2 cond0 t v1 v2 TD HeqAL.\n  unfold ICMP in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v2); auto.\nQed.\n\nLemma FCMP_eqAL : forall lc1 gl lc2 cond fp v1 v2 TD,\n  eqAL _ lc1 lc2 ->\n  FCMP TD lc1 gl cond fp v1 v2 = FCMP TD lc2 gl cond fp v1 v2.\nProof.\n  intros lc1 gl lc2 cond0 fp v1 v2 TD HeqAL.\n  unfold FCMP in *.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v1); auto.\n  rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v2); auto.\nQed.\n\nLemma values2GVs_eqAL : forall l0 lc1 gl lc2 TD,\n  eqAL _ lc1 lc2 ->\n  values2GVs TD l0 lc1 gl = values2GVs TD l0 lc2 gl.\nProof.\n  induction l0 as [|[s v] l0]; intros lc1 gl lc2 TD HeqAL; simpl; auto.\n    rewrite getOperandValue_eqAL with (lc2:=lc2)(v:=v); auto.\n    erewrite IHl0; eauto.\nQed.\n\n(***********************************************************)\n(* Uniqueness of operations *)\nLemma updateValuesForNewBlock_spec4 : forall rs lc id1 gv,\n  lookupAL _ rs id1 = Some gv ->\n  lookupAL _ (updateValuesForNewBlock rs lc) id1 = Some gv.\nProof.\n  induction rs; intros; simpl in *.\n    inversion H.\n\n    destruct a.\n    destruct (id1==a); subst.\n      inversion H; subst. apply lookupAL_updateAddAL_eq; auto.\n      rewrite <- lookupAL_updateAddAL_neq; auto.\nQed.\n\n(***********************************************************)\n(* Properties of initLocals and initializeFrameValues *)\nLemma initLocals_spec : forall TD la gvs id1 lc,\n  In id1 (getArgsIDs la) ->\n  initLocals TD la gvs = Some lc ->\n  exists gv, lookupAL _ lc id1 = Some gv.\nProof.\n  unfold initLocals.\n  induction la; intros; simpl in *.\n    inversion H.\n\n    destruct a as [[t c] id0].\n    simpl in H.\n    destruct H as [H | H]; subst; simpl.\n      destruct gvs.\n        remember (_initializeFrameValues TD la nil nil) as R1.\n        destruct R1; tinv H0.\n        remember (gundef TD t) as R2.\n        destruct R2; inv H0.\n        eauto using lookupAL_updateAddAL_eq.\n\n        remember (_initializeFrameValues TD la gvs nil) as R1.\n        destruct R1; tinv H0.\n        destruct ((fit_gv TD t) g); inv H0.\n        eauto using lookupAL_updateAddAL_eq.\n\n      destruct (eq_atom_dec id0 id1); subst.\n        destruct gvs.\n          remember (_initializeFrameValues TD la nil nil) as R1.\n          destruct R1; tinv H0.\n          remember (gundef TD t) as R2.\n          destruct R2; inv H0.\n          eauto using lookupAL_updateAddAL_eq.\n\n          remember (_initializeFrameValues TD la gvs nil) as R1.\n          destruct R1; tinv H0.\n          destruct ((fit_gv TD t) g); inv H0.\n          eauto using lookupAL_updateAddAL_eq.\n\n        destruct gvs.\n          remember (_initializeFrameValues TD la nil nil) as R1.\n          destruct R1; tinv H0.\n          remember (gundef TD t) as R2.\n          destruct R2; inv H0.\n          symmetry in HeqR1.\n          eapply IHla in HeqR1; eauto.\n          destruct HeqR1 as [gv HeqR1].\n          rewrite <- lookupAL_updateAddAL_neq; eauto.\n\n          remember (_initializeFrameValues TD la gvs nil) as R1.\n          destruct R1; tinv H0.\n          destruct ((fit_gv TD t) g); inv H0.\n          symmetry in HeqR1.\n          eapply IHla in HeqR1; eauto.\n          destruct HeqR1 as [gv HeqR1].\n          rewrite <- lookupAL_updateAddAL_neq; eauto.\nQed.\n\n(***********************************************************)\n(* Properties of updateValuesForNewBlock *)\nLemma updateValuesForNewBlock_spec6 : forall lc rs id1 gvs\n  (Hlk : lookupAL _ (updateValuesForNewBlock rs lc) id1 = ret gvs)\n  (Hin : id1 `in` (dom rs)),\n  lookupAL _ rs id1 = Some gvs.\nProof.\n  induction rs; simpl; intros.\n    fsetdec.\n\n    destruct a.\n    assert (id1 = i0 \\/ id1 `in` dom rs) as J. fsetdec.\n    destruct J as [J | J]; subst.\n      rewrite lookupAL_updateAddAL_eq in Hlk; auto. inv Hlk.\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i0 i0); auto.\n        contradict n; auto.\n\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id1 i0);\n        subst; eauto.\n        rewrite lookupAL_updateAddAL_eq in Hlk; auto.\n        rewrite <- lookupAL_updateAddAL_neq in Hlk; eauto.\nQed.\n\nLemma updateValuesForNewBlock_spec7 : forall lc rs id1 gvs\n  (Hlk : lookupAL _ (updateValuesForNewBlock rs lc) id1 = ret gvs)\n  (Hnotin : id1 `notin` (dom rs)),\n  lookupAL _ lc id1 = ret gvs.\nProof.\n  induction rs; simpl; intros; auto.\n    destruct a.\n\n    destruct_notin.\n    rewrite <- lookupAL_updateAddAL_neq in Hlk; eauto.\nQed.\n\nLemma updateValuesForNewBlock_spec6' : forall lc rs id1\n  (Hin : id1 `in` (dom rs)),\n  lookupAL _ (updateValuesForNewBlock rs lc) id1 = lookupAL _ rs id1.\nProof.\n  induction rs; simpl; intros.\n    fsetdec.\n\n    destruct a.\n    assert (id1 = a \\/ id1 `in` dom rs) as J. fsetdec.\n    destruct J as [J | J]; subst.\n      rewrite lookupAL_updateAddAL_eq.\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) a a); auto.\n        contradict n; auto.\n\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id1 a);\n        subst; eauto.\n        rewrite lookupAL_updateAddAL_eq; auto.\n        rewrite <- lookupAL_updateAddAL_neq; eauto.\nQed.\n\nLemma updateValuesForNewBlock_spec7' : forall lc rs id1\n  (Hin : id1 `notin` (dom rs)),\n  lookupAL _ (updateValuesForNewBlock rs lc) id1 = lookupAL _ lc id1.\nProof.\n  induction rs; simpl; intros; auto.\n    destruct a. destruct_notin.\n    rewrite <- lookupAL_updateAddAL_neq; eauto.\nQed.\n\nLemma updateValuesForNewBlock_spec5: forall lc1' lc2' i0\n  (Hlk: lookupAL _ lc1' i0 = lookupAL _ lc2' i0) lc2\n  (Hlk: merror = lookupAL _ lc2 i0),\n  lookupAL _ lc1' i0 =\n    lookupAL _ (Opsem.updateValuesForNewBlock lc2 lc2') i0.\nProof.\n  induction lc2 as [|[]]; simpl; intros; auto.\n    destruct (i0 == a); try congruence.\n    rewrite <- lookupAL_updateAddAL_neq; auto.\nQed.\n\n(***********************************************************)\n(* Properties of getIncomingValuesForBlockFromPHINodes *)\nLemma getIncomingValuesForBlockFromPHINodes_spec6 : forall TD b gl lc ps' rs id1\n  (HeqR1 : ret rs = getIncomingValuesForBlockFromPHINodes TD ps' b gl lc)\n  (Hin : In id1 (getPhiNodesIDs ps')),\n  id1 `in` dom rs.\nProof.\n  induction ps'; simpl; intros.\n    inv Hin.\n\n    destruct a. destruct b. simpl in *.\n    inv_mbind. inv HeqR1.\n    destruct (gv_chunks_match_typb TD g typ5).\n    destruct Hin as [Hin | Hin]; subst. inv H0. simpl. auto.\n    inv H0. simpl. auto.\n    inv H0.\nQed.\n\nLemma getIncomingValuesForBlockFromPHINodes_spec7 : forall TD b gl lc ps' rs id1\n  (HeqR1 : ret rs = getIncomingValuesForBlockFromPHINodes TD ps' b gl lc)\n  (Hin : id1 `in` dom rs),\n  In id1 (getPhiNodesIDs ps').\nProof.\n  induction ps'; simpl; intros.\n    inv HeqR1. fsetdec.\n\n    destruct a as [i0 ?]. destruct b as [l2 ? ? ?]. simpl in *.\n    inv_mbind. inv HeqR1. simpl in *.\n    assert (id1 = i0 \\/ id1 `in` dom l1) as J.\n    destruct (gv_chunks_match_typb TD g typ5).\n    inv H0. simpl in Hin.\n    fsetdec.\n    inv H0.\n    destruct J as [J | J]; subst; eauto.\nQed.\n\nLemma getIncomingValuesForBlockFromPHINodes_spec8 : forall TD b gl lc ps' rs id1\n  (HeqR1 : ret rs = getIncomingValuesForBlockFromPHINodes TD ps' b gl lc)\n  (Hnotin : ~ In id1 (getPhiNodesIDs ps')),\n  id1 `notin` dom rs.\nProof.\n  intros.\n  intro J. apply Hnotin.\n  eapply getIncomingValuesForBlockFromPHINodes_spec7 in HeqR1; eauto.\nQed.\n\nLemma getIncomingValuesForBlockFromPHINodes_spec9: forall TD gl lc b id0 gvs0\n  ps' l0,\n  ret l0 = Opsem.getIncomingValuesForBlockFromPHINodes TD ps' b gl lc ->\n  id0 `in` dom l0 ->\n  lookupAL _ l0 id0 = ret gvs0 ->\n  exists id1, exists t1, exists vls1, exists v, exists n,\n    In (insn_phi id1 t1 vls1) ps' /\\\n    nth_error vls1 n = Some (v, getBlockLabel b) /\\\n    Opsem.getOperandValue TD v lc gl= Some gvs0.\nProof.\n  induction ps' as [|[i0 t l0]]; simpl; intros.\n    inv H. fsetdec.\n\n    inv_mbind. simpl in *.\n    destruct (id0 == i0); subst.\n      destruct b. simpl in *.\n      symmetry in HeqR.\n      apply getValueViaLabelFromValuels__nth_list_value_l in HeqR; auto.\n      destruct HeqR as [n HeqR].\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i0 i0);\n        try congruence.\n      destruct (gv_chunks_match_typb TD g t).\n      inv H3.\n      \n      exists i0. exists t. exists l0. exists v. exists n.\n      split; auto. split. auto. auto. simpl in H1.\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i0 i0).\n      inv H1. eauto. apply n0 in e. inv e.\n      inv H3.\n      destruct (gv_chunks_match_typb TD g t).\n      inv H3. simpl in H1.\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id0 i0).\n      apply n in e. inv e.\n      apply IHps' in H1; auto; try fsetdec.\n      destruct H1 as [id1 [t1 [vls1 [v' [n' [J1 [J2 J3]]]]]]].\n      exists id1. exists t1. exists vls1. exists v'. exists n'.\n      split; auto.\n      apply in_dom_cons_inv in H0.\n      inv H0. assert (i0 = i0). auto. apply n in H. inv H.\n      auto.\n      inv H3.\nQed.\n\nLemma getIncomingValuesForBlockFromPHINodes_spec9': forall TD gl lc b id0 gvs0\n  ps' l0,\n  ret l0 = Opsem.getIncomingValuesForBlockFromPHINodes TD ps' b gl lc ->\n  id0 `in` dom l0 ->\n  lookupAL _ l0 id0 = ret gvs0 ->\n  exists t1, exists vls1, exists v, \n    In (insn_phi id0 t1 vls1) ps' /\\\n    getValueViaLabelFromValuels vls1 (getBlockLabel b) = Some v /\\\n    Opsem.getOperandValue TD v lc gl= Some gvs0.\nProof.\n  induction ps' as [|[i0 t l0]]; simpl; intros.\n    inv H. fsetdec.\n\n    inv_mbind. simpl in *.\n    destruct (id0 == i0); subst.\n      destruct b. simpl in *.\n      symmetry in HeqR.\n      inv H1.\n      destruct (gv_chunks_match_typb TD g t).\n      inv H3.\n      exists t. exists l0. exists v. \n      simpl in H2.\n      inv H2. split; auto. split. auto. simpl.\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i0 i0).\n      auto. assert (i0 = i0). auto. apply n in H. inv H.\n      inv H3.\n      \n      destruct (gv_chunks_match_typb TD g t).\n      inv H3. simpl in H1.\n      destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id0 i0).\n      apply n in e. inv e.\n\n      apply IHps' in H1; auto; try fsetdec.\n      destruct H1 as [t1 [vls1 [v' [J1 [J2 J3]]]]].\n      exists t1. exists vls1. exists v'.\n      split; auto.\n      apply in_dom_cons_inv in H0.\n      inv H0. assert (i0 = i0). auto. apply n in H. inv H.\n      auto.\n      inv H3.\nQed.\n\nEnd OpsemProps. End OpsemProps.\n", "meta": {"author": "snu-sf", "repo": "crellvm-vellvm", "sha": "54c7cc88ab5b4aec4c327f501cac4d9a667ca057", "save_path": "github-repos/coq/snu-sf-crellvm-vellvm", "path": "github-repos/coq/snu-sf-crellvm-vellvm/crellvm-vellvm-54c7cc88ab5b4aec4c327f501cac4d9a667ca057/src/Vellvm/opsem_props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.23996228695029526}}
{"text": "(*\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\nRequire Import String.\nRequire Import List.\nRequire Import Arith.\nRequire Import Program.\nRequire Import EquivDec.\nRequire Import Morphisms.\nRequire Import Utils.\nRequire Import DataSystem.\nRequire Import OQL.\n  \nSection TOQL.\n  (** Typing for CAMP *)\n\n  Section typ.\n  \n    Context {m:basic_model}.\n    Section constt.\n      Context (τconstants:tbindings).\n\n      Hint Resolve bindings_type_has_type : qcert.\n\n      Inductive oql_expr_type : tbindings -> oql_expr -> rtype -> Prop :=\n      | OTConst {τ} tenv c :\n          data_type (normalize_data brand_relation_brands c) τ ->\n          oql_expr_type tenv (OConst c) τ\n      | OTVar {τ} tenv v :\n          edot tenv v = Some τ -> oql_expr_type tenv (OVar v) τ\n      | OTTable {τ} tenv s :\n          tdot τconstants s = Some τ ->\n          oql_expr_type tenv (OTable s) τ\n      | OTBinop {τ₁ τ₂ τout} tenv b e₁ e₂ :\n          oql_expr_type tenv e₁ τ₁ ->\n          oql_expr_type tenv e₂ τ₂ ->\n          binary_op_type b τ₁ τ₂ τout ->\n          oql_expr_type tenv (OBinop b e₁ e₂) τout\n      | OTUnop {τ₁ τout} tenv u e₁ :\n          oql_expr_type tenv e₁ τ₁ ->\n          unary_op_type u τ₁ τout ->\n          oql_expr_type tenv (OUnop u e₁) τout.\n\n    End constt.\n    \n    Context (τconstants:tbindings).\n\n    Inductive oql_query_program_type : tbindings -> tbindings -> oql_query_program -> rtype -> Prop :=\n    | OTDefineQuery {tenv s e rest τ}  {tdefls τ₁} :\n        oql_expr_type (rec_concat_sort τconstants tdefls) tenv e τ₁ ->\n        oql_query_program_type (rec_concat_sort tdefls ((s,τ₁)::nil)) tenv rest τ ->\n        oql_query_program_type tdefls tenv (ODefineQuery s e rest) τ\n    | OTUndefineQuery {tenv s rest tdefls τ} :\n        oql_query_program_type (rremove tdefls s) tenv rest τ ->\n        oql_query_program_type tdefls tenv (OUndefineQuery s rest) τ\n    |OTQuery {tdefls tenv e τ}:\n     oql_expr_type (rec_concat_sort τconstants tdefls) tenv e τ ->\n     oql_query_program_type tdefls tenv (OQuery e) τ.\n\n    Definition oql_type (o:oql_query_program) (τ:rtype) : Prop\n      := oql_query_program_type nil nil o τ.\n    \n    End typ.\n\n  Theorem typed_oql_expr_yields_typed_data {m:basic_model} {τc} {τenv τout} c (env:list (string*data)) (q:oql_expr):\n    bindings_type c τc ->\n    bindings_type env τenv ->\n    (oql_expr_type τc τenv q τout) ->\n    (exists x, (oql_expr_interp brand_relation_brands c q env = Some x /\\ (x ▹ τout))).\n  Proof.\n    intros.\n    revert c env H H0.\n    dependent induction H1; simpl; intros.\n    - exists (normalize_data brand_relation_brands c).\n      split; [reflexivity|assumption].\n    - unfold bindings_type in H1.\n      apply (Forall2_lookupr_some H1).\n      assumption.\n    - unfold bindings_type in H0.\n      apply (Forall2_lookupr_some H0).\n      assumption.\n    - elim (IHoql_expr_type1 _ _ H0 H1); intros.\n      elim (IHoql_expr_type2 _ _ H0 H1); intros.\n      elim H2; clear H2; intros.\n      elim H3; clear H3; intros.\n      rewrite H2; rewrite H3; simpl.\n      destruct (typed_binary_op_yields_typed_data _ _ _ H4 H5 H) as [?[??]].\n      rewrite H6.\n      exists x1; auto.\n    - elim (IHoql_expr_type _ _ H0 H2); intros.\n      elim H3; clear H3; intros.\n      rewrite H3; simpl.\n      destruct (typed_unary_op_yields_typed_data _ _ H4 H) as [?[??]].\n      rewrite H5.\n      exists x0; auto.\n  Qed.\n\n  Lemma typed_oql_query_program_yields_typed_data {m:basic_model} {τc τdefls} {τenv τout} c (defls env:list (string*data)) (q:oql_query_program):\n    bindings_type c τc ->\n    bindings_type defls τdefls ->\n    bindings_type env τenv ->\n    (oql_query_program_type τc τdefls τenv q τout) ->\n    (exists x, (oql_query_program_interp brand_relation_brands c defls q env = Some x /\\ (x ▹ τout))).\n  Proof.\n    intros.\n    revert c defls env H H0 H1.\n    dependent induction H2; simpl; intros.\n    - assert (bt: bindings_type (rec_concat_sort c defls) (rec_concat_sort τc tdefls))\n        by (apply bindings_type_rec_concat_sort; trivial).\n      destruct (typed_oql_expr_yields_typed_data _ _ e bt H3 H)\n        as [d [de dt]].\n      rewrite de; simpl.\n      destruct (IHoql_query_program_type _ (rec_concat_sort defls ((s,d)::nil)) env H0);\n        eauto 2.\n      apply bindings_type_rec_concat_sort; trivial.\n      constructor; simpl; auto.\n    - destruct (IHoql_query_program_type c (rremove defls s) env); eauto 2.\n      apply rremove_well_typed.\n      trivial.\n    - eapply typed_oql_expr_yields_typed_data; eauto.\n      apply bindings_type_rec_concat_sort; trivial.\n  Qed.\n\n    (** Main typing soundness theorem for OQL *)\n\n  Theorem typed_oql_yields_typed_data {m:basic_model} {τc} {τout} c (q:oql_query_program):\n    bindings_type c τc ->\n    oql_type τc q τout ->\n    (exists x, (oql_interp brand_relation_brands c q = Some x /\\ (x ▹ τout))).\n  Proof.\n    intros.\n    eapply typed_oql_query_program_yields_typed_data; eauto\n    ; constructor.\n  Qed.\n  \nEnd TOQL.\n\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/OQL/Typing/TOQL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23996228695029526}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\n\nRequire Import CommonTheorems.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import CroniesTermInterface.\n\nSection CroniesTermProof.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n\n  Ltac update_destruct :=\n    match goal with\n      | [ |- context [ update _ ?y _ ?x ] ] => destruct (@name_eq_dec _ _ y x)\n    end.\n\n  Lemma handleClientRequest_spec :\n    forall h st client id c out st' l,\n      handleClientRequest h st client id c = (out, st', l) ->\n      currentTerm st' = currentTerm st.\n  Proof using. \n    intros. unfold handleClientRequest in *.\n    break_match; find_inversion; intuition.\n  Qed.\n\n  Lemma cronies_term_client_request :\n    refined_raft_net_invariant_client_request cronies_term.\n  Proof using. \n    unfold refined_raft_net_invariant_client_request, cronies_term,\n    update_elections_data_client_request in *.\n    intros. subst. simpl in *. repeat find_higher_order_rewrite.\n    update_destruct; subst; rewrite_update; eauto.\n    simpl in *. find_apply_lem_hyp handleClientRequest_spec.\n    repeat find_rewrite.\n    repeat break_match; simpl in *; eauto.\n  Qed.\n  (*   H : handleTimeout h' (snd (nwState net h')) = (out, d, l)\n       In h0 (cronies (update_elections_data_timeout h' (nwState net h')) t)\n   *)\n\n  Lemma handleTimeout_spec :\n    forall h st out st' l t h',\n      handleTimeout h (snd st) = (out, st', l) ->\n      In h' (cronies (update_elections_data_timeout h st) t) ->\n      (currentTerm (snd st) <= currentTerm st' /\\\n       (In h' (cronies (fst st) t) \\/\n        t = currentTerm st')).\n  Proof using. \n    intros.\n    unfold handleTimeout, tryToBecomeLeader, update_elections_data_timeout in *.\n    repeat (break_match; repeat find_inversion; simpl in *; auto);\n      intuition;\n      unfold handleTimeout, tryToBecomeLeader in *;\n      repeat (break_match; repeat find_inversion; simpl in *; auto); congruence.\n  Qed.\n\n\n  Lemma cronies_term_timeout :\n    refined_raft_net_invariant_timeout cronies_term.\n  Proof using. \n    unfold refined_raft_net_invariant_timeout, cronies_term.\n    intros. subst. simpl in *. repeat find_higher_order_rewrite.\n    update_destruct; subst; rewrite_update; eauto.\n    simpl in *.\n    find_eapply_lem_hyp handleTimeout_spec; eauto. intuition.\n    eapply le_trans; [|eauto]; eauto.\n  Qed.\n\n  Lemma doLeader_spec :\n    forall st h os st' ms,\n      doLeader st h = (os, st', ms) ->\n      currentTerm st' = currentTerm st.\n  Proof using. \n    intros. unfold doLeader in *.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma cronies_term_do_leader :\n    refined_raft_net_invariant_do_leader cronies_term.\n  Proof using. \n    unfold refined_raft_net_invariant_do_leader, cronies_term.\n    intros. subst. simpl in *. repeat find_higher_order_rewrite.\n    update_destruct; subst; rewrite_update; eauto.\n    simpl in *.\n    find_apply_lem_hyp doLeader_spec.\n    repeat find_rewrite.\n    match goal with\n      | H : nwState ?net ?h = (?g, ?st) |- _ =>\n        replace g with (fst (nwState net h)) in *; [|rewrite H; auto];\n        replace st with (snd (nwState net h)) in *; [|rewrite H; auto]\n    end; eauto.\n  Qed.\n\n  Lemma doGenericServer_spec :\n    forall st h os st' ms,\n      doGenericServer h st = (os, st', ms) ->\n      currentTerm st' = currentTerm st.\n  Proof using. \n    intros. unfold doGenericServer in *.\n    repeat break_match; repeat find_inversion;\n    use_applyEntries_spec; subst; simpl in *;\n    auto.\n  Qed.\n\n  Lemma cronies_term_do_generic_server :\n    refined_raft_net_invariant_do_generic_server cronies_term.\n  Proof using. \n    unfold refined_raft_net_invariant_do_generic_server, cronies_term.\n    intros. subst. simpl in *. repeat find_higher_order_rewrite.\n    update_destruct; subst; rewrite_update; eauto.\n    simpl in *.\n    find_apply_lem_hyp doGenericServer_spec.\n    repeat find_rewrite.\n    match goal with\n      | H : nwState ?net ?h = (?g, ?st) |- _ =>\n        replace g with (fst (nwState net h)) in *; [|rewrite H; auto];\n        replace st with (snd (nwState net h)) in *; [|rewrite H; auto]\n    end; eauto.\n  Qed.\n\n  Lemma handleAppendEntries_spec :\n    forall h st t n pli plt es ci st' m,\n      handleAppendEntries h st t n pli plt es ci = (st', m) ->\n      currentTerm st <= currentTerm st'.\n  Proof using. \n    intros.\n    unfold handleAppendEntries, advanceCurrentTerm in *.\n    repeat break_match; find_inversion; simpl in *;\n    do_bool; auto.\n  Qed.\n\n  Lemma update_elections_data_appendEntries_spec :\n    forall h st t n pli plt es ci st' e t',\n      update_elections_data_appendEntries h st t n pli plt es ci = st' ->\n      In e (cronies st' t') ->\n      In e (cronies (fst st) t').\n  Proof using. \n    intros.\n    unfold update_elections_data_appendEntries in *.\n    repeat break_match; repeat find_rewrite; subst; simpl in *; auto.\n  Qed.\n\n  Lemma cronies_term_append_entries :\n    refined_raft_net_invariant_append_entries cronies_term.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries, cronies_term.\n    intros. subst. simpl in *. repeat find_higher_order_rewrite.\n    update_destruct; subst; rewrite_update; eauto.\n    simpl in *.\n    find_apply_lem_hyp handleAppendEntries_spec.\n    find_eapply_lem_hyp update_elections_data_appendEntries_spec; eauto.\n    eapply le_trans; [|eauto]; eauto.\n  Qed.\n\n  Lemma handleAppendEntriesReply_spec :\n    forall h st h' t es r st' ms,\n      handleAppendEntriesReply h st h' t es r = (st', ms) ->\n      currentTerm st <= currentTerm st'.\n  Proof using. \n    intros.\n    unfold handleAppendEntriesReply, advanceCurrentTerm in *.\n    repeat break_match; try find_inversion; subst; simpl in *;\n    do_bool; intuition.\n  Qed.\n\n\n  Lemma cronies_term_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply cronies_term.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries_reply, cronies_term.\n    intros. subst. simpl in *. repeat find_higher_order_rewrite.\n    update_destruct; subst; rewrite_update; eauto.\n    simpl in *.\n    find_apply_lem_hyp handleAppendEntriesReply_spec.\n    eapply le_trans; [|eauto]; eauto.\n  Qed.\n\n  Lemma handleRequestVote_spec :\n    forall h st t h' pli plt st' m,\n      handleRequestVote h st t h' pli plt = (st', m) ->\n      currentTerm st <= currentTerm st'.\n  Proof using. \n    intros.\n    unfold handleRequestVote, advanceCurrentTerm in *.\n    repeat break_match; try find_inversion; subst; simpl in *;\n    do_bool; intuition.\n  Qed.\n\n  Lemma update_elections_data_requestVote_spec :\n    forall h st t h' pli plt st' t' e s,\n      update_elections_data_requestVote h h' t pli plt s st = st' ->\n      In e (cronies st' t') ->\n      In e (cronies (fst st) t').\n  Proof using. \n    intros.\n    unfold update_elections_data_requestVote in *.\n    repeat break_match; repeat find_rewrite; subst; simpl in *; auto.\n  Qed.\n\n  Lemma cronies_term_request_vote :\n    refined_raft_net_invariant_request_vote cronies_term.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote, cronies_term.\n    intros. subst. simpl in *. repeat find_higher_order_rewrite.\n    update_destruct; subst; rewrite_update; eauto.\n    simpl in *.\n    find_apply_lem_hyp handleRequestVote_spec.\n    find_eapply_lem_hyp update_elections_data_requestVote_spec; eauto.\n    eapply le_trans; [|eauto]; eauto.\n  Qed.\n\n\n  Lemma handleRequestVoteReply_spec :\n    forall h st h' t v st',\n      st' = handleRequestVoteReply h st h' t v ->\n      currentTerm st' = currentTerm st \\/\n      (currentTerm st <= currentTerm st' /\\\n       type st' = Follower).\n  Proof using. \n    intros.\n    unfold handleRequestVoteReply, advanceCurrentTerm in *.\n    repeat break_match; try find_inversion; subst; simpl in *; intuition;\n    do_bool; intuition.\n  Qed.\n\n\n  Lemma cronies_term_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply cronies_term.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote_reply, cronies_term.\n    intros. subst. simpl in *. repeat find_higher_order_rewrite.\n    update_destruct; subst; rewrite_update; eauto.\n    simpl in *.\n    match goal with\n      | H : forall _, st' _ = _ |- _ => clear H\n    end.\n    unfold update_elections_data_requestVoteReply in *.\n    match goal with\n      | |- context [handleRequestVoteReply ?h ?st ?h' ?t ?v] =>\n        remember (handleRequestVoteReply h st h' t v) as new_state\n    end.\n    find_copy_apply_lem_hyp handleRequestVoteReply_spec.\n    intuition.\n    - unfold update_elections_data_requestVoteReply in *.\n      break_match; simpl in *; repeat find_rewrite; eauto;\n      break_match; eauto;\n      subst; repeat find_reverse_rewrite; intuition.\n    - unfold update_elections_data_requestVoteReply in *.\n      break_match; simpl in *;\n      try solve [subst; unfold raft_data in *; congruence].\n      eapply le_trans; [|eauto]; eauto.\n  Qed.\n\n  Lemma cronies_term_init :\n    refined_raft_net_invariant_init cronies_term.\n  Proof using. \n    unfold refined_raft_net_invariant_init, cronies_term.\n    intros. simpl in *. intuition.\n  Qed.\n\n  Lemma cronies_term_reboot :\n    refined_raft_net_invariant_reboot cronies_term.\n  Proof using. \n    unfold refined_raft_net_invariant_reboot, cronies_term, reboot.\n    intros. simpl in *. repeat find_higher_order_rewrite.\n    update_destruct; subst; rewrite_update; eauto.\n    simpl in *.\n     match goal with\n      | H : nwState ?net ?h = (?g, ?st) |- _ =>\n        replace g with (fst (nwState net h)) in *; [|rewrite H; auto];\n        replace st with (snd (nwState net h)) in *; [|rewrite H; auto]\n     end; eauto.\n  Qed.\n\n  Lemma cronies_term_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset cronies_term.\n  Proof using. \n    unfold refined_raft_net_invariant_state_same_packet_subset, cronies_term.\n    intros.\n    repeat find_reverse_higher_order_rewrite. eauto.\n  Qed.\n\n  Theorem cronies_term_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      cronies_term net.\n  Proof using rri. \n    intros. apply refined_raft_net_invariant; auto.\n    - apply cronies_term_init.\n    - apply cronies_term_client_request.\n    - apply cronies_term_timeout.\n    - apply cronies_term_append_entries.\n    - apply cronies_term_append_entries_reply.\n    - apply cronies_term_request_vote.\n    - apply cronies_term_request_vote_reply.\n    - apply cronies_term_do_leader.\n    - apply cronies_term_do_generic_server.\n    - apply cronies_term_state_same_packet_subset.\n    - apply cronies_term_reboot.\n  Qed.\n\n  Instance cti : cronies_term_interface.\n  Proof.\n    split.\n    auto using cronies_term_invariant.\n  Qed.\nEnd CroniesTermProof.", "meta": {"author": "ahmet-celik", "repo": "pverdi", "sha": "dc88c4a5fd7d90b5bb48e583bd8286097f983f81", "save_path": "github-repos/coq/ahmet-celik-pverdi", "path": "github-repos/coq/ahmet-celik-pverdi/pverdi-dc88c4a5fd7d90b5bb48e583bd8286097f983f81/raft-proofs/CroniesTermProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23996228695029526}}
{"text": "Require Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.InlineConstAndOpByRewriteInterp.\nRequire Import Crypto.Compilers.Z.Syntax.\nRequire Import Crypto.Compilers.Z.InlineConstAndOpByRewrite.\n\nModule Export Rewrite.\n  Definition InterpInlineConstAndOp {t} (e : Expr t)\n  : forall x, Interp (InlineConstAndOp e) x = Interp e x\n    := @InterpInlineConstAndOp _ _ _ _ _ t e Syntax.Util.make_const_correct.\n\n  Hint Rewrite @InterpInlineConstAndOp : reflective_interp.\nEnd Rewrite.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Compilers/Z/InlineConstAndOpByRewriteInterp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.23988794777431952}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Termes.\nRequire Import Conv.\nRequire Import Ered.\nRequire Export MyList.\nRequire Import Types.\n\n \nSection Typage.\n\n  Inductive Ewf : env -> Prop :=\n    | Ewf_nil : Ewf nil\n    | Ewf_var :\n        forall (e : env) (T : term) (s : sort),\n        Etyp e T (Srt s) -> Ewf (T :: e)\nwith Etyp : env -> term -> term -> Prop :=\n  | Etype_prop : forall e : env, Ewf e -> Etyp e (Srt prop) (Srt kind)\n  | Etype_set : forall e : env, Ewf e -> Etyp e (Srt set) (Srt kind)\n  | Etype_var :\n      forall e : env,\n      Ewf e ->\n      forall (v : nat) (t : term), item_lift t e v -> Etyp e (Ref v) t\n  | Etype_abs :\n      forall (e : env) (T : term) (s1 : sort),\n      Etyp e T (Srt s1) ->\n      forall (M U : term) (s2 : sort),\n      Etyp (T :: e) U (Srt s2) ->\n      Etyp (T :: e) M U -> Etyp e (Abs T M) (Prod T U)\n  | Etype_app :\n      forall (e : env) (v V : term),\n      Etyp e v V ->\n      forall u Ur : term,\n      Etyp e u (Prod V Ur) -> Etyp e (App u v) (subst v Ur)\n  | Etype_prod :\n      forall (e : env) (T : term) (s1 : sort),\n      Etyp e T (Srt s1) ->\n      forall (U : term) (s2 : sort),\n      Etyp (T :: e) U (Srt s2) -> Etyp e (Prod T U) (Srt s2)\n  | Etype_Econv :\n      forall (e : env) (t U V : term),\n      Etyp e t U ->\n      Econv U V -> forall s : sort, Etyp e V (Srt s) -> Etyp e t V.\n\n  Hint Resolve Ewf_nil Etype_prop Etype_set Etype_var: ecoc.\n\n\nLemma typ_Etyp : forall (e : env) (a Ta : term), typ e a Ta -> Etyp e a Ta. \nfix typ_Etyp 4.\nintros.\ncase H; intros.\napply Etype_prop.\ncase H0.\napply Ewf_nil.\n\nintros; apply Ewf_var with s.\napply typ_Etyp; trivial.\n\napply Etype_set.\ncase H0.\napply Ewf_nil.\n\nintros; apply Ewf_var with s; auto.\n\napply Etype_var.\ncase H0.\napply Ewf_nil.\n\nintros; apply Ewf_var with s.\napply typ_Etyp; trivial.\n\ntrivial.\n\napply Etype_abs with s1 s2; auto.\n\napply Etype_app with V; auto.\n\napply Etype_prod with s1; auto.\n\napply Etype_Econv with U s; auto.\napply conv_Econv; trivial.\nQed.\n\n  Lemma Etype_prop_set :\n   forall s : sort,\n   is_prop s -> forall e : env, Ewf e -> Etyp e (Srt s) (Srt kind).\nsimple destruct 1; intros; rewrite H0.\napply Etype_prop; trivial.\napply Etype_set; trivial.\nQed.\n\n  Lemma Etyp_free_db :\n   forall (e : env) (t T : term), Etyp e t T -> free_db (length e) t.\nsimple induction 1; intros; auto with coc ecoc core arith datatypes.\ninversion_clear H1.\napply db_ref.\nelim H3; simpl in |- *; intros; auto with coc ecoc core arith datatypes.\nQed.\n\n\n  Lemma Etyp_Ewf : forall (e : env) (t T : term), Etyp e t T -> Ewf e.\nsimple induction 1; auto with coc core arith datatypes.\nQed.\n\n\n  Lemma Ewf_sort :\n   forall (n : nat) (e f : env),\n   trunc _ (S n) e f ->\n   Ewf e ->\n   forall t : term, item _ t e n -> exists s : sort, Etyp f t (Srt s).\nsimple induction n.\ndo 3 intro.\ninversion_clear H.\ninversion_clear H0.\nintros.\ninversion_clear H0.\ninversion_clear H.\nexists s; auto with coc core arith datatypes.\n\ndo 5 intro.\ninversion_clear H0.\nintros.\ninversion_clear H2.\ninversion_clear H0.\nelim H with e0 f t; intros; auto with coc core arith datatypes.\nexists x0; auto with coc core arith datatypes.\n\napply Etyp_Ewf with x (Srt s); auto with coc core arith datatypes.\nQed.\n\n\n\n  Definition inv_Etype (P : Prop) (e : env) (t T : term) : Prop :=\n    match t with\n    | Srt prop => Econv T (Srt kind) -> P\n    | Srt set => Econv T (Srt kind) -> P\n    | Srt kind => True\n    | Ref n => forall x : term, item _ x e n -> Econv T (lift (S n) x) -> P\n    | Abs A M =>\n        forall (s1 s2 : sort) (U : term),\n        Etyp e A (Srt s1) ->\n        Etyp (A :: e) M U ->\n        Etyp (A :: e) U (Srt s2) -> Econv T (Prod A U) -> P\n    | App u v =>\n        forall Ur V : term,\n        Etyp e v V -> Etyp e u (Prod V Ur) -> Econv T (subst v Ur) -> P\n    | Prod A B =>\n        forall s1 s2 : sort,\n        Etyp e A (Srt s1) ->\n        Etyp (A :: e) B (Srt s2) -> Econv T (Srt s2) -> P\n    end.\n\n  Lemma inv_Etype_Econv :\n   forall (P : Prop) (e : env) (t U V : term),\n   Econv U V -> inv_Etype P e t U -> inv_Etype P e t V.\ndo 6 intro.\ncut (forall x : term, Econv V x -> Econv U x).\nintro.\ncase t; simpl in |- *; intros.\ngeneralize H1.\nelim s; auto with coc ecoc core arith datatypes; intros.\n\napply H1 with x; auto with coc core arith datatypes.\n\napply H1 with s1 s2 U0; auto with coc core arith datatypes.\n\napply H1 with Ur V0; auto with coc core arith datatypes.\n\napply H1 with s1 s2; auto with coc core arith datatypes.\n\nintros; apply trans_Econv_Econv with V; auto with coc core arith datatypes.\nQed.\n\n\n  Theorem Etyp_inversion :\n   forall (P : Prop) (e : env) (t T : term),\n   Etyp e t T -> inv_Etype P e t T -> P.\nsimple induction 1; simpl in |- *; intros.\nauto with coc ecoc core arith datatypes.\n\nauto with coc ecoc core arith datatypes.\n\nelim H1; intros.\napply H2 with x; auto with coc ecoc core arith datatypes.\nrewrite H3; auto with coc ecoc core arith datatypes.\n\napply H6 with s1 s2 U; auto with coc ecoc core arith datatypes.\n\napply H4 with Ur V; auto with coc ecoc core arith datatypes.\n\napply H4 with s1 s2; auto with coc ecoc core arith datatypes.\n\napply H1.\napply inv_Etype_Econv with V; auto with coc ecoc core arith datatypes.\nQed.\n\n\n\n\n  Lemma inv_Etyp_kind : forall (e : env) (t : term), ~ Etyp e (Srt kind) t.\nred in |- *; intros.\napply Etyp_inversion with e (Srt kind) t; simpl in |- *;\n auto with coc ecoc core arith datatypes.\nQed.\n\n  Lemma inv_Etyp_prop :\n   forall (e : env) (T : term), Etyp e (Srt prop) T -> Econv T (Srt kind).\nintros.\napply Etyp_inversion with e (Srt prop) T; simpl in |- *;\n auto with ecoc coc core arith datatypes.\nQed.\n\n  Lemma inv_Etyp_set :\n   forall (e : env) (T : term), Etyp e (Srt set) T -> Econv T (Srt kind).\nintros.\napply Etyp_inversion with e (Srt set) T; simpl in |- *;\n auto with coc ecoc core arith datatypes.\nQed.\n\n  Lemma inv_Etyp_ref :\n   forall (P : Prop) (e : env) (T : term) (n : nat),\n   Etyp e (Ref n) T ->\n   (forall U : term, item _ U e n -> Econv T (lift (S n) U) -> P) -> P.\nintros.\napply Etyp_inversion with e (Ref n) T; simpl in |- *; intros;\n auto with coc ecoc core arith datatypes.\napply H0 with x; auto with coc ecoc core arith datatypes.\nQed.\n\n  Lemma inv_Etyp_abs :\n   forall (P : Prop) (e : env) (A M U : term),\n   Etyp e (Abs A M) U ->\n   (forall (s1 s2 : sort) (T : term),\n    Etyp e A (Srt s1) ->\n    Etyp (A :: e) M T -> Etyp (A :: e) T (Srt s2) -> Econv (Prod A T) U -> P) ->\n   P.\nintros.\napply Etyp_inversion with e (Abs A M) U; simpl in |- *;\n auto with coc ecoc core arith datatypes; intros.\napply H0 with s1 s2 U0; auto with coc ecoc core arith datatypes.\nQed.\n\n  Lemma inv_Etyp_app :\n   forall (P : Prop) (e : env) (u v T : term),\n   Etyp e (App u v) T ->\n   (forall V Ur : term,\n    Etyp e u (Prod V Ur) -> Etyp e v V -> Econv T (subst v Ur) -> P) -> P.\nintros.\napply Etyp_inversion with e (App u v) T; simpl in |- *;\n auto with coc ecoc core arith datatypes; intros.\napply H0 with V Ur; auto with coc ecoc core arith datatypes.\nQed.\n\n  Lemma inv_Etyp_prod :\n   forall (P : Prop) (e : env) (T U s : term),\n   Etyp e (Prod T U) s ->\n   (forall s1 s2 : sort,\n    Etyp e T (Srt s1) -> Etyp (T :: e) U (Srt s2) -> Econv (Srt s2) s -> P) ->\n   P.\nintros.\napply Etyp_inversion with e (Prod T U) s; simpl in |- *;\n auto with coc ecoc core arith datatypes; intros.\napply H0 with s1 s2; auto with coc ecoc core arith datatypes.\nQed.\n\n\n\n\n  Lemma Etyp_mem_kind :\n   forall (e : env) (t T : term), mem_sort kind t -> ~ Etyp e t T.\nred in |- *; intros.\napply Etyp_inversion with e t T; auto with coc core arith datatypes.\ngeneralize e T.\nclear H0.\nelim H; simpl in |- *; auto with coc core arith datatypes; intros.\napply Etyp_inversion with e0 u (Srt s1); auto with coc core arith datatypes.\n\napply Etyp_inversion with (u :: e0) v (Srt s2);\n auto with coc core arith datatypes.\n\napply Etyp_inversion with e0 u (Srt s1); auto with coc core arith datatypes.\n\napply Etyp_inversion with (u :: e0) v U; auto with coc core arith datatypes.\n\napply Etyp_inversion with e0 u (Prod V Ur);\n auto with coc core arith datatypes.\n\napply Etyp_inversion with e0 v V; auto with coc core arith datatypes.\nQed.\n  \n\nLemma inv_Etyp_Econv_kind :\n forall (e : env) (t T : term), Econv t (Srt kind) -> ~ Etyp e t T.\nintros.\napply Etyp_mem_kind.\napply Ered_sort_mem.\nelim Econv_church_rosser with t (Srt kind); intros;\n auto with ecoc coc core arith datatypes.\nrewrite (Ered_Enormal (Srt kind) x); auto with ecoc coc core arith datatypes.\nred in |- *; red in |- *; intros.\ninversion_clear H2.\nQed.\n\nEnd Typage.\n\n", "meta": {"author": "coq-contribs", "repo": "coq-in-coq", "sha": "0e6fb33eb41c5612ec119966acf93adabe6764a9", "save_path": "github-repos/coq/coq-contribs-coq-in-coq", "path": "github-repos/coq/coq-contribs-coq-in-coq/coq-in-coq-0e6fb33eb41c5612ec119966acf93adabe6764a9/theories/ETypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117165898111866, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.23988794079263073}}
{"text": "(** Verification of a simple example template: a single-node structure *)\n\nRequire Import lock.\nFrom iris.algebra Require Import excl auth gmap agree gset.\nFrom iris.algebra.lib Require Import frac_agree.\nFrom iris.heap_lang Require Export notation locations lang.\nFrom iris.base_logic.lib Require Export invariants.\nFrom iris.program_logic Require Export atomic.\nFrom iris.proofmode Require Import tactics.\nFrom iris.heap_lang Require Import proofmode.\nFrom iris.bi.lib Require Import fractional.\nSet Default Proof Using \"All\".\nRequire Import auth_ext search_str.\n\n(** We use integers as keys. *)\nDefinition K := Z.\n\n(* The keyspace is some arbitrary finite subset of K. *)\nParameter KS : gset K.\n\n\n(** Definitions of cameras used in the template verification *)\nSection One_Node_Cameras.\n\n  (* RA for fractional set of keys *)\n  Definition frackeysCmra : cmra := frac_agreeR (gsetUR K).\n\n  Class frackeysG Σ :=\n    FrackeyshG { frackeys_inG :> inG Σ  frackeysCmra}.\n  Definition frackeysΣ : gFunctors := #[GFunctor frackeysCmra].\n\n  Instance subG_frackeysΣ {Σ} : subG frackeysΣ Σ → frackeysG Σ.\n  Proof. solve_inG. Qed.\n\nEnd One_Node_Cameras.\n\n\n(** Syntactic sugar for fraction-set RA *)\nNotation \"γ ⤇[ q ] m\" := (own γ (to_frac_agree q m))\n  (at level 20, q at level 50, format \"γ ⤇[ q ]  m\") : bi_scope.\nNotation \"γ ⤇½ m\" := (own γ (to_frac_agree (1/2) m))\n  (at level 20, format \"γ ⤇½  m\") : bi_scope.\n\n(** Verification of the template *)\nSection One_Node_Template.\n\n  Context `{!heapG Σ, !frackeysG Σ}.\n  Notation iProp := (iProp Σ).\n\n  (** The code of the template. *)\n\n  (* The following parameters are the implementation-specific helper functions\n   * assumed by the template. *)\n\n  Parameter allocRoot : val.\n  Parameter decisiveOp : (dOp → val).\n\n  Definition create : val :=\n    λ: <>,\n      let: \"r\" := allocRoot #() in\n      \"r\".  \n\n  Definition CSSOp (Ψ: dOp) (r: Node) : val :=\n    rec: \"dictOp\" \"k\" :=\n      lockNode #r;;\n      let: \"res\" := ((decisiveOp Ψ) #r \"k\") in\n      unlockNode #r;;\n      \"res\".\n\n  (** Assumptions on the implementation made by the template proofs. *)\n\n  (* The node predicate is specific to each template implementation. *)\n  Parameter node : Node → gset K → iProp.\n\n  (* The following assumption is justified by the fact that GRASShopper uses a\n   * first-order separation logic. *)\n  Parameter node_timeless_proof : ∀ n C, Timeless (node n C).\n  Instance node_timeless n C: Timeless (node n C).\n  Proof. apply node_timeless_proof. Qed.\n\n  (* The following hypothesis is proved as GRASShopper lemmas in\n   * hashtbl-give-up.spl and b+-tree.spl *)\n  Hypothesis node_sep_star: ∀ n C C',\n    node n C ∗ node n C' -∗ False.\n\n\n  (** Helper functions specs *)\n\n  (* The following specs are proved for each implementation in GRASShopper *)\n\n  Parameter allocRoot_spec :\n      ⊢ ({{{ True }}}\n           allocRoot #()\n         {{{ (r: Node),\n             RET #r; node r ∅ ∗ (lockLoc r) ↦ #false  }}})%I.\n\n  Parameter decisiveOp_spec : ∀ (dop: dOp) (n: Node) (k: K) (C: gset K),\n      ⊢ ({{{ ⌜k ∈ KS⌝ ∗ node n C }}}\n           decisiveOp dop #n #k\n         {{{ (res: bool) (C1: gset K),\n             RET #res;\n             node n C1 ∗ ⌜Ψ dop k C C1 res⌝ }}})%I.\n\n  (** The concurrent search structure invariant *)\n\n  Definition nodePred γ n : iProp :=\n    ∃ C, node n C\n    ∗ γ ⤇½ C.\n\n  Definition CSS γ r (C: gset K) : iProp :=\n    ∃ (b: bool),\n      γ ⤇½ C\n      ∗ lockR b r (nodePred γ r).\n\n  (** High-level lock specs **)\n\n  Lemma lockNode_spec_high γ (r: Node) :\n    ⊢  <<< ∀ (C: gset K), CSS γ r C >>>\n         lockNode #r @ ⊤\n       <<< CSS γ r C ∗ nodePred γ r, RET #() >>>.\n  Proof.\n    iIntros (Φ) \"AU\". \n    awp_apply (lockNode_spec r).\n    iApply (aacc_aupd_commit with \"AU\"); first done.\n    iIntros (C) \"Hcss\". iDestruct \"Hcss\" as (b) \"(HC & Hlock)\".  \n    iAaccIntro with \"Hlock\".\n    { iIntros \"Hlockn\". iModIntro. iSplitL.\n      iFrame. iExists b. iFrame.\n      eauto with iFrame.\n    }\n    iIntros \"(Hlockn & Hnp)\". iModIntro. \n    iSplitL. iFrame. iExists true. iFrame.\n    eauto with iFrame. \n  Qed.\n  \n  Lemma unlockNode_spec_high γ (r: Node) :\n    ⊢  nodePred γ r -∗ \n        <<< ∀ (C: gset K), CSS γ r C >>>\n          unlockNode #r @ ⊤\n       <<< CSS γ r C, RET #() >>>.\n  Proof.\n    iIntros \"Hnp\" (Φ) \"AU\". \n    awp_apply (unlockNode_spec r).\n    iApply (aacc_aupd_commit with \"AU\"); first done.\n    iIntros (C) \"Hcss\".\n    iDestruct \"Hcss\" as (b) \"(HC & Hlock)\".\n    iAssert (⌜b = true⌝)%I as \"%\".\n    { destruct b; try done.\n      iDestruct \"Hlock\" as \"(_ & Hnp')\".\n      iDestruct \"Hnp\" as (Cn)\"(node & _)\".\n      iDestruct \"Hnp'\" as (Cn')\"(node' & _)\".\n      iExFalso; iApply (node_sep_star r); try iFrame. }\n    subst b.      \n    iCombine \"Hlock Hnp\" as \"HlockR\". \n    iAaccIntro with \"HlockR\".\n    { iIntros \"(Hlockn & Hnp)\". iModIntro. iSplitR \"Hnp\".\n      iFrame. iExists true. iFrame.\n      iIntros \"AU\". iModIntro. iFrame. }\n    iIntros \"Hlockn\". iModIntro. \n    iSplitL. iFrame. iExists false. iFrame.\n    eauto with iFrame. \n  Qed.\n  \n\n  (** Proof of CSSOp *)\n\n  Theorem create_spec :\n   ⊢ {{{ True }}}\n        create #()\n     {{{ γ (r: Node), RET #r; CSS γ r ∅ }}}.\n  Proof.\n    iIntros (Φ). iModIntro.\n    iIntros \"_ HΦ\".\n    wp_lam. wp_apply allocRoot_spec; try done.\n    iIntros (r) \"(node & Hl)\". iApply fupd_wp.\n    iMod (own_alloc (to_frac_agree (1) (∅: gset K))) \n          as (γ)\"Hf\". { try done. }\n    iEval (rewrite <-Qp_half_half) in \"Hf\".      \n    iEval (rewrite (frac_agree_op (1/2) (1/2) _)) in \"Hf\". \n    iDestruct \"Hf\" as \"(Hf & Hf')\".\n    iModIntro. wp_pures.\n    iModIntro. iApply (\"HΦ\" $! γ r).\n    iExists false. iFrame.\n    iExists ∅. iFrame.\n  Qed.     \n\n  Theorem CSSOp_spec (γ: gname) r (dop: dOp) (k: K):\n   ⊢ ⌜k ∈ KS⌝ -∗ <<< ∀ C, CSS γ r C >>>\n                          CSSOp dop r #k @ ⊤\n                 <<< ∃ C' (res: bool), CSS γ r C'\n                                     ∗ ⌜Ψ dop k C C' res⌝, RET #res >>>.\n  Proof.\n    iIntros \"%\" (Φ) \"AU\". wp_lam. wp_bind(lockNode _)%E.\n    (* Open AU to get lockNode precondition *)\n    awp_apply (lockNode_spec_high γ r); try done.\n    iApply (aacc_aupd_abort with \"AU\"); first done.\n    iIntros (C0) \"HInv\". iAaccIntro with \"HInv\".\n    { iIntros \"HInv\". iModIntro. eauto with iFrame. }\n    iIntros \"(HInv & Hnode)\".\n    (* Close AU and move on *)\n    iModIntro. iFrame. iIntros \"AU\". iModIntro.\n    (* Execute decisiveOp *)\n    wp_pures. wp_bind (decisiveOp _ _ _)%E.\n    iDestruct \"Hnode\" as (Cn) \"(Hn & Hcn)\".\n    wp_apply ((decisiveOp_spec dop r k) with \"[Hn]\"). eauto with iFrame.\n    iIntros (res C') \"(Hn & %)\".\n    wp_pures.\n\n    awp_apply (unlockNode_spec_low).\n    iApply (aacc_aupd_commit with \"AU\"); first done.\n    iIntros (C) \"Hcss\".\n    iDestruct \"Hcss\" as (b)\"(HC & Hlock)\".\n    iAssert (⌜C = Cn⌝)%I as \"%\".\n    { iPoseProof (own_valid_2 _ _ _ with \"[$Hcn] [$HC]\") as \"H'\".\n      iDestruct \"H'\" as %H'. apply frac_agree_op_valid in H'.\n      destruct H' as [_ H']. apply leibniz_equiv_iff in H'.\n      by iPureIntro. } subst Cn.\n    iAssert (⌜b = true⌝)%I with \"[-]\" as \"%\".\n    {\n      destruct b.\n      - by iPureIntro.\n      - iExFalso. iDestruct \"Hlock\" as \"(_ & Hn')\".\n        iDestruct \"Hn'\" as (C1)\"(Hn' & _)\".\n        iApply node_sep_star; iFrame.\n    } subst b.\n    iEval (unfold lockR) in \"Hlock\".\n    iDestruct \"Hlock\" as \"(Hl & _)\".\n    iAaccIntro with \"Hl\".\n    { iIntros \"Hl\". iModIntro.\n      iSplitR \"Hcn Hn\".\n      { iExists true. iFrame. }\n      iIntros \"AU\". iModIntro. iFrame. }\n    iIntros \"Hl\". \n    iCombine \"Hcn HC\" as \"H'\". \n    iEval (rewrite <-frac_agree_op) in \"H'\". \n    iEval (rewrite Qp_half_half) in \"H'\".\n    iMod ((own_update (γ) (to_frac_agree 1 C) \n                  (to_frac_agree 1 C')) with \"[$H']\") as \"H'\".\n    { apply cmra_update_exclusive. \n      unfold valid, cmra_valid. simpl. unfold prod_valid_instance.\n      split; simpl; try done. }\n    iEval (rewrite <-Qp_half_half) in \"H'\".\n    iEval (rewrite frac_agree_op) in \"H'\".  \n    iDestruct \"H'\" as \"(Hcn & HC)\".\n    iModIntro. iExists C', res.\n    iSplitL. iFrame \"∗%\". iExists false. iFrame.\n    iExists C'. iFrame.\n    iIntros \"HΦ\". iModIntro. wp_pures.\n    by iModIntro.\n  Qed.\n\nEnd One_Node_Template.\n", "meta": {"author": "nyu-acsys", "repo": "template-proofs", "sha": "3911d3f9c25f3fffdd95d6aa052fae606f4d52c2", "save_path": "github-repos/coq/nyu-acsys-template-proofs", "path": "github-repos/coq/nyu-acsys-template-proofs/template-proofs-3911d3f9c25f3fffdd95d6aa052fae606f4d52c2/templates/single_copy/single_node.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23987421188575345}}
{"text": "Require Import Lia.\nRequire Import Bool.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Event.\nRequire Import Time.\nFrom PromisingLib Require Import Language.\n\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\n\nSet Implicit Arguments.\n\n\nModule ThreadEvent.\n  Inductive t :=\n  | promise (loc:Loc.t) (from to:Time.t) (msg:Message.t) (kind:Memory.op_kind)\n  | silent\n  | read (loc:Loc.t) (ts:Time.t) (val:Const.t) (released:option View.t) (ord:Ordering.t)\n  | write (loc:Loc.t) (from to:Time.t) (val:Const.t) (released:option View.t) (ord:Ordering.t)\n  | update (loc:Loc.t) (tsr tsw:Time.t) (valr valw:Const.t) (releasedr releasedw:option View.t) (ordr ordw:Ordering.t)\n  | fence (ordr ordw:Ordering.t)\n  | syscall (e:Event.t)\n  | failure\n  .\n  #[global]\n  Hint Constructors t: core.\n\n  Inductive kind :=\n  | kind_promise\n  | kind_syscall\n  | kind_others\n  .\n  #[global]\n  Hint Constructors kind: core.\n\n  Definition kinds_all := fun k: kind => True.\n  #[global]\n  Hint Unfold kinds_all: core.\n  Definition kinds_promise := fun k: kind => k = kind_promise.\n  #[global]\n  Hint Unfold kinds_promise: core.\n  Definition kinds_program := fun k: kind => k <> kind_promise.\n  #[global]\n  Hint Unfold kinds_program: core.\n  Definition kinds_tau := fun k: kind => k <> kind_syscall.\n  #[global]\n  Hint Unfold kinds_tau: core.\n\n  Definition get_kind (e:t): kind :=\n    match e with\n    | promise _ _ _ _ _ => kind_promise\n    | syscall _ => kind_syscall\n    | _ => kind_others\n    end.\n\n  Definition get_event (e:t): option Event.t :=\n    match e with\n    | syscall e => Some e\n    | _ => None\n    end.\n\n  Definition get_program_event (e:t): ProgramEvent.t :=\n    match e with\n    | promise _ _ _ _ _  => ProgramEvent.silent\n    | silent => ProgramEvent.silent\n    | read loc _ val _ ord => ProgramEvent.read loc val ord\n    | write loc _ _ val _ ord => ProgramEvent.write loc val ord\n    | update loc _ _ valr valw _ _ ordr ordw => ProgramEvent.update loc valr valw ordr ordw\n    | fence ordr ordw => ProgramEvent.fence ordr ordw\n    | syscall ev => ProgramEvent.syscall ev\n    | failure => ProgramEvent.failure\n    end.\n\n  Definition get_machine_event (e: t): MachineEvent.t :=\n    match e with\n    | syscall e => MachineEvent.syscall e\n    | failure => MachineEvent.failure\n    | _ => MachineEvent.silent\n    end.\n\n  Definition is_promising (e:t) : option (Loc.t * Time.t) :=\n    match e with\n    | promise loc from to msg kind => Some (loc, to)\n    | _ => None\n    end.\n\n  Definition is_reading (e:t): option (Loc.t * Time.t * Const.t * option View.t * Ordering.t) :=\n    match e with\n    | read loc ts val released ord => Some (loc, ts, val, released, ord)\n    | update loc tsr _ valr _ releasedr _ ordr _ => Some (loc, tsr, valr, releasedr, ordr)\n    | _ => None\n    end.\n\n  Definition is_writing (e:t): option (Loc.t * Time.t * Time.t * Const.t * option View.t * Ordering.t) :=\n    match e with\n    | write loc from to val released ord => Some (loc, from, to, val, released, ord)\n    | update loc tsr tsw _ valw _ releasedw _ ordw => Some (loc, tsr, tsw, valw, releasedw, ordw)\n    | _ => None\n    end.\n\n  Definition is_accessing (e:t): option (Loc.t * Time.t) :=\n    match e with\n    | read loc ts _ _ _ => Some (loc, ts)\n    | write loc _ ts _ _ _ => Some (loc, ts)\n    | update loc _ ts _ _ _ _ _ _ => Some (loc, ts)\n    | _ => None\n    end.\n\n  Definition is_accessing_loc (l: Loc.t) (e: t): Prop :=\n    match is_accessing e with\n    | Some (loc, _) => loc = l\n    | None => False\n    end.\n\n  Lemma eq_program_event_eq_loc\n        e1 e2 loc\n        (EVENT: get_program_event e1 = get_program_event e2):\n    is_accessing_loc loc e1 <-> is_accessing_loc loc e2.\n  Proof.\n    unfold is_accessing_loc.\n    destruct e1, e2; ss; inv EVENT; ss.\n  Qed.\n\n  Inductive le: forall (lhs rhs:t), Prop :=\n  | le_promise\n      loc from to msg1 msg2 kind1 kind2\n      (LEREL: Message.le msg1 msg2):\n      le (promise loc from to msg1 kind1) (promise loc from to msg2 kind2)\n  | le_silent:\n      le silent silent\n  | le_read\n      loc ts val rel1 rel2 ord\n      (LEREL: View.opt_le rel1 rel2):\n      le (read loc ts val rel1 ord) (read loc ts val rel2 ord)\n  | le_write\n      loc from to val rel1 rel2 ord\n      (LEREL: View.opt_le rel1 rel2):\n      le (write loc from to val rel1 ord) (write loc from to val rel2 ord)\n  | le_update\n      loc tsr tsw valr valw relr1 relr2 relw1 relw2 ordr ordw\n      (LEREL: View.opt_le relr1 relr2)\n      (LEREL: View.opt_le relw1 relw2):\n      le (update loc tsr tsw valr valw relr1 relw1 ordr ordw) (update loc tsr tsw valr valw relr2 relw2 ordr ordw)\n  | le_fence ordr ordw:\n      le (fence ordr ordw) (fence ordr ordw)\n  | le_syscall e:\n      le (syscall e) (syscall e)\n  | le_failure:\n      le failure failure\n  .\n  #[global]\n  Hint Constructors le: core.\n\n  Definition lift (ord0:Ordering.t) (e:t): t :=\n    match e with\n    | promise loc from to msg kind =>\n      promise loc from to msg kind\n    | silent => silent\n    | read loc ts val released ord =>\n      read loc ts val released (Ordering.join ord0 ord)\n    | write loc from to val released ord =>\n      write loc from to val released (Ordering.join ord0 ord)\n    | update loc tsr tsw valr valw releasedr releasedw ordr ordw =>\n      update loc tsr tsw valr valw releasedr releasedw (Ordering.join ord0 ordr) (Ordering.join ord0 ordw)\n    | fence ordr ordw =>\n      fence (Ordering.join ord0 ordr) (Ordering.join ord0 ordw)\n    | syscall e =>\n      syscall e\n    | failure =>\n      failure\n    end.\n\n  Lemma lift_plain e:\n    lift Ordering.plain e = e.\n  Proof. destruct e; ss. Qed.\n\nEnd ThreadEvent.\n\nModule Local.\n  Structure t := mk {\n    tview: TView.t;\n    promises: Memory.t;\n  }.\n\n  Definition init := mk TView.bot Memory.bot.\n\n  Inductive is_terminal (lc:t): Prop :=\n  | is_terminal_intro\n      (PROMISES: (promises lc) = Memory.bot)\n  .\n  #[global]\n  Hint Constructors is_terminal: core.\n\n  Inductive wf (lc:t) (mem:Memory.t): Prop :=\n  | wf_intro\n      (TVIEW_WF: TView.wf (tview lc))\n      (TVIEW_CLOSED: TView.closed (tview lc) mem)\n      (PROMISES: Memory.le (promises lc) mem)\n      (FINITE: Memory.finite (promises lc))\n      (BOT: Memory.bot_none (promises lc))\n      (RESERVE: Memory.reserve_wf (promises lc) mem)\n  .\n  #[global]\n  Hint Constructors wf: core.\n\n  Lemma cap_wf\n        lc promises mem1 mem2\n        (CAP: Memory.cap promises mem1 mem2)\n        (WF: wf lc mem1):\n    wf lc mem2.\n  Proof.\n    inv WF. econs; eauto.\n    - eapply TView.cap_closed; eauto.\n    - eapply Memory.cap_le; eauto.\n    - eapply Memory.cap_reserve_wf; eauto.\n  Qed.\n\n  Inductive disjoint (lc1 lc2:t): Prop :=\n  | disjoint_intro\n      (DISJOINT: Memory.disjoint (promises lc1) (promises lc2))\n  .\n  #[global]\n  Hint Constructors disjoint: core.\n\n  Global Program Instance disjoint_Symmetric: Symmetric disjoint.\n  Next Obligation.\n    econs. symmetry. apply H.\n  Qed.\n\n  Definition promise_consistent (lc:t): Prop :=\n    forall loc ts from val released\n       (PROMISE: Memory.get loc ts (promises lc) = Some (from, Message.full val released)),\n      Time.lt ((TView.cur (tview lc)).(View.rlx) loc) ts.\n\n  Lemma bot_promise_consistent\n        lc\n        (PROMISES: (promises lc) = Memory.bot):\n    promise_consistent lc.\n  Proof.\n    ii. rewrite PROMISES, Memory.bot_get in *. ss.\n  Qed.\n\n  Lemma terminal_promise_consistent\n        lc\n        (TERMINAL: is_terminal lc):\n    promise_consistent lc.\n  Proof.\n    inv TERMINAL. apply bot_promise_consistent. auto.\n  Qed.\n\n\n  Inductive promise_step (lc1:t) (mem1:Memory.t) (loc:Loc.t) (from to:Time.t) (msg:Message.t) (lc2:t) (mem2:Memory.t) (kind:Memory.op_kind): Prop :=\n  | promise_step_intro\n      promises2\n      (PROMISE: Memory.promise (promises lc1) mem1 loc from to msg promises2 mem2 kind)\n      (CLOSED: Memory.closed_message msg mem2)\n      (LC2: lc2 = mk (tview lc1) promises2):\n      promise_step lc1 mem1 loc from to msg lc2 mem2 kind\n  .\n  #[global]\n  Hint Constructors promise_step: core.\n\n  Inductive read_step (lc1:t) (mem1:Memory.t) (loc:Loc.t) (to:Time.t) (val:Const.t) (released:option View.t) (ord:Ordering.t) (lc2:t): Prop :=\n  | read_step_intro\n      from\n      tview2\n      (GET: Memory.get loc to mem1 = Some (from, Message.full val released))\n      (READABLE: TView.readable (TView.cur (tview lc1)) loc to released ord)\n      (TVIEW: TView.read_tview (tview lc1) loc to released ord = tview2)\n      (LC2: lc2 = mk tview2 (promises lc1)):\n      read_step lc1 mem1 loc to val released ord lc2\n  .\n  #[global]\n  Hint Constructors read_step: core.\n\n  Inductive write_step (lc1:t) (sc1:TimeMap.t) (mem1:Memory.t) (loc:Loc.t) (from to:Time.t) (val:Const.t) (releasedm released:option View.t) (ord:Ordering.t) (lc2:t) (sc2:TimeMap.t) (mem2:Memory.t) (kind:Memory.op_kind): Prop :=\n  | write_step_intro\n      promises2\n      (RELEASED: released = TView.write_released (tview lc1) sc1 loc to releasedm ord)\n      (WRITABLE: TView.writable (TView.cur (tview lc1)) sc1 loc to ord)\n      (WRITE: Memory.write (promises lc1) mem1 loc from to val released promises2 mem2 kind)\n      (RELEASE: Ordering.le Ordering.strong_relaxed ord -> Memory.nonsynch_loc loc (promises lc1))\n      (LC2: lc2 = mk (TView.write_tview (tview lc1) sc1 loc to ord) promises2)\n      (SC2: sc2 = sc1):\n      write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n  .\n  #[global]\n  Hint Constructors write_step: core.\n\n  Inductive fence_step (lc1:t) (sc1:TimeMap.t) (ordr ordw:Ordering.t) (lc2:t) (sc2:TimeMap.t): Prop :=\n  | fence_step_intro\n      tview2\n      (READ: TView.read_fence_tview (tview lc1) ordr = tview2)\n      (RELEASE: Ordering.le Ordering.strong_relaxed ordw -> Memory.nonsynch (promises lc1))\n      (LC2: lc2 = mk (TView.write_fence_tview tview2 sc1 ordw) (promises lc1))\n      (SC2: sc2 = TView.write_fence_sc tview2 sc1 ordw):\n      fence_step lc1 sc1 ordr ordw lc2 sc2\n  .\n  #[global]\n  Hint Constructors fence_step: core.\n\n  Inductive failure_step (lc1:t): Prop :=\n  | failure_step_intro\n      (CONSISTENT: promise_consistent lc1)\n  .\n  #[global]\n  Hint Constructors failure_step: core.\n\n  Inductive program_step:\n    forall (e:ThreadEvent.t) (lc1:t) (sc1:TimeMap.t) (mem1:Memory.t) (lc2:t) (sc2:TimeMap.t) (mem2:Memory.t), Prop :=\n  | step_silent\n      lc1 sc1 mem1:\n      program_step ThreadEvent.silent lc1 sc1 mem1 lc1 sc1 mem1\n  | step_read\n      lc1 sc1 mem1\n      loc ts val released ord lc2\n      (LOCAL: Local.read_step lc1 mem1 loc ts val released ord lc2):\n      program_step (ThreadEvent.read loc ts val released ord) lc1 sc1 mem1 lc2 sc1 mem1\n  | step_write\n      lc1 sc1 mem1\n      loc from to val released ord lc2 sc2 mem2 kind\n      (LOCAL: Local.write_step lc1 sc1 mem1 loc from to val None released ord lc2 sc2 mem2 kind):\n      program_step (ThreadEvent.write loc from to val released ord) lc1 sc1 mem1 lc2 sc2 mem2\n  | step_update\n      lc1 sc1 mem1\n      loc ordr ordw\n      tsr valr releasedr releasedw lc2\n      tsw valw lc3 sc3 mem3 kind\n      (LOCAL1: Local.read_step lc1 mem1 loc tsr valr releasedr ordr lc2)\n      (LOCAL2: Local.write_step lc2 sc1 mem1 loc tsr tsw valw releasedr releasedw ordw lc3 sc3 mem3 kind):\n      program_step (ThreadEvent.update loc tsr tsw valr valw releasedr releasedw ordr ordw) lc1 sc1 mem1 lc3 sc3 mem3\n  | step_fence\n      lc1 sc1 mem1\n      ordr ordw lc2 sc2\n      (LOCAL: Local.fence_step lc1 sc1 ordr ordw lc2 sc2):\n      program_step (ThreadEvent.fence ordr ordw) lc1 sc1 mem1 lc2 sc2 mem1\n  | step_syscall\n      lc1 sc1 mem1\n      e lc2 sc2\n      (LOCAL: Local.fence_step lc1 sc1 Ordering.seqcst Ordering.seqcst lc2 sc2):\n      program_step (ThreadEvent.syscall e) lc1 sc1 mem1 lc2 sc2 mem1\n  | step_failure\n      lc1 sc1 mem1\n      (LOCAL: Local.failure_step lc1):\n      program_step ThreadEvent.failure lc1 sc1 mem1 lc1 sc1 mem1\n  .\n  #[global]\n  Hint Constructors program_step: core.\n\n\n  (* step_future *)\n\n  Lemma promise_step_future\n        lc1 sc1 mem1 loc from to msg lc2 mem2 kind\n        (STEP: promise_step lc1 mem1 loc from to msg lc2 mem2 kind)\n        (WF1: wf lc1 mem1)\n        (SC1: Memory.closed_timemap sc1 mem1)\n        (CLOSED1: Memory.closed mem1):\n    <<WF2: wf lc2 mem2>> /\\\n    <<SC2: Memory.closed_timemap sc1 mem2>> /\\\n    <<CLOSED2: Memory.closed mem2>> /\\\n    <<FUTURE: Memory.future mem1 mem2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<MSG_WF: Message.wf msg>> /\\\n    <<MSG_TS: Memory.message_to msg loc to>> /\\\n    <<MSG_CLOSED: Memory.closed_message msg mem2>>.\n  Proof.\n    inv WF1. inv STEP.\n    exploit Memory.promise_future; eauto. i. des.\n    splits; ss.\n    - econs; ss. eapply TView.future_closed; eauto.\n    - eapply Memory.future_closed_timemap; eauto.\n    - refl.\n    - inv PROMISE.\n      + inv PROMISES0. inv ADD. auto.\n      + inv PROMISES0. inv SPLIT. auto.\n      + inv PROMISES0. inv LOWER. auto.\n      + econs.\n    - by inv PROMISE.\n  Qed.\n\n  Lemma read_step_future\n        lc1 mem1 loc ts val released ord lc2\n        (STEP: read_step lc1 mem1 loc ts val released ord lc2)\n        (WF1: wf lc1 mem1)\n        (CLOSED1: Memory.closed mem1):\n    <<WF2: wf lc2 mem1>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<REL_WF: View.opt_wf released>> /\\\n    <<REL_CLOSED: Memory.closed_opt_view released mem1>>.\n  Proof.\n    inv WF1. inv STEP.\n    dup CLOSED1. inv CLOSED0. exploit CLOSED; eauto. i. des.\n    inv MSG_WF. inv MSG_CLOSED.\n    exploit TViewFacts.read_future; try exact GET; eauto.\n    i. des. splits; auto.\n    - econs; eauto.\n    - apply TViewFacts.read_tview_incr.\n  Qed.\n\n  Lemma write_step_future\n        lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n        (STEP: write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n        (REL_WF: View.opt_wf releasedm)\n        (REL_CLOSED: Memory.closed_opt_view releasedm mem1)\n        (WF1: wf lc1 mem1)\n        (SC1: Memory.closed_timemap sc1 mem1)\n        (CLOSED1: Memory.closed mem1):\n    <<WF2: wf lc2 mem2>> /\\\n    <<SC2: Memory.closed_timemap sc2 mem2>> /\\\n    <<CLOSED2: Memory.closed mem2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<SC_FUTURE: TimeMap.le sc1 sc2>> /\\\n    <<MEM_FUTURE: Memory.future mem1 mem2>> /\\\n    <<REL_WF: View.opt_wf released>> /\\\n    <<REL_TS: Time.le ((View.rlx (View.unwrap released)) loc) to>> /\\\n    <<REL_CLOSED: Memory.closed_opt_view released mem2>>.\n  Proof.\n    inv WF1. inv STEP.\n    exploit TViewFacts.write_future; eauto.\n    { inv WRITE. eapply Memory.promise_op. eauto. }\n    s. i. des.\n    exploit Memory.write_future; try apply WRITE; eauto. i. des.\n    exploit Memory.write_get2; try apply WRITE; eauto; try by viewtac. i. des.\n    splits; eauto.\n    - apply TViewFacts.write_tview_incr. auto.\n    - refl.\n    - inv WRITE. inv PROMISE; try inv TS; ss.\n  Qed.\n\n  Lemma write_step_non_cancel\n        lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n        (STEP: write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind):\n    negb (Memory.op_kind_is_cancel kind).\n  Proof.\n    inv STEP. inv WRITE. inv PROMISE; ss.\n  Qed.\n\n  Lemma write_step_strong_relaxed\n        lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n        (STEP: write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n        (ORD: Ordering.le Ordering.strong_relaxed ord):\n    negb (Memory.op_kind_is_lower kind).\n  Proof.\n    inv STEP. inv WRITE. ss.\n    destruct kind; ss.\n    inv PROMISE. des. subst.\n    exploit Memory.lower_get0; try exact PROMISES. i. des.\n    exploit RELEASE; eauto. inv MSG_LE; eauto. i. subst.\n    inv RELEASED. revert H0.\n    unfold TView.write_released. condtac; ss. destruct ord; ss.\n  Qed.\n\n  Lemma fence_step_future\n        lc1 sc1 mem1 ordr ordw lc2 sc2\n        (STEP: fence_step lc1 sc1 ordr ordw lc2 sc2)\n        (WF1: wf lc1 mem1)\n        (SC1: Memory.closed_timemap sc1 mem1)\n        (CLOSED1: Memory.closed mem1):\n    <<WF2: wf lc2 mem1>> /\\\n    <<SC2: Memory.closed_timemap sc2 mem1>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<SC_FUTURE: TimeMap.le sc1 sc2>>.\n  Proof.\n    inv WF1. inv STEP.\n    exploit TViewFacts.read_fence_future; eauto. i. des.\n    exploit TViewFacts.write_fence_future; eauto. i. des.\n    splits; eauto.\n    - etrans.\n      + apply TViewFacts.write_fence_tview_incr. auto.\n      + apply TViewFacts.write_fence_tview_mon; eauto; try refl.\n        apply TViewFacts.read_fence_tview_incr. auto.\n    - apply TViewFacts.write_fence_sc_incr.\n  Qed.\n\n  Lemma program_step_future\n        e lc1 sc1 mem1 lc2 sc2 mem2\n        (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n        (WF1: wf lc1 mem1)\n        (SC1: Memory.closed_timemap sc1 mem1)\n        (CLOSED1: Memory.closed mem1):\n    <<WF2: wf lc2 mem2>> /\\\n    <<SC2: Memory.closed_timemap sc2 mem2>> /\\\n    <<CLOSED2: Memory.closed mem2>> /\\\n    <<TVIEW_FUTURE: TView.le (tview lc1) (tview lc2)>> /\\\n    <<SC_FUTURE: TimeMap.le sc1 sc2>> /\\\n    <<MEM_FUTURE: Memory.future mem1 mem2>>.\n  Proof.\n    inv STEP.\n    - esplits; eauto; try refl.\n    - exploit read_step_future; eauto. i. des.\n      esplits; eauto; try refl.\n    - exploit write_step_future; eauto; try by econs. i. des.\n      esplits; eauto; try refl.\n    - exploit read_step_future; eauto. i. des.\n      exploit write_step_future; eauto; try by econs. i. des.\n      esplits; eauto. etrans; eauto.\n    - exploit fence_step_future; eauto. i. des. esplits; eauto; try refl.\n    - exploit fence_step_future; eauto. i. des. esplits; eauto; try refl.\n    - esplits; eauto; try refl.\n  Qed.\n\n  Lemma promise_step_inhabited\n        lc1 mem1 loc from to msg lc2 mem2 kind\n        (STEP: promise_step lc1 mem1 loc from to msg lc2 mem2 kind)\n        (INHABITED1: Memory.inhabited mem1):\n    <<INHABITED2: Memory.inhabited mem2>>.\n  Proof.\n    inv STEP.\n    inv PROMISE; eauto using Memory.add_inhabited, Memory.split_inhabited, Memory.lower_inhabited, Memory.cancel_inhabited.\n  Qed.\n\n  Lemma program_step_inhabited\n        e lc1 sc1 mem1 lc2 sc2 mem2\n        (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n        (INHABITED1: Memory.inhabited mem1):\n    <<INHABITED2: Memory.inhabited mem2>>.\n  Proof.\n    inv STEP; eauto.\n    - inv LOCAL. inv WRITE.\n      inv PROMISE; eauto using Memory.add_inhabited, Memory.split_inhabited, Memory.lower_inhabited, Memory.cancel_inhabited.\n    - inv LOCAL2. inv WRITE.\n      inv PROMISE; eauto using Memory.add_inhabited, Memory.split_inhabited, Memory.lower_inhabited, Memory.cancel_inhabited.\n  Qed.\n\n\n  (* step_disjoint *)\n\n  Lemma promise_step_disjoint\n        lc1 sc1 mem1 loc from to msg lc2 mem2 lc kind\n        (STEP: promise_step lc1 mem1 loc from to msg lc2 mem2 kind)\n        (WF1: wf lc1 mem1)\n        (SC1: Memory.closed_timemap sc1 mem1)\n        (CLOSED1: Memory.closed mem1)\n        (DISJOINT1: disjoint lc1 lc)\n        (WF: wf lc mem1):\n    <<DISJOINT2: disjoint lc2 lc>> /\\\n    <<WF: wf lc mem2>>.\n  Proof.\n    inv WF1. inv DISJOINT1. inversion WF. inv STEP.\n    exploit Memory.promise_future; try apply PROMISE; eauto. i. des.\n    exploit Memory.promise_disjoint; try apply PROMISE; eauto. i. des.\n    splits; ss. econs; eauto.\n    eapply TView.future_closed; eauto.\n  Qed.\n\n  Lemma read_step_disjoint\n        lc1 mem1 lc2 loc ts val released ord lc\n        (STEP: read_step lc1 mem1 loc ts val released ord lc2)\n        (WF1: wf lc1 mem1)\n        (DISJOINT1: disjoint lc1 lc)\n        (WF: wf lc mem1):\n    disjoint lc2 lc.\n  Proof.\n    inv WF1. inv DISJOINT1. inv WF. inv STEP. ss.\n  Qed.\n\n  Lemma write_step_disjoint\n        lc1 sc1 mem1 lc2 sc2 loc from to val releasedm released ord mem2 kind lc\n        (STEP: write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n        (WF1: wf lc1 mem1)\n        (SC1: Memory.closed_timemap sc1 mem1)\n        (CLOSED1: Memory.closed mem1)\n        (DISJOINT1: disjoint lc1 lc)\n        (WF: wf lc mem1):\n    <<DISJOINT2: disjoint lc2 lc>> /\\\n    <<WF: wf lc mem2>>.\n  Proof.\n    inv WF1. inv DISJOINT1. inversion WF. inv STEP.\n    exploit Memory.write_disjoint; try apply WRITE; eauto. i. des.\n    splits; ss. econs; eauto.\n    inv WRITE. eapply TView.promise_closed; eauto.\n  Qed.\n\n  Lemma fence_step_disjoint\n        lc1 sc1 mem1 lc2 sc2 ordr ordw lc\n        (STEP: fence_step lc1 sc1 ordr ordw lc2 sc2)\n        (WF1: wf lc1 mem1)\n        (SC1: Memory.closed_timemap sc1 mem1)\n        (DISJOINT1: disjoint lc1 lc)\n        (WF: wf lc mem1):\n    <<DISJOINT2: disjoint lc2 lc>> /\\\n    <<WF: wf lc mem1>>.\n  Proof.\n    inv WF1. inv DISJOINT1. inv WF. inv STEP. splits; ss.\n  Qed.\n\n  Lemma read_step_promises\n        lc1 mem loc to val released ord lc2\n        (READ: read_step lc1 mem loc to val released ord lc2):\n    (promises lc1) = (promises lc2).\n  Proof.\n    inv READ. auto.\n  Qed.\n\n  Lemma program_step_disjoint\n        e lc1 sc1 mem1 lc2 sc2 mem2 lc\n        (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n        (WF1: wf lc1 mem1)\n        (SC1: Memory.closed_timemap sc1 mem1)\n        (CLOSED1: Memory.closed mem1)\n        (DISJOINT1: disjoint lc1 lc)\n        (WF: wf lc mem1):\n    <<DISJOINT2: disjoint lc2 lc>> /\\\n    <<WF: wf lc mem2>>.\n  Proof.\n    inv STEP.\n    - esplits; eauto.\n    - exploit read_step_disjoint; eauto.\n    - exploit write_step_disjoint; eauto.\n    - exploit read_step_future; eauto. i. des.\n      exploit read_step_disjoint; eauto. i. des.\n      exploit write_step_disjoint; eauto.\n    - exploit fence_step_disjoint; eauto.\n    - exploit fence_step_disjoint; eauto.\n    - esplits; eauto.\n  Qed.\n\n\n  (* step_no_reserve_except *)\n\n  Lemma promise_step_no_reserve_except\n        lc1 mem1 loc from to msg lc2 mem2 kind\n        (STEP: promise_step lc1 mem1 loc from to msg lc2 mem2 kind)\n        (RESERVE1: Memory.reserve_wf (promises lc1) mem1)\n        (NORESERVE1: Memory.no_reserve_except (promises lc1) mem1):\n    Memory.no_reserve_except (promises lc2) mem2.\n  Proof.\n    ii. inv STEP. s.\n    eapply Memory.promise_no_reserve_except; eauto.\n  Qed.\n\n  Lemma program_step_no_reserve_except\n        e lc1 sc1 mem1 lc2 sc2 mem2\n        (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n        (RESERVE1: Memory.reserve_wf (promises lc1) mem1)\n        (NORESERVE1: Memory.no_reserve_except (promises lc1) mem1):\n    Memory.no_reserve_except (promises lc2) mem2.\n  Proof.\n    ii. inv STEP; try inv LOCAL; eauto; ss.\n    - inv WRITE.\n      erewrite Memory.remove_o; eauto. condtac; ss.\n      + des. subst.\n        exploit Memory.promise_get0; eauto.\n        { inv PROMISE; ss. }\n        i. des. congr.\n      + eapply Memory.promise_no_reserve_except; eauto.\n    - inv LOCAL1. inv LOCAL2. inv WRITE. ss.\n      erewrite Memory.remove_o; eauto. condtac; ss.\n      + des. subst.\n        exploit Memory.promise_get0; eauto.\n        { inv PROMISE; ss. }\n        i. des. congr.\n      + eapply Memory.promise_no_reserve_except; eauto.\n  Qed.\n\n\n  Lemma program_step_promises_bot\n        e lc1 sc1 mem1 lc2 sc2 mem2\n        (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n        (PROMISES: (promises lc1) = Memory.bot):\n    (promises lc2) = Memory.bot.\n  Proof.\n    inv STEP; try inv LOCAL; ss.\n    - eapply Memory.write_promises_bot; eauto.\n    - inv LOCAL1. inv LOCAL2.\n      eapply Memory.write_promises_bot; eauto.\n  Qed.\nEnd Local.\n", "meta": {"author": "snu-sf", "repo": "promising2-coq", "sha": "52dd46538036a7a69c132e89dd3e7698b5e2f830", "save_path": "github-repos/coq/snu-sf-promising2-coq", "path": "github-repos/coq/snu-sf-promising2-coq/promising2-coq-52dd46538036a7a69c132e89dd3e7698b5e2f830/src/lang/Local.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23987421188575342}}
{"text": "Require Export concurrency.paco.src.paconotation concurrency.paco.src.pacotac concurrency.paco.src.pacodef concurrency.paco.src.pacotacuser.\nSet Implicit Arguments.\n\n(** ** Predicates of Arity 7\n*)\n\n(** 1 Mutual Coinduction *)\n\nSection Arg7_1.\n\nDefinition monotone7 T0 T1 T2 T3 T4 T5 T6 (gf: rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6) :=\n  forall x0 x1 x2 x3 x4 x5 x6 r r' (IN: gf r x0 x1 x2 x3 x4 x5 x6) (LE: r <7= r'), gf r' x0 x1 x2 x3 x4 x5 x6.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.\nVariable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.\nVariable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.\nVariable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.\nVariable gf : rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6.\nImplicit Arguments gf [].\n\nTheorem paco7_acc: forall\n  l r (OBG: forall rr (INC: r <7= rr) (CIH: l <_paco_7= rr), l <_paco_7= paco7 gf rr),\n  l <7= paco7 gf r.\nProof.\n  intros; assert (SIM: paco7 gf (r \\7/ l) x0 x1 x2 x3 x4 x5 x6) by eauto.\n  clear PR; repeat (try left; do 8 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco7_mon: monotone7 (paco7 gf).\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_mult_strong: forall r,\n  paco7 gf (upaco7 gf r) <7= paco7 gf r.\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco7_mult: forall r,\n  paco7 gf (paco7 gf r) <7= paco7 gf r.\nProof. intros; eapply paco7_mult_strong, paco7_mon; eauto. Qed.\n\nTheorem paco7_fold: forall r,\n  gf (upaco7 gf r) <7= paco7 gf r.\nProof. intros; econstructor; [ |eauto]; eauto. Qed.\n\nTheorem paco7_unfold: forall (MON: monotone7 gf) r,\n  paco7 gf r <7= gf (upaco7 gf r).\nProof. unfold monotone7; intros; destruct PR; eauto. Qed.\n\nEnd Arg7_1.\n\nHint Unfold monotone7.\nHint Resolve paco7_fold.\n\nImplicit Arguments paco7_acc            [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_mon            [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_mult           [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_fold           [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_unfold         [ T0 T1 T2 T3 T4 T5 T6 ].\n\nInstance paco7_inst  T0 T1 T2 T3 T4 T5 T6 (gf : rel7 T0 T1 T2 T3 T4 T5 T6->_) r x0 x1 x2 x3 x4 x5 x6 : paco_class (paco7 gf r x0 x1 x2 x3 x4 x5 x6) :=\n{ pacoacc    := paco7_acc gf;\n  pacomult   := paco7_mult gf;\n  pacofold   := paco7_fold gf;\n  pacounfold := paco7_unfold gf }.\n\n(** 2 Mutual Coinduction *)\n\nSection Arg7_2.\n\nDefinition monotone7_2 T0 T1 T2 T3 T4 T5 T6 (gf: rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6) :=\n  forall x0 x1 x2 x3 x4 x5 x6 r_0 r_1 r'_0 r'_1 (IN: gf r_0 r_1 x0 x1 x2 x3 x4 x5 x6) (LE_0: r_0 <7= r'_0)(LE_1: r_1 <7= r'_1), gf r'_0 r'_1 x0 x1 x2 x3 x4 x5 x6.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.\nVariable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.\nVariable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.\nVariable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.\nVariable gf_0 gf_1 : rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6.\nImplicit Arguments gf_0 [].\nImplicit Arguments gf_1 [].\n\nTheorem paco7_2_0_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_0 <7= rr) (CIH: l <_paco_7= rr), l <_paco_7= paco7_2_0 gf_0 gf_1 rr r_1),\n  l <7= paco7_2_0 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco7_2_0 gf_0 gf_1 (r_0 \\7/ l) r_1 x0 x1 x2 x3 x4 x5 x6) by eauto.\n  clear PR; repeat (try left; do 8 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco7_2_1_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_1 <7= rr) (CIH: l <_paco_7= rr), l <_paco_7= paco7_2_1 gf_0 gf_1 r_0 rr),\n  l <7= paco7_2_1 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco7_2_1 gf_0 gf_1 r_0 (r_1 \\7/ l) x0 x1 x2 x3 x4 x5 x6) by eauto.\n  clear PR; repeat (try left; do 8 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco7_2_0_mon: monotone7_2 (paco7_2_0 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_2_1_mon: monotone7_2 (paco7_2_1 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_2_0_mult_strong: forall r_0 r_1,\n  paco7_2_0 gf_0 gf_1 (upaco7_2_0 gf_0 gf_1 r_0 r_1) (upaco7_2_1 gf_0 gf_1 r_0 r_1) <7= paco7_2_0 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_2_1_mult_strong: forall r_0 r_1,\n  paco7_2_1 gf_0 gf_1 (upaco7_2_0 gf_0 gf_1 r_0 r_1) (upaco7_2_1 gf_0 gf_1 r_0 r_1) <7= paco7_2_1 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco7_2_0_mult: forall r_0 r_1,\n  paco7_2_0 gf_0 gf_1 (paco7_2_0 gf_0 gf_1 r_0 r_1) (paco7_2_1 gf_0 gf_1 r_0 r_1) <7= paco7_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco7_2_0_mult_strong, paco7_2_0_mon; eauto. Qed.\n\nCorollary paco7_2_1_mult: forall r_0 r_1,\n  paco7_2_1 gf_0 gf_1 (paco7_2_0 gf_0 gf_1 r_0 r_1) (paco7_2_1 gf_0 gf_1 r_0 r_1) <7= paco7_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco7_2_1_mult_strong, paco7_2_1_mon; eauto. Qed.\n\nTheorem paco7_2_0_fold: forall r_0 r_1,\n  gf_0 (upaco7_2_0 gf_0 gf_1 r_0 r_1) (upaco7_2_1 gf_0 gf_1 r_0 r_1) <7= paco7_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco7_2_1_fold: forall r_0 r_1,\n  gf_1 (upaco7_2_0 gf_0 gf_1 r_0 r_1) (upaco7_2_1 gf_0 gf_1 r_0 r_1) <7= paco7_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco7_2_0_unfold: forall (MON: monotone7_2 gf_0) (MON: monotone7_2 gf_1) r_0 r_1,\n  paco7_2_0 gf_0 gf_1 r_0 r_1 <7= gf_0 (upaco7_2_0 gf_0 gf_1 r_0 r_1) (upaco7_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone7_2; intros; destruct PR; eauto. Qed.\n\nTheorem paco7_2_1_unfold: forall (MON: monotone7_2 gf_0) (MON: monotone7_2 gf_1) r_0 r_1,\n  paco7_2_1 gf_0 gf_1 r_0 r_1 <7= gf_1 (upaco7_2_0 gf_0 gf_1 r_0 r_1) (upaco7_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone7_2; intros; destruct PR; eauto. Qed.\n\nEnd Arg7_2.\n\nHint Unfold monotone7_2.\nHint Resolve paco7_2_0_fold.\nHint Resolve paco7_2_1_fold.\n\nImplicit Arguments paco7_2_0_acc            [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_2_1_acc            [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_2_0_mon            [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_2_1_mon            [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_2_0_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_2_1_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_2_0_mult           [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_2_1_mult           [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_2_0_fold           [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_2_1_fold           [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_2_0_unfold         [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_2_1_unfold         [ T0 T1 T2 T3 T4 T5 T6 ].\n\nInstance paco7_2_0_inst  T0 T1 T2 T3 T4 T5 T6 (gf_0 gf_1 : rel7 T0 T1 T2 T3 T4 T5 T6->_) r_0 r_1 x0 x1 x2 x3 x4 x5 x6 : paco_class (paco7_2_0 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3 x4 x5 x6) :=\n{ pacoacc    := paco7_2_0_acc gf_0 gf_1;\n  pacomult   := paco7_2_0_mult gf_0 gf_1;\n  pacofold   := paco7_2_0_fold gf_0 gf_1;\n  pacounfold := paco7_2_0_unfold gf_0 gf_1 }.\n\nInstance paco7_2_1_inst  T0 T1 T2 T3 T4 T5 T6 (gf_0 gf_1 : rel7 T0 T1 T2 T3 T4 T5 T6->_) r_0 r_1 x0 x1 x2 x3 x4 x5 x6 : paco_class (paco7_2_1 gf_0 gf_1 r_0 r_1 x0 x1 x2 x3 x4 x5 x6) :=\n{ pacoacc    := paco7_2_1_acc gf_0 gf_1;\n  pacomult   := paco7_2_1_mult gf_0 gf_1;\n  pacofold   := paco7_2_1_fold gf_0 gf_1;\n  pacounfold := paco7_2_1_unfold gf_0 gf_1 }.\n\n(** 3 Mutual Coinduction *)\n\nSection Arg7_3.\n\nDefinition monotone7_3 T0 T1 T2 T3 T4 T5 T6 (gf: rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6) :=\n  forall x0 x1 x2 x3 x4 x5 x6 r_0 r_1 r_2 r'_0 r'_1 r'_2 (IN: gf r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6) (LE_0: r_0 <7= r'_0)(LE_1: r_1 <7= r'_1)(LE_2: r_2 <7= r'_2), gf r'_0 r'_1 r'_2 x0 x1 x2 x3 x4 x5 x6.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.\nVariable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.\nVariable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.\nVariable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.\nVariable gf_0 gf_1 gf_2 : rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6 -> rel7 T0 T1 T2 T3 T4 T5 T6.\nImplicit Arguments gf_0 [].\nImplicit Arguments gf_1 [].\nImplicit Arguments gf_2 [].\n\nTheorem paco7_3_0_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_0 <7= rr) (CIH: l <_paco_7= rr), l <_paco_7= paco7_3_0 gf_0 gf_1 gf_2 rr r_1 r_2),\n  l <7= paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco7_3_0 gf_0 gf_1 gf_2 (r_0 \\7/ l) r_1 r_2 x0 x1 x2 x3 x4 x5 x6) by eauto.\n  clear PR; repeat (try left; do 8 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco7_3_1_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_1 <7= rr) (CIH: l <_paco_7= rr), l <_paco_7= paco7_3_1 gf_0 gf_1 gf_2 r_0 rr r_2),\n  l <7= paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco7_3_1 gf_0 gf_1 gf_2 r_0 (r_1 \\7/ l) r_2 x0 x1 x2 x3 x4 x5 x6) by eauto.\n  clear PR; repeat (try left; do 8 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco7_3_2_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_2 <7= rr) (CIH: l <_paco_7= rr), l <_paco_7= paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 rr),\n  l <7= paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 (r_2 \\7/ l) x0 x1 x2 x3 x4 x5 x6) by eauto.\n  clear PR; repeat (try left; do 8 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco7_3_0_mon: monotone7_3 (paco7_3_0 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_3_1_mon: monotone7_3 (paco7_3_1 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_3_2_mon: monotone7_3 (paco7_3_2 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_3_0_mult_strong: forall r_0 r_1 r_2,\n  paco7_3_0 gf_0 gf_1 gf_2 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_3_1_mult_strong: forall r_0 r_1 r_2,\n  paco7_3_1 gf_0 gf_1 gf_2 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco7_3_2_mult_strong: forall r_0 r_1 r_2,\n  paco7_3_2 gf_0 gf_1 gf_2 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 8 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco7_3_0_mult: forall r_0 r_1 r_2,\n  paco7_3_0 gf_0 gf_1 gf_2 (paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco7_3_0_mult_strong, paco7_3_0_mon; eauto. Qed.\n\nCorollary paco7_3_1_mult: forall r_0 r_1 r_2,\n  paco7_3_1 gf_0 gf_1 gf_2 (paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco7_3_1_mult_strong, paco7_3_1_mon; eauto. Qed.\n\nCorollary paco7_3_2_mult: forall r_0 r_1 r_2,\n  paco7_3_2 gf_0 gf_1 gf_2 (paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco7_3_2_mult_strong, paco7_3_2_mon; eauto. Qed.\n\nTheorem paco7_3_0_fold: forall r_0 r_1 r_2,\n  gf_0 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco7_3_1_fold: forall r_0 r_1 r_2,\n  gf_1 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco7_3_2_fold: forall r_0 r_1 r_2,\n  gf_2 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <7= paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco7_3_0_unfold: forall (MON: monotone7_3 gf_0) (MON: monotone7_3 gf_1) (MON: monotone7_3 gf_2) r_0 r_1 r_2,\n  paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 <7= gf_0 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone7_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco7_3_1_unfold: forall (MON: monotone7_3 gf_0) (MON: monotone7_3 gf_1) (MON: monotone7_3 gf_2) r_0 r_1 r_2,\n  paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 <7= gf_1 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone7_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco7_3_2_unfold: forall (MON: monotone7_3 gf_0) (MON: monotone7_3 gf_1) (MON: monotone7_3 gf_2) r_0 r_1 r_2,\n  paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 <7= gf_2 (upaco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone7_3; intros; destruct PR; eauto. Qed.\n\nEnd Arg7_3.\n\nHint Unfold monotone7_3.\nHint Resolve paco7_3_0_fold.\nHint Resolve paco7_3_1_fold.\nHint Resolve paco7_3_2_fold.\n\nImplicit Arguments paco7_3_0_acc            [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_1_acc            [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_2_acc            [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_0_mon            [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_1_mon            [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_2_mon            [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_0_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_1_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_2_mult_strong    [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_0_mult           [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_1_mult           [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_2_mult           [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_0_fold           [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_1_fold           [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_2_fold           [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_0_unfold         [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_1_unfold         [ T0 T1 T2 T3 T4 T5 T6 ].\nImplicit Arguments paco7_3_2_unfold         [ T0 T1 T2 T3 T4 T5 T6 ].\n\nInstance paco7_3_0_inst  T0 T1 T2 T3 T4 T5 T6 (gf_0 gf_1 gf_2 : rel7 T0 T1 T2 T3 T4 T5 T6->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6 : paco_class (paco7_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6) :=\n{ pacoacc    := paco7_3_0_acc gf_0 gf_1 gf_2;\n  pacomult   := paco7_3_0_mult gf_0 gf_1 gf_2;\n  pacofold   := paco7_3_0_fold gf_0 gf_1 gf_2;\n  pacounfold := paco7_3_0_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco7_3_1_inst  T0 T1 T2 T3 T4 T5 T6 (gf_0 gf_1 gf_2 : rel7 T0 T1 T2 T3 T4 T5 T6->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6 : paco_class (paco7_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6) :=\n{ pacoacc    := paco7_3_1_acc gf_0 gf_1 gf_2;\n  pacomult   := paco7_3_1_mult gf_0 gf_1 gf_2;\n  pacofold   := paco7_3_1_fold gf_0 gf_1 gf_2;\n  pacounfold := paco7_3_1_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco7_3_2_inst  T0 T1 T2 T3 T4 T5 T6 (gf_0 gf_1 gf_2 : rel7 T0 T1 T2 T3 T4 T5 T6->_) r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6 : paco_class (paco7_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2 x3 x4 x5 x6) :=\n{ pacoacc    := paco7_3_2_acc gf_0 gf_1 gf_2;\n  pacomult   := paco7_3_2_mult gf_0 gf_1 gf_2;\n  pacofold   := paco7_3_2_fold gf_0 gf_1 gf_2;\n  pacounfold := paco7_3_2_unfold gf_0 gf_1 gf_2 }.\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/concurrency/paco/src/paco7.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23986766542353896}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*              Layers of VMM: MShareIntro                             *)\n(*                                                                     *)\n(*          Introduce the shared-memory                                *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file defines the abstract data and the primitives for the PIPCIntro layer,\nwhich will introduce the primtives of thread*)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import LoadStoreSem2.\nRequire Import XOmega.\nRequire Import ObservationImpl.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealSMSPool.\n\nRequire Import INVLemmaContainer.\nRequire Import INVLemmaMemory.\n\nRequire Import AbstractDataType.\n\nRequire Export ObjCPU.\nRequire Export ObjFlatMem.\nRequire Export ObjContainer.\nRequire Export ObjVMM.\nRequire Export ObjLMM.\nRequire Export ObjShareMem.\n\n(** * Abstract Data and Primitives at this layer*)\nSection WITHMEM.\n\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n  \n  (*Record RData :=\n    mkRData {\n        HP: flatmem; (**r we model the memory from 1G to 3G as heap*)\n        ti: trapinfo; (**r abstract of CR2, stores the address where page fault happens*)\n        pg: bool; (**r abstract of CR0, indicates whether the paging is enabled or not*)\n        ikern: bool; (**r pure logic flag, shows whether it's in kernel mode or not*)\n        ihost: bool; (**r logic flag, shows whether it's in the host mode or not*)         \n\n        AT: LATable; (**r allocation table*)\n        nps: Z; (**r number of the pages*)\n        pperm: PPermT; (**r physical page permission table *)\n\n        PT: Z; (**r the current page table index*)\n        ptpool: PMapPool; (**r page table pool*)\n        idpde: IDPDE; (**r shared identity maps *)\n        ipt: bool; (**r pure logic flag, shows whether it's using the kernel's page table*)\n        pb : PTBitMap; (**r [page table bit map], indicating which page table has been used*)\n        smspool: SharedMemSTPool (**r the shared-memory pool for IPC*)\n      }.*)\n\n  (** ** Invariants at this layer *)\n  (** [0th page map] is reserved for the kernel thread*)\n  Record high_level_invariant (abd: RData) :=\n    mkInvariant {\n        valid_nps: pg abd = true -> kern_low <= nps abd <= maxpage;\n        valid_AT_kern: pg abd = true -> LAT_kern (LAT abd) (nps abd);\n        valid_AT_usr: pg abd = true -> LAT_usr (LAT abd) (nps abd);\n        valid_kern: ipt abd = false -> pg abd = true;\n        valid_iptt: ipt abd = true -> ikern abd = true; \n        valid_iptf: ikern abd = false -> ipt abd = false; \n        valid_ihost: ihost abd = false -> pg abd = true /\\ ikern abd = true;\n        valid_container: Container_valid (AC abd);\n        valid_pperm_ppage: Lconsistent_ppage (LAT abd) (pperm abd) (nps abd);\n        init_pperm: pg abd = false -> (pperm abd) = ZMap.init PGUndef;\n        valid_PMap: pg abd = true -> \n                    (forall i, 0<= i < num_proc ->\n                               PMap_valid (ZMap.get i (ptpool abd)));\n        (* 0th page map is reserved for the kernel thread*)          \n        valid_PT_kern: pg abd = true -> ipt abd = true -> (PT abd) = 0;\n        valid_PMap_kern: pg abd = true -> PMap_kern (ZMap.get 0 (ptpool abd));\n        valid_PT: pg abd = true -> 0<= PT abd < num_proc;\n        valid_dirty: dirty_ppage (pperm abd) (HP abd);\n\n        valid_idpde: pg abd = true -> IDPDE_init (idpde abd);\n        valid_pperm_pmap: consistent_pmap (ptpool abd) (pperm abd) (LAT abd) (nps abd);\n        valid_pmap_domain: consistent_pmap_domain (ptpool abd) (pperm abd) (LAT abd) (nps abd);\n        valid_lat_domain: consistent_lat_domain (ptpool abd) (LAT abd) (nps abd);\n\n        valid_root: pg abd = true -> cused (ZMap.get 0 (AC abd)) = true\n      }.\n\n  (** ** Definition of the abstract state ops *)\n  Global Instance mshareintro_data_ops : CompatDataOps RData :=\n    {\n      empty_data := init_adt;\n      high_level_invariant := high_level_invariant;\n      low_level_invariant := low_level_invariant;\n      kernel_mode adt := ikern adt = true /\\ ihost adt = true;\n      observe := ObservationImpl.observe\n    }.\n\n  (** ** Proofs that the initial abstract_data should satisfy the invariants*)    \n  Section Property_Abstract_Data.\n\n    Lemma empty_data_high_level_invariant:\n      high_level_invariant init_adt.\n    Proof.\n      constructor; simpl; intros; auto; try inv H.\n      - apply empty_container_valid.\n      - eapply Lconsistent_ppage_init.\n      - eapply dirty_ppage_init.\n      - eapply consistent_pmap_init.\n      - eapply consistent_pmap_domain_init.\n      - eapply consistent_lat_domain_init.\n    Qed.\n\n    (** ** Definition of the abstract state *)\n    Global Instance mshareintro_data_prf : CompatData RData.\n    Proof.\n      constructor.\n      - apply low_level_invariant_incr.\n      - apply empty_data_low_level_invariant.\n      - apply empty_data_high_level_invariant.\n    Qed.\n\n  End Property_Abstract_Data.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  (** * Proofs that the primitives satisfies the invariants at this layer *)\n  Section INV.\n\n    Global Instance flatmem_copy_inv: PreservesInvariants flatmem_copy_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant;      \n      try eapply dirty_ppage_gss_copy; eauto.\n    Qed.\n\n    Section ALLOC.\n\n      Lemma alloc_high_level_inv:\n        forall d d' i n,\n          alloc_spec i d = Some (d', n) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        inv H0. constructor; simpl; eauto.\n        - intros; eapply LAT_kern_norm; eauto. eapply _x.\n        - intros; eapply LAT_usr_norm; eauto.\n        - eapply alloc_container_valid'; eauto.\n        - eapply Lconsistent_ppage_norm_alloc; eauto.\n        - intros; congruence.\n        - eapply dirty_ppage_gso_alloc; eauto.\n        - eapply consistent_pmap_gso_at_false; eauto. apply _x.\n        - eapply consistent_pmap_domain_gso_at_false; eauto. apply _x.\n        - eapply consistent_lat_domain_gss_nil; eauto.\n        - zmap_solve.\n      Qed.\n      \n      Lemma alloc_low_level_inv:\n        forall d d' n n' i,\n          alloc_spec i d = Some (d', n) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        inv H0. constructor; eauto.\n      Qed.\n\n      Lemma alloc_kernel_mode:\n        forall d d' i n,\n          alloc_spec i d = Some (d', n) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n      Qed.\n\n      Global Instance alloc_inv: PreservesInvariants alloc_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply alloc_low_level_inv; eassumption.\n        - eapply alloc_high_level_inv; eassumption.\n        - eapply alloc_kernel_mode; eassumption.\n      Qed.\n\n    End ALLOC.\n\n    Global Instance pfree_inv: PreservesInvariants pfree_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n      - intros; eapply LAT_kern_norm; eauto. \n      - intros; eapply LAT_usr_norm; eauto.\n      - eapply Lconsistent_ppage_norm_undef; eauto.\n      - eapply dirty_ppage_gso_undef; eauto.\n      - eapply consistent_pmap_gso_pperm_alloc; eauto.\n      - eapply consistent_pmap_domain_gso_at_0; eauto.\n      - eapply consistent_lat_domain_gss_nil; eauto.\n    Qed.\n\n    Global Instance trapin_inv: PrimInvariants trapin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance trapout_inv: PrimInvariants trapout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance hostin_inv: PrimInvariants hostin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance hostout_inv: PrimInvariants hostout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance ptin_inv: PrimInvariants ptin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance ptout_inv: PrimInvariants ptout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance fstore_inv: PreservesInvariants fstore_spec.\n    Proof.\n      split; intros; inv_generic_sem H; inv H0; functional inversion H2.\n      - functional inversion H. split; trivial.        \n      - functional inversion H.\n        split; subst; simpl; \n        try (eapply dirty_ppage_store_unmaped; try reflexivity; try eassumption); trivial. \n      - functional inversion H0.\n        split; simpl; try assumption.\n    Qed.\n\n    Global Instance setPT_inv: PreservesInvariants setPT_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n    Qed.\n\n    Global Instance pmap_init_inv: PreservesInvariants pmap_init_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant.\n      - apply real_nps_range.\n      - apply real_lat_kern_valid.\n      - apply real_lat_usr_valid.\n      - apply real_container_valid.\n      - rewrite init_pperm0; try assumption.\n        apply Lreal_pperm_valid.        \n      - eapply real_pt_PMap_valid; eauto.\n      - apply real_pt_PMap_kern.\n      - omega.\n      - assumption.\n      - apply real_idpde_init.\n      - apply real_pt_consistent_pmap. \n      - apply real_pt_consistent_pmap_domain. \n      - apply Lreal_at_consistent_lat_domain.\n    Qed.\n\n    Global Instance clearCR2_inv: PreservesInvariants clearCR2_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n    Qed.\n\n    Section PTINSERT.\n      \n      Section PTINSERT_PTE.\n\n        Lemma ptInsertPTE_high_level_inv:\n          forall d d' n vadr padr p,\n            ptInsertPTE0_spec n vadr padr p d = Some d' ->\n            high_level_invariant d ->\n            high_level_invariant d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n          inv H0; constructor_gso_simpl_tac; intros.\n          - eapply LAT_kern_norm; eauto. \n          - eapply LAT_usr_norm; eauto.\n          - eapply Lconsistent_ppage_norm; eassumption.\n          - eapply PMap_valid_gso_valid; eauto.\n          - functional inversion H2. functional inversion H1. \n            eapply PMap_kern_gso; eauto.\n          - functional inversion H2. functional inversion H0.\n            eapply consistent_pmap_ptp_same; try eassumption.\n            eapply consistent_pmap_gso_pperm_alloc'; eassumption.\n          - functional inversion H2.\n            eapply consistent_pmap_domain_append; eauto.\n            destruct (ZMap.get pti pdt); try contradiction;\n            red; intros (v0 & p0 & He); contra_inv. \n          - eapply consistent_lat_domain_gss_append; eauto.\n            subst pti; destruct (ZMap.get (PTX vadr) pdt); try contradiction;\n            red; intros (v0 & p0 & He); contra_inv. \n        Qed.\n\n        Lemma ptInsertPTE_low_level_inv:\n          forall d d' n vadr padr p n',\n            ptInsertPTE0_spec n vadr padr p d = Some d' ->\n            low_level_invariant n' d ->\n            low_level_invariant n' d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n          inv H0. constructor; eauto.\n        Qed.\n\n        Lemma ptInsertPTE_kernel_mode:\n          forall d d' n vadr padr p,\n            ptInsertPTE0_spec n vadr padr p d = Some d' ->\n            kernel_mode d ->\n            kernel_mode d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n        Qed.\n\n      End PTINSERT_PTE.\n\n      Section PTALLOCPDE.\n\n        Lemma ptAllocPDE_high_level_inv:\n          forall d d' n vadr v,\n            ptAllocPDE0_spec n vadr d = Some (d', v) ->\n            high_level_invariant d ->\n            high_level_invariant d'.\n        Proof.\n          intros. functional inversion H; subst; eauto. \n          inv H0; constructor_gso_simpl_tac; intros.\n          - eapply LAT_kern_norm; eauto. eapply _x.\n          - eapply LAT_usr_norm; eauto.\n          - eapply alloc_container_valid'; eauto.\n          - apply Lconsistent_ppage_norm_hide; try assumption.\n          - congruence.\n          - eapply PMap_valid_gso_pde_unp; eauto.\n            eapply real_init_PTE_defined.\n          - functional inversion H3. \n            eapply PMap_kern_gso; eauto.\n          - eapply dirty_ppage_gss; eauto.\n          - eapply consistent_pmap_ptp_gss; eauto; apply _x.\n          - eapply consistent_pmap_domain_gso_at_false; eauto; try apply _x.\n            eapply consistent_pmap_domain_ptp_unp; eauto.\n            apply real_init_PTE_unp.\n          - apply consistent_lat_domain_gss_nil; eauto.\n            apply consistent_lat_domain_gso_p; eauto.\n          - zmap_solve.\n        Qed.\n\n        Lemma ptAllocPDE_low_level_inv:\n          forall d d' n vadr v n',\n            ptAllocPDE0_spec n vadr d = Some (d', v) ->\n            low_level_invariant n' d ->\n            low_level_invariant n' d'.\n        Proof.\n          intros. functional inversion H; try congruence; subst; eauto.\n          inv H0. constructor; eauto.\n        Qed.\n\n        Lemma ptAllocPDE_kernel_mode:\n          forall d d' n vadr v,\n            ptAllocPDE0_spec n vadr d = Some (d', v) ->\n            kernel_mode d ->\n            kernel_mode d'.\n        Proof.\n          intros. functional inversion H; try congruence; subst; eauto.\n        Qed.\n\n      End PTALLOCPDE.\n\n      Lemma ptInsert_high_level_inv:\n        forall d d' n vadr padr p v,\n          ptInsert0_spec n vadr padr p d = Some (d', v) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        - eapply ptInsertPTE_high_level_inv; eassumption.\n        - eapply ptAllocPDE_high_level_inv; eassumption.\n        - eapply ptInsertPTE_high_level_inv; try eassumption.\n          eapply ptAllocPDE_high_level_inv; eassumption.\n      Qed.\n\n      Lemma ptInsert_low_level_inv:\n        forall d d' n vadr padr p n' v,\n          ptInsert0_spec n vadr padr p d = Some (d', v) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        - eapply ptInsertPTE_low_level_inv; eassumption.\n        - eapply ptAllocPDE_low_level_inv; eassumption.\n        - eapply ptInsertPTE_low_level_inv; try eassumption.\n          eapply ptAllocPDE_low_level_inv; eassumption.\n      Qed.\n\n      Lemma ptInsert_kernel_mode:\n        forall d d' n vadr padr p v,\n          ptInsert0_spec n vadr padr p d = Some (d', v) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        - eapply ptInsertPTE_kernel_mode; eassumption.\n        - eapply ptAllocPDE_kernel_mode; eassumption.\n        - eapply ptInsertPTE_kernel_mode; try eassumption.\n          eapply ptAllocPDE_kernel_mode; eassumption.\n      Qed.\n\n    End PTINSERT.\n\n    Section PTRESV.\n\n      Lemma ptResv_high_level_inv:\n        forall d d' n vadr p v,\n          ptResv_spec n vadr p d = Some (d', v) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        eapply ptInsert_high_level_inv; try eassumption.\n        eapply alloc_high_level_inv; eassumption.\n      Qed.\n\n      Lemma ptResv_low_level_inv:\n        forall d d' n vadr p n' v,\n          ptResv_spec n vadr p d = Some (d', v) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        eapply ptInsert_low_level_inv; try eassumption.\n        eapply alloc_low_level_inv; eassumption.\n      Qed.\n\n      Lemma ptResv_kernel_mode:\n        forall d d' n vadr p v,\n          ptResv_spec n vadr p d = Some (d', v) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        eapply ptInsert_kernel_mode; try eassumption.\n        eapply alloc_kernel_mode; eassumption.\n      Qed.\n\n      Global Instance ptResv_inv: PreservesInvariants ptResv_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply ptResv_low_level_inv; eassumption.\n        - eapply ptResv_high_level_inv; eassumption.\n        - eapply ptResv_kernel_mode; eassumption.\n      Qed.\n\n    End PTRESV.\n\n    Section PTRESV2.\n\n      Lemma ptResv2_high_level_inv:\n        forall d d' n vadr p n' vadr' p' v,\n          ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros; functional inversion H; subst; eauto;\n        eapply ptInsert_high_level_inv; try eassumption.\n        - eapply alloc_high_level_inv; eassumption.\n        - eapply ptInsert_high_level_inv; try eassumption.\n          eapply alloc_high_level_inv; eassumption.\n      Qed.\n\n      Lemma ptResv2_low_level_inv:\n        forall d d' n vadr p n' vadr' p' l v,\n          ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n          low_level_invariant l d ->\n          low_level_invariant l d'.\n      Proof.\n        intros; functional inversion H; subst; eauto;\n        eapply ptInsert_low_level_inv; try eassumption.\n        - eapply alloc_low_level_inv; eassumption.\n        - eapply ptInsert_low_level_inv; try eassumption.\n          eapply alloc_low_level_inv; eassumption.\n      Qed.\n\n      Lemma ptResv2_kernel_mode:\n        forall d d' n vadr p n' vadr' p' v,\n          ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros; functional inversion H; subst; eauto;\n        eapply ptInsert_kernel_mode; try eassumption.\n        - eapply alloc_kernel_mode; eassumption.\n        - eapply ptInsert_kernel_mode; try eassumption.\n          eapply alloc_kernel_mode; eassumption.\n      Qed.\n\n      Global Instance ptResv2_inv: PreservesInvariants ptResv2_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply ptResv2_low_level_inv; eassumption.\n        - eapply ptResv2_high_level_inv; eassumption.\n        - eapply ptResv2_kernel_mode; eassumption.\n      Qed.\n\n    End PTRESV2.\n\n    Global Instance pt_new_inv: PreservesInvariants pt_new_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2;\n       rename i into id, i0 into q, z into i.\n      - exploit split_container_valid; eauto.\n        eapply container_split_some; eauto.\n        auto.\n      - unfold update_cusage, update_cchildren; zmap_solve.\n    Qed.\n\n    Global Instance set_shared_mem_state_inv: \n      PreservesInvariants set_shared_mem_state_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n    Qed.\n\n    Global Instance set_shared_mem_seen_inv: \n      PreservesInvariants set_shared_mem_seen_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n    Qed.\n\n    Global Instance set_shared_mem_loc_inv: \n      PreservesInvariants set_shared_mem_loc_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n    Qed.\n\n    Global Instance clear_shared_mem_inv: \n      PreservesInvariants clear_shared_mem_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n    Qed.\n\n    Global Instance device_output_inv: PreservesInvariants device_output_spec.\n    Proof. \n      preserves_invariants_simpl'' low_level_invariant high_level_invariant; eauto.\n    Qed.\n\n  End INV.\n\n  (** * Specification of primitives that will be implemented at this layer*)\n  Definition exec_loadex {F V} := exec_loadex2 (F := F) (V := V).\n\n  Definition exec_storeex {F V} :=  exec_storeex2 (flatmem_store:= flatmem_store) (F := F) (V := V).\n\n  Global Instance flatmem_store_inv: FlatmemStoreInvariant (flatmem_store:= flatmem_store).\n  Proof.\n    split; inversion 1; intros. \n    - functional inversion H0. split; trivial.\n    - functional inversion H1. \n      split; simpl; try (eapply dirty_ppage_store_unmaped'; try reflexivity; try eassumption); trivial.\n  Qed.\n\n  Global Instance trapinfo_set_inv: TrapinfoSetInvariant.\n  Proof.\n    split; inversion 1; intros; constructor; auto.\n  Qed.\n\n  (** * Layer Definition *)\n  Definition mshareintro_fresh : compatlayer (cdata RData) :=\n    clear_shared_mem ↦ gensem clear_shared_mem_spec\n                     ⊕ get_shared_mem_state ↦ gensem get_shared_mem_state_spec\n                     ⊕ get_shared_mem_seen ↦ gensem get_shared_mem_seen_spec\n                     ⊕ get_shared_mem_loc ↦ gensem get_shared_mem_loc_spec\n                     ⊕ set_shared_mem_state ↦ gensem set_shared_mem_state_spec\n                     ⊕ set_shared_mem_seen ↦ gensem set_shared_mem_seen_spec\n                     ⊕ set_shared_mem_loc ↦ gensem set_shared_mem_loc_spec.\n\n  Definition mshareintro_passthrough : compatlayer (cdata RData) :=\n    fload ↦ gensem fload_spec\n          ⊕ fstore ↦ gensem fstore_spec\n          ⊕ flatmem_copy ↦ gensem flatmem_copy_spec\n          ⊕ vmxinfo_get ↦ gensem vmxinfo_get_spec\n          ⊕ device_output ↦ gensem device_output_spec\n          ⊕ pfree ↦ gensem pfree_spec\n          ⊕ set_pt ↦ gensem setPT_spec\n          ⊕ pt_read ↦ gensem ptRead_spec\n          ⊕ pt_resv ↦ gensem ptResv_spec\n          ⊕ pt_resv2 ↦ gensem ptResv2_spec\n          ⊕ pt_new ↦ gensem pt_new_spec\n          (*⊕ pt_free ↦ gensem pt_free_spec*)\n          ⊕ pmap_init ↦ gensem pmap_init_spec\n\n          ⊕ pt_in ↦ primcall_general_compatsem' ptin_spec (prim_ident:= pt_in)\n          ⊕ pt_out ↦ primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)\n          ⊕ clear_cr2 ↦ gensem clearCR2_spec\n          ⊕ container_get_nchildren ↦ gensem container_get_nchildren_spec\n          ⊕ container_get_quota ↦ gensem container_get_quota_spec\n          ⊕ container_get_usage ↦ gensem container_get_usage_spec\n          ⊕ container_can_consume ↦ gensem container_can_consume_spec\n          ⊕ container_alloc ↦ gensem alloc_spec\n          ⊕ trap_in ↦ primcall_general_compatsem trapin_spec\n          ⊕ trap_out ↦ primcall_general_compatsem trapout_spec\n          ⊕ host_in ↦ primcall_general_compatsem hostin_spec\n          ⊕ host_out ↦ primcall_general_compatsem hostout_spec\n          ⊕ trap_get ↦ primcall_trap_info_get_compatsem trap_info_get_spec\n          ⊕ trap_set ↦ primcall_trap_info_ret_compatsem trap_info_ret_spec\n          ⊕ accessors ↦ {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.\n\n  Definition mshareintro : compatlayer (cdata RData) := mshareintro_fresh ⊕ mshareintro_passthrough.\n\nEnd WITHMEM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/MShareIntro.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.2398313585667088}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom extructures Require Import ord fset fmap.\nFrom CoqUtils Require Import word.\nRequire Import lib.utils lib.ssr_list_utils common.types.\nRequire Import cfi.property cfi.classes.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule Abs.\n\nOpen Scope bool_scope.\n\nSection WithClasses.\n\nContext (mt : machine_types).\nContext {ops : machine_ops mt}.\nContext {opss : machine_ops_spec ops}.\n\nOpen Scope word_scope.\n\nLocal Notation word := (mword mt).\nLocal Notation \"x .+1\" := (x + 1).\n\nLocal Notation imemory := {fmap word -> word}.\nLocal Notation dmemory := {fmap word -> word}.\nLocal Notation registers := {fmap reg mt -> word}.\n\nRecord state := State {\n  imem : imemory;\n  dmem : dmemory;\n  regs : registers;\n  pc   : word;\n  cont : bool (* machine stops when this is false;\n                 this starts out as true in initial state *)\n}.\n\nDefinition cfi_abs_state_eq (s1 s2 : state) :=\n  [&& imem s1 == imem s2,\n      dmem s1 == dmem s2,\n      regs s1 == regs s2,\n      pc s1 == pc s2 &\n      cont s1 == cont s2].\n\nLemma cfi_abs_state_eqP : Equality.axiom cfi_abs_state_eq.\nProof.\nmove=> [?????] [?????]; apply/(iffP idP).\n  by case/and5P=> /=; do !move => /= /eqP ->.\nby case; do !move => ->; rewrite /cfi_abs_state_eq !eqxx.\nQed.\n\nDefinition cfi_abs_state_eqMixin := EqMixin cfi_abs_state_eqP.\nCanonical cfi_abs_state_eqType :=\n  Eval hnf in EqType state cfi_abs_state_eqMixin.\n\n(* Para-virtualizing system calls, since CFI doesn't have any system\n   calls of its own and dealing with them is an interesting problem *)\nRecord syscall := Syscall {\n  sem : state -> option state\n}.\n\nDefinition syscall_table := {fmap word -> syscall}.\n\nVariable table : syscall_table.\n\nContext {ids : cfi_id mt}.\n\nVariable cfg : id -> id -> bool.\n\nDefinition valid_jmp := classes.valid_jmp cfg.\n\nImplicit Types imem : imemory.\nImplicit Types dmem : dmemory.\nImplicit Types reg : registers.\n\nInductive step : state -> state -> Prop :=\n| step_nop : forall imem dmem reg pc i,\n             forall (FETCH : imem pc = Some i),\n             forall (INST : decode_instr i = Some (Nop _)),\n             step (State imem dmem reg pc true) (State imem dmem reg pc.+1 true)\n| step_const : forall imem dmem reg reg' pc i n r,\n             forall (FETCH : imem pc = Some i),\n             forall (INST : decode_instr i = Some (Const n r)),\n             forall (UPD : updm reg r (swcast n) = Some reg'),\n             step (State imem dmem reg pc true) (State imem dmem reg' pc.+1 true)\n| step_mov : forall imem dmem reg reg' pc i r1 r2 w1,\n             forall (FETCH : imem pc = Some i),\n             forall (INST : decode_instr i = Some (Mov r1 r2)),\n             forall (R1W : reg r1 = Some w1),\n             forall (UPD : updm reg r2 w1 = Some reg'),\n             step (State imem dmem reg pc true) (State imem dmem reg' pc.+1 true)\n| step_binop : forall imem dmem reg reg' pc i f r1 r2 r3 w1 w2,\n             forall (FETCH : imem pc = Some i),\n             forall (INST : decode_instr i = Some (Binop f r1 r2 r3)),\n             forall (R1W : reg r1 = Some w1),\n             forall (R2W : reg r2 = Some w2),\n             forall (UPD : updm reg r3 (binop_denote f w1 w2) = Some reg'),\n             step (State imem dmem reg pc true) (State imem dmem reg' pc.+1 true)\n| step_load : forall imem dmem reg reg' pc i r1 r2 w1 w2,\n             forall (FETCH : imem pc = Some i),\n             forall (INST : decode_instr i = Some (Load r1 r2)),\n             forall (R1W : reg r1 = Some w1),\n             forall (MEM1 : imem w1 = Some w2 \\/ dmem w1 = Some w2),\n             forall (UPD : updm reg r2 w2 = Some reg'),\n             step (State imem dmem reg pc true) (State imem dmem reg' pc.+1 true)\n| step_store : forall imem dmem dmem' reg pc i r1 r2 w1 w2,\n             forall (FETCH : imem pc = Some i),\n             forall (INST : decode_instr i = Some (Store r1 r2)),\n             forall (R1W : reg r1 = Some w1),\n             forall (R2W : reg r2 = Some w2),\n             forall (UPD : updm dmem w1 w2 = Some dmem'),\n             step (State imem dmem reg pc true) (State imem dmem' reg pc.+1 true)\n| step_jump : forall imem dmem reg pc i r w b,\n             forall (FETCH : imem pc = Some i),\n             forall (INST : decode_instr i = Some (Jump r)),\n             forall (RW : reg r = Some w),\n             forall (VALID : valid_jmp pc w = b),\n             step (State imem dmem reg pc true) (State imem dmem reg w b)\n| step_bnz : forall imem dmem reg pc i r n w,\n             forall (FETCH : imem pc = Some i),\n             forall (INST : decode_instr i = Some (Bnz r n)),\n             forall (RW : reg r = Some w),\n             let pc' := pc + (if w == 0 then 1 else swcast n) in\n             step (State imem dmem reg pc true) (State imem dmem reg pc' true)\n| step_jal : forall imem dmem reg reg' pc i r w b,\n             forall (FETCH : imem pc = Some i),\n             forall (INST : decode_instr i = Some (Jal r)),\n             forall (RW : reg r = Some w),\n             forall (UPD : updm reg ra (pc.+1) = Some reg'),\n             forall (VALID : valid_jmp pc w = b),\n             step (State imem dmem reg pc true) (State imem dmem reg' w b)\n| step_syscall : forall imem dmem dmem' reg reg' pc pc' sc,\n                 forall (FETCH : imem pc = None),\n                 forall (NOUSERM : dmem pc = None),\n                 forall (GETCALL : table pc = Some sc),\n                 forall (CALL : sem sc (State imem dmem reg pc true) =\n                                Some (State imem dmem' reg' pc' true)),\n                 step (State imem dmem reg pc true)\n                      (State imem dmem' reg' pc' true).\n\nInductive step_a : state -> state -> Prop :=\n| step_attack : forall imem dmem dmem' reg reg' pc b\n             (MSAME: domm dmem = domm dmem')\n             (RSAME: domm reg = domm reg'),\n             step_a (State imem dmem reg pc b)\n                    (State imem dmem' reg' pc b).\n\n(* Extending valid_jmp to a complete allowed CFG *)\nDefinition succ (st : state) (st' : state) : bool :=\n  let '(State imem dmem reg pc _) := st in\n  let '(State _ _ _ pc' _) := st' in\n  match (imem pc) with\n    | Some i =>\n      match decode_instr i with\n        | Some (Jump r) => valid_jmp pc pc'\n        | Some (Jal r) => valid_jmp pc pc'\n        | Some (Bnz r imm) => (pc' == pc .+1) || (pc' == pc + swcast imm)\n        | None => false\n        | _ => pc' == pc .+1\n      end\n    | None =>\n      match dmem pc with\n        | Some _ => false\n        | None =>\n          match table pc with\n            | Some sc => true\n              (* This allows monitor service to return anywhere *)\n              (* An alternative would be restricting this to the value\n                 in the ra register (which should be the same at the end\n                 of the system call to what it was before it) *)\n            | None => false\n          end\n      end\n  end.\n\nDefinition initial (s : state) :=\n  cont s.\n\nDefinition all_attacker (xs : seq state) : Prop :=\n  forall x1 x2, In2 x1 x2 xs -> step_a x1 x2.\n\nDefinition all_stuck (xs : seq state) : Prop :=\n  forall x, x \\in xs -> ~ exists s, step x s.\n\nDefinition stopping (xs : seq state) : Prop :=\n  all_attacker xs /\\ all_stuck xs.\n\nProgram Instance abstract_cfi_machine : cfi_machine := {\n  state := [eqType of state];\n  initial s := initial s;\n\n  step := step;\n  step_a := step_a;\n\n  succ := succ;\n  stopping := stopping\n}.\n\nLemma step_succ_violation ast ast' :\n   ~~ succ ast ast' ->\n   step ast ast' ->\n   cont ast /\\ ~~ cont ast'.\nProof.\n  intros SUCC STEP.\n  inversion STEP; subst; simpl in SUCC; rewrite FETCH in SUCC;\n  try rewrite INST in SUCC;\n  try (rewrite eqxx in SUCC; congruence);\n  try (destruct (w == 0)); try (rewrite eqxx ?orbT in SUCC);\n  try (rewrite RW in SUCC);\n  try rewrite GETCALL NOUSERM in SUCC;\n  try congruence; auto.\nQed.\n\nLemma step_a_violation ast ast' :\n   step_a ast ast' ->\n   cont ast = cont ast'.\nProof.\n  intros STEP.\n  inversion STEP; subst. reflexivity.\nQed.\n\nLemma all_attacker_red ast ast' axs :\n  all_attacker (ast :: ast' :: axs) ->\n  all_attacker (ast' :: axs).\nProof.\n  intros ATTACKER asi asj IN2.\n  assert (IN2' : In2 asi asj (ast :: ast' :: axs))\n    by (simpl; auto).\n  apply ATTACKER in IN2'.\n  assumption.\nQed.\n\nLemma all_stuck_red ast ast' axs :\n  all_stuck (ast :: ast' :: axs) ->\n  all_stuck (ast' :: axs).\nProof.\n  intros ALLS asi IN.\n  unfold all_stuck in ALLS.\n  have IN' : asi \\in (ast :: ast' :: axs)\n    by rewrite inE IN orbT.\n  auto.\nQed.\n\nLemma stuck_states_preserved_by_a asi tl :\n  all_attacker (asi :: tl) ->\n  ~~ cont asi ->\n  forall asj, asj \\in tl -> ~~ cont asj.\nProof.\n  intros ALLATTACKER CONT asj IN.\n  move: asi ALLATTACKER CONT.\n  induction tl; intros.\n  - done.\n  - rewrite !inE in IN; case/orP: IN.\n    + move=> /eqP ?; subst a.\n      assert (IN2: In2 asi asj (asi :: asj :: tl))\n        by (simpl; auto).\n      apply ALLATTACKER in IN2.\n      destruct (step_a_violation IN2).\n      assumption.\n    + assert (IN2: In2 asi a (asi :: a :: tl))\n        by (simpl; auto).\n      apply ALLATTACKER in IN2.\n      assert (CONT' := step_a_violation IN2).\n      rewrite CONT' in CONT.\n      apply all_attacker_red in ALLATTACKER.\n      move => /IHtl {IHtl} IHtl; eapply IHtl; eauto.\nQed.\n\nLemma stuck_trace s s' xs s'' :\n  interm (@cfi_step abstract_cfi_machine) (s :: xs) s s'' ->\n  ~~ cont s ->\n  s' \\in s :: xs ->\n  ~ exists s''', step s' s'''.\nProof.\n  intros INTERM CONT IN (s''' & STEP).\n  induction INTERM as [? ? STEP'|? ? ? ? STEP' INTERM'].\n  - rewrite !inE in IN. case/orP: IN; move=> /eqP *; subst.\n    + inv STEP; by discriminate.\n    + destruct STEP' as [STEPA | STEPN].\n      * inv STEPA; simpl in *;\n        inv STEP; by discriminate.\n      * inv STEPN; by discriminate.\n  - rewrite !inE in IN; case/orP: IN => [/eqP ? | IN]; subst;\n    [inv STEP; by discriminate | subst].\n    destruct STEP' as [STEPA | STEPN].\n    + inv STEPA.\n      simpl in *.\n      by auto.\n    + inv STEPN; by discriminate.\nQed.\n\nTheorem cfi : cfi abstract_cfi_machine.\nProof.\n  unfold cfi.\n  intros.\n  clear INIT.\n  induction INTERM as [s s' STEP | s s' s'' xs STEP INTERM ].\n  - unfold trace_has_at_most_one_violation.\n    destruct STEP as [STEPA | STEPN].\n    + left. unfold trace_has_cfi.\n      intros si sj INTRACE STEP.\n      have [SUCC//|SUCC] := boolP (succ si sj).\n      destruct (step_succ_violation SUCC STEP) as [CONT1 CONT2].\n      assert (CONTRA := step_a_violation STEPA).\n      destruct INTRACE as [[? ?]|INTRACE]; subst.\n      * by rewrite -CONTRA CONT1 in CONT2.\n      * by (inv INTRACE).\n    + unfold trace_has_cfi.\n      have [SUCC|SUCC] := boolP (succ s s').\n      * left. intros.\n        destruct INTRACE as [[? ?]|INTRACE];\n        [subst; by assumption | by (inv INTRACE)].\n      * right.\n        exists s; exists s'; do 2 exists [::].\n        simpl; repeat split; try (auto || intros ? ? IN2; by (destruct IN2)).\n        intros ? IN [s0 STEP]; rewrite inE in IN; move/eqP in IN; subst.\n        destruct (step_succ_violation SUCC STEPN) as [H1 H2].\n        inv STEP; simpl in H2; by discriminate.\n  - unfold trace_has_at_most_one_violation in IHINTERM.\n    destruct IHINTERM as [TCFI | [sv1 [sv2 [hs [tl VIOLATION]]]]].\n    { (*case no violation in the trace*)\n      destruct STEP as [STEPA | STEPN].\n      - left. unfold trace_has_cfi.\n        intros si sj INTRACE STEP.\n        have [SUCC|SUCC] := boolP (succ si sj); first assumption.\n        destruct (step_succ_violation SUCC STEP) as [CONT1 CONT2];\n        assert (CONTRA := step_a_violation STEPA);\n        destruct xs; first (by inv INTRACE);\n        apply interm_first_step in INTERM; subst;\n        destruct INTRACE as [[? ?]|INTRACE]; subst.\n        + by rewrite -CONTRA CONT1 in CONT2.\n        + by auto.\n      - have [SUCC|SUCC] := boolP (succ s s').\n        + left. intros ? ? INTRACE STEP.\n          destruct xs; first (by inv INTRACE).\n          apply interm_first_step in INTERM; subst.\n          destruct INTRACE as [[? ?]|INTRACE];\n            [subst; by assumption | by auto].\n        + right.\n          destruct xs; first (by inv INTERM).\n          assert (EQ := interm_first_step INTERM); subst.\n          exists s; exists s'; exists [::]; exists xs.\n          simpl; repeat split;\n          try (auto || intros ? ? IN2; by (destruct IN2)).\n          { intros ? ? IN2.\n            assert (STEP := interm_in2_step INTERM IN2).\n            destruct STEP as [STEPA | STEPN']; first (by assumption).\n            unfold trace_has_cfi in TCFI.\n            exfalso.\n            destruct (step_succ_violation SUCC STEPN) as [CONT1 CONT2].\n            clear TCFI SUCC.\n            apply In2_implies_In in IN2.\n            eapply stuck_trace; eauto.\n          }\n          { intros x IN (s0 & STEP).\n            destruct (step_succ_violation SUCC STEPN) as [CONT1 CONT2].\n            eapply stuck_trace; eauto.\n          }\n    }\n    { destruct VIOLATION as [LST [[STEPV SUCC] [HCFI [TCFI STOP]]]].\n      right.\n      exists sv1; exists sv2; exists (s :: hs); exists tl.\n      repeat split;\n        try solve [rewrite LST; reflexivity\n                  | auto\n                  | simpl in STOP; destruct STOP; assumption].\n      intros si sj IN2 STEPN.\n      destruct hs.\n      - destruct IN2 as [[? ?]|CONTRA];\n        [subst | destruct CONTRA].\n        have [SUCC'|SUCC'] := boolP (succ si sj); first (by assumption).\n        destruct (step_succ_violation SUCC' STEPN) as [CONT1 CONT2].\n        inv STEPV; by discriminate.\n      - destruct IN2 as [[? ?]|IN2]; subst.\n        + have [SUCC'|SUCC'] := boolP (succ si sj); first (by assumption).\n          destruct (step_succ_violation SUCC' STEPN) as [CONT1 CONT2].\n          exfalso.\n          simpl in INTERM.\n          remember (hs ++ sv1 :: sv2 :: tl) as lst.\n          assert (Heq: sj :: hs ++ sv1 :: sv2 :: tl = sj :: lst)\n            by (rewrite Heqlst; reflexivity).\n          rewrite Heq in INTERM.\n          have IN: sv1 \\in (sj :: hs) ++ sv1 :: (sv2 :: tl).\n            by rewrite mem_cat !inE eqxx /= !orbT; auto.\n          simpl ((sj :: hs) ++ sv1 :: sv2 :: tl) in IN.\n          rewrite  Heq in IN.\n          assert (EQ := interm_first_step INTERM); subst.\n          eapply stuck_trace; eauto.\n        + apply HCFI; by assumption.\n    }\nQed.\n\nEnd WithClasses.\n\nNotation imemory mt := {fmap mword mt -> mword mt}.\nNotation dmemory mt := {fmap mword mt -> mword mt}.\nNotation registers mt := {fmap reg mt -> mword mt}.\n\nEnd Abs.\n\nArguments Abs.State {_} _ _ _ _ _.\n\nCanonical Abs.cfi_abs_state_eqType.\n", "meta": {"author": "micro-policies", "repo": "micro-policies-coq", "sha": "28163163c88387fc24475ed219f5705f9e0d4fc6", "save_path": "github-repos/coq/micro-policies-micro-policies-coq", "path": "github-repos/coq/micro-policies-micro-policies-coq/micro-policies-coq-28163163c88387fc24475ed219f5705f9e0d4fc6/cfi/abstract.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.23983135856670879}}
{"text": "From stdpp Require Import base gmap.\nFrom mathcomp Require Import ssreflect.\nFrom stdpp Require Import namespaces.\nFrom iris.algebra Require Import agree auth csum gset gmap excl namespace_map frac.\nFrom iris.heap_lang Require Import notation proofmode.\nFrom cryptis Require Import lib term cryptis primitives tactics.\nFrom cryptis Require Import session nsl dh.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection NSLDH.\n\nContext `{!cryptisG Σ, !heapG Σ, !sessionG Σ}.\nNotation iProp := (iProp Σ).\n\nImplicit Types t : term.\nImplicit Types rl : role.\n\nVariable N : namespace.\nVariable P : role → term → term → term → term → iProp.\n\nLtac protocol_failure :=\n  by intros; wp_pures; iApply (\"Hpost\" $! None).\n\nDefinition nsl_dh_init : val := λ: \"c\" \"g\" \"skA\" \"pkA\" \"pkB\",\n  let: \"a\" := mkdh #() in\n  let: \"ga\" := texp (tgroup \"g\") \"a\" in\n  bind: \"gb\" := nsl_init (N.@\"nsl\") \"c\" \"skA\" \"pkA\" \"pkB\" \"ga\" in\n  SOME (texp \"gb\" \"a\").\n\nDefinition nsl_dh_resp : val := λ: \"c\" \"g\" \"skB\" \"pkB\",\n  let: \"b\" := mkdh #() in\n  let: \"gb\" := texp (tgroup \"g\") \"b\" in\n  bind: \"res\" := nsl_resp (N.@\"nsl\") \"c\" \"skB\" \"pkB\" \"gb\" in\n  let: \"pkA\" := Fst \"res\" in\n  let: \"ga\" := Snd \"res\" in\n  SOME (\"pkA\", texp \"ga\" \"b\").\n\nImplicit Types Ψ : val → iProp.\nImplicit Types kA kB : term.\n\nDefinition nsl_dh_inv g rl ga gb kA kB : iProp :=\n  P rl ga gb kA kB ∗\n  match rl with\n  | Init =>\n    ∃ a, ⌜ga = TExp g [a]⌝ ∧\n    □ ∀ b, (pterm (TExp g [a; b]) → ◇ pterm b)\n  | Resp =>\n    ∃ b, ⌜gb = TExp g [b]⌝ ∧\n    □ ∀ a, (pterm (TExp g [a; b]) → ◇ pterm a)\n  end%I.\n\nDefinition nsl_dh_ctx g γ :=\n  nsl_ctx (@dh_meta _ _) (N.@\"nsl\") (nsl_dh_inv g) γ.\n\nLemma nsl_dh_alloc g E E' :\n  ↑N ⊆ E →\n  enc_pred_token E ={E'}=∗ ∃ γ, nsl_dh_ctx g γ.\nProof.\nmove=> sub; apply: nsl_alloc; solve_ndisj.\nQed.\n\nDefinition nsl_dh_fail (k : term) a : iProp :=\n  ∃ k', dh_meta a (N.@\"peer\") k' ∧ corruption k k'.\n\nLemma pterm_nsl_dh1 g a k k' :\n  sterm g -∗\n  dh_seed (nsl_dh_fail k) a -∗\n  dh_meta (TExp g [a]) (N.@\"peer\") k' -∗\n  pterm (TExp g [a]) ↔ ▷ corruption k k'.\nProof.\niIntros \"#gP #a_pred #meta\"; iSplit.\n- iIntros \"#p_e\".\n  iDestruct (dh_seed_elim1 with \"a_pred p_e\") as (k'') \"[meta' corr]\".\n  iModIntro.\n  by iPoseProof (term_meta_agree with \"meta meta'\") as \"<-\".\n- iIntros \"#corr\".\n  iApply dh_pterm_TExp; eauto.\n  by iExists k'; iModIntro; iModIntro; iSplit; eauto.\nQed.\n\nLemma pterm_nsl_dh2 g a k t :\n  dh_seed (nsl_dh_fail k) a -∗\n  pterm (TExp g [a; t]) -∗ ◇ pterm t.\nProof.\niIntros \"#a_pred #p_e\".\nby iPoseProof (dh_seed_elim2 with \"a_pred p_e\") as \">[??]\".\nQed.\n\nLemma wp_nsl_dh_init Q c γ g kA kB E Ψ :\n  ↑cryptisN ⊆ E →\n  ↑N ⊆ E →\n  channel c -∗\n  nsl_dh_ctx g γ -∗\n  sterm g -∗\n  pterm (TKey Enc kA) -∗\n  pterm (TKey Enc kB) -∗\n  (∀ ga gb, |==> P Init ga gb kA kB ∗ Q Init ga gb kA kB) -∗\n  (∀ ogab : option term,\n      (if ogab is Some gab then ∃ a gb,\n         ⌜gab = Spec.texp gb a⌝ ∧\n         sterm gab ∧\n         Q Init (TExp g [a]) gb kA kB ∗\n         (corruption kA kB ∨\n          ∃ b, ⌜gb = TExp g [b]⌝ ∗\n               P Resp (TExp g [a]) (TExp g [b]) kA kB ∗\n               □ (pterm gab → ▷ False))\n       else True) -∗\n      Ψ (repr ogab)) -∗\n  WP nsl_dh_init c g (TKey Dec kA) (TKey Enc kA) (TKey Enc kB) @ E {{ Ψ }}.\nProof.\niIntros (??) \"#cP #ctx #s_g #p_e_kA #p_e_kB init Hpost\".\nrewrite /nsl_dh_init; wp_pures; wp_bind (mknonce _).\niApply (wp_mkdh (nsl_dh_fail kA) g).\niIntros (a) \"#s_a #a_pred token\".\nrewrite (term_meta_token_difference _ (↑N.@\"peer\")); last solve_ndisj.\niDestruct \"token\" as \"[dh token]\".\niMod (term_meta_set _ _ kB with \"dh\") as \"#dh\"; eauto.\nwp_pures; wp_bind (tgroup _); iApply wp_tgroup.\nwp_pures; wp_bind (texp _ _); iApply wp_texp.\nrewrite Spec.texpA; wp_pures; wp_bind (nsl_init _ _ _ _ _ _).\niApply (wp_nsl_init (nsl_dh_inv g) Q\n          with \"cP ctx p_e_kA p_e_kB [] [] [init] [token]\") => //.\n- solve_ndisj.\n- rewrite sterm_TExp /=; iSplit => //.\n  by rewrite /=; iSplit.\n- by iModIntro; iApply pterm_nsl_dh1.\n- iIntros (nB); rewrite /=.\n  iMod (\"init\" $! (TExp g [a]) nB) as \"[init resp]\"; iModIntro.\n  iFrame.\n  iExists a; iSplit => //.\n  iModIntro; iIntros (b) \"p_b\".\n  by iApply pterm_nsl_dh2.\n- rewrite (term_meta_token_difference _ (↑N.@\"nsl\")); last solve_ndisj.\n  by iDestruct \"token\" as \"[token _]\".\niIntros (onB) \"pub\"; case: onB=> [nB|]; last by protocol_failure.\niDestruct \"pub\" as \"[#s_nB [init [#fail | [resp #succ]]]]\".\n  wp_pures; wp_bind (texp _ _); iApply wp_texp; wp_pures.\n  iApply (\"Hpost\" $! (Some (Spec.texp nB a))).\n  iModIntro; iExists _, _; iSplit; eauto.\n  iSplit; first by iApply sterm_texp => //.\n  iFrame; by eauto.\niDestruct \"succ\" as (b) \"(-> & #succ)\".\nwp_pures; wp_bind (texp _ _); iApply wp_texp; wp_pures.\niApply (\"Hpost\" $! (Some (Spec.texp (TExp g [b]) a))).\niModIntro; iExists _, _; iSplit => //.\niSplit; first by iApply sterm_texp => //.\niFrame.\niRight; iExists b.\nrewrite Spec.texpA; iSplit => //; iFrame.\niIntros \"!> #contra\".\niDestruct (\"succ\" with \"contra\") as \"{succ} >succ\".\nby iApply dh_seed_elim0.\nQed.\n\nLemma wp_nsl_dh_resp Q c γ g kB E Ψ :\n  ↑cryptisN ⊆ E →\n  ↑N ⊆ E →\n  channel c -∗\n  nsl_dh_ctx g γ -∗\n  sterm g -∗\n  pterm (TKey Enc kB) -∗\n  (∀ ga gb kA, |==> P Resp ga gb kA kB ∗ Q Resp ga gb kA kB) -∗\n  (∀ oresp : option (term * term),\n      (if oresp is Some (pkA, gab) then\n         ∃ kA b ga,\n           ⌜pkA = TKey Enc kA⌝ ∧\n           ⌜gab = Spec.texp ga b⌝ ∧\n           pterm pkA ∧\n           sterm gab ∧\n           Q Resp ga (TExp g [b]) kA kB ∗\n           (corruption kA kB ∨\n            ∃ a, ⌜ga = TExp g [a]⌝ ∗\n                  P Init ga (TExp g [b]) kA kB ∗\n                  □ (pterm gab → ▷ False))\n       else True) -∗\n      Ψ (repr oresp)) -∗\n  WP nsl_dh_resp c g (TKey Dec kB) (TKey Enc kB) @ E {{ Ψ }}.\nProof.\niIntros (??) \"#? #ctx #s_g #p_e_kB resp Hpost\".\nrewrite /nsl_dh_resp; wp_pures; wp_bind (mkdh _).\niApply (wp_mkdh (nsl_dh_fail kB)).\niIntros (b) \"#s_b #b_pred token\".\nrewrite (term_meta_token_difference _ (↑N.@\"peer\")); last solve_ndisj.\niDestruct \"token\" as \"[dh token]\".\nwp_pures; wp_bind (tgroup _); iApply wp_tgroup.\nwp_pures; wp_bind (texp _ _); iApply wp_texp.\nrewrite Spec.texpA; wp_pures; wp_bind (nsl_resp _ _ _ _ _).\niApply (wp_nsl_resp (nsl_dh_inv g) Q \n          with \"[//] ctx p_e_kB [token] [] [resp dh]\") => //.\n- solve_ndisj.\n- rewrite (term_meta_token_difference _ (↑N.@\"nsl\")); last solve_ndisj.\n  by iDestruct \"token\" as \"[token _]\".\n- by rewrite sterm_TExp /=; iSplit; eauto.\n- iIntros (kA nA).\n  iMod (term_meta_set _ _ kA with \"dh\") as \"#meta\"; eauto.\n  iMod (\"resp\" $! nA (TExp g [b]) kA) as \"[resp init]\".\n  iModIntro; iSplit.\n  + iModIntro; rewrite [corruption _ _]comm; by iApply pterm_nsl_dh1.\n  + iFrame; iExists b; iSplit => //.\n    iIntros \"!> %\".\n    rewrite -[ [a; b]]/(seq.cat [a] [b]) TExpC /=.\n    by iIntros \"#?\"; iApply pterm_nsl_dh2.\niIntros ([[pkA nA]|]) \"resp\"; last by protocol_failure.\niDestruct \"resp\" as (kA) \"(-> & #p_e_kA & #s_nA & #p_nA & inv)\".\nwp_pures; wp_bind (texp _ _); iApply wp_texp; wp_pures.\niApply (\"Hpost\" $! (Some (TKey Enc kA, Spec.texp nA b))).\niModIntro; iExists _, _, _; do 4!iSplit => //; eauto.\n  by iApply sterm_texp.\niDestruct \"inv\" as \"[? inv]\"; iFrame.\niDestruct \"inv\" as \"[inv|[resp inv]]\"; eauto.\niDestruct \"inv\" as (t) \"[-> #inv]\".\nrewrite Spec.texpA.\nrewrite -[ [b; t]]/(seq.cat [b] [t]) TExpC /=.\niRight; iExists _; iSplit => //; iFrame.\niIntros \"!> #contra\".\niSpecialize (\"inv\" with \"contra\").\niDestruct \"inv\" as \">inv\".\nby iApply dh_seed_elim0.\nQed.\n\nEnd NSLDH.\n\nArguments nsl_dh_ctx {Σ _ _ _} N P g γ.\nArguments nsl_dh_alloc {Σ _ _ _} N P g E E'.\nArguments wp_nsl_dh_init {Σ _ _ _ N} P Q.\nArguments wp_nsl_dh_resp {Σ _ _ _ N} P Q.\n", "meta": {"author": "arthuraa", "repo": "cryptis", "sha": "056d1fb93b8d8395b0c19639edb961d4919c63f6", "save_path": "github-repos/coq/arthuraa-cryptis", "path": "github-repos/coq/arthuraa-cryptis/cryptis-056d1fb93b8d8395b0c19639edb961d4919c63f6/nsl_dh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.23983134956404145}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.lib.Axioms.\n\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import VST.sepcomp.mem_lemmas.\n\n(** * Concurrent Machine Semantics *)\n\n(** NOTE: In the code, we call interaction semantics [CoreSemantics]. *)\n\n(** The [G] type parameter is the type of global environments, the type\n    [SCH] is the type of schedules, the type [C] is the type of\n    machine states  *)\n\n(** [initial_core] produces the core state (and memory) corresponding to an entry\n   point of a module.  The arguments are the genv, a pointer to the\n   function to run, and the arguments for that function. *)\n\n(** [halted] indicates when a machine state has reached a halted state,\n   for now this means the schedule ran out. *)\n\n(** [thread_step] is the fundamental small-step relation for the\n   sequential semantics. *)\n\n(** [machine_step] is the extern, small-step machine steps. These\n    represent the synchronisation primitives and schedule operations. *)\n\n(** The remaining properties give basic sanity properties which constrain\n   the behavior of programs. *)\n(** -2 a state cannot both step and be halted, and *)\n\nDefinition option_proj {A: Type} (default: A) (x: option A) :=\n match x with Some y => y | None => default end.\n\nRecord ConcurSemantics {G TID SCH TR C M res: Type} : Type :=\n  { initial_machine : option res -> M -> C (*-> M*) -> M -> val -> list val -> Prop\n    ; conc_halted : SCH -> C -> option val\n    ; thread_step : G -> SCH -> C -> M -> C -> M -> Prop\n    ; machine_step : G -> SCH -> TR -> C -> M -> SCH -> TR -> C -> M -> Prop\n    ; running_thread : C -> TID -> Prop\n    ; thread_step_not_halted:\n      forall ge  U m q  m' q', thread_step ge U q m q' m' -> conc_halted U q = None\n    ; machine_step_not_halted:\n        forall ge  U m tr q  U' m' tr' q', machine_step ge U tr q m U' tr' q' m' -> conc_halted U q = None\n   } .\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/concurrency/common/machine_semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.2398313495640414}}
{"text": "Require Export MicroBFTtacts.\n\n\nSection MicroBFTbreak.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext          }.\n  Context { microbft_context    : MicroBFT_context      }.\n  Context { m_initial_keys      : MicroBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys     }.\n  Context { usig_hash           : USIG_hash             }.\n  Context { microbft_auth       : MicroBFT_auth         }.\n\n\n  Lemma on_comp_MicroBFTlocalSys_new :\n    forall r s u l {A} (F : n_proc 2 (msg_comp_name 0) -> A) (m : A),\n      on_comp (MicroBFTlocalSys_new r s u l) F m\n      = F (MicroBFT_replicaSM_new r s).\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite on_comp_MicroBFTlocalSys_new : microbft.\n\n  Lemma decr_n_procs_MicroBFTlocalSys_new :\n    forall r s u l,\n      decr_n_procs (MicroBFTlocalSys_new r s u l)\n      = MicroBFTsubs_new u l.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite decr_n_procs_MicroBFTlocalSys_new : microbft.\n\n  Lemma M_break_MicroBFT_state_update :\n    forall {O} r s m subs (F : n_procs 1 -> option MAIN_state * DirectedMsgs -> O),\n      M_break (MAIN_update r s m) subs F\n      = match m with\n        | MicroBFT_request _ => M_break (interp_s_proc (handle_request r s m)) subs F\n        | MicroBFT_commit  _ => M_break (interp_s_proc (handle_commit  r s m)) subs F\n        | MicroBFT_accept  _ => M_break (interp_s_proc (handle_accept  r s m)) subs F\n        end.\n  Proof.\n    destruct m; introv; simpl; auto.\n  Qed.\n  Hint Rewrite @M_break_MicroBFT_state_update : microbft.\n\n  Lemma M_break_USIG_update :\n    forall {O} s i subs (F : n_procs 0 -> option USIG_state * USIG_output_interface  -> O),\n      M_break (USIG_update s i) subs F\n      = match i with\n        | create_ui_in r => M_break (interp_s_proc (let (s',ui) := create_UI r s in [R](s',create_ui_out ui))) subs F\n        | verify_ui_in (r,ui) => M_break (interp_s_proc (let b := verify_UI r ui s in [R](s,verify_ui_out b))) subs F\n        end.\n  Proof.\n    destruct i; repnd; introv; simpl; auto.\n  Qed.\n  Hint Rewrite @M_break_USIG_update : microbft.\n\n  Lemma M_break_LOG_update :\n    forall {O} l i subs (F : n_procs 0 -> option LOG_state * LOG_output_interface  -> O),\n      M_break (LOG_update l i) subs F\n      = match i with\n        | log_new r => M_break (interp_s_proc (let l' :=  r :: l in [R](l',log_out true))) subs F\n        end.\n  Proof.\n    destruct i; repnd; introv; simpl; auto.\n  Qed.\n  Hint Rewrite @M_break_LOG_update : microbft.\n\n  Lemma M_break_call_proc_USIGname_MicroBFTsubs_new :\n    forall {O} i u l (F : n_procs 1 -> USIG_output_interface -> O),\n      M_break\n        (call_proc USIGname i)\n        (MicroBFTsubs_new u l)\n        F\n      = M_break\n          (USIG_update u i)\n          (decr_n_procs (MicroBFTsubs_new u l))\n          (fun subs out =>\n             F (bind_op (MicroBFTsubs_new u l)\n                        (fun s => MicroBFTsubs_new s l)\n                        (fst out))\n               (snd out)).\n  Proof.\n    introv.\n    simpl.\n    destruct i; repnd; simpl; tcsp.\n  Qed.\n  Hint Rewrite @M_break_call_proc_USIGname_MicroBFTsubs_new : microbft2.\n\n  Lemma M_break_call_proc_LOGname_MicroBFTsubs_new :\n    forall {O} i u l (F : n_procs 1 -> LOG_output_interface -> O),\n      M_break\n        (call_proc LOGname i)\n        (MicroBFTsubs_new u l)\n        F\n      = M_break\n          (LOG_update l i)\n          (decr_n_procs (MicroBFTsubs_new u l))\n          (fun subs out =>\n             F (bind_op (MicroBFTsubs_new u l)\n                        (fun s => MicroBFTsubs_new u s)\n                        (fst out))\n               (snd out)).\n  Proof.\n    introv.\n    simpl.\n    destruct i; repnd; simpl; tcsp.\n  Qed.\n  Hint Rewrite @M_break_call_proc_LOGname_MicroBFTsubs_new : microbft2.\n\n  Lemma M_break_call_proc_USIGname_MicroBFTsubs :\n    forall {O} i n (F : n_procs 1 -> USIG_output_interface -> O),\n      M_break\n        (call_proc USIGname i)\n        (MicroBFTsubs n)\n        F\n      = M_break\n          (USIG_update (USIG_initial n) i)\n          (decr_n_procs (MicroBFTsubs n))\n          (fun subs out =>\n             F (bind_op (MicroBFTsubs n)\n                        (fun s => MicroBFTsubs_new_u s)\n                        (fst out))\n               (snd out)).\n  Proof.\n    introv.\n    simpl.\n    destruct i; repnd; simpl; tcsp.\n  Qed.\n  Hint Rewrite @M_break_call_proc_USIGname_MicroBFTsubs : microbft2.\n\n  Lemma M_break_call_proc_LOGname_MicroBFTsubs :\n    forall {O} i n (F : n_procs 1 -> LOG_output_interface -> O),\n      M_break\n        (call_proc LOGname i)\n        (MicroBFTsubs n)\n        F\n      = M_break\n          (LOG_update LOG_initial i)\n          (decr_n_procs (MicroBFTsubs n))\n          (fun subs out =>\n             F (bind_op (MicroBFTsubs n)\n                        (fun s => MicroBFTsubs_new_l n s)\n                        (fst out))\n               (snd out)).\n  Proof.\n    introv.\n    simpl.\n    destruct i; repnd; simpl; tcsp.\n  Qed.\n  Hint Rewrite @M_break_call_proc_LOGname_MicroBFTsubs : microbft2.\n\n  Lemma M_break_call_proc_USIGname_MicroBFTsubs_new_u :\n    forall {O} i u (F : n_procs 1 -> USIG_output_interface -> O),\n      M_break\n        (call_proc USIGname i)\n        (MicroBFTsubs_new_u u)\n        F\n      = M_break\n          (USIG_update u i)\n          (decr_n_procs (MicroBFTsubs_new_u u))\n          (fun subs out =>\n             F (bind_op (MicroBFTsubs_new_u u)\n                        (fun s => MicroBFTsubs_new_u s)\n                        (fst out))\n               (snd out)).\n  Proof.\n    introv.\n    simpl.\n    destruct i; repnd; simpl; tcsp.\n  Qed.\n  Hint Rewrite @M_break_call_proc_USIGname_MicroBFTsubs_new_u : microbft2.\n\n  Lemma M_break_call_proc_LOGname_MicroBFTsubs_new_u :\n    forall {O} i u (F : n_procs 1 -> LOG_output_interface -> O),\n      M_break\n        (call_proc LOGname i)\n        (MicroBFTsubs_new_u u)\n        F\n      = M_break\n          (LOG_update LOG_initial i)\n          (decr_n_procs (MicroBFTsubs_new_u u))\n          (fun subs out =>\n             F (bind_op (MicroBFTsubs_new_u u)\n                        (fun s => MicroBFTsubs_new u s)\n                        (fst out))\n               (snd out)).\n  Proof.\n    introv.\n    simpl.\n    destruct i; repnd; simpl; tcsp.\n  Qed.\n  Hint Rewrite @M_break_call_proc_LOGname_MicroBFTsubs_new_u : microbft2.\n\n  Lemma M_break_call_proc_USIGname_MicroBFTsubs_new_l :\n    forall {O} i n l (F : n_procs 1 -> USIG_output_interface -> O),\n      M_break\n        (call_proc USIGname i)\n        (MicroBFTsubs_new_l n l)\n        F\n      = M_break\n          (USIG_update (USIG_initial n) i)\n          (decr_n_procs (MicroBFTsubs_new_l n l))\n          (fun subs out =>\n             F (bind_op (MicroBFTsubs_new_l n l)\n                        (fun s => MicroBFTsubs_new s l)\n                        (fst out))\n               (snd out)).\n  Proof.\n    introv.\n    simpl.\n    destruct i; repnd; simpl; tcsp.\n  Qed.\n  Hint Rewrite @M_break_call_proc_USIGname_MicroBFTsubs_new_l : microbft2.\n\n  Lemma M_break_call_proc_LOGname_MicroBFTsubs_new_l :\n    forall {O} i n l (F : n_procs 1 -> LOG_output_interface -> O),\n      M_break\n        (call_proc LOGname i)\n        (MicroBFTsubs_new_l n l)\n        F\n      = M_break\n          (LOG_update l i)\n          (decr_n_procs (MicroBFTsubs_new_l n l))\n          (fun subs out =>\n             F (bind_op (MicroBFTsubs_new_l n l)\n                        (fun s => MicroBFTsubs_new_l n s)\n                        (fst out))\n               (snd out)).\n  Proof.\n    introv.\n    simpl.\n    destruct i; repnd; simpl; tcsp.\n  Qed.\n  Hint Rewrite @M_break_call_proc_LOGname_MicroBFTsubs_new_l : microbft2.\n\n  Lemma M_break_call_create_ui :\n    forall {A n} {O}\n           (m    : nat)\n           (d    : unit -> Proc A)\n           (f    : UI -> Proc A)\n           (subs : n_procs n)\n           (F    : n_procs n -> A -> O),\n      M_break (interp_proc (call_create_ui m d f)) subs F\n      = M_break (call_proc USIGname (create_ui_in m))\n                subs\n                (fun subs out =>\n                   on_create_ui_out\n                     (fun ui => M_break (interp_proc (f ui)) subs F)\n                     (fun _ => M_break (interp_proc (d tt)) subs F)\n                     out).\n  Proof.\n    introv.\n    unfold call_create_ui; simpl.\n    rewrite M_break_bind; simpl.\n    apply eq_M_break; introv.\n    destruct s; simpl; auto; smash_microbft.\n  Qed.\n  Hint Rewrite @M_break_call_create_ui : microbft.\n\n  Lemma M_break_call_verify_ui :\n    forall {A n} {O}\n           (mui  : nat * UI)\n           (d    : unit -> Proc A)\n           (f    : unit -> Proc A)\n           (subs : n_procs n)\n           (F    : n_procs n -> A -> O),\n      M_break (interp_proc (call_verify_ui mui d f)) subs F\n      = M_break (call_proc USIGname (verify_ui_in mui))\n                subs\n                (fun subs out =>\n                   if_true_verify_ui_out\n                     (fun _ => M_break (interp_proc (f tt)) subs F)\n                     (fun _ => M_break (interp_proc (d tt)) subs F)\n                     out).\n  Proof.\n    introv.\n    unfold call_verify_ui; simpl.\n    rewrite M_break_bind; simpl.\n    apply eq_M_break; introv.\n    destruct s; simpl; auto; smash_microbft.\n  Qed.\n  Hint Rewrite @M_break_call_verify_ui : microbft.\n\n  Definition lower_out_break {n} {A} {B}\n             (l : n_procs (S n))\n             (F : n_procs (S n) -> A -> B) : n_procs n -> A -> B :=\n    fun k a => F (update_subs l k) a.\n\n  Lemma M_break_M_run_sm_on_input_MicroBFT_replicaSM_new :\n    forall {O} r s m subs (F : n_procs 2 -> option MAIN_state * DirectedMsgs -> O),\n      M_break (M_run_sm_on_input (MicroBFT_replicaSM_new r s) m) subs F\n      = match m with\n        | MicroBFT_request _ => M_break (interp_s_proc (handle_request r s m)) (decr_n_procs subs) (lower_out_break subs F)\n        | MicroBFT_commit  _ => M_break (interp_s_proc (handle_commit  r s m)) (decr_n_procs subs) (lower_out_break subs F)\n        | MicroBFT_accept  _ => M_break (interp_s_proc (handle_accept  r s m)) (decr_n_procs subs) (lower_out_break subs F)\n        end.\n  Proof.\n    introv.\n    unfold M_run_sm_on_input.\n    destruct m; introv; simpl; auto;\n      try (complete (unfold M_on_decr, M_break, MAIN_update;\n                     simpl; repeat dest_cases w; ginv)).\n  Qed.\n  Hint Rewrite @M_break_M_run_sm_on_input_MicroBFT_replicaSM_new : microbft.\n\n  Lemma state_of_component_cons_same :\n    forall {cn} {n} (p : n_proc n cn) (l : n_procs n),\n      state_of_component cn (MkPProc cn p :: l) = Some (sm2state p).\n  Proof.\n    introv; unfold state_of_component; simpl; dest_cases w; simpl.\n    rewrite (UIP_refl_CompName _ w); auto.\n  Qed.\n  Hint Rewrite @state_of_component_cons_same : comp.\n\n  Lemma state_of_component_USIGname :\n    forall m (u : n_proc 1 USIGname) l,\n      state_of_component USIGname\n                         [MkPProc (msg_comp_name 0) m,\n                          MkPProc USIGname u,\n                          MkPProc LOGname l] = Some (sm2state u).\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite state_of_component_USIGname : microbft.\n\n  Lemma state_of_component_LOGname :\n    forall m u (l : n_proc 1 LOGname),\n      state_of_component LOGname\n                         [MkPProc (msg_comp_name 0) m,\n                          MkPProc USIGname u,\n                          MkPProc LOGname l] = Some (sm2state l).\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite state_of_component_LOGname : microbft.\n\nEnd MicroBFTbreak.\n\nHint Rewrite @M_break_MicroBFT_state_update : microbft.\nHint Rewrite @M_break_call_proc_USIGname_MicroBFTsubs_new : microbft2.\nHint Rewrite @M_break_call_proc_LOGname_MicroBFTsubs_new : microbft2.\nHint Rewrite @M_break_call_proc_USIGname_MicroBFTsubs : microbft2.\nHint Rewrite @M_break_call_proc_LOGname_MicroBFTsubs : microbft2.\nHint Rewrite @M_break_call_proc_USIGname_MicroBFTsubs_new_u : microbft2.\nHint Rewrite @M_break_call_proc_LOGname_MicroBFTsubs_new_u : microbft2.\nHint Rewrite @M_break_call_proc_USIGname_MicroBFTsubs_new_l : microbft2.\nHint Rewrite @M_break_call_proc_LOGname_MicroBFTsubs_new_l : microbft2.\nHint Rewrite @M_break_call_create_ui : microbft.\nHint Rewrite @M_break_call_verify_ui : microbft.\nHint Rewrite @M_break_USIG_update : microbft.\nHint Rewrite @M_break_LOG_update : microbft.\nHint Rewrite @M_break_M_run_sm_on_input_MicroBFT_replicaSM_new : microbft.\nHint Rewrite @on_comp_MicroBFTlocalSys_new : microbft.\nHint Rewrite @decr_n_procs_MicroBFTlocalSys_new : microbft.\nHint Rewrite @state_of_component_USIGname : microbft.\nHint Rewrite @state_of_component_LOGname : microbft.\n\n\nHint Rewrite @state_of_component_cons_same : comp.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MicroBFTbreak.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2397680644768405}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Abhishek Anand & Vincent Rahli & Mark Bickford\n\n*)\n\n\nRequire Export per_props_squash.\nRequire Export sequents.\n\n\nLemma teq_and_eq_if_squash {o} :\n  forall lib (a : @NTerm o) s1 s2 H wa ca1 ca2,\n    hyps_functionality lib s1 H\n    -> similarity lib s1 s2 H\n    -> inhabited_type lib (lsubstc a wa s1 ca1)\n    -> tequality lib (lsubstc a wa s1 ca1) (lsubstc a wa s2 ca2)\n    -> (tequality lib\n          (mkc_squash (lsubstc a wa s1 ca1))\n          (mkc_squash (lsubstc a wa s2 ca2))\n        # (inhabited_type lib (lsubstc a wa s1 ca1))).\nProof.\n  introv hf sim ceq1 ceq2.\n\n  assert (hyps_functionality lib s2 H)\n    as hf2\n      by (apply @similarity_hyps_functionality_trans with (s1 := s1); auto).\n\n  assert (similarity lib s2 s1 H) as sim21 by (apply similarity_sym; auto).\n  assert (similarity lib s1 s1 H) as sim11 by (apply similarity_refl in sim; auto).\n  assert (similarity lib s2 s2 H) as sim22 by (apply similarity_refl in sim21; auto).\n\n  dands; auto.\n  rw @tequality_mkc_squash; auto.\nQed.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/per/sequents_squash.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2397680644768405}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Bool.\nRequire Import Arith.\nRequire Import NArith Ndec.\nRequire Import ZArith.\nFrom IntMap Require Import Allmaps.\nRequire Import bases.\nRequire Import defs.\nRequire Import semantics.\nRequire Import refcorrect.\nRequire Import lattice_fixpoint.\nRequire Import coacc_test.\n\n(* fonction de suppression des états non coaccessibles *)\n\nFixpoint non_coacc_kill (d : preDTA) (m : Map bool) {struct m} : preDTA :=\n  match d, m with\n  | M0, M0 => M0 state\n  | M1 a s, M1 a' b => if Neqb a a' && b then M1 state a s else M0 state\n  | M2 x y, M2 z t => M2 state (non_coacc_kill x z) (non_coacc_kill y t)\n  | _, _ => M0 state\n  end.\n\nDefinition predta_kill_non_coacc (d : preDTA) (a : ad) : preDTA :=\n  non_coacc_kill d (predta_coacc_states d a).\n\nDefinition dta_kill_non_coacc (d : DTA) : DTA :=\n  match d with\n  | dta p a => dta (predta_kill_non_coacc p a) a\n  end.\n\nDefinition predta_kill_non_coacc_lazy (d : preDTA) \n  (a : ad) : preDTA := non_coacc_kill d (predta_coacc_states_0 d a).\n\nDefinition dta_kill_non_coacc_lazy (d : DTA) : DTA :=\n  match d with\n  | dta p a => dta (predta_kill_non_coacc_lazy p a) a\n  end.\n\nLemma kill_non_coacc_lazy_eq_kill_non_coacc :\n forall d : DTA, dta_kill_non_coacc_lazy d = dta_kill_non_coacc d.\nProof.\n\tintros. unfold dta_kill_non_coacc_lazy, dta_kill_non_coacc in |- *.\n\tunfold predta_kill_non_coacc_lazy, predta_kill_non_coacc in |- *.\n\tunfold predta_coacc_states, predta_coacc_states_0 in |- *. induction  d as (p, a).\n\trewrite\n  (lazy_power_eg_power bool eqm_bool (predta_coacc p a) \n     (map_mini state p) (S (MapCard state p))). reflexivity.\n\tsplit. exact (eqm_bool_equal a0 b). intros. rewrite H.\n\texact (equal_eqm_bool b).\nQed.\n\n(* démo : un état apparait dans non_coacc_kill ssi il est coacc *)\n\nLemma non_coacc_kill_0 :\n forall (d : preDTA) (a : ad) (s : state) (m : Map bool),\n ensemble_base state d m ->\n MapGet state d a = Some s ->\n MapGet bool m a = Some true ->\n MapGet state (non_coacc_kill d m) a = Some s.\nProof.\n\tsimple induction d; intros. inversion H0. induction  m as [| a2 a3| m1 Hrecm1 m0 Hrecm0]; simpl in H1. inversion H1. simpl in H0. simpl in |- *. elim (bool_is_true_or_false (Neqb a a1)); intros. rewrite H2 in H0. elim (bool_is_true_or_false (Neqb a2 a1)); intros; rewrite H3 in H1;\n  inversion H1. rewrite (Neqb_complete _ _ H2). rewrite (Neqb_complete _ _ H3).\n\trewrite (Neqb_correct a1). simpl in |- *. rewrite (Neqb_correct a1). inversion H0. reflexivity. rewrite H2 in H0.\n\tinversion H0. inversion H. induction  m1 as [| a0 a1| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. inversion H1.\n\tinversion H1. simpl in |- *. unfold ensemble_base in H1. elim H1.\n\tintros. induction  a as [| p]; simpl in |- *; simpl in H2; simpl in H3.\n\texact (H _ _ _ H4 H2 H3). induction  p as [p Hrecp| p Hrecp| ]; simpl in |- *; simpl in H2;\n  simpl in H3. exact (H0 _ _ _ H5 H2 H3). exact (H _ _ _ H4 H2 H3). exact (H0 _ _ _ H5 H2 H3).\nQed.\n\nLemma non_coacc_kill_1 :\n forall (d : preDTA) (a : ad) (s : state) (m : Map bool),\n ensemble_base state d m ->\n MapGet state (non_coacc_kill d m) a = Some s ->\n MapGet state d a = Some s /\\ MapGet bool m a = Some true.\nProof.\n\tsimple induction d; intros. induction  m as [| a0 a1| m1 Hrecm1 m0 Hrecm0]; inversion H0.\n\tinduction  m as [| a2 a3| m1 Hrecm1 m0 Hrecm0]. inversion H. simpl in H. simpl in H0.\n\telim (bool_is_true_or_false (Neqb a a2)); intros; rewrite H1 in H0. elim (bool_is_true_or_false a3); intros; rewrite H2 in H0. simpl in H0. elim (bool_is_true_or_false (Neqb a a1)); intros; rewrite H3 in H0;\n  inversion H0. rewrite (Neqb_complete _ _ H1).\n\tsimpl in |- *. rewrite <- (Neqb_complete _ _ H1). rewrite <- (Neqb_complete _ _ H3). rewrite H2. rewrite (Neqb_correct a). split; reflexivity. simpl in H0.\n\tinversion H0. simpl in H0. inversion H0. inversion H.\n\tinduction  m1 as [| a0 a1| m1_1 Hrecm1_1 m1_0 Hrecm1_0]. inversion H1. inversion H1. unfold ensemble_base in H1. elim H1. intros. induction  a as [| p]; simpl in |- *; simpl in H2. exact (H _ _ _ H3 H2). induction  p as [p Hrecp| p Hrecp| ]; simpl in |- *; simpl in H2. exact (H0 _ _ _ H4 H2).\n\texact (H _ _ _ H3 H2). exact (H0 _ _ _ H4 H2).\nQed.\n\nLemma predta_kill_non_coacc_0 :\n forall (d : preDTA) (a a0 : ad) (s : state),\n preDTA_ref_ok d ->\n (MapGet state d a0 = Some s /\\ coacc d a a0 <->\n  MapGet state (predta_kill_non_coacc d a) a0 = Some s).\nProof.\n\tintros. split. intros. intros. elim (predta_coacc_fix d a a0). intros. intros. elim H0. intros. apply\n  (fun p : ensemble_base state d (predta_coacc_states d a) =>\n   non_coacc_kill_0 d a0 s (predta_coacc_states d a) p H3 (H2 H4)). unfold predta_coacc_states in |- *. apply\n  (power_def_ok bool (ensemble_base state d) (predta_coacc d a)\n     (map_mini state d) (S (MapCard state d))). unfold def_ok_app in |- *.\n\tintros. exact (predta_coacc_def_ok d a x). exact (map_mini_appartient state d). exact H. intros. unfold predta_kill_non_coacc in H0. elim\n  (fun p : ensemble_base state d (predta_coacc_states d a) =>\n   non_coacc_kill_1 d a0 s (predta_coacc_states d a) p H0). intros. split. exact H1.\n\telim (predta_coacc_fix d a a0 H). intros. exact (H3 H2).\n\tunfold predta_coacc_states in |- *. apply\n  (power_def_ok bool (ensemble_base state d) (predta_coacc d a)\n     (map_mini state d) (S (MapCard state d))). unfold def_ok_app in |- *.\n\tintros. exact (predta_coacc_def_ok d a x). exact (map_mini_appartient state d).\nQed.\n\n(* coaccessibilité des états conservée en supprimant les coaccessibles *)\n\nDefinition predta_kill_non_coacc_def_0 (d : preDTA) \n  (a0 a1 : ad) : Prop :=\n  preDTA_ref_ok d ->\n  coacc d a0 a1 -> coacc (predta_kill_non_coacc d a0) a0 a1.\n\nLemma predta_kill_non_coacc_1 :\n forall (d : preDTA) (a : ad) (s : state),\n MapGet state d a = Some s -> predta_kill_non_coacc_def_0 d a a.\nProof.\n\tunfold predta_kill_non_coacc_def_0 in |- *. intros. elim (predta_coacc_fix d a a H0). intros. apply (coacc_id (predta_kill_non_coacc d a) a s).\n\tunfold predta_kill_non_coacc in |- *. apply (non_coacc_kill_0 d a s (predta_coacc_states d a)). unfold predta_coacc_states in |- *.\n\tapply\n  (power_def_ok bool (ensemble_base state d) (predta_coacc d a)\n     (map_mini state d) (S (MapCard state d))). unfold def_ok_app in |- *.\n\tintros. exact (predta_coacc_def_ok d a x). exact (map_mini_appartient state d). exact H. exact (H3 H1).\nQed.\n\nLemma predta_kill_non_coacc_2 :\n forall (d : preDTA) (a0 a1 a2 : ad) (s1 s2 : state) \n   (pl : prec_list) (c : ad),\n MapGet state d a2 = Some s2 ->\n MapGet state d a1 = Some s1 ->\n MapGet prec_list s1 c = Some pl ->\n prec_occur pl a2 ->\n coacc d a0 a1 ->\n predta_kill_non_coacc_def_0 d a0 a1 -> predta_kill_non_coacc_def_0 d a0 a2.\nProof.\n\tunfold predta_kill_non_coacc_def_0 in |- *. intros. apply (coacc_nxt (predta_kill_non_coacc d a0) a0 a1 a2 s1 s2 pl c). elim (predta_kill_non_coacc_0 d a0 a2 s2 H5). intros. apply H7.\n\tsplit. exact H. exact H6. elim (predta_kill_non_coacc_0 d a0 a1 s1 H5). intros. apply H7. split; assumption. exact H1. exact H2.\n\texact (H4 H5 H3).\nQed.\n\nLemma predta_kill_non_coacc_3 :\n forall (d : preDTA) (a0 a1 : ad),\n preDTA_ref_ok d -> coacc d a0 a1 -> coacc (predta_kill_non_coacc d a0) a0 a1.\nProof.\n\tintros. exact\n  (coacc_ind predta_kill_non_coacc_def_0 predta_kill_non_coacc_1\n     predta_kill_non_coacc_2 d a0 a1 H0 H H0).\nQed.\n\n(* sémantique de reconnaissance dans les coaccessibles *)\n\n(* sens trivial : si un terme est reconnu par l'automate où on a kille\nles non coaccessibles alors il est reconnu dans l automate *)\n\nDefinition predta_kill_non_coacc_rec_def_0 (p : preDTA) \n  (a : ad) (t : term) (pr : reconnaissance p a t) :=\n  forall (p0 : preDTA) (m : Map bool),\n  p = non_coacc_kill p0 m ->\n  ensemble_base state p0 m -> reconnaissance p0 a t.\n\nDefinition predta_kill_non_coacc_rec_def_1 (p : preDTA) \n  (s : state) (t : term) (pr : state_reconnait p s t) :=\n  forall (p0 : preDTA) (m : Map bool),\n  p = non_coacc_kill p0 m ->\n  ensemble_base state p0 m -> state_reconnait p0 s t.\n\nDefinition predta_kill_non_coacc_rec_def_2 (p : preDTA) \n  (pl : prec_list) (lt : term_list) (pr : liste_reconnait p pl lt) :=\n  forall (p0 : preDTA) (m : Map bool),\n  p = non_coacc_kill p0 m ->\n  ensemble_base state p0 m -> liste_reconnait p0 pl lt.\n\nLemma predta_kill_non_coacc_rec_0 :\n forall (d : preDTA) (a : ad) (t : term) (ladj : state)\n   (e : MapGet state d a = Some ladj) (s : state_reconnait d ladj t),\n predta_kill_non_coacc_rec_def_1 d ladj t s ->\n predta_kill_non_coacc_rec_def_0 d a t (rec_dta d a t ladj e s).\nProof.\n\tunfold predta_kill_non_coacc_rec_def_1, predta_kill_non_coacc_rec_def_0\n  in |- *.\n\tintros. rewrite H0 in e. apply (rec_dta p0 a t ladj). elim (non_coacc_kill_1 _ _ _ _ H1 e). intros. exact H2. exact (H _ _ H0 H1).\nQed.\n\nLemma predta_kill_non_coacc_rec_1 :\n forall (d : preDTA) (s : state) (c : ad) (tl : term_list) \n   (l : prec_list) (e : MapGet prec_list s c = Some l)\n   (l0 : liste_reconnait d l tl),\n predta_kill_non_coacc_rec_def_2 d l tl l0 ->\n predta_kill_non_coacc_rec_def_1 d s (app c tl) (rec_st d s c tl l e l0).\nProof.\n\tunfold predta_kill_non_coacc_rec_def_1, predta_kill_non_coacc_rec_def_2\n  in |- *.\n\tintros. exact (rec_st p0 s c tl l e (H _ _ H0 H1)).\nQed.\n\nLemma predta_kill_non_coacc_rec_2 :\n forall d : preDTA,\n predta_kill_non_coacc_rec_def_2 d prec_empty tnil (rec_empty d).\nProof.\n\tunfold predta_kill_non_coacc_rec_def_2 in |- *. intros.\n\texact (rec_empty p0).\nQed.\n\nLemma predta_kill_non_coacc_rec_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (r : reconnaissance d a hd),\n predta_kill_non_coacc_rec_def_0 d a hd r ->\n forall l : liste_reconnait d la tl,\n predta_kill_non_coacc_rec_def_2 d la tl l ->\n predta_kill_non_coacc_rec_def_2 d (prec_cons a la ls) \n   (tcons hd tl) (rec_consi d a la ls hd tl r l).\nProof.\n\tunfold predta_kill_non_coacc_rec_def_0, predta_kill_non_coacc_rec_def_2\n  in |- *.\n\tintros. exact (rec_consi p0 a la ls hd tl (H _ _ H1 H2) (H0 _ _ H1 H2)).\nQed.\n\nLemma predta_kill_non_coacc_rec_4 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list) (l : liste_reconnait d ls (tcons hd tl)),\n predta_kill_non_coacc_rec_def_2 d ls (tcons hd tl) l ->\n predta_kill_non_coacc_rec_def_2 d (prec_cons a la ls) \n   (tcons hd tl) (rec_consn d a la ls hd tl l).\nProof.\n\tunfold predta_kill_non_coacc_rec_def_2 in |- *. intros.\n\texact (rec_consn p0 a la ls hd tl (H _ _ H0 H1)).\nQed.\n\nLemma predta_kill_non_coacc_rev :\n forall (p : preDTA) (a : ad) (t : term) (m : Map bool),\n reconnaissance (non_coacc_kill p m) a t ->\n ensemble_base state p m -> reconnaissance p a t.\nProof.\n\tintros. exact\n  (mreconnaissance_ind predta_kill_non_coacc_rec_def_0\n     predta_kill_non_coacc_rec_def_1 predta_kill_non_coacc_rec_def_2\n     predta_kill_non_coacc_rec_0 predta_kill_non_coacc_rec_1\n     predta_kill_non_coacc_rec_2 predta_kill_non_coacc_rec_3\n     predta_kill_non_coacc_rec_4 (non_coacc_kill p m) a t H p m\n     (refl_equal (non_coacc_kill p m)) H0).\nQed.\n\n(* sens moins trivial : si un terme est reconnu par ... *)\n\nInductive reconnaissance_co : preDTA -> ad -> ad -> term -> Prop :=\n    rec_co_dta :\n      forall (d : preDTA) (a b : ad) (t : term) (ladj : state),\n      MapGet state d a = Some ladj ->\n      state_reconnait_co d ladj b t ->\n      coacc d b a -> reconnaissance_co d a b t\nwith state_reconnait_co : preDTA -> state -> ad -> term -> Prop :=\n    rec_co_st :\n      forall (d : preDTA) (s : state) (c b : ad) (tl : term_list)\n        (l : prec_list),\n      MapGet prec_list s c = Some l ->\n      liste_reconnait_co d l b tl -> state_reconnait_co d s b (app c tl)\nwith liste_reconnait_co : preDTA -> prec_list -> ad -> term_list -> Prop :=\n  | rec_co_empty :\n      forall (d : preDTA) (b : ad), liste_reconnait_co d prec_empty b tnil\n  | rec_co_consi :\n      forall (d : preDTA) (a : ad) (la ls : prec_list) \n        (hd : term) (b : ad) (tl : term_list),\n      reconnaissance_co d a b hd ->\n      liste_reconnait_co d la b tl ->\n      liste_reconnait_co d (prec_cons a la ls) b (tcons hd tl)\n  | rec_co_consn :\n      forall (d : preDTA) (a : ad) (la ls : prec_list) \n        (hd : term) (b : ad) (tl : term_list),\n      liste_reconnait_co d ls b (tcons hd tl) ->\n      liste_reconnait_co d (prec_cons a la ls) b (tcons hd tl).\n\nScheme mreconnaissance_co_ind := Induction for reconnaissance_co\n  Sort Prop\n  with mstrec_co_ind := Induction for state_reconnait_co\n  Sort Prop\n  with mlrec_co_ind := Induction for liste_reconnait_co \n  Sort Prop.\n\nDefinition rec_co_def_0 (d : preDTA) (a a1 : ad) (t : term)\n  (pr : reconnaissance_co d a a1 t) :=\n  forall a0 : ad, coacc d a0 a1 -> reconnaissance_co d a a0 t.\n\nDefinition rec_co_def_1 (d : preDTA) (s : state) (a1 : ad) \n  (t : term) (pr : state_reconnait_co d s a1 t) :=\n  forall a0 : ad, coacc d a0 a1 -> state_reconnait_co d s a0 t.\n\nDefinition rec_co_def_2 (d : preDTA) (p : prec_list) \n  (a1 : ad) (tl : term_list) (pr : liste_reconnait_co d p a1 tl) :=\n  forall a0 : ad, coacc d a0 a1 -> liste_reconnait_co d p a0 tl.\n\nLemma rec_co_0 :\n forall (d : preDTA) (a b : ad) (t : term) (ladj : state)\n   (e : MapGet state d a = Some ladj)\n   (s : state_reconnait_co d ladj b t),\n rec_co_def_1 d ladj b t s ->\n forall c : coacc d b a, rec_co_def_0 d a b t (rec_co_dta d a b t ladj e s c).\nProof.\n\tunfold rec_co_def_1, rec_co_def_0 in |- *. intros. exact (rec_co_dta d a a0 t ladj e (H _ H0) (coacc_transitive _ _ _ _ H0 c)).\nQed.\n\nLemma rec_co_1 :\n forall (d : preDTA) (s : state) (c b : ad) (tl : term_list) \n   (l : prec_list) (e : MapGet prec_list s c = Some l)\n   (l0 : liste_reconnait_co d l b tl),\n rec_co_def_2 d l b tl l0 ->\n rec_co_def_1 d s b (app c tl) (rec_co_st d s c b tl l e l0).\nProof.\n\tunfold rec_co_def_2, rec_co_def_1 in |- *. intros. exact (rec_co_st d s c a0 tl l e (H _ H0)).\nQed.\n\nLemma rec_co_2 :\n forall (d : preDTA) (b : ad),\n rec_co_def_2 d prec_empty b tnil (rec_co_empty d b).\nProof.\n\tunfold rec_co_def_2 in |- *. intros. exact (rec_co_empty d a0).\nQed.\n\nLemma rec_co_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term) \n   (b : ad) (tl : term_list) (r : reconnaissance_co d a b hd),\n rec_co_def_0 d a b hd r ->\n forall l : liste_reconnait_co d la b tl,\n rec_co_def_2 d la b tl l ->\n rec_co_def_2 d (prec_cons a la ls) b (tcons hd tl)\n   (rec_co_consi d a la ls hd b tl r l).\nProof.\n\tunfold rec_co_def_0, rec_co_def_2 in |- *. intros. exact (rec_co_consi d a la ls hd a0 tl (H _ H1) (H0 _ H1)).\nQed.\n\nLemma rec_co_4 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term) \n   (b : ad) (tl : term_list) (l : liste_reconnait_co d ls b (tcons hd tl)),\n rec_co_def_2 d ls b (tcons hd tl) l ->\n rec_co_def_2 d (prec_cons a la ls) b (tcons hd tl)\n   (rec_co_consn d a la ls hd b tl l).\nProof.\n\tunfold rec_co_def_2 in |- *. intros. exact (rec_co_consn d a la ls hd a0 tl (H _ H0)).\nQed.\n\nLemma rec_co_5 :\n forall (d : preDTA) (a a0 a1 : ad) (t : term),\n reconnaissance_co d a a1 t -> coacc d a0 a1 -> reconnaissance_co d a a0 t.\nProof.\n\tintros. exact\n  (mreconnaissance_co_ind rec_co_def_0 rec_co_def_1 rec_co_def_2 rec_co_0\n     rec_co_1 rec_co_2 rec_co_3 rec_co_4 d a a1 t H a0 H0).\nQed.\n\nDefinition rec_co_def_3 (t : term) : Prop :=\n  forall (d : preDTA) (a : ad),\n  preDTA_ref_ok d -> reconnaissance d a t -> reconnaissance_co d a a t.\n\nDefinition rec_co_def_4 (d : preDTA) (l : prec_list) \n  (tl : term_list) : Prop :=\n  forall a : ad,\n  preDTA_ref_ok d ->\n  liste_reconnait d l tl ->\n  (forall u : term,\n   term_list_occur u tl ->\n   forall (d : preDTA) (a : ad),\n   preDTA_ref_ok d -> reconnaissance d a u -> reconnaissance_co d a a u) ->\n  (forall b : ad, prec_occur l b -> coacc d a b) ->\n  liste_reconnait_co d l a tl.\n\nLemma rec_co_6 : forall d : preDTA, rec_co_def_4 d prec_empty tnil.\nProof.\n\tunfold rec_co_def_4 in |- *. intros. exact (rec_co_empty d a).\nQed.\n\nLemma rec_co_7 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list),\n reconnaissance d a hd ->\n liste_reconnait d la tl ->\n rec_co_def_4 d la tl -> rec_co_def_4 d (prec_cons a la ls) (tcons hd tl).\nProof.\n\tunfold rec_co_def_4 in |- *. intros. apply (rec_co_consi d a la ls hd a0 tl).\n\texact\n  (rec_co_5 d a a0 a hd (H4 hd (tlo_head hd hd tl (to_eq hd)) d a H2 H)\n     (H5 a (prec_hd a la ls))). apply (H1 a0 H2 H0). intros. exact (H4 u (tlo_tail u hd tl H6) d0 a1 H7 H8). intros. exact (H5 _ (prec_int0 a b la ls H6)).\nQed.\n\nLemma rec_co_8 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term)\n   (tl : term_list),\n liste_reconnait d ls (tcons hd tl) ->\n rec_co_def_4 d ls (tcons hd tl) ->\n rec_co_def_4 d (prec_cons a la ls) (tcons hd tl).\nProof.\n\tunfold rec_co_def_4 in |- *. intros. apply (rec_co_consn d a la ls hd a0 tl).\n\tapply (H0 a0 H1 H). intros. exact (H3 u H5 d0 a1 H6 H7). intros.\n\texact (H4 b (prec_int1 a b la ls H5)).\nQed.\n\nLemma rec_co_9 :\n forall (d : preDTA) (tl : term_list) (a : ad) (l : prec_list),\n liste_reconnait d l tl ->\n (forall u : term,\n  term_list_occur u tl ->\n  forall (d : preDTA) (a : ad),\n  preDTA_ref_ok d -> reconnaissance d a u -> reconnaissance_co d a a u) ->\n (forall b : ad, prec_occur l b -> coacc d a b) ->\n preDTA_ref_ok d -> liste_reconnait_co d l a tl.\nProof.\n\tintros. exact\n  (liste_reconnait_ind rec_co_def_4 rec_co_6 rec_co_7 rec_co_8 d l tl H a H2\n     H H0 H1).\nQed.\n\nLemma rec_co_10 :\n forall (a : ad) (tl : term_list),\n (forall u : term, term_list_occur u tl -> rec_co_def_3 u) ->\n rec_co_def_3 (app a tl).\nProof.\n\tunfold rec_co_def_3 in |- *. intros. inversion H1. inversion H3.\n\tapply (rec_co_dta d a0 a0 (app a tl) ladj H2). apply (rec_co_st d ladj a a0 tl l H11). apply (rec_co_9 d tl a0 l H12 H). intros. elim (H0 a0 ladj a l b H2 H11 H13). intros.\n\texact\n  (coacc_nxt d a0 a0 b ladj x l a H14 H2 H11 H13 (coacc_id d a0 ladj H2)). exact H0. exact (coacc_id _ _ _ H2).\nQed.\n\nLemma rec_co :\n forall (d : preDTA) (a : ad) (t : term),\n preDTA_ref_ok d -> reconnaissance d a t -> reconnaissance_co d a a t.\nProof.\n\tintros. exact (indprinciple_term rec_co_def_3 rec_co_10 t d a H H0). \nQed.\n\nDefinition rec_co_rec_def_0 (d : preDTA) (a a0 : ad) \n  (t : term) (pr : reconnaissance_co d a a0 t) := reconnaissance d a t.\n\nDefinition rec_co_rec_def_1 (d : preDTA) (s : state) \n  (a0 : ad) (t : term) (pr : state_reconnait_co d s a0 t) :=\n  state_reconnait d s t.\n\nDefinition rec_co_rec_def_2 (d : preDTA) (p : prec_list) \n  (a0 : ad) (tl : term_list) (pr : liste_reconnait_co d p a0 tl) :=\n  liste_reconnait d p tl.\n\nLemma rec_co_rec_0 :\n forall (d : preDTA) (a b : ad) (t : term) (ladj : state)\n   (e : MapGet state d a = Some ladj)\n   (s : state_reconnait_co d ladj b t),\n rec_co_rec_def_1 d ladj b t s ->\n forall c : coacc d b a,\n rec_co_rec_def_0 d a b t (rec_co_dta d a b t ladj e s c).\nProof.\n\tunfold rec_co_rec_def_0, rec_co_rec_def_1 in |- *. intros. exact (rec_dta d a t ladj e H).\nQed.\n\nLemma rec_co_rec_1 :\n forall (d : preDTA) (s : state) (c b : ad) (tl : term_list) \n   (l : prec_list) (e : MapGet prec_list s c = Some l)\n   (l0 : liste_reconnait_co d l b tl),\n rec_co_rec_def_2 d l b tl l0 ->\n rec_co_rec_def_1 d s b (app c tl) (rec_co_st d s c b tl l e l0).\nProof.\n\tunfold rec_co_rec_def_1, rec_co_rec_def_2 in |- *. intros. exact (rec_st d s c tl l e H).\nQed.\n\nLemma rec_co_rec_2 :\n forall (d : preDTA) (b : ad),\n rec_co_rec_def_2 d prec_empty b tnil (rec_co_empty d b).\nProof.\n\tunfold rec_co_rec_def_2 in |- *. intros. exact (rec_empty d).\nQed.\n\nLemma rec_co_rec_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term) \n   (b : ad) (tl : term_list) (r : reconnaissance_co d a b hd),\n rec_co_rec_def_0 d a b hd r ->\n forall l : liste_reconnait_co d la b tl,\n rec_co_rec_def_2 d la b tl l ->\n rec_co_rec_def_2 d (prec_cons a la ls) b (tcons hd tl)\n   (rec_co_consi d a la ls hd b tl r l).\nProof.\n\tunfold rec_co_rec_def_0, rec_co_rec_def_2 in |- *. intros.\n\texact (rec_consi d a la ls hd tl H H0).\nQed.\n\nLemma rec_co_rec_4 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term) \n   (b : ad) (tl : term_list) (l : liste_reconnait_co d ls b (tcons hd tl)),\n rec_co_rec_def_2 d ls b (tcons hd tl) l ->\n rec_co_rec_def_2 d (prec_cons a la ls) b (tcons hd tl)\n   (rec_co_consn d a la ls hd b tl l).\nProof.\n\tunfold rec_co_rec_def_2 in |- *. intros. exact (rec_consn d a la ls hd tl H).\nQed.\n\nLemma rec_co_rec :\n forall (d : preDTA) (a a0 : ad) (t : term),\n reconnaissance_co d a a0 t -> reconnaissance d a t.\nProof.\n\texact\n  (mreconnaissance_co_ind rec_co_rec_def_0 rec_co_rec_def_1 rec_co_rec_def_2\n     rec_co_rec_0 rec_co_rec_1 rec_co_rec_2 rec_co_rec_3 rec_co_rec_4).\nQed.\n\nDefinition rec_nonco_kill_def_0 (d : preDTA) (a a0 : ad) \n  (t : term) (pr : reconnaissance_co d a a0 t) :=\n  preDTA_ref_ok d -> reconnaissance_co (predta_kill_non_coacc d a0) a a0 t.\n\nDefinition rec_nonco_kill_def_1 (d : preDTA) (s : state) \n  (a0 : ad) (t : term) (pr : state_reconnait_co d s a0 t) :=\n  preDTA_ref_ok d -> state_reconnait_co (predta_kill_non_coacc d a0) s a0 t.\n\nDefinition rec_nonco_kill_def_2 (d : preDTA) (p : prec_list) \n  (a0 : ad) (tl : term_list) (pr : liste_reconnait_co d p a0 tl) :=\n  preDTA_ref_ok d -> liste_reconnait_co (predta_kill_non_coacc d a0) p a0 tl.\n\nLemma rec_nonco_kill_0 :\n forall (d : preDTA) (a b : ad) (t : term) (ladj : state)\n   (e : MapGet state d a = Some ladj)\n   (s : state_reconnait_co d ladj b t),\n rec_nonco_kill_def_1 d ladj b t s ->\n forall c : coacc d b a,\n rec_nonco_kill_def_0 d a b t (rec_co_dta d a b t ladj e s c).\nProof.\n\tunfold rec_nonco_kill_def_0, rec_nonco_kill_def_1 in |- *. intros.\n\tapply (rec_co_dta (predta_kill_non_coacc d b) a b t ladj).\n\tunfold predta_kill_non_coacc in |- *. apply (non_coacc_kill_0 d a ladj (predta_coacc_states d b)). unfold predta_coacc_states in |- *. apply\n  (power_def_ok bool (ensemble_base state d) (predta_coacc d b)\n     (map_mini state d) (S (MapCard state d))). unfold def_ok_app in |- *.\n\tintros. exact (predta_coacc_def_ok d b x). exact (map_mini_appartient state d). exact e. elim (predta_coacc_fix d b a H0). intros.\n\texact (H2 c). exact (H H0). exact (predta_kill_non_coacc_3 _ _ _ H0 c).\nQed.\n\nLemma rec_nonco_kill_1 :\n forall (d : preDTA) (s : state) (c b : ad) (tl : term_list) \n   (l : prec_list) (e : MapGet prec_list s c = Some l)\n   (l0 : liste_reconnait_co d l b tl),\n rec_nonco_kill_def_2 d l b tl l0 ->\n rec_nonco_kill_def_1 d s b (app c tl) (rec_co_st d s c b tl l e l0).\nProof.\n\tunfold rec_nonco_kill_def_1, rec_nonco_kill_def_2 in |- *. intros.\n\texact (rec_co_st (predta_kill_non_coacc d b) s c b tl l e (H H0)).\nQed.\n\nLemma rec_nonco_kill_2 :\n forall (d : preDTA) (b : ad),\n rec_nonco_kill_def_2 d prec_empty b tnil (rec_co_empty d b).\nProof.\n\tunfold rec_nonco_kill_def_2 in |- *. intros. exact (rec_co_empty (predta_kill_non_coacc d b) b).\nQed.\n\nLemma rec_nonco_kill_3 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term) \n   (b : ad) (tl : term_list) (r : reconnaissance_co d a b hd),\n rec_nonco_kill_def_0 d a b hd r ->\n forall l : liste_reconnait_co d la b tl,\n rec_nonco_kill_def_2 d la b tl l ->\n rec_nonco_kill_def_2 d (prec_cons a la ls) b (tcons hd tl)\n   (rec_co_consi d a la ls hd b tl r l).\nProof.\n\tunfold rec_nonco_kill_def_0, rec_nonco_kill_def_2 in |- *. intros.\n\texact\n  (rec_co_consi (predta_kill_non_coacc d b) a la ls hd b tl (H H1) (H0 H1)).\nQed.\n\nLemma rec_nonco_kill_4 :\n forall (d : preDTA) (a : ad) (la ls : prec_list) (hd : term) \n   (b : ad) (tl : term_list) (l : liste_reconnait_co d ls b (tcons hd tl)),\n rec_nonco_kill_def_2 d ls b (tcons hd tl) l ->\n rec_nonco_kill_def_2 d (prec_cons a la ls) b (tcons hd tl)\n   (rec_co_consn d a la ls hd b tl l).\nProof.\n\tunfold rec_nonco_kill_def_2 in |- *. intros. exact (rec_co_consn _ a la ls hd b tl (H H0)).\nQed.\n\nLemma rec_nonco_kill :\n forall (d : preDTA) (a a0 : ad) (t : term),\n reconnaissance_co d a a0 t ->\n preDTA_ref_ok d -> reconnaissance_co (predta_kill_non_coacc d a0) a a0 t.\nProof.\n\tintros. exact\n  (mreconnaissance_co_ind rec_nonco_kill_def_0 rec_nonco_kill_def_1\n     rec_nonco_kill_def_2 rec_nonco_kill_0 rec_nonco_kill_1 rec_nonco_kill_2\n     rec_nonco_kill_3 rec_nonco_kill_4 d a a0 t H H0).\nQed.\n\nLemma predta_kill_non_coacc_dir :\n forall (d : preDTA) (a : ad) (t : term),\n preDTA_ref_ok d ->\n reconnaissance d a t ->\n reconnaissance (non_coacc_kill d (predta_coacc_states d a)) a t.\nProof.\n\tintros. exact (rec_co_rec _ _ _ _ (rec_nonco_kill d a a t (rec_co d a t H H0) H)).\nQed.\n\n(* sémantique du kill non coacc states : *)\n\nLemma predta_kill_non_coacc_semantics :\n forall (d : DTA) (t : term),\n DTA_ref_ok d -> (reconnait d t <-> reconnait (dta_kill_non_coacc d) t).\nProof.\n\tsimple induction d. simpl in |- *. intros. split. exact (predta_kill_non_coacc_dir p a t H).\n\tunfold predta_kill_non_coacc in |- *. intros. apply (predta_kill_non_coacc_rev p a t (predta_coacc_states p a) H0). unfold predta_coacc_states in |- *. apply\n  (power_def_ok bool (ensemble_base state p) (predta_coacc p a)\n     (map_mini state p) (S (MapCard state p))). unfold def_ok_app in |- *. intros. exact (predta_coacc_def_ok p a x). exact (map_mini_appartient state p).\nQed.\n\nLemma predta_kill_non_coacc_lazy_semantics :\n forall (d : DTA) (t : term),\n DTA_ref_ok d -> (reconnait d t <-> reconnait (dta_kill_non_coacc_lazy d) t).\nProof.\n\tintros. rewrite (kill_non_coacc_lazy_eq_kill_non_coacc d).\n\texact (predta_kill_non_coacc_semantics d t H).\nQed.", "meta": {"author": "coq-contribs", "repo": "tree-automata", "sha": "9c755a15ca199e76d4fec767998abee82429ecfa", "save_path": "github-repos/coq/coq-contribs-tree-automata", "path": "github-repos/coq/coq-contribs-tree-automata/tree-automata-9c755a15ca199e76d4fec767998abee82429ecfa/non_coacc_kill.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23976805794376713}}
{"text": "Require Import Coq.Sets.Ensembles.\nRequire Import Coq.micromega.Lia.\nRequire Import VST.concurrency.conclib.\nRequire Import VST.floyd.library.\nRequire Import bst.puretree.\nRequire Import bst.bst_conc_cglock.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition t_struct_tree := Tstruct _tree noattr.\nDefinition t_struct_tree_t := Tstruct _tree_t noattr.\n\nLemma unfold_data_at_tree: forall p k (v pa pb: val),\n      data_at Ews t_struct_tree (vint k, (v, (pa, pb))) p =\n        field_at Ews t_struct_tree (DOT _key) (vint k) p *\n          spacer Ews 4 8 p *\n          field_at Ews t_struct_tree (DOT _value) v p *\n          field_at Ews t_struct_tree (DOT _left) pa p *\n          field_at Ews t_struct_tree (DOT _right) pb p.\nProof. intros. apply pred_ext; unfold_data_at (data_at _ _ _ _); cancel. Qed.\n\n(** TODO For some unknow reason, the tactic \"unfold_data_at\" does not\n    work as expected after importing general_locks. So I have to prove\n    the helper lemma above before general_locks. *)\n\nRequire Import VST.atomics.general_locks.\nImport puretree.\n\nFixpoint tree_rep (t: tree val) (p: val): mpred :=\n match t with\n | E => !!(p=nullval) && emp\n | T a x v b => !! (Int.min_signed <= x <= Int.max_signed /\\ tc_val (tptr Tvoid) v) &&\n   EX pa:val, EX pb:val,\n                    malloc_token Ews t_struct_tree p *\n                    data_at Ews t_struct_tree (Vint (Int.repr x),(v,(pa,pb))) p *\n                    tree_rep a pa * tree_rep b pb\n end.\n\nInstance tree_ghost: Ghost := discrete_PCM (tree val).\n\nNotation tree_info := (@G tree_ghost).\n\nDefinition treebox_rep (t: tree val) (b: val) :=\n  EX p: val, data_at Ews (tptr t_struct_tree) p b * tree_rep t p.\n\n\n\nDefinition node_lock_inv g lock np :=\n  (EX tr, my_half g Tsh tr *\n          treebox_rep tr (field_address t_struct_tree_t [StructField _t] np)) *\n  malloc_token Ews tlock lock * malloc_token Ews t_struct_tree_t np.\n\nDefinition nodebox_rep (g : gname)\n           (sh : share) (lock : val) (nb: val) :=\n  EX np: val,\n     data_at sh (tptr t_struct_tree_t) np nb *\n     field_at sh t_struct_tree_t [StructField _lock] lock np *\n     lock_inv sh lock (node_lock_inv g lock np).\n\nDefinition surely_malloc_spec :=\n  DECLARE _surely_malloc\n  WITH t:type, gv: globals\n  PRE [ size_t ]\n    PROP (0 <= sizeof t <= Int.max_unsigned;\n          complete_legal_cosu_type t = true;\n          natural_aligned natural_alignment t = true)\n    PARAMS (Vptrofs (Ptrofs.repr (sizeof t))) GLOBALS (gv)\n    SEP (mem_mgr gv)\n  POST [ tptr tvoid ] EX p:_,\n    PROP ()\n    LOCAL (temp ret_temp p)\n    SEP (mem_mgr gv; malloc_token Ews t p * data_at_ Ews t p).\n\nProgram Definition lookup_spec :=\n  DECLARE _lookup\n  ATOMIC TYPE (rmaps.ConstType (val * share * val * Z * globals * gname))\n  OBJ BST INVS base.empty base.top\n  WITH b, sh, lock, x, gv, g\n  PRE [tptr (tptr t_struct_tree_t), tint]\n   PROP (readable_share sh; Int.min_signed <= x <= Int.max_signed)\n   PARAMS (b; Vint (Int.repr x)) GLOBALS (gv)\n   SEP (mem_mgr gv; nodebox_rep g sh lock b) |\n        (!! sorted_tree BST && public_half g BST)\n  POST [tptr Tvoid]\n   EX ret: val,\n   PROP ()\n   LOCAL (temp ret_temp ret)\n   SEP (mem_mgr gv; nodebox_rep g sh lock b) |\n         (!! (sorted_tree BST /\\ ret = lookup nullval x BST) && public_half g BST).\n\nProgram Definition insert_spec :=\n  DECLARE _insert\n  ATOMIC TYPE (rmaps.ConstType (val * share * val * Z * val * globals * gname))\n  OBJ BST INVS base.empty base.top\n  WITH b, sh, lock, x, v, gv, g\n  PRE [tptr (tptr t_struct_tree_t), tint, tptr tvoid]\n   PROP (readable_share sh; Int.min_signed <= x <= Int.max_signed;\n        is_pointer_or_null v)\n   PARAMS (b; Vint (Int.repr x); v) GLOBALS (gv)\n   SEP (mem_mgr gv; nodebox_rep g sh lock b) |\n        (!! sorted_tree BST && public_half g BST)\n  POST [tvoid]\n   PROP ()\n   LOCAL ()\n   SEP (mem_mgr gv; nodebox_rep g sh lock b) |\n        (!! sorted_tree (insert x v BST) && public_half g (insert x v BST)).\n\nDefinition turn_left_spec :=\n DECLARE _turn_left\n  WITH ta: tree val, x: Z, vx: val, tb: tree val, y: Z, vy: val,\n              tc: tree val, b: val, l: val, pa: val, r: val\n  PRE  [ tptr (tptr t_struct_tree),\n         tptr t_struct_tree,\n         tptr t_struct_tree]\n    PROP (Int.min_signed <= x <= Int.max_signed; is_pointer_or_null vx)\n    PARAMS ( b; l; r) GLOBALS ()\n    SEP (data_at Ews (tptr t_struct_tree) l b;\n         data_at Ews t_struct_tree (Vint (Int.repr x), (vx, (pa, r))) l;\n         malloc_token Ews t_struct_tree l; tree_rep ta pa; tree_rep (T tb y vy tc) r)\n  POST [ Tvoid ]\n    EX pc: val,\n    PROP (Int.min_signed <= y <= Int.max_signed; is_pointer_or_null vy)\n    LOCAL()\n    SEP (data_at Ews (tptr t_struct_tree) r b;\n         data_at Ews t_struct_tree (Vint (Int.repr y), (vy, (l, pc))) r;\n         malloc_token Ews t_struct_tree r; tree_rep (T ta x vx tb) l; tree_rep tc pc).\n\nDefinition pushdown_left_spec :=\n DECLARE _pushdown_left\n  WITH ta: tree val, x: Z, v: val, tb: tree val, b: val, p: val, gv: globals\n  PRE  [ tptr (tptr (t_struct_tree)) ]\n    PROP(Int.min_signed <= x <= Int.max_signed; tc_val (tptr Tvoid) v)\n    PARAMS ( b ) GLOBALS (gv)\n    SEP (mem_mgr gv; data_at Ews (tptr t_struct_tree) p b;\n         malloc_token Ews t_struct_tree p;\n         spacer Ews 4 8 p;\n         field_at Ews t_struct_tree [StructField _key] (Vint (Int.repr x)) p;\n         field_at Ews t_struct_tree [StructField _value] v p;\n         treebox_rep ta (field_address t_struct_tree [StructField _left] p);\n         treebox_rep tb (field_address t_struct_tree [StructField _right] p))\n  POST [ Tvoid ]\n    PROP()\n    LOCAL()\n    SEP (mem_mgr gv; treebox_rep (pushdown_left ta tb) b).\n\nProgram Definition delete_spec :=\n DECLARE _delete\n ATOMIC TYPE (rmaps.ConstType (_ * _ * _ * _ * _ * _))\n         OBJ BST INVS base.empty base.top\n WITH b, x, lock, gv, sh, g\n PRE  [ tptr (tptr t_struct_tree_t), tint]\n    PROP (Int.min_signed <= x <= Int.max_signed; readable_share sh)\n    PARAMS ( b; Vint (Int.repr x)) GLOBALS (gv)\n    SEP (mem_mgr gv; nodebox_rep g sh lock b) |\n        (!!(sorted_tree BST) && public_half g BST)\n  POST [ Tvoid ]\n    PROP ()\n    LOCAL ()\n    SEP (mem_mgr gv; nodebox_rep g sh lock b) |\n        (!!(sorted_tree (delete x BST)) && public_half g (delete x BST)).\n\nDefinition treebox_new_spec :=\n  DECLARE _treebox_new\n  WITH gv: globals\n  PRE  [  ]\n    PROP () PARAMS () GLOBALS (gv) SEP (mem_mgr gv)\n  POST [ tptr (tptr t_struct_tree_t) ]\n    EX v:val, EX lock:val, EX g:gname,\n    PROP ()\n    LOCAL (temp ret_temp v)\n    SEP (mem_mgr gv; nodebox_rep g Ews lock v;\n        malloc_token Ews (tptr t_struct_tree_t) v;\n        public_half g E).\n\nDefinition tree_free_spec :=\n DECLARE _tree_free\n  WITH t: tree val, p: val, gv: globals\n  PRE  [ tptr t_struct_tree ]\n       PROP() PARAMS ( p ) GLOBALS (gv) SEP (mem_mgr gv; tree_rep t p)\n  POST [ Tvoid ]\n    PROP()\n    LOCAL()\n    SEP (mem_mgr gv).\n\nDefinition treebox_free_spec :=\n DECLARE _treebox_free\n  WITH lock: val, b: val, gv: globals, g: gname\n  PRE  [ tptr (tptr t_struct_tree_t) ]\n       PROP()\n       PARAMS (b) GLOBALS (gv)\n       SEP (mem_mgr gv; nodebox_rep g Ews lock b;\n           malloc_token Ews (tptr t_struct_tree_t) b)\n  POST [ Tvoid ]\n    PROP()\n    LOCAL()\n    SEP (mem_mgr gv).\n\nDefinition tree_inv g g1 g2 :=\n  EX (b: bool) (v: val) (l1 l2 : list (key * val)),\n  ghost_var gsh1 (b, v) g1 * ghost_var gsh1 (l1 ++ l2) g2 *\n  public_half g (insert_seq_opt b v l1 l2).\n\nDefinition thread_lock_R sh lock g g1 b (gv: globals) :=\n  ghost_var gsh2 (true, (gv ___stringlit_1)) g1 * mem_mgr gv *\n  data_at sh (tptr (tptr (t_struct_tree_t))) b (gv _tb) *\n  data_at Ers (tarray tschar 16)\n          (map (Vint oo cast_int_int I8 Signed)\n               [Int.repr 79; Int.repr 78; Int.repr 69;\n               Int.repr 95; Int.repr 70; Int.repr 82;\n               Int.repr 79; Int.repr 77; Int.repr 95;\n               Int.repr 84; Int.repr 72; Int.repr 82;\n               Int.repr 69; Int.repr 65; Int.repr 68;\n               Int.repr 0]) (gv ___stringlit_1) * nodebox_rep g sh lock b.\n\nDefinition thread_lock_inv sh lock g g1 b gv lockt :=\n  selflock (thread_lock_R sh lock g g1 b gv) sh lockt.\n\nDefinition thread_func_spec :=\n DECLARE _thread_func\n  WITH y : val, x : iname * gname * gname * gname * share * val * val * globals * invG\n    PRE [ tptr tvoid ]\n         let '(i, g1, g2, g, sh, lock, b, gv, inv_names) := x in\n         PROP  (readable_share sh)\n         PARAMS ( y ) GLOBALS (gv)\n         SEP   (invariant i (tree_inv g g1 g2); ghost_var gsh2 (false, nullval) g1;\n               mem_mgr gv; data_at sh (tptr (tptr (t_struct_tree_t))) b (gv _tb);\n               data_at Ers (tarray tschar 16)\n                       (map (Vint oo cast_int_int I8 Signed)\n                            [Int.repr 79; Int.repr 78; Int.repr 69;\n                            Int.repr 95; Int.repr 70; Int.repr 82;\n                            Int.repr 79; Int.repr 77; Int.repr 95;\n                            Int.repr 84; Int.repr 72; Int.repr 82;\n                            Int.repr 69; Int.repr 65; Int.repr 68;\n                            Int.repr 0]) (gv ___stringlit_1);\n               nodebox_rep g sh lock b;\n               lock_inv sh (gv _thread_lock)\n                        (thread_lock_inv sh lock g g1 b gv (gv _thread_lock)))\n  POST [ tptr tvoid ]\n         PROP ()\n         LOCAL ()\n         SEP ().\n\nDefinition main_spec :=\n  DECLARE _main\n          WITH gv : globals\n                      PRE  [] main_pre prog tt gv\n                      POST [ tint ] main_post prog gv.\n\nDefinition acquire_spec := DECLARE _acquire acquire_spec.\nDefinition release_spec := DECLARE _release release_spec.\nDefinition release2_spec := DECLARE _release2 release2_spec.\nDefinition makelock_spec := DECLARE _makelock (makelock_spec _).\nDefinition freelock_spec := DECLARE _freelock (freelock_spec _).\nDefinition freelock2_spec := DECLARE _freelock2 (freelock2_spec _).\nDefinition spawn_spec := DECLARE _spawn spawn_spec.\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [acquire_spec; release_spec; makelock_spec;\n                          freelock2_spec; freelock_spec; release2_spec;\n                          surely_malloc_spec;\n                          lookup_spec; insert_spec;\n                          turn_left_spec; pushdown_left_spec; delete_spec;\n                          treebox_new_spec; tree_free_spec; treebox_free_spec;\n                          spawn_spec; thread_func_spec; main_spec]).\n\nLemma field_at_value_eq : forall {cs : compspecs} sh1 sh2 t gfs v1 v2 p,\n  readable_share sh1 -> readable_share sh2 ->\n  repinject (nested_field_type t gfs) v1 <> Vundef ->\n  repinject (nested_field_type t gfs) v2 <> Vundef ->\n  type_is_by_value (nested_field_type t gfs) = true ->\n  type_is_volatile (nested_field_type t gfs) = false ->\n  field_at sh1 t gfs v1 p * field_at sh2 t gfs v2 p |-- !!(v1 = v2).\nProof.\n  intros; unfold field_at, at_offset; Intros.\n  rewrite !by_value_data_at_rec_nonvolatile; auto.\n  sep_apply mapsto_value_eq; Intros; apply prop_right.\n  set (t' := nested_field_type t gfs) in *.\n  pose proof (f_equal (valinject t') H6) as Heq.\n  rewrite !valinject_repinject in Heq; auto.\nQed.\n\nLemma data_at_value_eq : forall {cs : compspecs} sh1 sh2 t v1 v2 p,\n  readable_share sh1 -> readable_share sh2 ->\n  repinject t v1 <> Vundef -> repinject t v2 <> Vundef ->\n  type_is_by_value t = true -> type_is_volatile t = false ->\n  data_at sh1 t v1 p * data_at sh2 t v2 p |-- !!(v1 = v2).\nProof. intros; unfold data_at; apply field_at_value_eq; auto. Qed.\n\nLemma nodebox_rep_share_join : forall g (sh1 sh2 sh : share) (lock : val) (nb : val),\n    readable_share sh1 -> readable_share sh2 -> sepalg.join sh1 sh2 sh ->\n    nodebox_rep g sh1 lock nb * nodebox_rep g sh2 lock nb = nodebox_rep g sh lock nb.\nProof.\n  intros. unfold nodebox_rep. apply pred_ext.\n  - Intros np1 np2. assert_PROP (np1 <> Vundef) by entailer!.\n    assert_PROP (np2 <> Vundef) by entailer!.\n    sep_apply data_at_value_eq; Intros; subst. Exists np2.\n    rewrite <- (data_at_share_join sh1 sh2 sh), <- (field_at_share_join sh1 sh2 sh),\n    <- (lock_inv_share_join sh1 sh2 sh); auto. cancel.\n  - Intros np; Exists np np.\n    rewrite <- (data_at_share_join sh1 sh2 sh), <- (field_at_share_join sh1 sh2 sh),\n    <- (lock_inv_share_join sh1 sh2 sh); auto. cancel.\nQed.\n\nLemma tree_rep_saturate_local:\n   forall t p, tree_rep t p |-- !! is_pointer_or_null p.\nProof. destruct t; simpl; intros. entailer!. Intros pa pb. entailer!. Qed.\nHint Resolve tree_rep_saturate_local: saturate_local.\n\nLemma tree_rep_valid_pointer:\n  forall t p, tree_rep t p |-- valid_pointer p.\nProof. intros. destruct t; simpl; normalize; auto with valid_pointer. Qed.\nHint Resolve tree_rep_valid_pointer: valid_pointer.\n\nLemma if_trueb: forall {A: Type} b (a1 a2: A), b = true -> (if b then a1 else a2) = a1.\nProof. intros; subst; auto. Qed.\n\nLemma if_falseb: forall {A: Type} b (a1 a2: A), b = false -> (if b then a1 else a2) = a2.\nProof. intros; subst; auto. Qed.\n\nLemma node_lock_exclusive : forall g lock np,\n    exclusive_mpred (node_lock_inv g lock np).\nProof.\n  intros. unfold node_lock_inv. unfold exclusive_mpred. unfold treebox_rep.\n  Intros tr1 tr2 tp1 tp2. sep_apply field_at_conflict; auto.\n  rewrite sepcon_comm. rewrite sepcon_FF. auto.\nQed.\nHint Resolve node_lock_exclusive.\n\nLemma tree_rep_nullval: forall t, tree_rep t nullval |-- !! (t = E).\nProof.\n  intros. destruct t; [entailer! |].\n  simpl tree_rep. Intros pa pb. entailer!.\nQed.\nHint Resolve tree_rep_nullval: saturate_local.\n\nLemma treebox_rep_spec: forall (t: tree val) (b: val),\n  treebox_rep t b =\n  EX p: val,\n  match t with\n  | E => !!(p=nullval) && data_at Ews (tptr t_struct_tree) p b\n  | T l x v r => !! (Int.min_signed <= x <= Int.max_signed /\\ tc_val (tptr Tvoid) v) &&\n      data_at Ews (tptr t_struct_tree) p b * malloc_token Ews t_struct_tree p *\n      spacer Ews 4 8 p *\n      field_at Ews t_struct_tree [StructField _key] (Vint (Int.repr x)) p *\n      field_at Ews t_struct_tree [StructField _value] v p *\n      treebox_rep l (field_address t_struct_tree [StructField _left] p) *\n      treebox_rep r (field_address t_struct_tree [StructField _right] p)\n  end.\nProof.\n  intros.\n  unfold treebox_rep at 1. f_equal. extensionality p.\n  destruct t; simpl.\n  - apply pred_ext; entailer!.\n  - unfold treebox_rep. apply pred_ext; entailer!.\n    + Intros pa pb. Exists pb pa. rewrite unfold_data_at_tree.\n      rewrite (field_at_data_at _ t_struct_tree [StructField _left]).\n      rewrite (field_at_data_at _ t_struct_tree [StructField _right]). cancel.\n    + Intros pa pb. Exists pb pa. rewrite unfold_data_at_tree.\n      rewrite (field_at_data_at _ t_struct_tree [StructField _left]).\n      rewrite (field_at_data_at _ t_struct_tree [StructField _right]). cancel.\nQed.\n\nLemma bst_left_entail: forall (t1 t1' t2: tree val) k (v p1 p2 p b: val),\n  Int.min_signed <= k <= Int.max_signed ->\n  is_pointer_or_null v ->\n  data_at Ews (tptr t_struct_tree) p b * malloc_token Ews t_struct_tree p *\n  data_at Ews t_struct_tree (Vint (Int.repr k), (v, (p1, p2))) p *\n  tree_rep t1 p1 * tree_rep t2 p2\n  |-- treebox_rep t1 (field_address t_struct_tree [StructField _left] p) *\n       (treebox_rep t1'\n         (field_address t_struct_tree [StructField _left] p) -*\n        treebox_rep (T t1' k v t2) b).\nProof.\n  intros.\n  rewrite unfold_data_at_tree.\n  rewrite (field_at_data_at _ t_struct_tree [StructField _left]).\n  unfold treebox_rep at 1. Exists p1. cancel.\n  rewrite <- wand_sepcon_adjoint.\n  unfold treebox_rep.\n  Exists p.\n  simpl.\n  Intros p'.\n  Exists p' p2.\n  entailer!.\n  rewrite unfold_data_at_tree.\n  rewrite (field_at_data_at _ t_struct_tree [StructField _left]).\n  cancel.\nQed.\n\nLemma bst_right_entail: forall (t1 t2 t2': tree val) k (v p1 p2 p b: val),\n  Int.min_signed <= k <= Int.max_signed ->\n  is_pointer_or_null v ->\n  data_at Ews (tptr t_struct_tree) p b * malloc_token Ews t_struct_tree p *\n  data_at Ews t_struct_tree (Vint (Int.repr k), (v, (p1, p2))) p *\n  tree_rep t1 p1 * tree_rep t2 p2\n  |-- treebox_rep t2 (field_address t_struct_tree [StructField _right] p) *\n       (treebox_rep t2'\n         (field_address t_struct_tree [StructField _right] p) -*\n        treebox_rep (T t1 k v t2') b).\nProof.\n  intros.\n  rewrite unfold_data_at_tree.\n  rewrite (field_at_data_at _ t_struct_tree [StructField _right]).\n  unfold treebox_rep at 1. Exists p2. cancel.\n  rewrite <- wand_sepcon_adjoint.\n  clear p2.\n  unfold treebox_rep.\n  Exists p.\n  simpl.\n  Intros p2.\n  Exists p1 p2.\n  entailer!.\n  rewrite unfold_data_at_tree.\n  rewrite (field_at_data_at _ t_struct_tree [StructField _right]).\n  cancel.\nQed.\n\nLemma insert_tree_inv_shift1: forall {inv_names : invG} i g g1 g2 l k v,\n    invariant i (tree_inv g g1 g2) *\n    ghost_var gsh2 l g2 |--\n              atomic_shift (λ BST : tree val,\n                              !! sorted_tree BST && public_half g BST) ∅ ⊤\n              (λ (BST : tree val) (_ : ()),\n               fold_right_sepcon\n                 [!! sorted_tree (insert k v BST) && public_half g (insert k v BST)])\n              (λ _ : (), ghost_var gsh2 (l ++ [(k, v)]) g2).\nProof.\n  intros; apply inv_atomic_shift; auto. 1: apply empty_subseteq.\n  unfold tree_inv. iIntros \"t\". iDestruct \"t\" as (b) \">t\".\n  iDestruct \"t\" as (v0) \"t\". iDestruct \"t\" as (l1 l2) \"[[g1 g2] t]\". iModIntro.\n  iExists (insert_seq_opt b v0 l1 l2). rewrite sepcon_comm sepcon_andp_prop. iSplit.\n  - iApply (prop_right with \"t\"). apply insert_seq_opt_sorted.\n  - iFrame. iSplit.\n    + iIntros \"[% c] !>\". iExists b, v0, l1, l2. iModIntro. iFrame.\n    + iIntros (_) \"(>g & [% c] & _)\".\n      iPoseProof (ghost_var_inj (A := list (key * val)) with \"[$g2 $g]\") as \"%\";\n        auto with share; subst l.\n      iMod (ghost_var_update with \"[g2 g]\") as \"g2\". {\n        rewrite <- (ghost_var_share_join gsh1 gsh2 Tsh) by auto with share; iFrame. }\n      rewrite <- (ghost_var_share_join gsh1 gsh2 Tsh) by auto with share.\n      iDestruct \"g2\" as \"[g2 $]\".\n      iExists b, v0, l1, (l2 ++ [(k, v)]). iModIntro. iModIntro.\n      rewrite insert_seq_opt_assoc. rewrite <- app_assoc. iFrame.\nQed.\n\nLemma insert_tree_inv_shift2: forall {inv_names : invG} i g g1 g2 (v1 v2: val),\n    invariant i (tree_inv g g1 g2) *\n    ghost_var gsh2 (false, v1) g1 |--\n              atomic_shift (λ BST : tree val, !! sorted_tree BST && public_half g BST) ∅ ⊤\n              (λ (BST : tree val) (_ : ()),\n               fold_right_sepcon\n                 [!! sorted_tree (insert 1 v2 BST) && public_half g (insert 1 v2 BST)])\n              (λ _ : (), ghost_var gsh2 (true, v2) g1).\nProof.\n  intros; apply inv_atomic_shift; auto. 1: apply empty_subseteq.\n  unfold tree_inv. iIntros \"t\". iDestruct \"t\" as (b) \">t\".\n  iDestruct \"t\" as (v0) \"t\". iDestruct \"t\" as (l1 l2) \"[[g1 g2] t]\". iModIntro.\n  iExists (insert_seq_opt b v0 l1 l2). rewrite sepcon_comm sepcon_andp_prop. iSplit.\n  - iApply (prop_right with \"t\"). apply insert_seq_opt_sorted.\n  - iFrame. iSplit.\n    + iIntros \"[% c] !>\". iExists b, v0, l1, l2. iModIntro. iFrame.\n    + iIntros (_) \"(>g & [% c] & _)\".\n      iPoseProof (ghost_var_inj (A := (bool * val)) with \"[$g1 $g]\") as \"%\";\n        auto with share. inv H0.\n      iMod (ghost_var_update with \"[g1 g]\") as \"g1\". {\n        rewrite <- (ghost_var_share_join gsh1 gsh2 Tsh) by auto with share; iFrame. }\n      rewrite <- (ghost_var_share_join gsh1 gsh2 Tsh) by auto with share.\n      iDestruct \"g1\" as \"[g1 $]\".\n      iExists true, v2, (l1 ++ l2), nil. iModIntro. iModIntro.\n      simpl insert_seq_opt. rewrite insert_seq_assoc app_nil_r. iFrame.\nQed.\n\nLemma thread_inv_exclusive : forall sh lock g g1 b gv lockt,\n    readable_share sh -> exclusive_mpred (thread_lock_inv sh lock g g1 b gv lockt).\nProof.\n  intros; apply selflock_exclusive.\n  unfold thread_lock_R. apply exclusive_sepcon1. apply exclusive_sepcon1.\n  apply exclusive_sepcon2. apply data_at_exclusive; auto. simpl; lia.\nQed.\nHint Resolve thread_inv_exclusive.\n\nLemma body_thread_func : semax_body Vprog Gprog f_thread_func thread_func_spec.\nProof.\n  start_function.\n  unfold MORE_COMMANDS. unfold abbreviate.\n  forward. (* _l = &_thread_lock; *)\n  unfold nodebox_rep.\n  Intros np.\n  forward. (* _t'1 = _tb; *)\n  assert_PROP (is_pointer_or_null (gv ___stringlit_1)) by entailer!.\n  assert (Int.min_signed ≤ 1 ∧ 1 ≤ Int.max_signed) by (compute; split; intro; easy).\n  forward_call (b, sh, lock, 1, (gv ___stringlit_1), gv, g,\n                ghost_var gsh2 (true, gv ___stringlit_1) g1, inv_names). {\n    sep_apply (insert_tree_inv_shift2 i g g1 g2 nullval (gv ___stringlit_1)).\n    unfold nodebox_rep. Exists np. entailer!. }\n  forward_call (gv _thread_lock, sh, thread_lock_R sh lock g g1 b gv,\n                thread_lock_inv sh lock g g1 b gv (gv _thread_lock)). {\n    lock_props. unfold thread_lock_inv at 2. unfold thread_lock_R.\n    rewrite selflock_eq. unfold thread_lock_inv, thread_lock_R. entailer!. }\n  forward.\nQed.\n\nLemma body_main: semax_body Vprog Gprog f_main main_spec.\nProof.\n  start_function.\n  sep_apply (create_mem_mgr gv).\n  rewrite <- (emp_sepcon (mem_mgr _)); Intros.\n  viewshift_SEP 0 (EX inv_names : invG, wsat) by (go_lower; apply make_wsat).\n  Intros inv_names.\n  ghost_alloc (ghost_var Tsh (false, nullval)). Intro g1.\n  ghost_alloc (ghost_var Tsh (@nil (key * val))). Intro g2.\n  rewrite <- 2 (ghost_var_share_join gsh1 gsh2 Tsh) by auto with share; Intros.\n  forward_call (gv). (* _t'1 = _treebox_new([]); *)\n  Intros v. destruct v as [[b lock] g]. simpl fst. simpl snd.\n  forward. (* _tb = _t'1;   *)\n  forward. (* _t_lock = &_thread_lock; *)\n  forward. (* _t'6 = _tb; *)\n  assert (readable_share Ews) by apply writable_readable, writable_Ews.\n  assert_PROP (is_pointer_or_null (gv ___stringlit_2)) by entailer!.\n  assert (Int.min_signed ≤ 3 ∧ 3 ≤ Int.max_signed) by (compute; split; intro; easy).\n  gather_SEP wsat (ghost_var gsh1 _ g1) (ghost_var gsh1 _ g2) (public_half _ _).\n  viewshift_SEP 0 (EX i, |> (wsat * invariant i (tree_inv g g1 g2))). {\n    go_lower. rewrite !sepcon_assoc. apply make_inv'. unfold tree_inv.\n    Exists false nullval (@nil (key * val)) (@nil (key * val)).\n    simpl insert_seq_opt. simpl app. cancel. } Intros i.\n  rewrite invariant_dup; Intros.\n  forward_call (b, Ews, lock, 3, (gv ___stringlit_2), gv, g,\n                ghost_var gsh2 [(3, (gv ___stringlit_2))] g2, inv_names). {\n    sep_apply (insert_tree_inv_shift1 i g g1 g2 [] 3 (gv ___stringlit_2)).\n    simpl app. apply sepcon_derives; [apply derives_refl | cancel]. }\n  forward. (* _t'5 = _tb; *)\n  assert_PROP (is_pointer_or_null (gv ___stringlit_3)) by entailer!.\n  assert (Int.min_signed ≤ 1 ∧ 1 ≤ Int.max_signed) by (compute; split; intro; easy).\n  rewrite invariant_dup; Intros.\n  forward_call (b, Ews, lock, 1, (gv ___stringlit_3), gv, g,\n                ghost_var gsh2 [(3, (gv ___stringlit_2));\n                                (1, (gv ___stringlit_3))] g2, inv_names). {\n    sep_apply (insert_tree_inv_shift1 i g g1 g2 [(3, (gv ___stringlit_2))]\n                                     1 (gv ___stringlit_3)).\n    simpl app. apply sepcon_derives; [apply derives_refl | cancel]. }\n  forward. (* _t'4 = _tb;  *)\n  assert_PROP (is_pointer_or_null (gv ___stringlit_4)) by entailer!.\n  assert (Int.min_signed ≤ 4 ∧ 4 ≤ Int.max_signed) by (compute; split; intro; easy).\n  rewrite invariant_dup; Intros.\n  forward_call (b, Ews, lock, 4, (gv ___stringlit_4), gv, g,\n                ghost_var gsh2 [(3, (gv ___stringlit_2));\n                                (1, (gv ___stringlit_3));\n                                (4, (gv ___stringlit_4))] g2, inv_names). {\n    sep_apply (insert_tree_inv_shift1\n                 i g g1 g2 [(3, gv ___stringlit_2); (1, gv ___stringlit_3)]\n                 4 (gv ___stringlit_4)).\n    simpl app. apply sepcon_derives; [apply derives_refl | cancel]. }\n  destruct split_Ews as (sh1 & sh2 & ? & ? & Hsh).\n  forward_call (gv _thread_lock, Ews,\n                thread_lock_inv sh1 lock g g1 b gv (gv _thread_lock)).\n  rewrite invariant_dup; Intros.\n  forward_spawn _thread_func nullval (i, g1, g2, g, sh1, lock, b, gv, inv_names). {\n    rewrite <- (lock_inv_share_join sh1 sh2 Ews); auto.\n    rewrite <- (data_at_share_join sh1 sh2 Ews); auto.\n    rewrite <- (nodebox_rep_share_join g sh1 sh2 Ews); auto. entailer!. }\n  forward.\n  sep_apply (create_mem_mgr gv).\n  assert_PROP (is_pointer_or_null (gv ___stringlit_5)) by entailer!.\n  rewrite invariant_dup; Intros.\n  forward_call (b, sh2, lock, 1, (gv ___stringlit_5), gv, g,\n                ghost_var gsh2 [(3, (gv ___stringlit_2));\n                                (1, (gv ___stringlit_3));\n                                (4, (gv ___stringlit_4));\n                                (1, (gv ___stringlit_5))] g2, inv_names). {\n    sep_apply (insert_tree_inv_shift1\n                 i g g1 g2 [(3, gv ___stringlit_2); (1, gv ___stringlit_3);\n                            (4, gv ___stringlit_4)]\n                 1 (gv ___stringlit_5)).\n    simpl app. apply sepcon_derives; [apply derives_refl | cancel]. }\n  forward_call (gv _thread_lock, sh2,\n                thread_lock_inv sh1 lock g g1 b gv (gv _thread_lock)).\n  unfold thread_lock_inv at 2. rewrite selflock_eq. Intros.\n  forward_call (gv _thread_lock, Ews, sh1, thread_lock_R sh1 lock g g1 b gv,\n                thread_lock_inv sh1 lock g g1 b gv (gv _thread_lock)). {\n    lock_props. unfold thread_lock_inv.\n    rewrite <- (lock_inv_share_join sh1 sh2 Ews); auto. entailer!. }\n  unfold thread_lock_R. Intros.\n  gather_SEP (nodebox_rep g sh1 _ _) (nodebox_rep g sh2 _ _).\n  rewrite (nodebox_rep_share_join g sh1 sh2 Ews lock b); auto.\n  gather_SEP (data_at sh1 _ _ _) (data_at sh2 _ _ _).\n  rewrite (data_at_share_join sh1 sh2 Ews); auto.\n  forward.\n  forward_call (lock, b, gv, g).\n  forward.\nQed.\n\nLemma body_treebox_free: semax_body Vprog Gprog f_treebox_free treebox_free_spec.\nProof.\n  start_function.\n  unfold nodebox_rep.\n  Intros np.\n  forward.\n  forward.\n  forward_call (lock, Ews, node_lock_inv g lock np).\n  forward_call (lock, Ews, node_lock_inv g lock np). (* _freelock(_l); *)\n  - lock_props.\n  - unfold node_lock_inv. unfold treebox_rep. Intros tr p.\n    change (tptr t_struct_tree) with\n        (nested_field_type t_struct_tree_t [StructField _t]).\n    rewrite <- field_at_data_at.\n    forward. (* _p = (_tgp -> _t); *)\n    forward_call (tr, p, gv). (* _tree_free(_p); *)\n    gather_SEP (my_half _ _ _).\n    viewshift_SEP 0 (emp). { go_lower. apply own_dealloc. }\n    forward_call (t_struct_tree_t, np, gv). (* _free(_tgp); *)\n    + if_tac; entailer!.\n      unfold_data_at_ np.\n      unfold_data_at (data_at Ews t_struct_tree_t _ np). cancel.\n    + forward_call (tlock, lock, gv). (* _free(_l); *)\n      * if_tac; entailer!.\n      * forward_call (tptr t_struct_tree_t, b, gv).\n        -- if_tac; entailer!.\n        -- entailer!.\nQed.\n\nLemma body_tree_free: semax_body Vprog Gprog f_tree_free tree_free_spec.\nProof.\n  start_function.\n  forward_if.\n  - destruct t; simpl tree_rep. 1: Intros; contradiction.\n    Intros pa pb.\n    forward.\n    forward.\n    forward_call (t_struct_tree, p, gv).\n    + rewrite if_false; auto. entailer!.\n    + forward_call (t1, pa, gv).\n      forward_call (t2, pb, gv).\n      entailer!.\n  - forward. subst.\n    sep_apply tree_rep_nullval. Intros. subst. simpl tree_rep. entailer!.\nQed.\n\nLemma body_treebox_new: semax_body Vprog Gprog f_treebox_new treebox_new_spec.\nProof.\n  start_function.\n  forward_call (tptr t_struct_tree_t, gv).\n  Intros p. (* treebox p *)\n  forward_call (t_struct_tree_t, gv).\n  Intros newt. (* tree_t *newt *)\n  forward.\n  forward_call (tarray (tptr tvoid) 2, gv).\n  1: vm_compute; split; easy.\n  Intros l. (* lock_t *l *)\n  ghost_alloc (both_halves E). 1: apply @part_ref_valid.\n  Intros g'. rewrite <- both_halves_join.\n  forward_call (l, Ews, node_lock_inv g' l newt). Intros.\n  forward.\n  forward.\n  assert_PROP (field_compatible t_struct_tree_t [] newt) by entailer!.\n  forward_call (l, Ews, node_lock_inv g' l newt).\n  - lock_props.\n    unfold node_lock_inv. Exists (@E val).\n    unfold_data_at (data_at Ews t_struct_tree_t _ _).\n    unfold treebox_rep. Exists nullval.\n    change (tptr t_struct_tree) with\n        (nested_field_type t_struct_tree_t [StructField _t]).\n    rewrite <- field_at_data_at. cancel. unfold tree_rep. entailer!.\n  - forward. Exists p l g'. unfold nodebox_rep. Exists newt. entailer!.\nQed.\n\nLemma body_surely_malloc: semax_body Vprog Gprog f_surely_malloc surely_malloc_spec.\nProof.\n  start_function.\n  forward_call (t, gv). Intros p.\n  forward_if\n  (PROP ( )\n   LOCAL (temp _p p)\n   SEP (mem_mgr gv; malloc_token Ews t p * data_at_ Ews t p)).\n  - if_tac. subst p. entailer!. entailer!.\n  - forward_call 1. contradiction.\n  - if_tac.\n    + forward. subst p. congruence.\n    + Intros. forward. entailer!.\n  - forward. Exists p; entailer!.\nQed.\n\nDefinition pushdown_left_inv (b_res: val)\n           (t_res: tree val) (gv: globals) : environ -> mpred :=\n  EX b: val, EX ta: tree val, EX x: Z, EX v: val, EX tb: tree val,\n  PROP  ()\n  LOCAL (temp _t b; gvars gv)\n  SEP   (mem_mgr gv; treebox_rep (T ta x v tb) b;\n        (treebox_rep (pushdown_left ta tb) b -* treebox_rep t_res b_res)).\n\nLemma body_pushdown_left: semax_body Vprog Gprog f_pushdown_left pushdown_left_spec.\nProof.\n  start_function.\n  forward_loop (pushdown_left_inv b (pushdown_left ta tb) gv).\n  - (* Precondition *)\n    unfold pushdown_left_inv. Exists b ta x v tb. entailer!.\n    apply derives_trans with (treebox_rep (T ta x v tb) b).\n    2: cancel; apply -> wand_sepcon_adjoint; cancel.\n    rewrite (treebox_rep_spec (T ta x v tb)). Exists p. entailer!.\n  - (* Loop body *)\n    unfold pushdown_left_inv. clear x v H H0. Intros b0 ta0 x vx tbc0.\n    unfold treebox_rep at 1. Intros p0.\n    forward. (* p = *t; *)\n    simpl tree_rep. Intros pa pbc.\n    forward. (* q = p->right *)\n    forward_if.\n    + subst. assert_PROP (tbc0 = E) by entailer!. subst.\n      forward. (* q = p->left *)\n      forward. (* *t=q *)\n      forward_call (t_struct_tree, p0, gv). (* _free(_p); *)\n      1: if_tac; entailer!.\n      forward. (* return *)\n      simpl tree_rep. simpl pushdown_left. cancel.\n      apply modus_ponens_wand'. Exists pa. entailer!.\n    + destruct tbc0 as [| tb0 y vy tc0]. 1: simpl tree_rep; Intros; easy.\n      forward_call (ta0, x, vx, tb0, y, vy, tc0, b0, p0, pa, pbc).\n      (* _turn_left(_t, _p, _q); *)\n      Intros pc.\n      forward. (* _t = &(_q -> _left); *)\n      Exists (field_address t_struct_tree [StructField _left] pbc) ta0 x vx tb0.\n      gather_SEP (data_at Ews _ _ b0) (malloc_token _ _ _). Intros.\n      Opaque tree_rep. entailer!. Transparent tree_rep.\n      apply RAMIF_PLAIN.trans'. now apply bst_left_entail.\nQed.\n\nLemma body_turn_left: semax_body Vprog Gprog f_turn_left turn_left_spec.\nProof.\n  start_function.\n  simpl tree_rep.\n  Intros pb pc.\n  forward. (* mid=r->left *)\n  forward. (* l->right=mid *)\n  forward. (* r->left=l *)\n  forward. (* _l = r *)\n  Exists pc.\n  entailer!.\n  simpl tree_rep.\n  Exists pa pb.\n  entailer!.\nQed.\n\nDefinition lookup_inv (b: val) (lock:val) (sh: share) (x: Z) gv (inv_names : invG)\n           (Q : val -> mpred) (g:gname) (np tp: val)\n           (root_t: tree_info) : environ -> mpred :=\n  (EX tn: val, EX t : tree_info,\n   PROP (lookup nullval x t = lookup nullval x root_t)\n   LOCAL (temp _p tn; temp _tgt np; temp _t b; temp _l lock;\n          temp _x (vint x); gvars gv)\n   SEP (data_at sh (tptr t_struct_tree_t) np b;\n       field_at sh t_struct_tree_t [StructField _lock] lock np;\n       lock_inv sh lock (node_lock_inv g lock np);\n       my_half g Tsh root_t; field_at Ews t_struct_tree_t [StructField _t] tp np;\n       malloc_token Ews t_struct_tree_t np;\n       tree_rep t tn; malloc_token Ews tlock lock;\n       tree_rep t tn -* tree_rep root_t tp;\n       atomic_shift\n         (λ BST : tree val, !! sorted_tree BST && public_half g BST) ∅ ⊤\n         (λ (BST : tree val) (ret : val),\n          fold_right_sepcon\n            [!! (sorted_tree BST ∧ ret = lookup nullval x BST) && public_half g BST])\n         Q; mem_mgr gv))%assert.\n\nLemma body_lookup: semax_body Vprog Gprog f_lookup lookup_spec.\nProof.\n  start_function.\n  unfold nodebox_rep. Intros np.\n  forward. (* _tgt = *_t; *)\n  forward. (* _l = (_tgt -> _lock); *)\n  forward_call (lock, sh, (node_lock_inv g lock np)). (* _acquire(_l); *)\n  unfold node_lock_inv at 2. unfold treebox_rep. Intros a tp.\n  change (tptr t_struct_tree) with\n      (nested_field_type t_struct_tree_t [StructField _t]).\n  rewrite <- field_at_data_at.\n  forward. (* _p = (_tgt -> _t); *)\n  forward_while (lookup_inv b lock sh x gv inv_names Q g np tp a).\n  (* while (_p != (tptr tvoid) (0)) { *)\n  - unfold lookup_inv. Exists tp a. entailer!. apply -> wand_sepcon_adjoint. cancel.\n  - entailer!.\n  - destruct t; unfold tree_rep at 1; fold tree_rep. 1: now Intros. Intros pa pb.\n    forward. (* _y = (_p -> _key); *)\n    forward_if; [|forward_if].\n    + forward. Exists (pa, t1). simpl fst. simpl snd. entailer!.\n      * rewrite <- H0; simpl. rewrite if_trueb; auto. now apply Z.ltb_lt.\n      * apply RAMIF_PLAIN.trans''. apply -> wand_sepcon_adjoint. simpl.\n        Exists pa pb. entailer!.\n    + forward. Exists (pb, t2). simpl fst. simpl snd. entailer!.\n      * rewrite <- H0. simpl. rewrite if_falseb. 2: apply Z.ltb_ge; lia.\n        rewrite if_trueb; auto. now apply Z.ltb_lt.\n      * apply RAMIF_PLAIN.trans''. apply -> wand_sepcon_adjoint. simpl.\n        Exists pa pb. entailer!.\n    + assert (x = k) by lia. subst x. clear H H3 H4. forward.\n      gather_SEP (atomic_shift _ _ _ _ _) (my_half _ _ _).\n      viewshift_SEP 0 (EX y, Q y * (!! (y = v) && (my_half g Tsh a))). {\n        go_lower.\n        rewrite <- (sepcon_emp\n                      (atomic_shift (λ BST : tree_info, !! sorted_tree BST &&\n                                                        public_half g BST) ∅ ⊤\n                                    (λ (BST : tree_info) (ret : val),\n                                     !! (sorted_tree BST ∧ ret = lookup nullval k BST)\n                                     && public_half g BST * emp) Q *\n                       my_half g Tsh a)).\n        apply sync_commit_same. intro t. Intros.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro]. Exists t. cancel.\n        apply imp_andp_adjoint. Intros. rewrite if_true in H3; auto. subst t.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro].\n        rewrite <- wand_sepcon_adjoint.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro]. Exists v.\n        entailer!. rewrite <- H0. simpl.\n        now do 2 (rewrite if_falseb; [|apply Z.ltb_irrefl]). } Intros y. subst y.\n      forward_call (lock, sh, node_lock_inv g lock np).\n      * assert (Frame =\n                [Q v; mem_mgr gv; data_at sh (tptr t_struct_tree_t) np b;\n                 field_at sh t_struct_tree_t [StructField _lock] lock np]);\n          subst Frame; [ reflexivity | clear H].\n        lock_props. unfold node_lock_inv. unfold treebox_rep. Exists a tp.\n        rewrite (field_at_data_at Ews _ _ _ _). simpl nested_field_type.\n        simpl fold_right_sepcon. cancel.\n        apply modus_ponens_wand'. simpl. Exists pa pb. entailer!.\n      * forward. Exists v. unfold nodebox_rep. Exists np. entailer!.\n  - subst tn. sep_apply tree_rep_nullval. Intros. subst t. simpl in H0.\n    gather_SEP (atomic_shift _ _ _ _ _) (my_half _ _ _).\n    viewshift_SEP 0 (EX y, Q y * (!! (y = nullval) && (my_half g Tsh a))). {\n      go_lower.\n        rewrite <- (sepcon_emp\n                      (atomic_shift (λ BST : tree_info, !! sorted_tree BST &&\n                                                        public_half g BST) ∅ ⊤\n                                    (λ (BST : tree_info) (ret : val),\n                                     !! (sorted_tree BST ∧ ret = lookup nullval x BST)\n                                     && public_half g BST * emp) Q *\n                       my_half g Tsh a)).\n        apply sync_commit_same. intro tr. Intros.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro]. Exists tr. cancel.\n        apply imp_andp_adjoint. Intros. rewrite if_true in H2; auto. subst tr.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro].\n        rewrite <- wand_sepcon_adjoint.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro]. Exists nullval.\n        entailer!. } Intros y. subst y.\n    forward_call (lock, sh, node_lock_inv g lock np).\n    + assert (Frame =\n              [Q nullval; mem_mgr gv; data_at sh (tptr t_struct_tree_t) np b;\n               field_at sh t_struct_tree_t [StructField _lock] lock np]);\n        subst Frame; [ reflexivity | clear H1].\n      lock_props. unfold node_lock_inv. unfold treebox_rep. Exists a tp.\n      rewrite (field_at_data_at Ews _ _ _ _). simpl nested_field_type.\n      simpl fold_right_sepcon. cancel. apply modus_ponens_wand.\n    + forward. Exists nullval. unfold nodebox_rep. Exists np. entailer!.\nQed.\n\nDefinition insert_inv (b: val) (lock:val) (sh: share) (x: Z) (v: val)\n           gv (inv_names : invG) (Q: mpred) (g:gname) (np: val)\n           (root_t: tree_info) : environ -> mpred :=\n  (EX tn: val, EX t : tree_info,\n   PROP ()\n   LOCAL (temp _tr tn; temp _tgt np; temp _t b; temp _l lock;\n          temp _x (vint x); temp _value v; gvars gv)\n   SEP (data_at sh (tptr t_struct_tree_t) np b;\n       field_at sh t_struct_tree_t [StructField _lock] lock np;\n       lock_inv sh lock (node_lock_inv g lock np);\n       my_half g Tsh root_t;\n       malloc_token Ews t_struct_tree_t np;\n       treebox_rep t tn; malloc_token Ews tlock lock;\n       treebox_rep (insert x v t) tn -* treebox_rep (insert x v root_t)\n                   (field_address t_struct_tree_t [StructField _t] np);\n       atomic_shift\n         (λ BST : tree val, !! sorted_tree BST && public_half g BST)\n         ∅ ⊤\n         (λ (BST : tree val) (_ : ()),\n          fold_right_sepcon\n            [!! sorted_tree (insert x v BST) && public_half g (insert x v BST)])\n         (λ _ : (), Q); mem_mgr gv))%assert.\n\nLemma body_insert: semax_body Vprog Gprog f_insert insert_spec.\nProof.\n  start_function.\n  unfold nodebox_rep. Intros np.\n  forward. (* _tgt = *_t; *)\n  forward. (* _l = (_tgt -> _lock); *)\n  forward_call (lock, sh, (node_lock_inv g lock np)). (* _acquire(_l); *)\n  unfold node_lock_inv at 2. unfold treebox_rep. Intros tr tp.\n  forward. (* _tr = &(_tgt -> _t); *)\n  forward_loop (insert_inv b lock sh x v gv inv_names Q g np tr).\n  - unfold insert_inv. Exists (field_address t_struct_tree_t [StructField _t] np) tr.\n    entailer!. unfold treebox_rep at 1.\n    Exists tp. cancel. rewrite <- wand_sepcon_adjoint. cancel.\n  - unfold insert_inv. Intros tn t. unfold treebox_rep at 1. Intros p.\n    forward. (* _p = *_tr; *)\n    forward_if. (* if (_p == (tptr tvoid) (0)) { *)\n    + subst p.\n      forward_call (t_struct_tree, gv).\n      Intros p'.\n      forward. (* *_tr = _p; *)\n      forward. (* (_p -> _key) = _x; *)\n      forward. (* (_p -> _value) = _value; *)\n      forward. (* (_p -> _left) = (tptr tvoid) (0); *)\n      forward. (* (_p -> _right) = (tptr tvoid) (0); *)\n      assert_PROP (t = E) by entailer!. subst t. simpl tree_rep. Intros.\n      gather_SEP (atomic_shift _ _ _ _ _) (my_half _ _ _).\n      viewshift_SEP 0 (Q * my_half g Tsh (insert x v tr)). {\n        go_lower.\n        rewrite <- (sepcon_emp\n                      (atomic_shift (λ BST : tree_info, !! sorted_tree BST &&\n                                                        public_half g BST) ∅ ⊤\n                                    (λ (BST : tree_info) (_ : ()),\n                                     !! sorted_tree (insert x v BST) &&\n                                     @public_half tree_ghost g (insert x v BST) * emp)\n                                    (λ _ : (), Q) * my_half g Tsh tr)).\n        apply sync_commit_gen1. intros tr1. Intros.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro]. Exists tr1. cancel.\n        apply imp_andp_adjoint. Intros. rewrite if_true in H2; auto. subst tr1.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro]. Exists tr tr.\n        entailer!. 2: exact tt. rewrite <- wand_sepcon_adjoint.\n        sep_apply (public_update g tr tr (insert x v tr)). Intros.\n        apply ghost_seplog.bupd_mono. entailer!. now apply insert_sorted. }\n      forward_call (lock, sh, node_lock_inv g lock np). (* _release(_l); *)\n      * assert (Frame =\n                [Q; mem_mgr gv; data_at sh (tptr t_struct_tree_t) np b;\n                 field_at sh t_struct_tree_t [StructField _lock] lock np]);\n          subst Frame; [ reflexivity | clear H1].\n        lock_props. unfold node_lock_inv. Exists (insert x v tr).\n        simpl fold_right_sepcon. cancel. apply modus_ponens_wand'.\n        unfold treebox_rep. Exists p'. simpl. Exists nullval nullval. entailer!.\n      * forward. (* return; *) unfold nodebox_rep. Exists np. entailer!.\n    + destruct t; simpl tree_rep. 1: now Intros. Intros pa pb.\n      forward. (* _y = (_p -> _key); *)\n      forward_if; [|forward_if].\n      * forward. (* _tr = &(_p -> _left); *)\n        unfold insert_inv.\n        Exists (field_address t_struct_tree [StructField _left] p) t1.\n        entailer!. simpl treebox_rep. rewrite if_trueb. 2: now apply Z.ltb_lt.\n        apply RAMIF_PLAIN.trans'. now apply bst_left_entail.\n      * forward. (* _tr = &(_p -> _right); *)\n        unfold insert_inv.\n        Exists (field_address t_struct_tree [StructField _right] p) t2.\n        entailer!. simpl treebox_rep. rewrite if_falseb. 2: apply Z.ltb_ge; lia.\n        rewrite if_trueb. 2: now apply Z.ltb_lt.\n        apply RAMIF_PLAIN.trans'. now apply bst_right_entail.\n      * assert (x = k) by lia. subst x. clear H2 H3 H4.\n        forward. (* (_p -> _value) = _value; *)\n        gather_SEP (atomic_shift _ _ _ _ _) (my_half _ _ _).\n        viewshift_SEP 0 (Q * my_half g Tsh (insert k v tr)). {\n        go_lower.\n        rewrite <- (sepcon_emp\n                      (atomic_shift (λ BST : tree_info, !! sorted_tree BST &&\n                                                        public_half g BST) ∅ ⊤\n                                    (λ (BST : tree_info) (_ : ()),\n                                     !! sorted_tree (insert k v BST) &&\n                                     @public_half tree_ghost g (insert k v BST) * emp)\n                                    (λ _ : (), Q) * my_half g Tsh tr)).\n        apply sync_commit_gen1. intros tr1. Intros.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro]. Exists tr1. cancel.\n        apply imp_andp_adjoint. Intros. rewrite if_true in H3; auto. subst tr1.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro]. Exists tr tr.\n        entailer!. 2: exact tt. rewrite <- wand_sepcon_adjoint.\n        sep_apply (public_update g tr tr (insert k v tr)). Intros.\n        apply ghost_seplog.bupd_mono. entailer!. now apply insert_sorted. }\n        forward_call (lock, sh, node_lock_inv g lock np). (* _release(_l); *)\n        -- assert (Frame =\n                   [Q; mem_mgr gv; data_at sh (tptr t_struct_tree_t) np b;\n                    field_at sh t_struct_tree_t [StructField _lock] lock np]);\n             subst Frame; [ reflexivity | clear H2].\n           lock_props. unfold node_lock_inv. Exists (insert k v tr).\n           simpl fold_right_sepcon. cancel. apply modus_ponens_wand'.\n           unfold treebox_rep. Exists p. simpl.\n           do 2 (rewrite if_falseb; [|apply Z.ltb_irrefl]). simpl tree_rep.\n           Exists pa pb. entailer!.\n        -- forward. (* return; *) unfold nodebox_rep. Exists np. entailer!.\nQed.\n\nDefinition delete_inv (b: val) (lock:val) (sh: share) (x: Z)\n           gv (inv_names : invG) (Q: mpred) (g:gname) (np: val)\n           (root_t: tree_info) : environ -> mpred :=\n  (EX tn: val, EX t : tree_info,\n   PROP ()\n   LOCAL (temp _tr tn; temp _tgt np; temp _t b; temp _l lock;\n          temp _x (vint x); gvars gv)\n   SEP (data_at sh (tptr t_struct_tree_t) np b;\n       field_at sh t_struct_tree_t [StructField _lock] lock np;\n       lock_inv sh lock (node_lock_inv g lock np);\n       my_half g Tsh root_t;\n       malloc_token Ews t_struct_tree_t np;\n       treebox_rep t tn; malloc_token Ews tlock lock;\n       treebox_rep (delete x t) tn -* treebox_rep (delete x root_t)\n                   (field_address t_struct_tree_t [StructField _t] np);\n       atomic_shift\n         (λ BST : tree val, !! sorted_tree BST && public_half g BST)\n         ∅ ⊤\n         (λ (BST : tree val) (_ : ()),\n          fold_right_sepcon\n            [!! sorted_tree (delete x BST) && public_half g (delete x BST)])\n         (λ _ : (), Q); mem_mgr gv))%assert.\n\nLemma body_delete: semax_body Vprog Gprog f_delete delete_spec.\nProof.\n  start_function.\n  unfold nodebox_rep. Intros np.\n  forward. (* _tgt = *_t; *)\n  forward. (* _l = (_tgt -> _lock); *)\n  forward_call (lock, sh, (node_lock_inv g lock np)). (* _acquire(_l); *)\n  unfold node_lock_inv at 2. unfold treebox_rep. Intros tr tp.\n  forward. (* _tr = &(_tgt -> _t); *)\n  forward_loop (delete_inv b lock sh x gv inv_names Q g np tr).\n  - unfold delete_inv. Exists (field_address t_struct_tree_t [StructField _t] np) tr.\n    entailer!. unfold treebox_rep at 1.\n    Exists tp. cancel. rewrite <- wand_sepcon_adjoint. cancel.\n  - unfold delete_inv. Intros tn t. unfold treebox_rep at 1. Intros p.\n    forward. (* _p = *_tr; *)\n    forward_if. (* if (_p == (tptr tvoid) (0)) { *)\n    + subst p. assert_PROP (t = E) by entailer!. subst t.\n      simpl tree_rep. Intros. simpl delete.\n      gather_SEP (atomic_shift _ _ _ _ _) (my_half _ _ _).\n      viewshift_SEP 0 (Q * my_half g Tsh (delete x tr)). {\n        go_lower.\n        rewrite <- (sepcon_emp\n                      (atomic_shift (λ BST : tree_info, !! sorted_tree BST &&\n                                                        public_half g BST) ∅ ⊤\n                                    (λ (BST : tree_info) (_ : ()),\n                                     !! sorted_tree (delete x BST) &&\n                                     @public_half tree_ghost g (delete x BST) * emp)\n                                    (λ _ : (), Q) * my_half g Tsh tr)).\n        apply sync_commit_gen1. intros tr1. Intros.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro]. Exists tr1. cancel.\n        apply imp_andp_adjoint. Intros. rewrite if_true in H1; auto. subst tr1.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro]. Exists tr tr.\n        entailer!. 2: exact tt. rewrite <- wand_sepcon_adjoint.\n        sep_apply (public_update g tr tr (delete x tr)). Intros.\n        apply ghost_seplog.bupd_mono. entailer!. now apply delete_sorted. }\n      forward_call (lock, sh, node_lock_inv g lock np). (* _release(_l); *)\n      * assert (Frame =\n                [Q; mem_mgr gv; data_at sh (tptr t_struct_tree_t) np b;\n                 field_at sh t_struct_tree_t [StructField _lock] lock np]);\n          subst Frame; [ reflexivity | clear H0].\n        lock_props. unfold node_lock_inv. Exists (delete x tr).\n        simpl fold_right_sepcon. cancel. apply modus_ponens_wand'.\n        unfold treebox_rep. Exists nullval. simpl. entailer!.\n      * forward. (* return; *) unfold nodebox_rep. Exists np. entailer!.\n    + destruct t; simpl tree_rep. 1: now Intros. Intros pa pb.\n      forward. (* _y = (_p -> _key); *)\n      forward_if; [|forward_if].\n      * forward. (* _tr = &(_p -> _left); *)\n        unfold insert_inv.\n        Exists (field_address t_struct_tree [StructField _left] p) t1.\n        entailer!. simpl treebox_rep. rewrite if_trueb. 2: now apply Z.ltb_lt.\n        apply RAMIF_PLAIN.trans'. now apply bst_left_entail.\n      * forward. (* _tr = &(_p -> _right); *)\n        unfold insert_inv.\n        Exists (field_address t_struct_tree [StructField _right] p) t2.\n        entailer!. simpl treebox_rep. rewrite if_falseb. 2: apply Z.ltb_ge; lia.\n        rewrite if_trueb. 2: now apply Z.ltb_lt.\n        apply RAMIF_PLAIN.trans'. now apply bst_right_entail.\n      * assert (x = k) by lia. subst x. clear H1 H2 H3.\n        rewrite unfold_data_at_tree. Intros.\n        gather_SEP (field_at _ _ [StructField _left] _ _) (tree_rep _ pa).\n        replace_SEP 0 (treebox_rep\n                         t1 (field_address t_struct_tree [StructField _left] p)). {\n          unfold treebox_rep; entailer!. Exists pa.\n          rewrite field_at_data_at. simpl. entailer!. }\n        gather_SEP (field_at _ _ [StructField _right] _ _) (tree_rep _ pb).\n        replace_SEP 0 (treebox_rep\n                         t2 (field_address t_struct_tree [StructField _right] p)). {\n          unfold treebox_rep; entailer!. Exists pb.\n          rewrite field_at_data_at. entailer!. }\n        forward_call (t1, k, v, t2, tn, p, gv); [entailer! .. |].\n        (* _pushdown_left(_tr); *)\n        gather_SEP (atomic_shift _ _ _ _ _) (my_half _ _ _).\n        viewshift_SEP 0 (Q * my_half g Tsh (delete k tr)). {\n        go_lower.\n        rewrite <- (sepcon_emp\n                      (atomic_shift (λ BST : tree_info, !! sorted_tree BST &&\n                                                        public_half g BST) ∅ ⊤\n                                    (λ (BST : tree_info) (_ : ()),\n                                     !! sorted_tree (delete k BST) &&\n                                     @public_half tree_ghost g (delete k BST) * emp)\n                                    (λ _ : (), Q) * my_half g Tsh tr)).\n        apply sync_commit_gen1. intros tr1. Intros.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro]. Exists tr1. cancel.\n        apply imp_andp_adjoint. Intros. rewrite if_true in H2; auto. subst tr1.\n        eapply derives_trans; [|apply ghost_seplog.bupd_intro]. Exists tr tr.\n        entailer!. 2: exact tt. rewrite <- wand_sepcon_adjoint.\n        sep_apply (public_update g tr tr (delete k tr)). Intros.\n        apply ghost_seplog.bupd_mono. entailer!. now apply delete_sorted. }\n        forward_call (lock, sh, node_lock_inv g lock np). (* _release(_l); *)\n        -- assert (Frame =\n                   [Q; mem_mgr gv; data_at sh (tptr t_struct_tree_t) np b;\n                    field_at sh t_struct_tree_t [StructField _lock] lock np]);\n             subst Frame; [ reflexivity | clear H1].\n           lock_props. unfold node_lock_inv. Exists (delete k tr).\n           simpl fold_right_sepcon. cancel. apply modus_ponens_wand'.\n           unfold treebox_rep. Intros p'. Exists p'. simpl.\n           do 2 (rewrite if_falseb; [|apply Z.ltb_irrefl]). cancel.\n        -- forward. (* return; *) unfold nodebox_rep. Exists np. entailer!.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "DeepSpecDB", "sha": "a67d933b4288498bd04c70748b7fa28f676983c3", "save_path": "github-repos/coq/PrincetonUniversity-DeepSpecDB", "path": "github-repos/coq/PrincetonUniversity-DeepSpecDB/DeepSpecDB-a67d933b4288498bd04c70748b7fa28f676983c3/concurrency/verif_bst_conc_cglock2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23976805794376713}}
{"text": "Require Import Rewriter.Language.Language.\nRequire Import Rewriter.Language.Wf.\nRequire Import Crypto.Language.API.\n\nModule Compilers.\n  Import Language.Compilers.\n  Import Language.Inversion.Compilers.\n  Import Language.Wf.Compilers.\n  Import Language.API.Compilers.\n  Import Compilers.API.\n\n  Create HintDb wf_extra discriminated.\n  Create HintDb interp_extra discriminated.\n#[global]\n  Hint Constants Opaque : wf_extra interp_extra.\n\n#[global]\n  Hint Opaque expr.interp expr.Interp : interp_extra.\n#[global]\n  Hint Opaque expr.Wf expr.Wf3 : wf_extra interp_extra.\n\n  Module expr.\n    Import Language.Wf.Compilers.expr.\n    Global Hint Constructors wf : wf_extra.\n    Global Hint Resolve Wf_APP : wf_extra.\n    Global Hint Opaque expr.APP : wf_extra interp_extra.\n#[global]\n    Hint Rewrite @expr.Interp_APP : interp_extra.\n    Global Hint Immediate Wf_of_Wf3 : wf_extra.\n    Global Hint Resolve Wf3_of_Wf : wf_extra.\n\n    Definition Wf_base_Reify_as {t} v\n      := @Wf_base_Reify_as base.type.base base.base_interp base.type.base_beq ident ident.buildIdent base.reflect_base_beq t v.\n\n    Definition Wf_Reify_as {t} v\n      := @Wf_Reify_as base.type.base base.base_interp base.type.base_beq ident ident.buildIdent base.reflect_base_beq t v.\n\n    Definition Wf_base_reify {t} v\n      := @Wf_base_reify base.type.base base.base_interp base.type.base_beq ident ident.buildIdent base.reflect_base_beq t v.\n\n    Definition Wf_reify {t} v\n      := @Wf_reify base.type.base base.base_interp base.type.base_beq ident ident.buildIdent base.reflect_base_beq t v.\n\n    Definition Interp_Reify_as {t} v\n      := @Interp_Reify_as base.type.base base.base_interp ident ident.buildIdent (@ident.interp) ident.buildInterpIdentCorrect t v.\n\n    Definition Interp_reify {t} v\n      := @Interp_reify base.type.base base.base_interp ident ident.buildIdent (@ident.interp) ident.buildInterpIdentCorrect t v.\n\n    Definition interp_reify {t} v\n      := @interp_reify base.type.base base.base_interp ident ident.buildIdent (@ident.interp) ident.buildInterpIdentCorrect t v.\n\n    Definition interp_reify_list {t} v\n      := @interp_reify_list base.type.base base.base_interp ident ident.buildIdent (@ident.interp) ident.buildInterpIdentCorrect t v.\n\n    Definition interp_reify_option {t} v\n      := @interp_reify_option base.type.base base.base_interp ident ident.buildIdent (@ident.interp) ident.buildInterpIdentCorrect t v.\n\n    Definition Wf_Interp_Proper {t} e Hwf\n      := @Wf_Interp_Proper_gen _ ident _ _ (@ident.interp) (@ident.interp_Proper) t e Hwf.\n  End expr.\n\n#[global]\n  Hint Constructors expr.wf : wf_extra.\n#[global]\n  Hint Resolve expr.Wf_APP expr.Wf_Reify_as expr.Wf_base_Reify_as expr.Wf_reify expr.Wf_base_reify : wf_extra.\n  (** Work around COQBUG(https://github.com/coq/coq/issues/11536) *)\n#[global]\n  Hint Extern 0 (expr.Wf (GallinaReify.base.Reify_as _ _)) => simple apply (@expr.Wf_base_Reify) : wf_extra.\n#[global]\n  Hint Extern 0 (expr.Wf (GallinaReify.Reify_as _ _)) => simple apply (@expr.Wf_Reify) : wf_extra.\n  (** Work around COQBUG(https://github.com/coq/coq/issues/11536) *)\n#[global]\n  Hint Extern 0 (expr.Wf (fun var => GallinaReify.base.reify _)) => simple apply (@expr.Wf_base_reify) : wf_extra.\n#[global]\n  Hint Extern 0 (expr.Wf (fun var => GallinaReify.reify _)) => simple apply (@expr.Wf_reify) : wf_extra.\n#[global]\n  Hint Opaque expr.APP GallinaReify.Reify_as GallinaReify.base.reify : wf_extra interp_extra.\n#[global]\n  Hint Rewrite @expr.Interp_Reify_as @expr.interp_reify @expr.interp_reify_list @expr.interp_reify_option @expr.Interp_reify @expr.Interp_APP : interp_extra.\n\n  Module GeneralizeVar.\n    Import Language.Wf.Compilers.GeneralizeVar.\n\n    Definition Wf_FromFlat_ToFlat {t} e Hwf\n      := @Wf_FromFlat_ToFlat _ ident (@base.try_make_transport_cps _ base.try_make_base_transport_cps) (base.type.type_beq _ base.type.base_beq) base.reflect_type_beq base.try_make_transport_cps_correct _ t e Hwf.\n\n    Definition Wf_GeneralizeVar {t} e Hwf\n      := @Wf_GeneralizeVar _ ident (@base.try_make_transport_cps _ base.try_make_base_transport_cps) (base.type.type_beq _ base.type.base_beq) base.reflect_type_beq base.try_make_transport_cps_correct _ t e Hwf.\n\n    Definition Interp_FromFlat_ToFlat {t} e Hwf\n      := @Interp_gen1_FromFlat_ToFlat _ ident (@base.try_make_transport_cps _ base.try_make_base_transport_cps) (base.type.type_beq _ base.type.base_beq) base.reflect_type_beq base.try_make_transport_cps_correct _ _ (@ident.interp) _ (@ident.interp_Proper) t e Hwf.\n\n    Definition Interp_GeneralizeVar {t} e Hwf\n      := @Interp_gen1_GeneralizeVar _ ident (@base.try_make_transport_cps _ base.try_make_base_transport_cps) (base.type.type_beq _ base.type.base_beq) base.reflect_type_beq base.try_make_transport_cps_correct _ _ (@ident.interp) _ (@ident.interp_Proper) t e Hwf.\n  End GeneralizeVar.\n\n  Global Hint Extern 0 (?x == ?x) => apply expr.Wf_Interp_Proper_gen : wf_extra interp_extra.\n#[global]\n  Hint Resolve GeneralizeVar.Wf_FromFlat_ToFlat GeneralizeVar.Wf_GeneralizeVar : wf_extra.\n#[global]\n  Hint Opaque GeneralizeVar.FromFlat GeneralizeVar.ToFlat GeneralizeVar.GeneralizeVar : wf_extra interp_extra.\n#[global]\n  Hint Rewrite @GeneralizeVar.Interp_GeneralizeVar @GeneralizeVar.Interp_FromFlat_ToFlat : interp_extra.\nEnd Compilers.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Language/WfExtra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.23976805794376704}}
{"text": "(**************************************************************************************************)\n(* Total Constructor/Destructorization for Local (Co)pattern Matching.                                   *)\n(*                                                                                                *)\n(* File: UtilsTypechecker.v                                                                       *)\n(*                                                                                                *)\n(**************************************************************************************************)\n\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.Minus.\nRequire Import Coq.Arith.Compare_dec.\nRequire Import Coq.Arith.PeanoNat.\nImport ListNotations.\nRequire Import Coq.omega.Omega.\n\nRequire Import AST.\nRequire Import Names.\nRequire Import GenericLemmas.\nRequire Import GenericTactics.\nRequire Import Skeleton.\nRequire Import ProgramDef.\nRequire Import Eval.\nRequire Export Typechecker.\n\n\n\nLemma preservation_in_list : forall (p : program) (e e' : expr) (left right : list expr) (cargs : list TypeName),\n    program_skeleton p // [] ||- (left ++ [e] ++ right) :: cargs ->\n    Forall\n      (fun e1 : expr =>\n         forall t : TypeName,\n           program_skeleton p / [] |- e1 : t -> forall e2 : expr, [p |- e1 ==> e2] -> program_skeleton p / [] |- e2 : t)\n      (left ++ [e] ++ right) ->\n    [ p |- e ==> e' ] ->\n    program_skeleton p // [] ||- (left ++ [e'] ++ right) :: cargs.\nProof.\n  intros p e e' left right cargs Ht Hall Heval.\n  generalize dependent cargs.\n  induction left.\n  -intros. simpl. simpl in Ht.\n   inversion Hall as [|_x _l Hhead Htail]; subst. inversion Ht; subst.\n   apply ListTypeDeriv_Cons; try assumption.\n   apply Hhead; try assumption.\n  -intros. inversion Ht; subst.\n   apply ListTypeDeriv_Cons; try assumption.\n   apply IHleft; try assumption.\n   inversion Hall. assumption.\nQed.\n\nLemma typeDerivList_lenghts_eq : forall (sk : skeleton) (exs : list expr) (ts : list TypeName),\n    (sk // [] ||- exs :: ts) ->\n    List.length exs = List.length ts.\nProof.\n  intros. generalize dependent ts.\n  induction exs.\n  -intros. inversion H. reflexivity.\n  -intros. induction ts; try solve [inversion H].\n   simpl. f_equal. inversion H. apply IHexs; try assumption.\nQed.\n\nLemma weaken_nth_option : forall {X : Type} (xsBase xs : list X) (x : X) (n : nat),\n    Some x = nth_option n xsBase ->\n    Some x = nth_option n (xsBase ++ xs).\nProof.\n  intros X xsBase xs x n H.\n  generalize dependent n. induction xsBase; intros.\n  -destruct n; try solve [inversion H].\n  -destruct n; try solve [inversion H; reflexivity].\n   simpl. simpl in H. apply IHxsBase. assumption.\nQed.\n\nLemma weaken_listDeriv:\n  forall (sk : skeleton) (ls : list expr),\n    Forall\n      (fun e : expr =>\n         forall (ctxBase ctx : list TypeName) (t : TypeName),\n           sk / ctxBase |- e : t -> sk / (ctxBase ++ ctx) |- e : t) ls ->\n    forall ctxBase ctx argts : list TypeName,\n      sk // ctxBase ||- ls :: argts -> sk // (ctxBase ++ ctx) ||- ls :: argts.\nProof.\n  intros sk ls H ctxBase ctx argts H7.\n  generalize dependent argts; induction ls; intros;\n    try solve [destruct argts; try solve [inversion H7]; apply ListTypeDeriv_Nil].\n  destruct argts; try solve [inversion H7].\n  inversion H. inversion H7. apply ListTypeDeriv_Cons.\n  * apply H2. assumption.\n  * apply IHls; try assumption.\nQed.\n\nLemma weaken_bindings:\n  forall (sk : skeleton) (bindings_exprs : list expr) (bindings_types : list TypeName),\n    Forall\n      (fun e : expr =>\n         forall (ctxBase ctx : list TypeName) (t : TypeName),\n           sk / ctxBase |- e : t -> sk / (ctxBase ++ ctx) |- e : t)\n      (map (fun et : expr * TypeName => let (e, _) := et in e) (combine bindings_exprs bindings_types)) ->\n    forall ctxBase ctx : list TypeName,\n      sk // ctxBase ||- bindings_exprs :: bindings_types ->\n      sk // (ctxBase ++ ctx) ||- bindings_exprs :: bindings_types.\nProof.\n  intros sk bindings_exprs bindings_types H_ind ctxBase ctx H.\n  generalize dependent bindings_exprs; induction bindings_types; intros;\n    destruct bindings_exprs; try solve [inversion H].\n  - apply ListTypeDeriv_Nil.\n  - inversion H. inversion H_ind. apply ListTypeDeriv_Cons.\n    + apply H10; assumption.\n    + apply IHbindings_types with (bindings_exprs := bindings_exprs); try assumption.\nQed.\n\nLemma weaken_typederiv : forall (sk : skeleton) (t : TypeName) (ctx ctxBase : list TypeName) (e : expr),\n    (sk / ctxBase |- e : t) ->\n    sk / (ctxBase ++ ctx) |- e : t.\nProof.\n  intros sk t ctx ctxBase e H.\n  generalize dependent t. generalize dependent ctx. generalize dependent ctxBase.\n  induction e using expr_strong_ind; intros.\n  (* E_Var *)\n  - apply T_Var. inversion H. apply weaken_nth_option. assumption.\n  (* E_Constr *)\n  - inversion H0. subst.\n    simpl. apply T_Constr with (cargs := cargs); try assumption; try reflexivity.\n    clear H0 H3.\n    generalize dependent cargs. induction ls; intros.\n    + destruct cargs; try solve [inversion H6]. apply ListTypeDeriv_Nil.\n    + destruct cargs; try solve [inversion H6]. apply ListTypeDeriv_Cons.\n      * inversion H. apply H2 with (ctxBase := ctxBase) (ctx := ctx) (t := t).\n        inversion H6. assumption.\n      * inversion H. apply IHls; try assumption. inversion H6. assumption.\n  (* E_DestrCall *)\n  - inversion H0; subst.\n    apply T_DestrCall with (dargs := dargs); try assumption.\n    + apply IHe. assumption.\n    + clear H0 H6.\n      generalize dependent dargs. induction ls; intros.\n      * destruct dargs; try solve [inversion H9]. apply ListTypeDeriv_Nil.\n      * destruct dargs; try solve [inversion H9]. apply ListTypeDeriv_Cons.\n        -- inversion H. apply H2 with (ctxBase := ctxBase). inversion H9. assumption.\n        -- inversion H. apply IHls; try assumption. inversion H9. assumption.\n  (* E_FunCall *)\n  - inversion H0; subst.\n    apply T_FunCall with (argts := argts); try assumption.\n    apply weaken_listDeriv; assumption.\n  (* E_MatchFunCall *)\n  - let solve_tac :=\n        (apply T_GlobalConsFunCall with (argts := argts) || apply T_LocalConsFunCall with (argts := argts)) ; try assumption;\n          [> apply IHe; try assumption\n          | apply weaken_listDeriv; assumption]\n    in\n    inversion H0; subst;\n      [> solve_tac | solve_tac].\n  (* E_MatchFunCall *)\n  - inversion H0; subst;\n      (apply T_GlobalGenFunCall with (argts := argts) || apply T_LocalGenFunCall with (argts := argts));\n      try assumption;\n    apply weaken_listDeriv; try assumption.\n  (* E_Match *)\n  - inversion H1; subst.\n    apply T_Match with\n        (bindings_exprs := bindings_exprs)\n        (bindings_types := bindings_types)\n        (ctorlist := ctorlist);\n      try assumption; try reflexivity.\n    + apply IHe; assumption.\n    + apply weaken_bindings; assumption.\n  (* E_CoMatch *)\n  - inversion H1; subst.\n    apply T_CoMatch with\n        (bindings_exprs := bindings_exprs)\n        (bindings_types := bindings_types)\n        (dtorlist := dtorlist);\n      try assumption; try reflexivity.\n    apply weaken_bindings; assumption.\n  (* E_Let *)\n  - inversion H; subst.\n    apply T_Let with (t1 := t1).\n    + apply IHe1; assumption.\n    + apply IHe2 with (ctxBase := t1 :: ctxBase); assumption.\nQed.\n\nLemma nth_option_eq : forall {X : Type} (xs xs': list X) (x : X),\n    nth_option (List.length xs) (xs ++ [x] ++ xs') = Some x.\nProof.\n  intros X xs x.\n  induction xs; try reflexivity.\n  simpl. apply IHxs.\nQed.\n\nLemma nth_option_lt : forall {X : Type} (xs xs' : list X) (x : X) (n : nat),\n    List.length xs <? n = true ->\n    nth_option n (xs ++ [x] ++ xs') = nth_option (n - 1) (xs ++ xs').\nProof.\n  intros X xs xs' x n H.\n  generalize dependent n; induction xs; intros; try reflexivity.\n  -simpl. destruct n; try solve [inversion H].\n   simpl. rewrite <- minus_n_O. reflexivity.\n  -destruct n; try solve [inversion H]. simpl.\n   assert (Hsimpl : nth_option (n - 0) (a :: xs ++ xs') = nth_option (n - 1) (xs ++ xs')).\n   destruct n; try solve [inversion H]. simpl. rewrite <- minus_n_O. reflexivity.\n   rewrite Hsimpl. apply IHxs. simpl in H. unfold Nat.ltb in H. simpl in H.\n   destruct n; try discriminate H. apply Nat.ltb_lt. apply Nat.leb_le in H. unfold lt. inversion H.\n   +apply le_n.\n   +subst. apply le_n_S. assumption.\nQed.\n\nLemma nth_option_gt : forall {X : Type} (xs xs' : list X) (x : X) (n : nat),\n    List.length xs <? n = false ->\n    List.length xs =? n = false ->\n    nth_option n (xs ++ [x] ++ xs') = nth_option n (xs ++ xs').\nProof.\n  intros X xs xs' x n Hlt Heq.\n  generalize dependent n; induction xs; intros.\n  -destruct n; try solve [inversion Heq]; try solve [inversion Hlt].\n  -simpl. destruct n.\n   +reflexivity.\n   +simpl. apply IHxs.\n    *simpl in Hlt. assumption.\n    *assumption.\nQed.\n\nLtac listTypeDeriv_tac argts ls := generalize dependent argts; induction ls; intros; destruct argts; try solve [inversion Ht_args]; try apply ListTypeDeriv_Nil.\n\nLemma subst_typing_cong : forall (sk : skeleton) (t t' : TypeName) (ctx_left ctx_right : list TypeName) (e e' : expr),\n    (sk / [] |- e' : t') ->\n    (sk / ctx_left ++ [t'] ++ ctx_right |- e : t) ->\n    sk / ctx_left ++ ctx_right |- (substitute' (List.length ctx_left) e' e) : t.\nProof.\n  intros sk t t' ctx_left ctx_right e e' He' He.\n  generalize dependent t. generalize dependent ctx_left. generalize dependent ctx_right.\n  induction e using expr_strong_ind; intros;\n    let rec genfun_tac :=  subst; simpl;\n                             match goal with\n                             | [ _: _ // _ ||- _ :: ?argts  |- _ ] =>\n                               (apply T_GlobalGenFunCall with (argts := argts) ||\n                                                              apply T_LocalGenFunCall with (argts := argts))\n                                 end;\n                             try assumption;\n                             clear Hin He;\n                             listTypeDeriv_tac argts ls;\n                             apply ListTypeDeriv_Cons;\n                             [> inversion H; apply H2; inversion Ht_args; assumption\n                             | inversion H; inversion Ht_args; subst; apply IHls; try assumption\n                             ]\n    in\n    let rec consfun_tac := subst; simpl;\n                             match goal with\n                             | [ _: _ // _ ||- _ :: ?argts  |- _ ] =>\n                               (apply T_GlobalConsFunCall with (argts := argts) ||\n                                                               apply T_LocalConsFunCall with (argts := argts))\n                             end;\n                             try assumption;\n                             [> apply IHe; assumption\n                             | clear Hin He;\n                               listTypeDeriv_tac argts ls;\n                               apply ListTypeDeriv_Cons;\n                               [> inversion H; apply H2; inversion Ht_args; assumption\n                               | inversion H; inversion Ht_args; subst; apply IHls; try assumption\n                               ]\n                             ]\n    in\n  inversion He as [ sk' ctx' v' t''\n                          | sk' ctx' args sn' cargs tn' HIn Ht_args tn_eq\n                          | sk' ctx' args ex sn' dargs rtype Hin Ht_ex Ht_args\n                          | sk' ctx' args n' argts rtype Hin Ht_args\n                          | sk' ctx' args ex qn argts rtype Hin Ht_ex Ht_args (* E_ConsFunCallG *)\n                          | sk' ctx' args ex qn argts rtype Hin Ht_ex Ht_args (* E_ConsFunCallL *)\n                          | sk' ctx' args qn argts Hin Ht_args (* E_GenFunCallG *)\n                          | sk' ctx' args qn argts Hin Ht_args (* E_GenFunCallL *)\n                          | sk' ctx' qn ex  b_exs b_ts bs cs tn' ctorlist Ht_ex bs_comb Ht_bs HlookupConstr Hexhaustive Ht_cs\n                          | sk' ctx' qn dtors b_exs b_ts bs cs bs_comb Ht_bs HlookupDestr Hexhaustive Ht_cs\n                          | sk' ctx' e1' e2' t1 t2\n                  ]; unfold substitute; [> | | | | consfun_tac | consfun_tac |  try genfun_tac | try genfun_tac | | | ].\n  (* E_Var *)\n  -subst. simpl. destruct (List.length ctx_left =? v) eqn:Elen.\n   +apply beq_nat_true in Elen. rewrite <- Elen in H. rewrite nth_option_eq in H.\n    inversion H. apply weaken_typederiv with (ctxBase := []). assumption.\n   +destruct (List.length ctx_left <? v) eqn:Elenle.\n    *destruct v. simpl.\n     --induction ctx_left; try solve [inversion Elen].\n       simpl. inversion Elenle.\n     --rewrite  nth_option_lt in H; try assumption.\n       apply T_Var; try assumption.\n    *rewrite nth_option_gt in H; try assumption.\n     apply T_Var; try assumption.\n  (* E_Constr *)\n  -simpl. apply T_Constr with (cargs := cargs); try assumption.\n   subst. clear HIn He.\n   listTypeDeriv_tac cargs ls.\n   apply ListTypeDeriv_Cons.\n   +inversion H. apply H2. inversion Ht_args. assumption.\n   +inversion H. inversion Ht_args. subst. apply IHls; try assumption.\n  (* E_DestrCall *)\n  -subst. simpl. apply T_DestrCall with (dargs := dargs); try assumption.\n   +apply IHe. assumption.\n   +clear Hin He IHe.\n   listTypeDeriv_tac dargs ls.\n   apply ListTypeDeriv_Cons.\n    *inversion H. apply H2. inversion Ht_args. assumption.\n    *inversion H. inversion Ht_args. subst. apply IHls; try assumption.\n  (* E_FunCall *)\n  -subst. simpl. apply T_FunCall with (argts := argts); try assumption.\n   clear Hin He.\n   listTypeDeriv_tac argts ls.\n   apply ListTypeDeriv_Cons.\n   +inversion H. apply H2. inversion Ht_args. assumption.\n   +inversion H. inversion Ht_args; subst. apply IHls; try assumption.\n  (* E_Match *)\n  -subst. simpl. rewrite map_combine_in_fst.\n   apply T_Match with (bindings_exprs := map (substitute' (List.length ctx_left) e') b_exs)\n                      (bindings_types := b_ts)\n                      (ctorlist := ctorlist); try assumption; try reflexivity.\n   +apply IHe. assumption.\n   +clear - H0 Ht_bs. generalize dependent b_ts; induction b_exs; intros; destruct b_ts; try solve [inversion Ht_bs].\n    *simpl. apply ListTypeDeriv_Nil.\n    *inversion H0. apply ListTypeDeriv_Cons.\n     --apply H2. inversion Ht_bs. assumption.\n     --apply IHb_exs; try assumption. inversion Ht_bs. assumption.\n  (* E_CoMatch *)\n  -subst. simpl. rewrite map_combine_in_fst.\n   apply T_CoMatch with (bindings_exprs := map (substitute' (List.length ctx_left) e') b_exs)\n                        (bindings_types := b_ts)\n                        (dtorlist := dtors); try assumption; try reflexivity.\n   clear - H0 Ht_bs. generalize dependent b_ts; induction b_exs; intros; destruct b_ts; try solve [inversion Ht_bs].\n   +apply ListTypeDeriv_Nil.\n   +inversion H0. apply ListTypeDeriv_Cons; try assumption.\n    *apply H2. inversion Ht_bs. assumption.\n    *apply IHb_exs; try assumption.\n     inversion Ht_bs. assumption.\n  (* E_Let *)\n  -subst; simpl. apply T_Let with (t1 := t1).\n   +apply IHe1; try assumption.\n   +assert (E : List.length ctx_left + 1 = List.length (t1 :: ctx_left)).\n    simpl. rewrite <- plus_n_Sm. rewrite <- plus_n_O. reflexivity.\n    rewrite E. apply IHe2 with (ctx_left := t1 :: ctx_left). assumption.\nQed.\n\nLemma subst_typing : forall (sk : skeleton) (t t' : TypeName) (ctx : list TypeName) (e e' : expr),\n    (sk / [] |- e' : t') ->\n    (sk / t' :: ctx |- e : t) ->\n    sk / ctx |- (substitute e' e) : t.\nProof.\n  intros. apply subst_typing_cong with (ctx_left := []) (t' := t'); try assumption.\nQed.\n\nLemma multisubst_typing : forall (sk : skeleton) (argts : list TypeName) (args : list expr) (e : expr) (t : TypeName),\n    sk // [] ||- args :: argts ->\n    (sk / argts |- e : t) ->\n    sk / [] |- (multi_subst args e) : t.\nProof.\n  intros sk argts args e t Hargs He.\n  generalize dependent e.\n  generalize dependent argts. induction args; intros; destruct argts; try solve [inversion Hargs]; try assumption.\n  simpl. apply IHargs with (argts := argts).\n  -inversion Hargs. assumption.\n  -apply subst_typing with (t' := t0); try assumption.\n   inversion Hargs. assumption.\nQed.\n\nLemma listTypeDeriv'_lemma : forall (prog : skeleton)(args : list expr)(argts : list TypeName)(ctxs: list ctxt),\n    prog /// ctxs |||- args ::: argts ->\n    length argts =? length args  = true.\nProof.\n   intros prog args. induction args; intro argts; induction argts; intros ctxs H; try reflexivity; try inversion H; subst.\n  simpl. eapply IHargs. eassumption.\nQed.\n\nLemma listTypeDeriv'_lemma_ctx: forall (prog : skeleton)(args : list expr)(argts : list TypeName)(ctxs: list ctxt),\n    prog /// ctxs |||- args ::: argts ->\n    length ctxs =? length args  = true.\nProof.\n  intros prog args argts ctxs H.\n  gen_induction (argts, ctxs) args; destruct ctxs; try solve [inversion H]; auto.\n  simpl. inversion_clear H. IH_auto_tac.\nQed.\n\nFact index_list_typechecks : forall (s : skeleton) (l r : list TypeName) (n : nat),\n    length r = n ->\n    s // r ++ l ||- map fst (index_list n l) :: l.\nProof.\n  intros s l r n H.\n  gen_induction (r, n) l.\n  - simpl. apply ListTypeDeriv_Nil.\n  - simpl. apply ListTypeDeriv_Cons.\n    + apply T_Var.\n      gen_induction n r; destruct n; try solve [inversion H]; try reflexivity.\n      simpl. apply IHr. inversion H; reflexivity.\n    + specialize (IHl (S n) (r ++ [a])).\n      simpl in IHl.\n      assert ((r ++ [a]) ++ l = r ++ a :: l);\n        [> clear; induction r; auto; simpl; f_equal; auto |].\n      rewrite <- H0. IH_tac. rewrite app_length. simpl.\n      rewrite Nat.add_1_r. f_equal. assumption.\nQed.\n\n", "meta": {"author": "ps-tuebingen", "repo": "decomposition-diversity", "sha": "28ab18c34f0a192c9b3d58caa709dee3e9129068", "save_path": "github-repos/coq/ps-tuebingen-decomposition-diversity", "path": "github-repos/coq/ps-tuebingen-decomposition-diversity/decomposition-diversity-28ab18c34f0a192c9b3d58caa709dee3e9129068/Formalization/UtilsTypechecker.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23976805141069374}}
{"text": "Require Import Coq.Strings.String.\nFrom Mtac2 Require Import Base Logic Datatypes List MFix MTeleMatch.\nImport M.notations.\nImport Mtac2.lib.List.ListNotations.\n\nDefinition funs_of (T : Prop) : mlist Prop -> Prop :=\n  fix f l :=\n  match l with\n  | [m: ] => T\n  | X :m: l => X -> f l\n  end.\n  (* fun T l => fold_right (fun B X => B -> X) T l.  *)\n\nDefinition args_of : mlist Prop -> Prop :=\n  fix f l :=\n  match l with\n  | [m: ] => True\n  | X :m: l => (X * f l)%type\n  end.\n\nDefinition apply_args_of {T} : forall {l}, funs_of T l -> args_of l -> T :=\n  fix f l :=\n  match l as l return funs_of T l -> args_of l -> T with\n  | [m: ] => fun t _ => t\n  | X :m: l => fun F '(x, a) => f l (F x) a\n  end.\n\n(* Compute funs_of (M nat) [m: True | False]. *)\n\nDefinition funs_bind {T X : Type} : forall {l},\n  (X -> funs_of (M T) l) -> (M X -> funs_of (M T) l) :=\n  fix f l :=\n    match l return (X -> funs_of _ l) -> (M X -> funs_of _ l) with\n    | [m:] => fun g mx => M.bind mx g\n    | Y :m: l => fun g mx y => f _ (fun x => g x y) mx\n    end.\n\n(* Definition unify_within {T} {X:Prop} (x : X) : *)\n(*   forall l, funs_of (M T) [m: X & l] -> funs_of (M T) [m: X & l] := *)\n(*   fix f l := *)\n(*     match l as l return funs_of _ [m: X & l] -> funs_of _ [m: X & l] with *)\n(*     | nil => fun F x' => M.unify x x' UniEvarconv;; F x' *)\n(*     | [m: Y & l] => fun F x' y => f l (fun x'' => F x'' y) x' *)\n(*     end. *)\n\n(* Eval cbn in unify_within (M.ret 2) [m: ] (fun x => M.ret x). *)\n(* Eval cbn in ltac:(mrun ( *)\n(*                       x <- M.evar nat; *)\n(*                       unify_within (M.ret x) [m: ] (fun _ => M.ret x) (M.ret 2) *)\n(*                  )). *)\n\nRecord Apply_Args (P T : Type) (t : T) :=\n  APPLY_ARGS {\n      apply_type: Type;\n      apply_func: apply_type;\n    }.\n\nDefinition remove_ret {V} {B} {Q : B -> Type} {A} : forall (v : V) b (m : Q b), (Q b -> M A) -> M A :=\n  fun v b m cont =>\n  m' <- M.remove v (M.ret m);\n  oe <- M.unify m m' UniMatchNoRed;\n  match oe with\n  | mNone => M.failwith \"Impossible branch.\"\n  | mSome e =>\n    match meq_sym e in _ =m= m'' return _ -> M A  with\n    | meq_refl =>\n      fun cont =>\n        cont m'\n    end cont\n  end\n.\n\nDefinition apply_type_of (P : Type) :\n  forall {T} (t : T),\n                      M (sigT (funs_of (M P))) :=\n  mfix f (T : _) : T -> M (sigT (funs_of (M P))) :=\n     mtmmatch T as T' return T' -> M (sigT (funs_of (M P))) with\n     | (M P : Type) =c> fun t => M.ret (existT (funs_of (M P)) [m:] t)\n     | [? X F] (forall x : X, F x) =c>\n        fun ft =>\n          M.nu (FreshFrom ft) mNone (fun x_nu : X =>\n          x <- M.evar X;\n          let F' := reduce (RedOneStep [rl:RedBeta]) (F x) in\n          let f' := reduce (RedOneStep [rl:RedBeta]) (ft x) in\n          r <- f F' f';\n          mif M.is_evar x then\n            o <- M.unify x_nu x UniEvarconv;\n            let '(existT _ rl rp) := r in\n             rp' <- M.abs_fun x_nu rp;\n             mtry (M.remove x_nu (\n                   let r' : sigT (funs_of (M P)) := existT _ (M X :m: rl) (funs_bind rp') in\n                   M.ret r'\n                 )) with\n          | [?s] CannotRemoveVar s =>\n            let err := (String.append \"A hypothesis depends on \" s) in\n            M.failwith err\n         end\n       else M.remove x_nu (M.ret r)\n       )\n  | _ => fun _ =>\n      M.failwith \"The lemma's conclusion does not unify with the goal.\"\n  end\n.\n\n(* Notation \"'[apply_args_mtac' t 'in' P ]\" := *)\n(*   ( *)\n(*     (* M.print \"bla\";; *) *)\n(*     let t' := t in *)\n(*     let P' := P in *)\n(*     r <- apply_type_of P' t'; *)\n(*     (* M.print_term r;; *) *)\n(*     let '(existT _ rl rp) := r in *)\n(*     M.ret (APPLY_ARGS P' _ t' _ rp) *)\n(*   ). *)\n\n(* Hint Extern 0 (Apply_Args ?P ?T ?t) => *)\n(* mrun [apply_args_mtac t in P] : typeclass_instances. *)\n\n(* Goal forall x y : nat, Apply_Args (x =m= x) _ (fun x => test_lemma True x y). *)\n(*   intros. *)\n(*   mrun [apply_args_mtac (fun x => test_lemma True x y) in x = x]. *)\n(* Defined. *)\n(* Eval vm_compute in Unnamed_thm. *)\n\n(* Definition bla x y := Eval vm_compute in @apply_func _ _ _ (Unnamed_thm x y). *)\n(* (* Notation \"'[test' t ]\" := (let f := ltac:(mrun t) in ltac:(let e := uconstr:(id f) in exact e)) (at level 0, t at level 11). *) *)\n\n(* Notation \"'[static_apply' t 'in' P ]\" := *)\n(*   ( *)\n(*     let t' := t in (* WHY IS THIS NECESSARY? *) *)\n(*     let F := M.eval [apply_args_mtac t' in P] in *)\n(*     @apply_func _ _ _ F *)\n(*   ) (at level 0, P, t at level 11). *)\n\n(* (* Notation \"'[bla' t ]\" := (let F := ltac:(mrun (M.unify t 1 UniCoq)) in 0 ). *) *)\n(* Notation \"'[bla' t ]\" := (let F := ltac:(let t := open_constr:(t) in unify t 1) in True). *)\n(* Fail Goal [bla _]. *)\n(* Goal 1=1. *)\n(*   mrun ([static_apply (test_lemma _ _ _) in _=_] (M.ret I) (M.evar (1>0))). *)\n(* Abort. *)\n\nNotation \"t '&s>' '[s' t1 ; .. ; tn ]\" :=\n  (\n    let t' := t in\n    let r := M.eval (apply_type_of _ t') in\n    let args := M.eval ((* debug true [m:] *) (M.coerce (pair t1 .. (pair tn I) ..))) in\n    apply_args_of (projT2 r) args\n  ) (at level 41, left associativity,\n     format \"t  &s>  [s  t1 ;  .. ;  tn ]\"\n    ).\n\n\n(* Definition test_lemma (T : Type) (x y : nat) : T -> y > 0 -> M (x =m= x) := *)\n(*   fun t H => M.print_term (T, x, y, t, H);; M.ret meq_refl. *)\n\n(* Goal 1=m=1. *)\n(*   mrun ((test_lemma _ _ _) &s> [s M.ret I ; M.evar (1>0) ]). *)\n(*   auto. *)\n(* Qed. *)\n\n(* Goal 1=m=1. *)\n(*   mrun ( *)\n(*       let f : M(1=1) := *)\n(*           (test_lemma _ _ _) &s> [s M.ret I ; M.evar (1>0) ] in *)\n(*       M.ret eq_refl). *)\n(* Qed. *)", "meta": {"author": "Mtac2", "repo": "Mtac2", "sha": "d16c2e682d5ab18ed77b13b4fd60a42a65c4f958", "save_path": "github-repos/coq/Mtac2-Mtac2", "path": "github-repos/coq/Mtac2-Mtac2/Mtac2-d16c2e682d5ab18ed77b13b4fd60a42a65c4f958/theories/ideas/StaticApply.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.23971250905104408}}
{"text": "From Coq Require Import List ListSet Streams ProofIrrelevance Arith.Plus Arith.Minus FinFun Rdefinitions.\nImport ListNotations.\n\nFrom CasperCBC Require Import Lib.Preamble Lib.ListExtras Lib.Measurable VLSM.Decisions VLSM.Common VLSM.Composition VLSM.ProjectionTraces.\n\nRequire Import Coq.Program.Tactics.\n\n(** * VLSM Equivocation Definitions **)\n\n(**\n This module is dedicated to building the language for discussing equivocation.\n Equivocation occurs on the receipt of a message which has not been previously sent.\n The designated sender (validator) of the message is then said to be equivocating.\n Our main purpose is to keep track of equivocating senders in a composite context\n and limit equivocation by means of a composition constraint.\n**)\n\nLemma exists_proj1_sig {A:Type} (P:A -> Prop) (a:A):\n  (exists xP:{x | P x}, proj1_sig xP = a) <-> P a.\nProof.\n  split.\n  - intros [[x Hx] Heq];simpl in Heq;subst x.\n    assumption.\n  - intro Ha.\n    exists (exist _ a Ha).\n    reflexivity.\nQed.\n\n(** ** Basic equivocation **)\n\nClass ReachableThreshold V `{Hm : Measurable V} :=\n  { threshold : {r | (r >= 0)%R}\n  ; reachable_threshold : exists (vs:list V), NoDup vs /\\ (sum_weights vs > proj1_sig threshold)%R\n  }.\n\n(** Assuming a set of <<state>>s, and a set of <<validator>>s,\nwhich is [Measurable] and has a [ReachableThreshold], we can define\n[basic_equivocation] starting from a computable [is_equivocating_fn]\ndeciding whether a validator is equivocating in a state.\n\nTo avoid a [Finite] constraint on the entire set of validators, we will\nassume that there is a finite set of validators for each state, which\ncan be retrieved through the [state_validators] function.\nThis can be taken to be entire set of validators when that is finite,\nor the set of senders for all messages in the state for\n[state_encapsulating_messages].\n\nThis allows us to determine the [equivocating_validators] for a given\nstate as those equivocating in that state.\n\nThe [equivocation_fault] is determined the as the sum of weights of the\n[equivocating_validators].\n\nWe call a state [not_heavy] if its corresponding [equivocation_fault]\nis lower than the [threshold] set for the <<validator>>s type.\n**)\n\nClass basic_equivocation\n  (state validator : Type)\n  {measurable_V : Measurable validator}\n  {reachable_threshold : ReachableThreshold validator}\n  :=\n  { is_equivocating (s : state) (v : validator) : Prop\n  ; is_equivocating_dec : RelDecision is_equivocating\n\n    (** retrieves a set containing all possible validators for a state. **)\n\n  ; state_validators (s : state) : set validator\n\n  ; state_validators_nodup : forall (s : state), NoDup (state_validators s)\n\n    (** All validators which are equivocating in a given composite state **)\n\n  ; equivocating_validators\n      (s : state)\n      : list validator\n      := List.filter (fun v => bool_decide (is_equivocating s v)) (state_validators s)\n\n     (** The equivocation fault sum: the sum of the weights of equivocating\n     validators **)\n\n  ; equivocation_fault\n      (s : state)\n      : R\n      :=\n      sum_weights (equivocating_validators s)\n\n  ; not_heavy\n      (s : state)\n      := (equivocation_fault s <= proj1_sig threshold)%R\n }.\n\n\n(**\n*** State-message oracles. Endowing states with history.\n\n    Our first step is to define some useful concepts in the context of a single VLSM.\n\n    Apart from basic definitions of equivocation, we introduce the concept of a\n    [state_message_oracle]. Such an oracle can, given a state and a message,\n    decide whether the message has been sent (or received) in the history leading\n    to the current state. Formally, we say that a [message] <m> [has_been_sent]\n    if we're in  [state] <s> iff every protocol trace which produces <s> contains <m>\n    as a sent message somewhere along the way.\n\n    The existence of such oracles, which practically imply endowing states with history,\n    is necessary if we are to detect equivocation using a composition constaint, as these\n    constraints act upon states, not traces.\n **)\n\nSection Simple.\n    Context\n      {message : Type}\n      (vlsm : VLSM message)\n      (pre_vlsm := pre_loaded_with_all_messages_vlsm vlsm)\n      .\n\n(** The following property detects equivocation in a given trace for a given message. **)\n\n    Definition equivocation_in_trace\n      (msg : message)\n      (tr : list (vtransition_item vlsm))\n      : Prop\n      :=\n      exists\n        (prefix suffix : list transition_item)\n        (item : transition_item),\n        tr = prefix ++ item :: suffix\n        /\\ input item = Some msg\n        /\\ ~ In (Some msg) (List.map output prefix).\n\n(** We intend to give define several message oracles: [has_been_sent], [has_not_been_sent],\n    [has_been_received] and [has_not_been_received]. To avoid repetition, we give\n    build some generic definitions first. **)\n\n(** General signature of a message oracle **)\n\n    Definition state_message_oracle\n      := vstate vlsm -> message -> Prop.\n\n    Definition specialized_selected_message_exists_in_all_traces\n      (X : VLSM message)\n      (message_selector : message -> transition_item -> Prop)\n      (s : state)\n      (m : message)\n      : Prop\n      :=\n      forall\n      (start : state)\n      (tr : list transition_item)\n      (Htr : finite_protocol_trace_init_to X start s tr),\n      trace_has_message message_selector m tr.\n\n    Definition selected_message_exists_in_all_preloaded_traces\n      := specialized_selected_message_exists_in_all_traces pre_vlsm.\n\n    Definition specialized_selected_message_exists_in_some_traces\n      (X : VLSM message)\n      (message_selector : message -> transition_item -> Prop)\n      (s : state)\n      (m : message)\n      : Prop\n      :=\n      exists\n      (start : state)\n      (tr : list transition_item)\n      (Htr : finite_protocol_trace_init_to X start s tr),\n      trace_has_message message_selector m tr.\n\n    Definition selected_message_exists_in_some_preloaded_traces: forall\n      (message_selector : message -> transition_item -> Prop)\n      (s : state)\n      (m : message),\n        Prop\n      := specialized_selected_message_exists_in_some_traces pre_vlsm.\n\n    Definition specialized_selected_message_exists_in_no_trace\n      (X : VLSM message)\n      (message_selector : message -> transition_item -> Prop)\n      (s : state)\n      (m : message)\n      : Prop\n      :=\n      forall\n      (start : state)\n      (tr : list transition_item)\n      (Htr : finite_protocol_trace_init_to X start s tr),\n      ~trace_has_message message_selector m tr.\n\n    Definition selected_message_exists_in_no_preloaded_trace :=\n      specialized_selected_message_exists_in_no_trace pre_vlsm.\n\n    Lemma selected_message_exists_not_some_iff_no\n      (X : VLSM message)\n      (message_selector : message -> transition_item -> Prop)\n      (s : state)\n      (m : message)\n      : ~ specialized_selected_message_exists_in_some_traces X message_selector s m\n        <-> specialized_selected_message_exists_in_no_trace X message_selector s m.\n    Proof.\n      split.\n      - intro Hnot.\n        intros is tr Htr Hsend.\n        apply Hnot.\n        exists is, tr, Htr. exact Hsend.\n      - intros Hno [is [tr [Htr Hsend]]].\n        exact (Hno is tr Htr Hsend).\n    Qed.\n\n    Lemma selected_message_exists_preloaded_not_some_iff_no\n      (message_selector : message -> transition_item -> Prop)\n      (s : state)\n      (m : message)\n      : ~ selected_message_exists_in_some_preloaded_traces message_selector s m\n        <-> selected_message_exists_in_no_preloaded_trace message_selector s m.\n    Proof.\n      apply selected_message_exists_not_some_iff_no.\n    Qed.\n\n    (** Sufficient condition for 'specialized_selected_message_exists_in_some_traces'\n    *)\n    Lemma specialized_selected_message_exists_in_some_traces_from\n      (X : VLSM message)\n      (message_selector : message -> transition_item -> Prop)\n      (s : state)\n      (m : message)\n      (start : state)\n      (tr : list transition_item)\n      (Htr : finite_protocol_trace_from_to X start s tr)\n      (Hsome : trace_has_message message_selector m tr)\n      : specialized_selected_message_exists_in_some_traces X message_selector s m.\n    Proof.\n      assert (protocol_state_prop X start) as Hstart\n        by (apply ptrace_first_pstate in Htr; assumption).\n      apply protocol_state_has_trace in Hstart.\n      destruct Hstart as [is [tr' Htr']].\n      assert (finite_protocol_trace_init_to X is s (tr'++tr)).\n      {\n        destruct Htr'.\n        split;\n        [apply finite_protocol_trace_from_to_app with start|];\n        assumption.\n      }\n      exists _, _, H.\n      apply Exists_app.\n      right;assumption.\n    Qed.\n\n    Definition selected_messages_consistency_prop\n      (message_selector : message -> transition_item -> Prop)\n      (s : vstate vlsm)\n      (m : message)\n      : Prop\n      :=\n      selected_message_exists_in_some_preloaded_traces message_selector s m\n      <-> selected_message_exists_in_all_preloaded_traces message_selector s m.\n\n    Lemma selected_message_exists_in_all_traces_initial_state\n      (s : vstate vlsm)\n      (Hs : vinitial_state_prop vlsm s)\n      (message_selector : message -> transition_item -> Prop)\n      (m : message)\n      : ~ selected_message_exists_in_all_preloaded_traces message_selector s m.\n    Proof.\n      intro Hselected.\n      assert (Hps : protocol_state_prop pre_vlsm s)\n        by (apply initial_is_protocol;assumption).\n      assert (Htr : finite_protocol_trace_init_to pre_vlsm s s []).\n      { split; try assumption. constructor. assumption. }\n      specialize (Hselected s [] Htr).\n      unfold trace_has_message in Hselected.\n      rewrite Exists_nil in Hselected.\n      assumption.\n      Qed.\n\n(** Checks if all [protocol_trace]s leading to a certain state contain a certain message.\n    The [message_selector] argument specifices whether we're looking for received or sent\n    messages.\n\n    Notably, the [protocol_trace]s over which we are iterating belong to the preloaded\n    version of the target VLSM. This is because we want VLSMs to have oracles which\n    are valid irrespective of the composition they take part in. As we know,\n    the behaviour preloaded VLSMs includes behaviours of its projections in any\n    composition. **)\n\n    Definition all_traces_have_message_prop\n      (message_selector : message -> transition_item -> Prop)\n      (oracle : state_message_oracle)\n      (s : state)\n      (m : message)\n      : Prop\n      :=\n      oracle s m <-> selected_message_exists_in_all_preloaded_traces message_selector s m.\n\n    Definition no_traces_have_message_prop\n      (message_selector : message -> transition_item -> Prop)\n      (oracle : state_message_oracle)\n      (s : state)\n      (m : message)\n      : Prop\n      :=\n      oracle s m <-> selected_message_exists_in_no_preloaded_trace message_selector s m.\n\n    Definition has_been_sent_prop : state_message_oracle -> state -> message -> Prop\n      := (all_traces_have_message_prop (field_selector output)).\n\n    Definition has_not_been_sent_prop : state_message_oracle -> state -> message -> Prop\n      := (no_traces_have_message_prop (field_selector output)).\n\n    Definition has_been_received_prop : state_message_oracle -> state -> message -> Prop\n      := (all_traces_have_message_prop (field_selector input)).\n\n    Definition has_not_been_received_prop : state_message_oracle -> state -> message -> Prop\n      := (no_traces_have_message_prop (field_selector input)).\n\n(** Per the vocabulary of the official VLSM document, we say that VLSMs endowed\n    with a [state_message_oracle] for sent messages have the [has_been_sent] capability.\n    Capabilities for receiving messages are treated analogously, so we omit mentioning\n    them explicitly.\n\n    Notably, we also define the [has_not_been_sent] oracle, which decides if a message\n    has definitely not been sent, on any of the traces producing a current state.\n\n    Furthermore, we require a [sent_excluded_middle] property, which stipulates\n    that any argument to the oracle should return true in exactly one of\n    [has_been_sent] and [has_not_been_sent]. **)\n\n    Class has_been_sent_capability := {\n      has_been_sent: state_message_oracle;\n      has_been_sent_dec :> RelDecision has_been_sent;\n\n      proper_sent:\n        forall (s : state)\n               (Hs : protocol_state_prop pre_vlsm s)\n               (m : message),\n               (has_been_sent_prop has_been_sent s m);\n\n      has_not_been_sent: state_message_oracle\n        := fun (s : state) (m : message) => ~ has_been_sent s m;\n\n      proper_not_sent:\n        forall (s : state)\n               (Hs : protocol_state_prop pre_vlsm s)\n               (m : message),\n               has_not_been_sent_prop has_not_been_sent s m;\n    }.\n\n    (** Reverse implication for 'selected_messages_consistency_prop'\n    always holds. *)\n    Lemma consistency_from_protocol_proj2\n      (s : state)\n      (Hs: protocol_state_prop pre_vlsm s)\n      (m : message)\n      (selector : message -> transition_item -> Prop)\n      (Hall : selected_message_exists_in_all_preloaded_traces selector s m)\n      : selected_message_exists_in_some_preloaded_traces selector s m.\n    Proof.\n      apply protocol_state_has_trace in Hs.\n      destruct Hs as [is [tr Htr]].\n      exists _, _, Htr.\n      apply (Hall _ _ Htr).\n    Qed.\n\n    Lemma has_been_sent_consistency\n      {Hbs : has_been_sent_capability}\n      (s : state)\n      (Hs : protocol_state_prop pre_vlsm s)\n      (m : message)\n      : selected_messages_consistency_prop (field_selector output) s m.\n    Proof.\n      split.\n      - intro Hsome.\n        destruct (decide (has_been_sent s m)) as [Hsm|Hsm].\n        apply proper_sent in Hsm;assumption.\n        apply proper_not_sent in Hsm;[|assumption].\n        exfalso.\n        destruct Hsome as [is [tr [Htr Hmsg]]].\n        elim (Hsm _ _ Htr).\n        assumption.\n      - apply consistency_from_protocol_proj2.\n        assumption.\n    Qed.\n\n    (** Sufficent condition for 'proper_sent' avoiding the\n    'pre_loaded_with_all_messages_vlsm'\n    *)\n    Lemma specialized_proper_sent\n      {Hbs : has_been_sent_capability}\n      (s : state)\n      (Hs : protocol_state_prop vlsm s)\n      (m : message)\n      (Hsome : specialized_selected_message_exists_in_some_traces vlsm (field_selector output) s m)\n      : has_been_sent s m.\n    Proof.\n      destruct Hs as [_om Hs].\n      assert (Hpres : protocol_state_prop pre_vlsm s).\n      { exists _om. apply (pre_loaded_with_all_messages_protocol_prop vlsm). assumption. }\n      apply proper_sent; [assumption|].\n      specialize (has_been_sent_consistency s Hpres m) as Hcons.\n      apply Hcons.\n      destruct Hsome as [is [tr [Htr Hsome]]].\n      exists is, tr.\n      split; [|assumption].\n      revert Htr.\n      unfold pre_vlsm;clear.\n      destruct vlsm as (T,(S,M)).\n      apply VLSM_incl_finite_protocol_trace_init_to.\n      apply vlsm_incl_pre_loaded_with_all_messages_vlsm.\n    Qed.\n\n    (** 'proper_sent' condition specialized to regular vlsm traces\n    (avoiding 'pre_loaded_with_all_messages_vlsm')\n    *)\n    Lemma specialized_proper_sent_rev\n      {Hbs : has_been_sent_capability}\n      (s : state)\n      (Hs : protocol_state_prop vlsm s)\n      (m : message)\n      (Hsm : has_been_sent s m)\n      : specialized_selected_message_exists_in_all_traces vlsm (field_selector output) s m.\n    Proof.\n      destruct Hs as [_om Hs].\n      assert (Hpres : protocol_state_prop pre_vlsm s).\n      { exists _om. apply (pre_loaded_with_all_messages_protocol_prop vlsm). assumption. }\n      apply proper_sent in Hsm; [|assumption].\n      intros is tr Htr.\n      specialize (Hsm is tr).\n      spec Hsm;[|assumption].\n      revert Htr.\n      unfold pre_vlsm;clear.\n      destruct vlsm as (T,(S,M)).\n      apply VLSM_incl_finite_protocol_trace_init_to.\n      apply vlsm_incl_pre_loaded_with_all_messages_vlsm.\n    Qed.\n\n    Lemma has_been_sent_consistency_proper_not_sent\n      (has_been_sent: state_message_oracle)\n      (has_been_sent_dec: RelDecision has_been_sent)\n      (s : state)\n      (m : message)\n      (proper_sent: has_been_sent_prop has_been_sent s m)\n      (has_not_been_sent\n        := fun (s : state) (m : message) => ~ has_been_sent s m)\n      (Hconsistency : selected_messages_consistency_prop (field_selector output) s m)\n      : has_not_been_sent_prop has_not_been_sent s m.\n    Proof.\n      unfold has_not_been_sent_prop.\n      unfold no_traces_have_message_prop.\n      unfold has_not_been_sent.\n      rewrite <- selected_message_exists_preloaded_not_some_iff_no.\n      apply not_iff_compat.\n      apply (iff_trans proper_sent).\n      symmetry;exact Hconsistency.\n    Qed.\n\n  (** It is now straightforward to define a [no_equivocations] composition constraint.\n      An equivocating transition can be detected by calling the [has_been_sent]\n      oracle on its arguments and we simply forbid them.\n\n      However, since we might allow certain other messages, such as initial\n      messages, we give a slightly more general definition, that of\n      [no_equivocation_except_from] those specified by a given predicate.\n  **)\n\n    Definition no_equivocations_except_from\n      {Hbs : has_been_sent_capability}\n      (exception : message -> Prop)\n      (l : vlabel vlsm)\n      (som : state * option message)\n      :=\n      let (s, om) := som in\n      match om with\n      | None => True\n      | Some m => has_been_sent s m \\/ exception m\n      end.\n\n    (** The [no_equivocations] constraint only allows initial messages\n    as exceptions (messages being received without being previously sent).\n    *)\n    Definition no_equivocations\n      {Hbs : has_been_sent_capability}\n      (l : vlabel vlsm)\n      (som : state * option message)\n      : Prop\n      :=\n      no_equivocations_except_from (vinitial_message_prop vlsm) l som.\n\n\n    Class has_been_received_capability := {\n      has_been_received: state_message_oracle;\n      has_been_received_dec :> RelDecision has_been_received;\n\n      proper_received:\n        forall (s : state)\n               (Hs : protocol_state_prop pre_vlsm s)\n               (m : message),\n               (has_been_received_prop has_been_received s m);\n\n      has_not_been_received: state_message_oracle\n        := fun (s : state) (m : message) => ~ has_been_received s m;\n\n      proper_not_received:\n        forall (s : state)\n               (Hs : protocol_state_prop pre_vlsm s)\n               (m : message),\n               has_not_been_received_prop has_not_been_received s m;\n    }.\n\n    Lemma has_been_received_consistency\n      {Hbs : has_been_received_capability}\n      (s : state)\n      (Hs : protocol_state_prop pre_vlsm s)\n      (m : message)\n      : selected_messages_consistency_prop (field_selector input) s m.\n    Proof.\n      split.\n      - intro Hsome.\n        destruct (decide (has_been_received s m)) as [Hsm|Hsm];\n          [apply proper_received in Hsm;assumption|].\n        apply proper_not_received in Hsm;[|assumption].\n        destruct Hsome as [is [tr [Htr Hsome]]].\n        elim (Hsm _ _ Htr).\n        assumption.\n      - apply consistency_from_protocol_proj2.\n        assumption.\n    Qed.\n\n    Lemma has_been_received_consistency_proper_not_received\n      (has_been_received: state_message_oracle)\n      (has_been_received_dec: RelDecision has_been_received)\n      (s : state)\n      (m : message)\n      (proper_received: has_been_received_prop has_been_received s m)\n      (has_not_been_received\n        := fun (s : state) (m : message) => ~ has_been_received s m)\n      (Hconsistency : selected_messages_consistency_prop (field_selector input) s m)\n      : has_not_been_received_prop has_not_been_received s m.\n    Proof.\n      unfold has_not_been_received_prop.\n      unfold no_traces_have_message_prop.\n      unfold has_not_been_received.\n      split.\n      - intros Hsm is tr Htr Hsome.\n        assert (Hsm' : selected_message_exists_in_some_preloaded_traces (field_selector input) s m)\n          by (exists is; exists tr; exists Htr; assumption).\n        apply Hconsistency in Hsm'.\n        apply proper_received in Hsm'. contradiction.\n      - intro Hnone. destruct (decide (has_been_received s m)) as [Hsm|Hsm];[|assumption].\n        exfalso.\n        apply proper_received in Hsm. apply Hconsistency in Hsm.\n        destruct Hsm as [is [tr [Htr Hsm]]].\n        elim (Hnone is tr Htr). assumption.\n    Qed.\n\n    Definition sent_messages\n      (s : vstate vlsm)\n      : Type\n      :=\n      sig (fun m => selected_message_exists_in_some_preloaded_traces (field_selector output) s m).\n\n    Lemma sent_messages_proper\n      (Hhbs : has_been_sent_capability)\n      (s : vstate vlsm)\n      (Hs : protocol_state_prop pre_vlsm s)\n      (m : message)\n      : has_been_sent s m <-> exists (m' : sent_messages s), proj1_sig m' = m.\n    Proof.\n      unfold sent_messages. rewrite exists_proj1_sig.\n      specialize (proper_sent s Hs m) as Hbs.\n      unfold has_been_sent_prop,all_traces_have_message_prop in Hbs.\n      rewrite Hbs.\n      symmetry.\n      exact (has_been_sent_consistency s Hs m).\n    Qed.\n\n    Definition received_messages\n      (s : vstate vlsm)\n      : Type\n      :=\n      sig (fun m => selected_message_exists_in_some_preloaded_traces (field_selector input) s m).\n\n    Lemma received_messages_proper\n      (Hhbs : has_been_received_capability)\n      (s : vstate vlsm)\n      (Hs : protocol_state_prop pre_vlsm s)\n      (m : message)\n      : has_been_received s m <-> exists (m' : received_messages s), proj1_sig m' = m.\n    Proof.\n      unfold received_messages. rewrite exists_proj1_sig.\n      specialize (proper_received s Hs m) as Hbs.\n      unfold has_been_received_prop,all_traces_have_message_prop in Hbs.\n      rewrite Hbs.\n      symmetry.\n      exact (has_been_received_consistency s Hs m).\n    Qed.\n\n    Class computable_sent_messages := {\n      sent_messages_fn : vstate vlsm -> list message;\n\n      sent_messages_full :\n        forall (s : vstate vlsm) (Hs : protocol_state_prop pre_vlsm s) (m : message),\n          In m (sent_messages_fn s) <-> exists (sm : sent_messages s), proj1_sig sm = m;\n\n      sent_messages_consistency :\n        forall\n          (s : vstate vlsm)\n          (Hs : protocol_state_prop pre_vlsm s)\n          (m : message),\n          selected_messages_consistency_prop (field_selector output) s m\n    }.\n\n    Lemma computable_sent_messages_initial_state_empty\n      {Hrm : computable_sent_messages}\n      (s : vinitial_state vlsm)\n      : sent_messages_fn (proj1_sig s) = [].\n    Proof.\n      assert (Hps : protocol_state_prop pre_vlsm (proj1_sig s))\n        by (apply initial_is_protocol; apply proj2_sig).\n      destruct s as [s Hs]. simpl in *.\n      destruct (sent_messages_fn s) as [|m l] eqn:Hsm; try reflexivity.\n      specialize (sent_messages_full s Hps m) as Hl. apply proj1 in Hl.\n      spec Hl; try (rewrite Hsm; left; reflexivity).\n      destruct Hl as [[m0 Hm] Heq]. simpl in Heq. subst m0.\n      apply sent_messages_consistency in Hm; try assumption.\n      exfalso. revert Hm.\n      apply selected_message_exists_in_all_traces_initial_state.\n      assumption.\n    Qed.\n\n    Definition computable_sent_messages_has_been_sent\n      {Hsm : computable_sent_messages}\n      (s : vstate vlsm)\n      (m : message)\n      : Prop\n      :=\n      In m (sent_messages_fn s).\n\n    Global Instance computable_sent_message_has_been_sent_dec\n      {Hsm : computable_sent_messages}\n      {eq_message: EqDecision message}\n      : RelDecision computable_sent_messages_has_been_sent\n      :=\n        fun s m => in_dec decide_eq m (sent_messages_fn s).\n\n    Lemma computable_sent_messages_has_been_sent_proper\n      {Hsm : computable_sent_messages}\n      (s : state)\n      (Hs : protocol_state_prop pre_vlsm s)\n      (m : message)\n      : has_been_sent_prop computable_sent_messages_has_been_sent s m.\n    Proof.\n      unfold has_been_sent_prop. unfold all_traces_have_message_prop.\n      unfold computable_sent_messages_has_been_sent.\n      split.\n      - intro Hin.\n        apply sent_messages_full in Hin;[|assumption].\n        destruct Hin as [[m0 Hm0] Hx].\n        simpl in Hx. subst m0. apply (sent_messages_consistency s Hs m).\n        assumption.\n      - intro H.\n        apply (sent_messages_consistency s Hs m) in H.\n        apply sent_messages_full; try assumption.\n        exists (exist _ m H). reflexivity.\n    Qed.\n\n    Definition computable_sent_messages_has_not_been_sent\n      {Hsm : computable_sent_messages}\n      (s : vstate vlsm)\n      (m : message)\n      : Prop\n      :=\n      ~ computable_sent_messages_has_been_sent s m.\n\n    Lemma computable_sent_messages_has_not_been_sent_proper\n      {Hsm : computable_sent_messages}\n      (s : state)\n      (Hs : protocol_state_prop pre_vlsm s)\n      (m : message)\n      : has_not_been_sent_prop computable_sent_messages_has_not_been_sent s m.\n    Proof.\n      unfold has_not_been_sent_prop. unfold no_traces_have_message_prop.\n      unfold computable_sent_messages_has_not_been_sent.\n      unfold computable_sent_messages_has_been_sent.\n      split.\n      - intro Hin.\n        cut (~ selected_message_exists_in_some_preloaded_traces (field_selector output) s m).\n        { intros Hno is tr Htr Hexists.\n          contradict Hno;exists is, tr, Htr;assumption.\n        }\n        contradict Hin.\n        apply sent_messages_full;[assumption|].\n        exists (exist _ m Hin).\n        reflexivity.\n      - intros Htrace Hin.\n        apply sent_messages_full in Hin;[|assumption].\n        destruct Hin as [[m0 Hm] Heq];simpl in Heq;subst m0.\n        destruct Hm as [is [tr [Htr Hex]]].\n        apply (Htrace is tr Htr Hex).\n    Qed.\n\n    Definition computable_sent_messages_has_been_sent_capability\n      {Hsm : computable_sent_messages}\n      {eq_message : EqDecision message}\n      : has_been_sent_capability\n      :=\n      {|\n        has_been_sent := computable_sent_messages_has_been_sent;\n        proper_sent := computable_sent_messages_has_been_sent_proper;\n        proper_not_sent := computable_sent_messages_has_not_been_sent_proper\n      |}.\n\n    Class computable_received_messages := {\n      received_messages_fn : vstate vlsm -> list message;\n\n      received_messages_full :\n        forall (s : vstate vlsm) (Hs : protocol_state_prop pre_vlsm s) (m : message),\n          In m (received_messages_fn s) <-> exists (sm : received_messages s), proj1_sig sm = m;\n\n      received_messages_consistency :\n        forall\n          (s : vstate vlsm)\n          (Hs : protocol_state_prop pre_vlsm s)\n          (m : message),\n          selected_messages_consistency_prop (field_selector input) s m\n    }.\n\n    Lemma computable_received_messages_initial_state_empty\n      {Hrm : computable_received_messages}\n      (s : vinitial_state vlsm)\n      : received_messages_fn (proj1_sig s) = [].\n    Proof.\n      assert (Hps : protocol_state_prop pre_vlsm (proj1_sig s))\n        by (apply initial_is_protocol;apply proj2_sig).\n      destruct s as [s Hs]. simpl in *.\n      destruct (received_messages_fn s) as [|m l] eqn:Hrcv; try reflexivity.\n      specialize (received_messages_full s Hps m) as Hl. apply proj1 in Hl.\n      spec Hl; try (rewrite Hrcv; left; reflexivity).\n      destruct Hl as [[m0 Hm] Heq]. simpl in Heq. subst m0.\n      apply received_messages_consistency in Hm; try assumption.\n      exfalso. revert Hm.\n      apply selected_message_exists_in_all_traces_initial_state.\n      assumption.\n    Qed.\n\n    Definition computable_received_messages_has_been_received\n      {Hsm : computable_received_messages}\n      (s : vstate vlsm)\n      (m : message)\n      : Prop\n      :=\n      In m (received_messages_fn s).\n\n    Global Instance computable_received_messages_has_been_received_dec\n      {Hsm : computable_received_messages}\n      {eq_message : EqDecision message}\n      : RelDecision computable_received_messages_has_been_received\n      :=\n      fun s m => in_dec decide_eq m (received_messages_fn s).\n\n    Lemma computable_received_messages_has_been_received_proper\n      {Hsm : computable_received_messages}\n      (s : state)\n      (Hs : protocol_state_prop pre_vlsm s)\n      (m : message)\n      : has_been_received_prop computable_received_messages_has_been_received s m.\n    Proof.\n      unfold has_been_received_prop. unfold all_traces_have_message_prop.\n      unfold computable_received_messages_has_been_received.\n      split.\n      - intro Hin.\n        apply received_messages_full in Hin;[|assumption].\n        destruct Hin as [[m0 Hm] Heq];simpl in Heq;subst m0.\n        apply received_messages_consistency;assumption.\n      - intro H. apply received_messages_full;[assumption|].\n        apply (received_messages_consistency s Hs m) in H.\n        exists (exist _ m H). reflexivity.\n    Qed.\n\n    Definition computable_received_messages_has_not_been_received\n      {Hsm : computable_received_messages}\n      (s : vstate vlsm)\n      (m : message)\n      : Prop\n      :=\n      ~ computable_received_messages_has_been_received s m.\n\n    Lemma computable_received_messages_has_not_been_received_proper\n      {Hsm : computable_received_messages}\n      (s : state)\n      (Hs : protocol_state_prop pre_vlsm s)\n      (m : message)\n      : has_not_been_received_prop computable_received_messages_has_not_been_received s m.\n    Proof.\n      unfold has_not_been_received_prop. unfold no_traces_have_message_prop.\n      unfold computable_received_messages_has_not_been_received.\n      unfold computable_received_messages_has_been_received.\n      rewrite <- selected_message_exists_preloaded_not_some_iff_no.\n      apply not_iff_compat.\n      rewrite received_messages_full;[|assumption].\n      unfold received_messages.\n      rewrite exists_proj1_sig.\n      reflexivity.\n    Qed.\n\n    Definition computable_received_messages_has_been_received_capability\n      {Hsm : computable_received_messages}\n      {eq_message : EqDecision message}\n      : has_been_received_capability\n      :=\n      {|\n        has_been_received := computable_received_messages_has_been_received;\n        proper_received := computable_received_messages_has_been_received_proper;\n        proper_not_received := computable_received_messages_has_not_been_received_proper\n      |}.\nEnd Simple.\n\n(**\n *** Stepwise consistency properties for [state_message_oracle].\n\n The above definitions like [all_traces_have_message_prop]\n connect a [state_message_oracle] to a predicate on\n [transition_item] by relating the oracle holding on a state\n to a satsifying transition existing in all traces.\n\n This is equivalent to two local properties,\n one is that the oracle cannot only for any initial state,\n the other is that the oracle judgement is appropriately\n related for the starting and [destination] states of\n any [protocol_transition].\n\n These conditions are defined in the record [oracle_stepwise_props]\n *)\n\nRecord oracle_stepwise_props\n       [message] [vlsm: VLSM message]\n       (message_selector: message -> transition_item -> Prop)\n       (oracle: state_message_oracle vlsm) : Prop :=\n  {oracle_no_inits: forall (s: vstate vlsm),\n      initial_state_prop (VLSM_sign:=sign vlsm) s ->\n      forall m, ~oracle s m;\n   oracle_step_update:\n       forall l s im s' om,\n         protocol_transition (pre_loaded_with_all_messages_vlsm vlsm) l (s,im) (s',om) ->\n         forall msg, oracle s' msg <->\n                     (message_selector msg {|l:=l; input:=im; destination:=s'; output:=om|}\n                      \\/ oracle s msg)\n  }.\nArguments oracle_no_inits {message} {vlsm} {message_selector} {oracle} _.\nArguments oracle_step_update {message} {vlsm} {message_selector} {oracle} _.\n\nLemma oracle_partial_trace_update\n      [message] [vlsm: VLSM message]\n      [selector: message -> transition_item -> Prop]\n      [oracle: state_message_oracle vlsm]\n      (Horacle: oracle_stepwise_props selector oracle)\n      s0 s tr\n         (Htr: finite_protocol_trace_from_to (pre_loaded_with_all_messages_vlsm vlsm) s0 s tr):\n    forall m,\n      oracle s m\n      <-> (trace_has_message selector m tr \\/ oracle s0 m).\nProof.\n  induction Htr.\n  - intro m.\n    unfold trace_has_message.\n    rewrite Exists_nil.\n    tauto.\n  - intro m. specialize (IHHtr m).\n    unfold trace_has_message.\n    rewrite Exists_cons.\n    apply (Horacle.(oracle_step_update)) with (msg:=m) in H.\n    tauto.\nQed.\n\n(**\n   Proving the trace properties from the stepwise properties\n   begins with a lemma using induction along a trace to\n   prove that given a [finite_protocol_trace] to a state,\n   the oracle holds at that state for some message iff\n   a satsifying transition item exists in the trace.\n\n   The theorems for [all_traces_have_message_prop]\n   and [no_traces_have_message_prop] are mostly rearraning\n   quantifiers to use this lemma, also using [protocol_state_prop]\n   to choose a trace to the state for the directions where\n   one is not given.\n *)\nSection TraceFromStepwise.\n  Context\n    (message : Type)\n    (vlsm: VLSM message)\n    (selector : message -> transition_item -> Prop)\n    (oracle : state_message_oracle vlsm)\n    (oracle_props : oracle_stepwise_props selector oracle)\n    .\n\n  Local Lemma H_protocol_trace_prop\n        [s0 s tr]\n        (Htr: finite_protocol_trace_init_to (pre_loaded_with_all_messages_vlsm vlsm) s0 s tr):\n    forall m,\n      oracle s m <-> trace_has_message selector m tr.\n  Proof.\n    intro m.\n    destruct Htr as [Htr Hinit].\n    rewrite (oracle_partial_trace_update oracle_props _ _ _ Htr).\n    assert (~oracle s0 m).\n    apply oracle_props, Hinit.\n    tauto.\n  Qed.\n\n  Lemma prove_all_have_message_from_stepwise:\n    forall (s : state)\n           (Hs : protocol_state_prop (pre_loaded_with_all_messages_vlsm vlsm) s)\n           (m : message),\n      (all_traces_have_message_prop vlsm selector oracle s m).\n  Proof.\n    intros s Hproto m.\n    unfold all_traces_have_message_prop.\n    split.\n    - intros Hsent s0 tr Htr.\n      apply (H_protocol_trace_prop Htr).\n      assumption.\n    - intro H_all_traces.\n      apply protocol_state_has_trace in Hproto.\n      destruct Hproto as [s0 [tr Htr]].\n      apply (H_protocol_trace_prop Htr).\n      specialize (H_all_traces s0 tr Htr).\n      assumption.\n  Qed.\n\n  Lemma prove_none_have_message_from_stepwise:\n    forall (s : state)\n           (Hs : protocol_state_prop (pre_loaded_with_all_messages_vlsm vlsm) s)\n           (m : message),\n      no_traces_have_message_prop vlsm selector (fun s m => ~oracle s m) s m.\n  Proof.\n    intros s Hproto m.\n    pose proof (H_protocol_trace_prop).\n    split.\n    - intros H_not_sent start tr Htr.\n      contradict H_not_sent.\n      apply (H_protocol_trace_prop Htr).\n      assumption.\n    - intros H_no_traces.\n      apply protocol_state_has_trace in Hproto.\n      destruct Hproto as [s0 [tr Htr]].\n      specialize (H_no_traces s0 tr Htr).\n      contradict H_no_traces.\n      apply (H_protocol_trace_prop Htr).\n      assumption.\n  Qed.\n\n  Lemma in_futures_preserving_oracle_from_stepwise:\n    forall (s1 s2: state)\n      (Hfutures : in_futures (pre_loaded_with_all_messages_vlsm vlsm) s1 s2)\n      (m : message),\n      oracle s1 m -> oracle  s2 m.\n  Proof.\n    intros s1 s2 [tr Htr] m Hs1m.\n    apply (oracle_partial_trace_update oracle_props _ _ _ Htr).\n    right;assumption.\n  Qed.\nEnd TraceFromStepwise.\n\n(**\n   The stepwise properties are proven from the trace properties\n   by considering the empty trace to prove the [oracle_no_inits]\n   property, and by considering a trace that ends with the given\n   [protocol_transition] to prove the [oracle_step_update] property.\n *)\nSection StepwiseFromTrace.\n  Context\n    (message : Type)\n    (vlsm: VLSM message)\n    (selector: message -> transition_item -> Prop)\n    (oracle: state_message_oracle vlsm)\n    (oracle_dec: RelDecision oracle)\n    (Horacle_all_have:\n       forall s (Hs: protocol_state_prop (pre_loaded_with_all_messages_vlsm vlsm) s) m,\n        all_traces_have_message_prop vlsm selector oracle s m)\n    (Hnot_oracle_none_have:\n       forall s (Hs: protocol_state_prop (pre_loaded_with_all_messages_vlsm vlsm) s) m,\n         no_traces_have_message_prop vlsm selector (fun m s => ~oracle m s) s m).\n\n  Lemma oracle_no_inits_from_trace:\n    forall (s: vstate vlsm), initial_state_prop (VLSM_sign:=sign vlsm) s ->\n                             forall m, ~oracle s m.\n  Proof.\n    intros s Hinit m Horacle.\n    assert (Hproto : protocol_state_prop (pre_loaded_with_all_messages_vlsm vlsm) s)\n      by (apply initial_is_protocol;assumption).\n    apply Horacle_all_have in Horacle;[|assumption].\n    specialize (Horacle s nil).\n    eapply Exists_nil;apply Horacle;clear Horacle.\n    split;[constructor|];assumption.\n  Qed.\n\n  Lemma examine_one_trace:\n    forall is s tr,\n      finite_protocol_trace_init_to (pre_loaded_with_all_messages_vlsm vlsm) is s tr ->\n    forall m,\n      oracle s m <->\n      trace_has_message selector m tr.\n  Proof.\n    intros is s tr Htr m.\n    assert (protocol_state_prop (pre_loaded_with_all_messages_vlsm vlsm) s)\n      by (apply ptrace_last_pstate in Htr;assumption).\n    split.\n    - intros Horacle.\n      apply Horacle_all_have in Horacle;[|assumption].\n      specialize (Horacle is tr Htr).\n      assumption.\n    - intro Hexists.\n      apply dec_stable.\n      intro Hnot.\n      apply Hnot_oracle_none_have in Hnot;[|assumption].\n      rewrite <- selected_message_exists_preloaded_not_some_iff_no in Hnot.\n      apply Hnot.\n      exists is, tr, Htr.\n      assumption.\n  Qed.\n\n  Lemma oracle_step_property_from_trace:\n       forall l s im s' om,\n         protocol_transition (pre_loaded_with_all_messages_vlsm vlsm) l (s,im) (s',om) ->\n         forall msg, oracle s' msg\n                     <-> (selector msg {| l:=l; input:=im; destination:=s'; output:=om |}\n                          \\/ oracle s msg).\n  Proof.\n    intros l s im s' om Htrans msg.\n    rename Htrans into Htrans'.\n    pose proof Htrans' as [[Hproto_s [Hproto_m Hvalid]] Htrans].\n    set (preloaded:= pre_loaded_with_all_messages_vlsm vlsm) in * |- *.\n\n    pose proof (protocol_state_has_trace _ _ Hproto_s)\n      as [is [tr [Htr Hinit]]].\n\n    pose proof (Htr' := extend_right_finite_trace_from_to _ Htr Htrans').\n\n    rewrite (examine_one_trace _ _ _ (conj Htr Hinit) msg).\n    rewrite (examine_one_trace _ _ _ (conj Htr' Hinit) msg).\n    clear.\n    progress cbn. unfold trace_has_message.\n    rewrite Exists_app, Exists_cons, Exists_nil.\n    tauto.\n  Qed.\n\n  Lemma stepwise_props_from_trace : oracle_stepwise_props selector oracle.\n  Proof.\n    constructor.\n    refine oracle_no_inits_from_trace.\n    refine oracle_step_property_from_trace.\n  Defined.\nEnd StepwiseFromTrace.\n\n(**\n** Stepwise view of [has_been_sent_capability]\n\nThis reduces the proof obligations in [has_been_sent_capability]\nto proving the stepwise properties of [oracle_stepwise_props].\n[has_been_step_stepwise_props] is a specialization of [oracle_stepwise_props]\nto the right <<message_selector>>.\n\nThere are also lemmas for accessing the stepwise properties about\na [has_been_sent] predicate given an instance of [has_been_sent_capability], to allow using\n[has_been_sent_capability_from_stepwise] to define a [has_been_sent_capability]\nfor composite VLSMs, or for proofs (e.g, about invariants) where\nthese are more convenient.\n **)\n\nDefinition has_been_sent_stepwise_props\n       [message] [vlsm: VLSM message] (has_been_sent_pred: state_message_oracle vlsm) : Prop :=\n  (oracle_stepwise_props (field_selector output) has_been_sent_pred).\n\nLemma has_been_sent_capability_from_stepwise\n      [message : Type]\n      [vlsm: VLSM message]\n      [has_been_sent_pred: state_message_oracle vlsm]\n      (has_been_sent_pred_dec: RelDecision has_been_sent_pred)\n      (has_been_sent_alt_props: has_been_sent_stepwise_props has_been_sent_pred):\n  has_been_sent_capability vlsm.\nProof.\n  refine ({|has_been_sent:=has_been_sent_pred|}).\n  apply prove_all_have_message_from_stepwise;assumption.\n  apply prove_none_have_message_from_stepwise;assumption.\nDefined.\n\nLemma has_been_sent_stepwise_from_trace\n      [message : Type]\n      [vlsm: VLSM message]\n      (Hhbs: has_been_sent_capability vlsm):\n  oracle_stepwise_props (field_selector output) (has_been_sent vlsm).\nProof.\n  apply stepwise_props_from_trace.\n  apply has_been_sent_dec.\n  apply proper_sent.\n  apply proper_not_sent.\nDefined.\n\nLemma has_been_sent_step_update\n      `{Hhbs: has_been_sent_capability message vlsm}:\n  forall [l s im s' om],\n    protocol_transition (pre_loaded_with_all_messages_vlsm vlsm) l (s,im) (s',om) ->\n    forall m,\n      has_been_sent vlsm s' m <-> (om = Some m \\/ has_been_sent vlsm s m).\nProof.\n  exact (oracle_step_update (has_been_sent_stepwise_from_trace Hhbs)).\nQed.\n\n(**\n** Stepwise view of [has_been_received_capability]\n *)\n\nDefinition has_been_received_stepwise_props\n       [message] [vlsm: VLSM message] (has_been_received_pred: state_message_oracle vlsm) : Prop :=\n  (oracle_stepwise_props (field_selector input) has_been_received_pred).\n\nLemma has_been_received_capability_from_stepwise\n      [message : Type]\n      [vlsm: VLSM message]\n      [has_been_received_pred: state_message_oracle vlsm]\n      (has_been_received_pred_dec: RelDecision has_been_received_pred)\n      (has_been_sent_alt_props: has_been_received_stepwise_props has_been_received_pred):\n  has_been_received_capability vlsm.\nProof.\n  refine ({|has_been_received:=has_been_received_pred|}).\n  apply prove_all_have_message_from_stepwise;assumption.\n  apply prove_none_have_message_from_stepwise;assumption.\nDefined.\n\nLemma has_been_received_stepwise_from_trace\n      [message : Type]\n      [vlsm: VLSM message]\n      (Hhbr: has_been_received_capability vlsm):\n  oracle_stepwise_props (field_selector input) (has_been_received vlsm).\nProof.\n  apply stepwise_props_from_trace.\n  apply has_been_received_dec.\n  apply proper_received.\n  apply proper_not_received.\nDefined.\n\nLemma has_been_received_step_update\n      `{Hhbs: has_been_received_capability message vlsm}:\n  forall [l s im s' om],\n    protocol_transition (pre_loaded_with_all_messages_vlsm vlsm) l (s,im) (s',om) ->\n    forall m,\n      has_been_received vlsm s' m <-> (im = Some m \\/ has_been_received vlsm s m).\nProof.\n  exact (oracle_step_update (has_been_received_stepwise_from_trace Hhbs)).\nQed.\n\n(**\n** A state message oracle for messages sent or received\n\nIn protocols like the CBC full node protocol, validators often\nwork with the set of all messages they have directly observed,\nwhich includes the messages the node sent itself along with\nmessages that were received.\nThe [has_been_observed] oracle holds for a message if the\nmessage was sent or received in any transition.\n *)\n\nClass has_been_observed_capability {message} (vlsm: VLSM message) :=\n  {\n  has_been_observed: state_message_oracle vlsm;\n  has_been_observed_dec :> RelDecision has_been_observed;\n  has_been_observed_stepwise_props: oracle_stepwise_props item_sends_or_receives has_been_observed;\n  }.\nArguments has_been_observed {message} vlsm {_}.\nArguments has_been_observed_dec {message} vlsm {_}.\n\nDefinition has_been_observed_step_update `{Hhbo: has_been_observed_capability message vlsm} :\n  forall l s im s' om,\n    protocol_transition (pre_loaded_with_all_messages_vlsm vlsm) l (s, im) (s', om) ->\n    forall msg,\n      has_been_observed vlsm s' msg <->\n      ((im = Some msg \\/ om = Some msg) \\/ has_been_observed vlsm s msg)\n  := oracle_step_update has_been_observed_stepwise_props.\n\nLemma proper_observed `(Hhbo: has_been_observed_capability message vlsm):\n  forall (s:state),\n    protocol_state_prop (pre_loaded_with_all_messages_vlsm vlsm) s ->\n    forall m,\n      all_traces_have_message_prop vlsm item_sends_or_receives (has_been_observed vlsm) s m.\nProof.\n  intros.\n  apply prove_all_have_message_from_stepwise.\n  apply Hhbo.\n  assumption.\nQed.\n\nLemma proper_not_observed `(Hhbo: has_been_observed_capability message vlsm):\n  forall (s:state),\n    protocol_state_prop (pre_loaded_with_all_messages_vlsm vlsm) s ->\n    forall m,\n      no_traces_have_message_prop vlsm item_sends_or_receives\n                                  (fun s m => ~has_been_observed vlsm s m) s m.\nProof.\n  intros.\n  apply prove_none_have_message_from_stepwise.\n  apply Hhbo.\n  assumption.\nQed.\n\n(** A received message introduces no additional equivocations to a state\n    if it has already been observed in s or it is an initial message.\n*)\nDefinition no_additional_equivocations\n  {message : Type}\n  (vlsm : VLSM message)\n  {Hbo : has_been_observed_capability vlsm}\n  (s : state)\n  (m : message)\n  : Prop\n  :=\n  has_been_observed vlsm s m \\/ vinitial_message_prop vlsm m.\n\n(** If the [initial_message_prop] is decidable, then the\n    [no_additional_equivocations] is also decidable.\n*)\n\n  Lemma no_additional_equivocations_dec\n  {message : Type}\n  (vlsm : VLSM message)\n  {Hbo : has_been_observed_capability vlsm}\n  (initial_dec : vdecidable_initial_messages_prop vlsm)\n  : RelDecision (no_additional_equivocations vlsm).\nProof.\n  intros s m. apply Decision_or; [|apply initial_dec].\n  apply has_been_observed_dec.\nQed.\n\nDefinition no_additional_equivocations_constraint\n  {message : Type}\n  (vlsm : VLSM message)\n  {Hbo : has_been_observed_capability vlsm}\n  (l : vlabel vlsm)\n  (som : state * option message)\n  : Prop\n  :=\n  let (s, om) := som in\n  match om with\n  | None => True\n  | Some m => no_additional_equivocations vlsm s m\n  end.\n\nSection sent_received_observed_capabilities.\n\nContext\n  {message : Type}\n  (vlsm : VLSM message)\n  {Hbr : has_been_received_capability vlsm}\n  {Hbs : has_been_sent_capability vlsm}\n  .\n\nLemma has_been_observed_sent_received_iff\n  {Hbo : has_been_observed_capability vlsm}\n  (s : state)\n  (Hs : protocol_state_prop (pre_loaded_with_all_messages_vlsm vlsm) s)\n  (m : message)\n  : has_been_observed vlsm s m <-> has_been_received vlsm s m \\/ has_been_sent vlsm s m.\nProof.\n  specialize\n    (prove_all_have_message_from_stepwise message vlsm  item_sends_or_receives\n    (has_been_observed vlsm) has_been_observed_stepwise_props _ Hs m) as Hall.\n  split; [intro H | intros [H | H]].\n  - apply proj1 in Hall. specialize (Hall H).\n    apply consistency_from_protocol_proj2 in Hall; [|assumption].\n    destruct Hall as [is [tr [Htr Hexists]]].\n    apply Exists_or_inv in Hexists.\n    destruct Hexists as [Hsent | Hreceived].\n    + left. specialize (has_been_received_consistency vlsm _ Hs m) as Hcons.\n      apply proper_received; [assumption|].\n      apply Hcons. exists is, tr, Htr. assumption.\n    + right. specialize (has_been_sent_consistency vlsm _ Hs m) as Hcons.\n      apply proper_sent; [assumption|].\n      apply Hcons. exists is, tr, Htr. assumption.\n  - apply Hall.\n    intro is; intros.\n    apply proper_received in H; [|assumption]. specialize (H is tr Htr).\n    apply Exists_or. left. assumption.\n  - apply Hall.\n    intro is; intros.\n    apply proper_sent in H; [|assumption]. specialize (H is tr Htr).\n    apply Exists_or. right. assumption.\nQed.\n\nDefinition has_been_observed_from_sent_received\n  (s : vstate vlsm)\n  (m : message)\n  : Prop\n  := has_been_sent vlsm s m \\/ has_been_received vlsm s m.\n\nLemma has_been_observed_from_sent_received_dec\n  : RelDecision has_been_observed_from_sent_received.\nProof.\n  intros s m.\n  apply Decision_or.\n  - apply has_been_sent_dec.\n  - apply has_been_received_dec.\nQed.\n\nLemma has_been_observed_from_sent_received_stepwise_props\n  : oracle_stepwise_props item_sends_or_receives has_been_observed_from_sent_received.\nProof.\n  apply stepwise_props_from_trace; [apply has_been_observed_from_sent_received_dec|..]\n  ; intros; split; intros.\n  - intro; intros.\n    destruct H as [H | H].\n    + apply proper_sent in H; [|apply Hs]. specialize (H _ _ Htr).\n      apply Exists_or. right. assumption.\n    + apply proper_received in H; [|apply Hs]. specialize (H _ _ Htr).\n      apply Exists_or. left. assumption.\n  - apply consistency_from_protocol_proj2 in H; [|assumption].\n    destruct H as [is [tr [Htr Hexists]]].\n    apply Exists_or_inv in Hexists.\n    destruct Hexists as [Hsent | Hreceived].\n    + right. apply proper_received; [assumption|].\n      apply has_been_received_consistency; [assumption|assumption|].\n      exists is, tr, Htr. assumption.\n    + left. apply proper_sent; [assumption|].\n      apply has_been_sent_consistency; [assumption|assumption|].\n      exists is, tr, Htr. assumption.\n  - intro; intros. intro Hexists. elim H.\n    apply Exists_or_inv in Hexists.\n    destruct Hexists as [Hexists| Hexists].\n    + right. apply proper_received; [assumption|].\n      apply has_been_received_consistency; [assumption|assumption|].\n      exists start, tr, Htr. assumption.\n    + left. apply proper_sent; [assumption|].\n      apply has_been_sent_consistency; [assumption|assumption|].\n      exists start, tr, Htr. assumption.\n  - intros [Hobs | Hobs].\n    + apply proper_sent in Hobs; [|assumption].\n      apply has_been_sent_consistency in Hobs; [|assumption|assumption].\n      destruct Hobs as [is [tr [Htr Hexists]]].\n      specialize (H _ _ Htr). elim H. apply Exists_or. right. assumption.\n    + apply proper_received in Hobs; [|assumption].\n      apply has_been_received_consistency in Hobs; [|assumption|assumption].\n      destruct Hobs as [is [tr [Htr Hexists]]].\n      specialize (H _ _ Htr). elim H. apply Exists_or. left. assumption.\nQed.\n\nLocal Program Instance has_been_observed_capability_from_sent_received\n  : has_been_observed_capability vlsm\n  :=\n  { has_been_observed := has_been_observed_from_sent_received;\n    has_been_observed_dec := has_been_observed_from_sent_received_dec;\n\n    has_been_observed_stepwise_props := has_been_observed_from_sent_received_stepwise_props\n  }.\n\nEnd sent_received_observed_capabilities.\n\n(**\n*** No-Equivocation Invariants\n\nA VLSM that enforces the [no_equivocations] constraint and also\nsupports [has_been_recevied] (or [has_been_observed]) obeys an\ninvariant that any message that tests as [has_been_received]\n(resp. [has_been_observed]) in a state also tests as [has_been_sent]\nin the same state.\n *)\nSection NoEquivocationInvariants.\n  Context\n    message\n    (X: VLSM message)\n    (Hhbs: has_been_sent_capability X)\n    (Hhbo: has_been_observed_capability X)\n    (Henforced: forall l s om, vvalid X l (s,om) -> no_equivocations X l (s,om))\n  .\n\n  Definition observed_were_sent_or_initial (s: state) : Prop :=\n    forall msg, has_been_observed X s msg -> has_been_sent X s msg \\/ vinitial_message_prop X msg.\n\n  Lemma observed_were_sent_initial s:\n    vinitial_state_prop X s ->\n    observed_were_sent_or_initial s.\n  Proof.\n    intros Hinitial msg Hsend.\n    contradict Hsend.\n    apply (oracle_no_inits has_been_observed_stepwise_props).\n    assumption.\n  Qed.\n\n  Lemma observed_were_sent_preserved l s im s' om:\n    protocol_transition X l (s,im) (s',om) ->\n    observed_were_sent_or_initial s ->\n    observed_were_sent_or_initial s'.\n  Proof.\n    intros Hptrans Hprev msg Hobs.\n    specialize (Hprev msg).\n    apply preloaded_weaken_protocol_transition in Hptrans.\n    apply (oracle_step_update has_been_observed_stepwise_props _ _ _ _ _ Hptrans) in Hobs.\n    simpl in Hobs.\n    specialize (Henforced l s (Some msg)).\n    rewrite (oracle_step_update (has_been_sent_stepwise_from_trace Hhbs) _ _ _ _ _ Hptrans).\n    destruct Hptrans as [[_ [_  Hv]] _].\n    destruct Hobs as [[|]|].\n    - (* by [no_equivocations], the incoming message [im] was previously sent *)\n      rewrite H in Hv.\n      specialize (Henforced Hv).\n      destruct Henforced; [|right; assumption].\n      left. right. assumption.\n    - left. left. assumption.\n    - specialize (Hprev H).\n      destruct Hprev as [Hprev|Hprev]; [|right; assumption].\n      left. right. assumption.\n  Qed.\n\n  Lemma observed_were_sent_invariant s:\n    protocol_state_prop X s ->\n    observed_were_sent_or_initial s.\n  Proof.\n    intro Hproto.\n    induction Hproto using protocol_state_prop_ind.\n    - intros msg Hsend.\n      contradict Hsend.\n      apply (oracle_no_inits has_been_observed_stepwise_props).\n      assumption.\n    - intros msg Hobs.\n      specialize (IHHproto msg).\n      apply preloaded_weaken_protocol_transition in Ht.\n      apply (oracle_step_update has_been_observed_stepwise_props _ _ _ _ _ Ht) in Hobs.\n      specialize (Henforced l s (Some msg)).\n      rewrite (oracle_step_update (has_been_sent_stepwise_from_trace Hhbs) _ _ _ _ _ Ht).\n      destruct Ht as [[_ [_  Hv]] _].\n      simpl in Hobs |- *.\n      destruct Hobs as [[|]|].\n      + (* by [no_equivocations], the incoming message [im] was previously sent *)\n        rewrite H in Hv.\n        spec Henforced Hv.\n        destruct Henforced as [Hbs | Hinitial]; [|right; assumption].\n        left. right. assumption.\n      + left. left. assumption.\n      + spec IHHproto H. destruct IHHproto; [|right; assumption].\n        left. right. assumption.\n  Qed.\n\n  Lemma no_equivocations_preloaded_traces\n    (is : state)\n    (tr : list transition_item)\n    : finite_protocol_trace (pre_loaded_with_all_messages_vlsm X) is tr -> finite_protocol_trace X is tr.\n  Proof.\n    intro Htr.\n    induction Htr using finite_protocol_trace_rev_ind.\n    - split;[|assumption].\n      rapply @finite_ptrace_empty.\n      apply initial_is_protocol.\n      assumption.\n    - destruct IHHtr as [IHtr His].\n      split; [|assumption].\n      rapply extend_right_finite_trace_from;[assumption|].\n      apply protocol_transition_origin in Hx as Hlst'.\n      destruct Hx as [Hvalid Htrans].\n      split;[|exact Htrans].\n      apply finite_ptrace_last_pstate in IHtr as Hstate.\n      split;[assumption|]. clear Hstate.\n      split;[|apply Hvalid].\n      destruct Hvalid as [_ [_ Hv]].\n      apply Henforced in Hv.\n      destruct iom as [m|]; [|apply option_protocol_message_None].\n      apply option_protocol_message_Some.\n      destruct Hv as [Hbsm | Him]\n      ; [|apply initial_message_is_protocol; assumption].\n      apply proper_sent in Hbsm; [|assumption].\n      specialize (Hbsm _ tr (ptrace_add_default_last Htr)).\n      apply can_emit_protocol.\n      apply (can_emit_from_protocol_trace X _ _ _ (conj IHtr His) Hbsm).\n  Qed.\n\n  Lemma preloaded_incl_no_equivocations\n    : VLSM_incl (pre_loaded_with_all_messages_vlsm X) X.\n  Proof.\n    specialize no_equivocations_preloaded_traces.\n    clear -X. destruct X as [T [S M]].\n    apply VLSM_incl_finite_traces_characterization.\n  Qed.\n\n  Lemma preloaded_eq_no_equivocations\n    : VLSM_eq (pre_loaded_with_all_messages_vlsm X) X.\n  Proof.\n    specialize preloaded_incl_no_equivocations.\n    specialize (vlsm_incl_pre_loaded_with_all_messages_vlsm X).\n    clear -X. destruct X as [T [S M]].\n    intros Hincl Hincl'.\n    apply VLSM_eq_incl_iff. split; assumption.\n  Qed.\n\nEnd NoEquivocationInvariants.\n\n(**\n*** Equivocation in compositions.\n\n We now move on to a composite context. Each component of our composition\n    will have [has_been_sent] and [has_been_received] capabilities.\n\n    We introduce [validator]s along with their respective [Weight]s, the\n    [A] function which maps validators to indices of component VLSMs and\n    the [sender] function which maps messages to their (unique) designated\n    sender (if any).\n\n    For the equivocation fault sum to be computable, we also require that\n    the number of [validator]s and the number of machines in the\n    composition are both finite. See [finite_index], [finite_validator].\n**)\n\nSection Composite.\n\n  Context {message : Type}\n          {index : Type}\n          {IndEqDec : EqDecision index}\n          (IM : index -> VLSM message)\n          {i0 : Inhabited index}\n          (constraint : composite_label IM -> composite_state IM  * option message -> Prop)\n          (X := composite_vlsm IM constraint)\n          {index_listing : list index}\n          (finite_index : Listing index_listing)\n          (has_been_sent_capabilities : forall i : index, (has_been_sent_capability (IM i)))\n          (has_been_observed_capabilities : forall i : index, (has_been_observed_capability (IM i)))\n          .\n\n  Section StepwiseProps.\n    Context\n      [message_selectors: forall i : index, message -> vtransition_item (IM i) -> Prop]\n      [oracles: forall i, state_message_oracle (IM i)]\n      (stepwise_props: forall i, oracle_stepwise_props (message_selectors i) (oracles i))\n      .\n\n      Definition composite_message_selector : message -> vtransition_item X -> Prop.\n      Proof.\n        intros msg [[i li] input s output].\n        apply (message_selectors i msg).\n        exact {|l:=li;input:=input;destination:=s i;output:=output|}.\n      Defined.\n\n      Definition composite_oracle : vstate X -> message -> Prop :=\n        fun s msg => exists i, oracles i (s i) msg.\n\n      Lemma composite_stepwise_props :\n        oracle_stepwise_props composite_message_selector composite_oracle.\n      Proof.\n        split.\n        - (* initial states not claim *)\n          intros s Hs m [i H].\n          revert H.\n          fold (~ oracles i (s i) m).\n          apply (oracle_no_inits (stepwise_props i)).\n          apply Hs.\n        - (* step update property *)\n          intros l s im s' om Hproto msg.\n          destruct l as [i li].\n          simpl.\n          assert (forall j, s j = s' j \\/ j = i).\n          {\n            intro j.\n            apply (protocol_transition_preloaded_project_any j) in Hproto.\n            destruct Hproto;[left;assumption|right].\n            destruct H as [lj [Hlj _]].\n            congruence.\n          }\n          apply protocol_transition_preloaded_project_active in Hproto;simpl in Hproto.\n          apply (oracle_step_update (stepwise_props i)) with (msg:=msg) in Hproto.\n          split.\n          + intros [j Hj].\n            destruct (H j) as [Hunchanged|Hji].\n            * right;exists j;rewrite Hunchanged;assumption.\n            * subst j.\n              apply Hproto in Hj.\n              destruct Hj;[left;assumption|right;exists i;assumption].\n          + intros [Hnow | [j Hbefore]].\n            * exists i.\n              apply Hproto.\n              left;assumption.\n            * exists j.\n              destruct (H j) as [Hunchanged| ->].\n              -- rewrite <- Hunchanged;assumption.\n              -- apply Hproto.\n                 right.\n                 assumption.\n      Qed.\n  End StepwiseProps.\n\n  (** A message 'has_been_sent' for a composite state if it 'has_been_sent' for any of\n  its components.*)\n  Definition composite_has_been_sent\n    (s : vstate X)\n    (m : message)\n    : Prop\n    := exists (i : index), has_been_sent (IM i) (s i) m.\n\n  (** 'composite_has_been_sent' is decidable. *)\n  Lemma composite_has_been_sent_dec : RelDecision composite_has_been_sent.\n  Proof.\n    intros s m.\n    apply (Decision_iff (P:=List.Exists (fun i => has_been_sent (IM i) (s i) m) index_listing)).\n    - rewrite <- exists_finite by (apply finite_index). reflexivity.\n    - apply Exists_dec.\n  Qed.\n\n  Lemma composite_has_been_sent_stepwise_props :\n    has_been_sent_stepwise_props composite_has_been_sent.\n  Proof.\n    unfold has_been_sent_stepwise_props.\n    pose proof (composite_stepwise_props\n                  (fun i => has_been_sent_stepwise_from_trace\n                              (has_been_sent_capabilities i)))\n         as [Hinits Hstep].\n    split;[exact Hinits|].\n    (* <<exact Hstep>> doesn't work because [composite_message_selector]\n       pattern matches on the label l, so we instantiate and destruct\n       to let that simplify *)\n    intros l;specialize (Hstep l);destruct l.\n    exact Hstep.\n  Qed.\n\n  Global Instance composite_has_been_sent_capability : has_been_sent_capability X :=\n    has_been_sent_capability_from_stepwise\n      composite_has_been_sent_dec\n      composite_has_been_sent_stepwise_props.\n\n  Section composite_has_been_received.\n\n  Context\n        (has_been_received_capabilities : forall i : index, (has_been_received_capability (IM i)))\n        .\n\n  (** A message 'has_been_received' for a composite state if it 'has_been_received' for any of\n  its components.*)\n  Definition composite_has_been_received\n    (s : vstate X)\n    (m : message)\n    : Prop\n    := exists (i : index), has_been_received (IM i) (s i) m.\n\n  (** 'composite_has_been_received' is decidable. *)\n  Lemma composite_has_been_received_dec : RelDecision composite_has_been_received.\n  Proof.\n    intros s m.\n    apply (Decision_iff (P:=List.Exists (fun i => has_been_received (IM i) (s i) m) index_listing)).\n    - rewrite <- exists_finite by (apply finite_index). reflexivity.\n    - apply Exists_dec.\n  Qed.\n\n  Lemma composite_has_been_received_stepwise_props :\n    has_been_received_stepwise_props composite_has_been_received.\n  Proof.\n    unfold has_been_received_stepwise_props.\n    pose proof (composite_stepwise_props\n                  (fun i => has_been_received_stepwise_from_trace\n                              (has_been_received_capabilities i)))\n         as [Hinits Hstep].\n    split;[exact Hinits|].\n    (* <<exact Hstep>> doesn't work because [composite_message_selector]\n       pattern matches on the label l, so we instantiate and destruct\n       to let that simplify *)\n    intros l;specialize (Hstep l);destruct l.\n    exact Hstep.\n  Qed.\n\n  Global Instance composite_has_been_received_capability : has_been_received_capability X :=\n    has_been_received_capability_from_stepwise\n      composite_has_been_received_dec\n      composite_has_been_received_stepwise_props.\n\n  End composite_has_been_received.\n\n\n  (** A message 'has_been_observed' for a composite state if it 'has_been_observed' for any of\n  its components.*)\n  Definition composite_has_been_observed\n    (s : vstate X)\n    (m : message)\n    : Prop\n    := exists (i : index), has_been_observed (IM i) (s i) m.\n\n  (** 'composite_has_been_observed' is decidable. *)\n  Lemma composite_has_been_observed_dec : RelDecision composite_has_been_observed.\n  Proof.\n    intros s m.\n    apply (Decision_iff (P:=List.Exists (fun i => has_been_observed (IM i) (s i) m) index_listing)).\n    - rewrite <- exists_finite by (apply finite_index). reflexivity.\n    - apply Exists_dec.\n  Qed.\n\n  Lemma composite_has_been_observed_stepwise_props :\n    oracle_stepwise_props item_sends_or_receives composite_has_been_observed.\n  Proof.\n    pose proof (composite_stepwise_props\n                  (fun i => has_been_observed_stepwise_props))\n         as [Hinits Hstep].\n    split;[exact Hinits|].\n    intros l;specialize (Hstep l);destruct l.\n    exact Hstep.\n  Qed.\n\n  Global Instance composite_has_been_observed_capability : has_been_observed_capability X :=\n    { has_been_observed_dec := composite_has_been_observed_dec;\n      has_been_observed_stepwise_props := composite_has_been_observed_stepwise_props\n    }.\n\n  Context\n        {validator : Type}\n        (A : validator -> index)\n        (sender : message -> option validator)\n        .\n\n  (** Definitions for safety and nontriviality of the [sender] function.\n      Safety means that if we designate a validator as the sender\n      of a certain messsage, then it is impossible for other components\n      to produce that message\n\n      Weak/strong nontriviality say that each validator should\n      be designated sender for at least one/all its protocol\n      messages.\n  **)\n\n  Definition sender_safety_prop : Prop :=\n    forall\n    (i : index)\n    (m : message)\n    (v : validator)\n    (Hid : A v = i)\n    (Hsender : sender m = Some v),\n    can_emit (composite_vlsm_constrained_projection IM constraint i) m /\\\n    forall (j : index)\n           (Hdif : i <> j),\n           ~can_emit (composite_vlsm_constrained_projection IM constraint j) m.\n\n   (** An alternative, possibly friendlier, formulation. Note that it is\n       slightly weaker, in that it does not require that the sender\n       is able to send the message. **)\n\n  Definition sender_safety_alt_prop : Prop :=\n    forall\n    (i : index)\n    (m : message)\n    (v : validator)\n    (Hsender : sender m = Some v),\n    can_emit (composite_vlsm_constrained_projection IM constraint i) m ->\n    A v = i.\n\n  Definition sender_weak_nontriviality_prop : Prop :=\n    forall (v : validator),\n    exists (m : message),\n    can_emit (composite_vlsm_constrained_projection IM constraint (A v)) m /\\\n    sender m = Some v.\n\n  Definition sender_strong_nontriviality_prop : Prop :=\n    forall (v : validator),\n    forall (m : message),\n    can_emit (composite_vlsm_constrained_projection IM constraint (A v)) m ->\n    sender m = Some v.\n\n  Definition no_sender_for_initial_message_prop : Prop :=\n    forall (m : message),\n    vinitial_message_prop X m ->\n    sender m = None.\n\n  Context\n        (has_been_received_capabilities : forall i : index, (has_been_received_capability (IM i)))\n        .\n\n   (** We say that a validator <v> (with associated component <i>) is equivocating wrt.\n   to another component <j>, if there exists a message which [has_been_received] by\n   <j> but [has_not_been_sent] by <i> **)\n\n  Definition equivocating_wrt\n    (v : validator)\n    (j : index)\n    (sv sj : state)\n    (i := A v)\n    : Prop\n    :=\n    exists (m : message),\n    sender(m) = Some v /\\\n    has_not_been_sent  (IM i) sv m /\\\n    has_been_received  (IM j) sj m.\n\n  (** We can now decide whether a validator is equivocating in a certain state. **)\n\n  Definition is_equivocating_statewise\n    (s : vstate X)\n    (v : validator)\n    : Prop\n    :=\n    exists (j : index),\n    j <> (A v) /\\\n    equivocating_wrt v j (s (A v)) (s j).\n\n  (** An alternative definition for detecting equivocation in a certain state,\n      which checks if for every [protocol_trace] there exists equivocation\n      involving the given validator\n\n      Notably, this definition is not generally equivalent to [is_equivocating_statewise],\n      which does not verify the order in which receiving and sending occurred.\n  **)\n\n  Definition is_equivocating_tracewise\n    (s : vstate X)\n    (v : validator)\n    (j := A v)\n    : Prop\n    :=\n    forall (tr : protocol_trace X)\n    (last : transition_item)\n    (prefix : list transition_item)\n    (Hpr : trace_prefix X (proj1_sig tr) last prefix)\n    (Hlast : destination last = s),\n    exists (m : message),\n    (sender m = Some v) /\\\n    List.Exists\n    (fun (elem : vtransition_item X) =>\n    input elem = Some m\n    /\\ ~has_been_sent (IM j) ((destination elem) j) m\n    ) prefix.\n\n  (** A possibly friendlier version using a previously defined primitive. **)\n  Definition is_equivocating_tracewise_alt\n    (s : vstate X)\n    (v : validator)\n    (j := A v)\n    : Prop\n    :=\n    forall (tr : protocol_trace X)\n    (last : transition_item)\n    (prefix : list transition_item)\n    (Hpr : trace_prefix X (proj1_sig tr) last prefix)\n    (Hlast : destination last = s),\n    exists (m : message),\n    (sender m = Some v) /\\\n    equivocation_in_trace X m (prefix ++ [last]).\n\n  Context\n      (validator_listing : list validator)\n      {finite_validator : Listing validator_listing}\n      {measurable_V : Measurable validator}\n      {threshold_V : ReachableThreshold validator}\n      .\n  (** For the equivocation sum fault to be computable, we require that\n      our is_equivocating property is decidable. The current implementation\n      refers to [is_equivocating_statewise], but this might change\n      in the future **)\n\n  Definition equivocation_dec_statewise\n     (Hdec : RelDecision is_equivocating_statewise)\n      : basic_equivocation (vstate X) (validator)\n    :=\n    {|\n      state_validators := fun _ => validator_listing;\n      state_validators_nodup := fun _ => proj1 finite_validator;\n      is_equivocating := is_equivocating_statewise;\n      is_equivocating_dec := Hdec\n    |}.\n\n  Definition equivocation_dec_tracewise\n     (Hdec : RelDecision is_equivocating_tracewise)\n      : basic_equivocation (vstate X) (validator)\n    :=\n    {|\n      state_validators := fun _ => validator_listing;\n      state_validators_nodup := fun _ => proj1 finite_validator;\n      is_equivocating := is_equivocating_tracewise;\n      is_equivocating_dec := Hdec\n    |}.\n\n  Definition equivocation_fault_constraint\n    (Dec : basic_equivocation (vstate X) validator)\n    (l : vlabel X)\n    (som : vstate X * option message)\n    : Prop\n    :=\n    let (s', om') := (vtransition X l som) in\n    not_heavy s'.\n\n    (* begin hide *)\n  Lemma sent_component_protocol_composed\n    (s : vstate X)\n    (Hs : protocol_state_prop X s)\n    (i : index)\n    (m : message)\n    (Hsent : (@has_been_sent _ _ (has_been_sent_capabilities i)\n           (s i) m)) :\n    protocol_message_prop X m.\n  Proof.\n    assert (Hcomp : has_been_sent X s m) by (exists i; intuition).\n    assert (protocol_state_prop (pre_loaded_with_all_messages_vlsm X) s) by\n      (apply pre_loaded_with_all_messages_protocol_state_prop; intuition).\n\n    apply protocol_state_has_trace in Hs as H'.\n    destruct H' as [is [tr Hpr]].\n    assert (Hpr_pre : finite_protocol_trace_init_to (pre_loaded_with_all_messages_vlsm X) is s tr). {\n      revert Hpr.\n      apply VLSM_incl_finite_protocol_trace_init_to.\n      apply vlsm_incl_pre_loaded_with_all_messages_vlsm.\n    }\n    apply protocol_trace_output_is_protocol with (is0:=is) (tr0:=tr).\n    - apply ptrace_forget_last in Hpr; apply Hpr.\n    - apply (proper_sent _ _ H) in Hcomp.\n      apply (Hcomp is tr Hpr_pre).\n  Qed.\n\n  Lemma received_component_protocol_composed\n    (s : vstate X)\n    (Hs : protocol_state_prop X s)\n    (i : index)\n    (m : message)\n    (Hreceived : (@has_been_received _ _ (has_been_received_capabilities i)\n           (s i) m)) :\n    protocol_message_prop X m.\n  Proof.\n    assert (Hcomp : has_been_received X s m) by (exists i; assumption).\n    assert (protocol_state_prop (pre_loaded_with_all_messages_vlsm X) s) by\n      (apply pre_loaded_with_all_messages_protocol_state_prop; assumption).\n    \n    apply protocol_state_has_trace in Hs as [is [tr Hpr]].\n    assert (Hpr_pre : finite_protocol_trace_init_to (pre_loaded_with_all_messages_vlsm X) is s tr). {\n      revert Hpr.\n      apply VLSM_incl_finite_protocol_trace_init_to.\n      apply vlsm_incl_pre_loaded_with_all_messages_vlsm.\n    }\n\n    specialize (@proper_received _ X _ s H m) as Hprop.\n    unfold has_been_received_prop in Hprop.\n    unfold all_traces_have_message_prop in Hprop.\n    apply Hprop in Hcomp.\n    specialize (Hcomp is tr Hpr_pre).\n    destruct Hpr as [Hpr _].\n    apply ptrace_forget_last in Hpr.\n    apply protocol_trace_input_is_protocol with (is0 := is) (tr0 := tr);assumption.\n  Qed.\n     (* end hide *)\nEnd Composite.\n\nSection cannot_resend_message.\nContext\n  {message : Type}\n  `{EqDecision message}\n  (X : VLSM message)\n  (PreX := pre_loaded_with_all_messages_vlsm X)\n  {Hbs : has_been_sent_capability X}\n  {Hbr : has_been_received_capability X}\n  .\n\nDefinition state_received_not_sent (s : state) (m : message) : Prop :=\n  has_been_received X s m /\\ ~ has_been_sent X s m.\n\nLemma state_received_not_sent_trace_iff\n  (m : message)\n  (s : state)\n  (is : state)\n  (tr : list transition_item)\n  (Htr : finite_protocol_trace_init_to PreX is s tr)\n  : state_received_not_sent s m <-> trace_received_not_sent_before_or_after tr m.\nProof.\n  assert (Hs : protocol_state_prop PreX s).\n  { apply proj1 in Htr.  apply ptrace_last_pstate in Htr.\n    assumption.\n  }\n  split; intros [Hbrm Hnbsm].\n  - apply proper_received in Hbrm; [|assumption].\n    specialize (Hbrm is tr Htr).\n    split; [assumption|].\n    intro Hbsm. elim Hnbsm.\n    apply proper_sent; [assumption|].\n    apply has_been_sent_consistency; [assumption| assumption|].\n    exists is, tr, Htr. assumption.\n  - split.\n    + apply proper_received; [assumption|].\n      apply has_been_received_consistency; [assumption| assumption|].\n      exists is, tr, Htr. assumption.\n    + intro Hbsm. elim Hnbsm.\n      apply proper_sent in Hbsm; [|assumption].\n      spec Hbsm is tr Htr. assumption.\nQed.\n\nDefinition state_received_not_sent_invariant\n  (s : state)\n  (P : message -> Prop)\n  : Prop\n  := forall m, state_received_not_sent s m -> P m.\n\nLemma state_received_not_sent_invariant_trace_iff\n  (P : message -> Prop)\n  (s : state)\n  (is : state)\n  (tr : list transition_item)\n  (Htr : finite_protocol_trace_init_to PreX is s tr)\n  : state_received_not_sent_invariant s P <->\n    trace_received_not_sent_before_or_after_invariant tr P.\nProof.\n  split; intros Hinv m Hm\n  ; apply Hinv\n  ; apply (state_received_not_sent_trace_iff m s is tr Htr)\n  ; assumption.\nQed.\n\n(**\nA sent message cannot have been previously sent or received.\n*)\nDefinition cannot_resend_message_stepwise_prop : Prop :=\n  forall l s oim s' m,\n    protocol_transition (pre_loaded_with_all_messages_vlsm X) l (s,oim) (s',Some m) ->\n    ~has_been_sent X s m /\\ ~has_been_received X s' m.\n\nLemma cannot_resend_received_message_in_future\n  (Hno_resend : cannot_resend_message_stepwise_prop)\n  (s1 s2 : state)\n  (Hfuture : in_futures PreX s1 s2)\n  : forall m : message,\n    state_received_not_sent s1 m -> state_received_not_sent s2 m.\nProof.\n  intros m Hm.\n  destruct Hfuture as [tr2 Htr2].\n  induction Htr2.\n  - assumption.\n  - apply IHHtr2;clear IHHtr2.\n    specialize (has_been_received_step_update H m) as Hrupd.\n    specialize (has_been_sent_step_update H m) as Hmupd.\n    destruct Hm as [Hr Hs].\n    eapply or_intror in Hr; apply Hrupd in Hr.\n    split.\n    + assumption.\n    + intros [->|]%Hmupd;[|apply Hs;assumption].\n      apply Hno_resend in H as [_ []].\n      assumption.\nQed.\n\n  Context\n    (Hno_resend : cannot_resend_message_stepwise_prop).\n\n  Lemma lift_preloaded_trace_to_seeded\n    (P : message -> Prop)\n    (tr: list transition_item)\n    (Htrm: trace_received_not_sent_before_or_after_invariant tr P)\n    (is: state)\n    (Htr: finite_protocol_trace PreX is tr)\n    : finite_protocol_trace (pre_loaded_vlsm X P) is tr.\n  Proof.\n    unfold trace_received_not_sent_before_or_after_invariant in Htrm.\n    split; [|apply Htr].\n    induction Htr using finite_protocol_trace_rev_ind; intros.\n    - rapply @finite_ptrace_empty.\n      apply initial_is_protocol. assumption.\n    - assert (trace_received_not_sent_before_or_after_invariant tr P) as Htrm'.\n      { intros m [Hrecv Hsend]. apply (Htrm m);clear Htrm.\n        split;[apply Exists_app;left;assumption|].\n        contradict Hsend.\n        unfold trace_has_message in Hsend.\n        rewrite Exists_app, Exists_cons, Exists_nil in Hsend.\n        simpl in Hsend.\n        cut (oom <> Some m);[tauto|clear Hsend].\n        intros ->.\n        cut (has_been_received X sf m);[apply (Hno_resend _ _ _ _ _ Hx)|].\n        apply (has_been_received_step_update Hx);right.\n        erewrite oracle_partial_trace_update.\n        - left;exact Hrecv.\n        - apply has_been_received_stepwise_from_trace.\n        - apply ptrace_add_default_last. apply Htr.\n      }\n      specialize (IHHtr Htrm').\n      apply (extend_right_finite_trace_from _ IHHtr).\n      repeat split;try apply Hx;\n      [apply finite_ptrace_last_pstate;assumption|].\n      destruct iom as [m|];[|apply option_protocol_message_None].\n      (* If m was sent during tr, it is protocol because it was\n         produced in a valid (by IHHtr) trace.\n         If m was not sent during tr, \n       *)\n      assert (Decision (trace_has_message (field_selector output) m tr)) as [Hsent|Hnot_sent].\n      apply (@Exists_dec _). intros. apply decide_eq.\n      + exact (protocol_trace_output_is_protocol _ _ _ IHHtr _ Hsent).\n      + apply initial_message_is_protocol.\n        right. apply Htrm.\n        split.\n        * apply Exists_app. right;apply Exists_cons. left;reflexivity.\n        * intro Hsent;destruct Hnot_sent.\n          unfold trace_has_message in Hsent.\n          rewrite Exists_app, Exists_cons, Exists_nil in Hsent.\n          destruct Hsent as [Hsent|[[=->]|[]]];[assumption|exfalso].\n          apply Hno_resend in Hx as Hx'.\n          apply (proj2 Hx');clear Hx'.\n          rewrite (has_been_received_step_update Hx).\n          left;reflexivity.\n  Qed.\n\n  Lemma lift_preloaded_state_to_seeded\n    (P : message -> Prop)\n    (s: state)\n    (Hequiv_s: state_received_not_sent_invariant s P)\n    (Hs: protocol_state_prop PreX s)\n    : protocol_state_prop (pre_loaded_vlsm X P) s.\n  Proof.\n    apply protocol_state_has_trace in Hs as Htr.\n    destruct Htr as [is [tr Htr]].\n    specialize (lift_preloaded_trace_to_seeded P tr) as Hlift.\n    spec Hlift.\n    { revert Hequiv_s.\n      apply state_received_not_sent_invariant_trace_iff with is; assumption.\n    }\n    specialize (Hlift _ (ptrace_forget_last Htr)).\n    apply proj1 in Hlift.\n    apply finite_ptrace_last_pstate in Hlift.\n    rewrite <- (ptrace_get_last Htr). assumption.\n  Qed.\n\n  Lemma lift_generated_to_seeded\n    (P : message -> Prop)\n    (s : state)\n    (Hequiv_s: state_received_not_sent_invariant s P)\n    (m : message)\n    (Hgen : protocol_generated_prop PreX s m)\n    : protocol_generated_prop (pre_loaded_vlsm X P) s m.\n  Proof.\n    apply non_empty_protocol_trace_from_protocol_generated_prop.\n    apply non_empty_protocol_trace_from_protocol_generated_prop in Hgen.\n    destruct Hgen as [is [tr [item [Htr Hgen]]]].\n    exists is, tr, item. split; [|assumption].\n    specialize (lift_preloaded_trace_to_seeded P tr) as Hlift.\n    spec Hlift.\n    { revert Hequiv_s.\n      apply state_received_not_sent_invariant_trace_iff with is.\n      apply ptrace_add_last. assumption.\n      apply last_error_destination_last.\n      destruct Hgen as [Hlst [Hs _]]. rewrite Hlst. subst. reflexivity.\n    }\n    apply Hlift. assumption.\n  Qed.\n\nEnd cannot_resend_message.\n\nSection full_node_constraint.\n\n  Context {message : Type}\n          `{EqDecision message}\n          {index : Type}\n          {IndEqDec : EqDecision index}\n          (IM : index -> VLSM message)\n          {i0 : Inhabited index}\n          (X := free_composite_vlsm IM)\n          (has_been_sent_capabilities : forall i : index, (has_been_sent_capability (IM i)))\n          (has_been_received_capabilities : forall i : index, (has_been_received_capability (IM i)))\n          {index_listing : list index}\n          (finite_index : Listing index_listing)\n          (X_has_been_sent_capability : has_been_sent_capability X := composite_has_been_sent_capability IM (free_constraint IM) finite_index has_been_sent_capabilities)\n          (X_has_been_received_capability : has_been_received_capability X := composite_has_been_received_capability IM (free_constraint IM) finite_index has_been_received_capabilities)\n          (X_has_been_observed_capability : has_been_observed_capability X := has_been_observed_capability_from_sent_received X)\n          (admissible_index : composite_state IM -> index -> Prop)\n          (** admissible equivocator index: this index can equivocate from given state *)\n          .\n\n  Existing Instance X_has_been_observed_capability.\n  Existing Instance X_has_been_sent_capability.\n\n  (**\n  Given a composite state @s@, a message @m@, and a node index @i@\n  if there is a machine we say that message @m@ can be\n  [node_generated_without_further_equivocation] by node @i@ if the message\n  can be produced by node @i@ pre_loaded with all messages in a trace in which\n  all message equivocation is done through messages causing\n  [no_additional_equivocations] to state @s@\n  (message [has_been_observed] in @s@ or it has the [initial_message_prop]erty).\n  *)\n  Definition node_generated_without_further_equivocation\n    (s : composite_state IM)\n    (m : message)\n    (i : index)\n    : Prop\n    := exists (si : vstate (IM i)),\n      protocol_generated_prop (pre_loaded_with_all_messages_vlsm (IM i)) si m /\\\n      state_received_not_sent_invariant (IM i) si (no_additional_equivocations X s).\n\n  (**\n  Similar to the condition above, but now the message is required to be\n  generated by the machine pre-loaded only with messages causing\n  [no_additional_equivocations] to state @s@.\n  *)\n  Definition node_generated_without_further_equivocation_alt\n    (s : composite_state IM)\n    (m : message)\n    (i : index)\n    : Prop\n    := can_emit (pre_loaded_vlsm (IM i) (no_additional_equivocations X s)) m.\n\n  (**\n  The equivocation-based abstract definition of the full node condition\n  stipulates that a message can be received in a state @s@ if either it causes\n  [no_additional_equivocations] to state @s@, or it can be\n  [node_generated_without_further_equivocation] by an admissible node.\n  *)\n  Definition full_node_condition_for_admissible_equivocators\n    (l : composite_label IM)\n    (som : composite_state IM * option message)\n    : Prop\n    :=\n    no_additional_equivocations_constraint X l som \\/\n    let (s, om) := som in\n      exists m, om = Some m /\\\n      exists (i : index), admissible_index s i /\\\n      node_generated_without_further_equivocation s m i.\n\n  (**\n  Similar to the condition above, but using the\n  [node_generated_without_further_equivocation_alt] property.\n  *)\n  Definition full_node_condition_for_admissible_equivocators_alt\n    (l : composite_label IM)\n    (som : composite_state IM * option message)\n    : Prop\n    :=\n    no_additional_equivocations_constraint X l som \\/\n    let (s, om) := som in\n      exists m, om = Some m /\\\n      exists (i : index), admissible_index s i /\\\n      node_generated_without_further_equivocation_alt s m i.\n\n  (**\n  We here show that if a machine has the [cannot_resend_message_stepwise_prop]erty,\n  then the [node_generated_without_further_equivocation] property is stronger\n  than the [node_generated_without_further_equivocation_alt] property.\n  *)\n  Lemma node_generated_without_further_equivocation_alt_iff\n    (i : index)\n    (Hno_resend : cannot_resend_message_stepwise_prop (IM i))\n    (s: composite_state IM)\n    (Hs: protocol_state_prop\n       (pre_loaded_with_all_messages_vlsm (free_composite_vlsm IM)) s)\n    (m : message)\n    (Hsmi : node_generated_without_further_equivocation s m i)\n    : node_generated_without_further_equivocation_alt s m i.\n  Proof.\n    destruct Hsmi as [si [Hsim Hsi]].\n    apply can_emit_iff. exists si.\n    revert Hsim.\n    apply lift_generated_to_seeded with (has_been_sent_capabilities i)  (has_been_received_capabilities i)\n    ; assumption.\n  Qed.\n\n  (** if all machines satisty the [cannot_resend_message_stepwise_prop]erty,\n  then the [full_node_condition_for_admissible_equivocators] is stronger than\n  the [full_node_condition_for_admissible_equivocators_alt].\n  *)\n  Lemma full_node_condition_for_admissible_equivocators_subsumption\n    (Hno_resend : forall i : index, cannot_resend_message_stepwise_prop (IM i))\n    : preloaded_constraint_subsumption IM\n        full_node_condition_for_admissible_equivocators\n        full_node_condition_for_admissible_equivocators_alt.\n  Proof.\n    intros s Hs l om [Hno_equiv | Hfull]; [left; assumption|].\n    right.\n    destruct Hfull as [m [Hom [i [Hi Hfull]]]].\n    subst om. exists m. split; [reflexivity|].\n    exists i. split; [assumption|].\n    specialize (Hno_resend i).\n    apply node_generated_without_further_equivocation_alt_iff\n    ; assumption.\n  Qed.\n\nEnd full_node_constraint.\n\nSection seeded_composite_vlsm_no_equivocation.\n\n(** ** Pre-loading a VLSM composition with no equivocations constraint\n\nWhen adding initial messages to a VLSM composition with a no equivocation\nconstraint, we cannot simply use the [pre_loaded_vlsm] construct\nbecause the no-equivocation constraint must also be altered to reflect that\nthe newly added initial messages are safe to be received at all times.\n*)\n\n  Context\n    {message : Type}\n    {index : Type}\n    {IndEqDec : EqDecision index}\n    (IM : index -> VLSM message)\n    {i0 : Inhabited index}\n    (constraint : composite_label IM -> composite_state IM  * option message -> Prop)\n    (X := free_composite_vlsm IM)\n    (has_been_sent_capabilities : forall i : index, (has_been_sent_capability (IM i)))\n    (has_been_received_capabilities : forall i : index, (has_been_received_capability (IM i)))\n    {index_listing : list index}\n    (finite_index : Listing index_listing)\n    (X_has_been_sent_capability : has_been_sent_capability X := composite_has_been_sent_capability IM (free_constraint IM) finite_index has_been_sent_capabilities)\n    .\n\n  Existing Instance X_has_been_sent_capability.\n\n  Section seeded_composite_vlsm_no_equivocation_definition.\n\n    Context\n      (seed : message -> Prop)\n      .\n\n    (** Constraint is updated to also allow seeded messages. *)\n\n    Definition no_equivocations_additional_constraint_with_pre_loaded\n      (l : composite_label IM)\n      (som : composite_state IM * option message)\n      (initial_or_seed := fun m => vinitial_message_prop X m \\/ seed m)\n      :=\n      no_equivocations_except_from X initial_or_seed l som\n      /\\ constraint l som.\n\n    Definition composite_no_equivocation_vlsm_with_pre_loaded\n      : VLSM message\n      :=\n      pre_loaded_vlsm (composite_vlsm IM no_equivocations_additional_constraint_with_pre_loaded) seed.\n\n    Lemma seeded_equivocators_incl_preloaded\n      : VLSM_incl composite_no_equivocation_vlsm_with_pre_loaded (pre_loaded_with_all_messages_vlsm (free_composite_vlsm IM)).\n    Proof.\n      unfold composite_no_equivocation_vlsm_with_pre_loaded.\n      match goal with\n      |- VLSM_incl (pre_loaded_vlsm ?v _) _ =>\n        specialize (pre_loaded_with_all_messages_vlsm_is_pre_loaded_with_True v) as Hprev\n      end.\n      apply VLSM_eq_incl_iff in Hprev. apply proj2 in Hprev.\n      match type of Hprev with\n      | VLSM_incl (mk_vlsm ?m) _ => apply VLSM_incl_trans with m\n      end\n      ; [apply pre_loaded_vlsm_incl; intros; exact I|].\n      match type of Hprev with\n      | VLSM_incl _ (mk_vlsm ?m) => apply VLSM_incl_trans with m\n      end\n      ; [assumption| ].\n      unfold free_composite_vlsm.\n      simpl.\n      apply preloaded_constraint_subsumption_pre_loaded_with_all_messages_incl.\n      intro. intros. exact I.\n    Qed.\n\n  End seeded_composite_vlsm_no_equivocation_definition.\n\n  (** Adds a no-equivocations condition on top of an existing constraint. *)\n  Definition no_equivocations_additional_constraint\n    (l : composite_label IM)\n    (som : composite_state IM * option message)\n    :=\n    no_equivocations X l som\n    /\\ constraint l som.\n\n  Context\n    (SeededNoeqvFalse := composite_no_equivocation_vlsm_with_pre_loaded (fun m => False))\n    (Noeqv := composite_vlsm IM no_equivocations_additional_constraint)\n    .\n\n  Lemma false_composite_no_equivocation_vlsm_with_pre_loaded\n    : VLSM_eq SeededNoeqvFalse Noeqv.\n  Proof.\n    unfold SeededNoeqvFalse.\n    unfold composite_no_equivocation_vlsm_with_pre_loaded.\n    match goal with\n    |- VLSM_eq (pre_loaded_vlsm ?m _) _ => specialize (vlsm_is_pre_loaded_with_False m) as Heq\n    end.\n    apply VLSM_eq_sym in Heq.\n    match type of Heq with\n    | VLSM_eq _ ?v => apply VLSM_eq_trans with (machine v)\n    end\n    ; [assumption|].\n    apply VLSM_eq_incl_iff.\n    specialize (constraint_subsumption_incl IM) as Hincl.\n    split.\n    - specialize\n        (Hincl\n          (no_equivocations_additional_constraint_with_pre_loaded (fun _ : message => False))\n          no_equivocations_additional_constraint\n        ).\n      apply Hincl.\n      intros l som. unfold no_equivocations_additional_constraint_with_pre_loaded.\n      clear -l.\n      unfold no_equivocations_additional_constraint.\n      unfold no_equivocations.\n      unfold no_equivocations_except_from.\n      destruct som as (s, [m|]); [|exact id].\n      rewrite <- or_assoc.\n      intros [[H|contra] Hc]; [|contradiction].\n      split; assumption.\n    - specialize\n        (Hincl\n          no_equivocations_additional_constraint\n          (no_equivocations_additional_constraint_with_pre_loaded (fun _ : message => False))\n        ).\n      apply Hincl.\n      intros l som. unfold no_equivocations_additional_constraint_with_pre_loaded.\n      clear -l.\n      unfold no_equivocations_additional_constraint.\n      unfold no_equivocations.\n      unfold no_equivocations_except_from.\n      destruct som as (s, [m|]); [|exact id].\n      rewrite <- or_assoc.\n      intros [H Hc].\n      split; [|assumption].\n      left. assumption.\n  Qed.\n\nEnd seeded_composite_vlsm_no_equivocation.\n\nSection has_been_sent_irrelevance.\n\n(**\n  As we have several ways of obtaining the 'has_been_sent' property, we need to\n  sometime show that they are equivalent.\n*)\n\n  Context\n    {message : Type}\n    (X : VLSM message)\n    (Hbs1 : has_been_sent_capability X)\n    (Hbs2 : has_been_sent_capability X)\n    (has_been_sent1 := @has_been_sent _ X Hbs1)\n    (has_been_sent2 := @has_been_sent _ X Hbs2)\n    .\n\n  Lemma has_been_sent_irrelevance\n    (s : state)\n    (m : message)\n    (Hs : protocol_state_prop (pre_loaded_with_all_messages_vlsm X) s)\n    : has_been_sent1 s m -> has_been_sent2 s m.\n  Proof.\n    intro H.\n    apply proper_sent in H; [|assumption].\n    apply proper_sent; [assumption|].\n    assumption.\n  Qed.\n\nEnd has_been_sent_irrelevance.\n", "meta": {"author": "zunction", "repo": "casper-cbc-proofs", "sha": "92493810dd32a8301882f9eb8a0488a6ac9d0cd1", "save_path": "github-repos/coq/zunction-casper-cbc-proofs", "path": "github-repos/coq/zunction-casper-cbc-proofs/casper-cbc-proofs-92493810dd32a8301882f9eb8a0488a6ac9d0cd1/VLSM/Equivocation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.2397031497173926}}
{"text": "Require Import HoareDef MutHeader MutGImp MutG0 SimModSem.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import Relation_Definitions.\n\n(*** TODO: export these in Coqlib or Universe ***)\nRequire Import Relation_Operators.\nRequire Import RelationPairs.\nFrom ITree Require Import\n     Events.MapDefault.\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Maps\n     Data.Map.FMapAList.\n\nRequire Import HTactics.\n\nRequire Import Imp.\nRequire Import ImpNotations.\nRequire Import ImpProofs.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\n\nSection SIMMODSEM.\n\n  Context `{Σ: GRA.t}.\n\n  Let W: Type := Any.t * Any.t.\n\n  Let wf: unit -> W -> Prop :=\n    fun _ '(mrps_src0, mrps_tgt0) =>\n      (<<SRC: mrps_src0 = tt↑>>) /\\\n      (<<TGT: mrps_tgt0 = tt↑>>)\n  .\n\n  Theorem correct:\n    refines2 [MutGImp.G] [MutG0.G].\n  Proof.\n    eapply adequacy_local2. econs; ss. i.\n    econstructor 1 with (wf:=wf) (le:=top2); et; ss.\n    econs; ss. init. unfold cfunU.\n    unfold gF.\n    unfold MutGImp.gF.\n    Local Opaque vadd.\n    steps.\n    rewrite unfold_eval_imp.\n    (* eapply Any.downcast_upcast in _UNWRAPN. des. *)\n    unfold unint in *. destruct v; clarify; ss.\n    des_ifs.\n    2: exfalso; apply n; solve_NoDup.\n    3:{ exfalso; apply n0; solve_NoDup. }\n    - imp_steps. red. esplits; et.\n    - unfold ccallU.\n      imp_steps. replace (z =? 0)%Z with false.\n      2:{ symmetry. eapply Z.eqb_neq. auto. }\n      imp_steps.\n      rewrite _UNWRAPU1. steps. imp_steps. red. esplits; et.\n    Unshelve. all: ss. all: try exact 0.\n  Qed.\n\nEnd SIMMODSEM.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/mutsum/MutGImp0proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23966798115040908}}
{"text": "(****************************************************************************)\n(* Copyright 2020 The Project Oak Authors                                   *)\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\nRequire Import Coq.Lists.List.\nRequire Import Cava.Util.List.\nRequire Import AesSpec.Cipher.\n\nSection ChangeRepresentation.\n  Context (state state_alt key key_alt : Type)\n          (projkey : key_alt -> key)\n          (to_state_alt : state -> state_alt)\n          (from_state_alt : state_alt -> state)\n          (add_round_key : state -> key -> state)\n          (sub_bytes shift_rows mix_columns : state -> state)\n          (inv_sub_bytes inv_shift_rows inv_mix_columns : state -> state).\n  Context (from_state_alt_to_state_alt : forall st, from_state_alt (to_state_alt st) = st).\n\n  Lemma cipher_change_key_rep first_key last_key middle_keys\n        first_key_alt last_key_alt middle_keys_alt input :\n    projkey first_key_alt = first_key ->\n    projkey last_key_alt = last_key ->\n    map projkey middle_keys_alt = middle_keys ->\n    cipher state key add_round_key sub_bytes shift_rows mix_columns\n           first_key last_key middle_keys input\n    = cipher state key_alt (fun st k => add_round_key st (projkey k))\n             sub_bytes shift_rows mix_columns first_key_alt last_key_alt\n             middle_keys_alt input.\n  Proof.\n    intros; subst; cbv [cipher].\n    repeat (f_equal; [ ]). rewrite fold_left_map.\n    reflexivity.\n  Qed.\n\n  Lemma equivalent_inverse_cipher_change_key_rep first_key last_key middle_keys\n        first_key_alt last_key_alt middle_keys_alt input :\n    projkey first_key_alt = first_key ->\n    projkey last_key_alt = last_key ->\n    map projkey middle_keys_alt = middle_keys ->\n    equivalent_inverse_cipher\n      state key add_round_key\n      inv_sub_bytes inv_shift_rows inv_mix_columns\n      first_key last_key middle_keys input\n    = equivalent_inverse_cipher\n        state key_alt (fun st k => add_round_key st (projkey k))\n        inv_sub_bytes inv_shift_rows inv_mix_columns first_key_alt last_key_alt\n        middle_keys_alt input.\n  Proof.\n    intros; subst; cbv [equivalent_inverse_cipher].\n    repeat (f_equal; [ ]). rewrite !fold_left_map.\n    reflexivity.\n  Qed.\n\n  Lemma cipher_change_state_rep first_key last_key middle_keys\n        input :\n    cipher state key add_round_key sub_bytes shift_rows mix_columns\n           first_key last_key middle_keys input\n    = from_state_alt\n        (cipher state_alt key\n                (fun st k => to_state_alt (add_round_key (from_state_alt st) k))\n                (fun st => to_state_alt (sub_bytes (from_state_alt st)))\n                (fun st => to_state_alt (shift_rows (from_state_alt st)))\n                (fun st => to_state_alt (mix_columns (from_state_alt st)))\n                first_key last_key middle_keys (to_state_alt input)).\n  Proof.\n    intros; subst; cbv [cipher].\n    rewrite !from_state_alt_to_state_alt.\n    repeat (f_equal; [ ]).\n    factor_out_loops.\n    eapply fold_left_double_invariant\n      with (I:=fun b c => c = from_state_alt b);\n      intros; subst;\n        rewrite ?from_state_alt_to_state_alt;\n        reflexivity.\n  Qed.\n\n  Lemma equivalent_inverse_cipher_change_state_rep first_key last_key middle_keys\n        input :\n    equivalent_inverse_cipher\n      state key add_round_key inv_sub_bytes inv_shift_rows inv_mix_columns\n      first_key last_key middle_keys input\n    = from_state_alt\n        (equivalent_inverse_cipher\n           state_alt key\n           (fun st k => to_state_alt (add_round_key (from_state_alt st) k))\n           (fun st => to_state_alt (inv_sub_bytes (from_state_alt st)))\n           (fun st => to_state_alt (inv_shift_rows (from_state_alt st)))\n           (fun st => to_state_alt (inv_mix_columns (from_state_alt st)))\n           first_key last_key middle_keys (to_state_alt input)).\n  Proof.\n    intros; subst; cbv [equivalent_inverse_cipher].\n    rewrite !from_state_alt_to_state_alt.\n    repeat (f_equal; [ ]).\n    factor_out_loops.\n    eapply fold_left_double_invariant\n      with (I:=fun b c => c = from_state_alt b);\n      intros; subst;\n        rewrite ?from_state_alt_to_state_alt;\n        reflexivity.\n  Qed.\nEnd ChangeRepresentation.\n\nSection Extensionality.\n  Context (state key : Type)\n          (add_round_key add_round_key' : state -> key -> state)\n          (sub_bytes shift_rows mix_columns : state -> state)\n          (sub_bytes' shift_rows' mix_columns' : state -> state)\n          (inv_sub_bytes inv_shift_rows inv_mix_columns : state -> state)\n          (inv_sub_bytes' inv_shift_rows' inv_mix_columns' : state -> state).\n  Context (add_round_key_equiv : forall st k, add_round_key st k = add_round_key' st k)\n          (sub_bytes_equiv : forall st, sub_bytes st = sub_bytes' st)\n          (shift_rows_equiv : forall st, shift_rows st = shift_rows' st)\n          (mix_columns_equiv : forall st, mix_columns st = mix_columns' st)\n          (inv_sub_bytes_equiv : forall st, inv_sub_bytes st = inv_sub_bytes' st)\n          (inv_shift_rows_equiv : forall st, inv_shift_rows st = inv_shift_rows' st)\n          (inv_mix_columns_equiv : forall st, inv_mix_columns st = inv_mix_columns' st).\n\n  Hint Rewrite add_round_key_equiv sub_bytes_equiv shift_rows_equiv mix_columns_equiv\n       inv_sub_bytes_equiv inv_shift_rows_equiv inv_mix_columns_equiv : equiv.\n\n  Lemma cipher_subroutine_ext first_key last_key middle_keys input :\n    cipher state key add_round_key sub_bytes shift_rows mix_columns\n           first_key last_key middle_keys input\n    = cipher state key add_round_key' sub_bytes' shift_rows' mix_columns'\n             first_key last_key middle_keys input.\n  Proof.\n    cbv [cipher]. autorewrite with equiv.\n    erewrite fold_left_ext; [ reflexivity | ].\n    intros. autorewrite with equiv. reflexivity.\n  Qed.\n\n  Lemma equivalent_inverse_cipher_subroutine_ext\n        first_key last_key middle_keys input :\n    equivalent_inverse_cipher\n      state key add_round_key inv_sub_bytes inv_shift_rows inv_mix_columns\n      first_key last_key middle_keys input\n    = equivalent_inverse_cipher\n        state key add_round_key' inv_sub_bytes' inv_shift_rows' inv_mix_columns'\n        first_key last_key middle_keys input.\n  Proof.\n    cbv [equivalent_inverse_cipher]. autorewrite with equiv.\n    erewrite fold_left_ext; [ reflexivity | ].\n    intros. autorewrite with equiv. reflexivity.\n  Qed.\n\nEnd Extensionality.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/silveroak-opentitan/aes/Spec/CipherProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23966798115040905}}
{"text": "Require Import Burrow.trees.\nRequire Import Burrow.ra.\nFrom iris.prelude Require Import options.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic Require Export base_logic.\n\nRequire Import cpdt.CpdtTactics.\nRequire Import coq_tricks.Deex.\nRequire Import Burrow.tpcms.\n\nInductive Free (M: Type) `{!EqDecision M} :=\n  | Empty : Free M\n  | Have : M -> nat -> Free M\n  | Conflict : Free M\n.\nArguments Empty {_}%type_scope {EqDecision0}.\nArguments Have {_}%type_scope {EqDecision0} _ _%nat_scope.\nArguments Conflict {_}%type_scope {EqDecision0}.\n\nInstance free_op {M} `{!EqDecision M} : Op (Free M) := λ a b , match a, b with\n  | Empty, y => y\n  | Conflict, y => Conflict\n  | Have m x, Empty => Have m x\n  | Have m x, Have n y => if decide (m = n) then Have m (x + y + 1) else Conflict\n  | Have _ _, Conflict => Conflict\n  end\n.\n\nInstance free_op_comm {M} `{!EqDecision M} : Comm (=) (@free_op M EqDecision0).\nProof. unfold Comm. intros. unfold free_op. destruct x, y; trivial.\n  repeat case_decide; trivial.\n  - f_equal. + symmetry. trivial. + lia.\n  - crush.\n  - crush.\nQed.\n\nInstance free_op_assoc {M} `{!EqDecision M} : Assoc (=) (@free_op M EqDecision0).\nProof. unfold Assoc. intros. unfold free_op. destruct x, y, z; try case_decide; intuition.\n  - case_decide; trivial. case_decide.\n    + f_equal. lia.\n    + crush.\n  - case_decide; trivial. case_decide; trivial. crush.\nQed.\n\nInductive Exc (M: Type) :=\n  | Unknown : Exc M\n  | Yes : M -> Exc M\n  | Fail : Exc M\n.\nArguments Unknown {_}%type_scope.\nArguments Yes {_}%type_scope _.\nArguments Fail {_}%type_scope.\n\nInstance exc_op {M} : Op (Exc M) := λ a b , match a, b with\n  | Unknown, y => y\n  | Fail, y => Fail\n  | Yes m, Unknown => Yes m\n  | Yes _, _ => Fail\n  end\n.\n\nInstance exc_op_comm {M} `{!EqDecision M} : Comm (=) (@exc_op M).\nProof. unfold Comm. intros. unfold exc_op. destruct x, y; trivial.\nQed.\n\nInstance exc_op_assoc {M} `{!EqDecision M} : Assoc (=) (@exc_op M).\nProof. unfold Assoc. intros. unfold exc_op. destruct x, y, z; trivial.\nQed.\n\nInductive RwLock (M: Type) `{!EqDecision M} :=\n  | Rwl : (Exc (bool * Z * M)) -> Exc () -> Exc () -> nat -> Free M -> RwLock M\n.\nArguments Rwl {_}%type_scope {EqDecision0} _ _ _ _%nat_scope _.\n\nInstance rw_op {M} `{!EqDecision M} : Op (RwLock M) := λ a b , match a, b with\n  | Rwl c ep eg sp sg, Rwl c' ep' eg' sp' sg' =>\n      Rwl (c ⋅ c') (ep ⋅ ep') (eg ⋅ eg') (sp + sp') (sg ⋅ sg')\n  end\n.\n\nInstance rw_op_comm {M} `{!EqDecision M} : Comm (=) (@rw_op M EqDecision0).\nProof. unfold Comm. intros. unfold rw_op. destruct x, y.\n  f_equal.\n  - apply exc_op_comm.\n  - apply exc_op_comm.\n  - apply exc_op_comm.\n  - lia.\n  - apply free_op_comm.\nQed.\n\nInstance rw_op_assoc {M} `{!EqDecision M} : Assoc (=) (@rw_op M EqDecision0).\nProof. unfold Assoc. intros. unfold rw_op. destruct x, y, z.\n  f_equal.\n  - apply exc_op_assoc.\n  - apply exc_op_assoc.\n  - apply exc_op_assoc.\n  - lia.\n  - apply free_op_assoc.\nQed.\n\nDefinition Central {M: Type} `{!EqDecision M} (e: bool) (r: Z) (x: M) : RwLock M :=\n  Rwl (Yes (e, r, x)) Unknown Unknown 0 (Empty).\n  \nDefinition ExcPending {M: Type} `{!EqDecision M}: RwLock M :=\n  Rwl Unknown (Yes ()) Unknown 0 (Empty).\n  \nDefinition ExcGuard {M: Type} `{!EqDecision M}: RwLock M :=\n  Rwl Unknown Unknown (Yes ()) 0 (Empty).\n  \nDefinition ShPending {M: Type} `{!EqDecision M}: RwLock M :=\n  Rwl Unknown Unknown Unknown 1 (Empty).\n  \nDefinition ShGuard {M: Type} `{!EqDecision M} (m: M) : RwLock M :=\n  Rwl Unknown Unknown Unknown 0 (Have m 0).\n  \nDefinition free_count {M} `{!EqDecision M} (m: Free M) : nat :=\n  match m with\n  | Empty => 0\n  | Have _ n => n + 1\n  | Conflict => 0\n  end.\n  \nDefinition P {M} `{!EqDecision M} (rw: RwLock M) :=\n  match rw with\n  | Rwl _ Fail _ _ _ => False\n  | Rwl _ _ Fail _ _ => False\n  | Rwl _ _ _ _ Conflict => False\n  | Rwl (Yes (e, r, x)) ep eg sp sg =>\n         r = sp + (free_count sg)\n      /\\ (e = false -> ep = Unknown /\\ eg = Unknown)\n      /\\ (e = true -> (ep = Yes () \\/ eg = Yes ()) /\\ ¬(ep = Yes() /\\ eg = Yes()))\n      /\\ (eg = Yes () -> sg = Empty)\n      /\\ (match sg with Have m _ => x = m | _ => True end)\n  | _ => False\n  end.\n\nDefinition V {M} `{!EqDecision M} (rw: RwLock M) :=\n  ∃ z , P (rw ⋅ z).\n\nDefinition rw_unit (M: Type) `{!EqDecision M} : RwLock M :=\n  Rwl Unknown Unknown Unknown 0 Empty.\n\nDefinition I_defined {M} `{!EqDecision M} (rw: RwLock M) :=\n  rw = rw_unit M \\/ P rw.\n\nDefinition I {M} `{!EqDecision M} `{!TPCM M} (rw: RwLock M) :=\n  match rw with\n  | Rwl (Yes (_,_,x)) _ Unknown _ _ => x\n  | _ => unit\n  end.\n\nDefinition rw_mov {M} `{!EqDecision M} `{!TPCM M} (a b : RwLock M) :=\n  ∀ p, I_defined (a ⋅ p) -> I_defined (b ⋅ p) /\\ I (a ⋅ p) = I (b ⋅ p).\n\nLemma rw_unit_dot (M: Type) `{!EqDecision M} (a : RwLock M) :\n  rw_op a (rw_unit M) = a.\nProof.\n  unfold rw_unit. destruct a. unfold \"⋅\", rw_op. unfold \"⋅\", exc_op, free_op.\n  f_equal; trivial.\n  - destruct e; trivial.\n  - destruct e0; trivial.\n  - destruct e1; trivial.\n  - lia.\n  - destruct f; trivial.\nQed.\n\nLemma rw_init_valid {M} `{!EqDecision M} `{!TPCM M} (x: M)\n  : P (Central false 0 x).\nProof.\n  unfold P, Central, free_count. split; trivial.\n  - intuition; discriminate.\nQed.\n\nLemma rw_mov_exc_begin {M} `{!EqDecision M} `{!TPCM M} rc x\n  : rw_mov (Central false rc x) (Central true rc x ⋅ ExcPending).\nProof.\n  unfold rw_mov. intros. unfold I_defined, I in *.\n  destruct H.\n  - exfalso. unfold \"⋅\", rw_op, rw_unit, Central in H. destruct p. inversion H.\n      unfold \"⋅\", exc_op in H1. destruct e; discriminate.\n  - split.\n    + right. unfold P in *. unfold Central, ExcPending in *. destruct p.\n      unfold \"⋅\", rw_op in *. unfold \"⋅\", exc_op, free_op in *. destruct e, e0, e1, f; try contradiction; crush.\n    + unfold P in *. unfold Central, ExcPending in *. destruct p.\n      unfold \"⋅\", rw_op in *. unfold \"⋅\", exc_op, free_op in *. destruct e, e0, e1, f; try contradiction; crush.\nQed.\n\nDefinition rw_exchange_cond {M} `{!EqDecision M} `{!TPCM M}\n    (f: RwLock M) (m: M) (f': RwLock M) (m': M) :=\n  ∀ p ,\n    I_defined (f ⋅ p) -> I_defined (f' ⋅ p) /\\ mov (dot m (I (f ⋅ p))) (dot m' (I (f' ⋅ p))).\n\nLemma rw_mov_exc_acquire {M} `{!EqDecision M} `{!TPCM M} (exc: bool) (x: M)\n  : rw_exchange_cond\n    (Central exc 0 x ⋅ ExcPending)\n    (unit: M)\n    (Central exc 0 x ⋅ ExcGuard)\n    x.\nProof.\n  unfold rw_exchange_cond. intro. intro. split.\n  - unfold I_defined, \"⋅\", rw_op, Central, ExcGuard, ExcPending in *. destruct p.\n      unfold \"⋅\", exc_op, free_op in *.  right. destruct H.\n      + exfalso. unfold rw_unit in H. destruct e, e0, e1, f; inversion H.\n      + destruct e, e0, e1, f; unfold P in *; intuition; try destruct exc; try destruct u; intuition; unfold free_count in *; try lia; intuition; try discriminate.\n  - rewrite unit_dot_left. unfold I, I_defined in *. unfold \"⋅\", Central, ExcPending, ExcGuard, rw_op in *.\n      destruct p. unfold \"⋅\", free_op, exc_op in *. destruct e, e1, e0; trivial;\n        try (rewrite unit_dot);\n        try (rewrite unit_dot_left);\n        try (apply reflex);\n        unfold P in H; destruct f; try (destruct u); try (destruct exc); unfold rw_unit in *; intuition; try (inversion H0).\nQed.\n\nLemma rw_mov_exc_release {M} `{!EqDecision M} `{!TPCM M} (exc: bool) (rc: Z) (x y: M)\n  : rw_exchange_cond\n    (Central exc rc y ⋅ ExcGuard)\n    x\n    (Central false rc x)\n    (unit: M).\nProof.\n  unfold rw_exchange_cond. intro. intro. split.\n  - unfold I_defined, \"⋅\", rw_op, Central, ExcGuard, ExcPending in *. destruct p.\n      unfold \"⋅\", exc_op, free_op in *.  right. destruct H.\n      + exfalso. unfold rw_unit in H. destruct e, e0, e1, f; inversion H.\n      + destruct e, e0, e1, f; unfold P; intuition; try destruct exc; try destruct u; crush.\n  - rewrite unit_dot_left. unfold I, I_defined in *. unfold \"⋅\", Central, ExcPending, ExcGuard, rw_op in *.\n      destruct p. unfold \"⋅\", free_op, exc_op in *. destruct e, e1, e0; trivial;\n        try (rewrite unit_dot);\n        try (rewrite unit_dot_left);\n        try (apply reflex);\n        unfold P in H; destruct f; try (destruct u); try (destruct exc); unfold rw_unit in *; intuition; try (inversion H0).\nQed.\n\nLemma rw_mov_shared_begin {M} `{!EqDecision M} `{!TPCM M} (exc: bool) (rc: Z) (x: M)\n  : rw_mov\n    (Central exc rc x)\n    (Central exc (rc + 1) x ⋅ ShPending).\nProof.\n  unfold rw_mov. intros. unfold I_defined, I in *.\n  destruct H.\n  - exfalso. unfold \"⋅\", rw_op, rw_unit, Central in H. destruct p. inversion H.\n      unfold \"⋅\", exc_op in H1. destruct e; discriminate.\n  - split.\n    + right. unfold P in *. unfold Central, ShPending in *. destruct p.\n      unfold \"⋅\", rw_op in *. unfold \"⋅\", exc_op, free_op, free_count in *. destruct e, e0, e1, f; try contradiction; try destruct exc; intuition; try lia.\n    + unfold P in *. unfold Central, ShPending in *. destruct p.\n      unfold \"⋅\", rw_op in *. unfold \"⋅\", exc_op, free_op in *. destruct e, e0, e1, f; try contradiction; crush.\nQed.\n\nLemma rw_mov_shared_acquire {M} `{!EqDecision M} `{!TPCM M} (rc: Z) (x: M)\n  : rw_mov\n    (Central false rc x ⋅ ShPending)\n    (Central false rc x ⋅ ShGuard x).\nProof.\n  unfold rw_mov. intros. unfold I_defined, I in *.\n  destruct H.\n  - exfalso. unfold \"⋅\", rw_op, rw_unit, Central in H. destruct p. inversion H.\n  - split.\n    + right. unfold P in *. unfold Central, ShPending, ShGuard in *. destruct p.\n      unfold \"⋅\", rw_op in *. unfold \"⋅\", exc_op, free_op, free_count in *. destruct e, e0, e1, f; try contradiction; intuition; try lia; try discriminate.\n        case_decide; intuition; try lia; try discriminate.\n    + unfold P in *. unfold Central, ShPending, ShGuard in *. destruct p.\n      unfold \"⋅\", rw_op in *. unfold \"⋅\", exc_op, free_op in *. destruct e, e0, e1, f; try contradiction; crush.\nQed.\n\nLemma rw_mov_shared_release {M} `{!EqDecision M} `{!TPCM M} (exc: bool) (rc: Z) (x y: M)\n  : rw_mov\n    (Central exc rc x ⋅ ShGuard y)\n    (Central exc (rc - 1) x).\nProof.\n  unfold rw_mov. intros. unfold I_defined, I in *.\n  destruct H.\n  - exfalso. unfold \"⋅\", rw_op, rw_unit, Central in H. destruct p. inversion H.\n      unfold \"⋅\", exc_op in H1. destruct e; discriminate.\n  - split.\n    + right. unfold P in *. unfold Central, ShGuard in *. destruct p.\n      unfold \"⋅\", rw_op in *. unfold \"⋅\", exc_op, free_op, free_count in *. destruct e, e0, e1, f, exc; try contradiction; try case_decide; intuition; try lia; try discriminate; try subst x; trivial.\n    + unfold P in *. unfold Central, ShGuard in *. destruct p.\n      unfold \"⋅\", rw_op in *. unfold \"⋅\", exc_op, free_op in *. destruct e, e0, e1, f; try contradiction; crush.\nQed.\n\nLemma rw_mov_shared_retry {M} `{!EqDecision M} `{!TPCM M} (exc: bool) (rc: Z) (x: M)\n  : rw_mov\n    (Central exc rc x ⋅ ShPending)\n    (Central exc (rc - 1) x).\nProof.\n  unfold rw_mov. intros. unfold I_defined, I in *.\n  destruct H.\n  - exfalso. unfold \"⋅\", rw_op, rw_unit, Central in H. destruct p. inversion H.\n  - split.\n    + right. unfold P in *. unfold Central, ShPending in *. destruct p.\n      unfold \"⋅\", rw_op in *. unfold \"⋅\", exc_op, free_op, free_count in *. destruct e, e0, e1, f, exc; try contradiction; try case_decide; intuition; try lia.\n    + unfold P in *. unfold Central, ShPending in *. destruct p.\n      unfold \"⋅\", rw_op in *. unfold \"⋅\", exc_op, free_op in *. destruct e, e0, e1, f; try contradiction; crush.\nQed.\n\nDefinition rw_borrow_back_cond {M} `{!EqDecision M} `{!TPCM M} (f: RwLock M) (m: M)\n  := ∀ p ,\n    I_defined (f ⋅ p) -> ∃ z , (dot m z) = I (f ⋅ p).\n\nLemma rw_mov_shared_borrow {M} `{!EqDecision M} `{!TPCM M} (x: M)\n  : rw_borrow_back_cond (ShGuard x) x.\nProof.\n  unfold rw_borrow_back_cond. intros. exists unit. rewrite unit_dot.\n  unfold ShGuard, \"⋅\", rw_op, I, I_defined in *. destruct p. destruct H.\n  - exfalso. unfold rw_unit in H. inversion H. unfold \"⋅\" in H5. unfold free_op in H5.\n      destruct f; try discriminate. case_decide; try discriminate.\n  - unfold \"⋅\", exc_op, free_op in *. unfold P in H. destruct e, e0, e1, f; try contradiction;\n      try (case_decide); try contradiction; try (destruct p); try (destruct p);\n      try intuition; try (destruct u); try contradiction; unfold free_count in *; try lia;\n      intuition; try discriminate; destruct b; intuition; destruct u0; intuition;\n      try discriminate.\nQed.\n\nGlobal Instance free_eqdec {M} `{!EqDecision M} : EqDecision (Free M).\nProof. solve_decision. Qed.\n\nGlobal Instance exc_eqdec {M} `{!EqDecision M} : EqDecision (Exc M).\nProof. solve_decision. Qed.\n\nGlobal Instance rwlock_eqdec {M} `{!EqDecision M} : EqDecision (RwLock M).\nProof. solve_decision. Qed.\n\nLemma rw_valid_monotonic {M} `{!EqDecision M} `{!TPCM M}\n  (f: RwLock M) (g: RwLock M) : V (f ⋅ g) -> V f.\nProof.\n  unfold V. intro. deex. exists (g ⋅ z). unfold \"⋅\" in *. rewrite rw_op_assoc. trivial. Qed.\n  \nLemma rw_unit_valid {M} `{!EqDecision M} `{!TPCM M}\n  : V (rw_unit M).\nProof.\n  unfold V. exists (Central false 0 (unit: M)).\n    unfold \"⋅\".\n    rewrite rw_op_comm.\n    rewrite rw_unit_dot. unfold P, rw_unit, Central. unfold free_count. crush.\nQed.\n  \nLemma rw_mov_reflex {M} `{!EqDecision M} `{!TPCM M}\n  (f: RwLock M) : rw_mov f f.\nProof.\n  unfold rw_mov. intros. split; trivial. Qed.\n  \nLemma rw_mov_trans {M} `{!EqDecision M} `{!TPCM M}\n  (f g h: RwLock M) : rw_mov f g -> rw_mov g h -> rw_mov f h.\nProof. unfold rw_mov. intuition.\n  - have q := H p. have q0 := H0 p. intuition.\n  - have q := H p. have q0 := H0 p. intuition.\n    rewrite H4. trivial.\nQed.\n\nLemma left_is_unit {M} `{!EqDecision M} (a b: RwLock M)\n  : rw_op a b = rw_unit M -> a = rw_unit M.\nProof.\n  intros. unfold rw_op, rw_unit in *. destruct a, b. inversion H. f_equal.\n  - unfold \"⋅\" in *. unfold exc_op in H1. destruct e; unfold exc_op in *; intuition.\n      destruct e2; intuition; try discriminate.\n  - unfold \"⋅\" in *. unfold exc_op in H2. destruct e; unfold exc_op in *; intuition;\n      destruct e2; intuition; try discriminate; destruct e1; intuition; destruct e0; intuition;\n      try discriminate; try subst e4; try subst e3; trivial; try destruct e3; trivial;\n      try discriminate; try destruct e4; try discriminate.\n  - unfold \"⋅\" in *. unfold exc_op in H3. destruct e1, e4; intuition; try discriminate.\n  - lia.\n  - unfold \"⋅\" in *. unfold free_op in *. destruct f; try (symmetry; trivial); destruct f0;\n      trivial; try case_decide; try discriminate.\nQed.\n  \nLemma rw_mov_monotonic {M} `{!EqDecision M} `{!TPCM M} : forall x y z ,\n      rw_mov x y -> V (rw_op x z) -> V (rw_op y z) /\\ rw_mov (rw_op x z) (rw_op y z).\nProof.\n  intros. assert (V (rw_op y z)) as Vrw.\n  - have h : Decision (rw_op y z = rw_unit M) by solve_decision. destruct h.\n    + rewrite e. apply rw_unit_valid.\n    + unfold V in *.\n      deex. unfold rw_mov in H. have h := H (rw_op z z0).\n      unfold I_defined in h. unfold \"⋅\" in *.  intuition.\n      rewrite rw_op_assoc in H2.\n      have h := H2 H0. destruct_ands. destruct H3.\n      * rewrite rw_op_assoc in H3.\n        have liu := left_is_unit _ _ H3. contradiction.\n      * exists z0. rewrite rw_op_assoc in H3. trivial.\n  - split; trivial. unfold rw_mov. intros. unfold rw_mov in H.\n    unfold \"⋅\" in *. rewrite <- rw_op_assoc. rewrite <- rw_op_assoc.\n      apply H.\n      rewrite <- rw_op_assoc in H1. trivial.\nQed.\n\nGlobal Instance rwlock_tpcm {M} `{!EqDecision M} `{!TPCM M} : TPCM (RwLock M) := {\n  m_valid := V ;\n  dot := rw_op ;\n  mov := rw_mov ;\n  unit := rw_unit M ;\n  valid_monotonic := rw_valid_monotonic ;\n  unit_valid := rw_unit_valid ;\n  unit_dot := rw_unit_dot M ;\n  tpcm_comm := rw_op_comm ;\n  tpcm_assoc := rw_op_assoc ;\n  reflex := rw_mov_reflex ;\n  trans := rw_mov_trans ;\n  mov_monotonic := rw_mov_monotonic ;\n}.\n\nLemma rwlock_I_valid_left\n    {M} `{!EqDecision M} `{!TPCM M}\n  : ∀ r : RwLock M, I_defined r → m_valid r.\nProof. intro.\n  unfold m_valid, rwlock_tpcm.\n  unfold I_defined. intro. destruct H.\n  - rewrite H. apply rw_unit_valid.\n  - unfold V. exists (rw_unit M). unfold \"⋅\". rewrite rw_unit_dot. trivial.\nQed.\n\nLemma rwlock_I_defined_unit\n    {M} `{!EqDecision M} `{!TPCM M}\n   : I_defined (unit: RwLock M).\nProof.\n  unfold I_defined. left. trivial.\nQed.\n   \nLemma rwlock_I_unit\n    {M} `{!EqDecision M} `{!TPCM M}\n  : I unit = unit.\nProof.\n  trivial.\nQed.\n\nLemma rwlock_I_mov_refines\n    {M} `{!EqDecision M} `{!TPCM M}\n  : ∀ b b' : RwLock M, mov b b' → I_defined b → I_defined b' ∧ mov (I b) (I b').\nProof.\n  intros.\n  unfold mov, rwlock_tpcm, rw_mov in H.\n  have h := H (rw_unit M). unfold \"⋅\" in h.\n  repeat (rewrite rw_unit_dot in h). intuition. rewrite H3. apply reflex.\nQed.\n\nDefinition rwlock_ref\n    M `{!EqDecision M} `{!TPCM M}\n    : Refinement (RwLock M) M :=\n({|\n  rel_defined := I_defined ;\n  rel := I ;\n  rel_valid_left := rwlock_I_valid_left ;\n  rel_defined_unit := rwlock_I_defined_unit ;\n  rel_unit := rwlock_I_unit ;\n  mov_refines := rwlock_I_mov_refines ;\n|}).\n\nSection RwlockLogic.\n\nContext {𝜇: BurrowCtx}.\nContext `{hG : @gen_burrowGS 𝜇 Σ}.\n\nContext {M} `{!EqDecision M} `{!TPCM M}.\nContext `{m_hastpcm: !HasTPCM 𝜇 M}.\nContext `{rw_hastpcm: !HasTPCM 𝜇 (RwLock M)}.\nContext `{!HasRef 𝜇 rw_hastpcm m_hastpcm (rwlock_ref M)}.\n\nDefinition rwloc 𝛼 𝛾 := extend_loc 𝛼 (rwlock_ref M) 𝛾.\n\nLemma rw_new 𝛾 (x: M)\n  : L 𝛾 x ==∗ ∃ 𝛼 , L (rwloc 𝛼 𝛾) (Central false 0 x).\nProof. \n  apply InitializeExt.\n  - unfold rel_defined, rwlock_ref.\n    unfold I_defined. right. apply rw_init_valid.\n  - trivial.\nQed.\n\nLemma rw_exc_begin 𝛾 rc (x: M)\n  : L 𝛾 (Central false rc x) ==∗ L 𝛾 (Central true rc x) ∗ L 𝛾 ExcPending.\nProof.\n  rewrite <- L_op.\n  apply FrameUpdate.\n  apply rw_mov_exc_begin.\nQed.\n\nLemma rw_exc_acquire 𝛼 𝛾 exc (x: M)\n   : L (rwloc 𝛼 𝛾) (Central exc 0 x)\n  -∗ L (rwloc 𝛼 𝛾) ExcPending\n ==∗ L (rwloc 𝛼 𝛾) (Central exc 0 x)\n   ∗ L (rwloc 𝛼 𝛾) ExcGuard\n   ∗ L 𝛾 x.\nProof.\n  iIntros \"A B\".\n  iDestruct (L_join with \"A B\") as \"T\".\n  iMod (L_unit M 𝛾) as \"U\".\n  iMod (FrameExchange _ _ _ _ x _ (dot (Central exc 0 x) ExcGuard) with \"T U\") as \"T\".\n  - apply rw_mov_exc_acquire.\n  - rewrite L_op.\n    iModIntro.\n    iDestruct \"T\" as \"[[S R] U]\".\n    iFrame.\nQed.\n  \nLemma rw_exc_release 𝛼 𝛾 exc rc (x y: M)\n   : L (rwloc 𝛼 𝛾) (Central exc rc y)\n  -∗ L (rwloc 𝛼 𝛾) ExcGuard\n  -∗ L 𝛾 x\n ==∗ L (rwloc 𝛼 𝛾) (Central false rc x).\nProof.\n  iIntros \"a b c\".\n  iDestruct (L_join with \"a b\") as \"a\".\n  iMod (FrameExchange _ _ _ _ (unit: M) _ (Central false rc x) with \"a c\") as \"[a b]\".\n  - apply rw_mov_exc_release.\n  - iModIntro. iFrame.\nQed.\n\nLemma rw_shared_begin 𝛾 exc rc (x: M)\n  : L 𝛾 (Central exc rc x) ==∗ L 𝛾 (Central exc (rc+1) x) ∗ L 𝛾 ShPending.\nProof.\n  rewrite <- L_op.\n  apply FrameUpdate.\n  apply rw_mov_shared_begin.\nQed.\n  \nLemma rw_shared_acquire 𝛾 rc (x: M)\n  : L 𝛾 (Central false rc x) -∗ L 𝛾 ShPending ==∗ L 𝛾 (Central false rc x) ∗ L 𝛾 (ShGuard x).\nProof.\n  iIntros \"A B\".\n  iDestruct (L_join with \"A B\") as \"A\".\n  iMod (FrameUpdate _ _ (dot (Central false rc x) (ShGuard x)) with \"A\") as \"A\".\n  - apply rw_mov_shared_acquire.\n  - rewrite L_op. iModIntro. iFrame.\nQed.\n  \nLemma rw_shared_release 𝛾 exc rc (x y: M)\n  : L 𝛾 (Central exc rc x) -∗ L 𝛾 (ShGuard y) ==∗ L 𝛾 (Central exc (rc-1) x).\nProof.\n  iIntros \"A B\".\n  iDestruct (L_join with \"A B\") as \"A\".\n  iMod (FrameUpdate _ _ ((Central exc (rc-1) x)) with \"A\") as \"A\".\n  - apply rw_mov_shared_release.\n  - iModIntro. iFrame.\nQed.\n  \nLemma rw_shared_retry 𝛾 exc rc (x: M)\n  : L 𝛾 (Central exc rc x) -∗ L 𝛾 ShPending ==∗ L 𝛾 (Central exc (rc-1) x).\nProof.\n  iIntros \"A B\".\n  iDestruct (L_join with \"A B\") as \"A\".\n  iMod (FrameUpdate _ _ ((Central exc (rc-1) x)) with \"A\") as \"A\".\n  - apply rw_mov_shared_retry.\n  - iModIntro. iFrame.\nQed.\n  \nLemma rw_borrow_back 𝛼 𝛾 (x: M) 𝜅\n  : B 𝜅 (rwloc 𝛼 𝛾) (ShGuard x) ⊢ B 𝜅 𝛾 x.\nProof.\n  apply BorrowBack. apply rw_mov_shared_borrow. Qed.\n\nEnd RwlockLogic.\n", "meta": {"author": "secure-foundations", "repo": "burrow", "sha": "a7022aa81e1e19d31b6ae7b8803790c64ac2b511", "save_path": "github-repos/coq/secure-foundations-burrow", "path": "github-repos/coq/secure-foundations-burrow/burrow-a7022aa81e1e19d31b6ae7b8803790c64ac2b511/src/tpcms/rwlock.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23966798115040905}}
{"text": "From Equations Require Import Equations.\nRequire Import Equations.Prop.Subterm.\n\nRequire Import Psatz.\n\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\n\nRequire Export SystemFR.OpenTOpen.\nRequire Export SystemFR.ReducibilitySubst.\nRequire Export SystemFR.TOpenTClose.\nRequire Export SystemFR.NoTypeFVar.\nRequire Export SystemFR.Polarity.\nRequire Export SystemFR.EquivalentPairsWithRelation.\n\nOpaque makeFresh.\nOpaque PeanoNat.Nat.eq_dec.\nOpaque reducible_values.\n\nLemma polarity_open_aux:\n  forall m T pols k rep,\n    type_nodes T < m ->\n    has_polarities T pols ->\n    is_erased_term rep ->\n    has_polarities (open k T rep) pols.\nProof.\n  induction m; destruct T;\n    repeat step || constructor || step_inversion has_polarities;\n      eauto with lia;\n      eauto with b_polarity.\n  exists X; repeat\n         step || fv_open || list_utils ||\n         (progress rewrite is_erased_term_tfv in * by steps) ||\n         (rewrite <- open_topen by (steps; eauto with twf)).\n\n  apply_any; repeat step || autorewrite with bsize; try lia.\nQed.\n\nLemma polarity_open:\n  forall T pols k rep,\n    has_polarities T pols ->\n    is_erased_term rep ->\n    has_polarities (open k T rep) pols.\nProof.\n  eauto using polarity_open_aux.\nQed.\n\nLemma pair_in_list:\n  forall X Y (l: list (X*Y)) x y,\n    (x,y) ∈ l ->\n    x ∈ support l.\nProof.\n  induction l; steps; eauto.\nQed.\n\nLemma support_invert_polarities:\n  forall pols, support (invert_polarities pols) = support pols.\nProof.\n  induction pols; repeat step || f_equal.\nQed.\n\nLemma equivalent_pairs_same:\n  forall pols pols' rel X X',\n    equivalent_pairs_with_relation rel pols pols' eq ->\n    lookup PeanoNat.Nat.eq_dec rel X = Some X' ->\n    lookup PeanoNat.Nat.eq_dec (swap rel) X' = Some X ->\n    ((X, Negative) ∈ pols -> False) ->\n    (X', Negative) ∈ pols' ->\n    False.\nProof.\n  induction pols; destruct pols'; repeat step; eauto.\nQed.\n\nDefinition hp_rename_prop T :=\n  forall pols T' pols' rel,\n    has_polarities T pols ->\n    equivalent_pairs_with_relation rel pols pols' eq ->\n    equal_with_relation type_var rel T T' ->\n    has_polarities T' pols'.\n\nDefinition hp_rename_prop_aux n T := type_nodes T = n -> hp_rename_prop T.\n\nDefinition hp_rename_until n :=\n  forall n', n' < n -> forall T, hp_rename_prop_aux n' T.\n\n#[export]\nHint Unfold hp_rename_prop: u_hprename.\n#[export]\nHint Unfold hp_rename_prop_aux: u_hprename.\n#[export]\nHint Unfold hp_rename_until: u_hprename.\n\nLemma has_polarities_rename_fvar:\n  forall n x f, hp_rename_prop_aux n (fvar x f).\nProof.\n  repeat autounfold with u_hprename.\n  repeat step || step_inversion has_polarities.\n  force_invert equal_with_relation;\n    repeat step;\n    try solve [ constructor; eauto with lia; eauto using equivalent_pairs_same ].\nQed.\n\n#[export]\nHint Immediate has_polarities_rename_fvar: b_hp_rename.\n\nLemma equivalent_with_pairs_invert:\n  forall (pols pols' : map nat polarity) (rel : map nat nat),\n    equivalent_pairs_with_relation rel pols pols' eq ->\n    equivalent_pairs_with_relation rel (invert_polarities pols) (invert_polarities pols') eq.\nProof.\n  induction pols; steps.\nQed.\n\nLemma hp_rename_induct_invert:\n  forall T1 T2 n pols pols' rel,\n    hp_rename_until n ->\n    equivalent_pairs_with_relation rel pols pols' eq ->\n    has_polarities T1 (invert_polarities pols) ->\n    equal_with_relation type_var rel T1 T2 ->\n    type_nodes T1 < n ->\n    has_polarities T2 (invert_polarities pols').\nProof.\n  repeat autounfold with u_hprename; intros.\n  repeat step || eapply_any;\n    eauto using equivalent_with_pairs_invert.\nQed.\n\nLemma hp_rename_induct:\n  forall T1 T2 n pols pols' rel,\n    hp_rename_until n ->\n    equivalent_pairs_with_relation rel pols pols' eq ->\n    has_polarities T1 pols ->\n    equal_with_relation type_var rel T1 T2 ->\n    type_nodes T1 < n ->\n    has_polarities T2 pols'.\nProof.\n  repeat autounfold with u_hprename; intros.\n  repeat step; eauto.\nQed.\n\nLemma equivalent_with_pairs_cons:\n  forall T (pols pols': map nat T) (rel : map nat nat) X Y,\n    equivalent_pairs_with_relation rel pols pols' eq ->\n    (X ∈ support pols -> False) ->\n    (Y ∈ range rel -> False) ->\n    equivalent_pairs_with_relation ((X, Y) :: rel) pols pols' eq.\nProof.\n  induction pols; destruct pols'; repeat step || t_lookup.\nQed.\n\nLemma has_polarities_rename_rec:\n  forall n k T0 Ts, hp_rename_until n -> hp_rename_prop_aux n (T_rec k T0 Ts).\nProof.\n  unfold hp_rename_prop_aux, hp_rename_prop.\n  repeat\n    step || step_inversion has_polarities || step_inversion equal_with_relation || constructor;\n    eauto using hp_rename_induct_invert with lia;\n    eauto using hp_rename_induct with lia.\n\n  - exists (makeFresh (pfv Ts' type_var :: support pols' :: range rel :: nil)); steps; try finisher.\n    eapply (\n        hp_rename_induct _ _ _ _ _\n                         ((X, makeFresh (pfv Ts' type_var :: support pols' :: range rel :: nil)) :: rel)); eauto 1;\n      repeat step || apply equal_with_relation_topen || finisher || autorewrite with bsize ||\n             apply equivalent_with_pairs_cons;\n      try lia; try finisher.\nQed.\n\n#[export]\nHint Immediate has_polarities_rename_rec: b_hp_rename.\n\nLemma strong_induction_aux:\n  forall P,\n    (forall n, (forall n', n' < n -> P n') -> P n) ->\n    forall n, forall n', n' < n -> P n'.\nProof.\n  induction n; repeat step; eauto with lia.\nQed.\n\nLemma strong_induction:\n  forall P,\n    (forall n, (forall n', n' < n -> P n') -> P n) ->\n    forall n, P n.\nProof.\n  intros; eapply strong_induction_aux; steps.\nQed.\n\nLemma has_polarities_rename_aux: forall n T, hp_rename_prop_aux n T.\nProof.\n  induction n using strong_induction; destruct T; steps;\n    eauto 2 with b_hp_rename;\n    try solve [\n      unfold hp_rename_prop_aux, hp_rename_prop;\n      repeat\n        step || step_inversion has_polarities || step_inversion equal_with_relation || constructor;\n        eauto using hp_rename_induct with lia;\n        eauto using hp_rename_induct_invert with lia\n    ].\nQed.\n\nLemma has_polarities_rename: forall T, hp_rename_prop T.\nProof.\n  intros; eapply has_polarities_rename_aux; eauto.\nQed.\n\nLemma equivalent_with_pairs_refl:\n  forall T rel (l: list (nat * T)),\n    (forall x, x ∈ support l -> lookup PeanoNat.Nat.eq_dec rel x = Some x) ->\n    (forall x, x ∈ support l -> lookup PeanoNat.Nat.eq_dec (swap rel) x = Some x) ->\n    equivalent_pairs_with_relation rel l l eq.\nProof.\n  induction l; steps.\nQed.\n\nLemma has_polarities_rename_one:\n  forall T X Y pol pols k,\n    has_polarities (topen k T (fvar X type_var)) ((X, pol) :: pols) ->\n    ~(X ∈ pfv T type_var) ->\n    ~(Y ∈ pfv T type_var) ->\n    ~(X ∈ support pols) ->\n    ~(Y ∈ support pols) ->\n    has_polarities (topen k T (fvar Y type_var)) ((Y, pol) :: pols).\nProof.\n  intros.\n  eapply (has_polarities_rename _ _ _ _ ((X,Y) :: idrel (pfv T type_var ++ support pols))); eauto 1;\n    repeat step || apply equal_with_relation_topen || apply equal_with_idrel ||\n           apply equivalent_with_pairs_cons || apply equivalent_pairs_with_relation ||\n           apply equivalent_with_pairs_refl || rewrite swap_idrel in * ||\n           apply idrel_lookup || apply equal_with_relation_refl2 ||\n           rewrite range_idrel in * || list_utils.\nQed.\n\nLemma has_polarities_swap_aux:\n  forall n T pols i j,\n    type_nodes T < n ->\n    has_polarities T pols ->\n    has_polarities (swap_type_holes T i j) pols.\nProof.\n  induction n; destruct T; repeat step || constructor || apply_any || step_inversion has_polarities;\n    eauto with lia.\n\n  exists X; repeat step || rewrite pfv_swap_type_holes in *.\n  rewrite topen_swap2; steps.\n  apply IHn; repeat step || autorewrite with bsize in *; try lia.\nQed.\n\nLemma has_polarities_swap:\n  forall T pols i j,\n    has_polarities T pols ->\n    has_polarities (swap_type_holes T i j) pols.\nProof.\n  eauto using has_polarities_swap_aux.\nQed.\n\nLemma has_polarities_topen_aux:\n  forall n T pols X k,\n    type_nodes T < n ->\n    has_polarities T pols ->\n    ~(X ∈ support pols) ->\n    has_polarities (topen k T (fvar X type_var)) pols.\nProof.\n  induction n; destruct T;\n    repeat step || constructor || t_lookup ||\n           step_inversion has_polarities || apply_any ||\n           rewrite support_invert_polarities in *;\n    eauto with lia;\n    eauto using pair_in_list.\n\n  define M (makeFresh ((X :: nil) :: pfv T3 type_var :: pfv (topen (S k) T3 (fvar X type_var)) type_var :: support pols :: nil)).\n  exists M; steps; try finisher.\n\n  rewrite open_swap; steps.\n  apply_any; repeat step || autorewrite with bsize; eauto with lia; try finisher.\n\n  rewrite topen_swap; repeat step || apply has_polarities_swap.\n  apply has_polarities_rename_one with X0; steps; try finisher.\nQed.\n\nLemma has_polarities_topen:\n  forall T pols X k,\n    has_polarities T pols ->\n    ~(X ∈ support pols) ->\n    has_polarities (topen k T (fvar X type_var)) pols.\nProof.\n  eauto using has_polarities_topen_aux.\nQed.\n", "meta": {"author": "epfl-lara", "repo": "SystemFR", "sha": "a68d12d6360f395958506deea66112c46be492a0", "save_path": "github-repos/coq/epfl-lara-SystemFR", "path": "github-repos/coq/epfl-lara-SystemFR/SystemFR-a68d12d6360f395958506deea66112c46be492a0/PolarityLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23966798115040905}}
{"text": "Require Import LogicalRelations.\nRequire Import SimulationRelation.\nRequire Export SimValues.\nRequire Export AsmX.\nRequire Import FiniteFunctionalChoice.\n\n\n(** * Relations for [Asm.regset]s *)\n\nSection ASM_REL.\n  Context `{Hmem: BaseMemoryModel}.\n  Context {D1 D2} (R: simrel D1 D2).\n\n  (** ** Preliminaries *)\n\n  (** We need the following definition in order to express the\n    monotonicity of [set_regs]. XXX: set_regs is no longer a thing? *)\n\n  Definition indexed_rel C A B := C -> rel A B.\n\n  Inductive list_indexed_rel {C A B} (R: indexed_rel C A B):\n    indexed_rel (list C) (list A) (list B) :=\n    | nil_indexed_rel:\n        Monotonic nil\n          (list_indexed_rel R nil)\n    | cons_indexed_rel c cs:\n        Monotonic cons\n          (R c ++> list_indexed_rel R cs ++> list_indexed_rel R (c::cs)).\n\n  Lemma list_indexed_rel_match_val_of_type_intro p tl:\n    forall vl vl2,\n      list_rel (match_val R p) vl vl2 ->\n      Val.has_type_list vl2 tl ->\n      list_indexed_rel (match_val_of_type R p) tl vl vl2.\n  Proof.\n    induction tl; inversion 1; inversion 1; subst; constructor; auto.\n    apply match_val_of_type_intro; auto.\n  Qed.\n\n  Global Instance list_indexed_rel_match_val_of_type_elim p tl:\n    Related\n      (list_indexed_rel (match_val_of_type R p) tl)\n      (list_rel (match_val R p))\n      subrel.\n  Proof.\n    red.\n    induction 1; constructor; auto.\n    eapply match_val_erase_type; eauto.\n  Qed.\n\n  Global Instance list_indexed_rel_match_val_of_type_weaken l p:\n    Related\n      (list_indexed_rel (match_val_of_type R p) l)\n      (list_rel (match_val R p))\n      subrel.\n  Proof.\n    red.\n    induction 1; constructor; auto.\n    eapply match_val_erase_type; eauto.\n  Qed.\n\n  (** ** The [regset_match] relation *)\n\n  Definition regset_match p: rel regset regset :=\n    (- ==> match_val R p).\n\n  Global Instance regset_match_relim p rs1 rs2 r:\n    RElim (regset_match p) rs1 rs2 True (match_val R p (rs1 r) (rs2 r)).\n  Proof.\n    unfold regset_match.\n    repeat intro; solve_monotonic.\n  Qed.\n\n  Lemma wt_regset_regset_match p:\n    Monotonic (@wt_regset) (regset_match p --> impl).\n  Proof.\n    intros rs2 rs1 Hrs Hrs2 r.\n    specialize (Hrs r).\n    specialize (Hrs2 r).\n    eapply (val_has_type_match R); eauto.\n  Qed.\n\n  (** ** The [wt_regset_match] relation *)\n\n  Definition wt_regset_match p: rel regset regset :=\n    forall_pointwise_rel (fun r => match_val_of_type R p (typ_of_preg r)).\n\n  Global Instance wt_regset_match_relim p rs1 rs2 r ty:\n    RElim (wt_regset_match p) rs1 rs2\n      (typ_of_preg r = ty)\n      (match_val_of_type R p ty (rs1 r) (rs2 r)).\n  Proof.\n    unfold wt_regset_match.\n    intros Hrs Hty; subst.\n    solve_monotonic.\n  Qed.\n\n  Lemma wt_regset_match_intro p rs1 rs2:\n    wt_regset rs2 ->\n    regset_match p rs1 rs2 ->\n    wt_regset_match p rs1 rs2.\n  Proof.\n    intros Hrs2 Hrs r.\n    eapply match_val_of_type_intro; eauto.\n  Qed.\n\n  Lemma wt_regset_match_elim p rs1 rs2:\n    wt_regset_match p rs1 rs2 ->\n    wt_regset rs2 /\\ regset_match p rs1 rs2.\n  Proof.\n    intros Hrs.\n    split.\n    - intro r.\n      eapply (match_val_has_type R).\n      solve_monotonic.\n    - solve_monotonic.\n      intros r; rauto.\n  Qed.\n\n  Global Instance wt_regset_match_subrel p:\n    Related (wt_regset_match p) (regset_match p) subrel.\n  Proof.\n    intros rs1 rs2 Hrs.\n    solve_monotonic.\n    intros r; rauto.\n  Qed.\n\n  Global Instance wt_regset_match_le_subrel:\n    Monotonic (@wt_regset_match) (le ++> subrel)%rel.\n  Proof.\n    intros p p' LE rs rs' Hrs i. specialize (Hrs i). simpl in Hrs.\n    eapply match_val_of_type_acc; eauto.\n  Qed.\n  \n  Global Instance reg_eq_transport p rs1 rs2 r v1:\n    Transport (wt_regset_match p) rs1 rs2\n      (rs1 r = v1)\n      (exists v2, rs2 r = v2 /\\ match_val_of_type R p (typ_of_preg r) v1 v2)%type.\n  Proof.\n    intros Hrs H.\n    specialize (Hrs r).\n    rewrite H in Hrs; clear H.\n    eauto.\n  Qed.\n\n  (** ** Relational properties of [regset] operations *)\n\n  (** *** [Pregmap.set] *)\n\n  Global Instance regset_set_rel_wt p:\n    Monotonic\n      (@Pregmap.set val)\n      (forallr - @ r,\n         match_val_of_type R p (typ_of_preg r) ++>\n         wt_regset_match p ++>\n         wt_regset_match p).\n  Proof.\n    unfold Pregmap.set.\n    solve_monotonic.\n    intros r; solve_monotonic.\n    congruence.\n  Qed.\n\n  Local Instance regset_set_rel p:\n    Monotonic\n      (@Pregmap.set val)\n      (- ==> match_val R p ++> regset_match p ++> regset_match p).\n  Proof.\n    unfold Pregmap.set.\n    solve_monotonic.\n    intros r; solve_monotonic.\n  Qed.\n\n  Global Instance regset_set_rel_params:\n    Params (@Pregmap.set) 4.\n\n  (** *** [undef_regs] *)\n\n  Global Instance undef_regs_match_wt p:\n    Monotonic\n      (@undef_regs)\n      (- ==> wt_regset_match p ++> wt_regset_match p).\n  Proof.\n    intro l.\n    induction l; simpl; solve_monotonic.\n  Qed.\n\n  Local Instance undef_regs_match p:\n    Monotonic\n      (@undef_regs)\n      (- ==> regset_match p ++> regset_match p).\n  Proof.\n    intro l.\n    induction l; simpl; solve_monotonic.\n  Qed.\n\n  Local Instance set_pair_match p:\n    Monotonic (@set_pair)\n              ( - ==> match_val R p ++> regset_match p ++> regset_match p).\n  Proof.\n    intro pr. destruct pr; repeat rstep; simpl; repeat rstep. \n  Qed.\n\n  \n  (** *** [set_regs] *)\n\n  (** XXX set_regs is no longer a thing? *)\n\n  (*\n  Local Instance set_regs_match D1 D2 (R: simrel D1 D2) p:\n    Monotonic\n      (@set_regs)\n      (- ==> list_rel (match_val R p) ++> regset_match p ++> regset_match p).\n  Proof.\n    intro l.\n    induction l; simpl.\n    - solve_monotonic.\n    - intros v1 v2 H.\n      Local Remove Hints arrow_pointwise_rintro : typeclass_instances.\n      solve_monotonic.\n  Qed.\n  *)\nEnd ASM_REL.\n\nGlobal Instance regset_match_le_subrel_params:\n  Params (@regset_match) 3.\n\nGlobal Instance wt_regset_match_le_subrel_params:\n  Params (@wt_regset_match) 3.\n\n\n(** ** Functoriality of [regset_match] *)\n\nSection FUNCTOR.\n  Context `{Hmem: BaseMemoryModel}.\n\n  Lemma FunctionalChoice_on_preg {B}:\n    ChoiceFacts.FunctionalChoice_on preg B.\n  Proof.\n    eapply FunctionalChoice_on_finite.\n    - solve_finite ltac:(fun r => destruct r as [|[]|[]| |[]|]).\n    - exact (inhabits PC).\n    - exact preg_eq.\n  Qed.\n\n  Lemma regset_match_id {D} p:\n    regset_match (simrel_id (D:=D)) p = eq.\n  Proof.\n    apply functional_extensionality; intro rs1.\n    apply functional_extensionality; intro rs2.\n    unfold regset_match.\n    unfold simrel_id; simpl.\n    rewrite match_val_simrel_id.\n    apply prop_ext; split.\n    - intros H.\n      apply functional_extensionality; intro r.\n      auto.\n    - red; congruence.\n  Qed.\n\n  Lemma regset_match_compose {D1 D2 D3} R12 R23 p q:\n    regset_match (simrel_compose (D1:=D1) (D2:=D2) (D3:=D3) R12 R23) (p, q) =\n    rel_compose (regset_match R12 p) (regset_match R23 q).\n  Proof.\n    unfold regset_match.\n    rewrite (match_val_simrel_compose R12 R23) by typeclasses eauto.\n    rewrite arrow_pointwise_rel_compose.\n    - reflexivity.\n    - apply FunctionalChoice_on_preg.\n  Qed.\n\n  Lemma wt_regset_match_compose {D1 D2 D3} R12 R23 p q:\n    wt_regset_match (simrel_compose (D1:=D1) (D2:=D2) (D3:=D3) R12 R23) (p, q) =\n    rel_compose (wt_regset_match R12 p) (wt_regset_match R23 q).\n  Proof.\n    apply functional_extensionality; intro rs1.\n    apply functional_extensionality; intro rs3.\n    apply prop_ext; split.\n    - intros H.\n      apply wt_regset_match_elim in H.\n      destruct H as [Hrs3 Hrs].\n      rewrite regset_match_compose in Hrs.\n      destruct Hrs as (rs2 & Hrs12 & Hrs23).\n      exists rs2; split; eapply wt_regset_match_intro; eauto.\n      eapply (wt_regset_regset_match R23); eauto.\n    - intros (rs2 & Hrs12 & Hrs23).\n      apply wt_regset_match_elim in Hrs12; destruct Hrs12 as [Hrs2 Hrs12].\n      apply wt_regset_match_elim in Hrs23; destruct Hrs23 as [Hrs3 Hrs23].\n      apply wt_regset_match_intro; eauto.\n      rewrite regset_match_compose.\n      exists rs2; split; eauto.\n  Qed.\n\n  Global Instance regset_match_wfunctor:\n    SimrelFunctorW (@regset_match Hmem).\n  Proof.\n    split.\n    - intros.\n      intros wa wb Hwb.\n      red in Hwb; subst.\n      unfold regset_match.\n      rstep. eapply match_val_simrel_equiv_fw.\n    - intros.\n      eapply regset_match_id.\n    - intros.\n      eapply regset_match_compose.\n  Qed.\nEnd FUNCTOR.\n", "meta": {"author": "VeriGu", "repo": "E6998-Formal-Verification", "sha": "83c0bdd12b723f81c08886be1dedca0ca8aff0eb", "save_path": "github-repos/coq/VeriGu-E6998-Formal-Verification", "path": "github-repos/coq/VeriGu-E6998-Formal-Verification/E6998-Formal-Verification-83c0bdd12b723f81c08886be1dedca0ca8aff0eb/certikos/liblayers/compcertx/SimAsmRegset.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23960216650253519}}
{"text": "(* nn_prop library for yalla *)\n\n\n(** * Parametric negative translation from [ll] into [ill]. *)\n(** Properties relying on cut admissibility *)\n\nRequire Import List_more.\nRequire Import List_Type_more.\nRequire Import Permutation_Type.\nRequire Import genperm_Type.\n\nRequire Import subs.\nRequire Import ll_fragments.\nRequire Export nn_def.\n\nRequire Import bbb.\n\n\nSection RTranslation.\n\n(** We fix the parameter [R] of the translation. *)\n\nVariable R : iformula.\n\n(** In [llR] (where [bot] is equivalent to [R]),\n  [A] is implied by the dual of its translation. *)\nLemma back_to_llR : forall A,\n  llR (unill R) (unill (trans R A) :: A :: nil).\nProof with myeeasy ; try ((try rewrite a2a_i) ; PCperm_Type_solve).\ninduction A ; simpl ; rewrite ? bidual.\n- apply parr_r.\n  apply (ex_r _ ((covar a :: var a :: nil) ++ unill R :: nil))...\n  eapply (@cut_r (pfrag_llR (unill R)) eq_refl (dual one)).\n  + apply (ex_r _ (unill R :: one :: nil))...\n    apply (gax_r (pfrag_llR (unill R)) false).\n  + apply bot_r.\n    apply ax_r.\n- apply (ex_r _ (covar a :: var a :: nil))...\n  apply ax_r...\n- eapply parr_r.\n  apply (bot_r (pfrag_llR (unill R))).\n  apply (gax_r (pfrag_llR (unill R)) false).\n- apply (ex_r _ (bot :: one :: nil))...\n  apply bot_r.\n  apply one_r.\n- assert (Hax := @ax_exp (pfrag_llR (unill R)) (unill R)).\n  apply parr_r.\n  apply parr_r.\n  change (tens (dual (unill R)) (unill (trans R A2)) ::\n  tens (dual (unill R)) (unill (trans R A1)) :: unill R :: tens A1 A2 :: nil)\n    with (tens (dual (unill R)) (unill (trans R A2)) ::  \n    (tens (dual (unill R)) (unill (trans R A1)) :: unill R :: tens A1 A2 :: nil) ++ nil).\n  apply tens_r.\n  + apply (gax_r (pfrag_llR (unill R)) true).\n  + apply (ex_r _ (tens (dual (unill R)) (unill (trans R A1))\n             :: (unill (trans R A2) :: tens A1 A2 :: nil) ++ (unill R :: nil)))...\n    apply tens_r.\n    -- eapply ex_r ; [ | apply Permutation_Type_swap ]...\n    -- apply (ex_r _ (tens A1 A2 ::\n             (unill (trans R A2) :: nil) ++ unill (trans R A1) :: nil))...\n       apply tens_r.\n       ++ eapply ex_r ; [ apply IHA1 | ]...\n       ++ eapply ex_r ; [ apply IHA2 | ]...\n- apply (ex_r _ (parr A1 A2 ::\n                 tens (unill (trans R A2)) (unill (trans R A1)) :: nil))...\n  apply parr_r.\n  apply (ex_r _ (tens (unill (trans R A2)) (unill (trans R A1))\n                  :: (A1 :: nil) ++ (A2 :: nil)))...\n  apply tens_r...\n- apply parr_r.\n  apply top_r.\n- eapply ex_r ; [ | apply Permutation_Type_swap ].\n  eapply top_r.\n- assert (Hax := @ax_exp (pfrag_llR (unill R)) (unill R)).\n  apply parr_r.\n  apply with_r.\n  + apply (ex_r _ (tens (dual (unill R)) (unill (trans R A1)) ::\n                    (aplus A1 A2 :: nil) ++ unill R :: nil))...\n    apply tens_r.\n    * eapply ex_r ; [ | apply Permutation_Type_swap ]...\n    * eapply ex_r ; [ | apply Permutation_Type_swap ].\n      apply plus_r1.\n      eapply ex_r ; [ | apply Permutation_Type_swap ]...\n  + apply (ex_r _ (tens (dual (unill R)) (unill (trans R A2)) ::\n                    (aplus A1 A2 :: nil) ++ unill R :: nil))...\n    apply tens_r...\n    * eapply ex_r ; [ | apply Permutation_Type_swap ]...\n    * eapply ex_r ; [ | apply Permutation_Type_swap ].\n      apply plus_r2.\n      eapply ex_r ; [ | apply Permutation_Type_swap ]...\n- assert (Hax := @ax_exp (pfrag_llR (unill R)) (unill R)).\n  eapply ex_r ; [ | apply Permutation_Type_swap ].\n  apply with_r.\n  + eapply ex_r ; [ | apply Permutation_Type_swap ].\n    apply plus_r1...\n  + eapply ex_r ; [ | apply Permutation_Type_swap ].\n    apply plus_r2...\n- apply parr_r.\n  apply (ex_r _ ((oc A ::\n                  map wn (tens (dual (unill R)) (unill (trans R A)) :: nil))\n                  ++ unill R :: nil)) ; [idtac | simpl]...\n  apply (@cut_r (pfrag_llR (unill R)) eq_refl (dual one)).\n  + apply (ex_r _ (unill R :: one :: nil))...\n    apply (gax_r (pfrag_llR (unill R)) false).\n  + apply bot_r.\n    apply oc_r ; simpl.\n    apply (ex_r _ ((wn (tens (dual (unill R)) (unill (trans R A))) :: nil)\n                     ++ (A :: nil) ++ nil))...\n    apply de_r.\n    apply tens_r...\n    apply (gax_r (pfrag_llR (unill R)) true).\n- assert (Hax := @ax_exp (pfrag_llR (unill R)) (unill R)).\n  change (wn A :: nil) with (map wn (A :: nil)).\n  apply oc_r ; simpl.\n  apply parr_r.\n  apply (ex_r _ (tens (dual (unill R)) (unill (trans R A)) :: (wn A :: nil) ++ unill R :: nil))...\n  apply tens_r.\n  + eapply ex_r...\n  + apply (ex_r _ (wn A :: unill (trans R A) :: nil))...\n    apply de_r...\n    eapply ex_r ; [ | apply Permutation_Type_swap ]...\nQed.\n\n(** The previous lemma comes with the following result from the [ll_fragments] library:\n<<\nLemma ll_to_llR : forall R l, ll_ll l -> llR R l.\n>> to deduce: *)\n\n(** A sequent whose translation is provable in [ill] was provable in [llR]. *)\nLemma ill_trans_to_llR : forall l,  ill_ll (map (trans R) l) R -> llR (unill R) l.\nProof with myeeasy ; try PCperm_Type_solve.\nintros l Hill.\napply (ill_to_ll i2a) in Hill.\napply (stronger_pfrag _ (mk_pfrag true NoAxioms false false true))\n  in Hill.\n- eapply cut_admissible_axfree in Hill.\n  + apply (ll_to_llR (unill R)) in Hill.\n    assert (forall l',\n      llR (unill R) (l' ++ map dual (map unill (map (trans R) (rev l))))\n        -> llR (unill R) (l' ++ rev l)) as Hll.\n    { clear.\n      induction l using rev_ind_Type ; intros...\n      assert (Hb := back_to_llR x).\n      rewrite rev_unit in X.\n      apply (ex_r _ _ (dual (unill (trans R x))\n               :: l' ++ map dual (map unill (map (trans R) (rev l))))) in X...\n      apply (@cut_r _ (eq_refl (pcut (pfrag_llR (unill R)))) _ _ _ X) in Hb.\n      rewrite rev_unit.\n      change (x :: rev l) with ((x :: nil) ++ rev l).\n      rewrite app_assoc.\n      eapply IHl.\n      eapply ex_r... }\n    assert (llR (unill R) (dual (unill R) :: nil)) as HR\n      by (apply (gax_r (pfrag_llR (unill R)) true)).\n    apply (@cut_r _ (eq_refl (pcut (pfrag_llR (unill R)))) _ _ _ HR) in Hill.\n    rewrite app_nil_r in Hill.\n    rewrite <- (app_nil_l (rev _)) in Hill.\n    rewrite <- ? map_rev in Hill.\n    apply Hll in Hill.\n    eapply ex_r ; [ apply Hill | ].\n    symmetry.\n    apply Permutation_Type_rev.\n  + intros Hax ; inversion Hax.\n- nsplit 5 ; myeasy.\n  intros Hax ; inversion Hax.\nQed.\n\n\n(** *** Sufficient condition on [R] for embedding [llR] into [ill_ll]\n\nextension of [ll_to_ill_trans] *)\n\n(** Elementary intuitionistic formulas *)\nInductive ielem : iformula -> Type :=\n| ie_ivar : forall X, X <> atN -> ielem (ivar X)\n| ie_ione : ielem ione\n| ie_itens : forall A B, ielem A -> ielem B -> ielem (itens A B)\n| ie_izero : ielem izero\n| ie_iplus : forall A B, ielem A -> ielem B -> ielem (iplus A B)\n| ie_itop : ielem itop.\n\nLemma ie_ie : forall A, ielem A ->\n  ill_ll (A :: nil) (negR R (trans R (unill A))).\nProof with try now (apply ax_exp_ill).\ninduction A ; intros Hgfn ; inversion Hgfn ;\n  simpl ; unfold trans.\n- unfold a2i ; unfold i2a ; rewrite (i2i_not_atN _ H0).\n  apply negR_irr.\n  apply negR_ilr...\n  reflexivity.\n- apply negR_irr.\n  apply negR_ilr...\n  reflexivity.\n- apply IHA1 in H1.\n  apply IHA2 in H2.\n  apply negR_irr.\n  apply negR_ilr ; [ reflexivity | | ]...\n  rewrite <- (app_nil_l _).\n  apply tens_ilr.\n  list_simpl ; cons2app.\n  apply tens_irr ; eassumption.\n- apply negR_irr.\n  rewrite <- (app_nil_l _).\n  apply zero_ilr.\n- rewrite <- (app_nil_l _).\n  apply zero_ilr.\n- apply IHA1 in H1.\n  apply IHA2 in H2.\n  apply negR_irr.\n  apply negR_ilr ; [ reflexivity | | ]...\n  rewrite <- (app_nil_l _).\n  apply plus_ilr ; constructor ; eassumption.\nQed.\n\nLemma ie_dual : forall A, ielem A ->\n  ill_ll (trans R (dual (unill A)) :: nil) A.\nProof with try now (apply ax_exp_ill).\ninduction A ; intros Hgfn ; inversion Hgfn ;\n  simpl ; unfold trans...\n- unfold a2i ; unfold i2a ; rewrite (i2i_not_atN _ H0)...\n- apply IHA1 in H1.\n  apply IHA2 in H2.\n  rewrite <- (app_nil_l _).\n  apply tens_ilr.\n  list_simpl.\n  cons2app.\n  apply tens_irr ; eassumption.\n- apply top_irr.\n- apply IHA1 in H1.\n  apply IHA2 in H2.\n  rewrite <- (app_nil_l _).\n  apply plus_ilr ; constructor ; eassumption.\nQed.\n\nEnd RTranslation.\n\n\nLemma ie_ie_diag : forall A, ielem A ->\n  ill_ll (trans A (unill A) :: A :: nil) A.\nProof.\nintros A Hgfn.\neapply ex_ir ; [ | apply Permutation_Type_swap ].\ncons2app.\nrewrite <- (app_nil_l _).\neapply cut_ir_axfree.\n- intros a ; destruct a.\n- apply ie_ie.\n  assumption.\n- apply negR_ilr ; try apply ax_exp_ill.\n  reflexivity.\nQed.\n\nLemma ie_dual_diag : forall A, ielem A ->\n  ill_ll (trans A (dual (unill A)) :: nil) A.\nProof.\nintros A ; apply ie_dual.\nQed.\n\nProposition llR_ie_to_ill_trans : forall R l, ielem R ->\n  llR (unill R) l -> ill_ll (map (trans R) l) R.\nProof with myeeasy ; try PEperm_Type_solve.\nintros R l Hie Hll.\nassert (Hax := @ax_exp_ill ipfrag_ill R).\nrewrite <- (app_nil_l (R :: _)) in Hax.\ninduction Hll ; \n  (try now (apply Hmix0)) ;\n  (try now (rewrite map_app ; eapply Hmix2)) ;\n  (try now (apply P_axfree in H ; inversion H)) ;\n  (try now (inversion f)) ;\n  simpl.\n- eapply ex_ir.\n  + eapply lmap_ilr ; [ | apply Hax ].\n    eapply (ax_ir _ (a2i X)).\n  + PEperm_Type_solve.\n- eapply ex_ir...\n  apply Permutation_Type_map...\n- list_simpl in IHHll ; rewrite trans_wn in IHHll.\n  list_simpl ; rewrite trans_wn.\n  eapply Permutation_Type_map in p.\n  eapply ex_oc_ir...\n- rewrite <- (app_nil_l _).\n  rewrite <- (app_nil_l _).\n  apply lmap_ilr...\n  apply one_irr.\n- rewrite <- (app_nil_l (ione :: _)).\n  apply one_ilr...\n- apply negR_irr in IHHll1.\n  apply negR_irr in IHHll2.\n  apply (tens_irr _ _ _ _ _ IHHll1) in IHHll2.\n  apply (lmap_ilr _ _ _ _ _ _ _ IHHll2) in Hax.\n  apply (ex_ir _ _ _ _ Hax)...\n- rewrite <- (app_nil_l (itens _ _ :: _)).\n  apply tens_ilr.\n  eapply ex_ir...\n- rewrite <- (app_nil_l (izero :: _)).\n  apply zero_ilr.\n- apply negR_irr in IHHll.\n  apply (plus_irr1 _ _ (negR R (trans R B))) in IHHll.\n  apply (lmap_ilr _ _ _ _ _ _ _ IHHll) in Hax.\n  apply (ex_ir _ _ _ _ Hax)...\n- apply negR_irr in IHHll.\n  apply (plus_irr2 _ _ (negR R (trans R B))) in IHHll.\n  apply (lmap_ilr _ _ _ _ _ _ _ IHHll) in Hax.\n  apply (ex_ir _ _ _ _ Hax)...\n- rewrite <- (app_nil_l (iplus _ _ :: _)).\n  apply plus_ilr...\n- simpl in IHHll ; rewrite map_map in IHHll.\n  simpl in IHHll ; rewrite <- map_map in IHHll.\n  apply negR_irr in IHHll.\n  apply oc_irr in IHHll.\n  apply negR_ilr...\n  eapply ex_ir...\n  list_simpl...\n  rewrite ? map_map...\n- rewrite <- (app_nil_l (ioc _ :: _)).\n  apply de_ilr...\n  eapply ex_ir ; [ | apply Permutation_Type_middle ].\n  apply negR_ilr...\n  apply negR_irr.\n  eapply ex_ir...\n- rewrite <- (app_nil_l (ioc _ :: _)).\n  apply wk_ilr...\n- rewrite <- (app_nil_l (ioc _ :: _)).\n  change nil with (map ioc nil).\n  rewrite <- (app_nil_l (map _ _ ++ _)).\n  apply co_ilr.\n  eapply ex_ir...\n- apply negR_irr in IHHll1.\n  apply negR_irr in IHHll2.\n  apply (stronger_ipfrag _ (cutupd_ipfrag ipfrag_ill true) (cutupd_ipfrag_true _)) in IHHll1.\n  apply (stronger_ipfrag _ (cutupd_ipfrag ipfrag_ill true) (cutupd_ipfrag_true _)) in IHHll2.\n  assert (pi0 := @trans_dual R (cutupd_ipfrag ipfrag_ill true) eq_refl eq_refl A).\n  rewrite <- (app_nil_l _) in pi0.\n  eapply (cut_ir _ _ _ _ _ _ IHHll2) in pi0.\n  list_simpl in pi0.\n  eapply (cut_ir _ _ _ _ _ _ IHHll1) in pi0.\n  unfold ill_ll ;  change ipfrag_ill with (cutrm_ipfrag (cutupd_ipfrag ipfrag_ill true)).\n  apply cut_admissible_ill_axfree ; [ intros a ; destruct a | ].\n  eapply ex_ir...\n- destruct a ; subst.\n  + apply ie_dual_diag...\n  + simpl.\n    eapply ex_ir ; [ | apply Permutation_Type_swap ].\n    rewrite <- 2 (app_nil_l (negR _ _ :: _)).\n    apply lmap_ilr...\n    * apply one_irr.\n    * eapply ex_ir.\n      -- apply ie_ie_diag...\n      -- PEperm_Type_solve.\nUnshelve. all : reflexivity.\nQed.\n\n\n(** Ingredients for generating fresh variables *)\nDefinition a2n := yalla_ax.a2n.\nDefinition n2a := yalla_ax.n2a.\nDefinition n2n_a := yalla_ax.n2n_a.\n\n\n(** ** Study of the case [R = bot] *)\n\n(** Given a sequent, the following 3 statements are equivalent:\n - the translation of the sequent is provable in [ill] for any [R];\n - the sequent is provable in [llR bot];\n - the sequent is provable in [ll].\n*)\n\nTheorem ill_trans_to_llR_bot : forall l,\n  (forall R, ill_ll (map (trans R) l) R) -> llR bot l.\nProof with myeeasy ; try PCperm_Type_solve.\nintros l Hill.\nremember (fresh_of_list a2n n2a l) as z.\nspecialize Hill with (ivar (a2i z)).\napply ill_trans_to_llR in Hill...\napply (subs_llR _ bot z) in Hill ; subst.\nsimpl in Hill.\nrewrite repl_at_eq in Hill...\nrewrite (subs_fresh_list _ _ n2n_a) in Hill...\nQed.\n\nTheorem llR_bot_to_ll : forall l, llR bot l -> ll_ll l.\nProof with myeeasy.\nintros l HR.\ninduction HR ;\n  (try now (inversion f)) ;\n  try now constructor.\n- eapply ex_r...\n- eapply ex_wn_r...\n- eapply cut_ll_r...\n- destruct a.\n  + apply one_r.\n  + apply bot_r.\n    apply one_r.\nQed.\n\nTheorem ll_ll_to_ill_trans : forall R l,\n  ll_ll l -> ill_ll (map (trans R) l) R.\nProof.\nintros R l Hll.\napply (ll_to_ill_trans R) in Hll ; myeasy.\n- eapply stronger_ipfrag ; [ | apply Hll ].\n  nsplit 3 ; myeasy.\n  intros a ; destruct a.\n- intros f ; inversion f.\n- intros f ; inversion f.\nQed.\n\n\n(** ** Study of the case [R = one] *)\n\n(** Given a sequent, the following 3 statements are equivalent:\n - the translation of the sequent is provable in [ill] for parameter [ione];\n - the sequent is provable in [llR one];\n - the sequent is provable in [ll_mix02].\n*)\n\nLemma ill_trans_to_llR_one : forall l,\n  ill_ll (map (trans ione) l) ione -> llR one l.\nProof.\napply ill_trans_to_llR.\nQed.\n\nTheorem llR_one_to_ll_mix02 : forall l, llR one l -> ll_mix02 l.\nProof with myeeasy.\nintros l pi.\ninduction pi ; try now constructor.\n- eapply ex_r...\n- eapply ex_wn_r...\n- eapply cut_mix02_r...\n- destruct a ; simpl.\n  + apply bot_r.\n    apply mix0_r...\n  + change (one :: one :: nil) with ((one :: nil) ++ (one :: nil)).\n    apply mix2_r ; try apply one_r...\nQed.\n\nTheorem ll_mix02_to_ill_trans : forall l,\n  ll_mix02 l -> ill_ll (map (trans ione) l) ione.\nProof with myeeasy.\nintros l Hll.\napply (ll_to_ill_trans ione) in Hll ; myeasy.\n- eapply stronger_ipfrag ; [ | apply Hll ].\n  nsplit 3 ; myeasy.\n  intros a ; destruct a.\n- intros f.\n  apply one_irr.\n- intros f l1 l2 pi1 pi2.\n  rewrite <- (app_nil_l (map _ l2 ++ map _ l1)).\n  rewrite <- (app_nil_r (map _ l2 ++ map _ l1)).\n  eapply cut_ir_axfree.\n  + intros a ; destruct a.\n  + apply tens_irr...\n  + apply tens_ilr.\n    apply one_ilr.\n    apply one_ilr.\n    apply one_irr.\nQed.\n\n\n(** ** Study of the case [R = zero] *)\n\n(** Given a sequent, the following 2 statements are equivalent:\n - the translation of the sequent is provable in [ill] for parameter [izero];\n - the sequent is provable in [llR zero].\n*)\n\nLemma ill_trans_to_llR_zero : forall l,\n  ill_ll (map (trans izero) l) izero -> llR zero l.\nProof.\napply ill_trans_to_llR.\nQed.\n\nLemma llR_zero_to_ill_trans : forall l,\n  llR zero l -> ill_ll (map (trans izero) l) izero.\nProof with myeeasy.\nintros l pi.\neapply llR_ie_to_ill_trans...\nconstructor.\nQed.\n\n(** Moreover in these systems, the general weakening rule is admissible. *)\nLemma aff_to_ill_trans : forall l A,\n  ill_ll (map (trans izero) l) izero -> ill_ll (map (trans izero) (A :: l)) izero.\nProof with myeeasy.\nintros l A Hll.\nsimpl.\ncons2app.\nrewrite <- (app_nil_r (map _ _)).\neapply cut_ir_axfree ; try (now (intros a ; destruct a))...\napply zero_ilr.\nQed.\n\n\n(** ** Study of the case [R = wn one] *)\n\n(** Given a sequent, the following 3 statements are equivalent:\n - the translation of the sequent is provable in [ill] for any parameter [R] such that [R] is provable in [ill];\n - the sequent is provable in [llR (wn one)];\n - the sequent is provable in [ll_mix0].\n*)\n\nTheorem ill_trans_to_llR_wn_one : forall l,\n  (forall R, ill_ll nil R -> ill_ll (map (trans R) l) R) -> llR (wn one) l.\nProof with myeeasy ; try PCperm_Type_solve.\nintros l Hill.\nremember (fresh_of_list a2n n2a l) as z.\nassert (ill_ll nil (ilpam (ioc (ivar (a2i z))) (ivar (a2i z))))\n  as Hz.\n{ apply lpam_irr.\n  apply de_ilr.\n  apply ax_ir. }\nspecialize Hill with (ilpam (ioc (ivar (a2i z))) (ivar (a2i z))).\nassert (Hz2 := Hz).\napply Hill in Hz2 ; clear Hill.\napply ill_trans_to_llR in Hz2...\napply (subs_llR _ bot z) in Hz2 ; subst.\nsimpl in Hz2.\nrewrite repl_at_eq in Hz2 ; try rewrite a2a_i...\neapply (llR1_R2 _ (wn one)) in Hz2.\n- rewrite (subs_fresh_list _ _ n2n_a) in Hz2...\n- simpl.\n  rewrite <- (app_nil_l (wn _ :: _)).\n  apply tens_r.\n  + change (wn one :: nil) with (map wn (one :: nil)).\n    apply oc_r ; simpl.\n    apply bot_r.\n    apply de_r.\n    apply one_r.\n  + apply one_r.\n- simpl.\n  apply (ex_r _ (parr bot (wn one) :: oc bot :: nil))...\n  apply parr_r.\n  apply bot_r.\n  change (wn one) with (dual (oc bot)).\n  apply ax_exp.\nQed.\n\nTheorem llR_wn_one_to_ll_mix0 : forall l, llR (wn one) l -> ll_mix0 l.\nProof with myeeasy.\nintros l pi.\ninduction pi ; try now constructor.\n- eapply ex_r...\n- eapply ex_wn_r...\n- eapply cut_mix0_r...\n- destruct a ; simpl.\n  + change nil with (map wn nil).\n    apply oc_r.\n    apply bot_r.\n    apply mix0_r...\n  + apply wk_r.\n    apply one_r.\nQed.\n\nTheorem ll_mix0_to_ill_trans : forall R l,\n  ill_ll nil R -> ll_mix0 l -> ill_ll (map (trans R) l) R.\nProof with myeeasy.\nintros R l HR Hll.\napply (stronger_pfrag _ (cutupd_pfrag pfrag_mix0 true)) in Hll.\n- apply (ll_to_ill_trans R) in Hll ; myeasy.\n  + unfold ill_ll ; change ipfrag_ill with (cutrm_ipfrag (cutupd_ipfrag ipfrag_ill true)).\n    apply cut_admissible_ill_axfree ; [ intros a ; destruct a | ].\n    eapply stronger_ipfrag ; [ | apply Hll ].\n    nsplit 3...\n    intros a ; destruct a.\n  + intros f.\n    eapply stronger_ipfrag ; [ | apply HR ].\n    nsplit 3...\n    intros a ; destruct a.\n  + intros f ; inversion f.\n- nsplit 5...\n  intros a ; destruct a.\nQed.\n\n\n(** ** Study of the case [R = oc bot] *)\n\n(** Given a sequent, the following 3 statements are equivalent:\n - the translation of the sequent is provable in [ill] for any parameter [ioc R];\n - the sequent is provable in [llR (oc bot)];\n - the sequent is provable in [ll_bbb].\n*)\n\nTheorem ill_trans_to_llR_oc_bot : forall l,\n  (forall R, ill_ll (map (trans (ioc R)) l) (ioc R)) ->\n  llR (oc bot) l.\nProof with myeeasy ; try PCperm_Type_solve.\nintros l Hill.\nremember (fresh_of_list a2n n2a l) as z.\nspecialize Hill with (ivar (a2i z)).\napply ill_trans_to_llR in Hill...\napply (subs_llR _ bot z) in Hill ; subst.\nsimpl in Hill.\nrewrite repl_at_eq in Hill...\nrewrite (subs_fresh_list _ _ n2n_a) in Hill...\nQed.\n\nTheorem llR_oc_bot_to_ll_bbb : forall l, llR (oc bot) l -> ll_bbb l.\nProof.\napply bb_to_bbb.\nQed.\n\nLemma ll_mix02_to_ill_trans_gen : forall R l,\n ll_mix02 l -> ill_ll (ioc R :: map (trans (ioc R)) l) (ioc R).\nProof with myeeasy.\nintros R l Hll.\nchange (ioc R :: map (trans _) l)\n  with (map ioc (R :: nil) ++ map (trans (ioc R)) l).\napply (stronger_pfrag _ (cutupd_pfrag pfrag_mix02 true)) in Hll.\n- eapply (ll_to_ill_trans_gen (ioc R) _ _ (R :: nil)) in Hll ; myeasy.\n  + unfold ill_ll ; change ipfrag_ill with (cutrm_ipfrag (cutupd_ipfrag ipfrag_ill true)).\n    apply cut_admissible_ill_axfree ; [ intros a ; destruct a | ].\n    eapply stronger_ipfrag ; [ | apply Hll ].\n    nsplit 3...\n    intros a ; destruct a.\n  + intros ; apply ax_exp_ill.\n  + intros ; simpl.\n    rewrite <- (app_nil_l (ioc R :: _)).\n    rewrite <- (app_nil_r (map _ l1)).\n    rewrite app_comm_cons.\n    rewrite (app_assoc _ (map _ l1)).\n    eapply (cut_ir _ (itens (ioc R) (ioc R))).\n    * rewrite <- 2 (app_nil_l (ioc R :: _)).\n      rewrite <- ? app_assoc.\n      change nil with (map ioc nil) at 2.\n      apply co_ilr.\n      eapply ex_ir.\n      -- apply tens_irr ; [ apply X | apply X0 ].\n      -- PEperm_Type_solve.\n    * apply tens_ilr.\n      apply wk_ilr.\n      apply ax_exp_ill.\n- nsplit 5...\n  intros a ; destruct a.\nUnshelve. all: reflexivity.\nQed.\n\nTheorem ll_bbb_to_ill_trans : forall R l,\n  ll_bbb l -> ill_ll (map (trans (ioc R)) l) (ioc R).\nProof with myeeasy ; try PEperm_Type_solve ; try now (apply ax_exp_ill).\nintros R l Hll.\ninduction Hll ; (try now (inversion f)) ; simpl.\n- eapply ex_ir.\n  + eapply lmap_ilr ; [ | ].\n    * eapply (ax_ir _ (a2i X)).\n    * rewrite app_nil_l...\n  + PEperm_Type_solve.\n- eapply ex_ir...\n  apply Permutation_Type_map...\n- apply (ll_mix02_to_ill_trans_gen R) in l.\n  rewrite <- (app_nil_l (ioc _ :: _)) in l.\n  rewrite map_app.\n  rewrite <- (app_nil_r (map _ l1)).\n  eapply (cut_ir_axfree) ; [ intros a ; destruct a | | ]...\n  eapply ex_ir ; [ | apply Permutation_Type_app_comm ]...\n- apply negR_ilr...\n  apply one_irr.\n- rewrite <- (app_nil_l (ione :: _)).\n  apply one_ilr...\n- apply negR_ilr...\n  list_simpl.\n  eapply ex_ir ; [ | apply Permutation_Type_app_comm ].\n  apply tens_irr ; apply negR_irr ; eapply ex_ir.\n  + apply IHHll1.\n  + PEperm_Type_solve.\n  + apply IHHll2.\n  + PEperm_Type_solve.\n- rewrite <- (app_nil_l (itens _ _ :: _)).\n  apply tens_ilr.\n  eapply ex_ir...\n- rewrite <- (app_nil_l (izero :: _)).\n  apply zero_ilr.\n- apply negR_ilr...\n  apply plus_irr1 ; apply negR_irr ; eapply ex_ir...\n- apply negR_ilr...\n  apply plus_irr2 ; apply negR_irr ; eapply ex_ir...\n- rewrite <- (app_nil_r (map _ _)).\n  rewrite <- (app_nil_l (iplus _ _ :: _)).\n  apply plus_ilr ; eapply ex_ir ; [ apply IHHll1 | | apply IHHll2 | ]...\n- apply negR_ilr...\n  rewrite map_map ; simpl.\n  rewrite <- map_map.\n  simpl in IHHll ; rewrite map_map in IHHll.\n  simpl in IHHll ; rewrite <- map_map in IHHll.\n  apply oc_irr.\n  apply negR_irr.\n  eapply ex_ir...\n- rewrite <- (app_nil_l (ioc _ :: _)).\n  apply de_ilr...\n  list_simpl.\n  apply negR_ilr...\n  apply negR_irr...\n- rewrite <- (app_nil_l (ioc _ :: _)).\n  apply wk_ilr...\n- rewrite <- 2 (app_nil_l (ioc _ :: _)).\n  change nil with (map ioc nil).\n  apply co_ilr.\n  eapply ex_ir...\nQed.\n\n(** The following result is the converse of [bb_to_bbb] proved in the [bbb] library *)\n\nTheorem bbb_to_bb : forall l, ll_bbb l -> llR (oc bot) l.\nProof.\nintros l pi.\napply ill_trans_to_llR_oc_bot.\nintros R.\napply ll_bbb_to_ill_trans ; eassumption.\nQed.\n\n\n", "meta": {"author": "olaure01", "repo": "yalla", "sha": "9c6a66fa3a3d68b5a21ce7fa695402a0f2dda4d7", "save_path": "github-repos/coq/olaure01-yalla", "path": "github-repos/coq/olaure01-yalla/yalla-9c6a66fa3a3d68b5a21ce7fa695402a0f2dda4d7/yalla/nn_prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23960216046857682}}
{"text": "Require Import FcEtt.sigs.\n\nRequire Export FcEtt.tactics.\nRequire Export FcEtt.imports.\nRequire Export FcEtt.ett_inf.\nRequire Export FcEtt.ett_ott.\nRequire Export FcEtt.ett_ind.\nRequire Export FcEtt.ext_wf.\nRequire Export FcEtt.ett_par.\nRequire Export FcEtt.ett_inf_cs.\n\nRequire Import FcEtt.erase_syntax.\nRequire Import FcEtt.fc_invert.\nRequire Import FcEtt.ext_consist.\nRequire Import FcEtt.erase.\nRequire Import FcEtt.fc_head_reduction.\n\n(* Needed for annotation lemma at end. *)\nRequire Import FcEtt.fc_preservation.\nRequire Import FcEtt.ext_subst.\n\nSet Implicit Arguments.\nSet Bullet Behavior \"Strict Subproofs\".\n\n\nModule fc_consist (wf : fc_wf_sig) (weak : fc_weak_sig) (subst : fc_subst_sig)\n                  (e_invert : ext_invert_sig)(e_subst : ext_subst_sig).\n\nImport wf weak.\n\nExport subst.\n\n\nModule invert := fc_invert wf weak subst.\nExport invert.\n\n\nModule consist := ext_consist e_invert wf.\nExport consist.\n\n\nModule erase' := erase wf weak subst e_invert.\nExport erase'.\n\n\nModule head := fc_head_reduction  e_invert weak wf subst.\nExport head.\n\nModule pres := fc_preservation wf weak subst e_subst.\nImport pres.\n(* Why does this cause so many messages? *)\n\n\nLemma erased_tm_erase_mutual :\n  (forall G0 a B (H : AnnTyping G0 a B),\n     erased_tm (erase a) /\\ erased_tm (erase B)) /\\\n  (forall G0 phi (H : AnnPropWff G0 phi),\n      forall a b A, phi = (Eq a b A) ->\n                                         erased_tm (erase a) /\\ erased_tm (erase b)\n                                         /\\ erased_tm (erase A)) /\\\n  (forall G0 D g p1 p2 (H : AnnIso G0 D g p1 p2),\n     True) /\\\n  (forall  G0 D g A B (H : AnnDefEq G0 D g A B),\n      True) /\\\n  (forall G0 (H : AnnCtx G0),\n     forall x A, binds x (Tm A) G0 -> erased_tm (erase_tm A)\n  ).\nProof.\n apply ann_typing_wff_iso_defeq_mutual; intros; simpl; repeat split; eauto.\n all: try solve [inversion H; eauto].\n all: try solve [inversion H1; eauto].\n all: try solve [inversion H0; eauto].\n   (* all: try solve [ try (destruct rho); simpl; eauto]. *)\n  - (* a_Pi rho *)\n    erased_pick_fresh y. inversion H0. eauto using lc_erase.\n    move: (H y) => h0. assert (W: y `notin` L). eauto.\n    apply h0 in W. inversion W. rewrite <- open_tm_erase_tm in H1. eauto.\n  - (* a_UAbs rho *)\n    destruct rho; eauto. \n    (* rel *)\n    pick fresh x and apply erased_a_Abs. \n    replace (a_Var_f x) with (erase (a_Var_f x)); eauto.\n    rewrite open_tm_erase_tm. assert (W: x `notin` L). auto. apply H0 in W.\n    inversion W. auto. auto.\n    (*irrel*)\n    pick fresh x and apply erased_a_Abs.\n    replace (a_Var_f x) with (erase (a_Var_f x)); eauto.\n    rewrite open_tm_erase_tm. assert (W: x `notin` L). auto. apply H0 in W.\n    inversion W. auto.\n    econstructor.\n    assert (W: x `notin` L). auto.\n    apply r in W. inversion W. simpl. \n    rewrite Rew.r_erase_tm.\n    rewrite Rew.r_erase_tm in H1. rewrite -open_tm_erase_tm in H1.\n    simpl in H1. auto.\n  - (* a_Pi type *)\n    erased_pick_fresh y. inversion H. eauto using lc_erase.\n    move: (H0 y) => h0. assert (W: y `notin` L). eauto.\n    apply h0 in W. inversion W. clear h0 W. \n    rewrite <- open_tm_erase_tm in H2. eauto.\n  - inversion H. inversion H0. destruct rho; simpl; eauto.\n  - rewrite <- open_tm_erase_tm.\n    set M := erase_tm B.\n    inversion H. inversion H2; subst.\n    pick fresh x.\n    unfold M in Fr.\n    rewrite (tm_subst_tm_tm_intro x); eauto.\n    eapply subst_tm_erased. inversion H0. auto.\n    eapply H7. fsetdec.\n  - (* a_CPi erase constraint *)\n    destruct phi. destruct (H _ _ _ eq_refl) as (h0 & h1 & h2). simpl.\n    eauto. erased_pick_fresh y; eauto using lc_erase.\n    assert (W: y `notin` L). auto. apply H0 in W.\n    rewrite Rew.r_erase_tm.\n    erewrite open_co_erase_tm2. inversion W. apply H1.\n  - (* a_UCAbs *)\n    pick fresh y and apply erased_a_CAbs.\n    assert (W: y `notin` L). auto. apply H0 in W.\n    rewrite Rew.r_erase_tm.\n    erewrite open_co_erase_tm2. inversion W. apply H1.\n  - (* a_CPi type *)\n    destruct phi. destruct (H _ _ _ eq_refl) as (h0 & h1 & h2). simpl.\n    eauto. erased_pick_fresh y; eauto using lc_erase.\n    assert (W: y `notin` L). auto. apply H0 in W.\n    rewrite Rew.r_erase_tm.\n    erewrite open_co_erase_tm2. inversion W. apply H2.\n  - rewrite <- open_co_erase_tm.\n    set M := erase_tm B.\n    inversion H. inversion H2; subst.\n    pick fresh x.\n    unfold M in Fr.\n    assert (W: x `notin` L). fsetdec. apply H10 in W.\n    erewrite open_co_erase_tm with (a := (g_Var_f x)).\n    erewrite open_co_erase_tm2 in W. apply W.\n  - inversion H1. subst. inversion H. auto.\n  - inversion H1. subst. inversion H0. auto.\n  - inversion H1. subst. inversion H. auto.\n  - simpl in H1.\n    apply binds_cons_iff in H1.\n    inversion H1. inversion H2.\n    + inversion H4; subst; auto.\n      inversion H0; auto.\n    + apply H in H2; auto.\n  - simpl in H1.\n    apply binds_cons_iff in H1.\n    inversion H1. destruct phi.\n    inversion H2. inversion H4. \n    apply H in H2; auto.\nQed.\n\nLemma erased_tm_erase : forall G0 a B, AnnTyping G0 a B -> erased_tm (erase a).\nProof.\n  intros.\n  destruct erased_tm_erase_mutual.\n  apply H0 in H. inversion H. auto.\nQed.\n\nLemma erased_tm_erase_type : forall G0 a B, AnnTyping G0 a B -> erased_tm (erase B).\nProof.\n  intros.\n  destruct erased_tm_erase_mutual.\n  apply H0 in H. inversion H. auto.\nQed.\n\nHint Resolve erased_tm_erase : erased.\n\n\nDefinition AnnGood G D := Good (erase_context G) D.\n\nLemma AnnGoodIsGood : forall G D, AnnGood G D -> Good (erase_context G) D.\nProof. intros. auto.\nQed.\n\nLemma AnnGoodnil : AnnGood nil AtomSetImpl.empty.\n  unfold AnnGood. simpl. unfold Good. unfold erased_context.\n  split. auto.\n  intros.\n  unfold binds in H. inversion H.\nQed.\n\nLemma AnnDefEq_consistent : forall S D g A B, AnnDefEq S D g A B -> AnnGood S D -> consistent (erase A) (erase B).\nProof.\n  intros S D g A B H H0.\n  pose S' := AnnGoodIsGood H0.\n  destruct (AnnDefEq_regularity H) as (S1 & S2 & gs & TS1 & TS2 & ES).\n  assert (DefEq (erase_context S) D (erase A) (erase B) (erase S1)).\n  { apply (AnnDefEq_erase H).\n    auto.\n  }\n  assert (C : consistent (erase A) (erase B)).\n  eapply join_consistent.\n  eapply consistent_defeq. eauto. eauto.\n  inversion C; subst; auto.\nQed.\n\n\nLemma Paths_are_DataTy : forall T a,\n    Path T a -> Value a -> forall G A, AnnTyping G a A -> DataTy A a_Star.\nProof.\n  induction 1; intros.\n  - inversion H0. subst.\n    eapply (binds_to_type _ _ AnnSig_an_toplevel); eauto.\n  - inversion H1. inversion H2. subst.\n    move: (IHPath H8 _ _ H14) => h0.\n    inversion h0. subst.\n    pick fresh x.\n    rewrite (tm_subst_tm_tm_intro x); eauto with lngen.\n  - inversion H1. inversion H2. subst.\n    move: (IHPath H7 _ _ H11) => h0.\n    inversion h0. subst.\n    pick fresh x.\n    rewrite (co_subst_co_tm_intro x); eauto with lngen.\n  - inversion H1.\nQed.\n\n\n\nLemma Paths_have_value_types : forall T a,\n    Path T a -> Value a -> forall G A, AnnTyping G a A -> value_type A.\nProof. intros.\n       eapply DataTy_value_type; eauto.\n       eapply Paths_are_DataTy; eauto.\nQed.\n\nLemma values_have_value_types :\n  forall G D a A, AnnGood G D ->  AnnTyping G a A -> Value a -> value_type A.\nProof.\n  intros G D a A AN H V.\n  move: (AnnTyping_regularity H) => h0.\n  inversion H; subst; auto.\n  all: try solve [inversion V; inversion H2].\n  all: match goal with\n  | [H : AnnTyping ?G ?b ?A |- value_type ?b] =>\n    apply AnnTyping_lc in H; split_hyp; lc_inversion c;  eauto\n       end.\n  + inversion V.\n    eapply (@Paths_have_value_types T (a_App b rho a0)); eauto.\n  + inversion V.\n    eapply (@Paths_have_value_types T (a_CApp a1 g)); eauto.\n  + eapply DataTy_value_type.\n    eapply (binds_to_type _ _ AnnSig_an_toplevel); eauto.\nQed.\n\n\n(* --------- Paths infect the cannonical forms lemmas for functions --------- *)\n\nLemma canonical_forms_a_Pi :\n  forall G D a rho A B, AnnGood G D ->\n                   AnnTyping G a (a_Pi rho A B) -> Value a ->\n                   (exists a', a = a_Abs rho A a') \\/ (exists T, Path T a).\nProof.\n  intros G D a rho A B AN H V.\n  inversion V; subst; inversion H; subst; try solve [inversion H0].\n  all: try solve [left; exists a0; auto].\n  all: try solve [right; exists T; auto].\nQed.\n\nLemma canonical_forms_a_CPi :\n  forall G D a phi B, AnnGood G D ->\n                 AnnTyping G a (a_CPi phi B) -> Value a ->\n                 (exists a', a = a_CAbs phi a') \\/ (exists T, Path T a).\nProof.\n  intros G D a phi B AN H V.\n  inversion V; subst; inversion H; subst; try solve [inversion H0].\n  all: try solve [left; exists a0; auto].\n  all: try solve [right; exists T; auto].\nQed.\n\nLemma consistent_a_Pi :\n  forall G A B C g rho,\n    AnnGood G (dom G) -> value_type C ->\n    AnnDefEq G (dom G) g C (a_Pi rho A B) -> exists A' B', C = a_Pi rho A' B'.\nProof.\n  intros G A B C g rho AN VT DE.\n  move: (AnnDefEq_consistent DE AN) => K;  simpl in K.\n  inversion K.\n  destruct C; destruct rho0; try destruct rho1; simpl in H; inversion H.\n  - exists C1. exists C2. subst. auto.\n  - subst. exists C1. exists C2. auto.\n  - inversion VT.\n  - inversion VT.\n  - inversion H0.\n  - assert False.\n    apply AnnDefEq_lc in DE. split_hyp.\n    match goal with\n      [ H0 : ¬ value_type (a_Pi rho (erase_tm A) (erase_tm B)),\n        H4 : lc_tm (a_Pi rho A B) |- _ ] =>\n    apply H0; econstructor;\n      pose M := H4; clearbody M; inversion M;\n      eauto using lc_tm_erase;\n      move: (lc_erase) => [h0 _]; apply h0 in H4; auto end.\n    done.\n  - subst.\n    apply value_type_erase in VT. done.\nQed.\n\nLemma consistent_a_CPi :\n  forall G phi B C g,\n    AnnGood G (dom G) -> value_type C -> AnnDefEq G (dom G) g C (a_CPi phi B) -> exists phi' B', C = a_CPi phi' B'.\nProof.\n  intros G phi B C g AN VT DE.\n  move: (AnnDefEq_consistent DE AN) => K;  simpl in K.\n  inversion K.\n  destruct C; try destruct rho; simpl in H; inversion H;\n  try solve [inversion VT; inversion H1].\n  - subst. exists phi0. exists C.  auto.\n  - inversion H0.\n  - assert False.\n    apply AnnDefEq_lc in DE. split_hyp.\n    apply H0. econstructor.\n    pose M := H4. inversion M.\n    apply lc_erase. auto.\n    move: (lc_erase) => [h0 _]. apply h0 in H4. apply H4.\n    done.\n  - subst.\n    apply value_type_erase in VT. done.\nQed.\n\n\nDefinition irrelevant G D (a : tm) :=\n  (forall x A, binds x (Tm A) G -> x `notin` fv_tm (erase a)) /\\ AnnGood G D.\n\n\n(* Other statement?\nLemma progress : forall a A G D, AnnGood G D -> AnnTyping G a A -> CoercedValue a \\/ exists a', head_reduction G a a'.\n*)\nLemma progress : forall G a A, irrelevant G (dom G) a -> AnnTyping G a A -> CoercedValue a \\/ exists a', head_reduction G a a'.\nProof.\n  intros G a A AN H.\n  destruct AN as [IR AN].\n  assert (M : AnnTyping G a A); auto.\n  dependent induction H; destruct (AnnTyping_lc M) as [LCa LCA]; inversion LCa.\n  - left; auto.\n  - apply IR in H0. simpl in H0. fsetdec.\n  - left; eauto.\n  - destruct rho; try solve [left; eauto].\n    pick fresh x.\n    have: x `notin` L; auto => h0.\n    move: (H2 x h0) => h1.\n    inversion h1. subst. clear H2.\n    destruct (H1 x h0) as [V | [a' R]].\n    { move: (H0 x h0) => h2.\n      have ctx: (AnnCtx ([(x, Tm A)] ++ G)) by eauto with ctx_wff.\n      move: (AnnCtx_uniq ctx) => u. inversion u. subst.\n      intros x0 A0 b0.\n      apply binds_cons_uniq_1 in b0. destruct b0; split_hyp.\n      ++ subst. auto.\n      ++ move: (IR _ _ H2) => fr. simpl in fr.\n         rewrite <- open_tm_erase_tm.\n         eapply notin_sub; [idtac| eapply fv_tm_tm_tm_open_tm_wrt_tm_upper].\n         simpl.\n         fsetdec.\n      ++ eauto. }\n    { unfold AnnGood. simpl. eapply Good_add_tm_2; eauto.\n      rewrite <- erase_dom. auto.\n      eapply Typing_erased. eapply (AnnTyping_erase). eauto. }\n    { eauto. }\n    -- inversion V. subst.\n       ++ left.\n       econstructor.\n       eapply Value_AbsIrrel_exists with (x := x); eauto.\n       ++ resolve_open a.\n       left. eapply CV.\n       eapply Value_AbsIrrel_exists with (x:=x); eauto.\n    -- right. exists (a_Abs Irrel A (close_tm_wrt_tm x a')).\n       eapply An_AbsTerm_exists with (x := x).\n         { eapply notin_union; auto.\n           simpl. rewrite fv_tm_tm_tm_close_tm_wrt_tm. auto. }\n         auto.\n         rewrite open_tm_wrt_tm_close_tm_wrt_tm. auto.\n  - destruct IHAnnTyping1; auto.\n    + intros. move: (IR x A0 H6) => h0. destruct rho; simpl in h0. fsetdec. fsetdec.\n    + inversion M. subst.\n      match goal with\n        H: CoercedValue b |- _ => inversion H\n      end.\n      -- (* application of a value *)\n        edestruct canonical_forms_a_Pi as [[ a1 EQ] | [T P]] ; eauto; subst.\n        (* path case solved automatically *)\n        ++ right. (* a lambda, do a beta reduction *)\n           exists (open_tm_wrt_tm a1 a). eapply An_AppAbs; eauto.\n      -- right. (* push/pull rule *)\n         subst.\n         inversion H.\n         subst.\n         have VT: value_type A1. eapply values_have_value_types; eauto.\n         edestruct consistent_a_Pi as (A' & B' & EQ); eauto. subst.\n         edestruct canonical_forms_a_Pi as [[ a0' EQ] | [T P]]; eauto; subst.\n    + subst.\n      match goal with H : exists a' : tm, head_reduction G b a' |- _ => destruct H end.\n      right. eexists. eapply An_AppLeft; eauto.\n  - (* cast *)\n    subst. destruct IHAnnTyping1; auto.\n    inversion H2.\n    + subst. left; auto.\n    + subst. right. inversion H4.\n      eexists.  eapply An_Combine; eauto.\n    + destruct H2. right. eexists. eapply An_ConvTerm; eauto.\n  - left; auto.\n  - left; auto.\n  - destruct IHAnnTyping; auto.\n    + intros. move: (IR x A H5) => h0. simpl in h0. fsetdec.\n    + inversion M. subst.\n      match goal with\n        H : CoercedValue ?a1 |- _ => inversion H\n      end.\n      -- edestruct canonical_forms_a_CPi as [[a2 EQ]|[T p]]; eauto; subst.\n         right. exists (open_tm_wrt_co a2 g). eapply An_CAppCAbs; eauto.\n         destruct (AnnTyping_lc H) as [h0 h1]. inversion h0; auto.\n      -- subst.  inversion H. subst.\n         have VT: value_type A. eapply values_have_value_types; eauto.\n        edestruct consistent_a_CPi as (A' & a2 & EQ); eauto. subst.\n        edestruct canonical_forms_a_CPi as [[a0' EQ]|[T p]]; eauto; subst.\n    + destruct H5. right. eexists. eapply An_CAppLeft. eauto. eauto.\n  - left. eauto.\n  - right. exists a. eauto.\nQed.\n\n\n(* ------------------------------------- *)\n\n(* This is proved in the preservation file.\nLemma reduction_erasure : forall G a a',\n    head_reduction G a a' ->\n    reduction_in_one (erase a) (erase a') \\/ erase a = erase a'. *)\n\n\n(* ------------------------------------- *)\nInductive multi (rel : tm -> tm -> Prop) : tm -> tm -> Prop :=\n| multi_refl : forall a, lc_tm a -> multi rel a a\n| multi_step : forall a b c, rel a b -> multi rel b c -> multi rel a c.\n\nLemma multi_trans : forall r a b, multi r a b -> forall c, multi r b c -> multi r a c.\nProof.\n  intros.\n  dependent induction H. auto.\n  eapply multi_step. eauto. auto.\nQed.\n\n(* ------------------------------------- *)\n\nLemma multi_An_AbsTerm_exists : ∀ (G : list (atom * sort)) (x : atom) (A a a' : tm),\n       x `notin` union (fv_tm a) (union (fv_tm a') (dom G))\n       → AnnTyping G A a_Star\n         → multi (head_reduction ([(x, Tm A)] ++ G)) (open_tm_wrt_tm a (a_Var_f x))\n             (open_tm_wrt_tm a' (a_Var_f x))\n           → multi (head_reduction G) (a_Abs Irrel A a) (a_Abs Irrel A a').\nProof.\n  intros.\n  dependent induction H1.\n  + apply open_tm_wrt_tm_inj in x; auto.\n    subst.\n    eapply multi_refl; eauto using AnnTyping_lc1.\n  + eapply multi_step with (b := a_Abs Irrel A (close_tm_wrt_tm x b)); eauto.\n    eapply An_AbsTerm_exists with (x:=x); auto.\n    autorewrite with lngen. auto.\n    autorewrite with lngen. auto.\n    eapply IHmulti with (x0:=x); auto.\n    autorewrite with lngen. auto.\n    autorewrite with lngen. auto.\nQed.\n\nLemma multi_An_ConvTerm : ∀ (G : context) (a : tm) (g : co) (a' : tm),\n    lc_co g → multi (head_reduction G) a a'\n    → multi (head_reduction G) (a_Conv a g) (a_Conv a' g).\nProof.\n  intros.\n  dependent induction H0.\n  - eapply multi_refl; eauto.\n  - eapply multi_step with (b:= (a_Conv b g)); auto.\nQed.\n\nLemma multi_An_AppLeft : ∀ (G : context) (a b: tm) rho (a' : tm),\n    lc_tm b → multi (head_reduction G) a a'\n    → multi (head_reduction G) (a_App a rho b) (a_App a' rho b).\nProof.\n  intros.\n  dependent induction H0.\n  - eapply multi_refl; eauto.\n  - eapply multi_step with (b:= (a_App b0 rho b)); auto.\nQed.\n\nLemma multi_An_CAppLeft : ∀ (G : context) (a: tm) (g:co) (a' : tm),\n    lc_co g → multi (head_reduction G) a a'\n    → multi (head_reduction G) (a_CApp a g) (a_CApp a' g).\nProof.\n  intros.\n  dependent induction H0.\n  - eapply multi_refl; eauto.\n  - eapply multi_step with (b:= (a_CApp b g)); auto.\nQed.\n\n\n(* ------------------------------------- *)\n\nLemma multi_preservation : forall G a b A, multi (head_reduction G) a b ->\n                                      AnnTyping G a A ->\n                                      AnnTyping G b A.\nProof.\n  induction 1.\n  intros. auto.\n  intros.\n  eapply IHmulti.\n  eapply preservation; eauto.\nQed.\n\n\n(* ------------------------------------- *)\n\n(* TODO: move elsewhere?  ext_consist for the first two? *)\n\nLemma erased_constraint_erase :\n  forall G a b A, AnnPropWff G (Eq a b A) -> erased_tm (erase a) /\\ erased_tm (erase b)\n                                      /\\ erased_tm (erase A).\nProof.\n  move: erased_tm_erase_mutual => [_ [h [_ _]]].\n  eauto.\nQed.\n\nLemma erased_context_erase :\n  forall G, AnnCtx G -> erased_context (erase_context G).\n       Proof.\n         induction 1; simpl; unfold erased_context; rewrite Forall_forall.\n         - intros. inversion H.\n         - intros. destruct x0. inversion H2.\n           -- inversion H3. destruct s. inversion H6. subst. \n              econstructor. eapply erased_tm_erase. eauto.\n              inversion H6.\n           -- unfold erased_context in IHAnnCtx.\n              move: (Forall_forall (λ p : atom * sort, let (_, s) := p in erased_sort s) (erase_context G)) => [h0 h1].\n              move: (h0 IHAnnCtx) => h2.\n              eapply (h2 (a,s)). auto.\n         - intros. destruct x. inversion H2.\n           -- inversion H3. destruct s. inversion H6.\n              inversion H6. subst.\n              destruct phi.\n              inversion H0.\n              econstructor. \n              + eapply erased_tm_erase. eauto using AnnTyping_lc1.\n              + eapply erased_tm_erase. eauto using AnnTyping_lc2.\n              + eapply erased_tm_erase_type. eauto.\n           -- unfold erased_context in IHAnnCtx.\n              move: (Forall_forall (λ p : atom * sort, let (_, s) := p in erased_sort s) (erase_context G)) => [h0 h1].\n              move: (h0 IHAnnCtx) => h2.\n              eapply (h2 (a,s)). auto.\n       Qed.\n\nLemma AnnGood_add_tm :\n  forall G x A,  x `notin` dom G -> AnnTyping G A a_Star -> AnnGood G (dom G) -> AnnGood (x ~ Tm A ++ G) (dom (x ~ Tm A ++ G)).\nProof.\n  intros G x A Fr AT GG.\n  inversion GG.  econstructor. eapply erased_context_erase; eauto using AnnTyping_AnnCtx.\n  intros.\n  simpl in H1.\n  apply binds_cons_1 in H1.\n  destruct H1 as [[_ EQ] | BI1]. inversion EQ.\n  edestruct (H0 c1) as (C & P1 & P2); eauto.\n  move: (binds_In _ c1 _ _ BI1) => b0.\n  unfold erase_context in b0. move: (dom_map _ _ erase_sort G) => DM. fsetdec.\n  exists C. repeat split;\n         eapply context_Par_irrelevance; eauto.\nQed.\n\n(* ------------------------------------- *)\n\n(* A specialized version of eauto that only uses the most common\n   lc lemmas to cut down the search space. *)\nLtac eauto_lc := simpl; eauto using AnnTyping_lc1, Value_lc,\n                        AnnDefEq_lc3, AnnPropWff_lc.\n\n\n(* If an annotated term erases to a value, then it evaluates to a coerced value. *)\nLemma erased_Value_reduces_to_CoercedValue :\n  forall G a0 A,\n    AnnTyping G a0 A\n    -> AnnGood G (dom G) -> forall a, erase a0 = a -> Value a\n           -> exists av, multi (head_reduction G) a0 av /\\ CoercedValue av /\\ erase av = a.\nProof.\n  intros G a0 A H. induction H.\n  all: intros GG aa E V; simpl in E; inversion E; subst.\n  all: try solve [inversion V].\n  all: try solve [eexists; repeat split;\n                  try eapply multi_refl; eauto_lc].\n  + exists (a_Pi rho A B).\n    have ?: lc_tm (a_Pi rho A B) by eauto_lc.\n    repeat split; try eapply multi_refl; eauto_lc.\n\n  + have ?: lc_tm (a_Abs rho A a) by eauto_lc.\n    destruct rho.\n    ++ exists (a_Abs Rel A a).\n       repeat split; try eapply multi_refl; eauto_lc.\n    ++ (* irrelevant abstraction case *)\n      inversion V. subst.\n      match goal with\n        [H5 : forall x, x `notin` ?L -> Value _ |- _ ] =>\n        pick_fresh y; move: (H5 y ltac:(auto)) => Va; clear H5 end.\n\n      have EE: erase (open_tm_wrt_tm a (a_Var_f y)) = open_tm_wrt_tm (erase_tm a) (a_Var_f y)\n        by simpl_erase; auto.\n\n       have G1 : AnnGood (y ~ Tm A ++ G) (dom (y ~ Tm A ++ G)) by  eapply AnnGood_add_tm; eauto.\n\n       match goal with\n         [ H1 : ∀ x : atom, x `notin` ?L → AnnGood _ _ -> _ |- _ ] =>\n         move: (H1 y ltac:(auto) G1 _ EE Va) => [av [MS [VV EV]]] end.\n\n       exists (a_Abs Irrel A (close_tm_wrt_tm y av)).\n       repeat split.\n       +++ eapply multi_An_AbsTerm_exists with (x:=y);\n            autorewrite with lngen; eauto.\n       +++ econstructor.\n           eapply Value_AbsIrrel_exists with (x:=y); autorewrite with lngen; eauto_lc.\n       +++ simpl_erase. rewrite EV.\n           simpl. rewrite close_tm_wrt_tm_open_tm_wrt_tm; eauto using fv_tm_erase_tm.\n\n  + destruct rho; simpl in V; inversion V; subst;\n    move: (IHAnnTyping1 GG (erase b) eq_refl ltac:(auto)) => [av [MS [CV EE]]];\n    inversion CV; subst.\n    ++ exists (a_App av Rel a).\n       repeat split. eapply multi_An_AppLeft; eauto_lc.\n       repeat econstructor; eauto_lc.\n       eapply Path_to_Path; eauto_lc.\n       simpl. autorewcs. congruence.\n    ++ move: (multi_preservation MS H) => TC. inversion TC.\n       move: (values_have_value_types GG H9 H3) => VT.\n       move: (consistent_a_Pi GG VT H11) => [A' [B' EQ]]. subst.\n       pose VV := H3. clearbody VV.\n       eapply An_Push with (b:=a) in H3; try eapply H11; try reflexivity.\n       eexists.\n       split. eapply multi_trans.\n       eapply multi_An_AppLeft; eauto_lc.\n       eapply multi_step; eauto_lc.\n       eapply multi_refl; eauto_lc.\n       repeat econstructor; eauto_lc.\n       split.\n       eapply CC; econstructor; eauto_lc.\n       econstructor; eauto_lc.\n       eapply Path_to_Path; eauto_lc.\n       simpl in EE. simpl. congruence.\n    ++ exists (a_App av Irrel a).\n       repeat split. eapply multi_An_AppLeft; eauto_lc.\n       repeat econstructor; eauto_lc.\n       eapply Path_to_Path; eauto_lc.\n       simpl. autorewcs. congruence.\n    ++ move: (multi_preservation MS H) => TC. inversion TC.\n       move: (values_have_value_types GG H9 H3) => VT.\n       move: (consistent_a_Pi GG VT H11) => [A' [B' EQ]]. subst.\n       pose VV := H3. clearbody VV.\n       eapply An_Push with (b:=a) in H3; try eapply H11; try reflexivity.\n       eexists.\n       split. eapply multi_trans.\n       eapply multi_An_AppLeft; eauto_lc.\n       eapply multi_step; eauto_lc.\n       eapply multi_refl; eauto_lc.\n       repeat econstructor; eauto_lc.\n       split.\n       eapply CC; econstructor; eauto_lc.\n       econstructor; eauto_lc.\n       eapply Path_to_Path; eauto_lc.\n       simpl in EE. simpl. congruence.\n\n  + move: (IHAnnTyping1 GG _ eq_refl V) => [av [MS [CV EE]]].\n    inversion CV.\n    ++ subst.\n      exists (a_Conv av g).\n      repeat split.\n      eapply multi_An_ConvTerm; eauto using AnnDefEq_lc3.\n      eapply CC; eauto using AnnDefEq_lc3.\n      simpl. autorewcs. auto.\n    ++ subst.\n      have ?: lc_tm a0 by eauto using Value_lc.\n      have ?: lc_co g by eauto using AnnDefEq_lc3.\n      exists (a_Conv a0 (g_Trans g0 g)).\n      split.\n      eapply multi_trans.\n      eapply multi_An_ConvTerm; eauto.\n      eapply multi_step.\n      eapply An_Combine; eauto.\n      eapply multi_refl; eauto.\n      split. eapply CC; eauto.\n      simpl. simpl in EE. auto.\n  + exists (a_CPi phi B).\n    have ?: lc_tm (a_CPi phi B) by eapply AnnTyping_lc1; eauto.\n    repeat split; try eapply multi_refl; eauto using Value_lc;\n      simpl; auto.\n    econstructor; eauto using AnnTyping_lc1, AnnPropWff_lc.\n  + exists (a_CAbs phi a).\n    have ?: lc_tm (a_CAbs phi a). eapply AnnTyping_lc1; eauto.\n    repeat split; try eapply multi_refl; eauto using Value_lc;\n      simpl; auto.\n    econstructor; eauto using AnnTyping_lc1, AnnPropWff_lc.\n  + (* CApp case (for paths) *)\n    simpl in V; inversion V; subst;\n    move: (IHAnnTyping GG (erase a1) eq_refl ltac:(auto)) => [av [MS [CV EE]]];\n    inversion CV; subst.\n    ++ exists (a_CApp av g).\n       repeat split.\n       eapply multi_An_CAppLeft; eauto_lc.\n       repeat econstructor; eauto_lc.\n       eapply Path_to_Path; eauto_lc.\n       simpl. autorewcs. congruence.\n    ++ move: (multi_preservation MS H) => TC. inversion TC.\n       move: (values_have_value_types GG H9 H3) => VT.\n       move: (consistent_a_CPi GG VT H11) => [A' [B' EQ]]. subst.\n       pose VV := H3. clearbody VV.\n       eapply An_CPush with (g:=g0) in H3; try eapply H11; try reflexivity.\n       eexists.\n       split.\n       eapply multi_trans.\n       eapply multi_An_CAppLeft; eauto_lc.\n       eapply multi_step; eauto_lc.\n       eapply multi_refl; eauto_lc.\n       repeat econstructor; eauto_lc.\n       split.\n       eapply CC; econstructor; eauto_lc.\n       eapply Path_to_Path; eauto_lc.\n       simpl in EE. simpl. congruence.\nQed.\n\n\n(* simple solver for irrelevant goals *)\n(* TODO replace args y AA b0 h0 with \"fresh\" *)\nLtac solve_irrelevant y AA b0 h0 :=\n  match goal with\n    [ H1 : irrelevant _ _ _ |- _ ] => inversion H1 end;\n  match goal with\n    [ H4 : forall x A, binds x _ _ -> x `notin` _ |- _ ] =>\n    simpl in H4; econstructor; eauto;\n    try (intros y AA b0; move: (H4 y AA b0) => h0; fsetdec) end.\n\n\n(* paths are not (erased) abstractions. *)\nLemma paths_arent_abs :\n  forall a T, Path T a -> forall rho b, a = a_UAbs rho b -> False.\nProof.\n  intros a T P.\n  induction P; intros r b0 EQ;\n    try  destruct rho; simpl in *; inversion EQ.\nQed.\n\nLtac no_paths:=\n  match goal with\n    [ EE : erase (a_App ?b0 ?rho ?a) = a_UAbs _ ?b, H : Path ?T ?b0 |- _ ] =>\n    destruct rho; simpl in EE;\n    match goal with\n      [ FF : ?a = a_UAbs _ ?b |- _ ] =>\n      have P: (Path T a); by eauto using lc_tm_erase end end.\n\n(* Each of the subcases are by induction on a0 to account for top-level coercions on the term.\n   This tactic handles all of the inductive cases. *)\nLtac induction_a0 :=\n  let IR := fresh  in\n  let a0' := fresh in\n  let y := fresh in\n  let AA := fresh in\n  let b0 := fresh in\n  let h0 := fresh in\n  match goal with\n    [ IHa0 : ∀ A0 : tm, irrelevant ?G (dom ?G) ?a0 → _,\n        H1 : irrelevant ?G _ (a_Conv ?a0 ?g),\n        H2 : AnnTyping ?G (a_Conv ?a0 ?g) ?A0 |- _ ] =>\n    inversion H2; subst;\n    (have IR: irrelevant G (dom G) a0 by solve_irrelevant y AA b0 h0);\n    move: (IHa0 _ IR ltac:(eauto) ltac:(auto)) =>\n    [a0' [? ?]];\n    exists (a_Conv a0' g);\n    split; [ eapply multi_An_ConvTerm; eauto with lc | simpl; auto ]\n  end.\n\nLemma reduction_annotation : forall a a',\n    reduction_in_one a a' ->\n    forall G a0 A0, irrelevant G (dom G) a0 -> AnnTyping G a0 A0 -> erase a0 = a ->\n    exists a0', multi (head_reduction G) a0 a0' /\\ erase a0' = a'.\nProof.\n  intros a a' H.\n  induction H.\n  - (* E_AbsTerm. Body of irrelevant abs takes a step. *)\n    intros.\n    dependent induction a0; try destruct rho; simpl in H3; inversion H3; subst.\n    + inversion H2. subst.\n      pick fresh x for (L \\u L0 \\u (fv_tm a0_2) \\u dom G \\u fv_tm a').\n      move: (H11 x ltac:(auto)) => RC. inversion RC. subst. clear H11.\n      move: (H10 x ltac:(auto)) => T2. clear H10.\n      inversion H1.\n      have IR: irrelevant ((x ~ Tm a0_1) ++ G) (dom (x ~ Tm a0_1 ++ G))\n                       (open_tm_wrt_tm a0_2 (a_Var_f x)).\n      econstructor; eauto.\n      { intros x0 A0 b0.\n        destruct (binds_cons_1 _ x0 x _ _ _ b0).\n        + split_hyp.\n          inversion H9. subst.\n          autorewcshyp H4.  auto.\n        + move: (binds_In _ _ _ _ H7) => h0.\n          have NE: x0 <> x. fsetdec.\n          move: (H5 _ _ H7) => NI. simpl in NI.\n          simpl_erase.\n          move: (fv_tm_tm_tm_open_tm_wrt_tm_upper (erase a0_2) (a_Var_f x)) => h1.\n          simpl in h1. fsetdec.\n      }\n      { eapply AnnGood_add_tm; eauto. }\n      have h1: erase (open_tm_wrt_tm a0_2 (a_Var_f x)) =\n               open_tm_wrt_tm (erase_tm a0_2) (a_Var_f x).\n      simpl_erase. auto.\n      move: (H0 x ltac:(auto) _ _ _ IR T2 h1) => [a0' [ms ee]].\n      exists (a_Abs Irrel a0_1 (close_tm_wrt_tm x a0')).\n      split.\n      eapply multi_An_AbsTerm_exists with (x:=x);\n        autorewrite with lngen; auto.\n      simpl_erase. rewrite ee.\n      simpl. autorewrite with lngen. auto.\n    + inversion H2.\n    + induction_a0.\n  - (* E_AppRel *) \n    intros.\n    dependent induction a0; try destruct rho; simpl in H3; inversion H3; subst.\n    + inversion H1. simpl in H4.\n      inversion H2. subst.\n      have I1: irrelevant G (dom G) a0_1.\n      solve_irrelevant y AA b0 h0.\n      move: (IHreduction_in_one _ _ _ I1 H11 eq_refl) => [a0_1' [MS E']].\n      exists (a_App a0_1' Rel a0_2).\n      split.\n      eapply multi_An_AppLeft; eauto using AnnTyping_lc1.\n      simpl. autorewcs. congruence.\n    + induction_a0.\n  - (* E_AppIrrel *) \n    intros.\n    dependent induction a0; try destruct rho; simpl in H2; inversion H2; subst.\n    + inversion H1. simpl in H4.\n      inversion H2. subst.\n      have I1: irrelevant G (dom G) a0_1.\n      solve_irrelevant y AA b0 h0.\n      move: (IHreduction_in_one _ _ _ I1 H8 eq_refl) => [a0_1' [MS E']].\n      exists (a_App a0_1' Irrel a0_2).\n      split.\n      eapply multi_An_AppLeft; eauto using AnnTyping_lc1.\n      simpl. autorewcs. congruence.\n    + induction_a0.\n  - (* E_CAppLeft. *) \n    intros.\n    match goal with\n      [ H2 : erase ?a0 = _ |- _ ] =>\n      dependent induction a0; try destruct rho; simpl in H2; inversion H2; subst\n    end.\n    + induction_a0.\n    + ann_invert_clear.\n      have I: irrelevant G (dom G) a0. solve_irrelevant y AA b0 h0.\n      match goal with\n        [ H7 : AnnTyping ?G a0 ?A |- _ ] =>\n        move: (IHreduction_in_one _ _ _ I H7 eq_refl) => [a0_1' [MS E']]\n      end.\n      exists (a_CApp a0_1' g).\n      split. eapply multi_An_CAppLeft; eauto with lc.\n      simpl. autorewcs. congruence.\n  - (* E_AppAbs *)\n    intros.\n    (* Need induction on a0 for the coercions around the application. *)\n    dependent induction a0; try destruct rho; simpl in H3; inversion H3; subst.\n    + (* No coercions. a0 is a direct (Rel) application of\n      a0_1, which erases to an abstraction. *)\n      ann_invert_clear.\n      inversion H1.\n      have ?: Value (a_UAbs Rel v) by eauto.\n      move: (erased_Value_reduces_to_CoercedValue H10 H4 H5 ltac:(auto)) =>\n      [av ?]. split_hyp.\n      move: (multi_preservation H6 H10) => Tav.\n      (* Check if there is a coercion at the top of av *)\n      match goal with [ H : CoercedValue av |- _ ] => inversion H; subst end.\n      ++ (* Value av *)\n         match goal with [ H10 : Value av , H9 : erase av = _ |- _ ] =>\n            inversion Tav; subst; inversion H10; subst; simpl in H9; inversion H9 end.\n         exists (open_tm_wrt_tm a a0_2).\n         split.\n         eapply multi_trans with (b:= a_App (a_Abs Rel A a) Rel a0_2).\n         eapply multi_An_AppLeft; eauto_lc.\n         eapply multi_step; eauto_lc.\n         eapply multi_refl; eauto.\n         { lc_inversion c. subst.\n           pick fresh y.\n           rewrite (tm_subst_tm_tm_intro y); auto.\n           eapply tm_subst_tm_tm_lc_tm; eauto using AnnTyping_lc1. }\n         rewrite open_tm_erase_tm. auto.\n         (* prove that paths don't erase to abstractions. *)\n         no_paths.\n      ++ (* av = (a |> g) *)\n         have LC: lc_tm a0_1 by eauto using AnnTyping_lc1.\n         (* Push rule *)\n         inversion H1.\n         ann_invert_clear.\n         match goal with\n           [ H4 : AnnGood _ _,  H20 : AnnDefEq G (dom G) g A0 (a_Pi Rel A B),\n             H18 : AnnTyping G a A0, H11: Value a |- _ ] =>\n         move: (values_have_value_types H4 H18 H11) => VT;\n         move: (consistent_a_Pi H4 VT H20) => [A' [B' EQ]]; subst;\n         move: (An_Push _ _ _ _ a0_2 _ _ _ _ _ _ H11 H20 eq_refl eq_refl)=> RED end.\n         have TA': AnnTyping G A' a_Star.\n           { move: (AnnTyping_regularity H17) => T1. inversion T1. auto. }\n         have Tb': AnnTyping G (a_Conv a0_2 (g_Sym (g_PiFst g))) A'.\n           { eapply An_Conv; eauto.\n             eapply An_Sym.  eauto. eauto using AnnTyping_regularity.\n             eapply An_Refl; eauto. eauto with ctx_wff.\n             eapply An_PiFst; eauto. }\n\n         (* Now Beta *)\n         simpl in *.\n         match goal with\n           [ H10: Value ?a, H9 : erase_tm ?a = _ , Ta : AnnTyping G ?a _ |- _ ] =>\n           inversion Ta; subst; inversion H10; subst; simpl in H9; inversion H9 end.\n\n         eexists.\n         split.\n         (* evaluate to application of coerced value *)\n         eapply multi_trans with (b:= a_App (a_Conv (a_Abs Rel A' a0) g) Rel a0_2).\n         eapply multi_An_AppLeft; eauto_lc.\n\n         (* do push rule, lifting coercion to outside. *)\n         eapply (multi_step _ RED).\n\n         (* do beta reduction inside coercion *)\n         eapply multi_step.\n         eapply An_ConvTerm. eauto using AnnTyping_lc1, AnnDefEq_lc3.\n         eapply An_AppAbs; eauto using AnnTyping_lc1.\n\n         (* stop *)\n         eapply multi_refl.\n         { lc_inversion c. repeat econstructor; eauto_lc. }\n\n         (* erasure property *)\n         simpl_erase. auto.\n\n         destruct rho.\n         +++ have P: Path T (a_App (erase v) Rel (erase a0)); by eauto\n                                                                    using lc_tm_erase.\n         +++ have P: Path T (a_App (erase v) Irrel a_Bullet); by eauto using lc_tm_erase.\n    + (* induction step for top-level coercions (Rel) *)\n      induction_a0.\n  - (* E_AppAbs Irrel*)\n    intros.\n    dependent induction a0; try destruct rho; simpl in H2; inversion H2; subst.\n    + (* No coercions. a0 is a direct (Irrel) application of\n        a0_1, which erases to an abstraction. *)\n      ann_invert_clear.\n      inversion H0.\n      match goal with [H12 : AnnTyping G a0_1 (a_Pi Irrel A B),\n                       H4  : AnnGood G (dom G),\n                       H6  : erase_tm a0_1 = a_UAbs Irrel v |- _ ] =>\n      move: H12 => Ta01;\n      move: (erased_Value_reduces_to_CoercedValue Ta01 H4 H6\n             ltac:(auto)) => [av [RE ?]];\n      split_hyp end.\n      move: (multi_preservation RE Ta01) => Tav.\n      (* Check if there is a coercion at the top of av *)\n      match goal with [ H : CoercedValue av |- _ ] => inversion H; subst end.\n      ++ (* Value av *)\n         match goal with [ H10 : Value av , H9 : erase av = _ |- _ ] =>\n            inversion Tav; subst; inversion H10; subst; simpl in H9; inversion H9 end.\n         exists (open_tm_wrt_tm a a0_2).\n         split.\n         eapply multi_trans with (b:= a_App (a_Abs Irrel A a) Irrel a0_2).\n         eapply multi_An_AppLeft; eauto_lc.\n         eapply multi_step; eauto_lc.\n         eapply multi_refl; eauto.\n         { lc_inversion c. subst.\n           pick fresh y.\n           rewrite (tm_subst_tm_tm_intro y); auto.\n           eapply tm_subst_tm_tm_lc_tm; eauto using AnnTyping_lc1. }\n         {\n         (* argument really is irelevant. *)\n           simpl_erase.\n           pick fresh x.\n           move: (H16 x ltac:(auto)) => RC. inversion RC.\n           rewrite (tm_subst_tm_tm_intro x (erase a)).\n           replace (a_Var_f x) with (erase (a_Var_f x)); auto.\n           rewrite open_tm_erase_tm.\n           rewrite tm_subst_tm_tm_fresh_eq; auto.\n           rewrite (tm_subst_tm_tm_intro x (erase a)).\n           replace (a_Var_f x) with (erase (a_Var_f x)); auto.\n           rewrite open_tm_erase_tm.\n           rewrite tm_subst_tm_tm_fresh_eq; auto.\n           apply fv_tm_erase_tm; auto.\n           apply fv_tm_erase_tm; auto.\n         }\n\n         no_paths.\n      ++ (* av = (a |> g) *)\n         have LC: lc_tm a0_1 by eauto using AnnTyping_lc1.\n         (* Push rule *)\n         inversion H0.\n         ann_invert_clear.\n         match goal with\n           [ H4 : AnnGood _ _,  H20 : AnnDefEq G (dom G) g A0 (a_Pi Irrel A B),\n             H18 : AnnTyping G a A0, H11: Value a |- _ ] =>\n         move: (values_have_value_types H4 H18 H11) => VT;\n         move: (consistent_a_Pi H4 VT H20) => [A' [B' EQ]]; subst;\n         move: (An_Push _ _ _ _ a0_2 _ _ _ _ _ _ H11 H20 eq_refl eq_refl)=> RED;\n         have TA': AnnTyping G A' a_Star by\n           (move: (AnnTyping_regularity H18) => T1; inversion T1; auto)\n         end.\n         have Tb': AnnTyping G (a_Conv a0_2 (g_Sym (g_PiFst g))) A'.\n           { eapply An_Conv; eauto.\n             eapply An_Sym.  eauto. eauto using AnnTyping_regularity.\n             eapply An_Refl; eauto. eauto with ctx_wff.\n             eapply An_PiFst; eauto. }\n\n         (* Now Beta *)\n         simpl in *.\n         match goal with\n           [ H10: Value ?a, H9 : erase_tm ?a = _ , Ta : AnnTyping G ?a _ |- _ ] =>\n           inversion Ta; subst; inversion H10; subst; simpl in H9; inversion H9 end.\n\n         eexists.\n         split.\n         (* evaluate to application of coerced value *)\n         eapply multi_trans with (b:= a_App (a_Conv (a_Abs Irrel A' a0) g) Irrel a0_2).\n         eapply multi_An_AppLeft; eauto_lc.\n\n         (* do push rule, lifting coercion to outside. *)\n         eapply (multi_step _ RED).\n\n         (* do beta reduction inside coercion *)\n         eapply multi_step.\n         eapply An_ConvTerm. eauto using AnnTyping_lc1, AnnDefEq_lc3.\n         eapply An_AppAbs; eauto using AnnTyping_lc1.\n\n         (* stop *)\n         eapply multi_refl.\n\n         { lc_inversion c. repeat econstructor; eauto_lc.\n           pick fresh y.\n           move: (H22 y ltac:(auto)) => h0.\n           rewrite (tm_subst_tm_tm_intro y); auto.\n           apply tm_subst_tm_tm_lc_tm; eauto_lc.\n         }\n\n         (* erasure property *)\n         {\n           simpl_erase.\n           pick fresh x.\n           move: (H22 x ltac:(auto)) => RC. inversion RC.\n           rewrite (tm_subst_tm_tm_intro x (erase a0)).\n           replace (a_Var_f x) with (erase (a_Var_f x)); auto.\n           rewrite open_tm_erase_tm.\n           rewrite tm_subst_tm_tm_fresh_eq; auto.\n           rewrite (tm_subst_tm_tm_intro x (erase a0)).\n           replace (a_Var_f x) with (erase (a_Var_f x)); auto.\n           rewrite open_tm_erase_tm.\n           rewrite tm_subst_tm_tm_fresh_eq; auto.\n           apply fv_tm_erase_tm; auto.\n           apply fv_tm_erase_tm; auto.\n         }\n\n         destruct rho.\n         +++ have P: Path T (a_App (erase v) Rel (erase a0)); by eauto\n                                                                    using lc_tm_erase.\n         +++ have P: Path T (a_App (erase v) Irrel a_Bullet); by eauto using lc_tm_erase.\n    + (* induction step for top-level coercions (irrel) *)\n      induction_a0.\n  - (* E_CAbsCApp *)\n    intros.\n    match goal with\n      [ H3 : erase a0 = _ |- _ ] =>\n    dependent induction a0; try destruct rho; simpl in H3; inversion H3; subst\n    end.\n    +  (* induction step *)\n      induction_a0.\n\n    + (* no coercion on top. *)\n      clear IHa0.\n      ann_invert_clear.\n      match goal with\n        [ H0 : irrelevant _ _ _ |- _ ] => inversion H0\n      end.\n      have ?: Value (a_UCAbs b) by eauto.\n      match goal with\n        [ H8 : AnnTyping G a0 _,\n          H4 : AnnGood G (dom G),\n          H5 : erase_tm a0 = _ |- _ ] =>\n        move: (erased_Value_reduces_to_CoercedValue H8 H4 H5 ltac:(auto)) =>\n        [av ?] ;  split_hyp end.\n      match goal with\n        [ H6 : multi (head_reduction G) a0 ?av,\n          H8 : AnnTyping G a0 _ |- _ ] =>\n        move: (multi_preservation H6 H8) => Tav\n      end.\n      (* Check if there is a coercion at the top of av *)\n      match goal with [ H : CoercedValue av |- _ ] => inversion H; subst end.\n      ++ (* Value av *)\n        match goal with [ H10 : Value av , H9 : erase av = _ |- _ ] =>\n        inversion Tav; subst; inversion H10; subst; try destruct rho;\n        simpl in H9; inversion H9 end.\n        subst.\n\n        exists (open_tm_wrt_co a1 g).\n        split.\n        eapply multi_trans with (b := a_CApp (a_CAbs (Eq a b0 A1) a1) g).\n        eapply multi_An_CAppLeft; eauto_lc.\n        eapply multi_step.\n        eapply An_CAppCAbs; eauto_lc.\n        eapply multi_refl; eauto_lc.\n\n        { invert_lc.\n          eapply lc_body_tm_wrt_co; eauto_lc. }\n\n        rewrite <- open_co_erase_tm2 with (g := g_Triv).\n        auto.\n\n      ++ (* av = (a |> g0) *)\n         have LC: lc_tm a1 by eauto using Value_lc.\n         (* Push rule *)\n         match goal with\n           [ H0 : irrelevant _ _ _ |- _ ] => inversion H0\n         end.\n         ann_invert_clear.\n         match goal with\n           [ H4 : AnnGood _ _,  H20 : AnnDefEq G (dom G) ?g0 A (a_CPi _ _),\n             H18 : AnnTyping G a1 A, H11: Value a1 |- _ ] =>\n         move: (values_have_value_types H4 H18 H11) => VT;\n         move: (consistent_a_CPi H4 VT H20) => [phi' [B' EQ]]; subst;\n         move : (An_CPush G a1 g0 g _ _ _ _ _ _ H11 H20 eq_refl eq_refl) => RED\n         end.\n         destruct phi' as [a' b' A'].\n         have Tb':\n           AnnDefEq G (dom G) (g_Cast g (g_Sym (g_CPiFst g0))) a' b'.\n           { eapply An_Cast; eauto. }\n\n         (* Now CBeta *)\n         simpl in *.\n         match goal with\n           [ H10: Value ?a, H9 : erase_tm ?a = _ , Ta : AnnTyping G ?a _ |- _ ] =>\n           inversion Ta; subst; inversion H10; subst; try destruct rho;\n           simpl in H9; inversion H9 end.\n\n         eexists.\n         split.\n         (* evaluate to application of coerced value *)\n         eapply multi_trans.\n\n         eapply multi_An_CAppLeft; eauto_lc.\n\n         (* do push rule, lifting coercion to outside. *)\n         eapply (multi_step _ RED).\n\n         (* do beta reduction inside coercion *)\n         eapply multi_step.\n         eapply An_ConvTerm. eauto using AnnTyping_lc1, AnnDefEq_lc3.\n         eapply An_CAppCAbs; eauto_lc.\n\n         (* stop *)\n         eapply multi_refl.\n\n         { lc_inversion c. repeat econstructor; eauto_lc. }\n\n         simpl_erase.\n         rewrite <- open_co_erase_tm2 with (g := g_Triv).\n         auto.\n\n  - (* E_Axiom *)\n    intros.\n    dependent induction a0; try destruct rho; simpl in H2; inversion H2; subst.\n\n    + unfold toplevel in H. unfold erase_sig in H.\n      destruct (@binds_map_3 _ _ erase_csort F (Ax a A) an_toplevel H).\n      split_hyp. destruct x; inversion H3. subst.\n\n      exists a0. repeat split.\n      eapply multi_step. eauto.\n      eapply multi_refl.\n      eauto using AnnTyping_lc1, an_toplevel_closed.\n\n    + (* induction step *)\n      induction_a0.\n\nUnshelve. all: auto.\nQed.\n\nEnd fc_consist.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/corespec/src/FcEtt/fc_consist.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23960216046857682}}
{"text": "Require Import List.\nImport ListNotations.\n(*Require Import Coq.Lists.ListSet.*)\nRequire Import Extraction.\n\nRequire Import Unify.\nRequire Import MiniKanrenSyntax.\nRequire Import Stream.\nRequire Import DenotationalSem.\nRequire Import OperationalSem.\nRequire Import OpSemSoundness.\nRequire Import OpSemCompleteness.\n\n\nModule ObviousConstraintStore <: ConstraintStoreSig.\n\nDefinition constraint_store (s : subst) : Set := list (term * term).\n\nDefinition init_cs : constraint_store empty_subst := [].\n\nInductive add_constraint_ind_def : forall (s : subst), constraint_store s -> term -> term -> option (constraint_store s) -> Set :=\n| acC : forall s cs t1 t2, add_constraint_ind_def s cs t1 t2 (Some ((t1, t2) :: cs)).\n\nDefinition add_constraint := add_constraint_ind_def.\n\nLemma add_constraint_exists :\n  forall (s : subst) (cs : constraint_store s) (t1 t2 : term),\n    {r : option (constraint_store s) & add_constraint s cs t1 t2 r}.\nProof. intros. eexists. econstructor. Qed.\n\nLemma add_constraint_unique :\n  forall (s : subst) (cs : constraint_store s) (t1 t2 : term) (r r' : option (constraint_store s)),\n    add_constraint s cs t1 t2 r -> add_constraint s cs t1 t2 r' -> r = r'.\nProof. intros. good_inversion H. good_inversion H0. simpl_existT_cs_same. reflexivity. Qed.\n\nInductive upd_cs_ind_def : forall (s : subst), constraint_store s -> forall (d : subst), option (constraint_store (compose s d)) -> Set :=\n| uC : forall s cs d, upd_cs_ind_def s cs d (Some cs).\n\nDefinition upd_cs := upd_cs_ind_def.\n\nLemma upd_cs_exists :\n  forall (s : subst) (cs : constraint_store s) (d : subst),\n    {r : option (constraint_store (compose s d)) & upd_cs s cs d r}.\nProof. intros. eexists. econstructor. Qed.\n\nLemma upd_cs_unique :\n  forall (s : subst) (cs : constraint_store s) (d : subst) (r r' : option (constraint_store (compose s d))),\n    upd_cs s cs d r -> upd_cs s cs d r' -> r = r'.\nProof. intros. good_inversion H. good_inversion H0. simpl_existT_cs_same. reflexivity. Qed.\n\nDefinition in_denotational_sem_cs (s : subst) (cs : constraint_store s) (f : repr_fun) :=\n  forall (t1 t2 : term), In (t1, t2) cs -> ~ gt_eq (apply_repr_fun f t1) (apply_repr_fun f t2).\n\nNotation \"[| s , cs , f |]\" := (in_denotational_sem_cs s cs f) (at level 0).\n\nLemma init_condition : forall f, [| empty_subst , init_cs , f |].\nProof. unfold in_denotational_sem_cs. contradiction. Qed.\n\nLemma add_constraint_fail_condition :\n  forall (s : subst) (cs : constraint_store s) (t1 t2 : term),\n    add_constraint s cs t1 t2 None ->\n    forall f, ~ ([| s , cs  , f |] /\\ [ s , f ] /\\ [| Disunify t1 t2 , f |]).\nProof. intros. inversion H. Qed.\n\nLemma add_constraint_success_condition :\n  forall (s : subst) (cs cs' : constraint_store s) (t1 t2 : term),\n    add_constraint s cs t1 t2 (Some cs') ->\n    forall f, [| s , cs' , f |] /\\ [ s , f ] <->\n              [| s , cs  , f |] /\\ [ s , f ] /\\ [| Disunify t1 t2 , f |].\nProof.\n  unfold in_denotational_sem_cs. intros.\n  good_inversion H. simpl_existT_cs_same. good_inversion H4. split.\n  { intros [DSCS DSS]. split; try split; intros; auto.\n    { apply DSCS. right. auto. }\n    { constructor. apply DSCS. left. auto. }  }\n  { intros [DSCS [DSS DSG]]. good_inversion DSG. split; auto. intros.\n    destruct H; auto. good_inversion H; auto. }\nQed.\n\nLemma upd_cs_fail_condition :\n  forall (s : subst) (cs : constraint_store s) (d : subst),\n    upd_cs s cs d None -> forall f, ~ ([| s , cs , f |] /\\ [ compose s d , f ]).\nProof. intros. inversion H. Qed.\n\nLemma upd_cs_success_condition :\n  forall (s : subst) (cs : constraint_store s) (d : subst) (cs' : constraint_store (compose s d)),\n    upd_cs s cs d (Some cs') ->\n    forall f, [| compose s d , cs' , f |] /\\ [ compose s d , f ] <->\n              [| s           , cs  , f |] /\\ [ compose s d , f ].\nProof.\n  unfold in_denotational_sem_cs. intros. good_inversion H. simpl_existT_cs_same.\n  good_inversion H3. reflexivity.\nQed.\n\nEnd ObviousConstraintStore.\n\n\nModule OperationalSemObviousCS := OperationalSemAbstr ObviousConstraintStore.\n\nModule OperationalSemObviousCSSoundness := OperationalSemSoundnessAbstr ObviousConstraintStore.\n\nModule OperationalSemObviousCSCompleteness := OperationalSemCompletenessAbstr ObviousConstraintStore.\n\nImport OperationalSemObviousCS.\n\nExtraction Language Haskell.\n\nExtraction \"extracted/obvious_diseq_interpreter.hs\" op_sem_exists.\n\n\n", "meta": {"author": "miniKanren-disequality-semantics", "repo": "coq", "sha": "322b9406f7140d5005603cae456ec54d4646a246", "save_path": "github-repos/coq/miniKanren-disequality-semantics-coq", "path": "github-repos/coq/miniKanren-disequality-semantics-coq/coq-322b9406f7140d5005603cae456ec54d4646a246/src/ObviousDisequality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23960216046857682}}
{"text": "From iris.algebra Require Import auth agree excl csum.\nFrom iris.proofmode Require Import tactics.\nFrom Perennial.base_logic.lib Require Export own.\nFrom iris.prelude Require Import options.\n\nDefinition crashR := csumR fracR (agreeR unitO).\nDefinition NC_tok q : crashR := Cinl q.\nDefinition C_tok : crashR := Cinr (to_agree ()).\n\nClass crashGS Σ := { crash_inG :> inG Σ crashR; crash_name : gname }.\nClass crashGpreS Σ := { crash_inPreG :> inG Σ crashR }.\n\nDefinition crashΣ : gFunctors :=\n    #[GFunctor (csumR fracR (agreeR unitO))].\n\nGlobal Instance subG_crashGS {Σ} : subG crashΣ Σ → crashGpreS Σ.\nProof. solve_inG. Qed.\n\nGlobal Instance crashGpreS_fromGS Σ :\n  crashGS Σ → crashGpreS Σ.\nProof. intros ?. constructor. apply _. Defined.\n\nDefinition NC_def `{crashGS Σ} q := own crash_name (NC_tok q).\nDefinition NC_aux `{crashGS Σ} : seal NC_def. by eexists. Qed.\nDefinition NC `{crashGS Σ} := NC_aux.(unseal).\nGlobal Arguments NC {_ _} _%Qp.\nDefinition C_def `{crashGS Σ} := own crash_name C_tok.\nDefinition C_aux `{crashGS Σ} : seal C_def. by eexists. Qed.\nDefinition C `{crashGS Σ} := C_aux.(unseal).\n\nLemma NC_alloc `{!crashGpreS Σ} : ⊢ |==> ∃ _ : crashGS Σ, NC 1.\nProof.\n  iIntros.\n  iMod (own_alloc (Cinl 1%Qp)) as (γ) \"H\".\n  { rewrite //=. }\n  iExists {| crash_name := γ |}.\n  rewrite /NC NC_aux.(seal_eq). by iFrame.\nQed.\n\nLemma NC_alloc_strong `{!crashGpreS Σ} :\n  ⊢ |==> ∃ γn : gname, let Hc := {| crash_name := γn |} in NC 1.\nProof.\n  iIntros.\n  iMod (own_alloc (Cinl 1%Qp)) as (γ) \"H\".\n  { rewrite //=. }\n  iExists γ.\n  rewrite /NC NC_aux.(seal_eq). by iFrame.\nQed.\n\nSection crash_tok_props.\nContext `{!crashGS Σ}.\nImplicit Types i : positive.\nImplicit Types P Q R : iProp Σ.\n\nGlobal Instance C_timeless : Timeless C.\nProof. rewrite /C C_aux.(seal_eq). apply _. Qed.\n\nGlobal Instance C_persistent : Persistent C.\nProof. rewrite /C C_aux.(seal_eq). apply _. Qed.\n\nGlobal Instance NC_timeless q : Timeless (NC q).\nProof. rewrite /NC NC_aux.(seal_eq). apply _. Qed.\n\nLemma NC_split q:\n  NC q ⊢ NC (q/2) ∗ NC (q/2).\nProof. by rewrite /NC NC_aux.(seal_eq) -own_op -Cinl_op frac_op Qp.div_2. Qed.\n\nLemma NC_join q:\n  NC (q/2) ∗ NC (q/2) ⊢ NC q.\nProof. by rewrite /NC NC_aux.(seal_eq) -own_op -Cinl_op frac_op Qp.div_2. Qed.\n\nLemma NC_C q: NC q -∗ C -∗ False.\nProof.\n rewrite /C C_aux.(seal_eq).\n rewrite /NC NC_aux.(seal_eq).\n  iIntros \"H H'\".\n  { by iDestruct (own_valid_2 with \"H H'\") as %?. }\nQed.\n\nLemma NC_upd_C: NC 1 ==∗ C.\nProof.\n rewrite /C C_aux.(seal_eq).\n rewrite /NC NC_aux.(seal_eq).\n iIntros \"H\". iMod (own_update with \"H\") as \"$\".\n { by apply cmra_update_exclusive. }\n done.\nQed.\nEnd crash_tok_props.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/base_logic/lib/crash_token.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2396021604685768}}
{"text": "(** * Functoriality of the construction of adjunctions *)\nRequire Import Category.Core Functor.Core NaturalTransformation.Core.\nRequire Import Functor.Identity Functor.Composition.Core.\nRequire Import NaturalTransformation.Composition.Core NaturalTransformation.Composition.Laws.\nRequire Import NaturalTransformation.Identity.\nRequire Import NaturalTransformation.Paths.\nRequire Import Functor.Dual NaturalTransformation.Dual.\nRequire Import Adjoint.Core Adjoint.UnitCounit Adjoint.Dual.\nRequire Import Adjoint.Functorial.Parts.\nRequire Import HoTT.Tactics.\nRequire Import Basics.Tactics.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope natural_transformation_scope.\nLocal Open Scope morphism_scope.\n\nSection laws.\n  (** Some tactics to handle all the proofs.  The tactics deal with\n      the \"obvious\" commutativity requirements by writing back and\n      forth with associativity and respectfulness of composition,\n      trying to find applications of the adjunction laws. *)\n  Local Ltac try_various_ways tac :=\n    progress repeat first [ progress tac\n                          | rewrite <- ?Functor.Core.composition_of;\n                            progress try_associativity_quick tac\n                          | rewrite -> ?Functor.Core.composition_of;\n                            progress try_associativity_quick tac ].\n\n  (** This is suboptimal, because we keep rewriting back and forth\n      with associativity and [composition_of].  But it only takes 0.74\n      seconds total, so it's probably not worth optimizing. *)\n  Local Ltac handle_laws' :=\n    idtac;\n    match goal with\n      | _ => reflexivity\n      | _ => progress rewrite ?identity_of, ?Category.Core.left_identity, ?Category.Core.right_identity\n      | _ => try_various_ways ltac:(f_ap)\n      | [ |- context[components_of ?T ?x] ]\n        => try_various_ways ltac:(simpl rewrite <- (commutes T))\n      | [ |- context[unit ?A] ]\n        => try_various_ways ltac:(rewrite (unit_counit_equation_1 A))\n      | [ |- context[unit ?A] ]\n        => try_various_ways ltac:(rewrite (unit_counit_equation_2 A))\n    end.\n\n  Local Ltac t :=\n    apply path_natural_transformation; intro;\n    cbn;\n    repeat handle_laws'.\n\n  Section left.\n    Local Arguments unit : simpl never.\n    Local Arguments counit : simpl never.\n\n    Section identity_of.\n      Context `{Funext}.\n      Variables C D : PreCategory.\n\n      Variable G : Functor D C.\n      Variable F : Functor C D.\n      Variable A : F -| G.\n\n      Definition left_identity_of\n      : @left_morphism_of C C 1 D D 1 G F A G F A 1\n        = ((left_identity_natural_transformation_2 _)\n             o (right_identity_natural_transformation_1 _))%natural_transformation.\n      Proof. t. Qed.\n\n      Definition left_identity_of_nondep\n      : @left_morphism_of_nondep C D G F A G F A 1 = 1%natural_transformation.\n      Proof. t. Qed.\n    End identity_of.\n\n    Section composition_of_dep.\n      Context `{Funext}.\n      Variables C C' C'' : PreCategory.\n      Variable CF : Functor C C'.\n      Variable CF' : Functor C' C''.\n      Variables D D' D'' : PreCategory.\n      Variable DF : Functor D D'.\n      Variable DF' : Functor D' D''.\n\n      Variable G : Functor D C.\n      Variable F : Functor C D.\n      Variable A : F -| G.\n      Variable G' : Functor D' C'.\n      Variable F' : Functor C' D'.\n      Variable A' : F' -| G'.\n      Variable G'' : Functor D'' C''.\n      Variable F'' : Functor C'' D''.\n      Variable A'' : F'' -| G''.\n      Variable T : NaturalTransformation (CF o G) (G' o DF).\n      Variable T' : NaturalTransformation (CF' o G') (G'' o DF').\n\n      Local Open Scope natural_transformation_scope.\n\n      Definition left_composition_of\n      : (@left_morphism_of\n           _ _ _ _ _ _ _ _\n           A _ _ A''\n           ((associator_1 _ _ _)\n              o (T' oR DF)\n              o (associator_2 _ _ _)\n              o (CF' oL T)\n              o (associator_1 _ _ _)))\n        = (associator_2 _ _ _)\n            o (DF' oL left_morphism_of A A' T)\n            o (associator_1 _ _ _)\n            o (left_morphism_of A' A'' T' oR CF)\n            o (associator_2 _ _ _).\n      Proof. t. Qed.\n    End composition_of_dep.\n\n    Section composition_of.\n      Context `{Funext}.\n      Variables C D : PreCategory.\n\n      Variable G : Functor D C.\n      Variable F : Functor C D.\n      Variable A : F -| G.\n      Variable G' : Functor D C.\n      Variable F' : Functor C D.\n      Variable A' : F' -| G'.\n      Variable G'' : Functor D C.\n      Variable F'' : Functor C D.\n      Variable A'' : F'' -| G''.\n      Variable T : NaturalTransformation G G'.\n      Variable T' : NaturalTransformation G' G''.\n\n      Local Open Scope natural_transformation_scope.\n\n      Definition left_composition_of_nondep\n      : (@left_morphism_of_nondep _ _ _ _ A _ _ A'' (T' o T))\n        = ((left_morphism_of_nondep A A' T)\n             o (left_morphism_of_nondep A' A'' T')).\n      Proof. t. Qed.\n    End composition_of.\n  End left.\n\n  Section right.\n    Section identity_of.\n      Context `{Funext}.\n      Variables C D : PreCategory.\n\n      Variable F : Functor C D.\n      Variable G : Functor D C.\n      Variable A : F -| G.\n\n      Definition right_identity_of\n      : @right_morphism_of C C 1 D D 1 F G A F G A 1\n        = ((right_identity_natural_transformation_2 _)\n             o (left_identity_natural_transformation_1 _))%natural_transformation\n        := ap (@NaturalTransformation.Dual.opposite _ _ _ _)\n              (@left_identity_of _ _ _ F^op G^op A^op).\n\n      Definition right_identity_of_nondep\n      : @right_morphism_of_nondep C D F G A F G A 1 = 1%natural_transformation\n        := ap (@NaturalTransformation.Dual.opposite _ _ _ _)\n              (@left_identity_of_nondep _ _ _ F^op G^op A^op).\n    End identity_of.\n\n    Section composition_of_dep.\n      Context `{Funext}.\n      Variables C C' C'' : PreCategory.\n      Variable CF : Functor C C'.\n      Variable CF' : Functor C' C''.\n      Variables D D' D'' : PreCategory.\n      Variable DF : Functor D D'.\n      Variable DF' : Functor D' D''.\n\n      Variable F : Functor C D.\n      Variable G : Functor D C.\n      Variable A : F -| G.\n      Variable F' : Functor C' D'.\n      Variable G' : Functor D' C'.\n      Variable A' : F' -| G'.\n      Variable F'' : Functor C'' D''.\n      Variable G'' : Functor D'' C''.\n      Variable A'' : F'' -| G''.\n      Variable T : NaturalTransformation (F' o CF) (DF o F).\n      Variable T' : NaturalTransformation (F'' o CF') (DF' o F').\n\n      Local Open Scope natural_transformation_scope.\n\n      (** This is slow, at about 3.8 s.  It also requires the opposite\n          association to unify. *)\n      Definition right_composition_of\n      : right_morphism_of\n          A A''\n          ((associator_2 DF' DF F)\n             o ((DF' oL T)\n                  o ((associator_1 DF' F' CF)\n                       o ((T' oR CF)\n                            o (associator_2 F'' CF' CF)))))\n        = (associator_1 G'' DF' DF)\n            o ((right_morphism_of A' A'' T' oR DF)\n                 o ((associator_2 CF' G' DF)\n                      o ((CF' oL right_morphism_of A A' T)\n                           o (associator_1 CF' CF G))))\n        := ap (@NaturalTransformation.Dual.opposite _ _ _ _)\n              (@left_composition_of\n                 _ _ _ _ (DF^op) (DF'^op) _ _ _ (CF^op) (CF'^op)\n                 _ _ A^op _ _ A'^op _ _ A''^op T^op T'^op).\n    End composition_of_dep.\n\n    Section composition_of.\n      Context `{Funext}.\n      Variables C D : PreCategory.\n\n      Variable F : Functor C D.\n      Variable G : Functor D C.\n      Variable A : F -| G.\n      Variable F' : Functor C D.\n      Variable G' : Functor D C.\n      Variable A' : F' -| G'.\n      Variable F'' : Functor C D.\n      Variable G'' : Functor D C.\n      Variable A'' : F'' -| G''.\n      Variable T : NaturalTransformation F F'.\n      Variable T' : NaturalTransformation F' F''.\n\n      Local Open Scope natural_transformation_scope.\n\n      Definition right_composition_of_nondep\n      : (@right_morphism_of_nondep _ _ _ _ A'' _ _ A (T' o T))\n        = ((right_morphism_of_nondep A' A T)\n             o (right_morphism_of_nondep A'' A' T'))\n        := ap (@NaturalTransformation.Dual.opposite _ _ _ _)\n              (@left_composition_of_nondep _ _ _ _ _ A''^op _ _ A'^op _ _ A^op T'^op T^op).\n    End composition_of.\n  End right.\nEnd laws.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Categories/Adjoint/Functorial/Laws.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.23959215063535602}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.floyd.VSU.\nRequire Import pile.\nRequire Import spec_stdlib.\nRequire Import spec_pile.\nRequire Import spec_pile_private.\nRequire Import PileModel.\n\nSection Pile_VSU.\nVariable M: MallocFreeAPD.\n\nLemma listrep_local_facts:\n  forall sigma p,\n   listrep M sigma p |--\n   !! (is_pointer_or_null p /\\ (p=nullval <-> sigma=nil) /\\ Forall (Z.le 0) sigma).\nProof.\nintros.\nrevert p; induction sigma; \n  unfold listrep; fold listrep; intros.\n  entailer!; intuition.\nIntros y. entailer!.\nsplit.\nsplit; intro. subst p. destruct H0; contradiction. discriminate.\nconstructor; auto. lia.\nQed.\n\nLocal Hint Resolve listrep_local_facts : saturate_local.\n\nLemma listrep_valid_pointer:\n  forall sigma p,\n   listrep M sigma p |-- valid_pointer p.\nProof.\n destruct sigma; unfold listrep; fold listrep;\n intros; entailer!; auto with valid_pointer.\nQed.\n\nLocal Hint Resolve listrep_valid_pointer : valid_pointer.\n\nLemma prep_local_facts:\n  forall sigma p,\n   prep M sigma p |-- !! (isptr p /\\ Forall (Z.le 0) sigma).\nProof.\nintros.\nunfold prep.\nIntros q.\nentailer!.\nQed.\nLocal Hint Resolve prep_local_facts : saturate_local.\n\nLemma prep_valid_pointer:\n  forall sigma p,\n   prep M sigma p |-- valid_pointer p.\nProof. \n intros.\n unfold prep. Intros x.\n entailer!; auto with valid_pointer.\nQed.\nLocal Hint Resolve prep_valid_pointer : valid_pointer.\n\nDefinition pilefreeable (p: val) : mpred :=\n            malloc_token M Ews tpile p.\n\nDefinition PILE: PileAPD := Build_PileAPD (prep M) prep_local_facts prep_valid_pointer pilefreeable.\n\nDefinition PILEPRIV: PilePrivateAPD M := Build_PilePrivateAPD M PILE (eq_refl _).\n\nDefinition surely_malloc_spec :=\n  DECLARE _surely_malloc\n   WITH t:type, gv: globals\n   PRE [ size_t ]\n       PROP (0 <= sizeof t <= Ptrofs.max_unsigned;\n                complete_legal_cosu_type t = true;\n                natural_aligned natural_alignment t = true)\n       PARAMS (Vptrofs (Ptrofs.repr (sizeof t))) GLOBALS (gv)\n       SEP (mem_mgr M gv)\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (mem_mgr M gv; malloc_token M Ews t p * data_at_ Ews t p).\n\n  Definition Pile_ASI: funspecs := PileASI M PILE.\n\n  Definition pile_imported_specs:funspecs := MallocFreeASI M.\n\n  Definition pile_internal_specs: funspecs := surely_malloc_spec::Pile_ASI.\n\n  Definition PileVprog: varspecs. mk_varspecs prog. Defined.\n  Definition PileGprog: funspecs := pile_imported_specs ++ pile_internal_specs.\n\nLemma body_surely_malloc: semax_body PileVprog PileGprog f_surely_malloc surely_malloc_spec.\nProof.\nstart_function.\nforward_call (malloc_spec_sub M t) gv.\nIntros p.\nif_tac.\n{ subst.\n  forward_if False.\n  - forward_call 1. contradiction.\n  - congruence. }\nforward_if True.\n+ contradiction.\n+ forward. entailer!.\n+ forward. Exists p. entailer!.\nQed.\n\nLemma body_Pile_new: semax_body PileVprog PileGprog f_Pile_new (Pile_new_spec M PILE).\nProof.\nstart_function.\nforward_call (tpile, gv).\nsplit3; simpl; auto; computable.\nIntros p.\nrepeat step!.\nsimpl spec_pile.pilerep.\nunfold prep, listrep, pile_freeable.\nrepeat step!.\nQed.\n\nLemma body_Pile_add: semax_body PileVprog PileGprog f_Pile_add (Pile_add_spec M PILE).\nProof.\nstart_function.\nforward_call (tlist, gv).\nsplit3; simpl; auto; computable.\nIntros q.\nsimpl spec_pile.pilerep; unfold prep.\nIntros head.\nforward.\nforward.\nforward.\nforward.\nsimpl pilerep; unfold prep.\nExists q.\nunfold listrep at 2; fold listrep.\nExists head.\nentailer!; try apply derives_refl.\nQed.\n\nLemma body_Pile_count: semax_body PileVprog PileGprog f_Pile_count (Pile_count_spec PILE).\nProof.\nstart_function.\nsimpl pilerep; unfold prep. Intros head.\nforward.\nunfold Sfor.\nforward.\nforward_loop (EX r:val, EX s2: list Z,\n   PROP(0 <= sumlist s2 <= sumlist sigma)\n   LOCAL(temp _c (Vint (Int.repr (sumlist sigma - sumlist s2)));\n              temp _p p; temp _q r)\n   SEP (data_at Ews tpile head p; \n          listrep M s2 r -* listrep M sigma head;\n          listrep M s2 r))%assert\n   break: \n  (PROP()\n   LOCAL(temp _c (Vint (Int.repr (sumlist sigma))); temp _p p)\n   SEP (data_at Ews tpile head p; \n          listrep M sigma head))%assert.\n-\nExists head sigma.\nentailer!. rewrite Z.sub_diag. auto.\napply wand_sepcon_adjoint. cancel.\n-\nIntros r s2.\nforward_if (r<>nullval).\nforward.\nentailer!.\nsubst r.\nforward.\nentailer!.\nassert (s2=nil) by intuition; subst s2.\nsimpl. rewrite Z.sub_0_r; auto.\nsep_apply (modus_ponens_wand (listrep M s2 nullval)).\ncancel.\nIntros.\ndestruct s2.\nassert_PROP False; [ | contradiction]. {\n entailer!. assert (r=nullval) by intuition; subst r. congruence.\n}\nunfold listrep at 3; fold (listrep M).\nIntros r'.\nforward.\nforward. {\n entailer!.\n simpl in H0.\n clear - H0 H H2 H9.\n rewrite (Int.signed_repr z) by rep_lia.\n rewrite (Int.signed_repr) by rep_lia.\n assert (0 <= sumlist s2). {\n clear - H9. induction s2; simpl; auto. lia.\n inv H9. apply IHs2 in H2. lia.\n }\n rep_lia.\n}\nforward.\nExists r' s2.\nentailer!.\nsimpl. split.\nsimpl in H0.\n assert (0 <= sumlist s2). {\n clear - H9. induction s2; simpl; auto. lia.\n inv H9. apply IHs2 in H2. lia.\n }\n rep_lia.\n f_equal; f_equal; lia.\napply -> wand_sepcon_adjoint.\nmatch goal with |- (_ * ?A * ?B * ?C)%logic |-- _ => \n assert ((A * B * C)%logic |-- listrep M (z::s2) r) end.\nunfold listrep at 2; fold (listrep M). Exists r'. entailer!.\nsep_apply H10.\nsep_apply modus_ponens_wand.\nauto.\n -\nforward.\nsimpl pilerep; unfold prep.\nExists head.\ncancel.\nQed.\n\nLemma body_Pile_free: semax_body PileVprog PileGprog f_Pile_free (Pile_free_spec M PILE).\nProof.\nstart_function.\nsimpl pilerep; unfold prep. \nsimpl pile_freeable. unfold pilefreeable. Intros head.\nforward.\nforward_while (EX q:val, EX s2: list Z,\n   PROP ( )\n   LOCAL (temp _q q; temp _p p; gvars gv)\n   SEP (data_at Ews tpile head p; \n       listrep M s2 q; malloc_token M Ews tpile p;\n   mem_mgr M gv))%assert.\n{ Exists head sigma; entailer!. }\n{ entailer!. }\n{ destruct s2.\n   assert_PROP False; [|contradiction]. unfold listrep. entailer!.\n  unfold listrep; fold (listrep M).\n  Intros y.\n  forward.\n  forward_call (free_spec_sub M (Tstruct _list noattr)) (q, gv).\n  rewrite if_false by (intro; subst; contradiction).\n  cancel.\n  forward.\n  Exists (y, s2).\n  entailer!. cancel. }\nsubst.\nassert_PROP (p<>nullval). entailer!.\nforward_call (free_spec_sub M (Tstruct _pile noattr))  (p, gv).\nrewrite if_false by auto.\ncancel.\nforward.\nrewrite (proj1 H0) by auto.\nunfold listrep.\nentailer!.\nQed.\n\n\nDefinition PileVSU: @VSU NullExtension.Espec\n           nil pile_imported_specs ltac:(QPprog prog) Pile_ASI emp.\n Proof. \n    mkVSU prog pile_internal_specs.\n    + solve_SF_internal body_surely_malloc.\n    + solve_SF_internal body_Pile_new.\n    + solve_SF_internal body_Pile_add.\n    + solve_SF_internal body_Pile_count.\n    + solve_SF_internal body_Pile_free.\n  Qed.\n\nDefinition PilePrivateVSU: @VSU NullExtension.Espec\n      nil pile_imported_specs ltac:(QPprog prog) (PilePrivateASI M PILEPRIV) emp.\n Proof. \n    mkVSU prog pile_internal_specs.\n    + solve_SF_internal body_surely_malloc.\n    + solve_SF_internal body_Pile_new.\n    + solve_SF_internal body_Pile_add.\n    + solve_SF_internal body_Pile_count.\n    + solve_SF_internal body_Pile_free.\n  Qed.\n\nEnd Pile_VSU.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs64/VSUpile/verif_pile.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.23950804663043068}}
{"text": "Add LoadPath \"../from_compcert\".\nRequire Import Libs.\n(*Require Import Floats.*)\nRequire Import AST.\nRequire Import Setoid.\nRequire Import ArithClasses.\n\n\n\n(* we define the type of memories for Loops *)\n\n\n(* memory is splitted in arrays. Each array is recognised through it's\n   ident.\n\n   each cell of the array is then accessed through a list of indexes\n   of type int *)\n\nRecord Array_Id := mk_Array_Id {\n  open_Array_Id : ident}.\n\nGlobal Instance singletonInd_Array_Id : singletonInd Array_Id ident :=\n{ open := open_Array_Id;\n  mk := mk_Array_Id}.\nProof.\n  destruct i; auto.\n  auto.\nQed.\n\nRecord Cell_Id `(Numerical Num) := mkCellIdent\n  { array : Array_Id;\n    cell : list Num}.\n\nImplicit Arguments Cell_Id [[H]].\nImplicit Arguments array [[Num] [H]].\nImplicit Arguments cell [[Num] [H]].\n\nDefinition z2icell (ci: Cell_Id Z) : option (Cell_Id int) :=\n  do c <- z2ilist (ci.(cell));\n  Some {| array := ci.(array);\n     cell := c|}.\n\nDefinition i2zcell (ci: Cell_Id int) : Cell_Id Z :=\n  {| array := ci.(array);\n     cell := i2zlist ci.(cell)|}.\n\nLemma z2i2zcell zci ici: z2icell zci = Some ici -> i2zcell ici = zci.\nProof.\n  unfold z2icell, i2zcell.\n  destruct zci, ici. simpl. intro SOME.\n  monadInv SOME.\n  inv SOME.\n  f_equal.\n  apply z2i2zlist. auto.\nQed.\n\nGlobal Instance EqDec_t `{Numerical Num}: EqDec (Cell_Id Num).\nProof.\n  constructor. intros.\n  dec_eq.\nQed.\n\n\nModule Type BASEMEM(N:NUMERICAL).\n  Import N.\n  Existing Instance Numerical_Num.\n\n  (* values of the language *)\n  Parameter Value: Type.\n\n  (* memories *)\n  Parameter Memory: Type.\n\n\n  (* memories can be of \"same layout\", and it's an equivalence\n     relation. One can see two memories with the same layout as memories\n     with the same arrays, containing the same layout of values. *)\n\n  Parameter same_memory_layout: relation Memory.\n\n  Declare Instance Equiv_smt: Equivalence same_memory_layout.\n  \n\n  Parameter read: Memory -> Cell_Id Num -> option Value.\n\n  (* two memories with same layout are readable at the same locations *)\n\n  Parameter read_same_layout:\n    forall mem1 mem2 ci, same_memory_layout mem1 mem2 ->\n    is_some (read mem1 ci) -> is_some (read mem2 ci).\n\n  Parameter write: Memory -> Cell_Id Num -> Value -> option Memory.\n\n  (* you don't change the layout of a memory by writing in it *)\n\n  Parameter write_keep_layout:\n    forall mem1 mem2 ci v, write mem1 ci v = Some mem2 -> same_memory_layout mem1 mem2.\n\n  (* two memories with the same layout are accessible at the same locations *)\n  Parameter write_same_layout:\n    forall mem1 mem2 ci v, same_memory_layout mem1 mem2 ->\n    (is_some (write mem1 ci v) -> is_some (write mem2 ci v)).\n\n\n  (* write followed by a read *)\n  Definition read_write mem ci v : option Value :=\n    do mem' <- write mem ci v;\n    read mem' ci.\n\n  (* at the same location for two memories with the same layout, we read\n     the new value *)\n  (* one might have espect something like:\n\n     read_write mem1 ci v = Some mem2 ->\n     read mem2 ci = Some v\n\n     This would not take into account the fact that writing at some\n     location can lead to lose information. Say you have a char[] and\n     you write a large value in it. The compiler will automatically\n     downgrade the large value to a char before writing it. So reading\n     it will lead to a value in the range of char, not the initial one.\n     \n     For the correctness of the reordering of write, it is in fact\n     useless to know exactly what would be read, but just that it is\n     the same, whatever the order of the writes are*)\n\n  Parameter rws: forall mem1 mem2 ci v,\n    same_memory_layout mem1 mem2 ->\n    read_write mem1 ci v = read_write mem2 ci v.\n\n  (* at an other location, we read the old value *)\n  Parameter rwo: forall mem1 mem2 ci1 ci2 v,\n    write mem1 ci1 v = Some mem2 -> ci1 <> ci2 ->\n    read mem2 ci2 = read mem1 ci2.\n\nEnd BASEMEM.\n\n\n(* This is a very simplist instance of the module type. A more\n   credible one can be found in OtherMemory. It is to show it is\n   instanciable and to \"explain\" better some prerequisites*)\n\nModule BMem(N:NUMERICAL) <: BASEMEM(N).\n  Import N.\n  Existing Instance Numerical_Num.\n\n\n  Definition Value := Z.\n\n  (*\n  Inductive has_type: value -> typ -> Prop :=\n  | HT_int: forall i, has_type (Vint i) Tint\n  | HT_float: forall f, has_type (Vfloat f) Tfloat.\n\n  Definition typ_of (v:val) :=\n    match v with\n      | Vint _ => Tint\n      | Vfloat _ => Tfloat\n    end.\n  *)\n  Module ValEqDec <: EQUALITY_TYPE.\n    Definition t := Value.\n    Global Instance EqDec_t: EqDec Value.\n    Proof.\n      constructor. unfold Value.\n      apply ZEqDec.EqDec_t.\n    Qed.\n  End ValEqDec.\n\n\n\n  Definition valid_cell:= Cell_Id Num -> bool.\n\n\n  Definition eqA_valid_cell (mt1 mt2: valid_cell) := forall ci, mt1 ci = mt2 ci.\n\n  Lemma valid_cell_equiv: Equivalence eqA_valid_cell.\n  Proof.\n    prove_equiv; dintuition congruence.\n  Qed.\n\n  Instance EqA_mt : EqA valid_cell:=\n  { eqA := eqA_valid_cell;\n    eqAequiv := valid_cell_equiv}.\n\n\n  (* a memory is a mapping between Cell_Ids and Values *)\n  Definition Memory := Cell_Id Num -> option Value.\n\n\n  Implicit Type m: Memory.\n\n  Definition valid_cell_of (mem: Memory) ci :=\n    match mem ci with\n      | None => false\n      | Some _ => true\n    end.\n\n  Definition same_memory_layout mem1 mem2 := valid_cell_of mem1 ≡ valid_cell_of mem2.\n\n  Global Instance Equiv_smt: Equivalence same_memory_layout.\n  Proof.\n    prove_equiv; unfold same_memory_layout.\n    reflexivity. symmetry; auto.\n    intros * H H0. eapply transitivity; eauto.\n  Defined.\n\n\n  Definition read m ci:= m ci.\n\n  (* two memories with same layout are readable at the same locations *)\n\n(*  Lemma same_typ_of: forall mem1 mem2 ci, same_memory_layout mem1 mem2 ->\n    typ_of <$> mem1 ci = typ_of <$> mem2 ci.\n  Proof.\n    intros * H.\n    unfold same_memory_layout, mem_type_of in H.\n    simpl in *. auto.\n  Qed.*)\n\n  Lemma read_same_layout:\n    forall mem1 mem2 ci, same_memory_layout mem1 mem2 -> is_some (read mem1 ci) ->\n      is_some (read mem2 ci).\n  Proof.\n    unfold same_memory_layout, read, valid_cell_of.\n    intros * H. compute in H. specialize (H ci).\n    destruct (mem1 ci), (mem2 ci); intro; simpl in *;  auto.\n  Qed.\n\n\n  Definition write m ci v :=\n    if valid_cell_of m ci then\n      Some (fun ci' => if ci' == ci then Some v else m ci')\n    else\n      None.\n\n  (* you don't change the layout of a memory by writing in it *)\n\n  Lemma write_keep_layout:\n    forall mem1 mem2 ci v, write mem1 ci v = Some mem2 -> same_memory_layout mem1 mem2.\n  Proof.\n    unfold write, same_memory_layout.\n    intros mem1 mem2 ci v H.\n    simpl. intro ci'.\n    dest_if; simpl; clean.\n    unfold valid_cell_of in *; simpl in *.\n    dest==; subst; auto.\n  Qed.\n\n  Lemma write_same_layout:\n    forall mem1 mem2 ci v, same_memory_layout mem1 mem2 -> (is_some (write mem1 ci v) -> is_some (write mem2 ci v)).\n  Proof.\n    unfold same_memory_layout, write, valid_cell_of. compute.\n    intros mem1 mem2 ci v H.\n    specialize (H ci).\n    destruct (mem1 ci); destruct (mem2 ci); clean.\n  Qed.\n\n\n  Definition read_write m ci v : option Value :=\n    do m' <- write m ci v;\n    read m' ci.\n\n  Lemma rws: forall mem1 mem2 ci v,\n    same_memory_layout mem1 mem2 ->\n    read_write mem1 ci v = read_write mem2 ci v.\n  Proof.\n    unfold same_memory_layout, write, read, valid_cell_of. compute.\n    intros mem1 mem2 ci v H.\n    specialize (H ci).\n    destruct (mem1 ci); destruct (mem2 ci); clean.\n  Qed.\n\n  Lemma rwo: forall mem1 mem2 ci1 ci2 v, write mem1 ci1 v = Some mem2 -> ci1 <> ci2 ->\n    read mem2 ci2 = read mem1 ci2.\n  Proof.\n    unfold same_memory_layout, write, read, valid_cell_of. compute.\n    intros mem1 mem2 ci1 ci2 v H H0.\n    destruct (mem1 ci1); clean.\n  Qed.\n\nEnd BMem.\n\n(* build a complete memory from a base memory *)\nModule MEMORY (N:NUMERICAL) (BM: BASEMEM(N)).\n  Export BM.\n\n  (* two memories are equivalent if the map the same cells to the same values\n     and they have the same layout *)\n  Definition eqA_memory mem1 mem2 :=\n    same_memory_layout mem1 mem2 /\\\n    forall ci, read mem1 ci = read mem2 ci.\n\n  Lemma eqA_mem_equiv : Equivalence eqA_memory.\n  Proof.\n    prove_equiv; unfold eqA_memory; intros; split'.\n    Case \"Reflexivity\"; SCase \"left\". \n      reflexivity.\n    Case \"Reflexivity\"; SCase \"right\". \n      reflexivity.\n    Case \"Symmetry\"; SCase \"left\".\n      inv H. symmetry; auto.\n    Case \"Symmetry\"; SCase \"right\".\n      inv H; symmetry; auto.\n    Case \"Transitivity\"; SCase \"left\".\n      inv H; inv H0; etransitivity; eauto.\n      inv H; inv H0; etransitivity; eauto.\n  Qed.\n    \n\n\n  (* this gives us the notation ≡ *)\n  Global Instance EqA_memory : EqA Memory :=\n  { eqA := eqA_memory;\n    eqAequiv := eqA_mem_equiv}.\n\n  Lemma EqA_memory_unfold: forall mem1 mem2,\n    mem1 ≡ mem2 = (same_memory_layout mem1 mem2 /\\\n    forall ci, read mem1 ci = read mem2 ci).\n  Proof.\n    reflexivity.\n  Qed.\n\n  \n\n  Lemma use_EqA_memory_1: forall mem1 mem2,\n    mem1 ≡ mem2 -> forall ci, read mem1 ci = read mem2 ci.\n  Proof.\n    intros * [? ?]; auto.\n  Qed.\n\n  Lemma use_EqA_memory_2: forall mem1 mem2,\n    mem1 ≡ mem2 -> same_memory_layout mem1 mem2.\n  Proof.\n    intros * [? ?]; auto.\n  Qed.\n\n\n  (* we don't want EqA_memory to be unfold in general *)\n  Global Opaque EqA_memory.\n\n\n  Global Hint Resolve use_EqA_memory_1 use_EqA_memory_2 read_same_layout\n    write_keep_layout write_same_layout rws rwo: memory.\n\n  Lemma smt_refl: forall m, same_memory_layout m m.\n  Proof. reflexivity. Qed.\n\n  Lemma smt_sym: forall mem1 mem2, same_memory_layout mem1 mem2 -> same_memory_layout mem2 mem1.\n  Proof. symmetry. auto. Qed.\n\n  Lemma smt_trans: forall mem1 mem2 m3, same_memory_layout mem1 mem2 -> same_memory_layout mem2 m3 -> same_memory_layout mem1 m3.\n  Proof. etransitivity; eauto. Qed.\n\n  Global Hint Immediate smt_sym: memory.\n  Global Hint Resolve 5 smt_trans: memory.\n  Hint Extern 1 (same_memory_layout ?X ?X) => reflexivity: memory.\n\n\n  Ltac get_all_mem_layouts :=\n  option_on_right;\n  repeat\n  match goal with\n    | H: ?mem1 ≡ ?mem2 |- _ =>\n      match goal with\n        | H' : same_memory_layout mem1 mem2 |- _ => fail 1\n        | H' : same_memory_layout mem2 mem1 |- _ => fail 1\n        | |- _ =>\n          pose proof (use_EqA_memory_2 _ _ H)\n      end\n  end;\n  repeat\n  match goal with\n    | H: write ?mem1 _ _ = Some ?mem2 |- _ =>\n      match goal with\n        | H' : same_memory_layout mem1 mem2 |- _ => fail 1\n        | H' : same_memory_layout mem2 mem1 |- _ => fail 1\n        | |- _ =>\n          pose proof (write_keep_layout _ _ _ _ H)\n      end\n  end.\n\n\n  Definition owrite omem ci v: option Memory :=\n    do mem <- omem;\n    write mem ci v.\n\n  Lemma rws': forall mem1 mem2 mem1' mem2' ci v, same_memory_layout mem1 mem2 ->\n    write mem1 ci v = Some mem1' -> write mem2 ci v = Some mem2' ->\n    read mem1' ci = read mem2' ci.\n  Proof.\n    intros mem1 mem2 mem1' mem2' ci v H H0 H1. \n    pose proof (rws mem1 mem2 ci v H). compute in H2.\n    rewrite H0, H1 in H2. auto.\n  Qed.\n  Hint Resolve rws': memory.\n\n\n  Ltac check_diff x y :=\n    match goal with\n      | H : x <> y |- _ => idtac\n      | H : y <> x |- _  => idtac\n    end.\n\n  Ltac push_read_up :=\n  repeat\n  match goal with\n    | H: write ?mem1 ?ci1 ?v = Some ?mem2 |- context[read ?mem2 ?ci2] =>\n      check_diff ci1 ci2;\n      replace (read mem2 ci2) with (read mem1 ci2) by (symmetry; eapply rwo; eauto)\n  end.\n\n\n  Ltac solve_same_memory :=\n    repeat match goal with\n             | H : _ ≡ _ |- _ => apply use_EqA_memory_2 in H\n           end;\n    repeat match goal with\n             | H: write _ _ _ = Some _ |- _ =>\n               apply write_keep_layout in H; revert H\n             | H : same_memory_layout _ _ |- _ => revert H\n           end;\n    clear'; intros;\n    let rec aux := (* aux is used to backtrack *)\n    match goal with\n    | H: same_memory_layout ?m1 ?m2 |- same_memory_layout ?m1 ?m2\n      => apply H\n    | H: same_memory_layout ?m1 ?m2 |- same_memory_layout ?m1 ?m2\n      => symmetry; apply H\n    | H: same_memory_layout ?m1 _ |- same_memory_layout ?m1 _ =>\n      etransitivity; [eapply H| clear H; solve [aux]]\n    | H: same_memory_layout _ ?m1 |- same_memory_layout ?m1 _ =>\n      etransitivity; [symmetry; eapply H| clear H; solve [aux]]\n    end in solve [aux].\n\n\n  (* if two cells are differents, we can permut the write *)\n  Lemma permut_write: forall mem1 mem2 ci1 ci2 v1 v2, ci1 <> ci2 ->\n    mem1 ≡ mem2 ->\n    owrite (write mem1 ci1 v1) ci2 v2 ≡ owrite (write mem2 ci2 v2) ci1 v1.\n  Proof.\n    intros * DIFF EQUIV.\n    remember (write mem1 ci1 v1) as omem1.\n    remember (write mem2 ci2 v2) as omem2.\n    destruct' omem1 as [mem1'|]; destruct' omem2 as [mem2'|];\n    unfold owrite; prog_dos; prog_dos; clean; try reflexivity.\n\n    Case \"Some mem1'\"; SCase \"Some mem2'\".\n\n    repeat match goal with\n        | H: write ?M1 ?CI ?V = Some _|- context[write ?M2 ?CI ?V] =>\n          let HSOME := fresh in\n          let HSAME := fresh in\n            assert (is_some (write M2 CI V)) as HSOME by\n            (assert (same_memory_layout M1 M2) as HSAME by solve_same_memory;\n             eapply write_same_layout;[ eapply HSAME| instantiate; eauto]);\n            inv HSOME\n      end.\n    simpl; rewrite EqA_memory_unfold.\n    get_all_mem_layouts.\n\n    split'.\n    SSCase \"left\".\n      eauto with memory.\n    SSCase \"right\".\n      intro ci.\n      dest ci == ci1; dest ci == ci2; repeat (progress subst); auto;\n        push_read_up; eauto with memory.\n\n    Case \"Some mem1'\"; SCase \"None\". \n    simpl.\n    get_all_mem_layouts.\n    prog_match_option; auto.\n\n    assert (is_some (write mem ci2 v2)) by auto. symmetry in H0.\n    eapply (write_same_layout mem mem2) in H1.\n    rewrite Heqomem2 in H1. auto. etransitivity; eauto.\n\n    Case \"None\"; SCase \"Some mem2'\". \n    simpl.\n    get_all_mem_layouts.\n    case_eq (write mem2' ci1 v1); intros; auto.\n\n    assert (is_some (write mem2' ci1 v1)) by auto. \n    symmetry in H0. eapply (write_same_layout mem2' mem1) in H2.\n    rewrite Heqomem1 in H2. auto.\n    symmetry in H0. symmetry. etransitivity; eauto.\n  Qed.\n\nEnd MEMORY.\n\nModule ZBMem := BMem(ZNum).\nModule IntBMem := BMem(IntNum).\n\nModule Zmem := MEMORY(ZNum)(ZBMem).\nModule Intmem := MEMORY(IntNum)(IntBMem).\n\nModule BmemI2Z(BMI: BASEMEM(IntNum)) <: BASEMEM(ZNum).\n\n  (* values of the language *)\n  Definition Value:= BMI.Value.\n\n  (* memories *)\n  Definition Memory := BMI.Memory.\n  Implicit Type m: Memory.\n  Implicit Type ci: Cell_Id Z.\n\n  (* memories can be of \"same layout\", and it's an equivalence relation *)\n\n  Definition same_memory_layout : relation Memory := BMI.same_memory_layout.\n\n  Global Instance Equiv_smt: Equivalence same_memory_layout.\n  Proof.\n    unfold same_memory_layout.\n    apply BMI.Equiv_smt.\n  Qed.    \n\n  Definition read m ci : option Value :=\n    do ci' <- z2icell ci;\n    BMI.read m ci'.\n\n  (* two memories with same layout are readable at the same locations *)\n\n  Lemma read_same_layout:\n    forall mem1 mem2 ci, same_memory_layout mem1 mem2 ->\n      is_some (read mem1 ci) -> is_some (read mem2 ci).\n  Proof.\n    intros * SMT SOME.\n    unfold read in *.\n    monadInv SOME. simpl_do.\n    eapply BMI.read_same_layout; eauto.\n  Qed.\n\n  Definition write m ci v: option Memory :=\n    do ci' <- z2icell ci;\n    BMI.write m ci' v.\n\n  (* you don't change the layout of a memory by writing in it *)\n\n  Lemma write_keep_layout:\n    forall mem1 mem2 ci v, write mem1 ci v = Some mem2 -> same_memory_layout mem1 mem2.\n  Proof.\n    unfold write. intros * SOME.\n    monadInv SOME. eapply BMI.write_keep_layout; eauto.\n  Qed.\n\n  Lemma write_same_layout:\n    forall mem1 mem2 ci v, same_memory_layout mem1 mem2 -> (is_some (write mem1 ci v)\n      -> is_some (write mem2 ci v)).\n  Proof.\n    unfold write. intros * SMT SOME.\n    monadInv SOME. simpl_do. eapply BMI.write_same_layout; eauto.\n  Qed.\n\n\n\n  Definition read_write m ci v : option Value :=\n    do m' <- write m ci v;\n    read m' ci.\n\n\n  Lemma rws: forall mem1 mem2 ci v,\n    same_memory_layout mem1 mem2 ->\n    read_write mem1 ci v = read_write mem2 ci v.\n  Proof.\n    intros * SMT.\n    destruct (z2icell ci) as [ci'|] _eqn.\n    pose proof (BMI.rws mem1 mem2 ci' v SMT).\n    unfold BMI.read_write in H.\n    unfold read_write, read, write.\n    rewrite Heqo.\n    compute in H. compute. auto.\n\n    unfold read_write, read, write.\n    rewrite Heqo. simpl_do. reflexivity.\n  Qed.\n  Lemma inv_cons: forall A (a1 a2 :A) l1 l2,\n    tag_to_inv (a1 :: l1 = a2 :: l2).\n  Proof. auto. Qed.\n  Hint Rewrite inv_cons: opt_inv.\n\n  Lemma rwo: forall mem1 mem2 ci1 ci2 v, write mem1 ci1 v = Some mem2 -> ci1 <> ci2 ->\n    read mem2 ci2 = read mem1 ci2.\n  Proof.\n    unfold write, read.\n\n    intros * SOME DIFF.\n    monadInv SOME.\n    prog_dos.\n    eapply BMI.rwo; eauto.\n    intro. apply DIFF. subst.\n    erewrite <- z2i2zcell; eauto.\n    erewrite <- (z2i2zcell ci1); eauto.\n  Qed.\n\n\nEnd BmemI2Z.\n\n", "meta": {"author": "pilki", "repo": "s2sLoop", "sha": "821528456333c518788df2834c674e850d7e7291", "save_path": "github-repos/coq/pilki-s2sLoop", "path": "github-repos/coq/pilki-s2sLoop/s2sLoop-821528456333c518788df2834c674e850d7e7291/src/Memory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.23950804663043065}}
{"text": "(* begin hide *)\nFrom ITree Require Import\n     ITree\n     Basics.Monad\n     Events.StateFacts\n     Eq.Eqit.\n\nFrom Vellvm Require Import\n     Utilities\n     Syntax\n     Semantics.LLVMEvents\n     Semantics.Denotation\n     Handlers.Handlers.\n(* end hide *)\n\nSection InterpreterMCFG.\n\n  (**\n   Partial interpretations of the trees produced by the denotation of _VIR_ programs.\n   The intent is to allow us to only interpret as many layers as needed\n   to perform the required semantic reasoning, and lift for free the\n   equivalence down the pipe.\n   This gives us a _vertical_ notion of compositionality.\n   *)\n\n  Definition interp_mcfg1 {R} (t: itree L0 R) g :=\n    let uvalue_trace       := interp_intrinsics t in\n    let L1_trace           := interp_global uvalue_trace g in\n    L1_trace.\n\n  Definition interp_mcfg2 {R} (t: itree L0 R) g l :=\n    let uvalue_trace   := interp_intrinsics t in\n    let L1_trace       := interp_global uvalue_trace g in\n    let L2_trace       := interp_local_stack L1_trace l in\n    L2_trace.\n\n  Definition interp_mcfg3 {R} (t: itree L0 R) g l m :=\n    let uvalue_trace   := interp_intrinsics t in\n    let L1_trace       := interp_global uvalue_trace g in\n    let L2_trace       := interp_local_stack L1_trace l in\n    let L3_trace       := interp_memory L2_trace m in\n    L3_trace.\n\n  Definition interp_mcfg4 {R} RR (t: itree L0 R) g l m :=\n    let uvalue_trace   := interp_intrinsics t in\n    let L1_trace       := interp_global uvalue_trace g in\n    let L2_trace       := interp_local_stack L1_trace l in\n    let L3_trace       := interp_memory L2_trace m in\n    let L4_trace       := model_undef RR L3_trace in\n    L4_trace.\n\n  (* The interpreter stray away from the model starting from the fourth layer: we pick an arbitrary valid path of execution *)\n  Definition interp_mcfg4_exec {R} (t: itree L0 R) g l m :=\n    let uvalue_trace   := interp_intrinsics t in\n    let L1_trace       := interp_global uvalue_trace g in\n    let L2_trace       := interp_local_stack L1_trace l in\n    let L3_trace       := interp_memory L2_trace m in\n    let L4_trace       := exec_undef L3_trace in\n    L4_trace.\n\nEnd InterpreterMCFG.\n\nSection InterpreterCFG.\n\n  (**\n   Partial interpretations of the trees produced by the\n   denotation of cfg. They differ from the ones of Vellvm programs by\n   their event signature, as well as by the lack of a stack of local event.\n   The intent is to allow us to only interpret as many layers as needed\n   to perform the required semantic reasoning, and lift for free the\n   equivalence down the pipe.\n   This gives us a _vertical_ notion of compositionality.\n   *)\n\n  (**\n   NOTE: Can we avoid this duplication w.r.t. [interpi]?\n   *)\n\n  Definition interp_cfg1 {R} (t: itree instr_E R) (g: global_env) :=\n    let L0_trace       := interp_intrinsics t in\n    let L1_trace       := interp_global L0_trace g in\n    L1_trace.\n\n  Definition interp_cfg2 {R} (t: itree instr_E R) (g: global_env) (l: local_env) :=\n    let L0_trace       := interp_intrinsics t in\n    let L1_trace       := interp_global L0_trace g in\n    let L2_trace       := interp_local L1_trace l in\n    L2_trace.\n\n  Definition interp_cfg3 {R} (t: itree instr_E R) (g: global_env) (l: local_env) (m: memory_stack) :=\n    let L0_trace       := interp_intrinsics t in\n    let L1_trace       := interp_global L0_trace g in\n    let L2_trace       := interp_local L1_trace l in\n    let L3_trace       := interp_memory L2_trace m in\n    L3_trace.\n\n  Definition interp_cfg4 {R} RR (t: itree instr_E R) (g: global_env) (l: local_env) (m: memory_stack) :=\n    let L0_trace       := interp_intrinsics t in\n    let L1_trace       := interp_global L0_trace g in\n    let L2_trace       := interp_local L1_trace l in\n    let L3_trace       := interp_memory L2_trace m in\n    let L4_trace       := model_undef RR L3_trace in\n    L4_trace.\n\nEnd InterpreterCFG.\n\nModule D := Denotation Addr LLVMEvents.\nExport D.\n\nModule SemNotations.\n  \n  Notation ℑ1 := interp_cfg1. \n  Notation ℑ2 := interp_cfg2. \n  Notation ℑ3 := interp_cfg3. \n  Notation ℑ4 := interp_cfg4. \n  Notation ℑ  := interp_cfg4.\n\n  Notation ℑs1 := interp_mcfg1. \n  Notation ℑs2 := interp_mcfg2. \n  Notation ℑs3 := interp_mcfg3. \n  Notation ℑs4 := interp_mcfg4. \n  Notation ℑs  := interp_mcfg4.\n\n  Notation Ret1 g x     := (Ret (g,x)).\n  Notation Ret2 g l x   := (Ret (l,(g,x))).\n  Notation Ret3 g l m x := (Ret (m,(l,(g,x)))).\n\n  Notation \"⟦ e 'at?' t '⟧e'\" :=  (denote_exp t e).\n  Notation \"⟦ e 'at' t '⟧e'\" :=   (denote_exp (Some t) e).\n  Notation \"⟦ e '⟧e'\" :=          (denote_exp None e).\n  Notation \"⟦ e 'at?' t '⟧e3'\" := (ℑ3 (translate exp_to_instr ⟦ e at? t ⟧e)).\n  Notation \"⟦ e 'at' t '⟧e3'\" :=  (ℑ3 (translate exp_to_instr ⟦ e at t ⟧e)).\n  Notation \"⟦ e '⟧e3'\" :=         (ℑ3 (translate exp_to_instr ⟦ e ⟧e )).\n\n  Notation \"⟦ i '⟧i'\" :=        (denote_instr i).\n  Notation \"⟦ i '⟧i3'\" :=       (ℑ3 ⟦ i ⟧i).\n\n  Notation \"⟦ c '⟧c'\" :=          (denote_code c).\n  Notation \"⟦ c '⟧c3'\" :=         (ℑ3 ⟦ c ⟧c).\n\n  Notation \"⟦ t '⟧t'\" :=        (denote_terminator t).\n  Notation \"⟦ t '⟧t3'\" :=       (ℑ3 (translate exp_to_instr ⟦ t ⟧t)).\n\n  Notation \"⟦ phi '⟧Φ' from\"  := (denote_phi from phi) (at level 0, from at next level).\n  Notation \"⟦ phi '⟧Φ3' from\" := (ℑ3 (denote_phi from phi)) (at level 0, from at next level).\n\n  Notation \"⟦ phis '⟧Φs' from\"  := (denote_phis from phis) (at level 0, from at next level).\n  Notation \"⟦ phis '⟧Φs3' from\" := (ℑ3 (denote_phis from phis)) (at level 0, from at next level).\n\n  Notation \"⟦ bk '⟧b'\" :=  (denote_block bk).\n  Notation \"⟦ bk '⟧b3' id\" := (ℑ3 (⟦ bk ⟧b id)) (at level 0, id at next level).\n\n  Notation \"⟦ bks '⟧bs'\"  := (denote_ocfg bks).\n  Notation \"⟦ bks '⟧bs3' ids\" := (ℑ3 (denote_ocfg bks ids)) (at level 0, ids at next level).\n\n  Notation \"⟦ f '⟧cfg'\"  := (denote_cfg f).\n  Notation \"⟦ f '⟧cfg3'\" := (ℑ3 (denote_cfg f)).\n\n  Notation \"⟦ f '⟧f'\"  := (denote_function f).\n\n  Ltac intros3 := intros (? & ? & ? & ?).\n   \nEnd SemNotations.\n", "meta": {"author": "vellvm", "repo": "vellvm", "sha": "c9b7d6a283c4954b25bf7bcb1b1e54b92b62d699", "save_path": "github-repos/coq/vellvm-vellvm", "path": "github-repos/coq/vellvm-vellvm/vellvm-c9b7d6a283c4954b25bf7bcb1b1e54b92b62d699/src/coq/Semantics/InterpretationStack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2393748172682083}}
{"text": "Add Search Blacklist \"Private_\" \"_subproof\".\nSet Printing Depth 50.\nRemove Search Blacklist \"Private_\" \"_subproof\".\nAdd Search Blacklist \"Private_\" \"_subproof\".\nAdd LoadPath \"../..\".\nRequire Import BetaJulia.BasicPLDefs.Identifier.\nRequire Import BetaJulia.Sub0280a.BaseDefs.\nRequire Import BetaJulia.Sub0280a.BaseMatchProps.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nOpen Scope btjm.\nLemma cname_eq__decidable : forall n1 n2 : cname, Decidable.decidable (n1 = n2).\nProof.\n(intros n1 n2; destruct n1; destruct n2; (left; reflexivity) || (right; intros H; inversion H)).\nQed.\nDefinition sem_sub (t1 t2 : ty) := forall k : nat, ||-[ k][t1]<= [t2].\nNotation \"'||-' '[' t1 ']' '<=' '[' t2 ']'\" := (sem_sub t1 t2) (at level 50) : btjm_scope.\nLemma sem_sub__refint_eXrefX : ||- [TRef tint]<= [TExist vX (TRef tX)].\nProof.\n(intros k).\n(destruct k; intros w1; exists 1; intros v Hm).\n-\n(apply match_ty_ref__weak_inv in Hm).\n(destruct Hm as [t' Heq]; subst).\n(simpl).\nexists tint.\nconstructor.\n-\n(apply match_ty_ref__inv in Hm).\n(destruct Hm as [t' [Heq Href]]; subst).\n(simpl).\nexists t'.\n(split; intros w; exists w; tauto).\nQed.\nLemma sem_sub__eXrefX_eYrefY : ||- [TExist vX (TRef tX)]<= [TExist vY (TRef tY)].\nProof.\n(intros k; intros w1; exists w1; intros v Hm).\n(destruct w1).\n-\n(apply match_ty_exist__0_inv in Hm; contradiction).\n-\n(apply match_ty_exist__inv in Hm).\n(destruct Hm as [tx Hmx]).\n(apply match_ty_exist).\nexists tx.\nassumption.\nQed.\nLemma sem_sub_refeXrefX_eYrefY : ||- [TRef (TExist vX (TRef tX))]<= [TExist vY (TRef tY)].\nProof.\n(intros k w1).\nexists (S w1).\n(intros v Hm).\n(apply match_ty_exist).\nexists (TExist vX (TRef tX)).\nassumption.\nQed.\nLemma not_sem_sub__refint_refflt : ~ ||- [TRef tint]<= [TRef tflt].\nProof.\n(intros Hcontra).\nspecialize (Hcontra 1 0).\n(destruct Hcontra as [w2 Hcontra]).\n(assert (Hm : |-[ 1, 0] TRef tint <$ TRef tint) by (apply match_ty_value_type__reflexive; constructor)).\nspecialize (Hcontra _ Hm).\nclear Hm.\n(apply match_ty_ref__inv in Hcontra).\n(destruct Hcontra as [t' [Heq Hcontra]]).\n(inversion Heq; subst).\nclear Heq.\n(destruct Hcontra as [Hcontra _]).\n(assert (Hm : |-[ 0, 0] tint <$ tint) by (apply match_ty_value_type__reflexive; constructor)).\nspecialize (Hcontra 0).\n(destruct Hcontra as [w2' Hcontra]).\nspecialize (Hcontra _ Hm).\n(apply match_ty_cname__inv in Hcontra).\n(inversion Hcontra).\nQed.\nLemma sem_sub__eunion__unione : forall (X : id) (t1 t2 : ty), ||- [TExist X (TUnion t1 t2)]<= [TUnion (TExist X t1) (TExist X t2)].\nProof.\n(intros X t1 t2 k).\n(intros w1).\nexists w1.\n(intros v Hm).\n(destruct w1).\n-\n(apply match_ty_exist__0_inv in Hm).\ncontradiction.\n-\n(apply match_ty_exist__inv in Hm).\n(destruct Hm as [tx Hmx]).\n(simpl in Hmx).\n(apply match_ty_union__inv in Hmx).\n(destruct Hmx as [Hmx| Hmx]; [ apply match_ty_union_1 | apply match_ty_union_2 ]; apply match_ty_exist; exists tx; assumption).\nQed.\nLemma sem_sub__unione__eunion : forall (X : id) (t1 t2 : ty), ||- [TUnion (TExist X t1) (TExist X t2)]<= [TExist X (TUnion t1 t2)].\nProof.\n(intros X t1 t2 k).\n(intros w1).\nexists w1.\n(intros v Hm).\n(apply match_ty_union__inv in Hm).\n(destruct Hm as [Hm| Hm]).\n-\n(destruct w1).\n+\n(apply match_ty_exist__0_inv in Hm).\ncontradiction.\n+\n(apply match_ty_exist__inv in Hm).\n(destruct Hm as [tx Hmx]).\n(simpl in Hmx).\n(apply match_ty_exist).\nexists tx.\n(apply match_ty_union_1).\nassumption.\n-\n(destruct w1).\n+\n(apply match_ty_exist__0_inv in Hm).\ncontradiction.\n+\n(apply match_ty_exist__inv in Hm).\n(destruct Hm as [tx Hmx]).\n(simpl in Hmx).\n(apply match_ty_exist).\nexists tx.\n(apply match_ty_union_2).\nassumption.\nQed.\nLemma sem_sub__pair_exist_distr_1 : forall (X : id) (t1 t2 : ty), ||- [TPair (TExist X t1) t2]<= [TExist X (TPair t1 t2)].\nProof.\n(intros X t1 t2 k w1).\n(* Auto-generated comment: Succeeded. *)\n\n", "meta": {"author": "uwplse", "repo": "analytics-data", "sha": "64d3fccac3a25230d1adb59fcf1aded3f375029a", "save_path": "github-repos/coq/uwplse-analytics-data", "path": "github-repos/coq/uwplse-analytics-data/analytics-data-64d3fccac3a25230d1adb59fcf1aded3f375029a/diffs-annotated-fixed-2/7/user-7-session-108.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23937481080113598}}
{"text": "Class inhabited(A: Type): Type := mk_inhabited { default: A }.\nGlobal Arguments mk_inhabited {_} _.\nGlobal Hint Mode inhabited + : typeclass_instances.\n\nGlobal Hint Extern 1 (inhabited _) =>\n  simple refine (mk_inhabited _); constructor\n  : typeclass_instances.\n\nModule InhabitedTests.\n  Goal inhabited nat. typeclasses eauto. Abort.\n  Goal inhabited (list nat). typeclasses eauto. Abort.\n  Goal forall A, inhabited (option A). typeclasses eauto. Abort.\n\n  Inductive test_foo: Type :=\n  | C1(x: False)\n  | C2\n  | C3(x: False).\n\n  Goal inhabited test_foo. typeclasses eauto. Abort.\nEnd InhabitedTests.\n\n(* TODO move code below to specific files *)\n\nRequire Import coqutil.Word.Interface.\nGlobal Instance word_inhabited{width: BinInt.Z}{word: word.word width}: inhabited word :=\n  mk_inhabited (word.of_Z BinInt.Z0).\n\nRequire Import coqutil.Map.Interface.\nGlobal Instance map_inhabited{key value: Type}{map: map.map key value}: inhabited map :=\n  mk_inhabited map.empty.\n\nModule Option.\n  Definition force{A: Type}{i: inhabited A}(o: option A): A :=\n    match o with\n    | Some a => a\n    | None => default\n    end.\nEnd Option.\n", "meta": {"author": "mit-plv", "repo": "coqutil", "sha": "48eeef16cc9aa3a057d4a76207b88b34fd397e24", "save_path": "github-repos/coq/mit-plv-coqutil", "path": "github-repos/coq/mit-plv-coqutil/coqutil-48eeef16cc9aa3a057d4a76207b88b34fd397e24/src/coqutil/Datatypes/Inhabited.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23937481080113596}}
{"text": "(*\n * © 2020 Massachusetts Institute of Technology.\n * MIT Proprietary, Subject to FAR52.227-11 Patent Rights - Ownership by the Contractor (May 2014)\n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n     List.\n\nFrom SPICY Require Import\n     MyPrelude\n     AdversaryUniverse\n     Maps\n     ChMaps\n     Messages\n     Keys\n     Automation\n     Tactics\n     Simulation\n\n     ModelCheck.UniverseEqAutomation\n     ModelCheck.SafeProtocol\n     ModelCheck.ProtocolFunctions\n     ModelCheck.ProtocolAutomation.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations.\nImport RealWorld.RealWorldNotations.\n\nSet Implicit Arguments.\n\n(* User ids *)\nDefinition A   := 0.\nDefinition B   := 1.\n\nNotation owner  := {| IdealWorld.read := true; IdealWorld.write := true |}.\nNotation reader := {| IdealWorld.read := true; IdealWorld.write := false |}.\nNotation writer := {| IdealWorld.read := false; IdealWorld.write := true |}.\n\nSection IdealWorldDefs.\n  Import IdealWorld.\n\n  Definition mkiU\n             (cv : channels)\n             (perms__a perms__b : permissions)\n             (p__a p__b : cmd (Base Nat)) : universe Nat :=\n    {| channel_vector := cv;\n       users :=\n         $0\n          $+ (A,   {| perms := perms__a ; protocol := p__a |})\n          $+ (B,   {| perms := perms__b ; protocol := p__b |})\n    |}.\nEnd IdealWorldDefs.\n\nSection RealWorldDefs.\n  Import RealWorld.\n\n  Definition mkrUsr (ks : key_perms) (p : user_cmd (Base Nat)) :=\n    {| key_heap  := ks ;\n       protocol  := p ;\n       msg_heap  := [] ;\n       c_heap    := [] ;\n       from_nons := [] ;\n       sent_nons := [] ;\n       cur_nonce := 0\n    |}.\n\n  Definition mkrU\n             (gks : keys)\n             (keys__a keys__b : key_perms)\n             (p__a p__b : user_cmd (Base Nat)) (adv : user_data Unit) : universe Nat Unit :=\n    {| users :=\n         $0 $+ (A, mkrUsr keys__a p__a)\n            $+ (B, mkrUsr keys__b p__b)\n     ; adversary        := adv\n     ; all_ciphers      := $0\n     ; all_keys         := gks\n    |}.\nEnd RealWorldDefs.\n\n#[export] Hint Unfold mkrU mkrUsr : user_build.\n\nModule SignPingSendProtocol.\n\n  Section IW.\n    Import IdealWorld.\n\n    Notation CH__A2B := (Single 0).\n    Notation perms_CH__A2B := 0.\n\n    Definition PERMS__a := $0 $+ (perms_CH__A2B, {| read := true; write := true |}). (* writer *)\n    Definition PERMS__b := $0 $+ (perms_CH__A2B, {| read := true; write := false |}). (* reader *)\n\n    Definition ideal_univ_start :=\n      mkiU (#0 #+ (CH__A2B, [])) PERMS__a PERMS__b\n           (* user A *)\n           ( n <- Gen\n           ; _ <- Send (Content n) CH__A2B\n           ; Return n)\n\n           (* user B *)\n           ( m <- @Recv Nat CH__A2B\n           ; ret (extractContent m)).\n\n  End IW.\n\n  Section RW.\n    Import RealWorld.\n\n    Definition KID1 : key_identifier := 0.\n\n    Definition KEY1  := MkCryptoKey KID1 Signing AsymKey.\n    Definition KEYS  := $0 $+ (KID1, KEY1).\n\n    Definition A__keys := $0 $+ (KID1, true).\n    Definition B__keys := $0 $+ (KID1, false).\n\n    Definition real_univ_start :=\n      mkrU KEYS A__keys B__keys\n           (* user A *)\n           ( n  <- Gen\n           ; c  <- Sign KID1 B (message.Content n)\n           ; _  <- Send B c\n           ; Return n)\n\n           (* user B *)\n           ( c  <- @Recv Nat (Signed KID1 true)\n           ; v  <- Verify KID1 c\n           ; ret (if fst v\n                  then match snd v with\n                       | message.Content p => p\n                       | _                 => 0\n                       end\n                  else 1)).\n  \n  End RW.\n\n  #[export] Hint Unfold\n       A B KID1 KEY1 KEYS A__keys B__keys\n       PERMS__a PERMS__b\n       real_univ_start mkrU mkrUsr\n       ideal_univ_start mkiU : constants.\n  \n  Import SimulationAutomation.\n\n  #[export] Hint Extern 0 (IdealWorld.lstep_universe _ _ _) =>\n    progress(autounfold with constants; simpl) : core.\n\n  #[export] Hint Extern 1 (PERMS__a $? _ = _) => unfold PERMS__a : core.\n  #[export] Hint Extern 1 (PERMS__b $? _ = _) => unfold PERMS__b : core.\n\n  #[export] Hint Extern 1 (istepSilent ^* _ _) =>\n  autounfold with constants; simpl;\n    repeat (ideal_single_silent_multistep A);\n    repeat (ideal_single_silent_multistep B); solve_refl : core.\n  \nEnd SignPingSendProtocol.\n\nModule EncPingSendProtocol.\n\n  Section IW.\n    Import IdealWorld.\n\n    Definition CH__A2B : channel_id := Single 0.\n    Definition perms_CH__A2B := 0.\n\n    Definition PERMS__a := $0 $+ (perms_CH__A2B, {| read := false; write := true |}). (* writer *)\n    Definition PERMS__b := $0 $+ (perms_CH__A2B, {| read := true; write := false |}). (* reader *)\n\n    Definition ideal_univ_start :=\n      mkiU (#0 #+ (CH__A2B, [])) PERMS__a PERMS__b\n           (* user A *)\n           ( n <- Gen\n           ; _ <- Send (Content n) CH__A2B\n           ; Return n)\n\n           (* user B *)\n           ( m <- @Recv Nat CH__A2B\n           ; ret (extractContent m)).\n\n  End IW.\n\n  Section RW.\n    Import RealWorld.\n\n    Definition KID__A : key_identifier := 0.\n    Definition KID__B : key_identifier := 1.\n\n    Definition KEY__A  := MkCryptoKey KID__A Signing AsymKey.\n    Definition KEY__B := MkCryptoKey KID__B Encryption AsymKey.\n    Definition KEYS  := $0 $+ (KID__A, KEY__A) $+ (KID__B, KEY__B).\n\n    Definition A__keys := $0 $+ (KID__A, true) $+ (KID__B, false).\n    Definition B__keys := $0 $+ (KID__A, false) $+ (KID__B, true).\n\n    Definition real_univ_start :=\n      mkrU KEYS A__keys B__keys\n           (* user A *)\n           ( n  <- Gen\n           ; c  <- SignEncrypt KID__A KID__B B (message.Content n)\n           ; _  <- Send B c\n           ; Return n)\n\n           (* user B *)\n           ( c  <- @Recv Nat (SignedEncrypted KID__A KID__B true)\n           ; v  <- Decrypt c\n           ; ret (extractContent v)).\n  \n  End RW.\n\n  #[export] Hint Unfold\n       A B KID__A KID__B KEY__A KEY__B KEYS A__keys B__keys\n       PERMS__a PERMS__b\n       real_univ_start mkrU mkrUsr\n       ideal_univ_start mkiU : constants.\n  \n  Import SimulationAutomation.\n\n  #[export] Hint Extern 0 (IdealWorld.lstep_universe _ _ _) =>\n    progress(autounfold with constants; simpl) : core.\n\n  #[export] Hint Extern 1 (PERMS__a $? _ = _) => unfold PERMS__a : core.\n  #[export] Hint Extern 1 (PERMS__b $? _ = _) => unfold PERMS__b : core.\n\n  #[export] Hint Extern 1 (istepSilent ^* _ _) =>\n  autounfold with constants; simpl;\n    repeat (ideal_single_silent_multistep A);\n    repeat (ideal_single_silent_multistep B); solve_refl : core.\n  \nEnd EncPingSendProtocol.\n", "meta": {"author": "mit-ll", "repo": "SPICY", "sha": "ad89c31a093ed2e0b7b4ef55c87ec9b175749fe0", "save_path": "github-repos/coq/mit-ll-SPICY", "path": "github-repos/coq/mit-ll-SPICY/SPICY-ad89c31a093ed2e0b7b4ef55c87ec9b175749fe0/protocols/ExampleProtocols.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23937481080113596}}
{"text": "(****************************************************************************)\n(*                                                                          *)\n(*                                   Menhir                                 *)\n(*                                                                          *)\n(*           Jacques-Henri Jourdan, CNRS, LRI, Université Paris Sud         *)\n(*                                                                          *)\n(*  Copyright Inria. All rights reserved. This file is distributed under    *)\n(*  the terms of the GNU Lesser General Public License as published by the  *)\n(*  Free Software Foundation, either version 3 of the License, or (at your  *)\n(*  option) any later version, as described in the file LICENSE.            *)\n(*                                                                          *)\n(****************************************************************************)\n\nRequire Grammar.\nRequire Export Alphabet.\nFrom Coq Require Import Orders.\nFrom Coq Require Export List Syntax.\n\nModule Type AutInit.\n  (** The grammar of the automaton. **)\n  Declare Module Gram:Grammar.T.\n  Export Gram.\n\n  (** The set of non initial state is considered as an alphabet. **)\n  Parameter noninitstate : Type.\n  Global Declare Instance NonInitStateAlph : Alphabet noninitstate.\n\n  Parameter initstate : Type.\n  Global Declare Instance InitStateAlph : Alphabet initstate.\n\n  (** When we are at this state, we know that this symbol is the top of the\n     stack. **)\n  Parameter last_symb_of_non_init_state: noninitstate -> symbol.\nEnd AutInit.\n\nModule Types(Import Init:AutInit).\n  (** In many ways, the behaviour of the initial state is different from the\n     behaviour of the other states. So we have chosen to explicitaly separate\n     them: the user has to provide the type of non initial states. **)\n  Inductive state :=\n    | Init: initstate -> state\n    | Ninit: noninitstate -> state.\n\n  Global Program Instance StateAlph : Alphabet state :=\n    { AlphabetComparable := {| compare := fun x y =>\n        match x, y return comparison with\n          | Init _, Ninit _ => Lt\n          | Init x, Init y => compare x y\n          | Ninit _, Init _ => Gt\n          | Ninit x, Ninit y => compare x y\n        end |};\n      AlphabetFinite := {| all_list := map Init all_list ++ map Ninit all_list |} }.\n  Local Obligation Tactic := intros.\n  Next Obligation.\n  destruct x, y; intuition; apply compare_antisym.\n  Qed.\n  Next Obligation.\n  destruct x, y, z; intuition.\n  apply (compare_trans _ i0); intuition.\n  congruence.\n  congruence.\n  apply (compare_trans _ n0); intuition.\n  Qed.\n  Next Obligation.\n  intros x y.\n  destruct x, y; intuition; try discriminate.\n  rewrite (compare_eq i i0); intuition.\n  rewrite (compare_eq n n0); intuition.\n  Qed.\n  Next Obligation.\n  apply in_or_app; destruct x; intuition;\n    [left|right]; apply in_map; apply  all_list_forall.\n  Qed.\n\n  Coercion Ninit : noninitstate >-> state.\n  Coercion Init : initstate >-> state.\n\n  (** For an LR automaton, there are four kind of actions that can be done at a\n     given state:\n       - Shifting, that is reading a token and putting it into the stack,\n       - Reducing a production, that is popping the right hand side of the\n          production from the stack, and pushing the left hand side,\n       - Failing\n       - Accepting the word (special case of reduction)\n\n     As in the menhir parser generator, we do not want our parser to read after\n     the end of stream. That means that once the parser has read a word in the\n     grammar language, it should stop without peeking the input stream. So, for\n     the automaton to be complete, the grammar must be particular: if a word is\n     in its language, then it is not a prefix of an other word of the language\n     (otherwise, menhir reports an end of stream conflict).\n\n     As a consequence of that, there is two notions of action: the first one is\n     an action performed before having read the stream, the second one is after\n  **)\n\n  Inductive lookahead_action (term:terminal) :=\n  | Shift_act: forall s:noninitstate,\n                 T term = last_symb_of_non_init_state s -> lookahead_action term\n  | Reduce_act: production -> lookahead_action term\n  | Fail_act: lookahead_action term.\n  Arguments Shift_act {term}.\n  Arguments Reduce_act {term}.\n  Arguments Fail_act {term}.\n\n  Inductive action :=\n  | Default_reduce_act: production -> action\n  | Lookahead_act : (forall term:terminal, lookahead_action term) -> action.\n\n  (** Types used for the annotations of the automaton. **)\n\n  (** An item is a part of the annotations given to the validator.\n     It is acually a set of LR(1) items sharing the same core. It is needed\n     to validate completeness. **)\n  Record item := {\n  (** The pseudo-production of the item. **)\n    prod_item: production;\n\n  (** The position of the dot. **)\n    dot_pos_item: nat;\n\n  (** The lookahead symbol of the item. We are using a list, so we can store\n     together multiple LR(1) items sharing the same core. **)\n    lookaheads_item: list terminal\n  }.\nEnd Types.\n\nModule Type T.\n  Include AutInit <+ Types.\n  Module Export GramDefs := Grammar.Defs Gram.\n\n  (** For each initial state, the non terminal it recognizes. **)\n  Parameter start_nt: initstate -> nonterminal.\n\n  (** The action table maps a state to either a map terminal -> action. **)\n  Parameter action_table:\n    state -> action.\n  (** The goto table of an LR(1) automaton. **)\n  Parameter goto_table: state -> forall nt:nonterminal,\n    option { s:noninitstate | NT nt = last_symb_of_non_init_state s }.\n\n  (** Some annotations on the automaton to help the validation. **)\n\n  (** When we are at this state, we know that these symbols are just below\n     the top of the stack. The list is ordered such that the head correspond\n     to the (almost) top of the stack. **)\n  Parameter past_symb_of_non_init_state: noninitstate -> list symbol.\n\n  (** When we are at this state, the (strictly) previous states verify these\n     predicates. **)\n  Parameter past_state_of_non_init_state: noninitstate -> list (state -> bool).\n\n  (** The items of the state. **)\n  Parameter items_of_state: state -> list item.\n\n  (** The nullable predicate for non terminals :\n     true if and only if the symbol produces the empty string **)\n  Parameter nullable_nterm: nonterminal -> bool.\n\n  (** The first predicates for non terminals, symbols or words of symbols. A\n     terminal is in the returned list if, and only if the parameter produces a\n     word that begins with the given terminal **)\n  Parameter first_nterm: nonterminal -> list terminal.\nEnd T.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/MenhirLib/Automaton.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23937481080113596}}
{"text": "(* Lifts for packing *)\n\nFrom Coq Require Import Bool String List BinPos Compare_dec Lia Arith.\nRequire Import Equations.Prop.DepElim.\nFrom Equations Require Import Equations.\nFrom MetaCoq Require Import Ast utils Typing.\nFrom Translation\nRequire Import util Sorts SAst SLiftSubst Equality SCommon XTyping\n               Conversion ITyping ITypingLemmata ITypingAdmissible.\nImport ListNotations.\n\nSection Pack.\n\nContext `{Sort_notion : Sorts.notion}.\n\n(* In order to do things properly we need to extend the context heterogenously,\n   this is done by extending the context with packed triples\n   (x : A, y : B, e : heq A x B y).\n   We call Γm the mix of Γ1 and Γ2.\n   We also need to define correspond lifts.\n\n   If Γ, Γ1, Δ |- t : T then\n   Γ, Γm, Δ↑ |- llift #|Γm| #|Δ| t : llift #|Γm| #|Δ| T\n   If Γ, Γ2, Δ |- t : T then\n   Γ, Γm, Δ↑ |- rlift #|Γm| #|Δ| t : rlift #|Γm| #|Δ| T\n *)\n\nFixpoint llift γ δ (t:sterm)  : sterm :=\n  match t with\n  | sRel i =>\n    if i <? δ\n    then sRel i\n    else if i <? δ + γ\n         then sProjT1 (sRel i)\n         else sRel i\n  | sLambda na A B b =>\n    sLambda na (llift γ δ A) (llift γ (S δ) B) (llift γ (S δ) b)\n  | sApp u A B v =>\n    sApp (llift γ δ u) (llift γ δ A) (llift γ (S δ) B) (llift γ δ v)\n  | sProd na A B => sProd na (llift γ δ A) (llift γ (S δ) B)\n  | sSum na A B => sSum na (llift γ δ A) (llift γ (S δ) B)\n  | sPair A B u v =>\n    sPair (llift γ δ A) (llift γ (S δ) B) (llift γ δ u) (llift γ δ v)\n  | sPi1 A B p => sPi1 (llift γ δ A) (llift γ (S δ) B) (llift γ δ p)\n  | sPi2 A B p => sPi2 (llift γ δ A) (llift γ (S δ) B) (llift γ δ p)\n  | sEq A u v => sEq (llift γ δ A) (llift γ δ u) (llift γ δ v)\n  | sRefl A u => sRefl (llift γ δ A) (llift γ δ u)\n  | sJ A u P w v p =>\n    sJ (llift γ δ A)\n       (llift γ δ u)\n       (llift γ (S (S δ)) P)\n       (llift γ δ w)\n       (llift γ δ v)\n       (llift γ δ p)\n  | sTransport A B p t =>\n    sTransport (llift γ δ A) (llift γ δ B) (llift γ δ p) (llift γ δ t)\n  | sHeq A a B b =>\n    sHeq (llift γ δ A) (llift γ δ a) (llift γ δ B) (llift γ δ b)\n  | sHeqToEq p => sHeqToEq (llift γ δ p)\n  | sHeqRefl A a => sHeqRefl (llift γ δ A) (llift γ δ a)\n  | sHeqSym p => sHeqSym (llift γ δ p)\n  | sHeqTrans p q => sHeqTrans (llift γ δ p) (llift γ δ q)\n  | sHeqTransport p t => sHeqTransport (llift γ δ p) (llift γ δ t)\n  | sCongProd B1 B2 p q =>\n    sCongProd (llift γ (S δ) B1) (llift γ (S δ) B2)\n              (llift γ δ p) (llift γ (S δ) q)\n  | sCongLambda B1 B2 t1 t2 pA pB pt =>\n    sCongLambda (llift γ (S δ) B1) (llift γ (S δ) B2)\n                (llift γ (S δ) t1) (llift γ (S δ) t2)\n                (llift γ δ pA) (llift γ (S δ) pB) (llift γ (S δ) pt)\n  | sCongApp B1 B2 pu pA pB pv =>\n    sCongApp (llift γ (S δ) B1) (llift γ (S δ) B2)\n             (llift γ δ pu) (llift γ δ pA) (llift γ (S δ) pB) (llift γ δ pv)\n  | sCongSum B1 B2 p q =>\n    sCongSum (llift γ (S δ) B1) (llift γ (S δ) B2)\n             (llift γ δ p) (llift γ (S δ) q)\n  | sCongPair B1 B2 pA pB pu pv =>\n    sCongPair (llift γ (S δ) B1) (llift γ (S δ) B2)\n             (llift γ δ pA) (llift γ (S δ) pB)\n             (llift γ δ pu) (llift γ δ pv)\n  | sCongPi1 B1 B2 pA pB pp =>\n    sCongPi1 (llift γ (S δ) B1) (llift γ (S δ) B2)\n             (llift γ δ pA) (llift γ (S δ) pB) (llift γ δ pp)\n  | sCongPi2 B1 B2 pA pB pp =>\n    sCongPi2 (llift γ (S δ) B1) (llift γ (S δ) B2)\n             (llift γ δ pA) (llift γ (S δ) pB) (llift γ δ pp)\n  | sCongEq pA pu pv => sCongEq (llift γ δ pA) (llift γ δ pu) (llift γ δ pv)\n  | sCongRefl pA pu => sCongRefl (llift γ δ pA) (llift γ δ pu)\n  | sEqToHeq p => sEqToHeq (llift γ δ p)\n  | sHeqTypeEq A B p => sHeqTypeEq (llift γ δ A) (llift γ δ B) (llift γ δ p)\n  | sSort x => sSort x\n  | sPack A B => sPack (llift γ δ A) (llift γ δ B)\n  | sProjT1 x => sProjT1 (llift γ δ x)\n  | sProjT2 x => sProjT2 (llift γ δ x)\n  | sProjTe x => sProjTe (llift γ δ x)\n  | sAx id => sAx id\n  end.\n\nFixpoint rlift γ δ t : sterm :=\n  match t with\n  | sRel i =>\n    if i <? δ\n    then sRel i\n    else if i <? δ + γ\n         then sProjT2 (sRel i)\n         else sRel i\n  | sLambda na A B b =>\n    sLambda na (rlift γ δ A) (rlift γ (S δ) B) (rlift γ (S δ) b)\n  | sApp u A B v =>\n    sApp (rlift γ δ u) (rlift γ δ A) (rlift γ (S δ) B) (rlift γ δ v)\n  | sProd na A B => sProd na (rlift γ δ A) (rlift γ (S δ) B)\n  | sSum na A B => sSum na (rlift γ δ A) (rlift γ (S δ) B)\n  | sPair A B u v =>\n    sPair (rlift γ δ A) (rlift γ (S δ) B) (rlift γ δ u) (rlift γ δ v)\n  | sPi1 A B p => sPi1 (rlift γ δ A) (rlift γ (S δ) B) (rlift γ δ p)\n  | sPi2 A B p => sPi2 (rlift γ δ A) (rlift γ (S δ) B) (rlift γ δ p)\n  | sEq A u v => sEq (rlift γ δ A) (rlift γ δ u) (rlift γ δ v)\n  | sRefl A u => sRefl (rlift γ δ A) (rlift γ δ u)\n  | sJ A u P w v p =>\n    sJ (rlift γ δ A)\n       (rlift γ δ u)\n       (rlift γ (S (S δ)) P)\n       (rlift γ δ w)\n       (rlift γ δ v)\n       (rlift γ δ p)\n  | sTransport A B p t =>\n    sTransport (rlift γ δ A) (rlift γ δ B) (rlift γ δ p) (rlift γ δ t)\n  | sHeq A a B b =>\n    sHeq (rlift γ δ A) (rlift γ δ a) (rlift γ δ B) (rlift γ δ b)\n  | sHeqToEq p => sHeqToEq (rlift γ δ p)\n  | sHeqRefl A a => sHeqRefl (rlift γ δ A) (rlift γ δ a)\n  | sHeqSym p => sHeqSym (rlift γ δ p)\n  | sHeqTrans p q => sHeqTrans (rlift γ δ p) (rlift γ δ q)\n  | sHeqTransport p t => sHeqTransport (rlift γ δ p) (rlift γ δ t)\n  | sCongProd B1 B2 p q =>\n    sCongProd (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n              (rlift γ δ p) (rlift γ (S δ) q)\n  | sCongLambda B1 B2 t1 t2 pA pB pt =>\n    sCongLambda (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n                (rlift γ (S δ) t1) (rlift γ (S δ) t2)\n                (rlift γ δ pA) (rlift γ (S δ) pB) (rlift γ (S δ) pt)\n  | sCongSum B1 B2 p q =>\n    sCongSum (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n              (rlift γ δ p) (rlift γ (S δ) q)\n  | sCongPair B1 B2 pA pB pu pv =>\n    sCongPair (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n             (rlift γ δ pA) (rlift γ (S δ) pB)\n             (rlift γ δ pu) (rlift γ δ pv)\n  | sCongPi1 B1 B2 pA pB pp =>\n    sCongPi1 (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n             (rlift γ δ pA) (rlift γ (S δ) pB) (rlift γ δ pp)\n  | sCongPi2 B1 B2 pA pB pp =>\n    sCongPi2 (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n             (rlift γ δ pA) (rlift γ (S δ) pB) (rlift γ δ pp)\n  | sCongApp B1 B2 pu pA pB pv =>\n    sCongApp (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n             (rlift γ δ pu) (rlift γ δ pA) (rlift γ (S δ) pB) (rlift γ δ pv)\n  | sCongEq pA pu pv => sCongEq (rlift γ δ pA) (rlift γ δ pu) (rlift γ δ pv)\n  | sCongRefl pA pu => sCongRefl (rlift γ δ pA) (rlift γ δ pu)\n  | sEqToHeq p => sEqToHeq (rlift γ δ p)\n  | sHeqTypeEq A B p => sHeqTypeEq (rlift γ δ A) (rlift γ δ B) (rlift γ δ p)\n  | sSort x => sSort x\n  | sPack A B => sPack (rlift γ δ A) (rlift γ δ B)\n  | sProjT1 x => sProjT1 (rlift γ δ x)\n  | sProjT2 x => sProjT2 (rlift γ δ x)\n  | sProjTe x => sProjTe (rlift γ δ x)\n  | sAx id => sAx id\n  end.\n\nEnd Pack.\n\nNotation llift0 γ t := (llift γ 0 t).\nNotation rlift0 γ t := (rlift γ 0 t).\n\nSection Mix.\n\nContext `{Sort_notion : Sorts.notion}.\n\nInductive ismix Σ Γ : forall (Γ1 Γ2 Γm : scontext), Type :=\n| mixnil : ismix Σ Γ [] [] []\n| mixsnoc Γ1 Γ2 Γm s A1 A2 :\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γ1 |-i A1 : sSort s ->\n    Σ ;;; Γ ,,, Γ2 |-i A2 : sSort s ->\n    ismix Σ Γ\n          (Γ1 ,, A1)\n          (Γ2 ,, A2)\n          (Γm ,, (sPack (llift0 #|Γm| A1) (rlift0 #|Γm| A2)))\n.\n\nFact mix_length1 :\n  forall {Σ Γ Γ1 Γ2 Γm},\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    #|Γm| = #|Γ1|.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hm.\n  dependent induction hm.\n  - cbn. reflexivity.\n  - cbn. f_equal. assumption.\nDefined.\n\nFact mix_length2 :\n  forall {Σ Γ Γ1 Γ2 Γm},\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    #|Γm| = #|Γ2|.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hm.\n  dependent induction hm.\n  - cbn. reflexivity.\n  - cbn. f_equal. assumption.\nDefined.\n\nFact safe_nth_mix :\n  forall {Σ} {Γ Γ1 Γ2 Γm : scontext},\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    forall {n isdecl isdecl1 isdecl2},\n      safe_nth Γm (exist _ n isdecl) =\n      sPack (llift0 (#|Γm| - S n)\n                    (safe_nth Γ1 (exist _ n isdecl1)))\n            (rlift0 (#|Γm| - S n)\n                    (safe_nth Γ2 (exist _ n isdecl2))).\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hm.\n  dependent induction hm.\n  - cbn. easy.\n  - intro n. destruct n ; intros isdecl isdecl1 isdecl2.\n    + cbn. replace (#|Γm| - 0) with #|Γm| by mylia. reflexivity.\n    + cbn. erewrite IHhm. reflexivity.\nDefined.\n\nLemma llift00 :\n  forall {t δ}, llift 0 δ t = t.\nProof.\n  intro t.\n  induction t ; intro δ.\n  all: try (cbn ; f_equal ; easy).\n  cbn. case_eq δ.\n  + intro h. cbn. f_equal.\n  + intros m h. case_eq (n <=? m).\n    * intro. reflexivity.\n    * intro nlm. cbn.\n      replace (m+0)%nat with m by mylia.\n      rewrite nlm. f_equal.\nDefined.\n\nLemma rlift00 :\n  forall {t δ}, rlift 0 δ t = t.\nProof.\n  intro t.\n  induction t ; intro δ.\n  all: try (cbn ; f_equal ; easy).\n  cbn. case_eq δ.\n  + intro h. cbn. f_equal.\n  + intros m h. case_eq (n <=? m).\n    * intro. reflexivity.\n    * intro nlm. cbn.\n      replace (m+0)%nat with m by mylia.\n      rewrite nlm. f_equal.\nDefined.\n\nLemma lift_llift :\n  forall {t i j k},\n    lift i k (llift j k t) = llift (i+j) k (lift i k t).\nProof.\n  intro t. induction t ; intros i j k.\n  all: try (cbn ; f_equal ; easy).\n  unfold llift at 1. case_eq (n <? k) ; intro e ; bprop e.\n  - unfold lift. case_eq (k <=? n) ; intro e1 ; bprop e1 ; try mylia.\n    unfold llift. rewrite e. reflexivity.\n  - case_eq (n <? k + j) ; intro e1 ; bprop e1.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift. case_eq (i + n <? k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + (i+j)) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift. case_eq (i + n <? k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + (i + j)) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_llift' :\n  forall {t i j k},\n    lift i k (llift j k t) = llift j (k+i) (lift i k t).\nProof.\n  intro t. induction t ; intros i j k.\n  all: try (cbn ; f_equal ;\n            try replace (S (S (k + i))) with ((S (S k)) + i)%nat by mylia ;\n            try replace (S (k + i)) with ((S k) + i)%nat by mylia ;\n            easy).\n  unfold llift at 1. case_eq (n <? k) ; intro e ; bprop e.\n  - unfold lift. case_eq (k <=? n) ; intro e1 ; bprop e1 ; try mylia.\n    unfold llift. case_eq (n <? k + i) ; intro e3 ; bprop e3 ; try mylia.\n    reflexivity.\n  - case_eq (n <? k + j) ; intro e1 ; bprop e1.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift.\n      case_eq (i + n <? k + i) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + i + j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift.\n      case_eq (i + n <? k + i) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + i + j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_llift3 :\n  forall {t i j k l},\n    l <= k ->\n    lift i l (llift j k t) = llift j (i+k) (lift i l t).\nProof.\n  intro t. induction t ; intros i j k l h.\n  all: try (cbn ; f_equal ;\n            try replace (S (S (i + k))) with (i + (S (S k)))%nat by mylia ;\n            try replace (S (i + k)) with (i + (S k))%nat by mylia ;\n            easy).\n  unfold llift at 1.\n  case_eq (n <? k) ; intro e ; bprop e.\n  - cbn. case_eq (l <=? n) ; intro e1 ; bprop e1.\n    + unfold llift. case_eq (i + n <? i + k) ; intro e3 ; bprop e3 ; try mylia.\n      reflexivity.\n    + unfold llift. case_eq (n <? i + k) ; intro e3 ; bprop e3 ; try mylia.\n      reflexivity.\n  - case_eq (n <? k + j) ; intro e1 ; bprop e1.\n    + cbn. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift.\n      case_eq (i + n <? i + k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? i + k + j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + cbn. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift. case_eq (i+n <? i+k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i+n <? i+k+j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_llift4 :\n  forall {t i j k l},\n    k < i ->\n    i <= k + j ->\n    lift i l (llift (j - (i - k)) l t) = llift j (k+l) (lift i l t).\nProof.\n  intro t. induction t ; intros i j k l h1 h2.\n  all: try (cbn ; f_equal ;\n            try replace (S (S (k + l))) with (k + (S (S l)))%nat by mylia ;\n            try replace (S (k + l)) with (k + (S l))%nat by mylia ;\n            easy).\n  unfold llift at 1.\n  case_eq (n <? l) ; intro e ; bprop e ; try mylia.\n  - unfold lift. case_eq (l <=? n) ; intro e1 ; bprop e1 ; try mylia.\n    unfold llift. case_eq (n <? k + l) ; intro e3 ; bprop e3 ; try mylia.\n    reflexivity.\n  - case_eq (n <? l + (j - (i - k))) ; intro e1 ; bprop e1 ; try mylia.\n    + unfold lift. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift. case_eq (i+n <? k+l) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i+n <? k+l+j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + unfold lift. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift. case_eq (i+n <? k+l) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i+n <? k+l+j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_llift5 :\n  forall {t i j k l},\n    j + k <= i + l ->\n    l <= k ->\n    llift j k (lift i l t) = lift i l t.\nProof.\n  intro t. induction t ; intros i j k l h1 h2.\n  all: try (cbn ; f_equal ; easy).\n  unfold lift. case_eq (l <=? n) ; intro e ; bprop e.\n  - unfold llift. case_eq (i+n <? k) ; intro e1 ; bprop e1 ; try mylia.\n    case_eq (i+n <? k+j) ; intro e3 ; bprop e3 ; try mylia.\n    reflexivity.\n  - unfold llift. case_eq (n <? k) ; intro e1 ; bprop e1 ; try mylia.\n    reflexivity.\nDefined.\n\nLemma lift_rlift :\n  forall {t i j k},\n    lift i k (rlift j k t) = rlift (i+j) k (lift i k t).\nProof.\n  intro t. induction t ; intros i j k.\n  all: try (cbn ; f_equal ; easy).\n  unfold rlift at 1. case_eq (n <? k) ; intro e ; bprop e.\n  - unfold lift. case_eq (k <=? n) ; intro e1 ; bprop e1 ; try mylia.\n    unfold rlift. rewrite e. reflexivity.\n  - case_eq (n <? k + j) ; intro e1 ; bprop e1.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift. case_eq (i + n <? k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + (i+j)) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift. case_eq (i + n <? k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + (i + j)) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_rlift' :\n  forall {t i j k},\n    lift i k (rlift j k t) = rlift j (k+i) (lift i k t).\nProof.\n  intro t. induction t ; intros i j k.\n  all: try (cbn ; f_equal ;\n            try replace (S (S (k + i))) with ((S (S k)) + i)%nat by mylia ;\n            try replace (S (k + i)) with ((S k) + i)%nat by mylia ;\n            easy).\n  unfold rlift at 1. case_eq (n <? k) ; intro e ; bprop e.\n  - unfold lift. case_eq (k <=? n) ; intro e1 ; bprop e1 ; try mylia.\n    unfold rlift. case_eq (n <? k + i) ; intro e3 ; bprop e3 ; try mylia.\n    reflexivity.\n  - case_eq (n <? k + j) ; intro e1 ; bprop e1.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift.\n      case_eq (i + n <? k + i) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + i + j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift.\n      case_eq (i + n <? k + i) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + i + j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_rlift3 :\n  forall {t i j k l},\n    l <= k ->\n    lift i l (rlift j k t) = rlift j (i+k) (lift i l t).\nProof.\n  intro t. induction t ; intros i j k l h.\n  all: try (cbn ; f_equal ;\n            try replace (S (S (i + k))) with (i + (S (S k)))%nat by mylia ;\n            try replace (S (i + k)) with (i + (S k))%nat by mylia ;\n            easy).\n  unfold rlift at 1.\n  case_eq (n <? k) ; intro e ; bprop e.\n  - cbn. case_eq (l <=? n) ; intro e1 ; bprop e1.\n    + unfold rlift. case_eq (i + n <? i + k) ; intro e3 ; bprop e3 ; try mylia.\n      reflexivity.\n    + unfold rlift. case_eq (n <? i + k) ; intro e3 ; bprop e3 ; try mylia.\n      reflexivity.\n  - case_eq (n <? k + j) ; intro e1 ; bprop e1.\n    + cbn. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift.\n      case_eq (i + n <? i + k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? i + k + j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + cbn. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift. case_eq (i+n <? i+k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i+n <? i+k+j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_rlift4 :\n  forall {t i j k l},\n    k < i ->\n    i <= k + j ->\n    lift i l (rlift (j - (i - k)) l t) = rlift j (k+l) (lift i l t).\nProof.\n  intro t. induction t ; intros i j k l h1 h2.\n  all: try (cbn ; f_equal ;\n            try replace (S (S (k + l))) with (k + (S (S l)))%nat by mylia ;\n            try replace (S (k + l)) with (k + (S l))%nat by mylia ;\n            easy).\n  unfold rlift at 1.\n  case_eq (n <? l) ; intro e ; bprop e ; try mylia.\n  - unfold lift. case_eq (l <=? n) ; intro e1 ; bprop e1 ; try mylia.\n    unfold rlift. case_eq (n <? k + l) ; intro e3 ; bprop e3 ; try mylia.\n    reflexivity.\n  - case_eq (n <? l + (j - (i - k))) ; intro e1 ; bprop e1 ; try mylia.\n    + unfold lift. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift. case_eq (i+n <? k+l) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i+n <? k+l+j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + unfold lift. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift. case_eq (i+n <? k+l) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i+n <? k+l+j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_rlift5 :\n  forall {t i j k l},\n    j + k <= i + l ->\n    l <= k ->\n    rlift j k (lift i l t) = lift i l t.\nProof.\n  intro t. induction t ; intros i j k l h1 h2.\n  all: try (cbn ; f_equal ; easy).\n  unfold lift. case_eq (l <=? n) ; intro e ; bprop e.\n  - unfold rlift. case_eq (i+n <? k) ; intro e1 ; bprop e1 ; try mylia.\n    case_eq (i+n <? k+j) ; intro e3 ; bprop e3 ; try mylia.\n    reflexivity.\n  - unfold rlift. case_eq (n <? k) ; intro e1 ; bprop e1 ; try mylia.\n    reflexivity.\nDefined.\n\nFixpoint llift_context n (Δ : scontext) : scontext :=\n  match Δ with\n  | nil => nil\n  | A :: Δ => (llift n #|Δ| A) :: (llift_context n Δ)\n  end.\n\nFact llift_context_length :\n  forall {n Δ}, #|llift_context n Δ| = #|Δ|.\nProof.\n  intros n Δ.\n  induction Δ.\n  - cbn. reflexivity.\n  - cbn. f_equal. assumption.\nDefined.\n\nFact llift_context0 :\n  forall {Γ}, llift_context 0 Γ = Γ.\nProof.\n  intro Γ. induction Γ.\n  - reflexivity.\n  - cbn. rewrite llift00. rewrite IHΓ. reflexivity.\nDefined.\n\nFixpoint rlift_context n (Δ : scontext) : scontext :=\n  match Δ with\n  | nil => nil\n  | A :: Δ => (rlift n #|Δ| A) :: (rlift_context n Δ)\n  end.\n\nFact rlift_context_length :\n  forall {n Δ}, #|rlift_context n Δ| = #|Δ|.\nProof.\n  intros n Δ.\n  induction Δ.\n  - cbn. reflexivity.\n  - cbn. f_equal. assumption.\nDefined.\n\nFact rlift_context0 :\n  forall {Γ}, rlift_context 0 Γ = Γ.\nProof.\n  intro Γ. induction Γ.\n  - reflexivity.\n  - cbn. rewrite rlift00. rewrite IHΓ. reflexivity.\nDefined.\n\n(* We introduce an alternate version of ismix that will be implied by ismix but\n   will be used as an intermediary for the proof.\n *)\nInductive ismix' Σ Γ : forall (Γ1 Γ2 Γm : scontext), Type :=\n| mixnil' : ismix' Σ Γ [] [] []\n| mixsnoc' Γ1 Γ2 Γm s A1 A2 :\n    ismix' Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm |-i llift0 #|Γm| A1 : sSort s ->\n    Σ ;;; Γ ,,, Γm |-i rlift0 #|Γm|A2 : sSort s ->\n    ismix' Σ Γ\n          (Γ1 ,, A1)\n          (Γ2 ,, A2)\n          (Γm ,, (sPack (llift0 #|Γm| A1) (rlift0 #|Γm| A2)))\n.\n\nLemma wf_mix {Σ Γ Γ1 Γ2 Γm} (h : wf Σ Γ) :\n  ismix' Σ Γ Γ1 Γ2 Γm ->\n  wf Σ (Γ ,,, Γm).\nProof.\n  intro hm. induction hm.\n  - cbn. assumption.\n  - cbn. econstructor.\n    + assumption.\n    + eapply type_Pack with (s0 := s) ; assumption.\nDefined.\n\nFact mix'_length1 :\n  forall {Σ Γ Γ1 Γ2 Γm},\n    ismix' Σ Γ Γ1 Γ2 Γm ->\n    #|Γm| = #|Γ1|.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hm.\n  dependent induction hm.\n  - cbn. reflexivity.\n  - cbn. f_equal. assumption.\nDefined.\n\nFact mix'_length2 :\n  forall {Σ Γ Γ1 Γ2 Γm},\n    ismix' Σ Γ Γ1 Γ2 Γm ->\n    #|Γm| = #|Γ2|.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hm.\n  dependent induction hm.\n  - cbn. reflexivity.\n  - cbn. f_equal. assumption.\nDefined.\n\nFact safe_nth_mix' :\n  forall {Σ} {Γ Γ1 Γ2 Γm : scontext},\n    ismix' Σ Γ Γ1 Γ2 Γm ->\n    forall {n isdecl isdecl1 isdecl2},\n      (safe_nth Γm (exist _ n isdecl)) =\n      sPack (llift0 (#|Γm| - S n)\n                    (safe_nth Γ1 (exist _ n isdecl1)))\n            (rlift0 (#|Γm| - S n)\n                    (safe_nth Γ2 (exist _ n isdecl2))).\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hm.\n  dependent induction hm.\n  - cbn. easy.\n  - intro n. destruct n ; intros isdecl isdecl1 isdecl2.\n    + cbn. replace (#|Γm| - 0) with #|Γm| by mylia. reflexivity.\n    + cbn. erewrite IHhm. reflexivity.\nDefined.\n\nDefinition llift_subst :\n  forall (u t : sterm) (i j m : nat),\n    llift j (i+m) (u {m := t}) = (llift j (S i+m) u) {m := llift j i t}.\nProof.\n  induction u ; intros t i j m.\n  all: try (cbn ; f_equal;\n            try replace (S (S (S (j + m))))%nat with (j + (S (S (S m))))%nat by mylia ;\n            try replace (S (S (j + m)))%nat with (j + (S (S m)))%nat by mylia ;\n            try replace (S (j + m))%nat with (j + (S m))%nat by mylia ;\n            try replace (S (S (S (i + m))))%nat with (i + (S (S (S m))))%nat by mylia ;\n            try replace (S (S (i + m)))%nat with (i + (S (S m)))%nat by mylia ;\n            try replace (S (i + m))%nat with (i + (S m))%nat by mylia;\n            try  (rewrite IHu; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu1; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu2; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu3; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu4; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu5; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu6; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu7; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu8; cbn; repeat f_equal; mylia)).\n  case_eq (m ?= n) ; intro e ; bprop e.\n  - subst. case_eq (n <=? i + n) ; intro e1 ; bprop e1 ; try mylia.\n    cbn. rewrite e. rewrite lift_llift3 by mylia.\n    f_equal. mylia.\n  - case_eq (n <=? i + m) ; intro e1 ; bprop e1.\n    + unfold llift at 1.\n      case_eq (Init.Nat.pred n <? i + m) ; intro e3 ; bprop e3 ; try mylia.\n      cbn. rewrite e. reflexivity.\n    + case_eq (n <=? i+m+j) ; intro e3 ; bprop e3.\n      * unfold llift at 1.\n        case_eq (Init.Nat.pred n <? i + m) ; intro e5 ; bprop e5 ; try mylia.\n        case_eq (Init.Nat.pred n <? i+m+j) ; intro e7 ; bprop e7 ; try mylia.\n        cbn. rewrite e. reflexivity.\n      * unfold llift at 1.\n        case_eq (Init.Nat.pred n <? i + m) ; intro e5 ; bprop e5 ; try mylia.\n        case_eq (Init.Nat.pred n <? i+m+j) ; intro e7 ; bprop e7 ; try mylia.\n        cbn. rewrite e. reflexivity.\n  - case_eq (n <=? i+m) ; intro e1 ; bprop e1 ; try mylia.\n    unfold llift at 1.\n    case_eq (n <? i+m) ; intro e3 ; bprop e3 ; try mylia.\n    cbn. rewrite e. reflexivity.\nDefined.\n\nDefinition rlift_subst :\n  forall (u t : sterm) (i j m : nat),\n    rlift j (i+m) (u {m := t}) = (rlift j (S i+m) u) {m := rlift j i t}.\nProof.\n  induction u ; intros t i j m.\n  all: try (cbn ; f_equal;\n            try replace (S (S (S (j + m))))%nat with (j + (S (S (S m))))%nat by mylia ;\n            try replace (S (S (j + m)))%nat with (j + (S (S m)))%nat by mylia ;\n            try replace (S (j + m))%nat with (j + (S m))%nat by mylia ;\n            try replace (S (S (S (i + m))))%nat with (i + (S (S (S m))))%nat by mylia ;\n            try replace (S (S (i + m)))%nat with (i + (S (S m)))%nat by mylia ;\n            try replace (S (i + m))%nat with (i + (S m))%nat by mylia;\n            try  (rewrite IHu; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu1; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu2; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu3; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu4; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu5; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu6; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu7; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu8; cbn; repeat f_equal; mylia)).\n  case_eq (m ?= n) ; intro e ; bprop e.\n  - subst. case_eq (n <=? i + n) ; intro e1 ; bprop e1 ; try mylia.\n    cbn. rewrite e. rewrite lift_rlift3 by mylia.\n    f_equal. mylia.\n  - case_eq (n <=? i + m) ; intro e1 ; bprop e1.\n    + unfold rlift at 1.\n      case_eq (Init.Nat.pred n <? i + m) ; intro e3 ; bprop e3 ; try mylia.\n      cbn. rewrite e. reflexivity.\n    + case_eq (n <=? i+m+j) ; intro e3 ; bprop e3.\n      * unfold rlift at 1.\n        case_eq (Init.Nat.pred n <? i + m) ; intro e5 ; bprop e5 ; try mylia.\n        case_eq (Init.Nat.pred n <? i+m+j) ; intro e7 ; bprop e7 ; try mylia.\n        cbn. rewrite e. reflexivity.\n      * unfold rlift at 1.\n        case_eq (Init.Nat.pred n <? i + m) ; intro e5 ; bprop e5 ; try mylia.\n        case_eq (Init.Nat.pred n <? i+m+j) ; intro e7 ; bprop e7 ; try mylia.\n        cbn. rewrite e. reflexivity.\n  - case_eq (n <=? i+m) ; intro e1 ; bprop e1 ; try mylia.\n    unfold rlift at 1.\n    case_eq (n <? i+m) ; intro e3 ; bprop e3 ; try mylia.\n    cbn. rewrite e. reflexivity.\nDefined.\n\nFact safe_nth_llift :\n  forall {Δ Γm : scontext} {n is1 is2},\n    safe_nth (llift_context #|Γm| Δ) (exist _ n is1) =\n    llift #|Γm| (#|Δ| - S n) (safe_nth Δ (exist _ n is2)).\nProof.\n  intro Δ. induction Δ.\n  - cbn. easy.\n  - intro Γm. destruct n ; intros is1 is2.\n    + cbn. replace (#|Δ| - 0) with #|Δ| by mylia. reflexivity.\n    + cbn. erewrite IHΔ. reflexivity.\nDefined.\n\nFact safe_nth_rlift :\n  forall {Δ Γm : scontext} {n is1 is2},\n    safe_nth (rlift_context #|Γm| Δ) (exist _ n is1) =\n    rlift #|Γm| (#|Δ| - S n) (safe_nth Δ (exist _ n is2)).\nProof.\n  intro Δ. induction Δ.\n  - cbn. easy.\n  - intro Γm. destruct n ; intros is1 is2.\n    + cbn. replace (#|Δ| - 0) with #|Δ| by mylia. reflexivity.\n    + cbn. erewrite IHΔ. reflexivity.\nDefined.\n\n(* Should be somewhere else. *)\nLemma inversion_wf_cat :\n  forall {Σ Δ Γ},\n    wf Σ (Γ ,,, Δ) ->\n    wf Σ Γ.\nProof.\n  intros Σ Δ. induction Δ ; intros Γ h.\n  - assumption.\n  - dependent destruction h.\n    apply IHΔ. assumption.\nDefined.\n\nFact nil_eq_cat :\n  forall {Δ Γ},\n    [] = Γ ,,, Δ ->\n    ([] = Γ) * ([] = Δ).\nProof.\n  intro Δ ; destruct Δ ; intros Γ e.\n  - rewrite cat_nil in e. split ; easy.\n  - cbn in e. inversion e.\nDefined.\n\n(* llift/rlift and closedness *)\n\nFact closed_above_llift_id :\n  forall t n k l,\n    closed_above l t = true ->\n    k >= l ->\n    llift n k t = t.\nProof.\n  intro t. induction t ; intros m k l clo h.\n  all: try (cbn ; cbn in clo ; repeat destruct_andb ;\n            repeat erewrite_close_above_lift_id ;\n            reflexivity).\n  unfold closed in clo. unfold closed_above in clo.\n  bprop clo. unfold llift.\n  case_eq (n <? k) ; intro e ; bprop e ; try mylia.\n  reflexivity.\nDefined.\n\nFact closed_llift :\n  forall t n k,\n    closed t ->\n    llift n k t = t.\nProof.\n  intros t n k h.\n  unfold closed in h.\n  eapply closed_above_llift_id.\n  - eassumption.\n  - mylia.\nDefined.\n\nFact closed_above_rlift_id :\n  forall t n k l,\n    closed_above l t = true ->\n    k >= l ->\n    rlift n k t = t.\nProof.\n  intro t. induction t ; intros m k l clo h.\n  all: try (cbn ; cbn in clo ; repeat destruct_andb ;\n            repeat erewrite_close_above_lift_id ;\n            reflexivity).\n  unfold closed in clo. unfold closed_above in clo.\n  bprop clo. unfold rlift.\n  case_eq (n <? k) ; intro e ; bprop e ; try mylia.\n  reflexivity.\nDefined.\n\nFact closed_rlift :\n  forall t n k,\n    closed t ->\n    rlift n k t = t.\nProof.\n  intros t n k h.\n  unfold closed in h.\n  eapply closed_above_rlift_id.\n  - eassumption.\n  - mylia.\nDefined.\n\nFixpoint llift_red1 {n k t1 t2} (h : t1 ▷ t2) :\n  llift n k t1 ▷ llift n k t2.\nProof.\n  destruct h ; cbn ;\n    try match goal with\n        | h : ?t ▷ _ |- ?tt ▷ _ =>\n          match tt with\n          | context [t] =>\n            econstructor ;\n              eapply llift_red1 ; [ exact h | .. ]\n          end\n        end.\n  - eapply meta_red_eq ; [ econstructor |].\n    replace k with (k + 0)%nat by mylia.\n    rewrite llift_subst.\n    replace (k + 0)%nat with k by mylia.\n    replace (S k + 0)%nat with (S k) by mylia.\n    reflexivity.\n  - eapply meta_red_eq ; [ econstructor |]. reflexivity.\n  - eapply meta_red_eq ; [ econstructor |]. reflexivity.\nDefined.\n\nLemma nl_llift :\n  forall {t u n k},\n    nl t = nl u ->\n    nl (llift n k t) = nl (llift n k u).\nProof.\n  intros t u n k.\n  case (nl_dec (nl t) (nl u)).\n  - intros e _.\n    revert u e n k.\n    induction t ;\n    intros u e m k ; destruct u ; cbn in e ; try discriminate e.\n    all:\n      try (cbn ; inversion e ;\n           repeat (erewrite_assumption by eassumption) ; reflexivity).\n  - intros h e. exfalso. apply h. apply e.\nDefined.\n\nLemma llift_conv :\n  forall {n k t1 t2},\n    t1 ≡ t2 ->\n    llift n k t1 ≡ llift n k t2.\nProof.\n  intros n k t1 t2 h.\n  induction h.\n  - apply conv_eq. apply nl_llift. assumption.\n  - eapply conv_red_l.\n    + eapply llift_red1. eassumption.\n    + assumption.\n  - eapply conv_red_r.\n    + eassumption.\n    + eapply llift_red1. eassumption.\nDefined.\n\nFixpoint rlift_red1 {n k t1 t2} (h : t1 ▷ t2) :\n  rlift n k t1 ▷ rlift n k t2.\nProof.\n  destruct h ; cbn ;\n    try match goal with\n        | h : ?t ▷ _ |- ?tt ▷ _ =>\n          match tt with\n          | context [t] =>\n            econstructor ;\n              eapply rlift_red1 ; [ exact h | .. ]\n          end\n        end.\n  - eapply meta_red_eq ; [ econstructor |].\n    replace k with (k + 0)%nat by mylia.\n    rewrite rlift_subst.\n    replace (k + 0)%nat with k by mylia.\n    replace (S k + 0)%nat with (S k) by mylia.\n    reflexivity.\n  - eapply meta_red_eq ; [ econstructor |]. reflexivity.\n  - eapply meta_red_eq ; [ econstructor |]. reflexivity.\nDefined.\n\nLemma nl_rlift :\n  forall {t u n k},\n    nl t = nl u ->\n    nl (rlift n k t) = nl (rlift n k u).\nProof.\n  intros t u n k.\n  case (nl_dec (nl t) (nl u)).\n  - intros e _.\n    revert u e n k.\n    induction t ;\n    intros u e m k ; destruct u ; cbn in e ; try discriminate e.\n    all:\n      try (cbn ; inversion e ;\n           repeat (erewrite_assumption by eassumption) ; reflexivity).\n  - intros h e. exfalso. apply h. apply e.\nDefined.\n\nLemma rlift_conv :\n  forall {n k t1 t2},\n    t1 ≡ t2 ->\n    rlift n k t1 ≡ rlift n k t2.\nProof.\n  intros n k t1 t2 h.\n  induction h.\n  - apply conv_eq. apply nl_rlift. assumption.\n  - eapply conv_red_l.\n    + eapply rlift_red1. eassumption.\n    + assumption.\n  - eapply conv_red_r.\n    + eassumption.\n    + eapply rlift_red1. eassumption.\nDefined.\n\nFact llift_ax_type :\n  forall {Σ},\n    type_glob Σ ->\n    forall {id ty},\n      lookup_glob Σ id = Some ty ->\n      forall n k, llift n k ty = ty.\nProof.\n  intros Σ hg id ty isd n k.\n  destruct (typed_ax_type hg isd).\n  eapply closed_llift.\n  eapply type_ctxempty_closed. eassumption.\nDefined.\n\nFact rlift_ax_type :\n  forall {Σ},\n    type_glob Σ ->\n    forall {id ty},\n      lookup_glob Σ id = Some ty ->\n      forall n k, rlift n k ty = ty.\nProof.\n  intros Σ hg id ty isd n k.\n  destruct (typed_ax_type hg isd).\n  eapply closed_rlift.\n  eapply type_ctxempty_closed. eassumption.\nDefined.\n\nLtac lh h :=\n  lazymatch goal with\n  | [ type_llift' :\n        forall (Σ : sglobal_context) (Γ Γ1 Γ2 Γm Δ : scontext) (t A : sterm),\n          Σ;;; Γ ,,, Γ1 ,,, Δ |-i t : A ->\n          type_glob Σ ->\n          ismix' Σ Γ Γ1 Γ2 Γm ->\n          Σ;;; Γ ,,, Γm ,,, llift_context #|Γm| Δ\n          |-i llift #|Γm| #|Δ| t : llift #|Γm| #|Δ| A\n    |- _ ] =>\n    lazymatch type of h with\n    | _ ;;; ?Γ' ,,, ?Γ1' ,,, ?Δ' |-i _ : ?T' =>\n      eapply meta_conv ; [\n        eapply meta_ctx_conv ; [\n          eapply type_llift' with (Γ := Γ') (Γ1 := Γ1') (Δ := Δ') (A := T') ; [\n            exact h\n          | eassumption\n          | eassumption\n          ]\n        | .. ]\n      | .. ]\n    | _ ;;; (?Γ' ,,, ?Γ1' ,,, ?Δ'),, ?d' |-i _ : ?T' =>\n      eapply meta_conv ; [\n        eapply meta_ctx_conv ; [\n          eapply type_llift' with (Γ := Γ') (Γ1 := Γ1') (Δ := Δ',, d') (A := T') ; [\n            exact h\n          | eassumption\n          | eassumption\n          ]\n        | .. ]\n      | .. ]\n    | _ ;;; (?Γ' ,,, ?Γ1' ,,, ?Δ'),, ?d',, ?d'' |-i _ : ?T' =>\n      eapply meta_conv ; [\n        eapply meta_ctx_conv ; [\n          eapply type_llift' with (Γ := Γ') (Γ1 := Γ1') (Δ := (Δ',, d'),, d'') (A := T') ; [\n            exact h\n          | eassumption\n          | eassumption\n          ]\n        | .. ]\n      | .. ]\n    end ; try (cbn ; reflexivity)\n  | _ => fail \"Cannot retrieve type_llift'\"\n  end.\n\nLtac rh h :=\n  lazymatch goal with\n  | [ type_rlift' :\n        forall (Σ : sglobal_context) (Γ Γ1 Γ2 Γm Δ : scontext) (t A : sterm),\n          Σ;;; Γ ,,, Γ2 ,,, Δ |-i t : A ->\n          type_glob Σ ->\n          ismix' Σ Γ Γ1 Γ2 Γm ->\n          Σ;;; Γ ,,, Γm ,,, rlift_context #|Γm| Δ\n          |-i rlift #|Γm| #|Δ| t : rlift #|Γm| #|Δ| A\n    |- _ ] =>\n    lazymatch type of h with\n    | _ ;;; ?Γ' ,,, ?Γ2' ,,, ?Δ' |-i _ : ?T' =>\n      eapply meta_conv ; [\n        eapply meta_ctx_conv ; [\n          eapply type_rlift' with (Γ := Γ') (Γ2 := Γ2') (Δ := Δ') (A := T') ; [\n            exact h\n          | eassumption\n          | eassumption\n          ]\n        | .. ]\n      | .. ]\n    | _ ;;; (?Γ' ,,, ?Γ2' ,,, ?Δ'),, ?d' |-i _ : ?T' =>\n      eapply meta_conv ; [\n        eapply meta_ctx_conv ; [\n          eapply type_rlift' with (Γ := Γ') (Γ2 := Γ2') (Δ := Δ',, d') (A := T') ; [\n            exact h\n          | eassumption\n          | eassumption\n          ]\n        | .. ]\n      | .. ]\n    | _ ;;; (?Γ' ,,, ?Γ2' ,,, ?Δ'),, ?d',, ?d'' |-i _ : ?T' =>\n      eapply meta_conv ; [\n        eapply meta_ctx_conv ; [\n          eapply type_rlift' with (Γ := Γ') (Γ2 := Γ2') (Δ := (Δ',, d'),, d'') (A := T') ; [\n            exact h\n          | eassumption\n          | eassumption\n          ]\n        | .. ]\n      | .. ]\n    end ; try (cbn ; reflexivity)\n  | _ => fail \"Cannot retrieve type_rlift'\"\n  end.\n\nLtac emh :=\n  lazymatch goal with\n  | h : _ ;;; _ |-i ?t : _ |- _ ;;; _ |-i llift _ _ ?t : _ => lh h\n  | h : _ ;;; _ |-i ?t : _ |- _ ;;; _ |-i rlift _ _ ?t : _ => rh h\n  | _ => fail \"Not a case for emh\"\n  end.\n\nFixpoint type_llift' {Σ Γ Γ1 Γ2 Γm Δ t A}\n  (h : Σ ;;; Γ ,,, Γ1 ,,, Δ |-i t : A) {struct h} :\n  type_glob Σ ->\n  ismix' Σ Γ Γ1 Γ2 Γm ->\n  Σ ;;; Γ ,,, Γm ,,, llift_context #|Γm| Δ\n  |-i llift #|Γm| #|Δ| t : llift #|Γm| #|Δ| A\n\nwith type_rlift' {Σ Γ Γ1 Γ2 Γm Δ t A}\n  (h : Σ ;;; Γ ,,, Γ2 ,,, Δ |-i t : A) {struct h} :\n  type_glob Σ ->\n  ismix' Σ Γ Γ1 Γ2 Γm ->\n  Σ ;;; Γ ,,, Γm ,,, rlift_context #|Γm| Δ\n  |-i rlift #|Γm| #|Δ| t : rlift #|Γm| #|Δ| A\n\nwith wf_llift' {Σ Γ Γ1 Γ2 Γm Δ} (h : wf Σ (Γ ,,, Γ1 ,,, Δ)) {struct h} :\n  type_glob Σ ->\n  ismix' Σ Γ Γ1 Γ2 Γm ->\n  wf Σ (Γ ,,, Γm ,,, llift_context #|Γm| Δ)\n\nwith wf_rlift' {Σ Γ Γ1 Γ2 Γm Δ} (h : wf Σ (Γ ,,, Γ2 ,,, Δ)) {struct h} :\n  type_glob Σ ->\n  ismix' Σ Γ Γ1 Γ2 Γm ->\n  wf Σ (Γ ,,, Γm ,,, rlift_context #|Γm| Δ)\n.\nProof.\n  (* type_llift' *)\n  - { dependent destruction h ; intros hg hm.\n      - unfold llift at 1.\n        case_eq (n <? #|Δ|) ; intro e ; bprop e.\n        + erewrite @safe_nth_lt with (isdecl' := e0).\n          eapply meta_conv.\n          * eapply type_Rel. eapply wf_llift' ; eassumption.\n          * erewrite safe_nth_lt. erewrite safe_nth_llift.\n            rewrite lift_llift3 by mylia.\n            f_equal. mylia.\n        + case_eq (n <? #|Δ| + #|Γm|) ; intro e1 ; bprop e1.\n          * erewrite safe_nth_ge'. erewrite safe_nth_lt.\n            eapply type_ProjT1' ; try assumption.\n            eapply meta_conv.\n            -- eapply type_Rel.\n               eapply wf_llift' ; eassumption.\n            -- erewrite safe_nth_ge'. erewrite safe_nth_lt.\n               erewrite safe_nth_mix' by eassumption.\n               cbn. f_equal.\n               replace (S (n - #|llift_context #|Γm| Δ|))\n                 with ((S n) - #|Δ|)\n                 by (rewrite llift_context_length ; mylia).\n               rewrite lift_llift4 by mylia. f_equal.\n               ++ mylia.\n               ++ f_equal. eapply safe_nth_cong_irr.\n                  rewrite llift_context_length. reflexivity.\n          * erewrite safe_nth_ge'. erewrite safe_nth_ge'.\n            eapply meta_conv.\n            -- eapply type_Rel.\n               eapply wf_llift' ; eassumption.\n            -- erewrite safe_nth_ge'. erewrite safe_nth_ge'.\n               rewrite lift_llift5 by mylia.\n               f_equal. eapply safe_nth_cong_irr.\n               rewrite llift_context_length. rewrite (mix'_length1 hm). mylia.\n      - cbn. eapply type_Sort. eapply wf_llift' ; eassumption.\n      - cbn. eapply type_Prod ; emh.\n      - cbn. eapply type_Lambda ; emh.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite llift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_App ; emh.\n      - cbn. eapply type_Sum ; emh.\n      - cbn. eapply type_Pair ; emh.\n        replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite llift_subst.\n        cbn. replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        reflexivity.\n      - cbn. eapply type_Pi1 ; emh.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite llift_subst.\n        cbn. replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_Pi2 ; emh.\n      - cbn. eapply type_Eq ; emh.\n      - cbn. eapply type_Refl ; emh.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite llift_subst.\n        replace (S #|Δ| + 0)%nat with (#|Δ| + 1)%nat by mylia.\n        rewrite llift_subst.\n        cbn. replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        replace (S (#|Δ| + 1))%nat with (S (S #|Δ|)) by mylia.\n        eapply type_J ; emh.\n        + cbn. unfold ssnoc. cbn. f_equal. f_equal.\n          * replace (S #|Δ|) with (1 + #|Δ|)%nat by mylia.\n            rewrite lift_llift3 by mylia. reflexivity.\n          * replace (S #|Δ|) with (1 + #|Δ|)%nat by mylia.\n            rewrite lift_llift3 by mylia. reflexivity.\n        + replace (S (S #|Δ|)) with ((S #|Δ|) + 1)%nat by mylia.\n          rewrite <- llift_subst.\n          change (sRefl (llift #|Γm| #|Δ| A0) (llift #|Γm| #|Δ| u))\n            with (llift #|Γm| #|Δ| (sRefl A0 u)).\n          replace (#|Δ| + 1)%nat with (S #|Δ| + 0)%nat by mylia.\n          rewrite <- llift_subst. f_equal. mylia.\n      - cbn. eapply type_Transport ; emh.\n      - cbn. eapply type_Heq ; emh.\n      - cbn. eapply type_HeqToEq ; emh.\n      - cbn. eapply type_HeqRefl ; emh.\n      - cbn. eapply type_HeqSym ; emh.\n      - cbn.\n        eapply @type_HeqTrans\n          with (B := llift #|Γm| #|Δ| B) (b := llift #|Γm| #|Δ| b) ; emh.\n      - cbn. eapply type_HeqTransport ; emh.\n      - cbn. eapply type_CongProd ; emh.\n        cbn. f_equal.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongLambda ; emh.\n        + cbn. f_equal.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n        + cbn. f_equal.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite 2!llift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_CongApp ; emh.\n        cbn. f_equal.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongSum ; emh.\n        cbn. f_equal.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongPair ; emh.\n        + cbn. f_equal.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n        + cbn. f_equal.\n          * replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n            rewrite llift_subst. cbn.\n            replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n            reflexivity.\n          * replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n            rewrite llift_subst. cbn.\n            replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n            reflexivity.\n        + replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n          rewrite llift_subst. cbn.\n          replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n          reflexivity.\n        + replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n          rewrite llift_subst. cbn.\n          replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n          reflexivity.\n      - cbn. eapply type_CongPi1 ; emh.\n        cbn. f_equal.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite 2!llift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_CongPi2 ; emh.\n        cbn. f_equal.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongEq ; emh.\n      - cbn. eapply type_CongRefl ; emh.\n      - cbn. eapply type_EqToHeq ; emh.\n      - cbn. eapply type_HeqTypeEq ; emh.\n      - cbn. eapply type_Pack ; emh.\n      - cbn. eapply @type_ProjT1 with (A2 := llift #|Γm| #|Δ| A2) ; emh.\n      - cbn. eapply @type_ProjT2 with (A1 := llift #|Γm| #|Δ| A1) ; emh.\n      - cbn. eapply type_ProjTe ; emh.\n      - cbn. erewrite llift_ax_type by eassumption.\n        eapply type_Ax.\n        + eapply wf_llift' ; eassumption.\n        + assumption.\n      - eapply type_conv ; try emh.\n        eapply llift_conv. assumption.\n    }\n\n  (* type_rlift' *)\n  - { dependent destruction h ; intros hg hm.\n      - unfold rlift at 1.\n        case_eq (n <? #|Δ|) ; intro e ; bprop e.\n        + erewrite @safe_nth_lt with (isdecl' := e0).\n          eapply meta_conv.\n          * eapply type_Rel. eapply wf_rlift' ; eassumption.\n          * erewrite safe_nth_lt. erewrite safe_nth_rlift.\n            rewrite lift_rlift3 by mylia.\n            f_equal. mylia.\n        + case_eq (n <? #|Δ| + #|Γm|) ; intro e1 ; bprop e1.\n          * erewrite safe_nth_ge'. erewrite safe_nth_lt.\n            eapply type_ProjT2' ; try assumption.\n            eapply meta_conv.\n            -- eapply type_Rel.\n               eapply wf_rlift' ; eassumption.\n            -- erewrite safe_nth_ge'. erewrite safe_nth_lt.\n               erewrite safe_nth_mix' by eassumption.\n               cbn. f_equal.\n               replace (S (n - #|rlift_context #|Γm| Δ|))\n                 with ((S n) - #|Δ|)\n                 by (rewrite rlift_context_length ; mylia).\n               rewrite lift_rlift4 by mylia. f_equal.\n               ++ mylia.\n               ++ f_equal. eapply safe_nth_cong_irr.\n                  rewrite rlift_context_length. reflexivity.\n          * erewrite safe_nth_ge'. erewrite safe_nth_ge'.\n            eapply meta_conv.\n            -- eapply type_Rel.\n               eapply wf_rlift' ; eassumption.\n            -- erewrite safe_nth_ge'. erewrite safe_nth_ge'.\n               rewrite lift_rlift5 by mylia.\n               f_equal. eapply safe_nth_cong_irr.\n               rewrite rlift_context_length. rewrite (mix'_length2 hm). mylia.\n      - cbn. eapply type_Sort. eapply wf_rlift' ; eassumption.\n      - cbn. eapply type_Prod ; emh.\n      - cbn. eapply type_Lambda ; emh.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite rlift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_App ; emh.\n      - cbn. eapply type_Sum ; emh.\n      - cbn. eapply type_Pair ; emh.\n        replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite rlift_subst.\n        cbn. replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        reflexivity.\n      - cbn. eapply type_Pi1 ; emh.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite rlift_subst.\n        cbn. replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_Pi2 ; emh.\n      - cbn. eapply type_Eq ; emh.\n      - cbn. eapply type_Refl ; emh.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite rlift_subst.\n        replace (S #|Δ| + 0)%nat with (#|Δ| + 1)%nat by mylia.\n        rewrite rlift_subst.\n        cbn. replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        replace (S (#|Δ| + 1))%nat with (S (S #|Δ|)) by mylia.\n        eapply type_J ; emh.\n        + cbn. unfold ssnoc. cbn. f_equal. f_equal.\n          * replace (S #|Δ|) with (1 + #|Δ|)%nat by mylia.\n            rewrite lift_rlift3 by mylia. reflexivity.\n          * replace (S #|Δ|) with (1 + #|Δ|)%nat by mylia.\n            rewrite lift_rlift3 by mylia. reflexivity.\n        + replace (S (S #|Δ|)) with ((S #|Δ|) + 1)%nat by mylia.\n          rewrite <- rlift_subst.\n          change (sRefl (rlift #|Γm| #|Δ| A0) (rlift #|Γm| #|Δ| u))\n            with (rlift #|Γm| #|Δ| (sRefl A0 u)).\n          replace (#|Δ| + 1)%nat with (S #|Δ| + 0)%nat by mylia.\n          rewrite <- rlift_subst. f_equal. mylia.\n      - cbn. eapply type_Transport ; emh.\n      - cbn. eapply type_Heq ; emh.\n      - cbn. eapply type_HeqToEq ; emh.\n      - cbn. eapply type_HeqRefl ; emh.\n      - cbn. eapply type_HeqSym ; emh.\n      - cbn.\n        eapply @type_HeqTrans\n          with (B := rlift #|Γm| #|Δ| B) (b := rlift #|Γm| #|Δ| b) ; emh.\n      - cbn. eapply type_HeqTransport ; emh.\n      - cbn. eapply type_CongProd ; emh.\n        cbn. f_equal.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongLambda ; emh.\n        + cbn. f_equal.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n        + cbn. f_equal.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite 2!rlift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_CongApp ; emh.\n        cbn. f_equal.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongSum ; emh.\n        cbn. f_equal.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongPair ; emh.\n        + cbn. f_equal.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n        + cbn. f_equal.\n          * replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n            rewrite rlift_subst. cbn.\n            replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n            reflexivity.\n          * replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n            rewrite rlift_subst. cbn.\n            replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n            reflexivity.\n        + replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n          rewrite rlift_subst. cbn.\n          replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n          reflexivity.\n        + replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n          rewrite rlift_subst. cbn.\n          replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n          reflexivity.\n      - cbn. eapply type_CongPi1 ; emh.\n        cbn. f_equal.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite 2!rlift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_CongPi2 ; emh.\n        cbn. f_equal.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongEq ; emh.\n      - cbn. eapply type_CongRefl ; emh.\n      - cbn. eapply type_EqToHeq ; emh.\n      - cbn. eapply type_HeqTypeEq ; emh.\n      - cbn. eapply type_Pack ; emh.\n      - cbn. eapply @type_ProjT1 with (A2 := rlift #|Γm| #|Δ| A2) ; emh.\n      - cbn. eapply @type_ProjT2 with (A1 := rlift #|Γm| #|Δ| A1) ; emh.\n      - cbn. eapply type_ProjTe ; emh.\n      - cbn. erewrite rlift_ax_type by eassumption.\n        eapply type_Ax.\n        + eapply wf_rlift' ; eassumption.\n        + assumption.\n      - eapply type_conv ; try emh.\n        eapply rlift_conv. assumption.\n    }\n\n  (* wf_llift' *)\n  - { destruct Δ.\n      - cbn. rewrite cat_nil in h.\n        intros hg hm. eapply wf_mix.\n        + eapply inversion_wf_cat. eassumption.\n        + eassumption.\n      - cbn. intros hg hm. dependent destruction h.\n        econstructor.\n        + eapply wf_llift' ; eassumption.\n        + eapply type_llift' with (A := sSort s0) ; eassumption.\n    }\n\n  (* wf_rlift' *)\n  - { destruct Δ.\n      - cbn. rewrite cat_nil in h.\n        intros hg hm. eapply wf_mix.\n        + eapply inversion_wf_cat. eassumption.\n        + eassumption.\n      - cbn. intros hg hm. dependent destruction h.\n        econstructor.\n        + eapply wf_rlift' ; eassumption.\n        + eapply type_rlift' with (A := sSort s0) ; eassumption.\n    }\n\n  Unshelve.\n  all: pose (mix'_length1 hm) ;\n       pose (mix'_length2 hm) ;\n       cbn ; try rewrite !length_cat ;\n       try rewrite !llift_context_length ;\n       try rewrite !rlift_context_length ;\n       try rewrite !length_cat in isdecl ;\n       try mylia.\nDefined.\n\nLemma ismix_ismix' :\n  forall {Σ Γ Γ1 Γ2 Γm},\n    type_glob Σ ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    ismix' Σ Γ Γ1 Γ2 Γm.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hg h.\n  dependent induction h.\n  - constructor.\n  - econstructor.\n    + assumption.\n    + eapply @type_llift' with (A := sSort s) (Δ := []) ; eassumption.\n    + eapply @type_rlift' with (A := sSort s) (Δ := []) ; eassumption.\nDefined.\n\nCorollary type_llift :\n  forall {Σ Γ Γ1 Γ2 Γm Δ t A},\n    type_glob Σ ->\n    Σ ;;; Γ ,,, Γ1 ,,, Δ |-i t : A ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm ,,, llift_context #|Γm| Δ\n    |-i llift #|Γm| #|Δ| t : llift #|Γm| #|Δ| A.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm Δ t A hg ht hm.\n  eapply type_llift'.\n  - eassumption.\n  - assumption.\n  - eapply ismix_ismix' ; eassumption.\nDefined.\n\nCorollary wf_llift :\n  forall {Σ Γ Γ1 Γ2 Γm Δ},\n    type_glob Σ ->\n    wf Σ (Γ ,,, Γ1 ,,, Δ) ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    wf Σ (Γ ,,, Γm ,,, llift_context #|Γm| Δ).\nProof.\n  intros Σ Γ Γ1 Γ2 Γm Δ hg hw hm.\n  eapply wf_llift'.\n  - eassumption.\n  - assumption.\n  - eapply ismix_ismix' ; eassumption.\nDefined.\n\nCorollary type_rlift :\n  forall {Σ Γ Γ1 Γ2 Γm Δ t A},\n    type_glob Σ ->\n    Σ ;;; Γ ,,, Γ2 ,,, Δ |-i t : A ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm ,,, rlift_context #|Γm| Δ\n    |-i rlift #|Γm| #|Δ| t : rlift #|Γm| #|Δ| A.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm Δ t A hg ht hm.\n  eapply type_rlift'.\n  - eassumption.\n  - assumption.\n  - eapply ismix_ismix' ; eassumption.\nDefined.\n\nCorollary wf_rlift :\n  forall {Σ Γ Γ1 Γ2 Γm Δ},\n    type_glob Σ ->\n    wf Σ (Γ ,,, Γ2 ,,, Δ) ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    wf Σ (Γ ,,, Γm ,,, rlift_context #|Γm| Δ).\nProof.\n  intros Σ Γ Γ1 Γ2 Γm Δ hg hw hm.\n  eapply wf_rlift'.\n  - eassumption.\n  - assumption.\n  - eapply ismix_ismix' ; eassumption.\nDefined.\n\n(* Lemma to use ismix knowledge about sorting. *)\nLemma ismix_nth_sort :\n  forall {Σ Γ Γ1 Γ2 Γm},\n    type_glob Σ ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    forall x is1 is2,\n      ∑ s,\n        (Σ;;; Γ ,,, Γ1\n         |-i lift0 (S x) (safe_nth Γ1 (exist _ x is1)) : sSort s) *\n        (Σ;;; Γ ,,, Γ2\n         |-i lift0 (S x) (safe_nth Γ2 (exist _ x is2)) : sSort s).\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hg hm.\n  dependent induction hm.\n  - intros x is1. cbn in is1. easy.\n  - intro x. destruct x ; intros is1 is2.\n    + cbn. exists s. split ; eapply @typing_lift01 with (A := sSort s) ; eassumption.\n    + cbn. cbn in is1, is2.\n      set (is1' := gt_le_S x #|Γ1| (gt_S_le (S x) #|Γ1| is1)).\n      set (is2' := gt_le_S x #|Γ2| (gt_S_le (S x) #|Γ2| is2)).\n      destruct (IHhm x is1' is2') as [s' [h1 h2]].\n      exists s'. split.\n      * replace (S (S x)) with (1 + (S x))%nat by mylia.\n        rewrite <- liftP3 with (k := 0) by mylia.\n        eapply @typing_lift01 with (A := sSort s') ; eassumption.\n      * replace (S (S x)) with (1 + (S x))%nat by mylia.\n        rewrite <- liftP3 with (k := 0) by mylia.\n        eapply @typing_lift01 with (A := sSort s') ; eassumption.\nDefined.\n\n(* Simpler to use corollaries *)\n\nCorollary type_llift0 :\n  forall {Σ Γ Γ1 Γ2 Γm t A},\n    type_glob Σ ->\n    Σ ;;; Γ ,,, Γ1 |-i t : A ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm |-i llift0 #|Γm| t : llift0 #|Γm| A.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm t A hg ? ?.\n  eapply @type_llift with (Δ := nil) ; eassumption.\nDefined.\n\nCorollary type_llift1 :\n  forall {Σ Γ Γ1 Γ2 Γm t A B},\n    type_glob Σ ->\n    Σ ;;; (Γ ,,, Γ1) ,, B |-i t : A ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm ,, (llift0 #|Γm| B)\n    |-i llift #|Γm| 1 t : llift #|Γm| 1 A.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm t A B hg ht hm.\n  eapply @type_llift with (Δ := [ B ]).\n  - assumption.\n  - exact ht.\n  - eassumption.\nDefined.\n\nCorollary type_rlift0 :\n  forall {Σ Γ Γ1 Γ2 Γm t A},\n    type_glob Σ ->\n    Σ ;;; Γ ,,, Γ2 |-i t : A ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm |-i rlift0 #|Γm| t : rlift0 #|Γm| A.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm t A ? ? ?.\n  eapply @type_rlift with (Δ := nil) ; eassumption.\nDefined.\n\nCorollary type_rlift1 :\n  forall {Σ Γ Γ1 Γ2 Γm t A B},\n    type_glob Σ ->\n    Σ ;;; (Γ ,,, Γ2) ,, B |-i t : A ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm ,, (rlift0 #|Γm| B)\n    |-i rlift #|Γm| 1 t : rlift #|Γm| 1 A.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm t A B hg ht hm.\n  eapply @type_rlift with (Δ := [ B ]).\n  - assumption.\n  - exact ht.\n  - eassumption.\nDefined.\n\n(* More lemmata about exchange.\n   They should go above with the others.\n *)\n\nLemma llift_substProj :\n  forall {t γ l},\n    (lift 1 (S l) (llift γ (S l) t)) {l := sProjT1 (sRel 0)} = llift (S γ) l t.\nProof.\n  intro t. induction t ; intros γ l.\n  all: try (cbn ; f_equal ; easy).\n  unfold llift.\n  case_eq (n <? S l) ; intro e ; bprop e ; try mylia.\n  - case_eq (n <? l) ; intro e1 ; bprop e1 ; try mylia.\n    + unfold lift. case_eq (S l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      cbn. case_eq (l ?= n) ; intro e5 ; bprop e5 ; try mylia.\n      reflexivity.\n    + case_eq (n <? l + S γ) ; intro e3 ; bprop e3 ; try mylia.\n      unfold lift. case_eq (S l <=? n) ; intro e5 ; bprop e5 ; try mylia.\n      cbn. case_eq (l ?= n) ; intro e7 ; bprop e7 ; try mylia.\n      f_equal. f_equal. mylia.\n  - case_eq (n <? l) ; intro e1 ; bprop e1 ; try mylia.\n    case_eq (n <? S l + γ) ; intro e3 ; bprop e3 ; try mylia.\n    + case_eq (n <? l + S γ) ; intro e5 ; bprop e5 ; try mylia.\n      unfold lift. case_eq (S l <=? n) ; intro e7 ; bprop e7 ; try mylia.\n      cbn. case_eq (l ?= S n) ; intro e9 ; bprop e9 ; try mylia.\n      reflexivity.\n    + case_eq (n <? l + S γ) ; intro e5 ; bprop e5 ; try mylia.\n      unfold lift. case_eq (S l <=? n) ; intro e7 ; bprop e7 ; try mylia.\n      cbn. case_eq (l ?= S n) ; intro e9 ; bprop e9 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma rlift_substProj :\n  forall {t γ l},\n    (lift 1 (S l) (rlift γ (S l) t)) {l := sProjT2 (sRel 0)} = rlift (S γ) l t.\nProof.\n  intro t. induction t ; intros γ l.\n  all: try (cbn ; f_equal ; easy).\n  unfold rlift.\n  case_eq (n <? S l) ; intro e ; bprop e ; try mylia.\n  - case_eq (n <? l) ; intro e1 ; bprop e1 ; try mylia.\n    + unfold lift. case_eq (S l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      cbn. case_eq (l ?= n) ; intro e5 ; bprop e5 ; try mylia.\n      reflexivity.\n    + case_eq (n <? l + S γ) ; intro e3 ; bprop e3 ; try mylia.\n      unfold lift. case_eq (S l <=? n) ; intro e5 ; bprop e5 ; try mylia.\n      cbn. case_eq (l ?= n) ; intro e7 ; bprop e7 ; try mylia.\n      f_equal. f_equal. mylia.\n  - case_eq (n <? l) ; intro e1 ; bprop e1 ; try mylia.\n    case_eq (n <? S l + γ) ; intro e3 ; bprop e3 ; try mylia.\n    + case_eq (n <? l + S γ) ; intro e5 ; bprop e5 ; try mylia.\n      unfold lift. case_eq (S l <=? n) ; intro e7 ; bprop e7 ; try mylia.\n      cbn. case_eq (l ?= S n) ; intro e9 ; bprop e9 ; try mylia.\n      reflexivity.\n    + case_eq (n <? l + S γ) ; intro e5 ; bprop e5 ; try mylia.\n      unfold lift. case_eq (S l <=? n) ; intro e7 ; bprop e7 ; try mylia.\n      cbn. case_eq (l ?= S n) ; intro e9 ; bprop e9 ; try mylia.\n      reflexivity.\nDefined.\n\nEnd Mix.", "meta": {"author": "TheoWinterhalter", "repo": "ett-to-itt", "sha": "b77534bf62673292da2139639f081cad4721a383", "save_path": "github-repos/coq/TheoWinterhalter-ett-to-itt", "path": "github-repos/coq/TheoWinterhalter-ett-to-itt/ett-to-itt-b77534bf62673292da2139639f081cad4721a383/theories/PackLifts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.23937480433406366}}
{"text": "(* Following http://adam.chlipala.net/theses/andreser.pdf chapter 3 *)\nRequire Import Coq.ZArith.ZArith Coq.micromega.Lia.\nRequire Import Coq.Structures.Orders.\nRequire Import Coq.Lists.List.\nRequire Import Crypto.Algebra.Nsatz.\nRequire Import Crypto.Arithmetic.ModularArithmeticTheorems.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.LetIn.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.NatUtil.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.Decidable.Bool2Prop.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Crypto.Util.Tactics.UniquePose.\nRequire Import Crypto.Util.CPSUtil.\nRequire Import Crypto.Util.CPSNotations.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.EquivModulo.\nRequire Import Crypto.Util.ZUtil.Modulo Crypto.Util.ZUtil.Div.\nRequire Import Crypto.Util.ZUtil.Zselect.\nRequire Import Crypto.Util.ZUtil.Hints.Core.\nRequire Import Crypto.Util.ZUtil.Modulo.PullPush.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.\nRequire Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.\nRequire Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.\nRequire Import Crypto.Util.Notations.\nImport ListNotations. Local Open Scope Z_scope.\n\n\nReserved Notation \"'dlet_list_pair_only_snd' x := v 'in' f\"\n         (at level 200, f at level 200, format \"'dlet_list_pair_only_snd'  x  :=  v  'in' '//' f\").\nReserved Notation \"'dlet_list_pair' x := v 'in' f\"\n         (at level 200, f at level 200, format \"'dlet_list_pair'  x  :=  v  'in' '//' f\").\nReserved Notation \"'dlet_list' x := v 'in' f\"\n         (at level 200, f at level 200, format \"'dlet_list'  x  :=  v  'in' '//' f\").\nDeclare Scope runtime_scope.\nDelimit Scope runtime_scope with RT.\nImport CPSBindNotations.\nLocal Open Scope cps_scope.\n\nModule Type Runtime.\n  Parameter Let_In : forall {A P} (x : A) (f : forall a : A, P a), P x.\n  Parameter runtime_nth_default : forall {A}, A -> list A -> nat -> A.\n  Parameter runtime_add : Z -> Z -> Z.\n  Parameter runtime_sub : Z -> Z -> Z.\n  Parameter runtime_mul : Z -> Z -> Z.\n  Parameter runtime_div : Z -> Z -> Z.\n  Parameter runtime_modulo : Z -> Z -> Z.\n  Parameter runtime_opp : Z -> Z.\n  Arguments runtime_add (_ _)%RT.\n  Arguments runtime_sub (_ _)%RT.\n  Arguments runtime_mul (_ _)%RT.\n  Arguments runtime_div _%RT _%Z.\n  Arguments runtime_modulo _%RT _%Z.\n  Arguments runtime_opp _%RT.\n  Infix \"*\" := runtime_mul : runtime_scope.\n  Infix \"+\" := runtime_add : runtime_scope.\n  Infix \"-\" := runtime_sub : runtime_scope.\n  Infix \"/\" := runtime_div : runtime_scope.\n  Notation \"x 'mod' y\" := (runtime_modulo x y) : runtime_scope.\n  Notation \"- x\" := (runtime_opp x) : runtime_scope.\n  Notation \"'dlet_nd' x .. y := v 'in' f\" := (Let_In (P:=fun _ => _) v (fun x => .. (fun y => f) .. )) (only parsing).\n  Notation \"'dlet' x .. y := v 'in' f\" := (Let_In v (fun x => .. (fun y => f) .. )).\n\n  Module RT_Z.\n    Parameter zselect : Z -> Z -> Z -> Z.\n    Parameter add_get_carry_full : Z -> Z -> Z -> Z * Z.\n    Parameter add_with_get_carry_full : Z -> Z -> Z -> Z -> Z * Z.\n    Parameter mul_split : Z -> Z -> Z -> Z * Z.\n    Parameter land : Z -> Z -> Z.\n  End RT_Z.\nEnd Runtime.\n\nModule RuntimeDefinitions <: Runtime.\n  Definition Let_In := @LetIn.Let_In.\n  Definition runtime_nth_default := List.nth_default.\n  Definition runtime_add := Z.add.\n  Definition runtime_sub := Z.sub.\n  Definition runtime_mul := Z.mul.\n  Definition runtime_opp := Z.opp.\n  Definition runtime_div := Z.div.\n  Definition runtime_modulo := Z.modulo.\n  Module RT_Z.\n    Definition zselect := Z.zselect.\n    Definition add_get_carry_full := Z.add_get_carry_full.\n    Definition add_with_get_carry_full := Z.add_with_get_carry_full.\n    Definition mul_split := Z.mul_split.\n    Definition land := Z.land.\n  End RT_Z.\nEnd RuntimeDefinitions.\n\nModule RuntimeAxioms : Runtime.\n  Include RuntimeDefinitions.\nEnd RuntimeAxioms.\n\nModule Export RuntimeDefinitionsCbv.\n  Import RuntimeDefinitions.\n  Declare Reduction cbv_no_rt\n    := cbv -[Let_In\n               runtime_nth_default\n               runtime_add\n               runtime_sub\n               runtime_mul\n               runtime_opp\n               runtime_div\n               runtime_modulo\n               RT_Z.add_get_carry_full\n               RT_Z.add_with_get_carry_full\n               RT_Z.mul_split].\n  Declare Reduction lazy_no_rt\n    := lazy -[Let_In\n                runtime_nth_default\n                runtime_add\n                runtime_sub\n                runtime_mul\n                runtime_opp\n                runtime_div\n                runtime_modulo\n                RT_Z.add_get_carry_full\n                RT_Z.add_with_get_carry_full\n                RT_Z.mul_split].\n  Declare Reduction pattern_rt\n    := pattern Let_In,\n       runtime_nth_default,\n       runtime_add,\n       runtime_sub,\n       runtime_mul,\n       runtime_opp,\n       runtime_div,\n       runtime_modulo,\n       RT_Z.add_get_carry_full,\n       RT_Z.add_with_get_carry_full,\n       RT_Z.mul_split.\n\n  Import RuntimeAxioms.\n  Declare Reduction pattern_ax_rt\n    := pattern (@Let_In),\n       (@runtime_nth_default),\n       runtime_add,\n       runtime_sub,\n       runtime_mul,\n       runtime_opp,\n       runtime_div,\n       runtime_modulo,\n       RT_Z.add_get_carry_full,\n       RT_Z.add_with_get_carry_full,\n       RT_Z.mul_split.\nEnd RuntimeDefinitionsCbv.\n\nModule RT_Extra (Import RT : Runtime).\n  Fixpoint dlet_nd_list_pair {A B} (ls : list (A * B)) {T} (f : list (A * B) -> T) : T\n    := match ls with\n       | nil => f nil\n       | cons x xs\n         => dlet_nd x1 := fst x in dlet_nd x2 := snd x in @dlet_nd_list_pair A B xs T (fun xs => f ((x1, x2) :: xs))\n       end.\n\n  Fixpoint dlet_nd_list {A} (ls : list A) {T} (f : list A -> T) : T\n    := match ls with\n       | nil => f nil\n       | cons x xs\n         => dlet_nd x := x in @dlet_nd_list A xs T (fun xs => f (x :: xs))\n       end.\n\n  Fixpoint dlet_nd_list_pair_only_snd {A B} (ls : list (A * B)) {T} (f : list (A * B) -> T) : T\n    := match ls with\n       | nil => f nil\n       | cons x xs\n         => dlet_nd x2 := snd x in @dlet_nd_list_pair_only_snd A B xs T (fun xs => f ((fst x, x2) :: xs))\n       end.\n\n  Notation \"'dlet_list_pair_only_snd' x := v 'in' f\" := (dlet_nd_list_pair_only_snd v (fun x => f)).\n  Notation \"'dlet_list_pair' x := v 'in' f\" := (dlet_nd_list_pair v (fun x => f)).\n  Notation \"'dlet_list' x := v 'in' f\" := (dlet_nd_list v (fun x => f)).\n\n\n  Definition expand_list_helper {A} (default : A) (ls : list A) (n : nat) (idx : nat) : list A\n  := nat_rect\n       (fun _ => nat -> list A)\n       (fun _ => nil)\n       (fun n' rec_call idx\n        => cons (runtime_nth_default default ls idx) (rec_call (S idx)))\n       n\n       idx.\n  Definition expand_list {A} (default : A) (ls : list A) (n : nat) : list A\n    := expand_list_helper default ls n 0.\nEnd RT_Extra.\n\nModule Associational (Import RT : Runtime).\n  Module Import Deps.\n    Module Export RT_Extra := RT_Extra RT.\n  End Deps.\n  Definition eval (p:list (Z*Z)) : Z :=\n    fold_right (fun x y => x + y) 0%Z (map (fun t => fst t * snd t) p).\n\n  Definition mul (p q:list (Z*Z)) : list (Z*Z) :=\n    flat_map (fun t =>\n      map (fun t' =>\n        (fst t * fst t', (snd t * snd t')%RT))\n    q) p.\n\n  Definition square_cps (p:list (Z*Z)) : ~> list (Z*Z) :=\n    list_rect\n      _\n      (return nil)\n      (fun t ts acc T k\n       => (dlet two_t2 := (2 * snd t)%RT in\n               acc\n                 _\n                 (fun acc\n                  => k (((fst t * fst t, (snd t * snd t)%RT)\n                           :: (map (fun t'\n                                    => (fst t * fst t', (two_t2 * snd t')%RT))\n                                   ts))\n                          ++ acc))))\n      p.\n\n  Definition negate_snd (p:list (Z*Z)) : list (Z*Z) :=\n    map (fun cx => (fst cx, (-snd cx)%RT)) p.\n\n  Definition split (s:Z) (p:list (Z*Z)) : list (Z*Z) * list (Z*Z)\n    := let hi_lo := partition (fun t => fst t mod s =? 0) p in\n       (snd hi_lo, map (fun t => (fst t / s, snd t)) (fst hi_lo)).\n\n  Definition reduce (s:Z) (c:list _) (p:list _) : list (Z*Z) :=\n    let lo_hi := split s p in fst lo_hi ++ mul c (snd lo_hi).\n\n  (* reduce at most [n] times, stopping early if the high list is nil at any point *)\n  Definition repeat_reduce (n : nat) (s:Z) (c:list _) (p:list _) : list (Z * Z)\n    := nat_rect\n         _\n         (fun p => p)\n         (fun n' repeat_reduce_n' p\n          => let lo_hi := split s p in\n             if (length (snd lo_hi) =? 0)%nat\n             then p\n             else let p := fst lo_hi ++ mul c (snd lo_hi) in\n                  repeat_reduce_n' p)\n         n\n         p.\n\n  (* rough template (we actually have to do things a bit differently to account for duplicate weights):\n[ dlet fi_c := c * fi in\n   let (fj_high, fj_low) := split fj at s/fi.weight in\n   dlet fi_2 := 2 * fi in\n    dlet fi_2_c := 2 * fi_c in\n    (if fi.weight^2 >= s then fi_c * fi else fi * fi)\n       ++ fi_2_c * fj_high\n       ++ fi_2 * fj_low\n | fi <- f , fj := (f weight less than i) ]\n   *)\n  (** N.B. We take advantage of dead code elimination to allow us to\n      let-bind partial products that we don't end up using *)\n  (** [v] -> [(v, v*c, v*c*2, v*2)] *)\n  Definition let_bind_for_reduce_square_cps (c:list (Z*Z)) (p:list (Z*Z)) : ~> list ((Z*Z) * list(Z*Z) * list(Z*Z) * list(Z*Z)) :=\n    fun T\n    => let two := [(1,2)] (* (weight, value) *) in\n       map_cps2 (fun t T k => dlet_list_pair_only_snd c_t := mul [t] c in dlet_list_pair_only_snd two_c_t := mul c_t two in dlet_list_pair_only_snd two_t := mul [t] two in k (t, c_t, two_c_t, two_t)) p.\n  Definition reduce_square_cps (s:Z) (c:list (Z*Z)) (p:list (Z*Z)) : ~>list (Z*Z) :=\n    (p <- let_bind_for_reduce_square_cps c p;\n    let div_s := map (fun t => (fst t / s, snd t)) in\n    return (list_rect\n      _\n      nil\n      (fun t ts acc\n       => (let '(t, c_t, two_c_t, two_t) := t in\n           (if ((fst t * fst t) mod s =? 0)\n            then div_s (mul [t] c_t)\n            else mul [t] [t])\n             ++ (flat_map\n                   (fun '(t', c_t', two_c_t', two_t')\n                    => if ((fst t * fst t') mod s =? 0)\n                       then div_s\n                              (if fst t' <=? fst t\n                               then mul [t'] two_c_t\n                               else mul [t] two_c_t')\n                       else (if fst t' <=? fst t\n                             then mul [t'] two_t\n                             else mul [t] two_t'))\n                   ts))\n            ++ acc)\n      p)).\n\n  Definition bind_snd_cps (p : list (Z*Z)) : ~>list (Z * Z) :=\n    @dlet_nd_list_pair_only_snd _ _ p.\n\n  Section Carries.\n    Definition carryterm_cps (w fw:Z) (t:Z * Z) : ~> list (Z * Z) :=\n      fun T k\n      => if (Z.eqb (fst t) w)\n         then dlet_nd t2 := snd t in\n              dlet_nd d2 := (t2 / fw)%RT in\n              dlet_nd m2 := (t2 mod fw)%RT in\n              k [(w * fw, d2);(w,m2)]\n         else k [t].\n\n    Definition carry_cps (w fw:Z) (p:list (Z * Z)) : ~> list (Z * Z):=\n      fun T => flat_map_cps (carryterm_cps w fw) p.\n  End Carries.\nEnd Associational.\n\nModule Positional (Import RT : Runtime).\n  Module Import Deps.\n    Module Associational := Associational RT.\n  End Deps.\n  Section Positional.\n  Context (weight : nat -> Z).\n\n  Definition to_associational (n:nat) (xs:list Z) : list (Z*Z)\n    := combine (map weight (List.seq 0 n)) xs.\n  Definition eval n x := Associational.eval (@to_associational n x).\n  Definition zeros n : list Z := repeat 0 n.\n  Definition add_to_nth i x (ls : list Z) : list Z\n    := ListUtil.update_nth i (fun y => (x + y)%RT) ls.\n\n  Definition place (t:Z*Z) (i:nat) : nat * Z :=\n    nat_rect\n      (fun _ => unit -> (nat * Z)%type)\n      (fun _ => (O, if fst t =? 1 then snd t else (fst t * snd t)%RT))\n      (fun i' place_i' _\n       => let i := S i' in\n          if (fst t mod weight i =? 0)\n          then (i, let c := fst t / weight i in if c =? 1 then snd t else (c * snd t)%RT)\n          else place_i' tt)\n      i\n      tt.\n\n  Definition from_associational_cps n (p:list (Z*Z)) : ~> list Z :=\n    fun T => fold_right_cps2 (fun t ls T k =>\n      let '(p1, p2) := place t (pred n) in\n      dlet_nd p2 := p2 in\n      k (add_to_nth p1 p2 ls)) (zeros n) p.\n\n  Definition extend_to_length (n_in n_out : nat) (p:list Z) : list Z :=\n    p ++ zeros (n_out - n_in).\n\n  Definition drop_high_to_length (n : nat) (p:list Z) : list Z :=\n    firstn n p.\n\n  Section mulmod.\n    Context (s:Z)\n            (c:list (Z*Z)).\n    Definition mulmod_cps (n:nat) (a b:list Z) : ~> list Z\n      := let a_a := to_associational n a in\n         let b_a := to_associational n b in\n         let ab_a := Associational.mul a_a b_a in\n         let abm_a := Associational.repeat_reduce n s c ab_a in\n         from_associational_cps n abm_a.\n\n    Definition squaremod_cps (n:nat) (a:list Z) : ~> list Z\n      := (let a_a := to_associational n a in\n         aa_a <- Associational.reduce_square_cps s c a_a;\n         let aam_a := Associational.repeat_reduce (pred n) s c aa_a in\n         from_associational_cps n aam_a).\n  End mulmod.\n\n  Definition add_cps (n:nat) (a b:list Z) : ~> list Z\n    := let a_a := to_associational n a in\n       let b_a := to_associational n b in\n       from_associational_cps n (a_a ++ b_a).\n\n  Section Carries.\n    Definition carry_cps n m (index:nat) (p:list Z) : ~> list Z :=\n      (p <- @Associational.carry_cps (weight index)\n         (weight (S index) / weight index)\n         (to_associational n p);\n       from_associational_cps\n           m p).\n\n    Definition carry_reduce_cps n (s:Z) (c:list (Z * Z))\n               (index:nat) (p : list Z) : ~> list Z :=\n      (p <- @carry_cps n (S n) index p;\n         p <- from_associational_cps\n           n (Associational.reduce\n                s c (to_associational (S n) p));\n       return p).\n\n    (* N.B. It is important to reverse [idxs] here, because fold_right is\n      written such that the first terms in the list are actually used\n      last in the computation. For example, running:\n\n      `Eval cbv - [Z.add] in (fun a b c d => fold_right Z.add d [a;b;c]).`\n\n      will produce [fun a b c d => (a + (b + (c + d)))].*)\n    Definition chained_carries_cps n s c p (idxs : list nat) : ~> _ :=\n      fun T => fold_right_cps2 (fun a b => carry_reduce_cps n s c a b) p (rev idxs).\n\n    (* carries without modular reduction; useful for converting between bases *)\n    Definition chained_carries_no_reduce_cps n p (idxs : list nat) : ~> _ :=\n      fun T => fold_right_cps2 (fun a b => carry_cps n n a b) p (rev idxs).\n\n    (* Reverse of [eval]; translate from Z to basesystem by putting\n    everything in first digit and then carrying. *)\n    Definition encode_cps n s c (x : Z) : ~> list Z :=\n      (p <- from_associational_cps n [(1,x)]; chained_carries_cps n s c p (seq 0 n)).\n\n    (* Reverse of [eval]; translate from Z to basesystem by putting\n    everything in first digit and then carrying, but without reduction. *)\n    Definition encode_no_reduce_cps n (x : Z) : ~> list Z :=\n      (p <- from_associational_cps n [(1,x)]; chained_carries_no_reduce_cps n p (seq 0 n)).\n  End Carries.\n\n  Section sub.\n    Context (n:nat)\n            (s:Z)\n            (c:list (Z * Z))\n            (coef:Z).\n\n    Definition negate_snd_cps (a:list Z) : ~> list Z\n      := let A := to_associational n a in\n         let negA := Associational.negate_snd A in\n         from_associational_cps n negA.\n\n    Definition scmul_cps (x:Z) (a:list Z) : ~> list Z\n      := let A := to_associational n a in\n         let R := Associational.mul A [(1, x)] in\n         from_associational_cps n R.\n\n    Definition balance_cps : ~> list Z\n      := (sc <- encode_cps n s c (s - Associational.eval c); v <- scmul_cps coef sc; return v).\n\n    Definition sub_cps (a b:list Z) : ~> list Z\n      := (balance <- balance_cps;\n            ca <- add_cps n balance a;\n            _b <- negate_snd_cps b;\n            camb <- add_cps n ca _b;\n            return camb).\n\n    Definition opp_cps (a:list Z) : ~> list Z\n      := sub_cps (zeros n) a.\n  End sub.\n\n  Section select.\n    Definition zselect_cps (mask cond:Z) (p:list Z) : ~> _ :=\n      fun T k => dlet t := RT_Z.zselect cond 0 mask in k (List.map (RT_Z.land t) p).\n\n    Definition select (cond:Z) (if_zero if_nonzero:list Z) :=\n      List.map (fun '(p, q) => RT_Z.zselect cond p q) (List.combine if_zero if_nonzero).\n  End select.\nEnd Positional.\nEnd Positional.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/ArithmeticCPS/Core.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2392746598334529}}
{"text": "From stdpp Require Import fin_maps gmap.\nFrom iris.bi.lib Require Import fractional.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic.lib Require Import saved_prop gen_heap.\nFrom aneris.prelude Require Import collect.\nFrom aneris.lib Require Import gen_heap_light.\nFrom aneris.aneris_lang Require Export aneris_lang network resources.\n\nFrom RecordUpdate Require Import RecordSet.\nSet Default Proof Using \"Type\".\n\nImport uPred.\nImport RecordSetNotations.\n\nDefinition messages_history := prod message_soup message_soup.\n\nDefinition messages_history_map := gmap socket_address messages_history.\n\nImplicit Types mh : messages_history_map.\nImplicit Types rt : messages_history.\n\n(* The set of all received messages *)\nDefinition messages_received mh := collect (λ _ rt, rt.1) mh.\n\nLemma elem_of_messages_received mh :\n  ∀ m, m ∈ messages_received mh ↔\n         ∃ sa rt, mh !! sa = Some rt ∧ m ∈ rt.1.\nProof. by apply elem_of_collect; eauto. Qed.\n\n(* The set of all transmitted messages *)\nDefinition messages_sent mh := collect (λ _ rt, rt.2) mh.\n\nLemma elem_of_messages_sent mh :\n  ∀ m, m ∈ messages_sent mh ↔\n         ∃ sa rt, mh !! sa = Some rt ∧ m ∈ rt.2.\nProof. by apply elem_of_collect; eauto. Qed.\n\n(** Definitions for the message history *)\nDefinition messages_received_sent mh : messages_history :=\n  (messages_received mh, messages_sent mh).\n\n(* [m] has been received *)\nDefinition message_received m mh := m ∈ (messages_received mh).\n\nLemma gset_to_gmap_singleton (v: message_soup * message_soup)\n      (a : socket_address) : gset_to_gmap v {[ a ]} = {[a := v]}.\nProof.\n  assert ({[a]} = {[a]} ∪ (∅: gset socket_address)) as -> by by set_solver.\n    by rewrite (gset_to_gmap_union_singleton v a ∅) gset_to_gmap_empty.\nQed.\n\nLemma messages_received_init B :\n  messages_received (gset_to_gmap (∅, ∅) B) = ∅.\nProof.\n  rewrite /messages_received.\n  apply collect_empty_f.\n  intros ? [].\n  rewrite lookup_gset_to_gmap_Some.\n  by intros [? [=]].\nQed.\n\nLemma messages_sent_init B :\n  messages_sent (gset_to_gmap (∅, ∅) B) = ∅.\nProof.\n  rewrite /messages_sent.\n  apply collect_empty_f.\n  intros ? [].\n  rewrite lookup_gset_to_gmap_Some.\n  by intros [? [=]].\nQed.\n\nLemma messages_received_sent_init B :\n  messages_received_sent (gset_to_gmap (∅, ∅) B) = (∅, ∅).\nProof.\n  rewrite /messages_received_sent. f_equal.\n  - apply messages_received_init.\n  - apply messages_sent_init.\nQed.\n\nLemma messages_sent_insert a R T mh :\n  messages_sent (<[a:=(R, T)]> mh) = T ∪ messages_sent (delete a mh).\nProof.\n  rewrite /messages_sent.\n  apply collect_insert.\nQed.\n\nLemma message_received_insert a msg R T mh :\n  message_received msg (<[a:=(R, T)]> mh) ↔\n                   msg ∈ R ∨ message_received msg (delete a mh).\nProof.\n  rewrite /message_received /messages_received.\n  rewrite collect_insert //= elem_of_union //.\nQed.\n\n Lemma messages_received_insert  a R T mh :\n   messages_received (<[a:=(R, T)]> mh) = R ∪ messages_received (delete a mh).\n Proof.\n   rewrite /messages_received.\n   apply collect_insert.\n Qed.\n\nLemma messages_sent_split a R T mh :\n  mh !! a = Some (R, T) →\n  messages_sent mh =\n  T ∪ messages_sent (delete a mh).\nProof.\n  intros.\n  assert (mh = <[a := (R,T)]>mh) as Heq by by rewrite insert_id.\n  rewrite {1} Heq.\n  apply collect_insert.\nQed.\n\n(* The messages in the logical map mh, that tracks received and transmitted\n   messages, have coherent addresses. *)\nDefinition messages_addresses_coh mh :=\n  ∀ a R T, mh !! a = Some (R, T) →\n    (∀ m, m ∈ R → m_destination m = a) ∧ (∀ m, m ∈ T → m_sender m = a).\n\nDefinition messages_received_from_sent_coh mh :=\n  messages_received mh ⊆ messages_sent mh.\n\nDefinition messages_received_from_sent_coh_aux mh :=\n  ∀ rt m,\n    mh !! (m_destination m) = Some rt →\n    m ∈ rt.1 →\n    ∃ rt', mh !! (m_sender m) = Some rt' ∧ m ∈ rt'.2.\n\nLemma messages_received_from_sent_corrolary_coh mh :\n  messages_addresses_coh mh →\n  messages_received_from_sent_coh mh →\n  messages_received_from_sent_coh_aux mh.\nProof.\n  intros Hacoh Hrcoh.\n  intros rt m Hrt Hm.\n  assert (m ∈ messages_received mh) as Hmr.\n  { by apply elem_of_collect; eauto. }\n  apply Hrcoh, elem_of_collect in Hmr as (sa & rt' & Hrt' & Hmt).\n  assert (mh !! sa = Some (rt'.1, rt'.2)) as Hgas by by destruct rt'.\n  specialize (Hacoh sa rt'.1  rt'.2 Hgas) as (Hc1 & Hc2).\n  specialize (Hc2 m Hmt). set_solver.\nQed.\n\nLemma messages_sent_dijsoint a R T mh :\n  mh !! a = Some (R, T) →\n  messages_addresses_coh mh →\n  T ## messages_sent (delete a mh).\nProof.\n  intros Ha Hmcoh.\n  apply elem_of_disjoint.\n  intros m HmT Hms.\n  apply elem_of_collect in Hms as (a' & (R',T') & Ha' & Ht).\n  simplify_map_eq.\n  destruct (Hmcoh a R T Ha) as (_ & HT).\n  specialize (HT m HmT).\n  rewrite -HT in Ha'.\n  destruct (decide (a' = (m_sender m))) as [->|Hneq].\n  - by rewrite lookup_delete in Ha'.\n  - rewrite lookup_delete_ne in Ha'; last done.\n    destruct (Hmcoh a' R' T' Ha') as (_ & HT').\n    specialize (HT' m Ht).\n    done.\nQed.\n", "meta": {"author": "fresheed", "repo": "trillium-experiments", "sha": "a9c38a9e9566fb8057ae97ecb8d1a0c09c799aef", "save_path": "github-repos/coq/fresheed-trillium-experiments", "path": "github-repos/coq/fresheed-trillium-experiments/trillium-experiments-a9c38a9e9566fb8057ae97ecb8d1a0c09c799aef/vendor/aneris/theories/aneris_lang/state_interp/messages_history.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.23927465303653053}}
{"text": "Require Import FloydSeq.base2.\nRequire Import FloydSeq.forward.\n\n\nInductive FWD : Type :=\n| FWD_end: FWD\n| FWD_straight0: FWD -> FWD\n| FWD_straight1: forall {A: Type}, (A -> FWD) -> FWD\n| FWD_intro: forall {A: Type}, (A -> FWD) -> FWD\n| FWD_while0: forall (P: environ->mpred), FWD -> FWD -> FWD\n| FWD_while1: forall (P: environ->mpred) {A: Type}, (A -> FWD) -> FWD -> FWD.\n\nLtac go_FWD f :=\n  match f with\n  | FWD_end => idtac\n  | FWD_straight0 ?f' => forward; [ .. | go_FWD f']\n  | FWD_straight1 ?f1 =>\n         let x := fresh \"x\" in forward x; [ .. |\n         let y := constr:(f1 x) in let y' := (eval cbv beta in y) in\n         go_FWD y']\n  | FWD_intro ?f1 =>\n         let x := fresh \"x\" in forward_intro x;\n         let y := constr:(f1 x) in let y' := (eval cbv beta in y) in\n         go_FWD y'\n  | FWD_while0 ?P ?Q ?f1 ?f2 =>\n          forward_while P (*Q*); [ | | | go_FWD f1 | go_FWD f2]\n  | FWD_while1 ?P ?Q ?f1 ?f2 =>\n            let x := fresh \"x\" in forward_while P (*x*);\n             [ | |\n             |  let y := constr:(f1 x) in let y' := (eval cbv beta in y) in\n                 go_FWD y'\n             | go_FWD f2]\n  end.", "meta": {"author": "QinxiangCao", "repo": "VST-A-VSTpart", "sha": "fd8e5b0846a121c20b267fef7ca36e33dd24fae6", "save_path": "github-repos/coq/QinxiangCao-VST-A-VSTpart", "path": "github-repos/coq/QinxiangCao-VST-A-VSTpart/VST-A-VSTpart-fd8e5b0846a121c20b267fef7ca36e33dd24fae6/floyd-seq/real_forward.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23919817393835974}}
{"text": "Require Import\n  ByteString.Lib.Tactics\n  ByteString.Lib.Nomega\n  ByteString.Lib.FMapExt\n  ByteString.Lib.Fiat\n  ByteString.Lib.FromADT\n  ByteString.Memory\n  ByteString.Heap\n  Coq.FSets.FMapFacts\n  Coq.Structures.DecidableTypeEx.\n\nModule HeapCanonical (M : WSfun Ptr_as_DT).\n\nModule Import Heap := Heap M.\n\nImport HeapState.\nImport FMapExt.\n\nOpen Scope N_scope.\n\n(** In order to refine to a computable heap, we have to add the notion of\n    \"free memory\", from which addresses may be allocated. A further\n    optimization here would be to add a free list, to which free blocks are\n    returned, in order avoid gaps in the heap. A yet further optimization\n    would be to better manage the free space to avoid fragmentation. The\n    implementation below simply grows the heap with every allocation. *)\n\nTheorem HeapCanonical : FullySharpened HeapSpec.\nProof.\n  start sharpening ADT.\n\n  eapply transitivityT.\n  eapply annotate_ADT with\n    (methDefs' := icons {|methBody :=  _|}\n                 (icons {|methBody :=  _|}\n                 (icons {|methBody :=  _|}\n                 (icons {|methBody :=  _|}\n                 (icons {|methBody :=  _|}\n                 (icons {|methBody :=  _|}\n                 (icons {|methBody :=  _|}\n                 (icons {|methBody :=  _|}\n                 (icons {|methBody :=  _|}\n                 (icons {|methBody :=  _|} inil ) ) ) ) ) ) ) ) ) )\n    (AbsR := fun or nr =>\n       M.Equal (resvs or) (resvs (snd nr)) /\\\n       M.Equal (bytes or) (bytes (snd nr)) /\\\n       P.for_all (fun addr sz => plusPtr addr sz <=? fst nr) (resvs (snd nr))).\n  simpl; repeat apply Build_prim_prod; simpl;\n  intros; try simplify with monad laws; set_evars.\n\n  (* refine constructor emptyS *)\n  {\n    (*\n    instantiate (1 := Build_prim_prod {| consBody := _ |} ());\n    simpl; simplify with monad laws; set_refine_evar.\n    (* tactic should do all this automatically. *)\n    *)\n\n    refine pick val (0%N, newHeapState).\n      finish honing.\n\n    intuition; simpl.\n    apply for_all_empty; relational; nomega.\n  }\n\n  (* refine method allocS. *)\n  {\n    (*\n    instantiate (1 := Build_prim_prod {| methBody := _ |} _); simpl;\n    set_refine_evar; simplify with monad laws.\n    (* tactic should do all this automatically. *)\n   *)\n\n    unfold find_free_block.\n\n    refine pick val (fst r_n).\n    {\n      simplify with monad laws; simpl.\n\n      refine pick val (plusPtr (A:=Word) (fst r_n) (` d),\n                       {| resvs := M.add (fst r_n) (` d) (resvs (snd r_n))\n                        ; bytes := bytes (snd r_n) |}).\n        simplify with monad laws; simpl.\n\n        finish honing.\n\n      simpl in *; intuition.\n      rewrite H2; reflexivity.\n      apply for_all_add_true; relational; try nomega.\n        rewrite <- H2.\n        destruct d.\n        eapply allocations_no_overlap_r; eauto.\n        rewrite H2.\n        eapply for_all_impl; eauto; relational;\n        intros; nomega.\n      split.\n        eapply for_all_impl; eauto; relational;\n        intros; nomega.\n      nomega.\n    }\n\n    repeat breakdown; simpl in *.\n    rewrite H0.\n    eapply for_all_impl; eauto;\n    relational; nomega.\n  }\n  (* And so on :) ....*)\n\n  (* refine method freeS. *)\n  {\n    refine pick val (fst r_n,\n                     {| resvs := M.remove d (resvs (snd r_n))\n                      ; bytes := bytes (snd r_n) |}).\n    try simplify with monad laws; simpl.\n      finish honing.\n\n    simpl in *; intuition.\n    - rewrite H2; reflexivity.\n    - apply for_all_remove; relational; nomega.\n  }\n\n  (* refine method reallocS. *)\n  {\n    unfold find_free_block.\n    refine pick val (Ifopt M.find d (resvs (snd r_n)) as sz\n                     Then If ` d0 <=? sz Then d Else fst r_n\n                     Else fst r_n).\n    {\n      simplify with monad laws.\n\n      refine pick val\n        (Ifopt M.find d (resvs (snd r_n)) as sz\n         Then If ` d0 <=? sz\n              Then\n                (fst r_n,\n                 {| resvs := M.add d (` d0) (resvs (snd r_n)) (* update *)\n                  ; bytes := bytes (snd r_n) |})\n              Else\n                (plusPtr (A:=Word) (fst r_n) (` d0),\n                 {| resvs :=\n                      M.add (fst r_n) (` d0) (M.remove d (resvs (snd r_n)))\n                  ; bytes :=\n                      copy_bytes d (fst r_n) sz (bytes (snd r_n))|})\n         Else\n           (plusPtr (A:=Word) (fst r_n) (` d0),\n            {| resvs := M.add (fst r_n) (` d0) (resvs (snd r_n))\n             ; bytes := bytes (snd r_n) |})).\n        simplify with monad laws.\n        simpl.\n        finish honing.\n\n      simpl in *; intuition; rewrite ?H2;\n      (destruct (M.find d _) as [sz|] eqn:Heqe;\n       [ destruct (` d0 <=? sz) eqn:Heqe1;\n         simpl; rewrite ?Heqe1 |]); simpl.\n      - rewrite remove_add; reflexivity.\n      - reflexivity.\n      - apply F.add_m; auto.\n        apply F.Equal_mapsto_iff; split; intros.\n          simplify_maps.\n        simplify_maps; intuition.\n        subst.\n        apply F.find_mapsto_iff in H1.\n        congruence.\n      - rewrite copy_bytes_idem; assumption.\n      - rewrite N.min_l.\n          rewrite H0; reflexivity.\n        nomega.\n      - assumption.\n      - normalize.\n        apply_for_all; relational.\n        rewrite <- remove_add.\n        apply for_all_add_true; relational; try nomega.\n          simplify_maps.\n        split.\n          apply for_all_remove; relational; nomega.\n        nomega.\n      - normalize.\n        apply_for_all; relational.\n        rewrite <- remove_add.\n        apply for_all_add_true; relational; try nomega.\n          simplify_maps.\n        split.\n          apply for_all_remove; relational; try nomega.\n          apply for_all_remove; relational; try nomega.\n          eapply for_all_impl; eauto;\n          relational; nomega.\n        nomega.\n      - rewrite <- remove_add.\n        apply for_all_add_true; relational; try nomega.\n          simplify_maps.\n        split.\n          apply for_all_remove; relational; try nomega.\n          eapply for_all_impl; eauto;\n          relational; nomega.\n        nomega.\n    }\n\n    simpl in *; intuition; rewrite ?H1;\n    (destruct (M.find d _) as [sz|] eqn:Heqe;\n     [ destruct (` d0 <=? sz) eqn:Heqe1;\n       simpl; rewrite ?Heqe1 |]); simpl.\n    - normalize.\n      rewrite <- H2 in Heqe.\n      pose proof (allocations_no_overlap H Heqe) as H2'.\n      apply P.for_all_iff; relational; intros; try nomega.\n      simplify_maps.\n      specialize (H2' _ _ H5 H3).\n      nomega.\n    - normalize.\n      apply_for_all; relational.\n      apply for_all_remove; relational; try nomega.\n      eapply for_all_impl; eauto;\n      relational; try nomega.\n      rewrite <- H2 in H4.\n      auto.\n    - apply for_all_remove; relational.\n        nomega.\n      remember (fun _ _ => _ <=? _) as P.\n      remember (fun _ _ => negb _) as P'.\n      apply for_all_impl with (P:=P) (P':=P');\n      relational; try nomega.\n      rewrite H2.\n      assumption.\n  }\n\n  (* refine method peekS. *)\n  {\n    refine pick val (Ifopt M.find (plusPtr d d0) (bytes (snd r_n)) as v\n                     Then v\n                     Else Zero).\n      simplify with monad laws.\n      refine pick val r_n.\n      simplify with monad laws.\n      simpl; finish honing.\n      simpl in *; intuition.\n\n    clear H.\n    simpl in *; intuition.\n    destruct (M.find (plusPtr d d0) _) as [sz|] eqn:Heqe;\n    simpl; normalize.\n      left.\n      rewrite H0.\n      assumption.\n    right.\n    split; intuition.\n    destruct H1.\n    apply F.find_mapsto_iff in H1.\n    rewrite H0 in H1.\n    congruence.\n  }\n\n  (* refine method pokeS. *)\n  {\n    refine pick val (fst r_n,\n                     {| resvs := resvs (snd r_n)\n                      ; bytes := M.add (plusPtr d d0) d1 (bytes (snd r_n)) |}).\n    simpl.\n    finish honing.\n\n    simpl in *; intuition;\n    destruct (d <? fst r_n) eqn:Heqe; simpl; trivial;\n    rewrite H0; reflexivity.\n  }\n\n  (* refine method memcpyS. *)\n  {\n    refine pick val (fst r_n,\n                     {| resvs := resvs (snd r_n)\n                      ; bytes := copy_bytes (plusPtr d d0) (plusPtr d1 d2)\n                                            d3 (bytes (snd r_n)) |}).\n      finish honing.\n\n    simpl in *; intuition;\n    rewrite H0; reflexivity.\n  }\n\n  (* refine method memsetS. *)\n  {\n    refine pick val\n       (fst r_n,\n        {| resvs := resvs (snd r_n)\n         ; bytes :=\n             P.update\n               (bytes (snd r_n))\n               (N.peano_rect\n                  (fun _ => M.t Word)\n                  (bytes (snd r_n))\n                  (fun i => M.add (plusPtr(A:=Word) d (d0 + i))%N d2) d1) |}).\n      simpl; finish honing.\n\n    simpl in *; intuition.\n    apply P.update_m; trivial.\n    induction d1 using N.peano_ind; simpl; trivial.\n    rewrite !N.peano_rect_succ.\n    apply F.add_m; auto.\n  }\n\n  (* refine method readS. *)\n  {\n    refine pick eq.\n    simplify with monad laws; simpl.\n    refine pick val r_n.\n      simplify with monad laws; simpl.\n      destruct H0, H2.\n      rewrite Npeano_rect_eq\n        with (g := fun (i : N) (xs : list Word) =>\n          match M.find (plusPtr d (d0 + i)) (bytes (snd r_n)) with\n          | Some w => w\n          | None => Zero\n          end :: xs).\n        finish honing.\n      intros.\n      f_equal.\n      rewrite H2.\n      reflexivity.\n\n    simpl in *; intuition.\n  }\n\n  (* refine method writeS. *)\n  {\n    refine pick val\n       (fst r_n,\n        {| resvs := resvs (snd r_n)\n         ; bytes := load_into_map (plusPtr d d0) d1 (bytes (snd r_n)) |}).\n      finish honing.\n\n    simpl in *; intuition.\n    apply load_into_map_Proper; auto.\n    reflexivity.\n  }\n\n  constructor.\n  finish_SharpeningADT_WithoutDelegation.\nDefined.\n\nEnd HeapCanonical.\n", "meta": {"author": "jwiegley", "repo": "bytestring-fiat", "sha": "109d3abcae4ffe02ff8ba173887259f42138dea8", "save_path": "github-repos/coq/jwiegley-bytestring-fiat", "path": "github-repos/coq/jwiegley-bytestring-fiat/bytestring-fiat-109d3abcae4ffe02ff8ba173887259f42138dea8/src/HeapCanon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23918060086456247}}
{"text": "Require Import Coq.Reals.Rdefinitions.\nRequire Import Coq.Reals.Rbasic_fun.\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Lists.ListSet.\nRequire Import ChargeCore.Tactics.Lemmas.\nRequire Import ChargeCore.Tactics.Indexed.\nRequire Import ExtLib.Tactics.\nRequire Import Logic.Logic.\nRequire Import Logic.ProofRules.\nRequire Import Logic.ArithFacts.\nRequire Import Logic.Automation.\nRequire Import Logic.EnabledLemmas.\nRequire Import Logic.Inductively.\n\nLocal Open Scope HP_scope.\nLocal Open Scope string_scope.\n\n(** TODO: Move this **)\nLemma land_dup : forall A : Formula, A -|- A //\\\\ A.\nProof. intros; split; charge_tauto. Qed.\n\n\n(* Adds time derivative to an Evolution.\n * - the global time is stored in [t]\n * - the time until the next discrete step is stored in [T]\n *)\nDefinition mkEvolution (world : Evolution) : Evolution :=\n  fun st' => st' \"T\" = --1 //\\\\ world st'.\n\nDefinition World (world : Evolution) : Formula :=\n  Continuous (mkEvolution world) //\\\\ 0 < \"T\" //\\\\ 0 <= \"T\"!.\n\nDefinition TimeBound (d : R) : Formula :=\n  0 <= \"T\" <= d.\n\nDefinition Discr (Prog : ActionFormula) (d : R) : ActionFormula :=\n  Prog //\\\\ \"T\" = 0 //\\\\ 0 <= \"T\"! <= d.\n\nDefinition Sys (P : ActionFormula) (w : Evolution) (d : R) : ActionFormula :=\n  \"T\" <= d //\\\\ (Discr P d \\\\// World w).\n\nDefinition System (P : ActionFormula) (w : Evolution) (d : R) : ActionFormula :=\n  Sys P w d \\\\// (Enabled (Sys P w d) -->> lfalse).\n\nDefinition TimedPreserves (delta : R) (P : StateFormula) (A : ActionFormula) : Formula :=\n  Preserves (P //\\\\ 0 <= \"T\" <= delta) A.\n\nDefinition SysNeverStuck (delta : R) (I : StateFormula) (A : ActionFormula) : Formula :=\n  0 <= \"T\" <= delta //\\\\ I -->> Enabled A.\n\nGlobal Instance Proper_mkEvolution_lentails\n: Proper (lentails ==> lentails) mkEvolution.\nProof.\n  unfold mkEvolution. morphism_intro.\n  rewrite Evolution_lentails_lentails in H.\n  apply Evolution_lentails_lentails.\n  simpl in *. restoreAbstraction.\n  intros. rewrite H. reflexivity.\nQed.\n\nGlobal Instance Proper_mkEvolution_lequiv\n: Proper (lequiv ==> lequiv) mkEvolution.\nProof.\n  unfold mkEvolution. morphism_intro.\n  eapply Evolution_lequiv_lequiv.\n  intro.\n  eapply Evolution_lequiv_lequiv with (x:=x0) in H.\n  rewrite H. reflexivity.\nQed.\n\nGlobal Instance Proper_World_lequiv\n: Proper (lequiv ==> lequiv) World.\nProof.\n  unfold World; morphism_intro.\n  rewrite H. reflexivity.\nQed.\n\nGlobal Instance Proper_World_lentails\n: Proper (lentails ==> lentails) World.\nProof.\n  unfold World; morphism_intro.\n  rewrite H. reflexivity.\nQed.\n\nGlobal Instance Proper_Discr\n: Proper (lequiv ==> eq ==> lequiv) Discr.\nProof.\n  morphism_intro; unfold Discr.\n  subst. rewrite H. reflexivity.\nQed.\n\nGlobal Instance Proper_Sys_lequiv\n: Proper (lequiv ==> lequiv ==> eq ==> lequiv) Sys.\nProof.\n  unfold Sys, Discr, World. morphism_intro.\n  subst. rewrite H; clear H. rewrite H0; clear H0. reflexivity.\nQed.\n\nGlobal Instance Proper_Sys_lentails\n: Proper (lentails ==> lentails ==> eq ==> lentails) Sys.\nProof.\n  unfold Sys, Discr, World. morphism_intro.\n  subst. rewrite H; clear H. rewrite H0; clear H0. reflexivity.\nQed.\n\nGlobal Instance Proper_System_lequiv\n: Proper (lequiv ==> lequiv ==> eq ==> lequiv) System.\nProof.\n  unfold System, Discr, World. morphism_intro.\n  subst. rewrite H; clear H. rewrite H0; clear H0. reflexivity.\nQed.\n\nTheorem Preserves_Sys\n: forall P Prog IndInv (w : Evolution) (d:R),\n  (forall st', is_st_formula (w st')) ->\n  P //\\\\ IndInv //\\\\ 0 <= \"T\"! <= \"T\" //\\\\ \"T\" <= d (* This could be \"T\"! < \"T\" *)\n    //\\\\ World w |-- next IndInv ->\n  P //\\\\ IndInv //\\\\ \"T\" = 0 //\\\\ 0 <= \"T\"! <= d\n    //\\\\ Discr Prog d |-- next IndInv ->\n  P |-- Preserves IndInv (Sys Prog w d).\nProof.\n  intros P Prog IndInv world delta.\n  intros Hst_world Hworld Hdiscr.\n  unfold Preserves.\n  charge_revert.\n  charge_intros. unfold Sys.\n  decompose_hyps.\n  { rewrite <- Hdiscr. unfold Discr.\n    charge_tauto. }\n  { rewrite <- Hworld.\n    simpl. restoreAbstraction.\n    unfold World; repeat charge_split; try charge_tauto.\n    charge_assert (Exists T : R, \"T\" = T //\\\\ (\"T\") ! <= T).\n    { apply Exists_with_st with (t:=\"T\"). intros.\n      charge_intros. charge_split; [ charge_assumption | ].\n      eapply diff_ind with (G:=\"T\" <= x) (Hyps:=ltrue).\n      - compute; tauto.\n      - compute; tauto.\n      - charge_assumption.\n      - unfold mkEvolution.\n        intros. simpl. split; auto.\n      - simpl next. restoreAbstraction; charge_tauto.\n      - solve_linear.\n      - charge_tauto.\n      - solve_linear. }\n    { charge_intros.\n      charge_fwd.\n      solve_linear. } }\nQed.\n\nDefinition SafeAndReactive d (I : StateFormula) (S : ActionFormula)\n  : Formula :=\n  TimedPreserves d I S //\\\\ SysNeverStuck d I S.\n\nLemma SysSystem_TimedPreserves\n: forall G I P w d,\n  G |-- TimedPreserves d I (Sys P w d) ->\n  G |-- SysNeverStuck  d I (Sys P w d) ->\n  G |-- TimedPreserves d I (System P w d).\nProof.\n  intros. unfold SysNeverStuck, TimedPreserves, Preserves in *.\n  rewrite (land_dup G).\n  rewrite H at 1.\n  rewrite H0.\n  charge_revert.\n  unfold System.\n  charge_intros.\n  decompose_hyps.\n  - charge_tauto.\n  - charge_exfalso. charge_tauto.\nQed.\n\nTheorem SafeAndReactive_TimedPreserves\n: forall G I D w d,\n  G |-- SafeAndReactive d I (Sys D w d) ->\n  G |-- TimedPreserves d I (System D w d).\nProof.\n  intros. rewrite H. unfold SafeAndReactive.\n  apply SysSystem_TimedPreserves; charge_tauto.\nQed.\n\nTheorem SystemSys\n: forall G I P w d,\n    G |-- TimedPreserves d I (System P w d) ->\n    G |-- TimedPreserves d I (Sys P w d).\nProof.\n  unfold TimedPreserves, Preserves. intros.\n  rewrite H.\n  unfold System. charge_tauto.\nQed.\n\nDefinition SysDisjoin_simpl\n: forall D1 D2 W d,\n    Sys D1 W d \\\\// Sys D2 W d -|- Sys (D1 \\\\// D2) W d.\nProof.\n  unfold Sys. intros.\n  split.\n  { decompose_hyps; unfold Discr; charge_tauto. }\n  { unfold Discr. decompose_hyps; charge_tauto. }\nQed.\n\nTheorem SysDisjoin_compose\n: forall G D1 D2 w d P Q,\n    G |-- TimedPreserves d P (Sys D1 w d) ->\n    G |-- TimedPreserves d Q (Sys D2 w d) ->\n    G |-- TimedPreserves d (P \\\\// Q) (Sys ((P //\\\\ D1) \\\\// (Q //\\\\ D2)) w d).\nProof.\n  intros.\n  etransitivity.\n  2: eapply Proper_Preserves_lequiv.\n  3: symmetry; eapply SysDisjoin_simpl.\n  2: reflexivity.\n  rewrite land_dup.\n  rewrite H at 1; rewrite H0.\n  unfold TimedPreserves.\n  rewrite Preserves_Or.\n  unfold Preserves.\n  charge_intros.\n  simpl next; restoreAbstraction.\n  charge_assert (next P //\\\\ 0 <= (\"T\") ! //\\\\ (\"T\") ! <= d \\\\//\n                 next Q //\\\\ 0 <= (\"T\") ! //\\\\ (\"T\") ! <= d).\n  { charge_use.\n    - charge_revert. charge_revert. charge_clear.\n      charge_intros.\n      unfold Sys, Discr.\n      charge_cases; charge_tauto.\n    - charge_revert. charge_clear. charge_intros.\n      charge_cases; charge_tauto. }\n  { charge_clear. charge_intros; charge_cases; charge_tauto. }\nQed.\n\nTheorem NeverStuck_disjoin\n: forall G D1 D2 w d P Q,\n    is_st_formula P ->\n    is_st_formula Q ->\n    G |-- SysNeverStuck d P (Sys D1 w d) ->\n    G |-- SysNeverStuck d Q (Sys D2 w d) ->\n    G |-- SysNeverStuck d (P \\\\// Q) (Sys ((P //\\\\ D1) \\\\// (Q //\\\\ D2)) w d).\nProof.\n  unfold SysNeverStuck.\n  do 7 intro. intros Hst_P Hst_Q.\n  intros.\n  rewrite land_dup.\n  rewrite H at 1; rewrite H0.\n  rewrite <- SysDisjoin_simpl.\n  rewrite <- Enabled_or.\n  charge_intros. charge_cases.\n  - charge_left.\n    charge_assert (P //\\\\ Enabled (Sys D1 w d)); [ charge_tauto | ].\n    rewrite Enabled_and_push by assumption.\n    charge_clear.\n    charge_intro. apply Proper_Enabled_lentails.\n    unfold Sys, Discr. charge_cases; charge_tauto.\n  - charge_right.\n    charge_assert (Q //\\\\ Enabled (Sys D2 w d)); [ charge_tauto | ].\n    rewrite Enabled_and_push by assumption.\n    apply forget_prem.\n    charge_intro. apply Proper_Enabled_lentails.\n    unfold Sys, Discr. charge_cases; charge_tauto.\nQed.\n\n(* MOVE *)\nLemma mkEvolution_and\n: forall P Q, mkEvolution P //\\\\ mkEvolution Q -|- mkEvolution (P //\\\\ Q).\nProof.\n  unfold mkEvolution; simpl; intros.\n  eapply Evolution_lequiv_lequiv.\n  intros. Transparent ChargeCore.Logics.ILInsts.ILFun_Ops.\n  simpl. Opaque ChargeCore.Logics.ILInsts.ILFun_Ops.\n  restoreAbstraction.\n  split; charge_tauto.\nQed.\n\nDefinition SysCompose_simpl\n: forall D1 D2 W1 W2 d,\n    Sys (D1 //\\\\ D2) (W1 //\\\\ W2) d |-- Sys D1 W1 d //\\\\ Sys D2 W2 d.\nProof.\n  unfold Sys, Discr, World; intros.\n  { repeat charge_cases. charge_tauto.\n    charge_right. charge_right.\n    rewrite <- mkEvolution_and. rewrite Continuous_and.\n    charge_tauto. }\n(*\n  { repeat charge_cases.\n    - charge_tauto.\n    - charge_exfalso. solve_linear.\n    - charge_exfalso. solve_linear.\n    - charge_right. repeat charge_split; try charge_tauto.\n      charge_assert (Continuous (mkEvolution W1) //\\\\\n                     Continuous (mkEvolution W2)).\n      { charge_tauto. }\n      apply forget_prem.\n      rewrite Continuous_and_lequiv.\n      rewrite mkEvolution_and. charge_tauto. }\n*)\nQed.\n\nLemma Enabled_TimeBound :\n  forall d,\n    (d > 0)%R ->\n    |-- Enabled (next (TimeBound d)).\nProof.\n  intros. enable_ex_st. exists d. solve_linear.\nQed.\n\nDefinition SysRename_rule\n: forall D W d sigma sigma',\n    RenameMapOk sigma ->\n    sigma \"T\" = \"T\" ->\n    RenameDerivOk sigma sigma' ->\n    Sys (Rename sigma D)\n        (fun st' : state =>\n           Forall st'' : state,\n                         (Forall x : Var, st'' x = sigma' st' x) -->> Rename sigma (W st''))\n        d\n    |-- Rename sigma (Sys D W d).\nProof.\n  intros.\n  unfold Sys, Discr, World.\n  repeat first [ rewrite Rename_and\n               | rewrite Rename_or\n               | rewrite Rename_Comp by apply H ].\n  simpl; restoreAbstraction. rewrite H0.\n  charge_split; [ charge_assumption | ].\n  charge_cases; [ charge_left | charge_right ].\n  { simpl. restoreAbstraction. charge_tauto. }\n  { simpl. restoreAbstraction.\n    charge_split; try charge_tauto.\n    rewrite <- Rename_Continuous' by eassumption.\n    charge_assert (Continuous\n     (mkEvolution\n        (fun st' : state =>\n         Forall st'' : state,\n         (Forall x : Var, st'' x = sigma' st' x) -->> Rename sigma (W st'')))).\n    { charge_assumption. }\n    apply forget_prem.\n    charge_intros.\n    (** TODO: This is bad. *)\n    unfold Continuous.\n    repeat (apply lexistsL; intros).\n    charge_exists x. charge_exists x0.\n    repeat charge_split; try charge_assumption.\n    breakAbstraction.\n    intros.\n    forward_reason.\n    unfold is_solution in *.\n    destruct H3. exists x1.\n    unfold solves_diffeqs in *.\n    intros.\n    specialize (H3 _ H6).\n    revert H3. simpl.\n    intros. forward_reason.\n    split; eauto.\n    rewrite H7; clear H7.\n    rewrite <- H3; clear H3.\n    red in H1.\n    specialize (H1 _ x1).\n    destruct H1.\n    specialize (H1 \"T\" z).\n    rewrite <- H1.\n    unfold deriv_stateF.\n    generalize dependent (x3 \"T\").\n    rewrite H0. simpl. intros.\n    unfold Ranalysis1.derive.\n    eapply Ranalysis1.pr_nu.\n    auto. }\nQed.\n\nDefinition Sys_rename_formula\n: forall D W d sigma sigma',\n      RenameMapOk sigma ->\n      st_term_renamings D ->\n      (forall st', st_term_renamings (W st')) ->\n    Sys (rename_formula sigma D)\n        (fun st' : state =>\n           Forall st'' : state,\n                         (Forall x : Var, st'' x = sigma' st' x) -->> rename_formula sigma (W st''))\n        d |--\n    Sys (Rename sigma D)\n        (fun st' : state =>\n           Forall st'' : state,\n                         (Forall x : Var, st'' x = sigma' st' x) -->> Rename sigma (W st''))\n        d.\nProof.\n  intros. unfold Sys.\n  charge_split.\n  { charge_assumption. }\n  { charge_revert. charge_clear.\n    charge_intros. apply lorL.\n    { apply lorR1.\n      rewrite Rename_ok; [ reflexivity | assumption | assumption ]. }\n    { apply lorR2.\n      apply Proper_World_lentails.\n      apply Evolution_lentails_lentails.\n      intros.\n      apply lforall_lentails_m.\n      red. intros.\n      rewrite Rename_ok; [ reflexivity | auto | assumption ]. } }\nQed.\n\nLtac sysrename_side_cond :=\n  match goal with\n  | [ |- forall _ : state, is_st_formula _ ]\n    => tlaIntuition; abstract is_st_term_list\n  | [ |- NotRenamed _ _ ]\n    => reflexivity\n  | [ |- _ ] => apply deriv_term_list; reflexivity\n  end.\n\nTheorem SysNeverStuck_Sys : forall (d :R) I W D,\n    (d >= 0)%R ->\n    I //\\\\ \"T\" = 0 |-- Enabled (0 <= \"T\"! <= d //\\\\ D) ->\n    I //\\\\ 0 < \"T\" <= d |-- Enabled (World W) ->\n    |-- SysNeverStuck d I (Sys D W d).\nProof.\n  intros d I W D Hd. intros. unfold SysNeverStuck.\n  charge_intros.\n  charge_assert (\"T\" = 0 \\\\// 0 < \"T\" <= d).\n  { solve_linear. }\n  charge_revert.\n  charge_clear.\n  charge_intros. charge_cases.\n  { unfold Sys.\n    rewrite <- Enabled_and_push by (compute; tauto).\n    charge_split; [ solve_linear | ].\n    rewrite <- EnabledLemmas.Enabled_or.\n    charge_left. unfold Discr.\n    rewrite (landC D). repeat rewrite landA.\n    rewrite <- Enabled_and_push by (compute; tauto).\n    charge_split; [ charge_assumption | ].\n    simpl in *. restoreAbstraction. repeat rewrite <- landA.\n    eassumption. }\n  { unfold Sys.\n    rewrite <- Enabled_and_push by (compute; tauto).\n    charge_split;\n      [ simpl; restoreAbstraction; charge_assumption | ].\n    rewrite <- EnabledLemmas.Enabled_or.\n    charge_right. assumption. }\nQed.\n\nTheorem SysNeverStuck_Sys' : forall (d :R) I W D,\n    is_st_formula I ->\n    (d >= 0)%R ->\n    |-- Enabled (I -->> \"T\" = 0 -->> 0 <= \"T\"! <= d //\\\\ D) ->\n    |-- Enabled (I -->> 0 < \"T\" <= d -->> World W) ->\n    |-- SysNeverStuck d I (Sys D W d).\nProof.\n  intros. eapply SysNeverStuck_Sys; eauto.\n  - do 2 charge_revert.\n    repeat (rewrite <- Enabled_limpl_st; [ | refine _ ]).\n    assumption.\n  - do 2 charge_revert.\n    repeat (rewrite <- Enabled_limpl_st; [ | refine _ ]).\n    assumption.\nQed.\n\n(** TODO: Move Up **)\nLemma TimedPreserves_And_simple\n  : forall d I1 I2 A B,\n    is_st_formula I1 -> is_st_formula I2 ->\n    TimedPreserves d I1 A //\\\\ TimedPreserves d I2 B\n                   |-- TimedPreserves d (I1 //\\\\ I2) (A //\\\\ B).\nProof.\n  intros. unfold TimedPreserves.\n  rewrite Preserves_And_simple.\n  eapply Preserves_equiv.\n  { simpl; tauto. }\n  { simpl; tauto. }\n  { split; charge_tauto. }\n  { reflexivity. }\nQed.\n\nLemma TimedPreserves_And\n  : forall (d : R) (I1 I2 : StateFormula) (A B : ActionFormula),\n   is_st_formula I1 ->\n   is_st_formula I2 ->\n   TimedPreserves d I1 ((I2 //\\\\ TimeBound d) //\\\\ A) //\\\\\n   TimedPreserves d I2 ((I1 //\\\\ TimeBound d) //\\\\ B)\n   |-- TimedPreserves d (I1 //\\\\ I2) (A //\\\\ B).\nProof.\n  intros. unfold TimedPreserves, TimeBound.\n  rewrite Preserves_And.\n  eapply Preserves_equiv.\n  { simpl; tauto. }\n  { simpl; tauto. }\n  { split; charge_tauto. }\n  { reflexivity. }\nQed.\n\nLemma TimedPreserves_intro\n  : forall (d : R) (I P G : Formula) (A : ActionFormula),\n    G //\\\\ P |-- TimedPreserves d I A ->\n    G |-- TimedPreserves d I (P //\\\\ A).\nProof.\n  unfold TimedPreserves. intros.\n  apply Preserves_intro; assumption.\nQed.\n\nGlobal Instance Proper_TimedPreserves_lentails\n  : Proper (eq ==> eq ==> lentails --> lentails) TimedPreserves.\nProof.\n  morphism_intro. unfold Basics.flip in *.\n  unfold TimedPreserves. subst. rewrite H1. reflexivity.\nQed.\n\nGlobal Instance Proper_TimedPreserves_lequiv\n  : Proper (eq ==> eq ==> lequiv ==> lequiv) TimedPreserves.\nProof.\n  morphism_intro. unfold Basics.flip in *.\n  unfold TimedPreserves. subst. rewrite H1. reflexivity.\nQed.\n\n\nLemma TimedPreserves_Rename\n  : forall d (sigma : RenameMap) I A,\n    sigma \"T\" = \"T\" ->\n    RenameMapOk sigma ->\n    TimedPreserves d (Rename sigma I) (Rename sigma A) -|- Rename sigma (TimedPreserves d I A).\nProof.\n  unfold TimedPreserves, Preserves. intros.\n  simpl next. restoreAbstraction.\n  autorewrite with rw_rename.\n  simpl rename_formula. rewrite H. simpl next_term. restoreAbstraction. reflexivity.\nQed.\n\n\n(** \"Parsing\" of [Sys] allows us to recover the benefits of the\n ** deep embedding.\n **)\n\nInductive SysParse (D : ActionFormula) (w : Evolution) (d : R)\n: ActionFormula -> Prop :=\n| Parsed : SysParse D w d (Sys D w d).\n\nExisting Class SysParse.\nExisting Instance Parsed.\n\n(* Some projection functions. *)\nDefinition Sys_D (A : ActionFormula)\n           {D w d} {SP : SysParse D w d A} : ActionFormula := D.\nArguments Sys_D _ {_ _ _ _} : clear implicits.\n\nDefinition Sys_w (A : ActionFormula)\n           {D w d} {SP : SysParse D w d A} : Evolution := w.\nArguments Sys_w _ {_ _ _ _} _ : clear implicits.\n\nDefinition Sys_d (A : ActionFormula)\n           {D w d} {SP : SysParse D w d A} : R := d.\nArguments Sys_d _ {_ _ _ _} : clear implicits.\n\nDefinition SysRename (sigma : RenameMap) (sigma' : RenameMapDeriv)\n           (A : ActionFormula) {D w d} {SP : SysParse D w d A}\n  : ActionFormula :=\n    Sys (rename_formula sigma D)\n        (fun st' : state =>\n           Forall st'' : state,\n             (Forall x : Var, st'' x = sigma' st' x) -->>\n             rename_formula sigma (w st''))\n        d.\nArguments SysRename _ _ _ {_ _ _ _} : clear implicits.\n\nDefinition SysCompose (A : ActionFormula) (B : ActionFormula)\n           {DA DB wA wB d} {SP_A : SysParse DA wA d A}\n           {SP_B : SysParse DB wB d B}\n  : ActionFormula :=\n  Sys (DA //\\\\ DB) (wA //\\\\ wB) d.\nArguments SysCompose _ _ {_ _ _ _ _ _ _} : clear implicits.\n\nDefinition SysDisjoin (IA : StateFormula) (A : ActionFormula)\n           (IB : StateFormula) (B : ActionFormula)\n           {DA DB w d} {SP_A : SysParse DA w d A}\n           {SP_B : SysParse DB w d B}\n  : ActionFormula :=\n  Sys ((IA //\\\\ DA) \\\\// (IB //\\\\ DB)) w d.\nArguments SysDisjoin _ _ _ _ {_ _ _ _ _ _} : clear implicits.\n\nDefinition SysSystem (A : ActionFormula)\n           {D w d} {SP : SysParse D w d A} : ActionFormula :=\n  System D w d.\nArguments SysSystem _ {_ _ _ _} : clear implicits.\n\nLemma SysCompose_abstract :\n  forall A B {DA DB wA wB d} {SP_A : SysParse DA wA d A}\n         {SP_B : SysParse DB wB d B},\n    SysCompose A B |-- A.\nProof.\n  intros. unfold SysCompose. rewrite SysCompose_simpl.\n  inversion SP_A. charge_tauto.\nQed.\n\nTheorem SysDisjoin_SafeAndReactive :\n  forall DA DB w d IA IB G,\n    is_st_formula IA ->\n    is_st_formula IB ->\n    G |-- SafeAndReactive d IA (Sys DA w d) ->\n    G |-- SafeAndReactive d IB (Sys DB w d) ->\n    G |-- SafeAndReactive d (IA \\\\// IB)\n                  (SysDisjoin IA (Sys DA w d) IB (Sys DB w d)).\nProof.\n  unfold SafeAndReactive. intros. charge_split.\n  { apply SysDisjoin_compose; [ rewrite H1 | rewrite H2 ];\n    charge_tauto. }\n  { apply NeverStuck_disjoin; try assumption;\n    [ rewrite H1 | rewrite H2 ];\n    charge_tauto. }\nQed.\n", "meta": {"author": "dricketts", "repo": "quadcopter", "sha": "62bb21915612a141e1ffabc73df3dc2d931c54ce", "save_path": "github-repos/coq/dricketts-quadcopter", "path": "github-repos/coq/dricketts-quadcopter/quadcopter-62bb21915612a141e1ffabc73df3dc2d931c54ce/examples/System.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23918059505750583}}
{"text": "(** * Functoriality of the construction of adjunctions *)\nRequire Import Category.Core Functor.Core NaturalTransformation.Core.\nRequire Import Functor.Identity Functor.Composition.Core.\nRequire Import NaturalTransformation.Composition.Core NaturalTransformation.Composition.Laws.\nRequire Import NaturalTransformation.Identity.\nRequire Import NaturalTransformation.Paths.\nRequire Import Functor.Dual NaturalTransformation.Dual Category.Dual.\nRequire Import Adjoint.Core Adjoint.UnitCounit Adjoint.UnitCounitCoercions Adjoint.Dual.\nRequire Import Adjoint.Composition.Core.\nRequire Import Adjoint.Functorial.Parts.\nRequire Import HProp Types.Sigma HoTT.Tactics.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope natural_transformation_scope.\nLocal Open Scope morphism_scope.\n\nSection laws.\n  (** Some tactics to handle all the proofs.  The tactics deal with\n      the \"obvious\" commutativity requirements by writing back and\n      forth with associativity and respectfulness of composition,\n      trying to find applications of the adjunction laws. *)\n  Local Ltac try_various_ways tac :=\n    progress repeat first [ progress tac\n                          | rewrite <- ?Functor.Core.composition_of;\n                            progress try_associativity_quick tac\n                          | rewrite -> ?Functor.Core.composition_of;\n                            progress try_associativity_quick tac ].\n\n  (** This is suboptimal, because we keep rewriting back and forth\n      with associativity and [composition_of].  But it only takes 0.74\n      seconds total, so it's probably not worth optimizing. *)\n  Local Ltac handle_laws' :=\n    idtac;\n    match goal with\n      | _ => reflexivity\n      | _ => progress rewrite ?identity_of, ?Category.Core.left_identity, ?Category.Core.right_identity\n      | _ => try_various_ways ltac:(f_ap)\n      | [ |- context[components_of ?T ?x] ]\n        => try_various_ways ltac:(simpl rewrite <- (commutes T))\n      | [ |- context[unit ?A] ]\n        => try_various_ways ltac:(rewrite (unit_counit_equation_1 A))\n      | [ |- context[unit ?A] ]\n        => try_various_ways ltac:(rewrite (unit_counit_equation_2 A))\n    end.\n\n  Local Ltac t :=\n    apply path_natural_transformation; intro;\n    cbn;\n    repeat handle_laws'.\n\n  Section left.\n    Local Arguments unit : simpl never.\n    Local Arguments counit : simpl never.\n\n    Section identity_of.\n      Context `{Funext}.\n      Variables C D : PreCategory.\n\n      Variable G : Functor D C.\n      Variable F : Functor C D.\n      Variable A : F -| G.\n\n      Definition left_identity_of\n      : @left_morphism_of C C 1 D D 1 G F A G F A 1\n        = ((left_identity_natural_transformation_2 _)\n             o (right_identity_natural_transformation_1 _))%natural_transformation.\n      Proof. t. Qed.\n\n      Definition left_identity_of_nondep\n      : @left_morphism_of_nondep C D G F A G F A 1 = 1%natural_transformation.\n      Proof. t. Qed.\n    End identity_of.\n\n    Section composition_of_dep.\n      Context `{Funext}.\n      Variables C C' C'' : PreCategory.\n      Variable CF : Functor C C'.\n      Variable CF' : Functor C' C''.\n      Variables D D' D'' : PreCategory.\n      Variable DF : Functor D D'.\n      Variable DF' : Functor D' D''.\n\n      Variable G : Functor D C.\n      Variable F : Functor C D.\n      Variable A : F -| G.\n      Variable G' : Functor D' C'.\n      Variable F' : Functor C' D'.\n      Variable A' : F' -| G'.\n      Variable G'' : Functor D'' C''.\n      Variable F'' : Functor C'' D''.\n      Variable A'' : F'' -| G''.\n      Variable T : NaturalTransformation (CF o G) (G' o DF).\n      Variable T' : NaturalTransformation (CF' o G') (G'' o DF').\n\n      Local Open Scope natural_transformation_scope.\n\n      Definition left_composition_of\n      : (@left_morphism_of\n           _ _ _ _ _ _ _ _\n           A _ _ A''\n           ((associator_1 _ _ _)\n              o (T' oR DF)\n              o (associator_2 _ _ _)\n              o (CF' oL T)\n              o (associator_1 _ _ _)))\n        = (associator_2 _ _ _)\n            o (DF' oL left_morphism_of A A' T)\n            o (associator_1 _ _ _)\n            o (left_morphism_of A' A'' T' oR CF)\n            o (associator_2 _ _ _).\n      Proof. t. Qed.\n    End composition_of_dep.\n\n    Section composition_of.\n      Context `{Funext}.\n      Variables C D : PreCategory.\n\n      Variable G : Functor D C.\n      Variable F : Functor C D.\n      Variable A : F -| G.\n      Variable G' : Functor D C.\n      Variable F' : Functor C D.\n      Variable A' : F' -| G'.\n      Variable G'' : Functor D C.\n      Variable F'' : Functor C D.\n      Variable A'' : F'' -| G''.\n      Variable T : NaturalTransformation G G'.\n      Variable T' : NaturalTransformation G' G''.\n\n      Local Open Scope natural_transformation_scope.\n\n      Definition left_composition_of_nondep\n      : (@left_morphism_of_nondep _ _ _ _ A _ _ A'' (T' o T))\n        = ((left_morphism_of_nondep A A' T)\n             o (left_morphism_of_nondep A' A'' T')).\n      Proof. t. Qed.\n    End composition_of.\n  End left.\n\n  Section right.\n    Section identity_of.\n      Context `{Funext}.\n      Variables C D : PreCategory.\n\n      Variable F : Functor C D.\n      Variable G : Functor D C.\n      Variable A : F -| G.\n\n      Definition right_identity_of\n      : @right_morphism_of C C 1 D D 1 F G A F G A 1\n        = ((right_identity_natural_transformation_2 _)\n             o (left_identity_natural_transformation_1 _))%natural_transformation\n        := ap (@NaturalTransformation.Dual.opposite _ _ _ _)\n              (@left_identity_of _ _ _ F^op G^op A^op).\n\n      Definition right_identity_of_nondep\n      : @right_morphism_of_nondep C D F G A F G A 1 = 1%natural_transformation\n        := ap (@NaturalTransformation.Dual.opposite _ _ _ _)\n              (@left_identity_of_nondep _ _ _ F^op G^op A^op).\n    End identity_of.\n\n    Section composition_of_dep.\n      Context `{Funext}.\n      Variables C C' C'' : PreCategory.\n      Variable CF : Functor C C'.\n      Variable CF' : Functor C' C''.\n      Variables D D' D'' : PreCategory.\n      Variable DF : Functor D D'.\n      Variable DF' : Functor D' D''.\n\n      Variable F : Functor C D.\n      Variable G : Functor D C.\n      Variable A : F -| G.\n      Variable F' : Functor C' D'.\n      Variable G' : Functor D' C'.\n      Variable A' : F' -| G'.\n      Variable F'' : Functor C'' D''.\n      Variable G'' : Functor D'' C''.\n      Variable A'' : F'' -| G''.\n      Variable T : NaturalTransformation (F' o CF) (DF o F).\n      Variable T' : NaturalTransformation (F'' o CF') (DF' o F').\n\n      Local Open Scope natural_transformation_scope.\n\n      (** This is slow, at about 3.8 s.  It also requires the opposite\n          association to unify. *)\n      Definition right_composition_of\n      : right_morphism_of\n          A A''\n          ((associator_2 DF' DF F)\n             o ((DF' oL T)\n                  o ((associator_1 DF' F' CF)\n                       o ((T' oR CF)\n                            o (associator_2 F'' CF' CF)))))\n        = (associator_1 G'' DF' DF)\n            o ((right_morphism_of A' A'' T' oR DF)\n                 o ((associator_2 CF' G' DF)\n                      o ((CF' oL right_morphism_of A A' T)\n                           o (associator_1 CF' CF G))))\n        := ap (@NaturalTransformation.Dual.opposite _ _ _ _)\n              (@left_composition_of\n                 _ _ _ _ (DF^op) (DF'^op) _ _ _ (CF^op) (CF'^op)\n                 _ _ A^op _ _ A'^op _ _ A''^op T^op T'^op).\n    End composition_of_dep.\n\n    Section composition_of.\n      Context `{Funext}.\n      Variables C D : PreCategory.\n\n      Variable F : Functor C D.\n      Variable G : Functor D C.\n      Variable A : F -| G.\n      Variable F' : Functor C D.\n      Variable G' : Functor D C.\n      Variable A' : F' -| G'.\n      Variable F'' : Functor C D.\n      Variable G'' : Functor D C.\n      Variable A'' : F'' -| G''.\n      Variable T : NaturalTransformation F F'.\n      Variable T' : NaturalTransformation F' F''.\n\n      Local Open Scope natural_transformation_scope.\n\n      Definition right_composition_of_nondep\n      : (@right_morphism_of_nondep _ _ _ _ A'' _ _ A (T' o T))\n        = ((right_morphism_of_nondep A' A T)\n             o (right_morphism_of_nondep A'' A' T'))\n        := ap (@NaturalTransformation.Dual.opposite _ _ _ _)\n              (@left_composition_of_nondep _ _ _ _ _ A''^op _ _ A'^op _ _ A^op T'^op T^op).\n    End composition_of.\n  End right.\nEnd laws.\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Categories/Adjoint/Functorial/Laws.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23918059505750583}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import sha.sha.\nRequire Import sha.SHA256.\nRequire Import sha.sha_lemmas.\nRequire Import sha.spec_sha.\nLocal Open Scope nat.\nLocal Open Scope logic.\n\nLemma body_SHA256_Init: semax_body Vprog Gtot f_SHA256_Init SHA256_Init_spec.\nProof.\nstart_function.\nname c_ _c.\nunfold data_at_.\n(* BEGIN: without these lines, the \"do 8 forward\" takes 40 times as long. *)\nunfold field_at_.\nunfold_data_at (field_at _ _ _ _ _).\nsimpl fst; simpl snd.\n(* END: without these lines *)\nTime do 8 (forward; unfold upd_Znth, sublist; simpl app). (* 21 sec *)\nTime repeat forward. (* 14 sec *)\nExists (map Vint init_registers,\n      (Vint Int.zero, (Vint Int.zero, (list_repeat (Z.to_nat 64) Vundef, Vint Int.zero)))).\nunfold_data_at (data_at _ _ _ _).\nTime entailer!. (* 5.2 sec *)\nrepeat split; auto.\nunfold s256_h, fst, s256a_regs.\nrewrite hash_blocks_equation. reflexivity.\nunfold data_at. apply derives_refl'; f_equal.\nf_equal.\nsimpl.\nrepeat (apply f_equal2; [f_equal; apply int_eq_e; compute; reflexivity | ]); auto.\nTime Qed. (* 33.6 sec *)\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/sha/verif_sha_init.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23918058925044902}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import PromiseConsistent.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\n\nSet Implicit Arguments.\n\n\nSection SimulationThread.\n  Variable (lang_src lang_tgt:language).\n\n  Definition SIM_TERMINAL :=\n    forall (st_src:(Language.state lang_src)) (st_tgt:(Language.state lang_tgt)), Prop.\n\n  Definition SIM_THREAD :=\n    forall (sim_terminal: SIM_TERMINAL)\n      (st1_src:(Language.state lang_src)) (lc1_src:Local.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n      (st1_tgt:(Language.state lang_tgt)) (lc1_tgt:Local.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t), Prop.\n\n  Definition _sim_thread_step\n             (sim_thread: forall (st1_src:(Language.state lang_src)) (lc1_src:Local.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n                            (st1_tgt:(Language.state lang_tgt)) (lc1_tgt:Local.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t), Prop)\n             st1_src lc1_src sc1_src mem1_src\n             st1_tgt lc1_tgt sc1_tgt mem1_tgt\n    :=\n    forall pf_tgt e_tgt st3_tgt lc3_tgt sc3_tgt mem3_tgt\n      (STEP_TGT: Thread.step pf_tgt e_tgt\n                             (Thread.mk _ st1_tgt lc1_tgt sc1_tgt mem1_tgt)\n                             (Thread.mk _ st3_tgt lc3_tgt sc3_tgt mem3_tgt)),\n      <<FAILURE: Thread.steps_failure (Thread.mk _ st1_src lc1_src sc1_src mem1_src)>> \\/\n      exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n        <<FAILURE: e_tgt <> ThreadEvent.failure>> /\\\n        <<STEPS: rtc (@Thread.tau_step _)\n                     (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                     (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n        <<STEP_SRC: Thread.opt_step e_src\n                                    (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                                    (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n        <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n        <<SC3: TimeMap.le sc3_src sc3_tgt>> /\\\n        <<MEMORY3: sim_memory mem3_src mem3_tgt>> /\\\n        <<SIM: sim_thread st3_src lc3_src sc3_src mem3_src st3_tgt lc3_tgt sc3_tgt mem3_tgt>>.\n\n  Definition _sim_thread\n             (sim_thread: SIM_THREAD)\n             (sim_terminal: SIM_TERMINAL)\n             (st1_src:(Language.state lang_src)) (lc1_src:Local.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n             (st1_tgt:(Language.state lang_tgt)) (lc1_tgt:Local.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t): Prop :=\n    forall sc1_src mem1_src\n      sc1_tgt mem1_tgt\n      (SC: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY: sim_memory mem1_src mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc0_src sc1_src)\n      (SC_FUTURE_TGT: TimeMap.le sc0_tgt sc1_tgt)\n      (MEM_FUTURE_SRC: Memory.future_weak mem0_src mem1_src)\n      (MEM_FUTURE_TGT: Memory.future_weak mem0_tgt mem1_tgt)\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed mem1_tgt)\n      (CONS_TGT: Local.promise_consistent lc1_tgt),\n      <<TERMINAL:\n        forall (TERMINAL_TGT: (Language.is_terminal lang_tgt) st1_tgt),\n          <<FAILURE: Thread.steps_failure (Thread.mk _ st1_src lc1_src sc1_src mem1_src)>> \\/\n          exists st2_src lc2_src sc2_src mem2_src,\n            <<STEPS: rtc (@Thread.tau_step _)\n                         (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                         (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n            <<SC: TimeMap.le sc2_src sc1_tgt>> /\\\n            <<MEMORY: sim_memory mem2_src mem1_tgt>> /\\\n            <<TERMINAL_SRC: (Language.is_terminal lang_src) st2_src>> /\\\n            <<LOCAL: sim_local SimPromises.bot lc2_src lc1_tgt>> /\\\n            <<TERMINAL: sim_terminal st2_src st1_tgt>>>> /\\\n      <<CAP:\n        forall mem2_src\n          (CAP_SRC: Memory.cap (Local.promises lc1_src) mem1_src mem2_src),\n        exists mem2_tgt,\n          <<MEMORY: sim_memory mem2_src mem2_tgt>> /\\\n          <<CAP_TGT: Memory.cap (Local.promises lc1_tgt) mem1_tgt mem2_tgt>>>> /\\\n      <<PROMISES:\n        forall (PROMISES_TGT: (Local.promises lc1_tgt) = Memory.bot)\n          (NORESERVE: Memory.no_reserve mem1_tgt),\n          <<FAILURE: Thread.steps_failure (Thread.mk _ st1_src lc1_src sc1_src mem1_src)>> \\/\n          exists st2_src lc2_src sc2_src mem2_src,\n            <<STEPS: rtc (@Thread.tau_step _)\n                         (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                         (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n            <<PROMISES_SRC: (Local.promises lc2_src) = Memory.bot>>>> /\\\n      <<STEP: _sim_thread_step (sim_thread sim_terminal)\n                               st1_src lc1_src sc1_src mem1_src\n                               st1_tgt lc1_tgt sc1_tgt mem1_tgt>>.\n\n  Lemma _sim_thread_mon: monotone9 _sim_thread.\n  Proof.\n    ii. exploit IN; try apply SC; eauto. i. des.\n    splits; eauto. ii.\n    exploit STEP; eauto. i. des; eauto.\n    right. esplits; eauto.\n  Qed.\n  #[local]\n  Hint Resolve _sim_thread_mon: paco.\n\n  Definition sim_thread: SIM_THREAD := paco9 _sim_thread bot9.\n\n  Lemma sim_thread_mon\n        sim_terminal1 sim_terminal2\n        (SIM: sim_terminal1 <2= sim_terminal2):\n    sim_thread sim_terminal1 <8= sim_thread sim_terminal2.\n  Proof.\n    pcofix CIH. i. punfold PR. pfold. ii.\n    exploit PR; try apply SC; eauto. i. des.\n    splits; auto.\n    - i. exploit TERMINAL; eauto. i. des; eauto.\n      right. esplits; eauto.\n    - ii. exploit STEP; eauto. i. des; eauto.\n      inv SIM0; [|done].\n      right. esplits; eauto.\n  Qed.\nEnd SimulationThread.\n#[export]\nHint Resolve _sim_thread_mon: paco.\n\n\nLemma sim_thread_step\n      lang_src lang_tgt\n      sim_terminal\n      pf_tgt e_tgt\n      st1_src lc1_src sc1_src mem1_src\n      st1_tgt lc1_tgt sc1_tgt mem1_tgt\n      st3_tgt lc3_tgt sc3_tgt mem3_tgt\n      (STEP: @Thread.step lang_tgt pf_tgt e_tgt\n                          (Thread.mk _ st1_tgt lc1_tgt sc1_tgt mem1_tgt)\n                          (Thread.mk _ st3_tgt lc3_tgt sc3_tgt mem3_tgt))\n      (SC: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY: sim_memory mem1_src mem1_tgt)\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed mem1_tgt)\n      (CONS_TGT: Local.promise_consistent lc3_tgt)\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src st1_tgt lc1_tgt sc1_tgt mem1_tgt):\n  <<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src sc1_src mem1_src)>> \\/\n  exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n    <<FAILURE: e_tgt <> ThreadEvent.failure>> /\\\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<STEP: Thread.opt_step e_src\n                            (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                            (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n    <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n    <<SC: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEMORY: sim_memory mem3_src mem3_tgt>> /\\\n    <<WF_SRC: Local.wf lc3_src mem3_src>> /\\\n    <<WF_TGT: Local.wf lc3_tgt mem3_tgt>> /\\\n    <<SC_SRC: Memory.closed_timemap sc3_src mem3_src>> /\\\n    <<SC_TGT: Memory.closed_timemap sc3_tgt mem3_tgt>> /\\\n    <<MEM_SRC: Memory.closed mem3_src>> /\\\n    <<MEM_TGT: Memory.closed mem3_tgt>> /\\\n    <<SIM: sim_thread sim_terminal st3_src lc3_src sc3_src mem3_src st3_tgt lc3_tgt sc3_tgt mem3_tgt>>.\nProof.\n  hexploit step_promise_consistent; eauto. s. i.\n  punfold SIM. exploit SIM; eauto; try refl. i. des.\n  exploit Thread.step_future; eauto. s. i. des.\n  exploit STEP0; eauto. i. des; eauto.\n  inv SIM0; [|done]. right.\n  exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n  exploit Thread.opt_step_future; eauto. s. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_thread_opt_step\n      lang_src lang_tgt\n      sim_terminal\n      e_tgt\n      st1_src lc1_src sc1_src mem1_src\n      st1_tgt lc1_tgt sc1_tgt mem1_tgt\n      st3_tgt lc3_tgt sc3_tgt mem3_tgt\n      (STEP: @Thread.opt_step lang_tgt e_tgt\n                              (Thread.mk _ st1_tgt lc1_tgt sc1_tgt mem1_tgt)\n                              (Thread.mk _ st3_tgt lc3_tgt sc3_tgt mem3_tgt))\n      (SC: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY: sim_memory mem1_src mem1_tgt)\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed mem1_tgt)\n      (CONS_TGT: Local.promise_consistent lc3_tgt)\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src st1_tgt lc1_tgt sc1_tgt mem1_tgt):\n  <<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src sc1_src mem1_src)>> \\/\n  exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n    <<FAILURE: e_tgt <> ThreadEvent.failure>> /\\\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<STEP: Thread.opt_step e_src\n                            (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                            (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n    <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n    <<SC: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEMORY: sim_memory mem3_src mem3_tgt>> /\\\n    <<WF_SRC: Local.wf lc3_src mem3_src>> /\\\n    <<WF_TGT: Local.wf lc3_tgt mem3_tgt>> /\\\n    <<SC_SRC: Memory.closed_timemap sc3_src mem3_src>> /\\\n    <<SC_TGT: Memory.closed_timemap sc3_tgt mem3_tgt>> /\\\n    <<MEM_SRC: Memory.closed mem3_src>> /\\\n    <<MEM_TGT: Memory.closed mem3_tgt>> /\\\n    <<SIM: sim_thread sim_terminal st3_src lc3_src sc3_src mem3_src st3_tgt lc3_tgt sc3_tgt mem3_tgt>>.\nProof.\n  inv STEP.\n  - right. esplits; eauto; ss. econs 1.\n  - eapply sim_thread_step; eauto.\nQed.\n\nLemma sim_thread_rtc_step\n      lang_src lang_tgt\n      sim_terminal\n      st1_src lc1_src sc1_src mem1_src\n      e1_tgt e2_tgt\n      (STEPS: rtc (@Thread.tau_step lang_tgt) e1_tgt e2_tgt)\n      (SC: TimeMap.le sc1_src (Thread.sc e1_tgt))\n      (MEMORY: sim_memory mem1_src (Thread.memory e1_tgt))\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed (Thread.memory e1_tgt))\n      (CONS_TGT: Local.promise_consistent (Thread.local e2_tgt))\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src (Thread.state e1_tgt) (Thread.local e1_tgt) (Thread.sc e1_tgt) (Thread.memory e1_tgt)):\n  <<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src sc1_src mem1_src)>> \\/\n  exists st2_src lc2_src sc2_src mem2_src,\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<SC: TimeMap.le sc2_src (Thread.sc e2_tgt)>> /\\\n    <<MEMORY: sim_memory mem2_src (Thread.memory e2_tgt)>> /\\\n    <<WF_SRC: Local.wf lc2_src mem2_src>> /\\\n    <<WF_TGT: Local.wf (Thread.local e2_tgt) (Thread.memory e2_tgt)>> /\\\n    <<SC_SRC: Memory.closed_timemap sc2_src mem2_src>> /\\\n    <<SC_TGT: Memory.closed_timemap (Thread.sc e2_tgt) (Thread.memory e2_tgt)>> /\\\n    <<MEM_SRC: Memory.closed mem2_src>> /\\\n    <<MEM_TGT: Memory.closed (Thread.memory e2_tgt)>> /\\\n    <<SIM: sim_thread sim_terminal st2_src lc2_src sc2_src mem2_src (Thread.state e2_tgt) (Thread.local e2_tgt) (Thread.sc e2_tgt) (Thread.memory e2_tgt)>>.\nProof.\n  revert SC MEMORY WF_SRC WF_TGT SC_SRC SC_TGT MEM_SRC MEM_TGT SIM.\n  revert st1_src lc1_src sc1_src mem1_src.\n  induction STEPS; i.\n  { right. esplits; eauto. }\n  inv H. inv TSTEP. destruct x, y. ss.\n  exploit Thread.step_future; eauto. s. i. des.\n  hexploit rtc_tau_step_promise_consistent; eauto. s. i.\n  exploit sim_thread_step; eauto. i. des; eauto.\n  exploit IHSTEPS; eauto. i. des.\n  - left. inv FAILURE0. des.\n    unfold Thread.steps_failure. esplits; [|eauto].\n    etrans; eauto. etrans; eauto. inv STEP0; eauto.\n    econs 2; eauto. econs.\n    + econs. eauto.\n    + destruct e, e_src; ss.\n  - right. destruct z. ss.\n    esplits; try apply MEMORY1; eauto.\n    etrans; [eauto|]. etrans; [|eauto]. inv STEP0; eauto.\n    econs 2; eauto. econs.\n    + econs. eauto.\n    + destruct e, e_src; ss.\nQed.\n\nLemma sim_thread_plus_step\n      lang_src lang_tgt\n      sim_terminal\n      pf_tgt e_tgt\n      st1_src lc1_src sc1_src mem1_src\n      e1_tgt e2_tgt e3_tgt\n      (STEPS: rtc (@Thread.tau_step lang_tgt) e1_tgt e2_tgt)\n      (STEP: @Thread.step lang_tgt pf_tgt e_tgt e2_tgt e3_tgt)\n      (SC: TimeMap.le sc1_src (Thread.sc e1_tgt))\n      (MEMORY: sim_memory mem1_src (Thread.memory e1_tgt))\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed (Thread.memory e1_tgt))\n      (CONS_TGT: Local.promise_consistent (Thread.local e3_tgt))\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src (Thread.state e1_tgt) (Thread.local e1_tgt) (Thread.sc e1_tgt) (Thread.memory e1_tgt)):\n  <<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src sc1_src mem1_src)>> \\/\n  exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n    <<FAILURE: e_tgt <> ThreadEvent.failure>> /\\\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<STEP: Thread.opt_step e_src\n                            (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                            (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n    <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n    <<SC: TimeMap.le sc3_src (Thread.sc e3_tgt)>> /\\\n    <<MEMORY: sim_memory mem3_src (Thread.memory e3_tgt)>> /\\\n    <<WF_SRC: Local.wf lc3_src mem3_src>> /\\\n    <<WF_TGT: Local.wf (Thread.local e3_tgt) (Thread.memory e3_tgt)>> /\\\n    <<SC_SRC: Memory.closed_timemap sc3_src mem3_src>> /\\\n    <<SC_TGT: Memory.closed_timemap (Thread.sc e3_tgt) (Thread.memory e3_tgt)>> /\\\n    <<MEM_SRC: Memory.closed mem3_src>> /\\\n    <<MEM_TGT: Memory.closed (Thread.memory e3_tgt)>> /\\\n    <<SIM: sim_thread sim_terminal st3_src lc3_src sc3_src mem3_src (Thread.state e3_tgt) (Thread.local e3_tgt) (Thread.sc e3_tgt) (Thread.memory e3_tgt)>>.\nProof.\n  destruct e1_tgt, e2_tgt, e3_tgt. ss.\n  exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n  hexploit step_promise_consistent; eauto. s. i.\n  exploit sim_thread_rtc_step; eauto. s. i. des; eauto.\n  exploit Thread.rtc_tau_step_future; try exact STEPS0; eauto. s. i. des.\n  exploit sim_thread_step; try exact STEP; try exact SIM0; eauto. s. i. des.\n  - left. inv FAILURE. des.\n    unfold Thread.steps_failure. esplits; [|eauto].\n    etrans; eauto.\n  - right. rewrite STEPS1 in STEPS0.\n    esplits; try exact STEPS0; try exact STEP0; eauto.\nQed.\n\nLemma sim_thread_future\n      lang_src lang_tgt\n      sim_terminal\n      st_src lc_src sc1_src sc2_src mem1_src mem2_src\n      st_tgt lc_tgt sc1_tgt sc2_tgt mem1_tgt mem2_tgt\n      (SIM: @sim_thread lang_src lang_tgt sim_terminal st_src lc_src sc1_src mem1_src st_tgt lc_tgt sc1_tgt mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc1_src sc2_src)\n      (SC_FUTURE_TGT: TimeMap.le sc1_tgt sc2_tgt)\n      (MEM_FUTURE_SRC: Memory.future_weak mem1_src mem2_src)\n      (MEM_FUTURE_TGT: Memory.future_weak mem1_tgt mem2_tgt):\n  sim_thread sim_terminal st_src lc_src sc2_src mem2_src st_tgt lc_tgt sc2_tgt mem2_tgt.\nProof.\n  pfold. ii.\n  punfold SIM. exploit SIM; (try by etrans; eauto); eauto.\nQed.\n\n\nLemma cap_property\n      mem1 mem2 lc sc\n      (CAP: Memory.cap (Local.promises lc) mem1 mem2)\n      (WF: Local.wf lc mem1)\n      (SC: Memory.closed_timemap sc mem1)\n      (CLOSED: Memory.closed mem1):\n  <<FUTURE: Memory.future_weak mem1 mem2>> /\\\n  <<WF: Local.wf lc mem2>> /\\\n  <<SC: Memory.closed_timemap sc mem2>> /\\\n  <<CLOSED: Memory.closed mem2>> /\\\n  <<NORESERVE: Memory.no_reserve_except (Local.promises lc) mem2>>.\nProof.\n  splits.\n  - eapply Memory.cap_future_weak; eauto.\n  - eapply Local.cap_wf; eauto.\n  - eapply Memory.cap_closed_timemap; eauto.\n  - eapply Memory.cap_closed; eauto.\n  - eapply Memory.cap_no_reserve_except; eauto. apply WF.\nQed.\n\nLemma sc_property\n      sc1 sc2 mem\n      (MAX: Memory.max_full_timemap mem sc2)\n      (SC1: Memory.closed_timemap sc1 mem)\n      (MEM: Memory.closed mem):\n  <<SC2: Memory.closed_timemap sc2 mem>> /\\\n  <<LE: TimeMap.le sc1 sc2>>.\nProof.\n  splits.\n  - eapply Memory.max_full_timemap_closed; eauto.\n  - eapply Memory.max_full_timemap_spec; eauto.\nQed.\n\nLemma sim_thread_consistent\n      lang_src lang_tgt\n      sim_terminal\n      st_src lc_src sc_src mem_src\n      st_tgt lc_tgt sc_tgt mem_tgt\n      (SIM: sim_thread sim_terminal st_src lc_src sc_src mem_src st_tgt lc_tgt sc_tgt mem_tgt)\n      (SC: TimeMap.le sc_src sc_tgt)\n      (MEMORY: sim_memory mem_src mem_tgt)\n      (WF_SRC: Local.wf lc_src mem_src)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src mem_src)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src)\n      (MEM_TGT: Memory.closed mem_tgt)\n      (CONSISTENT: Thread.consistent (Thread.mk lang_tgt st_tgt lc_tgt sc_tgt mem_tgt)):\n  Thread.consistent (Thread.mk lang_src st_src lc_src sc_src mem_src).\nProof.\n  hexploit consistent_promise_consistent; eauto. s. i.\n  generalize SIM. intro X.\n  punfold X. exploit X; eauto; try refl. i. des.\n  ii. ss.\n  exploit CAP; eauto. i. des.\n  exploit cap_property; try exact CAP0; eauto. i. des.\n  exploit cap_property; try exact CAP_TGT; eauto. i. des.\n  exploit Memory.max_full_timemap_exists; try apply CLOSED0. i. des.\n  exploit sim_memory_max_full_timemap; try exact MEMORY0; eauto. i. subst.\n  exploit sc_property; try exact SC_MAX; eauto. i. des.\n  exploit sc_property; try exact x0; eauto. i. des.\n  exploit CONSISTENT; eauto. s. i. des.\n  - left. inv FAILURE. des.\n    exploit sim_thread_future; try exact SIM; try exact LE; try exact LE0; eauto. i.\n    exploit sim_thread_plus_step; try exact STEPS; try exact FAILURE; try exact x2; eauto; try refl.\n    { inv FAILURE; inv STEP0. inv LOCAL. inv LOCAL0. ss. }\n    i. des; auto. ss.\n  - hexploit Local.bot_promise_consistent; eauto. i.\n    exploit sim_thread_future; try exact SIM; try exact LE; try exact LE0; eauto. i.\n    exploit sim_thread_rtc_step; try apply STEPS; try exact x1; eauto; try refl. i. des; eauto.\n    destruct e2. ss.\n    punfold SIM0. exploit SIM0; eauto; try refl. i. des.\n    hexploit Thread.rtc_tau_step_no_reserve_except; try exact STEPS; eauto. i.\n    unfold Thread.no_reserve_except in *. ss.\n    rewrite PROMISES0 in *.\n    hexploit Memory.no_reserve_except_bot_no_reserve; try apply MEM_TGT0; eauto. i.\n    exploit PROMISES1; eauto. i. des.\n    + left. unfold Thread.steps_failure in *. des.\n      esplits; [|eauto]. etrans; eauto.\n    + right. eexists (Thread.mk _ _ _ _ _). splits; [|eauto].\n      etrans; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising2-coq", "sha": "52dd46538036a7a69c132e89dd3e7698b5e2f830", "save_path": "github-repos/coq/snu-sf-promising2-coq", "path": "github-repos/coq/snu-sf-promising2-coq/promising2-coq-52dd46538036a7a69c132e89dd3e7698b5e2f830/src/opt/SimThread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.34864512179822543, "lm_q1q2_score": 0.2391529268120847}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.int_or_ptr.\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nInductive tree := \n| LEAF: forall i, 0 <= i <= Int.max_signed -> tree\n| NODE: tree -> tree -> tree.\n\nFixpoint treerep (t: tree) (p: val) : mpred :=\n  match t with\n  | LEAF i _ => !! (p = Vint (Int.repr (i+i+1))) && emp\n  | NODE t1 t2 => EX p1:val, EX p2: val,\n               data_at Tsh (Tstruct _tree noattr) (p1,p2) p\n              * treerep t1 p1 * treerep t2 p2\n  end.\n\nDefinition POINTER_BOUNDARY : Z := 1024.\n\nDefinition valid_int_or_ptr (x: val) :=\n match x with\n | Vint i => Int.testbit i 0 = true\n              \\/ Int.unsigned i < POINTER_BOUNDARY\n | Vptr b z => Ptrofs.testbit z 0 = false\n | _ => False\n end.\n\nLemma valid_int_or_ptr_ii1:\n forall i, valid_int_or_ptr (Vint (Int.repr (i + i + 1))).\nProof.\nintros.\nsimpl.\nleft.\nrewrite Int.unsigned_repr_eq.\nrewrite Zodd_mod.\napply Zeq_is_eq_bool.\nreplace (i+i) with (2*i)%Z by lia.\nrewrite <- Zmod_div_mod; try lia.\nrewrite Z.mul_comm, Z.add_comm.\nrewrite Z_mod_plus_full.\nreflexivity.\ncompute; reflexivity.\nexists (Z.div Int.modulus 2).\nreflexivity.\nQed.\n\n\nLemma valid_int_or_ptr_i2:\n forall i, 0 <= i < POINTER_BOUNDARY ->\n   valid_int_or_ptr (Vint (Int.repr i)).\nProof.\nintros.\nsimpl.\nright.\nunfold POINTER_BOUNDARY in *.\nrewrite Int.unsigned_repr by rep_lia.\nrep_lia.\nQed.\n\nLemma field_compatible_valid_int_or_ptr:\n  forall p, \n  field_compatible (Tstruct _tree noattr) [] p ->\n  valid_int_or_ptr p.\nProof.\nintros.\ndestruct H as [H1 [_ [_ [H2 _]]]].\ndestruct p; try contradiction.\nclear - H2; simpl in *.\n    rewrite Zodd_even_bool.\n    apply negb_false_iff.\n    apply Zeven_bool_iff.\n    inv H2.\n    1: inv H.\n    inv H1.\n    specialize (H5 _left _ _ eq_refl eq_refl).\n    inv H5.\n    inv H.\n    simpl in H0.\n    destruct H0 as [j H].\n    rewrite Z.add_0_r in H.\n    rewrite H; clear.\n    replace (j*4)%Z with (2*(2*j))%Z by lia.\n    apply Zeven_2p.\nQed.\n\nLemma treerep_local_facts:\n  forall t p,\n   treerep t p |--\n   !! (valid_int_or_ptr p).\nProof.\nintros.\ndestruct t; simpl.\nentailer!.\napply valid_int_or_ptr_ii1.\nIntros p1 p2.\nentailer!.\napply field_compatible_valid_int_or_ptr; auto.\nQed.\n\n#[export] Hint Resolve treerep_local_facts : saturate_local.\n\nDefinition test_int_or_ptr_spec :=\n DECLARE _test_int_or_ptr\n WITH x : val\n PRE [ int_or_ptr_type ]\n   PROP(valid_int_or_ptr x) PARAMS (x) SEP()\n POST [ tint ]\n   PROP() \n   RETURN (Vint (Int.repr (match x with\n                    | Vint _ => 1\n                    | _ => 0\n                    end)))\n   SEP().\n\nDefinition int_or_ptr_to_int_spec :=\n DECLARE _int_or_ptr_to_int\n WITH x : val\n PRE [ int_or_ptr_type ]\n   PROP(is_int I32 Signed x) PARAMS (x) SEP()\n POST [ tint ]\n   PROP() RETURN (x) SEP().\n\nDefinition int_or_ptr_to_ptr_spec :=\n DECLARE _int_or_ptr_to_ptr\n WITH x : val\n PRE [ int_or_ptr_type ]\n   PROP(isptr x) PARAMS (x) SEP()\n POST [ tptr tvoid ]\n   PROP() RETURN (x) SEP().\n\nDefinition int_to_int_or_ptr_spec :=\n DECLARE _int_to_int_or_ptr\n WITH x : val\n PRE [ tint ]\n   PROP(valid_int_or_ptr x) PARAMS(x) SEP()\n POST [ int_or_ptr_type ]\n   PROP() RETURN(x) SEP().\n\nDefinition ptr_to_int_or_ptr_spec :=\n DECLARE _ptr_to_int_or_ptr\n WITH x : val\n PRE [ tptr tvoid ]\n   PROP(valid_int_or_ptr x) PARAMS(x) SEP()\n POST [ int_or_ptr_type ]\n   PROP() RETURN(x) SEP().\n\nDefinition makenode_spec :=\n DECLARE _makenode \n  WITH p: val, q: val\n  PRE [ int_or_ptr_type, int_or_ptr_type ]\n    PROP() PARAMS(p; q) SEP()\n  POST [ tptr (Tstruct _tree noattr) ]\n    EX r:val, \n    PROP() RETURN (r) \n    SEP (data_at Tsh (Tstruct _tree noattr) (p,q) r).\n\nDefinition copytree_spec :=\n DECLARE _copytree\n  WITH t: tree, p : val\n  PRE  [ int_or_ptr_type ]\n    PROP() PARAMS (p) SEP (treerep t p)\n  POST [ int_or_ptr_type ]\n    EX v:val,\n    PROP() RETURN (v) \n    SEP (treerep t p; treerep t v).\n\nDefinition Gprog : funspecs :=\n    ltac:(with_library prog [\n    test_int_or_ptr_spec;\n    int_or_ptr_to_int_spec;\n    int_or_ptr_to_ptr_spec;\n    int_to_int_or_ptr_spec;\n    ptr_to_int_or_ptr_spec;\n    makenode_spec; copytree_spec\n  ]).\n\nLemma body_copytree: semax_body Vprog Gprog f_copytree copytree_spec.\nProof.\n  start_function.\n  assert_PROP (valid_int_or_ptr p) by entailer!.\n  destruct t.\n* (* LEAF *)\n unfold treerep.\n Intros. subst p.\n forward_call (Vint (Int.repr (i+i+1))).\n forward_if.\n - (* then clause *)\n   forward. simpl.\n   Exists (Vint (Int.repr(i+i+1))).\n   entailer!!.\n - (* else clause *)\n  inv H0.\n* (* NODE *) \n  unfold treerep; fold treerep.\n  rename p into t.\n  Intros p q.\n  forward_call t.\n  assert_PROP (isptr t) by entailer!.\n  destruct t; try contradiction. clear H0.\n  forward_if.\n  - (* then clause *)\n    contradiction.\n  - (* else clause *)\n   clear H0. simpl in H.\n   forward_call (Vptr b i).\n   forward.\n     entailer!.\n     destruct p; try contradiction; apply I.\n   forward_call (t1,p).\n   Intros p1.\n   deadvars.\n   forward.\n   forward.\n    entailer!.\n     destruct q; try contradiction; apply I.\n   forward_call (t2,q).\n   Intros p2.\n   forward.\n   deadvars.\n  assert_PROP (p1 <> Vundef).\n  entailer!.\n  assert_PROP (p2 <> Vundef).\n  entailer!.\n   forward_call (p1,p2).\n  Intros r.\n  assert_PROP (valid_int_or_ptr r). {\n    entailer!.\n    apply field_compatible_valid_int_or_ptr; auto.\n  }\n  forward_call r.\n  forward. simpl.\n  Exists r p q p1 p2.\n  entailer!!.\nQed.\n\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/verif_int_or_ptr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23914545451109065}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Linearization of the control-flow graph: \n    translation from LTL to LTLin *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Ordered.\nRequire Import FSets.\nRequire FSetAVL.\nRequire Import AST.\nRequire Import Values.\nRequire Import Globalenvs.\nRequire Import Errors.\nRequire Import Op.\nRequire Import Locations.\nRequire Import LTL.\nRequire Import LTLin.\nRequire Import Kildall.\nRequire Import Lattice.\n\nOpen Scope error_monad_scope.\n\n(** To translate from LTL to LTLin, we must lay out the nodes\n  of the LTL control-flow graph in some linear order, and insert\n  explicit branches and conditional branches to make sure that\n  each node jumps to its successors as prescribed by the\n  LTL control-flow graph.  However, branches are not necessary\n  if the fall-through behaviour of LTLin instructions already\n  implements the desired flow of control.  For instance,\n  consider the two LTL instructions\n<<\n    L1: Lop op args res L2\n    L2: ...\n>>\n  If the instructions [L1] and [L2] are laid out consecutively in the LTLin\n  code, we can generate the following LTLin code:\n<<\n    L1: Lop op args res\n    L2: ...\n>>\n  However, if this is not possible, an explicit [Lgoto] is needed:\n<<\n    L1: Lop op args res\n        Lgoto L2\n        ...\n    L2: ...\n>>\n  The main challenge in code linearization is therefore to pick a\n  ``good'' order for the nodes that exploits well the\n  fall-through behavior.  Many clever trace picking heuristics\n  have been developed for this purpose.  \n\n  In this file, we present linearization in a way that clearly\n  separates the heuristic part (choosing an order for the basic blocks)\n  from the actual code transformation parts.  We proceed in two passes:\n- Choosing an order for the nodes.  This returns an enumeration of CFG\n  nodes stating that they must be laid out in the order shown in the\n  list.\n- Generate LTLin code where each node branches explicitly to its\n  successors, except if one of these successors is the immediately\n  following instruction.\n\n  The beauty of this approach is that correct code is generated\n  under surprisingly weak hypotheses on the enumeration of\n  CFG nodes: it suffices that every reachable instruction occurs\n  exactly once in the enumeration.  We therefore follow an approach\n  based on validation a posteriori: a piece of untrusted Caml code\n  implements the node enumeration heuristics, and the resulting\n  enumeration is checked for correctness by Coq functions that are\n  proved to be sound.\n*)\n\n(** * Determination of the order of basic blocks *)\n\n(** We first compute a mapping from CFG nodes to booleans,\n  indicating whether a CFG instruction is reachable or not.\n  This computation is a trivial forward dataflow analysis\n  where the transfer function is the identity: the successors\n  of a reachable instruction are reachable, by the very\n  definition of reachability. *)\n\nModule DS := Dataflow_Solver(LBoolean)(NodeSetForward).\n\nDefinition reachable_aux (f: LTL.function) : option (PMap.t bool) :=\n  DS.fixpoint\n    (successors f)\n    (fun pc r => r)\n    ((f.(fn_entrypoint), true) :: nil).\n\nDefinition reachable (f: LTL.function) : PMap.t bool :=\n  match reachable_aux f with  \n  | None => PMap.init true\n  | Some rs => rs\n  end.\n\n(** We then enumerate the nodes of reachable instructions.\n  This task is performed by external, untrusted Caml code. *)\n\nParameter enumerate_aux: LTL.function -> PMap.t bool -> list node.\n\n(** Now comes the a posteriori validation of a node enumeration. *)\n\nModule Nodeset := FSetAVL.Make(OrderedPositive).\n\n(** Build a [Nodeset.t] from a list of nodes, checking that the list\n  contains no duplicates. *)\n\nFixpoint nodeset_of_list (l: list node) (s: Nodeset.t)\n                         {struct l}: res Nodeset.t :=\n  match l with\n  | nil => OK s\n  | hd :: tl =>\n      if Nodeset.mem hd s \n      then Error (msg \"Linearize: duplicates in enumeration\")\n      else nodeset_of_list tl (Nodeset.add hd s)\n  end.\n\nDefinition check_reachable_aux\n     (reach: PMap.t bool) (s: Nodeset.t)\n     (ok: bool) (pc: node) (i: LTL.instruction) : bool :=\n  if reach!!pc then ok && Nodeset.mem pc s else ok.\n\nDefinition check_reachable\n     (f: LTL.function) (reach: PMap.t bool) (s: Nodeset.t) : bool :=\n  PTree.fold (check_reachable_aux reach s) f.(LTL.fn_code) true.\n\nDefinition enumerate (f: LTL.function) : res (list node) :=\n  let reach := reachable f in\n  let enum := enumerate_aux f reach in\n  do s <- nodeset_of_list enum Nodeset.empty;\n  if check_reachable f reach s\n  then OK enum\n  else Error (msg \"Linearize: wrong enumeration\").\n\n(** * Translation from LTL to LTLin *)\n\n(** We now flatten the structure of the CFG graph, laying out\n  LTL instructions consecutively in the order computed by [enumerate],\n  and inserting branches to the labels of sucessors if necessary.\n  Whether to insert a branch or not is determined by\n  the [starts_with] function below.\n\n  For LTL conditional branches [Lcond cond args s1 s2],\n  we have two possible translations:\n<<\n      Lcond cond args s1;       or     Lcond (not cond) args s2;\n      Lgoto s2                         Lgoto s1\n>>\n  We favour the first translation if [s2] is the label of the\n  next instruction, and the second if [s1] is the label of the\n  next instruction, thus avoiding the insertion of a redundant [Lgoto]\n  instruction. *)\n\nFixpoint starts_with (lbl: label) (k: code) {struct k} : bool :=\n  match k with\n  | Llabel lbl' :: k' => if peq lbl lbl' then true else starts_with lbl k'\n  | _ => false\n  end.\n\nDefinition add_branch (s: label) (k: code) : code :=\n  if starts_with s k then k else Lgoto s :: k.\n\nDefinition linearize_instr (b: LTL.instruction) (k: code) : code :=\n  match b with\n  | LTL.Lnop s =>\n      add_branch s k\n  | LTL.Lop op args res s =>\n      Lop op args res :: add_branch s k\n  | LTL.Lload chunk addr args dst s =>\n      Lload chunk addr args dst :: add_branch s k\n  | LTL.Lstore chunk addr args src s =>\n      Lstore chunk addr args src :: add_branch s k\n  | LTL.Lcall sig ros args res s =>\n      Lcall sig ros args res :: add_branch s k\n  | LTL.Ltailcall sig ros args =>\n      Ltailcall sig ros args :: k\n  | LTL.Lbuiltin ef args res s =>\n      Lbuiltin ef args res :: add_branch s k\n  | LTL.Lcond cond args s1 s2 =>\n      if starts_with s1 k then\n        Lcond (negate_condition cond) args s2 :: add_branch s1 k\n      else\n        Lcond cond args s1 :: add_branch s2 k\n  | LTL.Ljumptable arg tbl =>\n      Ljumptable arg tbl :: k\n  | LTL.Lreturn or =>\n      Lreturn or :: k\n  end.\n\n(** Linearize a function body according to an enumeration of its nodes.  *)\n\nFixpoint linearize_body (f: LTL.function) (enum: list node)\n                        {struct enum} : code :=\n  match enum with\n  | nil => nil\n  | pc :: rem =>\n      match f.(LTL.fn_code)!pc with\n      | None => linearize_body f rem\n      | Some b => Llabel pc :: linearize_instr b (linearize_body f rem)\n      end\n  end.\n\n(** * Entry points for code linearization *)\n\nDefinition transf_function (f: LTL.function) : res LTLin.function :=\n  do enum <- enumerate f;\n  OK (mkfunction\n       (LTL.fn_sig f)\n       (LTL.fn_params f)\n       (LTL.fn_stacksize f)\n       (add_branch (LTL.fn_entrypoint f) (linearize_body f enum))).\n\nDefinition transf_fundef (f: LTL.fundef) : res LTLin.fundef :=\n  AST.transf_partial_fundef transf_function f.\n\nDefinition transf_program (p: LTL.program) : res LTLin.program :=\n  transform_partial_program transf_fundef p.\n", "meta": {"author": "Ptival", "repo": "compcert-alias", "sha": "c839efb9cd2a4c27add46a1868fe0444d1dfdd9e", "save_path": "github-repos/coq/Ptival-compcert-alias", "path": "github-repos/coq/Ptival-compcert-alias/compcert-alias-c839efb9cd2a4c27add46a1868fe0444d1dfdd9e/backend/Linearize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23914545451109062}}
{"text": "(* (c) Copyright 2006-2018 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrnat seq.\nFrom fourcolor Require Import cfmap cfreducible configurations present.\nFrom fourcolor Require Import task001to214 task215to234 task235to282.\nFrom fourcolor Require Import task283to302 task303to322 task323to485.\nFrom fourcolor Require Import task486to506 task507to541 task542to588.\nFrom fourcolor Require Import task589to633.\n\n(******************************************************************************)\n(*   C-reducibility of all the configurations in the_configs, collating the   *)\n(* proofs by reflection in all the [job|task]MMMtoMMM.v files.                *)\n(******************************************************************************)\n\nLemma the_reducibility : reducibility.\nProof.\nrewrite /reducibility; apply cat_reducible_range with 322.\n  CatReducible red000to214 red214to234 red234to282 red282to302 red302to322.\nCatReducible red322to485 red485to506 red506to541 red541to588 red588to633.\nQed.\n", "meta": {"author": "coq-community", "repo": "fourcolor", "sha": "e831b0b00e264285f91938917a0a5ef64ec1a829", "save_path": "github-repos/coq/coq-community-fourcolor", "path": "github-repos/coq/coq-community-fourcolor/fourcolor-e831b0b00e264285f91938917a0a5ef64ec1a829/theories/reducibility.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2391454545110906}}
{"text": "Require Import Coq.Program.Equality.\nRequire Import Coq.Sets.Ensembles.\n\nAdd LoadPath \".\" as Top0.\nRequire Import Top0.Tactics.\nRequire Import Top0.Keys.\nRequire Import Top0.Definitions.\nRequire Import Top0.Environment.\nRequire Import Top0.TypeSystem.\nRequire Import Top0.Heap.\nRequire Import Top0.CorrectnessLemmas.\nRequire Import Top0.AdditionalLemmas.\nRequire Import Top0.Axioms.\n\nModule EffectSoundness.\n\nImport TypeSoundness.\n\nLemma EmptyInNil:\n  forall st, Epsilon_Phi_Soundness (st, Phi_Nil).\nProof.\n  intros st. apply EPS. intros da HIn.\n  inversion  HIn.\nQed.\n  \nLemma sound_approx_inj :\n  forall (st1 st2 : Epsilon) (dy : Phi),\n    Epsilon_Phi_Soundness (st1, dy) ->\n    Epsilon_Phi_Soundness (Union StaticAction st1 st2, dy) /\\ Epsilon_Phi_Soundness (Union StaticAction st2 st1, dy).\nProof. \n  intros st1 st2 dy HSound; split; inversion HSound as [ ? ? H' ]; subst; constructor;\n  intros da HIn; apply H' in HIn; destruct HIn as [ca HIn]; exists ca; intuition.\nQed.\n\nLemma sound_comp :\n  forall (st1 st2 : Epsilon) (dy1 dy2 : Phi),\n    Epsilon_Phi_Soundness (st1, dy1) -> Epsilon_Phi_Soundness (st2, dy2) ->\n    Epsilon_Phi_Soundness (Union StaticAction st1 st2, Phi_Seq dy1 dy2). \nProof.\n  intros st1 st2 dy1 dy2 H1 H2.\n  inversion H1 as [? ? HEps1]; inversion H2 as [? ? HEps2]; subst; constructor;\n  intros eff HIn.\n  inversion HIn; subst.\n  destruct H3 as [HIn_1 | HIn_2].\n  - apply HEps1 in HIn_1; destruct HIn_1 as [ca HIn']; exists ca; intuition.\n  - apply HEps2 in HIn_2; destruct HIn_2 as [ca HIn']; exists ca; intuition.\nQed. \n\nLemma sound_comp_par :\n  forall (st1 st2 : Epsilon) (dy1 dy2 : Phi),\n    Epsilon_Phi_Soundness (st1, dy1) -> Epsilon_Phi_Soundness (st2, dy2) ->\n    Epsilon_Phi_Soundness (Union StaticAction st1 st2, Phi_Par dy1 dy2). \nProof.\n  intros st1 st2 dy1 dy2 H1 H2.\n  inversion H1 as [? ? HEps1]; inversion H2 as [? ? HEps2]; subst; constructor;\n  intros eff HIn. \n  inversion HIn; subst.\n  destruct H3 as [HIn_1 | HIn_2].\n  - apply HEps1 in HIn_1; destruct HIn_1 as [ca HIn']; exists ca; intuition.\n  - apply HEps2 in HIn_2; destruct HIn_2 as [ca HIn']; exists ca; intuition.\nQed.\n\nLemma fold_dist_union : forall rho (eff1 eff2 : Epsilon),\n                          fold_subst_eps rho (Union_Static_Action eff1 eff2) =\n                          Union_Static_Action (fold_subst_eps rho eff1) (fold_subst_eps rho eff2).\nProof.  \n  intros rho eff1 eff2.\n  unfold fold_subst_eps.\n  apply Extensionality_Ensembles. \n  unfold Same_set, Included. split. \n  - intros x H. unfold In in *. unfold Union_Static_Action.\n    destruct H as [sa [H1 H2]]. subst.\n    destruct H1.\n    + apply Union_introl. unfold In in *.\n      exists x. intuition.\n    +  apply Union_intror. unfold In in *.\n      exists x. intuition.   \n  - intros x H. unfold In in *. destruct H.\n    + unfold In in H. destruct H as [sa ?].\n      exists sa. intuition. apply Union_introl. auto.\n    + unfold In in H. destruct H as [sa ?].\n      exists sa. intuition. apply Union_intror. auto.\nQed.\n\nLemma eff_sound : \n  forall e hp hp' env rho v dynamic_eff,\n    (hp, env, rho, e) ⇓ (hp', v, dynamic_eff) ->\n    forall stty ctxt rgns ty static_eff,\n      TcEnv (stty, rho, env, ctxt) -> \n      TcExp (ctxt, rgns, e, ty, static_eff) ->     \n      TcHeap (hp, stty) ->\n      TcRho (rho, rgns) ->\n      Epsilon_Phi_Soundness (fold_subst_eps rho static_eff, dynamic_eff).\nProof.\n  intros e hp hp' env rho v dynamic_eff D. \n  intros stty ctxt rgns ty static_eff HTcEnv HTcExp HTcHeap HTcRho. \n  dynamic_cases (dependent induction D) Case; inversion HTcExp; subst.\n  Case \"cnt n\". apply EmptyInNil.\n  Case \"bool b\". apply EmptyInNil.\n  Case \"var x\". apply EmptyInNil.\n  Case \"mu_abs\". apply EmptyInNil.\n  Case \"rgn_abs\". apply EmptyInNil.\n  Case \"mu_app\".  \n    assert (clsTcVal : exists stty', \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n             /\\ TcHeap (fheap, stty')\n             /\\ TcVal (stty', Cls (env', rho', Mu f x ec' ee'), subst_rho rho (Ty2_Arrow tya effc ty effe Ty2_Effect)))\n       by (eapply ty_sound; eauto). \n     \n    destruct clsTcVal as [sttyb [Weakb [TcHeapb TcVal_cls]]]; eauto. \n    assert (argTcVal : exists stty',\n             (forall l t', ST.find l sttyb = Some t' -> ST.find l stty' = Some t')\n             /\\ TcHeap (aheap, stty')\n             /\\ TcVal (stty', v0, subst_rho rho tya)) by\n        (eapply ty_sound; eauto using update_env, ext_stores__env).\n    destruct argTcVal as [sttya [Weaka [TcHeapa TcVal_v']]]; eauto.\n \n    assert (Sf : Epsilon_Phi_Soundness (fold_subst_eps rho efff, facts)) by (eapply IHD1; eauto). \n    assert (Sa : Epsilon_Phi_Soundness (fold_subst_eps rho effa, aacts)) by\n        (eapply IHD2 with (stty := sttyb);\n         eauto using update_env, ext_stores__env).\n\n\n    inversion TcVal_cls as  [ | | | ? ? ? ? ? ? ? TcRho_rho' TcInc' TcEnv_env' TcExp_abs | | |]; subst. \n    inversion TcExp_abs as [ | | | | ? ? ? ? ? ? ? ?  TcExp_eb | | | | | | | | | | | | | | | | | | | | ]; subst.  \n\n    rewrite <- H4 in TcVal_cls. \n    do 2 rewrite subst_rho_arrow in H4. inversion H4. \n    rewrite <- H9 in TcVal_v'.\n    \n    assert (Sb : Epsilon_Phi_Soundness (fold_subst_eps rho effc, bacts)).\n    rewrite <- H10; eapply IHD3 with (stty := sttya) (rho:=rho'); eauto.\n    SCase \"Extended Env\".\n      apply update_env.\n      SSCase \"TcEnv\". apply update_env.\n        SSSCase \"Extended\". eapply ext_stores__env; eauto.\n        SSSCase \"Extended TcVal\". eapply ext_stores__val; eauto.\n      SSCase \"TcVal\".  eassumption. \n\n    do 2 rewrite fold_dist_union.\n    apply sound_comp; [| assumption].\n    apply sound_comp; [|assumption].\n    assumption.\n  Case \"rgn_app\".\n    assert (cls_TcVal : exists stty', \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n             /\\ TcHeap (fheap, stty')\n             /\\ TcVal (stty', Cls (env', rho', Lambda x eb),  subst_rho rho (Ty2_ForallRgn effr tyr)))\n    by (eapply ty_sound; eauto). \n    destruct cls_TcVal as [sttyb [Weakb [TcHeapb TcVal_cls]]]; eauto.\n    rewrite fold_dist_union. \n    apply sound_comp.\n    \n    eapply IHD1; eauto.\n    inversion TcVal_cls as  [ | | | ? ? ? ? ? ? ? TcRho_rho' TcInc' TcEnv_env' TcExp_abs | | |]; subst. \n    inversion TcExp_abs as [ | | | | ? ? ? ? ? ? ? ? ? TcExp_eb | | | | | | | | | | | | | | | | | | | | ]; subst. \n    do 2 rewrite subst_rho_forallrgn in H5. inversion H5. clear H5.\n    unfold open_rgn_eff.\n    erewrite <- subst_rho_open_close_eps; eauto. \n    replace (Rgn2_Const true true v') with  (mk_rgn_type (Rgn2_Const true false v')) by (simpl; reflexivity).\n    rewrite <- subst_as_close_open_eps.\n    replace (subst_eps x (Rgn2_Const true false v') effr0) with (subst_in_eff x v' effr0) by (unfold subst_in_eff; reflexivity).\n    rewrite <- subst_add_comm_eff; eauto.\n    eapply IHD2; eauto.\n    eapply extended_rho; eauto. apply update_rho; auto.  eapply not_set_elem_not_in_rho; eauto. assumption.\n  Case \"eff_app\".   \n    assert (cls_TcVal : exists stty', \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n             /\\ TcHeap (hp', stty')\n             /\\ TcVal (stty', Cls (env', rho', Mu f x ec' ee'),  subst_rho rho (Ty2_Arrow tya effc tyc effe Ty2_Effect)))\n    by (eapply ty_sound; eauto).\n\n    destruct cls_TcVal as [sttyb [Weakb [TcHeapb TcVal_cls]]]; eauto. \n    assert (argTcVal : exists stty',\n             (forall l t', ST.find l sttyb = Some t' -> ST.find l stty' = Some t')\n             /\\ TcHeap (hp', stty')\n             /\\ TcVal (stty', v', subst_rho rho tya)) by\n        (eapply ty_sound; eauto using update_env, ext_stores__env).\n    destruct argTcVal as [sttya [Weaka [TcHeapa TcVal_v']]]; eauto.\n\n    assert (Sf : Epsilon_Phi_Soundness (fold_subst_eps rho efff, facts)) by (eapply IHD1; eauto). \n    assert (Sa : Epsilon_Phi_Soundness (fold_subst_eps rho effa, aacts)) by\n        (eapply IHD2 with (stty := sttyb);\n         eauto using update_env, ext_stores__env).\n\n    inversion TcVal_cls as  [ | | | ? ? ? ? ? ? ? TcRho_rho' TcInc' TcEnv_env' TcExp_abs | | | ]; subst. \n    inversion TcExp_abs as [ | | | | ? ? ? ? ? ? ? ? TcExp_eb | | | | | | | | | | | | | | | | | | | |]; subst.\n\n    rewrite <- H4 in TcVal_cls. \n    do 2 rewrite subst_rho_arrow in H4. inversion H4. \n    rewrite <- H8 in TcVal_v'.\n    \n    assert (Sb : Epsilon_Phi_Soundness (fold_subst_eps rho effe, bacts)).\n    rewrite <- H11.\n    eapply IHD3 with (stty := sttya); eauto.\n    apply update_env.\n    SCase \"TcEnv\". apply update_env.\n       SSCase \"Extended\". eapply ext_stores__env; eauto.\n       SSCase \"Extended TcVal\". eapply ext_stores__val; eauto. eassumption.\n        \n    do 2 rewrite fold_dist_union.\n    apply sound_comp; [| assumption].\n    apply sound_comp; [|assumption].\n    assumption.\n  Case \"par_pair\".\n    assert (HA : Epsilon_Phi_Soundness (fold_subst_eps rho eff1, acts_mu1)).\n    eapply IHD3; eauto.\n    assert (HB : Epsilon_Phi_Soundness (fold_subst_eps rho eff2, acts_mu2)).\n    eapply IHD4; eauto.\n    assert (HC : Epsilon_Phi_Soundness (fold_subst_eps rho eff3, acts_eff1)).\n    eapply IHD1; eauto.\n    assert (HD : Epsilon_Phi_Soundness (fold_subst_eps rho eff4, acts_eff2)).\n    eapply IHD2; eauto.  \n    assert (H_ : Epsilon_Phi_Soundness (Union_Static_Action (fold_subst_eps rho eff1) (fold_subst_eps rho eff2), \n                                        Phi_Seq acts_mu1 acts_mu2))\n     by (apply sound_comp; auto).\n    assert (H__ : Epsilon_Phi_Soundness (Union_Static_Action (fold_subst_eps rho eff3) (fold_subst_eps rho eff4), \n                                         Phi_Seq acts_eff1 acts_eff2))\n     by (apply sound_comp; auto).\n\n    rewrite fold_dist_union.\n    replace (fold_subst_eps rho (Union_Static_Action (Union_Static_Action eff3 eff4) eff2)) with\n            (Union_Static_Action (fold_subst_eps rho (Union_Static_Action eff3 eff4)) (fold_subst_eps rho eff2))\n      by (rewrite <- fold_dist_union; reflexivity).\n\n    replace (Union_Static_Action (Union_Static_Action (fold_subst_eps rho (Union_Static_Action eff3 eff4))\n                                                      (fold_subst_eps rho eff2)) (fold_subst_eps rho eff1)) with\n     (Union_Static_Action (fold_subst_eps rho (Union_Static_Action eff3 eff4)) \n                                              (Union_Static_Action (fold_subst_eps rho eff1) (fold_subst_eps rho eff2))). \n    SCase \"\". \n     { apply sound_comp with (dy1:=Phi_Par acts_eff1 acts_eff2) (dy2:=Phi_Par acts_mu1 acts_mu2).\n       - rewrite fold_dist_union. apply sound_comp_par; assumption.\n       - apply sound_comp_par; assumption. } \n    SCase \"replace proof\". \n      rewrite fold_dist_union.\n      unfold Union_Static_Action.\n      { apply Extensionality_Ensembles;\n        unfold Same_set, Included; split; intros x HUnion; unfold Ensembles.In in *.\n        - inversion HUnion; subst; inversion H1; subst. \n          + apply Union_introl. apply Union_introl. apply Union_introl. assumption.\n          + apply Union_introl. apply Union_introl. apply Union_intror. assumption.\n          + apply Union_intror. assumption. \n          + apply Union_introl. apply Union_intror. assumption.\n        - inversion HUnion; subst; inversion H1; subst. \n          + apply Union_introl. assumption.\n          + apply Union_intror. apply Union_intror. assumption.\n          + apply Union_intror. apply Union_introl. assumption. }\n  Case \"cond_true\". \n    assert (boolTcVal : exists stty', \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n             /\\ TcHeap (cheap, stty')\n             /\\ TcVal (stty', Bit true, subst_rho rho Ty2_Boolean)) by (eapply ty_sound; eauto).\n    destruct boolTcVal as [sttyb [Weakb [TcHeapb TcVal_bool]]]; eauto. \n\n    assert (Epsilon_Phi_Soundness (fold_subst_eps rho eff, cacts)) by (eapply IHD1; eauto).\n    do 2 rewrite fold_dist_union.\n    assert (Epsilon_Phi_Soundness (fold_subst_eps rho eff1, tacts)) by\n      (eapply IHD2 with (stty := sttyb); eauto using ext_stores__env).\n\n    eapply sound_comp; eauto.\n    replace tacts with (Phi_Seq tacts (Phi_Nil)) by (apply Phi_Seq_Nil_R). \n    eapply sound_comp; [assumption | apply EmptyInNil].     \n  Case \"cond_false\". \n    assert (bool_TcVal : exists stty', \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n             /\\ TcHeap (cheap, stty')\n             /\\ TcVal (stty', Bit false, subst_rho rho Ty2_Boolean)) by (eapply ty_sound; eauto). \n    destruct bool_TcVal as [sttyb [Weakb [TcHeapb TcVal_bool]]]; eauto.    \n    \n    assert (Epsilon_Phi_Soundness (fold_subst_eps rho eff, cacts)) by (eapply IHD1; eauto).\n    do 2 rewrite fold_dist_union.\n    assert (Epsilon_Phi_Soundness (fold_subst_eps rho eff2, facts)) by\n      (eapply IHD2 with (stty := sttyb);  eauto using ext_stores__env).\n\n    eapply sound_comp; eauto.\n    replace facts with (Phi_Seq (Phi_Nil) facts) by (apply Phi_Seq_Nil_L).\n    eapply sound_comp; [apply EmptyInNil | assumption].  \n  Case \"new_ref e\".\n    assert (Epsilon_Phi_Soundness (fold_subst_eps rho  veff, vacts)) by (eapply IHD; eauto).\n    rewrite fold_dist_union.\n    apply sound_comp; [assumption | ].\n    econstructor. intros eff HIn.\n    inversion HIn; subst.\n    eexists. split. unfold In, fold_subst_eps, Singleton_Static_Action, fold_subst_sa.\n    eexists. intuition.\n    simpl. simpl in H; inversion H; subst. rewrite subst_rho_rgn_const. constructor.\n  Case \"get_ref e\".\n    assert (Epsilon_Phi_Soundness (fold_subst_eps rho aeff, aacts)) by (eapply IHD; eauto).\n    rewrite fold_dist_union.\n    apply sound_comp; [assumption | ]. \n    econstructor. intros eff HIn.\n    inversion HIn.\n    eexists. split. unfold In, fold_subst_eps, Singleton_Static_Action, fold_subst_sa.\n    eexists. intuition.\n    simpl. simpl in H; inversion H; subst. rewrite subst_rho_rgn_const. constructor.\n  Case \"set_ref e1 e2\".\n    assert (loc_TcVal : exists stty', \n             (forall k t', ST.find k stty = Some t' -> ST.find k stty' = Some t')\n             /\\ TcHeap (heap', stty')\n             /\\ TcVal (stty', Loc (Rgn2_Const true false s) l, subst_rho rho (Ty2_Ref (mk_rgn_type (Rgn2_Const true false s)) t)))\n      by (eapply ty_sound; eauto).  \n    destruct loc_TcVal as [sttyb [Weakb [TcHeapb TcVal_bool]]]; eauto.    \n\n    assert (Epsilon_Phi_Soundness (fold_subst_eps rho aeff, aacts)) by (eapply IHD1; eauto).\n    do 2 rewrite fold_dist_union.\n    assert (Epsilon_Phi_Soundness (fold_subst_eps rho veff, vacts)).\n      eapply IHD2 with (stty := sttyb); eauto using ext_stores__env.\n\n    apply sound_comp. apply sound_comp. assumption. assumption.  \n    econstructor. intros eff HIn.\n    inversion HIn.\n    eexists. split. unfold In, fold_subst_eps, Singleton_Static_Action, fold_subst_sa.\n    eexists. intuition.\n    simpl. simpl in H; inversion H; subst. rewrite subst_rho_rgn_const. constructor.\n  Case \"nat_plus x y\".\n    assert (H : exists stty', \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n             /\\ TcHeap (lheap, stty')\n             /\\ TcVal (stty', Num va, subst_rho rho Ty2_Natural)) by (eapply ty_sound; eauto).\n    destruct H as [sttyx [Weakx [TcHeapx TcVal_x]]]; eauto.\n    rewrite fold_dist_union.\n    apply sound_comp; eauto.\n    eapply IHD2 with (stty := sttyx); eauto using ext_stores__env.\n  Case \"nat_minus x y\".\n    assert (H : exists stty', \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n             /\\ TcHeap (lheap, stty')\n             /\\ TcVal (stty', Num va, subst_rho rho Ty2_Natural)) by (eapply ty_sound; eauto).\n    destruct H as [sttyx [Weakx [TcHeapx TcVal_x]]]; eauto.\n    rewrite fold_dist_union.\n    apply sound_comp; eauto.\n    eapply IHD2 with (stty := sttyx); eauto using ext_stores__env.\n  Case \"nat_times x y\". \n    assert (H : exists stty', \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n             /\\ TcHeap (lheap, stty')\n             /\\ TcVal (stty', Num va, subst_rho rho Ty2_Natural)) by (eapply ty_sound; eauto).\n    destruct H as [sttyx [Weakx [TcHeapx TcVal_x]]]; eauto.\n    rewrite fold_dist_union.\n    apply sound_comp; eauto.\n    eapply IHD2 with (stty := sttyx); eauto using ext_stores__env.\n  Case \"bool_eq x y\".\n    assert (H : exists stty', \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n             /\\ TcHeap (lheap, stty')\n             /\\ TcVal (stty', Num va, subst_rho rho Ty2_Natural)) by (eapply ty_sound; eauto).\n    destruct H as [sttyx [Weakx [TcHeapx TcVal_x]]]; eauto.\n    rewrite fold_dist_union.\n    apply sound_comp; eauto.\n    eapply IHD2 with (stty := sttyx); eauto using ext_stores__env. \n  Case \"alloc_abs\". apply EmptyInNil.\n  Case \"read_abs\". apply EmptyInNil.\n  Case \"write_abs\". apply EmptyInNil.  \n  Case \"read_conc\". apply EmptyInNil.\n  Case \"write_conc\". apply EmptyInNil.\n  Case \"eff_concat\".\n     assert (H : exists stty', \n             (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n             /\\ TcHeap (hp', stty')\n             /\\ TcVal (stty', Eff effa, subst_rho rho Ty2_Effect)) by (eapply ty_sound; eauto).\n    destruct H as [sttyx [Weakx [TcHeapx TcVal_x]]]; eauto.\n    rewrite fold_dist_union.\n    apply sound_comp; eauto.\n  Case \"eff_top\". apply EmptyInNil.\n  Case \"eff_empty\". apply EmptyInNil.\nQed.\n\n\nLemma ReadOnlyTracePreservesHeap_2 : \n  forall e hp hp' env rho v dynamic_eff,\n    (hp, env, rho, e) ⇓ (hp', v, dynamic_eff) ->\n    forall stty ctxt rgns ty static_eff,\n      TcEnv (stty, rho, env, ctxt) -> \n      TcExp (ctxt, rgns, e, ty, static_eff) ->     \n      TcHeap (hp, stty) ->\n      TcRho (rho, rgns) ->\n      ReadOnlyStatic (static_eff) ->\n      hp = hp'.\nProof.\n  intros.\n  eapply ReadOnlyTracePreservesHeap_1; [eassumption | ].\n  eapply ReadOnlyStaticImpliesReadOnlyPhi; [eapply ReadOnlyStaticImpliesReadOnlySubstStatic; eassumption | ].\n  eapply eff_sound; eassumption.\nQed.\n\nEnd EffectSoundness.\n\n", "meta": {"author": "esmifro", "repo": "SurfaceEffects", "sha": "3450e4b771de4062ab73ee20947adf3f9de579ba", "save_path": "github-repos/coq/esmifro-SurfaceEffects", "path": "github-repos/coq/esmifro-SurfaceEffects/SurfaceEffects-3450e4b771de4062ab73ee20947adf3f9de579ba/EffectSystem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2391454483250407}}
{"text": "From ITree Require Import\n     ITree\n     ITreeFacts\n     Events.State\n     Events.StateFacts\n     Events.Exception\n.\n\nFrom SecureExample Require Import\n     LabelledImp\n     Lattice\n.\n\nImport Monads.\nImport MonadNotation.\nLocal Open Scope monad_scope.\n\nSection LabelledImpHandler.\n\nContext (Labels : Lattice).\n\nDefinition priv_io (A : Type) (e : IOE Labels A) :=\n  match e with\n  | LabelledPrint _ s _ => s end.\n\n\nDefinition priv_exc (A : Type) (e : impExcE Labels A ) :=\n  match e with\n  | Throw s => s end.\n\nDefinition priv_exc_io := case_ priv_exc priv_io.\n\nDefinition product_rel {R1 R2 S1 S2} (RR1: R1 -> S1 -> Prop) (RR2 : R2 -> S2 -> Prop)\n           (p1 : R1 * R2) (p2 : S1 * S2) : Prop :=\n  RR1 (fst p1) (fst p2) /\\ RR2 (snd p1) (snd p2).\n\nDefinition handle_case {E1 E2 : Type -> Type} {M : Type -> Type} (hl : E1 ~> M) (hr : E2 ~> M) : (E1 +' E2) ~> M :=\n  fun _ e => match e with\n          | inl1 el => hl _ el\n          | inr1 er => hr _ er end.\n\nDefinition handle_state_io : forall A, (stateE +' (IOE Labels)) A ->\n                                  stateT map (itree ((impExcE Labels) +' (IOE Labels))) A :=\n  fun _ e => match e with\n          | inl1 el => handleState _ el\n          | inr1 er => fun s => r <- ITree.trigger (inr1 er);; Ret (s, r) end.\n\nDefinition handle_imp : forall A, ((impExcE Labels) +' stateE +' (IOE Labels)) A ->\n                             stateT map (itree ((impExcE Labels) +' (IOE Labels)) ) A :=\n  fun _ e => match e with\n          | inl1 el => fun s => r <- ITree.trigger (inl1 el);; Ret (s, r)\n          | inr1 er => handle_state_io _ er end.\n\nDefinition interp_imp {R} (t : itree ((impExcE Labels) +' stateE +' (IOE Labels)) R ) : stateT map (itree ((impExcE Labels) +' (IOE Labels))) R :=\n  interp_state handle_imp t.\n\nHint Unfold interp_imp : core.\nHint Unfold handle_state_io : core.\nHint Unfold handle_imp : core.\nHint Unfold product_rel : core.\n(*\nLtac use_simpobs :=\n  repeat match goal with\n         | H : TauF _ = observe ?t |- _ => apply simpobs in H\n         | H : RetF _ = observe ?t |- _ => apply simpobs in H\n         | H : VisF _ _ = observe ?t |- _ => apply simpobs in H\n  end.\n\nLtac destruct_imp_ev := repeat match goal with\n                        | e : (?E1 +' ?E2) ?A |- _ => destruct e\n                        | exc : impExcE ?A |- _ => destruct exc\n                        | st : stateE ?A |- _ => destruct st\n                        | io : IOE ?A |- _ => destruct io\n                        end.\n\n (* TODO : replace with labelled equiv *)\nLemma interp_eqit_secure_imp : forall (R1 R2 : Type) (RR : R1 -> R2 -> Prop) (priv_map : privacy_map)\n                                 (t1 : itree (impExcE +' stateE +' IOE) R1 )\n                                 (t2 : itree (impExcE +' stateE +' IOE) R2),\n    eqit_secure sense_preorder (priv_imp priv_map) RR true true Public t1 t2 ->\n    low_eqit_secure_impstate true true priv_map RR (interp_imp t1 )  (interp_imp t2).\nProof.\n  red. intros.\n  eapply interp_eqit_secure_state; eauto.\n  - constructor; red; intros; cbv; intros; auto. red in H1. rewrite H1; auto.\n    rewrite H1; auto.\n  - intros. destruct_imp_ev.\n    + destruct s.\n      * eapply respect_public'. cbv. auto. red. intros. cbn.\n        setoid_rewrite bind_trigger. apply eqit_secure_public_Vis. cbv. auto.\n        intros [].\n      * eapply respect_private_e. cbv. auto. constructor. intros [].\n        intros. setoid_rewrite bind_trigger. pfold. constructor. intros [].\n        cbv. auto.\n    + destruct (priv_map x) eqn : Hl.\n      * apply respect_public'. cbv. rewrite Hl. auto.\n        red. intros. cbn. apply secure_eqit_ret.  split; auto. cbv. rewrite H1; auto.\n      * apply respect_private_ne. cbv. rewrite Hl. auto.\n        constructor. exact 0. intros. cbn. apply terminates_ret. red. intros. auto.\n    + destruct (priv_map x) eqn : Hl.\n      * apply respect_public'. cbv. rewrite Hl. auto.\n        red. intros. cbn. apply secure_eqit_ret. split; auto.\n        cbn. apply low_equiv_update_public; auto.\n      * apply respect_private_ne. cbv. rewrite Hl. auto.\n        constructor. exact tt. intros. cbn. apply terminates_ret.\n        apply low_equiv_update_private_r; auto. red; intros; auto.\n    + destruct s.\n      * eapply respect_public'. cbv. auto. red. intros. cbn.\n        setoid_rewrite bind_trigger. apply eqit_secure_public_Vis. cbv. auto.\n        intros []. apply secure_eqit_ret. split; auto.\n      * eapply respect_private_ne. cbv. auto. constructor. exact tt.\n        intros. cbn. setoid_rewrite bind_trigger. apply terminates_vis.\n        intros []. apply terminates_ret. red; intros; auto.\n         cbn. split; auto. constructor. exact tt.\nQed.\n*)\nEnd LabelledImpHandler.\n", "meta": {"author": "DeepSpec", "repo": "InteractionTrees", "sha": "8e28e2ee08496c696e03916a22d93c39559a9715", "save_path": "github-repos/coq/DeepSpec-InteractionTrees", "path": "github-repos/coq/DeepSpec-InteractionTrees/InteractionTrees-8e28e2ee08496c696e03916a22d93c39559a9715/secure_example/LabelledImpHandler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.23913813979781748}}
{"text": "Module Type T1.\n  Parameter t : Type.\nEnd T1.\n\nModule Type T2.\n  Declare Module M : T1.\n  Parameter t : Type.\n  Parameter test : t = M.t.\nEnd T2.\n\nModule M1 <: T1.\n  Definition t : Type := bool.\nEnd M1.\n\nModule M2 <: T2.\n  Module M := M1.\n  Definition t : Type := nat.\n  Lemma test : t = t. Proof. reflexivity. Qed.\nEnd M2.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/output/qualification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.3775406617944891, "lm_q1q2_score": 0.2391381301363536}}
{"text": "(** This file implements symbolic evaluation for the\n ** language defined in IL.v\n **)\nRequire Import Word.\nRequire Import PropX.\nRequire Import Expr SepExpr.\nRequire Import Prover.\nRequire Import Env.\nRequire Structured SymEval.\nImport List.\n\nRequire Import IL SepIL ILEnv.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(** The Symbolic Evaluation Interfaces *)\nModule MEVAL := SymEval.SymbolicEvaluator SH.\n\nSection typed.\n  Variable types : list type.\n  Variables pcT stT : tvar.\n\n  (** Symbolic registers **)\n  Definition SymRegType : Type :=\n    (expr types * expr types * expr types)%type.\n\n  (** Symbolic State **)\n  Record SymState : Type :=\n  { SymMem   : option (SH.SHeap types pcT stT)\n  ; SymRegs  : SymRegType\n  ; SymPures : list (expr types)\n  }.\n\n  (** Register accessor functions **)\n  Definition sym_getReg (r : reg) (sr : SymRegType) : expr types :=\n    match r with\n      | Sp => fst (fst sr)\n      | Rp => snd (fst sr)\n      | Rv => snd sr\n    end.\n\n  Definition sym_setReg (r : reg) (v : expr types) (sr : SymRegType) : SymRegType :=\n    match r with\n      | Sp => (v, snd (fst sr), snd sr)\n      | Rp => (fst (fst sr), v, snd sr)\n      | Rv => (fst sr, v)\n    end.\n  \n  (** These the reflected version of the IL, it essentially \n   ** replaces all uses of W with expr types so that the value\n   ** can be inspected.\n   **)\n  Inductive sym_loc :=\n  | SymReg : reg -> sym_loc\n  | SymImm : expr types -> sym_loc\n  | SymIndir : reg -> expr types -> sym_loc.\n\n  (* Valid targets of assignments *)\n  Inductive sym_lvalue :=\n  | SymLvReg : reg -> sym_lvalue\n  | SymLvMem : sym_loc -> sym_lvalue\n  | SymLvMem8 : sym_loc -> sym_lvalue.\n  \n  (* Operands *)\n  Inductive sym_rvalue :=\n  | SymRvLval : sym_lvalue -> sym_rvalue\n  | SymRvImm : expr types -> sym_rvalue\n  | SymRvLabel : label -> sym_rvalue.\n\n  (* Non-control-flow instructions *)\n  Inductive sym_instr :=\n  | SymAssign : sym_lvalue -> sym_rvalue -> sym_instr\n  | SymBinop : sym_lvalue -> sym_rvalue -> binop -> sym_rvalue -> sym_instr.\n\n  Inductive sym_assert :=\n  | SymAssertCond : sym_rvalue -> test -> sym_rvalue -> option bool -> sym_assert.\n\n  Definition istream : Type := list ((list sym_instr * option state) + sym_assert).\nEnd typed.\n\nSection stateD.\n  Notation pcT := (tvType 0).\n  Notation tvWord := (tvType 0).\n  Notation stT := (tvType 1).\n  Notation tvState := (tvType 2).\n  Notation tvTest := (tvType 3).\n  Notation tvReg := (tvType 4).\n\n  Variable types' : list type.\n  Notation TYPES := (repr bedrock_types_r types').\n  Variable funcs : functions TYPES.\n  Variable sfuncs : SEP.predicates TYPES pcT stT.\n\n  Definition stateD (uvars vars : env TYPES) cs (stn_st : IL.settings * state) (ss : SymState TYPES pcT stT) : Prop :=\n    let (stn,st) := stn_st in\n    match ss with\n      | {| SymMem := m ; SymRegs := (sp, rp, rv) ; SymPures := pures |} =>\n        match \n          exprD funcs uvars vars sp tvWord ,\n          exprD funcs uvars vars rp tvWord ,\n          exprD funcs uvars vars rv tvWord\n          with\n          | Some sp , Some rp , Some rv =>\n            Regs st Sp = sp /\\ Regs st Rp = rp /\\ Regs st Rv = rv\n          | _ , _ , _ => False\n        end\n        /\\ match m with \n             | None => True\n             | Some m => \n               PropX.interp cs (SepIL.SepFormula.sepFormula (SEP.sexprD funcs sfuncs uvars vars (SH.sheapD m)) stn_st)%PropX\n           end\n        /\\ AllProvable funcs uvars vars (match m with \n                                           | None => pures\n                                           | Some m => pures ++ SH.pures m\n                                         end)\n    end.\n\n  Definition qstateD (uvars vars : env TYPES) cs (stn_st : IL.settings * state) (qs : SymEval.Quant) (ss : SymState TYPES pcT stT) : Prop :=\n    SymEval.quantD vars uvars qs (fun vars_env meta_env => stateD meta_env vars_env cs stn_st ss).\n\nEnd stateD.\n\nImplicit Arguments sym_loc [ ].\nImplicit Arguments sym_lvalue [ ].\nImplicit Arguments sym_rvalue [ ].\nImplicit Arguments sym_instr [ ].\nImplicit Arguments sym_assert [ ].\n\nSection Denotations.\n  Variable types' : list type.\n  Notation TYPES := (repr bedrock_types_r types').\n\n  Notation pcT := (tvType 0).\n  Notation tvWord := (tvType 0).\n  Notation stT := (tvType 1).\n  Notation tvState := (tvType 2).\n  Notation tvTest := (tvType 3).\n  Notation tvReg := (tvType 4).\n\n\n  (** Denotation/reflection functions give the meaning of the reflected syntax *)\n  Variable funcs' : functions TYPES.\n  Notation funcs := (repr (bedrock_funcs_r types') funcs').\n  Variable sfuncs : SEP.predicates TYPES pcT stT.\n  Variable uvars vars : env TYPES.\n  \n  Definition sym_regsD (rs : SymRegType TYPES) : option regs :=\n    match rs with\n      | (sp, rp, rv) =>\n        match \n          exprD funcs uvars vars sp tvWord ,\n          exprD funcs uvars vars rp tvWord ,\n          exprD funcs uvars vars rv tvWord \n          with\n          | Some sp , Some rp , Some rv =>\n            Some (fun r => \n              match r with\n                | Sp => sp\n                | Rp => rp\n                | Rv => rv\n              end)\n          | _ , _ , _ => None\n        end\n    end.\n\n  Definition sym_locD (s : sym_loc TYPES) : option loc :=\n    match s with\n      | SymReg r => Some (Reg r)\n      | SymImm e =>\n        match exprD funcs uvars vars e tvWord with\n          | Some e => Some (Imm e)\n          | None => None\n        end\n      | SymIndir r o =>\n        match exprD funcs uvars vars o tvWord with\n          | Some o => Some (Indir r o)\n          | None => None\n        end\n    end.\n\n  Definition sym_lvalueD (s : sym_lvalue TYPES) : option lvalue :=\n    match s with\n      | SymLvReg r => Some (LvReg r)\n      | SymLvMem l => match sym_locD l with\n                        | Some l => Some (LvMem l)\n                        | None => None\n                      end\n      | SymLvMem8 l => match sym_locD l with\n                         | Some l => Some (LvMem8 l)\n                         | None => None\n                       end\n    end.\n\n  Definition sym_rvalueD (r : sym_rvalue TYPES) : option rvalue :=\n    match r with\n      | SymRvLval l => match sym_lvalueD l with\n                         | Some l => Some (RvLval l)\n                         | None => None\n                       end\n      | SymRvImm e => match exprD funcs uvars vars e tvWord with\n                        | Some l => Some (RvImm l)\n                        | None => None\n                      end\n      | SymRvLabel l => Some (RvLabel l)\n    end.\n\n  Definition sym_instrD (i : sym_instr TYPES) : option instr :=\n    match i with\n      | SymAssign l r =>\n        match sym_lvalueD l , sym_rvalueD r with\n          | Some l , Some r => Some (Assign l r)\n          | _ , _ => None\n        end\n      | SymBinop lhs l o r =>\n        match sym_lvalueD lhs , sym_rvalueD l , sym_rvalueD r with\n          | Some lhs , Some l , Some r => Some (Binop lhs l o r)\n          | _ , _ , _ => None\n        end\n    end.\n\n  Fixpoint sym_instrsD (is : list (sym_instr TYPES)) : option (list instr) :=\n    match is with\n      | nil => Some nil\n      | i :: is => \n        match sym_instrD i , sym_instrsD is with\n          | Some i , Some is => Some (i :: is)\n          | _ , _ => None\n        end\n    end.\n\n  Fixpoint istreamD (is : istream TYPES) (stn : settings) (st : state) (res : option state) : Prop :=\n    match is with\n      | nil => Some st = res\n      | inl (ins, st') :: is => \n        match sym_instrsD ins with\n          | None => False\n          | Some ins => \n            match st' with\n              | None => evalInstrs stn st ins = None\n              | Some st' => evalInstrs stn st ins = Some st' /\\ istreamD is stn st' res\n            end\n        end\n      | inr asrt :: is =>\n        match asrt with\n          | SymAssertCond l t r t' => \n            match sym_rvalueD l , sym_rvalueD r with\n              | Some l , Some r =>\n                match t' with\n                  | None => \n                    Structured.evalCond l t r stn st = None\n                  | Some t' =>\n                    Structured.evalCond l t r stn st = Some t' /\\ istreamD is stn st res\n                end\n              | _ , _ => False\n            end\n        end\n    end.\n\n  Section SymEvaluation.\n    Variable Prover : ProverT TYPES.\n    Variable meval : MEVAL.MemEvaluator TYPES pcT stT.\n\n    Section with_facts.\n    Variable Facts : Facts Prover.\n\n    Definition sym_evalLoc (lv : sym_loc TYPES) (ss : SymState TYPES pcT stT) : expr TYPES :=\n      match lv with\n        | SymReg r => sym_getReg r (SymRegs ss)\n        | SymImm l => l\n        | SymIndir r w => fPlus (sym_getReg r (SymRegs ss)) w\n      end.\n\n    Definition sym_evalLval (lv : sym_lvalue TYPES) (val : expr TYPES) (ss : SymState TYPES pcT stT)\n      : option (SymState TYPES pcT stT) :=\n      match lv with\n        | SymLvReg r =>\n          Some {| SymMem := SymMem ss \n                ; SymRegs := sym_setReg r val (SymRegs ss)\n                ; SymPures := SymPures ss\n                |}\n        | SymLvMem l => \n          let l := sym_evalLoc l ss in\n            match SymMem ss with\n              | None => None\n              | Some m =>\n                match MEVAL.swrite_word meval _ Facts l val m with\n                  | Some m =>\n                    Some {| SymMem := Some m\n                          ; SymRegs := SymRegs ss\n                          ; SymPures := SymPures ss\n                          |}\n                  | None => None\n                end\n            end\n        | SymLvMem8 l => \n          let l := sym_evalLoc l ss in\n            match SymMem ss with\n              | None => None\n              | Some m =>\n                match MEVAL.swrite_byte meval _ Facts l val m with\n                  | Some m =>\n                    Some {| SymMem := Some m\n                          ; SymRegs := SymRegs ss\n                          ; SymPures := SymPures ss\n                          |}\n                  | None => None\n                end\n            end\n      end.\n\n    Definition sym_evalRval (rv : sym_rvalue TYPES) (ss : SymState TYPES pcT stT) : option (expr TYPES) :=\n      match rv with\n        | SymRvLval (SymLvReg r) =>\n          Some (sym_getReg r (SymRegs ss))\n        | SymRvLval (SymLvMem l) =>\n          let l := sym_evalLoc l ss in\n            match SymMem ss with\n              | None => None\n              | Some m => \n                MEVAL.sread_word meval _ Facts l m\n            end\n        | SymRvLval (SymLvMem8 l) =>\n          let l := sym_evalLoc l ss in\n            match SymMem ss with\n              | None => None\n              | Some m => \n                MEVAL.sread_byte meval _ Facts l m\n            end\n        | SymRvImm w => Some w \n        | SymRvLabel l => None (* TODO: can we use labels? it seems like we need to reflect these as words. *)\n        (* an alternative would be to reflect these as a function call that does the positioning...\n         * - it isn't clear that this can be done since the environment would need to depend on the settings.\n         *)\n        (*Some (Expr.Const (TYPES := TYPES) (t := tvType 2) l) *)\n      end.\n\n    Definition sym_assertTest (l : sym_rvalue TYPES) (t : test) (r : sym_rvalue TYPES) (ss : SymState TYPES pcT stT) (res : bool) \n      : option (expr TYPES) :=\n      let '(l, t, r) := \n        if res then (l, t, r)\n        else match t with\n               | IL.Eq => (l, IL.Ne, r)\n               | IL.Ne => (l, IL.Eq, r)\n               | IL.Lt => (r, IL.Le, l)\n               | IL.Le => (r, IL.Lt, l)\n             end\n      in\n      match sym_evalRval l ss , sym_evalRval r ss with\n        | Some l , Some r =>\n          Some match t with\n                 | IL.Eq => Expr.Equal tvWord l r\n                 | IL.Ne => Expr.Not (Expr.Equal tvWord l r)\n                 | IL.Lt => Expr.Func 4 (l :: r :: nil)\n                 | IL.Le => Expr.Not (Expr.Func 4 (r :: l :: nil))\n          end\n        | _ , _ => None\n      end.\n\n    Definition sym_evalInstr (i : sym_instr TYPES) (ss : SymState TYPES pcT stT) : option (SymState TYPES pcT stT) :=\n      match i with \n        | SymAssign lv rv =>\n          match sym_evalRval rv ss with\n            | None => None\n            | Some rv => sym_evalLval lv rv ss\n          end\n        | SymBinop lv l o r =>\n          match sym_evalRval l ss , sym_evalRval r ss with\n            | Some l , Some r => \n              let v :=\n                match o with\n                  | Plus  => fPlus\n                  | Minus => fMinus\n                  | Times => fMult\n                end _ l r\n                in\n                sym_evalLval lv v ss\n            | _ , _ => None\n          end\n      end.\n\n    Fixpoint sym_evalInstrs (is : list (sym_instr TYPES)) (ss : SymState TYPES pcT stT) \n      : SymState TYPES pcT stT + (SymState TYPES pcT stT * list (sym_instr TYPES)) :=\n      match is with\n        | nil => inl ss\n        | i :: is =>\n          match sym_evalInstr i ss with\n            | None => inr (ss, i :: is)\n            | Some ss => sym_evalInstrs is ss\n          end\n      end.\n    End with_facts.\n    \n    Variable learnHook : MEVAL.LearnHook TYPES (SymState TYPES pcT stT).\n\n    Inductive SymResult : Type :=\n    | Safe      : SymEval.Quant -> SymState TYPES pcT stT -> SymResult\n(*    | Unsafe    : SymEval.Quant -> SymResult *)\n    | SafeUntil : SymEval.Quant -> SymState TYPES pcT stT -> istream TYPES -> SymResult. \n\n    Fixpoint sym_evalStream (facts : Facts Prover) (is : istream TYPES) (qs : SymEval.Quant) (u g : variables) \n      (ss : SymState TYPES pcT stT) : SymResult :=\n      match is with\n        | nil => Safe qs ss\n        | inl (ins, st) :: is =>\n          match sym_evalInstrs facts ins ss with\n            | inr (ss,rm) => SafeUntil qs ss (inl (rm, st) :: is)\n            | inl ss => sym_evalStream facts is qs u g ss\n          end\n        | inr asrt :: is =>\n          match asrt with\n            | SymAssertCond l t r (Some res) =>\n              match sym_assertTest facts l t r ss res with\n                | Some sp =>\n                  let facts' := Learn Prover facts (sp :: nil) in \n                  let ss' := \n                    {| SymRegs := SymRegs ss \n                     ; SymMem := SymMem ss\n                     ; SymPures := sp :: SymPures ss\n                     |}\n                  in\n                  let (ss', qs') := learnHook Prover u g ss' facts' (sp :: nil) in\n                  sym_evalStream facts' is (SymEval.appendQ qs' qs) (u ++ SymEval.gatherAll qs') (g ++ SymEval.gatherEx qs') ss'\n                | None => SafeUntil qs ss (inr asrt :: is)\n              end\n            | SymAssertCond l t r None =>\n              match sym_evalRval facts l ss , sym_evalRval facts r ss with\n                | None , _ => SafeUntil qs ss (inr asrt :: is)\n                | _ , None => SafeUntil qs ss (inr asrt :: is)\n                | Some _ , Some _ => sym_evalStream facts is qs u g ss \n              end\n          end\n      end.\n  End SymEvaluation.\nEnd Denotations.\n\nDefinition IL_stn_st : Type := (IL.settings * IL.state)%type.\n\nSection spec_functions.\n  Variable ts : list type.\n  Let types := repr core_bedrock_types_r ts.\n\n  Local Notation \"'pcT'\" := (tvType 0).\n  Local Notation \"'tvWord'\" := (tvType 0).\n  Local Notation \"'stT'\" := (tvType 1).\n\n  Definition IL_mem_satisfies (cs : PropX.codeSpec (tvarD types pcT) (tvarD types stT)) \n    (P : ST.hprop (tvarD types pcT) (tvarD types stT) nil) (stn_st : (tvarD types stT)) : Prop :=\n    PropX.interp cs (SepIL.SepFormula.sepFormula P stn_st).\n  \n  Definition IL_ReadWord : IL_stn_st -> tvarD types tvWord -> option (tvarD types tvWord) :=\n    (fun stn_st => IL.ReadWord (fst stn_st) (Mem (snd stn_st))).\n  Definition IL_WriteWord : IL_stn_st -> tvarD types tvWord -> tvarD types tvWord -> option IL_stn_st :=\n    (fun stn_st p v => \n      let (stn,st) := stn_st in\n        match IL.WriteWord stn (Mem st) p v with\n          | None => None\n          | Some m => Some (stn, {| Regs := Regs st ; Mem := m |})\n        end).\n\n  Definition IL_ReadByte : IL_stn_st -> tvarD types tvWord -> option (tvarD types tvWord) :=\n    (fun stn_st a => match IL.ReadByte (Mem (snd stn_st)) a with\n                       | None => None\n                       | Some b => Some (BtoW b)\n                     end).\n  Definition IL_WriteByte : IL_stn_st -> tvarD types tvWord -> tvarD types tvWord -> option IL_stn_st :=\n    (fun stn_st p v => \n      let (stn,st) := stn_st in\n        match IL.WriteByte (Mem st) p (WtoB v) with\n          | None => None\n          | Some m => Some (stn, {| Regs := Regs st ; Mem := m |})\n        end).\n\n  Theorem IL_mem_satisfies_himp : forall cs P Q stn_st,\n    IL_mem_satisfies cs P stn_st ->\n    ST.himp cs P Q ->\n    IL_mem_satisfies cs Q stn_st.\n  Proof.\n    unfold IL_mem_satisfies; intros.\n    eapply sepFormula_himp_imply in H0.\n    2: eapply (refl_equal stn_st). unfold PropXRel.PropX_imply in *.\n    eapply PropX.Imply_E; eauto. \n  Qed.\n  Theorem IL_mem_satisfies_pure : forall cs p Q stn_st,\n    IL_mem_satisfies cs (ST.star (ST.inj p) Q) stn_st ->\n    interp cs p.\n  Proof.\n    unfold IL_mem_satisfies; intros.\n    rewrite sepFormula_eq in H. \n    PropXTac.propxFo; auto.\n  Qed.\n\n  Section ForWord.\n    Local Notation \"'ptrT'\" := (tvType 0) (only parsing).\n    Local Notation \"'valT'\" := (tvType 0) (only parsing).\n\n    Variable mep : MEVAL.PredEval.MemEvalPred types.\n    Variable pred : SEP.predicate types pcT stT.\n    Variable funcs : functions types.\n\n    Hypothesis read_pred_correct : forall P (PE : ProverT_correct P funcs),\n      forall args uvars vars cs facts pe p ve stn st,\n        MEVAL.PredEval.pred_read_word mep P facts args pe = Some ve ->\n        Valid PE uvars vars facts ->\n        exprD funcs uvars vars pe ptrT = Some p ->\n        match \n          applyD (exprD funcs uvars vars) (SEP.SDomain pred) args _ (SEP.SDenotation pred)\n          with\n          | None => False\n          | Some p => ST.satisfies cs p stn st\n        end ->\n        match exprD funcs uvars vars ve valT with\n          | Some v =>\n            ST.HT.smem_get_word (implode stn) p st = Some v\n          | _ => False\n        end.\n\n    Hypothesis write_pred_correct : forall P (PE : ProverT_correct P funcs),\n      forall args uvars vars cs facts pe p ve v stn st args',\n        MEVAL.PredEval.pred_write_word mep P facts args pe ve = Some args' ->\n        Valid PE uvars vars facts ->\n        exprD funcs uvars vars pe ptrT = Some p ->\n        exprD funcs uvars vars ve valT = Some v ->\n        match\n          applyD (@exprD _ funcs uvars vars) (SEP.SDomain pred) args _ (SEP.SDenotation pred)\n          with\n          | None => False\n          | Some p => ST.satisfies cs p stn st\n        end ->\n        match \n          applyD (@exprD _ funcs uvars vars) (SEP.SDomain pred) args' _ (SEP.SDenotation pred)\n          with\n          | None => False\n          | Some pr => \n            match ST.HT.smem_set_word (explode stn) p v st with\n              | None => False\n              | Some sm' => ST.satisfies cs pr stn sm'\n            end\n        end.\n\n    Hypothesis read_pred_byte_correct : forall P (PE : ProverT_correct P funcs),\n      forall args uvars vars cs facts pe p ve stn st,\n        MEVAL.PredEval.pred_read_byte mep P facts args pe = Some ve ->\n        Valid PE uvars vars facts ->\n        exprD funcs uvars vars pe ptrT = Some p ->\n        match \n          applyD (exprD funcs uvars vars) (SEP.SDomain pred) args _ (SEP.SDenotation pred)\n          with\n          | None => False\n          | Some p => ST.satisfies cs p stn st\n        end ->\n        match ST.HT.smem_get p st with\n          | Some b => exprD funcs uvars vars ve valT = Some (BtoW b)\n          | _ => False\n        end.\n\n    Hypothesis write_pred_byte_correct : forall P (PE : ProverT_correct P funcs),\n      forall args uvars vars cs facts pe p ve v stn st args',\n        MEVAL.PredEval.pred_write_byte mep P facts args pe ve = Some args' ->\n        Valid PE uvars vars facts ->\n        exprD funcs uvars vars pe ptrT = Some p ->\n        exprD funcs uvars vars ve valT = Some v ->\n        match\n          applyD (@exprD _ funcs uvars vars) (SEP.SDomain pred) args _ (SEP.SDenotation pred)\n          with\n          | None => False\n          | Some p => ST.satisfies cs p stn st\n        end ->\n        match \n          applyD (@exprD _ funcs uvars vars) (SEP.SDomain pred) args' _ (SEP.SDenotation pred)\n          with\n          | None => False\n          | Some pr => \n            match ST.HT.smem_set p (WtoB v) st with\n              | None => False\n              | Some sm' => ST.satisfies cs pr stn sm'\n            end\n        end.\n\n    Theorem interp_satisfies : forall cs P stn st,\n      PropX.interp cs (SepIL.SepFormula.sepFormula P (stn,st)) <->\n      (HT.satisfies (memoryIn (IL.Mem st)) (IL.Mem st) /\\ ST.satisfies cs P stn (memoryIn (IL.Mem st))).\n    Proof.\n      clear. intros. rewrite sepFormula_eq. unfold sepFormula_def. simpl in *.\n      intuition. eapply ST.HT.satisfies_memoryIn.\n    Qed.\n\n    Require Import Reflection.\n\n    Ltac think :=\n      repeat match goal with\n               | [ H : exists x , _ |- _ ] => destruct H\n               | [ H : _ /\\ _ |- _ ] => destruct H\n             end.\n\n    (** TODO: find a better place for these! **)\n    Lemma mem_set_relevant_memoryIn : forall m p v m',\n      H.mem_set m p v = Some m' ->\n      relevant (memoryIn m) = relevant (memoryIn m').\n    Proof.\n      clear. do 5 intro. unfold relevant, memoryIn, HT.memoryIn. generalize H.all_addr.\n      induction l; simpl; auto; intros.\n      unfold H.mem_set, WriteByte, H.mem_get, ReadByte in *.\n      destruct (equiv_dec a p); unfold equiv in *; subst.\n      destruct (m p); try congruence. inversion H; simpl in *. destruct (weq p p); try congruence.\n\n      destruct (m p); try congruence. inversion H. subst.\n      destruct (weq a p). subst; congruence.\n      rewrite IHl. reflexivity.\n    Qed.\n\n\n    Lemma mem_set_word_relevant_memoryIn : forall (p v : Memory.W) x1 m p0,\n      Memory.mem_set_word H.addr H.mem H.footprint_w H.mem_set p0 p v m =\n      Some x1 -> relevant (memoryIn x1) = relevant (memoryIn m).\n    Proof.\n      clear.\n      unfold Memory.mem_set_word; do 2 intro. destruct (H.footprint_w p).\n      destruct p1. destruct p1. do 2 destruct p0. destruct p1. \n      repeat match goal with\n               | [ |- match ?X with _ => _ end = _ -> _ ] => case_eq X; try congruence; intro; intro\n               | [ |- _ -> _ ] => intros\n               | [ H : H.mem_set _ _ _ = Some _ |- _ ] =>\n                 eapply mem_set_relevant_memoryIn in H\n             end.\n      congruence.\n    Qed.\n\n    Lemma mep_correct : @MEVAL.PredEval.MemEvalPred_correct types pcT stT (IL.settings * IL.state)\n      (tvType 0) (tvType 0) IL_mem_satisfies IL_ReadWord IL_WriteWord IL_ReadByte IL_WriteByte mep pred funcs.\n    Proof.\n      constructor; intros; destruct stn_st as [ stn st ];\n        match goal with\n          | [ H : match ?X with _ => _ end |- _ ] =>\n            revert H; case_eq X; intros; try contradiction\n        end.\n\n      { eapply interp_satisfies in H3. think.\n        apply satisfies_star in H4. think.\n        eapply read_pred_correct in H; eauto.\n        Focus 2. simpl in *.\n        match goal with\n          | [ H : applyD ?A ?B ?C ?D ?E = _ |- match ?X with _ => _ end ] =>\n            change X with (applyD A B C D E); rewrite H\n        end. eassumption.\n\n        revert H; consider (exprD funcs uvars vars ve tvWord); intros; auto.\n        unfold IL_ReadWord, ReadWord. simpl.\n        eapply satisfies_get_word; eauto.\n        eapply split_smem_get_word; eauto. }\n\n      { eapply interp_satisfies in H4. think.\n        apply satisfies_star in H5. think.\n        eapply write_pred_correct in H; eauto.\n        Focus 2. simpl in *.\n        match goal with\n          | [ H : applyD ?A ?B ?C ?D ?E = _ |- match ?X with _ => _ end ] =>\n            change X with (applyD A B C D E); rewrite H\n        end. eassumption.\n        revert H.\n        match goal with\n          | [ |- match ?X with _ => _ end -> match ?Y with _ => _ end ] =>\n            change X with Y; consider Y; intros; auto\n        end.\n        revert H8. consider (smem_set_word (explode stn) p v x); try contradiction; intros.\n        unfold IL_WriteWord, WriteWord in *.\n        unfold split in *. intuition.\n        eapply split_set_word in H8; eauto. think.\n        generalize H8.\n        eapply satisfies_set_word in H8; eauto. think. \n        simpl in *. rewrite H8. unfold IL_mem_satisfies.\n        generalize satisfies_star. unfold ST.satisfies. rewrite sepFormula_eq. unfold sepFormula_def; simpl.\n        intros. eapply H13; clear H13. exists s. exists x0. intuition.\n        unfold split. intuition.\n        eapply relevant_eq; eauto. 2: apply satisfies_memoryIn.\n        eapply smem_set_word_relevant in H14. rewrite <- H14. rewrite <- H11.\n          \n        eapply mem_set_word_relevant_memoryIn; eauto.\n        rewrite <- H11; apply satisfies_memoryIn. }\n\n      { eapply interp_satisfies in H3. think.\n        apply satisfies_star in H4. think.\n        eapply read_pred_byte_correct in H; eauto.\n        Focus 2. simpl in *.\n        match goal with\n          | [ H : applyD ?A ?B ?C ?D ?E = _ |- match ?X with _ => _ end ] =>\n            change X with (applyD A B C D E); rewrite H\n        end. eassumption.\n\n        consider (smem_get p x); intros; auto; try tauto.\n        revert H; consider (exprD funcs uvars vars ve tvWord); intros; auto; try discriminate.\n        injection H7; clear H7; intros; subst.\n        unfold IL_ReadByte, ReadByte. simpl.\n        eapply split_smem_get in H4; eauto.\n        eapply satisfies_get in H4; eauto.\n        unfold H.mem_get, ReadByte in H4; rewrite H4.\n        reflexivity. }\n\n      { eapply interp_satisfies in H4. think.\n        apply satisfies_star in H5. think.\n        eapply write_pred_byte_correct in H; eauto.\n        Focus 2. simpl in *.\n        match goal with\n          | [ H : applyD ?A ?B ?C ?D ?E = _ |- match ?X with _ => _ end ] =>\n            change X with (applyD A B C D E); rewrite H\n        end. eassumption.\n        revert H.\n        match goal with\n          | [ |- match ?X with _ => _ end -> match ?Y with _ => _ end ] =>\n            change X with Y; consider Y; intros; auto\n        end.\n        revert H8. consider (smem_set p (WtoB v) x); try contradiction; intros.\n        unfold IL_WriteByte, WriteByte in *.\n\n        Lemma smem_set'_present : forall p v ls m m',\n          smem_set' ls p v m = Some m'\n          -> exists v', smem_get' ls p m = Some v'.\n          clear; induction ls; simpl; intuition.\n          discriminate.\n          destruct (H.addr_dec a p); subst; eauto.\n          destruct (DepList.hlist_hd m); eauto; discriminate.\n          specialize (IHls (DepList.hlist_tl m)).\n          destruct (smem_set' ls p v (DepList.hlist_tl m)); eauto; discriminate.\n        Qed.\n\n        Lemma smem_set_present : forall p v m m',\n          smem_set p v m = Some m'\n          -> exists v', smem_get p m = Some v'.\n          intros; eapply smem_set'_present; eauto.\n        Qed.\n\n        destruct (smem_set_present _ _ _ H8).\n        generalize H5; intro Ho; eapply split_smem_get in Ho; eauto.\n        eapply satisfies_get in Ho; eauto.\n        unfold H.mem_get, ReadByte in Ho; rewrite Ho.\n        hnf; rewrite sepFormula_eq; PropXTac.propxFo.\n        exists s; exists x0; intuition.\n        unfold split in *; intuition.\n\n        Lemma smem_set'_disjoint : forall p v ls m m' m'',\n          smem_set' ls p v m = Some m'\n          -> disjoint' ls m m''\n          -> disjoint' ls m' m''.\n          clear; induction ls; simpl; intuition.\n          destruct (H.addr_dec a p); subst.\n          rewrite H0 in H; discriminate.\n          specialize (IHls (DepList.hlist_tl m)).\n          destruct (smem_set' ls p v (DepList.hlist_tl m)); try discriminate.\n          injection H; clear H; intros; subst; auto.\n          destruct (H.addr_dec a p); subst.\n          rewrite H0 in H; discriminate.\n          specialize (IHls (DepList.hlist_tl m)).\n          destruct (smem_set' ls p v (DepList.hlist_tl m)); try discriminate.\n          injection H; clear H; intros; subst; auto.\n          destruct (H.addr_dec a p); subst.\n          destruct (DepList.hlist_hd m); try discriminate.\n          injection H; clear H; intros; subst; auto.\n          specialize (IHls (DepList.hlist_tl m)).\n          destruct (smem_set' ls p v (DepList.hlist_tl m)); try discriminate.\n          injection H; clear H; intros; subst; auto.\n        Qed.\n\n        Lemma smem_set_disjoint : forall p v m m' m'',\n          smem_set p v m = Some m'\n          -> disjoint m m''\n          -> disjoint m' m''.\n          intros; eapply smem_set'_disjoint; eauto.\n        Qed.\n\n        eauto using smem_set_disjoint.\n\n        Lemma parts : forall A (B : A -> Type) x ls (h1 h2 : B x) (t1 t2 : DepList.hlist B ls),\n          DepList.HCons h1 t1 = DepList.HCons h2 t2\n          -> h1 = h2 /\\ t1 = t2.\n          clear; intros.\n          assert (DepList.hlist_hd (DepList.HCons h1 t1) = DepList.hlist_hd (DepList.HCons h2 t2)) by congruence.\n          assert (DepList.hlist_tl (DepList.HCons h1 t1) = DepList.hlist_tl (DepList.HCons h2 t2)) by congruence.\n          auto.\n        Qed.\n\n        Lemma memoryIn'_agree : forall ls m1 m2,\n          List.Forall (fun p => m1 p = m2 p) ls\n          -> memoryIn' m1 ls = memoryIn' m2 ls.\n          clear; induction 1; simpl; intuition.\n          f_equal; auto.\n        Qed.\n\n        Lemma memoryIn'_join : forall m p v ls, NoDup ls\n          -> forall m1 m2 m1',\n            memoryIn' m ls = join' ls m1 m2\n            -> smem_set' ls p v m1 = Some m1'\n            -> memoryIn' (fun p' => if weq p' p then Some v else m p') ls = join' ls m1' m2.\n          clear; induction 1; simpl; intuition.\n          apply parts in H1; destruct H1.\n          destruct (H.addr_dec x p); subst.\n          destruct (DepList.hlist_hd m1); try discriminate.\n          injection H2; clear H2; intros; subst.\n          simpl.\n          f_equal.\n          unfold H.mem_get, ReadByte; destruct (weq p p); tauto.\n          rewrite (@memoryIn'_agree _ _ m); auto.\n          apply Forall_forall; intros.\n          destruct (weq x p); subst; tauto.\n          specialize (IHNoDup (DepList.hlist_tl m1)).\n          destruct (smem_set' l p v (DepList.hlist_tl m1)); try discriminate.\n          rewrite (IHNoDup _ _ H3 eq_refl); clear IHNoDup.\n          injection H2; clear H2; intros; subst; simpl.\n          f_equal; auto.\n          unfold H.mem_get, ReadByte.\n          destruct (weq x p); intuition.\n        Qed.\n\n        Lemma memoryIn_join : forall m m1 m2 p v m1',\n          memoryIn m = join m1 m2\n          -> smem_set p v m1 = Some m1'\n          -> memoryIn (fun p' => if weq p' p then Some v else m p') = join m1' m2.\n          intros; eapply memoryIn'_join; eauto using H.NoDup_all_addr.\n        Qed.\n        \n        eauto using memoryIn_join. }\n    Qed.\n\n    Variable predIndex : nat.\n\n    Theorem MemPredEval_To_MemEvaluator_correct preds : \n      nth_error preds predIndex = Some pred ->\n      @MEVAL.MemEvaluator_correct types pcT stT\n      (@MEVAL.PredEval.MemEvalPred_to_MemEvaluator _ pcT stT mep predIndex) funcs preds\n      (IL.settings * IL.state) (tvType 0) (tvType 0) IL_mem_satisfies\n      IL_ReadWord IL_WriteWord IL_ReadByte IL_WriteByte.\n    Proof.\n      intros.\n      eapply MEVAL.PredEval.MemEvaluator_MemEvalPred_correct; simpl;\n        try eauto using IL_mem_satisfies_himp, IL_mem_satisfies_pure, mep_correct.\n    Qed.\n\n  End ForWord.\n\nEnd spec_functions.\n", "meta": {"author": "csgordon", "repo": "bedrock", "sha": "debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12", "save_path": "github-repos/coq/csgordon-bedrock", "path": "github-repos/coq/csgordon-bedrock/bedrock-debab1b6e491b7c5e83bd3b1fe5d0e4c4e728d12/src/SymIL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043814, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.23903422317733086}}
{"text": "(************************************************************************)\n(*  v      *   The Coq Proof Assistant  /  The Coq Development Team     *)\n(* <O___,, *   INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2016     *)\n(*   \\VV/  **************************************************************)\n(*    //   *      This file is distributed under the terms of the       *)\n(*         *       GNU Lesser General Public License Version 2.1        *)\n(************************************************************************)\n\n(** These are the notations whose level and associativity are imposed by Coq *)\n\n(** Notations for propositional connectives *)\n\nReserved Notation \"x -> y\" (at level 99, right associativity, y at level 200).\nReserved Notation \"x <-> y\" (at level 95, no associativity).\nReserved Notation \"x /\\ y\" (at level 80, right associativity).\nReserved Notation \"x \\/ y\" (at level 85, right associativity).\nReserved Notation \"x |_| y\" (at level 85, right associativity).\nReserved Notation \"~ x\" (at level 75, right associativity).\n\n(** Notations for equality and inequalities *)\n\nReserved Notation \"x = y  :>  T\"\n(at level 70, y at next level, no associativity).\nReserved Notation \"x = y\" (at level 70, no associativity).\nReserved Notation \"x = y = z\"\n(at level 70, no associativity, y at next level).\n\nReserved Notation \"x <> y  :>  T\"\n(at level 70, y at next level, no associativity).\nReserved Notation \"x <> y\" (at level 70, no associativity).\n\nReserved Notation \"x <= y\" (at level 70, no associativity).\nReserved Notation \"x < y\" (at level 70, no associativity).\nReserved Notation \"x >= y\" (at level 70, no associativity).\nReserved Notation \"x > y\" (at level 70, no associativity).\n\nReserved Notation \"x <= y <= z\" (at level 70, y at next level).\nReserved Notation \"x <= y < z\" (at level 70, y at next level).\nReserved Notation \"x < y < z\" (at level 70, y at next level).\nReserved Notation \"x < y <= z\" (at level 70, y at next level).\n\n(** Arithmetical notations (also used for type constructors) *)\n\nReserved Notation \"x + y\" (at level 50, left associativity).\nReserved Notation \"x - y\" (at level 50, left associativity).\nReserved Notation \"x * y\" (at level 40, left associativity).\nReserved Notation \"x / y\" (at level 40, left associativity).\nReserved Notation \"- x\" (at level 35, right associativity).\nReserved Notation \"/ x\" (at level 35, right associativity).\nReserved Notation \"x ^ y\" (at level 30, right associativity).\n\n(** Notations for booleans *)\n\nReserved Notation \"x || y\" (at level 50, left associativity).\nReserved Notation \"x && y\" (at level 40, left associativity).\n\n(** Notations for pairs *)\n\nReserved Notation \"( x , y , .. , z )\" (at level 0).\n\n(** Notation \"{ x }\" is reserved and has a special status as component\n    of other notations such as \"{ A } + { B }\" and \"A + { B }\" (which\n    are at the same level as \"x + y\");\n    \"{ x }\" is at level 0 to factor with \"{ x : A | P }\" *)\n\nReserved Notation \"{ x }\" (at level 0, x at level 99).\n\n(** Notations for sigma-types or subsets *)\n\nReserved Notation \"{ x  |  P }\" (at level 0, x at level 99).\nReserved Notation \"{ x  |  P  & Q }\" (at level 0, x at level 99).\n\nReserved Notation \"{ x : A  |  P }\" (at level 0, x at level 99).\nReserved Notation \"{ x : A  |  P  & Q }\" (at level 0, x at level 99).\n\nReserved Notation \"{ x : A  & P }\" (at level 0, x at level 99).\nReserved Notation \"{ x : A  & P  & Q }\" (at level 0, x at level 99).\n\nDeclare Scope core_scope.\nDelimit Scope core_scope with core.\n\nDeclare Scope function_scope.\nDelimit Scope function_scope with function.\nBind Scope function_scope with Funclass.\n\nDeclare Scope type_scope.\nDelimit Scope type_scope with type.\nBind Scope type_scope with Sortclass.\n\nOpen Scope core_scope.\nOpen Scope function_scope.\nOpen Scope type_scope.\n\n(** ML Tactic Notations *)\n\nDeclare ML Module \"ltac_plugin\".\n\nGlobal Set Default Proof Mode \"Classic\".\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/coq/theories/Init/Notations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2390124686100395}}
{"text": "Require Import Coq.Lists.List.\nRequire Import ProD3.core.Coqlib.\nRequire Import ProD3.core.ExtPred.\nRequire Import ProD3.core.Result.\nRequire Import ProD3.core.FuncSpec.\nRequire Import Hammer.Plugin.Hammer.\n\n(* Section DisjointTest. *)\n\n(* Context {tags_t: Type} {tags_t_inhabitant : Inhabitant tags_t}.\nNotation Val := (@ValueBase bool).\nNotation Sval := (@ValueBase (option bool)).\nNotation Lval := ValueLvalue.\n\nNotation ident := (String.string).\nNotation path := (list ident).\n\nContext `{target : @Target tags_t (@Expression tags_t)}. *)\n\nLtac res_list :=\n  lazymatch goal with\n  | |- res_list ?P ?l =>\n      first [\n        apply rnil\n      | apply rcons;\n        only 2 : res_list\n      ]\n  | |- _ =>\n      fail \"The goal is not (res_list _ _)\"\n  end.\n\n(* Import String.\nOpen Scope string_scope. *)\n\nLemma disjoint_cancel : forall p q1 q2,\n  disjoint q1 q2 ->\n  disjoint (p ++ q1) (p ++ q2).\nProof.\n  induction p; intros.\n  - auto.\n  - simpl.\n    replace (String.eqb a a) with true by hauto use: String.eqb_eq.\n    auto.\nQed.\n\n(* This is a preliminary implementation. It only tests verbatim paths. We use this tactic to\n  test the rest tactics. *)\nLtac test_disjoint :=\n  refine (@id (result (disjoint _ _)) _);\n  first [\n    left; try apply disjoint_cancel; reflexivity\n  | right; exact I\n  ].\n\n(* Axiom p : list string.\nDefinition x := result (disjoint (p ++ [\"a\"]) (p ++ [\"c\"])).\n\nGoal x.\n  test_disjoint.\n  Show Proof.\nAbort.\n\nGoal result (disjoint [] [\"c\"]).\n  test_disjoint.\n  Show Proof.\nAbort. *)\n\nLtac test_ext_exclude :=\n  res_list;\n  apply Result.forallb;\n  res_list;\n  apply Result.forallb;\n  res_list;\n  test_disjoint.\n", "meta": {"author": "verified-network-toolchain", "repo": "VerifiableP4", "sha": "87afa7bef7d88da2e9a642e37c0ddb2412b57509", "save_path": "github-repos/coq/verified-network-toolchain-VerifiableP4", "path": "github-repos/coq/verified-network-toolchain-VerifiableP4/VerifiableP4-87afa7bef7d88da2e9a642e37c0ddb2412b57509/core/DisjointTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23901246187607114}}
{"text": "(** * Functoriality of the comma category construction *)\nRequire Import Functor.Core NaturalTransformation.Core.\nRequire Import Functor.Composition.Core NaturalTransformation.Composition.Core.\nRequire Import NaturalTransformation.Composition.Laws.\nRequire Import Functor.Paths.\nRequire Import Category.Strict.\nRequire Comma.Core.\nLocal Set Warnings Append \"-notation-overridden\". (* work around bug #5567, https://coq.inria.fr/bugs/show_bug.cgi?id=5567, notation-overridden,parsing should not trigger for only printing notations *)\nImport Comma.Core.\nLocal Set Warnings Append \"notation-overridden\".\nImport Functor.Identity.FunctorIdentityNotations NaturalTransformation.Identity.NaturalTransformationIdentityNotations.\nRequire Import HoTT.Tactics PathGroupoids Types.Forall.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\n\nLocal Open Scope morphism_scope.\nLocal Open Scope category_scope.\n\n(** The comma category construction is functorial in its category\n    arguments.  We really should be using ∏ (dependent product) here,\n    but I'm lazy, and will instead expand it out. *)\n\nLocal Ltac helper_t fwd_tac bak_tac fin :=\n  repeat\n    first [ fin\n          | rewrite <- ?Category.Core.associativity;\n            progress repeat first [ bak_tac\n                                  | apply ap10; apply ap ]\n          | rewrite -> ?Category.Core.associativity;\n            progress repeat first [ fwd_tac\n                                  | apply ap ]\n          | rewrite <- !composition_of ].\n\nLocal Tactic Notation \"helper\" tactic(fin) constr(hyp_fwd) constr(hyp_bak) :=\n  let H := fresh in\n  let H' := fresh in\n  pose proof hyp_fwd as H;\n    pose proof hyp_bak as H';\n    simpl in *;\n    helper_t ltac:(rewrite -> H) ltac:(rewrite <- H') fin.\n\nLocal Ltac functorial_helper_t unfold_lem :=\n  repeat (apply path_forall || intro); simpl;\n  rewrite !transport_forall_constant; simpl;\n  transport_path_forall_hammer; simpl;\n  apply CommaCategory.path_morphism; simpl;\n  unfold unfold_lem; simpl;\n  repeat match goal with\n           | _ => exact idpath\n           | [ |- context[CommaCategory.g (transport ?P ?p ?z)] ]\n             => simpl rewrite (@ap_transport _ P _ _ _ p (fun _ => @CommaCategory.g _ _ _ _ _ _ _) z)\n           | [ |- context[CommaCategory.h (transport ?P ?p ?z)] ]\n             => simpl rewrite (@ap_transport _ P _ _ _ p (fun _ => @CommaCategory.h _ _ _ _ _ _ _) z)\n           | [ |- context[transport (fun y => ?f (?g y) ?z)] ]\n             => simpl rewrite (fun a b => @transport_compose _ _ a b (fun y => f y z) g)\n           | [ |- context[transport (fun y => ?f (?g y))] ]\n             => simpl rewrite (fun a b => @transport_compose _ _ a b (fun y => f y) g)\n           | _ => rewrite !CommaCategory.ap_a_path_object'; simpl\n           | _ => rewrite !CommaCategory.ap_b_path_object'; simpl\n         end.\n\nSection functorial.\n  Section single_source.\n    Variables A B C : PreCategory.\n    Variable S : Functor A C.\n    Variable T : Functor B C.\n\n    Section morphism_of.\n      Variables A' B' C' : PreCategory.\n      Variable S' : Functor A' C'.\n      Variable T' : Functor B' C'.\n\n      Variable AF : Functor A A'.\n      Variable BF : Functor B B'.\n      Variable CF : Functor C C'.\n\n      Variable TA : NaturalTransformation (S' o AF) (CF o S).\n      Variable TB : NaturalTransformation (CF o T) (T' o BF).\n\n      Definition functorial_morphism_of_object_of : (S / T) -> (S' / T')\n        := fun x => CommaCategory.Build_object\n                      S' T'\n                      (AF (CommaCategory.a x))\n                      (BF (CommaCategory.b x))\n                      (TB (CommaCategory.b x) o CF _1 (CommaCategory.f x) o TA (CommaCategory.a x)).\n\n      Definition functorial_morphism_of_morphism_of\n                 s d (m : morphism (S / T) s d)\n      : morphism (S' / T') (functorial_morphism_of_object_of s) (functorial_morphism_of_object_of d).\n      Proof.\n        simpl in *.\n        refine (CommaCategory.Build_morphism\n                  (functorial_morphism_of_object_of s)\n                  (functorial_morphism_of_object_of d)\n                  (AF _1 (CommaCategory.g m))\n                  (BF _1 (CommaCategory.h m))\n                  _).\n        unfold functorial_morphism_of_object_of; simpl.\n        clear.\n        abstract helper (exact (CommaCategory.p m)) (commutes TA) (commutes TB).\n      Defined.\n\n      Definition functorial_morphism_of : Functor (S / T) (S' / T').\n      Proof.\n        refine (Build_Functor\n                  (S / T) (S' / T')\n                  functorial_morphism_of_object_of\n                  functorial_morphism_of_morphism_of\n                  _\n                  _);\n        abstract (\n            intros;\n            apply CommaCategory.path_morphism; simpl;\n            auto with functor\n          ).\n      Defined.\n    End morphism_of.\n\n    Section identity_of.\n      Definition functorial_identity_of_helper x\n      : @functorial_morphism_of_object_of _ _ _ S T 1 1 1 1 1 x = x.\n      Proof.\n        let A := match goal with |- ?A = ?B => constr:(A) end in\n        let B := match goal with |- ?A = ?B => constr:(B) end in\n        refine (@CommaCategory.path_object' _ _ _ _ _ A B 1%path 1%path _).\n        exact (Category.Core.right_identity _ _ _ _ @ Category.Core.left_identity _ _ _ _)%path.\n      Defined.\n\n      Definition functorial_identity_of `{Funext}\n      : @functorial_morphism_of\n          _ _ _ S T\n          1 1 1 1 1\n        = 1%functor.\n      Proof.\n        path_functor; simpl.\n        exists (path_forall _ _ functorial_identity_of_helper).\n        simpl.\n        functorial_helper_t functorial_identity_of_helper.\n      Qed.\n    End identity_of.\n  End single_source.\n\n  Section composition_of.\n    Variables A B C : PreCategory.\n    Variable S : Functor A C.\n    Variable T : Functor B C.\n\n    Variables A' B' C' : PreCategory.\n    Variable S' : Functor A' C'.\n    Variable T' : Functor B' C'.\n\n    Variables A'' B'' C'' : PreCategory.\n    Variable S'' : Functor A'' C''.\n    Variable T'' : Functor B'' C''.\n\n    Variable AF : Functor A A'.\n    Variable BF : Functor B B'.\n    Variable CF : Functor C C'.\n\n    Variable TA : NaturalTransformation (S' o AF) (CF o S).\n    Variable TB : NaturalTransformation (CF o T) (T' o BF).\n\n    Variable AF' : Functor A' A''.\n    Variable BF' : Functor B' B''.\n    Variable CF' : Functor C' C''.\n\n    Variable TA' : NaturalTransformation (S'' o AF') (CF' o S').\n    Variable TB' : NaturalTransformation (CF' o T') (T'' o BF').\n\n    Let AF'' := (AF' o AF)%functor.\n    Let BF'' := (BF' o BF)%functor.\n    Let CF'' := (CF' o CF)%functor.\n\n    Let TA'' : NaturalTransformation (S'' o AF'') (CF'' o S)\n      := ((associator_2 _ _ _)\n            o (CF' oL TA)\n            o (associator_1 _ _ _)\n            o (TA' oR AF)\n            o associator_2 _ _ _)%natural_transformation.\n    Let TB'' : NaturalTransformation (CF'' o T) (T'' o BF'')\n      := ((associator_1 _ _ _)\n            o (TB' oR BF)\n            o (associator_2 _ _ _)\n            o (CF' oL TB)\n            o associator_1 _ _ _)%natural_transformation.\n\n    Definition functorial_composition_of_helper x\n    : (functorial_morphism_of TA' TB' o functorial_morphism_of TA TB)%functor x\n      = functorial_morphism_of TA'' TB'' x.\n    Proof.\n      let A := match goal with |- ?A = ?B => constr:(A) end in\n      let B := match goal with |- ?A = ?B => constr:(B) end in\n      refine (@CommaCategory.path_object' _ _ _ _ _ A B 1%path 1%path _).\n      subst AF'' BF'' CF'' TA'' TB''.\n      simpl in *.\n      abstract (\n          autorewrite with morphism; simpl;\n          helper (exact idpath) (commutes TA') (commutes TB')\n        ).\n    Defined.\n\n    Definition functorial_composition_of `{Funext}\n    : (functorial_morphism_of TA' TB' o functorial_morphism_of TA TB)%functor\n      = functorial_morphism_of TA'' TB''.\n    Proof.\n      path_functor; simpl.\n      exists (path_forall _ _ functorial_composition_of_helper).\n      functorial_helper_t functorial_composition_of_helper.\n    Qed.\n  End composition_of.\nEnd functorial.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Categories/Comma/Functorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23898001888212939}}
{"text": "Add LoadPath \"..\".\nRequire Import Hyb_Substitution.\nRequire Import Setoid.\nRequire Import LibList.\nRequire Import PermutLib.\nRequire Import Hyb_PPermutLib.\nRequire Import Hyb_OkLib.\nRequire Import Hyb_EmptyEquivLib.\n\nOpen Scope hybrid_is5_scope.\nOpen Scope is5_scope.\nOpen Scope permut_scope.\n\n(* Notation for term typing *)\nGlobal Reserved Notation \" G '|=' Ctx '|-' M ':::' A \" (at level 70).\n\n\n(*** Definitions ::: Statics ***)\n\n\n(*\n   For each full context (that is, context and background), we require\n   that the variables - both for terms and worlds - are unique.\n*)\nInductive types_Hyb: bg_Hyb -> ctx_Hyb -> te_Hyb -> ty -> Prop :=\n\n| t_hyp_Hyb: forall A G w (Gamma: list (prod var ty)) v\n  (Ok_Bg: ok_Bg_Hyb ((w, Gamma) :: G))\n  (HT: Mem (v, A) Gamma),\n  G |= (w, Gamma) |- hyp_Hyb (fte v) ::: A\n\n| t_lam_Hyb: forall L A B G w Gamma M\n  (Ok_Bg: ok_Bg_Hyb ((w, Gamma) :: G))\n  (HT: forall v', v' \\notin L ->\n    G |= (w, (v', A) :: Gamma) |- M ^t^ (hyp_Hyb (fte v')) ::: B),\n  G |= (w, Gamma) |- (lam_Hyb A M) ::: A ---> B\n\n| t_appl_Hyb: forall A B G w Gamma M N\n  (Ok_Bg: ok_Bg_Hyb ((w, Gamma) :: G))\n  (HT1: G |= (w, Gamma) |- M ::: A ---> B)\n  (HT2: G |= (w, Gamma) |- N ::: A),\n  G |= (w, Gamma) |- (appl_Hyb M N) ::: B\n\n| t_box_Hyb: forall L A G w Gamma M\n  (Ok_Bg: ok_Bg_Hyb (G & (w, Gamma)))\n  (HT: forall w', w' \\notin L ->\n    G & (w, Gamma) |= (w', nil) |- M ^w^ (fwo w') ::: A),\n  G |= (w, Gamma) |- box_Hyb M ::: [*] A\n\n| t_unbox_Hyb: forall A G w Gamma M\n  (Ok_Bg: ok_Bg_Hyb ((w, Gamma) :: G))\n  (HT: G |= (w, Gamma) |- M ::: [*] A),\n  G |= (w, Gamma) |- unbox_fetch_Hyb (fwo w) M ::: A\n\n| t_unbox_fetch_Hyb: forall A G w Gamma w' Gamma' M\n  (Ok_Bg: ok_Bg_Hyb ((w, Gamma) :: G & (w', Gamma')))\n  (HT: (G & (w', Gamma')) |= (w, Gamma) |- M ::: [*] A),\n  forall G', (G & (w, Gamma)) ~=~ G' ->\n    G' |= (w', Gamma') |- unbox_fetch_Hyb (fwo w) M ::: A\n\n| t_here_Hyb: forall A G w Gamma M\n  (Ok_Bg: ok_Bg_Hyb ((w, Gamma) :: G))\n  (HT: G |= (w, Gamma) |- M ::: A),\n  G |= (w, Gamma) |- get_here_Hyb (fwo w) M ::: <*> A\n\n| t_get_here_Hyb: forall A G w Gamma w' Gamma' M\n  (Ok_Bg: ok_Bg_Hyb ((w, Gamma) :: G & (w', Gamma')))\n  (HT: G & (w', Gamma') |= (w, Gamma) |- M ::: A),\n  forall G', (G & (w, Gamma)) ~=~ G' ->\n    G' |= (w', Gamma') |- get_here_Hyb (fwo w) M ::: <*> A\n\n| t_letdia_Hyb: forall L_w L_t A B G w Gamma M N\n  (Ok_Bg: ok_Bg_Hyb ((w, Gamma) :: G))\n  (HT1: G |= (w, Gamma) |- M ::: <*> A)\n  (HT2: forall v', v' \\notin L_t -> forall w', w' \\notin L_w ->\n    (w', (v', A) :: nil) :: G |=\n      (w, Gamma) |- (N ^w^ (fwo w')) ^t^ (hyp_Hyb (fte v')) ::: B),\n  G |= (w, Gamma) |- letdia_get_Hyb (fwo w) M N ::: B\n\n| t_letdia_get_Hyb: forall L_w L_t A B G w (Gamma: list (prod var ty)) Ctx' M N\n  (Ok_Bg: ok_Bg_Hyb ((w, Gamma) :: G & Ctx'))\n  (HT1: G & Ctx' |= (w, Gamma) |- M ::: <*> A)\n  (HT2: forall v', v' \\notin L_t -> forall w', w' \\notin L_w ->\n    (w', ((v', A) :: nil)) :: G & (w, Gamma) |=\n      Ctx' |- (N ^w^ (fwo w')) ^t^ (hyp_Hyb (fte v')) ::: B),\n  forall G0, (G & (w, Gamma)) ~=~ G0 ->\n    G0 |= Ctx' |- letdia_get_Hyb (fwo w) M N ::: B\n\nwhere \" G '|=' Ctx '|-' M ':::' A \" := (types_Hyb G Ctx M A)\n  : hybrid_is5_scope.\n\n\n(*** Definitions ::: Dynamics ***)\n\n\nInductive value_Hyb: te_Hyb -> Prop :=\n| val_lam_Hyb: forall A M, value_Hyb (lam_Hyb A M)\n| val_box_Hyb: forall M, value_Hyb (box_Hyb M)\n| val_get_here_Hyb: forall M Ctx, value_Hyb M -> value_Hyb (get_here_Hyb Ctx M)\n.\n\n\nGlobal Reserved Notation \" M |-> N \" (at level 70).\n\n(*\n   In order to define a step of reduction we require that certain terms\n   are locally closed.\n*)\nInductive step_Hyb: (te_Hyb * vwo) -> (te_Hyb * vwo) -> Prop :=\n| red_appl_lam_Hyb: forall ctx M A N,\n  lc_w_Hyb M ->\n  lc_t_n_Hyb 1 M ->\n  lc_w_Hyb N -> lc_t_Hyb N ->\n  (appl_Hyb (lam_Hyb A M) N, ctx) |-> ( M ^t^ N , ctx)\n\n| red_unbox_fetch_box_Hyb: forall ctx ctx' M,\n   lc_w_n_Hyb 1 M ->\n  lc_t_Hyb M ->\n  (unbox_fetch_Hyb ctx' (box_Hyb M), ctx) |-> (M ^w^ ctx, ctx)\n\n| red_letdia_get_get_here_Hyb: forall ctx ctx' ctx'' M N,\n  lc_w_Hyb M -> lc_t_Hyb M ->\n  lc_w_n_Hyb 1 N ->\n  lc_t_n_Hyb 1 N -> value_Hyb M ->\n  (letdia_get_Hyb ctx' (get_here_Hyb ctx'' M) N, ctx) |->\n    ((N ^w^ ctx'') ^t^ M, ctx)\n\n| red_appl_Hyb: forall ctx M N M'\n  (HT: (M, ctx) |-> (M', ctx)),\n  lc_w_Hyb M -> lc_t_Hyb M ->\n  lc_w_Hyb N -> lc_t_Hyb N ->\n  (appl_Hyb M N, ctx) |-> (appl_Hyb M' N, ctx)\n\n| red_unbox_fetch_Hyb: forall ctx' M M' ctx\n  (HT: (M, ctx') |-> (M', ctx')),\n  lc_w_Hyb M -> lc_t_Hyb M ->\n  (unbox_fetch_Hyb ctx' M, ctx) |-> (unbox_fetch_Hyb ctx' M', ctx)\n\n| red_get_here_Hyb: forall ctx ctx' M M'\n  (HT: (M, ctx) |-> (M', ctx)),\n  lc_w_Hyb M -> lc_t_Hyb M ->\n  (get_here_Hyb ctx M, ctx') |-> (get_here_Hyb ctx M', ctx')\n\n| red_letdia_get_Hyb: forall ctx ctx' M N M'\n  (HT: (M, ctx) |-> (M', ctx)),\n  lc_w_Hyb M -> lc_t_Hyb M ->\n  lc_w_n_Hyb 1 N ->\n  lc_t_n_Hyb 1 N ->\n  (letdia_get_Hyb ctx M N, ctx') |-> (letdia_get_Hyb ctx M' N, ctx')\n\nwhere \" M |-> N \" := (step_Hyb M N ) : hybrid_is5_scope.\n\n\nInductive steps_Hyb : te_Hyb * vwo -> te_Hyb * vwo -> Prop :=\n| single_step_Hyb: forall M M' w, (M, w) |-> (M', w) -> steps_Hyb (M, w) (M', w)\n| multi_step_Hyb: forall M M' M'' w,\n  (M, w) |-> (M', w) -> steps_Hyb (M', w) (M'', w)\n  -> steps_Hyb (M, w) (M'', w)\n.\n\nNotation \" M |->+ N \" := (steps_Hyb M N) (at level 70) : hybrid_is5_scope.\n\n\n(*** Properties ***)\n\n\n(*\n   Properties of background and context:\n   * Background is defined up to ~=~ relation\n   * Context is defined up to *=* relation\n   * Weakening rules for\n     * Background\n     * Specific element of background\n     * Main context\n*)\n\n(* Proof: simple induction on typing rules *)\nLemma BackgroundSubsetImpl_Hyb:\nforall G G' Ctx M A\n  (HT: G |= Ctx |- M ::: A)\n  (HSubst: exists GT, (G++GT) ~=~ G')\n  (H_ok: ok_Bg_Hyb (Ctx :: G')),\n  G' |= Ctx |- M ::: A.\nintros;\ngeneralize dependent G';\ninduction HT; intros.\n(* hyp *)\nconstructor; auto.\n(* lam *)\napply t_lam_Hyb with (L:=L \\u used_t_vars_Hyb ((w, Gamma)::G'));\n[assumption | intros; eapply H; auto].\n(* appl *)\neconstructor; auto.\n(* box *)\ndestruct HSubst as [GT];\napply t_box_Hyb with (L:=L \\u used_w_vars_Hyb (G' & (w, Gamma))); intros;\n[ apply ok_Bg_Hyb_cons_last |\n  apply H; [ | exists GT | ] ]; auto; try PPermut_Hyb_simpl;\neapply ok_Bg_Hyb_fresh_wo;\n[ apply ok_Bg_Hyb_cons_last |\n  rewrite notin_union in H1; destruct H1]; auto.\n(* unbox *)\nconstructor; auto.\n(* unbox_fetch *)\ndestruct HSubst as [GT];\napply t_unbox_fetch_Hyb with (Gamma:=Gamma) (G:=G++GT).\napply ok_Bg_Hyb_ppermut with (G:=(w', Gamma')::G'0);\n  [rewrite <- H0; rewrite <- H; rew_app | ]; auto.\napply IHHT; [exists GT | ]; auto; try PPermut_Hyb_simpl.\napply ok_Bg_Hyb_ppermut with (G:=(w', Gamma')::G'0); auto.\nrewrite <- H0; rewrite <- H; rew_app; auto.\ntransitivity (G' ++ GT); PPermut_Hyb_simpl; auto.\n(* here *)\nconstructor; auto.\n(* get_here *)\ndestruct HSubst as [GT];\napply t_get_here_Hyb with (Gamma:=Gamma) (G:=G++GT).\napply ok_Bg_Hyb_ppermut with (G:=(w', Gamma')::G'0);\n  [rewrite <- H0; rewrite <- H; rew_app | ]; auto.\napply IHHT; [exists GT | ]; auto; try PPermut_Hyb_simpl;\n  apply ok_Bg_Hyb_ppermut with (G:=(w', Gamma')::G'0); auto;\n  rewrite <- H0; rewrite <- H; rew_app; auto.\nrewrite <- H0; rewrite <- H; rew_app; auto.\n(* letdia *)\napply t_letdia_Hyb with (A:=A) (L_t:=L_t \\u used_t_vars_Hyb ((w, Gamma) :: G'))\n  (L_w:=L_w \\u used_w_vars_Hyb ((w, Gamma)::G'));\n[  | | intros; apply H]; auto;\ndestruct HSubst as [GT];\n[ exists GT; rew_app; auto |\n  rewrite notin_union in *; destruct H1; destruct H0];\napply ok_Bg_Hyb_ppermut with (G:= (w', (v', A) :: nil ) :: (w, Gamma) :: G');\n[ | apply ok_Bg_Hyb_fresh_wo_te]; auto.\n(* letdia_get *)\ndestruct HSubst as [GT];\napply t_letdia_get_Hyb with (A:=A) (Gamma:=Gamma) (G:=G++GT)\n                           (L_t:=L_t \\u used_t_vars_Hyb (Ctx'::G'))\n                           (L_w:=L_w \\u used_w_vars_Hyb (Ctx'::G')).\napply ok_Bg_Hyb_ppermut with (G:=Ctx' :: G');\n  [rewrite <- H1; rewrite <- H0; rew_app | ]; auto.\napply IHHT.\n  exists GT; rew_app; auto.\n  apply ok_Bg_Hyb_ppermut with (G:=Ctx' :: G');\n  [ rewrite <- H1; rewrite <- H0; rew_app | ]; auto.\n  intros; apply H; auto.\n  exists GT; rew_app; auto.\n  apply ok_Bg_Hyb_ppermut with (G:=(w', (v', A) :: nil) :: Ctx' :: G'); auto;\n  rewrite <- H1; rewrite <- H0;\n  assert ((G & (w, Gamma) ++ GT)  ~=~ (G ++ GT) & (w, Gamma))\n    by (symmetry; rew_app; auto);\n  rewrite H4; destruct Ctx'; auto.\nrewrite <- H1; rewrite <- H0; rew_app; auto.\nQed.\n\n\n(*\n   Proof: using BackgroundSubsetImpl with some tweaks to remove ok_Bg_Hyb from\n   assumptions.\n*)\nLemma PPermut_Hyb_bg:\nforall G Gamma w M A,\n  G |= (w, Gamma) |- M ::: A ->\n    forall G',\n      G ~=~ G' ->\n      G' |= (w, Gamma) |- M ::: A.\nintros; apply BackgroundSubsetImpl_Hyb with (G:=G);\n[ | exists (@nil ctx_Hyb) | ]; rew_app; auto;\ninversion H; subst;\ntry (apply ok_Bg_Hyb_ppermut with (G:=(w, Gamma) :: G); auto);\napply ok_Bg_Hyb_cons_last; auto;\nrewrite <- H6 || rewrite <- H1;\napply ok_Bg_Hyb_ppermut with (G:=(w0, Gamma0) :: G0 & (w, Gamma)); eauto.\nQed.\n\n\n(*\n   Adding types_Hyb as morphism for PPermut_Hyb will allow us to simply rewrite\n   PPermut_Hybations of backgrounds.\n*)\nAdd Morphism types_Hyb : PPermut_Hyb_types.\nsplit; intros; destruct y0;\n[ apply PPermut_Hyb_bg with (G:=x) |\n  apply PPermut_Hyb_bg with (G:=y) ]; auto.\nQed.\n\n\n(* Proof: Simple induction on typing rules *)\nLemma ContextPermutImpl_Hyb:\nforall G Gamma Gamma' w M A\n  (HPerm: Gamma *=* Gamma')\n  (HT: G |= (w, Gamma) |- M ::: A),\n  G |= (w, Gamma') |- M ::: A.\nintros; generalize dependent Gamma';\nremember (w, Gamma) as Ctx; generalize dependent Gamma;\ninduction HT;\nintros; simpl in *; try (inversion HeqCtx; subst).\n(* hyp *)\nconstructor;\n[ eapply ok_Bg_Hyb_permut |\n  eapply Mem_permut]; eauto.\n(* lam *)\neconstructor; [ eapply ok_Bg_Hyb_permut | ]; eauto.\n(* appl *)\neconstructor; [ eapply ok_Bg_Hyb_permut | | ]; eauto.\n(* box *)\neconstructor; [ eapply ok_Bg_Hyb_permut_last | intros]; eauto;\nassert (G & (w, Gamma') ~=~ G & (w, Gamma0)) by auto;\nrewrite H1; apply HT; eauto.\n(* unbox *)\neconstructor; [ eapply ok_Bg_Hyb_permut | ]; eauto.\n(* unbox_fetch *)\napply t_unbox_fetch_Hyb with (G:=G) (Gamma:=Gamma); auto.\napply ok_Bg_Hyb_ppermut with (G:=(w0, Gamma) :: G & (w, Gamma0)); auto.\nassert (G & (w, Gamma'0) ~=~ (G & (w, Gamma0))) as H0 by auto;\nrewrite H0; auto.\n(* here *)\neconstructor; [ eapply ok_Bg_Hyb_permut | ]; eauto.\n(* get_here *)\napply t_get_here_Hyb with (G:=G) (Gamma:=Gamma); auto.\napply ok_Bg_Hyb_ppermut with (G:=(w0, Gamma) :: G & (w, Gamma0)); auto.\nassert (G & (w, Gamma'0) ~=~ (G & (w, Gamma0))) as H1 by auto;\nrewrite H1; auto.\n(* letdia *)\neconstructor; [ eapply ok_Bg_Hyb_permut | | ]; eauto.\n(* letdia_get *)\napply t_letdia_get_Hyb with (L_w:=L_w) (L_t:=L_t) (A:=A) (Gamma:=Gamma) (G:=G).\napply ok_Bg_Hyb_ppermut with (G:=(w0, Gamma) :: G & (w, Gamma0)); auto.\nassert (G & (w, Gamma') ~=~ (G & (w, Gamma0))) as H2 by auto;\nrewrite H2; auto.\nintros; eapply H; eauto.\nauto.\nQed.\n\n\n(* Weakening lemmas *)\n\nLemma GlobalWeakening_Hyb:\nforall G G' Ctx Ctx' M A\n  (HT: G ++ G' |= Ctx |- M ::: A)\n  (H_ok: ok_Bg_Hyb (Ctx :: G & Ctx' ++ G')),\n  G & Ctx' ++ G' |= Ctx |- M ::: A.\nintros; rew_app;\napply BackgroundSubsetImpl_Hyb with (G:=G++G'); auto;\n[ exists (Ctx'::nil); rew_app; symmetry |\n  rew_app in *]; auto.\nQed.\n\n(*\nProof: induction on typing\n  * we need to be carefull when switching contexts - it's important to know\n  if the context we're switching to is the one we intend to extend\n  * if it is the case, it implies certain equivalences between pairs of\n  backgrounds, which then help to use the induction hypothesis\n  * otherwise we have to deconstruct background in order to extract the context\n  that we want to switch\n*)\nLemma Weakening_general_Hyb:\n  forall G w Gamma M A\n  (HT: G |= (w, Gamma) |- M ::: A),\n  (forall G' w' Delta Delta',\n    G ~=~ (G' & (w', Delta)) ->\n    ok_Bg_Hyb ((w, Gamma) :: G' & (w', Delta ++ Delta')) ->\n    G' & (w', Delta ++ Delta') |= (w, Gamma) |- M ::: A) /\\\n  (forall Gamma',\n    ok_Bg_Hyb ((w, Gamma ++ Gamma') :: G) ->\n    G |= (w, Gamma ++ Gamma') |- M ::: A).\nintros;\nremember (w, Gamma) as Ctx;\ngeneralize dependent Gamma;\ngeneralize dependent w;\ninduction HT; split;\nintros; subst; simpl;\ntry (inversion HeqCtx; subst).\n(* hyp *)\nconstructor; auto.\nconstructor; auto; rewrite Mem_app_or_eq; left; assumption.\n(* lam *)\napply t_lam_Hyb with\n  (L:=L \\u used_t_vars_Hyb ((w0, Gamma0) :: G' & (w', Delta ++ Delta')));\n[ | intros; eapply H]; auto.\napply t_lam_Hyb with (L:=L \\u used_t_vars_Hyb ((w0, Gamma0++Gamma')::G));\n[ | intros; eapply H with (v':=v')  (w:=w0) (Gamma:=(v' ,A)::Gamma0)]; auto;\nrew_app; auto.\n(* appl *)\neconstructor; [ | eapply IHHT1| eapply IHHT2]; eauto.\neconstructor; [ | eapply IHHT1| eapply IHHT2]; eauto.\n(* box *)\napply t_box_Hyb with\n  (L:=L \\u used_w_vars_Hyb (G' & (w0, Gamma0) & (w', Delta ++ Delta')));\nintros;\nassert (G' & (w', Delta ++ Delta') & (w0, Gamma0) ~=~\n        G' & (w0, Gamma0) & (w', Delta ++ Delta')) by (rew_app; auto);\n[ apply ok_Bg_Hyb_ppermut with (G:=(w0, Gamma0) :: G' & (w', Delta ++ Delta')) |\n  rewrite H3]; auto; try PPermut_Hyb_simpl;\napply H with (w:=w'0) (Gamma:=nil);\n[ | | rewrite H0 | rewrite H0 in Ok_Bg]; auto; try PPermut_Hyb_simpl.\napply ok_Bg_Hyb_fresh_wo; auto;\napply ok_Bg_Hyb_ppermut with\n  (G:=((w0, Gamma0) :: G' & (w', Delta ++ Delta')));\nauto.\napply t_box_Hyb with (L:=L \\u used_w_vars_Hyb (G & (w0, Gamma0++Gamma')));\n[ apply ok_Bg_Hyb_ppermut with (G:= (w0, Gamma0++Gamma') :: G) |\n  intros; eapply H]; auto; try PPermut_Hyb_simpl;\napply ok_Bg_Hyb_fresh_wo; auto;\napply ok_Bg_Hyb_ppermut with (G:=(w0, Gamma0++Gamma')::G); auto;\nPPermut_Hyb_simpl.\n(* unbox *)\nconstructor; [ | eapply IHHT]; eauto.\nconstructor; [ | eapply IHHT]; eauto.\n(* unbox_fetch 1 *)\ndestruct (permut_context_Hyb_dec (w'0, Delta) (w, Gamma)) as [Eq|Neq];\nsimpl in *.\n(* = *)\ndestruct Eq; subst;\nassert (G ~=~ G'0) by\n   (apply PPermut_Hyb_last_rev with (Gamma := Gamma) (Gamma':= Delta) (w:=w);\n    [ apply permut_sym |\n      transitivity G' ]; auto);\nassert ((w0, Gamma0) :: G'0 & (w, Delta ++ Delta') ~=~\n        (w, Gamma ++ Delta') :: G & (w0, Gamma0)) by\n  (rewrite H3;\n   transitivity ((w, Delta ++ Delta') :: G'0 & (w0, Gamma0));\n     [ transitivity ((w0, Gamma0) :: (w, Delta ++ Delta') :: G'0) | ]; auto;\n       transitivity ((w, Delta ++ Delta') :: (w0, Gamma0) :: G'0);\n       auto; PPermut_Hyb_simpl);\napply t_unbox_fetch_Hyb with (G:=G) (Gamma:=Gamma++Delta');\n[rewrite <- H4 | apply IHHT | rewrite H3]; auto; rewrite <- H4; auto.\n(* <> *)\nassert (exists Gamma', exists G0, exists G1,\n  Gamma' *=* Gamma /\\ G'0 = G0 & (w, Gamma') ++ G1) as H2 by\n  ( apply PPermut_Hyb_split_neq with (G':=G) (w:=w'0) (Gamma := Delta);\n    [ symmetry; transitivity G' | ]; auto);\ndestruct H2 as (Gamma', (GH, (GT, (H2a, H2b)))); subst;\napply t_unbox_fetch_Hyb with\n  (Gamma:=Gamma) (G:=GH ++ GT & (w'0, Delta ++ Delta')).\napply ok_Bg_Hyb_ppermut with\n  (G := (w0, Gamma0) :: (GH & (w, Gamma) ++ GT) & (w'0, Delta ++ Delta')); auto.\nrew_app; PPermut_Hyb_simpl.\nassert ((w0, Gamma0) :: (GH & (w, Gamma) ++ GT) & (w'0, Delta ++ Delta') ~=~\n       ((w0, Gamma0) :: (GH & (w, Gamma') ++ GT) & (w'0, Delta ++ Delta')))\n  by PPermut_Hyb_simpl.\nrewrite H2; auto.\napply PPermut_Hyb_bg with\n  (G:= (GH ++ GT & (w0, Gamma0)) & (w'0, Delta ++ Delta')).\n  apply IHHT with (w1:=w) (Gamma1:=Gamma) (G':=GH ++ GT & (w0, Gamma0));\n  assert (G ~=~ GH ++ GT & (w'0, Delta)) by\n  ( apply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma)); auto;\n    transitivity G'; [ | rewrite H0]; auto; PPermut_Hyb_simpl);\n  auto; try PPermut_Hyb_simpl.\n  apply ok_Bg_Hyb_ppermut with (G:= (w0, Gamma0) :: GH ++ (w, Gamma) :: GT &\n     (w'0, Delta ++ Delta')); auto; try PPermut_Hyb_simpl.\n  assert ((w0, Gamma0) :: GH ++ (w, Gamma) :: GT & (w'0, Delta ++ Delta') ~=~\n       ((w0, Gamma0) :: (GH & (w, Gamma') ++ GT) & (w'0, Delta ++ Delta')))\n  by PPermut_Hyb_simpl.\n  rewrite H3; auto.\n  transitivity (((w0, Gamma0) :: GH ++ GT) &\n    (w'0, Delta++Delta')); [rew_app | ]; auto; PPermut_Hyb_simpl.\n  transitivity (((w, Gamma) :: GH ++ GT ) &\n    (w'0, Delta ++ Delta')); [ | rew_app]; auto; PPermut_Hyb_simpl.\n(* unbox_fetch 2 *)\napply t_unbox_fetch_Hyb with (G:=G) (Gamma:=Gamma);\nrewrite <- H in H0; [ | apply IHHT with (w1:=w) (Gamma1:=Gamma) |]; auto.\n(* here *)\nconstructor; [ | apply IHHT with (w:=w0)(Gamma:=Gamma0)]; auto.\nconstructor; [ | apply IHHT]; auto.\n(* get_here 1 *)\ndestruct (permut_context_Hyb_dec (w'0, Delta) (w, Gamma)) as [Eq|Neq];\nsimpl in *.\n(* = *)\ndestruct Eq; subst;\nassert (G ~=~ G'0) by\n   (apply PPermut_Hyb_last_rev with (Gamma := Gamma) (Gamma':= Delta) (w:=w);\n    [ apply permut_sym |\n      transitivity G' ]; auto);\nassert ((w0, Gamma0) :: G'0 & (w, Delta ++ Delta') ~=~\n        (w, Gamma ++ Delta') :: G & (w0, Gamma0)) by\n  (rewrite H3;\n   transitivity ((w, Delta ++ Delta') :: G'0 & (w0, Gamma0));\n     [ transitivity ((w0, Gamma0) :: (w, Delta ++ Delta') :: G'0) | ]; auto;\n       transitivity ((w, Delta ++ Delta') :: (w0, Gamma0) :: G'0);\n       auto; PPermut_Hyb_simpl);\napply t_get_here_Hyb with (G:=G) (Gamma:=Gamma++Delta');\n[rewrite <- H4 | apply IHHT | rewrite H3]; auto; rewrite <- H4; auto.\n(* <> *)\nassert (exists Gamma', exists G0, exists G1,\n  Gamma' *=* Gamma /\\ G'0 = G0 & (w, Gamma') ++ G1) as H2 by\n  ( apply PPermut_Hyb_split_neq with (G':=G) (w:=w'0) (Gamma := Delta);\n    [ symmetry; transitivity G' | ]; auto);\ndestruct H2 as (Gamma', (GH, (GT, (H2a, H2b)))); subst;\napply t_get_here_Hyb with\n  (Gamma:=Gamma) (G:=GH ++ GT & (w'0, Delta ++ Delta')).\napply ok_Bg_Hyb_ppermut with\n  (G := (w0, Gamma0) :: (GH & (w, Gamma) ++ GT) & (w'0, Delta ++ Delta')); auto.\nrew_app; PPermut_Hyb_simpl.\nassert ((w0, Gamma0) :: (GH & (w, Gamma) ++ GT) & (w'0, Delta ++ Delta') ~=~\n       ((w0, Gamma0) :: (GH & (w, Gamma') ++ GT) & (w'0, Delta ++ Delta')))\n  by PPermut_Hyb_simpl.\nrewrite H2; auto.\napply PPermut_Hyb_bg with\n  (G:= (GH ++ GT & (w0, Gamma0)) & (w'0, Delta ++ Delta')).\n  apply IHHT with (w1:=w) (Gamma1:=Gamma) (G':=GH ++ GT & (w0, Gamma0));\n  assert (G ~=~ GH ++ GT & (w'0, Delta)) by\n  ( apply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma)); auto;\n    transitivity G'; [ | rewrite H0]; auto; PPermut_Hyb_simpl);\n  auto; try PPermut_Hyb_simpl.\n  apply ok_Bg_Hyb_ppermut with (G:= (w0, Gamma0) :: GH ++ (w, Gamma) :: GT &\n     (w'0, Delta ++ Delta')); auto; try PPermut_Hyb_simpl.\n  assert ((w0, Gamma0) :: GH ++ (w, Gamma) :: GT & (w'0, Delta ++ Delta') ~=~\n       ((w0, Gamma0) :: (GH & (w, Gamma') ++ GT) & (w'0, Delta ++ Delta')))\n  by PPermut_Hyb_simpl.\n  rewrite H3; auto.\n  transitivity (((w0, Gamma0) :: GH ++ GT) &\n    (w'0, Delta++Delta')); [rew_app | ]; auto; PPermut_Hyb_simpl.\n  transitivity (((w, Gamma) :: GH ++ GT ) &\n    (w'0, Delta ++ Delta')); [ | rew_app]; auto; PPermut_Hyb_simpl.\n(* get_here 2 *)\napply t_get_here_Hyb with (G:=G) (Gamma:=Gamma);\nrewrite <- H in H0; [ | apply IHHT with (w1:=w) (Gamma1:=Gamma) |]; auto.\n(* letdia *)\napply t_letdia_Hyb with (A:=A)\n  (L_w:=L_w \\u used_w_vars_Hyb((w0, Gamma0) :: G' & (w', Delta ++ Delta')))\n  (L_t:=L_t \\u used_t_vars_Hyb ((w0, Gamma0) :: G' & (w', Delta ++ Delta')));\n[ | apply IHHT with (w:=w0) (Gamma:=Gamma0) | ]; auto;\nintros; destruct H with (v':=v') (w':=w'0) (w:=w0) (Gamma:=Gamma0); auto;\nreplace ((w'0, (v', A) :: nil) :: G' & (w', Delta ++ Delta')) with\n   (((w'0, (v', A) :: nil) :: G') & (w', Delta ++ Delta')) by\n   (rew_app; reflexivity);\napply H4; rew_app; auto;\napply ok_Bg_Hyb_ppermut with\n  (G:=(w'0, (v', A) :: nil) :: (w0, Gamma0) :: G' & (w', Delta ++ Delta'));\nauto.\neapply t_letdia_Hyb with (A:=A)\n  (L_t := L_t \\u used_t_vars_Hyb ((w0, Gamma0 ++ Gamma') :: G))\n  (L_w := L_w \\u used_w_vars_Hyb ((w0, Gamma0 ++ Gamma') :: G));\n[ | apply IHHT | ]; auto;\nintros; eapply H; auto;\napply ok_Bg_Hyb_ppermut with\n  (G:=(w', (v', A) :: nil) :: (w0, Gamma0 ++ Gamma') :: G);\nauto.\n(* letdia_get 1 *)\ndestruct (permut_context_Hyb_dec (w', Delta) (w, Gamma)) as [Eq | Neq];\nsimpl in *.\n(* = *)\ndestruct Eq; subst;\nassert (G ~=~ G') by\n  (apply PPermut_Hyb_last_rev with (w:=w) (Gamma:=Gamma) (Gamma':=Delta);\n   [apply permut_sym | transitivity G0]; auto);\napply t_letdia_get_Hyb with (Gamma:=Gamma++Delta') (G:=G) (A:=A)\n  (L_w:=L_w \\u used_w_vars_Hyb ((w0, Gamma0) :: G' & (w, Gamma ++ Delta')))\n  (L_t:=L_t \\u used_t_vars_Hyb ((w0, Gamma0) :: G & (w, Gamma ++ Delta'))).\napply ok_Bg_Hyb_ppermut with (G:=(w0, Gamma0) :: G' & (w, Delta ++ Delta'));\n[rewrite <- H4 | auto];\ntransitivity ((w, Delta ++ Delta') :: G & (w0, Gamma0)); auto.\napply IHHT; auto;\napply ok_Bg_Hyb_ppermut with (G:=(w0, Gamma0) :: G' & (w, Delta ++ Delta'));\n[rewrite <- H4 | auto];\ntransitivity ((w, Delta ++ Delta') :: G & (w0, Gamma0)); auto.\nintros; destruct H with (v':=v') (w':=w') (w1:=w0) (Gamma1:=Gamma0); eauto;\nreplace ( (w', (v', A) :: nil) :: G & (w, Gamma ++ Delta') ) with\n  (( (w', (v', A) :: nil) :: G) & (w, Gamma ++ Delta')) by\n  (rew_app; reflexivity);\neapply H7; auto;\napply ok_Bg_Hyb_ppermut with\n  (G:=(w', (v', A) :: nil ) :: (w0, Gamma0) :: G & (w, Gamma ++ Delta'));\n[ rew_app | rewrite H4]; auto;\napply ok_Bg_Hyb_fresh_wo_te;\n[ apply ok_Bg_Hyb_ppermut\n  with (G:=(w0, Gamma0) :: G' & (w, Delta ++ Delta')) | | ];\nauto.\nrewrite notin_union in *; destruct H5; auto;\nrewrite <- H4; auto.\nrewrite <- H4; auto.\n(* <> *)\nassert (exists Gamma', exists G0, exists G1,\n  Gamma' *=* Gamma /\\ G' = G0 & (w, Gamma') ++ G1) by\n  ( apply PPermut_Hyb_split_neq with (G':=G) (w:=w') (Gamma := Delta);\n    [ symmetry; transitivity G0 | ]; auto).\ndestruct H3 as (Gamma', (GH, (GT, (H3a, H3b)))); subst;\nassert ((w0, Gamma0) :: (GH & (w, Gamma') ++ GT) & (w', Delta ++ Delta') ~=~\n  (w0, Gamma0) :: (GH & (w, Gamma) ++ GT) & (w', Delta ++ Delta'))\nby PPermut_Hyb_simpl;\nassert (G ~=~ GH ++ GT & (w', Delta)) by\n  ( apply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma));\n    transitivity G0; auto; rewrite H1; PPermut_Hyb_simpl);\napply t_letdia_get_Hyb with\n  (Gamma:=Gamma) (G:=GH ++ GT & (w', Delta ++ Delta'))\n  (L_w:=L_w \\u used_w_vars_Hyb ((w0, Gamma0) :: (GH & (w, Gamma) ++ GT) &\n    (w', Delta ++ Delta')))\n  (L_t:=L_t \\u used_t_vars_Hyb ((w0, Gamma0) :: (GH & (w, Gamma) ++ GT) &\n    (w', Delta ++ Delta')))(A:=A).\napply ok_Bg_Hyb_ppermut with\n  (G:=(w0, Gamma0) :: (GH & (w, Gamma') ++ GT) & (w', Delta ++ Delta'));\nrew_app in *; auto; try PPermut_Hyb_simpl.\napply PPermut_Hyb_bg with\n  (G:= (GH ++ GT & (w0, Gamma0)) & (w', Delta ++ Delta'));\n[ | rew_app]; auto;\napply IHHT with (w1:=w) (Gamma1:=Gamma); auto;\n[ rewrite H4 | ]; rew_app; auto;\nrew_app; apply ok_Bg_Hyb_ppermut with\n  (G:=(w0, Gamma0) :: (GH & (w, Gamma') ++ GT) & (w', Delta ++ Delta')); auto;\nrew_app; try PPermut_Hyb_simpl.\nintros; destruct H with (v':=v')(w':=w'0) (w1:=w0) (Gamma1:=Gamma0); auto;\napply PPermut_Hyb_bg with\n  (G:=((w'0, (v', A)::nil) :: GH++GT & (w, Gamma)) & (w', Delta ++ Delta'));\n[ | rew_app]; auto;\napply H7; rew_app; [constructor | ]; auto;\n[ rewrite H4; rew_app; auto | ];\napply ok_Bg_Hyb_ppermut with\n  (G:= ((w'0, (v', A) :: nil) ::(w0, Gamma0) :: GH & (w, Gamma') ++ GT) &\n    (w', Delta ++ Delta')); rew_app; auto;\n[ transitivity (((w'0, (v', A) :: nil) ::(w0, Gamma0) :: GH ++GT & (w, Gamma))\n  & (w', Delta ++ Delta')); rew_app |\n rew_app in *; apply ok_Bg_Hyb_fresh_wo_te]; auto; try PPermut_Hyb_simpl.\nrewrite H3; auto.\nrewrite H3; auto.\nrew_app; PPermut_Hyb_simpl.\n(* letdia_get 2 *)\napply t_letdia_get_Hyb with (G:=G) (Gamma:=Gamma) (A:=A)\n  (L_w:=L_w \\u used_w_vars_Hyb (((w0, Gamma0 ++ Gamma') :: G & (w, Gamma))))\n  (L_t:=L_t \\u used_t_vars_Hyb ((w0, Gamma0 ++ Gamma') :: G & (w, Gamma))).\nrewrite <- H0 in H1; apply ok_Bg_Hyb_ppermut with\n  (G:=(w0, Gamma0 ++ Gamma') :: G & (w, Gamma)); auto.\napply IHHT with (w1:=w) (Gamma1:=Gamma); auto.\nrewrite <- H0 in H1; apply ok_Bg_Hyb_ppermut with\n  (G:=(w0, Gamma0 ++ Gamma') :: G & (w, Gamma)); auto.\nintros; destruct H with (v':=v')(w':=w') (w1:=w0)(Gamma1:=Gamma0); auto;\napply H5; apply ok_Bg_Hyb_ppermut with\n  (G:= (w', (v', A)::nil) :: (w0, Gamma0 ++ Gamma') :: G & (w, Gamma));\n[ | apply ok_Bg_Hyb_fresh_wo_te ]; auto; rewrite H0; auto.\nassumption.\nQed.\n\nLemma WeakeningBackgroundElem_Hyb:\nforall G G' w Delta Delta' Ctx M A\n  (H_ok: ok_Bg_Hyb (Ctx :: G & (w, Delta ++ Delta') ++ G'))\n  (HT: G & (w, Delta) ++ G' |= Ctx |- M ::: A),\n  G & (w, Delta ++ Delta') ++ G' |= Ctx |- M ::: A.\nintros;\nassert ( G & (w, Delta ++ Delta') ++ G' ~=~ (G++G') & (w, Delta ++ Delta'))\n  by (rew_app; auto);\nrewrite H;\ndestruct Ctx; eapply Weakening_general_Hyb; auto.\nrew_app; assert (G ++ G' & (w, Delta) ~=~ G & (w, Delta) ++ G') by auto;\nrewrite H0; assumption.\napply ok_Bg_Hyb_ppermut with (G:=(v, l) :: G & (w, Delta ++ Delta') ++ G');\nauto.\nQed.\n\nLemma Weakening_Hyb:\nforall G w Gamma Gamma' M A\n  (H_ok: ok_Bg_Hyb ((w,Gamma++Gamma')::G))\n  (HT: G |= (w, Gamma) |- M ::: A),\n  G |= (w, Gamma ++ Gamma') |- M ::: A.\nintros;\neapply Weakening_general_Hyb; eassumption.\nQed.\n\n(*\n   When we can prove something in empty context and background, then we\n   can also do it in any \"full\" version of this context & background\n*)\nLemma types_weakened_Hyb:\nforall G G' w Gamma M A\n  (Ok: ok_Bg_Hyb ((w, Gamma)::G ++ G'))\n  (HT: emptyEquiv_Hyb G ++ G' |= (w, nil) |- M ::: A),\n  G ++ G'|= (w, Gamma) |- M ::: A.\ninduction G; intros; simpl in *; rew_app in *; auto.\napply Weakening_Hyb with (Gamma':=Gamma) in HT; rew_app in *; auto.\ndestruct a; rew_app in *.\nassert ((v,l) :: G ++ G' ~=~ G ++ (v,l)::G') by PPermut_Hyb_simpl;\nrewrite H; apply IHG.\nrewrite <- H; auto.\nassert (emptyEquiv_Hyb G ++ (v, l) :: G' ~=~\n  emptyEquiv_Hyb G & (v, nil ++ l) ++ G')\n  by PPermut_Hyb_simpl; rewrite H0; eapply WeakeningBackgroundElem_Hyb.\nrew_app.\napply ok_Bg_Hyb_empty_first in Ok.\nassert ((w, nil) :: (v, l) :: G ++ G' ~=~ ((w, nil) :: G) ++ (v, l) :: G') by\n  PPermut_Hyb_simpl; rewrite H1 in Ok;\neapply emptyEquiv_Hyb_ok_Bg_Hyb_part in Ok; simpl in *; rew_app in *; auto.\nassert (emptyEquiv_Hyb G & (v, nil) ++ G' ~=~\n  (v, nil) :: emptyEquiv_Hyb G ++ G') by\n  PPermut_Hyb_simpl; rewrite H1; auto.\nQed.\n\n\n(* Type preservation under various types of substitution *)\n\n\n(*\nProof: induction on typing\n  * for hypothesis case we simply use weakening\n  * for cases where we change worlds, we have to find the element, for\n  which the substitution is defined - in other words, the context, from\n  which the variable to substitute comes from; there are always two\n  options: either it is the marked element or we have to do a manual\n  split in order to find it\n*)\nLemma subst_t_Hyb_preserv_types:\nforall G w Gamma B M N v A\n  (H_lc_t: lc_t_Hyb M)\n  (H_lc_w: lc_w_Hyb M)\n  (HT: G |= (w, Gamma) |- N ::: B),\n  (* \"inner\" substitution *)\n  ( forall Gamma0,\n    permut Gamma ((v, A) :: Gamma0) ->\n    emptyEquiv_Hyb G |= (w, nil) |- M ::: A ->\n    G |= (w, Gamma0) |- [M // fte v] N ::: B)\n  /\\\n  (* \"outer\" substitution *)\n  ( forall G0 G' G'' w' Gamma',\n    G ~=~ (G0 & (w', (v,A)::Gamma')) ->\n    G' ~=~ (G0 & (w, Gamma)) ->\n    G'' ~=~ (G0 & (w', Gamma')) ->\n    emptyEquiv_Hyb G' |= (w', nil) |- M ::: A ->\n    G'' |= (w, Gamma) |- [M // fte v] N ::: B).\nintros;\nremember (w, Gamma) as Ctx;\ngeneralize dependent v;\ngeneralize dependent A;\ngeneralize dependent M;\ngeneralize dependent w;\ngeneralize dependent Gamma;\ninduction HT; split; intros;\ninversion HeqCtx; subst;\nsimpl in *.\n\n(* hyp *)\ncase_if.\ninversion H1; subst;\nassert (A = A0) by (eapply ok_Bg_Hyb_Mem_eq; eauto);\nsubst; replace G with (G ++ nil) by (rew_app; auto);\napply types_weakened_Hyb;\n[eapply ok_Bg_Hyb_permut_first_tail with (C:=Gamma0) | ]; rew_app; eauto.\nconstructor;\n[ apply ok_Bg_Hyb_permut_first_tail with (C:=Gamma0) (x:=v0) (A:=A0) |\n  apply Mem_permut with (l' := (v0, A0) :: Gamma1) in HT]; eauto.\nrewrite Mem_cons_eq in HT; destruct HT; auto;\ninversion H2; subst; elim H1; reflexivity.\n\ncase_if.\ninversion H3; subst;\neapply ok_Bg_Hyb_Mem_contradict in Ok_Bg;\ncontradiction || eauto.\nconstructor; auto;\napply ok_Bg_Hyb_ppermut with (G:=((w0, Gamma0)::G0) & (w', Gamma'));\n[ rewrite H1 |\n  eapply ok_Bg_Hyb_permut_no_last; rewrite H in Ok_Bg; rew_app]; eauto.\n\n(* lam *)\napply t_lam_Hyb with (L:=L \\u \\{v});\n[ apply ok_Bg_Hyb_permut_first_tail with (C:=Gamma0) (x:=v) (A:=A0) |\n  intros]; auto;\nrewrite notin_union in H2; rewrite notin_singleton in H2; destruct H2;\nunfold open_t_Hyb in *;\nrewrite <- subst_t_Hyb_comm; auto;\neapply H; auto;\npermut_simpl || rew_app; eauto.\n\napply t_lam_Hyb with (L:=L \\u \\{v});\n[ apply ok_Bg_Hyb_ppermut with (G:=((w0, Gamma0)::G0) & (w', Gamma'));\n  [ rewrite H2 |\n    rewrite H0 in Ok_Bg; rew_app] |\n  intros]; eauto with ok_bg_hyb_rew;\nrewrite notin_union in H4; rewrite notin_singleton in H4; destruct H4;\nunfold open_t_Hyb in *;\nrewrite <- subst_t_Hyb_comm; auto;\neapply H with (G0:=G0) (w':=w'); eauto;\nassert (emptyEquiv_Hyb G' ~=~\n  emptyEquiv_Hyb (G0 ++ nil & (w0, (v', A) :: Gamma0))) as E\n by (rewrite H1; rew_app; eapply emptyEquiv_Hyb_last_change; auto);\nrew_app in *; rewrite <- E; auto.\n\n(* appl *)\neconstructor;  [ | eapply IHHT1 | eapply IHHT2];\ntry apply ok_Bg_Hyb_permut_first_tail with (C:=Gamma0) (x:=v) (A:=A0); eauto.\n\neconstructor;\n[ apply ok_Bg_Hyb_ppermut with (G:=((w0, Gamma0)::G0) & (w', Gamma'));\n  [rewrite H1 | rewrite H in Ok_Bg] |\n  eapply IHHT1 |\n  eapply IHHT2]; eauto;\napply ok_Bg_Hyb_permut_no_last_spec in Ok_Bg; rew_app; auto.\n\n(* box *)\napply t_box_Hyb with (L:=L \\u used_w_vars_Hyb (emptyEquiv_Hyb G & (w0, nil)));\n[ apply ok_Bg_Hyb_permut_no_last with (v:=v) (A:=A0);\n  eapply ok_Bg_Hyb_permut_last |\n  intros; unfold open_w_Hyb]; eauto;\nrewrite <- subst_Hyb_order_irrelevant_bound;\n[ eapply H; eauto |\n  repeat rewrite emptyEquiv_Hyb_rewrite];\nsimpl; rew_app; auto;\napply BackgroundSubsetImpl_Hyb with (G:=emptyEquiv_Hyb G); auto;\n[ exists ((w', (@nil (prod var ty))) :: nil); rew_app; auto |\n  assert ((w0, nil) :: emptyEquiv_Hyb G & (w', nil) ~=~\n    (w', nil) :: emptyEquiv_Hyb G & (w0, nil)) by auto];\nrew_app; rewrite emptyEquiv_Hyb_rewrite_last; simpl; auto;\nrewrite H3;\napply ok_Bg_Hyb_fresh_wo; auto;\napply emptyEquiv_Hyb_ok_Bg_Hyb in Ok_Bg;\nrewrite emptyEquiv_Hyb_rewrite in Ok_Bg;\nsimpl in *; auto.\n\napply t_box_Hyb with\n  (L:=L \\u used_w_vars_Hyb(emptyEquiv_Hyb G0 ++ (w', nil) :: (w0, nil) :: nil));\n[ rewrite H2; rewrite H0 in Ok_Bg |\n  intros; unfold open_w_Hyb; rewrite <- subst_Hyb_order_irrelevant_bound];\neauto with ok_bg_hyb_rew;\neapply H with (G'' := G'' & (w0, Gamma0)) (G0:=G0 & (w0, Gamma0)) (w'0:=w')\n  (Gamma':=Gamma') (A0:=A0); auto;\nrepeat rewrite emptyEquiv_Hyb_rewrite;\nsimpl; rew_app; try PPermut_Hyb_simpl;\napply BackgroundSubsetImpl_Hyb with (G:=emptyEquiv_Hyb G0 & (w0, nil));\n[ rewrite H1 in H3; rewrite emptyEquiv_Hyb_rewrite in H3 |\n  exists ((w'0, (@nil (var * ty)))::nil); rew_app |\n  apply emptyEquiv_Hyb_ok_Bg_Hyb in Ok_Bg; rewrite H0 in Ok_Bg]; auto;\nrepeat rewrite emptyEquiv_Hyb_rewrite in Ok_Bg;\nsimpl in *; rew_app in *;\napply ok_Bg_Hyb_ppermut with\n  (G:=(w'0, nil) :: emptyEquiv_Hyb G0 ++ (w', nil) :: (w0, nil) :: nil);\n[eauto with ppermut_rew | apply ok_Bg_Hyb_fresh_wo ]; auto.\n\n(* unbox *)\neconstructor; [ | eapply IHHT];\ntry apply ok_Bg_Hyb_permut_first_tail with (C:=Gamma0) (x:=v) (A:=A0); eauto.\n\neconstructor;\n[ rewrite H1; rewrite H in Ok_Bg |\n  eapply IHHT]; eauto with ok_bg_hyb_rew.\n\n(* unbox_fetch *)\napply t_unbox_fetch_Hyb with (G:=G) (Gamma:=Gamma); auto;\n[ apply ok_Bg_Hyb_permut_no_last_spec with (v:=v) (A:=A0);\n  apply ok_Bg_Hyb_ppermut with (G:= (w, Gamma) :: G & (w0, Gamma0)) |\n  eapply IHHT; eauto; rewrite <- H in H1; rew_app]; auto.\n\ndestruct (eq_var_dec w w'0).\n(* = *)\nsubst;\nassert (G ~=~ G0 /\\ Gamma *=* (v, A0) :: Gamma'0) as HP by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w'0);\n   [eauto with ok_bg_hyb_rew | transitivity G'; auto]);\ndestruct HP;\napply t_unbox_fetch_Hyb with (G:=G) (Gamma:=Gamma'0);\neauto with ok_bg_hyb_rew;\nspecialize IHHT with (Gamma1:=Gamma) (w:=w'0);\ndestruct IHHT with (M0:=M0) (A0:=A0) (v:=v); auto;\n[ apply H6; auto; rewrite H1 in H3; rewrite H4 |\n  rewrite H4; symmetry]; auto.\n(* <> *)\nassert (exists Gamma', exists GH, exists GT,\n  Gamma' *=* (v, A0)::Gamma'0 /\\ G = GH & (w'0, Gamma') ++ GT) as HP by\n  (apply PPermut_Hyb_split_neq with (w:=w) (Gamma:=Gamma) (G':=G0);\n    auto; transitivity G'; auto).\ndestruct HP as (Gamma', (GH, (GT, (HPa, HPb)))).\nassert (GH & (w'0, Gamma') ++ GT ~=~ GH & (w'0, (v, A0)::Gamma'0) ++ GT)\n  by PPermut_Hyb_simpl;\napply t_unbox_fetch_Hyb with (G:=GH ++ GT & (w'0, Gamma'0)) (Gamma:=Gamma).\nsubst;\napply ok_Bg_Hyb_ppermut with\n  (G:= (((w, Gamma) :: (GH & (w0, Gamma0) ++ GT)) & (w'0, Gamma'0)));\n[rew_app | ]; auto;\napply ok_Bg_Hyb_permut_no_last_spec with (v:=v)(A:=A0).\napply ok_Bg_Hyb_ppermut with\n  (G:=(w, Gamma):: (GH & (w'0, Gamma') ++ GT) & (w0, Gamma0));\nrew_app in *; auto; PPermut_Hyb_simpl.\neapply IHHT with (w1:=w) (Gamma1:=Gamma) (w':=w'0) (Gamma':=Gamma'0)\n                 (G0:=GH ++ GT & (w0, Gamma0)); rew_app; auto; subst;\nrew_app; auto;\nrewrite H1 in H3;\nassert (GH ++ (w, Gamma) :: GT ~=~ G0) by\n  (apply PPermut_Hyb_last_rev_simpl with (a:=(w'0, (v, A0) :: Gamma'0));\n  rew_app in *; rewrite <- H0; rewrite <- H; auto; PPermut_Hyb_simpl).\nPPermut_Hyb_simpl; eauto.\nassert (GH ++ (w, Gamma) :: GT & (w0, Gamma0) ~=~ G0 & (w0,Gamma0)) by\n  (rewrite <- H5; rew_app; auto; PPermut_Hyb_simpl);\nrewrite H6; auto.\nsubst; rewrite H2; PPermut_Hyb_simpl.\napply PPermut_Hyb_last_rev with (w:=w'0) (Gamma:=Gamma')\n  (Gamma':=(v,A0)::Gamma'0);\n[ | symmetry]; auto; transitivity G'; auto; rewrite <- H; PPermut_Hyb_simpl.\n\n(* here *)\neconstructor; [ | eapply IHHT];\ntry apply ok_Bg_Hyb_permut_first_tail with (C:=Gamma0) (x:=v) (A:=A0); eauto.\n\neconstructor;\n[ rewrite H1; rewrite H in Ok_Bg |\n  eapply IHHT]; eauto with ok_bg_hyb_rew.\n\n(* get_here *)\napply t_get_here_Hyb with (G:=G) (Gamma:=Gamma); auto;\n[ apply ok_Bg_Hyb_permut_no_last_spec with (v:=v) (A:=A0);\n  apply ok_Bg_Hyb_ppermut with (G:= (w, Gamma) :: G & (w0, Gamma0)) |\n  eapply IHHT; eauto; rewrite <- H in H1; rew_app]; auto.\n\ndestruct (eq_var_dec w w'0).\n(* = *)\nsubst;\nassert (G ~=~ G0 /\\ Gamma *=* (v, A0) :: Gamma'0) as HP by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w'0);\n   [eauto with ok_bg_hyb_rew | transitivity G'; auto]);\ndestruct HP;\napply t_get_here_Hyb with (G:=G) (Gamma:=Gamma'0);\neauto with ok_bg_hyb_rew;\nspecialize IHHT with (Gamma1:=Gamma) (w:=w'0);\ndestruct IHHT with (M0:=M0) (A0:=A0) (v:=v); auto;\n[ apply H6; auto; rewrite H1 in H3; rewrite H4 |\n  rewrite H4; symmetry]; auto.\n(* <> *)\nassert (exists Gamma', exists GH, exists GT,\n  Gamma' *=* (v, A0)::Gamma'0 /\\ G = GH & (w'0, Gamma') ++ GT) as HP by\n  (apply PPermut_Hyb_split_neq with (w:=w) (Gamma:=Gamma) (G':=G0);\n    eauto; transitivity G'; auto).\ndestruct HP as (Gamma', (GH, (GT, (HPa, HPb)))).\nassert (GH & (w'0, Gamma') ++ GT ~=~ GH & (w'0, (v, A0)::Gamma'0) ++ GT)\n  by PPermut_Hyb_simpl;\napply t_get_here_Hyb with (G:=GH ++ GT & (w'0, Gamma'0)) (Gamma:=Gamma).\nsubst;\napply ok_Bg_Hyb_ppermut with\n  (G:= (((w, Gamma) :: (GH & (w0, Gamma0) ++ GT)) & (w'0, Gamma'0)));\n[rew_app | ]; auto;\napply ok_Bg_Hyb_permut_no_last_spec with (v:=v)(A:=A0).\napply ok_Bg_Hyb_ppermut with\n  (G:=(w, Gamma):: (GH & (w'0, Gamma') ++ GT) & (w0, Gamma0));\nrew_app in *; auto; PPermut_Hyb_simpl.\neapply IHHT with (w1:=w) (Gamma1:=Gamma) (w':=w'0) (Gamma':=Gamma'0)\n                 (G0:=GH ++ GT & (w0, Gamma0)) (A0:=A0); rew_app; auto; subst;\nrew_app; auto;\nrewrite H1 in H3;\nassert (GH ++ (w, Gamma) :: GT ~=~ G0) by\n  (apply PPermut_Hyb_last_rev_simpl with (a:=(w'0, (v, A0) :: Gamma'0));\n  rew_app in *; rewrite <- H0; rewrite <- H; auto; PPermut_Hyb_simpl).\nPPermut_Hyb_simpl; auto.\nassert (GH ++ (w, Gamma) :: GT & (w0, Gamma0) ~=~ G0 & (w0,Gamma0)) by\n  (rewrite <- H5; rew_app; auto; PPermut_Hyb_simpl);\nrewrite H6; auto.\nsubst; rewrite H2; PPermut_Hyb_simpl.\napply PPermut_Hyb_last_rev with (w:=w'0) (Gamma:=Gamma')\n  (Gamma':=(v,A0)::Gamma'0);\n[ | symmetry]; auto; transitivity G'; auto; rewrite <- H; PPermut_Hyb_simpl.\n\n(* letdia *)\napply t_letdia_Hyb with\n  (L_t := L_t \\u \\{v})\n  (L_w := L_w \\u used_w_vars_Hyb ((w0, nil) :: emptyEquiv_Hyb G)) (A:=A);\n[ apply ok_Bg_Hyb_permut_first_tail with (C:=Gamma0) (x:=v) (A:=A0) |\n  eapply IHHT |\n  intros]; eauto;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite notin_union in H2; rewrite notin_singleton in H2; destruct H2;\nrewrite <- subst_Hyb_order_irrelevant_bound;\n[ rewrite <- subst_t_Hyb_comm | assumption ];\n[ eapply H | |] ; eauto;\napply BackgroundSubsetImpl_Hyb with (G:=emptyEquiv_Hyb G); auto;\n[ exists ((w', (@nil (var*ty)))::nil);\n  PPermut_Hyb_simpl ; rew_app; PPermut_Hyb_simpl | ].\nassert ((w0, nil) :: (w', nil) :: emptyEquiv_Hyb G ~=~\n  (w',nil) :: (w0, nil) :: emptyEquiv_Hyb G) by PPermut_Hyb_simpl;\nrewrite H5; apply ok_Bg_Hyb_fresh_wo;\n[ apply emptyEquiv_Hyb_ok_Bg_Hyb in Ok_Bg;  simpl in * | ]; auto.\n\neapply t_letdia_Hyb with\n  (L_t := L_t \\u \\{v})\n  (L_w := L_w \\u  used_w_vars_Hyb ((w', nil) ::\n    emptyEquiv_Hyb (G0 & (w0, Gamma0))));\n[ rewrite H2; rewrite H0 in Ok_Bg | eapply IHHT | intros];\neauto with ok_bg_hyb_rew;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *.\nrewrite notin_union in H4; rewrite notin_singleton in H4; destruct H4;\nrewrite <- subst_Hyb_order_irrelevant_bound;\n[ rewrite <- subst_t_Hyb_comm | assumption ];\n[ eapply H with (G0:=(w'0, (v',A)::nil)::G0) (w'0:=w')\n  (Gamma':=Gamma') (A0:=A0) | | ]; auto;\nrew_app; rewrite H1 in H3; rew_app in *; simpl; try PPermut_Hyb_simpl;\napply BackgroundSubsetImpl_Hyb with (G:= emptyEquiv_Hyb (G0 & (w0, Gamma0)));\nauto; [exists ((w'0, (@nil (var*ty))):: nil); PPermut_Hyb_simpl | ];\nassert ((w'0, nil) :: (w', nil)::emptyEquiv_Hyb(G0 & (w0, Gamma0)) ~=~\n  (w', nil) :: (w'0, nil) :: emptyEquiv_Hyb (G0 & (w0, Gamma0))) by auto;\nrewrite <- H7; apply ok_Bg_Hyb_fresh_wo;\n[rewrite H0 in Ok_Bg; apply emptyEquiv_Hyb_ok_Bg_Hyb in Ok_Bg | ]; auto;\n  assert (emptyEquiv_Hyb((w', (v, A0) :: Gamma') :: G0 & (w0, Gamma0)) ~=~\n    (w', nil) :: emptyEquiv_Hyb (G0 & (w0, Gamma0))) by (simpl; auto);\nrewrite <- H8;\nassert ((w0, Gamma0) :: G0 & (w', (v, A0) :: Gamma') ~=~\n  ((w', (v, A0) :: Gamma') :: G0 & (w0, Gamma0))) by auto;\nrewrite <- H9; auto.\n\n(* letdia_get *)\nassert (w <> w0) by\n  (apply ok_Bg_Hyb_first_last_neq with (C:=Gamma) (C':=Gamma0) (G:=G); auto).\neapply t_letdia_get_Hyb with (G:=G) (Gamma:=Gamma) (L_t := L_t \\u \\{v}) (A:=A)\n  (L_w:=L_w \\u used_w_vars_Hyb ((w0, nil) :: emptyEquiv_Hyb (G & (w, Gamma))));\nauto.\napply ok_Bg_Hyb_permut_no_last_spec with (v:=v) (A:=A0);\napply ok_Bg_Hyb_ppermut with (G:= (w, Gamma) :: G & (w0, Gamma0)); auto.\neapply IHHT with (w':=w0) (Gamma':=Gamma1) (v:=v) (A0:=A0); auto.\nrew_app; rewrite <- H0 in H2; auto.\nintros; unfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite notin_union in H5; rewrite notin_singleton in H5; destruct H5;\nrewrite <- subst_Hyb_order_irrelevant_bound;\n[rewrite <- subst_t_Hyb_comm | ]; auto.\neapply H with (v:=v) (A0:=A0); auto.\nrewrite <- H0 in H2;\napply BackgroundSubsetImpl_Hyb with (G:=emptyEquiv_Hyb (G & (w, Gamma))); auto;\n[ exists ((w', (@ nil (var * ty)))::nil); PPermut_Hyb_simpl | ];\nassert ((w0, nil) :: (w', nil) :: emptyEquiv_Hyb (G & (w, Gamma)) ~=~\n  (w', nil) :: (w0, nil) ::emptyEquiv_Hyb (G & (w, Gamma)))\nby PPermut_Hyb_simpl;\nrewrite H8;\napply ok_Bg_Hyb_fresh_wo; [apply emptyEquiv_Hyb_ok_Bg_Hyb in Ok_Bg | auto];\nassert ((w, Gamma) :: G & (w0, Gamma0) ~=~ (w0, Gamma0):: G & (w, Gamma)) by\n  auto;\nrewrite H9 in Ok_Bg; simpl in Ok_Bg; auto.\n\nassert (w <> w0) by\n  (apply ok_Bg_Hyb_first_last_neq with (C:=Gamma) (C':=Gamma0) (G:=G); auto).\ndestruct (eq_var_dec w w'); subst.\n(* = *)\nassert (G ~=~ G1 /\\ Gamma *=* (v, A0) :: Gamma') by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w');\n    [ | rewrite H0; rewrite <- H1]; eauto);\ndestruct H7; rewrite H3; rewrite <- H7;\napply t_letdia_get_Hyb with (G:=G) (Gamma:=Gamma') (L_t:=L_t \\u \\{v}) (A:=A)\n  (L_w:=L_w \\u used_w_vars_Hyb ((w', nil) ::\n    emptyEquiv_Hyb (G1 & (w0, Gamma0)))).\neauto with ok_bg_hyb_rew.\neapply IHHT with (v:=v) (A0:=A0); auto;\nrewrite H2 in H4; rewrite H7; auto.\nintros; unfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite notin_union in H9; rewrite notin_singleton in H9; destruct H9;\nrewrite <- subst_Hyb_order_irrelevant_bound;\n[ rewrite <- subst_t_Hyb_comm | ]; auto.\nedestruct H with (v:=v) (w'0 := w'0) (Gamma1:=Gamma0) (A0:=A0)\n  (v':=v') (M:=M0) as (Ha, Hb);\nauto.\neapply Hb with (G0 := (w'0, (v',A)::nil) ::G) (w'1 := w') (Gamma':=Gamma');\n[ | auto |  | ]; try PPermut_Hyb_simpl.\nrewrite H2 in H4; rewrite H7.\napply BackgroundSubsetImpl_Hyb with (G:=emptyEquiv_Hyb (G1 & (w0, Gamma0)));\nauto. exists (((w'0, (@nil (prod var ty))) :: nil)); rew_app; simpl; auto;\nPPermut_Hyb_simpl.\nassert ((w', nil) :: (w'0, nil) :: emptyEquiv_Hyb (G1 & (w0, Gamma0)) ~=~\n  (w'0, nil) :: (w',nil) :: emptyEquiv_Hyb (G1 & (w0, Gamma0))) by auto;\nrewrite H12; apply ok_Bg_Hyb_fresh_wo; auto;\nassert ((w', nil) :: emptyEquiv_Hyb (G1 & (w0, Gamma0)) ~=~\n  emptyEquiv_Hyb ((w', Gamma) :: G & (w0, Gamma0))) by\n  (simpl in *; rewrite H7; auto);\nrewrite H13; apply emptyEquiv_Hyb_ok_Bg_Hyb in Ok_Bg; auto.\nauto.\n(* <> *)\nassert (G & (w, Gamma) ~=~ G1 & (w', (v, A0) :: Gamma')) by\n  (transitivity G0; auto);\nsymmetry in H7;\nassert (exists Gamma0, exists GH, exists GT,\n  Gamma0 *=* Gamma /\\ G1 = GH & (w, Gamma0) ++ GT) by\n  (apply PPermut_Hyb_split_neq with (w:=w') (Gamma:=(v,A0) :: Gamma') (G':=G);\n    auto);\ndestruct H8 as (Gamma'', (GH, H8)); destruct H8 as (GT, H8);\ndestruct H8.\napply t_letdia_get_Hyb with (G:=GH++GT & (w', Gamma')) (Gamma:=Gamma) (A:=A)\n  (L_t:=L_t \\u \\{v}) (L_w:=L_w \\u used_w_vars_Hyb\n     ((w', nil) :: emptyEquiv_Hyb\n       (GH ++ GT ++ (w, Gamma) :: (w0, Gamma0) :: nil))).\nassert (G & (w, Gamma) & (w0, Gamma0) ~=~ (w, Gamma) :: G & (w0, Gamma0)) by\n  auto.\nrewrite <- H10 in Ok_Bg; rewrite <- H7 in Ok_Bg;\nsubst; apply ok_Bg_Hyb_ppermut with\n  (G:=((w, Gamma) :: (GH & (w', Gamma') ++ GT) & (w0, Gamma0))); [ | rew_app];\nauto.\napply ok_Bg_Hyb_ppermut with\n  (G:= (((w, Gamma) :: (GH & (w0, Gamma0) ++ GT)) & (w', Gamma')));\n[rew_app; PPermut_Hyb_simpl | apply ok_Bg_Hyb_permut_no_last_spec\n  with (v:=v)(A:=A0)];\napply ok_Bg_Hyb_ppermut with\n  ((GH & (w, Gamma'') ++ GT) & (w', (v, A0) :: Gamma') & (w0, Gamma0));\n[ rew_app | ]; auto; try PPermut_Hyb_simpl.\neapply IHHT with (w1:=w) (Gamma1:=Gamma) (A0:=A0) (w':=w')\n  (G0:=GH++GT & (w0,Gamma0)) (Gamma':=Gamma'); auto;\n[ symmetry; subst; rew_app in * | rew_app | ]; auto.\nPPermut_Hyb_simpl; apply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma));\nrewrite <- H7; PPermut_Hyb_simpl.\nrewrite H2 in H4; rewrite H9 in H4;\nassert ((GH & (w, Gamma'') ++ GT) & (w0, Gamma0) ~=~\n  (GH ++ GT & (w0, Gamma0)) ++ nil & (w, Gamma))\n  by (rew_app; PPermut_Hyb_simpl);\nrewrite <- H10; auto.\nintros; unfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite notin_union in H10; rewrite notin_singleton in H10; destruct H10;\nrewrite <- subst_Hyb_order_irrelevant_bound;\n[rewrite <- subst_t_Hyb_comm | ]; auto;\neapply H with (v':=v') (w':=w'0) (Gamma1:=Gamma0) (w1:=w0) (A0:=A0)\n              (v:=v) (G0:=(w'0, (v', A) :: nil) :: (GH ++ GT) & (w, Gamma))\n              (w'0:=w') (Gamma':=Gamma'); auto; try PPermut_Hyb_simpl.\napply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma)); rewrite <- H7;\nsubst; PPermut_Hyb_simpl.\nrew_app; rewrite H2 in H4; rewrite H9 in H4; simpl;\napply BackgroundSubsetImpl_Hyb with\n  (G:=emptyEquiv_Hyb (GH ++ GT ++ (w, Gamma) :: (w0, Gamma0) :: nil)); auto.\nassert (GH ++ GT ++ (w, Gamma) :: (w0, Gamma0) :: nil ~=~\n  (GH & (w, Gamma'') ++ GT) & (w0, Gamma0)) by (rew_app; PPermut_Hyb_simpl);\nrewrite H13; auto.\nexists ((w'0, (@nil (var*ty))) :: nil); PPermut_Hyb_simpl.\nassert ((w, Gamma) :: G & (w0, Gamma0) ~=~ G0 & (w0, Gamma0)) by\n  (rewrite <- H0; auto).\nrewrite H13 in Ok_Bg; rewrite H1 in Ok_Bg; subst;\nassert ((w', nil)\n      :: (w'0, nil)\n         :: emptyEquiv_Hyb (GH ++ GT ++ (w, Gamma) :: (w0, Gamma0) :: nil) ~=~\n      (w'0, nil)\n      :: (w', nil)\n         :: emptyEquiv_Hyb (GH ++ GT ++ (w, Gamma) :: (w0, Gamma0) :: nil))\nby auto.\nrewrite H9; apply ok_Bg_Hyb_fresh_wo;\nassert (((GH & (w, Gamma'') ++ GT) & (w', (v, A0) :: Gamma')) & (w0, Gamma0) ~=~\n  ((w', (v, A0) :: Gamma') :: GH ++ GT ++ (w, Gamma) :: nil) &  (w0, Gamma0))\n  by PPermut_Hyb_simpl;\nrew_app in *; [rewrite H14 in Ok_Bg | auto];\napply emptyEquiv_Hyb_ok_Bg_Hyb in Ok_Bg; simpl in *; auto.\nsymmetry; transitivity (G1 & (w', Gamma')); subst; rew_app in *;\nPPermut_Hyb_simpl.\nQed.\n\nLemma subst_t_Hyb_preserv_types_inner:\nforall G w Gamma A B M N v\n  (H_lc_t: lc_t_Hyb M)\n  (H_lc_w: lc_w_Hyb M)\n  (HT: G |= (w, (v, A) :: Gamma) |- N ::: B)\n  (HM: emptyEquiv_Hyb G |= (w, nil) |- M ::: A),\n  G |= (w, Gamma) |- [M//fte v] N ::: B.\nintros; eapply subst_t_Hyb_preserv_types with (Gamma := (v, A) :: Gamma); eauto.\nQed.\n\nLemma subst_t_Hyb_preserv_types_outer:\nforall G0 G G' G'' w w' Gamma Gamma' A B M N v\n  (H_lc_t: lc_t_Hyb M)\n  (H_lc_w: lc_w_Hyb M)\n  (G0G: G ~=~ (G0 & (w', (v, A) :: Gamma')))\n  (G0G': G' ~=~ (G0 & (w, Gamma)))\n  (G0G'': G'' ~=~ (G0 & (w', Gamma')))\n  (HM: emptyEquiv_Hyb G' |= (w', nil) |- M ::: A)\n  (HT: G |= (w, Gamma) |- N ::: B),\n  G'' |= (w, Gamma) |- [M // fte v] N ::: B.\nintros; eapply subst_t_Hyb_preserv_types; eauto.\nQed.\n\n(*\nProof: induction on typing\n  * for terms with world change: we again have to check whether the\n  world which we will switch into is one of those in renaming\n*)\nLemma rename_w_Hyb_preserv_types:\nforall G w Gamma A M G' w' Gamma'\n  (HT: G |= (w, Gamma) |- M ::: A),\n  (* \"new\" substitution *)\n  ( G ~=~ (G' & (w', Gamma')) ->\n    G' |= (w, Gamma ++ Gamma') |- {{ fwo w // fwo w' }} M ::: A) /\\\n  (* \"old\" substitution *)\n  ( G ~=~ (G' & (w', Gamma')) ->\n    G' |= (w', Gamma' ++ Gamma) |- {{ fwo w' // fwo w }} M ::: A) /\\\n  (* \"outer\" substitution *)\n  (forall G0 w'' Gamma'',\n    G ~=~ (G0 & (w', Gamma') & (w'', Gamma'')) ->\n    G' ~=~ (G0 & (w', Gamma' ++ Gamma'')) ->\n    G' |= (w, Gamma) |- {{ fwo w' // fwo w''}} M ::: A).\nintros;\nremember (w, Gamma) as Ctx;\ngeneralize dependent Gamma;\ngeneralize dependent w;\ngeneralize dependent w';\ngeneralize dependent Gamma';\ngeneralize dependent G';\ninduction HT; repeat split; intros;\ninversion HeqCtx; subst;\nsimpl in *.\n\n(* hyp *)\nconstructor;\n[ rewrite H in Ok_Bg  |\n  rewrite Mem_app_or_eq; left ]; auto;\neapply ok_Bg_Hyb_split2; eauto.\nconstructor;\n[ rewrite H in Ok_Bg |\n  rewrite Mem_app_or_eq; right ]; auto;\neapply ok_Bg_Hyb_split2; eauto.\nconstructor;\n[ rewrite H in Ok_Bg; rewrite H0 | ]; auto;\neapply ok_Bg_Hyb_split3; eauto.\n\n(* lam *)\napply t_lam_Hyb with (L := L);\n[ rewrite H0 in Ok_Bg; apply ok_Bg_Hyb_split2 with (w:=w'); eauto |\n  intros; unfold open_t_Hyb in *];\nrewrite subst_Hyb_order_irrelevant_free; simpl; auto;\napply H with (v':=v') (G':=G') (Gamma := (v',A)::Gamma0); auto.\napply t_lam_Hyb with (L := L).\nrewrite H0 in Ok_Bg; apply ok_Bg_Hyb_split2 with (w:=w0); eauto.\nintros; unfold open_t_Hyb in *;\nrewrite subst_Hyb_order_irrelevant_free;\ndestruct H with (v':=v') (G':=G') (Gamma':=Gamma')\n(w':=w')(w:=w0) (Gamma:=(v',A)::Gamma0); eauto; destruct H3;\n[ apply ContextPermutImpl_Hyb with (Gamma := (Gamma' ++ (v', A) :: Gamma0));\n  [permut_simpl | ] | simpl; apply notin_empty ]; eauto.\n\napply t_lam_Hyb with (L := L);\n[ rewrite H0 in Ok_Bg |\n  intros];\nrewrite H1; try eapply ok_Bg_Hyb_split3; eauto;\nunfold open_t_Hyb in *;\nrewrite subst_Hyb_order_irrelevant_free;\ndestruct H with (v':=v') (G':=G0 & (w', Gamma'++Gamma'')) (Gamma':=Gamma')\n(w':=w')(w:=w0) (Gamma:=(v',A)::Gamma0); eauto. destruct H4.\napply H5 with (G1:=G0) (Gamma''0:=Gamma''); eauto.\nsimpl; apply notin_empty.\n\n(* appl *)\napply t_appl_Hyb with (A:=A);\n[ rewrite H in Ok_Bg |\n  apply IHHT1 with (Gamma:=Gamma0) |\n  apply IHHT2 with (Gamma:=Gamma0) ];\neauto; eapply ok_Bg_Hyb_split2; eauto.\napply t_appl_Hyb with (A:=A);\n[ rewrite H in Ok_Bg |\n  apply IHHT1 with (Gamma:=Gamma0) |\n  apply IHHT2 with (Gamma:=Gamma0) ];\neauto; eapply ok_Bg_Hyb_split2; eauto.\napply t_appl_Hyb with (A:=A);\n[ rewrite H in Ok_Bg; rewrite H0 |\n  eapply IHHT1 |\n  eapply IHHT2 ]; eauto;\neapply ok_Bg_Hyb_split3; eauto.\n\n(* box *)\napply t_box_Hyb with (L:=\\{w'} \\u L);\n[ rewrite H0 in Ok_Bg; apply ok_Bg_Hyb_split4 with (w:=w'); eauto |\n  intros];\nunfold open_w_Hyb in *; rewrite notin_union in H1; destruct H1;\nrewrite notin_singleton in *; rewrite <- subst_w_Hyb_comm; auto.\ndestruct H with (w':=w'0) (G':=G' & (w0, Gamma0++Gamma')) (Gamma':=Gamma0)\n                          (w'0:=w0) (w:=w'0)\n                          (Gamma:=(@nil (var * ty))); auto.\ndestruct H4. eapply H5; eauto; PPermut_Hyb_simpl.\napply t_box_Hyb with (L:=\\{w0} \\u L);\n[ rewrite H0 in Ok_Bg; apply ok_Bg_Hyb_split4 with (w:=w0);\n  apply ok_Bg_Hyb_ppermut with (G:=G' & (w', Gamma') & (w0, Gamma0)); auto |\n  intros]; try PPermut_Hyb_simpl;\nunfold open_w_Hyb in *; rewrite notin_union in H1; destruct H1;\nrewrite notin_singleton in *; rewrite <- subst_w_Hyb_comm; auto;\neapply H; eauto.\napply t_box_Hyb with (L:=\\{w''} \\u L);\n[ rewrite H0 in Ok_Bg; rewrite H1; eapply ok_Bg_Hyb_split6; eauto |\n  intros];\nunfold open_w_Hyb in *;\nrewrite notin_union in H2; destruct H2;\nrewrite notin_singleton in *;\nrewrite <- subst_w_Hyb_comm; auto;\neapply H with (G0:=G0 & (w0, Gamma0)) (Gamma':=Gamma') (Gamma'':=Gamma''); auto;\ntry PPermut_Hyb_simpl; rewrite H0; PPermut_Hyb_simpl.\n\n(* unbox *)\ncase_if.\ninversion H0; subst; rewrite H in Ok_Bg;\napply ok_Bg_Hyb_first_last_neq in Ok_Bg; elim Ok_Bg; auto.\nconstructor; [rewrite H in Ok_Bg | apply IHHT with (Gamma:=Gamma0)]; eauto;\neapply ok_Bg_Hyb_split2; eauto.\n\ncase_if; constructor;\n[ rewrite H in Ok_Bg |\n  apply IHHT with (Gamma:=Gamma0) ]; eauto;\neapply ok_Bg_Hyb_split2; eauto.\n\ncase_if.\ninversion H1; subst; rewrite H in Ok_Bg;\napply ok_Bg_Hyb_first_last_neq in Ok_Bg; elim Ok_Bg; auto.\nconstructor; [rewrite H0; rewrite H in Ok_Bg | eapply IHHT]; eauto;\neapply ok_Bg_Hyb_split3; eauto.\n\n(* unbox_fetch *)\ncase_if.\ninversion H1; subst;\nassert (G ~=~ G'0 /\\ Gamma *=* Gamma'0) as HP by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w'0);\n   [eauto | rewrite H; rewrite H0; auto]);\ndestruct HP; constructor.\nrewrite <- H2; apply ok_Bg_Hyb_split2 with (w:=w'0);\neapply ok_Bg_Hyb_permut; eauto.\napply ContextPermutImpl_Hyb with (Gamma:=Gamma0 ++ Gamma);\n[ permut_simpl |\n  apply IHHT] ; auto.\nassert (G'0 & (w'0, Gamma'0) ~=~ G & (w, Gamma)) by\n  (symmetry; transitivity G'; auto);\nassert (exists Gamma'', exists GH, exists GT,\n  Gamma'' *=* Gamma /\\ G'0 = GH & (w, Gamma'') ++ GT) as Split by\n  (eapply PPermut_Hyb_split_neq; eauto; right; intro; subst;\n    elim H1; reflexivity);\ndestruct Split as (Gamma'', (GH, Split)); destruct Split as (GT, H3);\ndestruct H3 as (H3a, H3b).\napply t_unbox_fetch_Hyb with (G:=GH++GT) (Gamma:=Gamma).\nassert ((w, Gamma) :: G & (w0, Gamma0) ~=~ G & (w, Gamma) & (w0, Gamma0)) by\n  auto.\nrewrite H3 in Ok_Bg; rewrite <- H2 in Ok_Bg; rew_app in *;\nassert (GH & (w, Gamma) ++ GT ~=~ (w, Gamma) :: GH ++ GT)\n  by (PPermut_Hyb_simpl);\napply ok_Bg_Hyb_ppermut with\n  (G:= (GH & (w, Gamma) ++ GT) & (w0, Gamma0 ++ Gamma'0));\n[ rewrite H4 |\n  apply ok_Bg_Hyb_split4 with (w:=w'0)]; rew_app; auto.\nsubst; rew_app in *;\napply ok_Bg_Hyb_ppermut with\n  (G:=(GH ++ (w, Gamma'') :: GT ++ (w'0, Gamma'0) :: (w0, Gamma0) :: nil));\ntry PPermut_Hyb_simpl; auto.\neapply IHHT with (w1:=w) (Gamma1:=Gamma); auto; subst; symmetry;\nPPermut_Hyb_simpl;\napply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma)); rew_app in *; auto;\nrew_app; auto; rewrite <- H2; PPermut_Hyb_simpl.\napply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma)); rew_app in *;\nauto; subst; PPermut_Hyb_simpl.\n\ncase_if;\n[ inversion H1; subst; apply ok_Bg_Hyb_first_last_neq in Ok_Bg;\n  elim Ok_Bg; auto | destruct (eq_var_dec w w'0)].\nsubst; assert (G ~=~ G'0 /\\ Gamma *=* Gamma'0) by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w'0); [ | rewrite <- H0]; eauto);\ndestruct H2; constructor.\nrewrite <- H2; apply ok_Bg_Hyb_permut with (Ctx := (Gamma ++ Gamma0)); eauto;\neapply ok_Bg_Hyb_split2; eauto.\napply ContextPermutImpl_Hyb with (Gamma:=Gamma ++ Gamma0);\n[ permut_simpl |\n  eapply IHHT with (w:=w'0) (Gamma1:=Gamma) (Gamma':=Gamma0)] ; auto.\nassert (G'0 & (w'0, Gamma'0) ~=~ G & (w, Gamma)) by\n  (symmetry; transitivity G'; auto);\nassert (exists Gamma'', exists GH, exists GT,\n  Gamma'' *=* Gamma /\\ G'0 = GH & (w, Gamma'') ++ GT) as Split by\n  (eapply PPermut_Hyb_split_neq; eauto; right; intro; subst;\n    elim H1; reflexivity);\ndestruct Split as (Gamma'', (GH, Split));\ndestruct Split as (GT, (Ha, Hb)); subst;\napply t_unbox_fetch_Hyb with (G:=GH++GT) (Gamma:=Gamma).\nassert (GH & (w, Gamma) ++ GT ~=~ (w, Gamma) :: GH ++ GT)\n  by PPermut_Hyb_simpl;\napply ok_Bg_Hyb_ppermut with\n  (G:= (GH & (w, Gamma'') ++ GT) & (w'0, Gamma0 ++ Gamma'0));\n[ PPermut_Hyb_simpl | apply ok_Bg_Hyb_split4 with (w:=w0)]; rew_app; auto.\nassert ((w, Gamma) :: G & (w0, Gamma0) ~=~\n  (G & (w, Gamma)) & (w0, Gamma0)) by auto;\nrewrite H4 in Ok_Bg; rewrite <- H2 in Ok_Bg; rew_app in *;\nremember (GH ++ (w, Gamma'') :: GT) as GHT;\nassert (GH ++ (w, Gamma'') :: GT ++ (w0, Gamma'0) :: (w'0, Gamma0) :: nil ~=~\n  GHT & (w0, Gamma'0) & (w'0, Gamma0)) by (subst; rew_app; auto).\nrewrite H5; apply ok_Bg_Hyb_swap_worlds; subst; rew_app in *; auto.\neapply IHHT; auto; PPermut_Hyb_simpl.\napply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma)); rew_app in *;\nrewrite H; rewrite H0; PPermut_Hyb_simpl.\ntransitivity (GH & (w, Gamma) ++ GT); PPermut_Hyb_simpl.\n\ncase_if.\ninversion H2; subst;\nassert (G ~=~ G0 & (w'0, Gamma'0) /\\ Gamma *=* Gamma'') by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w''); [ | rewrite H; rewrite H0];\n    eauto);\ndestruct H3; apply t_unbox_fetch_Hyb with (G:=G0) (Gamma := Gamma'0 ++ Gamma);\n[ rewrite H3 in Ok_Bg | apply IHHT | rewrite H1]; eauto.\napply ok_Bg_Hyb_split9 with (w':=w'');\napply ok_Bg_Hyb_ppermut with (G:= (w'', Gamma)::G0 & (w'0, Gamma'0) &\n  (w0, Gamma0));\neauto; PPermut_Hyb_simpl.\nrewrite H3; PPermut_Hyb_simpl.\ndestruct (eq_var_dec w w'0).\nsubst; assert (G ~=~ G0 & (w'', Gamma'') /\\ Gamma *=* Gamma'0) by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w'0); [ | rewrite H; rewrite H0];\n   eauto; PPermut_Hyb_simpl);\ndestruct H3;\napply t_unbox_fetch_Hyb with (G:=G0) (Gamma := Gamma ++ Gamma'');\n[ rewrite H3 in Ok_Bg |\n  eapply IHHT with (G':=G0 & (w0, Gamma0)) (Gamma' := Gamma'') |\n  rewrite H1]; eauto.\neapply ok_Bg_Hyb_split9; eauto.\nrewrite H3; PPermut_Hyb_simpl.\nassert (G0 & (w'0, Gamma'0) & (w'', Gamma'')  ~=~ G & (w, Gamma)) by\n  (symmetry; transitivity G'; auto);\nassert (exists Gamma'', exists GH, exists GT,\n  Gamma'' *=* Gamma /\\ G0 & (w'0, Gamma'0) = GH & (w, Gamma'') ++ GT)\n  as Split.\napply PPermut_Hyb_split_neq with (w:=w'')\n  (Gamma:=Gamma'') (G':= G); auto; right; intro; subst; elim H2; auto.\nassert (exists Gamma'', exists GH, exists GT,\n  Gamma'' *=* Gamma /\\ G0 = GH & (w, Gamma'') ++ GT) as Split' by\n  (destruct Split as (Gamma''', (GH, Split));\n    destruct Split as (GT, (Ha, Hb));\n   apply PPermut_Hyb_split_neq with (w:=w'0) (Gamma:=Gamma'0) (G':=GH ++ GT);\n   [ rew_app; transitivity (GH & (w, Gamma) ++ GT) |\n     right; intro; subst; elim n]; auto; rewrite Hb; auto);\ndestruct Split' as (Gamma''',(GH, Split'));\ndestruct Split' as (GT, (Ha, Hb));\napply t_unbox_fetch_Hyb with (G:=GH++GT & (w'0, Gamma'0++Gamma''))\n  (Gamma:=Gamma).\napply ok_Bg_Hyb_ppermut with (G':=(G' & (w0, Gamma0))) in Ok_Bg;\n[ | rewrite <- H; auto]; rewrite H0 in Ok_Bg; subst G0.\napply ok_Bg_Hyb_ppermut with\n  (G:= (GH & (w, Gamma''') ++ GT) & (w'0, Gamma'0 ++ Gamma'') & (w0, Gamma0));\n[ rew_app | ]; auto; try PPermut_Hyb_simpl; eapply ok_Bg_Hyb_split6; eauto.\neapply IHHT with (w1:=w) (Gamma1:=Gamma) (G0:=GH++GT & (w0,Gamma0))\n  (Gamma':=Gamma'0) (Gamma'':=Gamma''); auto.\nPPermut_Hyb_simpl. apply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma));\nrewrite <- H3; subst; PPermut_Hyb_simpl.\nPPermut_Hyb_simpl.\nrewrite H1; subst; PPermut_Hyb_simpl.\n\n(* here *)\ncase_if.\ninversion H0; subst; rewrite H in Ok_Bg;\napply ok_Bg_Hyb_first_last_neq in Ok_Bg; elim Ok_Bg; auto.\nconstructor;\n[ rewrite H in Ok_Bg | apply IHHT with (Gamma:=Gamma0)]; eauto;\neapply ok_Bg_Hyb_split2; eauto.\n\ncase_if; constructor;\n[ rewrite H in Ok_Bg |\n  apply IHHT with (Gamma:=Gamma0) ]; eauto;\neapply ok_Bg_Hyb_split2; eauto.\n\ncase_if.\ninversion H1; subst; rewrite H in Ok_Bg;\napply ok_Bg_Hyb_first_last_neq in Ok_Bg; elim Ok_Bg; auto.\nconstructor; [rewrite H0; rewrite H in Ok_Bg | eapply IHHT]; eauto;\neapply ok_Bg_Hyb_split3; eauto.\n\n(* get_here *)\ncase_if.\ninversion H1; subst;\nassert (G ~=~ G'0 /\\ Gamma *=* Gamma'0) as HP by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w'0);\n   [eauto | rewrite H; rewrite H0; auto]);\ndestruct HP; constructor.\nrewrite <- H2; apply ok_Bg_Hyb_split2 with (w:=w'0);\neapply ok_Bg_Hyb_permut; eauto.\napply ContextPermutImpl_Hyb with (Gamma:=Gamma0 ++ Gamma);\n[ permut_simpl |\n  apply IHHT] ; auto.\nassert (G'0 & (w'0, Gamma'0) ~=~ G & (w, Gamma)) by\n  (symmetry; transitivity G'; auto);\nassert (exists Gamma'', exists GH, exists GT,\n  Gamma'' *=* Gamma /\\ G'0 = GH & (w, Gamma'') ++ GT) as Split by\n  (eapply PPermut_Hyb_split_neq; eauto; right; intro; subst; elim H1;\n    reflexivity);\ndestruct Split as (Gamma'', (GH, Split)); destruct Split as (GT, H3);\ndestruct H3 as (H3a, H3b).\napply t_get_here_Hyb with (G:=GH++GT) (Gamma:=Gamma).\nassert ((w, Gamma) :: G & (w0, Gamma0) ~=~ G & (w, Gamma) & (w0, Gamma0)) by\n  auto.\nrewrite H3 in Ok_Bg; rewrite <- H2 in Ok_Bg; rew_app in *;\nassert (GH & (w, Gamma) ++ GT ~=~ (w, Gamma) :: GH ++ GT)\n  by (PPermut_Hyb_simpl);\napply ok_Bg_Hyb_ppermut with\n  (G:= (GH & (w, Gamma) ++ GT) & (w0, Gamma0 ++ Gamma'0));\n[ rewrite H4 |\n  apply ok_Bg_Hyb_split4 with (w:=w'0)]; rew_app; auto.\nsubst; rew_app in *;\napply ok_Bg_Hyb_ppermut with\n  (G:=(GH ++ (w, Gamma'') :: GT ++ (w'0, Gamma'0) :: (w0, Gamma0) :: nil));\ntry PPermut_Hyb_simpl; auto.\neapply IHHT with (w1:=w) (Gamma1:=Gamma); auto; subst; symmetry;\nPPermut_Hyb_simpl;\napply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma)); rew_app in *; auto;\nrew_app; auto; rewrite <- H2; PPermut_Hyb_simpl.\napply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma)); rew_app in *; auto;\nsubst; PPermut_Hyb_simpl.\n\ncase_if;\n[ inversion H1; subst; apply ok_Bg_Hyb_first_last_neq in Ok_Bg; elim Ok_Bg;\n  auto | destruct (eq_var_dec w w'0)].\nsubst; assert (G ~=~ G'0 /\\ Gamma *=* Gamma'0) by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w'0); [ | rewrite <- H0]; eauto);\ndestruct H2; constructor.\nrewrite <- H2; apply ok_Bg_Hyb_permut with (Ctx := (Gamma ++ Gamma0)); eauto;\neapply ok_Bg_Hyb_split2; eauto.\napply ContextPermutImpl_Hyb with (Gamma:=Gamma ++ Gamma0);\n[ permut_simpl |\n  eapply IHHT with (w:=w'0) (Gamma1:=Gamma) (Gamma':=Gamma0)] ; auto.\nassert (G'0 & (w'0, Gamma'0) ~=~ G & (w, Gamma)) by\n  (symmetry; transitivity G'; auto);\nassert (exists Gamma'', exists GH, exists GT,\n  Gamma'' *=* Gamma /\\ G'0 = GH & (w, Gamma'') ++ GT) as Split by\n  (eapply PPermut_Hyb_split_neq; eauto; right; intro; subst; elim H1;\n    reflexivity);\ndestruct Split as (Gamma'', (GH, Split));\ndestruct Split as (GT, (Ha, Hb)); subst;\napply t_get_here_Hyb with (G:=GH++GT) (Gamma:=Gamma).\nassert (GH & (w, Gamma) ++ GT ~=~ (w, Gamma) :: GH ++ GT)\n  by PPermut_Hyb_simpl;\napply ok_Bg_Hyb_ppermut with\n  (G:= (GH & (w, Gamma'') ++ GT) & (w'0, Gamma0 ++ Gamma'0));\n[ PPermut_Hyb_simpl | apply ok_Bg_Hyb_split4 with (w:=w0)]; rew_app; auto.\nassert ((w, Gamma) :: G & (w0, Gamma0) ~=~\n  (G & (w, Gamma)) & (w0, Gamma0)) by auto;\nrewrite H4 in Ok_Bg; rewrite <- H2 in Ok_Bg; rew_app in *;\nremember (GH ++ (w, Gamma'') :: GT) as GHT;\nassert (GH ++ (w, Gamma'') :: GT ++ (w0, Gamma'0) :: (w'0, Gamma0) :: nil ~=~\n  GHT & (w0, Gamma'0) & (w'0, Gamma0)) by (subst; rew_app; auto).\nrewrite H5; apply ok_Bg_Hyb_swap_worlds; subst; rew_app in *; auto.\neapply IHHT; auto; PPermut_Hyb_simpl.\napply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma)); rew_app in *;\nrewrite H; rewrite H0; PPermut_Hyb_simpl.\ntransitivity (GH & (w, Gamma) ++ GT); PPermut_Hyb_simpl.\n\ncase_if.\ninversion H2; subst;\nassert (G ~=~ G0 & (w'0, Gamma'0) /\\ Gamma *=* Gamma'') by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w''); [ | rewrite H; rewrite H0]; eauto);\ndestruct H3; apply t_get_here_Hyb with (G:=G0) (Gamma := Gamma'0 ++ Gamma);\n[ rewrite H3 in Ok_Bg | apply IHHT | rewrite H1]; eauto.\napply ok_Bg_Hyb_split9 with (w':=w'');\napply ok_Bg_Hyb_ppermut with (G:= (w'', Gamma)::G0 & (w'0, Gamma'0) &\n  (w0, Gamma0));\neauto; PPermut_Hyb_simpl.\nrewrite H3; PPermut_Hyb_simpl.\ndestruct (eq_var_dec w w'0).\nsubst; assert (G ~=~ G0 & (w'', Gamma'') /\\ Gamma *=* Gamma'0) by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w'0); [ | rewrite H; rewrite H0];\n   eauto; PPermut_Hyb_simpl);\ndestruct H3;\napply t_get_here_Hyb with (G:=G0) (Gamma := Gamma ++ Gamma'');\n[ rewrite H3 in Ok_Bg |\n  eapply IHHT with (G':=G0 & (w0, Gamma0)) (Gamma' := Gamma'') |\n  rewrite H1]; eauto.\neapply ok_Bg_Hyb_split9; eauto.\nrewrite H3; PPermut_Hyb_simpl.\nassert (G0 & (w'0, Gamma'0) & (w'', Gamma'')  ~=~ G & (w, Gamma)) by\n  (symmetry; transitivity G'; auto);\nassert (exists Gamma'', exists GH, exists GT,\n  Gamma'' *=* Gamma /\\ G0 & (w'0, Gamma'0) = GH & (w, Gamma'') ++ GT)\n  as Split.\napply PPermut_Hyb_split_neq with (w:=w'')\n  (Gamma:=Gamma'') (G':= G); auto; right; intro; subst; elim H2; auto.\nassert (exists Gamma'', exists GH, exists GT,\n  Gamma'' *=* Gamma /\\ G0 = GH & (w, Gamma'') ++ GT) as Split' by\n  (destruct Split as (Gamma''', (GH, Split));\n    destruct Split as (GT, (Ha, Hb));\n   apply PPermut_Hyb_split_neq with (w:=w'0) (Gamma:=Gamma'0) (G':=GH ++ GT);\n   [ rew_app; transitivity (GH & (w, Gamma) ++ GT) |\n     right; intro; subst; elim n]; auto; rewrite Hb; auto);\ndestruct Split' as (Gamma''',(GH, Split'));\ndestruct Split' as (GT, (Ha, Hb));\napply t_get_here_Hyb with (G:=GH++GT & (w'0, Gamma'0++Gamma''))\n  (Gamma:=Gamma).\napply ok_Bg_Hyb_ppermut with (G':=(G' & (w0, Gamma0))) in Ok_Bg;\n[ | rewrite <- H; auto]; rewrite H0 in Ok_Bg; subst G0.\napply ok_Bg_Hyb_ppermut with\n  (G:= (GH & (w, Gamma''') ++ GT) & (w'0, Gamma'0 ++ Gamma'') & (w0, Gamma0));\n[ rew_app | ]; auto; try PPermut_Hyb_simpl; eapply ok_Bg_Hyb_split6; eauto.\neapply IHHT with (w1:=w) (Gamma1:=Gamma) (G0:=GH++GT & (w0,Gamma0))\n  (Gamma':=Gamma'0) (Gamma'':=Gamma''); auto.\nPPermut_Hyb_simpl. apply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma));\nrewrite <- H3; subst; PPermut_Hyb_simpl.\nPPermut_Hyb_simpl.\nrewrite H1; subst; PPermut_Hyb_simpl.\n\n(* letdia *)\ncase_if.\ninversion H1; subst; rewrite H0 in Ok_Bg;\napply ok_Bg_Hyb_first_last_neq in Ok_Bg; elim Ok_Bg; auto.\napply t_letdia_Hyb with (L_w:=L_w \\u \\{w'}) (L_t:=L_t) (A:=A);\n[ rewrite H0 in Ok_Bg |\n  eapply IHHT with (w:=w0) (Gamma:=Gamma0) | ]; eauto.\neapply ok_Bg_Hyb_split2; eauto.\nintros; rewrite notin_union in H3; destruct H3;\nrewrite notin_singleton in H4;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite <- subst_w_Hyb_comm; auto;\nrewrite subst_Hyb_order_irrelevant_free;\n[ eapply H with (w:=w0) (Gamma:=Gamma0) (w':=w'0) | simpl]; eauto;\nrewrite H0; PPermut_Hyb_simpl.\n\ncase_if.\napply t_letdia_Hyb with (L_w:=L_w \\u \\{w0}) (L_t:=L_t) (A:=A);\n[ rewrite H0 in Ok_Bg | eapply IHHT with (w:=w0) (Gamma:=Gamma0) | ]; eauto.\neapply ok_Bg_Hyb_split2; eauto.\nintros; rewrite notin_union in H2; destruct H2;\nrewrite notin_singleton in H3;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite <- subst_w_Hyb_comm; auto;\nrewrite subst_Hyb_order_irrelevant_free;\n[ eapply H with (w:=w0) (Gamma:=Gamma0) (w':=w'0) | simpl]; eauto;\nrewrite H0; PPermut_Hyb_simpl.\n\ncase_if.\ninversion H2; subst; rewrite H0 in Ok_Bg;\napply ok_Bg_Hyb_first_last_neq in Ok_Bg; elim Ok_Bg; auto.\napply t_letdia_Hyb with (L_w:=L_w \\u \\{w''}) (L_t:=L_t) (A:=A);\n[ rewrite H0 in Ok_Bg; rewrite H1 |\n  eapply IHHT with (w:=w0) (Gamma:=Gamma0) | ]; eauto.\neapply ok_Bg_Hyb_split3; eauto.\nintros; rewrite notin_union in H4; destruct H4;\nrewrite notin_singleton in H5;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite <- subst_w_Hyb_comm; auto;\nrewrite subst_Hyb_order_irrelevant_free; simpl; auto;\neapply H with (w:=w0) (Gamma:=Gamma0) (G0:=G0 & ((w'0, (v', A)::nil)))\n  (Gamma':=Gamma') (Gamma'':=Gamma''); auto;\n[ rewrite H0 |rewrite H1 ]; rew_app; auto;\nPPermut_Hyb_simpl.\n\n(* letdia_get *)\ncase_if.\ninversion H3; subst;\nassert (G ~=~ G' /\\ Gamma *=* Gamma') by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w'); [ | transitivity G0]; eauto);\ndestruct H4;\neapply t_letdia_Hyb with (L_w := L_w \\u \\{w'}).\nrewrite <- H4; apply ok_Bg_Hyb_permut with (Ctx:=(Gamma0 ++ Gamma)); auto;\neapply ok_Bg_Hyb_split1; eauto.\napply ContextPermutImpl_Hyb with (Gamma := Gamma0++Gamma); [permut_simpl|];\nauto; eapply IHHT; auto.\nintros; rewrite notin_union in H7; destruct H7;\nrewrite notin_singleton in H8;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite <- subst_w_Hyb_comm; auto;\nrewrite subst_Hyb_order_irrelevant_free; simpl; auto;\neapply H with (v':=v') (w'0:=w'0) (w:=w0); auto;\n[ | rew_app]; eauto.\ndestruct (eq_var_dec w w0).\nsubst; apply ok_Bg_Hyb_first_last_neq in Ok_Bg; elim Ok_Bg; auto.\nassert (G' & (w', Gamma') ~=~ G & (w, Gamma)) by\n  (symmetry; transitivity G0; auto);\nassert (exists Gamma'', exists GH, exists GT,\n  Gamma'' *=* Gamma /\\ G' = GH & (w, Gamma'') ++ GT) by\n  (eapply PPermut_Hyb_split_neq; eauto; right; intro; subst; eauto);\ndestruct H5 as (Gamma'', (GH, (GT, (Ha, Hb))));\nassert (G & (w, Gamma) ~=~\n       (GH ++ GT ++ (w', Gamma') :: nil) &  (w, Gamma));\n[subst; symmetry | rew_app]; auto.\nrewrite <- H4; PPermut_Hyb_simpl.\napply t_letdia_get_Hyb with (L_w:=L_w \\u \\{w'}) (L_t:=L_t) (A:=A)\n  (G:=GH++GT) (Gamma:=Gamma);\nassert ((w, Gamma) :: G & (w0, Gamma0) ~=~\n  (GH ++ GT & (w', Gamma')) & (w, Gamma) & (w0, Gamma0)) by\n  (PPermut_Hyb_simpl; apply PPermut_Hyb_last_rev_simpl with (a:=(w,Gamma)); auto).\nrewrite H6 in Ok_Bg.\napply ok_Bg_Hyb_ppermut with (G:=(GH ++ GT & (w, Gamma)) &\n  (w0, Gamma0 ++ Gamma')).\nPPermut_Hyb_simpl.\nrew_app in *; eauto. eapply ok_Bg_Hyb_split8; eauto.\neapply IHHT with (w1:=w) (G0:=GH++GT) (w':=w0)\n  (Gamma':=Gamma0) (Gamma'':=Gamma');\nauto.\nPPermut_Hyb_simpl; apply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma));\nrewrite H5; PPermut_Hyb_simpl.\nintros; rewrite notin_union in H8; destruct H8;\nrewrite notin_singleton in H9;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite <- subst_w_Hyb_comm; auto;\nrewrite subst_Hyb_order_irrelevant_free; simpl; auto;\neapply H with (w1:=w0) (Gamma1:=Gamma0); auto.\nrewrite H5; PPermut_Hyb_simpl.\nsubst; PPermut_Hyb_simpl.\n\ncase_if.\ninversion H3; subst;\napply ok_Bg_Hyb_first_last_neq in Ok_Bg; elim Ok_Bg; auto.\ndestruct (eq_var_dec w w').\nsubst; assert (G ~=~ G' /\\ Gamma *=* Gamma').\n  apply ok_Bg_Hyb_impl_ppermut with (w:=w'); auto. eauto with ok_bg_hyb_rew.\n  transitivity G0; auto.\ndestruct H4;\napply t_letdia_Hyb with (L_w:=L_w \\u \\{w0}) (L_t:=L_t) (A:=A).\nrewrite <- H4; apply ok_Bg_Hyb_permut with (Ctx := Gamma ++ Gamma0); auto;\neapply ok_Bg_Hyb_split2; eauto.\napply ContextPermutImpl_Hyb with (Gamma:=Gamma++Gamma0); auto;\neapply IHHT with (Gamma1:=Gamma); eauto.\nintros; rewrite <- H4;\napply ContextPermutImpl_Hyb with (Gamma:=Gamma++Gamma0); auto;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite <- subst_w_Hyb_comm; auto;\nrewrite subst_Hyb_order_irrelevant_free; simpl; auto.\neapply H with (w'0 := w'0); eauto.\nassert (G' & (w', Gamma') ~=~ G & (w, Gamma)) by\n  (symmetry; transitivity G0; auto);\nassert (exists Gamma'', exists GH, exists GT,\n  Gamma'' *=* Gamma /\\ G' = GH & (w, Gamma'') ++ GT) by\n  (eapply PPermut_Hyb_split_neq; eauto).\ndestruct H5 as (Gamma'', (GH, (GT, (Ha, Hb)))).\napply t_letdia_get_Hyb with (L_w:=L_w \\u \\{w0})\n  (L_t:=L_t) (A:=A) (G:=GH++GT) (Gamma:=Gamma).\nsubst; assert ((w, Gamma) :: G & (w0, Gamma0) ~=~\n  (GH & (w, Gamma'') ++ GT) & (w', Gamma') & (w0, Gamma0)) by\n(rewrite H4; auto).\nrewrite H5 in Ok_Bg.\napply ok_Bg_Hyb_ppermut with (G:= GH & (w, Gamma'') ++ GT &\n  (w', Gamma' ++ Gamma0));\nrew_app in *; [ PPermut_Hyb_simpl | ];\napply ok_Bg_Hyb_ppermut with\n  (G:=(GH ++ (w, Gamma'') :: GT) & (w', Gamma' ++ Gamma0));\n[ | apply ok_Bg_Hyb_split4 with (w:=w0)]; rew_app; auto;\napply ok_Bg_Hyb_ppermut with (G:=GH ++ (w, Gamma'') :: GT ++ (w', Gamma') ::\n  (w0, Gamma0) :: nil); eauto.\neapply IHHT; auto.\nPPermut_Hyb_simpl; apply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma));\nrewrite <- H4; subst; PPermut_Hyb_simpl.\nintros. rewrite notin_union in H6; destruct H6;\nrewrite notin_singleton in H7; unfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite <- subst_w_Hyb_comm; auto;\nrewrite subst_Hyb_order_irrelevant_free; simpl; auto;\neapply H with (w1:=w0) (Gamma1:=Gamma0); auto; PPermut_Hyb_simpl.\napply PPermut_Hyb_last_rev_simpl with (a:=(w,Gamma));\nrewrite <- H4; subst; PPermut_Hyb_simpl.\nsubst; PPermut_Hyb_simpl.\n\ncase_if.\ninversion H4; subst;\nassert (G ~=~ G1 & (w', Gamma') /\\ Gamma *=* Gamma'') by\n (apply ok_Bg_Hyb_impl_ppermut with (w:=w'');\n  [ | transitivity G0]; eauto);\ndestruct H5;\neapply t_letdia_get_Hyb with (G:=G1) (Gamma:=Gamma'++Gamma)\n  (L_w:=L_w \\u \\{w''}).\nrewrite H5 in Ok_Bg; eauto.\nclear H HT2 IHHT.\neapply ok_Bg_Hyb_split2; eauto; apply ok_Bg_Hyb_ppermut with\n  (G:=(w'', Gamma) :: G1 & (w', Gamma') & (w0, Gamma0));\neauto; PPermut_Hyb_simpl.\neapply IHHT with (Gamma':=Gamma'); auto;\ntry PPermut_Hyb_simpl.\nintros; unfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite <- subst_w_Hyb_comm; auto;\nrewrite subst_Hyb_order_irrelevant_free; simpl; auto;\neapply H with (w:=w0) (G0:=(w'0, (v',A)::nil)::G1)\n  (Gamma':=Gamma') (Gamma'':=Gamma); auto;\n[ eauto | rew_app]; constructor; [ | symmetry]; auto;\nrewrite H5; rew_app; auto.\nrewrite H2; PPermut_Hyb_simpl.\ndestruct (eq_var_dec w w').\nsubst.\nassert (G ~=~ G1 & (w'', Gamma'') /\\ Gamma *=* Gamma').\n  apply ok_Bg_Hyb_impl_ppermut with (w:=w'); [ | transitivity G0]; eauto;\n  rewrite H1; PPermut_Hyb_simpl.\ndestruct H5;\neapply t_letdia_get_Hyb with (G:=G1) (Gamma:=Gamma++Gamma'')\n  (L_w:=L_w \\u \\{w''}) (L_t := L_t).\nclear H HT2 IHHT.\nrewrite H5 in Ok_Bg; eapply ok_Bg_Hyb_split9; eauto.\neapply IHHT with (w:=w'); auto; PPermut_Hyb_simpl.\nintros; unfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite <- subst_w_Hyb_comm; auto;\nrewrite subst_Hyb_order_irrelevant_free; simpl; auto;\neapply H with (w:=w0) (G0:=(w'0, (v',A)::nil)::G1)\n  (Gamma':=Gamma) (Gamma'':=Gamma''); auto;\nrew_app; constructor; auto;\nsymmetry; transitivity ((G1 ++ (w'', Gamma'')::nil) & (w', Gamma)); auto;\nrew_app; auto.\nrewrite H2; PPermut_Hyb_simpl.\nassert (G & (w, Gamma) ~=~ G1 & (w', Gamma') & (w'', Gamma'')) by\n  (symmetry; transitivity G0; symmetry; auto);\nassert (exists Gamma0, exists GH, exists GT,\n  Gamma0 *=* Gamma /\\ G1 & (w'', Gamma'') = GH & (w, Gamma0) ++ GT) by\n  (apply PPermut_Hyb_split_neq with (w:=w') (G':=G) (Gamma:=Gamma');\n   try symmetry; auto; transitivity (G1 & (w', Gamma') & (w'', Gamma'')); auto;\n  PPermut_Hyb_simpl).\nassert (exists Gamma0, exists GH, exists GT,\n  Gamma0 *=* Gamma /\\ G1 = GH & (w, Gamma0) ++ GT) by\n  (destruct H6 as (Gamma5, (GH, (GT, (H6a, H6b)))); subst;\n   apply PPermut_Hyb_split_neq with (w:=w'') (G':=GH++GT) (Gamma:=Gamma'');\n   auto; [rewrite H6b; rew_app; auto | right; intro; subst; elim H4;\n     reflexivity];\n  PPermut_Hyb_simpl).\ndestruct H7 as (Gamma'1, (GH, (GT, (H7a, H7b)))); subst.\napply t_letdia_get_Hyb with (L_w:=L_w \\u \\{w''})\n  (L_t:=L_t) (A:=A) (G:=GH++GT & (w', Gamma'++Gamma'')) (Gamma:=Gamma).\nassert ((w, Gamma) :: G & (w0, Gamma0) ~=~ G0  & (w0, Gamma0)) by\n  (rewrite <- H0; auto);\nrewrite H7 in Ok_Bg; rewrite H1 in Ok_Bg.\napply ok_Bg_Hyb_ppermut with (G:= (GH & (w, Gamma'1) ++ GT) &\n  (w', Gamma' ++ Gamma'') & (w0, Gamma0));\nrew_app in *; eauto; try PPermut_Hyb_simpl.\nclear IHHT H HT2. eapply ok_Bg_Hyb_split10; eauto.\neapply IHHT with (w1:=w) (G0:=GH++GT & (w0, Gamma0))\n  (Gamma':=Gamma') (Gamma'':=Gamma''); rew_app; auto;\nrew_app in *; transitivity ((GH ++ GT ++ (w', Gamma') ::\n  (w'', Gamma'') :: nil) & (w0, Gamma0));\n[ PPermut_Hyb_simpl | rew_app]; auto;\napply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma));\nrewrite H5; symmetry; transitivity (GH ++ GT ++ (w, Gamma) :: (w', Gamma') ::\n  (w'', Gamma'') :: nil); [rew_app |  apply PPermut_Hyb_app_head; symmetry];\nauto; try PPermut_Hyb_simpl.\nintros; unfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite <- subst_w_Hyb_comm; auto;\nrewrite subst_Hyb_order_irrelevant_free; simpl; auto;\neapply H with (G0:=(w'0, (v', A) :: nil) :: (GH ++ GT) & (w, Gamma))\n  (Gamma':=Gamma') (Gamma'':=Gamma''); auto; PPermut_Hyb_simpl.\napply PPermut_Hyb_last_rev_simpl with (a:=(w, Gamma)); rewrite H5;\nPPermut_Hyb_simpl.\nrewrite H2; PPermut_Hyb_simpl.\nQed.\n\nLemma rename_w_Hyb_preserv_types_new:\nforall G w Gamma A M G' w' Gamma'\n  (HT: G |= (w, Gamma) |- M ::: A)\n  (GG': PPermut_Hyb G (G' & (w', Gamma'))),\n  G' |= (w, Gamma ++ Gamma') |- {{ fwo w // fwo w' }} M ::: A.\nintros; apply rename_w_Hyb_preserv_types with (G := G) (w := w) (w':= w');\neauto.\nQed.\n\nLemma rename_w_Hyb_preserv_types_old:\nforall G w Gamma A M G' w' Gamma'\n  (HT: G |= (w, Gamma) |- M ::: A)\n  (GG': PPermut_Hyb G (G' & (w', Gamma'))),\n  G' |= (w', Gamma' ++ Gamma) |- {{ fwo w' // fwo w }} M ::: A.\nintros; apply rename_w_Hyb_preserv_types with (G := G) (w := w) (w':= w');\neauto.\nQed.\n\nLemma rename_w_Hyb_preserv_types_outer:\nforall G G0 w Gamma A M G' w' Gamma' w'' Gamma''\n  (HT: G |= (w, Gamma) |- M ::: A)\n  (GG: PPermut_Hyb G (G0 & (w', Gamma') & (w'', Gamma'')))\n  (GG': PPermut_Hyb G' (G0 & (w', Gamma' ++ Gamma''))),\n  G' |= (w, Gamma) |- {{ fwo w' // fwo w'' }} M ::: A.\nintros; eapply rename_w_Hyb_preserv_types; eauto.\nQed.\n\n(*\nProof sketch: double induction: on term and on typing\n  * for hypothesis, it is not possible to type it in empty context\n  * for cases where M is already a value, there is no problem\n  * otherwise we know, that for a simple term the theorem was true,\n  so we do case analysis to obtain the step\n  * the only exception is here M, where we know it is a value when\n  M was also a value\n*)\nLemma Progress_Hyb:\nforall G w M A\n  (H_lc_w: lc_w_Hyb M)\n  (H_lc_t: lc_t_Hyb M)\n  (HT: emptyEquiv_Hyb G |= (w, nil) |- M ::: A),\n  value_Hyb M \\/ exists N, (M, fwo w) |-> (N, fwo w).\nintros;\nremember (w, (@nil ty)) as Ctx;\ngeneralize dependent Ctx;\ngeneralize dependent A;\ngeneralize dependent w;\ngeneralize dependent G;\ninduction M; intros; eauto using value_Hyb;\ninversion HeqCtx; subst.\n(* hyp *)\ninversion HT; subst;\nrewrite Mem_nil_eq in HT0;\ncontradiction.\n(* appl *)\nright; inversion HT; subst;\ninversion H_lc_t; subst;\ninversion H_lc_w; subst;\nedestruct IHM1 with (A := A0 ---> A); eauto;\n[ inversion H0; subst; inversion HT1; subst; inversion H3 |\n  inversion H0];\neexists; constructor; eauto;\ninversion H5; subst; auto.\n(* unbox & unbox_fetch *)\nright; inversion HT; subst;\ninversion H_lc_w; subst;\ninversion H_lc_t; subst.\n(* unbox *)\nedestruct IHM with (A := [*]A); eauto;\n[ inversion H0; subst; inversion HT0; subst; inversion H3 |\n  destruct H0];\neexists; constructor; eauto;\ninversion H1; inversion H2; subst; auto;\nerewrite closed_var_subst_ctx; eauto; constructor.\n(* unbox_fetch *)\nassert (Gamma = nil) by\n  ( apply emptyEquiv_Hyb_permut_empty with\n    (G:= (G0 & (w0, Gamma))) (G':=G) (w:=w0); auto;\n    apply Mem_last); subst;\ndestruct IHM with (A := [*]A)\n                  (Ctx := (w0, (@nil ty)))\n                  (G := G0 & (w, nil))\n                  (w := w0);\neauto.\nassert (emptyEquiv_Hyb (G0 & (w, nil)) = G0 & (w, nil)) by\n  ( repeat rewrite emptyEquiv_Hyb_rewrite; simpl;\n   apply emptyEquiv_Hyb_permut_split_last in H6; rewrite H6; reflexivity);\nrewrite H0; auto.\ninversion H0; subst; inversion HT0; subst;\neexists; constructor; eauto; inversion H2; auto; subst.\ninversion H3; subst; auto.\ndestruct H0; eexists; constructor; eauto.\n(* here & get_here *)\ninversion HT; subst;\ninversion H_lc_w; subst;\ninversion H_lc_t; subst.\n(* here *)\nedestruct IHM; eauto;\n[ left; econstructor|\n  right; destruct H0; eexists];\neauto using step_Hyb.\n(* get_here *)\nassert (Gamma = nil) by\n  ( apply emptyEquiv_Hyb_permut_empty with\n    (G:= (G0 & (w0, Gamma))) (G':=G) (w:=w0); auto;\n    apply Mem_last); subst;\ndestruct IHM with (A := A0)\n                  (Ctx := (w0, (@nil ty)))\n                  (G := G0 & (w, nil))\n                  (w := w0);\neauto.\nassert (emptyEquiv_Hyb (G0 & (w, nil)) = G0 & (w, nil)) by\n  ( repeat rewrite emptyEquiv_Hyb_rewrite; simpl;\n   apply emptyEquiv_Hyb_permut_split_last in H6; rewrite H6; reflexivity);\nrewrite H0; auto.\nleft; inversion H0; subst; inversion HT0; subst;\neconstructor; eauto using step_Hyb.\nright; destruct H0; eexists;\neconstructor; eauto using step_Hyb.\n(* letdia & letdia_get *)\nright; inversion HT; subst;\ninversion H_lc_w; subst;\ninversion H_lc_t; subst.\n(* letdia *)\nedestruct IHM1 with (A := <*>A0); eauto;\n[ inversion H0; subst; inversion HT1; subst |\n  destruct H0];\neexists; constructor; eauto.\ninversion H5; subst; auto.\ninversion H7; subst; auto.\ninversion H5; subst; auto.\ninversion H7; subst; auto.\n(* letdia_get *)\nassert (Gamma = nil) by\n  ( apply emptyEquiv_Hyb_permut_empty\n    with (G:= (G0 & (w0, Gamma))) (G':=G) (w:=w0);\n    auto; apply Mem_last); subst;\nedestruct IHM1 with (G := G0 & (w, nil))\n                    (w := w0)\n                    (Ctx := (w0, (@nil ty)))\n                    (A := <*>A0); eauto.\nassert ( emptyEquiv_Hyb (G0 & (w, nil)) = G0 & (w, nil)) by\n   ( repeat rewrite emptyEquiv_Hyb_rewrite; simpl;\n     apply emptyEquiv_Hyb_permut_split_last in H6; rewrite H6; reflexivity).\nrewrite H0; auto.\ninversion H0; subst; inversion HT1; subst;\neexists; constructor; eauto;\ntry apply closed_t_succ; auto;\ninversion H5; inversion H8; subst; auto.\ndestruct H0;\neexists; constructor; eauto;\ntry apply closed_t_succ; auto;\ninversion H5; inversion H8; subst; auto.\nQed.\n\n(*\n   Proof sketch: double induction on typing and making a step\n   * for beta reduction we take a fresh variable and expand the\n   substitution a little bit, then apply the previously proven lemma\n   that substitution preserves types\n   * for unbox box reduction, the schema is basically the same\n   * for letdia here we combine the two above + use the knowledge\n   that term and world substitution can be done in any order\n*)\nLemma Preservation_Hyb:\nforall G M N A w\n  (HT: emptyEquiv_Hyb G |= (w, nil) |- M ::: A)\n  (HS: (M, fwo w) |-> (N, fwo w)),\n  emptyEquiv_Hyb G |= (w, nil) |- N ::: A.\nintros;\nremember (w, (@nil (var * ty))) as Ctx;\nremember (emptyEquiv_Hyb G) as G';\ngeneralize dependent w;\ngeneralize dependent N;\ngeneralize dependent G;\ninduction HT; intros;\ninversion HS; subst;\ntry (inversion HeqCtx; subst);\ntry (econstructor; eauto).\n(* appl_lam *)\ninversion HT1; subst;\nunfold open_t_Hyb in *;\nassert (exists v, v \\notin L \\u free_vars_Hyb M0) as HF by apply Fresh;\ndestruct HF as (v_fresh).\nrewrite subst_t_Hyb_neutral_free with (v:=v_fresh);\n[ eapply subst_t_Hyb_preserv_types_inner; eauto |\n  rewrite notin_union in H; destruct H]; auto.\nrewrite <- double_emptyEquiv_Hyb; auto.\n(* unbox_box *)\ninversion HT; subst;\nassert (exists v, v \\notin L \\u (free_worlds_Hyb M0)) as HF by apply Fresh;\ndestruct HF as (w_fresh);\nunfold open_w_Hyb in *;\nreplace ({{fwo w0 // bwo 0}}M0)\n  with ({{fwo w0 // fwo w_fresh}} {{fwo w_fresh // bwo 0}}M0)\n  by (rewrite subst_w_Hyb_neutral_free; auto);\nreplace (@nil (var * ty)) with (nil ++ (@nil (var * ty))); eauto;\napply rename_w_Hyb_preserv_types_old with (G := emptyEquiv_Hyb G0 & (w0, nil));\nauto.\n(* unbox_fetch_box *)\ninversion HT; subst;\nassert (exists v, v \\notin L \\u (free_worlds_Hyb M0)) as HF by apply Fresh;\ndestruct HF as (w_fresh);\nunfold open_w_Hyb in *;\nreplace ({{fwo w0 // bwo 0}}M0)\n  with ({{fwo w0 // fwo w_fresh}} {{fwo w_fresh // bwo 0}}M0)\n  by (rewrite subst_w_Hyb_neutral_free; auto);\nreplace (@nil (var * ty)) with (nil ++ (@nil (var * ty))); eauto;\napply rename_w_Hyb_preserv_types_old with (G := G & (w0, nil) & (w, Gamma));\nauto; PPermut_Hyb_simpl.\n(* unbox_fetch *)\nassert (Gamma = nil) by\n  ( apply emptyEquiv_Hyb_permut_empty with (G:= (G & (w, Gamma))) (G':=G0)\n    (w:=w);\n    auto; apply Mem_last); subst;\neapply IHHT with (G0:=G & (w0, nil)); eauto;\nrepeat rewrite emptyEquiv_Hyb_rewrite; simpl;\napply emptyEquiv_Hyb_permut_split_last in H; rewrite H; reflexivity.\n(* get_here *)\nassert (Gamma = nil) by\n  ( apply emptyEquiv_Hyb_permut_empty with (G:= (G & (w, Gamma))) (G':=G0)\n    (w:=w);\n    auto; apply Mem_last); subst;\neapply IHHT with (G0:=G & (w0, nil)); eauto;\nrepeat rewrite emptyEquiv_Hyb_rewrite; simpl;\napply emptyEquiv_Hyb_permut_split_last in H; rewrite H; reflexivity.\n(* letdia + (here | get_here ) *)\nassert (exists w1, w1 \\notin L_w \\u free_worlds_Hyb N) as HF by apply Fresh;\nassert (exists v1, v1 \\notin L_t \\u free_vars_Hyb N) as HF2 by apply Fresh;\ndestruct HF as (w_fresh); destruct HF2 as (v_fresh);\ninversion HT; subst.\n(* letdia #1 *)\nrewrite notin_union in *; destruct H0; destruct H1;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite subst_t_Hyb_neutral_free with (v:=v_fresh);\n[ rewrite subst_Hyb_order_irrelevant_bound |\n  apply subst_w_Hyb_preserv_free_vars]; auto;\n[ rewrite <- subst_w_Hyb_neutral_free with (w0:=w_fresh) |\n  constructor];\n[ apply subst_t_Hyb_preserv_types_inner with (A:=A) |\n  apply subst_t_Hyb_preserv_free_worlds]; auto;\n[ | rewrite <- double_emptyEquiv_Hyb; auto];\nreplace ((v_fresh, A) :: nil) with (nil ++ (v_fresh, A) :: nil) by auto;\napply rename_w_Hyb_preserv_types_new with\n  (G:= (w_fresh, (v_fresh, A)::nil) :: emptyEquiv_Hyb G0);\n[ rewrite <- subst_Hyb_order_irrelevant_bound |\n  rew_app]; auto; try PPermut_Hyb_simpl; constructor.\n(* letdia #2 *)\nrewrite notin_union in *; destruct H0; destruct H1;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite subst_t_Hyb_neutral_free with (v:=v_fresh);\n[ rewrite subst_Hyb_order_irrelevant_bound |\n  apply subst_w_Hyb_preserv_free_vars]; auto;\n[ rewrite <- subst_w_Hyb_neutral_free with (w0:=w_fresh) |\n  constructor];\n[ eapply subst_t_Hyb_preserv_types_outer with (A:=A) (G0:=G)\n  (Gamma':=Gamma) (w':=w) |\n  apply subst_t_Hyb_preserv_free_worlds]; auto;\nrew_app;\nassert ( emptyEquiv_Hyb (G & (w0, nil)) = G & (w0, nil)) by\n   ( repeat rewrite emptyEquiv_Hyb_rewrite; simpl;\n     apply emptyEquiv_Hyb_permut_split_last in H4; rewrite H4; reflexivity);\nassert (Gamma = nil) by\n  ( apply emptyEquiv_Hyb_permut_empty with (G:= (G & (w, Gamma)))\n    (G':=G0) (w:=w); auto; apply Mem_last).\nsubst; rew_app. rewrite <- H10 in HT0; auto.\napply rename_w_Hyb_preserv_types_outer with (G0:=G)\n  (Gamma'':=(v_fresh,A) :: nil)\n  (Gamma':=Gamma) (G:=G & (w, Gamma) & (w_fresh, (v_fresh,A)::nil));\nassert (G & (w, Gamma) & (w_fresh, (v_fresh, A) :: nil) ~=~\n  (w_fresh, (v_fresh, A) :: nil) :: emptyEquiv_Hyb G0) by PPermut_Hyb_simpl.\nrewrite H12; rewrite <- subst_Hyb_order_irrelevant_bound;\n[eapply HT2; auto | constructor].\nPPermut_Hyb_simpl; auto.\nPPermut_Hyb_simpl.\n(* letdia *)\nassert (exists w1, w1 \\notin L_w \\u free_worlds_Hyb N) as HF by apply Fresh;\nassert (exists v1, v1 \\notin L_t \\u free_vars_Hyb N) as HF2 by apply Fresh;\ndestruct HF as (w_fresh); destruct HF2 as (v_fresh);\ninversion HT; subst.\n(* letdia #1 *)\nrewrite notin_union in *; destruct H1; destruct H2;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *;\nrewrite subst_t_Hyb_neutral_free with (v:=v_fresh);\n[ rewrite subst_Hyb_order_irrelevant_bound |\n  apply subst_w_Hyb_preserv_free_vars]; auto;\n[ rewrite <- subst_w_Hyb_neutral_free with (w0:=w_fresh) |\n  constructor];\n[ eapply subst_t_Hyb_preserv_types_outer with (A:=A) (G0:=G) (w':=w)\n  (Gamma':=Gamma) |\n apply subst_t_Hyb_preserv_free_worlds]; eauto;\nassert (Gamma = nil) by\n  (apply emptyEquiv_Hyb_permut_empty with\n    (G:= (G & (w, Gamma))) (G':=G1) (w:=w); auto; apply Mem_last); subst;\nrew_app;\nassert ( emptyEquiv_Hyb (G & (w0, nil)) = G & (w0, nil)) by\n   ( repeat rewrite emptyEquiv_Hyb_rewrite; simpl;\n     apply emptyEquiv_Hyb_permut_split_last in H0; rewrite H0; reflexivity);\n[ rewrite <- H5 in HT0 |\n  eapply rename_w_Hyb_preserv_types_outer\n    with (G:= (w_fresh, (v_fresh,A)::nil):: G & (w,nil))\n         (Gamma'':=(v_fresh,A)::nil) (Gamma':=nil) (G0:=G)]; auto.\nrewrite <- subst_Hyb_order_irrelevant_bound;\n[ eapply HT2; eauto | constructor].\nPPermut_Hyb_simpl.\n(* letdia #2 *)\nassert (Gamma = nil) by\n  (apply emptyEquiv_Hyb_permut_empty with\n    (G:= (G & (w, Gamma))) (G':=G1) (w:=w); auto; apply Mem_last); subst.\nassert (w <> w0) by eauto with ok_bg_hyb_rew.\nassert (w1 <> w) by eauto with ok_bg_hyb_rew.\nrewrite <- H0; rewrite notin_union in *; destruct H1; destruct H2;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *; destruct (eq_var_dec w1 w0);\nsubst.\nassert (G0  ~=~ G /\\ Gamma0 *=* nil) by\n  (apply ok_Bg_Hyb_impl_ppermut with (w:=w0); eauto);\ndestruct H13; symmetry in H14; apply permut_nil_eq in H14;\nrewrite subst_t_Hyb_neutral_free with (v:=v_fresh);\n[ eapply subst_t_Hyb_preserv_types_inner with (A:=A) |\n  apply subst_w_Hyb_preserv_free_vars]; eauto;\n[ rewrite subst_Hyb_order_irrelevant_bound |\n  assert ( emptyEquiv_Hyb (G & (w, nil)) = G & (w, nil)) by\n    ( repeat rewrite emptyEquiv_Hyb_rewrite; simpl;\n      apply emptyEquiv_Hyb_permut_split_last in H0; rewrite H0; reflexivity)];\n[ rewrite <- subst_w_Hyb_neutral_free with (w0:=w_fresh) |\n  constructor | ]; auto;\n[ replace ((v_fresh,A)::nil) with (nil++(v_fresh,A)::nil) by auto |\n  apply subst_t_Hyb_preserv_free_worlds | ]; auto.\napply rename_w_Hyb_preserv_types_new with\n  (G:= (w_fresh, (v_fresh,A)::nil) :: G0 & (w, nil));\n[ rewrite <- subst_Hyb_order_irrelevant_bound; try constructor; subst |\n  rew_app; eauto].\nrewrite H13; eapply HT2; auto.\nPPermut_Hyb_simpl.\nrewrite H15; rewrite <- H13; subst; auto.\nassert (Gamma0 = nil) by\n  ( apply emptyEquiv_Hyb_permut_empty with (G:= (G0 & (w1, Gamma0)))\n      (G':=G & (w0, nil)) (w:=w1); auto;\n    assert (emptyEquiv_Hyb G = G) by\n      (apply emptyEquiv_Hyb_permut_split_last with (C:=(w, nil)) (H:=G1); auto);\n    [ rewrite emptyEquiv_Hyb_rewrite; simpl | apply Mem_last ];\nrewrite H13; auto); subst; assert (exists Gamma'', exists GH, exists GT,\n  Gamma'' *=* nil /\\ G = GH & (w1, Gamma'') ++ GT) by\n  ( apply PPermut_Hyb_split_neq with (w:=w0) (G':=G0) (Gamma:=nil);\n    [ symmetry | right; intro; subst; elim n]; auto);\ndestruct H13 as (Gamma'', (GH, (GT, (H12a, H12b))));\nsymmetry in H12a; apply permut_nil_eq in H12a; subst;\nrewrite subst_t_Hyb_neutral_free with (v:=v_fresh);\n[ apply subst_t_Hyb_preserv_types_outer with (A:=A) (G0 :=GH ++ GT & (w, nil))\n          (G := GH ++ GT & (w,nil) & (w1, (v_fresh, A) :: nil))\n       (G' := GH ++ GT & (w,nil) & (w0, nil)) (w' :=w1) (Gamma':=nil) |\n  apply subst_w_Hyb_preserv_free_vars]; auto; subst; rew_app; auto.\nassert (G0 & (w, nil) ~=~ GH ++ GT & (w,nil) & (w0, nil)) by\n  ( transitivity ((GH++GT & (w0,nil) &(w, nil))); auto;\n    assert (G0 & (w1, nil) ~=~  (GH ++ GT & (w0, nil) & (w1, nil))) by\n      (transitivity ((GH & (w1, nil) ++ GT) & (w0, nil)); rew_app in *; auto);\n    assert (G0 ~=~ GH ++ GT & (w0, nil)) by\n      (apply PPermut_Hyb_last_rev_simpl with (a:=(w1,nil)); rew_app in *; auto);\n  try PPermut_Hyb_simpl;\n  rewrite H14; rew_app; auto); rew_app in *; rewrite <- H13.\nassert (emptyEquiv_Hyb G0 = G0) by\n( assert (G0 ~=~ GH ++ GT & (w0, nil)) by\n    ( apply PPermut_Hyb_last_rev_simpl with (a:=(w, nil));\n      transitivity (GH ++ GT & (w, nil) & (w0, nil)); rew_app in *; auto);\n  apply emptyEquiv_Hyb_permut_split_last with (C:=(w1, nil)) (H := (w0, nil) ::\n    GH & (w1, nil) ++ GT);\n  assert (emptyEquiv_Hyb ((w0, nil) :: GH & (w1, nil) ++ GT) = ((w0, nil) ::\n    GH & (w1, nil) ++ GT)) by\n  ( apply emptyEquiv_Hyb_permut_split_last with (C:=(w, nil))\n    (H:= (w0,nil)::G1); simpl; rewrite <- H0; rew_app; symmetry; auto);\n  rewrite H14; rewrite H15; rew_app;\n  transitivity (GH ++ (w0, nil) :: (w1, nil)::GT); auto; PPermut_Hyb_simpl);\nrewrite emptyEquiv_Hyb_rewrite; simpl; rewrite H14; auto.\nrewrite subst_Hyb_order_irrelevant_bound;\n[ rewrite <- subst_w_Hyb_neutral_free with (w0:=w_fresh) | constructor];\n[ apply rename_w_Hyb_preserv_types_outer\n    with (G0 := GH ++ GT & (w,nil))\n         (G := (w_fresh, (v_fresh, A) :: nil) :: (GH & (w1, nil) ++ GT) &\n           (w, nil))\n         (Gamma':=nil)\n         (Gamma'':=(v_fresh, A)::nil) |\n  apply subst_t_Hyb_preserv_free_worlds]; auto.\nrewrite <- subst_Hyb_order_irrelevant_bound;\n[eapply HT2; eauto | constructor].\nPPermut_Hyb_simpl.\nPPermut_Hyb_simpl.\n(* letdia_step *)\ndestruct (eq_var_dec w0 w); subst.\neapply ok_Bg_Hyb_first_last_neq in Ok_Bg;\nelim Ok_Bg; auto.\nassert (Gamma = nil) by\n  ( apply emptyEquiv_Hyb_permut_empty with (G:= (G & (w, Gamma))) (G':=G1)\n    (w:=w); auto; apply Mem_last);\nsubst;\napply IHHT with (G0:=G & (w0,nil)) (w1:=w); auto;\nassert (emptyEquiv_Hyb G = G) by\n  (apply emptyEquiv_Hyb_permut_split_last with (C:=(w,nil)) (H:=G1); auto);\nrewrite emptyEquiv_Hyb_rewrite; simpl; rewrite H1; reflexivity.\nQed.\n\n(*\n   Lemmas needed for properties like termination or lang. equivalence.\n*)\n\nLemma types_Hyb_lc_w_Hyb:\nforall G Gamma M A w,\n  G |= (w, Gamma) |- M ::: A -> lc_w_Hyb M.\nintros; induction H; constructor; try apply IHHT;\nunfold open_w_Hyb in *; unfold open_t_Hyb in *;\nauto.\nassert (exists x, x \\notin L) by apply Fresh; destruct H0;\nspecialize H with x; apply H in H0; apply lc_w_n_Hyb_subst_t in H0; auto.\nassert (exists x, x \\notin L) by apply Fresh; destruct H0;\nspecialize H with x; apply H in H0; apply lc_w_n_Hyb_subst_w in H0; auto.\nassert (exists x, x \\notin L_t) by apply Fresh; destruct H1;\nassert (exists x, x \\notin L_w) by apply Fresh; destruct H2;\nspecialize H0 with x x0; apply H0 with (w':=x0) in H1; auto;\napply lc_w_n_Hyb_subst_t in H1; apply lc_w_n_Hyb_subst_w in H1; auto.\nassert (exists x, x \\notin L_t) by apply Fresh; destruct H2;\nassert (exists x, x \\notin L_w) by apply Fresh; destruct H3;\nspecialize H0 with x x0; apply H0 with (w':=x0) in H2; auto;\napply lc_w_n_Hyb_subst_t in H2; apply lc_w_n_Hyb_subst_w in H2; auto.\nQed.\n\nLemma types_Hyb_lc_t_Hyb:\nforall G Gamma M A w,\n  G |= (w, Gamma) |- M ::: A -> lc_t_Hyb M.\nintros; induction H; constructor; try apply IHHT;\nunfold open_w_Hyb in *; unfold open_t_Hyb in *;\nauto.\nassert (exists x, x \\notin L) by apply Fresh; destruct H0;\nspecialize H with x; apply H in H0;\napply lc_t_n_Hyb_subst_t in H0; auto; constructor.\nassert (exists x, x \\notin L) by apply Fresh; destruct H0;\nspecialize H with x; apply H in H0;\napply lc_t_n_Hyb_subst_w in H0; auto; constructor.\nassert (exists x, x \\notin L_t) by apply Fresh; destruct H1;\nassert (exists x, x \\notin L_w) by apply Fresh; destruct H2;\nspecialize H0 with x x0; apply H0 with (w':=x0) in H1; auto;\napply lc_t_n_Hyb_subst_t in H1; try constructor;\napply lc_t_n_Hyb_subst_w in H1; auto.\nassert (exists x, x \\notin L_t) by apply Fresh; destruct H2;\nassert (exists x, x \\notin L_w) by apply Fresh; destruct H3;\nspecialize H0 with x x0; apply H0 with (w':=x0) in H2; auto;\napply lc_t_n_Hyb_subst_t in H2; try constructor;\napply lc_t_n_Hyb_subst_w in H2; auto.\nQed.\n\nLemma lc_w_step_Hyb_preserv:\nforall M M' w,\n  lc_w_Hyb M ->\n  step_Hyb (M, fwo w) (M', fwo w) ->\n  lc_w_Hyb M'.\ninduction M; intros; inversion H0; subst; auto;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *; simpl in *.\napply lc_w_subst_t_Hyb; auto.\nconstructor; [eapply IHM1 |]; eauto.\ninversion H; subst; try omega; auto.\ndestruct v; [inversion H; subst; omega | constructor; eapply IHM; eauto].\ninversion H; subst; try omega; constructor; eauto.\napply IHM with w0; auto.\ninversion H; subst; try omega; inversion H11; subst; try omega;\napply lc_w_subst_t_Hyb; auto;\napply lc_w_n_L_subst_w; auto.\ninversion H; subst; try omega; constructor; auto.\napply IHM1 with w0; auto.\nQed.\n\nLemma lc_t_step_Hyb_preserv:\nforall M M' w,\n  lc_t_Hyb M ->\n  step_Hyb (M, w) (M', w) ->\n  lc_t_Hyb M'.\ninduction M; intros; inversion H0; subst; auto;\nunfold open_t_Hyb in *; unfold open_w_Hyb in *; simpl in *.\napply lc_t_subst_Hyb; auto.\nconstructor; [eapply IHM1 |]; eauto.\ninversion H; subst; try omega; auto.\ninversion H; subst; try omega; constructor; eapply IHM; eauto.\ninversion H; subst; try omega; constructor; eapply IHM; eauto.\ninversion H; subst; try omega; inversion H11; subst; try omega;\napply lc_t_subst_Hyb; auto;\napply lc_t_n_L_subst_w; auto.\ninversion H; subst; try omega; constructor; auto.\napply IHM1 with v; auto.\nQed.\n\nLemma lc_w_steps_Hyb_preserv:\nforall M M' w,\n  lc_w_Hyb M ->\n  steps_Hyb (M, fwo w) (M', fwo w) ->\n  lc_w_Hyb M'.\nintros; remember (M, fwo w) as M0; remember (M', fwo w) as M1;\ngeneralize dependent M; generalize dependent M'; generalize dependent w.\ninduction H0; intros; inversion HeqM0; inversion HeqM1; subst;\napply lc_w_step_Hyb_preserv in H; eauto.\nQed.\n\nLemma lc_t_steps_Hyb_preserv:\nforall M M' w,\n  lc_t_Hyb M ->\n  steps_Hyb (M, fwo w) (M', fwo w) ->\n  lc_t_Hyb M'.\nintros; remember (M, fwo w) as M0; remember (M', fwo w) as M1;\ngeneralize dependent M; generalize dependent M'; generalize dependent w.\ninduction H0; intros; inversion HeqM0; inversion HeqM1; subst;\napply lc_t_step_Hyb_preserv in H; eauto.\nQed.\n\nLemma steps_Hyb_unbox:\nforall M w' w M',\n lc_w_Hyb M -> lc_t_Hyb M ->\n steps_Hyb (M, fwo w') (M', fwo w') ->\n steps_Hyb\n   (unbox_fetch_Hyb (fwo w') M, w)\n   (unbox_fetch_Hyb (fwo w') M', w).\nintros; remember (M, fwo w') as M0; remember (M', fwo w') as M1;\ngeneralize dependent M;\ngeneralize dependent M';\ngeneralize dependent w';\ngeneralize dependent w;\ninduction H1; intros; inversion HeqM1; inversion HeqM0; subst;\n[constructor; constructor; auto | ];\napply multi_step_Hyb with (M':=unbox_fetch_Hyb (fwo w') M');\n[ constructor | eapply IHsteps_Hyb ]; eauto;\n[eapply lc_w_step_Hyb_preserv | eapply lc_t_step_Hyb_preserv]; eauto.\nQed.\n\nLemma steps_Hyb_get:\nforall M M'' w0 w1 w M' w'0,\n  (w0 = fwo w'0 \\/ w0 = bwo 0) ->\n  lc_w_Hyb M' -> lc_t_Hyb M' ->\n  lc_w_n_Hyb 1 M -> lc_t_n_Hyb 1 M ->\n  steps_Hyb (M', fwo w) (M'', fwo w) ->\n  steps_Hyb\n    (letdia_get_Hyb (fwo w) M' (get_here_Hyb w0 M), w1)\n    (letdia_get_Hyb (fwo w) M'' (get_here_Hyb w0 M), w1).\nintros.\nremember (M', fwo w) as M0; remember (M'', fwo w) as M1;\ngeneralize dependent M;\ngeneralize dependent M';\ngeneralize dependent M''.\ngeneralize dependent w;\ngeneralize dependent w0;\ngeneralize dependent w'0;\ngeneralize dependent w1.\ninduction H4; intros; inversion HeqM1; inversion HeqM0; subst;\n[constructor; constructor; auto |].\ninversion H0; subst; constructor; try omega; auto.\nconstructor; auto.\napply multi_step_Hyb\nwith (M':= letdia_get_Hyb (fwo w2) M' (get_here_Hyb w0 M0));\n[ constructor | eapply IHsteps_Hyb ]; eauto.\ninversion H0; subst; constructor; try omega; auto.\nconstructor; auto.\neapply lc_w_step_Hyb_preserv in H1; eauto.\neapply lc_t_step_Hyb_preserv in H2; eauto.\nQed.\n\nLemma steps_Hyb_letdia_here0:\nforall M N w0 w1 w M',\n  lc_w_Hyb (letdia_get_Hyb w (get_here_Hyb w0 M) M') ->\n  lc_t_Hyb (letdia_get_Hyb w (get_here_Hyb w0 M) M') ->\n  steps_Hyb (M, w0) (N, w0) -> value_Hyb N ->\n  steps_Hyb\n    (letdia_get_Hyb w (get_here_Hyb w0 M) M', w1)\n    (letdia_get_Hyb w (get_here_Hyb w0 N) M', w1).\nintros.\nremember (M, w0) as M0; remember (N, w0) as M1;\ngeneralize dependent M;\ngeneralize dependent N;\ngeneralize dependent w0.\ngeneralize dependent w1;\ngeneralize dependent w.\ngeneralize dependent M'.\ninduction H1; intros; inversion HeqM1; inversion HeqM0; subst.\ninversion H0; inversion H1; inversion H9; inversion H15; subst; try omega;\nrepeat constructor; auto.\ninversion H0; inversion H3; inversion H10; inversion H16; subst; try omega.\napply multi_step_Hyb\nwith (M':= letdia_get_Hyb (fwo w) (get_here_Hyb (fwo w4) M') M'0).\nrepeat constructor; auto.\napply IHsteps_Hyb; auto; repeat constructor; auto.\neapply lc_w_step_Hyb_preserv in H; eauto.\neapply lc_t_step_Hyb_preserv in H; eauto.\nQed.\n\nLemma steps_reorder:\nforall M M' M'' w,\n  (M, w) |->+ (M', w) -> (M', w)|-> (M'', w) -> (M, w) |->+ (M'', w).\nintros.\nremember (M, w) as M0; remember (M', w) as M1;\ngeneralize dependent M;\ngeneralize dependent M';\ngeneralize dependent M'';\ngeneralize dependent w.\ninduction H; intros; inversion HeqM0; inversion HeqM1; subst.\napply multi_step_Hyb with (M':=M'0); auto; repeat constructor; auto.\napply multi_step_Hyb with (M':=M'); auto.\napply IHsteps_Hyb with (M:=M') (M'1:=M'0); auto.\nQed.\n\nLemma steps_Hyb_letdia_here:\nforall M N w0 w1 w M',\n  lc_w_Hyb (letdia_get_Hyb w (get_here_Hyb w0 M) M') ->\n  lc_t_Hyb (letdia_get_Hyb w (get_here_Hyb w0 M) M') ->\n  steps_Hyb (M, w0) (N, w0) -> value_Hyb N ->\n  steps_Hyb\n    (letdia_get_Hyb w (get_here_Hyb w0 M) M', w1)\n    ((M' ^w^ w0) ^t^ N, w1).\nintros.\nassert ((letdia_get_Hyb w (get_here_Hyb w0 M) M', w1) |->+\n (letdia_get_Hyb w (get_here_Hyb w0 N) M', w1)).\napply steps_Hyb_letdia_here0; auto.\nassert ((letdia_get_Hyb w (get_here_Hyb w0 N) M', w1) |->\n((M' ^w^ w0 ) ^t^ N, w1)).\ninversion H; inversion H0; inversion H9; inversion H15; subst; try omega;\nconstructor; auto.\neapply lc_w_steps_Hyb_preserv in H1; eauto.\neapply lc_t_steps_Hyb_preserv in H1; eauto.\napply steps_reorder with (M':=(letdia_get_Hyb w (get_here_Hyb w0 N) M'));\nauto.\nQed.\n\nLemma steps_Hyb_appl:\nforall M N w M',\n  lc_w_Hyb (appl_Hyb M M') -> lc_t_Hyb (appl_Hyb M M') ->\n  steps_Hyb (M, fwo w) (N, fwo w) ->\n  steps_Hyb\n    (appl_Hyb M M', fwo w)\n    (appl_Hyb N M', fwo w).\nintros; remember (M, fwo w) as M0; remember (N, fwo w) as M1;\ngeneralize dependent M;\ngeneralize dependent N;\ngeneralize dependent w;\ngeneralize dependent M'.\ninduction H1; intros; inversion HeqM1; inversion HeqM0; subst.\ninversion H0; inversion H1; subst.\nrepeat constructor; auto.\ninversion H0; inversion H2; subst.\napply multi_step_Hyb with (M':=appl_Hyb M' M'0);\n[ constructor | eapply IHsteps_Hyb ]; eauto; try constructor; auto.\napply lc_w_step_Hyb_preserv in H; auto.\neapply lc_t_step_Hyb_preserv in H; eauto.\nQed.\n\nLemma steps_Hyb_letdia:\nforall M w' w M' N,\n  lc_w_Hyb (letdia_get_Hyb (fwo w') M N) ->\n  lc_t_Hyb (letdia_get_Hyb (fwo w') M N) ->\n  steps_Hyb (M, fwo w') (M', fwo w') ->\n  steps_Hyb\n    (letdia_get_Hyb (fwo w') M N, fwo w)\n    (letdia_get_Hyb (fwo w') M' N, fwo w).\nintros; remember (M, fwo w') as M0; remember (M', fwo w') as M1;\ngeneralize dependent M;\ngeneralize dependent M'.\ngeneralize dependent w;\ngeneralize dependent N.\ngeneralize dependent w'.\ninduction H1; intros; inversion HeqM1; inversion HeqM0; subst.\ninversion H0; inversion H1; subst.\nrepeat constructor; auto.\ninversion H0; inversion H2; subst.\napply multi_step_Hyb with (M':=letdia_get_Hyb (fwo w') M' N);\n[ constructor | eapply IHsteps_Hyb ]; eauto; try constructor; auto.\napply lc_w_step_Hyb_preserv in H; auto.\neapply lc_t_step_Hyb_preserv in H; eauto.\nQed.\n\nLemma steps_Hyb_here:\nforall M w' w M',\n lc_w_Hyb M -> lc_t_Hyb M ->\n steps_Hyb (M, fwo w') (M', fwo w') ->\n steps_Hyb\n   (get_here_Hyb (fwo w') M, w)\n   (get_here_Hyb (fwo w') M', w).\nintros; remember (M, fwo w') as M0; remember (M', fwo w') as M1;\ngeneralize dependent M;\ngeneralize dependent M';\ngeneralize dependent w';\ngeneralize dependent w;\ninduction H1; intros; inversion HeqM1; inversion HeqM0; subst;\n[constructor; constructor; auto | ];\napply multi_step_Hyb with (M':=get_here_Hyb (fwo w') M');\n[ constructor | eapply IHsteps_Hyb ]; eauto;\n[eapply lc_w_step_Hyb_preserv | eapply lc_t_step_Hyb_preserv]; eauto.\nQed.\n\n\nClose Scope hybrid_is5_scope.\nClose Scope is5_scope.\nClose Scope permut_scope.\n", "meta": {"author": "Ayertienna", "repo": "IS5", "sha": "3bfd1b8510f269071d59d77818f8936d194364bc", "save_path": "github-repos/coq/Ayertienna-IS5", "path": "github-repos/coq/Ayertienna-IS5/IS5-3bfd1b8510f269071d59d77818f8936d194364bc/src/Hybrid/Hyb_Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.23898001888212936}}
{"text": "Require Export Arith.EqNat.\nRequire Export Arith.Lt.\nRequire Export Arith.Compare_dec.\nRequire Export List.\nRequire Import String.\nOpen Scope string_scope.\nRequire Import TacticsSF.\nRequire Import TacticsCPDT.\nRequire Import Process.\nRequire Import List.\nRequire Import PrettyPrinter.\nRequire Import TypeAssignmentPoly.\nRequire Import ResultBasics.\nRequire Import ExampleCommon.\nRequire Import ExampleRecursion.\n\nLemma abp_sendB_Nack_procR_typing :\n  forall i k r r' (xc:free_id) (xerr1:free_id) (x:free_id) (xin:free_id),\n    r --(MInp (TSingleton k))--> r'\n    ->\n    ~ In xc (\"send_true\" :: \"send_false\" :: nil)\n    ->\n    ~ In x (xc :: \"send_true\" :: \"send_false\" :: nil)\n    ->\n    ~ In xin (x :: xc :: \"send_true\" :: \"send_false\" :: nil)\n    ->\n    ~ In xerr1 (xin :: x :: xc :: \"send_true\" :: \"send_false\" :: nil)\n    ->\n    (CTX.add(ValVariable (Var (Free xerr1)),\n        TChannel (SNack r k r' (token_of_bool i)))\n      (CTX.add(ValVariable (Var (Free xc)), TChannel SEpsilon)\n      (CTX.add(ValVariable (Var (Free xin)), TChannel (SToks (r')))\n      (CTX.add(ValVariable (Var (Free x)), TSingleton k) \n      (CTX.add(ValName (Nm (Free (String.append \"send_\" (string_of_bool i)))),\n        (TChannel (SFwd (SSend i))))\n      (CTX.add(ValName(CoNm (Free (String.append \"send_\" (string_of_bool i)))),\n        (TChannel (SDual (SFwd (SSend i)))))\n      (CTX.add(ValName (CoNm (Free (String.append \"send_\"\n        (string_of_bool (negb i))))),\n        (TChannel (SDual (SFwd (SSend (negb i))))))\n      CTX.empty)))))))\n    |-p Var (Free xerr1) ? ;\n      (IsEq (Var (Bound 0))\n        (Token (if if i then false else true then \"true\" else \"false\"))\n      (New\n      (CoNm (Free (String.append \"send_\" (if i then \"true\" else \"false\")))\n        ! Nm (Bound 0);\n      (CoNm (Bound 0) ! Var (Free x);\n      (CoNm (Bound 0) ! Var (Free xin);\n      (CoNm (Bound 0) ! Var (Free xerr1);\n      Zero)))))).\n\nProof.\n  intros i k r r' xc xerr1 x xin Htrans Hxc_nin Hx_nin Hxin_nin Hxerr1_nin.\n  compute.\n  apply TypPrefixInput  with (s:=SNack r k r' (token_of_bool i))\n      (L:=xc :: xerr1 :: xin :: x :: \"send_true\" :: \"send_false\" :: nil);\n    [constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n      | free_vals_in_ctx |].\n  intros G' rho t z H_z_nin Htrans4 G'def; compute; subst G'.\n  inversion Htrans4; subst.\n  Case \"Htrans4 : TRNackB\".\n    apply TypIsEq with (K:=Token (string_of_negb_string (string_of_bool i)))\n        (L:=token_of_bool (negb i));\n      [constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | apply LToken; destruct i; ctx_wf; discriminate_w_list\n        | free_vals_in_ctx |].\n    intro H_i_tok_eq.\n    apply TypNew  with (s:=SSend i)\n        (L:=z :: xc :: xerr1 :: xin :: x :: \"send_true\" :: \"send_false\"\n          :: nil).\n    intros d G' H_d_nin G'def; compute; subst G'.\n    eapply TypPrefixOutput with (s:=SDual (SFwd (SSend i)))\n        (rho:=TChannel (SSend i)) (t:=SDual (SFwd (SSend i)));\n      [apply trdual_w_mdual_involution; constructor\n        | left; discriminate\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | left; reflexivity\n        | reflexivity | ].\n    eapply TypPrefixOutput with (s:=SDual (SSend i)) (rho:=TSingleton k)\n        (t:=SDual (SSend1 i r' (SNack r k r' (token_of_bool i))));\n      [apply trdual_w_mdual_involution; constructor; assumption\n        | left; discriminate\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | right; split; [reflexivity | constructor]\n        | reflexivity | ].\n    eapply TypPrefixOutput with\n        (s:=SDual (SSend1 i r' (SNack r k r' (token_of_bool i))))\n        (rho:=TChannel (SToks r'))\n        (t:=SDual (SSend2 i (SNack r k r' (token_of_bool i))));\n      [apply trdual_w_mdual_involution; constructor; assumption\n        | left; discriminate\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | left; reflexivity\n        | reflexivity | ].\n    eapply TypPrefixOutput with\n        (s:=SDual (SSend2 i (SNack r k r' (token_of_bool i))))\n        (rho:=TChannel (SNack r k r' (token_of_bool i)))\n        (t:=SDual SEpsilon);\n      [apply trdual_w_mdual_involution; constructor; assumption\n        | left; discriminate\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | left; reflexivity\n        | reflexivity | ].\n    apply TypZero;\n      destruct i;\n      ctx_wf;\n      discriminate_w_list.\n\n  Case \"Htrans4 : TRNackC\".\n    apply TypIsEq with (K:=token_of_bool i) (L:=token_of_bool (negb i));\n      [constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | apply LToken; destruct i; ctx_wf; discriminate_w_list\n        | free_vals_in_ctx |].\n      intro H_bad;\n        destruct i in H_bad;\n        contradict H_bad;\n        discriminate.\nQed.\n", "meta": {"author": "cmcl", "repo": "msci", "sha": "06b1607ee1f4dde3c7c984ce6e1bbc86a8fd36f9", "save_path": "github-repos/coq/cmcl-msci", "path": "github-repos/coq/cmcl-msci/msci-06b1607ee1f4dde3c7c984ce6e1bbc86a8fd36f9/Coq Developments/session-polymorphism-coq-scripts/ExampleABPSendBNack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23895339742737803}}
{"text": "\nRequire Import String.\nImport List.\nImport ListNotations.\n\nRequire Import Flood_Properties.\nRequire Import List_Properties.\n\n\n(* Not needed but it's sanity *)\nLemma flood_safety_concat:\n  forall trace trace',\n  flood_safety trace ->\n  flood_safety trace' ->\n  flood_safety (trace ++ trace').\nProof.\n  unfold flood_safety.\n  intros.\n  apply nth_index_in_concat in H1.\n  destruct H1.\n  - assert (exists t1 : nat, t1 < t2 /\\ nth_error trace t1 = Some (Flood_Input i (m, c))).\n    + eapply H.\n      eassumption.\n    + destruct H2.\n      exists x.\n      destruct H2.\n      split.\n      * assumption.\n      * rewrite nth_error_app1.\n        -- assumption.\n        -- apply nth_error_Some.\n           rewrite H3.\n           discriminate.\n  - destruct H1.\n    destruct H1.\n    assert (exists t1 : nat, t1 < x /\\ nth_error trace' t1 = Some (Flood_Input i (m, c))).\n    + eapply H0.\n      eassumption.\n    + destruct H3.\n      destruct H3.\n      exists (x0 + Datatypes.length trace).\n      split.\n      * rewrite <- H1.\n        apply Plus.plus_lt_compat_r.\n        assumption.\n      * rewrite nth_error_app2.\n        -- rewrite PeanoNat.Nat.add_sub.\n           assumption.\n        -- apply Plus.le_plus_r.\nQed.\n\n\nLemma flood_safety_append_not_output: forall trace t,\n  flood_safety trace ->\n  (forall i j m c, t <> Flood_Output i j (m, c)) ->\n  flood_safety (trace ++ [t]).\nProof.\n  intros trace t.\n  unfold flood_safety in * |- *.\n  intros H_trace_safety H_not_output.\n  intros i j m c t2 H_nth.\n  specialize (H_trace_safety i j m c t2).\n  assert (exists t1 : nat, t1 < t2 /\\ nth_error trace t1 = Some (Flood_Input i (m, c))).\n  - apply H_trace_safety.\n    apply nth_different_tail_smaller with t.\n    + apply H_not_output.\n    + assumption.\n  - destruct H as [t1 H].\n    destruct H.\n    exists t1.\n    split.\n    + assumption.\n    + apply nth_succes_larger.\n      assumption.\nQed.\n\n\nLemma flood_safety_append_input: forall trace i m c,\n  flood_safety trace ->\n  flood_safety (trace ++ [Flood_Input i (m, c)]).\nProof.\n  intros.\n  apply flood_safety_append_not_output.\n  assumption.\n  intros.\n  discriminate.\nQed.\n\nLemma flood_safety_append_leak: forall trace i m c,\n  flood_safety trace ->\n  flood_safety (trace ++ [Flood_Leak i (m, c)]).\nProof.\n  intros.\n  apply flood_safety_append_not_output.\n  assumption.\n  intros.\n  discriminate.\nQed.\n\nLemma flood_safety_append_deliver: forall trace i j m c,\n  flood_safety trace ->\n  flood_safety (trace ++ [Flood_Deliver i j (m, c)]).\nProof.\n  intros.\n  apply flood_safety_append_not_output.\n  assumption.\n  intros.\n  discriminate.\nQed.\n\nLemma flood_safety_append_output:\n  forall trace t i j m c,\n  flood_safety trace ->\n  nth_error trace t = Some (Flood_Input i (m, c)) ->\n  flood_safety (trace ++ [Flood_Output i j (m, c)]).\nProof.\n  intros trace t i j m c.\n  intros H_safe_trace H_nth_input.\n  unfold flood_safety in * |- *.\n  intros i' j' m' c' t2.\n  intros H_nth_output.\n  assert (t2 < Datatypes.length trace \\/ Datatypes.length trace <= t2)\n    as H_t2_lt_ge\n    by (apply PeanoNat.Nat.lt_ge_cases).\n  destruct H_t2_lt_ge as [H_t2_lt | H_t2_ge].\n  - assert (nth_error trace t2 = Some (Flood_Output i' j' (m', c'))).\n    + erewrite <- nth_error_app1;\n      eassumption.\n    + assert (exists t1 : nat, t1 < t2 /\\ nth_error trace t1 = Some (Flood_Input i' (m', c')))\n        as H_input_in_trace\n        by (eapply H_safe_trace;\n            try eassumption).\n      destruct H_input_in_trace as [t1 H_input_in_trace].\n      destruct H_input_in_trace as [H_t1_lt H_input_in_trace].\n      exists t1.\n      split.\n      * assumption.\n      * rewrite nth_error_app1.\n        -- assumption.\n        -- eapply PeanoNat.Nat.lt_trans;\n           eassumption.\n  - rewrite nth_error_app2 in H_nth_output.\n    + exists t.\n      split.\n      * assert (t < Datatypes.length trace).\n        -- apply nth_error_Some.\n           unfold not.\n           intros H_is_none.\n           rewrite H_is_none in H_nth_input.\n           discriminate.\n        -- eapply PeanoNat.Nat.lt_le_trans;\n           eassumption.\n      * apply nth_succes_larger.\n        assert (t2 - Datatypes.length trace < Datatypes.length [Flood_Output i j (m, c)])\n          as H_t2_lt_length.\n        -- apply nth_error_Some.\n           unfold not.\n           intros H_is_none.\n           rewrite H_is_none in H_nth_output.\n           discriminate.\n        -- simpl in H_t2_lt_length.\n           destruct (t2 - Datatypes.length trace).\n           ++ simpl in H_nth_output.\n              inversion H_nth_output.\n              subst. clear H_nth_output.\n              assumption.\n           ++ inversion H_t2_lt_length.\n              apply Le.le_n_0_eq in H0.\n              inversion H0.\n    + assumption.\nQed.\n", "meta": {"author": "Crowton", "repo": "FloodingNetworkSafeAndLive", "sha": "8f891be37593f096cf519369ae4ccd6162092968", "save_path": "github-repos/coq/Crowton-FloodingNetworkSafeAndLive", "path": "github-repos/coq/Crowton-FloodingNetworkSafeAndLive/FloodingNetworkSafeAndLive-8f891be37593f096cf519369ae4ccd6162092968/flood_safety_properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23895339102679922}}
{"text": "Require Import Bool.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Global.\nRequire Import Local.\n\nSet Implicit Arguments.\n\n\nVariant tau T (step: forall (e:ThreadEvent.t) (th1 th2:T), Prop) (th1 th2:T): Prop :=\n| tau_intro\n    e\n    (TSTEP: step e th1 th2)\n    (EVENT: ThreadEvent.get_machine_event e = MachineEvent.silent)\n.\n#[export] Hint Constructors tau: core.\n\nVariant union E T (step: forall (e:E) (th1 th2:T), Prop) (th1 th2:T): Prop :=\n| union_intro\n    e\n    (USTEP: step e th1 th2)\n.\n#[export] Hint Constructors union: core.\n\nVariant pstep E T (step: forall (e: E) (th1 th2: T), Prop) (P: E -> Prop) (th1 th2: T): Prop :=\n| pstep_intro\n    e\n    (STEP: step e th1 th2)\n    (EVENT: P e)\n.\n#[export] Hint Constructors pstep: core.\n\nLemma tau_mon T (step1 step2: forall (e:ThreadEvent.t) (th1 th2:T), Prop)\n      (STEP: step1 <3= step2):\n  tau step1 <2= tau step2.\nProof.\n  i. inv PR. econs; eauto.\nQed.\n\nLemma union_mon E T (step1 step2: forall (e:E) (th1 th2:T), Prop)\n      (STEP: step1 <3= step2):\n  union step1 <2= union step2.\nProof.\n  i. inv PR. econs; eauto.\nQed.\n\nLemma pstep_mon E T (step1 step2: forall (e:E) (th1 th2:T), Prop) P1 P2\n      (STEP: step1 <3= step2)\n      (P: P1 <1= P2):\n  pstep step1 P1 <2= pstep step2 P2.\nProof.\n  i. inv PR. econs; eauto.\nQed.\n\nLemma tau_union: tau <4= (@union ThreadEvent.t).\nProof.\n  ii. inv PR. econs. eauto.\nQed.\n\nLemma pstep_union E T step P:\n  @pstep E T step P <2= @union E T step.\nProof.\n  i. inv PR. eauto.\nQed.\n\n\nModule Thread.\n  Section Thread.\n    Variable (lang: language).\n\n    Structure t := mk {\n      state: (Language.state lang);\n      local: Local.t;\n      global: Global.t;\n    }.\n\n    Variant step: forall (e: ThreadEvent.t) (th1 th2: t), Prop :=\n    | step_internal\n        e st lc1 gl1 lc2 gl2\n        (LOCAL: Local.internal_step e lc1 gl1 lc2 gl2):\n      step e (mk st lc1 gl1) (mk st lc2 gl2)\n    | step_program\n        e st1 lc1 gl1 st2 lc2 gl2\n        (STATE: Language.step lang (ThreadEvent.get_program_event e) st1 st2)\n        (LOCAL: Local.program_step e lc1 gl1 lc2 gl2):\n      step e (mk st1 lc1 gl1) (mk st2 lc2 gl2)\n    .\n    Hint Constructors step: core.\n\n    Definition tau_step := tau step.\n    Hint Unfold tau_step: core.\n\n    Definition all_step := union step.\n    Hint Unfold all_step: core.\n\n    Variant opt_step: forall (e:ThreadEvent.t) (th1 th2:t), Prop :=\n      | step_none\n          th:\n        opt_step ThreadEvent.silent th th\n      | step_some\n          e th1 th2\n          (STEP: step e th1 th2):\n        opt_step e th1 th2\n    .\n    Hint Constructors opt_step: core.\n\n    Variant internal_step: forall (th1 th2: t), Prop :=\n    | interal_step_intro\n        e st lc1 gl1 lc2 gl2\n        (LOCAL: Local.internal_step e lc1 gl1 lc2 gl2):\n      internal_step (mk st lc1 gl1) (mk st lc2 gl2)\n    .\n    Hint Constructors internal_step: core.\n\n    Variant program_step: forall (e: ThreadEvent.t) (th1 th2: t), Prop :=\n    | program_step_intro\n        e st1 lc1 gl1 st2 lc2 gl2\n        (STATE: Language.step lang (ThreadEvent.get_program_event e) st1 st2)\n        (LOCAL: Local.program_step e lc1 gl1 lc2 gl2):\n      program_step e (mk st1 lc1 gl1) (mk st2 lc2 gl2)\n    .\n    Hint Constructors program_step: core.\n\n    Lemma tau_opt_tau\n          th1 th2 th3 e\n          (STEPS: rtc tau_step th1 th2)\n          (STEP: opt_step e th2 th3)\n          (EVENT: ThreadEvent.get_machine_event e = MachineEvent.silent):\n      rtc tau_step th1 th3.\n    Proof.\n      induction STEPS.\n      - inv STEP; eauto.\n      - exploit IHSTEPS; eauto.\n    Qed.\n\n    Lemma tau_opt_all\n          th1 th2 th3 e\n          (STEPS: rtc tau_step th1 th2)\n          (STEP: opt_step e th2 th3):\n      rtc all_step th1 th3.\n    Proof.\n      induction STEPS.\n      - inv STEP; eauto.\n      - exploit IHSTEPS; eauto. i.\n        econs 2; eauto.\n        inv H. econs. eauto.\n    Qed.\n\n\n    (* consistency *)\n\n    Definition cap_of (th: t): t :=\n      mk (state th) (local th) (Global.cap_of (global th)).\n\n    Variant steps_failure (th1: t): Prop :=\n      | steps_failure_intro\n          e th2 th3\n          (STEPS: rtc tau_step th1 th2)\n          (STEP_FAILURE: step e th2 th3)\n          (EVENT_FAILURE: ThreadEvent.get_machine_event e = MachineEvent.failure)\n    .\n\n    Variant consistent (th: t): Prop :=\n      | consistent_failure\n          (FAILURE: steps_failure (cap_of th))\n      | consistent_fulfill\n          th2\n          (STEPS: rtc tau_step (cap_of th) th2)\n          (PROMISES: Local.promises (Thread.local th2) = BoolMap.bot)\n    .\n\n    Lemma cap_wf\n          th\n          (LC_WF: Local.wf (local th) (global th))\n          (GL_WF: Global.wf (global th)):\n      (<<LC_WF_CAP: Local.wf (local (cap_of th)) (global (cap_of th))>>) /\\\n      (<<GL_WF_CAP: Global.wf (global (cap_of th))>>).\n    Proof.\n      exploit Local.cap_wf; eauto.\n      exploit Global.cap_wf; eauto.\n    Qed.\n\n    (* step_future *)\n\n    Lemma step_future\n          e th1 th2\n          (STEP: step e th1 th2)\n          (LC_WF1: Local.wf (local th1) (global th1))\n          (GL_WF1: Global.wf (global th1)):\n      <<LC_WF2: Local.wf (local th2) (global th2)>> /\\\n      <<GL_WF2: Global.wf (global th2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local th1)) (Local.tview (local th2))>> /\\\n      <<GL_FUTURE: Global.future (global th1) (global th2)>>.\n    Proof.\n      inv STEP; ss.\n      - eauto using Local.internal_step_future.\n      - eauto using Local.program_step_future.\n    Qed.\n\n    Lemma opt_step_future\n          e th1 th2\n          (STEP: opt_step e th1 th2)\n          (LC_WF1: Local.wf (local th1) (global th1))\n          (GL_WF1: Global.wf (global th1)):\n      <<LC_WF2: Local.wf (local th2) (global th2)>> /\\\n      <<GL_WF2: Global.wf (global th2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local th1)) (Local.tview (local th2))>> /\\\n      <<GL_FUTURE: Global.future (global th1) (global th2)>>.\n    Proof.\n      inv STEP; eauto using step_future.\n      esplits; eauto; refl.\n    Qed.\n\n    Lemma rtc_all_step_future\n          th1 th2\n          (STEP: rtc all_step th1 th2)\n          (LC_WF1: Local.wf (local th1) (global th1))\n          (GL_WF1: Global.wf (global th1)):\n      <<LC_WF2: Local.wf (local th2) (global th2)>> /\\\n      <<GL_WF2: Global.wf (global th2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local th1)) (Local.tview (local th2))>> /\\\n      <<GL_FUTURE: Global.future (global th1) (global th2)>>.\n    Proof.\n      revert LC_WF1. induction STEP; i.\n      - splits; ss; refl.\n      - inv H. exploit step_future; eauto. i. des.\n        exploit IHSTEP; eauto. i. des.\n        splits; ss; etrans; eauto.\n    Qed.\n\n    Lemma rtc_tau_step_future\n          th1 th2\n          (STEP: rtc tau_step th1 th2)\n          (LC_WF1: Local.wf (local th1) (global th1))\n          (GL_WF1: Global.wf (global th1)):\n      <<LC_WF2: Local.wf (local th2) (global th2)>> /\\\n      <<GL_WF2: Global.wf (global th2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local th1)) (Local.tview (local th2))>> /\\\n      <<GL_FUTURE: Global.future (global th1) (global th2)>>.\n    Proof.\n      apply rtc_all_step_future; auto.\n      eapply rtc_implies; [|eauto].\n      apply tau_union.\n    Qed.\n\n    Lemma internal_step_future\n          th1 th2\n          (STEP: internal_step th1 th2)\n          (LC_WF1: Local.wf (local th1) (global th1))\n          (GL_WF1: Global.wf (global th1)):\n      <<LC_WF2: Local.wf (local th2) (global th2)>> /\\\n      <<GL_WF2: Global.wf (global th2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local th1)) (Local.tview (local th2))>> /\\\n      <<GL_FUTURE: Global.future (global th1) (global th2)>>.\n    Proof.\n      inv STEP; ss.\n      eauto using Local.internal_step_future.\n    Qed.\n\n    Lemma rtc_internal_step_future\n          th1 th2\n          (STEP: rtc internal_step th1 th2)\n          (LC_WF1: Local.wf (local th1) (global th1))\n          (GL_WF1: Global.wf (global th1)):\n      <<LC_WF2: Local.wf (local th2) (global th2)>> /\\\n      <<GL_WF2: Global.wf (global th2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local th1)) (Local.tview (local th2))>> /\\\n      <<GL_FUTURE: Global.future (global th1) (global th2)>>.\n    Proof.\n      revert LC_WF1. induction STEP; i.\n      - splits; ss; refl.\n      - exploit internal_step_future; eauto. i. des.\n        exploit IHSTEP; eauto. i. des.\n        splits; ss; etrans; eauto.\n    Qed.\n\n    Lemma program_step_future\n          e th1 th2\n          (STEP: program_step e th1 th2)\n          (LC_WF1: Local.wf (local th1) (global th1))\n          (GL_WF1: Global.wf (global th1)):\n      <<LC_WF2: Local.wf (local th2) (global th2)>> /\\\n      <<GL_WF2: Global.wf (global th2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local th1)) (Local.tview (local th2))>> /\\\n      <<GL_FUTURE: Global.future (global th1) (global th2)>>.\n    Proof.\n      inv STEP; ss.\n      eauto using Local.program_step_future.\n    Qed.\n\n    Lemma rtc_program_step_future\n          th1 th2\n          (STEP: rtc (tau program_step) th1 th2)\n          (LC_WF1: Local.wf (local th1) (global th1))\n          (GL_WF1: Global.wf (global th1)):\n      <<LC_WF2: Local.wf (local th2) (global th2)>> /\\\n      <<GL_WF2: Global.wf (global th2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local th1)) (Local.tview (local th2))>> /\\\n      <<GL_FUTURE: Global.future (global th1) (global th2)>>.\n    Proof.\n      revert LC_WF1. induction STEP; i.\n      - splits; ss; refl.\n      - inv H. exploit program_step_future; eauto. i. des.\n        exploit IHSTEP; eauto. i. des.\n        splits; ss; etrans; eauto.\n    Qed.\n\n\n    (* step_inhabited *)\n\n    Lemma step_inhabited\n          e th1 th2\n          (STEP: step e th1 th2)\n          (INHABITED1: Memory.inhabited (Global.memory (global th1))):\n      <<INHABITED2: Memory.inhabited (Global.memory (global th2))>>.\n    Proof.\n      inv STEP.\n      - eapply Local.internal_step_inhabited; eauto.\n      - eapply Local.program_step_inhabited; eauto.\n    Qed.\n\n\n    (* step_disjoint *)\n\n    Lemma step_disjoint\n          e th1 th2 lc\n          (STEP: step e th1 th2)\n          (DISJOINTH1: Local.disjoint (local th1) lc)\n          (LC_WF: Local.wf lc (global th1)):\n      <<DISJOINTH2: Local.disjoint (local th2) lc>> /\\\n      <<LC_WF: Local.wf lc (global th2)>>.\n    Proof.\n      inv STEP.\n      - eapply Local.internal_step_disjoint; eauto.\n      - eapply Local.program_step_disjoint; eauto.\n    Qed.\n\n    Lemma opt_step_disjoint\n          e th1 th2 lc\n          (STEP: opt_step e th1 th2)\n          (DISJOINTH1: Local.disjoint (local th1) lc)\n          (LC_WF: Local.wf lc (global th1)):\n      <<DISJOINTH2: Local.disjoint (local th2) lc>> /\\\n      <<LC_WF: Local.wf lc (global th2)>>.\n    Proof.\n      inv STEP.\n      - esplits; eauto.\n      - eapply step_disjoint; eauto.\n    Qed.\n\n    Lemma rtc_all_step_disjoint\n          th1 th2 lc\n          (STEP: rtc all_step th1 th2)\n          (DISJOINTH1: Local.disjoint (local th1) lc)\n          (LC_WF: Local.wf lc (global th1)):\n      <<DISJOINTH2: Local.disjoint (local th2) lc>> /\\\n      <<LC_WF: Local.wf lc (global th2)>>.\n    Proof.\n      revert DISJOINTH1 LC_WF. induction STEP; eauto. i.\n      inv H. exploit step_disjoint; eauto. i. des. eauto.\n    Qed.\n\n    Lemma rtc_tau_step_disjoint\n          th1 th2 lc\n          (STEP: rtc tau_step th1 th2)\n          (DISJOINTH1: Local.disjoint (local th1) lc)\n          (LC_WF: Local.wf lc (global th1)):\n      <<DISJOINTH2: Local.disjoint (local th2) lc>> /\\\n      <<LC_WF: Local.wf lc (global th2)>>.\n    Proof.\n      eapply rtc_all_step_disjoint; cycle 1; eauto.\n      eapply rtc_implies; [|eauto].\n      apply tau_union.\n    Qed.\n\n    Lemma program_step_promises\n          e th1 th2\n          (STEP: Thread.step e th1 th2)\n          (EVENT: ThreadEvent.is_program e):\n      BoolMap.le (Local.promises (local th2)) (Local.promises (local th1)) /\\\n      BoolMap.le (Global.promises (global th2)) (Global.promises (global th1)).\n    Proof.\n      inv STEP; try by (inv LOCAL; ss).\n      eapply Local.program_step_promises; eauto.\n    Qed.\n\n    Lemma step_promises_minus\n          e th1 th2\n          (STEP: step e th1 th2):\n      BoolMap.minus (Global.promises (Thread.global th1)) (Local.promises (Thread.local th1)) =\n      BoolMap.minus (Global.promises (Thread.global th2)) (Local.promises (Thread.local th2)).\n    Proof.\n      inv STEP; s.\n      - eapply Local.internal_step_promises_minus; eauto.\n      - eapply Local.program_step_promises_minus; eauto.\n    Qed.\n\n    Lemma rtc_all_step_promises_minus\n          th1 th2\n          (STEPS: rtc all_step th1 th2):\n      BoolMap.minus (Global.promises (Thread.global th1)) (Local.promises (Thread.local th1)) =\n      BoolMap.minus (Global.promises (Thread.global th2)) (Local.promises (Thread.local th2)).\n    Proof.\n      induction STEPS; ss. inv H.\n      exploit step_promises_minus; eauto. i. congr.\n    Qed.\n\n    Lemma rtc_tau_step_promises_minus\n          th1 th2\n          (STEPS: rtc tau_step th1 th2):\n      BoolMap.minus (Global.promises (Thread.global th1)) (Local.promises (Thread.local th1)) =\n      BoolMap.minus (Global.promises (Thread.global th2)) (Local.promises (Thread.local th2)).\n    Proof.\n      apply rtc_all_step_promises_minus.\n      eapply rtc_implies; try exact STEPS.\n      apply tau_union.\n    Qed.\n\n\n    (* step_strong_le *)\n\n    Lemma step_strong_le\n          e th1 th2\n          (STEP: step e th1 th2)\n          (LC_WF1: Local.wf (local th1) (global th1))\n          (GL_WF1: Global.wf (global th1)):\n      <<LC_WF2: Local.wf (local th2) (global th2)>> /\\\n      <<GL_WF2: Global.wf (global th2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local th1)) (Local.tview (local th2))>> /\\\n      <<GL_FUTURE: Global.strong_le (global th1) (global th2)>>\n      \\/\n      exists e_race th2',\n        <<STEP: step e_race th1 th2'>> /\\\n        <<EVENT: ThreadEvent.get_program_event e_race = ThreadEvent.get_program_event e>> /\\\n        <<RACE: ThreadEvent.get_machine_event e_race = MachineEvent.failure>>\n    .\n    Proof.\n      inv STEP; ss.\n      - eauto using Local.internal_step_strong_le.\n      - hexploit Local.program_step_strong_le; eauto. i. des.\n        { left. esplits; eauto. }\n        { right. exists e_race. esplits; eauto. econs 2; eauto.\n          rewrite EVENT. eauto.\n        }\n    Qed.\n\n    Lemma opt_step_strong_le\n          e th1 th2\n          (STEP: opt_step e th1 th2)\n          (LC_WF1: Local.wf (local th1) (global th1))\n          (GL_WF1: Global.wf (global th1)):\n      <<LC_WF2: Local.wf (local th2) (global th2)>> /\\\n      <<GL_WF2: Global.wf (global th2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local th1)) (Local.tview (local th2))>> /\\\n      <<GL_FUTURE: Global.strong_le (global th1) (global th2)>>\n      \\/\n      exists e_race th2',\n        <<STEP: step e_race th1 th2'>> /\\\n        <<EVENT: ThreadEvent.get_program_event e_race = ThreadEvent.get_program_event e>> /\\\n        <<RACE: ThreadEvent.get_machine_event e_race = MachineEvent.failure>>\n    .\n    Proof.\n      inv STEP; eauto using step_strong_le.\n      left. esplits; eauto; refl.\n    Qed.\n\n    Lemma rtc_tau_step_strong_le\n          th1 th2\n          (STEP: rtc tau_step th1 th2)\n          (LC_WF1: Local.wf (local th1) (global th1))\n          (GL_WF1: Global.wf (global th1)):\n      <<LC_WF2: Local.wf (local th2) (global th2)>> /\\\n      <<GL_WF2: Global.wf (global th2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (local th1)) (Local.tview (local th2))>> /\\\n      <<GL_FUTURE: Global.strong_le (global th1) (global th2)>>\n          \\/\n      <<FAILURE: steps_failure th1>>\n    .\n    Proof.\n      revert LC_WF1. induction STEP; i.\n      - left. splits; ss; refl.\n      - inv H. exploit step_strong_le; eauto. i. des.\n        2:{ right. repeat red. econs; [refl| |]; eauto. }\n        exploit IHSTEP; eauto. i. des.\n        { left. splits; auto; etrans; eauto. }\n        { inv FAILURE. right. econs.\n          { econs 2.\n            { econs; eauto. }\n            { eauto. }\n          }\n          { eauto. }\n          { eauto. }\n        }\n    Qed.\n\n\n    (* internal and program step *)\n\n    Lemma internal_step_tau_thread_step\n          th1 th2\n          (STEP: internal_step th1 th2)\n      :\n      tau_step th1 th2.\n    Proof.\n      inv STEP. econs 1; eauto. inv LOCAL; ss.\n    Qed.\n\n    Lemma program_step_thread_step\n          e th1 th2\n          (STEP: program_step e th1 th2)\n      :\n      step e th1 th2.\n    Proof.\n      inv STEP. econs 2; eauto.\n    Qed.\n\n    Lemma rtc_internal_step_rtc_tau_thread_step\n          th1 th2\n          (STEPS: rtc internal_step th1 th2)\n      :\n      rtc tau_step th1 th2.\n    Proof.\n      induction STEPS; eauto. econs 2; [|eauto].\n      eapply internal_step_tau_thread_step; eauto.\n    Qed.\n\n    Lemma rtc_tau_program_step_rtc_tau_thread_step\n          th1 th2\n          (STEPS: rtc (tau program_step) th1 th2)\n      :\n      rtc tau_step th1 th2.\n    Proof.\n      induction STEPS; eauto. econs 2; [|eauto].\n      inv H. econs; eauto. eapply program_step_thread_step; eauto.\n    Qed.\n\n  End Thread.\nEnd Thread.\n#[export] Hint Constructors Thread.step: core.\n#[export] Hint Constructors Thread.opt_step: core.\n#[export] Hint Constructors Thread.steps_failure: core.\n#[export] Hint Constructors Thread.consistent: core.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/model/Thread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772884, "lm_q2_score": 0.3140505578320071, "lm_q1q2_score": 0.2388827617885827}}
{"text": "(* This file is an automatic translation, the licence of the source can be found here: *)\n(* https://github.com/herd/herdtools7/blob/master/LICENSE.txt *)\n(* Translation of model SC, no co generated *)\nFrom Coq Require Import Relations Ensembles String.\nFrom RelationAlgebra Require Import lattice prop monoid rel kat.\nFrom Catincoq.lib Require Import Cat proprel.\nSection Model.\nVariable c : candidate.\nDefinition events := events c.\nDefinition R := R c.\nDefinition W := W c.\nDefinition IW := IW c.\nDefinition FW := FW c.\nDefinition B := B c.\nDefinition RMW := RMW c.\nDefinition F := F c.\nDefinition rf := rf c.\nDefinition po := po c.\nDefinition int := int c.\nDefinition ext := ext c.\nDefinition loc := loc c.\nDefinition addr := addr c.\nDefinition data := data c.\nDefinition ctrl := ctrl c.\nDefinition amo := amo c.\nDefinition rmw := rmw c.\nDefinition unknown_set := unknown_set c.\nDefinition unknown_relation := unknown_relation c.\nDefinition M := R ⊔ W.\nDefinition emptyset : set events := empty.\nDefinition classes_loc : set events -> Ensemble (Ensemble events) := partition loc.\nDefinition tag2events := unknown_relation \"tag2events\".\nDefinition emptyset_0 : set events := domain 0.\nDefinition partition := classes_loc.\nDefinition tag2instrs := tag2events.\nDefinition po_loc := po ⊓ loc.\nDefinition rfe := rf ⊓ ext.\nDefinition rfi := rf ⊓ int.\nDefinition co0 := loc ⊓ ([IW] ⋅ top ⋅ [(W ⊓ !IW)] ⊔ [(W ⊓ !FW)] ⋅ top ⋅ [FW]).\nDefinition toid (s : set events) : relation events := [s].\nDefinition fencerel (B : set events) := (po ⊓ [top] ⋅ top ⋅ [B]) ⋅ po.\nDefinition ctrlcfence (CFENCE : set events) := (ctrl ⊓ [top] ⋅ top ⋅ [CFENCE]) ⋅ po.\nDefinition imply (A : relation events) (B : relation events) := !A ⊔ B.\nDefinition nodetour (R1 : relation events) (R2 : relation events) (R3 : relation events) := R1 ⊓ !(R2 ⋅ R3).\nDefinition singlestep (R : relation events) := nodetour R R R.\n(* Definition of map already included in the prelude *)\nDefinition LKW := (*failed: try LKW with emptyset_0*) emptyset_0.\nDefinition WW r := r ⊓ [W] ⋅ top ⋅ [W].\nDefinition RW r := r ⊓ [R] ⋅ top ⋅ [W].\nDefinition U0 := po_loc ⊔ (rf ⊔ co0).\nInductive U : relation _ := U_c : incl (U0 ⊔ (WW (U ⋅ rf°) ⊓ !id ⊔ (RW (rf° ⋅ U) ⊓ !id ⊔ U ⋅ U))) U.\nSection scheme.\nVariables U' : relation events.\nVariable HU' : incl (U0 ⊔ (WW (U' ⋅ rf°) ⊓ !id ⊔ (RW (rf° ⋅ U') ⊓ !id ⊔ U' ⋅ U'))) U'.\n\n  Fixpoint U_ind' x y (r : U x y) : U' x y.\n  Proof.\n    destruct r as [x y r]; apply HU'.\n    destruct r as [r | r]; [ left | right ].\n     exact r.\n     destruct r as [r | r]; [ left | right ].\n       destruct r as [r1 r2]; split.\n        destruct r1 as [r11 r12]; split.\n         destruct r11 as [x_y r111 r112]; exists x_y.\n          apply U_ind'; exact r111.\n          exact r112.\n         exact r12.\n        exact r2.\n      destruct r as [r | r]; [ left | right ].\n        destruct r as [r1 r2]; split.\n         destruct r1 as [r11 r12]; split.\n          destruct r11 as [x_y r111 r112]; exists x_y.\n           exact r111.\n           apply U_ind'; exact r112.\n          exact r12.\n         exact r2.\n       destruct r as [x_y r1 r2]; exists x_y.\n        apply U_ind'; exact r1.\n        apply U_ind'; exact r2.\n  Qed.\nEnd scheme.\nDefinition sc_per_location := acyclic U.\nDefinition co := WW U.\nDefinition fr := RW U.\nDefinition mfence : relation events := (*failed: try fencerel MFENCE with 0*) 0.\nDefinition lfence : relation events := (*failed: try fencerel LFENCE with 0*) 0.\nDefinition sfence : relation events := (*failed: try fencerel SFENCE with 0*) 0.\nDefinition dmb_st : relation events := (*failed: try fencerel DMB.ST with 0*) 0.\nDefinition dsb_st : relation events := (*failed: try fencerel DSB.ST with 0*) 0.\nDefinition dmb : relation events := (*failed: try fencerel DMB with 0*) 0.\nDefinition dsb : relation events := (*failed: try fencerel DSB with 0*) 0.\nDefinition isb : relation events := (*failed: try fencerel ISB with 0*) 0.\nDefinition ctrlisb : relation events := (*failed: try ctrlcfence ISB with 0*) 0.\nDefinition sync : relation events := (*failed: try fencerel SYNC with 0*) 0.\nDefinition lwsync : relation events := (*failed: try fencerel LWSYNC with 0*) 0.\nDefinition eieio : relation events := (*failed: try fencerel EIEIO with 0*) 0.\nDefinition isync : relation events := (*failed: try fencerel ISYNC with 0*) 0.\nDefinition ctrlisync : relation events := (*failed: try ctrlcfence ISYNC with 0*) 0.\nDefinition DMB_ISH := (*failed: try DMB.ISH with emptyset_0*) emptyset_0.\nDefinition DMB_ISHLD := (*failed: try DMB.ISHLD with emptyset_0*) emptyset_0.\nDefinition DMB_ISHST := (*failed: try DMB.ISHST with emptyset_0*) emptyset_0.\nDefinition DSB_ISH := (*failed: try DSB.ISH with emptyset_0*) emptyset_0.\nDefinition DSB_ISHLD := (*failed: try DSB.ISHLD with emptyset_0*) emptyset_0.\nDefinition DSB_ISHST := (*failed: try DSB.ISHST with emptyset_0*) emptyset_0.\nDefinition DMB_SY := (*failed: try DMB.SY with emptyset_0*) emptyset_0.\nDefinition DMB_ST := (*failed: try DMB.ST with emptyset_0*) emptyset_0.\nDefinition DMB_LD := (*failed: try DMB.LD with emptyset_0*) emptyset_0.\nDefinition DSB_SY := (*failed: try DSB.SY with emptyset_0*) emptyset_0.\nDefinition DSB_ST := (*failed: try DSB.ST with emptyset_0*) emptyset_0.\nDefinition DSB_LD := (*failed: try DSB.LD with emptyset_0*) emptyset_0.\nDefinition DMB_OSH := (*failed: try DMB.OSH with emptyset_0*) emptyset_0.\nDefinition DSB_OSH := (*failed: try DSB.OSH with emptyset_0*) emptyset_0.\nDefinition DMB_OSHLD := (*failed: try DMB.OSHLD with emptyset_0*) emptyset_0.\nDefinition DSB_OSHLD := (*successful: try DSB.OSH with emptyset_0*) DSB_OSH.\nDefinition DMB_OSHST := (*failed: try DMB.OSHST with emptyset_0*) emptyset_0.\nDefinition DSB_OSHST := (*failed: try DSB.OSHST with emptyset_0*) emptyset_0.\nDefinition ISB := (*failed: try ISB with emptyset_0*) emptyset_0.\nDefinition A := (*failed: try A with emptyset_0*) emptyset_0.\nDefinition L := (*failed: try L with emptyset_0*) emptyset_0.\nDefinition Q := (*failed: try Q with emptyset_0*) emptyset_0.\nDefinition NoRet := (*failed: try NoRet with emptyset_0*) emptyset_0.\nDefinition dmb_ish := fencerel DMB_ISH.\nDefinition dmb_ishld := fencerel DMB_ISHLD.\nDefinition dmb_ishst := fencerel DMB_ISHST.\nDefinition dmb_fullsy := fencerel DMB_SY.\nDefinition dmb_fullst := fencerel DMB_ST.\nDefinition dmb_fullld := fencerel DMB_LD.\nDefinition dmb_sy := dmb_fullsy ⊔ dmb_ish.\nDefinition dmb_st_0 := dmb_fullst ⊔ dmb_ishst.\nDefinition dmb_ld := dmb_fullld ⊔ dmb_ishld.\nDefinition dsb_sy := fencerel DSB_SY.\nDefinition dsb_st_0 := fencerel DSB_ST.\nDefinition dsb_ld := fencerel DSB_LD.\nDefinition isb_0 := fencerel ISB.\nDefinition ctrlisb_0 := (*successful: try ctrlcfence ISB with 0*) ctrlcfence ISB.\nDefinition ctrlcfence_0 := ctrlisb_0 ⊔ ctrlisync.\nDefinition S0 := po ⊔ U.\nInductive S : relation _ := S_c : incl (S0 ⊔ (WW (Sloc ⋅ rf°) ⊓ !id ⊔ (RW (rf° ⋅ Sloc) ⊓ !id ⊔ S ⋅ S))) S\n     with Sloc : relation _ := Sloc_c : incl (S ⊓ loc) Sloc.\nSection scheme.\nVariables S' Sloc' : relation events.\nVariable HS' : incl (S0 ⊔ (WW (Sloc' ⋅ rf°) ⊓ !id ⊔ (RW (rf° ⋅ Sloc') ⊓ !id ⊔ S' ⋅ S'))) S'.\nVariable HSloc' : incl (S' ⊓ loc) Sloc'.\n\n  Fixpoint S_ind' x y (r : S x y) : S' x y\n      with Sloc_ind' x y (r : Sloc x y) : Sloc' x y.\n  Proof.\n    destruct r as [x y r]; apply HS'.\n    destruct r as [r | r]; [ left | right ].\n     exact r.\n     destruct r as [r | r]; [ left | right ].\n       destruct r as [r1 r2]; split.\n        destruct r1 as [r11 r12]; split.\n         destruct r11 as [x_y r111 r112]; exists x_y.\n          apply Sloc_ind'; exact r111.\n          exact r112.\n         exact r12.\n        exact r2.\n      destruct r as [r | r]; [ left | right ].\n        destruct r as [r1 r2]; split.\n         destruct r1 as [r11 r12]; split.\n          destruct r11 as [x_y r111 r112]; exists x_y.\n           exact r111.\n           apply Sloc_ind'; exact r112.\n          exact r12.\n         exact r2.\n       destruct r as [x_y r1 r2]; exists x_y.\n        apply S_ind'; exact r1.\n        apply S_ind'; exact r2.\n    destruct r as [x y r]; apply HSloc'.\n    destruct r as [r1 r2]; split.\n     apply S_ind'; exact r1.\n     exact r2.\n  Qed.\nEnd scheme.\nDefinition sc := acyclic S.\nDefinition co_0 := WW Sloc.\nDefinition fr_0 := RW Sloc.\nDefinition coe := co_0 ⊓ ext.\nDefinition fre := fr_0 ⊓ ext.\nDefinition atom := is_empty (rmw ⊓ fre ⋅ coe).\nDefinition witness_conditions := True.\nDefinition model_conditions := sc_per_location /\\ (sc /\\ atom).\nEnd Model.\n\nHint Unfold events R W IW FW B RMW F rf po int ext loc addr data ctrl amo rmw unknown_set unknown_relation M emptyset classes_loc tag2events emptyset_0 partition tag2instrs po_loc rfe rfi co0 toid fencerel ctrlcfence imply nodetour singlestep LKW WW RW U0 sc_per_location co fr mfence lfence sfence dmb_st dsb_st dmb dsb isb ctrlisb sync lwsync eieio isync ctrlisync DMB_ISH DMB_ISHLD DMB_ISHST DSB_ISH DSB_ISHLD DSB_ISHST DMB_SY DMB_ST DMB_LD DSB_SY DSB_ST DSB_LD DMB_OSH DSB_OSH DMB_OSHLD DSB_OSHLD DMB_OSHST DSB_OSHST ISB A L Q NoRet dmb_ish dmb_ishld dmb_ishst dmb_fullsy dmb_fullst dmb_fullld dmb_sy dmb_st_0 dmb_ld dsb_sy dsb_st_0 dsb_ld isb_0 ctrlisb_0 ctrlcfence_0 S0 sc co_0 fr_0 coe fre atom witness_conditions model_conditions : cat.\n\nDefinition valid (c : candidate) := model_conditions c.\n\n(* End of translation of model SC, no co generated *)\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/models/sccat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.23877999907513836}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n(* TABLE ACTIONS *)\n\n(*definit les actions elementaires sur les tables et leurs\nconsequences*)\n\nRequire Export DistributedReferenceCounting.machine0.machine.\n\nSection T_ACTION.\n\nDefinition Update_table (d0 : Date_table) (s0 : Site) \n  (new_date : nat) := change_site nat d0 s0 new_date.\n\nDefinition Set_rec_table (r0 : Rec_table) (s0 : Site) :=\n  change_site bool r0 s0 true.\n\nDefinition Reset_rec_table (r0 : Rec_table) (s0 : Site) :=\n  change_site bool r0 s0 false.\n                 \nDefinition Inc_send_table (t0 : Send_table) (s0 : Site) :=\n  change_site Z t0 s0 (t0 s0 + 1)%Z.  \n\nDefinition Dec_send_table (t0 : Send_table) (s0 : Site) :=\n  change_site Z t0 s0 (t0 s0 - 1)%Z.  \n\nEnd T_ACTION.\n\nSection DT_EFFECT.\n\nLemma update_here :\n forall (d0 : Date_table) (s0 : Site) (newdate : nat),\n Update_table d0 s0 newdate s0 = newdate.\nProof.\n intros; unfold Update_table in |- *; apply that_site.\nQed.\n\nLemma update_elsewhere :\n forall (d0 : Date_table) (s0 s1 : Site) (newdate : nat),\n s0 <> s1 -> Update_table d0 s0 newdate s1 = d0 s1.\nProof.\n intros; unfold Update_table in |- *; apply other_site; trivial.\nQed.\n\nEnd DT_EFFECT.\n\nSection ST_EFFECT.\n\nLemma S_inc_send_table :\n forall (t0 : Send_table) (s0 : Site),\n Inc_send_table t0 s0 s0 = (t0 s0 + 1)%Z.\nProof.\n intros; unfold Inc_send_table in |- *; apply that_site.\nQed.\n\nLemma no_inc_send_table :\n forall (t0 : Send_table) (s0 s1 : Site),\n s0 <> s1 -> Inc_send_table t0 s0 s1 = t0 s1.\nProof.\n intros; unfold Inc_send_table in |- *; apply other_site; auto.\nQed.\n\nLemma pred_dec_send_table :\n forall (t0 : Send_table) (s0 : Site),\n Dec_send_table t0 s0 s0 = (t0 s0 - 1)%Z.\nProof.\n intros; unfold Dec_send_table in |- *; apply that_site.\nQed.\n\nLemma no_dec_send_table :\n forall (t0 : Send_table) (s0 s1 : Site),\n s0 <> s1 -> Dec_send_table t0 s0 s1 = t0 s1.\nProof.\n intros; unfold Dec_send_table in |- *; apply other_site; auto.\nQed.\n\nEnd ST_EFFECT.\n\nSection RT_EFFECT.\n\nLemma true_set_rec_table :\n forall (r0 : Rec_table) (s0 : Site), Set_rec_table r0 s0 s0 = true.\nProof.\n intros; unfold Set_rec_table in |- *; apply that_site.\nQed.\n\nLemma S_set_rec_table :\n forall (r0 : Rec_table) (s0 : Site),\n r0 s0 = false -> Int (Set_rec_table r0 s0 s0) = (Int (r0 s0) + 1)%Z.\nProof.\n intros; rewrite true_set_rec_table; rewrite H; auto.\nQed.\n\nLemma inch_set_rec_table :\n forall (r0 : Rec_table) (s0 s1 : Site),\n s0 <> s1 -> Set_rec_table r0 s0 s1 = r0 s1.\nProof.\n intros; unfold Set_rec_table in |- *; apply other_site; trivial.\nQed.\n\nLemma no_set_rec_table :\n forall (r0 : Rec_table) (s0 s1 : Site),\n s0 <> s1 -> Int (Set_rec_table r0 s0 s1) = Int (r0 s1).\nProof.\n intros; rewrite inch_set_rec_table; trivial.\nQed.\n\nRemark false_reset_rec_table :\n forall (r0 : Rec_table) (s0 : Site), Reset_rec_table r0 s0 s0 = false.\nProof.\n intros; unfold Reset_rec_table in |- *; apply that_site.\nQed.\n\nLemma pred_reset_rec_table :\n forall (r0 : Rec_table) (s0 : Site),\n r0 s0 = true -> Int (Reset_rec_table r0 s0 s0) = (Int (r0 s0) - 1)%Z.\nProof.\n intros; rewrite false_reset_rec_table; rewrite H; auto.\nQed.\n\nLemma inch_reset_rec_table :\n forall (r0 : Rec_table) (s0 s1 : Site),\n s0 <> s1 -> Reset_rec_table r0 s0 s1 = r0 s1.\nProof.\n intros; unfold Reset_rec_table in |- *; apply other_site; auto.\nQed.\n\nLemma no_reset_rec_table :\n forall (r0 : Rec_table) (s0 s1 : Site),\n s0 <> s1 -> Int (Reset_rec_table r0 s0 s1) = Int (r0 s1).\nProof.\n intros; rewrite inch_reset_rec_table; trivial.\nQed.\n\nEnd RT_EFFECT.", "meta": {"author": "coq-contribs", "repo": "distributed-reference-counting", "sha": "6552f14cce0ea374c98adcbee0476ae268d64a7e", "save_path": "github-repos/coq/coq-contribs-distributed-reference-counting", "path": "github-repos/coq/coq-contribs-distributed-reference-counting/distributed-reference-counting-6552f14cce0ea374c98adcbee0476ae268d64a7e/machine0/table_act.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.2387215797528065}}
{"text": "Require Import Verdi.GhostSimulations.\n\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.CommitRecordedCommittedInterface.\nRequire Import VerdiRaft.StateMachineSafetyInterface.\nRequire Import VerdiRaft.StateMachineSafetyPrimeInterface.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.MaxIndexSanityInterface.\nRequire Import VerdiRaft.LeaderCompletenessInterface.\nRequire Import VerdiRaft.SortedInterface.\nRequire Import VerdiRaft.LogMatchingInterface.\nRequire Import VerdiRaft.PrevLogLeaderSublogInterface.\nRequire Import VerdiRaft.CurrentTermGtZeroInterface.\nRequire Import VerdiRaft.LastAppliedLeCommitIndexInterface.\nRequire Import VerdiRaft.MatchIndexAllEntriesInterface.\nRequire Import VerdiRaft.LeadersHaveLeaderLogsInterface.\nRequire Import VerdiRaft.LeaderSublogInterface.\nRequire Import VerdiRaft.TermsAndIndicesFromOneLogInterface.\nRequire Import VerdiRaft.GhostLogCorrectInterface.\nRequire Import VerdiRaft.GhostLogsLogPropertiesInterface.\nRequire Import VerdiRaft.GhostLogLogMatchingInterface.\nRequire Import VerdiRaft.TransitiveCommitInterface.\nRequire Import VerdiRaft.TermSanityInterface.\nRequire Import VerdiRaft.LeadersHaveLeaderLogsStrongInterface.\nRequire Import VerdiRaft.OneLeaderLogPerTermInterface.\n\nRequire Import VerdiRaft.RefinedLogMatchingLemmasInterface.\n\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\n\nRequire Import VerdiRaft.RaftMsgRefinementInterface.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nSection StateMachineSafetyProof.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n  Context {si : sorted_interface}.\n  Context {lmi : log_matching_interface}.\n  Context {smspi : state_machine_safety'interface}.\n  Context {rlmli : refined_log_matching_lemmas_interface}.\n  Context {pllsi : prevLog_leader_sublog_interface}.\n  Context {ctgt0 : current_term_gt_zero_interface}.\n  Context {lalcii : lastApplied_le_commitIndex_interface}.\n  Context {miaei : match_index_all_entries_interface}.\n  Context {lhlli : leaders_have_leaderLogs_interface}.\n  Context {lci : leader_completeness_interface}.\n  Context {lsi : leader_sublog_interface}.\n  Context {taifoli : terms_and_indices_from_one_log_interface}.\n  Context {glci : ghost_log_correct_interface}.\n  Context {lphogli : log_properties_hold_on_ghost_logs_interface}.\n  Context {glemi : ghost_log_entries_match_interface}.\n  Context {tci : transitive_commit_interface}.\n  Context {tsi : term_sanity_interface}.\n  \n  Context {lhllsi : leaders_have_leaderLogs_strong_interface}.\n  Context {ollpti : one_leaderLog_per_term_interface}.\n\n  Context {rmri : raft_msg_refinement_interface}.\n\n  Lemma exists_deghost_packet :\n    forall net p,\n      In p (nwPackets (deghost net)) ->\n      exists (q : packet (params := raft_refined_multi_params)),\n        In q (nwPackets net) /\\ p = deghost_packet q.\n  Proof using. \n    intros.\n    unfold deghost in *. simpl in *. do_in_map.\n    subst. eexists; eauto.\n  Qed.\n\n  Lemma state_machine_safety_deghost :\n    forall net,\n      commit_recorded_committed net ->\n      state_machine_safety' net ->\n      state_machine_safety (deghost net).\n  Proof using. \n    intros. unfold state_machine_safety in *. intuition.\n    - unfold state_machine_safety_host. intros.\n      do 2 eapply_prop_hyp commit_recorded_committed commit_recorded.\n      unfold state_machine_safety' in *. intuition. eauto.\n    - unfold state_machine_safety_nw. intros.\n      eapply_prop_hyp commit_recorded_committed commit_recorded.\n      unfold state_machine_safety', state_machine_safety_nw' in *. intuition.\n      find_apply_lem_hyp exists_deghost_packet. break_exists.\n      intuition. subst. simpl in *. repeat break_match. simpl in *.\n      subst. eapply_prop_hyp In In; repeat find_rewrite; simpl; eauto.\n  Qed.\n\n  Definition ghost_log_network : Type := @network _ raft_msg_refined_multi_params.\n  Definition ghost_log_packet : Type := @packet _ raft_msg_refined_multi_params.\n\n  Definition lifted_maxIndex_sanity (net : ghost_log_network) : Prop :=\n    (forall h,\n      lastApplied (snd (nwState net h)) <= maxIndex (log (snd (nwState net h)))) /\\\n    (forall h, commitIndex (snd (nwState net h)) <= maxIndex (log (snd (nwState net h)))).\n\n  Lemma lifted_maxIndex_sanity_init :\n    msg_refined_raft_net_invariant_init lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_init, lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition.\n  Qed.\n\n  Lemma handleClientRequest_lastApplied :\n    forall h st client id c out st' l,\n      handleClientRequest h st client id c = (out, st', l) ->\n      lastApplied st' = lastApplied st.\n  Proof using. \n    unfold handleClientRequest.\n    intros.\n    repeat break_match; find_inversion; auto.\n  Qed.\n\n  Lemma handleClientRequest_maxIndex :\n    forall h st client id c out st' l,\n      handleClientRequest h st client id c = (out, st', l) ->\n      sorted (log st') ->\n      maxIndex (log st) <= maxIndex (log st').\n  Proof using. \n    intros.\n    destruct (log st') using (handleClientRequest_log_ind ltac:(eauto)).\n    - auto.\n    - simpl in *. break_and.\n      destruct (log st); simpl in *.\n      + lia.\n      + find_insterU. conclude_using eauto. intuition.\n  Qed.\n\n  Lemma lifted_sorted_host :\n    forall net h,\n      refined_raft_intermediate_reachable net ->\n      sorted (log (snd (nwState net h))).\n  Proof using si rri. \n    intros.\n    pose proof (lift_prop _ logs_sorted_invariant).\n    find_insterU. conclude_using eauto.\n    unfold logs_sorted, logs_sorted_host in *. break_and.\n    unfold deghost in *. simpl in *. break_match. eauto.\n  Qed.\n\n  Lemma msg_lifted_sorted_host :\n    forall net h,\n      msg_refined_raft_intermediate_reachable net ->\n      sorted (log (snd (nwState net h))).\n  Proof using rmri si rri. \n    intros net0 ??.\n    rewrite <- msg_deghost_spec with (net := net0).\n    eapply msg_lift_prop.\n    - auto using lifted_sorted_host.\n    - auto.\n  Qed.\n  \n  Lemma lifted_sorted_network :\n    forall net p t n pli plt es ci,\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      sorted es.\n  Proof using rlmli. \n    intros. eapply entries_sorted_nw_invariant; eauto.\n  Qed.\n\n  Definition lifted_no_entries_past_current_term_host net :=\n    forall (h : name) e,\n      In e (log (snd (nwState net h))) ->\n      eTerm e <= currentTerm (snd (nwState net h)).\n\n  Lemma lifted_no_entries_past_current_term_host_invariant :\n    forall (net : @network _ raft_msg_refined_multi_params),\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_no_entries_past_current_term_host net.\n  Proof using rmri tsi. \n    intros.\n    enough (no_entries_past_current_term_host (deghost (mgv_deghost net))) by\n        (unfold no_entries_past_current_term_host, lifted_no_entries_past_current_term_host, deghost, mgv_deghost in *;\n         simpl in *;\n         repeat break_match; simpl in *; auto).\n    apply msg_lift_prop_all_the_way; eauto.\n    intros.\n    eapply no_entries_past_current_term_invariant; eauto.\n  Qed.\n\n  Lemma all_the_way_deghost_spec :\n    forall (net : ghost_log_network) h,\n      snd (nwState net h) = nwState (deghost (mgv_deghost net)) h.\n  Proof using rmri rri. \n    intros net0 ?.\n    rewrite deghost_spec.\n    rewrite msg_deghost_spec with (net := net0).\n    auto.\n  Qed.\n\n  Lemma all_the_way_simulation_1 :\n    forall (net : ghost_log_network),\n      msg_refined_raft_intermediate_reachable net ->\n      raft_intermediate_reachable (deghost (mgv_deghost net)).\n  Proof using rmri rri. \n    auto using simulation_1, msg_simulation_1.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_client_request :\n    msg_refined_raft_net_invariant_client_request lifted_maxIndex_sanity.\n  Proof using rmri si rri. \n    unfold msg_refined_raft_net_invariant_client_request, lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    simpl. intros.\n    find_copy_apply_lem_hyp handleClientRequest_maxIndex.\n    - intuition; simpl in *; repeat find_higher_order_rewrite; update_destruct_simplify; auto.\n      + erewrite handleClientRequest_lastApplied by eauto. eauto using Nat.le_trans.\n      + erewrite handleClientRequest_commitIndex by eauto. eauto using Nat.le_trans.\n    - match goal with H : _ |- _ => rewrite all_the_way_deghost_spec with (net := net) in H end.\n        eapply handleClientRequest_logs_sorted; eauto.\n        * auto using all_the_way_simulation_1.\n        * apply logs_sorted_invariant. auto using all_the_way_simulation_1.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_timeout :\n    msg_refined_raft_net_invariant_timeout lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_timeout, lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; simpl in *; repeat find_higher_order_rewrite; update_destruct_simplify; auto;\n    erewrite handleTimeout_log_same by eauto.\n    - erewrite handleTimeout_lastApplied; eauto.\n    - erewrite handleTimeout_commitIndex; eauto.\n  Qed.\n\n  Lemma handleAppendEntries_lastApplied :\n    forall h st t n pli plt es ci st' m,\n      handleAppendEntries h st t n pli plt es ci = (st', m) ->\n      lastApplied st' = lastApplied st.\n  Proof using. \n    unfold handleAppendEntries, advanceCurrentTerm;\n    intros; repeat break_match; repeat find_inversion; simpl; auto.\n  Qed.\n\n  Lemma sorted_maxIndex_app :\n    forall l1 l2,\n      sorted (l1 ++ l2) ->\n      maxIndex l2 <= maxIndex (l1 ++ l2).\n  Proof using. \n    induction l1; intros; simpl in *; intuition.\n    destruct l2; intuition. simpl in *.\n    specialize (H0 e). conclude H0 intuition. intuition.\n  Qed.\n\n  Lemma max_min_thing:\n    forall a b c,\n      a <= c ->\n      max a (min b c) <= c.\n  Proof using. \n    intros.\n    destruct (max a (min b c)) using (Nat.max_case _ _); intuition.\n  Qed.\n\n  Lemma in_ghost_packet :\n    forall (net : network (params := raft_refined_multi_params)) p,\n      In p (nwPackets net) ->\n      In (deghost_packet p) (nwPackets (deghost net)).\n  Proof using. \n    unfold deghost.\n    simpl. intuition.\n    apply in_map_iff.\n    eexists; eauto.\n  Qed.\n\n  Lemma in_mgv_ghost_packet :\n    forall (net : ghost_log_network) p,\n      In p (nwPackets net) ->\n      In (mgv_deghost_packet p) (nwPackets (mgv_deghost net)).\n  Proof using. \n    unfold mgv_deghost.\n    simpl. intuition.\n    apply in_map_iff.\n    eexists; eauto.\n  Qed.\n\n  Lemma pBody_deghost_packet :\n    forall (p : packet (params := raft_refined_multi_params)),\n      pBody (deghost_packet p) = pBody p.\n  Proof using. \n    unfold deghost_packet.\n    simpl. auto.\n  Qed.\n\n  Lemma pDst_deghost_packet :\n    forall (p : packet (params := raft_refined_multi_params)),\n      pDst (deghost_packet p) = pDst p.\n  Proof using. \n    unfold deghost_packet.\n    simpl. auto.\n  Qed.\n\n  Lemma pDst_mgv_deghost_packet :\n    forall (p : ghost_log_packet),\n      pDst (mgv_deghost_packet p) = pDst p.\n  Proof using. \n    unfold mgv_deghost_packet.\n    simpl. auto.\n  Qed.\n\n  Lemma pBody_mgv_deghost_packet :\n    forall (p : ghost_log_packet),\n      pBody (mgv_deghost_packet p) = snd (pBody p).\n  Proof using. \n    unfold mgv_deghost_packet.\n    simpl. auto.\n  Qed.\n\n  Lemma lifted_handleAppendEntries_logs_sorted :\n    forall (net : ghost_log_network) (p : ghost_log_packet) t n pli plt es ci st' m,\n      msg_refined_raft_intermediate_reachable net ->\n      handleAppendEntries (pDst p) (snd (nwState net (pDst p))) t n pli plt es ci = (st', m) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      In p (nwPackets net) ->\n      sorted (log st').\n  Proof using rmri si rri. \n    intros.\n    eapply (handleAppendEntries_logs_sorted _ (deghost_packet (mgv_deghost_packet p))).\n    - eauto using all_the_way_simulation_1.\n    - apply lift_prop.\n      + apply logs_sorted_invariant.\n      + auto using msg_simulation_1.\n    - rewrite <- all_the_way_deghost_spec.\n      rewrite pDst_deghost_packet.\n      rewrite pDst_mgv_deghost_packet.\n      eauto.\n    - rewrite pBody_deghost_packet.\n      rewrite pBody_mgv_deghost_packet.\n      auto.\n    - apply in_ghost_packet. apply in_mgv_ghost_packet. auto.\n  Qed.\n\n  Lemma contiguous_range_exact_lo_elim_exists :\n    forall es lo i,\n      contiguous_range_exact_lo es lo ->\n      lo < i <= maxIndex es -> exists e, eIndex e = i /\\ In e es.\n  Proof using. \n    unfold contiguous_range_exact_lo.\n    intuition.\n  Qed.\n\n  Lemma contiguous_range_exact_lo_elim_lt :\n    forall es lo e,\n      contiguous_range_exact_lo es lo ->\n      In e es ->\n      lo < eIndex e.\n  Proof using. \n    unfold contiguous_range_exact_lo.\n    intuition.\n  Qed.\n\n  Lemma lifted_sms_nw :\n    forall (net : network (params := raft_refined_multi_params)) h p t leaderId prevLogIndex prevLogTerm entries leaderCommit e,\n      state_machine_safety (deghost net) ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm\n                              entries leaderCommit ->\n      t >= currentTerm (snd (nwState net h)) ->\n      commit_recorded (deghost net) h e ->\n      (prevLogIndex > eIndex e \\/\n       (prevLogIndex = eIndex e /\\ prevLogTerm = eTerm e) \\/\n       eIndex e > maxIndex entries \\/\n       In e entries).\n  Proof using rri. \n    unfold state_machine_safety, state_machine_safety_nw.\n    intuition.\n    match goal with\n      | [ H : _ |- _ ] => eapply H with (p := deghost_packet p)\n    end.\n    - auto using in_ghost_packet.\n    - rewrite pBody_deghost_packet. eauto.\n    - rewrite deghost_spec. eauto.\n    - auto.\n  Qed.\n\n\n  Lemma msg_lifted_sms_nw :\n    forall (net : ghost_log_network) h p t leaderId prevLogIndex prevLogTerm entries leaderCommit e,\n      state_machine_safety (deghost (mgv_deghost net)) ->\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t leaderId prevLogIndex prevLogTerm\n                                    entries leaderCommit ->\n      t >= currentTerm (snd (nwState net h)) ->\n      commit_recorded (deghost (mgv_deghost net)) h e ->\n      (prevLogIndex > eIndex e \\/\n       (prevLogIndex = eIndex e /\\ prevLogTerm = eTerm e) \\/\n       eIndex e > maxIndex entries \\/\n       In e entries).\n  Proof using rmri rri. \n    intros net0;intros.\n    eapply lifted_sms_nw.\n    - eauto.\n    - eauto using in_mgv_ghost_packet.\n    - rewrite pBody_mgv_deghost_packet. eauto.\n    - rewrite msg_deghost_spec with (net := net0). eauto.\n    - auto.\n  Qed.\n\n  Lemma commit_recorded_lift_intro :\n    forall (net : network (params := raft_refined_multi_params)) h e,\n      In e (log (snd (nwState net h))) ->\n      (eIndex e <= lastApplied (snd (nwState net h)) \\/\n       eIndex e <= commitIndex (snd (nwState net h))) ->\n      commit_recorded (deghost net) h e.\n  Proof using rri. \n    unfold commit_recorded.\n    intros.\n    rewrite deghost_spec.\n    auto.\n  Qed.\n\n  Lemma msg_commit_recorded_lift_intro :\n    forall (net : ghost_log_network) h e,\n      In e (log (snd (nwState net h))) ->\n      (eIndex e <= lastApplied (snd (nwState net h)) \\/\n       eIndex e <= commitIndex (snd (nwState net h))) ->\n      commit_recorded (deghost (mgv_deghost net)) h e.\n  Proof using rmri rri. \n    unfold commit_recorded.\n    intros net0;intros.\n    rewrite deghost_spec.\n    rewrite msg_deghost_spec with (net := net0).\n    auto.\n  Qed.\n\n  Definition lifted_entries_contiguous (net : ghost_log_network) : Prop :=\n    forall h, contiguous_range_exact_lo (log (snd (nwState net h))) 0.\n\n  Lemma lifted_entries_contiguous_invariant :\n    forall net, msg_refined_raft_intermediate_reachable net ->\n           lifted_entries_contiguous net.\n  Proof using rmri rlmli. \n    unfold lifted_entries_contiguous.\n    intros.\n    pose proof (msg_lift_prop _ entries_contiguous_invariant _ ltac:(eauto) h).\n    find_rewrite_lem msg_deghost_spec.\n    auto.\n  Qed.\n\n  Definition lifted_entries_contiguous_nw (net : ghost_log_network) : Prop :=\n    forall p t n pli plt es ci,\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      contiguous_range_exact_lo es pli.\n\n  Lemma lifted_entries_contiguous_nw_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_entries_contiguous_nw net.\n  Proof using rmri rlmli. \n    unfold lifted_entries_contiguous_nw.\n    intros.\n    pose proof msg_lift_prop _ entries_contiguous_nw_invariant _ ltac:(eauto) (mgv_deghost_packet p).\n    match goal with\n    | [ H : context [In] |- _ ] => eapply H\n    end.\n    - auto using in_mgv_ghost_packet.\n    - rewrite pBody_mgv_deghost_packet. eauto.\n  Qed.\n\n  Definition lifted_entries_gt_0 (net : ghost_log_network) : Prop :=\n    forall h e,\n      In e (log (snd (nwState net h))) -> eIndex e > 0.\n\n  Lemma lifted_entries_gt_0_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_entries_gt_0 net.\n  Proof using rmri rlmli. \n    unfold lifted_entries_gt_0.\n    intros.\n    pose proof msg_lift_prop _ entries_gt_0_invariant _ ltac:(eauto).\n    unfold entries_gt_0 in *.\n    match goal with\n    | [ H : _ |- _ ] => eapply H; eauto\n    end.\n    rewrite msg_deghost_spec.\n    eauto.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_append_entries :\n    forall xs (p : ghost_log_packet) ys (net : ghost_log_network) st' ps' gd d m t n pli plt es ci,\n      handleAppendEntries (pDst p) (snd (nwState net (pDst p))) t n pli plt es ci = (d, m) ->\n      gd = update_elections_data_appendEntries (pDst p) (nwState net (pDst p)) t n pli plt es ci ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      lifted_maxIndex_sanity net ->\n      state_machine_safety (deghost (mgv_deghost net)) ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update name_eq_dec (nwState net) (pDst p) (gd, d) h) ->\n      (forall (p' : ghost_log_packet), In p' ps' -> In p' (xs ++ ys) \\/\n                         mgv_deghost_packet p' = mkPacket (params := raft_refined_multi_params)\n                                                          (pDst p) (pSrc p) m) ->\n      lifted_maxIndex_sanity (mkNetwork ps' st').\n  Proof using rmri rlmli si rri. \n    unfold lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intros.\n    intuition; simpl in *; repeat find_higher_order_rewrite; update_destruct_simplify; auto.\n    - erewrite handleAppendEntries_lastApplied by eauto.\n      assert (sorted (log d)) by (eauto using lifted_handleAppendEntries_logs_sorted).\n      match goal with\n        | _ : handleAppendEntries ?h ?s ?t ?n ?pli ?plt ?es ?ci = (?s', ?m) |- _ =>\n          pose proof handleAppendEntries_log_detailed\n               h s t n pli plt es ci s' m\n      end.\n      intuition; repeat find_rewrite.\n      + eauto.\n      + subst.\n        destruct (le_lt_dec (lastApplied (snd (nwState net (pDst p))))\n                            (maxIndex (log d))); auto.\n        exfalso.\n        assert (In p (nwPackets net)) by (find_rewrite; intuition).\n        assert (exists x, eIndex x = maxIndex (log d) /\\ In x (log (snd (nwState net (pDst p))))).\n        {\n          eapply contiguous_range_exact_lo_elim_exists.\n          - eapply lifted_entries_contiguous_invariant. auto.\n          - split.\n            + find_apply_lem_hyp maxIndex_non_empty. break_exists.  break_and.\n              repeat find_rewrite.\n              eapply contiguous_range_exact_lo_elim_lt.\n              * eapply lifted_entries_contiguous_nw_invariant; eauto.\n              * auto.\n            + eapply Nat.le_trans; [|eauto]. simpl in *. lia.\n        }\n        break_exists. break_and.\n        eapply findAtIndex_None; [|eauto| |]; eauto.\n        apply msg_lifted_sorted_host; auto.\n      + subst.\n        destruct (le_lt_dec (lastApplied (snd (nwState net (pDst p))))\n                            (maxIndex (log d))); auto.\n        exfalso.\n        assert (In p (nwPackets net)) by (find_rewrite; intuition).\n        break_exists; intuition. find_apply_lem_hyp findAtIndex_elim; intuition.\n\n        find_eapply_lem_hyp msg_lifted_sms_nw; eauto;\n        [|eapply msg_commit_recorded_lift_intro; eauto;\n        left; repeat find_rewrite; auto using Nat.lt_le_incl].\n        intuition.\n        * subst.\n          assert (0 < eIndex x) by (eapply lifted_entries_contiguous_invariant; eauto).\n          lia.\n        * destruct (log d); intuition. simpl in *.\n          intuition; subst; auto.\n          find_apply_hyp_hyp. lia.\n      + destruct (le_lt_dec (lastApplied (snd (nwState net (pDst p)))) pli); intuition;\n        [eapply Nat.le_trans; [| apply sorted_maxIndex_app]; auto;\n         break_exists; break_and;\n         erewrite maxIndex_removeAfterIndex by (eauto; apply msg_lifted_sorted_host; auto);\n         auto|]; [idtac].\n\n        destruct (le_lt_dec (lastApplied (snd (nwState net (pDst p)))) (maxIndex es)); intuition;\n        [match goal with\n           | |- context [ maxIndex (?ll1 ++ ?ll2) ] =>\n             pose proof maxIndex_app ll1 ll2\n         end; simpl in *; intuition|]; [idtac].\n        assert (exists x, eIndex x = maxIndex es /\\ In x (log (snd (nwState net (pDst p))))).\n        {\n          eapply contiguous_range_exact_lo_elim_exists.\n          - eapply lifted_entries_contiguous_invariant. auto.\n          - split.\n            + find_apply_lem_hyp maxIndex_non_empty. break_exists.  break_and.\n              repeat find_rewrite.\n              destruct es.\n              * simpl in *. intuition.\n              * simpl.  subst.\n                { eapply Nat.le_lt_trans with (m := eIndex x).\n                  - lia.\n                  - eapply contiguous_range_exact_lo_elim_lt.\n                    + eapply lifted_entries_contiguous_nw_invariant; eauto.\n                    + intuition.\n                }\n            + eapply Nat.le_trans; [|eauto]. simpl in *. lia.\n        }\n        break_exists. intuition.\n        match goal with\n          | H : findAtIndex _ _ = None |- _ =>\n            eapply @findAtIndex_None with (x := x) in H\n        end; eauto.\n        * congruence.\n        * apply msg_lifted_sorted_host. auto.\n      +   destruct (le_lt_dec (lastApplied (snd (nwState net (pDst p)))) (maxIndex es)); intuition;\n        [match goal with\n           | |- context [ maxIndex (?ll1 ++ ?ll2) ] =>\n             pose proof maxIndex_app ll1 ll2\n         end; simpl in *; intuition|]; [idtac].\n        exfalso.\n        assert (In p (nwPackets net)) by (find_rewrite; intuition).\n        break_exists; intuition. find_apply_lem_hyp findAtIndex_elim; intuition.\n        find_copy_apply_lem_hyp maxIndex_non_empty.\n        break_exists. intuition.\n\n        find_eapply_lem_hyp msg_lifted_sms_nw; eauto;\n        [|eapply msg_commit_recorded_lift_intro; eauto;\n        left; repeat find_rewrite; auto using Nat.lt_le_incl].\n\n        match goal with\n          | _ : In ?x es, _ : maxIndex es = eIndex ?x |- _ =>\n            assert (pli < eIndex x)\n                   by ( eapply contiguous_range_exact_lo_elim_lt; eauto;\n                        eapply lifted_entries_contiguous_nw_invariant; eauto)\n        end.\n        intuition.\n\n        match goal with\n          | H : _ = _ ++ _ |- _ => symmetry in H\n        end.\n        destruct es; intuition;\n        simpl in *;\n        intuition; subst_max; intuition;\n        repeat clean;\n        match goal with\n          | _ : eIndex ?x' = eIndex ?x, H : context [eIndex ?x'] |- _ =>\n            specialize (H x); conclude H ltac:(apply in_app_iff; auto)\n          end; intuition.\n    - assert (sorted (log d)) by (eauto using lifted_handleAppendEntries_logs_sorted).\n      match goal with\n        | _ : handleAppendEntries ?h ?s ?t ?n ?pli ?plt ?es ?ci = (?s', ?m) |- _ =>\n          pose proof handleAppendEntries_log_detailed\n               h s t n pli plt es ci s' m\n      end.\n      intuition; repeat find_rewrite; try apply max_min_thing;\n      match goal with\n        | H : context [ lastApplied _ ] |- _ => clear H\n      end.\n      + eauto.\n      + subst.\n        destruct (le_lt_dec (commitIndex (snd (nwState net (pDst p))))\n                            (maxIndex (log d))); auto.\n        exfalso.\n        assert (In p (nwPackets net)) by (find_rewrite; intuition).\n        assert (exists x, eIndex x = maxIndex (log d) /\\ In x (log (snd (nwState net (pDst p))))).\n        {\n          eapply contiguous_range_exact_lo_elim_exists.\n          - eapply lifted_entries_contiguous_invariant. auto.\n          - split.\n            + find_apply_lem_hyp maxIndex_non_empty. break_exists.  break_and.\n              repeat find_rewrite.\n              eapply contiguous_range_exact_lo_elim_lt.\n              * eapply lifted_entries_contiguous_nw_invariant; eauto.\n              * auto.\n            + eapply Nat.le_trans; [|eauto]. simpl in *. lia.\n        }\n        break_exists. intuition.\n        find_eapply_lem_hyp findAtIndex_None; eauto.\n        apply msg_lifted_sorted_host. auto.\n      + subst.\n        destruct (le_lt_dec (commitIndex (snd (nwState net (pDst p))))\n                            (maxIndex (log d))); auto.\n        exfalso.\n        assert (In p (nwPackets net)) by (find_rewrite; intuition).\n        break_exists; intuition. find_apply_lem_hyp findAtIndex_elim; intuition.\n\n        find_eapply_lem_hyp msg_lifted_sms_nw; eauto;\n        [|eapply msg_commit_recorded_lift_intro; eauto;\n        right; repeat find_rewrite; intuition].\n        intuition.\n        * subst.\n          assert (0 < eIndex x) by (eapply lifted_entries_contiguous_invariant; eauto).\n          lia.\n        * destruct (log d); intuition. simpl in *.\n          intuition; subst; auto.\n          find_apply_hyp_hyp. lia.\n      + destruct (le_lt_dec (commitIndex (snd (nwState net (pDst p)))) pli); intuition;\n        [eapply Nat.le_trans; [| apply sorted_maxIndex_app]; auto;\n         break_exists; intuition;\n         erewrite maxIndex_removeAfterIndex; eauto; apply msg_lifted_sorted_host; auto|]; [idtac].\n        destruct (le_lt_dec (commitIndex (snd (nwState net (pDst p)))) (maxIndex es)); intuition;\n        [match goal with\n           | |- context [ maxIndex (?ll1 ++ ?ll2) ] =>\n             pose proof maxIndex_app ll1 ll2\n         end; simpl in *; intuition|]; [idtac].\n        assert (exists x, eIndex x = maxIndex es /\\ In x (log (snd (nwState net (pDst p))))).\n        {\n          eapply contiguous_range_exact_lo_elim_exists.\n          - eapply lifted_entries_contiguous_invariant. auto.\n          - split.\n            + find_apply_lem_hyp maxIndex_non_empty. break_exists.  break_and.\n              repeat find_rewrite.\n              destruct es.\n              * simpl in *. intuition.\n              * simpl.  subst.\n                { eapply Nat.le_lt_trans with (m := eIndex x).\n                  - lia.\n                  - eapply contiguous_range_exact_lo_elim_lt.\n                    + eapply lifted_entries_contiguous_nw_invariant; eauto.\n                    + intuition.\n                }\n            + eapply Nat.le_trans; [|eauto]. simpl in *. lia.\n        }\n        break_exists. intuition.\n        match goal with\n          | H : findAtIndex _ _ = None |- _ =>\n            eapply @findAtIndex_None with (x := x) in H\n        end; eauto.\n        * congruence.\n        * apply msg_lifted_sorted_host; auto.\n      + destruct (le_lt_dec (commitIndex (snd (nwState net (pDst p)))) (maxIndex es)); intuition;\n        [match goal with\n           | |- context [ maxIndex (?ll1 ++ ?ll2) ] =>\n             pose proof maxIndex_app ll1 ll2\n         end; simpl in *; intuition|]; [idtac].\n        exfalso.\n        assert (In p (nwPackets net)) by (find_rewrite; intuition).\n        break_exists; intuition. find_apply_lem_hyp findAtIndex_elim; intuition.\n        find_copy_apply_lem_hyp maxIndex_non_empty.\n        break_exists. intuition.\n\n        find_eapply_lem_hyp msg_lifted_sms_nw; eauto;\n        [|eapply msg_commit_recorded_lift_intro; eauto;\n        right; repeat find_rewrite; intuition].\n        match goal with\n          | _ : In ?x es, _ : maxIndex es = eIndex ?x |- _ =>\n            assert (pli < eIndex x)\n              by (eapply contiguous_range_exact_lo_elim_lt; eauto;\n                        eapply lifted_entries_contiguous_nw_invariant; eauto)\n        end.\n\n        intuition.\n        * match goal with\n            | H : _ = _ ++ _ |- _ => symmetry in H\n          end.\n          destruct es; intuition;\n          simpl in *;\n          intuition; subst_max; intuition;\n          repeat clean;\n          match goal with\n            | _ : eIndex ?x' = eIndex ?x, H : context [eIndex ?x'] |- _ =>\n              specialize (H x); conclude H ltac:(apply in_app_iff; auto)\n          end; intuition.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_append_entries_reply :\n    msg_refined_raft_net_invariant_append_entries_reply lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_append_entries_reply,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; repeat find_higher_order_rewrite; update_destruct_simplify; auto.\n    - erewrite handleAppendEntriesReply_same_lastApplied by eauto.\n      erewrite handleAppendEntriesReply_same_log by eauto.\n      auto.\n    - erewrite handleAppendEntriesReply_same_commitIndex by eauto.\n      erewrite handleAppendEntriesReply_same_log by eauto.\n      auto.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_request_vote :\n    msg_refined_raft_net_invariant_request_vote lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_request_vote,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; repeat find_higher_order_rewrite; update_destruct_simplify; auto.\n    - erewrite handleRequestVote_same_log by eauto.\n      erewrite handleRequestVote_same_lastApplied by eauto.\n      auto.\n    - erewrite handleRequestVote_same_log by eauto.\n      erewrite handleRequestVote_same_commitIndex by eauto.\n      auto.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_request_vote_reply :\n    msg_refined_raft_net_invariant_request_vote_reply lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_request_vote_reply,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; repeat find_higher_order_rewrite; update_destruct_simplify; auto.\n    - rewrite handleRequestVoteReply_same_log.\n      rewrite handleRequestVoteReply_same_lastApplied.\n      auto.\n    - rewrite handleRequestVoteReply_same_log.\n      rewrite handleRequestVoteReply_same_commitIndex.\n      auto.\n  Qed.\n\n  Lemma doLeader_same_lastApplied :\n    forall st n os st' ms,\n      doLeader st n = (os, st', ms) ->\n      lastApplied st' = lastApplied st.\n  Proof using. \n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma fold_left_maximum_le' :\n    forall l x y,\n      x <= y ->\n      x <= fold_left max l y.\n  Proof using. \n    induction l; intros.\n    - auto.\n    - simpl. apply IHl. apply Nat.max_case_strong; lia.\n  Qed.\n\n  Lemma fold_left_maximum_le :\n    forall l x,\n      x <= fold_left max l x.\n  Proof using. \n    intros. apply fold_left_maximum_le'.\n    auto.\n  Qed.\n\n  Lemma fold_left_maxmimum_increase_init :\n    forall l x y,\n      fold_left max l x = x ->\n      x <= y ->\n      fold_left max l y = y.\n  Proof using. \n    induction l; intros.\n    - auto.\n    - simpl in *. revert H.\n      repeat (apply Nat.max_case_strong; intros).\n      + eauto.\n      + assert (a = y) by lia. subst_max. eauto.\n      + subst x. pose proof (fold_left_maximum_le l a).\n        assert (fold_left max l a = a) by lia.\n        eauto.\n      + subst x.\n        pose proof (fold_left_maximum_le l a).\n        assert (fold_left max l a = a) by lia.\n        assert (a = y) by lia.\n        subst. auto.\n  Qed.\n\n  Lemma fold_left_maximum_cases :\n    forall l x,\n      fold_left max l x = x \\/\n      exists y,\n        In y l /\\ fold_left max l x = y.\n  Proof using. \n    induction l; simpl.\n    - auto.\n    - intros.\n      specialize (IHl (max x a)).\n      intuition.\n      + revert H.\n        apply Nat.max_case_strong; intuition.\n        intuition eauto using fold_left_maxmimum_increase_init.\n      + break_exists. break_and. eauto.\n  Qed.\n\n  Lemma fold_left_maximum_ind :\n    forall l x (P : nat -> Prop),\n      P x ->\n      (forall y, In y l -> P y) ->\n      P (fold_left max l x).\n  Proof using. \n    intros.\n    destruct (fold_left_maximum_cases l x).\n    - find_rewrite. auto.\n    - break_exists. break_and. find_rewrite. eauto.\n  Qed.\n\n  Lemma doLeader_same_commitIndex :\n    forall st n os st' ms,\n      doLeader st n = (os, st', ms) ->\n      sorted (log st) ->\n      commitIndex st <= maxIndex (log st) ->\n      commitIndex st' <= maxIndex (log st').\n  Proof using. \n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; simpl; auto;\n    apply fold_left_maximum_ind; auto.\n    - intros. do_in_map. find_apply_lem_hyp filter_In.\n      subst. break_and.\n      apply maxIndex_is_max; eauto using findGtIndex_in.\n    - intros. do_in_map. find_apply_lem_hyp filter_In.\n      break_and. subst.\n      apply maxIndex_is_max; eauto using findGtIndex_in.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_do_leader :\n    msg_refined_raft_net_invariant_do_leader lifted_maxIndex_sanity.\n  Proof using rmri si rri. \n    unfold msg_refined_raft_net_invariant_do_leader,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; repeat find_higher_order_rewrite; update_destruct_simplify; auto.\n    - erewrite doLeader_same_log by eauto.\n      erewrite doLeader_same_lastApplied by eauto.\n      repeat match goal with\n        | [ H : forall _ , _ |- _ ] => specialize (H h0)\n      end.\n      unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n      simpl in *.\n      repeat find_rewrite. auto.\n    - repeat match goal with\n                 | [ H : forall _ , _ |- _ ] => specialize (H h0)\n               end.\n      unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n      simpl in *.\n      repeat find_rewrite. simpl in *.\n      erewrite doLeader_same_commitIndex; eauto.\n      find_eapply_lem_hyp (msg_lifted_sorted_host net h0).\n      unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n      simpl in *.\n      find_rewrite. auto.\n  Qed.\n\n  Lemma doGenericServer_lastApplied :\n    forall h st out st' ms,\n      doGenericServer h st = (out, st', ms) ->\n      lastApplied st' = lastApplied st \\/\n      (lastApplied st < commitIndex st  /\\\n       lastApplied st' = commitIndex st).\n  Proof using. \n    unfold doGenericServer.\n    intros.\n    repeat break_match; repeat find_inversion; simpl.\n    - do_bool.\n      revert Heqb.\n      eapply applyEntries_spec_ind; eauto.\n    - do_bool.\n      revert Heqb.\n      eapply applyEntries_spec_ind; eauto.\n  Qed.\n\n\n  Lemma lifted_maxIndex_sanity_do_generic_server :\n    msg_refined_raft_net_invariant_do_generic_server lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_do_generic_server,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; find_higher_order_rewrite; update_destruct_simplify; auto;\n    erewrite doGenericServer_log by eauto.\n    - repeat match goal with\n               | [ H : forall _ , _ |- _ ] => specialize (H h0)\n             end.\n      repeat find_rewrite. simpl in *.\n      find_apply_lem_hyp doGenericServer_lastApplied.\n      unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n      simpl in *.\n      intuition; repeat find_rewrite; auto.\n    - repeat match goal with\n               | [ H : forall _ , _ |- _ ] => specialize (H h0)\n             end.\n      unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n      simpl in *.\n      repeat find_rewrite. simpl in *.\n      erewrite doGenericServer_commitIndex by eauto.\n      auto.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_state_same_packet_subset :\n    msg_refined_raft_net_invariant_state_same_packet_subset lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_state_same_packet_subset,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; find_reverse_higher_order_rewrite; auto.\n  Qed.\n\n  Lemma lifted_maxIndex_sanity_reboot :\n    msg_refined_raft_net_invariant_reboot lifted_maxIndex_sanity.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_reboot,\n           lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    unfold reboot.\n    intuition; find_higher_order_rewrite; update_destruct_simplify; auto with *;\n    repeat match goal with\n             | [ H : forall _ , _ |- _ ] => specialize (H h0)\n           end;\n    unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *;\n    simpl in *;\n    repeat find_rewrite; simpl in *;\n    auto.\n  Qed.\n\n  Definition lifted_directly_committed (net : ghost_log_network) (e : entry) : Prop :=\n    exists quorum,\n      NoDup quorum /\\\n      length quorum > div2 (length nodes) /\\\n      (forall h, In h quorum -> In (eTerm e, e) (allEntries (fst (nwState net h)))).\n\n  Definition lifted_committed (net : ghost_log_network) (e : entry) (t : term) : Prop :=\n    exists h e',\n      eTerm e' <= t /\\\n      lifted_directly_committed net e' /\\\n      eIndex e <= eIndex e' /\\\n      In e (log (snd (nwState net h))) /\\ In e' (log (snd (nwState net h))).\n\n  Definition commit_invariant_host (net : ghost_log_network) : Prop :=\n    forall h e,\n      In e (log (snd (nwState net h))) ->\n      eIndex e <= commitIndex (snd (nwState net h)) ->\n      lifted_committed net e (currentTerm (snd (nwState net h))).\n\n  Definition commit_invariant_nw (net : ghost_log_network) : Prop :=\n    forall p t lid pli plt es lci e,\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t lid pli plt es lci ->\n      In e (fst (pBody p)) ->\n      eIndex e <= lci ->\n      lifted_committed net e t.\n\n  Definition commit_invariant (net : ghost_log_network) : Prop :=\n    commit_invariant_host net /\\\n    commit_invariant_nw net.\n\n  Lemma commit_invariant_init :\n    msg_refined_raft_net_invariant_init commit_invariant.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_init, commit_invariant.\n    split.\n    - unfold commit_invariant_host, commit_recorded_committed, commit_recorded, committed. simpl.\n      intuition.\n    - unfold commit_invariant_nw; simpl; intuition.\n  Qed.\n\n  Lemma msg_lifted_lastApplied_le_commitIndex :\n    forall net h,\n      msg_refined_raft_intermediate_reachable net ->\n      lastApplied (snd (nwState net h)) <= commitIndex (snd (nwState net h)).\n  Proof using rmri lalcii rri. \n    intros.\n    pose proof (lift_prop _ (lastApplied_le_commitIndex_invariant)).\n    find_apply_lem_hyp msg_simulation_1.\n    find_apply_hyp_hyp.\n    unfold lastApplied_le_commitIndex in *.\n    match goal with\n    | [ H : _ |- _ ] => specialize (H h)\n    end.\n    find_rewrite_lem deghost_spec.\n    find_rewrite_lem msg_deghost_spec.\n    auto.\n  Qed.\n\n  Lemma lifted_directly_committed_directly_committed :\n    forall net e,\n      lifted_directly_committed net e ->\n      directly_committed (mgv_deghost net) e.\n  Proof using rmri. \n    unfold lifted_directly_committed, directly_committed.\n    intuition.\n    break_exists_exists.\n    intuition.\n    rewrite msg_deghost_spec. auto.\n  Qed.\n\n  Lemma directly_committed_lifted_directly_committed :\n    forall net e,\n      directly_committed (mgv_deghost net) e ->\n      lifted_directly_committed net e.\n  Proof using rmri. \n    unfold lifted_directly_committed, directly_committed.\n    intuition.\n    break_exists_exists.\n    intuition.\n    find_apply_hyp_hyp.\n    find_rewrite_lem msg_deghost_spec. auto.\n  Qed.\n\n  Lemma lifted_committed_committed :\n    forall net e t,\n      lifted_committed net e t ->\n      committed (mgv_deghost net) e t.\n  Proof using rmri. \n    unfold lifted_committed, committed.\n    intros.\n    break_exists_exists.\n    rewrite msg_deghost_spec.\n    intuition auto using lifted_directly_committed_directly_committed.\n  Qed.\n\n  Lemma committed_lifted_committed :\n    forall net e t,\n      committed (mgv_deghost net) e t ->\n      lifted_committed net e t.\n  Proof using rmri. \n    unfold lifted_committed, committed.\n    intros.\n    break_exists_exists.\n    find_rewrite_lem msg_deghost_spec.\n    intuition auto using directly_committed_lifted_directly_committed.\n  Qed.\n\n  Lemma msg_deghost_spec' :\n    forall base multi ghost\n      (net : @network (@mgv_refined_base_params base)\n                      (@mgv_refined_multi_params base multi ghost)) h,\n      nwState (mgv_deghost net) h = nwState net h.\n  Proof using. \n    unfold mgv_deghost.\n    intros.\n    simpl.\n    destruct net. auto.\n  Qed.\n\n  Lemma commit_invariant_lower_commit_recorded_committed :\n    forall net : ghost_log_network,\n      msg_refined_raft_intermediate_reachable net ->\n      commit_invariant net ->\n      commit_recorded_committed (mgv_deghost net).\n  Proof using rmri lalcii rri. \n    unfold commit_invariant, commit_recorded_committed, commit_recorded, commit_invariant_host.\n    intuition;\n    repeat find_rewrite_lem deghost_spec;\n    repeat find_rewrite_lem msg_deghost_spec';\n    rewrite msg_deghost_spec';\n    apply lifted_committed_committed; auto.\n    eauto using Nat.le_trans, msg_lifted_lastApplied_le_commitIndex.\n  Qed.\n\n  Lemma handleClientRequest_currentTerm :\n    forall h st client id c out st' ms,\n      handleClientRequest h st client id c = (out, st', ms) ->\n      currentTerm st' = currentTerm st.\n  Proof using. \n    unfold handleClientRequest.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma handleClientRequest_commitIndex :\n    forall h st client id c out st' ms,\n      handleClientRequest h st client id c = (out, st', ms) ->\n      commitIndex st' = commitIndex st.\n  Proof using. \n    unfold handleClientRequest.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma directly_committed_allEntries_preserved :\n    forall net net' e,\n      directly_committed net e ->\n      (forall h, In (eTerm e, e) (allEntries (fst (nwState net h))) ->\n                 In (eTerm e, e) (allEntries (fst (nwState net' h)))) ->\n      directly_committed net' e.\n  Proof using. \n    unfold directly_committed.\n    intuition.\n    break_exists_exists.\n    intuition.\n  Qed.\n\n  Lemma update_elections_data_client_request_allEntries :\n    forall h st client id c out st' ms,\n      handleClientRequest h (snd st) client id c = (out, st', ms) ->\n      allEntries (update_elections_data_client_request h st client id c) =\n      allEntries (fst st) \\/\n      (exists e : entry,\n         eIndex e = S (maxIndex (log (snd st))) /\\\n         eTerm e = currentTerm (snd st) /\\\n         eClient e = client /\\ eInput e = c /\\ eId e = id /\\ type (snd st) = Leader /\\\n         allEntries (update_elections_data_client_request h st client id c) =\n         (currentTerm st', e) :: allEntries (fst st)).\n  Proof using. \n    intros.\n    unfold update_elections_data_client_request.\n    repeat break_match; repeat find_inversion; auto.\n    simpl.\n    find_copy_apply_lem_hyp handleClientRequest_log.\n    intuition.\n    - repeat find_rewrite. do_bool. lia.\n    - right.  break_exists_exists. intuition.\n      congruence.\n  Qed.\n\n  Lemma update_elections_data_client_request_allEntries_ind :\n    forall {h st client id c out st' ps},\n      handleClientRequest h (snd st) client id c = (out, st', ps) ->\n      forall (P : list (term * entry) -> Prop),\n        P (allEntries (fst st)) ->\n        (forall e,\n         eIndex e = S (maxIndex (log (snd st))) ->\n         eTerm e = currentTerm (snd st) ->\n         eClient e = client -> eInput e = c -> eId e = id -> type (snd st) = Leader ->\n         P ((currentTerm st', e) :: allEntries (fst st))) ->\n        P (allEntries (update_elections_data_client_request h st client id c)).\n  Proof using. \n    intros.\n    find_apply_lem_hyp update_elections_data_client_request_allEntries.\n    intuition.\n    - find_rewrite. auto.\n    - break_exists. intuition.\n      repeat find_rewrite.  auto.\n  Qed.\n\n  Lemma update_elections_data_client_request_preserves_allEntries :\n    forall h st client id c out st' ms t e,\n      handleClientRequest h (snd st) client id c = (out, st', ms) ->\n      In (t, e) (allEntries (fst st)) ->\n      In (t, e) (allEntries (update_elections_data_client_request h st client id c)).\n  Proof using. \n    intros.\n    match goal with\n      | [ |- context [ allEntries ?x ] ] =>\n        destruct (allEntries x)\n                 using (update_elections_data_client_request_allEntries_ind ltac:(eauto))\n    end; intuition.\n  Qed.\n\n  Lemma handleClientRequest_preservers_log :\n    forall h st client id c out st' ms e,\n      handleClientRequest h st client id c = (out, st', ms) ->\n      In e (log st) ->\n      In e (log st').\n  Proof using. \n    intros.\n    destruct (log st') using (handleClientRequest_log_ind ltac:(eauto)); intuition.\n  Qed.\n\n  Lemma committed_log_allEntries_preserved :\n    forall net net' e t,\n      committed net e t ->\n      (forall h e',\n         In e' (log (snd (nwState net h))) ->\n         In e' (log (snd (nwState net' h)))) ->\n      (forall h e' t',\n         In (t', e') (allEntries (fst (nwState net h))) ->\n         In (t', e') (allEntries (fst (nwState net' h)))) ->\n      committed net' e t.\n  Proof using. \n    unfold committed.\n    intros.\n    break_exists_exists.\n    intuition.\n    eapply directly_committed_allEntries_preserved; eauto.\n  Qed.\n\n  Lemma lifted_committed_log_allEntries_preserved :\n    forall net net' e t,\n      lifted_committed net e t ->\n      (forall h e',\n          In e' (log (snd (nwState net h))) ->\n          In e' (log (snd (nwState net' h)))) ->\n      (forall h e' t',\n          In (t', e') (allEntries (fst (nwState net h))) ->\n          In (t', e') (allEntries (fst (nwState net' h)))) ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    intros.\n    find_apply_lem_hyp lifted_committed_committed.\n    find_eapply_lem_hyp committed_log_allEntries_preserved; eauto.\n    apply committed_lifted_committed.\n    eapply committed_log_allEntries_preserved; eauto;\n    intros;\n    repeat find_rewrite_lem msg_deghost_spec;\n    rewrite msg_deghost_spec; auto.\n  Qed.\n\n  Lemma lift_max_index_sanity :\n    forall (net : ghost_log_network) h,\n      msg_refined_raft_intermediate_reachable net ->\n      maxIndex_sanity (deghost (mgv_deghost net)) ->\n      lastApplied (snd (nwState net h)) <= maxIndex (log (snd (nwState net h))) /\\\n      commitIndex (snd (nwState net h)) <= maxIndex (log (snd (nwState net h))).\n  Proof using rmri rri. \n    intros.\n    match goal with\n      | [ H : _, H' : _ |- _ ] => apply H in H'; clear H\n    end.\n    unfold maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex in *.\n    break_and.\n    repeat match goal with\n           | [ H : _ |- _ ] => specialize (H h)\n           end.\n    repeat find_rewrite_lem deghost_spec.\n    repeat find_rewrite_lem msg_deghost_spec'.\n    auto.\n  Qed.\n\n  Lemma haveNewEntries_log :\n    forall es st st',\n      log st = log st' ->\n      haveNewEntries st es = true ->\n      haveNewEntries st' es = true.\n  Proof using. \n    unfold haveNewEntries.\n    intros.\n    find_rewrite. auto.\n  Qed.\n\n  Lemma hCR_preserves_committed :\n    forall (net net' : ghost_log_network) h client id c out d l e t,\n      handleClientRequest h (snd (nwState net h)) client id c = (out, d, l) ->\n      (forall h', nwState net' h' = update name_eq_dec (nwState net) h (update_elections_data_client_request h (nwState net h) client id c, d) h') ->\n      lifted_committed net e t ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; simpl; eauto.\n    - intros. find_higher_order_rewrite.\n      update_destruct_simplify; eauto using handleClientRequest_preservers_log.\n    - intros. find_higher_order_rewrite.\n      update_destruct_simplify; eauto using update_elections_data_client_request_preserves_allEntries.\n  Qed.\n\n  Lemma not_empty_intro :\n    forall A (l : list A),\n      l <> [] -> not_empty l = true.\n  Proof using. \n    unfold not_empty.\n    intros.\n    break_match; congruence.\n  Qed.\n\n  Lemma haveNewEntries_true_intro :\n    forall st es,\n      es <> [] ->\n      (forall e, findAtIndex (log st) (maxIndex es) = Some e ->\n            eTerm e <> maxTerm es) ->\n      haveNewEntries st es = true.\n  Proof using. \n    unfold haveNewEntries.\n    intros.\n    do_bool. split.\n    - auto using not_empty_intro.\n    - break_match; auto.\n      apply Bool.negb_true_iff.\n      do_bool. intuition eauto.\n  Qed.\n\n  Definition lifted_prevLog_leader_sublog (net : network) : Prop :=\n    forall leader p t leaderId prevLogIndex prevLogTerm entries leaderCommit,\n      type (snd (nwState net leader)) = Leader ->\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t leaderId prevLogIndex prevLogTerm entries leaderCommit ->\n      currentTerm (snd (nwState net leader)) = prevLogTerm ->\n      0 < prevLogIndex ->\n      0 < prevLogTerm ->\n      exists ple, eIndex ple = prevLogIndex /\\\n             eTerm ple = prevLogTerm /\\\n             In ple (log (snd (nwState net leader))).\n\n  Lemma prevLog_leader_sublog_lifted :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_prevLog_leader_sublog net.\n  Proof using rmri pllsi rri. \n    intros.\n    pose proof (msg_lift_prop _ (lift_prop _ prevLog_leader_sublog_invariant)).\n    find_insterU. conclude_using eauto.\n    unfold prevLog_leader_sublog, lifted_prevLog_leader_sublog in *.\n    intros.\n    find_apply_lem_hyp in_mgv_ghost_packet.\n    find_apply_lem_hyp in_ghost_packet.\n    unfold deghost in *. simpl in *. break_match. simpl in *. subst.\n    specialize (H0 leader).\n    destruct (nwState leader). simpl in *.\n    eauto.\n  Qed.\n\n  Lemma commit_invariant_client_request :\n    forall h (net : ghost_log_network) st' ps' gd out d l client id c,\n      handleClientRequest h (snd (nwState net h)) client id c = (out, d, l) ->\n      gd = update_elections_data_client_request h (nwState net h) client id c ->\n      commit_invariant net ->\n      maxIndex_sanity (deghost (mgv_deghost net)) ->\n      msg_refined_raft_intermediate_reachable net ->\n      (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                         In p' (send_packets h (add_ghost_msg (msg_ghost_params := ghost_log_params) h (gd, d) l))) ->\n      commit_invariant (mkNetwork ps' st').\n  Proof using rmri rri. \n    unfold msg_refined_raft_net_invariant_client_request, commit_invariant.\n    intros. split.\n    - { unfold commit_invariant_host in *. break_and.\n        unfold commit_recorded_committed, commit_recorded in *.\n        intros. simpl in *.\n        repeat find_higher_order_rewrite.\n        rewrite update_fun_comm with (f := snd).\n        repeat match goal with H : _ |- _ => rewrite update_fun_comm with (f := snd) in H end.\n        simpl in *.\n        repeat match goal with\n                 | [H : _ |- _] => rewrite (update_fun_comm _ raft_data _) in H\n               end.\n        rewrite (update_fun_comm  _ raft_data).\n        rewrite update_nop_ext' by (now erewrite <- handleClientRequest_currentTerm by eauto).\n        match goal with\n          | [H : _ |- _] => rewrite update_nop_ext' in H\n              by (now erewrite <- handleClientRequest_commitIndex by eauto)\n        end.\n        update_destruct_simplify.\n        - find_copy_apply_lem_hyp handleClientRequest_log.\n          break_and. break_or_hyp.\n          + repeat find_rewrite.\n            eapply lifted_committed_log_allEntries_preserved; eauto.\n            * simpl. intros. find_higher_order_rewrite.\n              update_destruct_simplify; repeat find_rewrite; auto.\n            * simpl. intros. find_higher_order_rewrite.\n              update_destruct_simplify; eauto using update_elections_data_client_request_preserves_allEntries.\n          + break_exists. break_and. repeat find_rewrite.\n            simpl in *.\n            match goal with\n              | [ H : _ \\/ In _ _ |- _ ] => invc H\n            end.\n            * find_eapply_lem_hyp (lift_max_index_sanity net h0); auto.\n              break_and. simpl in *. lia.\n            * { eapply lifted_committed_log_allEntries_preserved; eauto.\n                - simpl. intros. find_higher_order_rewrite.\n                  update_destruct_simplify; repeat find_rewrite; auto.\n                  find_reverse_rewrite.\n                  eapply handleClientRequest_preservers_log; eauto.\n                - simpl. intros. find_higher_order_rewrite.\n                  update_destruct_simplify; eauto using update_elections_data_client_request_preserves_allEntries.\n              }\n        - eapply lifted_committed_log_allEntries_preserved; eauto.\n          + simpl. intros. find_higher_order_rewrite.\n            update_destruct_simplify; repeat find_rewrite; eauto using handleClientRequest_preservers_log.\n          + simpl. intros. find_higher_order_rewrite.\n            update_destruct_simplify; eauto using update_elections_data_client_request_preserves_allEntries.\n      }\n    - unfold commit_invariant_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp.\n      intuition.\n      + eapply hCR_preserves_committed; eauto. simpl. subst. auto.\n      + unfold send_packets in *.\n        do_in_map.\n        unfold add_ghost_msg in *.\n        do_in_map.\n        subst. simpl in *.\n        exfalso. eapply handleClientRequest_no_append_entries; eauto 10.\n  Qed.\n\n  Lemma handleTimeout_preserves_committed :\n    forall h (net net' : ghost_log_network) out d' l e t,\n      handleTimeout h (snd (nwState net h)) = (out, d', l) ->\n      (forall h', nwState net' h' = update name_eq_dec (nwState net) h (update_elections_data_timeout h (nwState net h), d') h') ->\n      lifted_committed net e t ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto.\n    - intros. repeat find_higher_order_rewrite. update_destruct_simplify.\n      + now erewrite handleTimeout_log_same by eauto.\n      + auto.\n    - intros. repeat find_higher_order_rewrite. update_destruct_simplify.\n      + now rewrite update_elections_data_timeout_allEntries.\n      + auto.\n  Qed.\n\n  Lemma lifted_committed_monotonic :\n    forall net t t' e,\n      lifted_committed net e t ->\n      t <= t' ->\n      lifted_committed net e t'.\n  Proof using. \n    unfold lifted_committed.\n    intros.\n    break_exists_exists.\n    intuition.\n  Qed.\n\n\n  Lemma commit_invariant_timeout :\n    msg_refined_raft_net_invariant_timeout commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_timeout, commit_invariant.\n    simpl. intuition.\n    - unfold commit_invariant_host in *.\n      simpl. intros.\n      repeat find_higher_order_rewrite.\n      update_destruct_simplify.\n      + eapply handleTimeout_preserves_committed; eauto.\n        match goal with\n        | [ H : context [commitIndex] |- _ ] => erewrite handleTimeout_commitIndex in H by eauto\n        end.\n        match goal with\n        | [ H : context [log] |- _ ] => erewrite handleTimeout_log_same in H by eauto\n        end.\n        eapply lifted_committed_monotonic; [eauto|].\n        find_apply_lem_hyp handleTimeout_type_strong.\n        intuition; repeat find_rewrite; auto.\n      + eapply handleTimeout_preserves_committed; eauto.\n    - unfold commit_invariant_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp.\n      intuition.\n      * eapply handleTimeout_preserves_committed; eauto.\n        simpl. intros. subst. auto.\n      * do_in_map.\n        subst. simpl in *.\n        unfold add_ghost_msg in *.\n        do_in_map.\n        subst. simpl in *.\n        find_eapply_lem_hyp handleTimeout_packets; eauto.\n        exfalso. eauto 10.\n  Qed.\n\n  Lemma committed_ext :\n    forall ps  st st' t e,\n      (forall h, st' h = st h) ->\n      committed (mkNetwork ps st) e t ->\n      committed (mkNetwork ps st') e t.\n  Proof using. \n    unfold committed, directly_committed.\n    simpl. intros.\n    break_exists_exists.\n    find_higher_order_rewrite.\n    intuition.\n    break_exists_exists.  intuition.\n    find_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma lifted_committed_ext :\n    forall ps st st' t e,\n      (forall h, st' h = st h) ->\n      lifted_committed (mkNetwork ps st) e t ->\n      lifted_committed (mkNetwork ps st') e t.\n  Proof using rmri. \n    intros.\n    apply committed_lifted_committed.\n    find_apply_lem_hyp lifted_committed_committed.\n    unfold mgv_deghost in *.\n    eauto using committed_ext.\n  Qed.\n\n  Definition lifted_state_machine_safety_nw' net :=\n    forall p t leaderId prevLogIndex prevLogTerm entries leaderCommit e t',\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t leaderId prevLogIndex prevLogTerm\n                              entries leaderCommit ->\n      lifted_committed net e t' ->\n      t >= t' ->\n      (prevLogIndex > eIndex e \\/\n       (prevLogIndex = eIndex e /\\ prevLogTerm = eTerm e) \\/\n       eIndex e > maxIndex entries \\/\n       In e entries).\n\n  Lemma lifted_state_machine_safety_nw'_invariant :\n    forall (net : @network _ raft_msg_refined_multi_params),\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_state_machine_safety_nw' net.\n  Proof using rmri smspi. \n    intros.\n    unfold lifted_state_machine_safety_nw'.\n    intros.\n    find_apply_lem_hyp lifted_committed_committed.\n    find_apply_lem_hyp in_mgv_ghost_packet.\n    match goal with\n      | _ : snd (pBody ?p) = ?x |- _ =>\n        assert (pBody (@mgv_deghost_packet _ _ ghost_log_params p) = x)\n          by (rewrite pBody_mgv_deghost_packet; auto)\n    end.\n    eapply state_machine_safety'_invariant; eauto.\n    eapply msg_lift_prop; eauto.\n  Qed.\n\n  Lemma lifted_entries_sorted_nw :\n    forall net p t n pli plt es ci,\n      msg_refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      sorted es.\n  Proof using rmri rlmli. \n    intros.\n    find_apply_lem_hyp in_mgv_ghost_packet.\n    match goal with\n      | _ : snd (pBody ?p) = ?x |- _ =>\n        assert (pBody (@mgv_deghost_packet _ _ ghost_log_params p) = x)\n          by (rewrite pBody_mgv_deghost_packet; auto)\n    end.\n    find_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n    eapply msg_lift_prop; eauto.\n  Qed.\n      \n  Lemma update_elections_data_appendEntries_preserves_allEntries' :\n    forall st h t n pli plt es ci x,\n      In x (allEntries (fst st)) ->\n      In x (allEntries (update_elections_data_appendEntries h st t n pli plt es ci)).\n  Proof using. \n    unfold update_elections_data_appendEntries.\n    intros. break_let. break_match; auto.\n    break_if; auto.\n    simpl. intuition.\n  Qed.\n\n  Lemma lifted_transitive_commit_invariant :\n    forall net h e e' t,\n      msg_refined_raft_intermediate_reachable net ->\n      In e (log (snd (nwState net h))) ->\n      In e' (log (snd (nwState net h))) ->\n      eIndex e <= eIndex e' ->\n      lifted_committed net e' t ->\n      lifted_committed net e t.\n  Proof using rmri tci. \n    intros net0;intros.\n    apply committed_lifted_committed.\n    find_apply_lem_hyp lifted_committed_committed.\n    repeat match goal with\n             | H : _ |- _ =>\n               rewrite <- msg_deghost_spec with (net := net0) in H\n           end.\n    eapply transitive_commit_invariant; eauto.\n    eapply msg_lift_prop; eauto.\n  Qed.\n  \n  Lemma handleAppendEntries_preserves_commit :\n    forall net net' h p t n pli plt es ci d m e t',\n      msg_refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      handleAppendEntries h (snd (nwState net h)) t n pli plt es ci = (d, m) ->\n      (forall h', nwState net' h' = update name_eq_dec (nwState net) h\n                                      (update_elections_data_appendEntries\n                                         h (nwState net h) t n pli plt es ci, d) h') ->\n      lifted_committed net e t' ->\n      lifted_committed net' e t'.\n  Proof using rmri tsi rlmli smspi si rri. \n    intros.\n    unfold lifted_committed in *.\n    break_exists_name host. break_exists_name e'.\n    exists host, e'.\n    intuition.\n    - (* directly committed doesn't change *)\n      unfold lifted_directly_committed in *.\n      break_exists_exists; intuition.\n      find_higher_order_rewrite.\n      update_destruct_simplify; eauto using update_elections_data_appendEntries_preserves_allEntries'.\n    - (* e is still around *)\n      find_higher_order_rewrite.\n      update_destruct_simplify; simpl in *; eauto.\n      assert (lifted_committed net e (currentTerm (snd (nwState net host)))) by\n            (unfold lifted_committed;\n             exists host, e'; intuition;\n             eapply lifted_no_entries_past_current_term_host_invariant; eauto).\n      find_eapply_lem_hyp handleAppendEntries_log_detailed. intuition; repeat find_rewrite; eauto.\n      + (* pli = 0, no entry at maxIndex es *)\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        assert (eIndex e > 0) by (eapply lifted_entries_gt_0_invariant; eauto).\n        intuition; try lia.\n        find_copy_eapply_lem_hyp msg_lifted_sorted_host.\n        exfalso.\n\tenough (exists e, eIndex e = (maxIndex es) /\\ In e (log (snd (nwState net host)))) by\n            (break_exists;\n             intuition; eapply findAtIndex_None; eauto).\n        eapply contiguous_range_exact_lo_elim_exists;\n          [apply lifted_entries_contiguous_invariant; auto|].\n        intuition.\n        * find_apply_lem_hyp maxIndex_non_empty.\n          break_exists; intuition; repeat find_rewrite.\n          enough (eIndex x > 0) by lia.\n          eapply lifted_entries_contiguous_nw_invariant; eauto.\n        * enough (eIndex e <= maxIndex (log (snd (nwState net host)))) by lia.\n          apply maxIndex_is_max; auto.\n      + (* pli = 0, bad entry at maxIndex es *)\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        assert (eIndex e > 0) by (eapply lifted_entries_gt_0_invariant; eauto).\n        intuition; try lia.\n        break_exists. intuition.\n        find_apply_lem_hyp maxIndex_non_empty.\n        break_exists_name maxEntry; intuition.\n        repeat find_rewrite.\n        find_false.\n        f_equal.\n        find_apply_lem_hyp findAtIndex_elim.\n        intuition.\n        eapply uniqueIndices_elim_eq; [| |eauto|];\n        eauto using sorted_uniqueIndices,lifted_entries_sorted_nw.\n        match goal with\n          | |- In ?e _ =>\n            assert (lifted_committed net e (currentTerm (snd (nwState net host)))) by\n                (unfold lifted_committed;\n                 exists host, e'; intuition;\n                 eapply lifted_no_entries_past_current_term_host_invariant; eauto)\n        end.\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        assert (eIndex x > 0) by (eapply lifted_entries_gt_0_invariant; eauto).\n        intuition; lia.\n      + find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        intuition;\n          try solve\n              [apply in_app_iff; right; apply removeAfterIndex_le_In; auto; lia];\n          [idtac].\n        find_copy_eapply_lem_hyp msg_lifted_sorted_host.\n        exfalso.\n\tenough (exists e, eIndex e = (maxIndex es) /\\ In e (log (snd (nwState net host)))) by\n            (break_exists;\n             intuition; eapply findAtIndex_None; eauto).\n        eapply contiguous_range_exact_lo_elim_exists;\n          [apply lifted_entries_contiguous_invariant; auto|].\n        intuition.\n        * find_apply_lem_hyp maxIndex_non_empty.\n          break_exists; intuition; repeat find_rewrite.\n          enough (eIndex x0 > 0) by lia.\n          enough (eIndex x0 > pli) by lia.\n          eapply lifted_entries_contiguous_nw_invariant; eauto.\n        * enough (eIndex e <= maxIndex (log (snd (nwState net host)))) by lia.\n          apply maxIndex_is_max; auto.\n      + find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        intuition;\n          try solve\n              [apply in_app_iff; right; apply removeAfterIndex_le_In; auto; lia];\n          [idtac].\n        break_exists. intuition.\n        find_apply_lem_hyp maxIndex_non_empty.\n        break_exists_name maxEntry; intuition.\n        repeat find_rewrite.\n        find_false.\n        f_equal.\n        find_apply_lem_hyp findAtIndex_elim.\n        intuition.\n        eapply uniqueIndices_elim_eq; [| |eauto|];\n        eauto using sorted_uniqueIndices,lifted_entries_sorted_nw.\n        match goal with\n          | |- In ?e _ =>\n            assert (lifted_committed net e (currentTerm (snd (nwState net host)))) by\n                (unfold lifted_committed;\n                 exists host, e'; intuition;\n                 eapply lifted_no_entries_past_current_term_host_invariant; eauto)\n        end.\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        intuition; try lia;\n        enough (pli < eIndex maxEntry) by lia;\n        eapply lifted_entries_contiguous_nw_invariant; eauto.\n    - find_higher_order_rewrite.\n      update_destruct_simplify; simpl in *; eauto.\n      assert (lifted_committed net e' (currentTerm (snd (nwState net host)))) by\n            (unfold lifted_committed;\n             exists host, e'; intuition;\n             eapply lifted_no_entries_past_current_term_host_invariant; eauto).\n      find_eapply_lem_hyp handleAppendEntries_log_detailed. intuition; repeat find_rewrite; eauto.\n      + (* pli = 0, no entry at maxIndex es *)\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        assert (eIndex e' > 0) by (eapply lifted_entries_gt_0_invariant; eauto).\n        intuition; try lia.\n        find_copy_eapply_lem_hyp msg_lifted_sorted_host.\n        exfalso.\n\tenough (exists e, eIndex e = (maxIndex es) /\\ In e (log (snd (nwState net host)))) by\n            (break_exists;\n             intuition; eapply findAtIndex_None; eauto).\n        eapply contiguous_range_exact_lo_elim_exists;\n          [apply lifted_entries_contiguous_invariant; auto|].\n        intuition.\n        * find_apply_lem_hyp maxIndex_non_empty.\n          break_exists; intuition; repeat find_rewrite.\n          enough (eIndex x > 0) by lia.\n          eapply lifted_entries_contiguous_nw_invariant; eauto.\n        * enough (eIndex e' <= maxIndex (log (snd (nwState net host)))) by lia.\n          apply maxIndex_is_max; auto.\n      + (* pli = 0, bad entry at maxIndex es *)\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        assert (eIndex e' > 0) by (eapply lifted_entries_gt_0_invariant; eauto).\n        intuition; try lia.\n        break_exists. intuition.\n        find_apply_lem_hyp maxIndex_non_empty.\n        break_exists_name maxEntry; intuition.\n        repeat find_rewrite.\n        find_false.\n        f_equal.\n        find_apply_lem_hyp findAtIndex_elim.\n        intuition.\n        eapply uniqueIndices_elim_eq; [| |eauto|];\n        eauto using sorted_uniqueIndices,lifted_entries_sorted_nw.\n        match goal with\n          | |- In ?e _ =>\n            assert (lifted_committed net e (currentTerm (snd (nwState net host)))) by\n                (unfold lifted_committed;\n                 exists host, e'; intuition;\n                 eapply lifted_no_entries_past_current_term_host_invariant; eauto)\n        end.\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        assert (eIndex x > 0) by (eapply lifted_entries_gt_0_invariant; eauto).\n        intuition; lia.\n      + find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        intuition;\n          try solve\n              [apply in_app_iff; right; apply removeAfterIndex_le_In; auto; lia];\n          [idtac].\n        find_copy_eapply_lem_hyp msg_lifted_sorted_host.\n        exfalso.\n\tenough (exists e, eIndex e = (maxIndex es) /\\ In e (log (snd (nwState net host)))) by\n            (break_exists;\n             intuition; eapply findAtIndex_None; eauto).\n        eapply contiguous_range_exact_lo_elim_exists;\n          [apply lifted_entries_contiguous_invariant; auto|].\n        intuition.\n        * find_apply_lem_hyp maxIndex_non_empty.\n          break_exists; intuition; repeat find_rewrite.\n          enough (eIndex x0 > 0) by lia.\n          enough (eIndex x0 > pli) by lia.\n          eapply lifted_entries_contiguous_nw_invariant; eauto.\n        * enough (eIndex e' <= maxIndex (log (snd (nwState net host)))) by lia.\n          apply maxIndex_is_max; auto.\n      + find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        intuition;\n          try solve\n              [apply in_app_iff; right; apply removeAfterIndex_le_In; auto; lia];\n          [idtac].\n        break_exists. intuition.\n        find_apply_lem_hyp maxIndex_non_empty.\n        break_exists_name maxEntry; intuition.\n        repeat find_rewrite.\n        find_false.\n        f_equal.\n        find_apply_lem_hyp findAtIndex_elim.\n        intuition.\n        eapply uniqueIndices_elim_eq; [| |eauto|];\n        eauto using sorted_uniqueIndices,lifted_entries_sorted_nw.\n        match goal with\n          | |- In ?e _ =>\n            assert (lifted_committed net e (currentTerm (snd (nwState net host)))) by\n                (unfold lifted_committed;\n                 exists host, e'; intuition;\n                 eapply lifted_no_entries_past_current_term_host_invariant; eauto)\n        end.\n        find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n        intuition; try lia;\n        enough (pli < eIndex maxEntry) by lia;\n        eapply lifted_entries_contiguous_nw_invariant; eauto.\n  Qed.\n\n  Lemma handleAppendEntries_currentTerm_le :\n    forall h st t n pli plt es ci st' m,\n      handleAppendEntries h st t n pli plt es ci = (st', m) ->\n      currentTerm st <= currentTerm st'.\n  Proof using. \n    intros.\n    unfold handleAppendEntries, advanceCurrentTerm in *.\n    repeat break_match; find_inversion; simpl in *;\n    do_bool; auto.\n  Qed.\n\n  Theorem handleAppendEntries_log_detailed :\n    forall h st t n pli plt es ci st' ps,\n      handleAppendEntries h st t n pli plt es ci = (st', ps) ->\n      (commitIndex st' = commitIndex st /\\ log st' = log st) \\/\n      (leaderId st' <> None /\\\n       currentTerm st' = t /\\\n       commitIndex st' = max (commitIndex st) (min ci (maxIndex es)) /\\\n       es <> nil /\\\n       pli = 0 /\\ t >= currentTerm st /\\ log st' = es /\\\n      haveNewEntries st es = true ) \\/\n      (leaderId st' <> None /\\\n       currentTerm st' = t /\\\n       commitIndex st' = max (commitIndex st)\n                             (min ci (maxIndex (es ++ (removeAfterIndex (log st) pli)))) /\\\n       es <> nil /\\\n        exists e,\n         In e (log st) /\\\n         eIndex e = pli /\\\n         eTerm e = plt) /\\\n      t >= currentTerm st /\\\n      log st' = es ++ (removeAfterIndex (log st) pli) /\\\n      haveNewEntries st es = true.\n  Proof using. \n    intros. unfold handleAppendEntries in *.\n    break_if; [find_inversion; subst; eauto|].\n    break_if;\n      [do_bool; break_if; find_inversion; subst;\n        try find_apply_lem_hyp haveNewEntries_true;\n        simpl in *; intuition eauto using advanceCurrentTerm_log, advanceCurrentTerm_commitIndex, some_none, advanceCurrentTerm_term|].\n    simpl in *. intuition eauto using advanceCurrentTerm_log, advanceCurrentTerm_commitIndex.\n    break_match; [|find_inversion; subst; eauto].\n    break_if; [find_inversion; subst; eauto|].\n    break_if; [|find_inversion; subst; eauto using advanceCurrentTerm_log, advanceCurrentTerm_commitIndex].\n    find_inversion; subst; simpl in *.\n    right. right.\n    find_apply_lem_hyp findAtIndex_elim.\n    intuition; do_bool; find_apply_lem_hyp haveNewEntries_true;\n    intuition eauto using advanceCurrentTerm_term; congruence.\n  Qed.\n\n  Definition lifted_entries_gt_0_nw (net : ghost_log_network) : Prop :=\n    forall p t n pli plt es ci e,\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      In e es ->\n      eIndex e > 0.\n\n  Lemma lifted_entries_gt_0_nw_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_entries_gt_0_nw net.\n  Proof using rmri rlmli. \n    unfold lifted_entries_gt_0_nw.\n    intros.\n    pose proof msg_lift_prop _ entries_gt_0_nw_invariant _ ltac:(eauto).\n    unfold entries_gt_0_nw in *.\n    find_apply_lem_hyp in_mgv_ghost_packet.\n    match goal with\n    | [ H : _ |- _ ] => eapply H; eauto\n    end.\n  Qed.\n\n  Definition lifted_entries_sorted_nw' (net : ghost_log_network) :=\n    forall p t n pli plt es ci,\n      In p (nwPackets net) ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      sorted es.\n\n  Lemma lifted_entries_sorted_nw'_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_entries_sorted_nw' net.\n  Proof using rmri rlmli. \n    intros.\n    pose proof msg_lift_prop _ entries_sorted_nw_invariant.\n    find_copy_apply_hyp_hyp.\n    unfold entries_sorted_nw, lifted_entries_sorted_nw' in *.\n    intros.\n    find_apply_lem_hyp in_mgv_ghost_packet.\n    eapply_prop_hyp In In; eauto.\n  Qed.\n\n  Lemma commit_invariant_append_entries :\n    forall xs p ys (net : ghost_log_network) st' ps' gd d m t n pli plt es ci,\n      handleAppendEntries (pDst p) (snd (nwState net (pDst p))) t n pli plt es ci = (d, m) ->\n      gd = update_elections_data_appendEntries (pDst p) (nwState net (pDst p)) t n pli plt es ci ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      commit_invariant net ->\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_maxIndex_sanity net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update name_eq_dec (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' ->\n             In p' (xs ++ ys) \\/ p' = mkPacket (pDst p) (pSrc p)\n                                             (write_ghost_log (pDst p) (gd, d), m)) ->\n      commit_invariant (mkNetwork ps' st').\n  Proof using rmri tsi glemi lphogli glci rlmli smspi si rri. \n    unfold commit_invariant.\n    intros.\n\n    assert (In p (nwPackets net)) by (repeat find_rewrite; auto with *).\n    split.\n    - break_and.\n       match goal with\n       | [ H : commit_invariant_host _ |- _ ] =>\n         rename H into Hhost;\n           unfold commit_invariant_host in *\n       end.\n       simpl. intros.\n       eapply lifted_committed_ext; eauto.\n\n       match goal with\n       | [ H : forall _, _ = _ |- _ ] => rewrite H in *\n       end.\n       update_destruct_simplify.\n       + (* e is in h's log *)\n         find_copy_apply_lem_hyp handleAppendEntries_log_detailed.\n         break_or_hyp.\n         * break_and. repeat find_rewrite.\n           eapply lifted_committed_monotonic; [\n               solve [eapply handleAppendEntries_preserves_commit; eauto] |\n               solve [eauto using handleAppendEntries_currentTerm_le] ].\n         * { break_or_hyp; repeat break_and.\n             - (* beginning of time case *)\n               repeat match goal with\n               | [ H : _ <= _, H': _ |- _ ] => rewrite H' in H\n               end.\n               find_apply_lem_hyp NPeano.Nat.max_le. break_or_hyp.\n               + (* my log is just the entries in the incoming AE.\n                    so e was in the incoming entries.\n                    but eIndex e <= old commit index.\n                    by maxIndex_commitIndex, exists e' in old log such that eIndex e = eIndex e'.\n                    note that e' is committed in the pre state by IH.\n                    now apply SMS'_nw invariant to e' to get four cases.\n                    first three are absurd by index calculation.\n                    it follows that e' is in es.\n                    but our new log is just es, so e' is in the new log.\n                    by thus e = e' by unique indices.\n                    thus e is committed.\n                  *)\n                 assert (eIndex e > 0) by (eapply lifted_entries_gt_0_nw_invariant; eauto).\n                 assert (exists e', eIndex e' = eIndex e /\\ In e' (log (snd (nwState net (pDst p))))).\n                 {\n                   eapply contiguous_range_exact_lo_elim_exists.\n                   - eapply lifted_entries_contiguous_invariant. auto.\n                   - split.\n                     + auto.\n                     + eapply Nat.le_trans; [eauto|].\n                       eapply_prop lifted_maxIndex_sanity.\n                 }\n                 break_exists_name e'.\n                 break_and.\n                 assert (lifted_committed net e' (currentTerm (snd (nwState net (pDst p))))) as He'committed\n                        by (apply Hhost; [auto|congruence]) .\n\n                 find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n                 concludes.\n                 assert (sorted (log d)) by (eauto using lifted_handleAppendEntries_logs_sorted).\n                 intuition.\n                 * lia.\n                 * lia.\n                 * match goal with\n                   | [ H : _ |- _ ] => eapply maxIndex_is_max in H; eauto; [idtac]\n                   end.\n                   lia.\n                 * assert (e = e') by (eapply uniqueIndices_elim_eq; eauto using sorted_uniqueIndices).\n                   subst.\n                   eapply lifted_committed_monotonic; [\n                       solve [eapply handleAppendEntries_preserves_commit; eauto] |\n                       solve [eauto using handleAppendEntries_currentTerm_le] ].\n               + (* eIndex e <= incoming ci.\n                    result follows by the network invariant. *)\n                 match goal with\n                 | [ H : commit_invariant_nw _ |- _ ] =>\n                   rename H into Hnet; unfold commit_invariant_nw in *\n                 end.\n                 eapply_prop_hyp In In; [| eauto | | eauto using Nat.min_glb_l].\n                 * eapply handleAppendEntries_preserves_commit; eauto.\n                 * find_eapply_lem_hyp ghost_log_correct_invariant; eauto.\n                   conclude_using eauto.\n                   { intuition.\n                     - match goal with\n                       | [ H : In _ _, H' : _ |- _ ] => rewrite H' in H\n                       end. auto.\n                     - break_exists. break_and.\n                       pose proof log_properties_hold_on_ghost_logs_invariant _ ltac:(eauto) as Hprop.\n                       unfold log_properties_hold_on_ghost_logs in *.\n                       unfold msg_log_property in *.\n                       specialize (Hprop (fun l => forall e, In e l -> eIndex e > 0) p).\n                       conclude_using ltac:(intros; eapply lifted_entries_gt_0_invariant; eauto).\n                       conclude_using eauto. simpl in *.\n                       find_apply_hyp_hyp.\n                       lia.\n                   }\n             - (* middle of time case *)\n               break_exists_name ple. break_and.\n               repeat match goal with\n                      | [ H : _ <= _, H': _ |- _ ] => rewrite H' in H\n                      end.\n               find_apply_lem_hyp NPeano.Nat.max_le. break_or_hyp.\n               + (* eIndex e <= old commit index *)\n                 repeat find_rewrite.\n                 match goal with\n                 | [ H : In e (_ ++ _) |- _ ] => apply in_app_or in H; destruct H\n                 end.\n                 * (* e is new *)\n                   { assert (eIndex e > 0) by (eapply lifted_entries_gt_0_nw_invariant; eauto).\n                     assert (exists e', eIndex e' = eIndex e /\\ In e' (log (snd (nwState net (pDst p))))).\n                     {\n                       eapply contiguous_range_exact_lo_elim_exists.\n                       - eapply lifted_entries_contiguous_invariant. auto.\n                       - split.\n                         + auto.\n                         + eapply Nat.le_trans; [eauto|].\n                           eapply_prop lifted_maxIndex_sanity.\n                     }\n                     break_exists_name e'.\n                     break_and.\n                     assert (lifted_committed net e' (currentTerm (snd (nwState net (pDst p))))) as He'committed\n                         by (apply Hhost; [auto|congruence]) .\n\n                     find_copy_eapply_lem_hyp lifted_state_machine_safety_nw'_invariant; eauto.\n                     concludes.\n                     assert (sorted es) by\n                         (eapply lifted_entries_sorted_nw'_invariant; eauto).\n                     assert (contiguous_range_exact_lo es (eIndex ple)) by\n                         (eapply lifted_entries_contiguous_nw_invariant; eauto).\n                     find_eapply_lem_hyp contiguous_range_exact_lo_elim_lt; eauto.\n                     intuition.\n                     * lia.\n                     * lia.\n                     * match goal with\n                       | [ H : _ |- _ ] => eapply maxIndex_is_max in H; eauto with *; [idtac]\n                       end.\n                       lia.\n                     * assert (e = e') by (eapply uniqueIndices_elim_eq; eauto using sorted_uniqueIndices).\n                       subst.\n                       eapply lifted_committed_monotonic; [\n                           solve [eapply handleAppendEntries_preserves_commit; eauto] |\n                           solve [eauto using handleAppendEntries_currentTerm_le] ].\n                   }\n                 * (* e is old *)\n                   { eapply lifted_committed_monotonic.\n                     - eapply handleAppendEntries_preserves_commit; eauto.\n                       eapply Hhost with (h := pDst p); eauto using removeAfterIndex_in.\n                     - eauto using handleAppendEntries_currentTerm_le.\n                   }\n               + (* eIndex e <= new commit index *)\n                 match goal with\n                 | [ H : In e _ |- _ ] =>\n                   repeat match goal with\n                   | [ H' : _ |- _ ] => rewrite H' in H\n                   end;\n                     apply in_app_or in H; destruct H\n                 end.\n                 * (* e is new *)\n                   (* follows from network invariant *)\n                   { match goal with\n                     | [ H : commit_invariant_nw _ |- _ ] =>\n                       rename H into Hnet; unfold commit_invariant_nw in *\n                     end.\n                     match goal with\n                     | [ H : In _ (nwPackets _), H' : _ |- _ ] => eapply H' in H\n                     end; [| eauto | | eauto using Nat.min_glb_l].\n                     * eapply handleAppendEntries_preserves_commit; eauto.\n                     * find_copy_eapply_lem_hyp ghost_log_correct_invariant; eauto.\n                       conclude_using eauto.\n                       { intuition.\n                         - match goal with\n                           | [ H : In _ _, H' : _ |- _ ] => rewrite H' in H\n                           end. auto.\n                         - break_exists_name gple. break_and.\n                           subst.\n                           eauto using findGtIndex_in.\n                       }\n                   }\n\n                 * (* e is old *)\n                   (* eIndex e <= pli\n                      by ghost log contiguous, exists e' in ghost log such that eIndex e = eIndex e'.\n                      e' is committed by the nw invariant.\n                      by ghost log matching, e = e'.\n                      thus e is committed.\n                    *)\n                   assert (eIndex e <= eIndex ple) by\n                       (eapply removeAfterIndex_In_le; eauto using msg_lifted_sorted_host).\n                   pose proof log_properties_hold_on_ghost_logs_invariant _ ltac:(eauto) as Hprop.\n                   unfold log_properties_hold_on_ghost_logs in *.\n                   unfold msg_log_property in *.\n                   specialize (Hprop (fun l => contiguous_range_exact_lo l 0) p).\n                   conclude_using ltac:(intros; eapply lifted_entries_contiguous_invariant; eauto).\n                   concludes.\n                   simpl in *.\n\n                   find_copy_eapply_lem_hyp ghost_log_correct_invariant; eauto.\n                   conclude_using eauto.\n                   { intuition.\n                     - subst. find_apply_lem_hyp removeAfterIndex_in.\n                       pose proof lifted_entries_gt_0_invariant _ ltac:(eauto) _ _ ltac:(eauto).\n                       lia.\n                     - break_exists_name gple. break_and.\n                       assert (exists e', eIndex e' = eIndex e /\\ In e' (fst (pBody p))).\n                       {\n                         eapply contiguous_range_exact_lo_elim_exists; eauto.\n                         split.\n                         + eapply lifted_entries_gt_0_invariant; eauto using removeAfterIndex_in.\n                         + eapply Nat.le_trans with (m := eIndex gple); try lia.\n                           apply maxIndex_is_max; auto.\n                           pose proof log_properties_hold_on_ghost_logs_invariant _ ltac:(eauto) as Hsort.\n                           unfold log_properties_hold_on_ghost_logs in *.\n                           unfold msg_log_property in *.\n                           specialize (Hsort sorted p msg_lifted_sorted_host).\n                           auto.\n                       }\n                       break_exists_name e'. break_and.\n                       find_apply_lem_hyp removeAfterIndex_in.\n                       assert (e = e').\n                       {\n                         eapply uniqueIndices_elim_eq;\n                         eauto using msg_lifted_sorted_host, sorted_uniqueIndices.\n                         pose proof ghost_log_entries_match_invariant _ ltac:(eauto) (pDst p) _ ltac:(eauto)\n                           as Hem.\n                         specialize (Hem ple gple e').\n                         repeat concludes.\n                         assert (eIndex e' <= eIndex ple) by lia.\n                         intuition.\n                       }\n                       subst.\n\n\n                       match goal with\n                       | [ H : commit_invariant_nw _ |- _ ] =>\n                         rename H into Hnet; unfold commit_invariant_nw in *\n                       end.\n                       eapply handleAppendEntries_preserves_commit; eauto.\n                       eapply Hnet; eauto using Nat.min_glb_l.\n                   }\n           }\n       + eapply handleAppendEntries_preserves_commit; eauto.\n    - (* nw invariant preserved *)\n      break_and.\n      unfold commit_invariant_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp.\n      intuition.\n      + eapply handleAppendEntries_preserves_commit; eauto.\n        simpl. subst. auto.\n      + subst. simpl in *.\n        find_apply_lem_hyp handleAppendEntries_not_append_entries.\n        subst. exfalso. eauto 10.\n  Qed.\n\n\n  Lemma handleAppendEntriesReply_preserves_commit :\n    forall (net net' : ghost_log_network) h src t es b st' l e t',\n      handleAppendEntriesReply h (snd (nwState net h)) src t es b = (st', l) ->\n      (forall h', nwState net' h' = update name_eq_dec (nwState net) h (fst (nwState net h), st') h') ->\n      lifted_committed net e t' ->\n      lifted_committed net' e t'.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto.\n    - intros. repeat find_higher_order_rewrite. update_destruct_simplify.\n      + now erewrite handleAppendEntriesReply_same_log by eauto.\n      + auto.\n    - intros. repeat find_higher_order_rewrite. update_destruct_simplify; auto.\n  Qed.\n\n  Lemma commit_invariant_append_entries_reply :\n    msg_refined_raft_net_invariant_append_entries_reply commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_append_entries_reply, commit_invariant.\n    simpl. intros.\n    split.\n    - unfold commit_invariant_host in *.\n      simpl. intuition.\n      repeat find_higher_order_rewrite.\n      update_destruct_simplify.\n      + eapply handleAppendEntriesReply_preserves_commit; eauto.\n        match goal with\n        | [ H : context [commitIndex] |- _ ] => erewrite handleAppendEntriesReply_same_commitIndex in H by eauto\n        end.\n        match goal with\n        | [ H : context [log] |- _ ] => erewrite handleAppendEntriesReply_same_log in H by eauto\n        end.\n        eapply lifted_committed_monotonic; [eauto|].\n        find_apply_lem_hyp handleAppendEntriesReply_type_term.\n        intuition; repeat find_rewrite; auto.\n      + eapply handleAppendEntriesReply_preserves_commit; eauto.\n    - unfold commit_invariant_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp.\n      intuition.\n      + eapply handleAppendEntriesReply_preserves_commit; eauto.\n        simpl. subst. auto.\n      + do_in_map. unfold add_ghost_msg in *. do_in_map.\n        subst. simpl in *.\n        find_apply_lem_hyp handleAppendEntriesReply_packets.\n        subst. simpl in *. intuition.\n  Qed.\n\n  Lemma handleRequestVote_preserves_committed :\n    forall (net net' : ghost_log_network) h t c li lt st' ms e t',\n      handleRequestVote h (snd (nwState net h)) t c li lt = (st', ms) ->\n      (forall h', nwState net' h' = update name_eq_dec (nwState net) h (update_elections_data_requestVote h c t c li lt (nwState net h), st') h') ->\n      lifted_committed net e t' ->\n      lifted_committed net' e t'.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto.\n    - intros. find_higher_order_rewrite. update_destruct_simplify.\n      + now erewrite handleRequestVote_same_log by eauto.\n      + auto.\n    - intros. find_higher_order_rewrite. update_destruct_simplify.\n      + now rewrite update_elections_data_requestVote_allEntries.\n      + auto.\n  Qed.\n\n  Lemma commit_invariant_request_vote :\n    msg_refined_raft_net_invariant_request_vote commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_request_vote, commit_invariant.\n    simpl. intuition.\n    - unfold commit_invariant_host in *.\n      simpl. intros.\n      repeat find_higher_order_rewrite.\n      update_destruct_simplify.\n      + eapply handleRequestVote_preserves_committed; eauto.\n        match goal with\n        | [ H : context [commitIndex] |- _ ] => erewrite handleRequestVote_same_commitIndex in H by eauto\n        end.\n        match goal with\n        | [ H : context [log] |- _ ] => erewrite handleRequestVote_same_log in H by eauto\n        end.\n        eapply lifted_committed_monotonic; eauto.\n        find_apply_lem_hyp handleRequestVote_currentTerm_leaderId.\n        intuition.\n        unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n        simpl in *.\n        repeat find_rewrite. auto.\n      + eapply handleRequestVote_preserves_committed; eauto.\n    - unfold commit_invariant_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp. intuition.\n      + eapply handleRequestVote_preserves_committed; eauto.\n        simpl. intros. subst. auto.\n      + subst. simpl in *. unfold write_ghost_log in *.\n        find_apply_lem_hyp handleRequestVote_no_append_entries.\n        subst.\n        exfalso. eauto 10.\n  Qed.\n\n  Lemma handleRequestVoteReply_preserves_committed :\n    forall (net net' : ghost_log_network) h src t v st' e t',\n      handleRequestVoteReply h (snd (nwState net h)) src t v = st' ->\n      (forall h', nwState net' h' = update name_eq_dec (nwState net) h\n                                      (update_elections_data_requestVoteReply h\n                                                                              src t v (nwState net h), st') h') ->\n      lifted_committed net e t' ->\n      lifted_committed net' e t'.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto.\n    - intros. repeat find_higher_order_rewrite. update_destruct_simplify.\n      + erewrite handleRequestVoteReply_log; eauto.\n      + auto.\n    - intros. repeat find_higher_order_rewrite. update_destruct_simplify.\n      + rewrite update_elections_data_requestVoteReply_allEntries. auto.\n      + auto.\n  Qed.\n\n  Lemma commit_invariant_request_vote_reply :\n    msg_refined_raft_net_invariant_request_vote_reply commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_request_vote_reply, commit_invariant.\n    simpl. intuition.\n    - unfold commit_invariant_host in *. simpl. intuition.\n      match goal with\n      | [ H : forall h, st' h = _ |- _ ] => repeat rewrite H in *\n      end. destruct (name_eq_dec (pDst p) h).\n      + subst h. subst gd. rewrite_update. simpl in *.\n        eapply handleRequestVoteReply_preserves_committed; eauto.\n        find_copy_apply_lem_hyp handleRequestVoteReply_type.\n        subst.\n        match goal with\n        | [ H : context [commitIndex] |- _ ] => rewrite handleRequestVoteReply_same_commitIndex in H\n        end.\n        match goal with\n        | [ H : context [log] |- _ ] => erewrite handleRequestVoteReply_same_log in H\n        end.\n        eapply lifted_committed_monotonic; eauto.\n        intuition; repeat find_rewrite; auto.\n      + rewrite_update. eapply handleRequestVoteReply_preserves_committed; eauto.\n        simpl. subst. auto.\n    - unfold commit_invariant_nw. simpl.\n      intros.\n      find_apply_hyp_hyp.\n      eapply handleRequestVoteReply_preserves_committed; eauto.\n      simpl. subst. auto.\n  Qed.\n\n\n  Lemma committed_ext' :\n    forall ps ps' st st' t e,\n      (forall h, st' h = st h) ->\n      committed (mkNetwork ps st) e t ->\n      committed (mkNetwork ps' st') e t.\n  Proof using. \n    unfold committed, directly_committed.\n    simpl. intros.\n    break_exists_exists.\n    find_higher_order_rewrite.\n    intuition.\n    break_exists_exists.  intuition.\n    find_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma lifted_committed_ext' :\n    forall ps ps' st st' t e,\n      (forall h, st' h = st h) ->\n      lifted_committed (mkNetwork ps st) e t ->\n      lifted_committed (mkNetwork ps' st') e t.\n  Proof using rmri. \n    intros.\n    apply committed_lifted_committed.\n    find_apply_lem_hyp lifted_committed_committed.\n    unfold mgv_deghost in *.\n    eauto using committed_ext'.\n  Qed.\n\n  Lemma doLeader_spec :\n    forall st n os st' ms,\n      doLeader st n = (os, st', ms) ->\n      (st' = st /\\ ms = []) \\/\n      (type st = Leader /\\\n       log st' = log st /\\\n       type st' = type st /\\\n       currentTerm st' = currentTerm st /\\\n       nextIndex st' = nextIndex st /\\\n       commitIndex st' = commitIndex (advanceCommitIndex st n) /\\\n       forall m, In m ms ->\n            exists h, h <> n /\\ m = replicaMessage (advanceCommitIndex st n) n h).\n  Proof using. \n    unfold doLeader.\n    intros.\n    destruct st. simpl in *.\n    repeat break_match; repeat find_inversion; simpl in *; eauto.\n    right. intuition.\n    - intros.\n      do_in_map. subst.\n      find_apply_lem_hyp filter_In. break_and.\n      break_if; try discriminate.\n      eexists. intuition eauto.\n    - intuition.\n  Qed.\n\n  Lemma haveQuorum_directly_committed :\n    forall net h e,\n      refined_raft_intermediate_reachable net ->\n      type (snd (nwState net h)) = Leader ->\n      In e (log (snd (nwState net h))) ->\n      haveQuorum (snd (nwState net h)) h (eIndex e) = true ->\n      eTerm e = currentTerm (snd (nwState net h)) ->\n      directly_committed net e.\n  Proof using miaei. \n    unfold haveQuorum, directly_committed.\n    intros. do_bool.\n    eexists. intuition eauto.\n    - apply filter_NoDup. pose proof no_dup_nodes. simpl in *. auto.\n    - find_apply_lem_hyp filter_In. break_and. do_bool.\n      eapply match_index_all_entries_invariant; eauto.\n  Qed.\n\n  Lemma advanceCommitIndex_committed :\n    forall h net,\n      refined_raft_intermediate_reachable net ->\n      type (snd (nwState net h)) = Leader ->\n      (forall e, In e (log (snd (nwState net h))) ->\n            eIndex e <= commitIndex (snd (nwState net h)) ->\n            committed net e (currentTerm (snd (nwState net h)))) ->\n      (forall e, In e (log (snd (nwState net h))) ->\n            eIndex e <= commitIndex (advanceCommitIndex (snd (nwState net h)) h) ->\n            committed net e (currentTerm (snd (nwState net h)))).\n  Proof using miaei. \n    unfold advanceCommitIndex.\n    intros. simpl in *.\n    match goal with\n    | [ H : context [fold_left Nat.max ?l ?x] |- _ ] =>\n      pose proof fold_left_maximum_cases l x\n    end. intuition.\n    break_exists. break_and.\n    find_apply_lem_hyp in_map_iff.\n    break_exists_name witness. break_and.\n    find_apply_lem_hyp filter_In.  break_and.\n    find_apply_lem_hyp findGtIndex_necessary. do_bool. break_and. do_bool. break_and.\n    do_bool.\n    unfold committed.\n    exists h, witness. intuition.\n    eapply haveQuorum_directly_committed; eauto.\n  Qed.\n\n  Lemma lifted_advanceCommitIndex_lifted_committed :\n    forall h net,\n      msg_refined_raft_intermediate_reachable net ->\n      type (snd (nwState net h)) = Leader ->\n      (forall e, In e (log (snd (nwState net h))) ->\n            eIndex e <= commitIndex (snd (nwState net h)) ->\n            lifted_committed net e (currentTerm (snd (nwState net h)))) ->\n      (forall e, In e (log (snd (nwState net h))) ->\n            eIndex e <= commitIndex (advanceCommitIndex (snd (nwState net h)) h) ->\n            lifted_committed net e (currentTerm (snd (nwState net h)))).\n  Proof using rmri miaei. \n    intros.\n    find_apply_lem_hyp msg_simulation_1.\n    match goal with\n    | [ H : refined_raft_intermediate_reachable _ |- _ ] =>\n      eapply advanceCommitIndex_committed in H\n    end;\n      repeat rewrite msg_deghost_spec' in *;\n      eauto using committed_lifted_committed, lifted_committed_committed.\n  Qed.\n\n  Lemma and_imp_2 :\n    forall P Q : Prop,\n      P /\\ (P -> Q) -> P /\\ Q.\n  Proof using. \n    tauto.\n  Qed.\n\n  Definition lifted_leaders_have_leaderLogs_strong (net : ghost_log_network) :=\n    forall h,\n      type (snd (nwState net h)) = Leader ->\n      exists ll es,\n        In (currentTerm (snd (nwState net h)), ll) (leaderLogs (fst (nwState net h))) /\\\n        log (snd (nwState net h)) = es ++ ll /\\\n        (forall e : entry, In e es -> eTerm e = currentTerm (snd (nwState net h))).\n\n  Lemma lifted_leaders_have_leaderLogs_strong_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_leaders_have_leaderLogs_strong net.\n  Proof using rmri lhllsi. \n    unfold lifted_leaders_have_leaderLogs_strong.\n    intros.\n    pose proof msg_lift_prop _ leaders_have_leaderLogs_strong_invariant _ ltac:(eauto) h.\n    rewrite msg_deghost_spec' in *. auto.\n  Qed.\n\n  Definition lifted_one_leaderLog_per_term (net : ghost_log_network) : Prop :=\n    forall h h' t ll ll',\n      In (t, ll) (leaderLogs (fst (nwState net h))) ->\n      In (t, ll') (leaderLogs (fst (nwState net h'))) ->\n      h = h' /\\ ll = ll'.\n\n  Lemma lifted_one_leaderLog_per_term_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_one_leaderLog_per_term net.\n  Proof using rmri ollpti. \n    unfold lifted_one_leaderLog_per_term.\n    intros.\n    pose proof msg_lift_prop _ one_leaderLog_per_term_invariant _ ltac:(eauto) h h' t ll ll'.\n    repeat rewrite msg_deghost_spec' in *. auto.\n  Qed.\n\n  Lemma lifted_leaderLog_in_log :\n    forall net leader ll e,\n      msg_refined_raft_intermediate_reachable net ->\n      type (snd (nwState net leader)) = Leader ->\n      In (currentTerm (snd (nwState net leader)), ll) (leaderLogs (fst (nwState net leader))) ->\n      In e ll ->\n      In e (log (snd (nwState net leader))).\n  Proof using rmri ollpti lhllsi. \n    intros.\n\n    find_copy_apply_lem_hyp lifted_leaders_have_leaderLogs_strong_invariant; auto.\n\n    break_exists_name ll'.\n    break_exists_name es.\n    break_and.\n    find_eapply_lem_hyp (lifted_one_leaderLog_per_term_invariant _ ltac:(eauto) leader leader _ ll ll' ltac:(eauto)).\n    intuition. subst.\n    unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n    simpl in *.\n    repeat find_rewrite. intuition.\n  Qed.\n\n  Definition lifted_leaders_have_leaderLogs (net : ghost_log_network) : Prop :=\n    forall h,\n      type (snd (nwState net h)) = Leader ->\n      exists ll,\n        In (currentTerm (snd (nwState net h)), ll) (leaderLogs (fst (nwState net h))).\n  Lemma lifted_leaders_have_leaderLogs_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_leaders_have_leaderLogs net.\n  Proof using rmri lhlli. \n    intros.\n    pose proof msg_lift_prop _ leaders_have_leaderLogs_invariant _ ltac:(eauto).\n    unfold leaders_have_leaderLogs, lifted_leaders_have_leaderLogs in *.\n    intros.\n    match goal with\n    | [ H : _ |- _ ] => specialize (H h)\n    end.\n    repeat find_rewrite_lem msg_deghost_spec.\n    auto.\n  Qed.\n\n\n  Definition lifted_leader_completeness_directly_committed (net : ghost_log_network) : Prop :=\n    forall t e log h,\n      lifted_directly_committed net e ->\n      t > eTerm e -> In (t, log) (leaderLogs (fst (nwState net h))) -> In e log.\n\n  Definition lifted_leader_completeness_committed (net : ghost_log_network) : Prop :=\n    forall t t' e log h,\n      lifted_committed net e t ->\n      t' > t -> In (t', log) (leaderLogs (fst (nwState net h))) -> In e log.\n\n  Definition lifted_leader_completeness (net : ghost_log_network) : Prop :=\n    lifted_leader_completeness_directly_committed net /\\\n    lifted_leader_completeness_committed net.\n\n  Lemma lifted_leader_completeness_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_leader_completeness net.\n  Proof using rmri lci. \n    intros.\n    pose proof msg_lift_prop _ leader_completeness_invariant _ ltac:(eauto).\n    unfold lifted_leader_completeness, leader_completeness in *.\n    intuition.\n    - unfold lifted_leader_completeness_directly_committed, leader_completeness_directly_committed in *.\n      intros.\n      find_apply_lem_hyp lifted_directly_committed_directly_committed.\n      eapply_prop_hyp directly_committed directly_committed; eauto.\n      rewrite msg_deghost_spec'. eauto.\n    - unfold lifted_leader_completeness_committed, leader_completeness_committed in *.\n      intros.\n      find_apply_lem_hyp lifted_committed_committed.\n      eapply_prop_hyp committed committed; eauto.\n      rewrite msg_deghost_spec'. eauto.\n  Qed.\n\n  Definition msg_lifted_leader_sublog_host (net : ghost_log_network) : Prop :=\n    forall leader e h,\n      type (snd (nwState net leader)) = Leader ->\n      In e (log (snd (nwState net h))) ->\n      eTerm e = currentTerm (snd (nwState net leader)) ->\n      In e (log (snd (nwState net leader))).\n\n  Lemma msg_lifted_leader_sublog_host_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      msg_lifted_leader_sublog_host net.\n  Proof using rmri lsi rri. \n    intros.\n    pose proof msg_lift_prop _ (lift_prop _ leader_sublog_invariant_invariant) _ ltac:(eauto).\n    simpl in *.\n    unfold leader_sublog_invariant, leader_sublog_host_invariant, msg_lifted_leader_sublog_host in *.\n    intuition.\n    match goal with\n    | [ H : _ |- _ ] =>\n      specialize (H leader e h)\n    end.\n    repeat find_rewrite_lem deghost_spec.\n    repeat find_rewrite_lem msg_deghost_spec.\n    auto.\n  Qed.\n\n  Lemma lifted_entries_match_invariant :\n    forall net h h',\n      msg_refined_raft_intermediate_reachable net ->\n      entries_match (log (snd (nwState net h))) (log (snd (nwState net h'))).\n  Proof using rmri rlmli. \n    intros.\n    find_apply_lem_hyp msg_simulation_1.\n    find_eapply_lem_hyp entries_match_invariant.\n    repeat rewrite msg_deghost_spec' in *.\n    eauto.\n  Qed.\n\n  Lemma lifted_terms_and_indices_from_one_log : forall net h,\n    refined_raft_intermediate_reachable net ->\n    terms_and_indices_from_one (log (snd (nwState net h))).\n  Proof using taifoli rri. \n    intros net0;intros.\n    pose proof (lift_prop _ terms_and_indices_from_one_log_invariant).\n    unfold terms_and_indices_from_one_log in *.\n    rewrite <- deghost_spec with (net := net0). auto.\n  Qed.\n\n\n  Lemma doLeader_preserves_committed :\n    forall (net net' : ghost_log_network) d h os d' ms gd  e t,\n      doLeader d h = (os, d', ms) ->\n      nwState net h = (gd, d) ->\n      (forall h', nwState net' h' = update name_eq_dec (nwState net) h (gd, d') h') ->\n      lifted_committed net e t ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto;\n    intros; find_higher_order_rewrite; update_destruct_simplify.\n    - intros. find_higher_order_rewrite.\n      erewrite doLeader_same_log; eauto.\n    - auto.\n    - repeat find_rewrite. auto.\n    - auto.\n  Qed.\n\n  Lemma doLeader_message_lci :\n    forall st h os st' ms m t n pli plt es ci,\n      doLeader st h = (os, st', ms) ->\n      In m ms ->\n      snd m = AppendEntries t n pli plt es ci ->\n      ci = commitIndex st'.\n  Proof using. \n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; intuition.\n    do_in_map.\n    unfold replicaMessage in *.\n    simpl in *.\n    repeat break_match; repeat find_inversion; subst; simpl in *;\n    repeat find_inversion; auto.\n  Qed.\n\n  Lemma doLeader_message_term :\n    forall st h os st' ms m t n pli plt es ci,\n      doLeader st h = (os, st', ms) ->\n      In m ms ->\n      snd m = AppendEntries t n pli plt es ci ->\n      t = currentTerm st'.\n  Proof using. \n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; intuition.\n    do_in_map.\n    subst.\n    unfold replicaMessage in *. simpl in *.\n    find_inversion.\n    auto.\n  Qed.\n\n\n  Lemma commit_invariant_do_leader :\n    forall net st' ps' gd d h os d' ms,\n      doLeader d h = (os, d', ms) ->\n      commit_invariant net ->\n      msg_refined_raft_intermediate_reachable net ->\n      lifted_maxIndex_sanity net ->\n      nwState net h = (gd, d) ->\n      (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d') h') ->\n      (forall p,\n          In p ps' -> In p (nwPackets net) \\/ In p (send_packets h (add_ghost_msg (msg_ghost_params := ghost_log_params) h (gd, d') ms))) ->\n      commit_invariant {| nwPackets := ps'; nwState := st' |}.\n  Proof using rmri miaei. \n    unfold commit_invariant.\n    simpl. intros. break_and.\n    apply and_imp_2.\n    split.\n    - find_apply_lem_hyp doLeader_spec. break_or_hyp.\n      + break_and.\n        unfold commit_invariant_host in *. simpl. intros. repeat find_higher_order_rewrite.\n        eapply lifted_committed_ext' with (ps := nwPackets net) (st := nwState net).\n        * intros. subst. repeat find_higher_order_rewrite.\n          match goal with\n          | [ |- context [ update _ _ ?x _ ?y ] ] =>\n            destruct (name_eq_dec x y); subst; rewrite_update\n          end; auto.\n        * match goal with\n          | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n            replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n              replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n              clear H\n          end.\n          destruct net. simpl in *. auto.\n          update_destruct_simplify; auto.\n      + break_and.\n        unfold commit_invariant_host in *.\n        simpl. intros. repeat find_higher_order_rewrite.\n        match goal with\n        | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n          replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n            replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n            clear H\n        end.\n        match goal with\n        | [ H : context [ update _ _ ?x _ ?y ] |- _ ] =>\n          destruct (name_eq_dec x y); subst; rewrite_update\n        end.\n        * { eapply lifted_committed_log_allEntries_preserved.\n            - simpl. find_rewrite. eapply lifted_advanceCommitIndex_lifted_committed; auto.\n              + simpl in *. repeat find_rewrite. auto.\n              + simpl in *. repeat find_rewrite. auto.\n            - simpl. intros. find_higher_order_rewrite.\n              update_destruct_simplify.\n              + repeat find_rewrite. auto.\n              + auto.\n            - simpl. intros. find_higher_order_rewrite.\n              update_destruct_simplify; auto.\n          }\n        * { eapply lifted_committed_log_allEntries_preserved; eauto.\n            + simpl. intros. find_higher_order_rewrite. update_destruct_simplify; repeat find_rewrite; auto.\n            + simpl. intros. find_higher_order_rewrite. update_destruct_simplify; repeat find_rewrite; auto.\n          }\n    - intros Hhostpost.\n      unfold commit_invariant_nw in *.\n      simpl. intros.\n      find_apply_hyp_hyp.\n      intuition.\n      + (* old packet *)\n        eapply_prop_hyp In In; eauto.\n        eauto using doLeader_preserves_committed.\n      + (* new packet *)\n        do_in_map. subst. simpl in *.\n        unfold add_ghost_msg in *.\n        do_in_map. subst. simpl in *.\n        find_copy_eapply_lem_hyp doLeader_message_lci; eauto.\n        find_copy_eapply_lem_hyp doLeader_message_term; eauto.\n        unfold write_ghost_log in *.\n        simpl in *.\n        unfold commit_invariant_host in *.\n        simpl in *.\n        specialize (Hhostpost h e).\n        subst.\n        repeat find_higher_order_rewrite.\n        repeat rewrite_update.\n        simpl in *.\n        intuition.\n  Qed.\n\n  Lemma doGenericServer_preserves_committed :\n    forall (net net' : ghost_log_network) h out st' ms e t,\n      doGenericServer h (snd (nwState net h)) = (out, st', ms) ->\n      (forall h', nwState net' h' = update name_eq_dec (nwState net) h (fst (nwState net h), st') h') ->\n      lifted_committed net e t ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto;\n    intros; repeat find_higher_order_rewrite; update_destruct_simplify; auto.\n    now erewrite doGenericServer_log by eauto.\n  Qed.\n\n  Lemma commit_invariant_do_generic_server :\n    msg_refined_raft_net_invariant_do_generic_server commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_do_generic_server, commit_invariant.\n    simpl. intros.\n    match goal with\n    | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n      replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n        replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n        clear H\n    end.\n    intuition.\n    - unfold commit_invariant_host in *.\n      simpl. intros.\n      repeat find_higher_order_rewrite.\n\n      update_destruct_simplify.\n      + eapply doGenericServer_preserves_committed; eauto.\n        match goal with\n        | [ H : context [commitIndex] |- _ ] => erewrite doGenericServer_commitIndex  in H  by eauto\n        end.\n        match goal with\n        | [ H : context [log] |- _ ] => erewrite doGenericServer_log in H by eauto\n        end.\n        eapply lifted_committed_monotonic; eauto.\n        find_apply_lem_hyp doGenericServer_type.\n        intuition. repeat find_rewrite. auto.\n      + eapply doGenericServer_preserves_committed; eauto.\n    - unfold commit_invariant_nw in *.\n      simpl. intuition.\n      + find_apply_hyp_hyp. intuition.\n        * eapply doGenericServer_preserves_committed; eauto.\n        * do_in_map. unfold add_ghost_msg in *. do_in_map.\n          find_apply_lem_hyp doGenericServer_packets.\n          subst. simpl in *. intuition.\n  Qed.\n\n  Lemma commit_invariant_state_same_packet_subset :\n    msg_refined_raft_net_invariant_state_same_packet_subset commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_state_same_packet_subset, commit_invariant.\n    intuition.\n    - unfold commit_invariant_host in *. intros.\n      repeat find_reverse_higher_order_rewrite.\n      destruct net, net'. simpl in *.\n      eapply lifted_committed_ext; [|eauto]. simpl. auto.\n    - unfold commit_invariant_nw in *. intros.\n      find_apply_hyp_hyp.\n      destruct net, net'. simpl in *.\n      eapply lifted_committed_ext'; [|eauto]. auto.\n  Qed.\n\n  Lemma reboot_preserves_committed :\n    forall (net net' : ghost_log_network) h e t,\n      (forall h', nwState net' h' = update name_eq_dec (nwState net) h (fst (nwState net h), reboot (snd (nwState net h))) h') ->\n      lifted_committed net e t ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    unfold reboot.\n    intros.\n    eapply lifted_committed_log_allEntries_preserved; eauto;\n    intros; repeat find_higher_order_rewrite; update_destruct_simplify; auto.\n  Qed.\n\n  Lemma commit_invariant_reboot :\n    msg_refined_raft_net_invariant_reboot commit_invariant.\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_reboot, commit_invariant.\n    intros.\n    match goal with\n    | [ H : nwState ?net ?h = (?x, ?y) |- _ ] =>\n      replace x with (fst (nwState net h)) in * by (rewrite H; auto);\n        replace y with (snd (nwState net h)) in * by (rewrite H; auto);\n        clear H\n    end.\n    intuition.\n    - unfold commit_invariant_host in *.\n      intros. repeat find_higher_order_rewrite.\n      update_destruct_simplify; eapply reboot_preserves_committed; eauto.\n    - unfold commit_invariant_nw in *.\n      intros.\n      unfold mgv_refined_base_params, raft_refined_base_params, refined_base_params in *.\n      simpl in *.\n      repeat find_reverse_rewrite.\n      eapply reboot_preserves_committed; eauto.\n  Qed.\n\n  Lemma maxIndex_sanity_lift :\n    forall net,\n      maxIndex_sanity (deghost (mgv_deghost net)) ->\n      lifted_maxIndex_sanity net.\n  Proof using rmri rri. \n    unfold maxIndex_sanity, lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intros. intuition;\n    repeat match goal with\n      | [ H : forall _, _, h : Net.name |- _ ] => specialize (H h)\n    end;\n    repeat find_rewrite_lem deghost_spec;\n    repeat find_rewrite_lem msg_deghost_spec;\n    auto.\n  Qed.\n\n  Lemma maxIndex_sanity_lower :\n    forall net,\n      lifted_maxIndex_sanity net ->\n      maxIndex_sanity (deghost (mgv_deghost net)).\n  Proof using rri. \n    unfold maxIndex_sanity, lifted_maxIndex_sanity, maxIndex_lastApplied, maxIndex_commitIndex.\n    intuition; rewrite deghost_spec; rewrite msg_deghost_spec';\n    repeat match goal with\n             | [ H : forall _, _, h : Net.name |- _ ] => specialize (H h)\n           end; intuition.\n  Qed.\n\n  Definition everything (net : ghost_log_network) : Prop :=\n    lifted_maxIndex_sanity net /\\\n    commit_invariant net /\\\n    state_machine_safety (deghost (mgv_deghost net)).\n\n  Lemma everything_init :\n    msg_refined_raft_net_invariant_init everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_init, everything.\n    intuition.\n    - apply lifted_maxIndex_sanity_init.\n    - apply commit_invariant_init.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed; [constructor|].\n        apply commit_invariant_init.\n      + apply state_machine_safety'_invariant.\n        constructor.\n  Qed.\n\n  Lemma everything_client_request :\n    msg_refined_raft_net_invariant_client_request' everything.\n  Proof using rmri lalcii smspi si rri. \n    unfold msg_refined_raft_net_invariant_client_request', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_client_request; eauto.\n    - eapply commit_invariant_client_request; eauto.\n      + auto using maxIndex_sanity_lower.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed; auto.\n        eapply commit_invariant_client_request; eauto.\n        apply maxIndex_sanity_lower. auto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_timeout :\n    msg_refined_raft_net_invariant_timeout' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_timeout', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_timeout; eauto.\n    - eapply commit_invariant_timeout; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_timeout; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_append_entries :\n    msg_refined_raft_net_invariant_append_entries' everything.\n  Proof using rmri tsi glemi lphogli glci lalcii rlmli smspi si rri. \n    unfold msg_refined_raft_net_invariant_append_entries', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_append_entries; eauto.\n      intros.\n      find_apply_hyp_hyp.\n      intuition.\n      right.\n      subst.\n      unfold mgv_deghost_packet. auto.\n    - eapply commit_invariant_append_entries; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_append_entries; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_append_entries_reply :\n    msg_refined_raft_net_invariant_append_entries_reply' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_append_entries_reply', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_append_entries_reply; eauto.\n    - eapply commit_invariant_append_entries_reply; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_append_entries_reply; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_request_vote :\n    msg_refined_raft_net_invariant_request_vote' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_request_vote', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_request_vote; eauto.\n    - eapply commit_invariant_request_vote; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_request_vote; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_request_vote_reply :\n    msg_refined_raft_net_invariant_request_vote_reply' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_request_vote_reply', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_request_vote_reply; eauto.\n    - eapply commit_invariant_request_vote_reply; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_request_vote_reply; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_do_leader :\n    msg_refined_raft_net_invariant_do_leader' everything.\n  Proof using rmri miaei lalcii smspi si rri. \n    unfold msg_refined_raft_net_invariant_do_leader', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_do_leader; eauto.\n    - eapply commit_invariant_do_leader; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_do_leader; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma everything_do_generic_server :\n    msg_refined_raft_net_invariant_do_generic_server' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_do_generic_server', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_do_generic_server; eauto.\n    - eapply commit_invariant_do_generic_server; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_do_generic_server; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Lemma directly_committed_state_same :\n    forall net net' e,\n      (forall h, nwState net' h = nwState net h) ->\n      directly_committed net e ->\n      directly_committed net' e.\n  Proof using. \n    unfold directly_committed.\n    intuition.\n    break_exists_exists.\n    intuition.\n    find_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma lifted_committed_state_same :\n    forall (net net' : ghost_log_network) e t,\n      (forall h, nwState net' h = nwState net h) ->\n      lifted_committed net e t ->\n      lifted_committed net' e t.\n  Proof using rmri. \n    intuition.\n    destruct net, net'.\n    simpl in *.\n    eapply lifted_committed_ext'; eauto.\n  Qed.\n\n  Lemma exists_in_mgv_deghost_packet :\n    forall (p : packet (params := raft_refined_multi_params)) (net : ghost_log_network),\n      In p (nwPackets (mgv_deghost net)) ->\n      exists q,\n        In q (nwPackets net) /\\\n        pDst q = pDst p /\\\n        pSrc q = pSrc p /\\\n        snd (pBody q) = pBody p.\n  Proof using. \n    unfold mgv_deghost.\n    simpl.\n    intros.\n    do_in_map.\n    subst. simpl.\n    eauto.\n  Qed.\n\n  Lemma state_machine_safety'_state_same_packet_subset :\n    msg_refined_raft_net_invariant_state_same_packet_subset\n      (fun net : ghost_log_network =>  state_machine_safety' (mgv_deghost net)).\n  Proof using rmri. \n    unfold msg_refined_raft_net_invariant_state_same_packet_subset, state_machine_safety'.\n    intuition.\n    - unfold state_machine_safety_host' in *. intuition.\n      repeat find_apply_lem_hyp committed_lifted_committed.\n      eauto 6 using lifted_committed_committed, lifted_committed_state_same.\n    - unfold state_machine_safety_nw' in *. intuition.\n\n      find_apply_lem_hyp exists_in_mgv_deghost_packet. break_exists. break_and.\n      find_apply_hyp_hyp.\n      find_apply_lem_hyp in_mgv_ghost_packet.\n      match goal with\n      | [ H : context [ pBody ] |- _ ] =>\n        eapply H; eauto\n      end.\n      + rewrite pBody_mgv_deghost_packet. repeat find_rewrite. eauto.\n      + apply lifted_committed_committed.\n        eapply lifted_committed_state_same; eauto using committed_lifted_committed.\n  Qed.\n\n  Lemma CRC_state_same_packet_subset :\n    msg_refined_raft_net_invariant_state_same_packet_subset\n      (fun net : ghost_log_network => commit_recorded_committed (mgv_deghost net)).\n  Proof using rri. \n    unfold msg_refined_raft_net_invariant_state_same_packet_subset, commit_recorded_committed,\n           commit_recorded, committed, directly_committed.\n    intros.\n    specialize (H1 h e).\n    repeat find_rewrite_lem deghost_spec.\n    repeat find_rewrite_lem msg_deghost_spec'.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp.\n    break_exists_exists.\n    repeat find_rewrite_lem msg_deghost_spec'.\n    repeat rewrite msg_deghost_spec'.\n    repeat find_higher_order_rewrite.\n    intuition.\n    break_exists_exists.\n    intuition.\n    find_apply_hyp_hyp.\n    repeat find_rewrite_lem msg_deghost_spec'.\n    repeat rewrite msg_deghost_spec'.\n    repeat find_higher_order_rewrite.\n    auto.\n  Qed.\n\n  Lemma everything_state_same_packet_subset :\n    msg_refined_raft_net_invariant_state_same_packet_subset' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_state_same_packet_subset', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_state_same_packet_subset; eauto.\n    - eapply commit_invariant_state_same_packet_subset; eauto.\n    - apply state_machine_safety_deghost.\n      + eapply CRC_state_same_packet_subset; eauto.\n        apply commit_invariant_lower_commit_recorded_committed; auto.\n\n      + eapply state_machine_safety'_state_same_packet_subset; eauto.\n        auto using state_machine_safety'_invariant, msg_simulation_1.\n  Qed.\n\n  Lemma everything_reboot :\n    msg_refined_raft_net_invariant_reboot' everything.\n  Proof using rmri lalcii smspi rri. \n    unfold msg_refined_raft_net_invariant_reboot', everything.\n    intuition.\n    - eapply lifted_maxIndex_sanity_reboot; eauto.\n    - eapply commit_invariant_reboot; eauto.\n    - apply state_machine_safety_deghost.\n      + apply commit_invariant_lower_commit_recorded_committed. auto.\n        eapply commit_invariant_reboot; eauto.\n      + apply state_machine_safety'_invariant. auto using msg_simulation_1.\n  Qed.\n\n  Theorem everything_invariant :\n    forall net,\n      msg_refined_raft_intermediate_reachable net ->\n      everything net.\n  Proof using rmri tsi glemi lphogli glci miaei lalcii rlmli smspi si rri. \n    intros.\n    apply msg_refined_raft_net_invariant'; auto.\n    - apply everything_init.\n    - apply everything_client_request.\n    - apply everything_timeout.\n    - apply everything_append_entries.\n    - apply everything_append_entries_reply.\n    - apply everything_request_vote.\n    - apply everything_request_vote_reply.\n    - apply everything_do_leader.\n    - apply everything_do_generic_server.\n    - apply everything_state_same_packet_subset.\n    - apply everything_reboot.\n  Qed.\n\n  Theorem state_machine_safety_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      state_machine_safety net.\n  Proof using rmri tsi glemi lphogli glci miaei lalcii rlmli smspi si rri. \n    intros.\n    apply lower_prop; intros; auto.\n    apply msg_lower_prop with (P := fun net => _ (deghost net)); intros; auto.\n    find_apply_lem_hyp everything_invariant.\n    unfold everything in *. intuition.\n  Qed.\n\n  Theorem maxIndex_sanity_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      maxIndex_sanity net.\n  Proof using rmri tsi glemi lphogli glci miaei lalcii rlmli smspi si rri. \n    intros.\n    apply lower_prop; intros; eauto.\n    apply msg_lower_prop with (P := fun net => _ (deghost net)); intros; auto.\n    find_apply_lem_hyp everything_invariant.\n    unfold everything in *. intuition.\n    auto using maxIndex_sanity_lower.\n  Qed.\n\n  Theorem commit_recorded_committed_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      commit_recorded_committed net.\n  Proof using rmri tsi glemi lphogli glci miaei lalcii rlmli smspi si rri. \n    intros.\n    apply msg_lower_prop; intros; auto.\n    find_copy_apply_lem_hyp everything_invariant.\n    unfold everything in *.\n    intuition.\n    auto using commit_invariant_lower_commit_recorded_committed.\n  Qed.\n\n  Instance smsi : state_machine_safety_interface.\n  Proof.\n    split.\n    exact state_machine_safety_invariant.\n  Qed.\n\n  Instance misi : max_index_sanity_interface.\n  Proof.\n    split.\n    exact maxIndex_sanity_invariant.\n  Qed.\n\n  Instance crci : commit_recorded_committed_interface.\n  Proof.\n    split.\n    intros.\n    find_apply_lem_hyp commit_recorded_committed_invariant.\n    unfold commit_invariant, commit_recorded_committed, commit_recorded in *.\n    intros.\n    find_rewrite_lem (deghost_spec net h).\n    intuition;\n    repeat match goal with\n             | [ H : forall _, _, h : entry |- _ ] => specialize (H h)\n             | [ H : forall _, _, h : Net.name |- _ ] => specialize (H h)\n           end;\n    repeat find_rewrite_lem deghost_spec; auto.\n  Qed.\nEnd StateMachineSafetyProof.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft-proofs/StateMachineSafetyProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.23869078726546258}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Adam Koprowski, 2006-04-27\n\nSome computability results instantiated for horpo.\n*)\n\nSet Implicit Arguments.\n\nFrom CoLoR Require Import RelExtras ListExtras Computability Horpo.\nFrom Coq Require Import Setoid Morphisms.\n\nModule HorpoComp (S : TermsSig.Signature)\n  (Prec : Horpo.Precedence with Module S := S).\n\n  Module Export Comp := Computability.Computability S Prec.\n\n  Import List.\n\n  Definition horpo_lt := transp horpo.\n  Definition horpo_mul_lt := MultisetLT horpo.\n  \n  Notation \"X << Y\" := (horpo_lt X Y) (at level 55).\n  Definition Htrans := clos_trans horpo.\n\n  Definition Terms := list Term.\n  Definition CompH := Computable horpo.\n  Definition CompTerms (Ts: Terms) := AllComputable horpo Ts.\n  Definition CompSubst (G: Subst) := forall Q, In (Some Q) G -> CompH Q.\n\n  Definition WFterms := { Ts: Terms | CompTerms Ts }.\n  Definition WFterms_to_mul (Ts: WFterms) := list2multiset (proj1_sig Ts).\n  Coercion WFterms_to_mul: WFterms >-> Multiset.\n  Definition H_WFterms_lt (M N: WFterms) := horpo_mul_lt M N.\n\n  #[global] Hint Unfold horpo_lt horpo_mul_lt CompH CompTerms : horpo.\n\n  Lemma horpo_comp_imp_acc M : CompH M -> AccR horpo M.\n\n  Proof. intro Mcomp. apply comp_imp_acc; eauto with horpo. Qed.\n\n  Lemma horpo_comp_step_comp M N : CompH M -> M >> N -> CompH N.\n\n  Proof.\n    intros Mcomp MN.\n    unfold CompH; apply comp_step_comp with M; eauto with horpo.\n  Qed.\n\n  Lemma horpo_comp_manysteps_comp M N : CompH M -> M >>* N -> CompH N.\n\n  Proof.\n    intros Mcomp M_N.\n    unfold CompH; apply comp_manysteps_comp with M; eauto with horpo.\n  Qed.\n\n  Lemma horpo_comp_pflat N Ns : isPartialFlattening Ns N -> algebraic N ->\n    AllComputable horpo Ns -> CompH N.\n\n  Proof.\n    intros NsN Nnorm NsC; unfold CompH. apply comp_pflat with Ns; trivial.\n  Qed.\n\n  Lemma horpo_neutral_comp_step : forall M, algebraic M -> isNeutral M ->\n    (CompH M <-> (forall N, M >> N -> CompH N)).\n\n  Proof.\n    intros M Mneutral; unfold CompH.\n    apply neutral_comp_step; eauto with horpo.\n  Qed.\n\n  Lemma CompH_morph_aux : forall x1 x2 : Term, x1 ~ x2 -> CompH x1 -> CompH x2.\n\n  Proof.\n    intros t t' teqt' H_t.\n    unfold CompH.\n    apply Computable_morph_aux with t; eauto with horpo.\n  Qed.\n\n  Global Instance CompH_morph : Proper (terms_conv ==> iff) CompH.\n\n  Proof.\n    intros; split; apply CompH_morph_aux; auto using terms_conv_sym.\n  Qed.\n\n  Lemma horpo_comp_conv: forall M M', CompH M -> M ~ M' -> CompH M'.\n\n  Proof. intros. rewrite <- H0; trivial. Qed.\n\n  Lemma horpo_var_comp : forall M, isVar M -> CompH M.\n\n  Proof.\n    intros M Mvar; unfold CompH. apply var_comp; eauto with horpo.\n  Qed.\n\n  Lemma horpo_comp_abs : forall M (Mabs: isAbs M), algebraic M ->\n    (forall G (cs: correct_subst (absBody Mabs) G) T, \n      isSingletonSubst T G -> CompH T ->\n      CompH (subst cs)) -> CompH M.\n\n  Proof.\n    intros M Mnorm Mabs H; unfold CompH. eapply comp_abs; eauto with horpo.\n  Qed.\n\n  Lemma horpo_comp_lift : forall N, CompH N -> CompH (lift N 1).\n\n  Proof.\n    intros.\n    setoid_replace (lift N 1) with N using relation terms_conv; trivial.\n    apply terms_conv_sym; apply terms_lift_conv.\n  Qed.\n\n  Lemma horpo_comp_app : forall M (Mapp: isApp M), \n    CompH (appBodyL Mapp) -> CompH (appBodyR Mapp) -> CompH M.\n\n  Proof.\n    intros M Mapp Ml Mr; unfold CompH. apply comp_app with Mapp; trivial.\n  Qed.\n\n  Lemma horpo_comp_algebraic : forall M, CompH M -> algebraic M.\n\n  Proof. intros. apply comp_algebraic with horpo; trivial. Qed.\n\n  Lemma horpo_comp_units_comp M :\n    (forall N, isAppUnit N M -> CompH N) -> CompH M.\n\n  Proof. intro Munits; unfold CompH. apply comp_units_comp; trivial. Qed.\n\nEnd HorpoComp.\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/HORPO/HorpoComp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23859554393525112}}
{"text": "Require Import Libs.\nRequire Import AST.\nRequire Import Setoid.\nRequire Import Memory.\nRequire Import ArithClasses.\nRequire Import Memtype.\nRequire Import Memdata.\nRequire Import Values.\nRequire Import Relation_Operators.\nRequire Import Operators_Properties.\nRequire Import Morphisms.\nSet Implicit Agruments.\n  \n\nTactic Notation \"rewrite_Heq_do\" :=\n  repeat\n    match goal with\n      | H : ?TRM = Some _ |- context[?TRM] =>\n        rewrite H\n      | H : ?TRM = None |- context[?TRM] =>\n        rewrite H\n    end; simpl_do.\n\n\n\nModule ExtraLemma(CM:MEM).\n  Lemma load_store: forall (m1 m2 m1' m2': CM.mem) mc b i v,\n    CM.store mc m1 b i v = Some m1' ->\n    CM.store mc m2 b i v = Some m2' ->\n    CM.load mc m1' b i = CM.load mc m2' b i.\n  Proof.\n    intros * STORE1 STORE2.\n    edestruct (CM.load_store_similar _ _ _ _ _ _ STORE1) as [v1 [LOAD1 _]]; eauto.\n    edestruct (CM.load_store_similar _ _ _ _ _ _ STORE2) as [v2 [LOAD2 ?]]; eauto.\n    rewrite LOAD1, LOAD2.\n    apply CM.load_loadbytes in LOAD1.\n    apply CM.load_loadbytes in LOAD2.\n    destruct LOAD1 as [bytes1 [LB1 DEC1]].\n    destruct LOAD2 as [bytes2 [LB2 DEC2]].\n    pose proof (CM.loadbytes_store_same _ _ _ _ _ _ STORE1).\n    pose proof (CM.loadbytes_store_same _ _ _ _ _ _ STORE2).\n    congruence.\n  Qed.\nEnd ExtraLemma.\n\n\nRequire Import Cminor.\n\n\nModule FromCminorEnv(N:NUMERICAL)(CM:MEM)<:(BASEMEM(N)).\n  Import N.\n  Existing Instance Numerical_Num.\n\n\n  (* we define a way to inject the memory model of Cminor inside the\n     one of Loops, modulo a reasonable expression of the result of an\n     alias analysis *)\n\n  Module EL := ExtraLemma(CM).\n  Hint Resolve EL.load_store.\n\n\n  (* a pointer is a block and an offset *)\n  Definition ptr := (block * int)%type.\n\n  (* it can be directly injected inside Cminor values *)\n  Definition val_of_ptr (p:ptr) : val:=\n    let (b, ofs) := p in Vptr b ofs.\n\n\n  Coercion val_of_ptr: ptr >-> val.\n\n  Hint Unfold val_of_ptr: no_coerc.\n\n  Implicit Type p: ptr.\n  Implicit Type mc chunk: memory_chunk.\n  Implicit Type b: block.\n  Implicit Type i: ident.\n\n\n  (* location can be either a pointer or a variable in the\n     environment. This will allow to represent a local variable as an\n     array of size 1 *)\n\n  Inductive location : Type :=\n  | LPtr: ptr -> location\n  | LVar: ident -> location.\n  Implicit Type l:location.\n\n  Definition LPtr' := LPtr.\n  Definition LVar' := LVar.\n  Coercion LPtr' : ptr >-> location.\n  Coercion LVar' : ident >-> location.\n\n  Hint Unfold LPtr' LVar': no_coerc.\n  Ltac no_coerc:= autounfold with no_coerc in *.\n\n\n  (* two location are \"non interfering\" (result of alias analysis)\n     when accessed according to the memory chunks *)\n\n  Inductive non_interfering:\n    location -> memory_chunk -> location -> memory_chunk -> Prop :=\n\n  (** a pointer (in the memory) and an ident (in the local store) are\n     non interfering*)\n  | NI_pv: forall p mc1 i mc2,\n    non_interfering p mc1 i mc2\n  | NI_vp: forall i mc1 p mc2,\n    non_interfering i mc1 p mc2\n\n  (** two different variables do not interfere *)\n  | NI_var: forall i1 mc1 i2 mc2, i1 <> i2 ->\n    non_interfering i1 mc1 i2 mc2\n\n  (** two pointers in different blocks do not interfere *)\n  | NI_diff_block:\n    forall b1 b2 ofs1 ofs2 mc1 mc2, b1 <> b2 ->\n      non_interfering (LPtr (b1, ofs1)) mc1 (LPtr (b2, ofs2)) mc2\n\n  (** when in the same block, two pointers are non interfering when the\n     corresponding locations do not overlap*)\n  | NI_12: forall b ofs1 ofs2 mc1 mc2, (** ptr1 before ptr2 *)\n    Int.signed ofs1 + (size_chunk mc1) <= Int.signed ofs2 ->\n    non_interfering (LPtr (b, ofs1)) mc1 (LPtr (b, ofs2)) mc2\n  | NI_21: forall b ofs1 ofs2 mc1 mc2, (** ptr2 before ptr1*)\n    Int.signed ofs2 + (size_chunk mc2) <= Int.signed ofs1 ->\n    non_interfering (LPtr (b, ofs1)) mc1 (LPtr (b, ofs2)) mc2.\n\n\n\n\n  (* a memory layout maps the array vision to the low level one\n\n   * a \"type\" is given to each array (all accesses to any cell of this\n     array will be done via this type)\n\n   * each cell_id (array * list int) is mapped to a location\n\n   * this mapping is non interfering\n   *)\n\n  Definition Correct_Layout chunk_of_array flatten_access :=\n      (* the layout is non interfering *)\n      forall ci1 ci2 mc1 mc2 l1 l2,\n        ci1 <> ci2 ->\n\n        chunk_of_array ci1.(array) = Some mc1 ->\n        chunk_of_array ci2.(array) = Some mc2 ->\n\n        flatten_access ci1 = Some l1 ->\n        flatten_access ci2 = Some l2 ->\n\n        non_interfering l1 mc1 l2 mc2.\n\n  Record memory_layout : Type := mkLayout {\n    chunk_of_array: Array_Id -> option memory_chunk; (* type of each array *)\n    flatten_access: Cell_Id Num -> option location; (* where is each cell maps in memory*)\n    correct_layout: Correct_Layout chunk_of_array flatten_access\n  }.\n\n  Hint Unfold Correct_Layout.\n\n  (* a \"memory\" for loops is then a Cminor memory, plus a Cminor\n     environment, and a layout *)\n\n  (* Coq's kernel does not allow to use an inductive definition as a\n     required field of a module. This explains why we go through an\n     intermediate Memory' definition*)\n\n  Record Memory': Type := mkMem {\n    ll_mem: CM.mem;\n    ll_env: env;\n    layout: memory_layout}.\n  Definition Memory := Memory'.\n  Implicit Type mem: Memory.\n\n  Definition Value := val.\n\n  Definition layout' (mem:Memory) := layout mem.\n  Coercion layout': Memory >-> memory_layout.\n  Hint Unfold layout': no_coerc.\n\n  Definition read mem ci : option val:=\n    do mc <- mem.(chunk_of_array) ci.(array);\n    do l <- mem.(flatten_access) ci;\n    match l with\n      | LPtr p => CM.loadv mc mem.(ll_mem) p\n      | LVar i => mem.(ll_env) ! i\n    end.\n\n\n  Definition write mem ci v : option Memory :=\n    do mc <- mem.(chunk_of_array) ci.(array);\n    do l <- mem.(flatten_access) ci;\n    match l with\n      | LPtr p =>\n        do nm <- CM.storev mc mem.(ll_mem) p v;\n        Some {| ll_mem := nm;\n                ll_env := mem.(ll_env);\n                layout := mem.(layout)|}\n      | LVar i =>\n        (** we need to check that i already existed in the\n           environment, to avoid creating new variables *)\n        do _ <- mem.(ll_env) ! i;\n        Some {| ll_mem := mem.(ll_mem);\n                ll_env := PTree.set i v  mem.(ll_env);\n                layout := mem.(layout)|}\n    end.\n\n  Ltac destr_ptrs :=\n    repeat match goal with | p : ptr |- _ => destruct p end.\n\n  Ltac mymonadInv H :=\n    let rec aux _ :=\n      monadInv H; try\n        match type of H with\n          | context[match ?l with\n                      | LPtr _ => _\n                      | LVar _ => _\n                    end] =>\n          let p := fresh \"p\" in let i := fresh \"i\" in\n          destruct l as [p| i]; try aux tt\n        end in\n     aux tt; destr_ptrs; simpl in *; rewrite_Heq_do.\n  \n  (* two memories are of \"same layout\" if you can go from one to the\n     other trough a sequence or [write] (since it's a refl *sym* trans\n     closure, it's a slightly bigger equivalence class)*)\n\n  Inductive sml_aux: relation Memory :=\n  |SMTA_intro: forall mem1 mem2 ci v,\n    write mem1 ci v = Some mem2 ->\n    sml_aux mem1 mem2.\n\n  Definition same_memory_layout: relation Memory :=\n    clos_refl_sym_trans_1n _ sml_aux.\n\n  Hint Constructors clos_refl_sym_trans_1n.\n\n  Instance Equiv_smt: Equivalence same_memory_layout.\n  Proof.\n    unfold same_memory_layout.\n    destruct (clos_rst_is_equiv _ sml_aux). unfold reflexive, transitive, symmetric in *.\n    prove_equiv; intros; rewrite <- (clos_rst_rst1n_iff) in *; eauto.\n  Qed.\n\n  (* you don't change the layout of a memory by writing in it *)\n  Lemma write_keep_layout:\n    forall mem1 mem2 ci v, write mem1 ci v = Some mem2 -> same_memory_layout mem1 mem2.\n  Proof.\n    intros * WRITE.\n    econstructor; auto.\n    left. econstructor. eauto.\n  Qed.\n\n(*  Ltac prog_match_loc_aux TERM :=\n    match TERM with\n      | context[match ?X with |LPtr _ => _ | LVar _ =>  _ end] =>\n        let p := fresh \"p\" in let i := fresh \"i\" in \n        destruct X as [p|i] _eqn\n    end.\n\n  Ltac prog_match_location :=\n    match goal with\n      | H : ?TERM |- _ =>\n        prog_match_loc_aux TERM\n      | |- ?TERM =>\n        prog_match_loc_aux TERM\n    end.*)\n\n  Lemma sml_aux_same_layout:\n    forall mem1 mem2, sml_aux mem1 mem2 \\/ sml_aux mem2 mem1 ->\n      layout mem1 = layout mem2.\n  Proof.\n    intros * [H|H]; inv H;\n    mymonadInv H0; auto.\n  Qed.\n\n  Lemma same_layout_same_layout:\n    forall mem1 mem2, same_memory_layout mem1 mem2 -> layout mem1 = layout mem2.\n  Proof.\n    intros * SMT. induction SMT; auto.\n    rewrite <- IHSMT.\n    apply sml_aux_same_layout; auto.\n  Qed.\n\n  Lemma write_same_layout:\n    forall mem1 mem2 ci v, same_memory_layout mem1 mem2 ->\n    (is_some (write mem1 ci v) -> is_some (write mem2 ci v)).\n  Proof.\n    intros * SMT. revert ci v. induction SMT; intros * ISSOME'. auto.\n\n    apply IHSMT. clear IHSMT.\n    inversion ISSOME' as [m ISSOME]. clear ISSOME'. clean.\n    pose proof (sml_aux_same_layout _ _ H) as SML.\n\n    unfold write in *; no_coerc;\n    rewrite SML in *;\n    unfold CM.storev in *;\n    mymonadInv ISSOME.\n\n    (* write in memory *)\n    edestruct (CM.valid_access_store) as [m VAS];[|rewrite VAS; simpl_do; auto].\n    destruct H as [H | H]; inv H; mymonadInv H0; simpl in *;\n    eauto using CM.store_valid_access_1,\n      CM.store_valid_access_2, CM.store_valid_access_3.\n\n    (* write in store *)\n\n    destruct H as [H | H]; inv H; mymonadInv H0; auto.\n    dest i0 == i; subst.\n    rewrite PTree.gss; simpl_do; auto.\n    rewrite PTree.gso; auto; simpl_do; rewrite_Heq_do; auto.\n    \n    dest i0 == i; subst; rewrite_Heq_do; auto.\n    rewrite PTree.gso in Heq_do1; auto; simpl_do; rewrite_Heq_do; auto.\n  Qed.\n\n\n  Definition read_write mem ci v : option val :=\n    do mem' <- write mem ci v;\n    read mem' ci.\n\n  (* two memories with same layout are readable at the same locations *)\n\n  Lemma read_same_layout:\n    forall mem1 mem2 ci, same_memory_layout mem1 mem2 ->\n    is_some (read mem1 ci) -> is_some (read mem2 ci).\n  Proof.\n    intros * SMT. revert ci.\n    induction SMT; intros * ISSOME'; auto.\n    pose proof sml_aux_same_layout _ _ H as SML.\n    apply IHSMT; clear IHSMT. clear dependent z.\n    inversion ISSOME' as [m ISSOME]; clear ISSOME'. clean.\n    unfold read in *. no_coerc. rewrite SML in *.\n    mymonadInv ISSOME.\n\n\n    (* write in memory *)\n    edestruct (CM.valid_access_load) as [v HREW]; [| rewrite HREW; auto].\n    apply CM.load_valid_access in ISSOME.\n    destruct H as [H | H]; inv H; mymonadInv H0; simpl in *;\n    eauto using CM.store_valid_access_1,\n      CM.store_valid_access_2, CM.store_valid_access_3.\n\n    (* write in store *)\n    destruct H as [H | H]; inv H; mymonadInv H0; simpl in *; clean;\n    dest i0 == i; subst.\n    rewrite PTree.gss; auto.\n    rewrite PTree.gso; auto.\n    rewrite PTree.gss in ISSOME; auto.\n    rewrite PTree.gso in ISSOME; auto.\n  Qed.\n  \n  Lemma rws: forall mem1 mem2 ci v,\n    same_memory_layout mem1 mem2 ->\n    read_write mem1 ci v = read_write mem2 ci v.\n  Proof.\n    intros * SMT.\n    unfold read_write.\n    pose proof (same_layout_same_layout mem1 mem2 SMT) as SML.\n    destruct (write mem1 ci v) as [m'|] _eqn; simpl_do.\n\n    assert (is_some (write mem2 ci v)).\n      eapply write_same_layout; eauto. auto.\n    inversion H as [m'0 ISSOME]; clear H. simpl_do. clean.\n    unfold write in*; unfold read in *. no_coerc. rewrite SML in *.\n    mymonadInv Heqo; mymonadInv ISSOME; simpl in *. eauto.\n    repeat rewrite PTree.gss; auto.\n\n    destruct (write mem2 ci v) as [m'|] _eqn; simpl_do; auto.\n    assert (is_some (write mem1 ci v)). symmetry in SMT.\n     eapply write_same_layout; eauto. auto.\n    inv H; congruence.\n  Qed.\n\n  Lemma rwo: forall mem1 mem2 ci1 ci2 v, write mem1 ci1 v = Some mem2 -> ci1 <> ci2 ->\n    read mem2 ci2 = read mem1 ci2.\n  Proof.\n    intros * WRITE NEQ.\n    unfold read, write in *.\n    mymonadInv WRITE; simpl in *; clean;\n    unfold CM.storev, CM.loadv in *; no_coerc;\n    prog_dos; try destruct l; try destruct l0; destr_ptrs; simpl_do; eauto;\n    destruct mem1; simpl in *;\n    destruct layout0; simpl in *;\n    specialize (correct_layout0 _ _ _ _ _ _ NEQ Heq_do Heq_do2 Heq_do0 Heq_do3);\n    inv correct_layout0;\n    \n    try eapply CM.load_store_other; eauto.\n\n    rewrite PTree.gso; auto.\n\n  Qed.\n\n\nEnd FromCminorEnv.\n\n\n\n", "meta": {"author": "pilki", "repo": "s2sLoop", "sha": "821528456333c518788df2834c674e850d7e7291", "save_path": "github-repos/coq/pilki-s2sLoop", "path": "github-repos/coq/pilki-s2sLoop/s2sLoop-821528456333c518788df2834c674e850d7e7291/src/OtherMemory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23859554393525112}}
{"text": "(*======================================================================================\n  Instruction codec\n  ======================================================================================*)\nRequire Import ssreflect ssrfun seq ssrbool ssrnat fintype.\nAdd LoadPath \"..\".\nRequire Import bitsrep bitsprops bitsops eqtype tuple.\nRequire Import Coq.Strings.String.\nRequire Import cast codec bitscodec.\nRequire Import instr encdechelp reg.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(*---------------------------------------------------------------------------\n    Casts for datatypes used in instructions\n  ---------------------------------------------------------------------------*)\nDefinition unSrcR : CAST Reg Src.\napply: MakeCast SrcR (fun s => if s is SrcR r then Some r else None) _.\nby elim; congruence. Defined.\n\nDefinition unSrcI : CAST DWORD Src.\napply: MakeCast SrcI (fun s => if s is SrcI i then Some i else None) _.\nby elim; congruence. Defined.\n\nDefinition unRegMemR d : CAST (DWORDorBYTEReg d) (RegMem d).\napply: MakeCast (RegMemR d) (fun rm => if rm is RegMemR r then Some r else None) _.\nby elim; congruence. Defined.\n\nDefinition unShiftCountCL : CAST unit ShiftCount.\napply: MakeCast (fun _=>ShiftCountCL) (fun c => if c is ShiftCountCL then Some tt else None) _.\nelim; congruence.\nDefined.\n\nDefinition unShiftCountI : CAST BYTE ShiftCount.\napply: MakeCast ShiftCountI (fun c => if c is ShiftCountI b then Some b else None) _.\nelim; congruence.\nDefined.\n\nDefinition unJmpTgtI : CAST Tgt JmpTgt.\napply: MakeCast JmpTgtI (fun t => if t is JmpTgtI d then Some d else None) _.\nelim; elim; congruence. Defined.\n\nDefinition unJmpTgtRM : CAST (RegMem true) JmpTgt.\napply: (MakeCast (fun (rm:RegMem true) => match rm with RegMemR r => JmpTgtR r | RegMemM m => JmpTgtM m end)\n  (fun i => match i with JmpTgtR r => Some (RegMemR true r) | JmpTgtM m => Some (RegMemM true m) | _ => None end) _).\nelim => //. move => m. elim => // ms. by move => [<-].\nby move => r y [<-].\nDefined.\n\nRequire Import bitsopsprops.\nDefinition unTgt : CAST DWORD Tgt.\napply: MakeCast mkTgt\n                (fun t => let: mkTgt d := t in Some d) _.\nby move => [d] y [<-].\nDefined.\n\nDefinition unSrcRM : CAST (RegMem true) Src.\napply: MakeCast\n  (fun (rm: RegMem true) => match rm with RegMemR r => SrcR r | RegMemM m => SrcM m end)\n  (fun i => match i with SrcR r => Some (RegMemR true r) | SrcM m => Some (RegMemM _ m)\n                       | _ => None\n            end) _.\nelim => //; by move => ? ? [<-]. Defined.\n\n(*---------------------------------------------------------------------------\n    Casts and codecs for bit-encoded types e.g. registers, scales, conditions\n  ---------------------------------------------------------------------------*)\nDefinition regCast : CAST (BITS 3) Reg.\napply: MakeCast (fun x => decReg x) (fun x => Some (encReg x)) _.\nmove => x y [<-]; by rewrite encRegK. Defined.\nDefinition regCodec   : Codec Reg   := bitsCodec 3 ~~> regCast.\n\nDefinition opCast : CAST (BITS 3) BinOp.\napply: MakeCast (fun x => decBinOp x) (fun x => Some (encBinOp x)) _.\nmove => x y [<-]; by rewrite encBinOpK. Defined.\nDefinition opCodec    : Codec BinOp   := bitsCodec 3 ~~> opCast.\n\nDefinition shiftOpCast : CAST (BITS 3) ShiftOp.\napply: MakeCast (fun x => decShiftOp x) (fun x => Some (encShiftOp x)) _.\nmove => x y [<-]; by rewrite encShiftOpK. Defined.\nDefinition shiftOpCodec : Codec ShiftOp   := bitsCodec 3 ~~> shiftOpCast.\n\nDefinition bitOpCast : CAST (BITS 2) BitOp.\napply: MakeCast (fun x => decBitOp x) (fun x => Some (encBitOp x)) _.\nmove => x y [<-]; by rewrite encBitOpK. Defined.\nDefinition bitOpCodec : Codec BitOp   := bitsCodec 2 ~~> bitOpCast.\n\nDefinition optionalNonSPregCast : CAST (BITS 3) (option NonSPReg).\napply: MakeCast (fun (x: BITS 3) => decNonSPReg x) (fun x =>\n  if x is Some r then Some (encNonSPReg r) else Some #b\"100\") _.\nelim => //.\n+ move => x y [<-]. by rewrite encNonSPRegK.\n+ by move => y [<-]. Defined.\nDefinition optionalNonSPRegCodec : Codec (option NonSPReg) :=\n  bitsCodec 3 ~~> optionalNonSPregCast.\n\nDefinition nonSPregCast : CAST (BITS 3) NonSPReg.\napply: MakeCast (fun x => if decNonSPReg x is Some y then y else EAX)\n                (fun y => Some (encNonSPReg y)) _.\nmove => x y [<-]. by rewrite encNonSPRegK. Defined.\n\nDefinition nonBPnonSPRegCodec : Codec NonSPReg :=\n    #b\"000\" .$ always EAX\n||| #b\"001\" .$ always ECX\n||| #b\"010\" .$ always EDX\n||| #b\"011\" .$ always EBX\n||| #b\"110\" .$ always ESI\n||| #b\"111\" .$ always EDI.\n\nDefinition nonSPRegCodec : Codec NonSPReg :=\n    nonBPnonSPRegCodec\n||| #b\"101\" .$ always EBP.\n\nDefinition byteRegCast : CAST (BITS 3) BYTEReg.\napply: MakeCast (fun x => decBYTEReg x) (fun x => Some (encBYTEReg x)) _.\nmove => x y [<-]; by rewrite encBYTERegK. Defined.\nDefinition byteRegCodec : Codec BYTEReg := bitsCodec 3 ~~> byteRegCast.\n\nDefinition dwordorbyteRegCodec dword : Codec (DWORDorBYTEReg dword) :=\n  if dword as dword return Codec (DWORDorBYTEReg dword)\n  then regCodec\n  else byteRegCodec.\n\nDefinition scaleCast : CAST (BITS 2) Scale.\napply: MakeCast decScale (fun x => Some (encScale x)) _.\nmove => x y [<-]; by rewrite encScaleK. Defined.\nDefinition scaleCodec : Codec Scale := bitsCodec 2 ~~> scaleCast.\n\nDefinition conditionCast : CAST (BITS 3) Condition.\napply: MakeCast decCondition (fun x => Some (encCondition x)) _.\nmove => x y [<-]; by rewrite encConditionK. Defined.\nDefinition conditionCodec : Codec Condition := bitsCodec 3 ~~> conditionCast.\n\nHint Rewrite domConstSeq domSeq domCast domAlt domEmp domSym domAny : dom.\n\nLemma totalScale : total scaleCodec. Proof. apply totalCast => //. apply totalBITS. Qed.\nLemma totalReg : total regCodec. Proof. apply totalCast => //. apply totalBITS. Qed.\nLemma totaloptionalNonSPReg : total optionalNonSPRegCodec. Proof. apply totalCast => //.\napply totalBITS. case => //. Qed.\nLemma totalOp : total opCodec. Proof. apply totalCast => //. apply totalBITS. Qed.\nLemma totalShiftOp : total shiftOpCodec. Proof. apply totalCast => //. apply totalBITS. Qed.\nLemma totalbyteReg : total byteRegCodec. Proof. apply totalCast => //. apply totalBITS. Qed.\nLemma totaldwordorbyteReg d : total (dwordorbyteRegCodec d).\nProof. destruct d. apply totalReg. apply totalbyteReg. Qed.\n\nDefinition SIB := (Reg * option (NonSPReg * Scale))%type.\n\nDefinition SIBCast : CAST (Scale * option NonSPReg * Reg) SIB.\napply: MakeCast (fun p => let: (sc,o,r) := p\n                 in (r, if o is Some ix then Some(ix,sc) else None))\n                (fun p => let: (base, o) := p\n                 in if o is Some(ix,sc) then Some(sc, Some ix, base)\n                                        else Some(S1, None, base)) _.\nmove => [r' o'] [[sc o] r].\ncase: o' => //.\n+ by move => [? ?] [-> <- ->].\n+ by move => [<- <- <-].\nDefined.\n\nDefinition SIBCodec : Codec SIB := scaleCodec $ optionalNonSPRegCodec $ regCodec ~~> SIBCast.\n\nLemma totalSIB : total SIBCodec.\nProof. rewrite /SIBCodec. apply totalCast. apply totalSeq. apply totalSeq.\napply totalScale. apply totaloptionalNonSPReg. apply totalReg.\nrewrite /castIsTotal.  move => [r o]. destruct o => //. by destruct p.\nQed.\n\nDefinition dispOffsetSIBCast dword : CAST (SIB * DWORD) (RegMem dword).\napply: MakeCast (fun p => RegMemM dword (mkMemSpec (Some p.1) p.2))\n  (fun rm => if rm is RegMemM (mkMemSpec (Some sib) offset) then Some(sib,offset) else None) _.\nelim => //. elim => //. elim => //. move => [x y] z [x' y']. by move => [-> ->]. Defined.\n\nDefinition dispOffsetCast dword : CAST (NonSPReg * DWORD) (RegMem dword).\napply: (MakeCast (fun p => RegMemM dword (mkMemSpec (Some (nonSPReg p.1,None)) p.2))\n  (fun rm => if rm is RegMemM (mkMemSpec (Some (nonSPReg base,None)) offset) then Some(base,offset) else None) _).\nelim => //. elim => //. elim => //. move => [x y] z [x' y'].\ncase: x => // r. case: y => //. by move => [-> ->]. Defined.\n\nDefinition dispOffsetNoBaseCast dword : CAST DWORD (RegMem dword).\napply: MakeCast (fun offset => RegMemM dword (mkMemSpec None offset))\n                (fun rm => if rm is RegMemM (mkMemSpec None offset)\n                           then Some offset else None) _.\nelim => //. elim => //. by elim => // ? ? [->]. Defined.\n\nDefinition RegMemCodec T (regOrOpcodeCodec : Codec T) dword : Codec (T * RegMem dword) :=\n    #b\"00\" .$ regOrOpcodeCodec $ SIBRM .$ (SIBCodec $ always #0 ~~> dispOffsetSIBCast dword)\n||| #b\"00\" .$ regOrOpcodeCodec $ (nonBPnonSPRegCodec $ always #0 ~~> dispOffsetCast dword)\n||| #b\"00\" .$ regOrOpcodeCodec $ (#b\"101\" .$ DWORDCodec ~~> dispOffsetNoBaseCast dword)\n||| #b\"01\" .$ regOrOpcodeCodec $ SIBRM .$ (SIBCodec $ shortDWORDCodec ~~> dispOffsetSIBCast dword)\n||| #b\"01\" .$ regOrOpcodeCodec $ (nonSPRegCodec $ shortDWORDCodec ~~> dispOffsetCast dword)\n||| #b\"10\" .$ regOrOpcodeCodec $ (SIBRM .$ SIBCodec $ DWORDCodec ~~> dispOffsetSIBCast dword)\n||| #b\"10\" .$ regOrOpcodeCodec $ (nonSPRegCodec $ DWORDCodec ~~> dispOffsetCast dword)\n||| #b\"11\" .$ regOrOpcodeCodec $ (dwordorbyteRegCodec dword ~~> unRegMemR dword).\n\n(*\nLemma totalRegMemCodec T (c: Codec T) d : total c -> total (RegMemCodec c d).\nProof. move => tc. rewrite /total/RegMemCodec.\nautorewrite with dom.\nmove => [x rm].\ndestruct rm.\n(* Register *)\nsimpl. by rewrite totaldwordorbyteReg tc.\n(* MemSpec *)\ndestruct ms.\ncase sib => [[base optix] |].\n(* Has a SIB *)\n+ case: optix => [[index sc] |].\n  - simpl.\n    rewrite /SIBCodec.\n    case E: (offset == #0). rewrite (eqP E)/=. rewrite tc/=.\n    destruct base; autorewrite with dom; simpl;\n      by rewrite totalScale totaloptionalNonSPReg totalReg/=.\n    destruct base; autorewrite with dom; simpl.\n      rewrite totalScale totaloptionalNonSPReg totalDWORD totalReg tc /=.\n      by rewrite !orbT !orbF.\n    rewrite totalScale totaloptionalNonSPReg totalReg totalDWORD tc/=.\n      by rewrite !orbT !orbF.\nsimpl.\nsimpl. rewrite totalDWORD/=. rewrite /SIBCodec.\nautorewrite with dom. simpl.\ncase E: (offset == #0). simpl. by rewrite tc totalReg.\nrewrite tc totalReg. simpl. by rewrite !orbT !orbF.\ncase E: (offset == #0). simpl. by rewrite tc totalDWORD.\n(* Has no SIB  *)\nby rewrite /= tc totalDWORD.\nQed.\n*)\n\nDefinition RegMemOpCodec (op: BITS 3) dword :=\n  RegMemCodec (Const op) dword ~~> sndUnitCast _.\n\nDefinition RegMemOpDepCodec (op: BITS 3) :=\n  BoolDep (fun d => RegMemCodec (Const op) d ~~> sndUnitCast _).\n\nDefinition unDstSrcRMR d : CAST (DWORDorBYTEReg d * RegMem d) (DstSrc d).\napply: (MakeCast\n       (fun p => match p.2 with RegMemR y => DstSrcRR d p.1 y\n                              | RegMemM y => DstSrcRM d p.1 y end)\n       (fun ds => match ds with DstSrcRR x y => Some (x,RegMemR _ y)\n                              | DstSrcRM x y => Some (x,RegMemM _ y)\n                              | _ => None end) _).\nby elim => // ? ? [? ?] [<-] <-. Defined.\n\nDefinition unDstSrcMRR d : CAST (DWORDorBYTEReg d * RegMem d) (DstSrc d).\napply: (MakeCast\n       (fun p => match p.2 with RegMemR y => DstSrcRR d y p.1\n                              | RegMemM y => DstSrcMR d y p.1 end)\n       (fun ds => match ds with DstSrcRR x y => Some (y, RegMemR _ x)\n                              | DstSrcMR x y => Some (y, RegMemM _ x)\n                              | _ => None end) _).\nby elim => // ? ? [? ?] [<-] <-. Defined.\n\nDefinition unDstSrcMRI d : CAST (RegMem d * DWORDorBYTE d) (DstSrc d).\napply: (MakeCast\n       (fun p => match p.1 with RegMemR y => (DstSrcRI d y p.2)\n                             | RegMemM y => (DstSrcMI d y p.2) end)\n       (fun ds => match ds with DstSrcRI x y => Some (RegMemR _ x, y)\n                              | DstSrcMI x y => Some (RegMemM _ x, y)\n                              | _ => None end) _).\nmove => ds [rm c].\nelim: ds => //. by move => ? ? [<- ->]. by move => ? ? [<- ->]. Defined.\n\n(*---------------------------------------------------------------------------\n    Casts for instructions\n  ---------------------------------------------------------------------------*)\nDefinition unPUSH : CAST Src Instr.\napply: MakeCast PUSH (fun i => if i is PUSH s then Some s else None) _.\nby elim; congruence. Defined.\n\nDefinition unINCD : CAST (RegMem true) Instr.\napply: MakeCast (UOP true OP_INC)\n                (fun i => if i is UOP true OP_INC rm then Some rm else None) _.\nelim => //. elim => //. elim => //. by move => ? ? [->]. Defined.\n\nDefinition unDECD : CAST (RegMem true) Instr.\napply: MakeCast (UOP true OP_DEC)\n                (fun i => if i is UOP true OP_DEC rm then Some rm else None) _.\nelim => //. elim => //. elim => //. by move => ? ? [->]. Defined.\n\nDefinition unPOP : CAST (RegMem true) Instr.\napply: MakeCast POP (fun i => if i is POP d then Some d else None) _.\nelim => //. by move => d rm [->]. Defined.\n\nDefinition unINC : CAST {d:bool & RegMem d} Instr.\napply: (MakeCast (fun (p:{d:bool & RegMem d}) => let: existT d v := p in UOP d OP_INC v)\n                 (fun i => if i is UOP d OP_INC v then Some (existT _ d v) else None) _).\nelim => //. elim => op src [y z]; destruct op => // [H]; by inversion H. Defined.\n\nDefinition unDEC : CAST {d:bool & RegMem d} Instr.\napply: (MakeCast (fun (p:{d:bool & RegMem d}) => let: existT d v := p in UOP d OP_DEC v)\n                 (fun i => if i is UOP d OP_DEC v then Some (existT _ d v) else None) _).\nelim => //. elim => op src [y z]; destruct op => // [H]; by inversion H. Defined.\n\nDefinition unNOT : CAST {d:bool & RegMem d} Instr.\napply: (MakeCast (fun (p:{d:bool & RegMem d}) => let: existT d v := p in UOP d OP_NOT v)\n                 (fun i => if i is UOP d OP_NOT v then Some (existT _ d v) else None) _).\nelim => //. elim => op src [y z]; destruct op => // [H]; by inversion H. Defined.\n\nDefinition unNEG : CAST {d:bool & RegMem d} Instr.\napply: (MakeCast (fun (p:{d:bool & RegMem d}) => let: existT d v := p in UOP d OP_NEG v)\n                 (fun i => if i is UOP d OP_NEG v then Some (existT _ d v) else None) _).\nelim => //. elim => op src [y z]; destruct op => // [H]; by inversion H. Defined.\n\nDefinition unIMUL : CAST (Reg * RegMem true) Instr.\napply: (MakeCast (fun p => IMUL p.1 p.2)\n                 (fun i => if i is IMUL dst src then Some (dst,src) else None) _).\nelim => //. by move => dst src [dst' src'] [<-] ->.  Defined.\n\nDefinition unIN : CAST (bool*BYTE) Instr.\napply: MakeCast (fun p => IN p.1 p.2) (fun i => if i is IN d p then Some(d,p) else None) _.\nby elim => // ? ? [? ?] [-> ->]. Defined.\n\nDefinition unOUT : CAST (bool*BYTE) Instr.\napply: MakeCast (fun p => OUT p.1 p.2) (fun i => if i is OUT d p then Some(d,p) else None) _.\nby elim => // ? ?  [? ?] [-> ->]. Defined.\n\nDefinition unLEA : CAST (Reg * RegMem true) Instr.\napply: MakeCast (fun p => LEA p.1 p.2) (fun i => if i is LEA x y then Some(x,y) else None) _.\nby elim => // ? ? [? ?] [-> ->]. Defined.\n\nDefinition unXCHG : CAST (DWORDorBYTEReg true * RegMem true) Instr.\napply: MakeCast (fun p => XCHG true p.1 p.2) (fun i => if i is XCHG true x y then Some(x,y) else None) _.\nelim => //. elim => //. by move => r s [r' s'] [<-] ->. Defined.\n\nDefinition unXCHGB : CAST (DWORDorBYTEReg false * RegMem false) Instr.\napply: MakeCast (fun p => XCHG false p.1 p.2) (fun i => if i is XCHG false x y then Some(x,y) else None) _.\nelim => //. elim => //. by move => r s [r' s'] [<-] ->. Defined.\n\nDefinition unMUL : CAST {d:bool & RegMem d} Instr.\napply: (MakeCast (fun (p:{d:bool & RegMem d}) => let: existT d v := p in MUL v)\n                 (fun i => if i is MUL d v then Some (existT _ d v) else None) _).\nelim => //. elim => src [y z] [H] H'; by inversion H'.\nDefined.\n\nDefinition unRET : CAST WORD Instr.\napply: MakeCast RETOP (fun i => if i is RETOP w then Some w else None) _.\nelim; congruence. Defined.\n\nDefinition unJMP : CAST JmpTgt Instr.\napply: MakeCast JMPrel (fun i => if i is JMPrel t then Some t else None) _.\nelim; congruence. Defined.\n\nDefinition unCALL : CAST JmpTgt Instr.\napply: MakeCast CALLrel (fun i => if i is CALLrel t then Some t else None) _.\nelim; congruence. Defined.\n\nDefinition isCMC : CAST unit Instr.\napply: MakeCast (fun _ => CMC) (fun i => if i is CMC then Some tt else None) _; by elim; elim.\nDefined.\n\nDefinition isCLC : CAST unit Instr.\napply: MakeCast (fun _ => CLC) (fun i => if i is CLC then Some tt else None) _; by elim; elim.\nDefined.\n\nDefinition isSTC : CAST unit Instr.\napply: MakeCast (fun _ => STC) (fun i => if i is STC then Some tt else None) _; by elim; elim.\nDefined.\n\nDefinition isHLT : CAST unit Instr.\napply: MakeCast (fun _ => HLT) (fun i => if i is HLT then Some tt else None) _; by elim; elim.\nDefined.\n\nDefinition unBOP : CAST (BinOp * {d:bool & DstSrc d}) Instr.\napply: (MakeCast (fun (p:BinOp * {d:bool & DstSrc d}) => let: existT d v := p.2 in BOP d p.1 v)\n                 (fun i => if i is BOP d op v then Some (op, existT _ d v) else None) _).\nelim => //. elim => op src [op' [y z]] [->] H' H; by inversion H. Defined.\n\nRequire Import Coq.Program.Equality.\nDefinition unBOPMRI : CAST ({d:bool & (BinOp * RegMem d * DWORDorBYTE d)%type}) Instr.\napply: (MakeCast (fun (p:{d:bool & (BinOp * RegMem d * DWORDorBYTE d)%type}) =>\n  let: existT d (op,rm,c) := p in\n    match rm with RegMemR y => BOP d op (DstSrcRI d y c)\n                | RegMemM y => BOP d op (DstSrcMI d y c) end)\n                 (fun i =>\n                  match i with BOP d op (DstSrcRI y c) => Some (existT _ d (op,RegMemR _ y,c))\n                             | BOP d op (DstSrcMI y c) => Some (existT _ d (op,RegMemM _ y,c))\n                             | _ => None end) _).\nelim => //.\nmove => d.\nmove => op.\nelim => //.\n+ move => dst c [d' [[op' rm] c']]. move => [H1 H2 H3 H4]. subst.\nby dependent destruction H4.\n+ move => dst c [d' [[op' rm] c']]. move => [H1 H2 H3 H4]. subst.\nby dependent destruction H4.\nDefined.\n\nDefinition BOPCodecRMR : Codec {d: bool & DstSrc d} :=\n  BoolDep (fun d =>\n    RegMemCodec (dwordorbyteRegCodec d) d ~~> unDstSrcRMR d).\nDefinition BOPCodecMRR : Codec {d: bool & DstSrc d} :=\n  BoolDep (fun d =>\n    RegMemCodec (dwordorbyteRegCodec d) d ~~> unDstSrcMRR d).\n\nDefinition MOVCodecMRI : Codec {d: bool & DstSrc d} :=\n  BoolDep (fun d =>\n    RegMemOpCodec #0 d $ DWORDorBYTECodec d ~~> unDstSrcMRI d).\n\nDefinition BOPCodecMRI : Codec Instr :=\n  BoolDep (fun d =>\n    RegMemCodec opCodec d $ DWORDorBYTECodec d) ~~> unBOPMRI.\n\nDefinition unMOVZX : CAST (Reg * RegMem true) Instr.\napply: MakeCast (fun p => MOVX false true p.1 p.2) (fun i => if i is MOVX false true x y then Some(x,y) else None) _.\nelim => //. elim => //. elim => //. by move => ? ? [? ?] [-> ->]. Defined.\n\nDefinition unMOVZXB : CAST (Reg * RegMem false) Instr.\napply: MakeCast (fun p => MOVX false false p.1 p.2) (fun i => if i is MOVX false false x y then Some(x,y) else None) _.\nelim => //. elim => //. elim => //. by move => ? ? [? ?] [-> ->]. Defined.\n\nDefinition unMOVSX : CAST (Reg * RegMem true) Instr.\napply: MakeCast (fun p => MOVX true true p.1 p.2) (fun i => if i is MOVX true true x y then Some(x,y) else None) _.\nelim => //. elim => //. elim => //. by move => ? ? [? ?] [-> ->]. Defined.\n\nDefinition unMOVSXB : CAST (Reg * RegMem false) Instr.\napply: MakeCast (fun p => MOVX true false p.1 p.2) (fun i => if i is MOVX true false x y then Some(x,y) else None) _.\nelim => //. elim => //. elim => //. by move => ? ? [? ?] [-> ->]. Defined.\n\nDefinition unMOV : CAST ({d:bool & DstSrc d}) Instr.\napply: (MakeCast (fun (p:{d:bool & DstSrc d}) => let: existT d v := p in MOVOP d v)\n                 (fun i => if i is MOVOP d v then Some (existT _ d v) else None) _).\nelim => // d ds [y z] H. by inversion H. Defined.\n\nDefinition unMOVRI : CAST (Reg*DWORD) Instr.\napply: (MakeCast\n  (fun p => MOVOP true (DstSrcRI _ p.1 p.2)) (fun i => if i is MOVOP true (DstSrcRI r d) then Some (r,d) else None) _).\nelim => //. elim => //. elim => //. by move => ? ? [? ?] [-> ->].\nDefined.\n\nDefinition unSHIFT : CAST ({d:bool & (ShiftOp * RegMem d)%type} * ShiftCount) Instr.\napply: (MakeCast (fun (p:{d:bool & (ShiftOp * RegMem d)%type} * ShiftCount) =>\n                  let: (existT d (op, v), count) := p in SHIFTOP d op v count)\n                 (fun i => if i is SHIFTOP d op v count then Some (existT _ d (op,v), count) else None) _).\nelim => //. move => d op dst count [c count']. move => [H1 H2]. by subst.\nDefined.\n\nDefinition unJCC : CAST (Condition*bool*Tgt) Instr.\napply: MakeCast (fun p => let: (c,d,t) := p in JCCrel c (negb d) t)\n                (fun i => if i is JCCrel c d t then Some(c,negb d,t) else None) _.\nProof. elim => //. move => cc cv tgt [[cc' cv'] tgt']. move => [-> <- ->].\nby rewrite negbK. Defined.\n\nDefinition TgtCodec : Codec Tgt := DWORDCodec ~~> unTgt.\nDefinition ShortTgtCodec : Codec Tgt := shortDWORDCodec ~~> unTgt.\n\nDefinition unTESTOP : CAST (Reg * RegMem true) Instr.\napply: (MakeCast (fun p => TESTOP true p.2 (RegImmR true p.1))\n                (fun i => if i is TESTOP true y (RegImmR x) then Some(x,y) else None) _).\nelim => //. elim => //. move => dst src [dst' src']. case src => // r. by move => [-> ->].\nDefined.\n\nDefinition unTESTOPB : CAST (BYTEReg * RegMem false) Instr.\napply: (MakeCast (fun p => TESTOP false p.2 (RegImmR false p.1))\n                (fun i => if i is TESTOP false y (RegImmR x) then Some(x,y) else None) _).\nelim => //. elim => //. move => dst src [dst' src']. case src => // r. by move => [-> ->].\nDefined.\n\nDefinition unTESTOPI : CAST (RegMem true * DWORD) Instr.\napply: (MakeCast (fun p => TESTOP true p.1 (RegImmI true p.2))\n                (fun i => if i is TESTOP true x (RegImmI d) then Some(x,d) else None) _).\nelim => //. elim => //. move => dst src [dst' src']. case src => // r. by move => [-> ->].\nDefined.\n\nDefinition unTESTOPBI : CAST (RegMem false * BYTE) Instr.\napply: (MakeCast (fun p => TESTOP false p.1 (RegImmI false p.2))\n                (fun i => if i is TESTOP false x (RegImmI d) then Some(x,d) else None) _).\nelim => //. elim => //. move => dst src [dst' src']. case src => // r. by move => [-> ->].\nDefined.\n\nDefinition unBITOPR : CAST (BitOp * (Reg * RegMem true)) Instr.\napply: (MakeCast (fun p => let: (op,(r,rm)) := p in BITOP op rm (inl r))\n                (fun i => if i is BITOP op y (inl r) then Some(op,(r,y)) else None) _).\nelim => //. move => op dst src [op' [dst' src']]. case src => // r. by move => [-> -> ->].\nDefined.\n\nDefinition unBITOPI : CAST (BitOp * RegMem true * BYTE) Instr.\napply: (MakeCast (fun p => let: (op,rm,b) := p in BITOP op rm (inr b))\n                (fun i => if i is BITOP op y (inr b) then Some(op,y,b) else None) _).\nelim => //. move => op dst src [[op' dst'] src']. case src => // r. by move => [-> -> ->].\nDefined.\n\nDefinition unEAXimm : CAST (DWORDorBYTE true) (DstSrc true).\napply: (MakeCast\n       (fun c => DstSrcRI true EAX c)\n       (fun ds => if ds is DstSrcRI EAX y then Some y else None) _).\nelim => //. elim => //. elim => //. by move => c y [->]. Defined.\n\nDefinition unALimm : CAST (DWORDorBYTE false) (DstSrc false).\napply: (MakeCast\n       (fun c => DstSrcRI false AL c)\n       (fun ds => if ds is DstSrcRI AL y then Some y else None) _).\nelim => //. elim => //. by move => c y [->].\nDefined.\n\nDefinition EAXimmCodec : Codec {d: bool & DstSrc d} :=\n  BoolDep (fun d => DWORDorBYTECodec d ~~> if d then unEAXimm else unALimm).\n\nDefinition unBOPMRId : CAST (BinOp * RegMem true * DWORD) Instr.\napply: (MakeCast (fun (p:BinOp * RegMem true * DWORD) =>\n  let: (op,rm,c) := p in\n    match rm with RegMemR y => BOP true op (DstSrcRI true y c)\n                | RegMemM y => BOP true op (DstSrcMI true y c) end)\n                 (fun i =>\n                  match i with BOP true op (DstSrcRI y c) => Some (op,RegMemR _ y,c)\n                             | BOP true op (DstSrcMI y c) => Some (op,RegMemM _ y,c)\n                             | _ => None end) _).\nelim => //.\nelim => //.\nmove => op.\nelim => //.\n+ move => dst c [[op' rm] c']. move => [H2 H3 H4]. by subst.\n+ move => dst c [[op' rm] c']. move => [H2 H3 H4]. by subst.\nDefined.\n\n\nDefinition InstrCodec : Codec Instr :=\n(* Unary operations *)\n    droplsb #x\"FE\" .$ RegMemOpDepCodec #0 ~~> unINC\n||| droplsb #x\"FE\" .$ RegMemOpDepCodec #1 ~~> unDEC\n||| droplsb #x\"F6\" .$ RegMemOpDepCodec #2 ~~> unNOT\n||| droplsb #x\"F6\" .$ RegMemOpDepCodec #3 ~~> unNEG\n||| INCPREF .$ regCodec ~~> unRegMemR true ~~> unINCD\n||| DECPREF .$ regCodec ~~> unRegMemR true ~~> unDECD\n(* Binary operations *)\n||| #b\"00\" .$ opCodec $ #b\"10\" .$ EAXimmCodec ~~> unBOP\n||| #b\"00\" .$ opCodec $ #b\"00\" .$ BOPCodecMRR ~~> unBOP\n||| #b\"00\" .$ opCodec $ #b\"01\" .$ BOPCodecRMR ~~> unBOP\n||| droplsb #x\"80\" .$ BOPCodecMRI\n||| #x\"83\" .$ RegMemCodec opCodec true $ shortDWORDCodec ~~> unBOPMRId\n(* MOV operationsl *)\n||| droplsb #x\"8A\" .$ BOPCodecRMR ~~> unMOV\n||| droplsb #x\"88\" .$ BOPCodecMRR ~~> unMOV\n||| MOVIMMPREF .$ regCodec $ DWORDCodec ~~> unMOVRI\n||| droplsb #x\"C6\" .$ MOVCodecMRI ~~> unMOV\n(* IMUL and MUL *)\n||| #x\"0F\" .$ #x\"AF\" .$ RegMemCodec regCodec _ ~~> unIMUL\n||| droplsb #x\"F6\" .$ RegMemOpDepCodec #4 ~~> unMUL\n(* IN and OUT *)\n||| droplsb #x\"E4\" .$ Any $ BYTECodec ~~> unIN\n||| droplsb #x\"E6\" .$ Any $ BYTECodec ~~> unOUT\n(* LEA *)\n||| #x\"8D\" .$ RegMemCodec regCodec _ ~~> unLEA\n(* XCHG *)\n||| #b\"10010\" .$ always (EAX:Reg) $ (regCodec ~~> unRegMemR true) ~~> unXCHG\n||| #x\"86\" .$ RegMemCodec byteRegCodec _ ~~> unXCHGB\n||| #x\"87\" .$ RegMemCodec regCodec _ ~~> unXCHG\n(* PUSH *)\n||| #x\"68\" .$ DWORDCodec ~~> unSrcI ~~> unPUSH\n||| #x\"6A\" .$ shortDWORDCodec ~~> unSrcI ~~> unPUSH\n||| #b\"01010\" .$ regCodec ~~> unSrcR ~~> unPUSH\n||| #x\"FF\" .$ RegMemOpCodec #6 _ ~~> unSrcRM ~~> unPUSH\n(* POP *)\n||| #x\"8F\" .$ RegMemOpCodec #0 _ ~~> unPOP\n||| #b\"01011\" .$ regCodec ~~> unRegMemR true ~~> unPOP\n(* RET *)\n||| #x\"C3\" .$ always #0 ~~> unRET\n||| #x\"C2\" .$ WORDCodec ~~> unRET\n(* Nullary operations *)\n||| #x\"F4\" ~~> isHLT\n||| #x\"F5\" ~~> isCMC\n||| #x\"F8\" ~~> isCLC\n||| #x\"F9\" ~~> isSTC\n(* MOVX *)\n||| #x\"0F\" .$ #x\"B6\" .$ RegMemCodec regCodec false ~~> unMOVZXB\n||| #x\"0F\" .$ #x\"B7\" .$ RegMemCodec regCodec true ~~> unMOVZX\n||| #x\"0F\" .$ #x\"BE\" .$ RegMemCodec regCodec false ~~> unMOVSXB\n||| #x\"0F\" .$ #x\"BF\" .$ RegMemCodec regCodec true ~~> unMOVSX\n(* SHIFTOP *)\n||| droplsb #x\"C0\" .$ (BoolDep (RegMemCodec shiftOpCodec)) $ (BYTECodec ~~> unShiftCountI) ~~> unSHIFT\n||| droplsb #x\"D0\" .$ (BoolDep (RegMemCodec shiftOpCodec)) $ (always #1 ~~> unShiftCountI) ~~> unSHIFT\n||| droplsb #x\"D2\" .$ (BoolDep (RegMemCodec shiftOpCodec)) $ (Emp ~~> unShiftCountCL) ~~> unSHIFT\n(* BITOP *)\n||| #x\"0F\" .$ BITOPPREF .$ bitOpCodec $ BITOPSUFF .$ (RegMemCodec regCodec true) ~~> unBITOPR\n||| #x\"0F\" .$ #x\"BA\" .$ RegMemCodec (#b\"1\" .$ bitOpCodec) true $ BYTECodec ~~> unBITOPI\n(* TESTOP *)\n||| #x\"A8\" .$ (always AL ~~> unRegMemR false) $ BYTECodec ~~> unTESTOPBI\n||| #x\"A9\" .$ (always (EAX:Reg) ~~> unRegMemR true) $ DWORDCodec ~~> unTESTOPI\n||| #x\"F6\" .$ RegMemOpCodec #0 false $ BYTECodec ~~> unTESTOPBI\n||| #x\"F7\" .$ RegMemOpCodec #0 true $ DWORDCodec ~~> unTESTOPI\n||| #x\"84\" .$ RegMemCodec byteRegCodec false ~~> unTESTOPB\n||| #x\"85\" .$ RegMemCodec regCodec true ~~> unTESTOP\n(* JMP *)\n||| #x\"E9\" .$ DWORDCodec ~~> unTgt ~~> unJmpTgtI ~~> unJMP\n||| #x\"EB\" .$ ShortTgtCodec ~~> unJmpTgtI ~~> unJMP\n||| #x\"FF\" .$ RegMemOpCodec #4 true ~~> unJmpTgtRM ~~> unJMP\n(* CALL *)\n||| #x\"E8\" .$ DWORDCodec ~~> unTgt ~~> unJmpTgtI ~~> unCALL\n||| #x\"FF\" .$ RegMemOpCodec #2 true ~~> unJmpTgtRM ~~> unCALL\n(* JCC *)\n||| #x\"0F\" .$ JCC32PREF .$ conditionCodec $ Any $ TgtCodec ~~> unJCC\n||| JCC8PREF .$ conditionCodec $ Any $ ShortTgtCodec  ~~> unJCC\n.\n\nRequire Import codecregex div.\n\n(* Various facts about the instruction codec that can be determined statically.\n   - it's non-ambiguous\n   - the maximum number of bits (currently 88)\n   - hence, it's finite\n   - the number of bits is always divisible by 8\n*)\n\n\n\nLemma InstrCodecIsNonAmbiguous : NonAmbiguous InstrCodec.\nProof. by vm_compute. Qed.\n\nDefinition MaxBits := Eval vm_compute in Option.default 0 (maxSize InstrCodec).\n\nLemma InstrCodecMaxBits : maxSize InstrCodec = Some MaxBits.\nProof. by vm_compute. Qed.\n\nLemma InstrCodecFinite : finiteCodec InstrCodec.\nProof.  by rewrite /finiteCodec InstrCodecMaxBits. Qed.\n\nLemma InstrCodecAlignment : forall l x, interp InstrCodec l x -> 8 %| size l.\nProof. move => l x I.\nhave byteAligned: all (fun x => 8 %| x) (sizes InstrCodec)\n  by vm_compute.\napply: sizesProp I. apply: InstrCodecFinite. apply byteAligned. Qed.\n\nCorollary encInstrAligned : forall l x, enc InstrCodec x = Some l -> 8 %| size l.\nProof. move => l x ENC. apply encSound in ENC. by apply: InstrCodecAlignment ENC. Qed.\n\nRequire Import bitreader monad cursor.\n\nCorollary InstrCodecRoundtrip l cursor cursor' e x:\n  enc InstrCodec x = Some l ->\n  apart (size l) cursor cursor' ->\n  runBitReader (codecToBitReader MaxBits InstrCodec) cursor (l++e) = Some(cursor', e, Some x).\nProof. move => ENC AP.\nhave CC := codecToFiniteBitReaderRoundtrip _ _ InstrCodecMaxBits AP ENC.\nhave CS := codecToBitReaderSound. apply: CC.\napply nonAmbiguousDet. apply InstrCodecIsNonAmbiguous. Qed.\n\nRequire Import reader.\nCorollary InstrCodecRoundtripReader (pc:DWORD) cursor' bits x:\n  enc InstrCodec x = Some bits ->\n  apart ((size bits) %/ 8) pc cursor' ->\n  8 %| size bits /\\\n  runReader (bitReaderToReader (codecToBitReader MaxBits InstrCodec) nil) pc\n    (fromBin bits).2 = Some(cursor',nil,(nil,Some x)).\nProof. move => ENC AP. have CC := InstrCodecRoundtrip nil ENC.\nhave ALIGN:=encInstrAligned ENC.\ncase E: (fromBin bits) => [resbits bytes].\nhave: toBin bytes = bits /\\ resbits = nil.\ndestruct (size_fromBin E) as [E1 E2].\nrewrite (eqP ALIGN) in E1.\ndestruct resbits => //. split => //.\nhave H := toBinFromBin E. by rewrite cats0 in H. move => [H1 H2]. subst.\nhave BRR := @bitReaderToReader_correct _ (codecToBitReader MaxBits InstrCodec)\n  bytes nil pc (fromByteCursor cursor') (Some x).\ncase EC: (fromByteCursor pc) => [p |]//. specialize (CC p (fromByteCursor cursor')).\n  have AP': apart (size (toBin bytes)) (fromByteCursor pc) (fromByteCursor cursor').\n  have AP1 := apart_widen 3 AP. rewrite divnK in AP1. by apply AP1. done.\n  rewrite -EC in CC.\nspecialize (CC AP'). rewrite cats0 in CC. specialize (BRR CC).\n  destruct BRR as [resbytes [resbits' [H3 H4]]].\n  split => //. simpl snd. destruct resbits' => //. rewrite H3.\n  rewrite /bitCursorAndBitsToByteCursor.\n  have H: (toBin resbytes) = nil by destruct (toBin resbytes) => //.\n  destruct resbytes => //.\n  destruct cursor' => //. by rewrite /fromByteCursor/widenCursor high_catB.\n  simpl in H. have SR: (size (rev b)) = 8. by rewrite size_rev size_tuple.\n  destruct (rev b) => //.\nQed.\n\nInstance readOptionInstr : Reader (option Instr) :=\n  let! (resbits, i) = bitReaderToReader (codecToBitReader MaxBits InstrCodec) nil;\n  retn i.\n\nInstance readInstr : Reader Instr :=\n  let! pc = readCursor;\n  if pc is mkCursor p\n  then\n    let! r = readOptionInstr;\n    if r is Some i then retn i else retn BADINSTR\n  else\n    retn BADINSTR.\n\n\nRequire Import writer monadinst.\nFixpoint writeBytes (s: seq BYTE) : WriterTm unit :=\n  if s is b::rest\n  then do! writeNext b; writeBytes rest\n  else retn tt.\n\nInstance writeBytesI : Writer (seq BYTE) := writeBytes.\n\n(* NOTE: we don't have a Roundtrip instance for Instr because the\n   encoding/decoding don't proceed in lock-step, as required by simrw.\n  Instead, we use explicit correctness lemma in programassemcorrect.\n*)\nInstance encodeInstr : Writer Instr := fun instr =>\n  let! pc = getWCursor;\n  if pc is mkCursor p then\n    if enc InstrCodec instr is Some bs\n    then writeNext (fromBin bs).2\n    else writerFail\n  else writerFail.\n\nLemma writeBytesSkipFree xs : writerTmSkipFree (writeBytes xs).\nProof. induction xs => //. Qed.\n\n(*\nModule Examples.\n\nRequire Import instrsyntax. Open Scope instr_scope.\nCompute bytesToHex (snd (fromBin (if enc InstrCodec\n  (BOP _ OP_ADD (DstSrcMI true (mkMemSpec (Some (nonSPReg EBX, Some(EDX,S4))) (#x\"12345678\")) (#x\"87654321\":DWORD))) is Some bs then bs else nil))).\n\nEnd Examples.\n*)\n", "meta": {"author": "jbj", "repo": "x86proved", "sha": "d314fa6d23c064a2be4bf686ac7da16a591fda01", "save_path": "github-repos/coq/jbj-x86proved", "path": "github-repos/coq/jbj-x86proved/x86proved-d314fa6d23c064a2be4bf686ac7da16a591fda01/src/x86/instrcodec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23859554393525104}}
{"text": "Require Import Coq.Arith.Peano_dec.\nRequire Import Coq.Structures.OrderedType.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Sets.Ensembles.\nRequire Import Ascii.\nRequire Import Coq.ZArith.Znat.\nRequire Import Coq.Program.Equality.\n\nAdd LoadPath \".\" as Top0.\nRequire Import Top0.Tactics.\nRequire Import Top0.Keys.\nRequire Import Top0.Definitions.\nRequire Import Top0.Nameless.\nRequire Import Top0.CorrectnessLemmas.\nRequire Import Top0.AdditionalLemmas.\nRequire Import Top0.Environment.\nRequire Import Top0.Heap. \nRequire Import Top0.Determinism.\nRequire Import Top0.Axioms.\n\nRequire Import Omega.\n\nModule TypeSoundness.\n\n  Import Heap.\n  Import Environment.\n\nModule RMapOrdProp := FMapFacts.OrdProperties R.\n\nLemma subst_rho_open_close_rgn :\n  forall rho n w v' rho' r r0 x,\n    lc_type_rgn r0 ->\n    find_R w rho = Some v' ->\n    fold_subst_rgn rho r = fold_subst_rgn rho' (closing_rgn_in_rgn2 n x r0) ->\n    fold_subst_rgn rho' (opening_rgn_in_rgn2 n (Rgn2_Const true true v') (closing_rgn_in_rgn2 n x r0)) =\n    fold_subst_rgn rho (opening_rgn_in_rgn2 n (mk_rgn_type w) r).\nProof. \n  intros rho n w v' rho' r r0 x Hlc1 HF H.\n  unfold rgn2_in_typ in r.\n  unfold rgn2_in_typ in r0. \n  unfold rgn2_in_exp in w.\n  dependent induction r; dependent induction Hlc1; simpl in *.\n  - repeat rewrite subst_rho_rgn_const in *. auto.\n  - destruct (RMapP.eq_dec r0 x); subst; simpl in *.\n    + rewrite subst_rho_index in H. rewrite subst_rho_rgn_const in H. inversion H.\n    + auto.\n  - auto.\n  - destruct (RMapP.eq_dec r x); subst; simpl in *.\n    + rewrite subst_rho_index in H.\n      destruct (subst_rho_fvar_1 rho n0) as [[v H0] | H0];\n      rewrite H0 in H; inversion H.\n    + auto.\n  - rewrite subst_rho_index in H. rewrite subst_rho_rgn_const in H. inversion H.\n  - destruct (RMapP.eq_dec r x); subst; simpl in *.\n    + repeat rewrite subst_rho_index in H. inversion H; subst.\n      rewrite NPeano.Nat.eqb_refl.\n      rewrite subst_rho_rgn_const.\n      dependent induction w; simpl.\n      * inversion HF; subst.\n        rewrite subst_rho_rgn_const.\n        reflexivity.\n      * inversion HF. symmetry.\n        apply subst_rho_fvar_2. now simpl.\n    + rewrite subst_rho_index in H.\n      destruct (subst_rho_fvar_1 rho' r) as [[v H0] | H0];\n      rewrite H0 in H; inversion H.\nQed.\n\nLemma subst_rho_open_close_sa:\n  forall rho n w v' rho' sa sa1 x,\n    lc_type_sa sa ->\n    find_R w rho = Some v' ->\n    fold_subst_sa rho sa1 = fold_subst_sa rho' (closing_rgn_in_sa2 n x sa) ->\n    fold_subst_sa rho' (opening_rgn_in_sa2 n (Rgn2_Const true true v') (closing_rgn_in_sa2 n x sa)) =\n    fold_subst_sa rho (opening_rgn_in_sa2 n (mk_rgn_type w) sa1).\nProof.\n  intros rho n w v' rho' sa sa1 x Hlc HF H.\n  unfold fold_subst_sa.\n  inversion Hlc; subst; induction sa1;\n  unfold fold_subst_sa in H; inversion H; simpl in *;\n  erewrite subst_rho_open_close_rgn; eauto.\nQed.    \n\nLemma subst_rho_open_close_eps:\n  forall rho n w v' rho' e e1 x,\n    lc_type_eps e ->\n    find_R w rho = Some v' ->\n    fold_subst_eps rho e1 = fold_subst_eps rho' (closing_rgn_in_eps2 n x e) ->\n    fold_subst_eps rho' (opening_rgn_in_eps2 n (Rgn2_Const true true v') (closing_rgn_in_eps2 n x e)) =\n    fold_subst_eps rho (opening_rgn_in_eps2 n (mk_rgn_type w) e1).\nProof.\n  intros rho n w v' rho' e e1 x  Hcl1 HF H. \n  apply Extensionality_Ensembles.  \n  unfold Same_set, Included.\n  split; intros; unfold In in *.\n  - unfold fold_subst_eps.  unfold fold_subst_eps in H0. \n    unfold opening_rgn_in_eps2, closing_rgn_in_eps2. unfold opening_rgn_in_eps2, closing_rgn_in_eps2 in H0.\n    destruct H0 as [sa [[sa' [[sa'' [H2 H3]] H4]] H5]].\n    rewrite <- H5. rewrite <- H4. rewrite <- H3.\n    inversion Hcl1. destruct (H0 sa'').\n\n    assert (fold_subst_sa rho sa = fold_subst_sa rho' (closing_rgn_in_sa2 n x sa'') /\\ e1 sa /\\ e sa'') \n      by (eapply subst_rho_eps_aux_1; eauto).\n\n    assert(H' : fold_subst_sa rho' (opening_rgn_in_sa2 n (Rgn2_Const true true v') \n                  (closing_rgn_in_sa2 n x sa'')) =  \n                fold_subst_sa rho (opening_rgn_in_sa2 n (mk_rgn_type w) sa)) \n    by (apply subst_rho_open_close_sa; auto; intuition).\n    rewrite H'. \n    exists (opening_rgn_in_sa2 n (mk_rgn_type w) sa).\n    intuition.\n    exists sa.\n    split; [ assumption | reflexivity].\n - unfold fold_subst_eps.  unfold fold_subst_eps in H0. \n   unfold opening_rgn_in_eps2, closing_rgn_in_eps2. unfold opening_rgn_in_eps2, closing_rgn_in_eps2 in H0.\n   destruct H0 as [sa [[sa' [H1 H2]] H3]].\n   rewrite <- H3. rewrite <- H2.    \n   exists (opening_rgn_in_sa2 n (Rgn2_Const true true v') (closing_rgn_in_sa2 n x sa)). \n   inversion Hcl1. destruct (H0 sa).\n   split.  \n   + exists (closing_rgn_in_sa2 n x sa).  split; [ | reflexivity].\n     exists sa. split; [ | reflexivity].  \n     apply subst_rho_eps_aux_1 with (sa := sa') (sa':=sa) in H; auto.\n   + eapply subst_rho_open_close_sa; eauto. \n     apply subst_rho_eps_aux_1 with (sa := sa') (sa':=sa) in H; auto.\n     destruct H as [A [B C]]; auto.\nQed.\n   \nLemma subst_rho_open_close :\n  forall rho w v' rho' x tyr0 tyr,\n    lc_type tyr0 ->\n    find_R w rho = Some v' ->\n    subst_rho rho' (close_var x tyr0) = subst_rho rho tyr ->\n    subst_rho rho' (open (mk_rgn_type (Rgn2_Const true false v')) (close_var x tyr0)) =\n    subst_rho rho (open (mk_rgn_type w) tyr).\nProof.\n  unfold open, close_var.\n  intros rho w v' rho' x tyr0 tyr Hcl1 HF.  \n  generalize dependent 0.   \n  generalize dependent tyr. generalize dependent tyr0. \n  induction tyr0; induction tyr; intros n;\n  simpl;\n  repeat (rewrite subst_rho_natural ||\n                  rewrite subst_rho_boolean ||\n                  rewrite subst_rho_unit ||\n                  rewrite subst_rho_forallrgn ||\n                  rewrite subst_rho_effect ||\n                  rewrite subst_rho_pair\n         );\n  try (solve [intro Z; inversion Z | intro Y; reflexivity | intro X; assumption |\n              intros; rewrite subst_rho_tyref in H; inversion H |\n              intros; rewrite subst_rho_arrow in H; inversion H ]).\n  - inversion Hcl1; subst. \n    intros. f_equal; inversion H.  \n    + erewrite <- IHtyr0_1; eauto.\n    + erewrite <- IHtyr0_2; eauto. \n  - intro. symmetry in H. rewrite  subst_rho_tyref in H.\n    rewrite  subst_rho_tyref in H. inversion H as [ [HR1 HR2] ].\n    repeat rewrite subst_rho_tyref. f_equal.\n    + erewrite subst_rho_open_close_rgn; eauto. now inversion Hcl1.\n    + erewrite IHtyr0; eauto. now inversion Hcl1. \n  - intro. symmetry in H. rewrite  subst_rho_arrow in H.\n    rewrite  subst_rho_tyref in H. now inversion H.\n  - intro.  rewrite  subst_rho_tyref in H. rewrite  subst_rho_arrow in H. now inversion H.\n  - repeat rewrite subst_rho_arrow. intro Z. inversion Z.\n    f_equal.\n    + rewrite <- IHtyr0_1; auto. now inversion Hcl1.\n    + apply subst_rho_open_close_eps; [ now inversion Hcl1 | assumption | now inversion Z].  \n    + rewrite <- IHtyr0_2; auto. now inversion Hcl1.\n    + apply subst_rho_open_close_eps; [ now inversion Hcl1 | assumption | now inversion Z].  \n    + rewrite <- IHtyr0_3; auto. now inversion Hcl1.\n  - repeat rewrite subst_rho_forallrgn.\n    intro Z; inversion Z.\n     f_equal.\n    + apply subst_rho_open_close_eps; [ now inversion Hcl1 | assumption | now inversion Z].\n    + rewrite <- IHtyr0; auto. now inversion Hcl1.\nQed.\n\nLemma ty_sound_var :   \n  forall x v stty rho env ctxt t,\n  TcEnv (stty, rho, env, ctxt) ->\n  find_E x env = Some v -> find_T x ctxt = Some t -> \n  TcVal (stty, v, subst_rho rho t).\nProof.\n  intros x v stty rho env ctxt t HTcEnv FindEnv FindCtxt. (* Hclosed. *)\n  inversion_clear HTcEnv as [? ? ? ? HBst HFwd HBack HTc].\n  destruct (HFwd x v FindEnv) as [y FindEnv']. \n  rewrite FindEnv' in FindCtxt. inversion FindCtxt; subst. \n  eapply HTc; [eexact FindEnv | eexact FindEnv' ]. (*| assumption]. *)\nQed.\n \nLemma ty_sound_closure:  \n  forall stty rgns env rho ctxt f x ec ee tyx tyc effc effe, \n    TcRho (rho, rgns) ->\n    TcInc (ctxt, rgns)->\n    TcEnv (stty, rho, env, ctxt) ->\n    TcExp (ctxt, rgns,  Mu f x ec ee, Ty2_Arrow tyx effc tyc effe Ty2_Effect, Empty_Static_Action) -> \n    TcVal (stty, Cls (env, rho,  Mu f x ec ee),  subst_rho rho (Ty2_Arrow tyx effc tyc effe Ty2_Effect)).   \nProof.\n  intros; econstructor; eauto.\nQed.\n\nLemma ty_sound_region_closure:\n  forall stty rgns env rho ctxt x er tyr effr, \n    TcRho (rho, rgns) -> \n    TcInc (ctxt, rgns) ->\n    TcEnv (stty, rho, env,ctxt) ->\n    TcExp (ctxt, rgns, Lambda x er, Ty2_ForallRgn (close_var_eff x effr) (close_var x tyr),  Empty_Static_Action) ->\n    TcVal (stty, Cls (env, rho, Lambda x er), subst_rho rho (Ty2_ForallRgn (close_var_eff x effr) (close_var x tyr))).\nProof.\n  intros. econstructor; eauto.\nQed.  \n  \nLemma weakening_trans :\n   forall stty stty' stty'', \n     (forall (l : ST.key) (t : tau),\n        ST.find (elt:=tau) l stty = Some t -> ST.find (elt:=tau) l stty' = Some t) ->\n     (forall (l : ST.key) (t : tau),\n        ST.find (elt:=tau) l stty' = Some t -> ST.find (elt:=tau) l stty'' = Some t) ->\n     (forall (l : ST.key) (t : tau),\n        ST.find (elt:=tau) l stty = Some t -> ST.find (elt:=tau) l stty'' = Some t).\nProof.\n  intros stty stty' stty'' Weak Weak'.\n  intros l t ?. apply Weak'. now apply Weak. \nQed.\n\nLemma bound_var_is_fresh :\n  forall rho rgns  x,\n    TcRho (rho, rgns) -> not_set_elem rgns x -> ~ R.In (elt:=Region) x rho.\nProof.\n  intros rho rgns x H1 H2.\n  inversion H1; subst.\n  unfold not_set_elem in H2. unfold Ensembles.Complement in H2. \n  unfold not. intro. \n  apply RMapP.in_find_iff in H. \n  apply H2. \n  eapply H0; eassumption.\nQed.  \n\n\n\nLemma ty_sound:\n  forall e env rho hp hp' v dynamic_eff,\n    (hp, env, rho, e) ⇓ (hp', v, dynamic_eff) ->\n    forall stty ctxt rgns t static_eff,\n      TcHeap (hp, stty) ->\n      TcRho (rho, rgns) ->\n      TcEnv (stty, rho, env, ctxt) ->\n      TcExp (ctxt, rgns, e, t, static_eff) ->\n      exists stty',\n        (forall l t', ST.find l stty = Some t' -> ST.find l stty' = Some t')\n         /\\ TcHeap (hp', stty')\n         /\\ TcVal (stty', v, subst_rho rho t).\nProof.\n  intros e env rho hp hp'  v dynamic_eff D.\n  dynamic_cases (dependent induction D) Case;\n  intros stty ctxt rgns t static_eff Hhp Hrho Henv Hexp; \n  inversion Hexp; subst.   \n  Case \"cnt n\".\n    exists stty; (split; [| split]; auto). rewrite subst_rho_natural.\n    econstructor; eassumption.\n  Case \"bool b\".\n    exists stty;  (split; [| split]; auto). rewrite subst_rho_boolean.\n    econstructor; eassumption. \n  Case \"var x\".\n    exists stty; (split; [| split]; auto).\n    eapply ty_sound_var; eassumption. \n  Case \"mu_abs\". \n    exists stty; (split; [| split]; auto).\n    eapply ty_sound_closure; try (solve [eassumption]). auto.\n    assert (TcInc (ctxt, rgns)) by admit.\n    auto.\n  Case \"rgn_abs\". \n    exists stty;  (split; [| split]; auto). \n    eapply ty_sound_region_closure; try (solve [eassumption]). auto.\n    assert (TcInc (ctxt, rgns)) by admit.\n    auto.\n  Case \"mu_app\".   \n    edestruct IHD1 as [sttym [Weak1 [TcHeap1 TcVal_mu]]]; eauto. \n    edestruct IHD2 as [sttya [Weaka [TcHeapa TcVal_arg]]]; eauto.  \n    eapply ext_stores__env; eauto.  \n    inversion TcVal_mu as [ | | | ? ? ? ? ? ? ? ?  TcRho_rho' TcEnv_env' TcExp_abs | | |] ; subst.      \n    inversion TcExp_abs as [ | |  | ? ? ? ? ? ? ? ? ? ? ? ? TcExp_ec TcExp_ee | | | | | | | | | | | | | | | | | | | | | ]; subst. \n    rewrite <- H5 in TcVal_mu. \n    do 2 rewrite subst_rho_arrow in H5. inversion H5.\n    assert (SubstEq1: subst_rho rho' tyx = subst_rho rho tya) by assumption. \n    assert (SubstEq2: subst_rho rho' tyc = subst_rho rho t) by assumption.\n    rewrite <- SubstEq1 in TcVal_arg.\n    unfold update_rec_E, update_rec_T in *. \n    edestruct IHD3 as [sttyb [Weakb [TcHeapb TcVal_res]]]; eauto.\n    SCase \"TcEnv\". \n     apply update_env. apply update_env. eapply ext_stores__env; eauto.  \n     eapply ext_stores__val; eauto. eassumption.\n     exists sttyb; intuition.  \n  Case \"rgn_app\".     \n    edestruct IHD1 as [sttyl [Weak1 [TcHeap1 TcVal_lam]]]; eauto. \n    inversion TcVal_lam as  [ | | | ? ? ? ? ? ? ?  TcRho_rho' TcInc'  TcEnv_env' TcExp_lam | | |]; subst.   \n    inversion TcExp_lam as [ | | | | ? ? ? ? ? ? ? ? ? TcExp_eb | | | | | | | | | | | | | | | | | | | |  ]; subst.  \n    edestruct IHD2 as [sttyr [Weak2 [TcHeap2 TcVal_res]]]; eauto using update_env, ext_stores__env.\n    apply update_rho. assumption. assumption. eapply extended_rho; eauto. \n    exists sttyr; intuition. \n    rewrite subst_rho_forallrgn in H5.\n    rewrite subst_rho_forallrgn in H5.\n    inversion H5.  \n    unfold update_R in TcVal_res. \n    simpl in TcVal_res. rewrite subst_add_comm in TcVal_res.\n    SCase \"abstraction body is well typed\".\n    unfold subst_in_type in TcVal_res.\n    rewrite SUBST_AS_CLOSE_OPEN in TcVal_res; auto.\n    erewrite subst_rho_open_close in TcVal_res; eauto. \n    SCase \"bound variable is free\".\n    eapply bound_var_is_fresh; eauto.\n  Case \"eff_app\".\n    edestruct IHD1 as [sttym [Weak1 [TcHeap1 TcVal_mu]]]; eauto.\n    edestruct IHD2 as [sttya [Weaka [TcHeapa TcVal_arg]]]; eauto using ext_stores__env.\n    inversion TcVal_mu as  [ | | | ? ? ? ? ? ? ? TcRho_rho' TcInc' TcEnv_env' TcExp_abs | | |]; subst. \n    inversion TcExp_abs as [ | | | | ? ? ? ? ? ? ? ? ? TcExp_eb | | | | | | | | | | | | | | | | | | | |  ]; subst. \n    edestruct IHD3 as [sttyb [Weakb [TcHeapb TcVal_res]]]; eauto.\n    SCase \"Extended Env\".\n      apply update_env.\n      SSCase \"TcEnv\". apply update_env.\n        SSSCase \"Extended\". eapply ext_stores__env; eauto.\n        SSSCase \"Extended TcVal\". rewrite <- H4 in TcVal_mu.  eapply ext_stores__val; eauto.\n      SSCase \"TcVal\". do 2 rewrite subst_rho_arrow in H4.\n          inversion H4.\n          assert (SubstEq: subst_rho rho' tyx = subst_rho rho tya) by assumption.\n          rewrite <- SubstEq in TcVal_arg.  eassumption. \n    exists sttyb. intuition.\n    rewrite subst_rho_effect. rewrite subst_rho_effect in TcVal_res.\n    assumption.\n  Case \"par_pair\". \n    edestruct IHD3 as [sttym [Weak1 [TcHeap1 TcVal_app1]]]; eauto. \n    edestruct IHD4 as [sttya [Weaka [TcHeapa TcVal_app2]]]; eauto. \n    (*inversion TcVal_app1 as [A B [C D HRApp1] | | | | | |]; subst. \n    inversion TcVal_app2 as [A B [C D HRApp2] | | | | | |]; subst.*)  \n    exists (Functional_Map_Union sttya sttym). intuition. \n    SCase \"Weakening\". \n      apply UnionStoreTyping; [apply Weaka | apply Weak1]; auto.\n    SCase \"TcHeap\".\n      eapply UnionTcHeap with (theta1:=theta1) (theta2:=theta2); eauto.  \n    SCase \"TcVal\".\n      rewrite subst_rho_pair. \n      econstructor; [eapply TcValExtended_2 | eapply TcValExtended_1]; eauto.\n  Case \"cond_true\".  \n    edestruct IHD1 as [sttyb [Weakb [TcHeapvb TcVal_e0]]]; eauto. \n    edestruct IHD2 as [stty1 [Weak1 [TcHeapv1 TcVal_e1]]]; \n      eauto using ext_stores__env.\n    exists stty1. intuition.\n  Case \"cond_false\".\n    edestruct IHD1 as [sttyb [Weakb [TcHeapvb TcVal_e0]]]; eauto. \n    edestruct IHD2 as [stty2 [Weak2 [TcHeapv2 TcVal_e2]]]; \n      eauto using ext_stores__env.\n    exists stty2. intuition.  \n  Case \"new_ref e\".          \n    destruct IHD with (stty := stty)\n                      (ctxt := ctxt)\n                      (rgns := rgns)  \n                      (t := t0)\n                      (static_eff := veff)\n      as [sttyv [Weakv [TcHeapv TcVal_v]]]; eauto.\n    assert (find_H (r, allocate_H heap' r) heap' = None)\n      by (apply allocate_H_fresh).\n    exists (update_ST ((r, allocate_H heap' r), subst_rho rho t0) sttyv); split; [ | split].  \n    SCase \"Extended stores\".   \n      intros k' t' STfind. destruct k' as [r' l']. \n      destruct (eq_nat_dec r r'); destruct (eq_nat_dec (allocate_H heap' r) l'); subst. \n      SSCase \"New address must be fresh, prove by contradiction\".\n        apply Weakv in STfind. \n        inversion_clear TcHeapv as [? ? ?  STfind_Hfind ?].  \n        destruct (STfind_Hfind (r', allocate_H heap' r') t' STfind) as [x F].\n        assert (C : None = Some x) by (rewrite <- F; rewrite <- H0; reflexivity).\n        discriminate. \n      SSCase \"Existing addresses are well-typed 1\".\n        apply ST_diff_key_2; [ simpl; intuition; apply n; congruence | now apply Weakv in STfind ].\n      SSCase \"Existing addresses are well-typed 2\".\n        apply ST_diff_key_2; [ simpl; intuition; apply n; congruence | now apply Weakv in STfind ].\n      SSCase \"Existing addresses are well-typed 3\".\n        apply ST_diff_key_2; [simpl; intuition; apply n; congruence | now apply Weakv ].\n    SCase \"Heap typeness\".  \n      apply update_heap_fresh; eauto. \n      remember (find_ST (r, allocate_H heap' r) sttyv) as to; symmetry in Heqto.\n      destruct to as [ t | ]. \n      SSCase \"New address must be fresh, prove by contradiction\".\n        inversion_clear TcHeapv as [? ? ? STfind_Hfind ?].  \n        destruct (STfind_Hfind (r, allocate_H heap' r) t Heqto) as [? ex].\n        rewrite H0 in ex. discriminate.\n      SSCase \"Heap typeness is preserved\".\n         reflexivity. \n    SCase \"Loc is well-typed\".\n       simpl in H; inversion H; subst. \n       rewrite subst_rho_tyref. unfold mk_rgn_type. rewrite subst_rho_rgn_const.\n       econstructor. apply ST_same_key_1.\n       intro.\n       eapply TcVal_implies_closed in TcVal_v; eauto.\n  Case \"get_ref e\".    \n    destruct IHD with (hp'0 := hp')\n                      (v := Loc (Rgn2_Const true false s) l) \n                      (stty := stty)\n                      (rgns := rgns)\n                      (ctxt := ctxt)\n                      (t := Ty2_Ref (mk_rgn_type ((Rgn2_Const true false s))) t)\n                      (static_eff := aeff)\n                      (dynamic_eff := aacts)\n    as [sttyv [Weakv [TcHeapv TcVal_v]]]; eauto.\n    exists sttyv. split; [ | split].\n    SCase \"HeapTyping extends\".\n      apply Weakv.\n    SCase \"Heap is well typed\".\n      apply TcHeapv.\n    SCase \"Value is well-typed\". \n      inversion_clear TcHeapv as [? ? ? ? HeapTcVal]. eapply HeapTcVal; eauto. \n      inversion TcVal_v; subst; simpl in H; inversion H; subst.\n      rewrite subst_rho_tyref in H7. inversion H7. subst.\n      assumption.\n  Case \"set_ref e1 e2\".  \n    destruct IHD1 with (hp' := heap')\n                       (v := Loc (Rgn2_Const true false s) l) \n                       (stty := stty)\n                       (ctxt := ctxt)\n                       (rgns := rgns)\n                       (t := Ty2_Ref (mk_rgn_type ((Rgn2_Const true false s))) t0)\n                       (static_eff := aeff)\n                       (dynamic_eff := aacts)\n       as [sttya [Weaka [TcHeapa TcVal_a]]]; eauto.\n    destruct IHD2 with (stty := sttya)\n                       (ctxt := ctxt)\n                       (rgns := rgns)  \n                       (t := t0)\n                       (static_eff := veff)\n      as [sttyv [Weakv [TcHeapv TcVal_v]]]; eauto using ext_stores__env.\n    exists sttyv. split; [ | split].\n    SCase \"HeapTyping extends\".\n      eapply weakening_trans; eauto.\n    SCase \"New heap is well typed\". \n      apply update_heap_exists with (t:= subst_rho rho t0).   \n      { assumption. }\n      { apply Weakv. inversion TcVal_a; subst. \n        simpl in H; inversion H; subst.\n        rewrite subst_rho_tyref in H4. inversion H4. subst.\n        assumption. }\n      { assumption. }\n    SCase \"Result value is well-typed\".\n      rewrite subst_rho_unit. constructor.\n  Case \"nat_plus x y\". \n    edestruct IHD1 as [sttyx [Weakx [TcHeapvx TcVal_x]]]; eauto. \n    edestruct IHD2 as [sttyy [Weaky [TcHeapvy TcVal_y]]]; \n      eauto using ext_stores__env. \n    exists sttyy. intuition. rewrite subst_rho_natural. constructor.\n  Case \"nat_minus x y\". \n    edestruct IHD1 as [sttyx [Weakx [TcHeapvx TcVal_x]]]; eauto. \n    edestruct IHD2 as [sttyy [Weaky [TcHeapvy TcVal_y]]]; \n      eauto using ext_stores__env.\n    exists sttyy. intuition. rewrite subst_rho_natural. constructor.\n  Case \"nat_times x y\". \n    edestruct IHD1 as [sttyx [Weakx [TcHeapvx TcVal_x]]]; eauto. \n    edestruct IHD2 as [sttyy [Weaky [TcHeapvy TcVal_y]]]; \n      eauto using ext_stores__env.\n    exists sttyy. intuition. rewrite subst_rho_natural. constructor.\n  Case \"bool_eq x y\". \n    edestruct IHD1 as [sttyx [Weakx [TcHeapvx TcVal_x]]]; eauto. \n    edestruct IHD2 as [sttyy [Weaky [TcHeapvy TcVal_y]]]; \n      eauto using ext_stores__env.\n    exists sttyy. intuition. rewrite subst_rho_boolean. constructor.\n  Case \"alloc_abs\".\n    exists stty. intuition. rewrite subst_rho_effect. constructor.\n  Case \"read_abs\".\n    exists stty. intuition. rewrite subst_rho_effect. constructor.\n  Case \"write_abs\".\n    exists stty. intuition. rewrite subst_rho_effect. constructor.\n  Case \"read_conc\".\n    exists stty. intuition.\n    assert (hp = hp') by (eapply EmptyTracePreservesHeap_1; eauto; reflexivity); now subst.\n    rewrite subst_rho_effect. constructor.      \n  Case \"write_conc\".\n    exists stty. intuition.\n    assert (hp = hp') by (eapply EmptyTracePreservesHeap_1; eauto; reflexivity); now subst.\n    rewrite subst_rho_effect. constructor. \n  Case \"eff_concat\". exists stty. intuition. rewrite subst_rho_effect. constructor.\n  Case \"eff_top\". exists stty. intuition. rewrite subst_rho_effect. constructor.\n  Case \"eff_empty\". exists stty. intuition. rewrite subst_rho_effect. constructor.\nAdmitted.\n\nEnd TypeSoundness.\n", "meta": {"author": "esmifro", "repo": "SurfaceEffects", "sha": "3450e4b771de4062ab73ee20947adf3f9de579ba", "save_path": "github-repos/coq/esmifro-SurfaceEffects", "path": "github-repos/coq/esmifro-SurfaceEffects/SurfaceEffects-3450e4b771de4062ab73ee20947adf3f9de579ba/TypeSystem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.2385084879110777}}
{"text": "(*\n * Coq code for \"Certified Assembly Programming with Embedded Code Pointers\"\n *\n * XCAP\n *\n * (for Coq version 8)\n *)\n\nRequire Import ZArith.\nRequire Import Eqdep.\nRequire Import Map.\nRequire Import Mapt.\nRequire Import tm.\nRequire Import tylist.\nRequire Import axiom.\nRequire Import propx.\nRequire Import seplogic.\n\nOpen Scope Z_scope.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n\nDefinition Itp P Si := OK nil Si P.\n\nNotation \"[[ P ]]. Si\" := (Itp P Si) (at level 130).\n\nNotation ItP := (fun a Si S => [[a S]].Si) (only parsing).\n\nNotation \"[[ a ]] Si\" := ((fun a Si S => [[a S]].Si) a Si) (at level 130).\n\nNotation Subsume :=\n  (fun a a' =>\n   forall Si S,\n   (fun a Si S => [[a S]].Si) a Si S ->\n   (fun a' Si S => [[a' S]].Si) a' Si S) (only parsing).\n\nNotation \"p ==>xcap q\" :=\n  ((fun a a' =>\n    forall Si S,\n    (fun a Si S => [[a S]].Si) a Si S ->\n    (fun a' Si S => [[a' S]].Si) a' Si S) p q)\n  (at level 130, right associativity).\nNotation \"p ==> q\" := (p ==>xcap q) (at level 130, right associativity).\n\nInductive InstrSeq : Set := instr  : Instr -> InstrSeq\n                          | instr' : Instr -> Word -> InstrSeq\n                          | iseq   : Instr -> InstrSeq -> InstrSeq.\n\nDefinition CodeHeap := Map.Map Label InstrSeq.\n\nFixpoint Di (l : Label) (i : InstrSeq) (H : Heap) (lpc : Label) {struct i} : Prop :=\n  match i with\n    instr c => Dc H l c lpc\n  | instr' c npc => Dc H l c npc /\\ npc = lpc\n  | iseq c i => exists npc, Dc H l c npc /\\ Di npc i H lpc\n  end.\n\nDefinition DC C H := (forall l i, Map.lookup C l i -> exists lpc, Di l i H lpc)\n                  /\\ (forall l, Map.in_dom H l ->\n                        exists l', exists i, exists lpc,\n                          Di l' i H lpc /\\ l' <= l < lpc).\n\nInductive WFiseq : CdHpSpec -> Assertion -> InstrSeq -> Prop :=\n  | wfiseq  : forall Si a c I a',\n                (a ==> (fun s => Ex s' .\n <<Next c s s'>> ./\\ a' s')) ->\n                WFiseq Si a' I                         -> WFiseq Si a (iseq c I)\n  | wfjcc   : forall Si a cc f I a' a'',\n                ((fun s => <<~(Fcc (_F s) cc)>> ./\\ a s) ==> a'') ->\n                ((fun s => <<Fcc (_F s) cc>> ./\\ a s) ==> a') ->\n                lookup Si f a' -> WFiseq Si a'' I\n                                              -> WFiseq Si a (iseq (jcc cc f) I)\n  | wfjmpi  : forall Si a f a', lookup Si f a' -> (a ==> a')\n                                           -> WFiseq Si a (instr (jmp (word f)))\n  | wfjmpr  : forall Si a r,\n                (a ==> fun S => extv _ _ (eq_rect _ _\n                                  (cptr _ (_R S r) (var _ _) ./\\ var _ _ S)\n                                  _ (eq_tplus_tO _)))\n                                            -> WFiseq Si a (instr (jmp (reg r)))\n  | wfcalli : forall Si a f fret a', lookup Si f a' ->\n                (a ==> (fun s => Ex s'.\n                                   <<Next (push (word fret)) s s'>> ./\\ a' s'))\n                                    -> WFiseq Si a (instr' (call (word f)) fret)\n  | wfcallr : forall Si a r fret,\n                (a ==> (fun S => extv _ _ (eq_rect _ _\n                                  (cptr _ (_R S r) (var _ _) ./\\\n                                   Ex s'.\n                                     <<Next (push (word fret)) S s'>> ./\\ var _ _ s')\n                                  _ (eq_tplus_tO _))))\n                                            -> WFiseq Si a (instr' (call (reg r)) fret)\n  | wfret   : forall Si a,\n                (a ==> (fun S => Ex fret.\n                                   <<Map.lookup (_H S) (_R S esp) fret>> ./\\\n                                  extv _ _ (eq_rect _ _\n                                  (cptr _ fret (var _ _) ./\\\n                                   Ex s'.\n                                     <<Next pop' S s'>> ./\\ var _ _ s')\n                                  _ (eq_tplus_tO _))))\n                                            -> WFiseq Si a (instr ret)\n  | wfecp   : forall Si a f a' a'' I, WFiseq Si a' I -> lookup Si f a'' ->\n               ((fun s => cptr _ f a'' ./\\ a s) ==> a')         -> WFiseq Si a I.\n\nNotation \"Si |-xcap{ a } i\" := (WFiseq Si a i) (at level 130).\nNotation \"Si |-{ a } i\" := (Si |-xcap{ a}i) (at level 130).\n\nInductive WFcode : CdHpSpec -> CodeHeap -> CdHpSpec -> Prop :=\n  | wfcdhp : forall Si Si' C,\n               (forall l a, lookup Si' l a\n                  -> exists I, Map.lookup C l I /\\ (Si' |-{ a}I))\n                                                              -> WFcode Si C Si'\n  | wflink :\n      forall Si1 Si2 Si'1 Si'2 C1 C2 Si Si',\n      WFcode Si1 C1 Si'1 ->\n      WFcode Si2 C2 Si'2 ->\n      Map.disjoint C1 C2 ->\n      subseteq Si1 (merge Si1 Si2) ->\n      subseteq Si2 (merge Si1 Si2) ->\n      (forall l, merge Si1 Si2 l = Si l) ->\n      (forall l, merge Si'1 Si'2 l = Si' l)   -> WFcode Si (Map.merge C1 C2) Si'.\n\nNotation \"Si |-xcap C :: Si'\" := (WFcode Si C Si') (at level 130).\nNotation \"Si |- C :: Si'\" := (Si |-xcap C :: Si') (at level 130).\n\nDefinition WFprogram Si a (P : Program) :=\n  let (s, pc) := P in let (HR, F) := s in let (H, R) := HR in exists C, exists i,\n  (Si |- C :: Si) /\\ (Si |-{a} i) /\\\n  [[star (fun H => <<(exists npc, Di pc i H npc) /\\ DC C H>>)\n         (fun H => a (H, R, F)) H]]. Si.\n\nNotation \"Si |-xcap[ a ] P\" := (WFprogram Si a P) (at level 130).\nNotation \"Si |-[ a ] P\" := (Si |-xcap[ a]P) (at level 130).\n\nLemma disjoint_uH_disjoint_2 : forall H H' H'' l w,\n  uH H' H'' l w -> Map.disjoint H H' -> Map.disjoint H H''.\nintros.\ndestruct H0.\n destruct H2.\n unfold Map.disjoint.\n intro.\n generalize (H1 a).\ndestruct (H a); auto.\n destruct (Z_eq_dec l a).\n rewrite e in H0.\n destruct H0.\nrewrite H0.\n tauto.\n rewrite (H3 a n).\n auto.\nQed.\n\nLemma disjoint_uH_merge_uH : forall h1 h2 h3 l w,\n  Map.disjoint h1 h2 -> uH h2 h3 l w -> uH (Map.merge h1 h2) (Map.merge h1 h3) l w.\nintros.\n destruct H0.\n destruct H1.\nsplit.\n generalize H0.\n unfold Map.in_dom, Map.merge.\n destruct (h1 l).\nintro.\n exists w0.\n auto.\n auto.\nsplit.\n generalize H1.\n unfold Map.lookup, Map.merge.\n generalize (H l).\ndestruct (h1 l).\n destruct H0.\n rewrite H0.\n tauto.\nauto.\nintros.\n generalize (H2 _ H3).\n unfold Map.merge.\n generalize (H l).\ndestruct (h1 l).\n destruct H0.\n rewrite H0.\n tauto.\nintros.\n rewrite H5.\n auto.\nQed.\n\n\nLemma InstrSeqWeakening : forall Si Si' a a' I,\n                            (Si |-{a'} I) -> (subseteq Si Si') -> (a ==> a')\n                                                                -> (Si' |-{a} I).\nintros; move H after Si'; generalize a H0 H1; clear a H0 H1.\ninduction H; intros.\napply wfiseq with a'.\nauto.\napply IHWFiseq; auto.\napply wfjcc with a' a''; intros.\napply H.\nunfold Itp in *.\ndest H5.\napply ok_and_i; auto.\napply H0.\nunfold Itp in *.\ndest H5.\napply ok_and_i; auto.\nunfold subseteq in H3.\nunfold lookup in *.\ngeneralize (H3 f).\nrewrite H1.\nauto.\nauto.\napply wfjmpi with a'.\nunfold lookup in *.\ngeneralize (H1 f).\nrewrite H.\nauto.\nauto.\napply wfjmpr.\nintros.\ngeneralize (H Si0 S (H1 Si0 S H2)).\nsimpl.\nauto.\napply wfcalli with a'.\nunfold lookup in *.\ngeneralize (H1 f).\nrewrite H.\nauto.\nauto.\napply wfcallr.\nintros.\ngeneralize (H Si0 S (H1 Si0 S H2)).\nsimpl.\nauto.\napply wfret.\nintros.\ngeneralize (H Si0 S (H1 Si0 S H2)).\nsimpl.\nauto.\napply wfecp with f a' a''.\napply IHWFiseq.\nauto.\nauto.\ninversion H0.\ngeneralize (H2 f).\nrewrite H5.\nauto.\nintros.\nunfold lookup.\nauto.\nintros.\napply H1.\nauto.\nunfold Itp.\napply ok_and_i.\napply (ok_and_e1 _ _ _ _ H4).\napply H3.\napply (ok_and_e2 _ _ _ _ H4).\nQed.\n\nLemma CodeHeapTyping :\n forall C Si l a,\n (Si |- C :: Si) ->\n lookup Si l a -> exists I : _, Map.lookup C l I /\\ (Si |-{ a}I).\nintros.\ngeneralize l a H0.\nclear l a H0.\ninduction H.\nintros.\ndestruct (H l a H0).\nsplit with x.\nauto.\nintros.\nunfold lookup in H6.\nrewrite <- (H5 l) in H6.\ndestruct (mergelookup H6).\ndestruct (IHWFcode1 l a H7).\nsplit with x.\ndestruct H8.\nsplit.\nunfold Map.lookup, Map.merge in |- *.\nunfold Map.lookup in H8.\nrewrite H8.\nauto.\napply InstrSeqWeakening with Si'1 a.\nauto.\nunfold subseteq in |- *.\nintro.\nrewrite <- (H5 a0).\nunfold merge in |- *.\ndestruct (Si'1 a0).\nauto.\nauto.\nauto.\ndestruct (IHWFcode2 l a H7).\ndestruct H8.\nsplit with x.\nsplit.\nunfold Map.lookup, Map.merge in |- *.\nunfold Map.disjoint in H1.\ngeneralize (H1 l).\ndestruct (C1 l).\nunfold Map.lookup in H8.\nrewrite H8.\ntauto.\nunfold Map.lookup in H8.\nrewrite H8.\nauto.\napply InstrSeqWeakening with Si'2 a.\nauto.\nunfold subseteq in |- *.\nintro.\nrewrite <- (H5 a0).\nunfold merge in |- *.\ngeneralize (IHWFcode2 a0).\nunfold lookup.\ndestruct (Si'2 a0).\nintros.\ngeneralize (IHWFcode1 a0).\nunfold lookup in |- *.\ndestruct (Si'1 a0).\nintros.\ndestruct (H11 a2).\nauto.\ndestruct H12.\ndestruct (H10 a1).\nauto.\ndestruct H14.\nunfold Map.lookup in H12.\nunfold Map.lookup in H14.\ngeneralize (H1 a0).\nrewrite H12.\nrewrite H14.\ntauto.\nauto.\nauto.\nauto.\nQed.\n\n\nTheorem Soundness :\n forall Si a P,\n (Si |-[ a]P) ->\n exists a' : _, (exists P' : _, (P |--> P') /\\ (Si |-[ a']P')).\nintros.\ndestruct P.\ndestruct s.\ndestruct p.\nrename w into pc.\ndestruct H.\ndestruct H.\nrename x into c.\nrename x0 into i.\ndestruct H.\ndestruct H0.\ndestv H1 ch.\ndestv H1 m.\ndest H1.\ndest H2.\ndest H2.\ndestruct H2.\ninduction H0.\nclear IHWFiseq.\ngeneralize (H0 Si (m, r, e) H3).\nintro.\ndest H6.\nexists a'.\nsimpl in H2.\ndestruct H2.\ndestruct H2.\ndestruct x0.\ndestruct p.\nexists ((Map.merge ch h0, r0, e0), x1).\nsplit.\napply stp_iseq with c0.\napply Dc_mono with ch.\nauto.\ndest H1.\nrewrite H8.\nunfold Map.subseteq, Map.merge.\nintro.\ndestruct (ch a0); auto.\ndest H1.\ndest H6.\nrewrite H8.\ngeneralize (okvalid _ _ H6).\nintro.\ninversion H10.\napply stp_add; auto.\napply stp_sub; auto.\napply stp_mov; auto.\napply stp_movrm with w; auto.\n apply Map.lookup_disj_merge_lookup_2; auto.\n rewrite <- H17.\n auto.\napply stp_movm; auto.\n apply disjoint_uH_merge_uH; auto.\napply stp_cmp; auto.\napply stp_push; auto.\n apply disjoint_uH_merge_uH; auto.\napply stp_pop with w R''; auto.\n apply Map.lookup_disj_merge_lookup_2; auto.\n  rewrite <- H15.\n auto.\napply stp_pop'; auto.\napply stp_int; auto.\nexists c.\n exists I.\n split.\n auto.\n split.\n auto.\n unfold Itp.\n unfold star.\n existsx ch.\n existsx h0.\n splitx.\n propx.\n split; auto.\n dest H1.\n dest H6.\n generalize (okvalid _ _ H6).\n intro.\n inversion H10.\n  rewrite <- H16.\n auto.\n  rewrite <- H16.\n auto.\n  rewrite <- H17.\n auto.\n  rewrite <- H17.\n auto.\n  apply disjoint_uH_disjoint_2 with m (Ra r0 d) (Ro r0 o); auto.\n  rewrite <- H17.\n auto.\n  apply disjoint_uH_disjoint_2 with m (r esp-4) (Ro r o); auto.\n  rewrite <- H15.\n auto.\n  rewrite <- H17.\n auto.\n  rewrite <- H16.\n auto.\n splitx.\n propx.\n split; auto.\n exists x.\n auto.\n dest H6.\n auto.\n(* jcc *)\ndestruct (Fcc_dec e cc).\nexists a'.\n exists (h, r, e, f).\n split.\n destruct H2.\n destruct H2.\n apply stp_jcc with cc x0; auto.\n dest H1.\n rewrite H10.\n apply Dc_mono with ch; auto.\n apply Map.subseteq_merge.\n exists c.\n destruct (CodeHeapTyping H H6).\n exists x0.\n destruct H9.\n split.\n auto.\n split.\n auto.\n unfold Itp, star.\n existsx ch.\n existsx m.\n splitx.\n auto.\n splitx.\n propx.\n split; auto.\n generalize H4.\n intro.\n destruct H11.\n auto.\n apply H5.\n unfold Itp.\n splitx.\n propx.\n auto.\n auto.\nexists a''.\n destruct H2.\n destruct H2.\n exists (h, r, e, x0).\n split.\n apply stp_jcc' with cc f; auto.\n dest H1.\n rewrite H10.\n apply Dc_mono with ch; auto.\n apply Map.subseteq_merge.\n exists c.\n exists I.\n split.\n auto.\n split.\n auto.\n unfold Itp, star.\n existsx ch.\n existsx m.\n splitx.\n auto.\n splitx.\n propx.\n split; auto.\n exists x.\n auto.\n apply H0.\n unfold Itp.\n splitx.\n propx.\n auto.\n auto.\n(* jmp f *)\nexists a'.\n destruct (CodeHeapTyping H H0).\n destruct H6.\n exists (h, r, e, f).\n cut (Ro r (word f)=f); auto.\n intro.\n split.\n rewrite <- H8.\n apply stp_jmp with x.\n dest H1.\n rewrite H9.\n apply Dc_mono with ch; auto.\n apply Map.subseteq_merge.\n exists c.\n exists x0.\n split.\n auto.\n split.\n auto.\n unfold Itp, star.\n existsx ch.\n existsx m.\n splitx.\n auto.\n splitx.\n propx.\n split; auto.\n unfold DC in H4.\n destruct H4.\n auto.\n apply H5.\n auto.\n(* jmp r *)\ngeneralize (H0 _ _ H3).\n simpl.\n intro.\n destv H5 a'.\n simpl in H5.\n exists a'.\n exists (h, r, e, Ro r (reg r0)).\n split.\n apply stp_jmp with x.\n dest H1.\n rewrite H6.\n apply Dc_mono with ch; auto.\n apply Map.subseteq_merge.\n exists c.\n dest H5.\n rewrite (ext_eq _ _ (fun x : State => a' x) a') in H5; auto.\n generalize (okvalid _ _ H5).\n simpl.\n intro.\n destruct (CodeHeapTyping H H7).\n destruct H8.\n exists x0.\n split.\n auto.\n split.\n rewrite (ext_eq _ _ (fun x : State => a' x) a') in H9; auto.\n unfold Itp, star.\n existsx ch.\n existsx m.\n splitx.\n auto.\n splitx.\n propx.\n split; auto.\n destruct H4.\n auto.\n auto.\n(* calli *)\nexists a'.\n dest H1.\n generalize (H5 _ _ H3).\n intro.\n dest H7.\n clear H5.\n dest H7.\n destruct x0.\n destruct p.\n exists (Map.merge ch h0, r0, e0, f).\n split.\n cut (Ro r (word f)=f); auto.\n intro.\n rewrite <- H8.\n apply stp_call with fret.\n rewrite H6.\n apply Dc_mono with ch; auto.\n unfold Di in H2.\n destruct H2.\n auto.\n apply Map.subseteq_merge.\n des H5.\n inversion H5.\n apply stp_push; auto.\n rewrite H6.\n  apply disjoint_uH_merge_uH; auto.\n exists c.\n destruct (CodeHeapTyping H H0).\n destruct H8.\n exists x0.\n split.\n auto.\n split.\n auto.\n unfold Itp, star.\n existsx ch.\n existsx h0.\n splitx.\n propx.\n split; auto.\n des H5.\n inversion H5.\n apply disjoint_uH_disjoint_2 with m (r esp-4) (Ro r (word fret)); auto.\n splitx.\n propx.\n split; auto.\n destruct H4.\n auto.\n auto.\n(* callr *)\ndest H1.\n generalize (H0 _ _ H3).\n clear H0.\n intro.\n destv H0 a'.\n simpl in H0.\nrewrite (ext_eq _ _ (fun x : State => a' x) a') in H0; auto.\n dest H0.\n dest H6.\ndestruct x0.\n destruct p.\n dest H6.\n des H6.\ninversion H6.\n clear H6.\n exists a'.\n exists (Map.merge ch h0, r1, e0, (Ro r (reg r0))).\nsplit.\n apply stp_call with fret.\n rewrite H5.\n apply Dc_mono with ch; auto.\nunfold Di in H2.\n destruct H2.\n auto.\n  apply Map.subseteq_merge.\napply stp_push; auto.\n rewrite H5.\n apply disjoint_uH_merge_uH; auto.\nexists c.\n des H0.\n simpl in H0.\nrewrite (ext_eq _ _ (fun S : State => a' S) a') in H0; auto.\ndestruct (CodeHeapTyping H H0).\n destruct H6.\n exists x0.\n split.\n auto.\nsplit.\n auto.\n unfold Itp, star.\n existsx ch.\n existsx h0.\n splitx.\n propx.\n split; auto.\n apply disjoint_uH_disjoint_2 with m (r esp-4) (Ro r (word fret)); auto.\nsplitx.\n propx.\n split; auto.\n destruct H4.\n auto.\n auto.\n(* ret *)\ndest H1.\n generalize (H0 _ _ H3).\n clear H0.\n intro.\n destv H0 fret.\n dest H0.\ndes H0.\n destv H6 a'.\n simpl in H6.\ndest H6.\ndes H6.\n simpl in H6.\nrewrite (ext_eq _ _ (fun S : State => a' S) a') in H6; auto.\ndest H7.\n destruct x0.\n destruct p.\n dest H7.\ndes H7.\n inversion H7.\n exists a'.\n exists (Map.merge ch h0, r0, e0, fret).\nsplit.\n rewrite H5.\n apply stp_ret with x.\nunfold Di in H2.\n auto.\n apply Dc_mono with ch; auto.\n apply Map.subseteq_merge.\napply Map.lookup_disj_merge_lookup_2; auto.\nrewrite <- H13.\n apply stp_pop'; auto.\nexists c.\n destruct (CodeHeapTyping H H6).\n destruct H18.\n exists x0.\n split.\n auto.\nsplit.\n auto.\n unfold Itp, star.\n existsx ch.\n existsx h0.\n splitx.\n propx.\n split; auto.\nrewrite <- H13.\n auto.\n splitx.\n propx.\n split; auto.\n destruct H4.\n auto.\n auto.\n(* ECP *)\napply IHWFiseq; auto.\napply H6.\n unfold Itp.\n splitx.\n apply ok_cptr_i.\n auto.\nauto.\nQed.", "meta": {"author": "mithrao", "repo": "Coq-assembly-verification", "sha": "c3ab9fea02cc7f94331888604231923069a01334", "save_path": "github-repos/coq/mithrao-Coq-assembly-verification", "path": "github-repos/coq/mithrao-Coq-assembly-verification/Coq-assembly-verification-c3ab9fea02cc7f94331888604231923069a01334/final-mctx/xcap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.2385084789580674}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import BaremoreSMC.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition granule_delegate_ops_spec (g: Pointer) (addr: Z64) (adt: RData) : option RData :=\n    match addr with\n    | VZ64 addr =>\n      let gidx := offset g in\n      rely is_int64 addr;\n      rely (peq (base g) ginfo_loc);\n      rely (gidx =? __addr_to_gidx addr);\n      rely is_gidx gidx;\n      rely Z.land (r_scr_el3 (cpu_regs (priv adt))) SCR_WORLD_MASK =? SCR_REALM_WORLD;\n      when adt == query_oracle adt;\n      let gn := (gs (share adt)) @ gidx in\n      rely prop_dec ((buffer (priv adt)) @ SLOT_DELEGATED = None);\n      rely prop_dec (glock gn = Some CPU_ID);\n      rely prop_dec (gtype gn = GRANULE_STATE_NS);\n      rely prop_dec ((gpt_lk (share adt)) @ gidx = None);\n      rely prop_dec ((gpt (share adt)) @ gidx = false);\n      let e1 := EVT CPU_ID (ACQ_GPT gidx) in\n      let e2 := EVT CPU_ID (REL_GPT gidx true) in\n      let g' := gn {ginfo: (ginfo gn) {g_tag: GRANULE_STATE_DELEGATED}}\n                   {gnorm: zero_granule_data_normal}\n                   {grec: zero_granule_data_rec} in\n      let regs' := (cpu_regs (priv adt)) {r_x0: 0} {r_x1: addr} {r_esr_el3: ESR_EC_SMC} in\n      let e' := EVT CPU_ID (REL gidx g') in\n      Some adt {log: e' :: e2 :: e1 :: (log adt)}\n           {share: (share adt) {gs: (gs (share adt)) # gidx == (g' {gtype: GRANULE_STATE_DELEGATED} {glock: None})}\n                               {gpt: (gpt (share adt)) # gidx == true}}\n           {priv: (priv adt) {cpu_regs: regs'}}\n    end.\n\nEnd Spec.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RmiOps/Specs/granule_delegate_ops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23850400037188732}}
{"text": "(* Semi-branching directed apartness *)\n\nFrom bisimulations Require Import prelude.\nFrom bisimulations Require Import system.\nFrom bisimulations Require Import relations.\nFrom bisimulations Require Import paths.\n\nSection DirectedBranchingApart.\nContext `{ReflSystem : @refl_system X System}.\n\nNotation Downstream_property l R p1 p2 := ((Downstream_property l (LL_RR_coRR_relation p1 p2) R)).\n\n(* db_dapart a b := a can do something b can't do *)\nInductive db_dapart : X → X → Prop :=\n  | Fwd l p1 p2 q : can_step l p1 p2 → Downstream_property l db_dapart p1 p2 q → db_dapart p1 q.\nHint Constructors db_dapart : hints.\n\nTheorem db_dapart_strong_ind :\n  ∀ P : X → X → Prop,\n    (∀ l (p1 p2 q : X),\n      can_step l p1 p2 →\n      Downstream_property l (rel_join db_dapart P) p1 p2 q →\n      P p1 q) →\n    ∀ p1 q1 : X, db_dapart p1 q1 → P p1 q1.\nProof.\n  intros P CaseFwd.\n  fix IH 3.\n  intros p1 q1 H.\n  inv H as [l p1' p2 q1' Hs_p1_p2 HQ].\n  eapply CaseFwd; try done.\n  intros q2 Hq12 q3 Hq23.\n  destruct (HQ q2 Hq12 q3 Hq23) as [Ha_p1_q2|[Ha_p2_q3|Ha_q3_p2]];\n    [left|right;left|right;right]; split; eauto.\nQed.\n\nTheorem db_dapart_strong_ind' :\n  ∀ P : X → X → Prop,\n    (∀ l (p1 p2 q : X), can_step l p1 p2 → Downstream_property l P p1 p2 q → P p1 q) →\n    ∀ p1 q1 : X, db_dapart p1 q1 → P p1 q1.\nProof.\n  intros P CaseFwd.\n  eapply db_dapart_strong_ind; eauto.\n  intros; eapply CaseFwd; try done.\n  eapply Downstream_property_closed_implication;\n    [eapply LL_RR_coRR_relation_MBRT| |done].\n  unfold rel_join. tauto.\nQed.\n\nLemma Downstream_property_closed_rel_join {R1 R2 : relation X} {l p1 p2 q1} :\n  Downstream_property l (rel_join R1 R2) p1 p2 q1 →\n  Downstream_property l R1 p1 p2 q1.\nProof. eapply Downstream_property_closed_implication; [eapply LL_RR_coRR_relation_MBRT|]. by intros p q []. Qed.\n\nInstance db_dapart_extend_forward_one {p1} :\n  Proper (can_step silent ==> impl) (db_dapart p1).\nProof.\n  intros q1 q2 Hs_q1_q2 H.\n  inv H.\n  eapply Fwd; try done.\n  eapply Downstream_property_closed_down; eauto using rtc_once.\nQed.\n\nInstance db_dapart_extend_forward {p1} :\n  Proper (rtc (can_step silent) ==> impl) (db_dapart p1).\nProof.\n  intros q1. \n  eapply rtc_ind_r; [done|].\n  intros q2 q3 _ Hs_q2_q3 IH H.\n  specialize (IH H).\n  by eapply db_dapart_extend_forward_one.\nQed.\n\nInstance db_dapart_extend_backwards_one :\n  Proper (can_step silent ==> eq ==> flip impl) db_dapart.\nProof.\n  intros p1 p2 Hs_p1_p2 q1 q1' <- Ha_p2_q1.\n  eapply Fwd; try done.\n  intros q2 Hq12 q3 Hq23.\n  right. left.\n  by eapply db_dapart_extend_forward; [eapply rtc_r|].\nQed.\n\nInstance db_dapart_extend_backwards :\n  Proper (rtc (can_step silent) ==> eq ==> flip impl) db_dapart.\nProof.\n  intros p2 p3 Hs_p2_p3 q1 q2 <- Ha.\n  revert p2 Hs_p2_p3.\n  eapply rtc_ind_l; [done|].\n  intros p1 p2 Hp12 Hp23.\n  by eapply db_dapart_extend_backwards_one.\nQed.\n\nEnd DirectedBranchingApart.\n", "meta": {"author": "jesyspa", "repo": "directed-branching-bisimulation", "sha": "ac2a4b8bee8b48c1b3a913ffd84446b5e171688d", "save_path": "github-repos/coq/jesyspa-directed-branching-bisimulation", "path": "github-repos/coq/jesyspa-directed-branching-bisimulation/directed-branching-bisimulation-ac2a4b8bee8b48c1b3a913ffd84446b5e171688d/theories/reflexive/directed_branching.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23850400037188732}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import ssreflect ssrbool.\nFrom MetaCoq.Template Require Import config utils.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICLiftSubst PCUICTyping PCUICCumulativity\n     PCUICReduction PCUICWeakeningConv PCUICWeakeningTyp PCUICEquality PCUICUnivSubstitutionConv\n     PCUICSigmaCalculus PCUICContextReduction\n     PCUICParallelReduction PCUICParallelReductionConfluence PCUICClosedConv PCUICClosedTyp\n     PCUICRedTypeIrrelevance PCUICOnFreeVars PCUICConfluence PCUICSubstitution.\n\nRequire Import CRelationClasses CMorphisms.\nRequire Import Equations.Prop.DepElim.\nRequire Import Equations.Type.Relation Equations.Type.Relation_Properties.\nFrom Equations Require Import Equations.\n\n(* We show that conversion/cumulativity starting from well-typed terms is transitive.\n  We first use typing to decorate the reductions/comparisons with invariants\n  showing that all the considered contexts/terms are well-scoped. In a second step\n  we use confluence of one-step reduction on well-scoped terms [ws_red_confluence], which also\n  commutes with alpha,universe-equivalence of contexts and terms [red1_eq_context_upto_l].\n  We can now derive transitivity of the conversion relation on *well-scoped*\n  terms. To deal with the closedness side condition we put them in the definition\n  of conversion/cumulativity: as terms need to move between contexts, and\n  we sometimes need to consider conversion in open contexts, we work with\n  them in an unpacked style.\n  This allows to state theorems about conversion/cumulativity of general terms\n  and contexts without wrapping/unwrapping them constantly into subsets.\n*)\n\nReserved Notation \" Σ ;;; Γ ⊢ t ≤[ pb ] u\" (at level 50, Γ, t, u at next level,\n  format \"Σ  ;;;  Γ  ⊢  t  ≤[ pb ]  u\").\n\nImplicit Types (cf : checker_flags) (Σ : global_env_ext).\n\nInductive ws_cumul_pb {cf} (pb : conv_pb) (Σ : global_env_ext) (Γ : context) : term -> term -> Type :=\n| ws_cumul_pb_compare (t u : term) :\n  is_closed_context Γ -> is_open_term Γ t -> is_open_term Γ u ->\n  compare_term pb Σ.1 (global_ext_constraints Σ) t u -> Σ ;;; Γ ⊢ t ≤[pb] u\n| ws_cumul_pb_red_l (t u v : term) :\n  is_closed_context Γ ->\n  is_open_term Γ t -> is_open_term Γ u -> is_open_term Γ v ->\n  red1 Σ Γ t v -> Σ ;;; Γ ⊢ v ≤[pb] u -> Σ ;;; Γ ⊢ t ≤[pb] u\n| ws_cumul_pb_red_r (t u v : term) :\n  is_closed_context Γ ->\n  is_open_term Γ t -> is_open_term Γ u -> is_open_term Γ v ->\n  Σ ;;; Γ ⊢ t ≤[pb] v -> red1 Σ Γ u v -> Σ ;;; Γ ⊢ t ≤[pb] u\nwhere \" Σ ;;; Γ ⊢ t ≤[ pb ] u \" := (ws_cumul_pb pb Σ Γ t u) : type_scope.\nDerive Signature NoConfusion for ws_cumul_pb.\n\nNotation \" Σ ;;; Γ ⊢ t ≤ u \" := (ws_cumul_pb Cumul Σ Γ t u) (at level 50, Γ, t, u at next level,\n    format \"Σ  ;;;  Γ  ⊢  t  ≤  u\") : type_scope.\n\nNotation \" Σ ;;; Γ ⊢ t = u \" := (ws_cumul_pb Conv Σ Γ t u) (at level 50, Γ, t, u at next level,\n  format \"Σ  ;;;  Γ  ⊢  t  =  u\") : type_scope.\n\nLemma ws_cumul_pb_refl' {pb} {cf} {Σ} (Γ : closed_context) (t : open_term Γ) : ws_cumul_pb pb Σ Γ t t.\nProof.\n  constructor; eauto with fvs. reflexivity.\nQed.\n\n#[global]\nInstance ws_cumul_pb_sym {cf Σ Γ} : Symmetric (ws_cumul_pb Conv Σ Γ).\nProof.\n  move=> x y; elim.\n  - move=> t u clΓ clt clu eq.\n    constructor 1; eauto with fvs.\n    cbn in *; now symmetry.\n  - move=> t u v clΓ clt clu clv r c c'.\n    econstructor 3; tea.\n  - move=> t u v clΓ clt clu clv r c c'.\n    econstructor 2; tea.\nQed.\n\nLemma red1_is_open_term {cf : checker_flags} {Σ} {wfΣ : wf Σ} {Γ : context} x y :\n  red1 Σ Γ x y ->\n  is_closed_context Γ ->\n  is_open_term Γ x ->\n  is_open_term Γ y.\nProof.\n  intros. eapply red1_on_free_vars; eauto with fvs.\nQed.\n#[global] Hint Immediate red1_is_open_term : fvs.\n\nLemma red_is_open_term {cf : checker_flags} {Σ} {wfΣ : wf Σ} {Γ : context} x y :\n  red Σ Γ x y ->\n  is_closed_context Γ ->\n  is_open_term Γ x ->\n  is_open_term Γ y.\nProof.\n  intros. eapply red_on_free_vars; eauto with fvs.\nQed.\n#[global] Hint Immediate red_is_open_term : fvs.\n\nLemma ws_cumul_pb_is_open_term {cf : checker_flags} {pb} {Σ : global_env_ext} {wfΣ : wf Σ} {Γ : context} {x y} :\n  ws_cumul_pb pb Σ Γ x y ->\n  [&& is_closed_context Γ, is_open_term Γ x & is_open_term Γ y].\nProof.\n  now induction 1; rewrite ?i ?i0 ?i1 ?i2.\nQed.\n\nLemma ws_cumul_pb_is_closed_context {cf : checker_flags} {pb} {Σ : global_env_ext} {wfΣ : wf Σ} {Γ : context} {x y} :\n  ws_cumul_pb pb Σ Γ x y -> is_closed_context Γ.\nProof.\n  now induction 1; rewrite ?i ?i0 ?i1 ?i2.\nQed.\n\nLemma ws_cumul_pb_is_open_term_left {cf : checker_flags} {pb} {Σ : global_env_ext} {wfΣ : wf Σ}\n  {Γ : context} {x y} :\n  ws_cumul_pb pb Σ Γ x y -> is_open_term Γ x.\nProof.\n  now induction 1; rewrite ?i ?i0 ?i1 ?i2.\nQed.\n\nLemma ws_cumul_pb_is_open_term_right {cf : checker_flags} {pb} {Σ : global_env_ext} {wfΣ : wf Σ} {Γ : context} {x y} :\n  ws_cumul_pb pb Σ Γ x y -> is_open_term Γ y.\nProof.\n  now induction 1; rewrite ?i ?i0 ?i1.\nQed.\n\n#[global] Hint Resolve ws_cumul_pb_is_closed_context ws_cumul_pb_is_open_term_left ws_cumul_pb_is_open_term_right : fvs.\n\nLemma ws_cumul_pb_alt `{cf : checker_flags} {pb} {Σ : global_env_ext} {wfΣ : wf Σ} Γ t u :\n  Σ ;;; Γ ⊢ t ≤[pb] u <~>\n  ∑ v v',\n    [× is_closed_context Γ, is_open_term Γ t, is_open_term Γ u,\n      red Σ Γ t v, red Σ Γ u v' & compare_term pb Σ (global_ext_constraints Σ) v v'].\nProof.\n  split.\n  - induction 1.\n    + exists t, u. intuition auto.\n    + destruct IHX as (v' & v'' & [-> _ -> redv redv' leqv]).\n      rewrite i0 /=.\n      exists v', v''. split; auto. now eapply red_step.\n    + destruct IHX as (v' & v'' & [-> -> cl redv redv' leqv ]).\n      exists v', v''. split; auto. now eapply red_step.\n  - intros (v' & v'' & [clΓ clt clu redv redv' leqv]).\n    apply clos_rt_rt1n in redv.\n    apply clos_rt_rt1n in redv'.\n    induction redv in u, v'', redv', leqv, clt, clu |- *.\n    * induction redv' in x, leqv, clt, clu |- *.\n    ** constructor; auto.\n    ** econstructor 3; tas. 2:eapply IHredv'. all:tea; eauto with fvs.\n    * econstructor 2; revgoals. eapply IHredv; cbn; eauto with fvs. all:eauto with fvs.\nQed.\n\nLemma ws_cumul_pb_forget {cf:checker_flags} {pb} {Σ : global_env_ext} {wfΣ : wf Σ} {Γ} {x y} :\n  ws_cumul_pb pb Σ Γ x y -> Σ ;;; Γ |- x <=[pb] y.\nProof.\n  induction 1.\n  - constructor; auto.\n  - econstructor 2; eauto.\n  - econstructor 3; eauto.\nQed.\n\nLemma ws_cumul_pb_forget_cumul {cf:checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ} {Γ} {x y} :\n  ws_cumul_pb Cumul Σ Γ x y -> Σ ;;; Γ |- x <=[Cumul] y.\nProof. apply (ws_cumul_pb_forget (pb:=Cumul)). Qed.\n\nLemma ws_cumul_pb_forget_conv {cf:checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ} {Γ} {x y} :\n  ws_cumul_pb Conv Σ Γ x y -> Σ ;;; Γ |- x <=[Conv] y.\nProof. apply (ws_cumul_pb_forget (pb:=Conv)). Qed.\n#[global] Hint Resolve ws_cumul_pb_forget_cumul ws_cumul_pb_forget_conv : pcuic.\n\n#[global]\nInstance ws_cumul_pb_trans {cf:checker_flags} {pb} {Σ : global_env_ext} {wfΣ : wf Σ} {Γ} :\n  Transitive (ws_cumul_pb pb Σ Γ).\nProof.\n  move=> t u v /ws_cumul_pb_alt [t' [u' [clΓ clt clu tt' uu' eq]]]\n    /ws_cumul_pb_alt[u'' [v' [_ clu' clv uu'' vv' eq']]].\n  eapply ws_cumul_pb_alt.\n  destruct (red_confluence (Γ := exist Γ clΓ) (t:=exist u clu) uu' uu'') as [u'nf [ul ur]].\n  destruct pb; cbn in *.\n  { eapply red_eq_term_upto_univ_r in ul as [tnf [redtnf ?]]; tea; try tc.\n    eapply red_eq_term_upto_univ_l in ur as [unf [redunf ?]]; tea; try tc.\n    exists tnf, unf.\n    split; auto; eauto with fvs.\n    - now transitivity t'.\n    - now transitivity v'.\n    - now transitivity u'nf. }\n  { eapply red_eq_term_upto_univ_r in ul as [tnf [redtnf ?]]; tea; try tc.\n    eapply red_eq_term_upto_univ_l in ur as [unf [redunf ?]]; tea; try tc.\n    exists tnf, unf.\n    split; eauto with fvs.\n    - now transitivity t'.\n    - now transitivity v'.\n    - now transitivity u'nf. }\nQed.\n\nArguments wt_cumul_pb_dom {cf c Σ Γ T U}.\nArguments wt_cumul_pb_codom {cf c Σ Γ T U}.\nArguments wt_cumul_pb_eq {cf c Σ Γ T U}.\n\nSection EqualityLemmas.\n  Context {cf : checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ}.\n\n  Lemma isType_open {Γ T} : isType Σ Γ T -> on_free_vars (shiftnP #|Γ| xpred0) T.\n  Proof using wfΣ.\n    move/isType_closedPT. now rewrite closedP_shiftnP.\n  Qed.\n\n  Lemma into_ws_cumul_pb {pb} {Γ : context} {T U} :\n    Σ;;; Γ |- T <=[pb] U ->\n    is_closed_context Γ -> is_open_term Γ T ->\n    is_open_term Γ U ->\n    Σ ;;; Γ ⊢ T ≤[pb] U.\n  Proof using wfΣ.\n    induction 1.\n    - constructor; auto.\n    - intros. econstructor 2 with v; cbn; eauto with fvs.\n    - econstructor 3 with v; cbn; eauto with fvs.\n  Qed.\n\n  Lemma isType_ws_cumul_pb_refl {pb} Γ T : isType Σ Γ T -> Σ ;;; Γ ⊢ T ≤[pb] T.\n  Proof using wfΣ.\n    intros H.\n    pose proof (isType_wf_local H).\n    eapply (ws_cumul_pb_refl' (exist Γ (wf_local_closed_context X)) (exist T (isType_open H))).\n  Qed.\n\n  (** From well-typed to simply well-scoped equality. *)\n  Lemma wt_cumul_pb_ws_cumul_pb {pb} {Γ : context} {T U} :\n    wt_cumul_pb pb Σ Γ T U ->\n    ws_cumul_pb pb Σ Γ T U.\n  Proof using wfΣ.\n    move=> [] dom codom equiv; cbn.\n    generalize (wf_local_closed_context (isType_wf_local dom)).\n    generalize (isType_open dom) (isType_open codom). clear -wfΣ equiv.\n    intros. apply into_ws_cumul_pb => //.\n  Qed.\n\n  Lemma wt_cumul_pb_trans pb Γ :\n    Transitive (wt_cumul_pb pb Σ Γ).\n  Proof using wfΣ.\n    intros x y z cum cum'.\n    have wscum := (wt_cumul_pb_ws_cumul_pb cum).\n    have wscum' := (wt_cumul_pb_ws_cumul_pb cum').\n    generalize (transitivity wscum wscum'). clear wscum wscum'.\n    destruct cum, cum'; split=> //.\n    apply ws_cumul_pb_forget in X. now cbn in X.\n  Qed.\n\n  Global Instance conv_trans Γ : Transitive (wt_conv Σ Γ).\n  Proof using wfΣ. apply wt_cumul_pb_trans. Qed.\n\n  Global Instance cumul_trans Γ : Transitive (wt_cumul Σ Γ).\n  Proof using wfΣ. apply wt_cumul_pb_trans. Qed.\n\nEnd EqualityLemmas.\n\nSet Warnings \"-uniform-inheritance\".\nCoercion wt_cumul_pb_ws_cumul_pb : wt_cumul_pb >-> ws_cumul_pb.\nSet Warnings \"uniform-inheritance\".\n\n#[global] Hint Immediate isType_ws_cumul_pb_refl : pcuic.\n\nRecord closed_relation {R : context -> term -> term -> Type} {Γ T U} :=\n  { clrel_ctx : is_closed_context Γ;\n    clrel_src : is_open_term Γ T;\n    clrel_rel : R Γ T U }.\nArguments closed_relation : clear implicits.\n\n#[global] Hint Immediate clrel_ctx clrel_src : fvs.\n\nDefinition closed_red1 Σ := (closed_relation (red1 Σ)).\nDefinition closed_red1_red1 {Σ Γ T U} (r : closed_red1 Σ Γ T U) := clrel_rel r.\n#[global] Hint Resolve closed_red1_red1 : fvs.\nCoercion closed_red1_red1 : closed_red1 >-> red1.\n\nLemma closed_red1_open_right {cf} {Σ Γ T U} {wfΣ : wf Σ} (r : closed_red1 Σ Γ T U) : is_open_term Γ U.\nProof.\n  destruct r. eauto with fvs.\nQed.\n\nDefinition closed_red Σ := (closed_relation (red Σ)).\nDefinition closed_red_red {Σ Γ T U} (r : closed_red Σ Γ T U) := clrel_rel r.\n#[global] Hint Immediate closed_red_red : fvs.\nCoercion closed_red_red : closed_red >-> red.\n\nLemma closed_red_open_right {cf} {Σ Γ T U} {wfΣ : wf Σ} (r : closed_red Σ Γ T U) : is_open_term Γ U.\nProof.\n  destruct r. eauto with fvs.\nQed.\n\nFrom Equations.Type Require Import Relation_Properties.\n\n(* \\rightsquigarrow *)\nNotation \"Σ ;;; Γ ⊢ t ⇝ u\" := (closed_red Σ Γ t u) (at level 50, Γ, t, u at next level,\n  format \"Σ  ;;;  Γ  ⊢  t  ⇝  u\").\n\nLemma closed_red1_red {Σ Γ t t'} : closed_red1 Σ Γ t t' -> Σ ;;; Γ ⊢ t ⇝ t'.\nProof.\n  intros []. split => //.\n  now eapply red1_red.\nQed.\n\nLemma ws_cumul_pb_alt_closed {cf} {pb} {Σ : global_env_ext} {wfΣ : wf Σ} Γ t u :\n  Σ ;;; Γ ⊢ t ≤[pb] u <~>\n  ∑ v v',\n    [× closed_red Σ Γ t v, closed_red Σ Γ u v' &\n       compare_term pb Σ (global_ext_constraints Σ) v v'].\nProof.\n  etransitivity. apply ws_cumul_pb_alt.\n  split; intros (v & v' & cl); exists v, v'; intuition.\nQed.\n\nLemma biimpl_introT {T} {U} : Logic.BiImpl T U -> T -> U.\nProof. intros [] => //. Qed.\n\nHint View for move/ biimpl_introT|2.\n\nLemma ws_cumul_pb_refl {cf} {Σ} {pb Γ t} : is_closed_context Γ -> is_open_term Γ t -> Σ ;;; Γ ⊢ t ≤[pb] t.\nProof.\n  move=> clΓ clt.\n  constructor; cbn; eauto with fvs. reflexivity.\nQed.\n#[global] Hint Immediate ws_cumul_pb_refl : pcuic.\n\nSection RedConv.\n  Context {cf} {Σ} {wfΣ : wf Σ}.\n\n  Lemma red_conv {pb Γ t u} : Σ ;;; Γ ⊢ t ⇝ u -> Σ ;;; Γ ⊢ t ≤[pb] u.\n  Proof using wfΣ.\n    move=> [clΓ clT /clos_rt_rt1n_iff r].\n    induction r.\n    - now apply ws_cumul_pb_refl.\n    - econstructor 2. 5:tea.\n      all:eauto with fvs.\n  Qed.\n\n  Lemma red_ws_cumul_pb_left {pb Γ} {t u v} :\n    Σ ;;; Γ ⊢ t ⇝ u -> Σ ;;; Γ ⊢ u ≤[pb] v -> Σ ;;; Γ ⊢ t ≤[pb] v.\n  Proof using wfΣ.\n    move=> [clΓ clT /clos_rt_rt1n_iff r].\n    induction r; auto.\n    econstructor 2. 5:tea. all:eauto with fvs.\n  Qed.\n\n  Lemma red_ws_cumul_pb_right {pb Γ t u v} :\n    Σ ;;; Γ ⊢ t ⇝ u -> Σ ;;; Γ ⊢ v ≤[pb] u -> Σ ;;; Γ ⊢ v ≤[pb] t.\n  Proof using wfΣ.\n    move=> [clΓ clT /clos_rt_rt1n_iff r].\n    induction r; auto.\n    econstructor 3. 5:eapply IHr. all:eauto with fvs.\n  Qed.\n\n  (* synonym of red_conv *)\n  Lemma red_ws_cumul_pb {pb Γ t u} :\n    Σ ;;; Γ ⊢ t ⇝ u -> Σ ;;; Γ ⊢ t ≤[pb] u.\n  Proof using wfΣ.\n    move=> r; eapply red_ws_cumul_pb_left; tea.\n    eapply ws_cumul_pb_refl; eauto with fvs.\n  Qed.\n\n  Lemma red_ws_cumul_pb_inv {pb Γ t u} :\n    Σ ;;; Γ ⊢ t ⇝ u ->\n    Σ ;;; Γ ⊢ u ≤[pb] t.\n  Proof using wfΣ.\n    move=> r; eapply red_ws_cumul_pb_right; tea.\n    eapply ws_cumul_pb_refl; eauto with fvs.\n  Qed.\nEnd RedConv.\n\n#[global] Hint Resolve red_conv red_ws_cumul_pb red_ws_cumul_pb_inv : pcuic.\n\nSet SimplIsCbn.\n\nDefinition conv_cum {cf:checker_flags} pb Σ Γ T T' :=\n  Σ ;;; Γ |- T <=[pb] T'.\n\nNotation ws_decl Γ d := (on_free_vars_decl (shiftnP #|Γ| xpred0) d).\n\nDefinition open_decl (Γ : context) := { d : context_decl | ws_decl Γ d }.\nDefinition open_decl_proj {Γ : context} (d : open_decl Γ) := proj1_sig d.\nCoercion open_decl_proj : open_decl >-> context_decl.\n\nDefinition vass_open_decl {Γ : closed_context} (na : binder_annot name) (t : open_term Γ) : open_decl Γ :=\n  exist (vass na t) (proj2_sig t).\n\nDefinition ws_cumul_decls {cf : checker_flags} (pb : conv_pb) (Σ : global_env_ext)\n  (Γ : context) (d : context_decl) (d' : context_decl) :=\n  All_decls_alpha_pb pb (fun pb => @ws_cumul_pb cf pb Σ Γ) d d'.\n\nLemma ws_cumul_decls_wf_decl_left {cf} {pb} {Σ} {wfΣ : wf Σ} {Γ d d'} :\n  ws_cumul_decls pb Σ Γ d d' -> ws_decl Γ d.\nProof.\n  intros []; cbn; eauto with fvs.\nQed.\n\nLemma ws_cumul_decls_wf_decl_right {cf} {pb} {Σ} {wfΣ : wf Σ} {Γ d d'} :\n  ws_cumul_decls pb Σ Γ d d' -> ws_decl Γ d'.\nProof.\n  intros []; cbn; eauto with fvs.\nQed.\n#[global] Hint Immediate ws_cumul_decls_wf_decl_left ws_cumul_decls_wf_decl_right : fvs.\n\nLemma ws_cumul_decls_cumul_pb_decls {cf : checker_flags} (pb : conv_pb) {Σ : global_env_ext} {wfΣ : wf Σ}\n  {Γ Γ' : context} {d d'} :\n  ws_cumul_decls pb Σ Γ d d' ->\n  cumul_pb_decls cumulAlgo_gen pb Σ Γ Γ' d d'.\nProof.\n  intros. intuition eauto with fvs.\n  destruct X; destruct pb; constructor; pcuic.\nQed.\n\nLemma into_ws_cumul_decls {cf : checker_flags} {pb : conv_pb} {Σ : global_env_ext} {wfΣ : wf Σ}\n  (Γ Γ' : context) d d' :\n  cumul_pb_decls cumulAlgo_gen pb Σ Γ Γ' d d' ->\n  on_free_vars_ctx xpred0 Γ ->\n  on_free_vars_ctx xpred0 Γ' ->\n  is_open_decl Γ d ->\n  is_open_decl Γ d' ->\n  ws_cumul_decls pb Σ Γ d d'.\nProof.\n  case: pb; move=> pb clΓ clΓ' isd isd';\n    destruct pb; cbn; constructor; auto; try inv_on_free_vars; eauto with fvs.\n  all:try apply: into_ws_cumul_pb; tea; eauto 3 with fvs.\nQed.\n\nLemma ws_cumul_decls_inv {cf} (pb : conv_pb) {Σ : global_env_ext} {wfΣ : wf Σ}\n  {Γ Γ' : context} {d d'} :\n  ws_cumul_decls pb Σ Γ d d' ->\n  [× on_free_vars_ctx xpred0 Γ, is_open_decl Γ d, is_open_decl Γ d' & cumul_pb_decls cumulAlgo_gen pb Σ Γ Γ' d d'].\nProof.\n  intros. split; eauto with fvs.\n  - destruct X; now destruct eqt.\n  - now eapply ws_cumul_decls_cumul_pb_decls.\nQed.\n\n#[global]\nInstance ws_cumul_decls_trans {cf : checker_flags} {pb} {Σ : global_env_ext} {wfΣ : wf Σ} {Γ : context} :\n  Transitive (ws_cumul_decls pb Σ Γ).\nProof.\n  intros d d' d''.\n  rewrite /ws_cumul_decls.\n  intros ond ond'; destruct ond; depelim ond'.\n  econstructor; now etransitivity.\n  econstructor; etransitivity; tea.\nQed.\n\nInductive wt_cumul_pb_decls {cf : checker_flags} (pb : conv_pb) (Σ : global_env_ext) (Γ Γ' : context) : context_decl -> context_decl -> Type :=\n| wt_cumul_pb_vass {na na' : binder_annot name} {T T' : term} :\n    isType Σ Γ T -> isType Σ Γ' T' ->\n    conv_cum pb Σ Γ T T' ->\n    eq_binder_annot na na' ->\n    wt_cumul_pb_decls pb Σ Γ Γ' (vass na T) (vass na' T')\n| wt_cumul_pb_vdef {na na' : binder_annot name} {b b' T T'} :\n    eq_binder_annot na na' ->\n    isType Σ Γ T -> isType Σ Γ' T' ->\n    Σ ;;; Γ |- b : T -> Σ ;;; Γ' |- b' : T' ->\n    Σ ;;; Γ |- b = b' ->\n    conv_cum pb Σ Γ T T' ->\n    wt_cumul_pb_decls pb Σ Γ Γ' (vdef na b T) (vdef na' b' T').\nDerive Signature for wt_cumul_pb_decls.\n\nDefinition ws_cumul_ctx_pb {cf:checker_flags} (pb : conv_pb) (Σ : global_env_ext) (Γ Γ' : context) :=\n  All2_fold (fun Γ Γ' => ws_cumul_decls pb Σ Γ) Γ Γ'.\n\nNotation \"Σ ⊢ Γ ≤[ pb ] Δ\" := (ws_cumul_ctx_pb pb Σ Γ Δ) (at level 50, Γ, Δ at next level,\n  format \"Σ  ⊢  Γ  ≤[ pb ]  Δ\") : pcuic.\n\nNotation \"Σ ⊢ Γ = Δ\" := (ws_cumul_ctx_pb Conv Σ Γ Δ) (at level 50, Γ, Δ at next level,\n  format \"Σ  ⊢  Γ  =  Δ\") : pcuic.\n\nNotation \"Σ ⊢ Γ ≤ Δ\" := (ws_cumul_ctx_pb Cumul Σ Γ Δ) (at level 50, Γ, Δ at next level,\n  format \"Σ  ⊢  Γ  ≤  Δ\") : pcuic.\n\nLemma ws_cumul_ctx_pb_closed_right {cf:checker_flags} {pb : conv_pb} {Σ} {wfΣ : wf Σ} {Γ Γ'}:\n  ws_cumul_ctx_pb pb Σ Γ Γ' -> is_closed_context Γ'.\nProof.\n  intros X. red in X.\n  induction X; auto.\n  rewrite on_free_vars_ctx_snoc IHX /= //.\n  rewrite -(All2_fold_length X); eauto with fvs.\nQed.\n\nLemma ws_cumul_ctx_pb_closed_left {cf:checker_flags} {pb : conv_pb} {Σ} {wfΣ : wf Σ} {Γ Γ'}:\n  ws_cumul_ctx_pb pb Σ Γ Γ' -> is_closed_context Γ.\nProof.\n  intros X. red in X.\n  induction X; auto.\n  rewrite on_free_vars_ctx_snoc IHX /=.\n  eauto with fvs.\nQed.\n\n#[global] Hint Resolve ws_cumul_ctx_pb_closed_left ws_cumul_ctx_pb_closed_right : fvs.\n\nDefinition wt_cumul_ctx_pb {cf:checker_flags} (pb : conv_pb) (Σ : global_env_ext) :=\n  All2_fold (wt_cumul_pb_decls pb Σ).\n\nNotation \"Σ ⊢ Γ ≤[ pb ] Δ ✓\" := (wt_cumul_ctx_pb pb Σ Γ Δ) (at level 50, Γ, Δ at next level,\n  format \"Σ  ⊢  Γ  ≤[ pb ]  Δ  ✓\") : pcuic.\n\nNotation wt_cumul_context Σ := (wt_cumul_ctx_pb Cumul Σ).\nNotation wt_conv_context Σ := (wt_cumul_ctx_pb Conv Σ).\n\nSection WtContextConversion.\n  Context {cf : checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ}.\n\n  Definition wt_decl Γ d :=\n    match d with\n    | {| decl_body := None; decl_type := ty |} => isType Σ Γ ty\n    | {| decl_body := Some b; decl_type := ty |} => isType Σ Γ ty × Σ ;;; Γ |- b : ty\n    end.\n\n  Lemma wf_local_All_fold Γ :\n    wf_local Σ Γ <~>\n    All_fold wt_decl Γ.\n  Proof using Type.\n    split.\n    - induction 1; constructor; auto.\n      red in t0, t1. cbn. split; auto.\n    - induction 1; [constructor|].\n      destruct d as [na [b|] ty]; cbn in p; constructor; intuition auto.\n  Qed.\n\n  Lemma wt_cumul_ctx_pb_forget {pb} {Γ Γ' : context} :\n    wt_cumul_ctx_pb pb Σ Γ Γ' ->\n    [× wf_local Σ Γ, wf_local Σ Γ' & cumul_pb_context cumulAlgo_gen pb Σ Γ Γ'].\n  Proof using Type.\n    move=> wteq.\n    eapply (All2_fold_impl (Q:=fun Γ Γ' d d' => wt_decl Γ d × wt_decl Γ' d' × cumul_pb_decls cumulAlgo_gen pb Σ Γ Γ' d d')) in wteq.\n    2:{ intros ???? []; intuition (cbn; try constructor; auto). }\n    eapply All2_fold_All_fold_mix_inv in wteq as [wteq [wfΓ wfΓ']].\n    eapply wf_local_All_fold in wfΓ. eapply wf_local_All_fold in wfΓ'.\n    split; auto.\n  Qed.\n\n  Lemma into_wt_cumul_ctx_pb {pb} {Γ Γ' : context} {T U : term} :\n    wf_local Σ Γ -> wf_local Σ Γ' ->\n    cumul_pb_context cumulAlgo_gen pb Σ Γ Γ' ->\n    wt_cumul_ctx_pb pb Σ Γ Γ'.\n  Proof using Type.\n    move=> /wf_local_All_fold wfΓ /wf_local_All_fold wfΓ'.\n    destruct pb=> eq.\n    eapply All2_fold_All_fold_mix in eq; tea.\n    eapply All2_fold_impl; tea; clear => Γ Γ' d d' [wtd [wtd' cum]] /=.\n    destruct cum; cbn in wtd, wtd'; constructor; intuition auto.\n    eapply All2_fold_All_fold_mix in eq; tea.\n    eapply All2_fold_impl; tea; clear => Γ Γ' d d' [wtd [wtd' cum]] /=.\n    destruct cum; cbn in wtd, wtd'; constructor; intuition auto.\n  Qed.\n\n  Lemma wt_ws_ws_cumul_ctx_pb {pb} {Γ Γ' : context} {T U : term} :\n    wt_cumul_ctx_pb pb Σ Γ Γ' ->\n    ws_cumul_ctx_pb pb Σ Γ Γ'.\n  Proof using wfΣ.\n    intros a; eapply All2_fold_impl_ind; tea.\n    intros ???? wt ws eq;\n    pose proof (All2_fold_length wt).\n    destruct eq.\n    - pose proof (isType_wf_local i).\n      eapply wf_local_closed_context in X.\n      eapply isType_open in i. apply isType_open in i0.\n      eapply into_ws_cumul_decls with Δ; eauto with fvs.\n      constructor; auto.\n      rewrite (All2_fold_length ws) //.\n    - pose proof (isType_wf_local i).\n      eapply wf_local_closed_context in X.\n      eapply isType_open in i. apply isType_open in i0.\n      eapply PCUICClosedTyp.subject_closed in t.\n      eapply PCUICClosedTyp.subject_closed in t0.\n      eapply (@closedn_on_free_vars xpred0) in t.\n      eapply (@closedn_on_free_vars xpred0) in t0.\n      eapply into_ws_cumul_decls with Δ; eauto with fvs.\n      destruct pb; constructor; auto.\n      rewrite (All2_fold_length ws) //; eauto with fvs.\n  Qed.\n\n  Lemma ws_cumul_ctx_pb_inv {pb} {Γ Γ' : context} :\n    ws_cumul_ctx_pb pb Σ Γ Γ' ->\n    [× on_free_vars_ctx xpred0 Γ, on_free_vars_ctx xpred0 Γ' & cumul_pb_context cumulAlgo_gen pb Σ Γ Γ'].\n  Proof using wfΣ.\n    move=> wteq.\n    split; eauto with fvs.\n    eapply All2_fold_impl; tea; move=> ???? []; constructor; eauto with pcuic.\n    all:try now eapply ws_cumul_pb_forget in eqt.\n  Qed.\n\n  #[global]\n  Instance ws_cumul_decls_sym Γ : Symmetric (ws_cumul_decls Conv Σ Γ).\n  Proof using Type.\n    move=> x y [na na' T T' eqan cv|na na' b b' T T' eqna eqb eqT];\n    constructor; now symmetry.\n  Qed.\n\n  Lemma ws_cumul_ctx_pb_forget {pb Γ Γ'} :\n    ws_cumul_ctx_pb pb Σ Γ Γ' -> cumul_pb_context cumulAlgo_gen pb Σ Γ Γ'.\n  Proof using wfΣ.\n    now move/ws_cumul_ctx_pb_inv => [].\n  Qed.\n\n  Lemma ws_cumul_ctx_pb_refl pb Γ : is_closed_context Γ -> ws_cumul_ctx_pb pb Σ Γ Γ.\n  Proof using wfΣ.\n    move=> onΓ. cbn.\n    move/on_free_vars_ctx_All_fold: onΓ => a.\n    eapply (All_fold_All2_fold_impl a). clear -wfΣ.\n    move=> Γ d a IH ond.\n    move/on_free_vars_ctx_All_fold: a => clΓ.\n    eapply (into_ws_cumul_decls _ Γ); auto.\n    destruct d as [na [b|] ty]; constructor; auto; reflexivity.\n  Qed.\n\nEnd WtContextConversion.\n", "meta": {"author": "SwampertX", "repo": "undergraduate-thesis", "sha": "b0c78984b94e56f1372a7195bd0babaab10fca8d", "save_path": "github-repos/coq/SwampertX-undergraduate-thesis", "path": "github-repos/coq/SwampertX-undergraduate-thesis/undergraduate-thesis-b0c78984b94e56f1372a7195bd0babaab10fca8d/final-report-new/code/v2/pcuic/theories/PCUICWellScopedCumulativity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23850400037188732}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Bedrock.IL Bedrock.SepIL.\nRequire Import Bedrock.Word Bedrock.Memory.\nImport List.\nRequire Import Bedrock.DepList Bedrock.EqdepClass.\nRequire Import Bedrock.PropX.\nRequire Import Bedrock.Expr Bedrock.SepExpr Bedrock.SepCancel.\nRequire Import Bedrock.Prover Bedrock.ILEnv.\nRequire Import Bedrock.Tactics Bedrock.Reflection.\nRequire Import Bedrock.TacPackIL.\nRequire Bedrock.ExprUnify.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nModule U := ExprUnify.UNIFIER.\nModule CANCEL := SepCancel.Make U SepIL.SH.\n\nSection existsSubst.\n  Variable types : list type.\n  Variable funcs : functions types.\n  Variable meta_base : env types.\n  Variable var_env : env types.\n  Variable sub : U.Subst types.\n\n  Definition ExistsSubstNone (_ : tvar) (_ : expr types) :=\n    False.\n\n  Fixpoint substInEnv (from : nat) (vals : env types) (ret : env types -> Prop) : Prop :=\n    match vals with\n      | nil => ret nil\n      | val :: vals =>\n        match U.Subst_lookup from sub with\n          | None => substInEnv (S from) vals (fun e => ret (val :: e))\n          | Some v =>\n            match exprD funcs meta_base var_env v (projT1 val) with\n              | None => ExistsSubstNone (projT1 val) v\n              | Some v' => projT2 val = v' /\\ substInEnv (S from) vals (fun e => ret (existT _ (projT1 val) v' :: e))\n            end\n        end\n    end.\n\n  Fixpoint existsMaybe (vals : list { t : tvar & option (tvarD types t) }) (ret : env types -> Prop) : Prop :=\n    match vals with\n      | nil => ret nil\n      | existT t None :: vals => exists x : tvarD types t, existsMaybe vals (fun e => ret (existT _ t x :: e))\n      | existT t (Some v) :: vals => existsMaybe vals (fun e => ret (existT _ t v :: e))\n    end.\n\nEnd existsSubst.\n\nDefinition existsSubst types funcs var_env sub (from : nat) (vals : list { t : tvar & option (tvarD types t) }) (ret : env types -> Prop) :=\n  existsMaybe vals (fun e => @substInEnv types funcs e var_env sub from e ret).\n\nFixpoint consistent {ts} (vals : list { x : tvar & option (tvarD ts x) }) (e : list { x : tvar & tvarD ts x }) : Prop :=\n  match vals , e with\n    | nil , nil => True\n    | existT t None :: vals , existT t' _ :: e =>\n      t = t' /\\ @consistent _ vals e\n    | existT t (Some v) :: vals , existT t' v' :: e =>\n      match equiv_dec t t' return Prop with\n        | left pf =>\n          v' = match (pf : t = t') in _ = t return tvarD ts t with\n                 | refl_equal => v\n               end /\\ @consistent _ vals e\n        | right _ => False\n      end\n    | _ , _ => False\n  end.\n\nLemma ex_iff : forall T (P P' : T -> Prop),\n  (forall x, P x <-> P' x) ->\n  ((exists x, P x) <-> (exists x, P' x)).\nProof. split; intuition; destruct H0 as [ x ? ]; exists x; firstorder. Qed.\n\nTheorem existsMaybe_sem : forall types vals (ret : env types -> Prop),\n  existsMaybe vals ret <->\n  existsEach (map (@projT1 _ _) vals) (fun e => consistent vals e /\\ ret e).\nProof.\n  induction vals; simpl; intros.\n  { intuition. }\n  { destruct a. destruct o.\n    { rewrite IHvals. intuition. exists t. apply existsEach_sem. apply existsEach_sem in H.\n      destruct H. exists x0. simpl in *. rewrite EquivDec_refl_left. intuition.\n      destruct H. apply existsEach_sem. apply existsEach_sem in H. destruct H.\n      exists x1. simpl in *. rewrite EquivDec_refl_left in H. intuition; subst; auto. }\n    { simpl. eapply ex_iff. intros. rewrite IHvals.\n      intuition; apply existsEach_sem in H; apply existsEach_sem; destruct H; exists x1; intuition. } }\nQed.\n\nLemma substInEnv_sem : forall types funcs meta_env var_env sub vals from ret,\n  @substInEnv types funcs meta_env var_env sub from vals ret <->\n  (U.Subst_equations_to funcs meta_env var_env sub from vals /\\ ret vals).\nProof.\n  induction vals; simpl; intros.\n  { intuition. }\n  { destruct a; simpl in *.\n    consider (U.Subst_lookup from sub); simpl; intros.\n    consider (exprD funcs meta_env var_env e x); simpl; intros.\n    { rewrite IHvals. intuition; subst; auto. }\n    { intuition. }\n    { rewrite IHvals. intuition. } }\nQed.\n\nLemma existsSubst_sem : forall ts (funcs : functions ts) vals sub vars_env from ret,\n  existsSubst funcs vars_env sub from vals ret <->\n  existsEach (map (@projT1 _ _) vals) (fun meta_env =>\n    consistent vals meta_env /\\ U.Subst_equations_to funcs meta_env vars_env sub from meta_env /\\ ret meta_env).\nProof.\n  intros. unfold existsSubst.\n  rewrite existsMaybe_sem. rewrite existsEach_sem. rewrite existsEach_sem.\n  apply ex_iff. intros. rewrite substInEnv_sem. intuition.\nQed.\n\nLemma AllProvable_impl_AllProvable : forall ts (funcs : functions ts) U G P ps,\n  AllProvable funcs U G ps ->\n  AllProvable_impl funcs U G P ps ->\n  P.\nProof. clear. induction ps; simpl; intros; eauto. intuition. Qed.\n\nSection canceller.\n  Variable ts : list type.\n  Let types := Env.repr BedrockCoreEnv.core ts.\n  Variable funcs : functions types.\n  Variable preds : SEP.predicates types BedrockCoreEnv.pc BedrockCoreEnv.st.\n  Variable algos : ILAlgoTypes.AllAlgos ts.\n\n  Record CancellerResult : Type :=\n  { AllExt : variables\n  ; ExExt  : variables\n  ; Lhs    : SH.SHeap types BedrockCoreEnv.pc BedrockCoreEnv.st\n  ; Rhs    : SH.SHeap types BedrockCoreEnv.pc BedrockCoreEnv.st\n  ; Subst  : U.Subst types\n  }.\n\n  Definition canceller (uvars : list tvar) (hyps : Expr.exprs types)\n    (lhs rhs : SEP.sexpr types BedrockCoreEnv.pc BedrockCoreEnv.st) : option CancellerResult :=\n    let prover :=\n      match ILAlgoTypes.Prover algos with\n        | None => provers.ReflexivityProver.reflexivityProver\n        | Some p => p\n      end\n    in\n    let hints :=\n      match ILAlgoTypes.Hints algos with\n        | None => UNF.default_hintsPayload _ _ _\n        | Some h => h\n      end\n    in\n    let (ql, lhs) := SH.hash lhs in\n    let facts := Summarize prover (map (liftExpr 0 0 0 (length ql)) hyps ++ SH.pures lhs) in\n    let pre :=\n      {| UNF.Vars  := rev ql\n       ; UNF.UVars := uvars\n       ; UNF.Heap  := lhs\n      |}\n    in\n    match UNF.forward hints prover 10 facts pre with\n      | ({| UNF.Vars := vars' ; UNF.UVars := uvars' ; UNF.Heap := lhs |}, n_forward) =>\n        let (qr, rhs) := SH.hash rhs in\n        let rhs :=\n          UNF.HEAP_FACTS.sheapSubstU 0 (length qr) (length uvars') rhs\n        in\n        let post :=\n          {| UNF.Vars  := vars'\n           ; UNF.UVars := uvars' ++ rev qr\n           ; UNF.Heap  := rhs\n          |}\n        in\n        match UNF.backward hints prover 10 facts post with\n          | ({| UNF.Vars := vars' ; UNF.UVars := uvars' ; UNF.Heap := rhs |}, n_backward) =>\n            let new_vars  := vars' in\n            let new_uvars := skipn (length uvars) uvars' in\n            let bound := length uvars' in\n            match CANCEL.sepCancel preds prover bound facts lhs rhs (U.Subst_empty _) false with\n              | Some (l,r,s) =>\n                Some {| AllExt := new_vars\n                      ; ExExt  := new_uvars\n                      ; Lhs    :=\n                        (** TODO: this is a hack for the moment to ensure that\n                         ** the pure premises are well typed without the new\n                         ** unification variables\n                         **)\n                        {| SH.impures := SH.impures l\n                         ; SH.pures   := SH.pures lhs\n                         ; SH.other   := SH.other l\n                         |}\n                      ; Rhs    := r\n                      ; Subst  := s\n                      |}\n              | None =>\n                if match ql , qr with\n                     | nil , nil =>\n                       match SH.pures lhs , SH.pures rhs with\n                         | nil, nil =>\n                           if EqNat.beq_nat n_forward 10 then EqNat.beq_nat n_backward 10 else false\n                         | _ , _ => false\n                       end\n                     | _ , _ => false\n                   end then\n                  None\n                else\n                  Some {| AllExt := new_vars\n                        ; ExExt  := new_uvars\n                        ; Lhs    := lhs\n                        ; Rhs    := rhs\n                        ; Subst  := U.Subst_empty _\n                        |}\n            end\n        end\n    end.\n\n  Lemma AllProvable_and_sem : forall U G P Ps,\n    AllProvable_and funcs U G P Ps <-> (AllProvable funcs U G Ps /\\ P).\n  Proof. induction Ps; simpl; intros; intuition auto. Qed.\n  Lemma app_inj_length : forall T (a b c d : list T),\n    a ++ b = c ++ d ->\n    length a = length c ->\n    a = c /\\ b = d.\n  Proof.\n    induction a; destruct c; simpl; intros; think; try solve [ intuition ].\n    inversion H; subst.  eapply IHa in H3. intuition; subst; auto. omega.\n  Qed.\n  Lemma WellTyped_env_app : forall ts a b c d,\n    WellTyped_env a c ->\n    WellTyped_env b d ->\n    WellTyped_env (types := ts) (a ++ b) (c ++ d).\n  Proof. clear.\n    intros. unfold WellTyped_env in *. unfold typeof_env in *. subst.\n    rewrite map_app. reflexivity.\n  Qed.\n  Ltac t_list_length := repeat (rewrite typeof_env_length || rewrite rev_length || rewrite map_length || rewrite app_length).\n  Hint Extern 1 (_ = _) => t_list_length; auto : list_length.\n\n  Ltac env_resolution :=\n    repeat (rewrite typeof_env_app || unfold typeof_env || rewrite map_app || rewrite map_rev || (f_equal; []) || assumption).\n\n  Lemma consistent_app : forall ts a b c,\n    consistent (ts := ts) (a ++ b) c ->\n    consistent a (firstn (length a) c) /\\ consistent b (skipn (length a) c).\n  Proof. clear.\n    induction a; simpl; intros; auto.\n    destruct a. destruct o. destruct c; try contradiction. destruct s. destruct (equiv_dec x x0); try contradiction.\n    destruct H. eapply IHa in H0. intuition.\n    destruct c; try contradiction. destruct s. destruct H. apply IHa in H0. intuition.\n  Qed.\n  Lemma consistent_Some : forall ts a c,\n    consistent (ts := ts) (map (fun x => existT _ (projT1 x) (Some (projT2 x))) a) c ->\n    a = c.\n  Proof.\n    induction a; destruct c; simpl; intros; try contradiction; auto.\n    destruct s. destruct a; simpl in *. destruct (equiv_dec x0 x); try contradiction.\n    unfold equiv in e. intuition; subst. f_equal; eauto.\n  Qed.\n  Lemma skipn_length : forall T a (b : list T),\n    length (skipn a b) = length b - a.\n  Proof. induction a; destruct b; simpl; intros; auto. Qed.\n\n  Lemma himp_remove_pure_p : forall cs U G p P Q,\n    (Provable funcs U G p ->\n      SH.SE.himp funcs preds U G cs P Q) ->\n    SH.SE.himp funcs preds U G cs (SEP.Star (@SEP.Inj _ _ _ p) P) Q.\n  Proof. clear.\n    intros. unfold SH.SE.himp. simpl. unfold Provable in *.\n    destruct (exprD funcs U G p tvProp); eapply himp_star_pure_c; intuition.\n  Qed.\n  Lemma himp_remove_pures_p : forall cs U G ps P Q,\n    (AllProvable funcs U G ps ->\n      SH.SE.himp funcs preds U G cs P Q) ->\n    SH.SE.himp funcs preds U G cs (SH.starred (@SEP.Inj _ _ _) ps P) Q.\n  Proof. clear.\n    induction ps; intros.\n    { rewrite SH.starred_nil. apply H. exact I. }\n    { rewrite SH.starred_cons. apply himp_remove_pure_p. intros.\n      eapply IHps. intro. apply H; simpl; auto. }\n  Qed.\n  Lemma himp_remove_pure_c : forall cs U G p P Q,\n    Provable funcs U G p ->\n    SH.SE.himp funcs preds U G cs P Q ->\n    SH.SE.himp funcs preds U G cs P (SEP.Star (@SEP.Inj _ _ _ p) Q).\n  Proof. clear.\n    intros. unfold SH.SE.himp. simpl. unfold Provable in *.\n    destruct (exprD funcs U G p tvProp); eapply himp_star_pure_cc; intuition.\n  Qed.\n  Lemma himp_remove_pures_c : forall cs U G ps P Q,\n    AllProvable funcs U G ps ->\n    SH.SE.himp funcs preds U G cs P Q ->\n    SH.SE.himp funcs preds U G cs P (SH.starred (@SEP.Inj _ _ _) ps Q).\n  Proof. clear.\n    induction ps; intros.\n    { rewrite SH.starred_nil. apply H0. }\n    { rewrite SH.starred_cons. simpl in *. apply himp_remove_pure_c; intuition. }\n  Qed.\n\n  Lemma ApplyCancelSep_with_eq' :\n    forall (algos_correct : ILAlgoTypes.AllAlgos_correct funcs preds algos),\n    forall (meta_env : env types) (hyps : Expr.exprs types),\n    Expr.AllProvable funcs meta_env nil hyps ->\n    forall (l r : SEP.sexpr types BedrockCoreEnv.pc BedrockCoreEnv.st) res cs,\n    forall (WTR : SEP.WellTyped_sexpr (typeof_funcs funcs) (SEP.typeof_preds preds) (typeof_env meta_env) nil r = true),\n    canceller (typeof_env meta_env) hyps l r = Some res ->\n    match res with\n      | {| AllExt := new_vars\n         ; ExExt  := new_uvars\n         ; Lhs    := lhs'\n         ; Rhs    := rhs'\n         ; Subst  := subst\n         |} =>\n        Expr.forallEach new_vars (fun nvs : Expr.env types =>\n          let var_env := nvs in\n          Expr.AllProvable_impl funcs meta_env var_env\n          (existsSubst funcs var_env subst 0\n            (map (fun x => existT (fun t => option (tvarD types t)) (projT1 x) (Some (projT2 x))) meta_env ++\n             map (fun x => existT (fun t => option (tvarD types t)) x None) new_uvars)\n            (fun meta_env : Expr.env types =>\n                (Expr.AllProvable_and funcs meta_env var_env\n                  (himp cs\n                    (SEP.sexprD funcs preds meta_env var_env\n                      (SH.sheapD (SH.Build_SHeap _ _ (SH.impures lhs') nil (SH.other lhs'))))\n                    (SEP.sexprD funcs preds meta_env var_env\n                      (SH.sheapD (SH.Build_SHeap _ _ (SH.impures rhs') nil (SH.other rhs')))))\n                  (SH.pures rhs')) ))\n            (SH.pures lhs'))\n    end ->\n    himp cs (@SEP.sexprD _ _ _ funcs preds meta_env nil l)\n            (@SEP.sexprD _ _ _ funcs preds meta_env nil r).\n  Proof.\n    Opaque UNF.backward UNF.forward Env.repr.\n    intros. unfold canceller in *.\n    assert (PC : ProverT_correct\n              match ILAlgoTypes.Prover algos with\n              | Some p => p\n              | None => ReflexivityProver.reflexivityProver\n              end funcs).\n    { generalize (ILAlgoTypes.Acorrect_Prover algos_correct).\n      destruct (ILAlgoTypes.Prover algos); intros; auto.\n      apply ReflexivityProver.reflexivityProver_correct. }\n    generalize dependent (match ILAlgoTypes.Prover algos with\n                            | Some p => p\n                            | None => ReflexivityProver.reflexivityProver\n                          end).\n    match goal with\n      | [ |- context [ ?X ] ] =>\n        match X with\n          | match ILAlgoTypes.Hints _ with _ => _ end =>\n            assert (HC : UNF.hintsSoundness funcs preds X); [ | generalize dependent X ]\n        end\n    end.\n    { generalize (ILAlgoTypes.Acorrect_Hints algos_correct).\n      destruct (ILAlgoTypes.Hints algos); auto using UNF.hintsSoundness_default. }\n    intros h HC p ? PC.\n    consider (SH.hash l); intros.\n    rewrite SH.hash_denote. rewrite H0; clear H0; simpl.\n    consider (SH.hash r); intros.\n    rewrite SH.hash_denote with (s := r). rewrite H0; simpl.\n    rewrite UNF.himp_existsEach_ST_EXT_existsEach.\n    rewrite UNF.ST_EXT.himp_existsEach_p; [ reflexivity | intros ].\n    rewrite app_nil_r.\n    apply CANCEL.HEAP_FACTS.himp_pull_pures; intro.\n    match goal with\n      | [ H : context [ Summarize ?P ?ps ] |- _ ] =>\n        assert (Valid PC meta_env (rev G) (Summarize P ps)); [ | generalize dependent (Summarize P ps); intros ]\n    end.\n    { eapply Summarize_correct.\n      apply AllProvable_app; auto.\n      revert H; clear - H3. induction hyps; simpl; intros; auto.\n      intuition. clear - H0 H3. unfold Provable in *.\n      generalize (liftExpr_ext funcs meta_env nil nil nil (rev G) nil a tvProp); simpl.\n      rewrite app_nil_r. rewrite rev_length. subst. rewrite map_length.\n      intro. rewrite H in *. auto. }\n    match goal with\n      | [ H : match ?X with _ => _ end = _ |- _ ] => consider X\n    end; intros.\n    apply CANCEL.SEP_FACTS.himp_WellTyped_sexpr; intro.\n\n    (** Forward **)\n    destruct (UNF.forwardLength _ _ _ _ _ H2).\n    assert (SH.WellTyped_sheap (typeof_funcs funcs) (UNF.SE.typeof_preds preds) (typeof_env meta_env) (rev v) s = true).\n    { rewrite SH.WellTyped_sheap_WellTyped_sexpr. rewrite <- H3. rewrite <- map_rev. apply H7. }\n\n    generalize (@UNF.forward_WellTyped _ _ _ _ _ _ _ HC _ _ _ _ _ H2 H9); intro.\n    simpl in *.\n    assert (WellTyped_env (rev v) (rev G)).\n    { unfold WellTyped_env. subst. rewrite <- map_rev. auto. }\n    eapply UNF.forwardOk  with (cs := cs) in H2; simpl; eauto using typeof_env_WellTyped_env.\n    simpl in H2. etransitivity; [ eapply H2 | clear H11; simpl in * ].\n    rewrite UNF.ST_EXT.himp_existsEach_p; [ reflexivity | intros ].\n    destruct H8.\n    (** NOTE: I can't shift s0 around until I can witness the existential **)\n\n    (** Open up everything **)\n    destruct u.\n    consider (UNF.backward h p 10 f\n           {| UNF.Vars := Vars\n            ; UNF.UVars := UVars ++ rev v0\n            ; UNF.Heap := UNF.HEAP_FACTS.sheapSubstU 0 (length v0) (length UVars) s0 |}); intros.\n    destruct (UNF.backwardLength _ _ _ _ _ H6); simpl in *.\n    destruct u.\n\n    assert (AllExt res = Vars0 /\\ ExExt res = skipn (length (typeof_env meta_env)) UVars0\n            /\\ SH.pures (Lhs res) = SH.pures Heap).\n    { clear - H13.\n      match goal with\n        | [ H : match ?X with _ => _ end = _ |- _ ] => destruct X\n      end; intros. destruct p0; destruct p0. inversion H13; auto.\n      match goal with\n        | [ H : match ?X with _ => _ end = _ |- _ ] => destruct X\n      end; try congruence. inversion H13; auto. }\n    intuition; subst.\n\n    rewrite ListFacts.rw_skipn_app in H11 by (auto with list_length).\n\n    destruct res. simpl in *. subst AllExt0; subst ExExt0.\n    eapply forallEach_sem with (env := rev G ++ G0) in H1; [ | solve [ env_resolution ] ].\n\n    eapply (@CANCEL.HEAP_FACTS.himp_pull_pures types _ _ funcs preds cs meta_env (rev G ++ G0) Heap). intro.\n    eapply AllProvable_impl_AllProvable in H1; [ clear H3 | rewrite H19; assumption ].\n\n    apply existsSubst_sem in H1. apply existsEach_sem in H1.\n    destruct H1. intuition.\n    assert (meta_env = firstn (length meta_env) x1 /\\\n            typeof_env (skipn (length (rev v0)) (skipn (length meta_env) x1)) = x0 /\\\n            typeof_env (firstn (length (rev v0)) (skipn (length meta_env) x1)) = rev v0).\n    { subst. clear - H3 H1.\n      generalize (typeof_env_length x1). rewrite H3; intros.\n      rewrite <- firstn_skipn with (n := length meta_env) (l := x1) in H3.\n      repeat (rewrite map_app in *  || rewrite map_map in * || rewrite map_id in * || rewrite app_ass in *\n        || rewrite ListFacts.rw_skipn_app in * by eauto || rewrite typeof_env_app in * ).\n      simpl in *. rewrite typeof_env_app in *. eapply app_inj_length in H3.\n      Focus 2. revert H. t_list_length. rewrite firstn_length. intro. rewrite min_l; omega.\n      destruct H3.\n      rewrite <- firstn_skipn with (n := length (rev v0)) (l := skipn (length meta_env) x1) in H2.\n      rewrite typeof_env_app in *.\n      eapply app_inj_length in H2. destruct H2. intuition.\n      { eapply consistent_app in H1. destruct H1; clear - H1.\n        revert H1. t_list_length. intros.\n        eapply consistent_Some in H1. auto. }\n      revert H. t_list_length. intro. rewrite firstn_length; rewrite min_l; auto.\n      rewrite skipn_length. omega. }\n    intuition. clear H3 H1.\n\n    eapply AllProvable_and_sem in H14. destruct H14.\n    rewrite app_ass in *.\n\n    subst UVars0.\n    assert (SH.WellTyped_sheap (typeof_funcs funcs) (UNF.SE.typeof_preds preds)\n     (typeof_env meta_env ++ rev v0)\n     (rev (map (projT1 (P:=tvarD types)) G) ++ x)\n     (UNF.HEAP_FACTS.sheapSubstU 0 (length v0) (length (typeof_env meta_env))\n        s0) = true).\n    { rewrite <- SH.WellTyped_sheap_WellTyped_sexpr in H7.\n      generalize (@UNF.HEAP_FACTS.sheapSubstU_WellTyped types BedrockCoreEnv.pc BedrockCoreEnv.st (typeof_funcs funcs) (UNF.SE.typeof_preds preds) (typeof_env meta_env) nil (rev v0) nil s0); simpl.\n      rewrite app_nil_r. intro XX.\n      rewrite SH.WellTyped_hash in WTR. rewrite H0 in WTR. simpl in WTR. rewrite app_nil_r in WTR.\n      apply XX in WTR. clear XX.\n      eapply SH.WellTyped_sheap_weaken with (tU' := nil) (tG := nil) (tG' := (rev (map (projT1 (P:=tvarD types)) G) ++ x)) in WTR.\n      simpl in WTR. rewrite app_nil_r in WTR.\n      rewrite Plus.plus_0_r in *. rewrite rev_length in WTR. apply WTR. }\n\n    generalize (@UNF.backward_WellTyped _ _ _ _ _ _ _ HC _ _ _ _ _ H6 H14); simpl.\n    eapply UNF.backwardOk with (cs := cs) in H6; simpl in *.\n    2: eassumption.\n    2: solve [ rewrite <- H18; eapply WellTyped_env_app; eauto using typeof_env_WellTyped_env ].\n    Focus 2.\n    rewrite <- map_rev.\n    eapply WellTyped_env_app. eapply typeof_env_WellTyped_env.\n    instantiate (1 := G0). symmetry. apply H11.\n    2: eassumption.\n    2: solve [ eapply Valid_weaken; eassumption ].\n    intro.\n\n    (** **)\n    rewrite UNF.himp_existsEach_ST_EXT_existsEach.\n    eapply UNF.ST_EXT.himp_existsEach_c. exists (rev (firstn (length (rev v0)) (skipn (length meta_env) x1))); split.\n    { rewrite map_rev. unfold typeof_env in H18. rewrite H18. apply rev_involutive. }\n    rewrite rev_involutive.\n\n    (** In order to call the canceller, they must have the same environments. **)\n    assert (SH.SE.ST.heq cs\n              (SH.SE.sexprD funcs preds meta_env (rev G ++ G0) (SH.sheapD Heap))\n              (SH.SE.sexprD funcs preds x1 (rev G ++ G0) (SH.sheapD Heap))).\n    { rewrite <- firstn_skipn with (l := x1) (n := length meta_env).\n      rewrite <- H15.\n      generalize (@CANCEL.SEP_FACTS.sexprD_weaken_wt types _ _ funcs preds cs meta_env (skipn (length meta_env) x1) nil\n        (SH.sheapD Heap) (rev G ++ G0)).\n      rewrite app_nil_r. intro XX; apply XX; clear XX.\n      rewrite <- SH.WellTyped_sheap_WellTyped_sexpr. rewrite <- H10. f_equal.\n      rewrite typeof_env_app. f_equal. rewrite <- map_rev. reflexivity.\n      rewrite <- H11. reflexivity. }\n    etransitivity; [ eapply H17 | clear H17 ].\n\n    assert (SH.SE.ST.heq cs\n              (SH.SE.sexprD funcs preds (meta_env ++ firstn (length (rev v0)) (skipn (length meta_env) x1)) (rev G ++ G0) (SH.sheapD (UNF.HEAP_FACTS.sheapSubstU 0 (length v0)\n                       (length (typeof_env meta_env)) s0)))\n              (UNF.SE.sexprD funcs preds meta_env\n                (firstn (length (rev v0)) (skipn (length meta_env) x1) ++ nil)\n                (SH.sheapD s0))).\n    { generalize (@UNF.HEAP_FACTS.sheapSubstU_sheapD types _ _ funcs preds cs\n        meta_env nil (firstn (length (rev v0)) (skipn (length meta_env) x1)) nil s0).\n      simpl. repeat rewrite app_nil_r. intros XX; rewrite XX; clear XX.\n      generalize (@CANCEL.SEP_FACTS.sexprD_weaken_wt types _ _ funcs preds cs\n        (meta_env ++ firstn (length (rev v0)) (skipn (length meta_env) x1))\n        nil (rev G ++ G0)\n          (SH.sheapD (UNF.HEAP_FACTS.sheapSubstU 0\n              (length (firstn (length (rev v0)) (skipn (length meta_env) x1)) +\n               0) (length meta_env) s0)) nil).\n      simpl. t_list_length.\n      intro XX; rewrite XX; clear XX.\n      rewrite H15. rewrite app_ass.\n      cutrewrite (length (firstn (length meta_env) x1) = length meta_env).\n      rewrite app_nil_r.\n      cutrewrite (length (firstn (length v0) (skipn (length meta_env) x1)) + 0 = length v0).\n      reflexivity.\n      rewrite Plus.plus_0_r. rewrite <- rev_length with (l := v0).\n      rewrite <- H18 at 2. t_list_length. reflexivity.\n      rewrite <- H15. reflexivity.\n      rewrite <- SH.WellTyped_sheap_WellTyped_sexpr.\n      rewrite SH.WellTyped_hash in WTR.\n      rewrite SH.WellTyped_sheap_WellTyped_sexpr in WTR. rewrite H0 in *. simpl in WTR.\n      clear - WTR H15 H12 H18 H11.\n      rewrite <- SH.WellTyped_sheap_WellTyped_sexpr in WTR.\n      generalize (@UNF.HEAP_FACTS.sheapSubstU_WellTyped_eq types BedrockCoreEnv.pc BedrockCoreEnv.st (typeof_funcs funcs) (SEP.typeof_preds preds)\n        (typeof_env meta_env) nil (rev v0) nil s0). simpl. t_list_length. rewrite app_nil_r in *.\n      intro XX; rewrite XX in WTR; clear XX.\n      rewrite <- WTR. rewrite <- H18. t_list_length. rewrite typeof_env_app. repeat rewrite Plus.plus_0_r.\n      f_equal. f_equal. rewrite <- rev_length with (l := v0). rewrite <- H18 at 2.\n      t_list_length. reflexivity. }\n    rewrite <- H17; clear H17.\n    revert H6. t_list_length.\n    intro H6. etransitivity; [ clear H6 | eapply H6 ].\n\n\n    (** witness the conclusion **)\n    eapply UNF.ST_EXT.himp_existsEach_c.\n    exists (skipn (length (rev v0)) (skipn (length meta_env) x1)). split.\n    { t_list_length. rewrite firstn_length; rewrite skipn_length. rewrite <- app_ass. rewrite ListFacts.rw_skipn_app.\n      rewrite <- H12. t_list_length. reflexivity.\n      env_resolution. t_list_length. f_equal. rewrite min_l; auto.\n      clear - H18 H15 H12.\n      assert (x1 = firstn (length meta_env) x1 ++ (firstn (length (rev v0)) (skipn (length meta_env) x1)) ++\n        (skipn (length (rev v0)) (skipn (length meta_env) x1))).\n      repeat rewrite firstn_skipn. reflexivity.\n      generalize dependent (firstn (length meta_env) x1).\n      generalize dependent (skipn (length (rev v0)) (skipn (length meta_env) x1)).\n      generalize dependent (firstn (length (rev v0)) (skipn (length meta_env) x1)).\n      intros. subst. rewrite <- rev_length. rewrite <- H18. t_list_length. omega. }\n    rewrite app_ass. rewrite H15 at 1.\n    t_list_length. repeat rewrite firstn_skipn.\n    clear H2.\n\n    assert (U.Subst_WellTyped (typeof_funcs funcs) (typeof_env x1)\n      (typeof_env (rev G ++ G0)) (U.Subst_empty types)).\n    { eapply U.Subst_empty_WellTyped. }\n    assert (SH.WellTyped_sheap (typeof_funcs funcs) (CANCEL.SE.typeof_preds preds)\n      (typeof_env x1) (typeof_env (rev G ++ G0)) Heap0 = true).\n    { rewrite <- H16. f_equal.\n      rewrite H15. rewrite <- H18. rewrite <- H12. t_list_length.\n      repeat rewrite <- typeof_env_app. repeat rewrite firstn_skipn. reflexivity.\n      rewrite typeof_env_app. f_equal. rewrite typeof_env_rev. reflexivity. apply H11. }\n    assert (SH.WellTyped_sheap (typeof_funcs funcs) (CANCEL.SE.typeof_preds preds)\n     (typeof_env x1) (typeof_env (rev G ++ G0)) Heap = true).\n    { eapply SH.WellTyped_sheap_weaken with (tG' := nil) (tU' := typeof_env (skipn (length meta_env) x1)) in H10.\n      rewrite H15 in H10 at 1. rewrite <- typeof_env_app in H10. rewrite firstn_skipn in H10.\n      rewrite app_nil_r in H10. rewrite <- H10. f_equal.\n      rewrite typeof_env_app. rewrite typeof_env_rev. f_equal. apply H11. }\n    consider (CANCEL.sepCancel preds p (length (typeof_env meta_env ++ rev v0 ++ x0)) f Heap Heap0 (U.Subst_empty _) false);\n    intros; try congruence.\n    { destruct p0. destruct p0. inversion H20; clear H20. subst s3. subst s1.\n      subst Lhs0. clear H19. simpl in *.\n      eapply CANCEL.sepCancel_correct with (cs := cs) (funcs := funcs) (U := x1) (G := rev G ++ G0) in H13; try eassumption.\n      { instantiate (1 := PC). eapply Valid_weaken with (ue := skipn (length meta_env) x1) (ge := G0) in H5.\n        rewrite <- firstn_skipn with (n := length meta_env) (l := x1). rewrite <- H15. assumption. }\n      { (* eapply CANCEL.sepCancel_PuresPrem in H13; try eassumption. *)\n        match type of H3 with\n          | himp ?CS (SEP.sexprD ?F ?P ?U ?G ?L) (SEP.sexprD ?F ?P ?U ?G ?R) =>\n            change (SEP.himp F P U G CS L R) in H3\n        end.\n        do 2 rewrite SH.sheapD_def. do 2 rewrite SH.sheapD_def in H3. simpl in *.\n        do 2 rewrite CANCEL.SEP_FACTS.heq_star_emp_l in H3.\n        rewrite CANCEL.SEP_FACTS.heq_star_comm\n          with (P := SH.starred (SEP.Inj (stateType:=BedrockCoreEnv.st)) (SH.pures s2) SEP.Emp).\n        rewrite CANCEL.SEP_FACTS.heq_star_comm\n          with (P := SH.starred (SEP.Inj (stateType:=BedrockCoreEnv.st)) (SH.pures Rhs0) SEP.Emp).\n        do 2 rewrite <- CANCEL.SEP_FACTS.heq_star_assoc.\n        apply CANCEL.SEP_FACTS.himp_star_frame. assumption.\n        eapply himp_remove_pures_p; intros.\n        eapply himp_remove_pures_c; auto. reflexivity. }\n      { eapply CANCEL.sepCancel_PureFacts in H13. 4: eapply H6.\n        eapply U.Subst_equations_to_Subst_equations; intuition.\n        intuition. intuition. } }\n    { match goal with\n      | [ H : (if ?X then _ else _) = _ |- _ ] =>\n        destruct X; try congruence\n      end.\n      inversion H20; clear H20.\n      destruct Lhs0; destruct Rhs0; simpl in *.\n      etransitivity. etransitivity; [ | eapply H3 ].\n      { repeat rewrite SH.sheapD_def; simpl; repeat apply ST.himp_star_frame; try reflexivity.\n        change (SEP.himp funcs preds x1 (rev G ++ G0) cs (SH.starred (SEP.Inj (stateType:=BedrockCoreEnv.st)) pures SEP.Emp) SEP.Emp).\n        clear. induction pures. reflexivity.\n        rewrite CANCEL.HEAP_FACTS.starred_cons.\n         rewrite IHpures.\n         eapply himp_remove_pure_p. intro; reflexivity. }\n      { repeat rewrite SH.sheapD_def; simpl; repeat apply ST.himp_star_frame; try reflexivity.\n        change (SEP.himp funcs preds x1 (rev G ++ G0) cs SEP.Emp (SH.starred (SEP.Inj (stateType:=BedrockCoreEnv.st)) pures0 SEP.Emp)).\n        clear - H1. induction pures0. reflexivity.\n        rewrite CANCEL.HEAP_FACTS.starred_cons.\n        simpl in H1; intuition.\n        rewrite <- H1 by assumption.\n        eapply himp_remove_pure_c; auto. reflexivity. } }\n  Qed.\n\n  Lemma ApplyCancelSep_with_eq :\n    forall (algos_correct : ILAlgoTypes.AllAlgos_correct funcs preds algos),\n    forall (meta_env : env (Env.repr BedrockCoreEnv.core types)) (hyps : Expr.exprs (_)),\n\n    forall (l r : SEP.sexpr types BedrockCoreEnv.pc BedrockCoreEnv.st) res,\n    canceller (typeof_env meta_env) hyps l r = Some res ->\n    Expr.AllProvable funcs meta_env nil hyps ->\n    forall (WTR : SEP.WellTyped_sexpr (typeof_funcs funcs) (SEP.typeof_preds preds) (typeof_env meta_env) nil r = true) cs,\n\n    match res with\n      | {| AllExt := new_vars\n         ; ExExt  := new_uvars\n         ; Lhs    := lhs'\n         ; Rhs    := rhs'\n         ; Subst  := subst\n         |} =>\n        Expr.forallEach new_vars (fun nvs : Expr.env types =>\n          let var_env := nvs in\n          Expr.AllProvable_impl funcs meta_env var_env\n          (existsSubst funcs var_env subst 0\n            (map (fun x => existT (fun t => option (tvarD types t)) (projT1 x) (Some (projT2 x))) meta_env ++\n             map (fun x => existT (fun t => option (tvarD types t)) x None) new_uvars)\n            (fun meta_env : Expr.env types =>\n                (Expr.AllProvable_and funcs meta_env var_env\n                  (himp cs\n                    (SEP.sexprD funcs preds meta_env var_env\n                      (SH.sheapD (SH.Build_SHeap _ _ (SH.impures lhs') nil (SH.other lhs'))))\n                    (SEP.sexprD funcs preds meta_env var_env\n                      (SH.sheapD (SH.Build_SHeap _ _ (SH.impures rhs') nil (SH.other rhs')))))\n                  (SH.pures rhs')) ))\n            (SH.pures lhs'))\n    end ->\n    himp cs (@SEP.sexprD _ _ _ funcs preds meta_env nil l)\n            (@SEP.sexprD _ _ _ funcs preds meta_env nil r).\n  Proof. intros. eapply ApplyCancelSep_with_eq'; eauto. Qed.\n\n  Lemma ApplyCancelSep :\n    forall (algos_correct : ILAlgoTypes.AllAlgos_correct funcs preds algos),\n    forall (meta_env : env (Env.repr BedrockCoreEnv.core types)) (hyps : Expr.exprs (_)),\n    forall (l r : SEP.sexpr types BedrockCoreEnv.pc BedrockCoreEnv.st),\n      Expr.AllProvable funcs meta_env nil hyps ->\n    forall (WTR : SEP.WellTyped_sexpr (typeof_funcs funcs) (SEP.typeof_preds preds) (typeof_env meta_env) nil r = true) cs,\n    match canceller (typeof_env meta_env) hyps l r with\n      | Some {| AllExt := new_vars\n         ; ExExt  := new_uvars\n         ; Lhs    := lhs'\n         ; Rhs    := rhs'\n         ; Subst  := subst\n         |} =>\n        Expr.forallEach new_vars (fun nvs : Expr.env types =>\n          let var_env := nvs in\n          Expr.AllProvable_impl funcs meta_env var_env\n          (existsSubst funcs var_env subst 0\n            (map (fun x => existT (fun t => option (tvarD types t)) (projT1 x) (Some (projT2 x))) meta_env ++\n             map (fun x => existT (fun t => option (tvarD types t)) x None) new_uvars)\n            (fun meta_env : Expr.env types =>\n                (Expr.AllProvable_and funcs meta_env var_env\n                  (himp cs\n                    (SEP.sexprD funcs preds meta_env var_env\n                      (SH.sheapD (SH.Build_SHeap _ _ (SH.impures lhs') nil (SH.other lhs'))))\n                    (SEP.sexprD funcs preds meta_env var_env\n                      (SH.sheapD (SH.Build_SHeap _ _ (SH.impures rhs') nil (SH.other rhs')))))\n                  (SH.pures rhs')) ))\n            (SH.pures lhs'))\n      | None =>\n        himp cs (@SEP.sexprD _ _ _ funcs preds meta_env nil l)\n                (@SEP.sexprD _ _ _ funcs preds meta_env nil r)\n    end ->\n    himp cs (@SEP.sexprD _ _ _ funcs preds meta_env nil l)\n            (@SEP.sexprD _ _ _ funcs preds meta_env nil r).\n  Proof.\n    intros. consider (canceller (typeof_env meta_env) hyps l r); intros; auto.\n    eapply ApplyCancelSep_with_eq; eauto.\n  Qed.\n\nEnd canceller.\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/src/CancelIL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2385040003718873}}
{"text": "From cap_machine Require Import rules_base.\nFrom iris.base_logic Require Export invariants gen_heap.\nFrom iris.program_logic Require Export weakestpre ectx_lifting.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import frac.\n\nSection cap_lang_rules.\n  Context `{memG Σ, regG Σ}.\n  Context `{MachineParameters}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types σ : ExecConf.\n  Implicit Types c : cap_lang.expr. \n  Implicit Types a b : Addr.\n  Implicit Types r : RegName.\n  Implicit Types v : cap_lang.val. \n  Implicit Types w : Word.\n  Implicit Types reg : gmap RegName Word.\n  Implicit Types ms : gmap Addr Word.\n\n  Inductive Mov_spec (regs: Reg) (dst: RegName) (src: Z + RegName) (regs': Reg): cap_lang.val -> Prop :=\n  | IsPtr_spec_success w:\n      word_of_argument regs src = Some w →\n      incrementPC (<[ dst := w ]> regs) = Some regs' →\n      Mov_spec regs dst src regs' NextIV\n  | Mov_spec_failure w:\n      word_of_argument regs src = Some w →\n      incrementPC (<[ dst := w ]> regs) = None →\n      Mov_spec regs dst src regs' FailedV.\n\n  Lemma wp_Mov Ep pc_p pc_g pc_b pc_e pc_a w dst src regs :\n    decodeInstrW w = Mov dst src ->\n    isCorrectPC (inr ((pc_p, pc_g), pc_b, pc_e, pc_a)) →\n    regs !! PC = Some (inr ((pc_p, pc_g), pc_b, pc_e, pc_a)) →\n    regs_of (Mov dst src) ⊆ dom _ regs →\n    {{{ ▷ pc_a ↦ₐ w ∗\n        ▷ [∗ map] k↦y ∈ regs, k ↦ᵣ y }}}\n      Instr Executable @ Ep\n    {{{ regs' retv, RET retv;\n        ⌜ Mov_spec regs dst src regs' retv ⌝ ∗\n        pc_a ↦ₐ w ∗\n        [∗ map] k↦y ∈ regs', k ↦ᵣ y }}}.\n  Proof.\n    iIntros (Hinstr Hvpc HPC Dregs φ) \"(>Hpc_a & >Hmap) Hφ\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 l1 l2 n) \"Hσ1 /=\". destruct σ1 as [r m]; simpl.\n    iDestruct \"Hσ1\" as \"[Hr Hm]\".\n    iDestruct (gen_heap_valid_inclSepM with \"Hr Hmap\") as %Hregs.\n    have HPC' := regs_lookup_eq _ _ _ HPC.\n    have ? := lookup_weaken _ _ _ _ HPC Hregs.\n    iDestruct (@gen_heap_valid with \"Hm Hpc_a\") as %Hpc_a; auto.\n    iModIntro. iSplitR. by iPureIntro; apply normal_always_head_reducible.\n    iNext. iIntros (e2 σ2 efs Hpstep).\n    apply prim_step_exec_inv in Hpstep as (-> & -> & (c & -> & Hstep)).\n    iSplitR; auto. eapply step_exec_inv in Hstep; eauto.\n\n    specialize (indom_regs_incl _ _ _ Dregs Hregs) as Hri. unfold regs_of in Hri.\n    destruct (Hri dst) as [wdst [H'dst Hdst]]. by set_solver+.\n\n    assert (exists w, word_of_argument regs src = Some w) as [wsrc Hwsrc].\n    { destruct src as [| r0]; eauto; cbn.\n      destruct (Hri r0) as [? [? ?]]. set_solver+. eauto. }\n\n    pose proof Hwsrc as Hwsrc'. eapply word_of_argument_Some_inv' in Hwsrc; eauto.\n\n    assert ((c, σ2) = updatePC (update_reg (r, m) dst wsrc)) as HH.\n    { destruct Hwsrc as [ [? [? ?] ] | [? (? & ? & Hr') ] ]; simplify_eq; eauto.\n      by rewrite /= /RegLocate Hr' in Hstep. }\n    rewrite /update_reg /= in HH.\n\n    destruct (incrementPC (<[ dst := wsrc ]> regs)) as [regs'|] eqn:Hregs';\n      pose proof Hregs' as H'regs'; cycle 1.\n    { apply incrementPC_fail_updatePC with (m:=m) in Hregs'.\n      eapply updatePC_fail_incl with (m':=m) in Hregs'.\n      2: by apply lookup_insert_is_Some'; eauto.\n      2: by apply insert_mono; eauto.\n      simplify_pair_eq.\n      iMod ((gen_heap_update_inSepM _ _ dst) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n      iFrame. iApply \"Hφ\"; iFrame. iPureIntro. econstructor; eauto. }\n\n    eapply (incrementPC_success_updatePC _ m) in Hregs'\n      as (p' & g' & b' & e' & a'' & a_pc' & HPC'' & Ha_pc' & HuPC & -> & ?).\n    eapply updatePC_success_incl with (m':=m) in HuPC. 2: by eapply insert_mono; eauto.\n    simplify_pair_eq. iFrame.\n    iMod ((gen_heap_update_inSepM _ _ dst) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n    iMod ((gen_heap_update_inSepM _ _ PC) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n    iFrame. iModIntro. iApply \"Hφ\". iFrame. iPureIntro. econstructor; eauto.\n  Qed.\n\n  Lemma wp_move_success_z E pc_p pc_g pc_b pc_e pc_a pc_a' w r1 wr1 z :\n    decodeInstrW w = Mov r1 (inl z) →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (pc_a + 1)%a = Some pc_a' →\n\n    {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ ▷ pc_a ↦ₐ w\n        ∗ ▷ r1 ↦ᵣ wr1 }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ r1 ↦ᵣ inl z }}}.\n  Proof.\n    iIntros (Hinstr Hvpc Hpca' ϕ) \"(>HPC & >Hpc_a & >Hr1) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hr1\") as \"[Hmap %]\".\n    iApply (wp_Mov with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by unfold regs_of; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [|].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC r1) // insert_insert insert_commute // insert_insert.\n      iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      incrementPC_inv; simplify_map_eq; eauto. destruct H4; try congruence. \n      inv Hvpc. naive_solver. }\n  Qed.\n\n  Lemma wp_move_success_reg E pc_p pc_g pc_b pc_e pc_a pc_a' w r1 wr1 rv wrv :\n    decodeInstrW w = Mov r1 (inr rv) →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (pc_a + 1)%a = Some pc_a' →\n\n    {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ ▷ pc_a ↦ₐ w\n        ∗ ▷ r1 ↦ᵣ wr1\n        ∗ ▷ rv ↦ᵣ wrv }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ r1 ↦ᵣ wrv\n          ∗ rv ↦ᵣ wrv }}}.\n  Proof.\n    iIntros (Hinstr Hvpc Hpca' ϕ) \"(>HPC & >Hpc_a & >Hr1 & >Hrv) Hφ\".\n    iDestruct (map_of_regs_3 with \"HPC Hr1 Hrv\") as \"[Hmap (%&%&%)]\".\n    iApply (wp_Mov with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by unfold regs_of; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [|].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC r1) // insert_insert (insert_commute _ PC r1) // insert_insert.\n      iDestruct (regs_of_map_3 with \"Hmap\") as \"(?&?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      incrementPC_inv; simplify_map_eq; eauto. \n      destruct H6; try congruence. inv Hvpc. naive_solver. }\n  Qed.\n\n  Lemma wp_move_success_reg_same E pc_p pc_g pc_b pc_e pc_a pc_a' w r1 wr1 :\n    decodeInstrW w = Mov r1 (inr r1) →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (pc_a + 1)%a = Some pc_a' →\n\n    {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ ▷ pc_a ↦ₐ w\n        ∗ ▷ r1 ↦ᵣ wr1 }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ r1 ↦ᵣ wr1 }}}.\n  Proof.\n    iIntros (Hinstr Hvpc Hpca' ϕ) \"(>HPC & >Hpc_a & >Hr1) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hr1\") as \"[Hmap %]\".\n    iApply (wp_Mov with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by unfold regs_of; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [|].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC r1) // insert_insert insert_commute // insert_insert.\n      iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      incrementPC_inv; simplify_map_eq; eauto. \n      destruct H4; try congruence. inv Hvpc. naive_solver. }\n  Qed.\n\n  Lemma wp_move_success_reg_samePC E pc_p pc_g pc_b pc_e pc_a pc_a' w :\n    decodeInstrW w = Mov PC (inr PC) →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (pc_a + 1)%a = Some pc_a' →\n\n    {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ ▷ pc_a ↦ₐ w }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w }}}.\n  Proof.\n    iIntros (Hinstr Hvpc Hpca' ϕ) \"(>HPC & >Hpc_a) Hφ\".\n    iDestruct (map_of_regs_1 with \"HPC\") as \"Hmap\".\n    iApply (wp_Mov with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by unfold regs_of; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [|].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite !insert_insert.\n      iDestruct (regs_of_map_1 with \"Hmap\") as \"?\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      incrementPC_inv; simplify_map_eq; eauto. \n      destruct H3; try congruence. inv Hvpc. naive_solver. }\n  Qed.\n\n  (*\n  Lemma wp_move_success_reg_toPC E pc_p pc_g pc_b pc_e pc_a w r1 p g b e a a' :\n    decodeInstrW w = Mov PC (inr r1) →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (a + 1)%a = Some a' →\n\n    {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ ▷ pc_a ↦ₐ w\n        ∗ ▷ r1 ↦ᵣ inr ((p,g),b,e,a) }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr ((p,g),b,e,a')\n          ∗ pc_a ↦ₐ w\n          ∗ r1 ↦ᵣ inr ((p,g),b,e,a) }}}.\n  Proof.\n    iIntros (Hinstr Hvpc Hpca' ϕ) \"(>HPC & >Hpc_a & >Hr1) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hr1\") as \"[Hmap %]\".\n    iApply (wp_Mov with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by unfold regs_of; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [|].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC r1) // insert_insert insert_commute // insert_insert.\n      iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      incrementPC_inv; simplify_map_eq; eauto. congruence. }\n  Qed.*)\n\n  Lemma wp_move_success_reg_fromPC E pc_p pc_g pc_b pc_e pc_a pc_a' w r1 wr1 :\n    decodeInstrW w = Mov r1 (inr PC) →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (pc_a + 1)%a = Some pc_a' →\n\n    {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ ▷ pc_a ↦ₐ w\n        ∗ ▷ r1 ↦ᵣ wr1 }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ r1 ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a) }}}.\n  Proof.\n    iIntros (Hinstr Hvpc Hpca' ϕ) \"(>HPC & >Hpc_a & >Hr1) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hr1\") as \"[Hmap %]\".\n    iApply (wp_Mov with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by unfold regs_of; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [|].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC r1) // insert_insert insert_commute // insert_insert.\n      iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      incrementPC_inv; simplify_map_eq; eauto. \n      destruct H4; try congruence. inv Hvpc. naive_solver. }\n  Qed.\n\nEnd cap_lang_rules.\n", "meta": {"author": "logsem", "repo": "cerise-stack-monotone", "sha": "dff1909f6abc6de99c28d8f12e903b98dd76fb41", "save_path": "github-repos/coq/logsem-cerise-stack-monotone", "path": "github-repos/coq/logsem-cerise-stack-monotone/cerise-stack-monotone-dff1909f6abc6de99c28d8f12e903b98dd76fb41/theories/rules/rules_Mov.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23846090906360973}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*              Object Primitives                                      *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AuxStateDataType.\nRequire Import FlatMemory.\nRequire Import AbstractDataType.\nRequire Import Integers.\nRequire Import Values.\nRequire Import RealParams.\nRequire Import Constant.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\n\nSection PRIM_Container.\n\n  Context `{real_params: RealParams}.\n\n    Function container_init_spec (mbi: Z) (adt: RData) : option RData :=\n      match (init adt, pg adt, ikern adt, ihost adt) with\n        | (false, false, true, true) =>\n          Some adt {vmxinfo: real_vmxinfo} {AT: real_AT (AT adt)} {nps: real_nps}\n                   {init: true} {AC: real_AC}\n        | _ => None\n      end.\n\n    Function container_init0_spec (mbi: Z) (adt: RData) : option RData :=\n      match (init adt, pg adt, ikern adt, ihost adt, ipt adt) with\n        | (false, false, true, true, true) =>\n          Some adt {vmxinfo: real_vmxinfo} {AT: real_AT (AT adt)} {nps: real_nps}\n                   {init: true} {AC: real_AC}\n        | _ => None\n      end.\n\n    Function container_get_parent_spec (i: Z) (adt: RData): option Z :=\n      let c := ZMap.get i (AC adt) in\n      match (ikern adt, ihost adt, cused c) with\n        | (true, true, true) => Some (cparent c) \n        | _ => None\n      end.\n\n    Function container_get_nchildren_spec (i: Z) (adt: RData) : option Z :=\n      let c := ZMap.get i (AC adt) in\n      match (ikern adt, ihost adt, cused c) with\n        | (true, true, true) => Some (Z_of_nat (length (cchildren c)))\n        | _ => None\n      end.\n\n    Function container_get_quota_spec (i: Z) (adt: RData) : option Z :=\n      let c := ZMap.get i (AC adt) in\n      match (ikern adt, ihost adt, cused c) with\n        | (true, true, true) => Some (cquota c) \n        | _ => None\n      end.\n\n    Function container_get_usage_spec (i: Z) (adt: RData): option Z :=\n      let c := ZMap.get i (AC adt) in\n      match (ikern adt, ihost adt, cused c) with\n        | (true, true, true) => Some (cusage c)\n        | _ => None\n      end.\n\n    Function container_can_consume_spec (i: Z) (n: Z) (adt: RData) : option Z :=\n      match (ikern adt, ihost adt, cused (ZMap.get i (AC adt))) with\n        | (true, true, true) => \n          Some (if zle_le 0 n (cquota (ZMap.get i (AC adt)) - cusage (ZMap.get i (AC adt))) \n                then 1 else 0)\n        | _ => None\n      end.\n\n    Function container_split_spec (id: Z) (q: Z) (adt: RData) : option (RData*Z) :=\n      let c := ZMap.get id (AC adt) in \n      let i := id * max_children + 1 + Z_of_nat (length (cchildren c)) in\n      match (ikern adt, ihost adt, cused c, zle_lt 0 i num_id,\n             zlt (Z_of_nat (length (cchildren c))) max_children,\n             zle_le 0 q (cquota c - cusage c)) with\n      | (true, true, true, left _, left _, left _) =>\n           let child := mkContainer q 0 id nil true in\n             Some (adt {AC: ZMap.set i child ((AC adt) {usage id := cusage c + q}\n                                                       {children id := (i :: cchildren c)})}, i)\n      | _ => None\n      end.\n(*\n    Function container_revoke_spec (adt: RData) (i: Z) : option RData :=\n      if zeq i 0 then None else\n      let c := ZMap.get i (AC adt) in \n      let p := ZMap.get (cparent c) (AC adt) in \n      match (ikern adt, ihost adt, cused c, cchildren c) with\n      | (true, true, true, nil) => \n         let p' := mkContainer (cquota p) (cusage p - cquota c)\n                     (cparent p) (remove zeq i (cchildren p)) (cused p) in\n           Some (mkRData (HP adt) (MM adt) (MMSize adt)\n                (ZMap.set (cparent c) p' (ZMap.set i Container_unused (AC adt)))\n                (CR3 adt) (ti adt) (pg adt) (ikern adt) (ihost adt))\n      | _ => None\n      end.\n*)\n    Function container_alloc_spec (id: Z) (adt: RData)  : option (RData*Z) :=\n      let c := ZMap.get id (AC adt) in\n      match (ikern adt, ihost adt, init adt, cused c) with          \n      | (true, true, true, true) =>\n        if cusage c <? cquota c then\n          let cur := mkContainer (cquota c) (cusage c + 1) (cparent c)\n                                 (cchildren c) (cused c) in\n          match first_free (AT adt) (nps adt) with\n            | inleft (exist i _) => \n              Some (adt {AT: ZMap.set i (ATValid true ATNorm 0) (AT adt)}\n                        {pperm: ZMap.set i PGAlloc (pperm adt)}\n                        {AC: ZMap.set id cur (AC adt)}, i)\n            | _ => None\n          end\n        else Some (adt, 0)\n      | _ => None\n    end.\n(*\n    Function container_free_spec (adt: RData) (i: Z) : option RData :=\n      let c := ZMap.get i (AC adt) in \n      match (ikern adt, ihost adt, cused c, 0 <? cusage c) with \n      | (true, true, true, true) =>\n        let cur := mkContainer (cquota c) (cusage c - 1) (cparent c)\n                        (cchildren c) (cused c) in\n        Some (mkRData (HP adt) (MM adt) (MMSize adt) (ZMap.set i cur (AC adt))\n             (CR3 adt) (ti adt) (pg adt) (ikern adt) (ihost adt))\n      | _ => None\n      end.\n*)\n\nEnd PRIM_Container.\n\nSection CVALID.\n\n  Lemma cvalid_unused_child_id_range :\n    forall C, Container_valid C ->\n      forall i, cused (ZMap.get i C) = true -> \n        forall j, i * max_children + 1 + Z_of_nat (length (cchildren (ZMap.get i C))) <=\n                  j < i * max_children + 1 + max_children -> cused (ZMap.get j C) = false.\n  Proof.\n    intros C Hvalid i Hi j Hrange; destruct Hvalid.\n    destruct (cused (ZMap.get j C)) eqn:Hj; auto.\n    destruct (zeq j 0) as [Heq|Hneq]; subst.\n    specialize (cvalid_id _ Hi); omega.    \n    specialize (cvalid_parents_child _ Hj Hneq).\n    rewrite (cvalid_parent_id _ Hj) in cvalid_parents_child.\n    destruct (zeq j 0); try congruence.\n    replace ((j-1) / max_children) with i in cvalid_parents_child.\n    specialize (cvalid_child_id_range _ Hi); rewrite Forall_forall in cvalid_child_id_range.\n    specialize (cvalid_child_id_range _ cvalid_parents_child); omega.\n    apply Zdiv.Zdiv_unique with (r:= j - (i * max_children + 1)); omega.\n  Qed.\n\n  Lemma cvalid_unused_next_child :\n    forall C, Container_valid C ->\n      forall i, cused (ZMap.get i C) = true ->\n        Z_of_nat (length (cchildren (ZMap.get i C))) < max_children ->\n        cused (ZMap.get (i * max_children + 1 + \n                         Z_of_nat (length (cchildren (ZMap.get i C)))) C) = false.\n  Proof.\n    intros; eapply cvalid_unused_child_id_range; eauto; omega.\n  Qed.\n\n  Lemma cvalid_child_id_pos :\n    forall C, Container_valid C ->\n      forall i, cused (ZMap.get i C) = true ->\n        forall k, k >= 0 -> 0 < i * max_children + 1 + k.\n  Proof.\n    intros C Hvalid i Hi k Hk; destruct Hvalid.\n    specialize (cvalid_id _ Hi); omega.\n  Qed.\n\n  Lemma cvalid_child_id_neq :\n    forall C, Container_valid C ->\n      forall i, cused (ZMap.get i C) = true ->\n        i <> i * max_children + 1 + Z_of_nat (length (cchildren (ZMap.get i C))).\n  Proof.\n    intros C Hvalid i Hi; destruct Hvalid.\n    assert (Hmath: forall i j, 0 <= i -> 0 <= j -> i <> i * max_children + 1 + j) by (intros; omega).\n    apply Hmath.\n    specialize (cvalid_id _ Hi); omega.\n    apply Nat2Z.is_nonneg.\n  Qed.\n\nEnd CVALID.\n\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import CommonTactic.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import AuxLemma.\nRequire Import Observation.\n\nSection OBJ_SIM.\n\n  Context `{Hobs: Observation}.\n\n  Context `{data : CompatData(Obs:=Obs) RData}.\n  Context `{data0 : CompatData(Obs:=Obs) RData}.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Notation HDATAOps := (cdata (cdata_prf := data) RData).\n  Notation LDATAOps := (cdata (cdata_prf := data0) RData).\n\n  Context `{rel_prf: CompatRel _ (Obs:=Obs) (memory_model_ops:= memory_model_ops) _\n                               (stencil_ops:= stencil_ops) HDATAOps LDATAOps}.\n\n  Context {re1: relate_impl_iflags}.\n  Context {re2: relate_impl_init}.\n  Context {re3: relate_impl_AC}.\n\n  Section CONTAINER_INIT_SIM.\n\n    Context `{real_params: RealParams}.\n\n    Context {re4: relate_impl_AT}.\n    Context {re5: relate_impl_nps}.\n    Context {re6: relate_impl_vmxinfo}.\n\n    Lemma container_init_exist:\n      forall s habd habd' labd mbi f,\n        container_init_spec mbi habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', container_init_spec mbi labd = Some labd'\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold container_init_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_init_eq; eauto.\n      exploit relate_impl_AC_eq; eauto.\n      exploit relate_impl_AT_eq; eauto.\n      exploit relate_impl_nps_eq; eauto.\n      exploit relate_impl_vmxinfo_eq; eauto. intros.\n      revert H; subrewrite. subdestruct.\n      inv HQ. refine_split'; trivial.\n\n      apply relate_impl_AC_update.\n      apply relate_impl_init_update.\n      apply relate_impl_nps_update. \n      apply relate_impl_AT_update.\n      apply relate_impl_vmxinfo_update. assumption.\n    Qed.\n\n    Context {mt1: match_impl_iflags}.\n    Context {mt2: match_impl_init}.\n    Context {mt3: match_impl_AC}.\n    Context {mt4: match_impl_AT}.\n    Context {mt5: match_impl_nps}.\n    Context {mt6: match_impl_vmxinfo}.\n\n    Lemma container_init_match:\n      forall s d d' m mbi f,\n        container_init_spec mbi d = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold container_init_spec; intros. subdestruct. inv H.      \n      apply match_impl_AC_update.\n      apply match_impl_init_update.\n      apply match_impl_nps_update. \n      apply match_impl_AT_update.\n      apply match_impl_vmxinfo_update. assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) container_init_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) container_init_spec}.\n\n    Lemma container_init_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem container_init_spec)\n            (id ↦ gensem container_init_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit container_init_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply container_init_match; eauto.\n    Qed.\n\n  End CONTAINER_INIT_SIM.\n\n  Section CONTAINER_INIT0_SIM.\n\n    Context `{real_params: RealParams}.\n\n    Context {re4: relate_impl_AT}.\n    Context {re5: relate_impl_nps}.\n    Context {re6: relate_impl_vmxinfo}.\n    Context {re7: relate_impl_ipt}.\n\n    Lemma container_init0_exist:\n      forall s habd habd' labd mbi f,\n        container_init0_spec mbi habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', container_init0_spec mbi labd = Some labd'\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold container_init0_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_init_eq; eauto.\n      exploit relate_impl_AC_eq; eauto.\n      exploit relate_impl_AT_eq; eauto.\n      exploit relate_impl_nps_eq; eauto.\n      exploit relate_impl_vmxinfo_eq; eauto.\n      exploit relate_impl_ipt_eq; eauto. intros.\n      revert H; subrewrite. subdestruct.\n      inv HQ. refine_split'; trivial.\n\n      apply relate_impl_AC_update.\n      apply relate_impl_init_update.\n      apply relate_impl_nps_update. \n      apply relate_impl_AT_update.\n      apply relate_impl_vmxinfo_update. assumption.\n    Qed.\n\n    Context {mt1: match_impl_iflags}.\n    Context {mt2: match_impl_init}.\n    Context {mt3: match_impl_AC}.\n    Context {mt4: match_impl_AT}.\n    Context {mt5: match_impl_nps}.\n    Context {mt6: match_impl_vmxinfo}.\n\n    Lemma container_init0_match:\n      forall s d d' m mbi f,\n        container_init0_spec mbi d = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold container_init0_spec; intros. subdestruct. inv H.      \n      apply match_impl_AC_update.\n      apply match_impl_init_update.\n      apply match_impl_nps_update. \n      apply match_impl_AT_update.\n      apply match_impl_vmxinfo_update. assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) container_init0_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) container_init0_spec}.\n\n    Lemma container_init0_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem container_init0_spec)\n            (id ↦ gensem container_init0_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit container_init0_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply container_init0_match; eauto.\n    Qed.\n\n  End CONTAINER_INIT0_SIM.\n\n  Section CONTAINER_GET_PARENT_SIM.\n\n    Lemma container_get_parent_exist:\n      forall s habd labd i p f,\n        container_get_parent_spec i habd = Some p\n        -> relate_AbData s f habd labd\n        -> container_get_parent_spec i labd = Some p.\n    Proof.\n      unfold container_get_parent_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_AC_eq; eauto. intros.\n      revert H. subrewrite.\n    Qed.\n\n    Lemma container_get_parent_sim:\n      forall id,\n        sim (crel RData RData) (id ↦ gensem container_get_parent_spec)\n                               (id ↦ gensem container_get_parent_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      match_external_states_simpl.\n      erewrite container_get_parent_exist; eauto 1.\n      reflexivity.\n    Qed.\n\n  End CONTAINER_GET_PARENT_SIM.\n\n  Section CONTAINER_GET_NCHILDREN_SIM.\n\n    Lemma container_get_nchildren_exist:\n      forall s habd labd i p f,\n        container_get_nchildren_spec i habd = Some p\n        -> relate_AbData s f habd labd\n        -> container_get_nchildren_spec i labd = Some p.\n    Proof.\n      unfold container_get_nchildren_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_AC_eq; eauto. intros.\n      revert H. subrewrite.\n    Qed.\n\n    Lemma container_get_nchildren_sim:\n      forall id,\n        sim (crel RData RData) (id ↦ gensem container_get_nchildren_spec)\n                               (id ↦ gensem container_get_nchildren_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      match_external_states_simpl.\n      erewrite container_get_nchildren_exist; eauto 1.\n      reflexivity.\n    Qed.\n\n  End CONTAINER_GET_NCHILDREN_SIM.\n\n  Section CONTAINER_GET_QUOTA_SIM.\n\n    Lemma container_get_quota_exist:\n      forall s habd labd i p f,\n        container_get_quota_spec i habd = Some p\n        -> relate_AbData s f habd labd\n        -> container_get_quota_spec i labd = Some p.\n    Proof.\n      unfold container_get_quota_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_AC_eq; eauto. intros.\n      revert H. subrewrite.\n    Qed.\n\n    Lemma container_get_quota_sim:\n      forall id,\n        sim (crel RData RData) (id ↦ gensem container_get_quota_spec)\n                               (id ↦ gensem container_get_quota_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      match_external_states_simpl.\n      erewrite container_get_quota_exist; eauto 1.\n      reflexivity.\n    Qed.\n\n  End CONTAINER_GET_QUOTA_SIM.\n\n  Section CONTAINER_GET_USAGE_SIM.\n\n    Lemma container_get_usage_exist:\n      forall s habd labd i p f,\n        container_get_usage_spec i habd = Some p\n        -> relate_AbData s f habd labd\n        -> container_get_usage_spec i labd = Some p.\n    Proof.\n      unfold container_get_usage_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_AC_eq; eauto. intros.\n      revert H. subrewrite.\n    Qed.\n\n    Lemma container_get_usage_sim:\n      forall id,\n        sim (crel RData RData) (id ↦ gensem container_get_usage_spec)\n                               (id ↦ gensem container_get_usage_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      match_external_states_simpl.\n      erewrite container_get_usage_exist; eauto 1.\n      reflexivity.\n    Qed.\n\n  End CONTAINER_GET_USAGE_SIM.\n\n  Section CONTAINER_CAN_CONSUME_SIM.\n\n    Lemma container_can_consume_exist:\n      forall s habd labd i n b f,\n        container_can_consume_spec i n habd = Some b\n        -> relate_AbData s f habd labd\n        -> container_can_consume_spec i n labd = Some b.\n    Proof.\n      unfold container_can_consume_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_AC_eq; eauto. intros.\n      revert H. subrewrite.\n    Qed.\n\n    Lemma container_can_consume_sim:\n      forall id,\n        sim (crel RData RData) (id ↦ gensem container_can_consume_spec)\n                               (id ↦ gensem container_can_consume_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      match_external_states_simpl.\n      erewrite container_can_consume_exist; eauto 1.\n      reflexivity.\n    Qed.\n\n  End CONTAINER_CAN_CONSUME_SIM.\n\n  Section CONTAINER_SPLIT_SIM.\n\n    Lemma container_split_exist:\n      forall s habd habd' labd i n z f,\n        container_split_spec i n habd = Some (habd', z)\n        -> relate_AbData s f habd labd\n        -> exists labd', container_split_spec i n labd = Some (labd', z)\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold container_split_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_init_eq; eauto.\n      exploit relate_impl_AC_eq; eauto. intros.\n      revert H; subrewrite. subdestruct.\n      inv HQ. refine_split'; trivial.\n\n      apply relate_impl_AC_update. assumption.\n    Qed.\n\n    Context {mt2: match_impl_AC}.\n\n    Lemma container_split_match:\n      forall s d d' m i n z f,\n        container_split_spec i n d = Some (d', z)\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold container_split_spec; intros. subdestruct. inv H.\n      eapply match_impl_AC_update. assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) container_split_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) container_split_spec}.\n\n    Lemma container_split_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem container_split_spec)\n            (id ↦ gensem container_split_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit container_split_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply container_split_match; eauto.\n    Qed.\n\n  End CONTAINER_SPLIT_SIM.\n\n  Section CONTAINER_ALLOC_SIM.\n\n    Context {re4: relate_impl_AT}.\n    Context {re5: relate_impl_pperm}.\n    Context {re6: relate_impl_nps}.\n\n    Lemma container_alloc_exist:\n      forall s habd habd' labd i f z,\n        container_alloc_spec i habd = Some (habd', z)\n        -> relate_AbData s f habd labd\n        -> exists labd', container_alloc_spec i labd = Some (labd', z)\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold container_alloc_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_init_eq; eauto.\n      exploit relate_impl_AT_eq; eauto.\n      exploit relate_impl_pperm_eq; eauto.\n      exploit relate_impl_nps_eq; eauto.\n      exploit relate_impl_AC_eq; eauto. intros.\n      revert H; subrewrite.\n      subdestruct; inv HQ; refine_split'; trivial.\n      apply relate_impl_AC_update. \n      apply relate_impl_pperm_update.\n      apply relate_impl_AT_update. assumption.\n    Qed.\n\n    Context {mt1: match_impl_AC}.\n    Context {mt2: match_impl_pperm}.\n    Context {mt3: match_impl_AT}.\n\n    Lemma container_alloc_match:\n      forall s d d' m i f z,\n        container_alloc_spec i d = Some (d',z)\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold container_alloc_spec; intros. \n      subdestruct; inv H; auto.\n      apply match_impl_AC_update.\n      apply match_impl_pperm_update.\n      apply match_impl_AT_update. assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) container_alloc_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) container_alloc_spec}.\n\n    Lemma container_alloc_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem container_alloc_spec)\n            (id ↦ gensem container_alloc_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit container_alloc_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply container_alloc_match; eauto.\n    Qed.\n\n  End CONTAINER_ALLOC_SIM.\n\nEnd OBJ_SIM.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/objects/ObjContainer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23840864186153393}}
{"text": "From trillium.prelude Require Import classical.\nFrom trillium.traces Require Import trace.\nFrom trillium.program_logic Require Import\n     ectx_language language traces.\n\n(** Ideally, all definitions in this file should be computational.\n    But that's is too much work. Hence, since we already assume classical\n    axioms in this work we can use those to axiomatize the function that\n    given an execution extracts its observations. *)\n\nRecord Event (Λ : language) := mkEvent {\n  is_triggered :> expr Λ → state Λ → expr Λ → state Λ → Prop;\n  (* The following two axioms ensure that events are only triggered\n     on head steps. *)\n  is_triggered_not_val :\n    ∀ e1 σ1 e2 σ2, is_triggered e1 σ1 e2 σ2 → to_val e1 = None;\n  is_triggered_ectx_free :\n    ∀ e1 σ1 e2 σ2,\n      is_triggered e1 σ1 e2 σ2 →\n      ∀ K e1', e1 = ectx_fill K e1' → is_Some (to_val e1') ∨ K = ectx_emp;\n  is_triggered_not_stuttering :\n    ∀ e1 σ1 e2 σ2,\n      is_triggered e1 σ1 e2 σ2 → e1 ≠ e2;\n}.\n\nArguments is_triggered {_} _ _ _ _.\nArguments is_triggered_not_val {_} _ _ _ _.\nArguments is_triggered_ectx_free {_} _.\nArguments is_triggered_not_stuttering {_} _.\n\nRecord EventObservation (Λ : language) := mkEventObservation {\n  pre_expr : expr Λ;\n  pre_state : state Λ;\n  post_expr : expr Λ;\n  post_state : state Λ;\n}.\n\nArguments mkEventObservation {_} _ _ _ _.\nArguments pre_state {_} _.\nArguments pre_expr {_} _.\nArguments post_state {_} _.\nArguments post_expr {_} _.\n\nDefinition validEventObservation\n           {Λ : language} (EV : Event Λ) (eo : EventObservation Λ) :=\n  EV eo.(pre_expr) eo.(pre_state) eo.(post_expr) eo.(post_state).\n\nDefinition event_obs (Λ : language) := list (EventObservation Λ).\n\nDefinition valid_event_obs\n           {Λ : language} (EV : Event Λ) (eo : event_obs Λ)  : Prop :=\n  Forall (validEventObservation EV) eo.\n\nInductive trace_has_events {Λ : language} (EV : Event Λ) :\n          execution_trace Λ → event_obs Λ → Prop :=\n| singleton_events c : trace_has_events EV {tr[c]} []\n| extend_observed ex c c' tp1 tp2 efs K eo eobs oζ:\n    trace_ends_in ex c →\n    c.2 = eo.(pre_state) →\n    c.1 = tp1 ++ ectx_fill K eo.(pre_expr) :: tp2 →\n    c'.2 = eo.(post_state) →\n    c'.1 = tp1 ++ ectx_fill K eo.(post_expr) :: tp2 ++ efs →\n    validEventObservation EV eo →\n    trace_has_events EV ex eobs →\n    trace_has_events EV (ex :tr[oζ]: c') (eobs ++ [eo])\n| extend_not_observed ex c c' eobs oζ:\n    trace_ends_in ex c →\n    (∀ tp1 tp2 efs K e1 e2,\n      c.1 = tp1 ++ ectx_fill K e1 :: tp2 →\n      c'.1 = tp1 ++ ectx_fill K e2 :: tp2 ++ efs →\n      ¬ EV e1 c.2 e2 c'.2) →\n    trace_has_events EV ex eobs →\n    trace_has_events EV (ex :tr[oζ]: c') eobs.\n\nSection properties.\n  Context {Λ : language} (EV : Event Λ).\n\n  Implicit Types e : expr Λ.\n  Implicit Types tp : list (expr Λ).\n  Implicit Types σ : state Λ.\n  Implicit Types eobs : event_obs Λ.\n  Implicit Types obs : EventObservation Λ.\n  Implicit Types ex : execution_trace Λ.\n\n  Lemma validEventObservation_exprs_neq obs :\n    validEventObservation EV obs → obs.(pre_expr) ≠ obs.(post_expr).\n  Proof. intros; eapply is_triggered_not_stuttering; done. Qed.\n\n  Lemma validEventObservation_not_val obs :\n    validEventObservation EV obs → to_val obs.(pre_expr) = None.\n  Proof. intros; eapply is_triggered_not_val; done. Qed.\n\n  Lemma trace_has_events_valid ex eobs :\n    trace_has_events EV ex eobs → valid_event_obs EV eobs.\n  Proof.\n    induction 1 as [|ex [tp σ] [tp' σ']|]; simplify_eq/=.\n    - by constructor.\n    - apply Forall_app; split; first done.\n      apply Forall_singleton; done.\n    - done.\n  Qed.\n\n  Lemma event_in_the_middle tp1 tp2 K e1 e2 efs tp1' tp2' K' eo efs' :\n    validEventObservation EV eo →\n    to_val e1 = None →\n    (∀ e1' K'', e1 = ectx_fill K'' e1' → is_Some (to_val e1') ∨ K'' = ectx_emp) →\n    tp1 ++ ectx_fill K e1 :: tp2 = tp1' ++ ectx_fill K' (pre_expr eo) :: tp2' →\n    tp1 ++ ectx_fill K e2 :: tp2 ++ efs =\n    tp1' ++ ectx_fill K' (post_expr eo) :: tp2' ++ efs' →\n    pre_expr eo = e1 ∧ post_expr eo = e2.\n  Proof.\n    intros HEV He1 Hnectx Heq1 Heq2.\n    destruct (decide (length tp1' < length tp1)).\n    { pose proof (f_equal (λ x, x !! length tp1') Heq1) as Heq1'.\n      rewrite /= lookup_app_l // lookup_app_r // Nat.sub_diag /= in Heq1'.\n      pose proof (f_equal (λ x, x !! length tp1') Heq2) as Heq2'.\n      rewrite /= lookup_app_l // lookup_app_r // Nat.sub_diag /= in Heq2'.\n      rewrite Heq1' in Heq2'; simplify_eq.\n      apply ectx_fill_inj in Heq2'.\n      exfalso; eapply validEventObservation_exprs_neq; done. }\n    pose proof (f_equal (λ x, x !! length tp1') Heq1) as Heq1'.\n    rewrite /= lookup_app_r in Heq1'; last lia.\n    rewrite // lookup_app_r // Nat.sub_diag /= in Heq1'.\n    pose proof (f_equal (λ x, x !! length tp1') Heq2) as Heq2'.\n    rewrite /= lookup_app_r in Heq2'; last lia.\n    rewrite // lookup_app_r // Nat.sub_diag /= in Heq2'.\n    rewrite /= app_comm_cons lookup_app_l in Heq2'; last first.\n    { simpl.\n      assert (length tp1' < length tp1 + S (length tp2)); last lia.\n      pose proof (f_equal length Heq1) as Heq'.\n      rewrite !app_length //= in Heq'; lia. }\n    destruct (length tp1' - length tp1); last first.\n    { simpl in *.\n      rewrite Heq1' in Heq2'; simplify_eq.\n      apply ectx_fill_inj in Heq2'.\n      exfalso; eapply validEventObservation_exprs_neq; done. }\n    simplify_eq/=.\n    pose proof Heq1' as Heq1''.\n    apply ectx_fill_positive in Heq1'' as [[K'' ->]|[K'' ->]];\n          [| |done|\n             by apply validEventObservation_not_val].\n    - rewrite ectx_comp_comp in Heq2'.\n      apply ectx_fill_inj in Heq2'.\n      rewrite ectx_comp_comp in Heq1'.\n      apply ectx_fill_inj in Heq1'.\n      simplify_eq.\n      assert (K'' = ectx_emp) as ->.\n      { edestruct Hnectx as [[]|]; [done| |done].\n        pose proof (validEventObservation_not_val _ HEV); simplify_eq. }\n      rewrite !ectx_fill_emp; done.\n    - rewrite ectx_comp_comp in Heq1'.\n      apply ectx_fill_inj in Heq1'.\n      rewrite ectx_comp_comp in Heq2'.\n      apply ectx_fill_inj in Heq2'.\n      assert (K'' = ectx_emp) as ->.\n      { edestruct @is_triggered_ectx_free as [[]|];\n          [done|symmetry; done| |done].\n        pose proof (validEventObservation_not_val _ HEV); simplify_eq. }\n      rewrite ectx_fill_emp in Heq1'.\n      rewrite ectx_fill_emp in Heq2'.\n      simplify_eq; done.\n  Qed.\n\n  (** This lemma, proven completely constructively, is an evidence why we\n      are justified in using classical logic in constructing observations of\n      a valid execution trace. *)\n  Lemma trace_has_events_functional ex eobs eobs' :\n    valid_exec ex →\n    trace_has_events EV ex eobs →\n    trace_has_events EV ex eobs' →\n    eobs = eobs'.\n  Proof.\n    intros Hex; revert eobs eobs'.\n    induction Hex as [|ex [tp σ] oζ [tp' σ'] Hendsin Hstep Hex IHex];\n      intros eobs eobs'.\n    { do 2 inversion 1; simplify_eq; done. }\n    inversion 1 as [|ex' [tpz σz] [tpy σy] tp1z tp2z ? ? obs3 ? eobs3 Hendsin'|\n                    ex' [tpz σz] [tpy σy] ? ? Hendsin' Hnobs]; simplify_eq/=.\n    - pose proof (trace_ends_in_inj _ _ _ Hendsin Hendsin'); simplify_eq.\n      inversion 1 as [|ex' [tpx σx] [tpw σw] tp1x tp2x ? ? obs4 ? eobs4 Hendsin''\n                           ??? Htpseq| ex' [tpx σx] [tpw σw] ? ? Hendsin'' Hnobs];\n        simplify_eq/=.\n      + repeat f_equal; first by apply IHex.\n        pose proof (trace_ends_in_inj _ _ _ Hendsin' Hendsin'') as Htpseq'.\n        simplify_eq Htpseq'; intros Htpseq'1 Htpseq'2; clear Htpseq'.\n        assert (pre_expr obs3 = pre_expr obs4 ∧ post_expr obs3 = post_expr obs4)\n          as [? ?].\n        eapply event_in_the_middle; [done| | |done|].\n        { apply validEventObservation_not_val; done. }\n        { intros; eapply is_triggered_ectx_free; eauto. }\n        { done. }\n        destruct obs3; destruct obs4; simplify_eq/=; done.\n      + pose proof (trace_ends_in_inj _ _ _ Hendsin Hendsin''); simplify_eq.\n        exfalso; eapply Hnobs; eauto.\n    - pose proof (trace_ends_in_inj _ _ _ Hendsin Hendsin'); simplify_eq.\n      inversion 1 as [|ex' [tpx σx] [tpw σw] ? ? ? ? obs4 eobs4 ?  Hendsin''|\n                    ex' [tpx σx] [tpw σw] ? Hendsin'' Hnobs']; simplify_eq/=.\n      + pose proof (trace_ends_in_inj _ _ _ Hendsin Hendsin''); simplify_eq.\n        exfalso; eapply Hnobs; eauto.\n      + apply IHex; done.\n  Qed.\n\n  Lemma trace_has_valid_events ex eobs :\n    trace_has_events EV ex eobs → valid_event_obs EV eobs.\n  Proof.\n    induction 1; [constructor| |done].\n    apply Forall_app_2; first done.\n    apply Forall_singleton; done.\n  Qed.\n\n  Lemma events_for_trace ex : ∃ eobs, trace_has_events EV ex eobs.\n  Proof.\n    induction ex as [c|ex [eobs Hthe] ? c].\n    { eexists; econstructor. }\n    destruct (ExcludedMiddle ((∃ tp1 tp2 efs K e1 e2,\n      (trace_last ex).1 = tp1 ++ ectx_fill K e1 :: tp2 ∧\n      c.1 = tp1 ++ ectx_fill K e2 :: tp2 ++ efs ∧\n      EV e1 (trace_last ex).2 e2 c.2))) as\n        [(tp1&tp2&efs&K&e1&e2&Heq1&Heq2&HEV)|Hnex].\n    - exists (eobs ++ [mkEventObservation e1 (trace_last ex).2 e2 c.2]).\n      econstructor; eauto using trace_ends_in_last.\n    - exists eobs; econstructor; [done| |done].\n      intros ?????????; apply Hnex; eauto 10.\n  Qed.\n\n  Definition events_of_trace ex : event_obs Λ := epsilon (events_for_trace ex).\n\n  Lemma trace_has_events_of_trace ex :\n    trace_has_events EV ex (events_of_trace ex).\n  Proof. apply (epsilon_correct _ (events_for_trace ex)). Qed.\n\n  Lemma events_of_trace_valid ex : valid_event_obs EV (events_of_trace ex).\n  Proof. eapply trace_has_valid_events; apply trace_has_events_of_trace. Qed.\n\n  Lemma events_of_trace_extend_same_tp ex c c' oζ:\n    valid_exec (ex :tr[oζ]: c') →\n    c.1 = c'.1 →\n    trace_ends_in ex c →\n    events_of_trace (ex :tr[oζ]: c') = events_of_trace ex.\n  Proof.\n    intros Hex Htps Hc.\n    destruct c as [tp σ]; destruct c' as [tp' σ']; simplify_eq/=.\n    cut (∀ eobs, trace_has_events EV (ex :tr[oζ]: (tp', σ')) eobs → events_of_trace ex = eobs).\n    { intros Help. erewrite Help; first done. apply trace_has_events_of_trace. }\n    intros eobs Heobs.\n    eapply trace_has_events_functional; [|apply trace_has_events_of_trace|].\n    { inversion Hex; done. }\n    inversion Heobs as [|?????? K ??? Hei|]; simplify_eq/=; last done.\n    pose proof (trace_ends_in_inj _ _ _ Hc Hei); simplify_eq/=.\n    exfalso; eapply validEventObservation_exprs_neq; first done.\n    eapply ectx_fill_inj; done.\n  Qed.\n\n  Lemma events_of_singleton_trace c : events_of_trace {tr[c]} = [].\n  Proof.\n    eapply trace_has_events_functional;\n      [constructor|apply trace_has_events_of_trace|constructor].\n  Qed.\n\n  Lemma events_of_trace_extend_pure ex c c' oζ:\n    (∀ eo, validEventObservation EV eo → eo.(pre_state) ≠ eo.(post_state)) →\n    valid_exec (ex :tr[oζ]: c') →\n    c.2 = c'.2 →\n    trace_ends_in ex c →\n    events_of_trace (ex :tr[oζ]: c') = events_of_trace ex.\n  Proof.\n    intros Himpure Hex Htps Hc.\n    destruct c as [tp σ]; destruct c' as [tp' σ']; simplify_eq/=.\n    cut (∀ eobs, trace_has_events EV (ex :tr[oζ]: (tp', σ')) eobs → events_of_trace ex = eobs).\n    { intros Help. erewrite Help; first done. apply trace_has_events_of_trace. }\n    intros eobs Heobs.\n    eapply trace_has_events_functional; [|apply trace_has_events_of_trace|].\n    { inversion Hex; done. }\n    inversion Heobs as [|?????? K ??? Hei|]; simplify_eq/=; last done.\n    pose proof (trace_ends_in_inj _ _ _ Hc Hei); simplify_eq/=.\n    exfalso; eapply Himpure; eauto.\n  Qed.\n\n    Definition event_is_triggered (ob : EventObservation Λ) (c c' : cfg Λ) :=\n    ∃ K tp1 tp2 efs,\n      c.2 = ob.(pre_state) ∧\n      c.1 = tp1 ++ ectx_fill K ob.(pre_expr) :: tp2 ∧\n      c'.2 = ob.(post_state) ∧\n      c'.1 = tp1 ++ ectx_fill K ob.(post_expr) :: tp2 ++ efs.\n\n  Lemma events_of_trace_extend_app (ex : execution_trace Λ) (c : cfg Λ) oζ:\n    valid_exec (ex :tr[oζ]: c) →\n    ∃ evs,\n      length evs ≤ 1 ∧\n      events_of_trace (ex :tr[oζ]: c) = events_of_trace ex ++ evs ∧\n      ∀ ev, ev ∈ evs → event_is_triggered ev (trace_last ex) c.\n  Proof.\n    intros Hvl.\n    pose proof (trace_has_events_of_trace (ex :tr[oζ]: c)) as Hthe.\n    inversion Hthe as [|?????????? Hend|]; simplify_eq.\n    - eexists [_]; split; first done.\n      erewrite (trace_has_events_functional ex (events_of_trace ex));\n        [|by eapply valid_exec_exec_extend_inv; eauto|by apply trace_has_events_of_trace|by eauto].\n      split; first done.\n      intros ev; rewrite elem_of_list_singleton; intros ->.\n      apply last_eq_trace_ends_in in Hend; simplify_eq.\n      eexists _, _, _, _; eauto.\n    - exists []; split; simpl; first lia.\n      rewrite app_nil_r.\n      split; last set_solver.\n      apply (trace_has_events_functional (ex :tr[oζ]: c)); [done|by apply trace_has_events_of_trace|].\n      eapply extend_not_observed; [eauto|eauto|by apply trace_has_events_of_trace].\n  Qed.\n\n  Lemma events_of_trace_app (ex : execution_trace Λ) (l : list (olocale Λ * cfg Λ)) :\n    valid_exec (ex +trl+ l) →\n    ∃ evs,\n      length evs ≤ length l ∧\n      events_of_trace (ex +trl+ l) = events_of_trace ex ++ evs ∧\n      ∀ ev  oζ1 oζ2,\n        ev ∈ evs →\n        ∃ i c1 c2 oζ1' oζ2',\n          ((oζ1, trace_last ex) :: l) !! i = Some (oζ1', c1) ∧\n          ((oζ2, trace_last ex) :: l) !! S i = Some (oζ2', c2) ∧\n          event_is_triggered ev c1 c2.\n  Proof.\n    induction l as [|[??]  ?] using rev_ind.\n    { exists []; rewrite /= app_nil_r; split_and!; [done|done|]. set_solver. }\n    rewrite -trace_append_list_assoc /=.\n    intros Hvl.\n    destruct IHl as (evs & Hevs1 & Hevs2 & Hevs3).\n    { eapply valid_exec_exec_extend_inv; eauto. }\n    apply events_of_trace_extend_app in Hvl as (evs' & Hevs'1 & Hevs'2 & Hevs'3).\n    rewrite Hevs2 in Hevs'2; rewrite Hevs'2.\n    rewrite -app_assoc.\n    eexists; split_and!; [|done|].\n    { rewrite !app_length /=; lia. }\n    intros ev oζ1 oζ2 [Hev|Hev]%elem_of_app.\n    - destruct (Hevs3 ev oζ1 oζ2 Hev) as (i & c1 & c2 & oζ1' & oζ2' & Hc1 & Hc2 & Htrg).\n      exists i, c1, c2, oζ1', oζ2'.\n      rewrite (lookup_app_l (_ :: _)); last first.\n      { apply lookup_lt_Some in Hc1; simpl in *; lia. }\n      rewrite lookup_app_l; last first.\n      { apply lookup_lt_Some in Hc2; simpl in *; lia. }\n      done.\n    - destruct (trace_last_of_append_list ex l oζ1) as [oζ Heq].\n      eexists (length l), _, _, oζ, _; split_and!; last by apply Hevs'3.\n      + rewrite -Heq.\n        rewrite (lookup_app_l (_ :: _)); first done.\n        simpl; lia.\n      + rewrite lookup_app_r; last done.\n        rewrite Nat.sub_diag //.\n  Qed.\n\n  Lemma events_of_trace_app_map (ex : execution_trace Λ) (l : list (olocale Λ * cfg Λ)) :\n    valid_exec (ex +trl+ l) →\n    ∃ evs,\n      length evs ≤ length l ∧\n      events_of_trace (ex +trl+ l) = events_of_trace ex ++ evs ∧\n      ∀ ev,\n        ev ∈ evs →\n        ∃ i c1 c2,\n          (trace_last ex :: map snd l) !! i = Some c1 ∧\n          (trace_last ex ::  map snd l) !! S i = Some c2 ∧\n          event_is_triggered ev c1 c2.\n  Proof.\n    intros Hval. destruct (events_of_trace_app ex l Hval) as (evs & Hlen & Hevs & H).\n    exists evs; repeat (split =>//). intros ev Hin.\n    destruct (H ev inhabitant inhabitant Hin) as (i & c1 & c2 & oζ1 & oζ2 & Hi & HSi & Htrig).\n    exists i, c1, c2. change (trace_last ex :: map snd l) with (map snd $ (inhabitant, trace_last ex) :: l).\n    rewrite ->!list_lookup_fmap, Hi, HSi. done.\n  Qed.\nEnd properties.\n\nSection properties.\n  Context {Λ : ectxLanguage} (EV : Event Λ).\n\n  Implicit Types e : expr Λ.\n  Implicit Types tp : list (expr Λ).\n  Implicit Types K : ectx Λ.\n  Implicit Types σ : state Λ.\n  Implicit Types eobs : event_obs Λ.\n  Implicit Types obs : EventObservation Λ.\n  Implicit Types ex : execution_trace Λ.\n\n  Lemma events_of_trace_extend_triggered ex tp1 tp2 K e1 e2 efs σ1 σ2 oζ :\n    valid_exec ex →\n    trace_ends_in ex (tp1 ++ fill K e1 :: tp2, σ1) →\n    head_step e1 σ1 e2 σ2 efs →\n    EV e1 σ1 e2 σ2 →\n    events_of_trace EV (ex :tr[oζ]: (tp1 ++ fill K e2 :: tp2 ++ efs, σ2)) =\n    events_of_trace EV ex ++ [mkEventObservation e1 σ1 e2 σ2].\n  Proof.\n    intros HexV Hex Hhstep HEV.\n    pose proof (trace_has_events_of_trace\n                  EV (ex :tr[oζ]: (tp1 ++ fill K e2 :: tp2 ++ efs, σ2))) as Hhasevs.\n    inversion Hhasevs as\n        [|??? tp1' tp2' efs' K' eo eobs ? Hei ? Heq1 ? Heq2 HEV' ? Heq3 Heq4|\n         ????? Hei HnEV]; simplify_eq.\n    - pose proof (trace_ends_in_inj _ _ _ Hex Hei); simplify_eq.\n      rewrite -Heq4.\n      assert (eobs = events_of_trace EV ex) as ->.\n      { eapply trace_has_events_functional;\n          [done|done| apply trace_has_events_of_trace]. }\n      repeat f_equal. simpl in *.\n      assert (pre_expr eo = e1 ∧ post_expr eo = e2) as [? ?].\n      eapply event_in_the_middle; [done| | |done|].\n      { eapply val_head_stuck; done. }\n      { intros ?? ->; eapply head_ctx_step_val; done. }\n      { done. }\n      destruct eo; simplify_eq/=; done.\n    - pose proof (trace_ends_in_inj _ _ _ Hex Hei); simplify_eq.\n      exfalso; eapply HnEV; eauto.\n  Qed.\n\n  Lemma events_of_trace_extend_not_triggered ex tp1 tp2 K e1 e2 efs σ1 σ2 oζ:\n    valid_exec ex →\n    trace_ends_in ex (tp1 ++ fill K e1 :: tp2, σ1) →\n    head_step e1 σ1 e2 σ2 efs →\n    ¬ EV e1 σ1 e2 σ2 →\n    events_of_trace EV (ex :tr[oζ]: (tp1 ++ fill K e2 :: tp2 ++ efs, σ2)) =\n    events_of_trace EV ex.\n  Proof.\n    intros HexV Hex Hhstep HEV.\n    pose proof (trace_has_events_of_trace\n                  EV (ex :tr[oζ]: (tp1 ++ fill K e2 :: tp2 ++ efs, σ2))) as Hhasevs.\n    inversion Hhasevs as\n        [|??? tp1' tp2' efs' K' eo eobs ? Hei ? Heq1 ? Heq2 HEV' ? Heq3 Heq4|\n         ????? Hei HnEV Hhasevs']; simplify_eq/=.\n    - pose proof (trace_ends_in_inj _ _ _ Hex Hei); simplify_eq/=.\n      exfalso.\n      assert (pre_expr eo = e1 ∧ post_expr eo = e2) as [? ?].\n      eapply event_in_the_middle; [done| | |done|].\n      { eapply val_head_stuck; done. }\n      { intros ?? ->; eapply head_ctx_step_val; done. }\n      { done. }\n      destruct eo; simplify_eq/=; done.\n    - pose proof (trace_ends_in_inj _ _ _ Hex Hei); simplify_eq.\n      eapply trace_has_events_functional;\n        [done|done| apply trace_has_events_of_trace].\n  Qed.\n\nEnd properties.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/trillium/events/event.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23840864186153393}}
{"text": "From iris.algebra Require Import excl.\nFrom iris_ora.algebra Require Export ora.\nFrom iris.prelude Require Import options.\n\nSection excl.\nContext {A : ofe}.\n\nInstance excl_orderN : OraOrderN (excl A) := dist.\nInstance excl_order : OraOrder (excl A) := equiv.\n\nDefinition excl_ora_mixin : OraMixin (excl A).\nProof.\n  split; try apply _; try done.\n  - intros ???? Hv Ho.\n    by rewrite -Ho in Hv; apply exclusiveN_r in Hv.\n  - eauto.\n  - apply dist_S.\n  - by intros ???? ->.\n  - apply equiv_dist.\n  - inversion 1.\nQed.\n\nCanonical Structure exclR := Ora (excl A) excl_ora_mixin.\n\nEnd excl.\n", "meta": {"author": "mansky1", "repo": "ora", "sha": "1f6ee54b698e2486fd4b1dd62b816f9269b93615", "save_path": "github-repos/coq/mansky1-ora", "path": "github-repos/coq/mansky1-ora/ora-1f6ee54b698e2486fd4b1dd62b816f9269b93615/theories/algebra/excl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2384086418615339}}
{"text": "(* Copyright (c) 2012-2015, Robbert Krebbers. *)\n(* This file is distributed under the terms of the BSD license. *)\nRequire Export types integer_operations.\nLocal Open Scope ctype_scope.\nLocal Unset Elimination Schemes.\n\nClass Env (K : iType) : iType := {\n  env_type_env :> IntEnv K;\n  size_of : env K → type K → nat;\n  align_of : env K → type K → nat;\n  field_sizes : env K → list (type K) → list nat;\n  alloc_can_fail : bool\n}.\n\nArguments size_of _ _ _ _ : simpl never.\nArguments align_of _ _ _ _ : simpl never.\nArguments field_sizes _ _ _ _ : simpl never.\n\nDefinition ptr_size_of `{Env K} (Γ : env K) (τp : ptr_type K) : nat :=\n  match τp with TType τ => size_of Γ τ | _ => 1 end.\nDefinition offset_of `{Env K} (Γ : env K) (τs : list (type K))\n  (i : nat) : nat := sum_list $ take i $ field_sizes Γ τs.\nDefinition bit_size_of `{Env K} (Γ : env K)\n  (τ : type K) : nat := size_of Γ τ * char_bits.\nDefinition bit_align_of `{Env K} (Γ : env K)\n  (τ : type K) : nat := align_of Γ τ * char_bits.\nDefinition ptr_bit_size_of `{Env K} (Γ : env K) (τp : ptr_type K) : nat :=\n  match τp with TType τ => bit_size_of Γ τ | _ => char_bits end.\nDefinition field_bit_sizes `{Env K} (Γ : env K)\n    (τs : list (type K)) : list nat :=\n  (λ sz, sz * char_bits) <$> field_sizes Γ τs.\nDefinition field_bit_padding `{Env K}\n    (Γ : env K) (τs : list (type K)) : list nat :=\n  zip_with (λ sz τ, sz - bit_size_of Γ τ) (field_bit_sizes Γ τs) τs.\nDefinition bit_offset_of `{Env K}\n    (Γ : env K) (τs : list (type K)) (i : nat) : nat :=\n  sum_list $ take i $ field_bit_sizes Γ τs.\n\nClass EnvSpec (K : iType) `{Env K} := {\n  int_env_spec :> IntEnvSpec K;\n  size_of_ptr_ne_0 Γ τp : size_of Γ (τp.*) ≠ 0;\n  size_of_int Γ τi : size_of Γ (intT τi) = rank_size (rank τi);\n  size_of_void_ne_0 Γ : size_of Γ voidT ≠ 0;\n  size_of_array Γ τ n : size_of Γ (τ.[n]) = n * size_of Γ τ;\n  size_of_struct Γ t τs :\n    ✓ Γ → Γ !! t = Some τs →\n    size_of Γ (structT t) = sum_list (field_sizes Γ τs);\n  size_of_fields Γ τs :\n    ✓ Γ → Forall2 (λ τ sz, size_of Γ τ ≤ sz) τs (field_sizes Γ τs);\n  size_of_union Γ t τs :\n    ✓ Γ → Γ !! t = Some τs →\n    Forall (λ τ, size_of Γ τ ≤ size_of Γ (unionT t)) τs;\n  align_of_array Γ τ n : (align_of Γ τ | align_of Γ (τ.[n]));\n  align_of_compound Γ c t τs i τ :\n    ✓ Γ → Γ !! t = Some τs → τs !! i = Some τ →\n    (align_of Γ τ | align_of Γ (compoundT{c} t));\n  align_of_divide Γ τ :\n    ✓ Γ → ✓{Γ} τ → (align_of Γ τ | size_of Γ τ);\n  align_of_offset_of Γ τs i τ :\n    ✓ Γ → ✓{Γ}* τs → τs !! i = Some τ → (align_of Γ τ | offset_of Γ τs i);\n  size_of_weaken Γ1 Γ2 τ :\n    ✓ Γ1 → ✓{Γ1} τ → Γ1 ⊆ Γ2 → size_of Γ1 τ = size_of Γ2 τ;\n  align_of_weaken Γ1 Γ2 τ :\n    ✓ Γ1 → ✓{Γ1} τ → Γ1 ⊆ Γ2 → align_of Γ1 τ = align_of Γ2 τ;\n  fields_sizes_weaken Γ1 Γ2 τs :\n    ✓ Γ1 → ✓{Γ1}* τs → Γ1 ⊆ Γ2 → field_sizes Γ1 τs = field_sizes Γ2 τs\n}.\n\nSection env_spec.\nContext `{EnvSpec K}.\nImplicit Types τ σ : type K.\nImplicit Types τs σs : list (type K).\nImplicit Types Γ : env K.\n\nLemma size_of_char Γ si : size_of Γ (intT (IntType si char_rank)) = 1.\nProof. rewrite size_of_int. by apply rank_size_char. Qed.\nLemma field_sizes_length Γ τs : ✓ Γ → length (field_sizes Γ τs) = length τs.\nProof. symmetry. by eapply Forall2_length, size_of_fields. Qed.\nLemma field_sizes_nil Γ : ✓ Γ → field_sizes Γ [] = [].\nProof. intros. apply nil_length_inv. by rewrite field_sizes_length. Qed.\nLemma size_of_union_lookup Γ t τs i τ :\n  ✓ Γ → Γ !! t = Some τs → τs !! i = Some τ →\n  size_of Γ τ ≤ size_of Γ (unionT t).\nProof.\n  intros. assert (Forall (λ τ, size_of Γ τ ≤ size_of Γ (unionT t)) τs) as Hτs\n    by eauto using size_of_union; rewrite Forall_lookup in Hτs. eauto.\nQed.\nLemma size_of_struct_lookup Γ t τs i τ :\n  ✓ Γ → Γ !! t = Some τs → τs !! i = Some τ →\n  size_of Γ τ ≤ size_of Γ (structT t).\nProof.\n  intros HΓ Ht Hτs. erewrite size_of_struct by eauto. clear Ht. revert i Hτs.\n  induction (size_of_fields Γ τs HΓ) as [|σ sz σs szs]; intros [|?] ?;\n    simplify_equality'; auto with lia.\n  transitivity (sum_list szs); eauto with lia.\nQed.\nLemma size_of_union_singleton Γ t τ :\n  ✓ Γ → Γ !! t = Some [τ] → size_of Γ τ ≤ size_of Γ (unionT t).\nProof. intros. by apply (size_of_union_lookup Γ t [τ] 0). Qed.\nLemma sizes_of_weaken P Γ1 Γ2 τs :\n  ✓ Γ1 → ✓{Γ1}* τs → Γ1 ⊆ Γ2 →\n  Forall (λ τ', P (size_of Γ1 τ')) τs → Forall (λ τ', P (size_of Γ2 τ')) τs.\nProof.\n  induction 4; decompose_Forall_hyps; constructor; simpl;\n    erewrite <-1?size_of_weaken by eauto; eauto.\nQed.\n\nLemma bit_size_of_weaken Γ1 Γ2 τ :\n  ✓ Γ1 → ✓{Γ1} τ → Γ1 ⊆ Γ2 → bit_size_of Γ1 τ = bit_size_of Γ2 τ.\nProof. intros. unfold bit_size_of. f_equal. by apply size_of_weaken. Qed.\nLemma bit_size_of_int Γ τi : bit_size_of Γ (intT τi) = int_width τi.\nProof. unfold bit_size_of. by rewrite size_of_int. Qed.\nLemma bit_size_of_char Γ si :\n  bit_size_of Γ (intT (IntType si char_rank)) = char_bits.\nProof. rewrite bit_size_of_int. by apply int_width_char. Qed.\nLemma bit_size_of_int_same_kind Γ τi1 τi2 :\n  rank τi1 = rank τi2 → bit_size_of Γ (intT τi1) = bit_size_of Γ (intT τi2).\nProof.\n  destruct τi1, τi2; intros; simplify_equality'. by rewrite !bit_size_of_int.\nQed.\nLemma bit_size_of_array Γ τ n : bit_size_of Γ (τ.[n]) = n * bit_size_of Γ τ.\nProof. unfold bit_size_of. by rewrite !size_of_array, Nat.mul_assoc. Qed.\nLemma bit_size_of_struct Γ t τs :\n  ✓ Γ → Γ !! t = Some τs →\n  bit_size_of Γ (structT t) = sum_list (field_bit_sizes Γ τs).\nProof.\n  unfold bit_size_of, field_bit_sizes. intros.\n  erewrite size_of_struct by eauto.\n  induction (field_sizes Γ τs); csimpl; auto with lia.\nQed.\nLemma bit_size_of_fields Γ τs :\n  ✓ Γ → Forall2 (λ τ sz, bit_size_of Γ τ ≤ sz) τs (field_bit_sizes Γ τs).\nProof.\n  intros HΓ. unfold bit_size_of, field_bit_sizes.\n  induction (size_of_fields Γ τs HΓ);\n    simpl; constructor; auto using Nat.mul_le_mono_nonneg_r with lia.\nQed.\nLemma bit_size_of_union Γ t τs :\n  ✓ Γ → Γ !! t = Some τs →\n  Forall (λ τ, bit_size_of Γ τ ≤ bit_size_of Γ (unionT t)) τs.\nProof.\n  intros ? Hτs. apply size_of_union in Hτs; auto. unfold bit_size_of.\n  induction Hτs; constructor; auto using Nat.mul_le_mono_nonneg_r with lia.\nQed.\nLemma bit_size_of_union_lookup Γ t τs i τ :\n  ✓ Γ → Γ !! t = Some τs → τs !! i = Some τ →\n  bit_size_of Γ τ ≤ bit_size_of Γ (unionT t).\nProof.\n  intros. unfold bit_size_of. apply Nat.mul_le_mono_nonneg_r;\n    eauto using size_of_union_lookup with lia.\nQed.\nLemma bit_size_of_union_singleton Γ t τ :\n  ✓ Γ → Γ !! t = Some [τ] → bit_size_of Γ τ ≤ bit_size_of Γ (unionT t).\nProof. intros. by apply (bit_size_of_union_lookup Γ t [τ] 0). Qed.\nLemma ptr_bit_size_of_alt Γ τp :\n  ptr_bit_size_of Γ τp = ptr_size_of Γ τp * char_bits.\nProof. destruct τp; simpl; unfold bit_size_of; lia. Qed.\n\nLemma field_bit_sizes_weaken Γ1 Γ2 τs :\n  ✓ Γ1 → ✓{Γ1}* τs → Γ1 ⊆ Γ2 → field_bit_sizes Γ1 τs = field_bit_sizes Γ2 τs.\nProof. unfold field_bit_sizes. auto using fields_sizes_weaken with f_equal. Qed.\nLemma field_bit_sizes_length Γ τs :\n  ✓ Γ → length (field_bit_sizes Γ τs) = length τs.\nProof. symmetry. by eapply Forall2_length, bit_size_of_fields. Qed.\nLemma field_bit_sizes_nil Γ : ✓ Γ → field_bit_sizes Γ [] = [].\nProof. intros. apply nil_length_inv. by rewrite field_bit_sizes_length. Qed.\nLemma field_bit_padding_weaken Γ1 Γ2 τs :\n  ✓ Γ1 → ✓{Γ1}* τs → Γ1 ⊆ Γ2 →\n  field_bit_padding Γ1 τs = field_bit_padding Γ2 τs.\nProof.\n  intros HΓ1 Hτs ?. unfold field_bit_padding.\n  erewrite <-(field_bit_sizes_weaken Γ1 Γ2) by eauto.\n  induction (bit_size_of_fields _ τs HΓ1); decompose_Forall_hyps;\n    auto using bit_size_of_weaken with f_equal.\nQed.\nLemma field_bit_padding_length Γ τs :\n  ✓ Γ → length (field_bit_padding Γ τs) = length τs.\nProof.\n  intros. unfold field_bit_padding.\n  rewrite zip_with_length, field_bit_sizes_length by done; lia.\nQed.\nLemma bit_offset_of_weaken Γ1 Γ2 τs i :\n  ✓ Γ1 → ✓{Γ1}* τs → Γ1 ⊆ Γ2 →\n  bit_offset_of Γ1 τs i = bit_offset_of Γ2 τs i.\nProof.\n  unfold bit_offset_of. eauto using field_bit_sizes_weaken with f_equal.\nQed.\nLemma bit_offset_of_alt Γ τs i :\n  bit_offset_of Γ τs i = offset_of Γ τs i * char_bits.\nProof.\n  unfold bit_offset_of, offset_of, field_bit_sizes.\n  revert i. induction (field_sizes Γ τs) as [|?? IH];\n    intros [|i]; simpl; auto with lia.\n  by rewrite IH, Nat.mul_add_distr_r.\nQed.\nLemma bit_offset_of_lt Γ τs i j σ :\n  ✓ Γ → τs !! i = Some σ → i < j →\n  bit_offset_of Γ τs i + bit_size_of Γ σ ≤ bit_offset_of Γ τs j.\nProof.\n  intros HΓ. revert i j σ. unfold bit_offset_of.\n  induction (bit_size_of_fields _ τs HΓ) as [|τ sz τs szs ?? IH];\n    intros [|i] [|j] σ ??; simplify_equality'; try lia.\n  specialize (IH i j σ). intuition lia.\nQed.\nLemma bit_offset_of_size Γ t τs i σ :\n  ✓ Γ → Γ !! t = Some τs → τs !! i = Some σ →\n  bit_offset_of Γ τs i + bit_size_of Γ σ ≤ bit_size_of Γ (structT t).\nProof.\n  intros HΓ Ht. erewrite bit_size_of_struct by eauto; clear Ht.\n  revert i σ. unfold bit_offset_of. induction (bit_size_of_fields _ τs HΓ)\n    as [|τ sz τs szs ?? IH]; intros [|i] σ ?; simplify_equality'; [lia|].\n  specialize (IH i σ). intuition lia.\nQed.\n\nLemma align_of_char Γ si : ✓ Γ → align_of Γ (intT (IntType si char_rank)) = 1.\nProof.\n  intros. apply Nat.divide_1_r; rewrite <-(size_of_char Γ si).\n  apply align_of_divide; repeat constructor; auto.\nQed.\nLemma bit_align_of_array Γ τ n : (bit_align_of Γ τ | bit_align_of Γ (τ.[n])).\nProof. apply Nat.mul_divide_mono_r, align_of_array. Qed.\nLemma bit_align_of_compound Γ c t τs i τ :\n  ✓ Γ → Γ !! t = Some τs → τs !! i = Some τ →\n  (bit_align_of Γ τ | bit_align_of Γ (compoundT{c} t)).\nProof. eauto using Nat.mul_divide_mono_r, align_of_compound. Qed.\nLemma bit_align_of_divide Γ τ :\n  ✓ Γ → ✓{Γ} τ → (bit_align_of Γ τ | bit_size_of Γ τ).\nProof. eauto using Nat.mul_divide_mono_r, align_of_divide. Qed.\nLemma bit_align_of_offset_of Γ τs i τ :\n  ✓ Γ → ✓{Γ}* τs → τs !! i = Some τ →\n  (bit_align_of Γ τ | bit_offset_of Γ τs i).\nProof.\n  rewrite bit_offset_of_alt.\n  eauto using Nat.mul_divide_mono_r, align_of_offset_of.\nQed.\nLemma bit_align_of_weaken Γ1 Γ2 τ :\n  ✓ Γ1 → ✓{Γ1} τ → Γ1 ⊆ Γ2 → bit_align_of Γ1 τ = bit_align_of Γ2 τ.\nProof. unfold bit_align_of; auto using align_of_weaken, f_equal. Qed.\n\nLemma size_of_base_ne_0 Γ τb : size_of Γ (baseT τb) ≠ 0.\nProof.\n  destruct τb; auto using size_of_void_ne_0, size_of_ptr_ne_0.\n  rewrite size_of_int. apply rank_size_ne_0.\nQed.\nLemma bit_size_of_base_ne_0 Γ τb : bit_size_of Γ (baseT τb) ≠ 0.\nProof. apply Nat.neq_mul_0. auto using char_bits_ne_0, size_of_base_ne_0. Qed.\n#[global] Instance: ∀ Γ τb, PropHolds (size_of Γ (baseT τb) ≠ 0).\nProof. apply size_of_base_ne_0. Qed.\n#[global] Instance: ∀ Γ τb, PropHolds (bit_size_of Γ (baseT τb) ≠ 0).\nProof. apply bit_size_of_base_ne_0. Qed.\nLemma size_of_ne_0 Γ τ : ✓ Γ → ✓{Γ} τ → size_of Γ τ ≠ 0.\nProof.\n  intros HΓ. revert τ. refine (type_env_ind _ HΓ _ _ _ _).\n  * auto using size_of_base_ne_0.\n  * intros. rewrite size_of_array. by apply Nat.neq_mul_0.\n  * intros [] t τs Ht Hτs IH Hlen.\n    + erewrite size_of_struct by eauto. clear Ht.\n      destruct (size_of_fields Γ τs HΓ); decompose_Forall_hyps; auto with lia.\n    + apply size_of_union in Ht; auto.\n      destruct Ht; decompose_Forall_hyps; auto with lia.\nQed.\nLemma align_of_ne_0 Γ τ : ✓ Γ → ✓{Γ} τ → align_of Γ τ ≠ 0.\nProof. eauto using Nat_divide_ne_0, size_of_ne_0, align_of_divide. Qed.\nLemma size_of_pos Γ τ : ✓ Γ → ✓{Γ} τ → 0 < size_of Γ τ.\nProof. intros. by apply Nat.neq_0_lt_0, size_of_ne_0. Qed.\nLemma bit_size_of_ne_0 Γ τ : ✓ Γ → ✓{Γ} τ → bit_size_of Γ τ ≠ 0.\nProof. intros. apply Nat.neq_mul_0. auto using char_bits_ne_0,size_of_ne_0. Qed.\nLemma bit_size_of_pos Γ τ : ✓ Γ → ✓{Γ} τ → 0 < bit_size_of Γ τ.\nProof. intros. by apply Nat.neq_0_lt_0, bit_size_of_ne_0. Qed.\nEnd env_spec.\n", "meta": {"author": "robbertkrebbers", "repo": "ch2o", "sha": "1afb3f615db053b741341e9bfd1d5c65bddea641", "save_path": "github-repos/coq/robbertkrebbers-ch2o", "path": "github-repos/coq/robbertkrebbers-ch2o/ch2o-1afb3f615db053b741341e9bfd1d5c65bddea641/types/type_environment.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23840215410642027}}
{"text": "Require Export MicroBFTprops2.\n\n\nSection MicroBFTass_uniq.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext          }.\n  Context { microbft_context    : MicroBFT_context      }.\n  Context { m_initial_keys      : MicroBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys     }.\n  Context { usig_hash           : USIG_hash             }.\n  Context { microbft_auth       : MicroBFT_auth         }.\n\n\n  Lemma ASSUMPTION_disseminate_unique_true :\n    forall (eo : EventOrdering), assume_eo eo ASSUMPTION_disseminate_unique.\n  Proof.\n    introv h; simpl in *; exrepnd; subst; GC.\n    rewrite h0 in h1; ginv.\n\n    unfold disseminate_data in *; simpl in *.\n    unfold M_byz_output_sys_on_event in *; simpl in *.\n    rewrite M_byz_output_ls_on_event_as_run in h5, h6.\n    rewrite h0 in *; simpl in *.\n    unfold MicroBFTheader.node2name in *; simpl in *; subst.\n    unfold MicroBFTsys in *; simpl in *.\n\n    remember (M_byz_run_ls_before_event (MicroBFTlocalSys (loc e)) e) as ls; symmetry in Heqls.\n    apply M_byz_run_ls_before_event_ls_is_microbft in Heqls.\n    repndors; exrepnd; subst.\n\n    { rewrite h5 in *; ginv.\n      unfold M_byz_output_ls_on_this_one_event in h5.\n      unfold M_byz_run_ls_on_one_event in h5.\n      revert dependent o.\n      unfold data_is_in_out, event2out in *.\n      remember (trigger e) as trig; symmetry in Heqtrig.\n      destruct trig; simpl in *; ginv; tcsp; introv a run b.\n\n      { allrw in_flat_map; exrepnd.\n        unfold M_run_ls_on_input in *.\n        autorewrite with microbft in *.\n        Time microbft_dest_msg Case;\n          repeat (simpl in *; autorewrite with microbft in *; smash_microbft2);\n          try (complete (repndors; ginv; tcsp)). }\n\n      { unfold M_run_ls_on_trusted, M_run_ls_on_input in *; simpl in *.\n        destruct i, o; simpl in *; repndors; ginv; tcsp. } }\n\n    { rewrite h5 in *; ginv.\n      unfold M_byz_output_ls_on_this_one_event in h5.\n      unfold M_byz_run_ls_on_one_event in h5.\n      revert dependent o.\n      unfold data_is_in_out, event2out in *.\n      remember (trigger e) as trig; symmetry in Heqtrig.\n      destruct trig; simpl in *; ginv; tcsp; introv a run b.\n\n      unfold M_run_ls_on_trusted, M_run_ls_on_input in *; simpl in *.\n      autorewrite with microbft in *.\n      destruct i, o; simpl in *; repndors; ginv; tcsp. }\n  Qed.\n  Hint Resolve ASSUMPTION_disseminate_unique_true : microbft.\n\nEnd MicroBFTass_uniq.\n\n\nHint Resolve ASSUMPTION_disseminate_unique_true : microbft.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MicroBFTass_uniq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.23840215410642018}}
{"text": "Require Export CoqRecon.Mono.Mono.\n\n(** Completeness is never true :(. *)\n\nLemma tsub_twice : forall t s,\n    (s ‡ s) † t = s † s † t.\nProof.\n  intro t;\n    induction t as [| | t1 IHt1 t2 IHt2 | T];\n    intros s; simpl; try reflexivity.\n  - rewrite IHt1, IHt2. reflexivity.\n  - unfold \"‡\",env_map.\n    destruct (s T) as [t |] eqn:HeqT; simpl; auto.\n    rewrite HeqT. reflexivity.\nQed.\n\nLemma tsub_gamma_twice : forall (s : tenv) (g : gamma),\n    s ‡ s × g = s × s × g.\nProof.\n  intros s g. extensionality T.\n  unfold \"×\", env_map.\n  destruct (g T) as [tg |] eqn:Heqtg; auto.\n  f_equal. apply tsub_twice.\nQed.\n\nSection Complete.\n  Local Hint Resolve sound : core.\n  Local Hint Resolve preservation : core.\n  Local Hint Resolve Subset_perm_l : core.\n  Local Hint Resolve Subset_perm_r : core.\n  Local Hint Resolve union_perm : core.\n  Local Hint Constructors Permutation : core.\n\n  Lemma tvars_subset : forall Γ e τ X C,\n      Γ ⊢ e ∴ τ ⊣ X ≀ C -> (Ctvars C ⊆ X).\n  Proof.\n    intros g e t X C H; induction H;\n      simpl; try firstorder.\n    - apply Subset_perm_l\n        with (T :: tvars τ1 ∪ tvars τ2 ∪ Ctvars (C1 ∪ C2))%set.\n      + rewrite <- app_assoc with (m := [T]); simpl.\n        rewrite app_assoc.\n        apply Permutation_middle.\n      + apply Subset_cons. (** Dang. *) admit.\n    - (** Same problem. *) admit.\n    - (** Same problem. *) admit.\n  Abort.\n\n  (* Pierce's proof in TAPL relies upon this assumption. *)\n  Lemma tsub_inverse : forall t s,\n      exists t', s † t' = t /\\ forall n, n ∈ tvars t' -> s n = None.\n  Proof.\n    intros t s;\n      induction t as\n        [| | t1 [t1' [IHt1 IHs1]] t2 [t2' [IHt2 IHs2]] | m].\n    - exists TBool; intuition.\n    - exists TNat; intuition.\n    - exists (t1' → t2')%typ; simpl.\n      rewrite IHt1, IHt2.\n      split; [reflexivity |].\n      intros n H. rewrite in_app_iff in H.\n      intuition.\n    - destruct (env_binds m s) as [HNone | [t HSome]].\n      + exists (TVar m); simpl. rewrite HNone.\n        intuition; subst; assumption.\n      + (* Which is difficult to formally verify...*)\n  Abort.\n\n  (** I used Pierce's [CT-Abs-Inf] rule\n      in place of [CT-Abs].\n      It seems his form of completenss is impossible\n      with this... *)\n  Theorem complete_weak : forall Γ e t X C,\n      Γ ⊢ e ∴ t ⊣ X ≀ C ->\n      forall σ τ,\n        (σ × Γ) ⊨ e ∴ τ ->\n        (forall m, m ∈ X -> σ m = None) ->\n        exists σ', Forall (uncurry (satisfy σ')) C /\\\n              σ' † t = τ /\\ mask σ' X = σ.\n  Proof.\n    intros g e τ X C H; induction H;\n      intros s t Ht Hd; inv Ht;\n        try (exists s; intuition; assumption).\n    - exists s; intuition.\n      unfold bound,env_map in *.\n      rewrite H in H1. inv H1.\n      reflexivity.\n    - (* This case is intractable.\n         There is no way to use the induction hypothesis. *)\n      admit.\n    - apply IHconstraint_typing1 in H7 as IH1;\n        [clear IHconstraint_typing1 H7 | intuition].\n      apply IHconstraint_typing2 in H9 as IH2;\n        [clear IHconstraint_typing2 H9 | intuition].\n      destruct IH1 as [s1 [HC1 [Ht1 Hs1]]].\n      destruct IH2 as [s2 [HC2 [Ht2 Hs2]]].\n      assert (HX12: member T X1 = false /\\ member T X2 = false).\n      { repeat rewrite Not_In_member_iff; split;\n          intros ?; apply H2; repeat rewrite in_app_iff;\n            intuition. }\n      destruct HX12 as [HX1 HX2].\n      exists (fun Y =>\n           if Y == T then Some t else\n             if member Y X1 then s1 Y else\n               if member Y X2 then s2 Y else s Y).\n      repeat split.\n      + constructor; simpl.\n        * unfold satisfy; simpl.\n          dispatch_eqdec.\n          (* Need induction...probably...*) admit.\n        * rewrite Forall_app; split.\n          -- (* Need induction. *) admit.\n          -- (* Need induction. *) admit.\n      + simpl; dispatch_eqdec; reflexivity.\n      + extensionality Y; unfold \"∉\"; simpl.\n        destruct (equiv_dec Y T) as [HYT | HYT];\n          unfold equiv, complement in *; subst. admit. admit.\n    - apply IHconstraint_typing1 in H8 as IH1;\n        [ clear IHconstraint_typing1 H8 | intuition ].\n      apply IHconstraint_typing2 in H10 as IH2;\n        [ clear IHconstraint_typing2 H10 | intuition ].\n      apply IHconstraint_typing3 in H11 as IH3;\n        [ clear IHconstraint_typing3 H11 | intuition ].\n      destruct IH1 as [s1 [HC1 [Ht1 Hs1]]].\n      destruct IH2 as [s2 [HC2 [Ht2 Hs2]]].\n      destruct IH3 as [s3 [HC3 [Ht3 Hs3]]].\n      exists (fun Y =>\n           if member Y X1 then s1 Y else\n             if member Y X2 then s2 Y else\n               if member Y X3 then s3 Y else s Y).\n      repeat split.\n      + repeat constructor.\n        * unfold satisfy, uncurry; simpl.\n          (* Requires induction... *) admit.\n        * unfold satisfy, uncurry; simpl.\n          (* Requires induction... *) admit.\n        * repeat rewrite Forall_app; repeat split.\n          (* Requires induction...*) admit. admit. admit.\n      + (* Nope. *) admit.\n      + extensionality Y; unfold mask; simpl.\n        destruct (member Y (X1 ∪ X2 ∪ X3)%set) eqn:HYmem.\n        * symmetry; apply Hd; auto using member_In.\n        * assert (HY123:\n                    member Y X1 = false /\\\n                    member Y X2 = false /\\\n                    member Y X3 = false).\n          { repeat rewrite Not_In_member_iff in *.\n            repeat rewrite in_app_iff in HYmem.\n            intuition. }\n          destruct HY123 as [HY1 [HY2 HY3]].\n          rewrite HY1,HY2,HY3. reflexivity.\n      + apply Hd;\n          repeat rewrite in_app_iff;\n          intuition.\n      + apply Hd;\n          repeat rewrite in_app_iff;\n          intuition.\n    - (* Same stuff... *)\n  Abort.\nEnd Complete.\n", "meta": {"author": "rudynicolop", "repo": "Type-Reconstruction", "sha": "c2455ced75254a40846d6b28992761480f277ab8", "save_path": "github-repos/coq/rudynicolop-Type-Reconstruction", "path": "github-repos/coq/rudynicolop-Type-Reconstruction/Type-Reconstruction-c2455ced75254a40846d6b28992761480f277ab8/vtr/coq/lib/Mono/Completeness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.23840215410642018}}
{"text": "(* Order of imports: import proofmode after utils after robinson *)\nFrom FOL Require Import FullSyntax Arithmetics.\n\nFrom FOL.Incompleteness Require Import utils fol_utils.\nFrom FOL.Proofmode Require Import Theories ProofMode.\n\nRequire Import Lia.\nRequire Import String.\n\n\nOpen Scope string_scope.\n\n(* ** Q-decidability *)\nSection Qdec.\n  Existing Instance PA_preds_signature.\n  Existing Instance PA_funcs_signature.\n\n  Definition Qdec φ := forall (pei : peirce) ρ, (forall k, bounded_t 0 (ρ k)) -> Qeq ⊢ φ[ρ] \\/ Qeq ⊢ ¬φ[ρ].\n\n  Lemma subst_t_closed t ρ : (forall k, bounded_t 0 (ρ k)) -> bounded_t 0 t`[ρ].\n  Proof.\n    intros H. destruct (find_bounded_t t) as [n Hn].\n    eapply subst_bounded_max_t; last eassumption.\n    intros l _. apply H.\n  Qed.\n  Lemma subst_closed φ ρ : (forall k, bounded_t 0 (ρ k)) -> bounded 0 φ[ρ].\n  Proof.\n    intros H. destruct (find_bounded φ) as [n Hn].\n    eapply subst_bounded_max; last eassumption.\n    intros l _. apply H.\n  Qed.\n\n  Lemma Qdec_subst φ ρ : Qdec φ -> Qdec φ[ρ].\n  Proof.\n    intros H pei ρ' Hb. rewrite subst_comp. apply H.\n    intros k. apply subst_t_closed, Hb.\n  Qed.\n\n  Lemma Qdec_iff φ ψ : Qeq ⊢I φ ↔ ψ -> Qdec φ -> Qdec ψ.\n  Proof.\n    intros H Hφ pei ρ Hρ. apply prv_intu_peirce in H.\n    pose proof (subst_Weak ρ H) as Hiff. cbn in Hiff. change (List.map _ _) with Qeq in Hiff.\n    destruct (Hφ pei ρ Hρ) as [H1|H1].\n    - left. fapply Hiff. fapply H1.\n    - right. fintros. fapply H1. fapply Hiff. ctx.\n  Qed.\n  Lemma Qdec_iff' φ ψ : \n    (forall ρ, (forall k, bounded_t 0 (ρ k)) -> Qeq ⊢I φ[ρ] ↔ ψ[ρ]) -> \n    Qdec φ -> Qdec ψ.\n  Proof.\n    intros H Hφ pei ρ Hρ. \n    specialize (H _ Hρ). apply prv_intu_peirce in H.\n    destruct (Hφ _ _ Hρ) as [H1|H1].\n    - left. fapply H. fapply H1.\n    - right. fintros. fapply H1. fapply H. ctx.\n  Qed.\n\n  Lemma Qdec_bot : Qdec ⊥.\n  Proof.\n    intros ρ Hb. right. fintros. ctx.\n  Qed.\n\n  Lemma Qdec_and φ ψ : Qdec φ -> Qdec ψ -> Qdec (φ ∧ ψ).\n  Proof. \n    intros Hφ Hψ pei ρ Hb. cbn.\n    destruct (Hφ _ _ Hb) as [H1|H1], (Hψ _ _ Hb) as [H2|H2].\n    2-4: right; fintros; fdestruct 0.\n    - left. now fsplit.\n    - fapply H2. ctx.\n    - fapply H1. ctx.\n    - fapply H1. ctx.\n  Qed.\n\n  Lemma Qdec_or φ ψ : Qdec φ -> Qdec ψ -> Qdec (φ ∨ ψ).\n  Proof. \n    intros Hφ Hψ ρ pei Hb. cbn.\n    destruct (Hφ _ _ Hb) as [H1|H1], (Hψ _ _ Hb) as [H2|H2].\n    1-3: left; now (fleft + fright).\n    right. fintros \"[H|H]\".\n    - fapply H1. ctx.\n    - fapply H2. ctx.\n  Qed.\n\n  Lemma Qdec_impl φ ψ : Qdec φ -> Qdec ψ -> Qdec (φ → ψ). \n  Proof.\n    intros Hφ Hψ pei ρ Hb. cbn.\n    destruct (Hφ _ _ Hb) as [H1|H1], (Hψ _ _ Hb) as [H2|H2].\n    - left. fintros. fapply H2.\n    - right. fintros. fapply H2. fapply 0. fapply H1.\n    - left. fintros. fapply H2.\n    - left. fintros. fexfalso. fapply H1. ctx.\n  Qed.\n  \n  Lemma Qdec_eq t s : Qdec (t == s).\n  Proof.\n    intros pei ρ Hb. cbn. \n    destruct (@closed_term_is_num _ t`[ρ]) as [k1 Hk1].\n    { apply subst_t_closed, Hb. }\n    destruct (@closed_term_is_num _ s`[ρ]) as [k2 Hk2].\n    { apply subst_t_closed, Hb. }\n    assert (k1 = k2 \\/ k1 <> k2) as [->|Hk] by lia; [left|right].\n    all: frewrite Hk1; frewrite Hk2.\n    - fapply ax_refl.\n    - clear Hk1. clear Hk2. revert Hk. induction k1 in k2 |-*; intros Hk.\n      + destruct k2; first congruence. cbn.\n        fapply ax_zero_succ.\n      + cbn. destruct k2.\n        * fintros. fapply (ax_zero_succ (num k1)). fapply ax_sym. ctx.\n        * cbn. fintros. assert (H' : k1 <> k2) by congruence.\n          specialize (IHk1 k2 H'). fapply IHk1.\n          fapply ax_succ_inj. ctx.\n  Qed.\n  Lemma Qdec_le t s : Qdec (t ⧀= s).\n  Proof.\n    intros pei ρ Hb.\n    destruct (@closed_term_is_num _ t`[ρ]) as [k1 Hk1].\n    { apply subst_t_closed, Hb. }\n    destruct (@closed_term_is_num _ s`[ρ]) as [k2 Hk2].\n    { apply subst_t_closed, Hb. }\n    rewrite PAle_subst.\n    enough (Qeq ⊢ num k1 ⧀= num k2 \\/ Qeq ⊢ ¬(num k1 ⧀= num k2)) as [H|H].\n    { left. unfold PAle. frewrite Hk1. frewrite Hk2. apply H. }\n    { right. unfold PAle. frewrite Hk1. frewrite Hk2. apply H. }\n    clear Hk1 Hk2.\n    induction k1 as [|k1 IH] in k2 |-*.\n    - left. fexists (num k2).\n      frewrite (ax_add_zero (num k2)). fapply ax_refl.\n    - destruct k2 as [|k2].\n      + right.\n        fstart. fintros \"[z H]\". fapply (ax_zero_succ (num k1 ⊕ z)).\n        frewrite <-(ax_add_rec z (num k1)). fapply \"H\".\n      + destruct (IH k2) as [IH'|IH'].\n        * left. fstart.\n          fassert (num k1 ⧀= num k2) as \"H\"; first apply IH'.\n          fdestruct \"H\" as \"[z Hz]\".\n          fexists z. frewrite (ax_add_rec z (num k1)).\n          fapply ax_succ_congr. fapply \"Hz\".\n        * right. fstart. fintros \"H\". fapply IH'.\n          fdestruct \"H\" as \"[z Hz]\".\n          fexists z. fapply ax_succ_inj.\n          frewrite <-(ax_add_rec z (num k1)). fapply \"Hz\".\n  Qed.\n\n  Section lemmas.\n    Context `{pei : peirce}.\n\n    Lemma Qsdec_le x y : bounded_t 0 x -> Qeq ⊢ ((x ⧀= y) ∨ (y ⧀= x)).\n    Proof.\n      intros Hx. destruct (closed_term_is_num Hx) as [k Hk].\n      unfold PAle. frewrite Hk. clear Hk.\n      induction k as [|k IH] in y |-*; fstart.\n      - fleft. fexists y. frewrite (ax_add_zero y). fapply ax_refl.\n      - fassert (ax_cases); first ctx.\n        fdestruct (\"H\" y) as \"[H|[y' H]]\".\n        + fright. fexists (σ (num k)). \n          frewrite \"H\". frewrite (ax_add_zero (σ num k)).\n          fapply ax_refl.\n        + specialize (IH y'). \n          fdestruct IH.\n          * fleft. \n            fdestruct \"H0\". fexists x0. frewrite \"H\". frewrite \"H0\".\n            fapply ax_sym. fapply ax_add_rec.\n          * fright. custom_simpl.\n            fdestruct \"H0\". fexists x0. frewrite \"H\". frewrite \"H0\".\n            fapply ax_sym. fapply ax_add_rec.\n    Qed.\n    Lemma Q_eqdec t x : Qeq ⊢ x == (num t) ∨ ¬(x == num t).\n    Proof. \n      induction t in x |-*; fstart; fintros.\n      - fassert (ax_cases); first ctx.\n        fdestruct (\"H\" x).\n        + fleft. frewrite \"H\".\n          fapply ax_refl.\n        + fright. fdestruct \"H\". frewrite \"H\".\n          fintros. fapply (ax_zero_succ x0).\n          fapply ax_sym. ctx.\n      - fassert (ax_cases); first ctx.\n        fdestruct (\"H\" x).\n        + fright. frewrite \"H\".\n          fapply ax_zero_succ.\n        + fdestruct \"H\". frewrite \"H\".\n          specialize (IHt x0). \n          fdestruct IHt.\n          * fleft. fapply ax_succ_congr. fapply \"H0\".\n          * fright. fintros. fapply \"H0\".\n            fapply ax_succ_inj. fapply \"H1\".\n    Qed.\n\n    Lemma PAle_zero_eq x : Qeq ⊢ x ⧀= zero → x == zero.\n    Proof.\n      fstart. fintros. unfold PAle. fdestruct \"H\".\n      fassert ax_cases.\n      { ctx. }\n      unfold ax_cases.\n      fdestruct (\"H0\" x).\n      - fapply \"H0\".\n      - fdestruct \"H0\".\n        fexfalso. fapply (ax_zero_succ (x1 ⊕ x0)).\n        frewrite <- (ax_add_rec x0 x1). frewrite <- \"H0\".\n        fapply \"H\".\n    Qed.\n    Lemma PAle'_zero_eq x : Qeq ⊢ (x ⧀=' zero) → x == zero.\n    Proof.\n      fstart. fintros. unfold PAle'. fdestruct \"H\".\n      fassert ax_cases as \"C\"; first ctx.\n      fdestruct (\"C\" x0) as \"[Hx'|[x' Hx']]\".\n      - frewrite <-(ax_add_zero x). frewrite <-\"Hx'\".\n        frewrite <-\"H\". frewrite \"Hx'\". fapply ax_refl.\n      - fexfalso. fapply (ax_zero_succ (x' ⊕ x)).\n        frewrite <-(ax_add_rec x x'). frewrite <-\"Hx'\".\n        fapply \"H\".\n    Qed.\n\n    Lemma add_zero_swap t x :\n      Qeq ⊢ x ⊕ zero == num t → x == num t.\n    Proof.\n      fstart. induction t in x |-*; fintros.\n      - fassert (ax_cases); first ctx.\n        fdestruct (\"H0\" x).\n        + ctx.\n        + fdestruct \"H0\".\n          fexfalso. fapply (ax_zero_succ (x0 ⊕ zero)).\n          frewrite <- (ax_add_rec zero x0). \n          frewrite <-\"H0\". fapply ax_sym. ctx.\n      - fassert (ax_cases); first ctx.\n        fdestruct (\"H0\" x).\n        + fexfalso. fapply (ax_zero_succ (num t)).\n          frewrite <-\"H\". frewrite \"H0\".\n          frewrite (ax_add_zero zero).\n          fapply ax_refl.\n        + fdestruct \"H0\".\n          frewrite \"H0\". fapply ax_succ_congr.\n          specialize (IHt x0). \n          fapply IHt. fapply ax_succ_inj.\n          frewrite <-(ax_add_rec zero x0).\n          frewrite <- \"H0\". fapply \"H\".\n    Qed.\n\n    Lemma add_rec_swap t x y:\n      Qeq ⊢ x ⊕ σ y == σ num t → x ⊕ y == num t.\n    Proof. \n      induction t in x |-*; fstart; fintros \"H\".\n      - fassert ax_cases as \"C\"; first ctx.\n        fdestruct (\"C\" x) as \"[Hx|[x' Hx']]\".\n        + frewrite \"Hx\". frewrite (ax_add_zero y).\n          fapply ax_succ_inj. frewrite <-(ax_add_zero (σ y)).\n          frewrite <-\"H\". frewrite \"Hx\". fapply ax_refl.\n        + frewrite \"Hx'\". fassert ax_cases as \"C\"; first ctx.\n          fdestruct (\"C\" x') as \"[Hx''|[x'' Hx'']]\".\n          * fexfalso. fapply (ax_zero_succ y). \n            fapply ax_succ_inj. frewrite <-\"H\".\n            frewrite \"Hx'\". frewrite \"Hx''\".\n            frewrite (ax_add_rec (σ y) zero). frewrite (ax_add_zero (σ y)).\n            fapply ax_refl.\n          * fexfalso. fapply (ax_zero_succ (x'' ⊕ σ y)). \n            fapply ax_succ_inj. frewrite <-\"H\".\n            frewrite \"Hx'\". frewrite \"Hx''\".\n            frewrite (ax_add_rec (σ y) (σ x'')).\n            frewrite (ax_add_rec (σ y) x''). fapply ax_refl.\n      - fassert ax_cases as \"C\"; first ctx.\n        fdestruct (\"C\" x) as \"[Hx'|[x' Hx']]\".\n        + fapply ax_succ_inj. frewrite <-\"H\".\n          frewrite \"Hx'\". frewrite (ax_add_zero y).\n          frewrite (ax_add_zero (σ y)). fapply ax_refl.\n        + frewrite \"Hx'\". frewrite (ax_add_rec y x').\n          fapply ax_succ_congr. \n          specialize (IHt x'). fapply IHt.\n          fapply ax_succ_inj. frewrite <-(ax_add_rec (σ y) x').\n          frewrite <-\"Hx'\". ctx.\n    Qed.\n\n    Lemma PAle_sigma_neq t x : Qeq ⊢ (x ⧀= σ(num t)) → ¬(x == σ(num t)) → x ⧀= num t.\n    Proof. \n      fstart. fintros. unfold PAle. fdestruct \"H\". custom_simpl.\n      fassert (ax_cases); first ctx.\n      fdestruct (\"H1\" x0).\n      - fexfalso. fapply \"H0\". \n        pose proof (add_zero_swap (S t) x). cbn in H.\n        fapply H. frewrite <- \"H1\". fapply ax_sym.\n        ctx.\n      - fdestruct \"H1\". fexists x1. custom_simpl.\n        fapply ax_sym. fapply add_rec_swap.\n        frewrite <-\"H1\". fapply ax_sym. fapply \"H\".\n    Qed. \n    Lemma PAle'_sigma_neq t x : Qeq ⊢ (x ⧀=' σ(num t)) → ¬(x == σ(num t)) → x ⧀=' num t.\n    Proof. \n      fstart. fintros. unfold PAle'.\n      fdestruct \"H\" as \"[z Hz]\".\n      fassert ax_cases as \"C\"; first ctx.\n      fdestruct (\"C\" z) as \"[Hz'|[z' Hz']]\".\n      - fexfalso. fapply \"H0\". frewrite \"Hz\". frewrite \"Hz'\".\n        fapply ax_sym. fapply ax_add_zero.\n      - fexists z'. fapply ax_succ_inj.\n        frewrite <-(ax_add_rec x z').\n        frewrite <-\"Hz'\". ctx.\n    Qed. \n\n    Lemma add_rec_swap2 t x y :\n      Qeq ⊢ x ⊕ y == num t → x ⊕ (σ y) == num (S t).\n    Proof.\n      induction t in x |-*; fstart; fintros \"H\".\n      - fassert ax_cases as \"C\"; first ctx. \n        fdestruct (\"C\" x) as \"[Hx'|[x' Hx']]\".\n        + frewrite <-\"H\". frewrite \"Hx'\". \n          frewrite (ax_add_zero (σ y)). frewrite (ax_add_zero y).\n          fapply ax_refl.\n        + fexfalso. fapply (ax_zero_succ (x' ⊕ y)). frewrite <-\"H\".\n          frewrite \"Hx'\". frewrite (ax_add_rec y x'). fapply ax_refl.\n      - fassert ax_cases as \"C\"; first ctx. \n        fdestruct (\"C\" x) as \"[Hx'|[x' Hx']]\".\n        + frewrite <-\"H\". frewrite \"Hx'\".\n          frewrite (ax_add_zero (σ y)). frewrite (ax_add_zero y).\n          fapply ax_refl.\n        + frewrite \"Hx'\". frewrite (ax_add_rec (σ y) x').\n          fapply ax_succ_congr.\n          fapply IHt. fapply ax_succ_inj.\n          frewrite <-(ax_add_rec y x'). frewrite <-\"Hx'\".\n          fapply \"H\".\n    Qed.\n\n    Lemma PAle_succ t x : Qeq ⊢ (x ⧀= num t) → (x ⧀= σ (num t)).\n    Proof. \n      fstart. fintros \"[z Hz]\". fexists (σ z).\n      fapply ax_sym. fapply add_rec_swap2. fapply ax_sym. fapply \"Hz\".\n    Qed.\n    Lemma PAle'_succ t x : Qeq ⊢ (x ⧀=' num t) → (x ⧀=' σ (num t)).\n    Proof. \n      fstart. fintros \"[z Hz]\". fexists (σ z).\n      frewrite (ax_add_rec x z). fapply ax_succ_congr. ctx.\n    Qed.\n\n    Lemma add_zero_num t :\n      Qeq ⊢ num t ⊕ zero == num t.\n    Proof.\n      induction t.\n      - cbn. frewrite (ax_add_zero zero). fapply ax_refl.\n      - cbn. frewrite (ax_add_rec zero (num t)).\n        fapply ax_succ_congr. apply IHt.\n    Qed.\n    Lemma PAle_num_eq t x :\n      Qeq ⊢ x == num t → x ⧀= num t.\n    Proof.\n      fstart. fintros \"H\". fexists zero.\n      frewrite \"H\". fapply ax_sym. fapply add_zero_num.\n    Qed.\n    Lemma PAle'_num_eq t x :\n      Qeq ⊢ x == num t → x ⧀=' num t.\n    Proof.\n      fstart. fintros \"H\". fexists zero.\n      frewrite (ax_add_zero x). fapply ax_sym. fapply \"H\".\n    Qed.\n\n\n    Fixpoint fin_disj n φ := match n with\n                             | 0 => φ[(num 0) ..]\n                             | S n => (fin_disj n φ) ∨ φ[(num (S n)) ..]\n                             end.\n    Fixpoint fin_conj n φ := match n with\n                             | 0 => φ[(num 0) ..]\n                             | S n => (fin_conj n φ) ∧ φ[(num (S n)) ..]\n                             end.\n\n\n\n    Lemma le_fin_disj t x :\n      Qeq ⊢ x ⧀= num t ↔ fin_disj t (x`[↑] == $0).\n    Proof.\n      induction t; cbn; rewrite subst_term_shift; fstart; fsplit.\n      - fapply PAle_zero_eq.\n      - fintros \"H\". unfold PAle. \n        frewrite \"H\". fexists zero.\n        frewrite (ax_add_zero zero). fapply ax_refl.\n      - fintros \"H\". fassert (x == σ num t ∨ (¬ x == σ num t)) as \"H1\".\n        { pose proof (Q_eqdec (S t) x). cbn in H. fapply H. }\n        fdestruct \"H1\" as \"[H1|H1]\".\n        + fright. ctx.\n        + fleft. fapply IHt. \n          fapply PAle_sigma_neq; ctx.\n      - fintros \"H\". fdestruct \"H\" as \"[H|H]\".\n        + fapply PAle_succ. fapply IHt. fapply \"H\".\n        + pose proof (PAle_num_eq (S t) x). cbn in H.\n          fapply H. fapply \"H\".\n    Qed.\n    Lemma le_swap_fin_disj t x :\n      Qeq ⊢ x ⧀=' num t ↔ fin_disj t (x`[↑] == $0).\n    Proof.\n      induction t; cbn; rewrite subst_term_shift; fstart; fsplit.\n      - fapply PAle'_zero_eq.\n      - unfold PAle'.  fintros \"H\". frewrite \"H\".\n        fexists zero. frewrite (ax_add_zero zero). fapply ax_refl.\n      - fintros \"H\". fassert (x == σ num t ∨ (¬ x == σ num t)) as \"H1\".\n        { pose proof (Q_eqdec (S t) x). cbn in H. fapply H. }\n        fdestruct \"H1\" as \"[H1|H1]\".\n        + fright. ctx.\n        + fleft. fapply IHt. \n          fapply PAle'_sigma_neq; ctx.\n      - fintros \"H\". fdestruct \"H\" as \"[H|H]\".\n        + fapply PAle'_succ. fapply IHt. fapply \"H\".\n        + pose proof (PAle'_num_eq (S t) x). cbn in H.\n          fapply H. fapply \"H\".\n    Qed.\n\n    Lemma Q_leibniz_t a x y : Qeq ⊢ x == y → a`[x..] == a`[y..].\n    Proof.\n      induction a.\n      - destruct x0; cbn.\n        + fintros. ctx.\n        + fintros. fapply ax_refl.\n      - destruct F.\n        + cbn in v. rewrite (vec_0_nil v).\n          fintros. fapply ax_refl.\n        + cbn in v. \n          destruct (vec_1_inv v) as [z ->]. cbn.\n          fintros. fapply (ax_succ_congr z`[y..] z`[x..]).\n          frevert 0. fapply IH. apply Vector.In_cons_hd.\n        + destruct (vec_2_inv v) as (a & b & ->).\n          cbn. fintros. fapply ax_add_congr.\n          all: frevert 0; fapply IH.\n          * apply Vector.In_cons_hd.\n          * apply Vector.In_cons_tl, Vector.In_cons_hd.\n        + destruct (vec_2_inv v) as (a & b & ->).\n          cbn. fintros. fapply ax_mult_congr.\n          all: frevert 0; fapply IH.\n          * apply Vector.In_cons_hd.\n          * apply Vector.In_cons_tl, Vector.In_cons_hd.\n    Qed.\n\n    Lemma Q_leibniz φ x y : \n      Qeq ⊢ x == y → φ[x..] → φ[y..].\n    Proof. \n      enough (Qeq ⊢ x == y → φ[x..] ↔ φ[y..]).\n      { fintros. fapply H; ctx. }\n      induction φ using form_ind_subst.\n      - cbn. fintros. fsplit; fintros; ctx. \n      - destruct P0. cbn in t. \n        destruct (vec_2_inv t) as (a & b & ->).\n        cbn. fstart. fintros.\n        fassert (a`[x..] == a`[y..]).\n        { pose proof (Q_leibniz_t a x y).\n          fapply H. fapply \"H\". }\n        fassert (b`[x..] == b`[y..]).\n        { pose proof (Q_leibniz_t b x y).\n          fapply H. fapply \"H\". }\n        frewrite \"H0\". frewrite \"H1\".\n        fsplit; fintros; ctx.\n      - fstart; fintros.\n        fassert (φ1[x..] ↔ φ1[y..]) by (fapply IHφ1; fapply \"H\").\n        fassert (φ2[x..] ↔ φ2[y..]) by (fapply IHφ2; fapply \"H\").\n        destruct b0; fsplit; cbn.\n        + fintros \"[H2 H3]\". fsplit.\n          * fapply \"H0\". ctx.\n          * fapply \"H1\". ctx.\n        + fintros \"[H2 H3]\". fsplit.\n          * fapply \"H0\". ctx.\n          * fapply \"H1\". ctx.\n        + fintros \"[H2|H3]\".\n          * fleft. fapply \"H0\". ctx.\n          * fright. fapply \"H1\". ctx.\n        + fintros \"[H2|H3]\".\n          * fleft. fapply \"H0\". ctx.\n          * fright. fapply \"H1\". ctx.\n        + fintros \"H2\" \"H3\". \n          fapply \"H1\". fapply \"H2\". fapply \"H0\". ctx.\n        + fintros \"H2\" \"H3\". \n          fapply \"H1\". fapply \"H2\". fapply \"H0\". ctx.\n      - fstart. fintros. fsplit; destruct q; cbn; fintros.\n        + specialize (H (x0`[↑]..)). \n          asimpl in H. asimpl. fapply H.\n          * ctx.\n          * fspecialize (\"H0\" x0). asimpl. ctx.\n        + fdestruct \"H0\". fexists x0.\n          specialize (H (x0`[↑]..)).\n          asimpl in H. asimpl. fapply H; ctx.\n        + specialize (H (x0`[↑]..)). \n          asimpl in H. asimpl. fapply H.\n          * ctx.\n          * fspecialize (\"H0\" x0). asimpl. ctx.\n        + fdestruct \"H0\". fexists x0.\n          specialize (H (x0`[↑]..)).\n          asimpl in H. asimpl. fapply H; ctx.\n    Qed.\n\n    (* Could probably be generalised to arbitrary finite disjunctions *)\n    Lemma forall_fin_disj_conj φ t :\n      Qeq ⊢ (∀ (fin_disj t ($1 == $0)) → φ) ↔ fin_conj t φ.\n    Proof.\n      induction t as [|t IH]; cbn; fstart; fsplit.\n      - fintros \"H\". fapply \"H\". fapply ax_refl.\n      - fintros \"H\" x \"H1\". \n        feapply Q_leibniz.\n        + feapply ax_sym. fapply \"H1\".\n        + ctx.\n      - fintros \"H\". fsplit.\n        + fapply IH. fintros x \"H1\". fapply \"H\". fleft. fapply \"H1\".\n        + fapply \"H\". fright. rewrite num_subst. fapply ax_refl.\n      - fintros \"[H1 H2]\" x \"[H3|H3]\".\n        + fdestruct IH as \"[H4 H5]\".\n          fapply \"H5\"; ctx.\n        + rewrite num_subst. feapply Q_leibniz.\n          * feapply ax_sym. fapply \"H3\".\n          * fapply \"H2\".\n    Qed.\n\n    Lemma exists_fin_disj φ t :\n      Qeq ⊢ (∃ (fin_disj t ($1 == $0)) ∧ φ) ↔ fin_disj t φ.\n    Proof.\n      induction t as [|t IH]; cbn; fstart; fsplit.\n      - fintros \"[x [H1 H2]]\". feapply Q_leibniz.\n        + fapply \"H1\".\n        + ctx.\n      - fintros \"H\". fexists zero. fsplit.\n        + fapply ax_refl.\n        + ctx.\n      - fintros \"[x [[H1|H1] H2]]\".\n        + fleft. fapply IH. fexists x. fsplit.\n          * fapply \"H1\".\n          * fapply \"H2\".\n        + fright. rewrite num_subst. feapply Q_leibniz.\n          * fapply \"H1\".\n          * ctx.\n      - fintros \"[H1|H1]\".\n        + fapply IH in \"H1\". fdestruct \"H1\" as \"[x [H1 H2]]\".\n          fexists x. fsplit.\n          * fleft. ctx.\n          * ctx.\n        + fexists (σ num t). fsplit.\n          * fright. rewrite num_subst. fapply ax_refl.\n          * ctx.\n    Qed.\n\n    Lemma forall_bound_iff φ ψ χ:\n      Qeq ⊢ φ ↔ ψ -> Qeq ⊢ (∀ φ → χ) ↔ (∀ ψ → χ).\n    Proof.\n      intros H. fstart. fsplit.\n      - fintros \"H1\" x \"H2\". fapply \"H1\". \n        apply (subst_Weak x..) in H. change (List.map _ _) with Qeq in H. \n        cbn in H. fapply H. fapply \"H2\".\n      - fintros \"H1\" x \"H2\". fapply \"H1\". \n        apply (subst_Weak x..) in H. change (List.map _ _) with Qeq in H. \n        cbn in H. fapply H. fapply \"H2\".\n    Qed.\n\n  End lemmas.\n\n\n  Lemma Qdec_fin_conj φ t :\n    Qdec φ -> Qdec (fin_conj t φ).\n  Proof.\n    intros Hφ. induction t; cbn.\n    - apply Qdec_subst, Hφ.\n    - apply Qdec_and.\n      + assumption.\n      + apply Qdec_subst, Hφ.\n  Qed.\n\n  Lemma Qdec_fin_disj φ t :\n    Qdec φ -> Qdec (fin_disj t φ).\n  Proof.\n    intros Hφ. induction t; cbn.\n    - apply Qdec_subst, Hφ.\n    - apply Qdec_or.\n      + assumption.\n      + apply Qdec_subst, Hφ.\n  Qed.\n  Lemma fin_disj_subst n φ ρ :\n    (fin_disj n φ)[ρ] = fin_disj n φ[up ρ].\n  Proof.\n    induction n; cbn.\n    - now asimpl.\n    - cbn. f_equal; first assumption.\n      asimpl. now rewrite num_subst.\n  Qed.\n\n  Theorem Qdec_bounded_forall t φ :\n    Qdec φ -> Qdec (∀ $0 ⧀= t`[↑] → φ).\n  Proof.\n    intros H pei ρ Hρ.\n    destruct (@closed_term_is_num _ t`[ρ]) as [x Hx].\n    { apply subst_t_closed, Hρ. }\n    enough (Qeq ⊢ (∀ (fin_disj x ($1 == $0))  → φ)[ρ] \\/ Qeq ⊢ ¬ (∀ (fin_disj x ($1 == $0)) → φ)[ρ]) as H'.\n    { cbn. asimpl. rewrite <-!subst_term_comp.\n      cbn in H'. rewrite fin_disj_subst in H'. \n      cbn in H'. unfold \"↑\" in H'.\n      destruct H' as [H1|H1].\n      - left. fstart. fintros. fapply H1. \n        rewrite fin_disj_subst. cbn.\n        fapply le_fin_disj. \n        fdestruct \"H\" as \"[z H]\". fexists z.\n        fassert (t`[ρ] == num x); first fapply Hx.\n        frewrite <-\"H0\". asimpl. fapply \"H\".\n      - right.  fstart. fintros. fapply H1. fstop.\n        fintros. fstart.\n        fapply \"H\".\n        rewrite fin_disj_subst. cbn.\n        fassert (x0 ⧀= num x).\n        { fapply le_fin_disj. fapply \"H0\". }\n        fdestruct \"H1\" as \"[z Hz]\".\n        fexists z. \n        fassert (t`[ρ] == num x); first fapply Hx.\n        asimpl. frewrite \"H1\". fapply \"Hz\". }\n    eapply Qdec_iff.\n    - apply frewrite_equiv_switch. apply forall_fin_disj_conj.\n    - apply Qdec_fin_conj, H.\n    - apply Hρ.\n  Qed.\n  Theorem Qdec_bounded_exists t φ :\n    Qdec φ -> Qdec (∃ ($0 ⧀= t`[↑]) ∧ φ).\n  Proof.\n    intros H pei ρ Hρ.\n    destruct (@closed_term_is_num _ t`[ρ]) as [x Hx].\n    { apply subst_t_closed, Hρ. }\n    enough (Qeq ⊢ (∃ (fin_disj x ($1 == $0)) ∧ φ)[ρ] \\/ Qeq ⊢ ¬ (∃ (fin_disj x ($1 == $0)) ∧ φ)[ρ]) as H'.\n    { cbn. \n      cbn in H'. rewrite fin_disj_subst in H'. \n      cbn in H'. unfold \"↑\" in H'.\n      destruct H' as [H1|H1].\n      - left. fstart. \n        fassert (∃ fin_disj x ($1 == $0) ∧ φ[up ρ]).\n        { fapply H1. }\n        fdestruct \"H\" as \"[z [H1 H2]]\".\n        rewrite fin_disj_subst. cbn.\n        fexists z. fsplit; last ctx.\n        fassert (z ⧀= num x).\n        { fapply le_fin_disj. fapply \"H1\". }\n        unfold PAle. fdestruct \"H\". fexists x0.\n        asimpl. frewrite Hx. fapply \"H\".\n      - right.  fstart. fintros. fapply H1.\n        fdestruct \"H\" as \"[z [H1 H2]]\". fexists z. \n        fsplit; last ctx.\n        rewrite fin_disj_subst. cbn. fapply le_fin_disj.\n        cbn. fdestruct \"H1\" as \"[z' Hz']\". fexists z'.\n        fassert (t`[ρ] == num x) by fapply Hx.\n        asimpl. frewrite <-\"H\". fapply \"Hz'\". }\n    eapply Qdec_iff.\n    - apply frewrite_equiv_switch. apply exists_fin_disj.\n    - apply Qdec_fin_disj, H.\n    - apply Hρ.\n  Qed.\n\n  Theorem Qdec_bounded_exists_comm t φ :\n    Qdec φ -> Qdec (∃ ($0 ⧀=' t`[↑]) ∧ φ).\n  Proof.\n    intros H pei ρ Hρ.\n    destruct (@closed_term_is_num _ t`[ρ]) as [x Hx].\n    { apply subst_t_closed, Hρ. }\n    enough (Qeq ⊢ (∃ (fin_disj x ($1 == $0)) ∧ φ)[ρ] \\/ Qeq ⊢ ¬ (∃ (fin_disj x ($1 == $0)) ∧ φ)[ρ]) as H'.\n    { cbn. \n      cbn in H'. rewrite fin_disj_subst in H'. \n      cbn in H'. unfold \"↑\" in H'.\n      destruct H' as [H1|H1].\n      - left. fstart. \n        fassert (∃ fin_disj x ($1 == $0) ∧ φ[up ρ]) by apply H1.\n        fdestruct \"H\" as \"[z [H1 H2]]\".\n        rewrite fin_disj_subst. cbn.\n        fexists z. fsplit; last ctx.\n        fassert (z ⧀=' num x).\n        { fapply le_swap_fin_disj. fapply \"H1\". }\n        unfold PAle'. fdestruct \"H\". fexists x0.\n        asimpl. frewrite Hx. fapply \"H\".\n      - right.  fstart. fintros. fapply H1.\n        fdestruct \"H\" as \"[z [H1 H2]]\". fexists z. \n        fsplit; last ctx.\n        rewrite fin_disj_subst. cbn. fapply le_swap_fin_disj.\n        cbn. fdestruct \"H1\". fexists x0.\n        fassert (t`[ρ] == num x) by fapply Hx.\n        asimpl. frewrite <-\"H0\". fapply \"H\". }\n    eapply Qdec_iff.\n    - apply frewrite_equiv_switch. apply exists_fin_disj.\n    - apply Qdec_fin_disj, H.\n    - apply Hρ.\n  Qed.\nEnd Qdec.\n", "meta": {"author": "uds-psl", "repo": "coq-library-fol", "sha": "0fe6a74eebe8b567d8196e0f62608ac3c55753f3", "save_path": "github-repos/coq/uds-psl-coq-library-fol", "path": "github-repos/coq/uds-psl-coq-library-fol/coq-library-fol-0fe6a74eebe8b567d8196e0f62608ac3c55753f3/theories/Incompleteness/qdec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2383312425124003}}
{"text": "Require Import Coqlib.\nRequire Import Asm.\nRequire Import Integers.\nRequire Import PeekTactics.\nRequire Import PeepsLib.\nRequire Import PregTactics.\nRequire Import StepIn.\nRequire Import AsmBits.\nRequire Import Values.\nRequire Import ValEq.\nRequire Import Integers.\nRequire Import PeepsTactics.\n\nDefinition peep_div_2_to_shr_example : code :=\n  Pmov_ri ECX two :: Pdiv ECX :: nil.\n\nSection DIV_2_TO_SHIFT.\n  \n  Variable concrete : code.\n\n  Definition peep_div_2_to_shr_defs : rewrite_defs :=\n    {|\n      fnd :=\n        Pmov_ri ECX two ::              \n                Pdiv ECX ::\n                nil\n      ; rpl := \n          Pshr_ri EAX Int.one ::\n                  Pnop ::\n                  nil              \n      ; lv_in := IR EAX :: PC :: nil\n      ; lv_out := IR EAX :: PC :: nil\n      ; clobbered := IR EDX :: IR ECX :: flags\n    |}.\n\n  Lemma peep_div_2_to_shr_selr :\n    StepEquiv.step_through_equiv_live (fnd peep_div_2_to_shr_defs) (rpl peep_div_2_to_shr_defs) (lv_in peep_div_2_to_shr_defs) (lv_out peep_div_2_to_shr_defs).\n  Proof.\n    prep_l.\n    step_l.\n    step_l.\n    prep_r.\n    step_r.\n    step_r.\n    finish_r.\n    prep_eq.\n    split.\n    2: eq_mem_tac.\n    intros.    \n    simpl_and_clear.\n    (*EAX*)\n    break_or'.\n    {\n      subst reg.\n      subst_max.\n      preg_simpl.      \n      unfold Val.divu in *.\n      simpl_match_hyp.\n      repeat inv_some.\n      simpl.\n      unfold Val.shru.\n      P0 preg_simpl_hyp nextinstr.\n      inv_vint.\n      rewrite Heqv1 in *.\n      P0 _simpl val_eq.\n      break_match; try congruence.\n      break_if.\n      f_equal.\n      inv_vint.\n      erewrite Int.divu_pow2.\n      eauto.\n      unfold Int.one.\n      unfold two.\n      cut (2 = two_p 1). intro. rewrite H0.      \n      apply Int.is_power2_two_p.      \n      unfold Int.zwordsize in *.\n      unfold Int.wordsize in *.\n      unfold Wordsize_32.wordsize in *.\n      simpl.\n      omega.\n      vm_compute.\n      reflexivity.\n      inv_vint.\n      clear -Heqb1.\n      exfalso.\n      unfold Int.ltu in *.\n      break_if.\n      congruence.\n      clear Heqs.\n      rewrite Int.unsigned_one in g.\n      rewrite Int.unsigned_repr_wordsize in *.            \n      unfold Int.zwordsize in *.\n      unfold Int.wordsize in *.\n      unfold Wordsize_32.wordsize in *.\n      simpl in *.\n      omega.      \n    }\n    (*PC*)\n    break_or'.\n    2: inv_false.\n    subst reg.\n    P0 _clear False.    \n    subst_max.\n    preg_simpl.\n    repeat find_rewrite_goal.\n    simpl.\n    reflexivity.    \n  Qed.\n\n  Definition peep_div_2_to_shr_proofs : rewrite_proofs :=\n    {|\n      defs := peep_div_2_to_shr_defs\n      ; selr := peep_div_2_to_shr_selr\n    |}.\n\n  Definition peep_div_2_to_shr :\n    concrete = fnd peep_div_2_to_shr_defs ->\n    StepEquiv.rewrite.\n  Proof.\n    intros.\n    peep_tac_mk_rewrite peep_div_2_to_shr_defs peep_div_2_to_shr_proofs.\n  Qed.\n\nEnd DIV_2_TO_SHIFT.\n\nDefinition peep_div_2_to_shr_rewrite (c : code) : option StepEquiv.rewrite.  \n  name peep_div_2_to_shr p.\n  unfold peep_div_2_to_shr_defs in p.\n  simpl in p.\n  specialize (p (Pmov_ri ECX two :: Pdiv ECX :: nil)).\n  specialize (p eq_refl).\n  exact (Some p).  \nDefined.\n\nDefinition div_2_to_shr (c : code) : list StepEquiv.rewrite :=\n  collect (map peep_div_2_to_shr_rewrite (ParamSplit.matched_pat peep_div_2_to_shr_example c)).\n", "meta": {"author": "uwplse", "repo": "peek", "sha": "4943735ed39fd5ddadf2c28fc2ada31504228561", "save_path": "github-repos/coq/uwplse-peek", "path": "github-repos/coq/uwplse-peek/peek-4943735ed39fd5ddadf2c28fc2ada31504228561/compcert/peeps/Peep_Div2ToShift.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23833124251240026}}
{"text": "Require Import Coqlib Maps.\nRequire Import AST Linking.\nRequire Import Values Memory Globalenvs Events.\nRequire Import RelationClasses.\nRequire Import sflib.\n\nSet Implicit Arguments.\n\n\n\nRecord t := mk {\n  unreach:> block -> bool; (* for finiteness' `j` function. *)\n  ge_nb: block;\n  nb: block;\n}.\n\nNotation \"'prange' '#' hi\" := (fun blk => Plt blk hi) (at level 50, no associativity).\nNotation \"'prange' lo '#'\" := (fun blk => Ple lo blk) (at level 50, no associativity).\nNotation \"'prange' lo hi\" := (fun blk => Ple lo blk /\\ Plt blk hi) (at level 50, no associativity).\n\nInductive wf (su: t): Prop :=\n| wf_intro\n  (WFLO: su <1= prange su.(ge_nb) #)\n  (WFHI: su <1= prange # su.(nb)).\n\n(* One strong point of definiton compared to inductive:\nelimination of multiple predicate requires\n- (inductive) multiple \"inv\"\n- (definition) unfold __ in *; des *)\nDefinition hle_old (su0 su1: t): Prop :=\n  (<<PRIV: su0.(unreach) <1= su1.(unreach)>>)\n  /\\ (<<OLD: su1.(unreach) /1\\ (prange # su0.(nb)) <1= su0.(unreach)>>)\n  /\\ (<<NB: Ple su0.(nb) su1.(nb)>>)\n  /\\ (<<GENB: su0.(ge_nb) = su1.(ge_nb)>>).\n\nDefinition hle (su0 su1: t): Prop :=\n  (<<OLD: forall blk (LT: Plt blk su0.(nb)), su0 blk = su1 blk>>)\n  /\\ (<<NB: Ple su0.(nb) su1.(nb)>>)\n  /\\ (<<GENB: su0.(ge_nb) = su1.(ge_nb)>>).\n\nLemma hle_old_hle: forall su0 su1, hle_old su0 su1 -> hle su0 su1.\nProof.\n  split; i; rr in H; des; rr; esplits; eauto.\n  - ii. destruct (su1 blk) eqn:T; ss.\n    + exploit OLD; eauto.\n    + destruct (su0 blk) eqn:T2; ss. exploit PRIV; eauto.\nQed.\nLemma hle_hle_old: forall su0 su1 (WF: wf su0), hle su0 su1 -> hle_old su0 su1.\nProof.\n  split; i; rr in H; des; rr; esplits; eauto.\n  - i. erewrite <- OLD; eauto.\n    inv WF. exploit WFHI; eauto.\n  - i. des. erewrite OLD; eauto.\nQed.\n\nLemma hle_update\n      (su0 su1 su2: t)\n      (EQ: forall blk (LT: Plt blk su0.(nb)), su1 blk = su2 blk)\n      (NB: Ple su1.(nb) su2.(nb))\n      (GENB: su1.(ge_nb) = su2.(ge_nb))\n      (HLE: hle su0 su1):\n    <<HLE: hle su0 su2>>.\nProof.\n  rr in HLE. des. rr. esplits; eauto; try xomega. rewrite <- GENB. ss.\nQed.\n\nLemma hle_old_update\n      (su0 su1 su2: t)\n      (EQ: forall blk (LT: Plt blk su0.(nb)), su1 blk = su2 blk)\n      (NB: Ple su1.(nb) su2.(nb))\n      (GENB: su1.(ge_nb) = su2.(ge_nb))\n      (HLE: hle_old su0 su1)\n      (WF: wf su0):\n    <<HLE: hle_old su0 su2>>.\nProof.\n  rr in HLE. rr. des. esplits; eauto.\n  - inv WF. i. exploit PRIV; eauto. i. erewrite <- EQ; eauto.\n  - i; des. erewrite <- EQ in PR; eauto.\n  - rewrite <- NB. xomega.\n  - rewrite <- GENB. ss.\nQed.\n\nGlobal Program Instance hle_old_PreOrder: PreOrder hle_old.\nNext Obligation.\n  rr. ii; des. esplits; eauto.\n  - ii. des; ss.\n  - xomega.\nQed.\nNext Obligation.\n  ii; des.\n  unfold hle_old in *. des.\n  esplits; eauto; try xomega.\n  - ii. des; ss. eapply OLD0; eauto. esplits; eauto. eapply OLD; eauto. esplits; eauto. xomega.\n  - congruence.\nQed.\n\nGlobal Program Instance hle_PreOrder: PreOrder hle.\nNext Obligation.\n  rr. ii; des. esplits; eauto. reflexivity.\nQed.\nNext Obligation.\n  ii; des. unfold hle in *. des. esplits; eauto; try xomega.\n  - ii. rewrite <- OLD; ss; try xomega. rewrite OLD0; ss.\n  - congruence.\nQed.\n\nInductive mle (su: t) (m0 m1: Memory.mem): Prop :=\n| mle_intro\n    (PERM: forall blk ofs\n        (VALID: (Mem.valid_block m0) blk),\n        (Mem.perm m1) blk ofs Max <1= (Mem.perm m0) blk ofs Max)\n    (RO: Mem.unchanged_on (loc_not_writable m0) m0 m1)\n    (PRIV: Mem.unchanged_on (Basics.flip (fun _ => su)) m0 m1).\n\nGlobal Program Instance mle_PreOrder su: PreOrder (mle su).\nNext Obligation.\n  rr. ii. econs; eauto with mem.\nQed.\nNext Obligation.\n  ii. inv H. inv H0. econs; ss; eauto.\n  - ii. eapply PERM; eauto. eapply PERM0; eauto. unfold Mem.valid_block in *. inv RO. xomega.\n  - eapply Mem.unchanged_on_implies with (P:= fun blk ofs => loc_not_writable x blk ofs /\\ Mem.valid_block x blk); ss.\n    eapply Mem.unchanged_on_trans.\n    + eapply Mem.unchanged_on_implies; try apply RO. i. des. ss.\n    + eapply Mem.unchanged_on_implies; try apply RO0; eauto.\n      ii. des. rr in H. eapply H; eauto.\n  - eapply Mem.unchanged_on_trans; eauto.\nQed.\n\nLemma store_mle\n      chunk m0 blk ofs v m1 (su: t)\n      (STR: Mem.store chunk m0 blk ofs v = Some m1)\n      (SU: ~su blk):\n    <<MLE: mle su m0 m1>>.\nProof.\n  econs; eauto.\n  - ii. eauto with mem.\n  - (* Copied from Events.volatile_store_readonly *)\n    eapply Mem.store_unchanged_on; eauto.\n    exploit Mem.store_valid_access_3; eauto. intros [P Q].\n    intros. unfold loc_not_writable. red; intros. elim H0.\n    apply Mem.perm_cur_max. apply P. auto.\n  - eapply Mem.store_unchanged_on; eauto.\nQed.\n\nLemma free_mle\n      m0 blk lo hi m1 (su: t)\n      (FREE: Mem.free m0 blk lo hi = Some m1)\n      (SU: ~su blk):\n    <<MLE: mle su m0 m1>>.\nProof.\n  econs; eauto.\n  - ii. eauto with mem.\n  - (* Copied from Events.extcall_free_ok *)\n    inv FREE. eapply Mem.free_unchanged_on; eauto.\n    intros. red; intros. elim H1.\n    apply Mem.perm_cur_max. apply Mem.perm_implies with Freeable; auto with mem.\n    eapply Mem.free_range_perm; eauto.\n  - eapply Mem.free_unchanged_on; eauto.\nQed.\n\nLemma storebytes_mle\n      m0 blk ofs mvs m1 (su: t)\n      (STR: Mem.storebytes m0 blk ofs mvs = Some m1)\n      (SU: ~su blk):\n    <<MLE: mle su m0 m1>>.\nProof.\n  econs; eauto.\n  - ii. eauto with mem.\n  - (* Copied from Events.volatile_store_readonly *)\n    inv STR. eapply Mem.storebytes_unchanged_on; eauto.\n    intros. red; intros. elim H1.\n    apply Mem.perm_cur_max.\n    eapply Mem.storebytes_range_perm; eauto.\n  - eapply Mem.storebytes_unchanged_on; eauto.\nQed.\n\nLemma alloc_mle\n      m0 lo hi m1 blk (su: t)\n      (ALC: Mem.alloc m0 lo hi = (m1, blk)):\n    <<MLE: mle su m0 m1>>.\nProof.\n  econs; eauto.\n  - ii. eauto with mem.\n  - eapply Mem.alloc_unchanged_on; eauto.\n  - eapply Mem.alloc_unchanged_on; eauto.\nQed.\n\nLemma mle_monotone\n      m0 m1 (su0 su1: t)\n      (LE: su0 <1= su1)\n      (MLE: su1.(mle) m0 m1):\n    <<MLE: su0.(mle) m0 m1>>.\nProof.\n  inv MLE. econs; eauto. eapply Mem.unchanged_on_implies; eauto. unfold Basics.flip in *. rr. ii. eapply LE; eauto.\nQed.\n\nLtac nb_tac :=\n  repeat\n    multimatch goal with\n    | [ H: nb _ = _ |- _ ] => rewrite H in *\n    | [ H: ge_nb _ = _ |- _ ] => rewrite H in *\n    end.\n", "meta": {"author": "snu-sf", "repo": "CompCertR", "sha": "f059afea5ce5cfc381ef3206df5f0a0d574694a3", "save_path": "github-repos/coq/snu-sf-CompCertR", "path": "github-repos/coq/snu-sf-CompCertR/CompCertR-f059afea5ce5cfc381ef3206df5f0a0d574694a3/common/Unreach.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23833123661849281}}
{"text": "(* ***********************************************************************) \n(*                                                                       *)\n(*   Synchronously executed Interpreted Time Petri Nets (SITPNs)         *)\n(*                                                                       *)\n(*                                                                       *)\n(*   Copyright Université de Montpellier, contributor(s): Vincent        *)\n(*   Iampietro, David Andreu, David Delahaye (May 2020)                  *)\n(*                                                                       *)\n(*   This software is governed by the CeCILL-C license under French law  *)\n(*   and abiding by the rules of distribution of free software.  You can *)\n(*   use, modify and/ or redistribute the software under the terms of    *)\n(*   the CeCILL-C license as circulated by CEA, CNRS and INRIA at the    *)\n(*   following URL \"http://www.cecill.info\".  The fact that you are      *)\n(*   presently reading this means that you have had knowledge of the     *)\n(*   CeCILL-C license and that you accept its terms.                     *)\n(*                                                                       *)\n(* ***********************************************************************) \n\n(* Import Sitpn material. *)\n\nRequire Import simpl.Sitpn.\nRequire Import simpl.SitpnTokenPlayer.\nRequire Import simpl.SitpnSemantics.\nRequire Import simpl.SitpnTactics.\nRequire Import simpl.SitpnCoreLemmas.\n\n(* Import misc. lemmas, tactics and definitions. *)\n\n\n\n\n(* Import lemmas about marking. *)\n\nRequire Import simpl.SitpnWellDefMarking.\nRequire Import simpl.SitpnRisingEdgeMarking.\nRequire Import simpl.SitpnFallingEdgeFiredComplete.\n\n(* Import classical logic. *)\n\nRequire Import Classical_Prop.\n\n(** * Completeness for [map_update_marking_pre]. *)\n\nSection MapUpdateMarkingPreComplete.\n\n  (** Completeness lemma for [modify_m]. *)\n\n  Lemma modify_m_complete :\n    forall (marking : list (Place * nat))\n           (p : Place)\n           (op : nat -> nat -> nat)\n           (nboftokens : nat),\n      In p (fs marking) ->\n      NoDup (fs marking) ->\n      exists m' : list (Place * nat),\n        modify_m marking p op nboftokens = Some m'\n        /\\ forall (n : nat), In (p, n) marking -> In (p, op n nboftokens) m'.\n  Proof.\n    induction marking.\n\n    (* BASE CASE, marking = [] *)\n    - intros p op nboftokens Hin; simpl in Hin; inversion Hin.\n\n    (* INDUCTION CASE *)\n    - destruct a; simpl; intros pl op nboftkens Hin_p_fsm Hnodup_fsm.\n\n      (* Two case, for p =? pl *)\n      case_eq (p =? pl); intros Heq_ppl.\n\n      (* Case (p =? pl) = true *)\n      + exists ((pl, op n nboftkens) :: marking).\n        repeat split.\n        intros nb Hv; inversion_clear Hv as [Heq_pn | Hin_m].\n        \n        (* Case (p, n) = (pl, nb) *)\n        -- injection Heq_pn as Heq_p Heq_n; rewrite Heq_n; apply in_eq.\n\n        (* Case (pl, nb) ∈ marking, contradiction with NoDup (fs ((p, n) :: marking)) \n           knowing that p = pl. *)\n        -- apply beq_nat_true in Heq_ppl.\n           rewrite Heq_ppl in Hnodup_fsm.\n           unfold fs in Hnodup_fsm; rewrite fst_split_cons_app in Hnodup_fsm.\n           simpl in Hnodup_fsm.\n           rewrite NoDup_cons_iff in Hnodup_fsm.\n           apply proj1 in Hnodup_fsm.\n           apply in_fst_split in Hin_m.\n           contradiction.\n\n      (* Case (p =? pl) = false *)\n      +\n        (* Specializes IHmarking. *)\n\n        assert (Hin_p_fsm' : In pl (fs marking)).\n        {\n          unfold fs in Hin_p_fsm; rewrite fst_split_cons_app in Hin_p_fsm.\n          simpl in Hin_p_fsm.\n          apply beq_nat_false in Heq_ppl.\n          inversion_clear Hin_p_fsm as [Heq_ppl' | Hin_pl_fsm];\n            [ contradiction | assumption ].\n        }\n\n        assert (Hnodup_fsm' : NoDup (fs marking)).\n        {\n          unfold fs in Hnodup_fsm; rewrite fst_split_cons_app in Hnodup_fsm.\n          simpl in Hnodup_fsm.\n          rewrite NoDup_cons_iff in Hnodup_fsm.\n          apply proj2 in Hnodup_fsm.\n          assumption.\n        }\n\n        specialize (IHmarking pl op nboftkens Hin_p_fsm' Hnodup_fsm')\n          as Hex_modif_m.\n        inversion_clear Hex_modif_m as (m' & Hw_modif_m).\n        inversion_clear Hw_modif_m as (Hmodif_m & Hdef_m').\n\n        (* Rewrites the goal with the newly-built hypothesis. *)\n        rewrite Hmodif_m.\n\n        (* Instantiates the new marking, then completes the goal. *)\n        exists ((p, n) :: m').\n        repeat split.\n        intros nb Hw.\n        inversion_clear Hw as [Heq_pn | Hin_m].\n        -- injection Heq_pn as Heq_p Heq_n.\n           apply beq_nat_false in Heq_ppl; contradiction.\n        -- apply in_cons; apply (Hdef_m' nb Hin_m).           \n  Qed.\n  \n  (** Completeness lemma for [update_marking_pre_aux]. *)\n\n  Lemma update_marking_pre_aux_complete :\n    forall (pre_places : list Place)\n           (sitpn : Sitpn)\n           (t : Trans)\n           (marking : list (Place * nat)),\n      IsWellDefinedSitpn sitpn ->\n      In t (transs sitpn) ->\n      Permutation (places sitpn) (fs marking) ->\n      IsDecListCons pre_places (pre_pl (lneighbours sitpn t)) ->\n      NoDup pre_places ->\n      exists m' : list (Place * nat),\n        update_marking_pre_aux sitpn marking t pre_places = Some m'\n        /\\ (forall (p : Place) (n : nat), In p pre_places -> In (p, n) marking -> In (p, n - pre sitpn t p) m')\n        /\\ (fs marking) = (fs m').\n  Proof.\n    intros pre_places sitpn t;\n      induction pre_places;\n      intros marking Hwell_def_sitpn Hin_t_transs\n             Hperm_pls His_dec Hnodup_prepl;\n      simpl.\n\n    (* BASE CASE, pre_places = [] *)\n    \n    - exists marking; repeat split.\n      intros p n Hfalse; inversion Hfalse.\n\n    (* INDUCTION CASE *)\n    -\n      (* Specializes modify_m_complete, then rewrites the goal. *)\n\n      assert (Hin_a_fsm : In a (fs marking)).\n      {\n        assert (Hin_a_fn : In a (flatten_neighbours (lneighbours sitpn t))).\n        {\n          unfold flatten_neighbours.\n          apply in_or_app; left.\n          deduce_in_from_is_dec_list_cons His_dec as Hin_a_prepl.\n          assumption.\n        }\n\n        specialize (in_transs_incl_flatten t Hwell_def_sitpn Hin_t_transs)\n          as Hincl_fn_fl.\n        specialize (Hincl_fn_fl a Hin_a_fn).\n        explode_well_defined_sitpn.\n        unfold NoUnknownPlaceInNeighbours in Hunk_pl_neigh.\n        specialize (Hunk_pl_neigh a Hincl_fn_fl).\n        rewrite Hperm_pls in Hunk_pl_neigh; assumption.\n      }\n\n      assert (Hnodup_fsm : NoDup (fs marking)).\n      {\n        explode_well_defined_sitpn.\n        unfold NoDupPlaces in Hnodup_places.\n        rewrite Hperm_pls in Hnodup_places.\n        assumption.\n      }\n      \n      specialize (modify_m_complete marking a Nat.sub (pre sitpn t a) Hin_a_fsm Hnodup_fsm)\n        as Hex_modif_m.\n\n      (* Explodes the newly-built hypotheses, then rewrites the goal. *)\n      inversion_clear Hex_modif_m as (m' & Hmodif_m_w).\n      inversion_clear Hmodif_m_w as (Hmodif_m & Hdef_m').\n      rewrite Hmodif_m.\n\n      (* Then specializes IHpre_places. *)\n      \n      assert (Hperm_pls_m' : Permutation (places sitpn) (fs m')).\n      {\n        specialize (modify_m_same_struct marking a Nat.sub (pre sitpn t a) m' Hmodif_m)\n          as Heq_fsm_fsm'.\n        unfold fs; rewrite <- Heq_fsm_fsm'; assumption.\n      }\n\n      assert (Hnodup_prepl' : NoDup pre_places).\n      {\n        rewrite NoDup_cons_iff in Hnodup_prepl;\n          apply proj2 in Hnodup_prepl;\n          assumption.\n      }\n      \n      specialize (@IHpre_places m' Hwell_def_sitpn Hin_t_transs Hperm_pls_m'\n                                (is_dec_list_cons_cons His_dec) Hnodup_prepl')\n        as Hex_up_mark_pre.\n\n      (* Explodes the newly-built hypothesis. *)\n      inversion_clear Hex_up_mark_pre as (final_marking & Hup_mark_pre_w).\n      inversion_clear Hup_mark_pre_w as (Hup_mark_pre & Hw).\n      inversion_clear Hw as (Hdef_fm & Heq_fsm'_fsfm).\n\n      (* Instantiates final_marking, then solves each branch of the goal. *)\n      exists final_marking.\n      repeat split.\n\n      (* Trivial case. *)\n      + assumption.\n\n      (* Case definition of final_marking. *)\n      + intros p n Hin_prepl_v Hin_pn_m.\n\n        (* Two case: a = p \\/ In p pre_places. *)\n        inversion_clear Hin_prepl_v as [Heq_ap | Hin_p_prepl].\n\n        (* Case a = p *)\n        -- rewrite <- Heq_ap in Hin_pn_m.\n           specialize (Hdef_m' n Hin_pn_m) as Hin_ansub_m'.\n\n           (* Specializes update_marking_pre_aux_not_in_pre_places \n              to deduce In (a, n - pre) final_marking. *)\n\n           assert (Heq_fsm_fsm' : (fs marking) = (fs m')).\n           {\n             apply (modify_m_same_struct marking a Nat.sub (pre sitpn t a) m' Hmodif_m).\n           }\n           \n           assert (Hnot_in_a_prepl : ~In a pre_places).\n           {\n             apply NoDup_cons_iff, proj1 in Hnodup_prepl; assumption.\n           }\n                  \n           rewrite (update_marking_pre_aux_not_in_pre_places\n                      sitpn m' t pre_places final_marking Hup_mark_pre\n                      a Hnot_in_a_prepl (n - pre sitpn t a)) in Hin_ansub_m'.\n           rewrite Heq_ap in Hin_ansub_m'.\n           assumption.\n\n        (* Case In p pre_places *)\n        --\n          (* Rewrites In (p, n) marking with modify_m_in_if_diff to\n             get In (p, n) m'. *)\n\n          assert (Hneq_ap : a <> p).\n          {\n            apply NoDup_cons_iff, proj1 in Hnodup_prepl.\n            apply (not_in_in_diff a p pre_places (conj Hnodup_prepl Hin_p_prepl)).\n          }\n          \n          rewrite (modify_m_in_if_diff marking a Nat.sub (pre sitpn t a) m'\n                                       Hmodif_m p n Hneq_ap)\n            in Hin_pn_m.\n\n          (* Completes the goal by applying Hdef_fm. *)\n          apply (Hdef_fm p n Hin_p_prepl Hin_pn_m).\n\n      (* Case fs marking = fs final_marking *)\n      +\n        assert (Heq_fsm_fsm' : (fs marking) = (fs m')).\n        {\n          apply (modify_m_same_struct marking a Nat.sub (pre sitpn t a) m' Hmodif_m).\n        }\n\n        transitivity (fs m'); [assumption | assumption].\n  Qed.\n  \n  (** Completeness lemma for [map_update_marking_pre]. *)\n\n  Lemma map_update_marking_pre_complete :\n    forall (sitpn : Sitpn)\n           (s s' : SitpnState)\n           (time_value : nat)\n           (env : Condition -> nat -> bool)\n           (fired : list Trans)\n           (marking : list (Place * nat)),\n      IsWellDefinedSitpn sitpn ->\n      IsWellDefinedSitpnState sitpn s ->\n      IsWellDefinedSitpnState sitpn s' ->\n      SitpnSemantics sitpn s s' time_value env rising_edge ->\n      Permutation (places sitpn) (fs marking) ->\n      incl fired (Sitpn.fired s) ->\n      NoDup fired ->\n      exists transient_marking : list (Place * nat),\n        map_update_marking_pre sitpn marking fired = Some transient_marking\n        /\\ forall (p : Place) (n : nat), In (p, n) marking ->\n                                         In (p, n - pre_sum sitpn p fired) transient_marking.\n  Proof.\n    intros sitpn s s' time_value env;\n      induction fired;\n      intros marking Hwell_def_sitpn Hwell_def_s Hwell_def_s' Hspec\n             Hperm_m Hincl_fired Hnodup_fired.\n\n    (* BASE CASE, fired = [] *)\n    - simpl; exists marking; split;\n        [ reflexivity | intros p n Hin; rewrite <- minus_n_O; assumption ].\n\n    (* INDUCTION CASE, a :: fired *)\n    - simpl.\n      unfold update_marking_pre.\n\n      (* Specializes update_marking_pre_aux_complete *)\n\n      assert (Hin_a_transs : In a (transs sitpn)).\n      {\n        specialize (Hincl_fired a (in_eq a fired)) as Hin_a_fired.\n        explode_well_defined_sitpn_state Hwell_def_s.\n        apply (Hincl_state_fired_transs a Hin_a_fired).\n      }\n\n      assert (Hnodup_prepl : NoDup (pre_pl (lneighbours sitpn a))).\n      {\n        explode_well_defined_sitpn.\n        unfold NoDupInNeighbours in Hnodup_neigh.\n        specialize (Hnodup_neigh a Hin_a_transs) as Hnodup_w.\n        apply proj1 in Hnodup_w.\n        apply nodup_app, proj1 in Hnodup_w.\n        assumption.\n      }\n\n      specialize (update_marking_pre_aux_complete\n                    (pre_pl (lneighbours sitpn a)) sitpn a marking\n                    Hwell_def_sitpn Hin_a_transs Hperm_m\n                    (IsDecListCons_refl (pre_pl (lneighbours sitpn a)))\n                    Hnodup_prepl)\n        as Hex_up_mark_pre.\n\n      (* Explodes the newly-built hypothesis, then rewrites the goal. *)\n\n      inversion_clear Hex_up_mark_pre as (m' & Hw).\n      inversion_clear Hw as (Hup_mark_pre & H_defm'_w).\n      inversion_clear H_defm'_w as (Hdef_m' & Heq_fsm_fsm').\n      rewrite Hup_mark_pre.\n      \n      (* Then specializes IHfired. *)\n\n      assert (Hperm_m' : Permutation (places sitpn) (fs m'))\n        by (rewrite Heq_fsm_fsm' in Hperm_m; assumption).\n      \n      assert (Hincl_fired' : incl fired (Sitpn.fired s))\n        by (apply (incl_cons_inv a fired (Sitpn.fired s) Hincl_fired)).\n\n      assert (Hnodup_fired' : NoDup fired)\n        by (apply NoDup_cons_iff, proj2 in Hnodup_fired; assumption).\n\n      specialize (IHfired m' Hwell_def_sitpn Hwell_def_s Hwell_def_s' Hspec\n                          Hperm_m' Hincl_fired' Hnodup_fired')\n        as Hex_map_up_pre.\n\n      (* Explodes the newly-built hypothesis and instantiates\n         transient_marking. *)\n      \n      inversion_clear Hex_map_up_pre as (transient_marking & Hw).\n      inversion_clear Hw as (Hmap_up_pre & Hdef_tm).\n      exists transient_marking.\n\n      (* Splits and solves each branch of the goal. *)\n\n      repeat split.\n\n      (* Equality case, trivial. *)\n      + trivial.\n\n      (* Case transient_marking definition. *)\n      + intros p n Hin_pn_m.\n\n        (* Two cases, either p ∈ (pre_pl a) or p ∉ (pre_pl a) *)\n\n        assert (Hin_prepl_v := classic (In p (pre_pl (lneighbours sitpn a)))).\n        inversion_clear Hin_prepl_v as [Hin_prepl | Hnot_in_prepl].\n\n        (* Case In p pre_pl *)\n        -- specialize (Hdef_m' p n Hin_prepl Hin_pn_m) as Hin_pn_m'.\n           rewrite Nat.sub_add_distr.\n           apply (Hdef_tm p (n - pre sitpn a p) Hin_pn_m').\n\n        (* Case ~In p pre_pl *)\n        --\n          (* If p in not is pre-places of a then there's no pre arc\n             between p and a. *)\n\n          assert (Heq_pre_0 : pre sitpn a p = 0).\n          {\n            explode_well_defined_sitpn.\n            unfold AreWellDefinedPreEdges in Hwell_def_pre.\n            specialize (Hwell_def_pre a p Hin_a_transs).\n            apply proj2 in Hwell_def_pre.\n            apply (Hwell_def_pre Hnot_in_prepl).\n          }\n\n          rewrite Heq_pre_0, Nat.add_0_l.\n\n          (* Rewrites In (p, n) marking with\n             update_marking_pre_aux_not_in_pre_places to get In (p, n) m'. *)\n\n          rewrite (update_marking_pre_aux_not_in_pre_places\n                     sitpn marking a (pre_pl (lneighbours sitpn a))\n                     m' Hup_mark_pre p Hnot_in_prepl) in Hin_pn_m.\n\n          (* Then completes the goal. *)\n\n          apply (Hdef_tm p n Hin_pn_m).          \n  Qed.\n  \nEnd MapUpdateMarkingPreComplete.\n\n\n(** * Completeness for [map_update_marking_post]. *)\n\nSection MapUpdateMarkingPostComplete.\n  \n  (** Completeness lemma for [update_marking_post_aux]. *)\n\n  Lemma update_marking_post_aux_complete :\n    forall (post_places : list Place)\n           (sitpn : Sitpn)\n           (t : Trans)\n           (marking : list (Place * nat)),\n      IsWellDefinedSitpn sitpn ->\n      In t (transs sitpn) ->\n      Permutation (places sitpn) (fs marking) ->\n      IsDecListCons post_places (post_pl (lneighbours sitpn t)) ->\n      NoDup post_places ->\n      exists m' : list (Place * nat),\n        update_marking_post_aux sitpn marking t post_places = Some m'\n        /\\ (forall (p : Place) (n : nat), In p post_places -> In (p, n) marking -> In (p, n + post sitpn t p) m')\n        /\\ (fs marking) = (fs m').\n  Proof.\n    intros post_places sitpn t;\n      induction post_places;\n      intros marking Hwell_def_sitpn Hin_t_transs\n             Hperm_pls His_dec Hnodup_postpl;\n      simpl.\n\n    (* BASE CASE, post_places = [] *)\n    \n    - exists marking; repeat split.\n      intros p n Hfalse; inversion Hfalse.\n\n    (* INDUCTION CASE *)\n    -\n      (* Specializes modify_m_complete, then rewrites the goal. *)\n\n      assert (Hin_a_fsm : In a (fs marking)).\n      {\n        assert (Hin_a_fn : In a (flatten_neighbours (lneighbours sitpn t))).\n        {\n          unfold flatten_neighbours.\n          do 3 (apply in_or_app; right).\n          deduce_in_from_is_dec_list_cons His_dec as Hin_a_postpl.\n          assumption.\n        }\n\n        specialize (in_transs_incl_flatten t Hwell_def_sitpn Hin_t_transs)\n          as Hincl_fn_fl.\n        specialize (Hincl_fn_fl a Hin_a_fn).\n        explode_well_defined_sitpn.\n        unfold NoUnknownPlaceInNeighbours in Hunk_pl_neigh.\n        specialize (Hunk_pl_neigh a Hincl_fn_fl).\n        rewrite Hperm_pls in Hunk_pl_neigh; assumption.\n      }\n\n      assert (Hnodup_fsm : NoDup (fs marking)).\n      {\n        explode_well_defined_sitpn.\n        unfold NoDupPlaces in Hnodup_places.\n        rewrite Hperm_pls in Hnodup_places.\n        assumption.\n      }\n      \n      specialize (modify_m_complete marking a Nat.add (post sitpn t a) Hin_a_fsm Hnodup_fsm)\n        as Hex_modif_m.\n\n      (* Explodes the newly-built hypotheses, then rewrites the goal. *)\n      inversion_clear Hex_modif_m as (m' & Hmodif_m_w).\n      inversion_clear Hmodif_m_w as (Hmodif_m & Hdef_m').\n      rewrite Hmodif_m.\n\n      (* Then specializes IHpost_places. *)\n      \n      assert (Hperm_pls_m' : Permutation (places sitpn) (fs m')).\n      {\n        specialize (modify_m_same_struct marking a Nat.add (post sitpn t a) m' Hmodif_m)\n          as Heq_fsm_fsm'.\n        unfold fs; rewrite <- Heq_fsm_fsm'; assumption.\n      }\n\n      assert (Hnodup_postpl' : NoDup post_places).\n      {\n        rewrite NoDup_cons_iff in Hnodup_postpl;\n          apply proj2 in Hnodup_postpl;\n          assumption.\n      }\n      \n      specialize (@IHpost_places m' Hwell_def_sitpn Hin_t_transs Hperm_pls_m'\n                                (is_dec_list_cons_cons His_dec) Hnodup_postpl')\n        as Hex_up_mark_post.\n\n      (* Explodes the newly-built hypothesis. *)\n      inversion_clear Hex_up_mark_post as (final_marking & Hup_mark_post_w).\n      inversion_clear Hup_mark_post_w as (Hup_mark_post & Hw).\n      inversion_clear Hw as (Hdef_fm & Heq_fsm'_fsfm).\n\n      (* Instantiates final_marking, then solves each branch of the goal. *)\n      exists final_marking.\n      repeat split.\n\n      (* Trivial case. *)\n      + assumption.\n\n      (* Case definition of final_marking. *)\n      + intros p n Hin_postpl_v Hin_pn_m.\n\n        (* Two case: a = p \\/ In p post_places. *)\n        inversion_clear Hin_postpl_v as [Heq_ap | Hin_p_postpl].\n\n        (* Case a = p *)\n        -- rewrite <- Heq_ap in Hin_pn_m.\n           specialize (Hdef_m' n Hin_pn_m) as Hin_ansub_m'.\n\n           (* Specializes update_marking_post_aux_not_in_post_places \n              to deduce In (a, n + post) final_marking. *)\n\n           assert (Heq_fsm_fsm' : (fs marking) = (fs m')).\n           {\n             apply (modify_m_same_struct marking a Nat.add (post sitpn t a) m' Hmodif_m).\n           }\n           \n           assert (Hnot_in_a_postpl : ~In a post_places).\n           {\n             apply NoDup_cons_iff, proj1 in Hnodup_postpl; assumption.\n           }\n                  \n           rewrite (update_marking_post_aux_not_in_post_places\n                      sitpn m' t post_places final_marking Hup_mark_post\n                      a Hnot_in_a_postpl (n + post sitpn t a)) in Hin_ansub_m'.\n           rewrite Heq_ap in Hin_ansub_m'.\n           assumption.\n\n        (* Case In p post_places *)\n        --\n          (* Rewrites In (p, n) marking with modify_m_in_if_diff to\n             get In (p, n) m'. *)\n\n          assert (Hneq_ap : a <> p).\n          {\n            apply NoDup_cons_iff, proj1 in Hnodup_postpl.\n            apply (not_in_in_diff a p post_places (conj Hnodup_postpl Hin_p_postpl)).\n          }\n          \n          rewrite (modify_m_in_if_diff marking a Nat.add (post sitpn t a) m'\n                                       Hmodif_m p n Hneq_ap)\n            in Hin_pn_m.\n\n          (* Completes the goal by applying Hdef_fm. *)\n          apply (Hdef_fm p n Hin_p_postpl Hin_pn_m).\n\n      (* Case fs marking = fs final_marking *)\n      +\n        assert (Heq_fsm_fsm' : (fs marking) = (fs m')).\n        {\n          apply (modify_m_same_struct marking a Nat.add (post sitpn t a) m' Hmodif_m).\n        }\n\n        transitivity (fs m'); [assumption | assumption].\n  Qed.\n  \n  (** Completeness lemma for [map_update_marking_post]. *)\n\n  Lemma map_update_marking_post_complete :\n    forall (sitpn : Sitpn)\n           (s s' : SitpnState)\n           (time_value : nat)\n           (env : Condition -> nat -> bool)\n           (fired : list Trans)\n           (marking : list (Place * nat)),\n      IsWellDefinedSitpn sitpn ->\n      IsWellDefinedSitpnState sitpn s ->\n      IsWellDefinedSitpnState sitpn s' ->\n      SitpnSemantics sitpn s s' time_value env rising_edge ->\n      Permutation (places sitpn) (fs marking) ->\n      incl fired (Sitpn.fired s) ->\n      NoDup fired ->\n      exists transient_marking : list (Place * nat),\n        map_update_marking_post sitpn marking fired = Some transient_marking\n        /\\ forall (p : Place) (n : nat), In (p, n) marking ->\n                                         In (p, n + post_sum sitpn p fired) transient_marking.\n  Proof.\n    intros sitpn s s' time_value env;\n      induction fired;\n      intros marking Hwell_def_sitpn Hwell_def_s Hwell_def_s' Hspec\n             Hperm_m Hincl_fired Hnodup_fired.\n\n    (* BASE CASE, fired = [] *)\n    - simpl; exists marking; split;\n        [ reflexivity | intros p n Hin; rewrite <- plus_n_O; assumption ].\n\n    (* INDUCTION CASE, a :: fired *)\n    - simpl.\n      unfold update_marking_post.\n\n      (* Specializes update_marking_post_aux_complete *)\n\n      assert (Hin_a_transs : In a (transs sitpn)).\n      {\n        specialize (Hincl_fired a (in_eq a fired)) as Hin_a_fired.\n        explode_well_defined_sitpn_state Hwell_def_s.\n        apply (Hincl_state_fired_transs a Hin_a_fired).\n      }\n\n      assert (Hnodup_postpl : NoDup (post_pl (lneighbours sitpn a))).\n      {\n        explode_well_defined_sitpn.\n        unfold NoDupInNeighbours in Hnodup_neigh.\n        specialize (Hnodup_neigh a Hin_a_transs) as Hnodup_w.\n        apply proj2 in Hnodup_w.\n        assumption.\n      }\n\n      specialize (update_marking_post_aux_complete\n                    (post_pl (lneighbours sitpn a)) sitpn a marking\n                    Hwell_def_sitpn Hin_a_transs Hperm_m\n                    (IsDecListCons_refl (post_pl (lneighbours sitpn a)))\n                    Hnodup_postpl)\n        as Hex_up_mark_post.\n\n      (* Explodes the newly-built hypothesis, then rewrites the goal. *)\n\n      inversion_clear Hex_up_mark_post as (m' & Hw).\n      inversion_clear Hw as (Hup_mark_post & H_defm'_w).\n      inversion_clear H_defm'_w as (Hdef_m' & Heq_fsm_fsm').\n      rewrite Hup_mark_post.\n      \n      (* Then specializes IHfired. *)\n\n      assert (Hperm_m' : Permutation (places sitpn) (fs m'))\n        by (rewrite Heq_fsm_fsm' in Hperm_m; assumption).\n      \n      assert (Hincl_fired' : incl fired (Sitpn.fired s))\n        by (apply (incl_cons_inv a fired (Sitpn.fired s) Hincl_fired)).\n\n      assert (Hnodup_fired' : NoDup fired)\n        by (apply NoDup_cons_iff, proj2 in Hnodup_fired; assumption).\n\n      specialize (IHfired m' Hwell_def_sitpn Hwell_def_s Hwell_def_s' Hspec\n                          Hperm_m' Hincl_fired' Hnodup_fired')\n        as Hex_map_up_post.\n\n      (* Explodes the newly-built hypothesis and instantiates\n         transient_marking. *)\n      \n      inversion_clear Hex_map_up_post as (transient_marking & Hw).\n      inversion_clear Hw as (Hmap_up_post & Hdef_tm).\n      exists transient_marking.\n\n      (* Splits and solves each branch of the goal. *)\n\n      repeat split.\n\n      (* Equality case, trivial. *)\n      + trivial.\n\n      (* Case transient_marking definition. *)\n      + intros p n Hin_pn_m.\n\n        (* Two cases, either p ∈ (post_pl a) or p ∉ (post_pl a) *)\n\n        assert (Hin_postpl_v := classic (In p (post_pl (lneighbours sitpn a)))).\n        inversion_clear Hin_postpl_v as [Hin_postpl | Hnot_in_postpl].\n\n        (* Case In p post_pl *)\n        -- specialize (Hdef_m' p n Hin_postpl Hin_pn_m) as Hin_pn_m'.\n           rewrite Nat.add_assoc.\n           apply (Hdef_tm p (n + post sitpn a p) Hin_pn_m').\n\n        (* Case ~In p post_pl *)\n        --\n          (* If p in not is post-places of a then there's no post arc\n             between p and a. *)\n\n          assert (Heq_post_0 : post sitpn a p = 0).\n          {\n            explode_well_defined_sitpn.\n            unfold AreWellDefinedPostEdges in Hwell_def_post.\n            specialize (Hwell_def_post a p Hin_a_transs).\n            apply proj2 in Hwell_def_post.\n            apply (Hwell_def_post Hnot_in_postpl).\n          }\n\n          rewrite Heq_post_0, Nat.add_0_l.\n\n          (* Rewrites In (p, n) marking with\n             update_marking_post_aux_not_in_post_places to get In (p, n) m'. *)\n\n          rewrite (update_marking_post_aux_not_in_post_places\n                     sitpn marking a (post_pl (lneighbours sitpn a))\n                     m' Hup_mark_post p Hnot_in_postpl) in Hin_pn_m.\n\n          (* Then completes the goal. *)\n\n          apply (Hdef_tm p n Hin_pn_m).          \n  Qed.\n  \nEnd MapUpdateMarkingPostComplete.\n\n(** * Completeness of the combination of map_update_marking functions. *)\n\nSection MapUpdateMarkingComplete.\n\n  (** ∀ t, ∀ l, t ∈ l ∧ NoDup l ⇒ post_sum l = post t + post_sum (l - {t}) \n   *  Needed to prove post_sum_eq_iff_incl. *)\n\n  Lemma post_sum_add_rm : \n    forall (sitpn : Sitpn)\n           (p : Place)\n           (l : list Trans)\n           (t : Trans),\n      In t l -> NoDup l -> post_sum sitpn p l = post sitpn t p + post_sum sitpn p (remove eq_nat_dec t l).\n  Proof.\n    intros sitpn p l;\n      functional induction (post_sum sitpn p l) using post_sum_ind;\n      intros a Hin_a_l Hnodup_l.\n    - inversion Hin_a_l.\n    - inversion_clear Hin_a_l as [Heq_at | Hin_a_tl].\n      + rewrite <- Heq_at.\n        simpl; case (Nat.eq_dec t t).\n        -- intro Heq_refl.\n           rewrite NoDup_cons_iff in Hnodup_l; apply proj1 in Hnodup_l.\n           specialize (not_in_remove_eq Nat.eq_dec t tail Hnodup_l) as Heq_rm.\n           rewrite Heq_rm; reflexivity.\n        -- intro Heq_diff; elim Heq_diff; reflexivity.\n      + simpl; case (Nat.eq_dec a t).\n        -- rewrite NoDup_cons_iff in Hnodup_l; apply proj1 in Hnodup_l.\n           specialize (not_in_in_diff t a tail (conj Hnodup_l Hin_a_tl)) as Hdiff_ta.\n           intro Heq_at; symmetry in Heq_at; contradiction.\n        -- intro Hdiff_at.\n           simpl; symmetry; rewrite Nat.add_comm.\n           rewrite <- Nat.add_assoc.\n           rewrite Nat.add_cancel_l; symmetry; rewrite Nat.add_comm.\n           rewrite NoDup_cons_iff in Hnodup_l; apply proj2 in Hnodup_l.\n           apply (IHn a Hin_a_tl Hnodup_l).\n  Qed.\n\n  (** For all list of transitions l and l', if l is a permutation \n   *  of l', then post_sum l = post_sum l'. *)\n\n  Lemma post_sum_eq_iff_incl :\n    forall (sitpn : Sitpn)\n           (p : Place)\n           (l l' : list Trans),\n      NoDup l ->\n      NoDup l' ->\n      (forall t : Trans, In t l <-> In t l') ->\n      post_sum sitpn p l = post_sum sitpn p l'.\n  Proof.\n    intros sitpn p l;\n      functional induction (post_sum sitpn p l) using post_sum_ind;\n      intros l' Hnodup_l Hnodup_l' Hequiv.\n    \n    (* BASE CASE *)\n    - functional induction (post_sum sitpn p l') using post_sum_ind.\n      + reflexivity.\n      + assert (Hin_eq : In t (t :: tail)) by apply in_eq.\n        rewrite <- Hequiv in Hin_eq; inversion Hin_eq.\n        \n    (* GENERAL CASE *)\n    - assert (Hin_eq : In t (t :: tail)) by apply in_eq.\n      rewrite Hequiv in Hin_eq.\n      specialize (post_sum_add_rm sitpn p l' t Hin_eq Hnodup_l') as Heq_postsum.\n      rewrite Heq_postsum.\n      rewrite Nat.add_cancel_l.\n      assert (Hequiv_tl : forall t0 : Trans, In t0 tail <-> In t0 (remove Nat.eq_dec t l')).\n      {\n        intro t0; split.\n        - intro Hin_tl; specialize (in_cons t t0 tail Hin_tl) as Hin_t0_ctl.\n          rewrite NoDup_cons_iff in Hnodup_l.\n          apply proj1 in Hnodup_l.\n          specialize (not_in_in_diff t t0 tail (conj Hnodup_l Hin_tl)) as Hdiff_tt0.\n          apply not_eq_sym in Hdiff_tt0.\n          rewrite Hequiv in Hin_t0_ctl.\n          rewrite in_remove_iff; apply (conj Hin_t0_ctl Hdiff_tt0).\n        - intro Hin_rm.\n          rewrite in_remove_iff in Hin_rm.\n          elim Hin_rm; clear Hin_rm; intros Hin_t0_l' Hdiff_t0t.\n          rewrite <- Hequiv in Hin_t0_l'.\n          inversion_clear Hin_t0_l' as [Heq_t0t | Hin_t0_tl].\n          + symmetry in Heq_t0t; contradiction.\n          + assumption.\n      }\n      \n      rewrite NoDup_cons_iff in Hnodup_l; apply proj2 in Hnodup_l.\n      specialize (nodup_if_remove l' Hnodup_l' t Nat.eq_dec) as Hnodup_rm.\n      apply (IHn (remove Nat.eq_dec t l') Hnodup_l Hnodup_rm Hequiv_tl). \n  Qed.\n  \n  (** Completeness lemma for map_update_marking functions. *)\n\n  Lemma map_update_marking_complete :\n    forall (sitpn : Sitpn)\n           (s s' : SitpnState)\n           (time_value : nat)\n           (env : Condition -> nat -> bool)\n           (frd : list Trans)\n           (m : list (Place * nat))\n           (transient_marking : list (Place * nat))\n           (final_marking : list (Place * nat)),\n      IsWellDefinedSitpn sitpn ->\n      IsWellDefinedSitpnState sitpn s ->\n      IsWellDefinedSitpnState sitpn s' ->\n      SitpnSemantics sitpn s s' time_value env rising_edge ->\n      (forall (p : Place) (n : nat),\n          In (p, n) m ->\n          In (p, n - pre_sum sitpn p frd) transient_marking) ->\n      (forall (p : Place) (n : nat),\n          In (p, n) transient_marking ->\n          In (p, n + post_sum sitpn p frd) final_marking) ->\n      Permutation (marking s) m ->\n      Permutation (fired s) frd ->\n      fs final_marking = fs m -> \n      NoDup final_marking ->\n      Permutation final_marking (marking s').\n  Proof.\n    intros sitpn s s' time_value env frd m transient_marking final_marking\n           Hwell_def_sitpn Hwell_def_s Hwell_def_s' Hspec\n           Hdef_tm Hdef_fm Hperm_ms Hperm_fs Heq_fsfm_fsm Hnodup_fm.\n\n    (* Strategy: apply NoDup_Permutation, then we need: \n       \n       - NoDup (marking s')\n       - ∀ x ∈ final_marking ⇔ x ∈ (marking s') *)\n\n    assert (Hnodup_ms' : NoDup (marking s')).\n    {\n      explode_well_defined_sitpn_state Hwell_def_s'.\n      explode_well_defined_sitpn.\n      unfold NoDupPlaces in Hnodup_places.\n      rewrite Hwf_state_marking in Hnodup_places.\n      apply (nodup_fst_split (marking s') Hnodup_places).\n    }\n\n    assert (Hequiv_fm_ms' : forall x : (Place * nat), In x final_marking <-> In x (marking s')).\n    {\n\n      assert (Heq_fsm_fsm' : fst (split (marking s)) = fst (split (marking s'))).\n      {\n        explode_well_defined_sitpn_state Hwell_def_s.\n        explode_well_defined_sitpn_state Hwell_def_s'.\n        rewrite <- Hwf_state_marking, <- Hwf_state_marking0.\n        reflexivity.\n      }\n\n      assert (Hnodup_fs : NoDup (fired s))\n        by (explode_well_defined_sitpn_state Hwell_def_s; assumption).\n\n      assert (Hnodup_frd : NoDup frd) by (rewrite <- Hperm_fs; assumption).\n\n      assert (Hequiv_frd : forall t : Trans, In t frd <-> In t (fired s))\n        by (intros t; rewrite Hperm_fs; reflexivity).      \n      \n      intros x; destruct x.\n\n      assert (Heq_presum : pre_sum sitpn p frd = pre_sum sitpn p (fired s))\n        by (apply (pre_sum_eq_iff_incl sitpn p frd (fired s) Hnodup_frd Hnodup_fs Hequiv_frd)).\n\n      assert (Heq_postsum : post_sum sitpn p frd = post_sum sitpn p (fired s))\n        by (apply (post_sum_eq_iff_incl sitpn p frd (fired s) Hnodup_frd Hnodup_fs Hequiv_frd)).\n\n      split; intros Hin.\n      \n      - (* Builds In (p, x) m, then specializes Hdef_tm and Hdef_fm to\n           get In (p, n - pre + post) final_marking *)\n          \n        specialize (in_fst_split p n final_marking Hin) as Hin_fsfm_ex.\n        unfold fs in Heq_fsfm_fsm.\n        rewrite Heq_fsfm_fsm in Hin_fsfm_ex.\n        apply in_fst_split_in_pair in Hin_fsfm_ex.\n\n        inversion_clear Hin_fsfm_ex as (x & Hin_m).\n\n        (* Specializes Hdef_tm then Hdef_fm. *)\n\n        specialize (Hdef_tm p x Hin_m) as Hin_tm.\n        specialize (Hdef_fm p (x - pre_sum sitpn p frd) Hin_tm) as Hin_fm.\n\n        (* Gets Sitpn semantics rule about definition of (marking s'), then deduces\n           In (p, n - pre + post) (marking s') from it. *)\n\n        inversion Hspec; clear H H0 H1 H2 H4 H5 H6 H7 H8 H9 H10 H11.\n        rename H3 into Hdef_ms'.\n\n        assert (Hin_ms : In (p, x) (marking s)) by (rewrite Hperm_ms; assumption).\n        \n        specialize (Hdef_ms' p x Hin_ms) as Hin_ms'.\n        \n        (* Gets (n = x - pre + post) by specializing nodup_same_pair. *)\n\n        assert (Hnodup_fsfm : NoDup (fst (split final_marking))).\n        {\n          explode_well_defined_sitpn.\n          explode_well_defined_sitpn_state Hwell_def_s.\n          unfold NoDupPlaces in Hnodup_places.\n          rewrite Hwf_state_marking in Hnodup_places.\n          assert (Hnodup_fsms : NoDup (fs (marking s))) by (unfold fs; assumption).\n          rewrite Hperm_ms in Hnodup_fsms.\n          unfold fs in Hnodup_fsms.\n          rewrite <- Heq_fsfm_fsm in Hnodup_fsms; assumption.\n        }\n        \n        assert (Hfst_eq : fst (p, n) = fst (p, x - pre_sum sitpn p frd + post_sum sitpn p frd))\n          by (simpl; reflexivity).\n        \n        specialize (nodup_same_pair\n                      final_marking Hnodup_fsfm\n                      (p, n)\n                      (p, x - pre_sum sitpn p frd + post_sum sitpn p frd)\n                      Hin Hin_fm Hfst_eq)\n          as Heq_pair.        \n        injection Heq_pair as Heq_nx.\n        rewrite Heq_nx.\n\n        (* Rewrites pre_sum frd and post_sum frd with pre_sum (fired s) \n           and post_sum (fired s) *)\n\n        rewrite Heq_presum, Heq_postsum; assumption.\n\n      - (* Builds In (p, x) (marking s), then specializes hyp. from Hspec to\n           get In (p, n - pre + post) (marking s') *)\n        \n        specialize (in_fst_split p n (marking s') Hin) as Hin_fsm_ex.\n        rewrite <- Heq_fsm_fsm' in Hin_fsm_ex.\n        apply in_fst_split_in_pair in Hin_fsm_ex.\n\n        inversion_clear Hin_fsm_ex as (x & Hin_ms).\n\n        (* Gets Sitpn semantics rule about definition of (marking s'), then deduces\n           In (p, n - pre + post) (marking s') from it. *)\n\n        inversion Hspec; clear H H0 H1 H2 H4 H5 H6 H7 H8 H9 H10 H11.\n        rename H3 into Hdef_ms'.\n        \n        specialize (Hdef_ms' p x Hin_ms) as Hin_ms'.\n        \n        (* Gets (n = x - pre + post) by specializing\n           nodup_same_pair. *)\n\n        assert (Hnodup_fs_ms' : NoDup (fst (split (marking s')))).\n        {\n          explode_well_defined_sitpn.\n          explode_well_defined_sitpn_state Hwell_def_s'.\n          unfold NoDupPlaces in Hnodup_places.\n          rewrite Hwf_state_marking in Hnodup_places.\n          assumption.\n        }\n        \n        assert (Hfst_eq : fst (p, n) = fst (p, x - pre_sum sitpn p (fired s) + post_sum sitpn p (fired s)))\n          by (simpl; reflexivity).\n        \n        specialize (nodup_same_pair\n                      (marking s') Hnodup_fs_ms'\n                      (p, n)\n                      (p, x - pre_sum sitpn p (fired s) + post_sum sitpn p (fired s))\n                      Hin Hin_ms' Hfst_eq)\n          as Heq_pair.        \n        injection Heq_pair as Heq_nx.\n        rewrite Heq_nx.\n\n        (* Specializes Hdef_tm then Hdef_fm to get\n           In (p, x - pre + post) final_marking *)\n        \n        assert (Hin_m : In (p, x) m) by (rewrite <- Hperm_ms; assumption).\n        specialize (Hdef_tm p x Hin_m) as Hin_tm.\n        specialize (Hdef_fm p (x - pre_sum sitpn p frd) Hin_tm) as Hin_fm.\n        \n        (* Rewrites pre_sum frd and post_sum frd with \n           pre_sum (fired s) and post_sum (fired s) *)\n\n        rewrite <- Heq_presum, <- Heq_postsum; assumption.\n    }\n\n    apply (NoDup_Permutation Hnodup_fm Hnodup_ms' Hequiv_fm_ms').    \n  Qed.\n  \nEnd MapUpdateMarkingComplete.\n", "meta": {"author": "viampietro", "repo": "sitpns", "sha": "9b81ca8a3299c51df561c42f40bc8bb42329446a", "save_path": "github-repos/coq/viampietro-sitpns", "path": "github-repos/coq/viampietro-sitpns/sitpns-9b81ca8a3299c51df561c42f40bc8bb42329446a/sitpn/simpl/SitpnRisingEdgeMarkingComplete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.23818812057617447}}
{"text": "From Undecidability.L.Tactics Require Import LTactics.\nFrom Undecidability.L Require Import UpToC.\nFrom Undecidability.L.Datatypes Require Export List.List_enc LNat LOptions LBool.\n\nSet Default Proof Using \"Type\".\n\nDefinition c__ntherror := 15.\nDefinition nth_error_time (X : Type) (A : list X) (n : nat) := (min (length A) n + 1) * c__ntherror. \nInstance termT_nth_error (X:Type) (Hx : registered X): computableTime' (@nth_error X) (fun l _ => (5, fun n _ => (nth_error_time l n, tt))). \nProof.\n  extract. solverec. all: unfold nth_error_time, c__ntherror; solverec. \nQed.\n\nDefinition c__length := 11.\nInstance termT_length X `{registered X} : computableTime' (@length X) (fun A _ => (c__length * (1 + |A|),tt)).\nProof.\nextract. solverec. all: unfold c__length; solverec.\nQed.\n\n\nInstance term_nth X (Hx : registered X) : computableTime' (@nth X) (fun n _ => (5,fun l lT => (1,fun d _ => (n*20+9,tt)))). \nProof.\n  extract.\n  solverec.\nQed.\n\nInstance term_repeat A `{registered A}: computableTime' (@repeat A) (fun _ _ => (5, fun n _ => (n * 12 + 4,tt))).\nProof.\n  extract. solverec.\nQed.\n\n\nSection Fix_X.\n  Context {X:Type} {intX : registered X}.\n\n  Variable X_eqb : X -> X -> bool.\n  Hypothesis X_eqb_spec : (forall (x y:X), Bool.reflect (x=y) (X_eqb x y)).\n    \n  Definition pos_nondec :=\n    fix pos_nondec (eqb: X -> X -> bool) (s : X) (A : list X) {struct A} : option nat :=\n      match A with\n      | [] => None\n      | a :: A0 =>\n        if eqb s a\n        then Some 0\n        else match pos_nondec eqb s A0 with\n            | Some n => Some (S n)\n            | None => None\n            end\n      end.\n\n  Lemma pos_nondec_spec (x:X) `{eq_dec X} A: pos_nondec X_eqb x A = pos x A.\n  Proof using X_eqb_spec.\n    induction A;[reflexivity|];cbn.\n    rewrite IHA. destruct (X_eqb_spec x a); repeat (destruct _; try congruence).\n  Defined. (* because other extract *)\n\n  Global Instance term_pos_nondec:\n    computable pos_nondec.\n  Proof.\n    extract.\n  Defined. (* because other extract *)\nEnd Fix_X.\n", "meta": {"author": "yforster", "repo": "coq-synthetic-computability", "sha": "b9523cb33180dc58b227432e60045cc38615b711", "save_path": "github-repos/coq/yforster-coq-synthetic-computability", "path": "github-repos/coq/yforster-coq-synthetic-computability/coq-synthetic-computability-b9523cb33180dc58b227432e60045cc38615b711/L/Datatypes/List/List_nat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.23818812057617444}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\n(**r: equivalence between bpf.model (with formal syntax + semantics) and bpf.src (for dx) *)\n\nFrom Coq Require Import Logic.FunctionalExtensionality ZArith Lia List.\nImport ListNotations.\nFrom compcert Require Import Integers Values Memory Memdata.\n\nFrom bpf.comm Require Import State Monad LemmaNat rBPFMonadOp.\n\nFrom bpf.model Require Import Semantics.\nFrom bpf.monadicmodel Require Import Opcode rBPFInterpreter.\n\n(*\nFrom bpf.equivalence Require Import switch decode_if. *)\n\nOpen Scope Z_scope.\n\nLemma Hrepr_eq: forall (a b:Z), (0 <= a <= 255)%Z -> (0 <= b <= 255)%Z ->\n  Int.repr a = Int.repr b <-> a = b.\nProof.\n  intros.\n  split; intro.\n  Transparent Int.repr.\n  unfold Int.repr in *.\n  inversion H1.\n  rewrite ! Int.Z_mod_modulus_eq in H3.\n  change Int.modulus with 4294967296%Z in H3.\n  rewrite ! Z.mod_small in H3.\n  all: try lia.\n\n  rewrite H1; reflexivity.\nQed.\n\n\nLemma Hrepr_neq: forall (a b:Z), (0 <= a <= 255)%Z -> (0 <= b <= 255)%Z ->\n  Int.repr a <> Int.repr b <-> a <> b.\nProof.\n  intros.\n  split; intro.\n  intro.\n  apply H1.\n  rewrite H2; reflexivity.\n  intro.\n  apply H1.\n  Transparent Int.repr.\n  unfold Int.repr in *.\n  inversion H2.\n  rewrite ! Int.Z_mod_modulus_eq in H4.\n  change Int.modulus with 4294967296%Z in H4.\n  rewrite ! Z.mod_small in H4.\n  all: lia.\nQed.\n\n\nOpen Scope nat_scope.\n\nLemma equivalence_between_check_mem:\n  forall st p ck v,\n    Semantics.check_mem p ck v st =rBPFInterpreter.check_mem p ck v st.\nProof.\n  intros.\n  unfold Semantics.check_mem, check_mem.\n  unfold Semantics.is_well_chunk_bool, is_well_chunk_bool.\n  unfold bindM, returnM.\n  destruct ck; try reflexivity.\nQed.\n\n\nLemma equivalence_between_Semantics_and_rBPFInterpreter:\n  Semantics.step = rBPFInterpreter.step.\nProof.\n  unfold Semantics.step, rBPFInterpreter.step.\n  unfold bindM, returnM.\n  apply functional_extensionality.\n\n  intros.\n  destruct eval_pc; [|reflexivity].\n  destruct p.\n  destruct eval_ins; [|reflexivity].\n  destruct p.\n  unfold decodeM, Decode.decode.\n\n  unfold get_opcode_ins,get_opcode, BinrBPF.get_opcode, byte_to_opcode, get_dst, int64_to_dst_reg.\n  unfold eval_reg, get_src64.\n\n  unfold bindM, returnM.\n\n  destruct BinrBPF.int64_to_dst_reg'; [| reflexivity].\n\n  remember (Z.to_nat (Int64.unsigned (Int64.and i0 (Int64.repr 255)))) as ins.\n  assert (Hins_255: ins <= 255). {\n    rewrite Heqins.\n    unfold Int64.and.\n\n    assert (Heq: (Int64.unsigned i0) = Z.of_nat (Z.to_nat(Int64.unsigned i0))). {\n      rewrite Z2Nat.id.\n      reflexivity.\n      assert (Hrange: (0 <= Int64.unsigned i0 < Int64.modulus)%Z) by apply Int64.unsigned_range.\n      lia.\n    }\n    rewrite Heq; clear.\n    change (Int64.unsigned (Int64.repr 255)) with (Z.of_nat (Z.to_nat 255%Z)) at 1.\n    rewrite LemmaNat.land_land.\n    assert (H: (Nat.land (Z.to_nat (Int64.unsigned i0)) (Z.to_nat 255)) <= 255%nat). {\n      rewrite Nat.land_comm.\n      rewrite LemmaNat.land_bound.\n      lia.\n    }\n    rewrite Int64.unsigned_repr; [ | change Int64.max_unsigned with 18446744073709551615%Z; lia].\n    lia.\n  }\n\n  assert (Heq_int_iff: Int.eq Int.zero (Int.and (Int.repr (Z.of_nat ins)) (Int.repr 8)) = (0 =? Nat.land ins  8)). {\n    assert (Hrange: Nat.land ins 8 <= 8).\n    rewrite Nat.land_comm.\n    rewrite land_bound. lia.\n    unfold Int.and, Int.zero.\n    rewrite Int.unsigned_repr; [| change Int.max_unsigned with 4294967295%Z; lia].\n    change (Int.unsigned (Int.repr 8)) with (Z.of_nat (Z.to_nat 8%Z)).\n    rewrite land_land.\n    change (Z.to_nat 8%Z) with 8.\n    destruct (0 =? Nat.land ins 8) eqn: Heq; [rewrite Nat.eqb_eq in Heq | rewrite Nat.eqb_neq in Heq].\n    rewrite Syntax.Int_eq_true.\n    apply Hrepr_eq. all: try lia.\n\n    rewrite Syntax.Int_eq_false.\n    apply Hrepr_neq. all: try lia.\n  }\n\nLtac or_simpl Hand :=\n  match goal with\n  | H: ?X = Nat.land ?Y ?Z |- ?W = ?Y \\/ _ =>\n    destruct (W =? Y) eqn: Hand; [rewrite Nat.eqb_eq in Hand; left; assumption | rewrite Nat.eqb_neq in Hand; right ]\n  end.\n\nLtac nat_land_compute :=\n  match goal with\n  | |- context [Nat.land ?X ?Y] =>\n    let res := eval compute in (Nat.land X Y) in\n      change (Nat.land X Y) with res; simpl\n  end.\n\nLtac destruct_match :=\n  match goal with\n  | |- ?X = ?X => reflexivity\n  | |- context[match match ?X with | _ => _ end with | _ => _ end] =>\n    destruct X; [ try reflexivity; try destruct_match | reflexivity]\n  | |- context[match match ?X with | _ => _ end with | _ => _ end] =>\n    destruct X; try reflexivity; try destruct_match\n  end.\n\n\nLtac nat_land_computeH :=\n  match goal with\n  | H: 0 <> Nat.land ?X ?Y |- _ =>\n    let res := eval compute in (Nat.land X Y) in\n      change (Nat.land X Y) with res in H; exfalso; apply H; reflexivity\n  end.\n\n  unfold reg64_to_reg32, State.eval_reg, get_src32, get_immediate, get_src, rBPFValues.sint32_to_vint, BinrBPF.get_immediate, rBPFValues.int64_to_sint32, int64_to_src_reg, eval_reg, reg64_to_reg32, bindM, returnM.\n  unfold Decode.get_instruction_alu32_imm, Decode.get_instruction_alu32_reg.\n  unfold step_opcode_alu32, get_opcode_alu32, byte_to_opcode_alu32, step_alu_binary_operation,eval_reg32, eval_src32, eval_reg, upd_reg, rBPFValues.val_intuoflongu, rBPFValues.val32_divu, rBPFValues.val32_modu, State.eval_reg, bindM, returnM.\n    rewrite Heq_int_iff. clear Heqins Heq_int_iff.\n    remember (Int.repr (Int64.unsigned (Int64.shru i0 (Int64.repr 32)))) as imm.\n\n  destruct (Nat.land ins 7 =? 0) eqn: Hland0; [rewrite Nat.eqb_eq in Hland0; rewrite Hland0 | rewrite Nat.eqb_neq in Hland0].\n  {\n    rewrite nat_land_7_eq in Hland0; [| lia].\n    destruct Hland0 as (m & Hins_eq).\n    rewrite Hins_eq in *.\n    unfold Decode.get_instruction_ld, step_opcode_mem_ld_imm, eval_ins_len, get_opcode_mem_ld_imm, byte_to_opcode_mem_ld_imm, eval_ins, get_immediate, upd_pc_incr,\n      bindM, returnM.\n    rewrite ! Nat.add_0_l in *.\n    do 32 (destruct m; [nat_land_compute; try reflexivity | ]).\n    destruct m; [nat_land_compute; try reflexivity | ].\n    lia.\n  }\n\n  destruct (Nat.land ins 7 =? 1) eqn: Hland1; [rewrite Nat.eqb_eq in Hland1; rewrite Hland1 | rewrite Nat.eqb_neq in Hland1].\n  {\n    rewrite nat_land_7_eq in Hland1; [| lia].\n    destruct Hland1 as (m & Hins_eq).\n    rewrite Hins_eq in *.\n    destruct BinrBPF.int64_to_src_reg'; [| reflexivity].\n    unfold Decode.get_instruction_ldx, get_offset, get_addr_ofs, step_opcode_mem_ld_reg, get_opcode_mem_ld_reg, byte_to_opcode_mem_ld_reg,\n      bindM, returnM.\n      do 33 (destruct m; [nat_land_compute; try reflexivity | ]).\n      lia.\n  }\n\n  destruct (Nat.land ins 7 =? 2) eqn: Hland2; [rewrite Nat.eqb_eq in Hland2; rewrite Hland2 | rewrite Nat.eqb_neq in Hland2].\n  {\n    rewrite nat_land_7_eq in Hland2; [| lia].\n    destruct Hland2 as (m & Hins_eq).\n    rewrite Hins_eq in *.\n    unfold Decode.get_instruction_st, get_offset, get_addr_ofs, step_opcode_mem_st_imm, get_opcode_mem_st_imm, byte_to_opcode_mem_st_imm,\n      bindM, returnM.\n      do 33 (destruct m; [nat_land_compute; try reflexivity | ]).\n      lia.\n  }\n\n  destruct (Nat.land ins 7 =? 3) eqn: Hland3; [rewrite Nat.eqb_eq in Hland3; rewrite Hland3 | rewrite Nat.eqb_neq in Hland3].\n  {\n    rewrite nat_land_7_eq in Hland3; [| lia].\n    destruct Hland3 as (m & Hins_eq).\n    rewrite Hins_eq in *.\n    destruct BinrBPF.int64_to_src_reg'; [| reflexivity].\n    unfold Decode.get_instruction_stx, BinrBPF.get_offset, get_offset, get_addr_ofs, step_opcode_mem_st_reg, get_opcode_mem_st_reg, byte_to_opcode_mem_st_reg,\n      bindM, returnM.\n      do 33 (destruct m; [nat_land_compute; try reflexivity | ]).\n      lia.\n  }\n\n  destruct (Nat.land ins 7 =? 4) eqn: Hland4; [rewrite Nat.eqb_eq in Hland4; rewrite Hland4 | rewrite Nat.eqb_neq in Hland4].\n  {\n    rewrite nat_land_7_eq in Hland4; [| lia].\n    destruct Hland4 as (m & Hins_eq).\n    rewrite Hins_eq in *.\n\n    destruct (0 =? Nat.land (4 + 8 * m) 8) eqn: Hand8; [rewrite Nat.eqb_eq in Hand8 | rewrite Nat.eqb_neq in Hand8].\n    - destruct m; [nat_land_compute; destruct Val.longofintu; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.longofintu; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.longofintu; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. destruct negb; [| reflexivity]. destruct Val.divu; try reflexivity. destruct Val.longofintu; try reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.longofintu; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.longofintu; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.longofintu; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.longofintu; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.longofintu; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. destruct negb; [| reflexivity]. destruct Val.modu; try reflexivity. destruct Val.longofintu; try reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.longofintu; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. destruct Int.ltu; [| reflexivity]. destruct Val.longofint; try reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      lia.\n    - destruct BinrBPF.int64_to_src_reg'; [| reflexivity].\n\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.longofintu; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.longofintu; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.longofintu; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct rBPFValues.comp_ne_32; [| reflexivity]. destruct Val.divu; try reflexivity. destruct Val.longofintu; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.longofintu; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.longofintu; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.longofintu; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.longofintu; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct rBPFValues.comp_ne_32; [| reflexivity]. destruct Val.modu; try reflexivity. destruct Val.longofintu; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.longofintu; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.longofintu; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct rBPFValues.compu_lt_32; [| reflexivity]. destruct Val.longofint; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [nat_land_computeH |].\n      lia.\n  }\n\nLtac destruct_if_reflexivity :=\n  match goal with\n  | |- ?X = ?X => reflexivity\n  | |- context[(if ?X then _ else _) ] =>\n    destruct X; try reflexivity\n  end.\n\n  destruct (Nat.land ins 7 =? 5) eqn: Hland5; [rewrite Nat.eqb_eq in Hland5; rewrite Hland5 | rewrite Nat.eqb_neq in Hland5].\n  {\n    rewrite nat_land_7_eq in Hland5; [| lia].\n    destruct Hland5 as (m & Hins_eq).\n    rewrite Hins_eq in *.\n    unfold Decode.get_instruction_branch_imm, BinrBPF.get_offset, Decode.get_instruction_branch_reg, get_offset, eval_immediate, step_opcode_branch, get_opcode_branch, byte_to_opcode_branch, upd_pc, BinrBPF.get_offset, upd_flag,\n      bindM, returnM.\n\n    destruct (0 =? Nat.land (5 + 8 * m) 8) eqn: Hand8; [rewrite Nat.eqb_eq in Hand8 | rewrite Nat.eqb_neq in Hand8].\n    - destruct m; [nat_land_compute; destruct_if_reflexivity | ].\n      destruct m; [nat_land_compute; destruct_if_reflexivity | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute | ]. destruct _bpf_get_call; try reflexivity.\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity | ].\n      destruct m; [inversion Hand8 | ].\n      lia.\n    - destruct BinrBPF.int64_to_src_reg'; [| reflexivity].\n\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute; unfold State.eval_reg; destruct_if_reflexivity; destruct_if_reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [nat_land_computeH |].\n      lia.\n  }\n\n  destruct (Nat.land ins 7 =? 6) eqn: Hland6; [rewrite Nat.eqb_eq in Hland6; rewrite Hland6 | rewrite Nat.eqb_neq in Hland6].\n  {\n    rewrite nat_land_7_eq in Hland6; [| lia].\n    destruct Hland6 as (m & Hins_eq).\n    rewrite Hins_eq in *.\n    reflexivity.\n  }\n\n  destruct (Nat.land ins 7 =? 7) eqn: Hland7; [rewrite Nat.eqb_eq in Hland7; rewrite Hland7 | rewrite Nat.eqb_neq in Hland7].\n  {\n    rewrite nat_land_7_eq in Hland7; [| lia].\n    destruct Hland7 as (m & Hins_eq).\n    rewrite Hins_eq in *.\n    unfold Decode.get_instruction_alu64_imm, Decode.get_instruction_alu64_reg, eval_immediate, step_opcode_alu64, get_opcode_alu64, byte_to_opcode_alu64, upd_reg, rBPFValues.val64_divlu, rBPFValues.val64_modlu,\n      bindM, returnM.\n\n    destruct (0 =? Nat.land (7 + 8 * m) 8) eqn: Hand8; [rewrite Nat.eqb_eq in Hand8 | rewrite Nat.eqb_neq in Hand8].\n    - destruct m; [nat_land_compute; destruct Val.addl; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.subl; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.mull; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. destruct_if_reflexivity. destruct Val.divlu; try reflexivity. destruct v; try reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.orl; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.andl; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. destruct_if_reflexivity. destruct Val.shll; try reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. destruct_if_reflexivity. destruct Val.shrlu; try reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.negl; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. destruct_if_reflexivity. destruct Val.modlu; try reflexivity. destruct v; try reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m; [nat_land_compute; destruct Val.xorl; try reflexivity |].\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. destruct_if_reflexivity. destruct Val.shrl; try reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [inversion Hand8 | ].\n      lia.\n    - destruct BinrBPF.int64_to_src_reg'; [| reflexivity].\n\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.addl; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.subl; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.mull; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. unfold State.eval_reg, Regs.val64_zero; destruct_if_reflexivity. destruct Val.divlu; try reflexivity. destruct v; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.orl; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.andl; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. unfold State.eval_reg, rBPFValues.val_intuoflongu; destruct_if_reflexivity. destruct Val.shll; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute.  unfold State.eval_reg, rBPFValues.val_intuoflongu; destruct_if_reflexivity. destruct Val.shrlu; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. unfold State.eval_reg, Regs.val64_zero; destruct_if_reflexivity. destruct Val.modlu; try reflexivity. destruct v; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. destruct Val.xorl; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. unfold State.eval_reg. destruct Regs.eval_regmap; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. unfold State.eval_reg, rBPFValues.val_intuoflongu; destruct_if_reflexivity. destruct Val.shrl; try reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [nat_land_computeH |].\n      destruct m.\n      { nat_land_compute. reflexivity. }\n      destruct m; [nat_land_computeH |].\n      lia.\n  }\n\n  exfalso.\n\n  remember (Nat.land ins 7) as Hand7.\n  assert (Hand7_le: Hand7 <= 7). {\n    rewrite HeqHand7.\n    rewrite Nat.land_comm.\n    rewrite land_bound.\n    lia.\n  }\n\n  lia.\nQed.\n\n\nClose Scope nat_scope.\n\nLemma equivalence_between_formal_and_dx_aux:\n  forall f,\n    Semantics.bpf_interpreter_aux f = rBPFInterpreter.bpf_interpreter_aux f.\nProof.\n  unfold Semantics.bpf_interpreter_aux, rBPFInterpreter.bpf_interpreter_aux.\n  rewrite equivalence_between_Semantics_and_rBPFInterpreter.\n  reflexivity.\nQed.\n\nTheorem equivalence_between_formal_and_dx:\n  forall f,\n    Semantics.bpf_interpreter f = rBPFInterpreter.bpf_interpreter f.\nProof.\n  intros.\n  unfold Semantics.bpf_interpreter, rBPFInterpreter.bpf_interpreter.\n  rewrite equivalence_between_formal_and_dx_aux.\n  reflexivity.\nQed.\n\nClose Scope Z_scope.", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/equivalence/equivalence1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.23817041170877612}}
{"text": "Load \"IND_MORPHISMS\".\n\n \n\n(***********Indistinguishability Axioms*******************************************)\n(************************************************************************************)\n \n\n(*********************FUNCApp***************************************************)\n(*******************************************************************************)\n\n Section  Core_Axioms.\nVariable fmb4 : message -> message -> message -> message -> Bool.\nVariable fm: message.\nVariable fb: Bool.\nVariable f1 : message  -> message.\nVariable f2b : message  -> message -> Bool.\nVariable f2m : message ->  message -> message.\nVariable f3b: message -> message -> message -> Bool.\nVariable f3bm: Bool -> message -> message -> message.\nVariable f3m : message -> message -> message -> message .\nVariable f4b: message -> message -> message -> message -> Bool.\nVariable f4m: message -> message -> message -> message -> message.\nVariable g2: Bool -> Bool -> Bool.\nVariable g3 : Bool -> Bool -> Bool -> Bool.\n (*************************************************************************************************)\nAxiom FUNCApp_att4: forall (p1 p2 p3 p4 : nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ bol (fmb4 (ostomsg (getelt_at_pos p1 ml1)) (ostomsg (getelt_at_pos  p2 ml1)) (ostomsg (getelt_at_pos  p3 ml1)) (ostomsg (getelt_at_pos  p4 ml1)))] )\n ~ (ml2 ++ [ bol (fmb4 (ostomsg (getelt_at_pos  p1 ml2)) (ostomsg (getelt_at_pos p2 ml2)) (ostomsg (getelt_at_pos  p3 ml2)) (ostomsg (getelt_at_pos p4 ml2)))] ).\n\nAxiom FUNCApp_fm: forall  {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ msg  fm] )\n ~ (ml2 ++ [ msg fm] ).\nAxiom FUNCApp_fb: forall  {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ bol  fb] )\n ~ (ml2 ++ [ bol fb] ).\n\nAxiom FUNCApp_f1: forall (p:nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ msg  (f1 (ostomsg (getelt_at_pos p ml1)))] ) ~ (ml2 ++ [ msg  (f1 (ostomsg (getelt_at_pos p ml2)))] ).\n\n\nAxiom FUNCApp_f2b: forall (p1 p2 :nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ bol  (f2b (ostomsg (getelt_at_pos p1 ml1)) (ostomsg (getelt_at_pos p2 ml1)))] ) ~ (ml2 ++ [ bol  (f2b (ostomsg (getelt_at_pos p1 ml2)) (ostomsg (getelt_at_pos p2 ml2)))] ).\n\nAxiom FUNCApp_f2m: forall (p1 p2 :nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ msg  (f2m (ostomsg (getelt_at_pos p1 ml1)) (ostomsg (getelt_at_pos p2 ml1)))] ) ~ (ml2 ++ [ msg (f2m (ostomsg (getelt_at_pos p1 ml2)) (ostomsg (getelt_at_pos p2 ml2)))] ).\n\n\n Axiom FUNCApp_f3b: forall (p1 p2 p3 :nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ bol  (f3b (ostomsg (getelt_at_pos p1 ml1)) (ostomsg (getelt_at_pos p2 ml1)) (ostomsg (getelt_at_pos p3 ml1)))] ) ~ (ml2 ++ [ bol  (f3b (ostomsg (getelt_at_pos p1 ml2)) (ostomsg (getelt_at_pos p2 ml2)) (ostomsg (getelt_at_pos p3 ml2)))] ).\n\n Axiom FUNCApp_f3bm: forall (p1 p2 p3 :nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ msg  (f3bm (ostobol (getelt_at_pos p1 ml1)) (ostomsg (getelt_at_pos p2 ml1)) (ostomsg (getelt_at_pos p3 ml1)))] ) ~ (ml2 ++ [ msg  (f3bm (ostobol (getelt_at_pos p1 ml2)) (ostomsg (getelt_at_pos p2 ml2)) (ostomsg (getelt_at_pos p3 ml2)))] ).\n\n Axiom FUNCApp_f3m: forall (p1 p2 p3 :nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ msg  (f3m (ostomsg (getelt_at_pos p1 ml1)) (ostomsg (getelt_at_pos p2 ml1)) (ostomsg (getelt_at_pos p3 ml1)))] ) ~ (ml2 ++ [ msg  (f3m (ostomsg (getelt_at_pos p1 ml2)) (ostomsg (getelt_at_pos p2 ml2)) (ostomsg (getelt_at_pos p3 ml2)))] ).\n\nAxiom FUNCApp_f4b: forall (p1 p2 p3 p4 :nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ bol  (f4b (ostomsg (getelt_at_pos p1 ml1)) (ostomsg (getelt_at_pos p2 ml1)) (ostomsg (getelt_at_pos p3 ml1)) (ostomsg (getelt_at_pos p4 ml1)))] ) ~ (ml2 ++  [ bol  (f4b (ostomsg (getelt_at_pos p1 ml2)) (ostomsg (getelt_at_pos p2 ml2)) (ostomsg (getelt_at_pos p3 ml2)) (ostomsg (getelt_at_pos p4 ml2)))] ).\n\nAxiom FUNCApp_f4m: forall (p1 p2 p3 p4 :nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ msg  (f4m (ostomsg (getelt_at_pos p1 ml1)) (ostomsg (getelt_at_pos p2 ml1)) (ostomsg (getelt_at_pos p3 ml1)) (ostomsg (getelt_at_pos p4 ml1)))] ) ~ (ml2 ++  [ msg  (f4m (ostomsg (getelt_at_pos p1 ml2)) (ostomsg (getelt_at_pos p2 ml2)) (ostomsg (getelt_at_pos p3 ml2)) (ostomsg (getelt_at_pos p4 ml2)))] ).\nAxiom FUNCApp_g2: forall (p1 p2 :nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ bol  (g2 (ostobol (getelt_at_pos p1 ml1)) (ostobol (getelt_at_pos p2 ml1)))] ) ~ (ml2 ++ [ bol  (g2 (ostobol (getelt_at_pos p1 ml2)) (ostobol (getelt_at_pos p2 ml2)))] ).\n\n\n Axiom FUNCApp_g3: forall (p1 p2 p3 :nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2 ) -> (ml1 ++ [ bol  (g3 (ostobol (getelt_at_pos p1 ml1)) (ostobol (getelt_at_pos p2 ml1)) (ostobol (getelt_at_pos p3 ml1)))] ) ~ (ml2 ++ [ bol  (g3 (ostobol (getelt_at_pos p1 ml2)) (ostobol (getelt_at_pos p2 ml2)) (ostobol (getelt_at_pos p3 ml2)))] ).\nAxiom FUNCApp_sublist:  forall (m n:nat) {n1} (ml1 ml2:mylist n1), (ml1 ~ ml2) -> (ml1 ++ [msg (f  (sublist m n (conv_mylist_listm ml1)))]) ~ (ml2 ++ [msg (f (sublist m n (conv_mylist_listm ml2)))]).\n\n(**************************************************************************************************)\nAxiom FUNCApp_const: forall (n m :nat) (ml1 ml2: mylist n) (a: mylist m), (ml1 ~ ml2) -> (ml1 ++ (const  a ml1 )) ~ (ml2 ++ (const a ml2)).\n\nAxiom FUNCApp_appelt:  forall (n p :nat) (ml1 ml2: mylist n), (ml1 ~ ml2) -> (ml1 ++ [getelt_at_pos  p ml1]  ) ~ (ml2 ++ [getelt_at_pos  p ml2]).\n\nAxiom FUNCApp_EQ_M: forall (p1 p2:nat) {n} (ml1 ml2: mylist n), (ml1 ~ ml2) -> (ml1 ++ ([ bol (EQ_M_at_pos  p1 p2 ml1) ])) ~ (ml2 ++ ([ bol (EQ_M_at_pos  p1 p2 ml2)])).\n(**\nAxiom FUNCApp_EQ_M1: forall (p p1 p2  :nat) {n}(ml1 ml2 :mylist n), (ml1 ~ ml2) -> (@insert_at_pos p  ( bol (EQ_M_at_pos (msg O) p1 p2 ml1)) n  ml1) ~ (@insert_at_pos p ( bol (EQ_M_at_pos (msg O) p1 p2 ml2)) n ml2). **)\nAxiom FUNCApp_EQ_B: forall ( p1 p2:nat) {n} (ml1 ml2: mylist n), (ml1 ~ ml2) ->  (ml1 ++  [ bol (EQ_B_at_pos  p1 p2 ml1)])  ~ (ml2 ++  [ bol (EQ_B_at_pos  p1 p2 ml2)])  .\n\n(**Axiom FUNCApp_EQ_B1: forall ( p p1 p2:nat) {n} (ml1 ml2: mylist n), (ml1 ~ ml2) ->  (@insert_at_pos p  ( bol (EQ_B_at_pos (bol TRue) p1 p2 ml1)) n  ml1)  ~ (@insert_at_pos p  ( bol (EQ_B_at_pos (bol TRue) p1 p2 ml1)) n  ml2) .**)\n\nAxiom FUNCApp_negpos: forall (p :nat) {n} (ml1 ml2: mylist n), (ml1 ~ ml2) -> (ml1 ++ (neg_at_pos p ml1)) ~ (ml2 ++ (neg_at_pos p ml2)).\n\nAxiom FUNCApp_ifmnespair : forall ( p1 p2 p3 p4 : nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2) -> (ml1 ++ [msg (ifm_nespair  p1 p2 p3 p4 ml1)]) ~(ml2 ++ [msg (ifm_nespair  p1 p2 p3 p4 ml2)]).\n\nAxiom FUNCApp_ifmpair: forall ( p1 p2 p3 p4  : nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2) -> (ml1 ++ [msg (ifm_pair  p1 p2 p3 p4 ml1)]) ~ (ml2 ++ [ msg (ifm_pair p1 p2 p3 p4 ml2)]). \n\n(*Axiom FUNCApp_expatpos: forall (n p p1 p2 p3 : nat) (ml1 ml2 : mylist n), (ml1 ~ ml2) -> ( app_elt_pos (msg (exp_at_pos (msg O) p1 p2 p3  ml1)) p ml1 ) ~ ( app_elt_pos (msg (exp_at_pos (msg O) p1 p2 p3  ml2)) p ml2 ) .  *)\n\nAxiom FUNCApp_expatpos: forall (p1 p2 p3 : nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2) -> ( ml1 ++ [msg (exp_at_pos  p1 p2 p3  ml1)]) ~ ( ml2 ++ [msg (exp_at_pos  p1 p2 p3  ml2)]) .\n(**\nAxiom FUNCApp_expatpos1: forall (p p1 p2 p3 : nat) {n} (ml1 ml2 : mylist n), (ml1 ~ ml2) -> ( @insert_at_pos p  (msg (exp_at_pos (msg O) p1 p2 p3  ml1)) n ml1 ) ~ ( @insert_at_pos p  (msg (exp_at_pos (msg O) p1 p2 p3  ml2)) n ml2 ).\n**)\n\n\n\nAxiom FUNCApp_att : forall {n} (ml1 ml2: mylist n) (l1 l2 :list message ), (ml1 ~ ml2) -> ([msg (f l1)] ++ ml1) ~ ([msg (f l2)] ++ ml2).\n\nAxiom FUNCApp_reveal:  forall ( p:nat) {n} (ml1 ml2 : mylist n) , (ml1 ~ ml2) -> ([msg (reveal_at_pos p ml1)] ++ml1   ) ~ ([msg (reveal_at_pos p ml2)] ++ml2 ).\n\nAxiom FUNCApp_to:  forall (p:nat) {n} (ml1 ml2 : mylist n) , (ml1 ~ ml2) -> ([msg (to_at_pos p ml1)] ++ ml1)  ~ ([msg (to_at_pos p ml2)] ++ ml2).\n\nAxiom FUNCApp_act:  forall (p:nat) {n} (ml1 ml2 : mylist n) , (ml1 ~ ml2) -> ([msg (act_at_pos p ml1)] ++ ml1)  ~ ([msg (act_at_pos p ml2)] ++ ml2).\n\nAxiom FUNCApp_new : forall {n} (ml1 ml2 : mylist n) , (ml1 ~ ml2) -> ([msg new ] ++ ml1) ~ ([msg new ] ++ ml2).\nAxiom FUNCApp_O : forall {n} (ml1 ml2 : mylist n) , (ml1 ~ ml2) -> ( ml1 ++ [msg O]) ~ (ml2 ++ [msg O]).\nAxiom FUNCApp_acc : forall {n} (ml1 ml2 : mylist n) , (ml1 ~ ml2) -> ( ml1 ++ [msg acc]) ~ (ml2 ++ [msg acc]).\nAxiom FUNCApp_session : forall ( m: nat ) {n} (ml1 ml2 : mylist m) , (ml1 ~ ml2) -> ([msg (i n) ] ++ ml1) ~ ([msg (i n) ] ++ ml2).\n(**\nAxiom FUNCApp_andB1: forall (p p1 p2:nat)  {n}(ml1 ml2: mylist n), (ml1 ~ ml2) ->  (@insert_at_pos p  ( bol (andB_at_pos (msg O) p1 p2 ml1)) n  ml1)  ~ (@insert_at_pos p  ( bol (andB_at_pos (msg O) p1 p2 ml1)) n  ml2) .\n**)\nAxiom FUNCApp_andB : forall (p1 p2 :nat) {m} (ml1 ml2 : mylist m), (ml1 ~ ml2) -> (ml1 ++ [bol (andB_at_pos p1 p2 ml1)]) ~  (ml2 ++ [bol (andB_at_pos p1 p2 ml2)]).\nAxiom FUNCApp_notB : forall (p :nat) {m} (ml1 ml2:mylist m), (ml1 ~ ml2) -> (ml1 ++ [bol (notB_at_pos  p ml1)]) ~ (ml2 ++ [bol (notB_at_pos p ml2)]).\nAxiom FUNCApp_m : forall (p :nat) {m} (ml1 ml2:mylist m), (ml1 ~ ml2) -> ( [ msg (m_at_pos  p ml1)] ++ ml1) ~  (  [msg (m_at_pos  p ml2) ] ++ ml2).\n(**\nAxiom FUNCApp_exptrm : forall (p n n1:nat) {m} (ml1 ml2:mylist m), (ml1~ml2) -> ((occexp_in_mylist n n1 ml1) = true) ->  ((occexp_in_mylist n n1 ml2) = true)  -> (@insert_at_pos p ( msg (exp (G n) (g n) (r n1))) m ml1) ~ (@insert_at_pos p ( msg (exp (G n) (g n) (r n1))) m ml2).\n**)\nAxiom FUNCApp_elt :   forall (p p1  :nat) {m} (ml1 ml2:mylist m), (ml1~ml2) ->  (ml1 ++ [getelt_at_pos  p1 ml1 ] ) ~ (ml2 ++ [  getelt_at_pos p1 ml2]).\n(*******************************add closed term at pos p***************************************)\n\nAxiom FUNCApp_os : forall (p n :nat) (t: oursum) (ml1 ml2:mylist n),  \n                     ml1 ~ ml2 -> (clos_os t = true) -> (@insert_at_pos p t n ml1) ~ (@insert_at_pos p t n ml2).\n\n\n(*******************RESTR******************************************************)\n(******************************************************************************)\n\n(****************** Ind closed under projections ****************)\nAxiom RESTR_proj : forall ( p :nat) {m} (ml1 ml2 :mylist m), ml1 ~ ml2 -> (proj_at_pos p ml1) ~ (proj_at_pos p ml2).\n(****************** Ind closed under permutations ****************)\nAxiom RESTR_swap : forall (p1 p2 : nat) {n} (ml1 ml2 : mylist n), ml1~ ml2 -> (swap_mylist p1 p2 ml1) ~ (swap_mylist p1 p2 ml2).\n\n\n\nAxiom FUNCApp_dropls: forall {n} (ml1 ml2: mylist n), ml1 ~ ml2 -> (droplastsec ml1) ~ (droplastsec ml2).\n(**\nAxiom FUNCApp_droplt: forall {n} (ml1 ml2: mylist n), ml1 ~ ml2 -> (droplast3rd ml1) ~ (droplast3rd ml2).\n\nAxiom RESTR_Drop: forall (n :nat)  (ml1 ml2 : mylist n) , ml1 ~ ml2 ->  (dropone ml1) ~ (dropone ml2).\nAxiom RESTR1 : forall (n m:nat)  (l1 l1' : mylist n) (l2 l2': mylist m) (x y: oursum), (l1 ++ [x] ++l2) ~ (l1'++ [y]++l2') -> (l1 ++ l2) ~ (l1'++l2').\n**)\n(********************Ind closed under permutations **********************)\n(**\n\nAxiom RESTR_SWAP : forall (p1 p2 : nat) {n} (ml1 ml2 : mylist n), ml1~ ml2 -> (swap_mylist p1 p2 ml1) ~ (swap_mylist p1 p2 ml2).\nAxiom RESTR_rev: forall (n:nat) (ml1 ml2: mylist n) , ml1 ~ ml2 -> (reverse ml1) ~ (reverse ml2).\nAxiom RESTR2 : forall (n1 n2 n3 :nat) (l1 l1' : mylist n1) (l2 l2' : mylist n2) (l3 l3' : mylist n3) (x1 x2 y1 y2 : oursum), (l1 ++ [x1] ++ l2 ++ [x2] ++ l3) ~ (l1' ++ [y1] ++ l2' ++ [y2] ++ l3') ->\n (l1 ++ [x2] ++ l2 ++ [x1] ++ l3) ~ (l1' ++ [y2] ++ l2' ++ [y1] ++ l3').\n**)\n(********************************************************************************)\nAxiom TFDIST: not ([bol TRue]~[bol FAlse]).\n\n\n(*****Axioms for if_then_else *****************)\n\n(**IFSAME**)\n\n\nAxiom IFSAME_M: forall (b:Bool) (x : message), (if_then_else_M b x x) # x.\nAxiom IFSAME_B: forall (b:Bool) (b1 : Bool),  (if_then_else_B b b1 b1) ## b1.\n\n(**IFEVAL**)\n\nAxiom IFEVAL_B : forall (b1 b2 : Bool)(n:nat),  (if_then_else_B (Bvar n) b1 b2) ## (if_then_else_B (Bvar n) ([n := TRue] b1) ([n := FAlse] b2)).\nAxiom IFEVAL_M : forall (t1 t2 : message) (n:nat),  (if_then_else_M (Bvar n) t1 t2) #(if_then_else_M (Bvar n) ((n := TRue) t1) ((n := FAlse) t2)).\nAxiom IFEVAL_B' : forall (b b1 b2 : Bool),  (if_then_else_B b b1 b2) ## (if_then_else_B b (subbol_bol' b TRue b1) (subbol_bol' b FAlse b2)).\n \nAxiom IFEVAL_M' : forall (b:Bool)(t1 t2  : message),  (if_then_else_M b t1 t2) #(if_then_else_M b (subbol_msg' b TRue t1) (subbol_msg' b FAlse t2)).\n\n\n(**IFTRue**)\n\nAxiom IFTRUE_M : forall (x y : message),  (if_then_else_M TRue x y) # x .\nAxiom IFTRUE_B : forall (b1 b2 : Bool), (if_then_else_B TRue b1 b2) ## b1.\n\n\n(**IFFAlse**)\n\nAxiom IFFALSE_M: forall (x y : message), (if_then_else_M FAlse x y) # y.\nAxiom IFFALSE_B: forall (b1 b2 : Bool),  (if_then_else_B FAlse b1 b2) ## b2.\n\n(********************************************IFBRANCH******************************************)\n(**********************************************************************************************)\n\nAxiom IFBRANCH_M: forall (n: nat) (ml1 ml2 : mylist n) (b b' : Bool)(x x' y y':message), (ml1 ++ [ bol b ; msg x] ) ~  ( ml2 ++ [ bol b'; msg x'])  ->  (ml1 ++ [bol b ; msg y ] ) ~( ml2 ++ [bol b' ; msg y'])\n-> (ml1 ++ [bol b ;msg (if_then_else_M b x y)])~ ( ml2 ++ [bol b' ; msg (if_then_else_M b' x' y')]).\n\nAxiom IFBRANCH_B: forall (n: nat) (ml1 ml2 : mylist n) (b b' : Bool)(b1 b1' b2 b2':Bool), (ml1 ++ [bol b ;bol b1]) ~ ( ml2 ++ [bol b' ; bol b1'])  ->  (ml1 ++ [ bol b; bol b2]) ~( ml2 ++ [bol b'; bol b2'])\n-> (ml1 ++ [ bol b ;bol (if_then_else_B b b1 b2)])~ (  ml2 ++ [bol b' ; bol (if_then_else_B b' b1' b2')] ).\n\n(*******************************Axioms for Fresh names*****************************************)\n(**********************************************************************************************)\n\nAxiom FRESHNEQ: forall (n : nat) (m : message), ((clos_msg m) = true)/\\ ( (Fresh [n] [msg m]) = true) ->[bol (EQ_M (N n) m)]~ [bol FAlse] .\n\nAxiom FRESHIND: forall (n n1 n2:nat) (v w: mylist n), ((clos_mylist (v++w)) = true) /\\ ( (Fresh [ n1] (v++w)) = true) /\\ ( (Fresh [ n2] (v++w)) = true) /\\  (v ~ w) <-> ((msg (r n1) ) +++ v) ~ (( msg (r n2)) +++w ) .\nAxiom FRESHIND_rs : forall (n n1 n2:nat) (v w: mylist n), ((clos_mylist (v++w)) = true) /\\ ( (Fresh [ n1] (v++w)) = true) /\\ ( (Fresh [ n2] (v++w)) = true) /\\  (v ~ w) <-> ((msg  (N n1)) +++ v) ~ (( msg  (N n2)) +++w ) .\n\n\n(*****************************************************************************************************************************************************************)\n(****Fresh [n;n1;n2;n3]-> [G(n); g(n);g(n)^(r (n1));g(n)^(r (n2)); g(n)^(r (n1))(r (n2))] ~[G(n); g(n);g(n)^(r (n1));g(n)^(r (n2)); g(n)^(r (n3))]*****************)\n\nAxiom DDH : forall (n n1 n2 n3: nat),  (Fresh [ n ; n1 ;  n2  ; n3 ] []) = true-> \n[ msg (G n) ; msg (g n) ; msg (exp (G n) (g n) (r  n1)) ; msg (exp (G n) (g n) (r  n2)) ; msg (exp (G n) (exp (G n) (g n) (r  n1)) (r  n2))]\n~ [msg (G n) ; msg (g n) ; msg (exp (G n) (g n) (r  n1)) ; msg (exp (G n) (g n) (r n2)) ; msg (exp (G n) (g n) (r n3))]  .\n\nGoal (f [ (if_then_else_M TRue O O)]) # (f [ O]).\nrewrite IFTRUE_M. reflexivity.  Qed. \n Check f.\nEnd Core_Axioms.\n\n\nEval compute in sublist 0 3 [ msg O; msg  (N 1); msg (N 2)].\nCheck f.", "meta": {"author": "ajayeeralla", "repo": "compSoundProofs", "sha": "3d85841b55bbff36e5884e07f62a60ea95645969", "save_path": "github-repos/coq/ajayeeralla-compSoundProofs", "path": "github-repos/coq/ajayeeralla-compSoundProofs/compSoundProofs-3d85841b55bbff36e5884e07f62a60ea95645969/CORE_AXIOMS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.3738758157951908, "lm_q1q2_score": 0.23817040797301178}}
{"text": "Require Import Coqlib.  \nRequire Import Maps. \n\nRequire Import Integers.\nOpen Scope Z_scope.\nImport ListNotations.\n\nSet Asymmetric Patterns.\n\nRequire Import state. \nRequire Import language.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import logic.\n\nOpen Scope nat.\nOpen Scope code_scope.\n\n(*+ soundness of instruction rule +*)\nDefinition ins_sound p q i :=\n  forall s,\n    s |= p -> (exists s', (Q__ s (cntrans i) s') /\\ s' |= q).\n\n(*+ soundness of instruction sequence rule +*)\nInductive safety_insSeq : CodeHeap -> State -> Label -> Label -> asrt -> funspec -> Prop :=\n| i_seq : forall C S pc npc q Spec i,\n    C pc = Some (cntrans i) -> \n    (\n      exists S' pc' npc',\n        P__ C (S, pc, npc) (S', pc', npc')\n    ) ->\n    (\n      forall S' pc' npc',\n        P__ C (S, pc, npc) (S', pc', npc') ->\n        safety_insSeq C S' pc' npc' q Spec\n    ) ->\n    safety_insSeq C S pc npc q Spec\n\n| call_seq : forall C S pc npc q Spec f,\n    C pc = Some (ccall f) ->\n    (\n      exists S1 S2 pc1 npc1 pc2 npc2,\n        P__ C (S, pc, npc) (S1, pc1, npc1) /\\\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2)\n    ) ->\n    (\n      forall S1 S2 pc1 npc1 pc2 npc2,\n        P__ C (S, pc, npc) (S1, pc1, npc1) ->\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n        (\n          exists fp fq L r,\n            pc2 = f /\\ npc2 = f +ᵢ ($ 4) /\\\n            Spec f = Some (fp, fq) /\\ S2 |= (fp L) ** r /\\\n            (forall S', S' |= (fq L) ** r ->\n                        safety_insSeq C S' (pc +ᵢ ($ 8)) (pc +ᵢ ($ 12)) q Spec) /\\\n            (forall S', S' |= fq L -> get_R (getregs S') r15 = Some (W pc))\n        )\n    ) ->\n    safety_insSeq C S pc npc q Spec\n\n| jmpl_seq : forall C S pc npc q aexp rd Spec,\n    C pc = Some (cjumpl aexp rd) ->\n    (\n      exists S1 S2 pc1 npc1 pc2 npc2,\n        P__ C (S, pc, npc) (S1, pc1, npc1) /\\\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2)\n    ) ->\n    (\n      forall S1 S2 pc1 npc1 pc2 npc2,\n        P__ C (S, pc, npc) (S1, pc1, npc1) ->\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n        (\n          exists fp fq L r,\n            Spec pc2 = Some (fp, fq) /\\ S2 |= (fp L) ** r /\\ (fq L) ** r ==> q /\\\n            npc2 = pc2 +ᵢ ($ 4)\n        )\n    ) ->\n    safety_insSeq C S pc npc q Spec\n\n| be_seq : forall C S pc npc q f Spec,\n    C pc = Some (cbe f) ->\n    (\n      exists S1 S2 pc1 npc1 pc2 npc2,\n        P__ C (S, pc, npc) (S1, pc1, npc1) /\\\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2)\n    ) ->\n    (\n      forall S1 S2 pc1 npc1 pc2 npc2,\n        P__ C (S, pc, npc) (S1, pc1, npc1) ->\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n        (\n          exists v, get_R (getregs S) z = Some (W v) /\\\n          (\n            v <> ($ 0) ->\n            (\n              exists fp fq L r,\n                Spec pc2 = Some (fp, fq) /\\ S2 |= (fp L) ** r /\\\n                (fq L ** r) ==> q /\\ npc2 = pc2 +ᵢ ($ 4)\n            )\n          ) /\\\n          ( \n            v = ($ 0) ->\n            safety_insSeq C S2 pc2 npc2 q Spec\n          )\n        )\n    ) ->\n    safety_insSeq C S pc npc q Spec\n\n| bne_seq : forall C S pc npc q f Spec,\n    C pc = Some (cbne f) ->\n    (\n      exists S1 S2 pc1 npc1 pc2 npc2,\n        P__ C (S, pc, npc) (S1, pc1, npc1) /\\\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2)\n    ) ->\n    (\n      forall S1 S2 pc1 npc1 pc2 npc2,\n        P__ C (S, pc, npc) (S1, pc1, npc1) ->\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n        (\n          exists v, get_R (getregs S) z = Some (W v) /\\\n          (\n            v = ($ 0) ->\n            (\n              exists fp fq L r,\n                Spec pc2 = Some (fp, fq) /\\ S2 |= (fp L) ** r /\\\n                (fq L ** r) ==> q /\\ npc2 = pc2 +ᵢ ($ 4)\n            )\n          ) /\\\n          ( \n            v <> ($ 0) ->\n            safety_insSeq C S2 pc2 npc2 q Spec\n          )\n        )\n    ) ->\n    safety_insSeq C S pc npc q Spec\n\n| retl_seq : forall C S pc npc q Spec,\n    C pc = Some (cretl) ->\n    (\n      exists S1 S2 pc1 npc1 pc2 npc2,\n        P__ C (S, pc, npc) (S1, pc1, npc1) /\\\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2)\n    ) ->\n    (\n      forall S1 S2 pc1 npc1 pc2 npc2,\n        P__ C (S, pc, npc) (S1, pc1, npc1) ->\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n        (\n          S2 |= q /\\\n          (exists f,\n              get_R (getregs S2) r15 = Some (W f) /\\\n              pc2 = f +ᵢ ($ 8) /\\ npc2 = f +ᵢ ($ 12)\n          )\n        )\n    ) ->\n    safety_insSeq C S pc npc q Spec\n\n| ret_seq : forall C S pc npc q Spec,\n    C pc = Some (cret) ->\n    (\n      exists S1 S2 pc1 npc1 pc2 npc2,\n        P__ C (S, pc, npc) (S1, pc1, npc1) /\\\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2)\n    ) ->\n    (\n      forall S1 S2 pc1 npc1 pc2 npc2,\n        P__ C (S, pc, npc) (S1, pc1, npc1) ->\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n        (\n          S2 |= q /\\\n          (exists f,\n              get_R (getregs S2) r15 = Some (W f) /\\\n              pc2 = f +ᵢ ($ 8) /\\ npc2 = f +ᵢ ($ 12)\n          )\n        )\n    ) ->\n    safety_insSeq C S pc npc q Spec.\n\n(*+ Safety +*)\nInductive safety : nat -> CodeHeap -> State -> Label -> Label -> asrt -> nat -> Prop :=\n| safety_end :\n    forall C S pc npc q k,\n      safety 0 C S pc npc q k\n\n| safety_cons : forall C S pc npc q n k,\n    (\n      forall i,\n        C pc = Some (cntrans i) ->\n        (\n          (\n            exists S' pc' npc',\n              P__ C (S, pc, npc) (S', pc', npc')\n          ) /\\\n          (\n            forall S' pc' npc',\n              P__ C (S, pc, npc) (S', pc', npc') ->\n              safety n C S' pc' npc' q k\n          )\n        )\n    ) ->\n    (\n      forall aexp rd,\n        C pc = Some (cjumpl aexp rd) ->\n        (\n          (\n            exists S1 S2 pc1 npc1 pc2 npc2,\n              P__ C (S, pc, npc) (S1, pc1, npc1) /\\ P__ C (S1, pc1, npc1) (S2, pc2, npc2)\n          ) /\\\n          (\n            forall S1 S2 pc1 npc1 pc2 npc2,\n              P__ C (S, pc, npc) (S1, pc1, npc1) ->\n              P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n              safety n C S2 pc2 npc2 q k\n          )\n        )\n    ) ->\n    (\n      forall f,\n        C pc = Some (cbe f) ->\n        (\n          (\n            exists S1 S2 pc1 npc1 pc2 npc2,\n              P__ C (S, pc, npc) (S1, pc1, npc1) /\\ P__ C (S1, pc1, npc1) (S2, pc2, npc2)\n          ) /\\\n          (\n            forall S1 S2 pc1 npc1 pc2 npc2,\n              P__ C (S, pc, npc) (S1, pc1, npc1) ->\n              P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n              safety n C S2 pc2 npc2 q k\n          )\n        )\n    ) ->\n    (\n      forall f,\n        C pc = Some (cbne f) ->\n        (\n          (\n            exists S1 S2 pc1 npc1 pc2 npc2,\n              P__ C (S, pc, npc) (S1, pc1, npc1) /\\ P__ C (S1, pc1, npc1) (S2, pc2, npc2)\n          ) /\\\n          (\n            forall S1 S2 pc1 npc1 pc2 npc2,\n              P__ C (S, pc, npc) (S1, pc1, npc1) ->\n              P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n              safety n C S2 pc2 npc2 q k\n          )\n        )\n    ) ->\n    (\n      forall f,\n        C pc = Some (ccall f) ->\n        (\n          (\n            exists S1 S2 pc1 npc1 pc2 npc2,\n              P__ C (S, pc, npc) (S1, pc1, npc1) /\\ P__ C (S1, pc1, npc1) (S2, pc2, npc2)\n          ) /\\\n          (\n            forall S1 S2 pc1 npc1 pc2 npc2,\n              P__ C (S, pc, npc) (S1, pc1, npc1) ->\n              P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n              safety n C S2 pc2 npc2 q (Nat.succ k)\n          )\n        )\n    ) ->\n    (\n      C pc = Some (cretl) ->\n      (\n        (\n          exists S1 S2 pc1 npc1 pc2 npc2,\n            P__ C (S, pc, npc) (S1, pc1, npc1) /\\ P__ C (S1, pc1, npc1) (S2, pc2, npc2)\n        ) /\\\n        (\n          forall S1 S2 pc1 pc2 npc1 npc2,\n            P__ C (S, pc, npc) (S1, pc1, npc1) ->\n            P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n            (\n              (Nat.eqb k 0 = true /\\ S2 |= q) \\/\n              (Nat.eqb k 0 = false /\\ safety n C S2 pc2 npc2 q (Nat.pred k))\n            )\n        )\n      )\n    ) ->\n    (\n      C pc = Some (cret) ->\n      (\n        (\n          exists S1 S2 pc1 npc1 pc2 npc2,\n            P__ C (S, pc, npc) (S1, pc1, npc1) /\\ P__ C (S1, pc1, npc1) (S2, pc2, npc2)\n        ) /\\\n        (\n          forall S1 S2 pc1 pc2 npc1 npc2,\n            P__ C (S, pc, npc) (S1, pc1, npc1) ->\n            P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n            (\n              (Nat.eqb k 0 = true /\\ S2 |= q) \\/\n              (Nat.eqb k 0 = false /\\ safety n C S2 pc2 npc2 q (Nat.pred k))\n            )\n        )\n      )\n    ) ->\n    safety (Nat.succ n) C S pc npc q k.\n\n(*\nCoInductive safety : CodeHeap -> State -> Label -> Label -> asrt -> nat -> Prop :=\n| safety_cons : forall C S pc npc q n,\n    (\n      forall S' i pc' npc',\n        C pc = Some (cntrans i) ->\n        P__ C (S, pc, npc) (S', pc', npc') ->\n        safety C S' pc' npc' q n\n    ) ->\n    (\n      forall S' pc' npc' aexp rd,\n        C pc = Some (cjumpl aexp rd) ->\n        P__ C (S, pc, npc) (S', pc', npc') ->\n        safety C S' pc' npc' q n\n    ) ->\n    (\n      forall S' pc' npc' aexp,\n        C pc = Some (cbe aexp) ->\n        P__ C (S, pc, npc) (S', pc', npc') ->\n        safety C S' pc' npc' q n\n    ) ->\n    (\n      forall S' pc' npc' aexp,\n        C pc = Some (cbne aexp) ->\n        P__ C (S, pc, npc) (S', pc', npc') ->\n        safety C S' pc' npc' q n\n    ) ->\n    (\n      forall f S1 S2 pc1 pc2 npc1 npc2,\n        C pc = Some (ccall f) ->\n        P__ C (S, pc, npc) (S1, pc1, npc1) ->\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n        safety C S2 pc2 npc2 q (Nat.succ n)\n    ) ->\n    (\n      forall S1 S2 pc1 pc2 npc1 npc2,\n        C pc = Some (cretl) ->\n        P__ C (S, pc, npc) (S1, pc1, npc1) ->\n        P__ C (S1, pc1, npc1) (S2, pc2, npc2) ->\n        (\n          (Nat.eqb n 0 = true /\\ S2 |= q) \\/\n          (Nat.eqb n 0 = false /\\ safety C S2 pc2 npc2 q (Nat.pred n))\n        )\n    ) ->\n    safety C S pc npc q n.\n*)\n\n(*\nDefinition cdhp_subst (Spec Spec' : funspec) :=\n  forall f fsp, Spec f = Some fsp -> Spec' f = Some fsp.\n*)\n\n(** Instruction Sequence rule Sound *)\nDefinition insSeq_sound (Spec : funspec) (p : asrt) (f : Label) (I : InsSeq) (q : asrt) :=\n  forall C S,\n    LookupC C f I -> S |= p -> safety_insSeq C S f (f +ᵢ ($ 4)) q Spec.\n\n(** Code Heap Sound *)\nDefinition cdhp_sound (Spec : funspec) (C : CodeHeap) :=\n  forall f fp fq L S,\n    Spec f = Some (fp, fq) -> S |= (fp L) ->\n    (*cdhp_subst Spec Spec' ->*)\n    exists I, LookupC C f I /\\ insSeq_sound Spec (fp L) f I (fq L).\n", "meta": {"author": "jpzha", "repo": "VeriSparc", "sha": "7fc60fbc4b4357b93836d1b461d7d27c669e9f58", "save_path": "github-repos/coq/jpzha-VeriSparc", "path": "github-repos/coq/jpzha-VeriSparc/VeriSparc-7fc60fbc4b4357b93836d1b461d7d27c669e9f58/coqimp/framework/soundness/soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.23817040726452715}}
{"text": "Require Import MachineModel.\n\n\n(* ===============================================================\n   Labels for the trace semantics and the labelled operational\n   ================================================================*)\n\nInductive Label := \n| Tau : Label\n| Tick : Label\n| Write_out : Address -> Value -> Label\n| Call : RegisterFile -> Flags -> Address -> Label\n| Callback : RegisterFile -> Flags -> Address -> Label\n| Return : RegisterFile -> Flags -> Address -> Label\n| Returnback : RegisterFile -> Flags -> Address -> Label.\n\n\n\n\n", "meta": {"author": "supercooldave", "repo": "ruse", "sha": "8ed8d89dce206fa43d4fe163783afd4de6e56167", "save_path": "github-repos/coq/supercooldave-ruse", "path": "github-repos/coq/supercooldave-ruse/ruse-8ed8d89dce206fa43d4fe163783afd4de6e56167/formalism/Labels.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23805434562536323}}
{"text": "From CoreErlang.FrameStack Require Export Frames.\nFrom CoreErlang Require Export Auxiliaries Matching.\n\nImport ListNotations.\n\nDefinition create_result (ident : FrameIdent) (vl : list Val)\n  : Redex :=\nmatch ident with\n| IValues => RValSeq vl\n| ITuple => RValSeq [VTuple vl]\n| IMap => RValSeq [VMap (make_val_map (deflatten_list vl))]\n| ICall m f => fst (eval m f vl []) (*side effects!!! *)\n| IPrimOp f => fst (primop_eval f vl []) (* side effects !!!!*)\n| IApp (VClos ext id vars e) =>\n  if Nat.eqb vars (length vl)\n  then RExp (e.[list_subst (convert_to_closlist ext ++ vl) idsubst])\n  else RExc (badarity (VClos ext id vars e))\n| IApp v => RExc (badfun v)\nend.\n\nProposition FrameIdent_eq_dec :\n  forall id1 id2 : FrameIdent, {id1 = id2} + {id1 <> id2}.\nProof.\n  decide equality; try apply string_dec.\n  apply Val_eq_dec.\nQed.\n\n(* Note: for simplicity, this semantics allows guards to evaluate\n   to exceptions, which is not allowed in normal Core Erlang. *)\nReserved Notation \"⟨ fs , e ⟩ --> ⟨ fs' , e' ⟩\" (at level 50).\nInductive step : FrameStack -> Redex -> FrameStack -> Redex -> Prop :=\n(**  Reduction rules *)\n\n(** Cooling: single value *)\n| cool_value v xs:\n  ⟨ xs, `v ⟩ --> ⟨ xs, RValSeq [v] ⟩\n\n(************************************************)\n(* heating should be separate for all complex expressions (to be\n   syntax-driven).\n   Only the intermediate and last steps can be extracted: *)\n| eval_step_params xs ident (el : list Exp) (vl : list Val) (v : Val) (e : Exp):\n  ⟨FParams ident vl (e :: el) :: xs, RValSeq [v]⟩ -->\n  ⟨FParams ident (vl ++ [v]) el :: xs, e⟩\n\n(* technical rule to avoid duplication for 0 subexpressions : *)\n| eval_step_params_0 xs ident e el vl:\n  ident <> IMap ->\n  ⟨FParams ident vl (e::el) ::xs, RBox⟩ --> ⟨FParams ident vl el :: xs, e⟩\n\n(* 0 subexpression in complex expressions: *)\n| eval_cool_params_0 xs ident (vl : list Val) (res : Redex) : \n  ident <> IMap ->\n  res = create_result ident vl ->\n  ⟨FParams ident vl [] ::xs, RBox⟩ --> ⟨xs, res⟩\n\n| eval_cool_params xs ident (vl : list Val) (v : Val) (res : Redex):\n  res = create_result ident (vl ++ [v]) ->\n  ⟨FParams ident vl [] :: xs, RValSeq [v]⟩ --> ⟨xs, res⟩\n\n(************************************************)\n(* Heating constructs with list subexpressions: *)\n| eval_heat_values (el : list Exp) (xs : list Frame):\n  ⟨ xs, EValues el ⟩ --> ⟨ (FParams IValues [] el)::xs, RBox ⟩\n\n| eval_heat_tuple (el : list Exp) (xs : list Frame):\n  ⟨ xs, ETuple el ⟩ --> ⟨ (FParams ITuple [] el)::xs, RBox ⟩\n\n(* This is handled separately, to satisfy the invariant in FCLOSED for maps *)\n| eval_heat_map_0 (xs : list Frame):\n  ⟨ xs, EMap [] ⟩ --> ⟨ xs, RValSeq [VMap []] ⟩\n\n| eval_heat_map (e1 e2 : Exp) (el : list (Exp * Exp)) (xs : list Frame):\n  ⟨ xs, EMap ((e1, e2) :: el) ⟩ -->\n  ⟨ (FParams IMap [] (e2 :: flatten_list el))::xs, e1 ⟩\n\n| eval_heat_call (el : list Exp) (xs : list Frame) m f:\n  ⟨ xs, ECall m f el ⟩ --> ⟨ (FParams (ICall m f) [] el)::xs, RBox ⟩\n\n| eval_heat_primop (el : list Exp) (xs : list Frame) f:\n  ⟨ xs, EPrimOp f el ⟩ --> ⟨ (FParams (IPrimOp f) [] el)::xs, RBox ⟩\n\n| eval_heat_app2 (el : list Exp) (xs : list Frame) (v : Val):\n  ⟨ FApp1 el :: xs, RValSeq [v] ⟩ --> ⟨ (FParams (IApp v) [] el)::xs, RBox ⟩\n\n(************************************************)\n(**  App *)\n| eval_heat_app xs e l:\n  ⟨xs, EApp e l⟩ --> ⟨FApp1 l :: xs, e⟩ \n(**  List *)\n(**  Cooling *)\n\n| eval_cool_cons_1 (hd : Exp) (tl : Val) xs :\n  ⟨ (FCons1 hd)::xs, RValSeq [tl] ⟩ --> ⟨ (FCons2 tl)::xs, RExp hd ⟩\n\n| eval_cool_cons_2 (hd tl : Val) xs :\n  ⟨ (FCons2 tl)::xs, RValSeq [hd] ⟩ --> ⟨ xs, RValSeq [VCons hd tl] ⟩\n\n(**  Heating *)\n| eval_heat_cons (hd tl : Exp) xs :\n  ⟨ xs, ECons hd tl ⟩ --> ⟨ (FCons1 hd)::xs, RExp tl ⟩\n\n(**  Let *)\n(**  Cooling *)\n| eval_cool_let l e2 vs xs :\n  length vs = l ->\n  ⟨ (FLet l e2)::xs, RValSeq vs ⟩ --> ⟨ xs, RExp (e2.[ list_subst vs idsubst ]) ⟩\n\n(**  Heating *)\n| eval_heat_let l e1 e2 xs :\n  ⟨ xs, ELet l e1 e2 ⟩ --> ⟨ (FLet l e2)::xs, RExp e1 ⟩\n\n(**  Seq *)\n(**  Cooling *)\n| eval_cool_seq e2 v xs :\n  ⟨ (FSeq e2)::xs, RValSeq [v] ⟩ --> ⟨ xs, RExp e2 ⟩\n(**  Heating *)\n| eval_heat_seq e1 e2 xs :\n  ⟨ xs, ESeq e1 e2 ⟩ --> ⟨ (FSeq e2)::xs, RExp e1 ⟩\n\n\n(**  Fun *)\n(**  Cooling *)\n| eval_cool_fun e vl xs :\n  ⟨ xs, EFun vl e ⟩ --> ⟨ xs, RValSeq [ VClos [] 0 vl e ] ⟩\n  (* TODO : id <> 0 usually *)\n\n\n(**  Case *)\n(**  Heating *)\n| eval_heat_case e l xs:\n  ⟨ xs, ECase e l ⟩ --> ⟨ (FCase1 l)::xs, RExp e ⟩\n\n(**  Cooling *)\n(* reduction started or it is already ongoing, the first pattern matched,\n   e1 the guard needs to be evaluated. vs' (the result of the pattern\n   matching is stored in the frame) *)\n| eval_step_case_match lp e1 e2 l vs vs' xs :\n  match_pattern_list lp vs = Some vs' ->\n  ⟨ (FCase1 ((lp,e1,e2)::l))::xs, RValSeq vs ⟩ -->\n  ⟨ (FCase2 vs lp e2 l)::xs, RExp (e1.[list_subst vs' idsubst]) ⟩\n\n(* reduction started or it is already ongoing, the first pattern doesn't \n   match, so we check the next pattern *)\n| eval_step_case_not_match lp e1 e2 l vs xs :\n  match_pattern_list lp vs = None ->\n  ⟨ (FCase1 ((lp,e1,e2)::l))::xs, RValSeq vs ⟩ -->\n  ⟨ (FCase1 l)::xs, RValSeq vs ⟩\n\n(* reduction is ongoing, the pattern matched, and the guard is true, thus \n   the reduction continues inside the given clause *)\n| eval_step_case_true vs lp e' l xs vs' :\n  match_pattern_list lp vs = Some vs' ->\n  ⟨ (FCase2 vs lp e' l)::xs, RValSeq [ VLit (Atom \"true\") ] ⟩ --> \n  ⟨ xs, RExp (e'.[list_subst vs' idsubst]) ⟩\n\n(* reduction is ongoing, the pattern matched, and the guard is false, thus\n   we check the next pattern. *)\n| eval_step_case_false vs lp' e' l xs :\n  (* NOTE: match_pattern_list lp vs = Some vs' -> is necessary? *)\n  ⟨ (FCase2 vs lp' e' l)::xs, RValSeq [ VLit (Atom \"false\") ] ⟩ --> ⟨ (FCase1 l)::xs, RValSeq vs ⟩\n\n(** Exceptions *)\n| eval_cool_case_empty vs xs:\n  ⟨ (FCase1 [])::xs, RValSeq vs ⟩ --> ⟨ xs, RExc if_clause ⟩\n\n(**  LetRec *)\n(**  Cooling *)\n(**  Heating *)\n| eval_heat_letrec l e lc xs :\n  convert_to_closlist (map (fun '(x,y) => (0,x,y)) l) = lc ->\n  (* TODO: for now the funids are 0 coded in *)\n  ⟨ xs, ELetRec l e ⟩ --> ⟨ xs, RExp e.[list_subst lc idsubst] ⟩\n\n\n(**  Try *)\n(**  Cooling *)\n| eval_cool_try_ok vl1 e2 vl2 e3 vs xs:\n  vl1 = length vs ->\n  ⟨ (FTry vl1 e2 vl2 e3)::xs, RValSeq vs ⟩ --> ⟨ xs, RExp e2.[ list_subst vs idsubst ] ⟩\n| eval_cool_try_err vl1 e2 e3 class reason details xs:\n  (* in Core Erlang exceptions always have 3 parts *)\n  ⟨ (FTry vl1 e2 3 e3)::xs, RExc (class, reason, details) ⟩ -->\n  ⟨ xs, RExp e3.[ list_subst [exclass_to_value class; reason; details] idsubst ] ⟩\n(**  Heating *)\n| eval_heat_try e1 vl1 e2 vl2 e3 xs :\n  ⟨ xs, ETry e1 vl1 e2 vl2 e3 ⟩ --> ⟨ (FTry vl1 e2 vl2 e3)::xs, RExp e1 ⟩\n  \n(** Exceptions *)\n(** Propogation *)\n| eval_prop_exc F exc xs :\n  (forall vl1 e2 vl2 e3, (FTry vl1 e2 vl2 e3) <> F) ->\n  ⟨ F::xs, RExc exc ⟩ --> ⟨ xs, RExc exc ⟩\n  (* TODO: details could be appended here to the stack trace *)\n\nwhere \"⟨ fs , e ⟩ --> ⟨ fs' , e' ⟩\" := (step fs e fs' e').\n\n\nReserved Notation \"⟨ fs , e ⟩ -[ k ]-> ⟨ fs' , e' ⟩\" (at level 50).\nInductive step_rt : FrameStack -> Redex -> nat -> FrameStack -> Redex -> Prop :=\n| step_refl fs e : ⟨ fs, e ⟩ -[ 0 ]-> ⟨ fs, e ⟩\n| step_trans fs e fs' e' fs'' e'' k:\n  ⟨ fs, e ⟩ --> ⟨ fs', e'⟩ -> ⟨fs', e'⟩ -[ k ]-> ⟨fs'', e''⟩\n  ->\n  ⟨ fs, e ⟩ -[S k]-> ⟨fs'', e''⟩\nwhere \"⟨ fs , e ⟩ -[ k ]-> ⟨ fs' , e' ⟩\" := (step_rt fs e k fs' e').\n\nDefinition step_any (fs : FrameStack) (e : Redex) (r : Redex) : Prop :=\n  exists k, is_result r /\\ ⟨fs, e⟩ -[k]-> ⟨[], r⟩.\nNotation \"⟨ fs , e ⟩ -->* v\" := (step_any fs e v) (at level 50).\n", "meta": {"author": "harp-project", "repo": "Core-Erlang-Formalization", "sha": "847eb02bf31edf45d9e9619f4258bae8ad65db4b", "save_path": "github-repos/coq/harp-project-Core-Erlang-Formalization", "path": "github-repos/coq/harp-project-Core-Erlang-Formalization/Core-Erlang-Formalization-847eb02bf31edf45d9e9619f4258bae8ad65db4b/src/FrameStack/SubstSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23805433908392964}}
{"text": "Require Import Coq.Classes.Morphisms.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.BaseTypes Fiat.Parsers.CorrectnessBaseTypes.\nRequire Import Fiat.Parsers.GenericBaseTypes Fiat.Parsers.GenericCorrectnessBaseTypes.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Valid.\nRequire Import Fiat.Parsers.GenericRecognizerCorrect.\nRequire Import Fiat.Parsers.BooleanRecognizer.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\nSection convenience.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char} {G : grammar Char}.\n  Context {data : @boolean_parser_dataT Char _}\n          {cdata : @boolean_parser_completeness_dataT' Char _ _ G _}\n          {rdata : @parser_removal_dataT' _ G _}\n          (gvalid : grammar_valid G).\n\n  Local Instance gencdata_default_proper {A}\n    : Proper (beq ==> eq ==> eq ==> eq ==> Basics.impl) (fun _ (_ : A) (x y : bool) => y = x).\n  Proof.\n    repeat intro; repeat subst; reflexivity.\n  Qed.\n\n  Local Existing Instance boolean_gendata.\n  Global Program Instance boolean_gencdata : generic_parser_correctness_dataT\n    := { parse_nt_is_correct str nt exp act := act = exp;\n         parse_item_is_correct str it exp act := act = exp;\n         parse_production_is_correct str p exp act := act = exp;\n         parse_productions_is_correct str p exp act := act = exp }.\n\n  Definition parse_item_sound\n    : forall str it, parse_item str it -> parse_of_item G str it\n    := parse_item_sound.\n\n  Definition parse_item_complete\n    : forall str it, parse_of_item G str it -> parse_item str it\n    := parse_item_complete.\n\n  Definition parse_nonterminal_sound\n    : forall str nt, parse_nonterminal str nt -> parse_of_item G str (NonTerminal nt)\n    := parse_nonterminal_sound.\n\n  Definition parse_nonterminal_complete\n    : forall str nt, parse_of_item G str (NonTerminal nt) -> parse_nonterminal str nt\n    := parse_nonterminal_complete.\n\n  Definition parse_of_nonterminal_complete\n    : forall str nt,\n      List.In nt (Valid_nonterminals G)\n      -> parse_of G str (Lookup G nt)\n      -> parse_nonterminal str nt\n    := parse_of_nonterminal_complete.\nEnd convenience.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/BooleanRecognizerCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2380543390839296}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness proof for the [Debugvar] pass. *)\n\nRequire Import Coqlib.\nRequire Import Axioms.\nRequire Import Maps.\nRequire Import Iteration.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Errors.\nRequire Import Machregs.\nRequire Import Locations.\nRequire Import Conventions.\nRequire Import Linear.\nRequire Import Debugvar.\n\n(** * Relational characterization of the transformation *)\n\nInductive match_code: code -> code -> Prop :=\n  | match_code_nil:\n      match_code nil nil\n  | match_code_cons: forall i before after c c',\n      match_code c c' ->\n      match_code (i :: c) (i :: add_delta_ranges before after c').\n\nRemark diff_same:\n  forall s, diff s s = nil.\nProof.\n  induction s as [ | [v i] s]; simpl.\n  auto.\n  rewrite Pos.compare_refl. rewrite dec_eq_true. auto.\nQed.\n\nRemark delta_state_same:\n  forall s, delta_state s s = (nil, nil).\nProof.\n  destruct s; simpl. rewrite ! diff_same; auto. auto.\nQed.\n\nLemma transf_code_match:\n  forall lm c before, match_code c (transf_code lm before c).\nProof.\n  intros lm. fix REC 1. destruct c; intros before; simpl.\n- constructor.\n- assert (DEFAULT: forall before after,\n            match_code (i :: c)\n                       (i :: add_delta_ranges before after (transf_code lm after c))).\n  { intros. constructor. apply REC. }\n  destruct i; auto. destruct c; auto. destruct i; auto.\n  set (after := get_label l0 lm).\n  set (c1 := Llabel l0 :: add_delta_ranges before after (transf_code lm after c)).\n  replace c1 with (add_delta_ranges before before c1).\n  constructor. constructor. apply REC.\n  unfold add_delta_ranges. rewrite delta_state_same. auto.\nQed.\n\nInductive match_function: function -> function -> Prop :=\n  | match_function_intro: forall f c,\n      match_code f.(fn_code) c ->\n      match_function f (mkfunction f.(fn_sig) f.(fn_stacksize) c).\n\nLemma transf_function_match:\n  forall f tf, transf_function f = OK tf -> match_function f tf.\nProof.\n  unfold transf_function; intros.\n  destruct (ana_function f) as [lm|]; inv H.\n  constructor. apply transf_code_match.\nQed.\n\nRemark find_label_add_delta_ranges:\n  forall lbl c before after, find_label lbl (add_delta_ranges before after c) = find_label lbl c.\nProof.\n  intros. unfold add_delta_ranges.\n  destruct (delta_state before after) as [killed born].\n  induction killed as [ | [v i] l]; simpl; auto.\n  induction born as [ | [v i] l]; simpl; auto.\nQed.\n\nLemma find_label_match_rec:\n  forall lbl c' c tc,\n  match_code c tc ->\n  find_label lbl c = Some c' ->\n  exists before after tc', find_label lbl tc = Some (add_delta_ranges before after tc') /\\ match_code c' tc'.\nProof.\n  induction 1; simpl; intros.\n- discriminate.\n- destruct (is_label lbl i).\n  inv H0. econstructor; econstructor; econstructor; eauto.\n  rewrite find_label_add_delta_ranges. auto.\nQed.\n\nLemma find_label_match:\n  forall f tf lbl c,\n  match_function f tf ->\n  find_label lbl f.(fn_code) = Some c ->\n  exists before after tc, find_label lbl tf.(fn_code) = Some (add_delta_ranges before after tc) /\\ match_code c tc.\nProof.\n  intros. inv H. eapply find_label_match_rec; eauto.\nQed.\n\n(** * Properties of availability sets *)\n\n(** These properties are not used in the semantic preservation proof,\n    but establish some confidence in the availability analysis. *)\n\nDefinition avail_above (v: ident) (s: avail) : Prop :=\n  forall v' i', In (v', i') s -> Plt v v'.\n\nInductive wf_avail: avail -> Prop :=\n  | wf_avail_nil:\n      wf_avail nil\n  | wf_avail_cons: forall v i s,\n     avail_above v s ->\n     wf_avail s ->\n     wf_avail ((v, i) :: s).\n\nLemma set_state_1:\n  forall v i s, In (v, i) (set_state v i s).\nProof.\n  induction s as [ | [v' i'] s]; simpl.\n- auto.\n- destruct (Pos.compare v v'); simpl; auto.\nQed.\n\nLemma set_state_2:\n  forall v i v' i' s,\n  v' <> v -> In (v', i') s -> In (v', i') (set_state v i s).\nProof.\n  induction s as [ | [v1 i1] s]; simpl; intros.\n- contradiction.\n- destruct (Pos.compare_spec v v1); simpl.\n+ subst v1. destruct H0. congruence. auto.\n+ auto.\n+ destruct H0; auto.\nQed.\n\nLemma set_state_3:\n  forall v i v' i' s,\n  wf_avail s ->\n  In (v', i') (set_state v i s) ->\n  (v' = v /\\ i' = i) \\/ (v' <> v /\\ In (v', i') s).\nProof.\n  induction 1; simpl; intros.\n- intuition congruence.\n- destruct (Pos.compare_spec v v0); simpl in H1.\n+ subst v0. destruct H1. inv H1; auto. right; split.\n  apply sym_not_equal. apply Plt_ne. eapply H; eauto.\n  auto.\n+ destruct H1. inv H1; auto.\n  destruct H1. inv H1. right; split; auto. apply sym_not_equal. apply Plt_ne. auto.\n  right; split; auto. apply sym_not_equal. apply Plt_ne. apply Plt_trans with v0; eauto.\n+ destruct H1. inv H1. right; split; auto. apply Plt_ne. auto.\n  destruct IHwf_avail as [A | [A B]]; auto.\nQed.\n\nLemma wf_set_state:\n  forall v i s, wf_avail s -> wf_avail (set_state v i s).\nProof.\n  induction 1; simpl.\n- constructor. red; simpl; tauto. constructor.\n- destruct (Pos.compare_spec v v0).\n+ subst v0. constructor; auto.\n+ constructor.\n  red; simpl; intros. destruct H2.\n  inv H2. auto. apply Plt_trans with v0; eauto.\n  constructor; auto.\n+ constructor.\n  red; intros. exploit set_state_3. eexact H0. eauto. intros [[A B] | [A B]]; subst; eauto.\n  auto.\nQed.\n\nLemma remove_state_1:\n  forall v i s, wf_avail s -> ~ In (v, i) (remove_state v s).\nProof.\n  induction 1; simpl; red; intros.\n- auto.\n- destruct (Pos.compare_spec v v0); simpl in *.\n+ subst v0. elim (Plt_strict v); eauto.\n+ destruct H1. inv H1.  elim (Plt_strict v); eauto.\n  elim (Plt_strict v). apply Plt_trans with v0; eauto.\n+ destruct H1. inv H1. elim (Plt_strict v); eauto.  tauto.\nQed.\n\nLemma remove_state_2:\n  forall v v' i' s, v' <> v -> In (v', i') s -> In (v', i') (remove_state v s).\nProof.\n  induction s as [ | [v1 i1] s]; simpl; intros.\n- auto.\n- destruct (Pos.compare_spec v v1); simpl.\n+ subst v1. destruct H0. congruence. auto.\n+ auto.\n+ destruct H0; auto.\nQed.\n\nLemma remove_state_3:\n  forall v v' i' s, wf_avail s -> In (v', i') (remove_state v s) -> v' <> v /\\ In (v', i') s.\nProof.\n  induction 1; simpl; intros.\n- contradiction.\n- destruct (Pos.compare_spec v v0); simpl in H1.\n+ subst v0. split; auto. apply sym_not_equal; apply Plt_ne; eauto.\n+ destruct H1. inv H1. split; auto. apply sym_not_equal; apply Plt_ne; eauto.\n  split; auto. apply sym_not_equal; apply Plt_ne. apply Plt_trans with v0; eauto.\n+ destruct H1. inv H1. split; auto. apply Plt_ne; auto.\n  destruct IHwf_avail as [A B] ; auto.\nQed.\n\nLemma wf_remove_state:\n  forall v s, wf_avail s -> wf_avail (remove_state v s).\nProof.\n  induction 1; simpl.\n- constructor.\n- destruct (Pos.compare_spec v v0).\n+ auto.\n+ constructor; auto.\n+ constructor; auto. red; intros.\n  exploit remove_state_3. eexact H0. eauto. intros [A B]. eauto.\nQed.\n\nLemma wf_filter:\n  forall pred s, wf_avail s -> wf_avail (List.filter pred s).\nProof.\n  induction 1; simpl.\n- constructor.\n- destruct (pred (v, i)) eqn:P; auto.\n  constructor; auto.\n  red; intros. apply filter_In in H1. destruct H1. eauto.\nQed.\n\nLemma join_1:\n  forall v i s1, wf_avail s1 -> forall s2, wf_avail s2 ->\n  In (v, i) s1 -> In (v, i) s2 -> In (v, i) (join s1 s2).\nProof.\n  induction 1; simpl; try tauto; induction 1; simpl; intros I1 I2; auto.\n  destruct I1, I2.\n- inv H3; inv H4. rewrite Pos.compare_refl. rewrite dec_eq_true; auto with coqlib.\n- inv H3.\n  assert (L: Plt v1 v) by eauto. apply Pos.compare_gt_iff in L. rewrite L. auto.\n- inv H4.\n  assert (L: Plt v0 v) by eauto. apply Pos.compare_lt_iff in L. rewrite L. apply IHwf_avail. constructor; auto. auto. auto with coqlib.\n- destruct (Pos.compare v0 v1).\n+ destruct (eq_debuginfo i0 i1); auto with coqlib.\n+ apply IHwf_avail; auto with coqlib. constructor; auto.\n+ eauto.\nQed.\n\nLemma join_2:\n  forall v i s1, wf_avail s1 -> forall s2, wf_avail s2 ->\n  In (v, i) (join s1 s2) -> In (v, i) s1 /\\ In (v, i) s2.\nProof.\n  induction 1; simpl; try tauto; induction 1; simpl; intros I; try tauto.\n  destruct (Pos.compare_spec v0 v1).\n- subst v1. destruct (eq_debuginfo i0 i1).\n  + subst i1. destruct I. auto. exploit IHwf_avail; eauto. tauto.\n  + exploit IHwf_avail; eauto. tauto.\n- exploit (IHwf_avail ((v1, i1) :: s0)); eauto. constructor; auto.\n  simpl. tauto.\n- exploit IHwf_avail0; eauto. tauto.\nQed.\n\nLemma wf_join:\n  forall s1, wf_avail s1 -> forall s2, wf_avail s2 -> wf_avail (join s1 s2).\nProof.\n  induction 1; simpl; induction 1; simpl; try constructor.\n  destruct (Pos.compare_spec v v0).\n- subst v0. destruct (eq_debuginfo i i0); auto. constructor; auto.\n  red; intros. apply join_2 in H3; auto. destruct H3. eauto.\n- apply IHwf_avail. constructor; auto.\n- apply IHwf_avail0.\nQed.\n\n(** * Semantic preservation *)\n\nSection PRESERVATION.\n\nVariable prog: program.\nVariable tprog: program.\n\nHypothesis TRANSF: transf_program prog = OK tprog.\n\nLet ge := Genv.globalenv prog.\nLet tge := Genv.globalenv tprog.\n\nLemma functions_translated:\n  forall v f,\n  Genv.find_funct ge v = Some f ->\n  exists tf,\n  Genv.find_funct tge v = Some tf /\\ transf_fundef f = OK tf.\nProof (Genv.find_funct_transf_partial transf_fundef _ TRANSF).\n\nLemma function_ptr_translated:\n  forall v f,\n  Genv.find_funct_ptr ge v = Some f ->\n  exists tf,\n  Genv.find_funct_ptr tge v = Some tf /\\ transf_fundef f = OK tf.\nProof (Genv.find_funct_ptr_transf_partial transf_fundef _ TRANSF).\n\nLemma symbols_preserved:\n  forall id,\n  Genv.find_symbol tge id = Genv.find_symbol ge id.\nProof (Genv.find_symbol_transf_partial transf_fundef _ TRANSF).\n\nLemma public_preserved:\n  forall id,\n  Genv.public_symbol tge id = Genv.public_symbol ge id.\nProof (Genv.public_symbol_transf_partial transf_fundef _ TRANSF).\n\nLemma varinfo_preserved:\n  forall b, Genv.find_var_info tge b = Genv.find_var_info ge b.\nProof (Genv.find_var_info_transf_partial transf_fundef _ TRANSF).\n\nLemma sig_preserved:\n  forall f tf,\n  transf_fundef f = OK tf ->\n  funsig tf = funsig f.\nProof.\n  unfold transf_fundef, transf_partial_fundef; intros.\n  destruct f. monadInv H.\n  exploit transf_function_match; eauto. intros M; inv M; auto.\n  inv H. reflexivity.\nQed.\n\nLemma find_function_translated:\n  forall ros ls f,\n  find_function ge ros ls = Some f ->\n  exists tf,\n  find_function tge ros ls = Some tf /\\ transf_fundef f = OK tf.\nProof.\n  unfold find_function; intros; destruct ros; simpl.\n  apply functions_translated; auto.\n  rewrite symbols_preserved. destruct (Genv.find_symbol ge i).\n  apply function_ptr_translated; auto.\n  congruence.\nQed.\n\n(** Evaluation of the debug annotations introduced by the transformation. *)\n\nLemma can_eval_safe_arg:\n  forall (rs: locset) sp m (a: builtin_arg loc),\n  safe_builtin_arg a -> exists v, eval_builtin_arg tge rs sp m a v.\nProof.\n  induction a; simpl; intros; try contradiction;\n  try (econstructor; now eauto with barg).\n  destruct H as [S1 S2].\n  destruct (IHa1 S1) as [v1 E1]. destruct (IHa2 S2) as [v2 E2].\n  exists (Val.longofwords v1 v2); auto with barg.\nQed.\n\nLemma eval_add_delta_ranges:\n  forall s f sp c rs m before after,\n  star step tge (State s f sp (add_delta_ranges before after c) rs m)\n             E0 (State s f sp c rs m).\nProof.\n  intros. unfold add_delta_ranges.\n  destruct (delta_state before after) as [killed born].\n  induction killed as [ | [v i] l]; simpl.\n- induction born as [ | [v i] l]; simpl.\n+ apply star_refl.\n+ destruct i as [a SAFE]; simpl.\n  exploit can_eval_safe_arg; eauto. intros [v1 E1].\n  eapply star_step; eauto.\n  econstructor.\n  constructor. eexact E1. constructor.\n  simpl; constructor.\n  simpl; auto.\n  traceEq.\n- eapply star_step; eauto.\n  econstructor.\n  constructor.\n  simpl; constructor.\n  simpl; auto.\n  traceEq.\nQed.\n\n(** Matching between program states. *)\n\nInductive match_stackframes: Linear.stackframe -> Linear.stackframe -> Prop :=\n  | match_stackframe_intro:\n      forall f sp rs c tf tc before after,\n      match_function f tf ->\n      match_code c tc ->\n      match_stackframes\n        (Stackframe f sp rs c)\n        (Stackframe tf sp rs (add_delta_ranges before after tc)).\n\nInductive match_states: Linear.state ->  Linear.state -> Prop :=\n  | match_states_instr:\n      forall s f sp c rs m tf ts tc\n        (STACKS: list_forall2 match_stackframes s ts)\n        (TRF: match_function f tf)\n        (TRC: match_code c tc),\n      match_states (State s f sp c rs m)\n                   (State ts tf sp tc rs m)\n  | match_states_call:\n      forall s f rs m tf ts,\n      list_forall2 match_stackframes s ts ->\n      transf_fundef f = OK tf ->\n      match_states (Callstate s f rs m)\n                   (Callstate ts tf rs m)\n  | match_states_return:\n      forall s rs m ts,\n      list_forall2 match_stackframes s ts ->\n      match_states (Returnstate s rs m)\n                   (Returnstate ts rs m).\n\nLemma parent_locset_match:\n  forall s ts,\n  list_forall2 match_stackframes s ts ->\n  parent_locset ts = parent_locset s.\nProof.\n  induction 1; simpl. auto. inv H; auto.\nQed.\n\n(** The simulation diagram. *)\n\nTheorem transf_step_correct:\n  forall s1 t s2, step ge s1 t s2 ->\n  forall ts1 (MS: match_states s1 ts1),\n  exists ts2, plus step tge ts1 t ts2 /\\ match_states s2 ts2.\nProof.\n  induction 1; intros ts1 MS; inv MS; try (inv TRC).\n- (* getstack *)\n  econstructor; split.\n  eapply plus_left. constructor; auto. apply eval_add_delta_ranges. traceEq.\n  constructor; auto.\n- (* setstack *)\n  econstructor; split.\n  eapply plus_left. constructor; auto. apply eval_add_delta_ranges. traceEq.\n  constructor; auto.\n- (* op *)\n  econstructor; split.\n  eapply plus_left.\n  econstructor; eauto.\n  instantiate (1 := v). rewrite <- H; apply eval_operation_preserved; exact symbols_preserved.\n  apply eval_add_delta_ranges. traceEq.\n  constructor; auto.\n- (* load *)\n  econstructor; split.\n  eapply plus_left.\n  eapply exec_Lload with (a := a).\n  rewrite <- H; apply eval_addressing_preserved; exact symbols_preserved.\n  eauto. eauto.\n  apply eval_add_delta_ranges. traceEq.\n  constructor; auto.\n- (* store *)\n  econstructor; split.\n  eapply plus_left.\n  eapply exec_Lstore with (a := a).\n  rewrite <- H; apply eval_addressing_preserved; exact symbols_preserved.\n  eauto. eauto.\n  apply eval_add_delta_ranges. traceEq.\n  constructor; auto.\n- (* call *)\n  exploit find_function_translated; eauto. intros (tf' & A & B).\n  econstructor; split.\n  apply plus_one.\n  econstructor. eexact A. symmetry; apply sig_preserved; auto. traceEq.\n  constructor; auto. constructor; auto. constructor; auto.\n- (* tailcall *)\n  exploit find_function_translated; eauto. intros (tf' & A & B).\n  exploit parent_locset_match; eauto. intros PLS.\n  econstructor; split.\n  apply plus_one.\n  econstructor. eauto. rewrite PLS. eexact A.\n  symmetry; apply sig_preserved; auto.\n  inv TRF; eauto. traceEq.\n  rewrite PLS. constructor; auto.\n- (* builtin *)\n  econstructor; split.\n  eapply plus_left.\n  econstructor; eauto.\n  eapply eval_builtin_args_preserved with (ge1 := ge); eauto. exact symbols_preserved.\n  eapply external_call_symbols_preserved. eauto.\n  exact symbols_preserved. exact public_preserved. exact varinfo_preserved.\n  apply eval_add_delta_ranges. traceEq.\n  constructor; auto.\n- (* label *)\n  econstructor; split.\n  eapply plus_left. constructor; auto. apply eval_add_delta_ranges. traceEq.\n  constructor; auto.\n- (* goto *)\n  exploit find_label_match; eauto. intros (before' & after' & tc' & A & B).\n  econstructor; split.\n  eapply plus_left. constructor; eauto. apply eval_add_delta_ranges; eauto. traceEq.\n  constructor; auto.\n- (* cond taken *)\n  exploit find_label_match; eauto. intros (before' & after' & tc' & A & B).\n  econstructor; split.\n  eapply plus_left. eapply exec_Lcond_true; eauto. apply eval_add_delta_ranges; eauto. traceEq.\n  constructor; auto.\n- (* cond not taken *)\n  econstructor; split.\n  eapply plus_left. eapply exec_Lcond_false; auto. apply eval_add_delta_ranges. traceEq.\n  constructor; auto.\n- (* jumptable *)\n  exploit find_label_match; eauto. intros (before' & after' & tc' & A & B).\n  econstructor; split.\n  eapply plus_left. econstructor; eauto.\n  apply eval_add_delta_ranges. reflexivity. traceEq.\n  constructor; auto.\n- (* return *)\n  econstructor; split.\n  apply plus_one.  constructor. inv TRF; eauto. traceEq.\n  rewrite (parent_locset_match _ _ STACKS). constructor; auto.\n- (* internal function *)\n  monadInv H7. rename x into tf.\n  assert (MF: match_function f tf) by (apply transf_function_match; auto).\n  inversion MF; subst.\n  econstructor; split.\n  apply plus_one. constructor. simpl; eauto. reflexivity.\n  constructor; auto.\n- (* external function *)\n  monadInv H8. econstructor; split.\n  apply plus_one. econstructor; eauto.\n  eapply external_call_symbols_preserved'. eauto.\n  exact symbols_preserved. exact public_preserved. exact varinfo_preserved.\n  constructor; auto.\n- (* return *)\n  inv H3. inv H1.\n  econstructor; split.\n  eapply plus_left. econstructor. apply eval_add_delta_ranges. traceEq.\n  constructor; auto.\nQed.\n\nLemma transf_initial_states:\n  forall st1, initial_state prog st1 ->\n  exists st2, initial_state tprog st2 /\\ match_states st1 st2.\nProof.\n  intros. inversion H.\n  exploit function_ptr_translated; eauto. intros [tf [A B]].\n  exists (Callstate nil tf (Locmap.init Vundef) m0); split.\n  econstructor; eauto. eapply Genv.init_mem_transf_partial; eauto.\n  replace (prog_main tprog) with (prog_main prog).\n  rewrite symbols_preserved. eauto.\n  symmetry. apply (transform_partial_program_main transf_fundef _ TRANSF).\n  rewrite <- H3. apply sig_preserved. auto.\n  constructor. constructor. auto.\nQed.\n\nLemma transf_final_states:\n  forall st1 st2 r,\n  match_states st1 st2 -> final_state st1 r -> final_state st2 r.\nProof.\n  intros. inv H0. inv H. inv H6. econstructor; eauto.\nQed.\n\nTheorem transf_program_correct:\n  forward_simulation (semantics prog) (semantics tprog).\nProof.\n  eapply forward_simulation_plus.\n  eexact public_preserved.\n  eexact transf_initial_states.\n  eexact transf_final_states.\n  eexact transf_step_correct.\nQed.\n\nEnd PRESERVATION.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/compcert/backend/Debugvarproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.23801850911057468}}
{"text": "From Coq.Unicode Require Import Utf8.\n\nAxiom FunExt :\n  ∀ (A : Type) (B : A → Type) (f g : ∀ x, B x), (∀ x, f x = g x) → f = g.\n\nAxiom PropExt : ∀ P Q : Prop, P ↔ Q → P = Q.\n\nLemma ProofIrrelevance : ∀ P : Prop, ∀ p q : P, p = q.\nProof.\n  intros P p q.\n  assert (True = P) as HP.\n  { apply PropExt; split; auto. }\n  revert p q.\n  refine (match HP in _ = u return ∀ p q : u, p = q :> u with eq_refl => _ end).\n  intros [] []; trivial.\nQed.\n\nAxiom Choice :\n  ∀ A B (R : A → B → Prop), (∀ x, ∃ y, R x y) → {f : A → B | ∀ x, R x (f x)}.\n\nDefinition epsilon {A : Type} {P : A → Prop} (Hex : ∃ x, P x) : A :=\n  proj1_sig (Choice unit A (λ _ x, P x) (λ _, Hex)) tt.\n\nLemma epsilon_correct {A : Type} (P : A → Prop) (Hex : ∃ x, P x) :\n  P (epsilon Hex).\nProof.\n  exact (proj2_sig (Choice unit A (λ _ x, P x) (λ _, Hex)) tt).\nQed.\n\nLemma ExcludedMiddle (P : Prop) : P ∨ ¬ P.\nProof.\n  set (PA b := b = true ∨ P).\n  set (PB b := b = false ∨ P).\n  set (U := sig (λ s, s = PA ∨ s = PB)).\n  set (R := (λ u b, proj1_sig u b) : U → bool → Prop).\n  assert (∀ u, ∃ b, R u b) as HR.\n  { intros u.\n    unfold R.\n    destruct (proj2_sig u) as [->| ->]; unfold PA, PB; eauto. }\n  apply Choice in HR as [f Hf].\n  set (A := exist _ _ (or_introl eq_refl) : U); simpl in *.\n  set (B := exist _ _ (or_intror eq_refl) : U); simpl in *.\n  assert (P ↔ A = B) as HPAB.\n  { split.\n    - intros HP.\n      unfold A, B.\n      assert (PA = PB) as ->.\n      { unfold PA, PB.\n        apply FunExt; intros x; apply PropExt; tauto. }\n      rewrite (ProofIrrelevance _ (or_introl eq_refl) (or_intror eq_refl));\n        trivial.\n    - intros HAB.\n      assert (proj1_sig A = proj1_sig B) as HPAB; [rewrite HAB; trivial|].\n      simpl in *.\n      assert (PA false) as HPAf; [rewrite HPAB; unfold PB; auto; fail|].\n      destruct HPAf; [congruence| trivial]. }\n  pose proof (Hf A) as HfA.\n  pose proof (Hf B) as HfB.\n  simpl in *.\n  destruct (f A) eqn:Aeq.\n  - destruct (f B) eqn:Beq.\n    + destruct HfB; [congruence| auto].\n    + right. intros HP; apply HPAB in HP. congruence.\n  - destruct HfA; [congruence| auto].\nQed.\n\nLemma NNP_P : ∀ P : Prop, ¬ ¬ P → P.\nProof.\n  intros P NNP.\n  destruct (ExcludedMiddle P); [trivial; fail|].\n  exfalso; apply NNP; trivial.\nQed.\n\nLemma P_NNP : ∀ P : Prop, P → ¬ ¬ P.\nProof.\n  intros P HP HnP; apply HnP; trivial.\nQed.\n\nLemma contrapositive : ∀ P Q : Prop, (¬ Q → ¬ P) → P → Q.\nProof.\n  intros P Q Hcontra HP.\n  destruct (ExcludedMiddle Q); [trivial; fail|].\n  exfalso; apply Hcontra; trivial.\nQed.\n\nLemma not_exists_forall_not :\n  ∀ (A : Type) (P : A → Prop), ¬ (∃ x, P x) → ∀ x, ¬ P x.\nProof. intros A P Hnex x HP; apply Hnex; eauto. Qed.\n\nLemma not_forall_exists_not :\n  ∀ (A : Type) (P : A → Prop), ¬ (∀ x, P x) → ∃ x, ¬ P x.\nProof.\n  intros A P.\n  apply contrapositive.\n  intros Hnex; apply P_NNP.\n  intros x; apply NNP_P; revert x.\n  apply not_exists_forall_not; trivial.\nQed.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/trillium/prelude/classical.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.23801850306234656}}
{"text": "(*\n * Copyright (c) 2017-present,\n * Programming Research Laboratory (ROPAS), Seoul National University, Korea\n * This software is distributed under the term of the BSD-3 clause license.\n *)\n(** * Abstract semantics (context-insen + localized) *)\n\nSet Implicit Arguments.\n\nRequire Import hpattern vgtac.\nRequire Import Global UserProofType DStr Syn Global.\nRequire DomCon SemCon DomInsen.\nRequire Import SemCommon.\n\nModule Make (Import PInput : PINPUT).\n\nLocal Open Scope type.\n\nInclude DomInsen.Make PInput.\n\nSection Sem.\n\nVariable g : G.t.\n\nLet pgm : InterCfg.t := G.icfg g.\n\nLet mode : UserInputType.update_mode := UserInputType.Strong.\n\nVariable amap : access_map.\n\nDefinition postfix_cmd (cn : InterNode.t) (s : state_t) : Prop :=\n  forall cmd (Hcmd : Some cmd = InterCfg.get_cmd pgm cn),\n    let m := s (cn, Inputof) in\n    let m' := run_only mode g cn cmd m in\n    let m'' := s (cn, Outputof) in\n    Mem.le m' m''.\n\nDefinition postfix_intra_edge (cn : InterNode.t) (s : state_t) : Prop :=\n  let p := InterNode.get_pid cn in\n  let n := InterNode.get_node cn in\n  forall n' cfg\n         (Hcfg : InterCfg.PidMap.MapsTo p cfg (InterCfg.cfgs pgm))\n         (Hedge : IntraCfg.is_succ cfg n n')\n         (Hcn_cond: not (InterCfg.is_call_node pgm cn)),\n    Mem.le (s (cn, Outputof)) (s ((p, n'), Inputof)).\n\nDefinition postfix_intra_call (cn : InterNode.t) (s : state_t) : Prop :=\n  forall callee (Hedge : InterCfg.is_succ pgm cn (callee, IntraNode.Entry))\n         retn (Hretn : Some retn = InterCfg.returnof pgm cn),\n    let access := get_all_access callee amap in\n    let m := s (cn, Outputof) in\n    let m' := Mem.subtract access m in\n    Mem.le m' (s (retn, Inputof)).\n\nDefinition postfix_inter_call (cn : InterNode.t) (s : state_t) : Prop :=\n  forall callee (Hedge : InterCfg.is_succ pgm cn (callee, IntraNode.Entry)),\n    let access := get_all_access callee amap in\n    let m := s (cn, Outputof) in\n    let m' := Mem.restrict access m in\n    Mem.le m' (s ((callee, IntraNode.Entry), Inputof)).\n\nDefinition postfix_inter_ret (cn : InterNode.t) \n           (s : state_t) : Prop :=\n  forall p (Hp : cn = (p, IntraNode.Exit))\n         cn' (Hedge : InterCfg.is_succ pgm cn cn')\n         calln (Hret: Some cn' = InterCfg.returnof pgm calln),\n    Mem.le (s (cn, Outputof)) (s (cn', Inputof)).\n\nDefinition postfix (s : state_t) : Prop :=\n  forall (cn : InterNode.t)  ,\n    postfix_cmd cn s\n    /\\ postfix_intra_edge cn s\n    /\\ postfix_intra_call cn s\n    /\\ postfix_inter_call cn s\n    /\\ postfix_inter_ret cn s.\n\nDefinition sound_amap_run (s : state_t) :=\n  forall cn cmd (Hcmd : Some cmd = InterCfg.get_cmd pgm cn),\n    Acc.le\n      (Acc.get_acc (run_access mode g cn cmd (s (cn, SemCommon.Inputof))))\n      (get_access (InterNode.get_pid cn) amap).\n\nDefinition sound_amap_reachable :=\n  forall f1 f2 (Hr : InterCfg.reachable pgm f1 f2),\n    Acc.le (get_access f2 amap) (get_access f1 amap).\n\nDefinition sound_amap (s : state_t) : Prop :=\n  sound_amap_run s /\\ sound_amap_reachable.\n\nEnd Sem.\n\nLocal Close Scope type.\n\nEnd Make.\n", "meta": {"author": "ropas", "repo": "zooberry", "sha": "17b1cb1a44c2a796d6b7d85c2026b142685d291b", "save_path": "github-repos/coq/ropas-zooberry", "path": "github-repos/coq/ropas-zooberry/zooberry-17b1cb1a44c2a796d6b7d85c2026b142685d291b/spec/Proof/SemInsenLocal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23801850306234654}}
{"text": "(* Do not edit this file, it was generated automatically *)\n(** Heavily annotated for a tutorial introduction. *)\n\n(** First, import the entire Floyd proof automation system, which includes\n ** the VeriC program logic and the MSL theory of separation logic**)\nRequire Import VST.floyd.proofauto.\n\n(** Import the [reverse.v] file, which is produced by CompCert's clightgen\n ** from reverse.c.   The file reverse.v defines abbreviations for identifiers\n ** (variable names, etc.) of the C program, such as _head, _reverse.\n ** It also defines \"prog\", which is the entire abstract syntax tree\n ** of the C program *)\nRequire Import VST.progs64.reverse.\n\n(* The C programming language has a special namespace for struct\n** and union identifiers, e.g., \"struct foo {...}\".  Some type-based operators\n** in the program logic need access to an interpretation of this namespace,\n** i.e., the meaning of each struct-identifier such as \"foo\".  The next\n** line (which looks identical for any program) builds this\n** interpretation, called \"CompSpecs\" *)\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\n\n(** Calculate the \"types-of-global-variables\" specification\n ** directly from the program *)\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n(** A convenience definition *)\nDefinition t_struct_list := Tstruct _list noattr.\n\n(** Inductive definition of linked lists *)\nFixpoint listrep (sigma: list val) (x: val) : mpred :=\n match sigma with\n | h::hs => \n    EX y:val, \n      data_at Tsh t_struct_list (h,y) x  *  listrep hs y\n | nil => \n    !! (x = nullval) && emp\n end.\n\nArguments listrep sigma x : simpl never.\n\n(** Whenever you define a new spatial operator, such as\n ** [listrep] here, it's useful to populate two hint databases.\n ** The [saturate_local] hint is a lemma that extracts\n ** pure propositional facts from a spatial fact.\n ** The [valid_pointer] hint is a lemma that extracts a\n ** valid-pointer fact from a spatial lemma.\n **)\n\nLemma listrep_local_facts:\n  forall sigma p,\n   listrep sigma p |--\n   !! (is_pointer_or_null p /\\ (p=nullval <-> sigma=nil)).\nProof.\nintros.\nrevert p; induction sigma; \n  unfold listrep; fold listrep; intros; normalize.\napply prop_right; split; simpl; auto. intuition.\nentailer!.\nsplit; intro. subst p. destruct H; contradiction. inv H2.\nQed.\n\nHint Resolve listrep_local_facts : saturate_local.\n\nLemma listrep_valid_pointer:\n  forall sigma p,\n   listrep sigma p |-- valid_pointer p.\nProof.\n destruct sigma; unfold listrep; fold listrep;\n intros; normalize.\n auto with valid_pointer.\n apply sepcon_valid_pointer1.\n apply data_at_valid_ptr; auto.\n simpl;  computable.\nQed.\n\nHint Resolve listrep_valid_pointer : valid_pointer.\n\n(** Specification of the [reverse] function.  It characterizes\n ** the precondition required for calling the function,\n ** and the postcondition guaranteed by the function.\n **)\nDefinition reverse_spec :=\n DECLARE _reverse\n  WITH sigma : list val, p: val\n  PRE  [ _p OF (tptr t_struct_list) ]\n     PROP ()\n     LOCAL (temp _p p)\n     SEP (listrep sigma p)\n  POST [ (tptr t_struct_list) ]\n    EX q:val,\n     PROP () LOCAL (temp ret_temp q)\n     SEP (listrep(rev sigma) q).\n\n(** The global function spec, characterizing the\n ** preconditions/postconditions of all the functions\n ** that your proved-correct program will call. \n ** Normally you include all the functions here, but\n ** in this tutorial example we include only one. *)\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ reverse_spec ]).\n\n(** For each function definition in the C program, prove that the\n ** function-body (in this case, f_reverse) satisfies its specification\n ** (in this case, reverse_spec).\n **)\nLemma body_reverse: semax_body Vprog Gprog\n                                    f_reverse reverse_spec.\nProof.\n(** The start_function tactic \"opens up\" a semax_body\n ** proof goal into a Hoare triple. *)\nstart_function.\n(** For each assignment statement, \"symbolically execute\" it\n ** using the forward tactic *)\nforward.  (* w = NULL; *)\nforward.  (* v = p; *)\n(** To prove a while-loop, you must supply a loop invariant,\n ** in this case (EX s1  PROP(...)LOCAL(...)(SEP(...)).  *)\nforward_while\n   (EX s1: list val, EX s2 : list val, \n    EX w: val, EX v: val,\n     PROP (sigma = rev s1 ++ s2)\n     LOCAL (temp _w w; temp _v v)\n     SEP (listrep s1 w; listrep s2 v)).\n(** The forward_while tactic leaves four subgoals,\n ** which we mark with * (the Coq \"bullet\") *)\n* (* Prove that precondition implies loop invariant *)\nExists (@nil val) sigma nullval p.\nentailer!.\nunfold listrep.\nentailer!.\n* (* Prove that loop invariant implies typechecking of loop condition *)\nentailer!.\n* (* Prove that loop body preserves invariant *)\ndestruct s2 as [ | h r].\n - unfold listrep at 2. \n   Intros. subst. contradiction.\n - unfold listrep at 2; fold listrep.\n   Intros y.\n   forward. (* t = v->tail *)\n   forward. (* v->tail = w; *)\n   forward. (* w = v; *)\n   forward. (* v = t; *)\n   (* At end of loop body; reestablish invariant *)\n   entailer!.\n   Exists (h::s1,r,v,y).\n   entailer!.\n   + simpl. rewrite app_ass. auto.\n   + unfold listrep at 3; fold listrep.\n     Exists w. entailer!.\n* (* after the loop *)\nforward.  (* return w; *)\nExists w; entailer!.\nrewrite (proj1 H1) by auto.\nunfold listrep at 2; fold listrep.\nentailer!.\nrewrite <- app_nil_end, rev_involutive.\nauto.\nQed.\n\n(** See the file [progs/verif_reverse.v] for an alternate\n ** proof of this function, using a general theory of\n ** list segments.  That file also has proofs of the\n ** sumlist function, the main function, and the\n ** [semax_func] theorem that ties all the functions together\n **)\n\n", "meta": {"author": "anshumanmohan", "repo": "RamifyCoq_VST", "sha": "0517a39b069f79f50a45321db6ca81c48397b73d", "save_path": "github-repos/coq/anshumanmohan-RamifyCoq_VST", "path": "github-repos/coq/anshumanmohan-RamifyCoq_VST/RamifyCoq_VST-0517a39b069f79f50a45321db6ca81c48397b73d/VST/progs64/verif_reverse2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.23789785362482155}}
{"text": "(**\n * Special handling of ascii and strings for extraction to Haskell.\n *)\n\nRequire Coq.extraction.Extraction.\n\nRequire Import Ascii.\nRequire Import String.\n\n(**\n * At the moment, Coq's extraction has no way to add extra import\n * statements to the extracted Haskell code.  You will have to\n * manually add:\n *\n *   import qualified Data.Bits\n *   import qualified Data.Char\n *)\n\nExtract Inductive ascii => \"Prelude.Char\"\n  [ \"(\\b0 b1 b2 b3 b4 b5 b6 b7 -> Data.Char.chr (\n      (if b0 then Data.Bits.shiftL 1 0 else 0) Prelude.+\n      (if b1 then Data.Bits.shiftL 1 1 else 0) Prelude.+\n      (if b2 then Data.Bits.shiftL 1 2 else 0) Prelude.+\n      (if b3 then Data.Bits.shiftL 1 3 else 0) Prelude.+\n      (if b4 then Data.Bits.shiftL 1 4 else 0) Prelude.+\n      (if b5 then Data.Bits.shiftL 1 5 else 0) Prelude.+\n      (if b6 then Data.Bits.shiftL 1 6 else 0) Prelude.+\n      (if b7 then Data.Bits.shiftL 1 7 else 0)))\" ]\n  \"(\\f a -> f (Data.Bits.testBit (Data.Char.ord a) 0)\n              (Data.Bits.testBit (Data.Char.ord a) 1)\n              (Data.Bits.testBit (Data.Char.ord a) 2)\n              (Data.Bits.testBit (Data.Char.ord a) 3)\n              (Data.Bits.testBit (Data.Char.ord a) 4)\n              (Data.Bits.testBit (Data.Char.ord a) 5)\n              (Data.Bits.testBit (Data.Char.ord a) 6)\n              (Data.Bits.testBit (Data.Char.ord a) 7))\".\nExtract Inlined Constant Ascii.ascii_dec => \"(Prelude.==)\".\n\nExtract Inductive string => \"Prelude.String\" [ \"([])\" \"(:)\" ].\nExtract Inlined Constant String.string_dec => \"(Prelude.==)\".\n", "meta": {"author": "Priyanka-Mondal", "repo": "Coq", "sha": "220c3eccfa5643b1ca2398d4940e29917da786d9", "save_path": "github-repos/coq/Priyanka-Mondal-Coq", "path": "github-repos/coq/Priyanka-Mondal-Coq/Coq-220c3eccfa5643b1ca2398d4940e29917da786d9/lib/plugins/extraction/ExtrHaskellString.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2378978536248215}}
{"text": "From HTTP Require Export\n     Tester.\nFrom App Require Export\n     Observe.\n\nDefinition solver_state := list (var * (N + list N)).\n\nDefinition assertN (nx : exp N) (n : N) (s : solver_state)\n  : option solver_state :=\n  match nx with\n  | Exp__Var x =>\n    match get x s with\n    | Some (inl n0) => if n0 =? n then Some s else None\n    | Some (inr ns) => if existsb (N.eqb n) ns\n                      then None\n                      else Some $ update x (inl n) s\n    | None => Some $ put x (inl n) s\n    end\n  | Exp__Const n0 => if n0 =? n then Some s else None\n  | Exp__Nth _ _  => None\n  end.\n\nDefinition assertNotN (nx : exp N) (n : N) (s : solver_state)\n  : option solver_state :=\n  match nx with\n  | Exp__Var x =>\n    match get x s with\n    | Some (inl n0) => if n0 =? n then None else Some s\n    | Some (inr ns) => Some $ update x (inr (n::ns)) s\n    | None => Some $ put x (inr [n]) s\n    end\n  | Exp__Const n0 => if n0 =? n then None else Some s\n  | Exp__Nth _ _ => None\n  end.\n\nDefinition unifyOrder (s : solver_state) (ox : orderT exp) (o : orderT id)\n  : option solver_state :=\n  let '((oidx, (bix, bax, six, sax)), (oid, (bi, ba, si, sa))) := (ox, o) in\n  if (bax, sax) = (ba, sa)?\n  then assertN oidx oid s >>= assertN bix bi >>= assertN six si\n  else None.\n\nDefinition unifyAccount (s : solver_state) (ax : accountT exp) (a : accountT id)\n  : option solver_state :=\n  let '((aidx, vx), (aid, v)) := (ax, a) in\n  if vx = v? then assertN aidx aid s else None.\n\nDefinition unifyList {A : (Type -> Type) -> Type}\n           (unifier : solver_state -> A exp -> A id -> option solver_state)\n           (lx : list (A exp)) (l : list (A id)) (s : solver_state)\n  : option solver_state :=\n  if length lx =? length l\n  then fold_left (fun os ab => os >>= (fun s => uncurry (unifier s) ab))\n                 (zip lx l) (pure s)\n  else None.\n\nFixpoint eval_nth_const {E} `{decideE -< E} `{failureE -< E}\n           (n : N) (l : list (exp N))\n  : Monads.stateT solver_state (itree E) nat :=\n  fun s =>\n    match l with\n    | [] => ret (s, O)\n    | x::l' =>\n      let left  s1 := ret (s1, O) in\n      let right s2 := '(s3, n') <- eval_nth_const n l' s2;;\n                      ret (s3, S n') in\n      match assertN x n s, assertNotN x n s with\n      | Some s1, Some s2 =>\n        b <- trigger Decide;;\n        if b : bool then left s1 else right s2\n      | Some s1, None => left s1\n      | None, Some s2 => right s2\n      | None, None => throw \"Unsatisfiable\"\n      end\n    end.\n\nFixpoint find_nth {A} (f : A -> bool) (l : list A) : option nat :=\n  if l is a::l'\n  then if f a then Some O else S <$> find_nth f l'\n  else None.\n\nDefinition eval_nth {E} `{decideE -< E} `{failureE -< E}\n         (x : exp N) (l : list (exp N))\n  : Monads.stateT solver_state (itree E) nat :=\n  fun s =>\n    if find_nth (exp_eq x) l is Some n\n    then ret (s, n)\n    else\n      match x with\n      | Exp__Var x =>\n        match get x s with\n        | Some (inl n) => eval_nth_const n l s\n        | _ => ret (s, length l)\n        end\n      | Exp__Const n => eval_nth_const n l s\n      | _ => throw \"Should not happen: eval_nth\"\n      end.\n\nDefinition instantiate_unify {E A} `{failureE -< E} `{decideE -< E}\n           (e : unifyE swap_response A)\n  : Monads.stateT solver_state (itree E) A :=\n  fun s : solver_state =>\n    match e with\n    | Unify__Fresh =>\n      let x : var := fresh_var s in\n      ret (put x (inr []) s, Exp__Var x)\n    | Unify__Eval v =>\n      if v is Exp__Nth n l\n      then eval_nth n l s\n      else throw \"Should not happen: instantiate_unify\"\n    | Unify__Match rx r =>\n      let mismatch := throw $ \"Expect \" ++ to_string rx\n                            ++ \" but observed \" ++ to_string r\n                            ++ \" under \" ++ to_string s in\n      let handle os' := if os' is Some s' then ret (s', tt) else mismatch in\n      match rx, r with\n      | Response__BadRequest      , Response__BadRequest\n      | Response__InsufficientFund, Response__InsufficientFund\n      | Response__NotFound        , Response__NotFound => ret (s, tt)\n      | Response__ListAccount lx  , Response__ListAccount l =>\n        handle $ unifyList (A:=accountT) unifyAccount lx l s\n      | Response__ListOrders  lx  , Response__ListOrders  l =>\n        handle $ unifyList (A:=orderT) unifyOrder lx l s\n      | Response__ListAccount [], Response__ListOrders  []\n      | Response__ListOrders  [], Response__ListAccount [] => ret (s, tt)\n      | Response__Account ax, Response__Account a => handle $ unifyAccount s ax a\n      | Response__Order   ox, Response__Order   o => handle $ unifyOrder   s ox o\n      | _, _ => mismatch\n      end\n    end.\n\nDefinition solver' {E F} `{failureE -< E} `{decideE -< E} `{F -< E}\n           (m : itree (unifyE swap_response +' F) void)\n  : Monads.stateT solver_state (itree E) void :=\n  interp\n    (fun _ e =>\n       match e with\n       | (ue|) => instantiate_unify ue\n       | (|ee)  => liftState (F:=itree _) (trigger ee)\n       end) m.\n\nDefinition solver {E F} `{failureE -< E} `{decideE -< E} `{F -< E}\n           (m : itree (unifyE swap_response +' F) void) : itree E void :=\n  snd <$> solver' m [].\n\nClass Is__stE q r s E `{failureE -< E} `{decideE -< E} `{observeE q r s -< E}.\nNotation stE q r s := (failureE +' decideE +' observeE q r s).\nInstance stE_Is__stE q r s : Is__stE q r s (stE q r s). Defined.\n\nDefinition solve_swap {E}\n           `{Is__stE (swap_request id) (swap_response id) (swap_state exp) E}\n           : swap_state exp -> itree E void\n  := solver ∘ observe_swap.\n", "meta": {"author": "liyishuai", "repo": "coq-http", "sha": "a0c97d1a7f0e1c7d5571ed3f3c117fd4732069bf", "save_path": "github-repos/coq/liyishuai-coq-http", "path": "github-repos/coq/liyishuai-coq-http/coq-http-a0c97d1a7f0e1c7d5571ed3f3c117fd4732069bf/app/Solver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.23776554053981008}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import BaremoreHandler.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition smc_mark_nonsecure_spec0 (addr: Z64) (adt: RData) : option RData :=\n    match addr with\n    | VZ64 _addr =>\n      rely is_int64 (3288334336 + 257);\n      rely is_int (3288334336 + 257);\n      rely is_int64 _addr;\n      when adt == set_monitor_call_spec (3288334336 + 257) (VZ64 _addr) adt;\n      when adt == el3_sync_lel_spec  adt;\n      when' _t'1 == get_monitor_call_ret_spec  adt;\n      rely is_int64 _t'1;\n      rely is_int _t'1;\n      let _ret := _t'1 in\n      rely is_int (1 - _ret);\n      when adt == assert_cond_spec (1 - _ret) adt;\n      Some adt\n     end\n    .\n\nEnd SpecLow.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/BaremoreSMC/LowSpecs/smc_mark_nonsecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2377655317183599}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype fintype choice ssrfun seq path.\n\nFrom mathcomp.ssreflect\nRequire Import tuple.\n\nSet Implicit Arguments.\n\n\nFrom Probchain\nRequire Import BlockChain InvMisc FixedList FixedMap Parameters.\n\n\nDefinition oraclestate_keytype := [eqType of ([eqType of ([eqType of Nonce] * [eqType of Hashed] * [eqType of BlockRecord])] )%type].\n\nDefinition OracleState := fixmap  oraclestate_keytype  [eqType of Hashed] oraclestate_size.\n\nDefinition oraclestate_new : OracleState := fixmap_empty oraclestate_keytype [eqType of Hashed] oraclestate_size.\n\n\nDefinition oraclestate_find k (m : OracleState) := fixmap_find k m.\n\n\n\nDefinition oraclestate_put (k: oraclestate_keytype) (v : Hashed) (m: OracleState) : OracleState :=\n  fixmap_put k v m.\n\n\nCanonical oraclestate_of_eqType := Eval hnf in [eqType of (OracleState)].\nCanonical oraclestate_of_choiceType := Eval hnf in [choiceType of (OracleState)].\nCanonical oraclestate_of_countType := Eval hnf in [countType of (OracleState)].\nCanonical oraclestate_of_finType := Eval hnf in [finType of (OracleState)].\n\n\n\n", "meta": {"author": "certichain", "repo": "probchain", "sha": "5ab581529565d2234c472964966bced07ff1809b", "save_path": "github-repos/coq/certichain-probchain", "path": "github-repos/coq/certichain-probchain/probchain-5ab581529565d2234c472964966bced07ff1809b/Structures/OracleState.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.37754066179448903, "lm_q1q2_score": 0.23776552206082674}}
{"text": "Require Import Kami.AllNotations.\n\nRequire Import ProcKami.FU.\n\nSection pmp.\n  Context {procParams: ProcParams}.\n  Variable ty: Kind -> Type.\n  \n  Local Open Scope kami_expr.\n  Local Open Scope kami_action.\n\n  Local Definition PmpEntryPkt\n    := STRUCT_TYPE {\n         \"cfg\" :: PmpCfg ;\n         \"addr\" :: Bit pmp_reg_width\n         }.\n\n  Local Definition pmp_entry_read\n    (n : nat)\n    :  ActionT ty PmpEntryPkt\n    := Read entry_cfg\n         :  PmpCfg\n         <- @^(\"pmp\" ++ natToHexStr n ++ \"cfg\");\n       Read entry_addr\n         :  Bit pmp_reg_width\n         <- @^(\"pmpaddr\" ++ natToHexStr n);\n       Ret\n         (STRUCT {\n            \"cfg\" ::= #entry_cfg;\n            \"addr\" ::= #entry_addr\n          } : PmpEntryPkt @# ty).\n\n  Local Definition pmp_addr_acc_kind\n    := STRUCT_TYPE {\n         \"any_matched\" :: Bool;\n         \"all_matched\" :: Bool\n       }.\n\n  Local Definition pmp_entry_acc_kind\n    := STRUCT_TYPE {\n         \"any_on\"  :: Bool;\n         \"addr\"    :: PAddr;\n         \"matched\" :: Bool;\n         \"pmp_cfg\" :: PmpCfg\n       }.\n\n  Local Definition div_up x y\n    := (if Nat.eqb (x mod y) 0\n         then x / y\n         else S (x / y))%nat.\n\n  Definition checkPmp\n    (check : AccessType @# ty)\n    (mode : PrivMode @# ty)\n    (addr : PAddr @# ty)\n    (addr_len : MemRqLgSize @# ty)\n    :  ActionT ty Bool\n    := (* System [\n         DispString _ \"[checkPmp] addr: \";\n         DispHex addr;\n         DispString _ \"\\n\";\n         DispString _ \"[checkPmp] addr len: \";\n         DispHex addr_len;\n         DispString _ \"\\n\"\n       ]; *)\n       LETA result\n         :  pmp_entry_acc_kind\n         <- fold_left\n              (fun (acc_act : ActionT ty pmp_entry_acc_kind) entry_index\n                => LETA acc <- acc_act;\n(*\n                   System [\n                     DispString _ \"[checkPmp] ==================================================\\n\";\n                     DispString _ (\"[checkPmp] checking register: pmp\" ++ natToHexStr (S entry_index) ++ \"cfg.\\n\");\n                     DispString _ \"[checkPmp] acc: \";\n                     DispHex #acc;\n                     DispString _ \"\\n\"\n                   ];\n*)\n                   LETA entry\n                     :  PmpEntryPkt\n                     <- pmp_entry_read entry_index;\n                   LET tor\n                     :  PAddr\n                     <- ((ZeroExtendTruncLsb PAddrSz (#entry @% \"addr\")) << (Const ty (natToWord 2 2)));\n(*\n                   System [\n                     DispString _ \"[checkPmp] entry: \";\n                     DispHex #entry;\n                     DispString _ \"\\n\";\n                     DispString _ \"[checkPmp] entry addr: \";\n                     DispHex (#entry @% \"addr\");\n                     DispString _ \"\\n\";\n                     DispString _ \"[checkPmp] sign extended entry addr: \";\n                     DispHex (#entry @% \"addr\");\n                     DispString _ \"\\n\";\n                     DispString _ \"[checkPmp] tor: \";\n                     DispHex #tor;\n                     DispString _ \"\\n\"\n                   ];\n*)\n                   LET mask0\n                     :  PAddr\n                     <- ((ZeroExtendTruncLsb PAddrSz (#entry @% \"addr\")) << (Const ty (natToWord 1 1))) .| $1;\n                   LET mask\n                     :  PAddr\n                     <- ~ (#mask0 .&  (~ (#mask0 + $1))) << (Const ty (natToWord 2 2));\n(*\n                   System [\n                     DispString _ \"[checkPmp] mask: \";\n                     DispHex #mask;\n                     DispString _ \"\\n\"\n                   ];\n*)\n                   GatherActions\n                     (map\n                       (fun index\n                         => LET offset\n                              :  Bit MemRqSize\n                              <- Const ty (natToWord MemRqSize (4 * index)%nat);\n                            If #offset < ($1 << addr_len)\n                              then\n                                LET curr_addr\n                                  :  PAddr\n                                  <- (addr + (ZeroExtendTruncLsb PAddrSz #offset));\n                                LET napot_match\n                                  :  Bool\n                                  <- ((CABit Bxor [#curr_addr; #tor]) .&  #mask) == $0;\n                                LET tor_match\n                                  :  Bool\n                                  <- (#acc @% \"addr\" <= #curr_addr) &&  (#curr_addr < #tor);\n                                LET matched\n                                  :  Bool\n                                  <- IF #entry @% \"cfg\" @% \"A\" == $1\n                                       then #tor_match\n                                       else #napot_match;\n                                Ret (Valid #matched : Maybe Bool @# ty)\n                              else Ret Invalid\n                              as result;\n                            Ret #result)\n                       (seq 0 (div_up Rlen_over_8 4)))\n                     as match_results;\n                   LET addr_result\n                     :  pmp_addr_acc_kind\n                     <- STRUCT {\n                          \"any_matched\"\n                            ::= (@Kor _ Bool)\n                                  (map\n                                    (fun result : Maybe Bool @# ty\n                                      => result @% \"valid\" &&  result @% \"data\")\n                                    match_results);\n                          \"all_matched\"\n                            ::= CABool And\n                                  (map\n                                    (fun result : Maybe Bool @# ty\n                                      => !(result @% \"valid\") || result @% \"data\") \n                                    match_results)\n                        } : pmp_addr_acc_kind @# ty;\n                   LET isOff <- #entry @% \"cfg\" @% \"A\" == $0;\n                   Ret (STRUCT {\n                            \"any_on\"  ::= ((#acc @% \"any_on\") || !#isOff) ;\n                            \"addr\"    ::= #tor ;\n                            \"matched\" ::= ((#acc @% \"matched\") ||\n                                           (!#isOff &&  #addr_result @% \"all_matched\"));\n                            \"pmp_cfg\" ::= (IF #acc @% \"matched\"\n                                           then #acc @% \"pmp_cfg\"\n                                           else #entry @% \"cfg\") }: pmp_entry_acc_kind @# ty))\n              (seq 0 16)\n              (Ret (STRUCT {\n                 \"any_on\"  ::= $$false;\n                 \"addr\"    ::= $$(getDefaultConst PAddr);\n                 \"matched\" ::= $$false;\n                 \"pmp_cfg\" ::= $$(getDefaultConst PmpCfg)\n               } : pmp_entry_acc_kind @# ty));\n(*\n    System [\n         DispString _ \"[checkPmp] ##################################################\\n\";\n         DispString _ \"[checkPmp] result: \";\n         DispHex #result;\n         DispString _ \"\\n\"\n       ];\n*)\n       Ret\n         (IF #result @% \"matched\"\n          then\n             (mode == $MachineMode &&  !(#result @% \"pmp_cfg\" @% \"L\")) ||\n             (Switch check Retn Bool With {\n               ($VmAccessLoad : AccessType @# ty)\n                 ::= #result @% \"pmp_cfg\" @% \"R\";\n               ($VmAccessSAmo : AccessType @# ty)\n                 ::= #result @% \"pmp_cfg\" @% \"R\" &&  #result @% \"pmp_cfg\" @% \"W\";\n               ($VmAccessInst : AccessType @# ty)\n                 ::= #result @% \"pmp_cfg\" @% \"X\"\n             })\n           else\n             (!(#result @% \"any_on\") || mode == $MachineMode)).\n\n  Local Close Scope kami_action.\n  Local Close Scope kami_expr.\n\nEnd pmp.\n", "meta": {"author": "sifive", "repo": "ProcKami", "sha": "7094363c5587d50653b918c323e043105fd172d6", "save_path": "github-repos/coq/sifive-ProcKami", "path": "github-repos/coq/sifive-ProcKami/ProcKami-7094363c5587d50653b918c323e043105fd172d6/Pipeline/Mem/Pmp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23771549720630472}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect ssrbool ssrfun eqtype ssrnat seq fintype.\nRequire Import finfun paths ssralg.\n(*Require Import div connect.*)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nReserved Notation \"\\big [ op / nil ]_ i F\"\n  (at level 36, F at level 36, op, nil at level 10, i at level 0,\n     right associativity,\n           format \"'[' \\big [ op / nil ]_ i '/  '  F ']'\").\nReserved Notation \"\\big [ op / nil ]_ ( <- r | P ) F\"\n  (at level 36, F at level 36, op, nil at level 10, r at level 50,\n           format \"'[' \\big [ op / nil ]_ ( <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / nil ]_ ( i <- r | P ) F\"\n  (at level 36, F at level 36, op, nil at level 10, i, r at level 50,\n           format \"'[' \\big [ op / nil ]_ ( i  <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / nil ]_ ( i <- r ) F\"\n  (at level 36, F at level 36, op, nil at level 10, i, r at level 50,\n           format \"'[' \\big [ op / nil ]_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / nil ]_ ( m <= i < n | P ) F\"\n  (at level 36, F at level 36, op, nil at level 10, m, i, n at level 50,\n           format \"'[' \\big [ op / nil ]_ ( m  <=  i  <  n  |  P )  F ']'\").\nReserved Notation \"\\big [ op / nil ]_ ( m <= i < n ) F\"\n  (at level 36, F at level 36, op, nil at level 10, i, m, n at level 50,\n           format \"'[' \\big [ op / nil ]_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / nil ]_ ( i | P ) F\"\n  (at level 36, F at level 36, op, nil at level 10, i at level 50,\n           format \"'[' \\big [ op / nil ]_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / nil ]_ ( i : t | P ) F\"\n  (at level 36, F at level 36, op, nil at level 10, i at level 50,\n           format \"'[' \\big [ op / nil ]_ ( i   :  t   |  P ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / nil ]_ ( i : t ) F\"\n  (at level 36, F at level 36, op, nil at level 10, i at level 50,\n           format \"'[' \\big [ op / nil ]_ ( i   :  t ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / nil ]_ ( i < n | P ) F\"\n  (at level 36, F at level 36, op, nil at level 10, i, n at level 50,\n           format \"'[' \\big [ op / nil ]_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / nil ]_ ( i < n ) F\"\n  (at level 36, F at level 36, op, nil at level 10, i, n at level 50,\n           format \"'[' \\big [ op / nil ]_ ( i  <  n )  F ']'\").\nReserved Notation \"\\big [ op / nil ]_ ( i \\in A | P ) F\"\n  (at level 36, F at level 36, op, nil at level 10, i, A at level 50,\n           format \"'[' \\big [ op / nil ]_ ( i  \\in  A  |  P ) '/  '  F ']'\").\nReserved Notation \"\\big [ op / nil ]_ ( i \\in A ) F\"\n  (at level 36, F at level 36, op, nil at level 10, i, A at level 50,\n           format \"'[' \\big [ op / nil ]_ ( i  \\in  A ) '/  '  F ']'\").\n\nReserved Notation \"\\sum_ i F\"\n  (at level 41, F at level 41, i at level 0,\n           right associativity,\n           format \"'[' \\sum_ i '/  '  F ']'\").\nReserved Notation \"\\sum_ ( <- r | P ) F\"\n  (at level 41, F at level 41, r at level 50,\n           format \"'[' \\sum_ ( <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i <- r | P ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\sum_ ( i  <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i <- r ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\sum_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( m <= i < n | P ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\sum_ ( m  <=  i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( m <= i < n ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\sum_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\sum_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i : t | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           only parsing).\nReserved Notation \"\\sum_ ( i : t ) F\"\n  (at level 41, F at level 41, i at level 50,\n           only parsing).\nReserved Notation \"\\sum_ ( i < n | P ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\sum_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i < n ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\sum_ ( i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i \\in A | P ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\sum_ ( i  \\in  A  |  P ) '/  '  F ']'\").\nReserved Notation \"\\sum_ ( i \\in A ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\sum_ ( i  \\in  A ) '/  '  F ']'\").\n\nReserved Notation \"\\max_ i F\"\n  (at level 41, F at level 41, i at level 0,\n           format \"'[' \\max_ i '/  '  F ']'\").\nReserved Notation \"\\max_ ( <- r | P ) F\"\n  (at level 41, F at level 41, r at level 50,\n           format \"'[' \\max_ ( <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( i <- r | P ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\max_ ( i  <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( i <- r ) F\"\n  (at level 41, F at level 41, i, r at level 50,\n           format \"'[' \\max_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( m <= i < n | P ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\max_ ( m  <=  i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( m <= i < n ) F\"\n  (at level 41, F at level 41, i, m, n at level 50,\n           format \"'[' \\max_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( i | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           format \"'[' \\max_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( i : t | P ) F\"\n  (at level 41, F at level 41, i at level 50,\n           only parsing).\nReserved Notation \"\\max_ ( i : t ) F\"\n  (at level 41, F at level 41, i at level 50,\n           only parsing).\nReserved Notation \"\\max_ ( i < n | P ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\max_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( i < n ) F\"\n  (at level 41, F at level 41, i, n at level 50,\n           format \"'[' \\max_ ( i  <  n )  F ']'\").\nReserved Notation \"\\max_ ( i \\in A | P ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\max_ ( i  \\in  A  |  P ) '/  '  F ']'\").\nReserved Notation \"\\max_ ( i \\in A ) F\"\n  (at level 41, F at level 41, i, A at level 50,\n           format \"'[' \\max_ ( i  \\in  A ) '/  '  F ']'\").\n\nReserved Notation \"\\prod_ i F\"\n  (at level 36, F at level 36, i at level 0,\n           format \"'[' \\prod_ i '/  '  F ']'\").\nReserved Notation \"\\prod_ ( <- r | P ) F\"\n  (at level 36, F at level 36, r at level 50,\n           format \"'[' \\prod_ ( <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( i <- r | P ) F\"\n  (at level 36, F at level 36, i, r at level 50,\n           format \"'[' \\prod_ ( i  <-  r  |  P ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( i <- r ) F\"\n  (at level 36, F at level 36, i, r at level 50,\n           format \"'[' \\prod_ ( i  <-  r ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( m <= i < n | P ) F\"\n  (at level 36, F at level 36, i, m, n at level 50,\n           format \"'[' \\prod_ ( m  <=  i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( m <= i < n ) F\"\n  (at level 36, F at level 36, i, m, n at level 50,\n           format \"'[' \\prod_ ( m  <=  i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( i | P ) F\"\n  (at level 36, F at level 36, i at level 50,\n           format \"'[' \\prod_ ( i  |  P ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( i : t | P ) F\"\n  (at level 36, F at level 36, i at level 50,\n           only parsing).\nReserved Notation \"\\prod_ ( i : t ) F\"\n  (at level 36, F at level 36, i at level 50,\n           only parsing).\nReserved Notation \"\\prod_ ( i < n | P ) F\"\n  (at level 36, F at level 36, i, n at level 50,\n           format \"'[' \\prod_ ( i  <  n  |  P ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( i < n ) F\"\n  (at level 36, F at level 36, i, n at level 50,\n           format \"'[' \\prod_ ( i  <  n ) '/  '  F ']'\").\nReserved Notation \"\\prod_ ( i \\in A | P ) F\"\n  (at level 36, F at level 36, i, A at level 50,\n           format \"'[' \\prod_ ( i  \\in  A  |  P )  F ']'\").\nReserved Notation \"\\prod_ ( i \\in A ) F\"\n  (at level 36, F at level 36, i, A at level 50,\n           format \"'[' \\prod_ ( i  \\in  A ) '/  '  F ']'\").\n\nDelimit Scope big_scope with BIG.\nOpen Scope big_scope.\n\nDefinition reducebig R I nil op r (P : pred I) (F : I -> R) : R :=\n  foldr (fun i x => if P i then op (F i) x else x) nil r.\n\nModule Type ReduceBigSig.\nParameter bigop : forall R I,\n   R -> (R -> R -> R) -> seq I -> pred I -> (I -> R) -> R.\nAxiom bigopE : bigop = reducebig.\nEnd ReduceBigSig.\n\nModule ReduceBig : ReduceBigSig.\nDefinition bigop := reducebig.\nLemma bigopE : bigop = reducebig. Proof. by []. Qed.\nEnd ReduceBig.\n\nNotation bigop := ReduceBig.bigop.\nCanonical Structure reduce_big_unlock := Unlockable ReduceBig.bigopE.\n\nDefinition index_iota m n := iota m (n - m).\n\nDefinition index_enum (T : finType) := enum T.\n\nLemma mem_index_iota : forall m n i, i \\in index_iota m n = (m <= i < n).\nProof.\nmove=> m n i; rewrite mem_iota; case le_m_i: (m <= i) => //=.\nby rewrite -leq_sub_add leq_subS // -ltn_0sub subn_sub subnK // ltn_0sub.\nQed.\n\nLemma filter_index_enum : forall T P, filter P (index_enum T) = enum P.\nProof. by move=> T P; rewrite /enum -enumE. Qed.\n\nNotation \"\\big [ op / nil ]_ ( <- r | P ) F\" :=\n  (bigop nil op r P F) : big_scope.\nNotation \"\\big [ op / nil ]_ ( i <- r | P ) F\" :=\n  (bigop nil op r (fun i => P%B) (fun i => F)) : big_scope.\nNotation \"\\big [ op / nil ]_ ( i <- r ) F\" :=\n  (bigop nil op r (fun _ => true) (fun  i => F)) : big_scope.\nNotation \"\\big [ op / nil ]_ ( m <= i < n | P ) F\" :=\n  (bigop nil op (index_iota m n) (fun i : nat => P%B) (fun i : nat => F))\n     : big_scope.\nNotation \"\\big [ op / nil ]_ ( m <= i < n ) F\" :=\n  (bigop nil op (index_iota m n) (fun _ => true) (fun i : nat => F))\n     : big_scope.\nNotation \"\\big [ op / nil ]_ ( i | P ) F\" :=\n  (bigop nil op (index_enum _) (fun i => P%B) (fun i => F)) : big_scope.\nNotation \"\\big [ op / nil ]_ i F\" :=\n  (bigop nil op (index_enum _) (fun _ => true) (fun i => F)) : big_scope.\nNotation \"\\big [ op / nil ]_ ( i : t | P ) F\" :=\n  (bigop nil op (index_enum _) (fun i : t => P%B) (fun i : t => F))\n     (only parsing) : big_scope.\nNotation \"\\big [ op / nil ]_ ( i : t ) F\" :=\n  (bigop nil op (index_enum _) (fun _ => true) (fun i : t => F))\n     (only parsing) : big_scope.\nNotation \"\\big [ op / nil ]_ ( i < n | P ) F\" :=\n  (\\big[op/nil]_(i : ordinal n | P%B) F) : big_scope.\nNotation \"\\big [ op / nil ]_ ( i < n ) F\" :=\n  (\\big[op/nil]_(i : ordinal n) F) : big_scope.\nNotation \"\\big [ op / nil ]_ ( i \\in A | P ) F\" :=\n  (\\big[op/nil]_(i | (i \\in A) && P) F) : big_scope.\nNotation \"\\big [ op / nil ]_ ( i \\in A ) F\" :=\n  (\\big[op/nil]_(i | i \\in A) F) : big_scope.\n\nNotation Local \"'+%R'\" := (@Ring.add _) (at level 0).\nNotation Local \"'+%N'\" := addn (at level 0, only parsing).\n\nNotation \"\\sum_ ( <- r | P ) F\" :=\n  (\\big[+%R/0%R]_(<- r | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i <- r | P ) F\" :=\n  (\\big[+%R/0%R]_(i <- r | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i <- r ) F\" :=\n  (\\big[+%R/0%R]_(i <- r) F%R) : ring_scope.\nNotation \"\\sum_ ( m <= i < n | P ) F\" :=\n  (\\big[+%R/0%R]_(m <= i < n | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( m <= i < n ) F\" :=\n  (\\big[+%R/0%R]_(m <= i < n) F%R) : ring_scope.\nNotation \"\\sum_ ( i | P ) F\" :=\n  (\\big[+%R/0%R]_(i | P%B) F%R) : ring_scope.\nNotation \"\\sum_ i F\" :=\n  (\\big[+%R/0%R]_i F%R) : ring_scope.\nNotation \"\\sum_ ( i : t | P ) F\" :=\n  (\\big[+%R/0%R]_(i : t | P%B) F%R) (only parsing) : ring_scope.\nNotation \"\\sum_ ( i : t ) F\" :=\n  (\\big[+%R/0%R]_(i : t) F%R) (only parsing) : ring_scope.\nNotation \"\\sum_ ( i < n | P ) F\" :=\n  (\\big[+%R/0%R]_(i < n | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i < n ) F\" :=\n  (\\big[+%R/0%R]_(i < n) F%R) : ring_scope.\nNotation \"\\sum_ ( i \\in A | P ) F\" :=\n  (\\big[+%R/0%R]_(i \\in A | P%B) F%R) : ring_scope.\nNotation \"\\sum_ ( i \\in A ) F\" :=\n  (\\big[+%R/0%R]_(i \\in A) F%R) : ring_scope.\n\nNotation \"\\sum_ ( <- r | P ) F\" :=\n  (\\big[+%N/0%N]_(<- r | P%B) F%N) : nat_scope.\nNotation \"\\sum_ ( i <- r | P ) F\" :=\n  (\\big[+%N/0%N]_(i <- r | P%B) F%N) : nat_scope.\nNotation \"\\sum_ ( i <- r ) F\" :=\n  (\\big[+%N/0%N]_(i <- r) F%N) : nat_scope.\nNotation \"\\sum_ ( m <= i < n | P ) F\" :=\n  (\\big[+%N/0%N]_(m <= i < n | P%B) F%N) : nat_scope.\nNotation \"\\sum_ ( m <= i < n ) F\" :=\n  (\\big[+%N/0%N]_(m <= i < n) F%N) : nat_scope.\nNotation \"\\sum_ ( i | P ) F\" :=\n  (\\big[+%N/0%N]_(i | P%B) F%N) : nat_scope.\nNotation \"\\sum_ i F\" :=\n  (\\big[+%N/0%N]_i F%N) : nat_scope.\nNotation \"\\sum_ ( i : t | P ) F\" :=\n  (\\big[+%N/0%N]_(i : t | P%B) F%N) (only parsing) : nat_scope.\nNotation \"\\sum_ ( i : t ) F\" :=\n  (\\big[+%N/0%N]_(i : t) F%N) (only parsing) : nat_scope.\nNotation \"\\sum_ ( i < n | P ) F\" :=\n  (\\big[+%N/0%N]_(i < n | P%B) F%N) : nat_scope.\nNotation \"\\sum_ ( i < n ) F\" :=\n  (\\big[+%N/0%N]_(i < n) F%N) : nat_scope.\nNotation \"\\sum_ ( i \\in A | P ) F\" :=\n  (\\big[+%N/0%N]_(i \\in A | P%B) F%N) : nat_scope.\nNotation \"\\sum_ ( i \\in A ) F\" :=\n  (\\big[+%N/0%N]_(i \\in A) F%N) : nat_scope.\n\nNotation Local \"'*%R'\" := (@Ring.mul _) (at level 0).\nNotation Local \"'*%N'\" := muln (at level 0, only parsing).\n\nNotation \"\\prod_ ( <- r | P ) F\" :=\n  (\\big[*%R/1%R]_(<- r | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i <- r | P ) F\" :=\n  (\\big[*%R/1%R]_(i <- r | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i <- r ) F\" :=\n  (\\big[*%R/1%R]_(i <- r) F%R) : ring_scope.\nNotation \"\\prod_ ( m <= i < n | P ) F\" :=\n  (\\big[*%R/1%R]_(m <= i < n | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( m <= i < n ) F\" :=\n  (\\big[*%R/1%R]_(m <= i < n) F%R) : ring_scope.\nNotation \"\\prod_ ( i | P ) F\" :=\n  (\\big[*%R/1%R]_(i | P%B) F%R) : ring_scope.\nNotation \"\\prod_ i F\" :=\n  (\\big[*%R/1%R]_i F%R) : ring_scope.\nNotation \"\\prod_ ( i : t | P ) F\" :=\n  (\\big[*%R/1%R]_(i : t | P%B) F%R) (only parsing) : ring_scope.\nNotation \"\\prod_ ( i : t ) F\" :=\n  (\\big[*%R/1%R]_(i : t) F%R) (only parsing) : ring_scope.\nNotation \"\\prod_ ( i < n | P ) F\" :=\n  (\\big[*%R/1%R]_(i < n | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i < n ) F\" :=\n  (\\big[*%R/1%R]_(i < n) F%R) : ring_scope.\nNotation \"\\prod_ ( i \\in A | P ) F\" :=\n  (\\big[*%R/1%R]_(i \\in A | P%B) F%R) : ring_scope.\nNotation \"\\prod_ ( i \\in A ) F\" :=\n  (\\big[*%R/1%R]_(i \\in A) F%R) : ring_scope.\n\nNotation \"\\prod_ ( <- r | P ) F\" :=\n  (\\big[*%N/1%N]_(<- r | P%B) F%N) : nat_scope.\nNotation \"\\prod_ ( i <- r | P ) F\" :=\n  (\\big[*%N/1%N]_(i <- r | P%B) F%N) : nat_scope.\nNotation \"\\prod_ ( i <- r ) F\" :=\n  (\\big[*%N/1%N]_(i <- r) F%N) : nat_scope.\nNotation \"\\prod_ ( m <= i < n | P ) F\" :=\n  (\\big[*%N/1%N]_(m <= i < n | P%B) F%N) : nat_scope.\nNotation \"\\prod_ ( m <= i < n ) F\" :=\n  (\\big[*%N/1%N]_(m <= i < n) F%N) : nat_scope.\nNotation \"\\prod_ ( i | P ) F\" :=\n  (\\big[*%N/1%N]_(i | P%B) F%N) : nat_scope.\nNotation \"\\prod_ i F\" :=\n  (\\big[*%N/1%N]_i F%N) : nat_scope.\nNotation \"\\prod_ ( i : t | P ) F\" :=\n  (\\big[*%N/1%N]_(i : t | P%B) F%N) (only parsing) : nat_scope.\nNotation \"\\prod_ ( i : t ) F\" :=\n  (\\big[*%N/1%N]_(i : t) F%N) (only parsing) : nat_scope.\nNotation \"\\prod_ ( i < n | P ) F\" :=\n  (\\big[*%N/1%N]_(i < n | P%B) F%N) : nat_scope.\nNotation \"\\prod_ ( i < n ) F\" :=\n  (\\big[*%N/1%N]_(i < n) F%N) : nat_scope.\nNotation \"\\prod_ ( i \\in A | P ) F\" :=\n  (\\big[*%N/1%N]_(i \\in A | P%B) F%N) : nat_scope.\nNotation \"\\prod_ ( i \\in A ) F\" :=\n  (\\big[*%N/1%N]_(i \\in A) F%N) : nat_scope.\n\nSection Extensionality.\n\nVariables (R : Type)  (nil : R) (op : R -> R -> R).\n\nSection SeqExtension.\n\nVariable I : Type.\n\nLemma big_filter : forall r (P : pred I) F,\n  \\big[op/nil]_(i <- filter P r) F i = \\big[op/nil]_(i <- r | P i) F i.\nProof. by rewrite unlock => r P F; elim: r => //= i r <-; case (P i). Qed.\n\nLemma big_filter_cond : forall r (P1 P2 : pred I) F,\n  \\big[op/nil]_(i <- filter P1 r | P2 i) F i\n     = \\big[op/nil]_(i <- r | P1 i && P2 i) F i.\nProof.\nmove=> r P1 P2 F; rewrite -big_filter -(big_filter r); congr bigop.\nrewrite -filter_predI; apply: eq_filter => i; exact: andbC.\nQed.\n\nLemma eq_bigl : forall r (P1 P2 : pred I) F, P1 =1 P2 ->\n  \\big[op/nil]_(i <- r | P1 i) F i = \\big[op/nil]_(i <- r | P2 i) F i.\nProof.\nby move=> r P1 P2 F eqP12; rewrite -big_filter (eq_filter eqP12) big_filter.\nQed.\n\nLemma eq_bigr : forall r (P : pred I) F1 F2, (forall i, P i -> F1 i = F2 i) ->\n  \\big[op/nil]_(i <- r | P i) F1 i = \\big[op/nil]_(i <- r | P i) F2 i.\nProof.\nmove=> r P F1 F2 eqF12; rewrite unlock.\nby elim: r => //= x r ->; case Px: (P x); rewrite // eqF12.\nQed.\n\nLemma eq_big : forall r (P1 P2 : pred I) F1 F2,\n  P1 =1 P2 -> (forall i, P1 i -> F1 i = F2 i) ->\n  \\big[op/nil]_(i <- r | P1 i) F1 i = \\big[op/nil]_(i <- r | P2 i) F2 i.\nProof. by move=> r P1 P2 F1 F2; move/eq_bigl <-; move/eq_bigr->. Qed.\n\nLemma congr_big : forall r1 r2 (P1 P2 : pred I) F1 F2,\n  r1 = r2 -> P1 =1 P2 -> (forall i, P1 i -> F1 i = F2 i) ->\n    \\big[op/nil]_(i <- r1 | P1 i) F1 i = \\big[op/nil]_(i <- r2 | P2 i) F2 i.\nProof. move=> r1 r2 P1 P2 F1 F2 <-{r2}; exact: eq_big. Qed.\n\nLemma big_seq0 : forall (P : pred I) F,\n  \\big[op/nil]_(i <- [::] | P i) F i = nil.\nProof. by rewrite unlock. Qed.\n\nLemma big_adds : forall i r (P : pred I) F,\n  let x := \\big[op/nil]_(j <- r | P j) F j in\n  \\big[op/nil]_(j <- i :: r | P j) F j = if P i then op (F i) x else x.\nProof. by rewrite unlock. Qed.\n\nLemma big_maps : forall (J : eqType) (h : J -> I) r F (P : pred I),\n  \\big[op/nil]_(i <- maps h r | P i) F i\n     = \\big[op/nil]_(j <- r | P (h j)) F (h j).\nProof. by rewrite unlock => J h r P F; elim: r => //= j r ->. Qed.\n\nLemma big_sub : forall x0 r (P : pred I) F,\n  \\big[op/nil]_(i <- r | P i) F i\n     = \\big[op/nil]_(0 <= i < size r | P (sub x0 r i)) (F (sub x0 r i)).\nProof.\nby move=> x0 r P F; rewrite -{1}(mkseq_sub x0 r) big_maps /index_iota subn0.\nQed.\n\nLemma big_hasC : forall r (P : pred I) F,\n  ~~ has P r -> \\big[op/nil]_(i <- r | P i) F i = nil.\nProof.\nmove=> r P F; rewrite -big_filter has_count count_filter.\ncase: filter => // _; exact: big_seq0.\nQed.\n\nLemma big_pred0_eq : forall (r : seq I) F,\n  \\big[op/nil]_(i <- r | false) F i = nil.\nProof. by move=> r F; rewrite big_hasC // has_pred0. Qed.\n\nLemma big_pred0 : forall r (P : pred I) F, P =1 xpred0 ->\n  \\big[op/nil]_(i <- r | P i) F i = nil.\nProof. move=> r P F; move/eq_bigl->; exact: big_pred0_eq. Qed.\n\nLemma big_cat_nested : forall r1 r2 (P : pred I) F,\n  let x := \\big[op/nil]_(i <- r2 | P i) F i in\n  \\big[op/nil]_(i <- r1 ++ r2 | P i) F i = \\big[op/x]_(i <- r1 | P i) F i.\nProof. by move=> r1 r2 P F; rewrite unlock /reducebig foldr_cat. Qed.\n\nLemma big_catl : forall r1 r2 (P : pred I) F, ~~ has P r2 ->\n  \\big[op/nil]_(i <- r1 ++ r2 | P i) F i = \\big[op/nil]_(i <- r1 | P i) F i.\nProof. by move=> r1 r2 P F; rewrite big_cat_nested; move/big_hasC->. Qed.\n\nLemma big_catr : forall r1 r2 (P : pred I) F, ~~ has P r1 ->\n  \\big[op/nil]_(i <- r1 ++ r2 | P i) F i = \\big[op/nil]_(i <- r2 | P i) F i.\nProof.\nmove=> r1 r2 P F; rewrite -big_filter -(big_filter r2) filter_cat.\nby rewrite has_count count_filter; case: filter.\nQed.\n\nLemma big_const_seq : forall r (P : pred I) x,\n  \\big[op/nil]_(i <- r | P i) x = iter (count P r) (op x) nil.\nProof. by rewrite unlock => r P x; elim: r => //= i r ->; case: (P i). Qed.\n\nEnd SeqExtension.\n\n(* The following lemma can be used to localise extensionality to     *)\n(* the specific index sequence. This is done by ssreflect rewriting, *)\n(* before applying congruence or induction lemmas. This is important *)\n(* for the latter, because ssreflect 1.1 still relies on primitive   *)\n(* Coq matching unification for second-order application (e.g., for  *)\n(* elim), and the latter can't handle the eqType constraint on I, as *)\n(* it doesn't recognize canonical projections.                       *)\nLemma big_cond_seq : forall (I : eqType) r (P : pred I) F,\n  \\big[op/nil]_(i <- r | P i) F i\n    = \\big[op/nil]_(i <- r | P i && (i \\in r)) F i.\nProof.\nmove=> I r P F; rewrite -!(big_filter r); congr bigop.\nby apply: eq_in_filter => i ->; rewrite andbT.\nQed.\n\nLemma congr_big_nat : forall m1 n1 m2 n2 P1 P2 F1 F2,\n    m1 = m2 -> n1 = n2 ->\n    (forall i, m1 <= i < n2 -> P1 i = P2 i) ->\n    (forall i, P1 i && (m1 <= i < n2) -> F1 i = F2 i) ->\n  \\big[op/nil]_(m1 <= i < n1 | P1 i) F1 i\n    = \\big[op/nil]_(m2 <= i < n2 | P2 i) F2 i.\nProof.\nmove=> m n _ _ P1 P2 F1 F2 <- <- eqP12 eqF12.\nrewrite big_cond_seq (big_cond_seq _ P2).\napply: eq_big => i; rewrite ?inE /= !mem_index_iota; last exact: eqF12.\ncase inmn_i: (m <= i < n); rewrite ?(andbT, andbF) //; exact: eqP12.\nQed.\n\nLemma big_geq : forall m n (P : pred nat) F, m >= n ->\n  \\big[op/nil]_(m <= i < n | P i) F i = nil.\nProof.\nby move=> m n P F ge_m_n; rewrite /index_iota (eqnP ge_m_n) big_seq0.\nQed.\n\nLemma big_ltn_cond : forall m n (P : pred nat) F, m < n ->\n  let x := \\big[op/nil]_(m.+1 <= i < n | P i) F i in\n  \\big[op/nil]_(m <= i < n | P i) F i = if P m then op (F m) x else x.\nProof.\nby move=> m [//|n] P F le_m_n; rewrite /index_iota leq_subS // big_adds.\nQed.\n\nLemma big_ltn : forall m n F, m < n ->\n  \\big[op/nil]_(m <= i < n) F i = op (F m) (\\big[op/nil]_(m.+1 <= i < n) F i).\nProof. move=> *; exact: big_ltn_cond. Qed.\n\nLemma big_addn : forall m n a (P : pred nat) F,\n  \\big[op/nil]_(m + a <= i < n | P i) F i =\n     \\big[op/nil]_(m <= i < n - a | P (i + a)) F (i + a).\nProof.\nmove=> m n a P F; rewrite /index_iota subn_sub addnC iota_addl big_maps.\nby apply: eq_big => ? *; rewrite addnC.\nQed.\n\nLemma big_add1 : forall m n (P : pred nat) F,\n  \\big[op/nil]_(m.+1 <= i < n | P i) F i =\n     \\big[op/nil]_(m <= i < n.-1 | P (i.+1)) F (i.+1).\nProof.\nmove=> m n P F; rewrite -addn1 big_addn subn1.\nby apply: eq_big => ? *; rewrite addn1.\nQed.\n\nLemma big_nat_recl : forall n F,\n  \\big[op/nil]_(0 <= i < n.+1) F i =\n     op (F 0) (\\big[op/nil]_(0 <= i < n) F i.+1).\nProof. by move=> n F; rewrite big_ltn // big_add1. Qed.\n\nLemma big_mkord : forall n (P : pred nat) F,\n  \\big[op/nil]_(0 <= i < n | P i) F i = \\big[op/nil]_(i < n | P i) F i.\nProof.\nmove=> n P F; rewrite /index_iota subn0 -(big_maps (@nat_of_ord n)).\nby congr bigop; rewrite val_enum_ord.\nQed.\n\nLemma big_nat_widen : forall m n1 n2 (P : pred nat) F, n1 <= n2 ->\n  \\big[op/nil]_(m <= i < n1 | P i) F i\n      = \\big[op/nil]_(m <= i < n2 | P i && (i < n1)) F i.\nProof.\nmove=> m n1 n2 P F len12; symmetry.\nrewrite -big_filter filter_predI big_filter.\ncongr bigop; rewrite /index_iota; set d1 := n1 - m; set d2 := n2 - m.\nrewrite -(@subnK d1 d2) /=; last by rewrite leq_sub2r ?leq_addr.\nhave: ~~ has (fun i => i < n1) (iota (m + d1) (d2 - d1)).\n  apply/hasPn=> i; rewrite mem_iota -leqNgt; case/andP=> le_mn1_i _.\n  by apply: leq_trans le_mn1_i; rewrite -leq_sub_add.\nrewrite iota_add filter_cat has_filter /=; case: filter => // _.\nrewrite cats0; apply/all_filterP; apply/allP=> i.\nrewrite mem_iota; case/andP=> le_m_i lt_i_md1.\napply: (leq_trans lt_i_md1); rewrite subnK // ltnW //.\nrewrite -ltn_0sub -(ltn_add2l m) addn0; exact: leq_trans lt_i_md1.\nQed.\n\nLemma big_ord_widen_cond : forall n1 n2 (P : pred nat) (F : nat -> R),\n     n1 <= n2 ->\n  \\big[op/nil]_(i < n1 | P i) F i\n      = \\big[op/nil]_(i < n2 | P i && (i < n1)) F i.\nProof.\nmove=> n1 n2 P F len12.\nby rewrite -big_mkord (big_nat_widen _ _ _ len12) big_mkord.\nQed.\n\nLemma big_ord_widen : forall n1 n2 (F : nat -> R),\n n1 <= n2 ->\n  \\big[op/nil]_(i < n1) F i = \\big[op/nil]_(i < n2 | i < n1) F i.\nProof. move=> *; exact: (big_ord_widen_cond (predT)). Qed.\n\nLemma big_ord_widen_leq : forall n1 n2 (P : pred 'I_(n1.+1)) F,\n n1 < n2 ->\n  \\big[op/nil]_(i < n1.+1 | P i) F i\n      = \\big[op/nil]_(i < n2 | P (inord i) && (i <= n1)) F (inord i).\nProof.\nmove=> n1 n2 P F len12; pose g G i := G (inord i : 'I_(n1.+1)).\nrewrite -(big_ord_widen_cond (g _ P) (g _ F) len12) {}/g.\nby apply: eq_big => i *; rewrite inord_val.\nQed.\n\nLemma big_ord_narrow_cond : forall n1 n2 (P : pred 'I_n2) F,\n  forall le_n1_n2 : n1 <= n2,\n  let w := widen_ord le_n1_n2 in\n  \\big[op/nil]_(i < n2 | P i && (i < n1)) F i\n    = \\big[op/nil]_(i < n1 | P (w i)) F (w i).\nProof.\nmove=> [|n1] n2 P F ltn12 /=.\n  by rewrite !big_pred0 // => [[//] | i]; rewrite andbF.\nrewrite (big_ord_widen_leq _ _ ltn12); apply: eq_big => i.\n  rewrite ltnS; case: leqP => [le_i_n1|_]; last by rewrite !andbF.\n  by congr (P _ && _); apply: val_inj; rewrite /= inordK.\nby case/andP=> _ le_i_n1; congr F; apply: val_inj; rewrite /= inordK.\nQed.\n\nLemma big_ord_narrow_cond_leq : forall n1 n2 (P : pred 'I_(n2.+1)) F,\n  forall le_n1_n2 : n1 <= n2,\n  let w := @widen_ord n1.+1 n2.+1 le_n1_n2 in\n  \\big[op/nil]_(i < n2.+1 | P i && (i <= n1)) F i\n  = \\big[op/nil]_(i < n1.+1 | P (w i)) F (w i).\nProof. move=> n1 n2; exact: big_ord_narrow_cond n1.+1 n2.+1. Qed.\n\nLemma big_ord_narrow : forall n1 n2 F,\n  forall le_n1_n2 : n1 <= n2,\n  let w := widen_ord le_n1_n2 in\n  \\big[op/nil]_(i < n2 | i < n1) F i = \\big[op/nil]_(i < n1) F (w i).\nProof. move=> *; exact: (big_ord_narrow_cond (predT)). Qed.\n\nLemma big_ord_narrow_leq : forall n1 n2 F,\n  forall le_n1_n2 : n1 <= n2,\n  let w := @widen_ord n1.+1 n2.+1 le_n1_n2 in\n  \\big[op/nil]_(i < n2.+1 | i <= n1) F i = \\big[op/nil]_(i < n1.+1) F (w i).\nProof. move=> *; exact: (big_ord_narrow_cond_leq (predT)). Qed.\n\nLemma big_ord_recl : forall n F,\n  \\big[op/nil]_(i < n.+1) F i =\n     op (F ord0) (\\big[op/nil]_(i < n) F (@lift n.+1 ord0 i)).\nProof.\nmove=> n F; pose G i := F (inord i).\nhave eqFG: forall i, F i = G i by move=> i; rewrite /G inord_val.\nrewrite (eq_bigr _ (fun i _ => eqFG i)) -(big_mkord _ (fun _ => _) G) eqFG.\nrewrite big_ltn // big_add1 /= big_mkord; congr op.\nby apply: eq_bigr => i _; rewrite eqFG.\nQed.\n\nLemma big_const : forall (I : finType) (A : pred I) x,\n  \\big[op/nil]_(i \\in A) x = iter #|A| (op x) nil.\nProof.\nby move=> *; rewrite big_const_seq count_filter cardE [index_enum _]enumE.\nQed.\n\nLemma big_const_nat : forall m n x,\n  \\big[op/nil]_(m <= i < n) x = iter (n - m) (op x) nil.\nProof. by move=> *; rewrite big_const_seq count_predT size_iota. Qed.\n\nLemma big_const_ord : forall n x,\n  \\big[op/nil]_(i < n) x = iter n (op x) nil.\nProof. by move=> *; rewrite big_const card_ord. Qed.\n\nEnd Extensionality.\n\nSection MonoidProperties.\n\nImport Monoid.\n\nVariable R : Type.\n\nVariable nil : R.\nNotation Local \"1\" := nil.\n\nSection Plain.\n\nVariable op : Monoid.law 1.\n\nNotation Local \"'*%M'\" := (operator op) (at level 0).\nNotation Local \"x * y\" := ( *%M x y).\n\nLemma eq_big_nil_seq : forall nil' I r (P : pred I) F,\n     right_unit nil' *%M -> has P r ->\n   \\big[*%M/nil']_(i <- r | P i) F i =\\big[*%M/1]_(i <- r | P i) F i.\nProof.\nmove=> nil' I r P F op_nil'.\nrewrite -!(big_filter _ _ r) has_count count_filter.\ncase/lastP: (filter P r) => {r p}// r i _.\nby rewrite -cats1 !(big_cat_nested, big_adds, big_seq0) op_nil' mulm1.\nQed.\n\nLemma eq_big_nil  : forall nil' (I : finType) i0 (P : pred I) F,\n     P i0 -> right_unit nil' *%M ->\n  \\big[*%M/nil']_(i | P i) F i =\\big[*%M/1]_(i | P i) F i.\nProof.\nmove=> nil' I i0 P F op_nil' Pi0; apply: eq_big_nil_seq => //.\nby apply/hasP; exists i0; first exact: mem_enum.\nQed.\n\nLemma big1_eq : forall I r (P : pred I), \\big[*%M/1]_(i <- r | P i) 1 = 1.\nProof.\nmove=> *; rewrite big_const_seq; elim: (count _ _) => //= n ->; exact: mul1m.\nQed.\n\nLemma big1 : forall (I : finType) (P : pred I) F,\n  (forall i, P i -> F i = 1) -> \\big[*%M/1]_(i | P i) F i = 1.\nProof. by move=> I P F eq_F_1; rewrite (eq_bigr _ _ _ eq_F_1) big1_eq. Qed.\n\nLemma big1_seq : forall (I : eqType) r (P : pred I) F,\n  (forall i, P i && (i \\in r) -> F i = 1)\n  -> \\big[*%M/1]_(i <- r | P i) F i = 1.\nProof.\nby move=> I r P F eqF1; rewrite big_cond_seq (eq_bigr _ _ _ eqF1) big1_eq.\nQed.\n\nLemma big_seq1 : forall I (i : I) F, \\big[*%M/1]_(j <- [:: i]) F j = F i.\nProof. by rewrite unlock => /= *; rewrite mulm1. Qed.\n\nLemma big_mkcond : forall I r (P : pred I) F,\n  \\big[*%M/1]_(i <- r | P i) F i =\n     \\big[*%M/1]_(i <- r) (if P i then F i else 1).\nProof.\nby rewrite unlock => I r P F; elim: r => //= i r ->; case P; rewrite ?mul1m.\nQed.\n\nLemma big_cat : forall I r1 r2 (P : pred I) F,\n  \\big[*%M/1]_(i <- r1 ++ r2 | P i) F i =\n     \\big[*%M/1]_(i <- r1 | P i) F i * \\big[*%M/1]_(i <- r2 | P i) F i.\nProof.\nmove=> I r1 r2 P F; rewrite !(big_mkcond _ P).\nelim: r1 => [|i r1 IHr1]; first by rewrite big_seq0 mul1m.\nby rewrite /= !big_adds IHr1 mulmA.\nQed.\n\nLemma big_pred1_eq : forall (I : finType) (i : I) F,\n  \\big[*%M/1]_(j | j == i) F j = F i.\nProof.\nby move=> I i F; rewrite -big_filter filter_index_enum enum1 big_seq1.\nQed.\n\nLemma big_pred1 : forall (I : finType) i (P : pred I) F,\n  P =1 pred1 i -> \\big[*%M/1]_(j | P j) F j = F i.\nProof. move=> I i P F; move/(eq_bigl _ _)->; exact: big_pred1_eq. Qed.\n\nLemma big_cat_nat : forall n m p (P : pred nat) F, m <= n -> n <= p ->\n  \\big[*%M/1]_(m <= i < p | P i) F i =\n   (\\big[*%M/1]_(m <= i < n | P i) F i) * (\\big[*%M/1]_(n <= i < p | P i) F i).\nProof.\nmove=> n m p F P le_mn le_np; rewrite -big_cat.\nby rewrite -{2}(subnK le_mn) -iota_add -subn_sub subnK // leq_sub2.\nQed.\n\nLemma big_nat1 : forall n F, \\big[*%M/1]_(n <= i < n.+1) F i = F n.\nProof. by move=> n F; rewrite big_ltn // big_geq // mulm1. Qed.\n\nLemma big_nat_recr : forall n F,\n  \\big[*%M/1]_(0 <= i < n.+1) F i = (\\big[*%M/1]_(0 <= i < n) F i) * F n.\nProof. by move=> n F; rewrite (@big_cat_nat n) ?leqnSn // big_nat1. Qed.\n\nLemma big_ord_recr : forall n F,\n  \\big[*%M/1]_(i < n.+1) F i =\n     (\\big[*%M/1]_(i < n) F (widen_ord (leqnSn n) i)) * F ord_max.\nProof.\nmove=> n F; transitivity (\\big[*%M/1]_(0 <= i < n.+1) F (inord i)).\n  by rewrite big_mkord; apply: eq_bigr=> i _; rewrite inord_val.\nrewrite big_nat_recr big_mkord; congr (_ * F _); last first.\n  by apply: val_inj; rewrite /= inordK.\nby apply: eq_bigr => [] i _; congr F; apply: ord_inj; rewrite inordK //= leqW.\nQed.\n\nEnd Plain.\n\nSection Abelian.\n\nVariable op : abelian_law 1.\n\nNotation Local \"'*%M'\" := (operator (law_of_abelian op)) (at level 0).\nNotation Local \"x * y\" := ( *%M x y).\n\nLemma eq_big_perm : forall (I : eqType) r1 r2 (P : pred I) F,\n    perm_eq r1 r2 ->\n  \\big[*%M/1]_(i <- r1 | P i) F i = \\big[*%M/1]_(i <- r2 | P i) F i.\nProof.\nmove=> I r1 r2 P F; move/perm_eqP; rewrite !(big_mkcond _ _ P).\nelim: r1 r2 => [|i r1 IHr1] r2 eq_r12.\n  by case: r2 eq_r12 => // i r2; move/(_ (pred1 i)); rewrite /= eqxx.\nhave r2i: i \\in r2 by rewrite -has_pred1 has_count -eq_r12 /= eqxx.\ncase/splitPr: r2 / r2i => [r3 r4] in eq_r12 *; rewrite big_cat /= !big_adds.\nrewrite mulmCA; congr (_ * _); rewrite -big_cat; apply: IHr1 => a.\nmove/(_ a): eq_r12; rewrite !count_cat /= addnCA; exact: addn_injl.\nQed.\n\nLemma big_uniq : forall (I : finType) (r : seq I) F,\n  uniq r -> \\big[*%M/1]_(i <- r) F i = \\big[*%M/1]_(i | i \\in r) F i.\nProof.\nmove=> I r F uniq_r; rewrite -(big_filter _ _ _ (mem r)); apply: eq_big_perm.\nby rewrite filter_index_enum uniq_perm_eq ?uniq_enum // => i; rewrite mem_enum.\nQed.\n\nLemma big_split : forall I r (P : pred I) F1 F2,\n  \\big[*%M/1]_(i <- r | P i) (F1 i * F2 i) =\n    \\big[*%M/1]_(i <- r | P i) F1 i * \\big[*%M/1]_(i <- r | P i) F2 i.\nProof.\nrewrite unlock => I r P F1 F2.\nelim: r => /= [|i r ->]; [by rewrite mulm1 | case: (P i) => //=].\nrewrite !mulmA; congr (_ * _); exact: mulmAC.\nQed.\n\nLemma bigID : forall I r (a P : pred I) F,\n  \\big[*%M/1]_(i <- r | P i) F i\n  = \\big[*%M/1]_(i <- r | P i && a i) F i *\n    \\big[*%M/1]_(i <- r | P i && ~~ a i) F i.\nProof.\nmove=> I r a P F; rewrite !(big_mkcond _ _ _ F) -big_split; apply: eq_bigr => i.\nby case: (a i); rewrite !simpm.\nQed.\nImplicit Arguments bigID [I r].\n\nLemma bigD1 : forall (I : finType) j (P : pred I) F,\n  P j -> \\big[*%M/1]_(i | P i) F i\n    = F j * \\big[*%M/1]_(i | P i && (i != j)) F i.\nProof.\nmove=> I j P F Pj; rewrite (bigID (pred1 j)); congr (_ * _).\nby apply: big_pred1 => i; rewrite /= andbC; case: eqP => // ->.\nQed.\nImplicit Arguments bigD1 [I P F].\n\nLemma cardD1x : forall (I : finType) (A : pred I) j,\n  A j -> #|SimplPred A| = 1 + #|[pred i | A i && (i != j)]|.\nProof.\nmove=> I A j Aj; rewrite (cardD1 j) [j \\in A]Aj; congr (_ + _).\nby apply: eq_card => i; rewrite inE /= andbC.\nQed.\nImplicit Arguments cardD1x [I A].\n\nLemma partition_big : forall (I J : finType) (P : pred I) p (Q : pred J) F,\n    (forall i, P i -> Q (p i)) ->\n      \\big[*%M/1]_(i | P i) F i =\n         \\big[*%M/1]_(j | Q j) \\big[*%M/1]_(i | P i && (p i == j)) F i.\nProof.\nmove=> I J P p Q F Qp; transitivity (\\big[*%M/1]_(i | P i && Q (p i)) F i).\n  by apply: eq_bigl => i; case Pi: (P i); rewrite // Qp.\nelim: {Q Qp}_.+1 {-2}Q (ltnSn #|Q|) => // n IHn Q.\ncase: (pickP Q) => [j Qj | Q0 _]; last first.\n  by rewrite !big_pred0 // => i; rewrite Q0 andbF.\nrewrite ltnS (cardD1x j Qj) (bigD1 j) //; move/IHn=> {n IHn} <-.\nrewrite (bigID (fun i => p i == j)); congr (_ * _); apply: eq_bigl => i.\n  by case: eqP => [-> | _]; rewrite !(Qj, simpm).\nby rewrite andbA.\nQed.\n\nImplicit Arguments partition_big [I J P F].\n\nLemma reindex_onto : forall (I J : finType) (h : J -> I) h' (P : pred I) F,\n   (forall i, P i -> h (h' i) = i) ->\n  \\big[*%M/1]_(i | P i) F i =\n    \\big[*%M/1]_(j | P (h j) && (h' (h j) == j)) F (h j).\nProof.\nmove=> I J h h' P F h'K.\nelim: {P}_.+1 {-3}P h'K (ltnSn #|P|) => //= n IHn P h'K.\ncase: (pickP P) => [i Pi | P0 _]; last first.\n  by rewrite !big_pred0 // => j; rewrite P0.\nrewrite ltnS (cardD1x i Pi); move/IHn {n IHn} => IH.\nrewrite (bigD1 i Pi) (bigD1 (h' i)) h'K ?Pi ?eq_refl //=; congr (_ * _).\nrewrite {}IH => [|j]; [apply: eq_bigl => j | by case/andP; auto].\nrewrite andbC -andbA (andbCA (P _)); case: eqP => //= hK; congr (_ && ~~ _).\nby apply/eqP/eqP=> [<-|->] //; rewrite h'K.\nQed.\nImplicit Arguments reindex_onto [I J P F].\n\nLemma reindex : forall (I J : finType) (h : J -> I) (P : pred I) F,\n  {on [pred i | P i], bijective h} ->\n  \\big[*%M/1]_(i | P i) F i = \\big[*%M/1]_(j | P (h j)) F (h j).\nProof.\nmove=> I J h P F [h' hK h'K]; rewrite (reindex_onto h h' h'K).\nby apply: eq_bigl => j; rewrite !inE; case Pi: (P _); rewrite //= hK ?eqxx.\nQed.\nImplicit Arguments reindex [I J P F].\n\nLemma pair_big_dep : forall (I J : finType) (P : pred I) (Q : I -> pred J) F,\n  \\big[*%M/1]_(i | P i) \\big[*%M/1]_(j | Q i j) F i j =\n    \\big[*%M/1]_(p | P p.1 && Q p.1 p.2) F p.1 p.2.\nProof.\nmove=> I J P Q F.\nrewrite (partition_big (fun p => p.1) P) => [|j]; last by case/andP.\napply: eq_bigr => i /= Pi; rewrite (reindex_onto (pair i) (fun p => p.2)).\n   by apply: eq_bigl => j; rewrite !eqxx [P i]Pi !andbT.\nby case=> i' j /=; case/andP=> _ /=; move/eqP->.\nQed.\n\nLemma pair_big : forall (I J : finType) (P : pred I) (Q : pred J) F,\n  \\big[*%M/1]_(i | P i) \\big[*%M/1]_(j | Q j) F i j =\n    \\big[*%M/1]_(p | P p.1 && Q p.2) F p.1 p.2.\nProof. move=> *; exact: pair_big_dep. Qed.\n\nLemma pair_bigA_ : forall (I J : finType) (F : I -> J -> R),\n  \\big[*%M/1]_i \\big[*%M/1]_j F i j = \\big[*%M/1]_p F p.1 p.2.\nProof. move=> *; exact: pair_big_dep. Qed.\n\nLemma exchange_big_dep :\n    forall (I J : finType) (P : pred I) (Q : I -> pred J) (xQ : pred J) F,\n    (forall i j, P i -> Q i j -> xQ j) ->\n  \\big[*%M/1]_(i | P i) \\big[*%M/1]_(j | Q i j) F i j =\n    \\big[*%M/1]_(j | xQ j) \\big[*%M/1]_(i | P i && Q i j) F i j.\nProof.\nmove=> I J P Q xQ F PQxQ; pose p u := (u.2, u.1).\nrewrite !pair_big_dep (reindex_onto (p J I) (p I J)) => [|[//]].\napply: eq_big => [] [j i] //=; symmetry; rewrite eq_refl andbC.\ncase: (@andP (P i)) => //= [[]]; exact: PQxQ.\nQed.\nImplicit Arguments exchange_big_dep [I J P Q F].\n\nLemma exchange_big :  forall (I J : finType) (P : pred I) (Q : pred J) F,\n  \\big[*%M/1]_(i | P i) \\big[*%M/1]_(j | Q j) F i j =\n    \\big[*%M/1]_(j | Q j) \\big[*%M/1]_(i | P i) F i j.\nProof.\nmove=> I J P Q F; rewrite (exchange_big_dep Q) //; apply: eq_bigr => i /= Qi.\nby apply: eq_bigl => j; rewrite [Q i]Qi andbT.\nQed.\n\nLemma exchange_big_dep_nat :\n  forall m1 n1 m2 n2 (P : pred nat) (Q : rel nat) (xQ : pred nat) F,\n    (forall i j, m1 <= i < n1 -> m2 <= j < n2 -> P i -> Q i j -> xQ j) ->\n  \\big[*%M/1]_(m1 <= i < n1 | P i) \\big[*%M/1]_(m2 <= j < n2 | Q i j) F i j =\n    \\big[*%M/1]_(m2 <= j < n2 | xQ j)\n       \\big[*%M/1]_(m1 <= i < n1 | P i && Q i j) F i j.\nProof.\nmove=> m1 n1 m2 n2 P Q xQ F PQxQ.\ntransitivity\n  (\\big[*%M/1]_(i < n1 - m1| P (i + m1))\n    \\big[*%M/1]_(j < n2 - m2 | Q (i + m1) (j + m2)) F (i + m1) (j + m2)).\n- rewrite -{1}[m1]add0n big_addn big_mkord; apply: eq_bigr => i _.\n  by rewrite -{1}[m2]add0n big_addn big_mkord.\nrewrite (exchange_big_dep (fun j: 'I__ => xQ (j + m2))) => [|i j]; last first.\n  by apply: PQxQ; rewrite leq_addl addnC -ltn_0sub -subn_sub ltn_0sub ltn_ord.\nsymmetry; rewrite -{1}[m2]add0n big_addn big_mkord; apply: eq_bigr => j _.\nby rewrite -{1}[m1]add0n big_addn big_mkord.\nQed.\nImplicit Arguments exchange_big_dep_nat [m1 n1 m2 n2 P Q F].\n\nLemma exchange_big_nat : forall m1 n1 m2 n2 (P Q : pred nat) F,\n  \\big[*%M/1]_(m1 <= i < n1 | P i) \\big[*%M/1]_(m2 <= j < n2 | Q j) F i j =\n    \\big[*%M/1]_(m2 <= j < n2 | Q j) \\big[*%M/1]_(m1 <= i < n1 | P i) F i j.\nProof.\nmove=> m1 n1 m2 n2 P Q F; rewrite (exchange_big_dep_nat Q) //.\nby apply: eq_bigr => i /= Qi; apply: eq_bigl => j; rewrite [Q i]Qi andbT.\nQed.\n\nEnd Abelian.\n\nEnd MonoidProperties.\n\nImplicit Arguments big_filter [R op nil I].\nImplicit Arguments big_filter_cond [R op nil I].\nImplicit Arguments congr_big [R op nil I r1 P1 F1].\nImplicit Arguments eq_big [R op nil I r P1  F1].\nImplicit Arguments eq_bigl [R op nil  I r P1].\nImplicit Arguments eq_bigr [R op nil I r  P F1].\nImplicit Arguments eq_big_nil [R op nil nil' I P F].\nImplicit Arguments big_cond_seq [R op nil I r].\nImplicit Arguments congr_big_nat [R op nil m1 n1 P1 F1].\nImplicit Arguments big_maps [R op nil I J r].\nImplicit Arguments big_sub [R op nil I r].\nImplicit Arguments big_catl [R op nil I r1 r2 P F].\nImplicit Arguments big_catr [R op nil I r1 r2  P F].\nImplicit Arguments big_geq [R op nil m n P F].\nImplicit Arguments big_ltn_cond [R op nil m n P F].\nImplicit Arguments big_ltn [R op nil m n F].\nImplicit Arguments big_addn [R op nil]. (* m n a *)\nImplicit Arguments big_mkord [R op nil n].\nImplicit Arguments big_nat_widen [R op nil] (* m n a *).\nImplicit Arguments big_ord_widen_cond [R op nil n1].\nImplicit Arguments big_ord_widen [R op nil n1].\nImplicit Arguments big_ord_widen_leq [R op nil n1].\nImplicit Arguments big_ord_narrow_cond [R op nil n1 n2 P F].\nImplicit Arguments big_ord_narrow_cond_leq [R op nil n1 n2 P F].\nImplicit Arguments big_ord_narrow [R op nil n1 n2 F].\nImplicit Arguments big_ord_narrow_leq [R op nil n1 n2 F].\nImplicit Arguments big_mkcond [R op nil I r].\nImplicit Arguments big1_eq [R op nil I].\nImplicit Arguments big1_seq [R op nil I].\nImplicit Arguments big1 [R op nil I].\nImplicit Arguments big_pred1 [R op nil I P F].\nImplicit Arguments eq_big_perm [R op nil I r1 P F].\nImplicit Arguments big_uniq [R op nil I F].\nImplicit Arguments bigID [R op nil I r].\nImplicit Arguments bigD1 [R op nil I P F].\nImplicit Arguments partition_big [R op nil I J P F].\nImplicit Arguments reindex_onto [R op nil I J P F].\nImplicit Arguments reindex [R op nil I J P F].\nImplicit Arguments pair_big_dep [R op nil I J].\nImplicit Arguments pair_big [R op nil I J].\nImplicit Arguments exchange_big_dep [R op nil I J P Q F].\nImplicit Arguments exchange_big_dep_nat [R op nil m1 n1 m2 n2 P Q F].\nImplicit Arguments big_ord_recl [R op nil].\nImplicit Arguments big_ord_recr [R op nil].\nImplicit Arguments big_nat_recl [R op nil].\nImplicit Arguments big_nat_recr [R op nil].\n\nSection BigProp.\n\nVariables (R : Type) (Pb : R -> Type).\nVariables (nil : R) (op1 op2 : R -> R -> R).\nHypothesis (Pb_nil : Pb nil)\n           (Pb_op1 : forall x y, Pb x -> Pb y -> Pb (op1 x y))\n           (Pb_eq_op : forall x y, Pb x -> Pb y -> op1 x y = op2 x y).\n\nLemma big_prop : forall I r (P : pred I) F,\n  (forall i, P i -> Pb (F i)) -> Pb (\\big[op1/nil]_(i <- r | P i) F i).\nProof.\nby rewrite unlock => I r P F PbF; elim: r => //= i *; case Pi: (P i); auto.\nQed.\n\n(* Pb must be given explicitly for the lemma below, because Coq second-order *)\n(* unification will not handle the eqType constraint on I.                   *)\nLemma big_prop_seq : forall (I : eqType) (r : seq I) (P : pred I) F,\n  (forall i, P i && (i \\in r) -> Pb (F i)) ->\n   Pb (\\big[op1/nil]_(i <- r | P i) F i).\nProof. move=> I r P F; rewrite big_cond_seq; exact: big_prop. Qed.\n\n(* Change operation *)\nLemma eq_big_op :  forall I r (P : pred I) F,\n   (forall i, P i -> Pb (F i)) ->\n  \\big[op1/nil]_(i <- r | P i) F i = \\big[op2/nil]_(i <- r | P i) F i.\nProof.\nhave:= big_prop; rewrite unlock => Pb_big I r P F Pb_F.\nby elim: r => //= i r <-; case Pi: (P i); auto.\nQed.\n\n(* See big_prop_seq above *)\nLemma eq_big_op_seq :  forall (I : eqType) r (P : pred I) F,\n    (forall i, P i && (i \\in r) -> Pb (F i)) ->\n  \\big[op1/nil]_(i <- r | P i) F i = \\big[op2/nil]_(i <- r | P i) F i.\nProof. move=> I r P F Pb_F; rewrite !(big_cond_seq P); exact: eq_big_op. Qed.\n\nEnd BigProp.\n\n(* The implicit arguments expect an explicit Pb *)\nImplicit Arguments eq_big_op_seq [R nil op1 I r P F].\nImplicit Arguments eq_big_op [R nil op1 I P F].\n\nSection BigRel.\n\nVariables (R1 R2 : Type) (Pr : R1 -> R2 -> Type).\nVariables (nil1 : R1) (op1 : R1 -> R1 -> R1).\nVariables (nil2 : R2) (op2 : R2 -> R2 -> R2).\nHypothesis Pr_nil : Pr nil1 nil2.\nHypothesis Pr_rel : forall x1 x2 y1 y2,\n  Pr x1 x2 -> Pr y1 y2 -> Pr (op1 x1 y1) (op2 x2 y2).\n\n(* Pr must be given explicitly *)\nLemma big_rel : forall I r (P : pred I) F1 F2,\n  (forall i, (P i) -> Pr (F1 i) (F2 i)) ->\n  Pr (\\big[op1/nil1]_(i <- r | P i) F1 i) (\\big[op2/nil2]_(i <- r | P i) F2 i).\nProof.\nrewrite !unlock => I r P F1 F2 PrF.\nelim: r => //= i *; case Pi: (P i); auto.\nQed.\n\nLemma big_rel_seq : forall (I : eqType) (r : seq I) (P : pred I) F1 F2,\n    (forall i, P i && (i \\in r) -> Pr (F1 i) (F2 i)) ->\n  Pr (\\big[op1/nil1]_(i <- r | P i) F1 i) (\\big[op2/nil2]_(i <- r | P i) F2 i).\nProof. move=> I r P *; rewrite !(big_cond_seq P); exact: big_rel. Qed.\n\nEnd BigRel.\n\nImplicit Arguments big_rel_seq [R1 R2 nil1 op1 nil2 op2 I r P F1 F2].\nImplicit Arguments big_rel [R1 R2 nil1 op1 nil2 op2 I P F1 F2].\n\nSection Morphism.\n\nVariables R1 R2 : Type.\nVariables (nil1 : R1) (nil2 : R2).\nVariables (op1 : R1 -> R1 -> R1) (op2 : R2 -> R2 -> R2).\nVariable phi : R1 -> R2.\nHypothesis phi_morphism : Monoid.morphism nil1 nil2 op1 op2 phi.\n\nLemma big_morph : forall I r (P : pred I) F,\n  phi (\\big[op1/nil1]_(i <- r | P i) F i) =\n     \\big[op2/nil2]_(i <- r | P i) phi (F i).\nProof.\ncase: phi_morphism => [phi1 phiM] I r P F.\nby rewrite !unlock; elim: r => //= i r <-; case: (P i).\nQed.\n\nEnd Morphism.\n\nImplicit Arguments big_morph [R1 R2 nil1 nil2 op1 op2].\n\nSection Distributivity.\n\nImport Monoid.\n\nVariable R : Type.\nVariables zero one : R.\nNotation Local \"0\" := zero.\nNotation Local \"1\" := one.\nVariable times : mul_law 0.\nNotation Local \"'*%M'\" := (mul_operator times) (at level 0).\nNotation Local \"x * y\" := ( *%M x y).\nVariable plus : add_law times.\nNotation Local \"'+%M'\" :=\n  (operator (law_of_abelian (law_of_additive plus))) (at level 0).\nNotation Local \"x + y\" := ( +%M x y).\n\nLemma big_distrl : forall I r alpha (P : pred I) F,\n  \\big[+%M/0]_(i <- r | P i) F i * alpha\n    = \\big[+%M/0]_(i <- r | P i) (F i * alpha).\nProof.\nmove=> *; apply: (big_morph ( *%M^~ _)).\nby split=> [|? * /=]; rewrite (mul0m,  mulm_addl).\nQed.\n\nLemma big_distrr : forall I r alpha (P : pred I) F,\n  alpha * \\big[+%M/0]_(i <- r | P i) F i\n    = \\big[+%M/0]_(i <- r | P i) (alpha * F i).\nProof.\nmove=> *; apply: (big_morph ( *%M _)).\nby split=> [|? * /=]; rewrite (mulm0,  mulm_addr).\nQed.\n\nLemma big_distr_big_dep :\n  forall (I J : finType) j0 (P : pred I) (Q : I -> pred J) F,\n  \\big[*%M/1]_(i | P i) \\big[+%M/0]_(j | Q i j) F i j =\n     \\big[+%M/0]_(f | pfamily j0 P Q f) \\big[*%M/1]_(i | P i) F i (f i).\nProof.\nmove=> I J j0 P Q F; rewrite -big_filter filter_index_enum; set r := enum P.\npose fIJ := {ffun I -> J}; pose Pf := pfamily j0 _ Q; symmetry.\ntransitivity (\\big[+%M/0]_(f | Pf (mem r) f) \\big[*%M/1]_(i <- r) F i (f i)).\n  apply: eq_big=> f; last by rewrite -big_filter filter_index_enum.\n  by apply: eq_forallb => i; rewrite /= mem_enum.\nhave: uniq r by exact: uniq_enum.\nelim: {P}r => /= [_|i r IHr].\n  rewrite (big_pred1 [ffun => j0]) ?big_seq0 //= => f.\n  apply/familyP/eqP=> /= [Df |->{f} i]; last by rewrite ffunE.\n  apply/ffunP=> i; rewrite ffunE; exact/eqP.\ncase/andP=> nri; rewrite big_adds big_distrl; move/IHr {IHr} <-.\nrewrite (partition_big (fun f : fIJ => f i) (Q i)); last first.\n  by move=> f; move/familyP; move/(_ i); rewrite /= inE /= eqxx.\npose seti j (f : fIJ) := [ffun k => if k == i then j else f k].\napply: eq_bigr => j Qij; rewrite (reindex_onto (seti j) (seti j0)); last first.\n  move=> f /=; case/andP; move/familyP=> eq_f; move/eqP=> fi.\n  by apply/ffunP => k; rewrite !ffunE; case: eqP => // ->.\nrewrite big_distrr; apply: eq_big => [f | f eq_f]; last first.\n  rewrite big_adds ffunE eq_refl !(big_cond_seq predT) /=; congr (_ * _).\n  by apply: eq_bigr => k; rewrite ffunE; case: eqP => // ->; case/idPn.\nrewrite !ffunE !eq_refl andbT; apply/andP/familyP=> [[Pjf fij0] k | Pff].\n  have:= familyP _ _ Pjf k; rewrite /= ffunE in_adds; case: eqP => // -> _.\n  by rewrite (negbET nri) -(eqP fij0) !ffunE ?inE /= !eqxx.\nsplit.\n  apply/familyP=> k; move/(_ k): Pff; rewrite /= ffunE in_adds.\n  by case: eqP => // ->.\napply/eqP; apply/ffunP=> k; have:= Pff k; rewrite !ffunE /=.\nby case: eqP => // ->; rewrite (negbET nri) /=; move/eqP.\nQed.\n\nLemma big_distr_big :\n  forall (I J : finType) j0 (P : pred I) (Q : pred J) F,\n  \\big[*%M/1]_(i | P i) \\big[+%M/0]_(j | Q j) F i j =\n     \\big[+%M/0]_(f | pffun_on j0 P Q f) \\big[*%M/1]_(i | P i) F i (f i).\nProof.\nmove=> I J j0 P Q F; rewrite (big_distr_big_dep j0); apply: eq_bigl => f.\nby apply/familyP/familyP=> Pf i; move/(_ i): Pf; case: (P i).\nQed.\n\nLemma bigA_distr_big_dep :\n  forall (I J : finType) (Q : I -> pred J) F,\n  \\big[*%M/1]_i \\big[+%M/0]_(j | Q i j) F i j\n    = \\big[+%M/0]_(f | family Q f) \\big[*%M/1]_i F i (f i).\nProof.\nmove=> I J Q F; case: (pickP J) => [j0 _ | J0].\n   exact: (big_distr_big_dep j0).\nrewrite /index_enum; case: (enum I) (mem_enum I) => [I0 | i r _].\n  have f0: I -> J by move=> i; have:= I0 i.\n  rewrite (big_pred1 (finfun f0)) ?big_seq0 // => g.\n  by apply/familyP/eqP=> _; first apply/ffunP; move=> i; have:= I0 i.\nhave Q0: Q _ =1 pred0 by move=> ? j; have:= J0 j.\nrewrite big_adds /= big_pred0 // mul0m big_pred0 // => f.\nby apply/familyP; move/(_ i); rewrite Q0.\nQed.\n\nLemma bigA_distr_big :\n  forall (I J : finType) (Q : pred J) (F : I -> J -> R),\n  \\big[*%M/1]_i \\big[+%M/0]_(j | Q j) F i j\n    = \\big[+%M/0]_(f | ffun_on Q f) \\big[*%M/1]_i F i (f i).\nProof. move=> *; exact: bigA_distr_big_dep. Qed.\n\nLemma bigA_distr_bigA :\n  forall (I J : finType) F,\n  \\big[*%M/1]_(i : I) \\big[+%M/0]_(j : J) F i j\n    = \\big[+%M/0]_(f : {ffun I -> J}) \\big[*%M/1]_i F i (f i).\nProof.\nmove=> *; rewrite bigA_distr_big; apply: eq_bigl => ?; exact/familyP.\nQed.\n\nEnd Distributivity.\n\nImplicit Arguments big_distrl [R zero times plus I r].\nImplicit Arguments big_distrr [R zero times plus I r].\nImplicit Arguments big_distr_big_dep [R zero one times plus I J].\nImplicit Arguments big_distr_big [R zero one times plus I J].\nImplicit Arguments bigA_distr_big_dep [R zero one times plus I J].\nImplicit Arguments bigA_distr_big [R zero one times plus I J].\nImplicit Arguments bigA_distr_bigA [R zero one times plus I J].\n\nSection Ring.\n\nImport ssralg.Ring.\n\nSection Opp.\n\nVariable R : additive_group.\n\nLemma sum_opp : forall I r P (F : I -> R),\n  \\sum_(i <- r | P i) - F i = - (\\sum_(i <- r | P i) F i).\nProof.\nmove=> *; symmetry; apply: big_morph.\nby split=> [|x y]; rewrite (oppr0, oppr_add).\nQed.\n\nLemma sum_split_sub : forall I r (P : pred I) (F1 F2 : I -> R),\n  \\sum_(i <- r | P i) (F1 i - F2 i)\n     = \\sum_(i <- r | P i) F1 i - \\sum_(i <- r | P i) F2 i.\nProof. by move=> *; rewrite -sum_opp -big_split /=. Qed.\n\nLemma sumr_const : forall (I : finType) (A : pred I) (x : R),\n  \\sum_(i \\in A) x = x *+ #|A|.\nProof. exact: big_const. Qed.\n\nEnd Opp.\n\nLemma prodr_const : forall (R : basic) (I : finType) (A : pred I) (x : R),\n  \\prod_(i \\in A) x = x ^+ #|A|.\nProof. move=> *; exact: big_const. Qed.\n\nEnd Ring.\n\n(* Redundant, unparseable notation to print constant sums and products. *)\nNotation \"\\su 'm_' ( i | P ) e\" :=\n  (\\sum_(<- index_enum _ | (fun i => P)) (fun _ => e%N))\n  (at level 41, e at level 41, format \"\\su 'm_' ( i  |  P )  e\") : nat_scope.\n\nNotation \"\\su 'm_' ( i \\in A ) e\" :=\n  (\\sum_(<- index_enum _ | (fun i => i \\in A)) (fun _ => e%N))\n  (at level 41, e at level 41, format \"\\su 'm_' ( i  \\in  A )  e\") : nat_scope.\n\nNotation \"\\su 'm_' ( i \\in A | P ) e\" :=\n  (\\sum_(<- index_enum _ | (fun i => (i \\in A) && P)) (fun _ => e%N))\n  (at level 41, e at level 41, format \"\\su 'm_' ( i  \\in  A  |  P )  e\")\n    : nat_scope.\n\nNotation \"\\pro 'd_' ( i | P ) e\" :=\n  (\\prod_(<- index_enum _ | (fun i => P)) (fun _ => e%N))\n  (at level 36, e at level 36, format \"\\pro 'd_' ( i  |  P )  e\") : nat_scope.\n\nLemma sum_nat_const : forall (I : finType) (A : pred I) (n : nat),\n  \\sum_(i \\in A) n = #|A| * n.\nProof. by move=> I A n; rewrite big_const; elim: #|A| => //= i ->. Qed.\n\nLemma sum1_card : forall (I : finType) (A : pred I), \\sum_(i \\in A) 1 = #|A|.\nProof. by move=> I A; rewrite sum_nat_const muln1. Qed.\n\nLemma prod_nat_const : forall (I : finType) (A : pred I) (n : nat),\n  \\prod_(i \\in A) n = n ^ #|A|.\nProof. by move=> I A n; rewrite big_const; elim: #|_| => //= ? ->. Qed.\n\nLemma sum_nat_const_nat : forall n1 n2 n : nat,\n  \\sum_(n1 <= i < n2) n = (n2 - n1) * n.\nProof. by move=> *; rewrite big_const_nat; elim: (_ - _) => //= ? ->. Qed.\n\nLemma prod_nat_const_nat : forall n1 n2 n : nat,\n  \\prod_(n1 <= i < n2) n = n ^ (n2 - n1).\nProof. by move=> *; rewrite big_const_nat; elim: (_ - _) => //= ? ->. Qed.\n\n(* Beware: applying sum_predU to a [disjoint A & B] hypothesis will strip *)\n(* the mem wrappers from A and B, possibly exposing internal coercions.   *)\nLemma sum_predU : forall (I : finType) (N : I -> nat) (a b : pred I),\n  [disjoint a & b] ->\n  \\sum_(i | a i || b i) N i = (\\sum_(i | a i) N i) + (\\sum_(i | b i) N i).\nProof.\nmove => d N a b Hdisj; rewrite (bigID a) //=; congr addn; apply: eq_bigl => x0.\n  by rewrite andb_orl andbb andbC [_ && _](pred0P Hdisj) orbF.\nrewrite andbC; move/pred0P: Hdisj; move/(_ x0)=> /=.\nby rewrite -topredE /=; case: a.\nQed.\n\nLemma ltn_0prodn_cond : forall I r (P : pred I) F,\n  (forall i, P i -> 0 < F i) -> 0 < \\prod_(i <- r | P i) F i.\nProof.\nby move=> I r P F Fpos; apply big_prop => // n1 n2; rewrite ltn_0mul => ->.\nQed.\n\nLemma ltn_0prodn : forall I r (P : pred I) F,\n  (forall i, 0 < F i) -> 0 < \\prod_(i <- r | P i) F i.\nProof. move=> I r P F Fpos; exact: ltn_0prodn_cond. Qed.\n\nNotation \"\\max_ ( <- r | P ) F\" :=\n  (\\big[maxn/0%N]_(<- r | P%B) F%N) : nat_scope.\nNotation \"\\max_ ( i <- r | P ) F\" :=\n  (\\big[maxn/0%N]_(i <- r | P%B) F%N) : nat_scope.\nNotation \"\\max_ ( i <- r ) F\" :=\n  (\\big[maxn/0%N]_(i <- r) F%N) : nat_scope.\nNotation \"\\max_ ( i | P ) F\" :=\n  (\\big[maxn/0%N]_(i | P%B) F%N) : nat_scope.\nNotation \"\\max_ i F\" :=\n  (\\big[maxn/0%N]_i F%N) : nat_scope.\nNotation \"\\max_ ( i : I | P ) F\" :=\n  (\\big[maxn/0%N]_(i : I | P%B) F%N) (only parsing) : nat_scope.\nNotation \"\\max_ ( i : I ) F\" :=\n  (\\big[maxn/0%N]_(i : I) F%N) (only parsing) : nat_scope.\nNotation \"\\max_ ( m <= i < n | P ) F\" :=\n (\\big[maxn/0%N]_(m <= i < n | P%B) F%N) : nat_scope.\nNotation \"\\max_ ( m <= i < n ) F\" :=\n (\\big[maxn/0%N]_(m <= i < n) F%N) : nat_scope.\nNotation \"\\max_ ( i < n | P ) F\" :=\n (\\big[maxn/0%N]_(i < n | P%B) F%N) : nat_scope.\nNotation \"\\max_ ( i < n ) F\" :=\n (\\big[maxn/0%N]_(i < n) F%N) : nat_scope.\nNotation \"\\max_ ( i \\in A | P ) F\" :=\n (\\big[maxn/0%N]_(i \\in A | P%B) F%N) : nat_scope.\nNotation \"\\max_ ( i \\in A ) F\" :=\n (\\big[maxn/0%N]_(i \\in A) F%N) : nat_scope.\n\nLemma leq_bigmax_cond : forall (I : finType) (P : pred I) F i0,\n  P i0 -> F i0 <= \\max_(i | P i) F i.\nProof.\nby move=> I P F i0 Pi0; rewrite -eqn_maxr (bigD1 i0) // maxnA /= maxnn eqxx.\nQed.\n\nLemma leq_bigmax : forall (I : finType) F (i0 : I), F i0 <= \\max_i F i.\nProof. by move=> *; exact: leq_bigmax_cond. Qed.\n\nImplicit Arguments leq_bigmax_cond [I P F].\nImplicit Arguments leq_bigmax [I F].\n\nLemma eq_bigmax_cond : forall (I : finType) (P : pred I) F,\n  ~~ pred0b P -> exists i0, P i0 && (F i0 == \\max_(i | P i) F i).\nProof.\nmove=> I P F n0P; set m := \\max_(i | P i) F i.\npose ub i := P i && (F i >= m); case: (pickP ub) => [i| ub0].\n  by case/andP=> Pi ubi; exists i; rewrite Pi eqn_leq leq_bigmax_cond.\nhave ubm: forall i, P i -> F i < m.\n  by move=> i Pi; case/nandP: (ub0 i); rewrite (Pi, ltnNge).\ncase/idP: (ltnn m); apply: (@big_prop _ (fun n => n < m)) => // [|n1 n2].\n  by case/existsP: n0P => i; move/ubm; exact: leq_trans.\nby rewrite !ltnNge leq_maxr negb_or => ->.\nQed.\n\nLemma eq_bigmax : forall (I : finType) F,\n  (~~ pred0b I) -> exists i0 : I, (F i0 == \\max_i F i).\nProof.\nby move=> I F; move/(eq_bigmax_cond F)=> [] x; move/andP=> [] _; exists x.\nQed.\n\nImplicit Arguments eq_bigmax_cond [I P F].\nImplicit Arguments eq_bigmax [I F].\n\nUnset Implicit Arguments.\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect_82beta/theories/bigops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.23770943289591243}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Vincent Rahli\n\n*)\n\n\n\nRequire Export computation8.\nRequire Export computation_preserves_lib.\nRequire Export atom_ren.\nRequire Export alphaeq5.\n\n\nDefinition abs2bot_op {o}\n           (op : @Opid o)\n           (bs : list BTerm) : NTerm :=\n  match op with\n  | Abs abs => mk_bot\n  | _ => oterm op bs\n  end.\n\nFixpoint abs2bot {o} (t : @NTerm o) : NTerm :=\n  match t with\n  | vterm v => vterm v\n  | sterm f => sterm (fun n => abs2bot (f n))\n  | oterm op bs => abs2bot_op op (map abs2bot_bterm bs)\n  end\nwith abs2bot_bterm {o} (b : @BTerm o) : BTerm :=\n       match b with\n       | bterm vs t => bterm vs (abs2bot t)\n       end.\n\nLemma subset_nil_implies_nil :\n  forall T (l : list T), subset l [] -> l = [].\nProof.\n  introv ss.\n  destruct l as [|x l]; allsimpl; auto.\n  pose proof (ss x); allsimpl; tcsp.\nQed.\nHint Resolve subset_nil_implies_nil : slow.\n\nLemma implies_props_abs2bot {o} :\n  forall (t : @NTerm o),\n    (nt_wf t -> nt_wf (abs2bot t))\n      # (subset (free_vars (abs2bot t)) (free_vars t))\n      # (subset (get_utokens (abs2bot t)) (get_utokens t)).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; dands; introv h; allsimpl; auto.\n\n  - Case \"sterm\".\n    inversion h as [|? imp|]; subst.\n    constructor; introv.\n    pose proof (imp n) as q; clear imp; repnd.\n    pose proof (ind n) as z; clear ind; repnd.\n    apply z0 in q0.\n    rw q1 in z1.\n    rw q in z.\n    dands; auto.\n\n    + unfold closed; eauto 3 with slow.\n\n    + unfold noutokens; eauto 3 with slow.\n\n  - Case \"oterm\".\n    unfold abs2bot_op.\n    inversion  h as [| |? ? imp e]; subst; clear h.\n\n    destruct op; allsimpl; eauto 2 with slow;\n    constructor; simpl; allrw map_map; allunfold @compose.\n\n    + introv i; allrw in_map_iff; exrepnd; subst.\n      destruct a as [l t]; simpl.\n      applydup ind in i1; repnd.\n      constructor.\n      apply i2.\n      apply imp in i1.\n      allrw @bt_wf_iff. auto.\n\n    + rw <- e.\n      apply eq_maps; introv i.\n      destruct x as [l t]; simpl; auto.\n\n    + introv i; allrw in_map_iff; exrepnd; subst.\n      destruct a as [l t]; simpl.\n      applydup ind in i1; repnd.\n      constructor.\n      apply i2.\n      apply imp in i1.\n      allrw @bt_wf_iff. auto.\n\n    + rw <- e.\n      apply eq_maps; introv i.\n      destruct x as [l t]; simpl; auto.\n\n    + introv i; allrw in_map_iff; exrepnd; subst.\n      destruct a as [l t]; simpl.\n      applydup ind in i1; repnd.\n      constructor.\n      apply i2.\n      apply imp in i1.\n      allrw @bt_wf_iff. auto.\n\n    + rw <- e.\n      apply eq_maps; introv i.\n      destruct x as [l t]; simpl; auto.\n\n  - Case \"oterm\".\n    destruct op; allsimpl; tcsp; allrw lin_flat_map; exrepnd;\n    allrw in_map_iff; exrepnd; subst;\n    destruct a as [l t]; allsimpl;\n    eexists; dands; eauto; allsimpl;\n    allrw in_remove_nvars; repnd; dands; auto;\n    apply ind in h1; repnd;\n    apply h4 in h2; auto.\n\n  - Case \"oterm\".\n    destruct op; allsimpl; tcsp; allrw in_app_iff; repndors; tcsp;\n    allrw lin_flat_map; exrepnd; try right;\n    destruct x0 as [l t]; allsimpl;\n    allrw in_map_iff; exrepnd;\n    destruct a as [l1 t1]; allsimpl; ginv;\n    applydup ind in h1; repnd;\n    eexists; dands; eauto.\nQed.\n\nLemma isprog_sterm_abs2bot {o} :\n  forall (f : @ntseq o),\n    isprog (sterm f)\n    -> isprog (sterm (fun n => abs2bot (f n))).\nProof.\n  introv isp.\n  allrw @isprog_eq.\n  inversion isp as [cl wf].\n  rw @nt_wf_sterm_iff in wf.\n  apply nt_wf_sterm_implies_isprogram.\n  apply wfst; introv.\n  pose proof (wf n) as k; clear wf; repnd.\n  pose proof (implies_props_abs2bot (f n)) as h; repnd.\n  autodimp h0 hyp.\n  rw k1 in h1.\n  rw k in h.\n  apply subset_nil_implies_nil in h1.\n  apply subset_nil_implies_nil in h.\n  dands; auto.\nQed.\nHint Resolve isprog_sterm_abs2bot : slow.\n\nLemma implies_isprog_abs2bot {o} :\n  forall (t : @NTerm o),\n    isprog t\n    -> isprog (abs2bot t).\nProof.\n  introv isp.\n  allrw @isprog_eq.\n  inversion isp as [cl wf].\n  pose proof (implies_props_abs2bot t) as h; repnd.\n  constructor; auto.\n  rw cl in h1.\n  apply subset_nil_implies_nil; auto.\nQed.\nHint Resolve implies_isprog_abs2bot : slow.\n\nLemma isnoncan_like_abs2bot {o} :\n  forall (t : @NTerm o),\n    isnoncan_like t -> isnoncan_like (abs2bot t).\nProof.\n  destruct t as [v|f|op bs]; unfold isnoncan_like; simpl; tcsp.\n  intro h.\n  destruct op; tcsp.\nQed.\nHint Resolve isnoncan_like_abs2bot : slow.\n\nLemma eapply_wf_def_sterm {o} :\n  forall (f : @ntseq o),\n    eapply_wf_def (sterm f).\nProof.\n  introv.\n  unfold eapply_wf_def; left; eexists; eauto.\nQed.\nHint Resolve eapply_wf_def_sterm : slow.\n\nFixpoint abs2bot_sub {o} (sub : @Sub o) : Sub :=\n  match sub with\n  | [] => []\n  | (v,t) :: sub => (v,abs2bot t) :: abs2bot_sub sub\n  end.\n\nLemma dec_op_abs {o} :\n  forall (op : @Opid o),\n    decidable {abs : opabs & op = Abs abs}.\nProof.\n  introv; unfold decidable.\n  dopid op as [can|ncan|exc|abs] Case; try (complete (right; sp; ginv)).\n  left; exists abs; auto.\nQed.\n\nLemma abs2bot_op_eq {o} :\n  forall op (bs : list (@BTerm o)),\n    abs2bot_op op bs\n    = if dec_op_abs op\n      then mk_bot\n      else oterm op bs.\nProof.\n  introv.\n  destruct op; boolvar; exrepnd; simpl; ginv; tcsp.\n  destruct n; eexists; eauto.\nQed.\n\nHint Rewrite @lsubst_aux_allvars_preserves_osize2 : slow.\n\nLemma unfold_lsubst2 {o} :\n  forall vars (sub : @Sub o) t,\n    {t' : NTerm\n     & alpha_eq t t'\n     # disjoint (bound_vars t') (vars ++ sub_free_vars sub)\n     # alpha_eq (lsubst t sub) (lsubst_aux t' sub)}.\nProof.\n  introv.\n  pose proof (unfold_lsubst sub t) as h; exrepnd.\n  pose proof (change_bvars_alpha_wspec (vars ++ sub_free_vars sub) t') as q.\n  destruct q as [t'' q]; repnd.\n  exists t''; dands; eauto 3 with slow.\n  rewrite h0.\n  apply lsubst_aux_alpha_congr_same_disj; auto.\n  allrw disjoint_app_l; repnd; eauto 3 with slow.\nQed.\n\nHint Rewrite @sub_free_vars_var_ren : hslow.\nHint Resolve disjoint_dom_sub_filt2 : slow.\nHint Resolve subset_sub_bound_vars_sub_filter : slow.\n\nDefinition abs2vbot_op {o}\n           v\n           (op : @Opid o)\n           (bs : list BTerm) : NTerm :=\n  match op with\n  | Abs abs => mk_vbot v\n  | _ => oterm op bs\n  end.\n\nFixpoint abs2vbot {o} v (t : @NTerm o) : NTerm :=\n  match t with\n  | vterm v => vterm v\n  | sterm f => sterm (fun n => abs2vbot v (f n))\n  | oterm op bs => abs2vbot_op v op (map (abs2vbot_bterm v) bs)\n  end\nwith abs2vbot_bterm {o} v (b : @BTerm o) : BTerm :=\n       match b with\n       | bterm vs t => bterm vs (abs2vbot v t)\n       end.\n\nLemma abs2vbot_op_eq {o} :\n  forall v op (bs : list (@BTerm o)),\n    abs2vbot_op v op bs\n    = if dec_op_abs op\n      then mk_vbot v\n      else oterm op bs.\nProof.\n  introv.\n  destruct op; boolvar; exrepnd; simpl; ginv; tcsp.\n  destruct n; eexists; eauto.\nQed.\n\nLemma abs2bot_as_abs2vbot {o} :\n  forall (t : @NTerm o), abs2bot t = abs2vbot nvarx t.\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv; allsimpl; tcsp.\n\n  - Case \"sterm\".\n    f_equal.\n    apply functional_extensionality; introv; auto.\n\n  - Case \"oterm\".\n    rewrite abs2bot_op_eq.\n    rewrite abs2vbot_op_eq.\n    boolvar; auto.\n    f_equal.\n    apply eq_maps; introv i.\n    destruct x as [l t]; allsimpl.\n    f_equal.\n    eapply ind; eauto.\nQed.\n\nFixpoint abs2vbot_sub {o} v (sub : @Sub o) : Sub :=\n  match sub with\n  | [] => []\n  | (x,t) :: sub => (x,abs2vbot v t) :: abs2vbot_sub v sub\n  end.\n\nLemma sub_find_abs2vbot_sub {o} :\n  forall v (sub : @Sub o) x,\n    sub_find (abs2vbot_sub v sub) x\n    = match sub_find sub x with\n      | Some t => Some (abs2vbot v t)\n      | None => None\n      end.\nProof.\n  induction sub; simpl; introv; tcsp; repnd; allsimpl.\n  boolvar; auto.\nQed.\n\nLemma sub_filter_abs2vbot_sub {o} :\n  forall v (sub : @Sub o) l,\n    sub_filter (abs2vbot_sub v sub) l\n    = abs2vbot_sub v (sub_filter sub l).\nProof.\n  induction sub; introv; simpl; auto.\n  repnd; simpl; boolvar; simpl; auto.\n  rewrite IHsub; auto.\nQed.\n\nLemma abs2vbot_lsubst_aux {o} :\n  forall v (t : @NTerm o) sub,\n    abs2vbot v (lsubst_aux t sub)\n    = lsubst_aux (abs2vbot v t) (abs2vbot_sub v sub).\nProof.\n  nterm_ind t as [x|f ind|op bs ind] Case; introv; simpl; auto.\n\n  - Case \"vterm\".\n    rewrite sub_find_abs2vbot_sub.\n    remember (sub_find sub x) as sf; symmetry in Heqsf; destruct sf; auto.\n\n  - Case \"oterm\".\n    repeat (rewrite abs2vbot_op_eq).\n    boolvar; simpl; autorewrite with slow; auto.\n    f_equal.\n    allrw map_map; unfold compose; simpl.\n    apply eq_maps; introv i.\n    destruct x as [l t]; allsimpl.\n    f_equal.\n    rewrite sub_filter_abs2vbot_sub.\n    eapply ind; eauto.\nQed.\n\nLemma abs2vbot_sub_var_ren {o} :\n  forall v l1 l2, @abs2vbot_sub o v (var_ren l1 l2) = var_ren l1 l2.\nProof.\n  induction l1; introv; simpl; auto.\n  destruct l2; simpl; auto.\n  fold (@var_ren o l1 l2).\n  rewrite IHl1; auto.\nQed.\nHint Rewrite @abs2vbot_sub_var_ren : slow.\n\nLemma implies_alpha_eq_abs2vbot {o} :\n  forall v1 v2 (t1 t2 : @NTerm o),\n    alpha_eq t1 t2\n    -> alpha_eq (abs2vbot v1 t1) (abs2vbot v2 t2).\nProof.\n  nterm_ind1s t1 as [x|f ind|op bs ind] Case; introv aeq; allsimpl.\n\n  - Case \"vterm\".\n    inversion aeq; subst; simpl; auto.\n\n  - Case \"sterm\".\n    inversion aeq as [|? ? imp|]; clear aeq; subst; allsimpl.\n    constructor.\n    introv.\n    apply ind; auto.\n\n  - Case \"oterm\".\n    apply alpha_eq_oterm_implies_combine in aeq; exrepnd; subst; allsimpl.\n    repeat (rewrite abs2vbot_op_eq).\n    boolvar; eauto 3 with slow.\n\n    apply alpha_eq_oterm_combine; allrw map_length; dands; auto.\n    introv i.\n    rewrite <- map_combine in i.\n    apply in_map_iff in i; exrepnd; allsimpl; ginv.\n    destruct a0 as [l1 t1].\n    destruct a as [l2 t2]; allsimpl.\n\n    applydup aeq0 in i1.\n\n    pose proof (fresh_vars\n                  (length l1)\n                  ((all_vars t1)\n                     ++ all_vars t2\n                     ++ all_vars (abs2vbot v1 t1)\n                     ++ all_vars (abs2vbot v2 t2))) as fv.\n    exrepnd.\n    allrw disjoint_app_r; repnd.\n\n    apply (alphabt_change_var_aux _ _ _ _ lvn) in i0; auto;\n    [|allrw disjoint_app_r; auto].\n    repnd.\n\n    apply (al_bterm_aux lvn); auto;\n    [allrw disjoint_app_r; auto|].\n\n    pose proof (ind t1 (lsubst_aux t1 (var_ren l1 lvn)) l1) as q; clear ind.\n    autorewrite with slow in *.\n    repeat (autodimp q hyp); eauto 3 with slow.\n    apply q in i2; clear q.\n    repeat (rewrite abs2vbot_lsubst_aux in i2).\n    autorewrite with slow in *; auto.\nQed.\nHint Resolve implies_alpha_eq_abs2vbot : slow.\n\nLemma implies_alphaeq_sub_abs2vbot_sub {o} :\n  forall v1 v2 (sub1 sub2 : @Sub o),\n    alphaeq_sub sub1 sub2\n    -> alphaeq_sub (abs2vbot_sub v1 sub1) (abs2vbot_sub v2 sub2).\nProof.\n  induction sub1; introv aeq; inversion aeq; subst; auto; clear aeq; simpl.\n  constructor; eauto 3 with slow.\n  apply alphaeq_eq.\n  apply implies_alpha_eq_abs2vbot.\n  apply alphaeq_eq; auto.\nQed.\n\nLemma abs2bot_sub_as_abs2vbot_sub {o} :\n  forall (sub : @Sub o), abs2bot_sub sub = abs2vbot_sub nvarx sub.\nProof.\n  induction sub; allsimpl; auto.\n  repnd; allsimpl; rewrite IHsub.\n  rewrite abs2bot_as_abs2vbot; auto.\nQed.\n\nLemma subset_free_vars_abs2vbot {o} :\n  forall v (t : @NTerm o),\n    subset (free_vars (abs2vbot v t)) (free_vars t).\nProof.\n  nterm_ind1s t as [x|f ind|op bs ind] Case; simpl; auto.\n  Case \"oterm\".\n  rewrite abs2vbot_op_eq; boolvar; simpl; autorewrite with slow; auto.\n  rewrite flat_map_map; unfold compose; simpl.\n  apply subset_flat_map2; introv i.\n  destruct x as [l t]; simpl.\n  apply subvars_eq.\n  apply implies_subvars_remove_nvars.\n  apply subvars_eq.\n  eapply ind; eauto 3 with slow.\nQed.\n\nLemma subset_bound_vars_abs2vbot {o} :\n  forall v (t : @NTerm o),\n    subset (bound_vars (abs2vbot v t)) (v :: bound_vars t).\nProof.\n  nterm_ind1s t as [x|f ind|op bs ind] Case; simpl; auto.\n  Case \"oterm\".\n  rewrite abs2vbot_op_eq; boolvar; simpl; eauto 3 with slow.\n  rewrite flat_map_map; unfold compose; simpl.\n  apply subset_flat_map; introv i.\n  destruct x as [l t]; simpl.\n  rw subset_app; dands.\n  - apply subset_cons1.\n    introv j; rw lin_flat_map; eexists; dands; eauto.\n    simpl; rw in_app_iff; sp.\n  - introv j.\n    eapply ind in j; eauto 3 with slow.\n    allsimpl; repndors; tcsp.\n    right; apply lin_flat_map.\n    eexists; dands; eauto.\n    simpl; apply in_app_iff; sp.\nQed.\n\nLemma subset_sub_free_vars_abs2vbot_sub {o} :\n  forall v (sub : @Sub o),\n    subset (sub_free_vars (abs2vbot_sub v sub)) (sub_free_vars sub).\nProof.\n  induction sub; simpl; auto.\n  repnd; allsimpl.\n  apply subset_app_lr; auto.\n  apply subset_free_vars_abs2vbot.\nQed.\n\nLemma abs2bot_lsubst {o} :\n  forall (t : @NTerm o) sub,\n    alpha_eq\n      (abs2bot (lsubst t sub))\n      (lsubst (abs2bot t) (abs2bot_sub sub)).\nProof.\n  introv.\n\n  pose proof (ex_fresh_var (sub_free_vars sub)) as fv; exrepnd.\n  repeat (rewrite abs2bot_as_abs2vbot).\n\n  eapply alpha_eq_trans;\n    [apply (implies_alpha_eq_abs2vbot _ v _ (lsubst t sub));\n      eauto 3 with slow|].\n\n  pose proof (unfold_lsubst sub t) as q; exrepnd; allsimpl.\n  rewrite q0; clear q0.\n\n  rewrite abs2bot_sub_as_abs2vbot_sub.\n\n  eapply alpha_eq_trans;\n    [|apply lsubst_alpha_congr3;\n       [apply alpha_eq_refl\n       |apply (implies_alphaeq_sub_abs2vbot_sub v _ sub _);\n         eauto 3 with slow]\n    ].\n\n  pose proof (unfold_lsubst (abs2vbot_sub v sub) (abs2vbot nvarx t)) as h; exrepnd.\n  rewrite h0; clear h0.\n\n  rewrite abs2vbot_lsubst_aux.\n\n  apply lsubst_aux_alpha_congr_same_disj;auto;[eauto 4 with slow|];[].\n\n  eapply subset_disjoint;[apply subset_bound_vars_abs2vbot|].\n\n  eapply subset_disjoint_r;[|apply subset_sub_free_vars_abs2vbot_sub].\n  apply disjoint_cons_l; dands; auto.\nQed.\n\nLemma isexc_abs2bot {o} :\n  forall (t : @NTerm o), isexc t -> isexc (abs2bot t).\nProof.\n  introv ise.\n  apply isexc_implies2 in ise; exrepnd; subst; simpl; auto.\nQed.\nHint Resolve isexc_abs2bot : slow.\n\nDefinition same_sign_bs {o} (bs1 bs2 : list (@BTerm o)) :=\n  map num_bvars bs1 = map num_bvars bs2.\n\nDefinition same_sign_bs_abs2bot {o} :\n  forall (bs : list (@BTerm o)),\n    same_sign_bs bs (map abs2bot_bterm bs).\nProof.\n  introv; unfold same_sign_bs.\n  rewrite map_map; unfold compose.\n  apply eq_maps; introv i.\n  destruct x as [l t]; unfold num_bvars; simpl; auto.\nQed.\nHint Resolve same_sign_bs_abs2bot : slow.\n\nLemma eapply_wf_def_oterm_change_bs {o} :\n  forall (op : @Opid o) bs1 bs2,\n   same_sign_bs bs1 bs2\n    -> eapply_wf_def (oterm op bs1)\n    -> eapply_wf_def (oterm op bs2).\nProof.\n  introv len eap.\n  allunfold @eapply_wf_def; repndors; exrepnd;\n  allunfold @mk_nseq; allunfold @mk_lam; ginv.\n\n  - unfold same_sign_bs in len; allsimpl.\n    destruct bs2; allsimpl; ginv; eauto.\n\n  - unfold same_sign_bs in len; allsimpl.\n    unfold num_bvars in len; allsimpl.\n    destruct bs2 as [|bt l]; allsimpl; ginv.\n    destruct l; allsimpl; ginv.\n    destruct bt as [l t]; allsimpl.\n    destruct l as [|x l]; allsimpl; ginv.\n    destruct l; ginv; eauto.\nQed.\nHint Resolve eapply_wf_def_oterm_change_bs : slow.\n\nLemma isvalue_like_abs2bot {o} :\n  forall (t : @NTerm o), isvalue_like t -> isvalue_like (abs2bot t).\nProof.\n  introv i.\n  apply isvalue_like_implies_or1 in i.\n  unfold is_can_or_exc in i; repndors.\n  - apply iscan_implies in i; repndors; exrepnd; subst; simpl; eauto 3 with slow.\n  - apply isexc_implies2 in i; exrepnd; subst; eauto 3 with slow.\nQed.\nHint Resolve isvalue_like_abs2bot : slow.\n\nLemma alpha_eq_mk_fresh_not_in {o} :\n  forall v1 v2 (t : @NTerm o),\n    !LIn v1 (free_vars t)\n    -> !LIn v2 (free_vars t)\n    -> alpha_eq (mk_fresh v1 t) (mk_fresh v2 t).\nProof.\n  introv ni1 ni2.\n  apply alpha_eq_oterm_combine; simpl; dands; auto.\n  introv h; repndors; tcsp; ginv.\n  apply alpha_eq_bterm_bterm_disjoint;\n    try (apply disjoint_singleton_l); auto.\nQed.\nHint Resolve alpha_eq_mk_fresh_not_in : slow.\n\nLemma  pushdown_fresh_abs2bot {o} :\n  forall n (t : @NTerm o),\n    isvalue_like t\n    -> alpha_eq\n         (pushdown_fresh n (abs2bot t))\n         (abs2bot (pushdown_fresh n t)).\nProof.\n  introv isv.\n  unfold pushdown_fresh.\n  destruct t as [v|f|op bs]; simpl; auto.\n  repeat (rewrite abs2bot_op_eq).\n  boolvar; simpl; auto.\n\n  - exrepnd; subst.\n    unfold isvalue_like in isv; allsimpl; tcsp.\n\n  - unfold mk_fresh_bterms.\n    allrw map_map; unfold compose; simpl.\n    apply alpha_eq_oterm_combine2.\n    autorewrite with slow.\n    dands; auto.\n    introv i.\n    rewrite <- map_combine in i.\n    apply in_map_iff in i; exrepnd; ginv.\n    apply in_combine_same in i1; repnd; subst.\n    destruct a as [l t]; allsimpl.\n    apply alpha_eq_bterm_congr; fold_terms.\n\n    unfold maybe_new_var; boolvar; auto.\n\n    pose proof (newvar_prop (abs2bot t)) as k.\n    remember (newvar (abs2bot t)) as nv1; clear Heqnv1.\n\n    pose proof (newvar_prop t) as h.\n    remember (newvar t) as nv2; clear Heqnv2.\n\n    assert (!LIn nv2 (free_vars (abs2bot t))) as j.\n    {\n      intro j.\n      pose proof (implies_props_abs2bot t) as z; repnd.\n      apply z1 in j; auto.\n    }\n\n    eauto 3 with slow.\nQed.\n\nLemma implies_nt_wf_abs2bot {o} :\n  forall (t : @NTerm o), nt_wf t -> nt_wf (abs2bot t).\nProof.\n  introv.\n  pose proof (implies_props_abs2bot t); tcsp.\nQed.\nHint Resolve implies_nt_wf_abs2bot : slow.\n\nFixpoint abs2vbot_utok_sub {o} v (sub : @utok_sub o) : utok_sub :=\n  match sub with\n  | [] => []\n  | (x,t) :: sub => (x,abs2vbot v t) :: abs2vbot_utok_sub v sub\n  end.\n\nFixpoint abs2bot_utok_sub {o} (sub : @utok_sub o) : utok_sub :=\n  match sub with\n  | [] => []\n  | (x,t) :: sub => (x,abs2bot t) :: abs2bot_utok_sub sub\n  end.\n\nLemma utoks_sub_find_abs2vbot_utok_sub {o} :\n  forall v (sub : @utok_sub o) a,\n    utok_sub_find (abs2vbot_utok_sub v sub) a\n    = match utok_sub_find sub a with\n      | Some t => Some (abs2vbot v t)\n      | None => None\n      end.\nProof.\n  induction sub; introv; simpl; auto.\n  repnd; simpl; boolvar; auto.\nQed.\n\nLemma abs2vbot_subst_utokens_aux {o} :\n  forall v (t : @NTerm o) sub,\n    abs2vbot v (subst_utokens_aux t sub)\n    = subst_utokens_aux (abs2vbot v t) (abs2vbot_utok_sub v sub).\nProof.\n  nterm_ind t as [x|f ind|op bs ind] Case; introv; auto.\n\n  Case \"oterm\".\n  rewrite subst_utokens_aux_oterm.\n  simpl.\n  repeat (rewrite abs2vbot_op_eq).\n  boolvar; try (rewrite subst_utokens_aux_oterm); simpl.\n\n  - exrepnd; subst; simpl; auto.\n\n  - remember (get_utok op) as guo; symmetry in Heqguo; destruct guo; simpl;\n    allrw @map_map; unfold compose.\n\n    + apply get_utok_some in Heqguo; subst; allsimpl.\n      unfold subst_utok.\n      rewrite utoks_sub_find_abs2vbot_utok_sub.\n      remember (utok_sub_find sub g) as f; symmetry in Heqf; destruct f; auto.\n      simpl.\n      f_equal.\n      allrw map_map; unfold compose.\n      apply eq_maps; introv i.\n      destruct x as [l t]; simpl.\n      f_equal; eauto.\n\n    + rewrite abs2vbot_op_eq; boolvar; tcsp; GC.\n      f_equal.\n      apply eq_maps; introv i.\n      destruct x as [l t]; simpl.\n      f_equal; eauto.\nQed.\n\nLemma abs2bot_utok_sub_as_abs2vbot_utok_sub {o} :\n  forall (sub : @utok_sub o), abs2bot_utok_sub sub = abs2vbot_utok_sub nvarx sub.\nProof.\n  induction sub; allsimpl; auto.\n  repnd; allsimpl; rewrite IHsub.\n  rewrite abs2bot_as_abs2vbot; auto.\nQed.\n\nLemma implies_alphaeq_utok_sub_abs2vbot_utok_sub {o} :\n  forall v1 v2 (sub1 sub2 : @utok_sub o),\n    alphaeq_utok_sub sub1 sub2\n    -> alphaeq_utok_sub (abs2vbot_utok_sub v1 sub1) (abs2vbot_utok_sub v2 sub2).\nProof.\n  induction sub1; introv aeq; inversion aeq; subst; auto; clear aeq; simpl.\n  constructor; eauto 3 with slow.\n  apply alphaeq_eq.\n  apply implies_alpha_eq_abs2vbot.\n  apply alphaeq_eq; auto.\nQed.\n\nLemma subset_free_vars_utok_sub_abs2vbot_utok_sub {o} :\n  forall v (sub : @utok_sub o),\n    subset\n      (free_vars_utok_sub (abs2vbot_utok_sub v sub))\n      (free_vars_utok_sub sub).\nProof.\n  induction sub; simpl; auto.\n  repnd; allsimpl.\n  apply subset_app_lr; auto.\n  apply subset_free_vars_abs2vbot.\nQed.\n\nLemma abs2bot_subst_utokens {o} :\n  forall (t : @NTerm o) sub,\n    alpha_eq\n      (abs2bot (subst_utokens t sub))\n      (subst_utokens (abs2bot t) (abs2bot_utok_sub sub)).\nProof.\n  introv.\n\n  pose proof (ex_fresh_var (free_vars_utok_sub sub)) as fv; exrepnd.\n  repeat (rewrite abs2bot_as_abs2vbot).\n\n  eapply alpha_eq_trans;\n    [apply (implies_alpha_eq_abs2vbot _ v _ (subst_utokens t sub));\n      eauto 3 with slow|].\n\n  pose proof (unfold_subst_utokens sub t) as q; exrepnd; allsimpl.\n  rewrite q0; clear q0.\n\n  rewrite abs2bot_utok_sub_as_abs2vbot_utok_sub.\n\n  eapply alpha_eq_trans;\n    [|apply alpha_eq_subst_utokens;\n       [apply alpha_eq_refl\n       |apply (implies_alphaeq_utok_sub_abs2vbot_utok_sub v _ sub _);\n         eauto 3 with slow]\n    ].\n\n  pose proof (unfold_subst_utokens (abs2vbot_utok_sub v sub) (abs2vbot nvarx t)) as h; exrepnd.\n  rewrite h0; clear h0.\n\n  rewrite abs2vbot_subst_utokens_aux.\n\n  apply alpha_eq_subst_utokens_aux;eauto 4 with slow.\n\n  eapply subset_disjoint_r;[|apply subset_bound_vars_abs2vbot].\n\n  eapply subset_disjoint;[apply subset_free_vars_utok_sub_abs2vbot_utok_sub|].\n  apply disjoint_cons_r; dands; eauto 3 with slow.\nQed.\n\nHint Resolve wf_term_subst : slow.\n\nLemma compute_step_abs2bot {o} :\n  forall (t : @NTerm o) u,\n    wf_term t\n    -> compute_step [] t = csuccess u\n    -> {w : NTerm\n        & compute_step [] (abs2bot t) = csuccess w\n        # alpha_eq w (abs2bot u)}.\nProof.\n  nterm_ind1s t as [v|f ind|op bs ind] Case; introv wf comp.\n\n  - Case \"vterm\".\n    csunf; allsimpl; ginv.\n\n  - Case \"sterm\".\n    csunf comp; allsimpl; ginv; auto.\n    eexists; csunf; simpl; dands; eauto.\n\n  - Case \"oterm\".\n    dopid op as [can|ncan|exc|abs] SCase.\n\n    + SCase \"Can\".\n      csunf comp; allsimpl; ginv; auto.\n      eexists; csunf; simpl; dands; eauto.\n\n    + SCase \"NCan\".\n      destruct bs as [|b1 bs]; try (complete (allsimpl; ginv)).\n      destruct b1 as [l t]; try (complete (allsimpl; ginv)).\n      destruct l; try (complete (allsimpl; ginv)).\n\n      {\n        destruct t as [x|f|op bts]; try (complete (allsimpl; ginv));[|].\n\n        - csunf comp; allsimpl.\n          dopid_noncan ncan SSCase; allsimpl; ginv; auto.\n\n          {\n            SSCase \"NApply\".\n            apply compute_step_seq_apply_success in comp; exrepnd; subst; allsimpl.\n            csunf; simpl; auto.\n            eexists; dands; eauto.\n          }\n\n          {\n            SSCase \"NEApply\".\n\n            apply compute_step_eapply_success in comp; exrepnd; subst.\n            repndors; exrepnd; allsimpl; subst.\n\n            + apply compute_step_eapply2_success in comp1; repnd; subst.\n              repndors; exrepnd; subst; ginv.\n              csunf; simpl.\n              dcwf h; simpl.\n              boolvar; try omega.\n              rewrite Znat.Nat2Z.id; auto.\n              eexists; dands; eauto.\n\n            + csunf; simpl.\n              apply isexc_implies2 in comp0; exrepnd; subst.\n              dcwf h; simpl; auto.\n              eexists; dands; eauto.\n\n            + fold_terms.\n              rewrite compute_step_eapply_iscan_isnoncan_like; eauto 3 with slow.\n              pose proof (ind arg2 arg2 []) as h; clear ind.\n              repeat (autodimp h hyp); eauto 3 with slow.\n              apply wf_term_eapply_iff in wf; exrepnd; allunfold @nobnd; ginv.\n              apply h in comp1; clear h; auto.\n              exrepnd; rewrite comp1.\n              eexists; dands; eauto.\n              simpl; repeat prove_alpha_eq4.\n          }\n\n          {\n            SSCase \"NFix\".\n            apply compute_step_fix_success in comp; repnd; subst.\n            csunf; simpl; auto.\n            eexists; dands; eauto.\n          }\n\n          {\n            SSCase \"NCbv\".\n            apply compute_step_cbv_success in comp; exrepnd; subst.\n            csunf; simpl; auto.\n            eexists; dands; eauto.\n            eapply alpha_eq_trans;[|apply alpha_eq_sym; apply abs2bot_lsubst]; auto.\n          }\n\n          {\n            SSCase \"NTryCatch\".\n            apply compute_step_try_success in comp; exrepnd; subst; allsimpl.\n            csunf; simpl.\n            eexists; dands; eauto.\n          }\n\n          {\n            SSCase \"NCanTest\".\n            apply compute_step_seq_can_test_success in comp; exrepnd; subst; allsimpl.\n            csunf; simpl.\n            eexists; dands; eauto.\n          }\n\n        - dopid op as [can2|ncan2|exc2|abs2] SSCase.\n\n          + SSCase \"Can\".\n            dopid_noncan ncan SSSCase.\n\n            {\n              SSSCase \"NApply\".\n\n              csunf comp; allsimpl.\n              apply compute_step_apply_success in comp.\n              repndors; exrepnd; subst; auto; csunf; simpl; eexists; dands; eauto.\n              eapply alpha_eq_trans;[|apply alpha_eq_sym; apply abs2bot_lsubst]; auto.\n            }\n\n            {\n              SSSCase \"NEApply\".\n\n              csunf comp; allsimpl.\n              apply compute_step_eapply_success in comp.\n              repndors; exrepnd; subst; auto.\n              repndors; exrepnd; subst; allsimpl; auto.\n\n              - apply compute_step_eapply2_success in comp1; repnd; subst.\n                repndors; exrepnd; subst; auto; ginv.\n\n                + unfold mk_lam in *; ginv.\n                  csunf; simpl.\n                  dcwf h; simpl.\n                  apply iscan_implies in comp0; repndors; exrepnd; subst; simpl; auto;\n                  eexists; dands; eauto;\n                  eapply alpha_eq_trans;\n                  try (apply alpha_eq_sym; apply abs2bot_lsubst); auto.\n\n                + unfold mk_nseq in *; allsimpl; ginv; GC.\n                  csunf; simpl.\n                  dcwf h; simpl.\n                  boolvar; simpl; auto; try omega.\n                  rewrite Znat.Nat2Z.id; auto.\n                  eexists; dands; eauto.\n\n              - fold_terms; rewrite compute_step_eapply_iscan_isexc; eauto 3 with slow.\n\n              - fold_terms; rewrite compute_step_eapply_iscan_isnoncan_like; eauto 3 with slow.\n\n                pose proof (ind arg2 arg2 []) as q; clear ind.\n                repeat (autodimp q hyp); eauto 2 with slow.\n                apply wf_term_eapply_iff in wf; exrepnd; allunfold @nobnd; ginv.\n                apply q in comp1; clear q; auto.\n                exrepnd; rewrite comp1; auto.\n                eexists; dands; eauto.\n                repeat prove_alpha_eq4.\n            }\n\n            {\n              SSSCase \"NFix\".\n\n              csunf comp; allsimpl.\n              apply compute_step_fix_success in comp.\n              repndors; exrepnd; subst; auto.\n              csunf; simpl; eexists; dands; eauto.\n            }\n\n            {\n              SSSCase \"NSpread\".\n\n              csunf comp; allsimpl.\n              apply compute_step_spread_success in comp.\n              repndors; exrepnd; subst; auto.\n              csunf; simpl; eexists; dands; eauto.\n              eapply alpha_eq_trans;[|apply alpha_eq_sym; apply abs2bot_lsubst]; auto.\n            }\n\n            {\n              SSSCase \"NDsup\".\n\n              csunf comp; allsimpl.\n              apply compute_step_dsup_success in comp.\n              repndors; exrepnd; subst; auto.\n              csunf; simpl; eexists; dands; eauto.\n              eapply alpha_eq_trans;[|apply alpha_eq_sym; apply abs2bot_lsubst]; auto.\n            }\n\n            {\n              SSSCase \"NDecide\".\n\n              csunf comp; allsimpl.\n              apply compute_step_decide_success in comp.\n              repndors; exrepnd; subst; auto.\n              repndors; exrepnd; subst; auto;\n              csunf; simpl; eexists; dands; eauto;\n              eapply alpha_eq_trans;\n              try (apply alpha_eq_sym; apply abs2bot_lsubst); auto.\n            }\n\n            {\n              SSSCase \"NCbv\".\n\n              csunf comp; allsimpl.\n              apply compute_step_cbv_success in comp.\n              repndors; exrepnd; subst; auto.\n              csunf; simpl; eexists; dands; eauto.\n              eapply alpha_eq_trans;\n                try (apply alpha_eq_sym; apply abs2bot_lsubst); auto.\n            }\n\n            {\n              SSSCase \"NSleep\".\n\n              csunf comp; allsimpl.\n              apply compute_step_sleep_success in comp.\n              repndors; exrepnd; subst; auto.\n              csunf; simpl.\n              unfold compute_step_sleep; simpl.\n              eexists; dands; eauto.\n            }\n\n            {\n              SSSCase \"NTUni\".\n\n              csunf comp; allsimpl.\n              apply compute_step_tuni_success in comp.\n              repndors; exrepnd; subst; auto.\n              csunf; simpl.\n              unfold compute_step_tuni; simpl.\n              boolvar; try omega.\n              rewrite Znat.Nat2Z.id; auto.\n              eexists; dands; eauto.\n            }\n\n            {\n              SSSCase \"NMinus\".\n\n              csunf comp; allsimpl.\n              apply compute_step_minus_success in comp.\n              repndors; exrepnd; subst; auto.\n              csunf; simpl.\n              unfold compute_step_minus; simpl.\n              eexists; dands; eauto.\n            }\n\n            {\n              SSSCase \"NFresh\".\n\n              csunf comp; allsimpl; ginv.\n            }\n\n            {\n              SSSCase \"NTryCatch\".\n\n              csunf comp; allsimpl.\n              apply compute_step_try_success in comp.\n              repndors; exrepnd; subst; auto.\n              csunf; simpl.\n              eexists; dands; eauto.\n            }\n\n            {\n              SSSCase \"NParallel\".\n\n              csunf comp; allsimpl.\n              apply compute_step_parallel_success in comp.\n              repndors; exrepnd; subst; auto.\n              csunf; simpl.\n              unfold compute_step_parallel.\n              eexists; dands; eauto.\n            }\n\n            {\n              SSSCase \"NCompOp\".\n\n              apply compute_step_ncompop_can1_success in comp; repnd.\n              repndors; exrepnd; allsimpl; subst; tcsp; simpl.\n\n              - csunf; simpl.\n                dcwf h.\n                apply compute_step_compop_success_can_can in comp1; exrepnd; subst; ginv; GC.\n                repndors; exrepnd; subst; allsimpl;\n                unfold compute_step_comp; allrw;\n                eexists; dands; eauto;\n                boolvar; auto.\n\n              - rewrite compute_step_ncompop_ncanlike2; eauto 3 with slow.\n                dcwf h.\n                pose proof (ind t t []) as q; clear ind.\n                repeat (autodimp q hyp); eauto 2 with slow.\n                allrw @wf_term_ncompop_iff; exrepnd; ginv.\n                apply q in comp4; clear q; auto.\n                exrepnd.\n                rewrite comp2; auto.\n                eexists; dands; eauto.\n                repeat prove_alpha_eq4.\n\n              - csunf; simpl.\n                apply isexc_implies2 in comp1; exrepnd; subst.\n                dcwf h; simpl; auto.\n                eexists; dands; eauto.\n            }\n\n            {\n              SSSCase \"NArithOp\".\n\n              apply compute_step_narithop_can1_success in comp; repnd.\n              repndors; exrepnd; allsimpl; subst; tcsp; allsimpl.\n\n              - csunf; simpl.\n                dcwf h.\n                apply compute_step_arithop_success_can_can in comp1; exrepnd; subst; ginv; GC.\n                repndors; exrepnd; subst; allsimpl;\n                unfold compute_step_comp; allrw;\n                eexists; dands; eauto;\n                boolvar; auto.\n\n              - rewrite compute_step_narithop_ncanlike2; eauto 3 with slow.\n                dcwf h.\n                pose proof (ind t t []) as q; clear ind.\n                repeat (autodimp q hyp); eauto 2 with slow.\n                allrw @wf_term_narithop_iff; exrepnd; ginv.\n                apply q in comp4; clear q; auto.\n                exrepnd.\n                rewrite comp2; auto.\n                eexists; dands; eauto.\n                repeat prove_alpha_eq4.\n\n              - csunf; simpl.\n                apply isexc_implies2 in comp1; exrepnd; subst.\n                dcwf h; simpl; auto.\n                eexists; dands; eauto.\n            }\n\n            {\n              SSSCase \"NCanTest\".\n\n              csunf comp; allsimpl.\n              apply compute_step_can_test_success in comp.\n              repndors; exrepnd; subst; auto.\n              csunf; simpl.\n              eexists; dands; eauto.\n              destruct (canonical_form_test_for c can2); auto.\n            }\n\n          + SSCase \"NCan\".\n\n            csunf comp; allsimpl.\n            remember (compute_step [] (oterm (NCan ncan2) bts)) as c.\n            destruct c; allsimpl; ginv.\n            symmetry in Heqc.\n\n            pose proof (ind\n                          (oterm (NCan ncan2) bts)\n                          (oterm (NCan ncan2) bts) []) as q; clear ind.\n            repeat (autodimp q hyp); eauto 2 with slow.\n\n            applydup @wf_oterm_iff in wf; repnd.\n            pose proof (wf0 (bterm [] (oterm (NCan ncan2) bts))) as wfn; allsimpl.\n            autodimp wfn hyp.\n            allrw @wf_bterm_iff.\n\n            apply q in Heqc; clear q; auto.\n            exrepnd.\n            csunf; allsimpl.\n            rewrite Heqc1; auto; simpl.\n            eexists; dands; eauto.\n            repeat prove_alpha_eq4.\n\n          + SSCase \"Exc\".\n\n            csunf comp; allsimpl.\n            apply compute_step_catch_success in comp.\n            repndors; exrepnd; subst; allsimpl; ginv.\n\n            * csunf; simpl; auto.\n              eexists; dands; eauto.\n              unfold mk_atom_eq.\n              repeat prove_alpha_eq4.\n              eapply alpha_eq_trans;\n                try (apply alpha_eq_sym; apply abs2bot_lsubst); auto.\n\n            * csunf; simpl; auto.\n              rewrite compute_step_catch_if_diff; auto.\n              eexists; dands; eauto.\n\n          + SSCase \"Abs\".\n\n            csunf comp; allsimpl; ginv.\n      }\n\n      {\n        csunf comp; allsimpl.\n        apply compute_step_fresh_success in comp; exrepnd; subst.\n        repndors; exrepnd; subst; ginv.\n\n        - csunf; simpl; boolvar; auto.\n          eexists; dands; eauto.\n\n        - rewrite compute_step_fresh_if_isvalue_like2; simpl; eauto 3 with slow.\n          eexists; dands; eauto.\n          apply pushdown_fresh_abs2bot; auto.\n\n        - rewrite compute_step_fresh_if_isnoncan_like; simpl; eauto 3 with slow.\n\n          allrw @wf_fresh_iff.\n\n          pose proof (ind t (subst t n (mk_utoken (get_fresh_atom t))) [n]) as q; clear ind.\n          repeat (autodimp q hyp); eauto 2 with slow.\n          { rewrite simple_osize_subst; eauto 2 with slow. }\n          apply q in comp2; clear q; eauto 3 with slow;[].\n          exrepnd; allsimpl.\n\n          pose proof (abs2bot_lsubst t [(n,mk_utoken (get_fresh_atom t))]) as aeq.\n          pose proof (compute_step_alpha\n                        []\n                        (abs2bot (lsubst t [(n, mk_utoken (get_fresh_atom t))]))\n                        (lsubst (abs2bot t) (abs2bot_sub [(n, mk_utoken (get_fresh_atom t))]))\n                        w) as comp.\n          repeat (autodimp comp hyp).\n          { apply implies_nt_wf_abs2bot.\n            apply nt_wf_subst; eauto 2 with slow. }\n          exrepnd; allsimpl.\n          fold_terms; allrw @fold_subst.\n\n          assert (!LIn (get_fresh_atom t) (get_utokens (abs2bot t))) as ni1.\n          {\n            intro h.\n            pose proof (implies_props_abs2bot t) as q; repnd.\n            apply q in h.\n            apply get_fresh_atom_prop in h; tcsp.\n          }\n\n          assert (!LIn (get_fresh_atom (abs2bot t)) (get_utokens (abs2bot t))) as ni2.\n          {\n            intro h.\n            apply get_fresh_atom_prop in h; tcsp.\n          }\n\n          pose proof (compute_step_subst_utoken\n                        []\n                        (abs2bot t)\n                        t2'\n                        [(n, mk_utoken (get_fresh_atom t))]) as comp'.\n          repeat (autodimp comp' hyp); simpl; eauto 3 with slow.\n\n          { unfold get_utokens_sub; simpl.\n            apply disjoint_singleton_l; auto. }\n\n          exrepnd; allsimpl.\n\n          pose proof (comp'0 [(n, mk_utoken (get_fresh_atom (abs2bot t)))]) as comp''.\n          allsimpl.\n          repeat (autodimp comp'' hyp); eauto 3 with slow.\n\n          { unfold get_utokens_sub; simpl.\n            apply disjoint_singleton_l; auto. }\n\n          exrepnd; allsimpl.\n          allrw @fold_subst.\n          rewrite comp''1; simpl.\n          eexists; dands; eauto.\n\n          apply implies_alpha_eq_mk_fresh.\n\n          rename comp''0 into aeq1.\n          assert (alpha_eq (subst w0 n (mk_utoken (get_fresh_atom t))) (abs2bot x)) as aeq2.\n          { eauto 4 with slow. }\n\n          unfold get_utokens_sub in *; allsimpl.\n          allrw disjoint_singleton_l.\n\n          eapply alpha_eq_trans;\n            [|apply alpha_eq_sym; apply abs2bot_subst_utokens].\n          simpl.\n\n          eapply alpha_eq_trans;\n            [apply alpha_eq_subst_utokens_same;exact aeq1|].\n\n          eapply alpha_eq_trans;\n            [apply simple_alphaeq_subst_utokens_subst;\n              intro i; apply comp'4 in i; auto|].\n\n          eapply alpha_eq_trans;\n            [|apply alpha_eq_subst_utokens_same;exact aeq2].\n\n          eapply alpha_eq_trans;\n            [|apply alpha_eq_sym;apply simple_alphaeq_subst_utokens_subst;auto].\n\n          auto.\n      }\n\n    + SCase \"Exc\".\n\n      csunf comp; allsimpl; ginv.\n      csunf; simpl.\n      eexists; dands; eauto.\n\n    + SCase \"Abs\".\n\n      csunf comp; allsimpl.\n      apply compute_step_lib_success in comp.\n      exrepnd; subst.\n      unfold found_entry in comp0; allsimpl; ginv.\nQed.\n\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"../util/\" \"../terms/\")\n*** End:\n*)\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/computation/computation_preserves_abs2bot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.23770943289591243}}
{"text": "Require Import ssreflect ssrbool ssrnat eqtype seq fintype.\nRequire Import bitsrep instr instrsyntax instrcodec SPred pointsto cursor reader writer roundtrip.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(*=program *)\nInductive program :=\n  prog_instr (c: Instr)\n| prog_skip | prog_seq (p1 p2: program)\n| prog_declabel (body: DWORD -> program)\n| prog_label (l: DWORD)\n| prog_data {T} {R: Reader T} {W: Writer T} (RT: Roundtrip R W) (v: T).\nCoercion prog_instr: Instr >-> program.\n(*=End *)\n\nRequire Import tuple.\n\n(* Instructions in instrsyntax are up to level 60, so delimiters need to be\n   above that. *)\n(*=programsyntax *)\nInfix \";;\" := prog_seq (at level 62, right associativity).\nNotation \"'LOCAL' l ';' p\" := (prog_declabel (fun l => p))\n  (at level 65, l ident, right associativity).\nNotation \"l ':;'\" := (prog_label l)\n  (at level 8, no associativity, format \"l ':;'\").\n(*=End *)\nNotation \"l ':;;' p\" := (prog_seq (prog_label l) p)\n  (at level 8, p at level 65, right associativity,\n   format \"l ':;;'  p\").\n\n(*=dd *)\nDefinition db := prog_data RoundtripBYTE.\nDefinition dw := prog_data RoundtripWORD.\nDefinition dd := prog_data RoundtripDWORD.\n(*=End *)\nDefinition ds s := prog_data (@RoundtripTupleBYTE (String.length s)) (stringToTupleBYTE s).\nDefinition dsz s := ds s;; db #0.\nDefinition align m := prog_data (RoundtripAlign m) tt.\nDefinition alignWith b m := prog_data (RoundtripAlignWith b m) tt.\nDefinition pad m := prog_data (RoundtripPad m) tt.\nDefinition padWith b m := prog_data (RoundtripPadWith b m) tt.\nDefinition skipAlign m := prog_data (RoundtripSkipAlign m) tt.\n\n(* Sometimes handy just to get nice output *)\nFixpoint linearizeWith (p: program) tail :=\n  match p with\n  | prog_skip => tail\n  | prog_seq p1 p2 => linearizeWith p1 (linearizeWith p2 tail)\n  | prog_declabel f => prog_declabel (fun d => linearizeWith (f d) tail)\n  | _ => if tail is prog_skip then p else prog_seq p tail\n  end.\nDefinition linearize p := linearizeWith p prog_skip.\n\nDeclare Reduction showprog :=\n  cbv beta delta -[fromNat fromHex makeMOV makeUOP makeBOP db dw dd ds align pad] zeta iota.\n\nFixpoint interpProgram i j prog :=\n  match prog with\n  | prog_instr c => i -- j :-> c\n  | prog_skip =>\n    match i, j with\n      mkCursor i, mkCursor j => i = j /\\\\ empSP\n    | _, _ => i = j /\\\\ empSP\n    end\n  | prog_seq p1 p2 => Exists i': DWORD, interpProgram i i' p1 ** interpProgram i' j p2\n  | prog_declabel body => Exists l, interpProgram i j (body l)\n  | prog_label l =>\n    match i, j with\n      mkCursor i, mkCursor j => i = j /\\\\ i = l /\\\\ empSP\n    | _, _ => i = j /\\\\ i = l /\\\\ empSP\n    end\n  | prog_data _ _ _ _ v => i -- j :-> v\n  end.\n\nRequire Import septac.\nLemma interpProgramLeAux prog : forall p q, interpProgram p q prog |-- leCursor p q /\\\\ interpProgram p q prog.\nProof.\ninduction prog => p q; rewrite /interpProgram-/interpProgram.\n+ apply memIsLe.\n+ destruct p. destruct q; sdestruct => ->; rewrite leCursor_refl; sbazooka.\n  sdestruct => ->; rewrite leCursor_refl; sbazooka.\n+ sdestruct => p'. rewrite -> IHprog1.   rewrite -> IHprog2.\n  sdestruct => H1. sdestruct => H2. rewrite (leCursor_trans H1 H2). sbazooka.\n+ sdestruct => p'. rewrite -> H. sbazooka.\n+ destruct p. destruct q; sdestructs => -> ->; rewrite leCursor_refl; sbazooka.\n  sdestruct => ->; rewrite leCursor_refl; sbazooka.\n+ apply memIsLe.\nQed.\n\nDefinition interpProgramLe p q prog := @interpProgramLeAux prog p q.\n\nGlobal Instance programMemIs : MemIs program := Build_MemIs interpProgramLe.\n\nLemma programMemIsSkip (p q:DWORDCursor) : p -- q :-> prog_skip -|- p = q /\\\\ empSP.\nProof. destruct p => //. destruct q => //=. split. sdestruct => ->. sbazooka.\nsdestruct => H. injection H => ->. sbazooka. destruct q => //=. Qed.\n\nLemma programMemIsInstr p q i : p -- q :-> prog_instr i -|- p -- q :-> i.\nProof. by reflexivity. Qed.\n\nLemma programMemIsData T R W (RT:Roundtrip R W) p q (d:T) : p -- q :-> prog_data _ d -|- p -- q :-> d.\nProof. by simpl. Qed.\n\nLemma programMemIsSeq p q p1 p2 :\n  p -- q :-> prog_seq p1 p2 -|- Exists p':DWORD, p -- p' :-> p1 ** p' -- q :-> p2.\nProof. by simpl. Qed.\n\nLemma programMemIsLabel (p q: DWORDCursor) l :\n  p -- q :-> prog_label l -|- p = q /\\\\ p = l /\\\\ empSP.\nProof. split.\ndestruct p => //. simpl. destruct q => //. sbazooka. congruence. congruence.\nby simpl. sdestructs => -> ->. simpl. sbazooka.\nQed.\n\nLemma programMemIsLocal p q p1 :\n  p -- q :-> prog_declabel p1 -|- Exists L, p -- q :-> (p1 L).\nProof. split => //=. Qed.\n\n(*Require Import bitsops.\nLemma programMemIsAlign (p:DWORD) q m :\n  p -- q :-> align m -|- apart (toNat (negB (lowWithZeroExtend m p))) p q /\\\\ p -- q :-> align m.\nProof. simpl.\nrewrite /readPad. rewrite programMemIsData.\nQed.\n*)\nModule ProgramTactic.\n\n  (* This is identical to prod/pair/fst/snd from the standard library, repeated\n     here to ensure we have full control over the fs and sn names. Then we can\n     safely unfold them with cbv without affecting unrelated user declarations.\n   *)\n  Record pr A B := pa { fs: A; sn: B }.\n\n  (* This helper tactic takes a memIs assertion and returns an unfolded one. *)\n  (* This uses the trick from CPDT in the chapter \"Building a Reification Tactic\n     that Recurses Under Binders\" *)\n  Ltac aux P :=\n    let P := eval cbv [fs sn] in P in\n    match P with\n    | fun (x: ?X) => @?i x -- @?j x :-> (@?p1 x ;; @?p2 x) =>\n        let P1 := aux (fun i'x: pr DWORD X => i (sn i'x) -- fs i'x :-> p1 (sn i'x)) in\n        let P2 := aux (fun i'x: pr DWORD X => fs i'x -- j (sn i'x) :-> p2 (sn i'x)) in\n        constr:(fun (x:X) => Exists i': DWORD, P1 (pa i' x) ** P2 (pa i' x))\n    | fun (x: ?X) => @mkCursor _ (@?i x) -- @mkCursor _ (@?j x) :-> (@?l x :;) =>\n        constr:(fun (x:X) => i x = j x /\\\\ i x = l x /\\\\ empSP)\n\n    | fun (x: ?X) => @?i x -- @?j x :-> (@?l x :;) =>\n        constr:(fun (x:X) => i x = j x /\\\\ i x = l x /\\\\ empSP)\n\n    | fun (x: ?X) => @?i x -- @?j x :-> (prog_instr (@?c x)) =>\n        constr:(fun (x:X) => i x -- j x :-> c x)\n\n    | fun (x: ?X) => @?i x -- @?j x :-> (@prog_data _ _ _ _ (@?c x)) =>\n        constr:(fun (x:X) => i x -- j x :-> c x)\n\n    | fun (x: ?X) => @mkCursor _ (@?i x) -- @mkCursor _ (@?j x) :-> (prog_skip) =>\n        constr:(fun (x:X) => i x = j x /\\\\ empSP)\n\n    | fun (x: ?X) => @?i x -- @?j x :-> (prog_skip) =>\n        constr:(fun (x:X) => i x = j x /\\\\ empSP)\n\n    | fun (x: ?X) => @?i x -- @?j x :-> (prog_declabel (@?body x)) =>\n        let P' := aux (fun lx: pr DWORD X =>\n                      i (sn lx) -- j (sn lx) :-> body (sn lx) (fs lx)) in\n        constr:(fun (x:X) => Exists l, P' (pa l x))\n    | _ => P\n    end.\n\n  Ltac unfold_program :=\n    match goal with\n    | |- context C [ @memIs program _ ?i ?j ?p ] =>\n        let e := aux (fun (_: unit) => @memIs program _ i j p) in\n        let e := eval cbv [fs sn] in (e tt) in\n        let g := context C [e] in\n        change g\n    end.\nEnd ProgramTactic.\n\n(* This tactic essentially just unfolds the definition of interpProgram.\n   Because of typeclass complications, this cannot just be done with standard\n   tactics. *)\nLtac unfold_program := ProgramTactic.unfold_program.\n\n(*\nRequire Import spec spectac reg.\nRequire Import instrsyntax. Open Scope instr_scope.\nExample exampleUnfoldLemma (i j: DWORD) p1  :\n i -- j :-> (LOCAL L;prog_skip;;L:;;p1;;INC EAX;;dd #4) |-- i -- j :-> p1.\nProof.\nunfold_program.\nsdestructs => i1 i2  -> i3 -> -> i4 i5.\nrewrite -> memIsLe. sdestruct => H1.\nrewrite -> memIsLe at 2. sdestruct => H1.\nsbazooka.\nQed.\n*)\n\nLemma programMemIs_entails_memAny (p: program) : forall i j,\n  i -- j :-> p |-- memAny i j.\nProof. induction p => i j.\n+ by apply readerMemIs_entails_memAny.\n+ rewrite -> programMemIsSkip. sdestruct => ->. by apply memAnyEmpty.\n+ rewrite programMemIsSeq. sdestruct => p'. rewrite -> IHp1.\nrewrite -> IHp2. by apply memAnyMerge.\n+ simpl. sdestruct => l. by rewrite -> H.\n  rewrite -> programMemIsLabel.\n  sdestructs => -> H. apply memAnyEmpty.\n+ by apply readerMemIs_entails_memAny.\nQed.\n\nLemma ddApart p q (v:DWORD) : p -- q :-> dd v |-- apart 4 p q /\\\\ p -- q :-> dd v.\nProof. rewrite programMemIsData. apply memIsFixed. Qed.\n\nLemma dbApart p q (v:BYTE) : p -- q :-> db v |-- apart 1 p q /\\\\ p -- q :-> db v.\nProof. rewrite programMemIsData. apply memIsFixed. Qed.\n\nLemma dwApart p q (v:WORD) : p -- q :-> dw v |-- apart 2 p q /\\\\ p -- q :-> dw v.\nProof. rewrite programMemIsData. apply memIsFixed. Qed.\n\nLemma dsApart p q v : p -- q :-> ds v |-- apart (length v) p q /\\\\ p -- q :-> ds v.\nProof. rewrite programMemIsData. apply memIsFixed. Qed.\n\nLemma fixedSizePad n : fixedSizeReader (readPad n) n.\nProof.\ninduction n => //=.\n+ by apply fixedSizeReader_retn.\n+ by apply (fixedSizeReader_bind fixedSizeBYTE).\nQed.\n\nLemma padApart p q n : p -- q :-> pad n |-- apart n p q /\\\\ p -- q :-> pad n.\nProof. rewrite programMemIsData. apply fixedSizePad. Qed.\n\n\nDefinition hasSize n (pr: program) := forall p q, p -- q :-> pr |-- apart n p q /\\\\ p -- q :-> pr.\n\nLemma dbHasSize b : hasSize 1 (db b).\nProof. rewrite /hasSize. move => p q. apply dbApart. Qed.\n\nLemma dwHasSize b : hasSize 2 (dw b).\nProof. rewrite /hasSize. move => p q. apply dwApart. Qed.\n\nLemma ddHasSize b : hasSize 4 (dd b).\nProof. rewrite /hasSize. move => p q. apply ddApart. Qed.\n\nLemma padHasSize n : hasSize n ( pad n).\nProof. rewrite /hasSize. move => p q. apply padApart. Qed.\n\nLemma dsHasSize s : hasSize (length s) (ds s).\nProof. rewrite /hasSize. move => p q. apply dsApart. Qed.\n\nLemma seqHasSize p1 p2 n1 n2 : hasSize n1 p1 -> hasSize n2 p2 -> hasSize (n1+n2) (p1;;p2).\nProof. move => H1 H2 p q. rewrite programMemIsSeq. sdestructs => p'.\nrewrite /hasSize in H1, H2. rewrite -> H1. rewrite -> H2.\nsdestructs => A1 A2.\nhave A := (apart_addn A1 A2). sbazooka.\nQed.\n\nLemma localHasSize n f : (forall L, hasSize n (f L)) -> hasSize n (LOCAL L; f L).\nProof. move => H. rewrite /hasSize. move => p q. rewrite programMemIsLocal.\nsdestruct => L. rewrite /hasSize in H. rewrite -> H. sbazooka.\nQed.\n\nLemma labelHasSize L : hasSize 0 (prog_label L).\nProof. rewrite /hasSize. move => p q. rewrite programMemIsLabel. sbazooka. Qed.\n\n\n\n(*---------------------------------------------------------------------------\n    Structural equivalence on programs, capturing monoidal sequencing and\n    scope extrusion\n  ---------------------------------------------------------------------------*)\nDefinition liftEq T U (eq: T -> T -> Prop) := fun (f g: U -> T) => forall u, eq (f u) (g u).\nInductive progEq : program -> program -> Prop :=\n| progEqRefl:  forall p, progEq p p\n| progEqSym:   forall p1 p2, progEq p1 p2 -> progEq p2 p1\n| progEqTrans: forall p1 p2 p3, progEq p1 p2 -> progEq p2 p3 -> progEq p1 p3\n| progEqDecLabel: forall p q, (liftEq progEq p q) -> progEq (prog_declabel p) (prog_declabel q)\n| progEqSeq:   forall p1 p2 q1 q2, progEq p1 q1 -> progEq p2 q2 -> progEq (prog_seq p1 p2) (prog_seq q1 q2)\n| progEqSeqAssoc: forall p1 p2 p3, progEq (p1;;p2;;p3) ((p1;;p2);;p3)\n| progEqSeqSkip: forall p, progEq (p;;prog_skip) p\n| progEqSkipSeq: forall p, progEq (prog_skip;;p) p\n| progEqSeqDecLabel: forall p f, progEq (p;; prog_declabel f) (prog_declabel (fun l => p;; f l))\n| progEqDecLabelSeq: forall p f, progEq (prog_declabel f;; p) (prog_declabel (fun l => f l;; p))\n| progEqDecLabelSkip: progEq (prog_declabel (fun l => prog_skip)) prog_skip.\n\n(* Add progEq as an instance of Equivalence for rewriting *)\nRequire Import Setoid Morphisms RelationClasses.\nGlobal Instance progEqEqu : Equivalence progEq.\nProof. constructor; red.\n+ apply progEqRefl.\n+ apply progEqSym.\n+ apply progEqTrans.\nQed.\n\n(* Declare morphisms for context rules *)\nGlobal Instance progEq_seq_m:\n  Proper (progEq ==> progEq ==> progEq) prog_seq.\nProof. move => p1 p2 EQ1 q1 q2 EQ2 . by apply progEqSeq. Qed.\n\nGlobal Instance progEq_decLabel_m:\n  Proper (liftEq progEq ==> progEq) prog_declabel.\nProof. move => f1 f2 EQ. by apply progEqDecLabel. Qed.\n\n(* Main lemma: memIs respects progEq *)\nRequire Import septac.\nLemma memIsProgEquiv p1 p2 : progEq p1 p2 -> forall (l l':DWORD), l -- l' :-> p1 -|- l -- l' :-> p2.\nProof. move => EQ. induction EQ => l l'.\n(* progEqRefl *)\n+ done.\n(* progEqSym *)\n+ by rewrite IHEQ.\n(* progEqTrans *)\n+ by rewrite IHEQ1 IHEQ2.\n(* progEqDecLabel *)\n+ unfold_program. unfold_program. split. sdestruct => lab. ssplit. rewrite -> H0. reflexivity.\nsdestruct => lab. ssplit. rewrite <-H0. reflexivity.\n(* progEqSeq *)\n+ unfold_program. unfold_program. split; sdestructs => i. rewrite IHEQ1 IHEQ2; sbazooka.\nrewrite -IHEQ1 -IHEQ2; sbazooka.\n(* progEqSeqAssoc *)\n+ unfold_program. unfold_program. split; sbazooka.\n(* progEqSeqSkip *)\n+ unfold_program. split. sdestructs => i ->. by ssimpl.\n  sbazooka.\n(* progEqSkipSeq *)\n+ unfold_program. split. sdestructs => i' ->. by ssimpl.\n  sbazooka.\n(* progEqSeqDecLabel *)\n+ unfold_program. do 3 rewrite /memIs/=. split; sbazooka.\n(* progEqDecLabelSeq *)\n+ unfold_program. do 3 rewrite /memIs/=. split; sbazooka.\n(* progEqDecLabelSkip *)\n+ unfold_program. unfold_program. split. sdestructs => i ->. sbazooka.\n  apply lexistsR with #0. sbazooka.\nQed.\n\n(* Now declare memIs as a morphism wrt progEq *)\nGlobal Instance memIs_progEq_m (p p': DWORD):\n  Proper (progEq ==> lequiv) (@memIs _ _ p p').\nProof. move => p1 p2 EQ. by apply memIsProgEquiv. Qed.\n", "meta": {"author": "jbj", "repo": "x86proved", "sha": "d314fa6d23c064a2be4bf686ac7da16a591fda01", "save_path": "github-repos/coq/jbj-x86proved", "path": "github-repos/coq/jbj-x86proved/x86proved-d314fa6d23c064a2be4bf686ac7da16a591fda01/src/x86/program.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.23770943289591243}}
{"text": "Require Import Config.\n\nInductive expr {C: yul_config}\n:= FunCall (name: yc_ident) (args: list expr) \n | Ident (name: yc_ident)\n | Const (t: yc_type) (val: yc_value t).\n\nDefinition typename {C: yul_config}: Type := yc_type * yc_ident.\n\nInductive stmt {C: yul_config}\n:= BlockStmt (s: block)\n | FunDef (name: yc_ident) (inputs outputs: list typename) (body: block)\n | VarDef (vars: list typename) (init: option expr)\n | Assign (lhs: list yc_ident) (rhs: expr) \n | If (cond: expr) (body: block)\n | Expr (e: expr)\n | Switch (e: expr) (cases: list case) (default: option block)\n | For (init: block) (cond: expr) (after: block) (body: block)\n | Break\n | Continue\n | Leave\nwith case {C: yul_config} := Case (t: yc_type) (val: yc_value t) (body: block)\nwith block {C: yul_config} := Block (body: list stmt).", "meta": {"author": "formalize", "repo": "coq-yul", "sha": "1433d729982f1b18e381dbfef64df4961e2f30b1", "save_path": "github-repos/coq/formalize-coq-yul", "path": "github-repos/coq/formalize-coq-yul/coq-yul-1433d729982f1b18e381dbfef64df4961e2f30b1/UntypedAST.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2377094328959124}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*          Jacques-Henri Jourdan, INRIA Paris-Rocquencourt            *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation, either version 2 of the License, or  *)\n(*  (at your option) any later version.  This file is also distributed *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Formalization of floating-point numbers, using the Flocq library. *)\n\nRequire Import Axioms.\nRequire Import Coqlib.\nRequire Import Integers.\nRequire Import Fappli_IEEE.\nRequire Import Fappli_IEEE_bits.\nRequire Import Fcore.\nRequire Import Fcalc_round.\nRequire Import Fcalc_bracket.\nRequire Import Fprop_Sterbenz.\nRequire Import Program.\n\nClose Scope R_scope.\n\nDefinition float := binary64. (**r the type of IEE754 doubles *)\n\nModule Float.\n\nDefinition zero: float := B754_zero _ _ false. (**r the float [+0.0] *)\n\nDefinition eq_dec: forall (f1 f2: float), {f1 = f2} + {f1 <> f2}.\nProof.\n  Ltac try_not_eq := try solve [right; congruence].\n  destruct f1 as [| |? []|], f2 as [| |? []|];\n  try destruct b; try destruct b0;\n  try solve [left; auto]; try_not_eq.\n  destruct (positive_eq_dec x x0); try_not_eq;\n    subst; left; f_equal; f_equal; apply proof_irr.\n  destruct (positive_eq_dec x x0); try_not_eq;\n    subst; left; f_equal; f_equal; apply proof_irr.\n  destruct (positive_eq_dec m m0); try_not_eq;\n  destruct (Z_eq_dec e e1); try solve [right; intro H; inv H; congruence];\n  subst; left; rewrite (proof_irr e0 e2); auto.\n  destruct (positive_eq_dec m m0); try_not_eq;\n  destruct (Z_eq_dec e e1); try solve [right; intro H; inv H; congruence];\n  subst; left; rewrite (proof_irr e0 e2); auto.\nDefined.\n\n(* Transform a Nan payload to a quiet Nan payload.\n   This is not part of the IEEE754 standard, but shared between all\n   architectures of Compcert. *)\nProgram Definition transform_quiet_pl (pl:nan_pl 53) : nan_pl 53 :=\n  Pos.lor pl (nat_iter 51 xO xH).\nNext Obligation.\n  destruct pl.\n  simpl. rewrite Z.ltb_lt in *.\n  assert (forall x, S (Fcore_digits.digits2_Pnat x) = Pos.to_nat (Pos.size x)).\n  { induction x0; simpl; auto; rewrite IHx0; zify; omega. }\n  fold (Z.of_nat (S (Fcore_digits.digits2_Pnat (Pos.lor x 2251799813685248)))).\n  rewrite H, positive_nat_Z, Psize_log_inf, <- Zlog2_log_inf in *. clear H.\n  change (Z.pos (Pos.lor x 2251799813685248)) with (Z.lor (Z.pos x) 2251799813685248%Z).\n  rewrite Z.log2_lor by (zify; omega).\n  apply Z.max_case. auto. simpl. omega.\nQed.\n\nLemma nan_payload_fequal:\n  forall prec p1 e1 p2 e2, p1 = p2 -> (exist _ p1 e1:nan_pl prec) = exist _ p2 e2.\nProof.\n  simpl; intros; subst. f_equal. apply Fcore_Zaux.eqbool_irrelevance.\nQed.\n\nLemma lor_idempotent:\n  forall x y, Pos.lor (Pos.lor x y) y = Pos.lor x y.\nProof.\n  induction x; destruct y; simpl; f_equal; auto;\n  induction y; simpl; f_equal; auto.\nQed.\n\nLemma transform_quiet_pl_idempotent:\n  forall pl, transform_quiet_pl (transform_quiet_pl pl) = transform_quiet_pl pl.\nProof.\n  intros []; simpl; intros. apply nan_payload_fequal.\n  simpl. apply lor_idempotent.\nQed.\n\n(** Arithmetic operations *)\n\n(* The Nan payload operations for neg and abs is not part of the IEEE754\n   standard, but shared between all architectures of Compcert. *)\nDefinition neg_pl (s:bool) (pl:nan_pl 53) := (negb s, pl).\nDefinition abs_pl (s:bool) (pl:nan_pl 53) := (false, pl).\n\nDefinition neg: float -> float := b64_opp neg_pl. (**r opposite (change sign) *)\nDefinition abs (x: float): float := (**r absolute value (set sign to [+]) *)\n  match x with\n  | B754_nan s pl => let '(s, pl) := abs_pl s pl in B754_nan _ _ s pl\n  | B754_infinity _ => B754_infinity _ _ false\n  | B754_finite _ m e H => B754_finite _ _ false m e H\n  | B754_zero _ => B754_zero _ _ false\n  end.\n\nDefinition binary_normalize64 (m e:Z) (s:bool): float :=\n  binary_normalize 53 1024 eq_refl eq_refl mode_NE m e s.\n\nDefinition binary_normalize64_correct (m e:Z) (s:bool) :=\n  binary_normalize_correct 53 1024 eq_refl eq_refl mode_NE m e s.\nGlobal Opaque binary_normalize64_correct.\n\nDefinition binary_normalize32 (m e:Z) (s:bool) : binary32 :=\n  binary_normalize 24 128 eq_refl eq_refl mode_NE m e s.\n\nDefinition binary_normalize32_correct (m e:Z) (s:bool) :=\n  binary_normalize_correct 24 128 eq_refl eq_refl mode_NE m e s.\nGlobal Opaque binary_normalize32_correct.\n\n(* The Nan payload operations for single <-> double conversions are not part of\n   the IEEE754 standard, but shared between all architectures of Compcert. *)\nDefinition floatofbinary32_pl (s:bool) (pl:nan_pl 24) : (bool * nan_pl 53).\n  refine (s, transform_quiet_pl (exist _ (Pos.shiftl_nat (proj1_sig pl) 29) _)).\n  abstract (\n    destruct pl; unfold proj1_sig, Pos.shiftl_nat, nat_iter, Fcore_digits.digits2_Pnat;\n    fold (Fcore_digits.digits2_Pnat x);\n    rewrite Z.ltb_lt in *;\n    zify; omega).\nDefined.\n\nDefinition binary32offloat_pl (s:bool) (pl:nan_pl 53) : (bool * nan_pl 24).\n  refine (s, exist _ (Pos.shiftr_nat (proj1_sig (transform_quiet_pl pl)) 29) _).\n  abstract (\n    destruct (transform_quiet_pl pl); unfold proj1_sig, Pos.shiftr_nat, nat_iter;\n    rewrite Z.ltb_lt in *;\n    assert (forall x, Fcore_digits.digits2_Pnat (Pos.div2 x) =\n                      (Fcore_digits.digits2_Pnat x - 1)%nat) by (destruct x0; simpl; zify; omega);\n    rewrite !H, <- !NPeano.Nat.sub_add_distr; zify; omega).\nDefined.\n\nDefinition floatofbinary32 (f: binary32) : float := (**r single precision embedding in double precision *)\n  match f with\n    | B754_nan s pl => let '(s, pl) := floatofbinary32_pl s pl in B754_nan _ _ s pl\n    | B754_infinity s => B754_infinity _ _ s\n    | B754_zero s => B754_zero _ _ s\n    | B754_finite s m e _ =>\n      binary_normalize64 (cond_Zopp s (Zpos m)) e s\n  end.\n\nDefinition binary32offloat (f: float) : binary32 := (**r conversion to single precision *)\n  match f with\n    | B754_nan s pl => let '(s, pl) := binary32offloat_pl s pl in B754_nan _ _ s pl\n    | B754_infinity s => B754_infinity _ _ s\n    | B754_zero s => B754_zero _ _ s\n    | B754_finite s m e _ =>\n      binary_normalize32 (cond_Zopp s (Zpos m)) e s\n  end.\n\nDefinition singleoffloat (f: float): float := (**r conversion to single precision, embedded in double *)\n  floatofbinary32 (binary32offloat f).\n\nDefinition Zoffloat (f:float): option Z := (**r conversion to Z *)\n  match f with\n    | B754_finite s m (Zpos e) _ => Some (cond_Zopp s (Zpos m) * Zpower_pos radix2 e)\n    | B754_finite s m 0 _ => Some (cond_Zopp s (Zpos m))\n    | B754_finite s m (Zneg e) _ => Some (cond_Zopp s (Zpos m / Zpower_pos radix2 e))\n    | B754_zero _ => Some 0\n    | _ => None\n  end.\n\nDefinition intoffloat (f:float): option int := (**r conversion to signed 32-bit int *)\n  match Zoffloat f with\n    | Some n =>\n      if Zle_bool Int.min_signed n && Zle_bool n Int.max_signed then\n        Some (Int.repr n)\n      else\n        None\n    | None => None\n  end.\n\nDefinition intuoffloat (f:float): option int := (**r conversion to unsigned 32-bit int *)\n  match Zoffloat f with\n    | Some n =>\n      if Zle_bool 0 n && Zle_bool n Int.max_unsigned then\n        Some (Int.repr n)\n      else\n        None\n    | None => None\n  end.\n\nDefinition longoffloat (f:float): option int64 := (**r conversion to signed 64-bit int *)\n  match Zoffloat f with\n    | Some n =>\n      if Zle_bool Int64.min_signed n && Zle_bool n Int64.max_signed then\n        Some (Int64.repr n)\n      else\n        None\n    | None => None\n  end.\n\nDefinition longuoffloat (f:float): option int64 := (**r conversion to unsigned 64-bit int *)\n  match Zoffloat f with\n    | Some n =>\n      if Zle_bool 0 n && Zle_bool n Int64.max_unsigned then\n        Some (Int64.repr n)\n      else\n        None\n    | None => None\n  end.\n\n(* Functions used to parse floats *)\nProgram Definition build_from_parsed\n  (prec:Z) (emax:Z) (prec_gt_0 :Prec_gt_0 prec) (Hmax:prec < emax)\n  (base:positive) (intPart:positive) (expPart:Z) :=\n  match expPart return _ with\n    | Z0 =>\n      binary_normalize prec emax prec_gt_0 Hmax mode_NE (Zpos intPart) Z0 false\n    | Zpos p =>\n      binary_normalize prec emax prec_gt_0 Hmax mode_NE ((Zpos intPart) * Zpower_pos (Zpos base) p) Z0 false\n    | Zneg p =>\n      let exp := Zpower_pos (Zpos base) p in\n      match exp return 0 < exp -> _ with\n        | Zneg _ | Z0 => _\n        | Zpos p =>\n          fun _ =>\n          FF2B prec emax _ (proj1 (Bdiv_correct_aux prec emax prec_gt_0 Hmax mode_NE false intPart Z0 false p Z0))\n      end _\n  end.\nNext Obligation.\napply Zpower_pos_gt_0.\nreflexivity.\nQed.\n\nDefinition build_from_parsed64 (base:positive) (intPart:positive) (expPart:Z) : float :=\n  build_from_parsed 53 1024 eq_refl eq_refl  base intPart expPart.\n\nDefinition build_from_parsed32 (base:positive) (intPart:positive) (expPart:Z) : float :=\n  floatofbinary32 (build_from_parsed 24 128 eq_refl eq_refl  base intPart expPart).\n\nDefinition floatofint (n:int): float := (**r conversion from signed 32-bit int *)\n  binary_normalize64 (Int.signed n) 0 false.\nDefinition floatofintu (n:int): float:= (**r conversion from unsigned 32-bit int *)\n  binary_normalize64 (Int.unsigned n) 0 false.\n\nDefinition floatoflong (n:int64): float := (**r conversion from signed 64-bit int *)\n  binary_normalize64 (Int64.signed n) 0 false.\nDefinition floatoflongu (n:int64): float:= (**r conversion from unsigned 64-bit int *)\n  binary_normalize64 (Int64.unsigned n) 0 false.\n\nDefinition singleofint (n:int): float := (**r conversion from signed 32-bit int to single-precision float *)\n  floatofbinary32 (binary_normalize32 (Int.signed n) 0 false).\nDefinition singleofintu (n:int): float:= (**r conversion from unsigned 32-bit int to single-precision float *)\n  floatofbinary32 (binary_normalize32 (Int.unsigned n) 0 false).\n\nDefinition singleoflong (n:int64): float := (**r conversion from signed 64-bit int to single-precision float *)\n  floatofbinary32 (binary_normalize32 (Int64.signed n) 0 false).\nDefinition singleoflongu (n:int64): float:= (**r conversion from unsigned 64-bit int to single-precision float *)\n  floatofbinary32 (binary_normalize32 (Int64.unsigned n) 0 false).\n\n(* The Nan payload operations for two-argument arithmetic operations are not part of\n   the IEEE754 standard, but all architectures of Compcert share a similar\n   NaN behavior, parameterized by:\n- a \"default\" payload which occurs when an operation generates a NaN from\n  non-NaN arguments;\n- a choice function determining which of the payload arguments to choose,\n  when an operation is given two NaN arguments. *)\n\nParameter default_pl : bool*nan_pl 53.\nParameter choose_binop_pl : bool -> nan_pl 53 -> bool -> nan_pl 53 -> bool.\n\nDefinition binop_pl (x y: binary64) : bool*nan_pl 53 :=\n  match x, y with\n  | B754_nan s1 pl1, B754_nan s2 pl2 =>\n      if choose_binop_pl s1 pl1 s2 pl2\n      then (s2, transform_quiet_pl pl2)\n      else (s1, transform_quiet_pl pl1)\n  | B754_nan s1 pl1, _ => (s1, transform_quiet_pl pl1)\n  | _, B754_nan s2 pl2 => (s2, transform_quiet_pl pl2)\n  | _, _ => default_pl\n  end.\n\nDefinition add: float -> float -> float := b64_plus binop_pl mode_NE. (**r addition *)\nDefinition sub: float -> float -> float := b64_minus binop_pl mode_NE. (**r subtraction *)\nDefinition mul: float -> float -> float := b64_mult binop_pl mode_NE. (**r multiplication *)\nDefinition div: float -> float -> float := b64_div binop_pl mode_NE. (**r division *)\n\nDefinition order_float (f1 f2:float): option Datatypes.comparison :=\n  match f1, f2 with\n    | B754_nan _ _,_ | _,B754_nan _ _ => None\n    | B754_infinity true, B754_infinity true\n    | B754_infinity false, B754_infinity false => Some Eq\n    | B754_infinity true, _ => Some Lt\n    | B754_infinity false, _ => Some Gt\n    | _, B754_infinity true => Some Gt\n    | _, B754_infinity false => Some Lt\n    | B754_finite true _ _ _, B754_zero _ => Some Lt\n    | B754_finite false _ _ _, B754_zero _ => Some Gt\n    | B754_zero _, B754_finite true _ _ _ => Some Gt\n    | B754_zero _, B754_finite false _ _ _ => Some Lt\n    | B754_zero _, B754_zero _ => Some Eq\n    | B754_finite s1 m1 e1 _, B754_finite s2 m2 e2 _ =>\n      match s1, s2 with\n        | true, false => Some Lt\n        | false, true => Some Gt\n        | false, false =>\n          match Zcompare e1 e2 with\n            | Lt => Some Lt\n            | Gt => Some Gt\n            | Eq => Some (Pcompare m1 m2 Eq)\n          end\n        | true, true =>\n          match Zcompare e1 e2 with\n            | Lt => Some Gt\n            | Gt => Some Lt\n            | Eq => Some (CompOpp (Pcompare m1 m2 Eq))\n          end\n      end\n  end.\n\nDefinition cmp (c:comparison) (f1 f2:float) : bool := (**r comparison *)\n  match c with\n  | Ceq =>\n      match order_float f1 f2 with Some Eq => true | _ => false end\n  | Cne =>\n      match order_float f1 f2 with Some Eq => false | _ => true end\n  | Clt =>\n      match order_float f1 f2 with Some Lt => true | _ => false end\n  | Cle =>\n      match order_float f1 f2 with Some(Lt|Eq) => true | _ => false end\n  | Cgt =>\n      match order_float f1 f2 with Some Gt => true | _ => false end\n  | Cge =>\n      match order_float f1 f2 with Some(Gt|Eq) => true | _ => false end\n  end.\n\n(** Conversions between floats and their concrete in-memory representation\n    as a sequence of 64 bits (double precision) or 32 bits (single precision). *)\n\nDefinition bits_of_double (f: float): int64 := Int64.repr (bits_of_b64 f).\nDefinition double_of_bits (b: int64): float := b64_of_bits (Int64.unsigned b).\n\nDefinition bits_of_single (f: float) : int := Int.repr (bits_of_b32 (binary32offloat f)).\nDefinition single_of_bits (b: int): float := floatofbinary32 (b32_of_bits (Int.unsigned b)).\n\nDefinition from_words (hi lo: int) : float := double_of_bits (Int64.ofwords hi lo).\n\n(** Below are the only properties of floating-point arithmetic that we\n  rely on in the compiler proof. *)\n\n(** Some tactics **)\n\nLtac compute_this val :=\n  let x := fresh in set val as x in *; vm_compute in x; subst x.\n\nLtac smart_omega :=\n  simpl radix_val in *; simpl Zpower in *;\n  compute_this Int.modulus; compute_this Int.half_modulus;\n  compute_this Int.max_unsigned;\n  compute_this Int.min_signed; compute_this Int.max_signed;\n  compute_this Int64.modulus; compute_this Int64.half_modulus;\n  compute_this Int64.max_unsigned;\n  compute_this (Zpower_pos 2 1024); compute_this (Zpower_pos 2 53); compute_this (Zpower_pos 2 52);\n  zify; omega.\n\nLemma floatofbinary32_exact :\n  forall f, is_finite_strict _ _ f = true ->\n    is_finite_strict _ _ (floatofbinary32 f) = true /\\ B2R _ _ f = B2R _ _ (floatofbinary32 f).\nProof.\n  destruct f as [ | | |s m e]; try discriminate; intro.\n  pose proof (binary_normalize64_correct (cond_Zopp s (Zpos m)) e s).\n  match goal with [H0:if Rlt_bool (Rabs ?x) _ then _ else _ |- _ /\\ ?y = _] => assert (x=y)%R end.\n  apply round_generic; [now apply valid_rnd_round_mode|].\n  apply (generic_inclusion_ln_beta _ (FLT_exp (3 - 128 - 24) 24)).\n  intro; eapply Zle_trans; [apply Zle_max_compat_l | apply Zle_max_compat_r]; omega.\n  apply generic_format_canonic; apply canonic_canonic_mantissa; apply (proj1 (andb_prop _ _ e0)).\n  rewrite H1, Rlt_bool_true in H0; intuition; unfold floatofbinary32, binary_normalize64.\n  match goal with [ |- _ _ _ ?x = true ] => destruct x end; try discriminate.\n  symmetry in H2; apply F2R_eq_0_reg in H2; destruct s; discriminate.\n  reflexivity.\n  eapply Rlt_trans.\n  unfold B2R; rewrite <- F2R_Zabs, abs_cond_Zopp; eapply bounded_lt_emax; now apply e0.\n  now apply bpow_lt.\nQed.\n\nLemma binary32offloatofbinary32_num :\n  forall f, is_nan _ _ f = false ->\n            binary32offloat (floatofbinary32 f) = f.\nProof.\n  intros f Hnan; pose proof (floatofbinary32_exact f); destruct f as [ | | |s m e]; try reflexivity.\n  discriminate.\n  specialize (H eq_refl); destruct H.\n  destruct (floatofbinary32 (B754_finite 24 128 s m e e0)) as [ | | |s1 m1 e1]; try discriminate.\n  unfold binary32offloat.\n  pose proof (binary_normalize32_correct (cond_Zopp s1 (Zpos m1)) e1 s1).\n  unfold B2R at 2 in H0; cbv iota zeta beta in H0; rewrite <- H0, round_generic in H1.\n  rewrite Rlt_bool_true in H1.\n  unfold binary_normalize32.\n  apply B2R_inj; intuition; match goal with [|- _ _ _ ?f = true] => destruct f end; try discriminate.\n  symmetry in H2; apply F2R_eq_0_reg in H2; destruct s; discriminate.\n  reflexivity.\n  unfold B2R; rewrite <- F2R_Zabs, abs_cond_Zopp; eapply bounded_lt_emax; apply e0.\n  now apply valid_rnd_round_mode.\n  now apply generic_format_B2R.\nQed.\n\nLemma floatofbinary32offloatofbinary32_pl:\n  forall s pl,\n    prod_rect (fun _ => _) floatofbinary32_pl (prod_rect (fun _ => _) binary32offloat_pl (floatofbinary32_pl s pl)) = floatofbinary32_pl s pl.\nProof.\n  destruct pl. unfold binary32offloat_pl, floatofbinary32_pl.\n  unfold transform_quiet_pl, proj1_sig. simpl.\n  f_equal. apply nan_payload_fequal.\n  unfold Pos.shiftr_nat. simpl.\n  rewrite !lor_idempotent. reflexivity.\nQed.\n\nLemma floatofbinary32offloatofbinary32 :\n  forall f, floatofbinary32 (binary32offloat (floatofbinary32 f)) = floatofbinary32 f.\nProof.\n  destruct f; try (rewrite binary32offloatofbinary32_num; tauto).\n  unfold floatofbinary32, binary32offloat.\n  rewrite <- floatofbinary32offloatofbinary32_pl at 2.\n  reflexivity.\nQed.\n\nLemma binary32offloatofbinary32offloat_pl:\n  forall s pl,\n    prod_rect (fun _ => _) binary32offloat_pl (prod_rect  (fun _ => _) floatofbinary32_pl (binary32offloat_pl s pl)) = binary32offloat_pl s pl.\nProof.\n  destruct pl. unfold binary32offloat_pl, floatofbinary32_pl. unfold prod_rect.\n  f_equal. apply nan_payload_fequal.\n  rewrite transform_quiet_pl_idempotent.\n  unfold transform_quiet_pl, proj1_sig.\n  change 51 with (29+22).\n  clear - x. revert x. unfold Pos.shiftr_nat, Pos.shiftl_nat.\n  induction (29)%nat. intro. simpl. apply lor_idempotent.\n  intro.\n  rewrite !nat_iter_succ_r with (f:=Pos.div2).\n  destruct x; simpl; try apply IHn.\n  clear IHn. induction n. reflexivity.\n  rewrite !nat_iter_succ_r with (f:=Pos.div2). auto.\nQed.\n\nLemma binary32offloatofbinary32offloat :\n  forall f, binary32offloat (floatofbinary32 (binary32offloat f)) = binary32offloat f.\nProof.\n  destruct f; try (rewrite binary32offloatofbinary32_num; simpl; tauto).\n  unfold floatofbinary32, binary32offloat.\n  rewrite <- binary32offloatofbinary32offloat_pl at 2.\n  reflexivity.\n  rewrite binary32offloatofbinary32_num; simpl. auto.\n  unfold binary_normalize32.\n  pose proof (binary_normalize32_correct (cond_Zopp b (Z.pos m)) e b).\n  destruct binary_normalize; auto. simpl in H.\n  destruct Rlt_bool in H. intuition.\n  unfold binary_overflow in H. destruct n.\n  destruct overflow_to_inf in H; discriminate.\nQed.\n\nTheorem singleoffloat_idem:\n  forall f, singleoffloat (singleoffloat f) = singleoffloat f.\nProof.\n  intros; unfold singleoffloat; rewrite binary32offloatofbinary32offloat; reflexivity.\nQed.\n\nTheorem singleoflong_idem:\n  forall n, singleoffloat (singleoflong n) = singleoflong n.\nProof.\n  intros; unfold singleoffloat, singleoflong. rewrite floatofbinary32offloatofbinary32; reflexivity.\nQed.\n\nTheorem singleoflongu_idem:\n  forall n, singleoffloat (singleoflongu n) = singleoflongu n.\nProof.\n  intros; unfold singleoffloat, singleoflongu. rewrite floatofbinary32offloatofbinary32; reflexivity.\nQed.\n\nDefinition is_single (f: float) : Prop := exists s, f = floatofbinary32 s.\n\nTheorem singleoffloat_is_single:\n  forall f, is_single (singleoffloat f).\nProof.\n  intros. exists (binary32offloat f); auto.\nQed.\n\nTheorem singleoffloat_of_single:\n  forall f, is_single f -> singleoffloat f = f.\nProof.\n  intros. destruct H as [s EQ]. subst f. unfold singleoffloat.\n  apply floatofbinary32offloatofbinary32.\nQed.\n\nTheorem is_single_dec: forall f, {is_single f} + {~is_single f}.\nProof.\n  intros. case (eq_dec (singleoffloat f) f); intros.\n  unfold singleoffloat in e. left. exists (binary32offloat f). auto.\n  right; red; intros; elim n. apply singleoffloat_of_single; auto.\nDefined.\n\n(** Commutativity properties of addition and multiplication. *)\n\nTheorem add_commut:\n  forall x y, is_nan _ _ x = false \\/ is_nan _ _ y = false -> add x y = add y x.\nProof.\n  intros x y NAN. unfold add, b64_plus. \n  pose proof (Bplus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE x y).\n  pose proof (Bplus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE y x).\n  unfold Bplus in *; destruct x; destruct y; auto.\n- rewrite (eqb_sym b0 b). destruct (eqb b b0) eqn:EQB; auto. f_equal; apply eqb_prop; auto.\n- rewrite (eqb_sym b0 b). destruct (eqb b b0) eqn:EQB.\n  f_equal; apply eqb_prop; auto.\n  auto.\n- simpl in NAN; intuition congruence.\n- exploit H; auto. clear H. exploit H0; auto. clear H0. \n  set (x := B754_finite 53 1024 b0 m0 e1 e2). \n  set (rx := B2R 53 1024 x).\n  set (y := B754_finite 53 1024 b m e e0).\n  set (ry := B2R 53 1024 y).\n  rewrite (Rplus_comm ry rx). destruct Rlt_bool. \n  intros (A1 & A2 & A3) (B1 & B2 & B3).\n  apply B2R_Bsign_inj; auto. rewrite <- B1 in A1. auto. \n  rewrite Z.add_comm. rewrite Z.min_comm. auto.\n  intros (A1 & A2) (B1 & B2). apply B2FF_inj. rewrite B2 in B1. rewrite <- B1 in A1. auto. \nQed.\n\nTheorem mul_commut:\n  forall x y, is_nan _ _ x = false \\/ is_nan _ _ y = false -> mul x y = mul y x.\nProof.\n  intros x y NAN. unfold mul, b64_mult. \n  pose proof (Bmult_correct 53 1024 eq_refl eq_refl binop_pl mode_NE x y).\n  pose proof (Bmult_correct 53 1024 eq_refl eq_refl binop_pl mode_NE y x).\n  unfold Bmult in *; destruct x; destruct y; auto.\n- f_equal. apply xorb_comm. \n- f_equal. apply xorb_comm. \n- f_equal. apply xorb_comm. \n- f_equal. apply xorb_comm. \n- simpl in NAN. intuition congruence.\n- f_equal. apply xorb_comm. \n- f_equal. apply xorb_comm. \n- set (x := B754_finite 53 1024 b0 m0 e1 e2) in *. \n  set (rx := B2R 53 1024 x) in *.\n  set (y := B754_finite 53 1024 b m e e0) in *.\n  set (ry := B2R 53 1024 y) in *.\n  rewrite (Rmult_comm ry rx) in *. destruct Rlt_bool. \n  destruct H as (A1 & A2 & A3); destruct H0 as (B1 & B2 & B3).\n  apply B2R_Bsign_inj; auto. rewrite <- B1 in A1. auto. \n  rewrite ! Bsign_FF2B. f_equal. f_equal. apply xorb_comm. apply Pos.mul_comm. apply Z.add_comm.\n  apply B2FF_inj. etransitivity. eapply H. rewrite xorb_comm. auto. \nQed.\n\n(** Properties of comparisons. *)\n\nTheorem order_float_finite_correct:\n  forall f1 f2, is_finite _ _ f1 = true -> is_finite _ _ f2 = true ->\n    match order_float f1 f2 with\n      | Some c => Rcompare (B2R _ _ f1) (B2R _ _ f2) = c\n      | None => False\n    end.\nProof.\n  Ltac apply_Rcompare :=\n    match goal with\n      | [ |- Rcompare _ _ = Lt ] => apply Rcompare_Lt\n      | [ |- Rcompare _ _ = Eq ] => apply Rcompare_Eq\n      | [ |- Rcompare _ _ = Gt ] => apply Rcompare_Gt\n    end.\n  unfold order_float; intros.\n  destruct f1, f2; try discriminate; unfold B2R, F2R, Fnum, Fexp, cond_Zopp;\n    try (replace 0%R with (Z2R 0 * bpow radix2 e)%R by (simpl Z2R; ring);\n         rewrite Rcompare_mult_r by (apply bpow_gt_0); rewrite Rcompare_Z2R).\n  apply_Rcompare; reflexivity.\n  destruct b0; reflexivity.\n  destruct b; reflexivity.\n  clear H H0.\n  apply andb_prop in e0; destruct e0; apply (canonic_canonic_mantissa _ _ false) in H.\n  apply andb_prop in e2; destruct e2; apply (canonic_canonic_mantissa _ _ false) in H1.\n  pose proof (Zcompare_spec e e1); unfold canonic, Fexp in H1, H.\n  assert (forall m1 m2 e1 e2,\n    let x := (Z2R (Zpos m1) * bpow radix2 e1)%R in\n    let y := (Z2R (Zpos m2) * bpow radix2 e2)%R in\n    canonic_exp radix2 (FLT_exp (3-1024-53) 53) x < canonic_exp radix2 (FLT_exp (3-1024-53) 53) y -> (x < y)%R).\n  intros; apply Rnot_le_lt; intro; apply (ln_beta_le radix2) in H5.\n  apply (fexp_monotone 53 1024) in H5; unfold canonic_exp in H4; omega.\n  apply Rmult_gt_0_compat; [apply (Z2R_lt 0); reflexivity|now apply bpow_gt_0].\n  assert (forall m1 m2 e1 e2, (Z2R (- Zpos m1) * bpow radix2 e1 < Z2R (Zpos m2) * bpow radix2 e2)%R).\n  intros; apply (Rlt_trans _ 0%R).\n  replace 0%R with (0*bpow radix2 e0)%R by ring; apply Rmult_lt_compat_r;\n    [apply bpow_gt_0; reflexivity|now apply (Z2R_lt _ 0)].\n  apply Rmult_gt_0_compat; [apply (Z2R_lt 0); reflexivity|now apply bpow_gt_0].\n  destruct b, b0; try (now apply_Rcompare; apply H5); inversion H3;\n    try (apply_Rcompare; apply H4; rewrite H, H1 in H7; assumption);\n    try (apply_Rcompare; do 2 rewrite Z2R_opp, Ropp_mult_distr_l_reverse;\n      apply Ropp_lt_contravar; apply H4; rewrite H, H1 in H7; assumption);\n    rewrite H7, Rcompare_mult_r, Rcompare_Z2R by (apply bpow_gt_0); reflexivity.\nQed.\n\nTheorem cmp_swap:\n  forall c x y, Float.cmp (swap_comparison c) x y = Float.cmp c y x.\nProof.\n  destruct c, x, y; simpl; try destruct b; try destruct b0; try reflexivity;\n  rewrite <- (Zcompare_antisym e e1); destruct (e ?= e1); try reflexivity;\n  change Eq with (CompOpp Eq); rewrite <- (Pcompare_antisym m m0 Eq);\n    simpl; destruct (Pcompare m m0 Eq); reflexivity.\nQed.\n\nTheorem cmp_ne_eq:\n  forall f1 f2, cmp Cne f1 f2 = negb (cmp Ceq f1 f2).\nProof.\n  unfold cmp; intros; destruct (order_float f1 f2) as [ [] | ]; reflexivity.\nQed.\n\nTheorem cmp_lt_eq_false:\n  forall f1 f2, cmp Clt f1 f2 = true -> cmp Ceq f1 f2 = true -> False.\nProof.\n  unfold cmp; intros; destruct (order_float f1 f2) as [ [] | ]; discriminate.\nQed.\n\nTheorem cmp_le_lt_eq:\n  forall f1 f2, cmp Cle f1 f2 = cmp Clt f1 f2 || cmp Ceq f1 f2.\nProof.\n  unfold cmp; intros; destruct (order_float f1 f2) as [ [] | ]; reflexivity.\nQed.\n\nCorollary cmp_gt_eq_false:\n  forall x y, cmp Cgt x y = true -> cmp Ceq x y = true -> False.\nProof.\n  intros; rewrite <- cmp_swap in H; rewrite <- cmp_swap in H0;\n  eapply cmp_lt_eq_false; now eauto.\nQed.\n\nCorollary cmp_ge_gt_eq:\n  forall f1 f2, cmp Cge f1 f2 = cmp Cgt f1 f2 || cmp Ceq f1 f2.\nProof.\n  intros.\n  change Cge with (swap_comparison Cle); change Cgt with (swap_comparison Clt);\n    change Ceq with (swap_comparison Ceq).\n  repeat rewrite cmp_swap.\n  now apply cmp_le_lt_eq.\nQed.\n\nTheorem cmp_lt_gt_false:\n  forall f1 f2, cmp Clt f1 f2 = true -> cmp Cgt f1 f2 = true -> False.\nProof.\n  unfold cmp; intros; destruct (order_float f1 f2) as [ [] | ]; discriminate.\nQed.\n\n(** Properties of conversions to/from in-memory representation.\n  The double-precision conversions are bijective (one-to-one).\n  The single-precision conversions lose precision exactly\n  as described by [singleoffloat] rounding. *)\n\nTheorem double_of_bits_of_double:\n  forall f, double_of_bits (bits_of_double f) = f.\nProof.\n  intros; unfold double_of_bits, bits_of_double, bits_of_b64, b64_of_bits.\n  rewrite Int64.unsigned_repr, binary_float_of_bits_of_binary_float; [reflexivity|].\n  destruct f.\n  simpl; try destruct b; vm_compute; split; congruence.\n  simpl; try destruct b; vm_compute; split; congruence.\n  destruct n as [p Hp].\n  simpl. rewrite Z.ltb_lt in Hp.\n  apply Zlt_succ_le with (m:=52) in Hp.\n  apply Zpower_le with (r:=radix2) in Hp.\n  edestruct Fcore_digits.digits2_Pnat_correct.\n  rewrite Zpower_nat_Z in H0.\n  eapply Z.lt_le_trans in Hp; eauto.\n  unfold join_bits; destruct b.\n  compute_this ((2 ^ 11 + 2047) * 2 ^ 52). smart_omega.\n  compute_this ((0 + 2047) * 2 ^ 52). smart_omega.\n  unfold bits_of_binary_float, join_bits.\n  destruct (andb_prop _ _ e0); apply Zle_bool_imp_le in H0; apply Zeq_bool_eq in H; unfold FLT_exp in H.\n  match goal with [H:Zmax ?x ?y = e|-_] => pose proof (Zle_max_l x y); pose proof (Zle_max_r x y) end.\n  rewrite H, Fcalc_digits.Z_of_nat_S_digits2_Pnat in *.\n  lapply (Fcalc_digits.Zpower_gt_Zdigits radix2 53 (Zpos m)). intro.\n  unfold radix2, radix_val, Zabs in H3.\n  pose proof (Zle_bool_spec (2 ^ 52) (Zpos m)).\n  assert (Zpos m > 0); [vm_compute; exact eq_refl|].\n  compute_this (2^11); compute_this (2^(11-1)).\n  inversion H4; fold (2^52) in *; destruct H6; destruct b; now smart_omega.\n  change Fcalc_digits.radix2 with radix2 in H1; omega.\nQed.\n\nTheorem single_of_bits_of_single:\n  forall f, single_of_bits (bits_of_single f) = singleoffloat f.\nProof.\n  intros; unfold single_of_bits, bits_of_single, bits_of_b32, b32_of_bits.\n  rewrite Int.unsigned_repr, binary_float_of_bits_of_binary_float; [reflexivity|].\n  destruct (binary32offloat f).\n  simpl; try destruct b; vm_compute; split; congruence.\n  simpl; try destruct b; vm_compute; split; congruence.\n  destruct n as [p Hp].\n  simpl. rewrite Z.ltb_lt in Hp.\n  apply Zlt_succ_le with (m:=23) in Hp.\n  apply Zpower_le with (r:=radix2) in Hp.\n  edestruct Fcore_digits.digits2_Pnat_correct.\n  rewrite Zpower_nat_Z in H0.\n  eapply Z.lt_le_trans in Hp; eauto.\n  compute_this (radix2^23).\n  unfold join_bits; destruct b.\n  compute_this ((2 ^ 8 + 255) * 2 ^ 23). smart_omega.\n  compute_this ((0 + 255) * 2 ^ 23). smart_omega.\n  unfold bits_of_binary_float, join_bits.\n  destruct (andb_prop _ _ e0); apply Zle_bool_imp_le in H0; apply Zeq_bool_eq in H.\n  unfold FLT_exp in H.\n  match goal with [H:Zmax ?x ?y = e|-_] => pose proof (Zle_max_l x y); pose proof (Zle_max_r x y) end.\n  rewrite H, Fcalc_digits.Z_of_nat_S_digits2_Pnat in *.\n  lapply (Fcalc_digits.Zpower_gt_Zdigits radix2 24 (Zpos m)). intro.\n  unfold radix2, radix_val, Zabs in H3.\n  pose proof (Zle_bool_spec (2 ^ 23) (Zpos m)).\n  compute_this (2^23); compute_this (2^24); compute_this (2^8); compute_this (2^(8-1)).\n  assert (Zpos m > 0); [exact eq_refl|].\n  inversion H4; destruct b; now smart_omega.\n  change Fcalc_digits.radix2 with radix2 in H1; omega.\nQed.\n\nTheorem bits_of_singleoffloat:\n  forall f, bits_of_single (singleoffloat f) = bits_of_single f.\nProof.\n  intro; unfold singleoffloat, bits_of_single; rewrite binary32offloatofbinary32offloat; reflexivity.\nQed.\n\nTheorem singleoffloat_of_bits:\n  forall b, singleoffloat (single_of_bits b) = single_of_bits b.\nProof.\n  intro; unfold singleoffloat, single_of_bits; rewrite floatofbinary32offloatofbinary32; reflexivity.\nQed.\n\nTheorem single_of_bits_is_single:\n  forall b, is_single (single_of_bits b).\nProof.\n  intros. exists (b32_of_bits (Int.unsigned b)); auto.\nQed.\n\n(** Conversions between floats and unsigned ints can be defined\n  in terms of conversions between floats and signed ints.\n  (Most processors provide only the latter, forcing the compiler\n  to emulate the former.)   *)\n\nDefinition ox8000_0000 := Int.repr Int.half_modulus.  (**r [0x8000_0000] *)\n\nLemma round_exact:\n  forall n, -2^53 < n < 2^53 ->\n    round radix2 (FLT_exp (3 - 1024 - 53) 53)\n      (round_mode mode_NE) (Z2R n) = Z2R n.\nProof.\n  intros; rewrite round_generic; [reflexivity|now apply valid_rnd_round_mode|].\n  apply generic_format_FLT; exists (Float radix2 n 0).\n  unfold F2R, Fnum, Fexp, bpow; rewrite Rmult_1_r; intuition.\n  pose proof (Zabs_spec n); now smart_omega.\nQed.\n\nLemma binary_normalize64_exact:\n  forall n, -2^53 < n < 2^53 ->\n    B2R _ _ (binary_normalize64 n 0 false) = Z2R n /\\\n    is_finite _ _ (binary_normalize64 n 0 false) = true.\nProof.\n  intros; pose proof (binary_normalize64_correct n 0 false).\n  unfold F2R, Fnum, Fexp, bpow in H0; rewrite Rmult_1_r, round_exact, Rlt_bool_true in H0; try now intuition.\n  rewrite <- Z2R_abs; apply Z2R_lt; pose proof (Zabs_spec n); now smart_omega.\nQed.\n\nTheorem floatofintu_floatofint_1:\n  forall x,\n  Int.ltu x ox8000_0000 = true ->\n  floatofintu x = floatofint x.\nProof.\n  unfold floatofintu, floatofint, Int.signed, Int.ltu; intro.\n  change (Int.unsigned ox8000_0000) with Int.half_modulus.\n  destruct (zlt (Int.unsigned x) Int.half_modulus); now intuition.\nQed.\n\nTheorem floatofintu_floatofint_2:\n  forall x,\n  Int.ltu x ox8000_0000 = false ->\n  floatofintu x = add (floatofint (Int.sub x ox8000_0000))\n                      (floatofintu ox8000_0000).\nProof.\n  unfold floatofintu, floatofint, Int.signed, Int.ltu, Int.sub; intros.\n  pose proof (Int.unsigned_range x).\n  compute_this (Int.unsigned ox8000_0000).\n  destruct (zlt (Int.unsigned x) 2147483648); try  discriminate.\n  rewrite Int.unsigned_repr by smart_omega.\n  destruct (zlt ((Int.unsigned x) - 2147483648) Int.half_modulus).\n  unfold add, b64_plus.\n  match goal with [|- _ = Bplus _ _ _ _ _ _ ?x ?y] =>\n    pose proof (Bplus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE x y) end.\n  do 2 rewrite (fun x H => proj1 (binary_normalize64_exact x H)) in H1 by smart_omega.\n  do 2 rewrite (fun x H => proj2 (binary_normalize64_exact x H)) in H1 by smart_omega.\n  rewrite <- Z2R_plus, round_exact in H1 by smart_omega.\n  rewrite Rlt_bool_true in H1;\n    replace (Int.unsigned x - 2147483648 + 2147483648) with (Int.unsigned x) in * by ring.\n  apply B2R_inj.\n  destruct (binary_normalize64_exact (Int.unsigned x)); [now smart_omega|].\n  match goal with [|- _ _ _ ?f = _] => destruct f end; intuition.\n  exfalso; simpl in H2; change 0%R with (Z2R 0) in H2; apply eq_Z2R in H2; omega.\n  try (change (53 ?= 1024) with Lt in H1).  (* for Coq 8.4 *)\n  simpl Zcompare in *.\n  match goal with [|- _ _ _ ?f = _] => destruct f end; intuition.\n  exfalso; simpl in H0; change 0%R with (Z2R 0) in H0; apply eq_Z2R in H0; omega.\n  rewrite (fun x H => proj1 (binary_normalize64_exact x H)) by smart_omega; now intuition.\n  rewrite <- Z2R_Zpower, <- Z2R_abs by omega; apply Z2R_lt;\n    pose proof (Zabs_spec (Int.unsigned x)); now smart_omega.\n  exfalso; now smart_omega.\nQed.\n\nLemma Zoffloat_correct:\n  forall f,\n    match Zoffloat f with\n      | Some n =>\n        is_finite _ _ f = true /\\\n        Z2R n = round radix2 (FIX_exp 0) (round_mode mode_ZR) (B2R _ _ f)\n      | None =>\n        is_finite _ _ f = false\n    end.\nProof.\n  destruct f; try now intuition.\n  simpl B2R. rewrite round_0. now intuition. now apply valid_rnd_round_mode.\n  destruct e. split. reflexivity.\n  rewrite round_generic. symmetry. now apply Rmult_1_r.\n  now apply valid_rnd_round_mode.\n  apply generic_format_FIX. exists (Float radix2 (cond_Zopp b (Zpos m)) 0). split; reflexivity.\n  split; [reflexivity|].\n  rewrite round_generic, Z2R_mult, Z2R_Zpower_pos, <- bpow_powerRZ;\n    [reflexivity|now apply valid_rnd_round_mode|apply generic_format_F2R; discriminate].\n  rewrite (inbetween_float_ZR_sign _ _ _ ((Zpos m) / Zpower_pos radix2 p)\n    (new_location (Zpower_pos radix2 p) (Zpos m mod Zpower_pos radix2 p) loc_Exact)).\n  unfold B2R, F2R, Fnum, Fexp, canonic_exp, bpow, FIX_exp, Zoffloat, radix2, radix_val.\n  pose proof (Rlt_bool_spec (Z2R (cond_Zopp b (Zpos m)) * / Z2R (Zpower_pos 2 p)) 0).\n  inversion H; rewrite <- (Rmult_0_l (bpow radix2 (Zneg p))) in H1.\n  apply Rmult_lt_reg_r in H1. apply (lt_Z2R _ 0) in H1.\n  destruct b; [split; [|ring_simplify];reflexivity|discriminate].\n  now apply bpow_gt_0.\n  apply Rmult_le_reg_r in H1. apply (le_Z2R 0) in H1.\n  destruct b; [destruct H1|split; [|ring_simplify]]; reflexivity.\n  now apply (bpow_gt_0 radix2 (Zneg p)).\n  unfold canonic_exp, FIX_exp; replace 0 with (Zneg p + Zpos p) by apply Zplus_opp_r.\n  apply (inbetween_float_new_location radix2 _ _ _ _ (Zpos p)); [reflexivity|].\n  apply inbetween_Exact; unfold B2R, F2R, Fnum, Fexp; destruct b.\n  rewrite  Rabs_left; [simpl; ring_simplify; reflexivity|].\n  replace 0%R with (0*(bpow radix2 (Zneg p)))%R by ring; apply Rmult_gt_compat_r.\n  now apply bpow_gt_0.\n  apply (Z2R_lt _ 0); reflexivity.\n  apply Rabs_right; replace 0%R with (0*(bpow radix2 (Zneg p)))%R by ring; apply Rgt_ge.\n  apply Rmult_gt_compat_r; [now apply bpow_gt_0|apply (Z2R_lt 0); reflexivity].\nQed.\n\nTheorem intoffloat_correct:\n  forall f,\n    match intoffloat f with\n      | Some n =>\n        is_finite _ _ f = true /\\\n        Z2R (Int.signed n) = round radix2 (FIX_exp 0) (round_mode mode_ZR) (B2R _ _ f)\n      | None =>\n        is_finite _ _ f = false \\/\n        (B2R _ _ f <= Z2R (Zpred Int.min_signed)\\/\n        Z2R (Zsucc Int.max_signed) <= B2R _ _ f)%R\n    end.\nProof.\n  intro; pose proof (Zoffloat_correct f); unfold intoffloat; destruct (Zoffloat f).\n  pose proof (Zle_bool_spec Int.min_signed z); pose proof (Zle_bool_spec z Int.max_signed). \n  compute_this Int.min_signed; compute_this Int.max_signed; destruct H.\n  inversion H0; [inversion H1|].\n  rewrite <- (Int.signed_repr z) in H2 by smart_omega; split; assumption.\n  right; right; eapply Rle_trans; [apply Z2R_le; apply Zlt_le_succ; now apply H6|].\n  rewrite H2, round_ZR_pos.\n  unfold round, scaled_mantissa, canonic_exp, FIX_exp, F2R, Fnum, Fexp; simpl bpow.\n  do 2 rewrite Rmult_1_r; now apply Zfloor_lb.\n  apply Rnot_lt_le; intro; apply Rlt_le in H7; apply (round_le radix2 (FIX_exp 0) (round_mode mode_ZR)) in H7;\n    rewrite <- H2, round_0 in H7; [apply (le_Z2R _ 0) in H7; now smart_omega|now apply valid_rnd_round_mode].\n  right; left; eapply Rle_trans; [|apply (Z2R_le z); simpl; omega].\n  rewrite H2, round_ZR_neg.\n  unfold round, scaled_mantissa, canonic_exp, FIX_exp, F2R, Fnum, Fexp; simpl bpow.\n  do 2 rewrite Rmult_1_r; now apply Zceil_ub.\n  apply Rnot_lt_le; intro; apply Rlt_le in H5; apply (round_le radix2 (FIX_exp 0) (round_mode mode_ZR)) in H5.\n  rewrite <- H2, round_0 in H5; [apply (le_Z2R 0) in H5; omega|now apply valid_rnd_round_mode].\n  left; assumption.\nQed.\n\nTheorem intuoffloat_correct:\n  forall f,\n    match intuoffloat f with\n      | Some n =>\n        is_finite _ _ f = true /\\\n        Z2R (Int.unsigned n) = round radix2 (FIX_exp 0) (round_mode mode_ZR) (B2R _ _ f)\n      | None =>\n        is_finite _ _ f = false \\/\n        (B2R _ _ f <= -1 \\/\n        Z2R (Zsucc Int.max_unsigned) <= B2R _ _ f)%R\n    end.\nProof.\n  intro; pose proof (Zoffloat_correct f); unfold intuoffloat; destruct (Zoffloat f).\n  pose proof (Zle_bool_spec 0 z); pose proof (Zle_bool_spec z Int.max_unsigned).\n  compute_this Int.max_unsigned; destruct H.\n  inversion H0. inversion H1.\n  rewrite <- (Int.unsigned_repr z) in H2 by smart_omega; split; assumption.\n  right; right; eapply Rle_trans; [apply Z2R_le; apply Zlt_le_succ; now apply H6|].\n  rewrite H2, round_ZR_pos.\n  unfold round, scaled_mantissa, canonic_exp, FIX_exp, F2R, Fnum, Fexp; simpl bpow;\n    do 2 rewrite Rmult_1_r; now apply Zfloor_lb.\n  apply Rnot_lt_le; intro; apply Rlt_le in H7; eapply (round_le radix2 (FIX_exp 0) (round_mode mode_ZR)) in H7;\n    rewrite <- H2, round_0 in H7; [apply (le_Z2R _ 0) in H7; now smart_omega|now apply valid_rnd_round_mode].\n  right; left; eapply Rle_trans; [|change (-1)%R with (Z2R (-1)); apply (Z2R_le z); omega].\n  rewrite H2, round_ZR_neg; unfold round, scaled_mantissa, canonic_exp, FIX_exp, F2R, Fnum, Fexp; simpl bpow.\n  do 2 rewrite Rmult_1_r; now apply Zceil_ub.\n  apply Rnot_lt_le; intro; apply Rlt_le in H5; apply (round_le radix2 (FIX_exp 0) (round_mode mode_ZR)) in H5;\n    rewrite <- H2, round_0 in H5; [apply (le_Z2R 0) in H5; omega|now apply valid_rnd_round_mode].\n  left; assumption.\nQed.\n\nLemma intuoffloat_interval:\n  forall f n,\n    intuoffloat f = Some n ->\n    (-1 < B2R _ _ f < Z2R (Zsucc Int.max_unsigned))%R.\nProof.\n  intro; pose proof (intuoffloat_correct f); destruct (intuoffloat f); try discriminate; destruct H.\n  destruct f; try discriminate; intros.\n  simpl B2R; change 0%R with (Z2R 0); change (-1)%R with (Z2R (-1)); split; apply Z2R_lt; reflexivity.\n  pose proof (Int.unsigned_range i).\n  unfold round, scaled_mantissa, B2R, F2R, Fnum, Fexp in H0 |- *; simpl bpow in H0; do 2 rewrite Rmult_1_r in H0;\n    apply eq_Z2R in H0.\n  split; apply Rnot_le_lt; intro.\n  rewrite Ztrunc_ceil in H0;\n    [apply Zceil_le in H3; change (-1)%R with (Z2R (-1)) in H3; rewrite Zceil_Z2R in H3; omega|].\n  eapply Rle_trans; [now apply H3|apply (Z2R_le (-1) 0); discriminate].\n  rewrite Ztrunc_floor in H0; [apply Zfloor_le in H3; rewrite Zfloor_Z2R in H3; now smart_omega|].\n  eapply Rle_trans; [|now apply H3]; apply (Z2R_le 0); discriminate.\nQed.\n\nTheorem intuoffloat_intoffloat_1:\n  forall x n,\n  cmp Clt x (floatofintu ox8000_0000) = true ->\n  intuoffloat x = Some n ->\n  intoffloat x = Some n.\nProof.\n  intros; unfold cmp in H; pose proof (order_float_finite_correct x (floatofintu ox8000_0000)).\n  destruct (order_float x (floatofintu ox8000_0000)); try destruct c; try discriminate.\n  pose proof (intuoffloat_correct x); rewrite H0 in H2; destruct H2.\n  specialize (H1 H2 eq_refl); pose proof (intoffloat_correct x); destruct (intoffloat x).\n  f_equal; rewrite <- (proj2 H4) in H3; apply eq_Z2R in H3.\n  pose proof (eq_refl (Int.repr (Int.unsigned n))); rewrite H3 in H5 at 1.\n  rewrite Int.repr_signed, Int.repr_unsigned in H5; assumption.\n  destruct H4; [rewrite H2 in H4; discriminate|].\n  apply intuoffloat_interval in H0; exfalso; destruct H0, H4.\n  eapply Rlt_le_trans in H0; [|now apply H4]; apply (lt_Z2R (-1)) in H0; discriminate.\n  apply Rcompare_Lt_inv in H1; eapply Rle_lt_trans in H1; [|now apply H4].\n  unfold floatofintu in H1; rewrite (fun x H => proj1 (binary_normalize64_exact x H)) in H1;\n    [apply lt_Z2R in H1; discriminate|split; reflexivity].\nQed.\n\nLemma Zfloor_minus :\n  forall x n, Zfloor(x-Z2R n) = Zfloor(x)-n.\nProof.\n  intros; apply Zfloor_imp; replace (Zfloor x - n + 1) with (Zfloor x + 1 - n) by ring; do 2 rewrite Z2R_minus.\n  split;\n    [apply Rplus_le_compat_r; now apply Zfloor_lb|\n     apply Rplus_lt_compat_r; rewrite Z2R_plus; now apply Zfloor_ub].\nQed.\n\nTheorem intuoffloat_intoffloat_2:\n  forall x n,\n  cmp Clt x (floatofintu ox8000_0000) = false ->\n  intuoffloat x = Some n ->\n  intoffloat (sub x (floatofintu ox8000_0000)) = Some (Int.sub n ox8000_0000).\nProof.\n  assert (B2R _ _ (floatofintu ox8000_0000) = Z2R (Int.unsigned ox8000_0000)).\n  apply (fun x H => proj1 (binary_normalize64_exact x H)); split; reflexivity.\n  intros; unfold cmp in H0; pose proof (order_float_finite_correct x (floatofintu ox8000_0000)).\n  destruct (order_float x (floatofintu ox8000_0000)); try destruct c; try discriminate;\n  pose proof (intuoffloat_correct x); rewrite H1 in H3; destruct H3; specialize (H2 H3 eq_refl).\n  apply Rcompare_Eq_inv in H2; apply B2R_inj in H2.\n  subst x; vm_compute in H1; injection H1; intro; subst n; vm_compute; reflexivity.\n  destruct x; try discriminate H3;\n    [rewrite H in H2; simpl B2R in H2; apply (eq_Z2R 0) in H2; discriminate|reflexivity].\n  reflexivity.\n  rewrite H in H2; apply Rcompare_Gt_inv in H2; pose proof (intuoffloat_interval _ _ H1).\n  unfold sub, b64_minus.\n  exploit (Bminus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE x (floatofintu ox8000_0000)); [assumption|reflexivity|]; intro.\n  rewrite H, round_generic in H6.\n  match goal with [H6:if Rlt_bool ?x ?y then _ else _|-_] =>\n    pose proof (Rlt_bool_spec x y); destruct (Rlt_bool x y) end.\n  destruct H6 as [? []].\n  match goal with [|- _ ?y = _] => pose proof (intoffloat_correct y); destruct (intoffloat y) end.\n  destruct H10.\n  f_equal; rewrite <- (Int.repr_signed i); unfold Int.sub; f_equal; apply eq_Z2R. \n  rewrite Z2R_minus, H11, H4.\n  unfold round, scaled_mantissa, F2R, Fexp, Fnum, round_mode; simpl bpow; repeat rewrite Rmult_1_r;\n    rewrite <- Z2R_minus; f_equal.\n  rewrite (Ztrunc_floor (B2R _ _ x)), <- Zfloor_minus, <- Ztrunc_floor;\n    [f_equal; assumption|apply Rle_0_minus; left; assumption|].\n  left; eapply Rlt_trans; [|now apply H2]; apply (Z2R_lt 0); reflexivity.\n  try (change (0 ?= 53) with Lt in H6,H8).  (* for Coq 8.4 *)\n  try (change (53 ?= 1024) with Lt in H6,H8).  (* for Coq 8.4 *)\n  exfalso; simpl Zcompare in H6, H8; rewrite H6, H8 in H10.\n  destruct H10 as [|[]]; [discriminate|..].\n  eapply Rle_trans in H10; [|apply Rle_0_minus; left; assumption]; apply (le_Z2R 0) in H10; apply H10; reflexivity.\n  eapply Rle_lt_trans in H10; [|apply Rplus_lt_compat_r; now apply (proj2 H5)].\n  rewrite <- Z2R_opp, <- Z2R_plus in H10; apply lt_Z2R in H10; discriminate.\n  exfalso; inversion H7; rewrite Rabs_right in H8.\n  eapply Rle_lt_trans in H8. apply Rle_not_lt in H8; [assumption|apply (bpow_le _ 31); discriminate].\n  change (bpow radix2 31) with (Z2R(Zsucc Int.max_unsigned - Int.unsigned ox8000_0000)); rewrite Z2R_minus.\n  apply Rplus_lt_compat_r; exact (proj2 H5).\n  apply Rle_ge; apply Rle_0_minus; left; assumption.\n  now apply valid_rnd_round_mode.\n  apply Fprop_Sterbenz.sterbenz_aux; [now apply fexp_monotone|now apply generic_format_B2R| |].\n  rewrite <- H; now apply generic_format_B2R.\n  destruct H5; split; left; assumption.\n  now destruct H2.\nQed.\n\n(** Conversions from ints to floats can be defined as bitwise manipulations\n  over the in-memory representation.  This is what the PowerPC port does.\n  The trick is that [from_words 0x4330_0000 x] is the float\n  [2^52 + floatofintu x]. *)\n\nDefinition ox4330_0000 := Int.repr 1127219200.        (**r [0x4330_0000] *)\n\nLemma split_bits_or:\n  forall x,\n  split_bits 52 11 (Int64.unsigned (Int64.ofwords ox4330_0000 x)) = (false, Int.unsigned x, 1075).\nProof.\n  intros.\n  transitivity (split_bits 52 11 (join_bits 52 11 false (Int.unsigned x) 1075)).\n  - f_equal. rewrite Int64.ofwords_add'. reflexivity.\n  - apply split_join_bits.\n    compute; auto.\n    generalize (Int.unsigned_range x).\n    compute_this Int.modulus; compute_this (2^52); omega.\n    compute_this (2^11); omega.\nQed.\n\nLemma from_words_value:\n  forall x,\n    B2R _ _ (from_words ox4330_0000 x) =\n    (bpow radix2 52 + Z2R (Int.unsigned x))%R /\\\n    is_finite _ _ (from_words ox4330_0000 x) = true.\nProof.\n  intros; unfold from_words, double_of_bits, b64_of_bits, binary_float_of_bits.\n  rewrite B2R_FF2B. rewrite is_finite_FF2B.\n  unfold binary_float_of_bits_aux; rewrite split_bits_or; simpl; pose proof (Int.unsigned_range x).\n  destruct (Int.unsigned x + Zpower_pos 2 52) eqn:?.\n  exfalso; now smart_omega.\n  simpl; rewrite <- Heqz;  unfold F2R; simpl.\n  rewrite <- (Z2R_plus 4503599627370496), Rmult_1_r.\n  split; [f_equal; compute_this (Zpower_pos 2 52); ring | reflexivity].\n  assert (Zneg p < 0) by reflexivity.\n  exfalso; now smart_omega.\nQed.\n\nTheorem floatofintu_from_words:\n  forall x,\n  floatofintu x =\n    sub (from_words ox4330_0000 x) (from_words ox4330_0000 Int.zero).\nProof.\n  intros; destruct (Int.eq_dec x Int.zero); [subst; vm_compute; reflexivity|].\n  assert (Int.unsigned x <> 0).\n  intro; destruct n; rewrite <- (Int.repr_unsigned x), H; reflexivity.\n  pose proof (Int.unsigned_range x).\n  pose proof (binary_normalize64_exact (Int.unsigned x)). destruct H1; [smart_omega|].\n  unfold floatofintu, sub, b64_minus.\n  match goal with [|- _ = Bminus _ _ _ _ _ _ ?x ?y] =>\n    pose proof (Bminus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE x y) end.\n  apply (fun f x y => f x y) in H3; try apply (fun x => proj2 (from_words_value x)).\n  do 2 rewrite (fun x => proj1 (from_words_value x)) in H3.\n  rewrite Int.unsigned_zero in H3.\n  replace (bpow radix2 52 + Z2R (Int.unsigned x) -\n    (bpow radix2 52 + Z2R 0))%R with (Z2R (Int.unsigned x)) in H3 by (simpl; ring).\n  rewrite round_exact in H3 by smart_omega.\n  match goal with [H3:if Rlt_bool ?x ?y then _ else _ |- _] =>\n    pose proof (Rlt_bool_spec x y); destruct (Rlt_bool x y) end; destruct H3 as [? []].\n  try (change (53 ?= 1024) with Lt in H3,H5).  (* for Coq 8.4 *)\n  simpl Zcompare in *; apply B2R_inj;\n    try match goal with [H':B2R _ _ ?f = _ , H'':is_finite _ _ ?f = true |- is_finite_strict _ _ ?f = true] => \n      destruct f; [\n        simpl in H'; change 0%R with (Z2R 0) in H'; apply eq_Z2R in H'; now destruct (H (eq_sym H')) | \n        discriminate H'' | discriminate H'' | reflexivity\n      ]\n    end.\n  rewrite H3; assumption.\n  inversion H4; change (bpow radix2 1024) with (Z2R (radix2 ^ 1024)) in H5; rewrite <- Z2R_abs in H5.\n  apply le_Z2R in H5; pose proof (Zabs_spec (Int.unsigned x));\n    exfalso; now smart_omega.\nQed.\n\nLemma ox8000_0000_signed_unsigned:\n  forall x,\n    Int.unsigned (Int.add x ox8000_0000) = Int.signed x + Int.half_modulus.\nProof.\n  intro; unfold Int.signed, Int.add; pose proof (Int.unsigned_range x).\n  destruct (zlt (Int.unsigned x) Int.half_modulus).\n  rewrite Int.unsigned_repr; compute_this (Int.unsigned ox8000_0000); now smart_omega.\n  rewrite (Int.eqm_samerepr _ (Int.unsigned x + -2147483648)).\n  rewrite Int.unsigned_repr; now smart_omega.\n  apply Int.eqm_add; [now apply Int.eqm_refl|exists 1;reflexivity].\nQed.\n\nTheorem floatofint_from_words:\n  forall x,\n  floatofint x =\n    sub (from_words ox4330_0000 (Int.add x ox8000_0000))\n        (from_words ox4330_0000 ox8000_0000).\nProof.\nLocal Transparent Int.repr Int64.repr.\n  intros; destruct (Int.eq_dec x Int.zero); [subst; vm_compute; reflexivity|].\n  assert (Int.signed x <> 0).\n  intro; destruct n; rewrite <- (Int.repr_signed x), H; reflexivity.\n  pose proof (Int.signed_range x).\n  pose proof (binary_normalize64_exact (Int.signed x)); destruct H1; [now smart_omega|].\n  unfold floatofint, sub, b64_minus.\n  match goal with [|- _ = Bminus _ _ _ _ _ _ ?x ?y] =>\n    pose proof (Bminus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE x y) end.\n  apply (fun f x y => f x y) in H3; try apply (fun x => proj2 (from_words_value x)).\n  do 2 rewrite (fun x => proj1 (from_words_value x)) in H3.\n  replace (bpow radix2 52 + Z2R (Int.unsigned (Int.add x ox8000_0000)) -\n    (bpow radix2 52 + Z2R (Int.unsigned ox8000_0000)))%R with (Z2R (Int.signed x)) in H3\n  by (rewrite ox8000_0000_signed_unsigned; rewrite Z2R_plus; simpl; ring).\n  rewrite round_exact in H3 by smart_omega.\n  match goal with [H3:if Rlt_bool ?x ?y then _ else _ |- _] =>\n    pose proof (Rlt_bool_spec x y); destruct (Rlt_bool x y) end; destruct H3 as [? []].\n  try (change (0 ?= 53) with Lt in H3,H5).  (* for Coq 8.4 *)\n  try (change (53 ?= 1024) with Lt in H3,H5).  (* for Coq 8.4 *)\n  simpl Zcompare in *; apply B2R_inj;\n    try match goal with [H':B2R _ _ ?f = _ , H'':is_finite _ _ ?f = true |- is_finite_strict _ _ ?f = true] => \n      destruct f; [\n        simpl in H'; change 0%R with (Z2R 0) in H'; apply eq_Z2R in H'; now destruct (H (eq_sym H')) | \n        discriminate H'' | discriminate H'' | reflexivity\n      ]\n    end.\n  rewrite H3; assumption.\n  inversion H4; unfold bpow in H5; rewrite <- Z2R_abs in H5;\n    apply le_Z2R in H5; pose proof (Zabs_spec (Int.signed x)); exfalso; now smart_omega.\nQed.\n\n(** Conversions from 32-bit integers to single-precision floats can\n  be decomposed into a conversion to a double-precision float,\n  followed by a [singleoffloat] normalization.  No double rounding occurs. *)\n\nLemma is_finite_strict_ge_1:\n  forall (f: binary32),\n  is_finite _ _ f = true ->\n  (1 <= Rabs (B2R _ _ f))%R ->\n  is_finite_strict _ _ f = true.\nProof.\n  intros. destruct f; auto. simpl in H0.\n  change 0%R with (Z2R 0) in H0.\n  change 1%R with (Z2R 1) in H0.\n  rewrite <- Z2R_abs in H0.\n  exploit le_Z2R; eauto.\nQed.\n\nLemma single_float_of_int:\n  forall n,\n  -2^53 < n < 2^53 ->\n  singleoffloat (binary_normalize64 n 0 false) = floatofbinary32 (binary_normalize32 n 0 false).\nProof.\n  intros. unfold singleoffloat. f_equal.\n  assert (EITHER: n = 0 \\/ Z.abs n > 0) by (destruct n; compute; auto).\n  destruct EITHER as [EQ|GT].\n  subst n; reflexivity.\n  exploit binary_normalize64_exact; eauto. intros [A B].\n  destruct (binary_normalize64 n 0 false) as [ | | | s m e] eqn:B64; simpl in *.\n- assert (0 = n) by (apply eq_Z2R; auto). subst n. simpl in GT. omegaContradiction.\n- discriminate.\n- discriminate.\n- set (n1 := cond_Zopp s (Z.pos m)) in *.\n  generalize (binary_normalize32_correct n1 e s).\n  fold (binary_normalize32 n1 e s). intros C.\n  generalize (binary_normalize32_correct n 0 false).\n  fold (binary_normalize32 n 0 false). intros D.\n  assert (A': @F2R radix2 {| Fnum := n; Fexp := 0 |} = Z2R n).\n  { unfold F2R. apply Rmult_1_r. }\n  rewrite A in C. rewrite A' in D.\n  destruct (Rlt_bool\n         (Rabs\n            (round radix2 (FLT_exp (3 - 128 - 24) 24) (round_mode mode_NE)\n               (Z2R n))) (bpow radix2 128)).\n+ destruct C as [C1 [C2 _]]; destruct D as [D1 [D2 _]].\n  assert (1 <= Rabs (round radix2 (FLT_exp (3 - 128 - 24) 24) (round_mode mode_NE) (Z2R n)))%R.\n  { apply abs_round_ge_generic.\n    apply fexp_correct. red. omega.\n    apply valid_rnd_round_mode.\n    apply generic_format_bpow with (e := 0). compute. congruence.\n    rewrite <- Z2R_abs. change 1%R with (Z2R 1). apply Z2R_le. omega. }\n  apply B2R_inj.\n  apply is_finite_strict_ge_1; auto. rewrite C1; auto.\n  apply is_finite_strict_ge_1; auto. rewrite D1; auto.\n  congruence.\n+ apply B2FF_inj. congruence.\nQed.\n\nTheorem singleofint_floatofint:\n  forall n, singleofint n = singleoffloat (floatofint n).\nProof.\n  intros. symmetry. apply single_float_of_int.\n  generalize (Int.signed_range n). smart_omega.\nQed.\n\nTheorem singleofintu_floatofintu:\n  forall n, singleofintu n = singleoffloat (floatofintu n).\nProof.\n  intros. symmetry. apply single_float_of_int.\n  generalize (Int.unsigned_range n). smart_omega.\nQed.\n\nTheorem mul2_add:\n  forall f, add f f = mul f (floatofint (Int.repr 2%Z)).\nProof.\n  intros. unfold add, b64_plus, mul, b64_mult.\n  destruct (is_finite_strict _ _ f) eqn:EQFINST.\n  - assert (EQFIN:is_finite _ _ f = true) by (destruct f; simpl in *; congruence).\n    pose proof (Bplus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE f f EQFIN EQFIN).\n    pose proof (Bmult_correct 53 1024 eq_refl eq_refl binop_pl mode_NE f\n                              (floatofint (Int.repr 2%Z))).\n    rewrite <- double, Rmult_comm in H.\n    replace (B2R 53 1024 (floatofint (Int.repr 2))) with 2%R in H0 by (compute; field).\n    destruct Rlt_bool.\n    + destruct H0 as [? []], H as [? []].\n      rewrite EQFIN in H1.\n      apply B2R_Bsign_inj; auto.\n      etransitivity. apply H. symmetry. apply H0.\n      etransitivity. apply H4. symmetry. etransitivity. apply H2.\n      destruct Bmult; try reflexivity; discriminate.\n      simpl. rewrite xorb_false_r.\n      erewrite <- Rmult_0_l, Rcompare_mult_r.\n      destruct f; try discriminate EQFINST.\n      simpl. unfold F2R.\n      erewrite <- Rmult_0_l, Rcompare_mult_r.\n      rewrite Rcompare_Z2R with (y:=0).\n      destruct b; reflexivity.\n      apply bpow_gt_0.\n      apply (Z2R_lt 0 2). omega.\n    + destruct H.\n      apply B2FF_inj.\n      etransitivity. apply H.\n      symmetry. etransitivity. apply H0.\n      f_equal. destruct Bsign; reflexivity.\n  - destruct f as [[]|[]| |]; try discriminate; try reflexivity.\n    simpl. destruct (choose_binop_pl b n b n); auto.\nQed.\n\nProgram Definition pow2_float (b:bool) (e:Z) (H:-1023 < e < 1023) : float :=\n  B754_finite _ _ b (nat_iter 52 xO xH) (e-52) _.\nNext Obligation.\n  unfold Fappli_IEEE.bounded, canonic_mantissa.\n  rewrite andb_true_iff, Zle_bool_true by omega. split; auto.\n  apply Zeq_bool_true. unfold FLT_exp. simpl Z.of_nat.\n  apply Z.max_case_strong; omega.\nQed.\n\nTheorem mul_div_pow2:\n  forall b e f H H',\n    mul f (pow2_float b e H) = div f (pow2_float b (-e) H').\nProof.\n  intros. unfold mul, b64_mult, div, b64_div.\n  pose proof (Bmult_correct 53 1024 eq_refl eq_refl binop_pl mode_NE f (pow2_float b e H)).\n  pose proof (Bdiv_correct 53 1024 eq_refl eq_refl binop_pl mode_NE f (pow2_float b (-e) H')).\n  lapply H1. clear H1. intro.\n  change (is_finite 53 1024 (pow2_float b e H)) with true in H0.\n  unfold Rdiv in H1.\n  replace (/ B2R 53 1024 (pow2_float b (-e) H'))%R\n    with (B2R 53 1024 (pow2_float b e H)) in H1.\n  destruct (is_finite _ _ f) eqn:EQFIN.\n  - destruct Rlt_bool.\n    + destruct H0 as [? []], H1 as [? []].\n      apply B2R_Bsign_inj; auto.\n      etransitivity. apply H0. symmetry. apply H1.\n      etransitivity. apply H3. destruct Bmult; try discriminate H2; reflexivity.\n      symmetry. etransitivity. apply H5. destruct Bdiv; try discriminate H4; reflexivity.\n      reflexivity.\n    + apply B2FF_inj.\n      etransitivity. apply H0. symmetry. etransitivity. apply H1.\n      reflexivity.\n  - destruct f; try discriminate EQFIN; auto. \n  - simpl.\n    assert ((4503599627370496 * bpow radix2 (e - 52))%R =\n            (/ (4503599627370496 * bpow radix2 (- e - 52)))%R).\n    { etransitivity. symmetry. apply (bpow_plus radix2 52).\n      symmetry. etransitivity. apply f_equal. symmetry. apply (bpow_plus radix2 52).\n      rewrite <- bpow_opp. f_equal. ring. }\n    destruct b. unfold cond_Zopp.\n    rewrite !F2R_Zopp, <- Ropp_inv_permute. f_equal. auto.\n    intro. apply F2R_eq_0_reg in H3. omega.\n    apply H2.\n  - simpl. intro. apply F2R_eq_0_reg in H2.\n    destruct b; simpl in H2; omega.\nQed.\n\nDefinition exact_inverse_mantissa := nat_iter 52 xO xH.\n\nProgram Definition exact_inverse (f: float) : option float :=\n  match f with\n  | B754_finite s m e B =>\n      if peq m exact_inverse_mantissa then\n      if zlt (-1023) (e + 52) then\n      if zlt (e + 52) 1023 then\n        Some(B754_finite _ _ s m (-e - 104) _)\n      else None else None else None\n  | _ => None\n  end.\nNext Obligation.\n  unfold Fappli_IEEE.bounded, canonic_mantissa. apply andb_true_iff; split.\n  simpl Z.of_nat. apply Zeq_bool_true. unfold FLT_exp. apply Z.max_case_strong; omega.\n  apply Zle_bool_true. omega.  \nQed.\n\nRemark B754_finite_eq:\n  forall s1 m1 e1 B1 s2 m2 e2 B2,\n  s1 = s2 -> m1 = m2 -> e1 = e2 ->\n  B754_finite _ _ s1 m1 e1 B1 = (B754_finite _ _ s2 m2 e2 B2 : float).\nProof.\n  intros. subst. f_equal. apply proof_irrelevance. \nQed.\n\nTheorem div_mul_inverse:\n  forall x y z, exact_inverse y = Some z -> div x y = mul x z.\nProof with (try discriminate).\n  unfold exact_inverse; intros. destruct y...\n  destruct (peq m exact_inverse_mantissa)...\n  destruct (zlt (-1023) (e + 52))...\n  destruct (zlt (e + 52) 1023)...\n  inv H.\n  set (n := - e - 52).\n  assert (RNG1: -1023 < n < 1023) by (unfold n; omega).\n  assert (RNG2: -1023 < -n < 1023) by (unfold n; omega).\n  symmetry. \n  transitivity (mul x (pow2_float b n RNG1)).\n  f_equal. apply B754_finite_eq; auto. unfold n; omega.\n  transitivity (div x (pow2_float b (-n) RNG2)).\n  apply mul_div_pow2. \n  f_equal. apply B754_finite_eq; auto. unfold n; omega.\nQed.\n\nGlobal Opaque\n  zero eq_dec neg abs singleoffloat intoffloat intuoffloat floatofint floatofintu\n  add sub mul div cmp bits_of_double double_of_bits bits_of_single single_of_bits from_words.\n\nEnd Float.\n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/lib/Floats.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2377094328959124}}
{"text": "Require Import Framework File FileDiskLayer FileDiskNoninterference FileDiskRefinement.\nRequire Import FunctionalExtensionality Lia Language SameRetType TSCommon InodeTS.\n\n\nTheorem Termination_Sensitive_create:\n  forall u u' m own ex,\n    Termination_Sensitive\n      u (create own) (create own) recover\n      AD_valid_state (AD_related_states u' ex)\n      (authenticated_disk_reboot_list m).\nProof.\n  unfold Termination_Sensitive, AD_valid_state,\n  AD_related_states, FD_valid_state, FD_related_states,\n  refines_valid, refines_related,\n  authenticated_disk_reboot_list, \n  create;\n  intros; \n  unfold refines, files_rep in *; cleanup; simpl in *.\n  destruct m; simpl in *.\n  {(**create finished **)\n   invert_exec.\n   repeat invert_step;\n   eapply lift2_invert_exec in H10; cleanup.\n   {\n    unfold refines, files_rep in *; cleanup.\n     eapply_fresh TS_alloc_inode in H6; eauto.\n     2: setoid_rewrite H8; eauto.\n     2: setoid_rewrite H3; eauto.\n     cleanup.\n     destruct x2; simpl in *; try solve [intuition congruence].\n    eapply_fresh Inode.alloc_finished_oracle_eq in H6; eauto.\n    destruct o; simpl in *; try solve [intuition congruence].\n\n    destruct s2.\n    eexists; econstructor_recovery.\n    econstructor.\n    eapply lift2_exec_step; eauto.\n    simpl; repeat exec_step.\n   }\n   {\n    unfold refines, files_rep in *; cleanup.\n    eapply_fresh TS_alloc_inode in H6; eauto.\n    2: setoid_rewrite H8; eauto.\n    2: setoid_rewrite H3; eauto.\n    cleanup.\n    destruct x2; simpl in *; try solve [intuition congruence].\n   eapply_fresh Inode.alloc_finished_oracle_eq in H6; eauto.\n   destruct o; simpl in *; try solve [intuition congruence].\n\n   destruct s2.\n   eexists; econstructor_recovery.\n   econstructor.\n   eapply lift2_exec_step; eauto.\n   simpl; repeat exec_step.\n   }\n  }\n  {\n    repeat invert_exec.\n    repeat invert_step_crash.\n    {\n      unfold refines, files_rep in *; logic_clean.\n    eapply lift2_invert_exec in H10; logic_clean.\n    eapply_fresh TS_alloc_inode with (v':= own) in H10; eauto.\n    logic_clean.\n    destruct x2; simpl in *; try solve [intuition congruence].\n   eapply_fresh Inode.alloc_finished_oracle_eq in H10; eauto.\n\n   unfold files_inner_rep in *; logic_clean.\n   eapply_fresh Inode.alloc_finished in H10; eauto.\n   eapply_fresh Inode.alloc_finished in H11; eauto.\n   cleanup; repeat split_ors; cleanup; try solve [intuition congruence].\n   {\n    repeat invert_step_crash.\n    destruct s2, s2.\n    match goal with\n        [H1: same_for_user_except _ _ ?x ?x0,\n        A : recovery_exec' _ _ _ _ _ _ _ |- _] =>  \n          eapply Termination_Sensitive_recover in A;\n          try instantiate (1:= (s0, (_, (fst (snd s), fst (snd s))))) in A;\n          unfold AD_valid_state, refines_valid, FD_valid_state; \n          intros; eauto\n     end.\n     edestruct H15.\n     2: { \n       eexists; econstructor_recovery; [|eauto]; eauto.\n       econstructor.\n       eapply lift2_exec_step; eauto.\n       simpl; repeat exec_step.\n       simpl in *; eauto.\n    }\n    {\n      simpl in *.\n       instantiate (1:= ex).\n       unfold AD_related_states, refines_related,\n       FD_related_states in *; simpl;\n       unfold refines, files_rep, files_crash_rep in *; simpl.\n       do 2 eexists; split.\n      split; eauto.\n      split; eauto.\n      unfold files_inner_rep; eexists; split; eauto.\n      eexists; split; eauto.\n      eapply DiskAllocator.block_allocator_rep_inbounds_eq.\n      apply b0.\n      intros; repeat solve_bounds.\n      instantiate (1:= Mem.upd x x7 {| owner:= own; blocks := []|}).\n      \n      {\n        unfold file_map_rep in *; cleanup; split.\n        {\n          unfold addrs_match_exactly in *; intros.\n          destruct (addr_dec a1 x7); subst.\n          repeat rewrite Mem.upd_eq; eauto.\n          intuition congruence.\n          repeat rewrite Mem.upd_ne; eauto.\n        }\n        {\n          intros.\n          destruct (addr_dec inum x7); subst.\n          {\n          rewrite Mem.upd_eq in H1, H5; eauto.\n          cleanup.\n          unfold file_rep; simpl; intuition eauto.\n          assert (i1 < @length addr []). {\n          eapply nth_error_Some; eauto.\n          congruence.\n          }\n          simpl in *; lia.\n          }\n          {\n            rewrite Mem.upd_ne in H1, H5; eauto.\n          }\n        }\n      }\n      split.\n      split; eauto.\n      split; eauto.\n      {\n        unfold files_inner_rep; eexists; split; eauto.\n      eexists; split; eauto.\n      eapply DiskAllocator.block_allocator_rep_inbounds_eq.\n      apply b.\n      intros; repeat solve_bounds.\n        instantiate (1:= Mem.upd x0 x6 {| owner:= own; blocks := []|}).\n        unfold file_map_rep in *; cleanup; split.\n        {\n          unfold addrs_match_exactly in *; intros.\n          destruct (addr_dec a1 x6); subst.\n          repeat rewrite Mem.upd_eq; eauto.\n          intuition congruence.\n          repeat rewrite Mem.upd_ne; eauto.\n        }\n        {\n          intros.\n          destruct (addr_dec inum x6); subst.\n          {\n          rewrite Mem.upd_eq in H1, H5; eauto.\n          cleanup.\n          unfold file_rep; simpl; intuition eauto.\n          assert (i1 < @length addr []). {\n          eapply nth_error_Some; eauto.\n          congruence.\n          }\n          simpl in *; lia.\n          }\n          {\n            rewrite Mem.upd_ne in H1, H5; eauto.\n          }\n        }\n      }\n      {\n        unfold same_for_user_except in *; cleanup.\n        assert (x6 = x7). {\n          eapply FileInnerSpecs.inode_missing_then_file_missing in H23; eauto.\n          eapply FileInnerSpecs.inode_missing_then_file_missing in H14; eauto.\n          destruct (Compare_dec.lt_dec x6 x7).\n          {\n            exfalso; eapply H25; eauto.\n            edestruct a.\n            destruct_fresh (x3 x6); eauto.\n            eapply FileInnerSpecs.inode_exists_then_file_exists in D; eauto; cleanup.\n            exfalso; eapply H1; eauto.\n            congruence.\n          }\n          {\n            apply PeanoNat.Nat.nlt_ge in n.\n            inversion n; eauto.\n            exfalso; eapply H21 with (i:=x7).\n            lia.\n            edestruct a.\n            destruct_fresh (x2 x7); eauto.\n            eapply FileInnerSpecs.inode_exists_then_file_exists in D; eauto; cleanup.\n            exfalso; eapply H8; eauto.\n            congruence.\n          }\n        }\n        subst.\n        split.\n        {\n          unfold addrs_match_exactly in *; intros.\n          destruct (addr_dec a1 x7); subst.\n          repeat rewrite Mem.upd_eq; eauto.\n          intuition congruence.\n          repeat rewrite Mem.upd_ne; eauto.\n        }\n        split; intros.\n        {\n          destruct (addr_dec inum x7); subst.\n          {\n          rewrite Mem.upd_eq in H5, H4; eauto.\n          cleanup.\n          simpl; intuition eauto.\n          }\n          {\n            rewrite Mem.upd_ne in H5, H4; eauto.\n          }\n        }\n        {\n          destruct (addr_dec inum x7); subst.\n          {\n          rewrite Mem.upd_eq in H4, H1; eauto.\n          cleanup.\n          simpl; intuition eauto.\n          }\n          {\n            rewrite Mem.upd_ne in H4, H1; eauto.\n          }\n        }\n      }\n    }\n    {\n    repeat invert_step_crash.\n    destruct s2, s2.\n    match goal with\n        [H1: same_for_user_except _ _ ?x ?x0,\n        A : recovery_exec' _ _ _ _ _ _ _ |- _] =>  \n          eapply Termination_Sensitive_recover in A;\n          try instantiate (1:= (s0, (_, (snd (snd s), snd (snd s))))) in A;\n          unfold AD_valid_state, refines_valid, FD_valid_state; \n          intros; eauto\n     end.\n     edestruct H15.\n     2: { \n       eexists; econstructor_recovery; [|eauto]; eauto.\n       econstructor.\n       eapply lift2_exec_step; eauto.\n       simpl; repeat exec_step.\n       rewrite cons_app;\n       eapply ExecBindCrash; \n       repeat econstructor.\n       simpl in *; eauto.\n    }\n    {\n      simpl in *.\n       instantiate (1:= ex).\n       unfold AD_related_states, refines_related,\n       FD_related_states in *; simpl;\n       unfold refines, files_rep, files_crash_rep in *; simpl.\n       do 2 eexists; intuition eauto.\n      unfold files_inner_rep; eexists; split; eauto.\n      repeat cleanup_pairs.\n      unfold files_inner_rep; eexists; split; eauto.\n    }\n  }\n  {\n    repeat invert_step_crash.\n    destruct s2, s2.\n    match goal with\n        [H1: same_for_user_except _ _ ?x ?x0,\n        A : recovery_exec' _ _ _ _ _ _ _ |- _] =>  \n          eapply Termination_Sensitive_recover in A;\n          try instantiate (1:= (s0, (_, (fst (snd s), fst (snd s))))) in A;\n          unfold AD_valid_state, refines_valid, FD_valid_state; \n          intros; eauto\n     end.\n     edestruct H15.\n     2: { \n       eexists; econstructor_recovery; [|eauto]; eauto.\n       econstructor.\n       eapply lift2_exec_step; eauto.\n       simpl; repeat exec_step.\n       rewrite cons_app;\n       eapply ExecBindCrash;\n       repeat econstructor.\n       simpl in *; eauto.\n    }\n    {\n      simpl in *.\n       instantiate (1:= ex).\n       unfold AD_related_states, refines_related,\n       FD_related_states in *; simpl;\n       unfold refines, files_rep, files_crash_rep in *; simpl.\n       do 2 eexists; split.\n      split; eauto.\n      split; eauto.\n      unfold files_inner_rep; eexists; split; eauto.\n      eexists; split; eauto.\n      eapply DiskAllocator.block_allocator_rep_inbounds_eq.\n      apply b0.\n      intros; repeat solve_bounds.\n      instantiate (1:= Mem.upd x x7 {| owner:= own; blocks := []|}).\n      \n      {\n        unfold file_map_rep in *; cleanup; split.\n        {\n          unfold addrs_match_exactly in *; intros.\n          destruct (addr_dec a1 x7); subst.\n          repeat rewrite Mem.upd_eq; eauto.\n          intuition congruence.\n          repeat rewrite Mem.upd_ne; eauto.\n        }\n        {\n          intros.\n          destruct (addr_dec inum x7); subst.\n          {\n          rewrite Mem.upd_eq in H1, H5; eauto.\n          cleanup.\n          unfold file_rep; simpl; intuition eauto.\n          assert (i1 < @length addr []). {\n          eapply nth_error_Some; eauto.\n          congruence.\n          }\n          simpl in *; lia.\n          }\n          {\n            rewrite Mem.upd_ne in H1, H5; eauto.\n          }\n        }\n      }\n      split.\n      split; eauto.\n      split; eauto.\n      {\n        unfold files_inner_rep; eexists; split; eauto.\n      eexists; split; eauto.\n      eapply DiskAllocator.block_allocator_rep_inbounds_eq.\n      apply b.\n      intros; repeat solve_bounds.\n        instantiate (1:= Mem.upd x0 x6 {| owner:= own; blocks := []|}).\n        unfold file_map_rep in *; cleanup; split.\n        {\n          unfold addrs_match_exactly in *; intros.\n          destruct (addr_dec a1 x6); subst.\n          repeat rewrite Mem.upd_eq; eauto.\n          intuition congruence.\n          repeat rewrite Mem.upd_ne; eauto.\n        }\n        {\n          intros.\n          destruct (addr_dec inum x6); subst.\n          {\n          rewrite Mem.upd_eq in H1, H5; eauto.\n          cleanup.\n          unfold file_rep; simpl; intuition eauto.\n          assert (i1 < @length addr []). {\n          eapply nth_error_Some; eauto.\n          congruence.\n          }\n          simpl in *; lia.\n          }\n          {\n            rewrite Mem.upd_ne in H1, H5; eauto.\n          }\n        }\n      }\n      {\n        unfold same_for_user_except in *; cleanup.\n        assert (x6 = x7). {\n          eapply FileInnerSpecs.inode_missing_then_file_missing in H23; eauto.\n          eapply FileInnerSpecs.inode_missing_then_file_missing in H14; eauto.\n          destruct (Compare_dec.lt_dec x6 x7).\n          {\n            exfalso; eapply H25; eauto.\n            edestruct a.\n            destruct_fresh (x3 x6); eauto.\n            eapply FileInnerSpecs.inode_exists_then_file_exists in D; eauto; cleanup.\n            exfalso; eapply H1; eauto.\n            congruence.\n          }\n          {\n            apply PeanoNat.Nat.nlt_ge in n.\n            inversion n; eauto.\n            exfalso; eapply H21 with (i:=x7).\n            lia.\n            edestruct a.\n            destruct_fresh (x2 x7); eauto.\n            eapply FileInnerSpecs.inode_exists_then_file_exists in D; eauto; cleanup.\n            exfalso; eapply H8; eauto.\n            congruence.\n          }\n        }\n        subst.\n        split.\n        {\n          unfold addrs_match_exactly in *; intros.\n          destruct (addr_dec a1 x7); subst.\n          repeat rewrite Mem.upd_eq; eauto.\n          intuition congruence.\n          repeat rewrite Mem.upd_ne; eauto.\n        }\n        split; intros.\n        {\n          destruct (addr_dec inum x7); subst.\n          {\n          rewrite Mem.upd_eq in H5, H4; eauto.\n          cleanup.\n          simpl; intuition eauto.\n          }\n          {\n            rewrite Mem.upd_ne in H5, H4; eauto.\n          }\n        }\n        {\n          destruct (addr_dec inum x7); subst.\n          {\n          rewrite Mem.upd_eq in H4, H1; eauto.\n          cleanup.\n          simpl; intuition eauto.\n          }\n          {\n            rewrite Mem.upd_ne in H4, H1; eauto.\n          }\n        }\n      }\n    }\n  }\n}\n{\n    repeat invert_step_crash.\n    {\n    destruct s2, s2.\n    match goal with\n        [H1: same_for_user_except _ _ ?x ?x0,\n        A : recovery_exec' _ _ _ _ _ _ _ |- _] =>  \n          eapply Termination_Sensitive_recover in A;\n          try instantiate (1:= (s0, (_, (snd (snd s), snd (snd s))))) in A;\n          unfold AD_valid_state, refines_valid, FD_valid_state; \n          intros; eauto\n     end.\n     edestruct H15.\n     2: { \n       eexists; econstructor_recovery; [|eauto]; eauto.\n       econstructor.\n       eapply lift2_exec_step; eauto.\n       simpl; repeat exec_step.\n       simpl in *; eauto.\n    }\n    {\n      simpl in *.\n       instantiate (1:= ex).\n       unfold AD_related_states, refines_related,\n       FD_related_states in *; simpl;\n       unfold refines, files_rep, files_crash_rep in *; simpl.\n       do 2 eexists; intuition eauto.\n      unfold files_inner_rep; eexists; split; eauto.\n      repeat cleanup_pairs.\n      unfold files_inner_rep; eexists; split; eauto.\n    }\n  }\n  {\n    destruct s2, s2.\n    match goal with\n        [H1: same_for_user_except _ _ ?x ?x0,\n        A : recovery_exec' _ _ _ _ _ _ _ |- _] =>  \n          eapply Termination_Sensitive_recover in A;\n          try instantiate (1:= (s0, (_, (snd (snd s), snd (snd s))))) in A;\n          unfold AD_valid_state, refines_valid, FD_valid_state; \n          intros; eauto\n     end.\n     edestruct H15.\n     2: { \n       eexists; econstructor_recovery; [|eauto]; eauto.\n       econstructor.\n       eapply lift2_exec_step; eauto.\n       simpl; repeat exec_step.\n       rewrite cons_app;\n       eapply ExecBindCrash;\n       repeat constructor.\n       simpl in *; eauto.\n    }\n    {\n      simpl in *.\n       instantiate (1:= ex).\n       unfold AD_related_states, refines_related,\n       FD_related_states in *; simpl;\n       unfold refines, files_rep, files_crash_rep in *; simpl.\n       do 2 eexists; intuition eauto.\n      unfold files_inner_rep; eexists; split; eauto.\n      repeat cleanup_pairs.\n      unfold files_inner_rep; eexists; split; eauto.\n    }\n  }\n}\n    }\n    {\n      eapply lift2_invert_exec_crashed in H9; cleanup.\n      unfold refines, files_rep in *; cleanup.\n     eapply_fresh TS_alloc_inode in H6; eauto.\n     2: setoid_rewrite H8; eauto.\n     2: setoid_rewrite H3; eauto.\n     cleanup.\n     destruct x2; simpl in *; try solve [intuition congruence].\n     eapply_fresh Inode.alloc_crashed in H6; eauto.\n     eapply_fresh Inode.alloc_crashed in H10; eauto.\n     destruct s2, s2.\n     match goal with\n        [H1: same_for_user_except _ _ ?x ?x0,\n        A : recovery_exec' _ _ _ _ _ _ _ |- _] =>  \n          eapply Termination_Sensitive_recover in A;\n          try instantiate (1:= (s0, (_, (snd (snd s), snd (snd s))))) in A;\n          unfold AD_valid_state, refines_valid, FD_valid_state; \n          intros; eauto\n     end.\n     edestruct H15.\n     2: { \n       eexists; econstructor_recovery; [|eauto]; eauto.\n       repeat rewrite <- app_assoc.\n       eapply ExecBindCrash.\n       eapply lift2_exec_step_crashed; eauto.\n       simpl in *; eauto.\n    }\n    {\n      repeat cleanup_pairs.\n      simpl in *.\n       instantiate (1:= ex).\n       unfold AD_related_states, refines_related,\n       FD_related_states in *; simpl;\n       unfold refines, files_rep, files_crash_rep in *; simpl.\n       do 2 eexists; intuition eauto.\n    }\n  }\n  }\nUnshelve.\nall: eauto.\nall: exact AD.\nQed.", "meta": {"author": "Atalay-Ileri", "repo": "ConFrm", "sha": "80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf", "save_path": "github-repos/coq/Atalay-Ileri-ConFrm", "path": "github-repos/coq/Atalay-Ileri-ConFrm/ConFrm-80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf/Storage/TerminationSensivitiy/FD_TS/TSCreate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.23770661912266916}}
{"text": "From stlc Require Export lang.\n\nInductive type :=\n  | TUnit : type\n  | TProd : type → type → type\n  | TSum : type → type → type\n  | TArrow : type → type → type\n  | TRec (τ : {bind 1 of type})\n  | TVar (x : var).\n\nInstance Ids_type : Ids type. derive. Defined.\nInstance Rename_type : Rename type. derive. Defined.\nInstance Subst_type : Subst type. derive. Defined.\nInstance SubstLemmas_typer : SubstLemmas type. derive. Qed.\n\nReserved Notation \"Γ ⊢ₜ e : τ\" (at level 74, e, τ at next level).\n\nInductive typed (Γ : list type) : expr → type → Prop :=\n  | Var_typedx x τ : Γ !! x = Some τ → Γ ⊢ₜ Var x : τ\n  | Unit_typed : Γ ⊢ₜ Unit : TUnit\n  | Pair_typed e1 e2 τ1 τ2 :\n     Γ ⊢ₜ e1 : τ1 → Γ ⊢ₜ e2 : τ2 → Γ ⊢ₜ Pair e1 e2 : TProd τ1 τ2\n  | Fst_typed e τ1 τ2 : Γ ⊢ₜ e : TProd τ1 τ2 → Γ ⊢ₜ Fst e : τ1\n  | Snd_typed e τ1 τ2 : Γ ⊢ₜ e : TProd τ1 τ2 → Γ ⊢ₜ Snd e : τ2\n  | InjL_typed e τ1 τ2 : Γ ⊢ₜ e : τ1 → Γ ⊢ₜ InjL e : TSum τ1 τ2\n  | InjR_typed e τ1 τ2 : Γ ⊢ₜ e : τ2 → Γ ⊢ₜ InjR e : TSum τ1 τ2\n  | Case_typed e0 e1 e2 τ1 τ2 ρ :\n     Γ ⊢ₜ e0 : TSum τ1 τ2 → τ1 :: Γ ⊢ₜ e1 : ρ → τ2 :: Γ ⊢ₜ e2 : ρ →\n     Γ ⊢ₜ Case e0 e1 e2 : ρ\n  | Lam_typed e τ1 τ2 : τ1 :: Γ ⊢ₜ e : τ2 → Γ ⊢ₜ Lam e : TArrow τ1 τ2\n  | App_typed e1 e2 τ1 τ2 :\n      Γ ⊢ₜ e1 : TArrow τ1 τ2 → Γ ⊢ₜ e2 : τ1 → Γ ⊢ₜ App e1 e2 : τ2\n  | Rec_typed e τ1 τ2 :\n      TArrow τ1 τ2 :: τ1 :: Γ ⊢ₜ e : τ2 → Γ ⊢ₜ Rec e : TArrow τ1 τ2\n  | TFold e τ : Γ ⊢ₜ e : τ.[TRec τ/] → Γ ⊢ₜ Fold e : TRec τ\n  | TUnfold e τ : Γ ⊢ₜ e : TRec τ → Γ ⊢ₜ Unfold e : τ.[TRec τ/]\nwhere \"Γ ⊢ₜ e : τ\" := (typed Γ e τ).\n\nLemma typed_subst_invariant Γ e τ s1 s2 :\n  Γ ⊢ₜ e : τ → (∀ x, x < length Γ → s1 x = s2 x) → e.[s1] = e.[s2].\nProof.\n  intros Htyped; revert s1 s2.\n  assert (∀ {A} `{Ids A} `{Rename A} (s1 s2 : nat → A) x,\n    (x ≠ 0 → s1 (pred x) = s2 (pred x)) → up s1 x = up s2 x).\n  { intros A H1 H2. rewrite /up=> s1 s2 [|x] //=; auto with f_equal lia. }\n  induction Htyped => s1 s2 Hs; f_equal/=; eauto using lookup_lt_Some with lia.\nQed.\n\nFixpoint env_subst (vs : list val) : var → expr :=\n  match vs with\n  | [] => ids\n  | v :: vs' => #v .: env_subst vs'\n  end.\n\nLemma env_subst_lookup vs x v :\n  vs !! x = Some v → env_subst vs x = of_val v.\nProof.\n  revert vs; induction x => vs.\n  - by destruct vs; inversion 1.\n  - destruct vs as [|w vs]; first by inversion 1.\n    rewrite -lookup_tail /=.\n    apply IHx.\nQed.\n", "meta": {"author": "euisuny", "repo": "logrel-iris", "sha": "37ad8f953c97cfa8c7eefa4a159dfbab6db6d17c", "save_path": "github-repos/coq/euisuny-logrel-iris", "path": "github-repos/coq/euisuny-logrel-iris/logrel-iris-37ad8f953c97cfa8c7eefa4a159dfbab6db6d17c/stlc/typing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.23767830217921007}}
{"text": "Require Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Wf.\nRequire Import Crypto.Compilers.InlineConstAndOpWf.\nRequire Import Crypto.Compilers.Z.Syntax.\nRequire Import Crypto.Compilers.Z.InlineConstAndOp.\n\nDefinition Wf_InlineConstAndOp {t} (e : Expr t) (Hwf : Wf e)\n  : Wf (InlineConstAndOp e)\n  := @Wf_InlineConstAndOp _ _ _ _ _ t e Hwf.\n\nHint Resolve Wf_InlineConstAndOp : wf.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Compilers/Z/InlineConstAndOpWf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.23767830217921004}}
{"text": "From Coq Require Import ssreflect.\nFrom stdpp Require Import base gmap.\nFrom iris.proofmode Require Import tactics.\nFrom aneris.prelude Require Import gset_map.\nFrom aneris.aneris_lang.lib Require Import list_proof.\nFrom aneris.aneris_lang.lib.serialization Require Import serialization_proof.\nFrom aneris.aneris_lang Require Import aneris_lifting proofmode.\nFrom aneris.examples.crdt.spec Require Import crdt_base crdt_time crdt_events crdt_denot crdt_resources.\nFrom aneris.examples.crdt.oplib Require Import oplib_code.\nFrom aneris.examples.crdt.oplib.spec Require Import model spec.\nFrom aneris.examples.crdt.oplib.examples.grow_only_set Require Import grow_only_set_code.\n\nSection gosCrdt.\n  Context `{!Log_Time} `{!EqDecision vl} `{!Countable vl}.\n\n  Definition gosOp : Type := vl.\n  Definition gosSt : Type := gset vl.\n\n  Definition gos_denot (s : gset (Event gosOp)) (state : gosSt) : Prop :=\n    gset_map EV_Op s = state.\n\n  Global Instance gos_denot_fun : Rel2__Fun gos_denot.\n  Proof. constructor; intros ? ? ? <- <-; done. Qed.\n\n  Global Instance gos_denot_instance : CrdtDenot gosOp gosSt := {\n    crdt_denot := gos_denot;\n  }.\nEnd gosCrdt.\n\nGlobal Arguments gosOp _ : clear implicits.\nGlobal Arguments gosSt _ {_ _}.\n\nSection OpGos.\n  Context `{!Log_Time}\n          `{!EqDecision vl} `{!Countable vl}.\n\n  Definition op_gos_effect (st : gosSt vl) (ev : Event (gosOp vl)) (st' : gosSt vl) : Prop :=\n    st' = {[EV_Op ev]} ∪ st.\n\n  Lemma op_gos_effect_fun st : Rel2__Fun (op_gos_effect st).\n  Proof. constructor; intros ??? -> ->; done. Qed.\n\n  Instance op_gos_effect_coh : OpCrdtEffectCoh op_gos_effect.\n  Proof.\n    intros s ev st st' Hst Hevs Hmax Hext.\n    rewrite /op_gos_effect /crdt_denot /= /gos_denot gset_map_union gset_map_singleton Hst.\n    clear; set_solver.\n  Qed.\n\n  Definition op_gos_init_st : gosSt vl := ∅.\n\n  Lemma op_gos_init_st_coh : ⟦ (∅ : gset (Event (gosOp vl))) ⟧ ⇝ op_gos_init_st.\n  Proof. done. Qed.\n\n  Global Instance op_gos_model_instance : OpCrdtModel (gosOp vl) (gosSt vl) := {\n    op_crdtM_effect := op_gos_effect;\n    op_crdtM_effect_fun := op_gos_effect_fun;\n    op_crdtM_effect_coh := op_gos_effect_coh;\n    op_crdtM_init_st := op_gos_init_st;\n    op_crdtM_init_st_coh := op_gos_init_st_coh\n  }.\n\nEnd OpGos.\n\nFrom aneris.aneris_lang.lib Require Import set_code set_proof.\nFrom aneris.aneris_lang.lib Require Import inject.\nFrom aneris.examples.crdt.oplib.proof Require Import time.\n\nSection gos_proof.\n  Context `{!EqDecision vl} `{!Countable vl}\n          `{!Inject vl val} `{!∀ (a : vl), Serializable vl_serialization $a}.\n\n  Context `{!anerisG M Σ}.\n\n  Context `{!CRDT_Params} `{!OpLib_Res (gosOp vl)}.\n\n  Definition gos_OpLib_Op_Coh :=\n    λ (op : gosOp vl) v, v = $op.\n\n  Lemma gos_OpLib_Op_Coh_Inj (o1 o2 : gosOp vl) (v : val) :\n    gos_OpLib_Op_Coh o1 v → gos_OpLib_Op_Coh o2 v → o1 = o2.\n  Proof. intros Ho1 Ho2; apply (inj inject); rewrite -Ho1 -Ho2; done. Qed.\n\n  Lemma gos_OpLib_Coh_Ser (op : gosOp vl) (v : val) :\n    gos_OpLib_Op_Coh op v → Serializable vl_serialization v.\n  Proof. intros ->; apply _. Qed.\n\n  Definition gos_OpLib_State_Coh := λ (st : gosSt vl) v, is_set st v.\n\n  Global Instance gos_OpLib_Params : OpLib_Params (gosOp vl) (gosSt vl) :=\n  {|\n    OpLib_Serialization := vl_serialization;\n    OpLib_State_Coh := gos_OpLib_State_Coh;\n    OpLib_Op_Coh := gos_OpLib_Op_Coh;\n    OpLib_Op_Coh_Inj := gos_OpLib_Op_Coh_Inj;\n    OpLib_Coh_Ser := gos_OpLib_Coh_Ser\n  |}.\n\n  Lemma gos_init_st_fn_spec : ⊢ init_st_fn_spec init_st.\n  Proof.\n    iIntros (addr).\n    iIntros \"!#\" (Φ) \"_ HΦ\".\n    rewrite /init_st.\n    wp_pures.\n    wp_apply wp_set_empty; first done.\n    iIntros (v Hv).\n    iApply \"HΦ\".\n    iPureIntro; apply Hv.\n  Qed.\n\n  Lemma gos_effect_spec : ⊢ effect_spec effect.\n  Proof.\n    iIntros (addr ev st s log_ev log_st).\n    iIntros \"!#\" (Φ) \"(%Hev & %Hst & %Hs & %Hevs) HΦ\".\n    rewrite /effect.\n    destruct log_ev as [log_ev orig vc].\n    destruct Hev as (evpl&evvc&evorig& ?&Hopcoh&?&?).\n    destruct Hevs as (Hnin & Hmax & Hext).\n    simplify_eq.\n    rewrite Hopcoh /=.\n    wp_pures.\n    wp_apply wp_set_add; first by iPureIntro; apply Hst.\n    iIntros (w Hw).\n    iApply \"HΦ\".\n    iExists _; done.\n  Qed.\n\n  Lemma gos_crdt_fun_spec : ⊢ crdt_fun_spec gos_crdt.\n  Proof.\n    iIntros (addr).\n    iIntros \"!#\" (Φ) \"_ HΦ\".\n    rewrite /gos_crdt.\n    wp_pures.\n    iApply \"HΦ\".\n    iExists _, _; iSplit; first done.\n    iSplit.\n    - iApply gos_init_st_fn_spec; done.\n    - iApply gos_effect_spec; done.\n  Qed.\n\n  Lemma prod_init_spec :\n    init_spec\n      (oplib_init\n         (s_ser (s_serializer vl_serialization)) (s_deser (s_serializer vl_serialization))) -∗\n    init_spec_for_specific_crdt\n      (gos_init (s_ser (s_serializer vl_serialization)) (s_deser (s_serializer vl_serialization))).\n  Proof.\n    iIntros \"#Hinit\" (repId addr addrs_val).\n    iIntros (Φ) \"!# (%Haddrs & %Hrepid & Hprotos & Hskt & Hfr & Htoken) HΦ\".\n    rewrite /gos_init.\n    wp_pures.\n    wp_apply (\"Hinit\" with \"[$Hprotos $Htoken $Hskt $Hfr]\").\n    { do 2 (iSplit; first done). iApply gos_crdt_fun_spec; done. }\n    iIntros (get update) \"(HLS & #Hget & #Hupdate)\".\n    wp_pures.\n    iApply \"HΦ\"; eauto.\n  Qed.\n\nEnd gos_proof.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/crdt/oplib/examples/grow_only_set/grow_only_set_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23767830217921004}}
{"text": "Require Import Coq.Strings.String.\n\nRequire Export SystemFR.ErasedSingleton.\nRequire Export SystemFR.SubtypeList.\nRequire Export SystemFR.EvalListMatch.\nRequire Export SystemFR.ReducibilitySubtype.\nRequire Export SystemFR.ErasedQuant.\n\nOpaque reducible_values.\n\nOpaque list_match.\n\nLemma reducible_union_left:\n  forall ρ t T1 T2,\n    valid_interpretation ρ ->\n    [ ρ ⊨ t : T1 ] ->\n    [ ρ ⊨ t : T_union T1 T2 ].\nProof.\n  unfold reduces_to; steps.\n  eexists; repeat step || simp_red; eauto using reducible_values_closed.\nQed.\n\nLemma reducible_union_right:\n  forall ρ t T1 T2,\n    valid_interpretation ρ ->\n    [ ρ ⊨ t : T2 ] ->\n    [ ρ ⊨ t : T_union T1 T2 ].\nProof.\n  unfold reduces_to; steps.\n  eexists; repeat step || simp_red; eauto using reducible_values_closed.\nQed.\n\nOpaque List.\n\nLemma tmatch_value:\n  forall ρ v t2 t3 T2 T3,\n    valid_interpretation ρ ->\n    wf t3 2 ->\n    wf T2 0 ->\n    wf T3 2 ->\n    is_erased_term t2 ->\n    is_erased_term t3 ->\n    is_erased_type T2 ->\n    is_erased_type T3 ->\n    pfv t2 term_var = nil ->\n    pfv t3 term_var = nil ->\n    pfv T2 term_var = nil ->\n    pfv T3 term_var = nil ->\n    [ ρ ⊨ v : List ]v ->\n    [ ρ ⊨ t2 : T2 ] ->\n    (forall h t, [ ρ ⊨ h : T_top ] -> [ ρ ⊨ t : List ] ->\n            [ ρ ⊨ open 0 (open 1 t3 h) t : open 0 (open 1 T3 h) t ]) ->\n    [ ρ ⊨ list_match v t2 t3 : List_Match v T2 T3 ].\nProof.\n  intros; evaluate_list_match; steps;\n    eauto with wf.\n\n  - eapply star_backstep_reducible; eauto;\n      repeat step || apply wf_list_match || apply is_erased_term_list_match ||\n             apply pfv_list_match;\n      eauto with wf.\n    unfold List_Match.\n    apply reducible_union_left; auto.\n    apply reducible_type_refine with uu; repeat step || simp_red || apply reducible_value_expr;\n      eauto using equivalent_refl with step_tactic.\n\n  - eapply reducibility_equivalent2; eauto using equivalent_sym;\n      repeat step || list_utils; t_closer.\n    unfold List_Match.\n    apply reducible_union_right; auto.\n    apply reducible_exists with h; repeat step || open_none; t_closer.\n    + apply reducible_value_expr; repeat step || simp_red_goal.\n    + apply reducible_exists with l; repeat step || open_none; t_closer;\n        eauto using reducible_value_expr.\n      apply reducible_type_refine with uu; repeat step || open_none; t_closer;\n      eauto using reducible_value_expr.\n      apply reducible_value_expr; repeat light || simp_red_goal.\n      apply equivalent_refl; steps; t_closer.\nQed.\n\nLemma tmatch:\n  forall ρ t t2 t3 T2 T3,\n    valid_interpretation ρ ->\n    wf t3 2 ->\n    wf T2 0 ->\n    wf T3 2 ->\n    is_erased_term t2 ->\n    is_erased_term t3 ->\n    is_erased_type T2 ->\n    is_erased_type T3 ->\n    pfv t2 term_var = nil ->\n    pfv t3 term_var = nil ->\n    pfv T2 term_var = nil ->\n    pfv T3 term_var = nil ->\n    [ ρ ⊨ t : List ] ->\n    [ ρ ⊨ t2 : T2 ] ->\n    (forall h t, [ ρ ⊨ h : T_top ]v -> [ ρ ⊨ t : List ]v ->\n            [ ρ ⊨ open 0 (open 1 t3 h) t : open 0 (open 1 T3 h) t ]) ->\n    [ ρ ⊨ list_match t t2 t3 : List_Match t T2 T3 ].\nProof.\n  intros.\n  unfold reduces_to in H11; steps.\n  apply reducibility_equivalent2 with (list_match v t2 t3); steps; t_closer.\n  - apply equivalent_sym.\n    equivalent_star;\n      repeat step || apply is_erased_term_list_match || apply wf_list_match || apply pfv_list_match;\n      eauto using evaluate_list_match_scrut;\n      t_closer.\n\n  - apply subtype_reducible with (List_Match v T2 T3).\n    + apply tmatch_value; steps.\n      unfold reduces_to in H11; steps.\n      unfold reduces_to in H17; steps.\n      eapply reducibility_equivalent2 with (open 0 (open 1 t3 h) v1);\n        repeat step || apply is_erased_type_open || apply equivalent_context ||\n               apply wf_open || apply fv_nils_open;\n        t_closer;\n        try solve [ apply equivalent_sym; equivalent_star ].\n      eapply reducibility_rtl; steps; eauto; t_closer.\n      rewrite (swap_term_holes_open t3); steps; t_closer.\n      eapply reducibility_equivalent2 with (open 0 (open 1 (swap_term_holes t3 0 1) v1) v0);\n        repeat step ||\n               apply is_erased_type_open || apply is_erased_open ||\n               apply equivalent_context || apply wf_swap_term_holes_3 ||\n               apply wf_open || apply fv_nils_open;\n        t_closer;\n        try solve [ apply equivalent_sym; equivalent_star ].\n\n      rewrite (swap_term_holes_open T3); steps; t_closer.\n      eapply reducibility_rtl; eauto;\n      repeat step || apply is_erased_type_open || apply fv_nils_open; eauto; t_closer.\n      rewrite <- (swap_term_holes_open t3); steps; t_closer.\n      rewrite <- (swap_term_holes_open T3); steps; t_closer.\n    + apply subtype_list_match_scrut; steps.\n      apply equivalent_sym; equivalent_star.\nQed.\n\nLemma open_tmatch_helper:\n  forall Θ Γ t t2 t3 T2 T3 x1 x2,\n    ~ x1 ∈ pfv_context Γ term_var ->\n    ~ x2 ∈ pfv_context Γ term_var ->\n    x1 <> x2 ->\n    wf t3 2 ->\n    wf T2 0 ->\n    wf T3 2 ->\n    is_erased_term t2 ->\n    is_erased_term t3 ->\n    is_erased_type T2 ->\n    is_erased_type T3 ->\n    subset (fv t2) (support Γ) ->\n    subset (fv t3) (support Γ) ->\n    subset (fv T2) (support Γ) ->\n    subset (fv T3) (support Γ) ->\n    [ Θ; Γ ⊨ t : List ] ->\n    [ Θ; Γ ⊨ t2 : T2 ] ->\n    [ Θ; (x1, T_top) :: (x2, List) :: Γ ⊨\n        open 0 (open 1 t3 (fvar x1 term_var)) (fvar x2 term_var) :\n        open 0 (open 1 T3 (fvar x1 term_var)) (fvar x2 term_var) ] ->\n    [ Θ; Γ ⊨ list_match t t2 t3 : List_Match t T2 T3 ].\nProof.\n  unfold open_reducible;\n    repeat step || apply tmatch || t_instantiate_sat3 ||\n           rewrite substitute_list_match || rewrite substitute_List_Match;\n    t_closer.\n\n  unshelve epose proof (H15 ρ ((x1, h) :: (x2, t0) :: lterms) _ _ _);\n    repeat step || apply SatCons || t_substitutions;\n    t_closer.\nQed.\n\nLemma open_tmatch:\n  forall Γ t t2 t3 T2 T3 x1 x2,\n    ~ x1 ∈ pfv_context Γ term_var ->\n    ~ x2 ∈ pfv_context Γ term_var ->\n    x1 <> x2 ->\n    wf t 0 ->\n    wf t2 0 ->\n    wf t3 2 ->\n    wf T2 0 ->\n    wf T3 2 ->\n    is_erased_term t ->\n    is_erased_term t2 ->\n    is_erased_term t3 ->\n    is_erased_type T2 ->\n    is_erased_type T3 ->\n    subset (fv t) (support Γ) ->\n    subset (fv t2) (support Γ) ->\n    subset (fv t3) (support Γ) ->\n    subset (fv T2) (support Γ) ->\n    subset (fv T3) (support Γ) ->\n    [ Γ ⊫ t : List ] ->\n    [ Γ ⊫ t2 : T2 ] ->\n    [ (x1, T_top) :: (x2, List) :: Γ ⊫\n        open 0 (open 1 t3 (fvar x1 term_var)) (fvar x2 term_var) :\n        open 0 (open 1 T3 (fvar x1 term_var)) (fvar x2 term_var) ] ->\n    [ Γ ⊫ list_match t t2 t3 : T_singleton (List_Match t T2 T3) (list_match t t2 t3) ].\nProof.\n  repeat step || apply open_reducible_singleton ||\n         apply is_erased_term_list_match || apply wf_list_match;\n    t_closer;\n    eauto using open_tmatch_helper.\n  eapply subset_transitive; eauto using pfv_list_match2; repeat step || sets.\nQed.\n", "meta": {"author": "epfl-lara", "repo": "SystemFR", "sha": "a68d12d6360f395958506deea66112c46be492a0", "save_path": "github-repos/coq/epfl-lara-SystemFR", "path": "github-repos/coq/epfl-lara-SystemFR/SystemFR-a68d12d6360f395958506deea66112c46be492a0/InferMatch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23765612787937973}}
{"text": "From mathcomp.ssreflect \nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp\nRequire Import path.\nRequire Import Eqdep.\nFrom Heaps\nRequire Import pred prelude idynamic ordtype pcm finmap unionmap heap coding. \nFrom Contracts\nRequire Import Automata2.\nRequire Import Arith Bool Omega.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Crowdfunding.\n(* Encoding of the Crowdfunding contract from the Scilla whitepaper *)\n\n(******************************************************\ncontract Crowdfunding\n (owner     : address,\n  max_block : uint,\n  goal      : uint)\n\n(* Mutable state description *)\n{\n  backers : address => uint = [];\n  funded  : boolean = false;\n}\n\n(* Transition 1: Donating money *)\ntransition Donate\n  (sender : address, value : uint, tag : string)\n  (* Simple filter identifying this transition *)\n  if tag == \"donate\" =>\n\n  bs <- & backers;\n  blk <- && block_number;\n  let nxt_block = blk + 1 in\n  if max_block <= nxt_block\n  then send (<to -> sender, amount -> 0,\n\t      tag -> main,\n\t      msg -> \"deadline_passed\">, MT)\n  else\n    if not (contains(bs, sender))\n    then let bs1 = put(sbs, ender, value) in\n         backers := bs1;\n         send (<to -> sender,\n                amount -> 0,\n\t        tag -> \"main\",\n\t        msg -> \"ok\">, MT)\n    else send (<to -> sender,\n                amount -> 0,\n\t        tag -> \"main\",\n\t        msg -> \"already_donated\">, MT)\n\n(* Transition 2: Sending the funds to the owner *)\ntransition GetFunds\n  (sender : address, value : uint, tag : string)\n  (* Only the owner can get the money back *)\n  if (tag == \"getfunds\") && (sender == owner) =>\n  blk <- && block_number;\n  bal <- & balance;\n  if max_block >= blk\n  then if goal <= bal\n       then funded := true;\n            send (<to -> owner, amount -> bal,\n                   tag -> \"main\", msg -> \"funded\">, MT)\n       else send (<to -> owner, amount -> 0,\n                   tag -> \"main\", msg -> \"failed\">, MT)\n  else send (<to -> owner, amount -> 0, tag -> \"main\",\n   \t      msg -> \"too_early_to_claim_funds\">, MT)\n\n(* Transition 3: Reclaim funds by a backer *)\ntransition Claim\n  (sender : address, value : uint, tag : string)\n  if tag == \"claim\" =>\n  blk <- && block_number;\n  if blk <= max_block\n  then send (<to -> sender, amount -> 0, tag -> \"main\",\n              msg -> \"too_early_to_reclaim\">, MT)\n  else bs <- & backers;\n       bal <- & balance;\n       if (not (contains(bs, sender))) || funded ||\n          goal <= bal\n       then send (<to -> sender, amount -> 0,\n                   tag -> \"main\",\n\t           msg -> \"cannot_refund\">, MT)\n       else\n       let v = get(bs, sender) in\n       backers := remove(bs, sender);\n       send (<to -> sender, amount -> v, tag -> \"main\",\n              msg -> \"here_is_your_money\">, MT)\n\n *******************************************************)\n\nRecord crowdState := CS {\n   owner_mb_goal : address * nat * value;\n   backers : seq (address * value);\n   funded : bool;\n}.\n\n(* Administrative setters/getters *)\nDefinition get_owner cs : address := (owner_mb_goal cs).1.1.\nDefinition get_goal cs : value := (owner_mb_goal cs).2.\nDefinition get_max_block cs : nat := (owner_mb_goal cs).1.2.\n\n\nDefinition set_backers cs bs : crowdState :=\n  CS (owner_mb_goal cs) bs (funded cs).\n\nDefinition set_funded cs f : crowdState :=\n  CS (owner_mb_goal cs) (backers cs) f.\n\n(* Defining three layers of initial states *)\n(* Parameters *)\nVariable init_owner : address.\nVariable init_max_block : nat.\nVariable init_goal : value.\nVariable init_address : address.\n(* Initial crowdfunding state *)\nDefinition init_state : crowdState :=\n  CS (init_owner, init_max_block, init_max_block) [::] false.\n(* Initial contract state *)\nDefinition init_cstate : cstate crowdState :=\n  CState init_address 0 init_state.\n(* Initial world *)\nDefinition init_world : world crowdState :=\nmkW emptymsg init_cstate b0 None.\n\nDefinition pred := world crowdState -> Prop.\n\n\n(*********************************************************)\n(********************* Transitions ***********************)\n(*********************************************************)\n\n(* Transition 1 *)\n(*\ntransition Donate\n  (sender : address, value : uint, tag : string)\n  (* Simple filter identifying this transition *)\n  if tag == \"donate\" =>\n\n  bs <- & backers;\n  blk <- && block_number; \n  let nxt_block = blk + 1 in\n  if max_block <= nxt_block\n  then send (<to -> sender, amount -> 0,\n\t      tag -> main,\n\t      msg -> \"deadline_passed\">, MT)\n  else\n    if not (contains(bs, sender))\n    then let bs1 = put(sbs, ender, value) in\n         backers := bs1;\n         send (<to -> sender,\n                amount -> 0,\n\t        tag -> \"main\",\n\t        msg -> \"ok\">, MT)\n    else send (<to -> sender,\n                amount -> 0,\n\t        tag -> \"main\",\n\t        msg -> \"already_donated\">, MT)\n *)\n\n(* Definition of the protocol *)\nVariable crowd_addr : address.\n\nNotation tft := (trans_fun_type crowdState).\nDefinition ok_msg := [:: (0, [:: 1])].\nDefinition no_msg := [:: (0, [:: 0])].\n\nDefinition donate_tag := 1.\nDefinition donate_fun : tft := fun id bal s m bc =>\n  if method m == donate_tag then\n    let bs := backers s in\n    let nxt_block := block_num bc + 1 in\n    let from := sender m in\n    if get_max_block s <= nxt_block\n    then (s, Some (Msg 0 crowd_addr from 0 no_msg))\n    else if all [pred e | e.1 != from] bs\n         (* new backer *)\n         then let bs' := (from, val m) :: bs in\n              let s'  := set_backers s bs' in\n              (s', Some (Msg 0 crowd_addr from 0 ok_msg))\n         else (s, Some (Msg 0 crowd_addr from 0 no_msg))\n  else (s, None).\n\nDefinition donate := CTrans donate_tag donate_fun.\n\n(* Transition 2: Sending the funds to the owner *)\n(*\ntransition GetFunds\n  (sender : address, value : uint, tag : string)\n  (* Only the owner can get the money back *)\n  if (tag == \"getfunds\") && (sender == owner) =>\n  blk <- && block_number;\n  bal <- & balance;\n  if max_block < blk\n  then if goal <= bal\n       then funded := true;   \n            send (<to -> owner, amount -> bal,\n                   tag -> \"main\", msg -> \"funded\">, MT)\n       else send (<to -> owner, amount -> 0,\n                   tag -> \"main\", msg -> \"failed\">, MT)\n  else send (<to -> owner, amount -> 0, tag -> \"main\",\n   \t      msg -> \"too_early_to_claim_funds\">, MT)\n *)\n\nDefinition getfunds_tag := 2.\nDefinition getfunds_fun : tft := fun id bal s m bc =>\n  let: from := sender m in\n  if (method m == getfunds_tag) && (from == (get_owner s)) then\n    let blk := block_num bc + 1 in\n    if (get_max_block s < blk)\n    then if get_goal s <= bal\n         then let s' := set_funded s true in\n              (s', Some (Msg bal crowd_addr from 0 ok_msg))\n         else (s, Some (Msg 0 crowd_addr from 0 no_msg))\n    else (s, Some (Msg 0 crowd_addr from 0 no_msg))\n  else (s, None).\n\nDefinition get_funds := CTrans getfunds_tag getfunds_fun.\n\n(* Transition 3: Reclaim funds by a backer *)\n(*\ntransition Claim\n  (sender : address, value : uint, tag : string)\n  if tag == \"claim\" =>\n  blk <- && block_number;\n  if blk <= max_block\n  then send (<to -> sender, amount -> 0, tag -> \"main\",\n              msg -> \"too_early_to_reclaim\">, MT)\n  else bs <- & backers;\n       bal <- & balance;\n       if (not (contains(bs, sender))) || funded ||\n          goal <= bal\n       then send (<to -> sender, amount -> 0,\n                   tag -> \"main\",\n\t           msg -> \"cannot_refund\">, MT)\n       else\n       let v = get(bs, sender) in\n       backers := remove(bs, sender);\n       send (<to -> sender, amount -> v, tag -> \"main\",\n              msg -> \"here_is_your_money\">, MT)\n*)\n\nDefinition claim_tag := 3.\nDefinition claim_fun : tft := fun id bal s m bc =>\n  let: from := sender m in\n  if method m == claim_tag then\n    let blk := block_num bc in\n    if blk <= get_max_block s\n    then\n      (* Too early! *)\n      (s, Some (Msg 0 crowd_addr from 0 no_msg))\n    else let bs := backers s in\n         if [|| funded s | get_goal s <= bal]\n         (* Cannot reimburse: campaign suceeded *)\n         then (s, Some (Msg 0 crowd_addr from 0 no_msg))\n         else let n := seq.find [pred e | e.1 == from] bs in\n              if n < size bs\n              then let v := nth 0 (map snd bs) n in\n                   let bs' := filter [pred e | e.1 != from] bs in\n                   let s'  := set_backers s bs' in\n                   (s', Some (Msg v crowd_addr from 0 ok_msg))\n              else\n                (* Didn't back or already claimed *)\n                (s, None)\n  else (s, None).\n\nDefinition claim := CTrans claim_tag claim_fun.\n\nProgram Definition crowd_prot : Protocol crowdState :=\n@CProt _ crowd_addr 0 init_state [:: donate; get_funds; claim] _.\n\nLemma crowd_tags : tags crowd_prot = [:: 1; 2; 3].\nProof. by []. Qed.\n\nProgram Definition prot : Protocol crowdState :=\n@CProt _ crowd_addr 0 init_state [:: donate; get_funds; claim] _.\n\nDefinition reachability w1 w2 := step_world prot w1 = w2.\n\nCheck reachability.\n\n(* Path definitions *)\nDefinition path := nat -> world crowdState.\nDefinition firstp (p : path) : world crowdState := p 0.\nDefinition path_predicate (p : path) := forall n, reachability (p n) (p (S n)).\n(* Good path sigma-type definitions *)\nDefinition gpath : Type := {p : path & path_predicate p}.\n(* Projection functions for sigma type good paths *)\nDefinition gpath_proj1 : gpath -> (nat -> world crowdState) :=\n  fun gp => match gp with\n            | existT a _ => a\n            end.\nCoercion gpath_proj1 : gpath >-> Funclass. \nDefinition gpath_proj2 (gp : gpath) : (path_predicate (gpath_proj1 gp)) :=\n  match gp with\n  | existT _ b => b\n  end.\nDefinition first (gp : gpath) : world crowdState := (gpath_proj1 gp 0).\n\n(* A cacophany of path constructions *)\n(* Constructing a random path *) \nFixpoint step_n_times (w : world crowdState) (n : nat) :=\n  match n with\n  | 0 => w\n  | S n' => step_world prot (step_n_times w n')\n  end.\n\nPrint step_world.\n\nDefinition make_path (w : world crowdState) : path := \n  step_n_times w.\n\nLemma rewrite_step_world_S :\n  forall (n : nat) (w : world crowdState),\n    step_n_times w (S n) = step_world prot (step_n_times w n).\nProof. reflexivity. Qed.\n\nLemma step_world_swap_helper :\n  forall (n : nat) (w : world crowdState),\n    step_world prot (step_n_times w n) =\n    step_n_times (step_world prot w) n.\nProof.\n  intros n w.\n  induction n.\n  - reflexivity.\n  - rewrite rewrite_step_world_S.\n    rewrite IHn.\n    rewrite rewrite_step_world_S.\n    reflexivity.\nQed.\n\nLemma step_world_swap :\n  forall n : nat,\n    step_world prot (step_n_times (step_world prot init_world) n) =\n    step_n_times (step_world prot (step_world prot init_world)) n.\nProof.\n  induction n.\n  - reflexivity.\n  - rewrite step_world_swap_helper.\n    reflexivity.\nQed.\n\nLemma step_world_ind :\n  forall n : nat,\n    step_world prot (step_n_times init_world n) = step_n_times init_world (S n).\nProof.\n  induction n.\n  - simpl; reflexivity.\n  - simpl. reflexivity.\nQed.\n\nLemma about_p : path_predicate (make_path init_world).\nProof.\n  unfold path_predicate.\n  induction n.\n  - simpl. unfold reachability. reflexivity.\n  - unfold reachability in *.\n    unfold make_path in *.\n    rewrite <- IHn.\n    simpl. reflexivity.\nQed.\n\nLemma about_p_hole :\n  forall w : world crowdState,\n    path_predicate (make_path w).\nProof.\n  unfold path_predicate.\n  induction n.\n  - simpl. unfold reachability. reflexivity.\n  - unfold reachability in *.\n    unfold make_path in *.\n    rewrite <- IHn.\n    simpl. reflexivity.\nQed.\n\nDefinition gp : gpath := (existT _ (make_path init_world) about_p).\n(* Can you make a sigma type with a dependent type? *)\nParameter generic_world : world crowdState.\nCheck (about_p_hole generic_world).\nDefinition gp_hole (w : world crowdState) : gpath := (existT _ (make_path w) (about_p_hole w)).\n(* The answer is yes *)\n\n(* Constructing an offset path *)\nDefinition make_offset_path (p : path) : path := fun n => p (S n).\nDefinition make_offset_path' (gp : gpath) : path := fun n => gpath_proj1 gp (S n).\nLemma about_offset_path :\n  forall p : path,\n    path_predicate p ->\n    path_predicate (make_offset_path p).\nProof.\n  intros p H_p.\n  unfold make_offset_path.\n  unfold path_predicate in *.\n  intro n. \n  exact (H_p (S n)).\nQed.\nLemma about_offset_path' :\n  forall gp : gpath,\n    path_predicate (make_offset_path' gp). \nProof.\n  intro gp.\n  destruct gp. unfold path_predicate in p.\n  unfold make_offset_path'.\n  unfold gpath_proj1.\n  unfold path_predicate.\n  intros n.\n  exact (p (S n)).\nQed.\n\nDefinition gp_offset (p : path) (pred : path_predicate p) : gpath :=\n  (existT _ (make_offset_path p) (about_offset_path pred)).\nDefinition gp_offset' (gp : gpath) : gpath :=\n  (existT _ (make_offset_path' gp) (about_offset_path' gp)).\n\n(* Constructing a backwards offset path *)\nDefinition make_backwards_offset_path (w0 : world crowdState) (p : path) : path :=\n  fun n => match n with 0 => w0 | _ => (p (n.-1)) end.\nDefinition make_backwards_offset_path' (w0 : world crowdState) (gp : gpath) : path :=\n  fun n => match n with 0 => w0 | _ => (gpath_proj1 gp (n.-1)) end.\nLemma about_backwards_offset_path :\n  forall (p : path) (w0 : world crowdState),\n    path_predicate p ->\n    reachability w0 (p 0) -> \n    path_predicate (make_backwards_offset_path w0 p).\nProof.\n  intros p w0 H_p.\n  unfold make_backwards_offset_path.\n  unfold path_predicate in *.\n  destruct n.\n  simpl. exact H.\n  simpl. replace (n-0) with n.\n  Focus 2. rewrite subn0. reflexivity.\n  apply (H_p n).\nQed.\nLemma about_backwards_offset_path' :\n  forall (gp : gpath) (w0 : world crowdState),\n    reachability w0 (gpath_proj1 gp 0) -> \n    path_predicate (make_backwards_offset_path' w0 gp). \nProof.\n  intros gp w0 H_0.\n  destruct gp. unfold path_predicate in p.\n  unfold make_backwards_offset_path'.\n  unfold gpath_proj1.\n  unfold path_predicate.\n  destruct n.\n  simpl. exact H_0.\n  simpl. replace (n-0) with n. Focus 2. rewrite subn0. reflexivity.\n  apply (p n).\nQed.\nDefinition gp_backwards_offset\n           (w0 : world crowdState) (p : path)\n           (pred : path_predicate p)\n           (r : reachability w0 (p 0)) : gpath :=\n  (existT _ (make_backwards_offset_path w0 p) (about_backwards_offset_path pred r)).\nDefinition gp_backwards_offset'\n           (w0 : world crowdState) (gp : gpath)\n           (r : reachability w0 (gpath_proj1 gp 0)) : gpath :=\n  (existT _ (make_backwards_offset_path' w0 gp) (about_backwards_offset_path' r)).    \n(* Satisfaction definition *)\nDefinition satisfies (w : world crowdState) (p : pred) : Prop := p w.\n(* I'm not sure that the following metalogic entail is necessary *)\nDefinition entails (p q : pred) : Prop :=\n  forall w, (satisfies w p) -> (satisfies w q).\nDefinition equiv (p q : pred) : Prop := entails p q /\\ entails q p.\n \nAxiom LEM : forall P : Prop, P \\/ ~ P.\nNotation \"w '|=' p\" := (satisfies w p) (at level 80, no associativity).\n\n(* Temporal operator definitions *)\nParameter Top : pred.\nParameter Bottom : pred.\nAxiom about_top : forall w, Top w.\nAxiom about_bottom : forall w, Bottom w -> False.\nDefinition Neg p : pred := fun w => (w |= p) -> False.\nDefinition Conj p q : pred := fun w => (w |= p) /\\ (w |= q).\nDefinition Disj p q : pred := fun w => (w |= p) \\/ (w |= q).\nDefinition Impl p q : pred := fun w => ~ (w |= p) \\/ (w |= q).\n\n(* Temporal operator definitions *)\n(* AX says 'in every next state', all gpaths beginning with w next satisfy p. *)\nDefinition AllNext (p : pred) := fun w =>  \n  forall gp : gpath, first gp = w -> gp 1 |= p.\n(* EX says 'in some next state', all gpaths beginning with w next satisfy p. *)\nDefinition ExistsNext (p : pred) := fun w =>  \n  exists gp : gpath, first gp = w /\\ gp 1 |= p.\n(* AG says all states along all paths beginning with  w satisfy p, including w. *)\nDefinition AllBox (p : pred) := fun w =>  \n  forall gp : gpath, first gp = w -> forall n, gp n |= p.\n(* EG says that there exists a path beginning with w along which all states satisfy p. *)\nDefinition ExistsBox (p : pred) := fun w =>  \n  exists gp : gpath, first gp = w /\\ forall n, gp n |= p.\n(* AF says all paths beginning with w contain a future state which satisfies p. *)\nDefinition AllFuture (p : pred) := fun w =>  \n  forall gp : gpath, first gp = w -> exists n, gp n |= p.\n(* EF says that there exists a path beginning with a future state which satisfies p. *)\nDefinition ExistsFuture (p : pred) := fun w =>  \n  exists gp : gpath, first gp = w /\\  exists n, gp n |= p.\n(* AU says that all paths beginning with w satisfy p Until q. *)\nDefinition AllUntil (p q : pred) := fun w =>  \n  forall gp : gpath, first gp = w -> exists n, gp n |= q /\\ forall m, m < n -> gp m |= p.\n(* EU says that there exists a path beginning with w that satifies p Until q. *)\nDefinition ExistsUntil (p q : pred) := fun w =>  \n  exists gp : gpath, first gp = w /\\ exists n, gp n |= q /\\ forall m, m < n -> gp m |= p.\n\n(* Extended temporal operator definitions *)\nDefinition AllRelease (p q : pred) := fun w => \n  Neg (ExistsUntil (Neg p) (Neg q)) w.\nDefinition ExistsRelease (p q : pred) := fun w => \n  Neg (AllUntil (Neg p) (Neg q)) w.\nDefinition AllWait (p q : pred) := fun w => \n  AllRelease q (Disj p q) w.\nDefinition ExistsWait (p q : pred) := fun w =>\n  ExistsRelease q (Disj p q) w.\n\n(* Notation definitions *)\nNotation \"p <=> q\" := (equiv p q) (at level 35, no associativity).\nNotation \"! p\" := (Neg p) (at level 60, right associativity).\nNotation \"p && q\" := (Conj p q) (at level 40, left associativity).\nNotation \"p || q\" := (Disj p q).\nNotation \"p --> q\" := (Impl p q) (at level 35, no associativity).\nNotation \"'AG' p\" := (AllBox p) (at level 35, no associativity).\nNotation \"'EG' p\" := (ExistsBox p) (at level 35, no associativity).\nNotation \"'AX' p\" := (AllNext p) (at level 35, no associativity).\nNotation \"'EX' p\" := (ExistsNext p) (at level 35, no associativity).\nNotation \"'AF' p\" := (AllFuture p) (at level 35, no associativity).\nNotation \"'EF' p\" := (ExistsFuture p) (at level 35, no associativity). \nNotation \"'A' '[' p 'U' q ']'\" := (AllUntil p q) (at level 35, no associativity).\nNotation \"'E' '[' p 'U' q ']'\" := (ExistsUntil p q) (at level 35, no associativity).\nNotation \"'A' '[' p 'R' q ']'\" := (AllRelease p q) (at level 35, no associativity).\nNotation \"'E' '[' p 'R' q ']'\" := (ExistsRelease p q) (at level 35, no associativity).\nNotation \"'A' '[' p 'W' q ']'\" := (AllWait p q) (at level 35, no associativity).\nNotation \"'E' '[' p 'W' q ']'\" := (ExistsWait p q) (at level 35, no associativity).\n\nTheorem ctl_1 : forall (P : pred),\n    AG P <=> (P && AX (AG P)).\nProof. Admitted.\nTheorem ctl_2 : forall (P : pred),\n    (P && AX (AG P)) <=> AG P.\nProof. Admitted.\nTheorem ctl_3 : forall (P : pred),\n    EG P <=> (P && EX (EG P)).\nProof. Admitted.      \nTheorem ctl_4 : forall (P : pred),\n    (P && EX (EG P)) <=> EG P.\nProof. Admitted.\nTheorem equiv_1 : forall (P : pred),\n    AX P <=> ! (EX (! P)).\nProof. Admitted.\nTheorem equiv_2 : forall (P : pred),\n    AF P <=> ! (EG (! P)).\nProof. Admitted.\nTheorem equiv_3 : forall (P : pred),\n    AG P <=> ! (EF (!P)).\nProof. Admitted.\nTheorem equiv_4 : forall (P : pred),\n    AF P <=> A [Top U P]. \nProof. Admitted.\nTheorem equiv_5 : forall (P : pred),\n    EF P <=> E [Top U P].\nProof. Admitted.\nTheorem equiv_6 : forall (P Q : pred),\n    A [P U Q] <=> E [!P U (!P && !Q)] && AF Q.\nProof. Admitted.\n\n(* \nLemma find_leq {A : eqType} (p : pred (A * nat)) (bs : seq (A * nat)) :\n  nth 0 [seq i.2 | i <- bs] (seq.find p bs) <= sumn [seq i.2 | i <- bs].\nProof.\nelim: bs=>//[[a w]]bs/=Gi; case:ifP=>_/=; first by rewrite leq_addr.\nby rewrite (leq_trans Gi (leq_addl w _)).\nQed.\n*)\n\n(***********************************************************)\n(**             Correctness properties                    **)\n(***********************************************************)\n\n(************************************************************************\n\n1. The contract always has sufficient balance to reimburse everyone,\nunless it's successfully finished its campaign:\n\nThe \"funded\" flag is set only if the campaign goals were reached, then\nall money goes to owner. Otherwise, the contract keeps all its money\nintact.\n\nPerhaps, we should make it stronger, adding a temporal property that\none's reimbursement doesn't change.\n\n************************************************************************)\n\nDefinition notfunded : pred :=\n  fun w => funded (state (st w)) = false.\nDefinition balance_sufficient s := \n  sumn (map snd (backers (state (st s)))) <= balance (st s).\n\nLemma temporal_balance_backed :\n    init_world |= AG (notfunded --> balance_sufficient).\nProof.\n  rewrite /satisfies/AllBox=>gp H_first n/=.\n  rewrite /satisfies/Impl.\n  case: gp H_first=>p r/= H0. \n  elim: n=>[|n Hi].\n  - by rewrite H0/satisfies; right. (* Hurray! *)\n  move: (r n); case: Hi=>H Ri;\n  rewrite /reachability in Ri; rewrite -Ri.\n  - remember (step_world prot (p n)) as w. clear Ri.\n    move: Heqw H.\n    case: (p n)=>inFlight st b out/=.\n    case: st=>id bal st/=.\n    case: inFlight=>val from to tg body/=?; subst w=>/=.\n    rewrite/step_world/=.\n    case: ifP=>[/eqP Zi|_]/=.\n    + subst tg=>/=; left; rewrite /donate_fun/=.\n      case:ifP=>_/=.\n      by rewrite /satisfies/=/notfunded/= in H *.\n\n    (* NOW we have a real mess. *)\n    (* How to get a clean case distinction on the three transitions? *)\nAbort.\n\n(* Ilya's proof for non-temporal model: \napply: safe_ind=>[|[id bal s]bc m M Hi]//.\nrewrite crowd_tags !inE in M.\n(* Get the exact transitions and start struggling... *)\nrewrite /= /apply_prot; case/orP: M; [|case/orP]=>/eqP M; rewrite M/=.\n\n(* Donate transition *)\nrewrite /donate_fun M eqxx.\ncase: ifP=>/=_; [move/Hi=>{Hi}Hi|].\n- by rewrite subn0; apply: (leq_trans Hi (leq_addr (val m) bal)).\ncase: ifP=>/=_; move/Hi=>{Hi}Hi; last first.\n- by rewrite subn0; apply: (leq_trans Hi (leq_addr (val m) bal)).\nby rewrite subn0 /balance_backed/= in Hi *; rewrite addnC leq_add2r.\n\n(* Get funds transition. *)\nrewrite /getfunds_fun M eqxx.\ncase: ifP=>//=_; case:ifP=>//=_;[|move/Hi=>{Hi}Hi]; last first.\n- by rewrite subn0; apply: (leq_trans Hi (leq_addr (val m) bal)).\ncase: ifP=>//=_; move/Hi=>{Hi}Hi.\nby rewrite subn0; apply: (leq_trans Hi (leq_addr (val m) bal)).\n\n(* Claim funds back *)\nrewrite /claim_fun M eqxx.\ncase: ifP=>//=_; [move/Hi=>{Hi}Hi|].\n- by rewrite subn0; apply: (leq_trans Hi (leq_addr (val m) bal)).\ncase: ifP=>//=X.\n- case/orP: X; first by rewrite /balance_backed/==>->.\n  by move=>_/Hi Z; rewrite subn0; apply: (leq_trans Z (leq_addr (val m) bal)).\ncase: ifP=>//=G/=; move/Hi=>/={Hi}Hi.\nrewrite addnC.\nhave H1: nth 0 [seq i.2 | i <- backers s]\n             (seq.find [pred e | e.1 == sender m] (backers s)) <=\n         sumn [seq i.2 | i <- backers s] by apply: find_leq.\nmove: (leq_trans H1 Hi)=> H2.\nrewrite -(addnBA _ H2); clear H2.\nsuff H3: sumn [seq i.2 | i <- backers s & [pred e | e.1 != sender m] i] <=\n         bal - nth 0 [seq i.2 | i <- backers s]\n                   (seq.find [pred e | e.1 == sender m] (backers s)).\n- by apply: (leq_trans H3 (leq_addl (val m) _ )).\nclear M.\nsuff H2: sumn [seq i.2 | i <- backers s & [pred e | e.1 != sender m] i] <=\n         sumn [seq i.2 | i <- backers s] -\n         nth 0 [seq i.2 | i <- backers s] (seq.find [pred e | e.1 == sender m] (backers s)).\n- by apply: (leq_trans H2); apply: leq_sub.\nclear Hi H1 X G bc bal id crowd_addr init_goal init_max_block init_owner.\nmove: (backers s)=>bs{s}.\nelim:bs=>//[[a v]] bs/= Hi/=; case:ifP; last first.\n- move/negbT; case: ifP=>//= _ _; rewrite addnC -addnBA//subnn addn0.\n  clear Hi; elim: bs=>//={a v}[[a v]]bs/=.\n  case:ifP=>//=_ H; first by rewrite leq_add2l. \n  by rewrite (leq_trans H (leq_addl _ _)).\nmove/negbTE=>->/={a}; rewrite -(leq_add2l v) in Hi. \nby rewrite addnBA in Hi; last by apply: find_leq.\nQed. *)\n\n(***********************************************************************)\n(******           Proving temporal properties                     ******)\n(***********************************************************************)\n\n(* Contribution of backer b is d is recorded in the `backers` *)\nDefinition donated b (d : value) st :=\n  (filter [pred e | e.1 == b] (backers (state st))) == [:: (b, d)].\n\n(* b doesn't claim its funding back *)\nDefinition no_claims_from b (q : bstate * message) := sender q.2 != b.\n\n(************************************************************************\n\n2. The following lemma shows that the donation record is going to be\npreserved by the protocol since the moment it's been contributed, as\nlong, as no messages from the corresponding backer b is sent to the\ncontract. This guarantees that the contract doesn't \"drop\" the record\nabout someone's donations.\n\nIn conjunctions with sufficient_funds_safe (proved above) this\nguarantees that, if the campaign isn't funded, there is always a\nnecessary amount on the balance to reimburse each backer, in the case\nof failure of the campaign.\n\n************************************************************************)\n(* \nLemma donation_preserved (b : address) (d : value):\n  since_as_long crowd_prot (donated b d)\n                (fun _ s' => donated b d s') (no_claims_from b).\nProof.\n(* This is where we would need a temporal logic, but, well.. *)\n(* Let's prove it out of the definition. *)\nelim=>[|[bc m] sc Hi]st st' P R; first by rewrite /reachable'=>/=Z; subst st'.\nrewrite /reachable'/==>E. \napply: (Hi (post (step_prot crowd_prot st bc m))); last 2 first; clear Hi.\n- by move=>q; move:(R q)=>{R}R G; apply: R; apply/In_cons; right.\n- rewrite E; set st1 := (step_prot crowd_prot st bc m); clear E R P.\n  by case: sc st1=>//=[[bc' m']] sc st1/=.   \nclear E.\nhave N: sender m != b. \n- suff B: no_claims_from b (bc, m) by [].\n  by apply: R; apply/In_cons; left.\ncase M: (method m \\in tags crowd_prot); last first.\n- by move/negbT: M=>M; rewrite (bad_tag_step bc st M).\ncase: st P=>id a s; rewrite /donated/==>D. \ncase/orP: M; [|case/orP;[| rewrite orbC]]=>/eqP T; \nrewrite /apply_prot T/=. \n- rewrite /donate_fun T/=; case: ifP=>//_; case: ifP=>//_/=.\n  by move/negbTE: N=>->. \n- by rewrite /getfunds_fun T/=; case: ifP=>//_; case: ifP=>//_; case:ifP.\nrewrite /claim_fun T/=; case:ifP=>//_; case: ifP=>//_; case: ifP=>//=X.\nrewrite -filter_predI/=; move/eqP:D=><-; apply/eqP.\nelim: (backers s)=>//=x xs Hi; rewrite Hi; clear Hi.\ncase B: (x.1 == b)=>//=.\nby move/eqP: B=>?; subst b; move/negbTE: N; rewrite eq_sym=>/negbT=>->.\nQed. *)\n\n(************************************************************************\n\n3. The final property: if the campaign has failed (goal hasn't been\nreached and the deadline has passed), every registered backer can get\nits donation back.\n\nTODO: formulate and prove it.\n\n************************************************************************)\n(*\nLemma can_claim_back b d st bc:\n  (* We have donated, so the contract holds that state *)\n  donated b d st ->\n  (* Not funded *)\n  ~~(funded (state st)) ->\n  (* Balance is small: not reached the goal *)\n  balance st < (get_goal (state st)) ->\n  (* Block number exceeds the set number *)\n  get_max_block (state st) < block_num bc ->\n  (* Can emit message from b *)\n  exists (m : message),\n    sender m == b /\\\n    out (step_prot crowd_prot st bc m) = Some (Msg d crowd_addr b 0 ok_msg).\nProof.\nmove=>D Nf Nb Nm.\nexists (Msg 0 b crowd_addr claim_tag [::]); split=>//.\nrewrite /step_prot.\ncase: st D Nf Nb Nm =>id bal s/= D Nf Nb Nm.\nrewrite /apply_prot/=/claim_fun/=leqNgt Nm/= leqNgt Nb/=.\nrewrite /donated/= in D.\nmove/negbTE: Nf=>->/=; rewrite -(has_find [pred e | e.1 == b]) has_filter.\nmove/eqP: D=>D; rewrite D/=.\ncongr (Some _); congr (Msg _ _ _ _ _). \nelim: (backers s) D=>//[[a w]]bs/=; case:ifP; first by move/eqP=>->{a}/=_; case. \nby move=>X Hi H; move/Hi: H=><-. \nQed.\n*)\n\n(************************************************************************\n\n4. Can we have a logic that allows to express all these properties\ndeclaratively? Perhaps, we could do it in TLA?\n\n(This is going to be our future work.)\n\n************************************************************************)\n\nEnd Crowdfunding.\n", "meta": {"author": "rooibosriot", "repo": "scilla-coq-unclassy", "sha": "c2419e5a48258578ce25769419913acd5cab7319", "save_path": "github-repos/coq/rooibosriot-scilla-coq-unclassy", "path": "github-repos/coq/rooibosriot-scilla-coq-unclassy/scilla-coq-unclassy-c2419e5a48258578ce25769419913acd5cab7319/Contracts/Crowdfunding.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23765612787937967}}
{"text": "Require Export Structure.\n\nSection Dual.\nUniverse U.\n\nSection CoTop.\nContext (C: BotCategory: Type@{U}).\n\nDefinition CoTop_mixin: TopCategory.mixin_of (co C) :=\n  TopCategory.Mixin (co C) 0 (@from_zero C) (@from_zero_unique C).\n\nCanonical CoTop: TopCategory: Type@{U} :=\n  TopCategory.Pack (co C) CoTop_mixin.\nEnd CoTop.\n\nSection CoBot.\nContext (C: TopCategory: Type@{U}).\n\nDefinition CoBot_mixin: BotCategory.mixin_of (co C) :=\n  BotCategory.Mixin (co C) 1 (@to_one C) (@to_one_unique C).\n\nCanonical CoBot: BotCategory: Type@{U} :=\n  BotCategory.Pack (co C) CoBot_mixin.\nEnd CoBot.\n\nSection CoProd.\nContext (C: CoprodCategory: Type@{U}).\n\nProgram Definition CoProd_mixin: ProdCategory.mixin_of (co C) :=\n  ProdCategory.Mixin (co C) coprod (fun a b c => @merge C b c a) (@in1 C) (@in2 C) (fun a b c f g h => @merge_in C b c a f g h).\n\nCanonical CoProd: ProdCategory: Type@{U} :=\n  ProdCategory.Pack (co C) CoProd_mixin.\nEnd CoProd.\n\nSection CoCoprod.\nContext (C: ProdCategory: Type@{U}).\n\nProgram Definition CoCoprod_mixin: CoprodCategory.mixin_of (co C) :=\n  CoprodCategory.Mixin (co C) prod (fun a b c => @fork C c a b) (@π₁ C) (@π₂ C) (fun a b c f g h => @fork_pi C c a b f g h).\n\nCanonical CoCoprod: CoprodCategory: Type@{U} :=\n  CoprodCategory.Pack (co C) CoCoprod_mixin.\nEnd CoCoprod.\n\nSection TopCo.\nContext (C: Category: Type@{U}) (m: BotCategory.mixin_of (co C): Type@{U}).\nLet C' := BotCategory.Pack (co C) m.\n\nDefinition TopCo_mixin: TopCategory.mixin_of C :=\n  TopCategory.Mixin C (0: C') (@from_zero C') (@from_zero_unique C').\n\nDefinition TopCo: TopCategory: Type@{U} :=\n  TopCategory.Pack C TopCo_mixin.\nEnd TopCo.\n\nSection BotCo.\nContext (C: Category: Type@{U}) (m: TopCategory.mixin_of (co C): Type@{U}).\nLet C' := TopCategory.Pack (co C) m.\n\nDefinition BotCo_mixin: BotCategory.mixin_of C :=\n  BotCategory.Mixin C (1: C') (@to_one C') (@to_one_unique C').\n\nDefinition BotCo: BotCategory: Type@{U} :=\n  BotCategory.Pack C BotCo_mixin.\nEnd BotCo.\n\nSection ProdCo.\nContext (C: Category: Type@{U}) (m: CoprodCategory.mixin_of (co C): Type@{U}).\nLet C' := CoprodCategory.Pack (co C) m.\n\nProgram Definition ProdCo_mixin: ProdCategory.mixin_of C :=\n  ProdCategory.Mixin C (@coprod C') (fun a b c => @merge C' b c a) (@in1 C') (@in2 C') (fun a b c f g h => @merge_in C' b c a f g h).\n\nDefinition ProdCo: ProdCategory: Type@{U} :=\n  ProdCategory.Pack C ProdCo_mixin.\nEnd ProdCo.\n\nSection CoprodCo.\nContext (C: Category: Type@{U}) (m: ProdCategory.mixin_of (co C): Type@{U}).\nLet C' := ProdCategory.Pack (co C) m.\n\nProgram Definition CoprodCo_mixin: CoprodCategory.mixin_of C :=\n  CoprodCategory.Mixin C (@prod C') (fun a b c => @fork C' c a b) (@π₁ C') (@π₂ C') (fun a b c f g h => @fork_pi C' c a b f g h).\n\nDefinition CoprodCo: CoprodCategory: Type@{U} :=\n  CoprodCategory.Pack C CoprodCo_mixin.\nEnd CoprodCo.\n\nEnd Dual.\n", "meta": {"author": "adamAndMath", "repo": "Category", "sha": "1d230ee099a3ec7bd21306a404f38b2b3f3c3865", "save_path": "github-repos/coq/adamAndMath-Category", "path": "github-repos/coq/adamAndMath-Category/Category-1d230ee099a3ec7bd21306a404f38b2b3f3c3865/Instances/Dual.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2375940615285965}}
{"text": "(****************************************************************************)\n(* Copyright 2021 The Project Oak Authors                                   *)\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\nRequire Import Coq.Strings.String.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Init.Byte.\nRequire Import Coq.Lists.List.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import Cava.Util.BitArithmetic.\nRequire Import Cava.Util.BitArithmeticProperties.\nRequire Import Cava.Util.Byte.\nRequire Import Cava.Util.If.\nRequire Import Cava.Util.List.\nRequire Import Cava.Util.Nat.\nRequire Import Cava.Util.Tactics.\nRequire Import Cava.Types.\nRequire Import Cava.Expr.\nRequire Import Cava.ExprProperties.\nRequire Import Cava.Invariant.\nRequire Import Cava.Primitives.\nRequire Import Cava.Semantics.\nRequire Import HmacSpec.SHA256Properties.\nRequire Import HmacHardware.Sha256.\nRequire HmacSpec.SHA256.\nImport ListNotations.\n\nRequire Import coqutil.Tactics.autoforward.\nLtac autoforward_in db H ::=\n  let tmp := fresh H in\n  rename H into tmp;\n  let A := type of tmp in\n  pose proof ((ltac:(typeclasses eauto with db) : autoforward A _) tmp) as H;\n  (* Recently, this `move` was added in coqutil, which breaks this proof script,\n     because through destruct_one_match_hyp, it depends on the hypotheses order,\n     and the most straightforward way to fix the broken proofs requires too\n     much memory to work on CI *)\n  (* move H after tmp; *)\n  clear tmp.\n\nLemma step_rotr n (x : denote_type sha_word) :\n  step (rotr n) tt (x,tt) = (tt, SHA256.ROTR (N.of_nat n) x).\nProof.\n  cbv [rotr]. stepsimpl.\n  cbv [SHA256.ROTR SHA256.truncating_shiftl SHA256.w].\n  repeat (f_equal; try lia).\nQed.\nHint Rewrite @step_rotr using solve [eauto] : stepsimpl.\n\nLemma step_sha256_compress\n      (H : denote_type sha_digest)\n      (k w : denote_type sha_word) (t : nat) (W : list N) :\n  k = nth t SHA256.K 0%N ->\n  w = nth t W 0%N ->\n  step sha256_compress tt (H,(k,(w,tt)))\n  = (tt, SHA256.sha256_compress W (List.resize 0%N 8 H) t).\nProof.\n  intros. rewrite resize_map_nth. cbn [List.map seq].\n  subst. cbv [sha256_compress]. stepsimpl.\n  autorewrite with push_nth. reflexivity.\nQed.\nHint Rewrite @step_sha256_compress using solve [eauto] : stepsimpl.\n\nLemma step_sha256_message_schedule_update\n      (w0 w1 w9 w14 : denote_type sha_word) (t i : nat) msg :\n  w0 = nth (t-16) (SHA256Alt.W msg i) 0%N ->\n  w1 = nth (t-15) (SHA256Alt.W msg i) 0%N ->\n  w9 = nth (t-7) (SHA256Alt.W msg i) 0%N ->\n  w14 = nth (t-2) (SHA256Alt.W msg i) 0%N ->\n  (16 <= t < 64) ->\n  step sha256_message_schedule_update tt (w0, (w1, (w9, (w14, tt))))\n  = (tt, nth t (SHA256Alt.W msg i) 0%N).\nProof.\n  intros. cbv [sha256_message_schedule_update]. stepsimpl.\n  rewrite nth_W_alt by lia. destruct_one_match; [ lia | ].\n  repeat match goal with H : _ = nth ?n _ _ |- _ =>\n                         rewrite <-H end.\n  cbv [SHA256.add_mod SHA256.w]. apply f_equal.\n  cbv [SHA256.sigma1 SHA256.sigma0 SHA256.SHR].\n  cbv [N.of_nat Pos.of_succ_nat Pos.succ]. clear.\n  (* fully compute moduli *)\n  repeat match goal with |- context [(_ mod ?m)%N] =>\n                         progress compute_expr m end.\n  (* convert to Z, solve with Z.div_mod_to_equations *)\n  zify.\n  repeat rewrite Z.rem_mod_nonneg; Z.div_mod_to_equations; lia.\nQed.\nHint Rewrite @step_sha256_message_schedule_update using solve [eauto] : stepsimpl.\n\nLemma step_sha256_round_constants (round : denote_type sha_round) :\n  step sha256_round_constants tt (round, tt)\n  = (tt, nth (N.to_nat round) SHA256.K 0%N).\nProof. reflexivity. Qed.\nHint Rewrite @step_sha256_round_constants using solve [eauto] : stepsimpl.\n\n(* High-level representation for sha256_inner:\n   msg : message seen so far (padded)\n   i : block index\n   t : round number (compression loop)\n   inner_done : whether the computation for the current block is complete\n   cleared : boolean indicating whether the circuit has been cleared\n *)\nInstance sha256_inner_invariant\n  : invariant_for sha256_inner (list N * nat * nat * bool * bool) :=\n  fun (state : denote_type (sha_digest ** sha_block ** Bit ** sha_round))\n    repr =>\n    let '(current_digest, (message_schedule, (done, round))) := state in\n    let '(msg, i, t, inner_done, cleared) := repr in\n    (* inner_done matches the [done] bit *)\n    inner_done = done\n    (* ...and if we've been cleared, then we're in the reset state *)\n    /\\ (if cleared\n       then current_digest = SHA256.H0\n            /\\ done = true\n            /\\ t = 0\n            /\\ i = 0\n            /\\ msg = []\n       else\n         (* ...if we're not cleared, the current digest is the expected digest *)\n         let initial_digest :=\n             fold_left (SHA256Alt.sha256_step msg) (seq 0 i) SHA256.H0 in\n         current_digest = fold_left (SHA256.sha256_compress (SHA256Alt.W msg i))\n                                    (seq 0 t) initial_digest\n         (* ...and the message has (S i) blocks (1 block = 16 words) *)\n         /\\ S i * 16 = length msg\n      )\n    /\\ if done\n      then if cleared then t = 0 else t = 64\n      else\n        (* the round is < 64 *)\n        (round < 64)%N\n        (* ...and inner_round matches [round] *)\n        /\\ t = N.to_nat round\n        (* ...and the message schedule is the expected slice of the message *)\n        /\\ message_schedule = List.slice 0%N (SHA256Alt.W msg i) (t - 15) 16.\n\nInstance sha256_inner_specification\n  : specification_for sha256_inner (list N * nat * nat * bool * bool) :=\n  {| reset_repr := ([], 0%nat, 0%nat, true, true);\n     update_repr :=\n       fun (input : denote_type [Bit; sha_block; sha_digest; Bit])\n         repr =>\n         let '(block_valid, (block, (initial_digest, (clear,_)))) := input in\n         let '(msg, i, t, inner_done, cleared) := repr in\n         let updated_msg := msg ++ block in\n         if clear\n         then ([], 0%nat, 0%nat, true, true)\n         else if inner_done\n              then if block_valid\n                   then if cleared\n                        then\n                          (* start with i=0 *)\n                          (updated_msg, 0, 0, false, false)\n                        else\n                          (* starting new block *)\n                          (updated_msg, S i, 0, false, false)\n                   else\n                     (* unchanged *)\n                     (msg, i, t, inner_done, cleared)\n              else (msg, i, S t, t =? 63, false);\n     precondition :=\n       fun (input : denote_type [Bit; sha_block; sha_digest; Bit])\n         repr =>\n         let '(block_valid, (block, (initial_digest, (clear,_)))) := input in\n         let '(msg, i, t, inner_done, cleared) := repr in\n         if block_valid\n         then\n           let new_i := if cleared then 0 else S i in\n           (* a valid block is passed only if we're not busy *)\n           inner_done = true\n           (* ...and the initial digest is the digest up to (the new value of) i *)\n           /\\ initial_digest = fold_left (SHA256Alt.sha256_step (msg ++ block))\n                                        (seq 0 new_i) SHA256.H0\n           (* and the length of the block is 16 *)\n           /\\ length block = 16\n         else\n           if inner_done\n           then True (* no requirements; stay in the done state until block is valid *)\n           else\n             (* the initial digest is the digest up to i *)\n             initial_digest = fold_left (SHA256Alt.sha256_step msg)\n                                        (seq 0 i) SHA256.H0;\n     postcondition :=\n       fun (input : denote_type [Bit; sha_block; sha_digest; Bit])\n         repr (output : denote_type (sha_digest ** Bit)) =>\n         let '(block_valid, (block, (initial_digest, (clear,_)))) := input in\n         let '(msg, i, t, inner_done, cleared) := repr in\n         let new_done := if clear\n                         then true\n                         else if block_valid\n                              then false\n                              else if inner_done\n                                   then true\n                                   else t =? 63 in\n         exists output_value : denote_type sha_digest,\n           output = (output_value, new_done)\n           /\\ (* the output value is only meaningful in the case when we're done and not\n                cleared *)\n           (if cleared\n            then True (* no guarantees *)\n            else if clear\n                 then True (* no guarantees *)\n                 else if new_done\n                      then\n                        (* if the initial digest is correct, the output value\n                           matches the expected digest *)\n                        initial_digest = fold_left (SHA256Alt.sha256_step msg) (seq 0 i) SHA256.H0 ->\n                        output_value = fold_left (SHA256Alt.sha256_step msg) (seq 0 (S i)) SHA256.H0\n                      else True (* no guarantees *))\n  |}.\n\nLemma sha256_inner_invariant_at_reset : invariant_at_reset sha256_inner.\nProof.\n  simplify_invariant sha256_inner. repeat split.\nQed.\n\nLocal Hint Unfold sha256_inner_state : stepsimpl.\n\nLemma sha256_inner_invariant_preserved : invariant_preserved sha256_inner.\nProof.\n  simplify_invariant sha256_inner. cbn [absorb_any].\n  simplify_spec sha256_inner.\n  intros (block_valid, (block, (initial_digest, (clear, [])))).\n  intros (current_digest, (message_schedule, (done, round))).\n  intros ((((msg, i), t), inner_done), cleared).\n  intros; logical_simplify; subst.\n  cbv [sha256_inner K]. cbn [negb]. stepsimpl.\n  repeat (destruct_pair_let; cbn [fst snd]).\n  autorewrite with tuple_if; cbn [fst snd].\n  (* destruct cases for [clear] *)\n  destruct clear; logical_simplify; [ tauto | ].\n  (* destruct cases for [block_valid] *)\n  destruct block_valid; logical_simplify; subst;\n    [ destruct cleared; logical_simplify; subst;\n      pull_snoc; natsimpl; push_length;\n      rewrite ?slice0_W_alt by length_hammer;\n      ssplit; (lia || reflexivity) | ].\n  (* destruct cases for [done] *)\n  destruct done; logical_simplify; subst; boolsimpl;\n    [ ssplit; auto; tauto | ].\n  (* destruct cases for [cleared] *)\n  destruct cleared; logical_simplify; subst; boolsimpl;\n    [ destr (round =? 63)%N;\n      ssplit; repeat destruct_one_match; lia | ].\n  destr (N.to_nat round =? 63);\n    (destr (round =? 63)%N; try lia; [ ]); subst;\n      [ ssplit; lazymatch goal with\n                | |- context [sha256_compress] => idtac\n                | |- _ => lia\n                end;\n      (* handle case involving last compression step *)\n      subst; destruct_one_match; try lia; [ ];\n      erewrite step_sha256_compress with (t:=63)\n      by (push_resize; push_nth; reflexivity);\n      cbn [fst snd]; push_resize;\n      rewrite seq_snoc with (len:=63); rewrite fold_left_app;\n      reflexivity | ].\n\n  (* For remaining cases, the new [done] is always 0 *)\n  cbn [N.lor N.eqb].\n  (* destruct case statements *)\n  repeat first [ discriminate\n               | lia\n               | destruct_one_match_hyp\n               | destruct_one_match ].\n  all:try (rewrite (N.mod_small _ (2 ^ N.of_nat 7))\n            by (change (2 ^ N.of_nat 7)%N with 128%N; lia)).\n  all:push_resize; push_nth.\n  all:repeat match goal with\n             | |- context [(?x <? ?y)] =>\n               destr (x <? y); try lia; [ ]\n             | |- context [(?x =? ?y)] =>\n               destr (x =? y); try lia; [ ]\n             end.\n  all:natsimpl.\n  all:ssplit;\n    lazymatch goal with\n    | |- ?x = ?x => reflexivity\n    | |- (_ < _)%N => lia\n    | |- @eq nat _ _ => length_hammer\n    | |- True => tauto\n    | _ => idtac\n    end.\n  (* solve subgoals about compression *)\n  all:\n    lazymatch goal with\n    | |- context [sha256_compress] =>\n      erewrite step_sha256_compress with (t:=N.to_nat round) by (f_equal; lia);\n        cbn [fst snd]; pull_snoc; rewrite ?resize_noop by (symmetry; length_hammer);\n          try reflexivity\n    | |- _ => idtac\n    end.\n\n  (* remaining subgoals should all be about message schedule: solve those *)\n  all:lazymatch goal with\n        | |- context [sha256_message_schedule_update] =>\n          erewrite step_sha256_message_schedule_update with (t:=(N.to_nat round+1))\n            by lazymatch goal with\n               | |- nth _ _ _ = nth _ _ _ => f_equal; lia\n               | _ => lia\n               end; cbn [fst snd];\n            lazymatch goal with\n            | |- context [List.slice ?d ?ls ?start ?len ++ [nth ?n ?ls ?d]] =>\n              replace n with (start + len) by lia\n            end; rewrite slice_snoc, tl_slice; f_equal; lia\n      end.\nQed.\n\nLemma sha256_inner_output_correct : output_correct sha256_inner.\nProof.\n  simplify_invariant sha256_inner. cbn [absorb_any].\n  simplify_spec sha256_inner.\n  intros (block_valid, (block, (initial_digest, (clear, [])))).\n  intros (current_digest, (message_schedule, (done, round))).\n  intros ((((msg, i), t), inner_done), cleared).\n  intros. logical_simplify. subst. cbn [fst snd] in *.\n  cbv [sha256_inner K]. stepsimpl.\n  repeat (destruct_pair_let; cbn [fst snd]).\n  autorewrite with tuple_if; cbn [fst snd].\n  stepsimpl. push_resize.\n  (* some general-purpose simplification *)\n  pull_snoc; natsimpl.\n  eexists. ssplit; [ | ].\n  { apply f_equal2; [ reflexivity | ].\n    (* prove that done bit matches spec *)\n    boolsimpl. destr clear;[ reflexivity | ].\n    destr block_valid; [ reflexivity | ].\n    destr done; boolsimpl; [ reflexivity | ].\n    logical_simplify; subst.\n    destr (N.to_nat round =? 63); destr (round =? 63)%N; lia. }\n  (* destruct cases for [cleared] *)\n  destruct cleared; logical_simplify; subst; [ tauto | ].\n  (* destruct cases for [clear] *)\n  destruct clear; logical_simplify; subst; [ tauto | ].\n  (* destruct cases for [block_valid] *)\n  destruct block_valid; logical_simplify; subst;\n    [ push_resize; rewrite ?resize_noop by (symmetry; length_hammer);\n      try reflexivity | ].\n  (* destruct cases for [done] *)\n  destruct done; logical_simplify; subst; boolsimpl;\n    [ intros; subst; rewrite !resize_noop by (symmetry; length_hammer);\n      reflexivity | ].\n  push_resize; push_nth.\n  erewrite step_sha256_compress with (t:=N.to_nat round)\n    by (repeat destruct_one_match;\n        repeat destruct_one_match_hyp; f_equal; lia).\n  cbn [fst snd]. push_resize.\n  rewrite ?resize_noop by (symmetry; length_hammer).\n  destr (N.to_nat round =? 63); destr (round =? 63)%N; try lia; [ ].\n  intros; subst. unfold SHA256Alt.sha256_step.\n  rewrite seq_snoc with (len:=63); rewrite fold_left_app.\n  reflexivity.\nQed.\n\nExisting Instances sha256_inner_invariant_at_reset sha256_inner_invariant_preserved\n         sha256_inner_output_correct.\nGlobal Instance sha256_inner_correctness : correctness_for sha256_inner.\nProof. constructor; typeclasses eauto. Defined.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/silveroak-opentitan/hmac/hw/Sha256InnerProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.237594056025101}}
{"text": "(* Do not edit this file, it was generated automatically *)\n(** Heavily annotated for a tutorial introduction. *)\n\n(** First, import the entire Floyd proof automation system, which includes\n ** the VeriC program logic and the MSL theory of separation logic**)\nRequire Import VST.floyd.proofauto.\n\n(** Import the [reverse.v] file, which is produced by CompCert's clightgen\n ** from reverse.c.   The file reverse.v defines abbreviations for identifiers\n ** (variable names, etc.) of the C program, such as _head, _reverse.\n ** It also defines \"prog\", which is the entire abstract syntax tree\n ** of the C program *)\nRequire Import VST.progs64.reverse.\n\n(* The C programming language has a special namespace for struct\n** and union identifiers, e.g., \"struct foo {...}\".  Some type-based operators\n** in the program logic need access to an interpretation of this namespace,\n** i.e., the meaning of each struct-identifier such as \"foo\".  The next\n** line (which looks identical for any program) builds this\n** interpretation, called \"CompSpecs\" *)\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\n\n(** Calculate the \"types-of-global-variables\" specification\n ** directly from the program *)\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n(** A convenience definition *)\nDefinition t_struct_list := Tstruct _list noattr.\n\n(** Inductive definition of linked lists *)\nFixpoint listrep (sigma: list val) (x: val) : mpred :=\n match sigma with\n | h::hs => \n    EX y:val, \n      data_at Tsh t_struct_list (h,y) x  *  listrep hs y\n | nil => \n    !! (x = nullval) && emp\n end.\n\nArguments listrep sigma x : simpl never.\n\n(** Whenever you define a new spatial operator, such as\n ** [listrep] here, it's useful to populate two hint databases.\n ** The [saturate_local] hint is a lemma that extracts\n ** pure propositional facts from a spatial fact.\n ** The [valid_pointer] hint is a lemma that extracts a\n ** valid-pointer fact from a spatial lemma.\n **)\n\nLemma listrep_local_facts:\n  forall sigma p,\n   listrep sigma p |--\n   !! (is_pointer_or_null p /\\ (p=nullval <-> sigma=nil)).\nProof.\nintros.\nrevert p; induction sigma; \n  unfold listrep; fold listrep; intros. entailer!. intuition.\nIntros y. entailer!.\nsplit; intro. subst p. destruct H; contradiction. inv H2.\nQed.\n\n#[export] Hint Resolve listrep_local_facts : saturate_local.\n\nLemma listrep_valid_pointer:\n  forall sigma p,\n   listrep sigma p |-- valid_pointer p.\nProof.\n destruct sigma; unfold listrep; fold listrep; intros; Intros; subst.\n auto with valid_pointer.\n Intros y.\n apply sepcon_valid_pointer1.\n apply data_at_valid_ptr; auto.\n simpl;  computable.\nQed.\n\n#[export] Hint Resolve listrep_valid_pointer : valid_pointer.\n\n(** Specification of the [reverse] function.  It characterizes\n ** the precondition required for calling the function,\n ** and the postcondition guaranteed by the function.\n **)\nDefinition reverse_spec :=\n DECLARE _reverse\n  WITH sigma : list val, p: val\n  PRE  [ tptr t_struct_list ]\n     PROP ()\n     PARAMS (p)\n     SEP (listrep sigma p)\n  POST [ (tptr t_struct_list) ]\n    EX q:val,\n     PROP () RETURN (q)\n     SEP (listrep(rev sigma) q).\n\n(** The global function spec, characterizing the\n ** preconditions/postconditions of all the functions\n ** that your proved-correct program will call. \n ** Normally you include all the functions here, but\n ** in this tutorial example we include only one. *)\nDefinition Gprog : funspecs :=[ reverse_spec ].\n\n(** For each function definition in the C program, prove that the\n ** function-body (in this case, f_reverse) satisfies its specification\n ** (in this case, reverse_spec).\n **)\nLemma body_reverse: semax_body Vprog Gprog\n                                    f_reverse reverse_spec.\nProof.\n(** The start_function tactic \"opens up\" a semax_body\n ** proof goal into a Hoare triple. *)\nstart_function.\n(** For each assignment statement, \"symbolically execute\" it\n ** using the forward tactic *)\nforward.  (* w = NULL; *)\nforward.  (* v = p; *)\n(** To prove a while-loop, you must supply a loop invariant,\n ** in this case (EX s1  PROP(...)LOCAL(...)(SEP(...)).  *)\nforward_while\n   (EX s1: list val, EX s2 : list val, \n    EX w: val, EX v: val,\n     PROP (sigma = rev s1 ++ s2)\n     LOCAL (temp _w w; temp _v v)\n     SEP (listrep s1 w; listrep s2 v)).\n(** The forward_while tactic leaves four subgoals,\n ** which we mark with * (the Coq \"bullet\") *)\n* (* Prove that precondition implies loop invariant *)\nExists (@nil val) sigma nullval p.\nentailer!.\nunfold listrep.\nentailer!.\n* (* Prove that loop invariant implies typechecking of loop condition *)\nentailer!.\n* (* Prove that loop body preserves invariant *)\ndestruct s2 as [ | h r].\n - unfold listrep at 2. \n   Intros. subst. contradiction.\n - unfold listrep at 2; fold listrep.\n   Intros y.\n   forward. (* t = v->tail *)\n   forward. (* v->tail = w; *)\n   forward. (* w = v; *)\n   forward. (* v = t; *)\n   (* At end of loop body; reestablish invariant *)\n   entailer!.\n   Exists (h::s1,r,v,y).\n   entailer!.\n   + simpl. rewrite app_ass. auto.\n   + unfold listrep at 3; fold listrep.\n     Exists w. entailer!.\n* (* after the loop *)\nforward.  (* return w; *)\nExists w; entailer!.\nrewrite (proj1 H1) by auto.\nunfold listrep at 2; fold listrep.\nentailer!.\nrewrite <- app_nil_end, rev_involutive.\nauto.\nQed.\n\n(** See the file [progs/verif_reverse.v] for an alternate\n ** proof of this function, using a general theory of\n ** list segments.  That file also has proofs of the\n ** sumlist function, the main function, and the\n ** [semax_func] theorem that ties all the functions together\n **)\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs64/verif_reverse2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2375221772078723}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\n(*****************************************************************************)\n(*          Projet Formel - Calculus of Inductive Constructions V5.10        *)\n(*****************************************************************************)\n(*\t\t\t\t\t\t\t\t\t     *)\n(*\t                    Category ONE                  \t\t     *)\n(*\t\t\t\t\t\t\t\t\t     *)\n(*****************************************************************************)\n(*\t\t\t\t\t\t\t\t\t     *)\n(*                     A. SAIBI\t  May 95                  \t\t     *)\n(*\t\t\t\t\t\t\t\t\t     *)\n(*****************************************************************************)\n\n\nRequire Export ONE.\nRequire Export Functor.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n(* !C : C -> One *)\n\nSection Fun_One.\n\nVariable C : Category.\n\nDefinition FunOne_ob (a : C) := Obone.\n\n Section funone_map_def.\n\n Variable a b : C.\n\n Definition FunOne_mor (f : a --> b) : FunOne_ob a --> FunOne_ob b :=\n   Id_Obone.\n\n Lemma FunOne_map_law : Map_law FunOne_mor.\n Proof.\n unfold Map_law, FunOne_mor in |- *.\n intros; apply Refl.\n Qed.\n\n Canonical Structure FunOne_map := Build_Map FunOne_map_law.\n\n End funone_map_def. \n\nLemma FunOne_comp_law : Fcomp_law FunOne_map.\nProof.\nunfold Fcomp_law in |- *; simpl in |- *.\nunfold Equal_One_mor in |- *; auto.\nQed.\n\nLemma FunOne_id_law : Fid_law FunOne_map.\nProof.\nunfold Fid_law in |- *; simpl in |- *.\nunfold Equal_One_mor in |- *; auto.\nQed.\n\nCanonical Structure FunOne := Build_Functor FunOne_comp_law FunOne_id_law.\n\nEnd Fun_One.\n", "meta": {"author": "JasonGross", "repo": "category-coq-experience-tests", "sha": "f9949ede618788fd051fe8327f997ee683388e49", "save_path": "github-repos/coq/JasonGross-category-coq-experience-tests", "path": "github-repos/coq/JasonGross-category-coq-experience-tests/category-coq-experience-tests-f9949ede618788fd051fe8327f997ee683388e49/ConCaT/CATEGORY_THEORY/ADJUNCTION/CCC/FunOne.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2375221772078723}}
{"text": "(** This file was written by Colm Bhandal, PhD student, Foundations and Methods group,\nSchool of Computer Science and Statistics, Trinity College, Dublin, Ireland.*)\n\n(***************************** Standard Imports *****************************)\n\nRequire Import Reals.\nRequire Import List.\nRequire Import ComhCoq.Extras.LibTactics.\n\n(***************************** Specialised Imports *****************************)\n\nRequire Import ComhCoq.StandardResults.\nRequire Import ComhCoq.ComhBasics.\nRequire Import ComhCoq.LanguageFoundations.\nRequire Import ComhCoq.SoftwareLanguage.\nRequire Import ComhCoq.InterfaceLanguage.\nRequire Import ComhCoq.ModeStateLanguage.\nRequire Import ComhCoq.EntityLanguage.\nRequire Import ComhCoq.NetworkLanguage.\nRequire Import ComhCoq.ProtAuxDefs.\nRequire Import ComhCoq.ProtAuxResults.\nRequire Import ComhCoq.EntAuxDefs.\nRequire Import ComhCoq.EntAuxResults.\nRequire Import ComhCoq.GenTacs.\n\n(*IDEA: MIGRATE SOME OF THE CONTENTS OF THE FILE OVER VARIUOS NAB (NET-AUX-BASICS)\nPREFIXED FILES, THEN *EXPORT* THEM HERE, SO THAT THIS FILE JUST ACTS AS A\nHUB RELAYING THE CONTENTS OF THOSE FILES. WHY? IT'S GETTING JOLLY BIG!*)\n\n(********************************* Some basic definitions *********************************)\n\nInductive initialNet : Network -> Prop :=\n  | initNtNil : initialNet []\n  | initNtCons e n : initialEnt e -> initialNet n ->\n    initialNet (e :: n).\n  \nInductive reachableNet : Network -> Type :=\n  | reachNetInit (n : Network) : initialNet n -> reachableNet n\n  | reachNetDisc (n n' : Network) (a : ActDiscNet) : reachableNet n ->\n    n -NA- a -NA> n' -> reachableNet n'\n  | reachNetDel (n n' : Network) (d : Delay) : reachableNet n ->\n    n -ND- d -ND> n' -> reachableNet n'.\n\nLemma link_net_prot_reach n p l h k i :\n  reachableNet n ->  [|p, l, h, k|] @ i .: n -> reachableProt p.\n  Admitted. (*6*)\n(**Proof: Intermediate results from net to ent and ent to prot.*)\n\n\nLtac link_netprotreach_tac U :=\n  match goal with\n  [H : reachableNet ?n, H0 : [|_, _, _, _|] @ _ .: ?n |- _] =>\n  let U1 := fresh U in lets U1 : link_net_prot_reach H H0\n  end.\n\nParameter currModeNet : Mode -> nat -> Network -> Prop.\n(**Idea: Lift currModeEnt*)\n\n(*transGuard t i n says that the entity at position i in n is transitioning\n from one mode to another and the guard on the transition is t.*)\nInductive transGuard (t : Time) (i : nat) (n : Network) : Prop :=\n  | tgWitness (p : ProcTerm) (l : Position) (h : Interface) (m m' : Mode) :\n    [| p , l , h , <| m , m' , t |> |] @ i .: n -> transGuard t i n.\n\nParameter nextModeNet : Mode -> nat -> Network -> Prop.\n(**Idea: Lift nextModeEnt*)\n\n(*inPosNet l i n says that the entity number i in n has position l.*)\nInductive inPosNet (l : Position) (i : nat) (n : Network) : Prop :=\n  | ipWitness (p : ProcTerm) (h : Interface) (k : ModeState) :\n    [| p , l , h , k |] @ i .: n -> inPosNet l i n.\n\n(*dist2d i i' n x says that the entities i and i' are separated by x in n.*)\nInductive distNet (i i' : nat) (n : Network) : Distance -> Prop :=\n  | dnWitness (l l' : Position) : inPosNet l i n -> inPosNet l' i' n ->\n    distNet i i' n (distFun l l').\t\n\n(*outgoing v t i n says that the message v with timestamp t is in the output queue of the interface component of the entity i in the network n.*)\nInductive outgoing (v : list BaseType) (t : Time) (i : nat) (n : Network) : Prop :=\n  | ogWitness (p : ProcTerm) (l : Position) (li : InputList) (lo : OutputList) (ln : NotifList) (k : ModeState) :\n    [| p , l , (mkInterface li lo ln) , k |] @ i .: n -> In (<( v , t )>) (outList lo) -> outgoing v t i n.\n\n(*incomingNet v i n says that the message v is in the input queue of the interface component of the entity i in the network n.\nNote: Even though the input queue is effectively untimed messages, it is modelled as a timed list, with \ntimestamps simply set to 0, hence \"v in Li\" becomes \"<v, 0> in Li\" to be more pedantic about it.*)\nInductive incomingNet (v : list BaseType) (i : nat) (n : Network) : Prop :=\n  | icWitness (p : ProcTerm) (l : Position) (li : InputList) (lo : OutputList) (ln : NotifList) (k : ModeState) :\n    [| p , l , (mkInterface li lo ln) , k |] @ i .: n -> In (<( v , zeroTime )>) (inList li) -> incomingNet v i n.\n\n\n(*incomingNetNotif v t i n says that the message v with timestamp t is in the\nnotification queue of the interface component of the entity i in the network n.*)\nInductive incomingNetNotif (v : list BaseType) (t : Time) (i : nat) (n : Network) : Prop :=\n  | icnWitness (p : ProcTerm) (l : Position) (li : InputList) (lo : OutputList) (ln : NotifList) (k : ModeState) :\n    [| p , l , (mkInterface li lo ln) , k |] @ i .: n -> In (<( v , t )>) (notifList ln) -> incomingNetNotif v t i n.\n\t\t\t \nInductive mState_in_net (k : ModeState) (i : nat) (n : Network) : Prop :=\n  minet (p : ProcTerm) (l : Position) (h : Interface) :\n  [|p, l, h, k|] @ i .: n -> mState_in_net k i n.\n\n\n\n(********************************* Lifting Protocol Predicates *********************************)\n\n(**The lifting function we use to lift predicates from the protocol level to the\nentity level.*)\nInductive liftEntNet (X : Entity -> Prop) (i : nat) (n : Network) : Prop :=\n  | lenWitness (e : Entity) : X e -> e @ i .: n -> liftEntNet X i n.\n\n(*----------------Simple Lifted Predicates----------------*)\n\n(**Broadcast*)\nDefinition bcWaitStateNet m x := liftEntNet (bcWaitStateEnt m x).\nDefinition sleepingStateNet := liftEntNet sleepingStateEnt.\nDefinition bcReadyStateNet m l := liftEntNet (bcReadyStateEnt m l).\n\n\n(**Overlap*)\nDefinition dormantStateNet := liftEntNet dormantStateEnt.\nDefinition tfsStartStateNet := liftEntNet tfsStartStateEnt.\nDefinition initStateNet m := liftEntNet (initStateEnt m).\nDefinition ovWaitStateNet m t x y := liftEntNet (ovWaitStateEnt m t x y).\nDefinition ovReadyStateNet m t l := liftEntNet (ovReadyStateEnt m t l).\nDefinition switchCurrStateNet := liftEntNet switchCurrStateEnt.\nDefinition switchListenStateNet := liftEntNet switchListenStateEnt.\nDefinition switchBcStateNet m := liftEntNet (switchBcStateEnt m).\nDefinition tfsCurrStateNet := liftEntNet tfsCurrStateEnt.\nDefinition tfsBcStateNet := liftEntNet tfsBcStateEnt.\nDefinition tfsListenStateNet := liftEntNet tfsListenStateEnt.\nDefinition pausedStateNet := liftEntNet pausedStateEnt.\nDefinition tfsNextStateNet m := liftEntNet (tfsNextStateEnt m).\n\n(**Listener*)\nDefinition listeningStateNet := liftEntNet listeningStateEnt.\nDefinition currCompStateNet m'' r := liftEntNet (currCompStateEnt m'' r).\nDefinition badOvlpStateNet := liftEntNet badOvlpStateEnt.\nDefinition rangeBadStateNet m := liftEntNet (rangeBadStateEnt m).\nDefinition currEqStateNet m m'' := liftEntNet (currEqStateEnt m m'').\n\n\n(*----------------Compound Lifted Predicates----------------*)\n\n\n(**Broadcast*)\nDefinition broadcastStateNet :=  liftEntNet broadcastStateEnt.\n\n(**Overlap*)\nDefinition overlapStateNet := liftEntNet overlapStateEnt.\nDefinition tfsStateNet := liftEntNet tfsStateEnt.\nDefinition nextSinceStateNet := liftEntNet (nextSinceStateEnt).\nDefinition switchStateNet := liftEntNet switchStateEnt.\n\n(**Listener*)\nDefinition listenerStateNet := liftEntNet listenerStateEnt.\nDefinition ovAbortStateNet := liftEntNet ovAbortStateEnt.\n\n\n(********************************* State Predicate Results *********************************)\n\nConjecture tfsStateNet_dec : forall (i : nat) (n : Network), decidable (tfsStateNet i n).\n(**Proof: Obvious*)\n\nConjecture tfsCurrNet_dec : forall (i : nat) (n : Network),\n  decidable (tfsCurrStateNet i n).\n(**Proof: Obvious*)\n\n(*Pre-requisite: some sort of lifting tactic*)\nLemma tfsCurrStateNet_bktrk_net : forall (n n' : Network) (i : nat) (a : ActDiscNet),\n  tfsCurrStateNet i n' -> n -NA- a -NA> n' ->\n  tfsCurrStateNet i n \\/\n  (exists m mF, exists p,\n  tfsNextStateNet m i n /\\ failSafe mF /\\\n  mState_in_net (<| m, mF, modeTransTime m mF p |>) i n'). Admitted. (*6*)\n(**Proof: Lift Back tracking and inter component relationships*)  \n\n(*Pre-requisite: some sort of lifting tactic- maybe a generic lifting tactic taking\nany predicate over a ProcTerm and lifting it to work over a network predicate?*)\nConjecture tfsCurrState_del_pres_net : forall (n n' : Network) (d : Delay) (i : nat),\n  n -ND- d -ND> n' ->\n  (tfsCurrStateNet i n <-> tfsCurrStateNet i n').\n(**Proof: #del-pres-fwd-net #del-pres-bkwd-net*)\n\n(*The only two possibilities for a change in mode state as per a discrete\ntransition are the standard mode switch or the mode switch to fail safe.*)\nLemma mState_switch_states : forall (n n' : Network) (i : nat)\n  (a : ActDiscNet) (k k' : ModeState), reachableNet n -> k <> k' ->\n  n -NA- a -NA> n' -> mState_in_net k i n -> mState_in_net k' i n' ->\n  (tfsCurrStateNet i n /\\ tfsBcStateNet i n') \\/\n  (switchCurrStateNet i n /\\ switchListenStateNet i n'). Admitted. (*3*)\n(**Proof: The mState_in_net predicates can be taken apart to show that there's an entity in the network. Then because the\nnetwork is reachable, the software component of this entity is a protocolState process. Also, it can be shown from the semantics of\nentities that the only law (what about init?) that changes the mode state is that in which the software component outputs on mCurr.\nBrute force analysis of the possible states of each 3 components of the softare component show that the only matching cases for this are\nthe two disjuncts. That is, the only capability a protocol process has of writing on mCurr is from the overlap component in those specific\nstates.*)\n\nConjecture tfsState_del_pres_net : forall (n n' : Network) (i : nat) (d : Delay),\n  n -ND- d -ND> n' -> (tfsStateNet i n <-> tfsStateNet i n').\n(**Proof: #del-pres-fwd-net #del-pres-bkwd-net*)\n\nLemma switch_states_mState : forall (n n' : Network) (i : nat) (a : ActDiscNet)\n  (m : Mode), n -NA- a -NA> n' -> switchCurrStateNet i n ->\n  switchListenStateNet i n' -> nextModeNet m i n -> currModeNet m i n'. Admitted. (*3*)\n(**Proof: Tracking shows us that the action must be tau, composed of an output from the software process on mCurr and an input\non the same by the mode state. Then it can be shown separately that an input on the mode state that is nextMode m yields a mode\nstate that it currMode m. Which can be lifted to currModeNet.*)\n\n(** A network transition which sees a software component of some entity\ntransform to a different software term is necessarily a tau transition.*)\nLemma procNeq_tau_net p p' l l' h h' k k' n n' a i :\n  [|p, l, h, k|] @ i .: n -> [|p', l', h', k'|] @ i .: n' ->\n  n -NA- a -NA> n' -> p <> p' -> a = anTau. Admitted. (*7*)\n\n(** The action linking a change from switchCurr to switchListen is always a tau.*)\nLemma switchCurr_listen_trans_tau (n n' : Network) (a : ActDiscNet) (i : nat) :\n  n -NA- a -NA> n' -> switchCurrStateNet i n -> switchListenStateNet i n' ->\n  a = anTau. introz U.\n  (*First of all, let's set up the fact that there are entities with unequal software\n  components.*)\n  state_pred_net_destr U0. state_pred_net_destr U1.\n  assert (p <> p0). unfold not; intro. subst.\n  (*The rest follows from a more general result that if the software component changes state, then\n  the action must be a tau. This in turn is true because all the other transitions preserve the\n  software process- this more general result should be simple enough to prove*)\n  Focus 2.\n  eapply procNeq_tau_net. apply H0.\n  eassumption. eassumption. eassumption.\n  (*Solve the remaining goal by state-pred-elim and remove Focus*)\n  Admitted.\n\n(*LOCAL TIDY*)\n\nLemma tfsStart_tfs_net i n :\n  tfsStartStateNet i n -> tfsStateNet i n. Admitted. (*#tfsNetLift #complexNetLift*)\n\nLemma tfsNext_tfs_net m i n :\n  tfsNextStateNet m i n -> tfsStateNet i n. Admitted. (*#tfsNetLift #complexNetLift*)\n\nLemma tfsCurr_tfs_net i n :\n  tfsCurrStateNet i n -> tfsStateNet i n. Admitted. (*#tfsNetLift #complexNetLift*)\n\nLemma tfsBc_tfs_net i n :\n  tfsBcStateNet i n -> tfsStateNet i n. Admitted. (*#tfsNetLift #complexNetLift*)\n\nLemma tfsListen_tfs_net i n :\n  tfsListenStateNet i n -> tfsStateNet i n. Admitted. (*#tfsNetLift #complexNetLift*)\n\n(** The following three tactics are mostly simply auxiliaries to the main\nresult of fwd_track_net_tac.*)\n(*Applies eexists up to 5 times (or not at all) before applying t- until\nthe application works.*)\nLtac first_eexists_5 t := first [t | (do 1 eexists);t | (do 2 eexists);t |\n  (do 3 eexists);t | (do 4 eexists);t | (do 5 eexists);t].\nLtac econstr_easssump := econstructor; eassumption.\nLtac first_ex_econ_eass := first_eexists_5 econstr_easssump.\n\n(** RE is the entity level result upon which this tactic works. Essentially,\nthis tactic lifts RE from the entity to the network level. Note that the tactic\nassumes a disjunctive goal of two branches and may not work otherwise.*)\nLtac fwd_track_net_tac RE :=\n  let U := fresh in let U0 := fresh in\n  (*Destruct a load of things and set up the link*)\n  intros U U0; destruct U0;\n  let e' := fresh \"e'\" in let b := fresh \"b\" in\n  let LNE := fresh \"LNE\" in\n  link_netentdiscfwd_tac e' b LNE;\n  (*The case of equality of entities is easy, we just substitute.*)\n  [subst; left | match goal with [LNE1 : _ -EA- b ->> e', e : Entity,\n  H0 : _ ?e |- _] =>\n  (*Apply an underlying (lower-level) result*)\n  lets LOW : RE LNE1 H0;\n  or_flat; ex_flat; [left | right] end];\n  first_ex_econ_eass.\n\nLemma tfsStart_next_net n n' a i :\n  n -NA- a -NA> n' -> tfsStartStateNet i n ->\n  tfsStartStateNet i n' \\/ exists m, tfsNextStateNet m i n'.\n  fwd_track_net_tac tfsStart_next_ent. Qed.\n\nLemma tfsNext_next_net m n n' a i :\n  n -NA- a -NA> n' -> tfsNextStateNet m i n ->\n  tfsNextStateNet m i n' \\/ tfsCurrStateNet i n'.\n  fwd_track_net_tac tfsNext_next_ent. Qed.\n\nLemma tfsCurr_next_net n n' a i :\n  n -NA- a -NA> n' -> tfsCurrStateNet i n ->\n  tfsCurrStateNet i n' \\/ tfsBcStateNet i n'.\n  fwd_track_net_tac tfsCurr_next_ent. Qed.\n\nLemma tfsBc_next_net n n' a i :\n  n -NA- a -NA> n' -> tfsBcStateNet i n ->\n  tfsBcStateNet i n' \\/ tfsListenStateNet i n'.\n  fwd_track_net_tac tfsBc_next_ent. Qed.\n\nLemma tfsListen_next_net n n' a i :\n  n -NA- a -NA> n' -> tfsListenStateNet i n ->\n  tfsListenStateNet i n' \\/ dormantStateNet i n'.\n  fwd_track_net_tac tfsListen_next_ent. Qed.\n\nLemma rangeBad_next_net m m'' i n n' a :\n  n -NA- a -NA> n' -> rangeBadStateNet m'' i n -> currModeNet m i n ->\n  rangeBadStateNet m'' i n' \\/ currEqStateNet m m'' i n'.\n  (*Proof: If it wasn't for the currModeNet entanglement, you'd just be able\n  to do: fwd_track_net_tac rangeBad_next_ent, but something else needs to be\n  done to account for this extra little feature of the proof.*)\n  Admitted. (*D- rangeBad_next_ent*)\n\nLemma badOvlp_next_net i n n' a :\n  n -NA- a -NA> n' -> badOvlpStateNet i n ->\n  badOvlpStateNet i n' \\/ listeningStateNet i n'.\n  Admitted. (*D- badOvlp_next_ent*)\n(*Proof: fwd_track_net_tac badOvlp_next_ent*)\n\nLtac netState_auto_pre := match goal with [U : [|_, _, _, _|] = _,\n  U1 : _ $||$ _ $||$ _ = _ |- _] =>\n  eapply lenWitness;[ | eassumption];\n  rewrite <- U; eapply lifpe; rewrite <- U1 end; constructor.\n\n(** Assume a network state predicate as the goal, and enough information in the\nhypothesis to prove it: an entInNet, an equality between that entity and its\nvarious components, and an equality between a process triple and the process of\nthat entity. Then this tactic should solve the goal.*)\nLtac netState_auto_tac :=\n  netState_auto_pre; eassumption.\n\nLemma tfsState_elim_net i n :\n  tfsStateNet i n -> tfsStartStateNet i n \\/\n  (exists m, tfsNextStateNet m i n) \\/\n  tfsCurrStateNet i n \\/ tfsBcStateNet i n \\/\n  tfsListenStateNet i n. intro. inversion H. inversion H0.\n  inversion H2. inversion H4.\n  left. netState_auto_tac.\n  right. left. eexists. netState_auto_tac.\n  right. right. left. netState_auto_tac.\n  right. right. right. left. netState_auto_tac.\n  right. right. right. right. netState_auto_tac.\n  Qed.\n\nLemma tfsListen_failSafe_net m i n :\n  tfsListenStateNet i n -> currModeNet m i n -> failSafe m.\n(*Proof: Similar result for tfsBc, and one for tfsCurr but for the next mode\nrather than the curr mode- perhaps inter-component results will be lifted\nfor these?*) Admitted. (*#inter-component-lift-net*)\n\n(*-LOCAL TIDY*)\n\nLemma tfs_currMode_disc_pres (n n' : Network) (a : ActDiscNet) (i : nat) (m : Mode) :\n  n -NA- a -NA> n' -> currModeNet m i n -> ~ failSafe m ->\n  tfsStateNet i n -> tfsStateNet i n'. introz U.\n  (*Destruct the tfs state into its components and apply an array of\n  network level fwd-tracking results.*)\n  apply tfsState_elim_net in U2. or_flat; ex_flat; [ |\n  rename H into OR | ..];[eapply tfsStart_next_net in OR |\n  eapply tfsNext_next_net in OR | eapply tfsCurr_next_net in OR |\n  eapply tfsBc_next_net in OR | ];\n  try eassumption; or_flat; ex_flat.\n  (*Now we're left with a nubmber of cases where, in the hypotheses,\n  you have that some tfs<..>StateNet holds. From here, we use lifting\n  results previously defined*)\n  apply tfsStart_tfs_net; assumption.\n  eapply tfsNext_tfs_net; eassumption.\n  eapply tfsNext_tfs_net; eassumption.\n  apply tfsCurr_tfs_net; assumption.\n  apply tfsCurr_tfs_net; assumption.\n  apply tfsBc_tfs_net; assumption.\n  apply tfsBc_tfs_net; assumption.\n  apply tfsListen_tfs_net; assumption.\n  (*The only case that differs is where we are tfsListen. In this case\n  we observe that the currMode is failSafe.*)\n  false. apply U1. eapply tfsListen_failSafe_net; eassumption.\n  Qed. \n\nLemma paused_switch_net (n : Network) (i : nat) :\n  reachableNet n -> (pausedStateNet i n <-> switchStateNet i n). Admitted. (*4*)\n(**Proof: Lift result from entity level ultimately- analogous theorems except with\nreachableProt and prot level state predicates.*)\n\nLemma bcWaitNet_del_bkwd (n n' : Network) (m : Mode) (x : Time)\n  (i : nat) (d : Delay) : n -ND- d -ND> n' ->\n  bcWaitStateNet m x i n' -> bcWaitStateNet m (x +dt+ d) i n.\n  Admitted. (*4*)\n(**Proof: Well, a backwards delay preservation would give us bcWaitState m x' i n for some x'. But forward tracking would then give us that\nin the derivative state the second parameter is x' - d. So x = x' - d and so x' = x + d, as required.*)\n\n(** An entity in an initial network is itself initial.*)\nLemma initialNet_ent e i n : initialNet n -> e @ i .: n ->\n  initialEnt e. intro. generalize dependent i.\n  induction H; intro i. intro. inversion H.\n  intro. inversion H1. assumption. eapply IHinitialNet.\n  eassumption. Qed.\n\n(** Looks for an initial network in the hypotheses and also an entity in\nthat network and adds the hypothesis that the entity in question is initial.*)\nLtac initNet_ent_tac := let U0 := fresh in\n  match goal with [U : initialNet ?n,\n  U1 : ?e @ ?i .: ?n |- _] => lets U0 : initialNet_ent U U1 end.\n\n(**Tactic for contradiction between initialNet and some state predicate.\nBasically what it does is get the goal to the stage where there is a\nhypothesis that says <...>StateProt dormant/sleeping/listening, which is\nimmediately solvable by inversion because none of these initial processes\nmatch the state predicate in quesion.*)\nLtac initNet_contra U := \n  inversion U as [e U1 U2]; inversion U1;\n  initNet_ent_tac; match goal with [U3 : [|_, _, _, _|] = ?e,\n  U4 : initialEnt ?e |- _] => rewrite <- U3 in U4;\n  inversion U4 end; match goal with [U5 : initialProc _ |- _] =>\n  inversion U5 end; match goal with [U6 : procProtocol = _ |- _] =>\n  symmetry in U6; subst_all U6 end; match reverse goal with\n  [U7 : context[procProtocol] |- _] => inversion U7 end; subst;\n  match goal with\n  | [U8 : context[dormant] |- _] => inversion U8\n  | [U8 : context[sleeping] |- _] => inversion U8\n  | [U8 : context[listening] |- _] => inversion U8\n  end.\n\nLemma initial_not_bcWait_net (n : Network) (m : Mode) (x : Time) (i : nat) :\n  initialNet n -> bcWaitStateNet m x i n -> False.\n  introz U.\n  (*Solve by init_net_contra*)\n  Admitted.\n\n(** If we're nextSince & we can delay, then we're in the ovWait state.*)\nLemma nextSince_del_ovWait (n n' : Network) (i : nat) (d : Delay) :\n  n -ND- d -ND> n' -> nextSinceStateNet i n ->\n  exists m t x y, ovWaitStateNet m t (delToTime (x +dt+ d)) (delToTime (y +dt+ d)) i n. Admitted. (*3*)\n(**Proof: Apply nextSince_rel_state and then eliminate bcReady other urgent states. Also eliminate\nthe ovWaitStates whos time parameter is less than d (a weak sort of urgency)- have a weak urgency\nresult for this- it will depend on a timed out urgency. In general, the pattern is roughly that,\nwe prove P(0) is urgent, then show that P(d) can delay by at most d, this in turn rests on a proof\nabout delay prefixes, saying that e(d)P can only delay by d', where d is less than d', when P can\ndelay by d' - d.*)\n\n(*This particular state combo means that the action must be tau & the interfaces of\nthe entity in question being preserved.*)\nLemma switchCurr_switchListen_net_link (n n' : Network) (i : nat)\n  (a : ActDiscNet) (e e' : Entity) : \n  switchCurrStateEnt e -> switchListenStateEnt e' ->\n  e @ i .: n -> e' @ i .: n' -> n -NA- a -NA> n' ->\n  a = anTau /\\ interEnt e = interEnt e'. Admitted. (*5*)\n(**Proof: Lift some EA::intercomponent & maybe some linking theorems\nOR\nUse some existing/new inversion tactics for destructing the state predicates and entities.*)\n\nLemma init_nextMode_net m i n :\n  reachableNet n -> initStateNet m i n -> nextModeNet m i n.\n  Admitted. (*7*)\n\n(*LOCAL TIDY*)\n\nLemma ovReady_prev_net_strong m t l n n' i a : \n  ovReadyStateNet m t l i n' -> n -NA- a -NA> n' ->\n  ovReadyStateNet m t l i n \\/\n  (exists x0 y0, ovWaitStateNet m t x0 y0 i n).\n  Admitted. (*#lift-track-net #strong*)\n\nLemma ovWait_prev_net_strong m t x y n n' i a : \n  ovWaitStateNet m t x y i n' -> n -NA- a -NA> n' ->\n  ovWaitStateNet m t x y i n \\/\n  (exists t0 l0, ovReadyStateNet m t0 l0 i n) \\/\n  initStateNet m i n. Admitted. (*#lift-track-net #strong*)\n\nLemma nextMode_pres_fwd_net m i n n' a :\n  reachableNet n -> nextModeNet m i n -> \n  ~(switchCurrStateNet i n \\/ ovAbortStateNet i n \\/\n  tfsCurrStateNet i n) ->\n  n -NA- a -NA> n' -> nextModeNet m i n'. Admitted. (*3*)\n(**Proof: Brute force? Inter-component relationships? Is there any\nmachinery that you can use to help you prove this one?*)\n\nLemma ovWait_del_pres_bkwd_net_strong n n' d m t x y i :\n  n -ND- d -ND> n' -> ovWaitStateNet m t x y i n' ->\n  ovWaitStateNet m t (x +dt+ d) (y +dt+ d) i n. Admitted. (*#del-pres-net #strong*)\n\nLemma ovReady_del_pres_bkwd_net n n' d m t l i :\n  n -ND- d -ND> n' -> ovReadyStateNet m t l i n' ->\n  ovReadyStateNet m t l i n. Admitted. (*#del-pres-net*)\n\nLemma nextModeNet_del_pres n n' d m i :\n  n -ND- d -ND> n' -> nextModeNet m i n -> nextModeNet m i n'.\n  Admitted. (*6*)\n(**Proof: Follows from the semantics. Perhaps there is a similar result\nfor the current mode that can be consulted for inspiration*)\n  \n(*-LOCAL TIDY*)\n\nLemma ovWait_ovReady_nextMode_net m t x y l i n :\n  reachableNet n -> ovWaitStateNet m t x y i n \\/ ovReadyStateNet m t l i n ->\n  nextModeNet m i n.\n  (*Proof: Induction on reachable using the auxialiary result init_nextMode_net.*)\n  introz U. genDep5 m t x y l. induction U; intros l y x t m; introz V.\n  (*\n  (*Base case fails because neither ovWait nor ovReady is initial*)\n  elim_intro V CON CON; initNet_contra CON.   \n  Focus 2.  \n  (*In the discrete inductive case, we show first that the previous state\n  was either ovWait, ovReady, or init.*)\n  assert ((exists t0 x0 y0, ovWaitStateNet m t0 x0 y0 i n) \\/\n  (exists t0 l0, ovReadyStateNet m t0 l0 i n) \\/\n  initStateNet m i n) as PREV.\n  elim_intro V OVW OVR.\n  lets OWP : ovWait_prev_net_strong OVW s. elim_intro OWP OWL OWR.\n  left. do 3 eexists. eassumption. right. or_flat; ex_flat.\n  left. do 2 eexists. eassumption. right. eassumption.\n  lets ORP : ovReady_prev_net_strong OVR s. or_flat.\n  right. left. do 2 eexists. eassumption.\n  left. ex_flat. do 3 eexists. eassumption.\n  (*Now we have that the previous state was either ovWait, ovReady or init,\n  and so I.H. or the result init_nextMode_net will do*)\n  clear V.\n  (*First lets convert our goal to showing that the previous state had a next\n  mode of m. We do this via a preservation tactic.*)\n  cut (nextModeNet m i n). intro NM.\n  (*The main thing to show here is that the previous state was not one\n  that could have allowed a mode change.*)\n  assert (~(switchCurrStateNet i n \\/ ovAbortStateNet i n \\/\n  tfsCurrStateNet i n)) as NMC. unfold not. intro. or_flat; ex_flat;\n  try rename H0 into H; try rename OR1 into OR; try rename OR2 into H;\n  solve [state_pred_elim H OR; entnetuniq2 EN n; state_pred_elim H2 H0;\n  subst; state_pred_elim H4 H6; state_pred_elim H5 H8].\n  (*And from here we can show our (sub)goal.*)\n  eapply nextMode_pres_fwd_net; eassumption.\n  (*So now the proof burden that remains is to show the the next mode\n  holds for the previous state.*)\n  or_flat; ex_flat.\n  (*In the ovWait and ovReady cases this follwos from the IH.*)\n  lets IH : IHU l x2 x1 x0 m. apply IH. left. assumption.\n  lets IH : IHU x1 y x x0 m. apply IH. right. assumption.\n  (*Otherwise the auxialiary result init_nextMode_net works.*)\n  eapply init_nextMode_net; eassumption.\n  (*Now onto the delay case. For this we first use backward preservation of the state predicates\n  to show that one holds in the previous case.*)\n  assert (ovWaitStateNet m t x y i n \\/ ovReadyStateNet m t l i n) as PREV.\n  or_flat. left.\n  (*Then we show by the inductive hypothesis that nextMode holds for \n  the previous case.*)\n  (*Finally, forward preservation of the nextModeNet predicate by the\n  delay relation gives us our goal.*)\n  (*Going to have to fix this- apply new strong version of del_pres?*)\n  eapply ovWait_del_pres_bkwd_net; eassumption.\n  right. eapply ovReady_del_pres_bkwd_net; eassumption.\n  eapply nextModeNet_del_pres; try eassumption.\n  lets IH : IHU l y x t m. apply IH; assumption.\n  Qed.*)\n  Admitted. (*#bism-redo*)\n\nLemma ovWaitState_nextMode_net (n : Network) (m : Mode) (t x y : Time) (i : nat):\n  reachableNet n -> ovWaitStateNet m t x y i n -> nextModeNet m i n.\n  (*Proof: Use the more general result ovWait_ovReady_nextMode_net.*)\n  introz U. eapply ovWait_ovReady_nextMode_net with (l := mkPosition 0 0).\n  assumption. left. eassumption. Qed.\n\n(*If a delay is possible, then every entity is in the listening state.*)\nTheorem del_listening_net (n n' : Network) (d : Delay) (e : Entity) (i : nat) :\n  reachableNet n -> n -ND- d -ND> n' -> e @ i .: n -> listeningStateNet i n.\n  Admitted. (*7*)\n(**Proof: Well if the network delays, then any member entity must also be able\nto delay [del link theorem- salvaged?]. And then we can lift the result\n(EA::del-listening-ent) to get that e is in the listening state, and we're done.*)\n\n\n\n(********************************* Basic Results *********************************)\n\n(*If the entity i is in position l in either network across a discrete transition,\nthen it is also in this position in the other network.*)\nTheorem inPos_pres_disc (n n' : Network) (a : ActDiscNet) (l : Position) (i : nat) :\n  n -NA- a -NA> n' ->\n  (inPosNet l i n <-> inPosNet l i n').\n  (*Proof: Follows directly from the entity semantics*)\n  introz U. split; introz U. destruct U0.\n  link_netentdiscfwd_tac e' b U. subst. econstructor; eassumption.\n  inversion U2; subst; econstructor; eassumption.\n  destruct U0.\n  link_netentdiscbkwd_tac e b U. subst. econstructor; eassumption.\n  inversion U2; subst; econstructor; eassumption.\n  Qed.\n\n(*If the curr mode of entity i is m in a derivative network,\nthen there is some curr mode for that entity in any source network.*)\nTheorem currMode_pres_bkwd (n n' : Network) (a : ActDiscNet) (m' : Mode) (i : nat) :\n  n -NA- a -NA> n' -> currModeNet m' i n' ->\n  exists m, currModeNet m i n. Admitted. (*7*)\n(**Proof: Well currMode m' i n' means that there is some e' @ i .: n'.\nThen we can show by (...salvaged linking theorem of some sort...) that\nthere is some e @ i .: n. It is easy then to show that every entity has\nsome current mode, and so e has one, call it m, and we're done (after a bit of lifting).*)\n\n\n(*If the curr mode of entity i is m in a network, then there\n is some curr mode for that entity in any derivative network.*)\nTheorem currMode_pres_fwd (n n' : Network) (a : ActDiscNet) (m : Mode) (i : nat) :\n  n -NA- a -NA> n' -> currModeNet m i n ->\n  exists m', currModeNet m' i n'. Admitted. (*7*)\n(**Proof: Analogous to the previous proof except we use some\n(...salvaged linking theorem of some sort...) to show that the number of\nentities are preserved forwards in a network.*)\n\n(*If v is outgoing with timestamp t, and the network can delay, then in\nthe derivative network v is outgoing with timestamp t - d.\nA useful corollary of this is that if t = 0, then delay is impossible.*)\nTheorem outgoing_del (n n' : Network) (d : Delay) (v : list BaseType) (t : Time) (i : nat) : \n  n -ND- d -ND> n' -> outgoing v t i n ->\n  {p : d <= t | outgoing v (minusTime t d p) i n'}. Admitted. (*5*)\n(**Proof: Idea is to invert/destruct outgoing to [p, l, {li, lo, ln}, k] @ i.: n & v, t : lo\napply ent-interface del linking tactic\napply interface-list del linkiing tactic\n*now we have that lo delays to some lo'*\nresult & accompanying tactic about timed lists v, t : l & l -d- l' then d <= t &\nv (t - d) : l'\ncontstructor & assumption\n.*)\n\nCorollary outgoing_del_contra (n n' : Network) (d : Delay)\n  (v : list BaseType) (i : nat) : n -ND- d -ND> n' ->  outgoing v zeroTime i n -> False. intros. \n  addHyp (outgoing_del n n' d v zeroTime i H H0). invertClear H1.\n  eapply Rle_not_lt. apply x. simpl. delPos. Qed.\n\n(*If v is outgoing with non-zero timestamp t, and the network performs a\ndiscrete action, then v is still outgoing in the derivative network.*)\t \nTheorem outgoing_disc_pres (n n' : Network) (a : ActDiscNet) (v : list BaseType) (t : Time) (i : nat) :\n  n -NA- a -NA> n' -> outgoing v t i n -> 0 < t ->\n  outgoing v t i n'. introz U.\n  inversion U0.\n  (*Apply net-ent disc linking tactic*)\n  link_netentdiscfwd_tac e' b LE.\n  (*Case entities are equal: constructor & rewrite*)\n  subst. econstructor; eassumption.\n  (*else destruct the derivative entity*)\n  destr_ent_inter e' p' l' k' li' lo' ln'.\n  (*apply a linking theorem from entities to output lists*)\n  lets LEO : link_ent_outList LE1. or_flat.\n  (*Equality case follows easily.*)\n  subst. econstructor; eassumption.\n  (*Else we need to apply some more support lemmas*)\n  ex_flat. or_flat.\n  econstructor. eassumption. eapply outList_in_input_pres;\n  eassumption.\n  econstructor. eassumption. eapply outList_in_output_pres;\n  eassumption. Qed.\n\n(*If v is incomingNetNotif with timestamp t, and the network can delay, then in\nthe derivative network v is incomingNetNotif with timestamp t - d.\nCorollary is that whenever t = 0 delay is impossible.*)\nTheorem incomingNetNotif_del (n n' : Network) (d : Delay) (v : list BaseType)\n  (t : Time) (i : nat) : \n  reachableNet n -> n -ND- d -ND> n' -> incomingNetNotif v t i n ->\n  {p : d <= t | incomingNetNotif v (minusTime t d p) i n'}.\n  (*invert/destruct incomingNotif to [p, l, {li, lo, ln}, k] @ i.: n & v, t : ln*)\n  intro RN. introz U. destruct U0.\n  (*Set up the derivaive entity.*)\n  link_netentdelfwd_tac e' Y. destr_ent_inter e' p' l' k' li' lo' ln'.\n  (*Apply ent-interface del linking tactic*)\n  link_entinterdel_tac Y.\n  (*Invert the delay to the lists.*)\n  inversion_clear Y1.\n  (*From here we split proof into two based on where d <= t or not*)\n  Rleltcases d t IQ.\n  (*In the case of d <= t we use a support lemma for the t - d stamp of the message*)\n  exists IQ. econstructor. apply Y.\n  eapply notifList_del_le. apply H3. assumption.\n  (*In the case of t < d, proceed by contradiction on noSynchProcInter. We know that since\n  a delay is possible for the entity, noSynch must be true between the entity components.*)\n  false. assert (noSync p {| li := li; lo := lo; ln := ln |} k d) as NSY. inversion Y0.\n  assumption. assert (p -PD- d -PD> p') as PDD. inversion Y0. assumption.\n  (*So it suffices to falsify this to get the contradiction i.e. show a synch between proc\n  and inter either now or after some delay less than d.*)\n  lets NS : NSY (chanAN ;? v). decompAnd2 NS NSN NSD.\n  (*Now we split into two subcases based on whether 0 < t or t = 0*)\n  remember ([|p, l, {| li := li; lo := lo; ln := ln |}, k|]) as e0.\n  timezerolteq t Q.\n  (*If 0 < t then there is some delay d' = t*)\n  clear NSN. mkdel t Q d'. assert (d' < d) as DD. rewrite Heqd'. assumption.\n  (*Let's turn the inequality into an equation*)\n  Rlttoplus DD x DP. mkdel x DP0 d''. assert (d = d' +d+ d'') as ED.\n  rewrite Rplus_comm in DP. apply delayEqR. simpl. my_applys_eq DP.\n  f_equal. rewrite Heqd''. reflexivity.\n  (*Then by the property of time splitting, we get that there was an intermediate entity\n  network from the original with delay d'. Call this n1.*)\n  lets TNX : timeSplit_net U ED. decompExAnd TNX n1 ND1 ND2.\n  (*Now, we know there must be some entity e1 in n1 which is delay linked to e0.*)\n  link_netentdelfwd_tac e1 ED. \n  (*Now we do some inversion on this transiton to get the corresponding delay of the\n  notification list.*)\n  rewrite Heqe0 in ED1. destr_ent_inter e1 p1 l1 k1 li1 lo1 ln1.\n  link_entinterdel_tac U. inversion U0. assert (d' <= t) as DT. rewrite Heqd'.\n  simpl. apply Rle_refl.\n  (*Once we have this delay, we can show that the notifList relation continues on,\n  and since d' = t, the timestamp is now 0.*)\n  lets ND : notifList_del_le DT H13 H0. assert (minusTime t d' DT = zeroTime) as TDZ.\n  apply timeEqR. simpl. rewrite Heqd'. simpl. ring. rewrite TDZ in ND. clear TDZ.  \n  (*Now we bring to our hypotheses the noSync condition for the intermediate state.*)\n  assert (p -PD- d' -PD> p1 /\\ k -ms- d' -ms> k1 /\\\n  {| li := li; lo := lo; ln := ln |} -i- d' -i> {| li := li1; lo := lo1; ln := ln1 |}).\n  inversion ED1; (repeat split); assumption. andflat HY.\n  lets NSF : NSD DD HY HY2 HY1.\n  (*Then ahead we go to show the synchronisation on chanAN of v does exist.*)\n  unfold noSyncNow in NSF. assert (discActEnabled p1 (chanAN;? v)) as DAE.\n  apply listening_AN_prot. assert (listeningStateNet i n1) as LSN. eapply del_listening_net.\n  eapply reachNetDel. apply RN. apply ND1. apply ND2. apply ED0. inversion LSN as [e IV1 IV2].\n  inversion IV1 as [p4 l4 h4 k4 IV3 IV4]. my_applys_eq IV3. rewrite <- IV4 in IV2.\n  entnetuniq2 EU n1. inversion EU. reflexivity. apply NSF in DAE. decompAnd2 DAE DI DM.\n  apply DI. apply notif_timeout_enabled. assumption.\n  (*If t = 0, then we have our contradiction with noSyncNow, just like the last step\n  of the previous case.*)\n  clear NSD. unfold noSyncNow in NSN. assert (discActEnabled p (chanAN;? v)) as DAE.\n  apply listening_AN_prot. assert (listeningStateNet i n) as LSN. eapply del_listening_net.\n  apply RN. apply U. apply H. inversion LSN. inversion H4. my_applys_eq H6.\n  cut (e = e0). intros. rewrite H8 in H7. rewrite Heqe0 in H7. inversion H7.\n  reflexivity. entnetuniq U e e0. assumption. apply NSN in DAE. decompAnd2 DAE DI DM.\n  apply DI. assert (t = zeroTime) as TZ. apply timeEqR. rewrite <- Q.\n  reflexivity. rewrite TZ in H0. apply notif_timeout_enabled. assumption. Qed.\n\n(*If v is incomingNetNotif with non-zero timestamp t, and the network performs a discrete\naction, then v is still incomingNetNotif in the derivative network.*)\nTheorem incomingNetNotif_disc_pres (n n' : Network) (a : ActDiscNet) (v : list BaseType) (t : Time) (i : nat) :\n  n -NA- a -NA> n' -> incomingNetNotif v t i n -> 0 < t ->\n  incomingNetNotif v t i n'. Admitted. (*4*)\n(**Proof: Analogous to (outgoing_disc_pres).*)\n\n(*If an entity is inPosNet l' i n', and there is some n such that it delays to n' via d,\nthen i is in inPosNet l i n for some l and the difference between the positions is at most\nspeedMax*d*)\nLemma inPos_del_bound_bkwd (n n' : Network) (d : Delay) (l' : Position) (i : nat) :\n  inPosNet l' i n' -> n -ND- d -ND> n' -> exists l,\n  inPosNet l i n /\\ dist2d l l' <= speedMax * d. Admitted. (*5*)\n(**Proof: Salvaged from old Coq model (pos_bound?).*)\n\nConjecture currMode_intro : forall (m : Mode) (e : Entity) (i : nat) (n : Network),\n  m = currModeEnt e -> e @ i .: n -> currModeNet m i n.\n(**Proof: Obvious- lift currModeEnt to currModeNet*)\n\nConjecture inPos_ex : forall (i : nat) (n : Network) (e : Entity),\n  e @ i .: n -> exists l, inPosNet l i n.\n(**Proof: Obvious- every entity has a position*)\n\nConjecture distNet_intro : forall (e1 e2 : Entity) (i j : nat) (n : Network) (x : Distance),\n  e1 @ i .: n -> e2 @ j .: n -> x = mkDistance (dist2d e1 e2) -> distNet i j n x.\n(**Proof: Obvious from definitions of things*)\n\nConjecture inPos_pos : forall (e : Entity) (i : nat) (l : Position) (n : Network),\n  e @ i .: n -> inPosNet l i n -> posEnt e = l.\n(**Proof: Obvious- invert/deconstruct inPostNet*)\n\nConjecture reachable_net_ent : forall (n : Network) (e : Entity) (i : nat),\n  reachableNet n -> e @ i .: n -> reachableEnt e.\n(**Proof: Obvious- inversion on reachableNet*)\n\n(*There are already proofs like this about distance in networks, just not using distNet*)\nConjecture disc_pres_distNet_bkwd : forall (n n' : Network) (a : ActDiscNet)\n  (i j : nat) (x : Distance),\n  n -NA- a -NA> n' -> distNet i j n' x -> distNet i j n x.\n(**Proof: Obvious- Lift other proofs which say essentially the same thing and apply constructor for distNet*)\n\n(*There are already proofs like this about distance in networks, just not using distNet*)\nConjecture del_link_distNet_bkwd : forall (n n' : Network) (d : Delay)\n  (i j : nat) (x' : Distance),\n  n -ND- d -ND> n' -> distNet i j n' x' ->\n  exists x, distNet i j n x /\\ x <= x' + 2*speedMax*d.\n(**Proof: Obvious- Lift similar proofs & apply distNet constructor*)\n\nConjecture distNet_elim : forall (i j : nat) (n : Network) (x : Distance),\n  distNet i j n x -> exists e1 e2,\n  e1 @ i .: n /\\ e2 @ j .: n /\\ x = {| distance := dist2d e1 e2 |}. \n\n(*Delay link from network to entity.*)\nLemma del_net_ent (e : Entity) (i : nat) (n n' : Network) (d : Delay) :\n  e @ i .: n -> n -ND- d -ND> n' -> exists e', e -ED- d ->> e'.\n  intros. genDep2 i n'. induction n; intros n' H0 i H.\n  inversion H. inversion H0. inversion H.\n  eexists. eassumption. eapply IHn. eassumption.\n  eassumption. Qed.\n\n(*If a network accepts some value*)\nLemma inRange_acc_input (n n' : Network) (v : list BaseType) (l : Position)\n  (r : Distance) (i : nat) (e : Entity) :\n  n -NA- ([-v, l, r-]) /?: -NA> n' -> e @ i .: n -> dist2d l (posEnt e) <= r ->\n  exists e', e -EA- ([-v, l, r-]) #? ->> e' /\\ e' @ i .: n'. Admitted. (*7*)\n\n(*Any entity within range of a broadcast inputs that broadcast.*)\nLemma inRange_out_input (n n' : Network) (v : list BaseType) (l : Position)\n  (r x: Distance) (i j : nat) (e : Entity) :\n  n -NA- ([-v, l, r-]) /! i -NA> n' -> e @ j .: n -> i <> j -> distNet i j n' x ->\n  x <= r -> exists e', e -EA- ([-v, l, r-]) #? ->> e' /\\ e' @ j .: n'.\n  genDep3 n' i j. induction n; intros. inversion H0.\n  inversion H. (*Use inRange_acc_input from here*) Admitted. (*7*)\n\nConjecture transGuard_disc_pres : forall (n n' : Network)\n  (a : ActDiscNet) (t : Time) (i : nat),\n  n -NA- a -NA> n' -> transGuard t i n -> transGuard t i n'.\n(**Proof: Obvious: discrete action preserves guard on mode state, immediate from mode state semantics*)\n\nConjecture transGuard_elim : forall (t : Time) (i : nat) (n : Network),\n  transGuard t i n -> exists m m',\n  mState_in_net (<| m, m', t |>) i n.\n(**Proof: Obvious: transGuard definition*)\n\nConjecture transGuard_intro : forall (t : Time) (i : nat) (n : Network)\n  (m m' : Mode), mState_in_net (<| m, m', t |>) i n ->\n  transGuard t i n.\n(**Proof: Immediate from definition of transGuard*)\n\nConjecture mState_disc_pres : forall (n n' : Network) (i : nat)\n  (a : ActDiscNet) (k  : ModeState), n -NA- a -NA> n' -> mState_in_net k i n ->\n  exists k', mState_in_net k' i n'.\n(**Proof: Obvious- inversion on mState_in_net, get that there's an entity, apply linking tactic to get entity in derivative,\nthen once there's an entity there's going to be a mode state, so mState_in_net is satisfied.*)\n\nConjecture transGuard_del : forall (n n' : Network)\n  (d : Delay) (t : Time) (i : nat),\n  n -ND- d -ND> n' -> transGuard t i n -> \n  exists p, transGuard (minusTime t d p) i n'.\n(**Proof: Obvious- transGuard definition and mode state semantics*)\n\nConjecture currModeNet_del_pres : forall (n n' : Network) (d : Delay)\n  (m : Mode) (i : nat), n -ND- d -ND> n' ->\n  (currModeNet m i n <-> currModeNet m i n').\n(**Proof: Obvious- delay preservation tactic*)\n\nConjecture currModeNet_dec : forall (m : Mode) (i : nat) (n : Network),\n  currModeNet m i n \\/ ~currModeNet m i n.\n(**Proof: Obvious- not important to prove as it's just law of excluded middle*)\n\nLemma initial_failSafe (n : Network) (e : Entity) (i : nat) :\n  initialNet n -> e @ i .: n -> failSafe e.\n  (*Proof: Follows directly from the definition of initial*)\n  introz U. generalize dependent i. induction n; intros i U0.\n  inversion U0. inversion U. subst. inversion U0. subst.\n  inversion H1. assumption. eapply IHn; eassumption. Qed.\n\nLemma curr_switch_ent_tau (n n' : Network) (a : ActDiscNet)\n  (e e' : Entity) (i : nat) (m m' : Mode) :\n  n -NA- a -NA> n' -> e @ i .: n -> e' @ i .: n' ->\n  currModeEnt e = m -> currModeEnt e' = m' -> m <> m' ->\n  e -EA- aeTau ->> e'. Admitted. (*5*)\n(**Proof: EXISITNG THEOREMS OF A SIMILAR NATURE TO HELP YOU SOLVE THIS? LOOK FOR M <> M'\nCase analyse the action a and in all cases where the action isn't tau, the mode states are equal, giving a contradiction. This leaves only the case where a is a tau. In this case, we apply a linking theorem to get that the tau was done by some entity while the rest of the entities were preserved. Well, then, the entity that did the tau must be our entity e, because otherwise its preservation would imply the equality of the modes, which is a contradiction.*)\n\n(**Broadly speaking, a linking theorem.*)\nLemma reachable_net_prot : forall (n : Network) (i : nat)\n  (p : ProcTerm) (l : Position) (h : Interface) (k : ModeState),\n  reachableNet n -> [|p, l, h, k|] @ i .: n ->\n  reachableProt p. Admitted. (*6*)\n(**Proof: DOES THEOREM LIKE THIS ALREADY EXIST? Induction on reachableNet and some linking results*)\n\n(**Delay preserves the current mode*)\nLemma currMode_del_pres_bkwd (n n' : Network) (d : Delay) (m : Mode) (i : nat) :\n  n -ND- d -ND> n' -> currModeNet m i n' -> currModeNet m i n. Admitted. (*6*)\n(**Proof: Follows directly from mode state semantics, and linking of delay from network to entity to modestate*)\n\nConjecture inPos_ent_net : forall (l : Position) (e : Entity) (i : nat) (n : Network),\n  inPosEnt l e -> e @ i .: n -> inPosNet l i n.\n(**Proof: Obvious from definitions*)\n\nConjecture inPos_unique : forall (l l' : Position) (i : nat) (n : Network),\n  inPosNet l i n -> inPosNet l' i n -> l = l'.\n(**Proof: Obvious- inversion and apply entInNetUnique*)\n\n(*An output by entity i from the network n means that the message is now pending\nnotification with timestamp AN.*)\nLemma outNet_incomingNetNotif (n n' : Network) (v : list BaseType) (r : Distance)\n  (l : Position) (i : nat) : n -NA- ([-v, l, r-]) /! i -NA> n' ->\n  incomingNetNotif ((baseDistance r)::v) adaptNotif i n'. Admitted. (*5*)\n(**Proof: Follows from interface semantics.*)\n\n(** Linking theorem.*)\nLemma incoming_net_ent (v : list BaseType) (i : nat) (n : Network) :\n  incomingNet v i n -> exists e, incomingEnt v e /\\ e @ i .: n. intro U.\n  invertClear U. exists ([|p, l, {| li := li; lo := lo; ln := ln |}, k|]).\n  split. repeat constructor. assumption. assumption. Qed.\n\n(** Linking theorem.*)\nLemma incoming_ent_net (v : list BaseType) (e : Entity) (i : nat) (n : Network) :\n  incomingEnt v e -> e @ i .: n -> incomingNet v i n.\n  (*Proof: Follows directly from the definition*)\n  introz U. inversion U. subst. destruct h. econstructor. eassumption.\n  inversion U. subst. inversion H1. assumption. Qed.\n\nLtac inposdp :=\n  match goal with\n  [ w : ?n -NA- _ -NA> ?n', H : inPosNet ?l ?i ?n' |- inPosNet ?l ?i ?n] =>\n  eapply inPos_pres_disc; [apply w | assumption]\n  end.\n\n(**Can be used directly for this particular protocol with 3 software components. Constructs the derivative triple and all the\ndelays between the corresponding components, as well as the position bound. Specification is somewhat crude, but easy to manipulate,\nparticularly with a tactic.*)\nLemma net_del_elim q q0 q1 l h k i n n' d :\n  [|q $||$ q0 $||$ q1, l, h, k|] @ i .: n ->\n  n -ND- d -ND> n' ->\n  exists q' q0' q1' l' h' k',\n  [|q' $||$ q0' $||$ q1', l', h', k'|] @ i .: n' /\\\n  q -PD- d -PD> q' /\\ q0 -PD- d -PD> q0' /\\ q1 -PD- d -PD> q1' /\\\n  h -i- d -i> h' /\\ k -ms- d -ms> k' /\\\n  dist2d l l' <= speedMax * d. Admitted. (*7*)\n(**Proof: First apply linking theorem for the entity. Then destruct the derivative entity. Then show that the delay between the entities\ncan only happen when the interface and mode state components also delay, and the distance inequality condition holds, giving the final three goals.\nThe first four goals then follow from an application of a result for software components: triples of processes always delay to triples, with each\nindividual component delaying to the corresponding component*)\n\nConjecture currMode_ent_ex : forall (m : Mode) (i : nat) (n : Network),\n  currModeNet m i n <-> exists e, e @ i .: n /\\ currModeEnt e = m.\n(**Proof: Obvious from definitions*)\n\nConjecture nextMode_ent_ex : forall (m : Mode) (i : nat) (n : Network),\n  nextModeNet m i n <-> exists e, e @ i .: n /\\ nextModeEnt m e.\n(**Proof: Obvious from definitions*)\n\nLtac currMode_ent_ex_tac e U :=\n  let Q := fresh in let U1 := fresh U in let U2 := fresh U in\n  match goal with\n  [H : currModeNet ?m ?i ?n |- _ ] => lets Q : H; rewrite currMode_ent_ex in Q;\n  decompExAnd Q e U1 U2\n  end.\n\nLtac nextMode_ent_ex_tac e U :=\n  let Q := fresh in let U1 := fresh U in let U2 := fresh U in\n  match goal with\n  [H : nextModeNet ?m ?i ?n |- _ ] => lets Q : H; rewrite nextMode_ent_ex in Q;\n  decompExAnd Q e U1 U2\n  end.\n\n(*LOCAL TIDY*)\n\nLemma mState_in_net_unique k k' i n : \n  mState_in_net k i n -> mState_in_net k' i n -> k = k'.\n  intros. inversion H. inversion H0. entnetuniq2 EN n.\n  inversion EN. reflexivity. Qed.\n\n(** Given a network state predicate as the goal and the corresponding\nentity state predicate in the hypotheses, this solves things using\nlenWitness.*)\nLtac netState_ent_net_tac := eapply lenWitness;\n  [eassumption | eassumption].\n\nLemma tfsNext_currModeNet_eq m1 m2 i n : currModeNet m1 i n ->\n  tfsNextStateNet m2 i n -> m1 = m2. Admitted. (*5*)\n(*Proof: On initially entering this state, the mode is read from the mode state,\ngiving the equality. In the discrete inductive case it can be shown by\ncurrModeNet_switch_states that the mode state doesn't change- (?) because if it were to change\nthat would imply a contradictory condition on the state predicates?. In the delay inductive\ncase, delay preservation for both mode state and tfsNext prevail.*)\n\n(** The nextSinceState relation can be broken down into the following cases.*)\nLemma nexSinceStateNet_cases i n :\n  nextSinceStateNet i n ->\n  (exists m t x y, ovWaitStateNet m t x y i n) \\/\n  (exists m t l, ovReadyStateNet m t l i n) \\/\n  (exists m, switchBcStateNet m i n) \\/\n  (switchCurrStateNet i n). intros. inversion H.\n  inversion H0. inversion H2. subst. inversion H4.\n  left. (*repeat eexists; eassumption. \n  right. left. repeat eexists; eassumption.\n  right. right. left. repeat eexists; eassumption.\n  right. right. right. repeat eexists; eassumption.\n  Qed.*)\n  Admitted. (*R*)\n\nLemma link_net_ent_disc :\n  forall (n n' : Network) (e e' : Entity) (i : nat) (a : ActDiscNet),\n  n -NA- a -NA> n' -> e @ i .: n -> e' @ i .: n'->\n  (e = e' \\/ (exists a', e -EA- a' ->> e')). Admitted. (*6*)\n(**Proof: Case analyse the network transition and this follows from the semantics*)\n\nLtac link_netentdisc_tac b :=\n  match goal with\n  | [ U1 : ?n -NA- ?a -NA> ?n', U2 : ?e @ ?i .: ?n,\n  U3 : ?e' @ ?i .: ?n' |- _] =>\n    let H1 := fresh in lets H1 : link_net_ent_disc U1 U2 U3;\n    let H2 := fresh in let H3 := fresh in\n    elim_intro H1 H2 H3; [subst_all H2 |\n    let H4 := fresh in invertClearAs2 H3 b H4]\n  end.\n\n(** Does some pre-processing on the proof of a backracking theorem at the\nnetwork level. Works where the backtracking has two predecessor cases.\nProbably needs to be slightly altered if there's a need to handle more cases. *)\nLtac backtrack_net_pre U :=\n  let U1 := fresh in let e := fresh \"e\" in let b := fresh \"b\" in\n  state_pred_net_destr U; link_netentdiscbkwd_tac0 e b U1;\n  let EQ := fresh \"EQ\" in let EX := fresh in\n  match goal with [U2 : _ \\/ _ |- _ ] =>\n  elim_intro U2 EQ EX; [left; econstructor | ];\n  [eassumption |  | ]; [ subst; assumption | ex_flat] end.\n\n(** Tactic for eliminating two contradictory state predicates H and H1*)\nLtac state_pred_elim_net H H1 :=\n  let e := fresh \"e\" in let e' := fresh \"e'\" in\n  let U1 := fresh in let U2 := fresh in let U3 := fresh in\n  let U1' := fresh in let U2' := fresh in\n  inversion H as [e U1 U2]; inversion H1 as [e' U1' U2'];\n  assert (e' = e) as U3;[eapply entInNetUnique; eassumption | ];\n  subst_all U3; destruct e as [p0 l0 h0 k0]; inversion U1;\n  inversion U1'; subst; \n  match goal with [SP1 : context[p0], SP2 : context[p0] |- _] =>\n  inversion SP1; inversion SP2 end; subst;\n  match goal with [PT : _ $||$ _ $||$ _ = ?p1 $||$ ?p2 $||$ ?p3 |- _] =>\n  inversion PT; subst;\n  repeat match goal with [PT : context[_ $||$ _ $||$ _] |- _] =>\n  clear PT end;\n  match goal with\n  | [SP1 : context[p1], SP2 : context[p1] |- _] =>\n    inversion SP1; subst; inversion SP2\n  | [SP1 : context[p2], SP2 : context[p2] |- _] =>\n    inversion SP1; subst; inversion SP2\n  | [SP1 : context[p3], SP2 : context[p3] |- _] =>\n    inversion SP1; subst; inversion SP2\n  end\n  end.\n\n(***************************** Lifted results *****************************)\n\nLemma tfsStart_prev_net i n n' a : tfsStartStateNet i n' ->\n  n -NA- a -NA> n' -> tfsStartStateNet i n \\/\n  exists m t x y, ovWaitStateNet m t x y i n.\n  Admitted. (*#lift-track-net*)\n\nLemma ovReady_prev_net m t l i n n' a :\n  ovReadyStateNet m t l i n' -> n -NA- a -NA> n' ->\n  ovReadyStateNet m t l i n \\/\n  exists x y, ovWaitStateNet m t x y i n. Admitted. (*#lift-track-net*)\n\n(*Organise these, write tactics for them, pull in results from elsewhere in\nthe file that belong here.*)\n\nLemma ovWait_del_pres_net m t x y i n n' d : n -ND- d -ND> n' ->\n  (ovWaitStateNet m t x y i n <-> ovWaitStateNet m t x y i n'). Admitted. (*4*)\n(*Standard delay preservation tactic at network level, which itself\nlifts from lower levels.*)\n\nLemma tfsNext_prev_net m i n n' a : tfsNextStateNet m i n' ->\n  n -NA- a -NA> n' -> tfsNextStateNet m i n \\/ tfsStartStateNet i n.\n  intros.\n  backtrack_net_pre H.\n  lets TPE : tfsNext_prev_ent H1 H5.\n  elim_intro TPE TN TS;[left | right]; netState_ent_net_tac.\n  Qed.  \n\nLemma del_pres_bkwd_tfsNext m i n n' d :\n  n -ND- d -ND> n' -> tfsNextStateNet m i n' -> tfsNextStateNet m i n.\n  Admitted. (*4*)\n(*Proof: Lift delay preservation- write tactic for this*)  \n\nLemma del_pres_bkwd_tfsStart i n n' d :\n  n -ND- d -ND> n' -> tfsStartStateNet i n' -> tfsStartStateNet i n.\n  Admitted. (*4*)\n\nLemma tfsNext_urgent_net m i n n' d : \n  tfsNextStateNet m i n -> n -ND- d -ND> n' -> False.\n(*Lift urgency- use tactic*) Admitted. (*5*)\n\nLemma tfsStart_urgent_net i n n' d : \n  tfsStartStateNet i n -> n -ND- d -ND> n' -> False.\n(*Lift urgency- use tactic*) Admitted. (*5*)\n\nLemma ovReady_wait_track_net m t l i m' t' x y n n' a :\n  ovReadyStateNet m t l i n -> ovWaitStateNet m' t' x y i n' ->\n  n -NA- a -NA> n' -> m = m' /\\\n  (exists p, t' = minusTime t (period m) p) /\\ x = t' /\\ y = period m.\n  Admitted. (*5*)\n(*Proof: #lift-track-net*)\n\nLemma ovWait_track_net m m' t t' x x' y y' i n n' a :\n  ovWaitStateNet m t x y i n -> ovWaitStateNet m' t' x' y' i n' ->\n  n -NA- a -NA> n' -> m = m' /\\ t = t' /\\ x = x' /\\ y = y'. Admitted. (*5*)\n(**Proof: Apply a tactic to extract the underlying process state predicates- at the\nlowest level e.g. ovWaitState p2 (tactic already exists I think?).\nThen apply a matching tactic at this level, and you should be done.*)\n\n(*Perhaps modify this to get rid of the \"t + period m\" and replace it with some existential\ninstead. Then do a separate tracking result to get the \"t + period m\".*)\nLemma ovWait_prev_net m t x y i n n' a : ovWaitStateNet m t x y i n' ->\n  n -NA- a -NA> n' ->\n  ovWaitStateNet m t x y i n \\/\n  (exists l, ovReadyStateNet m (t +t+ period m) l i n) \\/\n  initStateNet m i n.\n  Admitted. (*#lift-track-net*)\n\nLtac reach_net_prot_tac :=\n  match goal with [RN : reachableNet ?n,\n  EIN : [|_, _, _, _|] @ _ .: ?n |- _] =>\n  let RNP := fresh \"RNP\" in\n  let RPT := fresh \"RPT\" in\n  lets RNP : reachable_net_prot RN EIN;\n  lets RPT : reachableProt_triple RNP end.\n\n(*-LOCAL TIDY*)\n", "meta": {"author": "ColmBhandal", "repo": "PhD-Formalilsing-Comhordu", "sha": "7f31dbc4a9a205b3b722cff30e79442922e0f9c9", "save_path": "github-repos/coq/ColmBhandal-PhD-Formalilsing-Comhordu", "path": "github-repos/coq/ColmBhandal-PhD-Formalilsing-Comhordu/PhD-Formalilsing-Comhordu-7f31dbc4a9a205b3b722cff30e79442922e0f9c9/src/NetAuxBasics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.23752217720787228}}
{"text": "From Formalisation Require Import SizeNat Nom IpAddr radius_attr_rel radius.\nFrom Raffinement Require Import PHOAS RelNomPHOAS.\n\nDefinition radius_data : type :=\n  Pair (Pair (Pair (Pair (NatN 8) (NatN 8)) (NatN 16)) Span) (Option (Vector attribute)).\n\nDefinition radius_data_spec (rad : RadiusData) (r : type_to_Type radius_data) :=\n  code rad = mk_code r.1.1.1.1 /\\\n    identifier rad = r.1.1.1.2 /\\\n    length rad = r.1.1.2 /\\\n    authenticator rad = r.1.2 /\\\n    match attributes rad, r.2 with\n    | None, None => True\n    | Some vx, Some vy =>\n        VECTOR_spec attribute_rel vx vy\n    | _,_ => False%type\n    end.\n\nDefinition parse_radius_data_rel :\n  {code | forall data vs, adequate (fun _ => radius_data_spec) parse_radius_data code data vs}.\n  eapply exist. intros. unfold parse_radius_data.\n  repeat step.\n  eapply bind_adequate. eapply be_u8_adequate. intros. be_spec_clean. subst.\n  eapply (ret_adequate _ _ _ (Var vres)); repeat econstructor; eauto.\n  instantiate (1 := fun _ x y => x = mk_code y). simpl. eauto.\n  eapply be_u8_adequate.\n  eapply be_u16_adequate.\n  unfold sizeu16. step.\n  eapply (cond_adequate (EBin ELt (Const (ENat 20)) (EUna EVal (Var vres1))));\n    repeat clean_up; be_spec_clean; subst; repeat econstructor; eauto.\n  intro. eapply map_parser_adequate. eapply consequence_adequate. step.\n  intros. repeat clean_up. split; auto.\n  intros. eapply many1_adequate.\n  intros. eapply parse_radius_attribute_adequate.\n  eapply (ret_adequate _ _ _ (EBin EPair (EBin EPair (EBin EPair (EBin EPair (Var vres) (Var vres0)) (Var vres1)) (Var vres2)) (Var vres3)));\n    be_spec_clean; repeat clean_up; simpl; subst; repeat econstructor; eauto.\n  simpl. destruct r3; eauto. destruct vres3; eauto.\nDefined.\n\nLemma parse_radius_data_adequate : forall data vs,\n    adequate (fun _ => radius_data_spec) parse_radius_data (proj1_sig parse_radius_data_rel) data vs.\nProof. intros. destruct parse_radius_data_rel. eauto. Qed.\n\n\nDefinition equiv_parse_radius_data_rel {var} :\n  {code : @PHOAS var _ | equiv_prog Nil _ (`parse_radius_data_rel) code}.\n  eapply exist. simpl. repeat econstructor.\nDefined.\n", "meta": {"author": "Artalik", "repo": "NigronThesis", "sha": "370358a919f3d83c327b3bb7b455d9c8763fe543", "save_path": "github-repos/coq/Artalik-NigronThesis", "path": "github-repos/coq/Artalik-NigronThesis/NigronThesis-370358a919f3d83c327b3bb7b455d9c8763fe543/src/CoqNom/src/Formalisation/Formats/Radius/radius_rel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.23749227824054403}}
{"text": "(** * Properties about Context Free Grammars *)\nRequire Import Fiat.Parsers.StringLike.Core Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Transfer.\nRequire Import Fiat.Parsers.ContextFreeGrammar.SimpleCorrectness.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\nSet Implicit Arguments.\n\nSection cfg.\n  Context {Char} {HSLM1 HSLM2 : StringLikeMin Char}\n          {HSL1 : @StringLike _ HSLM1}\n          {HSL2 : @StringLike _ HSLM2}\n          (G : @grammar Char).\n  Context (R : @String _ HSLM1 -> @String _ HSLM2 -> Prop).\n  Context {is_respectful : transfer_respectful R}.\n\n  Local Ltac t' :=\n    repeat match goal with\n           | _ => assumption\n           | [ |- appcontext[match ?e with _ => _ end] ]\n             => is_var e; destruct e\n           | _ => tauto\n           | _ => solve [ eauto with nocore ]\n           | _ => intro\n           | [ H : and _ _ |- _ ] => destruct H\n           | [ H : ex _ |- _ ] => destruct H\n           | [ H : transfer_respectful _ |- _ ] => destruct H; try clear H\n           | [ |- and _ _ ] => split\n           | [ |- ex _ ] => eexists; solve [ t' ]\n           | [ H : is_true (andb ?x _) |- is_true (andb ?x _) ]\n             => destruct x eqn:?; simpl in *\n           end.\n\n  Local Ltac t :=\n    lazymatch goal with\n    | [ p : _ |- _ ] => destruct p\n    end;\n    simpl_simple_parse_of_correct;\n    t'.\n\n  Fixpoint transfer_simple_parse_of_correct {str1 str2 pats} (H : R str1 str2) (p : @simple_parse_of Char)\n    : simple_parse_of_correct G str1 pats p -> simple_parse_of_correct G str2 pats p\n  with transfer_simple_parse_of_production_correct {str1 str2 pat} (H : R str1 str2) (p : @simple_parse_of_production Char)\n    : simple_parse_of_production_correct G str1 pat p -> simple_parse_of_production_correct G str2 pat p\n  with transfer_simple_parse_of_item_correct {str1 str2 it} (H : R str1 str2) (p : @simple_parse_of_item Char)\n    : simple_parse_of_item_correct G str1 it p -> simple_parse_of_item_correct G str2 it p.\n  Proof.\n    { t. }\n    { t. }\n    { t. }\n  Defined.\nEnd cfg.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_simpl_example/src/Parsers/ContextFreeGrammar/SimpleTransfer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.2374922714390597}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nRequire Import machine_int.\nImport MachineInt.\nRequire Import mips_cmd.\nImport expr_m.\nRequire Import pick_sign_prg multi_lt_prg multi_add_u_u_prg multi_sub_u_u_prg.\nRequire Import multi_negate_prg copy_u_u_prg multi_is_zero_u_prg.\n\nLocal Open Scope mips_cmd_scope.\n\n(** x <- x + y with x signed and y unsigned, non-zero; the number of words in x\n    and y's payloads is supposed to be stored in rk *)\n\nSection multi_add_s_u0_sect.\n\nVariables rk rx ry a0 a1 a2 a3 a4 a5 rX : reg.\n\nDefinition multi_add_s_u0 :=\n  lw rX four16 rx ; (* payload of X *)\n  pick_sign rx a0 a1 ;\n  If_bgez a1 Then (* 0 <= x ? *)\n    If_beq a1 , r0 Then (* x = 0 ? *)\n      copy_u_u rk rX ry a2 a3 a4 ;\n      addiu a3 r0 zero16 ; (* no overflow *)\n      sw rk zero16 rx (* fix length *)\n    Else (* x != 0 *)\n      addiu a3 r0 one16 ;\n      multi_add_u_u rk a3 ry rX rX a0 a1 a2 ;\n      mflo a3 (* overflow *)\n  Else (* x < 0 *)\n    multi_lt rk ry rX a0 a1 a5 a2 a3 a4 ;\n    If_beq a5 , r0 Then (* x <= y ? *)\n      If_beq a2 , r0 Then (* x = y ? *)\n        addiu a3 r0 zero16 ; (* no overflow *)\n        sw r0 zero16 rx  (* fix length *)\n      Else (* x < y *)\n        multi_sub_u_u rk ry rX rX a0 a1 a2 a3 a4 a5 ;\n        multi_negate rx a0\n    Else (* x > y *)\n      multi_sub_u_u rk rX ry rX a0 a1 a5 a3 a2 a4.\n\nEnd multi_add_s_u0_sect.\n\nSection multi_add_s_u_sect.\n\n(** same as above except that y can be 0 *)\n\nVariables rk rx ry a0 a1 a2 a3 a4 a5 rX : reg.\n\nDefinition multi_add_s_u :=\n  multi_is_zero_u rk ry a0 a1 a2 ;\n  If_bne a2 , r0 Then (* y = 0 ? *)\n    addiu a3 r0 zero16 (* no overflow *)\n  Else (* y != 0 *)\n    multi_add_s_u0 rk rx ry a0 a1 a2 a3 a4 a5 rX.\n\nEnd multi_add_s_u_sect.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/cryptoasm/multi_add_s_u_prg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.23749227143905968}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import CMorphisms.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config Reflect Environment EnvironmentTyping.\nFrom MetaCoq.Template Require Import Ast AstUtils Induction.\n\nRequire Import ssreflect ssrbool.\nFrom Equations.Prop Require Import DepElim.\nFrom Equations Require Import Equations.\nSet Equations With UIP.\n\nDefinition R_universe_instance R :=\n  fun u u' => Forall2 R (List.map Universe.make u) (List.map Universe.make u').\n\n(** Cumulative inductive types:\n\n  To simplify the development, we allow the variance list to not exactly\n  match the instances, so as to keep syntactic equality an equivalence relation\n  even on ill-formed terms. It corresponds to the right notion on well-formed terms.\n*)\n\nDefinition R_universe_variance (Re Rle : Universe.t -> Universe.t -> Prop) v u u' :=\n  match v with\n  | Variance.Irrelevant => True\n  | Variance.Covariant => Rle (Universe.make u) (Universe.make u')\n  | Variance.Invariant => Re (Universe.make u) (Universe.make u')\n  end.\n\nFixpoint R_universe_instance_variance Re Rle v u u' :=\n  match u, u' return Prop with\n  | u :: us, u' :: us' =>\n    match v with\n    | [] => R_universe_instance_variance Re Rle v us us'\n      (* Missing variance stands for irrelevance, we still check that the instances have\n        the same length. *)\n    | v :: vs => R_universe_variance Re Rle v u u' /\\\n        R_universe_instance_variance Re Rle vs us us'\n    end\n  | [], [] => True\n  | _, _ => False\n  end.\n\nDefinition global_variance_gen lookup gr napp :=\n  match gr with\n  | IndRef ind =>\n    match lookup_inductive_gen lookup ind with\n    | Some (mdecl, idecl) =>\n      match destArity [] idecl.(ind_type) with\n      | Some (ctx, _) => if (context_assumptions ctx) <=? napp then mdecl.(ind_variance)\n        else None\n      | None => None\n      end\n    | None => None\n    end\n  | ConstructRef ind k =>\n    match lookup_constructor_gen lookup ind k with\n    | Some (mdecl, idecl, cdecl) =>\n      if (cdecl.(cstr_arity) + mdecl.(ind_npars))%nat <=? napp then\n        (** Fully applied constructors are always compared at the same supertype,\n          which implies that no universe ws_cumul_pb needs to be checked here. *)\n        Some []\n      else None\n    | _ => None\n    end\n  | _ => None\n  end.\n\nNotation global_variance Σ := (global_variance_gen (lookup_env Σ)).\n\nDefinition R_opt_variance Re Rle v :=\n  match v with\n  | Some v => R_universe_instance_variance Re Rle v\n  | None => R_universe_instance Re\n  end.\n\nDefinition R_global_instance_gen Σ Re Rle gr napp :=\n  R_opt_variance Re Rle (global_variance_gen Σ gr napp).\n\nNotation R_global_instance Σ := (R_global_instance_gen (lookup_env Σ)).\n\nLemma R_universe_instance_impl R R' :\n  RelationClasses.subrelation R R' ->\n  RelationClasses.subrelation (R_universe_instance R) (R_universe_instance R').\nProof.\n  intros H x y xy. eapply Forall2_impl ; tea.\nQed.\n\nLemma R_universe_instance_impl' R R' :\n  RelationClasses.subrelation R R' ->\n  forall u u', R_universe_instance R u u' -> R_universe_instance R' u u'.\nProof.\n  intros H x y xy. eapply Forall2_impl ; tea.\nQed.\n\nInductive compare_decls (eq_term leq_term : term -> term -> Type) : context_decl -> context_decl -> Type :=\n\t| compare_vass na T na' T' : eq_binder_annot na na' ->\n    leq_term T T' ->\n    compare_decls eq_term leq_term (vass na T) (vass na' T')\n  | compare_vdef na b T na' b' T' : eq_binder_annot na na' ->\n    eq_term b b' -> leq_term T T' ->\n    compare_decls eq_term leq_term (vdef na b T) (vdef na' b' T').\n\nDerive Signature NoConfusion for compare_decls.\n\nLemma alpha_eq_context_assumptions {Γ Δ} :\n  All2 (compare_decls eq eq) Γ Δ ->\n  context_assumptions Γ = context_assumptions Δ.\nProof.\n  induction 1 in |- *; cbn; auto.\n  destruct r; subst; cbn; auto.\nQed.\n\nLemma alpha_eq_extended_subst {Γ Δ k} :\n  All2 (compare_decls eq eq) Γ Δ ->\n  extended_subst Γ k = extended_subst Δ k.\nProof.\n  induction 1 in k |- *; cbn; auto.\n  destruct r; subst; cbn; f_equal; auto.\n  rewrite IHX. now rewrite (alpha_eq_context_assumptions X).\nQed.\n\nLemma expand_lets_eq {Γ Δ t} :\n  All2 (compare_decls eq eq) Γ Δ ->\n  expand_lets Γ t = expand_lets Δ t.\nProof.\n  intros. rewrite /expand_lets /expand_lets_k.\n  now rewrite (All2_length X) (alpha_eq_context_assumptions X) (alpha_eq_extended_subst X).\nQed.\n\nLemma alpha_eq_subst_context {Γ Δ s k} :\n  All2 (compare_decls eq eq) Γ Δ ->\n  All2 (compare_decls eq eq) (subst_context s k Γ) (subst_context s k Δ).\nProof.\n  intros.\n  rewrite /subst_context.\n  induction X.\n  - cbn; auto.\n  - rewrite !fold_context_k_snoc0. constructor; auto.\n    destruct r; subst; constructor; cbn; auto.\n    all:now rewrite (All2_length X).\nQed.\n\n(** ** Syntactic equality up-to universes\n  We don't look at printing annotations *)\n\n(** Equality is indexed by a natural number that counts the number of applications\n  that surround the current term, used to implement cumulativity of inductive types\n  correctly (only fully applied constructors and inductives benefit from it). *)\n\nInductive eq_term_upto_univ_napp Σ (Re Rle : Universe.t -> Universe.t -> Prop) (napp : nat) : term -> term -> Type :=\n| eq_Rel n  :\n    eq_term_upto_univ_napp Σ Re Rle napp (tRel n) (tRel n)\n\n| eq_Evar e args args' :\n    All2 (eq_term_upto_univ_napp Σ Re Re 0) args args' ->\n    eq_term_upto_univ_napp Σ Re Rle napp (tEvar e args) (tEvar e args')\n\n| eq_Var id :\n    eq_term_upto_univ_napp Σ Re Rle napp (tVar id) (tVar id)\n\n| eq_Sort s s' :\n    Rle s s' ->\n    eq_term_upto_univ_napp Σ Re Rle napp (tSort s) (tSort s')\n\n| eq_App t t' u u' :\n    eq_term_upto_univ_napp Σ Re Rle (#|u| + napp) t t' ->\n    All2 (eq_term_upto_univ_napp Σ Re Re 0) u u' ->\n    eq_term_upto_univ_napp Σ Re Rle napp (tApp t u) (tApp t' u')\n\n| eq_Const c u u' :\n    R_universe_instance Re u u' ->\n    eq_term_upto_univ_napp Σ Re Rle napp (tConst c u) (tConst c u')\n\n| eq_Ind i u u' :\n    R_global_instance Σ Re Rle (IndRef i) napp u u' ->\n    eq_term_upto_univ_napp Σ Re Rle napp (tInd i u) (tInd i u')\n\n| eq_Construct i k u u' :\n    R_global_instance Σ Re Rle (ConstructRef i k) napp u u' ->\n    eq_term_upto_univ_napp Σ Re Rle napp (tConstruct i k u) (tConstruct i k u')\n\n| eq_Lambda na na' ty ty' t t' :\n    eq_binder_annot na na' ->\n    eq_term_upto_univ_napp Σ Re Re 0 ty ty' ->\n    eq_term_upto_univ_napp Σ Re Rle 0 t t' ->\n    eq_term_upto_univ_napp Σ Re Rle napp (tLambda na ty t) (tLambda na' ty' t')\n\n| eq_Prod na na' a a' b b' :\n    eq_binder_annot na na' ->\n    eq_term_upto_univ_napp Σ Re Re 0 a a' ->\n    eq_term_upto_univ_napp Σ Re Rle 0 b b' ->\n    eq_term_upto_univ_napp Σ Re Rle napp (tProd na a b) (tProd na' a' b')\n\n| eq_LetIn na na' t t' ty ty' u u' :\n    eq_binder_annot na na' ->\n    eq_term_upto_univ_napp Σ Re Re 0 t t' ->\n    eq_term_upto_univ_napp Σ Re Re 0 ty ty' ->\n    eq_term_upto_univ_napp Σ Re Rle 0 u u' ->\n    eq_term_upto_univ_napp Σ Re Rle napp (tLetIn na t ty u) (tLetIn na' t' ty' u')\n\n| eq_Case ind p p' c c' brs brs' :\n    All2 (eq_term_upto_univ_napp Σ Re Re 0) p.(pparams) p'.(pparams) ->\n    R_universe_instance Re p.(puinst) p'.(puinst) ->\n    eq_term_upto_univ_napp Σ Re Re 0 p.(preturn) p'.(preturn) ->\n    All2 eq_binder_annot p.(pcontext) p'.(pcontext) ->\n    eq_term_upto_univ_napp Σ Re Re 0 c c' ->\n    All2 (fun x y =>\n      All2 (eq_binder_annot) (bcontext x) (bcontext y) *\n      eq_term_upto_univ_napp Σ Re Re 0 (bbody x) (bbody y)\n    ) brs brs' ->\n  eq_term_upto_univ_napp Σ Re Rle napp (tCase ind p c brs) (tCase ind p' c' brs')\n\n| eq_Proj p c c' :\n    eq_term_upto_univ_napp Σ Re Re 0 c c' ->\n    eq_term_upto_univ_napp Σ Re Rle napp (tProj p c) (tProj p c')\n\n| eq_Fix mfix mfix' idx :\n    All2 (fun x y =>\n      eq_term_upto_univ_napp Σ Re Re 0 x.(dtype) y.(dtype) *\n      eq_term_upto_univ_napp Σ Re Re 0 x.(dbody) y.(dbody) *\n      (x.(rarg) = y.(rarg)) *\n      eq_binder_annot x.(dname) y.(dname)\n    )%type mfix mfix' ->\n    eq_term_upto_univ_napp Σ Re Rle napp (tFix mfix idx) (tFix mfix' idx)\n\n| eq_CoFix mfix mfix' idx :\n    All2 (fun x y =>\n      eq_term_upto_univ_napp Σ Re Re 0 x.(dtype) y.(dtype) *\n      eq_term_upto_univ_napp Σ Re Re 0 x.(dbody) y.(dbody) *\n      (x.(rarg) = y.(rarg)) *\n      eq_binder_annot x.(dname) y.(dname)\n    ) mfix mfix' ->\n    eq_term_upto_univ_napp Σ Re Rle napp (tCoFix mfix idx) (tCoFix mfix' idx)\n\n| eq_Cast t1 c t2 t1' c' t2' :\n  eq_term_upto_univ_napp Σ Re Re 0 t1 t1' ->\n  eq_cast_kind c c' ->\n  eq_term_upto_univ_napp Σ Re Re 0 t2 t2' ->\n  eq_term_upto_univ_napp Σ Re Rle napp (tCast t1 c t2) (tCast t1' c' t2')\n\n| eq_Int i : eq_term_upto_univ_napp Σ Re Rle napp (tInt i) (tInt i)\n| eq_Float f : eq_term_upto_univ_napp Σ Re Rle napp (tFloat f) (tFloat f).\n\nNotation eq_term_upto_univ Σ Re Rle := (eq_term_upto_univ_napp Σ Re Rle 0).\n\n(* ** Syntactic conversion/cumulativity up-to universes *)\n\nDefinition compare_term `{checker_flags} (pb : conv_pb) Σ φ :=\n  eq_term_upto_univ Σ (eq_universe φ) (compare_universe pb φ).\n\nNotation eq_term := (compare_term Conv).\nNotation leq_term := (compare_term Cumul).\n\nLemma R_global_instance_refl Σ Re Rle gr napp u :\n  RelationClasses.Reflexive Re ->\n  RelationClasses.Reflexive Rle ->\n  R_global_instance Σ Re Rle gr napp u u.\nProof.\n  intros rRE rRle.\n  rewrite /R_global_instance_gen.\n  destruct global_variance_gen as [v|] eqn:lookup.\n  - induction u in v |- *; simpl; auto;\n    unfold R_opt_variance in IHu; destruct v; simpl; auto.\n    split; auto.\n    destruct t; simpl; auto.\n  - apply Forall2_same; eauto.\nQed.\n\n#[global] Instance eq_binder_annot_equiv {A} : RelationClasses.Equivalence (@eq_binder_annot A A).\nProof.\n  split.\n  - red. reflexivity.\n  - red; now symmetry.\n  - intros x y z; unfold eq_binder_annot.\n    congruence.\nQed.\n\nDefinition eq_binder_annot_refl {A} x : @eq_binder_annot A A x x.\nProof. reflexivity. Qed.\n#[global] Hint Resolve eq_binder_annot_refl : core.\n\n#[global] Instance eq_binder_annots_refl {A} : CRelationClasses.Equivalence (All2 (@eq_binder_annot A A)).\nProof.\n  split.\n  intros x. apply All2_reflexivity; tc.\n  * intros l. reflexivity.\n  * intros l l' H. eapply All2_symmetry => //.\n  * intros l l' H. eapply All2_transitivity => //.\n    intros ? ? ? ? ?. now etransitivity.\nQed.\n\nLemma eq_term_upto_univ_refl Σ Re Rle :\n  RelationClasses.Reflexive Re ->\n  RelationClasses.Reflexive Rle ->\n  forall napp t, eq_term_upto_univ_napp Σ Re Rle napp t t.\nProof.\n  intros hRe hRle napp.\n  induction t in napp, Rle, hRle |- * using term_forall_list_rect; simpl;\n    try constructor; try apply Forall_Forall2; try apply All_All2 ; try easy;\n      try now (try apply Forall_All ; apply Forall_True).\n  - eapply All_All2. 1: eassumption.\n    intros. simpl in X0. easy.\n  - destruct c; constructor.\n  - eapply All_All2. 1: eassumption.\n    intros. easy.\n  - now apply R_global_instance_refl.\n  - now apply R_global_instance_refl.\n  - destruct X as [Ppars Preturn]. eapply All_All2. 1:eassumption.\n    intros; easy.\n  - destruct X as [Ppars Preturn]. now apply Preturn.\n  - red in X0. eapply All_All2_refl. solve_all. reflexivity.\n  - eapply All_All2. 1: eassumption.\n    intros x [? ?]. repeat split ; auto.\n  - eapply All_All2. 1: eassumption.\n    intros x [? ?]. repeat split ; auto.\nQed.\n\nLemma eq_term_refl `{checker_flags} Σ φ t : eq_term Σ φ t t.\nProof.\n  apply eq_term_upto_univ_refl.\n  - intro; apply eq_universe_refl.\n  - intro; apply eq_universe_refl.\nQed.\n\n\nLemma leq_term_refl `{checker_flags} Σ φ t : leq_term Σ φ t t.\nProof.\n  apply eq_term_upto_univ_refl.\n  - intro; apply eq_universe_refl.\n  - intro; apply leq_universe_refl.\nQed.\n(*\nLemma eq_term_leq_term `{checker_flags} Σ φ napp t u :\n  eq_term_upto_univ_napp Σ napp φ t u -> leq_term Σ φ t u.\nProof.\n  induction t in u |- * using term_forall_list_rect; simpl; inversion 1;\n    subst; constructor; try (now unfold eq_term, leq_term in * );\n  try eapply Forall2_impl' ; try eapply All2_impl' ; try easy.\n  now apply eq_universe_leq_universe.\n  all: try (apply Forall_True, eq_universe_leq_universe).\n  apply IHt.\nQed. *)\n\n#[global] Instance R_global_instance_impl_same_napp Σ Re Re' Rle Rle' gr napp :\n  RelationClasses.subrelation Re Re' ->\n  RelationClasses.subrelation Rle Rle' ->\n  subrelation (R_global_instance Σ Re Rle gr napp) (R_global_instance Σ Re' Rle' gr napp).\nProof.\n  intros he hle t t'.\n  rewrite /R_global_instance_gen /R_opt_variance.\n  destruct global_variance_gen as [v|] eqn:glob.\n  induction t in v, t' |- *; destruct v, t'; simpl; auto.\n  intros []; split; auto.\n  destruct t0; simpl; auto.\n  now eapply R_universe_instance_impl'.\nQed.\n\nLemma eq_term_upto_univ_morphism0 Σ (Re Re' : _ -> _ -> Prop)\n      (Hre : forall t u, Re t u -> Re' t u)\n  : forall t u napp, eq_term_upto_univ_napp Σ Re Re napp t u -> eq_term_upto_univ_napp Σ Re' Re' napp t u.\nProof.\n  fix aux 4.\n  destruct 1; constructor; eauto.\n  all: unfold R_universe_instance in *.\n  all: try solve[ match goal with\n       | H : All2 _ _ _ |- _ => clear -H aux; induction H; constructor; eauto\n       | H : Forall2 _ _ _ |- _ => induction H; constructor; eauto\n       end].\n  - eapply R_global_instance_impl_same_napp; eauto.\n  - eapply R_global_instance_impl_same_napp; eauto.\n  - induction a1; constructor; auto. intuition auto.\n  - induction a; constructor; auto. intuition auto.\n  - induction a; constructor; auto. intuition auto.\nQed.\n\nLemma eq_term_upto_univ_morphism Σ (Re Re' Rle Rle' : _ -> _ -> Prop)\n      (Hre : forall t u, Re t u -> Re' t u)\n      (Hrle : forall t u, Rle t u -> Rle' t u)\n  : forall t u napp, eq_term_upto_univ_napp Σ Re Rle napp t u -> eq_term_upto_univ_napp Σ Re' Rle' napp t u.\nProof.\n  fix aux 4.\n  destruct 1; constructor; eauto using eq_term_upto_univ_morphism0.\n  all: unfold R_universe_instance in *.\n  all: try solve [match goal with\n       | H : Forall2 _ _ _ |- _ => induction H; constructor;\n                                   eauto using eq_term_upto_univ_morphism0\n       | H : All2 _ _ _ |- _ => induction H; constructor;\n                                eauto using eq_term_upto_univ_morphism0\n       end].\n  - clear X. induction a; constructor; eauto using eq_term_upto_univ_morphism0.\n  - eapply R_global_instance_impl_same_napp; eauto.\n  - eapply R_global_instance_impl_same_napp; eauto.\n  - clear X1 X2. induction a1; constructor; eauto using eq_term_upto_univ_morphism0.\n    destruct r0. split; eauto using eq_term_upto_univ_morphism0.\n  - induction a; constructor; eauto using eq_term_upto_univ_morphism0.\n    destruct r as [[[? ?] ?] ?].\n    repeat split; eauto using eq_term_upto_univ_morphism0.\n  - induction a; constructor; eauto using eq_term_upto_univ_morphism0.\n    destruct r as [[[? ?] ?] ?].\n    repeat split; eauto using eq_term_upto_univ_morphism0.\nQed.\n\n\nLemma global_variance_napp_mon {Σ gr napp napp' v} :\n  napp <= napp' ->\n  global_variance Σ gr napp = Some v ->\n  global_variance Σ gr napp' = Some v.\nProof.\n  intros hnapp.\n  rewrite /global_variance_gen.\n  destruct gr; try congruence.\n  - destruct lookup_inductive_gen as [[mdecl idec]|] => //.\n    destruct destArity as [[ctx s]|] => //.\n    elim: Nat.leb_spec => // cass indv.\n    elim: Nat.leb_spec => //. lia.\n  - destruct lookup_constructor_gen as [[[mdecl idecl] cdecl]|] => //.\n    elim: Nat.leb_spec => // cass indv.\n    elim: Nat.leb_spec => //. lia.\nQed.\n\n#[global] Instance R_global_instance_impl Σ Re Re' Rle Rle' gr napp napp' :\n  RelationClasses.subrelation Re Re' ->\n  RelationClasses.subrelation Re Rle' ->\n  RelationClasses.subrelation Rle Rle' ->\n  napp <= napp' ->\n  subrelation (R_global_instance Σ Re Rle gr napp) (R_global_instance Σ Re' Rle' gr napp').\nProof.\n  intros he hle hele hnapp t t'.\n  rewrite /R_global_instance_gen /R_opt_variance.\n  destruct global_variance_gen as [v|] eqn:glob.\n  rewrite (global_variance_napp_mon hnapp glob).\n  induction t in v, t' |- *; destruct v, t'; simpl; auto.\n  intros []; split; auto.\n  destruct t0; simpl; auto.\n  destruct (global_variance _ _ napp') as [v|] eqn:glob'; eauto using R_universe_instance_impl'.\n  induction t in v, t' |- *; destruct v, t'; simpl; auto; intros H; inv H.\n  eauto.\n  split; auto.\n  destruct t0; simpl; auto.\nQed.\n\n#[global] Instance eq_term_upto_univ_impl Σ Re Re' Rle Rle' napp napp' :\n  RelationClasses.subrelation Re Re' ->\n  RelationClasses.subrelation Rle Rle' ->\n  RelationClasses.subrelation Re Rle' ->\n  napp <= napp' ->\n  subrelation (eq_term_upto_univ_napp Σ Re Rle napp) (eq_term_upto_univ_napp Σ Re' Rle' napp').\nProof.\n  intros he hle hele hnapp t t'.\n  induction t in napp, napp', hnapp, t', Rle, Rle', hle, hele |- * using term_forall_list_rect;\n    try (inversion 1; subst; constructor;\n         eauto using R_universe_instance_impl'; fail).\n  - inversion 1; subst; constructor.\n    eapply All2_impl'; tea.\n    eapply All_impl; eauto.\n  - inversion 1; subst; constructor.\n    eapply IHt. 4:eauto. all:auto with arith. eauto.\n    solve_all.\n  - inversion 1; subst; constructor.\n    eapply R_global_instance_impl. 5:eauto. all:auto.\n  - inversion 1; subst; constructor.\n    eapply R_global_instance_impl. 5:eauto. all:eauto.\n  - destruct X as [IHpars IHret].\n    inversion 1; subst; constructor; eauto.\n    eapply All2_impl'; tea.\n    eapply All_impl; eauto.\n    eapply R_universe_instance_impl; eauto.\n    eapply All2_impl'; eauto.\n    cbn.\n    eapply All_impl; eauto.\n    intros x ? y [? ?]. split; eauto.\n  - inversion 1; subst; constructor.\n    eapply All2_impl'; tea.\n    eapply All_impl; eauto.\n    cbn. intros x [? ?] y [[[? ?] ?] ?]. repeat split; eauto.\n  - inversion 1; subst; constructor.\n    eapply All2_impl'; tea.\n    eapply All_impl; eauto.\n    cbn. intros x [? ?] y [[[? ?] ?] ?]. repeat split; eauto.\nQed.\n\n\nLemma eq_term_leq_term `{checker_flags} Σ φ t u :\n  eq_term Σ φ t u -> leq_term Σ φ t u.\nProof.\n  eapply eq_term_upto_univ_morphism. auto.\n  intros.\n  now apply eq_universe_leq_universe.\nQed.\n\nLemma eq_term_upto_univ_App `{checker_flags} Σ Re Rle napp f f' :\n  eq_term_upto_univ_napp Σ Re Rle napp f f' ->\n  isApp f = isApp f'.\nProof.\n  inversion 1; reflexivity.\nQed.\n\nLemma eq_term_App `{checker_flags} Σ φ f f' :\n  eq_term Σ φ f f' ->\n  isApp f = isApp f'.\nProof.\n  inversion 1; reflexivity.\nQed.\n\nLemma eq_term_upto_univ_mkApps `{checker_flags} Σ Re Rle napp f l f' l' :\n  eq_term_upto_univ_napp Σ Re Rle (#|l| + napp) f f' ->\n  All2 (eq_term_upto_univ Σ Re Re) l l' ->\n  eq_term_upto_univ_napp Σ Re Rle napp (mkApps f l) (mkApps f' l').\nProof.\n  induction l in f, f' |- *; intro e; inversion_clear 1.\n  - assumption.\n  - pose proof (eq_term_upto_univ_App _ _ _ _ _ _ e).\n    case_eq (isApp f).\n    + intro X; rewrite X in H0.\n      destruct f; try discriminate.\n      destruct f'; try discriminate.\n      cbn. inversion_clear e. constructor.\n      rewrite app_length /= -Nat.add_assoc //.\n      apply All2_app. assumption.\n      now constructor.\n    + intro X; rewrite X in H0.\n      eapply negbT in X. symmetry in H0; eapply negbT in H0.\n      rewrite - !mkApps_tApp //.\n      constructor. simpl. now simpl in e.\n      now constructor.\nQed.\n\nLemma leq_term_mkApps `{checker_flags} Σ φ f l f' l' :\n  leq_term Σ φ f f' ->\n  All2 (eq_term Σ φ) l l' ->\n  leq_term Σ φ (mkApps f l) (mkApps f' l').\nProof.\n  intros.\n  eapply eq_term_upto_univ_mkApps.\n  eapply eq_term_upto_univ_impl. 5:eauto. 4:auto with arith.\n  1-3:typeclasses eauto.\n  apply X0.\nQed.\n\nLemma leq_term_App `{checker_flags} Σ φ f f' :\n  leq_term Σ φ f f' ->\n  isApp f = isApp f'.\nProof.\n  inversion 1; reflexivity.\nQed.", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/template-coq/theories/TermEquality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.23749227143905968}}
{"text": "Require Import String.\nRequire Import Functors.\nRequire Import MonadLib.\nRequire Import Names.\nRequire Import EffPure.\nRequire Import EffState.\nRequire Import EffExcept.\nRequire Import Bool.\nRequire Import Ref.\nRequire Import Exception.\nRequire Import ESoundES.\n\nOpen Scope string_scope.\n\nSection Test_Section.\n\n  Definition D := BType :+: RefType :+: UnitType.\n\n  Definition E := Bool :+: RefE :+: (ExceptE D).\n\n  Definition V := StuckValue :+: BoolValue :+:\n    UnitValue :+: LocValue.\n\n  Variable MT : Set -> Set.\n  Context `{Fail_MT : FailMonad MT}.\n  Context {Inj_MT : InjMonad MT}.\n  Context {Reasonable_MT : Reasonable_Monad MT}.\n  Context {MT_eq_dec : forall (A : Set) (mta : MT A),\n    {exists a, mta = return_ a} + {mta = fail}}.\n\n  Variable ME : Set -> Set.\n  Context `{StateM_ME : StateM ME (list (Value V))}.\n  Context {Exception_ME : Exception ME Datatypes.unit}.\n  Context {Reasonable_ME : Reasonable_Monad ME}.\n\n  Definition WFV := (WFValue_VB D V (list (Names.DType D))) ::+::\n    (WFValue_Unit D V (list (Names.DType D)) ::+:: (WFValue_Loc D V (list (Names.DType D)))).\n\n  Definition WFVM := (WFValueM_base D V MT ME _ WFV) ::+::\n    (WFValueM_State D V MT ME _\n      (TypContextCE := DType_Env_CE _)\n      (TypContext_WFE := DType_Env_WFE _ _ WFV))\n    ::+:: (WFValueM_Except D V MT ME _).\n\n  Instance eq_DType_eq_alg : PAlgebra eq_DType_eqName D D (UP'_P (eq_DType_eq_P D)).\n  Proof.\n    eauto 250 with typeclass_instances.\n  Defined.\n\n  Instance eq_DType_neq_alg : PAlgebra eq_DType_neqName D D (UP'_P (eq_DType_neq_P D)).\n  Proof.\n    eauto 250 with typeclass_instances.\n  Defined.\n\n  Instance typeof_alg : forall T, FAlgebra TypeofName T (typeofR D MT) (E).\n  Proof.\n    intros; eauto 150 with typeclass_instances.\n  Defined.\n\n  Instance eval_alg : forall T : Set, FAlgebra EvalName T (evalMR V ME) E.\n  Proof.\n    intros; eauto 250 with typeclass_instances.\n  Defined.\n\n    Context {ME_eq_dec' : forall (A : Set) (mte : ME A) (env : list (Value V)),\n      (exists a, exists env',\n        put env >> mte = put env' >> return_ a) \\/\n      (exists env', put env >> mte = put env' >> throw tt)}.\n    Context {put_catch : forall (A : Set) (env : list (Value V)) e h,\n      put env >>= (fun _ => catch (A := A) e h) = catch (put env >>= fun _ => e) h}.\n    Context {Put_Exception_Disc :\n      forall (A B : Set) (a : A) (mb : ME B) env n,\n        (put env >>= fun _ => return_ a) <> mb >>= fun _ => throw n}.\n    Context {put_throw : forall (A B : Set) (env env' : list (Value V)) t,\n      put env >>= (fun _ => throw t (A := A)) = put env' >>= (fun _ => throw t) ->\n      put env >>= (fun _ => throw t (A := B)) = put env' >>= (fun _ => throw t)}.\n\n  Theorem eval_Sound :\n    forall (e : Exp E) Sigma (T : DType D)\n      (env : list (Value V)),\n      WF_Environment D V _ WFV Sigma env Sigma ->\n      fmap (@proj1_sig _ _) (typeof D E MT (proj1_sig e)) = return_ (proj1_sig T) ->\n      (exists v : Value V, exists env', exists Sigma',\n        (put env) >> evalM (evalM_E := eval_alg) V E ME (proj1_sig e) = put env' >> return_ (M := ME) v /\\\n        WFValueC D V _ WFV Sigma' v T) \\/\n      (exists t, exists env', exists Sigma',\n        put env >> evalM (evalM_E := eval_alg) V E ME (proj1_sig e) = put env' >> throw t\n        /\\ WF_Environment D V _ WFV Sigma' env' Sigma'\n        /\\ (forall n T, lookup Sigma n = Some T -> lookup Sigma' n = Some T)).\n  Proof.\n    apply eval_Except_State_Sound with (WFVM' := WFVM);\n      eauto 5 with typeclass_instances.\n    eauto 50 with typeclass_instances.\n    intros; repeat apply @P2Algebra_Plus.\n    eapply Bool_eval_soundness' with (WFV := WFV) (WFVM := WFVM);\n      eauto 250 with typeclass_instances.\n    eapply Ref_eval_soundness'' with (WFV := WFV) (WFVM := WFVM)\n      (TypContextCE :=  _) (TypContext_S := _)\n      (TypContext_WFE := DType_Env_WFE _ _ WFV);\n      eauto 250 with typeclass_instances.\n    eapply Except_eval_soundness' with (WFVM := WFVM);\n      eauto 250 with typeclass_instances.\n  Qed.\n\n  Eval compute in (\"Soundness for 'Bool :+: Ref :+: Exceptions ' Proven!\").\n\nEnd Test_Section.\n\n(*\n*** Local Variables: ***\n*** coq-prog-args: (\"-emacs-U\" \"-impredicative-set\") ***\n*** End: ***\n*)\n", "meta": {"author": "skeuchel", "repo": "3mt", "sha": "8b7f721f4a05e3e6eab60a64415240a3637ea104", "save_path": "github-repos/coq/skeuchel-3mt", "path": "github-repos/coq/skeuchel-3mt/3mt-8b7f721f4a05e3e6eab60a64415240a3637ea104/LSound/test_BRE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.3665897432423098, "lm_q1q2_score": 0.2374761873771947}}
{"text": "(** Bounded Instantiated Maps **)\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Relations.Relations.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Structures.Monad.\nRequire Import ExtLib.Structures.Traversable.\nRequire Import ExtLib.Data.Option.\nRequire Import ExtLib.Data.Prop.\nRequire Import ExtLib.Data.Pair.\nRequire Import ExtLib.Data.List.\nRequire Import ExtLib.Data.ListFirstnSkipn.\nRequire Import ExtLib.Data.HList.\nRequire Import ExtLib.Data.Monads.OptionMonad.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.SubstI.\nRequire Import MirrorCore.VariablesI.\nRequire Import MirrorCore.ExprDAs.\nRequire Import MirrorCore.Subst.FMapSubst.\nRequire Import MirrorCore.Instantiate.\n\nRequire Import MirrorCore.Util.Quant.\nRequire Import MirrorCore.Util.Forwardy.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(** TODO: This has to be somewhere else **)\nInstance Reflexive_pointwise\n         {T U} {R : U -> U -> Prop} (Refl : Reflexive R)\n: Reflexive (pointwise_relation T R).\nProof.\n  red. red. reflexivity.\nQed.\n\nSection parameterized.\n  Variable typ : Set.\n  Variable expr : Set.\n\n  Context {RType_typ : RType typ}.\n  Context {RTypeOk_typ : RTypeOk}.\n  Context {Typ0_Prop : Typ0 _ Prop}.\n  Context {Expr_expr : Expr typ expr}.\n  Context {ExprOk_expr : ExprOk Expr_expr}.\n  Context {ExprVar_expr : ExprVar expr}.\n  Context {ExprVarOk_expr : ExprVarOk _}.\n  Context {ExprUVar_expr : ExprUVar expr}.\n  Context {ExprUVarOk_expr : ExprUVarOk _}.\n\n  Local Instance RelDec_eq_typ : RelDec (@eq typ) :=\n    RelDec_Rty _.\n  Local Instance RelDecOk_eq_typ : RelDec_Correct RelDec_eq_typ :=\n    @RelDec_Correct_Rty _ _ _.\n\n  Local Existing Instance SUBST.Subst_subst.\n  Local Existing Instance SUBST.SubstOk_subst.\n  Local Existing Instance SUBST.SubstOpen_subst.\n  Local Existing Instance SUBST.SubstOpenOk_subst.\n\n  Definition amap : Type := SUBST.raw expr.\n  Definition WellFormed_amap : amap -> Prop := @SUBST.WellFormed _ _ _ _.\n  Definition amap_empty : amap := UVarMap.MAP.empty _.\n  Definition amap_lookup : nat -> amap -> option expr :=\n    @UVarMap.MAP.find _.\n  Definition amap_check_set : nat -> expr -> amap -> option amap :=\n    @SUBST.raw_set _ _ _ _.\n  Definition amap_instantiate (f : nat -> option expr) : amap -> amap :=\n    UVarMap.MAP.map (fun e => instantiate f 0 e).\n  Definition amap_substD\n  : forall (tus tvs : tenv typ), amap -> option (exprT tus tvs Prop) :=\n    @SUBST.raw_substD _ _ _ _.\n  Definition amap_is_full (* min : uvar *) (len : nat) (m : amap) : bool :=\n    UVarMap.MAP.cardinal m ?[ eq ] len.\n  Definition amap_domain (m : amap) : list uvar :=\n    map fst (UVarMap.MAP.elements m).\n  Fixpoint amap_aslist (m : amap) (f n : nat) : list (option expr) :=\n    match n with\n      | O => nil\n      | S n => amap_lookup f m :: amap_aslist m (S f) n\n    end.\n\n  Definition Forall_amap (P : uvar -> expr -> Prop) (m : amap) : Prop :=\n    forall u e,\n      amap_lookup u m = Some e ->\n      P u e.\n\n  Lemma Forall_amap_empty\n  : forall P, Forall_amap P amap_empty.\n  Proof.\n    clear. intros.\n    red. unfold amap_lookup, amap_empty.\n    intros. rewrite FMapSubst.SUBST.FACTS.empty_o in H. congruence.\n  Qed.\n\n  Definition bimap_max (maxU maxV : nat) e : Prop :=\n    mentionsAny (fun u' => u' ?[ ge ] maxU)\n                (fun v' => v' ?[ ge ] maxV) e = false.\n\n\n  Definition WellFormed_bimap (min : nat) (len : nat) (maxV : nat) (m : amap)\n  : Prop :=\n    (** 'acyclic' **)\n    SUBST.WellFormed m /\\\n    (** only in this range **)\n    Forall_amap (fun k _ => min <= k < min + len) m /\\\n    (** no forward pointers **)\n    Forall_amap (fun k e => bimap_max (min + len) maxV e) m.\n\n  Lemma WellFormed_bimap_empty\n  : forall a b c, WellFormed_bimap a b c amap_empty.\n  Proof.\n    clear - RTypeOk_typ Expr_expr. red.\n    intros. refine (conj _ (conj _ _));\n            eauto using SUBST.WellFormed_empty, Forall_amap_empty.\n    eapply SUBST.WellFormed_empty.\n  Qed.\n\n  Lemma WellFormed_bimap_WellFormed_amap\n  : forall a b c s,\n      WellFormed_bimap a b c s ->\n      WellFormed_amap s.\n  Proof.\n    destruct 1. assumption.\n  Qed.\n\n  Lemma amap_instantiates_substD\n  : forall tus tvs C (_ : CtxLogic.ExprTApplicative C) f s sD a b c,\n      WellFormed_bimap a b c s ->\n      amap_substD tus tvs s = Some sD ->\n      sem_preserves_if_ho C f ->\n      exists sD',\n        amap_substD tus tvs (amap_instantiate f s) = Some sD' /\\\n        C (fun us vs => sD us vs <-> sD' us vs).\n  Proof.\n    unfold amap_instantiate.\n    intros.\n    eapply SUBST.raw_substD_instantiate_ho in H2; eauto.\n    forward_reason.\n    eexists; split; eauto.\n    revert H3.\n    eapply CtxLogic.exprTAp.\n    eapply CtxLogic.exprTPure.\n    intros us vs.\n    clear. tauto.\n  Qed.\n\n  Lemma amap_lookup_substD\n  : forall (s : amap) (uv : uvar) (e : expr),\n      amap_lookup uv s = Some e ->\n      forall (tus tvs : list typ)\n             (sD : hlist typD tus -> hlist typD tvs -> Prop),\n        amap_substD tus tvs s = Some sD ->\n        exists\n          (t : typ) (val : exprT tus tvs (typD t))\n          (get : hlist typD tus -> typD t),\n          nth_error_get_hlist_nth typD tus uv =\n          Some (existT (fun t0 : typ => hlist typD tus -> typD t0) t get) /\\\n          exprD tus tvs t e = Some val /\\\n          (forall (us : hlist typD tus) (vs : hlist typD tvs),\n             sD us vs -> get us = val us vs).\n  Proof. eapply SUBST.substD_lookup'; eauto. Qed.\n\n  Lemma amap_substD_amap_empty\n    : forall tus tvs,\n      exists sD,\n        amap_substD tus tvs amap_empty = Some sD /\\\n        forall a b, sD a b.\n  Proof using.\n    intros.\n    eapply FMapSubst.SUBST.substD_empty.\n  Qed.\n\n  Lemma amap_domain_WellFormed\n  : forall (s : amap) (ls : list uvar),\n       WellFormed_amap s ->\n       amap_domain s = ls ->\n       forall n : nat, In n ls <-> amap_lookup n s <> None.\n  Proof. eapply SUBST.WellFormed_domain. Qed.\n\n  Lemma amap_lookup_normalized\n  : forall (s : amap) (e : expr) (u : nat),\n      WellFormed_amap s ->\n      amap_lookup u s = Some e ->\n      forall (u' : nat) (e' : expr),\n        amap_lookup u' s = Some e' -> mentionsU u' e = false.\n  Proof. eapply SUBST.normalized_fmapsubst. Qed.\n\n  Lemma amap_lookup_amap_instantiate\n  : forall u f m,\n      amap_lookup u (amap_instantiate f m) =\n      match amap_lookup u m with\n        | None => None\n        | Some e => Some (instantiate f 0 e)\n      end.\n  Proof.\n    unfold amap_lookup, amap_instantiate; intros.\n    apply SUBST.FACTS.map_o.\n  Qed.\n\n  Lemma syn_check_set\n  : forall uv e s s',\n      WellFormed_amap s ->\n      amap_check_set uv e s = Some s' ->\n      let e' := instantiate (fun u => amap_lookup u s) 0 e in\n      WellFormed_amap s' /\\\n      mentionsU uv e'= false /\\\n      forall u,\n        amap_lookup u s' =\n        if uv ?[ eq ] u then Some e'\n        else\n          match amap_lookup u s with\n            | None => None\n            | Some e =>\n              Some (instantiate (fun u =>\n                                   if uv ?[ eq ] u then Some e'\n                                   else None) 0 e)\n          end.\n  Proof.\n    intros. unfold amap_check_set, SUBST.raw_set in *.\n    forward. inv_all; subst.\n    split.\n    { eapply SUBST.raw_set_WellFormed; eauto.\n      instantiate (1 := e). instantiate (1 := uv).\n      unfold amap_check_set, SUBST.raw_set in *.\n      rewrite H0. reflexivity. }\n    split.\n    { assumption. }\n    intros.\n    unfold amap_lookup.\n    rewrite SUBST.FACTS.add_o.\n    destruct (SUBST.PROPS.F.eq_dec uv u); subst.\n    { rewrite rel_dec_eq_true; eauto with typeclass_instances. }\n    { rewrite rel_dec_neq_false; eauto with typeclass_instances.\n      unfold SUBST.raw_instantiate.\n      rewrite SUBST.FACTS.map_o.\n      destruct (UVarMap.MAP.find u s); try reflexivity. }\n  Qed.\n\n  Lemma mentionsAny_false_mentionsV\n    : forall fU fV v e,\n      mentionsAny fU fV e = false ->\n      mentionsV v e = true ->\n      fV v = false.\n  Proof.\n    intros. eapply mentionsAny_complete_false in H.\n    destruct H.\n    eauto. eauto.\n  Qed.\n\n  Lemma mentionsAny_false_mentionsU\n    : forall fU fV u e,\n      mentionsAny fU fV e = false ->\n      mentionsU u e = true ->\n      fU u = false.\n  Proof.\n    intros. eapply mentionsAny_complete_false in H.\n    destruct H.\n    eauto. eauto.\n  Qed.\n\n  Lemma WellFormed_bimap_check_set\n  : forall uv e s min len maxV s',\n      amap_check_set uv e s = Some s' ->\n      mentionsAny (fun u' => u' ?[ ge ] (min + len))\n                  (fun v' => v' ?[ ge ] maxV) e = false ->\n      min <= uv < min + len ->\n      WellFormed_bimap min len maxV s ->\n      WellFormed_bimap min len maxV s'.\n  Proof.\n    intros.\n    eapply syn_check_set in H; eauto.\n    red in H2. red.\n    { forward_reason.\n      split; auto.\n      split.\n      { red in H3. red.\n        intros.\n        rewrite H7 in H8.\n        consider (uv ?[ eq ] u); intros; subst.\n        omega.\n        forward. eapply H3; eauto. }\n      { red in H4; red; intros.\n        rewrite H7 in H8; clear H7.\n        consider (uv ?[ eq ] u); intros; subst.\n        { inv_all; subst.\n          eapply mentionsAny_complete_false; [ eauto | ].\n          split; intros.\n          { eapply mentionsU_instantiate in H7.\n            eapply mentionsAny_complete_false in H0; try eassumption.\n            destruct H0.\n            destruct H7.\n            { eapply H0. tauto. }\n            { forward_reason.\n              eapply H4 in H7.\n              eapply mentionsAny_complete_false in H7; try eassumption.\n              destruct H7; eauto. } }\n          { eapply mentionsV_instantiate_0 in H7; try eassumption.\n            destruct H7.\n            { eapply mentionsAny_false_mentionsV in H0; eauto. }\n            { destruct H7.\n              forward_reason.\n              eapply H4 in H8. eapply mentionsAny_false_mentionsV in H8; eauto. } } }\n        { forward.\n          inv_all; subst.\n          eapply mentionsAny_complete_false; try eassumption.\n          split.\n          { intros.\n            eapply H4 in H8.\n            eapply mentionsU_instantiate in H9.\n            destruct H9.\n            { forward_reason; forward.\n              eapply mentionsAny_false_mentionsU in H8; eauto. }\n            { forward_reason. forward.\n              subst. inv_all; subst.\n              eapply mentionsU_instantiate in H11.\n              destruct H11.\n              { forward_reason.\n                eapply mentionsAny_false_mentionsU in H11. eapply H11.\n                eapply H0. }\n              { forward_reason.\n                eapply mentionsAny_false_mentionsU in H12. eapply H12.\n                eapply H4. eauto. } } }\n          { intros.\n            eapply mentionsV_instantiate_0 in H9; try eassumption.\n            destruct H9.\n            { eapply H4 in H8.\n              eapply mentionsAny_false_mentionsV in H8; eauto. }\n            { forward_reason. forward.\n              inv_all; subst.\n              eapply mentionsV_instantiate_0 in H11; try eassumption.\n              destruct H11.\n              { eapply mentionsAny_false_mentionsV in H10. eapply H10.\n                eapply H0. }\n              { forward_reason.\n                eapply H4 in H11.\n                eapply mentionsAny_false_mentionsV in H11. eapply H11. auto. } } } } } }\n    { destruct H2. assumption. }\n  Qed.\n\n  Lemma Forall_amap_instantiate\n  : forall (P Q : uvar -> expr -> Prop) f m,\n      (forall u e, Q u e -> P u (instantiate f 0 e)) ->\n      Forall_amap Q m ->\n      Forall_amap P (amap_instantiate f m).\n  Proof.\n    clear.\n    intros. red.\n    unfold amap_lookup, amap_instantiate, amap_lookup. intros u e.\n    rewrite SUBST.FACTS.map_o.\n    consider (UVarMap.MAP.find u m); simpl; intros; try congruence.\n    inv_all. eapply H0 in H1. subst; eauto.\n  Qed.\n\n  Lemma WellFormed_bimap_instantiate\n  : forall s f min len maxV s',\n      amap_instantiate f s = s' ->\n      (forall u e,\n         f u = Some e ->\n         mentionsAny (fun u' => u' ?[ ge ] min)\n                     (fun v' => v' ?[ ge ] maxV) e = false) ->\n      WellFormed_bimap min len maxV s ->\n      WellFormed_bimap min len maxV s'.\n  Proof.\n    red; intros; subst.\n    red in H1. forward_reason.\n    split.\n    { red. intros.\n      rewrite SUBST.PROPS.F.find_mapsto_iff in H3.\n      unfold amap_instantiate in *.\n      rewrite SUBST.FACTS.map_o in H3.\n      red. intros.\n      consider (UVarMap.MAP.find k s); simpl in *; try congruence.\n      intros. inv_all; subst.\n      eapply SUBST.PROPS.F.not_find_in_iff.\n      rewrite SUBST.FACTS.map_o.\n      consider (UVarMap.MAP.find u s); try reflexivity.\n      intros. exfalso.\n      eapply mentionsU_instantiate in H4.\n      destruct H4.\n      { destruct H4.\n        eapply H. 2: eassumption.\n        eapply SUBST.PROPS.F.find_mapsto_iff. eassumption.\n        red. eexists.\n        eapply SUBST.PROPS.F.find_mapsto_iff. eassumption. }\n      { forward_reason.\n        specialize (H0 _ _ H4).\n        eapply mentionsAny_false_mentionsU in H0; [ | eassumption ].\n        eapply H1 in H5. consider (u ?[ ge ] min).\n        { congruence. }\n        { intros. omega. } } }\n    split.\n    { revert H1. eapply Forall_amap_instantiate. trivial. }\n    { revert H2. eapply Forall_amap_instantiate; intros.\n      unfold bimap_max in *.\n      eapply mentionsAny_complete_false; [ eauto | ].\n      eapply mentionsAny_complete_false in H2; [ | eauto ].\n      forward_reason; split.\n      { intros.\n        eapply mentionsU_instantiate in H4.\n        destruct H4; forward_reason.\n        { eauto. }\n        { eapply H0 in H4.\n          eapply mentionsAny_false_mentionsU in H4. 2: eassumption.\n          clear - H4.\n          consider (u0 ?[ ge ] (min + len)); auto.\n          intros. rewrite rel_dec_eq_true in H4; eauto with typeclass_instances.\n          omega. } }\n      { intros.\n        eapply mentionsV_instantiate_0 in H4; try eassumption.\n        destruct H4.\n        eauto.\n        forward_reason. eapply H0 in H5.\n        eapply mentionsAny_false_mentionsV in H5. 2: eauto. eauto. } }\n  Qed.\n\n  Definition nothing_in_range a b m : Prop :=\n    forall u, u < b -> amap_lookup (a + u) m = None.\n  Definition only_in_range min len m :=\n    Forall_amap (fun k _ => min <= k < min + len) m.\n\n  Lemma only_in_range_0_empty\n  : forall a am,\n      only_in_range a 0 am ->\n      UVarMap.MAP.Equal am amap_empty.\n  Proof.\n    clear. unfold Forall_amap. red.\n    intros.\n    specialize (H y). unfold amap_lookup in *.\n    rewrite SUBST.FACTS.empty_o.\n    destruct (UVarMap.MAP.find y am); auto.\n    exfalso. specialize (H _ eq_refl). omega.\n  Qed.\n\n  Lemma Forall_amap_Proper\n  : Proper (pointwise_relation _ (pointwise_relation _ iff) ==> UVarMap.MAP.Equal ==> iff)\n           Forall_amap.\n  Proof.\n    do 3 red; intros.\n    split; intros; red; intros;\n    eapply SUBST.FACTS.find_mapsto_iff in H2;\n    eapply SUBST.FACTS.Equal_mapsto_iff in H0; eauto.\n    - eapply H0 in H2.\n      eapply H1 in H2.\n      eapply H; eauto.\n    - eapply H0 in H2.\n      eapply H1 in H2.\n      eapply H; eauto.\n  Qed.\n\n  Lemma only_in_range_0_WellFormed_pre_entry\n  : forall a am mV,\n      only_in_range a 0 am ->\n      WellFormed_bimap a 0 mV am.\n  Proof.\n    clear. unfold WellFormed_bimap.\n    intros. eapply only_in_range_0_empty in H.\n    split.\n    - red. intros.\n      eapply SUBST.FACTS.Equal_mapsto_iff in H.\n      eapply H in H0. clear - H0.\n      eapply SUBST.FACTS.empty_mapsto_iff in H0.\n      destruct H0.\n    - split.\n      + eapply Forall_amap_Proper; eauto.\n        eapply Reflexive_pointwise.\n        eapply Reflexive_pointwise. eauto with typeclass_instances.\n        eapply Forall_amap_empty.\n      + eapply Forall_amap_Proper; eauto.\n        eapply Reflexive_pointwise.\n        eapply Reflexive_pointwise. eauto with typeclass_instances.\n        eapply Forall_amap_empty.\n  Qed.\n\n  (** Start pigeonhole stuff **)\n  Lemma cardinal_remove\n  : forall m x y,\n      amap_lookup x m = Some y ->\n      UVarMap.MAP.cardinal m = S (UVarMap.MAP.cardinal (UVarMap.MAP.remove x m)).\n  Proof.\n    clear. intros.\n    do 2 rewrite SUBST.PROPS.cardinal_fold.\n    assert (UVarMap.MAP.Equal m (UVarMap.MAP.add x y (UVarMap.MAP.remove x m))).\n    { red. intros.\n      rewrite SUBST.PROPS.F.add_o.\n      rewrite SUBST.PROPS.F.remove_o.\n      destruct (SUBST.PROPS.F.eq_dec x y0). subst; auto.\n      auto. }\n    etransitivity.\n    (rewrite SUBST.PROPS.fold_Equal with (eqA := @eq nat); try eassumption); eauto.\n    compute; intros; subst; auto.\n    compute; intros; subst; auto.\n    rewrite <- plus_n_O.\n    rewrite SUBST.PROPS.fold_add. reflexivity.\n    eauto.\n    compute; intros; subst; auto.\n    compute; intros; subst; auto.\n    eapply UVarMap.MAP.remove_1. reflexivity.\n  Qed.\n\n  Lemma cardinal_not_remove\n  : forall m x,\n      amap_lookup x m = None ->\n      UVarMap.MAP.cardinal m = UVarMap.MAP.cardinal (UVarMap.MAP.remove x m).\n  Proof.\n    clear. intros.\n    assert (UVarMap.MAP.Equal m (UVarMap.MAP.remove x m)).\n    { red. intros.\n      rewrite SUBST.PROPS.F.remove_o.\n      destruct (SUBST.PROPS.F.eq_dec x y). subst; auto.\n      auto. }\n    rewrite <- H0. reflexivity.\n  Qed.\n\n  Lemma subst_pull_sound\n  : forall b a m m',\n      subst_pull a b m = Some m' ->\n      nothing_in_range a b m' /\\\n      UVarMap.MAP.cardinal m' = UVarMap.MAP.cardinal m - b /\\\n      (forall u, u < a \\/ u >= a + b -> amap_lookup u m = amap_lookup u m') /\\\n      (forall u, u < b -> amap_lookup (a + u) m <> None).\n  Proof.\n    clear.\n    induction b.\n    { simpl. intros. inv_all; subst.\n      split.\n      { red. intros; exfalso; omega. }\n      split.\n      { omega. }\n      split.\n      { auto. }\n      { intros. exfalso; omega. } }\n    { simpl. unfold SUBST.raw_drop.\n      intros. forwardy.\n      eapply IHb in H. forward_reason.\n      inv_all. subst.\n      split.\n      { red. intros.\n        unfold amap_lookup. rewrite SUBST.PROPS.F.remove_o.\n        destruct (SUBST.PROPS.F.eq_dec a (a + u)); auto.\n        destruct u.\n        { exfalso; omega. }\n        { replace (a + S u) with (S a + u) by omega.\n          red in H. eapply H. omega. } }\n      split.\n      { replace (UVarMap.MAP.cardinal m - S b) with\n        ((UVarMap.MAP.cardinal m - b) - 1) by omega.\n        rewrite <- H2. clear - H0.\n        rewrite (@cardinal_remove _ _ _ H0). omega. }\n      split.\n      { intros.\n        destruct H1.\n        + rewrite H3; [ | left; eauto ].\n          unfold amap_lookup.\n          rewrite SUBST.PROPS.F.remove_neq_o; auto.\n        + rewrite H3; [ | right; omega ].\n          unfold amap_lookup.\n          rewrite SUBST.PROPS.F.remove_neq_o; auto.\n          omega. }\n      { intros.\n        destruct u.\n        { rewrite H3; [ | left; omega ].\n          replace (a + 0) with a. change_rewrite H0. congruence.\n          clear. apply plus_n_O. }\n        { replace (a + S u) with (S a + u) by omega.\n          apply H4. omega. } } }\n  Qed.\n\n  Lemma subst_pull_complete\n  : forall b a m,\n      (forall u, u < b -> amap_lookup (a + u) m <> None) ->\n      exists m',\n        subst_pull a b m = Some m'.\n  Proof.\n    clear. induction b; simpl; intros; eauto.\n    { destruct (IHb (S a) m); clear IHb.\n      { intros. replace (S a + u) with (a + S u) by omega.\n        eapply H. omega. }\n      { rewrite H0.\n        eapply subst_pull_sound in H0.\n        forward_reason. unfold SUBST.raw_drop.\n        rewrite <- H2 by (left; omega).\n        specialize (H 0).\n        replace (a + 0) with a in H by omega.\n        destruct (amap_lookup a m); eauto.\n        exfalso. eapply H; auto. omega. } }\n  Qed.\n\n  Fixpoint test_range from len m :=\n    match len with\n      | 0 => true\n      | S len =>\n        match amap_lookup from m with\n          | None => false\n          | Some _ => test_range (S from) len (UVarMap.MAP.remove from m)\n        end\n    end.\n\n  Lemma test_range_true_all\n  : forall l f m,\n      test_range f l m = true ->\n      forall u, u < l -> amap_lookup (f + u) m <> None.\n  Proof.\n    clear. induction l.\n    { intros; exfalso; omega. }\n    { simpl; intros; forward.\n      specialize (IHl _ _ H1).\n      destruct u.\n      { replace (f + 0) with f by omega. congruence. }\n      { replace (f + S u) with (S f + u) by omega.\n        cutrewrite (amap_lookup (S f + u) m =\n                    amap_lookup (S f + u) (UVarMap.MAP.remove f m)).\n        { apply IHl. omega. }\n        unfold amap_lookup.\n        rewrite SUBST.PROPS.F.remove_neq_o; auto. omega. } }\n  Qed.\n\n  Lemma cardinal_le_range\n  : forall len min m,\n      only_in_range min len m ->\n      UVarMap.MAP.cardinal m <= len.\n  Proof.\n    clear.\n    induction len.\n    { intros.\n      eapply only_in_range_0_empty in H.\n      cut (UVarMap.MAP.cardinal m = 0); try omega.\n      apply SUBST.PROPS.cardinal_1.\n      rewrite H.\n      apply UVarMap.MAP.empty_1. }\n    { intros.\n      assert (only_in_range min len (UVarMap.MAP.remove (min + len) m)).\n      { red. red in H. red. intros.\n        unfold amap_lookup in H0.\n        rewrite SUBST.PROPS.F.remove_o in H0.\n        destruct (SUBST.PROPS.F.eq_dec (min + len) u); try congruence.\n        eapply H in H0. omega. }\n      { eapply IHlen in H0.\n        consider (UVarMap.MAP.find (min + len) m); intros.\n        { erewrite cardinal_remove; eauto.\n          omega. }\n        { erewrite cardinal_not_remove; eauto. } } }\n  Qed.\n\n  Lemma subst_getInstantiation\n  : forall tus tvs ts m maxV P,\n      WellFormed_bimap (length tus) (length ts) maxV m ->\n      amap_substD (tus ++ ts) tvs m = Some P ->\n      amap_is_full (length ts) m = true ->\n      exists x : hlist (fun t => exprT tus tvs (typD t)) ts,\n        forall us vs,\n          let us' :=\n              hlist_map (fun t (x : exprT tus tvs (typD t)) => x us vs) x\n          in\n          P (HList.hlist_app us us') vs.\n  Proof.\n    intros.\n    assert (exists m',\n              subst_pull (length tus) (length ts) m = Some m' /\\\n              UVarMap.MAP.Empty m').\n    { unfold amap_is_full in H1.\n      consider (UVarMap.MAP.cardinal m ?[ eq ] length ts); intros.\n      assert (only_in_range (length tus) (length ts) m).\n      { clear - H. red in H. red; intros.\n        tauto. }\n      clear - H1 H2.\n      destruct (@subst_pull_complete (length ts) (length tus) m).\n      { eapply test_range_true_all.\n        generalize dependent (length tus).\n        generalize dependent m.\n        induction (length ts); intros.\n        { reflexivity. }\n        { simpl.\n          consider (amap_lookup n0 m).\n          { intros.\n            eapply IHn.\n            - erewrite cardinal_remove in H1; eauto.\n            - red. intros. red. intros.\n              unfold amap_lookup in H0.\n              rewrite SUBST.PROPS.F.remove_o in H0.\n              destruct (SUBST.PROPS.F.eq_dec n0 u); try congruence.\n              eapply H2 in H0. omega. }\n          { intros. exfalso.\n            assert (only_in_range (S n0) n m).\n            { red. red; intros. red in H2.\n              consider (n0 ?[ eq ] u); intros; subst; try congruence.\n              eapply H2 in H0. omega. }\n            eapply cardinal_le_range in H0. omega. } }  }\n      rewrite H. eexists; split; eauto.\n      eapply subst_pull_sound in H.\n      assert (only_in_range (length tus) 0 x).\n      { forward_reason.\n        red. red. intros.\n        exfalso.\n        assert ((u < length tus \\/ u >= length tus + length ts) \\/\n                (exists u', u' < length ts /\\ u = length tus + u')).\n        { consider (u ?[ lt ] length tus); try auto; intros.\n          consider (u ?[ ge ] (length tus + length ts)); try auto; intros.\n          right. exists (u - length tus). split; try omega. }\n        destruct H6.\n        { rewrite <- H3 in H5; eauto.\n          eapply H2 in H5. omega. }\n        { forward_reason. subst.\n          red in H.\n          rewrite H in H5. congruence. auto. } }\n      { eapply  only_in_range_0_empty in H0.\n        rewrite H0.\n        eapply UVarMap.MAP.empty_1. } }\n    { forward_reason.\n      eapply pull_sound in H2; eauto using SUBST.SubstOpenOk_subst.\n      { forward_reason.\n        specialize (@H4 tus ts tvs _ eq_refl eq_refl H0).\n        forward_reason.\n        exists x2. simpl. intros.\n        eapply H9.\n        assert (UVarMap.MAP.Equal x (UVarMap.MAP.empty expr)).\n        { red. red in H3. intros.\n          rewrite SUBST.FACTS.empty_o.\n          eapply SUBST.FACTS.not_find_in_iff.\n          red. intro. destruct H10. eapply H3.\n          eauto. }\n        generalize (@SUBST.raw_substD_Equal typ _ _ _ tus tvs x (UVarMap.MAP.empty _) _ H7 H10).\n        destruct (SUBST.substD_empty tus tvs).\n        intros.\n        forward_reason.\n        eapply H13; clear H13.\n        change_rewrite H12 in H11. inv_all; subst. eauto. }\n      { eapply WellFormed_bimap_WellFormed_amap; eauto. } }\n  Qed.\n\n  Lemma only_in_range_empty : forall a b,\n      only_in_range a b amap_empty.\n  Proof.\n    clear. red. intros.\n    eapply Forall_amap_empty.\n  Qed.\n\n  Lemma WellFormed_amap_amap_empty : WellFormed_amap amap_empty.\n  Proof. red. eapply FMapSubst.SUBST.WellFormed_empty. Qed.\n\n  Lemma list_substD_app\n  : forall tus tvs l2 l1 from sD,\n      FMapSubst.SUBST.list_substD tus tvs from (l1 ++ l2) = Some sD ->\n      exists s1D s2D,\n        FMapSubst.SUBST.list_substD tus tvs from l1 = Some s1D /\\\n        FMapSubst.SUBST.list_substD tus tvs (from + length l1) l2 = Some s2D /\\\n        forall us vs,\n          sD us vs <-> (s1D us vs /\\ s2D us vs).\n  Proof.\n    induction l1; simpl; intros.\n    { rewrite <- plus_n_O.\n      do 2 eexists; split; eauto. split; eauto.\n      intuition. }\n    { destruct a; forward; inv_all.\n      { eapply IHl1 in H2; forward_reason.\n        Cases.rewrite_all_goal.\n        do 2 eexists; split; eauto.\n        simpl. split.\n        rewrite <- Plus.plus_Snm_nSm. eassumption.\n        subst; intros. rewrite H5. intuition. }\n      { eapply IHl1 in H; forward_reason.\n        rewrite <- Plus.plus_Snm_nSm.\n        eauto. } }\n  Qed.\n\n  Lemma amap_substD_list_substD\n  : forall tus tvs am (from len : nat) sD maxV,\n      WellFormed_bimap from len maxV am ->\n      amap_substD tus tvs am = Some sD ->\n      exists sD',\n        FMapSubst.SUBST.list_substD tus tvs from (amap_aslist am from len) = Some sD' /\\\n        forall us vs,\n          sD us vs <-> sD' us vs.\n  Proof.\n    destruct 1.\n    intros; eapply FMapSubst.SUBST.amap_substD_list_substD; eauto.\n    destruct H0. eauto.\n  Qed.\n\n  Lemma amap_aslist_app\n    : forall a y x z,\n      amap_aslist a x (y + z) =\n      amap_aslist a x y ++ amap_aslist a (x + y) z.\n  Proof.\n    induction y; simpl.\n    { intros. f_equal. omega. }\n    { intros. f_equal. rewrite IHy. f_equal. f_equal. omega. }\n  Qed.\n\n  Lemma amap_aslist_nth_error\n    : forall ln st (mp : amap) n,\n      nth_error (amap_aslist mp st ln) n =\n      if n ?[ lt ] ln then Some (amap_lookup (st + n) mp) else None.\n  Proof.\n    clear.\n    induction ln; simpl; intros; destruct n; auto.\n    - simpl. unfold value. f_equal. f_equal. omega.\n    - simpl nth_error. rewrite IHln.\n      consider (n ?[ lt ] ln);\n        consider (S n ?[ lt ] S ln);\n        auto; try solve [ intros; exfalso; omega ].\n      intros.\n      f_equal. f_equal. omega.\n  Qed.\n\n  Lemma pigeon_principle'\n  : forall n (m : amap) low,\n      UVarMap.MAP.cardinal m > n ->\n      Forall_amap (fun k _ => low <= k < low + n) m ->\n      False.\n  Proof using.\n    induction n.\n    { simpl. intros.\n      assert (exists x, UVarMap.MAP.cardinal m = S x).\n      { destruct (UVarMap.MAP.cardinal m); eauto.\n        exfalso; omega. }\n      destruct H1.\n      eapply FMapSubst.SUBST.PROPS.cardinal_inv_2 in H1.\n      destruct H1.\n      eapply FMapSubst.SUBST.FACTS.find_mapsto_iff in m0.\n      eapply H0 in m0.\n      omega. }\n    { intros.\n      consider (UVarMap.MAP.find low m).\n      { intros.\n        specialize (IHn (UVarMap.MAP.remove low m) (S low)).\n        apply IHn; clear IHn.\n        { erewrite cardinal_remove in H; [ | eassumption ].\n          eapply gt_S_n in H. assumption. }\n        { red. red in H0.\n          intros.\n          unfold amap_lookup in *.\n          rewrite FMapSubst.SUBST.PROPS.F.remove_o in H2.\n          destruct (UVarMap.MAP.E.eq_dec low u); try congruence.\n          eapply H0 in H2. omega. } }\n      { intros.\n        eapply IHn with (m:=m) (low :=S low).\n        { omega. }\n        { clear - H0 H1.\n          unfold Forall_amap in *.\n          intros.\n          assert (u <> low).\n          { unfold amap_lookup in H.\n            intro. subst.\n            rewrite H1 in H. congruence. }\n          { eapply H0 in H.\n            omega. } } } }\n  Qed.\n\n  Lemma pigeon_principle\n  : forall (m : amap) n low,\n      amap_is_full n m = true ->\n      Forall_amap (fun k _ => low <= k < low + n) m ->\n      forall k, k < n ->\n                amap_lookup (low + k) m <> None.\n  Proof using.\n    unfold amap_is_full.\n    intros m n low H.\n    rewrite rel_dec_correct in H.\n    red; intros. revert H2. revert H0. revert H.\n    revert low. revert m. generalize dependent n. induction k.\n    { intros.\n      destruct n; try omega.\n      eapply pigeon_principle' with (m:=m) (n:=n) (low:=S low).\n      { omega. }\n      { red. intros.\n        assert (low <> u).\n        { intro. subst. replace (u + 0) with u in H2 by omega. congruence. }\n        eapply H0 in H3. omega. } }\n    { intros.\n      destruct n; try omega.\n      eapply lt_S_n in H1.\n      consider (amap_lookup low m).\n      { intros.\n        unfold amap_lookup in *.\n        eapply (IHk _ H1 (UVarMap.MAP.remove low m) (S low)).\n        { erewrite cardinal_remove in H by eassumption.\n          omega. }\n        { clear - H0.\n          unfold Forall_amap in *. intros.\n          unfold amap_lookup in H.\n          rewrite FMapSubst.SUBST.FACTS.remove_o in H.\n          destruct (UVarMap.MAP.E.eq_dec low u); try congruence.\n          eapply H0 in H. omega. }\n        { rewrite FMapSubst.SUBST.FACTS.remove_o.\n          destruct (UVarMap.MAP.E.eq_dec low (S low + k)); auto.\n          rewrite <- H2. f_equal. omega. } }\n      { intros.\n        apply (@pigeon_principle' n m (S low)).\n        { omega. }\n        { unfold Forall_amap in *; intros.\n          assert (u <> low) by congruence.\n          eapply H0 in H4.\n          omega. } } }\n  Qed.\n\nEnd parameterized.\n", "meta": {"author": "gmalecha", "repo": "mirror-core", "sha": "b962fbca15b0b5a4653f66d29d7115bb04ebd4f3", "save_path": "github-repos/coq/gmalecha-mirror-core", "path": "github-repos/coq/gmalecha-mirror-core/mirror-core-b962fbca15b0b5a4653f66d29d7115bb04ebd4f3/theories/RTac/BIMap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23741461558021823}}
{"text": "Require Import CSet Util Filter Take MoreList OUnion AllInRel MapDefined MapUpdate Position.\nRequire Import IL Annotation LabelsDefined.\nRequire Import Liveness.Liveness TrueLiveness SimI.\nRequire Import RenamedApart.\nRequire Import SpillSound ReconstrLive DoSpill.\nRequire Import SlotLiftArgs SlotLiftParams.\nRequire Export SpillMovesAgree.\n\n\nSet Implicit Arguments.\nUnset Printing Records.\n\nFixpoint extend_list X (L:list X) (Z:params) (RM : ⦃var⦄ * ⦃var⦄)\n  : list X\n  :=\n    match L, Z with\n    | l::L, z::Z => if [z ∈ fst RM ∩ snd RM]\n             then l::l::extend_list L Z RM\n             else l::extend_list L Z RM\n    | _, _ => nil\n    end.\n\n(** * SpillSim *)\n\nLemma extend_list_length X (L:list X) (RM : ⦃var⦄ * ⦃var⦄) (Z : params)\n      (NoDup:NoDupA eq Z) (Len:❬L❭ = ❬Z❭)\n  : ❬extend_list L Z RM❭ = ❬Z❭ + cardinal (of_list Z ∩ (fst RM ∩ snd RM)).\nProof.\n  general induction Len; simpl; eauto.\n  inv NoDup.\n  repeat cases; simpl; rewrite IHLen; eauto.\n  - rewrite cap_special_in; eauto.\n    rewrite add_cardinal_2; eauto. cset_tac.\n  - rewrite cap_special_notin; eauto.\nQed.\n\n\nLemma slot_lift_params_extend_list_length X slot RM Z (L:list X)\n      (Len:❬Z❭ = ❬L❭)\n  : ❬slot_lift_params slot RM Z❭ = ❬extend_list L Z RM❭.\nProof.\n  general induction Len; simpl; eauto.\n  repeat cases; eauto; simpl; eauto.\nQed.\n\nLemma omap_slotlift (slot : var -> var) (V V'':onv val) Yv (xl Z:params) (Len:❬xl❭=❬Z❭) RM RMapp\n      (Agr4 : agree_on eq (fst RMapp) V V'')\n      (Agr5 : agree_on eq (snd RMapp) V (fun x : var => V'' (slot x)))\n      (FVincl: of_list xl [<=] fst RMapp ∪ snd RMapp)\n  : omap (op_eval V) (Var ⊝ xl) = Some Yv\n    -> omap (op_eval V'') (slot_lift_args slot RM RMapp (Var ⊝ xl) Z)\n      = Some (extend_list Yv Z RM).\nProof.\n  intros.\n  general induction Len; simpl in *; eauto;\n    monad_inv H; simpl in *. unfold choose_y.\n  cases; simpl.\n  - assert (y ∈ fst RM /\\ y ∈ snd RM) by (revert COND; clear_all; cset_tac).\n    destruct H. repeat (cases; simpl).\n    + rewrite <- Agr4; eauto. rewrite EQ. simpl.\n      erewrite IHLen; eauto; [ | rewrite <- FVincl; eauto with cset ]; eauto.\n    + rewrite <- Agr5; eauto.\n      * rewrite EQ; eauto; simpl.\n        erewrite IHLen; eauto; [ | rewrite <- FVincl; eauto with cset ]; eauto.\n      * revert FVincl NOTCOND. clear_all. cset_tac.\n  - assert ((y ∈ fst RM -> y ∈ snd RM -> False))\n      by (revert NOTCOND; clear_all; cset_tac).\n    unfold choose_y; repeat cases; simpl; eauto.\n    + rewrite <- Agr4; [ rewrite EQ | ]; simpl; eauto.\n      erewrite IHLen; eauto; [ | rewrite <- FVincl; eauto with cset ]; eauto.\n    + rewrite <- Agr5; [ rewrite EQ | eauto]; simpl.\n      erewrite IHLen; eauto; [ | rewrite <- FVincl; eauto with cset ]; eauto.\n      cset_tac.\n    + rewrite <- Agr4; [ rewrite EQ | ]; simpl; eauto.\n      erewrite IHLen; eauto; [ | rewrite <- FVincl; eauto with cset ]; eauto.\n    + rewrite <- Agr5; [ rewrite EQ | eauto]; simpl.\n      erewrite IHLen; eauto; [ | rewrite <- FVincl; eauto with cset ]; eauto.\n      cset_tac.\n    + rewrite <- Agr5; [ rewrite EQ | eauto]; simpl.\n      erewrite IHLen; eauto; [ | rewrite <- FVincl; eauto with cset ]; eauto.\n    + rewrite <- Agr4; [ rewrite EQ | ]; simpl; eauto.\n      erewrite IHLen; eauto; [ | rewrite <- FVincl; eauto with cset ]; eauto.\n      cset_tac.\nQed.\n\n\n\n\nLemma update_with_list_lookup_in_list_first_slot (slot:var->var)\n      A (E:onv A) n (R M:set var)\n      Z (Y:list A) z\n: length Z = length Y\n  -> get Z n z\n  -> z ∈ R\n  -> disj (of_list Z) (map slot (of_list Z))\n  -> (forall n' z', n' < n -> get Z n' z' -> z' =/= z)\n  -> exists y, get Y n y\n         /\\ E [slot_lift_params slot (R, M) Z <--\n                               Some ⊝ extend_list Y Z (R, M)] z = Some y.\nProof.\n  intros Len Get In Disj First. length_equify.\n  general induction Len; simpl in *; isabsurd.\n  inv Get.\n  - exists y; repeat split; eauto using get.\n    cases; simpl.\n    + lud; eauto using get.\n    + cases; simpl.\n      * lud; eauto using get.\n  - edestruct (IHLen slot E n0) as [? [? ]]; eauto using get; dcr.\n    + eapply disj_incl; eauto with cset.\n    + intros. eapply (First (S n')); eauto using get. omega.\n    + exists x0. eexists; repeat split; eauto using get.\n      exploit (First 0); eauto using get; try omega.\n      cases; simpl.\n      * rewrite lookup_nequiv; eauto.\n        rewrite lookup_nequiv; eauto.\n        intro.\n        eapply (Disj z). eapply get_in_of_list in H3.\n        cset_tac. rewrite <- H2.\n        eapply map_iff; eauto. eexists x; split; eauto with cset.\n      * cases; simpl; lud.\n        -- eauto.\n        -- exfalso.\n           eapply (Disj (slot x)).\n           ++ eapply get_in_of_list in H3. rewrite <- H5. cset_tac.\n           ++ eapply map_iff; eauto. eexists x; split; eauto with cset.\n        -- eauto.\nQed.\n\n\nLemma slot_lift_params_agree (slot : var -> var) X (E:onv X) E' R M Z VL (Len:❬Z❭=❬VL❭)\n      (Agr2:agree_on eq (R \\ of_list Z) E E')\n      (Disj:disj (R ∪ of_list Z) (map slot (R ∪ of_list Z)))\n      (Incl:of_list Z [<=] R ∪ M)\n  : agree_on eq R (E [Z <-- Some ⊝ VL])\n             (E' [slot_lift_params slot (R, M) Z <-- Some ⊝ extend_list VL Z (R, M)]).\nProof.\n  hnf; intros.\n  decide (x ∈ of_list Z).\n  - assert (❬Z❭=❬Some ⊝ VL❭) by eauto with len.\n    edestruct (of_list_get_first _ i) as [n]; eauto; dcr.\n    edestruct update_with_list_lookup_in_list_first; eauto; dcr.\n    + intros; rewrite H2. eauto.\n    + rewrite <- H2. rewrite H6. inv_get.\n      edestruct update_with_list_lookup_in_list_first_slot;\n        try eapply Len; try eapply H3; try eapply H; dcr.\n      * eapply disj_incl; eauto with cset.\n      * intros; eauto.\n      * erewrite H7. inv_get. eauto.\n  - rewrite !lookup_set_update_not_in_Z; eauto.\n    + eapply Agr2. cset_tac.\n    + rewrite of_list_slot_lift_params; eauto.\n      clear - n Disj H; cset_tac.\nQed.\n\nLemma update_with_list_lookup_in_list_first_slot' (slot : var -> var) A (E:onv A) n (R M:set var)\n      Z (Y:list A) z\n: length Z = length Y\n  -> get Z n z\n  -> z ∈ M\n  -> disj (of_list Z ∪ R ∪ M) (map slot (of_list Z ∪ R ∪ M))\n  -> injective_on (of_list Z ∪ R ∪ M) slot\n  -> (forall n' z', n' < n -> get Z n' z' -> z' =/= z)\n  -> exists y, get Y n y /\\ E [slot_lift_params slot (R, M) Z <--\n                  Some ⊝ extend_list Y Z (R, M)] (slot z) = Some y.\nProof.\n  intros Len Get In Disj Inj First. length_equify.\n  general induction Len; simpl in *; isabsurd.\n  inv Get.\n  - exists y; repeat split; eauto using get.\n    cases; simpl.\n    + lud; eauto using get.\n    + cases; simpl.\n      * exfalso. cset_tac.\n      * lud; eauto using get.\n  - edestruct (IHLen slot E n0 R M) as [? [? ]]; eauto using get; dcr.\n    + eapply disj_incl; eauto.\n      clear; cset_tac.\n      clear; cset_tac'; eauto 20.\n    + eapply injective_on_incl; eauto.\n      clear; cset_tac.\n    + intros. eapply (First (S n')); eauto using get. omega.\n    + exists x0. eexists; repeat split; eauto using get.\n      exploit (First 0); eauto using get; try omega.\n      cases; simpl.\n      * rewrite lookup_nequiv; eauto.\n        rewrite lookup_nequiv; eauto.\n        -- intro. eapply Inj in H2; eauto with cset.\n        -- intro. hnf in H2; subst.\n           eapply (Disj (slot z)); eauto with cset.\n      * cases; simpl; lud; eauto.\n        -- exfalso. hnf in e; subst.\n           eapply (Disj (slot z)); eauto with cset.\n        -- exfalso. eapply H2. eapply Inj; eauto with cset.\nQed.\n\n\n\nLemma slot_lift_params_agree_slot (slot : var -> var) X (E:onv X) E' R M Z VL (Len:❬Z❭=❬VL❭)\n      (Agr2:agree_on eq (M \\ of_list Z) E (fun x => E' (slot x)))\n      (Disj:disj (of_list Z ∪ R ∪ M) (map slot (of_list Z ∪ R ∪ M)))\n      (Inj:injective_on (of_list Z ∪ R ∪ M) slot)\n      (Incl:of_list Z [<=] R ∪ M)\n        : agree_on eq M (E [Z <-- Some ⊝ VL])\n             (fun x => E' [slot_lift_params slot (R, M) Z <--\n                        Some ⊝ extend_list VL Z (R, M)] (slot x)).\nProof.\n  hnf; intros.\n  decide (x ∈ of_list Z).\n  - assert (❬Z❭=❬Some ⊝ VL❭) by eauto with len.\n    edestruct (of_list_get_first _ i) as [n]; eauto; dcr. hnf in H2; subst.\n    edestruct update_with_list_lookup_in_list_first; eauto; dcr.\n    rewrite H4. inv_get.\n    edestruct (@update_with_list_lookup_in_list_first_slot' slot); try eapply Len; try eapply H5;\n      try eapply Disj;\n      eauto; dcr.\n    rewrite H6. get_functional. eauto.\n  - rewrite !lookup_set_update_not_in_Z; eauto.\n    + eapply Agr2. cset_tac.\n    + rewrite of_list_slot_lift_params; eauto.\n      intro. eapply union_iff in H0; destruct H0.\n      * eapply (Disj (slot x)). cset_tac. cset_tac.\n      * eapply (Disj x). cset_tac.\n        eapply map_iff in H0; eauto. dcr.\n        eapply Inj in H3; eauto with cset.\n        exfalso; cset_tac.\n        cset_tac.\nQed.\n\n\nInstance SR (slot : var -> var) (VD:set var)\n  : PointwiseProofRelationI (((set var) * (set var)) * params) := {\n   ParamRelIP RMZ Z Z' := Z' = slot_lift_params slot (fst RMZ) Z /\\ Z = snd RMZ;\n   ArgRelIP V V' RMZ VL VL' :=\n     VL' = extend_list VL (snd RMZ) (fst RMZ) /\\\n     agree_on eq (fst (fst RMZ) \\ of_list (snd RMZ)) V V' /\\\n     agree_on eq (snd (fst RMZ) \\ of_list (snd RMZ)) V (fun x => V' (slot x)) /\\\n     ❬VL❭ = ❬snd RMZ❭ /\\\n     defined_on (fst (fst RMZ) \\ of_list (snd RMZ)\n                     ∪ map slot (snd (fst RMZ) \\ of_list (snd RMZ))) V'\n}.\n\nRequire Import AppExpFree Subset1.\n\nLemma sim_I (slot : var -> var) k Λ ZL LV VD r L L' V V' R M s lv sl ra\n  : agree_on eq R V V'\n    -> agree_on eq M V (fun x => V' (slot x))\n    -> live_sound Imperative ZL LV s lv\n    -> spill_sound k ZL Λ (R,M) s sl\n    -> spill_live VD sl lv\n    -> injective_on VD slot\n    -> disj VD (map slot VD)\n    -> defined_on (R ∪ map slot M) V'\n    -> R ∪ M ⊆ fst (getAnn ra)\n    -> labenv_sim SimExt (sim r) (SR slot VD) (zip pair Λ ZL) L L'\n    -> (fst (getAnn ra) ∪ snd (getAnn ra)) ⊆ VD\n    -> renamedApart s ra\n    -> app_expfree s\n    -> ann_R Subset1 lv ra\n    -> sim r SimExt (L, V, s) (L', V', do_spill slot s sl ZL Λ).\nProof.\n  simpl. unfold sim.\n  move VD before k. move s before VD. revert_until s.\n  sind s.\n  intros ? ? ? ? ? ? ? ? ? ? ? ? ?\n         Agr1 Agr2 LS SLS SL Inj Disj Def Incl' LSim RAincl RA AEF Sub1.\n  assert (Incl:R ∪ M [<=] VD). {\n    rewrite <- RAincl, <- Incl'. eauto with cset.\n  }\n  exploit L_sub_SpM as LSpM; eauto.\n  exploit Sp_sub_R as SpR; eauto.\n  assert (VDincl:getSp sl ∪ getL sl [<=] VD). {\n    rewrite LSpM, SpR.\n    rewrite <- Incl.\n    clear; cset_tac.\n  }\n  eapply sim_I_moves; eauto.\n  eapply injective_on_incl; eauto with cset.\n  eapply disj_incl; eauto with cset.\n  eapply defined_on_incl; eauto.\n  rewrite SpR at 1. rewrite LSpM.\n  rewrite map_union; eauto. clear; cset_tac.\n  rewrite !lookup_list_map. intros ? Agr3.\n  time (destruct s; invt spill_sound; invt spill_live; invt live_sound;\n        invt renamedApart; invt app_expfree; try invtc (@ann_R _ _ Subset1);\n    (exploit regs_agree_after_spill_load as Agr4); try eassumption;\n      exploit mem_agrees_after_spill_load as Agr5; try eassumption;\n        simpl in *; rewrite !elements_empty; simpl).\n  - destruct e; simpl in *.\n    + eapply (sim_let_op il_statetype_I); eauto.\n      * symmetry; eapply op_eval_agree; eauto using agree_on_incl.\n      * intros. left.\n        eapply (IH s); try eassumption.\n        -- eauto.\n        -- eapply agree_on_update_same; eauto.\n           eapply agree_on_incl; eauto.\n           clear; cset_tac.\n        -- eapply mem_agrees_after_spill_load_update; eauto.\n           rewrite SpR, Incl'; eauto.\n           rewrite H18 in RAincl.\n           revert RAincl; clear; cset_tac.\n        -- eapply defined_on_update_some.\n           eapply defined_on_incl.\n           eapply defined_on_after_spill_load; eauto.\n           instantiate (1:=K). clear; cset_tac.\n        -- pe_rewrite.\n           rewrite LSpM, SpR, <- Incl'. clear; cset_tac.\n        -- pe_rewrite. rewrite <- RAincl.\n           rewrite H18. clear; cset_tac.\n    + eapply (sim_let_call il_statetype_I).\n      * symmetry; eapply omap_op_eval_agree; eauto using agree_on_incl.\n      * intros. left. eapply (IH s); try eassumption.\n        -- eauto.\n        -- eapply agree_on_update_same; eauto.\n           eapply agree_on_incl; eauto.\n           clear; cset_tac.\n        -- eapply mem_agrees_after_spill_load_update; eauto.\n           rewrite SpR, Incl'; eauto.\n           rewrite H18 in RAincl.\n           revert RAincl; clear; cset_tac.\n        -- eapply defined_on_update_some.\n           eapply defined_on_incl.\n           eapply defined_on_after_spill_load; eauto.\n           instantiate (1:=K). clear; cset_tac.\n        -- pe_rewrite. rewrite LSpM, SpR, <- Incl'.\n           clear; cset_tac.\n        -- pe_rewrite. rewrite <- RAincl.\n           rewrite H18. clear; cset_tac.\n  - simpl in *.\n    eapply (sim_cond il_statetype_I).\n    + symmetry; eapply op_eval_agree; eauto using agree_on_incl.\n    + intros; left. eapply IH; try eassumption.\n      * eauto.\n      * eapply defined_on_after_spill_load; eauto.\n      * pe_rewrite. rewrite LSpM, SpR, <- Incl'. clear; cset_tac.\n      * pe_rewrite. rewrite <- RAincl, <- H9. clear; cset_tac.\n    + intros; left. eapply IH; try eassumption.\n      * eauto.\n      * eapply defined_on_after_spill_load; eauto.\n      * pe_rewrite. rewrite LSpM, SpR, <- Incl'. clear; cset_tac.\n      * pe_rewrite. rewrite <- RAincl, <- H9. clear; cset_tac.\n  - eapply labenv_sim_app; eauto using zip_get.\n    intros; simpl in *. dcr; subst; repeat get_functional.\n    split; eauto; intros.\n    erewrite !get_nth; eauto using zip_get.\n    edestruct op_eval_var; eauto; subst.\n    erewrite omap_slotlift; only 6: eauto.\n    eexists; split; eauto. split; eauto.\n    eapply slot_lift_params_extend_list_length; eauto.\n    split; eauto.\n    split; eauto using agree_on_incl.\n    split; eauto using agree_on_incl.\n    split; eauto.\n    eapply defined_on_incl.\n    eapply defined_on_after_spill_load; eauto. instantiate (1:=K).\n    rewrite H8, H11. reflexivity.\n    len_simpl. rewrite <- H17. eauto with len.\n    simpl. eapply agree_on_incl; eauto.\n    simpl. eapply agree_on_incl; eauto. simpl.\n    rewrite <- H12. eapply of_list_freeVars_vars.\n  - pno_step. simpl.\n    erewrite op_eval_agree; [reflexivity| |reflexivity]. symmetry.\n    eapply agree_on_incl; eauto using regs_agree_after_spill_load; eauto.\n  - eapply sim_fun_ptw; try eapply LSim; try eassumption.\n    + intros. left.\n      eapply (IH s); eauto.\n      * eapply defined_on_after_spill_load; eauto.\n      * pe_rewrite. rewrite LSpM, SpR, <- Incl'. clear; cset_tac.\n      * pe_rewrite. rewrite <- RAincl, <- H25. clear; cset_tac.\n    + intros. hnf; intros; simpl in *; dcr. subst.\n      inv_get.\n      exploit H12 as SPS'; try eassumption.\n      exploit H20 as LS'; try eassumption.\n      exploit H15 as SL'; try eassumption. destruct x as (R_f,M_f).\n      exploit H14 as In'; try eassumption; simpl in *; destruct In' as [In1 In2].\n      exploit H2 as RA'; try eassumption.\n      exploit (get_PIR2 H7) as EQ; only 1-2: eauto.\n      exploit H21 as In3; try eassumption.\n      destruct In3 as [In3 _].\n      unfold merge in EQ. simpl in *.\n      eapply IH; eauto.\n      * eapply slot_lift_params_agree; only 1-2: eauto.\n        -- eapply disj_incl; eauto.\n           ++ rewrite In3, <- EQ, In1, In2.\n             clear; eauto with cset.\n           ++ rewrite In3, <- EQ, In1, In2.\n             clear; eauto with cset.\n        -- rewrite EQ; eauto.\n      * eapply slot_lift_params_agree_slot; only 1-2: eauto.\n        -- eapply disj_incl; eauto.\n           rewrite In3, <- EQ, In1, In2. clear; cset_tac.\n           eapply map_incl; eauto.\n           rewrite In3, <- EQ, In1, In2. clear; cset_tac.\n        -- eapply injective_on_incl; eauto.\n           rewrite In3, <- EQ, In1, In2. clear; cset_tac.\n        -- rewrite EQ; eauto.\n      * eapply defined_on_update_list'.\n        -- len_simpl.\n           edestruct H8; eauto; dcr. simpl in *.\n           eapply slot_lift_params_extend_list_length; eauto.\n        -- rewrite of_list_slot_lift_params; eauto.\n           eapply defined_on_incl; eauto.\n           rewrite <- EQ in In3; revert In3; clear.\n           ++ cset_tac'.\n             ** eexists x. cset_tac.\n             ** eexists x; eauto.\n           ++ rewrite EQ; eauto.\n        -- eapply get_defined; intros; inv_get; eauto.\n      * edestruct H8; eauto; dcr.\n        simpl in *. rewrite EQ.\n        exploit H33; eauto. eapply ann_R_get in H4. eauto.\n      * edestruct H8; eauto; dcr.\n        rewrite H3. simpl. rewrite union_comm. rewrite <- union_assoc.\n        eapply union_incl_split.\n        -- rewrite <- RAincl. eapply incl_union_right.\n           rewrite <- H25. eapply incl_union_left.\n           eapply incl_list_union; eauto using zip_get.\n           unfold defVars. simpl. clear; eauto with cset.\n        -- rewrite <- RAincl. eauto with cset.\n      * exploit H24; eauto.\n    + hnf; intros; simpl in *; subst.\n      inv_get; simpl; eauto.\n    + eauto with len.\n    + eauto with len.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Spilling/SpillSim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.23729367625286418}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\n\nSet Implicit Arguments.\n\n\nLemma write_step_promise\n      lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n      (STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n      (PROMISES: (Local.promises lc1) = Memory.bot):\n  (Local.promises lc2) = Memory.bot.\nProof.\n  inv STEP. rewrite PROMISES in *. s.\n  apply Memory.ext. i. rewrite Memory.bot_get.\n  inv WRITE.\n  erewrite Memory.remove_o; eauto. condtac; ss. guardH o.\n  inv PROMISE; ss.\n  - erewrite Memory.add_o; eauto. condtac; ss.\n    apply Memory.bot_get.\n  - erewrite Memory.split_o; eauto. repeat condtac; ss.\n    + guardH o0. des. subst.\n      exploit Memory.split_get0; try exact PROMISES0; eauto. i. des.\n      rewrite Memory.bot_get in *. congr.\n    + apply Memory.bot_get.\n  - erewrite Memory.lower_o; eauto. condtac; ss.\n    apply Memory.bot_get.\nQed.\n\nLemma program_step_promise\n      lang e\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      (STEP: Thread.program_step e (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2))\n      (PROMISES: (Local.promises lc1) = Memory.bot):\n  (Local.promises lc2) = Memory.bot.\nProof.\n  inv STEP. inv LOCAL; ss; try by inv LOCAL0.\n  - eapply write_step_promise; eauto.\n  - eapply write_step_promise; eauto.\n    inv LOCAL1. auto.\nQed.\n\nLemma closed_timemap_max_ts\n      loc tm mem\n      (CLOSED: Memory.closed_timemap tm mem):\n  Time.le (tm loc) (Memory.max_ts loc mem).\nProof.\n  specialize (CLOSED loc). des.\n  eapply Memory.max_ts_spec. eauto.\nQed.\n\nLemma closed_timemap_max_concrete_ts\n      loc tm mem mts\n      (CLOSED: Memory.closed_timemap tm mem)\n      (MAX: Memory.max_concrete_ts mem loc mts):\n  Time.le (tm loc) mts.\nProof.\n  specialize (CLOSED loc). des.\n  eapply Memory.max_concrete_ts_spec; eauto.\nQed.\n\n\nLemma progress_promise_step\n      lc1 sc1 mem1\n      loc to val releasedm ord\n      (LT: Time.lt (Memory.max_ts loc mem1) to)\n      (WF1: Local.wf lc1 mem1)\n      (MEM1: Memory.closed mem1)\n      (SC1: Memory.closed_timemap sc1 mem1)\n      (WF_REL: View.opt_wf releasedm)\n      (CLOSED_REL: Memory.closed_opt_view releasedm mem1):\n  exists promises2 mem2,\n    Local.promise_step lc1 mem1 loc (Memory.max_ts loc mem1) to\n                       (Message.concrete val (TView.write_released (Local.tview lc1) sc1 loc to releasedm ord))\n                       (Local.mk (Local.tview lc1) promises2) mem2 Memory.op_kind_add.\nProof.\n  exploit (@Memory.add_exists_max_ts\n             mem1 loc to\n             (Message.concrete val (TView.write_released (Local.tview lc1) sc1 loc to releasedm ord))); eauto.\n  { econs. eapply TViewFacts.write_future0; eauto. apply WF1. }\n  i. des.\n  exploit Memory.add_exists_le; try apply WF1; eauto. i. des.\n  hexploit Memory.add_inhabited; try apply x0; [viewtac|]. i. des.\n  esplits. econs; eauto.\n  - econs; eauto; try congr.\n    + econs. unfold TView.write_released.\n      viewtac; repeat (condtac; viewtac);\n        (try by apply Time.bot_spec);\n        (try by unfold TimeMap.singleton, LocFun.add; condtac; [refl|congr]);\n        (try by left; eapply TimeFacts.le_lt_lt; [|eauto];\n         eapply closed_timemap_max_ts; apply WF1).\n      left. eapply TimeFacts.le_lt_lt; [|eauto].\n      eapply closed_timemap_max_ts. apply Memory.unwrap_closed_opt_view; viewtac.\n    + i. inv x0. inv ADD. clear DISJOINT MSG_WF CELL2.\n      exploit Memory.get_ts; try exact GET. i. des.\n      { subst. inv TO. }\n      exploit Memory.max_ts_spec; try exact GET. i. des.\n      eapply Time.lt_strorder. etrans; try exact TO.\n      eapply TimeFacts.lt_le_lt; eauto.\n  - econs. unfold TView.write_released. condtac; econs.\n    viewtac;\n      repeat condtac; viewtac;\n        (try eapply Memory.add_closed_view; eauto);\n        (try apply WF1).\n    + viewtac.\n    + erewrite Memory.add_o; eauto. condtac; eauto. ss. des; congr.\n    + erewrite Memory.add_o; eauto. condtac; eauto. ss. des; congr.\nQed.\n\nLemma progress_read_step\n      lc1 mem1\n      loc ord\n      (WF1: Local.wf lc1 mem1)\n      (MEM1: Memory.closed mem1):\n  exists val released lc2 mts,\n    <<MAX: Memory.max_concrete_ts mem1 loc mts>> /\\\n    <<READ: Local.read_step lc1 mem1 loc mts val released ord lc2>>.\nProof.\n  dup MEM1. inv MEM0.\n  exploit (Memory.max_concrete_ts_exists); eauto. i. des.\n  exploit (Memory.max_concrete_ts_spec); eauto. i. des.\n  esplits; eauto. econs; eauto.\n  econs; i; eapply Memory.max_concrete_ts_spec2; eauto; apply WF1.\nQed.\n\nLemma progress_read_step_cur\n      lc1 mem1\n      loc ord\n      (WF1: Local.wf lc1 mem1)\n      (MEM1: Memory.closed mem1):\n  exists val released lc2,\n    <<READ: Local.read_step lc1 mem1 loc ((TView.cur (Local.tview lc1)).(View.rlx) loc) val released ord lc2>>.\nProof.\n  dup WF1. inv WF0. inv TVIEW_CLOSED. inv CUR.\n  specialize (RLX loc). des.\n  esplits. econs; eauto.\n  econs; try apply TVIEW_WF; try refl.\nQed.\n\nLemma progress_write_step\n      lc1 sc1 mem1\n      loc to val releasedm ord\n      (LT: Time.lt (Memory.max_ts loc mem1) to)\n      (WF1: Local.wf lc1 mem1)\n      (SC1: Memory.closed_timemap sc1 mem1)\n      (MEM1: Memory.closed mem1)\n      (WF_REL: View.opt_wf releasedm)\n      (CLOSED_REL: Memory.closed_opt_view releasedm mem1)\n      (PROMISES1: Ordering.le Ordering.strong_relaxed ord -> Memory.nonsynch_loc loc (Local.promises lc1)):\n  exists released lc2 sc2 mem2,\n    Local.write_step lc1 sc1 mem1 loc (Memory.max_ts loc mem1) to val releasedm released ord lc2 sc2 mem2 Memory.op_kind_add.\nProof.\n  exploit progress_promise_step; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des. inv x0.\n  exploit Memory.remove_exists; eauto.\n  { inv PROMISE. erewrite Memory.add_o; try eexact PROMISES.\n    condtac; eauto. ss. des; exfalso; apply o; eauto.\n  }\n  i. des.\n  esplits. econs; eauto.\n  econs; i; (try eapply TimeFacts.le_lt_lt; [|eauto]).\n  apply Memory.max_ts_spec2. apply WF1.\nQed.\n\nLemma progress_write_step_split\n      lc1 sc1 mem1\n      loc from to msg val releasedm ord\n      (GET: Memory.get loc to (Local.promises lc1) = Some (from, msg))\n      (CONS: Time.lt ((TView.cur (Local.tview lc1)).(View.rlx) loc) to)\n      (WF1: Local.wf lc1 mem1)\n      (SC1: Memory.closed_timemap sc1 mem1)\n      (MEM1: Memory.closed mem1)\n      (WF_REL: View.opt_wf releasedm)\n      (TS_REL: Time.le ((View.rlx (View.unwrap releasedm)) loc) from)\n      (CLOSED_REL: Memory.closed_opt_view releasedm mem1)\n      (PROMISES1: Ordering.le Ordering.strong_relaxed ord -> Memory.nonsynch_loc loc (Local.promises lc1))\n      (RESERVE: exists val' released', msg = Message.concrete val' released'):\n  exists released lc2 sc2 mem2,\n    Local.write_step lc1 sc1 mem1 loc from (Time.middle from to) val releasedm\n                     released ord lc2 sc2 mem2 (Memory.op_kind_split to msg).\nProof.\n  exploit Memory.get_ts; try exact GET. i. des.\n  { subst. inv WF1. rewrite BOT in GET. ss. }\n  exploit (@Memory.split_exists\n             (Local.promises lc1) loc from (Time.middle from to) to\n             (Message.concrete val (TView.write_released (Local.tview lc1) sc1 loc (Time.middle from to) releasedm ord))\n             msg);\n    try apply Time.middle_spec; auto.\n  { econs. eapply TViewFacts.write_future0; eauto. apply WF1. }\n  i. des.\n  exploit Memory.split_exists_le; try apply WF1; eauto. i. des.\n  exploit Memory.split_get0; try exact x1. i. des.\n  exploit Memory.remove_exists; try exact GET2. i. des.\n  clear GET0 GET1 GET2 GET3.\n  assert (TS: Time.le ((TView.cur (Local.tview lc1)).(View.rlx) loc) from).\n  { destruct (TimeFacts.le_lt_dec ((TView.cur (Local.tview lc1)).(View.rlx) loc) from); ss.\n    inv WF1. inv TVIEW_CLOSED. inv CUR.\n    specialize (RLX loc). des.\n    clear REL ACQ PLN.\n    exploit PROMISES; try exact GET. i.\n    exploit Memory.get_ts; try exact RLX. i. des.\n    { subst. rewrite x4 in l. inv l. }\n    exploit Memory.get_disjoint; [exact RLX|exact x|..]. i. des.\n    { subst. timetac. }\n    exfalso.\n    eapply x6; econs; [|refl|..]; ss. econs. ss.\n  }\n  esplits. econs; eauto.\n  - econs; ss.\n    eapply TimeFacts.le_lt_lt; eauto.\n    apply Time.middle_spec. ss.\n  - econs; eauto. econs; eauto.\n    econs. unfold TView.write_released. ss.\n    condtac; ss; try by unfold TimeMap.bot; apply Time.bot_spec.\n    unfold LocFun.add. condtac; ss.\n    unfold TimeMap.join. condtac; ss.\n    + unfold TimeMap.join, TimeMap.singleton.\n      unfold LocFun.add, LocFun.init, LocFun.find.\n      condtac; ss.\n      repeat apply Time.join_spec; ss; try refl.\n      * etrans; eauto. econs. apply Time.middle_spec; ss.\n      * etrans; eauto. econs. apply Time.middle_spec; ss.\n    + unfold TimeMap.join, TimeMap.singleton.\n      unfold LocFun.add, LocFun.init, LocFun.find.\n      condtac; ss.\n      repeat apply Time.join_spec; ss; try refl.\n      * etrans; eauto. econs. apply Time.middle_spec; ss.\n      * inv WF1. inv TVIEW_WF. etrans; try eapply REL_CUR.\n        etrans; eauto. econs. apply Time.middle_spec; ss.\nQed.\n\nLemma progress_fence_step\n      lc1 sc1\n      ordr ordw\n      (PROMISES1: Ordering.le Ordering.strong_relaxed ordw -> Memory.nonsynch (Local.promises lc1))\n      (PROMISES2: ordw = Ordering.seqcst -> (Local.promises lc1) = Memory.bot):\n  exists lc2 sc2,\n    Local.fence_step lc1 sc1 ordr ordw lc2 sc2.\nProof.\n  esplits. econs; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/lang/Progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.23729367625286418}}
{"text": "Require Import Framework TotalMem.\nImport ListNotations.\n\nSet Implicit Arguments.\n\nSection DiskLayer.\n\n  Variable A: Type.\n  Variable AEQ: EqDec A.\n  Variable V : Type.\n  Variable in_domain: A -> Prop.\n\n  Inductive token' :=\n  | Crash : token'\n  | Cont : token'.\n\n  Definition state' :=  @total_mem A AEQ (V * list V).\n  \n  Inductive disk_prog : Type -> Type :=\n  | Read : A -> disk_prog V\n  | Write : A -> V -> disk_prog unit\n  | Sync : disk_prog unit.\n   \n  Inductive exec' :\n    forall T, user -> token' ->  state' -> disk_prog T -> @Result state' T -> Prop :=\n  | ExecRead : \n      forall d a u,\n        in_domain a ->\n        exec' u Cont d (Read a) (Finished d (fst (d a)))\n             \n  | ExecWrite :\n      forall d a v u,\n        in_domain a ->\n        exec' u Cont d (Write a v) (Finished (upd d a (v, (fst (d a)::snd (d a)))) tt)\n\n  | ExecSync :\n      forall d u,\n        exec' u Cont d Sync (Finished (sync d) tt)\n \n  | ExecCrash :\n      forall T d (p: disk_prog T) u,\n        exec' u Crash d p (Crashed d).\n\n  Hint Constructors exec' : core.\n\n  Theorem exec_deterministic_wrt_token' :\n    forall u o s T (p: disk_prog T) ret1 ret2,\n      exec' u o s p ret1 ->\n      exec' u o s p ret2 ->\n      ret1 = ret2.\n  Proof.\n    intros; destruct p; simpl in *; cleanup;\n    repeat\n      match goal with\n      | [H: exec' _ _ _ _ _ |- _] =>\n        inversion H; clear H; cleanup\n      end; eauto.    \n  Qed. \n  \n  Definition DiskOperation :=\n    Build_Core\n      disk_prog\n      exec'\n      exec_deterministic_wrt_token'.\n  \n  Definition DiskLang := Build_Layer DiskOperation.\n\nNotation \"| p |\" := (Op DiskOperation p)(at level 60).\nNotation \"x <-| p1 ; p2\" := (Bind (Op DiskOperation p1) (fun x => p2))(right associativity, at level 60). \nNotation \"p >> s\" := (p s) (right associativity, at level 60, only parsing).\n\nEnd DiskLayer.\n\nArguments Read {_ _}.\nArguments Sync {_ _}.\n", "meta": {"author": "Atalay-Ileri", "repo": "ConFrm", "sha": "80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf", "save_path": "github-repos/coq/Atalay-Ileri-ConFrm", "path": "github-repos/coq/Atalay-Ileri-ConFrm/ConFrm-80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf/src/Layers/BasicLayers/Disk/DiskLayer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23727423047278098}}
{"text": "(* The seppapp operator: separating append, useful for contiguous memory regions *)\nRequire Import Coq.ZArith.ZArith. Local Open Scope Z_scope.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import coqutil.Tactics.Tactics coqutil.Tactics.fwd.\nRequire Import coqutil.Byte.\nRequire Import coqutil.Word.Interface coqutil.Word.Properties coqutil.Word.Bitwidth.\nRequire Import coqutil.Map.Interface.\nRequire Import bedrock2.Map.Separation bedrock2.Map.SeparationLogic.\nRequire Import bedrock2.SepLib.\nRequire Import bedrock2.PurifySep.\n\nDefinition sepapp{width: Z}{BW: Bitwidth width}{word: word.word width}\n  {mem: map.map word Byte.byte}\n  (P1 P2: word -> mem -> Prop){P1size: PredicateSize P1}: word -> mem -> Prop :=\n  fun addr => sep (P1 addr) (P2 (word.add addr (word.of_Z P1size))).\n\nDeclare Scope sepapp_scope. Local Open Scope sepapp_scope.\nInfix \"*+\" := sepapp (at level 36, left associativity) : sepapp_scope.\n\n#[export] Hint Extern 1 (PredicateSize (sepapp ?P1 ?P2)) =>\n  lazymatch constr:(_: PredicateSize P1) with\n  | ?sz1 => lazymatch constr:(_: PredicateSize P2) with\n            | ?sz2 => exact (Z.add sz1 sz2)\n            end\n  end\n: typeclass_instances.\n\n(* Placeholder for use with sepapp.\n   After removing one clause out of a series of sepapps, we get\n   (stuffBefore start_addr * stuffAfter (start_addr + size_of_stuffBefore + size_of_hole))\n   Using `hole`, we can write it more concisely:\n   (stuffBefore *+ hole size_of_hole *+ stuffAfter) start_addr *)\nDefinition hole{key value}{mem: map.map key value}(n: Z)(addr: key): mem -> Prop :=\n  emp True.\n#[export] Hint Extern 1 (PredicateSize (hole ?n)) => exact n : typeclass_instances.\n#[export] Hint Opaque hole : typeclass_instances.\n\n(* pair of a predicate and its size, used as tree leaves *)\nInductive sized_predicate{width: Z}{BW: Bitwidth width}{word: word.word width}\n  {mem: map.map word Byte.byte}: Type :=\n| mk_sized_predicate(p: word -> mem -> Prop)(sz: PredicateSize p).\n\nSection Reassociate_sepapp.\n  Context {width: Z} {BW: Bitwidth width} {word: word.word width} {word_ok: word.ok word}\n    {mem: map.map word byte} {mem_ok: map.ok mem}.\n\n  Import List.ListNotations. Local Open Scope list_scope.\n\n  Lemma sep_assoc_eq: forall (p q r: mem -> Prop),\n      sep (sep p q) r = sep p (sep q r).\n  Proof.\n    intros. eapply iff1ToEq. eapply sep_assoc.\n  Qed.\n\n  Lemma sepapp_assoc(P1 P2 P3: word -> mem -> Prop)\n    {sz1: PredicateSize P1}{sz2: PredicateSize P2}:\n    sepapp (sepapp P1 P2) P3 = sepapp P1 (sepapp P2 P3).\n  Proof.\n    unfold sepapp. extensionality addr.\n    rewrite sep_assoc_eq. rewrite <- word.add_assoc, word.ring_morph_add.\n    reflexivity.\n  Qed.\n\n  Definition sized_emp := mk_sized_predicate (fun a => emp True) 0.\n\n  Definition sepapp_sized_predicates(sp1 sp2: sized_predicate): sized_predicate :=\n    match sp1, sp2 with\n    | mk_sized_predicate p1 sz1, mk_sized_predicate p2 sz2 =>\n        mk_sized_predicate (@sepapp _ _ _ mem p1 p2 sz1) (sz1 + sz2)\n    end.\n\n  Definition proj_predicate(sp: sized_predicate): word -> mem -> Prop :=\n    match sp with\n    | mk_sized_predicate p _ => p\n    end.\n\n  Definition proj_size(sp: sized_predicate): Z :=\n    match sp with\n    | mk_sized_predicate _ sz => sz\n    end.\n\n  Definition sepapps(l: list sized_predicate): word -> mem -> Prop :=\n    proj_predicate (List.fold_right sepapp_sized_predicates sized_emp l).\n\n  (* Could be made stronger, but probably better to purify before a record\n     has been unfolded into sepapps *)\n  Lemma purify_sepapps: forall l a, purify (sepapps l a) True.\n  Proof. unfold purify. intros. constructor. Qed.\n\n  Definition sepapps_size(l: list sized_predicate): Z :=\n    List.fold_right Z.add 0 (List.map proj_size l).\n\n  Lemma sepapps_nil: forall a, sepapps nil a = emp True.\n  Proof. intros. reflexivity. Qed.\n\n  Lemma sepapps_cons: forall p l a,\n      sepapps (cons p l) a = sep (proj_predicate p a)\n                                 (sepapps l (word.add a (word.of_Z (proj_size p)))).\n  Proof.\n    intros. unfold sepapps. destruct p as [P sz]. simpl.\n    destruct (List.fold_right sepapp_sized_predicates sized_emp l). simpl.\n    unfold sepapp. reflexivity.\n  Qed.\n\n  Lemma sepapps_app: forall l1 l2 a,\n      sepapps (l1 ++ l2) a = sep (sepapps l1 a)\n                                 (sepapps l2 (word.add a (word.of_Z (sepapps_size l1)))).\n  Proof.\n    induction l1; intros; simpl.\n    - rewrite sepapps_nil. eapply iff1ToEq. rewrite sep_emp_True_l.\n      change (sepapps_size nil) with 0. rewrite word.add_0_r. reflexivity.\n    - rewrite 2sepapps_cons. rewrite IHl1.\n      rewrite sep_assoc_eq.\n      f_equal. f_equal. f_equal.\n      change (sepapps_size (a :: l1)) with (proj_size a + sepapps_size l1).\n      rewrite word.ring_morph_add.\n      symmetry. apply word.add_assoc.\n  Qed.\n\n  Lemma expose_nth_sepapp: forall l n a P sz,\n      List.nth_error l n = Some (mk_sized_predicate P sz) ->\n      sepapps l a = sep (P (word.add a (word.of_Z (sepapps_size (List.firstn n l)))))\n                        (sepapps (List.firstn n l ++\n                                  cons (mk_sized_predicate (hole sz) sz)\n                                  (List.skipn (S n) l)) a).\n  Proof.\n    intros. rewrite (List.nth_error_expose _ _ _ H) at 1.\n    rewrite ?sepapps_app, ?sepapps_cons. eapply iff1ToEq.\n    cbn [proj_predicate proj_size]. unfold hole. cancel.\n  Qed.\n\n  Lemma merge_back_nth_sepapp: forall l n a P sz,\n      List.nth_error l n = Some (mk_sized_predicate (hole sz) sz) ->\n      sep (P (word.add a (word.of_Z (sepapps_size (List.firstn n l))))) (sepapps l a) =\n        (sepapps (List.firstn n l ++ cons (mk_sized_predicate P sz) (List.skipn (S n) l)) a).\n  Proof.\n    intros. rewrite (List.nth_error_expose _ _ _ H) at 2.\n    rewrite ?sepapps_app, ?sepapps_cons. eapply iff1ToEq.\n    cbn [proj_predicate proj_size]. unfold hole. cancel.\n  Qed.\n\n(* Not sure if needed at all\n  Definition interp_sepapp_tree(t: Tree.Tree sized_predicate): word -> mem -> Prop :=\n    proj_predicate (Tree.interp id sepapp_sized_predicates t).\n\n  Lemma flatten_eq_interp_sepapp_tree_aux(t: Tree.Tree sized_predicate):\n    forall sp0: sized_predicate,\n      match List.fold_left sepapp_sized_predicates (Tree.flatten t) sp0,\n        sepapp_sized_predicates sp0 (Tree.interp id sepapp_sized_predicates t) with\n      | mk_sized_predicate p1 sz1, mk_sized_predicate p2 sz2 =>\n          p1 = p2 /\\ sz1 = sz2\n      end.\n  Proof.\n    induction t; intros.\n    - simpl. destruct sp0. destruct a. simpl. auto.\n    - simpl. change @app with @List.app.\n      rewrite List.fold_left_app.\n      specialize (IHt1 sp0).\n      specialize (IHt2 (List.fold_left sepapp_sized_predicates (Tree.flatten t1) sp0)).\n      destruct_one_match.\n      destr sp0.\n      destr (List.fold_left sepapp_sized_predicates (Tree.flatten t1)\n               (mk_sized_predicate p0 sz0)).\n      destr (Tree.interp id sepapp_sized_predicates t1).\n      destr (Tree.interp id sepapp_sized_predicates t2).\n      simpl in *.\n      fwd. subst. rewrite <- sepapp_assoc. rewrite Z.add_assoc. split; reflexivity.\n  Qed.\n\n  Lemma flatten_eq_interp_sepapp_tree(t : Tree.Tree sized_predicate):\n    sepapps (Tree.flatten t) = interp_sepapp_tree t.\n  Proof.\n    unfold sepapps, interp_sepapp_tree, proj_predicate.\n    pose proof (flatten_eq_interp_sepapp_tree_aux t sized_emp) as P.\n    unfold sized_emp in *. do 2 destruct_one_match. simpl in P. apply proj1 in P.\n    subst.\n    extensionality a. unfold sepapp. eapply iff1ToEq.\n    rewrite word.add_0_r. eapply sep_emp_True_l.\n  Qed.\n\n  Lemma interp_sepapp_tree_eq_of_flatten_eq(LHS RHS : Tree.Tree sized_predicate):\n    Tree.flatten LHS = Tree.flatten RHS ->\n    interp_sepapp_tree LHS = interp_sepapp_tree RHS.\n  Proof. intros. rewrite <-2flatten_eq_interp_sepapp_tree. f_equal. assumption. Qed.\n*)\n\nEnd Reassociate_sepapp.\n\n#[export] Hint Resolve purify_sepapps: purify.\n\nLtac is_ground_Z x :=\n  lazymatch x with\n  | ?op ?a ?b =>\n      lazymatch (lazymatch op with\n                 | Z.add => constr:(true)\n                 | Z.mul => constr:(true)\n                 | _ => constr:(false)\n                 end) with\n      | true => lazymatch is_ground_Z a with\n                | true => lazymatch is_ground_Z b with\n                          | true => constr:(true)\n                          | false => constr:(false)\n                          end\n                | false => constr:(false)\n                end\n      | false => constr:(false)\n      end\n  | _ => isZcst x\n  end.\n\nLtac sized_predicate_list_size l :=\n  lazymatch l with\n  | cons (mk_sized_predicate _ ?sz) nil => sz\n  | cons (mk_sized_predicate _ ?sz) ?rest =>\n      let sz' := sized_predicate_list_size rest in\n      constr:(Z.add sz sz')\n  | nil => Z0\n  end.\n\n(* Often, only the last field of a record is of variable size,\n   so computing the size left-associatively and adding up all\n   the constant sizes can simplify the expressions *)\nLtac sepapps_size_with_ground_acc acc l :=\n  lazymatch l with\n  | cons (mk_sized_predicate _ ?sz) ?rest =>\n      lazymatch is_ground_Z sz with\n      | true => let acc' := eval cbv in (Z.add acc sz) in\n                  sepapps_size_with_ground_acc acc' rest\n      | false => lazymatch sized_predicate_list_size rest with\n                 | Z0 => constr:(Z.add acc sz)\n                 | ?sz' => constr:(Z.add acc (Z.add sz sz'))\n                 end\n      end\n  | nil => acc\n  end.\n\n#[export] Hint Extern 1 (PredicateSize (sepapps ?l)) =>\n  let sz := sepapps_size_with_ground_acc Z0 l in exact sz\n: typeclass_instances.\n", "meta": {"author": "mit-plv", "repo": "bedrock2", "sha": "7f2d764ed79f394fe715505a04301d0fb502407f", "save_path": "github-repos/coq/mit-plv-bedrock2", "path": "github-repos/coq/mit-plv-bedrock2/bedrock2-7f2d764ed79f394fe715505a04301d0fb502407f/bedrock2/src/bedrock2/sepapp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23727422406245927}}
{"text": "Require Import oeuf.Common.\n\nRequire Import oeuf.Utopia.\nRequire Import oeuf.Metadata.\nRequire Import Program.\n\nRequire Import oeuf.ListLemmas.\nRequire Import oeuf.HList.\nRequire Import oeuf.CompilationUnit.\nRequire Import oeuf.Semantics.\nRequire Import oeuf.HighestValues.\n\nRequire oeuf.Untyped1.\nRequire oeuf.Untyped2.\n\nModule A := Untyped1.\nModule B := Untyped2.\nModule S := Untyped1.\n\n\nDefinition compile_genv :=\n    let fix go g :=\n        match g with\n        | [] => []\n        | e :: g' =>\n                map S.weaken_expr (e :: go g')\n        end in go.\n\nDefinition compile_cu (cu : list S.expr * list metadata) :\n        list S.expr * list metadata :=\n    let '(exprs, metas) := cu in\n    (compile_genv exprs, metas).\n\n\nLemma compile_get_weaken : forall AE fname,\n    A.get_weaken AE fname = nth_error (compile_genv AE) fname.\ninduction AE; destruct fname; intros; simpl.\n- reflexivity.\n- reflexivity.\n- reflexivity.\n- rewrite IHAE. simpl.\n  destruct (nth_error _ fname) eqn:Heq.\n  + eapply map_nth_error in Heq. erewrite Heq. reflexivity.\n  + symmetry. rewrite nth_error_None in *. rewrite map_length. auto.\nQed.\n\n\nLtac i_ctor := intros; constructor; eauto.\nLtac i_lem H := intros; eapply H; eauto.\n\nTheorem I_sim : forall (AE BE : list S.expr) s s',\n    compile_genv AE = BE ->\n    A.sstep AE s s' ->\n    B.sstep BE s s'.\n\ndestruct s as [e l k | v];\nintros0 Henv Astep; inv Astep.\nall: try solve [i_ctor].\n\n- i_lem B.SMakeCall. rewrite <- compile_get_weaken. auto.\nQed.\n\n\n\nLemma compile_cu_compile_genv : forall A Ameta B Bmeta,\n    compile_cu (A, Ameta) = (B, Bmeta) ->\n    compile_genv A = B.\nsimpl. inversion 1. auto.\nQed.\n\nLemma compile_cu_metas : forall A Ameta B Bmeta,\n    compile_cu (A, Ameta) = (B, Bmeta) ->\n    Ameta = Bmeta.\nsimpl. inversion 1. auto.\nQed.\n\nLemma compile_genv_length : forall a,\n    length a = length (compile_genv a).\ninduction a; simpl in *.\n- reflexivity.\n- rewrite map_length. f_equal. auto.\nQed.\n\nLemma compile_genv_weaken_expr : forall A,\n    map S.weaken_expr (compile_genv A) =\n    compile_genv (map S.weaken_expr A).\ninduction A; simpl.\n- reflexivity.\n- rewrite IHA. reflexivity.\nQed.\n\nLemma compile_genv_get_nth : forall A fname body,\n    nth_error (compile_genv A) fname = Some body ->\n    A.get_weaken A fname = Some body.\ninduction A; intros0 Hnth; destruct fname; try discriminate; simpl in *.\n- auto.\n- eapply map_nth_error' in Hnth.  destruct Hnth as (? & ? & ?).\n  erewrite IHA; eauto.\n  f_equal. eauto.\nQed.\n\nSection Preservation.\n\n    Variable aprog : A.prog_type.\n    Variable bprog : B.prog_type.\n\n    Hypothesis Hcomp : compile_cu aprog = bprog.\n\n    Theorem fsim : Semantics.forward_simulation (A.semantics aprog) (B.semantics bprog).\n    destruct aprog as [A Ameta], bprog as [B Bmeta].\n    fwd eapply compile_cu_compile_genv; eauto.\n    fwd eapply compile_cu_metas; eauto.\n\n    eapply Semantics.forward_simulation_step with\n        (match_states := @eq S.state)\n        (match_values := @eq value).\n\n    - simpl. intros0 Bcall Hf Ha. invc Bcall.\n      fwd eapply compile_genv_get_nth as HH; eauto.\n      eexists. split; i_ctor.\n\n    - simpl. intros0 II Afinal. invc Afinal.\n      eexists. split. i_ctor. i_ctor.\n\n    - simpl. eauto.\n    - simpl. intros. tauto.\n\n    - intros0 Astep. intros0 II.\n      fwd eapply I_sim; eauto.\n      subst s1. eexists. eauto.\n\n    Qed.\n\n\nEnd Preservation.\n\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/UntypedComp2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2372742240624592}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\n\nRequire Export Qhomographic_sign.\nRequire Export Qhomographic_Qpositive_to_Qpositive.\nRequire Export Qhomographic_sign_properties.\n\nDefinition new_a (a b c d : Z) (p : Qpositive)\n  (H_Qhomographic_sg_denom_nonzero : Qhomographic_sg_denom_nonzero c d p) :=\n  fst\n    (fst (snd (Qhomographic_sign a b c d p H_Qhomographic_sg_denom_nonzero))).\n\nDefinition new_b (a b c d : Z) (p : Qpositive)\n  (H_Qhomographic_sg_denom_nonzero : Qhomographic_sg_denom_nonzero c d p) :=\n  fst\n    (snd\n       (fst\n          (snd (Qhomographic_sign a b c d p H_Qhomographic_sg_denom_nonzero)))).\n\nDefinition new_c (a b c d : Z) (p : Qpositive)\n  (H_Qhomographic_sg_denom_nonzero : Qhomographic_sg_denom_nonzero c d p) :=\n  fst\n    (snd\n       (snd\n          (fst\n             (snd\n                (Qhomographic_sign a b c d p H_Qhomographic_sg_denom_nonzero))))).\n\nDefinition new_d (a b c d : Z) (p : Qpositive)\n  (H_Qhomographic_sg_denom_nonzero : Qhomographic_sg_denom_nonzero c d p) :=\n  snd\n    (snd\n       (snd\n          (fst\n             (snd\n                (Qhomographic_sign a b c d p H_Qhomographic_sg_denom_nonzero))))).\n\nDefinition new_p (a b c d : Z) (p : Qpositive)\n  (H_Qhomographic_sg_denom_nonzero : Qhomographic_sg_denom_nonzero c d p) :=\n  snd (snd (Qhomographic_sign a b c d p H_Qhomographic_sg_denom_nonzero)).\n\nLemma Qhomographic_Qpositive_to_Q_homographicAcc_pos_1 :\n forall (a b c d : Z) (p : Qpositive)\n   (H_Qhomographic_sg_denom_nonzero : Qhomographic_sg_denom_nonzero c d p),\n (a * d)%Z <> (b * c)%Z ->\n h_sign a b c d p H_Qhomographic_sg_denom_nonzero = 1%Z ->\n (0 <\n  Z.sgn\n    (new_a a b c d p H_Qhomographic_sg_denom_nonzero +\n     new_b a b c d p H_Qhomographic_sg_denom_nonzero))%Z ->\n homographicAcc (new_a a b c d p H_Qhomographic_sg_denom_nonzero)\n   (new_b a b c d p H_Qhomographic_sg_denom_nonzero)\n   (new_c a b c d p H_Qhomographic_sg_denom_nonzero)\n   (new_d a b c d p H_Qhomographic_sg_denom_nonzero)\n   (new_p a b c d p H_Qhomographic_sg_denom_nonzero).\nProof.\n intros a b c d p H_hsign ad_neq_bc l1_eq_one z.\n set (na := new_a a b c d p H_hsign) in *.\n set (nb := new_b a b c d p H_hsign) in *.\n set (nc := new_c a b c d p H_hsign) in *.\n set (nd := new_d a b c d p H_hsign) in *.\n set (l3 := new_p a b c d p H_hsign) in *.\n assert\n  (H : Qhomographic_sign a b c d p H_hsign = (1%Z, (na, (nb, (nc, nd)), l3))).\n unfold na, nb, nc, nd, l3 in |- *.\n rewrite <- l1_eq_one.\n unfold new_a, new_b, new_c, new_d, new_p in |- *.\n replace (h_sign a b c d p H_hsign) with\n  (fst (Qhomographic_sign a b c d p H_hsign)); [ idtac | reflexivity ];\n  repeat rewrite <- pair_1; reflexivity.\n      destruct l3 as [p0| p0| ].\n      (* l3 = (nR p0) *)\n      apply homographicAcc_wf.\n      apply Zsgn_12.\n      assumption.\n     \n      generalize (sg_pos_1 a b c d p H_hsign na nb nc nd (nR p0) H).        \n      intros.\n      case H0.             \n      intro.\n      elim a0.\n      intros.     \n      assumption.\n      intros.\n      apply False_ind.      \n      elim a0.\n      intros.\n      generalize (Zsgn_12 (na + nb) z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros; assumption.\n      intro.\n      apply False_ind.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      apply Zsgn_12.\n      assumption.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      assumption.\n      intro.\n      apply False_ind.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      apply Zsgn_12.\n      assumption.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      assumption.\n      intro.\n      apply False_ind.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      apply Zsgn_12.\n      assumption.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      assumption.\n      intro.\n      apply False_ind.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      apply Zsgn_12.\n      assumption.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      intro.      \n      discriminate e.\n      (* l3 = (dL p0) *)\n      apply homographicAcc_wf.\n      apply Zsgn_12.\n      assumption.\n     \n      generalize (sg_pos_1 a b c d p H_hsign na nb nc nd (dL p0) H).        \n      intros.\n      case H0.             \n      intro.\n      elim a0.\n      intros.     \n      assumption.\n      intros.\n      apply False_ind.      \n      elim a0.\n      intros.\n      generalize (Zsgn_12 (na + nb) z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros; assumption.\n      intro.\n      apply False_ind.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      apply Zsgn_12.\n      assumption.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      assumption.\n      intro.\n      apply False_ind.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      apply Zsgn_12.\n      assumption.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      assumption.\n      intro.\n      apply False_ind.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      apply Zsgn_12.\n      assumption.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      assumption.\n      intro.\n      apply False_ind.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      apply Zsgn_12.\n      assumption.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      intro.      \n      discriminate e.\n      (* l3 = One *)\n      apply homographicacc0.\n      reflexivity.\n      apply Zsgn_12.\n      assumption.\n      generalize (sg_pos_1 a b c d p H_hsign na nb nc nd One H).        \n      intros.\n      case H0.             \n      intro.\n      elim a0.\n      intros.     \n      assumption.\n      intros.\n      apply False_ind.      \n      elim a0.\n      intros.\n      generalize (Zsgn_12 (na + nb) z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\nDefined.\n\nLemma Qhomographic_Qpositive_to_Q_homographicAcc_pos_2 :\n forall (a b c d : Z) (p : Qpositive)\n   (H_Qhomographic_sg_denom_nonzero : Qhomographic_sg_denom_nonzero c d p),\n (a * d)%Z <> (b * c)%Z ->\n h_sign a b c d p H_Qhomographic_sg_denom_nonzero = 1%Z ->\n (Z.sgn\n    (new_a a b c d p H_Qhomographic_sg_denom_nonzero +\n     new_b a b c d p H_Qhomographic_sg_denom_nonzero) <= 0)%Z ->\n homographicAcc (- new_a a b c d p H_Qhomographic_sg_denom_nonzero)\n   (- new_b a b c d p H_Qhomographic_sg_denom_nonzero)\n   (- new_c a b c d p H_Qhomographic_sg_denom_nonzero)\n   (- new_d a b c d p H_Qhomographic_sg_denom_nonzero)\n   (new_p a b c d p H_Qhomographic_sg_denom_nonzero).\nProof.\n intros a b c d p H_hsign ad_neq_bc l1_eq_one z.\n set (na := new_a a b c d p H_hsign) in *.\n set (nb := new_b a b c d p H_hsign) in *.\n set (nc := new_c a b c d p H_hsign) in *.\n set (nd := new_d a b c d p H_hsign) in *.\n set (l3 := new_p a b c d p H_hsign) in *.\n assert\n  (H : Qhomographic_sign a b c d p H_hsign = (1%Z, (na, (nb, (nc, nd)), l3))).\n unfold na, nb, nc, nd, l3 in |- *.\n rewrite <- l1_eq_one.\n unfold new_a, new_b, new_c, new_d, new_p in |- *.\n replace (h_sign a b c d p H_hsign) with\n  (fst (Qhomographic_sign a b c d p H_hsign)); [ idtac | reflexivity ];\n  repeat rewrite <- pair_1; reflexivity.\n      destruct l3 as [p0| p0| ].\n      (* l3 = (nR p0) *)\n      apply homographicAcc_wf.\n      generalize (sg_pos_1 a b c d p H_hsign na nb nc nd (nR p0) H).\n      intro.\n      case H0. \n      intros.\n      apply False_ind.\n      elim a0.\n      intros.      \n      generalize (Zsgn_14 _ z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      rewrite <- Zopp_plus_distr.\n      apply Zlt_neg_opp.\n      assumption.\n      generalize (sg_pos_1 a b c d p H_hsign na nb nc nd (nR p0) H).\n      intro.\n      case H0. \n      intros.\n      apply False_ind.\n      elim a0.\n      intros.      \n      generalize (Zsgn_14 _ z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      rewrite <- Zopp_plus_distr.\n      apply Zlt_neg_opp.\n      assumption.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      case (Z_le_lt_eq_dec 0 na H1).\n      intro.\n      apply False_ind.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_lt_le_compat.\n      assumption.      \n      assumption.\n      apply (Zsgn_14 _ z).\n      intro.\n      rewrite <- e.\n      simpl in |- *.\n      apply Z.le_refl.\n      intro.\n      elim a0.\n      intros.\n      apply Zle_neg_opp.      \n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      case (Z_le_lt_eq_dec 0 nb H3).\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_lt_compat.\n      assumption.      \n      assumption.\n      apply (Zsgn_14 _ z).\n      intro.\n      rewrite <- e.\n      simpl in |- *.\n      apply Z.le_refl.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Zle_neg_opp.      \n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      case (Z_le_lt_eq_dec 0 nc H5).\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (nc + nd)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_lt_le_compat.\n      assumption.      \n      assumption.\n      case (sg_pos_1 a b c d p H_hsign na nb nc nd (nR p0) H).\n      intro. \n      apply False_ind.\n      elim a1.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      assumption.\n      apply (Zsgn_14 _ z).\n      intros.\n      elim a1.\n      intros.\n      apply Zlt_le_weak.      \n      assumption.\n      intro.\n      rewrite <- e.\n      simpl in |- *.\n      apply Z.le_refl.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4. \n      intros.\n      apply Zle_neg_opp.      \n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      case (Z_le_lt_eq_dec 0 nd H6).\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (nc + nd)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_lt_compat.\n      assumption.      \n      assumption.\n      case (sg_pos_1 a b c d p H_hsign na nb nc nd (nR p0) H).\n      intro. \n      apply False_ind.\n      elim a1.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      assumption.\n      apply (Zsgn_14 _ z).\n      intros.\n      elim a1.\n      intros.\n      apply Zlt_le_weak.      \n      assumption.\n      intro.\n      rewrite <- e.\n      simpl in |- *.\n      apply Z.le_refl.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4. \n      intros.\n      apply Zle_neg_opp.      \n      assumption.\n      intro.      \n      discriminate e.\n      (* l3 = (dL p0) *)\n      apply homographicAcc_wf.\n      generalize (sg_pos_1 a b c d p H_hsign na nb nc nd (dL p0) H).\n      intro.\n      case H0. \n      intros.\n      apply False_ind.\n      elim a0.\n      intros.      \n      generalize (Zsgn_14 _ z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      rewrite <- Zopp_plus_distr.\n      apply Zlt_neg_opp.\n      assumption.\n      generalize (sg_pos_1 a b c d p H_hsign na nb nc nd (dL p0) H).\n      intro.\n      case H0. \n      intros.\n      apply False_ind.\n      elim a0.\n      intros.      \n      generalize (Zsgn_14 _ z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      rewrite <- Zopp_plus_distr.\n      apply Zlt_neg_opp.\n      assumption.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      case (Z_le_lt_eq_dec 0 na H1).\n      intro.\n      apply False_ind.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_lt_le_compat.\n      assumption.      \n      assumption.\n      apply (Zsgn_14 _ z).\n      intro.\n      rewrite <- e.\n      simpl in |- *.\n      apply Z.le_refl.\n      intro.\n      elim a0.\n      intros.\n      apply Zle_neg_opp.      \n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      case (Z_le_lt_eq_dec 0 nb H3).\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_lt_compat.\n      assumption.      \n      assumption.\n      apply (Zsgn_14 _ z).\n      intro.\n      rewrite <- e.\n      simpl in |- *.\n      apply Z.le_refl.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Zle_neg_opp.      \n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      case (Z_le_lt_eq_dec 0 nc H5).\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (nc + nd)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_lt_le_compat.\n      assumption.      \n      assumption.\n      case (sg_pos_1 a b c d p H_hsign na nb nc nd (dL p0) H).\n      intro. \n      apply False_ind.\n      elim a1.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      assumption.\n      apply (Zsgn_14 _ z).\n      intros.\n      elim a1.\n      intros.\n      apply Zlt_le_weak.      \n      assumption.\n      intro.\n      rewrite <- e.\n      simpl in |- *.\n      apply Z.le_refl.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4. \n      intros.\n      apply Zle_neg_opp.      \n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_pos_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      case (Z_le_lt_eq_dec 0 nd H6).\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (nc + nd)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_lt_compat.\n      assumption.      \n      assumption.\n      case (sg_pos_1 a b c d p H_hsign na nb nc nd (dL p0) H).\n      intro. \n      apply False_ind.\n      elim a1.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      assumption.\n      apply (Zsgn_14 _ z).\n      intros.\n      elim a1.\n      intros.\n      apply Zlt_le_weak.      \n      assumption.\n      intro.\n      rewrite <- e.\n      simpl in |- *.\n      apply Z.le_refl.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4. \n      intros.\n      apply Zle_neg_opp.      \n      assumption.\n      intro.      \n      discriminate e.\n      (* l3 = One *)\n      apply homographicacc0.\n      reflexivity.\n      generalize (sg_pos_1 a b c d p H_hsign na nb nc nd One H).\n      intro.\n      case H0. \n      intros.\n      apply False_ind.\n      elim a0.\n      intros.      \n      generalize (Zsgn_14 _ z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      rewrite <- Zopp_plus_distr.\n      apply Zlt_neg_opp.\n      assumption.\n      generalize (sg_pos_1 a b c d p H_hsign na nb nc nd One H).\n      intro.\n      case H0. \n      intros.\n      apply False_ind.\n      elim a0.\n      intros.      \n      generalize (Zsgn_14 _ z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_le_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      rewrite <- Zopp_plus_distr.\n      apply Zlt_neg_opp.\n      assumption.\nDefined.\n\n\nLemma Qhomographic_Qpositive_to_Q_homographicAcc_neg_1 :\n forall (a b c d : Z) (p : Qpositive)\n   (H_hsign : Qhomographic_sg_denom_nonzero c d p),\n (a * d)%Z <> (b * c)%Z ->\n h_sign a b c d p H_hsign = (-1)%Z ->\n (Z.sgn (new_a a b c d p H_hsign + new_b a b c d p H_hsign) < 0)%Z ->\n homographicAcc (- new_a a b c d p H_hsign) (- new_b a b c d p H_hsign)\n   (new_c a b c d p H_hsign) (new_d a b c d p H_hsign)\n   (new_p a b c d p H_hsign).\nProof.\n intros a b c d p H_hsign ad_neq_bc l1_eq__minus_one z.\n set (na := new_a a b c d p H_hsign) in *.\n set (nb := new_b a b c d p H_hsign) in *.\n set (nc := new_c a b c d p H_hsign) in *.\n set (nd := new_d a b c d p H_hsign) in *.\n set (l3 := new_p a b c d p H_hsign) in *.\n assert\n  (H :\n   Qhomographic_sign a b c d p H_hsign = ((-1)%Z, (na, (nb, (nc, nd)), l3))).\n unfold na, nb, nc, nd, l3 in |- *.\n rewrite <- l1_eq__minus_one.\n unfold new_a, new_b, new_c, new_d, new_p in |- *.\n replace (h_sign a b c d p H_hsign) with\n  (fst (Qhomographic_sign a b c d p H_hsign)); [ idtac | reflexivity ];\n  repeat rewrite <- pair_1; reflexivity.\n      destruct l3 as [p0| p0| ].\n      (* l3 = (nR p0) *)\n      apply homographicAcc_wf.\n      rewrite <- Zopp_plus_distr.\n      apply Zlt_neg_opp.\n      apply Zsgn_11.\n      assumption.\n     \n      generalize (sg_neg_1 a b c d p H_hsign na nb nc nd (nR p0) H).        \n      intros.\n      case H0.             \n      intro.\n      elim a0.\n      intros.     \n      apply False_ind.      \n      generalize (Zsgn_11 (na + nb) z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      intros.\n      elim a0.    \n      intros.  \n      assumption.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      apply False_ind.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      apply Zsgn_11.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      apply Zle_neg_opp.\n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      apply Zsgn_11.\n      assumption.\n      intros.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Zle_neg_opp.\n      assumption.\n      intro.\n      discriminate e.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      apply Zsgn_11.\n      assumption.\n      intros.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      apply Zsgn_11.\n      assumption.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      assumption.\n      intro.      \n      discriminate e.\n      (* l3 = (dL p0) *)\n      apply homographicAcc_wf.\n      rewrite <- Zopp_plus_distr.\n      apply Zlt_neg_opp.\n      apply Zsgn_11.\n      assumption.\n     \n      generalize (sg_neg_1 a b c d p H_hsign na nb nc nd (dL p0) H).        \n      intros.\n      case H0.             \n      intro.\n      elim a0.\n      intros.     \n      apply False_ind.      \n      generalize (Zsgn_11 (na + nb) z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      intros.\n      elim a0.    \n      intros.  \n      assumption.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      apply False_ind.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      apply Zsgn_11.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      apply Zle_neg_opp.\n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      apply Zsgn_11.\n      assumption.\n      intros.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      apply Zle_neg_opp.\n      assumption.\n      intro.\n      discriminate e.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      apply Zsgn_11.\n      assumption.\n      intros.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      assumption.\n      intro.      \n      discriminate e.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_compat.\n      assumption.      \n      assumption.\n      apply Zsgn_11.\n      assumption.\n      intro.\n      elim a0. \n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      assumption.\n      intro.      \n      discriminate e.\n      (* l3 = One *)\n      apply homographicacc0.\n      reflexivity.\n      rewrite <- Zopp_plus_distr.\n      apply Zlt_neg_opp.\n      apply Zsgn_11.\n      assumption.\n      generalize (sg_neg_1 a b c d p H_hsign na nb nc nd One H).        \n      intros.\n      case H0.             \n      intro.\n      elim a0.\n      intros.     \n      apply False_ind.      \n      generalize (Zsgn_11 (na + nb) z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      assumption.\nDefined.\n\n\nLemma Qhomographic_Qpositive_to_Q_homographicAcc_neg_2 :\n forall (a b c d : Z) (p : Qpositive)\n   (H_hsign : Qhomographic_sg_denom_nonzero c d p),\n (a * d)%Z <> (b * c)%Z ->\n h_sign a b c d p H_hsign = (-1)%Z ->\n (0 <= Z.sgn (new_a a b c d p H_hsign + new_b a b c d p H_hsign))%Z ->\n homographicAcc (new_a a b c d p H_hsign) (new_b a b c d p H_hsign)\n   (- new_c a b c d p H_hsign) (- new_d a b c d p H_hsign)\n   (new_p a b c d p H_hsign).\nProof.\n intros a b c d p H_hsign ad_neq_bc l1_eq__minus_one z.\n set (na := new_a a b c d p H_hsign) in *.\n set (nb := new_b a b c d p H_hsign) in *.\n set (nc := new_c a b c d p H_hsign) in *.\n set (nd := new_d a b c d p H_hsign) in *.\n set (l3 := new_p a b c d p H_hsign) in *.\n assert\n  (H :\n   Qhomographic_sign a b c d p H_hsign = ((-1)%Z, (na, (nb, (nc, nd)), l3))).\n unfold na, nb, nc, nd, l3 in |- *.\n rewrite <- l1_eq__minus_one.\n unfold new_a, new_b, new_c, new_d, new_p in |- *.\n replace (h_sign a b c d p H_hsign) with\n  (fst (Qhomographic_sign a b c d p H_hsign)); [ idtac | reflexivity ];\n  repeat rewrite <- pair_1; reflexivity.\n      destruct l3 as [p0| p0| ].\n      (* l3 = (nR p0) *)\n      apply homographicAcc_wf.\n      generalize (sg_neg_1 a b c d p H_hsign na nb nc nd (nR p0) H).\n      intro.\n      case H0. \n      intros.\n      elim a0.\n      intros.\n      assumption.\n      intros.\n      apply False_ind.\n      elim a0.\n      intros.      \n      generalize (Zsgn_13 _ z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      generalize (sg_neg_1 a b c d p H_hsign na nb nc nd (nR p0) H).\n      intro.\n      case H0. \n      intros.\n      elim a0.\n      intros.\n      rewrite <- Zopp_plus_distr.      \n      apply Zlt_neg_opp.\n      assumption.\n      intros.\n      apply False_ind.\n      elim a0.\n      intros.      \n      generalize (Zsgn_13 _ z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      assumption.\n      intros.\n      elim a0.\n      intros.\n      case (Z_le_lt_eq_dec na 0 H1).\n      intro.\n      apply False_ind.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      apply (Zsgn_13 _ z).\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_lt_le_compat.\n      assumption.      \n      assumption.\n      intro.\n      rewrite e.\n      apply Z.le_refl.\n      intro.      \n      discriminate e.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      assumption.\n      intros.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      case (Z_le_lt_eq_dec nb 0 H3).\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      apply (Zsgn_13 _ z).\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_lt_compat.\n      assumption.      \n      assumption.\n      intro.\n      rewrite e.\n      apply Z.le_refl.\n      intro.      \n      discriminate e.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      apply Zle_neg_opp.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      case (Z_le_lt_eq_dec 0 nc H5).\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_trans with (nc + nd)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_lt_le_compat.\n      assumption.      \n      assumption.\n      case (sg_neg_1 a b c d p H_hsign na nb nc nd (nR p0) H).\n      intro. \n      elim a1.\n      intros.\n      assumption.\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      apply (Zsgn_13 _ z). \n      elim a1.\n      intros.\n      assumption.\n      intro.\n      rewrite <- e.\n      simpl in |- *.\n      apply Z.le_refl.\n      intro.      \n      discriminate e.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (nR p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      apply Zle_neg_opp.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      case (Z_le_lt_eq_dec 0 nd H6).\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_trans with (nc + nd)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_lt_compat.\n      assumption.      \n      assumption.\n      case (sg_neg_1 a b c d p H_hsign na nb nc nd (nR p0) H).\n      intro. \n      elim a1.\n      intros.\n      assumption.\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      apply (Zsgn_13 _ z). \n      elim a1.\n      intros.\n      assumption.\n      intro.\n      rewrite <- e.\n      simpl in |- *.\n      apply Z.le_refl.\n      intro.      \n      discriminate e.\n      (* l3 = (dL p0) *)\n      apply homographicAcc_wf.\n      generalize (sg_neg_1 a b c d p H_hsign na nb nc nd (dL p0) H).\n      intro.\n      case H0. \n      intros.\n      elim a0.\n      intros.\n      assumption.\n      intros.\n      apply False_ind.\n      elim a0.\n      intros.      \n      generalize (Zsgn_13 _ z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      generalize (sg_neg_1 a b c d p H_hsign na nb nc nd (dL p0) H).\n      intro.\n      case H0. \n      intros.\n      elim a0.\n      intros.\n      rewrite <- Zopp_plus_distr.      \n      apply Zlt_neg_opp.\n      assumption.\n      intros.\n      apply False_ind.\n      elim a0.\n      intros.      \n      generalize (Zsgn_13 _ z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      assumption.\n      intros.\n      elim a0.\n      intros.\n      case (Z_le_lt_eq_dec na 0 H1).\n      intro.\n      apply False_ind.\n      elim H2.\n      intros.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      apply (Zsgn_13 _ z).\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_lt_le_compat.\n      assumption.      \n      assumption.\n      intro.\n      rewrite e.\n      apply Z.le_refl.\n      intro.      \n      discriminate e.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      assumption.\n      intros.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      case (Z_le_lt_eq_dec nb 0 H3).\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      apply (Zsgn_13 _ z).\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_lt_compat.\n      assumption.      \n      assumption.\n      intro.\n      rewrite e.\n      apply Z.le_refl.\n      intro.      \n      discriminate e.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      apply Zle_neg_opp.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      case (Z_le_lt_eq_dec 0 nc H5).\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_trans with (nc + nd)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_lt_le_compat.\n      assumption.      \n      assumption.\n      case (sg_neg_1 a b c d p H_hsign na nb nc nd (dL p0) H).\n      intro. \n      elim a1.\n      intros.\n      assumption.\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      apply (Zsgn_13 _ z). \n      elim a1.\n      intros.\n      assumption.\n      intro.\n      rewrite <- e.\n      simpl in |- *.\n      apply Z.le_refl.\n      intro.      \n      discriminate e.\n      generalize (sg_neg_2 a b c d p H_hsign na nb nc nd (dL p0) H). \n      intro.\n      case H0.         \n      intro.\n      case s.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      apply Zle_neg_opp.\n      assumption.\n      intro.\n      elim a0.\n      intros.\n      elim H2.\n      intros.\n      elim H4.\n      intros.\n      case (Z_le_lt_eq_dec 0 nd H6).\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.lt_trans with (nc + nd)%Z.\n      rewrite Zplus_0_r_reverse with 0%Z.\n      apply Zplus_le_lt_compat.\n      assumption.      \n      assumption.\n      case (sg_neg_1 a b c d p H_hsign na nb nc nd (dL p0) H).\n      intro. \n      elim a1.\n      intros.\n      assumption.\n      intro.\n      apply False_ind.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      apply (Zsgn_13 _ z). \n      elim a1.\n      intros.\n      assumption.\n      intro.\n      rewrite <- e.\n      simpl in |- *.\n      apply Z.le_refl.\n      intro.      \n      discriminate e.\n      (* l3 = One *)\n      apply homographicacc0.\n      reflexivity.\n      generalize (sg_neg_1 a b c d p H_hsign na nb nc nd One H).\n      intro.\n      case H0. \n      intros.\n      elim a0.\n      intros.\n      assumption.\n      intro.\n      apply False_ind.\n      elim a0.\n      intros.      \n      generalize (Zsgn_13 _ z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\n      rewrite <- Zopp_plus_distr.\n      apply Zlt_neg_opp.\n      generalize (sg_neg_1 a b c d p H_hsign na nb nc nd One H).\n      intro.\n      case H0. \n      intros.\n      elim a0.\n      intros.\n      assumption.\n      intro.\n      apply False_ind.\n      elim a0.\n      intros.      \n      generalize (Zsgn_13 _ z).\n      intro.\n      apply Z.lt_irrefl with 0%Z.\n      apply Z.le_lt_trans with (na + nb)%Z.\n      assumption.\n      assumption.\nDefined.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/qarith-stern-brocot/homographicAcc_Qhomographic_sign.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23724647464773652}}
{"text": "From sflib Require Import sflib.\nRequire Import Coq.Classes.RelationClasses.\nFrom Fairness Require Import Axioms NatStructsLarge.\nFrom Fairness Require Import PCMLarge World.\nFrom Fairness Require Import Mod.\nRequire Import String Lia Program.\n\nSet Implicit Arguments.\n\nSection THREADS_RA_DEF.\n\n  Inductive threadsRA_car : Type :=\n  | global_local\n      (ths_ctx ths_usr : TIdSet.t)\n      (ths_ctx' ths_usr' : TIdSet.t)\n  | local (ths_ctx' ths_usr' : TIdSet.t)\n  | boom\n  .\n\n  Inductive threadsRA_wf : threadsRA_car -> Prop :=\n  | wf_global_local ths_ctx ths_usr ths_ctx' ths_usr'\n      (DISJOINT : NatMapP.Disjoint ths_ctx ths_usr)\n      (LE_CTX : KeySetLE ths_ctx' ths_ctx)\n      (LE_USR : KeySetLE ths_usr' ths_usr)\n    : threadsRA_wf (global_local ths_ctx ths_usr ths_ctx' ths_usr')\n  | wf_local ths_ctx' ths_usr'\n    : threadsRA_wf (local ths_ctx' ths_usr')\n  .\n\n  Definition add (r1 r2 : threadsRA_car) : threadsRA_car :=\n    match r1, r2 with\n    | global_local ths_ctx ths_usr ths_ctx' ths_usr', global_local _ _ _ _      => boom\n    | global_local ths_ctx ths_usr ths_ctx' ths_usr', local ths_ctx'' ths_usr'' =>\n        if (disjoint ths_ctx' ths_ctx'' && disjoint ths_usr' ths_usr'')%bool\n        then global_local ths_ctx ths_usr (NatMapP.update ths_ctx' ths_ctx'') (NatMapP.update ths_usr' ths_usr'')\n        else boom\n    | global_local ths_ctx ths_usr ths_ctx' ths_usr', boom                      => boom\n    | local ths_ctx' ths_usr', global_local ths_ctx ths_usr ths_ctx'' ths_usr'' =>\n        if (disjoint ths_ctx' ths_ctx'' && disjoint ths_usr' ths_usr'')%bool\n        then global_local ths_ctx ths_usr (NatMapP.update ths_ctx' ths_ctx'') (NatMapP.update ths_usr' ths_usr'')\n        else boom\n    | local ths_ctx' ths_usr', local ths_ctx'' ths_usr''                        =>\n        if (disjoint ths_ctx' ths_ctx'' && disjoint ths_usr' ths_usr'')%bool\n        then local (NatMapP.update ths_ctx' ths_ctx'') (NatMapP.update ths_usr' ths_usr'')\n        else boom\n    | local ths_ctx' ths_usr', boom                                             => boom\n    | boom, _                                                                   => boom\n    end.\n  Program Instance threadsRA: URA.t :=\n    {|\n      URA.car := threadsRA_car;\n      URA.unit := local NatSet.empty NatSet.empty;\n      URA._wf := threadsRA_wf;\n      URA._add := add;\n      URA.core := fun _ => local NatSet.empty NatSet.empty;\n    |}.\n  Next Obligation.\n    destruct a, b; ss.\n    all: rewrite disjoint_comm with (x := ths_ctx').\n    all: rewrite disjoint_comm with (x := ths_usr').\n    all: rewrite union_comm with (x := ths_ctx').\n    all: rewrite union_comm with (x := ths_usr').\n    all: ss.\n  Qed.\n  Next Obligation.\n    destruct a, b, c; try (ss; des_ifs; fail).\n    all: unfold add; des_ifs; try (rewrite 2 union_assoc; ss); solve_disjoint!.\n  Qed.\n  Next Obligation.\n    unseal \"ra\". destruct a; try easy.\n    all:\n      unfold add; des_ifs; try (do 2 rewrite union_comm, union_empty; ss);\n      unfold NatSet.empty in Heq; solve_disjoint!.\n  Qed.\n  Next Obligation.\n    unseal \"ra\". econs.\n  Qed.\n  Next Obligation.\n    unseal \"ra\". destruct a, b; inv H; unfold add; des_ifs; econs; ss.\n    - assert (KeySetLE ths_ctx' (NatMapP.update ths_ctx' ths_ctx'0)) by eapply union_KeySetLE.\n      unfold KeySetLE in *. auto.\n    - assert (KeySetLE ths_usr' (NatMapP.update ths_usr' ths_usr'0)) by eapply union_KeySetLE.\n      unfold KeySetLE in *. auto.\n  Qed.\n  Next Obligation.\n    unseal \"ra\". destruct a; ss.\n    - f_equal; rewrite union_comm; ss.\n    - f_equal; rewrite union_comm; ss.\n  Qed.\n  Next Obligation.\n    exists (local NatSet.empty NatSet.empty). unseal \"ra\". ss.\n  Qed.\n\nEnd THREADS_RA_DEF.\n\nSection THREADS_RA.\n\n  Definition global_th (ths_ctx ths_usr : TIdSet.t) : threadsRA := global_local ths_ctx ths_usr TIdSet.empty TIdSet.empty.\n\n  Definition local_th_context (tid: thread_id): threadsRA := local (TIdSet.add tid TIdSet.empty) TIdSet.empty.\n\n  Definition local_th_user (tid: thread_id): threadsRA := local TIdSet.empty (TIdSet.add tid TIdSet.empty).\n\n  Lemma local_th_context_in_context ths_ctx ths_usr tid r_ctx\n        (VALID: URA.wf (global_th ths_ctx ths_usr ⋅ local_th_context tid ⋅ r_ctx))\n    :\n    TIdSet.In tid ths_ctx.\n  Proof.\n    eapply URA.wf_mon in VALID. unfold URA.add, URA.wf in VALID. unseal \"ra\".\n    unfold global_th, local_th_context in *. ss.\n    inv VALID. eapply LE_CTX. (do 3 econs); ss.\n  Qed.\n\n  Lemma local_th_user_in_user ths_ctx ths_usr tid r_ctx\n        (VALID: URA.wf (global_th ths_ctx ths_usr ⋅ local_th_user tid ⋅ r_ctx))\n    :\n    TIdSet.In tid ths_usr.\n    eapply URA.wf_mon in VALID. unfold URA.add, URA.wf in VALID. unseal \"ra\".\n    inv VALID. eapply LE_USR. (do 3 econs); ss.\n  Qed.\n\n  Lemma initial_global_th_valid\n    :\n    URA.wf (global_th TIdSet.empty TIdSet.empty).\n  Proof.\n    unfold URA.wf. unseal \"ra\". econs; eauto using Disjoint_empty, KeySetLE_empty.\n  Qed.\n\n  Lemma global_th_alloc_context ths_ctx0 ths_usr r_ctx\n        tid ths_ctx1\n        (VALID: URA.wf (global_th ths_ctx0 ths_usr ⋅ r_ctx))\n        (ADD: TIdSet.add_new tid ths_ctx0 ths_ctx1)\n        (NONE: ~ TIdSet.In tid ths_usr)\n    :\n    URA.wf (global_th ths_ctx1 ths_usr ⋅ local_th_context tid ⋅ r_ctx).\n  Proof.\n    unfold URA.wf, URA.add in *. unseal \"ra\". destruct r_ctx; ss.\n    rewrite ! union_empty in *. unfold union, NatMap.fold; ss. inv VALID. inv ADD. des_ifs.\n    - econs; ss.\n      + ii. des. eapply NatMapP.F.add_in_iff in H. des.\n        * subst. eauto.\n        * eapply DISJOINT. eauto.\n      + ii. eapply NatMapP.F.add_in_iff. rewrite union_comm in H. eapply NatMapP.F.add_in_iff in H. des; eauto.\n    - eapply NatMapP.F.not_find_in_iff in NEW. solve_andb.\n      + eapply disjoint_false_iff' in H. des.\n        eapply NatMapP.F.add_in_iff in H. rewrite NatMapP.F.empty_in_iff in H.\n        des; ss; subst. firstorder.\n      + unfold TIdSet.empty in H. solve_disjoint.\n  Qed.\n\n  Lemma global_th_alloc_user ths_ctx ths_usr0 r_ctx\n        tid ths_usr1\n        (VALID: URA.wf (global_th ths_ctx ths_usr0 ⋅ r_ctx))\n        (ADD: TIdSet.add_new tid ths_usr0 ths_usr1)\n        (NONE: ~ TIdSet.In tid ths_ctx)\n    :\n    URA.wf (global_th ths_ctx ths_usr1 ⋅ local_th_user tid ⋅ r_ctx).\n  Proof.\n    unfold URA.wf, URA.add in *. unseal \"ra\". destruct r_ctx; ss.\n    rewrite ! union_empty in *. unfold union, NatMap.fold; ss. inv VALID. inv ADD. des_ifs.\n    - econs; ss.\n      + ii. des. eapply NatMapP.F.add_in_iff in H0. des.\n        * subst. eauto.\n        * eapply DISJOINT. eauto.\n      + ii. eapply NatMapP.F.add_in_iff. rewrite union_comm in H. eapply NatMapP.F.add_in_iff in H. des; eauto.\n    - eapply NatMapP.F.not_find_in_iff in NEW.\n      eapply disjoint_false_iff' in Heq. des.\n      eapply NatMapP.F.add_in_iff in Heq. rewrite NatMapP.F.empty_in_iff in Heq.\n      des; ss; subst. firstorder.\n  Qed.\n\n  Lemma global_th_dealloc_context ths_ctx0 ths_usr r_ctx\n        tid ths_ctx1\n        (VALID: URA.wf (global_th ths_ctx0 ths_usr ⋅ local_th_context tid ⋅ r_ctx))\n        (REMOVE: TIdSet.remove tid ths_ctx0 = ths_ctx1)\n    :\n    URA.wf (global_th ths_ctx1 ths_usr ⋅ URA.unit ⋅ r_ctx).\n\n  Proof.\n    rewrite URA.unit_id. unfold URA.wf, URA.add in *. unseal \"ra\". destruct r_ctx; ss.\n    rewrite ! union_empty in *. unfold union, NatMap.fold in VALID; ss. des_ifs; inv VALID.\n    econs; ss.\n    - ii. des. eapply NatMapP.F.remove_in_iff in H; des. firstorder.\n    - unfold TIdSet.empty, TIdSet.add in *. solve_andb; solve_disjoint.\n      ii. eapply NatMapP.F.remove_in_iff. assert (tid = k \\/ tid <> k) by lia; des.\n      + subst. tauto.\n      + unfold KeySetLE in LE_CTX. rewrite union_comm in LE_CTX. setoid_rewrite NatMapP.F.add_in_iff in LE_CTX. eauto.\n  Qed.\n\n  Lemma global_th_dealloc_user ths_ctx ths_usr0 r_ctx\n        tid ths_usr1\n        (VALID: URA.wf (global_th ths_ctx ths_usr0 ⋅ local_th_user tid ⋅ r_ctx))\n        (REMOVE: TIdSet.remove tid ths_usr0 = ths_usr1)\n    :\n    URA.wf (global_th ths_ctx ths_usr1 ⋅ URA.unit ⋅ r_ctx).\n  Proof.\n    rewrite URA.unit_id. unfold URA.wf, URA.add in *. unseal \"ra\". destruct r_ctx; ss.\n    rewrite ! union_empty in *. unfold union, NatMap.fold in VALID; ss. des_ifs; inv VALID.\n    unfold TIdSet.empty, TIdSet.add in *. solve_disjoint.\n    unfold KeySetLE in LE_USR. rewrite union_comm in LE_USR. setoid_rewrite NatMapP.F.add_in_iff in LE_USR.\n    econs; ss.\n    - ii. des. eapply NatMapP.F.remove_in_iff in H1. firstorder.\n    - ii. rewrite NatMapP.F.remove_in_iff. split.\n      + ii. subst. tauto.\n      + firstorder.\n  Qed.\n\nEnd THREADS_RA.\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/src/simulation/AddWorld.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23724647464773652}}
{"text": "Require Import Rupicola.Lib.Api.\nRequire Import Rupicola.Lib.Conditionals.\n\nSection Gallina.\n  Definition cswap {T} (swap: bool) (a b: T) : T * T :=\n    if swap then (b, a) else (a, b).\nEnd Gallina.\n\nSection Compile.\n  Context {width: Z} {BW: Bitwidth width} {word: word.word width} {mem: map.map word Byte.byte}.\n  Context {locals: map.map String.string word}.\n  Context {env: map.map String.string (list String.string * list String.string * Syntax.cmd)}.\n  Context {ext_spec: bedrock2.Semantics.ExtSpec}.\n  Context {word_ok : word.ok word} {mem_ok : map.ok mem}.\n  Context {locals_ok : map.ok locals}.\n  Context {env_ok : map.ok env}.\n  Context {ext_spec_ok : Semantics.ext_spec.ok ext_spec}.\n\n  (* FIXME cswap should be compilable as-is; no need for a lemma. *)\n  (* There are two ways cswap could be compiled; you can either swap the local\n     variables (the pointers), or you can leave the pointers and copy over the\n     data. This version swaps the pointers without doing any copying. *)\n  Lemma compile_cswap_nocopy : forall {tr} {mem: mem} {locals: locals} {functions} (swap: bool) {A} (x y: A),\n    let v := cswap swap x y in\n    forall {P} {pred: P v -> predicate}\n      {k: nlet_eq_k P v} {k_impl}\n      R (Data : word -> A -> _ -> Prop)\n      swap_var x_var x_ptr y_var y_ptr tmp,\n\n      map.get locals swap_var = Some (word.of_Z (Z.b2z swap)) ->\n      map.get locals x_var = Some x_ptr ->\n      map.get locals y_var = Some y_ptr ->\n\n      (* tmp is a strictly temporary variable, confined to one part of the\n         if-clause; it gets unset after use *)\n      map.get locals tmp = None ->\n      (Data x_ptr x * Data y_ptr y * R)%sep mem ->\n\n      (let v := v in\n       <{ Trace := tr;\n          Memory := mem;\n          Locals := map.put (map.put locals x_var (fst (cswap swap x_ptr y_ptr))) y_var\n                      (snd (cswap swap x_ptr y_ptr));\n          Functions := functions }>\n       k_impl\n       <{ pred (k v eq_refl) }>) ->\n      <{ Trace := tr;\n         Memory := mem;\n         Locals := locals;\n         Functions := functions }>\n      cmd.seq\n        (cmd.cond\n           (expr.var swap_var)\n           (cmd.seq\n              (cmd.seq\n                 (cmd.seq\n                    (cmd.set tmp (expr.var x_var))\n                    (cmd.set x_var (expr.var y_var)))\n                 (cmd.set y_var (expr.var tmp)))\n              (cmd.unset tmp))\n           (cmd.skip))\n        k_impl\n      <{ pred (nlet_eq [x_var; y_var] v k) }>.\n  Proof.\n    intros; subst v; unfold cswap.\n    simple eapply compile_if with\n        (val_pred := fun _ tr' mem' locals' =>\n                      tr' = tr /\\\n                      mem' = mem0 /\\\n                      locals' =\n                      let locals := map.put locals0 x_var (if swap then y_ptr else x_ptr) in\n                      let locals := map.put locals y_var (if swap then x_ptr else y_ptr) in\n                      locals);\n      repeat compile_step;\n      repeat straightline'; subst_lets_in_goal; cbn; ssplit; eauto.\n    - rewrite !map.remove_put_diff, !map.remove_put_same, map.remove_not_in by congruence.\n      reflexivity.\n    - rewrite (map.put_noop x_var x_ptr), map.put_noop by assumption.\n      reflexivity.\n    - cbv beta in *; repeat compile_step; cbn.\n      destruct swap; eassumption.\n  Qed.\n\n  Lemma compile_cswap_pair : forall {tr mem locals functions} (swap: bool) {A} (x y: A * A),\n    let v := cswap swap x y in\n    forall {T} {pred: T -> predicate}\n      {k: (A * A) * (A * A) -> T} {k_impl},\n      (let __ := 0 in (* placeholder FIXME why? *)\n       <{ Trace := tr;\n          Memory := mem;\n          Locals := locals;\n          Functions := functions }>\n       k_impl\n       <{ pred (dlet (cswap swap (fst x) (fst y))\n                     (fun xy1 =>\n                        dlet (cswap swap (snd x) (snd y))\n                             (fun xy2 =>\n                                let x := (fst xy1, fst xy2) in\n                                let y := (snd xy1, snd xy2) in\n                                k (x, y)))) }>) ->\n      <{ Trace := tr;\n         Memory := mem;\n         Locals := locals;\n         Functions := functions }>\n      k_impl\n      <{ pred (dlet v k) }>.\n  Proof.\n    repeat straightline'.\n    subst_lets_in_goal. destruct_products.\n    destruct swap; cbv [cswap dlet] in *; cbn [fst snd] in *.\n    all:eauto.\n  Qed.\nEnd Compile.\n\nSection Helpers.\n  Context {width: Z} {BW: Bitwidth width} {word: word.word width} {mem: map.map word Byte.byte}.\n  Context {locals: map.map String.string word}.\n  Context {env: map.map String.string (list String.string * list String.string * Syntax.cmd)}.\n  Context {ext_spec: bedrock2.Semantics.ExtSpec}.\n  Context {word_ok : word.ok word} {mem_ok : map.ok mem}.\n  Context {locals_ok : map.ok locals}.\n  Context {env_ok : map.ok env}.\n  Context {ext_spec_ok : Semantics.ext_spec.ok ext_spec}.\n\n  Lemma cswap_iff1\n        {T} (pred : word ->T -> mem -> Prop) s pa pb a b :\n    Lift1Prop.iff1\n      ((pred (fst (cswap s pa pb)) (fst (cswap s a b)))\n       * pred (snd (cswap s pa pb))\n              (snd (cswap s a b)))%sep\n      (pred pa a * pred pb b)%sep.\n  Proof. destruct s; cbn [cswap fst snd]; ecancel. Qed.\n\n  Lemma map_get_cswap_fst\n        {key value} {map : map.map key value}\n        (m : map.rep (map:=map)) s ka kb a b :\n    map.get m ka = Some a ->\n    map.get m kb = Some b ->\n    map.get m (fst (cswap s ka kb)) = Some (fst (cswap s a b)).\n  Proof. destruct s; cbn [cswap fst fst]; auto. Qed.\n\n  Lemma map_get_cswap_snd\n        {key value} {map : map.map key value}\n        (m : map.rep (map:=map)) s ka kb a b :\n    map.get m ka = Some a ->\n    map.get m kb = Some b ->\n    map.get m (snd (cswap s ka kb)) = Some (snd (cswap s a b)).\n  Proof. destruct s; cbn [cswap fst snd]; auto. Qed.\n\n  Lemma cswap_cases_fst {T} (P : T -> Prop) s a b :\n    P a -> P b -> P (fst (cswap s a b)).\n  Proof. destruct s; cbn [cswap fst snd]; auto. Qed.\n\n  Lemma cswap_cases_snd {T} (P : T -> Prop) s a b :\n    P a -> P b -> P (snd (cswap s a b)).\n  Proof. destruct s; cbn [cswap fst snd]; auto. Qed.\n\n  Lemma cswap_pair {A B} b (x y : A * B) :\n    cswap b x y =\n    (fst (cswap b (fst x) (fst y)), fst (cswap b (snd x) (snd y)),\n     (snd (cswap b (fst x) (fst y)), snd (cswap b (snd x) (snd y)))).\n  Proof. destruct b; destruct_products; reflexivity. Qed.\nEnd Helpers.\n", "meta": {"author": "mit-plv", "repo": "rupicola", "sha": "3f59b3d2404ce425ddf4fd55ad2314996a573dc3", "save_path": "github-repos/coq/mit-plv-rupicola", "path": "github-repos/coq/mit-plv-rupicola/rupicola-3f59b3d2404ce425ddf4fd55ad2314996a573dc3/src/Rupicola/Lib/ControlFlow/CondSwap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23724647464773652}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Bool.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import ZArith NArith Nnat Ndec Ndigits.\nFrom IntMap Require Import Allmaps.\nRequire Import Wf_nat.\n\nRequire Import BDDvar_ad_nat.\nRequire Import bdd1.\nRequire Import bdd2.\nRequire Import bdd3.\nRequire Import bdd4.\nRequire Import bdd5_1.\n\nLemma BDDneg_memo_OK_1_lemma_2_1' :\n forall (cfg : BDDconfig) (memo : BDDneg_memo),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg memo ->\n BDDneg_memo_OK_2 cfg (BDDneg_memo_put memo BDDzero BDDone).\nProof.\n  intro cfg.  elim cfg; clear cfg; intros bs y; elim y; clear y; intros share counter.\n  intros memo H H0.  unfold BDDneg_memo_OK_2 in |- *.  intros node node' bound H1 H2.  unfold BDDneg_memo_put, BDDneg_memo_lookup in H1.\n  rewrite (MapPut_semantics ad memo BDDzero BDDone node) in H1.  elim (sumbool_of_bool (Neqb BDDzero node)).\n  intro y.  cut (BDDzero = node).  intro H3.  rewrite y in H1.  injection H1.  intros H4.\n  rewrite <- H3.  rewrite <- H4.  split.  left; reflexivity.  elim bound.\n  simpl in |- *.  elim H.  intros H5 H6.  elim H5; intros.  rewrite H7.  reflexivity.  \n  intros n H5.  simpl in |- *.  elim H.  intros H6 H7.  elim H6; intros.  simpl in H9.  rewrite H8.\n  reflexivity.  apply Neqb_complete.  assumption.  intro y.  rewrite y in H1.\n  unfold BDDneg_memo_OK_2 in H0.  apply H0.  assumption.  assumption.\nQed.\n\nLemma BDDneg_memo_OK_1_lemma_3_1' :\n forall (cfg : BDDconfig) (memo : BDDneg_memo),\n BDDconfig_OK cfg ->\n BDDneg_memo_OK_2 cfg memo ->\n BDDneg_memo_OK_2 cfg (BDDneg_memo_put memo BDDone BDDzero).\nProof.\n  intro cfg.  elim cfg; clear cfg; intros bs y; elim y; clear y; intros share counter.\n  intros memo H H0.  unfold BDDneg_memo_OK_2 in |- *.  intros node node' bound H1 H2.  unfold BDDneg_memo_put, BDDneg_memo_lookup in H1.\n  rewrite (MapPut_semantics ad memo BDDone BDDzero node) in H1.  elim (sumbool_of_bool (Neqb BDDone node)).\n  intro y.  cut (BDDone = node).  intro H3.  rewrite y in H1.  injection H1.  intros H4.\n  rewrite <- H3.  rewrite <- H4.  split.  right; left; reflexivity.  elim bound.\n  simpl in |- *.  elim H.  intros H5 H6.  elim H5; intros.  rewrite (proj1 H8).  reflexivity.\n  intros n H5.  simpl in |- *.  elim H.  intros H6 H7.  elim H6; intros.  rewrite (proj1 H9).\n  reflexivity.  apply Neqb_complete.  assumption.  intro y.  rewrite y in H1.  unfold BDDneg_memo_OK_2 in H0.\n  apply H0.  assumption.  assumption.\nQed.\n\nLemma BDDneg_memo_OK_1_lemma_1_2' :\n forall (cfg : BDDconfig) (x : BDDvar) (l r node : ad) \n   (n m : nat) (memo : BDDneg_memo),\n BDDconfig_OK cfg ->\n MapGet _ (fst cfg) node = Some (x, (l, r)) ->\n nat_of_N (var cfg node) < n ->\n n = S m ->\n BDDneg_memo_OK_2 (fst (BDDneg_2 (fst (BDDneg_2 cfg l m)) r m)) memo ->\n BDDneg_memo_OK_2 (fst (BDDneg_2 cfg node n))\n   (BDDneg_memo_put memo node (snd (BDDneg_2 cfg node n))).\nProof.\n  intro cfg.  elim cfg; clear cfg; intros bs y; elim y; clear y; intros share counter.\n  intros x l r node n m memo H H0 H1.  intro H3.  intros H2.  unfold BDDneg_memo_OK_2 in |- *.\n  intros node0 node' bound H4 H5.  unfold BDDneg_memo_put, BDDneg_memo_lookup in H4.  rewrite\n   (MapPut_semantics ad memo node\n      (snd (BDDneg_2 (bs, (share, counter)) node n)) node0)\n    in H4.\n  elim (sumbool_of_bool (Neqb node node0)).  intro y.  rewrite y in H4.  injection H4; intros.\n  cut (node = node0).  intro H7.  rewrite <- H7.  rewrite <- H7 in H5.  split.\n  apply nodes_preserved_2 with (cfg := (bs, (share, counter))).  right; right.  unfold in_dom in |- *.\n  rewrite H0.  reflexivity.  unfold nodes_preserved in |- *.  cut (config_node_OK (bs, (share, counter)) node).\n  cut\n   (is_internal_node (bs, (share, counter)) node ->\n    nat_of_N (var (bs, (share, counter)) node) < n).\n  intros H8 H9.  exact\n   (proj1 (proj2 (BDDneg_2_lemma n (bs, (share, counter)) node H H9 H8))).\n  intro; assumption.  right; right.  unfold in_dom in |- *.  rewrite H0; reflexivity.\n  apply BDDneg_memo_OK_1_lemma_1_1_1.  cut (config_node_OK (bs, (share, counter)) node).\n  intro H8.  cut\n   (is_internal_node (bs, (share, counter)) node ->\n    nat_of_N (var (bs, (share, counter)) node) < n).\n  intros H9.  exact (proj1 (BDDneg_2_lemma n (bs, (share, counter)) node H H8 H9)).\n  intro H9.  assumption.  right.  right.  unfold in_dom in |- *.  rewrite H0.  reflexivity.\n  apply nodes_preserved_2 with (cfg := (bs, (share, counter))).  right; right.  unfold in_dom in |- *.\n  rewrite H0.  reflexivity.  unfold nodes_preserved in |- *.  cut (config_node_OK (bs, (share, counter)) node).\n  cut\n   (is_internal_node (bs, (share, counter)) node ->\n    nat_of_N (var (bs, (share, counter)) node) < n).\n  intros H8 H9.  exact\n   (proj1 (proj2 (BDDneg_2_lemma n (bs, (share, counter)) node H H9 H8))).\n  intro; assumption.  right; right.  unfold in_dom in |- *.  rewrite H0; reflexivity.\n  rewrite <- H6.  cut (config_node_OK (bs, (share, counter)) node).  intro H8.\n  cut\n   (is_internal_node (bs, (share, counter)) node ->\n    nat_of_N (var (bs, (share, counter)) node) < n).\n  intros H9.  exact\n   (proj1\n      (proj2\n         (proj2\n            (proj2 (BDDneg_2_lemma n (bs, (share, counter)) node H H8 H9))))).  \n  intro; assumption.  right; right.  unfold in_dom in |- *.  rewrite H0; reflexivity.\n  assumption.  rewrite <- H6.  cut (config_node_OK (bs, (share, counter)) node).\n  intro H8.  cut\n   (is_internal_node (bs, (share, counter)) node ->\n    nat_of_N (var (bs, (share, counter)) node) < n).\n  intro H9.  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_neg (bool_fun_of_BDD (bs, (share, counter)) node)).\n  exact\n   (proj2\n      (proj2\n         (proj2\n            (proj2 (BDDneg_2_lemma n (bs, (share, counter)) node H H8 H9))))).\n  apply bool_fun_eq_neg_1.  apply bool_fun_eq_symm.  apply bool_fun_preservation.\n  assumption.  exact (proj1 (BDDneg_2_lemma n (bs, (share, counter)) node H H8 H9)).\n  exact\n   (proj1 (proj2 (BDDneg_2_lemma n (bs, (share, counter)) node H H8 H9))).\n  assumption.  intro; assumption.  right; right.  unfold in_dom in |- *.  rewrite H0.\n  reflexivity.  apply Neqb_complete.  assumption.  intro y.  rewrite y in H4.\n  unfold BDDneg_memo_OK_2 in H2.  split.  apply\n   nodes_preserved_2\n    with\n      (cfg := fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m)).\n  cut\n   (is_internal_node\n      (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m)) node0 ->\n    nat_of_N\n      (var (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n         node0) <\n    S\n      (nat_of_N\n         (var\n            (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n            node0))).\n  intro H6.  exact\n   (proj1\n      (H2 node0 node'\n         (S\n            (nat_of_N\n               (var\n                  (fst\n                     (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r\n                        m)) node0))) H4 H6)).\n  intro H6.  unfold lt in |- *.  apply le_n.  apply nodes_preserved_1 with (n := n) (x := x).\n  assumption.  assumption.  assumption.  assumption.  apply BDDneg_memo_OK_1_lemma_1_1_1.\n  cut (config_node_OK (bs, (share, counter)) node).  intro H6.  cut\n   (is_internal_node (bs, (share, counter)) node ->\n    nat_of_N (var (bs, (share, counter)) node) < n).\n  intro H7.  exact (proj1 (BDDneg_2_lemma n (bs, (share, counter)) node H H6 H7)).\n  intro H7.  assumption.  right.  right.  unfold in_dom in |- *.  rewrite H0.  reflexivity.\n  apply\n   nodes_preserved_2\n    with\n      (cfg := fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m)).\n  cut\n   (is_internal_node\n      (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m)) node0 ->\n    nat_of_N\n      (var (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n         node0) <\n    S\n      (nat_of_N\n         (var\n            (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n            node0))).\n  intro H6.  exact\n   (proj1\n      (H2 node0 node'\n         (S\n            (nat_of_N\n               (var\n                  (fst\n                     (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r\n                        m)) node0))) H4 H6)).\n  intro H6.  unfold lt in |- *.  apply le_n.  apply nodes_preserved_1 with (n := n) (x := x).  assumption.\n  assumption.  assumption.  assumption.  cut\n   (config_node_OK\n      (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m)) node').\n  intro H6.  cut\n   (nodes_preserved\n      (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n      (fst (BDDneg_2 (bs, (share, counter)) node n))).\n  intro H7.  apply\n   nodes_preserved_2\n    with\n      (cfg := fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m)).\n  assumption.  assumption.  apply nodes_preserved_1 with (x := x).  assumption.  \n  assumption.  assumption.  assumption.  apply BDDneg_memo_OK_lemma_1_4' with (memo := memo) (node := node0).\n  apply BDDneg_2_config_OK_lemma_2 with (n := n) (x := x) (node := node).  assumption.  assumption.\n  assumption.  assumption.  assumption.  cut\n   (is_internal_node\n      (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m)) node0 ->\n    nat_of_N\n      (var (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n         node0) <\n    S\n      (nat_of_N\n         (var\n            (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n            node0))).\n  intro H6.  exact\n   (proj1\n      (H2 node0 node'\n         (S\n            (nat_of_N\n               (var\n                  (fst\n                     (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r\n                        m)) node0))) H4 H6)).\n  intro H6.  unfold lt in |- *.  apply le_n.  assumption.  assumption.  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_of_BDD\n                (fst\n                   (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n                node').\n  apply bool_fun_preservation.  apply BDDneg_2_config_OK_lemma_2 with (node := node) (x := x) (n := n).\n  assumption.  assumption.  assumption.  assumption.  cut (config_node_OK (bs, (share, counter)) node).\n  intro H6.  cut\n   (is_internal_node (bs, (share, counter)) node ->\n    nat_of_N (var (bs, (share, counter)) node) < n).\n  intro H7.  exact (proj1 (BDDneg_2_lemma n (bs, (share, counter)) node H H6 H7)).  \n  intro; assumption.  right; right.  unfold in_dom in |- *.  rewrite H0.  reflexivity.\n  cut\n   (nodes_preserved\n      (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n      (fst (BDDneg_2 (bs, (share, counter)) node n))).\n  unfold nodes_preserved in |- *.  intro H6.  assumption.  apply nodes_preserved_1 with (x := x).\n  assumption.  assumption.  assumption.  assumption.  apply BDDneg_memo_OK_lemma_1_4' with (memo := memo) (node := node0).\n  apply BDDneg_2_config_OK_lemma_2 with (node := node) (x := x) (n := n).  assumption.  assumption.\n  assumption.  assumption.  assumption.  cut\n   (is_internal_node\n      (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m)) node0 ->\n    nat_of_N\n      (var (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n         node0) <\n    S\n      (nat_of_N\n         (var\n            (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n            node0))).\n  intro H6.  exact\n   (proj1\n      (H2 node0 node'\n         (S\n            (nat_of_N\n               (var\n                  (fst\n                     (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r\n                        m)) node0))) H4 H6)).\n  intro H6.  unfold lt in |- *.  apply le_n.  assumption.  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_neg\n                (bool_fun_of_BDD\n                   (fst\n                      (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r\n                         m)) node0)).\n  apply BDDneg_memo_OK_bool_fun_1' with (memo := memo).  apply BDDneg_2_config_OK_lemma_2 with (node := node) (x := x) (n := n).\n  assumption.  assumption.  assumption.  assumption.  assumption.  cut\n   (is_internal_node\n      (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m)) node0 ->\n    nat_of_N\n      (var (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n         node0) <\n    S\n      (nat_of_N\n         (var\n            (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n            node0))).\n  intro H6.  exact\n   (proj1\n      (H2 node0 node'\n         (S\n            (nat_of_N\n               (var\n                  (fst\n                     (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r\n                        m)) node0))) H4 H6)).\n  intro H6.  unfold lt in |- *.  apply le_n.  assumption.  apply bool_fun_eq_neg_1.  apply bool_fun_eq_symm.\n  apply bool_fun_preservation.  apply BDDneg_2_config_OK_lemma_2 with (n := n) (x := x) (node := node).\n  assumption.  assumption.  assumption.  assumption.  cut (config_node_OK (bs, (share, counter)) node).\n  intro H6.  cut\n   (is_internal_node (bs, (share, counter)) node ->\n    nat_of_N (var (bs, (share, counter)) node) < n).\n  intro H7.  exact (proj1 (BDDneg_2_lemma n (bs, (share, counter)) node H H6 H7)).\n  intro; assumption.  right; right.  unfold in_dom in |- *.  rewrite H0.  reflexivity.\n  cut\n   (nodes_preserved\n      (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n      (fst (BDDneg_2 (bs, (share, counter)) node n))).\n  unfold nodes_preserved in |- *.  intro H6.  assumption.  apply nodes_preserved_1 with (x := x).\n  assumption.  assumption.  assumption.  assumption.  cut\n   (is_internal_node\n      (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m)) node0 ->\n    nat_of_N\n      (var (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n         node0) <\n    S\n      (nat_of_N\n         (var\n            (fst (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r m))\n            node0))).\n  intro H6.  exact\n   (proj1\n      (H2 node0 node'\n         (S\n            (nat_of_N\n               (var\n                  (fst\n                     (BDDneg_2 (fst (BDDneg_2 (bs, (share, counter)) l m)) r\n                        m)) node0))) H4 H6)).\n  intro H6.  unfold lt in |- *.  apply le_n.\nQed.\n\nLemma BDDneg_1_lemma' :\n forall (bound : nat) (arg : BDDconfig * ad * BDDneg_memo),\n BDDconfig_OK (fst (fst arg)) ->\n config_node_OK (fst (fst arg)) (snd (fst arg)) ->\n BDDneg_memo_OK_2 (fst (fst arg)) (snd arg) ->\n (is_internal_node (fst (fst arg)) (snd (fst arg)) ->\n  nat_of_N (var (fst (fst arg)) (snd (fst arg))) < bound) ->\n fst (BDDneg_1 arg bound) = BDDneg_2 (fst (fst arg)) (snd (fst arg)) bound /\\\n BDDneg_memo_OK_2 (fst (fst (BDDneg_1 arg bound))) (snd (BDDneg_1 arg bound)).\nProof.\n  intro bound.  apply\n   lt_wf_ind\n    with\n      (P := fun bound : nat =>\n            forall arg : BDDconfig * ad * BDDneg_memo,\n            BDDconfig_OK (fst (fst arg)) ->\n            config_node_OK (fst (fst arg)) (snd (fst arg)) ->\n            BDDneg_memo_OK_2 (fst (fst arg)) (snd arg) ->\n            (is_internal_node (fst (fst arg)) (snd (fst arg)) ->\n             nat_of_N (var (fst (fst arg)) (snd (fst arg))) < bound) ->\n            fst (BDDneg_1 arg bound) =\n            BDDneg_2 (fst (fst arg)) (snd (fst arg)) bound /\\\n            BDDneg_memo_OK_2 (fst (fst (BDDneg_1 arg bound)))\n              (snd (BDDneg_1 arg bound))).\n  intros n H arg.  elim arg; clear arg; intro y.  elim y; clear y.  intros cfg node memo.\n  intros H0 H1 H2 H3.  elim\n   (option_sum _\n      (BDDneg_memo_lookup (snd (cfg, node, memo))\n         (snd (fst (cfg, node, memo))))).\n  intro y.  elim y; clear y; intros node' H4.  rewrite (BDDneg_1_lemma_1 (cfg, node, memo) node' n H4).\n  simpl in |- *.  split.  simpl in H2.  unfold BDDneg_memo_OK_2 in H2.  rewrite (proj2 (H2 node node' n H4 H3)).\n  reflexivity.  assumption.  intro y.  elim\n   (option_sum _\n      (MapGet _ (fst (fst (fst (cfg, node, memo))))\n         (snd (fst (cfg, node, memo))))).\n  intro y0.  elim y0; clear y0.  intro x.  elim x; clear x.  intros x y0.  elim y0; clear y0; intros l r H4.\n  elim (nat_sum n).  intros y0.  elim y0; clear y0.  intros m H5.  rewrite (BDDneg_1_lemma_4 (cfg, node, memo) x l r n m H5 y H4).\n\n\n\n\n\n  simpl in |- *.  cut\n   (fst (BDDneg_1 (cfg, l, memo) m) =\n    BDDneg_2 (fst (fst (cfg, l, memo))) (snd (fst (cfg, l, memo))) m /\\\n    BDDneg_memo_OK_2 (fst (fst (BDDneg_1 (cfg, l, memo) m)))\n      (snd (BDDneg_1 (cfg, l, memo) m))).\n  intro H6.  cut\n   (fst\n      (BDDneg_1\n         (fst\n            (fst\n               (BDDneg_1\n                  (fst (fst (cfg, node, memo)), l, snd (cfg, node, memo)) m)),\n         r,\n         snd\n           (BDDneg_1 (fst (fst (cfg, node, memo)), l, snd (cfg, node, memo))\n              m)) m) =\n    BDDneg_2\n      (fst\n         (fst\n            (fst\n               (fst\n                  (BDDneg_1\n                     (fst (fst (cfg, node, memo)), l, snd (cfg, node, memo))\n                     m)), r,\n            snd\n              (BDDneg_1\n                 (fst (fst (cfg, node, memo)), l, snd (cfg, node, memo)) m))))\n      (snd\n         (fst\n            (fst\n               (fst\n                  (BDDneg_1\n                     (fst (fst (cfg, node, memo)), l, snd (cfg, node, memo))\n                     m)), r,\n            snd\n              (BDDneg_1\n                 (fst (fst (cfg, node, memo)), l, snd (cfg, node, memo)) m))))\n      m /\\\n    BDDneg_memo_OK_2\n      (fst\n         (fst\n            (BDDneg_1\n               (fst\n                  (fst\n                     (BDDneg_1\n                        (fst (fst (cfg, node, memo)), l,\n                        snd (cfg, node, memo)) m)), r,\n               snd\n                 (BDDneg_1\n                    (fst (fst (cfg, node, memo)), l, snd (cfg, node, memo)) m))\n               m)))\n      (snd\n         (BDDneg_1\n            (fst\n               (fst\n                  (BDDneg_1\n                     (fst (fst (cfg, node, memo)), l, snd (cfg, node, memo))\n                     m)), r,\n            snd\n              (BDDneg_1\n                 (fst (fst (cfg, node, memo)), l, snd (cfg, node, memo)) m))\n            m))).  intro H7.  simpl in H6, H7. \n  rewrite (proj1 H7).  rewrite (proj1 H6).  cut\n   (BDDmake (fst (BDDneg_2 (fst (BDDneg_2 cfg l m)) r m)) x\n      (snd (BDDneg_2 cfg l m)) (snd (BDDneg_2 (fst (BDDneg_2 cfg l m)) r m)) =\n    BDDneg_2 cfg node n).\n\n  intro H8.  split.  assumption.  rewrite (proj1 H6) in H7.\n  elim H7; intros. rewrite H9 in H7. clear H9 H10. (* instead of Rewrite (proj1 ? ? H7) in H7. which does not work in 6.3. *)\n  rewrite H8.  apply BDDneg_memo_OK_1_lemma_1_2' with (x := x) (l := l) (r := r) (m := m).  assumption.\n  assumption.  apply H3.  split with x; split with l; split with r; assumption.\n  assumption.  exact (proj2 H7).  rewrite H5.  simpl in |- *.  simpl in H4.  rewrite H4.\n  reflexivity.  apply H.  rewrite H5.  unfold lt in |- *.  apply le_n.  simpl in |- *.  rewrite (proj1 H6).\n  simpl in |- *.  cut (config_node_OK cfg l).  intro.  cut (is_internal_node cfg l -> nat_of_N (var cfg l) < m).\n  intros H8.  exact (proj1 (BDDneg_2_lemma m cfg l H0 H7 H8)).  intro H8.  apply lt_trans_1 with (y := nat_of_N (var cfg node)).\n  cut (l = low cfg node).  intro H9.  rewrite H9.  apply BDDcompare_lt.  apply BDDvar_ordered_low.\n\n\n\n\n\n  assumption.  split with x; split with l; split with r.  assumption.  rewrite <- H9; assumption.\n  unfold low in |- *.  simpl in H4.  rewrite H4.  reflexivity.  rewrite <- H5.  apply H3.\n  simpl in |- *.  split with x; split with l; split with r; assumption.  cut (l = low cfg node); intros.\n  rewrite H7.  apply low_OK.  assumption.  split with x; split with l; split with r; assumption.\n  unfold low in |- *; simpl in H4; rewrite H4; reflexivity.  simpl in |- *.  rewrite (proj1 H6).\n  simpl in |- *.  cut (config_node_OK cfg l).  intro H7.  cut (is_internal_node cfg l -> nat_of_N (var cfg l) < m).\n  intro H8.  cut (config_node_OK cfg r).  intro H9.  elim H9; intro.  rewrite H10.\n  left; reflexivity.  elim H10; intro.  rewrite H11; right; left; reflexivity.\n  right; right.  unfold in_dom in |- *.  cut (is_internal_node cfg r).  intro H12.  inversion H12.\n  inversion H13.  inversion H14.  simpl in H0.  simpl in |- *.  cut\n   (MapGet (BDDvar * (ad * ad)) (fst (fst (BDDneg_2 cfg l m))) r =\n    Some (x0, (x1, x2))).\n  intro H16.  rewrite H16.  reflexivity.  exact (proj1 (proj2 (BDDneg_2_lemma m cfg l H0 H7 H8)) x0 x1 x2 r H15).\n  apply in_dom_is_internal.  assumption.  cut (r = high cfg node).  intro H9.  rewrite H9.\n  apply high_OK.  assumption.  split with x; split with l; split with r; assumption.  \n  unfold high in |- *.  simpl in H4; rewrite H4; reflexivity.  intro H8.  apply lt_trans_1 with (y := nat_of_N (var cfg node)).\n  apply BDDcompare_lt.  cut (l = low cfg node).  intro; rewrite H9.  apply BDDvar_ordered_low.\n  assumption.  split with x; split with l; split with r; assumption.  rewrite <- H9; assumption.\n  unfold low in |- *; simpl in H4; rewrite H4; reflexivity.  rewrite <- H5; apply H3.\n  simpl in |- *.  split with x; split with l; split with r; assumption.  cut (l = low cfg node).\n  intro H7.  rewrite H7.  apply low_OK.  assumption.  split with x; split with l; split with r; assumption.\n  unfold low in |- *; simpl in H4; rewrite H4; reflexivity.  simpl in |- *.  exact (proj2 H6).\n\n\n\n\n\n  simpl in |- *.  rewrite (proj1 H6).  simpl in |- *.  intro H7.  cut (var (fst (BDDneg_2 cfg l m)) r = var cfg r).\n  intro H8.  rewrite H8.  apply lt_trans_1 with (y := nat_of_N (var cfg node)).  apply BDDcompare_lt.\n  cut (r = high cfg node).  intro H9.  rewrite H9.  apply BDDvar_ordered_high.  assumption.\n  split with x; split with l; split with r; assumption.  cut (config_node_OK cfg (high cfg node)).\n  intro H10.  elim H10; intro.  inversion H7.  inversion H12.  inversion H13.\n  rewrite H9 in H14; rewrite H11 in H14.  cut (BDDconfig_OK (fst (BDDneg_2 cfg l m))).\n  intro H15.  rewrite (config_OK_zero (fst (BDDneg_2 cfg l m)) H15) in H14.  discriminate H14.\n  cut (config_node_OK cfg l).  intro H15.  cut (is_internal_node cfg l -> nat_of_N (var cfg l) < m).\n  intro H16.  exact (proj1 (BDDneg_2_lemma m cfg l H0 H15 H16)).  intro H16.  apply lt_trans_1 with (y := nat_of_N (var cfg node)).\n  cut (l = low cfg node).  intro H17.  rewrite H17.  apply BDDcompare_lt.  apply BDDvar_ordered_low.\n  assumption.  split with x; split with l; split with r; assumption.  rewrite <- H17; assumption.\n  unfold low in |- *; simpl in H4; rewrite H4.  reflexivity.  rewrite <- H5; apply H3.\n  simpl in |- *.  split with x; split with l; split with r; assumption.  cut (l = low cfg node).\n  intro H15.  rewrite H15.  apply low_OK.  assumption.  split with x; split with l; split with r; assumption.\n  unfold low in |- *; simpl in H4; rewrite H4; reflexivity.  elim H11; intro.  rewrite H9 in H7.\n  rewrite H12 in H7.  inversion H7.  inversion H13.  inversion H14.  cut (BDDconfig_OK (fst (BDDneg_2 cfg l m))).\n  intro H16.  rewrite (config_OK_one (fst (BDDneg_2 cfg l m)) H16) in H15.  discriminate H15.\n  cut (config_node_OK cfg l).  intro H16.  cut (is_internal_node cfg l -> nat_of_N (var cfg l) < m).\n\n\n\n\n\n  intros H17.  exact (proj1 (BDDneg_2_lemma m cfg l H0 H16 H17)).  intro H17.\n  apply lt_trans_1 with (y := nat_of_N (var cfg node)).  cut (l = low cfg node).  \n  intro H18.  rewrite H18.  apply BDDcompare_lt.  apply BDDvar_ordered_low.  assumption.\n  split with x; split with l; split with r.  assumption.  rewrite <- H18; assumption.\n  unfold low in |- *.  simpl in H4.  rewrite H4.  reflexivity.  rewrite <- H5.  apply H3.\n  simpl in |- *.  split with x; split with l; split with r; assumption.  cut (l = low cfg node); intros.\n  rewrite H16.  apply low_OK.  assumption.  split with x; split with l; split with r; assumption.\n  unfold low in |- *; simpl in H4; rewrite H4; reflexivity.  apply in_dom_is_internal.\n  assumption.  apply high_OK.  assumption.  split with x; split with l; split with r; assumption.\n  unfold high in |- *.  simpl in H4; rewrite H4; reflexivity.  rewrite <- H5; apply H3.\n  simpl in |- *.  split with x; split with l; split with r; assumption.  inversion H7.\n  inversion H8.  inversion H9.  unfold var in |- *.  rewrite H10.  cut (l = low cfg node).\n  cut (r = high cfg node).  intros H11 H12.  cut (config_node_OK cfg l).  cut (config_node_OK cfg r).\n  intros H13 H14.  cut (BDDconfig_OK (fst (BDDneg_2 cfg l m))).  intro H15.  elim H13; intro.\n\n\n\n\n\n\n\n  rewrite H16 in H10.  rewrite (config_OK_zero (fst (BDDneg_2 cfg l m)) H15) in H10; discriminate.\n  elim H16; intro.  rewrite H17 in H10.  rewrite (config_OK_one (fst (BDDneg_2 cfg l m)) H15) in H10; discriminate.\n  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) (fst cfg) r)).  intro y0.  elim y0; intro x3.\n  elim x3; intro y1; intro y2.  elim y2; intros y3 y4 y5.  rewrite y5.  cut (is_internal_node cfg l -> nat_of_N (var cfg l) < m).\n  intro H18.  cut\n   (MapGet (BDDvar * (ad * ad)) (fst (fst (BDDneg_2 cfg l m))) r =\n    Some (y1, (y3, y4))).\n  intro H19.  rewrite H19 in H10.  injection H10.  intros H20 H21 H22.  rewrite H22; reflexivity.\n  exact (proj1 (proj2 (BDDneg_2_lemma m cfg l H0 H14 H18)) y1 y3 y4 r y5).\n  intro H18.  apply lt_trans_1 with (y := nat_of_N (var cfg node)).  apply BDDcompare_lt.\n  rewrite H12.  apply BDDvar_ordered_low.  assumption.  split with x; split with l; split with r; assumption.\n  rewrite <- H12.  assumption.  rewrite <- H5.  apply H3.  simpl in |- *.  split with x; split with l; split with r; assumption.\n  intro y0.  unfold in_dom in H17.  rewrite y0 in H17.  discriminate.  cut (is_internal_node cfg l -> nat_of_N (var cfg l) < m).\n  intro H15.  exact (proj1 (BDDneg_2_lemma m cfg l H0 H14 H15)).  intro H15.  apply lt_trans_1 with (y := nat_of_N (var cfg node)).\n\n\n\n\n\n\n  apply BDDcompare_lt.  rewrite H12.  apply BDDvar_ordered_low.  assumption.  \n split with x; split with l; split with r; assumption.  rewrite <- H12; assumption.\n  rewrite <- H5; apply H3.  simpl in |- *.  split with x; split with l; split with r; assumption.\n  rewrite H11.  apply high_OK.  assumption.  split with x; split with l; split with r; assumption.\n  rewrite H12.  apply low_OK.  assumption.  split with x; split with l; split with r; assumption.\n  unfold high in |- *; simpl in H4; rewrite H4; reflexivity.  unfold low in |- *; simpl in H4; rewrite H4; reflexivity.  \n  apply H.  rewrite H5.  unfold lt in |- *.  apply le_n.  simpl in |- *.  assumption.  simpl in |- *.\n  cut (l = low cfg node).  intro; rewrite H6.  apply low_OK.  assumption.  \n  split with x; split with l; split with r; assumption.  unfold low in |- *; simpl in H4; rewrite H4; reflexivity.\n  simpl in |- *.  assumption.  simpl in |- *.  intro H6.  apply lt_trans_1 with (y := nat_of_N (var cfg node)).\n  apply BDDcompare_lt.  cut (l = low cfg node).  intro H7.  rewrite H7.  apply BDDvar_ordered_low.\n  assumption.  split with x; split with l; split with r; assumption.  rewrite <- H7; assumption.\n  unfold low in |- *; simpl in H4; rewrite H4; reflexivity.  rewrite <- H5; apply H3.\n  simpl in |- *.  split with x; split with l; split with r; assumption.  intro y0.  rewrite y0.\n  rewrite (BDDneg_1_lemma_3 (cfg, node, memo) x l r y H4).  simpl in |- *.  simpl in H4.\n  rewrite H4.  split.  reflexivity.  unfold BDDneg_memo_OK_2 in |- *.  intros node0 node' bound0 H5 H6.  unfold BDDneg_memo_lookup in H5.\n  rewrite (newMap_semantics ad node0) in H5.  discriminate.  simpl in |- *.  intro y0.  rewrite (BDDneg_1_lemma_2 (cfg, node, memo) n y y0).\n  simpl in |- *.  unfold BDDneg_2 in |- *.  elim n; rewrite y0.  elim (Neqb node BDDzero).\n\n\n\n\n\n\n\n\n\n\n\n  simpl in |- *.  split.  reflexivity.  apply BDDneg_memo_OK_1_lemma_2_1'.  assumption.\n  assumption.  simpl in |- *.  split.  reflexivity.  apply BDDneg_memo_OK_1_lemma_3_1'.\n  assumption. assumption.\n  fold BDDneg_2 in |- *.  intro n0.  intro H4.  elim (Neqb node BDDzero).  simpl in |- *.  split.\n  reflexivity.  apply BDDneg_memo_OK_1_lemma_2_1'.  assumption.  assumption.\n  simpl in |- *.  split.\n  reflexivity.  apply BDDneg_memo_OK_1_lemma_3_1'.  assumption.  assumption.\nQed.", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/bdds/bdd5_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23699021132464063}}
{"text": "Load \"preamble3D.v\".\n\n\n(* dans la couche 0 *)\nLemma LABCMP : forall A B C Ap Bp Cp M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(Ap :: Bp :: Cp ::  nil) = 3 -> rk(A :: B :: C :: Ap :: Bp :: Cp ::  nil) = 4 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(Ap :: Bp :: Cp :: M ::  nil) = 3 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: N ::  nil) = 3 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: P ::  nil) = 3 -> rk(A :: B :: C :: M :: P ::  nil) = 3.\nProof.\n\nintros A B C Ap Bp Cp M N P \nHABCeq HApBpCpeq HABCApBpCpeq HABCMeq HApBpCpMeq HABCNeq HApBpCpNeq HMNeq HABCPeq HApBpCpPeq\n.\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ABCMP requis par la preuve de (?)ABCMP pour la règle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABCMP requis par la preuve de (?)ABCMP pour la règle 5  *)\n(* Application de la règle 5 code (1 ou 2 dans la thèse) *)\n(* marque de l'antécédent : -4 *)\nassert(HABCMPm3 : rk(A :: B :: C :: M :: P :: nil) >= 3).\n{\n\tassert(HABCmtmp : rk(A :: B :: C :: nil) >= 3) by (solve_hyps_min HABCeq HABCm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: C :: nil) (A :: B :: C :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: C :: nil) (A :: B :: C :: M :: P :: nil) 3 3 HABCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la règle 1 code (5 dans la thèse) conclusion AUB *)\n(* marque des antécédents A B AiB : -4 -4 et -4*)\nassert(HABCMPM3 : rk(A :: B :: C :: M :: P :: nil) <= 3).\n{\n\tassert(HABCMMtmp : rk(A :: B :: C :: M :: nil) <= 3) by (solve_hyps_max HABCMeq HABCMM3).\n\tassert(HABCPMtmp : rk(A :: B :: C :: P :: nil) <= 3) by (solve_hyps_max HABCPeq HABCPM3).\n\tassert(HABCmtmp : rk(A :: B :: C :: nil) >= 3) by (solve_hyps_min HABCeq HABCm3).\n\tassert(Hincl : incl (A :: B :: C :: nil) (list_inter (A :: B :: C :: M :: nil) (A :: B :: C :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: M :: P :: nil) (A :: B :: C :: M :: A :: B :: C :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: C :: M :: A :: B :: C :: P :: nil) ((A :: B :: C :: M :: nil) ++ (A :: B :: C :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: B :: C :: M :: nil) (A :: B :: C :: P :: nil) (A :: B :: C :: nil) 3 3 3 HABCMMtmp HABCPMtmp HABCmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\nassert(HABCMPM : rk(A :: B :: C :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABCMPm : rk(A :: B :: C :: M :: P ::  nil) >= 1) by (solve_hyps_min HABCMPeq HABCMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LApBpCpMP : forall A B C Ap Bp Cp M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(Ap :: Bp :: Cp ::  nil) = 3 -> rk(A :: B :: C :: Ap :: Bp :: Cp ::  nil) = 4 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(Ap :: Bp :: Cp :: M ::  nil) = 3 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: N ::  nil) = 3 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: P ::  nil) = 3 -> rk(Ap :: Bp :: Cp :: M :: P ::  nil) = 3.\nProof.\n\nintros A B C Ap Bp Cp M N P \nHABCeq HApBpCpeq HABCApBpCpeq HABCMeq HApBpCpMeq HABCNeq HApBpCpNeq HMNeq HABCPeq HApBpCpPeq\n.\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ApBpCpMP requis par la preuve de (?)ApBpCpMP pour la règle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ApBpCpMP requis par la preuve de (?)ApBpCpMP pour la règle 5  *)\n(* Application de la règle 5 code (1 ou 2 dans la thèse) *)\n(* marque de l'antécédent : -4 *)\nassert(HApBpCpMPm3 : rk(Ap :: Bp :: Cp :: M :: P :: nil) >= 3).\n{\n\tassert(HApBpCpmtmp : rk(Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HApBpCpeq HApBpCpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Ap :: Bp :: Cp :: nil) (Ap :: Bp :: Cp :: M :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Ap :: Bp :: Cp :: nil) (Ap :: Bp :: Cp :: M :: P :: nil) 3 3 HApBpCpmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la règle 1 code (5 dans la thèse) conclusion AUB *)\n(* marque des antécédents A B AiB : -4 -4 et -4*)\nassert(HApBpCpMPM3 : rk(Ap :: Bp :: Cp :: M :: P :: nil) <= 3).\n{\n\tassert(HApBpCpMMtmp : rk(Ap :: Bp :: Cp :: M :: nil) <= 3) by (solve_hyps_max HApBpCpMeq HApBpCpMM3).\n\tassert(HApBpCpPMtmp : rk(Ap :: Bp :: Cp :: P :: nil) <= 3) by (solve_hyps_max HApBpCpPeq HApBpCpPM3).\n\tassert(HApBpCpmtmp : rk(Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HApBpCpeq HApBpCpm3).\n\tassert(Hincl : incl (Ap :: Bp :: Cp :: nil) (list_inter (Ap :: Bp :: Cp :: M :: nil) (Ap :: Bp :: Cp :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Ap :: Bp :: Cp :: M :: P :: nil) (Ap :: Bp :: Cp :: M :: Ap :: Bp :: Cp :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: Bp :: Cp :: M :: Ap :: Bp :: Cp :: P :: nil) ((Ap :: Bp :: Cp :: M :: nil) ++ (Ap :: Bp :: Cp :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Ap :: Bp :: Cp :: M :: nil) (Ap :: Bp :: Cp :: P :: nil) (Ap :: Bp :: Cp :: nil) 3 3 3 HApBpCpMMtmp HApBpCpPMtmp HApBpCpmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\nassert(HApBpCpMPM : rk(Ap :: Bp :: Cp :: M :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HApBpCpMPm : rk(Ap :: Bp :: Cp :: M :: P ::  nil) >= 1) by (solve_hyps_min HApBpCpMPeq HApBpCpMPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABCMNP : forall A B C Ap Bp Cp M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(Ap :: Bp :: Cp ::  nil) = 3 -> rk(A :: B :: C :: Ap :: Bp :: Cp ::  nil) = 4 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(Ap :: Bp :: Cp :: M ::  nil) = 3 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: N ::  nil) = 3 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: P ::  nil) = 3 -> rk(A :: B :: C :: M :: N :: P ::  nil) = 3.\nProof.\n\nintros A B C Ap Bp Cp M N P \nHABCeq HApBpCpeq HABCApBpCpeq HABCMeq HApBpCpMeq HABCNeq HApBpCpNeq HMNeq HABCPeq HApBpCpPeq\n.\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ABCMNP requis par la preuve de (?)ABCMNP pour la règle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABCMNP requis par la preuve de (?)ABCMNP pour la règle 5  *)\n(* Application de la règle 5 code (1 ou 2 dans la thèse) *)\n(* marque de l'antécédent : -4 *)\nassert(HABCMNPm3 : rk(A :: B :: C :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HABCmtmp : rk(A :: B :: C :: nil) >= 3) by (solve_hyps_min HABCeq HABCm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: C :: nil) (A :: B :: C :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: C :: nil) (A :: B :: C :: M :: N :: P :: nil) 3 3 HABCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la règle 1 code (5 dans la thèse) conclusion AUB *)\n(* marque des antécédents A B AiB : -4 4 et -4*)\nassert(HABCMNPM3 : rk(A :: B :: C :: M :: N :: P :: nil) <= 3).\n{\n\tassert(HABCNMtmp : rk(A :: B :: C :: N :: nil) <= 3) by (solve_hyps_max HABCNeq HABCNM3).\n\tassert(HABCMPeq : rk(A :: B :: C :: M :: P :: nil) = 3) by (apply LABCMP with (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HABCMPMtmp : rk(A :: B :: C :: M :: P :: nil) <= 3) by (solve_hyps_max HABCMPeq HABCMPM3).\n\tassert(HABCmtmp : rk(A :: B :: C :: nil) >= 3) by (solve_hyps_min HABCeq HABCm3).\n\tassert(Hincl : incl (A :: B :: C :: nil) (list_inter (A :: B :: C :: N :: nil) (A :: B :: C :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: M :: N :: P :: nil) (A :: B :: C :: N :: A :: B :: C :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: C :: N :: A :: B :: C :: M :: P :: nil) ((A :: B :: C :: N :: nil) ++ (A :: B :: C :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (A :: B :: C :: N :: nil) (A :: B :: C :: M :: P :: nil) (A :: B :: C :: nil) 3 3 3 HABCNMtmp HABCMPMtmp HABCmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\nassert(HABCMNPM : rk(A :: B :: C :: M :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABCMNPm : rk(A :: B :: C :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HABCMNPeq HABCMNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LApBpCpMNP : forall A B C Ap Bp Cp M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(Ap :: Bp :: Cp ::  nil) = 3 -> rk(A :: B :: C :: Ap :: Bp :: Cp ::  nil) = 4 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(Ap :: Bp :: Cp :: M ::  nil) = 3 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: N ::  nil) = 3 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: P ::  nil) = 3 -> rk(Ap :: Bp :: Cp :: M :: N :: P ::  nil) = 3.\nProof.\n\nintros A B C Ap Bp Cp M N P \nHABCeq HApBpCpeq HABCApBpCpeq HABCMeq HApBpCpMeq HABCNeq HApBpCpNeq HMNeq HABCPeq HApBpCpPeq\n.\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ApBpCpMNP requis par la preuve de (?)ApBpCpMNP pour la règle 1  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ApBpCpMNP requis par la preuve de (?)ApBpCpMNP pour la règle 5  *)\n(* Application de la règle 5 code (1 ou 2 dans la thèse) *)\n(* marque de l'antécédent : -4 *)\nassert(HApBpCpMNPm3 : rk(Ap :: Bp :: Cp :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HApBpCpmtmp : rk(Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HApBpCpeq HApBpCpm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (Ap :: Bp :: Cp :: nil) (Ap :: Bp :: Cp :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (Ap :: Bp :: Cp :: nil) (Ap :: Bp :: Cp :: M :: N :: P :: nil) 3 3 HApBpCpmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la règle 1 code (5 dans la thèse) conclusion AUB *)\n(* marque des antécédents A B AiB : -4 4 et -4*)\nassert(HApBpCpMNPM3 : rk(Ap :: Bp :: Cp :: M :: N :: P :: nil) <= 3).\n{\n\tassert(HApBpCpNMtmp : rk(Ap :: Bp :: Cp :: N :: nil) <= 3) by (solve_hyps_max HApBpCpNeq HApBpCpNM3).\n\tassert(HApBpCpMPeq : rk(Ap :: Bp :: Cp :: M :: P :: nil) = 3) by (apply LApBpCpMP with (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HApBpCpMPMtmp : rk(Ap :: Bp :: Cp :: M :: P :: nil) <= 3) by (solve_hyps_max HApBpCpMPeq HApBpCpMPM3).\n\tassert(HApBpCpmtmp : rk(Ap :: Bp :: Cp :: nil) >= 3) by (solve_hyps_min HApBpCpeq HApBpCpm3).\n\tassert(Hincl : incl (Ap :: Bp :: Cp :: nil) (list_inter (Ap :: Bp :: Cp :: N :: nil) (Ap :: Bp :: Cp :: M :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (Ap :: Bp :: Cp :: M :: N :: P :: nil) (Ap :: Bp :: Cp :: N :: Ap :: Bp :: Cp :: M :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (Ap :: Bp :: Cp :: N :: Ap :: Bp :: Cp :: M :: P :: nil) ((Ap :: Bp :: Cp :: N :: nil) ++ (Ap :: Bp :: Cp :: M :: P :: nil))) by (clear_all_rk;my_inO).\n\tassert(HT := rule_1 (Ap :: Bp :: Cp :: N :: nil) (Ap :: Bp :: Cp :: M :: P :: nil) (Ap :: Bp :: Cp :: nil) 3 3 3 HApBpCpNMtmp HApBpCpMPMtmp HApBpCpmtmp Hincl);\n\trewrite <-HT2 in HT;try rewrite <-HT1 in HT;apply HT.\n}\n\nassert(HApBpCpMNPM : rk(Ap :: Bp :: Cp :: M :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HApBpCpMNPm : rk(Ap :: Bp :: Cp :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HApBpCpMNPeq HApBpCpMNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LABCApBpCpMNP : forall A B C Ap Bp Cp M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(Ap :: Bp :: Cp ::  nil) = 3 -> rk(A :: B :: C :: Ap :: Bp :: Cp ::  nil) = 4 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(Ap :: Bp :: Cp :: M ::  nil) = 3 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: N ::  nil) = 3 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: P ::  nil) = 3 -> rk(A :: B :: C :: Ap :: Bp :: Cp :: M :: N :: P ::  nil) = 4.\nProof.\n\nintros A B C Ap Bp Cp M N P \nHABCeq HApBpCpeq HABCApBpCpeq HABCMeq HApBpCpMeq HABCNeq HApBpCpNeq HMNeq HABCPeq HApBpCpPeq\n.\n\n(* dans constructProofaux(), preuve de 3 <= rg <= 4 pour ABCApBpCpMNP requis par la preuve de (?)ABCApBpCpMNP pour la règle 5  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 4 pour ABCApBpCpMNP requis par la preuve de (?)ABCApBpCpMNP pour la règle 5  *)\n(* Application de la règle 5 code (1 ou 2 dans la thèse) *)\n(* marque de l'antécédent : -4 *)\nassert(HABCApBpCpMNPm3 : rk(A :: B :: C :: Ap :: Bp :: Cp :: M :: N :: P :: nil) >= 3).\n{\n\tassert(HABCmtmp : rk(A :: B :: C :: nil) >= 3) by (solve_hyps_min HABCeq HABCm3).\n\tassert(Hcomp : 3 <= 3) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: C :: nil) (A :: B :: C :: Ap :: Bp :: Cp :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: C :: nil) (A :: B :: C :: Ap :: Bp :: Cp :: M :: N :: P :: nil) 3 3 HABCmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la règle 5 code (1 ou 2 dans la thèse) *)\n(* marque de l'antécédent : -4 *)\nassert(HABCApBpCpMNPm4 : rk(A :: B :: C :: Ap :: Bp :: Cp :: M :: N :: P :: nil) >= 4).\n{\n\tassert(HABCApBpCpmtmp : rk(A :: B :: C :: Ap :: Bp :: Cp :: nil) >= 4) by (solve_hyps_min HABCApBpCpeq HABCApBpCpm4).\n\tassert(Hcomp : 4 <= 4) by (repeat constructor).\n\tassert(Hincl : incl (A :: B :: C :: Ap :: Bp :: Cp :: nil) (A :: B :: C :: Ap :: Bp :: Cp :: M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (A :: B :: C :: Ap :: Bp :: Cp :: nil) (A :: B :: C :: Ap :: Bp :: Cp :: M :: N :: P :: nil) 4 4 HABCApBpCpmtmp Hcomp Hincl);apply HT.\n}\n\nassert(HABCApBpCpMNPM : rk(A :: B :: C :: Ap :: Bp :: Cp :: M :: N :: P ::  nil) <= 4) by (apply rk_upper_dim).\nassert(HABCApBpCpMNPm : rk(A :: B :: C :: Ap :: Bp :: Cp :: M :: N :: P ::  nil) >= 1) by (solve_hyps_min HABCApBpCpMNPeq HABCApBpCpMNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nLemma LMNP : forall A B C Ap Bp Cp M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(Ap :: Bp :: Cp ::  nil) = 3 -> rk(A :: B :: C :: Ap :: Bp :: Cp ::  nil) = 4 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(Ap :: Bp :: Cp :: M ::  nil) = 3 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: N ::  nil) = 3 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: P ::  nil) = 3 -> rk(M :: N :: P ::  nil) = 2.\nProof.\n\nintros A B C Ap Bp Cp M N P \nHABCeq HApBpCpeq HABCApBpCpeq HABCMeq HApBpCpMeq HABCNeq HApBpCpNeq HMNeq HABCPeq HApBpCpPeq\n.\n\n(* dans constructProofaux(), preuve de 2 <= rg <= 3 pour MNP requis par la preuve de (?)MNP pour la règle 3  *)\n(* dans constructProofaux(), preuve de 1 <= rg <= 3 pour MNP requis par la preuve de (?)MNP pour la règle 5  *)\n(* Application de la règle 5 code (1 ou 2 dans la thèse) *)\n(* marque de l'antécédent : -4 *)\nassert(HMNPm2 : rk(M :: N :: P :: nil) >= 2).\n{\n\tassert(HMNmtmp : rk(M :: N :: nil) >= 2) by (solve_hyps_min HMNeq HMNm2).\n\tassert(Hcomp : 2 <= 2) by (repeat constructor).\n\tassert(Hincl : incl (M :: N :: nil) (M :: N :: P :: nil)) by (repeat clear_all_rk;my_inO).\n\tassert(HT := rule_5 (M :: N :: nil) (M :: N :: P :: nil) 2 2 HMNmtmp Hcomp Hincl);apply HT.\n}\n\n(* Application de la règle 3 code (6 dans la thèse) *)\n(* marque des antécédents A B AUB: 4 4 et 4*)\nassert(HMNPM2 : rk(M :: N :: P :: nil) <= 2).\n{\n\tassert(HABCMNPeq : rk(A :: B :: C :: M :: N :: P :: nil) = 3) by (apply LABCMNP with (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HABCMNPMtmp : rk(A :: B :: C :: M :: N :: P :: nil) <= 3) by (solve_hyps_max HABCMNPeq HABCMNPM3).\n\tassert(HApBpCpMNPeq : rk(Ap :: Bp :: Cp :: M :: N :: P :: nil) = 3) by (apply LApBpCpMNP with (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HApBpCpMNPMtmp : rk(Ap :: Bp :: Cp :: M :: N :: P :: nil) <= 3) by (solve_hyps_max HApBpCpMNPeq HApBpCpMNPM3).\n\tassert(HABCApBpCpMNPeq : rk(A :: B :: C :: Ap :: Bp :: Cp :: M :: N :: P :: nil) = 4) by (apply LABCApBpCpMNP with (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (M := M) (N := N) (P := P) ; assumption).\n\tassert(HABCApBpCpMNPmtmp : rk(A :: B :: C :: Ap :: Bp :: Cp :: M :: N :: P :: nil) >= 4) by (solve_hyps_min HABCApBpCpMNPeq HABCApBpCpMNPm4).\n\tassert(Hincl : incl (M :: N :: P :: nil) (list_inter (A :: B :: C :: M :: N :: P :: nil) (Ap :: Bp :: Cp :: M :: N :: P :: nil))) by (repeat clear_all_rk;my_inO).\n\tassert(HT1 : equivlist (A :: B :: C :: Ap :: Bp :: Cp :: M :: N :: P :: nil) (A :: B :: C :: M :: N :: P :: Ap :: Bp :: Cp :: M :: N :: P :: nil)) by (clear_all_rk;my_inO).\n\tassert(HT2 : equivlist (A :: B :: C :: M :: N :: P :: Ap :: Bp :: Cp :: M :: N :: P :: nil) ((A :: B :: C :: M :: N :: P :: nil) ++ (Ap :: Bp :: Cp :: M :: N :: P :: nil))) by (clear_all_rk;my_inO).\n\ttry rewrite HT1 in HABCApBpCpMNPmtmp;try rewrite HT2 in HABCApBpCpMNPmtmp.\n\tassert(HT := rule_3 (A :: B :: C :: M :: N :: P :: nil) (Ap :: Bp :: Cp :: M :: N :: P :: nil) (M :: N :: P :: nil) 3 3 4 HABCMNPMtmp HApBpCpMNPMtmp HABCApBpCpMNPmtmp Hincl);apply HT.\n}\n\n\nassert(HMNPM : rk(M :: N :: P ::  nil) <= 3) (* dim : 3 *) by (solve_hyps_max HMNPeq HMNPM3).\nassert(HMNPm : rk(M :: N :: P ::  nil) >= 1) by (solve_hyps_min HMNPeq HMNPm1).\nintuition.\nQed.\n\n(* dans la couche 0 *)\nTheorem def_Conclusion : forall A B C Ap Bp Cp M N P ,\nrk(A :: B :: C ::  nil) = 3 -> rk(Ap :: Bp :: Cp ::  nil) = 3 -> rk(A :: B :: C :: Ap :: Bp :: Cp ::  nil) = 4 ->\nrk(A :: B :: C :: M ::  nil) = 3 -> rk(Ap :: Bp :: Cp :: M ::  nil) = 3 -> rk(A :: B :: C :: N ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: N ::  nil) = 3 -> rk(M :: N ::  nil) = 2 -> rk(A :: B :: C :: P ::  nil) = 3 ->\nrk(Ap :: Bp :: Cp :: P ::  nil) = 3 -> \n\t rk(M :: N :: P ::  nil) = 2  .\nProof.\n\nintros A B C Ap Bp Cp M N P \nHABCeq HApBpCpeq HABCApBpCpeq HABCMeq HApBpCpMeq HABCNeq HApBpCpNeq HMNeq HABCPeq HApBpCpPeq\n.\nrepeat split.\n\n\tapply LMNP with (A := A) (B := B) (C := C) (Ap := Ap) (Bp := Bp) (Cp := Cp) (M := M) (N := N) (P := P) ; assumption.\nQed .\n", "meta": {"author": "pascalschreck", "repo": "ADG2021", "sha": "09a5b93c80a0390aa645f53d9b64c15c2cb453e5", "save_path": "github-repos/coq/pascalschreck-ADG2021", "path": "github-repos/coq/pascalschreck-ADG2021/ADG2021-09a5b93c80a0390aa645f53d9b64c15c2cb453e5/Two planes in 3D/inter2Planes_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23699021132464063}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*                   Proof of functional correctness                   *)\n(*       for the C functions implemented in the MShareIntro layer      *)\n(*                                                                     *)\n(*                        Xiongnan (Newman) Wu                         *)\n(*                                                                     *)\n(*                          Yale University                            *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import TacticsForTesting.\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import MemoryX.\nRequire Import EventsX.\nRequire Import Globalenvs.\nRequire Import Locations.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Cop.\nRequire Import ZArith.Zwf.\nRequire Import RealParams.\nRequire Import LoopProof.\nRequire Import VCGen.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import CompatClightSem.\nRequire Import PrimSemantics.\nRequire Import ShareOpGenSpec.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import CLemmas.\nRequire Import AbstractDataType.\nRequire Import MShareIntroCSource.\nRequire Import MShareIntro.\nRequire Import CalRealSMSPool.\nRequire Import XOmega.\n\n\nModule MSHAREINTROCODESHAREDMEMINIT.\n\n  Section WithPrimitives.\n\n    Context `{real_params: RealParams}.\n    Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n    Context `{Hmwd: UseMemWithData memb}.\n\n    Let mem := mwd (cdata RData).\n\n    Context `{Hstencil: Stencil}.\n    Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n    Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n    Local Open Scope Z_scope.\n\n    Section SharedMemInit.\n\n      Let L: compatlayer (cdata RData) := clear_shared_mem ↦ gensem clear_shared_mem_spec\n             ⊕ pmap_init ↦ gensem pmap_init_spec.\n      \n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n      \n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Local Open Scope Z_scope.\n\n      Section SharedMemInitBody.\n        \n        Context `{Hwb: WritableBlockOps}.\n        \n        Variable (sc: stencil).\n        \n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        (** pmap_init *)\n        \n        Variable bpmap_init: block.\n        \n        Hypothesis hpmap_init1 : Genv.find_symbol ge pmap_init = Some bpmap_init. \n        \n        Hypothesis hpmap_init2 : Genv.find_funct_ptr ge bpmap_init = Some (External (EF_external pmap_init (signature_of_type (Tcons tint Tnil) Tvoid cc_default)) (Tcons tint Tnil) Tvoid cc_default).\n\n        (** clear_shared_mem *)\n        \n        Variable bclear_shared_mem: block.\n        \n        Hypothesis hclear_shared_mem1 : Genv.find_symbol ge clear_shared_mem = Some bclear_shared_mem. \n        \n        Hypothesis hclear_shared_mem2 : Genv.find_funct_ptr ge bclear_shared_mem = Some (External (EF_external clear_shared_mem (signature_of_type (Tcons tint (Tcons tint Tnil)) Tvoid cc_default)) (Tcons tint (Tcons tint Tnil)) Tvoid cc_default).\n\n        Definition shared_mem_init_inner_mk_rdata (i j: Z) (adt: RData) := \n          adt {smspool: Calculate_smsp_inner i (Z.to_nat j) (smspool adt)}.\n\n        Section shared_mem_init_inner_loop_proof.\n\n          Variable minit: memb.\n          Variable adt: RData.\n          Variable i: Z.\n\n          Hypothesis pg : pg adt = true.\n          Hypothesis ihost: ihost adt = true.\n          Hypothesis ikern: ikern adt = true.\n          Hypothesis ipt: ipt adt = true.\n          Hypothesis irange: 0 <= i < num_proc.\n\n          Definition shared_mem_init_inner_loop_body_P (le: temp_env) (m: mem): Prop := \n            PTree.get _j le = Some (Vint Int.zero) /\\\n            PTree.get _i le = Some (Vint (Int.repr i)) /\\\n            m = (minit, adt).\n\n          Definition shared_mem_init_inner_loop_body_Q (le : temp_env) (m: mem): Prop :=    \n            m = (minit, shared_mem_init_inner_mk_rdata i (num_proc - 1) adt) /\\ PTree.get _i le = Some (Vint (Int.repr i)).\n\n          Lemma shared_mem_init_inner_loop_correct_aux : LoopProofSimpleWhile.t shared_mem_init_inner_while_condition shared_mem_init_inner_while_body ge (PTree.empty _) (shared_mem_init_inner_loop_body_P) (shared_mem_init_inner_loop_body_Q).\n          Proof.\n            generalize max_unsigned_val; intro muval.\n            apply LoopProofSimpleWhile.make with\n            (W := Z)\n              (lt := fun z1 z2 => (0 <= z2 /\\ z1 < z2)%Z)\n              (I := fun le m w => exists j,\n                                    PTree.get _i le = Some (Vint (Int.repr i)) /\\\n                                    PTree.get _j le = Some (Vint j) /\\\n                                    0 <= Int.unsigned j <= num_proc /\\\n                                    (Int.unsigned j = 0 /\\ m = (minit, adt) \\/ 0 < Int.unsigned j /\\ m = (minit, shared_mem_init_inner_mk_rdata i (Int.unsigned j - 1) adt)) /\\\n                                    w = num_proc - Int.unsigned j\n              )\n            .\n            apply Zwf_well_founded.\n            intros.\n            unfold shared_mem_init_inner_loop_body_P in H.\n            destruct H as [tjle tmpH].\n            destruct tmpH as [tile msubst].\n            subst.\n            esplit. esplit.\n            repeat vcgen.\n\n            intros.\n            unfold shared_mem_init_inner_while_condition.\n            unfold shared_mem_init_inner_while_body.\n            destruct H as [j tmpH].\n            destruct tmpH as [tile tmpH].\n            destruct tmpH as [tjle tmpH].\n            destruct tmpH as [jrange tmpH].\n            destruct tmpH as [jcase nval].\n            subst.\n            destruct jrange as [jlow jhigh].\n            apply Zle_lt_or_eq in jhigh.\n            destruct m.\n\n            Caseeq jhigh.\n            intro jhigh.\n\n            Caseeq jcase.\n            (* j = 0 *)\n            intro tmpH; destruct tmpH as [jval msubst].\n            injection msubst; intros; subst.\n            esplit. esplit.\n            repeat vcgen.\n            esplit. esplit.\n            repeat vcgen.\n            unfold clear_shared_mem_spec.\n            rewrite pg, ihost, ikern, ipt.\n            unfold shared_mem_arg'.\n            repeat rewrite zle_lt_true; auto.\n            exists (num_proc - Int.unsigned j - 1).\n            repeat vcgen.\n            esplit.\n            repeat vcgen.\n            right.\n            split.\n            omega.\n            unfold shared_mem_init_inner_mk_rdata.\n            rewrite jval; simpl.\n            unfold Calculate_smsp_inner_at_j.\n            reflexivity.\n\n            (* j > 0 *)\n            intro tmpH.\n            destruct tmpH as [jgt0 mval].\n            injection mval; intros; subst.\n            esplit. esplit.\n            repeat vcgen.\n            esplit. esplit.\n            repeat vcgen.\n            unfold clear_shared_mem_spec; simpl.\n            rewrite pg, ihost, ikern, ipt.\n            unfold shared_mem_arg'.\n            repeat rewrite zle_lt_true; auto.\n            exists (num_proc - Int.unsigned j - 1).\n            repeat vcgen.\n            esplit.\n            repeat vcgen.\n            right.\n            split.\n            omega.\n            unfold shared_mem_init_inner_mk_rdata.\n            replace (Int.unsigned j + 1 - 1) with (Int.unsigned j - 1 + 1) by omega.\n            change (Int.unsigned j - 1 + 1) with (Z.succ (Int.unsigned j - 1)).\n            rewrite Z2Nat.inj_succ with (n:=(Int.unsigned j - 1)).\n            Opaque Z.to_nat Z.of_nat.\n            simpl.\n            rewrite Nat2Z.inj_succ.\n            rewrite Z2Nat.id.\n            unfold Z.succ.\n            replace (Int.unsigned j - 1 + 1) with (Int.unsigned j) by omega.\n            unfold Calculate_smsp_inner_at_j.\n            reflexivity.\n            omega.\n            omega.\n\n            (* j = num_proc *)\n            intro jval.\n            subst.\n            esplit. esplit.\n            repeat vcgen.\n            unfold shared_mem_init_inner_loop_body_Q.\n            Caseeq jcase.\n            intro tmpH; destruct tmpH.\n            rewrite jval in H0.\n            discriminate H0.\n            intro tmpH; destruct tmpH.\n            rewrite jval in H1.\n            injection H1; intros; subst.\n            split; eauto.\n          Qed.\n\n        End shared_mem_init_inner_loop_proof.\n\n        Lemma shared_mem_init_inner_loop_correct: forall m d d' le i,\n                                       pg d = true ->\n                                       ihost d = true ->\n                                       ikern d = true ->\n                                       ipt d = true ->\n                                       0 <= i < num_proc ->\n                                       PTree.get _j le = Some (Vint Int.zero) ->\n                                       PTree.get _i le = Some (Vint (Int.repr i)) ->\n                                       d' = shared_mem_init_inner_mk_rdata i (num_proc - 1) d ->\n                                       exists le',\n                                         (exec_stmt ge (PTree.empty _) le ((m, d): mem) (Swhile shared_mem_init_inner_while_condition shared_mem_init_inner_while_body) E0 le' (m, d') Out_normal /\\ PTree.get _i le' = Some (Vint (Int.repr i))).\n        Proof.\n          intros.\n          generalize (shared_mem_init_inner_loop_correct_aux m d i H H0 H1 H2 H3).\n          unfold shared_mem_init_inner_loop_body_P.\n          unfold shared_mem_init_inner_loop_body_Q.\n          intro LP.\n          refine (_ (LoopProofSimpleWhile.termination _ _ _ _ _ _ LP le (m, d) _)).\n          intro pre.\n          destruct pre as [le' tmppre].\n          destruct tmppre as [m'' tmppre].\n          destruct tmppre as [stmp tmppre].\n          destruct tmppre as [m''val tpile'].\n          exists le'.\n          subst.\n          repeat vcgen.\n          repeat vcgen.\n        Qed.\n\n\n        Definition shared_mem_init_mk_rdata (i: Z) (adt: RData) := adt {smspool: Calculate_smsp (Z.to_nat i) (smspool adt)}.\n\n\n        Section shared_mem_init_loop_proof.\n\n          Variable minit: memb.\n          Variable adt: RData.\n\n          Hypothesis pg : pg adt = true.\n          Hypothesis ihost: ihost adt = true.\n          Hypothesis ikern: ikern adt = true.\n          Hypothesis ipt: ipt adt = true.\n\n          Definition shared_mem_init_loop_body_P (le: temp_env) (m: mem): Prop := \n            PTree.get _i le = Some (Vint Int.zero) /\\\n            m = (minit, adt).\n\n          Definition shared_mem_init_loop_body_Q (le : temp_env) (m: mem): Prop :=    \n            m = (minit, shared_mem_init_mk_rdata (num_proc - 1) adt).\n\n          Lemma shared_mem_init_loop_correct_aux : LoopProofSimpleWhile.t shared_mem_init_outter_while_condition shared_mem_init_outter_while_body ge (PTree.empty _) (shared_mem_init_loop_body_P) (shared_mem_init_loop_body_Q).\n          Proof.\n            generalize max_unsigned_val; intro muval.\n            apply LoopProofSimpleWhile.make with\n            (W := Z)\n              (lt := fun z1 z2 => (0 <= z2 /\\ z1 < z2)%Z)\n              (I := fun le m w => exists i,\n                                    PTree.get _i le = Some (Vint i) /\\\n                                    0 <= Int.unsigned i <= num_proc /\\ \n                                    (Int.unsigned i = 0 /\\ m = (minit, adt) \\/ 0 < Int.unsigned i /\\ m = (minit, shared_mem_init_mk_rdata (Int.unsigned i - 1) adt)) /\\\n                                    w = num_proc - Int.unsigned i\n              )\n            .\n            apply Zwf_well_founded.\n            intros.\n            unfold shared_mem_init_loop_body_P in H.\n            destruct H as [tile msubst].\n            subst.\n            esplit. esplit.\n            repeat vcgen.\n\n            intros.\n            unfold shared_mem_init_outter_while_condition.\n            unfold shared_mem_init_outter_while_body.\n            destruct H as [i tmpH].\n            destruct tmpH as [tile tmpH].\n            destruct tmpH as [irange tmpH].\n            destruct tmpH as [icase nval].\n            subst.\n            destruct irange as [ilow ihigh].\n            apply Zle_lt_or_eq in ihigh.\n            destruct m.\n\n            Caseeq ihigh.\n            intro ihigh.\n\n            Caseeq icase.\n            (* i = 0 *)\n            intro tmpH; destruct tmpH as [ival msubst].\n            injection msubst; intros; subst.\n\n            exploit (shared_mem_init_inner_loop_correct minit adt (shared_mem_init_inner_mk_rdata 0 (num_proc - 1) adt) (PTree.set _j (Vint (Int.repr 0)) (set_opttemp None Vundef le)) (Int.unsigned i)); repeat vcgen; try rewrite ival; try reflexivity.\n            destruct H as [le' stmt].\n            destruct stmt as [stmt tmp].\n\n            esplit. esplit.\n            repeat vcgen.\n            esplit. esplit.\n            repeat vcgen.\n            exists (num_proc - Int.unsigned i - 1).\n            repeat vcgen.\n            esplit.\n            repeat vcgen.\n            right.\n            split.\n            omega.\n            unfold shared_mem_init_mk_rdata.\n            rewrite ival; simpl.\n            unfold Calculate_smsp_at_i.\n            unfold shared_mem_init_inner_mk_rdata.\n            reflexivity.\n\n            (* i > 0 *)\n            intro tmpH.\n            destruct tmpH as [igt0 mval].\n            injection mval; intros; subst.\n\n            exploit (shared_mem_init_inner_loop_correct minit (shared_mem_init_mk_rdata (Int.unsigned i - 1) adt) (shared_mem_init_inner_mk_rdata (Int.unsigned i) (num_proc - 1) (shared_mem_init_mk_rdata (Int.unsigned i - 1) adt)) (PTree.set _j (Vint (Int.repr 0)) (set_opttemp None Vundef le)) (Int.unsigned i)); repeat vcgen.\n            destruct H as [le' stmt].\n            destruct stmt as [stmt tmp].\n\n            esplit. esplit.\n            repeat vcgen.\n            esplit. esplit.\n            repeat vcgen.\n            exists (num_proc - Int.unsigned i - 1).\n            repeat vcgen.\n            esplit.\n            repeat vcgen.\n            right.\n            split.\n            omega.\n            unfold shared_mem_init_mk_rdata.\n            f_equal.\n            replace (Int.unsigned i + 1 - 1) with (Int.unsigned i - 1 + 1) by omega.\n            change (Int.unsigned i - 1 + 1) with (Z.succ (Int.unsigned i - 1)).\n            rewrite Z2Nat.inj_succ with (n:=(Int.unsigned i - 1)).\n            Opaque Z.to_nat Z.of_nat.\n            simpl.\n            rewrite Nat2Z.inj_succ.\n            rewrite Z2Nat.id.\n            unfold Z.succ.\n            replace (Int.unsigned i - 1 + 1) with (Int.unsigned i) by omega.\n            unfold Calculate_smsp_at_i.\n            unfold shared_mem_init_inner_mk_rdata.\n            symmetry.\n            reflexivity.\n            omega.\n            omega.\n\n            (* i = num_proc *)\n            intro ival.\n            subst.\n            esplit. esplit.\n            repeat vcgen.\n            unfold shared_mem_init_loop_body_Q.\n            Caseeq icase.\n            intro tmpH; destruct tmpH.\n            rewrite ival in H0.\n            discriminate H0.\n            intro tmpH; destruct tmpH.\n            rewrite ival in H1.\n            injection H1; intros; subst.\n            split; eauto.\n          Qed.\n\n        End shared_mem_init_loop_proof.\n\n        Lemma shared_mem_init_loop_correct: forall m d d' le,\n                                       pg d = true ->\n                                       ihost d = true ->\n                                       ikern d = true ->\n                                       ipt d = true ->\n                                       PTree.get _i le = Some (Vint Int.zero) ->\n                                       d' = shared_mem_init_mk_rdata (num_proc - 1) d ->\n                                       exists le',\n                                         exec_stmt ge (PTree.empty _) le ((m, d): mem) (Swhile shared_mem_init_outter_while_condition shared_mem_init_outter_while_body) E0 le' (m, d') Out_normal.\n        Proof.\n          intros.\n          generalize (shared_mem_init_loop_correct_aux m d H H0 H1 H2).\n          unfold shared_mem_init_loop_body_P.\n          unfold shared_mem_init_loop_body_Q.\n          intro LP.\n          refine (_ (LoopProofSimpleWhile.termination _ _ _ _ _ _ LP le (m, d) _)).\n          intro pre.\n          destruct pre as [le' tmppre].\n          destruct tmppre as [m'' tmppre].\n          destruct tmppre as [stmp m''val].\n          exists le'.\n          subst.\n          repeat vcgen.\n          repeat vcgen.\n        Qed.\n\n        Lemma shared_mem_init_body_correct: forall m d d' env le mbi_adr,\n                                      env = PTree.empty _ ->\n                                      PTree.get _mbi_adr le = Some (Vint mbi_adr) ->\n                                      sharedmem_init_spec (Int.unsigned mbi_adr) d = Some d' ->\n                                      high_level_invariant d ->\n                                      exists le',\n                                        exec_stmt ge env le ((m, d): mem) shared_mem_init_body E0 le' (m, d') Out_normal.\n        Proof.\n          generalize max_unsigned_val; intro muval.\n          intros.\n          subst.\n          unfold shared_mem_init_body.\n          functional inversion H1; subst.\n\n          set (initd := ((((((((d {vmxinfo : real_vmxinfo}) {pg : true}) {LAT\n           : real_LAT (LAT d)}) {nps : real_nps} {AC: real_AC}) {init : true}) {PT : 0})\n       {ptpool : CalRealPT.real_pt (ptpool d)}) {idpde\n      : CalRealIDPDE.real_idpde (idpde d)})).\n          exploit (shared_mem_init_loop_correct m initd (shared_mem_init_mk_rdata (num_proc - 1) initd) (PTree.set _i (Vint (Int.repr 0))\n        (set_opttemp None Vundef (set_opttemp None Vundef le)))); unfold initd; simpl; try reflexivity; try assumption; repeat ptreesolve.\n          unfold real_smspool, CalRealIDPDE.real_idpde.\n          unfold shared_mem_init_mk_rdata.\n          Opaque Z.to_nat Z.of_nat Calculate_smsp.\n          simpl.\n          generalize (Calculate_smsp (Z.to_nat 63) (smspool d)).\n          generalize (CalRealIDPDE.real_idpde (idpde d)).\n          intros real_smspool' real_idpde' stmt.\n          destruct stmt as [le' stmt].\n          esplit.\n          repeat vcgen.\n        Qed.\n       \n      End SharedMemInitBody.\n\n      Theorem shared_mem_init_code_correct:\n        spec_le (shared_mem_init ↦ shared_mem_init_spec_low) (〚shared_mem_init ↦ f_shared_mem_init 〛L).\n      Proof.\n        set (L' := L) in *. unfold L in *.\n        fbigstep_pre L'.\n        fbigstep (shared_mem_init_body_correct s (Genv.globalenv p) makeglobalenv b1 Hb1fs Hb1fp b0 Hb0fs Hb0fp m'0 labd labd' (PTree.empty _) \n                                        (bind_parameter_temps' (fn_params f_shared_mem_init)\n                                                               (Vint mbi_adr::nil)\n                                                               (create_undef_temps (fn_temps f_shared_mem_init)))) H0. \n      Qed.\n\n\n    End SharedMemInit.\n\n  End WithPrimitives.\n\nEnd MSHAREINTROCODESHAREDMEMINIT.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/MShareIntroCodeSharedMemInit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23699021132464063}}
{"text": "(*  DEC 2.0 language specification.\n   Paolo Torrini  \n   Universite' de Lille - CRIStAL-CNRS\n*)\n\nRequire Import List.\n\nRequire Import AuxLibI1.\nRequire Import TypSpecI1. \nRequire Import ModTypI1. \nRequire Import LangSpecI1. \nRequire Import StaticSemI1.\nRequire Import DynamicSemI1.\nRequire Import WeakenI1.\n\nImport ListNotations.\n\n(** Type uniqueness *)\n\nModule UniqueTyp (IdT: ModTyp) <: ModTyp.\n\nModule WeakenL := Weaken IdT.\nExport WeakenL.\n\nDefinition Id := IdT.Id.\nDefinition IdEqDec := IdT.IdEqDec.\nDefinition IdEq := IdT.IdEq.\nDefinition W := IdT.W.\nDefinition BInit := IdT.BInit.\nDefinition WP := IdT.WP.\n\n\nDefinition UniETyping_def :=\n  fun (ftenv: funTC) (tenv: valTC)\n      (e: Exp) (t1: VTyp) (k: ExpTyping ftenv tenv e t1) => \n  forall (t2: VTyp),       \n    ExpTyping ftenv tenv e t2 -> \n        t1 = t2.\n\nDefinition UniPTyping_def :=\n  fun (ftenv: funTC) (tenv: valTC)\n      (ps: Prms) (pt1: PTyp) (k: PrmsTyping ftenv tenv ps pt1) => \n    forall (pt2: PTyp),  \n      PrmsTyping ftenv tenv ps pt2 -> \n        pt1 = pt2.\n\nDefinition UniType_ExpTyping_mut :=\n                      ExpTyping_mut UniETyping_def UniPTyping_def.\n  \nDefinition UniType_PrmsTyping_mut :=\n                      PrmsTyping_mut UniETyping_def UniPTyping_def.\n\n(****************************************************************************)\n\nLemma UniVTyping :\n  forall (v: Value) (t1 t2: VTyp),\n    VTyping v t1 -> \n    VTyping v t2 ->\n    t1 = t2.\nProof.\n  intros.\n  inversion H; subst.\n  inversion H0; subst.\n  reflexivity.\nDefined.  \n\nLemma UniIdTyping :\n  forall (tenv: valTC) (x: Id) (t1 t2: VTyp),\n    IdTyping tenv x t1 -> \n    IdTyping tenv x t2 ->\n    t1 = t2.\nProof.\n  intros.\n  inversion H; subst.\n  inversion H0; subst.\n  destruct (findE tenv x).\n  inversion H2; subst.\n  inversion H3; subst.\n  reflexivity.\n  inversion H2.\nDefined.  \n\nLemma UniIdFTyping :\n  forall (ftenv: funTC) (x: Id) (ft1 ft2: FTyp),\n    IdFTyping ftenv x ft1 -> \n    IdFTyping ftenv x ft2 ->\n    ft1 = ft2.\nProof.\n  intros.\n  inversion H; subst.\n  inversion H0; subst.\n  destruct (findE ftenv x).\n  inversion H2; subst.\n  inversion H3; subst.\n  reflexivity.\n  inversion H2.\nDefined.  \n\nLemma UniEnvTyping :\n  forall (env: valEnv) (tenv1 tenv2: valTC),\n    EnvTyping env tenv1 -> \n    EnvTyping env tenv2 ->\n    tenv1 = tenv2.\nProof.\n  intros.\n  inversion H; subst.\n  inversion H0; subst.\n  reflexivity.\nDefined.\n\nLemma UniFEnvTyping :\n  forall (fenv: funEnv) (ftenv1 ftenv2: funTC),\n    FEnvTyping fenv ftenv1 -> \n    FEnvTyping fenv ftenv2 ->\n    ftenv1 = ftenv2.\nProof.\n  intros.\n  inversion H; subst.\n  inversion H0; subst.\n  reflexivity.\nDefined.\n\n\nLemma UniETyping :\n  forall (ftenv: funTC) (tenv: valTC)\n         (e: Exp) (t1: VTyp),   \n      ExpTyping ftenv tenv e t1 -> \n      forall (t2: VTyp), \n         ExpTyping ftenv tenv e t2 -> \n         t1 = t2.\nProof.\n  intros.\n  eapply UniType_ExpTyping_mut.\n  - intros.\n    unfold UniETyping_def.\n    intros.\n    inversion X1; subst.\n    eapply UniVTyping.\n    exact v0.\n    assumption.\n  - intros.\n    unfold UniETyping_def.\n    intros.\n    inversion X1; subst.\n    eapply UniIdTyping.\n    exact i.\n    assumption.\n  - intros.\n    unfold UniETyping_def in *.\n    intros.\n    inversion X1; subst.\n    eapply H0 in X3.\n    exact X3.\n  - intros.\n    unfold UniETyping_def in *.\n    intros.\n    inversion X1; subst.\n    inversion m0; subst.\n    + inversion X2; subst.\n      eapply H0 in X4.\n      exact X4.\n    + eapply H in X3.\n      rewrite <- X3 in X4.\n      eapply H0 in X4.\n      exact X4.\n  - intros.\n    unfold UniETyping_def in *.\n    intros.\n    inversion X1; subst.\n    assert (tenv1 = tenv4).\n    eapply UniEnvTyping.\n    exact e1.\n    assumption.\n    rewrite <- H0 in X2.\n    eapply H in X2.\n    assumption.\n  - intros.\n    unfold UniETyping_def in *.\n    intros.\n    inversion X1; subst.\n    eapply H0 in X3.\n    assumption.\n  - intros.\n    unfold UniETyping_def in *.\n    intros.\n    inversion X1; subst.\n    assert (FT pt t = FT pt0 t0).\n    eapply UniIdFTyping.\n    exact i.\n    assumption.\n    inversion H1; subst.\n    reflexivity.\n  - intros.\n    unfold UniETyping_def, UniPTyping_def in *.\n    intros.\n    inversion X1; subst.\n    assert (FT pt t = FT pt0 t0).\n    eapply UniIdFTyping.\n    exact i.\n    assumption.\n    inversion H0; subst.\n    reflexivity.\n  - intros.\n    unfold UniETyping_def, UniPTyping_def in *.\n    intros.\n    inversion X1; subst.\n    reflexivity.\n  - intros.\n    unfold UniETyping_def, UniPTyping_def in *.\n    intros.\n    inversion X1; subst.\n    reflexivity.\n  - intros.\n    unfold UniETyping_def, UniPTyping_def in *.\n    intros.\n    inversion X1; subst.  \n    eapply H in X2.\n    eapply H0 in X3.\n    inversion X3; subst.\n    reflexivity.\n  - exact X.\n  - exact X0.\nDefined.    \n\nLemma UniPTyping :\n  forall (ftenv: funTC) (tenv: valTC)\n         (ps: Prms) (pt1: PTyp),   \n      PrmsTyping ftenv tenv ps pt1 -> \n      forall (pt2: PTyp), \n         PrmsTyping ftenv tenv ps pt2 -> \n         pt1 = pt2.\nProof.\n  intros.\n  eapply UniType_PrmsTyping_mut.\n  - intros.\n    unfold UniETyping_def.\n    intros.\n    inversion X1; subst.\n    eapply UniVTyping.\n    exact v0.\n    assumption.\n  - intros.\n    unfold UniETyping_def.\n    intros.\n    inversion X1; subst.\n    eapply UniIdTyping.\n    exact i.\n    assumption.\n  - intros.\n    unfold UniETyping_def in *.\n    intros.\n    inversion X1; subst.\n    eapply H0 in X3.\n    exact X3.\n  - intros.\n    unfold UniETyping_def in *.\n    intros.\n    inversion X1; subst.\n    inversion m0; subst.\n    + inversion X2; subst.\n      eapply H0 in X4.\n      exact X4.\n    + eapply H in X3.\n      rewrite <- X3 in X4.\n      eapply H0 in X4.\n      exact X4.\n  - intros.\n    unfold UniETyping_def in *.\n    intros.\n    inversion X1; subst.\n    assert (tenv1 = tenv4).\n    eapply UniEnvTyping.\n    exact e0.\n    assumption.\n    rewrite <- H0 in X2.\n    eapply H in X2.\n    assumption.\n  - intros.\n    unfold UniETyping_def in *.\n    intros.\n    inversion X1; subst.\n    eapply H0 in X3.\n    assumption.\n  - intros.\n    unfold UniETyping_def in *.\n    intros.\n    inversion X1; subst.\n    assert (FT pt t = FT pt0 t2).\n    eapply UniIdFTyping.\n    exact i.\n    assumption.\n    inversion H1; subst.\n    reflexivity.\n  - intros.\n    unfold UniETyping_def, UniPTyping_def in *.\n    intros.\n    inversion X1; subst.\n    assert (FT pt t = FT pt0 t2).\n    eapply UniIdFTyping.\n    exact i.\n    assumption.\n    inversion H0; subst.\n    reflexivity.\n  - intros.\n    unfold UniETyping_def, UniPTyping_def in *.\n    intros.\n    inversion X1; subst.\n    reflexivity.\n  - intros.\n    unfold UniETyping_def, UniPTyping_def in *.\n    intros.\n    inversion X1; subst.\n    reflexivity.\n  - intros.\n    unfold UniETyping_def, UniPTyping_def in *.\n    intros.\n    inversion X1; subst.  \n    eapply H in X2.\n    eapply H0 in X3.\n    inversion X3; subst.\n    reflexivity.\n  - exact X.\n  - exact X0.\nDefined.    \n\n\nEnd UniqueTyp.\n\n", "meta": {"author": "2xs", "repo": "dec", "sha": "79290ae2f92d437fe365a1b366a30e1eb2b83d19", "save_path": "github-repos/coq/2xs-dec", "path": "github-repos/coq/2xs-dec/dec-79290ae2f92d437fe365a1b366a30e1eb2b83d19/src/DEC2/UniqueTypI1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2369902051943411}}
{"text": "(* From StLib. *)\nRequire Export Programs.\n\nModule Kern (D : DOMAIN) (Pb : PROBLEM D).\n\n  Module P := Prog D Pb.\n  Export P.\n\n  (** [code] denotes the type of elementary (computation or communication)\n   * steps in a distributed kernel. *)\n  Inductive code : Type :=\n  | kNop : code\n  | kFire : cexpr -> code\n  | kIf : bexpr -> code -> code -> code\n  | kSeq : code -> code -> code\n  | kFor : string -> aexpr -> aexpr -> code -> code.\n\n  (** Notations for elementary steps. *)\n\n  Delimit Scope code_scope with code.\n\n  Notation \"'Nop'\" :=\n    kNop : code_scope.\n  Notation \"'Fire' c\" :=\n    (kFire c%aexpr) (at level 80) : code_scope.\n  Notation \"'If' b 'Then' p1 'Else' p2\" :=\n    (kIf b%bexpr p1 p2) (at level 80, right associativity) : code_scope.\n  Notation \"p1 ;; p2\" :=\n    (kSeq p1 p2) (at level 80, right associativity) : code_scope.\n  Notation \"'For' i 'From' a 'To' b 'Do' p\" :=\n    (kFor i a%aexpr b%aexpr p)\n      (at level 80, right associativity) : code_scope.\n\n  (** [denote] compiles programs of type [code] into programs of type\n   * [prog].  This translation is trivial, except for the compilation of the\n   * [Fire] command.  [denote] is parameterized with this compilation step.\n   *\n   * This allows to give two different denotational semantics to programs of\n   * type [code]: One for communication steps, where we check that\n   * dependencies are satisfied.  And one for computation steps, where we don't.\n   * In particular, we will have to check that the pieces of information we\n   * send are part of the current knowledge of the thread, but this is captured\n   * later on, when we give the semantics of distributed programs. *)\n  Fixpoint denote (p : code) F : prog :=\n    match p with\n      | Nop%code =>\n        Nop%prog\n      | (Fire c)%code =>\n        F c\n      | (If b Then p1 Else p2)%code =>\n        (If b Then (denote p1 F) Else (denote p2 F))%prog\n      | (p1;; p2)%code =>\n        (denote p1 F;; denote p2 F)%prog\n      | (For i From a To b Do q)%code =>\n        (For i From a To b Do denote q F)%prog\n    end.\n\n  Module Comp.\n    (** Computation steps.  Here, [Fire c] is compiled as an assertion stating\n     * that all the dependencies of [c] are satisfied, followed by a [Flag c]\n     * command. *)\n    Definition F c := P.Fire c.\n    Definition denote (p : code) : prog :=\n      denote p F.\n  End Comp.\n\n  Module Comm.\n    (** Communication steps.  This time, [Fire c] is equivalent to [Flag c]. *)\n    Definition F c := Flag c.\n    Definition denote (p : code) : prog :=\n      denote p F.\n  End Comm.\n\n  Definition thread := Z.\n  Definition time := Z.\n\n  (** [kern] is the type of distributed programs.  A distributed program\n   * is defined by two programs, representing respectively computation steps\n   * and communication steps.\n   *\n   * During computation steps, the program can access two distinguished\n   * variables, [\"id\"] and [\"T\"].  The former contains the thread's ID while\n   * the latter represents the current time step.\n   *\n   * Similarly, during communication steps, the program can access [\"id\"] and\n   * [\"T\"], but also [\"to\"], which contains the ID of the thread to which\n   * information will be sent.  E.g., if [T=2], [id=1] and [to=3], this is\n   * time step [2], the program is being executed by thread [1] and sending\n   * data to thread [3].\n   *)\n  Record kern :=\n    makeKernel\n      {\n        comp : code;\n        comm : code\n      }.\n\n  (** We now turn to semantics and correctness of distributed programs. *)\n  Record trace :=\n    makeTrace\n      {\n        beforeComp : time -> thread -> array;\n        afterComp  : time -> thread -> array;\n        sends      : time -> thread -> thread -> array\n      }.\n\n  Definition kexec (k : kern) (tr : trace)\n             (idMax : thread) (TMax : time) : Prop :=\n    (* Initially, nothing is computed. *)\n    (forall id, 0 <= id <= idMax -> beforeComp tr 0 id ≡ ∅)\n    /\\\n\n    (* We go from [beforeComp tr T id] to [afterComp tr T id] through a\n     * computation step. *)\n    (forall id T,\n       0 <= id <= idMax -> 0 <= T <= TMax ->\n       exec [(\"id\", id); (\"T\", T)]\n            (beforeComp tr T id)\n            (Comp.denote (comp k))\n            (afterComp tr T id))\n    /\\\n\n    (* [sends tr T id to] represents what is sent by thread [id] to thread\n     * [to] at step [T]. *)\n    (forall id to T,\n       0 <= id <= idMax -> 0 <= to <= idMax -> 0 <= T <= TMax ->\n       exec [(\"id\", id); (\"to\", to); (\"T\", T)]\n            ∅\n            (Comm.denote (comm k))\n            (sends tr T id to))\n    /\\\n\n    (* A thread cannot send a value it does not know. *)\n    (forall id to T,\n       0 <= id <= idMax -> 0 <= to <= idMax -> 0 <= T <= TMax ->\n       sends tr T id to ⊆ afterComp tr T id)\n    /\\\n\n    (* Conservation of knowledge: What a thread knows at time [T+1] comes\n     * from what it knew after computation step at time [T] and what other\n     * threads sent to it. *)\n    (forall id T,\n       0 <= id <= idMax -> 0 <= T <= TMax ->\n       beforeComp tr (T+1) id ⊆\n                  afterComp tr T id\n                  ∪ ⋃⎨sends tr T from id, from ∈〚0, idMax〛⎬)\n    /\\\n\n    (* Completeness *)\n    (target ⊆ ⋃⎨beforeComp tr (TMax+1) id, id ∈〚0, idMax〛⎬).\n\n  Definition kcorrect (k : kern) (idMax : thread) (TMax : time) :=\n    exists tr, kexec k tr idMax TMax.\n\n  (** Trace synthesizer *)\n\n  Definition sends_synth (k : kern) (idMax : thread) :=\n    fun T id to =>\n      shape [(\"id\", id); (\"to\", to); (\"T\", T)]\n            (Comm.denote (comm k)).\n\n  Definition computes_synth (k : kern) (idMax : thread) :=\n    fun T id =>\n      shape [(\"id\", id); (\"T\", T)]\n            (Comp.denote (comp k)).\n\n  Definition bf_synth (k : kern) (idMax : thread) :=\n    fun T id =>\n      (⋃⎨computes_synth k idMax T' id, T' ∈〚0, T-1〛⎬)\n        ∪ (⋃⎨⋃⎨sends_synth k idMax T' from id, from ∈〚0, idMax〛⎬,\n             T' ∈〚0, T-1〛⎬).\n\n  Definition af_synth (k : kern) (idMax : thread) :=\n    fun T id =>\n      (⋃⎨computes_synth k idMax T' id, T' ∈〚0, T〛⎬)\n        ∪ (⋃⎨⋃⎨sends_synth k idMax T' from id, from ∈〚0, idMax〛⎬,\n             T' ∈〚0, T-1〛⎬).\n\n  Definition trace_synth (k : kern) (idMax : thread) :=\n    makeTrace (bf_synth k idMax)\n              (af_synth k idMax)\n              (sends_synth k idMax).\n\n  (** Main correctness result. *)\n  Theorem trace_synth_correct :\n    forall k idMax TMax,\n      (forall T id,\n         0 <= id <= idMax -> 0 <= T <= TMax ->\n         vc [(\"id\", id); (\"T\", T)]\n            (⋃⎨computes_synth k idMax T' id, T' ∈〚0, T - 1〛⎬\n             ∪ ⋃⎨⋃⎨sends_synth k idMax T' from id, from ∈〚0, idMax〛⎬,\n                 T' ∈〚0, T - 1〛⎬)\n            (Comp.denote (comp k))) ->\n      (forall T id to,\n         0 <= id <= idMax -> 0 <= to <= idMax ->\n         0 <= T <= TMax ->\n         vc [(\"id\", id); (\"to\", to); (\"T\", T)] ∅ (Comm.denote (comm k))) ->\n      (forall T id to,\n         0 <= id <= idMax -> 0 <= to <= idMax ->\n         0 <= T <= TMax ->\n         sends_synth k idMax T id to ⊆ af_synth k idMax T id) ->\n      target ⊆ ⋃⎨bf_synth k idMax (TMax + 1) id, id ∈〚0, idMax〛⎬ ->\n      kexec k (trace_synth k idMax) idMax TMax.\n  Proof.\n    unfold kexec, trace_synth, beforeComp, afterComp; intuition.\n\n    + unfold bf_synth.\n      forward; omega.\n\n    + unfold bf_synth, af_synth.\n      eapply exec_equiv_r.\n      apply vc_sexec_correct. apply H; omega.\n      unfold computes_synth.\n      setoid_rewrite param_union_bin at 4; [|assumption].\n      apply bin_union_snd_third.\n\n    + simpl; unfold sends_synth.\n      eapply exec_equiv_r.\n      apply vc_sexec_correct. apply H0; omega.\n      apply bin_union_empty_l.\n\n    + simpl.\n      apply H1; omega.\n\n    + simpl. unfold bf_synth, af_synth.\n      replace (T + 1 - 1) with T by ring.\n      setoid_rewrite param_union_bin at 2; [|assumption].\n      apply equiv_incl.\n      setoid_rewrite bin_union_assoc; reflexivity.\n  Qed.\n\n  (** Handy tactic applying the main correctness result. *)\n  Tactic Notation \"synthesize\" \"trace\" :=\n    eexists; eapply trace_synth_correct; simpl.\n\nEnd Kern.\n", "meta": {"author": "mit-plv", "repo": "stencils", "sha": "02d87db4dd9fac1b1625394acf8d5bf455b1d166", "save_path": "github-repos/coq/mit-plv-stencils", "path": "github-repos/coq/mit-plv-stencils/stencils-02d87db4dd9fac1b1625394acf8d5bf455b1d166/sources/Kernels.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2369721616383417}}
{"text": "From hahn Require Import Hahn.\nFrom PromisingLib Require Import Basic DenseOrder.\nFrom Promising Require Import Memory View Time Cell TView.\n\nDefinition memory_close tview memory :=\n  ⟪ CLOSED_CUR :\n    Memory.closed_timemap (View.rlx (TView.cur tview)) memory ⟫ /\\\n  ⟪ CLOSED_ACQ :\n    Memory.closed_timemap (View.rlx (TView.acq tview)) memory ⟫ /\\\n  ⟪ CLOSED_REL :\n    forall loc,\n      Memory.closed_timemap (View.rlx (TView.rel tview loc)) memory ⟫.\n\nLemma loc_ts_eq_dec_eq {A} {a b : A} l ts :\n  (if loc_ts_eq_dec (l, ts) (l, ts) then a else b) = a.\nProof using. edestruct loc_ts_eq_dec; desf. Qed.\n\nLemma loc_ts_eq_dec_neq {A} {a b : A} {l ts l' ts'}\n      (NEQ: l <> l' \\/ ts <> ts'):\n  (if loc_ts_eq_dec (l, ts) (l', ts') then a else b) = b.\nProof using. edestruct loc_ts_eq_dec; desf. Qed.\n\n\nLemma memory_add_le memory memory' loc from to val released\n      (ADD : Memory.add memory loc from to val released memory'):\n  Memory.le memory memory'.\nProof using.\n  red. ins. erewrite Memory.add_o; eauto.\n  destruct (loc_ts_eq_dec (loc0, to0) (loc, to)); [simpls; desf|done].\n  exfalso. erewrite Memory.add_get0 in LHS; eauto.\n  desf.\nQed.\n\nLemma memory_remove_le memory memory' loc from to val released\n      (ADD : Memory.remove memory loc from to val released memory'):\n  Memory.le memory' memory.\nProof using.\n  red. ins. erewrite Memory.remove_o in LHS; eauto.\n    by destruct (loc_ts_eq_dec (loc0, to0) (loc, to)) in LHS; [desf|].\nQed.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nLemma inhabited_init : Memory.inhabited Memory.init.\nProof using. red. ins. Qed.\n\nLemma inhabited_future memory memory'\n      (INHAB : Memory.inhabited memory)\n      (FUTURE : Memory.future memory memory') :\n  Memory.inhabited memory'.\nProof using.\n  destruct FUTURE; auto.\n  apply clos_rt1n_rt in FUTURE.\n  apply clos_rt_rtn1 in FUTURE.\n  induction FUTURE; auto.\n  { destruct H.\n    eapply Memory.op_future0; eauto. }\n  destruct H0.\n  eapply Memory.op_future0; eauto.\nQed.\n\nLemma inhabited_future_init memory (FUTURE : Memory.future Memory.init memory) :\n  Memory.inhabited memory.\nProof using. eapply inhabited_future; eauto. apply inhabited_init. Qed.\n\nDefinition ts_lt_or_bot memory :=\n  forall loc to from msg (GET : Memory.get loc to memory = Some (from, msg)),\n    (to = Time.bot /\\ from = Time.bot) \\/\n    ⟪ FTLT : Time.lt from to ⟫.\n\nLemma memory_init_o loc to from msg\n      (GET : Memory.get loc to Memory.init = Some (from, msg)) :\n  to = Time.bot /\\ from = Time.bot /\\ msg = Message.elt.\nProof using.\n  unfold Memory.init, Cell.init, Cell.Raw.init in *.\n  unfold Memory.get, Cell.get in *; simpls.\n  apply IdentMap.singleton_find_inv in GET.\n  desf.\nQed.\n\nLemma ts_lt_or_bot_init : ts_lt_or_bot Memory.init.\nProof using. red. ins. apply memory_init_o in GET. left. desf. Qed.\n\nDefinition message_disjoint memory :=\n  forall loc to1 from1 msg1 to2 from2 msg2\n         (GET1 : Memory.get loc to1 memory = Some (from1, msg1))\n         (GET2 : Memory.get loc to2 memory = Some (from2, msg2)),\n    to1 = to2 \\/ Interval.disjoint (from1, to1) (from2, to2).\n\nLemma message_disjoint_init : message_disjoint Memory.init.\nProof using.\n  red. ins.\n  apply memory_init_o in GET1.\n  apply memory_init_o in GET2.\n  desf. by left.\nQed.\n\nLemma ts_lt_or_bot_add loc from to val released memory memory_add\n      (TLOB : ts_lt_or_bot memory)\n      (ADD : Memory.add memory loc from to val released memory_add) :\n  ts_lt_or_bot memory_add.\nProof using.\n  red. ins.\n  erewrite Memory.add_o in GET; eauto.\n  desf; simpls; desf.\n  { right. inv ADD. inv ADD0. }\n  all: by eapply TLOB; eauto.\nQed.\n\nLemma message_disjoint_add loc from to val released memory memory_add\n      (MD : message_disjoint memory)\n      (ADD : Memory.add memory loc from to val released memory_add) :\n  message_disjoint memory_add.\nProof using.\n  red. ins.\n  erewrite Memory.add_o in GET1; eauto.\n  erewrite Memory.add_o in GET2; eauto.\n  desf; simpls; desf.\n  { by left. }\n  { right. inv ADD. inv ADD0.\n    symmetry.\n    eapply DISJOINT; eauto. }\n  { right. inv ADD. inv ADD0.\n    eapply DISJOINT; eauto. }\n  all: by eapply MD; eauto.\nQed.\n\nLemma ts_lt_or_bot_lower loc from to val released released' memory memory_lower\n      (TLOB : ts_lt_or_bot memory)\n      (LOWER : Memory.lower memory loc from to val released released' memory_lower) :\n  ts_lt_or_bot memory_lower.\nProof using.\n  red. ins.\n  erewrite Memory.lower_o in GET; eauto.\n  desf; simpls; desf.\n  { right. inv LOWER. inv LOWER0. }\n  all: by eapply TLOB; eauto.\nQed.\n\nLemma message_disjoint_lower loc from to val released released' memory memory_lower\n      (MD : message_disjoint memory)\n      (LOWER : Memory.lower memory loc from to val released released' memory_lower) :\n  message_disjoint memory_lower.\nProof using.\n  red. ins.\n  erewrite Memory.lower_o in GET1; eauto.\n  erewrite Memory.lower_o in GET2; eauto.\n  desf; simpls; desf.\n  { by left. }\n  all: inv LOWER; inv LOWER0; eapply MD; eauto.\nQed.\n\nLemma ts_lt_or_bot_split loc from to to' val val' released released' memory memory_split\n      (TLOB : ts_lt_or_bot memory)\n      (SPLIT : Memory.split memory loc from to to' val val' released released' memory_split) :\n  ts_lt_or_bot memory_split.\nProof using.\n  red. ins.\n  erewrite Memory.split_o in GET; eauto.\n  desf; simpls; desf.\n  1,2: by right; inv SPLIT; inv SPLIT0.\n  all: eapply TLOB; eauto.\nQed.\n\nLemma ts_lt_or_bot_op loc from to val released kind memory memory'\n      (TLOB : ts_lt_or_bot memory)\n      (OP : Memory.op memory loc from to val released memory' kind) :\n  ts_lt_or_bot memory'.\nProof using.\n  destruct OP.\n  { eapply ts_lt_or_bot_add; eauto. }\n  { eapply ts_lt_or_bot_split; eauto. }\n  eapply ts_lt_or_bot_lower; eauto.\nQed.\n\nLemma ts_lt_or_bot_future memory memory'\n      (TLOB : ts_lt_or_bot memory)\n      (FUTURE : Memory.future memory memory') :\n  ts_lt_or_bot memory'.\nProof using.\n  apply clos_rt1n_rt in FUTURE.\n  apply clos_rt_rtn1 in FUTURE.\n  induction FUTURE; auto.\n  destruct H.\n  eapply ts_lt_or_bot_op; eauto.\nQed.\n\nLemma ts_lt_or_bot_future_init memory\n      (FUTURE : Memory.future Memory.init memory) :\n  ts_lt_or_bot memory.\nProof using. eapply ts_lt_or_bot_future; eauto. apply ts_lt_or_bot_init. Qed.\n\nLemma message_disjoint_split loc from to to' val val' released released' memory memory_split\n      (MD : message_disjoint memory)\n      (SPLIT : Memory.split memory loc from to to' val val' released released' memory_split) :\n  message_disjoint memory_split.\nProof using.\n  assert (exists msg, Memory.get loc to' memory = Some (from, msg))\n    as [msg GETI].\n  { inv SPLIT. inv SPLIT0. eexists. apply GET2. }\n  assert (Time.lt from to /\\ Time.lt to to') as [LTF LTT].\n  { inv SPLIT. inv SPLIT0. }\n  assert (Interval.le (from, to) (from, to')) as ILE1.\n  { constructor; simpls. reflexivity. apply Time.le_lteq. by left. }\n  assert (Interval.le (to, to') (from, to')) as ILE2.\n  { constructor; simpls. 2: reflexivity. apply Time.le_lteq. by left. }\n  red. ins.\n  erewrite Memory.split_o in GET1; eauto.\n  erewrite Memory.split_o in GET2; eauto.\n  desf; simpls; desf.\n  all: try by left.\n  all: try by (eapply MD in GET1; eapply GET1 in GET2; desf).\n  all: right.\n  { symmetry. apply Interval.disjoint_imm. }\n  { symmetry.\n    eapply Interval.le_disjoint; eauto.\n    eapply MD in GET1. eapply GET1 in GETI.\n    symmetry.\n    desf. }\n  { apply Interval.disjoint_imm. }\n  { symmetry.\n    eapply Interval.le_disjoint; eauto.\n    eapply MD in GET1. eapply GET1 in GETI.\n    symmetry.\n    desf. }\n  all: eapply Interval.le_disjoint; eauto.\n  all: eapply MD in GET2; eapply GET2 in GETI.\n  all: symmetry.\n  all: desf.\nQed.\n\nLemma message_disjoint_op loc from to val released memory memory' kind\n      (MD : message_disjoint memory)\n      (OP : Memory.op memory loc from to val released memory' kind) :\n  message_disjoint memory'.\nProof using.\n  destruct OP.\n  { eapply message_disjoint_add; eauto. }\n  { eapply message_disjoint_split; eauto. }\n  eapply message_disjoint_lower; eauto.\nQed.\n\nLemma message_disjoint_future memory memory'\n      (TLOB : message_disjoint memory)\n      (FUTURE : Memory.future memory memory') :\n  message_disjoint memory'.\nProof using.\n  apply clos_rt1n_rt in FUTURE.\n  apply clos_rt_rtn1 in FUTURE.\n  induction FUTURE; auto.\n  destruct H.\n  eapply message_disjoint_op; eauto.\nQed.\n\nLemma message_disjoint_future_init memory\n      (FUTURE : Memory.future Memory.init memory) :\n  message_disjoint memory.\nProof using. eapply message_disjoint_future; eauto. apply message_disjoint_init. Qed.\n\nLemma time_le_rect a b c d (AB : Time.le a b) (CD : Time.le c d) :\n  Time.le (Time.join a c) (Time.join b d).\nProof using.\n  unfold Time.join.\n  desf.\n  { apply Time.le_lteq. left.\n    eapply TimeFacts.le_lt_lt; eauto. }\n  etransitivity; eauto.\nQed.\n\nLemma timemap_le_rect a b c d (AB : TimeMap.le a b) (CD : TimeMap.le c d) :\n  TimeMap.le (TimeMap.join a c) (TimeMap.join b d).\nProof using.\n  unfold TimeMap.join. intros x.\n  all: by apply time_le_rect.\nQed.\n\nLemma view_le_rect a b c d (AB : View.le a b) (CD : View.le c d) :\n  View.le (View.join a c) (View.join b d).\nProof using.\n  unfold View.join in *.\n  destruct AB. destruct CD.\n  constructor; simpls; intros x.\n  all: by apply timemap_le_rect.\nQed.\n\nLemma memory_split_get_old memory memory_split\n      loc from to ts val val' released released'\n      (SP : Memory.split memory loc from to ts val val' released released' memory_split) :\n  Memory.get loc ts memory = Some (from, Message.mk val' released').\nProof using. inv SP. inv SPLIT. Qed.\n\nLemma interval_le_not_disjoint la ra lb rb\n      (LTA : Time.lt la ra)\n      (LTB : Time.lt lb rb)\n      (NEQ : ra <> rb)\n      (ILE : Interval.le (la, ra) (lb, rb)) :\n  ~ Interval.disjoint (la, ra) (lb, rb).\nProof using.\n  inv ILE. simpls.\n  intros HH. eapply HH; constructor; simpls; eauto.\n  { reflexivity. }\n  eapply TimeFacts.le_lt_lt; eauto.\nQed.\n\nLemma closed_view_le view memory memory'\n      (LE : Memory.le memory memory')\n      (CLOS : Memory.closed_view view memory) :\n  Memory.closed_view view memory'.\nProof using.\n  destruct CLOS.\n  constructor; red; [clear RLX; rename PLN into RLX|]; ins.\n  all: specialize (RLX loc); desc.\n  all: apply LE in RLX; eauto.\nQed.\n\n(*********************************************)\n(* TODO: explanation. Maybe a separate file. *)\n(*********************************************)\nDefinition message_view_wf memory :=\n  forall loc to from val released\n         (GET : Memory.get loc to memory = \n                Some (from, Message.mk val released)),\n    View.opt_wf released.\n\nLemma message_view_wf_add\n      memory loc from to val released memory'\n      (REL_WF : message_view_wf memory)\n      (PROM : Memory.add memory loc from to val released memory') :\n  message_view_wf memory'.\nProof using.\n  red. ins.\n  erewrite Memory.add_o in GET; eauto.\n  desf.\n  2: by eapply REL_WF; eauto.\n  simpls; desf.\n  inv PROM. inv ADD.\nQed.\n\nLemma message_view_wf_split\n      memory loc from to to' val val' released released' memory'\n      (REL_WF : message_view_wf memory)\n      (PROM : Memory.split memory loc from to to' val val' released released' memory') :\n  message_view_wf memory'.\nProof using.\n  red. ins.\n  erewrite Memory.split_o in GET; eauto.\n  desf.\n  3: by eapply REL_WF; eauto.\n  all: simpls; desf.\n  { inv PROM. inv SPLIT. }\n  inv PROM. inv SPLIT.\n  eapply REL_WF.\n  apply GET2.\nQed.\n\nLemma message_view_wf_lower\n      memory loc from to val released released' memory'\n      (REL_WF : message_view_wf memory)\n      (PROM : Memory.lower memory loc from to val released released' memory') :\n  message_view_wf memory'.\nProof using.\n  red. ins.\n  erewrite Memory.lower_o in GET; eauto.\n  desf.\n  2: by eapply REL_WF; eauto.\n  simpls; desf.\n  inv PROM. inv LOWER.\nQed.\n\nLemma message_view_wf_op\n      memory loc from to val released memory' kind\n      (REL_WF : message_view_wf memory)\n      (PROM : Memory.op memory loc from to val released memory' kind) :\n  message_view_wf memory'.\nProof using.\n  destruct PROM.\n  { eapply message_view_wf_add; eauto. }\n  { eapply message_view_wf_split; eauto. }\n  eapply message_view_wf_lower; eauto.\nQed.\n\nLemma message_view_wf_promise\n      promises memory loc from to val released promises' memory' kind\n      (REL_WF : message_view_wf memory)\n      (PROM : Memory.promise promises memory loc from to\n                             val released promises' memory' kind) :\n  message_view_wf memory'.\nProof using.\n  destruct PROM.\n  { eapply message_view_wf_add; eauto. }\n  { eapply message_view_wf_split; eauto. }\n  eapply message_view_wf_lower; eauto.\nQed.\n\nLemma message_view_wf_init : message_view_wf Memory.init.\nProof using.\n  red. ins. apply memory_init_o in GET. desf.\n  unfold Message.elt in *. desf.\n  apply View.opt_wf_none.\nQed.\n\nLemma message_view_wf_future memory memory'\n      (MVW    : message_view_wf memory)\n      (FUTURE : Memory.future memory memory') :\n  message_view_wf memory'.\nProof using.\n  induction FUTURE; auto.\n  apply IHFUTURE.\n  destruct H.\n  eapply message_view_wf_op; eauto.\nQed.\n\nLemma message_view_wf_future_init memory\n      (FUTURE : Memory.future Memory.init memory) :\n  message_view_wf memory.\nProof using.\n  eapply message_view_wf_future; eauto.\n  apply message_view_wf_init.\nQed.\n\nLemma memory_closed_timemap_le view memory memory'\n      (MEM_LE : Memory.le memory memory')\n      (MEM_CLOS : Memory.closed_timemap view memory) :\n  Memory.closed_timemap view memory'.\nProof using.\n  red; ins. specialize (MEM_CLOS loc). desf.\n  apply MEM_LE in MEM_CLOS.\n  eauto.\nQed.\n\nLemma memory_close_le tview memory memory'\n      (MEM_LE : Memory.le memory memory')\n      (MEM_CLOS : memory_close tview memory) :\n  memory_close tview memory'.\nProof using.\n  cdes MEM_CLOS.\n  red; splits; ins.\n  all: eapply memory_closed_timemap_le; eauto.\nQed.\n\n\n(*********************************************)\n(* TODO: explanation. Maybe a separate file. *)\n(*********************************************)\nLemma opt_wf_unwrap (view : option View.t) (H: View.wf (View.unwrap view)) :\n  View.opt_wf view.\nProof using. by destruct view; simpls; constructor. Qed.\n\nLemma view_join_bot_r (lhs : View.t): View.join lhs View.bot = lhs.\nProof using. rewrite View.join_comm. apply View.join_bot_l. Qed.\n\nLemma view_join_id l : View.join l l = l.\nProof using. rewrite View.le_join_l; reflexivity. Qed.\n\nLemma time_join_le_r lhs rhs (LE : Time.le lhs rhs): Time.join lhs rhs = rhs.\nProof using.\n  unfold Time.join. desf.\n  exfalso. eapply DenseOrder.lt_strorder. eapply TimeFacts.lt_le_lt; eauto.\nQed.\n\nLemma time_join_le_l lhs rhs (LE : Time.le rhs lhs): Time.join lhs rhs = lhs.\nProof using. unfold Time.join. desf. by apply TimeFacts.antisym. Qed.\n\nLemma time_join_bot_r lhs: Time.join lhs Time.bot = lhs.\nProof using. apply time_join_le_l. apply Time.bot_spec. Qed.\n\nLemma time_join_bot_l rhs: Time.join Time.bot rhs = rhs.\nProof using. apply time_join_le_r. apply Time.bot_spec. Qed.\n\nLemma time_lt_join_l lhs rlhs rrhs (LT : Time.lt lhs rlhs) :\n  Time.lt lhs (Time.join rlhs rrhs).\nProof using. unfold Time.join. desf. eapply TimeFacts.lt_le_lt; eauto. Qed.\n\nLemma time_lt_join_r lhs rlhs rrhs (LT : Time.lt lhs rrhs) :\n  Time.lt lhs (Time.join rlhs rrhs).\nProof using. unfold Time.join. desf. etransitivity; eauto. Qed.\n", "meta": {"author": "weakmemory", "repo": "promising1ToImm", "sha": "f27e87f0c2d037b30f0bc13763af39a11bb949a1", "save_path": "github-repos/coq/weakmemory-promising1ToImm", "path": "github-repos/coq/weakmemory-promising1ToImm/promising1ToImm-f27e87f0c2d037b30f0bc13763af39a11bb949a1/src/MemoryAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23695501149233403}}
{"text": "(** * Properties about Context Free Grammars *)\nRequire Import Coq.Numbers.Natural.Peano.NPeano Coq.Lists.List.\nRequire Import Fiat.Common Fiat.Common.UIP.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Equality.\n\nSet Implicit Arguments.\n\nImport ListNotations.\nLocal Open Scope list_scope.\n\nGlobal Instance item_rect_Proper {Char T}\n: Proper (pointwise_relation _ eq ==> pointwise_relation _ eq ==> eq ==> eq)\n         (@item_rect Char (fun _ => T)).\nProof.\n  lazy.\n  intros ?? H ?? H' ? [?|?] ?; subst; eauto with nocore.\nQed.\nGlobal Instance item_rect_Proper_forall {Char T}\n: Proper (forall_relation (fun _ => eq) ==> forall_relation (fun _ => eq) ==> forall_relation (fun _ => eq))\n         (@item_rect Char T).\nProof.\n  lazy.\n  intros ?? H ?? H' [?|?]; subst; eauto with nocore.\nQed.\n\nGlobal Instance item_rect_Proper_forall_R {C A} {R : relation A}\n  : Proper\n      ((pointwise_relation _ R)\n         ==> (pointwise_relation _ R)\n         ==> forall_relation (fun _ : item C => R))\n      (item_rect (fun _ : item C => A)).\nProof.\n  lazy; intros ?????? [?|?]; trivial.\nQed.\n\n#[global]\nHint Extern 1 (Proper _ (@item_rect _ _)) => exact item_rect_Proper : typeclass_instances.\n#[global]\nHint Extern 0 (Proper _ (@item_rect _ _)) => exact item_rect_Proper_forall : typeclass_instances.\n#[global]\nHint Extern 0 (Proper (pointwise_relation _ _ ==> pointwise_relation _ _ ==> forall_relation _) (item_rect _))\n=> refine item_rect_Proper_forall_R : typeclass_instances.\n\nSection cfg.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char} (G : grammar Char).\n\n  Definition parse_of_item_respectful'\n             (parse_of_respectful : forall {str1 str2} (H : str1 =s str2) {pats pats'} (Hpats : productions_code pats pats') (p : parse_of G str1 pats), parse_of G str2 pats')\n             {str1 str2} (H : str1 =s str2) {it it'} (Hit : item_code it it') (p : parse_of_item G str1 it)\n  : parse_of_item G str2 it'\n    := match p in (parse_of_item _ _ it), it' return item_code it it' -> parse_of_item G str2 it' with\n         | ParseTerminal ch P pf0 pf1, Terminal P' => fun Hit => ParseTerminal G str2 ch P' (transitivity (symmetry (Hit _)) pf0) (transitivity (eq_sym (is_char_Proper H eq_refl)) pf1)\n         | ParseTerminal _ _ _ _, NonTerminal _ => fun Hit => match Hit with end\n         | ParseNonTerminal nt H' p', NonTerminal nt'\n           => fun Hit\n              => ParseNonTerminal\n                   _\n                   (match Hit in (_ = nt') return List.In nt' _ with\n                      | eq_refl => H'\n                    end)\n                   (@parse_of_respectful\n                      _ _ H (Lookup G nt) (Lookup G nt')\n                      (match Hit in (_ = nt') return productions_code (G nt) (G nt') with\n                         | eq_refl => reflexivity _\n                       end)\n                      p')\n         | ParseNonTerminal _ _ _, Terminal _ => fun Hit => match Hit with end\n       end Hit.\n\n  Global Arguments parse_of_item_respectful' _ _ _ _ _ !_ _ !_ / .\n\n  Section bodies.\n    Context (parse_of_respectful : forall {str1 str2} (H : str1 =s str2) {pats pats'} (Hpats : productions_code pats pats') (p : parse_of G str1 pats), parse_of G str2 pats')\n            (parse_of_production_respectful : forall {str1 str2} (H : str1 =s str2) {pat pat'} (Hpat : production_code pat pat') (p : parse_of_production G str1 pat), parse_of_production G str2 pat').\n\n    Definition parse_of_respectful_step {str1 str2} (H : str1 =s str2) {pats pats'} (Hpats : productions_code pats pats') (p : parse_of G str1 pats) : parse_of G str2 pats'.\n    Proof.\n      refine (match p in (parse_of _ _ pats), pats' return productions_code pats pats' -> parse_of G str2 pats' with\n                | ParseHead pat pats p', pat'::pats' => fun Hpats' => ParseHead pats' (@parse_of_production_respectful _ _ H _ _ _ p')\n                | ParseTail pat pats p', pat'::pats' => fun Hpats' => ParseTail pat' (@parse_of_respectful _ _ H _ _ _ p')\n                | ParseHead _ _ _, nil => fun Hpats' => match _ : False with end\n                | ParseTail _ _ _, nil => fun Hpats' => match _ : False with end\n              end Hpats);\n      try solve [ clear -Hpats'; abstract inversion Hpats'\n                | clear -Hpats'; inversion Hpats'; subst; assumption ].\n    Defined.\n\n    Definition parse_of_production_respectful_step {str1 str2} (H : str1 =s str2) {pat pat'} (Hpat : production_code pat pat') (p : parse_of_production G str1 pat) : parse_of_production G str2 pat'.\n    Proof.\n      refine (match p in (parse_of_production _ _ pat), pat' return production_code pat pat' -> parse_of_production G str2 pat' with\n                | ParseProductionNil pf, nil => fun Hpat' => ParseProductionNil G str2 (transitivity (eq_sym (length_Proper H)) pf)\n                | ParseProductionCons n pat pats p0 p1, pat'::pats' => fun Hpat' => ParseProductionCons _ n (parse_of_item_respectful' (@parse_of_respectful) (take_Proper eq_refl H) _ p0) (@parse_of_production_respectful _ _ (drop_Proper eq_refl H) _ _ _ p1)\n                | ParseProductionNil _, _::_ => fun Hpat' => match _ : False with end\n                | ParseProductionCons _ _ _ _ _, nil => fun Hpat' => match _ : False with end\n              end Hpat);\n      try solve [ clear -Hpat'; abstract inversion Hpat'\n                | clear -Hpat'; inversion Hpat'; subst; assumption ].\n    Defined.\n\n    Global Arguments parse_of_respectful_step _ _ _ _ _ _ !_ / .\n    Global Arguments parse_of_production_respectful_step _ _ _ _ _ _ !_ / .\n  End bodies.\n\n  Fixpoint parse_of_respectful {str1 str2} (H : str1 =s str2) {pats pats'} (Hpats : productions_code pats pats') (p : parse_of G str1 pats) : parse_of G str2 pats'\n    := @parse_of_respectful_step (@parse_of_respectful) (@parse_of_production_respectful) _ _ H _ _ Hpats p\n  with parse_of_production_respectful {str1 str2} (H : str1 =s str2) {pat pat'} (Hpat : production_code pat pat') (p : parse_of_production G str1 pat) : parse_of_production G str2 pat'\n    := @parse_of_production_respectful_step (@parse_of_respectful) (@parse_of_production_respectful) _ _ H _ _ Hpat p.\n\n  Definition parse_of_item_respectful : forall {str1 str2} H {it it'} Hit p, _\n    := @parse_of_item_respectful' (@parse_of_respectful).\n\n  Global Arguments parse_of_item_respectful _ _ _ _ !_ _ !_ / .\n\n  Fixpoint parse_of_respectful_refl {str pf pats Hpats} (p : parse_of G str pats) : parse_of_respectful pf Hpats p = p\n    := match p return forall Hpats, parse_of_respectful pf Hpats p = p with\n         | ParseHead pat pats p' => fun Hpats => f_equal (ParseHead _) (parse_of_production_respectful_refl p')\n         | ParseTail pat pats p' => fun Hpats => f_equal (@ParseTail _ _ _ _ _ _ _) (parse_of_respectful_refl p')\n       end Hpats\n  with parse_of_production_respectful_refl {str pf pat Hpat} (p : parse_of_production G str pat) : parse_of_production_respectful pf Hpat p = p\n       := match p return forall Hpat, parse_of_production_respectful pf Hpat p = p with\n            | ParseProductionNil pf => fun Hpat => f_equal (ParseProductionNil _ _) (dec_eq_uip (Nat.eq_dec _) _ _)\n            | ParseProductionCons n pat pats p0 p1\n              => fun Hpat => f_equal2 (@ParseProductionCons _ _ _ _ _ _ _ _)\n                                      (parse_of_item_respectful_refl p0)\n                                      (parse_of_production_respectful_refl p1)\n          end Hpat\n  with parse_of_item_respectful_refl {str pf it Hit} (p : parse_of_item G str it) : parse_of_item_respectful pf Hit p = p\n       := match p return forall Hit, parse_of_item_respectful pf Hit p = p with\n            | ParseTerminal ch P pf1 pf2 => fun Hit => f_equal2 (ParseTerminal _ _ _ _) (dec_eq_uip (Bool.bool_dec _) _ _) (dec_eq_uip (Bool.bool_dec _) _ _)\n            | ParseNonTerminal nt H' p'\n              => fun Hit'\n                 => f_equal2 (ParseNonTerminal nt)\n                             match dec_eq_uip (@Equality.string_eq_dec nt) eq_refl Hit' in (_ = Hit') return match Hit' in (_ = nt') return List.In nt' _ with eq_refl => H' end = H' with\n                               | eq_refl => eq_refl\n                             end\n                             (@parse_of_respectful_refl _ _ _ _ p')\n          end Hit.\n\n  (*Global Instance parse_of_Proper : Proper (beq ==> eq ==> iff) (parse_of G).\n  Proof.\n    split; subst; apply parse_of_respectful; [ assumption | symmetry; assumption ].\n  Qed.\n\n  Global Instance parse_of_production_Proper : Proper (beq ==> eq ==> iff) (parse_of_production G).\n  Proof.\n    split; subst; apply parse_of_production_respectful; [ assumption | symmetry; assumption ].\n  Qed.\n\n  Global Instance parse_of_item_Proper : Proper (beq ==> eq ==> iff) (parse_of_item G).\n  Proof.\n    split; subst; apply parse_of_item_respectful; [ assumption | symmetry; assumption ].\n  Qed.*)\n\n  Definition ParseProductionSingleton str it (p : parse_of_item G str it) : parse_of_production G str [ it ].\n  Proof.\n    econstructor.\n    { eapply parse_of_item_respectful; [ | reflexivity | eassumption ].\n      rewrite take_long; reflexivity. }\n    { constructor.\n      rewrite drop_length; auto with arith. }\n  Defined.\n\n  Section definitions.\n    Context (P : String -> String.string -> Type).\n\n    Definition Forall_parse_of_item'\n               (Forall_parse_of : forall {str pats} (p : parse_of G str pats), Type)\n               {str it} (p : parse_of_item G str it)\n      := match p return Type with\n           | ParseTerminal ch P pf1 pf2 => unit\n           | ParseNonTerminal nt H' p'\n             => (P str nt * Forall_parse_of p')%type\n         end.\n\n    Fixpoint Forall_parse_of {str pats} (p : parse_of G str pats)\n      := match p with\n           | ParseHead pat pats p'\n             => Forall_parse_of_production p'\n           | ParseTail _ _ p'\n             => Forall_parse_of p'\n         end\n    with Forall_parse_of_production {str pat} (p : parse_of_production G str pat)\n         := match p return Type with\n              | ParseProductionNil pf => unit\n              | ParseProductionCons pat strs pats p' p''\n                => (Forall_parse_of_item' (@Forall_parse_of) p' * Forall_parse_of_production p'')%type\n            end.\n\n    Definition Forall_parse_of_item {str it} (p : parse_of_item G str it)\n      := @Forall_parse_of_item' (@Forall_parse_of) str it p.\n  End definitions.\n\n  (*Section expand.\n    Context {P P' : String -> String.string -> Type}.\n\n    Definition expand_forall_parse_of_item'\n               {str str' str''}\n               {Forall_parse_of : forall P {str pats} (p : parse_of G str pats), Type}\n               (expand : forall {pats pats' pats''} (Hpats : productions_code pats pats') (Hpats' : productions_code pats' pats'') (H : str =s str') (H' : str =s str'') {p}, @Forall_parse_of P str' pats' (parse_of_respectful H Hpats p) -> @Forall_parse_of P' str'' pats'' (parse_of_respectful H' Hpats' p))\n               (f : forall n, P str' n -> P' str'' n)\n               {it p} (H : str =s str') (H' : str =s str'')\n    : @Forall_parse_of_item' P (@Forall_parse_of P) str' it (parse_of_item_respectful H p)\n      -> @Forall_parse_of_item' P' (@Forall_parse_of P') str'' it (parse_of_item_respectful H' p).\n    Proof.\n      destruct p; simpl.\n      { exact (fun x => x). }\n      { intro ab.\n        exact (f _ (fst ab), expand _ H H' _ (snd ab)). }\n    Defined.\n\n    Global Arguments expand_forall_parse_of_item' : simpl never.\n\n    Fixpoint expand_forall_parse_of\n             str str' str''\n             (f : forall str0' str1', str0' ≤s str -> str0' =s str1' -> forall n, P str0' n -> P' str1' n)\n             pats (H : str =s str') (H' : str =s str'') (p : parse_of G str pats)\n             {struct p}\n    : Forall_parse_of P (parse_of_respectful H p) -> Forall_parse_of P' (parse_of_respectful H' p)\n    with expand_forall_parse_of_production\n           str str' str''\n           (f : forall str0' str1', str0' ≤s str -> str0' =s str1' -> forall n, P str0' n -> P' str1' n)\n           pat (H : str =s str') (H' : str =s str'') (p : parse_of_production G str pat)\n           {struct p}\n         : Forall_parse_of_production P (parse_of_production_respectful H p) -> Forall_parse_of_production P' (parse_of_production_respectful H' p).\n    Proof.\n      { destruct p.\n        simpl.\n        { apply expand_forall_parse_of_production; exact f. }\n        { refine (expand_forall_parse_of _ _ _ _ _ _ _ p); exact f. } }\n      { destruct p as [ | n pat pats pit pits ]; simpl.\n        { exact (fun x => x). }\n        { pose proof (fun f' f'' => @expand_forall_parse_of_item' _ (take n str') (take n str'') (@Forall_parse_of) (@expand_forall_parse_of _ _ _ f') f'' _ pit) as expand_forall_parse_of_item.\n          specialize (fun f' H H' => expand_forall_parse_of_production _ (drop n str') (drop n str'') f' _ H H' pits).\n          clear expand_forall_parse_of.\n          change (Forall_parse_of_item P (parse_of_item_respectful (take_Proper eq_refl H) pit) * Forall_parse_of_production P (parse_of_production_respectful (drop_Proper eq_refl H) pits)\n                  -> Forall_parse_of_item P' (parse_of_item_respectful (take_Proper eq_refl H') pit) * Forall_parse_of_production P' (parse_of_production_respectful (drop_Proper eq_refl H') pits))%type.\n          intro xy.\n          split.\n          { eapply expand_forall_parse_of_item; [ .. | exact (fst xy) ].\n            { intros ? ? H''; apply f.\n              rewrite str_le_take in H''; assumption. }\n            { intro; apply f.\n              { clear -H HSLP.\n                rewrite str_le_take, H; reflexivity. }\n              { rewrite <- H, <- H'; reflexivity. } } }\n          { eapply expand_forall_parse_of_production; [ .. | exact (snd xy) ].\n            intros ? ? H''; apply f.\n            etransitivity; [ eassumption | apply str_le_drop ]. } } }\n    Defined.\n\n    Global Arguments expand_forall_parse_of : simpl never.\n    Global Arguments expand_forall_parse_of_production : simpl never.\n\n    Definition expand_forall_parse_of_item {str str' str''} f {it} {p : parse_of_item G str it} (H : str =s str') (H' : str =s str'')\n      := @expand_forall_parse_of_item' str str' str'' _ (@expand_forall_parse_of str str' str'' f) (f _ _ ((_ : Proper (beq ==> beq ==> impl) str_le) _ _ H _ _ (reflexivity _) (reflexivity _)) (transitivity (symmetry H) H')) it p.\n\n    Global Arguments expand_forall_parse_of_item : simpl never.\n  End expand.*)\nEnd cfg.\n\nLtac simpl_parse_of_respectful :=\n  repeat match goal with\n           | [ |- context[@parse_of_respectful ?Char ?HSLM ?HSL ?HSLP ?G ?str1 ?str2 ?H ?pat ?pat' ?Hpat ?p] ]\n             => change (@parse_of_respectful Char HSLM HSL HSLP G str1 str2 H pat pat' Hpat p)\n                with (@parse_of_respectful_step Char HSLM HSL G (@parse_of_respectful Char HSLM HSL HSLP G) (@parse_of_production_respectful Char HSLM HSL HSLP G) str1 str2 H pat pat' Hpat p);\n               simpl @parse_of_respectful_step\n           | [ |- context[@parse_of_production_respectful ?Char ?HSLM ?HSL ?HSLP ?G ?str1 ?str2 ?H ?pat ?pat' ?Hpat ?p] ]\n             => change (@parse_of_production_respectful Char HSLM HSL HSLP G str1 str2 H pat pat' Hpat p)\n                with (@parse_of_production_respectful_step Char HSLM HSL G (@parse_of_respectful Char HSLM HSL HSLP G) (@parse_of_production_respectful Char HSLM HSL HSLP G) str1 str2 H pat pat' Hpat p);\n               simpl @parse_of_production_respectful_step\n           | _ => progress simpl @parse_of_item_respectful\n           | _ => progress simpl @parse_of_item_respectful'\n         end.\n\nSection parse_of_proper.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char} {G : grammar Char} {str : String}.\n\n  Local Ltac t_parse_of_impl lem :=\n    repeat intro;\n    match goal with\n      | [ H : Proper _ _, H' : _ -> _ |- _ ] => eapply H; [ eassumption.. | apply H'; try clear H H' ]\n    end;\n    eapply lem; [ .. | eassumption ];\n    try first [ assumption\n              | reflexivity\n              | symmetry; assumption ].\n\n  Section fun0.\n    Context {P : _ -> _ -> Prop}\n            {H : Proper (@item_code Char ==> @production_code Char ==> impl) P}.\n\n    Global Instance parse_of_item_fun0_Proper\n    : Proper (item_code ==> production_code ==> impl) (fun it (its : production Char) => parse_of_item G str it -> P it its).\n    Proof. t_parse_of_impl (@parse_of_item_respectful). Qed.\n    Global Instance parse_of_production_fun0_Proper\n    : Proper (item_code ==> production_code ==> impl) (fun (it : item Char) (its : production Char) => parse_of_production G str its -> P it its).\n    Proof. t_parse_of_impl (@parse_of_production_respectful). Qed.\n  End fun0.\n  Section fun0_flip.\n    Context {P : _ -> _ -> Prop}\n            {H : Proper (@item_code Char ==> @production_code Char ==> flip impl) P}.\n\n    Global Instance parse_of_item_fun0_Proper_flip\n    : Proper (item_code ==> production_code ==> flip impl) (fun it (its : production Char) => parse_of_item G str it -> P it its).\n    Proof. t_parse_of_impl (@parse_of_item_respectful). Qed.\n    Global Instance parse_of_production_fun0_Proper_flip\n    : Proper (item_code ==> production_code ==> flip impl) (fun (it : item Char) (its : production Char) => parse_of_production G str its -> P it its).\n    Proof. t_parse_of_impl (@parse_of_production_respectful). Qed.\n  End fun0_flip.\n\n  Section fun1.\n    Context {A} {RA : relation A}\n            {P : _ -> _ -> _ -> Prop}\n            {H : Proper (@item_code Char ==> @production_code Char ==> RA ==> impl) P}.\n\n    Global Instance parse_of_item_fun1_Proper\n    : Proper (item_code ==> production_code ==> RA ==> impl) (fun it (its : production Char) x => parse_of_item G str it -> P it its x).\n    Proof. t_parse_of_impl (@parse_of_item_respectful). Qed.\n    Global Instance parse_of_production_fun1_Proper\n    : Proper (item_code ==> production_code ==> RA ==> impl) (fun (it : item Char) (its : production Char) x => parse_of_production G str its -> P it its x).\n    Proof. t_parse_of_impl (@parse_of_production_respectful). Qed.\n  End fun1.\n  Section fun1_flip.\n    Context {A} {RA : relation A}\n            {P : _ -> _ -> _ -> Prop}\n            {H : Proper (@item_code Char ==> @production_code Char ==> RA ==> flip impl) P}.\n\n    Global Instance parse_of_item_fun1_Proper_flip\n    : Proper (item_code ==> production_code ==> RA ==> flip impl) (fun it (its : production Char) x => parse_of_item G str it -> P it its x).\n    Proof. t_parse_of_impl (@parse_of_item_respectful). Qed.\n    Global Instance parse_of_production_fun1_Proper_flip\n    : Proper (item_code ==> production_code ==> RA ==> flip impl) (fun (it : item Char) (its : production Char) x => parse_of_production G str its -> P it its x).\n    Proof. t_parse_of_impl (@parse_of_production_respectful). Qed.\n  End fun1_flip.\nEnd parse_of_proper.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/ContextFreeGrammar/Properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23695500573931236}}
{"text": "(** * Functoriality of composition of natural transformations *)\nRequire Import Category.Core Functor.Core NaturalTransformation.Core.\nRequire Import FunctorCategory.Core Functor.Composition.Core NaturalTransformation.Composition.Core NaturalTransformation.Composition.Laws.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope functor_scope.\n\nSection functorial_composition.\n  Context `{Funext}.\n  Variables C D E : PreCategory.\n\n  Local Open Scope natural_transformation_scope.\n\n  (** ** whiskering on the left is a functor *)\n  Definition whiskerL_functor (F : (D -> E)%category)\n  : ((C -> D) -> (C -> E))%category\n    := Build_Functor\n         (C -> D) (C -> E)\n         (fun G => F o G)%functor\n         (fun _ _ T => F oL T)\n         (fun _ _ _ _ _ => composition_of_whisker_l _ _ _)\n         (fun _ => whisker_l_right_identity _ _).\n\n  (** ** whiskering on the right is a functor *)\n  Definition whiskerR_functor (G : (C -> D)%category)\n  : ((D -> E) -> (C -> E))%category\n    := Build_Functor\n         (D -> E) (C -> E)\n         (fun F => F o G)%functor\n         (fun _ _ T => T oR G)\n         (fun _ _ _ _ _ => composition_of_whisker_r _ _ _)\n         (fun _ => whisker_r_left_identity _ _).\nEnd functorial_composition.\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Categories/NaturalTransformation/Composition/Functorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23695499998629063}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp\nRequire Import path.\nRequire Import Eqdep pred prelude idynamic ordtype pcm finmap unionmap heap coding. \nRequire Import Hgraphs Logs Wavefronts Apex Partitions.\nRequire Import WavefrontDimension MutatorCount.\nSet Implicit Arguments. \nUnset Strict Implicit.\nUnset Printing Implicit Defensive. \n\nSection PolicyDimension.\n\nVariable e0 : LogEntry.\n(* Initial graph an heap *)\nVariables (h0 : heap) (g0: graph h0).\n\n(* A collector log p will all unique entires *)\nVariables  (p : log).\n\n(* Final heap and graph for the log p with the corresponding certificate epf *)\nVariables (h : heap) (g: graph h).\nVariable (epf : executeLog g0 p = Some (ExRes g)).\n\nVariables (wp polp prp : par2).\n\n(* Wavefront partition *)\nNotation FL := (pr1 wp).\nNotation OL := (pr2 wp).\n\n(* Policy partition *)\nNotation SR := (pr1 polp).\nNotation LR := (pr2 polp).\n\n(* Protection partition *)\nNotation IS := (pr1 prp).\nNotation DS := (pr2 prp).\n\nNotation w_gt := (W_gt g wp).\nNotation w_lt := (W_lt g wp).\n\n(* Consider expose_r from Section 5.2.1 of the paper, taking IS =\n   True, so it's not mentioned so far. In this shape, expose_r is exactly\n   expose_apex, instantiated with W_gt and restricted to the SR part of\n   the partition. The LR-part will be processed further. *)\n\nDefinition expose_r : seq ptr := \n  [seq let pi := pe.2      in\n       let o  := source pi in\n       let f  := fld pi    in \n       o#f@g | pe <- prefixes e0 p &\n               let: (pre, pi)    := pe          in   \n               let k             := (kind pi)   in   \n               let o             := (source pi) in\n               let f             := (fld pi)    in   \n               let n             := (new pi)    in   \n               [&& (kindMA k), ((o, f) \\in w_gt pre),\n                   SR o & IS n]].\n\nDefinition expose_c : seq ptr := \n  [seq new pi | pi <- p &\n                let n := new pi    in\n                let o := source pi in\n                let f := fld pi    in\n                [&& (M_plus e0 p o f n > M_minus e0 p o f n), LR o & IS n]].\n\n(* Lemmas: similar to the one, proved for expose_apex *)\n\nLemma expose_r_fires et l1 l2 : \n  let o := source et in\n  let f := fld    et in\n  let x := o # f @ g in\n  IS x -> SR o -> \n  p = l1 ++ et :: l2  ->\n  kind et == T        ->\n  x \\in alreadyMarked p ++ expose_r.\nProof.\nmove=>/=H1 H2 E K.\nrewrite mem_cat; apply/orP.\ncase: (traced_objects epf E K); [left | right].\n- by apply/alreadyMarkedP; exists et, l1, l2.\ncase/hasP: b=>ema D/andP[K2]/andP[/eqP E2]/andP[/eqP E3]/eqP E4; rewrite E2 E3.\ncase: (prefix_wavefront e0 D E K)=>pre[G1]/(w_gt_approx epf wp) G2.\napply/mapP; exists (pre, ema)=>//=.\nrewrite mem_filter K2 -E2 -E3 H2 G1 -!(andbC true)/=.\napply/andP; split; last by rewrite -E4 H1.\nby apply: G2; case/prefV: G1=>[i][Y1] Y2 Y3; exists i.\nQed.\n\nLemma expose_c_fires et l1 l2 : \n  let o := source et in\n  let f := fld    et in\n  let x := o # f @ g in\n  IS x -> LR o ->\n  p = l1 ++ et :: l2  ->\n  kind et == T        ->\n  x \\in alreadyMarked p ++ expose_c.\nProof.\nmove=>/=H1 H2 E K.\nrewrite mem_cat; apply/orP.\ncase: (traced_objects' epf E K)=>B.\n- by left; apply/alreadyMarkedP; exists et, l1, l2.\ncase: B=> ema[l3][l4]/andP[M]/andP[/eqP E2]/andP[/eqP E3]N.\ncase X: (has (matchingTFull ema) p).\n- case/hasP: X=>e /in_split[l5][l6]E'/andP[K'/andP[E3']]/andP[E2']E4'.\n  by left; apply/alreadyMarkedP; exists e, l5, l6; move/eqP: E4'=>->.  \nmove/negbT: X=>X; subst l2.\nright; rewrite /expose_c.\ncase/mapP: (mut_count_fires e0 epf E K M E2 X N)=>e H3[Z1 Z2 Z3].\ncase/andP: M=>_/andP[/eqP Y1]/eqP Y2.\napply/mapP; exists e=>//; last by rewrite -Z3. \nrewrite !mem_filter -!Z1 -!Z2 in H3 *.\nrewrite Y1 in H2; rewrite H2/=.\nby case/andP: H3=>->->/=; rewrite andbC -Z3 -E2. \nQed.\n\nLemma expose_rc_fires et l1 l2 :\n  let o := source et in\n  let f := fld    et in\n  let x := o # f @ g in\n  IS x -> p = l1 ++ et :: l2  -> kind et == T ->\n  x \\in alreadyMarked p ++ expose_r ++ expose_c.\nProof.\nmove=>o f x H1 E K.\ncase H2: (SR o).\n- move: (expose_r_fires H1 H2 E K); rewrite -/x=>G.\n  by rewrite catA mem_cat G.\nmove: (pr_coh polp o); rewrite H2/==>{H2}H2.\nmove: (expose_c_fires H1 H2 E K); rewrite -/x=>G.\nrewrite !mem_cat in G *.\nby case/orP: G=>->//; rewrite -!(orbC true).\nQed.\n  \nEnd PolicyDimension.", "meta": {"author": "UCL-PPLV", "repo": "GCTransformations", "sha": "c0cdfe798ee4be1d898db5ede819f57e25378f21", "save_path": "github-repos/coq/UCL-PPLV-GCTransformations", "path": "github-repos/coq/UCL-PPLV-GCTransformations/GCTransformations-c0cdfe798ee4be1d898db5ede819f57e25378f21/Coq/PolicyDimension.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647394, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23695499998629058}}
{"text": "Set Implicit Arguments.\nSet Bullet Behavior \"Strict Subproofs\".\n\nRequire Import String Lists.List.\nImport ListNotations.\nOpen Scope string.\nOpen Scope list.\nFrom Utils Require Import Utils.\nFrom Pyrosome Require Import Theory.Core Elab.Elab Elab.ElabCompilers Tools.Matches.\nFrom Pyrosome.Lang Require Import SimpleVSubst SimpleVSTLC SimpleVCPS SimpleVFix SimpleVFixCPS SimpleVCC SimpleUnit.\nImport Core.Notations.\n(*TODO: repackage this in compilers*)\nImport CompilerDefs.Notations.\n\nRequire Coq.derive.Derive.\n\n\nDefinition fix_cc_lang_def : lang :=\n  {[l/subst\n  [:| \"G\" : #\"env\",\n      \"B\" : #\"ty\",\n      \"vf\" : #\"val\" \"G\" (#\"neg\" (#\"prod\" (#\"neg\" \"B\") \"B\"))\n      -----------------------------------------------\n      #\"fix\" \"vf\" : #\"val\" \"G\" (#\"neg\" \"B\")\n   ];\n  [:= \"G\" : #\"env\",\n      \"B\" : #\"ty\",\n      \"v\" : #\"val\" \"G\" (#\"neg\" (#\"prod\" (#\"neg\" \"B\") \"B\")),\n      \"v'\" : #\"val\" \"G\" \"B\"\n      ----------------------------------------------- (\"fix_beta\")\n      #\"jmp\" (#\"fix\" \"v\") \"v'\"\n      = #\"jmp\" \"v\" (#\"pair\" (#\"fix\" \"v\") \"v'\")\n      : #\"blk\" \"G\"\n  ]]}.\n\nDerive fix_cc_lang\n       SuchThat (elab_lang_ext (cc_lang++prod_cc ++ cps_prod_lang ++ block_subst ++value_subst)\n                               fix_cc_lang_def\n                               fix_cc_lang)\n       As fix_cc_wf.\nProof. auto_elab. Qed.\n#[export] Hint Resolve fix_cc_wf : elab_pfs.\n\n\n\n\nDefinition fix_cc_def : compiler :=\n  match # from (fix_cps_lang) with\n  | {{e #\"fix\" \"G\" \"A\" \"e\"}} =>\n    {{e #\"fix\" (#\"closure\" (#\"prod\" (#\"neg\" \"A\") \"A\")\n                 (#\"blk_subst\" (#\"snoc\" #\"forget\"\n                                 (#\"pair\"\n                                   (#\"pair\" (#\".1\" #\"hd\")\n                                     (#\".1\" (#\".2\" #\"hd\")))\n                                   (#\".2\" (#\".2\" #\"hd\"))))\n                                 \"e\") #\"hd\")}}\n  end.\n\n\n(*\nLemma term_rw_lhs_nth {V} `{Eqb V} (l : Rule.lang V) c t t'' s1 e e1 e2 s1_pre s1_post name\n  : wf_lang l ->\n    s1 = s1_pre ++ e1::s1_post ->\n    eq_term l c t'' e1 e2 ->\n    eq_term l c t (con name (s1_pre ++ e2::s1_post)) e ->\n    eq_term l c t (con name s1) e.\nProof.\n  intros; subst.\n  eapply eq_term_trans; eauto.\n  (*TODO: conv-stable inversion*)\nAdmitted.\n *)\n\nDerive fix_cc\n       SuchThat (elab_preserving_compiler (cc++prod_cc_compile++subst_cc)\n                                          (fix_cc_lang\n                                             ++ cc_lang\n                                             ++ forget_eq_wkn\n                                             ++ unit_eta\n                                             ++ unit_lang\n                                             ++ prod_cc\n                                             ++ cps_prod_lang\n                                             ++ block_subst\n                                             ++value_subst)\n                                          fix_cc_def\n                                          fix_cc\n                                          fix_cps_lang)\n       As fix_cc_preserving.\nProof.\n  auto_elab_compiler.\n  cleanup_elab_after\n    (reduce;\n     term_cong; try term_refl;\n     unfold Model.eq_term;\n     eapply eq_term_trans;\n     [eapply eq_term_sym;\n      eredex_steps_with cc_lang \"clo_eta\"|];\n     by_reduction).\nQed.\n#[export] Hint Resolve fix_cc_preserving : elab_pfs.\n", "meta": {"author": "DIJamner", "repo": "pyrosome", "sha": "a8d7f0aa3141b35a3c59d8d72aadf47a3b0c5df6", "save_path": "github-repos/coq/DIJamner-pyrosome", "path": "github-repos/coq/DIJamner-pyrosome/pyrosome-a8d7f0aa3141b35a3c59d8d72aadf47a3b0c5df6/src/Pyrosome/Lang/SimpleVFixCC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23694470687472416}}
{"text": "From Coq Require Import\n     List\n     ssreflect\n.\n\nFrom ExtensibleCompiler.Theory Require Import\n     Algebra\n     Environment\n     Eval\n     Functor\n     ProgramAlgebra\n     SubFunctor\n     Sum1\n     Types\n     UniversalProperty\n.\n\nLocal Open Scope SubFunctor.\n\nInductive Closure\n          L\n          `{F : forall V, Functor (L V)} `{FL : forall V, Functor (L V)}\n          E\n  : Set :=\n| MkClosure (closure : WellFormedValue (L nat)) (environment : Environment E)\n.\nArguments MkClosure {L F FL E}.\n\nGlobal Instance Functor__Closure\n       {L} `{F : forall V, Functor (L V)} `{FL : forall V, Functor (L V)}\n  : Functor (Closure L).\nProof.\n  refine {| fmap := fun A B f '(MkClosure c e) => MkClosure c (map f e) |}.\n  - move => ? [] c e.\n    rewrite map_id //.\n  - move => ????? [] c e.\n    rewrite map_map //.\nDefined.\n\nDefinition closure\n           {L V} `{F : forall V, Functor (L V)} `{FL : forall V, Functor (L V)}\n           `{(L V) supports (Closure L)}\n           c e\n  : WellFormedValue (L V)\n  := injectUP' (MkClosure c e).\n\nDefinition closureF\n           {L V} `{F : forall V, Functor (L V)} `{FL : forall V, Functor (L V)}\n           `{(L V) supports (Closure L)}\n           c e\n  : Fix (L V)\n  := proj1_sig (closure c e).\n\nGlobal Instance FoldUP'__closure\n       {L V} `{F : forall V, Functor (L V)} `{FL : forall V, Functor (L V)}\n       `{(L V) supports (Closure L)}\n       c e\n  : FoldUP' (closureF c e)\n  := proj2_sig (closure c e).\n\nDefinition isClosure\n           {L V} `{F : forall V, Functor (L V)} `{FL : forall V, Functor (L V)}\n           `{(L V) supports (Closure L)}\n  : Fix (L V) -> option _\n  := fun v =>\n       match projectUP' (F := Closure L) v with\n       | Some (MkClosure f e) => Some (f, e)\n       | None                 => None\n       end.\n", "meta": {"author": "Ptival", "repo": "extensible-nanopass-compiler", "sha": "4b496b16296691156ca811d7319cebc8de935d62", "save_path": "github-repos/coq/Ptival-extensible-nanopass-compiler", "path": "github-repos/coq/Ptival-extensible-nanopass-compiler/extensible-nanopass-compiler-4b496b16296691156ca811d7319cebc8de935d62/Syntax/Terms/Closure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2369447012810516}}
{"text": "Require Import stdpp.namespaces.\nRequire Import VST.veric.invariants.\nRequire Import VST.msl.ghost_seplog.\nRequire Import VST.msl.sepalg_generators.\nRequire Import VST.veric.compcert_rmaps.\nRequire Import VST.concurrency.conclib.\nRequire Export VST.concurrency.ghostsI.\nRequire Import VST.veric.bi.\nRequire Import VST.msl.sepalg.\nRequire Import List.\nImport Ensembles.\n\n#[export] Notation iname := iname.\n\nLemma coPset_to_Ensemble_minus : forall E1 E2, coPset_to_Ensemble (E1 ∖ E2) = Setminus (coPset_to_Ensemble E1) (coPset_to_Ensemble E2).\nProof.\n  intros; unfold coPset_to_Ensemble.\n  apply Extensionality_Ensembles; split; intros ? Hin; unfold In in *.\n  - apply elem_of_difference in Hin as []; constructor; auto.\n  - inv Hin. apply elem_of_difference; auto.\nQed.\n\nLemma coPset_to_Ensemble_single : forall x, coPset_to_Ensemble {[Pos.of_nat (S x)]} = Singleton x.\nProof.\n  intros; unfold coPset_to_Ensemble.\n  apply Extensionality_Ensembles; split; intros ? Hin; unfold In in *.\n  - apply elem_of_singleton in Hin.\n    apply (f_equal Pos.to_nat) in Hin.\n    rewrite -> !Nat2Pos.id in Hin by auto; inv Hin; constructor.\n  - inv Hin.\n    apply elem_of_singleton; auto.\nQed.\n\n(* recapitulating Iris \"semantic invariants\" so we can use custom namespaces. *)\nDefinition inv (N : namespace) (P : mpred) : mpred := \n  □ ∀ E, ⌜↑N ⊆ E⌝ → |={E,E ∖ ↑N}=> ▷ P ∗ (▷ P ={E ∖ ↑N,E}=∗ emp).\n\nDefinition own_inv (N : namespace) (P : mpred) :=\n    ∃ i, ⌜Pos.of_nat (S i) ∈ (↑N:coPset)⌝ ∧ invariant i P.\n\nLemma own_inv_acc E N P :\n  ↑N ⊆ E → own_inv N P |-- |={E,E∖↑N}=> ▷ P ∗ (▷ P ={E∖↑N,E}=∗ emp).\nProof.\n  intros.\n  iDestruct 1 as (i) \"[% HiP]\".\n  iPoseProof (inv_open (coPset_to_Ensemble E) with \"HiP\") as \"H\".\n  { unfold Ensembles.In, coPset_to_Ensemble; set_solver. }\n  iAssert (|={E,E ∖ {[Pos.of_nat (S i)]}}=> |> P * (|> P -* |={E ∖ {[Pos.of_nat (S i)]},E}=> emp)) with \"[H]\" as \"H\".\n  { unfold fupd, bi_fupd_fupd; simpl.\n    rewrite coPset_to_Ensemble_minus coPset_to_Ensemble_single; auto. }\n  iMod \"H\"; iApply fupd_mask_intro; first by set_solver.\n  iIntros \"mask\".\n  iDestruct \"H\" as \"[$ H]\"; iIntros \"?\".\n  iMod \"mask\"; iMod (\"H\" with \"[$]\"); auto.\nQed.\n\nLemma fresh_inv_name n N : ∃ i, (n <= i)%nat /\\ Pos.of_nat (S i) ∈ (↑N:coPset).\nProof.\n  pose proof (coPpick_elem_of (↑ N ∖ gset_to_coPset (list_to_set (map (fun i => Z.to_pos (i + 1)) (upto n))))).\n  rewrite elem_of_difference in H; destruct H as [HN H].\n  { apply coPset_infinite_finite, difference_infinite, gset_to_coPset_finite.\n    apply coPset_infinite_finite, nclose_infinite. }\n  exists (Pos.to_nat (coPpick (↑ N ∖ gset_to_coPset (list_to_set (map (fun i => Z.to_pos (i + 1)) (upto n))))) - 1)%nat; split.\n  - match goal with |-(?a <= ?b)%nat => destruct (le_lt_dec a b); auto; exfalso end.\n    apply H, elem_of_gset_to_coPset, elem_of_list_to_set, elem_of_list_In, in_map_iff.\n    apply Nat2Z.inj_lt in l.\n    setoid_rewrite In_upto; eexists; split; [|split; [|apply l]]; lia.\n  - destruct (eq_dec (coPpick (↑N ∖ gset_to_coPset (list_to_set (map (λ i : Z, Z.to_pos (i + 1)) (upto n))))) 1%positive).\n    + rewrite e in HN |- *; auto.\n    + rewrite -> Nat2Pos.inj_succ, Nat2Pos.inj_sub, Pos2Nat.id, Positive_as_OT.sub_1_r, Pos.succ_pred; auto; lia.\nQed.\n\nLemma own_inv_alloc N E P : ▷ P |-- |={E}=> own_inv N P.\nProof.\n  iIntros \"HP\".\n  iPoseProof (inv_alloc_strong _ _ (fun i => Pos.of_nat (S i) ∈ (↑N : coPset)) with \"HP\") as \"H\";\n    auto using fresh_inv_name.\nQed.\n\nGlobal Instance agree_persistent g P : Persistent (agree g P : mpred).\nProof.\n  apply core_persistent; auto.\nQed.\n\nLemma own_inv_to_inv M P: own_inv M P |-- inv M P.\nProof.\n  iIntros \"#I !>\". iIntros (E H).\n  iPoseProof (own_inv_acc with \"I\") as \"H\"; eauto.\nQed.\n\nGlobal Instance inv_persistent N P : Persistent (inv N P).\nProof.\n  apply _.\nQed.\n\nGlobal Instance inv_affine N P : Affine (inv N P).\nProof.\n  apply _.\nQed.\n\nLemma invariant_dup : forall N P, inv N P = (inv N P * inv N P)%logic.\nProof.\n  intros; apply pred_ext; rewrite <- (bi.persistent_sep_dup (inv N P)); auto.\nQed.\n\nLemma agree_join : forall g P1 P2, agree g P1 * agree g P2 |-- (|> P1 -* |> P2) * agree g P1.\nProof.\n  constructor; apply agree_join.\nQed.\n\nLemma agree_join2 : forall g P1 P2, agree g P1 * agree g P2 |-- (|> P1 -* |> P2) * agree g P2.\nProof.\n  constructor; apply agree_join2.\nQed.\n\nLemma inv_alloc : forall N E P, |> P |-- |={E}=> inv N P.\nProof.\n  intros; iIntros \"?\"; iApply own_inv_to_inv; iApply own_inv_alloc; auto.\nQed.\n\nLemma make_inv : forall N E P Q, (P |-- Q) -> P |-- |={E}=> inv N Q.\nProof.\n  intros.\n  eapply derives_trans, inv_alloc; auto.\n  eapply derives_trans, now_later; auto.\nQed.\n\nGlobal Instance into_inv_inv N P : IntoInv (inv N P) N := {}.\n\n#[export] Instance into_acc_inv N P E:\n  IntoAcc (X := unit) (inv N P)\n          (↑N ⊆ E) emp (updates.fupd E (E ∖ ↑N)) (updates.fupd (E ∖ ↑N) E)\n          (λ _ : (), (▷ P)%I) (λ _ : (), (▷ P)%I) (λ _ : (), None).\nProof.\n  rewrite /inv /IntoAcc /accessor bi.exist_unit.\n  intros; iIntros \"#I _\".\n  iMod (\"I\" with \"[%]\"); auto.\nQed.\n\n(* up *)\nLemma persistently_nonexpansive : nonexpansive persistently.\nProof.\n  intros; unfold nonexpansive, persistently.\n  intros; split; intros ?????; simpl in *; eapply (H (core a'')); eauto;\n    rewrite level_core; apply necR_level in H1; apply ext_level in H2; lia.\nQed.\n\nLemma persistently_nonexpansive2 : forall f, nonexpansive f ->\n  nonexpansive (fun a => persistently (f a)).\nProof.\n  intros; unfold nonexpansive.\n  intros; eapply predicates_hered.derives_trans; [apply H|].\n  apply persistently_nonexpansive.\nQed.\n\nLemma bupd_nonexpansive : nonexpansive own.bupd.\nProof.\n  unfold nonexpansive, own.bupd; split; simpl; intros;\n    apply H3 in H4 as (? & ? & ? & ? & ? & ? & ?); do 2 eexists; eauto; do 2 eexists; eauto;\n    repeat (split; auto); eapply (H x0); eauto; apply necR_level in H1; apply ext_level in H2; lia.\nQed.\n\nLemma bupd_nonexpansive2 : forall f, nonexpansive f ->\n  nonexpansive (fun a => own.bupd (f a)).\nProof.\n  intros; unfold nonexpansive.\n  intros; eapply predicates_hered.derives_trans; [apply H|].\n  apply bupd_nonexpansive.\nQed.\n\nLemma fupd_nonexpansive1 : forall E1 E2, nonexpansive (fupd.fupd E1 E2).\nProof.\n  unfold fupd.fupd, nonexpansive; intros.\n  apply (contractive.wand_nonexpansive (fun _ => wsat * ghost_set g_en E1)%pred\n    (fun P => (|==> |> predicates_hered.FF || wsat * ghost_set g_en E2 * P)%pred)\n    (const_nonexpansive _)).\n  apply bupd_nonexpansive2, @disj_nonexpansive, sepcon_nonexpansive, identity_nonexpansive; apply const_nonexpansive.\nQed.\n\nLemma fupd_nonexpansive2 : forall E1 E2 f, nonexpansive f ->\n  nonexpansive (fun a => fupd.fupd E1 E2 (f a)).\nProof.\n  intros; unfold nonexpansive.\n  intros; eapply predicates_hered.derives_trans; [apply H|].\n  apply fupd_nonexpansive1.\nQed.\n\nLemma later_nonexpansive1 : nonexpansive (box laterM).\nProof.\n  apply contractive_nonexpansive, later_contractive, identity_nonexpansive.\nQed.\n\nLemma inv_nonexpansive : forall N, nonexpansive (inv N).\nProof.\n  intros; unfold inv.\n  unfold bi_intuitionistically, bi_affinely, bi_persistently; simpl.\n  apply @conj_nonexpansive, persistently_nonexpansive2, @forall_nonexpansive; intros.\n  { apply const_nonexpansive. }\n  apply @impl_nonexpansive, fupd_nonexpansive2, sepcon_nonexpansive, contractive.wand_nonexpansive, fupd_nonexpansive2;\n    try apply later_nonexpansive1; apply const_nonexpansive.\nQed.\n\nLemma inv_nonexpansive2 : forall N f, nonexpansive f ->\n  nonexpansive (fun a => inv N (f a)).\nProof.\n  intros; unfold nonexpansive.\n  intros; eapply predicates_hered.derives_trans; [apply H|].\n  apply inv_nonexpansive.\nQed.\n\nGlobal Opaque inv.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/concurrency/invariants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23684230474085102}}
{"text": "Require Export generic synt_and_sos main_defs prog_reductions guarantees.\n\nLemma stengthening :\n  forall R R' G G' P P' Q Q' c,\n    assrtImp P P' ->\n    assrtImp Q' Q ->\n    rstImp R R' ->\n    rstImp G' G ->\n    [|R',G'|] |= [|P'|] c [|Q'|] ->\n    HG_val' R G P c Q.\nProof.\n  intros *.\n  intros Hp Hq Hr Hg.\n  intro.\n  red.\n  intros .\n  split.\n  intros.\n  dependent induction H1.\n  apply Hp in H0.\n  pose proof H _ H0.\n  destruct H1.\n  apply Hq.\n  apply H1.\n  constructor.\n  apply Hp in H0.\n  apply H in H0.\n  destruct H0.\n  apply Hq.\n  apply H0.\n  destruct H2.\n\n  constructor 2 with y.\n  left;auto.\n  eapply star_n_impl.\n  apply Hr.\n  assumption.\n  destruct H2.\n  simpl in *.\n  subst.\n  destruct y;simpl in *.\n  constructor 2 with (s,s0).\n  right;split;auto.\n  eapply star_n_impl.\n  apply Hr.\n  assumption.\n\n  red;intros.\n  apply Hg.\n  apply Hp in H0.\n  pose proof H _ H0.\n  destruct H4.\n  eapply H5.\n  eapply star_n_impl.\n  apply Hr.\n  apply H2.\n  apply H3.\nQed.\n\nLemma aver :\n  forall P c G Q,\n    triple G P c Q -> G_val P c G Q.\nProof.\n  induction 1;intros.\n  red;intros.\n  apply star_skip_means_R_star in H0.\n  apply reflexive_ID_eq in H0.\n  subst.\n  split;auto.\n\n  red;intros.\n  inv H1.\n  destruct2 y H2.\n  inv H2.\n  apply star_skip_means_R_star in H3.\n  apply reflexive_ID_eq in H3.\n  subst.\n  split;eauto.\n  \n  destruct H2.\n  simpl in *.\n  subst.\n  red in H4.\n  subst.\n  apply reflexive_assg_G_val in H3.\n  subst.\n  split;eauto.\n\n  assert(stable ID ([T]b)).\n  red.\n  intros.\n  destruct H1.\n  red in H2.\n  subst.\n  assumption.\n\n  red;intros.\n  destruct(b2assrt_dec b x).\n  assert((([T]b)[/\\]P) x).\n  split;auto.\n  pose proof IHtriple1 _ H4.\n  apply H5.\n  \n  pose proof star_if_inv_true ID b c1 c2 x s' H1 H3 b0.\n  assumption.\n\n  assert(stable ID ([F]b)).\n  red.\n  intros.\n  destruct H4.\n  red in H5.\n  subst.\n  assumption.\n\n  assert((([F]b)[/\\]P) x) by (split;auto).\n  pose proof IHtriple2 _ H5.\n  apply H6.\n  pose proof star_if_inv_false ID b c1 c2 x s' H4 H3 n.\n  assumption.\n\n  red;intros.\n  pose proof IHtriple1 _ H1.\n  apply sequence_reduces_in_parts_3 in H2.\n  destruct H2.\n  destruct H2.\n  pose proof H3 _ H2.\n  destruct H5.\n  pose proof IHtriple2 _ H5 _ H4.\n  destruct H7.\n  split;eauto.\n  eapply star_trans.\n  apply H6.\n  assumption.\n  red;intros.\n  apply H in H3.\n  apply IHtriple in H3.\n  apply H3 in H4.\n  destruct H4.\n  apply H0 in H4.\n  split;auto.\n  eapply star_R_star_incl.\n  apply H1.\n  assumption.\n\n  red;intros.\n  eapply hoare_while_ID;eauto.\nQed.\n\nSection Sequential_Hoare_soundness.\n\n(** End Sequential_Hoare_soundness. *)\n\nLemma auxy :\n  forall Rl Gl Rr Gr s0 s',\n    star st (rstAnd Rl Rr) s0 s' ->\n    star _ (rstAnd (rstOr Rl Gl) (rstOr Rr Gr)) s0 s'.\nProof.\n  intros *.\n  induction 1;auto.\n  destruct H0.\n  econstructor 2 with x0.\n  destruct H.\n  split.\n  left;auto.\n  left;auto.\n  constructor.\n  destruct H.\n  destruct H0.\n  constructor 2 with x0.\n  split;auto.\n  left;auto.\n  left;auto.\n  assumption.\nQed.\n\n(* Lemma soundness_rg_skip : *)\n(*   forall R : Env, forall G : relation st, forall P : assrt, *)\n(*     forall H : Reflexive G, forall H0 : stable R P, forall x : st, forall H1 : P x, *)\n(*       (∀s' : st, star (stmt * st) (prog_red R) (skip, x) (skip, s') → P s') *)\n(*         ∧ << R, G, skip, x >>. *)\n(* Proof. *)\n(*   split;intros. *)\n(*   apply star_skip_means_R_star in H2. *)\n(*   pose proof stable_star _ _ H0. *)\n(*   eapply H3;eauto. *)\n  \n(*   apply guarantee_SKIP. *)\n(* Qed. *)\n\n(* Lemma soundness_rg_assg : *)\n(*   forall (v : id)(a : aexp)(P : assrt)(R : Env)(Q : assrt)(G : Env), *)\n(*     forall (H : stable R P)(H0 : stable R Q)(H1 : ∀s : st, G s (s) [v <== aeval s a]), *)\n(*       forall (H2 : ∀s : st, P s → Q (s) [v <== aeval s a])(x : st)(H3 : P x), *)\n(*    (∀s' : st, star (stmt * st) (prog_red R) (v ::= a, x) (skip, s') → Q s') *)\n(*    ∧ << R, G, v ::= a, x >>. *)\n(* Proof. *)\n(*   split;intros. *)\n\n(*   do_star2starn H4. *)\n(*   revert n x H3 s' H4. *)\n(*   induction n;intros. *)\n(*   inv H4. *)\n(*   inv H4. *)\n(*   destruct2 y H6. *)\n(*   inv H5. *)\n(*   do_starn2star H7. *)\n(*   apply star_skip_means_R_star in H6. *)\n(*   pose proof stable_star _ _ H0. *)\n(*   eapply H7. *)\n(*   split. *)\n(*   2:apply H6. *)\n(*   apply H2. *)\n(*   assumption. *)\n(*   destruct H5. *)\n(*   simpl in *. *)\n(*   rewrite <- H5 in H7. *)\n(*   assert(P s0). *)\n(*   eapply H. *)\n(*   split;eauto. *)\n(*   pose proof IHn s0 H8 s' H7. *)\n(*   assumption. *)\n \n(*   red;intros. *)\n(*   do_star2starn H4. *)\n(*   revert n x H3 y c' c'' z H5 H4. *)\n(*   induction n;intros. *)\n(*   inv H4. *)\n(*   inv H5. *)\n(*   apply H1. *)\n(*   inv H4. *)\n(*   destruct2 y0 H7. *)\n(*   inv H6. *)\n(*   apply starn_skip_skip in H8. *)\n(*   subst. *)\n(*   inv H5. *)\n(*   destruct H6. *)\n(*   simpl in *. *)\n(*   rewrite <- H6 in H8. *)\n(*   assert(P s0). *)\n(*   eapply H. *)\n(*   split;eauto. *)\n(*   pose proof IHn _ H9 _ _ _ _ H5 H8. *)\n(*   assumption. *)\n(* Qed. *)\n\n(* Lemma soundness_rg_atom : *)\n(*   forall (R : Env)(G : Env)(P : assrt)(Q : assrt)(c : stmt)(H : Reflexive G), *)\n(*     forall (H0 : ∀x y : st, star st G x y → G x y)(H1 : stable R P)(H2 : stable R Q), *)\n(*       forall (H3 : G_val P c G Q)(x : st)(H4 : P x), *)\n(*    (∀s' : st, star (stmt * st) (prog_red R) (atomic(c), x) (skip, s') → Q s') *)\n(*    ∧ << R, G, atomic(c), x >>. *)\n(* Proof. *)\n(*   split; *)\n(*   intros. *)\n(*   apply star_does_atomic_inv in H5. *)\n(*   destruct H5 as [s1 [s2 [H6 [H7 H8]]]]. *)\n(*   pose proof stable_star _ _ H2. *)\n(*   eapply H5. *)\n(*   split. *)\n(*   2:apply H8. *)\n(*   assert(P s1).  *)\n(*   pose proof stable_star _ _ H1. *)\n(*   eapply H9;eauto. *)\n(*   pose proof H3 _ H9 s2 H7. *)\n(*   destruct H10. *)\n(*   assumption. *)\n\n(*   red;intros. *)\n(*   pose proof H5. *)\n(*   apply atomic_implies_skip in H5. *)\n(*   destruct H5. *)\n(*   subst. *)\n(*   pose proof red_atomic_imp_skip _ _ _ _ H6. *)\n(*   subst. *)\n(*   apply red_atomic_implies_cstep in H6. *)\n(*   pose proof star_does_atomic R c z y H6. *)\n(*   pose proof atomic_atomic_implies_Rstar _ _ _ _ H7. *)\n(*   clear H5. *)\n(*   assert(P y). *)\n(*   pose proof stable_star _ _ H1. *)\n(*   eapply H5. *)\n(*   split;eauto. *)\n(*   pose proof H3 _ H5 _ H6. *)\n(*   destruct H9. *)\n(*   apply H0 in H10. *)\n(*   assumption. *)\n(*   subst. *)\n(*   inv H6. *)\n(* Qed. *)\n\n(* Lemma soundness_rg_if : *)\n(*   forall (R : Env)(G : Env)(P : assrt)(c1 : stmt)(c2 : stmt)(Q : assrt)(b : bexp), *)\n(*     forall (H : Reflexive G)(H0 : stable R ([T]b))(H1 : stable R ([F]b))(H2 : stable R P), *)\n(*       forall (H3 : [| R , G |] |- [| ([T]b)[/\\]P |] c1 [| Q |]), *)\n(*         forall (H4 : [| R , G |] |- [| ([F]b)[/\\]P |] c2 [| Q |]), *)\n(*           forall (IHtriple_rg1 : [| R , G |] |= [| ([T]b)[/\\]P |] c1 [| Q |]), *)\n(*             forall (IHtriple_rg2 : [| R , G |] |= [| ([F]b)[/\\]P |] c2 [| Q |])(x : st)(H5 : P x), *)\n(*    (∀s' : st, *)\n(*     star (stmt * st) (prog_red R) (ifb b then c1 else c2 fi, x) (skip, s') *)\n(*     → Q s') ∧ << R, G, ifb b then c1 else c2 fi, x >>. *)\n(* Proof. *)\n(*   split;intros. *)\n(*   dependent induction H6. *)\n(*   destruct2 y H7. *)\n(*   inv H7. *)\n(*   assert((([F]b)[/\\]P) s0). *)\n(*   split;auto. *)\n(*   pose proof IHtriple_rg2 s0 H8. *)\n(*   destruct H10. *)\n(*   pose proof H10 _ H6. *)\n(*   assumption. *)\n\n(*   assert((([T]b)[/\\]P) s0). *)\n(*   split;auto. *)\n(*   pose proof IHtriple_rg1 s0 H8. *)\n(*   destruct H10. *)\n(*   apply H10;auto. *)\n(*   destruct H7;simpl in *. *)\n(*   symmetry in H7;subst. *)\n(*   assert(P s0). *)\n(*   eapply H2;split;eauto. *)\n(*   pose proof IHstar c1 c2 b H H0 H1 H2 H3 H4  *)\n(*              IHtriple_rg1 IHtriple_rg2 s0 H7 s' refl_equal refl_equal. *)\n(*   assumption. *)\n \n(*   destruct(b2assrt_dec b x) as [Bt | Bf]; *)\n(*              [ assert((assrtT b[/\\]P) x) by (split;auto) |  *)\n(*                assert((assrtF b[/\\]P) x) by (split;auto)]; *)\n(*              [ pose proof (IHtriple_rg1 _ H6) as H7 |  *)\n(*                pose proof (IHtriple_rg2 _ H6) as H7 ];destruct H7. *)\n(*   eapply within_if_true;auto. *)\n(*   eapply within_if_false;auto. *)\n(* Qed. *)\n\n(* Lemma soundness_rg_seq : *)\n(*   forall (R : Env)(G : Env)(c1 : stmt)(c2 : stmt)(P : assrt)(K : assrt)(Q : assrt), *)\n(*     forall (H : Reflexive G)(H0 : [| R , G |] |- [| P |] c1 [| K |]), *)\n(*       forall (H1 : [| R , G |] |- [| K |] c2 [| Q |]), *)\n(*         forall (IHtriple_rg1 : [| R , G |] |= [| P |] c1 [| K |]), *)\n(*           forall (IHtriple_rg2 : [| R , G |] |= [| K |] c2 [| Q |])(x : st)(H2 : P x), *)\n(*    (∀s' : st, star (stmt * st) (prog_red R) (c1; c2, x) (skip, s') → Q s') *)\n(*    ∧ << R, G, c1; c2, x >>. *)\n(* Proof. *)\n(*   split;intros. *)\n\n(*   apply sequence_reduces_in_parts_3 in H3. *)\n(*   destruct H3 as [s [H4 H5]]. *)\n(*   pose proof IHtriple_rg1 _ H2. *)\n(*   destruct H3. *)\n(*   apply H3 in H4. *)\n(*   pose proof IHtriple_rg2 _ H4. *)\n(*   destruct H7. *)\n(*   apply H7;auto. *)\n\n(*   eapply within_seq. *)\n(*   apply H. *)\n(*   pose proof IHtriple_rg1 _ H2. *)\n(*   destruct H3. *)\n(*   assumption. *)\n(*   pose proof IHtriple_rg1 _ H2. *)\n(*   destruct H3. *)\n(*   intros. *)\n(*   do_starn2star H5. *)\n(*   apply H3 in H6. *)\n(*   pose proof IHtriple_rg2 _ H6. *)\n(*   destruct H5. *)\n(*   assumption. *)\n(* Qed. *)\n\n(* Lemma soundness_rg_conseq : *)\n(*   forall (R : Env)(R' : Env)(G : Env)(G' : Env)(P : assrt)(P' : assrt)(Q : assrt)(Q' : assrt), *)\n(*     forall (c : stmt)(H : [| R' , G' |] |- [| P' |] c [| Q' |])(H0 : P[->]P')(H1 : Q'[->]Q), *)\n(*       forall (H2 : rstImp R R')(H3 : rstImp G' G), *)\n(*       forall (IHtriple_rg : [| R' , G' |] |= [| P' |] c [| Q' |])(x : st)(H4 : P x), *)\n(*    (∀s' : st, star (stmt * st) (prog_red R) (c, x) (skip, s') → Q s') *)\n(*    ∧ << R, G, c, x >>. *)\n(* Proof. *)\n(*   split; *)\n(*   pose proof stengthening R R' G G' P P' Q Q' c H0 H1 H2 H3 IHtriple_rg. *)\n(*   apply H5 in H4. *)\n(*   destruct H4. *)\n(*   assumption. *)\n\n(*   pose proof stengthening R R' G G' P P' Q Q' c H0 H1 H2 H3 IHtriple_rg. *)\n(*   apply H5 in H4. *)\n(*   destruct H4. *)\n(*   assumption. *)\n(* Qed. *)\n\n(* Lemma soundness_rg_while : *)\n(*   forall (R : Env)(G : Env)(P : assrt)(b : bexp)(c : stmt), *)\n(*     forall (H : Reflexive G)(H0 : stable R ([T]b))(H1 : stable R ([F]b))(H2 : stable R P), *)\n(*       forall (H3 : [| R , G |] |- [| ([T]b)[/\\]P |] c [| P |]), *)\n(*         forall (IHtriple_rg : [| R , G |] |= [| ([T]b)[/\\]P |] c [| P |])(x : st)(H4 : P x), *)\n(*    (∀s' : st, *)\n(*     star (stmt * st) (prog_red R) (while b do c end, x) (skip, s') *)\n(*     → (([F]b)[/\\]P) s') ∧ << R, G, while b do c end, x >>. *)\n(* Proof. *)\n(*   split. eapply hoare_while;eauto.  admit. *)\n(* Qed. *)\n\n(* Lemma soundness_rg_par : *)\n(*   forall (R : Env)(Rl : Env)(Rr : Env)(Gl : Env)(Gr : Env)(G : Env)(P : assrt)(Q1 : assrt), *)\n(*     forall (Q2 : assrt)(cr : stmt)(cl : stmt)(H : Reflexive Gl)(H0 : Reflexive Gr), *)\n(*       forall (H1 : rstImp (rstOr Gl Gr) G)(H2 : rstImp (rstOr Rl Gl) Rr), *)\n(*       forall (H3 : rstImp (rstOr Rr Gr) Rl)(H4 : stable (rstOr Rr Gr) Q1), *)\n(*         forall (H5 : stable (rstOr Rl Gl) Q2)(H6 : stable (rstOr Rr Gr) P), *)\n(*           forall (H7 : stable (rstOr Rl Gl) P)(H8 : [| Rl , Gl |] |- [| P |] cl [| Q1 |]), *)\n(*             forall (H9 : [| Rr , Gr |] |- [| P |] cr [| Q2 |]), *)\n(*               forall (IHtriple_rg1 : [| Rl , Gl |] |= [| P |] cl [| Q1 |]), *)\n(*                 forall (IHtriple_rg2 : [| Rr , Gr |] |= [| P |] cr [| Q2 |]), *)\n(*                   forall (x : st)(H10 : P x), *)\n(*    (∀s' : st, *)\n(*     star (stmt * st) (prog_red (rstAnd Rl Rr)) (par cl with cr end, x) *)\n(*       (skip, s') → (Q1[/\\]Q2) s') *)\n(*    ∧ << rstAnd Rl Rr, G, par cl with cr end, x >>. *)\n(* Proof. *)\n(* split. *)\n(*   intros. *)\n(*   pose proof IHtriple_rg1 _ H10. *)\n(*   pose proof IHtriple_rg2 _ H10. *)\n(*   destruct H12. *)\n(*   destruct H13. *)\n(*   pose proof par_reduces_to_skip_left Rl Rr Gl Gr cl cr x s' H2 H3 H14 H15 H11. *)\n(*   destruct H16. *)\n(*   destruct H16. *)\n(*   destruct H16. *)\n(*   destruct H17. *)\n(*   assert(<<Rr,Gr,x0,x1>>). *)\n(*   eapply within_prog_red_star. *)\n(*   apply H18. *)\n(*   assumption. *)\n(*   pose proof within_par_skip_left _ _ _ _ H0 H19. *)\n(*   pose proof rstAnd_split _ _ _ _ H17. *)\n(*   destruct H21. *)\n(*   split. *)\n\n(*   pose proof correct_reduction_wrt_rely_and_guarante _ _ _ _ _ _ H16 H14. *)\n(*   clear H21. *)\n(*   pose proof correct_reduction_wrt_rely_and_guarante _ _ _ _ _ _ H22 H20. *)\n(*   pose proof stable_star _ _ H4. *)\n(*   eapply H24. *)\n(*   split;eauto. *)\n\n(*   pose proof par_reduces_to_skip_right Rl Rr Gl Gr cl cr x s' H2 H3 H14 H15 H11. *)\n(*   destruct H23. *)\n(*   destruct H23. *)\n(*   destruct H23. *)\n(*   destruct H24. *)\n(*   assert(<<Rl,Gl,x2,x3>>). *)\n(*   eapply within_prog_red_star. *)\n(*   apply H25. *)\n(*   assumption. *)\n(*   pose proof within_par_skip_right _ _ _ _ H H26. *)\n(*   pose proof rstAnd_split _ _ _ _ H24. *)\n(*   destruct H28. *)\n\n(*   pose proof correct_reduction_wrt_rely_and_guarante _ _ _ _ _ _ H23 H15. *)\n(*   clear H21. *)\n(*   pose proof correct_reduction_wrt_rely_and_guarante _ _ _ _ _ _ H28 H27. *)\n(*   pose proof stable_star _ _ H5. *)\n(*   eapply H31. *)\n(*   split;eauto. *)\n  \n(*   (** Guarantee parallel. *) *)\n(*   eapply within_par_both. *)\n(*   eapply(rstOr_refl Gl Gr);eauto. *)\n(*   3:apply H1. *)\n(*   pose proof IHtriple_rg1 _ H10. *)\n(*   destruct H11. *)\n(*   clear H11. *)\n(*   eapply guarantee_impl with Rl. *)\n(*   red;intros. *)\n(*   destruct H11. *)\n(*   destruct H11. *)\n(*   apply H11. *)\n(*   assert((rstOr Rr Gr) s s'). *)\n(*   right. *)\n(*   assumption. *)\n(*   apply H3 in H13. *)\n(*   assumption. *)\n(*   assumption. *)\n(*   pose proof IHtriple_rg2 _ H10. *)\n(*   destruct H11. *)\n(*   clear H11. *)\n(*   eapply guarantee_impl with Rr. *)\n(*   red;intros. *)\n(*   destruct H11. *)\n(*   destruct H11. *)\n(*   apply H13. *)\n(*   assert((rstOr Rl Gl) s s'). *)\n(*   right. *)\n(*   assumption. *)\n(*   apply H2 in H13. *)\n(*   assumption. *)\n(*   assumption. *)\n(* Qed. *)\n\nTheorem soundness_rg :\n  forall R G P Q c,\n    [|  R  , G  |]  |- [|  P  |]  c [|  Q  |] ->\n    HG_val' R G  |= [|  P  |]  c [|  Q  |].\nProof.\n  induction 1;red;intros(*;split*).\n\n  (* SKIP *)\n  apply soundness_rg_skip;auto.\n\n  (* Assignment *)\n  eapply soundness_rg_assg with P;auto.\n \n  (* Atomic execution. *)\n  apply soundness_rg_atom with P;auto.\n  \n  (* Conditional *)\n  apply soundness_rg_if with P;auto.\n  \n  (* Sequence *)\n  apply soundness_rg_seq with P K;auto.\n  \n  (* Consequence *)\n  eapply soundness_rg_conseq;eauto.\n  \n  (** While loop *)\n  eapply soundness_rg_while;eauto.\n\n  (** Parallel computation rule *)\n  pose proof soundness_rg_par R Rl Rr Gl Gr G P.\n  apply H11;auto.\nQed.\n\nEnd Sequential_Hoare_soundness.", "meta": {"author": "dmrpereira", "repo": "RGCoq", "sha": "20f6aee522cf744e15011104ba23c99f61d4ce9c", "save_path": "github-repos/coq/dmrpereira-RGCoq", "path": "github-repos/coq/dmrpereira-RGCoq/RGCoq-20f6aee522cf744e15011104ba23c99f61d4ce9c/soundness_alt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.23684229839681964}}
{"text": "(*\n * Copyright (c) 2009-2016, Andrew Appel, Robert Dockins,\n    Aquinas Hobor and Le Xuan Bach\n *\n *)\n\nRequire Import msl.base.\nRequire Import msl.sepalg.\nRequire Import msl.psepalg.\nRequire Import msl.sepalg_generators.\nRequire Import msl.boolean_alg.\nRequire Import msl.eq_dec.\n\nRequire msl.tree_shares.\n\nModule Share : SHARE_MODEL := tree_shares.Share.\nImport Share.\n\nDefinition share : Type := Share.t.\n\nInstance pa_share : Perm_alg share := Share.pa.\nInstance sa_share : Sep_alg share := Share.sa.\nInstance ca_share : Canc_alg share := Share.ca.\nDefinition emptyshare : share := Share.bot.\nDefinition fullshare : share := Share.top.\n\nTheorem leq_join_sub : forall s1 s2:Share.t,\n  s1 <= s2 <-> join_sub s1 s2.\nProof.\n  split; intros.\n  pose (s' := glb s2 (comp s1)).\n  exists s'.\n  simpl; split.\n  subst s'.\n  rewrite glb_commute.\n  rewrite glb_assoc.\n  rewrite (glb_commute (comp s1) s1).\n  rewrite comp2.\n  apply glb_bot.\n  subst s'.\n  rewrite distrib2.\n  rewrite comp1.\n  rewrite glb_top.\n  rewrite <- ord_spec2; auto.\n\n  destruct H as [s' H].\n  destruct H.\n  rewrite ord_spec2.\n  rewrite <- H0.\n  rewrite <- lub_assoc.\n  rewrite lub_idem; auto.\nQed.\n\nLemma top_correct' : forall x:t, join_sub x top.\nProof.\n  intros; rewrite <- leq_join_sub; auto with ba.\nQed.\n\nLemma bot_identity : identity bot.\nProof.\n  hnf; intros.\n  destruct H.\n  rewrite lub_commute in H0.\n  rewrite lub_bot in H0.\n  auto.\nQed.\n\nHint Resolve bot_identity.\n\nLemma identity_share_bot : forall s,\n  identity s -> s = bot.\nProof.\n  intros.\n  apply identities_unique; auto.\n  exists s.\n  apply join_comm.\n\n  destruct (top_correct' s).\n  assert (x = top).\n  apply H; auto.\n  subst x; auto.\n  destruct (top_correct' bot).\n  assert (x = top).\n  apply bot_identity; auto.\n  subst x; auto.\n  apply join_comm in H1.\n  destruct (join_assoc H0 H1); intuition.\n  assert (x = top).\n  apply H; auto.\n  subst x.\n  replace bot with s.\n  rewrite identity_unit_equiv in H.\n  trivial.\n  eapply joins_units_eq; try apply H0. exists top; eauto.\n  simpl. split. apply glb_bot. apply lub_bot.\nQed.\n\nLemma factoryOverlap' : forall f1 f2 n1 n2,\n  isTokenFactory f1 n1 -> isTokenFactory f2 n2 -> joins f1 f2 -> False.\nProof.\n  intros.\n  destruct H1.\n  destruct H1.\n  apply (factoryOverlap f1 f2 n1 n2 H H0 H1).\nQed.\n\nLemma identityToken' : forall x, isToken x 0 <-> identity x.\nProof.\n  intro x; destruct (identityToken x); split; intros.\n  hnf; intros.\n  rewrite H in H2; auto.\n  apply H0.\n  apply identity_share_bot; auto.\nQed.\n\nLemma nonidentityToken' : forall x n, (n > 0)%nat -> isToken x n -> nonidentity x.\nProof.\n  intros.\n  generalize (nonidentityToken x n H H0).\n  repeat intro.\n  apply H1.\n  apply identity_share_bot; auto.\nQed.\n\nLemma nonidentityFactory' : forall x n, isTokenFactory x n -> nonidentity x.\nProof.\n  intros.\n  generalize (nonidentityFactory x n H); repeat intro.\n  apply H0.\n  apply identity_share_bot; auto.\nQed.\n\nLemma split_join : forall x1 x2 x,\n  split x = (x1,x2) -> join x1 x2 x.\nProof.\n  intros; split.\n  apply split_disjoint with x; auto.\n  apply split_together; auto.\nQed.\n\nLemma split_nontrivial' : forall x1 x2 x,\n  split x = (x1, x2) ->\n    (identity x1 \\/ identity x2) ->\n    identity x.\nProof.\n  intros.\n  rewrite (split_nontrivial x1 x2 x H).\n  apply bot_identity.\n  destruct H0.\n  left; apply identity_share_bot; auto.\n  right; apply identity_share_bot; auto.\nQed.\n\nLemma rel_leq : forall a x, join_sub (rel a x) a.\nProof.\n  intros.\n  rewrite <- leq_join_sub.\n\n  intros.\n  rewrite ord_spec1.\n  pattern a at 3.\n  replace a with (rel a top).\n  rewrite <- rel_preserves_glb.\n  rewrite glb_top.\n  auto.\n  apply rel_top1.\nQed.\n\nLemma rel_join : forall a x y z,\n  join x y z ->\n  join (rel a x) (rel a y) (rel a z).\nProof.\n  simpl; intuition. inv H.\n  constructor.\n  rewrite <- rel_preserves_glb.\n  replace bot with (rel a bot).\n  replace (glb x y) with bot; auto.\n  apply rel_bot1.\n  rewrite <- rel_preserves_lub. auto.\nQed.\n\nLemma rel_join2 : forall a x y s,\n  nonidentity a ->\n  join (rel a x) (rel a y) s ->\n  exists z, s = rel a z /\\ join x y z.\nProof.\n  simpl; intros.\n  destruct H0.\n  exists (lub x y).\n  split.\n  rewrite <- H1.\n  symmetry.\n  apply rel_preserves_lub.\n  split; auto.\n  rewrite <- rel_preserves_glb in H0.\n  replace bot with (rel a bot) in H0.\n  apply rel_inj_l with a; auto.\n  hnf; intros; apply H.\n  subst a; apply bot_identity.\n  apply rel_bot1.\nQed.\n\nLemma rel_nontrivial : forall a x,\n  identity (rel a x) ->\n  (identity a \\/ identity x).\nProof.\n  intros a x H.\n  destruct (eq_dec a bot); auto.\n  subst a.\n  left. apply bot_identity.\n\n  right.\n  assert (rel a x = bot).\n  apply identity_share_bot; auto.\n  assert (x = bot).\n  replace bot with (rel a bot) in H0.\n  apply rel_inj_l with a; auto.\n  apply rel_bot1.\n  subst x; apply bot_identity.\nQed.\n\nInstance share_cross_split : Cross_alg t.\nProof.\n  hnf; simpl; intuition. destruct H as [H1 H2]. destruct H0 as [H H3].\n  exists (glb a c, glb a d, glb b c, glb b d); intuition; constructor.\n  rewrite (glb_commute a d).\n  rewrite glb_assoc.\n  rewrite <- (glb_assoc c d a).\n  rewrite H.\n  rewrite (glb_commute bot a).\n  rewrite glb_bot.\n  rewrite glb_bot.\n  auto.\n  rewrite <- distrib1;  rewrite H3; rewrite <- H2; auto with ba.\n  rewrite (glb_commute b d).\n  rewrite glb_assoc.\n  rewrite <- (glb_assoc c d b).\n  rewrite H.\n  rewrite (glb_commute bot b).\n  rewrite glb_bot.\n  rewrite glb_bot.\n  auto.\n  rewrite <- distrib1;  rewrite H3; rewrite <- H2; auto with ba.\n  rewrite (glb_commute a c).\n  rewrite glb_assoc.\n  rewrite <- (glb_assoc a b c).\n  rewrite H1.\n  rewrite (glb_commute bot c).\n  rewrite glb_bot.\n  rewrite glb_bot.\n  auto.\n  rewrite (glb_commute a c).\n  rewrite (glb_commute b c).\n  rewrite <- distrib1; rewrite H2; rewrite <- H3; auto with ba.\n  rewrite (glb_commute a d).\n  rewrite glb_assoc.\n  rewrite <- (glb_assoc a b d).\n  rewrite H1.\n  rewrite (glb_commute bot d).\n  rewrite glb_bot.\n  rewrite glb_bot.\n  auto.\n  rewrite (glb_commute a d).\n  rewrite (glb_commute b d).\n  rewrite <- distrib1; rewrite H2; rewrite <- H3; auto with ba.\nQed.\n\nLemma bot_correct' : forall x, join_sub bot x.\nProof.\n  intros s.\n  destruct (top_correct' s).\n  exists s.\n  destruct (top_correct' bot).\n  assert (x0 = top).\n  apply bot_identity; auto.\n  subst x0.\n  apply join_comm in H0.\n  destruct (join_assoc H H0); intuition.\n  apply join_comm in H2.\n  destruct (join_assoc H1 H2); intuition.\n  assert (s = x1).\n  apply bot_identity; auto.\n  subst x1; auto.\nQed.\n\nLemma top_share_nonidentity : nonidentity top.\nProof.\n  hnf; intros.\n  assert (top = bot).\n  apply identity_share_bot; auto.\n  apply nontrivial; auto.\nQed.\n\nLemma top_share_nonunit: nonunit top.\nProof.\n  repeat intro. unfold unit_for in H.\n  destruct H. rewrite glb_commute in H. rewrite glb_top in H. subst.\n  rewrite lub_bot in H0. apply nontrivial; auto.\nQed.\n\nLemma bot_join_eq : forall x, join bot x x.\nProof.\n  intros.\n  destruct (join_ex_identities x); intuition.\n  destruct H0.\n  generalize (H _ _ H0).\n  intros; subst; auto.\n  replace bot with x0; auto.\n  apply identity_share_bot; auto.\nQed.\n\nLemma join_bot_eq : forall x, join x bot x.\nProof.\n  intros.\n  apply join_comm, bot_join_eq.\nQed.\n\nLemma bot_joins : forall x, joins bot x.\nProof.\n  intro x; exists x; apply bot_join_eq.\nQed.\n\nLemma dec_share_identity : forall x:t, { identity x } + { ~identity x }.\nProof.\n  intro x.\n  destruct (eq_dec x bot); subst.\n  left; apply bot_identity.\n  right; intro; elim n.\n  apply identity_share_bot; auto.\nQed.\n\nLemma dec_share_nonunit : forall x:t, { nonunit x } + { ~ nonunit x }.\nProof.\n  intro x.\n  destruct (dec_share_identity x) as [H | H]; [right | left].\n  + intro; revert H. apply nonunit_nonidentity; auto.\n  + apply nonidentity_nonunit; auto.\nQed.\n\nLemma fullshare_full : full fullshare.\nProof.\n  unfold full.\n  intros.\n  generalize (Share.top_correct);intros.\n  destruct H as [sigma'' ?].\n  spec H0 sigma''.\n  rewrite leq_join_sub in H0.\n  destruct H0.\n  destruct (join_assoc H H0) as [s [H1 H2]].\n  apply join_comm in H2. apply unit_identity in H2.\n  eapply split_identity; eauto.\nQed.\n\nLemma join_sub_fullshare : forall sh,\n  join_sub fullshare sh -> sh = fullshare.\nProof.\n  intros.\n  generalize fullshare_full; intro.\n  apply full_maximal in H0.\n  spec H0 sh H.\n  auto.\nQed.\n\nLemma dec_share_full : forall (sh : Share.t),\n  {full sh} + {~full sh}.\nProof with auto.\n  intro sh.\n  destruct (eq_dec sh top); subst.\n  left. apply fullshare_full.\n  right. intro. apply n.\n  generalize (Share.top_correct sh);intro.\n  apply leq_join_sub in H0.\n  destruct H0.\n  spec H x. spec H. exists top...\n  spec H sh top (join_comm H0)...\nQed.\n\nLemma rel_congruence : forall a x1 x2,\n  join_sub x1 x2 ->\n  join_sub (rel a x1) (rel a x2).\nProof.\n  intros.\n  destruct H.\n  exists (rel a x).\n  apply rel_join; auto.\nQed.\n\nLemma share_split_injective:\n  forall sh1 sh2, Share.split sh1 = Share.split sh2 -> sh1=sh2.\nProof.\n  intros sh1 sh2;\n    case_eq (Share.split sh1); case_eq (Share.split sh2); intros.\n  generalize (split_join _ _ _ H); intro.\n  generalize (split_join _ _ _ H0); intro.\n  inv H1.\n  eapply join_eq; eauto.\nQed.\n\nLemma share_joins_constructive:\n  forall sh1 sh2 : t , joins sh1 sh2 ->  {sh3 | join sh1 sh2 sh3}.\nProof.\n  intros.\n  exists (lub sh1 sh2).\n  destruct H.\n  destruct H; split; auto.\nQed.\n\nLemma share_join_sub_constructive:\n  forall sh1 sh3 : t , join_sub sh1 sh3 ->  {sh2 | join sh1 sh2 sh3}.\nProof.\n  intros.\n  exists (glb sh3 (comp sh1)).\n  destruct H.\n  destruct H.\n  split.\n  rewrite (glb_commute sh3 (comp sh1)).\n  rewrite <- glb_assoc.\n  rewrite comp2.\n  rewrite glb_commute.\n  rewrite glb_bot.\n  auto.\n  rewrite distrib2.\n  rewrite comp1.\n  rewrite glb_top.\n  rewrite <- ord_spec2.\n  rewrite <- H0.\n  apply lub_upper1.\nQed.\n\nLemma triple_join_exists_share : Trip_alg t.\nProof.\n  repeat intro.\n  destruct H; destruct H0; destruct H1.\n  exists (lub a (lub b c)).\n  split.\n  rewrite <- H2.\n  rewrite glb_commute.\n  rewrite distrib1.\n  rewrite glb_commute.\n  rewrite H1.\n  rewrite glb_commute.\n  rewrite H0.\n  rewrite lub_bot; auto.\n  rewrite <- H2.\n  apply lub_assoc.\nQed.\n\nLemma nonemp_split_neq1: forall sh sh1 sh2, nonidentity sh -> split sh = (sh1, sh2) -> sh1 <> sh.\nProof with auto.\n  intros until sh2; intros H H0.\n  destruct (dec_share_identity sh2).\n  generalize (split_nontrivial' _ _ _ H0); intro.\n  spec H1...\n  destruct (eq_dec sh1 sh)...\n  subst sh1.\n  generalize (split_join _ _ _ H0); intro.\n  apply join_comm in H1.\n  apply unit_identity in H1...\nQed.\n\nLemma nonemp_split_neq2: forall sh sh1 sh2, nonidentity sh -> split sh = (sh1, sh2) -> sh2 <> sh.\nProof with auto.\n  intros until sh2; intros H H0.\n  destruct (dec_share_identity sh1).\n  generalize (split_nontrivial' _ _ _ H0); intro.\n  spec H1...\n  destruct (eq_dec sh2 sh)...\n  subst sh2.\n  generalize (split_join _ _ _ H0); intro.\n  apply unit_identity in H1...\nQed.\n\nLemma bot_unit: forall sh,\n  join emptyshare sh sh.\nProof.\n  intro sh.\n  generalize (bot_joins sh); generalize bot_identity; intros.\n  destruct H0.\n  spec H sh x H0. subst.\n  trivial.\nQed.\n\nHint Resolve bot_unit.\n\nLemma join_bot: join emptyshare emptyshare emptyshare.\nProof.\n  apply bot_unit.\nQed.\n\n\nLemma share_rel_nonidentity:\n  forall {sh1 sh2}, nonidentity sh1 -> nonidentity sh2 -> nonidentity (Share.rel sh1 sh2).\nProof.\nintros.\nunfold nonidentity in *.\ngeneralize (rel_nontrivial sh1 sh2); intro. intuition.\nQed.\n\nLemma share_rel_nonunit: forall {sh1 sh2: Share.t},\n       nonunit sh1 -> nonunit sh2 -> nonunit (Share.rel sh1 sh2).\nProof. intros. apply nonidentity_nonunit. apply share_rel_nonidentity.\nintro. apply (@identity_unit _ _ _ sh1 Share.bot) in H1. apply H in H1; auto.\napply joins_comm. apply bot_joins.\nintro. apply (@identity_unit _ _ _ sh2 Share.bot) in H1. apply H0 in H1; auto.\napply joins_comm. apply bot_joins.\nQed.\n\n\nLemma decompose_bijection: forall sh1 sh2,\n sh1 = sh2 <-> decompose sh1 = decompose sh2.\nProof.\n intros.\n split;intros. subst;trivial.\n generalize (recompose_decompose sh1);intro.\n generalize (recompose_decompose sh2);intro.\n congruence.\nQed.\n\nModule ShareMap.\nSection SM.\n  Variable A:Type.\n  Variable EqDec_A : EqDec A.\n\n  Variable B:Type.\n  Variable JB: Join B.\n  Variable paB : Perm_alg B.\n  Variable saB : Sep_alg B.\n\n  Definition map := fpm A (lifted Share.Join_ba * B).\n  Instance Join_map : Join map := Join_fpm _.\n  Instance pa_map : Perm_alg map := Perm_fpm _ _.\n  Instance sa_map : Sep_alg map := Sep_fpm _ _.\n  Instance ca_map {CA: Canc_alg B} : Canc_alg map := Canc_fpm _.\n  Instance da_map {DA: Disj_alg B} : Disj_alg map := @Disj_fpm _ _ _ _.\n\n  Definition map_share (a:A) (m:map) : share :=\n    match lookup_fpm m a with\n    | Some (sh,_) => lifted_obj sh\n    | None => Share.bot\n    end.\n\n  Definition map_val (a:A) (m:map) : option B :=\n    match lookup_fpm m a with\n    | Some (_,b) => Some b\n    | None => None\n    end.\n\n  Definition empty_map : map := empty_fpm _ _.\n\n  Definition map_upd (a:A) (b:B) (m:map) : option map :=\n    match lookup_fpm m a with\n    | Some (sh,_) =>\n        if eq_dec (lifted_obj sh) fullshare\n           then Some (insert_fpm _ a (sh,b) m)\n           else None\n    | None => None\n    end.\n\nLemma join_lifted {t} {J: Join t}:\n    forall (a b c: lifted J), join a b c -> join (lifted_obj a) (lifted_obj b) (lifted_obj c).\nProof. destruct a; destruct b; destruct c; simpl; intros. apply H.\nQed.\n\n  Lemma map_join_char : forall m1 m2 m3,\n    join m1 m2 m3 <->\n    (forall a,\n       join (map_share a m1) (map_share a m2) (map_share a m3) /\\\n       join (map_val a m1) (map_val a m2) (map_val a m3)).\n  Proof with auto.\n    split; intros.\n    hnf in H. spec H a.\n    unfold map_val, map_share, lookup_fpm.\n    destruct (proj1_sig m1 a) as [[sh1 a1] ?| ];\n    destruct (proj1_sig m2 a) as [[sh2 a2] ?| ];\n    destruct (proj1_sig m3 a) as [[sh3 a3] ?| ]; inv H; try solve [inv H0]; simpl; auto.\n    destruct H3; simpl in *; auto.\n    split. apply join_lifted; auto. constructor; auto.\n    split; apply join_unit2; auto.\n    split; apply join_unit1; auto.\n    split; apply join_unit1; auto.\n    split; apply join_unit1; auto.\n\n    intro a. spec H a. destruct H.\n        unfold map_val, map_share, lookup_fpm in *.\n    destruct (proj1_sig m1 a) as [[sh1 a1] ?| ];\n    destruct (proj1_sig m2 a) as [[sh2 a2] ?| ];\n    destruct (proj1_sig m3 a) as [[sh3 a3] ?| ]; inv H0; try solve [inv H1]; auto.\n    constructor. split; auto.\n    apply join_unit2_e in H; auto. apply join_unit2; auto.\n    repeat f_equal. destruct sh1; destruct sh3; simpl in *; subst.\n    rewrite (proof_irr n n0); auto.\n    apply join_unit1_e in H; auto. apply join_unit1; auto.\n    repeat f_equal. destruct sh2; destruct sh3; simpl in *; subst.\n    rewrite (proof_irr n n0); auto.\n    constructor. constructor.\n Qed.\n\n  Lemma empty_map_identity {CAB: Canc_alg B}: identity empty_map.\n  Proof.\n    rewrite identity_unit_equiv.\n    intro x. simpl. auto. constructor.\n  Qed.\n\n  Lemma map_identity_unique {CAB: Canc_alg B}: forall m1 m2:map,\n    identity m1 -> identity m2 -> m1 = m2.\n  Proof.\n    intros.\n    destruct m1; destruct m2; simpl in *.\n    cut (x = x0). intros. subst x0.\n    replace f0 with f; auto.\n    apply proof_irr; auto.\n    rewrite identity_unit_equiv in H, H0.\n    extensionality a.\n    spec H a; spec H0 a.\n    apply lower_inv in H.\n    apply lower_inv in H0.\n    destruct H; destruct H0; simpl in *.\n    intuition; congruence.\n    destruct s0 as [? [? [? [? [? [? ?]]]]]].\n    rewrite H in H1. inv H1. rewrite H0 in H; inv H.\n    destruct x3. destruct H2. simpl in *. apply no_units in H. contradiction.\n    destruct s as [? [? [? [? [? [? ?]]]]]].\n    rewrite H in H0; inv H0. rewrite H1 in H; inv H.\n    destruct x2. destruct H2. simpl in *. apply no_units in H. contradiction.\n    destruct s as [? [? [? [? [? [? ?]]]]]].\n    rewrite H in H0; inv H0. rewrite H1 in H; inv H.\n    destruct x2. destruct H2. simpl in *. apply no_units in H. contradiction.\n  Qed.\n\n  Lemma map_identity_is_empty  {CAB: Canc_alg B} : forall m,\n    identity m -> m = empty_map.\n  Proof.\n    intros; apply map_identity_unique; auto.\n    apply empty_map_identity.\n  Qed.\n\n  Lemma empty_map_join {CAB: Canc_alg B} : forall m,\n    join empty_map m m.\n  Proof.\n    intro m. destruct (join_ex_units m).\n    replace empty_map with x; auto.\n    apply map_identity_is_empty.\n    eapply unit_identity; eauto.\n  Qed.\n\n  Lemma map_val_bot  : forall a m,\n    map_val a m = None <-> map_share a m = Share.bot.\n  Proof.\n    do 2 intro.\n    unfold map_val, map_share, lookup_fpm.\n    destruct (proj1_sig m a); intuition.\n    disc.\n    contradiction (no_units a0 a0). destruct a0. simpl in *. subst.\n    contradiction (n bot). auto.\n  Qed.\n\n  Lemma map_upd_success : forall a v m,\n    map_share a m = Share.top ->\n    exists m', map_upd a v m = Some m'.\n  Proof.\n    intros.\n    unfold map_upd. simpl.\n    unfold map_share, lookup_fpm in*.\n    destruct (proj1_sig  m a).\n    destruct p.\n    rewrite H.\n    unfold fullshare.\n    destruct (eq_dec top top).\n    eauto.\n    elim n; auto.\n    elim Share.nontrivial; auto.\n  Qed.\n\n  Lemma map_set_share1 : forall a v m m',\n    map_upd a v m = Some m' ->\n    map_share a m = Share.top.\n  Proof.\n    unfold map_upd, map_share.\n    intros.\n    destruct (lookup_fpm m a); disc.\n    destruct p.\n    destruct (eq_dec (lifted_obj l) fullshare); disc; auto.\n  Qed.\n\n  Lemma map_set_share2 : forall a v m m',\n    map_upd a v m = Some m' ->\n    map_share a m' = Share.top.\n  Proof.\n    unfold map_upd, map_share.\n    intros. destruct (lookup_fpm m a); disc.\n    destruct p. destruct (eq_dec (lifted_obj l) fullshare); disc.\n    inv H.\n    rewrite fpm_gss. auto.\n  Qed.\n\n  Lemma map_set_share3 : forall a v m m',\n    map_upd a v m = Some m' ->\n    forall a',\n      map_share a' m = map_share a' m'.\n  Proof.\n    unfold map_upd, map_share.\n    intros a v m m'.\n    case_eq (lookup_fpm m a); intros; disc.\n    destruct p.\n    destruct (eq_dec (lifted_obj l) fullshare); disc.\n    inv H0.\n    destruct (eq_dec a a'). subst.\n    rewrite H.\n    rewrite fpm_gss. auto.\n    rewrite fpm_gso; auto.\n  Qed.\n\n  Lemma map_gss_val: forall a v m m',\n        map_upd a v m = Some m' ->\n        map_val a m' = Some v.\n  Proof.\n    unfold map_upd, map_val.\n    intros a v m m'.\n    case_eq (lookup_fpm m a); intros; disc.\n    destruct p.\n    destruct (eq_dec (lifted_obj l) fullshare); disc.\n    inv H0.\n    rewrite fpm_gss. auto.\n  Qed.\n\n  Lemma map_gso_val : forall i j v m m',\n       i <> j ->\n       map_upd j v m = Some m' ->\n       map_val i m = map_val i m'.\n  Proof.\n    unfold map_upd, map_val.\n    intros i j v m m'.\n    case_eq (lookup_fpm m j); intros; disc.\n    destruct p.\n    destruct (eq_dec (lifted_obj l) fullshare); disc.\n    inv H1.\n    rewrite fpm_gso; auto.\n  Qed.\n\n  Lemma map_gso_share : forall i j v m m',\n    i <> j ->\n    map_upd j v m = Some m' ->\n    map_share i m = map_share i m'.\n  Proof.\n    unfold map_upd, map_share.\n    intros i j v m m'.\n    case_eq (lookup_fpm m j); intros; disc.\n    destruct p.\n    destruct (eq_dec (lifted_obj l) fullshare); disc.\n    inv H1.\n    rewrite fpm_gso; auto.\n  Qed.\n\n  Lemma map_upd_join : forall m1 m2 m3 a v m1',\n    map_upd a v m1 = Some m1' ->\n    join m1 m2 m3 ->\n    exists m3', map_upd a v m3 = Some m3' /\\\n      join m1' m2 m3'.\n  Proof.\n    intros.\n    rewrite map_join_char in H0.\n    destruct (H0 a).\n    generalize H; intros.\n    apply map_set_share1 in H.\n    rewrite H in H1.\n    destruct H1.\n    rewrite glb_commute in H1.\n    rewrite glb_top in H1.\n    rewrite H1 in H4.\n    rewrite lub_bot in H4.\n    symmetry in H4.\n    destruct (map_upd_success a v _ H4).\n    exists x; split; auto.\n    clear H2.\n    rewrite map_join_char.\n    intro a'.\n    destruct (eq_dec a a').\n    subst a'. split.\n    apply map_set_share2 in H3. rewrite H3.\n    apply map_set_share2 in H5. rewrite H5.\n    rewrite H1. apply join_unit2; auto.\n    erewrite map_gss_val; eauto.\n    apply map_val_bot in H1. rewrite H1.\n    erewrite map_gss_val; eauto. constructor.\n    destruct (H0 a'). split.\n    rewrite <- (map_gso_share a' a v m1 m1'); auto.\n    rewrite <- (map_gso_share a' a v m3 x); auto.\n    rewrite <- (map_gso_val a' a v m1 m1'); auto.\n    rewrite <- (map_gso_val a' a v m3 x); auto.\n  Qed.\n\n  Definition build_map (l:list (A * B)) : map :=\n     fold_right\n      (fun (ab:A * B) m =>\n        insert_fpm EqDec_A\n           (fst ab)\n           (mk_lifted fullshare top_share_nonunit,snd ab) m)\n      empty_map l.\n\n  Lemma build_map_results : forall (l:list (A*B)) a b,\n    NoDup (List.map (@fst _ _) l) ->\n    (In (a,b) l <->\n    (map_val a (build_map l) = Some b /\\\n     map_share a (build_map l) = Share.top)).\n  Proof.\n    induction l; simpl.\n    split; intros. elim H0.\n    destruct H0.\n    unfold build_map in H0. simpl in H0.\n    unfold map_val in H0.\n    simpl in H0. discriminate.\n    intros. split; intros.\n    destruct H0; subst.\n    unfold build_map.\n    simpl fold_right.\n    split.\n    unfold map_val.\n    rewrite fpm_gss. simpl; auto.\n    unfold map_share.\n    rewrite fpm_gss. simpl; auto.\n    generalize H0; intro H1.\n    rewrite IHl in H0.\n    inv H.\n    assert (fst a <> a0).\n    intro. subst a0.\n    elim H4.\n    clear -H1. induction l; simpl in *; intuition; subst; auto.\n    destruct H0.\n    unfold build_map. simpl fold_right.\n    split.\n    unfold map_val.\n    rewrite fpm_gso; auto.\n    unfold map_share.\n    rewrite fpm_gso; auto.\n    inv H. auto.\n    inv H.\n    destruct H0.\n    destruct a.\n    destruct (eq_dec a a0).\n    subst a0.\n    left. f_equal.\n    unfold build_map in H.\n    unfold map_val in H.\n    simpl fold_right in H.\n    rewrite fpm_gss in H.\n    inv H. auto.\n    right.\n    rewrite IHl; auto.\n    split.\n    revert H.\n    unfold build_map, map_val.\n    simpl fold_right.\n    rewrite fpm_gso; auto.\n    revert H0.\n    unfold build_map, map_share.\n    simpl fold_right.\n    rewrite fpm_gso; auto.\n  Qed.\n\n  Lemma build_map_join : forall (l1 l2:list (A * B)),\n    NoDup (List.map (@fst _ _) (l1++l2)) ->\n    join  (build_map l1)\n          (build_map l2)\n          (build_map (l1++l2)).\n  Proof.\n    induction l1; intros.\n    simpl app.\n    unfold build_map at 1.\n    simpl fold_right.\n    apply empty_fpm_join; auto with typeclass_instances.\n    inv H.\n    simpl app.\n    unfold build_map.\n    simpl fold_right.\n    apply insert_fpm_join. auto with typeclass_instances.\n    2: apply (IHl1 l2); auto.\n    assert (~In (fst a) (List.map (@fst _ _) l2)).\n    intro.\n    elim H2.\n    rewrite map_app.\n    apply in_or_app.\n    auto.\n    clear -H.\n    induction l2; simpl in *.\n    auto.\n    rewrite fpm_gso; auto.\n  Qed.\n\nEnd SM.\nEnd ShareMap.\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/msl/shares.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2368422983968196}}
{"text": "From Perennial.program_proof Require Import grove_prelude.\nFrom Goose.github_com.mit_pdos.gokv.tutorial.objectstore Require Export chunk dir client.\nFrom Perennial.base_logic.lib Require Import ghost_map.\n\n(*\n  map keyname → chunkhandle\n\n  global monotonic map: chunkhandle → chunkdata.\n  All points-tos are persistent (related to hashing plan).\n\n  { True }\n    PrepareWrite()\n  { writeId, RET #writeId; ownership of writeId }\n  ownership of writeId is:\n    for each index, a points-to with value chunkhandle. Initially points-to nil.\n\n  Just before the client sends a chunk for a particular index to a chunk server,\n  it updates the points-to for that index to a frozen points-to with value equal\n  to that chunk server+content hash.\n  This persistent points-to is precondition of dir.RecordChunk().\n\n  Client-side ghost state is map from string to (list u8).\n\n  PrepareWrite returns ownership of the ongoing write value.\n  AppendChunk changes this value.\n  Done takes ownership of the ongoing value, and (logically) atomically updates\n  the \"real\" value of that keyname to be the ongoing value.\n\n  Key invariant about top-level ghost state:\n    auth_map (1/2) m ∗\n    if m !! k = Some v →\n      ∃ chunkhandles,\n      k ↦[γdir] chunkhandles ∗\n      (there's a way to split up v into chunks such that\n       chunk_handle[j].content_hash ↦[γhash]□ v_chunks[j]\n\n *)\n\n(* Hashing plan:\n   1. Real Go code does hashing.\n   2. GooseLang model is a Go hashing service, which checks for duplicates.\n   3. Spec is monotonic map:\n      { True }\n       Hash(content)\n      { content_hash:string, RET #content_hash; content_hash ↦[γhash]□ content }\n*)\n\nModule PreparedWrite.\nRecord t := mk\n  {\n    Id: u64;\n    ChunkAddrs: list chan;\n  }.\n\nEnd PreparedWrite.\n\nModule RecordChunkArgs.\n  Record t := mk\n    {\n      WriteId: u64;\n      Index: u64;\n      Server: chan;\n      ContentHash: string;\n    }.\nEnd RecordChunkArgs.\n\nModule FinishWriteArgs.\n  Record t := mk\n    {\n      WriteId: u64;\n      Keyname: string;\n    }.\nEnd FinishWriteArgs.\n\nSection proof.\n\nContext `{!heapGS Σ}.\nContext `{ghost_mapG Σ nat (chan * list u8)}.\nContext `{ghost_mapG Σ (u64 * nat) unit}.\n\nRecord dir_names :=\n  {\n    writeId_gn:gname; (* ghost_map writeId → gname *)\n    recorded_gn:gname; (* ghost_map (writeId:u64, index:nat) → unit *)\n  }\n.\n\nDefinition own_PreparedWrite (v:val) (x:PreparedWrite.t) : iProp Σ :=\n  ∃ (addrs_sl:Slice.t),\n  ⌜v = (#x.(PreparedWrite.Id), (slice_val addrs_sl, #() ))%V⌝ ∗\n  readonly (is_slice_small addrs_sl uint64T 1%Qp x.(PreparedWrite.ChunkAddrs))\n  (* [∗ list] index ↦ '(addr, _) ∈ chunkhandles, is_chunk_host γchunk? addr *)\n.\n\nImplicit Type γd : dir_names.\n\n(* This owned by the client, and is used to decide what the data for this WriteID will be *)\nDefinition own_WriteId γd (id:u64) (chunkhandles:list (chan * (list u8) )) : iProp Σ :=\n  (* id + γ should determine the γid *)\n  ∃ γid, ghost_map_auth γid 1 (map_seq 0 chunkhandles)\n  (* [∗ list] index ↦ v ∈ chunkhandles, index ↪[γ] v *)\n  (* [∗ list] index ↦ '(addr, _) ∈ chunkhandles, is_chunk_host γchunk? addr *)\n.\n\nDefinition is_Clerk (ck:loc) γd : iProp Σ := True.\n\nLemma wp_Clerk__PrepareWrite (ck:loc) γd :\n  {{{\n        is_Clerk ck γd\n  }}}\n    Clerk__PrepareWrite #ck\n  {{{\n        v x, RET v; own_PreparedWrite v x ∗\n                     own_WriteId γd x.(PreparedWrite.Id) []\n  }}}\n.\nProof.\nAdmitted.\n\n(* This is a witness that the client has decided on the data/server at an index for a writeId *)\nDefinition is_client_writeId_index γd (id:u64) (index:nat) (chunkhandle:chan * list u8) : iProp Σ :=\n  ∃ γid, (* id + γ should determine the γid *)\n  index ↪[γid]□ chunkhandle\n.\n\nLemma decide_writeId_index γd (id:u64) chunkhandles newchunkhandle :\n  own_WriteId γd id chunkhandles ==∗\n  own_WriteId γd id (chunkhandles ++ [newchunkhandle]) ∗\n  is_client_writeId_index γd id (length chunkhandles) newchunkhandle.\nProof.\nAdmitted.\n\nDefinition is_dir_writeId_index_recorded γd (id:u64) (index:nat) : iProp Σ :=\n  (id, index) ↪[γd.(recorded_gn)]□ ()\n.\n\nLemma wp_Clerk__RecordChunk γd (ck:loc) args data :\n  {{{\n        is_Clerk ck γd ∗\n        is_client_writeId_index γd args.(RecordChunkArgs.WriteId) (int.nat args.(RecordChunkArgs.Index))\n                           (args.(RecordChunkArgs.Server), data)\n        (* own args *)\n        (* witness that args.(RecordChunkArgs.Server) stores data with args.(RecordChunkArgs.ContentHash) *)\n  }}}\n    Clerk__RecordChunk #ck (* #args *)\n  {{{\n        RET #(); is_dir_writeId_index_recorded γd args.(RecordChunkArgs.WriteId)\n                                                         (int.nat args.(RecordChunkArgs.Index))\n  }}}\n.\nProof.\nAdmitted.\n\nDefinition is_finished_writeId γd (id:u64) chunkhandles : iProp Σ :=\n  (* XXX: should be able to to have DfracDiscarded in place of (1:Qp) *)\n  ∃ γid, readonly (ghost_map_auth γid 1 (map_seq 0 chunkhandles))\n.\n\nDefinition object_ptsto γd (key:string) (data:list (list u8)) : iProp Σ :=\n True\n.\n\n(* The code is not exactly-once because FinishWrite might run many times. The\n   spec cannot take and return ownership of the object_ptsto. *)\nLemma wp_Clerk__FinishWrite γd (ck:loc) args chunkhandles (data newdata : list (list u8)) :\n  {{{\n        is_Clerk ck γd ∗\n        is_finished_writeId γd args.(FinishWriteArgs.WriteId) chunkhandles ∗\n        ([∗ list] index ↦ _ ∈ chunkhandles,\n          is_dir_writeId_index_recorded γd args.(FinishWriteArgs.WriteId) index) ∗\n        ⌜chunkhandles.*2 = newdata⌝ ∗\n        object_ptsto γd args.(FinishWriteArgs.Keyname) data\n  }}}\n    Clerk__FinishWrite #ck (* #args *)\n  {{{\n        RET #(); object_ptsto γd args.(FinishWriteArgs.Keyname) newdata\n  }}}\n.\nProof.\nAdmitted.\n\nEnd proof.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/tutorial/objectstore/proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2368422920527883}}
{"text": "From iris.base_logic Require Export invariants gen_heap.\nFrom iris.program_logic Require Export weakestpre ectx_lifting.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.algebra Require Import frac.\nFrom cap_machine Require Export rules_base.\n\nSection cap_lang_rules.\n  Context `{memG Σ, regG Σ}.\n  Context `{MachineParameters}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types σ : ExecConf.\n  Implicit Types c : cap_lang.expr. \n  Implicit Types a b : Addr.\n  Implicit Types r : RegName.\n  Implicit Types v : cap_lang.val. \n  Implicit Types w : Word.\n  Implicit Types reg : gmap RegName Word.\n  Implicit Types ms : gmap Addr Word.\n\n  Inductive IsPtr_spec (regs: Reg) (dst src: RegName) (regs': Reg): cap_lang.val -> Prop :=\n  | IsPtr_spec_success (w: Word):\n      regs !! src = Some w →\n      incrementPC (<[ dst := WInt (if is_cap w then 1%Z else 0%Z) ]> regs) = Some regs' ->\n      IsPtr_spec regs dst src regs' NextIV\n  | IsPtr_spec_failure (w: Word):\n      regs !! src = Some w →\n      incrementPC (<[ dst := WInt (if is_cap w then 1%Z else 0%Z) ]> regs) = None ->\n      IsPtr_spec regs dst src regs' FailedV.\n\n  Lemma wp_IsPtr Ep pc_p pc_b pc_e pc_a w dst src regs :\n    decodeInstrW w = IsPtr dst src ->\n    isCorrectPC (WCap pc_p pc_b pc_e pc_a) →\n    regs !! PC = Some (WCap pc_p pc_b pc_e pc_a) →\n    regs_of (IsPtr dst src) ⊆ dom regs →\n    \n    {{{ ▷ pc_a ↦ₐ w ∗\n        ▷ [∗ map] k↦y ∈ regs, k ↦ᵣ y }}}\n      Instr Executable @ Ep\n    {{{ regs' retv, RET retv;\n        ⌜ IsPtr_spec regs dst src regs' retv ⌝ ∗\n          pc_a ↦ₐ w ∗\n          [∗ map] k↦y ∈ regs', k ↦ᵣ y }}}.\n  Proof.\n    iIntros (Hinstr Hvpc HPC Dregs φ) \"(>Hpc_a & >Hmap) Hφ\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 ns l1 l2 nt) \"Hσ1 /=\". destruct σ1; simpl.\n    iDestruct \"Hσ1\" as \"[Hr Hm]\".\n    iDestruct (gen_heap_valid_inclSepM with \"Hr Hmap\") as %Hregs.\n    have ? := lookup_weaken _ _ _ _ HPC Hregs.\n    iDestruct (@gen_heap_valid with \"Hm Hpc_a\") as %Hpc_a; auto.\n    iModIntro. iSplitR. by iPureIntro; apply normal_always_head_reducible.\n    iNext. iIntros (e2 σ2 efs Hpstep).\n    apply prim_step_exec_inv in Hpstep as (-> & -> & (c & -> & Hstep)).\n    iIntros \"_\".\n    iSplitR; auto. eapply step_exec_inv in Hstep; eauto.\n    rewrite /exec in Hstep.\n\n    specialize (indom_regs_incl _ _ _ Dregs Hregs) as Hri. unfold regs_of in Hri.\n    destruct (Hri dst) as [wdst [H'dst Hdst]]. by set_solver+.\n    destruct (Hri src) as [wsrc [H'src Hsrc]]. by set_solver+.\n\n    assert (exec_opt (IsPtr dst src) (r, m) = updatePC (update_reg (r, m) dst (WInt (if is_cap wsrc then 1%Z else 0%Z)))) as HH.\n    {  rewrite /= Hsrc. unfold is_cap; destruct_word wsrc; auto. }\n    rewrite HH in Hstep. rewrite /update_reg /= in Hstep.\n\n    destruct (incrementPC (<[ dst := WInt (if is_cap wsrc then 1%Z else 0%Z) ]> regs))\n      as [regs'|] eqn:Hregs'; pose proof Hregs' as H'regs'; cycle 1.\n    { apply incrementPC_fail_updatePC with (m:=m) in Hregs'.\n      eapply updatePC_fail_incl with (m':=m) in Hregs'.\n      2: by apply lookup_insert_is_Some'; eauto.\n      2: by apply insert_mono; eauto.\n      simplify_pair_eq.\n      rewrite Hregs' in Hstep. inversion Hstep.\n      iFrame. iApply \"Hφ\"; iFrame. iPureIntro. econstructor; eauto. }\n\n    (* Success *)\n\n    eapply (incrementPC_success_updatePC _ m) in Hregs'\n      as (p' & g' & b' & e' & a'' & a_pc' & HPC'' & HuPC & ->).\n    eapply updatePC_success_incl with (m':=m) in HuPC. 2: by eapply insert_mono; eauto. rewrite HuPC in Hstep.\n\n    simplify_pair_eq. iFrame.\n    iMod ((gen_heap_update_inSepM _ _ dst) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n    iMod ((gen_heap_update_inSepM _ _ PC) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n    iFrame. iModIntro. iApply \"Hφ\". iFrame. iPureIntro. econstructor; eauto.\n  Qed.\n\n  Lemma wp_IsPtr_successPC E pc_p pc_b pc_e pc_a pc_a' w dst w' :\n    decodeInstrW w = IsPtr dst PC →\n    isCorrectPC (WCap pc_p pc_b pc_e pc_a) →\n    (pc_a + 1)%a = Some pc_a' →\n\n    {{{ ▷ PC ↦ᵣ WCap pc_p pc_b pc_e pc_a\n        ∗ ▷ pc_a ↦ₐ w\n        ∗ ▷ dst ↦ᵣ w'\n    }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ WCap pc_p pc_b pc_e pc_a'\n          ∗ pc_a ↦ₐ w\n          ∗ dst ↦ᵣ WInt 1%Z }}}.\n   Proof.\n     iIntros (Hinstr Hvpc Hpca' ϕ) \"(>HPC & >Hpc_a & >Hdst) Hφ\".\n     iDestruct (map_of_regs_2 with \"HPC Hdst\") as \"[Hmap %]\".\n     iApply (wp_IsPtr with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n     by rewrite !dom_insert; set_solver+.\n     iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n     destruct Hspec as [|].\n     { iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n       rewrite (insert_commute _ PC dst) // insert_insert insert_commute // insert_insert.\n       iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n     { incrementPC_inv; simplify_map_eq; eauto. congruence. }\n   Qed.\n\n   Lemma wp_IsPtr_success E pc_p pc_b pc_e pc_a pc_a' w dst r wr w' :\n     decodeInstrW w = IsPtr dst r →\n     isCorrectPC (WCap pc_p pc_b pc_e pc_a) →\n     (pc_a + 1)%a = Some pc_a' →\n\n       {{{ ▷ PC ↦ᵣ WCap pc_p pc_b pc_e pc_a\n             ∗ ▷ pc_a ↦ₐ w\n             ∗ ▷ r ↦ᵣ wr\n             ∗ ▷ dst ↦ᵣ w'\n       }}}\n         Instr Executable @ E\n       {{{ RET NextIV;\n           PC ↦ᵣ WCap pc_p pc_b pc_e pc_a'\n           ∗ pc_a ↦ₐ w\n           ∗ r ↦ᵣ wr\n           ∗ dst ↦ᵣ WInt (if is_cap wr then 1%Z else 0%Z) }}}.\n   Proof.\n    iIntros (Hinstr Hvpc Hpc_a ϕ) \"(>HPC & >Hpc_a & >Hr & >Hdst) Hφ\".\n    iDestruct (map_of_regs_3 with \"HPC Hr Hdst\") as \"[Hmap (%&%&%)]\".\n    iApply (wp_IsPtr with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [|].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC dst) // insert_insert (insert_commute _ r dst) //\n              (insert_commute _ dst PC) // insert_insert.\n      iDestruct (regs_of_map_3 with \"Hmap\") as \"(?&?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      incrementPC_inv; simplify_map_eq; eauto. congruence. }\n   Qed.\n\n   Lemma wp_IsPtr_success_dst E pc_p pc_b pc_e pc_a pc_a' w dst w' :\n     decodeInstrW w = IsPtr dst dst →\n     isCorrectPC (WCap pc_p pc_b pc_e pc_a) →\n     (pc_a + 1)%a = Some pc_a' →\n     \n       {{{ ▷ PC ↦ᵣ WCap pc_p pc_b pc_e pc_a\n             ∗ ▷ pc_a ↦ₐ w\n             ∗ ▷ dst ↦ᵣ w'\n       }}}\n         Instr Executable @ E\n       {{{ RET NextIV;\n           PC ↦ᵣ WCap pc_p pc_b pc_e pc_a'\n           ∗ pc_a ↦ₐ w\n           ∗ dst ↦ᵣ WInt (if is_cap w' then 1%Z else 0%Z) }}}.\n   Proof.\n     iIntros (Hinstr Hvpc Hpca' ϕ) \"(>HPC & >Hpc_a & >Hdst) Hφ\".\n     iDestruct (map_of_regs_2 with \"HPC Hdst\") as \"[Hmap %]\".\n     iApply (wp_IsPtr with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n     by rewrite !dom_insert; set_solver+.\n     iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n     destruct Hspec as [|].\n     { iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n       rewrite (insert_commute _ PC dst) // insert_insert insert_commute // insert_insert.\n       iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n     { incrementPC_inv; simplify_map_eq; eauto. congruence. }\n   Qed.\n\nEnd cap_lang_rules.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/rules/rules_IsPtr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.23681678865914327}}
{"text": "Require Import Platform.tests.Thread0 Platform.tests.Connect Platform.Bootstrap.\n\n\nModule Type S.\n  Parameter heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nModule M'.\n  Definition globalSched : W := ((heapSize + 50) * 4)%nat.\n\n  Definition inbuf_size := 40.\n\n  Theorem inbuf_size_lower : (inbuf_size >= 2)%nat.\n    unfold inbuf_size; auto.\n  Qed.\n\n  Theorem inbuf_size_upper : (N_of_nat (inbuf_size * 4) < Npow2 32)%N.\n    reflexivity.\n  Qed.\nEnd M'.\n\nImport M'.\n\nModule E := Connect.Make(M').\nImport E.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 1.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 1.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"connect\"!\"main\" @ [E.mainS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREmain[_] globalSched =?> 1 * 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREmain[_] globalSched =?> 1 * mallocHeap 0];;\n\n        Goto \"connect\"!\"main\"\n      end\n    }}.\n\n  Ltac t := unfold globalSched, localsInvariantMain, M'.globalSched; genesis.\n\n  Theorem ok0 : moduleOk boot.\n    vcgen; abstract t.\n  Qed.\n\n  Definition m1 := link Buffers.m boot.\n  Definition m2 := link E.m m1.\n  Definition m := link m2 E.T.T.m.\n\n  Lemma ok1 : moduleOk m1.\n    link Buffers.ok ok0.\n  Qed.\n\n  Lemma ok2 : moduleOk m2.\n    link E.ok ok1.\n  Qed.\n\n  Theorem ok : moduleOk m.\n    link ok2 E.T.T.ok.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n\n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, $ (size * 4) <= w -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/tests/ConnectDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2368167834845898}}
{"text": "(* Copyright (c) 2014, Robert Dockins *)\n\nRequire Import Setoid.\n\nRequire Import basics.\nRequire Import preord.\nRequire Import categories.\nRequire Import sets.\nRequire Import finsets.\nRequire Import esets.\nRequire Import effective.\nRequire Import plotkin.\nRequire Import embed.\nRequire Import joinable.\nRequire Import approx_rels.\nRequire Import profinite.\nRequire Import profinite_adj.\nRequire Import cont_functors.\n\n(**  * Continuous adjoint functors\n\n     Here we lift the lifting and forgetful adjoint functors into the\n     category of embeddings and prove that they are continuous.\n  *)\n\nDefinition forgetEMBED_map (A B:ob PLT) (f:A ⇀ B) : forgetPLT_ob A ⇀ forgetPLT_ob B :=\n  Embedding true (forgetPLT_ob A) (forgetPLT_ob B) \n    (@embed_map false A B f)\n    (@embed_mono false A B f)\n    (@embed_reflects false A B f)\n    (fun _ => I)\n    (@embed_directed2 false A B f).\n\nProgram Definition forgetEMBED : functor (EMBED false) (EMBED true) :=\n  Functor (EMBED false) (EMBED true) forgetPLT_ob forgetEMBED_map _ _ _.\nSolve Obligations of forgetEMBED with auto.\n\nProgram Definition liftEMBED_map (A B:ob ∂PLT) (f:A ⇀ B) : liftPPLT_ob A ⇀ liftPPLT_ob B :=\n  Embedding false (liftPPLT_ob A) (liftPPLT_ob B)\n    (fun x => match x with None => None | Some a => Some (f a) end)\n    _ _ _ _.\nNext Obligation.\n  simpl. intros.\n  destruct a; destruct a'; simpl; auto.\n  apply embed_mono. auto.\nQed.\nNext Obligation.\n  simpl. intros.\n  destruct a; destruct a'; simpl; auto.\n  apply embed_reflects with B f; auto.\nQed.\nNext Obligation.\n  intros. exists None. hnf. auto.\nQed.\nNext Obligation.\n  simpl. intros. \n  destruct a; destruct b.\n  - destruct y. \n    + destruct embed_directed2 with true A B f c1 c c0 as [q [?[??]]]; auto.\n      exists (Some q); auto.\n    + elim H.\n  - exists (Some c). auto.\n  - exists (Some c). auto.\n  - exists None. auto.\nQed.\n\nProgram Definition liftEMBED : functor (EMBED true) (EMBED false) :=\n  Functor (EMBED true) (EMBED false) liftPPLT_ob liftEMBED_map _ _ _.\nNext Obligation.\n  intros. split; hnf; simpl; intros.\n  - destruct x; simpl; auto.\n    destruct H. apply H.\n  - destruct x; simpl; auto.\n    destruct H. apply H0.\nQed.\nNext Obligation.\n  intros. split; hnf; simpl; intros.\n  - destruct x; auto. destruct H. apply H.\n  - destruct x; auto. destruct H. apply H0.\nQed.\nNext Obligation.\n  intros. split; hnf; simpl; intros.\n  - destruct x; auto. destruct H. apply H.\n  - destruct x; auto. destruct H. apply H0.\nQed.\n\nRequire Import bilimit.\n\nLemma forgetEMBED_continuous : continuous_functor forgetEMBED.\nProof.\n  hnf; intros.\n  apply decompose_is_colimit; simpl.\n  intros.\n  destruct (colimit_decompose _ I DS CC X x) as [i [s H]].\n  exists i. exists s. auto.\nQed.\n\nLemma liftEMBED_continuous : continuous_functor liftEMBED.\nProof.\n  hnf; intros.\n  apply decompose_is_colimit; simpl.\n  intros.\n  destruct x.\n  - destruct (colimit_decompose _ I DS CC X c) as [i [s H]].\n    exists i. exists (Some s). auto.\n  - destruct (directed.choose_ub_set I nil) as [i0 ?].\n    exists i0. exists None. auto.\nQed.\n", "meta": {"author": "robdockins", "repo": "domains", "sha": "6feea4ed576f8aa849af9fa102633d5df1191360", "save_path": "github-repos/coq/robdockins-domains", "path": "github-repos/coq/robdockins-domains/domains-6feea4ed576f8aa849af9fa102633d5df1191360/cont_adj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23678416436935573}}
{"text": "Require Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import STS.\nRequire Import Behavior.\nRequire Import ModSem.\nRequire Import Skeleton.\nRequire Import PCM.\n\nSet Implicit Arguments.\n\n\n\n\n\n\nSection CANNON.\n  Definition div (n m: Z): option Z :=\n    if Z_zerop m then None else Some (Z.div n m).\n\n  Definition fire_body {E} `{callE -< E} `{pE -< E} `{eventE -< E}\n    : list val -> itree E Z :=\n    fun args =>\n      powder <- trigger PGet;; powder <- powder↓?;;\n      r <- (div 1 powder)?;;\n      _ <- trigger (Syscall \"print\" [r]↑ top1);;\n      _ <- trigger (PPut (powder - 1)%Z↑);;\n      Ret r\n  .\n\n  Definition CannonSem: ModSem.t := {|\n    ModSem.fnsems := [(\"fire\", cfunU fire_body)];\n    ModSem.mn := \"Cannon\";\n    ModSem.initial_st := (1: Z)%Z↑;\n  |}\n  .\n\n  Definition Cannon: Mod.t := {|\n    Mod.get_modsem := fun _ => CannonSem;\n    Mod.sk := [(\"fire\", Sk.Gfun)];\n  |}\n  .\nEnd CANNON.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/cannon/Cannon0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2367841643693557}}
{"text": "Require Import StlcIso.SpecTyping.\nRequire Import StlcIso.SpecEquivalent.\nRequire Import StlcIso.LemmasEvaluation.\nRequire Import StlcIso.LemmasTyping.\nRequire Import StlcEqui.SpecEquivalent.\nRequire Import StlcEqui.LemmasEvaluation.\n\nRequire Import CompilerIE.Compiler.\n\nRequire Import UValIE.UVal.\n\nRequire Import LogRelIE.PseudoType.\nRequire Import LogRelIE.LemmasPseudoType.\nRequire Import LogRelIE.LR.\nRequire Import LogRelIE.LemmasLR.\n\nRequire Import BacktransIE.Emulate.\nRequire Import BacktransIE.InjectExtract.\nRequire Import BacktransIE.UpgradeDowngrade.\nRequire Import BacktransIE.Backtrans.\n\nLemma equivalencePreservation {t₁ t₂ τ} :\n  ValidTy τ ->\n  ⟪ I.empty i⊢ t₁ : τ ⟫ →\n  ⟪ I.empty i⊢ t₂ : τ ⟫ →\n  ⟪ I.empty i⊢ t₁ ≃ t₂ : τ ⟫ →\n  ⟪ E.empty e⊢ compie t₁ ≃ compie t₂ : τ ⟫.\nProof.\n  (* sufficient to prove one direction of equi-termination *)\n  revert t₁ t₂ τ.\n  enough (∀ {t₁ t₂ τ τ'},\n             ValidTy τ ->\n             ValidTy τ' ->\n            ⟪ I.empty i⊢ t₁ : τ ⟫ →\n            ⟪ I.empty i⊢ t₂ : τ ⟫ →\n            ⟪ I.empty i⊢ t₁ ≃ t₂ : τ ⟫ →\n            ∀ {C}, ⟪ ea⊢ C : E.empty , τ → E.empty , τ' ⟫ →\n                 E.Terminating (E.pctx_app (compie t₁) (eraseAnnot_pctx C)) → E.Terminating (E.pctx_app (compie t₂) (eraseAnnot_pctx C))) as Hltor.\n  { intros t₁ t₂ τ vτ ty1 ty2 ceq.\n    assert (⟪ I.empty i⊢ t₂ ≃ t₁ : τ ⟫) as ceq'\n            by (apply I.pctx_equiv_symm; assumption).\n    split;\n      refine (Hltor _ _ _ _ _ _ _ _ _ _ H0); crushValidTy.\n  }\n\n  intros t₁ t₂ τ τ' vτ vτ' ty₁ ty₂ ceq Cu tCu term.\n  destruct (E.Terminating_TermHor term) as [n termN]; clear term.\n\n  assert (⟪ pempty ⊩ t₁ ⟦ dir_gt , S n ⟧ compie t₁ : embed τ ⟫) as lre₁.\n  { change pempty with (embedCtx (repEmulCtx pempty)).\n      eapply compie_correct; crushValidTy_with_UVal.\n      cbn; eauto using ValidEnv_nil. }\n\n  unshelve epose proof (lrfull₁ := backtranslateCtx_works vτ' vτ (dwp_precise _) tCu lre₁).\n  exact (S (S n)).\n  eauto.\n\n  unfold backtranslateCtx in lrfull₁.\n  rewrite I.eraseAnnot_pctx_cat, I.pctx_cat_app in lrfull₁.\n\n  assert (I.Terminating (I.pctx_app (I.app (inject (S (S n)) τ) t₁)\n                                    (I.eraseAnnot_pctx (emulate_pctx (S (S n)) Cu)))) as termI\n    by (eapply (adequacy_gt lrfull₁ termN); eauto with arith).\n\n  change (I.app (inject (S (S n)) τ) t₁) with (I.pctx_app t₁ (I.eraseAnnot_pctx (I.ia_papp₂ τ (UValIE (S (S n)) τ) (injectA (S (S n)) τ) I.ia_phole))) in termI.\n  rewrite <- I.pctx_cat_app in termI.\n  rewrite <- I.eraseAnnot_pctx_cat in termI.\n\n  assert (⟪ i⊢ I.eraseAnnot_pctx (emulate_pctx (S (S n)) Cu) : I.empty, UValIE (S (S n)) τ → I.empty, UValIE (S (S n)) τ' ⟫) by\n    (change I.empty with (toUVals (S (S n)) E.empty);\n        eapply I.eraseAnnot_pctxT, emulate_pctx_T; eauto with tyvalid).\n\n  assert (vε : ValidEnv E.empty) by eauto with tyvalid.\n  assert (vuvalτ : ValidTy (UValIE (S (S n)) τ')) by crushValidTy_with_UVal.\n  pose proof (tEmCu := emulate_pctx_T (n := S (S n)) vε vτ' tCu).\n  assert (I.Terminating (I.pctx_app t₂ (backtranslateCtx (S (S n)) τ Cu))) as termS'.\n  { eapply ceq.\n    exact vuvalτ.\n    repeat (I.crushTypingMatchIAH + I.crushTypingMatchIAH2);\n    crushValidTy_with_UVal; eauto using I.pctxtyping_cat_annot, injectAT, emulate_pctx_T, I.PCtxTypingAnnot.\n    assumption.\n  }\n  unfold backtranslateCtx in termS'.\n\n  destruct (I.Terminating_TermHor termS') as [m termSm']; clear termS'.\n\n  assert (⟪ pempty ⊩ t₂ ⟦ dir_lt , S m ⟧ compie t₂ : embed τ ⟫) as lre₂\n      by (change pempty with (embedCtx (repEmulCtx pempty)); \n          eapply compie_correct;\n          cbn; assumption).\n\n  epose proof (lrfull₂ := backtranslateCtx_works vτ' vτ dwp_imprecise tCu lre₂).\n\n  eapply (adequacy_lt lrfull₂ termSm'); eauto with arith.\nQed.\n\nDefinition FullAbstraction (t₁ : I.Tm) (t₂ : I.Tm) (τ : Ty) : Prop :=\n  ⟪ I.empty i⊢ t₁ : τ ⟫ →\n  ⟪ I.empty i⊢ t₂ : τ ⟫ →\n  ⟪ I.empty i⊢ t₁ ≃ t₂ : τ ⟫ ↔\n  ⟪ E.empty e⊢ compie t₁ ≃ compie t₂ : τ ⟫.\n\nLemma fullAbstraction {t₁ t₂ τ} : FullAbstraction t₁ t₂ τ.\nProof.\n  unfold FullAbstraction.\n  intros.\n  pose proof I.typed_terms_are_valid t₁ τ ValidEnv_nil H as vτ.\n  split;\n  eauto using equivalenceReflectionEmpty, equivalencePreservation.\nQed.\n\nPrint Assumptions fullAbstraction.\n", "meta": {"author": "dominiquedevriese", "repo": "fixismu-coq", "sha": "8a98893e9ab1277bf5d6980446c2ec71a805c283", "save_path": "github-repos/coq/dominiquedevriese-fixismu-coq", "path": "github-repos/coq/dominiquedevriese-fixismu-coq/fixismu-coq-8a98893e9ab1277bf5d6980446c2ec71a805c283/FullAbstractionIE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.23675478551271306}}
{"text": "Require Import Coq.Lists.List Coq.Setoids.Setoid Coq.Classes.Morphisms.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.Refinement.BinOpBrackets.ParenBalanced.\nRequire Import Fiat.Parsers.Reachable.ParenBalanced.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.StringLike.Core.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Parsers.FoldGrammar.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Common.\nRequire Import Fiat.Common.Enumerable.\nRequire Import Fiat.Common.FixedPoints.\n\nLocal Open Scope bool_scope.\nLocal Open Scope string_like_scope.\n\nSet Implicit Arguments.\n\nLocal Notation eta x := (fst x, snd x) (only parsing).\nLocal Notation eta2 x := (fst x, (fst (snd x), snd (snd x))) (only parsing).\n\nLocal Opaque rdp_list_predata.\n\nSection specific.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char}\n          {CharE : Enumerable Char}.\n  Context {pdata : paren_balanced_hiding_dataT Char}.\n  Context (G : pregrammar Char).\n  Let predata := (@rdp_list_predata _ G).\n  Local Existing Instance predata.\n\n  Section assume_lists.\n    Context (pb_nts pbh_nts : nonterminals_listT).\n\n    Definition paren_balanced''_production_step\n               (hiding : bool)\n      := fun (it : item Char) (rest_balanced : nat -> bool) level\n         => let predata := @rdp_list_predata _ G in\n            match it with\n              | Terminal P\n                => ((pb_check_level_fun hiding P level)\n                      && match pb_new_level_fun P level with\n                           | new_level::nil => rest_balanced new_level\n                           | _ => false\n                         end)%bool\n              | NonTerminal nt\n                => (*(is_valid_nonterminal initial_nonterminals_data nt)\n                   &&*)\n                (if (hiding && Compare_dec.zerop level)\n                 then is_valid_nonterminal pbh_nts (of_nonterminal nt)\n                 else is_valid_nonterminal pb_nts (of_nonterminal nt))\n                  && rest_balanced level\n            end.\n\n    Definition paren_balanced''_production\n               (hiding : bool)\n               (level : nat)\n               (pat : production Char)\n    : bool\n      := fold_right\n           (paren_balanced''_production_step hiding)\n           Compare_dec.zerop\n           pat\n           level.\n\n    Definition paren_balanced''_productions\n               (hiding : bool)\n               (level : nat)\n               (pats : productions Char)\n    : bool\n      := fold_right\n           andb\n           true\n           (map (paren_balanced''_production hiding level) pats).\n\n    Definition paren_balanced''_nt\n               (hiding : bool)\n               (nt : nonterminal_carrierT)\n    : bool\n      := let predata := @rdp_list_predata _ G in\n         (paren_balanced''_productions\n            hiding\n            0\n            (Lookup_idx G nt)).\n\n    Section correct.\n      Context (H_pb : forall nt, is_valid_nonterminal pb_nts nt\n                                 -> paren_balanced''_nt false nt)\n              (H_pbh : forall nt, is_valid_nonterminal pbh_nts nt\n                                  -> paren_balanced''_nt true nt).\n\n      Fixpoint paren_balanced_productions_correct\n               (hiding : bool)\n               (level : nat)\n               (pats : productions Char)\n               (H_p : paren_balanced''_productions hiding level pats)\n               (str : String)\n               (p : parse_of G str pats)\n      : if hiding\n        then paren_balanced_hiding' str level\n        else paren_balanced' str level\n      with paren_balanced_production_correct\n             (hiding : bool)\n             (level : nat)\n             (pat : production Char)\n             (H_p : paren_balanced''_production hiding level pat)\n             (str : String)\n             (p : parse_of_production G str pat)\n           : if hiding\n             then paren_balanced_hiding' str level\n             else paren_balanced' str level.\n      Proof.\n        { destruct p as [?? p | ?? p ];\n          [ apply (fun hiding level H_p => paren_balanced_production_correct hiding level _ H_p _ p)\n          | apply (fun hiding level H_p => paren_balanced_productions_correct hiding level _ H_p _ p) ];\n          clear paren_balanced_production_correct paren_balanced_productions_correct;\n          unfold paren_balanced''_productions in *;\n          simpl in *;\n          apply Bool.andb_true_iff in H_p;\n          destruct H_p as [H_p0 H_p1];\n          assumption. }\n        { destruct p as [| ??? p0 p1 ].\n          { clear paren_balanced_productions_correct paren_balanced_production_correct.\n            unfold paren_balanced''_production in *.\n            simpl in *.\n            edestruct Compare_dec.zerop; subst; simpl in *; try congruence; [].\n            destruct hiding.\n            { rewrite paren_balanced_hiding'_nil by assumption; reflexivity. }\n            { rewrite paren_balanced'_nil by assumption; reflexivity. } }\n          { specialize (fun hiding level H_p => paren_balanced_production_correct hiding level _ H_p _ p1); clear p1.\n            unfold paren_balanced''_production in *.\n            simpl in *.\n            destruct p0 as [| ? ? p0 ].\n            { clear paren_balanced_productions_correct.\n              unfold paren_balanced''_production_step at 1 in H_p.\n              destruct (pb_new_level_fun P level) as [|? [|]] eqn:Heq;\n                simpl in *;\n                try rewrite Bool.andb_false_r in *; try congruence;\n                [].\n              apply Bool.andb_true_iff in H_p;\n                destruct H_p as [H_p0 H_p1].\n              specialize (paren_balanced_production_correct _ _ H_p1).\n              clear H_p1.\n              rewrite paren_balanced_hiding'_recr.\n              rewrite paren_balanced'_recr.\n              repeat match goal with\n                       | [ H : is_true (_ ~= [ _ ]) |- _ ]\n                         => pose proof (length_singleton _ _ H);\n                           progress apply take_n_1_singleton in H\n                       | [ H : context[length (StringLike.take _ _)] |- _ ]\n                         => rewrite take_length in H\n                     end.\n              erewrite !(proj1 (get_0 _ _)) by eassumption.\n              assert (H' : StringLike.drop n str =s StringLike.drop 1 str).\n              { destruct n as [|[|n]]; simpl in *; try congruence; try reflexivity.\n                destruct (length str) as [|[|]] eqn:?; try congruence.\n                apply bool_eq_empty; rewrite ?drop_length; omega. }\n              rewrite !H' in paren_balanced_production_correct; clear H'.\n              repeat match goal with\n                       | [ H : _ |- _ ] => setoid_rewrite pb_check_level_fun_correct in H\n                       | [ H : _ |- _ ] => setoid_rewrite pb_new_level_fun_correct in H\n                     end.\n              unfold paren_balanced_hiding'_step, paren_balanced'_step, pb_check_level_fun, pb_new_level_fun, pb_check_level, pb_new_level in *.\n              repeat match goal with\n                       | _ => assumption\n                       | _ => progress subst\n                       | [ H : filter _ _ = _::nil |- _ ] => eapply filter_enumerate in H\n                       | _ => progress split_iff\n                       | _ => specialize_by eassumption; progress subst\n                       | [ H : context[fold_right andb true (map _ _)] |- _ ]\n                         => rewrite fold_right_andb_map_in_iff in H\n                       | [ H : context[In _ (filter _ _)] |- _ ]\n                         => setoid_rewrite filter_In in H\n                       | [ H : forall x, _ /\\ _ -> _ |- _ ] => specialize (fun x A B => H x (conj A B))\n                       | [ H : forall x, In _ (enumerate _) -> _ |- _ ]\n                           => specialize (fun x => H x (enumerate_correct _))\n                       | [ H : ?x = true, H' : context[?x] |- _ ] => rewrite H in H'\n                       | [ H : ?x = false, H' : context[?x] |- _ ] => rewrite H in H'\n                       | [ H : ?x = ?y::nil |- _ ]\n                         => assert (forall n, In n x <-> n = y)\n                           by (intro; rewrite H; simpl; intuition);\n                           clear H\n                       | [ H : forall x, _ = x -> _ |- _ ] => specialize (H _ eq_refl)\n                       | [ H : forall x, x = _ -> _ |- _ ] => specialize (H _ eq_refl)\n                       | [ H : context[In _ (uniquize _ _)] |- _ ]\n                         => setoid_rewrite <- (ListFacts.uniquize_In_refl_iff _ EqNat.beq_nat _ (lb eq_refl) bl) in H\n                       | [ H : context[In _ (map _ _)] |- _ ]\n                         => setoid_rewrite in_map_iff in H\n                       | _ => progress destruct_head ex\n                       | _ => progress destruct_head and\n                       | [ H : forall x, ex _ -> _ |- _ ]\n                         => specialize (fun x a b => H x (ex_intro _ a b))\n                       | _ => progress cbv beta in *\n                       | _ => progress split_and\n                       | [ |- context[bool_of_sumbool ?e] ] => destruct e; simpl\n                       | [ |- appcontext[if ?e then _ else _] ]\n                         => destruct e eqn:?\n                       | [ H : forall ch, is_true (?P ch) -> _ |- _ ]\n                         => repeat match goal with\n                                     | [ H' : is_true (P ?ch') |- _ ]\n                                       => unique pose proof (H _ H')\n                                     | [ H' : P ?ch' = true |- _ ]\n                                       => unique pose proof (H _ H')\n                                   end;\n                           clear H\n                     end. }\n            { specialize (fun hiding level H_p => paren_balanced_productions_correct hiding level _ H_p _ p0); clear p0.\n              unfold paren_balanced''_production_step at 1 in H_p.\n              apply Bool.andb_true_iff in H_p;\n                destruct H_p as [H_p0 H_p1].\n              specialize (paren_balanced_production_correct _ _ H_p1); clear H_p1.\n              destruct hiding.\n              { simpl in *.\n                rewrite paren_balanced_hiding'_split_0; [ reflexivity | | eassumption ].\n                destruct level as [|level]; simpl in *.\n                { specialize (H_pbh _ H_p0); clear H_p0.\n                  unfold paren_balanced''_nt in *.\n                  (*apply Bool.andb_true_iff in H_pbh;\n                  destruct H_pbh as [H_pbh0 H_pbh1]; clear H_pbh.*)\n                  rewrite <- Carriers.list_to_productions_to_nonterminal in H_pbh.\n                  change Carriers.default_to_nonterminal with to_nonterminal in H_pbh.\n                  rewrite to_of_nonterminal in H_pbh by assumption.\n                  specialize (paren_balanced_productions_correct _ _ H_pbh).\n                  simpl in *.\n                  assumption. }\n                { specialize (H_pb _ H_p0); clear H_p0.\n                  unfold paren_balanced''_nt in *.\n                  (*apply Bool.andb_true_iff in H_pb;\n                  destruct H_pb as [H_pb0 H_pb1]; clear H_pb.*)\n                  rewrite <- Carriers.list_to_productions_to_nonterminal in H_pb.\n                  change Carriers.default_to_nonterminal with to_nonterminal in H_pb.\n                  rewrite to_of_nonterminal in H_pb by assumption.\n                  specialize (paren_balanced_productions_correct _ _ H_pb).\n                  simpl in *.\n                  assumption. } }\n              { simpl in *.\n                rewrite paren_balanced'_split_0; [ reflexivity | | eassumption ].\n                specialize (H_pb _ H_p0); clear H_p0.\n                unfold paren_balanced''_nt in *.\n                (*apply Bool.andb_true_iff in H_pb;\n                destruct H_pb as [H_pb0 H_pb1]; clear H_pb.*)\n                rewrite <- Carriers.list_to_productions_to_nonterminal in H_pb.\n                change Carriers.default_to_nonterminal with to_nonterminal in H_pb.\n                rewrite to_of_nonterminal in H_pb by assumption.\n                specialize (paren_balanced_productions_correct _ _ H_pb).\n                simpl in *.\n                assumption. } } } }\n      Defined.\n\n      Lemma paren_balanced_nt''_correct\n            (hiding : bool)\n            nt\n            (H_p : paren_balanced''_nt hiding (of_nonterminal nt))\n            (str : String)\n            (p : parse_of_item G str (NonTerminal nt))\n      : if hiding\n        then paren_balanced_hiding str\n        else paren_balanced str.\n      Proof.\n        dependent destruction p.\n        eapply paren_balanced_productions_correct;\n          try eassumption; instantiate;\n            rewrite <- Carriers.list_to_productions_to_nonterminal;\n            change Carriers.default_to_nonterminal with to_nonterminal;\n            rewrite ?to_of_nonterminal; eassumption.\n      Qed.\n    End correct.\n\n    Section correct_reflective.\n      Local Transparent rdp_list_predata.\n\n      Context (H_pb : fold_right andb true (map (paren_balanced''_nt false) pb_nts))\n              (H_pbh : fold_right andb true (map (paren_balanced''_nt true) pbh_nts)).\n\n      Local Ltac t :=\n        repeat match goal with\n                 | _ => progress simpl in *\n                 | _ => progress specialize_by assumption\n                 | _ => progress intros\n                 | _ => progress unfold rdp_list_is_valid_nonterminal in *\n                 | _ => progress subst\n                 | _ => congruence\n                 | [ H : string_beq _ _ = true |- _ ] => apply string_bl in H\n                 | [ H : EqNat.beq_nat _ _ = true |- _ ] => apply EqNat.beq_nat_true in H\n                 | [ H : is_true (_ || _) |- _ ] => apply Bool.orb_true_iff in H\n                 | [ H : is_true (_ && _) |- _ ] => apply Bool.andb_true_iff in H\n                 | [ H : _ /\\ _ |- _ ] => let H1 := fresh in\n                                          let H2 := fresh in\n                                          destruct H as [H1 H2]; try clear H\n                 | [ H : _ \\/ _ |- _ ] => destruct H\n                 | _ => solve [ eauto with nocore ]\n               end.\n\n      Lemma paren_balanced_nt'_correct\n            (hiding : bool)\n            nt\n            (H_p : paren_balanced''_nt hiding (of_nonterminal nt))\n            (str : String)\n            (p : parse_of_item G str (NonTerminal nt))\n      : if hiding\n        then paren_balanced_hiding str\n        else paren_balanced str.\n      Proof.\n        eapply paren_balanced_nt''_correct; try eassumption.\n        { clear -H_pb.\n          induction pb_nts; t. }\n        { clear -H_pbh.\n          induction pbh_nts; t. }\n      Qed.\n    End correct_reflective.\n  End assume_lists.\nEnd specific.\n\nSection paren_balanced_nonterminals.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char}.\n  Context {HEC : Enumerable Char}.\n  Context {pdata : paren_balanced_hiding_dataT Char}\n          (G : pregrammar Char)\n          (hiding : bool).\n  Let predata := (@rdp_list_predata _ G).\n  Local Existing Instance predata.\n\n  Definition paren_balanced_nonterminals (nt : String.string) : list nonterminal_carrierT * list nonterminal_carrierT\n    := greatest_fixpoint_of_lists\n         (fun pb_nts pbh_nts => paren_balanced''_nt (G := G) pb_nts pbh_nts false)\n         (fun pb_nts pbh_nts => paren_balanced''_nt (G := G) pb_nts pbh_nts true)\n         initial_nonterminals_data\n         initial_nonterminals_data.\nEnd paren_balanced_nonterminals.\n\nLocal Transparent rdp_list_predata.\n\nSection with_lists.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char}.\n  Context {HEC : Enumerable Char}.\n  Context {pdata : paren_balanced_hiding_dataT Char}.\n  Context (G : pregrammar Char).\n  Let predata := (@rdp_list_predata _ G).\n  Local Existing Instance predata.\n\n  Section pre.\n    Context (hiding : bool)\n            (nt : String.string).\n\n    Let pb_nts : nonterminals_listT\n      := fst (paren_balanced_nonterminals G nt).\n    Let pbh_nts : nonterminals_listT\n      := snd (paren_balanced_nonterminals G nt).\n\n    Let H_pb : fold_right andb true (map (paren_balanced''_nt pb_nts pbh_nts false) pb_nts).\n    Proof.\n      rapply @greatest_fixpoint_of_lists_correct_1.\n    Qed.\n    Let H_pbh : fold_right andb true (map (paren_balanced''_nt pb_nts pbh_nts true) pbh_nts).\n    Proof.\n      rapply @greatest_fixpoint_of_lists_correct_2.\n    Qed.\n\n    Lemma paren_balanced_nt_correct\n          (H_p : paren_balanced''_nt pb_nts pbh_nts hiding (of_nonterminal nt))\n          (str : String)\n          (p : parse_of_item G str (NonTerminal nt))\n    : if hiding\n      then paren_balanced_hiding str\n      else paren_balanced str.\n    Proof.\n      eapply paren_balanced_nt'_correct; eassumption.\n    Qed.\n  End pre.\n\n  Section rule.\n    Context (nt : String.string).\n\n    Let pb_nts : nonterminals_listT\n      := fst (paren_balanced_nonterminals G nt).\n    Let pbh_nts : nonterminals_listT\n      := snd (paren_balanced_nonterminals G nt).\n\n    Definition paren_balanced_hiding_correctness_type\n      := (*(fold_right andb true (map (paren_balanced''_nt pb_nts pbh_nts false) pb_nts))\n           && (fold_right andb true (map (paren_balanced''_nt pb_nts pbh_nts true) pbh_nts))\n           && *)(paren_balanced''_nt pb_nts pbh_nts true (of_nonterminal nt)).\n\n    Global Arguments paren_balanced_hiding_correctness_type / .\n\n    (** Just check for paren-balanced-ness, not for that it hides the binary operation. *)\n    Definition paren_balanced_correctness_type\n      := (*(fold_right andb true (map (paren_balanced''_nt pb_nts pbh_nts false) pb_nts))\n           && (fold_right andb true (map (paren_balanced''_nt pb_nts pbh_nts false) pbh_nts))\n           &&*) (paren_balanced''_nt pb_nts pbh_nts false (of_nonterminal nt)).\n\n    Global Arguments paren_balanced_hiding_correctness_type / .\n\n    Lemma paren_balanced_hiding_nt_correct\n          (Hvalid : paren_balanced_hiding_correctness_type)\n    : forall str', parse_of_item G str' (NonTerminal nt)\n                   -> paren_balanced_hiding str'.\n    Proof.\n      simpl in Hvalid.\n      apply (paren_balanced_nt_correct true);\n      assumption.\n    Qed.\n  End rule.\nEnd with_lists.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_simpl_example/src/Parsers/Refinement/BinOpBrackets/ParenBalancedGrammar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.236754785512713}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Poulet4.P4light.Syntax.Typed.\nRequire Import Poulet4.P4light.Syntax.Syntax.\nRequire Import Poulet4.P4light.Syntax.Value.\nRequire Import Poulet4.P4light.Semantics.Semantics.\nRequire Import ProD3.core.Coqlib.\nRequire Import ProD3.core.Hoare.\nRequire ProD3.core.AssertionLang.\nRequire Import ProD3.core.AssertionNotations.\nRequire Import ProD3.core.ConcreteHoare.\nRequire Import ProD3.core.Modifies.\nRequire Import ProD3.core.ExtPred.\nRequire Import ProD3.core.Result.\nRequire Import Hammer.Plugin.Hammer.\n\nSection FuncSpec.\n\nContext {tags_t: Type} {tags_t_inhabitant : Inhabitant tags_t}.\nNotation Val := (@ValueBase bool).\nNotation Sval := (@ValueBase (option bool)).\nNotation Lval := ValueLvalue.\n\nNotation ident := (String.string).\nNotation path := (list ident).\n\nContext `{target : @Target tags_t (@Expression tags_t)}.\n\n(* A func spec contains two levels binders. A func spec is like\n  WITH (p : path) ... ,\n    PATH p\n    MOD [...] [...]\n    WITH (x : X) ... ,\n      PRE ...\n      POST ...\n*)\n\nInductive func_spec_hoare : Type :=\n  | fsh_base : arg_assertion -> arg_ret_assertion -> func_spec_hoare\n  | fsh_bind {A} : (A -> func_spec_hoare) -> func_spec_hoare.\n\nRecord func_spec_aux : Type := mk_func_spec {\n  func_spec_p : path;\n  func_spec_body : func_spec_hoare;\n  func_spec_mod_vars : option (list path); (* None means anything can be modified. *)\n  func_spec_mod_exts : list path\n}.\n\nInductive func_spec : Type :=\n  | fs_base : func_spec_aux -> func_spec\n  | fs_bind {A} : (A -> func_spec) -> func_spec.\n\nFixpoint fundef_satisfies_hoare (ge : genv) (p : path) (func : fundef) (targs : list (P4Type)) (fs : func_spec_hoare) :=\n  match fs with\n  | fsh_base pre post =>\n       hoare_func ge p pre func targs post\n  | @fsh_bind A fs =>\n      (* How can we keep binder names? They are preserved when intro-ing them\n        through our tactic. *)\n      forall (x : A), fundef_satisfies_hoare ge p func targs (fs x)\n  end.\n\nDefinition func_sound_aux (ge : genv) (func : fundef) (targs : list (P4Type)) (fs : func_spec_aux) :=\n  let '(mk_func_spec p body vars exts) := fs in\n  fundef_satisfies_hoare ge p func targs body\n    /\\ func_modifies ge p func vars exts.\n\nFixpoint func_sound (ge : genv) (func : fundef) (targs : list (P4Type)) (fs : func_spec) :=\n  match fs with\n  | fs_base fs =>\n      func_sound_aux ge func targs fs\n  | @fs_bind A fs =>\n      (* How can we keep binder names? *)\n      forall (x : A), func_sound ge func targs (fs x)\n  end.\n\nDefinition path_eq_dec : forall (p p' : path), {p = p'} + {p <> p'}.\nProof.\n  apply list_eq_dec, String.string_dec.\nDefined.\n\nDefinition exclude {A} (mods : list path) (l : list (path * A)) :=\n  filter (fun '(p, _) => negb (In_dec path_eq_dec p mods)) l.\n\nFixpoint disjoint (p1 p2 : path) : bool :=\n  match p1 with\n  | [] => false\n  | n :: p1 =>\n      match p2 with\n      | [] => false\n      | m :: p2 =>\n          if String.eqb n m then disjoint p1 p2 else true\n      end\n  end.\n\n(* This is an iff, but we only prove one direction. *)\nLemma disjoint_spec : forall p1 p2,\n  disjoint p1 p2 ->\n  forall q, negb (is_prefix p1 q && is_prefix p2 q).\nProof.\n  induction p1 as [ | s1 p1]; destruct p2 as [ | s2 p2]; intros; inv H.\n  destruct q as [ | t q].\n  - auto.\n  - simpl.\n    destruct (String.eqb s1 s2) eqn:H_eqb_s1_s2;\n      destruct (String.eqb s1 t) eqn:H_eqb_s1_t;\n      destruct (String.eqb s2 t) eqn:H_eqb_s2_t;\n      try auto.\n    + hfcrush use: String.eqb_eq.\n    + hfcrush use: String.eqb_eq.\n    + hauto b: on.\nQed.\n\n(* For symbolic paths, we cannot decide whether two paths are disjoint. So we define a weaker\n  version: we use a tactic to generate a result for each test, which is either disjoint or\n  unknown.\n    We want to separate the decision procedure to test disjoint from the filter process,\n  so we do not directly define a relation (list ext_pred -> list ext_pred -> Prop). *)\n\n(* Test if modifying in the scopes of mods is disjoint from ep. *)\nDefinition ext_disjoint (mods : list path) (ep : ext_pred) :=\n  forallb (fun q => forallb (disjoint q) ep.(ep_paths)) mods.\n\nFixpoint ext_exclude (mods : list path) (a_ext : list ext_pred)\n    (rs : res_list (ext_disjoint mods) a_ext) : list ext_pred.\nProof.\n  inversion rs as [ | ep eps].\n  - exact nil.\n  - exact (\n      if r then ep :: ext_exclude mods eps rs0 else ext_exclude mods eps rs0).\nDefined.\n\nDefinition hoare_func_frame (ge : genv) (p : path) (pre : arg_assertion) (func : @fundef tags_t) (targs : list P4Type) (post : assertion) :=\n  forall st inargs st' outargs sig,\n    pre inargs st ->\n    exec_func ge read_ndetbit p st func targs inargs st' outargs sig ->\n    post st'.\n\nLemma modifies_exts_disjoint : forall (ep : ext_pred) exts st st',\n  modifies_exts exts st st' ->\n  ep (snd st) ->\n  ext_disjoint exts ep ->\n  ep (snd st').\nProof.\n  intros.\n  eapply ep_wellformed; only 2 : eauto.\n  intros; eapply H. clear H.\n  induction exts.\n  - auto.\n  - simpl in H1. rewrite Reflect.andE in H1. destruct H1.\n    assert (~(in_scope p a)). {\n      remember (ep_paths ep) as ps.\n      clear -H H2.\n      induction ps.\n      - auto.\n      - simpl in H. rewrite Reflect.andE in H. destruct H.\n        simpl in H2. rewrite Reflect.orE in H2. destruct H2.\n        + pose proof disjoint_spec.\n          hauto b: on.\n        + auto.\n    }\n    assert (~(in_scopes p exts)). {\n      auto.\n    }\n    clear -H3 H4.\n    hauto b: on.\nQed.\n\nLemma hoare_func_frame_intro : forall ge p a_arg a_mem a_ext func targs vars exts ext_rs a_mem' a_ext',\n  func_modifies_vars ge p func vars ->\n  func_modifies_exts ge p func exts ->\n  force (fun _ => []) (option_map exclude vars) a_mem = a_mem' ->\n  ext_exclude exts a_ext ext_rs = a_ext' ->\n  hoare_func_frame ge p (ARG a_arg (MEM a_mem (EXT a_ext))) func targs (MEM a_mem' (EXT a_ext')).\nProof.\n  unfold func_modifies_vars, func_modifies_exts, hoare_func_frame; intros.\n  destruct st; destruct st'.\n  split.\n  - clear -H H1 H3 H4.\n    destruct vars as [vars | ].\n    2 : { subst; constructor. }\n    specialize (H _ _  _ _ _ _ H4).\n    destruct H3 as [_ []].\n    generalize dependent a_mem'.\n    induction a_mem; intros.\n    + subst. constructor.\n    + simpl in H1. destruct a as [p' ?]. destruct (in_dec path_eq_dec p' vars) as [H_In | H_In].\n      * subst; simpl. apply IHa_mem; auto.\n        inv H0; auto.\n      * subst; simpl. constructor.\n        ++simpl in H; simpl.\n          rewrite <- H by auto.\n          inv H0; auto.\n        ++apply IHa_mem; auto.\n          inv H0; auto.\n  - clear -H0 H2 H3 H4.\n    generalize dependent a_ext'.\n    specialize (H0 _ _  _ _ _ _ H4).\n    destruct H3 as [_ []].\n    induction ext_rs; intros.\n    + subst. constructor.\n    + simpl in H2. destruct r as [H_disjoint | _].\n      * subst; split.\n        ++eapply (modifies_exts_disjoint _ _ _ _ H0 (proj1 H1)).\n          auto.\n        ++apply IHext_rs.\n        { apply H1. }\n        { reflexivity. }\n      * apply IHext_rs.\n        { apply H1. }\n        { apply H2. }\nQed.\n\nInductive func_post_combine : assertion -> arg_ret_assertion -> arg_ret_assertion -> Prop :=\n  | func_post_combine_base : forall f_mem f_ext a_arg a_ret a_mem a_ext,\n      func_post_combine\n        (MEM f_mem (EXT f_ext))\n        (ARG_RET a_arg a_ret (MEM a_mem (EXT a_ext)))\n        (ARG_RET a_arg a_ret (MEM (f_mem ++ a_mem) (EXT (f_ext ++ a_ext))))\n  | func_post_combine_ex : forall [A] F (P : A -> arg_ret_assertion) Q,\n      (forall (x : A), func_post_combine F (P x) (Q x)) ->\n      func_post_combine F (arg_ret_exists P) (arg_ret_exists Q).\n\nLemma func_post_combine_sound : forall outargs retv st F P Q,\n  func_post_combine F P Q ->\n  F st ->\n  P outargs retv st ->\n  Q outargs retv st.\nProof.\n  intros. induction H.\n  - destruct H1 as [? []].\n    split; eauto.\n    split; eauto.\n    destruct st; split.\n    + apply AssertionLang.mem_denote_app. sfirstorder.\n    + apply AssertionLang.ext_denote_app. sfirstorder.\n  - destruct H1.\n    eexists; eauto.\nQed.\n\nLemma func_spec_combine : forall ge p pre pre' func targs post post' frame,\n  arg_implies pre pre' ->\n  hoare_func ge p pre' func targs post' ->\n  hoare_func_frame ge p pre func targs frame ->\n  func_post_combine frame post' post ->\n  hoare_func ge p pre func targs post.\nProof.\n  unfold hoare_func; intros.\n  specialize (H _ _ H3).\n  epose proof (H0 _ _ _ _ _ ltac:(eassumption) ltac:(eassumption)).\n  destruct sig; only 1, 3, 4 : solve [inv H5].\n  eapply (func_post_combine_sound _ _ _ _ _ _ H2); eauto.\nQed.\n\nLemma func_spec_combine' : forall ge p pre_arg pre_mem pre_ext pre_arg' pre_mem' pre_ext' func targs post vars exts ext_rs post' f_mem f_ext,\n  fundef_satisfies_hoare ge p func targs\n    (fsh_base (ARG pre_arg' (MEM pre_mem' (EXT pre_ext'))) post')\n    /\\ func_modifies ge p func vars exts ->\n  arg_implies (ARG pre_arg (MEM pre_mem (EXT pre_ext))) (ARG pre_arg' (MEM pre_mem' (EXT pre_ext'))) ->\n  force (fun _ => []) (option_map exclude vars) pre_mem = f_mem ->\n  ext_exclude exts pre_ext ext_rs = f_ext ->\n  func_post_combine (MEM f_mem (EXT f_ext)) post' post ->\n  hoare_func ge p (ARG pre_arg (MEM pre_mem (EXT pre_ext))) func targs post.\nProof.\n  intros.\n  destruct H.\n  eapply func_spec_combine; eauto.\n  eapply hoare_func_frame_intro; eauto.\n  - destruct vars.\n    + unfold func_modifies_vars; simpl; intros.\n      refine (proj1 (H4 _ _ _ _ _ _ _) _ _); eauto.\n    + unfold func_modifies_vars; simpl; auto.\n  - unfold func_modifies_exts, modifies_exts; intros.\n    refine (proj2 (H4 _ _ _ _ _ _ _) _ _); eauto.\nQed.\n\nEnd FuncSpec.\n\nDeclare Scope func_spec.\nDelimit Scope func_spec with func_spec.\nDeclare Scope func_hoare.\nDelimit Scope func_hoare with func_hoare.\n\nNotation \"'WITH' , P \" :=\n  (fs_base P%func_spec) (at level 65, right associativity) : func_spec.\n\nNotation \"'WITH' x .. y , P \" :=\n  (fs_bind (fun x => .. (fs_bind (fun y => fs_base P%func_spec)) ..)) (at level 65, x binder, y binder, right associativity) : func_spec.\n\nNotation \"'PATH' p 'MOD' vars exts body\" :=\n  (mk_func_spec p body%func_hoare vars exts) (at level 64, vars at level 0, exts at level 0) : func_spec.\n\nNotation \"'WITH' , 'PRE' pre 'POST' post\" :=\n  (fsh_base pre post) (at level 63, right associativity) : func_hoare.\n\nNotation \"'WITH' x .. y , 'PRE' pre 'POST' post\" :=\n  (fsh_bind (fun x => .. (fsh_bind (fun y => fsh_base pre post)) ..)) (at level 63, x binder, y binder, right associativity) : func_hoare.\n", "meta": {"author": "verified-network-toolchain", "repo": "VerifiableP4", "sha": "87afa7bef7d88da2e9a642e37c0ddb2412b57509", "save_path": "github-repos/coq/verified-network-toolchain-VerifiableP4", "path": "github-repos/coq/verified-network-toolchain-VerifiableP4/VerifiableP4-87afa7bef7d88da2e9a642e37c0ddb2412b57509/core/FuncSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093882168609, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23666947174091393}}
{"text": "(*! ORAAT | Proof of the One-rule-at-a-time theorem !*)\nRequire Import\n        Koika.Common Koika.Syntax Koika.TypedSyntax\n        Koika.TypedSyntaxFunctions Koika.SemanticProperties.\nRequire Import Coq.setoid_ring.Ring_theory Coq.setoid_ring.Ring Coq.setoid_ring.Ring.\n\nOpen Scope bool_scope.\n\nSection Proof.\n  Context {pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t: Type}.\n  Context {reg_t_eq_dec: EqDec reg_t}.\n\n  Context {R: reg_t -> type}.\n  Context {Sigma: ext_fn_t -> ExternalSignature}.\n  Context {REnv: Env reg_t}.\n  Context (r: REnv.(env_t) R).\n  Context (sigma: forall f, Sig_denote (Sigma f)).\n\n  Notation Log := (Log R REnv).\n  Notation action := (action pos_t var_t fn_name_t R Sigma).\n  Notation rule := (rule pos_t var_t fn_name_t R Sigma).\n  Notation scheduler := (scheduler pos_t rule_name_t).\n\n  Context (rules: rule_name_t -> rule).\n\n  Fixpoint interp_scheduler'_trace\n           (sched_log: Log)\n           (s: scheduler)\n           {struct s} :=\n    let interp_try rl s1 s2 :=\n        match interp_rule r sigma sched_log (rules rl) with\n        | Some l => match interp_scheduler'_trace (log_app l sched_log) s1 with\n                   | Some (rs, log) => Some (rl :: rs, log)\n                   | None => None\n                   end\n        | None => interp_scheduler'_trace sched_log s2\n        end in\n    match s with\n    | Done => Some ([], sched_log)\n    | Cons rl s => interp_try rl s s\n    | Try rl s1 s2 => interp_try rl s1 s2\n    | SPos _ s => interp_scheduler'_trace sched_log s\n    end.\n\n  Definition interp_scheduler_trace_and_update\n        l\n        (s: scheduler) :=\n    match interp_scheduler'_trace l s with\n    | Some (rs, log) => Some (rs, commit_update r log)\n    | None => None\n    end.\n\n  Definition interp_oraat r rl: REnv.(env_t) R :=\n    interp_cycle sigma rules (Try rl Done Done) r.\n\n  Ltac set_forallb_fns :=\n    repeat match goal with\n           | [  |- context[log_forallb _ _ ?fn] ] =>\n             match fn with\n             | (fun _ => _) => set fn\n             end\n           end.\n\n  Lemma may_read_app_sl :\n    forall (sl sl': Log) prt idx,\n      may_read (log_app sl sl') prt idx =\n      may_read sl prt idx && may_read sl' prt idx.\n  Proof.\n    unfold may_read; intros.\n    destruct prt; rewrite !log_forallb_not_existsb, !log_forallb_app;\n      ring_simplify; f_equal.\n  Qed.\n\n  Lemma may_write_app_sl :\n    forall (sl sl': Log) l prt idx,\n      may_write (log_app sl sl') l prt idx =\n      may_write sl l prt idx && may_write sl' l prt idx.\n  Proof.\n    unfold may_write; intros.\n    destruct prt; rewrite !log_forallb_not_existsb, !log_forallb_app;\n      ring_simplify;\n      repeat (destruct (log_forallb _ _ _); cbn; try reflexivity).\n  Qed.\n\n  Ltac bool_step :=\n    match goal with\n    | _ => progress Common.bool_step\n    | [ H: log_forallb (log_app _ _) _ _ = _ |- _ ] =>\n      rewrite log_forallb_app in H\n    end.\n\n  Lemma may_read0_no_writes :\n    forall (sl: Log) idx,\n      may_read sl P0 idx = true ->\n      latest_write sl idx = None.\n  Proof.\n    unfold may_read; intros.\n    rewrite !log_forallb_not_existsb in H.\n    repeat (cleanup_step || bool_step).\n    unfold log_forallb in *.\n    rewrite forallb_forall in *.\n    unfold is_write0, is_write1, latest_write, log_find in *.\n    apply find_none_notb.\n    intros a HIn.\n    repeat match goal with\n           | [ H: forall (_: LogEntry _), _ |- _ ] => specialize (H a HIn)\n           end.\n    destruct a; cbn in *; destruct kind; subst; try reflexivity.\n    destruct port; cbn in *; try discriminate.\n  Qed.\n\n  Lemma may_read1_latest_write_is_0 :\n    forall (l: Log) idx,\n      may_read l P1 idx = true ->\n      latest_write l idx = latest_write0 l idx.\n  Proof.\n    unfold may_read, latest_write, latest_write0, log_find, log_forallb.\n    intros * H.\n    rewrite log_forallb_not_existsb in H; unfold log_forallb in H.\n    set (getenv REnv l idx) as ls in *; cbn in *; clearbody ls.\n    set (R idx) as t in *; cbn in *.\n    revert H.\n    induction ls.\n    - reflexivity.\n    - intros * H; cbn in H.\n      repeat (bool_step || cleanup_step).\n      rewrite (IHls ltac:(eassumption)).\n      unfold log_latest_write_fn; cbn.\n      destruct a, kind, port; try discriminate; reflexivity.\n  Qed.\n\n  Create HintDb oraat.\n  Hint Unfold interp_cycle : oraat.\n  Hint Unfold interp_oraat : oraat.\n  Hint Unfold interp_rule : oraat.\n\n  Ltac t_step :=\n    match goal with\n    | _ => cleanup_step\n    | _ => progress autounfold with oraat in *\n    | [ H: context[may_read (log_app _ _) _ _] |- _ ] =>\n      rewrite may_read_app_sl in H\n    | [ H: context[may_write (log_app _ _) _ _ _] |- _ ] =>\n      rewrite may_write_app_sl in H\n    | [ H: Some _ = Some _ |- _ ] =>\n      inversion H; subst; clear H\n    | [ H: opt_bind ?x _ = Some _ |- _ ] =>\n      destruct x eqn:?; cbn in H; try discriminate\n    | [ H: match ?x with _ => _ end = Some _ |- _ ] =>\n      destruct x eqn:?; subst; cbn in H; try discriminate\n    | _ =>\n      bool_step\n    | [ H: match ?x with _ => _ end = ?c |- _ ] =>\n      let c_hd := constr_hd c in\n      is_constructor c_hd; destruct x eqn:?\n    | [ H: ?x = _ |- context[match ?x with _ => _ end] ] =>\n      rewrite H\n    | [ H: context[_ -> _ = Some _] |- _ ] =>\n      erewrite H by eauto\n    | _ => reflexivity\n    end.\n\n  Ltac t :=\n    repeat t_step.\n\n  Lemma interp_action_commit:\n    forall {sig tau} (a: action sig tau) (Gamma: tcontext sig) (sl sl': Log) action_log lv,\n      interp_action r sigma Gamma (log_app sl sl') action_log a = Some lv ->\n      interp_action (commit_update r sl') sigma Gamma sl action_log a = Some lv.\n  Proof.\n    fix IH 3; destruct a; cbn;\n      intros Gamma sl sl' action_log lv HSome; try congruence.\n\n    - (* Assign *) t.\n    - (* Seq *) t.\n    - (* Bind *) t.\n    - (* If *) t.\n    - destruct port; t.\n      + (* Read0 *)\n        erewrite getenv_commit_update by eassumption.\n        erewrite may_read0_no_writes by eauto.\n        reflexivity.\n      + (* Read1 *)\n        rewrite log_app_assoc.\n        rewrite (latest_write0_app (log_app action_log sl) sl').\n        destruct latest_write0.\n        * reflexivity.\n        * erewrite getenv_commit_update by eassumption.\n          rewrite may_read1_latest_write_is_0 by eassumption.\n          reflexivity.\n    - (* Write *) t.\n    - (* UnOp *) t.\n    - (* BinOp *) t.\n    - (* ExternalCall *) t.\n    - (* InternalCall *)\n      assert (let interp_action r sigma :=\n                  @interp_action pos_t var_t fn_name_t reg_t ext_fn_t R Sigma REnv r sigma in\n              forall argspec (args: acontext sig argspec) (Gamma: tcontext sig) (sl sl': Log) action_log lv,\n                interp_args' (interp_action r sigma) Gamma (log_app sl sl') action_log args = Some lv ->\n                interp_args' (interp_action (commit_update r sl') sigma) Gamma sl action_log args = Some lv).\n      { clear -IH; intro.\n        fix IHargs 2; destruct args; cbn;\n          intros Gamma sl sl' action_log lv **.\n        + t.\n        + t. }\n      t.\n    - (* APos *) t.\n  Qed.\n\n  Lemma OneRuleAtATime':\n    forall s rs r' l0,\n      interp_scheduler_trace_and_update l0 s = Some (rs, r') ->\n      List.fold_left interp_oraat rs (commit_update r l0) = r'.\n  Proof.\n    induction s; cbn;\n      unfold interp_scheduler_trace_and_update; cbn.\n    - (* Done *) inversion 1; subst; cbn in *; eauto.\n    - (* Cons *) intros; t.\n      + erewrite interp_action_commit by (rewrite log_app_empty_r; eassumption);\n          cbn.\n        rewrite log_app_empty_l.\n        rewrite commit_update_assoc.\n        eapply IHs.\n        unfold interp_scheduler_trace_and_update.\n        rewrite Heqo1; reflexivity.\n      + eapply IHs.\n        unfold interp_scheduler_trace_and_update; rewrite Heqo.\n        reflexivity.\n    - (* Try *) intros; t.\n      + erewrite interp_action_commit by (rewrite log_app_empty_r; eassumption);\n          cbn.\n        rewrite log_app_empty_l.\n        rewrite commit_update_assoc.\n        eapply IHs1.\n        unfold interp_scheduler_trace_and_update.\n        rewrite Heqo1; reflexivity.\n      + eapply IHs2.\n        unfold interp_scheduler_trace_and_update; rewrite Heqo.\n        reflexivity.\n    - (* SPos *) eauto.\n  Qed.\n\n  Lemma interp_scheduler_trace_correct :\n    forall s l0 log,\n      interp_scheduler' r sigma rules l0 s = log ->\n      exists rs, interp_scheduler'_trace l0 s = Some (rs, log).\n  Proof.\n    induction s; cbn.\n    - (* Done *) inversion 1; subst; eauto.\n    - (* Cons *) intros * Heq. destruct interp_rule as [log' | ] eqn:?.\n      + destruct (IHs _ _ Heq) as (rs & Heq').\n        rewrite Heq'; eauto.\n      + destruct (IHs _ _ Heq) as (rs & Heq').\n        rewrite Heq'; eauto.\n    - (* Try *) intros * Heq. destruct interp_rule as [log' | ] eqn:?.\n      + destruct (IHs1 _ _ Heq) as (rs & Heq').\n        rewrite Heq'; eauto.\n      + destruct (IHs2 _ _ Heq) as (rs & Heq').\n        rewrite Heq'; eauto.\n    - (* SPos *) eauto.\n  Qed.\n\n  Lemma scheduler_trace_in_scheduler :\n    forall s log l0 rs,\n      interp_scheduler'_trace l0 s = Some (rs, log) ->\n      (forall r : rule_name_t, In r rs -> In r (scheduler_rules s)).\n  Proof.\n    induction s; cbn in *.\n    - (* Done *) inversion 1; subst; inversion 1.\n    - (* Cons *) intros * H * H'; t.\n      + inversion H'; subst; eauto.\n      + eauto.\n    - (* Try *) intros * H * H'; rewrite in_app_iff; t.\n      + inversion H'; subst; eauto.\n      + eauto.\n    - (* SPos *) eauto.\n  Qed.\n\n  Theorem OneRuleAtATime:\n    forall s log,\n      interp_scheduler r sigma rules s = log ->\n      exists rs,\n        (forall rl, List.In rl rs -> List.In rl (scheduler_rules s)) /\\\n        List.fold_left interp_oraat rs r = commit_update r log.\n  Proof.\n    intros * H.\n    apply interp_scheduler_trace_correct in H; destruct H as (rs & H).\n    exists rs; split.\n    - eauto using scheduler_trace_in_scheduler.\n    - rewrite <- (commit_update_empty r) at 1.\n      eapply OneRuleAtATime'.\n      unfold interp_scheduler_trace_and_update; rewrite H; reflexivity.\n  Qed.\nEnd Proof.\n", "meta": {"author": "mit-plv", "repo": "koika", "sha": "c758c7b0092186f76ed858f4137366cc62f7a04a", "save_path": "github-repos/coq/mit-plv-koika", "path": "github-repos/coq/mit-plv-koika/koika-c758c7b0092186f76ed858f4137366cc62f7a04a/coq/OneRuleAtATime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093882168609, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23666947174091393}}
{"text": "(** printing |-#    %\\vdash_{\\#}%    #&vdash;<sub>&#35;</sub>#     *)\n(** printing |-##   %\\vdash_{\\#\\#}%  #&vdash;<sub>&#35&#35</sub>#  *)\n(** printing |-##v  %\\vdash_{\\#\\#v}% #&vdash;<sub>&#35&#35v</sub># *)\n(** printing |-!    %\\vdash_!%       #&vdash;<sub>!</sub>#         *)\n(** remove printing ~ *)\n\nSet Implicit Arguments.\n\nRequire Import TLC.LibLN.\nRequire Import String.\nRequire Import Coq.Program.Equality.\n\nRequire Import Definitions RecordAndInertTypes Decompose ConstrLangAlt ConstrInterp.\nRequire Import TightTyping GeneralToTight.\nRequire Import ConstrEntailment.\nRequire Import TightConstrInterp.\n\n(** * Tight Entailment for Constraints *)\n\n(** ** Definition of tight entailment *)\nDefinition constr_entail_t (C1 C2 : constr) :=\n  forall tm vm G,\n    inert G ->\n    ok G ->\n    (tm, vm, G) ⊧# C1 -> (tm, vm, G) ⊧# C2.\n\nNotation \"C '⊩#' D\" := (constr_entail_t C D) (at level 50).\n\nLtac introe_t :=\n  match goal with\n  | |- _ => introv Hi Hok He\n  end.\n\n(** * Equivalence Theorems *)\n\nTheorem tight_to_general_entailment : forall C1 C2,\n    C1 ⊩# C2 -> C1 ⊩ C2.\nProof.\n  introv Ht. introe.\n  apply* tight_to_general_interp.\n  apply* Ht.\n  apply* general_to_tight_interp.\nQed.\n\nTheorem general_to_tight_entailment : forall C1 C2,\n    C1 ⊩ C2 -> C1 ⊩# C2.\nProof.\n  introv Ht. introe.\n  apply* general_to_tight_interp.\n  apply* Ht.\n  apply* tight_to_general_interp.\nQed.\n\n", "meta": {"author": "Linyxus", "repo": "constr-dot-calculus", "sha": "111c47bdc58350b8dd0b65ecbeeec783a8df2bc2", "save_path": "github-repos/coq/Linyxus-constr-dot-calculus", "path": "github-repos/coq/Linyxus-constr-dot-calculus/constr-dot-calculus-111c47bdc58350b8dd0b65ecbeeec783a8df2bc2/src/constr-dot/TightConstrEntailment.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.23666946512787237}}
{"text": "(** STG in COQ by Maciej Piróg, University of Wrocław, 2010 *)\n\n(** This library contains the definition of the explicit-environment\nsemantics and proof of its equivalence with the argument-accumulating\nsemantics. *)\n\nRequire Export Heaps.\nRequire Export Sem02.\nRequire Import Min.\n\n(** * Explicit Environment Semantics *)\n\nReserved Notation \"($ a $ b $ g $ e ↓↓↓ c $ d $ h $ f )\"\n  (at level 70, no associativity).\n\nInductive EES : heapB -> expr -> env -> vars -> heapB -> expr -> env ->\n  vars -> Prop :=\n\n| E_Con : forall Gamma C pi sigma,\n  ($ Gamma $ Constr C pi $ sigma $ nil ↓↓↓ Gamma $ Constr C pi $ sigma $ nil)\n\n| E_Accum : forall Gamma Delta x xm sigma_xm qn w rs sigma rho,\n  xm <> nil ->\n  env_map sigma xm = Some sigma_xm ->\n  ($ Gamma $ App x nil $ sigma $ sigma_xm ++ qn ↓↓↓ Delta $ w $ rho $ rs) ->\n  ($ Gamma $ App x xm  $ sigma $ qn             ↓↓↓ Delta $ w $ rho $ rs)\n\n| E_App1 : forall Gamma p x pn m e sigma tau,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m > length pn ->\n  ($ Gamma $ App x nil $ sigma $ pn ↓↓↓ Gamma $ App x nil $ sigma $ pn)\n\n| E_App2_5 : forall Gamma Delta m e x tau p pn w rs sigma rho,\n  env_find sigma x = Some (Atom p) ->\n  Gamma p = Some (Lf_n m e, tau) ->\n  m <= length pn -> \n  ($ Gamma $ e         $ zip_var_list m (firstn m pn) ++ shift m tau $ skipn m pn ↓↓↓ Delta $ w $ rho $ rs) ->\n  ($ Gamma $ App x nil $ sigma                                       $ pn         ↓↓↓ Delta $ w $ rho $ rs)\n\n| E_App4 : forall Gamma Delta sigma tau rho e p x C xs,\n  env_find sigma x = Some (Atom p) -> \n  Gamma p = Some (Lf_u e, tau) ->\n  ($ Gamma $ e         $ tau   $ nil ↓↓↓ Delta                                            $ Constr C xs $ rho $ nil) ->\n  ($ Gamma $ App x nil $ sigma $ nil ↓↓↓ setB Delta p (Lf_n 0 (Constr C xs), trim rho xs) $ Constr C xs $ rho $ nil)\n\n| E_App5 : forall Gamma Delta Theta x p pn y q qk e f n w rs sigma rho nu\n  mu tau,\n  env_find sigma x = Some (Atom p) ->\n  env_find rho y = Some (Atom q) ->\n  Gamma p = Some (Lf_u e, tau) ->\n  Delta q = Some (Lf_n n f, mu) ->\n  length qk < n ->\n  ($ Gamma $ e         $ tau   $ nil      ↓↓↓ Delta $ App y nil      $ rho $ qk) ->\n  ($ setB Delta p (Lf_n (n - length qk) f, trim (zip_var_list (length qk) qk ++ shift (length qk) mu) (fv (Lf_n (n - length qk) f))) $\n             App y nil $ rho   $ qk ++ pn ↓↓↓ Theta $ w              $ nu  $ rs) ->\n  ($ Gamma $ App x nil $ sigma $ pn       ↓↓↓ Theta $ w              $ nu  $ rs)\n\n| E_Let : forall Gamma Delta sigma rho lfs e w (ats : list nat) rs ss,\n  length ats = length lfs ->\n  (forall a : nat, In a ats -> Gamma a = None) -> \n  ($ allocB Gamma ats\n      (map (fun lf => (lf, trim (zip_var_list (length lfs) (map Atom ats) ++ shift (length lfs) sigma) (fv lf))) lfs)\n    $ e $ zip_var_list (length lfs) (map Atom ats) ++ shift (length lfs) sigma $ rs\n    ↓↓↓ Delta $ w $ rho $ ss) ->\n  ($ Gamma $ Letrec lfs e $ sigma $ rs ↓↓↓ Delta $ w $ rho $ ss)\n\n| E_Case_of : forall Gamma Delta Theta b e e0 als ys w c c0 rho_ys rs qs\n  sigma rho nu,\n  length ys = b ->\n  env_map rho ys = Some rho_ys ->\n  select_case als c = Some (Alt c0 b e0) ->\n  ($ Gamma $ e          $ sigma                                  $ nil ↓↓↓ Delta $ Constr c ys $ rho $ nil) ->\n  ($ Delta $ e0         $ zip_var_list b rho_ys ++ shift b sigma $ qs  ↓↓↓ Theta $ w           $ nu $ rs) ->\n  ($ Gamma $ Case e als $ sigma                                  $ qs  ↓↓↓ Theta $ w           $ nu $ rs)\n\nwhere \"($ a $ b $ g $ e ↓↓↓ c $ d $ h $ f )\" := (EES a b g e c d h f).\n\nHint Constructors EES.\n\n(** * [heapB_ok] *)\n\nDefinition heapB_ok (hb : heapB) : Prop :=\n(forall n lf tau, hb n = Some (lf, tau) -> no_atoms_lf lf) /\\\n(forall n lf tau, hb n = Some (lf, tau) ->\n  closed_by_lf (assoc_keys tau) 0 lf).\n\nLemma empty_ok:\nheapB_ok emptyB.\nProof.\nunfold heapB_ok.\nsplit; isa;\nunfold emptyB in *; discriminate.\nQed.\n\n(** * Properties of the semantics *)\n\nLemma no_atoms_EES_no_atoms_aux:\nforall Xi a beta Ps Omega c xi Qs,\n  ($ Xi $ a $ beta $ Ps ↓↓↓ Omega $ c $ xi $ Qs) ->\n  no_atoms a ->\n  (forall n lf tau, Xi n = Some (lf, tau) -> no_atoms_lf lf) ->\n  no_atoms c /\\\n  (forall n lf tau, Omega n = Some (lf, tau) -> no_atoms_lf lf).\nProof with isa; eauto.\nisa.\ninduction H...\n(* [6] Case *)\napply IHEES...\nconstructor...\ninversion H0.\ntrivial.\nconstructor...\ncontradiction.\n(* [5] Case *)\napply IHEES...\nassert (no_atoms_lf (Lf_n m e))...\ninversion_clear H5...\n(* [4] Case *)\nsplit...\napply IHEES...\nassert (no_atoms_lf (Lf_u e))...\ninversion_clear H4...\nunfold setB in H4.\ndestruct eq_nat_dec.\nsubst.\ninversion_clear H4.\nconstructor.\napply IHEES...\nassert (no_atoms_lf (Lf_u e))...\ninversion_clear H4...\nassert (no_atoms_lf (Lf_u e))...\ninversion_clear H5...\napply IHEES in H6...\ndestruct H6...\n(* [3] Case *)\napply IHEES2...\nassert (no_atoms_lf (Lf_u e))...\ninversion_clear H8...\napply IHEES1...\nunfold setB in H8.\nassert (no_atoms_lf (Lf_u e))...\ninversion_clear H9.\ndestruct eq_nat_dec.\nsubst.\ninversion_clear H8.\nassert (no_atoms_lf (Lf_n n f)).\n  apply IHEES1 in H10...\n  destruct H10...\ninversion_clear H8.\nconstructor...\napply IHEES1 in H10;\n  [destruct H10; eapply H10 | eapply H1 ]...\n(* [2] Case *)\ninversion H0; subst.\napply IHEES...\ndestruct (In_dec eq_nat_dec n ats).\napply allocB_in in H4...\neapply in_map_iff in H4.\ndestruct H4.\ndestruct H4.\ninversion H4; subst...\nrewrite map_length...\nrewrite allocB_nin in H4...\n(* [1] Case *)\ninversion H0; subst.\napply IHEES2...\napply In_select_case in H3.\napply H9 in H3.\ninversion H3; subst...\napply IHEES1 in H8...\ndestruct H8...\nQed.\n\nLemma no_atoms_EES_no_atoms :\nforall Xi a beta Ps Omega c xi Qs,\n  ($ Xi $ a $ beta $ Ps ↓↓↓ Omega $ c $ xi $ Qs) ->\n  no_atoms a ->\n  (forall n lf tau, Xi n = Some (lf, tau) -> no_atoms_lf lf) ->\n  no_atoms c.\nProof with eauto.\nintros.\neapply no_atoms_EES_no_atoms_aux in H1...\ndestruct H1...\nQed.\n\n(** * [only_atoms] restriction *)\n\nDefinition oa_heap (hb : heapB) := \nforall v lf tau, hb v = Some (lf, tau) ->\n  forall n a, In (n, a) tau -> is_atom a.\n\nDefinition oa_env (e : env) :=\nforall n a, In (n, a) e -> is_atom a.\n\nDefinition oa_accum (vs : vars) :=\nare_atoms vs.\n\nInductive only_atoms (hb : heapB) (e : env) (vs : vars) : Prop :=\n| oa_c : oa_heap hb -> oa_env e -> oa_accum vs -> only_atoms hb e vs.\n\nLtac oa_inversion OA :=\ncase OA;\n  let  a := fresh \"OA_ACCUM\"\n  with b := fresh \"OA_ENV\"\n  with c := fresh \"OA_HEAP\"\n  in intros c b a.\n\nLemma oa_env_map :\nforall sigma xm sigma_xm,\n  oa_env sigma ->\n  env_map sigma xm = Some sigma_xm ->\n  oa_accum sigma_xm.\nProof with isa; try discriminate.\nisa.\nrevert sigma_xm H0.\ninduction xm...\n(* nil *)\ninversion H0...\nunfold oa_accum...\napply atoms_nil.\n(* cons *)\ndestruct a...\nassert (exists s, env_map sigma xm = Some s).\n  remember_destruct (env_map sigma xm).\n  exists v...\n  rewrite <- X in H0...\ndestruct H1.\nrewrite H1 in *.\nassert (exists p, find_assoc sigma n = Some p).\n  remember_destruct (find_assoc sigma n).\n  exists v...\n  rewrite <- X in H0...\ndestruct H2.\nrewrite H2 in *.\ninversion H0.\nassert (oa_accum x).\n  apply IHxm...\napply find_assoc_in in H2.\nunfold oa_env in H.\nunfold oa_accum.\nunfold are_atoms...\ndestruct H5.\nsubst.\neapply H; eauto.\nunfold oa_accum in H3.\nunfold are_atoms in H3.\napply H3...\nQed.\n\nCreate HintDb oa.\n\nLemma oa_accum_app :\nforall vs ws,\n  oa_accum vs ->\n  oa_accum ws ->\n  oa_accum (vs ++ ws).\nProof.\nintros.\nunfold oa_accum in *.\napply atoms_app; auto.\nQed.\n\nLemma oa_env_app :\nforall sigma tau,\n  oa_env sigma ->\n  oa_env tau ->\n  oa_env (sigma ++ tau).\nProof with intros; eauto.\nintros.\nunfold oa_env in *...\napply in_app_or in H1.\ndestruct H1...\nQed.\n\nLemma oa_env_shift :\nforall m tau,\n  oa_env tau -> oa_env (shift m tau).\nProof with intros; eauto.\nintros.\nunfold oa_env in *...\napply In_shift in H0...\nQed.\n\nLemma oa_heap_val :\nforall Gamma p lf tau,\n  Gamma p = Some (lf, tau) ->\n  oa_heap Gamma ->\n  oa_env tau.\nProof with eauto.\nintros.\nunfold oa_heap in H0.\nunfold oa_env...\nQed.\n\nLemma oa_accum_nil :\noa_accum nil.\nProof.\nunfold oa_accum.\nunfold are_atoms.\nintros.\ninversion H.\nQed.\n\nLemma oa_accum_skipn :\nforall ps n,\n  oa_accum ps ->\n  oa_accum (skipn n ps).\nProof with isa.\nintros.\nunfold oa_accum in *.\napply atoms_skipn...\nQed.\n\nHint Resolve\n  atoms_skipn     In_zip_var_list\n  oa_env_map      oa_accum_app\n  oa_env_app      oa_env_shift\n  oa_heap_val     oa_accum_nil\n  oa_accum_skipn\n: oa.\n\nLemma oa_empty:\noa_heap emptyB.\nProof.\nunfold oa_heap.\nunfold emptyB.\nintros; discriminate.\nQed.\n\nLemma oa_empty_nil_nil:\nonly_atoms emptyB nil nil.\nProof.\nconstructor.\napply oa_empty.\nunfold oa_env; intros; inversion H.\nauto with oa.\nQed.\n\nLemma oa_accum_map_subst_var :\nforall beta x xs,\n  closed_by_expr (assoc_keys beta) 0 (App x xs) ->\n  oa_env beta ->\n  oa_accum (map (subst_var beta) xs).\nProof with auto with oa.\nintros.\ninduction xs...\nsimpl.\ninversion H; subst.\nunfold oa_accum.\ninversion H4.\nunfold are_atoms.\nintros.\ndestruct (eq_var_dec a0 (subst_var beta a)).\n(* eq *)\nsubst.\nelim H1 with (v := a); isa...\napply find_assoc_in_keys_ex_value in H5.\ndestruct H5.\nrewrite <- plus_n_O.\nrewrite H5.\napply find_assoc_in in H5.\nunfold oa_env in H0.\neapply H0; eauto.\ninversion H5.\n(* neq *)\ninversion H2...\n  (* case *)\ndestruct n...\n  (* case *)\nfold (In a0 (map (subst_var beta) xs)) in H5.\nassert (closed_by_expr (assoc_keys beta) 0 (App x xs)).\n  constructor...\n  constructor.\n  intros.\n  apply H1...\n  right...\napply IHxs in H6...\nQed.\n\nLemma oa_setB :\nforall Delta a lf mu,\n  oa_env mu ->\n  oa_heap Delta ->\n  oa_heap (setB Delta a (lf, mu)).\nProof with eauto with oa.\nintros.\nunfold oa_heap in *.\nintros.\nunfold setB in H1.\ndestruct eq_nat_dec...\ninversion H1; subst...\nQed.\n\nLemma oa_env_zip_var_list :\nforall qk n,\n  oa_accum qk ->\n  oa_env (zip_var_list n qk).\nProof with eisa; auto with oa.\nintros.\nunfold oa_env...\nunfold oa_accum in H.\nunfold are_atoms in H.\napply H.\neapply In_zip_var_list...\nQed.\n\nHint Resolve oa_setB oa_env_zip_var_list : oa.\n\nLemma oa_env_trim :\nforall beta xs,\n  oa_env beta ->\n  oa_env (trim beta xs).\nProof with eisa.\nintros.\nunfold trim.\nunfold oa_env in *...\napply filter_In in H0.\ndestruct H0...\nQed.\n\nHint Resolve oa_env_trim : oa.\n\nLemma trim_app_distr :\nforall beta tau vs,\n  trim (beta ++ tau) vs = trim beta vs ++ trim tau vs.\nProof with isa.\ninduction beta...\ndestruct a.\ndestruct In_dec...\nf_equal...\nQed.\n\nLemma In_trim :\nforall beta n a vs,\n  In (n, a) (trim beta vs) ->\n  In (n, a) beta.\nProof with isa.\nintros.\nunfold trim in *.\napply filter_In in H.\ndestruct H...\nQed.\n\nLemma only_atoms_EES_only_atoms :\nforall Xi a beta Ps Omega c xi Qs,\n  ($ Xi $ a $ beta $ Ps ↓↓↓ Omega $ c $ xi $ Qs) ->\n  forall (OA : only_atoms Xi beta Ps),\n  only_atoms Omega xi Qs.\nProof with eauto with oa.\nintros.\noa_inversion OA.\ninduction H.\n(* [8] *)\nconstructor...\n(* [7] *)\napply IHEES...\nconstructor...\n(* [6] *)\nconstructor...\n(* [5] *)\napply IHEES...\nconstructor...\napply oa_env_app...\nunfold oa_env.\nintros.\napply In_zip_var_list in H3.\napply In_firstn in H3...\nunfold oa_accum...\napply oa_env_app...\nunfold oa_env.\nintros.\napply In_zip_var_list in H3.\napply In_firstn in H3...\nunfold oa_accum...\n(* [4] *)\nelim IHEES...\nconstructor...\nconstructor...\n(* [3] *)\nelim IHEES1; isa...\napply IHEES2...\nconstructor...\napply oa_setB...\napply oa_env_trim...\napply oa_setB...\napply oa_env_trim...\nconstructor...\n(* [2] *)\nassert (oa_heap\n          (allocB Gamma ats\n             (map\n                (fun lf : lambda_form =>\n                 (lf, trim\n                 (zip_var_list (length lfs) (map Atom ats) ++\n                 shift (length lfs) sigma) (fv lf))) lfs))).\n  unfold oa_heap.\n  isa.\n  destruct (In_dec eq_nat_dec v ats)...\n    (* in *)\n  apply allocB_in in H2...\n  eapply in_map_iff in H2.\n  destruct H2.\n  destruct H2.\n  inversion H2; subst; clear H2...\n  rewrite trim_app_distr in H3.\n  apply in_app_or in H3.\n  destruct H3.\n  apply In_trim in H2.\n  apply In_zip_var_list in H2.\n  apply in_map_iff in H2.\n  do 2 destruct H2.\n  destruct a.\n  discriminate.\n  simpl...\n  apply In_trim in H2.\n  apply oa_env_shift with (m := length lfs) in OA_ENV.\n  unfold oa_env in OA_ENV...\n  rewrite map_length...\n    (* not in *)\n  rewrite allocB_nin in H2...\nassert (oa_env\n          (zip_var_list (length lfs) (map Atom ats) ++\n           shift (length lfs) sigma)).\n  apply oa_env_app...\n  apply oa_env_zip_var_list.\n  unfold oa_accum.\n  apply atoms_map_atom.\nassert (oa_accum rs)...\napply IHEES...\nconstructor...\n(* [1] *)\nelim IHEES1; isa...\napply IHEES2...\nconstructor...\nconstructor...\nQed.\n\nLemma subst_var_no_index :\nforall sigma n,\n  oa_env sigma ->\n  is_atom (subst_var sigma (Index n)) \\/\n  subst_var sigma (Index n) = Index n.\nProof with eisa.\nintros.\ndestruct (In_dec eq_nat_dec n (assoc_keys sigma)).\n(* in *)\nleft.\nunfold subst_var.\napply find_assoc_in_keys_ex_value in i.\ndestruct i.\nrewrite H0.\napply find_assoc_in in H0.\nunfold oa_env in H.\neapply H...\n(* not in *)\nright.\napply find_assoc_notin in n0.\nunfold subst_var.\nrewrite n0...\nQed.\n\nLemma subst_lemma :\nforall e m tau pn,\n  oa_env tau ->\n  m >= length pn ->\n  (e ~ [shift m tau]) ~ [zip_var_list m pn] =\n  e ~ [zip_var_list m pn ++ shift m tau].\nProof with isa.\nintros.\nunfold subst.\nrewrite map_expr_compose.\nf_equal.\napply functional_extensionality.\nintro v.\nunfold compose.\ndestruct v.\n(* Index *)\ndestruct (le_lt_dec m n).\n  (* <= *)\nrewrite subst_var_app_shift_ge; auto.\napply oa_env_shift with (m := m) in H.\napply subst_var_no_index with (n := n) in H.\ndestruct H.\n   (* left *)\nto_atom (subst_var (shift m tau) (Index n)).\napply subst_var_atom.\n   (* right *)\nrewrite H.\ncutrewrite (zip_var_list m pn = zip_var_list m pn ++ shift m nil).\napply subst_var_app_shift_ge with (tau := shift 0 nil)...\nsimpl.\napply app_nil_end.\n  (* > *)\nrewrite shift_lt_subst_var_id; try auto.\nrewrite subst_var_app_shift_lt...\n(* Atom *)\nunfold compose.\ndo 3 rewrite subst_var_atom...\nQed.\n\nLemma apply_with_offset_shift :\nforall m n v beta,\n  oa_env beta ->\n  apply_with_offset (subst_var beta) (m + n) v =\n  apply_with_offset (subst_var (shift m beta)) n v.\nProof with eisa.\nintros.\nunfold apply_with_offset.\ndestruct v...\ndestruct le_lt_dec.\nunfold plus_offset.\nunfold subst_var.\nunfold minus_offset.\ncutrewrite (n0 - (m + n) = n0 - n - m); try omega.\nrewrite find_assoc_shift.\nremember (find_assoc (shift m beta) (n0 - n)) as F.\nassert (forall v, F = Some v -> is_atom v).\n  intros.\n  symmetry in HeqF.\n  subst.\n  apply find_assoc_in in H0.\n  apply oa_env_shift with (m := m) in H.\n  unfold oa_env in H...\nremember_destruct F.\nassert (is_atom v)...\ndestruct v; try contradiction...\ndestruct le_lt_dec.\nf_equal.\nassert (n < n).\n  omega.\napply n_lt_n_false in H2; contradiction.\ndestruct le_lt_dec; f_equal; omega...\nomega.\ndestruct le_lt_dec...\nassert (n0 - n < m).\n  omega.\nrewrite find_assoc_shift_lt; try omega...\nf_equal.\nomega.\nQed.\n\nLemma map_expr_shift :\nforall beta e m n,\n  oa_env beta ->\n  map_expr (subst_var beta) (m + n) e =\n  map_expr (subst_var (shift m beta)) n e.\nProof with isa.\nintro beta.\ninduction e using expr_ind2 with\n    (P1 := fun (lf : lambda_form) => forall m n,\n      oa_env beta ->\n      map_lf (subst_var beta) (m + n) lf =\n      map_lf (subst_var (shift m beta)) n lf)\n    (P2 := fun (al : alt) => forall m n,\n      oa_env beta ->\n      map_alt (subst_var beta) (m + n) al =\n      map_alt (subst_var (shift m beta)) n al);\n  intros; try unfold subst; simpl; try f_equal;\n  try rewrite <- plus_assoc; isa;\n  try apply map_ext_in; isa;\n  try apply map_ext; isa;\n  try apply apply_with_offset_shift...\nQed.\n\nLemma subst_shift :\nforall beta m e,\n  oa_env beta ->\n  map_expr (subst_var beta) m e = e~[shift m beta].\nProof with isa.\nintros.\nassert (m = m + 0); try omega.\nrewrite H0 at 1.\napply map_expr_shift...\nQed.\n\nLemma alloc_similar_no_trim :\nforall (lfsF : defs) atsF beta\n(LENGTHF : length lfsF = length atsF)\nats XiP Gamma lfs pi0 pi1 b0 b1 e tau etau a\n(SIMILAR : similar Gamma XiP)\n(LENGTH : length ats = length lfs)\n(OA_ENV : oa_env beta)\n(B : allocB XiP ats\n       (map\n          (fun lf : lambda_form =>\n           (lf,\n           zip_var_list (length lfsF) (map Atom atsF) ++\n           shift (length lfsF) beta)) lfs) a = Some (Lf pi1 b1 e, tau))\n(A : allocA Gamma (map Atom ats)\n       (map (subst_lf (zip_var_list (length lfsF) (map Atom atsF)))\n          (map (map_lf (subst_var beta) (length lfsF)) lfs)) (Atom a) =\n     Some (Lf pi0 b0 etau)),\npi0 = pi1 /\\ b0 = b1 /\\ etau = e~[shift b1 tau].\nProof with eisa.\ninduction ats.\n(* [2] nil *)\nisa.\ndestruct lfs; simpl in *; try discriminate...\nunfold allocA in A...\nunfold allocB in B...\ndestruct SIMILAR.\ndestruct H0...\n(* [1] cons *)\nisa.\ndestruct lfs; simpl in *; try discriminate...\nunfold allocA in A...\nunfold allocB in B...\ndestruct (eq_nat_dec a a0); try subst a0... \n  (* eq *)\nunfold setA in A.\nunfold setB in B.\ndestruct eq_var_dec; try tauto...\ndestruct eq_nat_dec; try tauto...\ndestruct l.\ninversion A; subst.\ninversion B; subst.\nsplit...\nsplit...\nrewrite subst_shift.\nrewrite subst_shift...\nrewrite shift_app_distr.\nrewrite shift_zip_var_list; try (rewrite map_length; omega).\nrewrite shift_cummulative.\nrewrite plus_comm.\napply subst_lemma; try (rewrite map_length; omega)...\nunfold oa_env...\napply In_zip_var_list in H.\napply in_map_iff in H.\ndo 2 destruct H.\nsubst.\nunfold is_atom...\n  (* neq *)\nunfold allocA in IHats.\nunfold allocB in IHats.\nunfold setA in *.\nunfold setB in *.\nassert (a0 <> a); auto.\ndestruct eq_var_dec; try tauto...\ndestruct eq_nat_dec; try tauto...\ninversion e0; tauto.\ndestruct eq_nat_dec; try tauto...\nQed.\n\nLemma trim_fv :\nforall e b k atsF pi beta\n  (OA : oa_env beta),\n  k >= length atsF ->\n  e~[shift b (trim\n      (zip_var_list k (map Atom atsF) ++\n       shift k beta) (fv (Lf pi b e)))] =\n  e~[shift b (zip_var_list k (map Atom atsF) ++\n       shift k beta)].\nProof with isa.\nintros.\nassert (map_lf (subst_var (zip_var_list k (map Atom atsF) ++\n    shift k beta)) 0 (Lf pi b e) =\n    map_lf (subst_var (trim (zip_var_list k (map Atom atsF) ++\n    shift k beta) (fv (Lf pi b e)))) 0 (Lf pi b e)).\n  apply trim_fv_lf.\nassert (OA2 : oa_env (zip_var_list k (map Atom atsF) ++ shift k beta)).\n  apply oa_env_app.\n  unfold oa_env...\n  apply In_zip_var_list in H1.\n  apply in_map_iff in H1.\n  destruct H1.\n  destruct H1.\n  subst...\n  apply oa_env_shift...\nsimpl in H0.\ninversion H0; subst.\nunfold subst.\nassert (H1 : b = b + 0); auto with arith.\nrewrite H1 in H2 at 1 3.\nrewrite map_expr_shift in H2...\nrewrite map_expr_shift in H2.\nsymmetry in H2...\napply oa_env_trim...\nQed.\n\n(** * Completeness *)\n\nLemma alloc_similar :\nforall (lfsF : defs) atsF beta\n(LENGTHF : length lfsF = length atsF)\nats XiP Gamma lfs pi0 pi1 b0 b1 e tau etau a\n(SIMILAR : similar Gamma XiP)\n(LENGTH : length ats = length lfs)\n(OA_ENV : oa_env beta)\n(B : allocB XiP ats\n       (map\n          (fun lf : lambda_form =>\n           (lf, trim\n             (zip_var_list (length lfsF) (map Atom atsF) ++\n             shift (length lfsF) beta) (fv lf))) lfs) a =\n           Some (Lf pi1 b1 e, tau))\n(A : allocA Gamma (map Atom ats)\n       (map (subst_lf (zip_var_list (length lfsF) (map Atom atsF)))\n          (map (map_lf (subst_var beta) (length lfsF)) lfs)) (Atom a) =\n     Some (Lf pi0 b0 etau)),\npi0 = pi1 /\\ b0 = b1 /\\ etau = e~[shift b1 tau].\nProof with eisa.\ninduction ats...\n(* [2] nil *)\ndestruct lfs; simpl in *; try discriminate...\nunfold allocA in A...\nunfold allocB in B...\ndestruct SIMILAR.\ndestruct H0...\n(* [1] cons *)\ndestruct lfs; simpl in *; try discriminate...\nunfold allocA in A...\nunfold allocB in B...\ndestruct (eq_nat_dec a a0); try subst a0... \n  (* eq *)\nunfold setA in A.\nunfold setB in B.\ndestruct eq_var_dec; try tauto...\ndestruct eq_nat_dec; try tauto...\ndestruct l.\ninversion A; subst.\ninversion B; subst.\nsplit...\nsplit...\nrewrite trim_fv; try omega...\nrewrite subst_shift.\nrewrite subst_shift...\nrewrite shift_app_distr.\nrewrite shift_zip_var_list; try (rewrite map_length; omega).\nrewrite shift_cummulative.\nrewrite plus_comm.\napply subst_lemma; try (rewrite map_length; omega)...\nunfold oa_env...\napply In_zip_var_list in H.\napply in_map_iff in H.\ndestruct H.\ndestruct H.\nsubst.\nunfold is_atom...\n  (* neq *)\nunfold allocA in IHats.\nunfold allocB in IHats.\nunfold setA in *.\nunfold setB in *.\nassert (a0 <> a); auto.\ndestruct eq_var_dec; try tauto...\ndestruct eq_nat_dec; try tauto...\ninversion e0; tauto.\ndestruct eq_nat_dec; try tauto...\nQed.\n\nLemma select_case_subst :\nforall als als0 c c0 b e beta\n  (OA : oa_env beta),\n  select_case als c = Some (Alt c0 b e) ->\n  als = map (map_alt (subst_var beta) 0) als0 ->\n  exists e0,\n  select_case als0 c = Some (Alt c0 b e0) /\\ \n  e = e0~[shift b beta].\nProof with isa.\ninduction als...\ndiscriminate.\ndestruct als0...\ndiscriminate.\ndestruct a.\ndestruct a0.\ndestruct eq_nat_dec.\n(* c = c1 *)\ninversion H0; subst.\ninversion H; subst; clear H.\ndestruct eq_nat_dec; try tauto.\nclear e.\nexists e1.\nsplit...\napply subst_shift...\n(* c <> c1 *)\ninversion H0; subst.\ndestruct eq_nat_dec; subst...\ntauto.\nQed.\n\nLemma lf_subst_lemma :\nforall ats lfs sigma,\n  oa_env sigma ->\n  length lfs = length ats ->\n  map (subst_lf (zip_var_list (length lfs) (map Atom ats) ++\n    shift (length lfs) sigma)) lfs =\n  map (subst_lf (zip_var_list (length lfs) (map Atom ats)))\n       (map (map_lf (subst_var sigma) (length lfs)) lfs).\nProof with isa.\nintros.\nrewrite map_map.\napply map_ext_in...\ndestruct a.\nunfold subst_lf...\nf_equal...\nrewrite subst_shift.\ncutrewrite (b = b + 0)...\nrewrite map_expr_shift...\nrewrite map_expr_shift...\nrewrite map_expr_shift...\nsimpl_arith.\nrewrite shift_app_distr.\nrewrite shift_cummulative.\nrewrite shift_zip_var_list.\nrewrite plus_comm at 1.\nrewrite <- subst_lemma.\nunfold subst.\ncutrewrite (b + length lfs = length lfs + b)...\n(* premises *)\nomega.\ntrivial.\nrewrite map_length; omega.\nrewrite map_length; omega.\nauto with oa.\napply oa_env_zip_var_list.\nunfold oa_accum.\napply atoms_map_atom...\napply oa_env_app; auto with oa.\napply oa_env_zip_var_list.\nunfold oa_accum.\napply atoms_map_atom...\nQed.\n\nLemma select_case_subst_right :\nforall als c c0 b e beta\n  (OA : oa_env beta),\n  select_case als c = Some (Alt c0 b e) ->\n  select_case (map (map_alt (subst_var beta) 0) als) c =\n    Some (Alt c0 b (e~[shift b beta])).\nProof with isa.\ninduction als...\ndiscriminate.\ndestruct a...\ndestruct eq_nat_dec...\ninversion_clear H.\nf_equal...\nf_equal...\napply subst_shift...\nQed.\n\nLemma oa_accum_map :\nforall vs,\n  oa_accum vs -> \n  exists ns, vs = map Atom ns.\nProof with isa.\nintros.\ninduction vs.\n(* nil *)\nexists nil...\n(* cons *)\nunfold oa_accum in *.\ndupl H.\napply atoms_head in H.\nto_atom a.\napply atoms_tail in H0.\nintuition.\ndestruct H1.\nexists (a :: x)...\nf_equal...\nQed.\n\nProposition EES_complete :\nforall Xi Omega abeta Ps Qs cxi,\n    ($ Xi $ abeta $ Ps ↓↓ Omega $ cxi $ Qs) ->\n    forall a beta,\n    closed_by_expr (assoc_keys beta) 0 a ->\n    abeta = a~[beta] ->\n    no_atoms a ->\n  forall XiP, similar Xi XiP -> heapB_ok XiP ->\n  forall (ONLYATOMS : only_atoms XiP beta Ps),\n  exists OmegaP, exists xi, exists c,\n    similar Omega OmegaP /\\\n    ($ XiP $ a $ beta $ Ps ↓↓↓ OmegaP $ c $ xi $ Qs) /\\\n    closed_by_expr (assoc_keys xi) 0 c /\\\n    cxi = c~[xi] /\\\n    heapB_ok OmegaP.\nProof with isa.\nintros ? ? ebeta ? ? ? H.\ndupl H. rename H0 into CASE.\ninduction H; intros a beta CBY EQe NOATOMS...\n(* [8] Case Con *)\nsubst_inversion EQe.\nexists XiP.\nexists beta.\nexists (Constr C vs)...\n(* [7] Case Accum *)\nsubst_inversion EQe.\napply IHAAS with (XiP := XiP) (beta := beta) (a := App x nil) in H0...\n  (* thesis *)\ndestruct H0 as [x0 [x1 [ x2 []]]].\ndestruct H3.\ndestruct H6.\ndestruct H7.\nexists x0.\nexists x1.\nexists x2.\n    (* similar *)\nsplit...\n    (* reduction *)\nsplit.\neapply E_Accum with (sigma_xm := map (subst_var beta) xs).\n      (* xs <> nil *)\neapply map_neq_nil; eauto.\n      (* env_map *)\ninversion_clear CBY.\napply env_map_map_subst...\ninversion_clear NOATOMS...\n      (* premise *)\nrewrite H5 in H3.\napply H3.\n    (* closed, subst and heap_ok*)\nauto.\n  (* premises of the IH *)\n    (* closed_by_expr *)\ninversion_clear CBY.\nconstructor...\nconstructor...\ncontradiction.\n    (* subst *)\nunfold subst; subst...\nrewrite apply_with_offset_0_v...\n    (* no_atoms *)\ninversion_clear NOATOMS.\nconstructor...\nconstructor; isa; contradiction.\n    (* only_atoms *)\noa_inversion ONLYATOMS.\nconstructor; auto with oa.\napply oa_accum_app...\nsubst; apply oa_accum_map_subst_var with (x := x)...\n(* [6] Case App1 *)\nsubst_inversion EQe.\ndestruct xs; [ | discriminate ]...\nexists XiP.\nexists beta.\nexists (App x nil).\n  (* similar *)\nsplit...\n  (* reduction *)\nsplit...\ndupl H.\napply similar_dom_atom with (GammaP := XiP) in H3...\ndestruct p; try contradiction...\nsimilar_value H XiP.\napply E_App1 with (p := a) (m := m) (e := x0) (tau := x1)...\n    (* env_find *)\napply subst_var_env_find...\ninversion NOATOMS...\n  (* closed *)\nsplit...\n  (* subst *)\nsplit.\nunfold subst; subst...\nrewrite apply_with_offset_0_v...\n  (* heap_ok *)\nauto.\n(* [5] Case App2_5 *)\nsubst_inversion EQe.\ndupl H.\napply similar_dom_atom with (GammaP := XiP) in H4...\ndestruct p; try contradiction...\nsimilar_value H XiP.\nrename e into etau.\nrename x1 into tau.\nrename x0 into e.\napply IHAAS with (XiP := XiP) (a := e)\n  (beta := zip_var_list m (firstn m pn) ++ shift m tau) in H1...\n  (* thesis *)\nclear IHAAS.\ndestruct H1 as [x0 [x1 [x2 []]]].\ndestruct H8.\nexists x0.\nexists x1.\nexists x2.\n    (* similar *)\nsplit...\n    (* reduction *)\nsplit.\ndestruct xs; [ | discriminate ]...\neapply E_App2_5 with (sigma := beta) (x := x) (p := a) in H8...\n      (* env_find *)\napply subst_var_env_find...\ninversion NOATOMS...\n    (* closed, subst and keap_ok *)\nauto.\n  (* premises of the IH *)\n    (* closed_by_expr *)\ninversion_clear H3.\napply H9 in H.\ninversion H; subst.\nclear IHAAS H1.\nsimpl in H10.\nassert (ZER : 0 = length (firstn m pn) - length (firstn m pn)).\n  auto with *.\nassert (LEN : m = length (firstn m pn)).\n  symmetry.\n  apply firstn_le_length...\nrewrite LEN at 1.\nrewrite LEN at 3.\nrewrite LEN in H10.\nrewrite ZER.\napply closed_transfer...\n    (* subst *)\nrewrite H7.\napply subst_lemma.\noa_inversion ONLYATOMS.\neapply oa_heap_val; eauto.\nrewrite firstn_length.\nauto with arith.\n    (* no_atoms *)\ninversion_clear H3.\nset (lf := Lf Dont_update m e).\nassert (no_atoms_lf lf).\n  eapply H8.\n  apply H.\ninversion_clear H3...\n    (* only_atoms *)\noa_inversion ONLYATOMS.\nconstructor...\napply oa_env_app...\n  unfold oa_env...\n  apply In_zip_var_list in H8.\n  apply In_firstn in H8...\napply oa_env_shift.\neapply oa_heap_val; eauto.\napply oa_accum_skipn...\n(* [4] Case App4 *)\nsubst_inversion EQe.\ndestruct xs; [ | discriminate ]...\ndupl H.\napply similar_dom_atom with (GammaP := XiP) in H3...\ndestruct p; try contradiction...\nsimilar_value H XiP.\nrename e into etau.\nrename x0 into e.\nrename x1 into tau.\napply IHAAS with (XiP := XiP) (a := e) (beta := tau) in H0...\n  (* thesis *)\ndestruct H0 as [x0 [x1 [x2 []]]].\ndestruct H7.\ndestruct H8.\ndestruct H9.\nsubst_inversion H9.\napply E_App4 with (x := x) (sigma := beta) (p := a) in H7... (* A *)\nexists (setB x0 a (Lf_n 0 (Constr C vs), trim x1 vs)).\nexists x1.\nexists (Constr C vs).\n    (* similar *)\nsplit...\nunfold similar.\n      (* similar 1 *)\nsplit.\nintro.\nrewrite <- H4.\nunfold setA.\ndestruct eq_var_dec; [ discriminate | ]...\ninversion_clear H0.\napply H6.\n      (* similar 2 *)\nsplit.\nintro.\nrewrite <- H4.\nunfold setA.\nunfold setB.\ndestruct eq_nat_dec; destruct eq_var_dec.\nsubst; split; intro; discriminate.\nsubst; destruct n; auto.\ninversion e0; tauto.\ninversion_clear H0.\ninversion_clear H11.\napply H0.\n      (* similar 3 *)\ninversion_clear H0.\ninversion_clear H11.\nrewrite <- H4.\nunfold setA.\nunfold setB.\nintros.\ndestruct eq_nat_dec; destruct eq_var_dec; subst;\n  inversion H11; inversion H13; subst...\nrewrite shift_0_v.\n  rewrite H9.\n  split...\n  split...\n  unfold subst...\n  f_equal.\n  rewrite apply_with_offset_0_id.\n  rewrite apply_with_offset_0_id.\n  rewrite subst_trim_vars...  \ndestruct n; auto.\ninversion e1; tauto.\napply H12 with (a := a0)...\n    (* reduction *)\nsplit.\nclear IHAAS...\n    (* closed*)\nsplit...\n    (* subst *)\nsplit...\n    (* heap_ok *)\nunfold heapB_ok.\n      (* heap_ok 1 *)\nsplit...\nunfold setB in H6.\ndestruct eq_nat_dec.\n  inversion H6.\n  subst.\n  apply no_atoms_EES_no_atoms in H7...\n  constructor...\n  destruct H2.\n  eauto.\ndestruct H10.\neapply H10...\napply H6.\n      (* heap_ok 2 *)\nunfold setB in H6.\ndestruct eq_nat_dec.\n  subst.\n  inversion H6.\n  subst.\n  constructor.\n  clear IHAAS.\n  simpl_arith.\n  inversion H8; subst.\n  constructor.\n  apply closed_trim_vars...\ndestruct H10.\neapply H11.\napply H6.\n    (* A (env_find) *)\napply subst_var_env_find...\ninversion NOATOMS...\n  (* premises of the IH *)\n    (* closed_by_expr *)\ninversion_clear H2.\nset (lf := Lf Update 0 e).\nassert (closed_by_lf (assoc_keys tau) 0 lf).\n  eapply H8.\n  apply H.\ninversion_clear H2...\n    (* subst *)\nrewrite H6.\nrewrite shift_0_v.\ntrivial.\n    (* no_atoms *)\ninversion_clear H2.\nset (lf := Lf Update 0 e).\nassert (no_atoms_lf lf).\n  eapply H7.\n  apply H.\ninversion_clear H2...\n    (* only_atoms *)\noa_inversion ONLYATOMS.\nconstructor...\neapply oa_heap_val; eauto.\n(* [3] Case E_App5 *)\nsubst_inversion EQe.\ndupl H.\napply similar_dom_atom with (GammaP := XiP) in H6...\ndestruct p; try contradiction...\nsimilar_value H XiP.\nrename e into etau.\nrename x0 into e.\nrename x1 into tau.\nrewrite shift_0_v in H9.\neapply IHAAS1 with (a := e) (beta := tau) (XiP := XiP) in H2...\n  (* thesis *)\ndestruct H2.\nrename x0 into DeltaP.\ndestruct H2.\nrename x0 into rho.\ndestruct H2 as [x0 []].\ndestruct H10.\ndestruct H11.\ndestruct H12.\nsubst_inversion H12.\ndestruct xs0; isa; try discriminate.\ndestruct xs;  isa; try discriminate.\ndupl H0.\napply similar_dom_atom with (GammaP := DeltaP) in H9...\ndestruct q; try contradiction...\nsimilar_value H0 DeltaP.\nrename f into fmu.\nrename x0 into f.\nrename x2 into mu.\napply IHAAS2 with (a1 := App x1 nil) (beta := rho)\n    (XiP := setB DeltaP a\n      (Lf_n (n - length qk) f, trim (zip_var_list (length qk) qk ++\n        shift (length qk) mu) (fv (Lf_n (n - length qk) f))))\n  in H3...\n  (* thesis *)\ndestruct H3.\nrename x0 into OmegaP.\ndestruct H3.\nrename x0 into xi.\ndestruct H3.\ndestruct H3.\ndestruct H17.\ndestruct H18.\ndestruct H19.\nexists OmegaP.\nexists xi.\nexists x0.\n    (* similar *)\nsplit...\n    (* reduction *)\nsplit.\napply E_App5 with (p := a) (q := a0) (n := n) (Theta := OmegaP)\n  (x := x) (pn := pn) (rs := rs) (nu := xi) (w := x0)\n  (sigma := beta) (f := f) (mu := mu) in H10...\n      (* env_find 1 *)\napply subst_var_env_find...\ninversion NOATOMS...\n      (* env_find 2 *)\napply subst_var_env_find...\napply no_atoms_EES_no_atoms in H10.\ndestruct H5.\ninversion H10...\n  set (lf := Lf Update 0 e).\n  assert (no_atoms_lf lf).\n    eapply H5.\n    eauto.\ninversion_clear H21...\napply H5.\n    (* closed, subst and heap_ok *)\nauto.\n  (* premises of IHAAS2 *)\n    (* subst *)\nunfold subst...\nrewrite apply_with_offset_0_v...\n    (* no_atoms *)\napply no_atoms_EES_no_atoms in H10...\nset (lf := Lf_u e).\nassert (no_atoms_lf lf).\n  destruct H5.\n  eapply H5.\n  eauto.\ninversion_clear H17...\ndestruct H5.\neapply H5.\neauto.\n    (* similar *)\n      (* similar 1 *)\nsplit.\nintro.\nunfold setA.\ndestruct eq_var_dec; try discriminate...\ninversion_clear H2.\napply H17.\n      (* similar 2 *)\nsplit.\nintro.\nunfold setA.\nunfold setB.\ndestruct eq_nat_dec; destruct eq_var_dec.\nsubst; split; intro; discriminate.\nsubst; destruct n0; auto.\ninversion e0; tauto.\ninversion_clear H2.\ninversion_clear H18.\napply H2.\n      (* similar 3 *)\ninversion_clear H2.\ninversion_clear H18.\nunfold setA.\nunfold setB.\nintros.\ndestruct eq_nat_dec; destruct eq_var_dec; subst;\n  inversion H18; inversion H20; subst.\nsplit...\nsplit...\napply only_atoms_EES_only_atoms in H10.\noa_inversion H10.\napply oa_accum_map in OA_ACCUM.\ncase OA_ACCUM.\nintros x0 EQ.\nrewrite -> EQ.\nunfold Lf_n.\nrewrite trim_fv.\nrewrite shift_app_distr.\nrewrite shift_cummulative.\nrewrite <- EQ.\nclear x0 EQ.\ncutrewrite (n - length qk + length qk = n).\nrewrite shift_zip_var_list.\ncutrewrite (length qk + (n - length qk) = n)...\napply subst_lemma.\napply oa_heap_val with (Gamma := DeltaP) (p := a0) (lf := Lf_n n e0)...\nomega.\nomega.\nomega.\nomega.\nclear IHAAS1.\nclear IHAAS2.\nunfold oa_heap in OA_HEAP.\nunfold oa_env.\neapply OA_HEAP; eauto.\nrewrite map_length; omega.\noa_inversion ONLYATOMS.\nassert (oa_env tau).\n  eapply oa_heap_val; eauto.\nassert (only_atoms XiP beta nil).\n  constructor; auto with oa.\napply only_atoms_EES_only_atoms in H10.\noa_inversion H10...\nconstructor; auto with oa.\nconstructor; auto with oa.\ndestruct n0; auto.\ninversion e1; tauto.\napply H19 with (a := a1)...\n    (* heap_ok *)\nunfold heapB_ok.\n      (* heap_ok 1 *)\nsplit...\nunfold setB in H17.\ndestruct eq_nat_dec.\n  inversion H17.\n  subst.\n  inversion H13.\n  set (lf := Lf_n n f).\n  assert (no_atoms_lf lf).\n    eapply H16.\n    apply H0.\n  inversion_clear H19.\n  constructor...\ninversion H13.\neapply H18...\neauto.\n      (* heap_ok 2 *)\nunfold setB in H17.\ndestruct eq_nat_dec.\n        (* eq *)\ninversion H17; subst.\nclear IHAAS1 IHAAS2.\ninversion H13; subst.\napply H18 in H0.\ninversion H0; subst...\nconstructor...\napply closed_trim_fv.\napply closed_transfer...\nomega.\n        (* neq *)\ninversion H13; subst.\neapply H19; eauto.\n    (* only_atoms *)\noa_inversion ONLYATOMS.\nassert (oa_env tau).\n  eapply oa_heap_val; eauto.\nassert (only_atoms XiP tau nil).\n  constructor; auto with oa.\napply only_atoms_EES_only_atoms in H10...\noa_inversion H10.\nconstructor; auto with oa.\napply oa_setB...\napply oa_env_trim.\napply oa_env_app.\napply oa_env_zip_var_list...\n  apply oa_env_shift.\n  eapply oa_heap_val; eauto.\n  (* premises of IHAAS1 *)\n    (* closed_by_expr *)\ninversion H5.\nset (lf := Lf Update 0 e).\nassert (closed_by_lf (assoc_keys tau) 0 lf).\n  eapply H11.\n  apply H.\ninversion_clear H12...\n    (* no_atoms *)\ninversion H5.\nset (lf := Lf Update 0 e).\nassert (no_atoms_lf lf).\n  eapply H10.\n  apply H.\ninversion_clear H12...\n    (* only_atoms *)\noa_inversion ONLYATOMS.\nconstructor; auto with oa...\neapply oa_heap_val; eauto.\n(* [2] Case Let *)\nsubst_inversion EQe.\napply atoms_exists in H0.\ndestruct H0.\nrename x into ats0.\nassert (length lfs = length lfs0).\n  rewrite H6.\n  rewrite map_length.\n  trivial.\nrename H5 into H9.\napply IHAAS with\n    (XiP := allocB XiP ats0 (map\n      (fun lf => (lf, trim (zip_var_list (length lfs) (map Atom ats0)\n        ++ shift (length lfs) beta) (fv lf))) lfs0))\n    (a := e0)\n    (beta := zip_var_list (length lfs0) (map Atom ats0) ++\n      shift (length lfs0) beta)\n  in H2...\n  (* thesis *)\nclear IHAAS.\ndestruct H2 as [x [x0 [x1 []]]].\ndestruct H5.\nrename x into DeltaP.\nrename w into wxi.\nrename x1 into w.\nrename x0 into xi.\nexists DeltaP.\nexists xi.\nexists w.\n    (* similar *)\nsplit...\n    (* reduction *)\nrewrite H9 in H5.\napply E_Let in H5...\n      (* length *)\nrewrite H0 in H.\nrewrite map_length in H.\nrewrite H6 in H.\nrewrite map_length in H.\ntrivial.\n      (* freshness *)\nrewrite H0 in H1.\ndestruct H3.\ndestruct H11.\napply H11 in H1.\napply H1.\napply in_map...\n  (* premises of the IH *)\n    (* closed_by_expr *)\ninversion CBY; subst...\nclear IHAAS H2.\nassert (LEN : length lfs0 = length (map Atom ats0)).\n  rewrite map_length in *.\n  rewrite map_length in H.\n  auto.\nassert (ZER : 0 = length (map Atom ats0) - length (map Atom ats0)).\n  omega.\nrewrite LEN in *.\nrewrite ZER.\napply closed_transfer...\n  (* subst *)\nrewrite H7.\noa_inversion ONLYATOMS.\nrewrite subst_shift...\nrewrite <- H0.\nrewrite H9.\noa_inversion ONLYATOMS.\napply subst_lemma...\nomega.\n  (* no_atoms *)\ninversion NOATOMS...\n  (* similar *)\n    (* similar 1 *)\nsplit...\ndestruct (In_dec eq_var_dec (Index n) ats).\n      (* in *)\nrewrite H0 in i.\nrewrite in_map_iff in i.\ndestruct i.\ndestruct H5.\ndiscriminate.\n      (* not in *)\nrewrite allocA_nin...\ninversion H3...\n    (* similar 2 *)\nsplit...\ndestruct (In_dec eq_nat_dec a ats0).\n      (* in *)\nrewrite H0.\ndupl i.\neapply allocB_some with (H := XiP) in i.\ndestruct i.\nrewrite H5; clear H5.\nassert (In (Atom a) ats).\n  rewrite H0.\n  apply in_map...\neapply allocA_some with (H := Gamma) in H5.\ndestruct H5.\nrewrite <- H0.\nrewrite H5.\nintuition; discriminate.\nrewrite map_length...\nrewrite map_length...\nrewrite H0 in H.\nrewrite map_length in H.\nrewrite H6 in H.\nrewrite map_length in H.\ntrivial.\n      (* not in *)\ninversion H3.\ninversion H8.\nrewrite allocA_nin...\nrewrite allocB_nin...\nrewrite H0.\nintro.\napply in_map_iff in H12.\ndestruct H12.\ndestruct H12.\ninversion H12.\nrewrite H15 in H13.\ntauto.\n    (* similar 3 *)\nsubst.\noa_inversion ONLYATOMS.\nrewrite map_length in *.\nrewrite map_length in *.\neapply alloc_similar; eauto...\n  (* heapB_ok *)\n    (* no_atoms *)\nsplit...\ndestruct (In_dec eq_nat_dec n ats0).\n      (* in *)\napply allocB_in in H5...\napply in_map_iff in H5.\ndestruct H5.\ndestruct H5.\ninversion H5.\ninversion NOATOMS.\nsubst.\napply H14...\nrewrite map_length.\nsubst.\nrewrite map_length in H.\nrewrite map_length in H...\n      (* not in *)\nrewrite allocB_nin in H5...\ninversion H4.\neapply H8; eauto...\n    (* closed_by *)\ndestruct (In_dec eq_nat_dec n ats0).\n      (* in *)\napply allocB_in in H5.\napply in_map_iff in H5.\ndestruct H5.\ndestruct H5.\ninversion CBY; subst.\nclear IHAAS.\nclear H2.\ninversion H5; subst.\nclear H5.\ndestruct lf.\nconstructor...\nclear EQe.\nclear CASE.\napply H12 in H8.\nrewrite map_length.\ninversion H8; subst.\nassert (LEN : length lfs0 = length (map Atom ats0)).\n  rewrite map_length in *.\n  rewrite map_length in H.\n  symmetry...\nassert (B : b = length lfs0 + b - length lfs0).\n  auto with arith.\napply closed_trim_fv.\nrewrite B.\nrewrite LEN.\napply closed_transfer; try omega...\nrewrite <- LEN...\nrewrite map_length.\nrewrite H0 in H.\nrewrite map_length in H.\nrewrite H9 in H...\nauto.\n      (* not in *)\nrewrite allocB_nin in H5...\ndestruct H4.\neapply H8; eauto.\n  (* only_atoms *)\noa_inversion ONLYATOMS.\nconstructor.\n    (* heap *)\nunfold oa_heap...\ndestruct (In_dec eq_nat_dec v ats0).\n      (* in *)\napply allocB_in in H5...\napply in_map_iff in H5.\ndestruct H5.\ndestruct H5.\ninversion H5.\nassert (oa_env tau).\n  rewrite <- H13.\n  apply oa_env_trim.\n  apply oa_env_app; auto with oa.\n  apply oa_env_zip_var_list.\n  unfold oa_accum.\n  apply atoms_map_atom.\nunfold oa_env in H11.\neauto.\nrewrite map_length.\nrewrite H0 in H.\nrewrite map_length in H.\nrewrite H6 in H.\nrewrite map_length in H...\n      (* not in *)\nrewrite allocB_nin in H5...\neauto with oa.\n    (* env *)\napply oa_env_app; auto with oa.\napply oa_env_zip_var_list.\nunfold oa_accum.\napply atoms_map_atom.\n    (* accum *)\nauto.\n(* [1] Case Case_of *)\nsubst_inversion EQe.\noa_inversion ONLYATOMS.\ndestruct (select_case_subst als als0 c c0 (length ps) e0 beta)...\ndestruct H.\nrename x into e00.\napply IHAAS1 with (XiP := XiP) (beta := beta) (a := f) in H1...\n  (* thesis *)\ndestruct H1.\ndestruct H1.\ndestruct H1.\ndestruct H1.\ndestruct H8.\nrename x into DeltaP.\nrename x0 into rho.\ndestruct H9.\ndestruct H10.\nsubst_inversion H10.\nclear EQe.\napply IHAAS2 with (XiP := DeltaP) (beta0 := \n    zip_var_list (length ps) ps ++\n    shift (length ps) beta)\n  (a := e00) in H2...\n    (* thesis *)\nclear IHAAS1.\nclear IHAAS2.\ndestruct H2.\ndestruct H2.\ndestruct H2.\nrename x into ThetaP.\nrename x0 into xi.\nrename x1 into d.\ndestruct H2.\ndestruct H5.\nexists ThetaP.\nexists xi.\nexists d.\ndestruct H6.\ndestruct H7.\n      (* similar *)\nsplit...\n      (* reduction *)\nsplit.\napply E_Case_of with (Delta := DeltaP) (e0 := e00) (rho := rho) (c := c)\n  (c0 := c0) (ys := vs) (b := length ps) (rho_ys := ps)...\n        (* length *)\nunfold subst in H10; simpl in H10; inversion H10.\nrewrite map_length...\n        (* env_map *)\nrewrite env_map_map_subst.\nunfold subst in H10; simpl in H10; inversion H10.\nrewrite apply_with_offset_0_id...\ninversion NOATOMS; subst.\napply no_atoms_EES_no_atoms in H8...\ninversion H8; subst.\ninversion H8; subst...\ndestruct H4.\neapply H4; eauto.\ninversion H9; subst...\n      (*  closed_by, subst and heap_ok *)\nsplit...\n    (* premises of the second IH *)\n      (* closed_by *)\nclear CASE IHAAS1 IHAAS2.\ninversion CBY; subst.\napply In_select_case in H.\napply H12 in H.\ninversion H; subst...\nassert (ZER : 0 = length ps - length ps); try omega.\nrewrite ZER.\napply closed_transfer...\n      (* subst*)\napply subst_lemma.\noa_inversion ONLYATOMS...\nomega.\n      (* no_atoms *)\ninversion NOATOMS; subst.\napply In_select_case in H.\napply H12 in H.\ninversion H; subst...\n      (* only_atoms *)\noa_inversion ONLYATOMS.\nclear IHAAS1.\nclear IHAAS2.\napply only_atoms_EES_only_atoms in H8.\ninversion H8; subst; constructor...\napply oa_env_app; auto with oa.\napply oa_env_zip_var_list.\ninversion H9; subst.\nunfold subst in H10; simpl in H10.\nrewrite apply_with_offset_0_id in H10.\ninversion H10.\napply oa_accum_map_subst_var with (x := Atom 0)...\nconstructor; auto; constructor...\nconstructor; auto with oa.\n  (* premises of the first IH *)\n    (* closed_by *)\ninversion CBY; subst...\n    (* no_atoms *)\ninversion NOATOMS; subst...\n    (* only_atoms *)\noa_inversion ONLYATOMS.\nconstructor; auto with oa.\nQed.\n\n(** * Soundness *)\n\nProposition EES_sound :\nforall GammaP e beta rs OmegaP f xi qs\n    (RED : ($ GammaP $ e $ beta $ rs ↓↓↓ OmegaP $ f $ xi $ qs))\n    (Gamma : heapA)\n    (NOATOMS : no_atoms e)\n    (ONLYATOMS : only_atoms GammaP beta rs)\n    (OK_GammaP : heapB_ok GammaP)\n    (SIM_Gamma : similar Gamma GammaP)\n    (CLOSED : closed_by_expr (assoc_keys beta) 0 e),\n  exists Omega,\n    ($ Gamma $ e~[beta] $ rs ↓↓ Omega $ f~[xi] $ qs) /\\\n    similar Omega OmegaP /\\\n    heapB_ok OmegaP /\\\n    closed_by_expr (assoc_keys xi) 0 f.\nProof with isa.\nintros ? ? ? ? ? ? ? ? ?.\ninduction RED...\n(* [8] Case Con *)\nexists Gamma0.\nsplit...\nunfold subst...\n(* [7] Case Accum *)\napply IHRED in SIM_Gamma...\ndestruct SIM_Gamma.\ndestruct H1.\nexists x0.\nsplit...\napply A_Accum.\ndestruct xm...\nintro; discriminate.\nunfold subst in H1...\nrewrite apply_with_offset_0_v in *.\nrewrite apply_with_offset_0_id in *.\napply map_subst_env_map in H0.\nrewrite H0.\ninversion NOATOMS; subst...\nconstructor...\ninversion NOATOMS; subst...\nconstructor; isa; contradiction.\noa_inversion ONLYATOMS.\nconstructor...\napply oa_accum_app...\neapply oa_env_map; eauto.\ninversion CLOSED; subst.\nconstructor...\nconstructor...\ncontradiction.\n(* [6] Case App1 *)\nexists Gamma0.\nsplit...\napply env_find_subst_var in H.\nunfold subst...\nrewrite apply_with_offset_0_id.\nrewrite H.\neapply similar_value_left in H0; eauto.\n(* [5] Case App2_5 *)\nassert (TAU : oa_env tau).\n  oa_inversion ONLYATOMS.\n  unfold oa_heap in OA_HEAP.\n  unfold oa_env.\n  eapply OA_HEAP; eauto.\nassert (E : no_atoms e).\n  destruct OK_GammaP.\n  apply H2 in H0.\n  inversion H0; subst...\nassert (CLOSED_E : closed_by_expr\n    (assoc_keys (zip_var_list m (firstn m pn) ++ shift m tau)) 0 e).\n  destruct OK_GammaP.\n  apply H3 in H0.\n  inversion H0; subst...  \n  cutrewrite (0 = m - m).\n  assert (m = length (firstn m pn)).\n    symmetry.\n    apply firstn_le_length...\n  rewrite H4 at 1 3 4 5.\n  apply closed_transfer.\n  trivial.\n  rewrite <- H4...\n  omega.\napply env_find_subst_var in H.\neapply similar_value_left in H0; eauto.\napply IHRED in SIM_Gamma...\ndestruct SIM_Gamma.\ndestruct H2.\nexists x0.\nsplit...\neapply A_App2_5; eauto.\nclear IHRED.\nrewrite apply_with_offset_0_id.\nrewrite H.\napply H0.\nrewrite subst_lemma...\nrewrite firstn_length.\nauto with arith.\noa_inversion ONLYATOMS.\nconstructor; auto with oa.\napply oa_env_app; auto with oa.\napply oa_env_zip_var_list.\nunfold oa_accum in *.\napply atoms_firstn...\n(* [4] Case App4 *)\nassert (TAU : oa_env tau).\n  oa_inversion ONLYATOMS.\n  unfold oa_heap in OA_HEAP.\n  unfold oa_env.\n  eapply OA_HEAP; eauto.\nassert (E : no_atoms e).\n  destruct OK_GammaP.\n  apply H1 in H0.\n  inversion H0; subst...\nassert (CLOSED_E : closed_by_expr (assoc_keys tau) 0 e).\n  destruct OK_GammaP.\n  apply H2 in H0.\n  inversion H0; subst...  \neapply similar_value_left in H0; eauto.\ndupl SIM_Gamma.\napply IHRED in SIM_Gamma0...\ndestruct SIM_Gamma0.\nexists (setA x0 (Atom p) (Lf_n 0 ((Constr C xs)~[rho]))).\nunfold subst...\nrewrite apply_with_offset_0_v.\nrewrite apply_with_offset_0_id.\napply env_find_subst_var in H.\nrewrite H.\nsplit.\neapply A_App4; eauto.\nrewrite shift_0_v.\ndestruct H1.\nunfold subst in *...\nrewrite apply_with_offset_0_id in *...\nsplit.\n  (* similar *)\nunfold similar.\n    (* similar 1 *)\nsplit.\nintro.\nunfold setA.\ndestruct eq_var_dec; [ discriminate | ]...\ndestruct H1.\ndestruct H2.\ninversion_clear H2.\napply H4.\n      (* similar 2 *)\nsplit.\nintro.\nunfold setA.\nunfold setB.\ndestruct eq_nat_dec; destruct eq_var_dec.\nsubst; split; intro; discriminate.\nsubst; destruct n; auto.\ninversion e0; tauto.\ndestruct H1.\ndestruct H2.\ninversion_clear H2.\ninversion_clear H5.\napply H2.\n      (* similar 3 *)\ndestruct H1.\ndestruct H2.\ninversion_clear H2.\ninversion_clear H5.\nunfold setA.\nunfold setB.\nintros.\ndestruct eq_nat_dec; destruct eq_var_dec; subst;\n  inversion H5; inversion H7; subst...\nrewrite shift_0_v; auto.\n  split...\n  split...\n  unfold subst...\n  rewrite apply_with_offset_0_id...\n  f_equal.\n  apply subst_trim_vars.\ndestruct n; auto.\ninversion e1; tauto.\napply H6 with (a := a)...\n  (* heap_ok *)\nsplit.\ndestruct H1.\ndestruct H2.\nunfold heapB_ok.\n    (* heap_ok 1 *)\nsplit...\nunfold setB in H4.\ndestruct eq_nat_dec.\n  inversion H4.\n  subst.\n  apply no_atoms_EES_no_atoms in RED...\n  constructor...\n  destruct OK_GammaP.\n  eauto.\ndestruct H3.\neapply H3...\napply H4.\n      (* heap_ok 2 *)\nunfold setB in H4.\ndestruct eq_nat_dec.\n  subst.\n  inversion H4.\n  subst.\n  constructor.\n  destruct H3...\n  constructor.\n  inversion H5; subst.\n  apply closed_trim_vars...\ndestruct H3.\ndestruct H3.\neapply H6.\napply H4.\n    (* closed_by *)\ntauto.\n  (* only_atoms *)\noa_inversion ONLYATOMS.\nconstructor...\n(* [3] Case App5 *)\nassert (TAU : oa_env tau).\n  oa_inversion ONLYATOMS.\n  unfold oa_heap in OA_HEAP.\n  unfold oa_env.\n  eapply OA_HEAP; eauto.\nassert (CLOSED_E : closed_by_expr (assoc_keys tau) 0 e).\n  destruct OK_GammaP.\n  apply H5 in H1.\n  inversion H1; subst...  \ndupl SIM_Gamma.\napply IHRED1 in SIM_Gamma0...\ndestruct SIM_Gamma0.\ndestruct H4.\ndestruct H5.\ndestruct H6.\nrename Delta into DeltaP.\nrename x0 into Delta.\nremember (f~[shift n mu]) as fmu.\napply IHRED2 with (Gamma := setA Delta (Atom p)\n  (Lf_n (n - length qk) (fmu~[zip_var_list n qk]))) in H7.\ndestruct H7.\nexists x0.\n    (* red *)\nsplit.\nunfold subst...\nrewrite apply_with_offset_0_v.\napply env_find_subst_var in H.\nrewrite H.\nremember (w~[nu]) as wnu.\ndupl Heqwnu.\nunfold subst in Heqwnu0.\nrewrite <- Heqwnu0.\nremember (e~[tau]) as etau.\nunfold subst in H4...\nrewrite apply_with_offset_0_v in H4.\napply env_find_subst_var in H0.\nrewrite H0 in H4.\ndestruct H7.\napply A_App5 with (Delta := Delta) (q := Atom q) (qk := qk)\n  (e := etau) (f := fmu) (n := n)...\n      (* App *)\neapply similar_value_left in H1; eauto.\nrewrite shift_0_v in H1.\nsubst...\n      (* App *)\neapply similar_value_left in H2; eauto.\nsubst...\n      (* App *)\nassert (QQQ : App y nil ~ [rho] = App (Atom q) nil).\n  unfold subst...\n  rewrite apply_with_offset_0_v.\n  rewrite H0...\nrewrite QQQ in H7...\n    (* similar *)\ndestruct H7.\ndestruct H8.\ndestruct H9...\n  (* no atoms *)\nunfold env_find in H0.\ndestruct y...\nconstructor.\nconstructor.\nconstructor...\ncontradiction.\ndiscriminate.\n  (* only atoms *)\noa_inversion ONLYATOMS.\napply only_atoms_EES_only_atoms in RED1.\noa_inversion RED1...\nconstructor...\n    (* heap *)\nunfold oa_heap...\nunfold setB in H8.\ndestruct eq_nat_dec.\n      (* eq *)\ninversion H8; subst; clear H8.\napply In_trim in H9.\napply in_app_or in H9.\ndestruct H9.\napply In_zip_var_list in H8...\nassert (OAMU : oa_env mu).\n  unfold oa_heap in OA_HEAP0.\n  unfold oa_env...\n  eapply OA_HEAP0; eauto...\napply oa_env_shift with (m := length qk) in OAMU.\nunfold oa_env in OAMU.\neapply OAMU; eauto.\n      (* neq *)\nassert (OATAU0 : oa_env tau0).\nunfold oa_heap in OA_HEAP0.\nunfold oa_env...\neapply OA_HEAP0; eauto...\nunfold oa_env in OATAU0.\neapply OATAU0; eauto.\n    (* accum *)\napply oa_accum_app...\nconstructor; auto with oa.\n  (* heap_ok *)\nunfold heapB_ok.\n    (* heap_ok 1 *)\nsplit...\nunfold setB in H8.\ndestruct eq_nat_dec.\n      (* eq *)\ninversion H8; subst; clear H8.\ndestruct H6.\napply H6 in H2.\ninversion H2; subst.\nconstructor...\n      (* neq *)\ndestruct H6.\neapply H6; eauto.\n    (* heap_ok 2 *)\nunfold setB in H8.\ndestruct eq_nat_dec.\n      (* eq *)\ninversion H8; subst; clear H8.\ndestruct H6.\napply H8 in H2.\ninversion H2; subst.\nconstructor...\napply closed_trim_fv.\napply closed_transfer...\nomega.\n      (* neq *)\ndestruct H6.\neapply H9; eauto.\n  (* similar *)\nunfold similar.\n    (* similar 1 *)\nsplit...\nunfold setA.\ndestruct eq_var_dec.\ndiscriminate.\ndestruct H5...\n    (* similar 2 *)\nsplit...\nunfold setA.\nunfold setB.\ndestruct eq_nat_dec; destruct eq_var_dec.\nsubst; split; intro; discriminate.\nsubst; destruct n0; auto.\ninversion e0; tauto.\ninversion_clear H5.\ninversion_clear H9.\napply H5.\n    (* similar 3 *)\ninversion_clear H5.\ninversion_clear H11.\nunfold setA in *.\nunfold setB in *.\ndestruct eq_nat_dec; destruct eq_var_dec; subst;\n  inversion H8; inversion H9; subst...\nsplit...\nsplit...\n  apply only_atoms_EES_only_atoms in RED1.\n  oa_inversion RED1.\n  apply oa_accum_map in OA_ACCUM.\n  case OA_ACCUM.\n  intros x0 EQ.\n  rewrite -> EQ.\n  unfold Lf_n.\n  rewrite trim_fv.\n  rewrite shift_app_distr.\n  rewrite shift_cummulative.\n  rewrite <- EQ.\n  clear x0 EQ.\n  cutrewrite (n - length qk + length qk = n).\n  rewrite shift_zip_var_list.\n  cutrewrite (length qk + (n - length qk) = n)...\n  apply subst_lemma.\napply oa_heap_val with (Gamma := DeltaP) (p := q) (lf := Lf_n n e0)...\nomega.\nomega.\nomega.\nomega.\nunfold oa_heap in OA_HEAP.\nunfold oa_env.\neapply OA_HEAP; eauto.\nrewrite map_length; omega.\noa_inversion ONLYATOMS.\nassert (oa_env tau).\n  eapply oa_heap_val; eauto.\nassert (only_atoms Gamma sigma nil).\n  constructor; auto with oa.\napply only_atoms_EES_only_atoms in RED1.\noa_inversion RED1...\nconstructor; auto with oa.\nconstructor; auto with oa.\ndestruct n0; auto.\ninversion e1; tauto.\napply H12 with (a := a)...\n  (* no atoms *)\ndestruct OK_GammaP.\napply H4 in H1.\ninversion H1; subst...\n  (* only atoms *)\noa_inversion ONLYATOMS.\nconstructor...\nunfold oa_accum.\napply atoms_nil.\n(* [2] Case Let *)\nrename Gamma into GammaP.\nrename Gamma0 into Gamma.\nassert (NAE : no_atoms e).\n  inversion NOATOMS...\napply IHRED with\n    (Gamma := allocA Gamma (map Atom ats)\n    (map (subst_lf (zip_var_list (length lfs) (map Atom ats) ++\n      shift (length lfs) sigma)) lfs))\n  in NAE.\ndestruct NAE.\nrename Delta into DeltaP.\nrename x into Delta.\nexists Delta.\n  (* thesis *)\noa_inversion ONLYATOMS.\ndestruct H1.\ndestruct H2.\ndestruct H3.\nsplit...\nremember (w~[rho]) as wrho.\nunfold subst...\napply A_Let with (ats := map Atom ats).\n    (* length *)\nrewrite map_length.\nrewrite map_length.\ntrivial.\n    (* atoms *)\napply atoms_map_atom.\n    (* freshness *)\nintros.\nclear IHRED.\ndestruct SIM_Gamma.\ninversion H7.\nassert (is_atom a).\n  apply atom_in_map_atom with (ats := ats)...\nto_atom a.\ncase H8 with (a := a)...\napply H12.\napply H0.\napply in_map_iff in H5.\ndestruct H5.\ndestruct H5.\ninversion H5; subst...\n    (* red *)\nrewrite map_length.\nrewrite subst_shift.\nrewrite subst_lemma...\nrewrite lf_subst_lemma in H1...\nrewrite map_length.\nrewrite <- H.\napply le_refl.\ntrivial.\n  (* premises of the IH *)\n    (* only atoms *)\noa_inversion ONLYATOMS.\nconstructor...\nunfold oa_heap...\ndestruct (In_dec eq_nat_dec v ats).\n      (* in *)\napply allocB_in in H1.\napply in_map_iff in H1.\ndestruct H1.\ndestruct H1.\ninversion H1; subst; clear H1.\napply In_trim in H2.\napply in_app_or in H2.\ndestruct H2.\napply In_zip_var_list in H1.\napply in_map_iff in H1.\ndestruct H1.\ndestruct H1.\nsubst...\napply oa_env_shift with (m := length lfs) in OA_ENV...\nunfold oa_env in OA_ENV.\neauto.\nrewrite map_length...\nauto.\n      (* not in *)\nrewrite allocB_nin in H1...\nunfold oa_heap in OA_HEAP.\neapply OA_HEAP; eauto.\n    (*  *)\napply oa_env_app; auto with oa.\napply oa_env_zip_var_list; auto with oa.\nunfold oa_accum.\napply atoms_map_atom.\n    (* heap ok *)\nunfold heapB_ok.\n      (* heap ok 1 *)\nsplit...\ndestruct (In_dec eq_nat_dec n ats).\n        (* in *)\napply allocB_in in H1...\napply in_map_iff in H1.\ndestruct H1.\ndestruct H1.\ninversion H1; subst; clear H1.\ninversion NOATOMS; subst.\napply H4...\nrewrite map_length...\n        (* not in *)\nrewrite allocB_nin in H1...\nunfold heapB_ok in OK_GammaP.\ndestruct OK_GammaP.\neauto.\n      (* heap ok 2 *)\ndestruct (In_dec eq_nat_dec n ats).\n        (* in *)\napply allocB_in in H1...\napply in_map_iff in H1.\ndestruct H1.\ndestruct H1.\ninversion H1; subst; clear H1.\ninversion CLOSED; subst.\napply H4 in H2...\ninversion H2; subst.\napply closed_transfer with (qk := map Atom ats) in H1.\nconstructor...\napply closed_trim_fv.\nassert (L : length lfs + b - length (map Atom ats) = b).\n  rewrite map_length.\n  rewrite <- H.\n  auto with arith.\nrewrite L in H1.\ncutrewrite (length lfs = length (map Atom ats))...\n  rewrite map_length...\nrewrite map_length...\nrewrite <- H.\nauto with arith.\nrewrite map_length...\n        (* not in *)\nrewrite allocB_nin in H1...\nunfold heapB_ok in OK_GammaP.\ndestruct OK_GammaP.\neauto.\n    (* similar *)\nunfold similar.\n      (* similar 1 *)\nsplit...\ndestruct (In_dec eq_var_dec (Index n) (map Atom ats))...\n        (* in *)\napply in_map_iff in i.\ndestruct i.\ndestruct H1.\ndiscriminate.\n        (* not in *)\nrewrite allocA_nin...\nunfold similar in SIM_Gamma.\ndestruct SIM_Gamma...\n      (* similar 2 *)\nsplit...\ndestruct (In_dec eq_nat_dec a ats).\n        (* in *)\ndupl i.\neapply allocB_some with (H := GammaP) in i0.\ndestruct i0.\nrewrite H1; clear H1.\ndupl i.\napply in_map with (f := Atom) in i0.\neapply allocA_some with (H := Gamma) in i0.\ndestruct i0.\nrewrite H1.\nintuition; discriminate.\nrewrite map_length.\nrewrite map_length...\nrewrite map_length...\n        (* not in *)\ninversion SIM_Gamma.\ninversion H2.\nrewrite allocA_nin...\nrewrite allocB_nin...\nintro.\napply in_map_iff in H5.\ndestruct H5.\ndestruct H5.\ninversion H5.\nrewrite H8 in H6.\ntauto.\n      (* similar 3 *)\noa_inversion ONLYATOMS.\neapply alloc_similar; eauto...\nrewrite <- lf_subst_lemma...\n    (* closed by *)\ninversion CLOSED; subst.\nrewrite plus_comm in H4.\napply closed_transfer with (qk := (map Atom ats)) in H4.\ncutrewrite (0 = length lfs + 0 - length lfs); try omega.\nrewrite assoc_keys_app_distr in *.\nassert (length lfs = length (map Atom ats)).\n  rewrite map_length...\nrewrite H1 in *...\nrewrite map_length in *.\nrewrite <- H.\nauto with arith.\n(* [1] Case Case_of *)\ndupl SIM_Gamma.\napply IHRED1 in SIM_Gamma0...\ndestruct SIM_Gamma0.\ndestruct H2.\ndestruct H3.\ndestruct H4.\nclear IHRED1.\nrename Delta into DeltaP.\nrename x into Delta.\ndupl H4.\napply IHRED2 with (Gamma := Delta) in H4...\ndestruct H4.\ndestruct H4.\ndestruct H7.\ndestruct H8.\nclear IHRED2.\nexists x.\nsplit...\noa_inversion ONLYATOMS.\napply map_subst_env_map in H0.\napply select_case_subst_right with (beta := sigma) in H1...\nassert (CYS : Constr c ys ~ [rho] = Constr c rho_ys).\n  unfold subst...\n  rewrite apply_with_offset_0_id.\n  rewrite H0...\nrewrite CYS in H2.\napply A_Case_of with (Delta := Delta) (b := b) (e0 := e0 ~ [shift b sigma])\n  (c := c) (c0 := c0) (ps := rho_ys)...\n  (* length *)\nrewrite <- H0.\nrewrite map_length...\n  (* reduction *)\nrewrite subst_lemma...\n  (* length *)\nrewrite <- H0.\nrewrite map_length...\nomega.\n  (* no atoms in alt *)\nclear IHRED2.\ninversion NOATOMS; subst.\napply In_select_case in H1.\napply H10 in H1.\ninversion H1; subst...\n  (* only atoms *)\noa_inversion ONLYATOMS.\napply only_atoms_EES_only_atoms in RED1.\noa_inversion RED1.\nconstructor...\napply oa_env_app; auto with oa.\napply oa_env_zip_var_list.\neapply oa_env_map; eauto.\nconstructor; auto with oa.\n  (* closed by *)\nclear IHRED2.\ninversion CLOSED; subst.\napply In_select_case in H1.\napply H10 in H1.\ninversion H1; subst...\nassert (LRHO : length ys = length rho_ys).\n  apply map_subst_env_map in H0.\n  rewrite <- H0.\n  rewrite map_length...\ncutrewrite (0 = length rho_ys - length rho_ys); try omega.\nrewrite LRHO in *.\napply closed_transfer...\n  (* no atoms *)\ninversion NOATOMS; subst...\n  (* only atoms *)\noa_inversion ONLYATOMS.\nconstructor; auto with oa.\n  (* closed by *)\ninversion CLOSED...\nQed.\n", "meta": {"author": "maciejpirog", "repo": "stg-in-coq", "sha": "0e2ca64f0ed31b634f1031349dc2715c14b6e78e", "save_path": "github-repos/coq/maciejpirog-stg-in-coq", "path": "github-repos/coq/maciejpirog-stg-in-coq/stg-in-coq-0e2ca64f0ed31b634f1031349dc2715c14b6e78e/stg/src/Sem03.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.23666946512787237}}
{"text": "From MSSL Require Import Syntax.\nRequire Import Coq.FSets.FMapList.\nRequire Import Coq.Structures.OrdersEx.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Structures.OrderedTypeEx.\nRequire Import Syntax.\nRequire Import Relations.\n\n\nRequire Import List.\nImport ListNotations.\nRequire Import Variables.\n\nRequire Import Monoid MonoidExamples.\nRequire Import Functor.\nRequire Import Coq.Sets.Ensembles.\nOpen Scope type_scope.\n\nRequire Import Coq.Program.Basics.\n\nRequire Import Lifetime Store LVal Value.\n\nRequire Import Transition.\n\nRequire Import Monad.\nOpen Scope monad_scope.\n\n\nOpen Scope type_scope.\n   \n    Import MSSLSyntax.\n    Import Value.\n\n    Module D <: StoreDomain. \n        Definition loc := location.\n        Definition val := partialValue * sum Lifetime.t nat.\n    End D.\n\n    Module S := Store (D).\n\n    Definition isValue (e : expression) : Prop :=\n            match e with EVal v => True | _ => False end.\n\n    Definition getValue (e : expression) (H : isValue e) : Value.value :=\n        match e as e0 return (isValue e0 -> Value.value) with \n            | EVal v => const v\n            | _ => False_rect _ \n        end H.\n\n\n\n\n    Coercion EVal : Value.value >-> expression.\n\n    Axiom instantiate : S.t -> Lifetime.t -> expression -> expression.\n\n    Definition threadId := nat.\n    Definition pool := list (threadId * expression * Lifetime.t).\n\n\nInductive context : Type :=\n    | CEmpty : context \n    | CSeq : context -> expression -> context \n    | CBinding : Var.t -> context -> context \n    | CAssign : lval -> context -> context \n    | CBox : context -> context \n    | CTrc : context -> context \n    | CSpawn : Var.t -> list Value.value -> context -> list expression -> context.\n\nFixpoint build (c : context) (e : expression) : expression :=\n    match c with \n        | CEmpty => e \n        | CSeq c e' => ESeq (build c e) e' \n        | CBinding x c =>  EBinding x (build c e) \n        | CAssign w c => EAssign w (build c e)\n        | CBox c => EBox (build c e)\n        | CTrc c => ETrc (build c e)\n        | CSpawn f vl c el => ESpawn f ((List.map EVal vl)++[(build c e)]++el)\n        end.\n\n    Definition lstate := S.t * expression.\n\n\n    Definition read (σ : S.t) (l : Lifetime.t) (ω : lval) : \n        option (Value.partialValue * sum Lifetime.t nat) :=\n            S.loc σ l ω >>= S.get σ.\n    \n    Definition write (σ : S.t) (l : Lifetime.t) (ω : lval)  (v : Value.partialValue) : \n        option S.t :=\n            S.loc σ l ω >>= (fun a => S.get σ a >>= (fun x =>  S.set σ a (v, snd x))).\n    \n    Inductive step (p : program) (l : Lifetime.t) :\n        transition lstate pool :=\n            S_Copy : forall σ ω v m, \n            read σ l ω = Some (Some v, m) ->\n            step p l (σ, ERead Copy ω)  [] (σ, EVal v)\n        |   S_Move : forall σ ω v σ' m, \n            read σ l ω = Some (Some v, m) ->\n            write σ l ω None = Some σ' ->  \n            step p l (σ, ERead Move ω) [] (σ', EVal v)\n        |   S_Box : forall  (σ σ' : S.t) (m : nat) (v : value),\n            ~ S.defined σ (inr m) ->\n            S.allocate σ [(inr m, (Some v, inl Lifetime.glob))] = Some σ' -> \n            step p l (σ, EBox v) [] (σ', EVal (Value.Location (inr m) Owned))\n        |   S_Trc : forall  (σ σ' : S.t) (m : nat) (v : value),\n            ~ S.defined σ (inr m) ->\n            S.allocate σ [(inr m, (Some v, inr 1))] = Some σ' -> \n            step p l (σ, ETrc v) [] (σ', EVal (Location (inr m) (Trc true)))\n        |   S_Clone : forall  (σ σ' : S.t) (ω : lval) (m i : nat), \n            read σ l ω = Some (Some (Location (inr m) (Trc true)), inr i) ->\n            S.clone σ l ω = Some σ' ->\n            step p l (σ, EClone ω) [] (σ', EVal (Location (inr m) (Trc false)))\n        |   S_Borrow : forall σ ω ℓ b,\n            S.loc σ l ω = Some ℓ ->\n            step p l (σ, ERef b ω) [] (σ, EVal (Location ℓ Borrowed))\n        |   S_Declare : forall (σ σ' : S.t) (x : Var.t) (v : value),\n            write σ l (LVar x) (Some v) = Some σ' -> \n            step p l (σ, EBinding x v) [] (σ', EVal Unit)\n        |   S_Assign : forall (σ σ' σ'' : S.t) (ω : lval) \n            (v:value) (v' : partialValue) m,\n            read σ l ω = Some (v', m) -> \n            (* S.drop_val σ (Singleton _ v') = Some σ'' -> *)\n            write σ'' l ω (Some v) = Some σ' ->\n            step p l (σ, EAssign ω (EVal v)) [] (σ', EVal Unit)\n        |   S_Seq : forall (σ σ' : S.t) (v :value) (e1 e2  : expression),\n            (* Store.drop_val σ (Singleton _ (Some v)) = Some σ' -> *)\n            step p l (σ, ESeq (EVal v) e2) [] (σ, e2)\n        |   S_Block1 : forall ( m : Lifetime.t) (σ σ' : S.t) (e e' : expression) T,\n            step p m (σ, e) T (σ', e') -> \n            step p l (σ, EBlock e m) T (σ', EBlock e' m)\n        |   S_Block2 : forall (m : Lifetime.t) (σ σ' : S.t) (v : value),\n            (* Store.drop_lft σ m = Some σ' -> *)\n            step p l (σ, EBlock (EVal v) m) [] (σ, EVal v)\n        |   S_Spawn : forall (m m' : Lifetime.t) (σ σ' : S.t) (f : Var.t) (mth : method)\n                (e e' : expression) (el : list expression) (vl : list value) (t :threadId),\n            functions p f = Some mth ->\n            el = List.map EVal vl ->\n            instantiate σ l (EBlock e m) = EBlock e' m' ->\n            let xl := List.map (fun x =>  inl (fst x, m')) (params mth) in \n            let vl' := List.map (fun v => (Some v, inl m')) vl in\n            let u := List.combine xl vl' in\n            S.allocate σ u = Some σ' ->\n            step p l (σ, ESpawn f el) [(t, e', m')] (σ', EVal Unit).\n\n    Definition run (p : program) (l : Lifetime.t) : \n        transition lstate (list (threadId * expression * Lifetime.t)) :=\n            reachable _ _ (step p l).\n\n    \n    Inductive react (p : program) : relation (S.t * pool) :=\n        | react_done : forall σ, react p (σ, []) (σ, [])\n        | react_step : forall l t σ σ' σ'' e e' T0 T T',\n            step p l (σ, e) T0 (σ', e') -> \n            react p (σ'',T) (σ', T') ->\n            react p (σ, (t, e, l)::T) (σ', (t,e',l)::T' ++ T0).\n\n    Inductive reset : relation expression :=\n        | reset_val : reset (EVal Unit) (EVal Unit)\n        | reset_cooperate : forall e e' C,\n            e  = build C ECooperate ->\n            e' = build C (EVal Unit) ->\n            reset e e'.  \n\n    Definition resetAll : relation pool :=\n        fun (l1 l2 : pool) => forall i, \n            match nth_error l1 i, nth_error l2 i with \n                | None, None => True \n                | Some (_, e1, _), Some (_, e2, _) => reset e1 e2 \n                | _, _ => False \n            end.\n\n    Definition instant (p : program) : relation (S.t * pool) :=\n        fun st st' =>\n        let (σ, T) := st in \n        let (σ', T') := st' in\n        exists T'', react p (σ, T) (σ', T') /\\ resetAll T'' T'.\n\n    Definition reachable (p : program) : relation (S.t * pool) :=\n        clos_refl_trans _ (instant p).", "meta": {"author": "DabrowskiFr", "repo": "mssl", "sha": "8daf11bb2b9e9f73db1fad383a9d410f31fb27b7", "save_path": "github-repos/coq/DabrowskiFr-mssl", "path": "github-repos/coq/DabrowskiFr-mssl/mssl-8daf11bb2b9e9f73db1fad383a9d410f31fb27b7/theories/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.2366116377303075}}
{"text": "(******************************************************************************)\n(** ** RC11-RMW one-to-one Correspondence *)\n(******************************************************************************)\nRequire Import Classical List Relations Peano_dec.\nRequire Import Hahn.\nRequire Import Basic.\nRequire Import ClassicalDescription IndefiniteDescription.\nRequire Import RC11_Events RC11_Model RC11_Threads.\n\nLemma in_helper A (l: list A) (P: A -> Prop) :\n   ⦗fun a => In a (filterP P l)⦘ ⊆ ⦗fun a => In a l⦘.\nProof. unfolder; ins; desf; apply in_filterP_iff in H0; desf. Qed.\n\nLemma case_doma A (r: relation A) (P: A -> Prop) :\n  r ≡ ⦗P⦘ ⨾ r ∪ ⦗set_compl P⦘ ⨾ r.\nProof.\n  split; [unfolder; ins; tauto | basic_solver].\nQed.\n\nLemma case_domb A (r: relation A) (P: A -> Prop) :\n  r ≡ r ⨾ ⦗P⦘ ∪ r ⨾ ⦗set_compl P⦘.\nProof.\n  split; [unfolder; ins; tauto | basic_solver].\nQed.\n\nLemma case_dom A (r: relation A) (P: A -> Prop) :\n  r ≡ ⦗P⦘ ⨾ r ⨾ ⦗P⦘ \n    ∪ ⦗set_compl P⦘ ⨾ r ⨾ ⦗P⦘\n    ∪ ⦗P⦘ ⨾ r ⨾ ⦗set_compl P⦘\n    ∪ ⦗set_compl P⦘ ⨾ r ⨾ ⦗set_compl P⦘.\nProof.\n  split; [unfolder; ins; tauto | basic_solver].\nQed.\n\nDefinition NO_RMW_EDGES G := G.(rmw) ⊆ ∅₂.\n\nSection RC11_Correspondence.\nVariable G : execution.\nVariable G' : execution.\n\nNotation \"'acts''\" := G'.(acts).\nNotation \"'lab''\" := G'.(lab).\nNotation \"'loc''\" := (loc lab').\nNotation \"'val''\" := (val lab').\nNotation \"'mod''\" := (mod lab').\nNotation \"'sb''\" := G'.(sb).\nNotation \"'rf''\" := G'.(rf).\nNotation \"'mo''\" := G'.(mo).\nNotation \"'sw''\" := G'.(sw).\nNotation \"'rmw''\" := G'.(rmw).\nNotation \"'rb''\" := G'.(rb).\nNotation \"'hb''\" := G'.(hb).\nNotation \"'data''\" := G'.(data).\nNotation \"'addr''\" := G'.(addr).\nNotation \"'ctrl''\" := G'.(ctrl).\nNotation \"'deps''\" := G'.(deps).\nNotation \"'eco''\" := G'.(eco).\nNotation \"'same_loc''\" := G'.(same_loc).\nNotation \"rel |loc'\" := (rel ∩ same_loc') (at level 1).\nNotation \"'psc''\" := G'.(psc).\nNotation \"'psc_base''\" := G'.(psc_base).\nNotation \"'psc_f''\" := G'.(psc_f).\nNotation \"'scb''\" := G'.(scb).\nNotation \"'sb_neq_loc''\" := G'.(sb_neq_loc).\n\nNotation \"'E''\" := G'.(E).\nNotation \"'R''\" := (R lab').\nNotation \"'W''\" := (W lab').\nNotation \"'F''\" := (F lab').\nNotation \"'RMW''\" := (RMW lab').\nNotation \"'RW''\" := (RW lab').\nNotation \"'FR''\" := (FR lab').\nNotation \"'FW''\" := (FW lab').\nNotation \"'Na''\" := (Only_Na lab').\nNotation \"'Rlx''\" := (Rlx lab').\nNotation \"'Rel''\" := (Rel lab').\nNotation \"'Acq''\" := (Acq lab').\nNotation \"'Acqrel''\" := (Acqrel lab').\nNotation \"'Sc''\" := (Sc lab').\n\nNotation \"'acts'\" := G.(acts).\nNotation \"'lab'\" := G.(lab).\nNotation \"'loc'\" := (loc lab).\nNotation \"'val'\" := (val lab).\nNotation \"'mod'\" := (mod lab).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rf'\" := G.(rf).\nNotation \"'mo'\" := G.(mo).\nNotation \"'sw'\" := G.(sw).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'rb'\" := G.(rb).\nNotation \"'hb'\" := G.(hb).\nNotation \"'data'\" := G.(data).\nNotation \"'addr'\" := G.(addr).\nNotation \"'ctrl'\" := G.(ctrl).\nNotation \"'deps'\" := G.(deps).\nNotation \"'eco'\" := G.(eco).\nNotation \"'same_loc'\" := G.(same_loc).\nNotation \"rel |loc\" := (rel ∩ same_loc) (at level 1).\nNotation \"'psc'\" := G.(psc).\nNotation \"'psc_base'\" := G.(psc_base).\nNotation \"'psc_f'\" := G.(psc_f).\nNotation \"'scb'\" := G.(scb).\nNotation \"'sb_neq_loc'\" := G.(sb_neq_loc).\n\nNotation \"'E'\" := G.(E).\nNotation \"'R'\" := (R lab).\nNotation \"'W'\" := (W lab).\nNotation \"'F'\" := (F lab).\nNotation \"'RMW'\" := (RMW lab).\nNotation \"'RW'\" := (RW lab).\nNotation \"'FR'\" := (FR lab).\nNotation \"'FW'\" := (FW lab).\nNotation \"'Na'\" := (Only_Na lab).\nNotation \"'Rlx'\" := (Rlx lab).\nNotation \"'Rel'\" := (Rel lab).\nNotation \"'Acq'\" := (Acq lab).\nNotation \"'Acqrel'\" := (Acqrel lab).\nNotation \"'Sc'\" := (Sc lab).\nNotation \"'R_rmw'\" := (dom_rel rmw).\nNotation \"'W_rmw'\" := (codom_rel rmw).\n\nDefinition get_rmw_mod (modR: mode_r) (modW: mode_w) : option mode_rw :=\n  match modR, modW with\n  | Rrlx, Wrlx => Some RWrlx\n  | Racq, Wrlx => Some RWacq\n  | Rrlx, Wrel => Some RWrel\n  | Racq, Wrel => Some RWacqrel\n  | Rsc, Wsc => Some RWsc\n  | _, _ => None\n  end.\n\nHypothesis NRMW_EVENTS: NO_RMW_EVENTS G.\nHypothesis NRMW_EDGES: NO_RMW_EDGES G'.\n\nNotation \"'consistent''\" := (consistent G').\nNotation \"'consistent'\" := (consistent G).\n\nSection EDGES_TO_EVENTS.\n\nHypothesis ACTS: acts' = filterP (fun a => ~ R_rmw a) acts.\nHypothesis RMW_COR: forall r w (RMW_rw : rmw r w), RMW' w.\nHypothesis RMW_COR': forall w (RMW_y: RMW' w),\n  exists r l vr vw o or ow,\n    rmw r w /\\\n    lab' w = Armw l vr vw o /\\\n    lab r = Aload l vr or /\\\n    lab w = Astore l vw ow /\\\n    get_rmw_mod or ow = Some o /\\\n    sb|imm r w /\\\n    (forall r', rmw r' w -> r' = r).\nHypothesis LAB: forall a (N_Rrmw: ~ W_rmw a), lab' a = lab a.\nHypothesis MO: mo' ≡ mo.\nHypothesis RF: rf' ≡ rf ⨾ ⦗set_compl R_rmw⦘ ∪ rf ⨾ rmw.\nHypothesis SB: sb' ≡ ⦗set_compl R_rmw⦘ ⨾ sb ⨾ ⦗set_compl R_rmw⦘.\nHypothesis DEPS: WfDEPS G'.\n\nLemma ACTS0a: ⦗E'⦘ ≡ ⦗E'⦘ ⨾ ⦗set_compl R_rmw⦘.\nProof.\n  split; [|basic_solver].\n  unfold RC11_Model.E; rewrite ACTS; unfolder; ins; desf; in_simp.\nQed.\n\nLemma ACTS0b: ⦗E'⦘ ≡ ⦗set_compl R_rmw⦘ ⨾ ⦗E'⦘.\nProof.\n  split; [|basic_solver].\n  unfold RC11_Model.E; rewrite ACTS; unfolder; ins; desf; in_simp.\nQed.\n\nLemma ACTS1: E' ⊆₁ E.\nProof. unfold RC11_Model.E; rewrite ACTS; unfolder; ins; desf; in_simp. Qed.\n\nLemma ACTS2a: ⦗E'⦘ ≡ ⦗E⦘ ⨾ ⦗set_compl R_rmw⦘.\nProof.\n  split.\n  - by rewrite ACTS0a, ACTS1.\n  - unfold RC11_Model.E; rewrite ACTS; unfolder; ins; desf; in_simp.\nQed.\n\nLemma ACTS2b: ⦗E'⦘ ≡ ⦗set_compl R_rmw⦘ ⨾ ⦗E⦘.\nProof.\n  split.\n  - by rewrite ACTS0b, ACTS1.\n  - unfold RC11_Model.E; rewrite ACTS; unfolder; ins; desf; in_simp.\nQed.\n\nLemma ACTS3: ⦗E⦘ ≡ ⦗E'⦘ ∪ ⦗E⦘ ⨾ ⦗R_rmw⦘.\nProof. rewrite case_domb with (P := R_rmw); rewrite ACTS2a; basic_solver 42. Qed.\n\nLemma RF': rf ⊆ rf' ∪ rf ⨾ ⦗R_rmw⦘.\nProof.\n  rewrite RF; rewrite case_domb with (P := R_rmw) at 1; unionL; basic_solver.\nQed.\n\nLemma WW: W' ≡₁ W.\nProof.\n  split; ins; destruct (classic (W_rmw x)).\n  2, 4: by unfold RC11_Events.W in *; specialize (LAB x H0); crewrite LAB.\n  all: red in H0; desf; specialize (RMW_COR' x (RMW_COR x0 x H0));\n       destruct RMW_COR' as (r & COR); desf; specialize (COR5 r COR); desf;\n       solve_type_mismatch.\nQed.\n\nLemma FF: F' ≡₁ F.\nProof.\n  split; ins; destruct (classic (W_rmw x)).\n  2, 4: by unfold RC11_Events.F in *; specialize (LAB x H0); crewrite LAB.\n  all: red in H0; desf; specialize (RMW_COR' x (RMW_COR x0 x H0));\n       destruct RMW_COR' as (r & COR); desf; specialize (COR5 r COR); desf;\n       solve_type_mismatch.\nQed.\n\nLemma WR_MISMATCH a (Wa: W a) (Ra: R a): False.\nProof.\n  red in Wa; red in Ra; desf.\n  apply (NRMW_EVENTS a); red; desf.\nQed.\n\nLemma RR: R ⊆₁ R' ∪₁ R_rmw.\nProof.\n  unfolder; ins.\n  destruct (classic (R_rmw x)); [by right|].\n  left.\n  destruct (classic (W_rmw x)).\n  - red in H1; desf.\n    specialize (RMW_COR' x (RMW_COR x0 x H1)).\n    destruct RMW_COR' as (r & COR); desf.\n    specialize (COR5 x0 H1); desf.\n    solve_type_mismatch.\n  - specialize (LAB x H1).\n    red; red in H; rewrite LAB; desf.\nQed.\n\nLemma RR2 (WF: Wf G): R' ⊆₁ R ∪₁ W.\nProof.\n  unfolder; ins.\n  destruct (classic (W_rmw x)).\n  - right.\n    red in H0; desf.\n    cdes WF; cdes WF_RMW; apply RMW_DOM in H0; unfolder in H0; desf.\n  - left.\n    assert (~ RMW' x).\n    { intro; contradict H0.\n      specialize (RMW_COR' x H1).\n      destruct RMW_COR' as (r & COR); desf.\n      red; eexists; eauto. }\n    red in H; desf.\n    + rewrite (LAB x H0) in *; red; desf.\n    + contradict H1; red; desf.\nQed.\n\nLemma RR3 (WF: Wf G): R' ⊆₁ R ∪₁ RMW'.\nProof.\n  unfolder; ins.\n  destruct (classic (W_rmw x)).\n  - right.\n    red in H0; desf.\n    by apply RMW_COR with x0.\n  - left.\n    assert (~ RMW' x).\n    { intro; contradict H0.\n      specialize (RMW_COR' x H1).\n      destruct RMW_COR' as (r & COR); desf.\n      red; eexists; eauto. }\n    red in H; desf.\n    + rewrite (LAB x H0) in *; red; desf.\n    + contradict H1; red; desf.\nQed.\n\nLemma LOC: loc' = loc.\nProof.\n  exten; ins.\n  unfold RC11_Events.loc.\n  destruct (classic (W_rmw x)).\n  - red in H; destruct H.\n    specialize (RMW_COR' x (RMW_COR x0 x H)).\n    destruct RMW_COR' as (r & COR); desf.\n  - specialize (LAB x H).\n    by rewrite LAB.\nQed.\n\nLemma SAME_LOC: same_loc' ≡ same_loc.\nProof. by unfold RC11_Model.same_loc; rewrite LOC. Qed.\n\nLemma REL: Rel' ⊆₁ Rel.\nProof.\n  unfolder; ins.\n  destruct (classic (W_rmw x)).\n  + red in H0; desf.\n    specialize (RMW_COR' x (RMW_COR x0 x H0)).\n    destruct RMW_COR' as (r & COR); desf.\n    specialize (COR5 x0 H0); desf.\n    red; red in H.\n    unfold get_rmw_mod in *.\n    unfold RC11_Events.mod in *.\n    desf.\n  + red; red in H.\n    unfold RC11_Events.mod in *.\n    rewrite (LAB x H0) in *.\n    desf.\nQed.\n\nLemma RLX: Rlx' ⊆₁ Rlx.\nProof.\n  unfolder; ins.\n  destruct (classic (W_rmw x)).\n  + red in H0; desf.\n    specialize (RMW_COR' x (RMW_COR x0 x H0)).\n    destruct RMW_COR' as (r & COR); desf.\n    specialize (COR5 x0 H0); desf.\n    red; red in H.\n    unfold get_rmw_mod in *.\n    unfold RC11_Events.mod in *.\n    desf.\n  + red; red in H.\n    unfold RC11_Events.mod in *.\n    rewrite (LAB x H0) in *.\n    desf.\nQed.\n\nLemma M_SC: Sc' ⊆₁ Sc.\nProof.\n  unfolder; ins.\n  destruct (classic (W_rmw x)).\n  + red in H0; desf.\n    specialize (RMW_COR' x (RMW_COR x0 x H0)).\n    destruct RMW_COR' as (r & COR); desf.\n    specialize (COR5 x0 H0); desf.\n    red; red in H.\n    unfold get_rmw_mod in *.\n    unfold RC11_Events.mod in *.\n    desf.\n  + red; red in H.\n    unfold RC11_Events.mod in *.\n    rewrite (LAB x H0) in *.\n    desf.\nQed.\n\nLemma F_ACQ (WF: Wf G): F ∩₁ Acq' ⊆₁ F ∩₁ Acq.\nProof.\n  unfolder; ins; desf; split; auto.\n  assert (~ W_rmw x).\n  { intro.\n    assert (W x).\n    { cdes WF; cdes WF_RMW; red in H1.\n      desf; apply RMW_DOM in H1; unfolder in H1; desf. }\n    solve_type_mismatch. \n  }\n  red; red in H0.\n  unfold RC11_Events.mod in *; rewrite (LAB x H1) in *; desf.\nQed.\n\nLemma R_ACQ (WF: Wf G): (R ∩₁ Acq' ⊆₁ R ∩₁ Acq).\nProof.\n  unfolder; ins; desf; split; auto.\n  assert (~ W_rmw x).\n  { intro.\n    assert (W x).\n    { cdes WF; cdes WF_RMW; red in H1.\n      desf; apply RMW_DOM in H1; unfolder in H1; desf. }\n    by apply WR_MISMATCH with x.\n  }\n  red; red in H0.\n  unfold RC11_Events.mod in *; rewrite (LAB x H1) in *; desf.\nQed.\n\nLemma N_Wrmw_Init l (SB_TID: sb ⊆ sb∙ ∪ init_pair): (~ W_rmw (Init l)).\nProof.\n  remember (Init l) as I.\n  intro RMW_xI; red in RMW_xI; desc.\n  specialize (RMW_COR' I (RMW_COR x I RMW_xI)).\n  destruct RMW_COR' as (r & COR); desf.\n  specialize (COR5 x); intuition; desf.\n  unfolder in COR4; desc.\n  apply SB_TID in COR4.\n  unfolder in COR4; desf.\n  - red in COR6; desf.\n  - red in COR4; desf; apply COR6; red; desf.\nQed.\n\nLemma RF_Rrmw (WF: Wf G): rf ⊆ ⦗set_compl R_rmw⦘ ⨾ rf.\nProof.\n  cdes WF; cdes WF_RF.\n  arewrite (rf ⊆ ⦗W⦘ ⨾ rf) by rewrite RF_DOM at 1; basic_solver.\n  arewrite (W ⊆₁ set_compl R_rmw).\n  { unfolder; ins; intro Rrmw_x.\n    red in Rrmw_x; desf.\n    specialize (RMW_COR' y (RMW_COR x y Rrmw_x)).\n    destruct RMW_COR' as (r & COR).\n    desf. specialize (COR5 x Rrmw_x). desf.\n    solve_type_mismatch. }\n  done.\nQed.\n\nProposition edges_to_events : consistent -> consistent'.\nProof.\n  ins; cdes H; red; unnw; split.\n  (* Wf *) \n  { cdes WF; red; splits; unnw.\n    - (* WfACTS *) cdes WF_ACTS; red; splits; unnw.\n      + (* ACTS_INIT *)\n        rewrite ACTS.\n        ins; specialize (ACTS_INIT l).\n        apply in_filterP_iff; splits; auto.\n        unfold dom_rel.\n        intro; desf.\n        apply WR_MISMATCH with (Init l).\n        * red; rewrite (LAB_INIT l); desf.\n        * cdes WF_RMW; apply RMW_DOM in H0; unfolder in H0; desf.\n      + cdes WF; cdes WF_ACTS; cdes WF_SB.\n        ins; specialize (LAB_INIT l).\n        by rewrite (LAB (Init l) (N_Wrmw_Init l SB_TID)).\n    - (* WfSB *) cdes WF_SB; red; splits; unnw.\n      + (* SB_ACT *)\n        rewrite SB; rewrite SB_ACT at 1; rewrite !seqA.\n        seq_rewrite <- ACTS2b; seq_rewrite <- ACTS2a.\n        by seq_rewrite <- ACTS0a; seq_rewrite <- ACTS0b.\n      + (* SB_INIT *)\n        rewrite SB, ACTS2a.\n        arewrite (init_pair ⊆ ⦗set_compl R_rmw⦘ ⨾ init_pair).\n        { unfold init_pair, is_init; unfolder; ins; desf; splits; auto.\n          intro.\n          apply WR_MISMATCH with (Init l).\n          - cdes WF_ACTS; red; rewrite (LAB_INIT l); desf.\n          - red in H2; cdes WF_RMW; apply RMW_DOM in H2; unfolder in H2; desf.\n        }\n        by hahn_frame; rewrite SB_INIT.\n      + (* SB_IRR *)\n        rewrite SB.\n        by clear_equivs ⦗set_compl R_rmw⦘.\n      + (* SB_T *)\n        rewrite SB.\n        apply transitiveI.\n        arewrite_id ⦗set_compl R_rmw⦘ at 2; arewrite_id ⦗set_compl R_rmw⦘ at 2.\n        relsf.\n      + (* SB_TID *)\n        rewrite SB.\n        rewrite SB_TID at 1.\n        case_union_2 _ _; [unionR left | unionR right]; basic_solver.\n      + (* SB_TOT *)\n        ins; specialize (SB_TOT i).\n        rewrite SB.\n        arewrite (E' ⊆₁ E' ∩₁ (set_compl R_rmw))\n          by (unfold RC11_Model.E; rewrite ACTS; unfolder; ins; desf; in_simp).\n        red; ins.\n        assert (sb a b \\/ sb b a).\n        { apply SB_TOT; unfolder in IWa; unfolder in IWb; desf;\n          by split; auto; apply ACTS1. }\n        desf; [left | right]; unfolder in *; desf.\n    - (* WfRMW *) cdes WF_RMW; red; splits; unnw.\n      + (* RMW_DOM *) by red in NRMW_EDGES; rewrite NRMW_EDGES at 1.\n      + (* RMW_LOC *) by red in NRMW_EDGES; rewrite NRMW_EDGES at 1.\n      + (* RMW_MOD *) by red in NRMW_EDGES; ins; apply NRMW_EDGES in RMW_AB.\n      + (* RMW_IMM *) by red in NRMW_EDGES; rewrite NRMW_EDGES at 1.\n    - (* WfRF *) cdes WF_RF; red; splits; unnw.\n      + (* RF_ACT *)\n        rewrite RF; unionL.\n        * rewrite RF_ACT at 1.\n          relsf; unionR left.\n          rewrite !seqA; rewrite ACTS2a at 1; rewrite ACTS2b at 1.\n          seq_rewrite seq_eqvK; rewrite seq_eqvC at 1.\n          rewrite (RF_Rrmw WF) at 1.\n          by rewrite !seqA.\n        * relsf; unionR right.\n          rewrite RF_ACT at 1; arewrite_id ⦗E⦘ at 2; simpl_rels.\n          arewrite (rmw ⊆ rmw ⨾ ⦗E⦘) at 1.\n          { unfolder; ins; split; auto.\n            cdes WF_RMW; apply RMW_IMM in H0; unfolder in H0; desf.\n            cdes WF_SB; apply SB_ACT in H0; unfolder in H0; desf. }\n          rewrite ACTS2a at 1; rewrite ACTS2b at 1; rewrite (RF_Rrmw WF) at 1.\n          arewrite (rmw ⊆ rmw ⨾ ⦗set_compl R_rmw⦘) at 2.\n          { arewrite (rmw ⊆ rmw ⨾ ⦗W⦘)\n              by cdes WF_RMW; rewrite RMW_DOM at 1; basic_solver.\n            arewrite (W ⊆₁ set_compl R_rmw).\n            { unfolder; ins; intro Rrmw_x.\n              red in Rrmw_x; desf.\n              specialize (RMW_COR' y (RMW_COR x y Rrmw_x)).\n              destruct RMW_COR' as (r & COR).\n              desf. specialize (COR5 x Rrmw_x). desf.\n              solve_type_mismatch. }\n            done.\n          }\n          done.\n      + (* RF_IRR *)\n        rewrite RF; unionL; [by clear_equivs ⦗set_compl R_rmw⦘ |].\n        arewrite (rmw ⊆ sb) by cdes WF_RMW; rewrite RMW_IMM; eauto with rel.\n        clear - NTA.\n        rotate; red; repeat red in NTA.\n        ins; apply (NTA x).\n        unfolder in H; desf; apply t_trans with z; vauto.\n      + (* RF_DOM *)\n        rewrite RF, WW.\n        relsf. unionL; [unionR left | unionR right].\n        * rewrite RF_DOM at 1.\n          rewrite RR, id_union.\n          basic_solver.\n        * arewrite (rf ⊆ ⦗W⦘ ⨾ rf) by rewrite RF_DOM at 1; basic_solver.\n          hahn_frame.\n          unfolder; ins; split; auto; red.\n          specialize (RMW_COR x y H0).\n          red in RMW_COR; desf.\n      + (* RF_LOC *)\n        rewrite RF, LOC.\n        apply funeq_union.\n        * by clear_equivs ⦗set_compl R_rmw⦘.\n        * apply funeq_seq; auto.\n          by cdes WF_RMW.\n      + (* RF_VAL *)\n        assert (RF_HELPER: forall a b, rf a b -> valw lab' a = valr lab' b).\n        { intros a b RF_ab; specialize (RF_VAL a b RF_ab).\n          assert (~ W_rmw b).\n          { intro Wrmw_b.\n            apply WR_MISMATCH with b.\n            - red in Wrmw_b; desf; cdes WF_RMW.\n              apply RMW_DOM in Wrmw_b; unfolder in Wrmw_b; desf.\n            - apply RF_DOM in RF_ab; unfolder in RF_ab; desf. }\n          destruct (classic (W_rmw a)).\n          - red in H1; desf.\n            assert (Lb: valr lab' b = valr lab b).\n            { assert (LABb: lab' b = lab b) by by apply LAB.\n              by unfold RC11_Events.valr in *; rewrite LAB. }\n            assert (La: valw lab' a = valw lab a).\n            { specialize (RMW_COR' a (RMW_COR x a H1)).\n              destruct RMW_COR' as (r & COR); desf.\n              specialize (COR5 x H1); desf.\n              unfold RC11_Events.valw in *; desf. }\n            by rewrite Lb, La.\n          - assert (LABa: lab' a = lab a) by by apply LAB.\n            assert (LABb: lab' b = lab b) by by apply LAB.\n            unfold RC11_Events.valr, RC11_Events.valw.\n            by rewrite LABa, LABb. }\n        intros a b RF_ab.\n        apply RF in RF_ab; unfolder in RF_ab; desf; auto.\n        assert (T: valw lab' a = valr lab' z) by by apply RF_HELPER.\n        rewrite T.\n        assert (Lz: lab' z = lab z).\n        { apply LAB.\n          intro Wrmw_z.\n          apply WR_MISMATCH with z.\n          - red in Wrmw_z; desf; cdes WF_RMW.\n            apply RMW_DOM in Wrmw_z; unfolder in Wrmw_z; desf.\n          - apply RF_DOM in RF_ab; unfolder in RF_ab; desf. }\n        specialize (RMW_COR' b (RMW_COR z b RF_ab0)).\n        destruct RMW_COR' as (r & COR); desf.\n        specialize (COR5 z RF_ab0); desf.\n        unfold RC11_Events.valr, RC11_Events.valw in *.\n        rewrite Lz; desf.\n      + (* RF_FUN *)\n        rewrite RF.\n        red in RF_FUN.\n        apply functional_union.\n        * red.\n          intros x y z RF_yx RF_zx.\n          unfolder in RF_yx; unfolder in RF_zx; desf.\n          by apply RF_FUN with x.\n        * red; unfolder; ins; desf.\n          assert (sb z1 x) by by cdes WF_RMW; apply RMW_IMM.\n          assert (sb z0 x) by by cdes WF_RMW; apply RMW_IMM.\n          destruct (classic (z1 = z0)).\n          { (* z1 = z0 *) by subst; apply RF_FUN with z0. }\n          assert (sb z1 z0 \\/ sb z0 z1).\n          { apply st_implies_sb; auto.\n            apply st_trans with x.\n            - apply sb_not_init_implies_st with G; auto.\n              intro T.\n              apply WR_MISMATCH with z1.\n              + red in T. desf.\n                cdes WF_ACTS; red.\n                rewrite (LAB_INIT l); desf.\n              + cdes WF_RMW; apply RMW_DOM in H3; unfolder in H3; desf.\n            - apply st_inv, sb_not_init_implies_st with G; auto.\n              intro T.\n              apply WR_MISMATCH with z0.\n              + red in T. desf.\n                cdes WF_ACTS; red.\n                rewrite (LAB_INIT l); desf.\n              + cdes WF_RMW; apply RMW_DOM in H2; unfolder in H2; desf.\n            - cdes WF_SB; apply SB_ACT in H4; unfolder in H4; desf.\n            - cdes WF_SB; apply SB_ACT in H5; unfolder in H5; desf.\n          }\n          cdes WF_RMW; exfalso.\n          unfolder in RMW_IMM; desf.\n          -- (* sb z1 z0 *)\n             specialize (RMW_IMM z1 x H3); desf.\n             apply RMW_IMM0 with z0; auto.\n          -- (* sb z0 z1 *)\n             specialize (RMW_IMM z0 x H2); desf.\n             apply RMW_IMM0 with z1; auto.\n        * unfold dom_rel; ins; desf.\n          apply WR_MISMATCH with x.\n          -- unfolder in H1; desf; cdes WF_RMW.\n             apply RMW_DOM in H2; unfolder in H2; desf.\n          -- unfolder in H0; desf.\n             apply RF_DOM in H0; unfolder in H0; desf.\n      + (* RF_TOT *)\n        ins.\n        destruct (classic (W_rmw b)).\n        * red in H0; desf.\n          specialize (RMW_COR' b (RMW_COR x b H0)).\n          destruct RMW_COR' as (r & COR); desf.\n          specialize (COR5 x H0); desf.\n          assert (Er: E r).\n          { cdes WF_SB; cdes WF_RMW.\n            apply RMW_IMM in H0; red in H0; desf.\n            apply SB_ACT in H0; unfolder in H0; desf. }\n          assert (Rr: R r) by (red; desf).\n          specialize (RF_TOT r Er Rr); desf.\n          exists a; hahn_rewrite RF.\n          right; exists r; split; auto.\n        * destruct (classic (R_rmw b)).\n          { red in IN. rewrite ACTS in IN.\n            apply in_filterP_iff in IN; desf. }\n          assert (Rb: R b) by by red; red in READ; rewrite <- (LAB b H0).\n          apply ACTS1 in IN; specialize (RF_TOT b IN Rb); desf.\n          exists a; hahn_rewrite RF.\n          left; basic_solver.\n    - (* WfMO *) cdes WF_MO; red; splits; unnw; try by rewrite MO, ?WW, ?LOC.\n      + (* MO_ACT *)\n        assert (MIS: ⦗R_rmw⦘ ⨾ ⦗W⦘ ⊆ ∅₂).\n        { unfolder; ins; desf.\n          red in H1; desf.\n          specialize (RMW_COR' y0 (RMW_COR y y0 H1)).\n          destruct RMW_COR' as (r & COR); desf.\n          red in H2.\n          specialize (COR5 y H1); desf. }\n        rewrite MO.\n        rewrite MO_ACT at 1.\n        rewrite ACTS3.\n        clear_equivs ⦗E⦘.\n        relsf; unionL; try done; arewrite (mo ⊆ ⦗W⦘ ⨾ mo ⨾ ⦗W⦘) at 1.\n        2: rewrite seq_eqvC with (doma := W).\n        all: sin_rewrite MIS; basic_solver.\n      + (* MO_TOT *)\n        ins; specialize (MO_TOT l).\n        crewrite MO.\n        arewrite (E' ∩₁ W' ∩₁ (fun a : event => loc' a = Some l) ⊆₁ \n                  E ∩₁ W ∩₁ (fun a : event => loc a = Some l)).\n          by rewrite WW, ACTS1, LOC.\n        done.\n    - (* WfDEPS *) done.\n  }\n  (* Consistent *)\n  assert (SW: sw' ⊆ sw ∪ sw ⨾ rmw).\n  { unfold RC11_Model.sw, RC11_Model.release, RC11_Model.rs, RC11_Model.useq.\n    rewrite WW, FF, SAME_LOC, REL, RLX, (F_ACQ WF).\n    rewrite ACTS1 at 1.\n    arewrite (sb' ⊆ sb) by crewrite SB; basic_solver.\n    arewrite (⦗RMW⦘ ≡ ∅₂) by arewrite (RMW ≡₁ ∅₁); basic_solver.\n    arewrite (rmw' ⊆ ∅₂).\n    rels.\n    arewrite (rf' ⨾ ⦗RMW'⦘ ⊆ rf ⨾ rmw).\n    { arewrite (rf' ⊆ rf ∪ rf ⨾ rmw) by crewrite RF; basic_solver.\n      case_union_2 _ _; [| basic_solver].\n      arewrite (rf ⊆ rf ⨾ ⦗R⦘)\n        by cdes WF; cdes WF_RF; rewrite RF_DOM at 1; basic_solver.\n      arewrite (RMW' ⊆₁ W).\n      { unfolder; intros x RMW_x.\n        specialize (RMW_COR' x RMW_x).\n        destruct RMW_COR' as (r & COR); desf.\n        red; desf. }\n      unfolder; ins; desf.\n      by exfalso; apply WR_MISMATCH with y.\n    }\n    rewrite !seq_union_r; unionL.\n    - arewrite (rf' ⨾ ⦗R' ∩₁ Acq'⦘ ⊆ rf ⨾ ⦗R ∩₁ Acq⦘ ∪ rf ⨾ ⦗R ∩₁ Acq⦘ ⨾ rmw).\n      { arewrite (rf' ⊆ rf ∪ rf ⨾ rmw) by crewrite RF; basic_solver.\n        case_union_2 _ _; [unionR left | unionR right].\n        - rewrite (RR2 WF).\n          arewrite (rf ⊆ rf ⨾ ⦗R⦘)\n            by cdes WF; cdes WF_RF; rewrite RF_DOM at 1; basic_solver.\n          rewrite !set_inter_union_l, !id_union.\n          relsf; unionL.\n          + rewrite (R_ACQ WF); basic_solver.\n          + by unfolder; ins; desf; exfalso; apply WR_MISMATCH with y.\n        - rewrite !seqA.\n          arewrite (rmw ⨾ ⦗R' ∩₁ Acq'⦘ ⊆ rmw ⨾ ⦗RMW' ∩₁ Acq'⦘).\n          { rewrite (RR3 WF).\n            arewrite (rmw ⊆ rmw ⨾ ⦗W⦘)\n              by cdes WF; cdes WF_RMW; rewrite RMW_DOM at 1; basic_solver.\n            rewrite !set_inter_union_l, !id_union.\n            relsf; unionL.\n            - by unfolder; ins; desf; exfalso; apply WR_MISMATCH with y.\n            - basic_solver.\n          }\n          unfolder; ins; desf.\n          specialize (RMW_COR' y H2).\n          destruct RMW_COR' as (r & COR); desf.\n          eexists; splits; eauto.\n          + cdes WF; cdes WF_RMW; apply RMW_DOM in H1; unfolder in H1; desf.\n          + specialize (COR5 z H1); subst; red in H3.\n            unfold get_rmw_mod in COR3; unfold RC11_Events.mod in H3.\n            desf; red; unfold RC11_Events.mod; desf.\n      }\n      remember (⦗W ∩₁ Rel⦘ ∪ ⦗F ∩₁ Rel⦘ ⨾ sb) as r.\n      case_union_2 _ _; [unionR left | unionR right]; unionR left; by hahn_frame.\n    - arewrite (rf' ⊆ rf ∪ rf ⨾ rmw) by crewrite RF; basic_solver.\n      case_union_2 _ (rf ⨾ rmw).\n      + arewrite (rf ⨾ ⦗R' ∩₁ Rlx⦘ ⨾ sb ⨾ ⦗F ∩₁ Acq⦘ ⊆\n                  rf ⨾ ⦗R ∩₁ Rlx⦘ ⨾ sb ⨾ ⦗F ∩₁ Acq⦘).\n        { rewrite (RR2 WF).\n          arewrite (rf ⊆ rf ⨾ ⦗R⦘)\n            by cdes WF; cdes WF_RF; rewrite RF_DOM at 1; basic_solver.\n          rewrite !set_inter_union_l, !id_union.\n          relsf; unionL.\n          - basic_solver 42.\n          - arewrite (⦗R⦘ ⨾ ⦗W ∩₁ Rlx⦘ ⊆ ∅₂)\n              by unfolder; ins; desf; apply WR_MISMATCH with y.\n            basic_solver 42.\n        }\n        by unionR left -> right.\n      + rewrite !seqA.\n        arewrite (rmw ⨾ ⦗R' ∩₁ Rlx⦘ ⨾ sb ⨾ ⦗F ∩₁ Acq⦘ ⊆\n                  rmw ⨾ ⦗W ∩₁ Rlx⦘ ⨾ sb ⨾ ⦗F ∩₁ Acq⦘).\n        { rewrite (RR2 WF).\n          arewrite (rmw ⊆ rmw ⨾ ⦗W⦘)\n            by cdes WF; cdes WF_RMW; rewrite RMW_DOM at 1; basic_solver.\n          rewrite !set_inter_union_l, !id_union.\n          relsf; unionL.\n          - arewrite (⦗W⦘ ⨾ ⦗R ∩₁ Rlx⦘ ⊆ ∅₂)\n              by unfolder; ins; desf; apply WR_MISMATCH with y.\n            basic_solver 42.\n          - basic_solver 42.\n        }\n        arewrite (rmw ⨾ ⦗W ∩₁ Rlx⦘ ⊆ ⦗R ∩₁ Rlx⦘ ⨾ rmw).\n        { cdes WF; cdes WF_RMW.\n          unfolder; ins; desf.\n          specialize (RMW_MOD x y H0).\n          splits; auto.\n          - apply RMW_DOM in H0; unfolder in H0; desf.\n          - solve_mode_mismatch. }\n        arewrite (rmw ⨾ sb ⊆ sb).\n        { cdes WF; cdes WF_RMW; cdes WF_SB.\n          rewrite RMW_IMM.\n          basic_solver 42. }\n        eauto with rel.\n  }\n  assert (RB: rb' ⊆ rb ∪ mo).\n  { arewrite (rb ≡ rf⁻¹ ⨾ mo) by rewrite NRMW_implies_original_rb.\n    unfold RC11_Model.rb.\n    rewrite MO.\n    arewrite (rf' ⊆ rf ∪ rf ⨾ rmw) by crewrite RF; basic_solver.\n    rewrite transp_union.\n    unfolder; ins; desf; [basic_solver|].\n    assert (Ex: E' x).\n    { red; rewrite ACTS; apply in_filterP_iff; split.\n      - cdes WF; cdes WF_RMW; apply RMW_IMM in H3; unfolder in H3; desf.\n        cdes WF_SB; apply SB_ACT in H3; unfolder in H3; desf.\n      - intro.\n        red in H4; desf.\n        apply WR_MISMATCH with x; cdes WF; cdes WF_RMW.\n        + apply RMW_DOM in H3; unfolder in H3; desf.\n        + apply RMW_DOM in H4; unfolder in H4; desf.\n    }\n    assert (NEQ: x <> y) by (apply not_and_or in H1; desf); clear H1 Ex.\n    assert (MO_zx: mo z x) by (apply rf_rmw_mo; auto; basic_solver).\n    assert (N_MO_yx: ~ mo y x).\n    { intro MO_yx.\n      apply AT with z0.\n      exists y; split.\n      - by apply NRMW_implies_original_rb; auto; exists z.\n      - exists x; split; auto.\n    }\n    assert (MOS: mo x y \\/ mo y x).\n    { cdes WF; cdes WF_MO.\n      assert (W z) by (apply MO_DOM in H2; unfolder in H2; desf).\n      assert (exists lz, loc z = Some lz).\n      { case_eq (loc z); ins; eauto.\n        red in H3; unfold RC11_Events.loc in H4; solve_type_mismatch. }\n      destruct H4 as [lz L_z].\n      apply MO_TOT with lz; auto; unfolder; splits.\n      3, 6: by rewrite <- L_z; symmetry; apply MO_LOC.\n      - apply MO_ACT in MO_zx; unfolder in MO_zx; desf.\n      - apply MO_DOM in MO_zx; unfolder in MO_zx; desf.\n      - apply MO_ACT in H2; unfolder in H2; desf.\n      - apply MO_DOM in H2; unfolder in H2; desf.\n    }\n    desf; auto.\n  }\n  assert (ECO: eco' ⊆ eco).\n  { unfold RC11_Model.eco.\n    rewrite RB.\n    arewrite (rf' ⊆ rf ∪ rf ⨾ rmw) by crewrite RF; basic_solver.\n    rewrite MO, !crE; relsf; rewrite <- !unionA; unionL.\n    all: rels; eauto with rel; rewrite rf_rmw_mo; auto; eauto with rel.\n    1, 3: cdes WF; cdes WF_MO; relsf; eauto with rel.\n    rewrite (rb_seq_mo WF NRMW_EVENTS); eauto with rel.\n  }\n  assert (HB: hb' ⊆ hb).\n  { unfold RC11_Model.hb at 1.\n    arewrite (sb' ⊆ sb) by crewrite SB; basic_solver.\n    rewrite SW.\n    arewrite (sw ⨾ rmw ⊆ hb) by rewrite sw_in_hb, rmw_in_sb, sb_in_hb, hb_hb.\n    rewrite sw_in_hb, sb_in_hb; relsf.\n  }\n  splits.\n  - (* Coherence *)\n    red; red in COH.\n    by rewrite HB, ECO.\n  - (* Atomicity *) red; arewrite (rmw' ⊆ ∅₂); rels.\n  - (* Atomicity2 *)\n    red; red in AT2.\n    rewrite MO.\n    arewrite (rf' ⊆ rf ∪ rf ⨾ rmw) by crewrite RF; basic_solver.\n    rewrite transp_union.\n    relsf; unionL; auto.\n    unfolder; ins; desf.\n    apply AT with z1.\n    exists z; split.\n    + by apply NRMW_implies_original_rb; auto; exists x.\n    + exists z0; split; auto.\n  - (* SC *)\n    red; red in SC.\n    unfold RC11_Model.psc, RC11_Model.psc_base, RC11_Model.psc_f,\n      RC11_Model.scb in *.\n    arewrite (sb' ⊆ sb) by crewrite SB; basic_solver.\n    rewrite MO, SAME_LOC, FF, M_SC, HB, ECO, RB.\n    arewrite (sb_neq_loc' ⊆ sb_neq_loc).\n    { unfold RC11_Model.sb_neq_loc.\n      rewrite SAME_LOC, SB.\n      unfolder; ins; desf; split; auto.\n      apply or_not_and; right.\n      repeat (apply not_and_or in H1; desf).\n    }\n    by arewrite (sb ∪ sb_neq_loc ⨾ hb ⨾ sb_neq_loc ∪ hb |loc ∪ mo ∪ (rb ∪ mo) ⊆\n                (sb ∪ sb_neq_loc ⨾ hb ⨾ sb_neq_loc ∪ hb |loc ∪ mo ∪ rb)).\n  - (* No-thin-air *)\n    red; red in NTA.\n    arewrite (sb' ⊆ sb) by crewrite SB; basic_solver.\n    arewrite (rf' ⊆ rf ∪ rf ⨾ rmw) by crewrite RF; basic_solver.\n    clear - WF NTA; rewrite (rmw_in_sb WF); red.\n    arewrite ((sb ∪ (rf ∪ rf ⨾ sb))⁺ ⊆ (sb ∪ rf)⁺)\n      by eauto 42 with rel rel_full.\nQed.\n\nEnd EDGES_TO_EVENTS.\n\nSection EVENTS_TO_EDGES.\n\nVariable f: event -> event.\nHypothesis F_new: forall a, ~ In (f a) acts'.\nHypothesis F_fun: forall a b, f a = f b -> a = b.\nHypothesis F_tid: forall a, tid a = tid (f a).\nHypothesis F_read: forall a, R (f a).\n\nDefinition RMW_list := filterP RMW' acts'.\nDefinition newR := map f RMW_list.\nDefinition New_R := fun a => In a newR.\nHypothesis ACTS: acts = acts' ++ newR.\n\nHypothesis RMW_COR_R: forall r (NewR_r : New_R r), exists w, rmw r w.\nHypothesis RMW_COR_W: forall w (RMW_w : RMW' w), exists r, rmw r w.\nHypothesis RMW_COR: forall r w (RMW_rw: rmw r w),\n  exists l vr vw o or ow,\n    f w = r /\\\n    New_R r /\\\n    RMW' w /\\\n    lab' w = Armw l vr vw o /\\\n    lab r = Aload l vr or /\\\n    lab w = Astore l vw ow /\\\n    get_rmw_mod or ow = Some o /\\\n    sb|imm r w /\\\n    (forall r', rmw r' w -> r' = r) /\\\n    (forall w', rmw r w' -> w' = w).\nHypothesis LAB: forall a (N_RMW: ~ RMW' a), lab a = lab' a.\n\nHypothesis MO: mo ≡ mo'.\nHypothesis RF: rf ≡ rf' ⨾ ⦗set_compl RMW'⦘ ∪ rf' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹.\nHypothesis Rmw: rmw = (fun r w => RMW w /\\ r = f w).\nHypothesis SB: sb ≡ sb' ∪ sb' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹.\n\nHypothesis DEPS: WfDEPS G.\n\nLemma RMW_implies_not_init\n  (LAB_INIT: forall l : location, lab' (Init l) = init_label l):\n  forall a, RMW' a -> ~ is_init a.\nProof.\n  intros a RMW_a INIT_a.\n  unfold is_init in INIT_a; desf.\n  red in RMW_a; rewrite (LAB_INIT l) in RMW_a; desf.\nQed.\n\nLemma sb_implies_not_init (SB_TID: sb' ⊆ sb'∙ ∪ init_pair) a b (SB_ab: sb' a b): \n  ~ is_init b.\nProof.\n  clear - SB_TID SB_ab.\n  apply SB_TID in SB_ab.\n  unfolder in SB_ab; desf; unfold same_thread, tid, init_pair in *; desf.\nQed.\n\nLemma EE: E ≡₁ E' ∪₁ New_R.\nProof.\n  unfold RC11_Model.E; rewrite ACTS.\n  by unfolder; ins; rewrite in_app_iff.\nQed.\n\nLemma set_union_inter X (A B: X -> Prop): (A ∪₁ B) \\₁ B ⊆₁ A.\nProof. unfolder; ins; desf. Qed.\n\nLemma E_No_NewR: E' ≡₁ E' \\₁ New_R.\nProof.\n  unfolder; split; ins; splits; desf.\n  intro NR; red in NR; unfold RMW_list, newR in NR.\n  apply in_map_iff in NR; desf.\n  apply in_filterP_iff in NR0; desf.\n  red in H; specialize (F_new x0); desf.\nQed.\n\nLemma EE': E' ≡₁ E \\₁ New_R.\nProof.\n  rewrite EE, E_No_NewR.\n  unfolder; ins; split; ins; splits; desf; auto.\nQed.\n\nLemma New_R_seq_E: ⦗New_R⦘ ⨾ ⦗E'⦘ ⊆ ∅₂.\nProof. rewrite EE'; basic_solver. Qed.\n\nLemma rmw_transp_seq_sb (SB_ACT: sb' ⊆ ⦗E'⦘ ⨾ sb' ⨾ ⦗E'⦘):\n  rmw⁻¹ ⨾ sb' ⊆ ∅₂.\nProof.\n  arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗New_R⦘) at 1.\n  { unfolder; intros w r RMW_rw; desf; split; auto.\n    specialize (RMW_COR r w RMW_rw).\n    destruct RMW_COR as (l & COR); desf.\n  }\n  arewrite_false (⦗New_R⦘ ⨾ sb').\n  { rewrite SB_ACT.\n    arewrite_false (⦗New_R⦘ ⨾ ⦗E'⦘); try apply New_R_seq_E.\n    basic_solver.\n  }\n  basic_solver.\nQed.\n\nLemma sb_not_init_implies_st (SB_TID: sb' ⊆ sb'∙ ∪ init_pair)\n  a b (SB_ab: sb' a b) (N_INIT: ~ is_init a):\n  same_thread a b.\nProof.\n  eapply SB_TID in SB_ab.\n  unfold init_pair in *.\n  generalize SB_ab, SB_TID; basic_solver.\nQed.\n\nLemma SB_incl: sb' ⊆ sb.\nProof. rewrite SB; eauto with rel. Qed.\n\nLemma NewR_in_E: New_R ⊆₁ E.\nProof.\n  unfolder; intros r NewR_r.\n  red in NewR_r; unfold newR, RMW_list in *.\n  rewrite ACTS; apply in_app_iff; auto.\nQed.\n\nLemma NewR_in_R: New_R ⊆₁ R.\nProof.\n  unfolder; intros r NewR_r.\n  specialize (RMW_COR_R r NewR_r); destruct RMW_COR_R as [w RMW_rw].\n  specialize (RMW_COR r w RMW_rw).\n  destruct RMW_COR as (l & COR); desf.\nQed.\n\nLemma RMW_in_W: RMW' ⊆₁ W.\nProof.\n  unfolder; intros w RMW_w.\n  specialize (RMW_COR_W w RMW_w); destruct RMW_COR_W as [r RMW_rw].\n  specialize (RMW_COR r w RMW_rw).\n  destruct RMW_COR as (l & COR); desf.\n  red; desf.\nQed.\n\nLemma RMW_in_E (SB_ACT: sb ⊆ ⦗E⦘ ⨾ sb ⨾ ⦗E⦘): RMW' ⊆₁ E'.\nProof.\n  unfolder; intros w RMW_w.\n  assert (NewR_in_R := NewR_in_R).\n  assert (RMW_in_W := RMW_in_W).\n  specialize (RMW_COR_W w RMW_w); destruct (RMW_COR_W) as [r RMW_rw].\n  specialize (RMW_COR r w RMW_rw).\n  destruct RMW_COR as (l & COR); desf.\n  apply EE'; unfolder; split.\n  - unfolder in COR6; desf; apply SB_ACT in COR6; unfolder in COR6; desf.\n  - intro NewR_w.\n    apply NewR_in_R in NewR_w.\n    apply RMW_in_W in COR1.\n    solve_type_mismatch.\nQed.\n\nLemma NewR_implies_sb_to_RMW (SB_ACT: sb ⊆ ⦗E⦘ ⨾ sb ⨾ ⦗E⦘) r (NewR_r: New_R r):\n  exists w, RMW' w /\\ rmw r w /\\ sb|imm r w /\\ E' w.\nProof.\n  assert (NewR_in_R := NewR_in_R).\n  assert (RMW_in_W := RMW_in_W).\n  specialize (RMW_COR_R r NewR_r); destruct (RMW_COR_R) as [w RMW_rw].\n  specialize (RMW_COR r w RMW_rw).\n  destruct RMW_COR as (l & COR); desf.\n  exists w; splits; auto.\n  unfolder in COR6; desf.\n  apply EE'; unfolder; split.\n  - apply SB_ACT in COR6; unfolder in COR6; desf.\n  - intro NewR_w.\n    apply NewR_in_R in NewR_w.\n    apply RMW_in_W in COR1.\n    solve_type_mismatch.\nQed.\n\nLemma WW': W ≡₁ W'.\nProof.\n  red; intros w.\n  destruct (classic (RMW' w)) as [RMW_w | N_RMW_w].\n    by split; intro W_w; [red; red in RMW_w; desf | by apply RMW_in_W].\n  unfold RC11_Events.W.\n  by rewrite (LAB w N_RMW_w).\nQed.\n\nLemma LOC': loc = loc'.\nProof.\n  exten; ins.\n  unfold RC11_Events.loc.\n  destruct (classic (RMW' x)) as [RMW_x | N_RMW_x].\n  - specialize (RMW_COR_W x RMW_x).\n    destruct RMW_COR_W as [r RMW_rx].\n    specialize (RMW_COR r x RMW_rx).\n    destruct RMW_COR as (l & COR); desf.\n  - by rewrite (LAB x N_RMW_x).\nQed.\n\nLemma SAME_LOC': same_loc ≡ same_loc'.\nProof. by unfold RC11_Model.same_loc; rewrite LOC'. Qed.\n\nLemma RR': R' ≡₁ R ∪₁ RMW'.\nProof.\n  split; rename x into r.\n  - intro R_r; unfolder.\n    destruct (classic (RMW' r)) as [RMW_r | N_RMW_r]; [right | left].\n    + specialize (RMW_COR_W r RMW_r).\n      destruct RMW_COR_W as [r2 RMW_r2r].\n      specialize (RMW_COR r2 r RMW_r2r).\n      destruct RMW_COR as (l & COR); desf.\n    + red; red in R_r; by rewrite (LAB r N_RMW_r).\n  - unfolder; ins; desf.\n    + assert (N_RMW_r: ~ RMW' r).\n      { intro RMW_r.\n        apply RMW_in_W in RMW_r.\n        by apply WR_MISMATCH with r.\n      }\n      red; red in H.\n      by rewrite <- (LAB r N_RMW_r).\n    + red; red in H; desf.\nQed.\n\nLemma FF': F' ≡₁ F.\nProof.\n  split; intros F_x; unfold RC11_Events.F in *.\n  - rewrite LAB; auto.\n    intro RMW_x; red in RMW_x; desf.\n  - rewrite <- LAB; auto.\n    intro RMW_x.\n    specialize (RMW_COR_W x RMW_x); destruct RMW_COR_W as [r RMW_rx].\n    specialize (RMW_COR r x RMW_rx); destruct RMW_COR as (l & COR); desf.\nQed.\n\nLemma E_W: ⦗E⦘ ⨾ ⦗W⦘ ⊆ ⦗E'⦘ ⨾ ⦗W'⦘.\nProof.\n  rewrite EE, id_union.\n  relsf; unionL.\n  - by rewrite WW'.\n  - rewrite NewR_in_R.\n    unfolder; ins; desf.\n    by exfalso; apply WR_MISMATCH with y.\nQed.\n\nLemma F_REL': ⦗F ∩₁ Rel⦘ ⊆ ⦗F' ∩₁ Rel'⦘.\nProof.\n  unfolder; intros t a (EQ & F_a & Rel_a); desf; splits; auto; [by apply FF'|].\n  assert (lab a = lab' a) by (apply LAB; apply FF' in F_a; solve_type_mismatch).\n  solve_mode_mismatch.\nQed.\n\nLemma F_ACQ': ⦗F ∩₁ Acq⦘ ⊆ ⦗F' ∩₁ Acq'⦘.\nProof.\n  unfolder; intros t a (EQ & F_a & Acq_a); desf; splits; auto; [by apply FF'|].\n  assert (lab a = lab' a) by (apply LAB; apply FF' in F_a; solve_type_mismatch).\n  solve_mode_mismatch.\nQed.\n\nLemma W_REL': ⦗W ∩₁ Rel⦘ ⊆ ⦗W' ∩₁ Rel'⦘.\nProof.\n  rewrite WW'.\n  unfolder; intros t w (EQ & W_w & Rel_w); desf; splits; auto.\n  destruct (classic (RMW' w)) as [RMW_w | N_RMW_w].\n  - specialize (RMW_COR_W w RMW_w); destruct RMW_COR_W as [r RMW_rw].\n    specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n    red; red in Rel_w; unfold get_rmw_mod in COR5; mode_unfolder; desf.\n  - assert (lab w = lab' w) by by apply LAB.\n    solve_mode_mismatch.\nQed.\n\nLemma W_RLX': ⦗W ∩₁ Rlx⦘ ⊆ ⦗W' ∩₁ Rlx'⦘.\nProof.\n  rewrite WW'.\n  unfolder; intros t w (EQ & W_w & Rlx_w); desf; splits; auto.\n  destruct (classic (RMW' w)) as [RMW_w | N_RMW_w].\n  - specialize (RMW_COR_W w RMW_w); destruct RMW_COR_W as [r RMW_rw].\n    specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n    red; red in Rlx_w; unfold get_rmw_mod in COR5; mode_unfolder; desf.\n  - assert (lab w = lab' w) by by apply LAB.\n    solve_mode_mismatch.\nQed.\n\nLemma W_sbloc_W (WF: Wf G): ⦗W⦘ ⨾ sb|loc^? ⨾ ⦗W ∩₁ Rlx⦘ ⊆ ⦗W'⦘ ⨾ sb'|loc'^? ⨾ ⦗W' ∩₁ Rlx'⦘.\nProof.\n  rewrite SB.\n  arewrite (\n    ((sb' ∪ sb' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹) |loc)^? ⨾ ⦗W ∩₁ Rlx⦘ ⊆ sb'|loc^? ⨾ ⦗W ∩₁ Rlx⦘).\n  { arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗R⦘) by cdes WF; cdes WF_RMW;\n      apply domb_helper, transp_domb; rewrite RMW_DOM; basic_solver.\n    case_refl _; try basic_solver.\n    rewrite inter_union_l; relsf; unionL; [basic_solver|].\n    by unfolder; ins; desf; exfalso; apply WR_MISMATCH with y.\n  }\n  by rewrite W_RLX', WW', SAME_LOC'.\nQed.\n\nLemma R_ACQ': ⦗R ∩₁ Acq⦘ ⊆ ⦗R' ∩₁ Acq'⦘.\nProof.\n  rewrite RR'.\n  unfolder; ins; desf; splits; auto.\n  assert (lab y = lab' y).\n  { apply LAB; intro RMW_y; apply RMW_in_W in RMW_y.\n    by apply WR_MISMATCH with y. }\n  solve_mode_mismatch.\nQed.\n\nLemma R_RLX': ⦗R ∩₁ Rlx⦘ ⊆ ⦗R' ∩₁ Rlx'⦘.\nProof.\n  rewrite RR'.\n  unfolder; ins; desf; splits; auto.\n  assert (lab y = lab' y).\n  { apply LAB; intro RMW_y; apply RMW_in_W in RMW_y.\n    by apply WR_MISMATCH with y. }\n  solve_mode_mismatch.\nQed.\n\nLemma path_helper X (r r' : relation X)\n      (A : r' ⨾ r ≡ ∅₂)\n      (B : r' ⨾ r' ≡ ∅₂) :\n  (r ∪ r')＊ ≡ r＊ ∪ r＊ ⨾ r'.\nProof.\n  clear - A B.\n  split.\n  - eapply inclusion_rt_ind_left; eauto with rel.\n    relsf; unionL; eauto with rel rel_full.\n    + rewrite seq_rtE_r, A; rels; eauto with rel rel_full.\n    + arewrite (r ⨾ r＊ ⊆ r＊); rewrite seq_rtE_l; basic_solver 42.\n    + arewrite (r' ⨾ r＊ ⊆ r' ∪ (r' ⨾ r) ⨾ r＊) by rewrite seq_rtE_r.\n      seq_rewrite A; rels; rewrite B; rels.\n  - arewrite (r ⊆ r ∪ r').\n    arewrite (r ⊆ r ∪ r') at 2.\n    arewrite (r' ⊆ r ∪ r') at 3.\n    rewrite <- ct_end.\n    eauto with rel.\nQed.\n\nLemma pathp_helper X (r r' : relation X)\n      (A : r' ⨾ r ≡ ∅₂)\n      (B : r' ⨾ r' ≡ ∅₂) :\n  (r ∪ r')⁺ ≡ r⁺ ∪ r＊ ⨾ r'.\nProof.\n  clear - A B.\n  rewrite ct_begin, path_helper; auto.\n  split.\n  - relsf; unionL; eauto with rel rel_full.\n    + rewrite seq_rtE_r. rewrite A. rels. eauto with rel rel_full.\n    + arewrite (r ⨾ r＊ ⊆ r＊); eauto with rel rel_full.\n    + rewrite seq_rtE_l.\n      relsf; sin_rewrite B; rels.\n      rewrite ct_begin, !seqA.\n      seq_rewrite A; rels.\n  - unionL.\n    + rewrite ct_begin; basic_solver 42.\n    + rewrite rtE at 1; relsf; unionL.\n      * eauto with rel rel_full.\n      * unionR right -> left.\n        by rewrite ct_begin, !seqA.\nQed.\n\nProposition events_to_edges : consistent' -> consistent.\nProof.\n  ins; cdes H; red; unnw.\n  \n  assert (WF': Wf G).\n  { (* LAB_INIT *)\n    assert (LAB_INIT': forall l : location, lab (Init l) = init_label l).\n    { cdes WF; cdes WF_ACTS; ins; rewrite LAB; auto.\n      intro RMW_I; red in RMW_I; rewrite (LAB_INIT l) in RMW_I; desf. }\n    (* SB_ACT *)\n    assert (SB_ACT': sb ⊆ ⦗E⦘ ⨾ sb ⨾ ⦗E⦘).\n    { cdes WF; cdes WF_SB; rewrite SB, EE; unionL; rewrite SB_ACT at 1.\n      * clear; basic_solver.\n      * arewrite_id ⦗E'⦘ at 2; simpl_rels.\n        arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗New_R⦘) at 1.\n        { unfolder; intros w r RMW_rw; desf; split; auto.\n          specialize (RMW_COR r w RMW_rw).\n          destruct RMW_COR as (l & COR); desf.\n        }\n      arewrite (New_R ⊆₁ E' ∪₁ New_R) at 1 by basic_solver.\n      arewrite (E' ⊆₁ E' ∪₁ New_R) at 1 by basic_solver.\n      clear; basic_solver 42.\n    }\n    (* SB_T *)\n    assert (SB_T': transitive sb).\n    { cdes WF; cdes WF_SB; apply transitiveI; rewrite SB.\n      relsf; unionL; eauto with rel rel_full; rewrite !seqA;\n      sin_rewrite (rmw_transp_seq_sb SB_ACT); basic_solver.\n    }\n    (* SB_TID *)\n    assert (SB_TID': sb ⊆ sb∙ ∪ init_pair).\n    { cdes WF; cdes WF_SB; rewrite SB.\n      unionL.\n      * rewrite SB_TID at 1; unionL; basic_solver.\n      * rewrite SB_TID at 1; relsf; unionL.\n        -- arewrite (sb'∙ ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹ ⊆ (sb' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹)∙).\n           { assert (NewR_in_R := NewR_in_R).\n             clear - SB_TID RMW_COR F_read F_tid NRMW_EVENTS NewR_in_R LAB_INIT'.\n             unfolder; ins; desf; split; [eexists; splits; eauto |].\n             apply st_trans with z; auto.\n             apply st_inv.\n             specialize (RMW_COR y z H1).\n             destruct RMW_COR as (l & COR); desf.\n             \n             red; split.\n             - unfold tid; desf.\n               apply NewR_in_R in COR0.\n               assert (W (Init l0)) by (red; rewrite (LAB_INIT' l0); desf).\n               solve_type_mismatch.\n             - symmetry;apply F_tid.\n           }\n           basic_solver 42.\n        -- arewrite (init_pair ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹ ⊆ init_pair).\n           { clear - F_read RMW_COR NRMW_EVENTS LAB_INIT'.\n             unfold init_pair; unfolder; ins; desf; split; auto.\n             assert (R y).\n             { specialize (RMW_COR y z H1).\n               destruct RMW_COR as (l & COR); desf.\n             }\n             intro INIT_y.\n             assert (W y) by\n              (red in INIT_y; desf; red; rewrite (LAB_INIT' l); desf).\n             by apply WR_MISMATCH with y.\n           }\n           eauto with rel.\n    }\n    \n    (* RMW_DOM *)\n    assert (RMW_DOM': rmw ⊆ ⦗R⦘ ⨾ rmw ⨾ ⦗W⦘).\n    { unfolder; intros r w RMW_rw.\n      assert (RMW_in_W := RMW_in_W).\n      specialize (RMW_COR r w RMW_rw).\n      destruct RMW_COR as (l & COR); desf.\n      splits; auto.\n    }\n    (* RMW_LOC *)\n    assert (RMW_LOC': funeq loc rmw).\n    { red; intros r w RMW_rw.\n      specialize (RMW_COR r w RMW_rw).\n      destruct RMW_COR as (l & COR); desf.\n      unfold RC11_Events.loc; desf.\n    }\n    (* RMW_IMM *)\n    assert (RMW_IMM': rmw ⊆ sb|imm).\n    { unfolder; intros r w RMW_rw.\n      specialize (RMW_COR r w RMW_rw).\n      destruct RMW_COR as (l & COR); desf.\n    }\n    \n    cdes WF; red; unnw; splits.\n    - (* WfACTS *)\n      cdes WF_ACTS; red; splits; unnw; auto.\n      + (* ACTS_INIT *)\n        rewrite ACTS.\n        ins; specialize (ACTS_INIT l).\n        apply in_app_iff; auto.\n    - (* WfSB *)\n      cdes WF_SB; red; splits; unnw; auto.\n      + (* SB_INIT *)\n        rewrite EE, SB, id_union.\n        relsf; unionL.\n        * rewrite SB_INIT; eauto with rel.\n        * unionR right.\n          unfolder; intros i r (IP_ir & NewR_r).\n          assert (RMW_in_E := RMW_in_E).\n          specialize (RMW_COR_R r NewR_r); destruct RMW_COR_R as [w RMW_rw].\n          specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n          exists w; splits; auto.\n          apply SB_INIT.\n          unfolder in COR6; desf.\n          exists w; split.\n          -- unfold init_pair in *; split; desf.\n             by cdes WF; cdes WF_ACTS; apply RMW_implies_not_init.\n          -- unfolder; split; auto.\n             by apply RMW_in_E.\n      + (* SB_IRR *)\n        rewrite SB; unionL; auto.\n        rotate.\n        sin_rewrite (rmw_transp_seq_sb SB_ACT); basic_solver.\n      + (* SB_TOT *)\n        ins; specialize (SB_TOT i).\n        assert (NewR_implies_sb_to_RMW := NewR_implies_sb_to_RMW).\n        clear - WF SB ACTS SB_ACT' SB_TID' SB_TOT SB_T' RMW_COR NewR_implies_sb_to_RMW.\n        arewrite (E ⊆₁ E' ∪₁ New_R) by rewrite EE.\n        unfold is_total in *; ins; unfolder in IWa; unfolder in IWb; desf.\n        * assert (IWa': (E' ∩₁ (fun a : event => tid a = Some i)) a)\n            by basic_solver.\n          assert (IWb': (E' ∩₁ (fun a : event => tid a = Some i)) b)\n            by basic_solver.\n          specialize (SB_TOT a IWa' b IWb' NEQ); desf;\n          [left | right]; by apply SB_incl.\n        * apply (NewR_implies_sb_to_RMW SB_ACT') in IWa.\n          destruct IWa as (w & RMW_w & RMW_aw & SB_aw & E_w).\n          destruct (classic (w = b)) as [EQ | NEQ'].\n          { (* w = b *) unfolder in SB_aw; desf; subst; auto. }\n          assert (IWw': (E' ∩₁ (fun a : event => tid a = Some i)) w).\n          { unfolder; split; auto.\n            unfolder in SB_aw; desf.\n            apply SB_TID' in SB_aw; unfolder in SB_aw; desf.\n            - unfold same_thread in *; desf; congruence.\n            - repeat (red in SB_aw; desf).\n          }\n          assert (IWb': (E' ∩₁ (fun a : event => tid a = Some i)) b)\n            by basic_solver.\n          specialize (SB_TOT w IWw' b IWb' NEQ'); desf.\n          -- unfolder in SB_aw; desf; apply SB_incl in SB_TOT; eauto with rel.\n          -- right; apply SB; right; basic_solver.\n        * apply (NewR_implies_sb_to_RMW SB_ACT') in IWb.\n          destruct IWb as (w & RMW_w & RMW_aw & SB_aw & E_w).\n          destruct (classic (a = w)) as [EQ | NEQ'].\n          { (* a = w *) unfolder in SB_aw; desf; subst; auto. }\n          assert (IWa': (E' ∩₁ (fun a : event => tid a = Some i)) a)\n            by basic_solver.\n          assert (IWw': (E' ∩₁ (fun a : event => tid a = Some i)) w).\n          { unfolder; split; auto.\n            unfolder in SB_aw; desf.\n            apply SB_TID' in SB_aw; unfolder in SB_aw; desf.\n            - unfold same_thread in *; desf; congruence.\n            - repeat (red in SB_aw; desf).\n          }\n          specialize (SB_TOT a IWa' w IWw' NEQ'); desf.\n          -- left; apply SB; right; basic_solver.\n          -- unfolder in SB_aw; desf; apply SB_incl in SB_TOT; eauto with rel.\n        * apply (NewR_implies_sb_to_RMW SB_ACT') in IWa.\n          destruct IWa as (w1 & RMW_w1 & RMW_aw1 & SB_aw1 & E_w1).\n          apply (NewR_implies_sb_to_RMW SB_ACT') in IWb.\n          destruct IWb as (w2 & RMW_w2 & RMW_bw2 & SB_bw2 & E_w2).\n          destruct (classic (w1 = w2)) as [EQ | NEQ'].\n          { (* w1 = w2 *)\n            subst; exfalso; apply NEQ.\n            specialize (RMW_COR a w2 RMW_aw1).\n            destruct RMW_COR as (l & COR); desf.\n            by symmetry; apply COR7.\n          }\n          assert (IWw1: (E' ∩₁ (fun a : event => tid a = Some i)) w1).\n          { unfolder; split; auto.\n            unfolder in SB_aw1; desf.\n            apply SB_TID' in SB_aw1; unfolder in SB_aw1; desf.\n            - unfold same_thread in *; desf; congruence.\n            - repeat (red in SB_aw1; desf).\n          }\n          assert (IWw2: (E' ∩₁ (fun a : event => tid a = Some i)) w2).\n          { unfolder; split; auto.\n            unfolder in SB_bw2; desf.\n            apply SB_TID' in SB_bw2; unfolder in SB_bw2; desf.\n            - unfold same_thread in *; desf; congruence.\n            - repeat (red in SB_bw2; desf).\n          }\n          specialize (SB_TOT w1 IWw1 w2 IWw2 NEQ'); desf.\n          -- assert (SB_w1b: sb w1 b) by (apply SB; right; basic_solver).\n             unfolder in SB_aw1; desf.\n             eauto with rel.\n          -- assert (SB_w2a: sb w2 a) by (apply SB; right; basic_solver).\n             unfolder in SB_bw2; desf.\n             eauto with rel.\n    - (* WfRMW *)\n      cdes WF_RMW; red; splits; unnw; auto.\n      + (* RMW_MOD *)\n        intros r w RMW_rw.\n        specialize (RMW_COR r w RMW_rw).\n        destruct RMW_COR as (l & COR); desf.\n        clear - COR3 COR4 COR5.\n        unfold get_rmw_mod in *; destruct or, ow; desf; solve_mode_mismatch.\n    - (* WfRF *)\n      cdes WF_RF; red; splits; unnw.\n      + (* RF_ACT *)\n        rewrite RF; unionL.\n        * rewrite RF_ACT at 1; rewrite !seqA; rewrite seq_eqvC at 1.\n          arewrite (E' ⊆₁ E) by rewrite EE; basic_solver.\n          basic_solver 42.\n        * rewrite RF_ACT at 1; arewrite_id ⦗E'⦘ at 2; simpl_rels.\n          arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗E⦘) at 1.\n          { apply domb_helper, transp_domb; red; intros a b RMW_ab.\n            apply RMW_IMM' in RMW_ab; unfolder in RMW_ab; desf.\n            apply SB_ACT' in RMW_ab; unfolder in RMW_ab; desf.\n          }\n          arewrite (E' ⊆₁ E) by rewrite EE; basic_solver.\n          basic_solver 42.\n      + (* RF_IRR *)\n        rewrite RF; unionL.\n        * by clear_equivs ⦗set_compl RMW'⦘.\n        * arewrite (rf' ⊆ ⦗W⦘ ⨾ rf')\n            by rewrite WW'; rewrite RF_DOM at 1; basic_solver.\n          arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗R⦘)\n            by apply domb_helper, transp_domb; rewrite RMW_DOM'; basic_solver.\n          rotate; unfolder; ins; desf.\n          by apply WR_MISMATCH with z.\n      + (* RF_DOM *)\n        rewrite RF; unionL.\n        * rewrite RF_DOM at 1; rewrite RR', <- WW'; rewrite !seqA.\n          arewrite (⦗R ∪₁ RMW'⦘ ⨾ ⦗set_compl RMW'⦘ ⊆ ⦗set_compl RMW'⦘ ⨾ ⦗R⦘)\n            by unfolder; ins; desf.\n          basic_solver 42.\n        * arewrite (rf' ⊆ ⦗W⦘ ⨾ rf')\n            by rewrite WW'; rewrite RF_DOM at 1; basic_solver.\n          arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗R⦘) at 1.\n            by apply domb_helper, transp_domb; rewrite RMW_DOM'; basic_solver.\n          basic_solver 42.\n      + (* RF_LOC *)\n        rewrite RF; apply funeq_union.\n        * by rewrite LOC'; clear_equivs ⦗set_compl RMW'⦘.\n        * repeat apply funeq_seq.\n          -- by rewrite LOC'.\n          -- by apply funeq_eqv_rel.\n          -- by apply funeq_transp.\n      + (* RF_VAL *)\n        intros a b RF_ab; apply RF in RF_ab; unfolder in RF_ab; desf.\n        * assert (N_RMW_b: ~ RMW' b) by tauto.\n          destruct (classic (RMW' a)) as [RMW_a | N_RMW_a].\n          -- specialize (RMW_COR_W a RMW_a); destruct RMW_COR_W as [r RMW_ra].\n             specialize (RMW_COR r a RMW_ra); destruct RMW_COR as (l & COR); desf.\n             unfold valr, valw in *.\n             rewrite (LAB b N_RMW_b), <- (RF_VAL a b RF_ab).\n             desf.\n          -- unfold valr, valw in *.\n             by rewrite (LAB b N_RMW_b), (LAB a N_RMW_a), <- (RF_VAL a b RF_ab).\n        * assert (VA: valw lab a = valw lab' a).\n          { destruct (classic (RMW' a)) as [RMW_a | N_RMW_a].\n            - specialize (RMW_COR_W a RMW_a); destruct RMW_COR_W as [r RMW_ra].\n              specialize (RMW_COR r a RMW_ra); destruct RMW_COR as (l & COR); desf.\n              unfold valr, valw in *; desf.\n            - unfold valr, valw in *.\n              by rewrite (LAB a N_RMW_a).\n          }\n          rename RF_ab0 into RMW_z, RF_ab1 into RMW_bz.\n          specialize (RMW_COR_W z RMW_z); destruct RMW_COR_W as [r RMW_rz].\n          specialize (RMW_COR r z RMW_rz); destruct RMW_COR as (l & COR); desf.\n          specialize (COR7 b RMW_bz); desf.\n          rewrite VA, (RF_VAL a z RF_ab).\n          unfold valr, valw in *; desf.\n      + (* RF_FUN *)\n        rewrite RF.\n        apply functional_union.\n        * red; unfolder; ins; desf.\n          red in RF_FUN; apply (RF_FUN x y z); basic_solver.\n        * red; unfolder; ins; desf.\n          assert (z2 = z3).\n          { specialize (RMW_COR x z3 H6); destruct RMW_COR as (l & COR); desf.\n            apply (COR8 z2 H3). }\n          subst; apply (RF_FUN z3 y z); basic_solver.\n        * clear - RF_ACT F_new RMW_COR.\n          unfold dom_rel; ins; unfolder in *; desf.\n          apply (F_new z1).\n          specialize (RMW_COR x z1 H2); destruct RMW_COR as (l & COR); desf.\n          apply RF_ACT in H; desf.\n      + (* RF_TOT *)\n        ins.\n        destruct (classic (New_R b)) as [NewR_r | N_NewR].\n        * rename b into r.\n          assert (RR' := RR').\n          assert (NewR_in_R := NewR_in_R).\n          assert (RMW_in_W := RMW_in_W).\n          specialize (RMW_COR_R r NewR_r); destruct RMW_COR_R as [w RMW_rw].\n          specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n          assert (E' w).\n          { apply EE'; unfolder; split.\n            - unfolder in COR6; desf; apply SB_ACT' in COR6; unfolder in COR6; desf.\n            - intro NewR_w; apply NewR_in_R in NewR_w; apply RMW_in_W in COR1.\n              by apply WR_MISMATCH with w.\n          }\n          assert (R' w) by (apply RR'; unfolder; auto).\n          specialize (RF_TOT w H0 H1); desf.\n          exists a; apply RF; right.\n          exists w; split; auto.\n          unfolder; splits; auto.\n        * assert (E' b) by (apply EE'; unfolder; auto).\n          assert (R' b) by (apply RR'; unfolder; auto).\n          specialize (RF_TOT b H0 H1); desf.\n          exists a; apply RF.\n          destruct (classic (RMW' b)) as [RMW_b | N_RMW_b]; [right | left].\n          -- apply RMW_in_W in RMW_b.\n             by exfalso; apply WR_MISMATCH with b.\n          -- unfolder; split; auto.\n    - (* WfMO *)\n      cdes WF_MO; red; splits; unnw; rewrite ?MO, ?LOC'; try done.\n      + (* MO_ACT *)\n        rewrite MO_ACT at 1.\n        arewrite (E' ⊆₁ E) by rewrite EE; basic_solver.\n      + (* MO_DOM *)\n        rewrite MO_DOM at 1.\n        arewrite (W' ⊆₁ W) by rewrite WW'.\n      + (* MO_TOT *)\n        ins; specialize (MO_TOT l); rewrite MO.\n        arewrite (E ∩₁ W ∩₁ (fun a : event => loc' a = Some l) ⊆₁\n                  E' ∩₁ W' ∩₁ (fun a : event => loc' a = Some l)).\n        { rewrite WW', EE.\n          unfolder; ins; desf; splits; auto.\n          apply WW' in H2; apply NewR_in_R in H0.\n          by exfalso; apply WR_MISMATCH with x.\n        }\n        done.\n    - (* WfDEPS *) done.\n  }\n  \n  assert (RB: rb ⊆ rb' ∪ rmw ⨾ ⦗RMW'⦘ ⨾ rb'^?).\n  { arewrite (rb ≡ rf⁻¹ ⨾ mo) by rewrite NRMW_implies_original_rb.\n    unfold RC11_Model.rb.\n    rewrite MO, RF, !transp_union, !transp_seq, !transp_eqv_rel, !transp_inv,\n      seq_union_l, !seqA; unionL.\n    - unionR left.\n      arewrite (rf'⁻¹ ⊆ ⦗R'⦘ ⨾ rf'⁻¹) at 1\n        by cdes WF; cdes WF_RF; rewrite RF_DOM at 1; basic_solver.\n      arewrite (mo' ⊆ mo' ⨾ ⦗W'⦘) at 1\n        by cdes WF; cdes WF_MO; rewrite MO_DOM at 1; basic_solver.\n      unfolder; ins; desf; split; eauto.\n      apply or_not_and; left.\n      intro; subst; contradict H0; solve_type_mismatch.\n    - unionR right.\n      unfolder; ins; desf.\n      destruct (classic (z = y)) as [EQ | NEQ]; eauto.\n      repeat eexists; splits; eauto.\n      right.\n      repeat eexists; splits; eauto.\n      by apply or_not_and; left.\n  }\n  \n  assert (ECO: eco ⊆ \n    eco' ∪\n    rmw ⨾ ⦗RMW'⦘ ⨾ eco'^? ∪\n    eco' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹ ∪\n    rmw ⨾ ⦗RMW'⦘ ⨾ eco' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹).\n  { unfold RC11_Model.eco.\n    rewrite MO; rewrite RF; rewrite RB.\n    relsf; unionL; try basic_solver 42.\n  }\n  \n  assert (SW: sw ⊆ sw' ∪ sw' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹).\n  { unfold RC11_Model.sw, RC11_Model.release, RC11_Model.rs.\n    rewrite (NRMW_implies_original_useq WF' NRMW_EVENTS).\n    unfold RC11_Model.useq.\n    sin_rewrite (W_sbloc_W WF').\n    rewrite <- WW' at 1.\n    rewrite !seqA; sin_rewrite E_W; rewrite !seqA.\n    rewrite W_REL', F_REL', R_RLX', F_ACQ'.\n    \n    arewrite (sb ⨾ ⦗F' ∩₁ Acq'⦘ ⊆ sb' ⨾ ⦗F' ∩₁ Acq'⦘).\n    { rewrite SB; relsf; unionL; [basic_solver|].\n      arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗R⦘) by cdes WF'; cdes WF_RMW;\n        apply domb_helper, transp_domb; rewrite RMW_DOM; basic_solver.\n      rewrite FF'.\n      unfolder; ins; desf; solve_type_mismatch.\n    }\n    \n    arewrite (rmw' ≡ ∅₂) by basic_solver.\n    rels.\n    arewrite ((⦗W' ∩₁ Rel'⦘ ∪ ⦗F' ∩₁ Rel'⦘ ⨾ sb) ⨾ ⦗E'⦘ ⨾ ⦗W'⦘ ⊆\n              (⦗W' ∩₁ Rel'⦘ ∪ ⦗F' ∩₁ Rel'⦘ ⨾ sb') ⨾ ⦗E'⦘ ⨾ ⦗W'⦘).\n    { rewrite SB.\n      relsf; unionL; [by unionR left | by unionR right |].\n      arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗R⦘) by cdes WF'; cdes WF_RMW;\n        apply domb_helper, transp_domb; rewrite RMW_DOM; basic_solver.\n      arewrite_id ⦗E'⦘ at 1; simpl_rels.\n      rewrite <- WW'.\n      by unfolder; ins; desf; exfalso; apply WR_MISMATCH with y.\n    }\n    rewrite RF.\n    arewrite (((rf' ⨾ ⦗set_compl RMW'⦘ ∪ rf' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹) ⨾ rmw)＊ ⊆ (rf' ⨾ ⦗RMW'⦘)＊).\n    { rewrite seq_union_l.\n      arewrite ((rf' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹) ⨾ rmw ⊆ rf' ⨾ ⦗RMW'⦘).\n      { unfolder; ins; desf.\n        specialize (RMW_COR z0 z H2); destruct RMW_COR as (l & COR); desf.\n        specialize (COR8 y H3); desf.\n      }\n      arewrite_false (rf' ⨾ ⦗set_compl RMW'⦘ ⨾ rmw).\n      { cdes WF; cdes WF_RF; rewrite RF_ACT.\n        unfolder; ins; desf.\n        specialize (RMW_COR z1 y H4); destruct RMW_COR as (l & COR); desf.\n        apply (F_new y).\n        by red in H6.\n      }\n      rels.\n    }\n    case_union_2 _ (rf' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹); [unionR left | unionR right]; hahn_frame.\n    - rewrite R_ACQ'; rels; basic_solver 42.\n    - case_union_2 _ _.\n      + unionR left.\n        unfolder; ins; desf.\n        repeat eexists; splits; eauto; [solve_type_mismatch|].\n        specialize (RMW_COR y z0 H3); destruct RMW_COR as (l & COR); desf.\n        unfold get_rmw_mod in *; red; red in H5; solve_mode_mismatch.\n      + arewrite_id ⦗R' ∩₁ Rlx'⦘ at 1; simpl_rels.\n        arewrite_false (rmw⁻¹ ⨾ sb').\n        { arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗New_R⦘) at 1.\n          { unfolder; intros w r RMW_rw; desf; split; auto.\n            specialize (RMW_COR r w RMW_rw).\n            destruct RMW_COR as (l & COR); desf.\n          }\n          arewrite (sb' ⊆ ⦗E'⦘ ⨾ sb') by cdes WF; cdes WF_SB;\n            rewrite SB_ACT at 1; basic_solver.\n          unfolder; ins; desf.\n          apply (F_new x).\n          specialize (RMW_COR z0 x H0); destruct RMW_COR as (l & COR); desf.\n        }\n        rels.\n  }\n  \n  assert (RMW_seq_SB_SW: rmw⁻¹ ⨾ (sb' ∪ sw') ⊆ ∅₂).\n  { arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗New_R⦘) at 1.\n    { unfolder; intros w r RMW_rw; desf; split; auto.\n      specialize (RMW_COR r w RMW_rw).\n      destruct RMW_COR as (l & COR); desf.\n    }\n    arewrite (sb' ∪ sw' ⊆ ⦗E'⦘ ⨾ (sb' ∪ sw')).\n    { unionL.\n      - arewrite (sb' ⊆ ⦗E'⦘ ⨾ sb') by cdes WF; cdes WF_SB;\n          rewrite SB_ACT at 1; basic_solver.\n        basic_solver.\n      - rewrite seq_union_r; unionR right.\n        unfold RC11_Model.sw, RC11_Model.release, RC11_Model.rs.\n        arewrite (sb' ⊆ ⦗E'⦘ ⨾ sb') at 1 by cdes WF; cdes WF_SB;\n          rewrite SB_ACT at 1; basic_solver.\n        case_union_2 ⦗W' ∩₁ Rel'⦘ _.\n        + arewrite (⦗W' ∩₁ Rel'⦘ ⨾ ⦗E'⦘ ⊆ ⦗E'⦘ ⨾ ⦗W' ∩₁ Rel'⦘ ⨾ ⦗E'⦘) by basic_solver.\n          eauto with rel rel_full.\n        + arewrite (⦗F' ∩₁ Rel'⦘ ⨾ ⦗E'⦘ ⊆ ⦗E'⦘ ⨾ ⦗F' ∩₁ Rel'⦘) by basic_solver.\n          eauto with rel rel_full.\n    }\n    sin_rewrite New_R_seq_E.\n    rels.\n  }\n  \n  assert (HB: hb ⊆ hb' ∪ hb' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹).\n  { unfold RC11_Model.hb.\n    arewrite (sb ∪ sw ⊆ (sb' ∪ sw') ∪ (sb' ∪ sw') ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹).\n      by rewrite SB, SW; basic_solver 42.\n    rewrite pathp_helper;\n    try by (split; [rewrite !seqA; sin_rewrite RMW_seq_SB_SW|]; basic_solver).\n    seq_rewrite <- ct_end; eauto with rel rel_full.\n  }\n  assert (HB_SEQ_RMW: hb' ⨾ rmw ⊆ ∅₂).\n  { unfolder; ins; desf.\n    rename z into r, y into w, H1 into RMW_rw.\n    specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n    eby eapply F_new, hb_actb.\n  }\n  assert (RMW_SEQ_SB: rmw⁻¹ ⨾ sb' ⊆ ∅₂).\n  { cdes WF; cdes WF_SB.\n    unfolder; ins; desf.\n    rename z into r, x into w, H0 into RMW_rw.\n    specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n    eby eapply F_new, sb_acta.\n  }\n  assert (RMW_SEQ_RF: rmw⁻¹ ⨾ rf' ⊆ ∅₂).\n  { cdes WF; cdes WF_RF.\n    unfolder; ins; desf.\n    rename z into r, x into w, H0 into RMW_rw.\n    specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n    eby eapply F_new, rf_acta.\n  }\n  assert (RMW_SEQ_ECO: rmw⁻¹ ⨾ eco' ⊆ ∅₂).\n  { unfolder; ins; desf.\n    rename z into r, x into w, H0 into RMW_rw.\n    specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n    eby eapply F_new, eco_acta.\n  }\n  assert (RMW_SEQ_F: rmw⁻¹ ⨾ ⦗F ∩₁ Sc⦘ ⊆ ∅₂).\n  { unfolder; ins; desf.\n    rename y into r, x into w, H0 into RMW_rw.\n    specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n    solve_type_mismatch.\n  }\n  assert (RMW_SEQ_HB: rmw⁻¹ ⨾ hb' ⊆ ∅₂).\n  { unfolder; ins; desf.\n    rename z into r, x into w, H0 into RMW_rw.\n    specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n    eby eapply F_new, hb_acta.\n  }\n  assert (RMW_SEQ_MO: rmw⁻¹ ⨾ mo' ⊆ ∅₂).\n  { cdes WF; cdes WF_MO.\n    unfolder; ins; desf.\n    rename z into r, x into w, H0 into RMW_rw.\n    specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n    eby eapply F_new, mo_acta.\n  }\n  assert (RMW_SEQ_RB: rmw⁻¹ ⨾ rb' ⊆ ∅₂).\n  { cdes WF; cdes WF_RF.\n    unfolder; ins; desf.\n    rename z into r, x into w, H0 into RMW_rw.\n    specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n    eby eapply F_new, rb_acta.\n  }\n  assert (SB_RMW_HB: (sb' ∪ sb' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹) ⨾ hb' ⊆ sb' ⨾ hb').\n  { case_union_2 _ _; [basic_solver|].\n    simpl_rels; sin_rewrite RMW_SEQ_HB; basic_solver.\n  }\n  assert (HB_RMW_HB: (hb' ∪ hb' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹) ⨾ hb' ⊆ hb').\n  { case_union_2 _ _.\n    - arewrite (hb' ⨾ hb' ⊆ hb'); basic_solver.\n    - simpl_rels; sin_rewrite RMW_SEQ_HB; basic_solver.\n  }\n  assert (RMW_SB_RMW: rmw⁻¹ ⨾ (sb' ∪ sb' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹) ⊆ ∅₂).\n  { case_union_2 _ _; sin_rewrite RMW_SEQ_SB; basic_solver. }\n  assert (RMW_HB_RMW: rmw⁻¹ ⨾ (hb' ∪ hb' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹) ⊆ ∅₂).\n  { case_union_2 _ _; sin_rewrite RMW_SEQ_HB; basic_solver. }\n  assert (HB_RMW_HB_LOC: (hb' ∪ hb' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹) |loc' ⨾ hb' ⊆ hb'|loc' ⨾ hb').\n  { rewrite inter_union_l.\n    case_union_2 _ _; [basic_solver|].\n    rewrite inter_inclusion; simpl_rels; sin_rewrite RMW_SEQ_HB; basic_solver.\n  }\n\n  splits; auto.\n  + (* Coherence *)\n    red; red in COH.\n    case_refl _; rewrite HB; case_union_2 _ _.\n    - by apply irr_hb.\n    - unfolder; ins; desf.\n      apply F_new with (a := z).\n      specialize (RMW_COR x z H2); destruct RMW_COR as (l & COR); desf.\n      by apply hb_acta in H0.\n    - rewrite ECO.\n      relsf; repeat (apply irreflexive_union; split).\n      * by rewrite crE, seq_union_r, irreflexive_union in COH; desf.\n      * unfolder; ins; desf.\n        -- apply F_new with (a := x).\n           specialize (RMW_COR z x H1); destruct RMW_COR as (l & COR); desf.\n           by apply hb_actb in H0.\n        -- apply F_new with (a := z0).\n           specialize (RMW_COR z z0 H1); destruct RMW_COR as (l & COR); desf.\n           by apply hb_actb in H0.\n      * unfolder; ins; desf.\n        apply F_new with (a := z0).\n        specialize (RMW_COR x z0 H3); destruct RMW_COR as (l & COR); desf.\n        by apply hb_acta in H0.\n      * unfolder; ins; desf.\n        apply F_new with (a := z0).\n        specialize (RMW_COR z z0 H1); destruct RMW_COR as (l & COR); desf.\n        by apply hb_actb in H0.\n    - rewrite ECO.\n      relsf; repeat (apply irreflexive_union; split).\n      * unfolder; ins; desf.\n        apply F_new with (a := z).\n        specialize (RMW_COR z0 z H2); destruct RMW_COR as (l & COR); desf.\n        by apply eco_acta in H3.\n      * unfolder; ins; desf.\n        -- assert (EQ: x = z).\n           { specialize (RMW_COR z0 z H2); destruct RMW_COR as (l & COR); desf.\n             by apply (COR8 x). }\n           apply COH with x.\n           by unfolder; ins; desf; eexists; eauto.\n        -- assert (EQ: z2 = z).\n           { specialize (RMW_COR z0 z H2); destruct RMW_COR as (l & COR); desf.\n             by apply (COR8 z2). }\n           apply COH with x.\n           unfolder; ins; desf.\n           by exists z; split; auto.\n      * unfolder; ins; desf.\n        apply F_new with (a := z2).\n        specialize (RMW_COR x z2 H5); destruct RMW_COR as (l & COR); desf.\n        by apply hb_acta in H0.\n      * unfolder; ins; desf.\n        apply F_new with (a := z4).\n        specialize (RMW_COR x z4 H7); destruct RMW_COR as (l & COR); desf.\n        by apply hb_acta in H0.\n  + (* Atomicity *)\n    red; red in AT.\n    rewrite RB, MO.\n    case_union_2 _ _.\n    - unfolder; ins; desf.\n      apply F_new with (a := z0).\n      specialize (RMW_COR x z0 H2); destruct RMW_COR as (l & COR); desf.\n      by cdes WF; apply rb_acta in H0.\n    - case_refl _.\n      * unfolder; ins; desf.\n        specialize (RMW_COR x z H0); destruct RMW_COR as (l & COR); desf.\n        specialize (COR8 z0 H3); desf.\n        by cdes WF; cdes WF_MO; apply MO_IRR with z.\n      * unfolder; ins; desf.\n        specialize (RMW_COR x z H0); destruct RMW_COR as (l & COR); desf.\n        specialize (COR8 z1 H4); desf.\n        unfold RC11_Model.rb in H2; unfolder in H2; desf.\n        apply AT2 with z1.\n        unfolder; ins; desf; eauto with rel.\n  + (* Atomicity2 *)\n    by apply NRMW_implies_atomic2.\n  + (* SC *)\n    red; red in SC; unfold RC11_Model.psc in *.\n    assert (F_SC: F ∩₁ Sc ⊆₁ F' ∩₁ Sc').\n    { unfolder; ins; desf.\n      assert (LAB_EQ: lab x = lab' x).\n      { apply LAB; red; ins.\n        assert (W x).\n        { specialize (RMW_COR_W x H2); destruct RMW_COR_W as (r & RMW_rx).\n          cdes WF'; cdes WF_RMW; specialize (RMW_DOM r x RMW_rx).\n          unfolder in RMW_DOM; desf.\n        }\n        solve_type_mismatch.\n      }\n      unfold RC11_Events.F, RC11_Events.Sc, RC11_Events.mod.\n      by rewrite <- LAB_EQ.\n    }\n    assert (PSC_F: psc_f ⊆ psc_f').\n    { unfold RC11_Model.psc_f in *.\n      case_union_2 _ _.\n      - rewrite HB; case_union_2 _ _.\n        + rewrite F_SC; basic_solver 42.\n        + arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗R⦘) \n            by cdes WF'; eapply domb_helper, transp_domb, rmw_doma.\n          solve_type_mismatch 42.\n      - rewrite HB at 1; case_union_2 _ _.\n        + rewrite HB at 1; case_union_2 _ _.\n          { rewrite ECO.\n            case_union_4 _ _ (eco' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹) (rmw ⨾ ⦗RMW'⦘ ⨾ eco' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹).\n            2,3,4: by simpl_rels; (sin_rewrite HB_SEQ_RMW +\n                                   sin_rewrite RMW_SEQ_HB); basic_solver.\n            rewrite F_SC; basic_solver 42.\n          }\n          arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗R⦘) \n            by cdes WF'; eapply domb_helper, transp_domb, rmw_doma.\n          solve_type_mismatch 42.\n       + arewrite (F ∩₁ Sc ⊆₁ F' ∩₁ Sc').\n         rewrite HB at 1; case_union_2 _ _.\n         { rewrite ECO; relsf; unionL.\n           - sin_rewrite RMW_SEQ_ECO; basic_solver.\n           - case_refl _.\n            + unionR left.\n              unfolder; ins; desf.\n              exists x; splits; auto.\n              specialize (RMW_COR z1 z0 H3); destruct RMW_COR as (l & COR); desf.\n              specialize (COR8 z3 H4); desf.\n              by apply hb_trans with z0.\n            + unionR right.\n              clear_equivs ⦗RMW'⦘.\n              hahn_frame.\n              unfolder; ins; desf.\n              assert (z = y).\n              { specialize (RMW_COR z0 z H1); destruct RMW_COR as (l & COR); desf.\n                specialize (COR8 y H2); desf. }\n              desf.\n         - simpl_rels; sin_rewrite RMW_SEQ_HB; basic_solver.\n         - simpl_rels; sin_rewrite RMW_SEQ_HB; basic_solver.\n        }\n        arewrite (rmw⁻¹ ⊆ rmw⁻¹ ⨾ ⦗R⦘) \n            by cdes WF'; eapply domb_helper, transp_domb, rmw_doma.\n        arewrite (⦗R⦘ ⨾ ⦗F' ∩₁ Sc'⦘ ⊆ ∅₂).\n        { unfolder; ins; desf.\n          assert (~ RMW' y) by solve_type_mismatch.\n          specialize (LAB y H0).\n          solve_type_mismatch 42.\n        }\n        basic_solver.\n    }\n    rewrite PSC_F.\n    assert (SC_SB: ⦗Sc⦘ ⨾ sb' ⊆ ⦗Sc'⦘ ⨾ sb').\n    { unfolder; ins; desf; split; auto; rename x into w.\n      destruct (classic (RMW' w)).\n      - specialize (RMW_COR_W w H2); destruct RMW_COR_W as [r].\n        specialize (RMW_COR r w H3); destruct RMW_COR as (l & COR); desf.\n        unfold RC11_Events.Sc, RC11_Events.mod, get_rmw_mod in *; desf.\n      - unfold RC11_Events.Sc, RC11_Events.mod in *.\n        by rewrite (LAB w H2) in H0.\n    }\n    assert (SB_SC: sb' ⨾ ⦗Sc⦘ ⊆ sb' ⨾ ⦗Sc'⦘).\n    { unfolder; ins; desf; split; auto; rename y into w.\n      destruct (classic (RMW' w)).\n      - specialize (RMW_COR_W w H2); destruct RMW_COR_W as [r].\n        specialize (RMW_COR r w H3); destruct RMW_COR as (l & COR); desf.\n        unfold RC11_Events.Sc, RC11_Events.mod, get_rmw_mod in *; desf.\n      - unfold RC11_Events.Sc, RC11_Events.mod in *.\n        by rewrite (LAB w H2) in H1.\n    }\n    assert (PSC_BASE: psc_base ⊆ psc_base' ∪ psc_base' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹).\n    { unfold RC11_Model.psc_base in *.\n      repeat rewrite seq_union_l; unionL; repeat rewrite seq_union_r; unionL.\n      - unfold RC11_Model.scb, RC11_Model.sb_neq_loc.\n        rewrite SB, HB, MO, RB.\n        relsf; unionL; simpl_rels.\n(*         all: arewrite (Sc ⊆₁ Sc') by admit. *)\n        + sin_rewrite SC_SB; simpl_rels; sin_rewrite SB_SC.\n          repeat unionR left; eauto with rel.\n        + unionR right.\n          arewrite (⦗RMW'⦘ ⨾ rmw⁻¹ ⨾ ⦗Sc⦘ ⊆ ⦗Sc'⦘ ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹ ⨾ ⦗Sc⦘).\n          { unfolder; ins; desf.\n            splits; auto.\n            rename y into r, x into w, H1 into RMW_rw.\n            specialize (RMW_COR r w RMW_rw); destruct RMW_COR as (l & COR); desf.\n            unfold get_rmw_mod in COR5.\n            solve_mode_mismatch 42.\n          }\n          repeat unionR left.\n          arewrite (⦗Sc⦘ ⨾ sb' ⊆ ⦗Sc'⦘ ⨾ sb') by admit.\n          basic_solver 42.\n        + \n      - admit.\n      - admit.\n      - simpl_rels.\n        unfold RC11_Model.scb, RC11_Model.sb_neq_loc.\n        rewrite SB, HB, MO, RB.\n        repeat unionR right.\n        relsf; unionL; simpl_rels.\n        all: try (sin_rewrite RMW_SEQ_F; basic_solver).\n        all: rewrite ?SAME_LOC'.\n        all: try (arewrite (F ∩₁ Sc ⊆₁ F' ∩₁ Sc')).\n        all: try ((sin_rewrite RMW_SEQ_SB +\n                   sin_rewrite RMW_SEQ_HB +\n                   sin_rewrite RMW_SEQ_RB +\n                   sin_rewrite HB_RMW_HB_LOC +\n                   sin_rewrite HB_SEQ_RMW +\n                   sin_rewrite RMW_SEQ_MO); basic_solver 42).\n        + basic_solver 42.\n        + rewrite inclusion_minus_rel; repeat sin_rewrite SB_RMW_HB; simpl_rels;\n          rewrite sb_in_hb at 2; do 2 arewrite (hb' ⨾ hb' ⊆ hb'); basic_solver 42.\n        + rewrite inclusion_minus_rel; sin_rewrite RMW_SB_RMW; basic_solver 42.\n        + basic_solver 42.\n        + basic_solver 42.\n        + rewrite inclusion_minus_rel;\n          repeat sin_rewrite RMW_SB_RMW;\n          basic_solver 42.\n        + rewrite inclusion_minus_rel;\n          repeat sin_rewrite RMW_SB_RMW;\n          basic_solver 42.\n        + rewrite inter_inclusion.\n          sin_rewrite RMW_HB_RMW.\n          basic_solver.\n        + arewrite (hb' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹ ⨾ rmw ⨾ ⦗RMW'⦘ ⊆ hb').\n          { unfolder; ins; desf.\n            specialize (RMW_COR z0 z H2); destruct RMW_COR as (l & COR); desf.\n            specialize (COR8 y H3); desf.\n          }\n          case_refl _.\n          * admit.\n          * basic_solver 42.\n    }\n    by rewrite PSC_BASE.\n  + (* No-thin-air *)\n    do 2 red; red in NTA; rewrite SB, RF.\n    remember (rf' ⨾ ⦗set_compl RMW'⦘) as r2; remember (rf' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹) as r1'.\n    remember (sb' ⨾ ⦗RMW'⦘ ⨾ rmw⁻¹) as r2'; remember sb' as r1.\n    rewrite unionA with (r1 := r1), unionC with (r1 := r2').\n    rewrite unionA with (r1 := r2), <- unionA with (r1 := r1).\n    remember (r1 ∪ r2) as r; remember (r1' ∪ r2') as r'.\n    assert (H1: r' ⨾ r ≡ ∅₂).\n    { desf; split; [|basic_solver 42].\n      relsf; unionL; simpl_rels.\n      1,2: sin_rewrite RMW_SEQ_SB.\n      3,4: sin_rewrite RMW_SEQ_RF.\n      all: basic_solver.\n    }\n    assert (H2: r' ⨾ r' ≡ ∅₂).\n    { desf; split; [|basic_solver 42].\n      relsf; unionL; simpl_rels.\n      1,2: sin_rewrite RMW_SEQ_RF.\n      3,4: sin_rewrite RMW_SEQ_SB.\n      all: basic_solver.\n    }\n    rewrite (pathp_helper event r r' H1 H2); unionL.\n    - by desf; clear_equivs ⦗set_compl RMW'⦘.\n    - rewrite rt_begin.\n      cdes WF; cdes WF_SB; cdes WF_RF.\n      relsf; unionL; red; desf; unfolder; ins; desf.\n      1, 2: specialize (RMW_COR x z0 H4).\n      all: try specialize (RMW_COR x z2 H6); destruct RMW_COR as (l & COR); desf.\n      1, 2: apply (F_new z0).\n      all: try apply (F_new z2).\n      all: (apply RF_ACT in H0 + apply SB_ACT in H0); unfolder in H0; desf.\nAdmitted.\n\nEnd EVENTS_TO_EDGES.\n\nEnd RC11_Correspondence.\n\n", "meta": {"author": "personal-practice", "repo": "coq", "sha": "df9a5f44b57323b02ba108126569a22e98b433e2", "save_path": "github-repos/coq/personal-practice-coq", "path": "github-repos/coq/personal-practice-coq/coq-df9a5f44b57323b02ba108126569a22e98b433e2/scfix/RMW_Correspondence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.2366116374304099}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp\nRequire Import path.\nRequire Import Eqdep pred prelude idynamic ordtype pcm finmap unionmap heap coding. \nRequire Import Hgraphs Logs Wavefronts Apex Partitions.\nSet Implicit Arguments. \nUnset Strict Implicit.\nUnset Printing Implicit Defensive. \n\nSection WavefrontDimension.\n\n(* Initial graph an heap *)\nVariables (h0 : heap) (g0: graph h0).\n\n(* A collector log p will all unique entires *)\nVariables  (p : log).\n\n(* Final heap and graph for the log p with the corresponding certificate epf *)\nVariables (h : heap) (g: graph h).\nVariable (epf : executeLog g0 p = Some (ExRes g)).\n\nVariable wp : par2.\nNotation FL := (pr1 wp).\nNotation OL := (pr2 wp).\n\nDefinition all_obj_fields (e : ptr) := \n    [seq (e, f) | f <- iota 0 (size (fields g e))]. \n\nDefinition all_obj_fields_wf l :=\n    flatten [seq (all_obj_fields e.1) | e <- wavefront l].\n\n(* W_gt approximates the set of object fields behind the wavefront by\n   taking all_obj_fields of an object instead specific traced fields\n   in the wavefront.\n\n   Importantly, this is a *certified* function, as it needs to work\n   only on prefixes of p (in order to determine the size of the field\n   map for an object being processed correctly), hence the type of its\n   argument, which is not just a log, but a prefix of the main GC log\n   p, for which the expose procedure is run. *)\n\nDefinition W_gt l := \n   let wfl := [seq ef <- wavefront l         | FL ef.1] in\n   let wol := [seq ef <- all_obj_fields_wf l | OL ef.1] in\n       wfl ++ wol.\n\nLemma w_gt_approx l : \n  prefix l p -> {subset wavefront l <= W_gt l}.\nProof.\ncase=>n pf/=.\nmove=>o; rewrite /W_gt mem_cat !mem_filter.\ncase X: (FL o.1)=>//=H; first by rewrite H.\nmove: (pr_coh wp (o.1)); rewrite X=>/=->/=.\napply/flatten_mapP; exists o=>//.\napply/mapP; exists o.2; last by rewrite -surjective_pairing.\ncase: (wavefront_trace H)=>e[l1][l2][H1]H2 H3 H4.\nmove: (cat_take_drop n p); rewrite -pf=>/sym.\nrewrite H1 -catA cat_cons=>H5.\nmove: (trace_fsize epf H2 H5); rewrite H3 H4.\nby rewrite mem_iota add0n. \nQed.\n\nVariable e0 : LogEntry.\n\n(* expose_apex is sound with W_gt for *any* wavefront partition *)\n\nCorollary w_gt_expose_apex_sound : \n  {subset shouldBeMarked p g\n            <= alreadyMarked p ++ expose_apex e0 p g W_gt}.\nProof. by apply: (expose_apex_sound e0 epf w_gt_approx). Qed.\n\n(* W_gt is an underapproximation the set of object fields' values\n   behind the wavefront. Therefore, it over-approximates the set of\n   object fields ahead of the wavefront. We can show that it returns a\n   subset of all objects in the wavefront, as its OL-part only reports\n   the objects whose *all* fields were traced in the wavefront. *)\n\nDefinition W_lt l := \n   let wfl := [seq ef | ef <- wavefront l & FL ef.1] in\n   let wol := [seq ef | ef <- wavefront l & \n                        (OL ef.1) && \n                        (*  All fields of this object are in the wavefront *)\n                        all (fun e => e \\in wavefront l)\n                            (all_obj_fields_wf l)]\n   in  wfl ++ wol.\n\n\nLemma w_lt_approx l : \n  prefix l p -> {subset W_lt l <= wavefront l}.\nProof.\ncase=>n pf/=.\nmove=>o; rewrite /W_lt mem_cat/=; rewrite !mem_map// !mem_filter/=.\ncase X: (FL o.1)=>//=; last by case/andP=>_->.\nby case/orP=>//; case/andP=>_->.\nQed.\n\nEnd WavefrontDimension.\n\n", "meta": {"author": "UCL-PPLV", "repo": "GCTransformations", "sha": "c0cdfe798ee4be1d898db5ede819f57e25378f21", "save_path": "github-repos/coq/UCL-PPLV-GCTransformations", "path": "github-repos/coq/UCL-PPLV-GCTransformations/GCTransformations-c0cdfe798ee4be1d898db5ede819f57e25378f21/Coq/WavefrontDimension.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.23659438012321743}}
{"text": "(** * Build a table for the next binop at a given level *)\nRequire Import Coq.Lists.List Coq.Setoids.Setoid Coq.Classes.Morphisms.\nRequire Import Fiat.Parsers.Reachable.ParenBalanced.Core.\nRequire Import Fiat.Parsers.StringLike.Core.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Common.\n\nSet Implicit Arguments.\n\nSection specific.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char}.\n  Context {pdata : paren_balanced_hiding_dataT Char}.\n\n  Local Ltac induction_str_len str :=\n    let len := fresh \"len\" in\n    set (len := length str);\n      generalize (eq_refl : length str = len);\n      clearbody len; revert str;\n      induction len; intros str ?.\n\n  Section paren_balanced_def.\n    Definition paren_balanced'_step (ch : Char) (pbh_rest : nat -> bool) (start_level : nat)\n    : bool\n      := if is_bin_op ch\n         then pbh_rest start_level\n         else if is_open ch\n              then pbh_rest (S start_level)\n              else if is_close ch\n                   then ((Compare_dec.gt_dec start_level 0)\n                           && pbh_rest (pred start_level))%bool\n                   else pbh_rest start_level.\n\n    Global Instance paren_balanced'_step_Proper {ch}\n    : Proper ((eq ==> eq) ==> eq ==> eq) (paren_balanced'_step ch).\n    Proof.\n      unfold paren_balanced'_step.\n      repeat intro; subst.\n      unfold respectful in *.\n      edestruct Compare_dec.gt_dec; simpl;\n      repeat match goal with\n               | _ => reflexivity\n               | [ |- context[if ?e then _ else _] ] => destruct e\n               | [ H : _ |- _ ] => apply H\n             end.\n    Qed.\n\n    Definition paren_balanced' (str : String) (start_level : nat)\n    : bool\n      := fold\n           paren_balanced'_step\n           Compare_dec.zerop\n           str\n           start_level.\n\n    Lemma paren_balanced'_nil (str : String) (H : length str = 0)\n    : paren_balanced' str = Compare_dec.zerop.\n    Proof.\n      apply fold_nil; assumption.\n    Qed.\n\n    Lemma paren_balanced'_recr {HSLP : StringLikeProperties Char} (str : String)\n    : paren_balanced' str\n      = match get 0 str with\n          | Some ch => paren_balanced'_step ch (paren_balanced' (drop 1 str))\n          | None => Compare_dec.zerop\n        end.\n    Proof.\n      apply fold_recr.\n    Qed.\n\n    Global Instance paren_balanced'_Proper1 {HSLP : StringLikeProperties Char}\n    : Proper (beq ==> eq ==> eq) paren_balanced'.\n    Proof.\n      unfold paren_balanced'.\n      repeat intro; subst.\n      match goal with\n        | [ |- ?f ?x = ?g ?x ] => cut (f = g); [ let H := fresh in intro H; rewrite H; reflexivity | ]\n      end.\n      setoid_subst_rel beq.\n      reflexivity.\n    Qed.\n\n    Typeclasses Opaque paren_balanced'.\n    Opaque paren_balanced'.\n\n    (*Lemma paren_balanced'_S {HSLP : StringLikeProperties Char} (str : String) n\n    : paren_balanced' str n -> paren_balanced' str (S n).\n    Proof.\n      revert n.\n      induction_str_len str.\n      { rewrite paren_balanced'_nil by assumption; simpl.\n        reflexivity. }\n      { specialize (IHlen (drop 1 str)).\n        rewrite drop_length in IHlen.\n        repeat match goal with\n                 | [ H : ?A -> ?B |- _ ] => let H' := fresh in assert (H' : A) by omega; specialize (H H'); clear H'\n               end.\n        rewrite paren_balanced'_recr.\n        destruct (singleton_exists (take 1 str)) as [ch H''].\n        { rewrite take_length, H; reflexivity. }\n        { rewrite (proj1 (get_0 _ _) H'').\n          unfold paren_balanced'_step.\n          repeat match goal with\n                   | [ |- context[if ?e then _ else _] ] => destruct e eqn:?\n                   | _ => reflexivity\n                   | _ => solve [ eauto with nocore ]\n                   | _ => progress simpl in *\n                   | _ => setoid_rewrite Bool.andb_true_iff\n                   | _ => intro\n                   | [ H : and _ _ |- _ ] => destruct H\n                   | [ H : bool_of_sumbool ?x = true |- _ ] => destruct x\n                   | _ => progress subst\n                   | _ => congruence\n                   | [ H : ?n > 0 |- _ ] => is_var n; destruct n\n                 end. } }\n    Qed.\n\n    Lemma paren_balanced'_le {HSLP : StringLikeProperties Char} (str : String) n1 n2 (H : n1 <= n2)\n    : paren_balanced' str n1 -> paren_balanced' str n2.\n    Proof.\n      apply Minus.le_plus_minus in H.\n      revert str.\n      generalize dependent (n2 - n1).\n      intros diff ?; subst n2; revert n1.\n      induction diff; simpl.\n      { intros ?? H.\n        replace (n1 + 0) with n1 by omega.\n        assumption. }\n      { intro n1.\n        replace (n1 + S diff) with (S (n1 + diff)) by omega.\n        intros.\n        eauto using paren_balanced'_S with nocore. }\n    Qed.*)\n\n    Definition paren_balanced (str : String) := paren_balanced' str 0.\n\n    Global Instance paren_balanced_Proper1 {HSLP : StringLikeProperties Char}\n    : Proper (beq ==> eq) paren_balanced.\n    Proof.\n      repeat intro.\n      unfold paren_balanced.\n      setoid_subst_rel beq.\n      reflexivity.\n    Qed.\n\n    Lemma paren_balanced'_split {HSLP : StringLikeProperties Char}\n          (str : String) (n : nat) (level1 level2 : nat)\n          (H1 : paren_balanced' (take n str) level1)\n          (H2 : paren_balanced' (drop n str) level2)\n    : paren_balanced' str (level1 + level2).\n    Proof.\n      revert n level1 level2 H1 H2.\n      set (len := length str).\n      generalize (eq_refl : length str = len).\n      clearbody len.\n      revert str.\n      induction len as [|len IHlen].\n      { intros str Hlen ???.\n        rewrite !paren_balanced'_nil\n          by (rewrite ?drop_length, ?take_length, Hlen; destruct n; reflexivity).\n        destruct level1, level2; simpl; intros; congruence. }\n      { intros str Hlen ???.\n        specialize (IHlen (drop 1 str)).\n        specialize_by ltac:(rewrite drop_length; omega).\n        specialize (IHlen (pred n)).\n        destruct n as [|n].\n        { clear IHlen.\n          rewrite drop_0.\n          rewrite !paren_balanced'_nil\n            by (rewrite ?drop_length, ?take_length, Hlen; reflexivity).\n          destruct level1; simpl; intros; [ assumption | congruence ]. }\n        { simpl in *.\n          setoid_rewrite drop_drop in IHlen.\n          setoid_rewrite take_drop in IHlen.\n          rewrite !NPeano.Nat.add_1_r in IHlen.\n          specialize (fun H' level1 H => IHlen level1 level2 H H').\n          intros H1 H2.\n          specialize_by assumption.\n          rewrite paren_balanced'_recr in H1 |- *.\n          rewrite get_take_lt in H1 by omega.\n          destruct (get 0 str) eqn:H'.\n          { unfold paren_balanced'_step in *.\n            repeat match goal with\n                     | _ => progress simpl in *\n                     | [ |- appcontext[if ?e then _ else _] ] => destruct e eqn:?\n                     | [ IHlen : forall level : nat, _ -> _, H : is_true (paren_balanced' _ _) |- _ ]\n                       => specialize (IHlen _ H)\n                     | [ IHlen : forall level : nat, _ -> _, H : paren_balanced' _ _ = true |- _ ]\n                       => specialize (IHlen _ H)\n                     | _ => solve [ eauto with nocore ]\n                     | [ H : is_true (andb _ _) |- _ ] => apply Bool.andb_true_iff in H\n                     | _ => progress split_and\n                     | [ |- is_true (andb _ _) ] => apply Bool.andb_true_iff\n                     | _ => congruence\n                     | _ => omega\n                     | [ H : context[bool_of_sumbool ?e] |- _ ] => destruct e; simpl in H\n                     | [ |- context[bool_of_sumbool ?e] ] => destruct e; simpl\n                     | [ |- _ /\\ _ ] => split\n                     | [ H : context[pred ?x] |- _ ] => is_var x; destruct x\n                   end. }\n          { apply no_first_char_empty in H'.\n            omega. } } }\n    Qed.\n\n    Lemma paren_balanced'_split_0 {HSLP : StringLikeProperties Char}\n          (str : String) (n : nat) (level : nat)\n          (H1 : paren_balanced' (take n str) 0)\n          (H2 : paren_balanced' (drop n str) level)\n    : paren_balanced' str level.\n    Proof.\n      change level with (0 + level).\n      eapply paren_balanced'_split; eassumption.\n    Qed.\n  End paren_balanced_def.\n\n  Section paren_balanced_hiding_def.\n    Definition paren_balanced_hiding'_step (ch : Char) (pbh_rest : nat -> bool) (start_level : nat)\n    : bool\n      := if is_bin_op ch\n         then ((Compare_dec.gt_dec start_level 0)\n                 && pbh_rest start_level)%bool\n         else paren_balanced'_step ch pbh_rest start_level.\n\n    Global Instance paren_balanced_hiding'_step_Proper {ch}\n    : Proper ((eq ==> eq) ==> eq ==> eq) (paren_balanced_hiding'_step ch).\n    Proof.\n      unfold paren_balanced_hiding'_step.\n      repeat intro; subst.\n      edestruct Compare_dec.gt_dec; simpl;\n      repeat match goal with\n               | _ => reflexivity\n               | [ H : _ |- _ ] => erewrite !H; reflexivity\n             end.\n    Qed.\n\n    Definition paren_balanced_hiding' (str : String) (start_level : nat)\n    : bool\n      := fold\n           paren_balanced_hiding'_step\n           (Compare_dec.zerop)\n           str\n           start_level.\n\n    Lemma paren_balanced_hiding'_nil (str : String) (H : length str = 0)\n    : paren_balanced_hiding' str = Compare_dec.zerop.\n    Proof.\n      apply fold_nil; assumption.\n    Qed.\n\n    Lemma paren_balanced_hiding'_recr {HSLP : StringLikeProperties Char} (str : String)\n    : paren_balanced_hiding' str\n      = match get 0 str with\n          | Some ch => paren_balanced_hiding'_step ch (paren_balanced_hiding' (drop 1 str))\n          | None => Compare_dec.zerop\n        end.\n    Proof.\n      apply fold_recr.\n    Qed.\n\n    Global Instance paren_balanced_hiding'_Proper1 {HSLP : StringLikeProperties Char}\n    : Proper (beq ==> eq ==> eq) paren_balanced_hiding'.\n    Proof.\n      unfold paren_balanced_hiding'.\n      repeat intro; subst.\n      match goal with\n        | [ |- ?f ?x = ?g ?x ] => cut (f = g); [ let H := fresh in intro H; rewrite H; reflexivity | ]\n      end.\n      setoid_subst_rel beq.\n      reflexivity.\n    Qed.\n\n    Typeclasses Opaque paren_balanced_hiding'.\n    Opaque paren_balanced_hiding'.\n\n    (*Lemma paren_balanced_hiding'_S {HSLP : StringLikeProperties Char} (str : String) n\n    : paren_balanced_hiding' str n -> paren_balanced_hiding' str (S n).\n    Proof.\n      revert n.\n      induction_str_len str.\n      { rewrite paren_balanced_hiding'_nil by assumption; simpl.\n        reflexivity. }\n      { specialize (IHlen (drop 1 str)).\n        rewrite drop_length in IHlen.\n        repeat match goal with\n                 | [ H : ?A -> ?B |- _ ] => let H' := fresh in assert (H' : A) by omega; specialize (H H'); clear H'\n               end.\n        rewrite paren_balanced_hiding'_recr.\n        destruct (singleton_exists (take 1 str)) as [ch H''].\n        { rewrite take_length, H; reflexivity. }\n        { rewrite (proj1 (get_0 _ _) H'').\n          unfold paren_balanced_hiding'_step, paren_balanced'_step.\n          repeat match goal with\n                   | [ |- context[if ?e then _ else _] ] => destruct e eqn:?\n                   | _ => reflexivity\n                   | _ => solve [ eauto with nocore ]\n                   | _ => progress simpl in *\n                   | _ => setoid_rewrite Bool.andb_true_iff\n                   | _ => intro\n                   | [ H : and _ _ |- _ ] => destruct H\n                   | [ H : bool_of_sumbool (Compare_dec.gt_dec ?a ?b) = true |- _ ] => destruct (Compare_dec.gt_dec a b)\n                   | _ => congruence\n                   | [ H : ?n > 0 |- _ ] => is_var n; destruct n\n                 end. } }\n    Qed.\n\n    Lemma paren_balanced_hiding'_le {HSLP : StringLikeProperties Char} (str : String) n1 n2 (H : n1 <= n2)\n    : paren_balanced_hiding' str n1 -> paren_balanced_hiding' str n2.\n    Proof.\n      apply Minus.le_plus_minus in H.\n      revert str.\n      generalize dependent (n2 - n1).\n      intros diff ?; subst n2; revert n1.\n      induction diff; simpl.\n      { intros ?? H.\n        replace (n1 + 0) with n1 by omega.\n        assumption. }\n      { intro n1.\n        replace (n1 + S diff) with (S (n1 + diff)) by omega.\n        intros.\n        eauto using paren_balanced_hiding'_S with nocore. }\n    Qed.*)\n\n    Definition paren_balanced_hiding (str : String) := paren_balanced_hiding' str 0.\n\n    Global Instance paren_balanced_hiding_Proper1 {HSLP : StringLikeProperties Char}\n    : Proper (beq ==> eq) paren_balanced_hiding.\n    Proof.\n      repeat intro.\n      unfold paren_balanced_hiding.\n      setoid_subst_rel beq.\n      reflexivity.\n    Qed.\n\n    Lemma paren_balanced_hiding'_split {HSLP : StringLikeProperties Char}\n          (str : String) (n : nat) (level1 level2 : nat)\n          (H1 : if Compare_dec.gt_dec level2 0\n                then paren_balanced' (take n str) level1\n                else paren_balanced_hiding' (take n str) level1)\n          (H2 : paren_balanced_hiding' (drop n str) level2)\n    : paren_balanced_hiding' str (level1 + level2).\n    Proof.\n      revert n level1 level2 H1 H2.\n      set (len := length str).\n      generalize (eq_refl : length str = len).\n      clearbody len.\n      revert str.\n      induction len as [|len IHlen].\n      { intros str Hlen ???.\n        rewrite !paren_balanced_hiding'_nil\n          by (rewrite ?drop_length, ?take_length, Hlen; destruct n; reflexivity).\n        destruct level1, level2; simpl; intros; congruence. }\n      { intros str Hlen ???.\n        specialize (IHlen (drop 1 str)).\n        specialize_by ltac:(rewrite drop_length; omega).\n        specialize (IHlen (pred n)).\n        destruct n as [|n].\n        { clear IHlen.\n          rewrite drop_0.\n          rewrite ?paren_balanced_hiding'_nil, ?paren_balanced'_nil\n            by (rewrite ?drop_length, ?take_length, Hlen; reflexivity).\n          destruct level1, level2; simpl; intros; first [ assumption | congruence ]. }\n        { simpl in *.\n          setoid_rewrite drop_drop in IHlen.\n          rewrite !NPeano.Nat.add_1_r in IHlen.\n          specialize (fun H' level1 H => IHlen level1 level2 H H').\n          intros H1 H2.\n          specialize_by assumption.\n          rewrite paren_balanced_hiding'_recr in H1 |- *.\n          rewrite paren_balanced'_recr in H1.\n          rewrite !get_take_lt in H1 by omega.\n          destruct (get 0 str) eqn:H'.\n          { unfold paren_balanced_hiding'_step, paren_balanced'_step in *.\n            repeat match goal with\n                     | _ => progress simpl in *\n                     | [ |- appcontext[if ?e then _ else _] ] => destruct e eqn:?\n                     | [ IHlen : forall level : nat, is_true (?f _ _) -> _, H : is_true (?f _ _) |- _ ]\n                       => specialize (IHlen _ H)\n                     | [ IHlen : forall level : nat, is_true (?f _ _) -> _, H : ?f _ _ = true |- _ ]\n                       => specialize (IHlen _ H)\n                     | _ => solve [ eauto with nocore ]\n                     | [ H : is_true (andb _ _) |- _ ] => apply Bool.andb_true_iff in H\n                     | _ => progress split_and\n                     | [ |- is_true (andb _ _) ] => apply Bool.andb_true_iff\n                     | _ => congruence\n                     | _ => omega\n                     | [ H : context[take _ (drop _ _)] |- _ ] => setoid_rewrite take_drop in H\n                     | [ H : context[(_ + 1)%nat] |- _ ] => rewrite !NPeano.Nat.add_1_r in H\n                     | [ H : context[bool_of_sumbool ?e] |- _ ] => destruct e; simpl in H\n                     | [ H : context[match ?e with left _ => _ | right _ => _ end] |- _ ] => destruct e; simpl in H\n                     | [ |- context[bool_of_sumbool ?e] ] => destruct e; simpl\n                     | [ |- _ /\\ _ ] => split\n                     | [ H : context[pred ?x] |- _ ] => is_var x; destruct x\n                   end. }\n          { apply no_first_char_empty in H'.\n            omega. } } }\n    Qed.\n\n    Lemma paren_balanced_hiding'_split_0 {HSLP : StringLikeProperties Char}\n          (str : String) (n : nat) (level : nat)\n          (H1 : if Compare_dec.gt_dec level 0\n                then paren_balanced' (take n str) 0\n                else paren_balanced_hiding' (take n str) 0)\n          (H2 : paren_balanced_hiding' (drop n str) level)\n    : paren_balanced_hiding' str level.\n    Proof.\n      change level with (0 + level).\n      eapply paren_balanced_hiding'_split; eassumption.\n    Qed.\n  End paren_balanced_hiding_def.\n\n  Section paren_balanced_to_hiding.\n    Lemma paren_balanced_hiding_impl_paren_balanced' {HSLP : StringLikeProperties Char} n (str : String)\n    : paren_balanced_hiding' str n -> paren_balanced' str n.\n    Proof.\n      revert n.\n      induction_str_len str.\n      { rewrite paren_balanced_hiding'_nil, paren_balanced'_nil by assumption; trivial. }\n      { specialize (IHlen (drop 1 str)).\n        rewrite drop_length, <- Minus.pred_of_minus in IHlen.\n        specialize (IHlen (f_equal pred H)).\n        rewrite paren_balanced_hiding'_recr, paren_balanced'_recr.\n        edestruct get as [ch|]; trivial; [].\n        unfold paren_balanced_hiding'_step, paren_balanced'_step.\n        destruct (is_bin_op ch); try reflexivity;\n        intros [|?]; simpl;\n        destruct (is_open ch), (is_close ch);\n        eauto with nocore;\n        try (unfold is_true; intros; congruence). }\n    Qed.\n\n    Lemma paren_balanced_hiding_impl_paren_balanced {HSLP : StringLikeProperties Char} (str : String)\n    : paren_balanced_hiding str -> paren_balanced str.\n    Proof.\n      apply paren_balanced_hiding_impl_paren_balanced'.\n    Qed.\n\n    (*Lemma paren_balanced_impl_paren_balanced_hiding' {HSLP : StringLikeProperties Char} n (str : String)\n    : paren_balanced' str n -> paren_balanced_hiding' str (S n).\n    Proof.\n      revert n.\n      induction_str_len str.\n      { rewrite paren_balanced_hiding'_nil, paren_balanced'_nil by assumption; trivial. }\n      { specialize (IHlen (drop 1 str)).\n        rewrite drop_length, <- Minus.pred_of_minus in IHlen.\n        specialize (IHlen (f_equal pred H)).\n        rewrite paren_balanced_hiding'_recr, paren_balanced'_recr.\n        edestruct get as [ch|]; trivial; [].\n        unfold paren_balanced_hiding'_step, paren_balanced'_step.\n        destruct (is_bin_op ch); simpl; eauto with nocore; [].\n        intros [|?]; simpl;\n        destruct (is_open ch), (is_close ch);\n        eauto with nocore;\n        try (unfold is_true; intros; congruence). }\n    Qed.\n\n    Lemma paren_balanced_impl_paren_balanced_hiding'_lt {HSLP : StringLikeProperties Char} n n' (Hlt : n < n') (str : String)\n    : paren_balanced' str n -> paren_balanced_hiding' str n'.\n    Proof.\n      apply Minus.le_plus_minus in Hlt.\n      generalize dependent (n' - S n).\n      intros n'' ?; subst.\n      revert n.\n      induction n''.\n      { intro.\n        rewrite <- plus_n_O.\n        apply paren_balanced_impl_paren_balanced_hiding'. }\n      { simpl in *.\n        intros n H'.\n        apply paren_balanced_hiding'_S.\n        rewrite NPeano.Nat.add_succ_r; eauto with nocore. }\n    Qed.*)\n  End paren_balanced_to_hiding.\nEnd specific.\n\nGlobal Opaque paren_balanced' paren_balanced_hiding'.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_simpl_example/src/Parsers/Refinement/BinOpBrackets/ParenBalanced.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23643120734596226}}
{"text": "Require Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import STS.\nRequire Import Behavior.\nRequire Import ModSem.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import HoareDef OpenDef.\nRequire Import ProofMode.\nRequire Import Mem1.\nRequire Import AList.\n\nSet Implicit Arguments.\n\n\n\nDefinition _stkRA: URA.t := (mblock ==> (Excl.t (list val)))%ra.\nInstance stkRA: URA.t := Auth.t _stkRA.\n\nSection PROOF.\n\n  Context `{Σ: GRA.t}.\n  Context `{@GRA.inG stkRA Σ}.\n\n  Compute (URA.car (t:=_stkRA)).\n  Definition _is_stack (h: mblock) (stk: list val): _stkRA :=\n    (fun _h => if (dec _h h) then Some stk else ε)\n  .\n\n  Definition is_stack (h: mblock) (stk: list val): stkRA := Auth.white (_is_stack h stk).\n\n  Definition new_spec: fspec :=\n    (mk_simple (fun (_: unit) => (\n                    (ord_pure 0),\n                    (fun varg => (⌜varg = ([]: list val)↑⌝: iProp)%I),\n                    (fun vret => (∃ h, ⌜vret = (Vptr h 0)↑⌝ ** OwnM(is_stack h []): iProp)%I)\n    )))\n  .\n\n  Definition pop_spec: fspec :=\n    mk_simple (fun '(h, stk0) => (\n                   (ord_pure 0),\n                   (fun varg => (⌜varg = ([Vptr h 0%Z]: list val)↑⌝\n                                   ** OwnM (is_stack h stk0): iProp)%I),\n                   (fun vret =>\n                      (match stk0 with\n                       | [] => ⌜vret = (Vint (- 1))↑⌝ ** OwnM (is_stack h [])\n                       | hd :: tl => ⌜vret = hd↑⌝ ** OwnM (is_stack h tl)\n                       end: iProp)%I)\n              ))\n  .\n\n  Definition push_spec: fspec :=\n    mk_simple (fun '(h, x, stk0) => (\n                   (ord_pure 0),\n                   (fun varg => (⌜varg = ([Vptr h 0%Z; x]: list val)↑⌝\n                                   ** OwnM (is_stack h stk0): iProp)%I),\n                   (fun vret => (OwnM (is_stack h (x :: stk0)) ** ⌜vret = (Vundef)↑⌝: iProp)%I)\n              ))\n  .\n\n\n  (*** TODO: remove redundancy with Stack2 ***)\n  Notation pget := (p0 <- trigger PGet;; `p0: (gmap mblock (list val)) <- p0↓ǃ;; Ret p0) (only parsing).\n  Notation pput p0 := (trigger (PPut (p0: (gmap mblock (list val)))↑)) (only parsing).\n\n\n\n  Definition new_body: list val -> itree hEs val :=\n    fun args =>\n      _ <- (pargs [] args)?;;;\n      handle <- trigger (Choose _);;;\n      stk_mgr0 <- pget;;;\n      guarantee(stk_mgr0 !! handle = None);;;\n      let stk_mgr1 := <[handle:=[]]> stk_mgr0 in\n      _ <- pput stk_mgr1;;;\n      Ret (Vptr handle 0)\n  .\n\n  Definition pop_body: list val -> itree hEs val :=\n    fun args =>\n      handle <- (pargs [Tblk] args)?;;;\n      stk_mgr0 <- pget;;;\n      stk0 <- (stk_mgr0 !! handle)?;;;\n      match stk0 with\n      | x :: stk1 =>\n        _ <- pput (<[handle:=stk1]> stk_mgr0);;;\n        Ret x\n      | _ => Ret (Vint (- 1))\n      end\n  .\n\n  Definition push_body: list val -> itree hEs val :=\n    fun args =>\n      '(handle, x) <- (pargs [Tblk; Tuntyped] args)?;;;\n      stk_mgr0 <- pget;;;\n      stk0 <- (stk_mgr0 !! handle)?;;;\n      _ <- pput (<[handle:=(x :: stk0)]> stk_mgr0);;;\n      Ret Vundef\n  .\n\n\n  Definition StackSbtb: list (gname * kspecbody) :=\n    [(\"new\", mk_kspecbody new_spec (cfunU new_body) (fun _ => triggerNB));\n    (\"pop\",  mk_kspecbody pop_spec (cfunU pop_body) (fun _ => triggerNB));\n    (\"push\", mk_kspecbody push_spec (cfunU push_body) (fun _ => triggerNB))\n    ]\n  .\n\n  Definition StackStb: list (gname * fspec).\n    eapply (Seal.sealing \"stb\").\n    let x := constr:(List.map (map_snd (fun ksb => ksb.(ksb_fspec): fspec)) StackSbtb) in\n    let y := eval cbn in x in\n    eapply y.\n  Defined.\n\n  Definition KStackSem: KModSem.t := {|\n    KModSem.fnsems := StackSbtb;\n    KModSem.mn := \"Stack\";\n    KModSem.initial_mr := GRA.embed (@Auth.black _stkRA ε);\n    KModSem.initial_st := (∅: gmap mblock (list val))↑;\n  |}\n  .\n  Definition StackSem (stb: gname -> option fspec): ModSem.t :=\n    KModSem.transl_tgt stb KStackSem.\n\n\n\n  Definition KStack: KMod.t := {|\n    KMod.get_modsem := fun _ => KStackSem;\n    KMod.sk := [(\"new\", Sk.Gfun); (\"pop\", Sk.Gfun); (\"push\", Sk.Gfun)];\n  |}\n  .\n  Definition Stack (stb: Sk.t -> gname -> option fspec): Mod.t :=\n    KMod.transl_tgt stb KStack.\n\nEnd PROOF.\nGlobal Hint Unfold StackStb: stb.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/stack/Stack3A.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23638273791976905}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n  Copyright 2018 Luxembourg University\n  Copyright 2019 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Export Quorum.\nRequire Export Process.\n\n\nSection SM.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc : @DTimeContext }.\n  Context { pt  : @TimeConstraint dtc }.\n\n  Class SMcontext :=\n    MkSMcontext\n      {\n        (* number of faults *)\n        F : nat;\n\n        (* ++++++++ Nodes ++++++++ *)\n        num_generals : nat;\n        num_generals_non_empty : 0 < num_generals;\n        num_generals_constraint : F <= num_generals;\n\n        Gen : Set; (* same as in paper, replica 0 is commander *)\n        gen_deq : Deq Gen;\n        gens2nat : Gen -> nat_n num_generals;\n        gens_bij : bijective gens2nat;\n\n        SMtoken    : Set;\n        SMtokendeq : Deq SMtoken;\n\n        sm_value : Set;\n        sm_default_value : sm_value;\n        sm_value_deq : Deq sm_value;\n        sm_choice : list sm_value -> sm_value;\n        sm_choice_cond1 : forall v, sm_choice [v] = v;\n        sm_choice_cond2 : sm_choice [] = sm_default_value;\n        sm_choice_cond3 : forall l1 l2, eqset l1 l2 -> sm_choice l1 = sm_choice l2;\n\n        sm_initial_values : Gen -> sm_value;\n\n        SMsending_key   : Set;\n        SMreceiving_key : Set;\n      }.\n\n  Context { sm_context : SMcontext }.\n\n\n  Lemma sm_choice_diff :\n    forall l1 l2,\n      sm_choice l1 <> sm_choice l2\n      ->\n      exists v,\n        (In v l1 /\\ ~ In v l2)\n        \\/\n        (In v l2 /\\ ~ In v l1).\n  Proof.\n    introv h.\n    destruct (eqset_dec l1 l2 sm_value_deq) as [d|d].\n    { apply sm_choice_cond3 in d; rewrite d in *; tcsp. }\n    apply not_eqset_implies; auto.\n    apply sm_value_deq.\n  Qed.\n\n\n  (* ===============================================================\n     No trusted component\n     =============================================================== *)\n\n  Global Instance SM_I_IOTrustedFun : IOTrustedFun := MkIOTrustedFun (fun _ => MkIOTrusted unit unit tt).\n\n\n  Inductive General :=\n  | general (n : Gen).\n\n  Coercion general : Gen >-> General.\n\n  Definition General2Gen (g : General) : Gen :=\n    match g with\n    | general n => n\n    end.\n\n  Coercion General2Gen : General >-> Gen.\n\n  Lemma GeneralDeq : Deq General.\n  Proof.\n    introv; destruct x as [g1], y as [g2].\n    destruct (gen_deq g1 g2);[left|right]; subst; auto.\n    intro xx; inversion xx; subst; tcsp.\n  Defined.\n\n  Global Instance SM_I_Node : Node := MkNode General GeneralDeq.\n\n  Lemma general_inj : injective general.\n  Proof.\n    introv h; ginv; auto.\n  Qed.\n\n  Definition General2GenOp (g : General) : option Gen :=\n    Some (General2Gen g).\n\n  Lemma Gen2General_cond : forall n, General2GenOp (general n) = Some n.\n  Proof.\n    tcsp.\n  Qed.\n\n  Lemma General2Gen_cond : forall n m, General2GenOp m = Some n -> general n = m.\n  Proof.\n    introv h.\n    unfold General2GenOp in h; ginv; simpl; destruct m; auto.\n  Qed.\n\n  Global Instance SM_I_Quorum : Quorum_context :=\n    MkQuorumContext\n      Gen\n      num_generals\n      gen_deq\n      gens2nat\n      gens_bij\n      _\n      _\n      Gen2General_cond\n      General2Gen_cond\n      general_inj.\n\n  Definition SMtokens := list SMtoken.\n\n  Global Instance SM_I_AuthTok : AuthTok :=\n    MkAuthTok\n      SMtoken\n      SMtokendeq.\n\n\n  (* 0 is less than F+2 *)\n  Definition nat_n_Fp2_0 : nat_n num_generals.\n  Proof.\n    exists 0.\n    apply leb_correct.\n    apply num_generals_non_empty.\n  Defined.\n\n  Definition general0 : Gen := bij_inv gens_bij nat_n_Fp2_0.\n\n  Definition nat2gen (n : nat) : Gen.\n  Proof.\n    destruct gens_bij as [f a b].\n    destruct (lt_dec n num_generals) as [d|d].\n    - exact (f (mk_nat_n d)).\n    - exact general0.\n  Defined.\n\n  Definition SMcommander : Gen := nat2gen 0.\n\n  Definition is_commander (g : Gen) : bool :=\n    if gen_deq g SMcommander then true else false.\n\n  Definition is_lieutenant (g : Gen) : bool := negb (is_commander g).\n\n  Lemma is_commander_false :\n    forall n, is_commander n = false <-> n <> SMcommander.\n  Proof.\n    introv.\n    unfold is_commander.\n    dest_cases w; split; intro h; tcsp.\n  Qed.\n\n  Lemma is_commander_true :\n    forall n, is_commander n = true <-> n = SMcommander.\n  Proof.\n    introv.\n    unfold is_commander.\n    dest_cases w; split; intro h; tcsp.\n  Qed.\n\n(*  Record sm_sign :=\n    MkSmSign\n      {\n        sm_sign_id : General;\n        sm_sign_sign : SMtokens;\n      }.*)\n\n  Definition sm_signs := list Sign.\n\n  Inductive sm_signed_msg :=\n  (* FIX: should we also add timestamps here so that we can make difference\n       between different values that commanders proposed *)\n  (* V: [sm_order] is abstract.  Is it enough to instantiate it with pairs\n       of values and a timestamp? *)\n  | sm_signed_msg_sing (v : sm_value) (a : Sign)\n  | sm_signed_msg_cons (m : sm_signed_msg) (a : Sign).\n\n  Inductive SMmsg : Type :=\n  | sm_msg_init\n  | sm_msg_alarm\n  | sm_msg_signed (v : sm_signed_msg)\n  | sm_msg_result (v : sm_value).\n\n  Global Instance SM_I_Msg : Msg := MkMsg SMmsg.\n\n  (* FIX : Is this correct? *)\n  Definition SMmsg2status (m : SMmsg) : msg_status :=\n    match m with\n    | sm_msg_init     => MSG_STATUS_INTERNAL\n    | sm_msg_alarm    => MSG_STATUS_INTERNAL\n    | sm_msg_signed _ => MSG_STATUS_PROTOCOL\n    | sm_msg_result _ => MSG_STATUS_INTERNAL (* sent to itself *)\n    end.\n\n  Global Instance SM_I_get_msg_status : MsgStatus := MkMsgStatus SMmsg2status.\n\n  Inductive sm_bare_signed_msg :=\n  | sm_bare_signed_msg_sing (v : sm_value) (a : General)\n  | sm_bare_signed_msg_cons (m : sm_signed_msg) (a : General).\n\n  Inductive SMbare_msg : Type :=\n  | sm_bare_msg_signed (v : sm_bare_signed_msg)\n  | sm_bare_msg_result (v : sm_value).\n\n  Global Instance SM_I_Data : Data := MkData SMbare_msg.\n\n  (* extraxt value and auth *)\n\n  Fixpoint sm_signed_msg2value (m : sm_signed_msg) : sm_value :=\n    match m with\n    | sm_signed_msg_sing v _ => v\n    | sm_signed_msg_cons v _ => sm_signed_msg2value v\n    end.\n\n  Definition SMmsg2value (m : SMmsg) : option sm_value :=\n    match m with\n    | sm_msg_init     => None\n    | sm_msg_alarm    => None\n    | sm_msg_signed v => Some (sm_signed_msg2value v)\n    | sm_msg_result v => Some v\n    end.\n\n  Definition sm_signed_msg2sign (m : sm_signed_msg) : Sign :=\n    match m with\n    | sm_signed_msg_sing _ a => a\n    | sm_signed_msg_cons _ a => a\n    end.\n\n  Definition sm_signed_msg2auth (m : sm_signed_msg) : SMtokens :=\n    sign_token (sm_signed_msg2sign m).\n\n  Definition sm_signed_msg2sender (m : sm_signed_msg) : Gen :=\n    sign_name (sm_signed_msg2sign m).\n\n  Fixpoint sm_signed_msg2signs (m : sm_signed_msg) : list Sign :=\n    match m with\n    | sm_signed_msg_sing _ a => [a]\n    | sm_signed_msg_cons v a => snoc (sm_signed_msg2signs v) a\n    end.\n\n  (* only the last sender *)\n  Definition SMmsg2sender (m : SMmsg) : option Gen :=\n    match m with\n    | sm_msg_init     => None\n    | sm_msg_alarm    => None\n    | sm_msg_signed v => Some (sm_signed_msg2sender v)\n    | sm_msg_result v => None\n    end.\n\n  Fixpoint sm_signed_msg2senders (m : sm_signed_msg) : list Gen :=\n    match m with\n    | sm_signed_msg_sing _ a => [(sign_name a)]\n    | sm_signed_msg_cons v a => snoc (sm_signed_msg2senders v) (sign_name a)\n    end.\n\n  (* all senders; correct order *)\n  Definition SMmsg2senders (m : SMmsg) : list Gen :=\n    match m with\n    | sm_msg_init     => []\n    | sm_msg_alarm    => []\n    | sm_msg_signed v => sm_signed_msg2senders v\n    | sm_msg_result v => []\n    end.\n\n  Fixpoint sm_signed_msg2msgs (m : sm_signed_msg) : list sm_signed_msg :=\n    match m with\n    | sm_signed_msg_sing v a => [m]\n    | sm_signed_msg_cons v a => snoc (sm_signed_msg2msgs v) m\n    end.\n\n  (* all signed messages; correct order *)\n  Fixpoint SMmsg2signed_messages (m : SMmsg) : list SMmsg :=\n    match m with\n    | sm_msg_init     => []\n    | sm_msg_alarm    => []\n    | sm_msg_signed v => map sm_msg_signed (sm_signed_msg2msgs v)\n    | sm_msg_result v => []\n    end.\n\n\n  (* only the last signature *)\n  Definition SMmsg2sign (m : SMmsg) : option SMtokens :=\n    match m with\n    | sm_msg_init     => None\n    | sm_msg_alarm    => None\n    | sm_msg_signed v => Some (sign_token (sm_signed_msg2sign v))\n    | sm_msg_result v => None\n    end.\n\n  (* all signatures; correct order *)\n  Fixpoint SMmsg2signs (m : SMmsg) : list SMtokens :=\n    match m with\n    | sm_msg_init     => []\n    | sm_msg_alarm    => []\n    | sm_msg_signed v => map sign_token (sm_signed_msg2signs v)\n    | sm_msg_result v => []\n    end.\n\n  Definition gens : list Gen := nodes.\n  Definition ngens : list name := map general gens.\n\n  Lemma gens_prop : forall (x : Gen), In x gens.\n  Proof.\n    exact nodes_prop.\n  Qed.\n  Hint Resolve gens_prop : sm.\n\n  Global Instance SM_I_Key : Key := MkKey SMsending_key SMreceiving_key.\n\n  Class SMauth :=\n    MkSMauth\n      {\n        SMcreate : data -> sending_keys -> SMtokens;\n        SMverify : data -> name -> receiving_key -> SMtoken -> bool\n      }.\n  Context { sm_auth : SMauth }.\n\n  Global Instance SM_I_AuthFun : AuthFun :=\n    MkAuthFun\n      SMcreate\n      SMverify.\n\n  Class SMinitial_keys :=\n    MkSMinitial_keys {\n        initial_keys : key_map;\n      }.\n\n  Context { sm_initial_keys : SMinitial_keys }.\n\n  (*Record value_and_senders :=\n    Build_ValueAndSenders\n      {\n        (* None means that we have no messages so far, and sm_value_default means that we received message with empty value *)\n        v         : option sm_value;\n        senders   : list Gen;\n      }.*)\n\n  Definition sm_values := list sm_value.\n\n  Record SMstate :=\n    Build_SMstate\n      {\n        (* some initial value *)\n        init          : sm_value;\n\n        (* the values we received *)\n        V             : sm_values;\n\n        (* The keys that we're holding to communicate with the other replicas *)\n        local_keys    : local_key_map;\n      }.\n\n\n  Definition SMinitial_state (g : Gen) (init : sm_value) : SMstate :=\n    Build_SMstate\n      init\n      []\n      (initial_keys (general g)).\n\n\n  (****************************************************************************************)\n\n  Definition sm_bare_signed_msg2general (m : sm_bare_signed_msg) : General :=\n    match m with\n    | sm_bare_signed_msg_sing _ a => a\n    | sm_bare_signed_msg_cons _ a => a\n    end.\n\n  Definition SMdata_auth (n : name) (m : data) : option name :=\n    match m with\n    | sm_bare_msg_signed v => Some (sm_bare_signed_msg2general v)\n    | sm_bare_msg_result v => Some n\n    end.\n\n  Global Instance SM_I_DataAuth : DataAuth := MkDataAuth SMdata_auth.\n\n  Definition sm_signed_msg2bare (m : sm_signed_msg) : sm_bare_signed_msg :=\n    match m with\n    | sm_signed_msg_sing v a => sm_bare_signed_msg_sing v (node2name (sign_name a))\n    | sm_signed_msg_cons v a => sm_bare_signed_msg_cons v (node2name (sign_name a))\n    end.\n\n  Definition sm_signed_msg2main_auth_data (m : sm_signed_msg) : AuthenticatedData :=\n    MkAuthData (sm_bare_msg_signed (sm_signed_msg2bare m)) (sm_signed_msg2auth m).\n\n  Fixpoint sm_signed_msg2list_auth_data (m : sm_signed_msg) : list AuthenticatedData :=\n    match m with\n    | sm_signed_msg_sing _ _ => [sm_signed_msg2main_auth_data m]\n    | sm_signed_msg_cons v _ =>\n      snoc (sm_signed_msg2list_auth_data v)\n           (sm_signed_msg2main_auth_data m)\n    end.\n\n  Definition SMget_contained_auth_data (m : SMmsg) : list AuthenticatedData :=\n    match m with\n    | sm_msg_init     => []\n    | sm_msg_alarm    => []\n    | sm_msg_signed v => sm_signed_msg2list_auth_data v\n    | sm_msg_result v => [] (* these are not signed *)\n    end.\n\n  Global Instance SM_I_ContainedAuthData : ContainedAuthData :=\n    MkContainedAuthData SMget_contained_auth_data.\n\n  (* Here, we check that all signatures are correct *)\n  Definition verify_signed_msg_sign (slf : Gen) (lkm : local_key_map) (m : sm_signed_msg) : bool :=\n    forallb\n      (fun a => verify_authenticated_data (general slf) a lkm)\n      (sm_signed_msg2list_auth_data m).\n\n  (*(* Here, we check that all signatures are correct *)\n  Definition verify_msg_sign (slf : Gen) (lkm : local_key_map) (m : SMmsg) : bool :=\n    forallb\n      (fun a => verify_authenticated_data (general slf) a lkm)\n      (SMget_contained_auth_data m).*)\n\n  Fixpoint sm_signed_msg2sing (m : sm_signed_msg) : sm_value * Sign :=\n    match m with\n    | sm_signed_msg_sing v a => (v, a)\n    | sm_signed_msg_cons v _ => sm_signed_msg2sing v\n    end.\n\n  (* Here, we check that the first one to sign was the commander *)\n  Definition verify_msg_commander (m : SMmsg) : bool :=\n    match m with\n    | sm_msg_init  => false\n    | sm_msg_alarm => false\n    | sm_msg_signed v =>\n      let (_,a) := sm_signed_msg2sing v in\n      is_commander (sign_name a)\n    | sm_msg_result _ => false\n    end.\n\n  (* Here, we check that the first one to sign was the commander *)\n  Definition verify_signed_msg_commander (m : sm_signed_msg) : bool :=\n    is_commander (sign_name (snd (sm_signed_msg2sing m))).\n\n  Definition is_sm_signed_msg2directly_from_commander (m : sm_signed_msg) : bool :=\n    match m with\n    | sm_signed_msg_sing v a => is_commander (sign_name a)\n    | sm_signed_msg_cons v _ => false\n    end.\n\n  Definition verify_signed_msg (slf : Gen) (lkm : local_key_map) (m : sm_signed_msg) : bool :=\n    (* all signatures have to be correct *)\n    (verify_signed_msg_sign slf lkm m)\n      (* the first signer has to be the commander *)\n      && (verify_signed_msg_commander m)\n      (* the senders have to be different from each other *)\n      && (norepeatsb gen_deq (sm_signed_msg2senders m))\n      (* the receiver should not be in the list of signers *)\n      && (not_inb gen_deq slf (sm_signed_msg2senders m)).\n\n  (*Definition verify_msg (slf : Gen) (lkm : local_key_map) (m : SMmsg) : bool :=\n    verify_msg_sign slf lkm m && verify_msg_commander m.*)\n\n(* Fixpoint verify_msg_form_list_senders_signatures\n             (signed_messages  : list SMmsg)\n             (senders          : list Gen)\n             (signatures       : list SMtokens)\n             (lkm              : local_key_map) : bool :=\n    (* here we take care of only properly structure messages *)\n    match signed_messages, senders, signatures with\n    | [] , [], [] => true\n    | m :: l_signed_messages, g :: l_senders, a :: l_signatures =>\n      if verify_authenticated_data (general g) (sm_msg_lieutenant2auth_data m g a) lkm then\n        verify_msg_form_list_senders_signatures l_signed_messages l_senders l_signatures lkm\n      else false\n    | _ , _ , _ => false (* this should never happened *)\n    end.\n\n  Definition remove_first_element {A} (l : list A) : list A :=\n    match l with\n    | [] => []\n    | h :: t => t\n    end.\n\n    Definition first_element {A} (l : list A) :  option A :=\n    match l with\n    | [] => None\n    | h :: t =>  Some h\n    end.\n\n  Definition verify_msg (lkm : local_key_map) (m : SMmsg) : bool :=\n    let value                := SMmsg2value m in\n    let list_senders         := SMmsg2senders m in\n    let list_signatures      := SMmsg2signs m in\n    let list_signed_messages := app (SMmsg2signed_messages m) [m] in\n\n  (* here we check only if the message that commander signed was correct,\n   and forward the rest to the verify_msg_form_list_senders_signatures *)\n    let c := first_element list_senders in\n    let a := first_element list_signatures in\n\n    match c, a with\n    | Some c, Some a =>\n      if verify_authenticated_data (general c) (sm_msg_commander2auth_data value c a) lkm then\n\n        (* check if all other messages are signed properly *)\n        let list_senders'    := remove_first_element list_senders in\n        let list_signatures' := remove_first_element list_signatures in\n\n        verify_msg_form_list_senders_signatures list_signed_messages list_senders' list_signatures' lkm\n\n      else false\n\n    |_,_ => false (* this should never happened *)\n    end.*)\n\n  Definition check_new_value\n             (V : sm_values (*value_and_senders*))\n             (m : sm_signed_msg) : bool :=\n    if in_dec sm_value_deq (sm_signed_msg2value m) V then false\n    else true.\n\n(*  Fixpoint check_new_value\n           (slf : Gen)\n           (V   : list value_and_senders)\n           (m   : SMmsg) : bool :=\n    match V with\n    | [] => true\n    | entry :: entries =>\n      match entry with\n      | Build_ValueAndSenders v senders =>\n        match v with\n        | None => false (* this means that message was missing the value! *)\n        | Some value => if sm_value_deq (SMmsg2value m) value then false\n                        else check_new_value slf entries m\n        end\n      end\n    end.*)\n\n(*  Fixpoint occurrences (e : sm_value) (l : list sm_value) : nat :=\n    match l with\n    | [] => 0\n    | entry :: entries =>\n      if sm_value_deq e entry then 1 + occurrences e entries\n      else occurrences e entries\n    end.*)\n\n  (* median value is return -- see pg. 391\n  Fixpoint choice_V_ (l : list value_and_senders) : (option sm_value * nat) :=\n    match l with\n    | [] => (None, 0)\n    | entry :: entries => match entry with\n                          | Build_ValueAndSenders val senders =>\n                            match val with\n                            | None => (Some sm_value_default,0) (* pg. 391 retreat is default value *)\n                            | Some v =>\n                              let (sum_val, num) := choice_V entries in\n                               , num + 1)\n\n                              (Some v, 1)\n                              (* we should have a median value here *)\n(*                              let med :=  choice_V entries *)\n                            end\n                          end\n                              end.\n   *)\n\n(*  Fixpoint all_sm_values (l : list value_and_senders) : list sm_value :=\n    match l with\n    | [] => []\n    | entry :: entries =>\n      match entry with\n      | Build_ValueAndSenders val senders =>\n        match val with\n        | None => [sm_default_value] (* pg. 391 retreat is default value *)\n        | Some v =>\n          let l' := all_sm_values entries in\n          match l' with\n          | [] => [v]\n          | _ => v :: l'\n          end\n        end\n      end\n    end.\n\n  Fixpoint number_of_diff_values (l : list value_and_senders) : nat :=\n    match l with\n    | [] => 0\n    | entry :: entries => match entry with\n                          | Build_ValueAndSenders val senders =>\n                            match val with\n                            | None => 1 (* pg. 391 retreat is default value *)\n                            | Some v => (number_of_diff_values entries) + 1\n                            end\n                          end\n    end.\n\n\n  (* median value is return -- see pg. 391 *)\n  Definition choice_V (l : list value_and_senders) : sm_value :=\n    let nb_val  := number_of_diff_values l in\n    let all_val := all_sm_values l in\n    sm_choice all_val (*nb_val*).*)\n\n\n  (* message has the form (v:0) *)\n  Definition commander_message (m : SMmsg) : bool := verify_msg_commander m.\n\n  (* message has the form (v:0:j1:...jk) *)\n  Definition commander_lieutenant (m : SMmsg) : bool := negb (verify_msg_commander m).\n\n  (* general have not received any order yet *)\n  Definition no_order_yet (V : sm_values (*value_and_senders*)) : bool := nullb V.\n\n(*  (* add value v to the V; no order received so far *)\n  Definition add_value_to_V_no_order_yet (v : sm_value) (V : sm_values) :=\n    match V with\n    | [] => [v]\n    | l => l (* this should never happened!!! *)\n    end.*)\n\n  (*Definition update_state_V (s : SMstate) (V : sm_values) : SMstate :=\n    Build_SMstate\n      (init       s)\n      V\n      (local_keys s)\n      (bp         s).*)\n\n  Definition add_to_V (s : SMstate) (v : sm_value) : SMstate :=\n    Build_SMstate\n      (init          s)\n      (v ::        V s)\n      (local_keys    s).\n\n  Definition extend_signed_msg\n             (m    : sm_signed_msg)\n             (g    : General)\n             (keys : local_key_map) : sm_signed_msg :=\n    let a := authenticate (sm_bare_msg_signed (sm_bare_signed_msg_cons m g)) keys in\n    sm_signed_msg_cons m (MkSign (General2Gen g) a).\n\n  Definition extend_msg\n             (m    : SMmsg)\n             (g    : General)\n             (keys : local_key_map) : SMmsg :=\n    match m with\n    | sm_msg_init     => m\n    | sm_msg_alarm    => m\n    | sm_msg_signed v => sm_msg_signed (extend_signed_msg v g keys)\n    | sm_msg_result v => m\n    end.\n\n  Definition send_sm_msg_commander (m : SMmsg) (n : list name) : DirectedMsg :=\n    MkDMsg m n ('0).\n\n  Definition send_sm_msg_lieutenant (m : SMmsg) (n : list name) : DirectedMsg :=\n    MkDMsg m n ('0).\n\n  Definition gens_not_in_list (l : list Gen) : list Gen :=\n    diff gen_deq l gens.\n\n  Definition names_not_in_list (l : list Gen) : list name :=\n    map general (gens_not_in_list l).\n\n  Definition broadcast2not_in_list (l : list Gen) F : DirectedMsg :=\n    F (names_not_in_list l).\n\n  Definition create_new_sm_signed_msg\n             (v    : sm_value)\n             (keys : local_key_map) : sm_signed_msg :=\n    let b := sm_bare_signed_msg_sing v (general SMcommander) in\n    let a := authenticate (sm_bare_msg_signed b) keys in\n    sm_signed_msg_sing v (MkSign (SMcommander) a).\n\n  Definition create_new_msg_commander\n             (v    : sm_value)\n             (keys : local_key_map) : SMmsg :=\n    sm_msg_signed (create_new_sm_signed_msg v keys).\n\n  Definition create_new_msg_result (v : sm_value) : SMmsg:=\n    let b := sm_bare_msg_result v in\n    sm_msg_result v.\n\n  (* FIX: the paper is not clear what lieutenants do with their decision at the end.\n      We send the final decision to ourselves. *)\n  Definition send_sm_msg_result (slf : Gen) (m : sm_value) : DirectedMsg :=\n    MkDMsg (sm_msg_result m) [general slf] ('0).\n\n\n  (* FIX: correct delay?  [F] or [F+1]? *)\n  Definition send_alarm (slf : Gen) : DirectedMsg :=\n    MkDMsg sm_msg_alarm [general slf] (pdt_mult ('(S F)) (pdt_plus mu tau)).\n\n\n  (* handler of initial message sent to commander to start it *)\n  Definition SMhandler_initial (slf : Gen) : Update SMstate unit DirectedMsgs :=\n    fun state v t =>\n      let keys   := local_keys state in\n      let V_list := V state in\n\n      if dt_eq_dec t (nat2pdt 0) then\n\n        if is_commander slf then\n          let new_msg := create_new_msg_commander (init state) keys in\n          let new_state1 := add_to_V state (init state) in\n\n          (* commander broadcasts new message to all replicas *)\n          (Some new_state1, [broadcast2not_in_list [SMcommander] (send_sm_msg_commander new_msg)])\n\n        else\n          (Some state, [send_alarm slf])\n\n      else (* initial messages are supposed to be received at time 0 *)\n        (Some state, []).\n\n\n\n  Definition message_is_on_time (m : sm_signed_msg) (t : PosDTime) : bool :=\n    let signs := sm_signed_msg2signs m in\n    if dt_le_lt_dec t (nat2pdt (length signs) * (mu + tau))%dtime then\n      (* We don't care about messages with more than F+1 signatures,\n         we're not supposed to send any: *)\n      if le_dec (length signs) (S F) then true else false\n    else false.\n\n\n  Definition SMhandler_lieutenant (slf : Gen) : Update SMstate sm_signed_msg DirectedMsgs :=\n    fun state m time =>\n      let keys := local_keys state in\n      let Vs   := V state in\n\n      if is_lieutenant slf then\n\n        if verify_signed_msg slf keys m then\n\n          if message_is_on_time m time then\n\n            (* is message of the form (v:0), i.e., commander message *)\n            if is_sm_signed_msg2directly_from_commander m then\n\n              (* lieutenant have not received any order yet *)\n              if no_order_yet Vs then\n\n                (* add value (received with msg m) to the V, assuming that general have not received any order yet *)\n                let new_state1 := add_to_V state (sm_signed_msg2value m) in\n\n                if 1 <=? F then\n\n                  (* create new message v:0:i *)\n                  let new_signed_msg := extend_signed_msg m (general slf) keys in\n                  let new_msg := sm_msg_signed new_signed_msg in\n\n                  (* we broadcast new message to all replicas that are not in the message i.e. commander in this case *)\n                  (Some new_state1, [broadcast2not_in_list [slf,SMcommander] (send_sm_msg_lieutenant new_msg)])\n\n                else\n                  (Some new_state1, [])\n\n              else (* message has the form (v:0), but lieutenant has some order already received *)\n                (Some state, [])\n\n            else (* message is not of the form (v:0), i.e., commander message\n              i.e., message has the form (v:0:j1:..:jk *)\n\n              (* if this is the value that was not received before *)\n              if check_new_value Vs m then\n\n                (* add value (received with msg m) to the V, assuming that general already received some value *)\n                let new_state1 := add_to_V state (sm_signed_msg2value m) in\n\n                (* if k < m , i.e., (if number of senders is less than number of faults) then broadcast the message *)\n                (* NOTE : F + 1 because commander is one of the senders *)\n                if length (sm_signed_msg2senders m) <=? F then\n\n                  (* create new message v:0:j1:...:jk:i *)\n                  let new_signed_msg := extend_signed_msg m (general slf) keys in\n                  let new_msg := sm_msg_signed new_signed_msg in\n\n                  let ls := sm_signed_msg2senders m in\n\n                  (* we broadcast new message to all replicas that were not in the message *)\n                  (Some new_state1, [broadcast2not_in_list (slf :: ls) (send_sm_msg_lieutenant new_msg)])\n\n                else (* number of senders is not less than number of faults,\n                  i.e., in this case lieutenant obeys the order determined with choice(V) *)\n                  (Some new_state1, [])\n\n              else (* this value was received before *)\n                (Some state, [])\n\n          else (* message is not on time *)\n            (Some state, [])\n\n        else (* message is not signed properly *)\n          (Some state, [])\n\n      else (* not a lieutenant *)\n        (Some state, []).\n\n\n  Definition SMhandler_result (slf : Gen) : Update SMstate sm_value DirectedMsgs :=\n    fun state _ _ => (Some state, []).\n\n\n  Definition SMhandler_alarm (slf : Gen) : Update SMstate unit DirectedMsgs :=\n    fun state _ t =>\n      if is_lieutenant slf then\n        if dt_le_lt_dec t (pdt_mult ('(S F)) (pdt_plus mu tau))\n        then (Some state, []) (* this shouldn't happen because the alarm was set to [(F+1)*(mu+tau)] *)\n        else\n          let choice := sm_choice (V state) in\n          (* we send the signed msg that contains choice to all other replicas *)\n(*          let new_msg := create_new_msg_result choice in *)\n          (Some state, [send_sm_msg_result slf choice])\n      else (Some state, []).\n\n\n  (*\n     NOTE:\n\n     - The init message has to be sent to the commander at time T0\n     - Alarms have to be sent to the lieutenants at time T0, and have to be\n       set as in [send_alarm].\n   *)\n  Definition SMupdate (slf : Gen) : MUpdate SMstate :=\n    fun state m =>\n      match m with\n      | sm_msg_init     => SMhandler_initial    slf state tt\n      | sm_msg_alarm    => SMhandler_alarm      slf state tt\n      | sm_msg_signed v => SMhandler_lieutenant slf state v\n      | sm_msg_result v => SMhandler_result     slf state v\n      end.\n\n  Definition SMreplicaSM (slf : Gen) : MStateMachine _ :=\n    mkSM\n      (SMupdate slf)\n      (SMinitial_state slf (sm_initial_values slf)).\n\n  Definition SMsys : MUSystem (fun n => SMstate) := SMreplicaSM.\n\n  (*Definition initial_conditions (eo : EventOrdering) :=\n    forall (e : Event) g,\n      has_correct_trace_before e (loc e)\n      -> loc e = general g\n      -> isFirst e\n      -> (time e = 0 /\\ trigger e = Some sm_msg_init).*)\n\nEnd SM.\n\n\nHint Resolve gens_prop : sm.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/SM/SM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.23633853784694356}}
{"text": "(*\nAlternative (\"big-step\") definition of run_vm + proof that it corresponds to the one in VmSemantics.v.\n\nAuthor:  Adam Petz, ampetz@ku.edu\n*)\n\nRequire Import Preamble GenStMonad MonadVM Instr VmSemantics MyStack ConcreteEvidence MonadLaws.\nRequire Import Event_system More_lists LTS Term Term_system.\nRequire Import StructTactics.\n\nRequire Import List.\nImport ListNotations.\nRequire Import Coq.Program.Tactics.\n\nLemma hfhf : forall (act1 act2:VM unit) st il,\n    (act1;;\n     (fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                act2)) st =\n    (act1;; (act2 ;;\n            (fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                       (ret tt)))) st.\nProof.\n  intros.\n  generalize dependent act1.\n  generalize dependent act2.\n  generalize dependent st.\n  induction il; intros.\n  - simpl.\n    rewrite monad_comp.\n    rewrite <- monad_right_id'.\n    reflexivity.\n  -\n    simpl.\n    rewrite IHil.\n    repeat rewrite monad_comp.\n   \n    rewrite IHil.\n    rewrite IHil.\n\n    repeat rewrite monad_comp.\n    rewrite fafa.\n\n\n    Check gasd.\n   \n\n    assert (\n      (((act1;; act2;; build_comp a);; ret tt);;\n       fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il (ret tt)) st =\n      ((act1;; act2;; build_comp a);; ret tt;; fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il (ret tt)) st).\n    {\n    rewrite hghg.\n    reflexivity.\n    }\n    rewrite H.\n    rewrite gasd.\n\n    rewrite hlhl.\n    reflexivity.\nDefined.\n\nLemma gfds: forall (act:VM unit) (st:vm_st) il,\n    (fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n               (act)) st =\n    (act ;; \n     (fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                (ret tt))) st.\nProof.\n  intros.\n  generalize dependent act.\n  generalize dependent st.\n  induction il; intros.\n  - simpl. rewrite monad_right_id'. reflexivity.\n\n  - simpl.\n    erewrite IHil.\n    rewrite <- monad_comp.\n\n    rewrite hfhf.\n    rewrite monad_comp.\n    rewrite monad_comp.\n\n    rewrite fafa.\n    reflexivity.\nDefined.\n\n(* Not provable, act1 could fail *)\n(*\nLemma fads : forall (act1:VM unit) act2 il st v o,\n    act1 st = (o, v) ->\n    fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n              (act1 ;; act2) st =\n    fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n              (act2) v.\nProof.\n  intros.\n  rewrite gfds.\n  rewrite <- monad_comp.\n  unfold ret.\n  unfold bind.\n  rewrite H.\n  break_let.\n  break_match.\n  destruct o0.\n  - simpl in *.\n    break_let.\n    invc Heqp.\n    rewrite gfds.\n    unfold ret.\n    unfold bind.\n    destruct o0.\n    + simpl.\n      break_let.\n      repeat find_inversion.\n      rewrite <- Heqp.\n      rewrite gfds.\n      destruct v1.\n      simpl.\n      cbn.\n      break_let.\n      destruct v.\n      cbn.\n      rewrite gfds.\n      unfold bind.\n      rewrite Heqp0.\n      break_let.\n      unfold bind in Heqp1.\n      congruence.\n    + congruence.\n  - repeat find_inversion.\n    break_match.\n    break_match.\n    repeat break_let.\n    repeat find_inversion.\n    rewrite gfds.\n    unfold bind.\n    rewrite Heqp0.\n    repeat break_let.\n    unfold ret in Heqp.\n    congruence.\n    + repeat find_inversion.\n      rewrite gfds.\n      unfold bind.\n      rewrite Heqp0.\n      reflexivity.\n  - break_match.\n    break_match.\n    repeat break_let.\n    repeat find_inversion.\n    rewrite gfds.\n    unfold bind.\n    rewrite Heqp0.\n    repeat break_let.\n    unfold ret in *.\n    rewrite gfds in Heqp.\n    unfold bind in Heqp.\n    repeat break_let.\n    repeat find_inversion.\n    congruence.\n    \n      \n    \n    \n      \n      \n      rewrite <- Heqp0.\n\n\n    \n    rewrite Heqp0.\n    break_let.\n    congruence.\n  - invc Heqp.\n    rewrite <- Heqp0.\n    rewrite gfds.\n    unfold ret.\n    unfold bind.\n    rewrite Heqp0.\n    reflexivity.\nDefined.\n*)\n\nLemma fads : forall (act1:VM unit) act2 il st v z,\n    act1 st = (Some z, v) ->\n    fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n              (act1 ;; act2) st =\n    fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n              (act2) v.\nProof.\n  intros.\n  rewrite gfds.\n  rewrite <- monad_comp.\n  unfold ret.\n  unfold bind.\n  rewrite H.\n  break_let.\n  break_match.\n  destruct o0.\n  - simpl in *.\n    break_let.\n    invc Heqp.\n    rewrite gfds.\n    unfold ret.\n    unfold bind.\n    rewrite Heqp0.\n    break_let.\n    congruence.\n  - invc Heqp.\n    rewrite <- Heqp0.\n    rewrite gfds.\n    unfold ret.\n    unfold bind.\n    rewrite Heqp0.\n    reflexivity.\nDefined.\n\nDefinition run_vm_fold (il:list AnnoInstr) : VM unit :=\n  fold_left (fun (a:VM unit) (b:AnnoInstr) => a ;; (build_comp b)) il (GenStMonad.ret tt).\n\nDefinition run_vm' (il:list AnnoInstr) st : vm_st :=\n  let c := run_vm_fold il in\n  execSt st c.\n\nLemma vm_fold_step : forall a il st z v,\n    run_vm_fold (a :: il) st = (Some z, v) ->\n    run_vm_fold il (run_vm_step st a) = (Some z, v).\nProof.\n  intros.\n  simpl in *.\n  cbn in *.\n  rewrite gfds in H.\n  rewrite <- monad_comp in H.\n  rewrite monad_left_id in H.\n  cbn in H.\n  unfold ret in H.\n  unfold bind in H.\n  remember (build_comp a st) as ooo.\n  destruct ooo.\n  destruct o.\n  - break_let.\n    invc H.\n\n    unfold run_vm_fold in *.\n    unfold run_vm_step in *.\n    unfold execSt in *.\n    rewrite <- Heqooo.\n    simpl.\n    rewrite <- Heqp.\n    reflexivity.\n  - inv H.\nDefined.\n\n\nLemma newLem : forall il a st z v,\n    build_comp a st = (Some z, v) ->\n    (fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n               (GenStMonad.ret tt) (snd (build_comp a st))) =\n    (fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n               (GenStMonad.ret tt;; build_comp a) st).\nProof.\n  intros.\n  remember (build_comp a st) as aaa.\n  destruct aaa.\n  destruct o.\n  + simpl.\n    cbn.\n    assert (\n        fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                  (ret tt;; build_comp a) st =\n        fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                  (build_comp a) st\n      ) as H0.\n    {\n      Check bind.\n      Print bind.\n      Check tt.\n\n      erewrite gfds.\n      rewrite <- monad_comp.\n      rewrite monad_left_id.\n      erewrite gfds.\n      reflexivity.\n    }\n        \n    rewrite H0. clear H0.\n    simpl.\n    assert (\n        fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                  (build_comp a) st =\n        fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                  (build_comp a ;; ret tt) st\n      ) as H0.\n    {\n      erewrite gfds.\n      erewrite gfds.\n      rewrite <- monad_comp.\n      Check build_comp.\n\n      rewrite gasd.\n      reflexivity.\n    }\n        \n    rewrite H0.\n    clear H0.\n\n\n\n    (*\n    assert (build_comp a st = (None, v0)).\n    admit.\n    clear Heqaaa.\n    unfold bind.\n    unfold ret.\n    rewrite gfds.\n    cbn.\n    break_let.\n    simpl.\n\n    destruct st.\n    simpl.\n\n    assert (\n        (fun s : vm_st =>\n     match build_comp a s with\n     | (Some _, s') => (Some tt, s')\n     | (None, s') => (None, s')\n     end)\n    {|\n    st_ev := st_ev;\n    st_stack := st_stack;\n    st_trace := st_trace;\n    st_pl := st_pl;\n    st_store := st_store |}\n\n\n\n        =\n    match build_comp  a {|\n    st_ev := st_ev;\n    st_stack := st_stack;\n    st_trace := st_trace;\n    st_pl := st_pl;\n    st_store := st_store |}  with\n     | (Some _, s') => (Some tt, s')\n     | (None, s') => (None, s')\n    end) as HH by auto.\n    repeat break_let.\n    destruct o1; destruct o0; find_inversion.\n    find_inversion.\n\n    clear Heqp0.\n    simpl.\n    rewrite <- Heqp.\n    rewrite gfds.\n    unfold ret.\n    unfold bind.\n    repeat break_let.\n    repeat find_inversion.\n    rewrite gfds.\n    simpl.\n    cbn.\n    unfold bind.\n    rewrite Heqp1.\n    unfold bind in Heqp.\n    unfold ret in Heqp.\n    rewrite Heqp in Heqp0.\n    repeat find_inversion.\n    rewrite <- HH.\n     *)\n    \n   \n\n\n\n\n\n\n\n    \n    \n    erewrite fads.\n    reflexivity.\n    symmetry.\n    eassumption.\n  +\n    assert (\n        fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                  (ret tt;; build_comp a) st =\n        fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                  (build_comp a) st\n      ) as H0.\n    {\n          \n      erewrite gfds.\n      rewrite <- monad_comp.\n      rewrite monad_left_id.\n      erewrite gfds.\n      reflexivity.\n    }\n\n    rewrite H0. clear H0.\n\n    assert (\n        fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                  (build_comp a) st =\n        fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                  (build_comp a ;; ret tt) st\n      ) as H0.\n    {\n      erewrite gfds.\n      erewrite gfds.\n      rewrite <- monad_comp.\n      Check build_comp.\n\n      rewrite gasd.\n      reflexivity.\n    }\n    rewrite H0.\n    clear H0.\n        \n    simpl.\n    congruence.\nDefined.\n\nLemma runa : forall a il st z v,\n    run_vm_fold (a :: il) st = (Some z, v) ->\n    exists z' v',\n    build_comp a st = (Some z', v').\nProof.\n  intros.\n  simpl in *.\n  cbn in *.\n  erewrite gfds in H.\n  rewrite <- monad_comp in H.\n  rewrite monad_left_id in H.\n  cbn in H.\n  unfold ret in H.\n  unfold bind in H.\n  remember (build_comp a st) as ooo.\n  destruct ooo.\n  destruct o.\n  - break_let.\n    invc H.\n\n    destruct u.\n    exists tt.\n    exists v0.\n    reflexivity.\n  - inv H.\nDefined.\n\nLemma fold_destruct : forall il1 il2 st st' st'' x x',\n    run_vm_fold il1 st = (Some x, st') ->\n    run_vm_fold il2 st' = (Some x', st'') ->\n    run_vm_fold (il1 ++ il2) st = (Some x', st'').\nProof.\n  induction il1; intros.\n  - simpl.\n    rewrite <- H0.\n    simpl in *.\n    unfold run_vm_fold in H.\n    cbn in H.\n    unfold ret in H.\n    invc H.\n    reflexivity.\n  -\n    cbn in *.\n    unfold run_vm_fold in IHil1.\n    rewrite gfds.\n    cbn.\n    simpl.\n    monad_unfold.\n    break_let.\n    break_match.\n    break_let.\n    break_let.\n    rewrite <- Heqp1.\n    erewrite IHil1.\n    reflexivity.\n    rewrite <- H.\n    repeat rewrite gfds in *.\n    monad_unfold.\n    break_let.\n    simpl.\n    cbn.\n    (* rewrite gfds. *)\n    monad_unfold.\n    break_let.\n    break_match.\n    break_let.\n    break_let.\n    repeat find_inversion.\n    congruence.\n    repeat find_inversion.\n    eauto.\n    (*\n    break_let.\n    congruence.\n    repeat find_inversion.\n    eauto. *)\n\n    break_let.\n    repeat find_inversion.\n    rewrite gfds in H.\n    monad_unfold.\n    repeat break_let.\n    find_inversion.\n    destruct o.\n    inv Heqp.\n    inv H.\nDefined.\n\nLemma run_vm_iff : forall il st z v,\n    (run_vm_fold il) st = (Some z, v) -> \n    run_vm il st = run_vm' il st.\nProof.\n  intros.\n  generalize dependent st.\n  generalize dependent z.\n  generalize dependent v.\n  induction il; intros.\n  - simpl.\n    unfold run_vm'. simpl.\n    unfold execSt.\n    unfold run_vm_fold. simpl. reflexivity.\n  - simpl.\n    destruct runa with (a:=a) (il:=il) (st:=st) (z:=z) (v:=v).\n    apply H.\n    destruct_conjs.\n    erewrite IHil.\n    unfold run_vm'. simpl.\n    unfold execSt.\n    unfold snd.\n    simpl.\n    unfold run_vm_fold.\n    simpl.\n    cbn.\n    unfold run_vm_step.\n    simpl.\n    cbn.\n    unfold execSt.\n    unfold snd.\n    simpl.\n    cbn.\n    expand_let_pairs.\n    expand_let_pairs.\n    expand_let_pairs.\n    unfold snd at 2.\n    cbn.\n    (*unfold GenStMonad.ret.*)\n    simpl.\n    cbn.\n    expand_let_pairs.\n    unfold snd at 1.\n    unfold snd at 2.\n    (*unfold fold_left.*)\n    unfold snd.\n    cbn.\n    simpl.\n    repeat expand_let_pairs.\n    fold (GenStMonad.ret (S:=vm_st) (A:=unit)).\n    assert (\n    (fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                   (GenStMonad.ret tt) (snd (build_comp a st))) =\n        (fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b) il\n                   (GenStMonad.ret tt;; build_comp a) st)) as H00.\n    eapply newLem.\n\n    \n    apply H1.\n\n    congruence.\n\n\n    apply vm_fold_step. eassumption.\nDefined.\n\nRequire Import MonadVMFacts.\n\nSet Nested Proofs Allowed.\n\nLemma run_vm_iff_helper : forall t t' il st n,\n    t = snd (anno t' n) ->\n    il = (instr_compiler t) ->\n    exists z v,\n      (run_vm_fold il) st = (Some z, v).\nProof.\n  intros.\n  generalize dependent H.\n  generalize dependent t'.\n  generalize dependent st.\n  generalize dependent il.\n  generalize dependent n.\n  \n  induction t; intros.\n  - simpl in *.\n    destruct a;\n      try (boom; allss; simpl in *; cbn; boom; allss).\n  -\n    cbn in *.\n    simpl in *.\n    break_let.\n    simpl in *.\n    boom; allss.\n    boom; allss.\n    simpl.\n    cbn.\n    repeat break_let.\n    monad_unfold.\n    unfold get_store_at in *.\n    monad_unfold.\n    rewrite PeanoNat.Nat.eqb_refl in *.\n    allss.\n  -\n    unfold annotated in *.\n    cbn in *.\n\n    simpl in *.\n    destruct t'; inv H;\n      try (\n          repeat break_let;\n          simpl in *;\n          inv H2).\n    edestruct IHt1 with (st:=st) (il:=instr_compiler a).\n    reflexivity.\n    symmetry.\n    rewrite Heqp.\n    simpl.\n    reflexivity.\n    destruct_conjs.\n    edestruct IHt2 with (st:=H0) (il:=instr_compiler a0).\n    reflexivity.\n    rewrite Heqp0.\n    simpl. reflexivity.\n    destruct_conjs.\n\n    repeat eexists.\n\n\n    eapply fold_destruct.\n    eauto.\n    vmsts.\n    eauto.\n  -\n    simpl in *.\n    destruct r; destruct s.\n    subst.\n    cbn.\n    Print fold_destruct.\n    Check fold_destruct.\n\n    rewrite gfds.\n    monad_unfold.\n    cbn.\n    break_let.\n    rewrite <- Heqp.\n    clear Heqp.\n    simpl in *.\n    vmsts.\n    simpl in *.\n\n    \n    rewrite gfds.\n\n\n    assert (\n        fold_left (fun (a0 : VM unit) (b : AnnoInstr) => a0;; build_comp b)\n     (instr_compiler t1 ++\n      abesr :: instr_compiler t2 ++ [ajoins (Nat.pred n1)]) \n     (ret tt) =\n        run_vm_fold\n          (instr_compiler t1 ++\n                          abesr :: instr_compiler t2 ++ [ajoins (Nat.pred n1)])\n      ) as HH.\n    {\n      reflexivity.\n    }\n    \n    rewrite HH.\n    clear HH.\n    assert (\n        (instr_compiler t1 ++\n                        abesr :: instr_compiler t2 ++ [ajoins (Nat.pred n1)]) =\n         (instr_compiler t1 ++\n                        [abesr] ++ instr_compiler t2 ++ [ajoins (Nat.pred n1)])\n      ) as HH.\n    {\n      reflexivity.\n    }\n    rewrite HH. clear HH.\n    unfold bind.\n    unfold ret.\n    repeat break_let.\n    rewrite app_assoc in Heqp.\n    rewrite app_assoc in Heqp.\n    assert (\n        (((instr_compiler t1 ++ [abesr]) ++ instr_compiler t2) ++\n            [ajoins (Nat.pred n1)]) =\n        (instr_compiler t1 ++ ([abesr] ++ (instr_compiler t2 ++\n                                                          ([ajoins (Nat.pred n1)]))))\n      ) as HH.\n    {\n      simpl.\n      repeat rewrite <- app_assoc.\n\n      reflexivity.\n    }\n    \n    rewrite HH in Heqp. clear HH.\n    destruct t'; inv H;\n    \n      try (\n          simpl in *;\n          repeat break_let;\n          simpl in *;\n          inv H).\n    \n      \n    \n    edestruct IHt1 with (st:={|\n           st_ev := splitEv s st_ev0;\n           st_stack := push_stack EvidenceC (splitEv s0 st_ev0) st_stack0;\n           st_trace := st_trace0 ++ [Term.split n st_pl0];\n           st_pl := st_pl0;\n           st_store := st_store0 |}) (il:=instr_compiler a).\n    reflexivity.\n\n    symmetry.\n    rewrite Heqp0.\n    simpl.\n    reflexivity.\n    destruct_conjs.\n    \n    vmsts.\n    \n    assert (\n        push_stack EvidenceC (splitEv s0 st_ev0) st_stack0 =\n        st_stack1) as HH.\n    {\n      Print do_stack1.\n      Print run_vm'.\n      assert (run_vm' (instr_compiler a) {|\n         st_ev := splitEv s st_ev0;\n         st_stack := push_stack EvidenceC (splitEv s0 st_ev0) st_stack0;\n         st_trace := st_trace0 ++ [Term.split n st_pl0];\n         st_pl := st_pl0;\n         st_store := st_store0 |} =\n              {| st_ev := st_ev1; st_stack := st_stack1; st_trace := st_trace1; st_pl := st_pl1; st_store := st_store1 |}).\n      {\n        simpl.\n        cbn.\n        unfold run_vm'.\n        unfold execSt.\n        rewrite H2.\n        reflexivity.\n      }\n      \n      erewrite <- run_vm_iff in H0.\n      do_stack1 a.\n      assumption.\n      eassumption.\n    }\n    subst.\n    \n    \n    unfold run_vm_fold in Heqp.\n    rewrite fold_left_app in Heqp.\n    rewrite gfds in Heqp.\n    cbn in *.\n    monad_unfold.\n    simpl in *.\n\n    vmsts.\n    simpl in *.\n    assert (\n        fold_left\n             (fun (a : VM unit) (b : AnnoInstr) (s : vm_st) =>\n              match a s with\n              | (Some _, s') => let '(b0, s'') := build_comp b s' in (b0, s'')\n              | (None, s') => (None, s')\n              end) (instr_compiler a) (fun s : vm_st => (Some tt, s))\n             {|\n             st_ev := splitEv s st_ev0;\n             st_stack := push_stack EvidenceC (splitEv s0 st_ev0) st_stack0;\n             st_trace := st_trace0 ++ [Term.split n st_pl0];\n             st_pl := st_pl0;\n             st_store := st_store0 |} =\n        run_vm_fold (instr_compiler a)\n         {|\n             st_ev := splitEv s st_ev0;\n             st_stack := push_stack EvidenceC (splitEv s0 st_ev0) st_stack0;\n             st_trace := st_trace0 ++ [Term.split n st_pl0];\n             st_pl := st_pl0;\n             st_store := st_store0 |}) as HHH.\n    {\n      reflexivity.\n    }\n    rewrite HHH in Heqp. clear HHH.\n    rewrite H2 in Heqp. clear H2.\n    repeat break_let.\n    repeat find_inversion.\n\n    rewrite fold_left_app in Heqp2.\n    cbn in *.\n    repeat break_let.\n    monad_unfold.\n    vmsts.\n    rewrite gfds in Heqp.\n    cbn in *.\n    monad_unfold.\n    repeat break_let.\n\n    repeat find_inversion.\n    vmsts.\n\n    edestruct IHt2 with\n        (il:= instr_compiler a0)\n        \n        (st:= {|\n            st_ev := splitEv s0 st_ev0;\n            st_stack := push_stack EvidenceC st_ev1 st_stack0;\n            st_trace := st_trace1;\n            st_pl := st_pl1;\n            st_store := st_store1 |}).\n    reflexivity.\n    symmetry.\n    rewrite Heqp1.\n    simpl.\n    reflexivity.\n    destruct_conjs.\n\n    vmsts.\n    assert (\n        run_vm_fold (instr_compiler a0)\n                    {|\n            st_ev := splitEv s0 st_ev0;\n            st_stack := push_stack EvidenceC st_ev1 st_stack0;\n            st_trace := st_trace1;\n            st_pl := st_pl1;\n            st_store := st_store1 |} =\n        fold_left\n            (fun (a0 : VM unit) (b : AnnoInstr) (s : vm_st) =>\n             match a0 s with\n             | (Some _, s') => let '(b0, s'') := build_comp b s' in (b0, s'')\n             | (None, s') => (None, s')\n             end) (instr_compiler a0) (fun s : vm_st => (Some tt, s))\n            {|\n            st_ev := splitEv s0 st_ev0;\n            st_stack := push_stack EvidenceC st_ev1 st_stack0;\n            st_trace := st_trace1;\n            st_pl := st_pl1;\n            st_store := st_store1 |}) as HH.\n    {\n      reflexivity.\n    }\n      \n    rewrite <- HH in Heqp8. clear HH.\n    rewrite H0 in Heqp8.\n    assert (push_stack EvidenceC st_ev1 st_stack0 = st_stack3).\n    {\n      Print do_stack1.\n      Print run_vm'.\n      assert (run_vm' (instr_compiler a0) {|\n         st_ev := splitEv s0 st_ev0;\n         st_stack := push_stack EvidenceC st_ev1 st_stack0;\n         st_trace := st_trace1;\n         st_pl := st_pl1;\n         st_store := st_store1 |} =\n              {| st_ev := st_ev4; st_stack := st_stack3; st_trace := st_trace4; st_pl := st_pl4; st_store := st_store4 |}).\n      {\n        simpl.\n        cbn.\n        unfold run_vm'.\n        unfold execSt.\n        \n        rewrite H0.\n        reflexivity.\n      }\n      \n      erewrite <- run_vm_iff in H.\n      do_stack1 a0.\n      assumption.\n      eassumption.\n    }\n    subst.\n    clear H0.\n    repeat find_inversion.\n    repeat break_match;\n      repeat find_inversion.\n    eauto.\n\n    unfold push_stack in *.\n    unfold pop_stack in *.\n    congruence.\n\n  - (* abpar case *)\n    subst.\n    unfold run_vm_fold.\n    cbn.\n    monad_unfold.\n    destruct s; destruct r.\n    rewrite gfds.\n    monad_unfold.\n    repeat break_let.\n    subst.\n    monad_unfold.\n    break_let.\n    monad_unfold.\n    simpl in *.\n    vmsts.\n    simpl in *.\n    unfold Maps.map_set in *.\n    \n    unfold get_store_at in *.\n    unfold get in *.\n    simpl in *.\n    assert (\n\n        (st <- (fun s : vm_st => (Some s, s));;\n         match Maps.map_get (StVM.st_store st) (fst (range t1)) with\n         | Some e => ret e\n         | None => failm\n         end)\n          {|\n            st_ev := ppc (parallel_att_vm_thread (instr_compiler t1) (splitEv s st_ev2))\n                         (parallel_att_vm_thread (instr_compiler t2) (splitEv s0 st_ev2));\n            st_stack := st_stack2;\n            st_trace := (st_trace2 ++ [Term.split n0 st_pl2]) ++\n              shuffled_events (parallel_vm_events (instr_compiler t1) st_pl2)\n                (parallel_vm_events (instr_compiler t2) st_pl2);\n            st_pl := st_pl2;\n            st_store := (fst (range t2), parallel_att_vm_thread (instr_compiler t2) (splitEv s0 st_ev2))\n                          :: (fst (range t1), parallel_att_vm_thread (instr_compiler t1) (splitEv s st_ev2)) :: st_store2 |} =\n        (Some (parallel_att_vm_thread (instr_compiler t1) (splitEv s st_ev2)), {|\n            st_ev := ppc (parallel_att_vm_thread (instr_compiler t1) (splitEv s st_ev2))\n                         (parallel_att_vm_thread (instr_compiler t2) (splitEv s0 st_ev2));\n            st_stack := st_stack2;\n            st_trace := (st_trace2 ++ [Term.split n0 st_pl2]) ++\n              shuffled_events (parallel_vm_events (instr_compiler t1) st_pl2)\n                (parallel_vm_events (instr_compiler t2) st_pl2);\n            st_pl := st_pl2;\n            st_store := (fst (range t2), parallel_att_vm_thread (instr_compiler t2) (splitEv s0 st_ev2))\n                          :: (fst (range t1), parallel_att_vm_thread (instr_compiler t1) (splitEv s st_ev2)) :: st_store2 |})) as HH.\n    {\n      simpl.\n      unfold bind.\n      repeat break_let.\n      unfold StVM.st_store in Heqp5.\n\n      assert (\n          Maps.map_get\n              ((fst (range t2), parallel_att_vm_thread (instr_compiler t2) (splitEv s0 st_ev2))\n                 :: (fst (range t1), parallel_att_vm_thread (instr_compiler t1) (splitEv s st_ev2)) :: st_store2) (fst (range t1)) =\n          Some (parallel_att_vm_thread (instr_compiler t1) (splitEv s st_ev2))) as HH.\n      {\n        apply map_get_get_2.\n        invc H.\n        simpl in *.\n        clear Heqp2.\n        clear Heqp4.\n        clear Heqp3.\n        clear Heqp1.\n        clear Heqp0.\n        clear Heqp5.\n        clear Heqp.\n\n        eapply afaf.\n        eassumption.\n      }\n      \n      rewrite HH in Heqp5.\n      simpl in Heqp5.\n      unfold ret in Heqp5.\n      repeat find_inversion.\n      eauto.\n    }\n    rewrite HH in Heqp1. clear HH.\n    break_let.\n\n    assert (\n        (st <- (fun s : vm_st => (Some s, s));;\n             match Maps.map_get (StVM.st_store st) (fst (range t2)) with\n             | Some e => ret e\n             | None => failm\n             end)\n              {|\n              st_ev := ppc (parallel_att_vm_thread (instr_compiler t1) (splitEv s st_ev2))\n                         (parallel_att_vm_thread (instr_compiler t2) (splitEv s0 st_ev2));\n              st_stack := st_stack2;\n              st_trace := (st_trace2 ++ [Term.split n0 st_pl2]) ++\n                          shuffled_events (parallel_vm_events (instr_compiler t1) st_pl2)\n                            (parallel_vm_events (instr_compiler t2) st_pl2);\n              st_pl := st_pl2;\n              st_store := (fst (range t2), parallel_att_vm_thread (instr_compiler t2) (splitEv s0 st_ev2))\n                            :: (fst (range t1), parallel_att_vm_thread (instr_compiler t1) (splitEv s st_ev2)) :: st_store2 |} =\n\n\n        (Some (parallel_att_vm_thread (instr_compiler t2) (splitEv s0 st_ev2)),\n          {|\n              st_ev := ppc (parallel_att_vm_thread (instr_compiler t1) (splitEv s st_ev2))\n                         (parallel_att_vm_thread (instr_compiler t2) (splitEv s0 st_ev2));\n              st_stack := st_stack2;\n              st_trace := (st_trace2 ++ [Term.split n0 st_pl2]) ++\n                          shuffled_events (parallel_vm_events (instr_compiler t1) st_pl2)\n                            (parallel_vm_events (instr_compiler t2) st_pl2);\n              st_pl := st_pl2;\n              st_store := (fst (range t2), parallel_att_vm_thread (instr_compiler t2) (splitEv s0 st_ev2))\n                            :: (fst (range t1), parallel_att_vm_thread (instr_compiler t1) (splitEv s st_ev2)) :: st_store2 |})) as HH.\n    {\n      simpl.\n      unfold bind.\n      repeat break_let.\n      unfold StVM.st_store in Heqp4.\n\n      assert (\n          Maps.map_get\n              ((fst (range t2), parallel_att_vm_thread (instr_compiler t2) (splitEv s0 st_ev2))\n                 :: (fst (range t1), parallel_att_vm_thread (instr_compiler t1) (splitEv s st_ev2)) :: st_store2) (fst (range t2)) =\n          Some (parallel_att_vm_thread (instr_compiler t2) (splitEv s0 st_ev2))) as HH.\n      {\n        simpl.\n        Search PeanoNat.Nat.eqb.\n        rewrite PeanoNat.Nat.eqb_refl.\n        reflexivity.\n      }\n      rewrite HH in Heqp4.\n      simpl in Heqp4.\n      unfold ret in Heqp4.\n      repeat find_inversion.\n      eauto.\n    }\n    rewrite HH in Heqp2. clear HH.\n    repeat find_inversion.\n    eauto.\nDefined.\n\n(*\nLemma run_vm_iff : forall il st z v,\n    (run_vm_fold il) st = (Some z, v) -> \n    run_vm il st = run_vm' il st.\n *)\n\n(*\nLemma run_vm_iff_helper : forall t il st, \n    il = (instr_compiler t) ->\n    exists z v,\n      (run_vm_fold il) st = (Some z, v).\n*)\n\nLemma run_vm_iff_compiled : forall il st t t' n,\n    il = instr_compiler t ->\n    t = snd (anno t' n) ->\n    run_vm il st = run_vm' il st.\nProof.\n  intros.\n  edestruct run_vm_iff_helper.\n  eassumption.\n  eassumption.\n  destruct_conjs.\n  eapply run_vm_iff.\n  eassumption.\nDefined.\n\nLemma run_vm_iff_compiled_corrolary : forall il st t t',\n    il = instr_compiler t ->\n    t = annotated t' ->\n    run_vm il st = run_vm' il st.\nProof.\n  intros.\n  eapply run_vm_iff_compiled; eauto.\nDefined.\n\nLemma corr_corr : forall il st t,\n  il = instr_compiler (annotated t) ->\n  run_vm il st = run_vm' il st.\nProof.\n  intros.\n  eapply run_vm_iff_compiled_corrolary; eauto.\nDefined.\n\nTheorem vm_ordered_alt : forall t tr ev0 ev1 e e' s s' o o' t',\n    t = annotated t' -> \n    run_vm'\n      (instr_compiler t)\n      (mk_st e s [] 0 o) =\n      (mk_st e' s' tr 0 o') ->\n    prec (ev_sys t 0) ev0 ev1 ->\n    earlier tr ev0 ev1.\nProof.\n  intros.\n  eapply vm_ordered; eauto.\n  erewrite corr_corr; eauto.\n  rewrite H.\n  auto.\nDefined.\n", "meta": {"author": "ku-sldg", "repo": "copland-avm", "sha": "6c08b0e3df96a22cc675bcea309fe99ea7deca65", "save_path": "github-repos/coq/ku-sldg-copland-avm", "path": "github-repos/coq/ku-sldg-copland-avm/copland-avm-6c08b0e3df96a22cc675bcea309fe99ea7deca65/src/extra/RunAlt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23633853129793367}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import StructTact.StructTactics.\nRequire Import StructTact.Update.\n\nRequire Import Chord.Chord.\n\nRequire Import Chord.SystemReachable.\nRequire Import Chord.HandlerLemmas.\nRequire Import Chord.SystemLemmas.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nDefinition joined_for_query (q : query) :=\n  match q with\n  | Join p => false\n  | Join2 p => false\n  | _ => true\n  end.\n\n\nTheorem cur_request_matches_joined :\n  forall gst,\n    reachable_st gst ->\n    forall h st p q m,\n      sigma gst h = Some st ->\n      cur_request st = Some (p, q, m) ->\n      joined st = joined_for_query q.\nProof.\n  induction 1; intros.\n  - unfold initial_st in *.\n    find_apply_lem_hyp sigma_initial_st_start_handler; eauto.\n    subst.\n    unfold start_handler in *.\n    repeat break_match; simpl in *; try congruence.\n    find_inversion. reflexivity.\n  - invcs H0; simpl in *; eauto.\n    + update_destruct; subst; rewrite_update; simpl in *; eauto.\n      find_inversion. simpl in *. find_inversion. reflexivity.\n    + update_destruct; subst; rewrite_update; simpl in *; eauto.\n      find_inversion.\n      repeat (handler_def || handler_simpl).\n    + update_destruct; subst; rewrite_update; simpl in *; eauto.\n      find_inversion.\n      repeat (handler_def || handler_simpl).\nQed.\n\nTheorem cur_request_join_not_joined :\n  forall gst,\n    reachable_st gst ->\n    forall h st p q m,\n      sigma gst h = Some st ->\n      cur_request st = Some (p, Join q, m) ->\n      joined st = false.\nProof.\n  eauto using cur_request_matches_joined.\nQed.\n\nTheorem cur_request_join2_not_joined :\n  forall gst,\n    reachable_st gst ->\n    forall h st p q m,\n      sigma gst h = Some st ->\n      cur_request st = Some (p, Join2 q, m) ->\n      joined st = false.\nProof.\n  eauto using cur_request_matches_joined.\nQed.\n\nTheorem nodes_not_joined_have_no_successors :\n  forall gst,\n    reachable_st gst ->\n    forall h st,\n      sigma gst h = Some st ->\n      joined st = false ->\n      succ_list st = [].\nProof.\n  induction 1; intros.\n  - unfold initial_st in *.\n    find_apply_lem_hyp sigma_initial_st_start_handler; eauto.\n    subst.\n    unfold start_handler in *.\n    repeat break_match; simpl in *; congruence.\n  - invcs H0; simpl in *; eauto.\n    + update_destruct; subst; rewrite_update; simpl in *; eauto.\n      find_inversion. reflexivity.\n    + update_destruct; subst; rewrite_update; simpl in *; eauto.\n      find_inversion.\n      repeat (handler_def || handler_simpl);\n        find_eapply_lem_hyp cur_request_matches_joined; eauto;\n          simpl in *; congruence.\n    + update_destruct; subst; rewrite_update; simpl in *; eauto.\n      find_inversion.\n      repeat (handler_def || handler_simpl);\n        find_eapply_lem_hyp cur_request_matches_joined; eauto;\n          simpl in *; congruence.\n(*\nNodes do not set their successor lists until they finish joining. I don't really\nknow what invariants are needed here but they shouldn't be too complicated?\n\nDIFFICULTY: 2\nUSED: In phase one\n*)\nQed.\n", "meta": {"author": "DistributedComponents", "repo": "verdi-chord", "sha": "762fe660c648d7f2a009d2beaa5cf3b8ea4ac593", "save_path": "github-repos/coq/DistributedComponents-verdi-chord", "path": "github-repos/coq/DistributedComponents-verdi-chord/verdi-chord-762fe660c648d7f2a009d2beaa5cf3b8ea4ac593/systems/chord-props/NodesNotJoinedHaveNoSuccessors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23633853129793364}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.libglob.\n\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nLocal Open Scope logic.\n\n(*  The LG module has two global variables of its own:\n<<\nint LG_n = 3;\nstruct foo {  int initialized;  int m; } LG_foo = {0};\n>>\nFrom the client's point of view, these variables are hidden\naway in a separating conjuct of the form [LG.data n gv],\nwhere [LG.data] is the name of the abstraction,\n[n] is a client-visible parameter, and [gv] is the\nglobal-variables table.\n\nIn Coq, the LG module defines three things:\n - [LG.data], of type [globals -> mpred] (possibly with some other parameters, in this case [n:Z])\n - [initialized_globals : globals -> mpred]\n     This definition is supposed to match the extern initialized\n     global variables, as processed by CompCert clightgen,\n     for the initial state of LG's variables  [LG_n] and [LG_foo].\n - [initial],  which is a lemma showing that the extern \n      initialized global variables of the C-language LG module do \n      indeed form a legitimate initial state of the [LG.data _ gv]\n      abstraction.\n*)\n\nModule Type LG_TYPE.\n  Parameter data: Z -> globals -> mpred.\n  Parameter initialized_globals: globals -> mpred.\n  Axiom initial: forall gv, \n     initialized_globals gv |-- data 3 gv.\nEnd LG_TYPE.\n\n(* And here is an implementation of the LG module, satisfying\n   this module type. *)\n\nModule LG <: LG_TYPE. \n\n(* This is an _internal_ definition, not meant to be mentioned\n    in proofs about _clients_ of the LG module.  It describes\n    \"known to be initialized\" global LG data. *)\n  Definition data_ok (n: Z) (gv: globals) : mpred :=\n  !! (0 <= n <= Int.max_signed) &&\n  data_at Ews tint (Vint (Int.repr n)) (gv _LG_n) *\n  data_at Ews (Tstruct _foo noattr) (Vint Int.one, Vint (Int.repr n)) (gv _LG_foo).\n\n(* This is an externally visible definition, describing global\n    LG data whether initialized or not. *)\nDefinition data (n: Z) (gv: globals) : mpred :=\n  data_ok n gv || \n   (!! (n=3) && \n    data_at Ews tint (Vint (Int.repr n)) (gv _LG_n) *\n    data_at Ews (Tstruct _foo noattr) (Vint Int.zero, Vundef) (gv _LG_foo)).\n\n(*  This describes the extern global variables of the LG.c file,\n    as they would appear as processed by CompCert and Floyd. *)\nDefinition initialized_globals (gv: globals) := \n   !! (headptr (gv _LG_n)) &&\n   !! (headptr (gv _LG_foo)) &&\n   mapsto Ews tuint (offset_val 4 (gv _LG_foo))\n          (Vint (Int.repr 0)) *\n   data_at Ews tuint (Vint (Int.repr 0)) (gv _LG_foo) *\n   data_at Ews tint (Vint (Int.repr 3)) (gv _LG_n).\n\n(*  This lemma packages up the extern global variables of LG.c\n   into the client-visible [data] abstraction.  It's a bit clumsy\n   and verbose; it would be better to have better proof automation\n   support for this kind of thing. *)\nLemma initial:\n  forall gv, initialized_globals gv |-- data 3 gv.\nProof.\nintros.\nunfold initialized_globals, data.\nrewrite !data_at_tuint_tint.\nentailer!.\napply orp_right2.\ncancel.\nunfold_data_at (data_at _ (Tstruct _foo _) _ _).\nrewrite sepcon_comm.\napply sepcon_derives.\nrewrite field_at_data_at.\nsimpl.\nrewrite field_compatible_field_address\n  by auto with field_compatible.\nsimpl.  autorewrite with norm. cancel.\npose (x :=\nfield_at Ews (Tstruct _foo noattr) [\n      StructField _m] (Vint (Int.repr 0)) (gv _LG_foo)).\napply derives_trans with x; subst x.\nerewrite <- mapsto_field_at\n  by auto with field_compatible.\nsimpl.\nrewrite field_compatible_field_address\n  by auto with field_compatible.\nsimpl. cancel.\ncancel.\nQed.\n\nEnd LG.\n\n(* The [init] function is not meant to be called from clients directly.\n    Thus it can use an _internal_ abstraction, LG.data_ok,\n    in its specification. *)\nDefinition init_spec :=\n DECLARE _LG_init\n  WITH n: Z, gv: globals\n  PRE  []\n        PROP ()\n        PARAMS () GLOBALS (gv)\n        SEP(LG.data n gv)\n  POST [ tvoid ]\n         PROP()\n         RETURN ()\n         SEP (LG.data_ok n gv).\n\n(* The [bump] and [get] functions are meant to be called from\n    client modules.  *)\nDefinition bump_spec :=\n DECLARE _LG_bump\n  WITH n: Z, gv: globals\n  PRE  []\n        PROP (n < Int.max_signed)\n        PARAMS () GLOBALS (gv)\n        SEP(LG.data n gv)\n  POST [ tvoid ]\n         PROP()\n         RETURN ()\n         SEP (LG.data (n+1) gv).\n\nDefinition get_spec :=\n DECLARE _LG_get\n  WITH n: Z, gv: globals\n  PRE  []\n        PROP ()\n        PARAMS () GLOBALS (gv)\n        SEP(LG.data n gv)\n  POST [ tint ]\n         PROP()\n         RETURN (Vint (Int.repr n))\n         SEP (LG.data n gv).\n\nDefinition client_spec :=\n DECLARE _client\n  WITH n: Z, gv: globals\n  PRE  []\n        PROP (n < 1000000000)\n        PARAMS () GLOBALS (gv)\n        SEP(LG.data n gv)\n  POST [ tint ]\n         PROP()\n         RETURN (Vint (Int.repr (n+2)))\n         SEP (LG.data (n+2) gv).\n\nDefinition main_spec :=\n  DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre prog tt gv\n  POST [ tint ]  \n     PROP() \n     RETURN (Vint (Int.repr 5))\n     SEP(TT).\n  \nDefinition Gprog : funspecs :=\n    ltac:(with_library prog [\n    init_spec; bump_spec; get_spec; client_spec; main_spec]).\n\nLemma orp_if_bool:\n forall {A} {NA: NatDed A} (P Q: A),\n   orp P Q = EX b: bool, if b then P else Q.\nProof.\nintros.\napply pred_ext.\napply orp_left.\nExists true; auto.\nExists false; auto.\nIntros b.\ndestruct b.\napply orp_right1; auto.\napply orp_right2; auto.\nQed.\n\nLemma body_init:  semax_body Vprog Gprog f_LG_init init_spec.\nProof.\nstart_function.\nunfold LG.data.\nunfold LG.data_ok.\nrewrite orp_if_bool.\nIntros b; destruct b.\n*\nIntros.\nforward.\nforward_if (PROP() LOCAL() SEP(LG.data_ok n gv)).\ninv H0.\nforward.\nunfold LG.data_ok.\nentailer!.\n*\nIntros.\nforward.\nforward_if (PROP() LOCAL() SEP(LG.data_ok n gv)).\nforward.\nforward.\nunfold LG.data_ok.\nentailer!!.\nforward.\nunfold LG.data_ok.\nentailer!!.\nQed.\n\nLemma body_bump:  semax_body Vprog Gprog f_LG_bump bump_spec.\nProof.\nstart_function.\nforward_call (n,gv).\nunfold LG.data_ok.\nIntros.\nforward.\nforward.\nforward.\nforward.\nentailer!!.\nunfold LG.data.\napply orp_right1.\nunfold LG.data_ok.\nentailer!.\nQed.\n\nLemma body_get:  semax_body Vprog Gprog f_LG_get get_spec.\nProof.\nstart_function.\nforward_call (n,gv).\nunfold LG.data_ok.\nIntros.\nforward.\nforward_if False.\n*\nforward.\nunfold LG.data.\napply orp_right1.\nunfold LG.data_ok.\nentailer!!.\n*\nforward.\nforward.\nunfold LG.data.\napply orp_right1.\nunfold LG.data_ok.\nentailer!!.\n*\nIntros. contradiction.\nQed.\n\n\nLemma body_client: semax_body Vprog Gprog f_client client_spec.\nProof.\nstart_function.\nforward_call (n,gv).\nforward_call (n+1,gv).\nreplace (n+1+1) with (n+2) by lia.\nforward_call (n+2,gv).\nforward.\nQed.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nsep_apply (LG.initial gv); auto.\nforward_call (3,gv).\nforward.\nQed.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/verif_libglob.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23633853129793364}}
{"text": "(**\n       determinism & progress\n       also includes lemmas about Casting & Consistency\n*)\nRequire Import LibTactics.\nRequire Import Arith Lia.\nRequire Export KeyProperties.\n\n(***************************** casting ************************************)\n\n#[export] Hint Immediate casting_prv_value : core.\n\nLemma casting_top_normal : forall (v v': exp),\n    casting v t_top v' -> v' = e_top.\nProof.\n  intros v v' H.\n  inductions H; solve_false; auto.\nQed.\n\n\nLemma casting_toplike : forall A v1 v2 v1' v2',\n    topLike nil A -> value v1 -> value v2 -> casting v1 A v1' -> casting v2 A v2' -> v1' = v2'.\nProof with (split_unify; solve_false; auto).\n  assert (HH: forall v v', value v -> casting v t_top v' -> v' = e_top). {\n    intros.\n    inductions H0; solve_false; eauto;\n    inverts H; forwards*: IHcasting.\n  }\n  assert (HHarrow: forall v v' A1 A2, value v -> ord (t_arrow A1 A2) ->\n                   topLike nil (t_arrow A1 A2) ->\n                   casting v (t_arrow A1 A2) v' ->\n          v' = (e_anno (e_abs t_top e_top) (t_arrow A1 A2))). {\n    intros.\n    inductions H2; solve_false; eauto.\n  }\n  assert (HHforall: forall v v' A1 A2, value v -> ord (t_forall A1 A2) ->\n                   topLike nil (t_forall A1 A2) ->\n                   casting v (t_forall A1 A2) v' ->\n          v' = (e_anno (e_tabs e_top) (t_forall A1 A2))). {\n    intros.\n    inductions H2; solve_false; eauto.\n  }\n  assert (HHrcd: forall v v' l A, value v -> ord (t_rcd l A) ->\n                   topLike nil (t_rcd l A) ->\n                   casting v (t_rcd l A) v' ->\n          v' = (e_anno (e_rcd l e_top) (t_rcd l A))). {\n    intros.\n    inductions H2; solve_false; eauto.\n  }\n  intros A v1 v2 v1' v2' TL Val1 Val2 Red1 Red2.\n  gen v1' v2'.\n  proper_ind A; intros;\n  try solve [ inverts TL ].\n  - inverts TL. inverts H1.\n  - forwards*: HH Red1; forwards*: HH Val2 Red2; subst*.\n  - forwards*: HHarrow TL Red1.\n    forwards*: HHarrow TL Red2.\n    congruence.\n  - forwards*: HHforall TL Red1.\n    forwards*: HHforall TL Red2.\n    congruence.\n  - forwards*: HHrcd TL Red1.\n    forwards*: HHrcd TL Red2.\n    congruence.\n  - inverts Red1; solve_false; try solve [inverts H1; solve_false].\n    inverts Red2; solve_false; try solve [inverts H1; solve_false].\n    split_unify.\n    forwards*: IHr1 H1 H4.\n    forwards*: IHr2 H2 H5.\n    congruence.\nQed.\n\nLemma casting_sub: forall v v' A B,\n    value v -> casting v A v' -> pType v B -> TWell nil B -> algo_sub nil B A.\nProof with eauto with common.\n  introv Val Red Typ Wf. gen B.\n  induction Red; intros; try solve [ inverts Val; inverts Typ; auto_sub; eauto].\nQed.\n\n\n(**************************** consistency ************************************)\n\nLemma consistent_symm: forall v1 v2,\n    consistent v1 v2 -> consistent v2 v1.\nProof.\n  intros. induction H; auto.\n  applys* C_disjoint.\nQed.\n\nLemma consistent_refl: forall v A,\n    value v -> Typing nil nil v Inf A -> consistent v v.\nProof with auto.\n  intros v A Val Typ. gen A. induction Val;intros;auto.\n  -(* top top *)\n    apply C_disjoint with t_top t_top...\n  - inverts~ Typ.\n  - inverts~ Typ.\n  - inverts~ Typ.\n  - (*merge merge*)\n    inverts~ Typ.\n    + assert(consistent v1 v1). eauto.\n      assert(consistent v2 v2). eauto.\n      forwards:typ_value_ptype H1 Val1.\n      forwards:typ_value_ptype H4 Val2.\n      assert(consistent v1 v2). eauto.\n      assert(consistent v2 v1). eauto. auto.\n    + assert(consistent v1 v1). eauto.\n      assert(consistent v2 v2). eauto.\n      forwards: consistent_symm H8. auto.\nQed.\n\nLemma consistent_mergel: forall v1 v2 v,\n    lc_exp v1 -> lc_exp v2 -> consistent (e_merge v1 v2) v -> consistent v1 v /\\ consistent v2 v.\nProof.\n  intros v1 v2 v Lc1 Lc2 H.\n  inductions H.\n  -\n    inverts H.\n    lets* (?&?): disjoint_andl_inv H1.\n  - split; eauto.\n  - forwards (?&?): IHconsistent1; try reflexivity; auto.\n    forwards (?&?): IHconsistent2; try reflexivity; auto.\nQed.\n\nLemma consistent_merger: forall v1 v2 v,\n    lc_exp v1 -> lc_exp v2 -> consistent v (e_merge v1 v2) -> consistent v v1 /\\ consistent v v2.\nProof.\n  intros v1 v2 v Lc1 Lc2 H.\n  inductions H.\n  -\n    inverts H0.\n    lets* (?&?): disjoint_andr_inv H1.\n  - forwards (?&?): IHconsistent1; try reflexivity; auto.\n    forwards (?&?): IHconsistent2; try reflexivity; auto.\n  - split; eauto.\nQed.\n\n(***************************** determinism ************************************)\n\n\nLemma consistent_casting_no_ambiguity: forall (v1 v2 v1' v2': exp) (C: typ),\n    value v1 -> value v2 ->\n    casting v1 C v1' -> casting v2 C v2' ->\n    consistent v1 v2 -> v1' = v2'.\nProof with (solve_false; auto).\n  introv Val1 Val2 R1 R2 Cons.\n  gen v1 v2 v1' v2'. indTypSize (size_typ C).\n  lets~ [?|(?&?&?)]: ord_or_split C.\n  - inductions Cons.\n    + inverts R1; inverts R2...\n    + inverts R1; inverts R2...\n    + forwards~ S1: casting_sub R1 H.\n      forwards~ S2: casting_sub R2 H0.\n      apply disjoint_soundness in H1.\n      forwards~: H1 S1 S2.\n      forwards*: casting_toplike R1 R2.\n    + inverts Val1.\n      inverts keep R1; try solve [forwards~: casting_toplike R1 R2]; solve_false; auto.\n    + inverts Val2.\n      inverts keep R2; try solve [forwards~: casting_toplike R1 R2]; solve_false; auto.\n  - intros.\n  inverts keep R1; try solve [forwards~: casting_toplike R1 R2]; solve_false; auto.\n      inverts keep R2; try solve [forwards*: casting_toplike R1 R2]; solve_false; auto.\n        split_unify.\n        assert (HS: forall A B C, spl A B C -> size_typ B < size_typ A /\\ size_typ C < size_typ A). {\n          intros. induction H0; simpl; try lia.\n          pick fresh x. forwards~: H6 x.\n          forwards: size_typ_open_typ_wrt_typ_var C0 x.\n          forwards: size_typ_open_typ_wrt_typ_var C2 x.\n          forwards: size_typ_open_typ_wrt_typ_var B x.\n          elia.\n        }\n        lets~ (?&?): HS H.\n        forwards~: IH H1 H4. lia.\n        forwards~: IH H2 H5. lia.\n        congruence.\nQed.\n\nLemma casting_unique: forall v A B v1' v2',\n    Typing nil nil v Inf B ->\n    value v -> prevalue v -> casting v A v1' -> casting v A v2' -> v1' = v2'.\nProof with (solve_false; auto).\n  intros.\n  applys* consistent_casting_no_ambiguity.\n  applys* consistent_refl.\nQed.\n\nLemma wrapping_prevalue : forall e A u,\n    TWell nil A ->\n    wrapping e A u ->\n    prevalue u /\\\n    exists B, pType u B /\\\n    TWell nil B.\nProof.\n  intros. induction* H0.\n  forwards*: TWell_spl H0.\n  forwards*: IHwrapping1.\n  forwards*: IHwrapping2.\nQed.\n\nLemma wrapping_consistent : forall e A B C u1 u2,\n    Typing nil nil e Chk C ->\n    TWell nil A ->\n    TWell nil B ->\n    wrapping e A u1 ->\n    wrapping e B u2 ->\n    consistent u1 u2.\nProof with eauto 4.\n  introv Typ TW1 TW2 cast1 cast2.\n  forwards~ (PV1&B1&PT1&?): wrapping_prevalue cast1.\n  forwards~ (PV2&B2&PT2&?): wrapping_prevalue cast2.\n  inductions cast1.\n  - applys C_disjoint t_top...\n  - inverts PT1. inductions cast2; applys* C_disjoint.\n  - inverts PT1. inductions cast2; applys* C_disjoint.\n  - inverts PT1. inductions cast2; applys* C_disjoint.\n  - inductions cast2.\n    + applys C_disjoint B1 t_top...\n    + applys C_disjoint B1 (t_arrow A1 A2)...\n    + applys C_disjoint B1 (t_forall A1 A2)...\n    + applys C_disjoint B1 (t_rcd l A0)...\n    + applys C_anno...\n    + forwards: prevalue_merge_l_inv PV2.\n      forwards: prevalue_merge_r_inv PV2.\n      inverts PT2.\n      forwards~: IHcast2_1 H9.\n      forwards~: IHcast2_2 H11.\n  - forwards: prevalue_merge_l_inv PV1.\n    forwards: prevalue_merge_r_inv PV1.\n    inverts PT1.\n    forwards*: IHcast1_1.\nQed.\n\n\nLemma wrapping_unique : forall e A C u1 u2,\n    Typing nil nil e Chk C ->\n    wrapping e A u1 ->\n    wrapping e A u2 ->\n    u1 = u2.\nProof with eauto; solve_false.\n  introv Typ cast1 cast2. gen e u1 u2.\n  indTypSize (size_typ A).\n  inverts cast1; inverts cast2...\n  - split_unify.\n    forwards*: IH H0 H3; elia.\n    forwards*: IH H1 H4; elia.\n    congruence.\nQed.\n\n\nLtac papp_unify :=\n  repeat match goal with\n  | H: papp (e_anno (e_rcd _ _) _) (arg_la _) _ |- _ => inverts H\n  | H: papp (e_anno (e_abs _ _) _) (arg_exp _) _ |- _ => inverts H\n  | H: papp (e_anno (e_tabs _ _) _) (arg_typ _) _ |- _ => inverts H\n         end; subst.\n\n\nLtac auto_unify := try binds_unify; typing_unify; split_unify; appdist_unify; papp_unify; ptype_unify.\n\nLemma papp_unique: forall v e e1 e2 A,\n    value v -> Typing nil nil (e_app v e) Inf A ->\n    papp v (arg_exp e) e1 ->\n    papp v (arg_exp e) e2 ->\n    e1 = e2.\nProof with eauto.\n  intros v e e1 e2 A Val Typ P1 P2.\n  gen e2 A.\n  inductions P1; intros; inverts* P2.\n  - inverts Val.\n    inverts Typ.\n    forwards*: wrapping_unique H1 H9.\n    forwards* (_&?): appDist_arrow_unique H0 H8.\n    substs~.\n  - inverts Typ.\n    inverts H2.\n    + inverts H6.\n      forwards*: Typing_chk_inter_inv H7.\n      forwards*: IHP1_1.\n      forwards*: IHP1_2.\n      congruence.\n    + inverts H6.\n      forwards*: Typing_chk_inter_inv H7.\n      forwards*: IHP1_1.\n      forwards*: IHP1_2.\n      congruence.\nQed.\n\nLemma papp_unique2: forall v1 la e1 e2 A,\n    value v1 -> Typing nil nil (e_proj v1 la) Inf A -> papp v1 (arg_la la) e1 -> papp v1 (arg_la la) e2 -> e1 = e2.\nProof with eauto.\n  intros v1 la e1 e2 A Val1 Typ P1 P2. gen e2 A.\n  inductions P1; intros; inverts* P2.\n  - inverts Val1.\n    inverts Typ.\n    inverts H10.\n      inverts H9.\n      forwards*: appDist_rcd_unique H0 H6.\n      congruence.\n      forwards*: appDist_rcd_unique H0 H6.\n      congruence.\n  - inverts Typ.\n    inverts H5.\n      inversion H6;subst.\n      inverts H6.\n      forwards*: Typ_proj H5.\n      forwards*: IHP1_1 H1.\n      forwards*: Typ_proj H10.\n      forwards*: IHP1_2 H4.\n      subst*.\n\n      inversion H6;subst.\n      inverts H6.\n      forwards*: Typ_proj H9.\n      forwards*: IHP1_1 H1.\n      forwards*: Typ_proj H13.\n      forwards*: IHP1_2 H4.\n      subst*.\nQed.\n\nLemma papp_unique3: forall v1 e1 e2 A T,\n    value v1 -> Typing nil nil (e_tapp v1 T) Inf A -> papp v1 (arg_typ T) e1 -> papp v1 (arg_typ T) e2 -> e1 = e2.\nProof with eauto.\n  introv Val1 Typ P1 P2. gen e2 A.\n  inductions P1; intros; inverts* P2.\n  inverts Val1.\n  inverts Typ.\n  inverts H9.\n    forwards* (_&?): appDist_forall_unique H1 H8.\n    congruence.\n\n  inverts Typ.\n  inverts H6.\n\n    inverts H2.\n    forwards*: IHP1_1.\n    forwards*: IHP1_2.\n    congruence.\n    forwards*: IHP1_1.\n    forwards*: IHP1_2.\n    congruence.\n\n  inverts H2.\nQed.\n\n\nTheorem step_unique: forall A (e e1 e2 : exp),\n    Typing nil nil e Inf A -> step e e1 -> step e e2 -> e1 = e2.\nProof with intuition eauto.\n  introv Typ Red1.\n  gen A e2.\n  lets Red1' : Red1.\n  induction Red1;\n    introv Typ Red2.\n  - (* papp*)\n    inverts* Red2.\n    + forwards*: papp_unique H0 H5.\n    + forwards*: step_not_value H5...\n  - (* proj*)\n    inverts* Red2.\n    + forwards*: papp_unique2 H0 H5.\n    + forwards*: step_not_value H4...\n  - (* tapp*)\n    inverts* Red2.\n    + forwards*: papp_unique3 H0 H5.\n    + forwards*: step_not_value H5...\n  - (* annov*)\n    inverts* Red2.\n    + (* annov*)\n      inverts* Typ.\n      forwards* (N&Ty&S): Typing_chk2inf H8.\n      forwards*: casting_unique H1 H7.\n    + (* anno*)\n      forwards*: step_not_value H6...\n  - (* appl*)\n    inverts Red2;\n      try solve [forwards*: step_not_value Red1; intuition eauto].\n    + (* appl*)\n      inverts Typ.\n      forwards: IHRed1...\n      congruence.\n  - (* merge*)\n    inverts Typ;\n      inverts* Red2;\n      try solve [forwards*: step_not_value Red1_2; intuition eauto];\n      try solve [forwards*: step_not_value Red1_1; intuition eauto];\n      forwards*: IHRed1_1;\n      forwards*: IHRed1_2;\n      subst*...\n  - (* mergel*)\n    inverts* Red2;\n      try solve [forwards*: step_not_value H4; intuition eauto].\n    + (* mergel*)\n      inverts* Typ;\n        forwards*: IHRed1; intuition eauto;\n        congruence.\n  - (* merger*)\n    inverts* Red2;\n      try solve [forwards*: step_not_value H2; intuition eauto].\n    + (* mergel*)\n      forwards*: step_not_value H4...\n    + (* merger*)\n      inverts* Typ;\n        forwards*: IHRed1; intuition eauto;\n        congruence.\n  - (* anno*)\n    inverts* Red2;\n      inverts* Typ;\n      try solve [inverts* Red1; intuition eauto];\n      try solve [lets*: step_not_value Red1; intuition eauto].\n\n      inductions H5; solve_false.\n      forwards*: IHTyping1. congruence.\n    forwards*: IHRed1.\n    congruence.\n  - (* fix*)\n    inverts* Red2.\n  - (* rcd*)\n    inverts* Typ. inverts* Red2.\n    forwards*: step_not_value H1 Red1...\n    forwards*: IHRed1... congruence.\n  - (* proj*)\n    inverts* Typ. inverts* Red2; try solve [forwards*: step_not_value Red1; intuition eauto]. forwards*: IHRed1. congruence.\n  Unshelve.\n  1,3,5: apply nil. 1,2,3: pick_fresh x; apply x.\nQed.\n\n(***************************** progress ***************************************)\n\nLemma casting_progress: forall v A,\n    value v -> prevalue v -> Typing nil nil v Chk A -> exists v', casting v A v'.\nProof with eauto 4.\n  intros v A Val PV TypC.\n  lets* (B&Typ&Sub): Typing_chk2inf TypC. clear TypC. gen v.\n  inductions Sub; intros;\n    try solve [inverts Typ; inverts Val; exists~].\n  - inverts H0. inverts H3.\n  - inverts Typ; solve_false...\n    inverts Val; inverts H0; inverts H1.\n  - inductions Typ; inverts Val...\n    + inverts* H1; solve_false.\n    + inverts* H1; solve_false.\n    + inverts* H1; solve_false.\n    + inverts H1; eauto 4; solve_false; exists*.\n    + inverts H1; eauto 4; solve_false; exists*.\n    + inverts H1; eauto 4; solve_false; exists*.\n    + forwards* (?&?): IHTyp1.\n  - inverts Typ; inverts~ Val; inverts H2; inverts H3.\n  - inverts Typ; inverts Val...\n    + forwards* (?&?): IHSub H3.\n    + assert (topLike nil C \\/ ~topLike nil C).\n      applys toplike_decidable.\n      destruct H2.\n      inverts H2; try solve [ solve_false | exists* ].\n      exists*.\n    + assert (topLike nil C \\/ ~topLike nil C).\n      applys toplike_decidable.\n      destruct H2.\n      inverts H2; try solve [ solve_false | exists* ].\n      exists*.\n    + assert (topLike nil C \\/ ~topLike nil C).\n      applys toplike_decidable.\n      destruct H2.\n      inverts H2; try solve [ solve_false | exists* ].\n      exists*.\n    + forwards*: IHSub H6.\n  - inverts Typ; inverts Val...\n    + forwards* (?&?): IHSub H7.\n    + assert (topLike nil C \\/ ~topLike nil C).\n      applys toplike_decidable.\n      destruct H2.\n      inverts H2; try solve [ solve_false | exists* ].\n      exists*.\n    + assert (topLike nil C \\/ ~topLike nil C).\n      applys toplike_decidable.\n      destruct H2.\n      inverts H2; try solve [ solve_false | exists* ].\n      exists*.\n    + assert (topLike nil C \\/ ~topLike nil C).\n      applys toplike_decidable.\n      destruct H2.\n      inverts H2; try solve [ solve_false | exists* ].\n      exists*.\n    + forwards*: IHSub H10.\n  - assert(topLike nil (t_arrow A2 B2)\\/~topLike nil (t_arrow A2 B2)).\n    apply toplike_decidable. destruct H0.\n    exists*. inverts Typ; solve_false.\n    exists (e_anno e (t_arrow A2 B2)).\n    assert (nil ||- (t_arrow A1 B1) <: (t_arrow A2 B2)) by eauto.\n    applys Cast_anno...\n    forwards~: Typing_regular_1 H1.\n  - assert(topLike nil (t_forall B1 B2)\\/~topLike nil (t_forall B1 B2)).\n    apply toplike_decidable. destruct H2.\n    exists*. inverts Typ; solve_false.\n    exists (e_anno e (t_forall B1 B2)).\n    assert (nil ||- (t_forall A1 A2) <: (t_forall B1 B2)) by eauto.\n    applys Cast_anno...\n    forwards~: Typing_regular_1 H3.\n  - assert(topLike nil (t_rcd l B)\\/~topLike nil (t_rcd l B)).\n    apply toplike_decidable. destruct H0.\n    exists*. inverts Typ; solve_false.\n    exists (e_anno e (t_rcd l B)).\n    assert (nil ||- (t_rcd l A) <: (t_rcd l B)) by eauto.\n    applys Cast_anno...\n    forwards~: Typing_regular_1 H1.\n  - forwards* (?&?): IHSub1 Typ.\n    forwards* (?&?): IHSub2 Typ.\nQed.\n\n\nLemma casting_progress_1: forall v A' A,\n    value v ->\n    Typing nil nil v Inf A' ->\n    Typing nil nil v Chk A ->\n    exists v', casting v A v'.\nProof.\n  intros. forwards*: value_inf_prevalue.\n  applys~ casting_progress.\nQed.\n\n\nLemma wrapping_progress: forall e A B,\n    Typing nil nil e Chk A ->\n    TWell nil B ->\n    exists e', wrapping e B e'.\nProof with eauto 4 using Typing_regular_1, TWell_lc_typ.\n  intros.\n  forwards: Typing_regular_1 H.\n  forwards: TWell_lc_typ H0.\n  proper_ind B;\n  eauto 4 using Typing_regular_1;\n                try solve [ exists;\n                            constructor*;\n                            constructor*;\n                            intros contra; solve_false].\n  + inverts H0. inverts H5.\n  + assert (TL: topLike nil (t_arrow A0 B) \\/ ~topLike nil (t_arrow A0 B))\n        by applys toplike_decidable.\n      destruct TL.\n      * exists. applys EW_topArrow...\n      * exists. applys EW_anno...\n  + assert (TL: topLike nil (t_forall A0 B) \\/ ~topLike nil (t_forall A0 B))\n      by applys toplike_decidable.\n    destruct TL.\n    * exists. applys EW_topAll...\n    * exists. applys EW_anno...\n  + assert (TL: topLike nil (t_rcd l A0) \\/ ~topLike nil (t_rcd l A0))\n      by applys toplike_decidable.\n    destruct TL.\n    * exists. applys EW_topRcd...\n    * exists. applys EW_anno...\n  + forwards~ (?&?): IHr1.\n    forwards~ (?&?): IHr2.\n    exists. applys EW_and...\nQed.\n\nLemma TWell_checked_abs : forall D G A e T,\n    Typing D G (e_abs A e) Chk T ->\n    TWell D A.\nProof.\n  intros. inductions H; eauto.\nQed.\n\n\nLemma papp_progress: forall v e A,\n    value v -> Typing nil nil (e_app v e) Inf A -> exists e', papp v (arg_exp e) e'.\nProof with eauto using Typing_regular_1.\n  intros v e A Val Typ. gen A.\n  induction Val; intros.\n  - inverts Typ. inverts H1. inverts H4.\n  - inverts Typ. inverts H1. inverts H4.\n  - inverts Typ. inverts H4.\n    inverts H7.\n    inverts H6.\n    forwards: TWell_checked_abs H11.\n    forwards (e'&CE): wrapping_progress A H8...\n    forwards (e'&CE): wrapping_progress A H8...\n    forwards (e'&CE): wrapping_progress A H8...\n    forwards~: TWell_checked_abs H6.\n  - inverts Typ. inverts H3.\n  - inverts Typ. inverts H3.\n    forwards: Typing_chk_appDist H5 H6.\n    inverts H1; solve_false.\n  - inverts Typ. inverts H2.\n  - inverts Typ. inverts H3.\n    forwards: Typing_chk_appDist H5 H6.\n    inverts H1; solve_false.\n  - inverts Typ. inverts H2.\n  - inverts Typ.\n    inverts H1.\n    + inverts H4.\n      forwards: Typing_chk_inter_inv H5.\n      forwards*: IHVal1.\n      forwards*: IHVal2.\n    + inverts H4.\n      forwards: Typing_chk_inter_inv H5.\n      forwards*: IHVal1.\n      forwards*: IHVal2.\nQed.\n\n\nLemma papp_progress2: forall v1 la A,\n    value v1 -> Typing nil nil (e_proj v1 la) Inf A -> exists e, papp v1 (arg_la la) e.\nProof with eauto.\n  intros v1 la A Val1 Typ. gen A.\n  induction Val1; intros;\n    try solve [exists*].\n  - inverts Typ. inverts H3. inverts H4.\n  - inverts Typ. inverts H3. inverts H4.\n  - inverts Typ.\n    inverts H6.\n    forwards: Typing_chk_appDist H5 H7.\n    inverts H2; solve_false.\n  - inverts Typ.\n    inverts H5.\n  - inverts Typ. inverts H5.\n    forwards: Typing_chk_appDist H4 H6.\n    inverts H1; solve_false.\n  - inverts Typ. inverts H4.\n  - inverts Typ. inverts H5.\n    forwards: Typing_chk_appDist H4 H6.\n    inverts H1; solve_false.\n    exists*.\n  - inverts Typ. inverts H4.\n  - inverts Typ.\n    inverts H3; inverts H4...\n    + lets*: Typ_proj v1 la H3.\n      lets*: Typ_proj v2 la H8.\n      forwards* (?&?): IHVal1_1.\n      forwards* (?&?): IHVal1_2.\n    + lets*: Typ_proj v1 la H7.\n      lets*: Typ_proj v2 la H11.\n      forwards* (?&?): IHVal1_1.\n      forwards* (?&?): IHVal1_2.\nQed.\n\n\nLemma papp_progress3: forall v1 A B,\n    value v1 -> Typing nil nil (e_tapp v1 A) Inf B -> exists e, papp v1 (arg_typ A) e.\nProof with eauto.\n  introv Val1 Typ. gen B.\n  induction Val1; intros;\n  forwards Lc : Typing_regular_1 Typ;\n  inverts Lc.\n  - inverts Typ. inverts H3. inverts H6.\n  - inverts Typ. inverts H3. inverts H6.\n  - inverts Typ. inverts H6.\n    forwards: Typing_chk_appDist H8 H9.\n    inverts H2; solve_false.\n  - inverts Typ. inverts H5.\n  - inverts Typ. inverts H5.\n    exists*.\n  - inverts Typ. inverts H4.\n  - inverts Typ. inverts H5.\n    forwards: Typing_chk_appDist H7 H8.\n    inverts H1; solve_false.\n  - inverts Typ. inverts H4.\n  - inverts Typ.\n    forwards (_&?): disjoint_regular H7.\n    inverts H3; inverts H6...\n    + inversion H;subst.\n      forwards (?&?): disjoint_andr_inv B1 B2 H7.\n      constructor; inverts H...\n      forwards: Typ_tapp v1 A...\n      forwards: Typ_tapp v2 A...\n      forwards (?&?): IHVal1_1...\n      forwards (?&?): IHVal1_2...\n    + inversion H;subst.\n      forwards (?&?): disjoint_andr_inv B1 B2 H7.\n      constructor; inverts H...\n      forwards: Typ_tapp v1 A...\n      forwards: Typ_tapp v2 A...\n      forwards (?&?): IHVal1_1...\n      forwards (?&?): IHVal1_2...\nQed.\n\n\nTheorem progress : forall dir e A,\n    Typing nil nil e dir A ->\n    value e \\/ exists e', step e e'.\nProof with auto.\n  introv Typ. lets Typ': Typ.\n  inductions Typ; eauto;\n    lets Lc: Typing_regular_1 Typ'.\n  - (* var *)\n    invert H1.\n  - left...  \n  - (* app *)\n    inverts Lc.\n    right.\n    destruct~ IHTyp1 as [Val1 | [e1' Red1] ]...\n    elia.\n    + (* v1 v2 *)\n      forwards (?&?): papp_progress Val1 Typ'.\n      exists. applys Step_papp H0...\n    + exists*.\n  - left...  \n  - (* tabs *)\n    inverts Lc.\n    right.\n    destruct~ IHTyp as [Val1 | [e1' Red1] ].\n    elia.\n    + forwards* (?&?): papp_progress3 Val1 Typ'.\n    + exists*.\n  - (* proj *)\n    inverts Lc.\n    right.\n    destruct~ IHTyp as [ Val1 | [t1' Red1] ].\n    elia.\n    + forwards* (?&?): papp_progress2 Val1 Typ'.\n    + exists*.\n  - left... \n  - (* merge *)\n    inverts Lc.\n    destruct~ IHTyp1 as [ Val1 | [t1' Red1] ];\n      destruct~ IHTyp2 as [ Val2 | [t2' Red2] ];\n      subst; elia.\n    + (* e_merge v1 e2 *)\n      inverts* Typ1.\n    + (* e_merge e1 v2 *)\n      inverts* Typ2.\n    + (* e_merge e1 e2 *)\n      inverts* Typ2.\n  - (* anno *)\n    inductions Typ.\n    + left...\n    + left...\n    + left...\n    + forwards~: IHTyp1.\n      forwards~: IHTyp2.\n      destruct H. inverts H; left...\n      destruct H0. inverts H0; left...\n      destruct_conj.\n      right...\n      inverts keep H; inverts keep H0; exists*.\n    + inverts Typ'.\n      forwards*: IHTyp0.\n      destruct H0.\n      forwards*: value_inf_prevalue.\n        forwards*: casting_progress H3.\n        right. destruct H0. exists (e_anno x B)...\n  - (* fixpoint *)\n    right. eauto.\n  - (* mergev *)\n    destruct~ IHTyp1 as [ Val1 | [t1' Red1] ];\n      destruct~ IHTyp2 as [ Val2 | [t2' Red2] ];\n      subst; elia.\n    + (* e_merge v1 e2 *)\n      inverts* Typ1.\n    + (* e_merge e1 v2 *)\n      inverts* Typ2.\n    + (* e_merge e1 e2 *)\n      inverts* Typ2.\nQed.\n", "meta": {"author": "andongfan", "repo": "CP-Foundations", "sha": "d3ee6c916fccd7312d0f571f7d2be66ed9336ccc", "save_path": "github-repos/coq/andongfan-CP-Foundations", "path": "github-repos/coq/andongfan-CP-Foundations/CP-Foundations-d3ee6c916fccd7312d0f571f7d2be66ed9336ccc/fiplus/coq/Progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2363385312979336}}
{"text": "\nRequire Import Axioms.\nRequire Import Tactics.\nRequire Import Sigma.\nRequire Import Relation.\nRequire Import Equality.\nRequire Import Syntax.\nRequire Import SimpSub.\nRequire Import Dynamic.\nRequire Import Ofe.\nRequire Import Spaces.\nRequire Import Uniform.\nRequire Import Urelsp.\nRequire Import Intensional.\nRequire Import Ordinal.\nRequire Import Candidate.\nRequire Import Model.\nRequire Import Ceiling.\nRequire Import Truncate.\nRequire Import Standard.\nRequire Import System.\nRequire Import Semantics.\nRequire Import ProperClosed.\nRequire Import ProperFun.\nRequire Import MapTerm.\nRequire Import Hygiene.\nRequire Import Extend.\nRequire Import ExtendTruncate.\nRequire Import SemanticsPi.\nRequire Import SemanticsEqual.\nRequire Import SemanticsAll.\nRequire Import SemanticsExist.\nRequire Import SemanticsMu.\nRequire Import SemanticsGuard.\nRequire Import SemanticsKuniv.\nRequire Import SemanticsUniv.\nRequire Import SemanticsFut.\nRequire Import SemanticsQuotient.\nRequire Import SemanticsSet.\nRequire Import SemanticsWtype.\nRequire Import SemanticsSigma.\nRequire Import SemanticsSimple.\nRequire Import SemanticsSubtype.\nRequire Import SemanticsEqtype.\nRequire Import ExtSpace.\nRequire Import PreSpacify.\nRequire Import Lattice.\n\n\nLemma interp_kext_downward :\n  forall pg i j k K,\n    j <= i\n    -> interp_kext pg i k K\n    -> interp_kext pg j k (approx j K).\nProof.\nintros pg i j k K Hji Hint.\ndestruct Hint as (Q & h & Hcl & Hsteps & Hlev & <-).\nrewrite -> approx_combine_le; auto.\nexists Q, h.\nauto.\nQed.\n\n\nLemma interp_uext_downward :\n  forall pg i j a R,\n    j <= i\n    -> interp_uext pg i a R\n    -> interp_uext pg j a (ceiling (S j) R).\nProof.\nintros pg i j a R Hji Hint.\ndestruct Hint as (w & A & h & Hcl & Hsteps & Hlev & <-).\nrewrite -> ceiling_combine_le; [| omega].\nexists w, A, h.\nauto.\nQed.\n\n\nLemma cbasic_std_ind :\n  forall system pg s i a Q,\n    cbasic system pg s i a Q\n    -> (forall j, j <= i -> cbasic system pg s j a (projc j (stdc (S j) Q)))\n    -> Q = stdc (S i) Q.\nProof.\nintros system pg s i a Q Hint IH.\nso (IH i (le_refl _)) as Hint'.\nso (cbasic_fun _#7 Hint Hint') as Heq.\nso Heq as Heq'.\nrewrite <- stdc_idem in Heq'.\nrewrite -> projc_stdc in Heq'; [| apply le_refl].\nrewrite <- Heq in Heq'.\nexact Heq'.\nQed.\n\n\nDefinition fntruncate i (A : surel) (B : urelsp A -n> siurel_ofe) \n  : urelsp (ceiling i A) -n> siurel_ofe\n  :=\n  nearrow_compose\n    (nearrow_compose (iutruncate_ne i) B)\n    (embed_ceiling_ne i A).\n\n\nLemma semantics_downward :\n  forall system,\n    (forall pg s i j a K,\n       j <= i\n       -> kbasic system pg s i a K\n       -> kbasic system pg s j a (approx j K))\n    /\\\n    (forall pg s i j a Q,\n       j <= i\n       -> cbasic system pg s i a Q\n       -> cbasic system pg s j a (projc j (stdc (S j) Q)))\n    /\\\n    (forall pg s i j a R,\n       j <= i\n       -> basic system pg s i a R\n       -> basic system pg s j a (iutruncate (S j) R))\n    /\\\n    (forall pg s i j A b B,\n       j <= i\n       -> functional system pg s i A b B\n       -> functional system pg s j (ceiling (S j) A) b (fntruncate (S j) A B)).\nProof.\nintro system.\nexploit\n  (semantics_ind system\n     (fun pg s i a K => forall j, j <= i -> kbasicv system pg s j a (approx j K))\n     (fun pg s i a Q => forall j, j <= i -> cbasicv system pg s j a (projc j (stdc (S j) Q)))\n     (fun pg s i a R => forall j, j <= i -> basicv system pg s j a (iutruncate (S j) R))\n     (fun pg s i a K => forall j, j <= i -> kbasic system pg s j a (approx j K))\n     (fun pg s i a Q => forall j, j <= i -> cbasic system pg s j a (projc j (stdc (S j) Q)))\n     (fun pg s i a R => forall j, j <= i -> basic system pg s j a (iutruncate (S j) R))\n     (fun pg s i A b B =>\n        forall j, \n          j <= i \n          -> functional system pg s j (ceiling (S j) A) b (fntruncate (S j) A B))) as Hind;\ntry (intros; \n     cbn; \n     eauto using kbasicv, cbasicv; \n     first [apply interp_cty];\n     eauto;\n     done).\n\n(* ktarrow *)\n{\nintros pg s i a k A K _ IH1 _ IH2 j Hj.\ncbn.\nrewrite <- den_iutruncate.\napply interp_ktarrow; eauto.\nrewrite <- iutruncate_extend_iurel; auto.\n}\n\n(* kfut_zero *)\n{\nintros pg s k Hcl j Hj.\nassert (j = 0) by omega; subst j.\napply interp_kfut_zero; auto.\n}\n\n(* kfut *)\n{\nintros pg s i k K _ IH j Hj.\ncbn.\ndestruct j as [| j].\n  {\n  apply interp_kfut_zero; auto.\n  exact (kbasic_closed _#6 (IH 0 (Nat.le_0_l i))).\n  }\napply interp_kfut; auto.\napply IH.\nomega.\n}\n\n(* ext *)\n{\nintros pg s i Q h Hcin j Hj.\nrewrite <- projc_stdc; [| omega].\nrewrite -> projc_combine_le; auto.\nrewrite -> stdc_combine_le; [| omega].\napply interp_ext; auto.\n}\n\n(* clam *)\n{\nintros pg s i k a K L A h HeqL Hk _ IH2 j Hj.\nrewrite -> stdc_combine_le; [| omega].\nrewrite -> projc_stdc; auto.\nunfold projc.\ncbn.\neapply (interp_clam _#9 (le_ord_trans _#3 (approx_level j K) h)); eauto using approx_idem, interp_kext_downward.\nintros j' Hj' x.\nso (IH2 j' (le_trans _#3 Hj' Hj) (transport (approx_combine_le j' j K Hj') spcar x) j' (le_refl _)) as Hint.\nforce_exact Hint; clear Hint.\nf_equal.\n  {\n  f_equal.\n  f_equal.\n  f_equal.\n  symmetry.\n  apply objsome_compat.\n  apply (expair_compat_transport _#6 (approx_combine_le j' j K Hj')).\n  cut (forall l l' x (h : l = l'),\n         transport h spcar (std (S j') l x)\n         = std (S j') l' (transport h spcar x)).\n    {\n    intro Hcond.\n    apply Hcond.\n    }\n  intros l l' y Heq.\n  subst l'.\n  reflexivity.\n  }\n\n  {\n  cbn.\n  fold (proj j L).\n  fold (embed j K).\n  change (projc j' (stdc (S j') (projc j' (stdc (S j') (expair L (pi1 A (std (S j') K (embed j' K (transport (approx_combine_le _#3 Hj') spcar x))))))))\n          =\n          projc j' (stdc (S j') (projc j (expair L (pi1 A (embed j K (std (S j') (approx j K) (embed j' (approx j K) x)))))))).\n  setoid_rewrite <- projc_stdc at 1 2; [| omega ..].\n  rewrite -> projc_idem.\n  rewrite -> projc_combine_le; auto.\n  f_equal.\n  rewrite -> stdc_idem.\n  f_equal.\n  f_equal.\n  f_equal.\n  rewrite <- embed_std; auto.\n  rewrite -> !embed_std; [| omega ..].\n  f_equal.\n  rewrite -> (embed_combine_le _#4 Hj').\n  reflexivity.\n  }\n}\n\n(* capp *)\n{\nintros pg s i a b K L A B _ IH1 Hintb IH2 j Hj.\nso (IH1 _ Hj) as H1.\nso (IH2 _ Hj) as H2.\nunfold projc, stdc in H1, H2 |- *.\ncbn in H1, H2 |- *.\nrelquest.\n  {\n  apply interp_capp; eauto.\n  }\nf_equal.\ncbn.\nrewrite -> std_arrow_is.\ncbn.\nfold (proj j L).\nfold (std (S j) L).\nfold (std (S j) K).\nfold (embed j K).\nf_equal.\napply std_collapse.\napply (pi2 A).\nso (cbasic_std_ind _ pg s i b (expair K B) Hintb IH2) as Heq.\nunfold stdc in Heq.\ncbn in Heq.\ninjectionc Heq.\nintros H.\ninjectionT H.\nintros HeqB.\nrewrite -> HeqB at 2.\neapply dist_trans.\n2:{\n  apply std_dist; omega.\n  }\napply std_nonexpansive.\neapply dist_trans.\n  {\n  apply embed_proj.\n  }\n\n  {\n  rewrite -> HeqB at 2.\n  apply std_dist.\n  omega.\n  }\n}\n\n(* ctlam *)\n{\nintros pg s i a b k K A f B Hcl Ha Hk _ IH Hf j Hj.\nunfold projc, stdc.\ncbn.\nset (l := cin pg).\nso (interp_kext_downward _#5 Hj Hk) as Hk'.\nso (interp_uext_downward _#5 Hj Ha) as Ha'.\nassert (forall j' m n,\n          rel (extend_urel l stop (ceiling (S j) A)) j' m n\n          -> j' <= j) as Hcimpl.\n  {\n  intros j' m n H.\n  destruct H.\n  omega.\n  }\nset (f' :=\n       (fun j' m n (Hmn : rel (extend_urel l stop (ceiling (S j) A)) j' m n) =>\n          (transport\n             (eqsymm (approx_combine_le _#3 (Hcimpl _ _ _ Hmn)))\n             spcar\n             (std (S j') (approx j' K) \n                (f j' m n (Hmn ander)))))).\nset (B' := (proj j (qtarrow l A K) (std (S j) (qtarrow l A K) B))).\ncbn in B'.\nexploit (interp_ctlam system pg s j a b k \n           (approx j K) (ceiling (S j) A) f' B') as H; auto.\n  {\n  clear Hf B'.\n  intros j' m n Hmn.\n  subst f'.\n  cbn.\n  destruct Hmn as (Hj'a & Hmn).\n  assert (j' <= j) as Hj' by omega.\n  so (IH j' m n Hmn j' (le_refl _)) as H.\n  unfold projc, stdc in H.\n  cbn in H.\n  force_exact H; clear H.\n  f_equal.\n  apply (expair_compat_transport _#6 (eqtrans (approx_idem _ _) (eqsymm (approx_combine_le _#3 Hj')))).\n  rewrite <- transport_compose.\n  symmetry.\n  apply (transport_symm _ spcar _ _ (approx_combine_le _#3 Hj')).\n  rewrite -> proj_near.\n  rewrite -> transport_compose.\n  match goal with\n  | |- transport ?X _ _ = _ => rewrite -> (proof_irrelevance _ X (eq_refl _))\n  end.\n  reflexivity.\n  }\n\n  {\n  clear IH.\n  intros j' m n Hmn.\n  destruct Hmn as (Hj'a & Hmn).\n  subst f' B'.\n  cbn.\n  rewrite -> std_tarrow_is.\n  cbn.\n  unfold std_tarrow_action.\n  rewrite -> urelsp_index_embed_ceiling.\n  rewrite -> urelsp_index_inj.\n  rewrite -> Nat.min_r; auto.\n  fold (std (S j') K).\n  fold (proj j K).\n  rewrite -> embed_ceiling_urelspinj.\n  rewrite -> Hf.\n  rewrite <- proj_embed_up.\n  rewrite -> embed_std; auto.\n  }\n}\n\n(* ctapp *)\n{\nintros pg s i b m l A K B n p Hnp Hm _ IH j Hj.\nso (IH j Hj) as Hint.\nunfold projc, stdc in Hint.\ncbn in Hint.\nassert (rel (ceiling (S j) A) j n p) as Hnp'.\n  {\n  split; auto.\n  eapply urel_downward_leq; eauto.\n  }\nso (interp_ctapp _#12 Hnp' Hm Hint) as H.\ncbn in H.\nunfold projc, stdc.\ncbn.\nforce_exact H; clear H.\nf_equal.\nf_equal.\ndestruct Hnp' as (Hja, Hnp').\nrewrite -> embed_ceiling_urelspinj.\nrewrite -> std_tarrow_is.\ncbn.\nunfold std_tarrow_action.\nrewrite -> urelsp_index_inj.\nrewrite -> Nat.min_id.\nfold (proj j K).\nfold (std (S j) K).\nf_equal.\napply std_collapse.\napply (pi2 B).\napply urelspinj_dist; auto.\n}\n\n(* cpair *)\n{\nintros pg s i a b K L x y _ IH1 _ IH2 j Hj.\nunfold projc, stdc.\ncbn.\napply interp_cpair; [apply IH1 | apply IH2]; auto.\n}\n\n(* cpi1 *)\n{\nintros pg s i a K L x _ IH j Hj.\nunfold projc, stdc.\ncbn.\nso (IH _ Hj) as H.\nunfold projc, stdc in H.\ncbn in H.\nexact (interp_cpi1 _#8 H).\n}\n\n(* cpi2 *)\n{\nintros pg s i a K L x _ IH j Hj.\nunfold projc, stdc.\ncbn.\nso (IH _ Hj) as H.\nunfold projc, stdc in H.\ncbn in H.\nexact (interp_cpi2 _#8 H).\n}\n\n(* cnext zero *)\n{\nintros pg s a Hcl j Hj.\nassert (j = 0) by omega; subst j.\nunfold projc, stdc.\ncbn.\napply interp_cnext_zero; auto.\n}\n\n(* cnext *)\n{\nintros pg s i a K x Hinta IH j Hj.\nunfold projc, stdc.\ndestruct j as [| j].\n  {\n  cbn.\n  apply interp_cnext_zero.\n  exact (cbasic_closed _#6 Hinta).\n  }\ncbn.\napply interp_cnext.\nrewrite -> std_fut_is.\ncbn.\napply IH.\nomega.\n}\n\n(* cprev *)\n{\nintros pg s i A k x Hinta IH j Hj.\nunfold projc, stdc.\ncbn.\napply interp_cprev.\napply IH.\nomega.\n}\n\n(* cty *)\n{\nintros pg s i a R _ IH j Hj.\nunfold projc, stdc; cbn.\napply interp_cty; auto.\nrewrite -> std_type_is.\nrewrite <- iutruncate_extend_iurel.\napply IH; auto.\n}\n\n(* ccon *)\n{\nintros pg s i lv a gpg R Hlv Hle _ IH j Hj.\nrewrite -> iutruncate_extend_iurel.\napply interp_con; auto.\napply IH; auto.\n}\n\n(* karrow_type *)\n{\nintros pg s i a b A B Ha IH1 Hb IH2 j Hj.\nrewrite -> iutruncate_iuarrow.\nrewrite -> min_r; auto.\napply interp_karrow_type; auto.\n}\n\n(* karrow_type *)\n{\nintros pg s i a b A B Ha IH1 Hb IH2 j Hj.\nrewrite -> iutruncate_iuarrow.\nrewrite -> min_r; auto.\napply interp_arrow; auto.\n}\n\n(* pi *)\n{\nintros pg s i a b A B Ha IH1 Hb IH2 j Hj.\nrewrite -> iutruncate_iupi.\nrewrite -> min_r; auto.\napply interp_pi; auto.\napply IH2; auto.\n}\n\n(* intersect *)\n{\nintros pg s i a b A B Ha IH1 Hb IH2 j Hj.\nrewrite -> iutruncate_iuintersect.\nrewrite -> min_r; auto.\napply interp_intersect; auto.\napply IH2; auto.\n}\n\n(* prod *)\n{\nintros pg s i a b A B Ha IH1 Hb IH2 j Hj.\nrewrite -> iutruncate_iuprod.\napply interp_prod; auto.\n}\n\n(* sigma *)\n{\nintros pg s i a b A B Ha IH1 Hb IH2 j Hj.\nrewrite -> iutruncate_iusigma.\napply interp_sigma; auto.\napply IH2; auto.\n}\n\n(* set *)\n{\nintros pg s i a b A B Ha IH1 Hb IH2 j Hj.\nrewrite -> iutruncate_iuset.\napply interp_set; auto.\napply IH2; auto.\n}\n\n(* quotient *)\n{\nintros pg s i a b A B hs ht Ha IH1 Hb IH2 j Hj.\nrewrite -> iutruncate_iuquotient.\napply interp_quotient; auto.\nforce_exact (IH2 _ Hj).\napply functional_rewrite.\napply (eq_impl_eq_dep _#6 (ceiling_prod _#4)).\napply nearrow_extensionality.\nintros C.\ncbn.\nrewrite -> (pi1_transport_dep_lift _ _ (fun A B => @nonexpansive (urelsp A) (wiurel_ofe stop) B) _ _ (ceiling_prod j stop (den A) (den A))).\nrewrite -> app_transport_dom.\nauto.\n}\n\n(* guard *)\n{\nintros pg s i a b A B Ha IH1 Hb IH2 j Hj.\nrewrite -> (iutruncate_iuguard _#5 Hj).\napply interp_guard; auto.\nso (IH2 _ Hj) as Hfunc.\nunfold fntruncate in Hfunc.\nunfold embed_ceiling_squash_ne.\nrewrite <- nearrow_compose_assoc.\napply transport_functional.\nexact Hfunc.\n}\n\n(* fut zero *)\n{\nintros pg s a H j Hj.\nassert (j = 0) by omega; subst j.\nrewrite -> iutruncate_iufut0; [| omega].\napply interp_fut_zero; auto.\n}\n\n(* fut *)\n{\nintros pg s i a A Ha IH j Hj.\ndestruct j as [| j].\n  {\n  rewrite -> iutruncate_iufut_one.\n  apply interp_fut_zero.\n  eapply basic_closed; eauto.\n  }\nrewrite -> iutruncate_iufut; [| omega].\nrewrite -> Nat.min_r; [| omega].\ncbn.\napply interp_fut.\napply IH.\nomega.\n}\n\n(* void *)\n{\nintros pg s i j Hj.\nrewrite -> iutruncate_iubase.\nrewrite -> ceiling_void.\napply interp_void.\n}\n\n(* unit *)\n{\nintros pg s i j Hj.\nrewrite -> iutruncate_iubase.\nrewrite -> ceiling_unit.\nrewrite -> Nat.min_r; auto.\napply interp_unit.\n}\n\n(* bool *)\n{\nintros pg s i j Hj.\nrewrite -> iutruncate_iubase.\nrewrite -> ceiling_bool.\nrewrite -> Nat.min_r; auto.\napply interp_bool.\n}\n\n(* wt *)\n{\nintros pg s i a b A B Ha IH1 Hb IH2 j Hj.\nrewrite -> iutruncate_iuwt.\napply interp_wt; auto.\napply IH2; auto.\n}\n\n(* equal *)\n{\nintros pg s i a m n p q A Hmp Hnq _ IH j H2.\nso (srel_ceiling_intro _#7 (Nat.le_min_r (S i) (S j)) (srel_downward_leq _#7 (Nat.le_min_l i j) Hmp)) as Hmp'.\nso (srel_ceiling_intro _#7 (Nat.le_min_r (S i) (S j)) (srel_downward_leq _#7 (Nat.le_min_l i j) Hnq)) as Hnq'.\nfold min in Hmp', Hnq'.\nrewrite -> (iutruncate_iuequal _#11 Hmp' Hnq').\nsetoid_rewrite <- (Nat.min_r i j) at 1; auto.\napply interp_equal.\nrewrite -> Nat.min_r; auto.\n}\n\n(* eqtype *)\n{\nintros pg s i a b R R' _ IH1 _ IH2 j Hj.\nunfold iutruncate, iueqtype, eqtype_urel.\ncbn [fst snd].\nrewrite -> ceiling_property.\nrewrite -> min_r; [| omega].\nrewrite -> meta_truncate_pair; [| omega].\nrewrite -> !meta_truncate_iurel; try omega.\nreplace (property_urel (eqtype_property stop R R') stop j (eqtype_property_downward _#3)) with (property_urel (eqtype_property stop (iutruncate (S j) R) (iutruncate (S j) R')) stop j (eqtype_property_downward _#3)).\n  {\n  apply interp_eqtype; auto.\n  }\napply property_urel_extensionality; auto.\nintros j' Hj'.\nunfold eqtype_property.\nrewrite -> !iutruncate_combine_le; try omega.\nreflexivity.\n}\n\n(* subtype *)\n{\nintros pg s i a b R R' _ IH1 _ IH2 j Hj.\nunfold iutruncate, iusubtype, subtype_urel.\ncbn [fst snd].\nrewrite -> ceiling_property.\nrewrite -> min_r; [| omega].\nrewrite -> meta_truncate_pair; [| omega].\nrewrite -> !meta_truncate_iurel; try omega.\nreplace (property_urel (subtype_property stop (den R) (den R')) stop j (subtype_property_downward _#3)) with (property_urel (subtype_property stop (den (iutruncate (S j) R)) (den (iutruncate (S j) R'))) stop j (subtype_property_downward _#3)).\n  {\n  apply interp_subtype; auto.\n  }\napply property_urel_extensionality; auto.\nintros j' Hj'.\nunfold subtype_property.\nsplit.\n  {\n  intros Hact k m p Hk Hmp.\n  assert (k < S j) as Hkj by omega.\n  so (Hact _#3 Hk (conj Hkj Hmp)) as H.\n  destruct H; auto.\n  }\n\n  {\n  intros Hact k m p Hk Hmp.\n  destruct Hmp as (Hks & Hmp).\n  split; auto.\n  }\n}\n\n(* all *)\n{\nintros pg s i lv k a gpg K A h Hlv _ IH1 Hle _ IH2 j Hj.\nso (le_ord_trans _#3 (approx_level j _) h) as h'.\nrewrite -> iutruncate_iuall.\nreplace (nearrow_compose2 (embed_ne j K) (iutruncate_ne (S j)) (std (S i) (qarrow K (qtype stop)) A))\n  with (std (S j) (qarrow (approx j K) (qtype stop)) (nearrow_compose A (embed_ne j K))).\n2:{\n  rewrite -> !std_arrow_is; cbn.\n  apply nearrow_extensionality.\n  intro x.\n  cbn.\n  change (std (S j) (qtype stop) (pi1 A (embed j K (std (S j) (approx j K) x)))\n          =\n          iutruncate (S j) (std (S i) (qtype stop) (pi1 A (std (S i) K (embed j K x))))).\n  rewrite -> !std_type_is.\n  rewrite -> iutruncate_combine_le; [| omega].\n  apply iutruncate_collapse.\n  apply (pi2 A).\n  rewrite -> embed_std; auto.\n  apply std_dist; omega.\n  }\napply (interp_all _#7 gpg _ _ h'); auto.\nintros j' Hj' x.\nso (IH2 j' (le_trans _#3 Hj' Hj) (transport (approx_combine_le j' j K Hj') spcar x) j' (le_refl _)) as Hint.\nforce_exact Hint; clear Hint.\nf_equal.\n  {\n  f_equal.\n  f_equal.\n    {\n    f_equal.\n    rewrite -> approx_combine_le; auto.\n    }\n  f_equal.\n  f_equal.\n  symmetry.\n  apply objsome_compat.\n  apply (expair_compat_transport _#6 (approx_combine_le j' j K Hj')).\n  cut (forall l l' x (h : l = l'),\n         transport h spcar (std (S j') l x)\n         = std (S j') l' (transport h spcar x)).\n    {\n    intro Hcond.\n    apply Hcond.\n    }\n  intros l l' y Heq.\n  subst l'.\n  reflexivity.\n  }\n\n  {\n  cbn.\n  fold (embed j K).\n  rewrite -> iutruncate_idem.\n  f_equal.\n  f_equal.\n  rewrite -> embed_std; [| omega].\n  f_equal.\n  symmetry.\n  apply embed_combine_le.\n  }\n}\n\n(* alltp *)\n{\nintros pg s i a A _ IH j Hj.\nrewrite -> iutruncate_iualltp.\napply interp_alltp.\nintros k Hk X.\ncbn.\napply IH; auto.\nomega.\n}\n\n(* exist *)\n{\nintros pg s i lv k a gpg K A h Hlv _ IH1 Hle _ IH2 j Hj.\nso (le_ord_trans _#3 (approx_level j _) h) as h'.\nrewrite -> iutruncate_iuexist.\nreplace (nearrow_compose2 (embed_ne j K) (iutruncate_ne (S j)) (std (S i) (qarrow K (qtype stop)) A))\n  with (std (S j) (qarrow (approx j K) (qtype stop)) (nearrow_compose A (embed_ne j K))).\n2:{\n  rewrite -> !std_arrow_is; cbn.\n  apply nearrow_extensionality.\n  intro x.\n  cbn.\n  change (std (S j) (qtype stop) (pi1 A (embed j K (std (S j) (approx j K) x)))\n          =\n          iutruncate (S j) (std (S i) (qtype stop) (pi1 A (std (S i) K (embed j K x))))).\n  rewrite -> !std_type_is.\n  rewrite -> iutruncate_combine_le; [| omega].\n  apply iutruncate_collapse.\n  apply (pi2 A).\n  rewrite -> embed_std; auto.\n  apply std_dist; omega.\n  }\napply (interp_exist _#7 gpg _ _ h'); auto.\nintros j' Hj' x.\nso (IH2 j' (le_trans _#3 Hj' Hj) (transport (approx_combine_le j' j K Hj') spcar x) j' (le_refl _)) as Hint.\nforce_exact Hint; clear Hint.\nf_equal.\n  {\n  f_equal.\n  f_equal.\n    {\n    f_equal.\n    rewrite -> approx_combine_le; auto.\n    }\n  f_equal.\n  f_equal.\n  symmetry.\n  apply objsome_compat.\n  apply (expair_compat_transport _#6 (approx_combine_le j' j K Hj')).\n  cut (forall l l' x (h : l = l'),\n         transport h spcar (std (S j') l x)\n         = std (S j') l' (transport h spcar x)).\n    {\n    intro Hcond.\n    apply Hcond.\n    }\n  intros l l' y Heq.\n  subst l'.\n  reflexivity.\n  }\n\n  {\n  cbn.\n  fold (embed j K).\n  rewrite -> iutruncate_idem.\n  f_equal.\n  f_equal.\n  rewrite -> embed_std; [| omega].\n  f_equal.\n  symmetry.\n  apply embed_combine_le.\n  }\n}\n\n(* extt *)\n{\nintros pg s i w R h Hw j Hj.\nrewrite -> iutruncate_extend_iurel.\nrewrite -> iutruncate_combine_le; try omega.\napply interp_extt; auto.\n}\n\n(* mu *)\n{\nintros pg w s i a F Hw _ IH Hne Hmono Hlocal j Hj.\nrewrite -> iutruncate_iubase.\nassert (monotone (fun X => ceiling (S j) (den (F X)))) as Hmono'.\n  {\n  eapply impl_compose; eauto.\n  apply monotone_ceiling.\n  }\nassert (@nonexpansive (wurel_ofe w) (wurel_ofe w) (fun X => ceiling (S j) (den (F X)))) as Hne'.\n  {\n  apply compose_ne_ne; auto.\n  apply ceiling_nonexpansive.\n  }\nrewrite -> ceiling_extend_urel.\nrewrite -> ceiling_mu; auto.\nchange (basicv system pg s j (mu a) (iubase (extend_urel w stop (mu_urel w (fun X => den (iutruncate (S j) (F X))))))).\napply interp_mu; auto.\nintros X h.\nrewrite <- iutruncate_extend_iurel.\napply IH; auto.\n}\n\n(* ispositive *)\n{\nintros pg s i a Hcl j Hj.\nrewrite -> iutruncate_iubase.\nunfold SemanticsPositive.ispositive_urel.\nrewrite -> ceiling_property.\nrewrite -> Nat.min_r; auto.\napply interp_ispositive; auto.\n}\n\n(* isnegative *)\n{\nintros pg s i a Hcl j Hj.\nrewrite -> iutruncate_iubase.\nunfold SemanticsPositive.isnegative_urel.\nrewrite -> ceiling_property.\nrewrite -> Nat.min_r; auto.\napply interp_isnegative; auto.\n}\n\n(* rec *)\n{\nintros pg s i a A _ IH j Hj.\napply interp_rec.\napply IH; auto.\n}\n\n(* univ *)\n{\nintros pg s i m gpg Hm Hstr Hcex j Hj.\nrewrite -> iutruncate_iuuniv.\nrewrite -> Nat.min_r; auto.\napply interp_univ; auto.\n}\n\n(* kuniv *)\n{\nintros pg s i m gpg h Hm Hlt j Hj.\nrewrite -> iutruncate_iukuniv.\nrewrite -> Nat.min_r; auto.\napply interp_kuniv; auto.\n}\n\n(* kbasic *)\n{\nintros pg s i k k' K Hcl Hsteps _ IH j Hj.\neapply kinterp_eval; eauto.\n}\n\n(* cbasic *)\n{\nintros pg s i c c' Q Hcl Hsteps _ IH j Hj.\neapply cinterp_eval; eauto.\n}\n\n(* basic *)\n{\nintros pg s i a a' R Hcl Hsteps _ IH j Hj.\neapply interp_eval; eauto.\n}\n\n(* functional *)\n{\nintros pg s i A b B Hclb Hcoarse Hb IH j Hj.\neapply functional_i; eauto.\n  {\n  symmetry.\n  apply ceiling_idem.\n  }\nintros j' m p Hj' Hmp.\ndestruct Hmp as (Hj'' & Hmp).\ncbn.\nrewrite -> embed_ceiling_urelspinj.\nso (Hb j' m p (le_trans _#3 Hj' Hj) Hmp) as HB.\nforce_exact HB.\nf_equal.\nso (IH j' m p (le_trans _#3 Hj' Hj) Hmp j' (le_refl j')) as HB'.\nso (basic_fun _#7 HB HB') as Heq.\nrewrite -> Heq.\nsetoid_rewrite -> Heq at 2.\nrewrite -> iutruncate_combine.\nrewrite -> Nat.min_r; auto.\n}\n\n(* wrapup *)\n{\ndo 6 (destruct Hind as (?, Hind)).\ndo2 3 split; intros; eauto.\n}\nQed.\n\n\nLemma kbasic_downward :\n  forall system pg s i j a K,\n    j <= i\n    -> kbasic system pg s i a K\n    -> kbasic system pg s j a (approx j K).\nProof.\nintro system.\nexact (semantics_downward system andel).\nQed.\n\n\nLemma cbasic_downward :\n  forall system pg s i j a Q,\n    j <= i\n    -> cbasic system pg s i a Q\n    -> cbasic system pg s j a (projc j (stdc (S j) Q)).\nProof.\nintro system.\nexact (semantics_downward system anderl).\nQed.\n\n\nLemma basic_downward :\n  forall system pg s i j a R,\n    j <= i\n    -> basic system pg s i a R\n    -> basic system pg s j a (iutruncate (S j) R).\nProof.\nintro system.\nexact (semantics_downward system anderrl).\nQed.\n\n\nLemma functional_downward :\n  forall system pg s i j A b B,\n    j <= i\n    -> functional system pg s i A b B\n    -> functional system pg s j (ceiling (S j) A) b (fntruncate (S j) A B).\nProof.\nintro system.\nexact (semantics_downward system anderrr).\nQed.\n\n\nLemma kbasic_impl_approx :\n  forall system pg s i k K,\n    kbasic system pg s i k K\n    -> K = approx i K.\nProof.\nintros system pg s i k K Hint.\nso (kbasic_downward _#7 (le_refl i) Hint) as Hint'.\nexact (kbasic_fun _#7 Hint Hint').\nQed.\n\n\nLemma cbasic_impl_proj :\n  forall system pg s i a Q,\n    cbasic system pg s i a Q\n    -> Q = projc i Q.\nProof.\nintros system pg s i a Q Hint.\nso (cbasic_downward _#7 (le_refl _) Hint) as Hint'.\nso (cbasic_fun _#7 Hint Hint') as Heq.\nso Heq as H.\nrewrite <- projc_idem in H.\nrewrite <- Heq in H.\nexact H.\nQed.\n\n\nLemma cbasic_impl_std :\n  forall system pg s i a Q,\n    cbasic system pg s i a Q\n    -> Q = stdc (S i) Q.\nProof.\nintros system pg s i a Q Hint.\nso (cbasic_downward _ pg s i i a Q (le_refl _) Hint) as Hint'.\nso (cbasic_fun _#7 Hint Hint') as Heq.\nso Heq as H.\nrewrite -> projc_stdc in H; [| omega].\nrewrite <- stdc_idem in H.\nrewrite <- projc_stdc in H; [| omega].\nrewrite <- Heq in H.\nexact H.\nQed.\n\n\nLemma cbasic_impl_form :\n  forall system pg s i a Q,\n    cbasic system pg s i a Q\n    -> Q = projc i (stdc (S i) Q).\nProof.\nintros system pg s i a Q Hint.\nso (cbasic_downward _#7 (le_refl _) Hint) as Hint'.\nexact (cbasic_fun _#7 Hint Hint').\nQed.\n\n\nLemma basic_impl_iutruncate :\n  forall system pg s i a R,\n    basic system pg s i a R\n    -> R = iutruncate (S i) R.\nProof.\nintros system pg s i a R Hint.\nso (basic_downward _#7 (le_refl _) Hint) as H.\nexact (basic_fun _#7 Hint H).\nQed.\n\n\nLemma interp_kext_impl_approx :\n  forall pg i k K,\n    interp_kext pg i k K\n    -> K = approx i K.\nProof.\nintros pg i k K H.\ndecompose H.\nintros Q h _ _ _ <-.\nsymmetry.\napply approx_idem.\nQed.\n\n\nLemma interp_uext_impl_ceiling :\n  forall pg i a A,\n    interp_uext pg i a A\n    -> A = ceiling (S i) A.\nProof.\nintros pg i a A H.\ndecompose H.\nintros w R h _ _ _ <-.\nsymmetry.\napply ceiling_idem.\nQed.\n\n\nLemma basic_member_index :\n  forall system pg s i a A j m n,\n    basic system pg s i a A\n    -> rel (den A) j m n\n    -> j <= i.\nProof.\nintros system pg s i a A j m n Hint Hrel.\nso (basic_impl_iutruncate _#6 Hint) as Heq.\nrewrite -> Heq in Hrel.\ndestruct Hrel as (H & _).\nomega.\nQed.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/ProperDownward.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23622818254608752}}
{"text": "(* Version of sail_values.lem that uses Lems machine words library *)\n\n(*Require Import Sail_impl_base*)\nRequire Export ZArith.\nRequire Import Ascii.\nRequire Export String.\nRequire Import bbv.Word.\nRequire Export bbv.HexNotationWord.\nRequire Export List.\nRequire Export Sumbool.\nRequire Export DecidableClass.\nRequire Import Eqdep_dec.\nRequire Export Zeuclid.\nRequire Import Lia.\nImport ListNotations.\n\nLocal Open Scope Z.\nLocal Open Scope bool.\n\nModule Z_eq_dec.\nDefinition U := Z.\nDefinition eq_dec := Z.eq_dec.\nEnd Z_eq_dec.\nModule ZEqdep := DecidableEqDep (Z_eq_dec).\n\n\n(* Constraint solving basics.  A HintDb which unfolding hints and lemmata\n   can be added to, and a typeclass to wrap constraint arguments in to\n   trigger automatic solving. *)\nCreate HintDb sail.\n(* Facts translated from Sail's type system are wrapped in ArithFactP or\n   ArithFact so that the solver can be invoked automatically by Coq's\n   typeclass mechanism.  Most properties are boolean, which enjoys proof\n   irrelevance by UIP. *)\nClass ArithFactP (P : Prop) := { fact : P }.\nClass ArithFact (P : bool) := ArithFactClass : ArithFactP (P = true).\nLemma use_ArithFact {P} `(ArithFact P) : P = true.\nunfold ArithFact in *.\napply fact.\nDefined.\n\nLemma ArithFact_irrelevant (P : bool) (p q : ArithFact P) : p = q.\ndestruct p,q.\nf_equal.\napply Eqdep_dec.UIP_dec.\napply Bool.bool_dec.\nQed.\n\nLtac replace_ArithFact_proof :=\n  match goal with |- context[?x] =>\n    match tt with\n    | _ => is_var x; fail 1\n    | _ =>\n      match type of x with ArithFact ?P =>\n        let pf := fresh \"pf\" in\n        generalize x as pf; intro pf;\n        repeat multimatch goal with |- context[?y] =>\n          match type of y with ArithFact P =>\n            match y with\n            | pf => idtac\n            | _ => rewrite <- (ArithFact_irrelevant P pf y)\n            end\n          end\n        end\n      end\n    end\n  end.\n\nLtac generalize_ArithFact_proof_in H :=\n  match type of H with context f [?x] =>\n    match type of x with ArithFactP (?P = true) =>\n      let pf := fresh \"pf\" in\n      cut (forall (pf : ArithFact P), ltac:(let t := context f[pf] in exact t));\n      [ clear H; intro H\n      | intro pf; rewrite <- (ArithFact_irrelevant P x pf); apply H ]\n    | ArithFact ?P =>\n      let pf := fresh \"pf\" in\n      cut (forall (pf : ArithFact P), ltac:(let t := context f[pf] in exact t));\n      [ clear H; intro H\n      | intro pf; rewrite <- (ArithFact_irrelevant P x pf); apply H ]\n    end\n  end.\n\n(* Allow setoid rewriting through ArithFact *)\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Program.Tactics.\n\nSection Morphism.\nLocal Obligation Tactic := try solve [simpl_relation | firstorder auto].\nGlobal Program Instance ArithFactP_iff_morphism :\n  Proper (iff ==> iff) ArithFactP.\nEnd Morphism.\n\nDefinition build_ex {T:Type} (n:T) {P:T -> Prop} `{H:ArithFactP (P n)} : {x : T & ArithFactP (P x)} :=\n  existT _ n H.\n\nDefinition build_ex2 {T:Type} {T':T -> Type} (n:T) (m:T' n) {P:T -> Prop} `{H:ArithFactP (P n)} : {x : T & T' x & ArithFactP (P x)} :=\n  existT2 _ _ n m H.\n\nDefinition generic_eq {T:Type} (x y:T) `{Decidable (x = y)} := Decidable_witness.\nDefinition generic_neq {T:Type} (x y:T) `{Decidable (x = y)} := negb Decidable_witness.\nLemma generic_eq_true {T} {x y:T} `{Decidable (x = y)} : generic_eq x y = true -> x = y.\napply Decidable_spec.\nQed.\nLemma generic_eq_false {T} {x y:T} `{Decidable (x = y)} : generic_eq x y = false -> x <> y.\nunfold generic_eq.\nintros H1 H2.\nrewrite <- Decidable_spec in H2.\ncongruence.\nQed.\nLemma generic_neq_true {T} {x y:T} `{Decidable (x = y)} : generic_neq x y = true -> x <> y.\nunfold generic_neq.\nintros H1 H2.\nrewrite <- Decidable_spec in H2.\ndestruct Decidable_witness; simpl in *; \ncongruence.\nQed.\nLemma generic_neq_false {T} {x y:T} `{Decidable (x = y)} : generic_neq x y = false -> x = y.\nunfold generic_neq.\nintro H1.\nrewrite <- Decidable_spec.\ndestruct Decidable_witness; simpl in *; \ncongruence.\nQed.\nInstance Decidable_eq_from_dec {T:Type} (eqdec: forall x y : T, {x = y} + {x <> y}) : \n  forall (x y : T), Decidable (eq x y).\nrefine (fun x y => {|\n  Decidable_witness := proj1_sig (bool_of_sumbool (eqdec x y))\n|}).\ndestruct (eqdec x y); simpl; split; congruence.\nDefined.\n\nInstance Decidable_eq_unit : forall (x y : unit), Decidable (x = y).\nrefine (fun x y => {| Decidable_witness := true |}).\ndestruct x, y; split; auto.\nDefined.\n\nInstance Decidable_eq_string : forall (x y : string), Decidable (x = y) :=\n  Decidable_eq_from_dec String.string_dec.\n\nInstance Decidable_eq_pair {A B : Type} `(DA : forall x y : A, Decidable (x = y), DB : forall x y : B, Decidable (x = y)) : forall x y : A*B, Decidable (x = y).\nrefine (fun x y =>\n{| Decidable_witness := andb (@Decidable_witness _ (DA (fst x) (fst y)))\n     (@Decidable_witness _ (DB (snd x) (snd y))) |}).\ndestruct x as [x1 x2].\ndestruct y as [y1 y2].\nsimpl.\ndestruct (DA x1 y1) as [b1 H1];\ndestruct (DB x2 y2) as [b2 H2];\nsimpl.\nsplit.\n* intro H.\n  apply Bool.andb_true_iff in H.\n  destruct H as [H1b H2b].\n  apply H1 in H1b.\n  apply H2 in H2b.\n  congruence.\n* intro. inversion H.\n  subst.\n  apply Bool.andb_true_iff.\n  tauto.\nQed.\n\nDefinition generic_dec {T:Type} (x y:T) `{Decidable (x = y)} : {x = y} + {x <> y}.\nrefine ((if Decidable_witness as b return (b = true <-> x = y -> _) then fun H' => _ else fun H' => _) Decidable_spec).\n* left. tauto.\n* right. intuition.\nDefined.\n\nInstance Decidable_eq_list {A : Type} `(D : forall x y : A, Decidable (x = y)) : forall (x y : list A), Decidable (x = y) :=\n  Decidable_eq_from_dec (list_eq_dec (fun x y => generic_dec x y)).\n\n(* Used by generated code that builds Decidable equality instances for records. *)\nLtac cmp_record_field x y :=\n  let H := fresh \"H\" in\n  case (generic_dec x y);\n  intro H; [ |\n    refine (Build_Decidable _ false _);\n    split; [congruence | intros Z; destruct H; injection Z; auto]\n  ].\n\n\nNotation \"x <=? y <=? z\" := ((x <=? y) && (y <=? z)) (at level 70, y at next level) : Z_scope.\nNotation \"x <=? y <? z\" := ((x <=? y) && (y <? z)) (at level 70, y at next level) : Z_scope.\nNotation \"x <? y <? z\" := ((x <? y) && (y <? z)) (at level 70, y at next level) : Z_scope.\nNotation \"x <? y <=? z\" := ((x <? y) && (y <=? z)) (at level 70, y at next level) : Z_scope.\n\n(* Project away range constraints in comparisons *)\nDefinition ltb_range_l {lo hi} (l : {x & ArithFact (lo <=? x <=? hi)}) r := Z.ltb (projT1 l) r.\nDefinition leb_range_l {lo hi} (l : {x & ArithFact (lo <=? x <=? hi)}) r := Z.leb (projT1 l) r.\nDefinition gtb_range_l {lo hi} (l : {x & ArithFact (lo <=? x <=? hi)}) r := Z.gtb (projT1 l) r.\nDefinition geb_range_l {lo hi} (l : {x & ArithFact (lo <=? x <=? hi)}) r := Z.geb (projT1 l) r.\nDefinition ltb_range_r {lo hi} l (r : {x & ArithFact (lo <=? x <=? hi)}) := Z.ltb l (projT1 r).\nDefinition leb_range_r {lo hi} l (r : {x & ArithFact (lo <=? x <=? hi)}) := Z.leb l (projT1 r).\nDefinition gtb_range_r {lo hi} l (r : {x & ArithFact (lo <=? x <=? hi)}) := Z.gtb l (projT1 r).\nDefinition geb_range_r {lo hi} l (r : {x & ArithFact (lo <=? x <=? hi)}) := Z.geb l (projT1 r).\n\nDefinition ii := Z.\nDefinition nn := nat.\n\n(*val pow : Z -> Z -> Z*)\nDefinition pow m n := m ^ n.\n\nProgram Definition pow2 n : {z : Z & ArithFact (2 ^ n <=? z <=? 2 ^ n)} := existT _ (pow 2 n) _.\nNext Obligation.\nconstructor.\nunfold pow.\nauto using Z.leb_refl with bool.\nQed.\n\nLemma ZEuclid_div_pos : forall x y, 0 < y -> 0 <= x -> 0 <= ZEuclid.div x y.\nintros.\nunfold ZEuclid.div.\nchange 0 with (0 * 0).\napply Zmult_le_compat.\n3,4: auto with zarith.\n* apply Z.sgn_nonneg. auto with zarith.\n* apply Z_div_pos; auto. apply Z.lt_gt. apply Z.abs_pos. auto with zarith.\nQed.\n\nLemma ZEuclid_pos_div : forall x y, 0 < y -> 0 <= ZEuclid.div x y -> 0 <= x.\nintros x y GT.\n  specialize (ZEuclid.div_mod x y);\n  specialize (ZEuclid.mod_always_pos x y);\n  generalize (ZEuclid.modulo x y);\n  generalize (ZEuclid.div x y);\n  intros.\nnia.\nQed.\n\nLemma ZEuclid_div_ge : forall x y, y > 0 -> x >= 0 -> x - ZEuclid.div x y >= 0.\nintros.\nunfold ZEuclid.div.\nrewrite Z.sgn_pos. 2: solve [ auto with zarith ].\nrewrite Z.mul_1_l.\napply Z.le_ge.\napply Zle_minus_le_0.\napply Z.div_le_upper_bound.\n* apply Z.abs_pos. auto with zarith.\n* rewrite Z.mul_comm.\n  nia.\nQed.\n\nLemma ZEuclid_div_mod0 : forall x y, y <> 0 ->\n  ZEuclid.modulo x y = 0 ->\n  y * ZEuclid.div x y = x.\nintros x y H1 H2.\nrewrite Zplus_0_r_reverse at 1.\nrewrite <- H2.\nsymmetry.\napply ZEuclid.div_mod.\nassumption.\nQed.\n\nHint Resolve ZEuclid_div_pos ZEuclid_pos_div ZEuclid_div_ge ZEuclid_div_mod0 : sail.\n\nLemma Z_geb_ge n m : (n >=? m) = true <-> n >= m.\nrewrite Z.geb_leb.\nsplit.\n* intro. apply Z.le_ge, Z.leb_le. assumption.\n* intro. apply Z.ge_le in H. apply Z.leb_le. assumption.\nQed.\n\n\n(*\nDefinition inline lt := (<)\nDefinition inline gt := (>)\nDefinition inline lteq := (<=)\nDefinition inline gteq := (>=)\n\nval eq : forall a. Eq a => a -> a -> bool\nDefinition inline eq l r := (l = r)\n\nval neq : forall a. Eq a => a -> a -> bool*)\nDefinition neq l r := (negb (l =? r)). (* Z only *)\n\n(*let add_int l r := integerAdd l r\nDefinition add_signed l r := integerAdd l r\nDefinition sub_int l r := integerMinus l r\nDefinition mult_int l r := integerMult l r\nDefinition div_int l r := integerDiv l r\nDefinition div_nat l r := natDiv l r\nDefinition power_int_nat l r := integerPow l r\nDefinition power_int_int l r := integerPow l (Z.to_nat r)\nDefinition negate_int i := integerNegate i\nDefinition min_int l r := integerMin l r\nDefinition max_int l r := integerMax l r\n\nDefinition add_real l r := realAdd l r\nDefinition sub_real l r := realMinus l r\nDefinition mult_real l r := realMult l r\nDefinition div_real l r := realDiv l r\nDefinition negate_real r := realNegate r\nDefinition abs_real r := realAbs r\nDefinition power_real b e := realPowInteger b e*)\n\nDefinition print_endline (_ : string) : unit := tt.\nDefinition prerr_endline (_ : string) : unit := tt.\nDefinition prerr (_ : string) : unit := tt.\nDefinition print_int (_ : string) (_ : Z) : unit := tt.\nDefinition prerr_int (_ : string) (_ : Z) : unit := tt.\nDefinition putchar (_ : Z) : unit := tt.\n\nDefinition shl_int := Z.shiftl.\nDefinition shr_int := Z.shiftr.\n\n(*\nDefinition or_bool l r := (l || r)\nDefinition and_bool l r := (l && r)\nDefinition xor_bool l r := xor l r\n*)\nDefinition append_list {A:Type} (l : list A) r := l ++ r.\nDefinition length_list {A:Type} (xs : list A) := Z.of_nat (List.length xs).\nDefinition take_list {A:Type} n (xs : list A) := firstn (Z.to_nat n) xs.\nDefinition drop_list {A:Type} n (xs : list A) := skipn (Z.to_nat n) xs.\n(*\nval repeat : forall a. list a -> Z -> list a*)\nFixpoint repeat' {a} (xs : list a) n :=\n  match n with\n  | O => []\n  | S n => xs ++ repeat' xs n\n  end.\nLemma repeat'_length {a} {xs : list a} {n : nat} : List.length (repeat' xs n) = (n * List.length xs)%nat.\ninduction n.\n* reflexivity.\n* simpl.\n  rewrite app_length.\n  auto with arith.\nQed.\nDefinition repeat {a} (xs : list a) (n : Z) :=\n  if n <=? 0 then []\n  else repeat' xs (Z.to_nat n).\nLemma repeat_length {a} {xs : list a} {n : Z} (H : n >= 0) : length_list (repeat xs n) = n * length_list xs.\nunfold length_list, repeat.\ndestruct n.\n+ reflexivity. \n+ simpl (List.length _).\n  rewrite repeat'_length.\n  rewrite Nat2Z.inj_mul.\n  rewrite positive_nat_Z.\n  reflexivity.  \n+ exfalso.\n  auto with zarith.\nQed.\n\n(*declare {isabelle} termination_argument repeat = automatic\n\nDefinition duplicate_to_list bit length := repeat [bit] length\n\nFixpoint replace bs (n : Z) b' := match bs with\n  | [] => []\n  | b :: bs =>\n     if n = 0 then b' :: bs\n              else b :: replace bs (n - 1) b'\n  end\ndeclare {isabelle} termination_argument replace = automatic\n\nDefinition upper n := n\n\n(* Modulus operation corresponding to quot below -- result\n   has sign of dividend. *)\nDefinition hardware_mod (a: Z) (b:Z) : Z :=\n  let m := (abs a) mod (abs b) in\n  if a < 0 then ~m else m\n\n(* There are different possible answers for integer divide regarding\nrounding behaviour on negative operands. Positive operands always\nround down so derive the one we want (trucation towards zero) from\nthat *)\nDefinition hardware_quot (a:Z) (b:Z) : Z :=\n  let q := (abs a) / (abs b) in\n  if ((a<0) = (b<0)) then\n    q  (* same sign -- result positive *)\n  else\n    ~q (* different sign -- result negative *)\n\nDefinition max_64u := (integerPow 2 64) - 1\nDefinition max_64  := (integerPow 2 63) - 1\nDefinition min_64  := 0 - (integerPow 2 63)\nDefinition max_32u := (4294967295 : Z)\nDefinition max_32  := (2147483647 : Z)\nDefinition min_32  := (0 - 2147483648 : Z)\nDefinition max_8   := (127 : Z)\nDefinition min_8   := (0 - 128 : Z)\nDefinition max_5   := (31 : Z)\nDefinition min_5   := (0 - 32 : Z)\n*)\n\n(* just_list takes a list of maybes and returns Some xs if all elements have\n   a value, and None if one of the elements is None. *)\n(*val just_list : forall a. list (option a) -> option (list a)*)\nFixpoint just_list {A} (l : list (option A)) := match l with\n  | [] => Some []\n  | (x :: xs) =>\n    match (x, just_list xs) with\n      | (Some x, Some xs) => Some (x :: xs)\n      | (_, _) => None\n    end\n  end.\n(*declare {isabelle} termination_argument just_list = automatic\n\nlemma just_list_spec:\n  ((forall xs. (just_list xs = None) <-> List.elem None xs) &&\n   (forall xs es. (just_list xs = Some es) <-> (xs = List.map Some es)))*)\n\nLemma just_list_length {A} : forall (l : list (option A)) (l' : list A),\n  Some l' = just_list l -> List.length l = List.length l'.\ninduction l.\n* intros.\n  simpl in H.\n  inversion H.\n  reflexivity.\n* intros.\n  destruct a; simplify_eq H.\n  simpl in *.\n  destruct (just_list l); simplify_eq H.\n  intros.\n  subst.\n  simpl.\n  f_equal.\n  apply IHl.\n  reflexivity.\nQed.\n\nLemma just_list_length_Z {A} : forall (l : list (option A)) l', Some l' = just_list l -> length_list l = length_list l'.\nunfold length_list.\nintros.\nf_equal.\nauto using just_list_length.\nQed.\n\nFixpoint member_Z_list (x : Z) (l : list Z) : bool :=\nmatch l with\n| [] => false\n| h::t => if x =? h then true else member_Z_list x t\nend.\n\nLemma member_Z_list_In {x l} : member_Z_list x l = true <-> In x l.\ninduction l.\n* simpl. split. congruence. tauto.\n* simpl. destruct (x =? a) eqn:H.\n  + rewrite Z.eqb_eq in H. subst. tauto.\n  + rewrite Z.eqb_neq in H. split.\n    - intro Heq. right. apply IHl. assumption.\n    - intros [bad | good]. congruence. apply IHl. assumption.\nQed.\n\n(*** Bits *)\nInductive bitU := B0 | B1 | BU.\n\nScheme Equality for bitU.\nDefinition eq_bit := bitU_beq.\nInstance Decidable_eq_bit : forall (x y : bitU), Decidable (x = y) :=\n  Decidable_eq_from_dec bitU_eq_dec.\n\nDefinition showBitU b :=\nmatch b with\n  | B0 => \"O\"\n  | B1 => \"I\"\n  | BU => \"U\"\nend%string.\n\nDefinition bitU_char b :=\nmatch b with\n| B0 => \"0\"\n| B1 => \"1\"\n| BU => \"?\"\nend%char.\n\n(*instance (Show bitU)\n  let show := showBitU\nend*)\n\nClass BitU (a : Type) : Type := {\n  to_bitU : a -> bitU;\n  of_bitU : bitU -> a\n}.\n\nInstance bitU_BitU : (BitU bitU) := {\n  to_bitU b := b;\n  of_bitU b := b\n}.\n\nDefinition bool_of_bitU bu := match bu with\n  | B0 => Some false\n  | B1 => Some true\n  | BU => None\n  end.\n\nDefinition bitU_of_bool (b : bool) := if b then B1 else B0.\n\n(*Instance bool_BitU : (BitU bool) := {\n  to_bitU := bitU_of_bool;\n  of_bitU := bool_of_bitU\n}.*)\n\nDefinition cast_bit_bool := bool_of_bitU.\n(*\nDefinition bit_lifted_of_bitU bu := match bu with\n  | B0 => Bitl_zero\n  | B1 => Bitl_one\n  | BU => Bitl_undef\n  end.\n\nDefinition bitU_of_bit := function\n  | Bitc_zero => B0\n  | Bitc_one  => B1\n  end.\n\nDefinition bit_of_bitU := function\n  | B0 => Bitc_zero\n  | B1 => Bitc_one\n  | BU => failwith \"bit_of_bitU: BU\"\n  end.\n\nDefinition bitU_of_bit_lifted := function\n  | Bitl_zero => B0\n  | Bitl_one  => B1\n  | Bitl_undef => BU\n  | Bitl_unknown => failwith \"bitU_of_bit_lifted Bitl_unknown\"\n  end.\n*)\nDefinition not_bit b :=\nmatch b with\n  | B1 => B0\n  | B0 => B1\n  | BU => BU\n  end.\n\n(*val is_one : Z -> bitU*)\nDefinition is_one (i : Z) :=\n  if i =? 1 then B1 else B0.\n\nDefinition binop_bit op x y :=\n  match (x, y) with\n  | (BU,_) => BU (*Do we want to do this or to respect | of I and & of B0 rules?*)\n  | (_,BU) => BU (*Do we want to do this or to respect | of I and & of B0 rules?*)\n(*  | (x,y) => bitU_of_bool (op (bool_of_bitU x) (bool_of_bitU y))*)\n  | (B0,B0) => bitU_of_bool (op false false)\n  | (B0,B1) => bitU_of_bool (op false  true)\n  | (B1,B0) => bitU_of_bool (op  true false)\n  | (B1,B1) => bitU_of_bool (op  true  true)\n  end.\n\n(*val and_bit : bitU -> bitU -> bitU*)\nDefinition and_bit := binop_bit andb.\n\n(*val or_bit : bitU -> bitU -> bitU*)\nDefinition or_bit := binop_bit orb.\n\n(*val xor_bit : bitU -> bitU -> bitU*)\nDefinition xor_bit := binop_bit xorb.\n\n(*val (&.) : bitU -> bitU -> bitU\nDefinition inline (&.) x y := and_bit x y\n\nval (|.) : bitU -> bitU -> bitU\nDefinition inline (|.) x y := or_bit x y\n\nval (+.) : bitU -> bitU -> bitU\nDefinition inline (+.) x y := xor_bit x y\n*)\n\n(*** Bool lists ***)\n\n(*val bools_of_nat_aux : integer -> natural -> list bool -> list bool*)\nFixpoint bools_of_nat_aux len (x : nat) (acc : list bool) : list bool :=\n  match len with\n  | O => acc\n  | S len' => bools_of_nat_aux len' (x / 2) ((if x mod 2 =? 1 then true else false) :: acc)\n  end %nat.\n  (*else (if x mod 2 = 1 then true else false) :: bools_of_nat_aux (x / 2)*)\n(*declare {isabelle} termination_argument bools_of_nat_aux = automatic*)\nDefinition bools_of_nat len n := bools_of_nat_aux (Z.to_nat len) n [] (*List.reverse (bools_of_nat_aux n)*).\n\n(*val nat_of_bools_aux : natural -> list bool -> natural*)\nFixpoint nat_of_bools_aux (acc : nat) (bs : list bool) : nat :=\n  match bs with\n  | [] => acc\n  | true :: bs => nat_of_bools_aux ((2 * acc) + 1) bs\n  | false :: bs => nat_of_bools_aux (2 * acc) bs\nend.\n(*declare {isabelle; hol} termination_argument nat_of_bools_aux = automatic*)\nDefinition nat_of_bools bs := nat_of_bools_aux 0 bs.\n\n(*val unsigned_of_bools : list bool -> integer*)\nDefinition unsigned_of_bools bs := Z.of_nat (nat_of_bools bs).\n\n(*val signed_of_bools : list bool -> integer*)\nDefinition signed_of_bools bs :=\n  match bs with\n    | true :: _  => 0 - (1 + (unsigned_of_bools (List.map negb bs)))\n    | false :: _ => unsigned_of_bools bs\n    | [] => 0 (* Treat empty list as all zeros *)\n  end.\n\n(*val int_of_bools : bool -> list bool -> integer*)\nDefinition int_of_bools (sign : bool) bs := if sign then signed_of_bools bs else unsigned_of_bools bs.\n\n(*val pad_list : forall 'a. 'a -> list 'a -> integer -> list 'a*)\nFixpoint pad_list_nat {a} (x : a) (xs : list a) n :=\n  match n with\n  | O => xs\n  | S n' => pad_list_nat x (x :: xs) n'\n  end.\n(*declare {isabelle} termination_argument pad_list = automatic*)\nDefinition pad_list {a} x xs n := @pad_list_nat a x xs (Z.to_nat n).\n\nDefinition ext_list {a} pad len (xs : list a) :=\n  let longer := len - (Z.of_nat (List.length xs)) in\n  if longer <? 0 then skipn (Z.abs_nat (longer)) xs\n  else pad_list pad xs longer.\n\n(*let extz_bools len bs = ext_list false len bs*)\nDefinition exts_bools len bs :=\n  match bs with\n    | true :: _ => ext_list true len bs\n    | _ => ext_list false len bs\n  end.\n\nFixpoint add_one_bool_ignore_overflow_aux bits := match bits with\n  | [] => []\n  | false :: bits => true :: bits\n  | true :: bits => false :: add_one_bool_ignore_overflow_aux bits\nend.\n(*declare {isabelle; hol} termination_argument add_one_bool_ignore_overflow_aux = automatic*)\n\nDefinition add_one_bool_ignore_overflow bits :=\n  List.rev (add_one_bool_ignore_overflow_aux (List.rev bits)).\n\n(* Ported from Lem, bad for large n.\nDefinition bools_of_int len n :=\n  let bs_abs := bools_of_nat len (Z.abs_nat n) in\n  if n >=? 0 then bs_abs\n  else add_one_bool_ignore_overflow (List.map negb bs_abs).\n*)\nFixpoint bitlistFromWord_rev {n} w :=\nmatch w with\n| WO => []\n| WS b w => b :: bitlistFromWord_rev w\nend.\nDefinition bitlistFromWord {n} w :=\n  List.rev (@bitlistFromWord_rev n w).\n\nDefinition bools_of_int len n :=\n  let w := Word.ZToWord (Z.to_nat len) n in\n  bitlistFromWord w.\n\n(*** Bit lists ***)\n\n(*val bits_of_nat_aux : natural -> list bitU*)\nFixpoint bits_of_nat_aux n x :=\n  match n,x with\n  | O,_ => []\n  | _,O => []\n  | S n, S _ => (if x mod 2 =? 1 then B1 else B0) :: bits_of_nat_aux n (x / 2)\n  end%nat.\n(**declare {isabelle} termination_argument bits_of_nat_aux = automatic*)\nDefinition bits_of_nat n := List.rev (bits_of_nat_aux n n).\n\n(*val nat_of_bits_aux : natural -> list bitU -> natural*)\nFixpoint nat_of_bits_aux acc bs := match bs with\n  | [] => Some acc\n  | B1 :: bs => nat_of_bits_aux ((2 * acc) + 1) bs\n  | B0 :: bs => nat_of_bits_aux (2 * acc) bs\n  | BU :: bs => None\nend%nat.\n(*declare {isabelle} termination_argument nat_of_bits_aux = automatic*)\nDefinition nat_of_bits bits := nat_of_bits_aux 0 bits.\n\nDefinition not_bits := List.map not_bit.\n\nDefinition binop_bits op bsl bsr :=\n  List.fold_right (fun '(bl, br) acc => binop_bit op bl br :: acc) [] (List.combine bsl bsr).\n(*\nDefinition and_bits := binop_bits (&&)\nDefinition or_bits := binop_bits (||)\nDefinition xor_bits := binop_bits xor\n\nval unsigned_of_bits : list bitU -> Z*)\nDefinition unsigned_of_bits bits :=\nmatch just_list (List.map bool_of_bitU bits) with\n| Some bs => Some (unsigned_of_bools bs)\n| None => None\nend.\n\n(*val signed_of_bits : list bitU -> Z*)\nDefinition signed_of_bits bits :=\n  match just_list (List.map bool_of_bitU bits) with\n  | Some bs => Some (signed_of_bools bs)\n  | None => None\n  end.\n\n(*val int_of_bits : bool -> list bitU -> maybe integer*)\nDefinition int_of_bits (sign : bool) bs :=\n if sign then signed_of_bits bs else unsigned_of_bits bs.\n\n(*val pad_bitlist : bitU -> list bitU -> Z -> list bitU*)\nFixpoint pad_bitlist_nat (b : bitU) bits n :=\nmatch n with\n| O => bits\n| S n' => pad_bitlist_nat b (b :: bits) n'\nend.\nDefinition pad_bitlist b bits n := pad_bitlist_nat b bits (Z.to_nat n). (* Negative n will come out as 0 *)\n(*  if n <= 0 then bits else pad_bitlist b (b :: bits) (n - 1).\ndeclare {isabelle} termination_argument pad_bitlist = automatic*)\n\nDefinition ext_bits pad len bits :=\n  let longer := len - (Z.of_nat (List.length bits)) in\n  if longer <? 0 then skipn (Z.abs_nat longer) bits\n  else pad_bitlist pad bits longer.\n\nDefinition extz_bits len bits := ext_bits B0 len bits.\nParameter undefined_list_bitU : list bitU.\nDefinition exts_bits len bits :=\n  match bits with\n  | BU :: _ => undefined_list_bitU (*failwith \"exts_bits: undefined bit\"*)\n  | B1 :: _ => ext_bits B1 len bits\n  | _ => ext_bits B0 len bits\n  end.\n\nFixpoint add_one_bit_ignore_overflow_aux bits := match bits with\n  | [] => []\n  | B0 :: bits => B1 :: bits\n  | B1 :: bits => B0 :: add_one_bit_ignore_overflow_aux bits\n  | BU :: _ => undefined_list_bitU (*failwith \"add_one_bit_ignore_overflow: undefined bit\"*)\nend.\n(*declare {isabelle} termination_argument add_one_bit_ignore_overflow_aux = automatic*)\n\nDefinition add_one_bit_ignore_overflow bits :=\n  rev (add_one_bit_ignore_overflow_aux (rev bits)).\n\nDefinition bitlist_of_int n :=\n  let bits_abs := B0 :: bits_of_nat (Z.abs_nat n) in\n  if n >=? 0 then bits_abs\n  else add_one_bit_ignore_overflow (not_bits bits_abs).\n\nDefinition bits_of_int len n := exts_bits len (bitlist_of_int n).\n\n(*val arith_op_bits :\n  (integer -> integer -> integer) -> bool -> list bitU -> list bitU -> list bitU*)\nDefinition arith_op_bits (op : Z -> Z -> Z) (sign : bool) l r :=\n  match (int_of_bits sign l, int_of_bits sign r) with\n    | (Some li, Some ri) => bits_of_int (length_list l) (op li ri)\n    | (_, _) => repeat [BU] (length_list l)\n  end.\n\n\nDefinition char_of_nibble x :=\n  match x with\n  | (B0, B0, B0, B0) => Some \"0\"%char\n  | (B0, B0, B0, B1) => Some \"1\"%char\n  | (B0, B0, B1, B0) => Some \"2\"%char\n  | (B0, B0, B1, B1) => Some \"3\"%char\n  | (B0, B1, B0, B0) => Some \"4\"%char\n  | (B0, B1, B0, B1) => Some \"5\"%char\n  | (B0, B1, B1, B0) => Some \"6\"%char\n  | (B0, B1, B1, B1) => Some \"7\"%char\n  | (B1, B0, B0, B0) => Some \"8\"%char\n  | (B1, B0, B0, B1) => Some \"9\"%char\n  | (B1, B0, B1, B0) => Some \"A\"%char\n  | (B1, B0, B1, B1) => Some \"B\"%char\n  | (B1, B1, B0, B0) => Some \"C\"%char\n  | (B1, B1, B0, B1) => Some \"D\"%char\n  | (B1, B1, B1, B0) => Some \"E\"%char\n  | (B1, B1, B1, B1) => Some \"F\"%char\n  | _ => None\n  end.\n\nFixpoint hexstring_of_bits bs := match bs with\n  | b1 :: b2 :: b3 :: b4 :: bs =>\n     let n := char_of_nibble (b1, b2, b3, b4) in\n     let s := hexstring_of_bits bs in\n     match (n, s) with\n     | (Some n, Some s) => Some (String n s)\n     | _ => None\n     end\n  | [] => Some EmptyString\n  | _ => None\n  end%string.\n\nFixpoint binstring_of_bits bs := match bs with\n  | b :: bs => String (bitU_char b) (binstring_of_bits bs)\n  | [] => EmptyString\n  end.\n\nDefinition show_bitlist bs :=\n  match hexstring_of_bits bs with\n  | Some s => String \"0\" (String \"x\" s)\n  | None => String \"0\" (String \"b\" (binstring_of_bits bs))\n  end.\n\n(*** List operations *)\n(*\nDefinition inline (^^) := append_list\n\nval subrange_list_inc : forall a. list a -> Z -> Z -> list a*)\nDefinition subrange_list_inc {A} (xs : list A) i j :=\n  let toJ := firstn (Z.to_nat j + 1) xs in\n  let fromItoJ := skipn (Z.to_nat i) toJ in\n  fromItoJ.\n\n(*val subrange_list_dec : forall a. list a -> Z -> Z -> list a*)\nDefinition subrange_list_dec {A} (xs : list A) i j :=\n  let top := (length_list xs) - 1 in\n  subrange_list_inc xs (top - i) (top - j).\n\n(*val subrange_list : forall a. bool -> list a -> Z -> Z -> list a*)\nDefinition subrange_list {A} (is_inc : bool) (xs : list A) i j :=\n if is_inc then subrange_list_inc xs i j else subrange_list_dec xs i j.\n\nDefinition splitAt {A} n (l : list A) := (firstn n l, skipn n l).\n\n(*val update_subrange_list_inc : forall a. list a -> Z -> Z -> list a -> list a*)\nDefinition update_subrange_list_inc {A} (xs : list A) i j xs' :=\n  let (toJ,suffix) := splitAt (Z.to_nat j + 1) xs in\n  let (prefix,_fromItoJ) := splitAt (Z.to_nat i) toJ in\n  prefix ++ xs' ++ suffix.\n\n(*val update_subrange_list_dec : forall a. list a -> Z -> Z -> list a -> list a*)\nDefinition update_subrange_list_dec {A} (xs : list A) i j xs' :=\n  let top := (length_list xs) - 1 in\n  update_subrange_list_inc xs (top - i) (top - j) xs'.\n\n(*val update_subrange_list : forall a. bool -> list a -> Z -> Z -> list a -> list a*)\nDefinition update_subrange_list {A} (is_inc : bool) (xs : list A) i j xs' :=\n  if is_inc then update_subrange_list_inc xs i j xs' else update_subrange_list_dec xs i j xs'.\n\nOpen Scope nat.\nFixpoint nth_in_range {A} (n:nat) (l:list A) : n < length l -> A.\nrefine \n  (match n, l with\n  | O, h::_ => fun _ => h\n  | S m, _::t => fun H => nth_in_range A m t _\n  | _,_ => fun H => _\n  end).\nexfalso. inversion H.\nexfalso. inversion H.\nsimpl in H. lia.\nDefined.\n\nLemma nth_in_range_is_nth : forall A n (l : list A) d (H : n < length l),\n  nth_in_range n l H = nth n l d.\nintros until d. revert n.\ninduction l; intros n H.\n* inversion H.\n* destruct n.\n  + reflexivity.\n  + apply IHl.\nQed.\n\nLemma nth_Z_nat {A} {n} {xs : list A} :\n  (0 <= n)%Z -> (n < length_list xs)%Z -> Z.to_nat n < length xs.\nunfold length_list.\nintros nonneg bounded.\nrewrite Z2Nat.inj_lt in bounded; auto using Zle_0_nat.\nrewrite Nat2Z.id in bounded.\nassumption.\nQed.\n\nClose Scope nat.\n\n(*val access_list_inc : forall a. list a -> Z -> a*)\nDefinition access_list_inc {A} (xs : list A) n `{ArithFact (0 <=? n)} `{ArithFact (n <? length_list xs)} : A.\nrefine (nth_in_range (Z.to_nat n) xs (nth_Z_nat _ _)).\n* apply Z.leb_le.\n  auto using use_ArithFact.\n* apply Z.ltb_lt.\n  auto using use_ArithFact.\nDefined.\n\n(*val access_list_dec : forall a. list a -> Z -> a*)\nDefinition access_list_dec {A} (xs : list A) n `{H1:ArithFact (0 <=? n)} `{H2:ArithFact (n <? length_list xs)} : A.\nrefine (\n  let top := (length_list xs) - 1 in\n  @access_list_inc A xs (top - n) _ _).\nabstract (constructor; apply use_ArithFact, Z.leb_le in H1; apply use_ArithFact, Z.ltb_lt in H2; apply Z.leb_le; lia).\nabstract (constructor; apply use_ArithFact, Z.leb_le in H1; apply use_ArithFact, Z.ltb_lt in H2; apply Z.ltb_lt; lia).\nDefined.\n\n(*val access_list : forall a. bool -> list a -> Z -> a*)\nDefinition access_list {A} (is_inc : bool) (xs : list A) n `{ArithFact (0 <=? n)} `{ArithFact (n <? length_list xs)} :=\n  if is_inc then access_list_inc xs n else access_list_dec xs n.\n\nDefinition access_list_opt_inc {A} (xs : list A) n := nth_error xs (Z.to_nat n).\n\n(*val access_list_dec : forall a. list a -> Z -> a*)\nDefinition access_list_opt_dec {A} (xs : list A) n :=\n  let top := (length_list xs) - 1 in\n  access_list_opt_inc xs (top - n).\n\n(*val access_list : forall a. bool -> list a -> Z -> a*)\nDefinition access_list_opt {A} (is_inc : bool) (xs : list A) n :=\n  if is_inc then access_list_opt_inc xs n else access_list_opt_dec xs n.\n\nDefinition list_update {A} (xs : list A) n x := firstn n xs ++ x :: skipn (S n) xs.\n\n(*val update_list_inc : forall a. list a -> Z -> a -> list a*)\nDefinition update_list_inc {A} (xs : list A) n x := list_update xs (Z.to_nat n) x.\n\n(*val update_list_dec : forall a. list a -> Z -> a -> list a*)\nDefinition update_list_dec {A} (xs : list A) n x :=\n  let top := (length_list xs) - 1 in\n  update_list_inc xs (top - n) x.\n\n(*val update_list : forall a. bool -> list a -> Z -> a -> list a*)\nDefinition update_list {A} (is_inc : bool) (xs : list A) n x :=\n  if is_inc then update_list_inc xs n x else update_list_dec xs n x.\n\n(*Definition extract_only_element := function\n  | [] => failwith \"extract_only_element called for empty list\"\n  | [e] => e\n  | _ => failwith \"extract_only_element called for list with more elements\"\nend*)\n\n(*** Machine words *)\n\nDefinition mword (n : Z) :=\n  match n with\n  | Zneg _ => False\n  | Z0 => word 0\n  | Zpos p => word (Pos.to_nat p)\n  end.\n\nDefinition get_word {n} : mword n -> word (Z.to_nat n) :=\n  match n with\n  | Zneg _ => fun x => match x with end\n  | Z0 => fun x => x\n  | Zpos p => fun x => x\n  end.\n\nDefinition with_word {n} {P : Type -> Type} : (word (Z.to_nat n) -> P (word (Z.to_nat n))) -> mword n -> P (mword n) :=\nmatch n with\n| Zneg _ => fun f w => match w with end\n| Z0 => fun f w => f w\n| Zpos _ => fun f w => f w\nend.\n\nProgram Definition to_word {n} : n >=? 0 = true -> word (Z.to_nat n) -> mword n :=\n  match n with\n  | Zneg _ => fun H _ => _\n  | Z0 => fun _ w => w\n  | Zpos _ => fun _ w => w\n  end.\n\nDefinition word_to_mword {n} (w : word (Z.to_nat n)) `{H:ArithFact (n >=? 0)} : mword n :=\n  to_word (use_ArithFact H) w.\n\n(*val length_mword : forall a. mword a -> Z*)\nDefinition length_mword {n} (w : mword n) := n.\n\n(*val slice_mword_dec : forall a b. mword a -> Z -> Z -> mword b*)\n(*Definition slice_mword_dec w i j := word_extract (Z.to_nat i) (Z.to_nat j) w.\n\nval slice_mword_inc : forall a b. mword a -> Z -> Z -> mword b\nDefinition slice_mword_inc w i j :=\n  let top := (length_mword w) - 1 in\n  slice_mword_dec w (top - i) (top - j)\n\nval slice_mword : forall a b. bool -> mword a -> Z -> Z -> mword b\nDefinition slice_mword is_inc w i j := if is_inc then slice_mword_inc w i j else slice_mword_dec w i j\n\nval update_slice_mword_dec : forall a b. mword a -> Z -> Z -> mword b -> mword a\nDefinition update_slice_mword_dec w i j w' := word_update w (Z.to_nat i) (Z.to_nat j) w'\n\nval update_slice_mword_inc : forall a b. mword a -> Z -> Z -> mword b -> mword a\nDefinition update_slice_mword_inc w i j w' :=\n  let top := (length_mword w) - 1 in\n  update_slice_mword_dec w (top - i) (top - j) w'\n\nval update_slice_mword : forall a b. bool -> mword a -> Z -> Z -> mword b -> mword a\nDefinition update_slice_mword is_inc w i j w' :=\n  if is_inc then update_slice_mword_inc w i j w' else update_slice_mword_dec w i j w'\n\nval access_mword_dec : forall a. mword a -> Z -> bitU*)\nParameter undefined_bit : bool.\nDefinition getBit {n} :=\nmatch n with\n| O => fun (w : word O) i => undefined_bit\n| S n => fun (w : word (S n)) i => wlsb (wrshift' w i)\nend.\n\nDefinition access_mword_dec {m} (w : mword m) n := bitU_of_bool (getBit (get_word w) (Z.to_nat n)).\n\n(*val access_mword_inc : forall a. mword a -> Z -> bitU*)\nDefinition access_mword_inc {m} (w : mword m) n :=\n  let top := (length_mword w) - 1 in\n  access_mword_dec w (top - n).\n\n(*Parameter access_mword : forall {a}, bool -> mword a -> Z -> bitU.*)\nDefinition access_mword {a} (is_inc : bool) (w : mword a) n :=\n  if is_inc then access_mword_inc w n else access_mword_dec w n.\n\nDefinition setBit {n} :=\nmatch n with\n| O => fun (w : word O) i b => w\n| S n => fun (w : word (S n)) i (b : bool) =>\n  let bit : word (S n) := wlshift' (natToWord _ 1) i in\n  let mask : word (S n) := wnot bit in\n  let masked := wand mask w in\n  if b then masked else wor masked bit\nend.\n\n(*val update_mword_bool_dec : forall 'a. mword 'a -> integer -> bool -> mword 'a*)\nDefinition update_mword_bool_dec {a} (w : mword a) n b : mword a :=\n  with_word (P := id) (fun w => setBit w (Z.to_nat n) b) w.\nDefinition update_mword_dec {a} (w : mword a) n b :=\n match bool_of_bitU b with\n | Some bl => Some (update_mword_bool_dec w n bl)\n | None => None\n end.\n\n(*val update_mword_inc : forall a. mword a -> Z -> bitU -> mword a*)\nDefinition update_mword_inc {a} (w : mword a) n b :=\n  let top := (length_mword w) - 1 in\n  update_mword_dec w (top - n) b.\n\n(*Parameter update_mword : forall {a}, bool -> mword a -> Z -> bitU -> mword a.*)\nDefinition update_mword {a} (is_inc : bool) (w : mword a) n b :=\n  if is_inc then update_mword_inc w n b else update_mword_dec w n b.\n\n(*val int_of_mword : forall 'a. bool -> mword 'a -> integer*)\nDefinition int_of_mword {a} `{ArithFact (a >=? 0)} (sign : bool) (w : mword a) :=\n  if sign then wordToZ (get_word w) else Z.of_N (wordToN (get_word w)).\n\n\n(*val mword_of_int : forall a. Size a => Z -> Z -> mword a\nDefinition mword_of_int len n :=\n  let w := wordFromInteger n in\n  if (length_mword w = len) then w else failwith \"unexpected word length\"\n*)\nProgram Definition mword_of_int {len} `{H:ArithFact (len >=? 0)} n : mword len :=\nmatch len with\n| Zneg _ => _\n| Z0 => ZToWord 0 n\n| Zpos p => ZToWord (Pos.to_nat p) n\nend.\nNext Obligation.\ndestruct H as [H].\nunfold Z.geb, Z.compare in H.\ndiscriminate.\nDefined.\n\n(*\n(* Translating between a type level number (itself n) and an integer *)\n\nDefinition size_itself_int x := Z.of_nat (size_itself x)\n\n(* NB: the corresponding sail type is forall n. atom(n) -> itself(n),\n   the actual integer is ignored. *)\n\nval make_the_value : forall n. Z -> itself n\nDefinition inline make_the_value x := the_value\n*)\n\nFixpoint wordFromBitlist_rev l : word (length l) :=\nmatch l with\n| [] => WO\n| b::t => WS b (wordFromBitlist_rev t)\nend.\nDefinition wordFromBitlist l : word (length l) :=\n  nat_cast _ (List.rev_length l) (wordFromBitlist_rev (List.rev l)).\n\nLocal Open Scope nat.\n\nFixpoint nat_diff {T : nat -> Type} n m {struct n} :\nforall\n (lt : forall p, T n -> T (n + p))\n (eq : T m -> T m)\n (gt : forall p, T (m + p) -> T m), T n -> T m :=\n(match n, m return (forall p, T n -> T (n + p)) -> (T m -> T m) -> (forall p, T (m + p) -> T m) -> T n -> T m with\n| O, O => fun lt eq gt => eq\n| S n', O => fun lt eq gt => gt _\n| O, S m' => fun lt eq gt => lt _\n| S n', S m' => @nat_diff (fun x => T (S x)) n' m'\nend).\n\nDefinition fit_bbv_word {n m} : word n -> word m :=\nnat_diff n m\n (fun p w => nat_cast _ (Nat.add_comm _ _) (extz w p))\n (fun w => w)\n (fun p w => split2 _ _ (nat_cast _ (Nat.add_comm _ _) w)).\n\nLocal Close Scope nat.\n\n(*** Bitvectors *)\n\nClass Bitvector (a:Type) : Type := {\n  bits_of : a -> list bitU;\n  of_bits : list bitU -> option a;\n  of_bools : list bool -> a;\n  (* The first parameter specifies the desired length of the bitvector *)\n  of_int : Z -> Z -> a;\n  length : a -> Z;\n  unsigned : a -> option Z;\n  signed : a -> option Z;\n  arith_op_bv : (Z -> Z -> Z) -> bool -> a -> a -> a\n}.\n\nInstance bitlist_Bitvector {a : Type} `{BitU a} : (Bitvector (list a)) := {\n  bits_of v := List.map to_bitU v;\n  of_bits v := Some (List.map of_bitU v);\n  of_bools v := List.map of_bitU (List.map bitU_of_bool v);\n  of_int len n := List.map of_bitU (bits_of_int len n);\n  length := length_list;\n  unsigned v := unsigned_of_bits (List.map to_bitU v);\n  signed v := signed_of_bits (List.map to_bitU v);\n  arith_op_bv op sign l r := List.map of_bitU (arith_op_bits op sign (List.map to_bitU l) (List.map to_bitU r))\n}.\n\nClass ReasonableSize (a : Z) : Prop := {\n  isPositive : a >=? 0 = true\n}.\n\n(* Definitions in the context that involve proof for other constraints can\n   break some of the constraint solving tactics, so prune definition bodies\n   down to integer types. *)\nLtac not_Z_bool ty := match ty with Z => fail 1 | bool => fail 1 | _ => idtac end.\nLtac clear_non_Z_bool_defns := \n  repeat match goal with H := _ : ?X |- _ => not_Z_bool X; clearbody H end.\nLtac clear_irrelevant_defns :=\nrepeat match goal with X := _ |- _ =>\n  match goal with |- context[X] => idtac end ||\n  match goal with _ : context[X] |- _ => idtac end || clear X\nend.\n\nLemma lift_bool_exists (l r : bool) (P : bool -> Prop) :\n  (l = r -> exists x, P x) ->\n  (exists x, l = r -> P x).\nintro H.\ndestruct (Bool.bool_dec l r) as [e | ne].\n* destruct (H e) as [x H']; eauto.\n* exists true; tauto.\nQed.\n\nLemma ArithFact_mword (a : Z) (w : mword a) : ArithFact (a >=? 0).\nconstructor.\ndestruct a.\n* auto with zarith.\n* auto using Z.le_ge, Zle_0_pos.\n* destruct w.\nQed.\n(* Remove constructor from ArithFact(P)s and if they're used elsewhere\n   in the context create a copy that rewrites will work on. *)\nLtac unwrap_ArithFacts :=\n  let gen X :=\n    let Y := fresh \"Y\" in pose X as Y; generalize Y\n  in\n  let unwrap H :=\n      let H' := fresh H in case H as [H']; clear H;\n      match goal with\n      | _ :  context[H'] |- _ => gen H'\n      | _ := context[H'] |- _ => gen H'\n      |   |- context[H']      => gen H'\n      | _ => idtac\n      end\n  in\n  repeat match goal with\n  | H:(ArithFact _) |- _ => unwrap H\n  | H:(ArithFactP _) |- _ => unwrap H\n  end.\nLtac unbool_comparisons :=\n  repeat match goal with\n  | H:@eq bool _ _ -> @ex bool _ |- _ => apply lift_bool_exists in H; destruct H\n  | H:@ex Z _ |- _ => destruct H\n  (* Omega doesn't know about In, but can handle disjunctions. *)\n  | H:context [member_Z_list _ _ = true] |- _ => rewrite member_Z_list_In in H\n  | H:context [In ?x (?y :: ?t)] |- _ => change (In x (y :: t)) with (y = x \\/ In x t) in H\n  | H:context [In ?x []] |- _ => change (In x []) with False in H\n  | H:?v = true |- _ => is_var v; subst v\n  | H:?v = false |- _ => is_var v; subst v\n  | H:true = ?v |- _ => is_var v; subst v\n  | H:false = ?v |- _ => is_var v; subst v\n  | H:_ /\\ _ |- _ => destruct H\n  | H:context [Z.geb _ _] |- _ => rewrite Z.geb_leb in H\n  | H:context [Z.gtb _ _] |- _ => rewrite Z.gtb_ltb in H\n  | H:context [Z.leb _ _ = true] |- _ => rewrite Z.leb_le in H\n  | H:context [Z.ltb _ _ = true] |- _ => rewrite Z.ltb_lt in H\n  | H:context [Z.eqb _ _ = true] |- _ => rewrite Z.eqb_eq in H\n  | H:context [Z.leb _ _ = false] |- _ => rewrite Z.leb_gt in H\n  | H:context [Z.ltb _ _ = false] |- _ => rewrite Z.ltb_ge in H\n  | H:context [Z.eqb _ _ = false] |- _ => rewrite Z.eqb_neq in H\n  | H:context [orb _ _ = true] |- _ => rewrite Bool.orb_true_iff in H\n  | H:context [orb _ _ = false] |- _ => rewrite Bool.orb_false_iff in H\n  | H:context [andb _ _ = true] |- _ => rewrite Bool.andb_true_iff in H\n  | H:context [andb _ _ = false] |- _ => rewrite Bool.andb_false_iff in H\n  | H:context [negb _ = true] |- _ => rewrite Bool.negb_true_iff in H\n  | H:context [negb _ = false] |- _ => rewrite Bool.negb_false_iff in H\n  | H:context [Bool.eqb _ ?r = true] |- _ => rewrite Bool.eqb_true_iff in H;\n                                             try (is_var r; subst r)\n  | H:context [Bool.eqb _ _ = false] |- _ => rewrite Bool.eqb_false_iff in H\n  | H:context [generic_eq _ _ = true] |- _ => apply generic_eq_true in H\n  | H:context [generic_eq _ _ = false] |- _ => apply generic_eq_false in H\n  | H:context [generic_neq _ _ = true] |- _ => apply generic_neq_true in H\n  | H:context [generic_neq _ _ = false] |- _ => apply generic_neq_false in H\n  | H:context [_ <> true] |- _ => rewrite Bool.not_true_iff_false in H\n  | H:context [_ <> false] |- _ => rewrite Bool.not_false_iff_true in H\n  | H:context [@eq bool ?l ?r] |- _ =>\n    lazymatch r with\n    | true => fail\n    | false => fail\n    | _ => rewrite (Bool.eq_iff_eq_true l r) in H\n    end\n  end.\nLtac unbool_comparisons_goal :=\n  repeat match goal with\n  (* Important to have these early in the list - setoid_rewrite can\n     unfold member_Z_list. *)\n  | |- context [member_Z_list _ _ = true] => rewrite member_Z_list_In\n  | |- context [In ?x (?y :: ?t)] => change (In x (y :: t)) with (y = x \\/ In x t) \n  | |- context [In ?x []] => change (In x []) with False\n  | |- context [Z.geb _ _] => setoid_rewrite Z.geb_leb\n  | |- context [Z.gtb _ _] => setoid_rewrite Z.gtb_ltb\n  | |- context [Z.leb _ _ = true] => setoid_rewrite Z.leb_le\n  | |- context [Z.ltb _ _ = true] => setoid_rewrite Z.ltb_lt\n  | |- context [Z.eqb _ _ = true] => setoid_rewrite Z.eqb_eq\n  | |- context [Z.leb _ _ = false] => setoid_rewrite Z.leb_gt\n  | |- context [Z.ltb _ _ = false] => setoid_rewrite Z.ltb_ge\n  | |- context [Z.eqb _ _ = false] => setoid_rewrite Z.eqb_neq\n  | |- context [orb _ _ = true] => setoid_rewrite Bool.orb_true_iff\n  | |- context [orb _ _ = false] => setoid_rewrite Bool.orb_false_iff\n  | |- context [andb _ _ = true] => setoid_rewrite Bool.andb_true_iff\n  | |- context [andb _ _ = false] => setoid_rewrite Bool.andb_false_iff\n  | |- context [negb _ = true] => setoid_rewrite Bool.negb_true_iff\n  | |- context [negb _ = false] => setoid_rewrite Bool.negb_false_iff\n  | |- context [Bool.eqb _ _ = true] => setoid_rewrite Bool.eqb_true_iff\n  | |- context [Bool.eqb _ _ = false] => setoid_rewrite Bool.eqb_false_iff\n  | |- context [generic_eq _ _ = true] => apply generic_eq_true\n  | |- context [generic_eq _ _ = false] => apply generic_eq_false\n  | |- context [generic_neq _ _ = true] => apply generic_neq_true\n  | |- context [generic_neq _ _ = false] => apply generic_neq_false\n  | |- context [_ <> true] => setoid_rewrite Bool.not_true_iff_false\n  | |- context [_ <> false] => setoid_rewrite Bool.not_false_iff_true\n  | |- context [@eq bool _ ?r] =>\n    lazymatch r with\n    | true => fail\n    | false => fail\n    | _ => setoid_rewrite Bool.eq_iff_eq_true\n    end\n  end.\n\n(* Split up dependent pairs to get at proofs of properties *)\nLtac extract_properties :=\n  (* Properties of local definitions *)\n  repeat match goal with H := context[projT1 ?X] |- _ =>\n    let x := fresh \"x\" in\n    let Hx := fresh \"Hx\" in\n    destruct X as [x Hx] in *;\n    change (projT1 (existT _ x Hx)) with x in * end;\n  (* Properties in the goal *)\n  repeat match goal with |- context [projT1 ?X] =>\n    let x := fresh \"x\" in\n    let Hx := fresh \"Hx\" in\n    destruct X as [x Hx] in *;\n    change (projT1 (existT _ x Hx)) with x in * end;\n  (* Properties with proofs embedded by build_ex; uses revert/generalize\n     rather than destruct because it seemed to be more efficient, but\n     some experimentation would be needed to be sure. \n  repeat (\n     match goal with H:context [@build_ex ?T ?n ?P ?prf] |- _ =>\n     let x := fresh \"x\" in\n     let zz := constr:(@build_ex T n P prf) in\n     revert dependent H(*; generalize zz; intros*)\n     end;\n     match goal with |- context [@build_ex ?T ?n ?P ?prf] =>\n     let x := fresh \"x\" in\n     let zz := constr:(@build_ex T n P prf) in\n     generalize zz as x\n     end;\n    intros).*)\n  repeat match goal with _:context [projT1 ?X] |- _ =>\n    let x := fresh \"x\" in\n    let Hx := fresh \"Hx\" in\n    destruct X as [x Hx] in *;\n    change (projT1 (existT _ x Hx)) with x in * end.\n(* TODO: hyps, too? *)\nLtac reduce_list_lengths :=\n  repeat match goal with |- context [length_list ?X] => \n    let r := (eval cbn in (length_list X)) in\n    change (length_list X) with r\n  end.\n(* TODO: can we restrict this to concrete terms? *)\nLtac reduce_pow :=\n  repeat match goal with H:context [Z.pow ?X ?Y] |- _ => \n    let r := (eval cbn in (Z.pow X Y)) in\n    change (Z.pow X Y) with r in H\n  end;\n  repeat match goal with |- context [Z.pow ?X ?Y] => \n    let r := (eval cbn in (Z.pow X Y)) in\n    change (Z.pow X Y) with r\n  end.\nLtac dump_context :=\n  repeat match goal with\n  | H:=?X |- _ => idtac H \":=\" X; fail\n  | H:?X |- _ => idtac H \":\" X; fail end;\n  match goal with |- ?X => idtac \"Goal:\" X end.\nLtac split_cases :=\n  repeat match goal with\n  |- context [match ?X with _ => _ end] => destruct X\n  end.\nLemma True_left {P:Prop} : (True /\\ P) <-> P.\ntauto.\nQed.\nLemma True_right {P:Prop} : (P /\\ True) <-> P.\ntauto.\nQed.\n\n(* Turn exists into metavariables like eexists, except put in dummy values when\n   the variable is unused.  This is used so that we can use eauto with a low\n   search bound that doesn't include the exists.  (Not terribly happy with\n   how this works...) *)\nLtac drop_Z_exists :=\nrepeat\n  match goal with |- @ex Z ?p =>\n   let a := eval hnf in (p 0) in\n   let b := eval hnf in (p 1) in\n   match a with b => exists 0 | _ => eexists end\n  end.\n(*\n  match goal with |- @ex Z (fun x => @?p x) =>\n   let xx := fresh \"x\" in\n   evar (xx : Z);\n   let a := eval hnf in (p xx) in\n   match a with context [xx] => eexists | _ => exists 0 end;\n   instantiate (xx := 0);\n   clear xx\n  end.\n*)\n(* For boolean solving we just use plain metavariables *)\nLtac drop_bool_exists :=\nrepeat match goal with |- @ex bool _ => eexists end.\n\n(* The linear solver doesn't like existentials. *)\nLtac destruct_exists :=\n  repeat match goal with H:@ex Z _ |- _ => destruct H end;\n  repeat match goal with H:@ex bool _ |- _ => destruct H end.\n\n(* The ASL to Sail translator sometimes puts constraints of the form\n   p | not(q) into function signatures, then the body case splits on q.\n   The filter_disjunctions tactic simplifies hypotheses by obtaining p. *)\n\nLemma truefalse : true = false <-> False.\nintuition.\nQed.\nLemma falsetrue : false = true <-> False.\nintuition.\nQed.\nLemma or_False_l P : False \\/ P <-> P.\nintuition.\nQed.\nLemma or_False_r P : P \\/ False <-> P.\nintuition.\nQed.\n\nLtac filter_disjunctions :=\n  repeat match goal with\n  | H1:?P \\/ ?t1 = ?t2, H2: ?t3 = ?t4 |- _ =>\n    (* I used to use non-linear matching above, but Coq is happy to match up\n       to conversion, including more unfolding than we normally do. *)\n    constr_eq t1 t3; constr_eq t2 t4; clear H1\n  | H1:context [?P \\/ ?t = true], H2: ?t = false |- _ => is_var t; rewrite H2 in H1\n  | H1:context [?P \\/ ?t = false], H2: ?t = true |- _ => is_var t; rewrite H2 in H1\n  | H1:context [?t = true \\/ ?P], H2: ?t = false |- _ => is_var t; rewrite H2 in H1\n  | H1:context [?t = false \\/ ?P], H2: ?t = true |- _ => is_var t; rewrite H2 in H1\n  end;\n  rewrite ?truefalse, ?falsetrue, ?or_False_l, ?or_False_r in *;\n  (* We may have uncovered more conjunctions *)\n  repeat match goal with H:and _ _ |- _ => destruct H end.\n\n(* Turn x := if _ then ... into x = ... \\/ x = ... *)\n\nLtac Z_if_to_or :=\n  repeat match goal with x := ?t : Z |- _ =>\n    let rec build_goal t :=\n      match t with\n      | if _ then ?y else ?z =>\n        let Hy := build_goal y in\n        let Hz := build_goal z in\n        constr:(Hy \\/ Hz)\n      | ?y => constr:(x = y)\n      end\n    in\n    let rec split_hyp t :=\n      match t with\n      | if ?b then ?y else ?z =>\n        destruct b in x; [split_hyp y| split_hyp z]\n      | _ => idtac\n      end\n    in\n    let g := build_goal t in\n    assert g by (clear -x; split_hyp t; auto);\n    clearbody x\n  end.\n\n(* Once we've done everything else, get rid of irrelevant bool and Z bindings\n   to help the brute force solver *)\nLtac clear_irrelevant_bindings :=\n  repeat\n    match goal with\n    | b : bool |- _ =>\n      lazymatch goal with\n      | _ : context [b] |- _ => fail\n      | |- context [b] => fail\n      | _ => clear b\n      end\n    | x : Z |- _ =>\n      lazymatch goal with\n      | _ : context [x] |- _ => fail\n      | |- context [x] => fail\n      | _ => clear x\n      end\n    | H:?x |- _ =>\n      let s := type of x in\n      lazymatch s with\n      | Prop =>\n        match x with\n        | context [?v] => is_var v; fail 1\n        | _ => clear H\n        end\n      | _ => fail\n      end\n    end.\n\n(* Currently, the ASL to Sail translation produces some constraints of the form\n   P \\/ x = true, P \\/ x = false, which are simplified by the tactic below.  In\n   future the translation is likely to be cleverer, and this won't be\n   necessary. *)\n(* TODO: remove duplication with filter_disjunctions *)\nLemma remove_unnecessary_casesplit {P:Prop} {x} :\n  P \\/ x = true -> P \\/ x = false -> P.\n  intuition congruence.\nQed.\nLemma remove_eq_false_true {P:Prop} {x} :\n  x = true -> P \\/ x = false -> P.\nintros H1 [H|H]; congruence.\nQed.\nLemma remove_eq_true_false {P:Prop} {x} :\n  x = false -> P \\/ x = true -> P.\nintros H1 [H|H]; congruence.\nQed.\nLtac remove_unnecessary_casesplit :=\nrepeat match goal with\n| H1 : ?P \\/ ?v = true, H2 : ?v = true |- _ => clear H1\n| H1 : ?P \\/ ?v = true, H2 : ?v = false |- _ => apply (remove_eq_true_false H2) in H1\n| H1 : ?P \\/ ?v = false, H2 : ?v = false |- _ => clear H1\n| H1 : ?P \\/ ?v = false, H2 : ?v = true |- _ => apply (remove_eq_false_true H2) in H1\n| H1 : ?P \\/ ?v1 = true, H2 : ?P \\/ ?v2 = false |- _ =>\n  constr_eq v1 v2;\n  is_var v1;\n  apply (remove_unnecessary_casesplit H1) in H2;\n  clear H1\n  (* There are worse cases where the hypotheses are different, so we actually\n     do the casesplit *)\n| H1 : _ \\/ ?v = true, H2 : _ \\/ ?v = false |- _ =>\n  is_var v;\n  destruct v;\n  [ clear H1; destruct H2; [ | congruence ]\n  | clear H2; destruct H1; [ | congruence ]\n  ]\nend;\n(* We may have uncovered more conjunctions *)\nrepeat match goal with H:and _ _ |- _ => destruct H end.\n\n(* Remove details of embedded proofs. *)\nLtac generalize_embedded_proofs :=\n  repeat match goal with H:context [?X] |- _ =>\n    match type of X with\n    | ArithFact  _ => generalize dependent X\n    | ArithFactP _ => generalize dependent X\n    end\n  end;\n  intros.\n\nLemma iff_equal_l {T:Type} {P:Prop} {x:T} : (x = x <-> P) -> P.\ntauto.\nQed.\nLemma iff_equal_r {T:Type} {P:Prop} {x:T} : (P <-> x = x) -> P.\ntauto.\nQed.\n\nLemma iff_known_l {P Q : Prop} : P -> P <-> Q -> Q.\ntauto.\nQed.\nLemma iff_known_r {P Q : Prop} : P -> Q <-> P -> Q.\ntauto.\nQed.\n\nLtac clean_up_props :=\n  repeat match goal with\n  (* I did try phrasing these as rewrites, but Coq was oddly reluctant to use them *)\n  | H:?x = ?x <-> _ |- _ => apply iff_equal_l in H\n  | H:_ <-> ?x = ?x |- _ => apply iff_equal_r in H\n  | H:context[true = false] |- _ => rewrite truefalse in H\n  | H:context[false = true] |- _ => rewrite falsetrue in H\n  | H1:?P <-> False, H2:context[?Q] |- _ => constr_eq P Q; rewrite -> H1 in H2\n  | H1:False <-> ?P, H2:context[?Q] |- _ => constr_eq P Q; rewrite <- H1 in H2\n  | H1:?P, H2:?Q <-> ?R |- _ => constr_eq P Q; apply (iff_known_l H1) in H2\n  | H1:?P, H2:?R <-> ?Q |- _ => constr_eq P Q; apply (iff_known_r H1) in H2\n  | H:context[_ \\/ False] |- _ => rewrite or_False_r in H\n  | H:context[False \\/ _] |- _ => rewrite or_False_l in H\n  end;\n  remove_unnecessary_casesplit.\n\nLtac prepare_for_solver :=\n(*dump_context;*)\n generalize_embedded_proofs;\n clear_irrelevant_defns;\n clear_non_Z_bool_defns;\n autounfold with sail in * |- *; (* You can add Hint Unfold ... : sail to let lia see through fns *)\n split_cases;\n extract_properties;\n repeat match goal with w:mword ?n |- _ => apply ArithFact_mword in w end;\n unwrap_ArithFacts;\n destruct_exists;\n unbool_comparisons;\n unbool_comparisons_goal;\n repeat match goal with H:and _ _ |- _ => destruct H end;\n remove_unnecessary_casesplit;\n reduce_list_lengths;\n reduce_pow;\n filter_disjunctions;\n Z_if_to_or;\n clear_irrelevant_bindings;\n subst;\n clean_up_props.\n\nLemma trivial_range {x : Z} : ArithFact ((x <=? x <=? x)).\nconstructor.\nauto using Z.leb_refl with bool.\nQed.\n\nLemma ArithFact_self_proof {P} : forall x : {y : Z & ArithFact (P y)}, ArithFact (P (projT1 x)).\nintros [x H].\nexact H.\nQed.\n\nLemma ArithFactP_self_proof {P} : forall x : {y : Z & ArithFactP (P y)}, ArithFactP (P (projT1 x)).\nintros [x H].\nexact H.\nQed.\n\nLtac fill_in_evar_eq :=\n match goal with |- ArithFact (?x =? ?y) =>\n   (is_evar x || is_evar y);\n   (* compute to allow projections to remove proofs that might not be allowed in the evar *)\n(* Disabled because cbn may reduce definitions, even after clearbody\n   let x := eval cbn in x in\n   let y := eval cbn in y in*)\n   idtac \"Warning: unknown equality constraint\"; constructor; exact (Z.eqb_refl _ : x =? y = true) end.\n\nLtac bruteforce_bool_exists :=\nmatch goal with\n| |- exists _ : bool,_ => solve [ exists true; bruteforce_bool_exists\n                                | exists false; bruteforce_bool_exists ]\n| _ => tauto\nend.\n\nLemma or_iff_cong : forall A B C D, A <-> B -> C <-> D -> A \\/ C <-> B \\/ D.\nintros.\ntauto.\nQed.\n\nLemma and_iff_cong : forall A B C D, A <-> B -> C <-> D -> A /\\ C <-> B /\\ D.\nintros.\ntauto.\nQed.\n\nLtac solve_euclid :=\nrepeat match goal with\n| |- context [ZEuclid.modulo ?x ?y] =>\n  specialize (ZEuclid.div_mod x y);\n  specialize (ZEuclid.mod_always_pos x y);\n  generalize (ZEuclid.modulo x y);\n  generalize (ZEuclid.div x y);\n  intros\n| |- context [ZEuclid.div ?x ?y] =>\n  specialize (ZEuclid.div_mod x y);\n  specialize (ZEuclid.mod_always_pos x y);\n  generalize (ZEuclid.modulo x y);\n  generalize (ZEuclid.div x y);\n  intros\nend;\nnia.\n(* Try to get the linear arithmetic solver to do booleans. *)\n\nLemma b2z_true x : x = true <-> Z.b2z x = 1.\ndestruct x; compute; split; congruence.\nQed.\n\nLemma b2z_false x : x = false <-> Z.b2z x = 0.\ndestruct x; compute; split; congruence.\nQed.\n\nLemma b2z_tf x : 0 <= Z.b2z x <= 1.\ndestruct x; simpl; lia.\nQed.\n\nLemma b2z_andb a b :\n  Z.b2z (a && b) = Z.min (Z.b2z a) (Z.b2z b).\ndestruct a,b; reflexivity.\nQed.\nLemma b2z_orb a b :\n  Z.b2z (a || b) = Z.max (Z.b2z a) (Z.b2z b).\ndestruct a,b; reflexivity.\nQed.\n\nLemma b2z_eq : forall a b, Z.b2z a = Z.b2z b <-> a = b.\nintros [|] [|];\nsimpl;\nintuition try congruence.\nQed.\n\nLemma b2z_negb x : Z.b2z (negb x) = 1 - Z.b2z x.\n  destruct x ; reflexivity.\nQed.\n\nLtac bool_to_Z :=\n  subst;\n  rewrite ?truefalse, ?falsetrue, ?or_False_l, ?or_False_r in *;\n  (* I did try phrasing these as rewrites, but Coq was oddly reluctant to use them *)\n  repeat match goal with\n  | H:?x = ?x <-> _ |- _ => apply iff_equal_l in H\n  | H:_ <-> ?x = ?x |- _ => apply iff_equal_r in H\n  end;\n  repeat match goal with\n  | H:context [negb ?v] |- _ => rewrite b2z_negb in H\n  | |- context [negb ?v]     => rewrite b2z_negb \n  |  H:context [?v = true] |- _  => is_var v; rewrite (b2z_true v) in *\n  | |- context [?v = true]       => is_var v; rewrite (b2z_true v) in *\n  |  H:context [?v = false] |- _ => is_var v; rewrite (b2z_false v) in *\n  | |- context [?v = false]      => is_var v; rewrite (b2z_false v) in *\n  | H:context [?v = ?w] |- _ => rewrite <- (b2z_eq v w) in H\n  | |- context [?v = ?w]     => rewrite <- (b2z_eq v w)\n  | H:context [Z.b2z (?v && ?w)] |- _ => rewrite (b2z_andb v w) in H\n  | |- context [Z.b2z (?v && ?w)]     => rewrite (b2z_andb v w)\n  | H:context [Z.b2z (?v || ?w)] |- _ => rewrite (b2z_orb v w) in H\n  | |- context [Z.b2z (?v || ?w)]     => rewrite (b2z_orb v w)\n  end;\n  change (Z.b2z true) with 1 in *;\n  change (Z.b2z false) with 0 in *;\n  repeat match goal with\n  | _:context [Z.b2z ?v] |- _ => generalize (b2z_tf v); generalize dependent (Z.b2z v)\n  | |- context [Z.b2z ?v]     => generalize (b2z_tf v); generalize dependent (Z.b2z v)\n  end.\nLtac solve_bool_with_Z :=\n  bool_to_Z;\n  intros;\n  lia.\n\n(* A more ambitious brute force existential solver. *)\n\nLtac guess_ex_solver :=\n  match goal with\n  | |- @ex bool ?t =>\n    match t with\n    | context [@eq bool ?b _] =>\n      solve [ exists b; guess_ex_solver\n            | exists (negb b); rewrite ?Bool.negb_true_iff, ?Bool.negb_false_iff;\n              guess_ex_solver ]\n    end\n(*  | b : bool |- @ex bool _ => exists b; guess_ex_solver\n  | b : bool |- @ex bool _ =>\n    exists (negb b); rewrite ?Bool.negb_true_iff, ?Bool.negb_false_iff;\n    guess_ex_solver*)\n  | |- @ex bool _ => exists true; guess_ex_solver\n  | |- @ex bool _ => exists false; guess_ex_solver\n  | x : ?ty |- @ex ?ty _ => exists x; guess_ex_solver\n  | _ => solve [tauto | eauto 3 with zarith sail | solve_bool_with_Z | lia]\n  end.\n\n(* A straightforward solver for simple problems like\n\n   exists ..., _ = true \\/ _ = false /\\ _ = true <-> _ = true \\/ _ = true\n*)\n\nLtac form_iff_true :=\nrepeat match goal with\n| |- ?l <-> _ = true =>\n  let rec aux t :=\n      match t with\n      | _ = true \\/ _ = true => rewrite <- Bool.orb_true_iff\n      | _ = true /\\ _ = true => rewrite <- Bool.andb_true_iff\n      | _ = false => rewrite <- Bool.negb_true_iff\n      | ?l \\/ ?r => aux l || aux r\n      | ?l /\\ ?r => aux l || aux r\n      end\n  in aux l\n       end.\nLtac simple_split_iff :=\n  repeat\n    match goal with\n    | |- _ /\\ _ <-> _ /\\ _ => apply and_iff_cong\n    | |- _ \\/ _ <-> _ \\/ _ => apply or_iff_cong\n    end.\nLtac simple_ex_iff :=\n  match goal with\n  | |- @ex _ _ => eexists; simple_ex_iff\n  | |- _ <-> _ =>\n    symmetry;\n    simple_split_iff;\n    form_iff_true;\n    solve [apply iff_refl | eassumption]\n  end.\n\n(* Another attempt at similar goals, this time allowing for conjuncts to move\n  around, and filling in integer existentials and redundant boolean ones.\n   TODO: generalise / combine with simple_ex_iff. *)\n\nLtac ex_iff_construct_bool_witness :=\nlet rec search x y :=\n  lazymatch y with\n  | x => constr:(true)\n  | ?y1 /\\ ?y2 =>\n    let b1 := search x y1 in\n    let b2 := search x y2 in\n    constr:(orb b1 b2)\n  | _ => constr:(false)\n  end\nin\nlet rec make_clause x :=\n  lazymatch x with\n  | ?l = true => l\n  | ?l = false => constr:(negb l)\n  | @eq Z ?l ?n => constr:(Z.eqb l n)\n  | ?p \\/ ?q =>\n    let p' := make_clause p in\n    let q' := make_clause q in\n    constr:(orb p' q')\n  | _ => fail\n  end in\nlet add_clause x xs :=\n  let l := make_clause x in\n  match xs with\n  | true => l\n  | _ => constr:(andb l xs)\n  end\nin\nlet rec construct_ex l r x :=\n  lazymatch l with\n  | ?l1 /\\ ?l2 =>\n    let y := construct_ex l1 r x in\n    construct_ex l2 r y\n  | _ =>\n   let present := search l r in\n   lazymatch eval compute in present with true => x | _ => add_clause l x end\n  end\nin\nlet witness := match goal with\n| |- ?l <-> ?r => construct_ex l r constr:(true)\nend in\ninstantiate (1 := witness).\n\nLtac ex_iff_fill_in_ints :=\n  let rec search l r y :=\n    match y with\n    | l = r => idtac\n    | ?v = r => is_evar v; unify v l\n    | ?y1 /\\ ?y2 => first [search l r y1 | search l r y2]\n    | _ => fail\n    end\n  in\n  match goal with\n  | |- ?l <-> ?r =>\n    let rec traverse l :=\n    lazymatch l with\n    | ?l1 /\\ ?l2 =>\n      traverse l1; traverse l2\n    | @eq Z ?x ?y => search x y r\n    | _ => idtac\n    end\n    in traverse l\n  end.\n\nLtac ex_iff_fill_in_bools :=\n  let rec traverse t :=\n    lazymatch t with\n    | ?v = ?t => try (is_evar v; unify v t)\n    | ?p /\\ ?q => traverse p; traverse q\n    | _ => idtac\n    end\n  in match goal with\n  | |- _ <-> ?r => traverse r\n  end.\n\nLtac conjuncts_iff_solve :=\n  ex_iff_fill_in_ints;\n  ex_iff_construct_bool_witness;\n  ex_iff_fill_in_bools;\n  unbool_comparisons_goal;\n  clear;\n  intuition.\n\nLtac ex_iff_solve :=\n  match goal with\n  | |- @ex _ _ => eexists; ex_iff_solve\n  (* Range constraints are attached to the right *)\n  | |- _ /\\ _ => split; [ex_iff_solve | lia]\n  | |- _ <-> _ => conjuncts_iff_solve || (symmetry; conjuncts_iff_solve)\n  end.\n\n\nLemma iff_false_left {P Q R : Prop} : (false = true) <-> Q -> (false = true) /\\ P <-> Q /\\ R.\nintuition.\nQed.\n\n(* Very simple proofs for trivial arithmetic.  Preferable to running omega/lia because\n   they can get bogged down if they see large definitions; should also guarantee small\n   proof terms. *)\nLemma Z_compare_lt_eq : Lt = Eq -> False. congruence. Qed.\nLemma Z_compare_lt_gt : Lt = Gt -> False. congruence. Qed.\nLemma Z_compare_eq_lt : Eq = Lt -> False. congruence. Qed.\nLemma Z_compare_eq_gt : Eq = Gt -> False. congruence. Qed.\nLemma Z_compare_gt_lt : Gt = Lt -> False. congruence. Qed.\nLemma Z_compare_gt_eq : Gt = Eq -> False. congruence. Qed.\nLtac z_comparisons :=\n  (* Don't try terms with variables - reduction may be expensive *)\n  match goal with |- context[?x] => is_var x; fail 1 | |- _ => idtac end;\n  solve [\n    exact eq_refl\n  | exact Z_compare_lt_eq\n  | exact Z_compare_lt_gt\n  | exact Z_compare_eq_lt\n  | exact Z_compare_eq_gt\n  | exact Z_compare_gt_lt\n  | exact Z_compare_gt_eq\n  ].\n                                                                                   \nLtac bool_ex_solve :=\nmatch goal with H : ?l = ?v -> @ex _ _ |- @ex _ _ =>\n     match v with true => idtac | false => idtac end;\n     destruct l;\n     repeat match goal with H:?X = ?X -> _ |- _ => specialize (H eq_refl) end;\n     repeat match goal with H:@ex _ _ |- _ => destruct H end;\n     unbool_comparisons;\n     guess_ex_solver\nend.\n\n(* Solve a boolean equality goal which is just rearranged clauses (e.g, at the\n   end of the clause_matching_bool_solver, below. *)\nLtac bruteforce_bool_eq :=\n  lazymatch goal with\n  | |- _ && ?l1 = _ => idtac l1; destruct l1; rewrite ?Bool.andb_true_l, ?Bool.andb_true_r, ?Bool.andb_false_l, ?Bool.andb_false_r; bruteforce_bool_eq\n  | |- ?l = _ => reflexivity\n  end.\n\nLtac clause_matching_bool_solver :=\n(* Do the left hand and right hand clauses have the same shape? *)\nlet rec check l r :=\n    lazymatch l with\n    | ?l1 || ?l2 =>\n      lazymatch r with ?r1 || ?r2 => check l1 r1; check l2 r2 end\n    | ?l1 =? ?l2 =>\n      lazymatch r with ?r1 =? ?r2 => check l1 r1; check l2 r2 end\n    | _ => is_evar l + constr_eq l r\n    end\nin\n(* Rebuild remaining rhs, dropping extra \"true\"s. *)\nlet rec add_clause l r :=\n  match l with\n  | true => r\n  | _ => match r with true => l | _ => constr:(l && r) end\n  end\nin\n(* Find a clause in r matching l, use unify to instantiate evars, return rest of r *)\nlet rec find l r :=\n    lazymatch r with\n    | ?r1 && ?r2 =>\n      match l with\n      | _ => let r1' := find l r1 in add_clause r1' r2\n      | _ => let r2' := find l r2 in add_clause r1 r2'\n      end\n    | _ => constr:(ltac:(check l r; unify l r; exact true))\n    end\nin\n(* For each clause in the lhs, find a matching clause in rhs, fill in\n   remaining evar with left over.  TODO: apply to goals without an evar clause *)\nmatch goal with\n  | |- @ex _ _ => eexists; clause_matching_bool_solver\n  | |- _ = _ /\\ _ <= _ <= _ => split; [clause_matching_bool_solver | lia]\n  | |- ?l = ?r =>\n  let rec clause l r :=\n      match l with\n      | ?l1 && ?l2 =>\n        let r2 := clause l1 r in clause l2 r2\n      | _ => constr:(ltac:(is_evar l; exact r))\n      | _ => find l r\n      end\n  in let r' := clause l r in\n     instantiate (1 := r');\n     rewrite ?Bool.andb_true_l, ?Bool.andb_assoc;\n     bruteforce_bool_eq\nend.\n\n\n\n(* Redefine this to add extra solver tactics *)\nLtac sail_extra_tactic := fail.\n\nLtac main_solver :=\n solve\n [ apply ArithFact_mword; assumption\n | z_comparisons\n | lia\n   (* Try sail hints before dropping the existential *)\n | subst; eauto 3 with zarith sail\n   (* The datatypes hints give us some list handling, esp In *)\n | subst; drop_Z_exists;\n   repeat match goal with |- and _ _ => split end;\n   eauto 3 with datatypes zarith sail\n | subst; match goal with |- context [ZEuclid.div] => solve_euclid\n                        | |- context [ZEuclid.modulo] => solve_euclid\n   end\n | match goal with |- context [Z.mul] => nia end\n (* If we have a disjunction from a set constraint on a variable we can often\n    solve a goal by trying them (admittedly this is quite heavy handed...) *)\n | subst; drop_Z_exists;\n   let aux x :=\n    is_var x;\n    intuition (subst;auto with datatypes)\n   in\n   match goal with\n   | _:(@eq Z _ ?x) \\/ (@eq Z _ ?x) \\/ _ |- context[?x] => aux x\n   | _:(@eq Z ?x _) \\/ (@eq Z ?x _) \\/ _ |- context[?x] => aux x\n   | _:(@eq Z _ ?x) \\/ (@eq Z _ ?x) \\/ _, _:@eq Z ?y (ZEuclid.div ?x _) |- context[?y] => is_var x; aux y\n   | _:(@eq Z ?x _) \\/ (@eq Z ?x _) \\/ _, _:@eq Z ?y (ZEuclid.div ?x _) |- context[?y] => is_var x; aux y\n   end\n (* Booleans - and_boolMP *)\n | solve_bool_with_Z\n | simple_ex_iff\n | ex_iff_solve\n | drop_bool_exists; solve [eauto using iff_refl, or_iff_cong, and_iff_cong | intuition]\n | match goal with |- (forall l r:bool, _ -> _ -> exists _ : bool, _) =>\n     let r := fresh \"r\" in\n     let H1 := fresh \"H\" in\n     let H2 := fresh \"H\" in\n     intros [|] r H1 H2;\n     let t2 := type of H2 in\n     match t2 with\n     | ?b = ?b -> _ =>\n       destruct (H2 eq_refl);\n       repeat match goal with H:@ex _ _ |- _ => destruct H end;\n       simple_ex_iff\n     | ?b = _ -> _ =>\n       repeat match goal with H:@ex _ _ |- _ => destruct H end;\n       clear H2;\n       repeat match goal with\n              | |- @ex bool _ => exists b\n              | |- @ex Z _ => exists 0\n              end;\n       intuition\n     end\n   end\n | match goal with |- (forall l r:bool, _ -> _ -> @ex _ _) =>\n     let H1 := fresh \"H\" in\n     let H2 := fresh \"H\" in\n     intros [|] [|] H1 H2;\n     repeat match goal with H:?X = ?X -> _ |- _ => specialize (H eq_refl) end;\n     repeat match goal with H:@ex _ _ |- _ => destruct H end;\n     guess_ex_solver\n   end\n(* While firstorder was quite effective at dealing with existentially quantified\n   goals from boolean expressions, it attempts lazy normalization of terms,\n   which blows up on integer comparisons with large constants.\n | match goal with |- context [@eq bool _ _] =>\n     (* Don't use auto for the fallback to keep runtime down *)\n     firstorder fail\n   end*)\n | bool_ex_solve\n | clause_matching_bool_solver\n | match goal with |- @ex _ _ => guess_ex_solver end\n | sail_extra_tactic\n | idtac \"Unable to solve constraint\"; dump_context; fail\n ].\n\n(* Omega can get upset by local definitions that are projections from value/proof pairs.\n   Complex goals can use prepare_for_solver to extract facts; this tactic can be used\n   for simpler proofs without using prepare_for_solver. *)\nLtac simple_omega :=\n  repeat match goal with\n  H := projT1 _ |- _ => clearbody H\n  end; lia.\n\nLtac solve_unknown :=\n  match goal with\n  | |- (ArithFact (?x ?y)) =>\n    is_evar x;\n    idtac \"Warning: unknown constraint\";\n    let t := type of y in\n    unify x (fun (_ : t) => true);\n    exact (Build_ArithFactP _ eq_refl : ArithFact true)\n  | |- (ArithFactP (?x ?y)) =>\n    is_evar x;\n    idtac \"Warning: unknown constraint\";\n    let t := type of y in\n    unify x (fun (_ : t) => True);\n    exact (Build_ArithFactP _ I : ArithFactP True)\n  end.\n\n(* Solving straightforward and_boolMP / or_boolMP goals *)\n\nLemma default_and_proof l r r' :\n  (l = true -> r' = r) ->\n  l && r' = l && r.\n  intro H.\ndestruct l; [specialize (H eq_refl) | clear H ]; auto.\nQed.\n\nLemma default_and_proof2 l l' r r' :\n  l' = l ->\n  (l = true -> r' = r) ->\n  l' && r' = l && r.\nintros; subst.\nauto using default_and_proof.\nQed.\n\nLemma default_or_proof l r r' :\n  (l = false -> r' = r) ->\n  l || r' = l || r.\n  intro H.\ndestruct l; [clear H | specialize (H eq_refl) ]; auto.\nQed.\n\nLemma default_or_proof2 l l' r r' :\n  l' = l ->\n  (l = false -> r' = r) ->\n  l' || r' = l || r.\nintros; subst.\nauto using default_or_proof.\nQed.\n\nLtac default_andor :=\n  intros; constructor; intros;\n  repeat match goal with\n  | H:@ex _ _ |- _ => destruct H\n  | H:@eq bool _ _ -> @ex bool _ |- _ => apply lift_bool_exists in H\n   end;\n  repeat match goal with |- @ex _ _ => eexists end;\n  rewrite ?Bool.eqb_true_iff, ?Bool.eqb_false_iff in *;\n  match goal with\n  | H:?v = true -> _ |- _ = ?v && _ => solve [eapply default_and_proof; eauto 2]\n  | H:?v = true -> _ |- _ = ?v && _ => solve [eapply default_and_proof2; eauto 2]\n  | H:?v = false -> _ |- _ = ?v || _ => solve [eapply default_or_proof; eauto 2]\n  | H:?v = false -> _ |- _ = ?v || _ => solve [eapply default_or_proof2; eauto 2]\n  | H:?v = true -> _ |- _ = ?v && _ => solve [rewrite Bool.andb_comm; eapply default_and_proof; eauto 2]\n  | H:?v = true -> _ |- _ = ?v && _ => solve [rewrite Bool.andb_comm; eapply default_and_proof2; eauto 2]\n  | H:?v = false -> _ |- _ = ?v || _ => solve [rewrite Bool.orb_comm; eapply default_or_proof; eauto 2]\n  | H:?v = false -> _ |- _ = ?v || _ => solve [rewrite Bool.orb_comm; eapply default_or_proof2; eauto 2]\n  end.\n\n(* Solving simple and_boolMP / or_boolMP goals where unknown booleans\n   have been merged together. *)\n\nLtac squashed_andor_solver :=\n  clear;\n  match goal with |- forall l r : bool, ArithFactP (_ -> _ -> _) => idtac end;\n  intros l r; constructor; intros;\n  let func := match goal with |- context[?f l r] => f end in\n  match goal with\n  | H1 : @ex _ _, H2 : l = _ -> @ex _ _ |- _ =>\n    let x1 := fresh \"x1\" in\n    let x2 := fresh \"x2\" in\n    let H1' := fresh \"H1\" in\n    let H2' := fresh \"H2\" in\n    apply lift_bool_exists in H2;\n    destruct H1 as [x1 H1']; destruct H2 as [x2 H2'];\n    exists x1, x2\n  | H : l = _ -> @ex _ _ |- _ =>\n    let x := fresh \"x\" in\n    let H' := fresh \"H\" in\n    apply lift_bool_exists in H;\n    destruct H as [x H'];\n    exists (func x l)\n  | H : @ex _ _ |- _ =>\n    let x := fresh \"x\" in\n    let H' := fresh \"H\" in\n    destruct H as [x H'];\n    exists (func x r)\n  end;\n  repeat match goal with\n  | H : l = _ -> @ex _ _ |- _ =>\n    let x := fresh \"x\" in\n    let H' := fresh \"H\" in\n    apply lift_bool_exists in H;\n    destruct H as [x H'];\n    exists x\n  | H : @ex _ _ |- _ =>\n    let x := fresh \"x\" in\n    let H' := fresh \"H\" in\n    destruct H as [x H'];\n    exists x\n  end;\n  (* Attempt to shrink size of problem.\n     I originally used just one match here with a non-linear pattern, but it\n     appears it matched up to convertability and so definitions could break\n     the generalization. *)\n  try match goal with\n      | _ : l = _ -> ?v = r |- _ => match goal with |- context[v] => generalize dependent v; intros end\n      | _ : l = _ -> Bool.eqb ?v r = true |- _ => match goal with |- context[v] => generalize dependent v; intros end\n      end;\n  unbool_comparisons; unbool_comparisons_goal;\n  repeat match goal with\n  | _ : context[?li =? ?ri] |- _ =>\n    specialize (Z.eqb_eq li ri); generalize dependent (li =? ri); intros\n  | |- context[?li =? ?ri] =>\n    specialize (Z.eqb_eq li ri); generalize (li =? ri); intros\n  end;\n  solve_bool_with_Z.\n\nLtac run_main_solver_impl :=\n(* Attempt a simple proof first to avoid lengthy preparation steps (especially\n   as the large proof terms can upset subsequent proofs). *)\ntry solve [default_andor];\nconstructor;\ntry simple_omega;\nprepare_for_solver;\n(*dump_context;*)\nunbool_comparisons_goal; (* Applying the ArithFact constructor will reveal an = true, so this might do more than it did in prepare_for_solver *)\nrepeat match goal with |- and _ _ => split end;\nmain_solver.\n\n(* This can be redefined to remove the abstract. *)\nLtac run_main_solver :=\n  solve\n    [ abstract run_main_solver_impl\n    | run_main_solver_impl (* for cases where there's an evar in the goal *)\n    ].\n\nLtac is_fixpoint ty :=\n  match ty with\n  | forall _reclimit, Acc _ _reclimit -> _ => idtac\n  | _ -> ?res => is_fixpoint res\n  end.\n\nLtac clear_fixpoints :=\n  repeat\n    match goal with\n    | H:_ -> ?res |- _ => is_fixpoint res; clear H\n    end.\nLtac clear_proof_bodies :=\n  repeat match goal with\n  | H := _ : ?ty |- _ =>\n    match type of ty with\n    | Prop => clearbody H\n    end\n  end.\n\nLtac solve_arithfact :=\n  clear_proof_bodies;\n  try solve [squashed_andor_solver]; (* Do this first so that it can name the intros *)\n  intros; (* To solve implications for derive_m *)\n  clear_fixpoints; (* Avoid using recursive calls *)\n  cbv beta; (* Goal might be eta-expanded *)\n  solve\n    [ solve_unknown\n    | assumption\n    | match goal with |- ArithFact ((?x <=? ?x <=? ?x)) => exact trivial_range end\n    | eauto 2 with sail (* the low search bound might not be necessary *)\n    | fill_in_evar_eq\n    | match goal with |- context [projT1 ?X] => apply (ArithFact_self_proof X) end\n    | match goal with |- context [projT1 ?X] => apply (ArithFactP_self_proof X) end\n    (* Trying reflexivity will fill in more complex metavariable examples than\n       fill_in_evar_eq above, e.g., 8 * n =? 8 * ?Goal3 *)\n    | constructor; apply Z.eqb_eq; reflexivity\n    | constructor; repeat match goal with |- and _ _ => split end; z_comparisons\n    | run_main_solver\n    ].\n\n(* Add an indirection so that you can redefine run_solver to fail to get\n   slow running constraints into proof mode. *)\nLtac run_solver := solve_arithfact.\n\nHint Extern 0 (ArithFact _) => run_solver : typeclass_instances.\nHint Extern 0 (ArithFactP _) => run_solver : typeclass_instances.\n\nHint Unfold length_mword : sail.\n\nLemma unit_comparison_lemma : true = true <-> True.\nintuition.\nQed.\nHint Resolve unit_comparison_lemma : sail.\n\nDefinition neq_atom (x : Z) (y : Z) : bool := negb (Z.eqb x y).\nHint Unfold neq_atom : sail.\n\nLemma ReasonableSize_witness (a : Z) (w : mword a) : ReasonableSize a.\nconstructor.\ndestruct a.\n* auto with zarith.\n* auto using Z.le_ge, Zle_0_pos.\n* destruct w.\nQed.\n\nHint Extern 0 (ReasonableSize ?A) => (unwrap_ArithFacts; solve [apply ReasonableSize_witness; assumption | constructor; auto with zarith]) : typeclass_instances.\n\nDefinition to_range (x : Z) : {y : Z & ArithFact ((x <=? y <=? x))} := build_ex x.\n\nInstance mword_Bitvector {a : Z} `{ArithFact (a >=? 0)} : (Bitvector (mword a)) := {\n  bits_of v := List.map bitU_of_bool (bitlistFromWord (get_word v));\n  of_bits v := option_map (fun bl => to_word isPositive (fit_bbv_word (wordFromBitlist bl))) (just_list (List.map bool_of_bitU v));\n  of_bools v := to_word isPositive (fit_bbv_word (wordFromBitlist v));\n  of_int len z := mword_of_int z; (* cheat a little *)\n  length v := a;\n  unsigned v := Some (Z.of_N (wordToN (get_word v)));\n  signed v := Some (wordToZ (get_word v));\n  arith_op_bv op sign l r := mword_of_int (op (int_of_mword sign l) (int_of_mword sign r))\n}.\n\nSection Bitvector_defs.\nContext {a b} `{Bitvector a} `{Bitvector b}.\n\nDefinition opt_def {a} (def:a) (v:option a) :=\nmatch v with\n| Some x => x\n| None => def\nend.\n\n(* The Lem version is partial, but lets go with BU here to avoid constraints for now *)\nDefinition access_bv_inc (v : a) n := opt_def BU (access_list_opt_inc (bits_of v) n).\nDefinition access_bv_dec (v : a) n := opt_def BU (access_list_opt_dec (bits_of v) n).\n\nDefinition update_bv_inc (v : a) n b := update_list true  (bits_of v) n b.\nDefinition update_bv_dec (v : a) n b := update_list false (bits_of v) n b.\n\nDefinition subrange_bv_inc (v : a) i j := subrange_list true  (bits_of v) i j.\nDefinition subrange_bv_dec (v : a) i j := subrange_list true  (bits_of v) i j.\n\nDefinition update_subrange_bv_inc (v : a) i j (v' : b) := update_subrange_list true  (bits_of v) i j (bits_of v').\nDefinition update_subrange_bv_dec (v : a) i j (v' : b) := update_subrange_list false (bits_of v) i j (bits_of v').\n\n(*val extz_bv : forall a b. Bitvector a, Bitvector b => Z -> a -> b*)\nDefinition extz_bv n (v : a) : option b := of_bits (extz_bits n (bits_of v)).\n\n(*val exts_bv : forall a b. Bitvector a, Bitvector b => Z -> a -> b*)\nDefinition exts_bv n (v : a) : option b := of_bits (exts_bits n (bits_of v)).\n\n(*val string_of_bv : forall a. Bitvector a => a -> string *)\nDefinition string_of_bv v := show_bitlist (bits_of v).\n\nEnd Bitvector_defs.\n\n(*** Bytes and addresses *)\n\nDefinition memory_byte := list bitU.\n\n(*val byte_chunks : forall a. list a -> option (list (list a))*)\nFixpoint byte_chunks {a} (bs : list a) := match bs with\n  | [] => Some []\n  | a::b::c::d::e::f::g::h::rest =>\n     match byte_chunks rest with\n     | None => None\n     | Some rest => Some ([a;b;c;d;e;f;g;h] :: rest)\n     end\n  | _ => None\nend.\n(*declare {isabelle} termination_argument byte_chunks = automatic*)\n\nSection BytesBits.\nContext {a} `{Bitvector a}.\n\n(*val bytes_of_bits : forall a. Bitvector a => a -> option (list memory_byte)*)\nDefinition bytes_of_bits (bs : a) := byte_chunks (bits_of bs).\n\n(*val bits_of_bytes : forall a. Bitvector a => list memory_byte -> a*)\nDefinition bits_of_bytes (bs : list memory_byte) : list bitU := List.concat (List.map bits_of bs).\n\nDefinition mem_bytes_of_bits (bs : a) := option_map (@rev (list bitU)) (bytes_of_bits bs).\nDefinition bits_of_mem_bytes (bs : list memory_byte) := bits_of_bytes (List.rev bs).\n\nEnd BytesBits.\n\n(*val bitv_of_byte_lifteds : list Sail_impl_base.byte_lifted -> list bitU\nDefinition bitv_of_byte_lifteds v :=\n  foldl (fun x (Byte_lifted y) => x ++ (List.map bitU_of_bit_lifted y)) [] v\n\nval bitv_of_bytes : list Sail_impl_base.byte -> list bitU\nDefinition bitv_of_bytes v :=\n  foldl (fun x (Byte y) => x ++ (List.map bitU_of_bit y)) [] v\n\nval byte_lifteds_of_bitv : list bitU -> list byte_lifted\nDefinition byte_lifteds_of_bitv bits :=\n  let bits := List.map bit_lifted_of_bitU bits in\n  byte_lifteds_of_bit_lifteds bits\n\nval bytes_of_bitv : list bitU -> list byte\nDefinition bytes_of_bitv bits :=\n  let bits := List.map bit_of_bitU bits in\n  bytes_of_bits bits\n\nval bit_lifteds_of_bitUs : list bitU -> list bit_lifted\nDefinition bit_lifteds_of_bitUs bits := List.map bit_lifted_of_bitU bits\n\nval bit_lifteds_of_bitv : list bitU -> list bit_lifted\nDefinition bit_lifteds_of_bitv v := bit_lifteds_of_bitUs v\n\n\nval address_lifted_of_bitv : list bitU -> address_lifted\nDefinition address_lifted_of_bitv v :=\n  let byte_lifteds := byte_lifteds_of_bitv v in\n  let maybe_address_integer :=\n    match (maybe_all (List.map byte_of_byte_lifted byte_lifteds)) with\n    | Some bs => Some (integer_of_byte_list bs)\n    | _ => None\n    end in\n  Address_lifted byte_lifteds maybe_address_integer\n\nval bitv_of_address_lifted : address_lifted -> list bitU\nDefinition bitv_of_address_lifted (Address_lifted bs _) := bitv_of_byte_lifteds bs\n\nval address_of_bitv : list bitU -> address\nDefinition address_of_bitv v :=\n  let bytes := bytes_of_bitv v in\n  address_of_byte_list bytes*)\n\nFixpoint reverse_endianness_list (bits : list bitU) :=\n  match bits with\n  | _ :: _ :: _ :: _ :: _ :: _ :: _ :: _ :: t =>\n    reverse_endianness_list t ++ firstn 8 bits\n  | _ => bits\n  end.\n\n(*** Registers *)\n\nDefinition register_field := string.\nDefinition register_field_index : Type := string * (Z * Z). (* name, start and end *)\n\nInductive register :=\n  | Register : string * (* name *)\n               Z * (* length *)\n               Z * (* start index *)\n               bool * (* is increasing *)\n               list register_field_index\n               -> register\n  | UndefinedRegister : Z -> register (* length *)\n  | RegisterPair : register * register -> register.\n\nRecord register_ref regstate regval a :=\n   { name : string;\n     (*is_inc : bool;*)\n     read_from : regstate -> a;\n     write_to : a -> regstate -> regstate;\n     of_regval : regval -> option a;\n     regval_of : a -> regval }.\nNotation \"{[ r 'with' 'name' := e ]}\" := ({| name := e; read_from := read_from r; write_to := write_to r; of_regval := of_regval r; regval_of := regval_of r |}).\nNotation \"{[ r 'with' 'read_from' := e ]}\" := ({| read_from := e; name := name r; write_to := write_to r; of_regval := of_regval r; regval_of := regval_of r |}).\nNotation \"{[ r 'with' 'write_to' := e ]}\" := ({| write_to := e; name := name r; read_from := read_from r; of_regval := of_regval r; regval_of := regval_of r |}).\nNotation \"{[ r 'with' 'of_regval' := e ]}\" := ({| of_regval := e; name := name r; read_from := read_from r; write_to := write_to r; regval_of := regval_of r |}).\nNotation \"{[ r 'with' 'regval_of' := e ]}\" := ({| regval_of := e; name := name r; read_from := read_from r; write_to := write_to r; of_regval := of_regval r |}).\nArguments name [_ _ _].\nArguments read_from [_ _ _].\nArguments write_to [_ _ _].\nArguments of_regval [_ _ _].\nArguments regval_of [_ _ _].\n\n(* Register accessors: pair of functions for reading and writing register values *)\nDefinition register_accessors regstate regval : Type :=\n  ((string -> regstate -> option regval) *\n   (string -> regval -> regstate -> option regstate)).\n\nRecord field_ref regtype a :=\n   { field_name : string;\n     field_start : Z;\n     field_is_inc : bool;\n     get_field : regtype -> a;\n     set_field : regtype -> a -> regtype }.\nArguments field_name [_ _].\nArguments field_start [_ _].\nArguments field_is_inc [_ _].\nArguments get_field [_ _].\nArguments set_field [_ _].\n\n(*\n(*let name_of_reg := function\n  | Register name _ _ _ _ => name\n  | UndefinedRegister _ => failwith \"name_of_reg UndefinedRegister\"\n  | RegisterPair _ _ => failwith \"name_of_reg RegisterPair\"\nend\n\nDefinition size_of_reg := function\n  | Register _ size _ _ _ => size\n  | UndefinedRegister size => size\n  | RegisterPair _ _ => failwith \"size_of_reg RegisterPair\"\nend\n\nDefinition start_of_reg := function\n  | Register _ _ start _ _ => start\n  | UndefinedRegister _ => failwith \"start_of_reg UndefinedRegister\"\n  | RegisterPair _ _ => failwith \"start_of_reg RegisterPair\"\nend\n\nDefinition is_inc_of_reg := function\n  | Register _ _ _ is_inc _ => is_inc\n  | UndefinedRegister _ => failwith \"is_inc_of_reg UndefinedRegister\"\n  | RegisterPair _ _ => failwith \"in_inc_of_reg RegisterPair\"\nend\n\nDefinition dir_of_reg := function\n  | Register _ _ _ is_inc _ => dir_of_bool is_inc\n  | UndefinedRegister _ => failwith \"dir_of_reg UndefinedRegister\"\n  | RegisterPair _ _ => failwith \"dir_of_reg RegisterPair\"\nend\n\nDefinition size_of_reg_nat reg := Z.to_nat (size_of_reg reg)\nDefinition start_of_reg_nat reg := Z.to_nat (start_of_reg reg)\n\nval register_field_indices_aux : register -> register_field -> option (Z * Z)\nFixpoint register_field_indices_aux register rfield :=\n  match register with\n  | Register _ _ _ _ rfields => List.lookup rfield rfields\n  | RegisterPair r1 r2 =>\n      let m_indices := register_field_indices_aux r1 rfield in\n      if isSome m_indices then m_indices else register_field_indices_aux r2 rfield\n  | UndefinedRegister _ => None\n  end\n\nval register_field_indices : register -> register_field -> Z * Z\nDefinition register_field_indices register rfield :=\n  match register_field_indices_aux register rfield with\n  | Some indices => indices\n  | None => failwith \"Invalid register/register-field combination\"\n  end\n\nDefinition register_field_indices_nat reg regfield=\n  let (i,j) := register_field_indices reg regfield in\n  (Z.to_nat i,Z.to_nat j)*)\n\n(*let rec external_reg_value reg_name v :=\n  let (internal_start, external_start, direction) :=\n    match reg_name with\n     | Reg _ start size dir =>\n        (start, (if dir = D_increasing then start else (start - (size +1))), dir)\n     | Reg_slice _ reg_start dir (slice_start, _) =>\n        ((if dir = D_increasing then slice_start else (reg_start - slice_start)),\n         slice_start, dir)\n     | Reg_field _ reg_start dir _ (slice_start, _) =>\n        ((if dir = D_increasing then slice_start else (reg_start - slice_start)),\n         slice_start, dir)\n     | Reg_f_slice _ reg_start dir _ _ (slice_start, _) =>\n        ((if dir = D_increasing then slice_start else (reg_start - slice_start)),\n         slice_start, dir)\n     end in\n  let bits := bit_lifteds_of_bitv v in\n  <| rv_bits           := bits;\n     rv_dir            := direction;\n     rv_start          := external_start;\n     rv_start_internal := internal_start |>\n\nval internal_reg_value : register_value -> list bitU\nDefinition internal_reg_value v :=\n  List.map bitU_of_bit_lifted v.rv_bits\n         (*(Z.of_nat v.rv_start_internal)\n         (v.rv_dir = D_increasing)*)\n\n\nDefinition external_slice (d:direction) (start:nat) ((i,j):(nat*nat)) :=\n  match d with\n  (*This is the case the thread/concurrecny model expects, so no change needed*)\n  | D_increasing => (i,j)\n  | D_decreasing => let slice_i = start - i in\n                    let slice_j = (i - j) + slice_i in\n                    (slice_i,slice_j)\n  end *)\n\n(* TODO\nDefinition external_reg_whole r :=\n  Reg (r.name) (Z.to_nat r.start) (Z.to_nat r.size) (dir_of_bool r.is_inc)\n\nDefinition external_reg_slice r (i,j) :=\n  let start := Z.to_nat r.start in\n  let dir := dir_of_bool r.is_inc in\n  Reg_slice (r.name) start dir (external_slice dir start (i,j))\n\nDefinition external_reg_field_whole reg rfield :=\n  let (m,n) := register_field_indices_nat reg rfield in\n  let start := start_of_reg_nat reg in\n  let dir := dir_of_reg reg in\n  Reg_field (name_of_reg reg) start dir rfield (external_slice dir start (m,n))\n\nDefinition external_reg_field_slice reg rfield (i,j) :=\n  let (m,n) := register_field_indices_nat reg rfield in\n  let start := start_of_reg_nat reg in\n  let dir := dir_of_reg reg in\n  Reg_f_slice (name_of_reg reg) start dir rfield\n              (external_slice dir start (m,n))\n              (external_slice dir start (i,j))*)\n\n(*val external_mem_value : list bitU -> memory_value\nDefinition external_mem_value v :=\n  byte_lifteds_of_bitv v $> List.reverse\n\nval internal_mem_value : memory_value -> list bitU\nDefinition internal_mem_value bytes :=\n  List.reverse bytes $> bitv_of_byte_lifteds*)\n\n\nval foreach : forall a vars.\n  (list a) -> vars -> (a -> vars -> vars) -> vars*)\nFixpoint foreach {a Vars} (l : list a) (vars : Vars) (body : a -> Vars -> Vars) : Vars :=\nmatch l with\n| [] => vars\n| (x :: xs) => foreach xs (body x vars) body\nend.\n\n(*declare {isabelle} termination_argument foreach = automatic\n\nval index_list : Z -> Z -> Z -> list Z*)\nFixpoint index_list' from to step n :=\n  if orb (andb (step >? 0) (from <=? to)) (andb (step <? 0) (to <=? from)) then\n    match n with\n    | O => []\n    | S n => from :: index_list' (from + step) to step n\n    end\n  else [].\n\nDefinition index_list from to step :=\n  if orb (andb (step >? 0) (from <=? to)) (andb (step <? 0) (to <=? from)) then\n    index_list' from to step (S (Z.abs_nat (from - to)))\n  else [].\n\nFixpoint foreach_Z' {Vars} from to step n (vars : Vars) (body : Z -> Vars -> Vars) : Vars :=\n  if orb (andb (step >? 0) (from <=? to)) (andb (step <? 0) (to <=? from)) then\n    match n with\n    | O => vars\n    | S n => let vars := body from vars in foreach_Z' (from + step) to step n vars body\n    end\n  else vars.\n\nDefinition foreach_Z {Vars} from to step vars body :=\n  foreach_Z' (Vars := Vars) from to step (S (Z.abs_nat (from - to))) vars body.\n\n(* Define these in proof mode to avoid anomalies related to abstract.\n   (See https://github.com/coq/coq/issues/10959) *)\n\nFixpoint foreach_Z_up' {Vars} (from to step off : Z) (n:nat) `{ArithFact (0 <? step)} `{ArithFact (0 <=? off)} (vars : Vars) (body : forall (z : Z) `(ArithFact ((from <=? z <=? to))), Vars -> Vars) {struct n} : Vars.\nrefine (\n  if sumbool_of_bool (from + off <=? to) then\n    match n with\n    | O => vars\n    | S n => let vars := body (from + off) _ vars in foreach_Z_up' _ from to step (off + step) n _ _ vars body\n    end\n  else vars\n).\nDefined.\n\nFixpoint foreach_Z_down' {Vars} from to step off (n:nat) `{ArithFact (0 <? step)} `{ArithFact (off <=? 0)} (vars : Vars) (body : forall (z : Z) `(ArithFact ((to <=? z <=? from))), Vars -> Vars) {struct n} : Vars.\nrefine (\n  if sumbool_of_bool (to <=? from + off) then\n    match n with\n    | O => vars\n    | S n => let vars := body (from + off) _ vars in foreach_Z_down' _ from to step (off - step) n _ _ vars body\n    end\n  else vars\n).\nDefined.\n\nDefinition foreach_Z_up {Vars} from to step vars body `{ArithFact (0 <? step)} :=\n    foreach_Z_up' (Vars := Vars) from to step 0 (S (Z.abs_nat (from - to))) vars body.\nDefinition foreach_Z_down {Vars} from to step vars body `{ArithFact (0 <? step)} :=\n    foreach_Z_down' (Vars := Vars) from to step 0 (S (Z.abs_nat (from - to))) vars body.\n\n(*val while : forall vars. vars -> (vars -> bool) -> (vars -> vars) -> vars\nFixpoint while vars cond body :=\n  if cond vars then while (body vars) cond body else vars\n\nval until : forall vars. vars -> (vars -> bool) -> (vars -> vars) -> vars\nFixpoint until vars cond body :=\n  let vars := body vars in\n  if cond vars then vars else until (body vars) cond body\n\n\nDefinition assert' b msg_opt :=\n  let msg := match msg_opt with\n  | Some msg => msg\n  | None  => \"unspecified error\"\n  end in\n  if b then () else failwith msg\n\n(* convert numbers unsafely to naturals *)\n\nclass (ToNatural a) val toNatural : a -> natural end\n(* eta-expanded for Isabelle output, otherwise it breaks *)\ninstance (ToNatural Z) let toNatural := (fun n => naturalFromInteger n) end\ninstance (ToNatural int)     let toNatural := (fun n => naturalFromInt n)     end\ninstance (ToNatural nat)     let toNatural := (fun n => naturalFromNat n)     end\ninstance (ToNatural natural) let toNatural := (fun n => n)                    end\n\nDefinition toNaturalFiveTup (n1,n2,n3,n4,n5) :=\n  (toNatural n1,\n   toNatural n2,\n   toNatural n3,\n   toNatural n4,\n   toNatural n5)\n\n(* Let the following types be generated by Sail per spec, using either bitlists\n   or machine words as bitvector representation *)\n(*type regfp :=\n  | RFull of (string)\n  | RSlice of (string * Z * Z)\n  | RSliceBit of (string * Z)\n  | RField of (string * string)\n\ntype niafp :=\n  | NIAFP_successor\n  | NIAFP_concrete_address of vector bitU\n  | NIAFP_indirect_address\n\n(* only for MIPS *)\ntype diafp :=\n  | DIAFP_none\n  | DIAFP_concrete of vector bitU\n  | DIAFP_reg of regfp\n\nDefinition regfp_to_reg (reg_info : string -> option string -> (nat * nat * direction * (nat * nat))) := function\n  | RFull name =>\n     let (start,length,direction,_) := reg_info name None in\n     Reg name start length direction\n  | RSlice (name,i,j) =>\n     let i = Z.to_nat i in\n     let j = Z.to_nat j in\n     let (start,length,direction,_) = reg_info name None in\n     let slice = external_slice direction start (i,j) in\n     Reg_slice name start direction slice\n  | RSliceBit (name,i) =>\n     let i = Z.to_nat i in\n     let (start,length,direction,_) = reg_info name None in\n     let slice = external_slice direction start (i,i) in\n     Reg_slice name start direction slice\n  | RField (name,field_name) =>\n     let (start,length,direction,span) = reg_info name (Some field_name) in\n     let slice = external_slice direction start span in\n     Reg_field name start direction field_name slice\nend\n\nDefinition niafp_to_nia reginfo = function\n  | NIAFP_successor => NIA_successor\n  | NIAFP_concrete_address v => NIA_concrete_address (address_of_bitv v)\n  | NIAFP_indirect_address => NIA_indirect_address\nend\n\nDefinition diafp_to_dia reginfo = function\n  | DIAFP_none => DIA_none\n  | DIAFP_concrete v => DIA_concrete_address (address_of_bitv v)\n  | DIAFP_reg r => DIA_register (regfp_to_reg reginfo r)\nend\n*)\n*)\n\n(* Arithmetic functions which return proofs that match the expected Sail\n   types in smt.sail. *)\n\nDefinition ediv_with_eq n m : {o : Z & ArithFact (o =? ZEuclid.div n m)} := build_ex (ZEuclid.div n m).\nDefinition emod_with_eq n m : {o : Z & ArithFact (o =? ZEuclid.modulo n m)} := build_ex (ZEuclid.modulo n m).\nDefinition abs_with_eq n   : {o : Z & ArithFact (o =? Z.abs n)} := build_ex (Z.abs n).\n\n(* Similarly, for ranges (currently in MIPS) *)\n\nDefinition eq_range {n m o p} (l : {l & ArithFact (n <=? l <=? m)}) (r : {r & ArithFact (o <=? r <=? p)}) : bool :=\n  (projT1 l) =? (projT1 r).\nDefinition add_range {n m o p} (l : {l & ArithFact (n <=? l <=? m)}) (r : {r & ArithFact (o <=? r <=? p)})\n  : {x & ArithFact (n+o <=? x <=? m+p)} :=\n  build_ex ((projT1 l) + (projT1 r)).\nDefinition sub_range {n m o p} (l : {l & ArithFact (n <=? l <=? m)}) (r : {r & ArithFact (o <=? r <=? p)})\n  : {x & ArithFact (n-p <=? x <=? m-o)} :=\n  build_ex ((projT1 l) - (projT1 r)).\nDefinition negate_range {n m} (l : {l : Z & ArithFact (n <=? l <=? m)})\n  : {x : Z & ArithFact ((- m) <=? x <=? (- n))} :=\n  build_ex (- (projT1 l)).\n\nDefinition min_atom (a : Z) (b : Z) : {c : Z & ArithFact (((c =? a) || (c =? b)) && (c <=? a) && (c <=? b))} :=\n  build_ex (Z.min a b).\nDefinition max_atom (a : Z) (b : Z) : {c : Z & ArithFact (((c =? a) || (c =? b)) && (c >=? a) && (c >=? b))} :=\n  build_ex (Z.max a b).\n\n\n(*** Generic vectors *)\n\nDefinition vec (T:Type) (n:Z) := { l : list T & length_list l = n }.\nDefinition vec_length {T n} (v : vec T n) := n.\nDefinition vec_access_dec {T n} (v : vec T n) m `{ArithFact ((0 <=? m <? n))} : T :=\n  access_list_dec (projT1 v) m.\n\nDefinition vec_access_inc {T n} (v : vec T n) m `{ArithFact (0 <=? m <? n)} : T :=\n  access_list_inc (projT1 v) m.\n\nProgram Definition vec_init {T} (t : T) (n : Z) `{ArithFact (n >=? 0)} : vec T n :=\n  existT _ (repeat [t] n) _.\nNext Obligation.\nintros.\ncbv beta.\nrewrite repeat_length. 2: apply Z_geb_ge, fact.\nunfold length_list.\nsimpl.\nauto with zarith.\nQed.\n\nDefinition vec_concat {T m n} (v : vec T m) (w : vec T n) : vec T (m + n).\nrefine (existT _ (projT1 v ++ projT1 w) _).\ndestruct v.\ndestruct w.\nsimpl.\nunfold length_list in *.\nrewrite <- e, <- e0.\nrewrite app_length.\nrewrite Nat2Z.inj_add.\nreflexivity.\nDefined.\n\nLemma skipn_length {A n} {l: list A} : (n <= List.length l -> List.length (skipn n l) = List.length l - n)%nat.\nrevert l.\ninduction n.\n* simpl. auto with arith.\n* intros l H.\n  destruct l.\n  + inversion H.\n  + simpl in H.\n    simpl.\n    rewrite IHn; auto with arith.\nQed.\nLemma update_list_inc_length {T} {l:list T} {m x} : 0 <= m < length_list l -> length_list (update_list_inc l m x) = length_list l.\nunfold update_list_inc, list_update, length_list.\nintro H.\nf_equal.\nassert ((0 <= Z.to_nat m < Datatypes.length l)%nat).\n{ destruct H as [H1 H2].\n  split.\n  + change 0%nat with (Z.to_nat 0).\n    apply Z2Nat.inj_le; auto with zarith.\n  + rewrite <- Nat2Z.id.\n    apply Z2Nat.inj_lt; auto with zarith.\n}\nrewrite app_length.\nrewrite firstn_length_le; only 2:lia.\ncbn -[skipn].\nrewrite skipn_length;\nlia.\nQed.\n\nProgram Definition vec_update_dec {T n} (v : vec T n) m t `{ArithFact (0 <=? m <? n)} : vec T n := existT _ (update_list_dec (projT1 v) m t) _.\nNext Obligation.\nintros; cbv beta.\nunfold update_list_dec.\nrewrite update_list_inc_length.\n+ destruct v. apply e.\n+ destruct H as [H].\n  unbool_comparisons.\n  destruct v. simpl (projT1 _). rewrite e.\n  lia.\nQed.\n\nProgram Definition vec_update_inc {T n} (v : vec T n) m t `{ArithFact (0 <=? m <? n)} : vec T n := existT _ (update_list_inc (projT1 v) m t) _.\nNext Obligation.\nintros; cbv beta.\nrewrite update_list_inc_length.\n+ destruct v. apply e.\n+ destruct H.\n  unbool_comparisons.\n  destruct v. simpl (projT1 _). rewrite e.\n  auto.\nQed.\n\nProgram Definition vec_map {S T} (f : S -> T) {n} (v : vec S n) : vec T n := existT _ (List.map f (projT1 v)) _.\nNext Obligation.\ndestruct v as [l H].\ncbn.\nunfold length_list.\nrewrite map_length.\napply H.\nQed.\n\nProgram Definition just_vec {A n} (v : vec (option A) n) : option (vec A n) :=\n  match just_list (projT1 v) with\n  | None => None\n  | Some v' => Some (existT _ v' _)\n  end.\nNext Obligation.\nintros; cbv beta.\nrewrite <- (just_list_length_Z _ _ Heq_anonymous).\ndestruct v.\nassumption.\nQed.\n\nDefinition list_of_vec {A n} (v : vec A n) : list A := projT1 v.\n\nDefinition vec_eq_dec {T n} (D : forall x y : T, {x = y} + {x <> y}) (x y : vec T n) :\n  {x = y} + {x <> y}.\nrefine (if List.list_eq_dec D (projT1 x) (projT1 y) then left _ else right _).\n* apply eq_sigT_hprop; auto using ZEqdep.UIP.\n* contradict n0. rewrite n0. reflexivity.\nDefined.\n\nInstance Decidable_eq_vec {T : Type} {n} `(DT : forall x y : T, Decidable (x = y)) :\n  forall x y : vec T n, Decidable (x = y).\nrefine (fun x y => {|\n  Decidable_witness := proj1_sig (bool_of_sumbool (vec_eq_dec (fun x y => generic_dec x y) x y))\n|}).\ndestruct (vec_eq_dec _ x y); simpl; split; congruence.\nDefined.\n\nProgram Definition vec_of_list {A} n (l : list A) : option (vec A n) :=\n  if sumbool_of_bool (n =? length_list l) then Some (existT _ l _) else None.\nNext Obligation.\nsymmetry.\napply Z.eqb_eq.\nassumption.\nQed.\n\nDefinition vec_of_list_len {A} (l : list A) : vec A (length_list l) := existT _ l (eq_refl _).\n\nDefinition map_bind {A B} (f : A -> option B) (a : option A) : option B :=\nmatch a with\n| Some a' => f a'\n| None => None\nend.\n\nDefinition sub_nat (x : Z) `{ArithFact (x >=? 0)} (y : Z) `{ArithFact (y >=? 0)} :\n  {z : Z & ArithFact (z >=? 0)} :=\n  let z := x - y in\n  if sumbool_of_bool (z >=? 0) then build_ex z else build_ex 0.\n\nDefinition min_nat (x : Z) `{ArithFact (x >=? 0)} (y : Z) `{ArithFact (y >=? 0)} :\n  {z : Z & ArithFact (z >=? 0)} :=\n  build_ex (Z.min x y).\n\nDefinition max_nat (x : Z) `{ArithFact (x >=? 0)} (y : Z) `{ArithFact (y >=? 0)} :\n  {z : Z & ArithFact (z >=? 0)} :=\n  build_ex (Z.max x y).\n\nDefinition shl_int_1 (x y : Z) `{HE:ArithFact (x =? 1)} `{HR:ArithFact (0 <=? y <=? 3)}: {z : Z & ArithFact (member_Z_list z [1;2;4;8])}.\nrefine (existT _ (shl_int x y) _).\ndestruct HE as [HE].\ndestruct HR as [HR].\nunbool_comparisons.\nassert (y = 0 \\/ y = 1 \\/ y = 2 \\/ y = 3) by lia.\nconstructor.\nintuition (subst; compute; auto).\nDefined.\n\nDefinition shl_int_8 (x y : Z) `{HE:ArithFact (x =? 8)} `{HR:ArithFact (0 <=? y <=? 3)}: {z : Z & ArithFact (member_Z_list z [8;16;32;64])}.\nrefine (existT _ (shl_int x y) _).\ndestruct HE as [HE].\ndestruct HR as [HR].\nunbool_comparisons.\nassert (y = 0 \\/ y = 1 \\/ y = 2 \\/ y = 3) by lia.\nconstructor.\nintuition (subst; compute; auto).\nDefined.\n\nDefinition shl_int_32 (x y : Z) `{HE:ArithFact (x =? 32)} `{HR:ArithFact (member_Z_list y [0;1])}: {z : Z & ArithFact (member_Z_list z [32;64])}.\nrefine (existT _ (shl_int x y) _).\ndestruct HE as [HE].\ndestruct HR as [HR].\nconstructor.\nunbool_comparisons.\ndestruct HR as [HR | [HR | []]];\nsubst; compute;\nauto.\nDefined.\n\nDefinition shr_int_32 (x y : Z) `{HE:ArithFact (0 <=? x <=? 31)} `{HR:ArithFact (y =? 1)}: {z : Z & ArithFact (0 <=? z <=? 15)}.\nrefine (existT _ (shr_int x y) _).\nabstract (\n  destruct HE as [HE];\n  destruct HR as [HR];\n  unbool_comparisons;\n  subst;\n  constructor;\n  unbool_comparisons_goal;\n  unfold shr_int;\n  rewrite <- Z.div2_spec;\n  rewrite Z.div2_div;\n  specialize (Z.div_mod x 2);\n  specialize (Z.mod_pos_bound x 2);\n  generalize (Z.div x 2);\n  generalize (x mod 2);\n  intros;\n  nia).\nDefined.\n\nLemma shl_8_ge_0 {n} : shl_int 8 n >= 0.\nunfold shl_int.\napply Z.le_ge.  \napply <- Z.shiftl_nonneg.\nlia.\nQed.\nHint Resolve shl_8_ge_0 : sail.\n\n(* This is needed because Sail's internal constraint language doesn't have\n   < and could disappear if we add it... *)\n\nLemma sail_lt_ge (x y : Z) :\n  x < y <-> y >= x +1.\nlia.\nQed.\nHint Resolve sail_lt_ge : sail.\n", "meta": {"author": "CTSRD-CHERI", "repo": "sail-cheri-mips", "sha": "13a9c3fb0c3f8d320d4f4650a63d23d3a8b12724", "save_path": "github-repos/coq/CTSRD-CHERI-sail-cheri-mips", "path": "github-repos/coq/CTSRD-CHERI-sail-cheri-mips/sail-cheri-mips-13a9c3fb0c3f8d320d4f4650a63d23d3a8b12724/prover_snapshots/coq/cheri-mips-snapshot/lib/sail/Values.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2362264894431585}}
{"text": "Require Import Coq.Strings.String Coq.Strings.Ascii Coq.Lists.List.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Reflective.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.Gensym.\n\nDelimit Scope item_scope with item.\nBind Scope item_scope with item.\nDelimit Scope production_scope with production.\nDelimit Scope prod_assignment_scope with prod_assignment.\nBind Scope production_scope with production.\nDelimit Scope productions_scope with productions.\nDelimit Scope productions_assignment_scope with prods_assignment.\nBind Scope productions_scope with productions.\nDelimit Scope grammar_scope with grammar.\nBind Scope grammar_scope with grammar.\n\n(** [abstract] doesn't work in definitions *)\nClass NoDupR {T} beq (ls : list T) := nodupr : uniquize beq ls = ls.\nHint Extern 5 (NoDupR _ _) => clear; (*abstract*) (vm_compute; reflexivity) : typeclass_instances.\n\nDefinition list_to_productions {T} (default : T) (ls : list (string * T)) : string -> T\n  := fun nt\n     => option_rect\n          (fun _ => T)\n          snd\n          default\n          (find (fun k => string_beq nt (fst k)) ls).\n\nRecord pregrammar Char :=\n  {\n    pregrammar_rproductions : list (string * rproductions Char);\n    pregrammar_idata : interp_RCharExpr_data Char;\n    pregrammar_rnonterminals : list string\n    := map fst pregrammar_rproductions;\n    rnonterminals_unique\n    : NoDupR string_beq pregrammar_rnonterminals;\n    RLookup_idx : nat -> rproductions Char\n    := fun n => nth n (map snd pregrammar_rproductions) nil\n  }.\n\nGlobal Existing Instance pregrammar_idata.\n\nRecord pregrammar' (Char : Type) :=\n  {\n    pregrammar_productions :> list (string * productions Char);\n    pregrammar_nonterminals : list string\n    := map fst pregrammar_productions;\n    invalid_nonterminal : string\n    := gensym pregrammar_nonterminals;\n    Lookup_idx : nat -> productions Char\n    := fun n => nth n (map snd pregrammar_productions) nil;\n    Lookup_string : string -> productions Char\n    := list_to_productions nil pregrammar_productions;\n    nonterminals_unique\n    : NoDupR string_beq pregrammar_nonterminals\n  }.\n\nGlobal Arguments pregrammar_nonterminals / .\nGlobal Arguments Lookup_idx {_} !_ !_  / .\nGlobal Arguments Lookup_string {_} !_ !_ / .\n\nExisting Instance nonterminals_unique.\nArguments nonterminals_unique {_} _.\n\nDefinition pregrammar'_of_pregrammar {Char} (g : pregrammar Char) : pregrammar' Char.\nProof.\n  eapply {| pregrammar_productions := List.map (fun xy => (fst xy, interp_rproductions (snd xy))) (pregrammar_rproductions g) |}.\n  Grab Existential Variables.\n  2:eapply (pregrammar_idata g). (* wheee, dependent subgoals in Coq 8.4 *)\n  abstract (\n      rewrite map_map; simpl;\n      apply (rnonterminals_unique g)\n    ).\nDefined.\n\nCoercion pregrammar'_of_pregrammar : pregrammar >-> pregrammar'.\n\nCoercion grammar_of_pregrammar {Char} (g : pregrammar' Char) : grammar Char\n  := {| Start_symbol := hd \"\"%string (pregrammar_nonterminals g);\n        Lookup := Lookup_string g;\n        Valid_nonterminals := (pregrammar_nonterminals g) |}.\n\nGlobal Instance valid_nonterminals_unique {Char} {G : pregrammar' Char}\n: NoDupR string_beq (Valid_nonterminals G)\n  := nonterminals_unique _.\n\nDefinition list_to_grammar {T} (default : productions T) (ls : list (string * productions T)) : grammar T\n  := {| Start_symbol := hd \"\"%string (map fst ls);\n        Lookup := list_to_productions default ls;\n        Valid_nonterminals := map fst ls |}.\n\nGlobal Arguments list_to_grammar {_} _ _.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_eapply_example/src/Parsers/ContextFreeGrammar/PreNotations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.23622648944315847}}
{"text": "Require Import\n        Coq.Strings.String\n        Coq.Vectors.Vector.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Common.BoundedLookup\n        Fiat.Common.ilist\n        Fiat.Computation\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.BinEncoders.Env.BinLib.Core\n        Fiat.BinEncoders.Env.Common.Specs\n        Fiat.BinEncoders.Env.Common.WordFacts\n        Fiat.BinEncoders.Env.Common.ComposeCheckSum\n        Fiat.BinEncoders.Env.Common.ComposeIf\n        Fiat.BinEncoders.Env.Common.ComposeOpt\n        Fiat.BinEncoders.Env.Automation.Solver\n        Fiat.BinEncoders.Env.Lib2.Bool\n        Fiat.BinEncoders.Env.Lib2.Option\n        Fiat.BinEncoders.Env.Lib2.FixListOpt\n        Fiat.BinEncoders.Env.Lib2.NoCache\n        Fiat.BinEncoders.Env.Lib2.WordOpt\n        Fiat.BinEncoders.Env.Lib2.NatOpt\n        Fiat.BinEncoders.Env.Lib2.Vector\n        Fiat.BinEncoders.Env.Lib2.EnumOpt\n        Fiat.BinEncoders.Env.Lib2.SumTypeOpt\n        Fiat.BinEncoders.Env.Lib2.IPChecksum.\n\nRequire Import Bedrock.Word.\n\nImport Vectors.VectorDef.VectorNotations.\nOpen Scope string_scope.\nOpen Scope Tuple_scope.\n\n(* Start Example Derivation. *)\nSection TCPPacketDecoder.\n\n  Definition TCP_Packet :=\n    @Tuple <\"SourcePort\" :: word 16,\n    \"DestPort\" :: word 16,\n    \"SeqNumber\" :: word 32,\n    \"AckNumber\" :: word 32,\n    \"NS\" :: bool, (* ECN-nonce concealment protection flag *)\n    \"CWR\" :: bool, (* Congestion Window Reduced (CWR) flag *)\n    \"ECE\" :: bool, (* ECN-Echo flag *)\n    (* We can infer the URG flag from the Urgent Pointer field *)\n    \"ACK\" :: bool, (* Acknowledgment field is significant flag *)\n    \"PSH\" :: bool, (* Push function flag *)\n    \"RST\" :: bool, (* Reset the connection flag *)\n    \"SYN\" :: bool, (* Synchronize sequence numbers flag *)\n    \"FIN\" :: bool, (* No more data from sender flag*)\n    \"WindowSize\" :: word 16,\n    \"UrgentPointer\" :: option (word 16),\n    \"Options\" :: list (word 32),\n    \"Payload\" :: list char >.\n\n  (* These values are provided by the IP header for checksum calculation.*)\n\n  Variable srcAddr : word 32.\n  Variable destAddr : word 32.\n  Variable tcpLength : word 16.\n\n  Definition TCP_Checksum_Valid\n             (n : nat)\n             (b : ByteString)\n    := IPChecksum_Valid (96 + n)\n       (transform (transform (encode_word srcAddr)\n                  (transform (encode_word destAddr)\n                  (transform (encode_word (wzero 8))\n                  (transform (encode_word (natToWord 8 6))\n                  (encode_word tcpLength)))))\n                  b).\n\n  Definition encode_TCP_Packet_Spec\n             (tcp : TCP_Packet) :=\n         (      encode_word_Spec (tcp!\"SourcePort\")\n          ThenC encode_word_Spec (tcp!\"DestPort\")\n          ThenC encode_word_Spec (tcp!\"SeqNumber\")\n          ThenC encode_word_Spec (tcp!\"AckNumber\")\n          ThenC encode_nat_Spec 4 (5 + |tcp!\"Options\"|)\n          ThenC encode_unused_word_Spec 3 (* These bits are reserved for future use. *)\n          ThenC encode_bool_Spec tcp!\"NS\"\n          ThenC encode_bool_Spec tcp!\"CWR\"\n          ThenC encode_bool_Spec tcp!\"ECE\"\n          ThenC encode_bool_Spec (match tcp!\"UrgentPointer\" with\n                                  | Some _ => true\n                                  | _ => false\n                                  end)\n          ThenC encode_bool_Spec tcp!\"ACK\"\n          ThenC encode_bool_Spec tcp!\"PSH\"\n          ThenC encode_bool_Spec tcp!\"RST\"\n          ThenC encode_bool_Spec tcp!\"SYN\"\n          ThenC encode_bool_Spec tcp!\"FIN\"\n          ThenC encode_word_Spec tcp!\"WindowSize\" DoneC)\nThenChecksum (TCP_Checksum_Valid) OfSize 16\nThenCarryOn (encode_option_Spec encode_word_Spec (encode_unused_word_Spec' 16 ByteString_id) tcp!\"UrgentPointer\"\n       ThenC encode_list_Spec encode_word_Spec tcp!\"Options\"\n       ThenC encode_list_Spec encode_word_Spec tcp!\"Payload\" DoneC).\n\n  Definition TCP_Packet_OK (tcp : TCP_Packet) :=\n    lt (|tcp!\"Options\"|) 11\n    /\\ wordToNat tcpLength = 20 (* length of packet header *)\n                             + (4 * |tcp!\"Options\"|) (* length of option field *)\n                             + (|tcp!\"Payload\"|).\n\n  Local Arguments NPeano.modulo : simpl never.\n\n  Definition TCP_Length :=\n    (fun _ : ByteString => (wordToNat tcpLength) * 8).\n\n  Lemma TCP_Packet_Header_Len_OK\n    : forall (tcp : TCP_Packet) (ctx ctx' ctx'' : CacheEncode) (c : word 16) (b b'' ext : ByteString),\n      (      encode_word_Spec (tcp!\"SourcePort\")\n          ThenC encode_word_Spec (tcp!\"DestPort\")\n          ThenC encode_word_Spec (tcp!\"SeqNumber\")\n          ThenC encode_word_Spec (tcp!\"AckNumber\")\n          ThenC encode_nat_Spec 4 (5 + |tcp!\"Options\"|)\n          ThenC encode_unused_word_Spec 3 (* These bits are reserved for future use. *)\n          ThenC encode_bool_Spec tcp!\"NS\"\n          ThenC encode_bool_Spec tcp!\"CWR\"\n          ThenC encode_bool_Spec tcp!\"ECE\"\n          ThenC encode_bool_Spec (match tcp!\"UrgentPointer\" with\n                                  | Some _ => true\n                                  | _ => false\n                                  end)\n          ThenC encode_bool_Spec tcp!\"ACK\"\n          ThenC encode_bool_Spec tcp!\"PSH\"\n          ThenC encode_bool_Spec tcp!\"RST\"\n          ThenC encode_bool_Spec tcp!\"SYN\"\n          ThenC encode_bool_Spec tcp!\"FIN\"\n          ThenC encode_word_Spec tcp!\"WindowSize\" DoneC) ctx ↝ (b, ctx') ->\n      (encode_option_Spec encode_word_Spec (encode_unused_word_Spec' 16 ByteString_id) tcp!\"UrgentPointer\"\n       ThenC encode_list_Spec encode_word_Spec tcp!\"Options\"\n       ThenC encode_list_Spec encode_word_Spec tcp!\"Payload\" DoneC) ctx' ↝ (b'', ctx'') ->\n      (lt (|tcp!\"Options\"|) 11\n       /\\ wordToNat tcpLength = 20 (* length of packet header *)\n                                + (4 * |tcp!\"Options\"|) (* length of option field *)\n                                + (|tcp!\"Payload\"|)) ->\n      (fun _ : TCP_Packet =>\n    16 +\n    (16 + (32 + (32 + (4 + (3 + (1 + (1 + (1 + (1 + (1 + (1 + (1 + (1 + (1 + (16 + length_ByteString ByteString_id))))))))))))))))\n     tcp +\n   (fun a0 : TCP_Packet =>\n    16 + ((|a0!\"Options\"|) * 32 + ((|a0!\"Payload\" |) * 8 + length_ByteString ByteString_id))) tcp + 16 =\n    (TCP_Length\n       (transform (transform b (transform (encode_checksum ByteString transformer ByteString_QueueTransformerOpt 16 c) b'')) ext)).\nProof.\n  intros.\n  intros; change transform_id with ByteString_id; rewrite length_ByteString_ByteString_id.\n  unfold TCP_Length; rewrite (proj2 H1).\n  match goal with\n    |- context [ @length ?A ?l] => remember (@length A l)\n  end.\n  match goal with\n    |- context [ @length ?A ?l] => remember (@length A l)\n  end.\n  omega.\nQed.\n\nDefinition TCP_Packet_decoder'\n  : CorrectDecoderFor TCP_Packet_OK encode_TCP_Packet_Spec.\nProof.\n  start_synthesizing_decoder.\n  normalize_compose transformer.\n  apply_IPChecksum_dep TCP_Packet_Header_Len_OK.\n\n  - unfold TCP_Packet_OK; intros ? H'; repeat split.\n    simpl; destruct H'.\n    unfold pow2; simpl in *.\n    unfold GetAttribute, GetAttributeRaw in H0; simpl in H0.\n    revert H0; clear; unfold StringId13; intros; omega.\n\n  - decode_step idtac.\n    decode_step idtac.\n    decode_step idtac.\n    decode_step idtac.\n\n    simpl in *. intros; split_and; decompose_pair_hyp.\n    instantiate (1 := fst (snd (snd (snd (snd (snd (snd (snd (snd proj))))))))).\n    \n    first [ rewrite <- H12\n          | rewrite <- H13 ].\n    match goal with\n      |- context [decides (negb match ?b with _ => _ end) (?b' = None) ] =>\n      assert (b = b') as H' by reflexivity; rewrite H'; destruct b';\n        simpl; intuition eauto\n    end.\n    discriminate.\n    destruct a'; intros; exact I.\n\n    decode_step idtac.\n    decode_step idtac.\n    decode_step idtac.\n\n    simpl in *. intros; split_and. decompose_pair_hyp.\n    simpl; intros; instantiate (1 := fst (snd (snd (snd (snd proj)))) - 5).\n    intuition; subst; simpl; auto with arith.\n    first [ rewrite <- H12\n          | rewrite <- H11]; simpl in *; auto with arith.\n\n    decode_step idtac.\n    decode_step idtac.\n    decode_step idtac.\n    decode_step idtac.\n\n    simpl in *; intros.\n    do 4 destruct H3.\n    split; eauto.\n    instantiate (1 := (wordToNat tcpLength) - 20 - (4 * (fst (snd (snd (snd (snd proj)))) - 5))).\n    first [ rewrite <- H6\n          | rewrite <- H5].\n    rewrite H7.\n    unfold snd, fst.\n    unfold GetAttribute, GetAttributeRaw in *; simpl in *.\n    repeat match goal with\n             |- context [ @length ?A (prim_fst ?l)] => remember (@length A (prim_fst l))\n           end.\n    assert (n = n1) by (subst; reflexivity).\n    rewrite H8; clear; omega.\n\n    decode_step idtac.\n    decode_step idtac.\n\n  - synthesize_cache_invariant.\n  - optimize_decoder_impl.\n\n    Time Defined.\n\n  Definition TCP_Packet_decoder_impl :=\n    Eval simpl in (fst (projT1 TCP_Packet_decoder')).\n\nEnd TCPPacketDecoder.\n\nPrint TCP_Packet_decoder_impl.\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/BinEncoders/Env/Examples/TCP_Packet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2361488674846436}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Bool.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import ZArith NArith Nnat Ndec Ndigits.\nFrom IntMap Require Import Map.\nFrom IntMap Require Import Allmaps.\nRequire Import List.\nRequire Import Wf_nat.\n\nRequire Import misc.\nRequire Import bool_fun.\nRequire Import config.\nRequire Import myMap.\n\nSection BDDgc.\n\nDefinition set_closed (bs : BDDstate) (marked : Map unit) :=\n  forall node node' : ad,\n  in_dom _ node marked = true ->\n  nodes_reachable bs node node' ->\n  in_dom _ node' bs = true -> in_dom _ node' marked = true.\n\nFixpoint add_used_nodes_1 (bs : BDDstate) (node : ad) \n (marked : Map unit) (bound : nat) {struct bound} : \n Map unit :=\n  match bound with\n  | O => (* Error *)  M0 unit\n  | S bound' =>\n      match MapGet _ marked node with\n      | None =>\n          match MapGet _ bs node with\n          | None => marked\n          | Some (x, (l, r)) =>\n              MapPut _\n                (add_used_nodes_1 bs r (add_used_nodes_1 bs l marked bound')\n                   bound') node tt\n          end\n      | Some tt => marked\n      end\n  end.\n\nDefinition add_used_nodes (bs : BDDstate) (node : ad) \n  (marked : Map unit) :=\n  add_used_nodes_1 bs node marked (S (nat_of_N (bs_node_height bs node))).\n\nDefinition mark (bs : BDDstate) (used : list ad) :=\n  fold_right (add_used_nodes bs) (M0 unit) used.\n\nDefinition new_bs (bs : BDDstate) (used : list ad) :=\n  MapDomRestrTo _ _ bs (mark bs used).\n\nDefinition new_fl (bs : BDDstate) (used : list ad) \n  (fl : BDDfree_list) :=\n  MapDomRestrByApp1 _ _ (fun a0 : ad => a0) fl bs (mark bs used).\n\nDefinition used_node_bs_1 (marked : Map unit) (node : ad) :=\n  match MapGet _ marked node with\n  | Some _ => true\n  | None => Neqb node BDDzero || Neqb node BDDone\n  end.\n\nFixpoint clean'1_1 (pf : ad -> ad) (m' : Map unit) \n (m : Map ad) {struct m} : Map ad :=\n  match m with\n  | M0 => m\n  | M1 a a' =>\n      if used_node_bs_1 m' (pf a) && used_node_bs_1 m' a' then m else M0 _\n  | M2 m1 m2 =>\n      makeM2 _ (clean'1_1 (fun a0 : ad => pf (Ndouble a0)) m' m1)\n        (clean'1_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m2)\n  end.\n\nDefinition clean'1 (m : Map ad) (m' : Map unit) :=\n  clean'1_1 (fun a : ad => a) m' m.\n(* Cleans memoization table  for negation *)\n\nFixpoint clean'2_1 (pf : ad -> ad) (m' : Map unit) \n (m : Map (Map ad)) {struct m} : Map (Map ad) :=\n  match m with\n  | M0 => m\n  | M1 a y =>\n      if used_node_bs_1 m' (pf a) then M1 _ a (clean'1 y m') else M0 _\n  | M2 m1 m2 =>\n      makeM2 _ (clean'2_1 (fun a0 : ad => pf (Ndouble a0)) m' m1)\n        (clean'2_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m2)\n  end.\n\nDefinition clean'2 (m : Map (Map ad)) (m' : Map unit) :=\n  clean'2_1 (fun a : ad => a) m' m.\n(* Cleans memoization table for disjunction *)\n\nFixpoint clean1 (m' : Map unit) (m : Map ad) {struct m} : \n Map ad :=\n  match m with\n  | M0 => m\n  | M1 a a' => if used_node_bs_1 m' a' then m else M0 _\n  | M2 m1 m2 => makeM2 _ (clean1 m' m1) (clean1 m' m2)\n  end.\n\nFixpoint clean2_1 (pf : ad -> ad) (m' : Map unit) (m : Map (Map ad))\n {struct m} : Map (Map ad) :=\n  match m with\n  | M0 => m\n  | M1 a y => if used_node_bs_1 m' (pf a) then M1 _ a (clean1 m' y) else M0 _\n  | M2 m1 m2 =>\n      makeM2 _ (clean2_1 (fun a0 : ad => pf (Ndouble a0)) m' m1)\n        (clean2_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m2)\n  end.\n\nDefinition clean2 (m : Map (Map ad)) (m' : Map unit) :=\n  clean2_1 (fun a : ad => a) m' m.\n\nFixpoint clean3_1 (pf : ad -> ad) (m' : Map unit) (m : Map (Map (Map ad)))\n {struct m} : Map (Map (Map ad)) :=\n  match m with\n  | M0 => m\n  | M1 a y => if used_node_bs_1 m' (pf a) then M1 _ a (clean2 y m') else M0 _\n  | M2 m1 m2 =>\n      makeM2 _ (clean3_1 (fun a0 : ad => pf (Ndouble a0)) m' m1)\n        (clean3_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m2)\n  end.\n\nDefinition clean3 (m : Map (Map (Map ad))) (m' : Map unit) :=\n  clean3_1 (fun a : ad => a) m' m.\n(* Cleans sharing map *)\n\nInductive dummy_mark : Set :=\n    DM : Map unit -> dummy_mark.\n\nDefinition gc_0 (cfg : BDDconfig) (used : list ad) :=\n  match cfg with\n  | (bs, (share, (fl, (cnt, (negm, (orm, um)))))) =>\n      match DM (mark bs used) with\n      | DM marked =>\n          let bs' := MapDomRestrTo _ _ bs marked in\n          let fl' :=\n            MapDomRestrByApp1 _ _ (fun a0 : ad => a0) fl bs marked in\n          let share' := clean3 share marked in\n          let negm' := clean'1 negm marked in\n          let orm' := clean'2 orm marked in\n          let um' := clean2 um marked in\n          (bs', (share', (fl', (cnt, (negm', (orm', um'))))))\n      end\n  end.\n\nDefinition gc_inf (cfg : BDDconfig) (used : list ad) := cfg.\n\n(* Temporary *)\nDefinition is_nil (A : Set) (l : list A) :=\n  match l with\n  | nil => true\n  | _ => false\n  end.\n\n(* inefficient because Nleb works by converting from ad to nat *)\nDefinition gc_x (x : ad) (cfg : BDDconfig) :=\n  if is_nil _ (fst (snd (snd cfg))) && Nleb x (fst (snd (snd (snd cfg))))\n  then gc_0 cfg\n  else gc_inf cfg.\n\n(* efficient version of gc_x *)\nDefinition gc_x_opt (x : ad) (cfg : BDDconfig) :=\n  match fl_of_cfg cfg with\n  | nil =>\n      match BDDcompare x (cnt_of_cfg cfg) with\n      | Datatypes.Lt => gc_0 cfg\n      | _ => gc_inf cfg\n      end\n  | _ => gc_inf cfg\n  end.\n\nLemma add_used_nodes_1_lemma_1 :\n forall (bound : nat) (bs : BDDstate) (node : ad) (marked : Map unit),\n BDDstate_OK bs ->\n nat_of_N (bs_node_height bs node) < bound ->\n forall node' : ad,\n in_dom _ node' marked = true ->\n in_dom _ node' (add_used_nodes_1 bs node marked bound) = true.\nProof.\n  simple induction bound.  intros bs node marked H00.  intros.\n  absurd (nat_of_N (bs_node_height bs node) < 0).  apply lt_n_O.  assumption.\n  intros n H bs node marked H00.  intros.  simpl in |- *.  elim (option_sum _ (MapGet _ marked node)).\n  intro y.  elim y; clear y.  intros u H2.  rewrite H2.  simpl in |- *.  elim u.\n  assumption.  intro y.  rewrite y.  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) bs node)).\n  intro y0.  elim y0; clear y0.  intro x.  elim x; clear x.  intros x y0.\n  elim y0; clear y0; intros l r.  intro y0.  rewrite y0.  unfold in_dom in |- *.\n  rewrite\n   (MapPut_semantics unit\n      (add_used_nodes_1 bs r (add_used_nodes_1 bs l marked n) n) node tt\n      node').\n  elim (sumbool_of_bool (Neqb node node')).  intro y1.  rewrite y1.  reflexivity.\n  intro y1.  rewrite y1.  cut (in_dom _ node' (add_used_nodes_1 bs l marked n) = true).\n  intro.  cut\n   (in_dom _ node' (add_used_nodes_1 bs r (add_used_nodes_1 bs l marked n) n) =\n    true).\n  intro.  unfold in_dom in H3.  elim\n   (option_sum _\n      (MapGet unit (add_used_nodes_1 bs r (add_used_nodes_1 bs l marked n) n)\n         node')).\n  intro y2.  elim y2; intros x0 y3.  rewrite y3.  reflexivity.  intro y2.  rewrite y2 in H3.\n  discriminate.  apply H.  assumption.  apply lt_trans_1 with (y := nat_of_N (bs_node_height bs node)).\n  apply BDDcompare_lt.  apply bs_node_height_right with (bs := bs) (x := x) (l := l) (r := r).\n  assumption.  assumption.  assumption.  assumption.  apply H.  assumption.\n  apply lt_trans_1 with (y := nat_of_N (bs_node_height bs node)).  apply BDDcompare_lt.\n  apply bs_node_height_left with (bs := bs) (x := x) (l := l) (r := r).  assumption.  assumption.\n  assumption.  assumption.  intro y0.  rewrite y0.  assumption.\nQed.\n\nLemma add_used_nodes_1_lemma_2 :\n forall (bound : nat) (bs : BDDstate) (node : ad) (marked : Map unit),\n BDDstate_OK bs ->\n nat_of_N (bs_node_height bs node) < bound ->\n set_closed bs marked ->\n (forall node' : ad,\n  nodes_reachable bs node node' /\\ in_dom _ node' bs = true ->\n  in_dom _ node' (add_used_nodes_1 bs node marked bound) = true) /\\\n (forall node' : ad,\n  in_dom _ node' (add_used_nodes_1 bs node marked bound) = true ->\n  in_dom _ node' marked = true \\/\n  in_dom _ node' bs = true /\\ nodes_reachable bs node node') /\\\n set_closed bs (add_used_nodes_1 bs node marked bound).\nProof.\n  simple induction bound.  intros.  absurd (nat_of_N (bs_node_height bs node) < 0).\n  apply lt_n_O.  assumption.  intros n H bs node marked H00.  intros.  simpl in |- *.\n  elim (option_sum _ (MapGet _ marked node)).\n  intro y.  elim y; clear y.  intros u H2.  rewrite H2.  simpl in |- *.  elim u.  split.\n  intros.  unfold set_closed in H1.  apply H1 with (node := node).  unfold in_dom in |- *.\n  rewrite H2.  reflexivity.  exact (proj1 H3).  exact (proj2 H3).\n  split.  intros.  left; assumption.  assumption.  intro y.  rewrite y.\n  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) bs node)).  intro y0.  elim y0; clear y0.\n  intro x.  elim x; clear x.  intros x y0.  elim y0; clear y0; intros l r.\n  intros y0.  rewrite y0.  cut (exists markedl : Map unit, markedl = add_used_nodes_1 bs l marked n).\n  intro.  elim H2; clear H2.  intro markedl.  intros.  rewrite <- H2.\n  cut (exists markedr : Map unit, markedr = add_used_nodes_1 bs r markedl n).\n  intro.  elim H3; clear H3.  intros markedr H3.  rewrite <- H3.\n  cut\n   ((forall node' : ad,\n     nodes_reachable bs l node' /\\ in_dom _ node' bs = true ->\n     in_dom _ node' markedl = true) /\\\n    (forall node' : ad,\n     in_dom _ node' markedl = true ->\n     in_dom _ node' marked = true \\/\n     in_dom _ node' bs = true /\\ nodes_reachable bs l node') /\\\n    set_closed bs markedl).\n  intro.  elim H4; clear H4; intros.  elim H5; clear H5; intros.\n  cut\n   ((forall node' : ad,\n     nodes_reachable bs r node' /\\ in_dom _ node' bs = true ->\n     in_dom _ node' markedr = true) /\\\n    (forall node' : ad,\n     in_dom _ node' markedr = true ->\n     in_dom _ node' markedl = true \\/\n     in_dom _ node' bs = true /\\ nodes_reachable bs r node') /\\\n    set_closed bs markedr).\n  intros.  elim H7; clear H7; intros.  elim H8; clear H8; intros.\n  cut\n   (forall node' : ad,\n    nodes_reachable bs node node' /\\\n    in_dom (BDDvar * (ad * ad)) node' bs = true ->\n    in_dom unit node' (MapPut unit markedr node tt) = true).\n  intro.  cut\n   (forall node' : ad,\n    in_dom unit node' (MapPut unit markedr node tt) = true ->\n    in_dom unit node' marked = true \\/\n    in_dom (BDDvar * (ad * ad)) node' bs = true /\\\n    nodes_reachable bs node node').\n  intros.  split.  assumption.  split.  assumption.  unfold set_closed in |- *.\n  intros.  unfold in_dom in H12.  rewrite (MapPut_semantics unit markedr node tt node0) in H12.\n  elim (sumbool_of_bool (Neqb node node0)).  intro y1.  rewrite <- (Neqb_complete _ _ y1) in H13.\n  apply H10.  split.  assumption.  assumption.  intro y1.  rewrite y1 in H12.\n  unfold set_closed in H9.  unfold in_dom in |- *.  rewrite (MapPut_semantics unit markedr node tt node').\n  elim (sumbool_of_bool (Neqb node node')).  intro y2.  rewrite y2.  reflexivity.\n  intro y2.  rewrite y2.  fold (in_dom _ node' markedr) in |- *.  apply H9 with (node := node0).\n  assumption.  assumption.  assumption.  intros.  unfold in_dom in H11.\n  rewrite (MapPut_semantics unit markedr node tt node') in H11.\n  elim (sumbool_of_bool (Neqb node node')).  intro y1.  rewrite y1 in H11.\n  rewrite <- (Neqb_complete _ _ y1).  right.  split.  unfold in_dom in |- *.\n  rewrite y0.  reflexivity.  apply nodes_reachable_0.  intro y1.  rewrite y1 in H11.\n  fold (in_dom _ node' markedr) in H11.  elim (H8 node' H11).  intro.\n  elim (H5 node' H12).  intro.  left; assumption.  intro.  elim H13; clear H13; intros.\n  right.  split.  assumption.  apply nodes_reachable_1 with (x := x) (l := l) (r := r).\n  assumption.  assumption.  intro.  right.  split.  exact (proj1 H12).\n  apply nodes_reachable_2 with (x := x) (l := l) (r := r).  assumption.  exact (proj2 H12).\n  intros.  unfold in_dom in |- *.  rewrite (MapPut_semantics unit markedr node tt node').\n  elim (sumbool_of_bool (Neqb node node')).  intro y1.  rewrite y1.  reflexivity.\n  intro y1.  rewrite y1.  fold (in_dom _ node' markedr) in |- *.  elim H10; clear H10; intros.\n  elim (nodes_reachable_lemma_1 bs node node' H10).  intro.  rewrite H12 in y1.\n  rewrite (Neqb_correct node') in y1.  discriminate.  intro.  inversion H12.\n  inversion H13.  inversion H14.  clear H12 H13 H14.  inversion H15.  clear H15.\n  elim H13; clear H13; intro.  rewrite y0 in H12.  injection H12.  clear H12; intros.\n  rewrite <- H14 in H13.  rewrite H3.  apply add_used_nodes_1_lemma_1. assumption.\n  apply lt_trans_1 with (y := nat_of_N (bs_node_height bs node)).  apply BDDcompare_lt.\n  apply bs_node_height_right with (bs := bs) (x := x) (l := l) (r := r).  assumption.  assumption.\n  assumption.  apply H4.  split.  assumption.  assumption.  apply H7.  split.\n  rewrite y0 in H12.  injection H12; intros.  rewrite H14.  assumption.\n  assumption.  rewrite H3.  apply H.  assumption.\n  apply lt_trans_1 with (y := nat_of_N (bs_node_height bs node)).\n  apply BDDcompare_lt.  apply bs_node_height_right with (bs := bs) (x := x) (l := l) (r := r).\n  assumption.  assumption.  assumption.  assumption.  rewrite H2.  apply H.\n  assumption.  apply lt_trans_1 with (y := nat_of_N (bs_node_height bs node)).\n  apply BDDcompare_lt.  apply bs_node_height_left with (bs := bs) (x := x) (l := l) (r := r).\n  assumption.  assumption.  assumption.  assumption.  split with (add_used_nodes_1 bs r markedl n).\n  reflexivity.  split with (add_used_nodes_1 bs l marked n).  intros.\n  reflexivity.  intro y0.  rewrite y0.  split.  intros.  elim H2; intros.\n  elim (nodes_reachable_lemma_1 bs node node' H3).  intro.  rewrite <- H5 in H4.\n  unfold in_dom in H4.  rewrite y0 in H4.  discriminate.  intro.  inversion H5.\n  inversion H6.  inversion H7.  inversion H8.  rewrite y0 in H9.  discriminate.\n  split.  intros.  left; assumption.  assumption.\nQed.\n\nLemma add_used_nodes_lemma_1 :\n forall (bs : BDDstate) (node : ad) (marked : Map unit),\n BDDstate_OK bs ->\n forall node' : ad,\n in_dom _ node' marked = true ->\n in_dom _ node' (add_used_nodes bs node marked) = true.\nProof.\n  intros.  unfold add_used_nodes in |- *.  apply add_used_nodes_1_lemma_1.  assumption.\n  unfold lt in |- *.  apply le_n.  assumption.\nQed.\n\nLemma add_used_nodes_lemma_2 :\n forall (bs : BDDstate) (node : ad) (marked : Map unit),\n BDDstate_OK bs ->\n set_closed bs marked ->\n (forall node' : ad,\n  nodes_reachable bs node node' /\\ in_dom _ node' bs = true ->\n  in_dom _ node' (add_used_nodes bs node marked) = true) /\\\n (forall node' : ad,\n  in_dom _ node' (add_used_nodes bs node marked) = true ->\n  in_dom _ node' marked = true \\/\n  in_dom _ node' bs = true /\\ nodes_reachable bs node node') /\\\n set_closed bs (add_used_nodes bs node marked).\nProof.\n  intros.  unfold add_used_nodes in |- *.  apply add_used_nodes_1_lemma_2.  assumption.\n  unfold lt in |- *.  apply le_n.  assumption.\nQed.\n\nLemma mark_lemma_1 :\n forall (used : list ad) (bs : BDDstate),\n BDDstate_OK bs ->\n set_closed bs (fold_right (add_used_nodes bs) (M0 unit) used) /\\\n (forall node : ad,\n  in_dom _ node (fold_right (add_used_nodes bs) (M0 unit) used) = true <->\n  (exists node' : ad,\n     In node' used /\\\n     nodes_reachable bs node' node /\\ in_dom _ node bs = true)).\nProof.\n  simple induction used.  intros.  simpl in |- *.  split.  unfold set_closed in |- *.  unfold in_dom in |- *.\n  simpl in |- *.  intros; discriminate.  unfold in_dom in |- *.  simpl in |- *.  split.\n  intro; discriminate.  intro.  inversion H0.  absurd False.\n  unfold not in |- *; trivial.  exact (proj1 H1).  intros.  simpl in |- *.  split.\n  refine\n   (proj2\n      (proj2\n         (add_used_nodes_lemma_2 bs a\n            (fold_right (add_used_nodes bs) (M0 unit) l) _ _))).\n  assumption.  exact (proj1 (H bs H0)).  split.  intro.\n  elim\n   (add_used_nodes_lemma_2 bs a (fold_right (add_used_nodes bs) (M0 unit) l)\n      H0).\n  intros.  elim H3; clear H3; intros.  elim (H3 node H1).  intro.\n  elim (proj1 (proj2 (H bs H0) node)).  intros.  split with x.  split.\n  right.  exact (proj1 H6).  exact (proj2 H6).  assumption.  intro.\n  split with a.  split.  left; reflexivity.  split.  exact (proj2 H5).\n  exact (proj1 H5).  exact (proj1 (H bs H0)).  intro.\n  elim H1; clear H1.  intros.  elim H1; clear H1; intros.\n  elim H1; clear H1.  intros.  rewrite <- H1 in H2.\n  apply\n   (proj1\n      (add_used_nodes_lemma_2 bs a\n         (fold_right (add_used_nodes bs) (M0 unit) l) H0 \n         (proj1 (H bs H0)))).\n  assumption.  intro.  lapply (proj2 (proj2 (H bs H0) node)).  intro.\n  refine (add_used_nodes_lemma_1 _ _ _ _ _ _).  assumption.  assumption.\n  split with x.  split.  assumption.  assumption.\nQed.\n\nLemma mark_lemma_2 :\n forall (bs : BDDstate) (used : list ad),\n BDDstate_OK bs ->\n forall node : ad,\n in_dom _ node (mark bs used) = true <->\n (exists node' : ad,\n    In node' used /\\ nodes_reachable bs node' node /\\ in_dom _ node bs = true).\nProof.\n  intros.  unfold mark in |- *.  apply (proj2 (mark_lemma_1 used bs H)).\nQed.\n\nLemma mark_lemma_3 :\n forall (bs : BDDstate) (used : list ad),\n BDDstate_OK bs ->\n forall node : ad,\n in_dom _ node (mark bs used) = true <->\n used_node_bs bs used node /\\ in_dom _ node bs = true.\nProof.\n  split.  intro.  elim (proj1 (mark_lemma_2 _ _ H _) H0).  intros.\n  split.  unfold used_node_bs in |- *.  split with x.  split.  exact (proj1 H1).\n  exact (proj1 (proj2 H1)).  exact (proj2 (proj2 H1)).  intro.\n  apply (proj2 (mark_lemma_2 bs used H node)).  elim H0; intros.\n  elim H1; intros.  split with x.  split.  exact (proj1 H3).  split.\n  exact (proj2 H3).  assumption.\nQed.\n\nLemma new_bs_lemma_1 :\n forall (bs : BDDstate) (used : list ad),\n BDDstate_OK bs ->\n forall node : ad,\n used_node_bs bs used node ->\n MapGet _ bs node = MapGet _ (new_bs bs used) node.\nProof.\n  intros.  unfold new_bs in |- *.  rewrite (MapDomRestrTo_semantics _ _ bs (mark bs used) node).\n  elim (option_sum _ (MapGet unit (mark bs used) node)).  intro y.\n  elim y; clear y; intros x y.  rewrite y.  reflexivity.  intro y.  rewrite y.\n  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) bs node)).  intro y0.\n  elim y0; clear y0; intros x y0.  cut (in_dom _ node (mark bs used) = true).\n  unfold in_dom in |- *.  rewrite y.  intro.  discriminate.  \n  apply (proj2 (mark_lemma_3 bs used H node)).  split.  assumption.  \n  unfold in_dom in |- *.  rewrite y0.  reflexivity.  tauto.\nQed.\n\nLemma new_bs_lemma_2 :\n forall (bs : BDDstate) (used : list ad),\n BDDstate_OK bs ->\n forall node : ad,\n in_dom _ node (new_bs bs used) = true -> used_node_bs bs used node.\nProof.\n  intros.  unfold new_bs in H0.  unfold in_dom in H0.\n  rewrite\n   (MapDomRestrTo_semantics (BDDvar * (ad * ad)) unit bs (mark bs used) node)\n    in H0.\n  elim (option_sum _ (MapGet unit (mark bs used) node)).  intro y.\n  elim y; clear y; intros x y.  cut (in_dom _ node (mark bs used) = true).  intro.\n  elim (proj1 (mark_lemma_3 bs used H node) H1).  tauto.  unfold in_dom in |- *.\n  rewrite y.  reflexivity.  intro y.  rewrite y in H0.  discriminate.  \nQed.\n\nLemma no_new_node_new_bs :\n forall (bs : BDDstate) (used : list ad),\n BDDstate_OK bs -> no_new_node_bs bs (new_bs bs used).\nProof.\n  intros.  unfold no_new_node_bs in |- *.  intros.  cut (used_node_bs bs used node).\n  intro.  rewrite (new_bs_lemma_1 bs used H node H1).  assumption.\n  apply new_bs_lemma_2.  assumption.  unfold in_dom in |- *.  rewrite H0.  reflexivity.\nQed.\n\nLemma new_bs_zero :\n forall (bs : BDDstate) (used : list ad),\n BDDstate_OK bs -> in_dom _ BDDzero (new_bs bs used) = false.\nProof.\n  intros.  apply not_true_is_false.  unfold not in |- *; intro.\n  cut (MapGet _ bs BDDzero = MapGet _ (new_bs bs used) BDDzero).\n  rewrite (proj1 H).  intro.  unfold in_dom in H0.  rewrite <- H1 in H0.\n  discriminate.  apply new_bs_lemma_1.  assumption.  apply new_bs_lemma_2.\n  assumption.  assumption.\nQed.\n\nLemma new_bs_one :\n forall (bs : BDDstate) (used : list ad),\n BDDstate_OK bs -> in_dom _ BDDone (new_bs bs used) = false.\nProof.\n  intros.  apply not_true_is_false.  unfold not in |- *; intro.\n  cut (MapGet _ bs BDDone = MapGet _ (new_bs bs used) BDDone).\n  rewrite (proj1 (proj2 H)).  intro.  unfold in_dom in H0.\n  rewrite <- H1 in H0.  discriminate.  apply new_bs_lemma_1.  assumption.\n  apply new_bs_lemma_2.  assumption.  assumption.\nQed.\n\nLemma new_bs_BDDhigh :\n forall (bs : BDDstate) (used : list ad) (x : BDDvar) (l r node : ad),\n BDDstate_OK bs ->\n MapGet _ (new_bs bs used) node = Some (x, (l, r)) ->\n in_dom _ r (new_bs bs used) = in_dom _ r bs.\nProof.\n  intros.  cut (MapGet _ (new_bs bs used) r = MapGet _ bs r).  intro.\n  unfold in_dom in |- *.  rewrite H1.  reflexivity.  symmetry  in |- *.  apply new_bs_lemma_1.\n  assumption.  unfold used_node_bs in |- *.  cut (used_node_bs bs used node).  intro.\n  elim H1.  intros.  split with x0.  split.  exact (proj1 H2).  \n  apply nodes_reachable_trans with (node2 := node).  exact (proj2 H2).\n  apply nodes_reachable_2 with (x := x) (l := l) (r := r).  rewrite <- H0.\n  apply new_bs_lemma_1.  assumption.  assumption.  apply nodes_reachable_0.\n  apply new_bs_lemma_2.  assumption.  unfold in_dom in |- *.  rewrite H0.  reflexivity.\nQed.\n\nLemma new_bs_BDDlow :\n forall (bs : BDDstate) (used : list ad) (x : BDDvar) (l r node : ad),\n BDDstate_OK bs ->\n MapGet _ (new_bs bs used) node = Some (x, (l, r)) ->\n in_dom _ l (new_bs bs used) = in_dom _ l bs.\nProof.\n  intros.  cut (MapGet _ (new_bs bs used) l = MapGet _ bs l).  intro.\n  unfold in_dom in |- *.  rewrite H1.  reflexivity.  symmetry  in |- *.  apply new_bs_lemma_1.\n  assumption.  unfold used_node_bs in |- *.  cut (used_node_bs bs used node).  intro.\n  elim H1.  intros.  split with x0.  split.  exact (proj1 H2).\n  apply nodes_reachable_trans with (node2 := node).  exact (proj2 H2).\n  apply nodes_reachable_1 with (x := x) (l := l) (r := r).  rewrite <- H0.\n  apply new_bs_lemma_1.  assumption.  assumption.  apply nodes_reachable_0.\n  apply new_bs_lemma_2.  assumption.  unfold in_dom in |- *.  rewrite H0.  reflexivity.\nQed.\n\nLemma new_bs_used_nodes_preserved :\n forall (bs : BDDstate) (used : list ad) (node : ad),\n BDDstate_OK bs ->\n used_node_bs bs used node -> node_preserved_bs bs (new_bs bs used) node.\nProof.\n  intros.  unfold node_preserved_bs in |- *.  intros.\n  rewrite <- (new_bs_lemma_1 _ used H node').  assumption.  elim H0.  intros.\n  split with x0.  split.  exact (proj1 H3).  \n  apply nodes_reachable_trans with (node2 := node).  exact (proj2 H3).\n  assumption.\nQed.\n\nLemma new_bsBDDbounded_1 :\n forall (n : nat) (bs : BDDstate) (used : list ad) (node : ad) (x : BDDvar),\n BDDstate_OK bs ->\n n = nat_of_N x ->\n in_dom _ node (new_bs bs used) = true ->\n BDDbounded bs node x -> BDDbounded (new_bs bs used) node x.\nProof.\n  intro.  apply\n   lt_wf_ind\n    with\n      (P := fun n : nat =>\n            forall (bs : BDDstate) (used : list ad) (node : ad) (x : BDDvar),\n            BDDstate_OK bs ->\n            n = nat_of_N x ->\n            in_dom (BDDvar * (ad * ad)) node (new_bs bs used) = true ->\n            BDDbounded bs node x -> BDDbounded (new_bs bs used) node x).\n  clear n.  intro.  intro H00.  intros.  elim (BDDbounded_lemma bs node x H2).\n  intro.  rewrite H3.  apply BDDbounded_0.  intro.  elim H3; clear H3; intro.\n  rewrite H3.  apply BDDbounded_1.  elim H3; clear H3.  intros x0 H3.\n  elim H3; clear H3.  intros l H3.  elim H3; clear H3.  intros r H3.\n  elim H3; clear H3; intros.  elim H4; clear H4; intros.\n  elim H5; clear H5; intros.  elim H6; clear H6; intros.\n  cut (MapGet _ (new_bs bs used) node = Some (x0, (l, r))).  intro.\n  cut (BDDbounded (new_bs bs used) l x0).  cut (BDDbounded (new_bs bs used) r x0).\n  intros.  apply BDDbounded_2 with (x := x0) (l := l) (r := r).  assumption.  assumption.\n  assumption.  assumption.  assumption.  cut (node_OK bs r).  intro.\n  unfold node_OK in H9.  elim H9; intro.  rewrite H10.  apply BDDbounded_0.\n  elim H10; intro.  rewrite H11.  apply BDDbounded_1.\n  apply H00 with (m := nat_of_N x0).  rewrite H0.  apply BDDcompare_lt.\n  assumption.  assumption.  reflexivity.  rewrite <- H11.\n  apply new_bs_BDDhigh with (x := x0) (l := l) (node := node).  assumption.  assumption.\n  assumption.  apply BDDbounded_node_OK with (n := x0).  assumption.\n  cut (node_OK bs l).  intro.  unfold node_OK in H9.  elim H9; intro.\n  rewrite H10.  apply BDDbounded_0.  elim H10; intro.  rewrite H11.\n  apply BDDbounded_1.  apply H00 with (m := nat_of_N x0).  rewrite H0.\n  apply BDDcompare_lt.  assumption.  assumption.  reflexivity.  rewrite <- H11.\n  apply new_bs_BDDlow with (x := x0) (r := r) (node := node).  assumption.  assumption.\n  assumption.  apply BDDbounded_node_OK with (n := x0).  assumption.\n  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) (new_bs bs used) node)).  intro y.\n  elim y; clear y; intro x1.  elim x1; clear x1.  intro y.  intro y0.\n  elim y0; intros y1 y2 y3.  rewrite <- H3.  symmetry  in |- *.  apply new_bs_lemma_1.\n   assumption.  apply new_bs_lemma_2.  assumption.  unfold in_dom in |- *.  rewrite y3.\n  unfold in_dom in |- *.  reflexivity.  intro y.  unfold in_dom in H1.  rewrite y in H1.  \n  discriminate.\nQed.\n\nLemma new_bs_OK :\n forall (bs : BDDstate) (used : list ad),\n BDDstate_OK bs -> BDDstate_OK (new_bs bs used).\nProof.\n  intros.  unfold BDDstate_OK in |- *.  unfold BDDstate_OK in H.  split.\n  lapply (new_bs_zero bs used).  unfold in_dom in |- *.\n  elim (MapGet (BDDvar * (ad * ad)) (new_bs bs used) BDDzero).  Focus 2. reflexivity.  intros.\n  discriminate.  assumption.  split.  lapply (new_bs_one bs used).\n  unfold in_dom in |- *.  elim (MapGet (BDDvar * (ad * ad)) (new_bs bs used) BDDone).\n  Focus 2.\n  reflexivity.  intros.  discriminate.  assumption.  intros a H0.  unfold BDD_OK in |- *.\n  cut (BDD_OK bs a).  unfold BDD_OK in |- *.\n  cut\n   (MapGet (BDDvar * (ad * ad)) (new_bs bs used) a =\n    MapGet (BDDvar * (ad * ad)) bs a).\n  intro.  rewrite H1.  elim (MapGet (BDDvar * (ad * ad)) bs a).  Focus 2. tauto.  intro a0.\n  elim a0.  intros y y0 H2.  apply new_bsBDDbounded_1 with (n := nat_of_N (ad_S y)).\n  assumption.  reflexivity.  assumption.  assumption.  symmetry  in |- *.\n  apply new_bs_lemma_1.  assumption.  apply new_bs_lemma_2.  assumption.\n  assumption.  apply (proj2 (proj2 H)).\n  cut (MapGet _ bs a = MapGet _ (new_bs bs used) a).  intro.  unfold in_dom in |- *.\n  rewrite H1.  assumption.  apply new_bs_lemma_1.  assumption.  \n  apply new_bs_lemma_2.  assumption.  assumption.\nQed.\n\nLemma new_cnt_OK :\n forall (bs : BDDstate) (used : list ad) (cnt : ad),\n BDDstate_OK bs -> cnt_OK bs cnt -> cnt_OK (new_bs bs used) cnt.\nProof.\n  intros.  unfold cnt_OK in |- *.  unfold cnt_OK in H0.\n  elim H0; clear H0; intros.  split.  assumption.  intros.\n  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) (new_bs bs used) a)).  intro y.\n  elim y; clear y; intros x y.  cut (used_node_bs bs used a).  intro.\n  rewrite <- (new_bs_lemma_1 bs used H a H3).  apply H1.  assumption.\n  apply new_bs_lemma_2.  assumption.  unfold in_dom in |- *.  rewrite y.  reflexivity.\n  tauto.\nQed.\n\nLemma new_fl_OK :\n forall (bs : BDDstate) (used : list ad) (fl : BDDfree_list) (cnt : ad),\n BDDstate_OK bs ->\n BDDfree_list_OK bs fl cnt ->\n cnt_OK bs cnt -> BDDfree_list_OK (new_bs bs used) (new_fl bs used fl) cnt.\nProof.\n  unfold BDDfree_list_OK in |- *.  intros bs used fl cnt H H0 H00.\n  elim H0; clear H0; intros.  split.  unfold new_fl in |- *.\n  apply MapDomRestrByApp1_lemma_4 with (fp := fun a0 : ad => a0).  reflexivity.\n  intros.  unfold not in |- *.  intro.  unfold in_dom in H2.\n  rewrite (proj2 (proj2 (proj1 (H1 a) H4))) in H2.  discriminate.\n  assumption.  split.  intros.  unfold new_fl in H2.  unfold BDDfree_list in fl.\n  unfold BDDstate in bs.  cut (forall a : ad, (fun a0 : ad => a0) ((fun a0 : ad => a0) a) = a).  intro.\n  elim\n   (MapDomRestrByApp1_lemma_3 (BDDvar * (ad * ad)) unit bs \n      (mark bs used) fl (fun a : ad => a) (fun a : ad => a) H3 node H2).\n  intro.  elim (proj1 (H1 node) H4).  intros.  elim H6; clear H6; intros.\n  split.  assumption.  split.  assumption.  \n  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) (new_bs bs used) node)).  intro y.\n  elim y; clear y; intro x.  elim x.  intro y.  intro y0.  elim y0.  intros y1 y2 y3.\n  rewrite (no_new_node_new_bs bs used H y y1 y2 node) in H7.  discriminate.\n  assumption.  tauto.  intro.  elim H4; clear H4; intros.\n  elim H5; clear H5; intros.  clear H6.  unfold cnt_OK in H00.  split.\n  apply ad_gt_1_lemma.  unfold not in |- *; intro.  unfold BDDstate_OK in H.\n  unfold BDDzero in H.  rewrite <- H6 in H.  unfold in_dom in H4.\n  rewrite (proj1 H) in H4.  discriminate.  unfold not in |- *; intro.\n  unfold BDDstate_OK in H.  unfold BDDone in H.  rewrite <- H6 in H.\n  unfold in_dom in H4.  rewrite (proj1 (proj2 H)) in H4.  discriminate.\n  split.  apply Nltb_lebmma.  apply not_true_is_false.  unfold not in |- *; intro.\n  unfold in_dom in H4.  rewrite (proj2 H00 _ H6) in H4.  discriminate.\n  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) (new_bs bs used) node)).  intro y.\n  elim y; clear y; intros x y.  cut (used_node_bs bs used node).  intro.  elim H6.\n  intros.  cut (in_dom unit node (mark bs used) = true).  intro.\n  rewrite H8 in H5.  discriminate.  apply (proj2 (mark_lemma_2 bs used H node)).\n  split with x0.  split.  exact (proj1 H7).  split.  exact (proj2 H7).\n  assumption.  apply new_bs_lemma_2.  assumption.  unfold in_dom in |- *.  rewrite y.\n  reflexivity.  tauto.  reflexivity.  intro.\n(*\n  Decompose Record H2.\n*)\n  elim H2; intros H3 H4; elim H4; intros H5 H6; clear H4.\n  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) bs node)).  intro y.  elim y; clear y.\n  intro x.  elim x; clear x.  intros x y.  elim y; clear y; intros l r H7.\n  unfold new_fl in |- *.  apply MapDomRestrByApp1_lemma_2 with (pf := fun a0 : ad => a0).\n  unfold in_dom in |- *.  rewrite H7.  reflexivity.  apply not_true_is_false.\n  unfold not in |- *.  intro.  cut (used_node_bs bs used node).  intro.\n  rewrite (new_bs_lemma_1 bs used H node H8) in H7.  rewrite H6 in H7.\n  discriminate.  exact (proj1 (proj1 (mark_lemma_3 bs used H node) H4)).\n  intro.  unfold new_fl in |- *.  apply MapDomRestrByApp1_lemma_1.\n  apply (proj2 (H1 node)).  split.  assumption.  split.  assumption.\n  assumption.\nQed.\n\nLemma used_node_bs_1_preserved :\n forall (bs : BDDstate) (used : list ad) (node : ad),\n BDDstate_OK bs ->\n used_node_bs_1 (mark bs used) node = true ->\n node_preserved_bs bs (new_bs bs used) node.\nProof.\n  intros.  unfold used_node_bs_1 in H0.\n  elim (option_sum _ (MapGet unit (mark bs used) node)).  intro y.  inversion y.\n  apply new_bs_used_nodes_preserved.  assumption.\n  refine (proj1 (proj1 (mark_lemma_3 bs used H node) _)).\n  unfold in_dom in |- *.  rewrite H1.  reflexivity.  intro y.  rewrite y in H0.\n  elim (orb_prop _ _ H0).  intro.  rewrite (Neqb_complete _ _ H1).\n  apply BDDzero_preserved.  assumption.  intro.\n  rewrite (Neqb_complete _ _ H1).  apply BDDone_preserved.  assumption.\nQed.\n\nLemma clean'1_1_lemma :\n forall (m : Map ad) (m' : Map unit) (pf : ad -> ad) (a a' : ad),\n MapGet _ (clean'1_1 pf m' m) a = Some a' <->\n used_node_bs_1 m' (pf a) && used_node_bs_1 m' a' = true /\\\n MapGet _ m a = Some a'.\nProof.\n  simple induction m.  simpl in |- *.  intros.  split.  intro.  discriminate.  tauto.  intros.\n  simpl in |- *.  split.  intro.\n  elim (sumbool_of_bool (used_node_bs_1 m' (pf a) && used_node_bs_1 m' a0)).\n  intro y.  rewrite y in H.  simpl in H.  elim (sumbool_of_bool (Neqb a a1)).\n  intro y0.  rewrite y0 in H.  injection H.  intro.  split.  rewrite H0 in y.\n  rewrite (Neqb_complete _ _ y0) in y.  assumption.  rewrite y0.  assumption.\n  intro y0.  rewrite y0 in H.  discriminate.  intro y.  rewrite y in H.  simpl in H.\n  discriminate.  intro.  elim H; clear H; intros.  elim (sumbool_of_bool (Neqb a a1)).\n  intro y.  rewrite y in H0.  injection H0.  intro.  rewrite H1.\n  rewrite (Neqb_complete _ _ y).  rewrite H.  simpl in |- *.\n  rewrite (Neqb_correct a1).  reflexivity.  intro y.  rewrite y in H0.\n  discriminate.  intros.  split.  intro.  simpl in H1.\n  rewrite\n   (makeM2_M2 _ (clean'1_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean'1_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n    in H1.\n  rewrite\n   (MapGet_M2_bit_0_if _ (clean'1_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean'1_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n    in H1.\n  elim (sumbool_of_bool (Nbit0 a)).  intro y.  rewrite y in H1.\n  rewrite (MapGet_M2_bit_0_if _ m0 m1 a).  rewrite y.\n  lapply\n   (proj1 (H0 m' (fun a0 : ad => pf (Ndouble_plus_one a0)) (Ndiv2 a) a')).\n  intro.  rewrite (Ndiv2_double_plus_one a) in H2.  assumption.  assumption.\n  assumption.  intro y.  rewrite y in H1.  rewrite (MapGet_M2_bit_0_if _ m0 m1 a).\n  rewrite y.  lapply (proj1 (H m' (fun a0 : ad => pf (Ndouble a0)) (Ndiv2 a) a')).\n  intro.  rewrite (Ndiv2_double a) in H2.  assumption.  assumption.\n  assumption.  intro.  simpl in |- *.\n  rewrite\n   (makeM2_M2 _ (clean'1_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean'1_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n   .\n  rewrite\n   (MapGet_M2_bit_0_if _ (clean'1_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean'1_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n   .\n  elim (sumbool_of_bool (Nbit0 a)).  intro y.  rewrite y.\n  rewrite (MapGet_M2_bit_0_if _ m0 m1 a) in H1.  rewrite y in H1.\n  apply\n   (proj2 (H0 m' (fun a0 : ad => pf (Ndouble_plus_one a0)) (Ndiv2 a) a')).\n  rewrite (Ndiv2_double_plus_one _ y).  assumption.  intro y.  rewrite y.\n  rewrite (MapGet_M2_bit_0_if _ m0 m1 a) in H1.  rewrite y in H1.\n  apply (proj2 (H m' (fun a0 : ad => pf (Ndouble a0)) (Ndiv2 a) a')).\n  rewrite (Ndiv2_double _ y).  assumption.\nQed.\n\nLemma clean'1_lemma :\n forall (m : Map ad) (m' : Map unit) (a a' : ad),\n MapGet _ (clean'1 m m') a = Some a' <->\n used_node_bs_1 m' a && used_node_bs_1 m' a' = true /\\\n MapGet _ m a = Some a'.\nProof.\n  intros.  unfold clean'1 in |- *.  apply clean'1_1_lemma with (pf := fun a : ad => a).\nQed.\n\nLemma clean'2_1_lemma :\n forall (m : Map (Map ad)) (m' : Map unit) (pf : ad -> ad) (a b c : ad),\n MapGet2 _ (clean'2_1 pf m' m) a b = Some c <->\n used_node_bs_1 m' (pf a) && (used_node_bs_1 m' b && used_node_bs_1 m' c) =\n true /\\ MapGet2 _ m a b = Some c.\nProof.\n  simple induction m.  simpl in |- *.  intros.  split.  intro.  unfold MapGet2 in H.\n  simpl in H.  discriminate.  tauto.  intros.  unfold MapGet2 in |- *.  simpl in |- *.  split.\n  intro.  elim (sumbool_of_bool (used_node_bs_1 m' (pf a))).  intro y.\n  rewrite y in H.  simpl in H.  elim (sumbool_of_bool (Neqb a a1)).  intro y0.\n  rewrite y0 in H.  rewrite y0.  rewrite <- (Neqb_complete _ _ y0).\n  rewrite y.  simpl in |- *.  apply (proj1 (clean'1_lemma a0 m' b c)).  assumption.\n  intro y0.  rewrite y0 in H.  discriminate.  intro y.  rewrite y in H.  simpl in H.\n  discriminate.  intro.  elim H; clear H; intros.  elim (andb_prop _ _ H).\n  clear H; intros.  elim (sumbool_of_bool (Neqb a a1)).  intro y.\n  rewrite y in H0.  rewrite <- (Neqb_complete _ _ y) in H.  rewrite H.\n  simpl in |- *.  rewrite y.  apply (proj2 (clean'1_lemma a0 m' b c)).  split.\n  assumption.  assumption.  intro y.  rewrite y in H0.  discriminate.  intros.\n  split.  intro.  unfold MapGet2 in H1.  simpl in H1.\n  rewrite\n   (makeM2_M2 _ (clean'2_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean'2_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n    in H1.\n  rewrite\n   (MapGet_M2_bit_0_if _ (clean'2_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean'2_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n    in H1.\n  unfold MapGet2 in |- *.  rewrite (MapGet_M2_bit_0_if _ m0 m1 a).\n  elim (sumbool_of_bool (Nbit0 a)).  intro y.  rewrite y.  rewrite y in H1.\n  lapply\n   (proj1 (H0 m' (fun a0 : ad => pf (Ndouble_plus_one a0)) (Ndiv2 a) b c)).\n  intro.  elim H2; intros.  unfold MapGet2 in H4.  split.\n  rewrite (Ndiv2_double_plus_one a y) in H3.  assumption.  assumption.\n  assumption.  intro y.  rewrite y in H1.  rewrite y.\n  lapply (proj1 (H m' (fun a0 : ad => pf (Ndouble a0)) (Ndiv2 a) b c)).  intro.\n  rewrite (Ndiv2_double a y) in H2.  assumption.  assumption.  intros.\n  simpl in |- *.  unfold MapGet2 in |- *.\n  rewrite\n   (makeM2_M2 _ (clean'2_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean'2_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n   .\n  rewrite\n   (MapGet_M2_bit_0_if _ (clean'2_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean'2_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n   .\n  unfold MapGet2 in H1.  rewrite (MapGet_M2_bit_0_if _ m0 m1 a) in H1.\n  elim (sumbool_of_bool (Nbit0 a)).  intro y.  rewrite y.  rewrite y in H1.\n  lapply\n   (proj2 (H0 m' (fun a0 : ad => pf (Ndouble_plus_one a0)) (Ndiv2 a) b c)).\n  intro.  assumption.  rewrite (Ndiv2_double_plus_one _ y).  assumption.\n  intro y.  rewrite y in H1.  rewrite y.\n  apply (proj2 (H m' (fun a0 : ad => pf (Ndouble a0)) (Ndiv2 a) b c)).\n  rewrite (Ndiv2_double _ y).  assumption.\nQed.\n\nLemma clean'2_lemma :\n forall (m : Map (Map ad)) (m' : Map unit) (a b c : ad),\n MapGet2 _ (clean'2 m m') a b = Some c <->\n used_node_bs_1 m' a && (used_node_bs_1 m' b && used_node_bs_1 m' c) = true /\\\n MapGet2 _ m a b = Some c.\nProof.\n  unfold clean'2 in |- *.  intros.  apply clean'2_1_lemma with (pf := fun a : ad => a).\nQed.\n\nLemma clean1_lemma :\n forall (m' : Map unit) (m : Map ad) (a a' : ad),\n MapGet _ (clean1 m' m) a = Some a' <->\n used_node_bs_1 m' a' = true /\\ MapGet _ m a = Some a'.\nProof.\n  simple induction m.  simpl in |- *.  split.  intro.  discriminate.  intro.  elim H.  intros.\n  discriminate.  simpl in |- *.  split.  intros.\n  elim (sumbool_of_bool (used_node_bs_1 m' a0)).  intro y.  rewrite y in H.\n  simpl in H.  elim (sumbool_of_bool (Neqb a a1)).  intro y0.  rewrite y0 in H.\n  injection H.  intro.  rewrite y0.  rewrite H0.  rewrite H0 in y.  split.\n  assumption.  reflexivity.  intro y0.  rewrite y0 in H.  discriminate.  intro y.\n  rewrite y in H.  simpl in H.  discriminate.  intro.  elim H; intros.\n  elim (sumbool_of_bool (Neqb a a1)).  intro y.  rewrite y in H1.  injection H1.\n  intro.  rewrite H2.  rewrite H0.  simpl in |- *.  rewrite y.  reflexivity.  intro y.\n  rewrite y in H1.  discriminate.  intros.  split.  intro.  simpl in H1.\n  rewrite (makeM2_M2 _ (clean1 m' m0) (clean1 m' m1) a) in H1.\n  rewrite (MapGet_M2_bit_0_if _ (clean1 m' m0) (clean1 m' m1) a) in H1.\n  rewrite (MapGet_M2_bit_0_if _ m0 m1 a).  elim (sumbool_of_bool (Nbit0 a)).\n  intro y.  rewrite y.  apply (proj1 (H0 (Ndiv2 a) a')).  rewrite y in H1.\n  assumption.  intro y.  rewrite y.  rewrite y in H1.\n  apply (proj1 (H (Ndiv2 a) a')).  assumption.  intro.\n  rewrite (MapGet_M2_bit_0_if _ m0 m1 a) in H1.  simpl in |- *.\n  rewrite (makeM2_M2 _ (clean1 m' m0) (clean1 m' m1) a).\n  rewrite (MapGet_M2_bit_0_if _ (clean1 m' m0) (clean1 m' m1) a).\n  elim (sumbool_of_bool (Nbit0 a)).  intro y.  rewrite y.  rewrite y in H1.\n  apply (proj2 (H0 (Ndiv2 a) a')).  assumption.  intro y.  rewrite y in H1.\n  rewrite y.  apply (proj2 (H (Ndiv2 a) a')).  assumption.\nQed.\n\nLemma clean2_1_lemma :\n forall (m' : Map unit) (m : Map (Map ad)) (pf : ad -> ad) (a b c : ad),\n MapGet2 _ (clean2_1 pf m' m) a b = Some c <->\n used_node_bs_1 m' (pf a) && used_node_bs_1 m' c = true /\\\n MapGet2 _ m a b = Some c.\nProof.\n  simple induction m.  unfold MapGet2 in |- *.  simpl in |- *.  split.  intro.  discriminate.  tauto.\n  simpl in |- *.  split.  intro.  unfold MapGet2 in |- *.  simpl in |- *.  unfold MapGet2 in H.\n  elim (sumbool_of_bool (used_node_bs_1 m' (pf a))).  intro y.  rewrite y in H.\n  simpl in H.  elim (sumbool_of_bool (Neqb a a1)).  intro y0.  rewrite y0 in H.\n  rewrite y0.  rewrite <- (Neqb_complete _ _ y0).  rewrite y.  simpl in |- *.\n  apply (proj1 (clean1_lemma m' a0 b c)).  assumption.  intro y0.\n  rewrite y0 in H.  discriminate.  intro y.  rewrite y in H.  simpl in H.\n  discriminate.  intro.  unfold MapGet2 in |- *.  unfold MapGet2 in H.  simpl in H.\n  elim (sumbool_of_bool (Neqb a a1)).  intro y.  rewrite y in H.\n  elim H; intros.  rewrite <- (Neqb_complete _ _ y).\n  rewrite <- (Neqb_complete _ _ y) in H0.  elim (andb_prop _ _ H0).  intros.\n  rewrite H2.  simpl in |- *.  rewrite (Neqb_correct a).\n  apply (proj2 (clean1_lemma m' a0 b c)).  split.  assumption.  assumption.\n  intro y.  rewrite y in H.  elim H; intros.  discriminate.  intros.  split.\n  intro.  simpl in H1.  unfold MapGet2 in H1.\n  rewrite\n   (makeM2_M2 (Map ad) (clean2_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean2_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n    in H1.\n  rewrite\n   (MapGet_M2_bit_0_if _ (clean2_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean2_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n    in H1.\n  unfold MapGet2 in |- *.  rewrite (MapGet_M2_bit_0_if _ m0 m1 a).\n  elim (sumbool_of_bool (Nbit0 a)).  intro y.  rewrite y.  rewrite y in H1.\n  lapply\n   (proj1 (H0 (fun a0 : ad => pf (Ndouble_plus_one a0)) (Ndiv2 a) b c)).\n  intro.  rewrite (Ndiv2_double_plus_one a y) in H2.  assumption.  \n  assumption.  intro y.  rewrite y.  rewrite y in H1.\n  lapply (proj1 (H (fun a0 : ad => pf (Ndouble a0)) (Ndiv2 a) b c)).\n  rewrite (Ndiv2_double a y).  tauto.  assumption.  intro.  simpl in |- *.\n  unfold MapGet2 in |- *.  unfold MapGet2 in H1.\n  rewrite\n   (makeM2_M2 _ (clean2_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean2_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n   .\n  rewrite\n   (MapGet_M2_bit_0_if _ (clean2_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean2_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n   .\n  rewrite (MapGet_M2_bit_0_if _ m0 m1 a) in H1.\n  elim (sumbool_of_bool (Nbit0 a)).  intro y.  rewrite y.  rewrite y in H1.\n  apply\n   (proj2 (H0 (fun a0 : ad => pf (Ndouble_plus_one a0)) (Ndiv2 a) b c)).\n  rewrite (Ndiv2_double_plus_one _ y).  assumption.  intro y.  rewrite y in H1.\n  rewrite y.  apply (proj2 (H (fun a0 : ad => pf (Ndouble a0)) (Ndiv2 a) b c)).\n  rewrite (Ndiv2_double _ y).  assumption.\nQed.\n\nLemma clean2_lemma :\n forall (m : Map (Map ad)) (m' : Map unit) (a b c : ad),\n MapGet2 _ (clean2 m m') a b = Some c <->\n used_node_bs_1 m' a && used_node_bs_1 m' c = true /\\\n MapGet2 _ m a b = Some c.\nProof.\n  intros.  unfold clean2 in |- *.  apply clean2_1_lemma with (pf := fun a : ad => a).\nQed.\n\nLemma clean3_1_lemma :\n forall (m' : Map unit) (m : Map (Map (Map ad))) (pf : ad -> ad)\n   (a b c d : ad),\n MapGet3 _ (clean3_1 pf m' m) a b c = Some d <->\n used_node_bs_1 m' (pf a) && (used_node_bs_1 m' b && used_node_bs_1 m' d) =\n true /\\ MapGet3 _ m a b c = Some d.\nProof.\n  simple induction m.  unfold MapGet3 in |- *.  simpl in |- *.  split.  intro.  discriminate.  tauto.\n  simpl in |- *.  split.  intro.  unfold MapGet3 in |- *.  simpl in |- *.  unfold MapGet3 in H.\n  elim (sumbool_of_bool (used_node_bs_1 m' (pf a))).  intro y.  rewrite y in H.\n  simpl in H.  elim (sumbool_of_bool (Neqb a a1)).  intro y0.  rewrite y0 in H.\n  rewrite y0.  rewrite <- (Neqb_complete _ _ y0).  rewrite y.  simpl in |- *.\n  apply (proj1 (clean2_lemma a0 m' b c d)).  assumption.  intro y0.\n  rewrite y0 in H.  discriminate.  intro y.  rewrite y in H.  simpl in H.\n  discriminate.  intro.  unfold MapGet3 in |- *.  unfold MapGet3 in H.  simpl in H.\n  elim (sumbool_of_bool (Neqb a a1)).  intro y.  rewrite y in H.\n  elim H; intros.  rewrite <- (Neqb_complete _ _ y).\n  rewrite <- (Neqb_complete _ _ y) in H0.  elim (andb_prop _ _ H0).  intros.\n  rewrite H2.  simpl in |- *.  rewrite (Neqb_correct a).\n  apply (proj2 (clean2_lemma a0 m' b c d)).  split.  assumption.\n  assumption.  intro y.  rewrite y in H.  elim H; intros.  discriminate.\n  intros.  split.  intro.  simpl in H1.  unfold MapGet3 in H1.\n  rewrite\n   (makeM2_M2 _ (clean3_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean3_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n    in H1.\n  rewrite\n   (MapGet_M2_bit_0_if _ (clean3_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean3_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n    in H1.\n  unfold MapGet3 in |- *.  rewrite (MapGet_M2_bit_0_if _ m0 m1 a).\n  elim (sumbool_of_bool (Nbit0 a)).  intro y.  rewrite y.  rewrite y in H1.\n  lapply\n   (proj1 (H0 (fun a0 : ad => pf (Ndouble_plus_one a0)) (Ndiv2 a) b c d)).\n  intro.  rewrite (Ndiv2_double_plus_one a y) in H2.  assumption.  assumption.\n  intro y.  rewrite y.  rewrite y in H1.\n  lapply (proj1 (H (fun a0 : ad => pf (Ndouble a0)) (Ndiv2 a) b c d)).\n  rewrite (Ndiv2_double a y).  tauto.  assumption.  intro.  simpl in |- *.\n  unfold MapGet3 in |- *.  unfold MapGet3 in H1.\n  rewrite\n   (makeM2_M2 _ (clean3_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean3_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n   .\n  rewrite\n   (MapGet_M2_bit_0_if _ (clean3_1 (fun a0 : ad => pf (Ndouble a0)) m' m0)\n      (clean3_1 (fun a0 : ad => pf (Ndouble_plus_one a0)) m' m1) a)\n   .\n  rewrite (MapGet_M2_bit_0_if _ m0 m1 a) in H1.\n  elim (sumbool_of_bool (Nbit0 a)).  intro y.  rewrite y.  rewrite y in H1.\n  apply\n   (proj2 (H0 (fun a0 : ad => pf (Ndouble_plus_one a0)) (Ndiv2 a) b c d)).\n   rewrite (Ndiv2_double_plus_one _ y).  assumption.  intro y.  rewrite y in H1.\n  rewrite y.\n  apply (proj2 (H (fun a0 : ad => pf (Ndouble a0)) (Ndiv2 a) b c d)).\n  rewrite (Ndiv2_double _ y).  assumption.\nQed.\n\nLemma clean3_lemma :\n forall (m : Map (Map (Map ad))) (m' : Map unit) (a b c d : ad),\n MapGet3 _ (clean3 m m') a b c = Some d <->\n used_node_bs_1 m' a && (used_node_bs_1 m' b && used_node_bs_1 m' d) = true /\\\n MapGet3 _ m a b c = Some d.\nProof.\n  intros.  unfold clean3 in |- *.  apply clean3_1_lemma with (pf := fun a : ad => a).\nQed.\n\nLemma new_negm_OK :\n forall (bs : BDDstate) (used : list ad) (negm : BDDneg_memo),\n BDDstate_OK bs ->\n BDDneg_memo_OK bs negm ->\n BDDneg_memo_OK (new_bs bs used) (clean'1 negm (mark bs used)).\nProof.\n  unfold BDDneg_memo_OK in |- *.  intros.  elim (proj1 (clean'1_lemma _ _ _ _) H1).\n  intros.  elim (H0 node node' H3).  clear H0.  intros.\n  elim H4; clear H4; intros.  elim H5; clear H5; intros.\n  elim (andb_prop _ _ H2).  intros.\n  cut (node_preserved_bs bs (new_bs bs used) node).\n  cut (node_preserved_bs bs (new_bs bs used) node').  intros.  split.\n  apply node_preserved_OK_bs with (bs := bs).  assumption.  assumption.  split.\n  apply node_preserved_OK_bs with (bs := bs).  assumption.  assumption.  split.\n  rewrite\n   (Neqb_complete (bs_node_height (new_bs bs used) node)\n      (bs_node_height bs node)).\n  rewrite\n   (Neqb_complete (bs_node_height (new_bs bs used) node')\n      (bs_node_height bs node')).\n  assumption.  apply node_preserved_bs_node_height_eq.  assumption.  apply new_bs_OK.\n  assumption.  assumption.  assumption.  apply node_preserved_bs_node_height_eq.\n  assumption.  apply new_bs_OK.  assumption.  assumption.  assumption.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD_bs bs node').\n  apply node_preserved_bs_bool_fun.  assumption.  apply new_bs_OK.  assumption.\n  assumption.  assumption.\n  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_of_BDD_bs bs node)).\n  assumption.  apply bool_fun_neg_preserves_eq.  apply bool_fun_eq_sym.\n  apply node_preserved_bs_bool_fun.  assumption.  apply new_bs_OK.  assumption.\n  assumption.  assumption.  apply used_node_bs_1_preserved.  assumption.  \n  assumption.  apply used_node_bs_1_preserved.  assumption.  assumption.\nQed.\n\nLemma new_orm_OK :\n forall (bs : BDDstate) (used : list ad) (orm : BDDor_memo),\n BDDstate_OK bs ->\n BDDor_memo_OK bs orm ->\n BDDor_memo_OK (new_bs bs used) (clean'2 orm (mark bs used)).\nProof.\n  unfold BDDor_memo_OK in |- *.  intros.  elim (proj1 (clean'2_lemma _ _ _ _ _) H1).\n  intros.  elim (H0 node1 node2 node H3).  intros.  elim H5; clear H5; intros.\n  elim H6; clear H6; intros.  elim H7; clear H7; intros.\n  elim (andb_prop _ _ H2).  intros.\n  cut (node_preserved_bs bs (new_bs bs used) node).\n  cut (node_preserved_bs bs (new_bs bs used) node1).\n  cut (node_preserved_bs bs (new_bs bs used) node2).  intros.  split.\n  apply node_preserved_OK_bs with (bs := bs).  assumption.  assumption.  split.\n  apply node_preserved_OK_bs with (bs := bs).  assumption.  assumption.  split.\n  apply node_preserved_OK_bs with (bs := bs).  assumption.  assumption.  split.\n  rewrite\n   (Neqb_complete (bs_node_height (new_bs bs used) node)\n      (bs_node_height bs node)).\n  rewrite\n   (Neqb_complete (bs_node_height (new_bs bs used) node1)\n      (bs_node_height bs node1)).\n  rewrite\n   (Neqb_complete (bs_node_height (new_bs bs used) node2)\n      (bs_node_height bs node2)).\n  assumption.  apply node_preserved_bs_node_height_eq.  assumption.  apply new_bs_OK.\n  assumption.  assumption.  assumption.  apply node_preserved_bs_node_height_eq.\n  assumption.  apply new_bs_OK.  assumption.  assumption.  assumption.\n  apply node_preserved_bs_node_height_eq.  assumption.  apply new_bs_OK.  assumption.  \n  assumption.  assumption.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD_bs bs node).\n  apply node_preserved_bs_bool_fun.  assumption.  apply new_bs_OK.  assumption.\n  assumption.  assumption.  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_or (bool_fun_of_BDD_bs bs node1)\n                (bool_fun_of_BDD_bs bs node2)).\n  assumption.  apply bool_fun_eq_sym.  apply bool_fun_or_preserves_eq.\n  apply node_preserved_bs_bool_fun.  assumption.  apply new_bs_OK.  assumption.\n  assumption.  assumption.  apply node_preserved_bs_bool_fun.  assumption.\n  apply new_bs_OK.  assumption.  assumption.  assumption.  \n  apply used_node_bs_1_preserved.  assumption.  elim (andb_prop _ _ H10).  tauto.\n  apply used_node_bs_1_preserved.  assumption.  assumption.\n  apply used_node_bs_1_preserved.  assumption.  elim (andb_prop _ _ H10).  tauto.\nQed.\n\nLemma new_univm_OK :\n forall (bs : BDDstate) (used : list ad) (univm : BDDuniv_memo),\n BDDstate_OK bs ->\n BDDuniv_memo_OK bs univm ->\n BDDuniv_memo_OK (new_bs bs used) (clean2 univm (mark bs used)).\nProof.\n  unfold BDDuniv_memo_OK in |- *.  intros.\n  elim (clean2_lemma univm (mark bs used) node x node').  intros.  elim H2.\n  intros.  elim (andb_prop _ _ H4).  intros.\n  cut (node_preserved_bs bs (new_bs bs used) node).\n  cut (node_preserved_bs bs (new_bs bs used) node').  intros.\n  decompose [and] (H0 x node node' H5).  split.\n  apply node_preserved_OK_bs with (bs := bs).  assumption.  assumption.  split.\n  apply node_preserved_OK_bs with (bs := bs).  assumption.  assumption.  split.\n  rewrite\n   (Neqb_complete (bs_node_height (new_bs bs used) node)\n      (bs_node_height bs node)).\n  rewrite\n   (Neqb_complete (bs_node_height (new_bs bs used) node')\n      (bs_node_height bs node')).\n  assumption.  apply node_preserved_bs_node_height_eq.  assumption.  apply new_bs_OK.\n  assumption.  assumption.  assumption.  apply node_preserved_bs_node_height_eq.\n  assumption.  apply new_bs_OK.  assumption.  assumption.  assumption.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD_bs bs node').\n  apply node_preserved_bs_bool_fun.  assumption.  apply new_bs_OK.  assumption.\n  assumption.  assumption.  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_forall x (bool_fun_of_BDD_bs bs node)).\n  assumption.  apply bool_fun_forall_preserves_eq.  apply bool_fun_eq_sym.\n  apply node_preserved_bs_bool_fun.  assumption.  apply new_bs_OK.  assumption.\n  assumption.  assumption.  apply used_node_bs_1_preserved.  assumption.  tauto.\n  apply used_node_bs_1_preserved.  assumption.  assumption.  assumption.  \nQed.\n\nLemma new_share_OK :\n forall (bs : BDDstate) (used : list ad) (share : BDDsharing_map),\n BDDstate_OK bs ->\n BDDsharing_OK bs share ->\n BDDsharing_OK (new_bs bs used) (clean3 share (mark bs used)).\nProof.\n  unfold BDDsharing_OK in |- *.  intros.  elim (H0 x l r a).  intros.  split.  intro.\n  elim (proj1 (clean3_lemma share (mark bs used) l r x a) H3).  intros.\n  elim (andb_prop _ _ H4).  intros.  elim (andb_prop _ _ H7).  intros.\n  cut (node_preserved_bs bs (new_bs bs used) a).  intro.\n  unfold node_preserved_bs in H10.  apply H10.  apply nodes_reachable_0.\n  apply H1.  assumption.  apply used_node_bs_1_preserved.  assumption.\n  assumption.  intro.\n  apply (proj2 (clean3_lemma share (mark bs used) l r x a)).\n  cut (MapGet _ bs a = Some (x, (l, r))).  intro.  cut (node_OK bs l).\n  cut (node_OK bs r).  intros.  split.  apply andb_true_intro.\n  cut\n   (forall a : ad,\n    MapGet _ bs a = None -> MapGet _ (mark bs used) a = None).\n  intro.  split.  elim H6.  intro.  rewrite H8.  unfold used_node_bs_1 in |- *.\n  rewrite (H7 BDDzero).  apply orb_true_intro.  left.  reflexivity.\n  exact (proj1 H).  intro.  elim H8.  intro.  rewrite H9.\n  unfold used_node_bs_1 in |- *.  rewrite (H7 BDDone).  apply orb_true_intro.  right.\n  reflexivity.  exact (proj1 (proj2 H)).  intro.  unfold used_node_bs_1 in |- *.\n  lapply (proj2 (mark_lemma_3 bs used H l)).  unfold in_dom in |- *.\n  elim (MapGet unit (mark bs used) l).  Focus 2. intro. discriminate.  reflexivity.\n  split.  unfold used_node_bs in |- *.  cut (used_node_bs bs used a).  intro.  elim H10.\n  intros.  split with x0.  split.  exact (proj1 H11).  \n  apply nodes_reachable_trans with (node2 := a).  exact (proj2 H11).\n  apply nodes_reachable_1 with (x := x) (l := l) (r := r).  assumption.\n  apply nodes_reachable_0.  apply new_bs_lemma_2.  assumption.  unfold in_dom in |- *.\n  rewrite H3.  reflexivity.  assumption.  apply andb_true_intro.  split.\n  elim H5.  intro.  rewrite H8.  unfold used_node_bs_1 in |- *.  rewrite (H7 BDDzero).\n  apply orb_true_intro.  left.  reflexivity.  exact (proj1 H).  intro.\n  elim H8.  intro.  rewrite H9.  unfold used_node_bs_1 in |- *.  rewrite (H7 BDDone).\n  apply orb_true_intro.  right.  reflexivity.  exact (proj1 (proj2 H)).\n  intro.  unfold used_node_bs_1 in |- *.  lapply (proj2 (mark_lemma_3 bs used H r)).\n  unfold in_dom in |- *.  elim (MapGet unit (mark bs used) r). Focus 2. intro.  discriminate.\n  reflexivity.  split.  unfold used_node_bs in |- *.  cut (used_node_bs bs used a).\n  intro.  elim H10.  intros.  split with x0.  split.  exact (proj1 H11).\n  apply nodes_reachable_trans with (node2 := a).  exact (proj2 H11).  \n  apply nodes_reachable_2 with (x := x) (l := l) (r := r).  assumption.\n  apply nodes_reachable_0.  apply new_bs_lemma_2.  assumption.  unfold in_dom in |- *.\n  rewrite H3.  reflexivity.  assumption.\n  cut (in_dom unit a (mark bs used) = true).  unfold in_dom in |- *.\n  unfold used_node_bs_1 in |- *.  elim (MapGet unit (mark bs used) a).  Focus 2. intro.\n  discriminate.  reflexivity.  apply (proj2 (mark_lemma_3 bs used H a)).\n  split.  apply new_bs_lemma_2.  assumption.  unfold in_dom in |- *.  rewrite H3.\n  reflexivity.  unfold in_dom in |- *.  rewrite H4.  reflexivity.  intros.\n  elim (sumbool_of_bool (in_dom _ a0 (mark bs used))).  intro y.\n  elim (proj1 (mark_lemma_3 bs used H a0) y).  intros.  unfold in_dom in H9.\n  rewrite H7 in H9.  discriminate.  unfold in_dom in |- *.\n  elim (MapGet unit (mark bs used) a0).  Focus 2. reflexivity.  intros.  discriminate.\n  apply H2.  assumption.  apply high_OK with (node := a) (x := x) (l := l).  assumption.\n  assumption.  apply low_OK with (node := a) (x := x) (r := r).  assumption.  assumption.\n  rewrite (new_bs_lemma_1 bs used H a).  assumption.  apply new_bs_lemma_2.\n  assumption.  unfold in_dom in |- *.  rewrite H3.  reflexivity.  \nQed.\n\nLemma new_cfg_OK :\n forall (bs : BDDstate) (share : BDDsharing_map) (fl : BDDfree_list)\n   (cnt : ad) (negm : BDDneg_memo) (orm : BDDor_memo) \n   (um : BDDuniv_memo) (used : list ad),\n BDDconfig_OK (bs, (share, (fl, (cnt, (negm, (orm, um)))))) ->\n BDDconfig_OK\n   (new_bs bs used,\n   (clean3 share (mark bs used),\n   (new_fl bs used fl,\n   (cnt,\n   (clean'1 negm (mark bs used),\n   (clean'2 orm (mark bs used), clean2 um (mark bs used))))))).\nProof.\n  intros.  unfold BDDconfig_OK in |- *.  simpl in |- *.  unfold BDDconfig_OK in H.  simpl in H.\n  elim H; intros.  elim H1; intros.  elim H3; intros.  elim H5; intros.\n  split.  apply new_bs_OK.  assumption.  split.  apply new_share_OK.\n  assumption.  assumption.  split.  apply new_fl_OK.  assumption.  assumption.\n  assumption.  split.  apply new_cnt_OK.  assumption.  assumption.  split.\n  apply new_negm_OK.  assumption.  exact (proj1 H7).  split.\n  apply new_orm_OK.  assumption.  exact (proj1 (proj2 H7)).\n  apply new_univm_OK.  assumption.  exact (proj2 (proj2 H7)).\nQed.\n \nLemma gc_0_OK : gc_OK gc_0.\nProof.\n  unfold gc_0 in |- *.  unfold gc_OK in |- *.  intro.  elim cfg.  intro y.  intro y0.  elim y0.\n  intro y1.  intro y2.  elim y2.  intro y3.  intro y4.  elim y4.  intro y5.  intro y6.  elim y6.\n  intro y7.  intro y8.  elim y8.\n  intros y9 y10 ul H H0.  split.  fold (new_bs y ul) in |- *.  fold (new_fl y ul y3) in |- *.\n  apply new_cfg_OK with (um := y10).  assumption.  unfold used_nodes_preserved in |- *.\n  simpl in |- *.  split.\n  unfold used_nodes_preserved_bs in |- *.  intros.  fold (new_bs y ul) in |- *.\n  apply new_bs_used_nodes_preserved.  exact (proj1 H).  unfold used_node_bs in |- *.\n  split with node.  split.  assumption.  apply nodes_reachable_0.  \n  unfold no_new_node in |- *.  simpl in |- *.  fold (new_bs y ul) in |- *.  apply no_new_node_new_bs.\n  exact (proj1 H).\nQed.\n\nLemma gc_inf_OK : gc_OK gc_inf.\nProof.\n  unfold gc_inf in |- *.  unfold gc_OK in |- *.  intros.  split.  assumption.  split.\n  apply used_nodes_preserved_refl.  unfold no_new_node in |- *.  unfold no_new_node_bs in |- *.\n  tauto.\nQed.\n\nLemma gc_x_OK : forall x : ad, gc_OK (gc_x x).\nProof.\n  intros.  unfold gc_x in |- *.  unfold gc_OK in |- *.  intros.\n  elim\n   (is_nil ad (fst (snd (snd cfg))) && Nleb x (fst (snd (snd (snd cfg))))).\n  apply gc_0_OK.  assumption.  assumption.  apply gc_inf_OK.  assumption.\n  assumption.  \nQed.\n\nLemma gc_x_opt_OK : forall x : ad, gc_OK (gc_x_opt x).\nProof.\n  intros.  unfold gc_x_opt in |- *.  unfold gc_OK in |- *.  intros.  elim (fl_of_cfg cfg).\n  elim (BDDcompare x (cnt_of_cfg cfg)).  apply gc_inf_OK.  assumption.\n  assumption.  apply gc_0_OK.  assumption.  assumption.  apply gc_inf_OK.\n  assumption.  assumption.  intros.  apply gc_inf_OK.  assumption.  assumption.\nQed.\n\n\nEnd BDDgc.", "meta": {"author": "coq-contribs", "repo": "smc", "sha": "e175520faa82eda0f014d300705612892fc7e778", "save_path": "github-repos/coq/coq-contribs-smc", "path": "github-repos/coq/coq-contribs-smc/smc-e175520faa82eda0f014d300705612892fc7e778/gc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.23614886196227952}}
{"text": "From iris.algebra Require Import excl auth cmra gmap agree gset numbers.\nFrom iris.algebra.lib Require Import frac_agree.\nFrom iris.heap_lang Require Export notation locations lang.\nFrom iris.base_logic.lib Require Export invariants.\nFrom iris.program_logic Require Export atomic.\nFrom iris.proofmode Require Import tactics.\nFrom iris.heap_lang Require Import proofmode par.\nFrom iris.bi.lib Require Import fractional.\nSet Default Proof Using \"All\".\nRequire Export auth_ext multicopy_lsm.\n\nSection multicopy_lsm_util.\n  Context {Σ} `{!heapG Σ, !multicopyG Σ, !multicopy_lsmG Σ}.\n  Notation iProp := (iProp Σ).\n  Local Notation \"m !1 i\" := (nzmap_total_lookup i m) (at level 20).\n\n  (** Useful lemmas *)\n\n  Lemma inFP_domm γ_f n D : inFP γ_f n -∗ own γ_f (● D) -∗ ⌜n ∈ D⌝.\n  Proof.\n    iIntros \"FP HD\".\n    iPoseProof (own_valid_2 _ _ _ with \"[$HD] [$FP]\") as \"H'\".\n    iDestruct \"H'\" as %H'.\n    apply auth_both_valid_discrete in H'.\n    destruct H' as [H' _].\n    apply gset_included in H'.\n    iPureIntro. set_solver.\n  Qed.\n\n  Lemma inFP_domm_glob γ_I γ_J γ_f γ_gh r hγ I J n :\n    inFP γ_f n -∗ global_state γ_I γ_J γ_f γ_gh r hγ I J -∗ ⌜n ∈ domm I⌝.\n  Proof.\n    iIntros \"#FP_n Hglob\".\n    iDestruct \"Hglob\" as \"(HI & Out_I & HJ\n            & Out_J & Inf_J & Hf & Hγ & FP_r & domm_IJ & domm_Iγ)\".\n    iPoseProof (inFP_domm with \"[$FP_n] [$]\") as \"%\".\n    by iPureIntro.\n  Qed.\n\n  Lemma own_alloc_set (S: gset K): True ==∗\n          ∃ (γ: gmap K gname), ([∗ set] k ∈ S, own (γ !!! k) (● (MaxNat 0))).\n  Proof.\n    iIntros \"_\".\n    iInduction S as [| s S] \"IH\" using set_ind_L.\n    - iModIntro. iExists _. try done.\n    - iMod (own_alloc (● (MaxNat 0))) as (γs)\"H'\".\n      { rewrite auth_auth_valid. try done. }\n      iDestruct \"IH\" as \">IH\".\n      iDestruct \"IH\" as (γ)\"IH\".\n      iModIntro. iExists (<[s := γs]> γ).\n      rewrite (big_sepS_delete _ ({[s]} ∪ S) s); last by set_solver.\n      iSplitL \"H'\". by rewrite lookup_total_insert.\n      assert (({[s]} ∪ S) ∖ {[s]} = S) as HS. set_solver.\n      rewrite HS.\n      iApply (big_sepS_mono\n                  (λ y, own (γ !!! y) (● {| max_nat_car := 0 |}) )%I\n                  (λ y, own (<[s:=γs]> γ !!! y) (● {| max_nat_car := 0 |}))%I\n                  S); try done.\n      intros k k_in_S. iFrame. iIntros \"H'\".\n      rewrite lookup_total_insert_ne; last by set_solver.\n      done.\n      (* No idea what is happening here *)\n      Unshelve. exact (∅: gmap K gname).\n  Qed.\n\n\n  Lemma ghost_heap_sync γ_gh n γ_en γ_cn γ_qn γ_cirn\n                                      γ_en' γ_cn' γ_qn' γ_cirn' :\n    own γ_gh (◯ {[n := ghost_loc γ_en γ_cn γ_qn γ_cirn]})\n      -∗ own γ_gh (◯ {[n := ghost_loc γ_en' γ_cn' γ_qn' γ_cirn']})\n          -∗ ⌜γ_en = γ_en'⌝ ∗ ⌜γ_cn = γ_cn'⌝\n              ∗ ⌜γ_qn = γ_qn'⌝ ∗ ⌜γ_cirn = γ_cirn'⌝.\n  Proof.\n    iIntros \"H1 H2\". iCombine \"H1\" \"H2\" as \"H\".\n    iPoseProof (own_valid with \"H\") as \"Valid\".\n    iDestruct \"Valid\" as %Valid.\n    rewrite auth_frag_valid in Valid *; intros Valid.\n    apply singleton_valid in Valid.\n    apply to_agree_op_inv in Valid.\n    apply leibniz_equiv in Valid.\n    inversion Valid.\n    by iPureIntro.\n  Qed.\n\n  Lemma ghost_heap_update γ_gh (hγ: gmap Node per_node_gl) n\n                                γ_en γ_cn γ_qn γ_cirn :\n    ⌜n ∉ dom (gset Node) hγ⌝ -∗\n          own γ_gh (● hγ) ==∗\n            own γ_gh (● <[n := ghost_loc γ_en γ_cn γ_qn γ_cirn]> hγ)\n          ∗ own γ_gh (◯ {[n := ghost_loc γ_en γ_cn γ_qn γ_cirn]}).\n  Proof.\n    iIntros \"%\". rename H into n_notin_hγ.\n    iIntros \"Hown\". set (<[ n := ghost_loc γ_en γ_cn γ_qn γ_cirn ]> hγ) as hγ'.\n    iDestruct (own_update _ _\n        (● hγ' ⋅ ◯ {[ n := ghost_loc γ_en γ_cn γ_qn γ_cirn ]})\n               with \"Hown\") as \"Hown\".\n    { apply auth_update_alloc.\n      rewrite /hγ'.\n      apply alloc_local_update; last done.\n      by rewrite <-not_elem_of_dom. }\n    iMod (own_op with \"Hown\") as \"[Ht● Ht◯]\".\n    iModIntro. iFrame.\n  Qed.\n\n  Lemma frac_eq γ_e γ_c γ_q es Cn Qn es' Cn' Qn' :\n              frac_ghost_state γ_e γ_c γ_q es Cn Qn -∗\n                  frac_ghost_state γ_e γ_c γ_q es' Cn' Qn' -∗\n                    ⌜es = es'⌝ ∗ ⌜Cn = Cn'⌝ ∗ ⌜Qn = Qn'⌝.\n  Proof.\n    iIntros \"H1 H2\". unfold frac_ghost_state.\n    iDestruct \"H1\" as \"(H1_es & H1_c & H1_q)\".\n    iDestruct \"H2\" as \"(H2_es & H2_c & H2_q)\".\n    iPoseProof (own_valid_2 _ _ _ with \"[$H1_es] [$H2_es]\") as \"Hes\".\n    iPoseProof (own_valid_2 _ _ _ with \"[$H1_c] [$H2_c]\") as \"Hc\".\n    iPoseProof (own_valid_2 _ _ _ with \"[$H1_q] [$H2_q]\") as \"Hq\".\n    iDestruct \"Hes\" as %Hes. iDestruct \"Hc\" as %Hc. iDestruct \"Hq\" as %Hq.\n    apply frac_agree_op_valid in Hes. destruct Hes as [_ Hes].\n    apply frac_agree_op_valid in Hc. destruct Hc as [_ Hc].\n    apply frac_agree_op_valid in Hq. destruct Hq as [_ Hq].\n    apply leibniz_equiv_iff in Hes.\n    apply leibniz_equiv_iff in Hc.\n    apply leibniz_equiv_iff in Hq.\n    iPureIntro. repeat split; try done.\n  Qed.\n\n  Lemma frac_update γ_e γ_c γ_q es Cn Qn es' Cn' Qn' :\n              frac_ghost_state γ_e γ_c γ_q es Cn Qn ∗\n                 frac_ghost_state γ_e γ_c γ_q es Cn Qn ==∗\n                      frac_ghost_state γ_e γ_c γ_q es' Cn' Qn' ∗\n                        frac_ghost_state γ_e γ_c γ_q es' Cn' Qn'.\n  Proof.\n    iIntros \"(H1 & H2)\".\n    iDestruct \"H1\" as \"(H1_es & H1_c & H1_q)\".\n    iDestruct \"H2\" as \"(H2_es & H2_c & H2_q)\".\n    iCombine \"H1_es H2_es\" as \"Hes\".\n    iEval (rewrite <-frac_agree_op) in \"Hes\".\n    iEval (rewrite Qp_half_half) in \"Hes\".\n    iCombine \"H1_c H2_c\" as \"Hc\".\n    iEval (rewrite <-frac_agree_op) in \"Hc\".\n    iEval (rewrite Qp_half_half) in \"Hc\".\n    iCombine \"H1_q H2_q\" as \"Hq\".\n    iEval (rewrite <-frac_agree_op) in \"Hq\".\n    iEval (rewrite Qp_half_half) in \"Hq\".\n    iMod ((own_update (γ_e) (to_frac_agree 1 es)\n                  (to_frac_agree 1 es')) with \"[$Hes]\") as \"Hes\".\n    { apply cmra_update_exclusive. \n      unfold valid, cmra_valid. simpl. unfold prod_valid_instance.\n      split; simpl; try done. }\n    iEval (rewrite <-Qp_half_half) in \"Hes\".\n    iEval (rewrite frac_agree_op) in \"Hes\".\n    iDestruct \"Hes\" as \"(H1_es & H2_es)\".\n    iMod ((own_update (γ_c) (to_frac_agree 1 Cn)\n                  (to_frac_agree 1 Cn')) with \"[$Hc]\") as \"Hc\".\n    { apply cmra_update_exclusive. \n      unfold valid, cmra_valid. simpl. unfold prod_valid_instance.\n      split; simpl; try done. }\n    iEval (rewrite <-Qp_half_half) in \"Hc\".\n    iEval (rewrite frac_agree_op) in \"Hc\".\n    iDestruct \"Hc\" as \"(H1_c & H2_c)\".\n    iMod ((own_update (γ_q) (to_frac_agree 1 Qn)\n                  (to_frac_agree 1 Qn')) with \"[$Hq]\") as \"Hq\".\n    { apply cmra_update_exclusive. \n      unfold valid, cmra_valid. simpl. unfold prod_valid_instance.\n      split; simpl; try done. }\n    iEval (rewrite <-Qp_half_half) in \"Hq\".\n    iEval (rewrite frac_agree_op) in \"Hq\".\n    iDestruct \"Hq\" as \"(H1_q & H2_q)\".\n    iModIntro. iFrame.\n  Qed.\n\n  Lemma flowint_update_result (γ: gname) (I I_n I_n': multiset_flowint_ur K) x :\n    ⌜flowint_update_P (_) I I_n I_n' x⌝ ∗ own γ x -∗\n    ∃ I', ⌜contextualLeq (_) I I'⌝\n          ∗ ⌜∃ I_o, I = I_n ⋅ I_o ∧ I' = I_n' ⋅ I_o⌝\n          ∗ own γ (● I' ⋅ ◯ I_n').\n  Proof.\n    unfold flowint_update_P.\n    case_eq (view_auth_proj x); last first.\n    - intros Hx. iIntros \"(% & ?)\". iExFalso. done.\n    - intros [q a] Hx.\n      iIntros \"[HI' Hown]\". iDestruct \"HI'\" as %HI'.\n      destruct HI' as [I' HI'].\n      destruct HI' as [Hagree [Hq [HIn [Hcontxl HIo]]]].\n      iExists I'.\n      iSplit. by iPureIntro.\n      iSplit. by iPureIntro. destruct x.\n      simpl in Hx. simpl in HIn.\n      rewrite Hx. rewrite <-HIn.\n      rewrite Hq Hagree.\n      assert (● I' ⋅ ◯ I_n' = View (Some (1%Qp, to_agree I')) I_n') as H'.\n      { rewrite /(● I' ⋅ ◯ I_n'). unfold cmra_op.\n        simpl. unfold view_op_instance. simpl.\n        assert (ε ⋅ I_n' = I_n') as H'. by rewrite left_id.\n        rewrite H'. unfold op, cmra_op. by simpl. }\n      by iEval (rewrite H').\n  Qed.\n\n  Lemma flowint_update_result' (γ: gname) (I I_n I_n': multiset_flowint_ur KT) x :\n    ⌜flowint_update_P (_) I I_n I_n' x⌝ ∗ own γ x -∗\n    ∃ I', ⌜contextualLeq (_) I I'⌝\n          ∗ ⌜∃ I_o, I = I_n ⋅ I_o ∧ I' = I_n' ⋅ I_o⌝\n          ∗ own γ (● I' ⋅ ◯ I_n').\n  Proof.\n    unfold flowint_update_P.\n    case_eq (view_auth_proj x); last first.\n    - intros Hx. iIntros \"(% & ?)\". iExFalso. done.\n    - intros [q a] Hx.\n      iIntros \"[HI' Hown]\". iDestruct \"HI'\" as %HI'.\n      destruct HI' as [I' HI'].\n      destruct HI' as [Hagree [Hq [HIn [Hcontxl HIo]]]].\n      iExists I'.\n      iSplit. by iPureIntro.\n      iSplit. by iPureIntro. destruct x.\n      simpl in Hx. simpl in HIn.\n      rewrite Hx. rewrite <-HIn.\n      rewrite Hq Hagree.\n      assert (● I' ⋅ ◯ I_n' = View (Some (1%Qp, to_agree I')) I_n') as H'.\n      { rewrite /(● I' ⋅ ◯ I_n'). unfold cmra_op.\n        simpl. unfold view_op_instance. simpl.\n        assert (ε ⋅ I_n' = I_n') as H'. by rewrite left_id.\n        rewrite H'. unfold op, cmra_op. by simpl. }\n      by iEval (rewrite H').\n  Qed.\n\n  Lemma dom_lookup (C: gmap K nat) k :\n        C !! k ≠ None → k ∈ dom (gset K) C.\n  Proof.\n    intros Hcn. destruct (C !! k) eqn: Hcnk.\n    rewrite elem_of_dom. rewrite Hcnk.\n    by exists n. done.\n  Qed.\n\n  Definition map_subset (S: gset K) (C: gmap K nat) :=\n              let f := λ a s', s' ∪ {[(a, C !!! a)]} in\n                        set_fold f (∅: gset KT) S.\n\n  Definition map_restriction (S: gset K) (C: gmap K T) :=\n              let f := λ a m, <[a := C !!! a ]> m in\n                        set_fold f (∅: gmap K T) S.\n\n\n  Lemma lookup_map_restriction S (C: gmap K nat) (k: K):\n              k ∈ S → map_restriction S C !! k = Some (C !!! k).\n  Proof.\n    set (P := λ (m: gmap K nat) (X: gset K),\n                    ∀ x, x ∈ X → m !! x = Some (C !!! x)).\n    apply (set_fold_ind_L P); try done.\n    intros x X r Hx HP.\n    unfold P in HP. unfold P.\n    intros x' Hx'.\n    destruct (decide (x' = x)).\n    - subst x'. by rewrite lookup_insert.\n    - assert (x' ∈ X) as x'_in_X. set_solver.\n      rewrite lookup_insert_ne. apply HP.\n      done. done.\n  Qed.\n\n  Lemma map_subset_member S C k t:\n              (k, t) ∈ map_subset S C ↔ k ∈ S ∧ t = C !!! k.\n  Proof.\n    set (P := λ (m: gset KT) (X: gset K),\n                    ∀ kx tx, (kx, tx) ∈ m ↔ kx ∈ X ∧ tx = C !!! kx).\n    apply (set_fold_ind_L P); try done.\n    - unfold P. intros kx tx. set_solver.\n    - intros x X r Hx HP. unfold P.\n      unfold P in HP. intros kx' tx'.\n      split.\n      + intros Hktx. rewrite elem_of_union in Hktx*; intros Hktx.\n        destruct Hktx as [H' | H'].\n        * apply HP in H'. destruct H' as [H' H''].\n          split; try done. set_solver.\n        * rewrite elem_of_singleton in H'*; intros H'.\n          inversion H'. split; try done; set_solver.\n      + intros [H' H'']. rewrite elem_of_union in H'*; intros H'.\n        destruct H' as [H' | H'].\n        rewrite elem_of_singleton in H'*; intros H'.\n        rewrite H'. rewrite H''. set_solver.\n        assert ((kx', tx') ∈ r) as Hkt.\n        apply HP. split; try done.\n        set_solver.\n  Qed.\n\n  Lemma map_restriction_dom S C :\n              dom (gset K) (map_restriction S C) = S.\n  Proof.\n    set (P := λ (m: gmap K nat) (X: gset K), dom (gset K) m = X).\n    apply (set_fold_ind_L P); try done.\n    - unfold P; set_solver.\n    - intros x X r Hx HP. unfold P. unfold P in HP.\n      apply leibniz_equiv. rewrite dom_insert.\n      rewrite HP. done.\n  Qed.\n\n\n  Lemma nodePred_nodeShared_eq γ_I γ_J γ_f γ_gh r n\n                               γ_en γ_cn γ_qn γ_cirn\n                               γ_en' γ_cn' γ_qn' γ_cirn'\n                               es Tn Qn es' Tn' Qn'\n                               Bn In Jn H :\n        own γ_gh (◯ {[n := ghost_loc γ_en γ_cn γ_qn γ_cirn]}) -∗\n          frac_ghost_state γ_en γ_cn γ_qn es Tn Qn -∗\n            nodeShared' γ_I γ_J γ_f γ_gh r n Tn' Qn' Bn H \n                    γ_en' γ_cn' γ_qn' γ_cirn' es' In Jn -∗\n              frac_ghost_state γ_en γ_cn γ_qn es Tn Qn\n              ∗ nodeShared' γ_I γ_J γ_f γ_gh r n Tn Qn Bn H \n                    γ_en γ_cn γ_qn γ_cirn es In Jn\n              ∗ ⌜es' = es⌝ ∗ ⌜Tn' = Tn⌝  ∗ ⌜Qn' = Qn⌝.\n  Proof.\n    iIntros \"HnP_gh HnP_frac HnS\".\n    iDestruct \"HnS\" as \"(HnS_gh & HnS_frac & HnS_si & HnS_FP\n                        & HnS_cl & HnS_oc & HnS_Bn & HnS_H  & HnS_star & Hφ)\".\n    iPoseProof (ghost_heap_sync with \"[$HnP_gh] [$HnS_gh]\")\n                              as \"(% & % & % & %)\".\n    subst γ_en'. subst γ_cn'. subst γ_qn'. subst γ_cirn'.\n    iPoseProof (frac_eq with \"[$HnP_frac] [$HnS_frac]\") as \"%\".\n    destruct H0 as [Hes [Hc Hq]].\n    subst es'. subst Tn'. subst Qn'.\n    iFrame. by iPureIntro.\n  Qed.\n\n  (** Lock module **)\n\n  Lemma lockNode_spec_high N γ_te γ_he γ_s Prot γ_I γ_J γ_f γ_gh r n:\n    ⊢ mcs_inv N γ_te γ_he γ_s Prot\n                (Inv_LSM γ_s γ_I γ_J γ_f γ_gh r) -∗\n        inFP γ_f n -∗\n              <<< True >>>\n                lockNode #n    @ ⊤ ∖ ↑(mcsN N)\n              <<< ∃ Cn Qn, nodePred γ_gh γ_s r n Cn Qn, RET #() >>>.\n  Proof.\n    iIntros \"#mcsInv #FP_n\".\n    iIntros (Φ) \"AU\".\n    awp_apply (lockNode_spec n).\n    iInv \"mcsInv\" as (T H) \"(mcs_high & >Inv_LSM)\".\n    iDestruct \"Inv_LSM\" as (hγ I J) \"(Hglob & Hstar)\".\n    iPoseProof (inFP_domm_glob with \"[$FP_n] [$Hglob]\") as \"%\".\n    rename H0 into n_in_I.\n    iEval (rewrite (big_sepS_elem_of_acc (_) (domm I) n);\n           last by eauto) in \"Hstar\".\n    iDestruct \"Hstar\" as \"(Hn & Hstar')\".\n    iDestruct \"Hn\" as (b Cn Qn) \"(HlockR & Hns)\".\n    iAaccIntro with \"HlockR\".\n    { iIntros \"HlockRn\". iModIntro.\n      iSplitR \"AU\".\n      { iExists T, H. iNext. iFrame.\n        iExists hγ, I, J. iFrame.\n        iPoseProof (\"Hstar'\" with \"[-]\") as \"Hstar\".\n        iExists b, Cn, Qn. iFrame.\n        iFrame.\n      }\n      iFrame.\n    }\n    iIntros \"(HlockRn & Hnp)\".\n    iMod \"AU\" as \"[_ [_ Hclose]]\".\n    iMod (\"Hclose\" with \"[Hnp]\") as \"HΦ\"; try done.\n    iModIntro. iSplitR \"HΦ\".\n    iNext. iExists T, H. iFrame.\n    iExists hγ, I, J. iFrame.\n    iPoseProof (\"Hstar'\" with \"[HlockRn Hns]\") as \"Hstar\".\n    iExists true, Cn, Qn. iFrame.\n    iFrame. done.\n  Qed.\n\n\n  Lemma nodePred_lockR_true γ_gh γ_s r bn n es Cn Cn' Qn' :\n    node r n es Cn -∗\n      lockR bn n (nodePred γ_gh γ_s r n Cn' Qn') -∗\n        ⌜bn = true⌝.\n  Proof.\n    iIntros \"node Hl_n\".\n    destruct bn; try done.\n    iDestruct \"Hl_n\" as \"(Hl & HnP')\".\n    iDestruct \"HnP'\" as (? ? ? ? ? ? ?) \"(n' & _)\".\n    iExFalso. iApply (node_sep_star r n). iFrame.\n  Qed.\n\n  Lemma lockR_true Cn' Qn' γ_gh γ_s r n Cn Qn:\n    lockR true n (nodePred γ_gh γ_s r n Cn Qn) -∗\n      lockR true n (nodePred γ_gh γ_s r n Cn' Qn').\n  Proof.\n    iIntros \"(Hl & _)\". iFrame.\n  Qed.\n\n  Lemma unlockNode_spec_high N γ_te γ_he γ_s Prot γ_I γ_J γ_f γ_gh r\n                                                          n Cn Qn:\n    ⊢ mcs_inv N γ_te γ_he γ_s Prot (Inv_LSM γ_s γ_I γ_J γ_f γ_gh r) -∗\n        inFP γ_f n -∗ nodePred γ_gh γ_s r n Cn Qn -∗\n              <<< True >>>\n                unlockNode #n    @ ⊤ ∖ ↑(mcsN N)\n              <<< True, RET #() >>>.\n  Proof.\n    iIntros \"#mcsInv #FP_n Hnp\". iIntros (Φ) \"AU\".\n    awp_apply (unlockNode_spec n).\n    iInv \"mcsInv\" as (T H) \"(mcs_high & >Inv_LSM)\".\n    iDestruct \"Inv_LSM\" as (hγ I J) \"(Hglob & Hstar)\".\n    iPoseProof (inFP_domm_glob with \"[$FP_n] [$Hglob]\") as \"%\".\n    rename H0 into n_in_I.\n    iEval (rewrite (big_sepS_elem_of_acc (_) (domm I) n);\n           last by eauto) in \"Hstar\".\n    iDestruct \"Hstar\" as \"(Hn & Hstar')\".\n    iDestruct \"Hn\" as (b Cn' Qn') \"(HlockR & Hns)\".\n    iAssert (lockR true n (nodePred γ_gh γ_s r n Cn Qn)\n              ∗ (nodePred γ_gh γ_s r n Cn Qn))%I\n      with \"[HlockR Hnp]\" as \"HlockR\".\n    {\n      destruct b eqn: Hb.\n    - (* Case n locked *)\n      iFrame \"∗\".\n    - (* Case n unlocked: impossible *)\n      iDestruct \"Hnp\" as (? ? ? ? ? ? ?)\"(node & _)\".\n      iPoseProof (nodePred_lockR_true with \"[$node] [$HlockR]\") as \"H'\".\n      iDestruct \"H'\" as %H'; inversion H'.\n    }\n    iAaccIntro with \"HlockR\".\n    { iIntros \"(HlockR & Hnp)\". iModIntro.\n      iSplitR \"Hnp AU\".\n      iExists T, H. iNext. iFrame.\n      iExists hγ, I, J. iFrame.\n      iPoseProof (\"Hstar'\" with \"[HlockR Hns]\") as \"Hstar\".\n      iExists true, Cn', Qn'. iFrame.\n      iFrame. iFrame.\n    }\n    iIntros \"HlockR\".\n    iMod \"AU\" as \"[_ [_ Hclose]]\".\n    iMod (\"Hclose\" with \"[]\") as \"HΦ\"; try done.\n    iModIntro. iSplitR \"HΦ\".\n    iNext. iExists T, H. iFrame.\n    iExists hγ, I, J. iFrame.\n    iPoseProof (\"Hstar'\" with \"[HlockR Hns]\") as \"Hstar\".\n    iExists false, Cn, Qn.\n    iAssert (lockR false n (nodePred γ_gh γ_s r n Cn Qn)\n                      ∗ nodeShared γ_I γ_J γ_f γ_gh r n Qn H)%I\n      with \"[Hns HlockR]\" as \"(HlockR & Hns)\".\n    {\n      iDestruct \"HlockR\" as \"(Hl & Hnp)\".\n      iDestruct \"Hnp\" as (γ_en γ_cn γ_qn γ_cirn esn Vn Tn)\n                             \"(node_n & #HnP_gh & HnP_frac & HnP_C & HnP_cts)\".\n      iDestruct \"Hns\" as (γ_en' γ_cn' γ_qn' γ_cirn' es' Tn' Bn' In0 Jn0) \"Hns'\".\n      iPoseProof (nodePred_nodeShared_eq with \"[$HnP_gh] [$HnP_frac] [$Hns']\")\n         as \"(HnP_frac & Hns' & % & % & %)\".\n      iSplitR \"Hns'\".\n      - iFrame. iExists γ_en, γ_cn, γ_qn, γ_cirn, esn, Vn, Tn.\n        iFrame \"∗#\".\n      - iExists γ_en, γ_cn, γ_qn, γ_cirn, esn, Tn, Bn', In0.\n        iExists Jn0.\n        iFrame.\n    }\n    iFrame. iFrame. iFrame.\n  Qed.\n\nEnd multicopy_lsm_util.", "meta": {"author": "nyu-acsys", "repo": "template-proofs", "sha": "3911d3f9c25f3fffdd95d6aa052fae606f4d52c2", "save_path": "github-repos/coq/nyu-acsys-template-proofs", "path": "github-repos/coq/nyu-acsys-template-proofs/template-proofs-3911d3f9c25f3fffdd95d6aa052fae606f4d52c2/templates/multicopy/multicopy_lsm_util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2361488619622795}}
{"text": "(****************************************************************************)\n(* Copyright 2021 The Project Oak Authors                                   *)\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\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import coqutil.Tactics.Tactics.\nRequire Import coqutil.Datatypes.Prod.\n\nRequire Import Cava.Util.Byte.\nRequire Import Cava.Types.\nRequire Import Cava.Expr.\nRequire Import Cava.Primitives.\nRequire Import Cava.TLUL.\nRequire Import Cava.Invariant.\nRequire Import Cava.Primitives.\nRequire Import Cava.Semantics.\nRequire Import Cava.Expr.\nRequire Import Cava.ExprProperties.\nRequire Import Cava.Util.Tactics.\nRequire Import Cava.Util.List.\nRequire Import Cava.Util.If.\nRequire Import Cava.Util.Nat.\nRequire Import Cava.Util.Byte.\n\nRequire Import HmacHardware.Hmac.\nRequire Import HmacHardware.Sha256.\nRequire Import HmacHardware.Sha256InnerProperties.\nRequire Import HmacHardware.Sha256PadderProperties.\nRequire Import HmacHardware.Sha256Properties.\nRequire Import HmacSpec.SHA256Properties.\n\nImport ListNotations.\n\nLocal Notation ShaRepr :=\n  (list Byte.byte * bool * nat * nat * nat * bool)%type.\nLocal Notation FifoRepr :=\n  (list N * list Byte.byte * bool * list Byte.byte)%type.\n\nLocal Notation HmacInnerSpecRepr :=\n  ( nat\n  * bool\n  * bool\n  * bool\n  * bool\n  * option (list N)\n  * bool\n  * ShaRepr\n  )%type.\n\nInstance hmac_inner_invariant : invariant_for hmac_inner HmacInnerSpecRepr :=\n  fun circuit_state '(state, input_done, raised_process, sha_signaled_done, sha_ready, digest_buf, has_content, sha_repr) =>\n  let\n    '( (finishing, (waiting_for_digest, (accept_fifo, (ptr, (inner_state, (digest, circ_sha_ready))))))\n    , circuit_sha_state) := circuit_state in\n\n  let '((ready, (block, (digest1, (count, done)))),\n        (sha256_padder_state, sha256_inner_state)) := circuit_sha_state in\n\n  let '(msg, msg_complete, padder_byte_index, inner_byte_index, t, cleared) := sha_repr in\n\n     sha256_invariant circuit_sha_state sha_repr\n  /\\ (state = 0 \\/ state = 2 \\/ state = 3)\n  /\\ (inner_state = N.of_nat state)\n  /\\ (if state =? 3 then input_done = true else True)\n  /\\ (if msg_complete then input_done = true else True)\n\n  /\\ sha_ready = circ_sha_ready\n  /\\ (if state =? 3 then sha_signaled_done = negb waiting_for_digest else True )\n  /\\ (if state =? 0 then True else if has_content then cleared = false /\\ msg <> [] else True)\n  /\\ (if state =? 3 then has_content = true else True )\n  /\\ (if state =? 3 then msg <> [] else True )\n  /\\ (if state =? 3 then\n    (match digest_buf with\n    | Some x =>\n        x = BigEndianBytes.bytes_to_Ns 4 (SHA256.sha256 msg)\n        /\\ waiting_for_digest = false\n        /\\ digest = x\n    | _ => waiting_for_digest = true\n     end) else digest_buf = None)\n  .\n\nInstance hmac_inner_specification\n  : specification_for hmac_inner HmacInnerSpecRepr := {|\n\n  reset_repr := (0, false, false, false, false, None, false, reset_repr);\n\n  precondition\n    (input : denote_type (input_of hmac_inner))\n    '(state, input_done, raised_process, sha_signaled_done, sha_ready, digest_buf, _, sha_repr) :=\n    let\n      '(fifo_valid, (fifo_data, (fifo_length, (fifo_final,\n        (cmd_hash_start, (cmd_hash_process, (cmd_hmac_enable, (hmac_key_vec, tt)))))))) := input\n    in\n    let '(msg, msg_complete, padder_byte_index, inner_byte_index, t, cleared) := sha_repr in\n\n    (* ** SHA256 conditions : ** *)\n    (* the total message length (including any new data) cannot exceed 2 ^\n       64 bits (2^61 bytes) -- using N so Coq doesn't try to compute 2 ^ 61\n       in nat *)\n    (N.of_nat (length msg) + (if fifo_final then fifo_length else 4) < 2 ^ 61)%N\n     (* ...and if data is valid, it must be in expected range *)\n     /\\ (if fifo_valid\n        then if fifo_final\n             then (fifo_data < 2 ^ (8 * fifo_length))%N\n                  /\\ (1 <= fifo_length <= 4)%N\n             else (fifo_data < 2 ^ 32)%N\n        else True)\n\n    /\\ (if fifo_final then fifo_valid = true else True)\n    (* Disable cmd_hmac_enable mode for this spec by only allowing\n    cmd_hmac_enable flag during idle moments *)\n    /\\ (if cmd_hmac_enable then (state = 0 /\\ cmd_hash_start <> true) else True)\n    /\\ (if cmd_hash_process then (state = 2 \\/ state = 3) else raised_process = false)\n    /\\ (if state =? 0 then fifo_valid = false else cmd_hash_start = true)\n    /\\ (if cmd_hash_start then True else fifo_valid = false)\n\n    (* no valid input after fifo_final *)\n    /\\ (if input_done then fifo_valid = false else True)\n\n    (* cmd_hash_process must be continuously asserted *)\n    /\\ (if raised_process then cmd_hash_process  = true else True);\n\n  update_repr (input : denote_type (input_of hmac_inner))\n    '(state, input_done, raised_process, sha_signaled_done, sha_ready, digest_buf, has_content, sha_repr) :=\n\n    let\n      '(fifo_valid, (fifo_data, (fifo_length, (fifo_final,\n        (cmd_hash_start, (cmd_hash_process, (cmd_hmac_enable, (hmac_key_vec, tt)))))))) := input\n    in\n\n    let fifo_valid := if sha_ready then fifo_valid else false in\n\n    let sha_input :=\n      (* Only emulate sha mode *)\n      match state with\n      | 0 => (false, (0%N, (false, (0%N, (true, tt)))))\n      | 2 => (fifo_valid, (fifo_data, (fifo_final, (fifo_length, (false, tt)))))%bool\n      | _ => (false, (0%N, (false, (0%N, (false, tt)))))\n      end\n    in\n\n    let sha_repr' := update_repr (c:=sha256) sha_input sha_repr in\n    let '(msg, msg_complete, padder_byte_index, inner_byte_index, t, cleared) := sha_repr\n    in\n\n    let clear := if state =? 0 then true else false in\n    let is_cleared := if clear\n                      then true\n                      else if (cleared:bool)\n                           then negb (fst sha_input)\n                           else false in\n\n    let count_16_pre :=\n        if (if (padder_byte_index =? 64) then t =? 0 else t =? 64)\n        then if (padder_byte_index =? inner_byte_index + 64) then true else false else false\n    in\n    let count_le15_pre :=\n        if (padder_byte_index <? 64) then t =? 0 else t =? 64\n    in\n\n    let is_cleared_or_done :=\n        if is_cleared\n        then true\n        else if fifo_valid\n             then false\n             else\n               if count_16_pre\n               then false\n               else\n                if (padder_byte_index =? padded_message_size msg) then if (t =? 64) then true else false else false\n    in\n\n    let state' :=\n      match state with\n      | 0 => if cmd_hash_start then 2 else 0\n      | 2 => if sha_ready then if cmd_hash_process then if fifo_final then 3 else 2 else 2 else 2\n      | 3 => if sha_signaled_done then 0 else 3\n      | _ => 0\n      end in\n\n\n    (* new value of [t] *)\n    let new_t :=\n        if clear\n        then 0\n        else if cleared\n             then 0\n             else if (padder_byte_index =? inner_byte_index)\n                  then if t =? 64\n                       then t\n                       else S t\n                  else if (padder_byte_index =? inner_byte_index + 64)\n                       then 0\n                       else t in\n\n    (* ready for new input only if the inner loop is done and the padder is\n       not *)\n    let is_ready :=\n        if is_cleared\n        then true\n        else\n          if count_16_pre then false\n          else if count_le15_pre then\n            if (if padder_byte_index =? padded_message_size msg\n              then fifo_valid\n              else if (msg_complete: bool) then true else fifo_valid)\n            then padder_byte_index mod 64 <=? 56\n            else true\n          else if inner_byte_index =? padder_byte_index\n            then\n              if if (t =? 64)%nat then true else (inner_byte_index =? 0)%nat\n              then true\n              else (t =? 63)%nat\n            else true\n    in\n\n    let input_done' :=\n      if state =? 0\n      then false\n      else\n        if input_done\n        then true\n        else if fifo_final then sha_ready else false\n    in\n\n    let raised_process' :=\n      if state' =? 0\n      then false\n      else\n        if cmd_hash_process\n        then true\n        else raised_process\n    in\n\n    let digest_buf :=\n      if state =? 3 then\n        if state' =? 0 then None\n        else\n          if is_cleared_or_done\n          then Some (BigEndianBytes.bytes_to_Ns 4 (SHA256.sha256 msg))\n          else None\n      else None\n    in\n\n    let has_content' :=\n      if state =? 0 then false\n      else\n        if has_content then true else fifo_valid\n      (* 0 <? length msg *)\n    in\n\n    (state', input_done', raised_process', is_cleared_or_done, is_ready, digest_buf,\n      has_content',\n      sha_repr');\n\n  postcondition\n    (input : denote_type (input_of hmac_inner))\n    '(state, input_done, raised_process, sha_signaled_done, sha_ready, digest_buf, _, sha_repr)\n    (output : denote_type (output_of hmac_inner)) :=\n    let\n      '(fifo_valid, (fifo_data, (fifo_length, (fifo_final,\n        (cmd_hash_start, (cmd_hash_process, (cmd_hmac_enable, (hmac_key_vec, tt)))))))) := input in\n\n        let fifo_data_valid := if sha_ready then fifo_valid else false in\n        let clear := state =? 0 in\n\n    let '(msg, msg_complete, padder_byte_index, inner_byte_index, t, cleared) := sha_repr in\n    (* new value of [cleared] *)\n    let is_cleared := if clear\n                      then true\n                      else if cleared\n                           then negb fifo_data_valid\n                           else false in\n\n    let count_16_pre :=\n        if (if (padder_byte_index =? 64) then t =? 0 else t =? 64)\n        then if (padder_byte_index =? inner_byte_index + 64) then true else false else false\n    in\n    let count_le15_pre :=\n        if (padder_byte_index <? 64) then t =? 0 else t =? 64\n    in\n\n    let is_cleared_or_done :=\n        if is_cleared\n        then true\n        else if fifo_data_valid\n             then false\n             else\n               if count_16_pre\n               then false\n               else\n                if (padder_byte_index =? padded_message_size msg) then if (t =? 64) then true else false else false\n    in\n\n    (* new value of [padder_byte_index] *)\n    let new_padder_byte_index :=\n        if clear\n        then 0\n        else if cleared\n         then 0\n         else if (padder_byte_index =? inner_byte_index)\n              then if t =? 64\n                   then if (padder_byte_index =? padded_message_size msg)\n                        then padder_byte_index\n                        else if msg_complete\n                             then padder_byte_index + 4\n                             else if fifo_data_valid\n                                  then padder_byte_index + 4\n                                  else padder_byte_index\n                   else padder_byte_index\n              else if (padder_byte_index =? inner_byte_index + 64)\n                   then padder_byte_index\n                   else if msg_complete\n                        then padder_byte_index + 4\n                        else if fifo_data_valid\n                             then padder_byte_index + 4\n                             else padder_byte_index in\n\n    (* new value of [t] *)\n    let new_t :=\n        if clear\n        then 0\n        else if cleared\n             then 0\n             else if (padder_byte_index =? inner_byte_index)\n                  then if t =? 64\n                       then t\n                       else S t\n                  else if (padder_byte_index =? inner_byte_index + 64)\n                       then 0\n                       else t in\n\n    (* ready for new input only if the inner loop is done and the padder is\n       not *)\n    let is_ready :=\n        if is_cleared\n        then true\n        else\n          if count_16_pre then false\n          else if count_le15_pre then\n            if (if padder_byte_index =? padded_message_size msg\n              then fifo_data_valid\n              else if msg_complete then true else fifo_data_valid)\n            then padder_byte_index mod 64 <=? 56\n            else true\n          else if inner_byte_index =? padder_byte_index\n            then\n              if if (t =? 64)%nat then true else (inner_byte_index =? 0)%nat\n              then true\n              else (t =? 63)%nat\n            else true\n    in\n\n    let accept_fifo := if state =? 2 then is_ready else false in\n\n    exists done odigest,\n      output = (accept_fifo, (done, odigest))\n      /\\ match digest_buf with\n         | Some x => done = true /\\ odigest = x\n         | _ => done = false\n         end\n|}.\n\n(* TODO: move me *)\nLtac nat_const X :=\n  match X with\n  | O => idtac\n  | S ?Y => nat_const Y\n  | _ => fail\n  end.\nLtac destr_nat_match :=\n  match goal with\n  | |- context [?X =? ?Y] =>\n      nat_const X; nat_const Y;\n      destr (X =? Y); try lia\n  end.\nLtac destr_nat_match_hyp :=\n  match goal with\n  | _: context [?X =? ?Y] |- _ =>\n      nat_const X; nat_const Y;\n      destr (X =? Y); try lia\n  end.\n\nLtac fail_if_if_in X :=\n  lazymatch X with\n  | context [if _ then _ else _] => fail\n  | _ => idtac\n  end.\n\nLtac destruct_one_inner_match :=\n  match goal with\n  | |- context [if ?B then _ else _] => fail_if_if_in B; destr B\n  end.\n\nLocal Hint Unfold\n      hmac_inner_state\n      hmac_inner_local_state\n      sha256_state\n      sha256_outer_state\n      padder_state\n      sha256_inner_state\n  : stepsimpl.\n\nLemma hmac_inner_invariant_at_reset :\n  invariant_at_reset hmac_inner.\nProof.\n  simplify_invariant hmac_inner.\n  cbn [reset_repr reset_state hmac_inner hmac_inner_specification sha256 sha256_specification default].\n  stepsimpl.\n\n  ssplit;\n    lazymatch goal with\n    | |- sha256_invariant _ _ => apply sha256_invariant_at_reset\n    | _ => reflexivity || lia || idtac\n    end.\nQed.\n\nLemma hmac_inner_invariant_preserved :\n  invariant_preserved hmac_inner.\nProof.\n  simplify_invariant hmac_inner. cbn [absorb_any].\n  simplify_spec hmac_inner.\n\n  intros input state repr new_repr.\n  pose (input_:=input). pose (state_:=state). pose (repr_:=repr). pose (new_repr_:=new_repr).\n  revert dependent repr. revert dependent state. revert dependent input. revert dependent new_repr.\n\n  intros (((((((new_state, new_input_done), new_raised_process), new_sha_signaled_done), new_sha_ready), new_digest), has_content), new_sha_repr).\n  intro.\n  intros (fifo_valid, (fifo_data, (fifo_length, (fifo_final,\n         (cmd_hash_start, (cmd_hash_process, (cmd_hmac_enable, (hmac_key_vec, [])))))))).\n  intro.\n  intros\n      ( (finishing, (waiting_for_digest, (accept_fifo, (ptr, (inner_state, (digest_circ, sha_ready_circ))))))\n      , sha_state_circ).\n  intro.\n  intros (((((((state, input_done), raised_process), sha_signaled_done), sha_ready), digest), new_has_content), sha_repr).\n  intro.\n  destruct sha_repr as (((((msg,msg_complete),?),?),?),?).\n  destruct new_sha_repr as (((((?,?),?),?),?),?).\n  destruct sha_state_circ as ((ready, (?, (?, (?, ?)))), (padder, inner)).\n  destruct padder as (?, (?, (?, (?, (?, ?))))).\n  destruct inner as (?, (?, (?, ?))).\n  intros.\n\n  (* for some reason the modulo expands into ugly match statement without this *)\n  remember (n mod 64) as n_mod_64.\n  logical_simplify. subst.\n\n  cbv [hmac_inner K]. cbn [negb]. stepsimpl.\n  repeat (destruct_pair_let; cbn [fst snd]).\n\n  lazymatch goal with\n  | H : sha256_invariant ?state ?repr\n    |- context [step sha256 ?state ?input] =>\n    assert (precondition sha256 input repr)\n  end.\n  { simplify_spec sha256. cbn [reset_repr sha256_specification denote_type] in *.\n    autorewrite with Nnat.\n    logical_simplify; subst; try lia.\n\n    destr (state =? 7); try lia.\n    destr (state =? 6); try lia.\n    destr (state =? 5); try lia.\n    destr (state =? 4); try lia.\n    destr (state =? 1); try lia.\n\n    destr (state =? 3); logical_simplify; subst; try lia;\n    [|destr (state =? 0); logical_simplify; subst; try lia;\n    [|destr (state =? 2); logical_simplify; subst; try lia]].\n    all:\n      repeat (match goal with\n                  | |- context [ ?X =? ?Y ] => destr ( X =? Y); try lia\n                  | |- context [ ?X <=? ?Y ] => destr ( X <=? Y); try lia\n                  | |- context [ ( ?X =? ?Y )%N ] => destr ( X =? Y)%N; try lia\n                  | |- context [ ( ?X <=? ?Y )%N ] => destr ( X <=? Y)%N; try lia\n                  end; try lia); boolsimpl.\n    all: cbn [fst snd].\n    all: try rewrite Tauto.if_same.\n    all: rewrite ?List.app_nil_r.\n    all: cbv [new_msg_bytes].\n    all: try (destruct msg_complete); try (ssplit; lia).\n    all: destruct sha_ready_circ.\n    all: try (push_length; ssplit; lia).\n    all: destruct fifo_valid.\n    all: try (push_length; ssplit; lia).\n    all: destruct fifo_final; try lia.\n    all: try (push_length; ssplit; lia).\n    all: destruct input_done; try lia.\n  }\n\n  ssplit.\n  {\n    cbn [fst snd] in *.\n    match goal with\n    | |- context [ @step ?i ?s ?o sha256 ?state ?input ] =>\n        epose proof (@invariant_preserved_pf s i o sha256 ShaRepr _ _ sha256_correctness input state\n        (msg, msg_complete, n, n0, n1, b) (l, b0, n2, n3, n4, b1) _ H0 H\n        ) as HX\n        ; remember (fst (@step i s o sha256 state input)) as step_sha\n    end.\n\n    cbn [denote_type absorb_any sha_block sha_digest sha_word fst snd] in *.\n    destruct_products.\n    repeat (inversion_prod; cbn [fst snd] in *).\n    apply HX.\n    Unshelve.\n    cbn [update_repr sha256_specification].\n    repeat (rewrite <- tup_if; cbn [fst snd]).\n    repeat inversion_prod.\n    subst.\n    autorewrite with Nnat.\n    destruct state.\n    {\n      repeat destr_nat_match.\n      now cbn [fst snd].\n    }\n    destruct state.\n    { repeat destr_nat_match.  }\n    destruct state.\n    {\n      repeat destr_nat_match.\n      repeat (rewrite <- tup_if; cbn [fst snd]).\n      reflexivity.\n    }\n    destruct state.\n    {\n      replace (N.to_nat 4) with 4 by lia.\n      replace (N.to_nat 5) with 5 by lia.\n      replace (N.to_nat 6) with 6 by lia.\n      repeat destr_nat_match.\n      repeat destr_nat_match_hyp.\n      subst.\n      repeat (rewrite <- tup_if; cbn [fst snd]).\n      destruct b.\n      all: rewrite ?Tauto.if_same.\n      { reflexivity. }\n      { reflexivity. }\n    }\n    lia.\n  }\n  { repeat (destruct_one_match); lia. }\n  { autorewrite with Nnat.\n    destruct cmd_hmac_enable; try lia.\n    { destruct state.\n      { all: cbn; boolsimpl.\n        now destruct cmd_hash_start.\n      }\n      lia.\n    }\n\n    destruct state; cbn [fst] in *.\n    all: cbn; boolsimpl.\n    { now destruct cmd_hash_start. }\n    destruct state; cbn [fst] in *.\n    { lia. }\n    destruct state; [destruct b|]; cbn [fst] in *.\n    all: cbn; boolsimpl.\n    {\n      destruct sha_ready_circ, fifo_valid; boolsimpl; cbn [fst]; try lia.\n      all: destruct cmd_hash_process, fifo_final; boolsimpl; try lia.\n    }\n    {\n      destruct fifo_final; logical_simplify; subst; try lia.\n      all: repeat (destruct_one_match; try lia).\n    }\n\n    destruct state; cbn [fst] in *.\n    all: cbn; boolsimpl.\n    { destruct waiting_for_digest, sha_signaled_done;\n      repeat destr_nat_match_hyp;\n      subst; boolsimpl; try lia. }\n    lia.\n  }\n  {\n    destruct state.\n    { destruct cmd_hash_start; destruct_one_match; cbn [fst snd]; congruence. }\n    destruct state.\n    { lia. }\n    destruct state.\n    {\n      destr_nat_match.\n      repeat destruct_one_inner_match; try lia.\n    }\n    destruct state; [|try lia].\n    repeat destr_nat_match; repeat destruct_one_inner_match; try lia.\n  }\n  {\n    destr (state =?0); try lia.\n    {\n      subst; cbn [fst snd].\n      intros; logical_simplify; subst.\n      trivial.\n    }\n    destr (state =?2).\n    {\n      destruct b0; [|trivial].\n      logical_simplify; subst.\n      repeat destr_nat_match_hyp; repeat destr_nat_match; repeat destruct_one_inner_match; try lia.\n      all: destruct msg_complete; [lia|].\n      all: repeat inversion_prod; revert H23; repeat (rewrite <- tup_if; cbn [fst snd]).\n      all: destruct sha_ready_circ; try lia; boolsimpl.\n      all: rewrite ?Tauto.if_same; now intros.\n    }\n    destr (state =? 3); try lia.\n    subst state input_done.\n    destruct b0; trivial.\n  }\n\n  {\n    use_correctness' sha256.\n    destruct state.\n    {\n      autorewrite with Nnat.\n      repeat destr_nat_match.\n      repeat destr_nat_match_hyp.\n      now cbn.\n    }\n\n    destruct state.\n    { destr_nat_match. }\n\n    destruct state.\n    {\n      autorewrite with Nnat.\n      repeat destr_nat_match.\n      repeat destr_nat_match_hyp.\n      cbn [fst snd] in *.\n\n      subst; cbn [fst snd].\n      cbv [andb].\n      destruct sha_ready_circ, fifo_valid; boolsimpl; try reflexivity.\n    }\n\n    destruct state.\n    {\n      autorewrite with Nnat.\n      replace (N.to_nat 4) with 4 by lia.\n      replace (N.to_nat 5) with 5 by lia.\n      repeat destr_nat_match.\n      repeat destr_nat_match_hyp.\n      cbn [fst snd] in *.\n      subst.\n      rewrite ?Tauto.if_same.\n      reflexivity.\n    }\n\n    lia.\n  }\n\n  {\n    use_correctness' sha256.\n    destruct state.\n    {\n      replace ((if cmd_hash_start then 2 else 0) =? 3) with false\n        by (destruct_one_match; destr_nat_match; lia).\n      trivial.\n    }\n\n    destruct state.\n    { destr_nat_match. }\n\n    destruct state.\n    {\n      autorewrite with Nnat.\n      repeat destr_nat_match.\n      repeat destr_nat_match_hyp.\n      cbn [fst snd] in *.\n      boolsimpl.\n      destruct sha_ready_circ, cmd_hash_process; boolsimpl; try reflexivity.\n      destruct fifo_final; logical_simplify; subst; destr_nat_match; try lia.\n      rewrite ?Tauto.if_same.\n      destr_nat_match; boolsimpl.\n      reflexivity.\n    }\n\n    destruct state.\n    {\n      autorewrite with Nnat.\n      replace (N.to_nat 4) with 4 by lia.\n      replace (N.to_nat 5) with 5 by lia.\n      replace (N.to_nat 6) with 6 by lia.\n      repeat destr_nat_match.\n      repeat destr_nat_match_hyp.\n      boolsimpl.\n      cbn [fst snd] in *.\n      boolsimpl.\n      destruct cmd_hmac_enable; try lia.\n      destruct sha_signaled_done, sha_ready_circ, cmd_hash_process;\n        repeat (destr_nat_match; boolsimpl); try reflexivity.\n      all: destruct b; boolsimpl; try reflexivity.\n      all: rewrite ?Tauto.if_same.\n      all: try reflexivity.\n\n      all: destruct fifo_valid, waiting_for_digest; boolsimpl; repeat destr_nat_match; try reflexivity.\n      all: subst; try lia.\n    }\n\n    lia.\n  }\n\n  {\n    assert (forall {A} (ls: list A), length ls > 0 -> ls <> []) as Hx.\n    { clear; intros; now destruct ls. }\n\n    destruct state.\n    { repeat destr_nat_match.\n      destruct cmd_hash_start; destr_nat_match; reflexivity.\n    }\n    destruct state.\n    { repeat destr_nat_match. }\n    destruct state.\n    {\n      repeat destr_nat_match.\n      repeat destr_nat_match_hyp.\n\n      destruct sha_ready_circ; repeat destr_nat_match.\n      {\n        assert ((if cmd_hash_process then if fifo_final then 3 else 2 else 2) =? 0 = false).\n        { repeat destruct_one_inner_match; destr_nat_match. }\n        rewrite H11.\n        destruct new_has_content.\n        {\n          repeat inversion_prod.\n          logical_simplify; subst.\n          autorewrite with tuple_if.\n          cbn [fst snd].\n          split.\n          { now rewrite ?Tauto.if_same. }\n          { repeat destruct_one_inner_match; cbn [new_msg_bytes]; try trivial.\n            all: apply Hx; push_length.\n            all: destruct msg; try congruence.\n            all: cbn [length]; lia.\n          }\n        }\n        destruct fifo_valid; try trivial.\n        repeat inversion_prod.\n        subst.\n        autorewrite with tuple_if.\n        cbn [fst snd].\n        split.\n        { rewrite ?Tauto.if_same. now destruct b. }\n        { apply Hx; destruct b; cbn [new_msg_bytes].\n          { destruct fifo_final; length_hammer. }\n          repeat destruct_one_inner_match.\n          all: try length_hammer.\n          all: simplify_invariant sha256; logical_simplify; subst.\n          all: try congruence.\n          all: try (destruct msg_complete; logical_simplify; subst; try lia).\n        }\n      }\n      repeat inversion_prod.\n      subst.\n      autorewrite with tuple_if.\n      cbn [fst snd].\n      destruct new_has_content; try lia.\n      logical_simplify; subst.\n      split.\n      { now rewrite ?Tauto.if_same. }\n      repeat destruct_one_inner_match; trivial.\n    }\n    destruct state; try lia.\n    destruct sha_signaled_done; destr_nat_match.\n    destruct new_has_content; [|destruct sha_ready_circ, fifo_valid]; try trivial.\n    all: repeat inversion_prod; subst; autorewrite with tuple_if; cbn [fst snd];\n          logical_simplify; subst; split;\n\n      [ rewrite ?Tauto.if_same |\n      repeat destruct_one_inner_match; trivial].\n    { reflexivity. }\n    all: destr_nat_match_hyp; logical_simplify; subst.\n    all: congruence.\n  }\n\n  {\n    destruct state.\n    { destruct_one_inner_match; destr_nat_match; trivial. }\n    destruct state; try lia.\n    destruct state.\n    { repeat destruct_one_inner_match; repeat destr_nat_match; try lia.\n      trivial.\n    }\n    destruct state; try lia.\n    { repeat destruct_one_inner_match; repeat destr_nat_match; try lia.\n    }\n  }\n\n  {\n    assert (forall {A} (ls: list A), length ls > 0 -> ls <> []) as Hx.\n    { clear; intros; now destruct ls. }\n    destruct state.\n    { destruct_one_inner_match; destr_nat_match; trivial. }\n\n    destruct state; try lia.\n    destruct state.\n    { repeat destruct_one_inner_match; repeat destr_nat_match;\n        repeat destr_nat_match_hyp; logical_simplify; subst; try trivial.\n      destruct msg_complete; logical_simplify; subst; try lia.\n      destruct input_done; logical_simplify; subst; try lia.\n\n      repeat inversion_prod.\n      destruct new_has_content.\n      all: subst; autorewrite with tuple_if; cbn [fst snd].\n      all: logical_simplify; subst.\n      all: simplify_invariant sha256.\n      all: repeat destruct_one_inner_match; try trivial.\n      all: apply Hx; cbn [new_msg_bytes]; push_length; try lia.\n\n    }\n\n    destruct state; try destruct_one_inner_match; repeat destr_nat_match; try lia.\n    {\n      repeat inversion_prod.\n      subst; autorewrite with tuple_if; cbn [fst snd].\n      simplify_invariant sha256.\n      repeat destruct_one_inner_match; try trivial.\n      repeat destr_nat_match_hyp; logical_simplify; subst.\n    }\n  }\n\n  { destruct state.\n    { repeat destr_nat_match.\n      destruct cmd_hash_start; destr_nat_match; reflexivity.\n    }\n    destruct state.\n    { repeat destr_nat_match. }\n    destruct state.\n\n\n    { repeat destr_nat_match.\n      destruct sha_ready_circ, cmd_hash_process, fifo_final; destr_nat_match.\n      all: try reflexivity.\n      autorewrite with Nnat.\n      repeat destr_nat_match.\n      boolsimpl.\n      destruct cmd_hmac_enable; try lia.\n      use_correctness' sha256.\n      cbn [fst snd negb].\n      simplify_invariant sha256.\n      destr_nat_match.\n      destruct b; now boolsimpl.\n    }\n    destruct state.\n    {\n      use_correctness' sha256.\n      repeat destr_nat_match.\n      destruct sha_signaled_done.\n      { now repeat destr_nat_match. }\n      repeat destr_nat_match.\n      cbn [fst snd].\n      simplify_invariant sha256.\n      destruct b; boolsimpl.\n      { logical_simplify; subst.\n        split; [reflexivity|].\n        destruct cmd_hmac_enable; try lia.\n      }\n      logical_simplify; subst.\n      repeat inversion_prod.\n      autorewrite with tuple_if in H6.\n      cbn [fst snd] in *.\n      rewrite ?Tauto.if_same in H6.\n      subst.\n      rewrite ?Tauto.if_same.\n      match goal with\n      | |- match (if ?X then _ else _) with _ => _ end => destr X\n      end.\n      {\n        split; try reflexivity. subst.\n        rewrite ?Tauto.if_same.\n        split; try reflexivity.\n\n        autorewrite with Nnat in *.\n        replace (N.to_nat 4) with 4 in * by lia.\n        replace (N.to_nat 5) with 5 in * by lia.\n        repeat destr_nat_match_hyp.\n        cbn [fst] in *.\n        destruct sha_ready_circ; try trivial.\n      }\n      rewrite ?Tauto.if_same.\n\n      destruct cmd_hmac_enable;try lia.\n      autorewrite with Nnat.\n      replace (N.to_nat 4) with 4 by lia.\n      replace (N.to_nat 5) with 5 by lia.\n      replace (N.to_nat 6) with 6 by lia.\n      repeat destr_nat_match.\n      destruct waiting_for_digest; try lia.\n      now boolsimpl.\n    }\n    lia.\n  }\n\nQed.\n\nLemma hmac_inner_output_correct :\n  output_correct hmac_inner.\nProof.\n  simplify_invariant hmac_inner. cbn [absorb_any].\n  simplify_spec hmac_inner.\n\n  intros input state repr new_repr.\n  pose (input_:=input). pose (state_:=state). pose (repr_:=repr). pose (new_repr_:=new_repr).\n  revert dependent repr. revert dependent state. revert dependent input.\n\n  intros (fifo_valid, (fifo_data, (fifo_length, (fifo_final,\n         (cmd_hash_start, (cmd_hash_process, (cmd_hmac_enable, (hmac_key_vec, [])))))))).\n  intro.\n  intros\n      ( (finishing, (waiting_for_digest, (accept_fifo, (ptr, (inner_state, (digest_circ, sha_ready_circ))))))\n      , sha_state_circ).\n  intro.\n  intros (((((((state, input_done), raised_process), sha_signaled_done), sha_ready), digest), has_content), sha_repr).\n  intro.\n  destruct sha_repr as (((((msg,msg_complete),?),?),?),?).\n  destruct sha_state_circ as ((ready, (?, (?, (?, ?)))), (padder, inner)).\n  destruct padder as (?, (?, (?, (?, (?, ?))))).\n  destruct inner as (?, (?, (?, ?))).\n  intros.\n\n  (* for some reason the modulo expands into ugly match statement without this *)\n  remember (n mod 64) as n_mod_64.\n  logical_simplify. subst.\n\n  cbv [hmac_inner K]. cbn [negb]. stepsimpl.\n  repeat (destruct_inner_pair_let; cbn [fst snd]).\n\n  lazymatch goal with\n  | H : sha256_invariant ?state ?repr\n    |- context [step sha256 ?state ?input] =>\n    assert (precondition sha256 input repr)\n  end.\n  { simplify_spec sha256. cbn [reset_repr sha256_specification denote_type] in *.\n    autorewrite with Nnat.\n    logical_simplify; subst; try lia.\n\n    destr (state =? 7); try lia.\n    destr (state =? 6); try lia.\n    destr (state =? 5); try lia.\n    destr (state =? 4); try lia.\n    destr (state =? 1); try lia.\n\n    destr (state =? 3); logical_simplify; subst; try lia;\n    [|destr (state =? 0); logical_simplify; subst; try lia;\n    [|destr (state =? 2); logical_simplify; subst; try lia]].\n    all:\n      repeat (match goal with\n                  | |- context [ ?X =? ?Y ] => destr ( X =? Y); try lia\n                  | |- context [ ?X <=? ?Y ] => destr ( X <=? Y); try lia\n                  | |- context [ ( ?X =? ?Y )%N ] => destr ( X =? Y)%N; try lia\n                  | |- context [ ( ?X <=? ?Y )%N ] => destr ( X <=? Y)%N; try lia\n                  end; try lia); boolsimpl.\n    all: cbn [fst snd].\n    all: try rewrite Tauto.if_same.\n    all: rewrite ?List.app_nil_r.\n    all: cbv [new_msg_bytes].\n    all: try (destruct msg_complete); try (ssplit; lia).\n    all: destruct sha_ready_circ.\n    all: try (push_length; ssplit; lia).\n    all: destruct fifo_valid.\n    all: try (push_length; ssplit; lia).\n    all: destruct fifo_final; try lia.\n    all: try (push_length; ssplit; lia).\n    all: destruct input_done; try lia.\n  }\n\n  Ltac use_correctness' c :=\n    lazymatch goal with\n    | |- context [ @snd ?A ?B (@step ?i ?s ?o c ?state ?input) ] =>\n      find_correctness c;\n      pose proof (@output_correct_pf\n                    s i o c _ _ _ _\n                    input state _ ltac:(eassumption) ltac:(eassumption));\n      generalize dependent (@snd A B (@step i s o c state input)); intros;\n      try simplify_postcondition c\n      (* ; logical_simplify *)\n      (* ; subst *)\n    end.\n  use_correctness' sha256.\n\n  destruct H24 as [sha_done].\n  destruct H24 as [sha_digest].\n  destruct H24 as [sha_ready].\n  logical_simplify.\n\n  eexists (match digest with Some _ => true | _ => false end).\n  eexists (match digest with Some x => x | _ =>\n      match state with\n      | 0 => _\n      | 2 => _\n      | 3 => _\n      | _ => SHA256.H0\n      end\n     end).\n\n  ssplit.\n  {\n    autorewrite with Nnat in *.\n    destruct state; cbn [fst snd].\n    { logical_simplify; subst; repeat destr_nat_match; boolsimpl.\n      cbn [fst snd].\n      subst.\n      reflexivity.\n    }\n    destruct state; [lia|].\n    destruct state; cbn [fst snd].\n    { logical_simplify; subst; repeat destr_nat_match; boolsimpl.\n      cbn [fst snd].\n      subst.\n      apply f_equal.\n      destruct cmd_hmac_enable; try lia.\n      assert ((if (sha_ready_circ && cmd_hash_process && fifo_final)%bool then 3 else 2) =? 0 = false)\n       by (destruct sha_ready_circ, cmd_hash_process, fifo_final; cbn [andb]; destr_nat_match).\n      rewrite H4.\n      apply f_equal.\n\n      reflexivity.\n    }\n\n    destruct state; cbn [fst snd].\n    {\n      simplify_invariant sha256.\n      repeat destr_nat_match.\n      boolsimpl.\n      destruct cmd_hmac_enable; try lia.\n      apply f_equal.\n      destruct digest, waiting_for_digest; logical_simplify; try lia.\n      2:{ logical_simplify; subst; boolsimpl; reflexivity. }\n      logical_simplify; subst; boolsimpl.\n\n      repeat destr_nat_match.\n      autorewrite with Nnat.\n      replace (N.to_nat 4) with 4 in * by lia.\n      replace (N.to_nat 5) with 5 in * by lia.\n      replace (N.to_nat 6) with 6 in * by lia.\n      repeat destr_nat_match.\n      cbn [fst snd].\n\n      apply f_equal.\n      destruct b; try lia.\n      rewrite Tauto.if_same.\n      simplify_invariant sha256.\n      repeat destruct_one_inner_match; try reflexivity.\n      all: try lia.\n      all: cbn [fst] in *.\n      all: rewrite Tauto.if_same in H32.\n      all: trivial.\n    }\n    lia.\n  }\n\n  destruct digest; split; reflexivity.\nQed.\n\n\nExisting Instances hmac_inner_invariant_preserved hmac_inner_output_correct hmac_inner_invariant_at_reset.\n\nGlobal Instance hmac_inner_correctness : correctness_for hmac_inner.\nProof. constructor; try typeclasses eauto. Defined.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/silveroak-opentitan/hmac/hw/HmacInnerProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2361488619622795}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Program.\n\nFrom Fairness Require Export ITreeLib FairBeh NatStructs.\nFrom Fairness Require Export Mod ModSimStutter Concurrency.\nFrom Fairness Require Import pind LPCM World.\n\nSet Implicit Arguments.\n\n\n\nSection KSIM.\n\n  Context `{M: URA.t}.\n\n  Variable state_src: Type.\n  Variable state_tgt: Type.\n\n  Variable _ident_src: ID.\n  Let ident_src := sum_tid _ident_src.\n  Variable _ident_tgt: ID.\n  Let ident_tgt := sum_tid _ident_tgt.\n\n  Variable wf_src: WF.\n  Variable wf_tgt: WF.\n\n  Notation srcE := (programE _ident_src state_src).\n  Notation tgtE := (programE _ident_tgt state_tgt).\n\n  Variable wf_stt: Type -> Type -> WF.\n\n  Definition kshared :=\n    ((@imap ident_src wf_src) *\n       (@imap ident_tgt wf_tgt) *\n       state_src *\n       state_tgt)%type.\n\n  Definition to_kshared (shr: shared state_src state_tgt _ident_src _ident_tgt wf_src wf_tgt): kshared :=\n    let '(ths, im_src, im_tgt, st_src, st_tgt) := shr in\n    (im_src, im_tgt, st_src, st_tgt).\n\n  Definition threads2 _id ev R := Th.t (prod bool (@thread _id ev R)).\n  Notation threads_src1 R0 := (threads _ident_src (sE state_src) R0).\n  Notation threads_src2 R0 := (threads2 _ident_src (sE state_src) R0).\n  Notation threads_tgt R1 := (threads _ident_tgt (sE state_tgt) R1).\n\n  Variant __sim_knot R0 R1 (RR: R0 -> R1 -> Prop)\n          (sim_knot: threads_src2 R0 -> threads_tgt R1 -> thread_id -> local_resources -> bool -> bool -> (prod bool (itree srcE R0)) -> (itree tgtE R1) -> kshared -> (wf_stt R0 R1).(T) -> Prop)\n          (_sim_knot: threads_src2 R0 -> threads_tgt R1 -> thread_id -> local_resources -> bool -> bool -> (prod bool (itree srcE R0)) -> (itree tgtE R1) -> kshared -> (wf_stt R0 R1).(T) -> Prop)\n          (thsl: threads_src2 R0) (thsr: threads_tgt R1)\n    :\n    thread_id -> local_resources -> bool -> bool -> (prod bool (itree srcE R0)) -> itree tgtE R1 -> kshared -> (wf_stt R0 R1).(T) -> Prop :=\n    | ksim_ret_term\n        tid f_src f_tgt\n        sf r_src r_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (RET: RR r_src r_tgt)\n        (NILS: Th.is_empty thsl = true)\n        (NILT: Th.is_empty thsr = true)\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, Ret r_src)\n                 (Ret r_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n\n    | ksim_ret_cont\n        tid f_src f_tgt\n        sf r_src r_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        o0\n        rs_local0 r_own r_shared0\n        (UPDRS: rs_local0 = NatMap.add tid r_own rs_local)\n        (WF: resources_wf r_shared0 rs_local0)\n        (STUTTER: (wf_stt R0 R1).(lt) o0 o)\n        (RET: RR r_src r_tgt)\n        (NNILS: Th.is_empty thsl = false)\n        (NNILT: Th.is_empty thsr = false)\n        (KSIM: forall tid0,\n            ((nm_pop tid0 thsl = None) /\\ (nm_pop tid0 thsr = None)) \\/\n              (exists b th_src thsl0 th_tgt thsr0,\n                  (nm_pop tid0 thsl = Some ((b, th_src), thsl0)) /\\\n                    (nm_pop tid0 thsr = Some (th_tgt, thsr0)) /\\\n                    ((b = true) ->\n                     (forall im_tgt0\n                        (FAIR: fair_update im_tgt im_tgt0 (prism_fmap inlp (tids_fmap tid0 (key_set thsr0)))),\n                         (sim_knot thsl0 thsr0 tid0\n                                   (snd (get_resource tid0 rs_local0))\n                                   true true\n                                   (b, Vis (inl1 (inl1 (inr1 Yield))) (fun _ => th_src))\n                                   (th_tgt)\n                                   (im_src, im_tgt0, st_src, st_tgt) o0))) /\\\n                    ((b = false) ->\n                     (forall im_tgt0\n                        (FAIR: fair_update im_tgt im_tgt0 (prism_fmap inlp (tids_fmap tid0 (key_set thsr0)))),\n                       exists im_src0,\n                         (fair_update im_src im_src0 (prism_fmap inlp (tids_fmap tid0 (key_set thsl0)))) /\\\n                           (sim_knot thsl0 thsr0 tid0\n                                     (snd (get_resource tid0 rs_local0))\n                                     true true\n                                     (b, th_src)\n                                     th_tgt\n                                     (im_src0, im_tgt0, st_src, st_tgt) o0)))))\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, Ret r_src)\n                 (Ret r_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n\n    | ksim_sync\n        tid f_src f_tgt\n        sf ktr_src ktr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        thsl0 thsr0\n        rs_local0 r_own r_shared0\n        (UPDRS: rs_local0 = NatMap.add tid r_own rs_local)\n        (WF: resources_wf r_shared0 rs_local0)\n        (THSL: thsl0 = Th.add tid (true, ktr_src tt) thsl)\n        (THSR: thsr0 = Th.add tid (ktr_tgt tt) thsr)\n        (KSIM: forall tid0,\n            ((nm_pop tid0 thsl0 = None) /\\ (nm_pop tid0 thsr0 = None)) \\/\n              (exists b th_src thsl1 th_tgt thsr1,\n                  (nm_pop tid0 thsl0 = Some ((b, th_src), thsl1)) /\\\n                    (nm_pop tid0 thsr0 = Some (th_tgt, thsr1)) /\\\n                    ((b = true) ->\n                     (forall im_tgt0 (FAIR: fair_update im_tgt im_tgt0 (prism_fmap inlp (tids_fmap tid0 (key_set thsr1)))),\n                       exists o0, ((wf_stt R0 R1).(lt) o0 o) /\\\n                               (sim_knot thsl1 thsr1 tid0\n                                         (snd (get_resource tid0 rs_local0))\n                                         true true\n                                         (b, Vis (inl1 (inl1 (inr1 Yield))) (fun _ => th_src))\n                                         (th_tgt)\n                                         (im_src, im_tgt0, st_src, st_tgt) o0))) /\\\n                    ((b = false) ->\n                     (forall im_tgt0 (FAIR: fair_update im_tgt im_tgt0 (prism_fmap inlp (tids_fmap tid0 (key_set thsr1)))),\n                       exists im_src0 o0,\n                         (fair_update im_src im_src0 (prism_fmap inlp (tids_fmap tid0 (key_set thsl1)))) /\\\n                           ((wf_stt R0 R1).(lt) o0 o) /\\\n                           (sim_knot thsl1 thsr1 tid0\n                                     (snd (get_resource tid0 rs_local0))\n                                     true true\n                                     (b, th_src)\n                                     th_tgt\n                                     (im_src0, im_tgt0, st_src, st_tgt) o0)))))\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, Vis (inl1 (inl1 (inr1 Yield))) ktr_src)\n                 (Vis (inl1 (inl1 (inr1 Yield))) ktr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n\n    | ksim_yieldL\n        tid f_src f_tgt\n        sf ktr_src itr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: exists im_src0 o0,\n            (fair_update im_src im_src0 (prism_fmap inlp (tids_fmap tid (key_set thsl)))) /\\\n              (_sim_knot thsl thsr tid rs_local true f_tgt\n                         (false, ktr_src tt)\n                         itr_tgt\n                         (im_src0, im_tgt, st_src, st_tgt) o0))\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, Vis (inl1 (inl1 (inr1 Yield))) ktr_src)\n                 (itr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n\n    | ksim_tauL\n        tid f_src f_tgt\n        sf itr_src itr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: _sim_knot thsl thsr tid rs_local true f_tgt\n                         (sf, itr_src)\n                         itr_tgt\n                         (im_src, im_tgt, st_src, st_tgt) o)\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, Tau itr_src)\n                 (itr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n    | ksim_chooseL\n        tid f_src f_tgt\n        sf X ktr_src itr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: exists x, _sim_knot thsl thsr tid rs_local true f_tgt\n                              (sf, ktr_src x)\n                              itr_tgt\n                              (im_src, im_tgt, st_src, st_tgt) o)\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, Vis (inl1 (inl1 (inl1 (Choose X)))) ktr_src)\n                 (itr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n    | ksim_rmwL\n        tid f_src f_tgt\n        sf X rmw ktr_src itr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: _sim_knot thsl thsr tid rs_local true f_tgt\n                         (sf, ktr_src (snd (rmw st_src) : X))\n                         itr_tgt\n                         (im_src, im_tgt, fst (rmw st_src), st_tgt) o)\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, Vis (inr1 (Rmw rmw)) ktr_src)\n                 (itr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n    | ksim_tidL\n        tid f_src f_tgt\n        sf ktr_src itr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: _sim_knot thsl thsr tid rs_local true f_tgt\n                         (sf, ktr_src tid)\n                         itr_tgt\n                         (im_src, im_tgt, st_src, st_tgt) o)\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, Vis (inl1 (inl1 (inr1 GetTid))) ktr_src)\n                 (itr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n    | ksim_UB\n        tid f_src f_tgt\n        sf ktr_src itr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, Vis (inl1 (inl1 (inl1 Undefined))) ktr_src)\n                 (itr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n    | ksim_fairL\n        tid f_src f_tgt\n        sf fm ktr_src itr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: exists im_src0,\n            (<<FAIR: fair_update im_src im_src0 (prism_fmap inrp fm)>>) /\\\n              (_sim_knot thsl thsr tid rs_local true f_tgt\n                         (sf, ktr_src tt)\n                         itr_tgt\n                         (im_src0, im_tgt, st_src, st_tgt) o))\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, Vis (inl1 (inl1 (inl1 (Fair fm)))) ktr_src)\n                 (itr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n\n    | ksim_tauR\n        tid f_src f_tgt\n        sf itr_src itr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: _sim_knot thsl thsr tid rs_local f_src true\n                         (sf, itr_src)\n                         itr_tgt\n                         (im_src, im_tgt, st_src, st_tgt) o)\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, itr_src)\n                 (Tau itr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n    | ksim_chooseR\n        tid f_src f_tgt\n        sf itr_src X ktr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: forall x, _sim_knot thsl thsr tid rs_local f_src true\n                              (sf, itr_src)\n                              (ktr_tgt x)\n                              (im_src, im_tgt, st_src, st_tgt) o)\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, itr_src)\n                 (Vis (inl1 (inl1 (inl1 (Choose X)))) ktr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n    | ksim_rmwR\n        tid f_src f_tgt\n        sf itr_src X rmw ktr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: _sim_knot thsl thsr tid rs_local f_src true\n                         (sf, itr_src)\n                         (ktr_tgt (snd (rmw st_tgt) : X))\n                         (im_src, im_tgt, st_src, fst (rmw st_tgt)) o)\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, itr_src)\n                 (Vis (inr1 (Rmw rmw)) ktr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n    | ksim_tidR\n        tid f_src f_tgt\n        sf itr_src ktr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: _sim_knot thsl thsr tid rs_local f_src true\n                         (sf, itr_src)\n                         (ktr_tgt tid)\n                         (im_src, im_tgt, st_src, st_tgt) o)\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, itr_src)\n                 (Vis (inl1 (inl1 (inr1 GetTid))) ktr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n    | ksim_fairR\n        tid f_src f_tgt\n        sf itr_src fm ktr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: forall im_tgt0 (FAIR: fair_update im_tgt im_tgt0 (prism_fmap inrp fm)),\n            (_sim_knot thsl thsr tid rs_local f_src true\n                       (sf, itr_src)\n                       (ktr_tgt tt)\n                       (im_src, im_tgt0, st_src, st_tgt) o))\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, itr_src)\n                 (Vis (inl1 (inl1 (inl1 (Fair fm)))) ktr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n\n    | ksim_observe\n        tid f_src f_tgt\n        sf fn args ktr_src ktr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: forall ret, sim_knot thsl thsr tid rs_local true true\n                               (sf, ktr_src ret)\n                               (ktr_tgt ret)\n                               (im_src, im_tgt, st_src, st_tgt) o)\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, Vis (inl1 (inl1 (inl1 (Observe fn args)))) ktr_src)\n                 (Vis (inl1 (inl1 (inl1 (Observe fn args)))) ktr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n\n    | ksim_call\n        tid f_src f_tgt\n        sf fn args ktr_src itr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local f_src f_tgt\n                 (sf, (trigger (Call fn args) >>= ktr_src))\n                 itr_tgt\n                 (im_src, im_tgt, st_src, st_tgt) o\n\n    | ksim_progress\n        tid\n        sf itr_src itr_tgt\n        rs_local\n        im_src im_tgt st_src st_tgt o\n        (KSIM: sim_knot thsl thsr tid rs_local false false\n                        (sf, itr_src)\n                        itr_tgt\n                        (im_src, im_tgt, st_src, st_tgt) o)\n      :\n      __sim_knot RR sim_knot _sim_knot thsl thsr tid rs_local true true\n                 (sf, itr_src)\n                 (itr_tgt)\n                 (im_src, im_tgt, st_src, st_tgt) o\n  .\n\n  Definition sim_knot R0 R1 (RR: R0 -> R1 -> Prop):\n    threads_src2 R0 -> threads_tgt R1 -> thread_id -> local_resources ->\n    bool -> bool -> (prod bool (itree srcE R0)) -> (itree tgtE R1) -> kshared -> (wf_stt R0 R1).(T) -> Prop :=\n    paco10 (fun r => pind10 (__sim_knot RR r) top10) bot10.\n\n  Lemma __ksim_mon R0 R1 (RR: R0 -> R1 -> Prop):\n    forall r r' (LE: r <10= r'), (__sim_knot RR r) <11= (__sim_knot RR r').\n  Proof.\n    ii. inv PR; try (econs; eauto; fail).\n    { econs 2; eauto. i. specialize (KSIM tid0). des; eauto. right.\n      esplits; eauto.\n      i. specialize (KSIM2 H _ FAIR). des. esplits; eauto.\n    }\n    { econs 3; eauto. i. specialize (KSIM tid0). des; eauto. right.\n      esplits; eauto.\n      i. specialize (KSIM1 H _ FAIR). des. esplits; eauto.\n      i. specialize (KSIM2 H _ FAIR). des. esplits; eauto.\n    }\n  Qed.\n\n  Lemma _ksim_mon R0 R1 (RR: R0 -> R1 -> Prop): forall r, monotone10 (__sim_knot RR r).\n  Proof.\n    ii. inv IN; try (econs; eauto; fail).\n    { des. econs; eauto. }\n    { des. econs; eauto. }\n    { des. econs; eauto. }\n  Qed.\n\n  Lemma ksim_mon R0 R1 (RR: R0 -> R1 -> Prop): forall q, monotone10 (fun r => pind10 (__sim_knot RR r) q).\n  Proof.\n    ii. eapply pind10_mon_gen; eauto.\n    ii. eapply __ksim_mon; eauto.\n  Qed.\n\n  Local Hint Constructors __sim_knot: core.\n  Local Hint Unfold sim_knot: core.\n  Local Hint Resolve __ksim_mon: paco.\n  Local Hint Resolve _ksim_mon: paco.\n  Local Hint Resolve ksim_mon: paco.\n\n  Lemma ksim_reset_prog\n        R0 R1 (RR: R0 -> R1 -> Prop)\n        ths_src ths_tgt tid rs_local\n        ssrc tgt shr o\n        ps0 pt0 ps1 pt1\n        (KSIM: sim_knot RR ths_src ths_tgt tid rs_local ps1 pt1 ssrc tgt shr o)\n        (SRC: ps1 = true -> ps0 = true)\n        (TGT: pt1 = true -> pt0 = true)\n    :\n    sim_knot RR ths_src ths_tgt tid rs_local ps0 pt0 ssrc tgt shr o.\n  Proof.\n    revert_until RR. pcofix CIH. i.\n    move KSIM before CIH. revert_until KSIM. punfold KSIM.\n    pattern ths_src, ths_tgt, tid, rs_local, ps1, pt1, ssrc, tgt, shr, o.\n    revert ths_src ths_tgt tid rs_local ps1 pt1 ssrc tgt shr o KSIM.\n    eapply pind10_acc.\n    intros rr DEC IH ths_src ths_tgt tid rs_local ps1 pt1 ssrc tgt shr o KSIM. clear DEC.\n    intros ps0 pt0 SRC TGT.\n    eapply pind10_unfold in KSIM.\n    2:{ eapply _ksim_mon. }\n    inv KSIM.\n\n    { pfold. eapply pind10_fold. econs; eauto. }\n\n    { clear rr IH. pfold. eapply pind10_fold. eapply ksim_ret_cont; eauto. i.\n      specialize (KSIM0 tid0). des; eauto. right.\n      esplits; eauto.\n      - i; hexploit KSIM2; clear KSIM2 KSIM3; eauto. i. eapply upaco10_mon_bot; eauto.\n      - i; hexploit KSIM3; clear KSIM2 KSIM3; eauto. i. des. esplits; eauto. i. eapply upaco10_mon_bot; eauto.\n    }\n\n    { clear rr IH. pfold. eapply pind10_fold. eapply ksim_sync; eauto. i.\n      specialize (KSIM0 tid0). des; eauto. right.\n      esplits; eauto.\n      - i; hexploit KSIM2; clear KSIM2 KSIM3; eauto. i. des. esplits; eauto. i. eapply upaco10_mon_bot; eauto.\n      - i; hexploit KSIM3; clear KSIM2 KSIM3; eauto. i. des. esplits; eauto. i. eapply upaco10_mon_bot; eauto.\n    }\n\n    { des. pfold. eapply pind10_fold. eapply ksim_yieldL. esplits; eauto. split; ss.\n      destruct KSIM1 as [KSIM1 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_tauL. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { des. pfold. eapply pind10_fold. eapply ksim_chooseL. esplits. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_rmwL. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_tidL. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_UB. }\n\n    { des. pfold. eapply pind10_fold. eapply ksim_fairL. esplits; eauto. split; ss.\n      destruct KSIM1 as [KSIM1 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_tauR. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_chooseR. i. split; ss. specialize (KSIM0 x).\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_rmwR. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_tidR. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_fairR. i. split; ss. specialize (KSIM0 _ FAIR).\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_observe. i. specialize (KSIM0 ret). pclearbot.\n      right; eapply CIH; eauto.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_call. }\n\n    { hexploit SRC; ss; i; clarify. hexploit TGT; ss; i; clarify.\n      pfold. eapply pind10_fold. eapply ksim_progress. pclearbot.\n      right; eapply CIH; eauto.\n    }\n\n  Qed.\n\n  Lemma ksim_set_prog\n        R0 R1 (RR: R0 -> R1 -> Prop)\n        ths_src ths_tgt tid rs_local\n        ssrc tgt shr o\n        (KSIM: sim_knot RR ths_src ths_tgt tid rs_local true true ssrc tgt shr o)\n    :\n    forall ps pt, sim_knot RR ths_src ths_tgt tid rs_local ps pt ssrc tgt shr o.\n  Proof.\n    revert_until RR. pcofix CIH. i.\n    remember true as ps1 in KSIM at 1. remember true as pt1 in KSIM at 1.\n    move KSIM before CIH. revert_until KSIM. punfold KSIM.\n    pattern ths_src, ths_tgt, tid, rs_local, ps1, pt1, ssrc, tgt, shr, o.\n    revert ths_src ths_tgt tid rs_local ps1 pt1 ssrc tgt shr o KSIM.\n    eapply pind10_acc.\n    intros rr DEC IH ths_src ths_tgt tid rs_local ps1 pt1 ssrc tgt shr o KSIM. clear DEC.\n    intros Eps1 Ept1 ps pt. clarify.\n    eapply pind10_unfold in KSIM.\n    2:{ eapply _ksim_mon. }\n    inv KSIM.\n\n    { pfold. eapply pind10_fold. econs; eauto. }\n\n    { clear rr IH. pfold. eapply pind10_fold. eapply ksim_ret_cont; eauto. i.\n      specialize (KSIM0 tid0). des; eauto. right.\n      esplits; eauto.\n      - i; hexploit KSIM2; clear KSIM2 KSIM3; eauto. i. eapply upaco10_mon_bot; eauto.\n      - i; hexploit KSIM3; clear KSIM2 KSIM3; eauto. i. des. esplits; eauto.\n        i. eapply upaco10_mon_bot; eauto.\n    }\n\n    { clear rr IH. pfold. eapply pind10_fold. eapply ksim_sync; eauto. i.\n      specialize (KSIM0 tid0). des; eauto. right.\n      esplits; eauto.\n      - i; hexploit KSIM2; clear KSIM2 KSIM3; eauto. i. des. esplits; eauto. i. eapply upaco10_mon_bot; eauto.\n      - i; hexploit KSIM3; clear KSIM2 KSIM3; eauto. i. des. esplits; eauto. i. eapply upaco10_mon_bot; eauto.\n    }\n\n    { des. pfold. eapply pind10_fold. eapply ksim_yieldL. esplits; eauto. split; ss.\n      destruct KSIM1 as [KSIM1 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_tauL. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { des. pfold. eapply pind10_fold. eapply ksim_chooseL. esplits. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_rmwL. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_tidL. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_UB. }\n\n    { des. pfold. eapply pind10_fold. eapply ksim_fairL. esplits; eauto. split; ss.\n      destruct KSIM1 as [KSIM1 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_tauR. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_chooseR. i. split; ss. specialize (KSIM0 x).\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_rmwR. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_tidR. split; ss.\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_fairR. i. split; ss. specialize (KSIM0 _ FAIR).\n      destruct KSIM0 as [KSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_observe. i. specialize (KSIM0 ret). pclearbot.\n      right; eapply CIH; eauto.\n    }\n\n    { pfold. eapply pind10_fold. eapply ksim_call. }\n\n    { pclearbot. eapply paco10_mon_bot; eauto. eapply ksim_reset_prog. eauto. all: auto. }\n\n  Qed.\n\nEnd KSIM.\n#[export] Hint Constructors __sim_knot: core.\n#[export] Hint Unfold sim_knot: core.\n#[export] Hint Resolve __ksim_mon: paco.\n#[export] Hint Resolve _ksim_mon: paco.\n#[export] Hint Resolve ksim_mon: paco.\n", "meta": {"author": "damhiya", "repo": "fairness", "sha": "279dcc679bd18b85666b97d6b540d94299c5d66e", "save_path": "github-repos/coq/damhiya-fairness", "path": "github-repos/coq/damhiya-fairness/fairness-279dcc679bd18b85666b97d6b540d94299c5d66e/src/simulation/KnotSim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7057850278370112, "lm_q2_score": 0.3345894279828469, "lm_q1q2_score": 0.23614820874284329}}
{"text": "(** printing |-#    %\\vdash_{\\#}%    #&vdash;<sub>&#35;</sub>#     *)\n(** printing |-##   %\\vdash_{\\#\\#}%  #&vdash;<sub>&#35&#35</sub>#  *)\n(** printing |-##v  %\\vdash_{\\#\\#v}% #&vdash;<sub>&#35&#35v</sub># *)\n(** printing |-!    %\\vdash_!%       #&vdash;<sub>!</sub>#         *)\n(** remove printing ~ *)\n\nSet Implicit Arguments.\n\nRequire Import TLC.LibLN.\nRequire Import String.\n\nRequire Import Definitions RecordAndInertTypes Decompose.\n\n(** * Abstract Syntax for Constraint Language *)\n\n(** ** Type and Term with constraint-bound variables *)\n\n(** *** Variables\n    The variables can either be bound by the core calculus (∀, let),\n    or by the constraint (∃ X. C).  *)\nInductive cvar : Set :=\n  | cvar_avar : avar -> cvar\n  | cvar_cvar : nat -> cvar.\n\n(** *** Type with type variables\n    All constructors are the same as those in [typ], except for one additional\n    constructor for type variables.\n    [ctyp_tvar] represents the reference to a type variable bound by\n    the constraint (∃t), represented by de Bruijn indices.  *)\nInductive ctyp : Set :=\n  | ctyp_top  : ctyp\n  | ctyp_bot  : ctyp\n  | ctyp_tvar : nat -> ctyp\n  | ctyp_typ : typ -> ctyp\n  | ctyp_rcd  : cdec -> ctyp\n  | ctyp_and  : ctyp -> ctyp -> ctyp\n  | ctyp_sel  : cvar -> typ_label -> ctyp\n  | ctyp_bnd  : ctyp -> ctyp\n  | ctyp_all  : ctyp -> ctyp -> ctyp\nwith cdec : Set :=\n  | cdec_typ  : typ_label -> ctyp -> ctyp -> cdec\n  | cdec_trm  : trm_label -> ctyp -> cdec.\n\n(** *** Terms with variables bound by constraints. *)\nInductive ctrm : Set :=\n  | ctrm_var  : cvar -> ctrm\n  | ctrm_trm  : trm -> ctrm\n  | ctrm_val  : cval -> ctrm\n  | ctrm_sel  : cvar -> trm_label -> ctrm\n  | ctrm_app  : cvar -> cvar -> ctrm\n  | ctrm_let  : ctrm -> ctrm -> ctrm\nwith cval : Set :=\n  | cval_new  : ctyp -> cdefs -> cval\n  | cval_lambda : ctyp -> ctrm -> cval\nwith cdef : Set :=\n  | cdef_typ  : typ_label -> ctyp -> cdef\n  | cdef_trm  : trm_label -> ctrm -> cdef\nwith cdefs : Set :=\n  | cdefs_nil : cdefs\n  | cdefs_cons : cdefs -> cdef -> cdefs.\n\nScheme ctyp_mut := Induction for ctyp Sort Prop\nwith   cdec_mut := Induction for cdec Sort Prop.\nCombined Scheme ctyp_mutind from ctyp_mut, cdec_mut.\n\nScheme ctrm_mut  := Induction for ctrm  Sort Prop\nwith   cval_mut  := Induction for cval Sort Prop\nwith   cdef_mut  := Induction for cdef  Sort Prop\nwith   cdefs_mut := Induction for cdefs Sort Prop.\nCombined Scheme ctrm_mutind from ctrm_mut, cval_mut, cdef_mut, cdefs_mut.\n\n(** Coercions *)\nCoercion ctyp_typ : typ >-> ctyp.\nCoercion ctrm_trm : trm >-> ctrm.\n\n(** *** Closeness\n    A type or term is closed, if it does not refer to variables bound\n    by the existential qualifier of the constraint language.\n\n    In other words, all type variables and term variables are substituted\n    to concrete types and variables.  *)\nInductive ctyp_closed : ctyp -> typ -> Prop :=\n| ctyp_top_closed : ctyp_closed ctyp_top typ_top\n| ctyp_bot_closed : ctyp_closed ctyp_bot typ_bot\n| ctyp_typ_closed : forall T,\n    ctyp_closed (ctyp_typ T) T\n| ctyp_rcd_closed : forall D D',\n    cdec_closed D D' ->\n    ctyp_closed (ctyp_rcd D) (typ_rcd D')\n| ctyp_and_closed : forall T T' U U',\n    ctyp_closed T T' ->\n    ctyp_closed U U' ->\n    ctyp_closed (ctyp_and T U) (typ_and T' U')\n| ctyp_sel_closed : forall x T,\n    ctyp_closed (ctyp_sel (cvar_avar x) T) (typ_sel x T)\n| ctyp_bnd_closed : forall T T',\n    ctyp_closed T T' -> ctyp_closed (ctyp_bnd T) (typ_bnd T')\n| ctyp_all_closed : forall S S' T T',\n    ctyp_closed S S' ->\n    ctyp_closed T T' ->\n    ctyp_closed (ctyp_all S T) (typ_all S' T')\nwith cdec_closed : cdec -> dec -> Prop :=\n| cdec_typ_closed : forall A S S' T T',\n    ctyp_closed S S' ->\n    ctyp_closed T T' ->\n    cdec_closed (cdec_typ A S T) (dec_typ A S' T')\n| cdec_trm_closed : forall a T T',\n    ctyp_closed T T' ->\n    cdec_closed (cdec_trm a T) (dec_trm a T')\n.\n\nScheme ctyp_closed_mut    := Induction for ctyp_closed Sort Prop\nwith   cdec_closed_mut    := Induction for cdec_closed Sort Prop.\nCombined Scheme ctyp_closed_mutind from ctyp_closed_mut, cdec_closed_mut.\n\nInductive ctrm_closed : ctrm -> trm -> Prop :=\n| ctrm_cvar_closed : forall x,\n    ctrm_closed (ctrm_var (cvar_avar x)) (trm_var x)\n| ctrm_trm_closed : forall t,\n    ctrm_closed (ctrm_trm t) t\n| ctrm_val_closed : forall v v',\n    cval_closed v v' ->\n    ctrm_closed (ctrm_val v) (trm_val v')\n| ctrm_sel_closed : forall x T,\n    ctrm_closed (ctrm_sel (cvar_avar x) T) (trm_sel x T)\n| ctrm_app_closed : forall x y,\n    ctrm_closed (ctrm_app (cvar_avar x) (cvar_avar y)) (trm_app x y)\n| ctrm_let_closed : forall t t' u u',\n    ctrm_closed t t' ->\n    ctrm_closed u u' ->\n    ctrm_closed (ctrm_let t u) (trm_let t' u')\nwith cval_closed : cval -> val -> Prop :=\n| cval_new_closed : forall T T' ds ds',\n    ctyp_closed T T' ->\n    cdefs_closed ds ds' ->\n    cval_closed (cval_new T ds) (val_new T' ds')\n| cval_lambda_closed : forall T T' t t',\n    ctyp_closed T T' ->\n    ctrm_closed t t' ->\n    cval_closed (cval_lambda T t) (val_lambda T' t')\nwith cdef_closed : cdef -> def -> Prop :=\n| cdef_typ_closed : forall A T T',\n    ctyp_closed T T' ->\n    cdef_closed (cdef_typ A T) (def_typ A T')\n| cdef_trm_closed : forall a t t',\n    ctrm_closed t t' ->\n    cdef_closed (cdef_trm a t) (def_trm a t')\nwith cdefs_closed : cdefs -> defs -> Prop :=\n| cdefs_nil_closed : cdefs_closed cdefs_nil defs_nil\n| cdefs_cons_closed : forall d d' ds ds',\n    cdef_closed d d' ->\n    cdefs_closed ds ds' ->\n    cdefs_closed (cdefs_cons ds d) (defs_cons ds' d')\n.\n\nLemma ctyp_closed_unique : forall T T1 T2,\n    ctyp_closed T T1 ->\n    ctyp_closed T T2 ->\n    T1 = T2\nwith cdec_closed_unique : forall D D1 D2,\n    cdec_closed D D1 ->\n    cdec_closed D D2 ->\n    D1 = D2.\nProof.\n  all: introv Hc1 Hc2.\n  - induction Hc1; inversion Hc2; subst; auto;\n      try (f_equal; apply* cdec_closed_unique);\n      try (f_equal; apply* ctyp_closed_unique).\n  - induction Hc1; inversion Hc2; subst; auto;\n      try (f_equal; apply* ctyp_closed_unique).\nQed.\n\nLemma ctrm_closed_unique : forall t t1 t2,\n    ctrm_closed t t1 ->\n    ctrm_closed t t2 ->\n    t1 = t2\nwith cval_closed_unique : forall v v1 v2,\n    cval_closed v v1 ->\n    cval_closed v v2 ->\n    v1 = v2\nwith cdef_closed_unique : forall d d1 d2,\n    cdef_closed d d1 ->\n    cdef_closed d d2 ->\n    d1 = d2\nwith cdefs_closed_unique : forall ds ds1 ds2,\n    cdefs_closed ds ds1 ->\n    cdefs_closed ds ds2 ->\n    ds1 = ds2.\nProof.\n  all: introv Hc1 Hc2; induction Hc1;\n    inversion Hc2; subst; auto;\n    try (f_equal; eauto);\n    try apply* ctyp_closed_unique.\nQed.\n\n(** ** Constraint Language *)\nInductive constr : Set :=\n(** ⊤ *)\n| constr_true : constr\n(** ⊥ *)\n| constr_false : constr\n(** C ⋏ D *)\n| constr_and : constr -> constr -> constr\n(** C ⋎ D *)\n| constr_or : constr -> constr -> constr\n(** ∃X. C *)\n| constr_exists_typ : constr -> constr\n(** ∃x. C *)\n| constr_exists_var : constr -> constr\n(** S <: T *)\n| constr_sub : ctyp -> ctyp -> constr\n(** t : T *)\n| constr_typ : ctrm -> ctyp -> constr\n.\n\n(** - true constraint *)\nNotation \"⊤\" := constr_true.\n(** - false constraint *)\nNotation \"⊥\" := constr_false.\n(** - and constraint *)\nNotation \"C '⋏' D\" := (constr_and C D) (at level 30).\n(** - or constraint *)\nNotation \"C '⋎' D\" := (constr_or C D) (at level 30).\n(** - type existence constraint *)\nNotation \"'∃t' C\" := (constr_exists_typ C) (at level 30).\n(** - variable existence constraint *)\nNotation \"'∃v' C\" := (constr_exists_var C) (at level 30).\n(** - typing constraint *)\nNotation \"x '⦂' T\" := (constr_typ x T) (at level 29).\n(** - subtyping constraint *)\nNotation \"S '<⦂' T\" := (constr_sub S T) (at level 29).\n\n(** Syntax sugars *)\n(** - type equality constraint *)\nNotation \"S '=⦂=' T\" := (S <⦂ T ⋏ T <⦂ S) (at level 29).\n\n(** ** Opening *)\n\nFixpoint open_rec_ctyp_typ (k : nat) (t : typ) (T : ctyp) : ctyp :=\n  match T with\n  | ctyp_top => ctyp_top\n  | ctyp_bot => ctyp_bot\n  | ctyp_tvar i => If k = i then ctyp_typ t else ctyp_tvar i\n  | ctyp_typ u => ctyp_typ u\n  | ctyp_rcd D => ctyp_rcd (open_rec_cdec_typ k t D)\n  | ctyp_and T U => ctyp_and (open_rec_ctyp_typ k t T) (open_rec_ctyp_typ k t U)\n  | ctyp_sel x T => ctyp_sel x T\n  | ctyp_bnd T => ctyp_bnd (open_rec_ctyp_typ k t T)\n  | ctyp_all T U => ctyp_all (open_rec_ctyp_typ k t T) (open_rec_ctyp_typ k t U)\n  end\nwith open_rec_cdec_typ (k : nat) (t : typ) (D : cdec) : cdec :=\n  match D with\n  | cdec_typ A T U => cdec_typ A (open_rec_ctyp_typ k t T) (open_rec_ctyp_typ k t U)\n  | cdec_trm a T => cdec_trm a (open_rec_ctyp_typ k t T)\n  end.\n\nDefinition open_rec_cvar (k : nat) (u : var) (v : cvar) : cvar :=\n  match v with\n  | cvar_avar x => cvar_avar x\n  | cvar_cvar i => If k = i then cvar_avar (avar_f u) else cvar_cvar i\n  end.\n\nFixpoint open_rec_ctyp_var (k : nat) (u : var) (T : ctyp) : ctyp :=\n  match T with\n  | ctyp_top => ctyp_top\n  | ctyp_bot => ctyp_bot\n  | ctyp_tvar i => ctyp_tvar i\n  | ctyp_typ u => ctyp_typ u\n  | ctyp_rcd D => ctyp_rcd (open_rec_cdec_var k u D)\n  | ctyp_and T U => ctyp_and (open_rec_ctyp_var k u T) (open_rec_ctyp_var k u U)\n  | ctyp_sel x T => ctyp_sel (open_rec_cvar k u x) T\n  | ctyp_bnd T => ctyp_bnd (open_rec_ctyp_var k u T)\n  | ctyp_all T U => ctyp_all (open_rec_ctyp_var k u T) (open_rec_ctyp_var k u U)\n  end\nwith open_rec_cdec_var (k : nat) (u : var) (D : cdec) : cdec :=\n  match D with\n  | cdec_typ A T U => cdec_typ A (open_rec_ctyp_var k u T) (open_rec_ctyp_var k u U)\n  | cdec_trm a T => cdec_trm a (open_rec_ctyp_var k u T)\n  end.\n\nFixpoint open_rec_ctrm_typ (k : nat) (t : typ) (u : ctrm) : ctrm :=\n  match u with\n  | ctrm_var x => ctrm_var x\n  | ctrm_trm t => ctrm_trm t\n  | ctrm_val v => ctrm_val (open_rec_cval_typ k t v)\n  | ctrm_sel x T => ctrm_sel x T\n  | ctrm_app x y => ctrm_app x y\n  | ctrm_let t1 t2 => ctrm_let (open_rec_ctrm_typ k t t1) (open_rec_ctrm_typ k t t2)\n  end\nwith open_rec_cval_typ (k : nat) (t : typ) (v : cval) : cval :=\n  match v with\n  | cval_new T ds => cval_new (open_rec_ctyp_typ k t T) (open_rec_cdefs_typ k t ds)\n  | cval_lambda T u => cval_lambda (open_rec_ctyp_typ k t T) (open_rec_ctrm_typ k t u)\n  end\nwith open_rec_cdef_typ (k : nat) (t : typ) (d : cdef) : cdef :=\n  match d with\n  | cdef_typ A T => cdef_typ A (open_rec_ctyp_typ k t T)\n  | cdef_trm a u => cdef_trm a (open_rec_ctrm_typ k t u)\n  end\nwith open_rec_cdefs_typ (k : nat) (t : typ) (ds : cdefs) : cdefs :=\n  match ds with\n  | cdefs_nil => cdefs_nil\n  | cdefs_cons ds d => cdefs_cons (open_rec_cdefs_typ k t ds) (open_rec_cdef_typ k t d)\n  end.\n\nFixpoint open_rec_ctrm_var (k : nat) (u : var) (t : ctrm) : ctrm :=\n  match t with\n  | ctrm_var x => ctrm_var (open_rec_cvar k u x)\n  | ctrm_trm t => ctrm_trm t\n  | ctrm_val v => ctrm_val (open_rec_cval_var k u v)\n  | ctrm_sel x T => ctrm_sel (open_rec_cvar k u x) T\n  | ctrm_app x y => ctrm_app (open_rec_cvar k u x) (open_rec_cvar k u y)\n  | ctrm_let t1 t2 => ctrm_let (open_rec_ctrm_var k u t1) (open_rec_ctrm_var k u t2)\n  end\nwith open_rec_cval_var (k : nat) (u : var) (v : cval) : cval :=\n  match v with\n  | cval_new T ds => cval_new (open_rec_ctyp_var k u T) (open_rec_cdefs_var k u ds)\n  | cval_lambda T t => cval_lambda (open_rec_ctyp_var k u T) (open_rec_ctrm_var k u t)\n  end\nwith open_rec_cdef_var (k : nat) (u : var) (d : cdef) : cdef :=\n  match d with\n  | cdef_typ A T => cdef_typ A (open_rec_ctyp_var k u T)\n  | cdef_trm a t => cdef_trm a (open_rec_ctrm_var k u t)\n  end\nwith open_rec_cdefs_var (k : nat) (u : var) (ds : cdefs) : cdefs :=\n  match ds with\n  | cdefs_nil => cdefs_nil\n  | cdefs_cons ds d => cdefs_cons (open_rec_cdefs_var k u ds) (open_rec_cdef_var k u d)\n  end.\n\nFixpoint open_rec_constr_typ (k : nat) (T : typ) (C : constr) : constr :=\n  match C with\n  | constr_true => constr_true\n  | constr_false => constr_false\n  | constr_and C1 C2 => constr_and (open_rec_constr_typ k T C1) (open_rec_constr_typ k T C2)\n  | constr_or C1 C2 => constr_or (open_rec_constr_typ k T C1) (open_rec_constr_typ k T C2)\n  | constr_exists_typ C => constr_exists_typ (open_rec_constr_typ (S k) T C)\n  | constr_exists_var C => constr_exists_var (open_rec_constr_typ k T C)\n  | constr_sub T1 T2 => constr_sub (open_rec_ctyp_typ k T T1) (open_rec_ctyp_typ k T T2)\n  | constr_typ t T0 => constr_typ (open_rec_ctrm_typ k T t) (open_rec_ctyp_typ k T T0)\n  end.\n\nFixpoint open_rec_constr_var (k : nat) (u : var) (C : constr) : constr :=\n  match C with\n  | constr_true => constr_true\n  | constr_false => constr_false\n  | constr_and C1 C2 => constr_and (open_rec_constr_var k u C1) (open_rec_constr_var k u C2)\n  | constr_or C1 C2 => constr_or (open_rec_constr_var k u C1) (open_rec_constr_var k u C2)\n  | constr_exists_typ C => constr_exists_typ (open_rec_constr_var k u C)\n  | constr_exists_var C => constr_exists_var (open_rec_constr_var (S k) u C)\n  | constr_sub T1 T2 => constr_sub (open_rec_ctyp_var k u T1) (open_rec_ctyp_var k u T2)\n  | constr_typ t T0 => constr_typ (open_rec_ctrm_var k u t) (open_rec_ctyp_var k u T0)\n  end.\n\nDefinition open_ctyp_typ (S : typ) (T : ctyp) : ctyp := open_rec_ctyp_typ 0 S T.\nDefinition open_cdec_typ (S : typ) (D : cdec) : cdec := open_rec_cdec_typ 0 S D.\nDefinition open_ctyp_var (u : var) (T : ctyp) : ctyp := open_rec_ctyp_var 0 u T.\nDefinition open_cdec_var (u : var) (D : cdec) : cdec := open_rec_cdec_var 0 u D.\nDefinition open_constr_typ (T : typ) (C : constr) : constr := open_rec_constr_typ 0 T C.\nDefinition open_constr_var (u : var) (C : constr) : constr := open_rec_constr_var 0 u C.\n\nNotation \"C '^^t' T\" := (open_constr_typ T C) (at level 30).\nNotation \"C '^^v' u\" := (open_constr_var u C) (at level 30).\n\n(** ** Lemmas on openning and closed types *)\n\nLtac invsc H := inversion H; subst; clear H.\nLtac invs H := inversion H; subst.\n\nLtac open_closed_eq_aux :=\n  match goal with\n  | |- (?P ?L) = (?P ?R) =>\n      assert (L = R) as ?H by eauto\n  | |- (?P ?L1 ?L2) = (?P ?R1 ?R2) =>\n      assert (L1 = R1) as ?H by eauto\n  end.\n\nLtac simpl_open_ctyp :=\n  unfold open_ctyp_typ, open_cdec_typ, open_ctyp_var, open_cdec_var; simpl.\n\nLtac solve_cong_eq :=\n  solve [\n    f_equal; eauto\n  ].\n\nLemma open_closed_ctyp_typ_unchanged : forall S T T',\n    ctyp_closed T T' ->\n    open_ctyp_typ S T = T\nwith open_closed_cdec_typ_unchanged : forall S D D',\n    cdec_closed D D' ->\n    open_cdec_typ S D = D.\nProof.\n  all: introv Hc; induction Hc; auto; simpl_open_ctyp; try solve_cong_eq.\nQed.\n\nLemma open_closed_ctyp_var_unchanged : forall S T T',\n    ctyp_closed T T' ->\n    open_ctyp_var S T = T\nwith open_closed_cdec_var_unchanged : forall S D D',\n    cdec_closed D D' ->\n    open_cdec_var S D = D.\nProof.\n  all: introv Hc; induction Hc; auto; simpl_open_ctyp; try solve_cong_eq.\nQed.\n\nDefinition is_closed_ctyp (T : ctyp) := exists T', ctyp_closed T T'.\n\nLemma open_closed_ctyp_typ_unchanged' : forall S T,\n    is_closed_ctyp T ->\n    open_ctyp_typ S T = T.\nProof.\n  introv [T' Hc]. apply* open_closed_ctyp_typ_unchanged.\nQed.\n\nLemma open_closed_ctyp_var_unchanged' : forall u T,\n    is_closed_ctyp T ->\n    open_ctyp_var u T = T.\nProof.\n  introv [T' Hc]. apply* open_closed_ctyp_var_unchanged.\nQed.\n\n(** * Constraint Interpretation *)\n\nReserved Notation \"G '⊧' C\" (at level 40).\n\nInductive satisfy_constr : ctx -> constr -> Prop :=\n\n| sat_true : forall G,\n    G ⊧ ⊤\n\n| sat_and : forall G C1 C2,\n    G ⊧ C1 ->\n    G ⊧ C2 ->\n    G ⊧ C1 ⋏ C2\n\n| sat_or1 : forall G C1 C2,\n    G ⊧ C1 ->\n    G ⊧ C1 ⋎ C2\n\n| sat_or2 : forall G C1 C2,\n    G ⊧ C2 ->\n    G ⊧ C1 ⋎ C2\n\n| sat_exists_typ : forall G T C,\n    G ⊧ C ^^t T ->\n    G ⊧ (∃t C)\n\n| sat_exists_var : forall G u C,\n    G ⊧ C ^^v u ->\n    G ⊧ (∃v C)\n\n| sat_typ : forall G t t' T T',\n    ctrm_closed t t' ->\n    ctyp_closed T T' ->\n    G ⊢ t' : T' ->\n    G ⊧ t ⦂ T\n\n| sat_sub : forall G S S' T T',\n    ctyp_closed S S' ->\n    ctyp_closed T T' ->\n    G ⊢ S' <: T' ->\n    G ⊧ S <⦂ T\n\nwhere \"G '⊧' C\" := (satisfy_constr G C).\n\nHint Constructors satisfy_constr constr.\n\n(** * Constraint Entailment *)\n\n(** ** Definition of entailment *)\nDefinition constr_entail (C1 C2 : constr) :=\n  forall G,\n    inert G ->\n    satisfy_constr G C1 -> satisfy_constr G C2.\n\nNotation \"C '⊩' D\" := (constr_entail C D) (at level 50).\n\n(** ** Tactics *)\n\nLtac introe := introv H0 H.\n\nLtac inv_sat :=\n  match goal with\n  | H : _ ⊧ (_ _) |- _ => idtac H; inversion H; subst; clear H\n  | H : _ ⊧ (_ _ _) |- _ => idtac H; inversion H; subst; clear H\n  | H : _ ⊧ ⊥ |- _ => idtac H; inversion H; subst; clear H\n  end.\n\nLtac inv_sat_all := repeat inv_sat.\n\nLtac inv_closed :=\n  match goal with\n  | H : ctyp_closed (_ _) _ |- _ => idtac H; inversion H; subst; clear H\n  | H : ctyp_closed (_ _ _) _ |- _ => idtac H; inversion H; subst; clear H\n  | H : ctrm_closed (_ _) _ |- _ => idtac H; inversion H; subst; clear H\n  | H : ctrm_closed (_ _ _) _ |- _ => idtac H; inversion H; subst; clear H\n  end.\n\nLtac inv_closed_all := repeat inv_closed.\n\nLtac simpl_open_constr :=\n  unfold open_constr_typ, open_constr_var in *; simpl in *; try case_if.\n\nLtac solve_open_closed_ctyp_eq T0 T :=\n  match goal with\n  | Hc : is_closed_ctyp T |- _ =>\n      try replace (open_rec_ctyp_typ 0 T0 T) with T in * by\n        (symmetry; apply* open_closed_ctyp_typ_unchanged');\n      try replace (open_rec_ctyp_var 0 T0 T) with T in * by\n        (symmetry; apply* open_closed_ctyp_var_unchanged')\n  | Hc : ctyp_closed T _ |- _ =>\n      idtac Hc;\n      try replace (open_rec_ctyp_typ 0 T0 T) with T in * by\n        (symmetry; apply* open_closed_ctyp_typ_unchanged);\n      try replace (open_rec_ctyp_var 0 T0 T) with T in * by\n        (symmetry; apply* open_closed_ctyp_var_unchanged)\n  end.\n\nLtac solve_ctyp_closed_unique T1 T2 :=\n  match goal with\n  | |- _ => replace T1 with T2 in * by apply* ctyp_closed_unique\n  end.\n\nLtac solve_ctrm_closed_unique t1 t2 :=\n  match goal with\n  | |- _ => replace t1 with t2 in * by apply* ctrm_closed_unique\n  end.\n\nLtac solve_trivial_sub :=\n  match goal with\n  | H : ?G ⊢ ?S <: ?T |- ?G ⊧ (ctyp_typ ?S) <⦂ (ctyp_typ ?T) =>\n    idtac G; idtac S; idtac T;\n    apply sat_sub with (S' := S) (T' := T); try assumption; try apply ctyp_typ_closed\n  end.\n\n(** ** Entailment Laws *)\n\n(** ∀ C, ⊥ ⊩ C\n    From false follows everything. *)\nTheorem ent_absurd : forall C,\n    ⊥ ⊩ C.\nProof.\n  introe. inversion H.\nQed.\n\n(** ∀ C, C ⊩ ⊤ *)\nTheorem ent_tautology : forall C,\n    C ⊩ ⊤.\nProof. introe. eauto. Qed.\n\nLemma ent_refl : forall C,\n    C ⊩ C.\nProof.\n  introe. auto.\nQed.\n\n(** If C1 ⊩ C2 and C2 ⊩ C3, then C1 ⊩ C3. *)\nTheorem ent_trans : forall C1 C2 C3,\n    C1 ⊩ C2 ->\n    C2 ⊩ C3 ->\n    C1 ⊩ C3.\nProof.\n  introv H12 H23.\n  introe.\n  eauto.\nQed.\n\nTheorem ent_cong_and : forall C C' D,\n    C ⊩ C' ->\n    C ⋏ D ⊩ C' ⋏ D.\nProof.\n  introv He. introe. inversion H; subst.\n  eauto.\nQed.\n\nTheorem ent_and_comm : forall C D,\n    C ⋏ D ⊩ D ⋏ C.\nProof.\n  introe. inv_sat. eauto.\nQed.\n\nTheorem ent_and_left : forall C D,\n    C ⋏ D ⊩ C.\nProof. introe. inversion H; subst. eauto. Qed.\n\nTheorem ent_and_right : forall C D,\n    C ⋏ D ⊩ D.\nProof. introe. inversion H; subst. eauto. Qed.\n\nTheorem ent_and_intro : forall C D,\n    C ⊩ D ->\n    C ⊩ C ⋏ D.\nProof.\n  introv Hcd. introe.\n  constructor*.\nQed.\n\nLemma ent_and_assoc : forall C1 C2 C3,\n    (C1 ⋏ C2) ⋏ C3 ⊩ C1 ⋏ (C2 ⋏ C3).\nProof.\n  introe. inv_sat. inv_sat. eauto.\nQed.\n\nLemma ent_or_comm : forall C D,\n    C ⋎ D ⊩ D ⋎ C.\nProof.\n  introe. inv_sat; eauto.\nQed.\n\nLemma ent_or_assoc : forall C1 C2 C3,\n    (C1 ⋎ C2) ⋎ C3 ⊩ C1 ⋎ (C2 ⋎ C3).\nProof.\n  introe. inv_sat; try inv_sat. all: eauto.\nQed.\n\nLemma ent_or_true : forall C,\n    ⊤ ⊩ C ⋎ ⊤.\nProof.\n  introe. eauto.\nQed.\n\nLemma ent_or_false : forall C,\n    C ⋎ ⊥ ⊩ C.\nProof.\n  introe. inv_sat; eauto. inv_sat.\nQed.\n\nLemma ent_or_dist_and : forall C D1 D2,\n    C ⋎ (D1 ⋏ D2) ⊩ (C ⋎ D1) ⋏ (C ⋎ D2).\nProof.\n  introe. inv_sat; try inv_sat; eauto.\nQed.\n\nLemma ent_and_dist_or : forall C D1 D2,\n    C ⋏ (D1 ⋎ D2) ⊩ (C ⋏ D1) ⋎ (C ⋏ D2).\nProof.\n  introe. inv_sat; try inv_sat; eauto.\nQed.\n\n(** If U is fresh for S and T, then\n    ∃ U. (S <: U ⋏ U <: T) ⊩ S <: T\n *)\nTheorem ent_sub_trans : forall S T,\n    is_closed_ctyp S -> is_closed_ctyp T ->\n    ∃t (S <⦂ (ctyp_tvar 0) ⋏ (ctyp_tvar 0) <⦂ T) ⊩ S <⦂ T.\nProof.\n  introv Hs Ht.\n  introe. inv_sat.\n  simpl_open_constr. inv_sat.\n  solve_open_closed_ctyp_eq T0 T.\n  solve_open_closed_ctyp_eq T0 S.\n  inv_sat_all. apply sat_sub with (S' := S'0) (T' := T'); auto.\n  solve_ctyp_closed_unique S' T'0.\n  eauto.\nQed.\n\n(** If C ⊩ D, then ∃ x. C ⊩ ∃ x. D *)\nLemma ent_cong_exists_v : forall C D,\n    (forall u C' D',\n        C ^^v u = C' ->\n        D ^^v u = D' ->\n        C' ⊩ D') ->\n    ∃v C ⊩ ∃v D.\nProof.\n  introv Hent. introe. inv_sat.\n  apply sat_exists_var with (u := u).\n  apply* Hent.\nQed.\n\n(** x: T ⊩ ∃y. y: T *)\nLemma ent_exists_v_intro : forall x T,\n    ctrm_var (cvar_avar (avar_f x)) ⦂ T ⊩ ∃v ctrm_var (cvar_cvar 0) ⦂ T.\nProof.\n  introv. introe.\n  inv_sat.\n  inversion H3; subst.\n  apply sat_exists_var with (u := x).\n  simpl_open_constr. apply* sat_typ.\n  solve_open_closed_ctyp_eq x T. auto.\nQed.\n\nLemma ent_exists_v_intro' : forall x T,\n    ctrm_trm (trm_var (avar_f x)) ⦂ T ⊩ ∃v ctrm_var (cvar_cvar 0) ⦂ T.\nProof.\n  introe. inv_sat. inv_closed.\n  apply sat_exists_var with (u := x). simpl_open_constr.\n  solve_open_closed_ctyp_eq x T. eapply sat_typ.\n  apply ctrm_cvar_closed.\n  match goal with\n  | H : ctyp_closed T _ |- _ => exact H\n  end.\n  auto.\nQed.\n\n(** ∃x. (x: {A:S1..T1} ⋏ x: {A:S2..T2}) ⊩ S1 <: T2 ⋏ S2 <: T1 *)\nLemma ent_bound_sub : forall A S1 T1 S2 T2,\n    ∃v (ctrm_var (cvar_cvar 0) ⦂ typ_rcd (dec_typ A S1 T1) ⋏\n        ctrm_var (cvar_cvar 0) ⦂ typ_rcd (dec_typ A S2 T2)) ⊩\n    S1 <⦂ T2 ⋏ S2 <⦂ T1.\nProof.\n  introv. introe.\n  inv_sat. simpl_open_constr.\n  inv_sat_all.\n  solve_ctrm_closed_unique t' t'0.\n  inv_closed_all.\n  assert (G ⊢ S1 <: T2 /\\ G ⊢ S2 <: T1) as [Hs1 Hs2] by apply* typ_bounds_subtyping.\n  apply* sat_and; solve_trivial_sub.\nQed.\n\n(** x: S ⋏ S <: T ⊩ x: T *)\nLemma ent_typ_subsume : forall x S T,\n    trm_var (avar_f x) ⦂ S ⋏ S <⦂ T ⊩ trm_var (avar_f x) ⦂ T.\nProof.\n  introe. inv_sat_all. inversion H3; subst.\n  apply* sat_typ.\n  solve_ctyp_closed_unique S' T'0. eauto.\nQed.\n\n(** U1 /\\ U2 <: {A: S..T} ⊩ U1 <: {A: S..T} \\/ U2 <: {A: S..T}\n *)\nTheorem ent_sub_and_rcd_or : forall U1 U2 A S T,\n    typ_and U1 U2 <⦂ typ_rcd (dec_typ A S T) ⊩\n        U1 <⦂ typ_rcd (dec_typ A S T) ⋎ U2 <⦂ typ_rcd (dec_typ A S T).\nProof.\n  introv. introe.\n  inv_sat. inv_closed_all.\n  match goal with\n  | H : G ⊢ _ <: _ |- _ =>\n    apply invert_subtyp_and1_rcd in H as [?H1 | ?H2]; try assumption;\n      try (apply sat_or1; solve_trivial_sub);\n      try (apply sat_or2; solve_trivial_sub)\n  end.\nQed.\n\n(** {A: S1..T1} <: {A: S2..T2} ⊩ S2 <: S1 ⋏ T1 <: T2 *)\nTheorem ent_inv_subtyp_typ : forall A S1 T1 S2 T2,\n    typ_rcd (dec_typ A S1 T1) <⦂ typ_rcd (dec_typ A S2 T2) ⊩\n        S2 <⦂ S1 ⋏ T1 <⦂ T2.\nProof.\n  introv. introe. inv_sat. inv_closed_all.\n  match goal with\n  | H : G ⊢ _ <: _ |- _ =>\n    apply invert_subtyp_typ in H as [Hs1 Hs2]; try assumption\n  end.\n  constructor; solve_trivial_sub.\nQed.\n\n(** If A ≠ B,\n    then {A:S1..T1} <: {B:S2..T2} ⊩ ⊥  *)\nTheorem ent_subtyp_typ_label_neq_false : forall A S1 T1 B S2 T2,\n    A <> B ->\n    typ_rcd (dec_typ A S1 T1) <⦂ typ_rcd (dec_typ B S2 T2) ⊩ ⊥.\nProof.\n  introv Hne. introe. inv_sat. inv_closed_all.\n  apply invert_subtyp_typ_label_neq_false in H6; try assumption.\n  contradiction.\nQed.\n\n(** S <: T ∧ U ⊩ S <: T ⋏ S <: U *)\nLemma ent_sub_and_and : forall S T U,\n    S <⦂ typ_and T U ⊩ S <⦂ T ⋏ S <⦂ U.\nProof.\n  introe. inv_sat. inv_closed.\n  assert (G ⊢ S' <: T /\\ G ⊢ S' <: U) as [Hs1 Hs2] by apply* invert_subtyp_and2.\n  apply* sat_and; eapply sat_sub with (S' := S');\n    try assumption;\n    try apply ctyp_typ_closed;\n    try assumption.\nQed.\n\n", "meta": {"author": "Linyxus", "repo": "constr-dot-calculus", "sha": "111c47bdc58350b8dd0b65ecbeeec783a8df2bc2", "save_path": "github-repos/coq/Linyxus-constr-dot-calculus", "path": "github-repos/coq/Linyxus-constr-dot-calculus/constr-dot-calculus-111c47bdc58350b8dd0b65ecbeeec783a8df2bc2/src/constr-dot/ConstrLang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.236082533665452}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*                 Xavier Leroy, INRIA Paris                           *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Recognition of combined operations, addressing modes and conditions\n  during the [CSE] phase. *)\n\nRequire Import FunInd.\nRequire Import Coqlib.\nRequire Import Integers Values Memory.\nRequire Import Op RTL CSEdomain.\nRequire Import CombineOp.\n\nSection COMBINE.\n\nVariable ge: genv.\nVariable sp: val.\nVariable m: mem.\nVariable get: valnum -> option rhs.\nVariable valu: valnum -> val.\nHypothesis get_sound: forall v rhs, get v = Some rhs -> rhs_eval_to valu ge sp m rhs (valu v).\n\nLemma get_op_sound:\n  forall v op vl, get v = Some (Op op vl) -> eval_operation ge sp op (map valu vl) m = Some (valu v).\nProof.\n  intros. exploit get_sound; eauto. intros REV; inv REV; auto.\nQed.\n\nLtac UseGetSound :=\n  match goal with\n  | [ H: get _ = Some _ |- _ ] =>\n      let x := fresh \"EQ\" in (generalize (get_op_sound _ _ _ H); intros x; simpl in x; FuncInv)\n  end.\n\nLemma combine_compimm_ne_0_sound:\n  forall x cond args,\n  combine_compimm_ne_0 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Cne (valu x) (Vint Int.zero) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Cne (valu x) (Vint Int.zero).\nProof.\n  intros until args. functional induction (combine_compimm_ne_0 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  destruct (eval_condition cond (map valu args) m); simpl; auto. destruct b; auto.\n  (* of and *)\n  UseGetSound. rewrite <- H.\n  destruct v; simpl; auto.\nQed.\n\nLemma combine_compimm_eq_0_sound:\n  forall x cond args,\n  combine_compimm_eq_0 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Ceq (valu x) (Vint Int.zero) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Ceq (valu x) (Vint Int.zero).\nProof.\n  intros until args. functional induction (combine_compimm_eq_0 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  rewrite eval_negate_condition.\n  destruct (eval_condition c (map valu args) m); simpl; auto. destruct b; auto.\n  (* of and *)\n  UseGetSound. rewrite <- H. destruct v; auto.\nQed.\n\nLemma combine_compimm_eq_1_sound:\n  forall x cond args,\n  combine_compimm_eq_1 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Ceq (valu x) (Vint Int.one) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Ceq (valu x) (Vint Int.one).\nProof.\n  intros until args. functional induction (combine_compimm_eq_1 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  destruct (eval_condition cond (map valu args) m); simpl; auto. destruct b; auto.\nQed.\n\nLemma combine_compimm_ne_1_sound:\n  forall x cond args,\n  combine_compimm_ne_1 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Cne (valu x) (Vint Int.one) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Cne (valu x) (Vint Int.one).\nProof.\n  intros until args. functional induction (combine_compimm_ne_1 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  rewrite eval_negate_condition.\n  destruct (eval_condition c (map valu args) m); simpl; auto. destruct b; auto.\nQed.\n\nTheorem combine_cond_sound:\n  forall cond args cond' args',\n  combine_cond get cond args = Some(cond', args') ->\n  eval_condition cond' (map valu args') m = eval_condition cond (map valu args) m.\nProof.\n  intros. functional inversion H; subst.\n  (* compimm ne zero *)\n  simpl; eapply combine_compimm_ne_0_sound; eauto.\n  (* compimm ne one *)\n  simpl; eapply combine_compimm_ne_1_sound; eauto.\n  (* compimm eq zero *)\n  simpl; eapply combine_compimm_eq_0_sound; eauto.\n  (* compimm eq one *)\n  simpl; eapply combine_compimm_eq_1_sound; eauto.\n  (* compuimm ne zero *)\n  simpl; eapply combine_compimm_ne_0_sound; eauto.\n  (* compuimm ne one *)\n  simpl; eapply combine_compimm_ne_1_sound; eauto.\n  (* compuimm eq zero *)\n  simpl; eapply combine_compimm_eq_0_sound; eauto.\n  (* compuimm eq one *)\n  simpl; eapply combine_compimm_eq_1_sound; eauto.\nQed.\n\nTheorem combine_addr_32_sound:\n  forall addr args addr' args',\n  combine_addr_32 get addr args = Some(addr', args') ->\n  eval_addressing32 ge sp addr' (map valu args') = eval_addressing32 ge sp addr (map valu args).\nProof.\n  intros. functional inversion H; subst.\n  (* indexed - lea *)\n  UseGetSound. simpl. unfold offset_addressing in H7. destruct (addressing_valid (offset_addressing_total a n)); inv H7.\n  eapply eval_offset_addressing_total_32; eauto.\nQed.\n\nTheorem combine_addr_64_sound:\n  forall addr args addr' args',\n  combine_addr_64 get addr args = Some(addr', args') ->\n  eval_addressing64 ge sp addr' (map valu args') = eval_addressing64 ge sp addr (map valu args).\nProof.\n  intros. functional inversion H; subst.\n  (* indexed - leal *)\n  UseGetSound. simpl. unfold offset_addressing in H7. destruct (addressing_valid (offset_addressing_total a n)); inv H7.\n  eapply eval_offset_addressing_total_64; eauto.\nQed.\n\nTheorem combine_addr_sound:\n  forall addr args addr' args',\n  combine_addr get addr args = Some(addr', args') ->\n  eval_addressing ge sp addr' (map valu args') = eval_addressing ge sp addr (map valu args).\nProof.\n  unfold combine_addr, eval_addressing; intros; destruct Archi.ptr64.\n  apply combine_addr_64_sound; auto.\n  apply combine_addr_32_sound; auto.\nQed.\n\nTheorem combine_op_sound:\n  forall op args op' args',\n  combine_op get op args = Some(op', args') ->\n  eval_operation ge sp op' (map valu args') m = eval_operation ge sp op (map valu args) m.\nProof.\n  intros. functional inversion H; subst.\n(* lea-lea *)\n  simpl. eapply combine_addr_32_sound; eauto.\n(* leal-leal *)\n  simpl. eapply combine_addr_64_sound; eauto.\n(* andimm - andimm *)\n  UseGetSound; simpl. rewrite <- H0. rewrite Val.and_assoc. auto.\n(* orimm - orimm *)\n  UseGetSound; simpl. rewrite <- H0. rewrite Val.or_assoc. auto.\n(* xorimm - xorimm *)\n  UseGetSound; simpl. rewrite <- H0. rewrite Val.xor_assoc. auto.\n(* andimm - andimm *)\n  UseGetSound; simpl. rewrite <- H0. rewrite Val.andl_assoc. auto.\n(* orimm - orimm *)\n  UseGetSound; simpl. rewrite <- H0. rewrite Val.orl_assoc. auto.\n(* xorimm - xorimm *)\n  UseGetSound; simpl. rewrite <- H0. rewrite Val.xorl_assoc. auto.\n(* cmp *)\n  simpl. decEq; decEq. eapply combine_cond_sound; eauto.\nQed.\n\nEnd COMBINE.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/x86/CombineOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23597951964532393}}
{"text": "(*\nRecord representing the AM Monad state structure.\n\nAuthor:  Adam Petz, ampetz@ku.edu\n*)\n\nRequire Import Maps EqbPair ConcreteEvidence.\n\nRequire Import List.\nImport ListNotations.\n\n\n\nDefinition asp_map := MapC (Plc * ASP_ID) ASP_ID.\nDefinition sig_map := MapC Plc ASP_ID.\n\n(* Specific AM monad state *)\nRecord AM_St : Type := mkAM_St\n                         { am_nonceMap : MapC nat BS;\n                           am_nonceId : nat;\n                           st_aspmap : asp_map;\n                           st_sigmap : sig_map;\n                           (*am_pl : Plc *)(*;\n                           checked : list nat*) }.\n\nDefinition empty_amst :=\n  mkAM_St [] 0 [] [].\n", "meta": {"author": "ku-sldg", "repo": "copland-avm", "sha": "6c08b0e3df96a22cc675bcea309fe99ea7deca65", "save_path": "github-repos/coq/ku-sldg-copland-avm", "path": "github-repos/coq/ku-sldg-copland-avm/copland-avm-6c08b0e3df96a22cc675bcea309fe99ea7deca65/src/extra/StAM_extra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23589574284857076}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.int_or_ptr.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nInductive tree := \n| LEAF: forall i, 0 <= i <= Int.max_signed -> tree\n| NODE: tree -> tree -> tree.\n\nFixpoint treerep (t: tree) (p: val) : mpred :=\n  match t with\n  | LEAF i _ => !! (p = Vint (Int.repr (i+i+1))) && emp\n  | NODE t1 t2 => EX p1:val, EX p2: val,\n               data_at Tsh (Tstruct _tree noattr) (p1,p2) p\n              * treerep t1 p1 * treerep t2 p2\n  end.\n\nDefinition POINTER_BOUNDARY : Z := 1024.\n\nDefinition valid_int_or_ptr (x: val) :=\n match x with\n | Vint i => Int.testbit i 0 = true\n              \\/ Int.unsigned i < POINTER_BOUNDARY\n | Vptr b z => Ptrofs.testbit z 0 = false\n | _ => False\n end.\n\nLemma valid_int_or_ptr_ii1:\n forall i, valid_int_or_ptr (Vint (Int.repr (i + i + 1))).\nProof.\nintros.\nsimpl.\nleft.\nrewrite Int.unsigned_repr_eq.\nrewrite Zodd_mod.\napply Zeq_is_eq_bool.\nreplace (i+i) with (2*i)%Z by lia.\nrewrite <- Zmod_div_mod; try lia.\nrewrite Z.mul_comm, Z.add_comm.\nrewrite Z_mod_plus_full.\nreflexivity.\ncompute; reflexivity.\nexists (Z.div Int.modulus 2).\nreflexivity.\nQed.\n\n\nLemma valid_int_or_ptr_i2:\n forall i, 0 <= i < POINTER_BOUNDARY ->\n   valid_int_or_ptr (Vint (Int.repr i)).\nProof.\nintros.\nsimpl.\nright.\nunfold POINTER_BOUNDARY in *.\nrewrite Int.unsigned_repr by rep_lia.\nrep_lia.\nQed.\n\nLemma field_compatible_valid_int_or_ptr:\n  forall p, \n  field_compatible (Tstruct _tree noattr) [] p ->\n  valid_int_or_ptr p.\nProof.\nintros.\ndestruct H as [H1 [_ [_ [H2 _]]]].\ndestruct p; try contradiction.\nclear - H2; simpl in *.\n    rewrite Zodd_even_bool.\n    apply negb_false_iff.\n    apply Zeven_bool_iff.\n    inv H2.\n    1: inv H.\n    inv H1.\n    specialize (H4 _left _ _ eq_refl eq_refl).\n    inv H4.\n    inv H.\n    simpl in H0.\n    destruct H0 as [j H].\n    rewrite Z.add_0_r in H.\n    rewrite H; clear.\n    replace (j*4)%Z with (2*(2*j))%Z by lia.\n    apply Zeven_2p.\nQed.\n\nLemma treerep_local_facts:\n  forall t p,\n   treerep t p |--\n   !! (valid_int_or_ptr p).\nProof.\nintros.\ndestruct t; simpl.\nentailer!.\napply valid_int_or_ptr_ii1.\nIntros p1 p2.\nentailer!.\napply field_compatible_valid_int_or_ptr; auto.\nQed.\n\n#[export] Hint Resolve treerep_local_facts : saturate_local.\n\nDefinition test_int_or_ptr_spec :=\n DECLARE _test_int_or_ptr\n WITH x : val\n PRE [ int_or_ptr_type ]\n   PROP(valid_int_or_ptr x) PARAMS (x) SEP()\n POST [ tint ]\n   PROP() \n   RETURN (Vint (Int.repr (match x with\n                    | Vint _ => 1\n                    | _ => 0\n                    end)))\n   SEP().\n\nDefinition int_or_ptr_to_int_spec :=\n DECLARE _int_or_ptr_to_int\n WITH x : val\n PRE [ int_or_ptr_type ]\n   PROP(is_int I32 Signed x) PARAMS (x) SEP()\n POST [ tint ]\n   PROP() RETURN (x) SEP().\n\nDefinition int_or_ptr_to_ptr_spec :=\n DECLARE _int_or_ptr_to_ptr\n WITH x : val\n PRE [ int_or_ptr_type ]\n   PROP(isptr x) PARAMS (x) SEP()\n POST [ tptr tvoid ]\n   PROP() RETURN (x) SEP().\n\nDefinition int_to_int_or_ptr_spec :=\n DECLARE _int_to_int_or_ptr\n WITH x : val\n PRE [ tint ]\n   PROP(valid_int_or_ptr x) PARAMS(x) SEP()\n POST [ int_or_ptr_type ]\n   PROP() RETURN(x) SEP().\n\nDefinition ptr_to_int_or_ptr_spec :=\n DECLARE _ptr_to_int_or_ptr\n WITH x : val\n PRE [ tptr tvoid ]\n   PROP(valid_int_or_ptr x) PARAMS(x) SEP()\n POST [ int_or_ptr_type ]\n   PROP() RETURN(x) SEP().\n\nDefinition makenode_spec :=\n DECLARE _makenode \n  WITH p: val, q: val\n  PRE [ int_or_ptr_type, int_or_ptr_type ]\n    PROP() PARAMS(p; q) SEP()\n  POST [ tptr (Tstruct _tree noattr) ]\n    EX r:val, \n    PROP() RETURN (r) \n    SEP (data_at Tsh (Tstruct _tree noattr) (p,q) r).\n\nDefinition copytree_spec :=\n DECLARE _copytree\n  WITH t: tree, p : val\n  PRE  [ int_or_ptr_type ]\n    PROP() PARAMS (p) SEP (treerep t p)\n  POST [ int_or_ptr_type ]\n    EX v:val,\n    PROP() RETURN (v) \n    SEP (treerep t p; treerep t v).\n\nDefinition Gprog : funspecs :=\n    ltac:(with_library prog [\n    test_int_or_ptr_spec;\n    int_or_ptr_to_int_spec;\n    int_or_ptr_to_ptr_spec;\n    int_to_int_or_ptr_spec;\n    ptr_to_int_or_ptr_spec;\n    makenode_spec; copytree_spec\n  ]).\n\nLemma body_copytree: semax_body Vprog Gprog f_copytree copytree_spec.\nProof.\n  start_function.\n  assert_PROP (valid_int_or_ptr p) by entailer!.\n  destruct t.\n* (* LEAF *)\n unfold treerep.\n Intros. subst p.\n forward_call (Vint (Int.repr (i+i+1))).\n forward_if.\n - (* then clause *)\n   forward. simpl.\n   Exists (Vint (Int.repr(i+i+1))).\n   entailer!.\n - (* else clause *)\n  inv H0.\n* (* NODE *) \n  unfold treerep; fold treerep.\n  rename p into t.\n  Intros p q.\n  forward_call t.\n  assert_PROP (isptr t) by entailer!.\n  destruct t; try contradiction. clear H0.\n  forward_if.\n  - (* then clause *)\n    contradiction.\n  - (* else clause *)\n   clear H0. simpl in H.\n   forward_call (Vptr b i).\n   forward.\n     entailer!.\n     destruct p; try contradiction; apply I.\n   forward_call (t1,p).\n   Intros p1.\n   deadvars.\n   forward.\n   forward.\n    entailer!.\n     destruct q; try contradiction; apply I.\n   forward_call (t2,q).\n   Intros p2.\n   forward.\n   deadvars.\n  assert_PROP (p1 <> Vundef).\n  entailer!.\n  assert_PROP (p2 <> Vundef).\n  entailer!.\n   forward_call (p1,p2).\n  Intros r.\n  assert_PROP (valid_int_or_ptr r). {\n    entailer!.\n    apply field_compatible_valid_int_or_ptr; auto.\n  }\n  forward_call r.\n  forward. simpl.\n  Exists r p q p1 p2.\n  entailer!.\nQed.\n\n\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/progs/verif_int_or_ptr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2358957428485707}}
{"text": "(* Inspired by:\n   Subjective Auxiliary State for Coarse-Grained Concurrency, Ley-Wild and Nanevski, POPL 2013. *)\n\nRequire Import VST.progs.conclib.\nRequire Import VST.progs.ghosts.\nRequire Import VST.progs.incrN.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition acquire_spec := DECLARE _acquire acquire_spec.\nDefinition release_spec := DECLARE _release release_spec.\nDefinition makelock_spec := DECLARE _makelock (makelock_spec _).\nDefinition freelock_spec := DECLARE _freelock (freelock_spec _).\nDefinition spawn_spec := DECLARE _spawn spawn_spec.\nDefinition freelock2_spec := DECLARE _freelock2 (freelock2_spec _).\nDefinition release2_spec := DECLARE _release2 release2_spec.\n\nInstance sum_ghost : Ghost :=\n  { G := nat; valid g := True; Join_G a b c := c = (a + b)%nat }.\nProof.\n  - exists (fun _ => O).\n    + intros.\n      hnf.\n      auto.\n    + auto.\n  - constructor.\n    + intros; hnf in *.\n      subst; auto.\n    + intros; hnf in *.\n      exists (b + c)%nat; split; hnf; omega.\n    + intros; hnf in *.\n      omega.\n    + intros; hnf in *.\n      omega.\n  - auto.\nDefined.\n\nInstance ctr_ghost : Ghost := ref_PCM sum_ghost.\n\nDefinition ghost_ref g n := ghost_reference(P := sum_ghost) g n.\nDefinition ghost_part g sh n := ghost_part(P := sum_ghost) g sh n.\nDefinition ghost_both g sh n1 n2 := ghost_part_ref(P := sum_ghost) g sh n1 n2.\n\nDefinition cptr_lock_inv g ctr :=\n  EX z : nat, data_at Ews tuint (Vint (Int.repr (Z.of_nat z))) ctr * ghost_ref g z.\n\nDefinition init_ctr_spec :=\n DECLARE _init_ctr\n  WITH gv: globals\n  PRE [ ]\n         PROP  ()\n         LOCAL (gvars gv)\n         SEP   (data_at_ Ews tuint (gv _ctr); data_at_ Ews tlock (gv _ctr_lock))\n  POST [ tvoid ]\n    EX g : gname,\n         PROP ()\n         LOCAL ()\n         SEP (lock_inv Ews (gv _ctr_lock) (cptr_lock_inv g (gv _ctr));\n              ghost_part g Tsh O).\n\nDefinition dest_ctr_spec :=\n DECLARE _dest_ctr\n  WITH g : gname, v : nat, gv: globals\n  PRE [ ]\n         PROP  ()\n         LOCAL (gvars gv)\n         SEP   (lock_inv Ews (gv _ctr_lock) (cptr_lock_inv g (gv _ctr));\n                ghost_part g Tsh v)\n  POST [ tvoid ]\n         PROP ()\n         LOCAL ()\n         SEP (data_at Ews tuint (vint (Z.of_nat v)) (gv _ctr);\n              data_at_ Ews tlock (gv _ctr_lock)).\n\nDefinition incr_spec :=\n DECLARE _incr\n  WITH sh : share, gsh : share, g : gname, n : nat, gv: globals\n  PRE [ ]\n         PROP  (readable_share sh; gsh <> Share.bot)\n         LOCAL (gvars gv)\n         SEP   (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g (gv _ctr)); ghost_part g gsh n)\n  POST [ tvoid ]\n         PROP ()\n         LOCAL ()\n         SEP (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g (gv _ctr)); ghost_part g gsh (S n)).\n\n\nDefinition thread_lock_R sh gsh g ctr lockc :=\n  lock_inv sh lockc (cptr_lock_inv g ctr) * ghost_part g gsh 1%nat.\n\nDefinition thread_lock_inv tsh sh gsh g ctr lockc lockt :=\n  selflock (thread_lock_R sh gsh g ctr lockc) tsh lockt.\n\nDefinition thread_func_spec :=\n DECLARE _thread_func\n  WITH y : val, x : share * share * share * gname * val * globals\n  PRE [ _args OF (tptr tvoid) ]\n         let '(tsh, sh, gsh, g, l, gv) := x in\n         PROP  (readable_share tsh; readable_share sh; gsh <> Share.bot)\n         LOCAL (temp _args y; gvars gv)\n         SEP   (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g (gv _ctr));\n                ghost_part g gsh O;\n                lock_inv tsh y (thread_lock_inv tsh sh gsh g (gv _ctr) (gv _ctr_lock) y))\n  POST [ tptr tvoid ]\n         PROP ()\n         LOCAL ()\n         SEP ().\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre prog nil gv\n  POST [ tint ] main_post prog nil gv.\n\nDefinition Gprog : funspecs := ltac:(with_library prog [acquire_spec; release_spec; release2_spec; makelock_spec;\n  freelock_spec; freelock2_spec; spawn_spec; init_ctr_spec; dest_ctr_spec; incr_spec; thread_func_spec; main_spec]).\n\nLemma ctr_inv_exclusive : forall lg p,\n  exclusive_mpred (cptr_lock_inv lg p).\nProof.\n  intros; unfold cptr_lock_inv.\n  eapply derives_exclusive, exclusive_sepcon1 with (Q := EX z : nat, _),\n    data_at__exclusive with (sh := Ews)(t := tuint); auto; simpl; try omega.\n  Intro z; apply sepcon_derives; [cancel|].\n  Exists z; apply derives_refl.\nQed.\nHint Resolve ctr_inv_exclusive.\n\nLemma thread_inv_exclusive : forall tsh sh gsh g ctr lock lockt,\n  exclusive_mpred (thread_lock_inv tsh sh gsh g ctr lock lockt).\nProof.\n  intros; apply selflock_exclusive.\n  unfold thread_lock_R.\n  apply exclusive_sepcon1; auto.\nQed.\nHint Resolve thread_inv_exclusive.\n\nLemma body_init_ctr: semax_body Vprog Gprog f_init_ctr init_ctr_spec.\nProof.\n  start_function.\n  forward.\n  forward.\n  ghost_alloc (fun g => ghost_both g Tsh O O).\n  { split; auto.\n    apply self_completable. }\n  Intros g.\n  forward_call (gv _ctr_lock, Ews, cptr_lock_inv g (gv _ctr)).\n  forward_call (gv _ctr_lock, Ews, cptr_lock_inv g (gv _ctr)).\n  { lock_props.\n    unfold cptr_lock_inv.\n    unfold ghost_both; rewrite <- ghost_part_ref_join.\n    unfold ghost_ref; Exists O; entailer!. }\n  forward.\n  unfold ghost_part; Exists g; entailer!.\nQed.\n\nLemma body_dest_ctr: semax_body Vprog Gprog f_dest_ctr dest_ctr_spec.\nProof.\n  start_function.\n  forward.\n  forward_call (gv _ctr_lock, Ews, cptr_lock_inv g (gv _ctr)).\n  forward_call (gv _ctr_lock, Ews, cptr_lock_inv g (gv _ctr)).\n  { lock_props. }\n  unfold cptr_lock_inv.\n  Intros z.\n  gather_SEP 2 3. replace_SEP 0 (!!(z = v) && ghost_both g Tsh v v).\n  { go_lower; clear.\n    rewrite sepcon_comm.\n    erewrite (add_andp (_ * _)) by apply (ref_sub(P := sum_ghost)).\n    rewrite if_true by auto; entailer!.\n    unfold ghost_part, ghost_ref; rewrite ghost_part_ref_join; apply derives_refl. }\n  Intros; subst.\n  viewshift_SEP 0 emp.\n  { go_lower.\n    apply own_dealloc. }\n  forward.\n  cancel.\nQed.\n\nLemma body_incr: semax_body Vprog Gprog f_incr incr_spec.\nProof.\n  start_function.\n  forward.\n  forward_call (gv _ctr_lock, sh, cptr_lock_inv g (gv _ctr)).\n  unfold cptr_lock_inv at 2; simpl.\n  Intros z.\n  forward.\n  forward.\n  gather_SEP 2 3.\n  viewshift_SEP 0 (ghost_part g gsh (S n) * ghost_ref g (S z)).\n  { go_lower.\n    rewrite sepcon_comm.\n    unfold ghost_part, ghost_ref; rewrite !ghost_part_ref_join.\n    apply ref_add with (b := 1%nat); try (hnf; omega).\n    intros; exists (c + 1)%nat; hnf; auto. }\n  Intros; forward_call (gv _ctr_lock, sh, cptr_lock_inv g (gv _ctr)).\n  { lock_props.\n    unfold cptr_lock_inv; Exists (S z).\n    rewrite Nat2Z.inj_succ.\n    entailer!. }\n  forward.\nQed.\n\nLemma body_thread_func : semax_body Vprog Gprog f_thread_func thread_func_spec.\nProof.\n  start_function.\n  Intros.\n  forward.\n  forward_call (sh, gsh, g, O, gv).\n  forward_call (y, tsh, thread_lock_R sh gsh g (gv _ctr) (gv _ctr_lock),\n                thread_lock_inv tsh sh gsh g (gv _ctr) (gv _ctr_lock) y).\n  { lock_props.\n    unfold thread_lock_inv, thread_lock_R.\n    rewrite selflock_eq at 2; cancel. }\n  forward.\nQed.\n\nDefinition N := 5.\n\nLemma ghost_part_share_join : forall g sh1 sh2 sh n1 n2, sh1 <> Share.bot -> sh2 <> Share.bot ->\n  sepalg.join sh1 sh2 sh ->\n  ghost_part g sh1 n1 * ghost_part g sh2 n2 = ghost_part g sh (n1 + n2)%nat.\nProof.\n  intros.\n  symmetry; apply own_op.\n  hnf; simpl.\n  repeat (split; auto).\n  constructor.\nQed.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\n  start_function.\n  fold N.\n  forward_call gv.\n  { rewrite sepcon_comm; apply sepcon_derives; [apply derives_refl | cancel]. }\n  Intros g.\n  (* need to split off shares for the locks and ghost here *)\n  destruct split_Ews as (sh1 & sh2 & ? & ? & Hsh).\n  destruct (split_shares (Z.to_nat N) Ews) as (sh0 & shs & ? & ? & ? & Hshs); auto.\n  destruct (split_shares (Z.to_nat N) Tsh) as (gsh0 & gshs & ? & ? & ? & Hgshs); auto.\n  rewrite Z2Nat.id in * by (unfold N; computable).\n  assert_PROP (field_compatible (tarray tlock N) [] (gv _thread_lock)) by entailer!.\n  set (thread_lock i := offset_val (sizeof tlock * i) (gv _thread_lock)).\n  forward_for_simple_bound N (EX i : Z, EX sh : share, EX gsh : share,\n    PROP (sepalg_list.list_join sh0 (sublist i N shs) sh;\n          sepalg_list.list_join gsh0 (sublist i N gshs) gsh) LOCAL (gvars gv)\n    SEP (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g (gv _ctr));\n         ghost_part g gsh O;\n         iter_sepcon (fun j => lock_inv sh2 (thread_lock j)\n           (thread_lock_inv sh1 (Znth j shs) (Znth j gshs) g (gv _ctr) (gv _ctr_lock) (thread_lock j)))\n           (upto (Z.to_nat i));\n         data_at_ Ews (tarray tlock (N - i)) (thread_lock i))).\n  { unfold N; computable. }\n  { Exists Ews Tsh.\n    subst thread_lock.\n    rewrite !sublist_same by auto; entailer!.\n    apply derives_refl. }\n  { (* first loop *)\n    forward.\n    simpl sem_binary_operation'.\n    replace (force_val _) with (thread_lock i)\n      by (rewrite sem_add_pi_ptr_special; auto; unfold N in *; rep_omega).\n    rewrite data_at__tarray.\n    destruct (Z.to_nat (N - i)) eqn: Hi.\n    { rewrite Z2Nat.inj_sub, Nat.sub_0_le in Hi by omega.\n      apply Z2Nat.inj_le in Hi; omega. }\n    simpl.\n    setoid_rewrite split2_data_at_Tarray_app with (v1 := [default_val tlock]);\n      rewrite ?Zlength_cons, ?Zlength_nil, ?Zlength_list_repeat'; auto.\n    erewrite data_at_singleton_array_eq by eauto.\n    forward_call (thread_lock i, Ews, thread_lock_inv sh1 (Znth i shs) (Znth i gshs) g\n      (gv _ctr) (gv _ctr_lock) (thread_lock i)).\n    { cancel. }\n    rewrite sublist_next in H9, H10 by omega.\n    inv H9; inv H10.\n    assert (readable_share (Znth i shs)) by (apply Forall_Znth; auto; omega).\n    assert (Znth i gshs <> Share.bot).\n    { intro X; contradiction bot_unreadable.\n      rewrite <- X; apply Forall_Znth; auto; omega. }\n    destruct (sepalg_list.list_join_assoc1 (sepalg.join_comm H14) H16) as (sh' & ? & Hsh').\n    destruct (sepalg_list.list_join_assoc1 (sepalg.join_comm H13) H17) as (gsh' & ? & Hgsh').\n    forward_spawn _thread_func (thread_lock i) (sh1, Znth i shs, Znth i gshs, g, thread_lock i, gv).\n    { erewrite <- lock_inv_share_join; try apply Hsh; auto.\n      unshelve erewrite <- (lock_inv_share_join _ _ _ _ _ _ _ Hsh'); auto.\n      { eapply readable_share_list_join; eauto. }\n      unshelve erewrite <- (ghost_part_share_join _ _ _ _ O O _ _ Hgsh'); auto.\n      { intro; subst.\n        contradiction bot_unreadable.\n        eapply readable_share_list_join; eauto. }\n      entailer!. }\n    { subst thread_lock; simpl.\n      apply isptr_is_pointer_or_null; rewrite isptr_offset_val; auto. }\n    Exists sh' gsh'; entailer!.\n    apply sepcon_derives.\n    - rewrite Z2Nat.inj_add, upto_app by omega.\n      rewrite iter_sepcon_app; simpl.\n      rewrite Z2Nat.id, Z.add_0_r by omega; cancel.\n    - rewrite <- Z.sub_add_distr.\n      subst thread_lock.\n      rewrite field_address0_offset, offset_offset_val.\n      rewrite Z.mul_succ_r with (m := i); cancel.\n      { rewrite field_compatible0_cons.\n        split; [omega|].\n        destruct H7 as (? & ? & ? & ? & ?).\n        repeat split; auto.\n        + hnf.\n          destruct (gv _thread_lock); try contradiction; simpl in *.\n          rewrite Z.max_r by omega.\n          rewrite Ptrofs.add_unsigned, Ptrofs.unsigned_repr;\n            rewrite Ptrofs.unsigned_repr; unfold N in *; try rep_omega.\n        + destruct (gv _thread_lock); try contradiction; simpl in *.\n          inv H23; try discriminate.\n          constructor.\n          intros; rewrite Ptrofs.add_unsigned, Ptrofs.unsigned_repr;\n            rewrite Ptrofs.unsigned_repr; unfold N in *; try rep_omega.\n          simpl; rewrite <- Z.add_assoc, Zred_factor4.\n          apply H29; omega. }\n    - apply Z2Nat.inj; try omega.\n      rewrite Nat2Z.id, Z2Nat.inj_sub by omega; simpl; omega. }\n  rewrite !sublist_nil, Zminus_diag; Intros shx gshx.\n  inv H8; inv H9.\n  forward_for_simple_bound N (EX i : Z, EX sh : share, EX gsh : share,\n    PROP (sepalg_list.list_join shx (sublist 0 i shs) sh;\n          sepalg_list.list_join gshx (sublist 0 i gshs) gsh) LOCAL (gvars gv)\n    SEP (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g (gv _ctr));\n         ghost_part g gsh (Z.to_nat i);\n         iter_sepcon (fun j => lock_inv sh2 (thread_lock j)\n           (thread_lock_inv sh1 (Znth j shs) (Znth j gshs) g (gv _ctr) (gv _ctr_lock) (thread_lock j)))\n           (sublist i N (upto (Z.to_nat N)));\n         data_at_ Ews (tarray tlock i) (gv _thread_lock))).\n  { unfold N; computable. }\n  { rewrite !sublist_nil; Exists shx gshx; entailer!.\n    { split; constructor. }\n    rewrite !data_at__eq, !data_at_zero_array_eq; auto. }\n  { (* second loop *)\n    forward.\n    replace (force_val _) with (thread_lock i)\n      by (simpl; rewrite sem_add_pi_ptr_special; auto; unfold N in *; simpl in *; rep_omega).\n    Opaque upto.\n    rewrite sublist_next with (i0 := i) by (auto; rewrite Zlength_upto, Z2Nat.id; omega); simpl.\n    rewrite Znth_upto by (simpl; unfold N in *; omega).\n    forward_call (thread_lock i, sh2, thread_lock_inv sh1 (Znth i shs) (Znth i gshs) g\n      (gv _ctr) (gv _ctr_lock) (thread_lock i)).\n    { cancel. }\n    unfold thread_lock_inv at 2; unfold thread_lock_R.\n    rewrite selflock_eq; Intros.\n    forward_call (thread_lock i, Ews, sh1, thread_lock_R (Znth i shs) (Znth i gshs) g (gv _ctr) (gv _ctr_lock),\n      thread_lock_inv sh1 (Znth i shs) (Znth i gshs) g (gv _ctr) (gv _ctr_lock) (thread_lock i)).\n    { lock_props.\n      unfold thread_lock_inv, thread_lock_R.\n      erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto; cancel. }\n    erewrite <- sublist_same with (al := shs) in Hshs by eauto.\n    erewrite <- sublist_same with (al := gshs) in Hgshs by eauto.\n    rewrite sublist_split with (mid := i) in Hshs, Hgshs by omega.\n    rewrite sublist_next with (i0 := i) in Hshs by omega.\n    rewrite sublist_next with (i0 := i) in Hgshs by omega.\n    rewrite app_cons_assoc in Hshs, Hgshs.\n    apply sepalg_list.list_join_unapp in Hshs as (sh' & Hshs1 & ?).\n    apply sepalg_list.list_join_unapp in Hgshs as (gsh' & Hgshs1 & ?).\n    apply sepalg_list.list_join_unapp in Hshs1 as (? & J & J1).\n    apply sepalg_list.list_join_unapp in Hgshs1 as (? & Jg & Jg1).\n    apply list_join_eq with (c := sh) in J; auto; subst.\n    apply list_join_eq with (c := gsh) in Jg; auto; subst.\n    rewrite <- sepalg_list.list_join_1 in J1, Jg1.\n    gather_SEP 3 1; erewrite lock_inv_share_join; eauto.\n    gather_SEP 3 2; erewrite ghost_part_share_join; eauto.\n    rewrite !(sublist_split 0 i (i + 1)), !sublist_len_1 by omega.\n    Exists sh' gsh'; entailer!.\n    { split; eapply sepalg_list.list_join_app; eauto; econstructor; eauto; constructor. }\n    rewrite Z2Nat.inj_add by omega.\n    rewrite !sepcon_assoc; apply sepcon_derives; [apply derives_refl|].\n    rewrite sepcon_comm, sepcon_assoc; apply sepcon_derives; [apply derives_refl|].\n    rewrite !data_at__tarray.\n    rewrite Z2Nat.inj_add, <- list_repeat_app by omega.\n    erewrite split2_data_at_Tarray_app by (rewrite Zlength_list_repeat; auto; omega).\n    rewrite Z.add_simpl_l; cancel.\n    simpl; erewrite data_at_singleton_array_eq by eauto.\n    rewrite field_address0_offset.\n    cancel.\n    { rewrite field_compatible0_cons; split; auto; try omega.\n      apply field_compatible_array_smaller0 with (n' := N); auto; omega. }\n    { intro X; contradiction unreadable_bot.\n      rewrite <- X; eapply readable_share_list_join; eauto. }\n    { intro X; contradiction unreadable_bot.\n      rewrite <- X; apply Forall_Znth; auto; omega. }\n    { eapply readable_share_list_join; eauto. }\n    { apply Forall_Znth; auto; omega. } }\n  Intros sh' gsh'.\n  eapply list_join_eq in Hshs; [|erewrite <- (sublist_same 0 N shs) by auto; eauto].\n  eapply list_join_eq in Hgshs; [|erewrite <- (sublist_same 0 N gshs) by auto; eauto].\n  subst.\n  forward_call (g, Z.to_nat N, gv).\n  forward.\n  rewrite Z2Nat.id; [|unfold N; computable].\n  (* We've proved that t is N! *)\n  forward.\nQed.\n\nDefinition extlink := ext_link_prog prog.\n\nDefinition Espec := add_funspecs (Concurrent_Espec unit _ extlink) extlink Gprog.\nExisting Instance Espec.\n\nLemma prog_correct:\n  semax_prog prog Vprog Gprog.\nProof.\nprove_semax_prog.\nrepeat (apply semax_func_cons_ext_vacuous; [reflexivity | reflexivity | ]).\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons body_init_ctr.\nsemax_func_cons body_dest_ctr.\nsemax_func_cons body_incr.\nsemax_func_cons body_thread_func.\nsemax_func_cons body_main.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/progs/verif_incr_gen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2358957366384354}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.AllEntriesTermSanityInterface.\n\nSection AllEntriesTermSanity.\n\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri: raft_refinement_interface}.\n\n  Lemma handleAppendEntries_currentTerm_monotonic:\n    forall h st (d : raft_data) \n      (m : msg) (t : term) (n : name) (pli : logIndex) \n      (plt : term) (es : list entry) (ci : logIndex),\n      handleAppendEntries h st t n pli plt es\n                          ci = (d, m) ->\n      currentTerm st <= currentTerm d.\n  Proof using. \n    intros.\n    unfold handleAppendEntries in *.\n    repeat break_match; simpl in *; do_bool; repeat find_inversion; auto; try omega;\n    simpl in *;\n    unfold advanceCurrentTerm in *; repeat break_match; do_bool; auto.\n  Qed.\n\n  Lemma allEntries_term_sanity_append_entries :\n    refined_raft_net_invariant_append_entries allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_eapply_lem_hyp update_elections_data_appendEntries_allEntries_term'; eauto.\n    intuition.\n    find_apply_lem_hyp handleAppendEntries_currentTerm_monotonic;\n      find_apply_hyp_hyp; omega.\n  Qed.\n\n  Lemma allEntries_term_sanity_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_apply_lem_hyp handleAppendEntriesReply_type_term. intuition; repeat find_rewrite; eauto.\n    find_apply_hyp_hyp. omega.\n  Qed.\n\n  Lemma allEntries_term_sanity_request_vote :\n    refined_raft_net_invariant_request_vote allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_rewrite_lem update_elections_data_requestVote_allEntries.\n    find_apply_lem_hyp handleRequestVote_type_term. intuition; repeat find_rewrite; eauto.\n    find_apply_hyp_hyp. omega.\n  Qed.\n\n  Lemma allEntries_term_sanity_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_rewrite_lem update_elections_data_requestVoteReply_allEntries.\n    find_apply_hyp_hyp.\n    unfold handleRequestVoteReply, advanceCurrentTerm.\n    repeat break_match; simpl in *; repeat find_inversion; do_bool; simpl in *; auto.\n    omega.\n  Qed.\n\n  Lemma allEntries_term_sanity_client_request :\n    refined_raft_net_invariant_client_request allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp update_elections_data_client_request_allEntries.\n    find_apply_lem_hyp handleClientRequest_type.\n    intuition; repeat find_rewrite;\n    try find_apply_hyp_hyp; auto.\n    break_exists.\n    intuition; repeat find_rewrite;\n    simpl in *.\n    intuition; simpl in *;\n    try match goal with\n      | H : context [ _ :: _ ] |- _ => clear H\n    end; repeat tuple_inversion; eauto.\n  Qed.\n\n  Lemma allEntries_term_sanity_timeout :\n    refined_raft_net_invariant_timeout allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_rewrite_lem update_elections_data_timeout_allEntries.\n    find_apply_lem_hyp handleTimeout_type_strong.\n    intuition; repeat find_rewrite; eauto.\n  Qed.\n\n  Lemma allEntries_term_sanity_do_leader :\n    refined_raft_net_invariant_do_leader allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_apply_lem_hyp doLeader_type. intuition.\n    repeat find_rewrite. eauto.\n  Qed.\n    \n\n  Lemma allEntries_term_sanity_do_generic_server :\n    refined_raft_net_invariant_do_generic_server allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_apply_lem_hyp doGenericServer_type. intuition.\n    repeat find_rewrite. eauto.\n  Qed.\n  \n\n  Lemma allEntries_term_sanity_reboot :\n    refined_raft_net_invariant_reboot allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n  Qed.\n      \n\n  Lemma allEntries_term_sanity_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    find_reverse_higher_order_rewrite. eauto.\n  Qed.\n\n\n  Lemma allEntries_term_sanity_init :\n    refined_raft_net_invariant_init allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros. simpl in *. intuition.\n  Qed.\n  \n  Instance aetsi : allEntries_term_sanity_interface.\n  Proof.\n    split.\n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply allEntries_term_sanity_init.\n    - apply allEntries_term_sanity_client_request.\n    - apply allEntries_term_sanity_timeout.\n    - apply allEntries_term_sanity_append_entries.\n    - apply allEntries_term_sanity_append_entries_reply.\n    - apply allEntries_term_sanity_request_vote.\n    - apply allEntries_term_sanity_request_vote_reply.\n    - apply allEntries_term_sanity_do_leader.\n    - apply allEntries_term_sanity_do_generic_server.\n    - apply allEntries_term_sanity_state_same_packet_subset.\n    - apply allEntries_term_sanity_reboot.\n  Qed. \nEnd AllEntriesTermSanity.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/verdi-raft/raft-proofs/AllEntriesTermSanityProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23589573663843535}}
{"text": "Require Export Nat.\nRequire Export ch2o.prelude.orders.\nRequire Export ch2o.prelude.nmap.\nRequire Export ch2o.prelude.stringmap.\nRequire Export ch2o.memory.memory_basics.\nRequire Export ch2o.abstract_c.architectures.\nRequire Export ch2o.abstract_c.interpreter.\nRequire Export ch2o.abstract_c.frontend_sound.\nRequire Export ch2o.core_c.smallstep.\nRequire Export ch2o.core_c.restricted_smallstep.\nRequire Export ch2o.core_c.expression_eval_smallstep.\nRequire Export bigstep_soundness.\nRequire Export three_locals.\n\nDefinition get_right{A B}(v: A + B)(H: match v with inl _ => False | inr _ => True end): B.\nProof.\ndestruct v.\nelim H.\nexact b.\nDefined.\n\nLocal Open Scope string_scope.\n\nDefinition A: architecture := {|\n  arch_sizes := architectures.lp64;\n  arch_big_endian := false;\n  arch_char_signedness := Signed;\n  arch_alloc_can_fail := false\n|}.\nNotation K := (arch_rank A).\n\nNotation M := (error (frontend_state K) string).\n\nLemma alloc_program_ok: match alloc_program (K:=K) decls empty with inl _ => False | inr _ => True end.\nProof.\nexact I.\nQed.\n\nDefinition alloc_program_result: frontend_state K.\nProof.\neapply snd.\neapply get_right.\napply alloc_program_ok.\nDefined.\n\n(*\nCompute (stringmap_to_list (env_t (to_env alloc_program_result))).\nCompute (stringmap_to_list (env_f (to_env alloc_program_result))).\n*)\n\nDefinition to_core_c_program: M (env K * funenv K * state K) :=\n  _ ← alloc_program decls;\n  Δg ← gets to_globals;\n  '(_,σs,σ,_) ← error_of_option (Δg !! \"main\"≫= maybe4 Fun)\n    (\"function `main` undeclared`\");\n  guard (σ = sintT%T ∨ σ = uintT%T) with\n    (\"function `main` should have return type `int`\");\n  Γ ← gets to_env;\n  δ ← gets to_funenv;\n  m ← gets to_mem;\n  mret (Γ, δ, initial_state m \"main\" []).\n\nDefinition to_core_c_program_result: string + env K * funenv K * state K :=\n  error_eval to_core_c_program ∅.\n\nLemma to_core_c_program_ok: match to_core_c_program_result with inl _ => False | inr _ => True end.\nProof.\nexact I.\nQed.\n\nDefinition core_c_program: env K * funenv K * state K := get_right to_core_c_program_result to_core_c_program_ok.\n\nDefinition Γ: env K := to_env alloc_program_result.\nDefinition δ: funenv K := to_funenv alloc_program_result.\nDefinition m0: mem K := to_mem alloc_program_result.\nDefinition S0 := initial_state m0 \"main\" [].\n\nLemma alloc_program_eq: alloc_program decls empty = mret () alloc_program_result.\nProof.\nreflexivity.\nQed.\n\nLemma Γ_valid: ✓ Γ.\nProof.\napply alloc_program_valid with (1:=alloc_program_eq).\nQed.\n\nLemma δ_valid: ✓{Γ,'{m0}} δ.\nProof.\napply alloc_program_valid with (1:=alloc_program_eq).\nQed.\n\nLemma m0_valid: ✓{Γ} m0.\napply alloc_program_valid with (1:=alloc_program_eq).\nQed.\n\nGoal ∀ S, Γ\\ δ ⊢ₛ S0 ⇒* S → ¬is_undef_state S.\nProof.\nintros.\nintro HS.\napply csteps_rcsteps in H.\ninv_rcsteps H. elim (is_Some_None HS).\ninversion H; clear H; subst.\ndestruct os; try discriminate.\nclear H7 H8.\nassert (match Some s with None => s | Some s => s end = s). {\n  reflexivity.\n}\nrewrite <- H6 in H.\nsimpl in H.\nsubst.\nclear H6.\nassert (m0 = ∅). reflexivity.\nrewrite H in H1. clear H.\nsimpl in H1.\napply exec_sound with (z:=2) in H1. {\n  destruct H1 as [H1|[m H1]].\n  - destruct S as [? [] ?]; try elim (is_Some_None HS).\n    inversion H1.\n    inversion H.\n  - subst.\n    elim (is_Some_None HS).\n}\napply Γ_valid.\napply δ_valid.\n{\n  apply type_check_sound.\n  - simpl. apply Γ_valid.\n  - reflexivity.\n}\nclear HS H1 S.\n\neconstructor.\neconstructor.\n- econstructor.\n  + simpl; lia.\n  + econstructor. split; (unfold int_lower || unfold int_upper); simpl; lia.\n- econstructor.\n  econstructor.\n  + econstructor.\n    * simpl; lia.\n    * econstructor. split; (unfold int_lower || unfold int_upper); simpl; lia.\n  + econstructor.\n    econstructor.\n    * econstructor.\n      -- simpl; lia.\n      -- econstructor.\n         reflexivity.\n    * econstructor.\n      -- econstructor.\n         reflexivity.\nQed.\n", "meta": {"author": "btj", "repo": "proofs-against-ch2o", "sha": "e7005477b916836d4243c43fbc939111af86446e", "save_path": "github-repos/coq/btj-proofs-against-ch2o", "path": "github-repos/coq/btj-proofs-against-ch2o/proofs-against-ch2o-e7005477b916836d4243c43fbc939111af86446e/bigstep_sl/three_locals_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.23589120319959497}}
{"text": "Require Import HoareDef SimModSem.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import Relation_Definitions.\n\n(*** TODO: export these in Coqlib or Universe ***)\nRequire Import Relation_Operators.\nRequire Import RelationPairs.\nFrom ITree Require Import\n     Events.MapDefault.\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Maps\n     Data.Map.FMapAList.\nRequire Import HTactics ProofMode IPM.\nRequire Import OpenDef.\nRequire Import Mem1 MemOpen STB.\n\nRequire Import Imp.\nRequire Import ImpNotations.\nRequire Import ImpProofs.\n\nRequire Import KnotMain0 KnotMainImp.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\nSection SIMMODSEM.\n\n  Import ImpNotations.\n\n  Context `{Σ: GRA.t}.\n\n  Let W: Type := Any.t * Any.t.\n\n  Let wf: unit -> W -> Prop :=\n    fun _ '(mrps_src0, mrps_tgt0) =>\n      (<<SRC: mrps_src0 = tt↑>>) /\\\n      (<<TGT: mrps_tgt0 = tt↑>>)\n  .\n\n\n  Theorem correct:\n    refines2 [KnotMainImp.KnotMain] [KnotMain0.Main].\n  Proof.\n    eapply adequacy_local2. econs; ss. i.\n    econstructor 1 with (wf:=wf) (le:=top2); et; ss.\n    econs; ss.\n    { init.\n      unfold fibF, fib.\n      steps.\n      rewrite unfold_eval_imp. steps.\n      des_ifs.\n      2:{ exfalso; apply n0. solve_NoDup. }\n      3:{ exfalso; apply n0. solve_NoDup. }\n      - imp_steps.\n        unfold unint in *. clarify.\n\n        des_ifs; ss; clarify.\n        2:{ lia. }\n        imp_steps.\n        red. esplits; et.\n      - imp_steps.\n        unfold unint in *. des_ifs; ss; clarify.\n        { lia. }\n        imp_steps.\n        unfold ccallU. imp_steps.\n        red. esplits; et.\n    }\n    econs; ss.\n    { init.\n      steps.\n      unfold mainF, main.\n      steps.\n      rewrite unfold_eval_imp. steps.\n      des_ifs.\n      2:{ exfalso; apply n0. solve_NoDup. }\n      imp_steps.\n      rewrite _UNWRAPU0. unfold ccallU. imp_steps.\n      red. esplits; et.\n    }\n    Unshelve. all: ss. all: try exact 0.\n  Qed.\n\nEnd SIMMODSEM.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/knot/KnotMainImp0proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23584543474053563}}
{"text": "(**\nRainbow, a termination proof certification tool\n\nSee the COPYRIGHTS and LICENSE files.\n\n- Kim Quyen LY, 2013-09-30\n\n* Translate CPF type into CoLoR type.\n\n*)\n\nSet Implicit Arguments.\n\n(* REMARK : [filter: term -> term'] inside [AFilterTerm] has a same\n   name with [filter] in List. *)\n\nRequire Import ATrs BinNat cpf cpf_ind cpf_util LogicUtil\n  Compare_dec ZUtil AFilterPerm ListUtil NatUtil AProj.\n\n(* REMARK: AProj: raw_pi : Sig -> option nat.\n   AFilterPerm: raw_pi : Sig -> list nat.\n   \n   Where AFilterPerm is non-collapsing arguments filtering with\n   permutations; and AProj is arguments filtering with projections\n   only.\n   \n   - In old Rainbow used:\n   AFilterPerm for : RPO + DP_argumentfilterProc and\n   AProj for: SubtermProc in DP_subtermProc. *)\n\nSection S.\n\n  (* TEST collapsing is true. *)\n\n  Definition is_collapsing (t: t3) : bool :=\n    match t with\n      | T3_collapsing _ => true\n      | T3_nonCollapsing _ => false\n    end.\n\n  Definition is_noncollapsing (t: t3) : bool :=\n    match t with\n      | T3_collapsing _ => false\n      | T3_nonCollapsing _ => true\n    end.\n\n  (* Check both collapsing and nonCollapsing is true *)\n\n  Definition is_col_noncol (t: t3) : bool :=\n    match t with\n      | T3_collapsing _\n      | T3_nonCollapsing _ => true\n    end.\n\n  (* TODO: MOVE *)\n  (* FIXME: in cpf2color_loop. has the same function of list position\n     -> list nat. but in result type *)\n\n  (* Define a function translate positive to nat.\n     REMARK: minus 1 because positive in Coq started from 1, when\n     natural numbers started from 0. *)\n\n  Definition color_positiveInteger (p: positive) : nat :=\n    nat_of_P p - 1.\n\n  (* Define a function taking a list of position of type\n     [positiveInteger] and return a list nat.\n     For example: if the list of position is : [1 2 3 4]\n     then the return value is: [0 1 2 3]. *)\n\n  Definition list_position_nat (ps: list position) : list nat :=\n    List.map color_positiveInteger ps.\n  \n  Variable arity : symbol -> nat.\n\n  Variable f : symbol.\n\n  (* Define a function transform arity cpf type into type nat. *)\n\n  Definition color_arity (a: cpf.arity) : nat := nat_of_N a.\n\n  (* Define [raw_pi: Sig -> list nat] in AFilterPerm from a list of\n     argument filtering. *)\n\n  (* If the list of position in nonCollapsing is equiv\n     with the increase list less than of (arity f) (i.e\n     if (arity f = 4) then the increase list less than\n     of 3 is: 0 1 2 3) then return nil/None otherwise\n     return a list of position in nonCollapsing.\n     \n     For example: the position list in nonCollapsing is:\n     [1 2 3 4] then tranform it to type [nat] by minus 1\n     the list become : 0 1 2 3.  Support the (arity f =\n     4) then the condition is true, for [0 1 2 3] is\n     equivalence with [0 1 2 3] then the return value is\n     [nil].  Otherwise if (arity f <> 4) then the\n     condition is false and the return value is the list\n     of [ps: 0 1 2 3].\n     *)\n\n  Fixpoint raw_pi_filter (l: list (symbol * cpf.arity * t3)): list nat :=\n    match l with\n      | (g, n, t) :: l' =>\n        match @eq_symb_dec (Sig arity) g f with\n          | left _ =>\n            match t with\n              | T3_collapsing p => color_positiveInteger p :: nil (* FIXME: nil?*)\n              | T3_nonCollapsing ps =>\n                if equiv beq_nat (list_position_nat ps) (nats_incr_lt (arity f))\n                  then nil\n                  else list_position_nat ps\n            end\n          | right _ => raw_pi_filter l'\n        end\n      | nil => nats_incr_lt (arity f)\n    end.\n\n  (* Define function [raw_pi: option nat] in the case\n     projection only from a list of argument filtering. *)\n\n  Fixpoint raw_pi_proj (l: list (symbol * cpf.arity * t3)): option nat :=\n    match l with\n      | (g, _, t) :: l' =>\n        match @eq_symb_dec (Sig arity) g f with\n          | left _ =>\n            match t with\n              | T3_collapsing p => Some (color_positiveInteger p)\n              | T3_nonCollapsing _ps => None\n            end\n          | right _ => raw_pi_proj l'\n        end\n      | nil => None\n    end.\n\nEnd S.\n\n(******************************************************************************)\n\nSection raw_pi.\n\n  Variable arity : symbol -> nat.\n  Variable l : list (symbol * cpf.arity * t3).\n\n  (* raw_pi filter : Sig -> list nat. *)\n\n  Definition color_raw_pi_filter (f: symbol) : list nat := raw_pi_filter arity f l.\n\n  (* raw_pi projection: Sig -> option nat. *)\n\n  Definition color_raw_pi_proj (f: symbol) : option nat := raw_pi_proj arity f l.\n\nEnd raw_pi.\n\n(******************************************************************************)\n\nSection pi.\n  \n  Variable arity : symbol -> nat.\n  Variable f: symbol.\n\n  (* TODO: proving the lemma [raw_pi_ok]; or make it as a variable and\n     then given the boolean function in the cpf2color_argfilter. *)\n\n  (* TODO *)\n  Lemma raw_pi_ok : forall ps, \n    forallb (bgt_nat (arity f)) (list_position_nat ps) = true.\n  Proof.\n  Admitted.\n\n  (*Variable raw_pi_ok : forall ps, \n    forallb (bgt_nat (arity f)) (list_position_nat ps) = true. *)\n\n  (* Define [pi: forall f: Sig, nat_lts (arity f)] in the case of\n  non-collapsing (filtering).*)\n\n  (* REMOVE *)\n  Fixpoint pi_filter (l : list (symbol * cpf.arity * t3)): nat_lts (arity f) :=\n    match l with\n      | (g, _, t3) :: l' =>\n        match @eq_symb_dec (Sig arity) g f with\n          | left _ =>\n            match t3 with\n              | T3_collapsing _p => mk_nat_lts (arity f)\n              | T3_nonCollapsing ps =>\n                build_nat_lts (arity f) (list_position_nat ps) (raw_pi_ok ps)\n            end\n          | right _ => pi_filter l'\n        end\n      | nil => mk_nat_lts (arity f) (* FIXME *)\n    end.\n  \n  (* Define [pi: forall f: Sig arity, option {k:nat | k < arity f}] in\n     the case of projection (collapsing) only from an argument af in CPF. *)\n\n  Fixpoint pi_proj (l: list (symbol * cpf.arity * t3)): option {k : nat | k < arity f}:=\n    match l with\n      | (g, _, t3) :: l' =>\n        match @eq_symb_dec (Sig arity) g f with\n          | left _ =>\n            match t3 with\n              | T3_collapsing p =>\n                let n := color_positiveInteger p in\n                  match lt_dec n (arity f) with\n                    | left h => Some (mk_proj (Sig arity) f h)\n                    | right _ => None\n                  end\n              | T3_nonCollapsing ps => None\n            end\n          | right _ => pi_proj l'\n        end\n      | nil => None\n    end.\n\nEnd pi.\n\n(******************************************************************************)\n(* FIXME: define [color_pi_filter] by using build_pi to be able to use\nthe lemma bnon_dup_ok in the correctness proof for AF in DP. *)\n\nSection build_pi.\n\nRequire Import AFilterPerm.\n\nVariable arity : symbol -> nat.\nVariable l: list (symbol * cpf.arity * t3).\n\nDefinition Fs : list (Sig arity) := list_split_triple l.\n\n(* TODO *)\nLemma Fs_ok : forall f, In f Fs.\n\nProof.\nAdmitted.\n\n(* Use this function for type: Sig -> list nat. *)\n\nDefinition color_raw_pi : (Sig arity) -> list nat :=\n  color_raw_pi_filter arity l.\n\n(* TODO *)\nLemma color_raw_pi_ok : bvalid color_raw_pi Fs = true.\n\nProof.\n\nAdmitted.\n\n(* REMARK: this is equal to the function [color_pi_filter] below. *)\nDefinition color_build_pi :=\n  build_pi Fs_ok color_raw_pi_ok.\n\nEnd build_pi.\n\n(******************************************************************************)\n\nSection color_pi.\n\n  Variable l : list (symbol * cpf.arity * t3).\n  Variable arity : symbol -> nat.\n\n  (* TEST: use in the case of rainbow_top_termin. *)\n  \n  Definition color_pi_filter (f: symbol) : nat_lts (arity f) :=\n    pi_filter arity f l.\n\n  (* Define a function [color_pi_proj] transform CPF type into CoLoR\n     type [pi_proj] *)\n\n  Definition color_pi_proj (f: symbol): option {k : nat | k < arity f} :=\n    pi_proj arity f l.\n\n  (* Define a function [color_filter] transform CPF type into CoLoR\n     type [filter] in non-collpasing. *)\n\n  Notation aterm := (ATerm.term (Sig arity)).\n\n  (* TEST: check the result use in rainbow_top_termin *)\n\n  Definition color_filter (t:aterm) :=\n    @AFilterPerm.filter (Sig arity) (color_pi_filter) t.\n\n  (* TEST Replace [color_pi_filter] by [build_pi] to be able to proof non-dup. *)\n  (*\n  Definition color_filter (t:aterm) :=\n    @AFilterPerm.filter (Sig arity) (color_build_pi l) t. *)\n\n  (* Define a function [color_proj] transform CPF type into CoLoR type\n     [proj] in projection only. *)\n\n  Definition color_proj (t: aterm) : aterm :=\n    @proj (Sig arity) (color_pi_proj) t.\n\n  (* Define a function [color_filter_rules] transform CPF type into\n  CoLoR type [filter_rules]. *)\n\n  Notation arules := (list (ATrs.rule (Sig arity))).\n\n  Definition color_filter_rule := @filter_rule (Sig arity).\n\n  Definition color_filter_rules r := List.map (color_filter_rule r).\n\n  (* Define a function [color_proj_rules] transform CPF type into\n  CoLoR type [proj_rules]. *)\n  \n  Definition color_proj_rules (r:arules) :=\n    @proj_rules (Sig arity) (color_pi_proj) r. \n\n  (* Define record type [Perm] in [ARedPair2.v] *)\n\n  Require Import ARedPair2.\n\n  (* TODO *)\n\n  (* Proof this non_dup by using the boolean function in the\n     bnon_dup_ok. And declare the boolean non_dup function as a\n     variable then add them in the boolean function of\n     cpf2color_argfilter.*)\n\n  (*Variable bnon_dup use build_pi to build [nats_lt] *)\n    \n  (* FIXME: define the function [non_dup] *)\n\n  (* TEST: used color_pi_filter *)\n  Lemma pi_perm_ok: @non_dup (Sig arity) (color_pi_filter).\n\n  Proof.\n    unfold color_build_pi. \n  Admitted.\n\n  (* Define record type [Proj] in [ARedPair2.v] *)\n\n  (* TEST: with color_pi_filter *)\n  Definition color_Perm : Perm (Sig arity) :=\n    @mkPerm (Sig arity) (color_pi_filter) (pi_perm_ok).  (* FIXME *)\n\n  (* Definition Sig_perm : Signature := filter_sig (pi_perm perm).*)\n \n  Definition color_Sig_perm : Signature := @Sig_perm (Sig arity) color_Perm.\n\n  (*************)\n  (* TEST: use color_build_pi *)\n  (*\n  Lemma pi_perm_ok2: @non_dup (Sig arity) (color_build_pi l).\n\n  Proof.\n    unfold color_build_pi. apply bnon_dup_ok.\n\n  Admitted.\n\n  Definition color_Perm2 : Perm (Sig arity) :=\n    @mkPerm (Sig arity) (color_build_pi l) (pi_perm_ok2).  (* FIXME *)\n\n  Definition color_Sig_perm2 : Signature := @Sig_perm (Sig arity) color_Perm2. *)\n\n  (*Record Proj := mkProj {\n     pi_proj : forall f: Sig, option {k | k < arity f} }.*)\n  \n  Definition color_Proj : Proj (Sig arity) := @mkProj (Sig arity) color_pi_proj.\n\nEnd color_pi.", "meta": {"author": "fblanqui", "repo": "rainbow", "sha": "3c437c0d40f01038b1d82f2a9a8085e366de3f15", "save_path": "github-repos/coq/fblanqui-rainbow", "path": "github-repos/coq/fblanqui-rainbow/rainbow-3c437c0d40f01038b1d82f2a9a8085e366de3f15/devel/gwen/coq_old/cpf2color_argfilter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23584543474053563}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\n(** this file contains some cardinal functions, which are message\ndependent *)\n\nRequire Export reduce.\nRequire Export DistributedReferenceCounting.machine4.machine.\n\n\nSection COUNT_MESSAGE.\n\nDefinition dec_predicate (m : Message) :=\n  match m with\n  | dec => true\n  | _ => false\n  end.\n\nDefinition inc_predicate (m : Message) :=\n  match m with\n  | inc_dec _ => true\n  | _ => false\n  end.\n\n(* the next one only recognises inc_dec messages related to s0 *)\n\nVariable s0 : Site.\n\nDefinition site_inc_predicate (m : Message) :=\n  match m with\n  | inc_dec s => if eq_site_dec s s0 then true else false\n  | _ => false\n  end.\n\n\nDefinition copy_predicate (m : Message) :=\n  match m with\n  | copy => true\n  | _ => false\n  end.\n\nDefinition dec_count (m : Message) :=\n  match m with\n  | dec => 1%Z\n  | _ => 0%Z\n  end.\n\nDefinition inc_count (m : Message) := 0%Z.\n\nDefinition copy_count (m : Message) :=\n  match m with\n  | copy => 1%Z\n  | _ => 0%Z\n  end.\n\nDefinition cardinal_count :=\n  fun_sum Message dec_count (fun_sum Message inc_count copy_count).\n\n\nDefinition cardinal := reduce Message cardinal_count.\n\nLemma disjoint_cardinal :\n forall q : queue Message,\n cardinal q =\n (reduce Message dec_count q +\n  (reduce Message inc_count q + reduce Message copy_count q))%Z.\nProof.\n  intro.\n  rewrite <- disjoint_reduce.\n  rewrite <- disjoint_reduce.\n  unfold cardinal in |- *.\n  unfold cardinal_count in |- *.\n  auto.\nQed.\n\nLemma cardinal_first_out :\n forall (q : queue Message) (m : Message),\n first Message q = value Message m ->\n cardinal (first_out Message q) = (cardinal q - cardinal_count m)%Z.\nProof.\n  intros.\n  unfold cardinal in |- *.\n  apply reduce_first_out.\n  auto.\nQed.\n\nEnd COUNT_MESSAGE.\n\n\n\n\nSection SIG_WEIGHT.\nLet Bag_of_message := Bag_of_Data Message.\n\nDefinition sigma_weight (bm : Bag_of_message) :=\n  sigma2_table Site LS LS (queue Message) (fun s1 s2 : Site => cardinal) bm.\n\nEnd SIG_WEIGHT.\n\n", "meta": {"author": "coq-contribs", "repo": "distributed-reference-counting", "sha": "6552f14cce0ea374c98adcbee0476ae268d64a7e", "save_path": "github-repos/coq/coq-contribs-distributed-reference-counting", "path": "github-repos/coq/coq-contribs-distributed-reference-counting/distributed-reference-counting-6552f14cce0ea374c98adcbee0476ae268d64a7e/machine4/cardinal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23584542874752712}}
{"text": "(* ------------------------------------------------------- *)\n(** #<hr> <center> <h1>#\n        The double time redundancy (DTR) transformation   \n#</h1>#    \n-  ctr block properties during even(1) cycles\n\n          Dmitry Burlyaev - Pascal Fradet - 2015          \n#</center> <hr>#                                           *)\n(* ------------------------------------------------------- *)\n(* Add LoadPath \"..\\..\\Common\\\".\nRequire Import CirReflect . \nAdd LoadPath \"..\\..\\TMRProof\\\".\nRequire Import tmrMainTh.\nAdd LoadPath \"..\\\".\nRequire Import dtrTransform.\nAdd LoadPath \"..\\memoryBlocks\".\n*)\n\nAdd LoadPath \"..\\..\\Common\\\".\nAdd LoadPath \"..\\..\\TMRProof\\\".\nAdd LoadPath \"..\\Transf\\\".\nAdd LoadPath \"..\\memoryBlocks\\\".\n\nRequire Import dtrTransform controlFsmStep.\n\nSet Implicit Arguments.\n\n(* ########################################################## *)\n(** Properties of DTR control block during the even(1) cycles  *)\n(* ########################################################## *)\n\n(*Normal mode: from the state '001' the control block goes to the states '000' if no fail signal raised*)\n(*No glitches*)\nLemma step1_tcbv : forall  t c, step (ctrBlockTMR false false true)  {~0,~0,~0}  t c \n                                  -> t={~1,~0,~0,~0,~0} /\\ c=(ctrBlockTMR false false false).\nProof.\nintrov H.\nassert ( step (ctrBl_dtr false false true)   (~0)  {~1,~0,~0,~0,~0}(ctrBl_dtr false false false)). (*property of a single ctrBl*)\n - assert ( exists t, exists c', step (ctrBl_dtr false false true) (~0) t c' ). apply step_all_ex.\n   Simpl. assert (HA :=  H0). apply fact_stepCtrBl_21 in H0. destruct H0; Simpl.\n - apply tmr_normal in H0. apply tmrVotRelat in H0.\n   + Rdet. Simpl. \n   + Checkpure.\n   + Checkpure.\nQed.\n\n(*Error detection: from the state '001' the control block goes to the states '010' if the fail signal raised*)\n(*No glitches*)\nLemma stepr1_tcbv : forall t c, step (ctrBlockTMR false false true)  {~1,~1,~1}  t c \n                          -> t={~1,~1,~1,~1,~1} /\\ c=(ctrBlockTMR false true false).\nProof.\nintrov H.\nassert ( step (ctrBl_dtr false false true)   (~1)  {~1,~1,~1,~1,~1}(ctrBl_dtr false true false)). (*property of a single ctrBl*)\n- assert ( exists t, exists c', step (ctrBl_dtr false false true) (~1) t c' ). apply step_all_ex.\n  Simpl. assert (HA :=  H0). apply fact_stepCtrBl_23 in H0. destruct H0; Simpl.\n- apply tmr_normal in H0. apply tmrVotRelat in H0.\n   + Rdet. Simpl. \n   + Checkpure.\n   + Checkpure.\nQed.\n\n(*Recovery from internal control block corruption during during the normal mode:\nif one of three redundant parts of the control block is corrupted then \nthe error disappears the next clock cycle thanks to TMR (without starting recovery since fail=0)*)\nLemma step1_tcbv_C: forall  t ctrTMR c, corrupt_1in3_cir (ctrBl_dtr false false true) ctrTMR \n                     ->  step (ctrTMR -o- ctrVoting)   {~0,~0,~0}  t  c \n                     -> t={~1,~0,~0,~0,~0} /\\ c=(ctrBlockTMR false false false).\nProof.\nintrov H H0. unfold ctrBlockTMR.\napply tmr_corruptc  with (c':=(ctrBl_dtr false false false)) (s:=(~0)) (t:={~1,~0,~0,~0,~0}) in H.\n - Inverts H0. apply det_step with (c1:=c1') (t1:=t0 )  in H. Inverts H.\n   + assert (F:  fstep ctrVoting {~ 1, ~ 0, ~ 0, ~ 0, ~ 0, \n                                 {~ 1, ~ 0, ~ 0, ~ 0, ~ 0},\n                                 {~ 1, ~ 0, ~ 0, ~ 0, ~ 0}}  = \n             Some ({~1,~0,~0,~0,~0} ,  ctrVoting)) by\n     (vm_compute; try easy). eapply fstep_imp_detstep in F; Simpl.\n   + Checkpure.\n   + apply H5.\n - Checkpure.\n - assert ( exists t, exists c', step (ctrBl_dtr false false true) (~0) t c' ). apply step_all_ex.\n  Simpl. assert (HA :=  H1). apply fact_stepCtrBl_21 in H1. destruct H1; Simpl.\nQed.", "meta": {"author": "dburl", "repo": "Coq_LDDL", "sha": "691023b88314c1ad531a1177954a1c6596fe4483", "save_path": "github-repos/coq/dburl-Coq_LDDL", "path": "github-repos/coq/dburl-Coq_LDDL/Coq_LDDL-691023b88314c1ad531a1177954a1c6596fe4483/DTRProof/controlBlock/controlStep1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2358454287475271}}
{"text": "Require Import AutoSep Bootstrap Malloc Buffers XmlLex XmlLang Arrays8 ArrayOps.\nRequire Import RelDb XmlOutput Bags Io Http HttpQ Thread.\n\n\nModule Type HIDE.\n  Parameter heapSize4 : N -> N.\n  Axiom heapSize4_eq : forall n, heapSize4 n = (n * 4)%N.\n\n  Parameter to_nat : N -> nat.\n  Axiom to_nat_eq : to_nat = N.to_nat.\nEnd HIDE.\n\nModule Hide : HIDE.\n  Definition heapSize4 n := (n * 4)%N.\n  Theorem heapSize4_eq : forall n, heapSize4 n = (n * 4)%N.\n    auto.\n  Qed.\n\n  Definition to_nat := N.to_nat.\n  Theorem to_nat_eq : to_nat = N.to_nat.\n    auto.\n  Qed.\nEnd Hide.\n\nRecord wf (ts : tables) (pr : program) (buf_size outbuf_size : N) : Prop := {\n  WellFormed : XmlLang.wf ts pr;\n  NotTooGreedy : (reserved pr <= 86)%nat;\n\n  Buf_size_lower : (buf_size >= 2)%N;\n  Buf_size_upper : (buf_size * 4 < Npow2 32)%N;\n\n  Outbuf_size_lower : (outbuf_size >= 2)%N;\n  Outbuf_size_upper : (outbuf_size * 4 < Npow2 32)%N;\n\n  ND : NoDup (Names ts);\n  GoodSchema : twfs ts;\n  UF : uf ts\n}.\n\nModule Type S.\n  Parameter ts : tables.\n  Parameter pr : program.\n  Parameters buf_size outbuf_size heapSize : N.\n\n  Axiom Wf : wf ts pr buf_size outbuf_size.\n\n  Parameters port numWorkers : W.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nModule Locations.\n  Definition globalSched : W := ((heapSize + 50) * 4)%N.\n  Definition globalSock : W := globalSched ^+ $4.\nEnd Locations.\n\nImport Locations.\n\nModule M'''.\n  Definition globalSched := globalSched.\n\n  Local Open Scope Sep_scope.\n\n  Definition globalInv (fs : files) : HProp :=\n    db ts * Ex fr, globalSock =*> fr * [| fr %in fs |].\nEnd M'''.\n\nModule T := Thread.Make(M''').\n\nImport T M'''.\nExport T M'''.\n\nModule MyM.\n  Definition sched := sched.\n  Definition globalInv := globalInv.\n\n  Definition buf_size := outbuf_size.\n\n  Theorem buf_size_lower : (nat_of_N buf_size >= 2)%nat.\n    generalize (Outbuf_size_lower _ _ _ _ M.Wf).\n    unfold buf_size; intros; nomega.\n  Qed.    \n\n  Theorem buf_size_upper : goodSize (4 * nat_of_N buf_size).\n    Transparent goodSize.\n    unfold goodSize.\n    rewrite Nat2N.inj_mul.\n    rewrite Nmult_comm.\n    rewrite N2Nat.id.\n    eapply Outbuf_size_upper; apply M.Wf.\n    Opaque goodSize.\n  Qed.\n\n  Theorem globalInv_monotone : forall fs fs', fs %<= fs'\n    -> globalInv fs ===> globalInv fs'.\n    unfold globalInv, M'''.globalInv; sepLemma.\n  Qed.\nEnd MyM.\n\nLtac unf := unfold MyM.sched, MyM.globalInv, M'''.globalSched, M'''.globalInv in *.\n\nModule MyIo := Io.Make(MyM).\nModule MyHttpQ := HttpQ.Make(MyM).\nModule MyHttp := MyHttpQ.H.\n\nDefinition mainS := SPEC reserving 49\n  PREmain[_] globalSched =?> 1 * globalSock =?> 1 * db ts * mallocHeap 0.\n\nDefinition handlerS := SPEC reserving 99\n  Al fs,\n  PREmain[_] sched fs * globalInv fs * mallocHeap 0.\n\nDefinition bsize := nat_of_N (buf_size * 4)%N.\n\nInductive unfold_here := UnfoldHere.\nLocal Hint Constructors unfold_here.\n\nImport MyHttpQ.Httpq.\n\nTheorem httpq_nil : Emp ===> httpq 0.\n  eapply Himp_trans; [ | apply httpq_bwd ].\n  apply Himp_ex_c; exists nil.\n  sepLemma; step SinglyLinkedList.hints.\nQed.\n\nDefinition hints : TacPackage.\n  prepare buffer_split_tagged (buffer_join_tagged, httpq_nil).\nDefined.\n\nDefinition m0 := bimport [[ \"buffers\"!\"bmalloc\" @ [bmallocS], \"sys\"!\"abort\" @ [abortS],\n                            \"xml_prog\"!\"main\" @ [XmlLang.mainS pr httpq ts],\n                            \"malloc\"!\"malloc\" @ [mallocS],\n                            \"http\"!\"readRequest\" @ [MyHttp.readRequestS],\n                            \"http\"!\"writeResponse\" @ [MyHttp.writeResponseS],\n                            \"scheduler\"!\"init\" @ [T.Q''.initS], \"scheduler\"!\"listen\" @ [T.Q''.listenS],\n                            \"scheduler\"!\"accept\" @ [T.Q''.acceptS], \"scheduler\"!\"close\" @ [T.Q''.closeS],\n                            \"scheduler\"!\"spawn\" @ [T.Q''.spawnS], \"scheduler\"!\"exit\" @ [T.Q''.exitS],\n                            \"httpq\"!\"send\" @ [MyHttpQ.sendS] ]]\n  bmodule \"xml_driver\" {{\n    bfunctionNoRet \"handler\"(\"fr\", \"inbuf\", \"len\", \"outbuf\", \"q\", \"tmp\", \"tmp2\") [handlerS]\n      \"inbuf\" <-- Call \"buffers\"!\"bmalloc\"(buf_size)\n      [Al fs, PREmain[_, R] sched fs * globalInv fs * R =?>8 bsize * mallocHeap 0];;\n\n      \"outbuf\" <-- Call \"buffers\"!\"bmalloc\"(buf_size)\n      [Al fs, PREmain[V, R] sched fs * globalInv fs * V \"inbuf\" =?>8 bsize * R =?>8 bsize * mallocHeap 0];;\n\n      \"q\" <-- Call \"malloc\"!\"malloc\"(0, 2)\n      [Al fs, PREmain[V, R] sched fs * globalInv fs * R =?> 2\n        * V \"inbuf\" =?>8 bsize * V \"outbuf\" =?>8 bsize * mallocHeap 0];;\n\n      [Al fs, PREmain[V] sched fs * globalInv fs * V \"q\" =?> 2\n        * V \"inbuf\" =?>8 bsize * V \"outbuf\" =?>8 bsize * mallocHeap 0]\n      While (1 = 1) {\n        \"fr\" <-- Call \"scheduler\"!\"accept\"($[globalSock])\n        [Al fs, PREmain[V, R] [| R %in fs |] * sched fs * globalInv fs * V \"q\" =?> 2\n          * V \"inbuf\" =?>8 bsize * V \"outbuf\" =?>8 bsize * mallocHeap 0];;\n\n        \"len\" <-- Call \"http\"!\"readRequest\"(\"fr\", \"inbuf\", bsize)\n        [Al fs, PREmain[V, R] [| V \"fr\" %in fs |] * sched fs * globalInv fs * V \"q\" =?> 2\n          * V \"inbuf\" =?>8 bsize * V \"outbuf\" =?>8 bsize * mallocHeap 0];;\n\n        If (\"len\" > bsize) {\n          Call \"sys\"!\"abort\"()\n          [PREonly[_] [| False |] ];;\n          Fail\n        } else {\n          Assert [Al fs, PREmain[V] [| V \"fr\" %in fs |] * sched fs * globalInv fs * V \"q\" =?> 2\n            * buffer_splitAt (wordToNat (V \"len\")) (V \"inbuf\") bsize\n            * V \"outbuf\" =?>8 bsize * mallocHeap 0\n            * [| wordToNat (V \"len\") <= bsize |]%nat ];;\n\n          Assert [Al fs, PREmain[V] [| V \"fr\" %in fs |] * sched fs * globalInv fs * V \"q\" =?> 2\n            * V \"inbuf\" =?>8 wordToNat (V \"len\")\n            * (V \"inbuf\" ^+ natToW (wordToNat (V \"len\"))) =?>8 (bsize - wordToNat (V \"len\"))\n            * V \"outbuf\" =?>8 bsize * mallocHeap 0 * [| wordToNat (V \"len\") <= bsize |]%nat ];;\n\n          Note [unfold_here];;\n\n          \"q\" *<- 0;;\n          \"tmp\" <- \"inbuf\" + \"len\";;\n          \"tmp2\" <- bsize - \"len\";;\n          \"tmp\" <-- Call \"xml_prog\"!\"main\"(\"tmp\", \"tmp2\", \"outbuf\", bsize, \"q\")\n          [Al fs, Al q, PREmain[V, R] [| V \"fr\" %in fs |] * sched fs * globalInv fs\n            * V \"q\" =*> q * (V \"q\" ^+ $4) =?> 1 * httpq q\n            * V \"inbuf\" =?>8 wordToNat (V \"len\")\n            * (V \"inbuf\" ^+ natToW (wordToNat (V \"len\"))) =?>8 (bsize - wordToNat (V \"len\"))\n            * V \"outbuf\" =?>8 bsize\n            * mallocHeap 0 * [| wordToNat (V \"len\") <= bsize |]%nat ];;\n\n          Assert [Al fs, Al q, PREmain[V] [| V \"fr\" %in fs |] * sched fs * globalInv fs\n            * V \"q\" =*> q * (V \"q\" ^+ $4) =?> 1 * httpq q\n            * buffer_joinAt (wordToNat (V \"len\")) (V \"inbuf\") bsize\n            * V \"outbuf\" =?>8 bsize * mallocHeap 0 ];;\n\n          Assert [Al fs, Al q, PREmain[V] [| V \"fr\" %in fs |] * sched fs * globalInv fs\n            * V \"q\" =*> q * (V \"q\" ^+ $4) =?> 1 * httpq q\n            * V \"inbuf\" =?>8 bsize\n            * V \"outbuf\" =?>8 bsize * mallocHeap 0 ];;\n\n          Call \"http\"!\"writeResponse\"(\"fr\", \"outbuf\", \"tmp\", bsize)\n          [Al fs, Al q, PREmain[V] [| V \"fr\" %in fs |] * sched fs * globalInv fs\n            * V \"q\" =*> q * (V \"q\" ^+ $4) =?> 1 * httpq q\n            * V \"inbuf\" =?>8 bsize\n            * V \"outbuf\" =?>8 bsize * mallocHeap 0 ];;\n\n          \"tmp\" <-* \"q\";;\n          Call \"httpq\"!\"send\"(\"tmp\")\n          [Al fs, PREmain[V] [| V \"fr\" %in fs |] * sched fs * globalInv fs\n            * V \"q\" =?> 2\n            * V \"inbuf\" =?>8 bsize\n            * V \"outbuf\" =?>8 bsize * mallocHeap 0 ]\n        };;\n\n        Call \"scheduler\"!\"close\"(\"fr\")\n        [Al fs, PREmain[V] sched fs * globalInv fs * V \"q\" =?> 2\n          * V \"inbuf\" =?>8 bsize * V \"outbuf\" =?>8 bsize * mallocHeap 0]\n      }\n    end with bfunctionNoRet \"main\"(\"fr\", \"x\") [mainS]\n      Init\n      [Al fs, Al v, PREmain[_] sched fs * globalSock =*> v * db ts * mallocHeap 0];;\n\n      \"fr\" <- 0;;\n      [Al fs, PREmain[_] sched fs * globalSock =?> 1 * db ts * mallocHeap 0]\n      While (\"fr\" < numWorkers) {\n        Spawn(\"xml_driver\"!\"handler\", 100)\n        [Al fs, PREmain[_] sched fs * globalSock =?> 1 * db ts * mallocHeap 0];;\n        \"fr\" <- \"fr\" + 1\n      };;\n\n      \"fr\" <-- Call \"scheduler\"!\"listen\"(port)\n      [Al fs, Al v, PREmain[_, R] [| R %in fs |] * sched fs * globalSock =*> v\n        * db ts * mallocHeap 0];;\n\n      globalSock *<- \"fr\";;\n\n      Exit 50\n    end\n  }}.\n\nLemma buf_size_lower'' : (buf_size < Npow2 32)%N.\n  eapply Nlt_trans; [ | apply (Buf_size_upper _ _ _ _ Wf) ].\n  specialize (Buf_size_lower _ _ _ _ Wf); intros.\n  pre_nomega.\n  rewrite N2Nat.inj_mul.\n  simpl.\n  generalize dependent (N.to_nat buf_size); intros.\n  change (Pos.to_nat 2) with 2 in *.\n  change (Pos.to_nat 4) with 4.\n  omega.\nQed.\n\nLemma buf_size_lower' : natToW 2 <= NToW buf_size.\n  unfold NToW.\n  rewrite NToWord_nat.\n  pre_nomega.\n  rewrite wordToNat_natToWord_idempotent.\n  generalize (Buf_size_lower _ _ _ _ Wf).\n  intros; nomega.\n  rewrite N2Nat.id.\n  apply buf_size_lower''.\nQed.\n\nLocal Hint Immediate buf_size_lower'.\n\nClose Scope Sep_scope.\n\nLemma bsize_in : (wordToNat (NToW buf_size) * 4) = bsize.\n  unfold NToW, bsize.\n  rewrite NToWord_nat.\n  rewrite N2Nat.inj_mul.\n  rewrite wordToNat_natToWord_idempotent.\n  auto.\n  rewrite N2Nat.id.\n  apply buf_size_lower''.\nQed.\n\nLemma bsize_roundTrip : wordToNat (natToW bsize) = bsize.\n  apply wordToNat_natToWord_idempotent.\n  unfold bsize.\n  rewrite N2Nat.id.\n  apply (Buf_size_upper _ _ _ _ Wf).\nQed.\n\nHint Rewrite bsize_in bsize_roundTrip : sepFormula.\nHint Rewrite bsize_roundTrip : N.\n\nHint Extern 1 (_ ?X = 0) =>\n  match type of X with\n    | list ?A => equate X (@nil A); reflexivity\n  end.\n\nLemma inBounds_nil : forall n, RelDb.inBounds n nil.\n  constructor.\nQed.\n\nHint Immediate inBounds_nil.\n\nLemma freeable8_8 : forall p n,\n  n = 8\n  -> freeable p 2\n  -> freeable8 p n.\n  intros; subst; eexists; split; eauto; eauto.\nQed.\n\nHint Immediate freeable8_8.\n\nLemma arrays_begone : forall specs P p q,\n  himp specs P (P * (array nil p * array nil q))%Sep.\n  unfold array; sepLemma.\nQed.\n\nHint Immediate arrays_begone.\n\nLemma bsize_bound : forall w : W,\n  w <= natToW bsize\n  -> (wordToNat w <= bsize)%nat.\n  intros.\n  nomega.\nQed.\n\nHint Immediate bsize_bound.\n\nLtac t0 := sep unf hints; eauto.\n\nLtac t1 := unf; unfold localsInvariantMain; post; evaluate hints; descend;\n  try match_locals; sep unf hints; eauto.\n\nLtac t :=\n  try match goal with\n        | [ |- context[unfold_here] ] => unfold buffer; generalize (NotTooGreedy _ _ _ _ Wf)\n      end; try solve [ t0 ]; t1.\n\nLtac u := abstract t.\n\nTheorem ok0 : moduleOk m0.\n  vcgen; abstract t.\nQed.\n\nSection boot.\n  Definition heapSize' := Hide.to_nat heapSize.\n\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%N.\n\n  Let heapSizeLowerBound' : (3 <= heapSize')%nat.\n    intros; unfold heapSize'; rewrite Hide.to_nat_eq.\n    assert (heapSize >= 3)%N by (apply N.le_ge; apply heapSizeLowerBound); nomega.\n  Qed.\n\n  Definition size := heapSize' + 50 + 2 + length ts.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize' * 4).\n    goodSize.\n  Qed.\n\n  Lemma heapSizeLowerBound'' : natToW 3 <= NToW heapSize.\n    hnf; intros.\n    red in H.\n    pre_nomega.\n    rewrite wordToNat_natToWord_idempotent in H by reflexivity.\n    unfold heapSize' in *.\n    rewrite Hide.to_nat_eq in *.\n    unfold NToW in *.\n    rewrite NToWord_nat in *.\n    rewrite wordToNat_natToWord_idempotent in H.\n    omega.\n    rewrite N2Nat.id.\n    eapply goodSize_weaken in mem_size.\n    2: instantiate (1 := N.to_nat heapSize); unfold size.\n    Transparent goodSize.\n    unfold goodSize in *.\n    rewrite N2Nat.id in *.\n    assumption.\n    unfold heapSize'.\n    rewrite Hide.to_nat_eq.\n    omega.\n  Qed.\n\n  Hint Immediate heapSizeLowerBound''.\n\n  Definition bootS := {|\n    Reserved := 49;\n    Formals := nil;\n    Precondition := fun _ => st ~> ![ 0 =?> (heapSize' + 50 + 2) * db ts ] st\n  |}.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"xml_driver\"!\"main\" @ [mainS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%N;;\n\n        Assert [PREmain[_] globalSched =?> 2 * 0 =?> heapSize' * db ts];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREmain[_] globalSock =?> 1 * globalSched =?> 1 * mallocHeap 0 * db ts];;\n\n        Goto \"xml_driver\"!\"main\"\n      end\n    }}.\n\n  Lemma bootstrap_Sp_nonzero : forall sp : W,\n    sp = 0\n    -> sp = (heapSize' * 4)%nat\n    -> goodSize (heapSize' * 4)\n    -> False.\n    intros; eapply bootstrap_Sp_nonzero; try eassumption; eauto.\n  Qed.\n\n  Lemma bootstrap_Sp_freeable : forall sp : W,\n    sp = (heapSize' * 4)%nat\n    -> freeable sp 50.\n    intros; eapply bootstrap_Sp_freeable; try eassumption; eauto.\n    instantiate (1 := 2).\n    unfold size in mem_size.\n    eapply goodSize_weaken; try apply mem_size.\n    omega.\n  Qed.\n\n  Lemma noWrap : noWrapAround 4 (wordToNat (NToW heapSize) - 1).\n    intros.\n    unfold NToW; rewrite NToWord_nat by auto.\n    unfold heapSize' in *; rewrite Hide.to_nat_eq in *.\n    rewrite wordToNat_natToWord_idempotent.\n    apply noWrap; eauto.\n    eapply goodSize_weaken.\n    2: instantiate (1 := (heapSize' * 4)%nat).\n    unfold heapSize'; rewrite Hide.to_nat_eq; auto.\n    unfold heapSize'; rewrite Hide.to_nat_eq; auto.\n  Qed.\n\n  Local Hint Immediate bootstrap_Sp_nonzero bootstrap_Sp_freeable noWrap.\n\n  Lemma break : NToW ((heapSize + 50) * 4)%N = ((heapSize' + 50) * 4)%nat.\n    intros.\n    unfold NToW; rewrite NToWord_nat by auto.\n    unfold heapSize'; rewrite N2Nat.inj_mul; auto.\n    rewrite Hide.to_nat_eq; rewrite N2Nat.inj_add; auto.\n  Qed.\n\n  Lemma times4 : (Hide.heapSize4 heapSize : W) = (heapSize' * 4)%nat.\n    rewrite Hide.heapSize4_eq; intros.\n    unfold NToW; rewrite NToWord_nat by auto.\n    unfold heapSize'; rewrite N2Nat.inj_mul; auto.\n    rewrite Hide.to_nat_eq; auto.\n  Qed.\n\n  Lemma wordToNat_heapSize : wordToNat (NToW heapSize) = heapSize'.\n    unfold heapSize'; rewrite Hide.to_nat_eq.\n    unfold NToW.\n    rewrite NToWord_nat.\n    apply wordToNat_natToWord_idempotent.\n    eapply goodSize_weaken.\n    2: instantiate (1 := (heapSize' * 4)%nat).\n    auto.\n    unfold heapSize'; rewrite Hide.to_nat_eq; auto.\n  Qed.\n\n  Hint Rewrite break times4 wordToNat_heapSize : sepFormula.\n\n  Lemma globalSched_plus4 :\n    Locations.globalSched ^+ natToW 4 = natToW ((heapSize' + 50) * 4 + 4).\n    unfold Locations.globalSched, heapSize'.\n    rewrite wplus_alt; unfold wplusN, wordBinN.\n    unfold NToW; rewrite NToWord_nat by auto.\n    rewrite N2Nat.inj_mul; auto.\n    rewrite Hide.to_nat_eq; rewrite N2Nat.inj_add; auto.\n    change (wordToNat (natToW 4)) with 4.\n    change (N.to_nat 4) with 4.\n    rewrite wordToNat_natToWord_idempotent.\n    reflexivity.\n    eapply goodSize_weaken; try apply mem_size.\n    unfold size, heapSize'.\n    rewrite Hide.to_nat_eq.\n    change (N.to_nat 50) with 50.\n    omega.\n  Qed.\n\n  Hint Rewrite globalSched_plus4 : sepFormula.\n\n  Ltac t := unfold M'''.globalSched, Locations.globalSched, Locations.globalSock, localsInvariantMain;\n    genesis; rewrite natToW_plus; reflexivity.\n\n  Theorem okb : moduleOk boot.\n    unfold boot; rewrite <- Hide.heapSize4_eq; vcgen; abstract t.\n  Qed.\n\n  Global Opaque heapSize'.\n\n  Lemma buf_size_upper' : goodSize (4 * wordToNat (NToWord 32 buf_size)).\n    red.\n    rewrite Nat2N.inj_mul.\n    rewrite NToWord_nat.\n    rewrite wordToNat_natToWord_idempotent.\n    rewrite N2Nat.id.\n    rewrite Nmult_comm.\n    apply (Buf_size_upper _ _ _ _ Wf).\n    rewrite N2Nat.id.\n    clear; generalize (Buf_size_upper _ _ _ _ Wf).\n    generalize (Npow2 32).\n    Hint Rewrite N2Nat.inj_mul : N.\n    intros; nomega.\n  Qed.\n\n  Definition m1 := link boot m0.\n  Definition m2 := link Buffers.m m1.\n  Definition m3 := link XmlLex.m m2.\n  Definition m4 := link ArrayOps.m m3.\n  Definition m5 := link NumOps.m m4.\n  Definition m6 := link MyIo.m m5.\n  Definition m7 := link MyHttp.m m6.\n  Definition m8 := link MyHttpQ.m m7.\n  Definition m9 := link T.m m8.\n\n  Definition m := link (XmlLang.m _ httpq\n    buf_size_lower' buf_size_upper'\n    (WellFormed _ _ _ _ Wf) (ND _ _ _ _ Wf)\n    (GoodSchema _ _ _ _ Wf)) m9.\n\n  Lemma ok1 : moduleOk m1.\n    link okb ok0.\n  Qed.\n\n  Lemma ok2 : moduleOk m2.\n    link Buffers.ok ok1.\n  Qed.\n\n  Lemma ok3 : moduleOk m3.\n    link XmlLex.ok ok2.\n  Qed.\n\n  Lemma ok4 : moduleOk m4.\n    link ArrayOps.ok ok3.\n  Qed.\n\n  Lemma ok5 : moduleOk m5.\n    link NumOps.ok ok4.\n  Qed.\n\n  Lemma ok6 : moduleOk m6.\n    link MyIo.ok ok5.\n  Qed.\n\n  Lemma ok7 : moduleOk m7.\n    link MyHttp.ok ok6.\n  Qed.\n\n  Lemma ok8 : moduleOk m8.\n    link MyHttpQ.ok ok7.\n  Qed.\n\n  Lemma ok9 : moduleOk m9.\n    link T.ok ok8.\n  Qed.\n\n  Lemma ok : moduleOk m.\n    link (XmlLang.ok _ httpq buf_size_lower' buf_size_upper' (WellFormed _ _ _ _ Wf)) ok9;\n    apply (UF _ _ _ _ Wf).\n  Qed.\n  \n  Variable stn : settings.\n  Variable prog : IL.program.\n  \n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis prec : forall specs, interp specs (Precondition bootS None (stn, st)).\n\n  Import Safety.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    eapply safety; try eassumption; [\n      link_simp; unfold labelSys, labelSys'; simpl; tauto\n      | apply ok\n      | apply LabelMap.find_2; link_simp; reflexivity\n      | auto ].\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/XmlProg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.23584497155546388}}
{"text": "(* ************************************************************************** *)\n(*                                                                            *)\n(* Verified Flash Translation Layer                                           *)\n(*                                                                            *)\n(*                                                                            *)\n(*   Author: Yu Guo <guoyu@ustc.edu.cn>                                       *)\n(*                          School of Computer Science and Technology, USTC   *)\n(*                                                                            *)\n(*           Yishuai Li <lyishuai@mail.ustc.edu.cn>                           *)\n(*                                         School of the Gifted Young, USTC   *)\n(*                                                                            *)\n(* ************************************************************************** *)\n\nRequire Import ListEx.\nRequire Import Monad.\n\nRequire Import Params.\nRequire Import Nand.\nRequire Import Data.\nRequire Import FtlFast.\n\nOpen Scope list_scope.\n\nDefinition write_command : Set := (block_no * page_off * char) %type.\n\nImport NewNand.\nImport NandData.\n\n(* Test NAND *)\n\nFixpoint nand_write_batch (c: chip) (wl : list write_command) \n  : op_result chip :=\n  match wl with \n    | nil => ret c\n    | cons wr wl' => \n      let (pn, char) := wr in\n      let (b, off) := pn in\n      do c' <== nand_write_page c b off (mkdata_chars (char::nil)) mkoob_empty;\n      nand_write_batch c' wl'\n  end.\n\nCompute ( \n  let wl := (0,0,c_a) :: nil in\n  do c0 <-- Some nand_init;\n  do c <== nand_write_batch c0 wl;\n  ret c).\n\nCompute ( \n  let wl := (0,0,c_a) :: (0,1,c_a) :: nil in\n  do c0 <-- Some nand_init;\n  do c <== nand_write_batch c0 wl;\n  ret c).\n\nCompute ( \n  let wl := (0,0,c_a) :: (0,1,c_a) :: nil in\n  do c0 <-- Some nand_init;\n  do c <== nand_write_batch c0 wl;\n  do c'<== nand_erase_block c 0;\n  ret c').\n\n(* Test NAND *)\n\nFixpoint ftl_write_batch (c: chip)(f: FTL) (wl : list write_command) \n  : op_result (chip * FTL) :=\n  match wl with \n    | nil => ret (c, f)\n    | cons wr wl' => \n      let (pn, char) := wr in\n      let (b, off) := pn in\n      do [c', f'] <== ftl_write c f b off (mkdata_chars (char::nil));\n      ftl_write_batch c' f' wl'\n  end.\n\nLet c0 := nand_init.\nLet f0 := ftl_init.\n\nCompute ( \n  let wl := (0,0,c_a) :: nil in\n  do [c, f] <== ftl_write_batch c0 f0 wl;\n  ret (c, f)).\n\nCompute ( \n  let wl := (0,0,c_a)::(0,1,c_b)::(0,0,c_c)::(0,0,c_d)::\nnil in\n  do c0 <-- Some nand_init;\n  do f0 <-- Some ftl_init;\n  do [c, f] <== ftl_write_batch c0 f0 wl;\n  ret (c, f)).\n", "meta": {"author": "zbh24", "repo": "DFTL", "sha": "685ac48f010e0fc2621e04defbeb57caee34186a", "save_path": "github-repos/coq/zbh24-DFTL", "path": "github-repos/coq/zbh24-DFTL/DFTL-685ac48f010e0fc2621e04defbeb57caee34186a/Test.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.235708802209709}}
{"text": "Coq < Section Easy012.\n\nCoq < Require Import Classical.\n\nCoq < Load CptdTactics.\nError: Can't find file CptdTactics.v on loadpath\n\nCoq < Load CpdtTactics.\n\nCoq < Variables I J K L: Prop.\nI is assumed\nJ is assumed\nK is assumed\nL is assumed\n\nCoq < Goal ((I /\\ J) /\\ (K /\\ L)) -> (I /\\ L).\n1 subgoal\n  \n  I : Prop\n  J : Prop\n  K : Prop\n  L : Prop\n  ============================\n   (I /\\ J) /\\ K /\\ L -> I /\\ L\n\nUnnamed_thm < crush.\nNo more subgoals.\n\nUnnamed_thm < Qed.\ncrush.\n\nUnnamed_thm is defined\n", "meta": {"author": "billwestfall", "repo": "coq_ide", "sha": "a2985a04f37f9c1c6f23799d543fdb862792d54b", "save_path": "github-repos/coq/billwestfall-coq_ide", "path": "github-repos/coq/billwestfall-coq_ide/coq_ide-a2985a04f37f9c1c6f23799d543fdb862792d54b/cptd/chapt01/012.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.23570879540448894}}
{"text": "Require Import\n        CertifiedExtraction.Extraction.DeallocSCA\n        CertifiedExtraction.Extraction.External.Core.\n\nLemma CompileWhileFalse:\n  forall {av} (env : GLabelMap.t (FuncSpec av)) (ext : StringMap.t (Value av))\n    (tenv : Telescope av) tenv' test body,\n    TelEq ext tenv tenv' ->\n    Lifted_is_false ext tenv test ->\n    {{ tenv }} (DFacade.While test body) {{ tenv' }} ∪ {{ ext }} // env.\nProof.\n  intros * H **.\n  rewrite <- H; clear H.\n  repeat match goal with\n         | [ H: forall st, st ≲ _ ∪ _ -> _, H': ?st ≲ _ ∪ _ |- _ ] => learn (H _ H')\n         | [ H: is_true ?t ?st, H': is_false ?t ?st |- _ ] => exfalso; exact (is_true_is_false_contradiction H H')\n         | _ => SameValues_Facade_t_step\n         | _ => facade_cleanup_call\n         | _ => LiftPropertyToTelescope_t\n         | _ => apply SafeWhileFalse\n         | [ H: RunsTo _ (DFacade.While _ _) _ _ |- _ ] => inversion H; unfold_and_subst; clear H\n         end.\nQed.\n\nLemma CompileWhileTrue:\n  forall {av} (env : GLabelMap.t (FuncSpec av)) (ext : StringMap.t (Value av))\n    (tenv : Telescope av) tenv' tenv'' test body,\n    Lifted_is_true ext tenv test ->\n    {{ tenv }}  body                      {{ tenv' }}  ∪ {{ ext }} // env ->\n    {{ tenv' }} (DFacade.While test body) {{ tenv'' }} ∪ {{ ext }} // env ->\n    {{ tenv }}  (DFacade.While test body) {{ tenv'' }} ∪ {{ ext }} // env.\nProof.\n  repeat match goal with\n         | [ H: forall st, st ≲ _ ∪ _ -> _, H': ?st ≲ _ ∪ _ |- _ ] => learn (H _ H')\n         | [ H: is_true ?t ?st, H': is_false ?t ?st |- _ ] => exfalso; exact (is_true_is_false_contradiction H H')\n         | _ => SameValues_Facade_t_step\n         | _ => facade_cleanup_call\n         | _ => LiftPropertyToTelescope_t\n         | _ => apply SafeWhileTrue\n         | [ H: RunsTo _ (DFacade.While _ _) _ _ |- _ ] => inversion H; unfold_and_subst; clear H\n         end.\nQed.\n\nLemma CompileWhileFalse_Loop:\n  forall {av} (vtest : StringMap.key)\n    (env : GLabelMap.t (FuncSpec av)) (ext : StringMap.t (Value av))\n    (tenv : Telescope av) tenv' body,\n    TelEq ext tenv tenv' ->\n    vtest ∉ ext ->\n    NotInTelescope vtest tenv ->\n    {{[[`vtest ->> (Word.natToWord 32 1) as _]]::tenv }}\n      (DFacade.While (TestE IL.Eq vtest O) body)\n    {{ tenv' }} ∪ {{ ext }} // env.\nProof.\n  intros * H **.\n  rewrite <- H.\n  apply CompileDeallocW_discretely; eauto.\n  apply CompileWhileFalse.\n  reflexivity.\n  unfold Lifted_is_false, LiftPropertyToTelescope, is_true, is_false, eval_bool, eval;\n  repeat match goal with\n         | _ => SameValues_Facade_t_step\n         | _ => facade_cleanup_call\n         | _ => progress simpl\n         end.\nQed.\n\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/CertifiedExtraction/Extraction/External/Loops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.23570879540448894}}
{"text": "(* from https://github.com/amintimany/monotone *)\nFrom iris.algebra Require Export cmra auth.\nFrom transfinite.base_logic Require Import base_logic.\nLocal Arguments validN _ _ _ !_ /.\nLocal Arguments valid _ _  !_ /.\nLocal Arguments op _ _ _ !_ /.\nLocal Arguments pcore _ _ !_ /.\nLocal Arguments ofe_dist !_ /.\nLocal Arguments ofe_equiv ! _ /.\n\nDefinition monotone {A : Type} (R : relation A) : Type := list A.\n\nDefinition principal {A : Type} (R : relation A) (a : A) :\n  monotone R := [a].\n\nSection monotone.\nLocal Set Default Proof Using \"Type\".\nContext `{SI: indexT}.\nContext {A : ofe} {R : relation A}.\nImplicit Types a b : A.\nImplicit Types x y : monotone R.\n\nDefinition Below (a : A) (x : monotone R) := ∃ b, b ∈ x ∧ R a b.\n\nLemma Below_app a x y : Below a (x ++ y) ↔ Below a x ∨ Below a y.\nProof.\n  split.\n  - intros (b & [|]%elem_of_app & ?); [left|right]; exists b; eauto.\n  - intros [(b & Hb1 & Hb2)|(b & Hb1 & Hb2)]; exists b; rewrite elem_of_app; eauto.\nQed.\n\nLemma Below_principal a b : Below a (principal R b) ↔ R a b.\nProof.\n  split.\n  - intros (c & ->%elem_of_list_singleton & ?); done.\n  - intros Hab; exists b; split; first apply elem_of_list_singleton; done.\nQed.\n\n(* OFE *)\nInstance monotone_dist : Dist (monotone R) :=\n  λ n x y, ∀ a, Below a x ↔ Below a y.\n\nInstance monotone_equiv : Equiv (monotone R) := λ x y, ∀ n, x ≡{n}≡ y.\n\nDefinition monotone_ofe_mixin : OfeMixin (monotone R).\nProof.\n  split.\n  - rewrite /equiv /monotone_equiv /dist /monotone_dist; intuition auto using O.\n  - intros n; split.\n    + rewrite /dist /monotone_dist /equiv /monotone_equiv; intuition.\n    + rewrite /dist /monotone_dist /equiv /monotone_equiv; intros ? ? Heq a.\n      split; apply Heq.\n    + rewrite /dist /monotone_dist /equiv /monotone_equiv;\n        intros ? ? ? Heq Heq' a.\n      split; intros Hxy.\n      * apply Heq'; apply Heq; auto.\n      * apply Heq; apply Heq'; auto.\n  - intros n x y; rewrite /dist /monotone_dist; auto.\nQed.\nCanonical Structure monotoneC := Ofe (monotone R) monotone_ofe_mixin.\n\n(* CMRA *)\nInstance monotone_validN : ValidN (monotone R) := λ n x, True.\nInstance monotone_valid : Valid (monotone R) := λ x, True.\n\nProgram Instance monotone_op : Op (monotone R) := λ x y, x ++ y.\nInstance monotone_pcore : PCore (monotone R) := Some.\n\nInstance monotone_comm : Comm (≡) (@op (monotone R) _).\nProof.\n  intros x y n a; rewrite /Below.\n  setoid_rewrite elem_of_app; split=> Ha; firstorder.\nQed.\nInstance monotone_assoc : Assoc (≡) (@op (monotone R) _).\nProof.\n  intros x y z n a; rewrite /Below /=.\n  repeat setoid_rewrite elem_of_app; split=> Ha; firstorder.\nQed.\nLemma monotone_idemp (x : monotone R) : x ⋅ x ≡ x.\nProof.\n  intros n a; rewrite /Below.\n  setoid_rewrite elem_of_app; split=> Ha; firstorder.\nQed.\n\nInstance monotone_validN_ne n :\n  Proper (dist n ==> impl) (@validN _ (monotone R) _ n).\nProof. intros x y ?; rewrite /impl; auto. Qed.\nInstance monotone_validN_proper n : Proper (equiv ==> iff) (@validN _ (monotone R) _ n).\nProof. move=> x y /equiv_dist H; auto. Qed.\n\nInstance monotone_op_ne' x : NonExpansive (op x).\nProof.\n  intros n y1 y2; rewrite /dist /monotone_dist /equiv /monotone_equiv /Below.\n  rewrite /=; setoid_rewrite elem_of_app => Heq a.\n  specialize (Heq a); destruct Heq as [Heq1 Heq2].\n  split; intros [b [[Hb|Hb] HRb]]; eauto.\n  - destruct Heq1 as [? [? ?]]; eauto.\n  - destruct Heq2 as [? [? ?]]; eauto.\nQed.\nInstance monotone_op_ne : NonExpansive2 (@op (monotone R) _).\nProof. by intros n x1 x2 Hx y1 y2 Hy; rewrite Hy !(comm _ _ y2) Hx. Qed.\nInstance monotone_op_proper :\n  Proper ((≡) ==> (≡) ==> (≡)) (@op (monotone R) _) := ne_proper_2 _.\n\nLemma monotone_included (x y : monotone R) : x ≼ y ↔ y ≡ x ⋅ y.\nProof.\n  split; [|by intros ?; exists y].\n  by intros [z Hz]; rewrite Hz assoc monotone_idemp.\nQed.\n\nDefinition monotone_cmra_mixin : CmraMixin (monotone R).\nProof.\n  apply cmra_total_mixin; try apply _ || by eauto.\n  - intros ?; apply monotone_idemp.\n  - rewrite /equiv /monotone_equiv /dist /monotone_dist; eauto.\nQed.\nCanonical Structure monotoneR : cmra := Cmra (monotone R) monotone_cmra_mixin.\n\nGlobal Instance monotone_cmra_total : CmraTotal monotoneR.\nProof. rewrite /CmraTotal; eauto. Qed.\nGlobal Instance monotone_core_id (x : monotone R) : CoreId x.\nProof. by constructor. Qed.\n\nGlobal Instance monotone_cmra_discrete : CmraDiscrete monotoneR.\nProof.\n  split; auto.\n  intros ? ?.\n  rewrite /dist /equiv /= /cmra_dist /cmra_equiv /=\n          /monotone_dist /monotone_equiv /dist /monotone_dist; eauto.\nQed.\n\nInstance monotone_empty : Unit (monotone R) := @nil A.\nLemma auth_ucmra_mixin : UcmraMixin (monotone R).\nProof. split; done. Qed.\n\nCanonical Structure monotoneUR := Ucmra (monotone R) auth_ucmra_mixin.\n\nGlobal Instance principal_ne\n       `{HRne : !∀ n, Proper ((dist n) ==> (dist n) ==> iff) R} :\n  NonExpansive (principal R).\nProof. intros n a1 a2 Ha; split; rewrite /= !Below_principal !Ha; done. Qed.\n\nGlobal Instance principal_proper\n       {HRne : ∀ n, Proper ((dist n) ==> (dist n) ==> iff) R} :\n  Proper ((≡) ==> (≡)) (principal R) := ne_proper _.\n\nGlobal Instance principal_discrete a : Discrete (principal R a).\nProof.\n  intros y; rewrite /dist /ofe_dist /= /equiv /ofe_equiv /= /monotone_equiv;\n    eauto.\nQed.\n\nLemma principal_injN_general n a b :\n  principal R a ≡{n}≡ principal R b → R a a → R a b.\nProof.\n  rewrite /principal /dist /monotone_dist => Hab Haa.\n  - destruct (Hab a) as [Ha _]; edestruct Ha as [? [?%elem_of_list_singleton ?]];\n    subst; eauto.\n    eexists _; split; first apply elem_of_list_singleton; eauto.\nQed.\n\nLemma principal_inj_general a b :\n  principal R a ≡ principal R b → R a a → R a b.\nProof. intros Hab; apply (principal_injN_general (@index_zero _)); eauto. Qed.\n\nGlobal Instance principal_injN_general' `{!Reflexive R} n :\n  Inj (λ a b, R a b ∧ R b a) (dist n) (principal R).\nProof.\n  intros x y Hxy; split; eapply (principal_injN_general n); eauto.\nQed.\n\nGlobal Instance principal_inj_general' `{!Reflexive R} :\n  Inj (λ a b, R a b ∧ R b a) (≡) (principal R).\nProof.\n  intros x y Hxy; specialize (Hxy (@index_zero _)); eapply principal_injN_general'; eauto.\nQed.\n\nGlobal Instance principal_injN `{!Reflexive R} {Has : AntiSymm (≡) R} n :\n  Inj (dist n) (dist n) (principal R).\nProof.\n  intros x y [Hxy Hyx]%principal_injN_general'.\n  erewrite (@anti_symm _ _ _ Has); eauto.\nQed.\nGlobal Instance principal_inj `{!Reflexive R} `{!AntiSymm (≡) R} :\n  Inj (≡) (≡) (principal R).\nProof. intros ???. apply equiv_dist=>n. by apply principal_injN, equiv_dist. Qed.\n\nLemma principal_R_opN_base `{!Transitive R} n x y :\n  (∀ b, b ∈ y → ∃ c, c ∈ x ∧ R b c) → y ⋅ x ≡{n}≡ x.\nProof.\n  intros HR; split; rewrite /op /monotone_op Below_app; [|by firstorder].\n  intros [(c & (d & Hd1 & Hd2)%HR & Hc2)|]; [|done].\n  exists d; split; [|transitivity c]; done.\nQed.\n\nLemma principal_R_opN `{!Transitive R} n a b :\n  R a b → principal R a ⋅ principal R b ≡{n}≡ principal R b.\nProof.\n  intros; apply principal_R_opN_base; intros c; rewrite /principal.\n  setoid_rewrite elem_of_list_singleton => ->; eauto.\nQed.\n\nLemma principal_R_op `{!Transitive R} a b :\n  R a b → principal R a ⋅ principal R b ≡ principal R b.\nProof. by intros ? ?; apply principal_R_opN. Qed.\n\nLemma principal_op_RN n a b x :\n  R a a → principal R a ⋅ x ≡{n}≡ principal R b → R a b.\nProof.\n  intros Ha HR.\n  destruct (HR a) as [[z [HR1%elem_of_list_singleton HR2]] _];\n    last by subst; eauto.\n  rewrite /op /monotone_op /principal Below_app Below_principal; auto.\nQed.\n\nLemma principal_op_R a b x :\n  R a a → principal R a ⋅ x ≡ principal R b → R a b.\nProof. intros ? ?; eapply (principal_op_RN (@index_zero _)); eauto. Qed.\n\nLemma principal_op_R' `{!Reflexive R} a b x :\n  principal R a ⋅ x ≡ principal R b → R a b.\nProof. intros; eapply principal_op_R; eauto. Qed.\n\nLemma principal_includedN `{!PreOrder R} n a b :\n  principal R a ≼{n} principal R b ↔ R a b.\nProof.\n  split.\n  - intros [z Hz]; eapply principal_op_RN; last by rewrite Hz; eauto.\n    reflexivity.\n  - intros ?; exists (principal R b); rewrite principal_R_opN; eauto.\nQed.\n\nLemma principal_included `{!PreOrder R} a b :\n  principal R a ≼ principal R b ↔ R a b.\nProof.\n  split.\n  - intros [z Hz]; eapply principal_op_R; last by rewrite Hz; eauto.\n    reflexivity.\n  - intros ?; exists (principal R b); rewrite principal_R_op; eauto.\nQed.\n\n(** Internalized properties *)\nLemma monotone_equivI `{!(∀ n : _, Proper (dist n ==> dist n ==> iff) R)}\n      `{!Reflexive R} `{!AntiSymm (≡) R} {M} a b :\n  principal R a ≡ principal R b ⊣⊢ (a ≡ b : uPred M).\nProof.\n  uPred.unseal. do 2 split.\n  - intros Hx. exact: principal_injN.\n  - intros Hx. exact: principal_ne.\nQed.\n\nLemma monotone_local_update_grow `{!Transitive R} a q na:\n  R a na →\n  (principal R a, q) ~l~> (principal R na, principal R na).\nProof.\n  intros Hana Hanb.\n  apply local_update_unital_discrete.\n  intros z _ Habz.\n  split; first done.\n  intros n; specialize (Habz n).\n  intros x; split.\n  - intros (y & ->%elem_of_list_singleton & Hy2).\n    by exists na; split; first constructor.\n  - intros (y & [->|Hy1]%elem_of_cons & Hy2).\n    + by exists na; split; first constructor.\n    + exists na; split; first constructor.\n      specialize (Habz x) as [_ [c [->%elem_of_list_singleton Hc2]]].\n      { exists y; split; first (by apply elem_of_app; right); eauto. }\n      etrans; eauto.\nQed.\n\nLemma monotone_local_update_get_frag `{!PreOrder R} a na:\n  R na a →\n  (principal R a, ε) ~l~> (principal R a, principal R na).\nProof.\n  intros Hana.\n  apply local_update_unital_discrete.\n  intros z _.\n  rewrite left_id.\n  intros <-.\n  split; first done.\n  apply monotone_included.\n  by apply principal_included.\nQed.\n\nLemma monotone_update `{!PreOrder R} a b c:\n  R a b →\n  R c b →\n  ● principal R a ~~> ● principal R b ⋅ ◯ principal R c.\nProof.\n  intros Hab Hcb.\n  etrans.\n  { apply auth_update_alloc; apply (monotone_local_update_grow _ _ b); done. }\n  etrans; first apply cmra_update_op_l.\n  apply auth_update_alloc.\n  apply monotone_local_update_get_frag; done.\nQed.\n\n\nEnd monotone.\n\nArguments monotoneC {_ _} _.\nArguments monotoneR {_ _} _.\nArguments monotoneUR {_ _} _.\n\n\n(** Having an instance of this class for a relation R allows almost\nall lemmas provided in this module to be used. See type classes\nrequired by some of preceding the lemmas and instances in the to see\nhow this works.\n\nThe only lemma that requires extra conditions on R is the injectivity\nof principal which requires antisymmetry. *)\nClass ProperPreOrder {A : Type} `{Dist A} (R : relation A) := {\n  ProperPreOrder_preorder :> PreOrder R;\n  ProperPreOrder_ne :> ∀ n, Proper ((dist n) ==> (dist n) ==> iff) R\n}.\n", "meta": {"author": "logsem", "repo": "melocoton", "sha": "b77eecc3381f53db0eb3c4cf1314e881a8dc41b3", "save_path": "github-repos/coq/logsem-melocoton", "path": "github-repos/coq/logsem-melocoton/melocoton-b77eecc3381f53db0eb3c4cf1314e881a8dc41b3/theories/monotone.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.23570879540448894}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.even.\nRequire Import VST.progs.verif_evenodd_spec.\n\nLocal Open Scope assert.\n\nDefinition Gprog : funspecs :=\n     ltac:(with_library prog [odd_spec; even_spec; main_spec]).\n\nLemma body_even : semax_body Vprog Gprog f_even even_spec.\nProof.\nstart_function.\nforward_if.\n*\n forward.\n*\n  forward_call (z-1, tt).\n  (* Prove that PROP precondition is OK *)\n  rep_omega.\n  (* After the call *)\n  forward.\n  entailer!.\n  rewrite Z.odd_sub; simpl.\n  case_eq (Z.odd z); rewrite Zodd_even_bool; destruct (Z.even z); simpl; try congruence.\nQed.\n\nLemma body_main : semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nforward_call (42).\nrep_omega.\nforward.\nQed.\n\n(* The Espec for odd is different from the Espec for even;\n  the former has only \"even\" as an external function, and vice versa. *)\nDefinition Espec := add_funspecs NullExtension.Espec (ext_link_prog even.prog) Gprog.\nExisting Instance Espec.\n\nLemma prog_correct:\n  semax_prog prog Vprog Gprog.\nProof.\nprove_semax_prog.\nsemax_func_cons_ext.\nsemax_func_cons body_even.\nsemax_func_cons body_main.\nQed.\n", "meta": {"author": "anshumanmohan", "repo": "RamifyCoq_VST", "sha": "0517a39b069f79f50a45321db6ca81c48397b73d", "save_path": "github-repos/coq/anshumanmohan-RamifyCoq_VST", "path": "github-repos/coq/anshumanmohan-RamifyCoq_VST/RamifyCoq_VST-0517a39b069f79f50a45321db6ca81c48397b73d/VST/progs/verif_even.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.23570878859926886}}
{"text": "From Coq Require Import List.\nImport ListNotations.\n\nFrom CasperCBC Require Import Lib.ListExtras VLSM.Common.\n\n(** * VLSM Plans *)\n\nSection plans.\n  Context\n    {message : Type}\n    {T : VLSM_type message}.\n\n  (** A plan is a (sequence of actions) which can be attempted on a\n  given state to yield a trace.\n  A [plan_item] is a singleton plan, and contains a label and an input\n  which would allow to transition from any given state\n  (note that we don't address validity for now)\n  *)\n  Record plan_item :=\n    { label_a : label;\n      input_a : option message\n    }.\n\nEnd plans.\n\nSection apply_plans.\n\n  Context\n    {message : Type}\n    {T : VLSM_type message}\n    {transition : label -> state * option message -> state * option message}\n    .\n\n  (** If we don't concern ourselves with the validity of the traces obtained\n  upon applying a plan, then a [VLSM_type] and a [transition] function\n  suffice for defining plan application and related results.\n  The advantage of this approach is that the same definition works for\n  pre_loaded versions as well as for all constrained variants of a composition.\n  *)\n\n  (** Applying a plan (list of [plan_item]s) to a state we obtain a\n  final state and a trace. We define that in the [_apply_plan] definition below\n  using a folding operation on the [_apply_plan_folder] function.\n  *)\n  Definition _apply_plan_folder\n    (a : plan_item)\n    (sl : state * list transition_item)\n    : state * list transition_item\n    :=\n    let (s, items) := sl in\n    match a with {| label_a := l'; input_a := input' |} =>\n      let (dest, out) := (transition l' (s, input')) in\n      (dest\n      , {| l := l';\n           input := input';\n           output := out;\n           destination := dest\n         |} :: items)\n    end.\n\n  Lemma _apply_plan_folder_additive\n    (start : state)\n    (aitems : list plan_item)\n    (seed_items : list transition_item)\n    : let (final, items) := fold_right _apply_plan_folder (start, []) aitems in\n      fold_right _apply_plan_folder (start, seed_items) aitems = (final, items ++ seed_items).\n  Proof.\n    generalize dependent seed_items.\n    induction aitems; simpl; intros; try reflexivity.\n    destruct (fold_right _apply_plan_folder (start, []) aitems) as (afinal, aitemsX).\n    rewrite IHaitems.\n    destruct a. simpl. destruct (transition label_a0 (afinal, input_a0)) as (dest, out).\n    reflexivity.\n  Qed.\n\n  Definition _apply_plan\n    (start : state)\n    (a : list plan_item)\n    : list transition_item * state\n    :=\n    let (final, items) :=\n      fold_right _apply_plan_folder (@pair state _ start []) (rev a) in\n    (rev items, final).\n\n  Lemma _apply_plan_last\n    (start : state)\n    (a : list plan_item)\n    (after_a := _apply_plan start a)\n    : finite_trace_last start (fst after_a) = snd after_a.\n  Proof.\n    induction a using rev_ind; try reflexivity.\n    unfold after_a. clear after_a. unfold _apply_plan.\n    rewrite rev_unit. unfold _apply_plan in IHa.\n    simpl in *.\n    destruct (fold_right _apply_plan_folder (start, []) (rev a)) as (final, items)\n      eqn:Happly.\n    simpl in IHa.\n    simpl.\n    destruct x.\n    destruct (transition label_a0 (final, input_a0)) as (dest,out) eqn:Ht.\n    unfold fst. unfold snd.\n    simpl.\n    rewrite finite_trace_last_is_last. reflexivity.\n  Qed.\n\n  Lemma _apply_plan_app\n    (start : state)\n    (a a' : list plan_item)\n    : _apply_plan start (a ++ a') =\n      let (aitems, afinal) := _apply_plan start a in\n      let (a'items, a'final) := _apply_plan afinal a' in\n       (aitems ++ a'items, a'final).\n  Proof.\n    unfold _apply_plan.\n    rewrite rev_app_distr.\n    rewrite fold_right_app. simpl.\n    destruct\n      (fold_right _apply_plan_folder (@pair state _ start []) (rev  a))\n      as (afinal, aitems) eqn:Ha.\n    destruct\n      (fold_right _apply_plan_folder (@pair state _ afinal []) (rev a'))\n      as (final, items) eqn:Ha'.\n    clear - Ha'.\n    specialize (_apply_plan_folder_additive afinal (rev a') aitems) as Hadd.\n    rewrite Ha' in Hadd.\n    rewrite Hadd. rewrite rev_app_distr. reflexivity.\n  Qed.\n\n  Lemma _apply_plan_cons\n    (start : state)\n    (ai : plan_item)\n    (a' : list plan_item)\n    : _apply_plan start (ai :: a') =\n      let (aitems, afinal) := _apply_plan start [ai] in\n      let (a'items, a'final) := _apply_plan afinal a' in\n       (aitems ++ a'items, a'final).\n  Proof.\n    replace (ai :: a') with ([ai] ++ a').\n    apply _apply_plan_app.\n    intuition.\n  Qed.\n\n  (** We can forget information from a trace to obtain a plan. *)\n  Definition _transition_item_to_plan_item\n    (item : transition_item)\n    : plan_item\n    := {| label_a := l item; input_a := input item |}.\n\n  Definition _trace_to_plan\n    (items : list transition_item)\n    : list plan_item\n    := map _transition_item_to_plan_item items.\n\n  Definition _messages_a\n    (a : list plan_item) :\n    list message :=\n    ListExtras.cat_option (List.map input_a a).\n\nEnd apply_plans.\n\nSection protocol_plans.\n\n  Context\n    {message : Type}\n    (X : VLSM message)\n    .\n\n  (**\n  We define several notations useful when we want to use the results above\n  for a specific [VLSM], by instantiating the generic definitions with the\n  corresponding [type] and [transition].\n  *)\n\n  Definition vplan_item := (@plan_item _ (type X)).\n  Definition plan : Type := list vplan_item.\n  Definition apply_plan := (@_apply_plan _ (type X) (vtransition X)).\n  Definition trace_to_plan := (@_trace_to_plan _ (type X)).\n  Definition apply_plan_app\n    (start : vstate X)\n    (a a' : plan)\n    : apply_plan start (a ++ a') =\n      let (aitems, afinal) := apply_plan start a in\n      let (a'items, a'final) := apply_plan afinal a' in\n       (aitems ++ a'items, a'final)\n    := (@_apply_plan_app _ (type X) (vtransition X) start a a').\n  Definition apply_plan_last\n    (start : vstate X)\n    (a : plan)\n    (after_a := apply_plan start a)\n    : finite_trace_last start (fst after_a) = snd after_a\n    := (@_apply_plan_last _ (type X) (vtransition X) start a).\n\n  (** A plan is protocol w.r.t. a state if by applying it to that state we\n  obtain a protocol trace sequence.\n  *)\n  Definition finite_protocol_plan_from\n    (s : vstate X)\n    (a : plan)\n    : Prop :=\n    finite_protocol_trace_from _ s (fst (apply_plan s a)).\n\n  Lemma finite_protocol_plan_from_app_iff\n    (s : vstate X)\n    (a b : plan)\n    (s_a := snd (apply_plan s a))\n    : finite_protocol_plan_from s a /\\ finite_protocol_plan_from s_a b <-> finite_protocol_plan_from s (a ++ b).\n  Proof.\n    unfold finite_protocol_plan_from.\n    specialize (apply_plan_app s a b) as Happ.\n    specialize (apply_plan_last s a) as Hlst.\n    destruct (apply_plan s a) as (aitems, afinal) eqn:Ha.\n    subst s_a.\n    simpl in *.\n    destruct (apply_plan afinal b) as (bitems, bfinal).\n    rewrite Happ. simpl. clear Happ. subst afinal.\n    apply finite_protocol_trace_from_app_iff.\n  Qed.\n\n  Lemma finite_protocol_plan_empty\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)  :\n    finite_protocol_plan_from s [].\n  Proof.\n    apply finite_ptrace_empty.\n    assumption.\n  Qed.\n\n  Lemma apply_plan_last_protocol\n    (s : vstate X)\n    (Hprs : protocol_state_prop X s)\n    (a : plan)\n    (Hpra : finite_protocol_plan_from s a)\n    (after_a := apply_plan s a) :\n    protocol_state_prop X (snd after_a).\n  Proof.\n    subst after_a.\n    rewrite <- apply_plan_last.\n    apply finite_ptrace_last_pstate.\n    assumption.\n  Qed.\n\n  (** By extracting a plan from a [protocol_trace] based on a state @s@\n  and reapplying the plan to the same state @s@ we obtain the original trace\n  *)\n  Lemma trace_to_plan_to_trace\n    (s : vstate X)\n    (tr : list (vtransition_item X))\n    (Htr : finite_protocol_trace_from X s tr)\n    : fst (apply_plan s (trace_to_plan tr)) = tr.\n  Proof.\n    induction Htr using finite_protocol_trace_from_rev_ind\n    ;[reflexivity|].\n    unfold trace_to_plan, _trace_to_plan.\n    rewrite map_app, apply_plan_app.\n    change (map _ tr) with (trace_to_plan tr).\n    specialize (apply_plan_last s (trace_to_plan tr)) as Hlst.\n    destruct (apply_plan s (trace_to_plan tr))\n      as (sitems,afinal) eqn:Hapl.\n    simpl in *. subst.\n    unfold _transition_item_to_plan_item, apply_plan, _apply_plan.\n    simpl.\n    replace (vtransition X l _) with (sf,oom) by (symmetry;apply Hx).\n    reflexivity.\n  Qed.\n\n  (** The plan extracted from a protocol trace is protocol w.r.t. the starting\n  state of the trace.\n  *)\n  Lemma finite_protocol_trace_from_to_plan\n    (s : vstate X)\n    (tr : list (vtransition_item X))\n    (Htr : finite_protocol_trace_from X s tr)\n    : finite_protocol_plan_from s (trace_to_plan tr).\n  Proof.\n    unfold finite_protocol_plan_from.\n    rewrite trace_to_plan_to_trace; assumption.\n  Qed.\n\n  (** Characterization of protocol plans. *)\n  Lemma finite_protocol_plan_iff\n    (s : vstate X)\n    (a : plan)\n    : finite_protocol_plan_from s a\n    <-> protocol_state_prop X s\n    /\\ Forall (fun ai => option_protocol_message_prop X (input_a ai)) a\n    /\\ forall\n        (prefa suffa : plan)\n        (ai : plan_item)\n        (Heqa : a = prefa ++ [ai] ++ suffa)\n        (lst := snd (apply_plan s prefa)),\n        vvalid X (label_a ai) (lst, input_a ai).\n  Proof.\n    induction a using rev_ind; repeat split; intros\n    ; try\n      ( apply finite_protocol_plan_from_app_iff in H\n      ; destruct H as [Ha Hx]; apply IHa in Ha as Ha').\n    - inversion H. assumption.\n    - constructor.\n    - destruct prefa; simpl in Heqa; discriminate Heqa.\n    - destruct H as [Hs _]. constructor. assumption.\n    - destruct Ha' as [Hs _].\n      assumption.\n    - destruct Ha' as [_ [Hmsgs _]].\n      apply Forall_app. split; try assumption.\n      repeat constructor. unfold finite_protocol_plan_from in Hx.\n      remember (snd (apply_plan s a)) as lst.\n      unfold apply_plan, _apply_plan in Hx. simpl in Hx.\n      destruct x.\n      destruct ( vtransition X label_a0 (lst, input_a0)) as (dest, out).\n      simpl. simpl in Hx. inversion Hx. subst.\n      destruct H6 as [[_ [Hom _]] _]. assumption.\n    - assert (Hsuffa : suffa = [] \\/ suffa <> []) by\n        (destruct suffa; try (left; congruence); right; congruence).\n      destruct Hsuffa.\n      + subst. rewrite app_assoc in Heqa. rewrite app_nil_r in Heqa.\n        apply app_inj_tail in Heqa. destruct Heqa; subst.\n        unfold lst. clear lst.\n        remember (snd (apply_plan s prefa)) as lst.\n        unfold finite_protocol_plan_from in Hx.\n        unfold apply_plan,_apply_plan in Hx. simpl in Hx.\n        destruct ai.\n        destruct ( vtransition X label_a0 (lst, input_a0)) as (dest, out).\n        simpl. simpl in Hx. inversion Hx. subst.\n        destruct H6 as [[_ [_ Hv]] _]. assumption.\n      + apply exists_last in H. destruct H as [suffa' [x' Heq]]. subst.\n        repeat rewrite app_assoc in Heqa.\n        apply app_inj_tail in Heqa. rewrite <- app_assoc in Heqa. destruct Heqa; subst.\n        destruct Ha' as [_ [_ Ha']].\n        specialize (Ha' _ _ _ eq_refl). assumption.\n    - destruct H as [Hs [Hinput Hvalid]].\n      apply Forall_app in Hinput. destruct Hinput as [Hinput Hinput_ai].\n      apply finite_protocol_plan_from_app_iff.\n      assert (Ha : finite_protocol_plan_from s a); try (split; try assumption)\n      ; try apply IHa; repeat split; try assumption.\n      + intros.\n        specialize (Hvalid prefa (suffa ++ [x]) ai).\n        repeat rewrite app_assoc in *.\n        subst a.\n        specialize (Hvalid eq_refl). assumption.\n      + unfold finite_protocol_plan_from.\n        specialize (Hvalid a [] x).\n        rewrite app_assoc in Hvalid. rewrite app_nil_r in Hvalid.\n        specialize (Hvalid eq_refl).\n        remember (snd (apply_plan s a)) as sa.\n        unfold apply_plan, _apply_plan. simpl.\n        destruct x.\n        destruct (vtransition X label_a0 (sa, input_a0)) as (dest, out) eqn:Ht.\n        simpl.\n        apply Forall_inv in Hinput_ai. simpl in Hinput_ai.\n        unfold finite_protocol_plan_from in Ha.\n        apply finite_ptrace_last_pstate in Ha.\n        specialize (apply_plan_last s a) as Hlst.\n        simpl in Hlst, Ha.\n        setoid_rewrite Hlst in Ha. setoid_rewrite <- Heqsa in Ha.\n        repeat constructor; try assumption.\n        exists out.\n        replace (@pair (@state message (@type message X)) (option message) dest out)\n          with (vtransition X label_a0 (sa, input_a0)).\n        destruct Ha as [_oma Hsa].\n        destruct Hinput_ai as [_s Hinput_a0].\n        apply protocol_generated with _oma _s; assumption.\n  Qed.\n\n  (** Characterizing a singleton protocol plan as a protocol transition. *)\n  Lemma finite_protocol_plan_from_one\n    (s : vstate X)\n    (a : plan_item) :\n    let res := vtransition X (label_a a) (s, input_a a) in\n    finite_protocol_plan_from s [a] <-> protocol_transition X (label_a a) (s, input_a a) res.\n  Proof.\n    split;\n    intros;\n    destruct a;\n    unfold apply_plan,_apply_plan in *; simpl in *;\n    unfold finite_protocol_plan_from in *;\n    unfold apply_plan, _apply_plan in *; simpl in *.\n    - match type of H with\n      | context[let (_, _) := let (_, _) := ?t in _ in _] =>\n        destruct t as [dest output] eqn : eq_trans\n      end.\n      inversion H. subst. setoid_rewrite eq_trans.\n      assumption.\n    - match type of H with\n      | protocol_transition _ _ _ ?t =>\n        destruct t as [dest output] eqn : eq_trans\n      end.\n      setoid_rewrite eq_trans.\n      apply finite_ptrace_extend.\n      apply finite_ptrace_empty.\n      apply protocol_transition_destination in H; intuition.\n      assumption.\n  Qed.\n\n  Definition preserves\n    (a : plan)\n    (P : vstate X -> Prop) :\n    Prop :=\n    forall (s : vstate X),\n    (P s -> protocol_state_prop X s -> finite_protocol_plan_from s a -> P (snd (apply_plan s a))).\n\n  Definition ensures\n    (a : plan)\n    (P : vstate X -> Prop) :\n    Prop :=\n    forall (s : vstate X),\n    (protocol_state_prop X s -> P s -> finite_protocol_plan_from s a).\n\n   (* If some property of a state guarantees a plan `b` applied to the state is protocol,\n      and this property is preserved by the application of some other plan `a`,\n      then these two plans can be composed and the application of `a ++ b` will also\n      be protocol. *)\n\n   Lemma plan_independence\n    (a b : plan)\n    (Pb : vstate X -> Prop)\n    (s : state)\n    (Hpr : protocol_state_prop X s)\n    (Ha : finite_protocol_plan_from s a)\n    (Hhave : Pb s)\n    (Hensures : ensures b Pb)\n    (Hpreserves : preserves a Pb) :\n   finite_protocol_plan_from s (a ++ b).\n   Proof.\n    unfold ensures in *.\n    unfold preserves in *.\n    apply finite_protocol_plan_from_app_iff.\n    split.\n    - assumption.\n    - remember (snd (apply_plan s a)) as s'.\n      specialize (Hensures s').\n      apply Hensures.\n      rewrite Heqs'.\n      apply apply_plan_last_protocol.\n      intuition.\n      intuition.\n      rewrite Heqs'.\n      apply Hpreserves.\n      all : intuition.\n   Qed.\n\nEnd protocol_plans.\n", "meta": {"author": "zunction", "repo": "casper-cbc-proofs", "sha": "92493810dd32a8301882f9eb8a0488a6ac9d0cd1", "save_path": "github-repos/coq/zunction-casper-cbc-proofs", "path": "github-repos/coq/zunction-casper-cbc-proofs/casper-cbc-proofs-92493810dd32a8301882f9eb8a0488a6ac9d0cd1/VLSM/Plans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23559260281945738}}
{"text": "Ltac remove_unrelevant_last_txn :=\n  repeat match goal with\n  | [H: context[trace_tid_last ?tid ((?tid0, _) :: ?t) = _] |-_] =>\n      unfold trace_tid_last in H; inversion H;\n      destruct (Nat.eq_dec tid tid0); subst\n  | [H: context[hd _\n       (map snd\n          (if ?tid0 =? ?tid0\n           then (?tid0, ?x) :: trace_filter_tid ?tid0 ?t\n           else trace_filter_tid ?tid0 ?t)) = ?y] |-_] =>\n      rewrite <- beq_nat_refl in H; simpl in H; inversion H\n  | [H: context[?tid <> ?tid0] |-_] =>\n      apply not_eq_sym in H; apply Nat.eqb_neq in H\nend.\n\nLemma seq_list_commit tid t:\n  sto_trace t -> \n  trace_tid_last tid t = seq_point\n  -> In tid (seq_list t).\nProof.\n  intros.\n  induction H; simpl; try discriminate.\n  1, 3, 4, 6-8, 10: remove_unrelevant_last_txn; rewrite n in H3; apply IHsto_trace in H3; auto.\n  1, 2: remove_unrelevant_last_txn; rewrite n in H4; apply IHsto_trace in H4; auto.\n  remove_unrelevant_last_txn.\n  apply in_or_app. right. simpl. auto.\n  remove_unrelevant_last_txn.\n  rewrite n in H4. \n  apply IHsto_trace in H4. \n  apply in_or_app. left. auto.\nQed.\n\nLemma trace_seqlist_seqpoint t tid:\n  In (tid, seq_point) t\n  -> In tid (seq_list t).\nProof.\n  intros.\n  functional induction seq_list t.\n  inversion H.\n  destruct (Nat.eq_dec tid tid0); subst; apply in_or_app. \n  right. simpl. auto.\n  left. apply IHl. apply in_inv in H. destruct H.\n  inversion H. apply Nat.eq_sym in H1. contradiction. auto.\n  all: destruct (Nat.eq_dec tid tid0); subst; apply IHl; apply in_inv in H; destruct H; try inversion H; auto.\nQed.\n\nLemma seq_list_no_two_seqpoint t tid:\n  sto_trace ((tid, seq_point) :: t)\n  -> ~ In (tid, seq_point) t.\nProof.\n  intros.\n  assert (sto_trace t). { apply sto_trace_app with (tid0 := tid) (action0 := seq_point). auto. }\n  inversion H.\n  intuition.\n\n  all: unfold trace_no_seq_points in H4; apply in_split in H6;\n  destruct H6; destruct H6;\n  rewrite H6 in H4; simpl in H4;\n  rewrite trace_filter_tid_app in H4;\n  simpl in H4;\n  rewrite <-beq_nat_refl in H4;\n  rewrite map_app in H4;\n  rewrite Forall_app in H4;\n  destruct H4; simpl in H7;\n  apply Forall_inv in H7; simpl in H7; auto.\nQed.\n", "meta": {"author": "michael-hahn", "repo": "sto_coq", "sha": "fa2c572d8b358db9488962d7df115485bacd04d4", "save_path": "github-repos/coq/michael-hahn-sto_coq", "path": "github-repos/coq/michael-hahn-sto_coq/sto_coq-fa2c572d8b358db9488962d7df115485bacd04d4/ltac.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.23559259640015465}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        Coq.Strings.String\n        Coq.Arith.Mult\n        Coq.Vectors.Vector.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Common.BoundedLookup\n        Fiat.Common.ilist\n        Fiat.Common.DecideableEnsembles\n        Fiat.Common.IterateBoundedIndex\n        Fiat.Common.Tactics.CacheStringConstant\n        Fiat.Computation\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Formats.WordOpt\n        Fiat.Narcissus.Formats.NatOpt\n        Fiat.Narcissus.Formats.StringOpt\n        Fiat.Narcissus.Formats.EnumOpt\n        Fiat.Narcissus.Formats.FixListOpt\n        Fiat.Narcissus.Formats.SumTypeOpt\n        Fiat.Narcissus.Formats.DomainNameOpt\n        Fiat.Narcissus.Formats.Vector\n        Fiat.Narcissus.BinLib.AlignedByteString\n        Fiat.Narcissus.BinLib.AlignWord\n        Fiat.Narcissus.BinLib.AlignedDecoders\n        Fiat.Narcissus.BinLib.AlignedEncodeMonad\n        Fiat.Narcissus.BinLib.AlignedDecodeMonad\n        Fiat.Narcissus.BinLib.AlignedList\n        Fiat.Narcissus.BaseFormats.\n\nRequire Import\n        Bedrock.Word.\n\nSection AlignedList.\n\n  Context {cache : Cache}.\n  Context {cacheAddNat : CacheAdd cache nat}.\n\n  Definition bytebuffer_of_bytebuffer_range {sz: nat} (from: nat) (len: nat) (v: ByteBuffer.t sz) : { n : _ & ByteBuffer.t n } :=\n    let l := List.firstn len (List.skipn from (Vector.to_list v)) in\n    existT ByteBuffer.t _ (Vector.of_list l).\n\n  Definition ByteBufferAlignedDecodeM {m : nat} (len: nat) : @AlignedDecodeM cache {n : _ & ByteBuffer.t n} m :=\n    fun (v: ByteBuffer.t m) idx env =>\n      let lastidx := idx + len in\n      if Coq.Init.Nat.leb lastidx m then\n        Some ((bytebuffer_of_bytebuffer_range idx len v, lastidx, addD env (8 * len)))\n      else\n        None.\n\n  Variable addD_addD_plus :\n    forall (ce : CacheDecode) (n m : nat), addD (addD ce n) m = addD ce (n + m).\n  Variable addD_0 :\n    forall ce, addD ce 0 = ce.\n\n  Lemma nth_opt_some\n    : forall sz (v : ByteBuffer.t sz) idx,\n      lt idx sz\n      -> exists b, nth_opt v idx = Some b.\n  Proof.\n    induction v; simpl; intros.\n    - inversion H.\n    - destruct idx; simpl.\n      + unfold nth_opt; simpl; eauto.\n      + apply_in_hyp lt_S_n.\n        unfold nth_opt; simpl; eauto.\n  Qed.\n\n  Lemma nth_opt_None\n    : forall sz (v : ByteBuffer.t sz) idx,\n      le sz idx\n      -> nth_opt v idx = None.\n  Proof.\n    induction v; simpl; intros.\n    - destruct idx; simpl; try reflexivity.\n    - inversion H; subst.\n      + eapply IHv; eauto.\n      + eapply IHv; Omega.omega.\n  Qed.\n\n  Lemma AlignedDecodeByteBufferM {C : Type}\n        (n : nat)\n    : forall (t : { n : _ & ByteBuffer.t n } -> DecodeM (C * _) ByteString)\n        (t' : { n : _ & ByteBuffer.t n } -> forall {numBytes}, AlignedDecodeM C numBytes),\n      (forall b, DecodeMEquivAlignedDecodeM (t b) (@t' b))\n      -> DecodeMEquivAlignedDecodeM\n          (fun v cd => `(b, bs, cd') <- decode_bytebuffer n v cd;\n                      t b bs cd')\n          (fun numBytes => b <- ByteBufferAlignedDecodeM n;\n                          t' b)%AlignedDecodeM%list.\n  Proof.\n    intros.\n    eapply DecodeMEquivAlignedDecodeM_trans with\n        (bit_decoder1 := (fun v cd => `(l, bs, cd') <- decode_list decode_word n v cd;\n                                      t (existT ByteBuffer.t _ (ByteBuffer.of_list l)) bs cd'))\n        (byte_decoder1 := (fun numBytes => l <- ListAlignedDecodeM (fun numBytes : nat => GetCurrentByte) n;\n                                           fun v idx cd =>\n                                             if (Coq.Init.Nat.leb idx numBytes) then\n                                               t' (existT ByteBuffer.t _ (ByteBuffer.of_list l)) _ v idx cd\n                                             else None\n                          )%AlignedDecodeM%list).\n    - eapply AlignedDecodeListM; eauto using AlignedDecodeCharM.\n      intros; repeat (eapply conj; intros).\n      + simpl; destruct (Coq.Init.Nat.leb n0 (numBytes_hd)) eqn: ? ;\n          repeat apply_in_hyp Compare_dec.leb_complete;\n          repeat apply_in_hyp Compare_dec.leb_complete_conv;\n          try Omega.omega; simpl; eauto.\n        pattern numBytes_hd, v; apply caseS; simpl; intros.\n        rewrite (proj1 (H _)); reflexivity.\n      + eapply H in H0; eauto.\n      + rewrite (proj1 (proj2 (proj2 (H _)) _ _ _)) in H0; rewrite H0;\n          find_if_inside; reflexivity.\n      + destruct (Coq.Init.Nat.leb 0 n0) eqn: ? ;\n        repeat apply_in_hyp Compare_dec.leb_complete;\n          repeat apply_in_hyp Compare_dec.leb_complete_conv;\n          try Omega.omega; simpl; eauto.\n        apply (proj2 (proj2 (H _)) _ _ _) in H0; eauto.\n      + destruct (Coq.Init.Nat.leb 0 n0) eqn: ? ;\n        repeat apply_in_hyp Compare_dec.leb_complete;\n          repeat apply_in_hyp Compare_dec.leb_complete_conv;\n          try Omega.omega; simpl; eauto.\n        eapply H; eauto.\n      + eapply H; eauto.\n    - clear t' H; revert t; induction n; simpl; intros.\n      + reflexivity.\n      + unfold decode_bytebuffer.\n        destruct (decode_Vector decode_word (S n) b cd) as [ [ [? ?] ? ] | ] eqn: ?; simpl.\n        * unfold decode_Vector in Heqo.\n          destruct (decode_word b cd) as [ [ [? ?] ?]  | ]; simpl in *; eauto; try discriminate.\n          fold (decode_Vector (decode_word (sz := 8)) n b1 c0) in Heqo.\n          rewrite DecodeBindOpt2_assoc; simpl.\n          erewrite IHn with (t := fun l => t (existT ByteBuffer.t _ (ByteBuffer.cons w (projT2 l)))).\n          unfold decode_bytebuffer.\n          destruct (decode_Vector decode_word n b1 c0) as [ [ [? ?] ?]  | ]; simpl in *; eauto; try discriminate.\n          injections.\n          reflexivity.\n        * unfold decode_Vector in Heqo.\n          destruct (decode_word b cd) as [ [ [? ?] ?]  | ]; simpl in *; eauto; try discriminate.\n          fold (decode_Vector (decode_word (sz := 8)) n b0 c) in Heqo.\n          rewrite DecodeBindOpt2_assoc; simpl.\n          erewrite IHn with (t := fun l => t (existT ByteBuffer.t _ (ByteBuffer.cons w (projT2 l)))).\n          unfold decode_bytebuffer.\n          destruct (decode_Vector decode_word n b0 c) as [ [ [? ?] ?]  | ]; simpl in *; eauto; try discriminate.\n    - intros n0 v idx; generalize t'; revert addD_addD_plus addD_0 n0 idx v. clear; induction n; simpl; intros.\n      + eapply AlignedDecodeMEquiv_trans. eapply ReturnAlignedDecodeM_LeftUnit.\n        unfold AlignedDecodeMEquiv, ByteBufferAlignedDecodeM, BindAlignedDecodeM; simpl; intros.\n        rewrite <- plus_n_O; find_if_inside; simpl; eauto.\n        unfold bytebuffer_of_bytebuffer_range; simpl.\n        simpl; rewrite addD_0; reflexivity.\n      + eapply AlignedDecodeMEquiv_trans.\n        eapply BindAlignedDecodeM_assoc.\n        eapply AlignedDecodeMEquiv_trans.\n        { instantiate (1 := (a <- GetCurrentByte;\n                             l <- ListAlignedDecodeM (fun numBytes : nat => GetCurrentByte) n;\n                             (fun (v0 : ByteBuffer.t n0) (idx0 : nat) (cd : CacheDecode) =>\n                                if Coq.Init.Nat.leb idx0 n0\n                                then t' (existT ByteBuffer.t (| (a :: l) |) (ByteBuffer.of_list (a :: l))) n0 v0 idx0 cd\n                                else None))%AlignedDecodeM).\n          intros ? ? ?; f_equal; apply functional_extensionality; intros.\n          unfold AlignedDecodeMEquiv, ByteBufferAlignedDecodeM, BindAlignedDecodeM in *; simpl in *; intros.\n          repeat (apply functional_extensionality; intros).\n          destruct (ListAlignedDecodeM (fun numBytes : nat => GetCurrentByte) n x0 x1 x2); simpl; eauto.\n        }\n        unfold AlignedDecodeMEquiv, ByteBufferAlignedDecodeM, BindAlignedDecodeM in *; simpl in *; intros.\n        unfold GetCurrentByte at 1.\n        destruct (Coq.Init.Nat.leb (idx0 + S n) n0) as [ | ] eqn: ?; simpl;\n          repeat apply_in_hyp Compare_dec.leb_complete;\n          repeat apply_in_hyp Compare_dec.leb_complete_conv;\n          try Omega.omega; simpl; eauto.\n        * destruct (nth_opt_some _ v0 idx0); try Omega.omega;\n            rewrite H; simpl.\n          pose proof (fun t' => IHn addD_addD_plus addD_0 _ (S idx0) v0 t' (addD c0 8)).\n          rewrite (Compare_dec.leb_correct (S idx0 + n) n0) in H0 by Omega.omega;\n            simpl in H0.\n          pose proof (H0 (fun n => t' (existT ByteBuffer.t (S (projT1 n)) (Vector.cons _ x _ (projT2 n))))).\n          cbv beta in H1.\n          simpl projT1 at 1 in H1; simpl projT2 at 1 in H1.\n          simpl projT1 at 1 in H1.\n          unfold ByteBuffer.of_list in *; simpl.\n          revert Heqb H.\n          rewrite H1, addD_addD_plus; clear; intros.\n          unfold bytebuffer_of_bytebuffer_range.\n          unfold projT1; unfold projT2.\n          f_equal; eauto.\n          2: f_equal; Omega.omega.\n          replace ((skipn idx0 (to_list v0))) with (x :: (skipn (S idx0) (to_list v0)));\n            auto.\n          generalize n0 v0 H; clear.\n          induction idx0; destruct v0; intros.\n          -- compute in H; discriminate.\n          -- compute in H; injections; reflexivity.\n          -- compute in H; discriminate.\n          -- unfold nth_opt in H; simpl in H;\n               apply_in_hyp IHidx0.\n             unfold to_list at 1; fold (@to_list _ n v0).\n             replace (skipn (S (S idx0)) (h :: to_list v0)) with\n                 (skipn (S idx0) (to_list v0)) by reflexivity.\n             rewrite H; reflexivity.\n        * destruct (nth_opt v0 idx0); simpl; eauto.\n          assert (Coq.Init.Nat.leb (S idx0 + n) n0 = false)\n            by (apply Compare_dec.leb_correct_conv; Omega.omega).\n          pose proof (fun t' => IHn addD_addD_plus addD_0 _ (S idx0) v0 t' (addD c0 8)).\n          rewrite H in H0; simpl in H0.\n          pose proof (H0 (fun n => t' (existT ByteBuffer.t (S (projT1 n)) (Vector.cons _ c1 _ (projT2 n))))).\n          erewrite <- H1 at -1.\n          f_equal; apply functional_extensionality; intro.\n  Qed.\n\n  Fixpoint buffer_blit_buffer' {sz1 sz2} start (src: ByteBuffer.t sz1) (dst: ByteBuffer.t sz2) :=\n    match src with\n    | Vector.nil => dst\n    | Vector.cons h _ t => buffer_blit_buffer' (S start) t (set_nth' dst start h)\n    end.\n\n  Definition buffer_blit_buffer {sz1 sz2} start (src: ByteBuffer.t sz1) (dst: ByteBuffer.t sz2) :=\n    let idx' := start + sz1 in\n    if Coq.Init.Nat.leb idx' sz2 then\n      Some (buffer_blit_buffer' start src dst, idx')\n    else None.\n\n  Definition AlignedEncodeByteBuffer\n    : forall sz, AlignedEncodeM (S := { n : _ & ByteBuffer.t n }) sz :=\n    fun sz2 (dst: ByteBuffer.t sz2) idx src env =>\n      let '(existT len src) := src in\n      match buffer_blit_buffer idx src dst with\n      | Some (v', idx') => Some (v', idx', addE env (8 * len))\n      | None => None\n      end.\n\n  Variable addE_addE_plus :\n    forall (ce : CacheFormat) (n m : nat), addE (addE ce n) m = addE ce (n + m).\n  Variable addE_0 :\n    forall ce, addE ce 0 = ce.\n\n  Lemma CorrectAlignedEncoderForFormatByteBuffer\n    (encode_word_OK : forall (a : word (1 * 8)) (l : list (word (1 * 8))) (env : CacheFormat)\n              (tenv' tenv'' : ByteString * CacheFormat),\n            format_word a env ∋ tenv' ->\n            format_list format_word l (snd tenv') ∋ tenv'' ->\n            exists tenv3 tenv4 : ByteString * CacheFormat,\n              projT1 (CorrectAlignedEncoderForFormatNChar addE_addE_plus addE_0) a env = Some tenv3 /\\\n              format_list format_word l (snd tenv3) ∋ tenv4)\n    : CorrectAlignedEncoder format_bytebuffer AlignedEncodeByteBuffer.\n  Proof.\n    eapply refine_CorrectAlignedEncoder\n      with (format' := fun s env => format_list format_word (ByteBuffer.to_list (projT2 s)) env);\n      [ | eapply CorrectAlignedEncoder_morphism with\n              (encode := fun sz v idx w c => AlignedEncodeList (@SetCurrentByte _ _) sz v idx (ByteBuffer.to_list (projT2 w)) c)].\n    - intros [? ?]; clear; split.\n      + revert env; induction t; simpl; intros.\n        * reflexivity.\n        * unfold format_bytebuffer in *; simpl in *; apply refine_under_bind; intros.\n          unfold Bind2; rewrite IHt; reflexivity.\n      + unfold format_bytebuffer, Bind2 in *.\n        intros; intro; eapply (H v).\n        clear H; revert env v H0; induction t; simpl; intros.\n        * eapply H0.\n        * unfold Bind2 in *.\n          computes_to_inv.\n          computes_to_econstructor; eauto.\n          computes_to_econstructor; eauto.\n          rewrite H0''; eauto.\n    - apply EquivFormat_reflexive.\n    - intros ? ? ? [n t]; revert sz v idx; induction t.\n      + simpl; intros.\n        unfold buffer_blit_buffer.\n        destruct (Coq.Init.Nat.leb (idx + 0) sz) eqn: ?; intros.\n        * eapply PeanoNat.Nat.leb_le in Heqb.\n          rewrite (proj2 (PeanoNat.Nat.ltb_lt idx (S sz))) by Omega.omega.\n          unfold ReturnAlignedEncodeM.\n          simpl. rewrite <- (addE_0 c) at 2.\n          simpl; repeat f_equal; try Omega.omega.\n        * eapply PeanoNat.Nat.leb_gt in Heqb.\n          rewrite (proj2 (PeanoNat.Nat.ltb_ge idx (S sz))) by Omega.omega.\n          reflexivity.\n      + simpl; intros.\n        unfold buffer_blit_buffer.\n        destruct (Coq.Init.Nat.leb (idx + (S n)) sz) eqn: ?; intros.\n        * eapply PeanoNat.Nat.leb_le in Heqb.\n          unfold SetCurrentByte at 1.\n          rewrite (proj2 (PeanoNat.Nat.ltb_lt idx sz)) by Omega.omega; simpl.\n          rewrite <- IHt.\n          simpl.\n          unfold buffer_blit_buffer.\n          destruct (Coq.Init.Nat.leb (S idx + n) sz) eqn: ?; intros.\n          eapply PeanoNat.Nat.leb_le in Heqb0; simpl;\n            rewrite addE_addE_plus; repeat (f_equal; try Omega.omega).\n          eapply PeanoNat.Nat.leb_gt in Heqb0; Omega.omega.\n        * eapply PeanoNat.Nat.leb_gt in Heqb.\n          unfold SetCurrentByte at 1.\n          destruct (PeanoNat.Nat.ltb idx sz) eqn: ? ; simpl; auto.\n          rewrite <- IHt.\n          unfold AlignedEncodeByteBuffer, buffer_blit_buffer.\n          destruct (Coq.Init.Nat.leb (S idx + n) sz) eqn: ? ; simpl; auto.\n          eapply PeanoNat.Nat.leb_le in Heqb0;\n            eapply PeanoNat.Nat.leb_le in Heqb1; Omega.omega.\n    - eexists (fun s env => _); repeat apply conj; intros;\n        try eapply ((projT2 (CorrectAlignedEncoderForFormatList\n                               _ _\n                               (CorrectAlignedEncoderForFormatNChar (sz := 1) addE_addE_plus addE_0) encode_word_OK))); eauto.\n      pose proof (proj2 (proj2 ((projT2 (CorrectAlignedEncoderForFormatList\n                                           _ _\n                                           (CorrectAlignedEncoderForFormatNChar (sz := 1) addE_addE_plus addE_0) encode_word_OK))))).\n      unfold EncodeMEquivAlignedEncodeM in *; intros ? [? ?] ?; simpl in *.\n      intuition.\n      eapply H; eauto.\n      eapply (proj1 (proj2 (H _ _ _))); eauto.\n      eapply (proj1 (proj2 (proj2 (H _ _ _)))); eauto.\n      eapply (proj2 (proj2 (proj2 (H _ _ _)))); eauto.\n  Qed.\n\nEnd AlignedList.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Narcissus/BinLib/AlignedByteBuffer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.23558081502983785}}
{"text": "From ITree Require Import ITree.\nFrom SimpleIO Require Import SimpleIO.\n\n#[global]\nInstance MonadIter_IO : MonadIter IO :=\n  fun _ _ f =>\n    IO.fix_io (fun self x =>\n      IO.bind (f x) (fun y =>\n      match y with\n      | inl x' => self x'\n      | inr r => IO.ret r\n      end)).\n\n(** Interpret [itree E] into [IO] given an interpreter of [E].\n    This is literally a specialization of [interp]. *)\nDefinition interp_io {E} : (E ~> IO) -> (itree E ~> IO) :=\n  interp.\nArguments interp_io {E} h [T] t.\n\n(** Interpret [itree IO] into [IO]. *)\nDefinition interp_io' : itree IO ~> IO :=\n  interp (E := IO) (M := IO) (fun T (e : IO T) => e).\nArguments interp_io' [T] t.\n\n(** Interpret [itree void1] into [IO]. *)\nDefinition interp_io_ : itree void1 ~> IO :=\n  interp (M := IO) (elim_void1 (E := IO)).\nArguments interp_io_ [T] t.\n", "meta": {"author": "Lysxia", "repo": "coq-itree-io", "sha": "6c52b7d9ff4bdacac85bdb4024913b621b15ebe9", "save_path": "github-repos/coq/Lysxia-coq-itree-io", "path": "github-repos/coq/Lysxia-coq-itree-io/coq-itree-io-6c52b7d9ff4bdacac85bdb4024913b621b15ebe9/src/ITreeIO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2354791944714021}}
{"text": "(* Disable notation conflict warnings *)\nSet Warnings \"-notation-overridden\".\n\nFrom mathcomp.ssreflect\nRequire Import ssreflect ssrnat prime ssrbool eqtype.\n\nRequire Import Core.\nRequire Import FV.\nRequire Import Proofs.Axioms.\nRequire Import Proofs.ContainerProofs.\nRequire Import Proofs.VarSet.\nRequire Import Proofs.VarSetFSet.\nRequire Import Proofs.Var.\n\nRequire Import Coq.Lists.List.\nRequire Import Coq.Bool.Bool.\n\nRequire Import GHC.Base.\nRequire Import Proofs.Prelude.\nImport GHC.Base.ManualNotations.\n\nRequire Import Coq.Classes.Morphisms.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n\n(** * Well-formedness of [FV]s. *)\n\n(* A FV is well formed when it is denoted by some VarSet vs. *)\n\n\nLemma RespectsVar_const_true : RespectsVar (const true).\nProof. move => x1 x2 Eq. reflexivity. Qed.\nHint Resolve RespectsVar_const_true.\nLemma RespectsVar_andb f0 f: \n  RespectsVar f0 -> RespectsVar f ->\n  RespectsVar (fun v : Var => f0 v && f v).\nProof.\n  move => r1 r2 x1 x2 Eq.\n  erewrite r1; eauto. \n  erewrite r2; eauto.\nQed.\n\nReserved Notation \"A ⊢ B\" (at level 70, no associativity).\n\nInductive Denotes : VarSet -> FV -> Prop :=\n| DenotesVarSet : forall vs fv,\n    (forall f in_scope vs' l,\n        RespectsVar f ->\n        extendVarSetList emptyVarSet l [=] vs' ->\n        extendVarSetList emptyVarSet (fst (fv f in_scope (l, vs'))) [=]\n        Tuple.snd (fv f in_scope (l, vs')) /\\\n        Tuple.snd (fv f in_scope (l, vs')) [=]\n        unionVarSet (minusVarSet (filterVarSet f vs) in_scope) vs') ->\n    vs ⊢ fv\nwhere \"A ⊢ B\" := (Denotes A B).\n\n\nTheorem Denotes_fvVarSet : forall m fv f in_scope l vs,\n    m ⊢ fv ->\n    RespectsVar f ->\n    extendVarSetList emptyVarSet l [=] vs ->\n    Tuple.snd (fv f in_scope (l, vs)) [=]\n    unionVarSet (minusVarSet (filterVarSet f m) in_scope) vs.\nProof.\n  move => m fv f in_scope l vs [vs' fv' H0] H1 H2.\n  specialize (H0 f in_scope vs l H1 H2); subst.\n  destruct fv'.\n  move: H0 => [h0 h1].\n  auto.\nQed.\n\n\nLemma Denotes_Equal vs1 vs2 f : vs1 [=] vs2 -> Denotes vs1 f -> Denotes vs2 f.\nProof.\n  move => Eqx.\n  move=> h. inversion h. subst.\n  constructor.\n  move => f0 in_scope vs' l RV EX.\n  specialize (H f0 in_scope vs' l RV EX).\n  move: H => [h0 h1].\n  split. done.\n  rewrite h1.\n  f_equiv.\n  f_equiv.\n  apply filterVarSet_equal; eauto.\nQed.\n\nRequire Import Coq.Classes.Morphisms.\nInstance Denotes_m : Proper (Equal ==> Logic.eq ==> iff) Denotes.\nProof.\n  move=> vs1 vs2 EqV f0 f EqF. rewrite EqF.\n  split; apply Denotes_Equal; try done.\n  symmetry. auto.\nQed.\n\n\nDefinition WF_fv (fv : FV) : Prop := exists vs, vs ⊢ fv.\n      \nLtac unfold_WF :=\n  repeat match goal with\n  | [ H : WF_fv ?fv |- _] =>\n    let vs := fresh \"vs\" in\n    let Hd := fresh \"Hdenotes\" in\n    inversion H as [vs Hd]; inversion Hd; subst; clear H\n  | [ |- WF_fv ?fv ] =>\n    unfold WF_fv\n  end.\n\n\n(* We show that the various operations on FVs produce well-formed FVs. *)\n\nLemma emptyVarSet_emptyFV : Denotes emptyVarSet emptyFV.\nProof.\n  constructor; intros; subst.\n  unfold emptyFV.\n  unfold Tuple.fst, Tuple.snd.\n  hs_simpl.\n  split; auto.\n  reflexivity.\nQed.\n\nLemma empty_FV_WF :\n  WF_fv emptyFV.\nProof.\n  unfold WF_fv. exists emptyVarSet. eapply emptyVarSet_emptyFV. \nQed.\n\n\nLemma unitVarSet_unitFV x : Denotes (unitVarSet x) (unitFV x).\nProof.\n  constructor; intros; subst. \n  unfold fst, snd.\n  unfold unitFV.\n  destruct elemVarSet eqn:E1;\n  destruct (f x) eqn:FX;\n  hs_simpl; split; auto.\n  - rewrite -> filterSingletonTrue; try done.\n    rewrite elemVarSet_minusVarSetTrue; try done.\n    hs_simpl.\n    reflexivity.\n  - rewrite filterSingletonFalse; try done.\n    hs_simpl.\n    reflexivity.\n  - elim In: (elemVarSet x vs') => //.    \n    hs_simpl.\n    rewrite <- H0.\n    rewrite extendVarSetList_extendVarSet_iff.\n    reflexivity.\n  - rewrite filterSingletonTrue; try done.\n    rewrite elemVarSet_minusVarSetFalse; try done.\n    elim E2: (elemVarSet x vs').\n    hs_simpl.\n    set_b_iff.\n    rewrite add_equal; try done.\n    hs_simpl.\n    reflexivity.\n  - elim E2: (elemVarSet x vs'); done.\n  - rewrite filterSingletonFalse; try done.\n    hs_simpl.\n    elim E2: (elemVarSet x vs'); done.\nQed.\n\n\nLemma unit_FV_WF :\n  forall x, WF_fv (unitFV x).\nProof.\n  move=>x. unfold WF_fv.\n  exists (unitVarSet x).\n  eapply unitVarSet_unitFV.\nQed.\n\nLemma filterVarSet_filterFV f vs x :\n  Proper ((fun x0 y : Var => x0 == y) ==> Logic.eq) f ->\n  Denotes vs x -> Denotes (filterVarSet f vs) (filterFV f x).\nProof.\n  move => p D.\n  constructor. move=> f0 in_scope vs' l h0 h1.\n  inversion D.\n  unfold filterFV.\n  specialize (H (fun v : Var => f0 v && f v) in_scope vs' l ltac:(eauto using RespectsVar_andb)).\n  destruct H. auto. \n  rewrite H.\n  rewrite H2.\n  rewrite <- filterVarSet_comp. \n  split; reflexivity. \nQed.\n\n\nLemma filter_FV_WF : forall f x,\n    RespectsVar f ->\n    WF_fv x -> WF_fv (filterFV f x).\nProof.\n  intros. unfold_WF.\n  exists (filterVarSet f vs). \n  eapply filterVarSet_filterFV; auto.\nQed.\n\nLemma delVarSet_delFV vs v fv :\n  Denotes vs fv -> Denotes (delVarSet vs v) (delFV v fv).\nProof.\n  move=> H. inversion H.\n  constructor; intros. unfold delFV.\n  specialize (H0 f (extendVarSet in_scope v) vs' l H3 H4).\n  destruct H0. intuition. rewrite H5.\n  destruct (fv f (extendVarSet in_scope v)) as [l0 h0] eqn:h.\n  simpl in *.\n  apply union_equal_1.\n  move => x. \n  unfold VarSetFSet.In.\n  rewrite !elemVarSet_minusVarSet.\n  split.\n  - move=> /andP [h1 h2].\n    apply /andP.\n    hs_simpl in h2.\n    rewrite negb_or in h2.\n    move: h2 => /andP.\n    move => [h3 h4].\n    intuition.\n    rewrite elemVarSet_filterVarSet in h1 => //.\n    rewrite elemVarSet_filterVarSet => // .\n    apply /andP.\n    move: h1 => /andP [h1 h2].\n    rewrite elemVarSet_delVarSet.\n    split; auto.\n    apply /andP. split; auto.\n  - move=> /andP [h1 h2].\n    apply /andP.\n\n    rewrite elemVarSet_filterVarSet in h1 => //.\n    move: h1 => /andP. move => [h3 h4].\n    elim hf: (f x); rewrite hf in h3; try done; clear h3.\n    rewrite elemVarSet_delVarSet in h4.\n    induction (v GHC.Base.== x) eqn:ev.\n    + done. \n    + move: h4 => /andP. move => [h5 h6].\n      rewrite elemVarSet_filterVarSet => //.\n      rewrite elemVarSet_extendVarSet.\n      rewrite hf.\n      rewrite ev.\n      rewrite h6.\n      done.\nQed.\n\n\nLemma del_FV_WF : forall fv v,\n    WF_fv fv -> WF_fv (delFV v fv).\nProof.\n  intros. unfold_WF.\n  exists (delVarSet vs v). \n  eapply delVarSet_delFV. auto.\nQed.\n\nLemma unionVarSet_unionFV vs vs' fv fv' :\n  Denotes vs fv -> Denotes vs' fv' -> Denotes (unionVarSet vs vs') (unionFV fv' fv).\nProof.\n  move=> H H1. inversion H. inversion H1. subst.\n  constructor.\n  move=> f in_scope vs1 l h h0.\n  unfold unionFV.\n  specialize (H0 f in_scope vs1 l h h0).  move: H0 => [h1 h2].\n  remember (fv f in_scope (l, vs1)) as vs_mid.\n  specialize (H4 f in_scope (Tuple.snd vs_mid) (Tuple.fst vs_mid) h h1); move: H4 => [h3 h4].\n  replace vs_mid with (Tuple.fst vs_mid, Tuple.snd vs_mid); [| destruct vs_mid; reflexivity].\n  intuition.\n  remember (fv' f in_scope (Tuple.fst vs_mid, Tuple.snd vs_mid)) as vs_fin.\n  rewrite h4.\n  rewrite h2.\n  rewrite <- union_assoc.\n  apply union_equal_1.\n  rewrite -> unionVarSet_minusVarSet.\n  rewrite unionVarSet_filterVarSet => //.\n  f_equiv.\n  apply filterVarSet_equal; try done.\n  set_b_iff. rewrite union_sym.\n  reflexivity. \nQed.\n\nLemma union_FV_WF : forall fv fv',\n    WF_fv fv -> WF_fv fv' -> WF_fv (unionFV fv fv').\nProof.\n  intros. unfold_WF.\n  exists (unionVarSet vs vs0). \n  eapply unionVarSet_unionFV; eauto.\nQed.  \n\nLemma mapUnionFV_nil A f : \n  mapUnionFV f (nil : list A) = emptyFV.\nProof.\n  simpl.\n  unfold emptyFV.\n  reflexivity.\nQed. \nHint Rewrite mapUnionFV_nil : hs_simpl. \n\nLemma mapUnionFV_cons A f (x : A) xs : \n  mapUnionFV f (x :: xs) = unionFV (mapUnionFV f xs) (f x).\nProof.\n  simpl.\n  unfold unionFV.\n  reflexivity.\nQed.\nHint Rewrite mapUnionFV_cons : hs_simpl. \n\n\nLemma map_union_FV_WF : forall A f (ls : list A),\n    (forall e, In e ls -> WF_fv (f e)) ->\n    WF_fv (mapUnionFV f ls).\nProof.\n  induction ls.\n  - intros.\n    exists emptyVarSet.\n    hs_simpl.\n    eapply emptyVarSet_emptyFV.\n  -  move=> h. simpl in h.\n    assert (h0 : forall e : A, In e ls -> WF_fv (f e)). { intros. apply h. tauto. }\n    apply IHls in h0.\n    assert (WF_fv (f a)). { apply h; tauto. }\n    hs_simpl.\n    move: h0 => [vs D].\n    move: H => [vs' D'].\n    eexists.\n    eapply unionVarSet_unionFV; eauto.\nQed.\n\nLemma unions_FV_WF : forall fvs,\n    (forall fv, In fv fvs -> WF_fv fv) ->\n    WF_fv (unionsFV fvs).\nProof.\n  apply map_union_FV_WF.\nQed.\n\nLemma mkFVs_FV_WF : forall vs,\n    WF_fv (mkFVs vs).\nProof.\n  intros. apply map_union_FV_WF; intros. apply unit_FV_WF.\nQed.\n\nHint Resolve unit_FV_WF.\nHint Resolve empty_FV_WF.\nHint Resolve union_FV_WF.\nHint Resolve unions_FV_WF.\nHint Resolve del_FV_WF.\nHint Resolve mkFVs_FV_WF.\n\n(** * Some other theroems about [FV]s. *)\n\nLemma union_empty_l : forall fv, FV.unionFV FV.emptyFV fv = fv.\nProof. reflexivity. Qed.\n\nLemma union_empty_r : forall fv, FV.unionFV fv FV.emptyFV = fv.\nProof. reflexivity. Qed.\n\nLemma DenotesfvVarSet vs fv :\n  Denotes vs fv -> fvVarSet fv [=] vs.\nProof.\n  move => [vs0 fv0 h1].\n  unfold fvVarSet, op_z2218U__, fvVarListVarSet, Tuple.snd.\n  specialize (h1 (const true) emptyVarSet emptyVarSet nil ltac:(eauto)). \n  destruct h1.\n  rewrite extendVarSetList_nil.\n  reflexivity.\n  remember (fv0 (const true) emptyVarSet (nil, emptyVarSet)) as tup.\n  replace tup with (Tuple.fst tup, Tuple.snd tup); [| destruct tup; reflexivity].\n  rewrite H0.\n  hs_simpl.\n  reflexivity.\nQed.\n\n\n\nLemma Denotes_inj1 vs1 vs2 fv : Denotes vs1 fv -> Denotes vs2 fv -> vs1 [=] vs2.\nProof.      \n  move => h1. inversion h1.\n  move => h2. inversion h2.\n  subst.\n  set in_scope := emptyVarSet.\n  assert (h : extendVarSetList emptyVarSet nil [=] emptyVarSet).\n  { rewrite <- mkVarSet_extendVarSetList. reflexivity. }\n  specialize (H (const true) in_scope emptyVarSet nil ltac:(auto) h).\n  specialize (H2 (const true) in_scope emptyVarSet nil ltac:(auto) h).\n  move: H => [h3 h4].\n  move: H2 => [h5 h6].\n  remember (fv (const true) emptyVarSet (nil,emptyVarSet)) as tup1.\n  replace tup1 with (Tuple.fst tup1, Tuple.snd tup1); [| destruct tup1; reflexivity].\n  remember (fv (const true) emptyVarSet (nil,emptyVarSet)) as tup2.\n  replace tup2 with (Tuple.fst tup2, Tuple.snd tup2); [| destruct tup2; reflexivity].\n  hs_simpl in h4.\n  hs_simpl in h6.\n  rewrite <- h4.\n  rewrite <- h6.\n  reflexivity.\nQed.\n\nLemma unionVarSet_same vs : unionVarSet vs vs [=] vs.\nProof. set_b_iff. fsetdec. Qed.\nHint Rewrite unionVarSet_same : hs_simpl.\n\nLemma delVarSet_fvVarSet: forall fv x,\n    WF_fv fv ->\n    delVarSet (fvVarSet fv) x [=] fvVarSet (delFV x fv).\nProof.\n  move => fv x [vs D].\n  move: (delVarSet_delFV _ x _ D) => h1.\n  move: (DenotesfvVarSet _ _ h1) => h2.\n  move: (DenotesfvVarSet _ _ D) => h3.\n  rewrite h3.\n  rewrite h2.\n  reflexivity.\nQed.\n\n(* --------------------------------------- *)\n\n\n\nLemma mapUnionVarSet_mapUnionFV A (ps : list A) \n      (f1 :  A -> VarSet) (f2 : A -> FV.FV) :\n  Forall2 Denotes (map f1 ps) (map f2 ps) ->\n  Denotes  (mapUnionVarSet f1 ps) (FV.mapUnionFV f2 ps).\nProof.\n  elim: ps => [|p ps IH]; unfold mapUnionVarSet; simpl.\n  hs_simpl.\n  - move=>h. constructor; intros; subst.\n    unfold Tuple.fst, Tuple.snd.\n    hs_simpl.\n    split; auto.\n    reflexivity.\n  - hs_simpl.\n    move=>h. inversion h. subst.\n    unfold mapUnionVarSet in IH.\n    specialize (IH H4). clear H4.\n    move: (unionVarSet_unionFV _ _ _ _ H2 IH) => h0.\n    unfold FV.unionFV in h0.\n    auto.\nQed.\n\n\nLemma unionsFV_cons fv fvs : \n  FV.unionsFV (fv :: fvs) = \n  FV.unionFV (FV.unionsFV fvs) fv.\nProof.\n  repeat unfold FV.unionsFV, FV.unionFV.\n  rewrite mapUnionFV_cons.\n  unfold FV.unionFV.\n  simpl.\n  reflexivity.\nQed.\n\n\nLemma unionsVarSet_unionsFV vss fvs: \n   Forall2 Denotes vss fvs ->\n   Denotes (Foldable.foldr unionVarSet emptyVarSet vss) (FV.unionsFV fvs).\nProof.\n  elim.\n  - hs_simpl. \n    unfold FV.unionsFV, FV.mapUnionFV.\n    constructor; intros; subst.\n    unfold Tuple.fst, Tuple.snd.\n    hs_simpl.\n    split; auto.\n    reflexivity.\n  - move => vs fv vss1 fvs1 D1 D2 IH. \n    hs_simpl. \n    move: (unionVarSet_unionFV _ _ _ _ D1 IH) => h0.\n    rewrite unionsFV_cons.\n    auto.\nQed.\n\n", "meta": {"author": "antalsz", "repo": "hs-to-coq", "sha": "cd62a35fff22cb6022a8935581746df658264f0f", "save_path": "github-repos/coq/antalsz-hs-to-coq", "path": "github-repos/coq/antalsz-hs-to-coq/hs-to-coq-cd62a35fff22cb6022a8935581746df658264f0f/examples/ghc/theories/FV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23547919447140206}}
{"text": "(** MetaType.v *)\nFrom Babel Require Import TerminalDogma \n                          ExtraDogma.Extensionality\n                          SetFacility\n                          POrderFacility.\n\nFrom Babel Require Import Ranko\n                            ExtensionalityCharacter\n                            ClassicalCharacter.\n\nFrom Babel Require Export MetaLanguage.Notations\n                            Parity.\n\nFrom Coq Require Import Relations Classical.\n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n\n(****************************************)\n(*                                      *)\n(*       DMT                            *)\n(*       (Deduction Metatype)           *)\n(*                                      *)\n(****************************************)\n\nModule DMT.\nSection ClassDef.\n\nRecord mixin_of (T : iType) := Mixin {\n    ded_sys : T -> T -> Prop;\n}.\n\nNotation class_of := mixin_of (only parsing).\n\nRecord type := Pack {\n    sort : iType;\n    class : class_of sort;\n}.\n\nEnd ClassDef.\n\nModule Exports.\n\n#[reversible]\nCoercion sort : type >-> iType.\n\nCoercion class : type >-> mixin_of.\n\nNotation dMT := type.\nNotation DMT s m := (@Pack s m).\nNotation Dsys := ded_sys.\n\nNotation \" ax ⊢ P ⇒ Q \" := ((Dsys ax) P Q) : MetaLan_scope.\n\nEnd Exports.\nEnd DMT.\nExport DMT.Exports.\n\n\n\n(****************************************)\n(*                                      *)\n(*       cpoDMT                         *)\n(*       (cpo with Deduction Metatype)  *)\n(*                                      *)\n(****************************************)\n\nModule CpoDMT.\n\nSection ClassDef.\n\nRecord mixin_of (T : iType) \n        (b_cpo : CPO.class_of T) (b_dMT : DMT.mixin_of T) \n        (bcpo := CPO T b_cpo) (bdMT := DMT T b_dMT):= Mixin {\n    \n    ded_iffP : forall (P Q : bcpo), \n        P ⊑ Q   <->   bdMT ⊢ P ⇒ Q;\n}.\n\nRecord class_of (T : iType) := Class {\n    b_cpo : CPO.class_of T;\n    b_dMT : DMT.mixin_of T;\n    mixin : mixin_of b_cpo b_dMT;\n}.\n\nRecord type := Pack {\n    sort : iType;\n    class : class_of sort;\n}.\n\nLocal Coercion sort : type >-> iType.\nLocal Coercion class : type >-> class_of.\n\nVariable (cT : type).\n\nDefinition pack (T : iType) (b_cpo : CPO.class_of T) (b_dMT : DMT.mixin_of T) \n    (m : mixin_of b_cpo b_dMT) : type := @Pack T (Class m).\n\nDefinition to_cpo : cpo := CPO cT (b_cpo cT).\nDefinition to_dMT : dMT := DMT cT (b_dMT cT).\n\nEnd ClassDef.\n\nModule Exports.\n\n#[reversible]\nCoercion sort : type >-> iType.\nCoercion to_cpo : type >-> cpo.\nCoercion to_dMT : type >-> dMT.\nCoercion class : type >-> class_of.\n\nNotation cpoDMT := type.\nNotation CpoDMT T m := (@pack T _ _ m).\n\nEnd Exports.\n\nEnd CpoDMT.\nExport CpoDMT.Exports.\n\n\n(****************************************)\n(*                                      *)\n(*       BaseMT                         *)\n(*       (Basic Metatype)               *)\n(*                                      *)\n(****************************************)\nModule BaseMT.\n\nSection ClassDef.\n\nRecord mixin_of (FType BType : iType) := Mixin {\n    SVal : clattice;\n    sat_eval : BType -> FType -> SVal;\n}.\n\nNotation class_of := mixin_of (only parsing).\n\n(** This acts as the basic rules of this program world. *)\nRecord type := Pack {\n    fType : iType;\n    bType : iType;\n    class : class_of fType bType;\n}.\n\nLocal Coercion class : type >-> mixin_of.\n\n\nEnd ClassDef.\n\n\nModule Exports.\n\nCoercion class : type >-> mixin_of.\n\nNotation baseMT := type.\nNotation BaseMT fT bT m := (@Pack fT bT m).\n\nNotation FType := fType.\nNotation BType := bType.\nNotation SVal := SVal.\n\nNotation \" P ∙ s \" := (sat_eval (class _) P s) : MetaLan_scope.\nNotation \" P ∙ s :> mT\" := (sat_eval (class mT) P s) \n    (only parsing): MetaLan_scope.\nNotation \" ⌈ x ⇒ y ⌉ \" := (forall P, P ∙ x ⊑ P ∙ y) : MetaLan_scope.\nNotation \" ⌈ x ⇒ y ⌉ :> mT \" := (forall P, P ∙ x :> mT ⊑ P ∙ y :> mT) \n    (only parsing): MetaLan_scope.\n\n\nEnd Exports.\nEnd BaseMT.\nExport BaseMT.Exports.\n\n(** How to do parity transformation? *)\nDefinition Parity_Trans : baseMT -> baseMT :=\n    fun b => \n    {|\n        BaseMT.fType := BType b;\n        BaseMT.bType := FType b;\n        BaseMT.class := {|\n            BaseMT.SVal := SVal b;\n            BaseMT.sat_eval := fun bt ft => BaseMT.sat_eval b ft bt;\n        |};\n    |}.\n\nDefinition parity_trans_involutive : \n    forall b : baseMT, Parity_Trans (Parity_Trans b) = b.\nProof. move => [] ? ? [] => //=. Qed.\n\n    \nSection BaseMT_Theories.\n\nVariable (mT : baseMT).\n\n\n\n(** Definition of two kinds of correctness *)\nDefinition correct\n    (x : FType mT) (f : BType mT -> BType mT) (y : FType mT) : Prop :=\n        forall P, P ∙ x ⊑ (f P)∙ y.\n\n(** Extensionality *)\nDefinition sat_eq : FType mT -> FType mT -> Prop :=\n    fun x y => forall P, P ∙ x = P ∙ y.\n\n(** Proof of equivalence relation. *)\nLemma sat_eq_refl : \n    reflexive _ sat_eq.\nProof. by rewrite /sat_eq.  Qed.\n\nLemma sat_eq_trans : \n    transitive _ sat_eq.\nProof. \n    rewrite /transitive => P Q R.\n    rewrite /sat_eq => HPQ HQR x.\n    rewrite -HQR. apply HPQ.\nQed.\n\nLemma sat_eq_symm :\n    symmetric _ sat_eq.\nProof.\n    rewrite /symmetric => P Q.\n    rewrite /sat_eq => H x. by rewrite H.\nQed.\n\nAdd Relation _ sat_eq\n    reflexivity proved by sat_eq_refl\n    symmetry proved by sat_eq_symm\n    transitivity proved by sat_eq_trans\n    as sat_eq_rel.\n\n\n(** Morphism between extensional equivalence and correctness *)\nAdd Morphism correct\n    with signature sat_eq ==> eq ==> sat_eq ==> iff \n        as correct_mor.\nProof.\n    move => P Q HPQ f R S HRS.\n    rewrite /correct. split.\n    - move => H s. rewrite -(HPQ s) -(HRS (f s)). by apply H.\n    - move => H s. rewrite (HPQ s) (HRS (f s)). by apply H.\nQed.\n\n(** Injection and Equivalence *)\n(** IMPORTANT : this is actually the ability of distinguish of [Asn] or [Stt]. *)\nDefinition sat_eval_inj :=\n    forall (x y : FType mT), sat_eq x y -> x = y.\n\nEnd BaseMT_Theories.\n\nNotation \" ⊨ { P } f { Q } \" := (@correct _ P f Q) : MetaLan_scope.\nNotation \" ⊨ [ x ] g [ y ] \" := (@correct _ x g y) : MetaLan_scope.\nNotation \" P '=FD' Q \" := (@sat_eq _ P Q) : MetaLan_scope.\n\n\n(****************************************)\n(*                                      *)\n(*       cpoMT                          *)\n(*       (CPO Metatype)                 *)\n(*                                      *)\n(****************************************)\n\nModule CpoMT.\n\nSection ClassDef.\n\n\nRecord mixin_of (fType bType : iType)\n            (b : BaseMT.mixin_of fType bType) \n            (b_cpo : CPO.class_of fType) \n            (base := BaseMT _ _ b) (bcpo := CPO _ b_cpo)\n        := Mixin {\n\n    sat_eval_monotonicity : forall (x y : bcpo), x ⊑ y <-> ⌈ x ⇒ y ⌉ :> base;\n}.\n\nRecord class_of (fType bType : iType) := Class {\n    base : BaseMT.mixin_of fType bType;\n    base_cpo : CPO.class_of fType;\n    mixin : mixin_of base base_cpo;\n}.\n\nRecord type := Pack {\n    fType : iType;\n    bType : iType;\n    class : class_of fType bType;\n}.\n\nLocal Coercion class : type >-> class_of.\n\nDefinition to_baseMT (c : type) : baseMT :=\n    BaseMT _ _ (base c).\n\nDefinition fType_cpo (c : type) : cpo := CPO _ (base_cpo c).\n\nLemma sat_eval_monotonicity_wrap (cT : type) :\n    forall (x y : (fType_cpo cT)), x ⊑ y <-> ⌈ x ⇒ y ⌉ :> (to_baseMT cT).\nProof. apply sat_eval_monotonicity. by apply (class cT). Qed.\n\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion class : type >-> class_of.\nCoercion mixin : class_of >-> mixin_of.\n\nCoercion to_baseMT : type >-> baseMT.\n\nNotation FType_cpo := fType_cpo.\nNotation Sat_eval_monotonicity := sat_eval_monotonicity_wrap.\n\nNotation cpoMT := type.\nNotation CpoMT fT bT m := (@Pack fT bT (Class m)).\n\nEnd Exports.\nEnd CpoMT.\n\nExport CpoMT.Exports.\n\nSection CpoMT_Theories.\n\nVariable (mT : cpoMT).\n\nAdd Morphism (@ord_op (FType_cpo mT))\n    with signature (@sat_eq mT) ==> (@sat_eq mT) ==> iff \n        as fType_le_mor.\nProof.\n    move => x y Hxy r s Hrs.\n    rewrite /correct. rewrite !Sat_eval_monotonicity.\n    split.\n    - move => H P. rewrite -Hxy -Hrs. by apply H.\n    - move => H P. rewrite Hxy Hrs. by apply H.\nQed.\n\nLemma cpoMT_sat_eval_inj : sat_eval_inj mT.\nProof.\n    rewrite /sat_eval_inj => x y Hxy. \n    apply (@poset_antisym (FType_cpo mT)). \n    all: apply Sat_eval_monotonicity => P; rewrite Hxy; by reflexivity.\nQed.\n\nEnd CpoMT_Theories.\n\n\n(****************************************)\n(*                                      *)\n(*       CLatticeMT                     *)\n(*                                      *)\n(*       (Complete Lattice)             *)\n(****************************************)\n\n\nModule CLatticeMT.\n\nSection ClassDef.\n\nRecord mixin_of (fType bType: iType)\n        (b : CpoMT.class_of fType bType) (b_cl : CLattice.class_of fType)\n        (mT := CpoMT fType bType b) (cl := CLattice fType b_cl) \n            := Mixin {\n\n    sat_eval_join_mor : \n        forall (X : 𝒫(cl)) (P : BType mT), \n          P ∙ (⊔ᶜˡ X) = ⊔ᶜˡ { P ∙ s, s | s ∈ X };\n}.\n\nRecord class_of (fType bType : iType) := Class {\n    b_cpoMT : CpoMT.class_of fType bType;\n    b_cl : CLattice.class_of fType;\n    mixin : mixin_of b_cpoMT b_cl;\n}.\n\nRecord type := Pack {\n    fType : iType;\n    bType : iType;\n    class : class_of fType bType;\n}.\n\nLocal Coercion class : type >-> class_of.\n\nDefinition to_cpoMT (cT : type) : cpoMT := CpoMT _ _ (b_cpoMT cT).\nDefinition FType_clattice (cT : type) : clattice := CLattice _ (b_cl cT).\n\nLemma sat_eval_join_mor_wrap (cT : type) :\n    forall (X : 𝒫(FType_clattice cT)) (P : BType (to_cpoMT cT)), \n        P ∙ (⊔ᶜˡ X) = ⊔ᶜˡ { P ∙ s, s | s ∈ X }.\nProof. apply sat_eval_join_mor. apply (mixin cT). Qed.\n\nEnd ClassDef.\n\nModule Exports.\n\nCoercion to_cpoMT : type >-> cpoMT.\nCoercion class : type >-> class_of.\n\nNotation FType_clattice := FType_clattice.\nCanonical FType_clattice.\n\nNotation Sat_eval_join_mor := sat_eval_join_mor_wrap.\n\nNotation cLatticeMT := type.\nNotation CLatticeMT fT bT m := (@Pack fT bT (Class m)).\n\nEnd Exports.\nEnd CLatticeMT.\n\nExport CLatticeMT.Exports.\n", "meta": {"author": "LucianoXu", "repo": "Project-Babel", "sha": "92a749468a5ab3f3acb5e0bcbf29800df90be651", "save_path": "github-repos/coq/LucianoXu-Project-Babel", "path": "github-repos/coq/LucianoXu-Project-Babel/Project-Babel-92a749468a5ab3f3acb5e0bcbf29800df90be651/Babel/MetaLanguage/Parity/MetaType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.235476003986888}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Operators and addressing modes.  The abstract syntax and dynamic\n  semantics for the CminorSel, RTL, LTL and Mach languages depend on the\n  following types, defined in this library:\n- [condition]:  boolean conditions for conditional branches;\n- [operation]: arithmetic and logical operations;\n- [addressing]: addressing modes for load and store operations.\n\n  These types are PowerPC-specific and correspond roughly to what the\n  processor can compute in one instruction.  In other terms, these\n  types reflect the state of the program after instruction selection.\n  For a processor-independent set of operations, see the abstract\n  syntax and dynamic semantics of the Cminor language.\n*)\n\nRequire Import BoolEqual.\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Events.\n\nSet Implicit Arguments.\n\n(** Conditions (boolean-valued operators). *)\n\nInductive condition : Type :=\n  | Ccomp: comparison -> condition      (**r signed integer comparison *)\n  | Ccompu: comparison -> condition     (**r unsigned integer comparison *)\n  | Ccompimm: comparison -> int -> condition (**r signed integer comparison with a constant *)\n  | Ccompuimm: comparison -> int -> condition (**r unsigned integer comparison with a constant *)\n  | Ccompf: comparison -> condition     (**r floating-point comparison *)\n  | Cnotcompf: comparison -> condition  (**r negation of a floating-point comparison *)\n  | Cmaskzero: int -> condition         (**r test [(arg & constant) == 0] *)\n  | Cmasknotzero: int -> condition      (**r test [(arg & constant) != 0] *)\n(*c PPC64 specific conditions: *)\n  | Ccompl: comparison -> condition     (**r signed int64 comparison *)\n  | Ccomplu: comparison -> condition    (**r unsigned int64 comparison *)\n  | Ccomplimm: comparison -> int64 -> condition (**r signed int64 comparison with a constant *)\n  | Ccompluimm: comparison -> int64 -> condition. (**r unsigned int64 comparison with a constant *)\n\n(** Arithmetic and logical operations.  In the descriptions, [rd] is the\n  result of the operation and [r1], [r2], etc, are the arguments. *)\n\nInductive operation : Type :=\n  | Omove: operation                    (**r [rd = r1] *)\n  | Ointconst: int -> operation         (**r [rd] is set to the given integer constant *)\n  | Ofloatconst: float -> operation     (**r [rd] is set to the given float constant *)\n  | Osingleconst: float32 -> operation  (**r [rd] is set to the given float constant *)\n  | Oaddrsymbol: ident -> ptrofs -> operation (**r [rd] is set to the the address of the symbol plus the offset *)\n  | Oaddrstack: ptrofs -> operation     (**r [rd] is set to the stack pointer plus the given offset *)\n(*c Integer arithmetic: *)\n  | Ocast8signed: operation             (**r [rd] is 8-bit sign extension of [r1] *)\n  | Ocast16signed: operation            (**r [rd] is 16-bit sign extension of [r1] *)\n  | Oadd: operation                     (**r [rd = r1 + r2] *)\n  | Oaddimm: int -> operation           (**r [rd = r1 + n] *)\n  | Oaddsymbol: ident -> ptrofs -> operation (**r [rd = addr(id + ofs) + r1] *)\n  | Osub: operation                     (**r [rd = r1 - r2] *)\n  | Osubimm: int -> operation           (**r [rd = n - r1] *)\n  | Omul: operation                     (**r [rd = r1 * r2] *)\n  | Omulimm: int -> operation           (**r [rd = r1 * n] *)\n  | Omulhs: operation                   (**r [rd = high part of r1 * r2, signed] *)\n  | Omulhu: operation                   (**r [rd = high part of r1 * r2, unsigned] *)\n  | Odiv: operation                     (**r [rd = r1 / r2] (signed) *)\n  | Odivu: operation                    (**r [rd = r1 / r2] (unsigned) *)\n  | Oand: operation                     (**r [rd = r1 & r2] *)\n  | Oandimm: int -> operation           (**r [rd = r1 & n] *)\n  | Oor: operation                      (**r [rd = r1 | r2] *)\n  | Oorimm: int -> operation            (**r [rd = r1 | n] *)\n  | Oxor: operation                     (**r [rd = r1 ^ r2] *)\n  | Oxorimm: int -> operation           (**r [rd = r1 ^ n] *)\n  | Onot: operation                     (**r [rd = ~r1] *)\n  | Onand: operation                    (**r [rd = ~(r1 & r2)] *)\n  | Onor: operation                     (**r [rd = ~(r1 | r2)] *)\n  | Onxor: operation                    (**r [rd = ~(r1 ^ r2)] *)\n  | Oandc: operation                    (**r [rd = r1 & ~r2] *)\n  | Oorc: operation                     (**r [rd = r1 | ~r2] *)\n  | Oshl: operation                     (**r [rd = r1 << r2] *)\n  | Oshr: operation                     (**r [rd = r1 >> r2] (signed) *)\n  | Oshrimm: int -> operation           (**r [rd = r1 >> n] (signed) *)\n  | Oshrximm: int -> operation          (**r [rd = r1 / 2^n] (signed) *)\n  | Oshru: operation                    (**r [rd = r1 >> r2] (unsigned) *)\n  | Orolm: int -> int -> operation      (**r rotate left and mask *)\n  | Oroli: int -> int -> operation      (**r rotate left and insert *)\n(*c PPC64 64-bit integer arithmetic: *)\n  | Olongconst: int64 -> operation      (**r [rd] is set to the given int64 constant *)\n  | Ocast32signed: operation            (**r [rd] is 64-bit sign extension of [r1] *)\n  | Ocast32unsigned: operation          (**r [rd] is 64-bit zero extension of [r1] *)\n  | Oaddl: operation                    (**r [rd = r1 + r2] *)\n  | Oaddlimm: int64 -> operation        (**r [rd = r1 + n] *)\n  | Osubl: operation                    (**r [rd = r1 - r2] *)\n  | Onegl: operation                    (**r [rd = - r1] *)\n  | Omull: operation                    (**r [rd = r1 * r2] *)\n  | Omullhs: operation                  (**r [rd = high part of r1 * r2, signed] *)\n  | Omullhu: operation                  (**r [rd = high part of r1 * r2, unsigned] *)\n  | Odivl: operation                    (**r [rd = r1 / r2] (signed) *)\n  | Odivlu: operation                   (**r [rd = r1 / r2] (unsigned) *)\n  | Oandl: operation                    (**r [rd = r1 & r2] *)\n  | Oandlimm: int64 -> operation        (**r [rd = r1 & n] *)\n  | Oorl: operation                     (**r [rd = r1 | r2] *)\n  | Oorlimm: int64 -> operation         (**r [rd = r1 | n] *)\n  | Oxorl: operation                    (**r [rd = r1 ^ r2] *)\n  | Oxorlimm: int64 -> operation        (**r [rd = r1 ^ n] *)\n  | Onotl: operation                    (**r [rd = ~r1] *)\n  | Oshll: operation                    (**r [rd = r1 << r2] *)\n  | Oshrl: operation                    (**r [rd = r1 >> r2] (signed) *)\n  | Oshrlimm: int -> operation          (**r [rd = r1 >> n] (signed) *)\n  | Oshrxlimm: int -> operation         (**r [rd = r1 / 2^n] (signed) *)\n  | Oshrlu: operation                   (**r [rd = r1 >> r2] (unsigned) *)\n  | Orolml: int -> int64 -> operation   (**r rotate left and mask *)\n  | Olongoffloat: operation             (**r [rd = signed_int64_of_float(r1)] *)\n  | Ofloatoflong: operation             (**r [rd = float_of_signed_int64(r1)] *)\n(*c Floating-point arithmetic: *)\n  | Onegf: operation                    (**r [rd = - r1] *)\n  | Oabsf: operation                    (**r [rd = abs(r1)] *)\n  | Oaddf: operation                    (**r [rd = r1 + r2] *)\n  | Osubf: operation                    (**r [rd = r1 - r2] *)\n  | Omulf: operation                    (**r [rd = r1 * r2] *)\n  | Odivf: operation                    (**r [rd = r1 / r2] *)\n  | Onegfs: operation                   (**r [rd = - r1] *)\n  | Oabsfs: operation                   (**r [rd = abs(r1)] *)\n  | Oaddfs: operation                   (**r [rd = r1 + r2] *)\n  | Osubfs: operation                   (**r [rd = r1 - r2] *)\n  | Omulfs: operation                   (**r [rd = r1 * r2] *)\n  | Odivfs: operation                   (**r [rd = r1 / r2] *)\n  | Osingleoffloat: operation           (**r [rd] is [r1] truncated to single-precision float *)\n  | Ofloatofsingle: operation           (**r [rd] is [r1] extended to double-precision float *)\n(*c Conversions between int and float: *)\n  | Ointoffloat: operation              (**r [rd = signed_int_of_float(r1)] *)\n  | Ofloatofwords: operation            (**r [rd = float_of_words(r1,r2)] *)\n(*c Manipulating 64-bit integers: *)\n  | Omakelong: operation                (**r [rd = r1 << 32 | r2] *)\n  | Olowlong: operation                 (**r [rd = low-word(r1)] *)\n  | Ohighlong: operation                (**r [rd = high-word(r1)] *)\n(*c Boolean tests: *)\n  | Ocmp: condition -> operation        (**r [rd = 1] if condition holds, [rd = 0] otherwise. *)\n  | Osel: condition -> typ -> operation.\n                                        (**r [rd = rs1] if condition holds, [rd = rs2] otherwise. *)\n\n(** Addressing modes.  [r1], [r2], etc, are the arguments to the\n  addressing. *)\n\nInductive addressing: Type :=\n  | Aindexed: int -> addressing            (**r Address is [r1 + offset] *)\n  | Aindexed2: addressing                  (**r Address is [r1 + r2] *)\n  | Aglobal: ident -> ptrofs -> addressing (**r Address is [symbol + offset] *)\n  | Abased: ident -> ptrofs -> addressing  (**r Address is [symbol + offset + r1] *)\n  | Ainstack: ptrofs -> addressing.        (**r Address is [stack_pointer + offset] *)\n\n(** Comparison functions (used in module [CSE]). *)\n\nDefinition eq_condition (x y: condition) : {x=y} + {x<>y}.\nProof.\n  generalize Int.eq_dec Int64.eq_dec; intro.\n  assert (forall (x y: comparison), {x=y}+{x<>y}). decide equality.\n  decide equality.\nDefined.\n\nDefinition beq_operation: forall (x y: operation), bool.\n  generalize Int.eq_dec Int64.eq_dec Ptrofs.eq_dec ident_eq Float.eq_dec Float32.eq_dec typ_eq eq_condition; boolean_equality.\nDefined.\n\nDefinition eq_operation (x y: operation): {x=y} + {x<>y}.\nProof.\n  decidable_equality_from beq_operation.\nDefined.\n\nDefinition eq_addressing (x y: addressing) : {x=y} + {x<>y}.\nProof.\n  generalize Int.eq_dec Int64.eq_dec Ptrofs.eq_dec ident_eq; intro.\n  decide equality.\nDefined.\n\nGlobal Opaque eq_condition eq_addressing eq_operation.\n\n(** * Evaluation functions *)\n\n(** Evaluation of conditions, operators and addressing modes applied\n  to lists of values.  Return [None] when the computation can trigger an\n  error, e.g. integer division by zero.  [eval_condition] returns a boolean,\n  [eval_operation] and [eval_addressing] return a value. *)\n\nDefinition eval_condition (cond: condition) (vl: list val) (m: mem): option bool :=\n  match cond, vl with\n  | Ccomp c, v1 :: v2 :: nil => Val.cmp_bool c v1 v2\n  | Ccompu c, v1 :: v2 :: nil => Val.cmpu_bool (Mem.valid_pointer m) c v1 v2\n  | Ccompimm c n, v1 :: nil => Val.cmp_bool c v1 (Vint n)\n  | Ccompuimm c n, v1 :: nil => Val.cmpu_bool (Mem.valid_pointer m) c v1 (Vint n)\n  | Ccompf c, v1 :: v2 :: nil => Val.cmpf_bool c v1 v2\n  | Cnotcompf c, v1 :: v2 :: nil => option_map negb (Val.cmpf_bool c v1 v2)\n  | Cmaskzero n, v1 :: nil => Val.maskzero_bool v1 n\n  | Cmasknotzero n, v1 :: nil => option_map negb (Val.maskzero_bool v1 n)\n  | Ccompl c, v1 :: v2 :: nil => Val.cmpl_bool c v1 v2\n  | Ccomplu c, v1 :: v2 :: nil => Val.cmplu_bool (Mem.valid_pointer m) c v1 v2\n  | Ccomplimm c n, v1 :: nil => Val.cmpl_bool c v1 (Vlong n)\n  | Ccompluimm c n, v1 :: nil => Val.cmplu_bool (Mem.valid_pointer m) c v1 (Vlong n)\n  | _, _ => None\n  end.\n\nDefinition eval_operation\n             (F V: Type) (genv: Genv.t F V) (sp: val)\n             (op: operation) (vl: list val) (m: mem): option val :=\n  match op, vl with\n  | Omove, v1::nil => Some v1\n  | Ointconst n, nil => Some (Vint n)\n  | Ofloatconst n, nil => Some (Vfloat n)\n  | Osingleconst n, nil => Some (Vsingle n)\n  | Oaddrsymbol s ofs, nil => Some (Genv.symbol_address genv s ofs)\n  | Oaddrstack ofs, nil => Some (Val.offset_ptr sp ofs)\n  | Ocast8signed, v1::nil => Some (Val.sign_ext 8 v1)\n  | Ocast16signed, v1::nil => Some (Val.sign_ext 16 v1)\n  | Oadd, v1::v2::nil => Some (Val.add v1 v2)\n  | Oaddimm n, v1::nil => Some (Val.add v1 (Vint n))\n  | Oaddsymbol s ofs, v1::nil => Some (Val.add (Genv.symbol_address genv s ofs) v1)\n  | Osub, v1::v2::nil => Some (Val.sub v1 v2)\n  | Osubimm n, v1::nil => Some (Val.sub (Vint n) v1)\n  | Omul, v1::v2::nil => Some (Val.mul v1 v2)\n  | Omulimm n, v1::nil => Some (Val.mul v1 (Vint n))\n  | Omulhs, v1::v2::nil => Some (Val.mulhs v1 v2)\n  | Omulhu, v1::v2::nil => Some (Val.mulhu v1 v2)\n  | Odiv, v1::v2::nil => Val.divs v1 v2\n  | Odivu, v1::v2::nil => Val.divu v1 v2\n  | Oand, v1::v2::nil => Some(Val.and v1 v2)\n  | Oandimm n, v1::nil => Some (Val.and v1 (Vint n))\n  | Oor, v1::v2::nil => Some(Val.or v1 v2)\n  | Oorimm n, v1::nil => Some (Val.or v1 (Vint n))\n  | Oxor, v1::v2::nil => Some(Val.xor v1 v2)\n  | Oxorimm n, v1::nil => Some (Val.xor v1 (Vint n))\n  | Onot, v1::nil => Some(Val.notint v1)\n  | Onand, v1::v2::nil => Some (Val.notint (Val.and v1 v2))\n  | Onor, v1::v2::nil => Some (Val.notint (Val.or v1 v2))\n  | Onxor, v1::v2::nil => Some (Val.notint (Val.xor v1 v2))\n  | Oandc, v1::v2::nil => Some (Val.and v1 (Val.notint v2))\n  | Oorc, v1::v2::nil => Some (Val.or v1 (Val.notint v2))\n  | Oshl, v1::v2::nil => Some (Val.shl v1 v2)\n  | Oshr, v1::v2::nil => Some (Val.shr v1 v2)\n  | Oshrimm n, v1::nil => Some (Val.shr v1 (Vint n))\n  | Oshrximm n, v1::nil => Val.shrx v1 (Vint n)\n  | Oshru, v1::v2::nil => Some (Val.shru v1 v2)\n  | Orolm amount mask, v1::nil => Some (Val.rolm v1 amount mask)\n  | Oroli amount mask, v1::v2::nil =>\n      Some(Val.or (Val.and v1 (Vint (Int.not mask))) (Val.rolm v2 amount mask))\n  | Olongconst n, nil => Some (Vlong n)\n  | Ocast32signed, v1::nil => Some (Val.longofint v1)\n  | Ocast32unsigned, v1::nil => Some (Val.longofintu v1)\n  | Oaddl, v1::v2::nil => Some (Val.addl v1 v2)\n  | Oaddlimm n, v1::nil => Some (Val.addl v1 (Vlong n))\n  | Osubl, v1::v2::nil => Some (Val.subl v1 v2)\n  | Onegl, v1::nil => Some (Val.negl v1)\n  | Omull, v1::v2::nil => Some (Val.mull v1 v2)\n  | Omullhs, v1::v2::nil => Some (Val.mullhs v1 v2)\n  | Omullhu, v1::v2::nil => Some (Val.mullhu v1 v2)\n  | Odivl, v1::v2::nil => Val.divls v1 v2\n  | Odivlu, v1::v2::nil => Val.divlu v1 v2\n  | Oandl, v1::v2::nil => Some(Val.andl v1 v2)\n  | Oandlimm n, v1::nil => Some (Val.andl v1 (Vlong n))\n  | Oorl, v1::v2::nil => Some(Val.orl v1 v2)\n  | Oorlimm n, v1::nil => Some (Val.orl v1 (Vlong n))\n  | Oxorl, v1::v2::nil => Some(Val.xorl v1 v2)\n  | Oxorlimm n, v1::nil => Some (Val.xorl v1 (Vlong n))\n  | Onotl, v1::nil => Some(Val.notl v1)\n  | Oshll, v1::v2::nil => Some (Val.shll v1 v2)\n  | Oshrl, v1::v2::nil => Some (Val.shrl v1 v2)\n  | Oshrlimm n, v1::nil => Some (Val.shrl v1 (Vint n))\n  | Oshrxlimm n, v1::nil => Val.shrxl v1 (Vint n)\n  | Oshrlu, v1::v2::nil => Some (Val.shrlu v1 v2)\n  | Orolml amount mask, v1::nil => Some (Val.rolml v1 amount mask)\n  | Olongoffloat, v1::nil => Val.longoffloat v1\n  | Ofloatoflong, v1::nil => Val.floatoflong v1\n  | Onegf, v1::nil => Some(Val.negf v1)\n  | Oabsf, v1::nil => Some(Val.absf v1)\n  | Oaddf, v1::v2::nil => Some(Val.addf v1 v2)\n  | Osubf, v1::v2::nil => Some(Val.subf v1 v2)\n  | Omulf, v1::v2::nil => Some(Val.mulf v1 v2)\n  | Odivf, v1::v2::nil => Some(Val.divf v1 v2)\n  | Onegfs, v1::nil => Some(Val.negfs v1)\n  | Oabsfs, v1::nil => Some(Val.absfs v1)\n  | Oaddfs, v1::v2::nil => Some(Val.addfs v1 v2)\n  | Osubfs, v1::v2::nil => Some(Val.subfs v1 v2)\n  | Omulfs, v1::v2::nil => Some(Val.mulfs v1 v2)\n  | Odivfs, v1::v2::nil => Some(Val.divfs v1 v2)\n  | Osingleoffloat, v1::nil => Some(Val.singleoffloat v1)\n  | Ofloatofsingle, v1::nil => Some(Val.floatofsingle v1)\n  | Ointoffloat, v1::nil => Val.intoffloat v1\n  | Ofloatofwords, v1::v2::nil => Some(Val.floatofwords v1 v2)\n  | Omakelong, v1::v2::nil => Some(Val.longofwords v1 v2)\n  | Olowlong, v1::nil => Some(Val.loword v1)\n  | Ohighlong, v1::nil => Some(Val.hiword v1)\n  | Ocmp c, _ => Some(Val.of_optbool (eval_condition c vl m))\n  | Osel c ty, v1::v2::vl => Some(Val.select (eval_condition c vl m) v1 v2 ty)\n  | _, _ => None\n  end.\n\nDefinition eval_addressing\n    (F V: Type) (genv: Genv.t F V) (sp: val)\n    (addr: addressing) (vl: list val) : option val :=\n  match addr, vl with\n  | Aindexed n, v1::nil => Some (Val.add v1 (Vint n))\n  | Aindexed2, v1::v2::nil => Some (Val.add v1 v2)\n  | Aglobal s ofs, nil => Some (Genv.symbol_address genv s ofs)\n  | Abased s ofs, v1::nil => Some (Val.add (Genv.symbol_address genv s ofs) v1)\n  | Ainstack ofs, nil => Some(Val.offset_ptr sp ofs)\n  | _, _ => None\n  end.\n\nRemark eval_addressing_Ainstack:\n  forall (F V: Type) (genv: Genv.t F V) sp ofs,\n  eval_addressing genv sp (Ainstack ofs) nil = Some (Val.offset_ptr sp ofs).\nProof.\n  intros. reflexivity.\nQed.\n\nRemark eval_addressing_Ainstack_inv:\n  forall (F V: Type) (genv: Genv.t F V) sp ofs vl v,\n  eval_addressing genv sp (Ainstack ofs) vl = Some v -> vl = nil /\\ v = Val.offset_ptr sp ofs.\nProof.\n  unfold eval_addressing; intros; destruct vl; inv H; auto.\nQed.\n\nLtac FuncInv :=\n  match goal with\n  | H: (match ?x with nil => _ | _ :: _ => _ end = Some _) |- _ =>\n      destruct x; simpl in H; try discriminate; FuncInv\n  | H: (match ?v with Vundef => _ | Vint _ => _ | Vlong _ => _ | Vfloat _ => _ | Vptr _ _ => _ end = Some _) |- _ =>\n      destruct v; simpl in H; try discriminate; FuncInv\n  | H: (Some _ = Some _) |- _ =>\n      injection H; intros; clear H; FuncInv\n  | _ =>\n      idtac\n  end.\n\n(** * Static typing of conditions, operators and addressing modes. *)\n\nDefinition type_of_condition (c: condition) : list typ :=\n  match c with\n  | Ccomp _ => Tint :: Tint :: nil\n  | Ccompu _ => Tint :: Tint :: nil\n  | Ccompimm _ _ => Tint :: nil\n  | Ccompuimm _ _ => Tint :: nil\n  | Ccompf _ => Tfloat :: Tfloat :: nil\n  | Cnotcompf _ => Tfloat :: Tfloat :: nil\n  | Cmaskzero _ => Tint :: nil\n  | Cmasknotzero _ => Tint :: nil\n  | Ccompl _ => Tlong :: Tlong :: nil\n  | Ccomplu _ => Tlong :: Tlong :: nil\n  | Ccomplimm _ _ => Tlong :: nil\n  | Ccompluimm _ _ => Tlong :: nil\n  end.\n\nDefinition type_of_operation (op: operation) : list typ * typ :=\n  match op with\n  | Omove => (nil, Tint)   (* treated specially *)\n  | Ointconst _ => (nil, Tint)\n  | Ofloatconst f => (nil, Tfloat)\n  | Osingleconst f => (nil, Tsingle)\n  | Oaddrsymbol _ _ => (nil, Tint)\n  | Oaddrstack _ => (nil, Tint)\n  | Ocast8signed => (Tint :: nil, Tint)\n  | Ocast16signed => (Tint :: nil, Tint)\n  | Oadd => (Tint :: Tint :: nil, Tint)\n  | Oaddimm _ => (Tint :: nil, Tint)\n  | Oaddsymbol _ _ => (Tint :: nil, Tint)\n  | Osub => (Tint :: Tint :: nil, Tint)\n  | Osubimm _ => (Tint :: nil, Tint)\n  | Omul => (Tint :: Tint :: nil, Tint)\n  | Omulimm _ => (Tint :: nil, Tint)\n  | Omulhs => (Tint :: Tint :: nil, Tint)\n  | Omulhu => (Tint :: Tint :: nil, Tint)\n  | Odiv => (Tint :: Tint :: nil, Tint)\n  | Odivu => (Tint :: Tint :: nil, Tint)\n  | Oand => (Tint :: Tint :: nil, Tint)\n  | Oandimm _ => (Tint :: nil, Tint)\n  | Oor => (Tint :: Tint :: nil, Tint)\n  | Oorimm _ => (Tint :: nil, Tint)\n  | Oxor => (Tint :: Tint :: nil, Tint)\n  | Oxorimm _ => (Tint :: nil, Tint)\n  | Onot => (Tint :: nil, Tint)\n  | Onand => (Tint :: Tint :: nil, Tint)\n  | Onor => (Tint :: Tint :: nil, Tint)\n  | Onxor => (Tint :: Tint :: nil, Tint)\n  | Oandc => (Tint :: Tint :: nil, Tint)\n  | Oorc => (Tint :: Tint :: nil, Tint)\n  | Oshl => (Tint :: Tint :: nil, Tint)\n  | Oshr => (Tint :: Tint :: nil, Tint)\n  | Oshrimm _ => (Tint :: nil, Tint)\n  | Oshrximm _ => (Tint :: nil, Tint)\n  | Oshru => (Tint :: Tint :: nil, Tint)\n  | Orolm _ _ => (Tint :: nil, Tint)\n  | Oroli _ _ => (Tint :: Tint :: nil, Tint)\n  | Olongconst _ => (nil, Tlong)\n  | Ocast32signed => (Tint :: nil, Tlong)\n  | Ocast32unsigned => (Tint :: nil, Tlong)\n  | Oaddl => (Tlong :: Tlong :: nil, Tlong)\n  | Oaddlimm _ => (Tlong :: nil, Tlong)\n  | Osubl => (Tlong :: Tlong :: nil, Tlong)\n  | Onegl => (Tlong :: nil, Tlong)\n  | Omull => (Tlong :: Tlong :: nil, Tlong)\n  | Omullhs => (Tlong :: Tlong :: nil, Tlong)\n  | Omullhu => (Tlong :: Tlong :: nil, Tlong)\n  | Odivl => (Tlong :: Tlong :: nil, Tlong)\n  | Odivlu => (Tlong :: Tlong :: nil, Tlong)\n  | Oandl => (Tlong :: Tlong :: nil, Tlong)\n  | Oandlimm _ => (Tlong :: nil, Tlong)\n  | Oorl => (Tlong :: Tlong :: nil, Tlong)\n  | Oorlimm _ => (Tlong :: nil, Tlong)\n  | Oxorl => (Tlong :: Tlong :: nil, Tlong)\n  | Oxorlimm _ => (Tlong :: nil, Tlong)\n  | Onotl => (Tlong :: nil, Tlong)\n  | Oshll => (Tlong :: Tint :: nil, Tlong)\n  | Oshrl => (Tlong :: Tint :: nil, Tlong)\n  | Oshrlimm _ => (Tlong :: nil, Tlong)\n  | Oshrxlimm _ => (Tlong :: nil, Tlong)\n  | Oshrlu => (Tlong :: Tint :: nil, Tlong)\n  | Orolml _ _ => (Tlong :: nil, Tlong)\n  | Olongoffloat => (Tfloat :: nil, Tlong)\n  | Ofloatoflong => (Tlong :: nil, Tfloat)\n  | Onegf => (Tfloat :: nil, Tfloat)\n  | Oabsf => (Tfloat :: nil, Tfloat)\n  | Oaddf => (Tfloat :: Tfloat :: nil, Tfloat)\n  | Osubf => (Tfloat :: Tfloat :: nil, Tfloat)\n  | Omulf => (Tfloat :: Tfloat :: nil, Tfloat)\n  | Odivf => (Tfloat :: Tfloat :: nil, Tfloat)\n  | Onegfs => (Tsingle :: nil, Tsingle)\n  | Oabsfs => (Tsingle :: nil, Tsingle)\n  | Oaddfs => (Tsingle :: Tsingle :: nil, Tsingle)\n  | Osubfs => (Tsingle :: Tsingle :: nil, Tsingle)\n  | Omulfs => (Tsingle :: Tsingle :: nil, Tsingle)\n  | Odivfs => (Tsingle :: Tsingle :: nil, Tsingle)\n  | Osingleoffloat => (Tfloat :: nil, Tsingle)\n  | Ofloatofsingle => (Tsingle :: nil, Tfloat)\n  | Ointoffloat => (Tfloat :: nil, Tint)\n  | Ofloatofwords => (Tint :: Tint :: nil, Tfloat)\n  | Omakelong => (Tint :: Tint :: nil, Tlong)\n  | Olowlong => (Tlong :: nil, Tint)\n  | Ohighlong => (Tlong :: nil, Tint)\n  | Ocmp c => (type_of_condition c, Tint)\n  | Osel c ty => (ty :: ty :: type_of_condition c, ty)\n  end.\n\nDefinition type_of_addressing (addr: addressing) : list typ :=\n  match addr with\n  | Aindexed _ => Tint :: nil\n  | Aindexed2 => Tint :: Tint :: nil\n  | Aglobal _ _ => nil\n  | Abased _ _ => Tint :: nil\n  | Ainstack _ => nil\n  end.\n\n(** Weak type soundness results for [eval_operation]:\n  the result values, when defined, are always of the type predicted\n  by [type_of_operation]. *)\n\nSection SOUNDNESS.\n\nVariable A V: Type.\nVariable genv: Genv.t A V.\n\nLemma type_of_operation_sound:\n  forall op vl sp v m,\n  op <> Omove ->\n  eval_operation genv sp op vl m = Some v ->\n  Val.has_type v (snd (type_of_operation op)).\nProof with (try exact I; try reflexivity).\n  intros.\n  destruct op; simpl in H0; FuncInv; subst; simpl.\n  congruence.\n  exact I.\n  auto.\n  auto.\n  unfold Genv.symbol_address. destruct (Genv.find_symbol genv i)...\n  destruct sp...\n  destruct v0...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  unfold Genv.symbol_address. destruct (Genv.find_symbol genv i)... destruct v0...\n  destruct v0; destruct v1... simpl. destruct (eq_block b b0)...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1; simpl in *; inv H0.\n    destruct (Int.eq i0 Int.zero\n         || Int.eq i (Int.repr Int.min_signed) && Int.eq i0 Int.mone); inv H2...\n  destruct v0; destruct v1; simpl in *; inv H0. destruct (Int.eq i0 Int.zero); inv H2...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int.iwordsize)...\n  destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int.iwordsize)...\n  destruct v0; simpl... destruct (Int.ltu i Int.iwordsize)...\n  destruct v0; simpl in *; inv H0. destruct (Int.ltu i (Int.repr 31)); inv H2...\n  destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int.iwordsize)...\n  destruct v0...\n  destruct v0; destruct v1...\n  exact I.\n  destruct v0...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1; simpl in *; inv H0.\n    destruct (Int64.eq i0 Int64.zero\n         || Int64.eq i (Int64.repr Int64.min_signed) && Int64.eq i0 Int64.mone); inv H2...\n  destruct v0; destruct v1; simpl in *; inv H0. destruct (Int64.eq i0 Int64.zero); inv H2...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0...\n  destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int64.iwordsize')...\n  destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int64.iwordsize')...\n  destruct v0; simpl... destruct (Int.ltu i Int64.iwordsize')...\n  destruct v0; simpl in *; inv H0. destruct (Int.ltu i (Int.repr 63)); inv H2...\n  destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int64.iwordsize')...\n  destruct v0...\n  destruct v0; simpl in H0; inv H0. destruct (Float.to_long f); inv H2...\n  destruct v0; simpl in H0; inv H0...\n  destruct v0...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0...\n  destruct v0; simpl in H0; inv H0. destruct (Float.to_int f); inv H2...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0...\n  destruct (eval_condition c vl m); simpl... destruct b...\n  unfold Val.select. destruct (eval_condition c vl m). apply Val.normalize_type. exact I.\nQed.\n\nEnd SOUNDNESS.\n\n(** * Manipulating and transforming operations *)\n\n(** Recognition of move operations. *)\n\nDefinition is_move_operation\n    (A: Type) (op: operation) (args: list A) : option A :=\n  match op, args with\n  | Omove, arg :: nil => Some arg\n  | _, _ => None\n  end.\n\nLemma is_move_operation_correct:\n  forall (A: Type) (op: operation) (args: list A) (a: A),\n  is_move_operation op args = Some a ->\n  op = Omove /\\ args = a :: nil.\nProof.\n  intros until a. unfold is_move_operation; destruct op;\n  try (intros; discriminate).\n  destruct args. intros; discriminate.\n  destruct args. intros. intuition congruence.\n  intros; discriminate.\nQed.\n\n(** [negate_condition cond] returns a condition that is logically\n  equivalent to the negation of [cond]. *)\n\nDefinition negate_condition (cond: condition): condition :=\n  match cond with\n  | Ccomp c => Ccomp(negate_comparison c)\n  | Ccompu c => Ccompu(negate_comparison c)\n  | Ccompimm c n => Ccompimm (negate_comparison c) n\n  | Ccompuimm c n => Ccompuimm (negate_comparison c) n\n  | Ccompf c => Cnotcompf c\n  | Cnotcompf c => Ccompf c\n  | Cmaskzero n => Cmasknotzero n\n  | Cmasknotzero n => Cmaskzero n\n  | Ccompl c => Ccompl(negate_comparison c)\n  | Ccomplu c => Ccomplu(negate_comparison c)\n  | Ccomplimm c n => Ccomplimm (negate_comparison c) n\n  | Ccompluimm c n => Ccompluimm (negate_comparison c) n\n  end.\n\nLemma eval_negate_condition:\n  forall cond vl m,\n  eval_condition (negate_condition cond) vl m = option_map negb (eval_condition cond vl m).\nProof.\n  intros. destruct cond; simpl.\n  repeat (destruct vl; auto). apply Val.negate_cmp_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmpu_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmp_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmpu_bool.\n  repeat (destruct vl; auto).\n  repeat (destruct vl; auto). destruct (Val.cmpf_bool c v v0); auto. destruct b; auto.\n  repeat (destruct vl; auto).\n  repeat (destruct vl; auto). destruct (Val.maskzero_bool v i) as [[]|]; auto.\n  repeat (destruct vl; auto). apply Val.negate_cmpl_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmplu_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmpl_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmplu_bool.\nQed.\n\n(** Shifting stack-relative references.  This is used in [Stacking]. *)\n\nDefinition shift_stack_addressing (delta: Z) (addr: addressing) :=\n  match addr with\n  | Ainstack ofs => Ainstack (Ptrofs.add (Ptrofs.repr delta) ofs)\n  | _ => addr\n  end.\n\nDefinition shift_stack_operation (delta: Z) (op: operation) :=\n  match op with\n  | Oaddrstack ofs => Oaddrstack (Ptrofs.add (Ptrofs.repr delta) ofs)\n  | _ => op\n  end.\n\nLemma type_shift_stack_addressing:\n  forall delta addr, type_of_addressing (shift_stack_addressing delta addr) = type_of_addressing addr.\nProof.\n  intros. destruct addr; auto.\nQed.\n\nLemma type_shift_stack_operation:\n  forall delta op, type_of_operation (shift_stack_operation delta op) = type_of_operation op.\nProof.\n  intros. destruct op; auto.\nQed.\n\nLemma eval_shift_stack_addressing:\n  forall F V (ge: Genv.t F V) sp addr vl delta,\n  eval_addressing ge (Vptr sp Ptrofs.zero) (shift_stack_addressing delta addr) vl =\n  eval_addressing ge (Vptr sp (Ptrofs.repr delta)) addr vl.\nProof.\n  intros. destruct addr; simpl; auto.\n  rewrite Ptrofs.add_zero_l; auto.\nQed.\n\nLemma eval_shift_stack_operation:\n  forall F V (ge: Genv.t F V) sp op vl m delta,\n  eval_operation ge (Vptr sp Ptrofs.zero) (shift_stack_operation delta op) vl m =\n  eval_operation ge (Vptr sp (Ptrofs.repr delta)) op vl m.\nProof.\n  intros. destruct op; simpl; auto.\n  rewrite Ptrofs.add_zero_l; auto.\nQed.\n\n(** Offset an addressing mode [addr] by a quantity [delta], so that\n  it designates the pointer [delta] bytes past the pointer designated\n  by [addr].  May be undefined, in which case [None] is returned. *)\n\nDefinition offset_addressing (addr: addressing) (delta: Z) : option addressing :=\n  match addr with\n  | Aindexed n => Some(Aindexed (Int.add n (Int.repr delta)))\n  | Aindexed2 => None\n  | Aglobal s n => Some(Aglobal s (Ptrofs.add n (Ptrofs.repr delta)))\n  | Abased s n => Some(Abased s (Ptrofs.add n (Ptrofs.repr delta)))\n  | Ainstack n => Some(Ainstack (Ptrofs.add n (Ptrofs.repr delta)))\n  end.\n\nLemma eval_offset_addressing:\n  forall (F V: Type) (ge: Genv.t F V) sp addr args delta addr' v,\n  offset_addressing addr delta = Some addr' ->\n  eval_addressing ge sp addr args = Some v ->\n  eval_addressing ge sp addr' args = Some(Val.add v (Vint (Int.repr delta))).\nProof.\n  intros.\n  assert (D: Ptrofs.repr delta = Ptrofs.of_int (Int.repr delta)) by (symmetry; auto with ptrofs).\n  destruct addr; simpl in H; inv H; simpl in *; FuncInv; subst.\n- rewrite Val.add_assoc; auto.\n- unfold Genv.symbol_address. destruct (Genv.find_symbol ge i); auto. rewrite D; auto.\n- unfold Genv.symbol_address. destruct (Genv.find_symbol ge i); auto.\n  rewrite Val.add_assoc. rewrite Val.add_permut. rewrite Val.add_commut.\n  simpl. rewrite D. auto.\n- destruct sp; simpl; auto. rewrite Ptrofs.add_assoc, D. auto.\nQed.\n\n(** Operations that are so cheap to recompute that CSE should not factor them out. *)\n\nDefinition is_trivial_op (op: operation) : bool :=\n  match op with\n  | Omove => true\n  | Ointconst _ => true\n  | Oaddrsymbol _ _ => true\n  | Oaddrstack _ => true\n  | _ => false\n  end.\n\n(** Operations that depend on the memory state. *)\n\nDefinition condition_depends_on_memory (c: condition) : bool :=\n  match c with\n  | Ccompu _ => true\n  | Ccompuimm _ _ => true\n  | Ccomplu _ => Archi.ppc64\n  | Ccompluimm _ _ => Archi.ppc64\n  | _ => false\n  end.\n\nDefinition op_depends_on_memory (op: operation) : bool :=\n  match op with\n  | Ocmp c => condition_depends_on_memory c\n  | Osel c ty => condition_depends_on_memory c\n  | _ => false\n  end.\n\nLemma condition_depends_on_memory_correct:\n  forall c args m1 m2,\n  condition_depends_on_memory c = false ->\n  eval_condition c args m1 = eval_condition c args m2.\nProof.\n  intros. destruct c; simpl; auto; discriminate.\nQed.\n\nLemma op_depends_on_memory_correct:\n  forall (F V: Type) (ge: Genv.t F V) sp op args m1 m2,\n  op_depends_on_memory op = false ->\n  eval_operation ge sp op args m1 = eval_operation ge sp op args m2.\nProof.\n  intros until m2. destruct op; simpl; try congruence; intros C.\n- f_equal; f_equal; apply condition_depends_on_memory_correct; auto.\n- destruct args; auto. destruct args; auto.\n  rewrite (condition_depends_on_memory_correct c args m1 m2 C).\n  auto.\nQed.\n\n(** Global variables mentioned in an operation or addressing mode *)\n\nDefinition globals_operation (op: operation) : list ident :=\n  match op with\n  | Oaddrsymbol s ofs => s :: nil\n  | Oaddsymbol s ofs => s :: nil\n  | _ => nil\n  end.\n\nDefinition globals_addressing (addr: addressing) : list ident :=\n  match addr with\n  | Aglobal s n => s :: nil\n  | Abased s n => s :: nil\n  | _ => nil\n  end.\n\n(** * Invariance and compatibility properties. *)\n\n(** [eval_operation] and [eval_addressing] depend on a global environment\n  for resolving references to global symbols.  We show that they give\n  the same results if a global environment is replaced by another that\n  assigns the same addresses to the same symbols. *)\n\nSection GENV_TRANSF.\n\nVariable F1 F2 V1 V2: Type.\nVariable ge1: Genv.t F1 V1.\nVariable ge2: Genv.t F2 V2.\nHypothesis agree_on_symbols:\n  forall (s: ident), Genv.find_symbol ge2 s = Genv.find_symbol ge1 s.\n\nRemark symbol_address_preserved:\n  forall s ofs, Genv.symbol_address ge2 s ofs = Genv.symbol_address ge1 s ofs.\nProof.\n  unfold Genv.symbol_address; intros. rewrite agree_on_symbols; auto.\nQed.\n\nLemma eval_operation_preserved:\n  forall sp op vl m,\n  eval_operation ge2 sp op vl m = eval_operation ge1 sp op vl m.\nProof.\n  intros. destruct op; simpl; auto; rewrite symbol_address_preserved; auto.\nQed.\n\nLemma eval_addressing_preserved:\n  forall sp addr vl,\n  eval_addressing ge2 sp addr vl = eval_addressing ge1 sp addr vl.\nProof.\n  intros. destruct addr; simpl; auto; rewrite symbol_address_preserved; auto.\nQed.\n\nEnd GENV_TRANSF.\n\n(** Compatibility of the evaluation functions with value injections. *)\n\nSection EVAL_COMPAT.\n\nVariable F1 F2 V1 V2: Type.\nVariable ge1: Genv.t F1 V1.\nVariable ge2: Genv.t F2 V2.\nVariable f: meminj.\n\nVariable m1: mem.\nVariable m2: mem.\n\nHypothesis valid_pointer_inj:\n  forall b1 ofs b2 delta,\n  f b1 = Some(b2, delta) ->\n  Mem.valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->\n  Mem.valid_pointer m2 b2 (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr delta))) = true.\n\nHypothesis weak_valid_pointer_inj:\n  forall b1 ofs b2 delta,\n  f b1 = Some(b2, delta) ->\n  Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->\n  Mem.weak_valid_pointer m2 b2 (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr delta))) = true.\n\nHypothesis weak_valid_pointer_no_overflow:\n  forall b1 ofs b2 delta,\n  f b1 = Some(b2, delta) ->\n  Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->\n  0 <= Ptrofs.unsigned ofs + Ptrofs.unsigned (Ptrofs.repr delta) <= Ptrofs.max_unsigned.\n\nHypothesis valid_different_pointers_inj:\n  forall b1 ofs1 b2 ofs2 b1' delta1 b2' delta2,\n  b1 <> b2 ->\n  Mem.valid_pointer m1 b1 (Ptrofs.unsigned ofs1) = true ->\n  Mem.valid_pointer m1 b2 (Ptrofs.unsigned ofs2) = true ->\n  f b1 = Some (b1', delta1) ->\n  f b2 = Some (b2', delta2) ->\n  b1' <> b2' \\/\n  Ptrofs.unsigned (Ptrofs.add ofs1 (Ptrofs.repr delta1)) <> Ptrofs.unsigned (Ptrofs.add ofs2 (Ptrofs.repr delta2)).\n\nLtac InvInject :=\n  match goal with\n  | [ H: Val.inject _ (Vint _) _ |- _ ] =>\n      inv H; InvInject\n  | [ H: Val.inject _ (Vfloat _) _ |- _ ] =>\n      inv H; InvInject\n  | [ H: Val.inject _ (Vsingle _) _ |- _ ] =>\n      inv H; InvInject\n  | [ H: Val.inject _ (Vptr _ _) _ |- _ ] =>\n      inv H; InvInject\n  | [ H: Val.inject_list _ nil _ |- _ ] =>\n      inv H; InvInject\n  | [ H: Val.inject_list _ (_ :: _) _ |- _ ] =>\n      inv H; InvInject\n  | _ => idtac\n  end.\n\nLemma eval_condition_inj:\n  forall cond vl1 vl2 b,\n  Val.inject_list f vl1 vl2 ->\n  eval_condition cond vl1 m1 = Some b ->\n  eval_condition cond vl2 m2 = Some b.\nProof.\n  intros. destruct cond; simpl in H0; FuncInv; InvInject; simpl; auto.\n  inv H3; inv H2; simpl in H0; inv H0; auto.\n  eauto 3 using Val.cmpu_bool_inject, Mem.valid_pointer_implies.\n  inv H3; simpl in H0; inv H0; auto.\n  eauto 3 using Val.cmpu_bool_inject, Mem.valid_pointer_implies.\n  inv H3; inv H2; simpl in H0; inv H0; auto.\n  inv H3; inv H2; simpl in H0; inv H0; auto.\n  inv H3; try discriminate; auto.\n  inv H3; try discriminate; auto.\n  inv H3; inv H2; simpl in H0; inv H0; auto.\n  inv H3; inv H2; simpl in H0; inv H0; auto.\n  inv H3; try discriminate; auto.\n  inv H3; try discriminate; auto.\nQed.\n\nLtac TrivialExists :=\n  match goal with\n  | [ |- exists v2, Some ?v1 = Some v2 /\\ Val.inject _ _ v2 ] =>\n      exists v1; split; auto\n  | _ => idtac\n  end.\n\nLemma eval_operation_inj:\n  forall op sp1 vl1 sp2 vl2 v1,\n  (forall id ofs,\n      In id (globals_operation op) ->\n      Val.inject f (Genv.symbol_address ge1 id ofs) (Genv.symbol_address ge2 id ofs)) ->\n  Val.inject f sp1 sp2 ->\n  Val.inject_list f vl1 vl2 ->\n  eval_operation ge1 sp1 op vl1 m1 = Some v1 ->\n  exists v2, eval_operation ge2 sp2 op vl2 m2 = Some v2 /\\ Val.inject f v1 v2.\nProof.\n  intros until v1; intros GL; intros. destruct op; simpl in H1; simpl; FuncInv; InvInject; TrivialExists.\n  apply GL; simpl; auto.\n  apply Val.offset_ptr_inject; auto.\n  inv H4; simpl; auto.\n  inv H4; simpl; auto.\n  apply Val.add_inject; auto.\n  apply Val.add_inject; auto.\n  apply Val.add_inject; auto. apply GL; simpl; auto.\n  apply Val.sub_inject; auto.\n  inv H4; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H3; simpl in H1; inv H1. simpl.\n    destruct (Int.eq i0 Int.zero\n         || Int.eq i (Int.repr Int.min_signed) && Int.eq i0 Int.mone); inv H2. TrivialExists.\n  inv H4; inv H3; simpl in H1; inv H1. simpl.\n  destruct (Int.eq i0 Int.zero); inv H2. TrivialExists.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int.iwordsize); auto.\n  inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int.iwordsize); auto.\n  inv H4; simpl; auto. destruct (Int.ltu i Int.iwordsize); auto.\n  inv H4; simpl in *; inv H1. destruct (Int.ltu i (Int.repr 31)); inv H2. econstructor; eauto.\n  inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int.iwordsize); auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H3; simpl in H1; inv H1. simpl.\n    destruct (Int64.eq i0 Int64.zero\n         || Int64.eq i (Int64.repr Int64.min_signed) && Int64.eq i0 Int64.mone); inv H2. TrivialExists.\n  inv H4; inv H3; simpl in H1; inv H1. simpl.\n    destruct (Int64.eq i0 Int64.zero); inv H2. TrivialExists.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int64.iwordsize'); auto.\n  inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int64.iwordsize'); auto.\n  inv H4; simpl; auto. destruct (Int.ltu i Int64.iwordsize'); auto.\n  inv H4; simpl in *; inv H1. destruct (Int.ltu i (Int.repr 63)); inv H2. econstructor; eauto.\n  inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int64.iwordsize'); auto.\n  inv H4; simpl; auto.\n  inv H4; simpl in H1; inv H1. simpl. destruct (Float.to_long f0); simpl in H2; inv H2.\n  exists (Vlong i); auto.\n  inv H4; simpl in H1; inv H1; simpl. TrivialExists.\n  inv H4; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; simpl in H1; inv H1. simpl. destruct (Float.to_int f0); simpl in H2; inv H2.\n  exists (Vint i); auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; simpl; auto.\n  subst. destruct (eval_condition c vl1 m1) eqn:?.\n  exploit eval_condition_inj; eauto. intros EQ; rewrite EQ.\n  destruct b; simpl; constructor.\n  simpl; constructor.\n  apply Val.select_inject; auto.  \n  destruct (eval_condition c vl1 m1) eqn:?; auto.\n  right; symmetry; eapply eval_condition_inj; eauto.\nQed.\n\nLemma eval_addressing_inj:\n  forall addr sp1 vl1 sp2 vl2 v1,\n  (forall id ofs,\n      In id (globals_addressing addr) ->\n      Val.inject f (Genv.symbol_address ge1 id ofs) (Genv.symbol_address ge2 id ofs)) ->\n  Val.inject f sp1 sp2 ->\n  Val.inject_list f vl1 vl2 ->\n  eval_addressing ge1 sp1 addr vl1 = Some v1 ->\n  exists v2, eval_addressing ge2 sp2 addr vl2 = Some v2 /\\ Val.inject f v1 v2.\nProof.\n  intros. destruct addr; simpl in H2; simpl; FuncInv; InvInject; TrivialExists;\n    auto using Val.add_inject, Val.offset_ptr_inject.\n  apply H; simpl; auto.\n  apply Val.add_inject; auto. apply H; simpl; auto.\nQed.\n\nEnd EVAL_COMPAT.\n\n(** Compatibility of the evaluation functions with the ``is less defined'' relation over values. *)\n\nSection EVAL_LESSDEF.\n\nVariable F V: Type.\nVariable genv: Genv.t F V.\n\nRemark valid_pointer_extends:\n  forall m1 m2, Mem.extends m1 m2 ->\n  forall b1 ofs b2 delta,\n  Some(b1, 0) = Some(b2, delta) ->\n  Mem.valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->\n  Mem.valid_pointer m2 b2 (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr delta))) = true.\nProof.\n  intros. inv H0. rewrite Ptrofs.add_zero. eapply Mem.valid_pointer_extends; eauto.\nQed.\n\nRemark weak_valid_pointer_extends:\n  forall m1 m2, Mem.extends m1 m2 ->\n  forall b1 ofs b2 delta,\n  Some(b1, 0) = Some(b2, delta) ->\n  Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->\n  Mem.weak_valid_pointer m2 b2 (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr delta))) = true.\nProof.\n  intros. inv H0. rewrite Ptrofs.add_zero. eapply Mem.weak_valid_pointer_extends; eauto.\nQed.\n\nRemark weak_valid_pointer_no_overflow_extends:\n  forall m1 b1 ofs b2 delta,\n  Some(b1, 0) = Some(b2, delta) ->\n  Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->\n  0 <= Ptrofs.unsigned ofs + Ptrofs.unsigned (Ptrofs.repr delta) <= Ptrofs.max_unsigned.\nProof.\n  intros. inv H. rewrite Z.add_0_r. apply Ptrofs.unsigned_range_2.\nQed.\n\nRemark valid_different_pointers_extends:\n  forall m1 b1 ofs1 b2 ofs2 b1' delta1 b2' delta2,\n  b1 <> b2 ->\n  Mem.valid_pointer m1 b1 (Ptrofs.unsigned ofs1) = true ->\n  Mem.valid_pointer m1 b2 (Ptrofs.unsigned ofs2) = true ->\n  Some(b1, 0) = Some (b1', delta1) ->\n  Some(b2, 0) = Some (b2', delta2) ->\n  b1' <> b2' \\/\n  Ptrofs.unsigned(Ptrofs.add ofs1 (Ptrofs.repr delta1)) <> Ptrofs.unsigned(Ptrofs.add ofs2 (Ptrofs.repr delta2)).\nProof.\n  intros. inv H2; inv H3. auto.\nQed.\n\nLemma eval_condition_lessdef:\n  forall cond vl1 vl2 b m1 m2,\n  Val.lessdef_list vl1 vl2 ->\n  Mem.extends m1 m2 ->\n  eval_condition cond vl1 m1 = Some b ->\n  eval_condition cond vl2 m2 = Some b.\nProof.\n  intros. eapply eval_condition_inj with (f := fun b => Some(b, 0)) (m1 := m1).\n  apply valid_pointer_extends; auto.\n  apply weak_valid_pointer_extends; auto.\n  apply weak_valid_pointer_no_overflow_extends; auto.\n  apply valid_different_pointers_extends; auto.\n  rewrite <- val_inject_list_lessdef. eauto. auto.\nQed.\n\nLemma eval_operation_lessdef:\n  forall sp op vl1 vl2 v1 m1 m2,\n  Val.lessdef_list vl1 vl2 ->\n  Mem.extends m1 m2 ->\n  eval_operation genv sp op vl1 m1 = Some v1 ->\n  exists v2, eval_operation genv sp op vl2 m2 = Some v2 /\\ Val.lessdef v1 v2.\nProof.\n  intros. rewrite val_inject_list_lessdef in H.\n  assert (exists v2 : val,\n          eval_operation genv sp op vl2 m2 = Some v2\n          /\\ Val.inject (fun b => Some(b, 0)) v1 v2).\n  eapply eval_operation_inj with (m1 := m1) (sp1 := sp).\n  apply valid_pointer_extends; auto.\n  apply weak_valid_pointer_extends; auto.\n  apply weak_valid_pointer_no_overflow_extends; auto.\n  apply valid_different_pointers_extends; auto.\n  intros. rewrite <- val_inject_lessdef; auto.\n  rewrite <- val_inject_lessdef; auto.\n  eauto. auto.\n  destruct H2 as [v2 [A B]]. exists v2; split; auto. rewrite val_inject_lessdef; auto.\nQed.\n\nLemma eval_addressing_lessdef:\n  forall sp addr vl1 vl2 v1,\n  Val.lessdef_list vl1 vl2 ->\n  eval_addressing genv sp addr vl1 = Some v1 ->\n  exists v2, eval_addressing genv sp addr vl2 = Some v2 /\\ Val.lessdef v1 v2.\nProof.\n  intros. rewrite val_inject_list_lessdef in H.\n  assert (exists v2 : val,\n          eval_addressing genv sp addr vl2 = Some v2\n          /\\ Val.inject (fun b => Some(b, 0)) v1 v2).\n  eapply eval_addressing_inj with (sp1 := sp).\n  intros. rewrite <- val_inject_lessdef; auto.\n  rewrite <- val_inject_lessdef; auto.\n  eauto. auto.\n  destruct H1 as [v2 [A B]]. exists v2; split; auto. rewrite val_inject_lessdef; auto.\nQed.\n\nEnd EVAL_LESSDEF.\n\n(** Compatibility of the evaluation functions with memory injections. *)\n\nSection EVAL_INJECT.\n\nVariable F V: Type.\nVariable genv: Genv.t F V.\nVariable f: meminj.\nHypothesis globals: meminj_preserves_globals genv f.\nVariable sp1: block.\nVariable sp2: block.\nVariable delta: Z.\nHypothesis sp_inj: f sp1 = Some(sp2, delta).\n\nRemark symbol_address_inject:\n  forall id ofs, Val.inject f (Genv.symbol_address genv id ofs) (Genv.symbol_address genv id ofs).\nProof.\n  intros. unfold Genv.symbol_address. destruct (Genv.find_symbol genv id) eqn:?; auto.\n  exploit (proj1 globals); eauto. intros.\n  econstructor; eauto. rewrite Ptrofs.add_zero; auto.\nQed.\n\nLemma eval_condition_inject:\n  forall cond vl1 vl2 b m1 m2,\n  Val.inject_list f vl1 vl2 ->\n  Mem.inject f m1 m2 ->\n  eval_condition cond vl1 m1 = Some b ->\n  eval_condition cond vl2 m2 = Some b.\nProof.\n  intros. eapply eval_condition_inj with (f := f) (m1 := m1); eauto.\n  intros; eapply Mem.valid_pointer_inject_val; eauto.\n  intros; eapply Mem.weak_valid_pointer_inject_val; eauto.\n  intros; eapply Mem.weak_valid_pointer_inject_no_overflow; eauto.\n  intros; eapply Mem.different_pointers_inject; eauto.\nQed.\n\nLemma eval_addressing_inject:\n  forall addr vl1 vl2 v1,\n  Val.inject_list f vl1 vl2 ->\n  eval_addressing genv (Vptr sp1 Ptrofs.zero) addr vl1 = Some v1 ->\n  exists v2,\n     eval_addressing genv (Vptr sp2 Ptrofs.zero) (shift_stack_addressing delta addr) vl2 = Some v2\n  /\\ Val.inject f v1 v2.\nProof.\n  intros.\n  rewrite eval_shift_stack_addressing.\n  eapply eval_addressing_inj with (sp1 := Vptr sp1 Ptrofs.zero); eauto.\n  intros. apply symbol_address_inject.\n  econstructor; eauto. rewrite Ptrofs.add_zero_l; auto.\nQed.\n\nLemma eval_operation_inject:\n  forall op vl1 vl2 v1 m1 m2,\n  Val.inject_list f vl1 vl2 ->\n  Mem.inject f m1 m2 ->\n  eval_operation genv (Vptr sp1 Ptrofs.zero) op vl1 m1 = Some v1 ->\n  exists v2,\n     eval_operation genv (Vptr sp2 Ptrofs.zero) (shift_stack_operation delta op) vl2 m2 = Some v2\n  /\\ Val.inject f v1 v2.\nProof.\n  intros.\n  rewrite eval_shift_stack_operation. simpl.\n  eapply eval_operation_inj with (sp1 := Vptr sp1 Ptrofs.zero) (m1 := m1); eauto.\n  intros; eapply Mem.valid_pointer_inject_val; eauto.\n  intros; eapply Mem.weak_valid_pointer_inject_val; eauto.\n  intros; eapply Mem.weak_valid_pointer_inject_no_overflow; eauto.\n  intros; eapply Mem.different_pointers_inject; eauto.\n  intros. apply symbol_address_inject.\n  econstructor; eauto. rewrite Ptrofs.add_zero_l; auto.\nQed.\n\nEnd EVAL_INJECT.\n\n(** * Masks for rotate and mask instructions *)\n\n(** Recognition of integers that are acceptable as immediate operands\n  to the [rlwim] PowerPC instruction.  These integers are of the form\n  [000011110000] or [111100001111], that is, a run of one bits\n  surrounded by zero bits, or conversely.  We recognize these integers by\n  running the following automaton on the bits.  The accepting states are\n  2, 3, 4, 5, and 6.\n<<\n               0          1          0\n              / \\        / \\        / \\\n              \\ /        \\ /        \\ /\n        -0--> [1] --1--> [2] --0--> [3]\n       /\n     [0]\n       \\\n        -1--> [4] --0--> [5] --1--> [6]\n              / \\        / \\        / \\\n              \\ /        \\ /        \\ /\n               1          0          1\n>>\n*)\n\nInductive rlw_state: Type :=\n  | RLW_S0\n  | RLW_S1\n  | RLW_S2\n  | RLW_S3\n  | RLW_S4\n  | RLW_S5\n  | RLW_S6\n  | RLW_Sbad.\n\nDefinition rlw_transition (s: rlw_state) (b: bool) : rlw_state :=\n  match s, b with\n  | RLW_S0, false => RLW_S1\n  | RLW_S0, true  => RLW_S4\n  | RLW_S1, false => RLW_S1\n  | RLW_S1, true  => RLW_S2\n  | RLW_S2, false => RLW_S3\n  | RLW_S2, true  => RLW_S2\n  | RLW_S3, false => RLW_S3\n  | RLW_S3, true  => RLW_Sbad\n  | RLW_S4, false => RLW_S5\n  | RLW_S4, true  => RLW_S4\n  | RLW_S5, false => RLW_S5\n  | RLW_S5, true  => RLW_S6\n  | RLW_S6, false => RLW_Sbad\n  | RLW_S6, true  => RLW_S6\n  | RLW_Sbad, _ => RLW_Sbad\n  end.\n\nDefinition rlw_accepting (s: rlw_state) : bool :=\n  match s with\n  | RLW_S0 => false\n  | RLW_S1 => false\n  | RLW_S2 => true\n  | RLW_S3 => true\n  | RLW_S4 => true\n  | RLW_S5 => true\n  | RLW_S6 => true\n  | RLW_Sbad => false\n  end.\n\nFixpoint is_mask_rec {A: Type} (trans: A -> bool -> A) (accept: A -> bool)\n                     (n: nat) (s: A) (x: Z) {struct n} : bool :=\n  match n with\n  | O =>\n      accept s\n  | S m =>\n      is_mask_rec trans accept m (trans s (Z.odd x)) (Z.div2 x)\n  end.\n\nDefinition is_rlw_mask (x: int) : bool :=\n  is_mask_rec rlw_transition rlw_accepting Int.wordsize RLW_S0 (Int.unsigned x).\n\n(** For the 64-bit [rldicl] and [rldicr] instructions, the acceptable\n  masks are (in big endian):\n- for [rldicl]: masks that clear the leftmost bits (most significant bits),\n  that is, [00000011111], that is, ones in the low bits followed by zeros\n  in the high bits;\n- for [rldicr]: masks that clear the rightmost bits (least significant bits),\n  that is, [11110000000], that is, zeros in the low bits followed by ones\n  in the high bits.\n\n  All ones  is OK, but not all zeroes.\n\n  The corresponding automata for [rldicl] is\n<<\n                 1          0\n                / \\        / \\\n                \\ /        \\ /      (accepting: [1], [2])\n     [0] --1--> [1] --0--> [2]\n>>\n  The automata for [rldicr] is\n<<\n      0          1\n     / \\        / \\\n     \\ /        \\ /          (accepting: [1])\n     [0] --1--> [1]\n>>\n*)\n\nInductive rll_state: Type := RLL_S0 | RLL_S1 | RLL_S2 | RLL_Sbad.\n\nDefinition rll_transition (s: rll_state) (b: bool) : rll_state :=\n  match s, b with\n  | RLL_S0, true => RLL_S1\n  | RLL_S1, false => RLL_S2\n  | RLL_S1, true => RLL_S1\n  | RLL_S2, false => RLL_S2\n  | _, _ => RLL_Sbad\n  end.\n\nDefinition rll_accepting (s: rll_state) : bool :=\n  match s with\n  | RLL_S1 | RLL_S2 => true\n  | _ => false\n  end.\n\nInductive rlr_state: Type := RLR_S0 | RLR_S1 | RLR_Sbad.\n\nDefinition rlr_transition (s: rlr_state) (b: bool) : rlr_state :=\n  match s, b with\n  | RLR_S0, false => RLR_S0\n  | RLR_S0, true => RLR_S1\n  | RLR_S1, true => RLR_S1\n  | _, _ => RLR_Sbad\n  end.\n\nDefinition rlr_accepting (s: rlr_state) : bool :=\n  match s with\n  | RLR_S1 => true\n  | _ => false\n  end.\n\nDefinition is_rldl_mask (x: int64) : bool :=    (*r 0s in the high bits, 1s in the low bits *)\n  is_mask_rec rll_transition rll_accepting Int64.wordsize RLL_S0 (Int64.unsigned x).\n\nDefinition is_rldr_mask (x: int64) : bool :=    (*r 1s in the high bits, 0s in the low bits *)\n  is_mask_rec rlr_transition rlr_accepting Int64.wordsize RLR_S0 (Int64.unsigned x).\n\n(** * Handling of builtin arguments *)\n\nDefinition builtin_arg_ok_1\n       (A: Type) (ba: builtin_arg A) (c: builtin_arg_constraint) :=\n  match c, ba with\n  | OK_all, _ => true\n  | OK_const, (BA_int _ | BA_long _ | BA_float _ | BA_single _) => true\n  | OK_addrstack, BA_addrstack _ => true\n  | OK_addressing, BA_addrstack _ => true\n  | OK_addressing, BA_addrglobal _ _ => true\n  | OK_addressing, BA_addptr (BA _) (BA_int _) => true\n  | OK_addressing, BA_addptr (BA_addrglobal _ _) (BA _) => true\n  | OK_addressing, BA_addptr (BA _) (BA _) => true\n  | _, _ => false\n  end.\n\nDefinition builtin_arg_ok\n       (A: Type) (ba: builtin_arg A) (c: builtin_arg_constraint) :=\n  match ba with\n  | (BA _ | BA_splitlong (BA _) (BA _)) => true\n  | _ => builtin_arg_ok_1 ba c\n  end.  \n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/powerpc/Op.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2354575046999239}}
{"text": "Require Import ClassicalDescription Omega.\n\nFrom hahn Require Import Hahn.\nRequire Import Events.\nRequire Import Execution.\nRequire Import Prog.\nRequire Import ProgToExecution.\nRequire Import ProgToExecutionProperties.\nRequire Import RMWinstrProps.\n\nSet Implicit Arguments.\n\n(******************************************************************************)\n(** **  *)\n(******************************************************************************)\n\nLemma ectrl_ctrl_step (tid : thread_id) \n         s s' (STEP : step tid s s')\n         MOD (ECTRL: exists a, (MOD ∩₁ ectrl s') a)\n        (NCTRL: MOD ∩₁ dom_rel (s'.(G).(ctrl)) ⊆₁ ∅) :\n         s.(G) = s'.(G).\nProof using.\ndestruct STEP; desc.\nred in H; desc.\ndestruct ISTEP0; try done.\nall: exfalso; eapply NCTRL.\nall: revert ECTRL;  unfolder; splits; try edone.\nall: desc; eauto; exists (ThreadEvent tid (eindex s)).\nall: rewrite UG; unfold add; ins; rewrite <- UECTRL; basic_solver.\nQed.\n\n\nLemma TWF_helper tid s1 (TWF : thread_wf tid s1): \n~ acts_set s1.(G) (ThreadEvent tid (s1.(eindex))).\nProof using.\nred in TWF.\nintro.\nspecialize (TWF (ThreadEvent tid (eindex s1)) H); desf.\nomega.\nQed.\n\nLemma TWF_helper_rmw tid s1 (TWF : thread_wf tid s1): \n~ acts_set s1.(G) (ThreadEvent tid (s1.(eindex) + 1)).\nProof using.\nred in TWF.\nintro.\nspecialize (TWF (ThreadEvent tid (eindex s1 +1)) H); desf.\nomega.\nQed.\n\n\nLemma acts_increasing (tid : thread_id) s s' (STEP : step tid s s') :\n  s.(G).(acts_set) ⊆₁ s'.(G).(acts_set).\nProof using.\ndestruct STEP; desc.\nred in H; desc.\ndestruct ISTEP0.\nall: rewrite UG; try done.\nall: unfold add, add_rmw, acts_set; ins.\nall: unfolder; ins; desc; eauto.\nQed.\n\nLemma is_r_ex_increasing (tid : thread_id) s s' (STEP : step tid s s') (TWF : thread_wf tid s):\n  s.(G).(acts_set) ∩₁ R_ex s.(G).(lab) ⊆₁ R_ex s'.(G).(lab).\nProof using.\ndestruct STEP; desc.\nred in H; desc.\ndestruct ISTEP0.\nall: rewrite UG; try done.\nall: unfold add, add_rmw, R_ex; ins.\nall: unfolder; ins; desc; eauto.\nall: rewrite !updo; try done.\nall: try by (intro; subst; eapply TWF_helper; edone).\nall: try by (intro; subst; eapply TWF_helper_rmw; edone).\nQed.\n\nLemma is_r_increasing (tid : thread_id) s s' (STEP : step tid s s') (TWF : thread_wf tid s):\n  s.(G).(acts_set) ∩₁ is_r s.(G).(lab) ⊆₁ is_r s'.(G).(lab).\nProof using.\ndestruct STEP; desc.\nred in H; desc.\ndestruct ISTEP0.\nall: rewrite UG; try done.\nall: unfold add, add_rmw, is_r; ins.\nall: unfolder; ins; desc; eauto.\nall: rewrite !updo; try done.\nall: try by (intro; subst; eapply TWF_helper; edone).\nall: try by (intro; subst; eapply TWF_helper_rmw; edone).\nQed.\n\n\nLemma is_w_increasing (tid : thread_id) s s' (STEP : step tid s s') (TWF : thread_wf tid s):\n  s.(G).(acts_set) ∩₁ is_w s.(G).(lab) ⊆₁ is_w s'.(G).(lab).\nProof using.\ndestruct STEP; desc.\nred in H; desc.\ndestruct ISTEP0.\nall: rewrite UG; try done.\nall: unfold add, add_rmw, is_w; ins.\nall: unfolder; ins; desc; eauto.\nall: rewrite !updo; try done.\nall: try by (intro; subst; eapply TWF_helper; edone).\nall: try by (intro; subst; eapply TWF_helper_rmw; edone).\nQed.\n\n(******************************************************************************)\n(** **  *)\n(******************************************************************************)\n\nLemma regf_expr_helper regf regf' depf MOD expr\n  (REGF : forall reg, RegFun.find reg regf = RegFun.find reg regf' \\/ \n           (exists a, RegFun.find reg depf a /\\ MOD a))\n  (NDEP: forall a (IN: MOD a), ~ DepsFile.expr_deps depf expr a):\n  RegFile.eval_expr regf expr = RegFile.eval_expr regf' expr.\nProof using.\nunfold DepsFile.expr_deps, DepsFile.val_deps in NDEP.\nunfold RegFile.eval_expr, RegFile.eval_value.\ndestruct expr.\n- destruct val; [by vauto| specialize (REGF reg); desf].\n  exfalso; eapply NDEP; edone.\n- destruct op0; [by vauto| specialize (REGF reg); desf].\n  rewrite REGF; auto.\n  exfalso; eapply NDEP; edone.\n- destruct op1, op2.\n* by vauto.\n* specialize (REGF reg); desf; [rewrite REGF|]; eauto.\n  exfalso; eapply NDEP; [edone| basic_solver].\n* specialize (REGF reg); desf; [rewrite REGF|]; eauto. \n  exfalso; eapply NDEP; [edone| basic_solver].\n* generalize (REGF reg0); intro REGF0. \n  specialize (REGF reg).\n  desf.\n  by rewrite REGF, REGF0; auto.\n  all: exfalso; eapply NDEP; [edone| basic_solver].\nQed.\n\nLemma regf_lexpr_helper regf regf' depf MOD expr\n  (REGF : forall reg, RegFun.find reg regf = RegFun.find reg regf' \\/ \n            (exists a, RegFun.find reg depf a /\\ MOD a))\n  (NDEP: forall a (IN: MOD a), ~ DepsFile.lexpr_deps depf expr a):\n  RegFile.eval_lexpr regf expr = RegFile.eval_lexpr regf' expr.\nProof using.\nunfold DepsFile.lexpr_deps in NDEP.\nunfold RegFile.eval_lexpr.\ndesf; exfalso; apply n; erewrite regf_expr_helper; eauto.\nins; specialize (REGF reg); desf; eauto.\nQed.\n\n(******************************************************************************)\n(** **  *)\n(******************************************************************************)\n\nDefinition sim_execution G G' MOD :=\n      ⟪ ACTS : G.(acts) = G'.(acts) ⟫ /\\\n      ⟪ SAME : same_lab_u2v G'.(lab) G.(lab) ⟫ /\\\n      ⟪ OLD_VAL : forall a (NIN: ~ MOD a), val (G'.(lab)) a = val (G.(lab)) a ⟫ /\\\n      ⟪ RMW  : G.(rmw)  ≡ G'.(rmw)  ⟫ /\\\n      ⟪ DATA : G.(data) ≡ G'.(data) ⟫ /\\\n      ⟪ ADDR : G.(addr) ≡ G'.(addr) ⟫ /\\\n      ⟪ CTRL : G.(ctrl) ≡ G'.(ctrl) ⟫ /\\\n      ⟪ FRMW : G.(rmw_dep) ≡ G'.(rmw_dep) ⟫ /\\\n      ⟪ RRF : G.(rf) ≡ G'.(rf) ⟫ /\\\n      ⟪ RCO : G.(co) ≡ G'.(co) ⟫.\n\nDefinition sim_state s s' MOD (new_rfi : relation actid) new_val := \n      ⟪ INSTRS  : s.(instrs) = s'.(instrs) ⟫ /\\\n      ⟪ PC  : s.(pc) = s'.(pc) ⟫ /\\\n      ⟪ EXEC : sim_execution s.(G) s'.(G) MOD ⟫ /\\\n      ⟪ EINDEX  : s.(eindex) = s'.(eindex) ⟫ /\\\n      ⟪ REGF  : forall reg, RegFun.find reg s.(regf) = RegFun.find reg s'.(regf) \\/ \nexists a, (RegFun.find reg s.(depf)) a /\\ MOD a ⟫ /\\\n      ⟪ DEPF  : s.(depf) = s'.(depf) ⟫ /\\\n      ⟪ ECTRL  : s.(ectrl) = s'.(ectrl) ⟫ /\\\n      ⟪ NEW_VAL1 : forall r w (RF: new_rfi w r) (INr: s'.(G).(acts_set) r) \n(INw: s'.(G).(acts_set) w) (READ: is_r s'.(G).(lab) r) (WRITE: is_w s'.(G).(lab) w) (IN_MOD: MOD r), \n                     val (s'.(G).(lab)) r = val (s'.(G).(lab)) w ⟫ /\\\n      ⟪ NEW_VAL2 : forall r (READ: is_r s'.(G).(lab) r) (IN_MOD: MOD r) \n                     (IN: s'.(G).(acts_set) r) (NIN_NEW_RF: ~ (codom_rel new_rfi) r), \n                     val (s'.(G).(lab)) r = Some (new_val r) ⟫.\n\nLemma sim_execution_same_r G G' MOD (EXEC: sim_execution G G' MOD) :\nis_r G'.(lab) ≡₁ is_r G.(lab).\nProof using.\nred in EXEC; desf.\neby erewrite same_lab_u2v_is_r.\nQed.\n\nLemma sim_execution_same_w G G' MOD (EXEC: sim_execution G G' MOD) :\nis_w G'.(lab) ≡₁ is_w G.(lab).\nProof using.\nred in EXEC; desf.\neby erewrite same_lab_u2v_is_w.\nQed.\n\nLemma sim_execution_same_acts G G' MOD (EXEC: sim_execution G G' MOD) :\nacts_set G ≡₁ acts_set G'.\nProof using.\nred in EXEC; desf.\nunfold acts_set; rewrite ACTS; basic_solver.\nQed.\n\n(******************************************************************************)\n(** **  *)\n(******************************************************************************)\n\nLemma receptiveness_sim_assign (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (reg : Reg.t) (expr : Instr.expr)\n  (ISTEP : Some (Instr.assign reg expr) = nth_error (instrs s1) (pc s1))\n  (UPC : pc s2 = pc s1 + 1) (UG : G s2 = G s1)\n  (UINDEX : eindex s2 = eindex s1)\n  (UREGS : regf s2 = RegFun.add reg (RegFile.eval_expr (regf s1) expr) (regf s1))\n  (UDEPS : depf s2 = RegFun.add reg (DepsFile.expr_deps (depf s1) expr) (depf s1))\n  (UECTRL : ectrl s2 = ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\ndo 7 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eby eexists; splits; [ rewrite <- INSTRS, <- PC| eapply assign; reflexivity].\n  * ins; congruence.\n  * ins; congruence.\n  * ins; congruence.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf.\n    destruct (classic ((exists a : actid, DepsFile.expr_deps (depf s1) expr a /\\ MOD a))) as [A|A].\n    by auto.\n    by left; apply (regf_expr_helper (regf s1) (regf s1') (depf s1) MOD expr REGF); eauto.\n  * ins; congruence.\n  * ins; congruence.\n  * by ins; apply NEW_VAL1; try done; rewrite <- UG.\n  * by ins; apply NEW_VAL2; try done; rewrite <- UG.\nQed.\n\nLemma receptiveness_sim_if_else (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (expr : Instr.expr) (shift : nat)\n  (e : RegFile.eval_expr (regf s1) expr = 0)\n  (ISTEP : Some (Instr.ifgoto expr shift) = nth_error (instrs s1) (pc s1))\n  (UPC : pc s2 = pc s1 + 1) (UG : G s2 = G s1)\n  (UINDEX : eindex s2 = eindex s1)\n  (UREGS : regf s2 = regf s1)\n  (UDEPS : depf s2 = depf s1)\n  (UECTRL : ectrl s2 = DepsFile.expr_deps (depf s1) expr ∪₁ ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  (NCTRL : MOD ∩₁ ectrl s2 ⊆₁ ∅)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\neexists.\n  exists (if Const.eq_dec (RegFile.eval_expr (regf s1') expr) 0\n        then pc s1' + 1 else shift).\n  do 5 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC|].\n    eapply if_; try reflexivity; ins; desf.\n  * ins; congruence.\n  * ins.\n    erewrite <- regf_expr_helper with (regf:= regf s1).\n    desf; congruence.\n    eauto.\n    ins; intro; eapply NCTRL; rewrite UECTRL; basic_solver.\n  * ins; congruence.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS; eauto.\n  * ins; congruence.\n  * ins; congruence.\n  * by ins; apply NEW_VAL1; try done; rewrite <- UG.\n  * by ins; apply NEW_VAL2; try done; rewrite <- UG.\nQed.\n\nLemma receptiveness_sim_if_then (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (expr : Instr.expr) (shift : nat)\n  (n : RegFile.eval_expr (regf s1) expr <> 0)\n  (ISTEP : Some (Instr.ifgoto expr shift) = nth_error (instrs s1) (pc s1))\n  (UPC : pc s2 = shift) (UG : G s2 = G s1)\n  (UINDEX : eindex s2 = eindex s1)\n  (UREGS : regf s2 = regf s1)\n  (UDEPS : depf s2 = depf s1)\n  (UECTRL : ectrl s2 = DepsFile.expr_deps (depf s1) expr ∪₁ ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  (NCTRL : MOD ∩₁ ectrl s2 ⊆₁ ∅)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\n eexists.\n  exists (if Const.eq_dec (RegFile.eval_expr (regf s1') expr) 0\n        then pc s1' + 1 else shift).\n  do 5 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC|].\n    eapply if_; try reflexivity; ins; desf.\n  * ins; congruence.\n  * ins.\n    erewrite <- regf_expr_helper with (regf:= regf s1).\n    desf; congruence.\n    eauto.\n    ins; intro; eapply NCTRL; rewrite UECTRL; basic_solver.\n  * ins; congruence.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS; eauto.\n  * ins; congruence.\n  * ins; congruence.\n  * by ins; apply NEW_VAL1; try done; rewrite <- UG.\n  * by ins; apply NEW_VAL2; try done; rewrite <- UG.\nQed.\n\nDefinition new_rfi_ex (new_rfi :relation actid) :=\nnew_rfi ∪ ⦗ set_compl (codom_rel new_rfi) ⦘.\n\nLemma new_rfi_unique (new_rfi : relation actid)\n      (new_rfif : functional new_rfi⁻¹):\nforall r, exists ! w, (new_rfi_ex new_rfi)⁻¹  r w.\nProof using.\nins.\ndestruct (classic ((codom_rel new_rfi) r)) as [X|X].\n- unfolder in X; desf.\nexists x; red; splits.\nunfold new_rfi_ex; basic_solver 12.\nunfold new_rfi_ex; unfolder; ins; desf.\neapply new_rfif; basic_solver.\nexfalso; eauto.\n- exists r; red; splits.\nunfold new_rfi_ex; basic_solver 12.\nunfold new_rfi_ex; unfolder; ins; desf.\nunfolder in X; exfalso; eauto.\nQed.\n\nDefinition new_write new_rfi new_rfif := \n  unique_choice (new_rfi_ex new_rfi)⁻¹ (@new_rfi_unique new_rfi new_rfif).\n\nDefinition get_val (v: option value) := \n  match v with | Some v => v | _ => 0 end.\n\nLemma RFI_index_helper tid s new_rfi (TWF : thread_wf tid s)\n   (RFI_INDEX : new_rfi ⊆ ext_sb)\n   w r (RFI: new_rfi w r) \n  (IN: ThreadEvent tid s.(eindex) = r \\/ In r s.(G).(acts)) :\n   w <> ThreadEvent tid (s.(eindex)).\nProof using.\nintro; subst; desf.\napply RFI_INDEX in RFI.\neby eapply ext_sb_irr.\nspecialize (TWF r IN); desf.\napply RFI_INDEX in RFI.\nunfold sb, ext_sb in RFI; unfolder in RFI; desf; omega.\nQed.\n\nLemma receptiveness_sim_load (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (ord : mode) (reg : Reg.t)\n  (lexpr : Instr.lexpr) (ISTEP : Some (Instr.load ord reg lexpr) = nth_error (instrs s1) (pc s1))\n  (val_ : value) (UPC : pc s2 = pc s1 + 1)\n  (UG : G s2 =\n     add (G s1) tid (eindex s1)\n       (Aload false ord (RegFile.eval_lexpr (regf s1) lexpr) val_) \n       ∅ (DepsFile.lexpr_deps (depf s1) lexpr) (ectrl s1) \n       ∅)\n  (UINDEX : eindex s2 = eindex s1 + 1)\n  (UREGS : regf s2 = RegFun.add reg val_ (regf s1))\n  (UDEPS : depf s2 = RegFun.add reg (eq (ThreadEvent tid (eindex s1))) (depf s1))\n  (UECTRL : ectrl s2 = ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  (NADDR : MOD ∩₁ dom_rel (s2.(G).(addr)) ⊆₁ ∅)\n  (RFI_INDEX : new_rfi ⊆ ext_sb)\n  (TWF : thread_wf tid s1)\n  (new_rfif : functional new_rfi⁻¹)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\ngeneralize (@new_write new_rfi new_rfif); intro F; destruct F as [new_w F].\nred in SIM; desc.\n\nassert (SAME_LOC: RegFile.eval_lexpr (regf s1) lexpr = RegFile.eval_lexpr (regf s1') lexpr).\n{ ins; eapply regf_lexpr_helper; eauto.\nins; intro; eapply NADDR; unfolder; splits; eauto.\nexists (ThreadEvent tid (eindex s1)).\nrewrite UG; unfold add; basic_solver. } \n\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\n\ndo 7 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply load with (val := \n      if excluded_middle_informative (MOD (ThreadEvent tid (eindex s1'))) \n      then if excluded_middle_informative ((codom_rel new_rfi) (ThreadEvent tid (eindex s1'))) \n           then (get_val (val s1'.(G).(lab) (new_w (ThreadEvent tid (eindex s1')))))\n           else (new_val (ThreadEvent tid (eindex s1')))\n      else val_);\n    reflexivity.\n  * ins; congruence.\n  * ins; congruence.\n  * ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG.\n    red in EXEC; desc.\n    red; splits; ins.\n    + by rewrite EINDEX, ACTS.\n    + rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      { by subst; rewrite !upds. }\n      ins. rewrite !updo; auto.\n    + rewrite EINDEX.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))).\n      by desf; unfold val; rewrite !upds.\n      unfold val; rewrite !updo; [|intro; desf|intro; desf].\n      by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN.\n    + by rewrite DATA, EINDEX.\n    + by rewrite ADDR, EINDEX, DEPF.\n    + by rewrite CTRL, EINDEX, ECTRL.\n    + by rewrite FRMW, EINDEX.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto.\n  * eby ins; rewrite <- DEPF, <- EINDEX.\n  * ins; congruence.\n  * simpl; ins.\n     unfold add, acts_set in INw; ins.\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    + exfalso; eapply RFI_index_helper.\n      edone.\n      eapply RFI_INDEX.\n      edone.\n      unfold add, acts_set in INr; ins.\n      rewrite EINDEX; destruct INr; [eauto|].\n      right; eapply sim_execution_same_acts; eauto.\n      by rewrite EINDEX.\n    + destruct INw as [X|INw]; [desf|].\n      destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n      -- unfold val in *; rewrite !upds.\n         rewrite !updo; try done.\n         destruct (excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))); [|desf].\n         destruct (excluded_middle_informative (codom_rel new_rfi (ThreadEvent tid (eindex s1')))).\n         2: by exfalso; apply n0; basic_solver 12.\n         assert (w = new_w (ThreadEvent tid (eindex s1'))).\n         { assert (U: exists ! w1 : actid, (new_rfi_ex new_rfi)⁻¹ (ThreadEvent tid (eindex s1')) w1).\n           apply new_rfi_unique, new_rfif.\n           eapply unique_existence with \n           (P:= fun x => (@new_rfi_ex new_rfi)⁻¹ (ThreadEvent tid (eindex s1')) x) in U; desc.\n           eapply U0.\n           unfold new_rfi_ex.\n           basic_solver.\n           apply F. }\n         unfold is_w in WRITE; rewrite updo in WRITE; desf.\n      -- unfold val in *; rewrite !updo; try done.\n         eapply NEW_VAL1; try edone.\n         unfold add, acts_set in INr; ins; desf.\n         by unfold is_r in *; rewrite updo in READ.\n         by unfold is_w in *; rewrite updo in WRITE.\n  * simpl; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    + destruct (excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))); [subst|desf].\n      destruct (excluded_middle_informative (codom_rel new_rfi (ThreadEvent tid (eindex s1')))); [desf|].\n      by unfold val in *; rewrite !upds.\n    + unfold val in *; rewrite !updo; try done.\n      apply NEW_VAL2; try done.\n      by unfold is_r in *; rewrite updo in READ.\n      by unfold add, acts_set in IN; ins; desf.\nQed.\n\nLemma receptiveness_sim_store (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (ord : mode) (reg : Reg.t)\n  (lexpr : Instr.lexpr) (expr : Instr.expr)\n  (ISTEP : Some (Instr.store ord lexpr expr) = nth_error (instrs s1) (pc s1))\n  (UPC : pc s2 = pc s1 + 1)\n  (UG : G s2 = add (G s1) tid (eindex s1)\n         (Astore Xpln ord (RegFile.eval_lexpr (regf s1) lexpr) (RegFile.eval_expr (regf s1) expr)) \n         (DepsFile.expr_deps (depf s1) expr) (DepsFile.lexpr_deps (depf s1) lexpr) (ectrl s1) ∅) \n  (UINDEX : eindex s2 = eindex s1 + 1)\n  (UREGS : regf s2 = regf s1)\n  (UDEPS : depf s2 = depf s1)\n  (UECTRL : ectrl s2 = ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  (NADDR : MOD ∩₁ dom_rel (s2.(G).(addr)) ⊆₁ ∅)\n  (NDATA: ⦗MOD⦘ ⨾ s2.(G).(data) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂)\n   (RFI_INDEX : new_rfi ⊆ ext_sb)\n  (TWF : thread_wf tid s1)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\n\nassert (SAME_LOC: RegFile.eval_lexpr (regf s1) lexpr = RegFile.eval_lexpr (regf s1') lexpr).\n{ ins; eapply regf_lexpr_helper; eauto.\nins; intro; eapply NADDR; unfolder; splits; eauto.\nexists (ThreadEvent tid (eindex s1)).\nrewrite UG; unfold add; basic_solver. } \n\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\n\n do 7 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply store; reflexivity.\n  * ins; congruence.\n  * ins; congruence.\n  * ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG.\n    red in EXEC; desc.\n    red; splits; ins.\n    + by rewrite EINDEX, ACTS.\n    + rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      { by subst; rewrite !upds. }\n      rewrite !updo; auto.\n    + rewrite EINDEX.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))); subst.\n      -- desf; unfold val; rewrite !upds.\n         erewrite regf_expr_helper; try edone.\n         intro reg0; specialize (REGF reg0); desf; eauto.\n         ins; intro DEPS; eapply NDATA; unfolder; splits; eauto.\n         by rewrite EINDEX.\n      -- unfold val;  rewrite !updo; try done.\n         by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN.\n    + by rewrite DATA, EINDEX, DEPF.\n    + by rewrite ADDR, EINDEX, DEPF.\n    + by rewrite CTRL, EINDEX, ECTRL.\n    + by rewrite FRMW, EINDEX.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto.\n  * by ins; rewrite <- DEPF, <- UDEPS.\n  * ins; congruence.\n  * simpl; ins.\n    unfold add, acts_set in INw; ins.\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    + exfalso; eapply RFI_index_helper.\n      edone.\n      eapply RFI_INDEX.\n      edone.\n      unfold add, acts_set in INr; ins.\n      rewrite EINDEX; destruct INr; [eauto|].\n      right; eapply sim_execution_same_acts; eauto.\n      by rewrite EINDEX.\n    + destruct INw as [X|INw]; [desf|].\n      destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n      by unfold is_r in *; rewrite !upds in READ; desf.\n      unfold val in *; rewrite !updo; try done.\n      eapply NEW_VAL1; try edone.\n      by  unfold add, acts_set in INr; ins; desf.\n      by unfold is_r in *; rewrite updo in READ.\n      by unfold is_w in *; rewrite updo in WRITE.\n  * simpl; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    by unfold is_r in *; rewrite upds in READ; desf.\n    unfold val; rewrite updo; try done.\n    apply NEW_VAL2; try done.\n    unfold is_r in *; rewrite updo in READ; try done.\n    by unfold add, acts_set in IN; ins; desf.\nQed.\n\nLemma receptiveness_sim_fence (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (ord : mode) \n  (ISTEP : Some (Instr.fence ord) = nth_error (instrs s1) (pc s1))\n  (UPC : pc s2 = pc s1 + 1)\n  (UG : G s2 = add (G s1) tid (eindex s1) (Afence ord) ∅ ∅ (ectrl s1) ∅)\n  (UINDEX : eindex s2 = eindex s1 + 1)\n  (UREGS : regf s2 = regf s1)\n  (UDEPS : depf s2 = depf s1)\n  (UECTRL : ectrl s2 = ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\n\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\n\ndo 7 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply fence; reflexivity.\n  * ins; congruence.\n  * ins; congruence.\n  * ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG.\n    red in EXEC; desc.\n    red; splits; ins.\n    + by rewrite EINDEX, ACTS.\n    + rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      { by subst; rewrite !upds. }\n      rewrite !updo; auto.\n    + rewrite EINDEX.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))).\n      by desf; unfold val; rewrite !upds.\n      unfold val; rewrite !updo; [|intro; desf|intro; desf].\n      by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN.\n    + by rewrite DATA, EINDEX.\n    + by rewrite ADDR, EINDEX.\n    + by rewrite CTRL, EINDEX, ECTRL.\n    + by rewrite FRMW, EINDEX.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto.\n  * by ins; rewrite <- DEPF, <- UDEPS.\n  * ins; congruence.\n  * ins.\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    by unfold is_w in WRITE; rewrite upds in WRITE; desf.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    by unfold is_r in READ; rewrite upds in READ; desf.\n    unfold val; rewrite !updo; try done.\n    eapply NEW_VAL1; try edone.\n    unfold add, acts_set in INr; ins; desf.\n    rewrite <- EINDEX in n0; desf.\n    unfold add, acts_set in INw; ins; desf.\n    rewrite <- EINDEX in n; desf.\n    red in EXEC; desf.\n    unfold is_r in *; rewrite updo in READ; try edone.\n    unfold is_w in *; rewrite updo in WRITE; try edone.\n  * simpl; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    by unfold is_r in *; rewrite upds in READ; desf.\n    unfold val; rewrite updo; try done.\n    apply NEW_VAL2; try done.\n    unfold is_r in *; rewrite updo in READ; try done.\n    by unfold add, acts_set in IN; ins; desf.\nQed.\n\nLemma receptiveness_sim_cas_fail (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (CASREX : cas_produces_R_ex_instrs (instrs s1))\n  (expr_old expr_new : Instr.expr)\n  rexmod\n  xmod\n  (ordr ordw : mode)\n  (reg : Reg.t)\n  (lexpr : Instr.lexpr)\n  (ISTEP : Some (Instr.update (Instr.cas expr_old expr_new) rexmod xmod ordr ordw reg lexpr) =\n           nth_error (instrs s1) (pc s1))\n  (val_ : value)\n  (NEXPECTED : val_ <> RegFile.eval_expr (regf s1) expr_old)\n  (UPC : pc s2 = pc s1 + 1)\n  (UG : G s2 =\n        add (G s1) tid (eindex s1)\n            (Aload rexmod ordr (RegFile.eval_lexpr (regf s1) lexpr) val_) \n            ∅ (DepsFile.lexpr_deps (depf s1) lexpr) (ectrl s1)\n            (DepsFile.expr_deps (depf s1) expr_old))\n  (UINDEX : eindex s2 = eindex s1 + 1)\n  (UREGS : regf s2 = RegFun.add reg val_ (regf s1))\n  (UDEPS : depf s2 = RegFun.add reg (eq (ThreadEvent tid (eindex s1))) (depf s1))\n  (UECTRL : ectrl s2 = ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  (NFRMW: MOD ∩₁ dom_rel (s2.(G).(rmw_dep)) ⊆₁ ∅)\n  (NADDR : MOD ∩₁ dom_rel (s2.(G).(addr)) ⊆₁ ∅)\n  (NREX:  MOD ∩₁ s2.(G).(acts_set) ∩₁ (R_ex s2.(G).(lab)) ⊆₁ ∅) \n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n  exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\nassert (rexmod = true); subst.\n{ clear -ISTEP CASREX. red in CASREX.\n  set (AA:=ISTEP).\n  symmetry in AA. apply nth_error_In in AA.\n  apply CASREX in AA. red in AA. desf. }\n\nassert (SAME_LOC: RegFile.eval_lexpr (regf s1) lexpr = RegFile.eval_lexpr (regf s1') lexpr).\n{ eapply regf_lexpr_helper; eauto.\nins; intro; eapply NADDR; unfolder; splits; eauto.\nexists (ThreadEvent tid (eindex s1)).\nrewrite UG; unfold add; basic_solver. } \n\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\n\ndo 7 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply cas_un with (val := val_); try reflexivity.\n    erewrite <- regf_expr_helper with (regf := (regf s1)); try edone.\n    ins; intro;  eapply NFRMW; rewrite UG; unfold add; ins; basic_solver.\n  * ins; congruence.\n  * ins; congruence.\n  * ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG.\n    red in EXEC; desc.\n    red; splits; ins.\n    + by rewrite EINDEX, ACTS.\n    + rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      { by subst; rewrite !upds; rewrite SAME_LOC. }\n      rewrite !updo; auto.\n    + rewrite EINDEX.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))).\n      rewrite SAME_LOC.\n      by desf; unfold val; rewrite !upds.\n      unfold val; rewrite !updo; [|intro; desf|intro; desf].\n      by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN.\n    + by rewrite DATA, EINDEX.\n    + by rewrite ADDR, EINDEX, DEPF.\n    + by rewrite CTRL, EINDEX, ECTRL.\n    + by rewrite FRMW, EINDEX, DEPF.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto.\n  * eby ins; rewrite <- DEPF, <- EINDEX.\n  * ins; congruence.\n  * ins.\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    by unfold is_w in WRITE; rewrite upds in WRITE; desf.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    + exfalso.\n      eapply NREX; split; [eauto|].\n      rewrite UG; unfold add; unfold acts_set; ins.\n      split; [eauto| rewrite EINDEX; eauto].\n      rewrite UG; unfold add; unfold R_ex; ins.\n      by rewrite EINDEX, upds.\n    + unfold val; rewrite !updo; try done.\n      eapply NEW_VAL1; try edone.\n      unfold add, acts_set in INr; ins; desf.\n      rewrite <- EINDEX in n0; desf.\n      unfold add, acts_set in INw; ins; desf.\n      rewrite <- EINDEX in n; desf.\n      red in EXEC; desf.\n      unfold is_r in *; rewrite updo in READ; try edone.\n      unfold is_w in *; rewrite updo in WRITE; try edone.\n  * simpl; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    + exfalso.\n      eapply NREX; split; [eauto|].\n      rewrite UG; unfold add; unfold acts_set; ins.\n      split; [eauto| rewrite EINDEX; eauto].\n      rewrite UG; unfold add; unfold R_ex; ins.\n      by rewrite EINDEX, upds.\n    + unfold val; rewrite updo; try done.\n      apply NEW_VAL2; try done.\n      unfold is_r in *; rewrite updo in READ; try done.\n      by unfold add, acts_set in IN; ins; desf.\nQed.\n\nLemma receptiveness_sim_cas_suc (tid : thread_id)\n  s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n  (CASREX : cas_produces_R_ex_instrs (instrs s1))\n  (expr_old expr_new : Instr.expr)\n  rexmod xmod\n  (ordr ordw : mode)\n  (reg : Reg.t)\n  (lexpr : Instr.lexpr)\n  (ISTEP : Some (Instr.update (Instr.cas expr_old expr_new) rexmod xmod ordr ordw reg lexpr) =\n           nth_error (instrs s1) (pc s1))\n  (UPC : pc s2 = pc s1 + 1)\n  (UG : G s2 =\n        add_rmw (G s1) tid (eindex s1)\n                (Aload rexmod ordr (RegFile.eval_lexpr (regf s1) lexpr)\n                       (RegFile.eval_expr (regf s1) expr_old))\n                (Astore xmod ordw (RegFile.eval_lexpr (regf s1) lexpr)\n                        (RegFile.eval_expr (regf s1) expr_new))\n                (DepsFile.expr_deps (depf s1) expr_new)\n                (DepsFile.lexpr_deps (depf s1) lexpr) (ectrl s1)\n                (DepsFile.expr_deps (depf s1) expr_old))\n  (UINDEX : eindex s2 = eindex s1 + 2)\n  (UREGS : regf s2 = RegFun.add reg (RegFile.eval_expr (regf s1) expr_old) (regf s1))\n  (UDEPS : depf s2 = RegFun.add reg (eq (ThreadEvent tid (eindex s1))) (depf s1))\n  (UECTRL : ectrl s2 = ectrl s1)\n  MOD (new_rfi : relation actid) new_val\n  (NFRMW: MOD ∩₁ dom_rel (s2.(G).(rmw_dep)) ⊆₁ ∅)\n  (NADDR : MOD ∩₁ dom_rel (s2.(G).(addr)) ⊆₁ ∅)\n  (NREX:  MOD ∩₁ s2.(G).(acts_set) ∩₁ (R_ex s2.(G).(lab)) ⊆₁ ∅) \n  (NDATA: ⦗MOD⦘ ⨾ s2.(G).(data) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂)\n  (RFI_INDEX : new_rfi ⊆ ext_sb)\n  (TWF : thread_wf tid s1)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n  exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\nred in SIM; desc.\n\nassert (rexmod = true); subst.\n{ clear -ISTEP CASREX. red in CASREX.\n  set (AA:=ISTEP).\n  symmetry in AA. apply nth_error_In in AA.\n  apply CASREX in AA. red in AA. desf. }\n\nassert (SAME_LOC: RegFile.eval_lexpr (regf s1) lexpr = RegFile.eval_lexpr (regf s1') lexpr).\n{ ins; eapply regf_lexpr_helper; eauto.\nins; intro; eapply NADDR; unfolder; splits; eauto.\nexists (ThreadEvent tid (eindex s1)).\nrewrite UG; unfold add_rmw; basic_solver. } \n\ncut (exists instrs pc G_ eindex regf depf ectrl, \n  step tid s1' {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |} /\\ \n  (sim_state s2 {| instrs := instrs; pc := pc; G := G_; eindex := eindex; regf := regf; depf := depf; ectrl := ectrl |}\n  MOD new_rfi new_val)).\nby ins; desc; eauto.\n\ndo 7 eexists; splits; red; splits.\n  * eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply cas_suc; try reflexivity.\n  * ins; congruence.\n  * ins; congruence.\n  * ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG; ins.\n    unfold acts_set, R_ex in NREX; ins.\n    red in EXEC; desc.\n    red; splits; ins.\n    + by rewrite EINDEX, ACTS.\n    + rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1' + 1))).\n      by subst; rewrite !upds; rewrite SAME_LOC.\n      rewrite updo; try done.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      by subst; rewrite !upds; rewrite updo; [| by desf]; rewrite upds; rewrite SAME_LOC.\n      rewrite !updo; auto.\n    + rewrite EINDEX.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1' + 1))).\n      -- subst; rewrite SAME_LOC.\n         unfold val; rewrite !upds.\n         erewrite regf_expr_helper; try edone.\n         intro reg0; specialize (REGF reg0); desf; eauto.\n         ins; intro DEPS; eapply NDATA; unfolder; splits; eauto.\n         by rewrite EINDEX.\n      -- unfold val; rewrite updo; [|done].\n         destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))).\n         ** subst; rewrite SAME_LOC.\n            rewrite !upds.\n            rewrite updo; [|intro; desf; omega].\n            rewrite !upds.\n            erewrite regf_expr_helper; try edone.\n            intro reg0; specialize (REGF reg0); desf; eauto.\n            ins; intro DEPS; eapply NFRMW; unfolder; splits; eauto.\n         ** rewrite !updo; try done.\n            by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN.\n    + by rewrite RMW, EINDEX.\n    + by rewrite DATA, EINDEX, DEPF.\n    + by rewrite ADDR, EINDEX, DEPF.\n    + by rewrite CTRL, EINDEX, ECTRL.\n    + by rewrite FRMW, EINDEX, DEPF.\n  * ins; congruence.\n  * ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto.\n    erewrite regf_expr_helper; eauto.\n    ins; intro; eapply NFRMW.\n    rewrite UG; ins; basic_solver.\n  * eby ins; rewrite <- DEPF, <- EINDEX.\n  * ins; congruence.\n  * ins; unfold acts_set, is_r, is_w in INr, INw, READ, WRITE; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'+1))); subst.\n    by rewrite upds in READ; desf.\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    rewrite updo in WRITE; [| intro; desf; omega].\n    by rewrite upds in WRITE; desf.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    + exfalso.\n      eapply NREX; split; [eauto|].\n      rewrite UG; unfold add; unfold acts_set; ins.\n      split; [eauto| rewrite EINDEX; eauto].\n      rewrite UG; unfold add; unfold R_ex; ins.\n      by rewrite updo; [| intro; desf; omega]; rewrite EINDEX, upds.\n    + unfold val; rewrite updo; [|done].\n      rewrite updo; [|done].\n      destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'+1))); subst.\n      -- exfalso.\n         apply RFI_INDEX in RF; unfold ext_sb in RF.\n         destruct r; [eauto|]; desc.\n         destruct INr as [X|[X|INr]]; try by desf.\n         apply sim_execution_same_acts in EXEC.\n         apply EXEC in INr.\n         apply TWF in INr; desc.\n         rewrite <- EINDEX in RF0.\n         desf; omega.\n      -- rewrite !updo; try done.\n         eapply NEW_VAL1; try edone.\n         by rewrite <- EINDEX in n0; desf.\n         by rewrite <- EINDEX in n; desf.\n         by rewrite !updo in READ; try edone.\n         by rewrite !updo in WRITE; try edone.\n  * simpl; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'+1))); subst.\n    by unfold is_r in READ; rewrite upds in READ; desf.\n    unfold val; rewrite updo; [|done].\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    + exfalso.\n      eapply NREX; split; [eauto|].\n      rewrite UG; unfold add; unfold acts_set; ins.\n      split; [eauto| rewrite EINDEX; eauto].\n      rewrite UG; unfold add; unfold R_ex; ins.\n      by rewrite updo; [| intro; desf; omega]; rewrite EINDEX, upds.\n    + unfold val; rewrite updo; try done.\n      apply NEW_VAL2; try done.\n      unfold is_r in *; rewrite !updo in READ; try done.\n      by unfold add, acts_set in IN; ins; desf.\nQed.\n\nLemma receptiveness_sim_inc (tid : thread_id)\n      s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n      (expr_add : Instr.expr)\n      rexmod xmod\n      (ordr ordw : mode)\n      (reg : Reg.t)\n      (lexpr : Instr.lexpr)\n      (ISTEP : Some (Instr.update\n                       (Instr.fetch_add expr_add) rexmod xmod ordr ordw reg lexpr) =\n               nth_error (instrs s1) (pc s1))\n      (val_ : nat)\n      (UPC : pc s2 = pc s1 + 1)\n      (UG : G s2 =\n            add_rmw (G s1) tid (eindex s1)\n                    (Aload rexmod ordr\n                           (RegFile.eval_lexpr (regf s1) lexpr) val_)\n                    (Astore xmod ordw (RegFile.eval_lexpr (regf s1) lexpr)\n                            (val_ + RegFile.eval_expr (regf s1) expr_add))\n                    ((eq (ThreadEvent tid s1.(eindex))) ∪₁\n                     (DepsFile.expr_deps s1.(depf) expr_add))\n                    (DepsFile.lexpr_deps (depf s1) lexpr)\n                    (ectrl s1) ∅)\n      (UINDEX : eindex s2 = eindex s1 + 2)\n      (UREGS : regf s2 = RegFun.add reg val_ (regf s1))\n      (UDEPS : depf s2 = RegFun.add reg (eq (ThreadEvent tid (eindex s1))) (depf s1))\n      (UECTRL : ectrl s2 = ectrl s1)\n      MOD (new_rfi : relation actid) new_val\n      (NFRMW: MOD ∩₁ dom_rel (s2.(G).(rmw_dep)) ⊆₁ ∅)\n      (NADDR : MOD ∩₁ dom_rel (s2.(G).(addr)) ⊆₁ ∅)\n      (NREX:  MOD ∩₁ s2.(G).(acts_set) ∩₁ (R_ex s2.(G).(lab)) ⊆₁ ∅) \n      (NDATA: ⦗MOD⦘ ⨾ s2.(G).(data) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂)\n      (TWF : thread_wf tid s1)\n      (RFI_INDEX : new_rfi ⊆ ext_sb)\n      (new_rfif : functional new_rfi⁻¹)\n      s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\n  generalize (@new_write new_rfi new_rfif); intro F; destruct F as [new_w F].\n  red in SIM; desc.\n  assert (SAME_LOC : RegFile.eval_lexpr (regf s1) lexpr =\n                     RegFile.eval_lexpr (regf s1') lexpr).\n  { ins; eapply regf_lexpr_helper; eauto.\n    ins; intro; eapply NADDR; unfolder; splits; eauto.\n    exists (ThreadEvent tid (eindex s1)).\n    rewrite UG; unfold add_rmw; basic_solver. } \n\n  cut (exists instrs pc G_ eindex regf depf ectrl, \n          step tid s1' (Build_state instrs pc G_ eindex regf depf ectrl) /\\ \n          (sim_state s2 (Build_state instrs pc G_ eindex regf depf ectrl)\n                     MOD new_rfi new_val)).\n  { ins; desc; eauto. }\n  do 7 eexists; splits; red; splits.\n  { eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply inc with (val := \n      if excluded_middle_informative (MOD (ThreadEvent tid (eindex s1'))) \n      then if excluded_middle_informative ((codom_rel new_rfi) (ThreadEvent tid (eindex s1'))) \n           then (get_val (val s1'.(G).(lab) (new_w (ThreadEvent tid (eindex s1')))))\n           else (new_val (ThreadEvent tid (eindex s1')))\n      else val_);\n    reflexivity. }\n  1,2,4,7: ins; congruence.\n  { ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG.\n    red in EXEC; desc.\n    red; splits; ins.\n    { by rewrite EINDEX, ACTS. }\n    { rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      { subst.\n        rewrite updo; [|intros HH; clear -HH; inv HH; omega]. \n        rewrite !upds. unfold same_label_u2v.\n        rewrite updo; [|intros HH; clear -HH; inv HH; omega]. \n        rewrite upds; auto. }\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1' + 1))).\n      { subst.\n        rewrite !upds. unfold same_label_u2v; auto. }\n      ins. rewrite !updo; auto. }\n    { rewrite EINDEX.\n      unfold val.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1' + 1))).\n      { subst.\n        destruct (excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))) as [MN|NMN].\n        { exfalso.\n          eapply NDATA. \n          apply seq_eqv_lr. splits; eauto.\n          basic_solver 10. }\n        assert (SAME_VAL : RegFile.eval_expr (regf s1 ) expr_add =\n                           RegFile.eval_expr (regf s1') expr_add).\n        { ins; eapply regf_expr_helper; eauto.\n          ins; intro; eapply NDATA; unfolder; splits; eauto.\n            by rewrite EINDEX. }\n        rewrite !upds. by rewrite SAME_VAL. }\n      rewrite updo; auto.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))).\n      { subst.\n        rewrite !upds.\n        destruct (excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))) as [MN|NMN].\n        { exfalso. eauto. }\n        rewrite updo; [|intros HH; clear -HH; inv HH; omega]. \n          by rewrite upds. }\n      rewrite !updo; auto.\n      by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN. }\n    { by rewrite RMW, EINDEX. }\n    { by rewrite DATA, EINDEX, DEPF. }\n    { by rewrite ADDR, EINDEX, DEPF. }\n    { by rewrite CTRL, EINDEX, ECTRL. }\n      by rewrite FRMW, EINDEX. }\n  { ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto. }\n  { eby ins; rewrite <- DEPF, <- EINDEX. }\n  { ins; unfold acts_set, is_r, is_w in INr, INw, READ, WRITE; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'+1))); subst.\n    { by rewrite upds in READ; desf. }\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    rewrite updo in WRITE; [| intro; desf; omega].\n    { by rewrite upds in WRITE; desf. }\n\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1' + 1))); subst.\n    { exfalso.\n      apply RFI_INDEX in RF; unfold ext_sb in RF.\n      destruct INr as [INr|[INr|INr]]; subst.\n      1,2: clear -RF; omega.\n      destruct r; [eauto|]; desc.\n      apply sim_execution_same_acts in EXEC.\n      apply EXEC in INr.\n      apply TWF in INr; desc.\n      rewrite <- EINDEX in RF0.\n      inv EE. clear -RF0 LT. omega. }\n\n    assert (is_w (lab (G s1')) w) as WW'.\n    { rewrite !updo in WRITE; edone. }\n\n    unfold val.\n    rewrite updo; auto.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    { rewrite !upds.\n      destruct (excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))) as [MN|NMN].\n      2: eby exfalso.\n      rewrite !updo; auto.\n      destruct (excluded_middle_informative\n                  (codom_rel new_rfi (ThreadEvent tid (eindex s1')))) as [|XX].\n      2: { exfalso. apply XX. generalize RF. clear. basic_solver. }\n      assert (w = new_w (ThreadEvent tid (eindex s1'))); subst.\n      { edestruct new_rfi_unique with\n            (r:=ThreadEvent tid (eindex s1')) as [wu [_ HH]]; eauto.\n        transitivity wu.\n        2: by apply HH.\n        symmetry. apply HH. do 2 red. generalize RF. clear. basic_solver. }\n      unfold get_val.\n      clear -WW'. unfold is_w in WW'. desf. }\n    rewrite !updo; auto.\n    eapply NEW_VAL1; try edone.\n    { by rewrite <- EINDEX in n0; desf. }\n    { by rewrite <- EINDEX in n; desf. }\n      by rewrite !updo in READ; try edone. }\n  simpl; ins.\n  destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'+1))); subst.\n  { by unfold is_r in READ; rewrite upds in READ; desf. }\n  unfold val; rewrite updo; [|done].\n  destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n  { rewrite upds. desf. }\n  unfold val; rewrite updo; try done.\n  apply NEW_VAL2; try done.\n  unfold is_r in *; rewrite !updo in READ; try done.\n    by unfold add, acts_set in IN; ins; desf.\nQed.\n\nLemma receptiveness_sim_exchange\n      (tid : thread_id)\n      s1 s2 (INSTRS0 : instrs s1 = instrs s2)\n      (new_expr : Instr.expr)\n      rexmod xmod\n      (ordr ordw : mode)\n      (reg : Reg.t)\n      (lexpr : Instr.lexpr)\n      (ISTEP : Some (Instr.update\n                       (Instr.exchange new_expr)\n                       rexmod xmod ordr ordw reg lexpr) = nth_error (instrs s1) (pc s1))\n      (val_ : nat)\n      (UPC : pc s2 = pc s1 + 1)\n      (UG : G s2 = add_rmw (G s1) tid (eindex s1)\n                           (Aload rexmod ordr (RegFile.eval_lexpr (regf s1) lexpr)\n                                  val_)\n                           (Astore xmod ordw (RegFile.eval_lexpr (regf s1) lexpr)\n                                   (RegFile.eval_expr (regf s1) new_expr))\n                           (DepsFile.expr_deps s1.(depf) new_expr)\n                           (DepsFile.lexpr_deps (depf s1) lexpr)\n                           (ectrl s1) ∅)\n      (UINDEX : eindex s2 = eindex s1 + 2)\n      (UREGS : regf s2 = RegFun.add reg val_ (regf s1))\n      (UDEPS : depf s2 = RegFun.add reg (eq (ThreadEvent tid (eindex s1)))\n                                    (depf s1))\n      (UECTRL : ectrl s2 = ectrl s1)\n      MOD (new_rfi : relation actid) new_val\n      (NFRMW: MOD ∩₁ dom_rel (s2.(G).(rmw_dep)) ⊆₁ ∅)\n      (NADDR : MOD ∩₁ dom_rel (s2.(G).(addr)) ⊆₁ ∅)\n      (NREX:  MOD ∩₁ s2.(G).(acts_set) ∩₁ (R_ex s2.(G).(lab)) ⊆₁ ∅) \n      (NDATA: ⦗MOD⦘ ⨾ s2.(G).(data) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂)\n      (TWF : thread_wf tid s1)\n      (RFI_INDEX : new_rfi ⊆ ext_sb)\n      (new_rfif : functional new_rfi⁻¹)\n      s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n  exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\n  generalize (@new_write new_rfi new_rfif); intro F; destruct F as [new_w F].\n  red in SIM; desc.\n  assert (SAME_LOC : RegFile.eval_lexpr (regf s1) lexpr =\n                     RegFile.eval_lexpr (regf s1') lexpr).\n  { ins; eapply regf_lexpr_helper; eauto.\n    ins; intro; eapply NADDR; unfolder; splits; eauto.\n    exists (ThreadEvent tid (eindex s1)).\n    rewrite UG; unfold add_rmw; basic_solver. } \n\n  cut (exists instrs pc G_ eindex regf depf ectrl, \n          step tid s1' (Build_state instrs pc G_ eindex regf depf ectrl) /\\ \n          (sim_state s2 (Build_state instrs pc G_ eindex regf depf ectrl)\n                     MOD new_rfi new_val)).\n  { ins; desc; eauto. }\n  do 7 eexists; splits; red; splits.\n  { eexists; red; splits; [by ins; eauto|].\n    eexists; splits; [eby rewrite <- INSTRS, <- PC |].\n    eapply exchange with (val :=\n      if excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))\n      then if excluded_middle_informative ((codom_rel new_rfi) (ThreadEvent tid (eindex s1')))\n           then (get_val (val s1'.(G).(lab) (new_w (ThreadEvent tid (eindex s1')))))\n           else (new_val (ThreadEvent tid (eindex s1')))\n      else val_);\n    reflexivity. }\n  1,2,4,7: ins; congruence.\n  { ins.\n    destruct (G s2) as [acts2 lab2 rmw2 data2 addr2 ctrl2 rf2 co2].\n    inversion UG; subst; clear UG.\n    red in EXEC; desc.\n    red; splits; ins.\n    { by rewrite EINDEX, ACTS. }\n    { rewrite EINDEX.\n      unfold same_lab_u2v in *; intro e.\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1'))).\n      { subst.\n        rewrite updo; [|intros HH; clear -HH; inv HH; omega]. \n        rewrite !upds. unfold same_label_u2v.\n        rewrite updo; [|intros HH; clear -HH; inv HH; omega]. \n        rewrite upds; auto. }\n      destruct (eq_dec_actid e (ThreadEvent tid (eindex s1' + 1))).\n      { subst.\n        rewrite !upds. unfold same_label_u2v; auto. }\n      ins. rewrite !updo; auto. }\n    { rewrite EINDEX.\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1' + 1))).\n      { subst; rewrite SAME_LOC.\n        unfold val; rewrite !upds.\n        erewrite regf_expr_helper; try edone.\n        intro reg0; specialize (REGF reg0); desf; eauto.\n        ins; intro DEPS; eapply NDATA; unfolder; splits; eauto.\n        by rewrite EINDEX. } \n      unfold val; rewrite updo; [|done].\n      destruct (eq_dec_actid a (ThreadEvent tid (eindex s1'))).\n      { subst; rewrite SAME_LOC.\n         rewrite !upds.\n         rewrite updo; [|intro; desf; omega].\n         rewrite !upds. desf. }\n      rewrite !updo; try done.\n      by apply OLD_VAL in NIN; unfold val in NIN; rewrite NIN. }\n    { by rewrite RMW, EINDEX. }\n    { by rewrite DATA, EINDEX, DEPF. }\n    { by rewrite ADDR, EINDEX, DEPF. }\n    { by rewrite CTRL, EINDEX, ECTRL. }\n      by rewrite FRMW, EINDEX. }\n  { ins; rewrite UREGS, UDEPS.\n    unfold RegFun.add, RegFun.find in *; desf; eauto. }\n  { eby ins; rewrite <- DEPF, <- EINDEX. }\n  { ins; unfold acts_set, is_r, is_w in INr, INw, READ, WRITE; ins.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'+1))); subst.\n    { by rewrite upds in READ; desf. }\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1'))); subst.\n    rewrite updo in WRITE; [| intro; desf; omega].\n    { by rewrite upds in WRITE; desf. }\n\n    destruct (eq_dec_actid w (ThreadEvent tid (eindex s1' + 1))); subst.\n    { exfalso.\n      apply RFI_INDEX in RF; unfold ext_sb in RF.\n      destruct INr as [INr|[INr|INr]]; subst.\n      1,2: clear -RF; omega.\n      destruct r; [eauto|]; desc.\n      apply sim_execution_same_acts in EXEC.\n      apply EXEC in INr.\n      apply TWF in INr; desc.\n      rewrite <- EINDEX in RF0.\n      inv EE. clear -RF0 LT. omega. }\n\n    assert (is_w (lab (G s1')) w) as WW'.\n    { rewrite !updo in WRITE; edone. }\n\n    unfold val.\n    rewrite updo; auto.\n    destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n    { rewrite !upds.\n      destruct (excluded_middle_informative (MOD (ThreadEvent tid (eindex s1')))) as [MN|NMN].\n      2: eby exfalso.\n      rewrite !updo; auto.\n      destruct (excluded_middle_informative\n                  (codom_rel new_rfi (ThreadEvent tid (eindex s1')))) as [|XX].\n      2: { exfalso. apply XX. generalize RF. clear. basic_solver. }\n      assert (w = new_w (ThreadEvent tid (eindex s1'))); subst.\n      { edestruct new_rfi_unique with\n            (r:=ThreadEvent tid (eindex s1')) as [wu [_ HH]]; eauto.\n        transitivity wu.\n        2: by apply HH.\n        symmetry. apply HH. do 2 red. generalize RF. clear. basic_solver. }\n      unfold get_val.\n      clear -WW'. unfold is_w in WW'. desf. }\n    rewrite !updo; auto.\n    eapply NEW_VAL1; try edone.\n    { by rewrite <- EINDEX in n0; desf. }\n    { by rewrite <- EINDEX in n; desf. }\n      by rewrite !updo in READ; try edone. }\n  simpl; ins.\n  destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'+1))); subst.\n  { by unfold is_r in READ; rewrite upds in READ; desf. }\n  unfold val; rewrite updo; [|done].\n  destruct (eq_dec_actid r (ThreadEvent tid (eindex s1'))); subst.\n  { rewrite upds. desf. }\n  unfold val; rewrite updo; try done.\n  apply NEW_VAL2; try done.\n  { unfold is_r in *; rewrite !updo in READ; done. }\n    by unfold add, acts_set in IN; ins; desf.\nQed.\n\nLemma receptiveness_sim_step (tid : thread_id)\n  s1 s2\n  (STEP : (step tid) s1 s2) \n  (CASREX : cas_produces_R_ex_instrs (instrs s1))\n  MOD (new_rfi : relation actid) new_val\n  (NCTRL : MOD ∩₁ ectrl s2 ⊆₁ ∅)\n  (NFRMW: MOD ∩₁ dom_rel (s2.(G).(rmw_dep)) ⊆₁ ∅)\n  (NADDR : MOD ∩₁ dom_rel (s2.(G).(addr)) ⊆₁ ∅)\n  (NREX:  MOD ∩₁ s2.(G).(acts_set) ∩₁ (R_ex s2.(G).(lab)) ⊆₁ ∅) \n  (NDATA: ⦗MOD⦘ ⨾ s2.(G).(data) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂)\n  (new_rfif : functional new_rfi⁻¹)\n   (RFI_INDEX : new_rfi ⊆ ext_sb)\n  (TWF : thread_wf tid s1)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid) s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\ndestruct STEP; red in H; desf.\ndestruct ISTEP0; desf.\n- eby eapply receptiveness_sim_assign.\n- eby eapply receptiveness_sim_if_else.\n- eby eapply receptiveness_sim_if_then.\n- eby eapply receptiveness_sim_load.\n- eby eapply receptiveness_sim_store.\n- eby eapply receptiveness_sim_fence.\n- eby eapply receptiveness_sim_cas_fail.\n- eby eapply receptiveness_sim_cas_suc.\n- eby eapply receptiveness_sim_inc.\n- eby eapply receptiveness_sim_exchange. \nQed.\n\nLemma receptiveness_sim (tid : thread_id)\n  s1 s2\n  (STEPS : (step tid)＊ s1 s2)\n  (CASREX : cas_produces_R_ex_instrs (instrs s1))\n  MOD (new_rfi : relation actid) new_val\n  (NCTRL : MOD ∩₁ ectrl s2 ⊆₁ ∅)\n  (NFRMW: MOD ∩₁ dom_rel (s2.(G).(rmw_dep)) ⊆₁ ∅)\n  (NADDR : MOD ∩₁ dom_rel (s2.(G).(addr)) ⊆₁ ∅)\n  (NREX:  MOD ∩₁ s2.(G).(acts_set) ∩₁ (R_ex s2.(G).(lab)) ⊆₁ ∅) \n  (NDATA: ⦗MOD⦘ ⨾ s2.(G).(data) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂)\n  (new_rfif : functional new_rfi⁻¹)\n   (RFI_INDEX : new_rfi ⊆ ext_sb)\n  (TWF : thread_wf tid s1)\n  s1' (SIM: sim_state s1 s1' MOD new_rfi new_val) :\n exists s2', (step tid)＊ s1' s2' /\\ sim_state s2 s2' MOD new_rfi new_val.\nProof using.\n  apply clos_rt_rtn1 in STEPS.\n  induction STEPS.\n  { by eexists; vauto. }\n  exploit IHSTEPS.\n  { unfolder; splits; ins; eauto; desf.\n    eapply ectrl_increasing in H1; eauto.\n    eapply NCTRL; basic_solver. }\n  { unfolder; splits; ins; eauto; desf.\n    eapply rmw_dep_increasing in H1; eauto.\n    eapply NFRMW; basic_solver. }\n  { unfolder; splits; ins; eauto; desf.\n    eapply addr_increasing in H1; eauto.\n    eapply NADDR; basic_solver. }\n  { unfolder; splits; ins; eauto; desf. \n    eapply NREX; split; [split; [eauto |] |].\n    eapply acts_increasing; edone.\n    eapply is_r_ex_increasing; eauto.\n    eapply thread_wf_steps; try edone. \n    { by apply clos_rtn1_rt. }\n    basic_solver. }\n  { unfolder; splits; ins; eauto; desf.\n    eapply data_increasing in H1; eauto.\n    eapply NDATA; basic_solver. }\n  intro; desc.\n  eapply receptiveness_sim_step in x0; eauto; desf.\n  { exists s2'0; splits; eauto. \n      by eapply rt_trans; [eauto | econs]. }\n  { arewrite (instrs y = instrs s1); auto.\n    apply clos_rtn1_rt in STEPS.\n    eapply steps_preserve_instrs; eauto. }\n  eapply thread_wf_steps; try edone.\n    by apply clos_rtn1_rt.\nQed.\n\nLemma receptiveness_helper (tid : thread_id)\n      s_init s\n      (CASREX : cas_produces_R_ex_instrs (instrs s_init))\n      (GPC : wf_thread_state tid s_init)\n      (new_val : actid -> value)\n      (new_rfi : relation actid)\n      (MOD: actid -> Prop)\n      (STEPS : (step tid)＊ s_init s)\n      (new_rfiE : new_rfi ≡ ⦗s.(G).(acts_set)⦘ ⨾ new_rfi ⨾ ⦗s.(G).(acts_set)⦘)\n      (new_rfiD : new_rfi ≡ ⦗is_w s.(G).(lab)⦘ ⨾ new_rfi ⨾ ⦗is_r s.(G).(lab)⦘)\n      (new_rfif : functional new_rfi⁻¹)\n      (RFI_INDEX : new_rfi ⊆ ext_sb)\n      (NCTRL : MOD ∩₁ ectrl s ⊆₁ ∅) \n      (NFRMW: MOD ∩₁ dom_rel (s.(G).(rmw_dep)) ⊆₁ ∅)\n      (NADDR : MOD ∩₁ dom_rel (s.(G).(addr)) ⊆₁ ∅)\n      (NREX:  MOD ∩₁ s.(G).(acts_set) ∩₁ (R_ex s.(G).(lab)) ⊆₁ ∅) \n      (NDATA: ⦗MOD⦘ ⨾ s.(G).(data) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂) \n      (new_rfiMOD : codom_rel new_rfi ⊆₁ MOD)\n      (NMODINIT: MOD ∩₁ s_init.(ProgToExecution.G).(acts_set) ⊆₁ ∅)\n      (EMOD : MOD ⊆₁ (ProgToExecution.G s).(acts_set)) :\n    exists s',\n      ⟪ STEPS' : (step tid)＊ s_init s' ⟫ /\\\n      ⟪ EXEC : sim_execution s.(G) s'.(G) MOD ⟫ /\\\n      ⟪ NEW_VAL1 : forall r w (RF: new_rfi w r), val (s'.(G).(lab)) r = val (s'.(G).(lab)) w ⟫ /\\\n      ⟪ NEW_VAL2 : forall r (RR : is_r s'.(G).(lab) r) (IN: MOD r) (NIN: ~ (codom_rel new_rfi) r),\n          val (s'.(G).(lab)) r = Some (new_val r) ⟫ /\\\n      ⟪ OLD_VAL : forall a (NIN: ~ MOD a), val (s'.(G).(lab)) a = val (s.(G).(lab)) a ⟫.\nProof using.\napply receptiveness_sim with (s1':= s_init) (MOD:=MOD) (new_rfi:=new_rfi) (new_val:=new_val) in STEPS.\nall: try done.\n- desc.\n  red in STEPS0; desc.\n  exists s2'; splits; eauto.\n  * ins; eapply NEW_VAL1; try done.\n    + hahn_rewrite new_rfiE in RF; unfolder in RF; desf.\n      apply sim_execution_same_acts in EXEC.\n      revert EXEC; basic_solver.\n    + hahn_rewrite new_rfiE in RF; unfolder in RF; desf.\n      apply sim_execution_same_acts in EXEC.\n      revert EXEC; basic_solver.\n    + hahn_rewrite new_rfiD in RF; unfolder in RF; desf.\n      apply sim_execution_same_r in EXEC.\n      revert EXEC; basic_solver.\n    + hahn_rewrite new_rfiD in RF; unfolder in RF; desf.\n      apply sim_execution_same_w in EXEC.\n      revert EXEC; basic_solver.\n    + revert new_rfiMOD; basic_solver.\n  * ins; eapply NEW_VAL2; try done.\n    apply sim_execution_same_acts in EXEC.\n    revert EXEC; basic_solver.\n  * ins; red in EXEC; desc.\n    by eapply OLD_VAL.\n- red; apply (acts_rep GPC).\n- red; splits; eauto.\n  { red; splits; eauto; red; red; ins; red; eauto; desf. }\n  ins; exfalso; revert NMODINIT; basic_solver.\n  ins; exfalso; unfolder in *; basic_solver.\nQed.\n\nLemma receptiveness_ectrl_helper (tid : thread_id) \n      s_init s \n      (GPC : wf_thread_state tid s_init)\n      (STEPS : (step tid)＊ s_init s)\n      MOD (NCTRL: MOD ∩₁ dom_rel (s.(G).(ctrl)) ⊆₁ ∅) \n      (NMODINIT: MOD ∩₁ s_init.(G).(acts_set) ⊆₁ ∅):\n      exists s', (step tid)＊ s_init s' /\\\n                 (MOD ∩₁ ectrl s' ⊆₁ ∅) /\\ s'.(G) = s.(G).\nProof using.\napply clos_rt_rtn1 in STEPS.\ninduction STEPS.\n- exists s_init; splits; vauto.\n  by rewrite (wft_ectrlE GPC).\n- assert (A: MOD ∩₁ dom_rel (ctrl (G y)) ⊆₁ ∅).\n  generalize (ctrl_increasing H).\n  revert NCTRL; basic_solver 12.\n  apply IHSTEPS in A.\n  desc.\n  destruct  (classic (MOD ∩₁ ectrl z ⊆₁ ∅)).\n  * exists z; splits; eauto.\n    eapply rt_trans.\n    eby apply clos_rtn1_rt.\n    by apply rt_step.\n  * exists s'; splits; eauto.\n    transitivity (G y); [done|].\n    eapply ectrl_ctrl_step; try edone.\n    destruct (classic (exists a : actid, (MOD ∩₁ ectrl z) a)); auto.\n    exfalso; apply H0; unfolder; ins; eapply H1; basic_solver.\nQed.\n\nLemma receptiveness_full (tid : thread_id)\n      s_init s\n      (new_val : actid -> value)\n      (new_rfi : relation actid)\n      (MOD: actid -> Prop)\n      (GPC : wf_thread_state tid s_init)\n      (CASREX : cas_produces_R_ex_instrs (instrs s_init))\n      (STEPS : (step tid)＊ s_init s)\n      (new_rfiE : new_rfi ≡ ⦗s.(G).(acts_set)⦘ ⨾ new_rfi ⨾ ⦗s.(G).(acts_set)⦘)\n      (new_rfiD : new_rfi ≡ ⦗is_w s.(G).(lab)⦘ ⨾ new_rfi ⨾ ⦗is_r s.(G).(lab)⦘)\n      (new_rfif : functional new_rfi⁻¹)\n      (RFI_INDEX : new_rfi ⊆ ext_sb)\n      (new_rfiMOD : codom_rel new_rfi ⊆₁ MOD)\n      (EMOD : MOD ⊆₁ (ProgToExecution.G s).(acts_set))\n      (NMODINIT: MOD ∩₁ s_init.(ProgToExecution.G).(acts_set) ⊆₁ ∅)\n      (NFRMW: MOD ∩₁ dom_rel (s.(G).(rmw_dep)) ⊆₁ ∅)\n      (NADDR : MOD ∩₁ dom_rel (s.(G).(addr)) ⊆₁ ∅)\n      (NREX:  MOD ∩₁ s.(G).(acts_set) ∩₁(R_ex s.(G).(lab)) ⊆₁ ∅) \n      (NCTRL: MOD ∩₁ dom_rel (s.(G).(ctrl)) ⊆₁ ∅)\n      (NDATA: ⦗MOD⦘ ⨾ s.(G).(data) ⨾ ⦗set_compl MOD⦘ ⊆ ∅₂) :\n    exists s',\n      ⟪ STEPS' : (step tid)＊ s_init s' ⟫ /\\\n      ⟪ RACTS : s.(G).(acts) = s'.(G).(acts) ⟫ /\\\n      ⟪ RRMW  : s.(G).(rmw)  ≡ s'.(G).(rmw)  ⟫ /\\\n      ⟪ RDATA : s.(G).(data) ≡ s'.(G).(data) ⟫ /\\\n      ⟪ RADDR : s.(G).(addr) ≡ s'.(G).(addr) ⟫ /\\\n      ⟪ RCTRL : s.(G).(ctrl) ≡ s'.(G).(ctrl) ⟫  /\\\n      ⟪ RFAILRMW : s.(G).(rmw_dep) ≡ s'.(G).(rmw_dep) ⟫  /\\\n      ⟪ SAME : same_lab_u2v (s'.(G).(lab)) (s.(G).(lab))⟫ /\\\n      ⟪ NEW_VAL1 : forall r w (RF: new_rfi w r), val (s'.(G).(lab)) r = val (s'.(G).(lab)) w ⟫ /\\\n      ⟪ NEW_VAL2 : forall r (RR : is_r s'.(G).(lab) r) (IN: MOD r) (NIN: ~ (codom_rel new_rfi) r),\n          val (s'.(G).(lab)) r = Some (new_val r) ⟫ /\\\n      ⟪ OLD_VAL : forall a (NIN: ~ MOD a), val (s'.(G).(lab)) a = val (s.(G).(lab)) a ⟫.\nProof using.\nforward (apply receptiveness_ectrl_helper); try edone.\n\nins; desc.\nrewrite <- H1 in *.\nclear STEPS H1 s.\nforward (eapply receptiveness_helper with (new_rfi:=new_rfi)); ins; eauto.\ndesc.\nred in EXEC; desc.\neexists; splits; eauto.\nQed.\n", "meta": {"author": "fresheed", "repo": "omm-imm", "sha": "59a4c709e31d3aaf2b34ebd5a8e7d3efe104f3c2", "save_path": "github-repos/coq/fresheed-omm-imm", "path": "github-repos/coq/fresheed-omm-imm/omm-imm-59a4c709e31d3aaf2b34ebd5a8e7d3efe104f3c2/src/basic/Receptiveness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23544472958611862}}
{"text": "(* This file contains highly trivial proofs, but they are carefully engineered\n   in such a way that the Qed is fast. This is tricky because we have to avoid\n   that constants such as 12 or 13 are unfolded by the typechecker while unifying\n   two terms. *)\n\nRequire Import aes.spec_encryption_LL.\nRequire Import compcert.common.Values.\nRequire Import VST.floyd.functional_base.\nLocal Open Scope Z.\n\nLemma round13eq: forall buf S12 S13,\n       S13 = mbed_tls_fround S12 buf 52 ->\n       Int.xor\n         (Int.xor\n            (Int.xor\n               (Int.xor (Int.repr (Znth 52 buf))\n                  (Znth\n                     (Z.land (Int.unsigned (col 0 S12))\n                        (Int.unsigned (Int.repr 255))) FT0))\n               (Znth\n                  (Z.land (Int.unsigned (Int.shru (col 1 S12) (Int.repr 8)))\n                     (Int.unsigned (Int.repr 255))) FT1))\n            (Znth\n               (Z.land (Int.unsigned (Int.shru (col 2 S12) (Int.repr 16)))\n                  (Int.unsigned (Int.repr 255))) FT2))\n         (Znth\n            (Z.land (Int.unsigned (Int.shru (col 3 S12) (Int.repr 24)))\n               (Int.unsigned (Int.repr 255))) FT3) = col 0 S13\n   /\\  Int.xor\n         (Int.xor\n            (Int.xor\n               (Int.xor (Int.repr (Znth 53 buf))\n                  (Znth\n                     (Z.land (Int.unsigned (col 1 S12))\n                        (Int.unsigned (Int.repr 255))) FT0))\n               (Znth\n                  (Z.land (Int.unsigned (Int.shru (col 2 S12) (Int.repr 8)))\n                     (Int.unsigned (Int.repr 255))) FT1))\n            (Znth\n               (Z.land (Int.unsigned (Int.shru (col 3 S12) (Int.repr 16)))\n                  (Int.unsigned (Int.repr 255))) FT2))\n         (Znth\n            (Z.land (Int.unsigned (Int.shru (col 0 S12) (Int.repr 24)))\n               (Int.unsigned (Int.repr 255))) FT3) = col 1 S13\n   /\\  Int.xor\n         (Int.xor\n            (Int.xor\n               (Int.xor (Int.repr (Znth 54 buf))\n                  (Znth\n                     (Z.land (Int.unsigned (col 2 S12))\n                        (Int.unsigned (Int.repr 255))) FT0))\n               (Znth\n                  (Z.land (Int.unsigned (Int.shru (col 3 S12) (Int.repr 8)))\n                     (Int.unsigned (Int.repr 255))) FT1))\n            (Znth\n               (Z.land (Int.unsigned (Int.shru (col 0 S12) (Int.repr 16)))\n                  (Int.unsigned (Int.repr 255))) FT2))\n         (Znth\n            (Z.land (Int.unsigned (Int.shru (col 1 S12) (Int.repr 24)))\n               (Int.unsigned (Int.repr 255))) FT3) = col 2 S13\n   /\\  Int.xor\n         (Int.xor\n            (Int.xor\n               (Int.xor (Int.repr (Znth 55 buf))\n                  (Znth\n                     (Z.land (Int.unsigned (col 3 S12))\n                        (Int.unsigned (Int.repr 255))) FT0))\n               (Znth\n                  (Z.land (Int.unsigned (Int.shru (col 0 S12) (Int.repr 8)))\n                     (Int.unsigned (Int.repr 255))) FT1))\n            (Znth\n               (Z.land (Int.unsigned (Int.shru (col 1 S12) (Int.repr 16)))\n                  (Int.unsigned (Int.repr 255))) FT2))\n         (Znth\n            (Z.land (Int.unsigned (Int.shru (col 2 S12) (Int.repr 24)))\n               (Int.unsigned (Int.repr 255))) FT3) = col 3 S13.\nProof.\n  intros. subst S13. destruct S12 as [c0 [c1 [c2 c3]]]. repeat split.\nQed.\n\nLemma round14eq: forall buf S13 S14,\n       S14 = mbed_tls_final_fround S13 buf 56 ->\n       Int.xor\n         (Int.xor\n            (Int.xor\n               (Int.xor (Int.repr (Znth 56 buf))\n                  (Znth\n                     (Z.land (Int.unsigned (col 0 S13))\n                        (Int.unsigned (Int.repr 255))) FSb))\n               (Int.shl\n                  (Znth\n                     (Z.land\n                        (Int.unsigned (Int.shru (col 1 S13) (Int.repr 8)))\n                        (Int.unsigned (Int.repr 255))) FSb)\n                  (Int.repr 8)))\n            (Int.shl\n               (Znth\n                  (Z.land (Int.unsigned (Int.shru (col 2 S13) (Int.repr 16)))\n                     (Int.unsigned (Int.repr 255))) FSb)\n               (Int.repr 16)))\n         (Int.shl\n            (Znth\n               (Z.land (Int.unsigned (Int.shru (col 3 S13) (Int.repr 24)))\n                  (Int.unsigned (Int.repr 255))) FSb) (Int.repr 24)) =\n       col 0 S14\n    /\\ Int.xor\n         (Int.xor\n            (Int.xor\n               (Int.xor (Int.repr (Znth 57 buf))\n                  (Znth\n                     (Z.land (Int.unsigned (col 1 S13))\n                        (Int.unsigned (Int.repr 255))) FSb))\n               (Int.shl\n                  (Znth\n                     (Z.land\n                        (Int.unsigned (Int.shru (col 2 S13) (Int.repr 8)))\n                        (Int.unsigned (Int.repr 255))) FSb)\n                  (Int.repr 8)))\n            (Int.shl\n               (Znth\n                  (Z.land (Int.unsigned (Int.shru (col 3 S13) (Int.repr 16)))\n                     (Int.unsigned (Int.repr 255))) FSb)\n               (Int.repr 16)))\n         (Int.shl\n            (Znth\n               (Z.land (Int.unsigned (Int.shru (col 0 S13) (Int.repr 24)))\n                  (Int.unsigned (Int.repr 255))) FSb) (Int.repr 24)) =\n       col 1 S14\n    /\\ Int.xor\n         (Int.xor\n            (Int.xor\n               (Int.xor (Int.repr (Znth 58 buf))\n                  (Znth\n                     (Z.land (Int.unsigned (col 2 S13))\n                        (Int.unsigned (Int.repr 255))) FSb))\n               (Int.shl\n                  (Znth\n                     (Z.land\n                        (Int.unsigned (Int.shru (col 3 S13) (Int.repr 8)))\n                        (Int.unsigned (Int.repr 255))) FSb)\n                  (Int.repr 8)))\n            (Int.shl\n               (Znth\n                  (Z.land (Int.unsigned (Int.shru (col 0 S13) (Int.repr 16)))\n                     (Int.unsigned (Int.repr 255))) FSb)\n               (Int.repr 16)))\n         (Int.shl\n            (Znth\n               (Z.land (Int.unsigned (Int.shru (col 1 S13) (Int.repr 24)))\n                  (Int.unsigned (Int.repr 255))) FSb) (Int.repr 24)) =\n       col 2 S14\n    /\\ Int.xor\n         (Int.xor\n            (Int.xor\n               (Int.xor (Int.repr (Znth 59 buf))\n                  (Znth\n                     (Z.land (Int.unsigned (col 3 S13))\n                        (Int.unsigned (Int.repr 255))) FSb))\n               (Int.shl\n                  (Znth\n                     (Z.land\n                        (Int.unsigned (Int.shru (col 0 S13) (Int.repr 8)))\n                        (Int.unsigned (Int.repr 255))) FSb)\n                  (Int.repr 8)))\n            (Int.shl\n               (Znth\n                  (Z.land (Int.unsigned (Int.shru (col 1 S13) (Int.repr 16)))\n                     (Int.unsigned (Int.repr 255))) FSb)\n               (Int.repr 16)))\n         (Int.shl\n            (Znth\n               (Z.land (Int.unsigned (Int.shru (col 2 S13) (Int.repr 24)))\n                  (Int.unsigned (Int.repr 255))) FSb) (Int.repr 24)) =\n       col 3 S14.\nProof.\n  intros. subst S14. destruct S13 as [c0 [c1 [c2 c3]]]. repeat split.\nQed.\n\nLemma map_append_eq_4x4:\n  forall (a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15: int)\n         (b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15: int),\n  a0  = b0  -> a1  = b1  ->  a2 = b2  -> a3  = b3  ->\n  a4  = b4  -> a5  = b5  ->  a6 = b6  -> a7  = b7  ->\n  a8  = b8  -> a9  = b9  -> a10 = b10 -> a11 = b11 ->\n  a12 = b12 -> a13 = b13 -> a14 = b14 -> a15 = b15 ->\n  map Vint ([a0; a1; a2; a3] ++ [a4; a5; a6; a7] ++ [a8; a9; a10; a11] ++ [a12; a13; a14; a15])\n= [Vint b0; Vint b1; Vint b2; Vint b3; Vint b4; Vint b5; Vint b6; Vint b7;\n   Vint b8; Vint b9; Vint b10; Vint b11; Vint b12; Vint b13; Vint b14; Vint b15].\nProof.\n  intros. subst. reflexivity.\nQed.\n\n(* This is more general than what we need (we only need it for i=12), but if we prove it for i=12\n   directly, the Qed takes forever. *)\nLemma round13_eq_assemble_general: forall i buf plaintext S0 S12 S13,\n  S0 = mbed_tls_initial_add_round_key plaintext buf ->\n  S12 = mbed_tls_enc_rounds i S0 buf 4 ->\n  S13 = mbed_tls_fround S12 buf (4 + 4 * Z.of_nat i) ->\n  S13 = mbed_tls_enc_rounds (S i) (mbed_tls_initial_add_round_key plaintext buf) buf 4.\nProof.\n  intros.\n  progress (unfold mbed_tls_enc_rounds; fold mbed_tls_enc_rounds).\n  subst S0 S12 S13. reflexivity.\nQed.\n\nLemma round13_eq_assemble: forall buf plaintext S0 S12 S13,\n  S0 = mbed_tls_initial_add_round_key plaintext buf ->\n  S12 = mbed_tls_enc_rounds 12 S0 buf 4 ->\n  S13 = mbed_tls_fround S12 buf 52 ->\n  S13 = mbed_tls_enc_rounds 13 (mbed_tls_initial_add_round_key plaintext buf) buf 4.\nProof.\n  intros. eapply round13_eq_assemble_general; eassumption.\nQed.\n\nLemma final_aes_eq: forall buf plaintext S0 S12 S13,\n  S0 = mbed_tls_initial_add_round_key plaintext buf ->\n  S12 = mbed_tls_enc_rounds 12 S0 buf 4 ->\n  S13 = mbed_tls_fround S12 buf 52 ->\n  [Vint (Int.and           (col 0 (mbed_tls_final_fround S13 buf 56))                (Int.repr 255));\n   Vint (Int.and (Int.shru (col 0 (mbed_tls_final_fround S13 buf 56)) (Int.repr  8)) (Int.repr 255));\n   Vint (Int.and (Int.shru (col 0 (mbed_tls_final_fround S13 buf 56)) (Int.repr 16)) (Int.repr 255));\n   Vint (Int.and (Int.shru (col 0 (mbed_tls_final_fround S13 buf 56)) (Int.repr 24)) (Int.repr 255));\n   Vint (Int.and           (col 1 (mbed_tls_final_fround S13 buf 56)) (Int.repr 255));\n   Vint (Int.and (Int.shru (col 1 (mbed_tls_final_fround S13 buf 56)) (Int.repr  8)) (Int.repr 255));\n   Vint (Int.and (Int.shru (col 1 (mbed_tls_final_fround S13 buf 56)) (Int.repr 16)) (Int.repr 255));\n   Vint (Int.and (Int.shru (col 1 (mbed_tls_final_fround S13 buf 56)) (Int.repr 24)) (Int.repr 255));\n   Vint (Int.and           (col 2 (mbed_tls_final_fround S13 buf 56))                (Int.repr 255));\n   Vint (Int.and (Int.shru (col 2 (mbed_tls_final_fround S13 buf 56)) (Int.repr  8)) (Int.repr 255));\n   Vint (Int.and (Int.shru (col 2 (mbed_tls_final_fround S13 buf 56)) (Int.repr 16)) (Int.repr 255));\n   Vint (Int.and (Int.shru (col 2 (mbed_tls_final_fround S13 buf 56)) (Int.repr 24)) (Int.repr 255));\n   Vint (Int.and           (col 3 (mbed_tls_final_fround S13 buf 56))                (Int.repr 255));\n   Vint (Int.and (Int.shru (col 3 (mbed_tls_final_fround S13 buf 56)) (Int.repr  8)) (Int.repr 255));\n   Vint (Int.and (Int.shru (col 3 (mbed_tls_final_fround S13 buf 56)) (Int.repr 16)) (Int.repr 255));\n   Vint (Int.and (Int.shru (col 3 (mbed_tls_final_fround S13 buf 56)) (Int.repr 24)) (Int.repr 255))]\n= map Vint (mbed_tls_aes_enc plaintext buf).\nProof.\n  intros.\n  unfold mbed_tls_aes_enc. progress unfold output_four_ints_as_bytes. progress unfold put_uint32_le.\n  pose proof (round13_eq_assemble buf plaintext S0 S12 S13) as E.\n  specialize (E H H0 H1).\n  apply map_append_eq_4x4; repeat f_equal; exact E.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/aes/encryption_LL_round_step_eqs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23544472958611862}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\n(** * Definition of a parse-tree-returning CFG parser-recognizer *)\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.Compare_dec Coq.Arith.Wf_nat.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.GenericBaseTypes.\nRequire Import Fiat.Parsers.GenericCorrectnessBaseTypes.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Parsers.MinimalParse.\nRequire Import Fiat.Parsers.CorrectnessBaseTypes.\nRequire Import Fiat.Parsers.BaseTypesLemmas.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Properties Fiat.Parsers.WellFoundedParse.\nRequire Import Fiat.Parsers.MinimalParseOfParse.\nRequire Import Fiat.Parsers.GenericRecognizer.\nRequire Import Fiat.Parsers.GenericRecognizerExt.\nRequire Import Fiat.Common.Wf Fiat.Common.Wf1.\nRequire Import Fiat.Common.List.ListFacts.\nRequire Import Fiat.Common.NatFacts.\nRequire Import Fiat.Common.UIP.\nRequire Import Fiat.Common.\nImport ListNotations.\nImport NPeano.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nLocal Arguments dec_stabalize : simpl never.\n\nLocal Ltac R_etransitivity_eq :=\n  idtac;\n  let x' := fresh in\n  match goal with\n  | [ |- ?R ?x _ ]\n    => let T := type of x in\n       evar (x' : T);\n       replace x with x'; subst x'\n  end.\n\nLocal Ltac subst_le_proof :=\n  idtac;\n  match goal with\n    | [ H : ?x <= ?y, H' : ?x <= ?y |- _ ]\n      => assert (H = H') by apply Le.le_proof_irrelevance; subst\n  end.\n\nLocal Ltac subst_nat_eq_proof :=\n  idtac;\n  match goal with\n    | [ H : ?x = ?y :> nat, H' : ?x = ?y |- _ ]\n      => assert (H = H') by apply UIP_nat; subst\n    | [ H : ?x = ?x :> nat |- _ ]\n      => assert (eq_refl = H) by apply UIP_nat; subst\n  end.\n\nLocal Ltac subst_bool_eq_proof :=\n  idtac;\n  match goal with\n    | [ H : ?x = ?y :> bool, H' : ?x = ?y |- _ ]\n      => assert (H = H') by apply UIP_bool; subst\n    | [ H : is_true ?x, H' : ?x = true |- _ ]\n      => assert (H = H') by apply UIP_bool; subst\n    | [ H : is_true ?x, H' : is_true ?x |- _ ]\n      => assert (H = H') by apply UIP_bool; subst\n  end.\n\nLocal Ltac prove_nonterminals_t' :=\n  idtac;\n  match goal with\n    | _ => assumption\n    | [ H : is_true (is_valid_nonterminal initial_nonterminals_data (of_nonterminal _)) |- _ ]\n      => apply initial_nonterminals_correct in H\n    | [ H : In (to_nonterminal _) (Valid_nonterminals ?G) |- _ ]\n      => apply initial_nonterminals_correct' in H\n  end.\nLocal Ltac prove_nonterminals_t := repeat prove_nonterminals_t'.\nLocal Ltac solve_nonterminals_t' :=\n  idtac;\n  match goal with\n    | _ => prove_nonterminals_t'\n    | [ H : context[of_nonterminal (to_nonterminal _)] |- _ ]\n      => rewrite of_to_nonterminal in H by prove_nonterminals_t\n  end.\nLocal Ltac solve_nonterminals_t := repeat solve_nonterminals_t'.\n\nSection recursive_descent_parser.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char} (G : grammar Char).\n  Context {data : @boolean_parser_dataT Char _}\n          {cdata : @boolean_parser_completeness_dataT' Char _ _ G data}\n          {rdata : @parser_removal_dataT' _ G _}\n          {gendata : @generic_parser_dataT Char}.\n  Context {gcdata : generic_parser_correctness_dataT}.\n  Context (str : String).\n\n  Local Notation dec T := (T + (T -> False))%type (only parsing).\n\n  Local Notation iffT x y := ((x -> y) * (y -> x))%type (only parsing).\n\n  Lemma dec_prod {A B} (HA : dec A) (HB : dec B) : dec (A * B).\n  Proof.\n    destruct HA; [ destruct HB; [ left; split; assumption | right ] | right ];\n    intros [? ?]; eauto with nocore.\n  Defined.\n\n  Lemma bool_of_sum_dec_prod {A B HA HB}\n    : (@dec_prod A B HA HB) = (andb HA HB) :> bool.\n  Proof. destruct HA, HB; reflexivity. Qed.\n\n  Lemma dec_In {A} {P : A -> Type} (HA : forall a, dec (P a)) ls\n  : dec { a : _ & (In a ls * P a) }.\n  Proof.\n    induction ls as [|x xs IHxs]; simpl.\n    { right; intros [? [? ?]]; assumption. }\n    { destruct (HA x); [ left; exists x; split; eauto | destruct IHxs; [ left | right ] ];\n      intros;\n      destruct_head sigT;\n      destruct_head prod;\n      destruct_head or;\n      subst;\n      eauto. }\n  Defined.\n\n  Lemma parse_complete_stabalize' {len0 valid str' it its}\n        (n m : nat)\n        (Hn : n >= length str')\n        (Hm : m >= length str')\n  : (minimal_parse_of_item (G := G) len0 valid (take n str') it\n     * minimal_parse_of_production (G := G) len0 valid (drop n str') its)\n    -> (minimal_parse_of_item (G := G) len0 valid (take m str') it\n        * minimal_parse_of_production (G := G) len0 valid (drop m str') its).\n  Proof.\n    intros [pi pp]; split;\n    [ eapply expand_minimal_parse_of_item; [ .. | eassumption ]\n    | eapply expand_minimal_parse_of_production; [ .. | eassumption ] ];\n    try reflexivity; eauto.\n    { clear -Hn Hm HSLP.\n      abstract (rewrite !take_long by assumption; reflexivity). }\n    { clear -Hn Hm HSLP.\n      abstract (apply bool_eq_empty; rewrite drop_length; omega). }\n  Defined.\n\n  Definition parse_complete_stabalize'' {len0 valid str' it its}\n        (n m : nat)\n        (Hn : n >= length str')\n        (Hm : m >= length str')\n    := (@parse_complete_stabalize' len0 valid str' it its n m Hn Hm,\n        @parse_complete_stabalize' len0 valid str' it its m n Hm Hn).\n\n  Definition parse_complete_stabalize {len0 valid str' it its}\n        (n : nat)\n        (Hn : n >= length str')\n    := @parse_complete_stabalize'' len0 valid str' it its n (S n) Hn (le_S _ _ Hn).\n\n  Global Arguments parse_complete_stabalize : simpl never.\n\n  Section min.\n    Section parts.\n      Local Ltac expand_onceL :=\n        idtac;\n        match goal with\n          | [ |- ?R (bool_of_sum ?x) ?y ]\n            => let x' := head x in\n               unfold x'\n        end.\n      Local Ltac expand_onceR :=\n        idtac;\n        match goal with\n          | [ |- ?R (bool_of_sum ?x) ?y ]\n            => let y' := head y in\n               unfold y'\n        end.\n      Local Ltac expand_once := try expand_onceL; try expand_onceR.\n      Local Ltac expand_both_once :=\n        idtac;\n        match goal with\n          | [ |- ?R ?x ?y ]\n            => let x' := head x in\n               let y' := head y in\n               try unfold x'; try unfold y'\n        end.\n\n      Local Hint Resolve beq_nat_true : generic_parser_correctness.\n\n      Local Ltac eq_t' :=\n        first [ progress subst_le_proof\n              | progress subst_nat_eq_proof\n              | progress subst_bool_eq_proof\n              | solve [ eauto with generic_parser_correctness nocore ]\n              | rewrite sub_twice, Min.min_r by assumption\n              | rewrite !@min_max_sub\n              | rewrite Nat.sub_max_distr_l\n              | rewrite <- Nat.sub_add_distr\n              | rewrite (proj2 (Nat.ltb_lt _ _)) by assumption\n              | idtac;\n                match goal with\n                  | [ |- ?x = ?x ] => reflexivity\n                  | [ H : ?x = true, H' : ?x = false |- _ ] => exfalso; clear -H H'; congruence\n                  | [ |- ?R ?v _ ]\n                    => match v with\n                       | bool_of_sum (match ?x with\n                                      | inl H => inl (@?L H)\n                                      | inr H' => inr (@?R H')\n                                      end)\n                         => replace v with (bool_of_sum x) by (case x; reflexivity)\n                       | bool_of_sum (match ?x with\n                                      | inl H => inl (@?L H)\n                                      | inr H' => match ?x' with\n                                                  | inl H'0 => inl (@?RL H' H'0)\n                                                  | inr H'0' => inr (@?RR H' H'0')\n                                                  end\n                                      end)\n                         => replace v with (orb (bool_of_sum x) (bool_of_sum x'))\n                           by (case x; case x'; reflexivity)\n                       | bool_of_sum (match ?x with\n                                      | left H => @?L H\n                                      | right H' => @?R H'\n                                      end)\n                         => replace v with (match x with\n                                            | left H => bool_of_sum (L H)\n                                            | right H' => bool_of_sum (R H')\n                                            end)\n                           by (case x; reflexivity)\n                       end\n                  | _ => solve [ eauto with nocore ]\n                  | [ |- ?R (bool_of_sum (sumbool_rect _ _ _ ?sb)) (option_rect _ _ _ (sumbool_rect _ _ _ ?sb)) ]\n                    => destruct sb; simpl\n                  | [ |- context[?e] ]\n                    => not is_var e;\n                      not is_evar e;\n                      match type of e with\n                        | _ <= _ => idtac\n                        | ?x = _ :> nat => not constr_eq e (eq_refl x)\n                      end;\n                      generalize e; intro\n                  | [ H : ?x = cons _ _ |- context[match ?x with _ => _ end] ] => rewrite H\n                end\n              | rewrite fold_left_orb_true\n              | rewrite bool_of_sum_dec_prod\n              | idtac;\n                let R := match goal with |- ?R ?LHS ?RHS => R end in\n                let LHS := match goal with |- ?R ?LHS ?RHS => LHS end in\n                let RHS := match goal with |- ?R ?LHS ?RHS => RHS end in\n                match RHS with\n                  | context Rc[bool_of_sum ?f0]\n                    => match f0 with\n                         | ?f ?ae ?be ?ce ?de ?ee ?ge ?he\n                           => match LHS with\n                                | context Lc[f ?a ?b ?c ?d ?e ?g ?h]\n                                  => unify a ae; unify b be; unify c ce; unify d de; unify e ee; unify g ge; unify h he;\n                                     let v := fresh in\n                                     set (v := f a b c d e g h);\n                                       let L' := context Lc[v] in\n                                       let R' := context Rc[bool_of_sum v] in\n                                       change (R L' R');\n                                         clearbody v; destruct v\n                              end\n                       end\n                end\n              | idtac;\n                let R := match goal with |- ?R ?LHS ?RHS => R end in\n                let LHS := match goal with |- ?R ?LHS ?RHS => LHS end in\n                let RHS := match goal with |- ?R ?LHS ?RHS => RHS end in\n                match RHS with\n                  | context Rc[bool_of_sum ?f0]\n                    => match f0 with\n                         | ?f ?ae ?be ?ce ?de ?ee ?ge\n                           => match LHS with\n                                | context Lc[f ?a ?b ?c ?d ?e ?g]\n                                  => unify a ae; unify b be; unify c ce; unify d de; unify e ee; unify g ge;\n                                     let v := fresh in\n                                     set (v := f a b c d e g);\n                                       let L' := context Lc[v] in\n                                       let R' := context Rc[bool_of_sum v] in\n                                       change (R L' R');\n                                         clearbody v; destruct v\n                              end\n                       end\n                end\n              | idtac;\n                let R := match goal with |- ?R ?LHS ?RHS => R end in\n                let LHS := match goal with |- ?R ?LHS ?RHS => LHS end in\n                let RHS := match goal with |- ?R ?LHS ?RHS => RHS end in\n                match RHS with\n                  | context Rc[bool_of_sum ?f0]\n                    => match f0 with\n                         | ?f ?ae ?be ?ce ?de ?ee\n                           => match LHS with\n                                | context Lc[f ?a ?b ?c ?d ?e]\n                                  => unify a ae; unify b be; unify c ce; unify d de; unify e ee;\n                                     let v := fresh in\n                                     set (v := f a b c d e);\n                                       let L' := context Lc[v] in\n                                       let R' := context Rc[bool_of_sum v] in\n                                       change (R L' R');\n                                         clearbody v; destruct v\n                              end\n                       end\n                end\n              | idtac;\n                let RHS := match goal with |- ?R _ ?RHS => RHS end in\n                match RHS with\n                  | context[match ?it with Terminal _ => _ | _ => _ end]\n                    => destruct it eqn:?\n                  | _ => progress subst\n                  | _ => progress simpl @bool_of_sum\n                  | context G[is_char ?x ?y]\n                    => let H := fresh in\n                       destruct (Utils.dec (is_char x y)) as [H|H];\n                         [ let G' := context G[true] in\n                           transitivity G'; [ | symmetry; exact H ]\n                         | let G' := context G[false] in\n                           transitivity G'; [ | symmetry; exact H ] ]\n                  | context G[beq_nat ?x ?y]\n                    => let H := fresh in\n                       destruct (Utils.dec (beq_nat x y)) as [H|H];\n                         [ let G' := context G[true] in\n                           transitivity G'; [ | symmetry; exact H ]\n                         | let G' := context G[false] in\n                           transitivity G'; [ | symmetry; exact H ] ]\n                  | context[match ?x with _ => _ end]\n                    => let H := match goal with\n                                  | [ H : ?x = cons _ _ |- _ ] => H\n                                end in\n                       etransitivity; [ | rewrite H; reflexivity ]\n                end\n              | idtac;\n                let LHS := match goal with |- ?R ?LHS ?RHS => LHS end in\n                let RHS := match goal with |- ?R ?LHS ?RHS => RHS end in\n                match LHS with\n                | match Utils.dec ?x with _ => _ end\n                  => match RHS with\n                     | context[x]\n                       => destruct (Utils.dec x)\n                     end\n                end\n              | idtac;\n                match goal with\n                | [ H : ?x = true |- context[?x] ] => rewrite H\n                | [ H : ?x = false |- context[?x] ] => rewrite H\n                | [ H : (_ <? _)%nat = true |- _ ]\n                  => apply Nat.ltb_lt in H\n                | [ H : ?T, H' : ~?T |- _ ] => specialize (H' H)\n                | [ H : False |- _ ] => destruct H\n                end ].\n\n      Local Ltac eq_t := expand_once; repeat eq_t'.\n\n      (** Here are some general tactics to do variadic list_rect reasoning.  Unfortunately, they're really slow (~ 20 s), so we don't use them. *)\n      Local Ltac curry_do_change HS :=\n        idtac;\n        match HS with\n          | context HS'[list_rect ?P ?N ?C]\n            => (let P0 := fresh in\n                let N0 := fresh in\n                let C0 := fresh in\n                (*set (P0 := P);*)\n                set (N0 := N);\n                set (C0 := C);\n                let HS'' := context HS'[list_rect P(*0*) N0 C0] in\n                change HS with HS'')\n        end.\n\n      Local Ltac pre_pre_curry_func :=\n        idtac;\n        let LHS := match goal with |- bool_of_sum ?LHS = ?RHS => LHS end in\n        let RHS := match goal with |- bool_of_sum ?LHS = ?RHS => RHS end in\n        curry_do_change LHS;\n          curry_do_change RHS.\n\n      Local Ltac pre_curry_func cont :=\n        idtac;\n        let LHS := match goal with |- bool_of_sum ?LHS = ?RHS => LHS end in\n        let RHS := match goal with |- bool_of_sum ?LHS = ?RHS => RHS end in\n        let ls := match LHS with\n                    | context[list_rect ?P ?N ?C ?ls] => ls\n                  end in\n        let LRL := match LHS with\n                     | context[list_rect ?P ?N ?C] => constr:(list_rect P N C)\n                   end in\n        let LRR := match RHS with\n                     | context[list_rect ?P ?N ?C] => constr:(list_rect P N C)\n                   end in\n        let F := fresh \"F\" in\n        let G := fresh \"G\" in\n        let F' := fresh \"F'\" in\n        let G' := fresh \"G'\" in\n        set (F := LRL);\n          set (G := LRR);\n          set (F' := fun ls (_ : unit) => F ls);\n          set (G' := fun ls (_ : unit) => G ls);\n          change (F ls) with (F' ls tt);\n          change (G ls) with (G' ls tt);\n          subst F G;\n          cont F' G'.\n      Local Ltac curry_func' F G n :=\n        idtac;\n        let LHS := match goal with |- bool_of_sum ?LHS = ?RHS => LHS end in\n        let RHS := match goal with |- bool_of_sum ?LHS = ?RHS => RHS end in\n        let ls := match LHS with\n                    | context[F ?ls ?x0 ?x] => ls\n                  end in\n        let x0 := match LHS with\n                    | context[F ?ls ?x0 ?x] => x0\n                  end in\n        let al := match LHS with\n                    | context[F ?ls ?x0 ?x] => x\n                  end in\n        let ar := match RHS with\n                    | context[G ?ls ?x0 ?x] => x\n                  end in\n        let T := (type of F) in\n        let P := match (eval cbv beta in T) with\n                   | forall (ls : ?lsT) (x0 : @?T ls) (y0 : @?T' ls x0), _ => T'\n                 end in\n        let F' := fresh \"F'\" in\n        let G' := fresh \"G'\" in\n        first [ constr_eq al ar;\n                first [ set (F' := fun ls v => F ls (fst v) (snd v));\n                        set (G' := fun ls (v : sigT (P ls)) => G ls (fst v) (snd v));\n                        progress change (F ls x0 al) with (F' ls (x0, al));\n                        progress change (G ls x0 ar) with (G' ls (x0, ar))\n                      | set (F' := fun ls (v : sigT (P ls)) => F ls (projT1 v) (projT2 v));\n                        set (G' := fun ls (v : sigT (P ls)) => G ls (projT1 v) (projT2 v));\n                        progress change (F ls x0 al) with (F' ls (existT (P ls) x0 al));\n                        progress change (G ls x0 ar) with (G' ls (existT (P ls) x0 ar)) ];\n                try subst F;\n                try subst G;\n                idtac n\n              | not constr_eq al ar;\n                first [ set (F' := fun ls v => F ls (fst v) (snd v));\n                        set (G' := fun ls v => G ls (fst v));\n                        progress change (F ls x0 al) with (F' ls (x0, al));\n                        progress change (G ls x0) with (G' ls (x0, al))\n                      | set (F' := fun ls (v : sigT (P ls)) => F ls (projT1 v) (projT2 v));\n                        set (G' := fun ls (v : sigT (P ls)) => G ls (projT1 v));\n                        progress change (F ls x0 al) with (F' ls (existT (P ls) x0 al));\n                        progress change (G ls x0) with (G' ls (existT (P ls) x0 al)) ];\n                try subst F;\n                try subst G ];\n          cbv beta in *;\n          try curry_func' F' G' (S n).\n      Local Ltac curry_list_rect := pre_pre_curry_func; pre_curry_func ltac:(fun F G => curry_func' F G 0).\n      Local Ltac post_resolve_list_rect :=\n        idtac;\n        (lazymatch goal with\n        | [ |- bool_of_sum (?F ?ls ?x) = ?G ?ls ?x ]\n          => (let y := fresh in\n              let IH := fresh in\n              refine (list_rect\n                        (fun ls' => forall x', bool_of_sum (F ls' x') = G ls' x')\n                        _\n                        _\n                        ls x);\n              subst F G;\n              cbv beta;\n              [ intro y;\n                let LHS := match goal with |- bool_of_sum ?LHS = ?RHS => LHS end in\n                let RHS := match goal with |- bool_of_sum ?LHS = ?RHS => RHS end in\n                match LHS with\n                  | context[list_rect _ ?N ?C]\n                    => subst N\n                end;\n                  match RHS with\n                    | context[list_rect _ ?N ?C]\n                      => subst N\n                  end;\n                  simpl @list_rect;\n                  revert y\n              | intros ?? IH y;\n                let LHS := match goal with |- bool_of_sum ?LHS = ?RHS => LHS end in\n                let RHS := match goal with |- bool_of_sum ?LHS = ?RHS => RHS end in\n                let C := match LHS with | context[list_rect _ ?N ?C] => C end in\n                let C' := match RHS with | context[list_rect _ ?N ?C] => C end in\n                simpl @list_rect;\n                  unfold C at 1, C' at 1;\n                  revert y ];\n              repeat match goal with\n                       | [ |- forall (x : sigT ?P), _ ] => intros_destruct; simpl\n                       | [ |- forall (x : _ * _), _ ] => intros_destruct; simpl\n                     end;\n              [\n              | repeat match type of IH with\n                         | forall (x : sigT ?P), _\n                           => specialize (fun a b => IH (existT P a b)); simpl in IH\n                         | forall (x : _ * _), _\n                           => specialize (fun a b => IH (a, b)); simpl in IH\n                       end ];\n              intros\n             )\n         end).\n      Local Ltac eq_list_rect_slow :=\n        curry_list_rect; post_resolve_list_rect.\n\n      (** And here's the really fast specialized version *)\n      Local Ltac eq_list_rect\n        := (idtac;\n            lazymatch goal with\n            | [ |- ?R (bool_of_sum (list_rect ?P ?N ?C ?ls ?a ?b ?c ?d ?e ?f ?g)) (list_rect ?P' ?N' ?C' ?ls ?a ?e ?f) ]\n              => idtac;\n                 (let R' := match (eval pattern a, e, f in R) with ?R' _ _ _ => R' end in\n                  let P0 := fresh in\n                  let N0 := fresh in\n                  let C0 := fresh in\n                  let P1 := fresh in\n                  let N1 := fresh in\n                  let C1 := fresh in\n                  set (P0 := P);\n                  set (P1 := P');\n                  set (N0 := N);\n                  set (N1 := N');\n                  set (C0 := C);\n                  set (C1 := C');\n                  refine (list_rect\n                            (fun ls' => forall a' b' c' d' e' f' g',\n                                 R' a' e' f'\n                                    (bool_of_sum (list_rect P0 N0 C0 ls' a' b' c' d' e' f' g'))\n                                    (list_rect P1 N1 C1 ls' a' e' f'))\n                            _\n                            _\n                            ls a b c d e f g);\n                  simpl @list_rect;\n                  [ subst N0 N1; simpl; intros\n                  | intros; unfold C0 at 1, C1 at 1; simpl ])\n            | [ |- ?R (bool_of_sum (list_rect ?P ?N ?C ?ls ?a ?b ?c ?d ?e ?f ?g ?h)) (list_rect ?P' ?N' ?C' ?ls ?a ?e (?len0 - ?f)) ]\n              => (let R' := match (eval pattern a, e, f, h in R) with ?R' _ _ _ _ => R' end in\n                  let P0 := fresh in\n                  let N0 := fresh in\n                  let C0 := fresh in\n                  let P1 := fresh in\n                  let N1 := fresh in\n                  let C1 := fresh in\n                  set (P0 := P);\n                  set (P1 := P');\n                  set (N0 := N);\n                  set (N1 := N');\n                  set (C0 := C);\n                  set (C1 := C');\n                  (*replace (len0 - f) with (len0 - f + 0) by omega;*)\n                  refine (list_rect\n                            (fun ls' => forall a' b' c' d' e' f' g' h' h''(* z'*),\n                                 R' a' e' f' h'\n                                    (bool_of_sum (list_rect P0 N0 C0 ls' a' b' c' d' e' f' g' h'))\n                                    (list_rect P1 N1 C1 ls' a' e' (len0 - f'(* + z'*))))\n                            _\n                            _\n                            ls a b c d e f g h h (*0*));\n                  simpl @list_rect;\n                  [ subst N0 N1; simpl; intros\n                  | intros; unfold C0 at 1, C1 at 1; simpl ])\n            | [ |- ?R (bool_of_sum (list_rect ?P ?N ?C ?ls ?a ?b ?c ?d ?e ?f ?g ?h)) (list_rect ?P' ?N' ?C' ?ls ?a ?e ?f ?h) ]\n              => (let R' := match eval pattern a, e, f, h in R with ?R' _ _ _ _ => R' end in\n                             let P0 := fresh in\n                  let N0 := fresh in\n                  let C0 := fresh in\n                  let P1 := fresh in\n                  let N1 := fresh in\n                  let C1 := fresh in\n                  set (P0 := P);\n                  set (P1 := P');\n                  set (N0 := N);\n                  set (N1 := N');\n                  set (C0 := C);\n                  set (C1 := C');\n                  refine (list_rect\n                            (fun ls' => forall a' b' c' d' e' f' g' h' h'',\n                                          R' a' e' f' h'\n                                             (bool_of_sum (list_rect P0 N0 C0 ls' a' b' c' d' e' f' g' h'))\n                                             (list_rect P1 N1 C1 ls' a' e' f' h''))\n                            _\n                            _\n                            ls a b c d e f g h h);\n                  simpl @list_rect;\n                  [ subst N0 N1; simpl; intros\n                  | intros; unfold C0 at 1, C1 at 1; simpl ])\n            | [ |- ?R (bool_of_sum (list_rect ?P ?N ?C ?ls ?a ?b ?c ?d ?e ?f)) (list_rect ?P' ?N' ?C' ?ls ?a ?c ?d ?f) ]\n              => (let P0 := fresh in\n                  let N0 := fresh in\n                  let C0 := fresh in\n                  let P1 := fresh in\n                  let N1 := fresh in\n                  let C1 := fresh in\n                  set (P0 := P);\n                  set (P1 := P');\n                  set (N0 := N);\n                  set (N1 := N');\n                  set (C0 := C);\n                  set (C1 := C');\n                  refine (list_rect\n                            (fun ls' => forall a' b' c' d' e' f' f'' ,\n                                 R (bool_of_sum (list_rect P0 N0 C0 ls' a' b' c' d' e' f'))\n                                   (list_rect P1 N1 C1 ls' a' c' d' f''))\n                            _\n                            _\n                            ls a b c d e f f);\n                  simpl @list_rect;\n                  [ subst N0 N1; simpl; intros\n                  | intros; unfold C0 at 1, C1 at 1; simpl ])\n            | [ |- ?R (bool_of_sum (list_rect ?P ?N ?C ?ls ?a ?b ?c ?d ?e ?f)) (list_rect ?P' ?N' ?C' ?ls ?c ?d ?f) ]\n              => (let P0 := fresh in\n                  let N0 := fresh in\n                  let C0 := fresh in\n                  let P1 := fresh in\n                  let N1 := fresh in\n                  let C1 := fresh in\n                  set (P0 := P);\n                  set (P1 := P');\n                  set (N0 := N);\n                  set (N1 := N');\n                  set (C0 := C);\n                  set (C1 := C');\n                  refine (list_rect\n                            (fun ls' => forall a' b' c' d' e' f' f'' ,\n                                          R (bool_of_sum (list_rect P0 N0 C0 ls' a' b' c' d' e' f'))\n                                            (list_rect P1 N1 C1 ls' c' d' f''))\n                            _\n                            _\n                            ls a b c d e f f);\n                  simpl @list_rect;\n                  [ subst N0 N1; simpl; intros\n                  | intros; unfold C0 at 1, C1 at 1; simpl ])\n            | [ |- ?R (bool_of_sum (list_rect ?P ?N ?C ?ls ?a ?b ?c ?d ?e)) (list_rect ?P' ?N' ?C' ?ls ?b ?c ?e) ]\n              => (let P0 := fresh in\n                  let N0 := fresh in\n                  let C0 := fresh in\n                  let P1 := fresh in\n                  let N1 := fresh in\n                  let C1 := fresh in\n                  set (P0 := P);\n                  set (P1 := P');\n                  set (N0 := N);\n                  set (N1 := N');\n                  set (C0 := C);\n                  set (C1 := C');\n                  refine (list_rect\n                            (fun ls' => forall a' b' c' d' e' e'',\n                                 R (bool_of_sum (list_rect P0 N0 C0 ls' a' b' c' d' e'))\n                                   (list_rect P1 N1 C1 ls' b' c' e''))\n                            _\n                            _\n                            ls a b c d e e);\n                  simpl @list_rect;\n                  [ subst N0 N1; simpl; intros\n                  | intros; unfold C0 at 1, C1 at 1; simpl ])\n            end).\n\n      Local Ltac eq_list_rect_prop1 PH Hv\n        := (idtac;\n            lazymatch goal with\n            | [ |- ?R (bool_of_sum (list_rect ?P ?N ?C ?ls ?a ?b ?c ?d ?e ?f)) (list_rect ?P' ?N' ?C' ?ls ?a ?c ?d ?f) ]\n              => (let P0 := fresh in\n                  let N0 := fresh in\n                  let C0 := fresh in\n                  let P1 := fresh in\n                  let N1 := fresh in\n                  let C1 := fresh in\n                  set (P0 := P);\n                  set (P1 := P');\n                  set (N0 := N);\n                  set (N1 := N');\n                  set (C0 := C);\n                  set (C1 := C');\n                  refine (list_rect\n                            (fun ls' => forall a' b' c' d' e' f' f'',\n                                          PH a'\n                                          -> R (bool_of_sum (list_rect P0 N0 C0 ls' a' b' c' d' e' f'))\n                                             (list_rect P1 N1 C1 ls' a' c' d' f''))\n                            _\n                            _\n                            ls a b c d e f f Hv);\n                  simpl @list_rect;\n                  [ subst N0 N1; simpl; intros\n                  | intros; unfold C0 at 1, C1 at 1; simpl ])\n            end).\n\n      Local Ltac eq_list_rect_fold_left_orb :=\n        idtac;\n        match goal with\n          | [ |- ?R (bool_of_sum (list_rect ?P ?N ?C ?ls)) (fold_left ?orb (map ?f ?ls) ?false) ]\n            => let P' := fresh in\n               let N' := fresh in\n               let N' := fresh in\n               let C' := fresh in\n               let f' := fresh in\n               set (P' := P);\n                 set (N' := N);\n                 set (C' := C);\n                 set (f' := f);\n                 refine (list_rect\n                           (fun ls' => R (bool_of_sum (list_rect P' N' C' ls'))\n                                         (fold_left orb (map f' ls') false))\n                           _\n                           _\n                           ls);\n                 simpl @list_rect; simpl @fold_left; intros;\n                 [ subst P' f' N'\n                 | unfold C' at 1, f' at 2 ]\n        end.\n\n      Local Ltac eq_list_rect_fold_right_orb :=\n        (idtac;\n         lazymatch goal with\n         | [ |- ?R (bool_of_sum (list_rect ?P ?N ?C ?ls)) (fold_right ?orb ?false (map ?f ?ls)) ]\n           => (let P' := fresh in\n               let N' := fresh in\n               let C' := fresh in\n               let f' := fresh in\n               set (P' := P);\n               set (N' := N);\n               set (C' := C);\n               set (f' := f);\n               refine (list_rect\n                         (fun ls' =>\n                              R (bool_of_sum (list_rect P' N' C' ls'))\n                                (fold_right orb false (map f' ls')))\n                         _\n                         _\n                         ls);\n               simpl @list_rect; simpl @fold_right; intros;\n               [ subst P' f' N'\n               | unfold C' at 1, f' at 1 ];\n               cbv beta)\n         | [ |- ?R (bool_of_sum (list_rect ?P ?N ?C ?ls ?k0 ?k1)) (fold_right ?orb ?false (map ?f ?ls)) ]\n           => (let R' := match (eval pattern ls in R) with ?R' _ => R' end in\n               let P' := fresh in\n               let N' := fresh in\n               let C' := fresh in\n               let f' := fresh in\n               set (P' := P);\n               set (N' := N);\n               set (C' := C);\n               set (f' := f);\n               refine (list_rect\n                         (fun ls' => forall k0' k1',\n                              R' ls'\n                                 (bool_of_sum (list_rect P' N' C' ls' k0' k1'))\n                                 (fold_right orb false (map f' ls')))\n                         _\n                         _\n                         ls k0 k1);\n               simpl @list_rect; simpl @fold_right; intros;\n               [ subst P' f' N'\n               | unfold C' at 1, f' at 1 ];\n               cbv beta)\n         | [ |- ?R (bool_of_sum (list_rect ?P ?N ?C ?ls ?k0)) (fold_right ?orb ?false (map ?f ?ls)) ]\n           => (let P' := fresh in\n               let N' := fresh in\n               let C' := fresh in\n               let f' := fresh in\n               set (P' := P);\n               set (N' := N);\n               set (C' := C);\n               set (f' := f);\n               refine (list_rect\n                         (fun ls' => forall k0',\n                              R (bool_of_sum (list_rect P' N' C' ls' k0'))\n                                (fold_right orb false (map f' ls')))\n                         _\n                         _\n                         ls k0);\n               simpl @list_rect; simpl @fold_right; intros;\n               [ subst P' f' N'\n               | unfold C' at 1, f' at 1 ];\n               cbv beta)\n         end).\n\n      Local Ltac t_item str_matches_nonterminal' :=\n        repeat match goal with\n               | [ H : andb _ _ = true |- _ ] => apply char_at_matches_is_char_no_ex in H; [ | assumption ]\n               | [ H : and _ _ |- _ ] => let H0 := fresh in\n                                         let H1 := fresh in\n                                         destruct H as [H0 H1]; try clear H\n               | [ H : or _ _ |- _ ] => let H0 := fresh in destruct H as [H0|H0]; try clear H\n               | [ H : beq_nat _ _ = true |- _ ] => apply Nat.eqb_eq in H\n               | [ H : ?x = 0, H' : context[?x] |- _ ] => rewrite H in H'\n               | _ => progress subst\n               | _ => progress simpl in *\n               | _ => congruence\n               | [ H : context[match get ?n ?s with _ => _ end] |- _ ]\n                 => destruct (get n s) eqn:?\n               | _ => eassumption\n               | [ H : minimal_parse_of_item _ _ _ (NonTerminal ?nt) |- _ ]\n                 => assert (List.In nt (Valid_nonterminals G));\n                   inversion H; clear H\n               | [ H : minimal_parse_of_item _ _ _ (Terminal _) |- _ ]\n                 => inversion H; clear H\n               | [ H : minimal_parse_of_nonterminal _ _ _ ?nt |- List.In ?nt (Valid_nonterminals G) ]\n                 => inversion H; clear H\n               | [ H : is_true (is_char (substring _ 0 _) _) |- _ ] =>\n                 apply length_singleton in H\n               | [ H : context[length (substring _ 0 _)] |- _ ]\n                 => rewrite take_length in H\n               | [ H : beq_nat ?len 1 = false,\n                       H' : ?offset + ?len <= length ?str,\n                            H'' : is_true (is_char (substring ?offset ?len ?str) _)\n                   |- _ ]\n                 => apply length_singleton in H''; rewrite substring_length in H''\n               | [ H : context[min] |- _ ] => rewrite Min.min_l in H by omega\n               | [ H : context[min] |- _ ] => rewrite Min.min_r in H by omega\n               | [ H : _ |- _ ] => rewrite Nat.add_sub in H\n               | [ H : andb (beq_nat _ 1) (char_at_matches _ _ _) = false |- False ] => contradict H\n               | [ |- _ <> false ] => apply Bool.not_false_iff_true\n               | [ |- andb (beq_nat _ 1) (char_at_matches _ _ _) = true ] => apply char_at_matches_is_char\n               | [ |- ex _ ] => eexists; split; eassumption\n               | [ H : context[to_nonterminal (of_nonterminal _)] |- _ ]\n                 => rewrite to_of_nonterminal in H by assumption\n               | [ H : minimal_parse_of_nonterminal _ _ _ (to_nonterminal (of_nonterminal ?nt)) |- _ ]\n                 => assert (List.In nt (Valid_nonterminals G));\n                   [ inversion H; clear H\n                   | rewrite to_of_nonterminal in H by assumption ]\n               | [ H : is_true (is_valid_nonterminal _ (of_nonterminal _)) |- _ ]\n                 => apply initial_nonterminals_correct in H\n               | [ H : List.In (to_nonterminal _) _ |- _ ]\n                 => apply initial_nonterminals_correct' in H\n               | [ H : is_valid_nonterminal initial_nonterminals_data (of_nonterminal ?nt) = false,\n                       H' : List.In ?nt (Valid_nonterminals ?G) |- _ ]\n                 => apply initial_nonterminals_correct in H'; congruence\n               end.\n\n      Section item.\n        Context {len0 valid}\n                (offset : nat) (len0_minus_len : nat)\n                (Hlen : len0 - len0_minus_len = 0 \\/ offset + (len0 - len0_minus_len) <= length str)\n                (str_matches_nonterminal'\n                 : nonterminal_carrierT -> parse_nt_T)\n                (str_matches_nonterminal\n                 : forall nt : nonterminal_carrierT,\n                     dec (minimal_parse_of_nonterminal (G := G) len0 valid (substring offset (len0 - len0_minus_len) str) (to_nonterminal nt))).\n\n        Section valid.\n          Context (Hmatches\n                   : forall nt,\n                      is_valid_nonterminal initial_nonterminals_data nt = true\n                      -> parse_nt_is_correct (substring offset (len0 - len0_minus_len) str) nt (str_matches_nonterminal nt) (str_matches_nonterminal' nt))\n                  (it : item Char).\n\n          Definition parse_item'\n          : dec (minimal_parse_of_item (G := G) len0 valid (substring offset (len0 - len0_minus_len) str) it).\n          Proof.\n            refine (match it return dec (minimal_parse_of_item len0 valid (substring offset _ str) it) with\n                      | Terminal P => if Sumbool.sumbool_of_bool (EqNat.beq_nat (len0 - len0_minus_len) 1 && char_at_matches offset str P)%bool\n                                      then inl (match get offset str as g return get offset str = g -> _ with\n                                                | Some ch => fun H => MinParseTerminal _ _ _ ch _ _ _\n                                                | None => fun _ => !\n                                                end eq_refl)\n                                      else inr (fun _ => !)\n                      | NonTerminal nt => if Sumbool.sumbool_of_bool (is_valid_nonterminal initial_nonterminals_data (of_nonterminal nt))\n                                          then if str_matches_nonterminal (of_nonterminal nt)\n                                               then inl (MinParseNonTerminal _)\n                                               else inr (fun _ => !)\n                                          else inr (fun _ => !)\n                    end);\n              clear str_matches_nonterminal Hmatches;\n              abstract (t_item str_matches_nonterminal').\n          Defined.\n\n          Definition parse_item'_correct\n          : parse_item_is_correct (substring offset (len0 - len0_minus_len) str) it parse_item' (GenericRecognizer.parse_item' str str_matches_nonterminal' offset (len0 - len0_minus_len) it).\n          Proof. eq_t. Qed.\n        End valid.\n\n        Section all.\n          Context (Hmatches\n                   : forall nt,\n                      parse_nt_is_correct (substring offset (len0 - len0_minus_len) str) nt (str_matches_nonterminal nt) (str_matches_nonterminal' nt))\n                  (it : item Char).\n\n          Definition parse_item'_all_correct\n            : parse_item_is_correct (substring offset (len0 - len0_minus_len) str) it (parse_item' it) (GenericRecognizer.parse_item' str str_matches_nonterminal' offset (len0 - len0_minus_len) it).\n          Proof. eq_t. Qed.\n        End all.\n      End item.\n\n      Hint Resolve parse_item'_correct parse_item'_all_correct : generic_parser_correctness.\n\n      Definition parse_item'_ext\n                 {len0 valid}\n                 (offset len0_minus_len : nat)\n                 (Hlen : (len0 - len0_minus_len) = 0 \\/ offset + (len0 - len0_minus_len) <= length str)\n                 (str_matches_nonterminal str_matches_nonterminal'\n                  : forall nt : nonterminal_carrierT,\n                      dec (minimal_parse_of_nonterminal (G := G) len0 valid (substring offset (len0 - len0_minus_len) str) (to_nonterminal nt)))\n                 (ext : forall nt,\n                          str_matches_nonterminal nt = str_matches_nonterminal' nt)\n                (it : item Char)\n      : parse_item' offset len0_minus_len Hlen str_matches_nonterminal it\n        = parse_item' offset len0_minus_len Hlen str_matches_nonterminal' it.\n      Proof.\n        expand_both_once; destruct it; try reflexivity; [].\n        rewrite ext.\n        clear ext str_matches_nonterminal.\n        reflexivity.\n      Qed.\n\n      Section production.\n        Context {len0 valid}\n                (parse_nonterminal\n                 : forall (offset : nat) (len0_minus_len : nat) (Hlen : (len0 - len0_minus_len) = 0 \\/ offset + (len0 - len0_minus_len) <= length str) (nt : nonterminal_carrierT),\n                    dec (minimal_parse_of_nonterminal (G := G) len0 valid (substring offset (len0 - len0_minus_len) str) (to_nonterminal nt))).\n\n        Lemma Hlen_helper {offset len} (Hlen : len = 0 \\/ offset + len <= length str)\n          : length (substring offset len str) = len.\n        Proof.\n          destruct Hlen; subst; rewrite substring_length; simpl;\n          apply Min.min_case_strong; omega.\n        Qed.\n\n        Lemma dec_in_helper {ls it its offset len0_minus_len}\n              (Hlen : (len0 - len0_minus_len) = 0 \\/ offset + (len0 - len0_minus_len) <= length str)\n        : iffT {n0 : nat &\n                     (In (min (length (substring offset (len0 - len0_minus_len) str)) n0) (map (min (length (substring offset (len0 - len0_minus_len) str))) ls) *\n                      minimal_parse_of_item (G := G) len0 valid (take n0 (substring offset (len0 - len0_minus_len) str)) it *\n                      minimal_parse_of_production (G := G) len0 valid (drop n0 (substring offset (len0 - len0_minus_len) str)) its)%type}\n               {n0 : nat &\n                     (In n0 ls *\n                      (minimal_parse_of_item (G := G) len0 valid (substring offset (len0 - max (len0 - n0) len0_minus_len) str) it *\n                       minimal_parse_of_production (G := G) len0 valid (substring (offset + n0) (len0 - (len0_minus_len + n0)) str) its))%type}.\n        Proof.\n          rewrite Hlen_helper by assumption.\n          split; first [ intros [n [[H0 H1] H2]]\n                       | intros [n [H0 [H1 H2]]] ].\n          { destruct (le_lt_dec (len0 - len0_minus_len) n) as [pf|pf].\n            { rewrite Min.min_l in H0 by assumption.\n              clear -H0 H1 H2 rdata cdata pf HSLP.\n              induction ls as [|x xs IHxs]; destruct_head_hnf False.\n              destruct (le_lt_dec (len0 - len0_minus_len) x).\n              { exists x.\n                repeat split.\n                { left; reflexivity. }\n                { eapply expand_minimal_parse_of_item_beq; [ .. | eassumption ].\n                  rewrite take_take, <- Nat.sub_min_distr_l.\n                  rewrite !Min.min_r by omega.\n                  reflexivity. }\n                { eapply expand_minimal_parse_of_production_beq; [ .. | eassumption ].\n                  rewrite drop_take, StringLike.drop_drop.\n                  rewrite Nat.sub_add_distr.\n                  apply bool_eq_empty; rewrite substring_length; apply Min.min_case_strong; generalize dependent (len0 - len0_minus_len); intros; omega. } }\n              { simpl in *.\n                rewrite Min.min_r in H0 by omega.\n                destruct IHxs as [n' [IH0 [IH1 IH2]]].\n                { destruct H0; try omega; assumption. }\n                { exists n'; repeat split; try assumption.\n                  right; assumption. } } }\n            { exists n; repeat split; try assumption.\n              { apply in_map_iff in H0.\n                repeat match goal with\n                       | _ => progress destruct_head ex\n                       | _ => progress destruct_head and\n                       | [ H : context[min ?x ?y] |- _ ]\n                         => rewrite (Min.min_r x y) in H by omega\n                       | _ => progress subst\n                       | [ H : min ?x ?y < ?x |- _ ] => revert H; apply (Min.min_case_strong x y)\n                       | _ => intro\n                       | _ => omega\n                       | _ => assumption\n                       end. }\n              { eapply expand_minimal_parse_of_item_beq; [ .. | eassumption ].\n                rewrite take_take.\n                rewrite <- Nat.sub_min_distr_l, sub_twice.\n                rewrite (Min.min_r len0) by omega.\n                reflexivity. }\n              { eapply expand_minimal_parse_of_production_beq; [ .. | eassumption ].\n                rewrite drop_take, StringLike.drop_drop.\n                rewrite (plus_comm offset), Nat.sub_add_distr; reflexivity. } } }\n          { exists n; repeat split; try assumption.\n            { apply in_map; assumption. }\n            { eapply expand_minimal_parse_of_item_beq; [ .. | eassumption ].\n              rewrite take_take.\n              rewrite <- Nat.sub_min_distr_l, sub_twice.\n              rewrite (Min.min_comm len0), <- !Min.min_assoc, (Min.min_r len0) by omega.\n              reflexivity. }\n            { eapply expand_minimal_parse_of_production_beq; [ .. | eassumption ].\n              rewrite drop_take, StringLike.drop_drop.\n              rewrite (plus_comm offset), Nat.sub_add_distr.\n              reflexivity. } }\n        Defined.\n\n        Local Opaque dec_in_helper.\n\n        Lemma parse_production'_helper {offset len0_minus_len it its} (pf : length (substring offset (len0 - len0_minus_len) str) <= len0)\n        : dec {n0 : nat &\n                    (minimal_parse_of_item (G := G) len0 valid (take n0 (substring offset (len0 - len0_minus_len) str)) it *\n                     minimal_parse_of_production (G := G) len0 valid (drop n0 (substring offset (len0 - len0_minus_len) str)) its)%type}\n          -> dec (minimal_parse_of_production (G := G) len0 valid (substring offset (len0 - len0_minus_len) str) (it :: its)).\n        Proof.\n          intros [H|H]; [ left; destruct H as [n [??]] | right; intro p; apply H; clear H ].\n          { econstructor; eassumption. }\n          { clear -p; abstract (inversion p; subst; eexists; split; eassumption). }\n        Defined.\n\n        Lemma minus_le {x y z} (H : x <= z) : x - y <= z.\n        Proof. omega. Qed.\n\n        Lemma eq_le_trans {x y z} (H : x = y) (H' : y <= z) : x <= z.\n        Proof. subst; assumption. Defined.\n\n        Lemma min_le_r {x y z} (H : y <= z) : min x y <= z.\n        Proof. apply Min.min_case_strong; omega. Qed.\n\n        Lemma lift_le {offset len n length_str} (H : len = 0 \\/ offset + len <= length_str)\n          : len - n = 0 \\/ offset + n + (len - n) <= length_str.\n        Proof.\n          destruct H;\n          [ left; subst\n          | destruct (le_lt_dec n len); [ right | left ] ];\n          omega.\n        Qed.\n\n        Lemma lift_le_min {offset n len length_str} (H : len = 0 \\/ offset + len <= length_str)\n          : min n len = 0 \\/ offset + min n len <= length_str.\n        Proof.\n          apply Min.min_case_strong; [ | intro; assumption ].\n          destruct H; subst; [ left | right ]; omega.\n        Qed.\n\n        Lemma lift_parse_prod {str' offset len0_minus_len a it its}\n              (H : (minimal_parse_of_item\n                      (G := G)\n                      len0 valid\n                      (substring offset (len0 - max (len0 - a) len0_minus_len) str') it *\n                   minimal_parse_of_production\n                     (G := G)\n                     len0 valid\n                     (substring (offset + a) (len0 - (len0_minus_len + a)) str') its)%type)\n          : minimal_parse_of_item\n              (G := G)\n              len0 valid\n              (take a (substring offset (len0 - len0_minus_len) str')) it *\n            minimal_parse_of_production\n              (G := G)\n              len0 valid\n              (drop a (substring offset (len0 - len0_minus_len) str')) its.\n        Proof.\n          destruct H as [pi pp]; split.\n          { eapply expand_minimal_parse_of_item_beq; [ | eassumption ].\n            rewrite take_take, <- Nat.sub_min_distr_l, sub_twice.\n            rewrite (Min.min_comm len0), <- !Min.min_assoc, min_minus_r.\n            reflexivity. }\n          { eapply expand_minimal_parse_of_production_beq; [ | eassumption ].\n            rewrite drop_take, StringLike.drop_drop, (plus_comm a offset), Nat.sub_add_distr.\n            reflexivity. }\n        Defined.\n\n        Local Ltac parse_production'_for_t' :=\n          idtac;\n          match goal with\n            | [ H : (beq_nat _ _) = true |- _ ] => apply EqNat.beq_nat_true in H\n            | _ => progress subst\n            | _ => solve [ constructor; assumption\n                         | constructor;\n                           rewrite substring_length; apply Min.min_case_strong; omega ]\n            | [ H : minimal_parse_of_production _ _ _ nil |- _ ] => (inversion H; clear H)\n            | [ H : minimal_parse_of_production _ _ _ (_::_) |- _ ] => (inversion H; clear H)\n            | [ H : ?x = 0, H' : context[?x] |- _ ] => rewrite H in H'\n            | _ => progress simpl in *\n            | _ => discriminate\n            | [ H : forall x, (_ * _)%type -> _ |- _ ] => specialize (fun x y z => H x (y, z))\n            | _ => solve [ eauto with nocore ]\n            | _ => solve [ apply Min.min_case_strong; omega ]\n            | _ => omega\n            | [ H : or _ _ |- _ ] => let H0 := fresh in destruct H as [H0|H0]; try clear H\n            | [ H : length (substring _ _ _) = 0 |- _ ] => rewrite substring_length in H\n            | [ H : context[min] |- _ ] => rewrite Min.min_l in H by omega\n            | [ H : context[min] |- _ ] => rewrite Min.min_r in H by omega\n            | [ H : _ |- _ ] => rewrite Nat.add_sub in H\n          end.\n        Local Ltac parse_production'_for_t := repeat parse_production'_for_t'.\n\n        Definition full_production_carrierT_reachableT (prod_idx : production_carrierT)\n          := { nt : _\n           & { prefix_count : _\n           & { pre_prod_idx : _\n             & (List.In nt (Valid_nonterminals G)\n                * (apply_n prefix_count production_tl pre_prod_idx = prod_idx)\n                * List.InT pre_prod_idx (nonterminal_to_production (of_nonterminal nt)))%type } } }.\n\n        Lemma production_reachable_convert idx p\n              (H : to_production idx = p)\n              (H' : full_production_carrierT_reachableT idx)\n        : production_is_reachable G p.\n        Proof.\n          subst.\n          destruct H' as [nt H']; exists nt.\n          destruct H' as [count [idx' [[Hvalid H0] H1]]]; subst.\n          erewrite <- nonterminal_to_production_correct by assumption.\n          induction (nonterminal_to_production (of_nonterminal nt)) as [|x xs IHxs]; simpl in *.\n          { destruct_head False. }\n          { destruct_head or; destruct_head sum; subst; specialize_by assumption.\n            { clear IHxs.\n              induction count as [|count IHcount]; simpl.\n              { eexists nil; simpl.\n                split; [ assumption | left; reflexivity ]. }\n              { rewrite apply_n_commute, production_tl_correct.\n                destruct IHcount as [prefix IHcount].\n                match goal with\n                  | [ |- context[_ ++ tl ?ls] ]\n                    => exists (match ls with\n                                 | nil => prefix\n                                 | x::_ => prefix ++ [x]\n                               end);\n                      destruct ls eqn:Heq; simpl in *\n                end;\n                  rewrite ?app_nil_r, <- ?app_assoc in IHcount;\n                  rewrite ?app_nil_r, <- ?app_assoc;\n                  assumption. } }\n            { destruct IHxs as [prefix [H0 H1]].\n              exists prefix.\n              split; [ assumption | right; assumption ]. } }\n        Qed.\n\n        Lemma full_production_carrierT_reachableT_tl {idx}\n              (H : full_production_carrierT_reachableT idx)\n        : full_production_carrierT_reachableT (production_tl idx).\n        Proof.\n          destruct H as [nt H]; exists nt.\n          destruct H as [count H]; exists (S count).\n          destruct H as [idx' H]; exists idx'.\n          destruct_head and; destruct_head Datatypes.prod; simpl; repeat split; try assumption.\n          rewrite apply_n_commute; apply f_equal; assumption.\n        Qed.\n\n        Lemma substring_length_le_helper {offset len0_minus_len}\n          : length (substring offset (len0 - len0_minus_len) str) <= len0.\n        Proof.\n          rewrite substring_length; apply Min.min_case_strong; omega.\n        Qed.\n\n        Lemma Hlen_sub_more {offset n len0_minus_len}\n          : len0 - len0_minus_len = 0 \\/ offset + (len0 - len0_minus_len) <= length str\n            -> len0 - max (len0 - n) len0_minus_len = 0 \\/\n               offset + (len0 - max (len0 - n) len0_minus_len) <= length str.\n        Proof.\n          clear; intros [Hlen|Hlen]; [ left | right ]; apply Max.max_case_strong; omega.\n        Qed.\n\n        Lemma Hlen_sub_some {n len0_minus_len offset}\n          : len0 - len0_minus_len = 0 \\/ offset + (len0 - len0_minus_len) <= length str\n            -> len0 - max (len0 - n) len0_minus_len <= len0.\n        Proof.\n          apply Max.max_case_strong; omega.\n        Qed.\n\n        Lemma Hlen_sub_helper {offset n len0_minus_len}\n          : len0 - len0_minus_len = 0 \\/ offset + (len0 - len0_minus_len) <= length str\n            -> len0 - (len0_minus_len + n) = 0 \\/\n               offset + n + (len0 - (len0_minus_len + n)) <= length str.\n        Proof.\n          rewrite Nat.sub_add_distr.\n          intros [Hlen|Hlen]; try solve [ left; omega | right; omega ].\n          destruct (Compare_dec.le_dec n (len0 - len0_minus_len));\n            solve [ left; omega | right; omega ].\n        Qed.\n\n        (** To match a [production], we must match all of its items.\n            But we may do so on any particular split. *)\n        Definition parse_production'_for\n                 (splits : production_carrierT -> String -> nat -> nat -> list nat)\n                 (Hsplits : forall offset len0_minus_len it its idx pf',\n                     (len0 - len0_minus_len) = 0 \\/ offset + (len0 - len0_minus_len) <= length str\n                     -> full_production_carrierT_reachableT idx\n                     -> production_carrier_valid idx\n                     -> to_production idx = it::its\n                     -> split_list_completeT_for (len0 := len0) (G := G) (valid := valid) it its (substring offset (len0 - len0_minus_len) str) pf' (splits idx str offset (len0 - len0_minus_len)))\n                 (offset len0_minus_len : nat)\n                 (Hlen : (len0 - len0_minus_len) = 0 \\/ offset + (len0 - len0_minus_len) <= length str)\n                 (prod_idx : production_carrierT)\n                 (Hreachable : full_production_carrierT_reachableT prod_idx)\n                 (Hvalid : production_carrier_valid prod_idx)\n        : dec (minimal_parse_of_production (G := G) len0 valid (substring offset (len0 - len0_minus_len) str) (to_production prod_idx)).\n        Proof.\n          revert offset len0_minus_len Hlen.\n          refine\n            (list_rect\n               (fun ps =>\n                  forall (idx : production_carrierT)\n                         (Hreachable : full_production_carrierT_reachableT idx)\n                         (Hvalid : production_carrier_valid idx)\n                         (Hidx : to_production idx = ps)\n                         (offset len0_minus_len : nat)\n                         (Hlen : (len0 - len0_minus_len) = 0 \\/ offset + (len0 - len0_minus_len) <= length str),\n                    dec (minimal_parse_of_production (G := G) len0 valid (substring offset (len0 - len0_minus_len) str) ps))\n               ((** 0-length production, only accept empty *)\n                 fun idx Hidx Hreachable Hvalid offset len0_minus_len Hlen\n                 => match Utils.dec (beq_nat (len0 - len0_minus_len) 0) with\n                      | left H => inl _\n                      | right H => inr (fun p => _)\n                    end)\n               (fun it its parse_production' idx Hreachable Hvalid Hidx offset len0_minus_len Hlen\n                => parse_production'_helper\n                     substring_length_le_helper\n                     (let parse_item := (fun n => parse_item' offset (max (len0 - n) len0_minus_len) (Hlen_sub_more Hlen) (parse_nonterminal offset (max (len0 - n) len0_minus_len) (Hlen_sub_more Hlen)) it) in\n                      let parse_production := (fun n : nat => parse_production' (production_tl idx) (full_production_carrierT_reachableT_tl Hreachable) (production_tl_valid _ Hvalid) (eq_trans (production_tl_correct _) (f_equal (@tl _) Hidx)) (offset + n) (len0_minus_len + n) (Hlen_sub_helper Hlen)) in\n                      match dec_In\n                              (fun n => dec_prod (parse_item n) (parse_production n))\n                              (splits idx str offset (len0 - len0_minus_len))\n                      with\n                        | inl p => inl (existT _ (projT1 p) (lift_parse_prod (snd (projT2 p))))\n                        | inr p\n                          => let H := (_ : split_list_completeT_for (G := G) (len0 := len0) (valid := valid) it its (substring offset (len0 - len0_minus_len) str) substring_length_le_helper (splits idx str offset (len0 - len0_minus_len))) in\n                             inr (fun p' => p (fst (dec_in_helper Hlen) (H p')))\n                      end))\n               (to_production prod_idx)\n               prod_idx\n               Hreachable\n               Hvalid\n               eq_refl);\n            [ clear parse_nonterminal Hsplits splits rdata cdata\n            | clear parse_nonterminal Hsplits splits rdata cdata\n            | clear parse_item parse_production ];\n            abstract parse_production'_for_t.\n        Defined.\n\n        Definition parse_production'_for_correct\n                   (parse_nonterminal'\n                    : forall (offset len0_minus_len : nat) (nt : nonterminal_carrierT),\n                       parse_nt_T)\n                   (parse_nonterminal_eq\n                    : forall offset len0_minus_len Hlen nt,\n                       is_valid_nonterminal initial_nonterminals_data nt = true\n                       -> parse_nt_is_correct (substring offset (len0 - len0_minus_len) str) nt (@parse_nonterminal offset len0_minus_len Hlen nt) (parse_nonterminal' offset len0_minus_len nt))\n                   (splits : production_carrierT -> String -> nat -> nat -> list nat)\n                   (Hsplits : forall offset len0_minus_len it its idx pf',\n                       len0 - len0_minus_len = 0 \\/ offset + (len0 - len0_minus_len) <= length str\n                       -> full_production_carrierT_reachableT idx\n                       -> production_carrier_valid idx\n                       -> to_production idx = it::its\n                       -> split_list_completeT_for (len0 := len0) (G := G) (valid := valid) it its (substring offset (len0 - len0_minus_len) str) pf' (splits idx str offset (len0 - len0_minus_len)))\n                   (offset len0_minus_len z : nat)\n                   (Hlen : len0 - len0_minus_len = 0 \\/ offset + (len0 - len0_minus_len) <= length str)\n                   (prod_idx : production_carrierT)\n                   (Hreachable : full_production_carrierT_reachableT prod_idx)\n                   (Hvalid : production_carrier_valid prod_idx)\n        : parse_production_is_correct (substring offset (len0 - len0_minus_len) str) prod_idx (parse_production'_for splits Hsplits offset len0_minus_len Hlen Hreachable Hvalid) (GenericRecognizer.parse_production'_for (len0 := len0) str parse_nonterminal' splits offset len0_minus_len prod_idx).\n        Proof.\n          eq_t; eq_list_rect; repeat eq_t'; [].\n          expand_onceL; repeat eq_t'; [].\n          expand_onceL; eq_list_rect_fold_right_orb; repeat eq_t'; [].\n          apply ret_orb_production_is_correct; repeat eq_t'; [].\n          eapply ret_production_cons_is_correct; repeat eq_t'.\n        Qed.\n\n        Lemma split_list_completeT_production_is_reachable\n              {it its offset len pf splits idx}\n              (Hlen : len = 0 \\/ offset + len <= length str)\n              (H : split_list_completeT (G := G) splits)\n              (Hreachable : full_production_carrierT_reachableT idx)\n              (Hvalid : production_carrier_valid idx)\n              (Heq : to_production idx = it::its)\n        : split_list_completeT_for (G := G) (len0 := len0) (valid := valid) it its (substring offset len str) pf (splits idx str offset len).\n        Proof.\n          specialize (fun nt Hvalid => H len0 valid str offset len pf nt Hvalid Hlen).\n          hnf in Hreachable.\n          destruct Hreachable as [nt [count [idx' [[Hr0 Hr1] Hr2]]]].\n          specialize (H nt).\n          erewrite <- nonterminal_to_production_correct in H by assumption.\n          apply initial_nonterminals_correct in Hr0.\n          specialize_by assumption.\n          subst.\n          generalize dependent (nonterminal_to_production (of_nonterminal nt)).\n          intro p; induction p as [|x xs IHxs]; simpl.\n          { intros ? []. }\n          { intros H [H'|H']; subst;\n            destruct_head prod;\n            specialize_by assumption; trivial; [].\n            clear dependent xs.\n            generalize dependent idx'.\n            induction count as [|count IHcount]; simpl in *; intros.\n            { repeat match goal with\n                       | [ H : ?x = _::_, H' : context[match ?x with _ => _ end] |- _ ] => rewrite H in H'\n                       | [ H : _ |- _ ] => apply Forall_tails_id in H\n                       | _ => solve [ eauto with nocore ]\n                     end. }\n            { specialize (IHcount (production_tl idx')).\n              specialize_by assumption.\n              rewrite production_tl_correct in IHcount.\n              apply IHcount; clear IHcount.\n              destruct (to_production idx');\n                simpl in *; destruct_head prod; trivial. } }\n        Qed.\n\n        Definition parse_production'\n                 (offset len0_minus_len : nat)\n                 (Hlen : len0 - len0_minus_len = 0 \\/ offset + (len0 - len0_minus_len) <= length str)\n                 (prod_idx : production_carrierT)\n                 (Hreachable : full_production_carrierT_reachableT prod_idx)\n                 (Hvalid : production_carrier_valid prod_idx)\n        : dec (minimal_parse_of_production (G := G) len0 valid (substring offset (len0 - len0_minus_len) str) (to_production prod_idx)).\n        Proof.\n          refine (parse_production'_for _ _ _ _ Hlen Hreachable Hvalid).\n          intros; eapply split_list_completeT_production_is_reachable; try eassumption.\n          eapply split_string_for_production_complete.\n        Defined.\n\n        Definition parse_production'_correct\n                    (parse_nonterminal'\n                    : forall (offset len0_minus_len : nat) (nt : nonterminal_carrierT),\n                        parse_nt_T)\n                   (parse_nonterminal_eq\n                    : forall offset len0_minus_len Hlen nt,\n                       is_valid_nonterminal initial_nonterminals_data nt = true\n                       -> parse_nt_is_correct (substring offset (len0 - len0_minus_len) str) nt (@parse_nonterminal offset len0_minus_len Hlen nt) (parse_nonterminal' offset len0_minus_len nt))\n                   (offset len0_minus_len : nat)\n                   (Hlen : len0 - len0_minus_len = 0 \\/ offset + (len0 - len0_minus_len) <= length str)\n                   (prod_idx : production_carrierT)\n                   (Hreachable : full_production_carrierT_reachableT prod_idx)\n                   (Hvalid : production_carrier_valid prod_idx)\n          : parse_production_is_correct (substring offset (len0 - len0_minus_len) str) prod_idx (parse_production' offset len0_minus_len Hlen Hreachable Hvalid) (GenericRecognizer.parse_production' (len0 := len0) str parse_nonterminal' offset len0_minus_len prod_idx).\n        Proof.\n          apply parse_production'_for_correct; try assumption.\n        Qed.\n      End production.\n\n      Hint Resolve parse_production'_correct : generic_parser_correctness.\n\n      Section productions.\n        Context {len0 valid}\n                (parse_nonterminal'\n                 : forall (offset len0_minus_len : nat)\n                          (nt : nonterminal_carrierT),\n                    parse_nt_T)\n                (parse_nonterminal\n                 : forall (offset len0_minus_len : nat)\n                          (Hlen : len0 - len0_minus_len = 0 \\/ offset + (len0 - len0_minus_len) <= length str)\n                          (nt : nonterminal_carrierT),\n                     dec (minimal_parse_of_nonterminal (G := G) len0 valid (substring offset (len0 - len0_minus_len) str) (to_nonterminal nt)))\n                (Hmatches\n                 : forall (offset len0_minus_len : nat)\n                          (Hlen : len0 - len0_minus_len = 0 \\/ offset + (len0 - len0_minus_len) <= length str)\n                          (nt : nonterminal_carrierT)\n                          (Hvalid : is_valid_nonterminal initial_nonterminals_data nt = true),\n                    parse_nt_is_correct (substring offset (len0 - len0_minus_len) str) nt (parse_nonterminal offset len0_minus_len Hlen nt) (parse_nonterminal' offset len0_minus_len nt))\n                (offset len0_minus_len : nat).\n\n        Definition productions_is_reachable (prods : productions Char)\n          := { nt : _ & { prefix : _ | In nt (Valid_nonterminals G) /\\ prefix ++ prods = Lookup G nt } }.\n\n        Lemma hd_productions_is_reachable (p : production Char) (ps : productions Char) (H : productions_is_reachable (p :: ps))\n        : production_is_reachable G p.\n        Proof.\n          destruct H as [nt H]; exists nt.\n          eexists nil; simpl.\n          destruct H as [prefix [? H]]; split; try assumption; [].\n          rewrite <- H; clear.\n          induction prefix as [|x xs IHxs]; simpl.\n          { left; reflexivity. }\n          { right; assumption. }\n        Qed.\n\n        Local Ltac t_prods_fin :=\n          try solve\n              [ eassumption\n              | idtac;\n                match goal with\n                  | [ p : _ |- _ ] => clear -p; abstract inversion p\n                end\n              | repeat\n                  match goal with\n                    | [ Hreachable : productions_is_reachable (?p :: ?ps)\n                        |- productions_is_reachable ?ps ]\n                      => exists (projT1 Hreachable); destruct Hreachable as [nt Hreachable]; simpl\n                    | [ Hreachable : productions_is_reachable (?p :: ?ps)\n                        |- full_production_carrierT_reachableT _ ]\n                      => exists (projT1 Hreachable); destruct Hreachable as [nt Hreachable]; simpl\n                    | [ Hreachable : { prefix : _ | ?V /\\ prefix ++ ?p::?ps = ?k }\n                        |- { prefix : _ | ?V /\\ prefix ++ ?ps = ?k } ]\n                      => exists (proj1_sig Hreachable ++ [p]); destruct Hreachable as [prefix [? Hreachable]]; split; [ assumption | simpl ]\n                    | [ H : ?x ++ ?y::?z = ?k |- (?x ++ [?y]) ++ ?z = ?k ]\n                      => clear -H; abstract (rewrite <- app_assoc; assumption)\n                    | [ |- { prefix : _ & (_ * _)%type } ]\n                      => eexists nil; simpl; split\n                    | [ H : { x : _ | ?k /\\ _ } |- ?k ] => destruct H as [? [? ?]]; assumption\n                    | [ H : { prefix : _ | _ /\\ prefix ++ ?p :: ?ps = ?k } |- InT ?p ?k ]\n                      => let prefix' := fresh \"prefix\" in\n                         destruct H as [prefix' [? H]]; clear -prefix' H;\n                         generalize dependent k; intros; subst;\n                         induction prefix'; simpl in *\n                    | [ |- ((?x = ?x) + _)%type ] => left; reflexivity\n                    | [ |- (_ + ?k)%type ] => right; assumption\n                    | [ H0 : minimal_parse_of_production _ _ _ ?p -> False,\n                             H1 : minimal_parse_of _ _ _ ?ps -> False,\n                                  H2 : minimal_parse_of _ _ _ (?p :: ?ps)\n                        |- False ]\n                      => clear -H0 H1 H2; abstract (inversion p'; subst; eauto with nocore)\n                    | _ => assumption\n                    | _ => progress simpl in *\n                  end ].\n\n        Definition full_productions_carrierT_reachableT (prods_idx : list production_carrierT)\n          := { nt : _\n           & { prefix : _\n             | List.In nt (Valid_nonterminals G)\n               /\\ prefix ++ prods_idx = nonterminal_to_production (of_nonterminal nt) } }.\n\n        Lemma invert_full_productions_carrierT_reachableT p ps\n              (H : full_productions_carrierT_reachableT (p::ps))\n        : (full_production_carrierT_reachableT p * full_productions_carrierT_reachableT ps)%type.\n        Proof.\n          destruct H as [nt [prefix [H0 H1]]];\n          split; exists nt;\n          [ exists 0; exists p; simpl; repeat split; try assumption\n          | exists (prefix ++ [p]); rewrite <- app_assoc; simpl; split; assumption ].\n          rewrite <- H1.\n          clear.\n          induction prefix; simpl in *; [ left | right ]; trivial.\n        Qed.\n\n        Definition parse_productions'\n                   (Hlen : len0 - len0_minus_len = 0 \\/ offset + (len0 - len0_minus_len) <= length str)\n                   (prods : list production_carrierT)\n                   (Hreachable : full_productions_carrierT_reachableT prods)\n                   (Hvalid : List.Forall production_carrier_valid prods)\n        : dec (minimal_parse_of (G := G) len0 valid (substring offset (len0 - len0_minus_len) str) (List.map to_production prods)).\n        Proof.\n          revert prods Hreachable Hvalid.\n          refine (list_rect\n                    (fun prods\n                     => full_productions_carrierT_reachableT prods\n                        -> List.Forall production_carrier_valid prods\n                        -> dec (minimal_parse_of (G := G) len0 valid (substring offset (len0 - len0_minus_len) str) (List.map to_production prods)))\n                    (fun _ _ => inr (fun p => _))\n                    (fun p ps IHps Hreachable Hvalid\n                     => match parse_production' parse_nonterminal offset len0_minus_len Hlen _ _ with\n                          | inl H => inl (MinParseHead _ _)\n                          | inr H\n                            => match IHps _ _ with\n                                 | inl H' => inl (MinParseTail _ _)\n                                 | inr H' => inr (fun p' => _)\n                               end\n                        end));\n            t_prods_fin; t_prods_fin;\n            try solve [ eapply invert_full_productions_carrierT_reachableT; eassumption\n                      | eapply (@Forall_inv_iff _ production_carrier_valid); eassumption ].\n        Defined.\n\n        Lemma parse_productions'_correct\n              (Hlen : (len0 - len0_minus_len) = 0 \\/ offset + (len0 - len0_minus_len) <= length str)\n              (prods : list production_carrierT)\n              (Hreachable : full_productions_carrierT_reachableT prods)\n              (Hvalid : List.Forall production_carrier_valid prods)\n        : parse_productions_is_correct\n            (substring offset (len0 - len0_minus_len) str) prods\n            (@parse_productions' Hlen prods Hreachable Hvalid)\n            (GenericRecognizer.parse_productions' (len0 := len0) str parse_nonterminal' offset len0_minus_len prods).\n        Proof.\n          eq_t; eq_list_rect_fold_right_orb; repeat eq_t'.\n        Qed.\n      End productions.\n\n      Hint Resolve parse_productions'_correct : generic_parser_correctness.\n\n      Section nonterminals.\n        Section step.\n          Context {len0 valid_len}\n                  (parse_nonterminal'\n                   : forall (p : nat * nat),\n                       prod_relation lt lt p (len0, valid_len)\n                       -> forall (valid : nonterminals_listT)\n                                 (offset len : nat)\n                                 (pf : len <= fst p)\n                                 (nt : nonterminal_carrierT),\n                            parse_nt_T)\n                  (parse_nonterminal\n                   : forall (p : nat * nat)\n                            (pR : prod_relation lt lt p (len0, valid_len))\n                            (valid : nonterminals_listT)\n                            (Hvalid_len : nonterminals_length valid <= snd p)\n                            (offset len : nat)\n                            (Hlen : len = 0 \\/ offset + len <= length str)\n                            (pf : len <= fst p)\n                            (nt : nonterminal_carrierT),\n                       dec (minimal_parse_of_nonterminal (G := G) (fst p) valid (substring offset len str) (to_nonterminal nt)))\n                  (Hmatches\n                   : forall (p : nat * nat)\n                            (pR : prod_relation lt lt p (len0, valid_len))\n                            (valid : nonterminals_listT)\n                            (Hvalid_len : nonterminals_length valid <= snd p)\n                            (offset len : nat)\n                            (Hlen : len = 0 \\/ offset + len <= length str)\n                            (pf : len <= fst p)\n                            (nt : nonterminal_carrierT)\n                            (Hvalid : is_valid_nonterminal initial_nonterminals_data nt = true),\n                       parse_nt_is_correct\n                         (substring offset len str) nt\n                         (@parse_nonterminal p pR valid Hvalid_len offset len Hlen pf nt)\n                         (@parse_nonterminal' p pR valid offset len pf nt)).\n\n          Let Hmatches'\n            : forall x y\n                     (pR pR' : prod_relation lt lt (x, y) (len0, valid_len))\n                     (valid : nonterminals_listT)\n                     (Hvalid_len : nonterminals_length valid <= y)\n                     (offset len : nat)\n                     (Hlen : len = 0 \\/ offset + len <= length str)\n                     (pf : len <= x)\n                     (nt : nonterminal_carrierT)\n                     (Hvalid : is_valid_nonterminal initial_nonterminals_data nt = true),\n              parse_nt_is_correct\n                (substring offset len str) nt\n                (@parse_nonterminal (x, y) pR valid Hvalid_len offset len Hlen pf nt)\n                (@parse_nonterminal' (x, y) pR' valid offset len pf nt).\n          Proof.\n            clear -Hmatches.\n            abstract (\n                unfold prod_relation, lt; simpl;\n                intros; destruct pR as [?|[? ?]], pR' as [?|[? ?]];\n                repeat first [ progress subst\n                             | subst_le_proof\n                             | subst_nat_eq_proof\n                             | omega\n                             | eapply (@Hmatches (_, _)); try eassumption ]\n              ).\n          Qed.\n\n          Local Ltac p_step_t' :=\n            idtac;\n            match goal with\n              | _ => assumption\n              | _ => progress subst\n              | _ => progress specialize_by assumption\n              | _ => progress simpl in *\n              | [ |- pred ?x < ?x ] => is_var x; destruct x\n              | _ => omega\n              | _ => discriminate\n              | _ => congruence\n              | _ => progress destruct_head and\n              | [ H : andb _ _ = true |- _ ] => apply Bool.andb_true_iff in H\n              | [ H : is_true ?e, H' : context[?e] |- _ ] => rewrite H in H'\n              | [ H : context[andb _ true] |- _ ] => rewrite Bool.andb_true_r in H\n              | [ H : negb _ = false |- _ ] => apply Bool.negb_false_iff in H\n              | [ H : beq_nat _ _ = true |- _ ] => apply beq_nat_true in H\n              | [ H : context[beq_nat ?x 0] |- context[pred ?x] ] => is_var x; destruct x\n              | [ H : _ <= 0 |- _ ] => apply le_n_0_eq in H\n              | [ H : 0 = _ |- _ ] => symmetry in H\n              | [ H : nonterminals_length ?v = 0, H' : context[is_valid_nonterminal ?v ?nt] |- _ ]\n                => rewrite nonterminals_length_zero in H' by assumption\n              | [ H : _ |- _ ] => rewrite of_to_nonterminal in H by assumption\n              | _ => rewrite of_to_nonterminal by assumption\n              | [ Hvalid : is_valid_nonterminal _ ?nt = true |- _ ]\n                => is_var nt; unique pose proof (proj1 (initial_nonterminals_correct' _) Hvalid)\n              | [ |- context[Lookup ?G (to_nonterminal ?nt)] ]\n                => is_var nt; rewrite <- nonterminal_to_production_correct by assumption\n              | [ H : context[Lookup ?G (to_nonterminal ?nt)] |- _ ]\n                => is_var nt; rewrite <- nonterminal_to_production_correct in H by assumption\n              | [ H : is_valid_nonterminal ?valid ?nt = true\n                  |- nonterminals_length (remove_nonterminal ?valid ?nt) <= _ ]\n                => let H' := fresh in\n                   assert (H' := remove_nonterminal_dec _ _ H);\n                     hnf in H';\n                     omega\n              | [ H : minimal_parse_of_nonterminal _ _ _ (to_nonterminal ?nt) |- _ ]\n                => inversion H; clear H\n              | [ |- Forall _ _ ] => apply nonterminal_to_production_valid; assumption\n              | [ H : or _ _ |- _ ] => let H0 := fresh in destruct H as [H0|H0]; try clear H\n              | [ |- context[length (substring _ _ _)] ]\n                => rewrite substring_length\n              | _ => apply Min.min_case_strong; omega\n              | [ H : ?x = 0 \\/ ?T |- _ ]\n                => destruct (Compare_dec.zerop x);\n                  [ clear H | assert T by (destruct H; try assumption; omega); clear H ]\n              | [ |- context[min ?x ?y - ?y] ]\n                => rewrite <- Nat.sub_min_distr_r, minus_diag, Min.min_0_r\n              | _ => rewrite Nat.add_sub\n              | _ => rewrite Min.min_r by omega\n              | _ => rewrite Min.min_l by omega\n              | [ H : context[length (substring _ 0 _)] |- _ ]\n                => rewrite take_length in H\n              | [ H : context[length (substring _ _ _)] |- _ ]\n                => rewrite substring_length, Min.min_r, Nat.add_sub in H by omega\n              | [ H : context[?x - (?x - _)] |- _ ] => rewrite sub_twice in H\n              | [ H : context[min ?x ?y] |- _ ] => rewrite (Min.min_r x y) in H by assumption\n              | [ H : context[min ?x ?y] |- _ ] => rewrite (Min.min_l x y) in H by assumption\n              | [ H : context[min ?x ?x] |- _ ] => rewrite Min.min_idempotent in H\n              | [ H : context[?x - ?x] |- _ ] => rewrite minus_diag in H\n              | [ H : context[?x - 0] |- _ ] => rewrite Nat.sub_0_r in H\n            end.\n          Local Ltac p_step := repeat p_step_t'.\n\n          Lemma Hlen_helper_sub_sub {len' len offset} (Hlen : len = 0 \\/ offset + len <= length str)\n            : len' - (len' - len) = 0 \\/ offset + (len' - (len' - len)) <= length str.\n          Proof.\n            clear -Hlen; omega.\n          Qed.\n\n          Definition parse_nonterminal_step\n                     (valid : nonterminals_listT)\n                     (Hvalid_len : nonterminals_length valid <= valid_len)\n                     (offset len : nat)\n                     (Hlen : len = 0 \\/ offset + len <= length str)\n                     (pf : len <= len0)\n                     (nt : nonterminal_carrierT)\n          : dec (minimal_parse_of_nonterminal (G := G) len0 valid (substring offset len str) (to_nonterminal nt)).\n          Proof.\n            destruct (Utils.dec (is_valid_nonterminal initial_nonterminals_data nt)) as [Hvalid|Hvalid];\n            [\n            | right; clear -rdata Hvalid Hlen; intro p;\n              abstract (\n                  inversion p; subst; try omega;\n                  solve_nonterminals_t;\n                  congruence\n            ) ].\n            refine (sumbool_rect (fun _ => _) (fun pf' => _) (fun pf' => _) (lt_dec len len0));\n            simpl;\n            [ (** [str] got smaller, so we reset the valid nonterminals list *)\n              destruct (@parse_productions'\n                          len\n                          initial_nonterminals_data\n                          (fun offset len0_minus_len Hlen nt\n                           => @parse_nonterminal\n                                (len, nonterminals_length initial_nonterminals_data)\n                                (or_introl pf')\n                                initial_nonterminals_data\n                                (reflexivity _)\n                                offset (len - len0_minus_len) Hlen (le_minus _ _) nt)\n                          offset (len - len)\n                          (Hlen_helper_sub_sub Hlen)\n                          (nonterminal_to_production nt))\n              as [mp|nmp];\n              [ eexists _, nil; simpl; split;\n                [ apply initial_nonterminals_correct'; eassumption\n                | rewrite of_to_nonterminal by assumption; reflexivity ]\n              |\n              | left; apply MinParseNonTerminalStrLt\n              | right; intro mp ]\n            | ((** [str] didn't get smaller, so we cache the fact that we've hit this nonterminal already *)\n              refine (sumbool_rect\n                        (fun _ => _)\n                        (fun is_valid => _)\n                        (fun is_valid => _)\n                        (Sumbool.sumbool_of_bool (negb (EqNat.beq_nat valid_len 0) && is_valid_nonterminal valid nt)));\n              [ ((** It was valid, so we can remove it *)\n                  edestruct (fun pf'' pf'''\n                            => @parse_productions'\n                                 len0\n                                 (remove_nonterminal valid nt)\n                                 (fun offset len0_minus_len Hlen\n                                  => @parse_nonterminal\n                                       (len0, pred valid_len)\n                                       (or_intror (conj eq_refl pf''))\n                                       (remove_nonterminal valid nt)\n                                       pf''' offset (len0 - len0_minus_len)\n                                       Hlen (le_minus _ _))\n                                 offset (len0 - len)\n                                 (Hlen_helper_sub_sub Hlen)\n                                 (nonterminal_to_production nt))\n                  as [mp|nmp];\n                  [\n                  |\n                  | eexists _, nil; simpl; split;\n                    [ apply initial_nonterminals_correct'; eassumption\n                    | rewrite of_to_nonterminal by assumption; reflexivity ]\n                  |\n                  | left; apply MinParseNonTerminalStrEq\n                  | right; intro mp ])\n              | ((** oops, we already saw this nonterminal in the past.  ABORT! *)\n                simpl in *;\n                right; intro mp) ])\n            ];\n            try first [ clear -is_valid; abstract p_step\n                      | clear -Hlen pf'; abstract p_step\n                      | clear -HSLP pf'; abstract p_step\n                      | clear -HSLP Hlen pf pf'; abstract p_step\n                      | clear -rdata Hvalid; abstract p_step\n                      | clear -rdata Hvalid mp; abstract p_step\n                      | clear -rdata Hvalid pf mp; abstract p_step\n                      | clear -rdata Hvalid is_valid; abstract p_step\n                      | clear -rdata Hvalid_len is_valid; abstract p_step\n                      | clear -HSLP rdata Hvalid Hlen mp; abstract p_step\n                      | clear -HSLP rdata Hvalid Hlen pf' mp nmp; abstract p_step\n                      | clear -HSLP rdata Hvalid Hlen Hvalid_len is_valid pf' mp; abstract p_step ].\n          Defined.\n\n          Definition parse_nonterminal_step_correct\n                     (valid : nonterminals_listT)\n                     (Hvalid_len : nonterminals_length valid <= valid_len)\n                     (offset len : nat)\n                     (Hlen : len = 0 \\/ offset + len <= length str)\n                     (pf pf' : len <= len0)\n                     (nt : nonterminal_carrierT)\n                     (Hvalid : is_valid_nonterminal initial_nonterminals_data nt = true)\n            : parse_nt_is_correct\n                (substring offset len str) nt\n                (@parse_nonterminal_step valid Hvalid_len offset len Hlen pf nt)\n                (GenericRecognizer.parse_nonterminal_step str parse_nonterminal' valid offset pf' nt).\n          Proof.\n            eq_t.\n            destruct (Utils.dec (is_valid_nonterminal initial_nonterminals_data nt)) as [Hvalid'|Hvalid']; simpl;\n              repeat eq_t'.\n            { apply ret_nt_is_correct; try assumption; [].\n              replace len with (len - (len - len)) at 1 by omega.\n              eapply parse_productions'_correct;\n                repeat eq_t'. }\n            { apply ret_nt_is_correct; try assumption; [].\n              replace len with (len0 - (len0 - len)) at 1 by omega.\n              match goal with\n              | [ |- context[?x <? ?y] ]\n                => destruct (x <? y) eqn:?\n              end;\n                repeat eq_t'. }\n          Qed.\n        End step.\n\n        Section wf.\n          Definition parse_nonterminal_or_abort\n          : forall (p : nat * nat)\n                   (valid : nonterminals_listT)\n                   (Hvalid_len : nonterminals_length valid <= snd p)\n                   (offset len : nat)\n                   (Hlen : len = 0 \\/ offset + len <= length str)\n                   (pf : len <= fst p)\n                   (nt : nonterminal_carrierT),\n              dec (minimal_parse_of_nonterminal (G := G) (fst p) valid (substring offset len str) (to_nonterminal nt))\n            := @Fix\n                 (nat * nat)\n                 _\n                 (well_founded_prod_relation lt_wf lt_wf)\n                 _\n                 (fun sl => @parse_nonterminal_step (fst sl) (snd sl)).\n\n          Lemma parse_nonterminal_or_abort_correct\n                (p : nat * nat)\n                (valid : nonterminals_listT)\n                (Hvalid_len : nonterminals_length valid <= snd p)\n                (offset len : nat)\n                (Hlen : len = 0 \\/ offset + len <= length str)\n                (pf : len <= fst p)\n                (nt : nonterminal_carrierT)\n                (Hvalid : is_valid_nonterminal initial_nonterminals_data nt)\n          : parse_nt_is_correct\n              (substring offset len str) nt\n              (@parse_nonterminal_or_abort p valid Hvalid_len offset len Hlen pf nt)\n              (GenericRecognizer.parse_nonterminal_or_abort str p valid offset pf nt).\n          Proof.\n            expand_once.\n            revert valid Hvalid_len offset len Hlen pf nt Hvalid.\n            match goal with\n              | [ |- context[Fix ?Wf _ _ ?p] ]\n                => induction (Wf p) as [?? IH]; intros\n            end.\n            match goal with\n            | [ |- ?R ?x ?y ] => set (x' := x)\n            end.\n            rewrite Fix5_eq\n              by (intros; apply parse_nonterminal_step_ext; eauto with nocore);\n              subst x'.\n            destruct_head prod.\n            R_etransitivity_eq.\n            { eapply parse_nonterminal_step_correct;\n              first [ intros; eapply IH; eassumption\n                    | assumption ]. }\n            { match goal with\n              | [ |- bool_of_sum ?x = bool_of_sum ?y ]\n                => destruct x, y; try reflexivity; exfalso; eauto with nocore\n              end. }\n            Unshelve.\n            assumption.\n            assumption.\n            assumption.\n            assumption.\n            assumption.\n          Qed.\n\n          Hint Resolve parse_nonterminal_or_abort_correct : generic_parser_correctness .\n\n          Definition parse_nonterminal'_substring\n                     (nt : nonterminal_carrierT)\n          : dec (minimal_parse_of_nonterminal (G := G) (length str) initial_nonterminals_data (substring 0 (length str) str) (to_nonterminal nt)).\n          Proof.\n            destruct (Utils.dec (is_valid_nonterminal initial_nonterminals_data nt)) as [Hvalid|Hvalid].\n            { eapply (@parse_nonterminal_or_abort (length str, nonterminals_length initial_nonterminals_data));\n              try first [ reflexivity | eassumption | right; reflexivity ]. }\n            { right; intro p.\n              clear -Hvalid p rdata.\n              abstract (\n                  inversion p; subst; try omega;\n                  repeat match goal with\n                           | [ H : is_true (is_valid_nonterminal initial_nonterminals_data (of_nonterminal _)) |- _ ]\n                             => apply initial_nonterminals_correct in H\n                           | [ |- is_valid_nonterminal initial_nonterminals_data (of_nonterminal _) = true ]\n                             => apply initial_nonterminals_correct\n                           | [ H : In (to_nonterminal _) (Valid_nonterminals ?G) |- _ ]\n                             => apply initial_nonterminals_correct' in H\n                           | [ H : context[of_nonterminal (to_nonterminal _)] |- _ ]\n                             => rewrite of_to_nonterminal in H by assumption\n                           | _ => congruence\n                           | [ H : _ = false |- _ ] => apply Bool.not_true_iff_false in H; apply H; clear H\n                         end\n                ). }\n          Defined.\n\n          Definition parse_nonterminal'_substring_minus\n                     (nt : nonterminal_carrierT)\n          : dec (minimal_parse_of_nonterminal (G := G) (length str) initial_nonterminals_data (substring 0 (length str - 0) str) (to_nonterminal nt)).\n          Proof.\n            destruct (parse_nonterminal'_substring nt) as [p|p]; [ left | right ];\n              rewrite <- minus_n_O;\n              exact p.\n          Defined.\n\n          Definition parse_nonterminal'\n                     (nt : nonterminal_carrierT)\n          : dec (minimal_parse_of_nonterminal (G := G) (length str) initial_nonterminals_data str (to_nonterminal nt)).\n          Proof.\n            destruct (parse_nonterminal'_substring nt) as [p|np];\n            [ left | right; intro p; apply np; clear np ].\n            { eapply expand_minimal_parse_of_nonterminal_beq; [ | eassumption ].\n              rewrite substring_correct3; reflexivity. }\n            { eapply expand_minimal_parse_of_nonterminal_beq; [ | eassumption ].\n              rewrite substring_correct3; reflexivity. }\n          Defined.\n\n          Lemma parse_nonterminal'_substring_correct\n                (nt : nonterminal_carrierT)\n          : parse_nt_is_correct\n              str nt\n              (@parse_nonterminal'_substring nt)\n              (GenericRecognizer.parse_nonterminal' str nt).\n          Proof.\n            rewrite <- drop_0 at 1.\n            erewrite <- take_long at 1 by reflexivity.\n            rewrite drop_length, <- minus_n_O.\n            expand_once.\n            destruct (Utils.dec (is_valid_nonterminal initial_nonterminals_data nt)) as [H|H];\n              repeat eq_t'.\n            { eapply (parse_nonterminal_or_abort_correct (_, _)); assumption. }\n            { unfold GenericRecognizer.parse_nonterminal_or_abort.\n              rewrite Fix5_eq by (intros; apply parse_nonterminal_step_ext; assumption).\n              unfold GenericRecognizer.parse_nonterminal_step at 1.\n              simpl.\n              rewrite H, Bool.andb_false_r; simpl.\n              edestruct lt_dec; try omega; simpl.\n              repeat eq_t'. }\n          Qed.\n\n          Lemma parse_nonterminal'_substring_minus_correct\n                (nt : nonterminal_carrierT)\n          : parse_nt_is_correct\n              str nt\n              (@parse_nonterminal'_substring_minus nt)\n              (GenericRecognizer.parse_nonterminal' str nt).\n          Proof.\n            R_etransitivity_eq; [ eapply parse_nonterminal'_substring_correct | ].\n            unfold parse_nonterminal'_substring_minus.\n            edestruct parse_nonterminal'_substring;\n              destruct (minus_n_O (length str)); reflexivity.\n          Qed.\n\n          Lemma parse_nonterminal'_correct\n                (nt : nonterminal_carrierT)\n          : parse_nt_is_correct\n              str nt\n              (@parse_nonterminal' nt)\n              (GenericRecognizer.parse_nonterminal' str nt).\n          Proof.\n            R_etransitivity_eq.\n            { eapply parse_nonterminal'_substring_correct. }\n            { unfold parse_nonterminal'.\n              symmetry.\n              repeat eq_t'. }\n          Qed.\n\n          Definition parse_nonterminal\n                     (nt : String.string)\n          : dec (minimal_parse_of_nonterminal (G := G) (length str) initial_nonterminals_data str nt).\n          Proof.\n            destruct (parse_nonterminal' (of_nonterminal nt)) as [p|p]; [ left | right ].\n            { clear -p rdata.\n              abstract (\n                  rewrite to_of_nonterminal in p; [ assumption | ];\n                  inversion p; subst; try omega;\n                  repeat match goal with\n                           | _ => assumption\n                           | [ H : is_true (is_valid_nonterminal initial_nonterminals_data (of_nonterminal _)) |- _ ]\n                             => apply initial_nonterminals_correct in H\n                           | [ |- is_valid_nonterminal initial_nonterminals_data (of_nonterminal _) = true ]\n                             => apply initial_nonterminals_correct\n                           | [ H : In (to_nonterminal _) (Valid_nonterminals ?G) |- _ ]\n                             => apply initial_nonterminals_correct' in H\n                           | [ H : context[of_nonterminal (to_nonterminal _)] |- _ ]\n                             => rewrite of_to_nonterminal in H by assumption\n                         end\n                ). }\n            { intro p'; apply p; clear p.\n              abstract (\n                  rewrite to_of_nonterminal; [ assumption | ];\n                  inversion p'; subst; try omega;\n                  repeat match goal with\n                           | _ => assumption\n                           | [ H : is_true (is_valid_nonterminal initial_nonterminals_data (of_nonterminal _)) |- _ ]\n                             => apply initial_nonterminals_correct in H\n                           | [ |- is_valid_nonterminal initial_nonterminals_data (of_nonterminal _) = true ]\n                             => apply initial_nonterminals_correct\n                           | [ H : In (to_nonterminal _) (Valid_nonterminals ?G) |- _ ]\n                             => apply initial_nonterminals_correct' in H\n                           | [ H : context[of_nonterminal (to_nonterminal _)] |- _ ]\n                             => rewrite of_to_nonterminal in H by assumption\n                         end\n                ). }\n          Defined.\n\n          Lemma parse_nonterminal_correct\n                (nt : String.string)\n          : parse_nt_is_correct\n              str (of_nonterminal nt)\n              (@parse_nonterminal nt)\n              (GenericRecognizer.parse_nonterminal str nt).\n          Proof.\n            expand_once.\n            repeat eq_t'.\n            eapply parse_nonterminal'_correct.\n          Qed.\n\n          Lemma parse_nonterminal_invalid_none\n                nt (H : is_valid_nonterminal initial_nonterminals_data (of_nonterminal nt) = false)\n            : @parse_nonterminal nt = false :> bool.\n          Proof.\n            unfold parse_nonterminal; repeat eq_t'.\n            unfold parse_nonterminal'; repeat eq_t'.\n            unfold parse_nonterminal'_substring; repeat eq_t'.\n            congruence.\n          Qed.\n\n          Lemma parse_nonterminal_invalid_none'\n                nt (H : ~List.In nt (Valid_nonterminals G))\n            : @parse_nonterminal nt = false :> bool.\n          Proof.\n            apply parse_nonterminal_invalid_none.\n            destruct (is_valid_nonterminal initial_nonterminals_data (of_nonterminal nt)) eqn:H'; trivial.\n            apply initial_nonterminals_correct in H'.\n            tauto.\n          Qed.\n\n          Lemma parse_nonterminal_correct'\n                (nt : nonterminal_carrierT)\n          : parse_nt_is_correct\n              str nt\n              (@parse_nonterminal (to_nonterminal nt))\n              (GenericRecognizer.parse_nonterminal str (to_nonterminal nt)).\n          Proof.\n            expand_once.\n            repeat eq_t'.\n            destruct (Utils.dec (is_valid_nonterminal initial_nonterminals_data nt)) as [H|H].\n            { rewrite of_to_nonterminal by assumption.\n              apply parse_nonterminal'_correct. }\n            { destruct (Utils.dec (is_valid_nonterminal initial_nonterminals_data (of_nonterminal (to_nonterminal nt)))) as [H'|H'].\n              { apply initial_nonterminals_correct, initial_nonterminals_correct' in H'.\n                congruence. }\n              { unfold GenericRecognizer.parse_nonterminal'.\n                unfold GenericRecognizer.parse_nonterminal_or_abort.\n                rewrite Fix5_eq by (intros; apply parse_nonterminal_step_ext; assumption).\n                unfold GenericRecognizer.parse_nonterminal_step at 1.\n                simpl.\n                rewrite H', Bool.andb_false_r; simpl.\n                edestruct lt_dec; try omega; simpl.\n                repeat eq_t'.\n                R_etransitivity_eq; [ eapply ret_nt_invalid_is_correct | ].\n                symmetry.\n                unfold parse_nonterminal'; repeat eq_t'.\n                unfold parse_nonterminal'_substring; repeat eq_t'.\n                congruence. } }\n          Qed.\n        End wf.\n      End nonterminals.\n    End parts.\n\n    Local Ltac str_to_substring :=\n      rewrite <- drop_0 at 1;\n      erewrite <- take_long at 1 by reflexivity;\n      rewrite drop_length(*, <- minus_n_O at 1*).\n    Local Ltac substring_to_str :=\n      repeat rewrite <- minus_n_O at 1; rewrite drop_0, take_long at 1 by reflexivity.\n\n    Lemma Hlen0 {lenstr} : lenstr - 0 = 0 \\/ 0 + (lenstr - 0) <= lenstr.\n    Proof. omega. Qed.\n\n\n    Section item.\n      Context (it : item Char).\n\n      Definition parse_item_substring : dec _\n        := parse_item' (len0 := length str) 0 0 Hlen0 (@parse_nonterminal'_substring_minus) it.\n\n      Definition parse_item\n        : dec (minimal_parse_of_item (G := G) (length str) initial_nonterminals_data str it).\n      Proof.\n        destruct parse_item_substring as [p|np];\n        [ left | right; intro p; apply np; clear np ];\n        (eapply expand_minimal_parse_of_item_beq; [ | eassumption ]);\n        clear -HSLP; abstract (rewrite <- minus_n_O, substring_correct3'; reflexivity).\n      Defined.\n\n      Lemma parse_item_substring_correct\n      : parse_item_is_correct\n          str it\n          parse_item_substring\n          (GenericRecognizer.parse_item str it).\n      Proof.\n        str_to_substring.\n        unfold GenericRecognizer.parse_item.\n        rewrite (minus_n_O (length str)) at 6;\n          apply parse_item'_all_correct; intro; substring_to_str.\n        apply parse_nonterminal'_substring_minus_correct.\n      Qed.\n\n      Lemma parse_item_correct\n        : parse_item_is_correct\n            str it\n            parse_item\n            (GenericRecognizer.parse_item str it).\n      Proof.\n        R_etransitivity_eq.\n        { eapply parse_item_substring_correct. }\n        { unfold parse_item;\n          destruct parse_item_substring; reflexivity. }\n      Qed.\n    End item.\n\n    Section production.\n      Context (p : production_carrierT)\n              (Hreachable : full_production_carrierT_reachableT p)\n              (Hvalid : production_carrier_valid p).\n\n      Definition parse_production_substring_minus\n        : dec (minimal_parse_of_production (G := G) (length str) initial_nonterminals_data (substring 0 (length str - 0) str) (to_production p)).\n      Proof.\n        eapply parse_production'; [ | right; clear; apply le_minus | reflexivity.. | assumption | assumption ].\n        intros.\n        eapply (@parse_nonterminal_or_abort (length str, _));\n          simpl; try reflexivity; subst; try assumption; apply le_minus.\n      Defined.\n\n      Definition parse_production_substring\n        : dec (minimal_parse_of_production (G := G) (length str) initial_nonterminals_data (substring 0 (length str) str) (to_production p)).\n      Proof.\n        destruct parse_production_substring_minus as [p'|p']; [ left | right ];\n          rewrite <- minus_n_O in p';\n          exact p'.\n      Defined.\n\n      Lemma parse_production_substring_minus_correct\n        : parse_production_is_correct\n            str p\n            parse_production_substring_minus\n            (GenericRecognizer.parse_production str p).\n      Proof.\n        str_to_substring.\n        unfold GenericRecognizer.parse_production, parse_production_substring.\n        apply parse_production'_correct.\n        simpl; intros.\n        eapply (parse_nonterminal_or_abort_correct (_, _)).\n        assumption.\n      Qed.\n\n      Definition parse_production\n        : dec (minimal_parse_of_production (G := G) (length str) initial_nonterminals_data str (to_production p)).\n      Proof.\n        destruct parse_production_substring as [p'|np];\n        [ left | right; intro p'; apply np; clear np ];\n        (eapply expand_minimal_parse_of_production_beq; [ | eassumption ]);\n        clear -HSLP; abstract (rewrite substring_correct3'; reflexivity).\n      Defined.\n\n      Lemma parse_production_substring_correct\n        : parse_production_is_correct\n            str p\n            parse_production_substring\n            (GenericRecognizer.parse_production str p).\n      Proof.\n        R_etransitivity_eq; [ eapply parse_production_substring_minus_correct | ].\n        unfold parse_production_substring.\n        destruct parse_production_substring_minus;\n          destruct (minus_n_O (length str)); reflexivity.\n      Qed.\n\n      Lemma parse_production_correct\n      : parse_production_is_correct\n            str p\n            parse_production\n            (GenericRecognizer.parse_production str p).\n      Proof.\n        R_etransitivity_eq.\n        { eapply parse_production_substring_correct. }\n        { unfold parse_production.\n          destruct parse_production_substring; reflexivity. }\n      Qed.\n    End production.\n\n    Section productions.\n      Context (ps : list production_carrierT)\n              (Hreachable : full_productions_carrierT_reachableT ps)\n              (Hvalid : List.Forall production_carrier_valid ps).\n\n      Definition parse_productions_substring_minus\n        : dec (minimal_parse_of (G := G) (length str) initial_nonterminals_data (substring 0 (length str - 0) str) (List.map to_production ps)).\n      Proof.\n        eapply parse_productions'; [ | right; apply le_minus | reflexivity.. | assumption | assumption ].\n        intros.\n        eapply (@parse_nonterminal_or_abort (length str, _));\n          simpl; try reflexivity; subst; try apply le_minus; assumption.\n      Defined.\n\n      Definition parse_productions_substring\n        : dec (minimal_parse_of (G := G) (length str) initial_nonterminals_data (substring 0 (length str) str) (List.map to_production ps)).\n      Proof.\n        destruct parse_productions_substring_minus as [p'|p']; [ left | right ];\n          rewrite <- minus_n_O in p';\n          exact p'.\n      Defined.\n\n      Definition parse_productions\n        : dec (minimal_parse_of (G := G) (length str) initial_nonterminals_data str (List.map to_production ps)).\n      Proof.\n        destruct parse_productions_substring as [p'|np];\n        [ left | right; intro p'; apply np; clear np ];\n        (eapply expand_minimal_parse_of_beq; [ | eassumption ]);\n        clear -HSLP; abstract (rewrite substring_correct3'; reflexivity).\n      Defined.\n\n      Lemma parse_productions_substring_minus_correct\n      : parse_productions_is_correct\n            str ps\n            parse_productions_substring_minus\n            (GenericRecognizer.parse_productions str ps).\n      Proof.\n        str_to_substring; apply parse_productions'_correct; simpl; intros.\n        eapply (parse_nonterminal_or_abort_correct (_, _)).\n        assumption.\n      Qed.\n\n      Lemma parse_productions_substring_correct\n      : parse_productions_is_correct\n            str ps\n            parse_productions_substring\n            (GenericRecognizer.parse_productions str ps).\n      Proof.\n        R_etransitivity_eq; [ eapply parse_productions_substring_minus_correct | ].\n        unfold parse_productions_substring.\n        destruct parse_productions_substring_minus;\n          destruct (minus_n_O (length str)); reflexivity.\n      Qed.\n\n      Lemma parse_productions_correct\n      : parse_productions_is_correct\n            str ps\n            parse_productions\n            (GenericRecognizer.parse_productions str ps).\n      Proof.\n        R_etransitivity_eq.\n        { apply parse_productions_substring_correct. }\n        { unfold parse_productions.\n          destruct parse_productions_substring; reflexivity. }\n      Qed.\n    End productions.\n  End min.\nEnd recursive_descent_parser.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/GenericRecognizerMin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23544472381675335}}
{"text": "(******************************************************************************)\n(*       Copyright (C) 2014 Florent Hivert <florent.hivert@lri.fr>            *)\n(*                                                                            *)\n(*  Distributed under the terms of the GNU General Public License (GPL)       *)\n(*                                                                            *)\n(*    This code is distributed in the hope that it will be useful,            *)\n(*    but WITHOUT ANY WARRANTY; without even the implied warranty of          *)\n(*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU       *)\n(*    General Public License for more details.                                *)\n(*                                                                            *)\n(*  The full text of the GPL is available at:                                 *)\n(*                                                                            *)\n(*                  http://www.gnu.org/licenses/                              *)\n(******************************************************************************)\nAdd Rec LoadPath \"../Combi/LRrule\".\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import ssreflect ssrfun ssrbool eqtype choice ssrnat seq ssrint rat\n               fintype bigop path ssralg ssrnum.\n(* Import bigop before ssralg/ssrnum to get correct printing of \\sum \\prod*)\n\nRequire Import tools subseq partition.\n\nImport GRing.Theory.\nImport Num.Theory.\n\n(* Lemma about rational computation **************************************)\n\nDefinition int_to_rat : int -> rat := intmul (GRing.one rat_Ring).\nCoercion int_to_rat : int >-> rat.\n\nLemma int_to_ratD : {morph int_to_rat : n m / (n + m)%R >-> (n + m)%R}.\nProof. move => m n /=; by apply mulrzDl. Qed.\n\nLemma int_to_ratM : {morph int_to_rat : n m / (n * m)%R >-> (n * m)%R}.\nProof. move => m n /=; by rewrite -intrM. Qed.\n\nSection FieldLemmas.\n\nLocal Open Scope ring_scope.\n\nLemma iter_plus1 n : (iter n (+%R (1 : rat)) 0 = int_to_rat n)%R.\nProof.\n  elim: n => [//= | n IHn] /=.\n  by rewrite -add1n PoszD IHn /int_to_rat mulrzDl.\nQed.\n\nLemma quot_eq1 (R : fieldType) (x y : R) : x / y = 1 -> x = y.\nProof.\n  move=> H.\n  have := GRing.Field.intro_unit H; rewrite invr_eq0 => Hy.\n  rewrite -[y]mul1r -H -mulrA [_ * y]mulrC.\n  by rewrite (divff Hy) mulr1.\nQed.\n\nEnd FieldLemmas.\n", "meta": {"author": "hivert", "repo": "Coq-HookLength", "sha": "f9f044a6defdeea7db48d8fe38735c32129cd928", "save_path": "github-repos/coq/hivert-Coq-HookLength", "path": "github-repos/coq/hivert-Coq-HookLength/Coq-HookLength-f9f044a6defdeea7db48d8fe38735c32129cd928/rat_coerce.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23538156343327818}}
{"text": "Require Import List.\nRequire Import CoqCompile.CpsK.\nRequire Import ExtLib.Structures.Monads.\nRequire Import ExtLib.Structures.Maps.\nRequire Import ExtLib.Data.Map.FMapAList.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.Monads.ReaderMonad ExtLib.Data.Monads.OptionMonad.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nModule Alpha.\n  Import CPSK.\n\n  Section maps.\n    Variable env_v : Type -> Type.\n    Context {Mv : DMap var env_v}.\n    Variable env_k : Type -> Type.\n    Context {Mk : DMap cont env_k}.\n    \n    Section monadic. \n      Variable m : Type -> Type.\n      Context {Monad_m : Monad m}.\n      Context {Reader_var : MonadReader (env_v var) m}.\n      Context {Reader_cont : MonadReader (env_k cont) m}.\n      Context {Zero_m : MonadZero m}.\n\n      Import MonadNotation.\n      Local Open Scope monad_scope.\n      Local Open Scope list_scope. \n  \n      Definition alpha_op (o1 o2 : op) : m unit :=\n        match o1 , o2 with\n          | Var_o v1 , Var_o v2 =>\n            x <- ask ;;\n            match Maps.lookup v1 x with\n              | None => assert (eq_dec v1 v2)\n              | Some v1 => assert (eq_dec v1 v2)\n            end\n          | Con_o c1 , Con_o c2 =>\n            assert (eq_dec c1 c2)\n          | Int_o z1 , Int_o z2 =>\n            assert (eq_dec z1 z2)\n          | _ , _ => assert false\n        end.\n\n      Definition alpha_k (k1 k2 : cont) : m unit :=\n        k2' <- asks (Maps.lookup k1) ;;\n        match k2' with\n          | None => assert (eq_dec k1 k2)\n          | Some k2' => assert (eq_dec k2' k2)\n        end.\n\n      Fixpoint all2 {T} (p : T -> T -> m unit) (ls1 ls2 : list T) : m unit :=\n        match ls1 , ls2 with\n          | nil , nil => ret tt\n          | l1 :: ls1 , l2 :: ls2 =>\n            p l1 l2 ;;\n            all2 p ls1 ls2\n          | _ , _ => assert false\n        end.\n\n      Global Instance RelDec_eq_pattern : RelDec (@eq pattern) :=\n      { rel_dec := fun x y =>\n        match x , y with\n          | Int_p x , Int_p y => eq_dec x y\n          | Con_p x , Con_p y => eq_dec x y\n          | _ , _ => false\n        end }.\n\n      Fixpoint alpha_exp' (e1 e2 : exp) {struct e1} : m unit :=\n        match e1, e2 with\n          | App_e f1 ks1 args1 , App_e f2 ks2 args2 =>\n            alpha_op f1 f2 ;;\n            all2 alpha_k ks1 ks2 ;;\n            all2 alpha_op args1 args2\n          | Let_e d1 e1 , Let_e d2 e2 =>\n            alpha_dec d1 d2 (alpha_exp' e1 e2)\n\n          | Letrec_e ds1 e1 , Let_e ds2 e2 =>\n            assert false \n(*\n            alpha_dec ds1 ds2 (alpha_exp' e1 e2)\n*)\n\n          | Switch_e op1 br1 e1 , Switch_e op2 br2 e2 =>\n            alpha_op op1 op2 ;;\n            match e1 , e2 with\n              | None , None => assert true\n              | Some e1 , Some e2 =>\n                alpha_exp' e1 e2\n              | _ , _ => assert false\n            end ;;\n            (fix all2 ls1 ls2 : m unit :=\n              match ls1 , ls2 with\n                | nil , nil => assert true\n                | (p1,e1) :: ls1 , (p2,e2) :: ls2 =>\n                  assert (eq_dec p1 p2) ;;\n                  alpha_exp' e1 e2 ;;\n                  all2 ls1 ls2\n                | _ , _ => assert false\n              end) br1 br2             \n          | Halt_e o1 o1', Halt_e o2 o2'=>\n            alpha_op o1 o2 ;;\n            alpha_op o1' o2'\n          | AppK_e k1 o1 , AppK_e k2 o2 =>\n            alpha_k k1 k2 ;;\n            all2 alpha_op o1 o2 \n          | LetK_e k1 e1 , LetK_e k2 e2 =>\n            assert false (** TODO **)\n          | _ , _ => assert false\n        end\n      with alpha_dec (d1 d2 : decl) (k : m unit) {struct d1} : m unit :=\n        match d1 , d2 with\n          | Op_d v1 o1 , Op_d v2 o2 =>\n            alpha_op o1 o2 ;;\n            local (add v1 v2) k\n          | Prim_d v1 p1 args1 , Prim_d v2 p2 args2 =>\n            assert (eq_dec p1 p2) ;;\n            all2 alpha_op args1 args2 ;;\n            local (add v1 v2) k\n          | Bind_d v1 w1 p1 args1 , Bind_d v2 w2 p2 args2 =>\n            assert (eq_dec p1 p2) ;;\n            all2 alpha_op args1 args2 ;;\n            local (fun x => add v1 v2 (add w1 w2 x)) k\n          | Fn_d v1 k1 a1 e1 , Fn_d v2 k2 a2 e2 =>\n            (fix map_multi (x y : list var) (k : m unit) : m unit :=\n              match x , y with\n                | nil , nil => \n                  (fix map_multi (x y : list cont) (k : m unit) : m unit :=\n                    match x , y with\n                      | nil , nil => k\n                      | x :: xs , y :: ys =>\n                        local (add x y) (map_multi xs ys k)\n                      | _ , _ => assert false\n                    end\n                  ) k1 k2 k\n                | x :: xs , y :: ys => \n                  local (add x y) (map_multi xs ys k)\n                | _ , _ => assert false\n              end) a1 a2 (alpha_exp' e1 e2) ;;\n            local (add v1 v2) k \n          | _ , _ => assert false\n        end.\n    End monadic.\n  End maps.\n\n  Definition alpha_exp (e1 e2 : exp) : bool :=\n    let res := runReader (runReaderT (unOptionT (alpha_exp' (m := optionT (readerT (alist var var) (reader (alist cont cont)))) e1 e2)) empty) empty in\n    match res with\n      | None => false\n      | Some _ => true\n    end.\n\n  Definition alpha_lam (e1 e2 : exp) (v1 v2 : list var) (k1 k2 : list cont) : bool :=\n    (fix build acc l1 l2 {struct l1} : bool :=\n      match l1 , l2 with\n        | nil , nil => \n          let res := runReader (runReaderT (unOptionT (alpha_exp' (m := optionT (readerT (alist var var) (reader (alist cont cont)))) e1 e2)) acc) empty (** TODO **) in\n          match res with\n            | None => false\n            | Some _ => true\n          end\n        | l1 :: ls1 , l2 :: ls2 =>\n          build (add l1 l2 acc) ls1 ls2\n        | _ , _ => false\n      end) empty v1 v2.\n  \n  Module TEST.\n    Require Import String.\n\n    Require Import BinNums.\n    (** Test cases needed **)\n    Definition f (n : Z) (v : var) : exp := \n      Let_e (Prim_d v Proj_p (Int_o n :: nil))\n      (Halt_e (Var_o v) (Var_o (wrapVar \"world\"%string))).\n\n    Goal (alpha_exp (f 2 (wrapVar \"0\")) (f 1 (wrapVar \"2\")) = false)%string.\n    Proof. vm_compute; reflexivity. Abort.\n\n    Goal (alpha_exp (f 2 (wrapVar \"0\")) (f 2 (wrapVar \"0\")) = true)%string.\n    Proof. vm_compute; reflexivity. Abort.\n(*\n    Goal (alpha_lam (f (wrapVar \"0\")) (f (wrapVar \"1\")) (wrapVar \"0\" :: nil) (wrapVar \"1\" :: nil) = true)%string.\n    Proof. vm_compute; reflexivity. Abort.\n\n    Goal (alpha_lam (f (wrapVar \"0\")) (f (wrapVar \"1\")) (wrapVar \"0\" :: nil) (wrapVar \"2\" :: nil) = false)%string.\n    Proof. vm_compute; reflexivity. Abort.\n*)\n  End TEST.\n\nEnd Alpha.", "meta": {"author": "coq-ext-lib", "repo": "coq-compile", "sha": "8edfe71f4f91d5abf479bee50a3f1529b99acd4f", "save_path": "github-repos/coq/coq-ext-lib-coq-compile", "path": "github-repos/coq/coq-ext-lib-coq-compile/coq-compile-8edfe71f4f91d5abf479bee50a3f1529b99acd4f/src/coq/AlphaEquivCpsK.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23538156343327815}}
{"text": "(** printing |-#    %\\vdash_{\\#}%    #&vdash;<sub>&#35;</sub>#     *)\n(** printing |-##   %\\vdash_{\\#\\#}%  #&vdash;<sub>&#35&#35</sub>#  *)\n(** printing |-##v  %\\vdash_{\\#\\#v}% #&vdash;<sub>&#35&#35v</sub># *)\n(** printing |-!    %\\vdash_!%       #&vdash;<sub>!</sub>#         *)\n(** remove printing ~ *)\n\nSet Implicit Arguments.\n\nRequire Import ConstrLangAlt Definitions Subenvironments RecordAndInertTypes ConstrTyping.\nRequire Import TightConstrEntailment.\n\nRequire Import Coq.Program.Equality.\n\n(** * Constraint Satisfactory based on Tight Subtyping *)\n\n(** * Tight Typing Rules with Constraints *)\n\nReserved Notation \"e '⊢c#' t ':' T\" (at level 39, t at level 59).\nReserved Notation \"e '⊢c#' T '<:' U\" (at level 39, T at level 59).\n\n(** ** Term typing [G ⊢c# t: T] *)\nInductive cty_trm_t : (constr * ctx) -> trm -> typ -> Prop :=\n\n(** [G(x) = T]  #<br>#\n    [――――――――]  #<br>#\n    [C, G ⊢c x: T]  *)\n| cty_var_t : forall C G x T,\n    binds x T G ->\n    (C, G) ⊢c# trm_var (avar_f x) : T\n\n(** [C, (G, x: T) ⊢c t^x: U^x]     #<br>#\n    [x fresh]                #<br>#\n    [――――――――――――――――――――――] #<br>#\n    [C, G ⊢c lambda(T)t: forall(T)U]      *)\n| cty_all_intro_t : forall L C G T t U,\n    (forall x, x \\notin L ->\n      (C, G & x ~ T) ⊢c open_trm x t : open_typ x U) ->\n    (C, G) ⊢c# trm_val (val_lambda T t) : typ_all T U\n\n(** [C, G ⊢c x: forall(S)T] #<br>#\n    [C, G ⊢c z: S]     #<br>#\n    [――――――――――――] #<br>#\n    [C, G ⊢c x z: T^z]     *)\n| cty_all_elim_t : forall C G x z S T,\n    (C, G) ⊢c# trm_var (avar_f x) : typ_all S T ->\n    (C, G) ⊢c# trm_var (avar_f z) : S ->\n    (C, G) ⊢c# trm_app (avar_f x) (avar_f z) : open_typ z T\n\n(** [C, (G, x: T^x) ⊢ ds^x :: T^x]  #<br>#\n    [x fresh]                  #<br>#\n    [―――――――――――――――――――――――]  #<br>#\n    [C, G ⊢ nu(T)ds :: mu(T)]          *)\n| cty_new_intro_t : forall L C G T ds,\n    (forall x, x \\notin L ->\n      (C, G & (x ~ open_typ x T)) /-c open_defs x ds :: open_typ x T) ->\n    (C, G) ⊢c# trm_val (val_new T ds) : typ_bnd T\n\n(** [C, G ⊢c x: {a: T}] #<br>#\n    [―――――――――――――] #<br>#\n    [C, G ⊢c x.a: T]        *)\n| cty_new_elim_t : forall C G x a T,\n    (C, G) ⊢c# trm_var (avar_f x) : typ_rcd (dec_trm a T) ->\n    (C, G) ⊢c# trm_sel (avar_f x) a : T\n\n(** [C, G ⊢c t: T]          #<br>#\n    [C, G, x: T ⊢c u^x: U]  #<br>#\n    [x fresh]           #<br>#\n    [―――――――――――――――――] #<br>#\n    [C, G ⊢c let t in u: U]     *)\n| cty_let_t : forall L C G t u T U,\n    (C, G) ⊢c# t : T ->\n    (forall x, x \\notin L ->\n      (C, G & x ~ T) ⊢c open_trm x u : U) ->\n    (C, G) ⊢c# trm_let t u : U\n\n(** [C, G ⊢c x: T^x]   #<br>#\n    [――――――――――――] #<br>#\n    [C, G ⊢c x: mu(T)]     *)\n| cty_rec_intro_t : forall C G x T,\n    (C, G) ⊢c# trm_var (avar_f x) : open_typ x T ->\n    (C, G) ⊢c# trm_var (avar_f x) : typ_bnd T\n\n(** [C, G ⊢c x: mu(T)] #<br>#\n    [――――――――――――] #<br>#\n    [C, G ⊢c x: T^x]   *)\n| cty_rec_elim_t : forall C G x T,\n    (C, G) ⊢c# trm_var (avar_f x) : typ_bnd T ->\n    (C, G) ⊢c# trm_var (avar_f x) : open_typ x T\n\n(** [C, G ⊢c x: T]     #<br>#\n    [C, G ⊢c x: U]     #<br>#\n    [――――――――――――] #<br>#\n    [C, G ⊢c x: T /\\ U]     *)\n| cty_and_intro_t : forall C G x T U,\n    (C, G) ⊢c# trm_var (avar_f x) : T ->\n    (C, G) ⊢c# trm_var (avar_f x) : U ->\n    (C, G) ⊢c# trm_var (avar_f x) : typ_and T U\n\n(** [C, G ⊢c t: T]   #<br>#\n    [C ⊩ S <: T] #<br>#\n    [――――――――――] #<br>#\n    [C, G ⊢c t: U]   *)\n| cty_sub_t : forall C G t T U,\n    (C, G) ⊢c# t : T ->\n    (C, G) ⊢c# T <: U ->\n    (C, G) ⊢c# t : U\nwhere \"e '⊢c#' t ':' T\" := (cty_trm_t e t T)\nwith csubtyp_t : (constr * ctx) -> typ -> typ -> Prop :=\n(** [C, G ⊢c x: S]   #<br>#\n    [C ⋏ x: S, G ⊢c T <: U] #<br>#\n    [――――――――――] #<br>#\n    [C, G ⊢c T <: U]   *)\n| csubtyp_intro_t : forall C G x S S' T U,\n    S ⩭ S' ->\n    binds x S' G ->\n    (C ⋏ ctrm_cvar (cvar_x (avar_f x)) ⦂ S, G) ⊢c# T <: U ->\n    (C, G) ⊢c# T <: U\n(** [C ⊩ T <: U]   #<br>#\n    [――――――――――] #<br>#\n    [C, G ⊢c T <: U]   *)\n| csubtyp_inst_t : forall C G S S' T T',\n    S ⩭ S' ->\n    T ⩭ T' ->\n    C ⊩# S <⦂ T ->\n    (C, G) ⊢c# S' <: T'\nwhere \"e '⊢c#' T '<:' U\" := (csubtyp_t e T U).\n\nHint Constructors cty_trm_t csubtyp_t.\n\nScheme cts_ty_trm_t_mut := Induction for cty_trm_t Sort Prop\nwith   cts_subtyp_t     := Induction for csubtyp_t Sort Prop.\nCombined Scheme cts_t_mutind from cts_ty_trm_t_mut, cts_subtyp_t.\n\n(** * Equivalence Theorems *)\n\n(** Tight typing implies general typing. *)\nLemma tight_to_general_constr_typing:\n  (forall e t T,\n     e ⊢c# t : T ->\n     e ⊢c t : T) /\\\n  (forall e S U,\n     e ⊢c# S <: U ->\n     e ⊢c S <: U).\nProof.\n  apply cts_t_mutind; intros; subst; eauto using tight_to_general_entailment.\nQed.\n\nTheorem general_to_tight_constr_typing :\n  (forall e t T,\n     e ⊢c t : T ->\n     e ⊢c# t : T) /\\\n  (forall e S U,\n     e ⊢c S <: U ->\n     e ⊢c# S <: U).\nProof.\n  apply cts_mutind; intros; subst; eauto using general_to_tight_entailment.\nQed.\n", "meta": {"author": "Linyxus", "repo": "constr-dot-calculus", "sha": "111c47bdc58350b8dd0b65ecbeeec783a8df2bc2", "save_path": "github-repos/coq/Linyxus-constr-dot-calculus", "path": "github-repos/coq/Linyxus-constr-dot-calculus/constr-dot-calculus-111c47bdc58350b8dd0b65ecbeeec783a8df2bc2/src/constr-dot/TightConstrTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.23534568896540328}}
{"text": "Require Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Locations.\nRequire Import Stacklayout.\nRequire Import Conventions.\nRequire Import Memory.\nRequire Import Asm.\n\nRequire Import PeekLib.\nRequire Import PeekTactics.\nRequire Import FindInstrLib.\nRequire Import PregTactics.\n\nRequire Import AsmBits.\nRequire Import MemoryAxioms.\nRequire Import PtrEquiv.\nRequire Import MemBits.\nRequire Import Zlen.\nRequire Import GlobalPerms.\nRequire Import SameSizeChunk.\n\nDefinition mem_nextblock_same (m m' : mem) : Prop :=\n  Mem.nextblock m = Mem.nextblock m'.\n\nDefinition mem_perm_same (m m' : mem) :=\n  forall b x p,\n    (Mem.mem_access m) !! b x Cur = Some p ->\n    (Mem.mem_access m') !! b x Cur = Some p.\n\nLemma perm_same_imp :\n  forall m m',\n    mem_perm_same m m' ->\n    forall b x p,\n      Mem.perm m b x Cur p ->\n      Mem.perm m' b x Cur p.\nProof.\n  intros. unfold mem_perm_same in *.\n  unfold Mem.perm in *.\n  unfold Mem.perm_order' in *.\n  break_match_hyp; try inv_false.\n  app H Heqo. collapse_match.\n  assumption.\nQed.\n\nLemma mem_alloc_nextblock :\n  forall m m',\n    mem_nextblock_same m m' ->\n    forall m0 b lo hi,\n      Mem.alloc m lo hi = (m0,b) ->\n      exists m'0,\n        Mem.alloc m' lo hi = (m'0,b) /\\ mem_nextblock_same m0 m'0.\nProof.\n  intros.\n  app Mem.nextblock_alloc H0.\n  destruct (Mem.alloc m' lo hi) eqn:?.\n  app Mem.nextblock_alloc Heqp.\n  app Mem.alloc_result H1.\n  app Mem.alloc_result H2.\n  assert (b = b0).\n  unfold mem_nextblock_same in H.\n  congruence. subst.\n  eexists; split. f_equal. congruence.\n  unfold mem_nextblock_same.\n  congruence.\nQed.\n\nLemma mem_alloc_perm :\n  forall m m',\n    mem_perm_same m m' ->\n    mem_nextblock_same m m' ->\n    forall m0 b lo hi,\n      Mem.alloc m lo hi = (m0,b) ->\n      exists m'0,\n        Mem.alloc m' lo hi = (m'0,b) /\\ mem_perm_same m0 m'0.  \nProof.\n  intros.\n  intros.\n  app mem_alloc_nextblock H0.\n  break_and. exists x. rewrite H0. split. reflexivity.\n  unfold mem_perm_same in H.\n  unfold mem_perm_same.\n  intros.\n  erewrite Mem.alloc_access_result in H4 by eauto.\n  erewrite Mem.alloc_access_result by eauto.\n  destruct (peq b0 (Mem.nextblock m)). subst.\n  unfold mem_nextblock_same in H2. rewrite <- H2.  \n  rewrite PMap.gss in *. \n  assumption.\n  unfold mem_nextblock_same in H2. rewrite <- H2.  \n  rewrite PMap.gso in * by congruence.\n  eapply H; eauto.\nQed.\n  \n\nLemma mem_free_perm :\n  forall m m',\n    mem_perm_same m m' ->\n    forall b lo hi m0,\n      Mem.free m b lo hi = Some m0 ->\n      exists m'0,\n        Mem.free m' b lo hi = Some m'0 /\\ mem_perm_same m0 m'0.\nProof.\n  intros.\n  unfold mem_perm_same in H.\n  assert (Mem.range_perm m' b lo hi Cur Freeable).\n  app Mem.free_range_perm H0.\n  unfold Mem.range_perm. intros.\n  unfold Mem.range_perm in H0.\n  specialize (H0 ofs H2).\n  unfold Mem.perm in *.\n  unfold Mem.perm_order' in *.\n  break_match_hyp; try congruence.\n  app H Heqo.\n  collapse_match. eauto.\n  inv_false.\n\n  app Mem.range_perm_free H1.\n  destruct H1. rewrite e.\n  exists x. split. reflexivity.\n  unfold mem_perm_same. intros.\n  app Mem.free_result H0.\n  app Mem.free_result e. subst.\n  unfold Mem.unchecked_free in *.\n  simpl in *.\n  clear H4. clear H3.\n  destruct (peq b b0); subst;\n  repeat rewrite PMap.gss in *; repeat rewrite PMap.gso in * by congruence;\n  try break_match;\n  try apply H;\n  try congruence.\nQed.\n\nLemma mem_free_nextblock :\n  forall m m',\n    mem_perm_same m m' ->\n    mem_nextblock_same m m' ->\n    forall b lo hi m0,\n      Mem.free m b lo hi = Some m0 ->\n      exists m'0,\n        Mem.free m' b lo hi = Some m'0 /\\ mem_nextblock_same m0 m'0.\nProof.\n  intros.\n  app mem_free_perm H. break_and.\n  exists x. split; auto.\n  app Mem.nextblock_free H1.\n  app Mem.nextblock_free H.\n  unfold mem_nextblock_same in *.\n  congruence.\nQed.\n\nLemma perm_same_valid_access :\n  forall m m',\n    mem_perm_same m m' ->\n    forall c b ofs p,\n      Mem.valid_access m c b ofs p ->\n      Mem.valid_access m' c b ofs p.\nProof.\n  intros.\n  unfold Mem.valid_access in *.\n  break_and. split; auto.\n  unfold Mem.range_perm in *.\n  intros. specialize (H0 _ H2).\n  eapply perm_same_imp; eauto.\nQed.\n\nLemma mem_store_perm_same :\n  forall m m',\n    mem_perm_same m m' ->\n    forall c b ofs v v' m0,\n      Mem.store c m b ofs v = Some m0 ->\n      exists m'0,\n        store_bits c m' b ofs v' = Some m'0 /\\ mem_perm_same m0 m'0.\nProof.\n  intros.\n  unfold mem_perm_same in H.\n  app Mem.store_valid_access_3 H0.\n  app perm_same_valid_access H0.\n  unfold store_bits.\n  break_match.\n  eexists. split.\n  reflexivity.\n  unfold mem_perm_same.\n  simpl.\n  intros. \n  app Mem.store_access H1.\n  eapply H; try congruence.\n  congruence.\nQed.\n\nLemma nextblock_store_bits :\n  forall c m b ofs v m',\n    store_bits c m b ofs v = Some m' ->\n    Mem.nextblock m = Mem.nextblock m'.\nProof.\n  intros. unfold store_bits in H.\n  break_match_hyp; try congruence.\n  inv H. simpl. reflexivity.\nQed.\n\nLemma mem_store_nextblock :\n  forall m m',\n    mem_perm_same m m' ->\n    mem_nextblock_same m m' ->\n    forall c b ofs v v' m0,\n      Mem.store c m b ofs v = Some m0 ->\n      exists m'0,\n        store_bits c m' b ofs v' = Some m'0 /\\ mem_nextblock_same m0 m'0.\nProof.\n  intros.\n  app mem_store_perm_same H.\n  break_and.\n  exists x. split. eassumption.\n\n  app Mem.nextblock_store H1.\n  app nextblock_store_bits H.\n  unfold mem_nextblock_same in *.\n  congruence.\nQed.\n\nLemma mem_load_exists :\n  forall m m',\n    mem_perm_same m m' ->\n    forall c b z v,\n      Mem.load c m b z = Some v ->\n      exists v',\n        Mem.load c m' b z = Some v'.\nProof.\n  intros.\n  app Mem.load_valid_access H0.\n  app perm_same_valid_access H0.\n  app Mem.valid_access_load H0.\nQed.\n\n\nDefinition wf_frag_bits (m : memory_chunk) (v : val) ( l : list memval) :=\n  l = encode_val_bits m v.\n\n  Ltac dl m n H0 :=\n    destruct m; simpl in H0; try congruence;\n    match goal with\n      | [ H : context[Val.eq ?X ?Y] |- _ ] => destruct (Val.eq X Y)\n    end;\n    simpl in H0;\n    try congruence;\n    match goal with\n      | [ H : context[quantity_eq ?X ?Y] |- _ ] => destruct (quantity_eq X Y)\n    end;\n    simpl in H0;\n    try congruence;\n    repeat (destruct n; simpl in H0; try congruence);\n    subst.\n\n\nLemma check_value_length :\n  forall l q v,\n    check_value (size_quantity_nat q) v q l = true ->\n    length l = size_quantity_nat q.\nProof.\n  intros;\n  do 8 (try destruct l); destruct q;\n  simpl in *; try congruence;\n  dl m n H; dl m0 n H; dl m1 n H;\n  dl m2 n H; dl m3 n H; dl m4 n H;\n  dl m5 n H; dl m6 n H.\n  destruct l. reflexivity. congruence.\nQed.\n\nLemma check_value_wf_64 :\n  forall v l,\n    check_value (size_quantity_nat Q64) v Q64 l = true ->\n    wf_frag Many64 v l.\nProof.\n  intros.\n  app check_value_length H.\n  simpl in H.\n  do 9 (try destruct l);\n    simpl in H;\n    try omega.\n\n\n  dl m n H0.\n  dl m0 n H0.\n  dl m1 n H0.\n  dl m2 n H0.\n  dl m3 n H0.\n  dl m4 n H0.\n  dl m5 n H0.\n  dl m6 n H0.\n  unfold wf_frag.\n  unfold encode_val.\n  split. Focus 2. eexists. eexists.\n  f_equal. unfold size_quantity_nat. instantiate (2 := Q64). simpl. reflexivity.\n  break_match; unfold inj_value; simpl; reflexivity.\nQed.\n\nLemma check_value_wf_32 :\n  forall chunk v l b o i s,\n    (chunk = Mint32 /\\ (v = Vptr b o)) \\/\n    (chunk = Many32 /\\ (v = Vptr b o \\/ v = Vint i \\/ v = Vsingle s)) ->\n    check_value (size_quantity_nat Q32) v Q32 l = true ->\n    wf_frag chunk v l.\nProof.\n  intros.\n  app check_value_length H0.\n  simpl in H.\n  do 5 (try destruct l);\n    simpl in H0;\n    try omega.\n\n  dl m n H1.\n  dl m0 n H1.\n  dl m1 n H1.\n  dl m2 n H1.\n  unfold wf_frag.\n  repeat break_or; split. break_and.\n  unfold encode_val.\n  subst.\n  reflexivity. \n  exists Q32. eexists. reflexivity.\n  \n  unfold encode_val.\n  break_and. subst.\n  repeat break_or; subst; reflexivity.\n  exists Q32. eexists. reflexivity.\nQed.\n\nLemma malformed_load_undef :\n  forall m v l q n,\n    ~ wf_frag m v (Fragment v q n :: l) ->\n    (decode_val m (Fragment v q n :: l) = Vundef \\/\n     (wf_frag Many32 v (Fragment v q n :: l) /\\ exists i, v = Vint i)).\nProof.\n  intros.\n  destruct m; simpl; auto;\n  unfold decode_val;\n  break_match;\n  simpl in Heqo; try congruence;\n  unfold proj_value;\n  break_match; unfold Val.load_result;\n  simpl; try solve [left; reflexivity];\n  try break_match; try solve [left; reflexivity];\n  try solve [\n        app (check_value_wf_32 Mint32) Heqb; congruence\n      ];\n  try solve [\n        app (check_value_wf_32 Many32) Heqb; congruence\n      ];\n  try solve [\n        app check_value_wf_64 Heqb; congruence\n      ].\n  Grab Existential Variables.\n  exact Float32.zero. \n  exact Int.zero.\n  exact Int.zero.\n  exact Int.zero.\n  exact xH.\n  exact Float32.zero.\n  exact Int.zero.\n  exact xH.\n  exact Float32.zero.\n  exact Int.zero.\n  exact xH.\n  exact Float32.zero.\n  exact Int.zero.\nQed.\n\nDefinition frag_equiv (t : allocator_metadata) (b b' : ZMap.t memval) (z : Z) : Prop :=\n  match ZMap.get z b with\n    | Fragment (Vptr blk ofs) Q32 3 =>\n      forall m,\n        (m = Mint32 \\/ m = Many32) ->\n        wf_frag m (Vptr blk ofs) (Mem.getN 4 z b) ->\n        exists v',\n          wf_frag_bits m v' (Mem.getN 4 z b') /\\\n          ptr_equiv_val t (Vptr blk ofs) v'\n    | Fragment (Vint i) Q32 3 =>\n      forall m,\n        (m = Mint32 \\/ m = Many32) ->\n        wf_frag m (Vint i) (Mem.getN 4 z b) ->\n        exists v',\n          wf_frag_bits m v' (Mem.getN 4 z b') /\\\n          ptr_equiv_val t (Vint i) v'\n    | Fragment Vundef q n => True\n    | Fragment v q n =>\n      (n = size_quantity_nat q - 1)%nat ->\n      forall m,\n        wf_frag m v (Mem.getN (size_quantity_nat q) z b) ->\n        exists v',\n          wf_frag_bits m v' (Mem.getN (size_quantity_nat q) z b') /\\\n          ptr_equiv_val t v v'\n    | Byte bits => ZMap.get z b' = Byte bits\n    | Undef => True\n  end.\n\nDefinition no_pointer (b : ZMap.t memval) (z : Z) :=\n  match ZMap.get z b with\n    | Fragment v _ _ => forall b o, v <> Vptr b o\n    | _ => True\n  end.\n\nDefinition contents_equiv (t : allocator_metadata) (c c' : PMap.t (ZMap.t memval)) :=\n  forall b ofs,\n    frag_equiv t (c !! b) (c' !! b) ofs /\\ no_pointer (c' !! b) ofs.\n\nLemma encode_val_bits_length :\n  forall chunk v,\n    length (encode_val_bits chunk v) = size_chunk_nat chunk.\nProof.\n  intros.\n  destruct chunk; unfold encode_val_bits; unfold size_chunk_nat;\n  destruct v; simpl; unfold Pos.to_nat; simpl;\n  reflexivity.\nQed.\n\nLemma inj_bytes_byte :\n  forall y x,\n    x <> nil ->\n    y = inj_bytes x ->\n    exists bits l,\n      y = Byte bits :: l.\nProof.\n  intros.\n  rewrite H0.\n  destruct x; try congruence.\n  unfold inj_bytes.\n  simpl. eexists; eauto.\nQed.\n\nLemma encode_int_not_nil :\n  forall n x,\n    (n > 0)%nat ->\n    encode_int n x <> nil.\nProof.\n  intros. destruct n; try omega.\n  unfold encode_int.\n  simpl. unfold rev_if_be.\n  break_match; try congruence.\n  simpl.\n  match goal with\n    | [ |- ?X ++ _ <> nil ] => destruct X\n  end; simpl; congruence.\nQed.\n\nLemma wf_frag_inv :\n  forall m v m' v',\n    wf_frag m v (encode_val m' v') ->\n    (m = m' \\/ (m = Many32 /\\ m' = Mint32) \\/ (m = Mint32 /\\ m' = Many32)) /\\ v = v'.\nProof.\n  intros. unfold wf_frag in H.\n  break_and. repeat break_exists.\n  unfold encode_val in H0.\n  do 2 break_match_hyp;\n    subst;\n    simpl in H0; try congruence;\n    unfold inj_value in *; simpl in H0;\n    inv H0;\n  try solve [\n  unfold encode_val in H; break_match;\n    unfold inj_value in H;\n    simpl in H; try congruence;\n    eauto];\n  unfold encode_val in H; break_match;\n  unfold inj_value in H;\n    simpl in H; try congruence;\n    eauto;\n    try app inj_bytes_byte H;\n    try congruence;\n    apply encode_int_not_nil;\n    omega.\nQed.\n\nLemma wf_frag_length_size :\n  forall m v l,\n    wf_frag m v l ->\n    size_chunk_nat m = length l.\nProof.\n  unfold wf_frag; intros.\n  break_and. subst. repeat break_exists.\n  unfold encode_val in H.\n  repeat break_match; simpl; try inv H;\n  simpl; reflexivity.\nQed.\n\nLemma of_nat_length :\n  forall chunk,\n    Z.of_nat (size_chunk_nat chunk) = size_chunk chunk.\nProof.\n  destruct chunk; simpl; omega.\nQed.\n\nLemma getN_setN_same :\n  forall vl p c n,\n    n = length vl ->\n    Mem.getN n p (Mem.setN vl p c) = vl.\nProof.\n  intros. subst n.\n  apply Mem.getN_setN_same.\nQed.\n\n\nLemma Zplus_comm :\n  forall (x y : Z),\n    x + y = y + x.\nProof.\n  intros. omega.\nQed.\n\n\nLemma wf_frag_only_lengths :\n  forall m v l,\n    wf_frag m v l ->\n    length l = 4%nat \\/ length l = 8%nat.\nProof.\n  intros.\n  app wf_frag_length_size H.\n  rewrite <- H.\n  destruct m; simpl; eauto;\n  unfold wf_frag in H0;\n  break_and; unfold encode_val in *;\n  break_match_hyp;\n  repeat break_exists;\n  subst l; simpl in *;\n  try congruence;\n  unfold inj_bytes in *; unfold encode_int in *;\n  unfold rev_if_be in *; break_match_hyp; simpl in *; try congruence.\nQed.\n\nLemma setN_get_nth :\n  forall l (ofs z : Z) c r,\n    ofs <= z < ofs + Z.of_nat (length l) ->\n    (ZMap.get z (Mem.setN l ofs c) = r <->\n    nth (Z.to_nat (z - ofs)) l Undef = r).\nProof.\n  induction l; intros. simpl in H. omega.\n  simpl in H. rewrite Zpos_P_of_succ_nat in H.\n  assert (z = ofs \\/ z > ofs) by omega.\n  destruct H0.\n  subst z.\n  unfold Mem.setN. fold Mem.setN.\n  rewrite Mem.setN_outside by omega.\n  rewrite ZMap.gss. simpl. rewrite Z.sub_diag. simpl.\n  reflexivity.\n\n  unfold Mem.setN. fold Mem.setN.\n  rewrite IHl by omega.\n  assert (0 < z - ofs) by omega.\n  rewrite Z2Nat.inj_lt in H1 by omega.\n  simpl in H1.\n  simpl. break_match. omega.\n  assert (Z.to_nat (z - (ofs + 1)) = n).\n\n  assert (z - ofs = Z.succ (z - (ofs + 1))) by omega.\n  rewrite H2 in Heqn.\n  rewrite Z2Nat.inj_succ in Heqn. inv Heqn.\n  reflexivity. omega.\n  \n  rewrite H2. reflexivity.\nQed.\n\n\nLemma getN_get :\n  forall chunk ofs c h l,\n    Mem.getN (size_chunk_nat chunk) ofs c = h :: l ->\n    ZMap.get ofs c = h.\nProof.\n  intros; destruct chunk; simpl in H; inv H; reflexivity.\nQed.\n\nLemma nth_succ_encode_head_frag_false :\n  forall n v v' m q,\n    nth (Datatypes.S n) (encode_val m v) Undef = Fragment v' q (size_quantity_nat q - 1) ->\n    False.\nProof.\n  intros. destruct m; destruct v; simpl in H; try break_match_hyp; try congruence;\n          unfold inj_bytes in H; unfold encode_int in H; simpl in H;\n          unfold rev_if_be in *; try break_match_hyp; simpl in H; try break_match_hyp; try congruence;\n          do 8 (try break_match_hyp; try congruence);\n          destruct q; simpl in H; inv H.\nQed.\n\nLemma get_last_part_malformed :\n  forall n chunk m v z v0 ofs c,\n    ofs < z < ofs + size_chunk chunk ->\n    ~wf_frag m v (Mem.getN n z (Mem.setN (encode_val chunk v0) ofs c)).\nProof.\n  intros. intro.\n  app wf_frag_only_lengths H0.\n  break_or.\n  * assert (n = 4%nat).\n      rewrite <- H2.\n      rewrite Mem.getN_length. reflexivity.\n    subst n.\n    unfold wf_frag in H1.\n    break_and. repeat break_exists.\n    simpl in H1. inv H1.\n    rewrite setN_get_nth in H4. Focus 2. rewrite encode_val_length.\n    rewrite of_nat_length. omega.\n    assert (0 < z - ofs) by omega.\n    app Z2Nat.inj_lt H1; try omega. simpl in H1.\n    destruct (Z.to_nat (z - ofs)); try omega.\n    app nth_succ_encode_head_frag_false H4.\n  * assert (n = 8%nat).\n      rewrite <- H2.\n      rewrite Mem.getN_length. reflexivity.\n    subst n.\n    unfold wf_frag in H1.\n    break_and. repeat break_exists.\n    simpl in H1. inv H1.\n    rewrite setN_get_nth in H4. Focus 2. rewrite encode_val_length.\n    rewrite of_nat_length. omega.\n    assert (0 < z - ofs) by omega.\n    app Z2Nat.inj_lt H1; try omega. simpl in H1.\n    destruct (Z.to_nat (z - ofs)); try omega.\n    app nth_succ_encode_head_frag_false H4.\nQed.\n\n\nLemma nth_zero_encode_non_head_frag_false :\n  forall v v' m q k,\n    (k < size_quantity_nat q - 1)%nat ->\n    nth O (encode_val m v) Undef = Fragment v' q k ->\n    False.\nProof.\n  intros.\n  destruct m; destruct v; simpl in H0; try break_match_hyp; try congruence;\n  unfold inj_bytes in H0; unfold encode_int in H0; simpl in H0;\n  unfold rev_if_be in *; try break_match_hyp; simpl in H0; try break_match_hyp; try congruence;\n  do 8 (try break_match_hyp; try congruence);\n  destruct q; simpl in H0; inv H0;\n  simpl in *; try omega.\nQed.\n\nLemma encode_head_non_head_frag_false :\n  forall v v' m q k l,\n    (k < size_quantity_nat q - 1)%nat ->\n    encode_val m v = Fragment v' q k :: l ->\n    False.\nProof.\n  intros.\n  eapply nth_zero_encode_non_head_frag_false. apply H.\n  instantiate (3 := m). instantiate (1 := v'). instantiate (1 := v).\n  rewrite H0. simpl. reflexivity.\nQed.\n\nLemma Pos_to_nat_gtz :\n  forall x,\n    (Pos.to_nat x > 0)%nat.\nProof.\n  intros.\n  destruct (Pos2Nat.is_succ x).\n  omega.\nQed.\n\n\nLemma getN_firstn :\n  forall n z l c,\n    (length l > n)%nat ->\n    Mem.getN n z (Mem.setN l z c) = firstn n l.\nProof.\n  induction n; intros.\n  * simpl. reflexivity.\n  * simpl.\n    destruct l; simpl in H; try omega.\n    simpl. rewrite IHn by omega.\n    rewrite Mem.setN_outside by omega.\n    rewrite ZMap.gss. reflexivity.\nQed.\n\nLemma getN_setN_tail :\n  forall n z ofs,\n    z < ofs < z + Z.of_nat n ->\n    forall h l c,\n    exists l' l'',\n      Mem.getN n z (Mem.setN (h :: l) ofs c) = l' ++ h :: l'' /\\ length l' = Z.to_nat (ofs - z).\nProof.\n  induction n; intros.\n  simpl in H. omega.\n  simpl. rewrite Mem.setN_outside by omega.\n  assert (z + 1 = ofs \\/ z + 1 < ofs) by omega. \n  destruct H0. subst ofs.\n  rewrite ZMap.gso by (rewrite Zplus_comm; apply z_neq; omega).\n  destruct n. simpl in H. omega.\n  simpl.\n  rewrite Mem.setN_outside by omega.\n  rewrite ZMap.gss. exists (ZMap.get z c :: nil).\n  exists (Mem.getN n (z + 1 + 1)\n                   (Mem.setN l (z + 1 + 1) (ZMap.set (z + 1) h c))).\n  split; try reflexivity.\n  replace (z + 1 - z) with 1 by omega.\n  simpl. reflexivity.\n  assert (z+1 < ofs < z+1 + (Z.of_nat n)). split; try omega.\n  simpl in H.\n  rewrite Zpos_P_of_succ_nat in H. omega.\n  edestruct (IHn (z + 1) ofs H1 h l c). destruct H2.\n  break_and.  simpl in H2. rewrite H2.\n  rewrite ZMap.gso. exists (ZMap.get z c :: x). exists x0.\n  split. simpl. reflexivity. simpl. rewrite H3.\n  rewrite <- Z2Nat.inj_succ by omega. f_equal. omega.\n  destruct (Z.eq_dec z ofs); auto. omega.\nQed.\n\nLemma encode_val_not_nil :\n  forall m v,\n    encode_val m v <> nil.\nProof.\n  destruct m; destruct v; simpl; try congruence;\n  unfold encode_int; unfold inj_value; simpl;\n  unfold rev_if_be; try break_match; simpl;\n  try congruence.\nQed.\n\nLemma get_before_beginning_malformed :\n  forall n chunk m v z v0 ofs c,\n    z < ofs < z + Z.of_nat n ->\n    ~wf_frag m v (Mem.getN n z (Mem.setN (encode_val chunk v0) ofs c)).\nProof.\n  intros. intro.\n  app wf_frag_only_lengths H0.\n  break_or.\n  * assert (n = 4%nat).\n      rewrite <- H2.\n      rewrite Mem.getN_length. reflexivity.\n    subst n.\n    app wf_frag_length_size H1.\n    rewrite H2 in H1.\n    destruct (encode_val chunk v0) eqn:?. app encode_val_not_nil Heql.\n    app getN_setN_tail H. break_and.\n    rewrite H in H0. \n    assert (0 < ofs - z < 4). simpl in H3. omega.\n    unfold wf_frag in H0. repeat break_and. repeat break_exists.\n    app Z2Nat.inj_lt H5; try omega.\n    app Z2Nat.inj_lt H6; try omega.\n    simpl in H5. simpl in H6. unfold Pos.to_nat in H6. simpl in H6.\n    do 4 (try destruct x; simpl in H4; try omega);\n      rewrite <- H4 in *; simpl in H8;\n      inv H8; destruct m; destruct v; simpl in H0; inv H0;\n      match goal with\n        | [ H : encode_val _ _ = _ :: _ |- _ ] => app encode_head_non_head_frag_false H\n      end;\n      simpl; omega.\n\n  * assert (n = 8%nat).\n      rewrite <- H2.\n      rewrite Mem.getN_length. reflexivity.\n    subst n.\n    app wf_frag_length_size H1.\n    rewrite H2 in H1.\n    destruct (encode_val chunk v0) eqn:?. app encode_val_not_nil Heql.\n    app getN_setN_tail H. break_and.\n    rewrite H in H0. \n    assert (0 < ofs - z < 8). simpl in H3. omega.\n    unfold wf_frag in H0. repeat break_and. repeat break_exists.\n    app Z2Nat.inj_lt H5; try omega.\n    app Z2Nat.inj_lt H6; try omega.\n    simpl in H5. simpl in H6. unfold Pos.to_nat in H6. simpl in H6.\n    do 8 (try destruct x; simpl in H4; try omega);\n      rewrite <- H4 in *; simpl in H8;\n      inv H8; destruct m; destruct v; simpl in H0; inv H0;\n      match goal with\n        | [ H : encode_val _ _ = _ :: _ |- _ ] => app encode_head_non_head_frag_false H\n      end;\n      simpl; omega.\n\nQed.\n\nLemma wf_frag_getN_aligned :\n  forall m v n z chunk v0 ofs c,\n    wf_frag m v (Mem.getN n z (Mem.setN (encode_val chunk v0) ofs c)) ->\n    z = ofs \\/ z + Z.of_nat n <= ofs \\/ z >= ofs + size_chunk chunk.\nProof.\n  intros.\n  assert (Hrange : ((z = ofs \\/ z + Z.of_nat n <= ofs \\/ z >= ofs + size_chunk chunk) \\/\n           (ofs < z < ofs + size_chunk chunk) \\/\n           (ofs < z + Z.of_nat n /\\ z < ofs))) by omega.\n  destruct Hrange. auto.\n  exfalso.\n\n  (* Now we just need contradiction *)\n  destruct H0.\n  * (* z gets something starting from middle of encode *)\n    eapply get_last_part_malformed; eauto. \n\n    \n  * (* z gets something ending with start of encode *)\n    eapply get_before_beginning_malformed; eauto. omega.\nQed.\n\n\n\nLemma nth_inj_bytes :\n  forall l n,\n  exists r,\n    nth n (inj_bytes l) Undef = r /\\\n    (r = Undef \\/ (exists bits, r = Byte bits)).\nProof.\n  induction l; intros.\n  simpl. break_match; exists Undef; split; eauto.\n  simpl. break_match.\n  exists (Byte a). split; eauto.\n  destruct (IHl n0).\n  exists x. eauto.\nQed.\n\nLemma ptr_equiv_encode_undef :\n  forall t v v',\n    ptr_equiv_val t v v' ->\n    forall z ofs chunk,\n      ofs <= z < ofs + Z.of_nat (size_chunk_nat chunk) ->\n      nth (Z.to_nat (z - ofs)) (encode_val chunk v) Undef = Undef ->\n      exists r,\n        nth (Z.to_nat (z - ofs)) (encode_val_bits chunk v') Undef = r.\nProof.\n  intros.\n  unfold ptr_equiv_val in H.\n  break_match_hyp;\n    repeat break_or;\n    repeat break_exists;\n    repeat break_and;\n    destruct chunk;\n    subst;\n    simpl;\n  try solve [\n  eexists;\n        repeat break_match; try reflexivity; eauto\n      ];\n  eexists; reflexivity.\nQed.\n\nLemma ptr_equiv_encode_byte :\n  forall t v v',\n    ptr_equiv_val t v v' ->\n    forall z ofs chunk,\n      ofs <= z < ofs + Z.of_nat (size_chunk_nat chunk) ->\n      forall bits,\n        nth (Z.to_nat (z - ofs)) (encode_val chunk v) Undef = Byte bits ->\n        nth (Z.to_nat (z - ofs)) (encode_val_bits chunk v') Undef = Byte bits.\nProof.\n  intros.\n  unfold ptr_equiv_val in H.\n  break_match_hyp;\n    repeat break_or;\n    repeat break_exists;\n    repeat break_and;\n    destruct chunk;\n    subst;\n    simpl in *;\n    repeat break_match_hyp;\n    congruence.\nQed.\n\nLemma wf_frag_ptr_equiv :\n  forall t v v',\n    ptr_equiv_val t v v' ->\n    forall m chunk,\n      wf_frag m v (encode_val chunk v) ->\n      wf_frag_bits m v' (encode_val_bits chunk v').\nProof.\n  intros.\n  unfold ptr_equiv_val in H.\n  break_match_hyp;\n    repeat break_or;\n    repeat break_exists;\n    repeat break_and;\n    destruct chunk;\n    subst;\n    unfold wf_frag in H0; unfold wf_frag_bits;\n    simpl in *;\n    repeat break_match_hyp;\n    simpl in *;\n    repeat break_and;\n    unfold inj_value in *;\n    unfold inj_bytes in *;\n    simpl in *;\n    try congruence;\n    repeat break_exists;\n    try congruence;\n  \n  unfold encode_int in *; simpl in *;\n  unfold rev_if_be in *; break_match;\n  simpl in *; congruence.\nQed.\n\n\n\n\n\n(* Don't go back before this *)\n\n(* This is necessary. *)\n(* We need this true *)\nLemma frag_equiv_pres :\n  forall t c c' z,\n    frag_equiv t c c' z ->\n    forall v v',\n      ptr_equiv_val t v v' ->\n      forall chunk ofs,\n        frag_equiv t (Mem.setN (encode_val chunk v) ofs c)\n                   (Mem.setN (encode_val_bits chunk v') ofs c') z.\nProof.\n  intros.\n  name (encode_val_length chunk v) evl.\n  name (encode_val_bits_length chunk v') evl'.\n  unfold frag_equiv.\n  break_match; repeat break_exists;\n  eauto.\n  assert (Hrange : (z < ofs \\/ z >= ofs + Z.of_nat (size_chunk_nat chunk)) \\/\n          (ofs <= z < ofs + Z.of_nat (size_chunk_nat chunk))) by omega.\n  destruct Hrange.\n  repeat rewrite Mem.setN_outside in * by omega.\n  unfold frag_equiv in H.\n  rewrite Heqm in H. eauto.\n  erewrite <- encode_val_length in H1.\n  instantiate (1 := v) in H1.\n  rewrite setN_get_nth in Heqm by omega.\n  repeat rewrite setN_get_nth by omega.\n  app ptr_equiv_encode_byte Heqm; omega.\n\n  name (of_nat_length chunk) ofl.\n  name (of_nat_length chunk) ofl'.\n  rewrite <- evl in ofl.\n  rewrite <- evl' in ofl'.\n  \n  \n  unfold size_quantity_nat;\n    destruct v0; destruct q;\n    repeat break_match;\n    intros;\n    auto;\n    try solve [simpl in *; omega];\n    match goal with\n      | [ H : wf_frag _ _ _ |- _ ] =>\n        app wf_frag_getN_aligned H\n\n    end;\n    match goal with\n      | [ H : wf_frag _ _ _ |- _ ] =>\n        app wf_frag_length_size H\n    end;\n    rewrite Mem.getN_length in H3;\n    break_or;\n    try (\n        rewrite Mem.setN_outside in Heqm by (simpl in H5; rewrite evl; omega);\n        rewrite Mem.getN_setN_outside in H4 by omega;\n        rewrite Mem.getN_setN_outside by omega;\n        unfold frag_equiv in H;\n        rewrite Heqm in H;\n        apply H;\n        eauto\n      );\n  rewrite <- H3 in H4;\n  app same_size_chunk H4;\n  repeat rewrite getN_setN_same in * by omega;\n  eexists; split;\n  try match goal with\n    | [ H : wf_frag _ _ _ |- _ ] => app wf_frag_inv H; break_and; subst v\n  end;\n  try match goal with\n    | [ H : ptr_equiv_val _ _ |- _ ] => app wf_frag_ptr_equiv H\n  end;\n  try eapply wf_frag_ptr_equiv; eauto;\n  assumption.\n  \nQed.\n\n\nLemma getN_in_or_out :\n  forall l ofs ofs0 c r,\n    ZMap.get ofs0 (Mem.setN l ofs c) = r ->\n    In r l \\/ ZMap.get ofs0 c = r.\nProof.\n  induction l; intros.\n  simpl in H. right. auto.\n  simpl in H. app IHl H.\n  destruct H. left. simpl. right. auto.\n  assert (ofs = ofs0 \\/ ofs <> ofs0) by omega.\n  destruct H1. subst ofs. rewrite ZMap.gss in H.\n  simpl. left. left. auto.\n  rewrite ZMap.gso in H by congruence.\n  right. auto.\nQed.\n\nLemma frag_not_in_inj_bytes :\n  forall x v q n,\n    ~ In (Fragment v q n) (inj_bytes x).\nProof.\n  induction x; intros. simpl.\n  auto.\n  simpl. \n  apply Classical_Prop.and_not_or.\n  split; try congruence.\n  apply IHx.\nQed.\n\nLemma no_pointer_ptr_equiv :\n  forall t v v',\n    ptr_equiv_val t v v' ->\n    forall c,\n      (forall ofs, no_pointer c ofs) ->\n      forall chunk ofs0 ofs,\n        no_pointer (Mem.setN (encode_val_bits chunk v') ofs c) ofs0.\nProof.\n  intros.\n  unfold no_pointer.\n  break_match; auto.\n  intros.\n  app getN_in_or_out Heqm.\n  destruct Heqm.\n  Focus 2. unfold no_pointer in H0.\n  specialize (H0 ofs0).\n  rewrite H2 in H0.\n  apply H0.\n\n  unfold ptr_equiv_val in H.\n  break_match_hyp;\n    repeat break_or;\n    repeat break_exists;\n    repeat break_and;\n    destruct chunk;\n    subst;\n    simpl in H2;\n    repeat break_or;\n    try congruence;\n  try app frag_not_in_inj_bytes H2.\nQed.\n\nLemma contents_equiv_pres :\n  forall t mc mc',\n    contents_equiv t mc mc' ->\n    forall v v',\n      ptr_equiv_val t v v' ->\n      forall chunk b ofs,\n        contents_equiv t (PMap.set b (Mem.setN (encode_val chunk v) ofs mc !! b) mc)\n                       (PMap.set b (Mem.setN (encode_val_bits chunk v') ofs mc' !! b) mc').\nProof.\n  intros.\n  unfold contents_equiv in *.\n\n  intros. destruct (peq b b0). subst.\n  split.\n  repeat rewrite PMap.gss. app frag_equiv_pres H0.\n  apply H. rewrite PMap.gss.\n  eapply no_pointer_ptr_equiv; eauto.\n  apply H.\n  repeat rewrite PMap.gso by congruence.\n  apply H.\nQed.\n\nDefinition mem_contents_equiv (t : allocator_metadata) (m m' : mem) :=\n  match_metadata t m /\\ match_metadata t m' /\\\n  contents_equiv t (Mem.mem_contents m) (Mem.mem_contents m').\n\nLemma mem_contents_equiv_store :\n  forall t m m',\n    mem_perm_same m m' ->\n    mem_contents_equiv t m m' ->\n    forall v v',\n      ptr_equiv_val t v v' ->\n      forall c b i m'',\n        Mem.store c m b i v = Some m'' ->\n        exists m''',\n          (store_bits c m' b i v' = Some m''' /\\\n           mem_perm_same m m' /\\\n           mem_contents_equiv t m'' m''').\nProof.\n  intros.\n  app mem_store_perm_same H2.\n  break_and.\n  eexists; split. eauto.\n  split.\n  app Mem.store_mem_contents H3.\n  name H2 Hst_bits.\n  unfold store_bits in H2.\n  break_match_hyp; try congruence.\n  unfold mem_contents_equiv. split.\n  eapply match_store; eauto.\n  unfold mem_contents_equiv in H0.\n  repeat break_and. eauto.\n  split. eapply match_store_bits; eauto.\n  unfold mem_contents_equiv in *. repeat break_and.\n  eauto.\n  inv H2.\n  unfold mem_contents_equiv in H0.\n  repeat break_and.\n  simpl. app Mem.store_mem_contents H3.  \n  rewrite H3. eapply contents_equiv_pres; eauto.\nQed.\n\nLemma ptr_equiv_undef_anything :\n  forall t v,\n    (forall b ofs, v <> Vptr b ofs) ->\n    ptr_equiv_val t Vundef v.\nProof.\n  intros. unfold ptr_equiv_val.\n  destruct v. left. auto.\n  right. left. eauto.\n  right. right. right. right. eauto.\n  right. right. left. eauto.\n  right. right. right. left. eauto.\n  specialize (H b i). congruence.\nQed.\n\nTactic Notation \"especialize\" constr(H) \"as\" ident(H2) := \n  match type of H with\n    | forall (x : ?X), _ =>\n      let f := fresh \"x\" in\n      evar (f : X);\n        name (H f) H2;\n          subst f\n  end.\n\nLemma frag_equiv_proj_bytes :\n  forall t c c',\n    (forall ofs, frag_equiv t c c' ofs) ->\n    forall chunk ofs l,\n      proj_bytes (Mem.getN (size_chunk_nat chunk) ofs c) = Some l ->\n      proj_bytes (Mem.getN (size_chunk_nat chunk) ofs c') = Some l.\nProof.\n  intros.\n  destruct chunk;\n    simpl in H0;\n    simpl;\n\n  \n  repeat match goal with\n    | [ H : context[match (ZMap.get ?X ?Y) with _ => _ end], H2 : forall _, frag_equiv _ _ _ _ |- _ ] =>       \n      let H4 := fresh \"H\" in\n      destruct (ZMap.get X Y) eqn:H4;\n        try congruence;\n        let H3 := fresh \"H\" in\n        especialize H2 as H3;\n          unfold frag_equiv in H3;\n          instantiate (1 := X) in H3;\n          rewrite H4 in H3;\n          try find_rewrite;\n          clear H3;\n          clear H4;\n          eauto\n         end.\n\nQed.\n\nLemma no_pointer_proj_value :\n  forall c',\n    (forall ofs, no_pointer c' ofs) ->\n    forall chunk q ofs b o,\n      proj_value q (Mem.getN (size_chunk_nat chunk) ofs c') <> Vptr b o.\nProof.\n  intros. unfold proj_value.\n  break_match. destruct chunk; simpl; congruence.\n  break_match; try solve [\n                     destruct chunk; simpl; congruence\n                   ].\n  break_match; try solve [\n                     destruct chunk; simpl; congruence\n                   ].\n  do 2 try break_match;\n    try congruence; subst;\n  unfold no_pointer in H;\n  simpl in Heql; inv Heql;\n  specialize (H ofs).\n  destruct (size_chunk_nat chunk) eqn:?.\n  destruct chunk; simpl in Heqn0;\n  unfold size_chunk_nat in Heqn0;\n  simpl in Heqn0; unfold Pos.to_nat in Heqn0;\n  simpl in Heqn0; try congruence.\n  simpl in H1. inv H1.\n  rewrite H2 in H. apply H.\nQed.\n\n\nLemma quantity_chunk_same :\n  forall q v chunk ofs c,\n    check_value (size_quantity_nat q) v q (Mem.getN (size_chunk_nat chunk) ofs c) = true ->\n    size_quantity_nat q = size_chunk_nat chunk.\nProof.\n  intros.\n  app check_value_length H.\n  rewrite Mem.getN_length in H. congruence.\nQed.\n\nLemma frag_equiv_proj_value :\n  forall t c c',\n    (forall ofs, frag_equiv t c c' ofs) ->\n    forall q chunk ofs v,\n      proj_value q (Mem.getN (size_chunk_nat chunk) ofs c) = v ->\n      ((v <> Vundef /\\ size_chunk_nat chunk = 8%nat) \\/\n       (((exists i, v = Vint i) \\/ (exists b o, v = Vptr b o) \\/ (exists s, v = Vsingle s)) /\\ size_chunk_nat chunk = 4%nat)) ->\n      proj_bytes (Mem.getN (size_chunk_nat chunk) ofs c') = None ->\n      exists v',\n        proj_value q (Mem.getN (size_chunk_nat chunk) ofs c') = v' /\\\n        ptr_equiv_val t v v'.\nProof.\n  \n  intros.\n  assert (size_chunk_nat chunk = 4%nat \\/ size_chunk_nat chunk = 8%nat) by omega.\n  destruct H3.\n  break_or; try break_and; try congruence.\n  repeat break_or; repeat break_exists;\n  unfold proj_value in H0;\n  repeat break_match_hyp; try congruence;\n  subst v;\n  app getN_get Heql;\n  name Heqb HH; rewrite <- H0 in HH; app quantity_chunk_same HH;\n  rewrite H1 in HH;\n  rewrite H1 in *;\n  destruct q; simpl in HH; try congruence;\n  try (\n      app (check_value_wf_32 Many32) H4);\n  \n  simpl in H5; rewrite Heql in H5;\n  repeat match goal with\n      | [ H : context[Val.eq ?X ?Y] |- _ ] => destruct (Val.eq X Y); try congruence\n      | [ H : context[quantity_eq ?X ?Y] |- _ ] => destruct (quantity_eq X Y); simpl in H; try congruence\n         end;\n  subst;\n  do 4 (try destruct n; simpl in H5; try congruence);\n\n  unfold frag_equiv in H; specialize (H ofs);\n  rewrite Heql in H;\n  app H H4;\n  clear H5.\n\n  break_and. simpl in H5. subst x0. eexists.\n  unfold wf_frag_bits in H4. rewrite H4 in H2.\n  simpl in H2. rewrite proj_inj_bytes in H2. inv H2.\n\n  break_and. simpl in H5. break_exists. break_and.\n  subst x1.\n  unfold wf_frag_bits in H4. rewrite H4 in H2.\n  simpl in H2. rewrite proj_inj_bytes in H2. inv H2.\n\n  break_and. simpl in H5. subst x0.\n  unfold wf_frag_bits in H4. unfold size_quantity_nat in H4.\n  rewrite H4. unfold encode_val_bits. rewrite proj_inj_value.\n  eexists; split; try reflexivity.\n  unfold proj_value. rewrite Heqb.\n  apply ptr_equiv_nonpointers; intros; congruence.\n\n  break_or; break_and; try congruence.\n  unfold proj_value in H0.\n  do 3 (break_match_hyp; try congruence).\n  \n  app getN_get Heql.\n  name Heqb HH.\n  rewrite <- H4 in HH.\n  app quantity_chunk_same HH.\n  rewrite H1 in HH.\n  destruct q; simpl in HH; try congruence.\n  app check_value_wf_64 H5.\n  rewrite H4 in H6.\n\n  simpl in H6;\n  repeat match goal with\n      | [ H : context[Val.eq ?X ?Y] |- _ ] => destruct (Val.eq X Y); try congruence\n      | [ H : context[quantity_eq ?X ?Y] |- _ ] => destruct (quantity_eq X Y); simpl in H; try congruence\n         end;\n  subst;\n  do 8 (try destruct n; simpl in H6; try congruence).\n\n  unfold frag_equiv in H; specialize (H ofs);\n  rewrite Heql in H; destruct v; try congruence;\n  rewrite H1 in *; unfold size_quantity_nat in *;\n  app H H5; try break_and;\n  clear H6;\n\n  unfold wf_frag_bits in *; rewrite H5 in *;\n  simpl in H8; try break_exists; try break_and; subst;\n  unfold encode_val_bits; rewrite proj_inj_value;\n  eexists; split; try reflexivity;\n  unfold proj_value; unfold size_quantity_nat; rewrite Heqb;\n  try solve [apply ptr_equiv_nonpointers; intros; congruence].\n  simpl. eexists; eauto.\n\n  Grab Existential Variables.\n  exact Vzero.\n  exact Int.zero.\n  exact Int.zero.\n  exact xH.\n  exact Float32.zero.\n  exact Int.zero.\n  exact Float32.zero.\n  exact Int.zero.\n  exact xH.\nQed.\n\nLemma proj_value_len :\n  forall l q,\n    size_quantity_nat q <> length l ->\n    proj_value q l = Vundef.\nProof.\n  intros; simpl.\n  unfold proj_value. do 3 (break_match; try reflexivity).\n  app check_value_length Heqb. rewrite Heqb in H. congruence.\nQed.\n\nLemma proj_value_frag_equiv :\n  forall t c c',\n    (forall ofs, frag_equiv t c c' ofs) ->\n    (forall ofs, no_pointer c' ofs) ->\n    forall q ofs chunk,\n      proj_bytes (Mem.getN (size_chunk_nat chunk) ofs c') = None ->\n      ptr_equiv_val t\n        (Val.load_result chunk (proj_value q (Mem.getN (size_chunk_nat chunk) ofs c)))\n        (Val.load_result chunk (proj_value q (Mem.getN (size_chunk_nat chunk) ofs c'))).\nProof.\n  intros. unfold Val.load_result.\n  destruct (Val.eq (proj_value q (Mem.getN (size_chunk_nat chunk) ofs c)) Vundef).\n  * (* original is undef *)\n    rewrite e.\n    destruct chunk; apply ptr_equiv_undef_anything;\n    try break_match; intros; try congruence;\n    try app no_pointer_proj_value Heqv.\n    apply no_pointer_proj_value; eauto.\n  * (* original is not undef *)\n    do 2 try break_match; try congruence;\n    try solve [\n          rewrite proj_value_len in Heqv by (\n                                             rewrite Mem.getN_length;\n                                             destruct q; simpl; auto;\n                                             unfold size_chunk_nat; simpl;\n                                             unfold Pos.to_nat; simpl;\n                                             congruence); congruence];\n\n        \n    try (app frag_equiv_proj_value Heqv; break_and; try find_rewrite);\n    try (break_match; subst; simpl in H4; congruence);\n    try simpl in H4; try rewrite <- H4;\n    try solve [\n          apply ptr_equiv_nonpointers; intros; congruence];\n    try break_match;\n    try solve [\n          apply ptr_equiv_nonpointers; intros; congruence];\n    try solve [\n          apply ptr_equiv_undef_anything; intros; congruence];\n    try break_exists; try break_and; try congruence;\n    try solve [app no_pointer_proj_value Heqv0; inv_false];\n    try (\n          app frag_equiv_proj_value Heqv; [break_and; rewrite H3 in Heqv0; subst x;\n                                           simpl in H4; break_exists; break_and; congruence | idtac]);\n    try solve [right; split; eauto];\n    try solve [\n          app frag_equiv_proj_value Heqv;\n          try solve [right; split; eauto];\n          break_and; rewrite H3 in Heqv0; subst x; assumption];\n    try solve [\n          app frag_equiv_proj_value Heqv;\n          try solve [right; split; eauto];\n          break_and; rewrite H3 in Heqv0; subst x; simpl in *; congruence].\n\n    unfold ptr_equiv_val.\n    break_match; try congruence;\n    app frag_equiv_proj_value Heqv; try congruence;\n    break_and; simpl in H4; try congruence.\n    break_exists. break_and. subst.\n    eexists; eauto.\n\nQed.\n  \nLemma frag_equiv_decode :\n  forall t c c',\n    (forall ofs, frag_equiv t c c' ofs) ->\n    (forall ofs, no_pointer c' ofs) ->\n    forall chunk ofs,\n      ptr_equiv_val t (decode_val chunk (Mem.getN (size_chunk_nat chunk) ofs c))\n                    (decode_val chunk (Mem.getN (size_chunk_nat chunk) ofs c')).\nProof.\n  intros. \n  \n  unfold decode_val.\n  break_match.\n  app frag_equiv_proj_bytes Heqo.\n  find_rewrite.\n  break_match;\n    apply ptr_equiv_nonpointers;\n    intros; congruence.\n\n  destruct chunk;\n    try solve [\n          break_match;\n          try apply ptr_equiv_undef_anything;\n          try apply ptr_equiv_nonpointers;\n          try intros; try congruence];\n    break_match;\n    try solve [\n          eapply proj_value_frag_equiv;\n          eauto];\n  unfold proj_value;\n  do 3 (try break_match;\n        try apply ptr_equiv_undef_int;\n        try apply ptr_equiv_undef_long;\n  try (apply ptr_equiv_nonpointers; intros; congruence)).\n  destruct v; try apply ptr_equiv_undef_int.\n  \n  app (check_value_wf_32 Many32) Heqb.\n  name Heqb Hwf.\n  rewrite <- Heql0 in Hwf.\n  simpl. unfold frag_equiv in H.\n  simpl in Heql0. inv Heql0.\n  specialize (H ofs).\n  rewrite H3 in H.\n  unfold wf_frag in Heqb.\n  break_and. repeat break_exists.\n  simpl in H2. unfold inj_value in H2.\n  simpl in H2. inv H2. app H Hwf.\n  break_and.\n  unfold wf_frag_bits in H5.\n  replace (size_chunk_nat Mint32) with (4%nat) in Heqo0 by (simpl; reflexivity).\n  rewrite H5 in Heqo0.\n  simpl in H6. subst x1.\n  simpl in Heqo0.\n  rewrite proj_inj_bytes in Heqo0. inv Heqo0.\n  rewrite decode_encode_int_4. reflexivity.\n\n  app (check_value_wf_32 Many32) Heqb.\n  name Heqb Hwf.\n  rewrite <- Heql0 in Hwf.\n  simpl. unfold frag_equiv in H.\n  simpl in Heql0. inv Heql0.\n  specialize (H ofs).\n  rewrite H3 in H.\n  unfold wf_frag in Heqb.\n  break_and. repeat break_exists.\n  simpl in H2. unfold inj_value in H2.\n  simpl in H2. inv H2. app H Hwf.\n  break_and.\n  unfold wf_frag_bits in H5.\n  replace (size_chunk_nat Mint32) with (4%nat) in Heqo0 by (simpl; reflexivity).\n  rewrite H5 in Heqo0.\n  simpl in H6. unfold encode_val_bits in Heqo0.\n  break_exists. break_and. subst x1.\n  rewrite proj_inj_bytes in Heqo0. inv Heqo0.\n  rewrite decode_encode_int_4. eauto.\n\n  \n  unfold Val.load_result. break_match; try solve [apply ptr_equiv_undef_int];\n  app (check_value_wf_32 Many32) Heqb;\n  name Heqb Hwf;\n  rewrite <- Heql0 in Hwf;\n  simpl; unfold frag_equiv in H;\n  simpl in Heql0; inv Heql0;\n  specialize (H ofs);\n  rewrite H3 in H;\n  unfold wf_frag in Heqb;\n  break_and; repeat break_exists;\n  simpl in H2; unfold inj_value in H2;\n  simpl in H2; inv H2; app H Hwf;\n  break_and;\n  unfold wf_frag_bits in H5;\n  replace (size_chunk_nat Many32) with (4%nat) in * by (simpl; reflexivity).\n  rewrite H5 in Heqo0.\n  simpl in H6. subst x1.\n  simpl in Heqo0.\n  rewrite proj_inj_bytes in Heqo0. inv Heqo0.\n  rewrite decode_encode_int_4. reflexivity.\n\n  simpl in H6. subst x1.\n  replace (size_quantity_nat Q32) with (4%nat) in * by reflexivity.\n  rewrite H5 in Heqo0. simpl in Heqo0. congruence.\n\n  simpl in H6. break_exists. break_and. subst x1.\n  replace (size_quantity_nat Q32) with (4%nat) in * by reflexivity.\n  rewrite H5 in Heqo0. \n  unfold encode_val_bits in Heqo0.\n  rewrite proj_inj_bytes in Heqo0. inv Heqo0.\n  rewrite decode_encode_int_4. eauto.\n\n\n  unfold Val.load_result. \n  app (check_value_wf_64) Heqb;\n  name Heqb Hwf;\n  rewrite <- Heql0 in Hwf.\n  unfold frag_equiv in H.\n  simpl in Heql0; inversion Heql0;\n  specialize (H ofs). clear Heql0. clear H4.\n  rewrite H3 in H;\n  unfold wf_frag in Heqb;\n  break_and; repeat break_exists.\n  destruct v; simpl in H2; try (apply ptr_equiv_nonpointers; intros; congruence);\n  unfold inj_value in H2; simpl in H2; inversion H2; inv H4;\n  subst x;\n  replace (size_quantity_nat Q64) with (8%nat) in * by reflexivity;\n  replace (size_chunk_nat Many64) with (8%nat) in * by (simpl; reflexivity);\n  app H Hwf;\n  \n  break_and;\n    unfold wf_frag_bits in H5;\n    simpl;\n    rewrite H5 in Heqo0; simpl in H6;\n    try (subst x; subst x0;\n         simpl in Heqo0; congruence).\n\n  break_exists. break_and.\n  subst x. subst x0. simpl in Heqo0. congruence.\n\n  \n  Grab Existential Variables.\n  exact Float32.zero.\n  exact Int.zero.        \n  exact Int.zero.\n  exact Int.zero.\n  exact xH.\n  exact Float32.zero.\n  exact Int.zero.\n  exact xH.\n  exact Float32.zero.\n  exact Int.zero.\n  exact Float32.zero.\n  exact Int.zero.\n  exact xH.\nQed.\n\nLemma contents_equiv_load_ptr_equiv :\n  forall t m m',\n    mem_perm_same m m' ->\n    mem_contents_equiv t m m' ->\n    forall c b i v,\n      Mem.load c m b i = Some v ->\n      exists v',\n        Mem.load c m' b i = Some v' /\\\n        ptr_equiv_val t v v'.\nProof.\n  intros.\n  app mem_load_exists H.\n  exists x.\n  app Mem.load_result H1.\n  app Mem.load_result H.\n  split; auto.\n  subst.\n  apply frag_equiv_decode.\n  intros. unfold mem_contents_equiv in H0.\n  unfold contents_equiv in H0. apply H0.\n  unfold mem_contents_equiv in H0.\n  unfold contents_equiv in H0.\n  apply H0.\nQed.\n\nLemma ptr_equiv_md_alloc :\n  forall t v v' lo hi b,\n    ptr_equiv_val t v v' ->\n    ptr_equiv_val (md_alloc t lo hi b) v v'.\nProof.\n  intros. unfold ptr_equiv_val in *.\n  break_match_hyp; simpl; eauto.\n  break_exists. break_and.\n  eexists; split; eauto.\n  eapply pinj_alloc. eauto.\nQed.\n\nLemma frag_equiv_alloc_pres :\n  forall t lo hi b c c' ofs,\n    frag_equiv t c c' ofs ->\n    frag_equiv (md_alloc t lo hi b) c c' ofs.\nProof.\n  intros. unfold frag_equiv in H.\n  break_match_hyp;\n    unfold frag_equiv; find_rewrite; eauto.\n  repeat (break_match_hyp; try find_rewrite; eauto);\n    intros; subst; exploit H; intros; eauto;\n    break_exists; break_and; eexists; split; eauto;\n    eapply ptr_equiv_md_alloc; eauto.\nQed.\n\nLemma contents_equiv_alloc :\n  forall t m m',\n    mem_nextblock_same m m' ->\n    mem_contents_equiv t m m' ->\n    forall m0 b lo hi,\n      Mem.alloc m lo hi = (m0,b) ->\n      exists m'0,\n        Mem.alloc m' lo hi = (m'0,b) /\\ mem_contents_equiv (md_alloc t lo hi b) m0 m'0.\nProof.\n  intros.\n  app mem_alloc_nextblock H1. break_and.\n  eexists. split. eassumption.\n  unfold mem_contents_equiv in *.\n  repeat break_and.\n  isplit.\n  eapply match_alloc; try apply H2; eauto.\n  isplit.\n  eapply match_alloc; try apply H1; eauto.\n\n  app Mem.mem_contents_alloc H2.\n  app Mem.mem_contents_alloc H1.\n  rewrite H2. rewrite H1.\n  unfold contents_equiv.\n  intros. split.\n  destruct (peq b b0). subst.\n  repeat rewrite PMap.gss.\n  unfold frag_equiv. \n  repeat rewrite ZMap.gi. auto.\n  repeat rewrite PMap.gso by congruence.\n  unfold contents_equiv in H5.\n  specialize (H5 b0 ofs).\n  break_and.\n  eapply frag_equiv_alloc_pres; eauto.\n  \n  destruct (peq b b0). subst.\n  repeat rewrite PMap.gss.\n  unfold no_pointer.\n  repeat rewrite ZMap.gi. auto.\n\n  repeat rewrite PMap.gso by congruence.\n  unfold contents_equiv in *.\n  specialize (H5 b0 ofs). break_and. eauto.\nQed.\n\n\n(* We need some notion about what has been allocated so far *)\n(* build up an inductive datatype of evidence that something's been allocated *)\n(* Note: this doesn't say anything about whether something's been freed *)\n\nInductive allocated : allocator_metadata -> block -> Prop :=\n| alloc_now :\n    forall t b lo hi,\n      allocated (md_alloc t lo hi b) b\n| alloc_prev_alloc :\n    forall t b lo hi x,\n      allocated t x ->\n      allocated (md_alloc t lo hi b) x\n| alloc_prev_free :\n    forall t b lo hi x,\n      allocated t x ->\n      allocated (md_free t lo hi b) x\n| alloc_prev_ec :\n    forall ef ge vl m tr v m' t b,\n      allocated t b ->\n      allocated (md_ec t ef ge vl m tr v m') b\n| alloc_prev_ec' :\n    forall ef ge vl m tr v m' t b,\n      allocated t b ->\n      allocated (md_ec' t ef ge vl m tr v m') b.\n\n\nDefinition is_global_block (ge : Genv.t fundef unit) (b : block) : Prop :=\n  exists id, Genv.find_symbol ge id = Some b.\n\nDefinition globals_allocated (ge : Genv.t fundef unit) (t : allocator_metadata) :=\n  forall b,\n    is_global_block ge b ->\n    allocated t b.\n\n\nDefinition ptr_equiv_mem (ge : Genv.t fundef unit) (t : allocator_metadata) (m m' : mem) : Prop := \n  mem_nextblock_same m m' /\\ mem_perm_same m m' /\\ mem_contents_equiv t m m'\n  /\\ globals_allocated ge t /\\  \n  global_perms ge m'.\n\nLemma ptr_equiv_valid_globals_r :\n  forall ge t m m',\n    ptr_equiv_mem ge t m m' ->\n    valid_globals ge m'.\nProof.\n  intros.\n  unfold ptr_equiv_mem in *.\n  repeat break_and; eauto.\n  eapply global_perms_valid_globals; eauto.\nQed.\n\nLemma ptr_equiv_global_perms_r :\n  forall ge t m m',\n    ptr_equiv_mem ge t m m' ->\n    global_perms ge m'.\nProof.\n  intros.\n  unfold ptr_equiv_mem in *;\n    repeat break_and;\n    auto.\nQed.\n  \n  \nLemma ptr_equiv_match_metadata_l :\n  forall ge t m m',\n    ptr_equiv_mem ge t m m' ->\n    match_metadata t m.\nProof.\n  intros. unfold ptr_equiv_mem in H.\n  repeat break_and. unfold mem_contents_equiv in H1.\n  repeat break_and. eauto.\nQed.\n\nLemma ptr_equiv_match_metadata_r :\n  forall ge t m m',\n    ptr_equiv_mem ge t m m' ->\n    match_metadata t m'.\nProof.\n  intros. unfold ptr_equiv_mem in H.\n  repeat break_and. unfold mem_contents_equiv in H1.\n  repeat break_and. eauto.\nQed.\n\nLemma valid_globals_store :\n  forall ge m,\n    valid_globals ge m ->\n    forall c b i v m',\n      Mem.store c m b i v = Some m' ->\n      valid_globals ge m'.\nProof.\n  intros.\n  unfold valid_globals in *.\n  intros. app H H1.\n  app Mem.store_access H0.\n  unfold Mem.valid_pointer in *.\n  unfold Mem.perm_dec in *.\n  unfold proj_sumbool in *.\n  break_match_hyp; try congruence.\n  clear Heqs. unfold Mem.perm_order' in p.\n  break_match_hyp; try inv_false.\n  rewrite <- H0 in Heqo.\n  break_match; try congruence.\n  clear Heqs.\n  unfold Mem.perm_order' in *.\n  break_match_hyp; try inv_false; try congruence.\nQed.\n\n(* Lemma valid_globals_store_bits : *)\n(*   forall ge m, *)\n(*     valid_globals ge m -> *)\n(*     forall c b i v m', *)\n(*       store_bits c m b i v = Some m' -> *)\n(*       valid_globals ge m'. *)\n(* Proof. *)\n(*   intros. unfold valid_globals in *. *)\n(*   intros. app H H1. *)\n(*   unfold Mem.valid_pointer in *. *)\n(*   unfold Mem.perm_dec in *. *)\n(*   unfold proj_sumbool in *. *)\n(*   repeat break_match; try congruence. *)\n(*   clear Heqs. clear Heqs0. *)\n(*   unfold store_bits in *. *)\n(*   break_match_hyp; try congruence; try find_inversion. *)\n(*   simpl in n. congruence. *)\n(* Qed. *)\n\n\nLemma ptr_equiv_mem_store :\n  forall ge t m m',\n    ptr_equiv_mem ge t m m' ->\n    forall v v',\n      ptr_equiv_val t v v' ->\n      forall c b i m'',\n        Mem.store c m b i v = Some m'' ->\n        exists m''',\n          (store_bits c m' b i v' = Some m''' /\\ ptr_equiv_mem ge t m'' m''').\nProof.\n  intros. \n  unfold ptr_equiv_mem in H. repeat break_and.\n  name H3 Hcont. unfold mem_contents_equiv in H3.\n  app mem_contents_equiv_store H1.\n  repeat break_and. exists x. split.\n  eauto.\n  app mem_store_perm_same H7.\n  break_and.\n  app mem_store_nextblock H.\n  repeat break_and.\n  rewrite H7 in H1. inv H1.\n  rewrite H in H7. inv H7.\n\n  unfold ptr_equiv_mem.\n  split; auto.\n  split; auto.\n  split; auto.\n  split; auto.\n  eapply global_perms_store_bits; eauto.\nQed.\n\nLemma ptr_equiv_mem_load :\n  forall ge t m m',\n    ptr_equiv_mem ge t m m' ->\n    forall c b i v,\n      Mem.load c m b i = Some v ->\n      exists v',\n        (Mem.load c m' b i = Some v' /\\ ptr_equiv_val t v v').\nProof.\n  intros.\n  unfold ptr_equiv_mem in H.\n  repeat break_and.\n  app mem_load_exists H1.\n  exists x.\n  split. assumption.\n  app Mem.load_result H0.\n  app Mem.load_result H1.\n  subst v. subst x.\n  unfold mem_contents_equiv in H2.\n  eapply frag_equiv_decode; eauto.\n  apply H2. apply H2.\nQed.\n\n(* Lemma valid_globals_alloc : *)\n(*   forall ge m, *)\n(*     valid_globals ge m -> *)\n(*     forall lo hi b m', *)\n(*       Mem.alloc m lo hi = (m',b) -> *)\n(*       valid_globals ge m'. *)\n(* Proof. *)\n(*   intros. *)\n(*   unfold valid_globals in *. *)\n(*   intros. app H H1. *)\n(*   rewrite Mem.valid_pointer_valid_access in *. *)\n(*   app Mem.valid_access_alloc_other H1. *)\n(* Qed. *)\n\nLemma ptr_equiv_mem_alloc :\n  forall ge t m m',\n    ptr_equiv_mem ge t m m' ->\n    forall m0 b lo hi,\n      Mem.alloc m lo hi = (m0,b) ->\n      exists m'0,\n        Mem.alloc m' lo hi = (m'0,b) /\\ ptr_equiv_mem ge (md_alloc t lo hi b) m0 m'0.\nProof.\n  intros. unfold ptr_equiv_mem in *.\n  break_and.\n  app mem_alloc_nextblock H.\n  repeat break_and. \n  app mem_alloc_perm H1. break_and. rewrite H in H1.\n  inv H1. rewrite H.\n\n  app contents_equiv_alloc H0. break_and.\n  eexists. \n  \n  split; try reflexivity; eauto.\n  split; eauto. split; eauto.\n\n  \n  rewrite H0 in H. inv H.\n  split.\n  assumption.\n  \n\n  split.\n\n  unfold globals_allocated in *.\n  intros. app H5 H.\n  econstructor; eauto.\n\n  eapply global_perms_alloc; eauto.\nQed.\n\n\nLemma ptr_equiv_md_free :\n  forall t v v' lo hi b,\n    ptr_equiv_val t v v' ->\n    ptr_equiv_val (md_free t lo hi b) v v'.\nProof.\n  intros. unfold ptr_equiv_val in *.\n  break_match_hyp; simpl; eauto.\n  break_exists. break_and.\n  eexists; split; eauto.\n  eapply pinj_free. eauto.\nQed.\n\nLemma frag_equiv_free_pres :\n  forall t lo hi b c c' ofs,\n    frag_equiv t c c' ofs ->\n    frag_equiv (md_free t lo hi b) c c' ofs.\nProof.\n  intros. unfold frag_equiv in H.\n  break_match_hyp;\n    unfold frag_equiv; find_rewrite; eauto.\n  repeat (break_match_hyp; try find_rewrite; eauto);\n    intros; subst; exploit H; intros; eauto;\n    break_exists; break_and; eexists; split; eauto;\n    eapply ptr_equiv_md_free; eauto.\nQed.\n\nLemma contents_equiv_md_free :\n  forall t c c' lo hi b,\n    contents_equiv t c c' ->\n    contents_equiv (md_free t lo hi b) c c'.\nProof.\n  unfold contents_equiv. intros.\n  specialize (H b0 ofs). break_and. split;\n    try eapply frag_equiv_free_pres; eauto.\nQed.\n\nLemma ptr_equiv_mem_free :\n  forall ge t m m',\n    ptr_equiv_mem ge t m m' ->\n    forall b lo hi m0,\n      Mem.free m b lo hi = Some m0 ->\n      exists m'0,\n        Mem.free m' b lo hi = Some m'0 /\\ ptr_equiv_mem ge (md_free t lo hi b) m0 m'0.\nProof.\n  intros.\n  unfold ptr_equiv_mem in H. repeat break_and. \n  app mem_free_perm H1. break_and.\n  app mem_free_nextblock H0.\n  break_and. rewrite H0 in H1. inv H1.\n  exists x. split. auto.\n  unfold ptr_equiv_mem.\n  split. auto.\n  split. auto.\n\n  split.\n  app Mem.free_result H7.\n  app Mem.free_result H0.\n  unfold mem_contents_equiv in *.\n  repeat break_and.\n  isplit.\n  eapply match_free; try apply H1; eauto.\n  isplit.\n  eapply match_free; try apply H7; eauto.\n  \n  subst x. subst m0.\n  unfold Mem.unchecked_free.\n  simpl.\n\n  eapply contents_equiv_md_free; eauto.\n\n  split.\n\n  unfold globals_allocated in *.\n  intros. app H3 H1. econstructor; eauto.\n\n  eapply global_perms_free; eauto.\n\nQed.\n\n\nLemma perm_same_range_perm :\n  forall m m',\n    mem_perm_same m m' ->\n    forall b i j y,\n      Mem.range_perm m b i j Cur y ->\n      Mem.range_perm m' b i j Cur y.\nProof.\n  intros. unfold Mem.range_perm in H0.\n  unfold Mem.range_perm. intros.\n  specialize (H0 ofs H1).\n  eapply perm_same_imp; eauto.\nQed.\n\nLemma perm_same_drop_perm :\n  forall m b i j perm m0 m',\n    mem_perm_same m m' ->\n    Mem.drop_perm m b i j perm = Some m0 ->\n    exists m0',\n      Mem.drop_perm m' b i j perm = Some m0'.\nProof.\n  intros.\n  unfold Mem.drop_perm in *.\n  break_match_hyp; try congruence.\n  \n  app perm_same_range_perm r.\n  \n  break_match; try congruence. inv H0.\n  eexists; split; try reflexivity.\n\nQed.\n\n\nLemma ptr_equiv_drop_perm :\n  forall ge t m m',\n    ptr_equiv_mem ge t m m' ->\n    forall b i j m0 perm,\n      Mem.drop_perm m b i j perm = Some m0 ->\n      exists m0',\n        Mem.drop_perm m' b i j perm = Some m0' /\\\n        ptr_equiv_mem ge t m0 m0'.\nProof.\n  intros.\n  unfold ptr_equiv_mem in H. break_and.\n  break_and.\n  app perm_same_drop_perm H0.\n  find_rewrite. eexists; split; eauto.\n  \n  \n  unfold ptr_equiv_mem. repeat isplit.\n  \n  * unfold mem_nextblock_same. simpl.\n    unfold Mem.drop_perm in *; repeat break_match_hyp; try congruence; repeat find_inversion.\n    apply H.\n\n  * repeat break_and.\n    unfold Mem.drop_perm in *.\n    repeat break_match_hyp; try congruence;\n    repeat opt_inv; subst;\n    unfold mem_perm_same in *;\n    unfold mem_nextblock_same in *;\n    simpl in *.\n    intros.\n    destruct (peq b b0);\n      try subst b;\n      repeat rewrite PMap.gss in *;\n      repeat rewrite PMap.gso in * by congruence;\n      try break_match;\n      eauto.\n  * unfold mem_contents_equiv in *.\n    repeat break_and. isplit.\n    eapply match_drop_perm; try apply H3; eauto.\n    isplit.\n    eapply match_drop_perm; try eapply H0; eauto.\n    unfold Mem.drop_perm in *; repeat break_match_hyp; try congruence; repeat find_inversion; simpl in *. assumption.\n  * repeat break_and; eauto.\n  * eapply global_perms_drop_perm; eauto.\n    repeat break_and. eauto.\nQed.\n\n(* I hate this *)\n\n(* Lemma ptr_equiv_store_raw : *)\n(*   forall m m', *)\n(*     ptr_equiv_mem m m' -> *)\n(*     forall v v' chunk, *)\n(*       (ptr_equiv_val v v' /\\ encode_val chunk v' = encode_val_bits chunk v') -> *)\n(*       forall b ofs m0, *)\n(*         Mem.store chunk m b ofs v = Some m0 -> *)\n(*         exists m0', *)\n(*           Mem.store chunk m' b ofs v' = Some m0' /\\ *)\n(*           ptr_equiv_mem m0 m0'. *)\n(* Proof. *)\n(*   intros. app Mem.store_valid_access_3 H1. *)\n(*   unfold ptr_equiv_mem in H. repeat break_and. *)\n(*   app perm_same_valid_access H1. *)\n(*   app Mem.valid_access_store H1. destruct H1. *)\n(*   instantiate (1 := v') in e. *)\n(*   rewrite e. eexists; split; eauto. *)\n(*   unfold ptr_equiv_mem. split. *)\n(*   app Mem.nextblock_store H2. *)\n(*   app Mem.nextblock_store e. *)\n(*   unfold mem_nextblock_same in *. congruence. *)\n(*   split. *)\n\n(*   unfold mem_perm_same. intros. *)\n(*   app Mem.perm_store_2 H2. *)\n(*   unfold mem_perm_same in H3.  *)\n(*   app H4 H2. *)\n(*   app Mem.perm_store_1 e. *)\n\n(*   unfold mem_contents_equiv in *. *)\n(*   app Mem.store_mem_contents H2.  *)\n(*   app Mem.store_mem_contents e. rewrite e. *)\n(*   rewrite H3. *)\n(*   rewrite H2. *)\n(*   eapply contents_equiv_pres. assumption. *)\n(*   assumption. *)\n(* Qed. *)\n  \n\n(* Lemma ptr_equiv_store_zero : *)\n(*   forall m m', *)\n(*     ptr_equiv_mem m m' -> *)\n(*     forall b ofs m0, *)\n(*       Mem.store Mint8unsigned m b ofs Vzero = Some m0 -> *)\n(*       exists m0', *)\n(*         Mem.store Mint8unsigned m' b ofs Vzero = Some m0' /\\ *)\n(*         ptr_equiv_mem m0 m0'. *)\n(* Proof. *)\n(*   intros. app Mem.store_valid_access_3 H0. *)\n(*   unfold ptr_equiv_mem in H. repeat break_and. *)\n(*   app perm_same_valid_access H0. *)\n(*   app Mem.valid_access_store H0. destruct H0. *)\n(*   instantiate (1 := Vzero) in e. *)\n(*   rewrite e. eexists; split; eauto. *)\n(*   unfold ptr_equiv_mem. split. *)\n(*   app Mem.nextblock_store H1. *)\n(*   app Mem.nextblock_store e. *)\n(*   unfold mem_nextblock_same in *. congruence. *)\n(*   split. *)\n\n(*   unfold mem_perm_same. intros. *)\n(*   app Mem.perm_store_2 H1. *)\n(*   unfold mem_perm_same in H2. *)\n(*   app H2 H1. *)\n(*   app Mem.perm_store_1 e. *)\n\n(*   unfold mem_contents_equiv in *. *)\n(*   app Mem.store_mem_contents H1.  *)\n(*   app Mem.store_mem_contents e. rewrite e. *)\n(*   replace (encode_val Mint8unsigned Vzero) with (encode_val_bits Mint8unsigned Vzero) by (simpl; reflexivity). *)\n(*   rewrite H1. *)\n(*   eapply contents_equiv_pres. assumption. *)\n(*   simpl. reflexivity. *)\n(* Qed. *)\n\n(* Not really useful anymore *)\nLemma ptr_equiv_store_zeros :\n  forall l ge t m m',\n    ptr_equiv_mem ge t m m' ->\n      forall b ofs m0,\n        store_zeros m b ofs l = Some m0 ->\n        exists m0',\n          store_zeros_bits m' b ofs l = Some m0' /\\\n          ptr_equiv_mem ge t m0 m0'.\nProof.\n  induction l using Z_nat_ind; intros.\n  rewrite store_zeros_equation in *. break_match_hyp; try omega. inv H0. eauto.\n  rewrite store_zeros_bits_equation. rewrite Heqs.\n  eauto.\n  rewrite store_zeros_equation in *. break_match_hyp; try omega. inv H0. eauto.\n  rewrite store_zeros_bits_equation. rewrite Heqs.\n  break_match_hyp; try congruence.\n  rewrite store_zeros_equation in H2. break_match_hyp; try omega. inv H2.\n  app ptr_equiv_mem_store Heqo. break_and. rewrite H1.\n  eexists; split; eauto.\n  replace (1-1) with 0 by omega.\n  rewrite store_zeros_bits_equation.\n  break_match; try omega. reflexivity.\n  simpl. reflexivity.\n  rewrite store_zeros_equation in H1.\n  break_match_hyp; try omega. inv H1.\n  rewrite store_zeros_bits_equation. break_match; try omega.\n  eauto.\n\n  rewrite store_zeros_equation in H1. break_match_hyp; try omega.\n  break_match_hyp; try congruence.\n  replace (l + 1 - 1) with l in H1 by omega.\n  app ptr_equiv_mem_store Heqo; simpl; try reflexivity.\n  break_and.\n\n  eapply IHl in H1; eauto.\n  rewrite store_zeros_bits_equation. break_match; try omega.\n  collapse_match.\n  replace (l + 1 - 1) with l by omega.\n  eauto.\nQed.\n\n\n", "meta": {"author": "uwplse", "repo": "peek", "sha": "4943735ed39fd5ddadf2c28fc2ada31504228561", "save_path": "github-repos/coq/uwplse-peek", "path": "github-repos/coq/uwplse-peek/peek-4943735ed39fd5ddadf2c28fc2ada31504228561/compcert/asmbits/PtrEquivMem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.23532835189048454}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*              Object Primitives                                      *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AuxStateDataType.\nRequire Import FlatMemory.\nRequire Import AbstractDataType.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Constant.\nRequire Import RealParams.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import CalRealSMSPool.\n\nRequire Import ObjLMM.\n\nSection OBJ_ShareMEM.\n\n  Context `{real_params: RealParams}.\n\n  Function shared_mem_arg (pid1 pid2: Z) :=\n    if zle_lt 0 pid1 num_proc then\n      if zle_lt 0 pid2 num_proc then\n        if zeq pid1 pid2 then false\n        else true\n      else false\n    else false.\n\n  Function shared_mem_arg' (pid1 pid2: Z) :=\n    if zle_lt 0 pid1 num_proc then\n      if zle_lt 0 pid2 num_proc then\n        true\n      else false\n    else false.\n  \n  Function get_shared_mem_state_spec (pid1 pid2: Z) (adt: RData) : option Z :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match ZMap.get pid2 (ZMap.get pid1 (smspool adt)) with\n          | SHRDValid i s vadr => Some (SharedMemInfo2Z i)\n          | _ => None\n        end \n      | _ => None\n    end.\n\n  Function get_shared_mem_seen_spec (pid1 pid2: Z) (adt: RData) : option Z :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match ZMap.get pid2 (ZMap.get pid1 (smspool adt)) with\n          | SHRDValid i s vadr => Some (BooltoZ s)\n          | _ => None\n        end \n      | _ => None\n    end.\n\n  Function get_shared_mem_loc_spec (pid1 pid2: Z) (adt: RData) : option Z :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match ZMap.get pid2 (ZMap.get pid1 (smspool adt)) with\n          | SHRDValid i s vadr => Some vadr\n          | _ => None\n        end \n      | _ => None\n    end.\n\n  Function set_shared_mem_state_spec (pid1 pid2 n: Z) (adt: RData) : option RData :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match (ZMap.get pid2 (ZMap.get pid1 (smspool adt)), Z2SharedMemInfo n) with\n          | (SHRDValid _ s vadr, Some i) =>\n            Some adt {smspool: ZMap.set pid1 (ZMap.set pid2 (SHRDValid i s vadr) \n                                                       (ZMap.get pid1 (smspool adt)))\n                                        (smspool adt)}\n          | _ => None\n        end \n      | _ => None\n    end.\n\n  Function set_shared_mem_seen_spec (pid1 pid2 n: Z) (adt: RData) : option RData :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match (ZMap.get pid2 (ZMap.get pid1 (smspool adt)), ZtoBool n) with\n          | (SHRDValid i _ vadr, Some s) =>\n            Some adt {smspool: ZMap.set pid1 (ZMap.set pid2 (SHRDValid i s vadr)\n                                                       (ZMap.get pid1 (smspool adt)))\n                                        (smspool adt)}\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Function set_shared_mem_loc_spec (pid1 pid2 vadr: Z) (adt: RData) : option RData :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match ZMap.get pid2 (ZMap.get pid1 (smspool adt)) with\n          | SHRDValid i s _  => \n            Some adt {smspool: ZMap.set pid1 (ZMap.set pid2 (SHRDValid i s vadr)\n                                                       (ZMap.get pid1 (smspool adt)))\n                                        (smspool adt)}\n          | _ => None\n        end \n      | _ => None\n    end.\n\n  Function clear_shared_mem_spec (pid1 pid2: Z) (adt: RData) : option RData :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg' pid1 pid2) with\n      | (true, true, true, true, true) =>\n        Some adt {smspool: ZMap.set pid1 (ZMap.set pid2 (SHRDValid SHRDDEAD true 0)\n                                                   (ZMap.get pid1 (smspool adt)))\n                                    (smspool adt)}\n      | _ => None\n    end.\n\n  Function shared_mem_to_pending_spec (pid1 pid2 vadr: Z) (adt: RData) : option RData :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match ZMap.get pid2 (ZMap.get pid1 (smspool adt)) with\n          | SHRDValid _ _ _ => \n            Some adt {smspool: ZMap.set pid1 (ZMap.set pid2 (SHRDValid SHRDPEND true vadr)\n                                                       (ZMap.get pid1 (smspool adt)))\n                                        (smspool adt)}\n          | _ => None\n        end \n      | _ => None\n    end.\n\n  Function shared_mem_to_dead_spec (pid1 pid2 vadr: Z) (adt: RData) : option RData :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match (ZMap.get pid2 (ZMap.get pid1 (smspool adt)), ZMap.get pid1 (ZMap.get pid2 (smspool adt))) with\n          | (SHRDValid _ _ _, SHRDValid _ _ _) => \n            let smsp := (ZMap.set pid1 (ZMap.set pid2 (SHRDValid SHRDDEAD true 0) (ZMap.get pid1 (smspool adt)))\n                                  (smspool adt)) in\n            let smsp' := (ZMap.set pid2 (ZMap.set pid1 (SHRDValid SHRDDEAD false 0) (ZMap.get pid2 smsp))\n                                   smsp) in\n            Some adt {smspool: smsp'}\n          | _ => None\n        end \n      | _ => None\n    end.\n\n  Function shared_mem_to_ready_spec (pid1 pid2 vadr: Z) (adt: RData) : option (RData * Z) :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match ZMap.get pid2 (ZMap.get pid1 (smspool adt)) with\n          | SHRDValid _ _ _ =>\n            match ZMap.get pid1 (ZMap.get pid2 (smspool adt)) with\n              | SHRDValid _ _ vadr' =>\n                if zle_lt 0 vadr' adr_max then\n                  match ptResv2_spec pid1 vadr PT_PERM_PTU pid2 vadr' PT_PERM_PTU adt with\n                    | Some (adt', rest) =>\n                      if zeq rest MagicNumber then Some (adt', MagicNumber)\n                      else\n                        let smsp := (ZMap.set pid1 (ZMap.set pid2 (SHRDValid SHRDREADY true 0) (ZMap.get pid1 (smspool adt')))\n                                              (smspool adt')) in\n                        let smsp' := (ZMap.set pid2 (ZMap.set pid1 (SHRDValid SHRDREADY false 0) (ZMap.get pid2 smsp))\n                                               smsp) in\n                        Some (adt' {smspool: smsp'}, rest)\n                    | _ => None\n                  end\n                else None\n              | _ => None\n            end\n          | _ => None\n        end \n      | _ => None\n    end.\n\n  Function get_shared_mem_status_seen_spec (pid1 pid2: Z) (adt: RData) : option Z :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match ZMap.get pid1 (ZMap.get pid2 (smspool adt)) with\n          | SHRDValid st _ _ => \n            if SharedMemInfo_dec st SHRDPEND then Some SHARED_MEM_PEND\n            else\n              match ZMap.get pid2 (ZMap.get pid1 (smspool adt)) with\n                | SHRDValid i' _ _ => Some (SharedMemInfo2Z i')\n                | _ => None\n              end\n          | _ => None\n        end\n      | _ => None\n    end.\n\n  Function sharedmem_init_spec (mbi_adr:Z) (adt: RData): option RData :=\n    match (init adt, pg adt, ikern adt, ihost adt, ipt adt) with\n      | (false, false, true, true, true) => \n        Some adt {vmxinfo: real_vmxinfo} {pg: true} {LAT: real_LAT (LAT adt)} {nps: real_nps}\n             {AC: real_AC} {init: true} {PT: 0} {ptpool: real_pt (ptpool adt)}\n             {idpde: real_idpde (idpde adt)}\n             {smspool: real_smspool (smspool adt)}\n      | _ => None\n    end.\n\n  Function shared_mem_status_spec (pid1 pid2: Z) (adt: RData) : option (RData * Z) :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match ZMap.get pid2 (ZMap.get pid1 (smspool adt)) with\n          | SHRDValid i' true _ => \n            match ZMap.get pid1 (ZMap.get pid2 (smspool adt)) with\n              | SHRDValid st _ _ => \n                if SharedMemInfo_dec st SHRDPEND then Some (adt, SHARED_MEM_PEND)\n                else Some (adt, SharedMemInfo2Z i')\n              | _ => None\n            end\n          | SHRDValid i' false vadr => \n            Some (adt {smspool: ZMap.set pid1 (ZMap.set pid2 (SHRDValid i' true vadr) \n                                                        (ZMap.get pid1 (smspool adt)))\n                                         (smspool adt)}, SharedMemInfo2Z i')\n          | _ => None\n        end \n      | _ => None\n    end.\n\n  Function offer_shared_mem_spec (pid1 pid2 vadr: Z) (adt: RData) : option (RData * Z) :=\n    match (ikern adt, ihost adt, pg adt, ipt adt, shared_mem_arg pid1 pid2) with\n      | (true, true, true, true, true) =>\n        match ZMap.get pid2 (ZMap.get pid1 (smspool adt)) with\n          | SHRDValid st _ _ => \n            if SharedMemInfo_dec st SHRDPEND then Some (adt, SHARED_MEM_PEND)\n            else\n              match ZMap.get pid1 (ZMap.get pid2 (smspool adt)) with\n                | SHRDValid st' _ vadr' => \n                  if zle_lt 0 vadr' adr_max then\n                    if SharedMemInfo_dec st' SHRDPEND then\n                      match ptResv2_spec pid1 vadr PT_PERM_PTU pid2 vadr' PT_PERM_PTU adt with\n                        | Some (adt', re) =>\n                          if zeq re MagicNumber\n                          then\n                            let smsp := (ZMap.set pid1 (ZMap.set pid2 (SHRDValid SHRDDEAD true 0) (ZMap.get pid1 (smspool adt)))\n                                                  (smspool adt')) in\n                            let smsp' := (ZMap.set pid2 (ZMap.set pid1 (SHRDValid SHRDDEAD false 0) (ZMap.get pid2 smsp))\n                                                   smsp) in\n                            Some (adt' {smspool: smsp'}, SHARED_MEM_DEAD)\n                          else\n                            let smsp := (ZMap.set pid1 (ZMap.set pid2 (SHRDValid SHRDREADY true 0) (ZMap.get pid1 (smspool adt')))\n                                                  (smspool adt')) in\n                            let smsp' := (ZMap.set pid2 (ZMap.set pid1 (SHRDValid SHRDREADY false 0) (ZMap.get pid2 smsp))\n                                                   smsp) in\n                            Some (adt' {smspool: smsp'}, SHARED_MEM_READY)\n                        | _ => None\n                      end\n                    else\n                      Some (adt {smspool: ZMap.set pid1 (ZMap.set pid2 (SHRDValid SHRDPEND true vadr) \n                                                                  (ZMap.get pid1 (smspool adt)))\n                                                   (smspool adt)}, SHARED_MEM_PEND)\n                  else None\n                | _ => None\n              end\n          | _ => None\n        end\n      | _ => None\n    end.\n\nEnd OBJ_ShareMEM.\n\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import CommonTactic.\nRequire Import RefinementTactic.\nRequire Import PrimSemantics.\nRequire Import Observation.\n\nSection OBJ_SIM.\n\n  Context `{Hobs: Observation}.\n\n  Context `{data : CompatData(Obs:=Obs) RData}.\n  Context `{data0 : CompatData(Obs:=Obs) RData}.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Notation HDATAOps := (cdata (cdata_prf := data) RData).\n  Notation LDATAOps := (cdata (cdata_prf := data0) RData).\n\n  Context `{rel_prf: CompatRel _ (Obs:=Obs) (memory_model_ops:= memory_model_ops) _\n                               (stencil_ops:= stencil_ops) HDATAOps LDATAOps}.\n\n  Section Shared_MEM_GETTER.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re3: relate_impl_smspool}.\n\n    Lemma get_shared_mem_state_exists:\n      forall s habd labd i1 i2 z f,\n      get_shared_mem_state_spec i1 i2 habd = Some z\n      -> relate_AbData s f habd labd\n      -> get_shared_mem_state_spec i1 i2 labd = Some z.\n    Proof.\n      unfold get_shared_mem_state_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1. \n      exploit relate_impl_ipt_eq; eauto; intros.\n      exploit relate_impl_smspool_eq; eauto; intros.\n      revert H; subrewrite.\n    Qed.\n\n    Lemma get_shared_mem_seen_exists:\n      forall s habd labd i1 i2 z f,\n      get_shared_mem_seen_spec i1 i2 habd = Some z\n      -> relate_AbData s f habd labd\n      -> get_shared_mem_seen_spec i1 i2 labd = Some z.\n    Proof.\n      unfold get_shared_mem_seen_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1. \n      exploit relate_impl_ipt_eq; eauto; intros.\n      exploit relate_impl_smspool_eq; eauto; intros.\n      revert H; subrewrite.\n    Qed.\n\n    Lemma get_shared_mem_state_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem get_shared_mem_state_spec)\n            (id ↦ gensem get_shared_mem_state_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl'.\n      match_external_states_simpl. \n      erewrite get_shared_mem_state_exists; eauto. reflexivity.\n    Qed.      \n\n    Lemma get_shared_mem_seen_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem get_shared_mem_seen_spec)\n            (id ↦ gensem get_shared_mem_seen_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl'.\n      match_external_states_simpl. \n      erewrite get_shared_mem_seen_exists; eauto. reflexivity.\n    Qed.      \n\n  End Shared_MEM_GETTER.\n\n  Section Shared_MEM_SETTER.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re3: relate_impl_smspool}.\n \n    Lemma set_shared_mem_seen_exists:\n      forall s habd habd' labd i1 i2 z f,\n        set_shared_mem_seen_spec i1 i2 z habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', set_shared_mem_seen_spec i1 i2 z labd = Some labd'\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold set_shared_mem_seen_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1. \n      exploit relate_impl_ipt_eq; eauto; intros.\n      exploit relate_impl_smspool_eq; eauto; intros.\n      revert H. subrewrite.\n      subdestruct; inv HQ; refine_split'; trivial.\n      apply relate_impl_smspool_update. assumption.\n    Qed.\n\n    Context {mt1: match_impl_smspool}.\n\n    Lemma set_shared_mem_seen_match:\n      forall s d d' m i1 i2 z f,\n        set_shared_mem_seen_spec i1 i2 z d = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold set_shared_mem_seen_spec; intros. subdestruct; inv H; trivial.\n      eapply match_impl_smspool_update. assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) set_shared_mem_seen_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) set_shared_mem_seen_spec}.\n\n    Lemma set_shared_mem_seen_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem set_shared_mem_seen_spec)\n            (id ↦ gensem set_shared_mem_seen_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl'.\n      exploit set_shared_mem_seen_exists; eauto 1; intros (labd' & HP & HM).\n      match_external_states_simpl. \n      eapply set_shared_mem_seen_match; eauto.\n    Qed.      \n\n  End Shared_MEM_SETTER.\n\n  Section Shared_MEM_STATUS.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re3: relate_impl_smspool}.\n \n    Lemma shared_mem_status_exists:\n      forall s habd habd' labd i1 i2 z f,\n        shared_mem_status_spec i1 i2 habd = Some (habd', z)\n        -> relate_AbData s f habd labd\n        -> exists labd', shared_mem_status_spec i1 i2 labd = Some (labd', z)\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold shared_mem_status_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1. \n      exploit relate_impl_ipt_eq; eauto; intros.\n      exploit relate_impl_smspool_eq; eauto; intros.\n      revert H. subrewrite.\n      subdestruct; inv HQ; refine_split'; trivial.\n      apply relate_impl_smspool_update. assumption.\n    Qed.\n\n    Context {mt1: match_impl_smspool}.\n\n    Lemma shared_mem_status_match:\n      forall s d d' m i1 i2 z f,\n        shared_mem_status_spec i1 i2 d = Some (d', z)\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold shared_mem_status_spec; intros. subdestruct; inv H; trivial.\n      eapply match_impl_smspool_update. assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) shared_mem_status_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) shared_mem_status_spec}.\n\n    Lemma shared_mem_status_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem shared_mem_status_spec)\n            (id ↦ gensem shared_mem_status_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl'.\n      exploit shared_mem_status_exists; eauto 1. intros (labd' & HP & HM).\n      match_external_states_simpl. \n      eapply shared_mem_status_match; eauto.\n    Qed.      \n\n  End Shared_MEM_STATUS.\n\n  Section PT_RESV2_SIM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_init}.\n    Context {re3: relate_impl_LAT}.\n    Context {re4: relate_impl_nps}.\n    Context {re5: relate_impl_pperm}.\n    Context {re6: relate_impl_ipt}.\n    Context {re7: relate_impl_ptpool}.\n    Context {re8: relate_impl_HP}.\n    Context {re9: relate_impl_AC}.\n\n    Lemma ptResv2_exist:\n      forall s habd habd' labd i n v p n' v' p' f,\n        ptResv2_spec n v p n' v' p' habd = Some (habd', i)\n        -> relate_AbData s f habd labd\n        -> exists labd', ptResv2_spec n v p n' v' p' labd = Some (labd', i)\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold ptResv2_spec; intros.\n      subdestruct. destruct p0.\n      - exploit alloc_exist; eauto.\n        intros (? & ? & ?).\n        subrewrite'. inv H. refine_split'; trivial.\n      - exploit alloc_exist; eauto.\n        intros (? & ? & ?).\n        exploit ptInsert0_exist; eauto.\n        intros (? & ? & ?).\n        subrewrite'. inv H. refine_split'; trivial.\n      - exploit alloc_exist; eauto.\n        intros (? & ? & ?).\n        revert Hdestruct2; intros Hc.\n        exploit ptInsert0_exist; eauto.\n        intros (? & ? & ?).\n        subrewrite'. clear Hc H3.\n        exploit ptInsert0_exist; eauto.\n    Qed.\n\n    Context {mt1: match_impl_pperm}.\n    Context {mt2: match_impl_LAT}.\n    Context {mt3: match_impl_ptpool}.\n    Context {mt4: match_impl_HP}.\n    Context {mt5: match_impl_AC}.\n\n    Lemma ptResv2_match:\n      forall s d d' m i n v p n' v' p' f,\n        ptResv2_spec n v p n' v' p' d = Some (d', i)\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold ptResv2_spec; intros. subdestruct; inv H; trivial.\n      - eapply ptInsert0_match; eauto.\n        eapply alloc_match; eauto.\n      - eapply ptInsert0_match; eauto.\n        eapply ptInsert0_match; eauto.\n        eapply alloc_match; eauto.\n    Qed.\n    \n    Context {inv: PreservesInvariants (HD:= data) ptResv2_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) ptResv2_spec}.\n\n    Lemma ptResv2_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem ptResv2_spec)\n            (id ↦ gensem ptResv2_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit ptResv2_exist; eauto 1; intros (labd' & HP & HM).\n      match_external_states_simpl.\n      eapply ptResv2_match; eauto.\n    Qed.\n\n  End PT_RESV2_SIM.\n\n  Section Offer_Shared_MEM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_init}.\n    Context {re3: relate_impl_LAT}.\n    Context {re4: relate_impl_nps}.\n    Context {re5: relate_impl_pperm}.\n    Context {re6: relate_impl_ipt}.\n    Context {re7: relate_impl_ptpool}.\n    Context {re8: relate_impl_HP}.\n    Context {re9: relate_impl_smspool}.\n    Context {re10: relate_impl_AC}.\n \n    Lemma offer_shared_mem_exists:\n      forall s habd habd' labd i1 i2 v z f,\n        offer_shared_mem_spec i1 i2 v habd = Some (habd', z)\n        -> relate_AbData s f habd labd\n        -> exists labd', offer_shared_mem_spec i1 i2 v labd = Some (labd', z)\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold offer_shared_mem_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1. \n      exploit relate_impl_smspool_eq; eauto; intros.\n      exploit relate_impl_ipt_eq; eauto; intros.\n      revert H. subrewrite.\n      subdestruct; inv HQ; try(refine_split'; trivial; fail).\n      - exploit ptResv2_exist; eauto.\n        intros (? & ? & ?).\n        exploit relate_impl_smspool_eq; eauto; intros.\n        subrewrite'. refine_split'. trivial.\n        apply relate_impl_smspool_update. assumption.        \n      - exploit ptResv2_exist; eauto.\n        intros (? & ? & ?).      \n        exploit relate_impl_smspool_eq; eauto; intros.\n        subrewrite'. refine_split'; trivial.\n        apply relate_impl_smspool_update. assumption.\n      - refine_split'; trivial.\n        apply relate_impl_smspool_update. assumption.\n    Qed.\n\n    Context {mt1: match_impl_pperm}.\n    Context {mt2: match_impl_LAT}.\n    Context {mt3: match_impl_ptpool}.\n    Context {mt4: match_impl_HP}.\n    Context {mt5: match_impl_smspool}.\n    Context {mt6: match_impl_AC}.\n\n    Lemma offer_shared_mem_match:\n      forall s d d' m i1 i2 v z f,\n        offer_shared_mem_spec i1 i2 v d = Some (d', z)\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold offer_shared_mem_spec; intros. subdestruct; inv H; trivial.\n      - eapply match_impl_smspool_update.\n        eapply ptResv2_match; eauto.\n      - eapply match_impl_smspool_update. \n        eapply ptResv2_match; eauto.\n      - eapply match_impl_smspool_update. \n        assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) offer_shared_mem_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) offer_shared_mem_spec}.\n\n    Lemma offer_shared_mem_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem offer_shared_mem_spec)\n            (id ↦ gensem offer_shared_mem_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl'.\n      exploit offer_shared_mem_exists; eauto 1. intros (labd' & HP & HM).\n      match_external_states_simpl. \n      eapply offer_shared_mem_match; eauto.\n    Qed.      \n\n  End Offer_Shared_MEM.\n \n  (** ** The low level specifications exist*)\n  Section SHAREDMEMINIT_SIM.\n\n    Context `{real_params: RealParams}.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re3: relate_impl_LAT}.\n    Context {re4: relate_impl_nps}.\n    Context {re5: relate_impl_init}.\n    Context {re6: relate_impl_PT}.\n    Context {re7: relate_impl_ptpool}.\n    Context {re8: relate_impl_idpde}.\n    Context {re9: relate_impl_smspool}.\n    Context {re10: relate_impl_vmxinfo}.\n    Context {re11: relate_impl_AC}.\n\n    Lemma sharedmem_init_exist:\n      forall s habd habd' labd i f,\n        sharedmem_init_spec i habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', sharedmem_init_spec i labd = Some labd' \n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold sharedmem_init_spec; intros. \n      exploit relate_impl_iflags_eq; eauto. inversion 1. \n      exploit relate_impl_init_eq; eauto.\n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_LAT_eq; eauto.\n      exploit relate_impl_ptpool_eq; eauto.\n      exploit relate_impl_idpde_eq; eauto.\n      exploit relate_impl_vmxinfo_eq; eauto.\n      exploit relate_impl_smspool_eq; eauto. intros.\n      revert H; subrewrite. subdestruct.\n      inv HQ. refine_split'; trivial.\n\n      apply relate_impl_smspool_update.\n      apply relate_impl_idpde_update.\n      apply relate_impl_ptpool_update.\n      apply relate_impl_PT_update.\n      apply relate_impl_init_update.\n      apply relate_impl_AC_update.\n      apply relate_impl_nps_update.\n      apply relate_impl_LAT_update.\n      apply relate_impl_pg_update. \n      apply relate_impl_vmxinfo_update. \n      assumption.\n    Qed.\n\n    Context {mt1: match_impl_iflags}.\n    Context {mt2: match_impl_ipt}.\n    Context {mt3: match_impl_LAT}.\n    Context {mt4: match_impl_nps}.\n    Context {mt5: match_impl_init}.\n    Context {mt6: match_impl_PT}.\n    Context {mt7: match_impl_ptpool}.\n    Context {mt8: match_impl_idpde}.\n    Context {mt10: match_impl_smspool}.\n    Context {mt11: match_impl_vmxinfo}.\n    Context {mt12: match_impl_AC}.\n\n    Lemma sharedmem_init_match:\n      forall s d d' m i f,\n        sharedmem_init_spec i d = Some d'\n        -> match_AbData s d m f\n        -> match_AbData s d' m f.\n    Proof.\n      unfold sharedmem_init_spec; intros. subdestruct. inv H. \n      eapply match_impl_smspool_update. \n      eapply match_impl_idpde_update.\n      eapply match_impl_ptpool_update. \n      eapply match_impl_PT_update. \n      eapply match_impl_init_update. \n      eapply match_impl_AC_update.\n      eapply match_impl_nps_update. \n      eapply match_impl_LAT_update.\n      eapply match_impl_pg_update. \n      eapply match_impl_vmxinfo_update. \n      assumption.\n    Qed.\n\n    Context {inv: PreservesInvariants (HD:= data) sharedmem_init_spec}.\n    Context {inv0: PreservesInvariants (HD:= data0) sharedmem_init_spec}.\n\n    Lemma sharedmem_init_sim :\n      forall id,\n        sim (crel RData RData) (id ↦ gensem sharedmem_init_spec)\n            (id ↦ gensem sharedmem_init_spec).\n    Proof.\n      intros. layer_sim_simpl. compatsim_simpl (@match_AbData). intros.\n      exploit sharedmem_init_exist; eauto 1; intros [labd' [HP HM]].\n      match_external_states_simpl.\n      eapply sharedmem_init_match; eauto.\n    Qed.\n\n  End SHAREDMEMINIT_SIM.\n\n  Section SHARED_MEM_TO_READY_SIM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_init}.\n    Context {re3: relate_impl_LAT}.\n    Context {re4: relate_impl_nps}.\n    Context {re5: relate_impl_pperm}.\n    Context {re6: relate_impl_ipt}.\n    Context {re7: relate_impl_ptpool}.\n    Context {re8: relate_impl_HP}.\n    Context {re9: relate_impl_smspool}.\n    Context {re10: relate_impl_AC}.\n\n    Lemma shared_mem_to_ready_exist:\n      forall s habd habd' labd pid1 pid2 vadr rest f,\n        shared_mem_to_ready_spec pid1 pid2 vadr habd = Some (habd', rest)\n        -> relate_AbData s f habd labd\n        -> exists labd', shared_mem_to_ready_spec pid1 pid2 vadr labd = Some (labd', rest)\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold shared_mem_to_ready_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_smspool_eq; eauto. intros.\n      revert H. subrewrite.\n      subdestruct;\n        eapply ptResv2_exist in Hdestruct7; eauto;\n        destruct Hdestruct7 as (labd' & -> & rel_labd');\n\tsubrewrite';\n        inv HQ; refine_split'; trivial.\n\n      rewrite (relate_impl_smspool_eq _ _ _ _ rel_labd').\n      apply relate_impl_smspool_update; assumption.\n    Qed.\n\n  End SHARED_MEM_TO_READY_SIM.\n\n  Section SHARED_MEM_TO_PENDING_SIM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re3: relate_impl_smspool}.\n\n    Lemma shared_mem_to_pending_exist:\n      forall s habd habd' labd pid1 pid2 vadr f,\n        shared_mem_to_pending_spec pid1 pid2 vadr habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', shared_mem_to_pending_spec pid1 pid2 vadr labd = Some labd'\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold shared_mem_to_pending_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_smspool_eq; eauto. intros.\n      revert H. subrewrite. subdestruct.\n      inv HQ; refine_split'; trivial.\n\n      apply relate_impl_smspool_update; assumption.\n    Qed.\n\n  End SHARED_MEM_TO_PENDING_SIM.\n\n  Section SHARED_MEM_TO_DEAD_SIM.\n\n    Context {re1: relate_impl_iflags}.\n    Context {re2: relate_impl_ipt}.\n    Context {re3: relate_impl_smspool}.\n\n    Lemma shared_mem_to_dead_exist:\n      forall s habd habd' labd pid1 pid2 vadr f,\n        shared_mem_to_dead_spec pid1 pid2 vadr habd = Some habd'\n        -> relate_AbData s f habd labd\n        -> exists labd', shared_mem_to_dead_spec pid1 pid2 vadr labd = Some labd'\n                         /\\ relate_AbData s f habd' labd'.\n    Proof.\n      unfold shared_mem_to_dead_spec; intros.\n      exploit relate_impl_iflags_eq; eauto. inversion 1.\n      exploit relate_impl_ipt_eq; eauto.\n      exploit relate_impl_smspool_eq; eauto. intros.\n      revert H. subrewrite. subdestruct.\n      inv HQ; refine_split'; trivial.\n\n      apply relate_impl_smspool_update; assumption.\n    Qed.\n\n  End SHARED_MEM_TO_DEAD_SIM.\n\nEnd OBJ_SIM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/objects/ObjShareMem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.23532834643947062}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef2.Spec.\nRequire Import TableDataOpsRef3.Specs.table_create3.\nRequire Import TableDataOpsRef3.LowSpecs.table_create3.\nRequire Import TableDataOpsRef3.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       table_create_spec\n       table_create2_spec\n    .\n\n  Lemma table_create3_spec_exists:\n    forall habd habd'  labd g_rd map_addr level g_rtt rtt_addr res\n           (Hspec: table_create3_spec g_rd map_addr level g_rtt rtt_addr habd = Some (habd', res))\n            (Hrel: relate_RData habd labd),\n    exists labd', table_create3_spec0 g_rd map_addr level g_rtt rtt_addr labd = Some (labd', res) /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque peq ptr_eq granule_fill_table.fill_table.\n    intros. duplicate Hrel. destruct D. clear hrepl lrepl. destruct g_rtt, g_rd.\n    unfold table_create3_spec, table_create3_spec0 in *.\n    unfold Assertion in *. rm_bind Hspec; rm_bind'. simpl in *.\n    unfold Assertion; rm_bind'; grewrite.\n    repeat simpl_hyp Hspec; extract_prop_dec; simpl_query_oracle; rm_bind'; grewrite.\n    - rewrite_oracle_rel rel_oracle C10.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold create_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec;\n        (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C10.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold create_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec;\n        (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C10.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold create_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec;\n        (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C10.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec; (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C10.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec; (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef3/RefProof/table_create3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2353283409884567}}
{"text": "Require Import Coq.Init.Tactics.\n\nDefinition id_True (x : True) : True := x.\n\nGoal True.  Time do 1000 simple refine (id_True _). exact I. Time Optimize Proof. Time Qed.\n(* Finished transaction in 0.034 secs (0.013u,0.02s) (successful)\n   Evars: 2001 -> 0\n   Finished transaction in 0. secs (0.u,0.s) (successful)\n   Finished transaction in 0.002 secs (0.002u,0.s) (successful) *)\nGoal True.  Time do 10000 simple refine (id_True _). exact I. Time Optimize Proof. Time Qed.\n(* Finished transaction in 0.284 secs (0.221u,0.062s) (successful)\n   Evars: 20001 -> 0\n   Finished transaction in 0.005 secs (0.005u,0.s) (successful)\n   Finished transaction in 0.015 secs (0.015u,0.s) (successful) *)\nGoal True.  Time do 100000 simple refine (id_True _). exact I. Time Optimize Proof. Time Qed.\n(* Finished transaction in 2.411 secs (2.324u,0.079s) (successful)\n   Evars: 200001 -> 0\n   Finished transaction in 0.056 secs (0.056u,0.s) (successful)\n   Finished transaction in 0.221 secs (0.197u,0.023s) (successful) *)\nGoal True.  Time do 1000000 simple refine (id_True _). exact I. Time Optimize Proof. Time Qed.\n(* Finished transaction in 27.145 secs (26.175u,0.84s) (successful)\n   Evars: 2000001 -> 0\n   Finished transaction in 0.669 secs (0.607u,0.059s) (successful)\n   Finished transaction in 5.337 secs (5.254u,0.066s) (successful) *)\n\n(* sh -c 'ulimit -s unlimited ; coqc bench/refine_id.v'  35.18s user 1.30s system 99% cpu 36.639 total *)", "meta": {"author": "andres-erbsen", "repo": "coq-experiments", "sha": "2018edd397a23c0429d316c96e86f9be7a9678f1", "save_path": "github-repos/coq/andres-erbsen-coq-experiments", "path": "github-repos/coq/andres-erbsen-coq-experiments/coq-experiments-2018edd397a23c0429d316c96e86f9be7a9678f1/experiments/bench/simple_refine_id.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23523315061190284}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n *)\n\n\nRequire Export per_props_nat.\nRequire Export per_props_uni.\n\n\nLemma union_all_types {o} :\n  forall lib (v : NVar),\n    @type o lib (mkc_tunion mkc_tnat v (mkcv_tuni [v] (mkc_var v))).\nProof.\n  introv.\n  apply tequality_tunion; dands; [apply type_tnat|].\n  introv en.\n  apply equality_in_tnat in en.\n  allrw @mkcv_tuni_substc; spcast.\n  allrw @mkc_var_substc.\n  apply tequality_mkc_tuni; auto.\nQed.\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"../util/\" \"../terms/\" \"../computation/\" \"../cequiv/\" \"../close/\")\n*** End:\n*)\n\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/per/union_all_types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23523314468797024}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  Ifnot, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export list.\nRequire Export per_props_function.\nRequire Export continuity_defs.\nRequire Export stronger_continuity_defs0.\nRequire Export cequiv_fresh.\n\n\nLemma hasvalue_like_apply {o} :\n  forall lib (t u : @NTerm o),\n    wf_term t\n    -> wf_term u\n    -> hasvalue_like lib (mk_apply t u)\n    -> ({v : NVar\n         & {b : NTerm\n         & reduces_to lib t (mk_lam v b)\n         # hasvalue_like lib (subst b v u)}}\n        [+] {s : nseq\n             & reduces_to lib t (mk_nseq s)\n             # hasvalue_like lib (mk_eapply (mk_nseq s) u) }\n        [+] {s : ntseq\n             & reduces_to lib t (mk_ntseq s)\n             # hasvalue_like lib (mk_eapply (sterm s) u) }\n        [+] {n : NTerm\n             & {e : NTerm\n             & computes_to_exception lib n t e }}).\nProof.\n  introv wt wu hv.\n  unfold hasvalue_like, reduces_to in hv; exrepnd.\n  revert dependent t.\n  induction k; introv wt comp.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    allunfold @isvalue_like; allsimpl; tcsp.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    csunf comp1; allsimpl.\n    destruct t as [v1|f1|op bs]; allsimpl; ginv.\n\n    { right; right; left.\n      exists f1; dands; eauto 3 with slow.\n      exists v; dands; auto.\n      exists k; auto. }\n\n    dopid op as [can|ncan|exc|abs] Case; allsimpl; ginv.\n\n    + Case \"Can\".\n      clear IHk.\n      apply compute_step_apply_success in comp1; repndors; exrepnd; subst; fold_terms; ginv.\n\n      { left.\n        exists v0 b; dands; eauto 3 with slow.\n        exists v; dands; auto.\n        exists k; auto. }\n\n      { right; left.\n        exists f; dands; eauto 3 with slow.\n        exists v; dands; auto.\n        exists k; auto. }\n\n    + remember (compute_step lib (oterm (NCan ncan) bs)) as cs.\n      symmetry in Heqcs; destruct cs; allsimpl; ginv; fold_terms.\n      applydup @compute_step_preserves_wf in Heqcs; auto.\n      apply IHk in comp0; auto; repndors; exrepnd.\n\n      * left.\n        exists v0 b; dands; auto.\n        eapply reduces_to_if_split2; eauto.\n\n      * right; left.\n        exists s; dands; auto.\n        eapply reduces_to_if_split2; eauto.\n\n      * right; right; left.\n        exists s; dands; auto.\n        eapply reduces_to_if_split2; eauto.\n\n      * right; right; right.\n        exists n0 e.\n        eapply reduces_to_if_split2; eauto.\n\n    + apply reduces_in_atmost_k_steps_if_isvalue_like in comp0; eauto 3 with slow; subst.\n      allapply @wf_exception_implies; exrepnd; subst; fold_terms.\n      right; right; right.\n      exists a t.\n      eapply reduces_to_symm.\n\n    + remember (compute_step lib (oterm (Abs abs) bs)) as cs.\n      symmetry in Heqcs; destruct cs; allsimpl; ginv; fold_terms.\n      applydup @compute_step_preserves_wf in Heqcs; auto.\n      apply IHk in comp0; auto; repndors; exrepnd.\n\n      * left.\n        exists v0 b; dands; auto.\n        eapply reduces_to_if_split2; eauto.\n\n      * right; left.\n        exists s; dands; auto.\n        eapply reduces_to_if_split2; eauto.\n\n      * right; right; left.\n        exists s; dands; auto.\n        eapply reduces_to_if_split2; eauto.\n\n      * right; right; right.\n        exists n0 e.\n        eapply reduces_to_if_split2; eauto.\nQed.\n\n(* !!MOVE *)\nLemma alpha_eq_mk_nseq {o} :\n  forall s (t : @NTerm o),\n    alpha_eq (mk_nseq s) t\n    -> t = mk_nseq s.\nProof.\n  introv aeq.\n  inversion aeq; allsimpl; cpx.\nQed.\n\n(* !!MOVE *)\nLemma hasvalue_like_apseq {o} :\n  forall lib s (t : @NTerm o),\n    wf_term t\n    -> hasvalue_like lib (mk_eapply (mk_nseq s) t)\n    -> {n : nat & computes_to_value lib t (mk_nat n) }\n       [+] raises_exception lib t.\nProof.\n  introv wt hv.\n  unfold hasvalue_like, reduces_to in hv; exrepnd.\n  revert dependent t.\n  induction k; introv wt comp.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    allunfold @isvalue_like; allsimpl; tcsp.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    csunf comp1; allsimpl.\n    destruct t as [v1|f1|op bs]; allsimpl; ginv;[].\n    dopid op as [can|ncan|exc|abs] Case; allsimpl; ginv.\n\n    + Case \"Can\".\n      clear IHk.\n      apply compute_step_eapply_success in comp1; exrepnd.\n      destruct l; try (complete (allsimpl; ginv)); ginv.\n      repndors; exrepnd; subst.\n\n      * apply compute_step_eapply2_success in comp1; repnd; GC.\n        repndors; exrepnd; subst; ginv.\n        allunfold @mk_nat; allunfold @mk_integer; ginv; fold_terms.\n        left; exists n; fold_terms.\n        apply computes_to_value_isvalue_refl; eauto 3 with slow.\n\n      * allsimpl; tcsp.\n\n      * allunfold @isnoncan_like; allsimpl; tcsp.\n\n    + remember (compute_step lib (oterm (NCan ncan) bs)) as cs.\n      symmetry in Heqcs; destruct cs; allsimpl; ginv; fold_terms.\n      applydup @compute_step_preserves_wf in Heqcs; auto.\n      dcwf xx; allsimpl; ginv; fold_terms.\n      apply IHk in comp0; auto; repndors; exrepnd.\n\n      * left.\n        exists n0; dands; auto.\n        allunfold @computes_to_value; repnd; dands; auto.\n        eapply reduces_to_if_split2; eauto.\n\n      * right.\n        allunfold @raises_exception; exrepnd.\n        exists a e.\n        eapply reduces_to_if_split2; eauto.\n\n    + dcwf h; allsimpl; ginv.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in comp0; eauto 3 with slow; subst.\n      right.\n      unfold raises_exception.\n      allapply @wf_exception_implies; exrepnd; subst; fold_terms.\n      exists a t.\n      eapply reduces_to_symm.\n\n    + dcwf h; allsimpl; ginv.\n      remember (compute_step lib (oterm (Abs abs) bs)) as cs.\n      symmetry in Heqcs; destruct cs; allsimpl; ginv; fold_terms.\n      applydup @compute_step_preserves_wf in Heqcs; auto.\n      apply IHk in comp0; auto; repndors; exrepnd.\n\n      * left.\n        exists n0; dands; auto.\n        allunfold @computes_to_value; repnd; dands; auto.\n        eapply reduces_to_if_split2; eauto.\n\n      * right.\n        allunfold @raises_exception; exrepnd.\n        exists a e.\n        eapply reduces_to_if_split2; eauto.\nQed.\n\nLemma approx_apply_fresh1 {o} :\n  forall lib v (t : @NTerm o) u,\n    isprog u\n    -> isprog_vars [v] t\n    -> approx\n         lib\n         (mk_fresh v (mk_apply t u))\n         (mk_apply (mk_fresh v t) u).\nProof.\n  introv ispu ispt.\n\n  pose proof (change_bvars_alpha_wspec [v] u) as hu.\n  destruct hu as [u' hu]; repnd.\n  allrw disjoint_singleton_l.\n  applydup @alpha_eq_preserves_isprog in hu as ispu'; auto.\n  eapply approx_alpha_rw_l_aux;\n    [apply implies_alpha_eq_mk_fresh;\n      apply implies_alpha_eq_mk_apply;\n      [apply alpha_eq_refl|apply alpha_eq_sym;exact hu]\n    |].\n  eapply approx_alpha_rw_r_aux;\n    [apply implies_alpha_eq_mk_apply;\n      [apply alpha_eq_refl|apply alpha_eq_sym;exact hu]\n    |].\n  clear dependent u.\n  rename ispu' into ispu.\n  rename u' into u.\n\n  pose proof (change_bvars_alpha_wspec [v] t) as ht.\n  destruct ht as [t' ht]; repnd.\n  allrw disjoint_singleton_l.\n  applydup (alphaeq_preserves_isprog_vars t t' [v]) in ht as ispt'; auto.\n  eapply approx_alpha_rw_l_aux;\n    [apply implies_alpha_eq_mk_fresh;\n      apply implies_alpha_eq_mk_apply;\n      [apply alpha_eq_sym;exact ht|apply alpha_eq_refl]\n    |].\n  eapply approx_alpha_rw_r_aux;\n    [apply implies_alpha_eq_mk_apply;\n      [apply implies_alpha_eq_mk_fresh;\n        apply alpha_eq_sym;exact ht\n      |apply alpha_eq_refl]\n    |].\n  clear dependent t.\n  rename ispt' into ispt.\n  rename t' into t.\n\n  apply approx_assume_hasvalue;\n    try (apply isprogram_apply);\n    try (apply isprogram_fresh);\n    try (apply isprog_vars_apply_implies);\n    eauto 3 with slow;[].\n\n  introv hv.\n  pose proof (fresh_atom o (get_utokens t ++ get_utokens u)) as fa.\n  destruct fa as [a fa].\n  allrw in_app_iff; allrw not_over_or; repnd.\n\n  pose proof (hasvalue_like_fresh_implies lib a v (mk_apply t u)) as h.\n  repeat (autodimp h hyp); simpl;\n  try (apply wf_apply); eauto 3 with slow;\n  allrw app_nil_r; allrw in_app_iff; tcsp.\n  rw @cl_subst_subst_aux in h; eauto 2 with slow.\n  unfold subst_aux in h; allsimpl; fold_terms.\n  rw (lsubst_aux_trivial_cl_term2 u) in h; eauto 3 with slow.\n\n  apply hasvalue_like_apply in h;\n    try (apply lsubst_aux_preserves_wf_term2);\n    eauto 3 with slow;[].\n\n  repndors; exrepnd.\n\n  - pose proof (reduces_to_fresh2 lib (mk_apply t u) (subst b v0 u) v a) as q.\n    repeat (autodimp q hyp); simpl;\n    try (apply wf_apply); eauto 3 with slow;\n    allrw app_nil_r; allrw in_app_iff; tcsp.\n    { unfsubst; simpl; fold_terms.\n      rw (lsubst_aux_trivial_cl_term2 u); eauto 3 with slow.\n      eapply reduces_to_if_split1;[apply reduces_to_prinarg; exact h0|].\n      csunf; simpl; auto. }\n    exrepnd.\n\n    pose proof (reduces_to_fresh2 lib t (mk_lam v0 b) v a) as r.\n    repeat (autodimp r hyp); simpl;\n    try (apply wf_apply); eauto 3 with slow;\n    allrw app_nil_r; allrw in_app_iff; tcsp.\n    { unfsubst; simpl; fold_terms. }\n    exrepnd.\n\n    eapply approx_trans;\n      [apply reduces_to_implies_approx2;\n        [apply isprogram_fresh;\n          apply isprog_vars_apply_implies;\n          eauto 3 with slow\n        |exact q1]\n      |].\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_apply;\n           try (apply isprogram_fresh);\n           eauto 3 with slow\n         |apply reduces_to_prinarg;exact r1]\n      ].\n    fold_terms.\n\n    eapply approx_alpha_rw_l_aux;\n      [apply implies_alpha_eq_mk_fresh;\n        apply alpha_eq_sym;exact q0\n      |].\n\n    eapply approx_alpha_rw_r_aux;\n      [apply alpha_eq_sym;\n        apply implies_alpha_eq_mk_apply;\n        [apply implies_alpha_eq_mk_fresh;exact r0\n        |apply alpha_eq_refl]\n      |].\n\n    pose proof (unfold_subst_utokens [(a,mk_var v)] (subst b v0 u)) as unfa.\n    exrepnd.\n    rw unfa0.\n\n    pose proof (unfold_subst_utokens [(a,mk_var v)] (mk_lam v0 b)) as unfb.\n    exrepnd.\n    rw unfb0.\n    apply alpha_eq_mk_lam in unfb1; exrepnd; subst.\n\n    allsimpl; fold_terms.\n    allrw app_nil_r.\n    allrw disjoint_singleton_r; allsimpl.\n    allrw in_app_iff; allrw not_over_or; repnd.\n\n    rw <- @cl_lsubst_lsubst_aux in h0; eauto 2 with slow.\n    applydup @reduces_to_preserves_isprog in h0;\n      [|apply isprog_eq;\n         apply isprogram_lsubst_if_isprog_sub;\n         simpl; eauto 3 with slow;\n         apply isprog_vars_eq in ispt;\n         repnd; allrw subvars_eq;auto];[].\n\n    apply isprog_lam_iff in h2.\n    applydup @alpha_eq_bterm_preserves_isprog_vars in unfb1;auto.\n\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_apply;\n           try (apply isprogram_fresh);\n           try (apply isprog_vars_lam);\n           try (apply implies_isprog_vars_subst_utokens_aux);\n           try (apply implies_isprog_vars_utok_sub_cons);\n           eauto 3 with slow\n         |apply reduces_to_prinarg;\n           apply reduces_to_if_step;\n           csunf; simpl;auto\n         ]\n      ];[]; fold_terms.\n\n    unfold maybe_new_var; rw memvar_singleton; boolvar; tcsp;[].\n\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_apply;\n           try (apply isprogram_lam);\n           try (apply isprog_vars_fresh_implies);\n           try (apply implies_isprog_vars_subst_utokens_aux);\n           try (apply implies_isprog_vars_utok_sub_cons);\n           eauto 3 with slow\n         |apply reduces_to_if_step;csunf;simpl;auto]\n      ];[].\n    unfold apply_bterm; simpl.\n\n    rw @cl_lsubst_lsubst_aux; eauto 3 with slow;[].\n    simpl; rw memvar_singleton; boolvar; tcsp;[].\n    fold_terms.\n\n    assert (isprogram t') as ispt'.\n    { apply alphaeq_preserves_program in unfa1; apply unfa1.\n      apply isprogram_subst_if_bt; eauto 3 with slow. }\n    apply isprogram_eq in ispt'.\n\n    apply alpha_implies_approx3;\n      try (apply isprogram_fresh);\n      try (apply implies_isprog_vars_subst_utokens_aux);\n      try (apply implies_isprog_vars_utok_sub_cons);\n      eauto 3 with slow.\n    apply implies_alpha_eq_mk_fresh.\n\n    rw @lsubst_aux_subst_utokens_aux_disj;\n      try (complete (unfold get_utokens_sub; simpl; allrw app_nil_r; allrw disjoint_singleton_r; auto));\n      try (complete (unfold free_vars_utok_sub; simpl; apply disjoint_singleton_l; simpl; tcsp));\n      [].\n\n    pose proof (lsubst_alpha_congr4 [v0] [v'] b b' [(v0,u)] [(v',u)]) as aeq.\n    allsimpl.\n    repeat (autodimp aeq hyp); eauto 3 with slow;[].\n    rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow;[].\n    allrw @fold_subst.\n\n    assert (alpha_eq t' (subst b' v' u)) as aeq' by eauto 3 with slow.\n\n    apply alpha_eq_subst_utokens_aux; simpl; allrw disjoint_singleton_l;\n    eauto 3 with slow.\n    unfsubst; intro i.\n    apply subset_bound_vars_lsubst_aux in i; allsimpl; allrw app_nil_r.\n    allrw in_app_iff; sp.\n\n  - pose proof (reduces_to_fresh2 lib (mk_apply t u) (mk_eapply (mk_nseq s) u) v a) as q.\n    repeat (autodimp q hyp); simpl;\n    try (apply wf_apply); eauto 3 with slow;\n    allrw app_nil_r; allrw in_app_iff; tcsp.\n    { unfsubst; simpl; fold_terms.\n      rw (lsubst_aux_trivial_cl_term2 u); eauto 3 with slow.\n      eapply reduces_to_if_split1;[apply reduces_to_prinarg; exact h1|].\n      csunf; simpl; auto. }\n    exrepnd.\n\n    unfold subst_utokens in q0; allsimpl; allrw app_nil_r.\n    boolvar; allrw disjoint_singleton_r; tcsp;[].\n    fold_terms.\n    rw @trivial_subst_utokens_aux in q0; simpl; allrw disjoint_singleton_r; auto.\n\n    pose proof (reduces_to_fresh2 lib t (mk_nseq s) v a) as r.\n    repeat (autodimp r hyp); simpl;\n    try (apply wf_apply); eauto 3 with slow;\n    allrw app_nil_r; allrw in_app_iff; tcsp.\n    { unfsubst; simpl; fold_terms. }\n    exrepnd.\n\n    unfold subst_utokens in r0; allsimpl; fold_terms.\n    apply alpha_eq_sym in r0.\n    apply alpha_eq_mk_nseq in r0; subst.\n\n    assert (reduces_to lib (mk_fresh v t) (mk_nseq s)) as r.\n    { eapply reduces_to_if_split1;[exact r1|].\n      csunf; simpl; auto. }\n    clear r1.\n\n    eapply approx_trans;\n      [apply reduces_to_implies_approx2;\n        [apply isprogram_fresh;\n          apply isprog_vars_apply_implies;\n          eauto 3 with slow\n        |exact q1]\n      |].\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_apply;\n           try (apply isprogram_fresh);\n           eauto 3 with slow\n         |apply reduces_to_prinarg;exact r]\n      ].\n    fold_terms.\n\n    eapply approx_alpha_rw_l_aux;\n      [apply implies_alpha_eq_mk_fresh;\n        apply alpha_eq_sym;exact q0\n      |].\n\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_apply;\n           try (apply isprogram_mk_nseq);\n           eauto 3 with slow\n         |apply reduces_to_if_step;\n           csunf;simpl;reflexivity]\n      ].\n\n    eapply cequiv_le_approx.\n    apply cequiv_shadowed_fresh.\n    apply isprogram_eapply; eauto 3 with slow.\n\n  - pose proof (reduces_to_fresh2 lib (mk_apply t u) (mk_eapply (sterm s) u) v a) as q.\n    repeat (autodimp q hyp); simpl;\n    try (apply wf_apply); eauto 3 with slow;\n    allrw app_nil_r; allrw in_app_iff; tcsp.\n    { unfsubst; simpl; fold_terms.\n      rw (lsubst_aux_trivial_cl_term2 u); eauto 3 with slow.\n      eapply reduces_to_if_split1;[apply reduces_to_prinarg; exact h1|].\n      csunf; simpl; auto. }\n    exrepnd.\n\n    unfold subst_utokens in q0; allsimpl; allrw app_nil_r.\n    boolvar; allrw disjoint_singleton_r; tcsp;[].\n    fold_terms.\n    rw @trivial_subst_utokens_aux in q0; simpl; allrw disjoint_singleton_r; auto.\n\n    pose proof (reduces_to_fresh2 lib t (mk_ntseq s) v a) as r.\n    repeat (autodimp r hyp); simpl;\n    try (apply wf_apply); eauto 3 with slow;\n    allrw app_nil_r; allrw in_app_iff; tcsp.\n    { unfsubst; simpl; fold_terms. }\n    exrepnd.\n\n    unfold subst_utokens in r0; allsimpl; fold_terms.\n    apply alpha_eq_sym in r0.\n    apply alpha_eq_sterm in r0; exrepnd; subst.\n\n    assert (reduces_to lib (mk_fresh v t) (sterm g)) as r.\n    { eapply reduces_to_if_split1;[exact r1|].\n      csunf; simpl; auto. }\n    clear r1.\n\n    eapply approx_trans;\n      [apply reduces_to_implies_approx2;\n        [apply isprogram_fresh;\n          apply isprog_vars_apply_implies;\n          eauto 3 with slow\n        |exact q1]\n      |].\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_apply;\n           try (apply isprogram_fresh);\n           eauto 3 with slow\n         |apply reduces_to_prinarg;exact r]\n      ].\n    fold_terms.\n\n    eapply approx_alpha_rw_l_aux;\n      [apply implies_alpha_eq_mk_fresh;\n        apply alpha_eq_sym;exact q0\n      |].\n\n    applydup @reduces_to_preserves_program in r;\n      try (apply isprogram_fresh; auto);[].\n\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_apply;eauto 3 with slow\n         |apply reduces_to_if_step; csunf;simpl;reflexivity]\n      ].\n\n    eapply cequiv_le_approx.\n    eapply cequiv_rw_r_eauto;\n      [apply implies_alpha_eq_mk_eapply;\n        [constructor;exact r2|apply alpha_eq_refl]\n      |].\n    apply cequiv_shadowed_fresh.\n    apply isprogram_eapply; eauto 2 with slow.\n    eapply alpha_prog_eauto;[|exact r0].\n    apply alpha_eq_sym; auto.\n\n  - pose proof (reduces_to_fresh2 lib (mk_apply t u) (mk_exception n e) v a) as q.\n    repeat (autodimp q hyp); simpl;\n    try (apply wf_apply); eauto 3 with slow;\n    allrw app_nil_r; allrw in_app_iff; tcsp.\n    { unfsubst; simpl; fold_terms.\n      rw (lsubst_aux_trivial_cl_term2 u); eauto 3 with slow.\n      eapply reduces_to_if_split1;[apply reduces_to_prinarg; exact h1|].\n      csunf; simpl; auto. }\n    exrepnd.\n\n    pose proof (reduces_to_fresh2 lib t (mk_exception n e) v a) as r.\n    repeat (autodimp r hyp); simpl;\n    try (apply wf_apply); eauto 3 with slow;\n    allrw app_nil_r; allrw in_app_iff; tcsp.\n    { unfsubst; simpl; fold_terms. }\n    exrepnd.\n\n    eapply approx_trans;\n      [apply reduces_to_implies_approx2;\n        [apply isprogram_fresh;\n          apply isprog_vars_apply_implies;\n          eauto 3 with slow\n        |exact q1]\n      |].\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_apply;\n           try (apply isprogram_fresh);\n           eauto 3 with slow\n         |apply reduces_to_prinarg;exact r1]\n      ].\n    fold_terms.\n\n    eapply approx_alpha_rw_l_aux;\n      [apply implies_alpha_eq_mk_fresh;\n        apply alpha_eq_sym;exact q0\n      |].\n\n    eapply approx_alpha_rw_r_aux;\n      [apply alpha_eq_sym;\n        apply implies_alpha_eq_mk_apply;\n        [apply implies_alpha_eq_mk_fresh;exact r0\n        |apply alpha_eq_refl]\n      |].\n\n    pose proof (unfold_subst_utokens [(a,mk_var v)] (mk_exception n e)) as unf.\n    exrepnd.\n    rw unf0.\n    apply alpha_eq_exception in unf1; exrepnd; subst.\n\n    allsimpl; fold_terms.\n    allrw app_nil_r.\n    allrw disjoint_singleton_r; allsimpl.\n    allrw in_app_iff; allrw not_over_or; repnd.\n\n    rw <- @cl_lsubst_lsubst_aux in h1; eauto 2 with slow.\n    applydup @reduces_to_preserves_isprog in h1;\n      [|apply isprog_eq;\n         apply isprogram_lsubst_if_isprog_sub;\n         simpl; eauto 3 with slow;\n         apply isprog_vars_eq in ispt;\n         repnd; allrw subvars_eq;auto];[].\n\n    apply isprog_exception_iff in h0; repnd.\n    applydup @alpha_eq_preserves_isprog in unf1; auto.\n    applydup @alpha_eq_preserves_isprog in unf4; auto.\n\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_apply;\n           try (apply isprogram_fresh);\n           try (apply isprog_vars_exception);dands;\n           try (apply implies_isprog_vars_subst_utokens_aux);\n           try (apply implies_isprog_vars_utok_sub_cons);\n           eauto 3 with slow\n         |eapply reduces_to_if_split2;\n           [csunf;simpl;auto|];fold_terms;\n           eapply reduces_to_if_step;\n           csunf;simpl;auto\n         ]\n      ];[]; fold_terms.\n\n    unfold maybe_new_var; simpl.\n\n    eapply approx_trans;\n      [apply reduces_to_implies_approx2;\n        [apply isprogram_fresh;\n          try (apply isprog_vars_exception);dands;\n          try (apply implies_isprog_vars_subst_utokens_aux);\n          try (apply implies_isprog_vars_utok_sub_cons);\n          eauto 3 with slow\n        |apply reduces_to_if_step;csunf;simpl;auto]\n      |];[];fold_terms.\n\n    unfold maybe_new_var; simpl.\n    apply approx_refl.\n    apply isprogram_exception;\n      apply isprogram_fresh;\n      try (apply implies_isprog_vars_subst_utokens_aux);\n      try (apply implies_isprog_vars_utok_sub_cons);\n      eauto 3 with slow.\nQed.\n\nLemma approx_apply_fresh2 {o} :\n  forall lib v (t : @NTerm o) u,\n    isprog u\n    -> isprog_vars [v] t\n    -> approx\n         lib\n         (mk_apply (mk_fresh v t) u)\n         (mk_fresh v (mk_apply t u)).\nProof.\n  introv ispu ispt.\n\n  pose proof (change_bvars_alpha_wspec [v] u) as hu.\n  destruct hu as [u' hu]; repnd.\n  allrw disjoint_singleton_l.\n  applydup @alpha_eq_preserves_isprog in hu as ispu'; auto.\n  eapply approx_alpha_rw_r_aux;\n    [apply implies_alpha_eq_mk_fresh;\n      apply implies_alpha_eq_mk_apply;\n      [apply alpha_eq_refl|apply alpha_eq_sym;exact hu]\n    |].\n  eapply approx_alpha_rw_l_aux;\n    [apply implies_alpha_eq_mk_apply;\n      [apply alpha_eq_refl|apply alpha_eq_sym;exact hu]\n    |].\n  clear dependent u.\n  rename ispu' into ispu.\n  rename u' into u.\n\n  pose proof (change_bvars_alpha_wspec [v] t) as ht.\n  destruct ht as [t' ht]; repnd.\n  allrw disjoint_singleton_l.\n  applydup (alphaeq_preserves_isprog_vars t t' [v]) in ht as ispt'; auto.\n  eapply approx_alpha_rw_r_aux;\n    [apply implies_alpha_eq_mk_fresh;\n      apply implies_alpha_eq_mk_apply;\n      [apply alpha_eq_sym;exact ht|apply alpha_eq_refl]\n    |].\n  eapply approx_alpha_rw_l_aux;\n    [apply implies_alpha_eq_mk_apply;\n      [apply implies_alpha_eq_mk_fresh;\n        apply alpha_eq_sym;exact ht\n      |apply alpha_eq_refl]\n    |].\n  clear dependent t.\n  rename ispt' into ispt.\n  rename t' into t.\n\n  apply approx_assume_hasvalue;\n    try (apply isprogram_apply);\n    try (apply isprogram_fresh);\n    try (apply isprog_vars_apply_implies);\n    eauto 3 with slow;[].\n\n  introv hv.\n  pose proof (fresh_atom o (get_utokens t ++ get_utokens u)) as fa.\n  destruct fa as [a fa].\n  allrw in_app_iff; allrw not_over_or; repnd.\n\n  apply hasvalue_like_apply in hv;\n    try (apply wf_fresh);\n    eauto 3 with slow.\n\n  repndors; exrepnd.\n\n  - eapply approx_trans;\n      [apply reduces_to_implies_approx2;\n        [apply isprogram_apply;\n          try (apply isprogram_fresh);\n          eauto 3 with slow\n        |eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact hv0|];\n         apply reduces_to_if_step;csunf;simpl;auto]\n      |].\n    unfold apply_bterm; simpl; allrw @fold_subst.\n\n    pose proof (fresh_reduces_to_implies lib v t (mk_lam v0 b) a) as h.\n    repeat (autodimp h hyp); unfold isvalue_like; simpl; tcsp; eauto 3 with slow;[].\n    exrepnd.\n\n    pose proof (unfold_subst_utokens [(a,mk_var v)] u0) as unf.\n    exrepnd.\n    rw unf0 in h0.\n    allsimpl; allrw disjoint_singleton_r.\n\n    assert {v1 : NVar & {t1 : NTerm & t' = mk_lam v1 t1}} as e.\n    { apply alpha_eq_mk_lam in h0; exrepnd.\n      destruct t' as [v1|f1|op1 bs1]; ginv.\n      dopid op1 as [can|ncan|exc|abs] Case; ginv.\n      destruct can; ginv.\n      - allsimpl.\n        repeat (destruct bs1; allsimpl; ginv).\n        destruct b0 as [l1 t1].\n        repeat (destruct l1; allsimpl; ginv).\n        fold_terms; ginv.\n        eexists; eexists; eauto.\n      - allsimpl.\n        unfold subst_utok in h2; allsimpl; boolvar; ginv.\n    }\n\n    exrepnd; subst; allsimpl; fold_terms.\n    allrw app_nil_r; allrw not_over_or; repnd.\n    unfold maybe_new_var in h0; allrw memvar_singleton; boolvar; tcsp;[].\n    apply alpha_eq_sym in unf1.\n    apply alpha_eq_mk_lam in unf1; exrepnd; subst.\n    apply alpha_eq_mk_lam in h0; exrepnd; subst; ginv.\n\n    pose proof (reduces_to_fresh2 lib (mk_apply t u) (subst b' v' u) v a) as q.\n    repeat (autodimp q hyp); simpl;\n    try (apply wf_apply); eauto 3 with slow;\n    allrw app_nil_r; allrw in_app_iff; tcsp.\n    { unfsubst; simpl; fold_terms.\n      rw (lsubst_aux_trivial_cl_term2 u); eauto 3 with slow.\n      rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n      allrw @fold_subst.\n      eapply reduces_to_if_split1;[apply reduces_to_prinarg; exact h1|].\n      csunf; simpl; auto. }\n    exrepnd.\n\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_fresh;\n           apply isprog_vars_apply;\n           dands;eauto 3 with slow\n         |exact q1]\n      ].\n\n    eapply approx_alpha_rw_r_aux;\n      [apply alpha_eq_sym;\n        apply implies_alpha_eq_mk_fresh;\n        exact q0\n      |].\n\n    pose proof (lsubst_alpha_congr4 [v'0] [v'] t1 b' [(v'0,u)] [(v',u)]) as aeq.\n    allsimpl.\n    repeat (autodimp aeq hyp); eauto 3 with slow;[].\n    allrw @fold_subst.\n\n    eapply approx_alpha_rw_r_aux;\n      [apply implies_alpha_eq_mk_fresh;\n        apply alpha_eq_subst_utokens_same;\n        exact aeq\n      |].\n\n    pose proof (lsubst_alpha_congr4\n                  [v0] [v'0] b\n                  (mk_fresh v (subst_utokens_aux t1 [(a,mk_var v)]))\n                  [(v0,u)] [(v'0,u)]) as aeq'.\n    allsimpl.\n    repeat (autodimp aeq' hyp); eauto 3 with slow;[].\n    allrw @fold_subst.\n\n    eapply approx_alpha_rw_l_aux;\n      [apply alpha_eq_sym;exact aeq'|].\n\n    applydup @reduces_to_preserves_isprog in h1 as ispb';\n      try (apply subst_preserves_isprog);\n      eauto 3 with slow;[].\n    apply isprog_lam_iff in ispb'.\n    apply alpha_eq_bterm_sym in unf1.\n    applydup @alpha_eq_bterm_preserves_isprog_vars in unf1; auto;[].\n\n    apply alpha_implies_approx3;\n      try (apply isprogram_subst_if_bt);\n      try (apply isprog_vars_iff_isprogram_bt);\n      try (apply isprog_vars_fresh_implies);\n      try (apply implies_isprog_vars_subst_utokens_aux);\n      eauto 3 with slow;[].\n\n    rw @cl_subst_subst_aux; eauto 3 with slow;[].\n    unfold subst_aux; simpl; rw memvar_singleton; boolvar; tcsp;[].\n    fold_terms.\n    apply implies_alpha_eq_mk_fresh.\n\n    rw @lsubst_aux_subst_utokens_aux_disj;\n      unfold get_utokens_sub;\n      allsimpl; allrw app_nil_r; allrw disjoint_singleton_r;\n      allsimpl; tcsp;\n      eauto 3 with slow;[].\n\n    rw @cl_subst_subst_aux; eauto 3 with slow;[].\n    unfold subst_aux.\n\n    unfold subst_utokens; simpl; boolvar; allrw disjoint_singleton_r; eauto 3 with slow.\n    destruct n; intro i.\n    apply subset_bound_vars_lsubst_aux in i; allsimpl; allrw app_nil_r.\n    allrw in_app_iff; sp.\n\n  - eapply approx_trans;\n      [apply reduces_to_implies_approx2;\n        [apply isprogram_apply;\n          try (apply isprogram_fresh);\n          eauto 3 with slow\n        |eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact hv1|];\n         apply reduces_to_if_step;csunf;simpl;auto]\n      |].\n    unfold apply_bterm; simpl; allrw @fold_subst.\n\n    pose proof (fresh_reduces_to_implies lib v t (mk_nseq s) a) as h.\n    repeat (autodimp h hyp); unfold isvalue_like; simpl; tcsp; eauto 3 with slow;[].\n    exrepnd.\n\n    pose proof (unfold_subst_utokens [(a,mk_var v)] u0) as unf.\n    exrepnd.\n    rw unf0 in h0.\n    allsimpl; allrw disjoint_singleton_r.\n    destruct t' as [x|f|op bs]; allsimpl; GC; try (complete (inversion h0));[].\n    dopid op as [can|ncan|exc|abs] Case; try (complete (inversion h0));[].\n    destruct can; allsimpl; try (complete (inversion h0));\n    [|unfold subst_utok in h0; allsimpl; boolvar; allsimpl; inversion h0].\n    apply alpha_eq_mk_nseq in h0.\n    destruct bs; allsimpl; ginv; fold_terms; ginv; GC.\n    apply alpha_eq_sym in unf1.\n    apply alpha_eq_mk_nseq in unf1; subst.\n    clear unf0.\n\n    pose proof (reduces_to_fresh2 lib (mk_apply t u) (mk_eapply (mk_nseq s) u) v a) as q.\n    repeat (autodimp q hyp); simpl;\n    try (apply wf_apply); eauto 3 with slow;\n    allrw app_nil_r; allrw in_app_iff; tcsp.\n    { unfsubst; simpl; fold_terms.\n      rw (lsubst_aux_trivial_cl_term2 u); eauto 3 with slow.\n      rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n      allrw @fold_subst.\n      eapply reduces_to_if_split1;[apply reduces_to_prinarg; exact h1|].\n      csunf; simpl; auto. }\n    exrepnd.\n\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_fresh;\n           apply isprog_vars_apply;\n           dands;eauto 3 with slow\n         |exact q1]\n      ].\n\n    eapply approx_alpha_rw_r_aux;\n      [apply alpha_eq_sym;\n        apply implies_alpha_eq_mk_fresh;\n        exact q0\n      |].\n    unfold subst_utokens; simpl; allrw app_nil_r.\n    boolvar; allrw disjoint_singleton_r; tcsp;[].\n    fold_terms.\n    rw @trivial_subst_utokens_aux; simpl; allrw disjoint_singleton_r; auto.\n\n    eapply cequiv_le_approx.\n    apply cequiv_sym.\n    apply cequiv_shadowed_fresh.\n    apply isprogram_eapply; eauto 3 with slow.\n\n  - eapply approx_trans;\n      [apply reduces_to_implies_approx2;\n        [apply isprogram_apply;\n          try (apply isprogram_fresh);\n          eauto 3 with slow\n        |eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact hv1|];\n         apply reduces_to_if_step;csunf;simpl;auto]\n      |].\n    unfold apply_bterm; simpl; allrw @fold_subst.\n\n    pose proof (fresh_reduces_to_implies lib v t (sterm s) a) as h.\n    repeat (autodimp h hyp); unfold isvalue_like; simpl; tcsp; eauto 3 with slow;[].\n    exrepnd.\n\n    pose proof (unfold_subst_utokens [(a,mk_var v)] u0) as unf.\n    exrepnd.\n    rw unf0 in h0.\n    allsimpl; allrw disjoint_singleton_r.\n\n    destruct t' as [x|f|op bs]; allsimpl; GC; try (complete (inversion h0));\n    [|destruct op; allsimpl; try (complete (inversion h0));[];\n      destruct c; allsimpl; try (complete (inversion h0));[];\n      allunfold @subst_utok; allsimpl; boolvar; allsimpl; try (complete (inversion h0))].\n\n    inversion h0 as [|? ? aeq|]; subst; clear h0.\n    apply alpha_eq_sym in unf1.\n    apply alpha_eq_sterm in unf1; exrepnd; subst.\n    unfold subst_utokens in unf0; allsimpl; ginv.\n    clear unf2.\n\n    pose proof (reduces_to_fresh2 lib (mk_apply t u) (mk_eapply (sterm f) u) v a) as q.\n    repeat (autodimp q hyp); simpl;\n    try (apply wf_apply); eauto 3 with slow;\n    allrw app_nil_r; allrw in_app_iff; tcsp.\n    { unfsubst; simpl; fold_terms.\n      rw (lsubst_aux_trivial_cl_term2 u); eauto 3 with slow.\n      rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n      allrw @fold_subst.\n      eapply reduces_to_if_split1;[apply reduces_to_prinarg; exact h1|].\n      csunf; simpl; auto. }\n    exrepnd.\n\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_fresh;\n           apply isprog_vars_apply;\n           dands;eauto 3 with slow\n         |exact q1]\n      ].\n\n    eapply approx_alpha_rw_r_aux;\n      [apply alpha_eq_sym;\n        apply implies_alpha_eq_mk_fresh;\n        exact q0\n      |].\n    unfold subst_utokens; simpl; allrw app_nil_r.\n    boolvar; allrw disjoint_singleton_r; tcsp;[].\n    fold_terms.\n    rw @trivial_subst_utokens_aux; simpl; allrw disjoint_singleton_r; auto.\n\n    applydup @reduces_to_preserves_program in hv1;\n      try (apply isprogram_fresh; auto);[].\n\n    eapply cequiv_le_approx.\n    apply cequiv_sym.\n    eapply cequiv_rw_r_eauto;\n      [apply implies_alpha_eq_mk_eapply;\n        [apply alpha_eq_sym;constructor;apply aeq|apply alpha_eq_refl]\n      |].\n    apply cequiv_shadowed_fresh.\n    apply isprogram_eapply; eauto 2 with slow.\n    eapply alpha_prog_eauto;[|exact hv2]; auto.\n\n  - eapply approx_trans;\n      [apply reduces_to_implies_approx2;\n        [apply isprogram_apply;\n          try (apply isprogram_fresh);\n          eauto 3 with slow\n        |eapply reduces_to_trans;\n          [apply reduces_to_prinarg;exact hv1|];\n         apply reduces_to_if_step;csunf;simpl;auto]\n      |].\n    fold_terms.\n\n    pose proof (fresh_reduces_to_implies lib v t (mk_exception n e) a) as h.\n    repeat (autodimp h hyp); unfold isvalue_like; simpl; tcsp; eauto 3 with slow;[].\n    exrepnd.\n\n    pose proof (unfold_subst_utokens [(a,mk_var v)] u0) as unf.\n    exrepnd.\n    rw unf0 in h0; clear unf0.\n    allsimpl; allrw disjoint_singleton_r.\n\n    assert {n1 : NTerm & {e1 : NTerm & t' = mk_exception n1 e1}} as xx.\n    { apply alpha_eq_exception in h0; exrepnd.\n      destruct t' as [v1|f1|op1 bs1]; ginv.\n      dopid op1 as [can|ncan|exc|abs] Case; ginv.\n      - destruct can; ginv.\n        allsimpl.\n        unfold subst_utok in h2; allsimpl; boolvar; ginv.\n      - allsimpl.\n        repeat (destruct bs1; allsimpl; ginv).\n        destruct b as [l1 t1].\n        destruct b0 as [l2 t2].\n        repeat (destruct l1; allsimpl; ginv).\n        repeat (destruct l2; allsimpl; ginv).\n        fold_terms; ginv.\n        eexists; eexists; eauto. }\n\n    exrepnd; subst; allsimpl; fold_terms.\n    allrw app_nil_r; allrw not_over_or; repnd.\n    unfold maybe_new_var in h0; allrw memvar_singleton; boolvar; tcsp; GC;[].\n    apply alpha_eq_sym in unf1.\n    apply alpha_eq_exception in unf1; exrepnd; subst.\n    apply alpha_eq_exception in h0; exrepnd; subst; ginv.\n\n    pose proof (reduces_to_fresh2 lib (mk_apply t u) (mk_exception a' e') v a) as q.\n    repeat (autodimp q hyp); simpl;\n    try (apply wf_apply); eauto 3 with slow;\n    allrw app_nil_r; allrw in_app_iff; tcsp.\n    { unfsubst; simpl; fold_terms.\n      rw (lsubst_aux_trivial_cl_term2 u); eauto 3 with slow.\n      rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n      allrw @fold_subst.\n      eapply reduces_to_if_split1;[apply reduces_to_prinarg; exact h1|].\n      csunf; simpl; auto. }\n    exrepnd.\n    allrw not_over_or; repnd.\n\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_fresh;\n           apply isprog_vars_apply;\n           dands;eauto 3 with slow\n         |exact q1]\n      ].\n\n    eapply approx_alpha_rw_r_aux;\n      [apply alpha_eq_sym;\n        apply implies_alpha_eq_mk_fresh;\n        exact q0\n      |].\n\n    eapply approx_alpha_rw_r_aux;\n      [apply implies_alpha_eq_mk_fresh;\n        apply alpha_eq_subst_utokens_same;\n        apply implies_alphaeq_exception;\n        [exact unf3|exact unf1]\n      |].\n\n    unfold subst_utokens; simpl; allrw app_nil_r; fold_terms.\n    boolvar; allrw disjoint_singleton_r; allrw in_app_iff;\n    allrw not_over_or; try (complete (destruct n0; sp));[].\n    repnd; GC.\n\n    applydup @reduces_to_preserves_isprog in h1 as ispb';\n      try (apply subst_preserves_isprog);\n      eauto 3 with slow;[].\n    apply isprog_exception_iff in ispb'; repnd.\n    apply alpha_eq_sym in unf1.\n    apply alpha_eq_sym in unf3.\n    applydup @alpha_eq_preserves_isprog in unf1;auto.\n    applydup @alpha_eq_preserves_isprog in unf3;auto.\n\n    eapply approx_trans;\n      [|apply reduces_to_implies_approx1;\n         [apply isprogram_fresh;\n           apply isprog_vars_exception_implies;\n           try (apply implies_isprog_vars_subst_utokens_aux);\n           eauto 3 with slow\n         |apply reduces_to_if_step;csunf;simpl;auto]\n      ].\n    fold_terms.\n    unfold maybe_new_var; simpl.\n\n    apply alpha_eq_sym in h0.\n    apply alpha_eq_sym in h3.\n    applydup @alpha_eq_preserves_isprog in h0;auto;\n    try(apply isprog_fresh_implies;\n        try (apply implies_isprog_vars_subst_utokens_aux);\n        eauto 3 with slow).\n    applydup @alpha_eq_preserves_isprog in h3;auto;\n    try(apply isprog_fresh_implies;\n        try (apply implies_isprog_vars_subst_utokens_aux);\n        eauto 3 with slow).\n\n    apply alpha_implies_approx3;\n      try (apply isprogram_exception);\n      eauto 3 with slow.\n\n    apply implies_alphaeq_exception; eauto 3 with slow.\nQed.\n\nLemma cequiv_apply_fresh {o} :\n  forall lib v (t : @NTerm o) a,\n    isprog a\n    -> isprog_vars [v] t\n    -> cequiv\n         lib\n         (mk_fresh v (mk_apply t a))\n         (mk_apply (mk_fresh v t) a).\nProof.\n  introv ispa ispt.\n  split.\n  - apply approx_apply_fresh1; auto.\n  - apply approx_apply_fresh2; auto.\nQed.\n\nLemma cequivc_apply_fresh {o} :\n  forall lib v (t : @CVTerm o [v]) a,\n    cequivc\n      lib\n      (mkc_fresh v (mkcv_apply [v] t (mk_cv [v] a)))\n      (mkc_apply (mkc_fresh v t) a).\nProof.\n  introv.\n  destruct_cterms.\n  unfold cequivc; simpl.\n  apply cequiv_apply_fresh;auto.\nQed.\n\nLemma fresh_in_function {o} :\n  forall lib v (t1 t2 : @CVTerm o [v]) A x B,\n    type lib A\n    -> (forall a1 a2,\n          equality lib a1 a2 A\n          -> tequality lib (substc a1 x B) (substc a2 x B))\n    -> (forall a1 a2,\n          equality lib a1 a2 A\n          -> equality\n               lib\n               (mkc_fresh v (mkcv_apply [v] t1 (mk_cv [v] a1)))\n               (mkc_fresh v (mkcv_apply [v] t2 (mk_cv [v] a2)))\n               (substc a1 x B))\n    -> equality lib (mkc_fresh v t1) (mkc_fresh v t2) (mkc_function A x B).\nProof.\n  introv tA tB imp.\n  apply equality_in_function.\n  dands; auto.\n  introv ea.\n  applydup imp in ea.\n\n  eapply equality_respects_cequivc_left in ea0;\n    [|apply cequivc_apply_fresh].\n\n  eapply equality_respects_cequivc_right in ea0;\n    [|apply cequivc_apply_fresh].\n\n  auto.\nQed.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/continuity/stronger_continuity_props1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2352212495409584}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.algebra.lib Require Import mono_list.\nFrom iris.bi.lib Require Import fractional.\nFrom iris.base_logic.lib Require Export own.\nFrom iris.prelude Require Import options.\n\nClass mono_listG (A : Type) Σ :=\n  MonoListG { mono_list_inG : inG Σ (mono_listR (leibnizO A)) }.\nLocal Existing Instance mono_list_inG.\n\nDefinition mono_listΣ (A : Type) : gFunctors :=\n  #[GFunctor (mono_listR (leibnizO A))].\n\nGlobal Instance subG_mono_listΣ {A Σ} :\n  subG (mono_listΣ A) Σ → (mono_listG A) Σ.\nProof. solve_inG. Qed.\n\nLocal Definition mono_list_auth_def `{!mono_listG A Σ}\n    (γ : gname) (q : Qp) (l : list A) : iProp Σ :=\n  own γ (●ML{#q} (l : listO (leibnizO A))).\nLocal Definition mono_list_auth_aux : seal (@mono_list_auth_def).\nProof. by eexists. Qed.\nDefinition mono_list_auth := mono_list_auth_aux.(unseal).\nLocal Definition mono_list_auth_unseal :\n  @mono_list_auth = @mono_list_auth_def := mono_list_auth_aux.(seal_eq).\nGlobal Arguments mono_list_auth {A Σ _} γ q l.\n\nLocal Definition mono_list_lb_def `{!mono_listG A Σ}\n    (γ : gname) (l : list A) : iProp Σ :=\n  own γ (◯ML (l : listO (leibnizO A))).\nLocal Definition mono_list_lb_aux : seal (@mono_list_lb_def).\nProof. by eexists. Qed.\nDefinition mono_list_lb := mono_list_lb_aux.(unseal).\nLocal Definition mono_list_lb_unseal :\n  @mono_list_lb = @mono_list_lb_def := mono_list_lb_aux.(seal_eq).\nGlobal Arguments mono_list_lb {A Σ _} γ l.\n\nDefinition mono_list_mapsto `{!mono_listG A Σ}\n    (γ : gname) (i : nat) (a : A) : iProp Σ :=\n  ∃ l : list A, ⌜ l !! i = Some a ⌝ ∗ mono_list_lb γ l.\n\nLocal Ltac unseal := rewrite\n  /mono_list_mapsto ?mono_list_auth_unseal /mono_list_auth_def\n  ?mono_list_lb_unseal /mono_list_lb_def.\n\nSection mono_list_own.\n  Context `{!mono_listG A Σ}.\n  Implicit Types (l : list A) (i : nat) (a : A).\n\n  Global Instance mono_list_auth_timeless γ q l : Timeless (mono_list_auth γ q l).\n  Proof. unseal. apply _. Qed.\n  Global Instance mono_list_lb_timeless γ l : Timeless (mono_list_lb γ l).\n  Proof. unseal. apply _. Qed.\n  Global Instance mono_list_lb_persistent γ l : Persistent (mono_list_lb γ l).\n  Proof. unseal. apply _. Qed.\n  Global Instance mono_list_mapsto_timeless γ i a :\n    Timeless (mono_list_mapsto γ i a) := _.\n  Global Instance mono_list_mapsto_persistent γ i a :\n    Persistent (mono_list_mapsto γ i a) := _.\n\n  Global Instance mono_list_auth_fractional γ l :\n    Fractional (λ q, mono_list_auth γ q l).\n  Proof. unseal. intros p q. by rewrite -own_op -mono_list_auth_dfrac_op. Qed.\n  Global Instance mono_list_auth_as_fractional γ q l :\n    AsFractional (mono_list_auth γ q l) (λ q, mono_list_auth γ q l) q.\n  Proof. split; [auto|apply _]. Qed.\n\n  Lemma mono_list_auth_agree γ q1 q2 l1 l2 :\n    mono_list_auth γ q1 l1 -∗\n    mono_list_auth γ q2 l2 -∗\n    ⌜(q1 + q2 ≤ 1)%Qp ∧ l1 = l2⌝.\n  Proof.\n    unseal. iIntros \"H1 H2\".\n    by iDestruct (own_valid_2 with \"H1 H2\") as %?%mono_list_auth_dfrac_op_valid_L.\n  Qed.\n  Lemma mono_list_auth_exclusive γ l1 l2 :\n    mono_list_auth γ 1 l1 -∗ mono_list_auth γ 1 l2 -∗ False.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct (mono_list_auth_agree with \"H1 H2\") as %[]; done.\n  Qed.\n\n  Lemma mono_list_auth_lb_valid γ q l1 l2 :\n    mono_list_auth γ q l1 -∗\n    mono_list_lb γ l2 -∗\n    ⌜ (q ≤ 1)%Qp ∧ l2 `prefix_of` l1 ⌝.\n  Proof.\n    unseal. iIntros \"Hauth Hlb\".\n    by iDestruct (own_valid_2 with \"Hauth Hlb\") as %?%mono_list_both_dfrac_valid_L.\n  Qed.\n\n  Lemma mono_list_lb_valid γ l1 l2 :\n    mono_list_lb γ l1 -∗\n    mono_list_lb γ l2 -∗\n    ⌜ l1 `prefix_of` l2 ∨ l2 `prefix_of` l1 ⌝.\n  Proof.\n    unseal. iIntros \"H1 H2\".\n    by iDestruct (own_valid_2 with \"H1 H2\") as %?%mono_list_lb_op_valid_L.\n  Qed.\n\n  Lemma mono_list_mapsto_agree γ i a1 a2 :\n    mono_list_mapsto γ i a1 -∗ mono_list_mapsto γ i a2 -∗ ⌜ a1 = a2 ⌝.\n  Proof.\n    iDestruct 1 as (l1 Hl1) \"H1\". iDestruct 1 as (l2 Hl2) \"H2\".\n    iDestruct (mono_list_lb_valid with \"H1 H2\") as %Hpre.\n    iPureIntro.\n    destruct Hpre as [Hpre|Hpre]; eapply prefix_lookup in Hpre; eauto; congruence.\n  Qed.\n\n  Lemma mono_list_auth_mapsto_lookup γ q l i a :\n    mono_list_auth γ q l -∗ mono_list_mapsto γ i a -∗ ⌜ l !! i = Some a ⌝.\n  Proof.\n    iIntros \"Hauth\". iDestruct 1 as (l1 Hl1) \"Hl1\".\n    iDestruct (mono_list_auth_lb_valid with \"Hauth Hl1\") as %[_ Hpre].\n    iPureIntro.\n    eapply prefix_lookup in Hpre; eauto; congruence.\n  Qed.\n\n  Lemma mono_list_lb_get γ q l :\n    mono_list_auth γ q l -∗ mono_list_lb γ l.\n  Proof. intros. unseal. by apply own_mono, mono_list_included. Qed.\n  Lemma mono_list_lb_le {γ l} l' :\n    l' `prefix_of` l →\n    mono_list_lb γ l -∗ mono_list_lb γ l'.\n  Proof. unseal. intros. by apply own_mono, mono_list_lb_mono. Qed.\n\n  Lemma mono_list_mapsto_get {γ l} i a :\n    l !! i = Some a →\n    mono_list_lb γ l -∗ mono_list_mapsto γ i a.\n  Proof. iIntros (Hli) \"Hl\". iExists l. by iFrame. Qed.\n\n  Lemma mono_list_alloc l :\n    ⊢ |==> ∃ γ, mono_list_auth γ 1 l ∗ mono_list_lb γ l.\n  Proof.\n    unseal. setoid_rewrite <- own_op. by apply own_alloc, mono_list_both_valid_L.\n  Qed.\n  Lemma mono_list_auth_update {γ l} l' :\n    l `prefix_of` l' →\n    mono_list_auth γ 1 l ==∗ mono_list_auth γ 1 l' ∗ mono_list_lb γ l'.\n  Proof.\n    iIntros (?) \"Hauth\".\n    iAssert (mono_list_auth γ 1 l') with \"[> Hauth]\" as \"Hauth\".\n    { unseal. iApply (own_update with \"Hauth\"). by apply mono_list_update. }\n    iModIntro. iSplit; [done|]. by iApply mono_list_lb_get.\n  Qed.\n\n  Lemma mono_list_auth_update_app {γ l} l' :\n    mono_list_auth γ 1 l ==∗\n    mono_list_auth γ 1 (l ++ l') ∗ mono_list_lb γ (l ++ l').\n  Proof. by apply mono_list_auth_update, prefix_app_r. Qed.\nEnd mono_list_own.\n", "meta": {"author": "clef-men", "repo": "caml5", "sha": "0de06d5792138eb17877ed1536a0401b7a322ee2", "save_path": "github-repos/coq/clef-men-caml5", "path": "github-repos/coq/clef-men-caml5/caml5-0de06d5792138eb17877ed1536a0401b7a322ee2/theories/base_logic/lib/mono_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2351779728005935}}
{"text": "(** * AND instruction *)\nRequire Import x86proved.x86.instrrules.core.\nImport x86.instrrules.core.instrruleconfig.\n\n(** ** Generic AND *)\nLemma AND_rule sz (ds:DstSrc sz) (v1: VWORD sz) :\n   |-- specAtDstSrc ds (fun D v2 =>\n       basic (D v1 ** OSZCP?)\n             (BOP _ OP_AND ds) \n             (let v := andB v1 v2 in\n              D v ** OSZCP false (msb v) (v == #0) false (lsb v))).\nProof. do_instrrule_triple. Qed.\n\n(** We make this rule an instance of the typeclass, and leave\n    unfolding things like [specAtDstSrc] to the getter tactic\n    [get_instrrule_of]. *)\nGlobal Instance: forall sz (ds : DstSrc sz), instrrule (BOP sz OP_AND ds) := @AND_rule.\n\n(** ** AND r1, r2 *)\nCorollary AND_RR_rule (r1 r2:Reg) v1 (v2:DWORD) :\n  |-- basic (r1~=v1 ** r2 ~= v2 ** OSZCP?)\n            (AND r1, r2) \n            (let v := andB v1 v2 in r1~=v ** r2 ~= v2 **\n             OSZCP false (msb v) (v == #0) false (lsb v)).\nProof. basic apply *. Qed.\n\n(** ** AND r1, [r2 + offset] *)\nCorollary AND_RM_rule (pbase:DWORD) (r1 r2:Reg) v1 (v2:DWORD) (offset:nat) :\n  |-- basic (r1~=v1 ** OSZCP?)\n            (AND r1, [r2 + offset]) \n            (let v:= andB v1 v2 in r1~=v ** OSZCP false (msb v) (v == #0) false (lsb v))\n      @ (r2 ~= pbase ** pbase +# offset :-> v2).\nProof. autorewrite with push_at. basic apply *. Qed.\n\nCorollary AND_RM_ruleNoFlags (pd:DWORD) (r1 r2:Reg) v1 (v2:DWORD) (offset:nat):\n  |-- basic (r1~=v1) (AND r1, [r2 + offset]) (r1~=andB v1 v2)\n             @ (r2 ~= pd ** pd +# offset :-> v2 ** OSZCP?).\nProof. autorewrite with push_at. basic apply *. Qed.\n\n(** ** AND r, v *)\nLemma AND_RI_rule (r:Reg) v1 (v2:DWORD) :\n  |-- basic (r~=v1 ** OSZCP?)\n            (AND r, v2) \n            (let v:= andB v1 v2 in r~=v ** OSZCP false (msb v) (v == #0) false (lsb v)).\nProof. basic apply *. Qed.\n", "meta": {"author": "nbenton", "repo": "x86proved", "sha": "7a58960f6456ee09dd46c990204a30c2fdd7fa1a", "save_path": "github-repos/coq/nbenton-x86proved", "path": "github-repos/coq/nbenton-x86proved/x86proved-7a58960f6456ee09dd46c990204a30c2fdd7fa1a/src/x86/instrrules/and.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.23517796644690522}}
{"text": "Require Import CertiGraph.prim.prim_env.\nRequire Export CertiGraph.lib.find_lemmas.\nRequire Export CertiGraph.priq.is_empty_lemmas.\nRequire Import CertiGraph.graph.MathUAdjMatGraph. \nRequire Import CertiGraph.graph.SpaceUAdjMatGraph1.\nRequire Import CertiGraph.prim.prim_spec1.\n\nLocal Open Scope Z.\n\n\n(***********************VERIFICATION***********************)\n\nSection PrimProof.\n\nContext {size: Z}.\t\nContext {inf: Z}.\nContext {Z_EqDec : EquivDec.EqDec Z eq}.\n\n(* Without a find + isEmpty priq file, just leave it IMO *)\nLemma find_min_lt_inf: forall u l,\n    u = find l (fold_right Z.min (hd 0 l) l) 0 -> (@isEmpty inf l) = Vzero ->\n    Zlength l > 0 -> Znth u l < inf + 1.\nProof.\n  intros. rewrite <- isEmpty_in' in H0. destruct H0 as [? [? ?]].\n  rewrite H. rewrite Znth_find.\n  - pose proof (fold_min _ _ H0). lia.\n  - now apply fold_min_in_list.\nQed.\n\n(**Initialisation functions**)\n\nLemma body_getCell: semax_body Vprog (@Gprog size inf Z_EqDec) f_getCell (@getCell_spec size inf).\nProof.\n  start_function.\n  rewrite (SpaceAdjMatGraph_unfold' _ _ _ addresses u); trivial.\n  assert ((Zlength (map Int.repr (Znth u (@graph_to_symm_mat size g)))) = size). {\n    unfold graph_to_symm_mat, graph_to_mat, vert_to_list.\n    rewrite Znth_map; repeat rewrite Zlength_map.\n    all: rewrite nat_inc_list_Zlength, Z2Nat.id; lia.\n  }\n  assert (0 <= i < Zlength (map Int.repr (Znth u (@graph_to_symm_mat size g)))) by lia.\n  assert (0 <= i < Zlength (Znth u (@graph_to_symm_mat size g))). {\n    rewrite Zlength_map in H1. lia.\n  }\n\n  Intros.\n  freeze FR := (iter_sepcon _ _) (iter_sepcon _ _).\n  unfold list_rep.\n  forward. forward. forward. thaw FR.\n  rewrite (SpaceAdjMatGraph_unfold'  _ _ _ addresses u); trivial.\t\n  entailer!.\n\n  all: unfold graph_to_symm_mat; rewrite graph_to_mat_Zlength; trivial.\n  apply Zlength_nonneg. lia.\nQed.\n\nLemma body_initialise_list: semax_body Vprog (@Gprog size inf Z_EqDec) f_initialise_list (@initialise_list_spec size).\nProof.\nstart_function.\nassert_PROP(Zlength old_list = size). entailer!.\nforward_for_simple_bound size\n    (EX i : Z,\n     PROP ()\n     LOCAL (temp _list arr; temp _size (Vint (Int.repr size)); temp _a (Vint (Int.repr a)))\n     SEP (\n      data_at Tsh (tarray tint size) (list_repeat (Z.to_nat i) (Vint (Int.repr a))++(sublist i size old_list)) arr\n    ))%assert.\nentailer!. rewrite app_nil_l. rewrite sublist_same by lia. entailer!.\n(*loop*)\nforward. entailer!.\nrewrite (sublist_split i (i+1)) by lia.\nreplace (sublist i (i+1) old_list) with [Znth i old_list]. simpl.\nrewrite upd_Znth_char.\nrewrite <- list_repeat_app' by lia.\nrewrite <- app_assoc. simpl. auto.\napply Zlength_list_repeat; lia.\nsymmetry; apply sublist_one; lia.\n(*postcon*)\nentailer!. rewrite sublist_nil. rewrite app_nil_r. entailer!.\nQed.\n\n(******************PRIM'S***************)\n\nLemma body_prim: semax_body Vprog (@Gprog size inf Z_EqDec) f_prim (@prim_spec size inf).\nProof.\n  start_function. rename H into Hprecon_1. rename H0 into Hprecon_2.\n  pose proof (inf_representable g).\n  rename H into inf_repr.\nassert (inf_repable: repable_signed inf). {\n  rep_lia.\n}\nassert (Hsz: 0 < size <= Int.max_signed). {\n  apply (size_representable g). }\nassert (Hsz2: size <= Int.max_signed). {\n  lia. }\nassert (size_repable: repable_signed size). {\n  unfold repable_signed. rep_lia. }\nassert (H_size4_rep: Int.min_signed <= size * 4 <= Int.max_signed). {\n  split; [rep_lia|].\n  apply Z.le_trans with (m := size * (4 * size)); trivial.\n  rewrite Z.mul_comm, (Z.mul_comm _ (4 * size)).\n  apply Z.le_mul_diag_r; lia.\n}\nassert (H_size4_rep': 4 <= size * 4 <= Int.max_unsigned). {\n  split; [lia|].\n  apply Z.le_trans with (m := Int.max_signed).\n  2: compute; inversion 1.\n  apply Z.le_trans with (m := size * (4 * size)); trivial.\n  rewrite Z.mul_comm, (Z.mul_comm _ (4 * size)).\n  apply Z.le_mul_diag_r; lia.\n} \n  \n(*replace all data_at_ with data_at Vundef*)\nrepeat rewrite data_at__tarray. set (k:=default_val tint); compute in k; subst k.\n(*populate key with inf*)\n\nunfold V in *.\nforward_call (size * 4). (* check that the call is ok *)\n  \nIntros key.\nremember (pointer_val_val key) as v_key.\nrename H into Ha.\n\nforward_call (v_key, (list_repeat (Z.to_nat size) Vundef), inf).\nsimpl sizeof. rewrite Z_div_mult. \nrewrite data_at__tarray.\nunfold default_val. simpl. entailer!. lia. \n\n\nassert_PROP (Zlength (map (fun x : Z => Vint (Int.repr x)) garbage) = size). entailer!.\nrewrite Zlength_list_repeat in H5. trivial.\nlia.\n\n\nforward_call (pointer_val_val parent_ptr, (map (fun x : Z => Vint (Int.repr x)) garbage), size).\nclear H garbage.\n\nforward_call (size * 4).\nIntros out.\nremember (pointer_val_val out) as v_out.\nrename H into Hb.\n\nforward_call (v_out, (list_repeat (Z.to_nat size) Vundef), 0).\nsimpl sizeof. rewrite Z_div_mult. \nrewrite data_at__tarray.\nunfold default_val. simpl. entailer!. lia.\nsplit3; trivial. red. rep_lia.\n\nassert (Hrbound: 0 <= r < size). apply vert_bound in Hprecon_1; auto.\nrewrite <- Heqv_key.\nforward.\nassert (Hstarting_keys: forall i, 0 <= i < size -> is_int I32 Signed (Znth i (upd_Znth r (list_repeat (Z.to_nat size) (Vint (Int.repr inf))) (Vint (Int.repr 0))))). {\n  intros. unfold is_int. destruct (Z.eq_dec i r).\n  +subst i. rewrite upd_Znth_same. auto. rewrite Zlength_list_repeat; lia.\n  +rewrite Znth_upd_Znth_diff; auto. rewrite Znth_list_repeat_inrange by lia. auto.\n}\nreplace (upd_Znth r (list_repeat (Z.to_nat size) (Vint (Int.repr inf))) (Vint (Int.repr 0))) with\n  (map (fun x => Vint (Int.repr x)) (upd_Znth r (list_repeat (Z.to_nat size) inf) 0)) in *.\n2: {\n  rewrite <- upd_Znth_map.\n  f_equal.\n  rewrite map_list_repeat.\n  reflexivity.\n}\nset (starting_keys:=map (fun x => Vint (Int.repr x)) (upd_Znth r (list_repeat (Z.to_nat size) inf) 0)) in *.\nassert (HZlength_starting_keys: Zlength starting_keys = size). {\n  unfold starting_keys. rewrite Zlength_map. rewrite Zlength_upd_Znth. rewrite Zlength_list_repeat; lia.\n}\nunfold repable_signed in inf_repable.\n(*push all vertices into priq*)\nforward_call(tt).\nsplit; lia. \nIntro priq_ptr.\nremember (pointer_val_val priq_ptr) as v_pq.\nrewrite <- Heqv_out.\n\n(*push all vertices into priq*)\nforward_for_simple_bound size\n  (EX i : Z,\n    PROP ()\n    LOCAL (\n      temp _pq v_pq; temp _out v_out;\n      temp _key v_key; temp _graph (pointer_val_val gptr);\n      temp _size (Vint (Int.repr size));\n      temp _inf (Vint (Int.repr inf));\n      temp _r (Vint (Int.repr r)); temp _parent (pointer_val_val parent_ptr)\n    )\n    SEP (\n      data_at Tsh (tarray tint size) (list_repeat (Z.to_nat size) (Vint (Int.repr 0))) v_out;\n      data_at Tsh (tarray tint size) (list_repeat (Z.to_nat size) (Vint (Int.repr size))) (pointer_val_val parent_ptr);\n      data_at Tsh (tarray tint size) starting_keys v_key;\n      data_at Tsh (tarray tint size) (sublist 0 i starting_keys ++ sublist i size (list_repeat (Z.to_nat size) Vundef)) v_pq;\n      (@SpaceAdjMatGraph' size CompSpecs Tsh (@graph_to_symm_mat size g) (pointer_val_val gptr) addresses);\n      free_tok v_pq (sizeof tint * size);\n      free_tok v_out (size * 4);\n      free_tok v_key (size * 4)\n    )\n  )%assert.\nentailer!.\nrewrite sublist_nil, sublist_same, app_nil_l.\nentailer!.\ntrivial. rewrite Zlength_list_repeat; lia.\n\n(*precon taken care of*)\n(*loop*)\nTransparent size.\nforward.\nGlobal Opaque size.\n\nassert (Znth i starting_keys = Vint (Int.repr (Znth i (upd_Znth r (list_repeat (Z.to_nat size) inf) 0)))). {\n  unfold starting_keys. rewrite Znth_map; auto.\n  rewrite Zlength_upd_Znth. rewrite Zlength_list_repeat; lia.\n}\nforward_call (v_pq, i, Znth i (upd_Znth r (list_repeat (Z.to_nat size) inf) 0), sublist 0 i starting_keys ++ sublist i size (list_repeat (Z.to_nat size) Vundef)).\nsplit. auto. unfold weight_inrange_priq.\ndestruct (Z.eq_dec i r). subst i. rewrite upd_Znth_same. split. pose proof Int.min_signed_neg; lia.\npose proof (inf_representable g); lia.\nrewrite Zlength_list_repeat; lia.\nrewrite upd_Znth_diff, Znth_list_repeat_inrange. rep_lia.\nlia. rewrite Zlength_list_repeat; lia. rewrite Zlength_list_repeat; lia. auto.\nentailer!.\nrewrite upd_Znth_app2. rewrite Zlength_sublist, Z.sub_0_r, Z.sub_diag; try lia.\nrewrite (sublist_split i (i+1) size). rewrite (sublist_one i (i+1)). rewrite upd_Znth_app1.\nrewrite upd_Znth0. rewrite app_assoc.\nrewrite (sublist_split 0 i (i+1)). rewrite (sublist_one i (i+1)). rewrite <- H0. entailer!.\nall: try lia.\nrewrite Zlength_cons, Zlength_nil; lia.\nrewrite Zlength_list_repeat. lia. lia.\nrewrite Zlength_list_repeat; lia.\nrewrite Zlength_sublist. rewrite Zlength_sublist. lia. lia. rewrite Zlength_list_repeat; lia. lia. lia.\nrewrite sublist_nil, app_nil_r, sublist_same; try lia.\n(*one last thing for convenience*)\nrewrite <- (map_list_repeat (fun x => Vint (Int.repr x))).\nrewrite <- (map_list_repeat (fun x => Vint (Int.repr x))).\npose proof (finGraph g) as fg.\n(*whew! all setup done!*)\n(*now for the pq loop*)\nforward_loop (\n  EX mst': (@G size inf),\n  EX fmst': FiniteGraph mst',\n  EX parents: list V,\n  EX keys: list Z, (*can give a concrete definition in SEP, but it leads to shenanigans during entailer*)\n  EX pq_state: list V, (*can give a concrete definition in SEP, but it leads to shenanigans during entailer*)\n  EX popped_vertices: list V,\n  EX unpopped_vertices: list V,\n    PROP (\n      (*graph stuff*)\n      is_partial_lgraph mst' g;\n      uforest' mst';\n      (*about the lists*)\n      Permutation (popped_vertices++unpopped_vertices) (VList g);\n      forall v, 0 <= v < size -> 0 <= Znth v parents <= size;\n      forall v, 0 <= v < size -> Znth v keys = if V_EqDec v r then 0 else elabel g (eformat (v, Znth v parents));\n      forall v, 0 <= v < size -> Znth v pq_state = if in_dec V_EqDec v popped_vertices then Z.add inf 1 else Znth v keys;\n      forall v, 0 <= v < size -> 0 <= Znth v parents < size ->\n          (evalid g (eformat (v, Znth v parents)) /\\ (*together you form a valid edge in g*)\n          (exists i, 0<=i<Zlength popped_vertices /\\ Znth i popped_vertices = Znth v parents /\\\n            i < find popped_vertices v 0) /\\ (*your parent has been popped, only time parents is updated, and you weren't in it when it was*)\n          (forall u, In u (sublist 0 (find popped_vertices v 0) popped_vertices) -> elabel g (eformat (v, Znth v parents)) <= elabel g (eformat (u,v))) (*your current parent is the lowest among the popped, until you're popped too*) (*<-used for proving weight invar below*)\n          );\n      forall v, 0 <= v < size -> Znth v parents = size -> forall u, In u (sublist 0 (find popped_vertices v 0) popped_vertices) -> ~adjacent g u v;\n      (*mst specific*)\n      Permutation (EList mst') (map (fun v => eformat (v, Znth v parents)) (filter (fun v => Znth v parents <? size) popped_vertices));\n      forall u v, In u popped_vertices -> In v popped_vertices -> (connected g u v <-> connected mst' u v);\n      (*misc*)\n      forall u v, In u unpopped_vertices -> ~ adjacent mst' u v;\n      (*weight*)\n      (* at the point of being popped, you had the lowest weight of all potential branches *)\n      forall v u1 u2, In v popped_vertices -> 0 <= Znth v parents < size ->\n        vvalid g u2 ->\n        In u1 (sublist 0 (find popped_vertices v 0) popped_vertices) ->\n        ~ In u2 (sublist 0 (find popped_vertices v 0) popped_vertices) ->\n        elabel g (eformat (v, Znth v parents)) <= elabel g (eformat (u1,u2));\n      (*minimality...*)\n      exists M, minimum_spanning_forest M g /\\ is_partial_lgraph mst' M;\n      (*the following two are yuck...*)\n      popped_vertices = nil -> r = find pq_state (fold_right Z.min (hd 0 pq_state) pq_state) 0;\n      popped_vertices <> nil -> hd_error popped_vertices = Some r\n    )\n    LOCAL (\n      temp _v (Vint (Int.repr size));\n      temp _pq v_pq; temp _out v_out;\n      temp _key v_key;\n      temp _graph (pointer_val_val gptr);\n      temp _size (Vint (Int.repr size));\n      temp _inf (Vint (Int.repr inf));\n      temp _r (Vint (Int.repr r));\n      temp _parent (pointer_val_val parent_ptr)\n    )\n    SEP (\n      data_at Tsh (tarray tint size) (map (fun x => if in_dec V_EqDec x popped_vertices\n        then (Vint (Int.repr 1)) else (Vint (Int.repr 0))) (nat_inc_list (Z.to_nat size))) v_out;\n      data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x)) parents) (pointer_val_val parent_ptr);\n      data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x)) keys) v_key;\n      data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x))\n        pq_state) v_pq;\n      (@SpaceAdjMatGraph' size CompSpecs Tsh (@graph_to_symm_mat size g) (pointer_val_val gptr) addresses);\n      free_tok v_pq (sizeof tint * size);\n      free_tok v_out (size * 4);\n      free_tok v_key (size * 4)\n    )\n  )\nbreak: (\n  EX mst: (@G size inf),\n  EX fmst: FiniteGraph mst,\n  EX popped_vertices: list V,\n  EX parents: list V,\n  EX keys: list Z,\n    PROP (\n      is_partial_lgraph mst g;\n      uforest' mst;\n      Permutation popped_vertices (VList mst);\n      forall v, 0 <= v < size -> 0 <= Znth v parents < size ->\n          (evalid g (eformat (v, Znth v parents)) /\\ (*together you form a valid edge in g*)\n          (exists i, 0<=i<Zlength popped_vertices /\\ Znth i popped_vertices = Znth v parents\n            /\\ i < find popped_vertices v 0) /\\ (*your parent has been popped, only time parents is updated, and you weren't in it when it was*)\n          (forall u, In u (sublist 0 (find popped_vertices v 0) popped_vertices) -> elabel g (eformat (v, Znth v parents)) <= elabel g (eformat (u,v))) (*your current parent is the lowest among the popped, until you're popped too*) (*<-used for proving weight invar below*)\n          );\n      forall v, 0 <= v < size -> Znth v parents = size -> forall u, In u (sublist 0 (find popped_vertices v 0) popped_vertices) -> ~adjacent g u v;\n      (*something about weight*)\n      Permutation (EList mst) (map (fun v => eformat (v, Znth v parents)) (filter (fun v => Znth v parents <? size) popped_vertices));\n      spanning mst g;\n      hd_error popped_vertices = Some r; (*<-idk if necessary, just putting it in in case*)\n      (*weight*)\n      forall v u1 u2, In v popped_vertices -> 0 <= Znth v parents < size ->\n        vvalid g u2 ->\n        In u1 (sublist 0 (find popped_vertices v 0) popped_vertices) ->\n        ~ In u2 (sublist 0 (find popped_vertices v 0) popped_vertices) ->\n        elabel g (eformat (v, Znth v parents)) <= elabel g (eformat (u1,u2));\n      forall v, 0 <= v < size -> 0 <= Znth v parents <= size;\n      (*minimality...*)\n      exists M, minimum_spanning_forest M g /\\ is_partial_lgraph mst M\n    )\n    LOCAL (\n      temp _pq v_pq; temp _out v_out;\n      temp _parent (pointer_val_val parent_ptr); temp _key v_key;\n      temp _graph (pointer_val_val gptr); temp _r (Vint (Int.repr r))\n    )\n    SEP (\n      data_at Tsh (tarray tint size) (list_repeat (Z.to_nat size) (Vint (Int.repr 1))) v_out;\n      data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x)) parents) (pointer_val_val parent_ptr);\n      data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x)) keys) v_key;\n      data_at Tsh (tarray tint size) (list_repeat (Z.to_nat size) (Vint (Int.repr (inf+1)))) v_pq;\n      (@SpaceAdjMatGraph' size CompSpecs Tsh (@graph_to_symm_mat size g) (pointer_val_val gptr) addresses);\n      free_tok v_pq (sizeof tint * size);\n      free_tok v_out (size * 4);\n      free_tok v_key (size * 4)\n    )\n  )\n%assert.\n(****PRECON****) {\n  remember (@edgeless_graph'\n            size inf\n            Hsz\n            (inf_representable g)) as elg. \n  Exists elg.\n  pose proof (finGraph elg) as fe. Exists fe.\n  Exists (list_repeat (Z.to_nat size) size).\n  Exists (upd_Znth r (list_repeat (Z.to_nat size) inf) 0).\n  Exists (upd_Znth r (list_repeat (Z.to_nat size) inf) 0).\n  Exists (nil (A:=V)).\n  Exists (VList g). rewrite app_nil_l.\n  assert (Hinv_1: is_partial_lgraph elg g).\n  subst elg. apply edgeless_partial_lgraph.\n  assert (Hinv_2: uforest' elg). subst elg. apply uforest'_edgeless_graph.\n  assert (Hinv_3: Permutation (VList g) (VList g)). apply Permutation_refl; auto.\n  assert (Hinv_4: forall v : Z, 0 <= v < size -> 0 <= Znth v (list_repeat (Z.to_nat size) size) <= size). {\n    intros. rewrite Znth_list_repeat_inrange; lia.\n  }\n  assert (Hinv_5: forall v : Z, 0 <= v < size -> Znth v (upd_Znth r (list_repeat (Z.to_nat size) inf) 0) =\n    (if V_EqDec v r then 0 else elabel g (eformat (v, Znth v (list_repeat (Z.to_nat size) size))))). {\n    intros. destruct (V_EqDec v r).\n    hnf in e; subst v. rewrite upd_Znth_same. auto. rewrite Zlength_list_repeat; lia.\n    unfold RelationClasses.complement, Equivalence.equiv in c. rewrite upd_Znth_diff.\n    repeat rewrite Znth_list_repeat_inrange by lia. symmetry; rewrite <- (invalid_edge_weight g); auto.\n    unfold not; intros. rewrite <- (eformat_adj g) in H0. apply adjacent_requires_vvalid in H0. destruct H0.\n    rewrite vert_bound in H1. lia.\n    rewrite Zlength_list_repeat; lia. rewrite Zlength_list_repeat; lia. auto.\n  }\n  assert (Hinv_6: forall v : Z,\n    0 <= v < size ->\n    Znth v (upd_Znth r (list_repeat (Z.to_nat size) inf) 0) =\n    (if in_dec V_EqDec v (nil (A:=V))\n     then (inf + 1)%Z\n     else Znth v (upd_Znth r (list_repeat (Z.to_nat size) inf) 0))). {\n    intros. destruct (in_dec V_EqDec v []); [contradiction | auto].\n  }\n  assert (Hinv_7: forall v : Z, 0 <= v < size ->\n    0 <= Znth v (list_repeat (Z.to_nat size) size) < size ->\n    evalid g (eformat (v, Znth v (list_repeat (Z.to_nat size) size))) /\\\n    (exists i : Z, 0 <= i < Zlength (nil (A:=V)) /\\\n       Znth i (nil (A:=V)) = Znth v (list_repeat (Z.to_nat size) size) /\\ i < find (nil (A:=V)) v 0) /\\\n    (forall u : V,\n     In u (sublist 0 (find (nil (A:=V)) v 0) (nil (A:=V))) ->\n     elabel g (eformat (v, Znth v (list_repeat (Z.to_nat size) size))) <=\n     elabel g (eformat (u, v)))). {\n    intros. rewrite Znth_list_repeat_inrange in H0; lia. }\n  assert (Hinv_8: forall v : Z, 0 <= v < size ->\n    Znth v (list_repeat (Z.to_nat size) size ) = size ->\n    forall u : V, In u (sublist 0 (find [] v 0) []) -> ~ adjacent g u v). {\n    intros. rewrite sublist_nil in H1. contradiction. }\n  assert (Hinv_9: Permutation (EList elg)\n      (map (fun v : Z => eformat (v, Znth v (list_repeat (Z.to_nat size) size)))\n         (filter (fun v : Z => Znth v (list_repeat (Z.to_nat size) size) <? size) []))). {\n    simpl.\n    (*because I've trouble using edgeless_graph_EList*) apply NoDup_Permutation. apply NoDup_EList. apply NoDup_nil.\n    intros. rewrite EList_evalid. split; intros.\n    subst elg.\n    pose proof (@edgeless_graph_evalid size inf (inf_representable g) Hsz x); contradiction. contradiction.\n  }\n  assert (Hr1: forall u v : V, In u (nil (A:=V)) -> In v (nil (A:=V)) -> connected g u v <-> connected elg u v). {\n    intros. contradiction.\n  }\n  assert (Hr2: (nil (A:=V)) = (nil (A:=V)) ->\n    r = find (upd_Znth r (list_repeat (Z.to_nat size) inf) 0)\n      (fold_right Z.min (hd 0 (upd_Znth r (list_repeat (Z.to_nat size) inf) 0))\n         (upd_Znth r (list_repeat (Z.to_nat size) inf) 0)) 0). {\n    intros. rewrite find_src; lia. \n  }\n  (*Hinv_12 (nil <> nil) seems to be missing, autoresolved?*)\n  assert (Hinv_13: forall u v : V, In u (VList g) -> ~ adjacent elg u v). {\n    unfold not; intros. destruct H0 as [e [? ?]]. destruct H0.\n    subst elg. pose proof (@edgeless_graph_evalid size inf (inf_representable g) Hsz e); contradiction.\n  }\n  assert (Hinv_14: forall v u1 u2 : V,\n    In v (nil (A:=V)) ->\n    0 <= Znth v (list_repeat (Z.to_nat size) size) < size ->\n    vvalid g u2 ->\n    In u1 (sublist 0 (find (nil (A:=V)) v 0) (nil (A:=V))) ->\n    ~ In u2 (sublist 0 (find (nil (A:=V)) v 0) (nil (A:=V))) ->\n    elabel g (eformat (v, Znth v (list_repeat (Z.to_nat size) size))) <=\n    elabel g (eformat (u1, u2))). {\n    intros. contradiction.\n  }\n  assert (Hinv_15: exists M, minimum_spanning_forest M g /\\ is_partial_lgraph elg M). {\n    destruct (exists_msf g) as [M ?]. exists M; split. auto.\n    subst elg. apply edgeless_partial_lgraph.\n  }                                                      (*fix up the SEP*)\n  replace (map (fun x : V => if in_dec V_EqDec x [] then Vint (Int.repr 1) else Vint (Int.repr 0)) (nat_inc_list (Z.to_nat size)))\n    with (map (fun x : Z => Vint (Int.repr x)) (list_repeat (Z.to_nat size) 0)). 2: {\n    apply list_eq_Znth. repeat rewrite Zlength_map. rewrite Zlength_list_repeat by lia. rewrite nat_inc_list_Zlength, Z2Nat.id; lia.\n    intros. rewrite Zlength_map, Zlength_list_repeat in H by lia.\n    rewrite Znth_map. 2: rewrite Zlength_list_repeat; lia.\n    rewrite Znth_list_repeat_inrange by lia.\n    rewrite Znth_map. 2: rewrite nat_inc_list_Zlength, Z2Nat.id; lia.\n    rewrite nat_inc_list_i. 2: rewrite Z2Nat.id; lia.\n    destruct (in_dec V_EqDec i []); [contradiction | auto].\n  }\n  unfold starting_keys.\n  time \"main loop precon (originally 446.87s):\" entailer!.\n  \n\n\n}\n(****MAIN LOOP****) {\n  clear Hstarting_keys HZlength_starting_keys starting_keys.\n  Intros mst' fmst' parents keys pq_state popped_vertices unpopped_vertices.\n  (*do a mass renaming for convenience*)\n  rename H into Hinv_1; rename H0 into Hinv_2;\n  rename H1 into Hinv_3; rename H2 into Hinv_4;\n  rename H3 into Hinv_5; rename H4 into Hinv_6;\n  rename H5 into Hinv_7; rename H6 into Hinv_8;\n  rename H7 into Hinv_9; rename H8 into Hinv_10;\n  rename H9 into Hinv_13; rename H10 into Hinv_14;\n  rename H11 into Hinv_15; rename H12 into Hr1;\n  rename H13 into Hr2.\n  assert_PROP (Zlength parents = size /\\\n               Zlength keys = size /\\\n               Zlength pq_state = size\n              ). {\n    entailer!.\n    repeat rewrite Zlength_map in *.\n    rewrite H2 in *.\n    split3; trivial.\n  }\n  destruct H as [HZlength_parents [HZlength_keys HZlength_pq_state]].\n  assert (Hpopped_or_unpopped: forall v, vvalid g v -> In v popped_vertices \\/ In v unpopped_vertices). {\n    intros. apply in_app_or. apply (Permutation_in (l:=VList g)). apply Permutation_sym; auto. apply VList_vvalid; auto.\n  }\n  (*^^significant lag from the three entailers above*)\n  assert (Hpopped_vvalid: forall v, In v popped_vertices -> vvalid g v). {\n    intros. rewrite <- VList_vvalid. apply (Permutation_in (l:=popped_vertices++unpopped_vertices)).\n    apply Hinv_3. apply in_or_app; left; auto.\n  }\n  assert (Hunpopped_vvalid: forall v, In v unpopped_vertices -> vvalid g v). {\n    intros. rewrite <- VList_vvalid. apply (Permutation_in (l:=popped_vertices++unpopped_vertices)).\n    apply Hinv_3. apply in_or_app; right; auto.\n  }\n  assert (@inrange_priq inf pq_state). {\n    unfold inrange_priq. rewrite Forall_forall. intros x Hx.\n    rewrite In_Znth_iff in Hx. destruct Hx as [i [? ?]].\n    unfold V in *.\n    rewrite HZlength_pq_state in H. subst x.\n    rewrite Hinv_6. 2: lia.\n    destruct (@in_dec Z V_EqDec i popped_vertices).    \n    rep_lia.\n    rewrite Hinv_5. 2: lia. destruct (V_EqDec i r).\n    pose proof (inf_representable g); rep_lia.\n    split. apply weight_representable. apply (Z.le_trans _ inf). apply weight_inf_bound. lia.\n  }\n  replace (data_at Tsh (tarray tint size) (map (fun x : Z => Vint (Int.repr x)) pq_state) v_pq)\n    with (data_at Tsh (tarray tint size) (map Vint (map Int.repr pq_state)) v_pq).\n  2: { rewrite list_map_compose. auto. }\n  forward_call (v_pq, pq_state).\n  1: repeat split; trivial; lia. \n  forward_if.\n\n  (*PROCEED WITH LOOP*) {\n  assert (@isEmpty inf pq_state = Vzero). {\n    destruct (@isEmptyTwoCases inf pq_state);\n    rewrite H1 in H0; simpl in H0; now inversion H0.\n  }\n  forward_call (v_pq, pq_state).\n  1: repeat split; trivial; lia.\n  Intros u. rename H2 into Hu.\n  assert (0 <= u < size). {\n    rewrite Hu. rewrite <- HZlength_pq_state. apply find_range.\n    apply min_in_list. apply incl_refl. destruct pq_state.\n    rewrite Zlength_nil in HZlength_pq_state. lia.\n    simpl. left; trivial.\n  }\n  assert (Hu_not_popped: ~ In u popped_vertices). { unfold not; intros.\n    assert (Znth u pq_state < inf + 1). apply (find_min_lt_inf u pq_state Hu H1).\n    unfold V in *. rewrite HZlength_pq_state. lia.\n    rewrite Hinv_6 in H4 by lia.\n    destruct (in_dec V_EqDec u popped_vertices). lia. contradiction.\n  }\n  assert (Hu_unpopped: In u unpopped_vertices). { destruct (Hpopped_or_unpopped u).\n    rewrite (vvalid_meaning g). auto. contradiction. auto.\n  }\n  forward.\n  replace (upd_Znth u (map (fun x : V =>\n    if in_dec V_EqDec x popped_vertices then Vint (Int.repr 1) else Vint (Int.repr 0))\n    (nat_inc_list (Z.to_nat size))) (Vint (Int.repr 1))) with (map (fun x : V =>\n    if in_dec V_EqDec x (popped_vertices+::u) then Vint (Int.repr 1) else Vint (Int.repr 0))\n    (nat_inc_list (Z.to_nat size))).\n  2: { apply list_eq_Znth. rewrite Zlength_upd_Znth. do 2 rewrite Zlength_map. auto.\n    intros. rewrite Zlength_map in H3. rewrite nat_inc_list_Zlength in H3.\n    destruct (Z.eq_dec i u). subst i.\n    +rewrite upd_Znth_same. rewrite Znth_map.\n    rewrite nat_inc_list_i. assert (In u (popped_vertices+::u)). apply in_or_app. right; simpl; auto.\n    destruct (in_dec V_EqDec u (popped_vertices+::u)). auto. contradiction.\n    lia. rewrite nat_inc_list_Zlength; lia.\n    rewrite Zlength_map, nat_inc_list_Zlength; lia.\n    +rewrite upd_Znth_diff. rewrite Znth_map. rewrite Znth_map. rewrite nat_inc_list_i.\n    destruct (in_dec V_EqDec i (popped_vertices+::u));\n    destruct (in_dec V_EqDec i popped_vertices). auto.\n    apply in_app_or in i0; destruct i0. contradiction. destruct H4. symmetry in H4; contradiction. contradiction.\n    assert (In i (popped_vertices+::u)). apply in_or_app. left; auto. contradiction.\n    auto. auto. rewrite nat_inc_list_Zlength; auto. rewrite nat_inc_list_Zlength; auto.\n    rewrite Zlength_map, nat_inc_list_Zlength; auto.\n    rewrite Zlength_map, nat_inc_list_Zlength; auto.\n    auto.\n    rewrite Z2Nat.id; lia. trivial.\n  }\n  rewrite upd_Znth_map. rewrite upd_Znth_map. rewrite list_map_compose. (*pq state*)\n  replace (Znth 0 pq_state) with (hd 0 pq_state). rewrite <- Hu. 2: { destruct pq_state. rewrite Zlength_nil in HZlength_pq_state; lia. simpl. rewrite Znth_0_cons. auto. }\n  assert (Hur: popped_vertices = nil -> u = r). {\n    intros. rewrite Hu. symmetry; apply Hr1. auto.\n  }\n  assert (Hu_min: forall v, 0 <= v < size -> Znth u pq_state <= Znth v pq_state). {\n    intros. rewrite Hu. rewrite Znth_find.\n    apply fold_min. apply Znth_In. unfold V in *. lia.\n    apply fold_min_in_list. unfold V in *. lia.\n  }\n  clear Hu. set (upd_pq_state:=upd_Znth u pq_state (inf + 1)).\n  (*for loop to update un-popped vertices' min weight.\n  The result is every vertex who's NOT in popped_vertices and connected, has their weight maintained or lowered*)\n  forward_for_simple_bound size (\n    EX i: Z,\n    EX parents': list Z,\n    EX keys': list Z,\n    EX pq_state': list Z,\n      PROP (\n        (*if you were already popped (out=1) or not adjacent, nothing happens*)\n        forall v, 0<=v<i -> (~adjacent g u v \\/ In v (popped_vertices+::u)) -> (\n          Znth v parents' = Znth v parents /\\\n          Znth v keys' = Znth v keys /\\\n          Znth v pq_state' = Znth v upd_pq_state);\n        (*if you are still in pq and adjacent, you are updated*)\n        forall v, 0<=v<i -> adjacent g u v -> ~ In v (popped_vertices+::u) -> (\n          Znth v parents' = (if Z.ltb (elabel g (eformat (u,v))) (Znth v upd_pq_state) then u else Znth v parents) /\\\n          Znth v keys' = Z.min (elabel g (eformat (u,v))) (Znth v upd_pq_state) /\\\n          Znth v pq_state' = Z.min (elabel g (eformat (u,v))) (Znth v upd_pq_state));\n        (*no change for those that haven't been checked*)\n        forall v, i<=v<size -> (\n          Znth v parents' = Znth v parents /\\\n          Znth v keys' = Znth v keys /\\\n          Znth v pq_state' = Znth v upd_pq_state\n        );\n        forall v, 0 <= v < size -> Int.min_signed <= Znth v keys' <= inf\n      )\n      LOCAL (temp _u (Vint (Int.repr u)); temp _t'4 (@isEmpty inf pq_state);\n             temp _v (Vint (Int.repr size)); temp _pq v_pq; temp _out v_out;\n             temp _key v_key; temp _graph (pointer_val_val gptr);\n             temp _size (Vint (Int.repr size)); temp _inf (Vint (Int.repr inf));\n             temp _r (Vint (Int.repr r)); temp _parent (pointer_val_val parent_ptr))\n      SEP (data_at Tsh (tarray tint size) (map (fun x => Vint (Int.repr x)) pq_state') v_pq;\n     data_at Tsh (tarray tint size)\n       (map\n          (fun x : V =>\n           if in_dec V_EqDec x (popped_vertices+::u) then Vint (Int.repr 1) else Vint (Int.repr 0))\n          (nat_inc_list (Z.to_nat size))) v_out;\n     data_at Tsh (tarray tint size) (map (fun x : Z => Vint (Int.repr x)) parents') (pointer_val_val parent_ptr);\n     data_at Tsh (tarray tint size) (map (fun x : Z => Vint (Int.repr x)) keys') v_key;\n     (@SpaceAdjMatGraph' size CompSpecs Tsh (@graph_to_symm_mat size g) (pointer_val_val gptr) addresses);\n     free_tok v_pq (sizeof tint * size);\n     free_tok v_out (size * 4);\n     free_tok v_key (size * 4)\n          )\n    )\n  %assert.\n  (*precon*) {\n    Exists parents. Exists keys. Exists upd_pq_state. entailer!.\n    remember (Zlength parents) as size.\n    (*in this case, proving the PROPs beforehand did not improve the timing*)\n    intros. rewrite Hinv_5 by lia. destruct (V_EqDec v r). auto. split; rep_lia.\n    pose proof (weight_representable g (eformat (v, Znth v parents))).\n    split; try rep_lia. apply weight_inf_bound.\n  }\n  (*loop*)\n  assert (is_int I32 Signed (if in_dec V_EqDec (Znth i (nat_inc_list (Z.to_nat size))) (popped_vertices+::u)\n    then Vint (Int.repr 1) else Vint (Int.repr 0))). {\n    unfold is_int. rewrite nat_inc_list_i. 2: rewrite Z2Nat.id; lia.\n    destruct (in_dec V_EqDec i (popped_vertices+::u)); auto.\n  }\n  assert (Hc: 0 <= i < Zlength (nat_inc_list (Z.to_nat size))). {\n    rewrite nat_inc_list_Zlength, Z2Nat.id; trivial. lia. }\n  forward.\n  rename H5 into Hinv2_1; rename H6 into Hinv2_2;\n  rename H7 into Hinv2_3; rename H8 into Hinv2_4.\n  assert_PROP (Zlength (map (fun x : Z => Vint (Int.repr x)) parents') = size /\\\n                Zlength (map (fun x : Z => Vint (Int.repr x)) keys') = size /\\\n                Zlength (map (fun x : Z => Vint (Int.repr x)) pq_state') = size). entailer!.\n  repeat rewrite Zlength_map in H5. destruct H5 as [? [? ?]].\n  rename H5 into HZlength_parents'. rename H6 into HZlength_keys'. rename H7 into HZlength_pq_state'.\n  rewrite nat_inc_list_i. 2: rewrite Z2Nat.id; lia.\n  set (out_i:=if in_dec V_EqDec i (popped_vertices+::u)\n               then Vint (Int.repr 1)\n               else Vint (Int.repr 0)). fold out_i.\n  forward_if.\n  (**In queue**)\n  +assert (~ In i (popped_vertices+::u)). {\n    destruct (in_dec V_EqDec i (popped_vertices +:: u)). simpl in H5. inversion H5. auto.\n   }\n   Transparent size.\n   forward_call (g, gptr, addresses, u, i).\n   Global Opaque size.\n   forward.\n  forward_if.\n    -(*g[u][i] < ..., update*)\n    (*implies adjacency*)\n      rewrite graph_to_mat_eq in H7; try lia. rewrite eformat_symm in H7.\n      rewrite Int.signed_repr in H7. rewrite Int.signed_repr in H7.\n      2: { assert (Int.min_signed <= Znth i keys' <= inf). apply Hinv2_4; lia.\n           pose proof (inf_representable g).\n           rep_lia.\n      }\n    2: { apply weight_representable. }\n    assert (Hadj_ui: adjacent g u i). {\n      rewrite eformat_adj_elabel.\n      assert (Znth i keys' <= inf). apply Hinv2_4. lia.\n      apply (Z.lt_le_trans _ (Znth i keys')); auto.\n    }\n    forward. forward. forward. entailer!.\n    rewrite upd_Znth_same. simpl. auto. rewrite Zlength_map. rewrite HZlength_keys'. auto.\n    rewrite upd_Znth_same. 2: { simpl. auto. rewrite Zlength_map. rewrite HZlength_keys'. auto. }\n    replace (map (fun x : Z => Vint (Int.repr x)) pq_state') with (map Vint (map Int.repr pq_state')).\n    2: rewrite list_map_compose; auto.\n    forward_call (v_pq, i, Znth i (Znth u (@graph_to_symm_mat size g)), pq_state').\n    split. lia.\n    unfold weight_inrange_priq.\n    rewrite graph_to_mat_eq. split.\n    apply weight_representable. rewrite eformat_adj_elabel, eformat_symm in Hadj_ui.\n    fold V in *. lia. lia. lia.\n    Exists (upd_Znth i parents' u).\n    Exists (upd_Znth i keys' (Znth i (Znth u (@graph_to_symm_mat size g)))).\n    Exists (upd_Znth i pq_state' (Znth i (Znth u (@graph_to_symm_mat size g)))).\n    rewrite list_map_compose. repeat rewrite (upd_Znth_map (fun x => Vint (Int.repr x))). \n    clear H0 H5.\n    assert (Hx1: forall v : Z, 0 <= v < i + 1 ->\n      ~ adjacent g u v \\/ In v (popped_vertices +:: u) ->\n      Znth v (upd_Znth i parents' u) = Znth v parents /\\\n      Znth v (upd_Znth i keys' (Znth i (Znth u (@graph_to_symm_mat size g)))) = Znth v keys /\\\n      Znth v (upd_Znth i pq_state' (Znth i (Znth u (@graph_to_symm_mat size g)))) =\n      Znth v upd_pq_state). {\n      intros. destruct (Z.lt_trichotomy v i). repeat rewrite upd_Znth_diff; try lia. apply Hinv2_1. lia. apply H5.\n      destruct H8. subst v. destruct H5; contradiction. lia.\n    } (*71s to 60s*)\n    assert (Hx2: forall v : Z,\n    0 <= v < i + 1 ->\n    adjacent g u v ->\n    ~ In v (popped_vertices +:: u) ->\n    Znth v (upd_Znth i parents' u) =\n    (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents) /\\\n    Znth v (upd_Znth i keys' (Znth i (Znth u (@graph_to_symm_mat size g)))) =\n    Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state) /\\\n    Znth v (upd_Znth i pq_state' (Znth i (Znth u (@graph_to_symm_mat size g)))) =\n    Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state)). {\n      intros. destruct (Z.lt_trichotomy v i).\n        (*v<i*) repeat rewrite upd_Znth_diff; try lia. apply Hinv2_2. lia. auto. auto.\n        destruct H9.\n        (*v=i*) subst v. repeat rewrite upd_Znth_same; try lia.\n        (*i not in popped, so must be in unpopped, which means upd_pq_state = pq_state = keys*)\n        assert (Znth i upd_pq_state = Znth i keys').\n          unfold upd_pq_state. rewrite upd_Znth_diff. 2: replace (Zlength pq_state) with size; lia. 2: replace (Zlength pq_state) with size; lia.\n          replace (Znth i keys') with (Znth i keys). rewrite Hinv_6.\n          destruct (in_dec V_EqDec i popped_vertices). exfalso; apply H8. apply in_or_app; left; auto. auto. lia.\n          symmetry. apply Hinv2_3. lia. unfold not; intros. apply H8. apply in_or_app; right; subst i; left; auto.\n        rewrite H9. split3.\n        rewrite <- (@graph_to_mat_eq size); try lia. destruct (Znth u (Znth i (@graph_to_symm_mat size g)) <? Znth i keys') eqn:bool.\n        auto. rewrite graph_to_mat_eq in bool; try lia. rewrite Z.ltb_nlt in bool. contradiction.\n        rewrite graph_to_mat_eq; try lia. rewrite eformat_symm. rewrite Zlt_Zmin; auto.\n        rewrite graph_to_mat_eq; try lia. rewrite eformat_symm. rewrite Zlt_Zmin; auto.\n        (*v>i*) lia.\n    } (*60s to 33s*)\n    assert(Hx3: forall v : Z,\n    i + 1 <= v < size ->\n    Znth v (upd_Znth i parents' u) = Znth v parents /\\\n    Znth v (upd_Znth i keys' (Znth i (Znth u (@graph_to_symm_mat size g)))) = Znth v keys /\\\n    Znth v (upd_Znth i pq_state' (Znth i (Znth u (@graph_to_symm_mat size g)))) = Znth v upd_pq_state). {\n      intros. repeat rewrite upd_Znth_diff; try lia. apply Hinv2_3. lia.\n    }\n    (*entailer unable to solve but no change to timing*)\n    assert (Hx4: forall v : Z,\n    0 <= v < size ->\n    Int.min_signed <= Znth v (upd_Znth i keys' (Znth i (Znth u (@graph_to_symm_mat size g)))) <= inf). {\n      intros. destruct (Z.eq_dec v i). subst i. rewrite upd_Znth_same. rewrite graph_to_mat_eq.\n      split. apply (weight_representable g (eformat (v,u))). apply weight_inf_bound. lia. lia. rewrite HZlength_keys'; lia.\n      rewrite upd_Znth_diff. apply Hinv2_4. auto. rewrite HZlength_keys'; lia.\n      rewrite HZlength_keys'; lia. auto.\n    } (*entailer unable to solve but no change to timing*)\n    time \"inner loop update-because-lt-postcon (orig 71 seconds)\" entailer!.\n    -forward. (*nothing changed*)\n    Exists parents'. Exists keys'. Exists pq_state'.\n    assert (Hx1: forall v : Z,\n          0 <= v < i + 1 ->\n          ~ adjacent g u v \\/ In v (popped_vertices +:: u) ->\n          Znth v parents' = Znth v parents /\\\n          Znth v keys' = Znth v keys /\\ Znth v pq_state' = Znth v upd_pq_state). {\n      intros. destruct (Z.lt_trichotomy v i). apply Hinv2_1; auto. lia. destruct H10.\n      subst v. apply Hinv2_3. lia. lia.\n    } (*60s to 53s*)\n    assert (Hx2: forall v : Z,\n      0 <= v < i + 1 ->\n      adjacent g u v ->\n      ~ In v (popped_vertices +:: u) ->\n      Znth v parents' =\n      (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents) /\\\n      Znth v keys' = Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state) /\\\n      Znth v pq_state' = Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state)). {\n      intros. destruct (Z.lt_trichotomy v i).\n      (*v < i*) apply Hinv2_2. lia. auto. auto.\n      destruct H11.\n      (*v = i*) subst v. rewrite <- (@graph_to_mat_eq size); try lia.\n      assert (Znth i upd_pq_state = Znth i keys'). {\n        unfold upd_pq_state. rewrite upd_Znth_diff. 2: replace (Zlength pq_state) with size; lia.  2: replace (Zlength pq_state) with size; lia.\n        replace (Znth i keys') with (Znth i keys). rewrite Hinv_6.\n        destruct (in_dec V_EqDec i popped_vertices). exfalso. apply H10. apply in_or_app; left; auto.\n        auto. lia. symmetry. apply Hinv2_3. lia. unfold not; intros. apply H10. apply in_or_app; right; subst i; left; auto.\n      } rewrite H11.\n      rewrite graph_to_mat_symmetric; try lia.\n      rewrite !Int.signed_repr in H7. split3.\n      destruct (Znth i (Znth u (@graph_to_symm_mat size g)) <? Znth i keys') eqn:bool.\n      rewrite Z.ltb_lt in bool. unfold V in *. lia.\n      apply Hinv2_3. lia.\n      unfold V in *.\n      rewrite Z.min_r; try lia. \n      replace (Znth i pq_state') with (Znth i upd_pq_state). rewrite H11.\n      unfold V in *. rewrite Z.min_r; try lia.\n      symmetry; apply Hinv2_3; lia.\n      assert (Int.min_signed <= Znth i keys' <= inf). apply Hinv2_4. lia. pose proof (inf_repable); unfold repable_signed in H13; lia.\n      rewrite graph_to_mat_eq; try lia. apply weight_representable.\n      (*v > i*) lia.\n    } (*53s to 30s*)\n    assert (Hx3: forall v : Z,\n      i + 1 <= v < size ->\n      Znth v parents' = Znth v parents /\\\n      Znth v keys' = Znth v keys /\\ Znth v pq_state' = Znth v upd_pq_state). {\n      intros. apply Hinv2_3. lia.\n    } (*entailer unable to solve but no change to timing*)\n    time \"inner loop no-update-because-not-lt-postcon (originally 60s)\" entailer!.\n    \n  +(*nothing changed because out of pq*)\n  assert (In i (popped_vertices+::u)). {\n    unfold typed_false in H5. destruct (V_EqDec u i); simpl in H5. unfold Equivalence.equiv in e; subst i. apply in_or_app; right; left; auto.\n    destruct (in_dec V_EqDec i (popped_vertices+::u)); simpl in H5. auto. inversion H5.\n  }\n  forward. (*again nothing changed*)\n  Exists parents'. Exists keys'. Exists pq_state'.\n  rewrite (SpaceAdjMatGraph_unfold' _ _ _ addresses u).\n  unfold list_rep.\n  2: unfold graph_to_symm_mat; rewrite graph_to_mat_Zlength; lia.\n  2: lia.\n  assert (forall v : Z,\n          0 <= v < i + 1 ->\n          ~ adjacent g u v \\/ In v (popped_vertices +:: u) ->\n          Znth v parents' = Znth v parents /\\\n          Znth v keys' = Znth v keys /\\ Znth v pq_state' = Znth v upd_pq_state). {\n    intros. destruct (Z.lt_trichotomy v i). apply Hinv2_1; auto. lia. destruct H9. subst v. apply Hinv2_3. lia. lia.\n  }\n  assert (forall v : Z,\n    0 <= v < i + 1 ->\n    adjacent g u v ->\n    ~ In v (popped_vertices +:: u) ->\n    Znth v parents' =\n    (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents) /\\\n    Znth v keys' = Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state) /\\\n    Znth v pq_state' = Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state)). {\n    intros. destruct (Z.lt_trichotomy v i). apply Hinv2_2. lia. auto. auto.\n    destruct H11. subst v. contradiction. (*i is popped*) lia.\n  }\n  assert (forall v : Z,\n    i + 1 <= v < size ->\n    Znth v parents' = Znth v parents /\\\n    Znth v keys' = Znth v keys /\\ Znth v pq_state' = Znth v upd_pq_state). {\n    intros. apply Hinv2_3. lia.\n  }\n  time \"inner loop no-update-because-out-postcon (originally 92 seconds):\" entailer!.\n  +(*inner loop done, postcon leading to next outer loop iter*)\n  Intros parents' keys' pq_state'.\n  assert (Htmp: Znth u parents' = Znth u parents /\\ Znth u keys' = Znth u keys /\\ Znth u pq_state' = Znth u upd_pq_state). {\n    apply H3. lia. right; apply in_or_app; right; left; auto.\n  } destruct Htmp as [Hu_parents [Hu_keys Hu_pq_state]].\n  (*need to split into two cases: if Znth u keys = inf, then it's a \"starter\" and so the same mst. Else, it's adde(eformat (u, Znth u keys))*)\n  clear H5. rename H3 into Hinv2_1; rename H4 into Hinv2_2; rename H6 into Hinv2_3.\n  assert (0 <= Znth u parents). { apply Hinv_4. auto. }\n  assert (Znth u parents <= size). { apply Hinv_4. auto. }\n  (*****We do as many props as we can here, especially the non-mst ones*****)\n  assert (Hperm_g: Permutation (popped_vertices +:: u ++ remove V_EqDec u unpopped_vertices) (VList g)). {\n    assert (NoDup unpopped_vertices). apply (NoDup_app_r V popped_vertices). apply (Permutation_NoDup (l:=VList g)). apply Permutation_sym; auto.\n    apply NoDup_VList.\n    rewrite <- app_assoc. simpl. apply (Permutation_trans (l':=popped_vertices++unpopped_vertices)).\n    apply Permutation_app_head. apply NoDup_Permutation. apply NoDup_cons. apply remove_In.\n    apply nodup_remove_nodup. auto. auto. intros; split; intros.\n    destruct H6. subst x. auto. rewrite remove_In_iff in H6. apply H6.\n    destruct (V_EqDec x u). unfold Equivalence.equiv in e. subst x. left; auto.\n    unfold RelationClasses.complement, Equivalence.equiv in c. right. rewrite remove_In_iff. split; auto.\n    auto.\n  }\n  assert (Hparents_bound: forall v : Z, 0 <= v < size -> 0 <= Znth v parents' <= size). {\n    intros. destruct (adjacent_dec g u v). destruct (in_dec Z.eq_dec v (popped_vertices +::u)).\n    replace (Znth v parents') with (Znth v parents). 2: symmetry; apply Hinv2_1; auto. apply Hinv_4; auto.\n    replace (Znth v parents') with (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents).\n    2: symmetry; apply (Hinv2_2 v); auto. rewrite <- (@graph_to_mat_eq size); auto.\n    destruct (Znth u (Znth v (@graph_to_symm_mat size g)) <? Znth v upd_pq_state) eqn:bool. lia. apply Hinv_4; auto.\n    replace (Znth v parents') with (Znth v parents). 2: symmetry; apply Hinv2_1; auto. apply Hinv_4; auto.\n  }\n  assert (Hkeys': forall v : Z, 0 <= v < size -> Znth v keys' = (if V_EqDec v r then 0 else elabel g (eformat (v, Znth v parents')))). {\n    intros. destruct (adjacent_dec g u v). destruct (in_dec Z.eq_dec v (popped_vertices +::u)).\n    ****\n    replace (Znth v keys') with (Znth v keys). 2: symmetry; apply Hinv2_1; auto. rewrite Hinv_5.\n    replace (Znth v parents') with (Znth v parents). 2: symmetry; apply Hinv2_1; auto. auto. auto.\n    ****\n    replace (Znth v keys') with (Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state)). 2: symmetry; apply Hinv2_2; auto.\n    replace (Znth v parents') with (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents). 2: symmetry; apply Hinv2_2; auto.\n    destruct (V_EqDec v r). hnf in e.\n    (*v=r*) subst v. destruct popped_vertices. exfalso. apply n. apply in_or_app; right; left. apply Hur; auto.\n    assert (hd_error (v :: popped_vertices) = Some r). apply Hr2. unfold not; intros. inversion H7. inversion H7. subst v.\n    exfalso. apply n. apply in_or_app; left; left; auto.\n    (*v <> r*)\n    rewrite <- (@graph_to_mat_eq size) by lia. destruct (Znth u (Znth v (@graph_to_symm_mat size g)) <? Znth v upd_pq_state) eqn:bool.\n    rewrite graph_to_mat_eq by lia. rewrite graph_to_mat_eq in bool by lia. rewrite Z.ltb_lt in bool. rewrite Zlt_Zmin by auto. rewrite eformat_symm; auto.\n    rewrite graph_to_mat_eq by lia. rewrite graph_to_mat_eq in bool by lia. rewrite Z.ltb_ge in bool. rewrite Z.min_r by auto.\n    unfold upd_pq_state. destruct (Z.eq_dec v u). subst v. exfalso; apply n. apply in_or_app; right; left; auto.\n    rewrite upd_Znth_diff. rewrite Hinv_6 by lia. destruct (in_dec V_EqDec v popped_vertices). exfalso; apply n. apply in_or_app; left; auto.\n    rewrite Hinv_5 by lia. destruct (V_EqDec v r). contradiction. auto.\n    replace (Zlength pq_state) with size by lia. lia.\n    replace (Zlength pq_state) with size by lia. lia. auto.\n    ****\n    replace (Znth v keys') with (Znth v keys). 2: symmetry; apply Hinv2_1; auto. rewrite Hinv_5.\n    replace (Znth v parents') with (Znth v parents). 2: symmetry; apply Hinv2_1; auto. auto. auto.\n  }\n  assert (Hpq_state': forall v : Z, 0 <= v < size -> Znth v pq_state' = (if in_dec V_EqDec v (popped_vertices +:: u) then inf + 1 else Znth v keys')). {\n    intros. destruct (in_dec V_EqDec v (popped_vertices +:: u)).\n    replace (Znth v pq_state') with (Znth v upd_pq_state). 2: symmetry; apply Hinv2_1; auto. unfold upd_pq_state.\n    apply in_app_or in i; destruct i.\n    rewrite upd_Znth_diff. rewrite Hinv_6 by lia. destruct (in_dec V_EqDec v popped_vertices). auto. contradiction.\n    replace (Zlength pq_state) with size; lia. replace (Zlength pq_state) with size; lia.\n    unfold not; intros; subst v. contradiction.\n    destruct H6. subst v. rewrite upd_Znth_same. auto. replace (Zlength pq_state) with size; lia.\n    contradiction.\n    destruct (adjacent_dec g u v).\n    (*second case*)\n    replace (Znth v pq_state') with (Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state)). 2: symmetry; apply Hinv2_2; auto.\n    replace (Znth v keys') with (Z.min (elabel g (eformat (u, v))) (Znth v upd_pq_state)). 2: symmetry; apply Hinv2_2; auto.\n    auto.\n    (*third case*)\n    replace (Znth v pq_state') with (Znth v upd_pq_state). 2: symmetry; apply Hinv2_1; auto. unfold upd_pq_state.\n    rewrite upd_Znth_diff. rewrite Hinv_6 by lia. destruct (in_dec V_EqDec v popped_vertices).\n    exfalso; apply n. apply in_or_app; left; auto.\n    symmetry; apply Hinv2_1; auto. unfold upd_pq_state.\n    replace (Zlength pq_state) with size; lia. replace (Zlength pq_state) with size; lia.\n    unfold not; intros. subst v. apply n. apply in_or_app; right; left; auto.\n  }\n  assert (Hpopped_nil: popped_vertices +:: u = [] -> r = find pq_state' (fold_right Z.min (hd 0 pq_state') pq_state') 0). {\n    intros. assert (In u (popped_vertices+::u)). apply in_or_app; right; left; auto.\n    rewrite H5 in H6. contradiction.\n  }\n  assert (Hpopped_unnil: popped_vertices +:: u <> [] -> hd_error (popped_vertices +:: u) = Some r). {\n    intros. destruct popped_vertices. rewrite Hur; auto.\n    apply hd_error_app. rewrite Hr2; auto. unfold not; intros. inversion H6.\n  }\n  assert (Hheavy: forall v : Z, 0 <= v < size -> 0 <= Znth v parents' < size ->\n    evalid g (eformat (v, Znth v parents')) /\\\n    (exists i : Z, 0 <= i < Zlength (popped_vertices +:: u) /\\\n      Znth i (popped_vertices +:: u) = Znth v parents' /\\\n      i < find (popped_vertices+::u) v 0)\n    /\\ (forall u0 : V,\n     In u0 (sublist 0 (find (popped_vertices +:: u) v 0) (popped_vertices +:: u)) ->\n     elabel g (eformat (v, Znth v parents')) <= elabel g (eformat (u0, v)))). {\n    intros. (*the main issue is u and unpopped; popped_vertices is an application of Hinv2_1 and Hinv_7*)\n    destruct (in_dec V_EqDec v (popped_vertices+::u)).\n    (*v in popped_vertices+::u*)\n    replace (Znth v parents') with (Znth v parents). 2: symmetry; apply Hinv2_1; auto.\n    replace (Znth v parents') with (Znth v parents) in H6. 2: symmetry; apply Hinv2_1; auto.\n    destruct (Hinv_7 v H5 H6). destruct H8 as [[j [? ?]] ?].\n    split. auto. split. exists j. split.\n    rewrite Zlength_app. rewrite Zlength_cons, Zlength_nil. lia.\n    split. rewrite app_Znth1 by lia. apply H9.\n    destruct H9. apply (Z.lt_le_trans _ (find popped_vertices v 0)). auto. apply find_app_le.\n    intros.\n    apply H10. rewrite sublist_app1 in H11. auto.\n    2: { split. lia. apply (find_range_gen (popped_vertices+::u) v 0). auto. lia. }\n    2: { assert (0 <= find (popped_vertices +:: u) v 0 < Zlength (popped_vertices +:: u)).\n        apply (find_range (popped_vertices+::u) v). auto. rewrite Zlength_app, Zlength_cons, Zlength_nil in H12. lia. }\n    destruct (V_EqDec v u).\n    (*subcase v = u*) hnf in e. subst v.\n    replace (find (popped_vertices +:: u) u 0) with (Zlength popped_vertices) in H11.\n    replace (find popped_vertices u 0) with (Zlength popped_vertices). auto.\n    rewrite find_notIn_0; auto.\n    rewrite find_app_notIn1. rewrite find_cons. rewrite Z.add_0_r. auto. auto.\n    (*subcase v <> u*) unfold RelationClasses.complement, Equivalence.equiv in c.\n    assert (In v popped_vertices). apply in_app_or in i; destruct i. auto. destruct H12. symmetry in H12; contradiction. contradiction.\n    replace (find (popped_vertices +:: u) v 0) with (find popped_vertices v 0) in H11. auto.\n    symmetry; apply find_app_In1. auto.\n    (*****NOT IN POPPED_VERTICES+::U*****)\n    assert (In v (remove V_EqDec u unpopped_vertices)). destruct (Hpopped_or_unpopped v). rewrite vert_bound; auto.\n    exfalso; apply n; apply in_or_app; left; auto. rewrite remove_In_iff. split. auto. unfold not; intros.\n    subst v. apply n; apply in_or_app; right; left; auto.\n    destruct (adjacent_dec g u v).\n    (*adjacent*)\n    replace (Znth v parents') with (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents).\n    2: symmetry; apply Hinv2_2; auto.\n    replace (Znth v parents') with (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents) in H6.\n    2: symmetry; apply Hinv2_2; auto.\n    rewrite <- ((@graph_to_mat_eq size) g u v) in * by lia.\n    destruct (Znth u (Znth v (@graph_to_symm_mat size g)) <? Znth v upd_pq_state) eqn: bool.\n    (*smaller, updated: u is the new parent*)\n      rewrite Z.ltb_lt in bool. split. rewrite eformat_symm. apply eformat_adj. auto.\n      split. exists (Zlength popped_vertices). split. rewrite Zlength_app, Zlength_cons, Zlength_nil.\n      split. apply Zlength_nonneg. lia. rewrite Znth_app2 by lia. rewrite Z.sub_diag, Znth_0_cons.\n      split. auto. rewrite find_notIn by auto. rewrite Zlength_app, Zlength_cons, Zlength_nil. lia.\n      intros.\n      assert (v <> u). unfold not; intros. subst v. apply n. apply in_or_app; right; left; auto.\n      rewrite sublist_same in H9. 2: auto. 2: { rewrite find_notIn, Z.add_0_r. auto. auto. }\n      apply in_app_or in H9; destruct H9.\n      rewrite eformat_symm, <- (@graph_to_mat_eq size) by lia.\n      unfold upd_pq_state in bool.\n      rewrite upd_Znth_diff in bool. 2: replace (Zlength pq_state) with size; lia.\n      2: replace (Zlength pq_state) with size; lia. 2: auto.\n      rewrite Hinv_6 in bool. 2: lia. destruct (in_dec V_EqDec v popped_vertices).\n      exfalso. apply n. apply in_or_app; left; auto.\n      rewrite Hinv_5 in bool by lia. destruct (V_EqDec v r). hnf in e; subst v.\n      destruct popped_vertices. exfalso; apply H10; symmetry; apply Hur. auto.\n      assert (hd_error (v :: popped_vertices) = Some r). apply Hr2. unfold not; intros; inversion H11.\n      inversion H11. subst v. exfalso; apply n. apply in_or_app; left; left; auto.\n      (*now check whether Znth v parents is size or lower.\n        If < size, use Hinv_7 to show that eformat(u0,v) must be bigger than parents.\n        If size, use Hinv_8 to derive that eformat(u0,v) is invalid.\n        *)\n      assert (Htmp: Znth v parents <= size). apply Hinv_4. lia. apply Z.le_lteq in Htmp; destruct Htmp.\n      assert (elabel g (eformat (v, Znth v parents)) <= elabel g (eformat (u0, v))). { apply (Hinv_7 v). lia.\n        split. apply Hinv_4. lia. lia. rewrite find_notIn, Z.add_0_r, sublist_same. auto. auto. auto.\n        unfold not; intros; apply n; apply in_or_app; left; auto.\n      }\n      apply (Z.le_trans _ (elabel g (eformat (v, Znth v parents)))). lia. lia.\n      (*Znth v parents = size. So elabel = inf, meaning it should not be connected to u0 by Hinv_8*)\n      assert (~ evalid g (eformat (u0, v))). {\n        unfold not; intros. rewrite <- eformat_adj in H12.\n        assert (~ adjacent g u0 v). apply Hinv_8. lia. lia.\n        rewrite find_notIn, Z.add_0_r by auto. rewrite sublist_same by auto. auto.\n        contradiction.\n      }\n      apply (invalid_edge_weight g) in H12.\n      replace (elabel g (eformat (u0, v))) with inf by trivial.\n      rewrite graph_to_mat_eq by lia. apply (weight_inf_bound).\n      (*u0 = u.*)\n      destruct H9. 2: contradiction. subst u0.\n      rewrite eformat_symm. apply Z.eq_le_incl. reflexivity.\n    (*case not smaller, so parent remains the same. Use Hinv_7*)\n    assert (Htmp: 0 <= Znth v parents < size). apply H6.\n    apply Hinv_7 in Htmp. 2: lia. destruct Htmp. destruct H10 as [[j [? ?]] ?].\n    split. auto. split. exists j. split. rewrite Zlength_app, Zlength_cons, Zlength_nil. lia.\n    split. rewrite Znth_app1 by lia. apply H11.\n    destruct H11. apply (Z.lt_le_trans _ (find popped_vertices v 0)). auto. apply find_app_le.\n    intros. rewrite find_notIn in H13 by auto. rewrite sublist_same in H13. 2: auto. 2: rewrite Z.add_0_r; auto.\n    apply in_app_or in H13. destruct H13. apply H12. rewrite find_notIn. rewrite Z.add_0_r, sublist_same by auto.\n    auto. unfold not; intros; apply n. apply in_or_app; left; auto.\n    destruct H13. 2: contradiction. subst u0.\n    (*use bool*)\n    unfold upd_pq_state in bool. rewrite Z.ltb_ge in bool.\n    destruct (V_EqDec u v).\n      (*v=u.*)\n      hnf in e; subst v. rewrite upd_Znth_same in bool.\n      2: replace (Zlength pq_state) with size; lia.\n      pose proof (weight_inf_bound g (eformat (u, u))). rewrite <- (@graph_to_mat_eq size) in H13 by lia.\n      lia.\n      (*v<>u*)\n      unfold RelationClasses.complement, Equivalence.equiv in c. rewrite upd_Znth_diff in bool.\n      2: replace (Zlength pq_state) with size; lia. 2: replace (Zlength pq_state) with size; lia.\n      2: auto.\n      rewrite Hinv_6 in bool by lia. destruct (in_dec V_EqDec v popped_vertices). exfalso; apply n; apply in_or_app; left; auto.\n      rewrite Hinv_5 in bool by lia. destruct (V_EqDec v r).\n      (*v=r*)hnf in e; subst v. (*hm...*)\n      exfalso; apply n. apply hd_error_In. apply Hpopped_unnil. unfold not; intros.\n      assert (In u (popped_vertices+::u)). apply in_or_app; right; left; auto. rewrite H13 in H14; contradiction.\n      (*v<>r*)\n      rewrite graph_to_mat_eq in bool by lia. apply bool.\n    (*finally, non adjacent*)\n    replace (Znth v parents') with (Znth v parents). 2: symmetry; apply Hinv2_1; auto.\n    replace (Znth v parents') with (Znth v parents) in H6. 2: symmetry; apply Hinv2_1; auto.\n    destruct (Hinv_7 v H5 H6). destruct H10 as [[j [? ?]] ?].\n    split. auto. split. exists j. split.\n    rewrite Zlength_app. rewrite Zlength_cons, Zlength_nil. lia.\n    split. rewrite app_Znth1 by lia. apply H11.\n    destruct H11. apply (Z.lt_le_trans _ (find popped_vertices v 0)). auto. apply find_app_le.\n    intros. rewrite find_notIn in H13 by auto. rewrite Z.add_0_r, sublist_same in H13 by auto.\n    apply in_app_or in H13. destruct H13. apply H12.\n    rewrite find_notIn. rewrite Z.add_0_r, sublist_same by auto.\n    auto. unfold not; intros; apply n. apply in_or_app; left; auto.\n    destruct H13. 2: contradiction. subst u0.\n    (*but elabel g (eformat (u,v)) = inf because it's invalid*)\n    assert (~ evalid g (eformat (u,v))). unfold not; intros; apply H8. rewrite eformat_adj; auto.\n    apply (invalid_edge_weight g) in H13.\n    repeat rewrite <- (@graph_to_mat_eq size) by lia.\n    replace (Znth u (Znth v (@graph_to_symm_mat size g))) with inf.\n    rewrite graph_to_mat_eq by lia. apply weight_inf_bound.\n    rewrite <- (@graph_to_mat_eq size) in H13 by lia.\n    symmetry. assumption. \n  }\n  assert (Hheavy2: forall v : Z, 0 <= v < size -> Znth v parents' = size ->\n    forall u0 : V, In u0 (sublist 0 (find (popped_vertices +:: u) v 0) (popped_vertices +:: u)) ->\n    ~ adjacent g u0 v). {\n    intros. destruct (in_dec V_EqDec v (popped_vertices+::u)).\n    apply in_app_or in i; destruct i.\n    rewrite find_app_In1 in H7 by auto. rewrite sublist_app1 in H7.\n    2: pose proof (find_lbound popped_vertices v 0); lia.\n    2: { rewrite find_ubound, Z.add_0_r. apply Z.le_refl. }\n    apply Hinv_8. lia. 2: auto.\n    replace (Znth v parents) with (Znth v parents'). auto. apply Hinv2_1. lia.\n    right; apply in_or_app; left; auto.\n    (*v=u, pretty much same deal*)\n    destruct H8. 2: contradiction. subst v. rewrite find_app_notIn1, find_cons, Z.add_0_r in H7 by auto.\n    rewrite sublist_app1 in H7. 2: { pose proof (Zlength_nonneg popped_vertices). split. lia. auto. }\n    2: apply Z.le_refl.\n    (*rewrite sublist_same in H7 by auto.*)\n    apply Hinv_8. lia. replace (Znth u parents) with (Znth u parents'); auto.\n    rewrite find_notIn_0; auto.\n    (*v unpopped, means u0 in popped or u0=u. Former: Hinv_8. Latter:?*)\n    rewrite find_notIn, Z.add_0_r, sublist_same in H7 by auto.\n    apply in_app_or in H7; destruct H7.\n    destruct (adjacent_dec g u v).\n    replace (Znth v parents') with (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents) in H6.\n    2: { symmetry; apply Hinv2_2; auto. }\n    rewrite <- (@graph_to_mat_eq size) in H6 by lia. destruct (Znth u (Znth v (@graph_to_symm_mat size g)) <? Znth v upd_pq_state).\n    assert (vvalid g u). apply adjacent_requires_vvalid in H8. apply H8. rewrite vert_bound in H9. lia.\n    apply Hinv_8. lia. lia. rewrite find_notIn_0, sublist_same; auto.\n    unfold not; intros; apply n; apply in_or_app; left; auto.\n    (*not adjacent: rewrite parents' into parents*)\n    replace (Znth v parents') with (Znth v parents) in H6. 2: { symmetry; apply Hinv2_1. lia. auto. }\n    apply Hinv_8. lia. lia. rewrite find_notIn_0, sublist_same; auto.\n    unfold not; intros; apply n; apply in_or_app; left; auto.\n    (*u0=u*)\n    destruct H7. 2: contradiction. subst u0.\n    destruct (adjacent_dec g u v). 2: auto.\n    replace (Znth v parents') with (if elabel g (eformat (u, v)) <? Znth v upd_pq_state then u else Znth v parents) in H6.\n    2: { symmetry; apply Hinv2_2; auto. }\n    rewrite <- (@graph_to_mat_eq size) in H6 by lia. destruct (Znth u (Znth v (@graph_to_symm_mat size g)) <? Znth v upd_pq_state) eqn:bool.\n    assert (vvalid g u). apply adjacent_requires_vvalid in H7. apply H7. rewrite vert_bound in H8. lia.\n    rewrite eformat_adj, evalid_inf_iff, <- (@graph_to_mat_eq size) in H7 by lia.\n    rewrite Z.ltb_ge in bool. unfold upd_pq_state in bool.\n    rewrite upd_Znth_diff in bool. rewrite Hinv_6 in bool by lia.\n    destruct (in_dec V_EqDec v popped_vertices). exfalso; apply n; apply in_or_app; left; auto.\n    rewrite Hinv_5 in bool by lia. destruct (V_EqDec v r).\n    hnf in e; subst v. exfalso; apply n. apply hd_error_In. apply Hpopped_unnil.\n    unfold not; intros. assert (In u (popped_vertices+::u)). apply in_or_app; right; left; auto.\n    rewrite H8 in H9; contradiction.\n    assert (elabel g (eformat (v,Znth v parents)) = inf). apply (invalid_edge_weight g).\n    unfold not; intros. apply eformat_evalid_vvalid in H8. destruct H8. rewrite H6 in H9. rewrite vert_bound in H9. lia.\n    rewrite H8 in bool. lia.\n    replace (Zlength pq_state) with size; lia.\n    replace (Zlength pq_state) with size; lia.\n    unfold not; intros; subst v. apply n; apply in_or_app; right; left; auto.\n  }\n  assert (Hweight: forall v u1 u2 : V,\n          In v (popped_vertices +:: u) ->\n          0 <= Znth v parents' < size ->\n          vvalid g u2 ->\n          In u1 (sublist 0 (find (popped_vertices +:: u) v 0) (popped_vertices +:: u)) ->\n          ~ In u2 (sublist 0 (find (popped_vertices +:: u) v 0) (popped_vertices +:: u)) ->\n          elabel g (eformat (v, Znth v parents')) <= elabel g (eformat (u1, u2))\n  ). { intros.\n    assert (0 <= v < size). {\n      apply in_app_or in H5. destruct H5. rewrite <- (vert_bound g). apply Hpopped_vvalid. auto.\n      destruct H5. 2: contradiction. subst u; auto. }\n    replace (Znth v parents') with (Znth v parents) in *. 2: { symmetry; apply (Hinv2_1 v); auto. }\n    apply in_app_or in H5. destruct H5.\n    (*case was already in popped vertices*)\n    rewrite find_app_In1 in H8, H9 by auto. rewrite sublist_app1 in H8, H9.\n      2: pose proof (find_lbound popped_vertices v 0); lia.\n      2: { pose proof (find_ubound popped_vertices v 0). rewrite Z.add_0_r in H11. auto. }\n      2: pose proof (find_lbound popped_vertices v 0); lia.\n      2: { pose proof (find_ubound popped_vertices v 0). rewrite Z.add_0_r in H11. auto. }\n    apply Hinv_14; auto.\n    (*case v = u*)\n    destruct H5. 2: contradiction. subst v.\n    assert ((sublist 0 (find (popped_vertices +:: u) u 0) (popped_vertices +:: u)) =\n      (popped_vertices)).\n    { rewrite find_app_notIn1, find_cons, Z.add_0_r by auto.\n         rewrite sublist_app1, sublist_same. auto. auto. auto.\n          pose proof (Zlength_nonneg popped_vertices). split. lia. auto.\n          apply Z.le_refl.\n    } rewrite H5 in H9, H8.\n    (*make use of Hu_min\n      case u2 = u: then apply Hheavy, done (guess it wasn't useless after all)\n      case u2 <> u: then by Hu_min, Znth u pq_state <= Znth u2 pq_state\n        u2 is unpopped, so by Hinv_6, Znth u2 pq_state = Znth v keys\n        u2 can't be r, so by Hinv_5, Znth v keys = elabel g (eformat (u2, Znth u2 parents))\n        ===> Znth u pq_state <= elabel g (eformat (u2, Znth u2 parents))\n        using Hheavy again? and Z.le_trans, Znth u pq_state <= elabel g (eformat (u1, u2))\n        subcase u = r a.k.a. popped_vertices = []: then contradiction on u1 being in empty\n        Then Znth u pq_state = Znth v keys = elabel g (eformat (u,Znth u parents)). Apply\n    *)\n    destruct (V_EqDec u2 u). hnf in e. subst u2.\n    assert ((forall u0 : V,\n          In u0 (sublist 0 (find (popped_vertices +:: u) u 0) (popped_vertices +:: u)) ->\n          elabel g (eformat (u, Znth u parents')) <= elabel g (eformat (u0, u)))).\n    apply Hheavy; lia. rewrite Hu_parents in H11. apply H11. rewrite H5. auto.\n    rewrite vert_bound in H7. assert (vvalid g u1). apply Hpopped_vvalid; auto. rewrite vert_bound in H11.\n    assert (0 <= Znth u2 parents <= size). apply Hinv_4; lia. destruct H12.\n    apply Z.le_lteq in H13. destruct H13.\n    2: { assert (~ adjacent g u1 u2). apply Hinv_8. lia. lia.\n          rewrite find_notIn, Z.add_0_r, sublist_same by auto. auto.\n        rewrite eformat_adj in H14. apply (invalid_edge_weight g) in H14.\n        replace (elabel g (eformat (u1, u2))) with inf\n          by trivial.\n        apply weight_inf_bound. }\n    (*u2 <> u*) unfold RelationClasses.complement, Equivalence.equiv in c.\n    assert (Znth u pq_state <= Znth u2 pq_state). apply Hu_min; lia.\n    rewrite (Hinv_6 u2) in H14 by lia. destruct (in_dec V_EqDec u2 popped_vertices). contradiction.\n    clear n. rewrite Hinv_5 in H14. destruct (V_EqDec u2 r).\n    hnf in e. subst u2. destruct popped_vertices. contradiction. exfalso; apply H9.\n    apply hd_error_In. apply Hr2. unfold not; intros. assert (In v (v::popped_vertices)) by (left; auto).\n    rewrite H15 in H16; contradiction.\n    unfold RelationClasses.complement, Equivalence.equiv in c0.\n    assert (elabel g (eformat (u2, Znth u2 parents)) <= elabel g (eformat (u1,u2))).\n      apply Hinv_7. lia. lia. rewrite find_notIn, Z.add_0_r, sublist_same by auto. auto. 2: auto.\n    apply (Z.le_trans _ (elabel g (eformat (u2, Znth u2 parents)))). 2: auto.\n    apply (Z.le_trans _ (Znth u pq_state)). 2: auto.\n    clear H14 H15.\n    rewrite Hinv_6 by lia. destruct (in_dec V_EqDec u popped_vertices). contradiction.\n    rewrite Hinv_5 by lia. destruct (V_EqDec u r).\n    hnf in e; subst u. destruct popped_vertices. contradiction. exfalso; apply n.\n    apply hd_error_In. apply Hr2. unfold not; intros. assert (In v (v::popped_vertices)). left; auto.\n    rewrite H14 in H15; contradiction.\n    apply Z.le_refl.\n  }\n  (*now split into cases*)\n  apply Z.le_lteq in H4. destruct H4.\n  ++ (*adde case*)\n  assert (vvalid mst' u). apply vert_bound. lia.\n  assert (vvalid mst' (Znth u parents)). apply vert_bound. lia.\n  assert (evalid g (eformat (u,(Znth u parents)))). apply Hinv_7; lia.\n  assert (Hfst: vvalid mst' (fst (eformat (u,(Znth u parents))))). {\n    destruct (Z.le_ge_cases u (Znth u parents)). rewrite eformat1; simpl; auto.\n    rewrite eformat2; simpl; auto.\n  }\n  assert (Hsnd: vvalid mst' (snd (eformat (u,(Znth u parents))))). {\n    destruct (Z.le_ge_cases u (Znth u parents)). rewrite eformat1; simpl; auto.\n    rewrite eformat2; simpl; auto.\n  }\n  assert (Hfst_le_snd: (fst (eformat (u,Znth u parents))) <= (snd (eformat (u,Znth u parents)))). {\n    destruct (Z.le_ge_cases u (Znth u parents)). rewrite eformat1; simpl; auto.\n    rewrite eformat2; simpl; auto.\n  }\n  assert (Int.min_signed <= elabel g (eformat (u,(Znth u parents))) < inf). {\n    split. apply weight_representable. apply evalid_inf_iff; auto.\n  }\n  assert (Hu_evalid: ~ evalid mst' (eformat (u,(Znth u parents)))). {\n    unfold not; intros. apply (Hinv_13 u (Znth u parents)).\n    auto. rewrite eformat_adj. auto.\n  }\n  assert (Huparents_popped: In (Znth u parents) popped_vertices). {\n    assert (exists i : Z, 0 <= i < Zlength (popped_vertices) /\\\n      Znth i (popped_vertices) = Znth u parents /\\ i < find popped_vertices u 0).\n    apply Hinv_7; lia. destruct H9 as [i [? [? ?]]]. rewrite <- H10. apply Znth_In. lia.\n  }\n  assert (Huparents_unpopped: ~ In (Znth u parents) unpopped_vertices). {\n    apply (NoDup_app_not_in V popped_vertices). apply (Permutation_NoDup (l:=VList g)).\n    apply Permutation_sym; apply Hinv_3. apply NoDup_VList. auto.\n  }\n  set (adde_u:=adde mst' (fst (eformat (u,Znth u parents))) (snd (eformat (u,Znth u parents))) Hfst Hsnd Hfst_le_snd (elabel g (eformat (u,(Znth u parents)))) H8).\n  Exists (adde_u).\n  Exists (finGraph adde_u).\n  Exists parents' keys' pq_state' (popped_vertices+::u) (remove V_EqDec u unpopped_vertices).\n  assert (HM: exists M : UAdjMatGG, minimum_spanning_forest M g /\\ is_partial_lgraph adde_u M). {\n    destruct Hinv_15 as [M [Hmsf_M Hpartial_M]]. pose proof (finGraph M).\n    destruct (evalid_dec M (eformat (u, Znth u parents))).\n    ****\n      exists M. split. auto. apply adde_partial_lgraph; auto. rewrite <- surjective_pairing; auto.\n      rewrite <- surjective_pairing. symmetry. apply Hmsf_M; auto.\n    ****\n      set (a:=eformat (u, Znth u parents)) in *.\n      (*find a corresponding edge b in M, show that elabel g a <= elabel g b\n        Then do a swap\n      *)\n      assert (connected M (Znth u parents) u). apply Hmsf_M. apply adjacent_connected. exists a.\n        split. apply (evalid_strong_evalid g); auto.\n        rewrite (edge_src_fst g), (edge_dst_snd g); auto.\n        unfold a; destruct (Z.le_ge_cases u (Znth u parents)). rewrite eformat1 by (simpl; auto).\n        simpl. right. auto.\n        rewrite eformat2 by (simpl; auto). simpl. left; auto.\n      destruct H9 as [p ?].\n      (*for convenience's sake, simplify*)\n      apply (connected_by_upath_exists_simple_upath) in H9. clear p. destruct H9 as [p [? ?]].\n      (*since Znth u parents is in popped and u isn't, use the partition to find a v1 v2*)\n      pose proof (finGraph M) as fM.\n      assert (exists l, fits_upath M l p). apply connected_exists_list_edges in H9; auto. destruct H11 as [l Hl].\n      assert (exists v1 v2, In v1 p /\\ In v2 p /\\ In v1 popped_vertices /\\ ~ In v2 popped_vertices /\\ (exists e, adj_edge M e v1 v2 /\\ In e l)).\n        apply (path_partition_checkpoint2 M popped_vertices p l (Znth u parents) u); auto.\n      destruct H11 as [v1 [v2 [? [? [? [? ?]]]]]].\n      destruct H15 as [b [Hc Hbl]]. assert (b = eformat (v1, v2)). {\n        destruct Hmsf_M. destruct H15. destruct H15. destruct H18. destruct H18. destruct H20. apply (H20 v1 v2 b (eformat (v1,v2))).\n        split. auto. apply eformat_adj'. rewrite <- eformat_adj. exists b; auto.\n      } subst b. assert (evalid M (eformat (v1,v2))). apply Hc.\n      assert (In v2 unpopped_vertices).\n        destruct (Hpopped_or_unpopped v2). rewrite vert_bound, <- (vert_bound M).\n        apply eformat_evalid_vvalid in H15; apply H15. contradiction. auto.\n      set (b:= eformat (v1,v2)) in *. clear Hc. assert (Hbl': In b l) by auto.\n      apply (fits_upath_split2 M p l b (Znth u parents) u) in Hbl'; auto.\n      destruct Hbl' as [p1 [p2 [l1 [l2 [Hp [Hp1p2 [Hl1 [Hl2 Hl']]]]]]]].\n      assert ((sublist 0 (find (popped_vertices +:: u) u 0) (popped_vertices +:: u)) = popped_vertices). {\n        rewrite find_app_notIn1, find_cons, Z.add_0_r by auto.\n        rewrite sublist_app1, sublist_same. auto. auto. auto.\n        pose proof (Zlength_nonneg popped_vertices). split. lia. auto.\n        apply Z.le_refl.\n      }\n      assert (elabel g a <= elabel g b). {\n        unfold b; unfold a. rewrite <- Hu_parents. apply Hweight; auto.\n        apply in_or_app; right; left; auto. rewrite Hu_parents; lia.\n        all: rewrite H17; auto.\n      } clear H17.\n      assert (~ evalid mst' b). {\n        unfold not; intros. rewrite <- EList_evalid in H17.\n        apply (Permutation_in (l':=(map (fun v : Z => eformat (v, Znth v parents))\n              (filter (fun v : Z => Znth v parents <? size) popped_vertices)))) in H17.\n        apply list_in_map_inv in H17. destruct H17 as [x [? ?]]. rewrite filter_In in H19. destruct H19.\n        assert (In (Znth x parents) popped_vertices). {\n          rewrite H17 in H15. apply eformat_evalid_vvalid in H15. do 2 rewrite vert_bound in H15.\n          assert ((exists i : Z,\n            0 <= i < Zlength popped_vertices /\\\n            Znth i popped_vertices = Znth x parents /\\ i < find popped_vertices x 0) /\\\n           (forall u : V,\n            In u (sublist 0 (find popped_vertices x 0) popped_vertices) ->\n            elabel g (eformat (x, Znth x parents)) <= elabel g (eformat (u, x)))). apply Hinv_7.\n          apply H15. apply H15. destruct H21. clear H22. destruct H21 as [i [? [? ?]]].\n          rewrite <- H22; apply Znth_In. lia.\n        }\n        (*now compare v1, v2, x, Znth x parents*)\n        unfold b in H17. apply eformat_eq in H17. destruct H17; destruct H17; subst v1; subst v2; contradiction.\n        apply Hinv_9.\n      }\n      clear Hinv_1 Hinv_2 Hinv_3 Hinv_4 Hinv_5 Hinv_6 Hinv_7 Hinv_8 Hinv_9 Hinv_10 Hr1 Hr2 Hinv_13 Hinv_14.\n      clear Hinv2_1 Hinv2_2 Hinv2_3 Hparents_bound Hkeys' Hpq_state' Hheavy Hheavy2 Hweight Hpopped_nil Hpopped_unnil.\n      clear Hpopped_or_unpopped Hpopped_vvalid Hunpopped_vvalid Hu_not_popped Hu_unpopped Hur Hu_min HZlength_parents HZlength_keys HZlength_pq_state Hu_parents Hu_keys Hu_pq_state Huparents_popped Huparents_unpopped.\n      set (remove_b:= eremove M b). (*huh, how come I don't need to provide evalid b?*)\n      assert (Ha_fst_vvalid: vvalid remove_b (fst a)). {\n        unfold a; simpl. destruct (Z.le_ge_cases u (Znth u parents)).\n        rewrite eformat1 by auto; simpl. rewrite vert_bound; lia.\n        rewrite eformat2 by auto; simpl. rewrite vert_bound; lia.\n      }\n      assert (Ha_snd_vvalid: vvalid remove_b (snd a)). {\n        unfold a; simpl. destruct (Z.le_ge_cases u (Znth u parents)).\n        rewrite eformat1 by auto; simpl. rewrite vert_bound; lia.\n        rewrite eformat2 by auto; simpl. rewrite vert_bound; lia.\n      }\n      assert (Ha_fst_le_snd: fst a <= snd a). {\n        unfold a; destruct (Z.le_ge_cases u (Znth u parents)).\n        rewrite eformat1; simpl; auto.\n        rewrite eformat2; simpl; auto.\n      }\n      set (w:=elabel g a).\n      assert (Ha_weight_bound: Int.min_signed <= w < inf). {\n        split. apply weight_representable. apply evalid_inf_iff; auto.\n      }\n      set (swap:=adde remove_b (fst a) (snd a) Ha_fst_vvalid Ha_snd_vvalid Ha_fst_le_snd w Ha_weight_bound).\n      assert (Hadde_partial_swap: is_partial_lgraph adde_u swap). {\n        unfold is_partial_lgraph; split. split. 2: split3.\n        intros. rewrite vert_bound; rewrite vert_bound in H19. lia.\n        intros. simpl. simpl in H19. simpl. unfold graph_gen.addValidFunc, graph_gen.removeValidFunc in *.\n        destruct H19. left. split. apply Hpartial_M. auto. unfold not; intros; subst e. contradiction. right; auto.\n        intros. rewrite (edge_src_fst swap); rewrite (edge_src_fst adde_u); auto.\n        intros. rewrite (edge_dst_snd swap); rewrite (edge_dst_snd adde_u); auto.\n        unfold preserve_vlabel, preserve_elabel; split; intros.\n        destruct vlabel. destruct vlabel. auto.\n        simpl. simpl in H19. unfold graph_gen.addValidFunc in H19. unfold graph_gen.update_elabel.\n        rewrite <- surjective_pairing.\n        unfold EquivDec.equiv_dec. destruct (E_EqDec a e). unfold w. auto.\n        unfold RelationClasses.complement, Equivalence.equiv in c. destruct H19.\n        destruct (E_EqDec e b). hnf in e0; subst e. contradiction.\n        apply Hpartial_M; auto.\n        rewrite <- surjective_pairing in H19; symmetry in H19; contradiction.\n      }\n      assert (NoDup l). apply (simple_upath_list_edges_NoDup M p l); auto.\n      assert (~ In b l1). { rewrite Hl' in H19.\n        assert (forall y, In y l1 -> ~ In y ([b] ++l2)). apply NoDup_app_not_in; auto.\n        unfold not; intros. apply H20 in H21. apply H21. apply in_or_app; left; left; auto.\n      }\n      assert (~ In b l2). { rewrite Hl' in H19. apply NoDup_app_r in H19.\n        unfold not; intros. apply (NoDup_app_not_in E [b] l2) in H21; auto. left; auto.\n      }\n      assert (Hp1l1_remove: fits_upath remove_b l1 p1). { apply (fits_upath_transfer' p1 l1 M).\n        intros. do 2 rewrite vert_bound; split; auto.\n        intros. simpl. unfold graph_gen.removeValidFunc.\n        split. apply (fits_upath_evalid M p1 l1); auto. unfold not; intros; subst e; contradiction.\n        intros. simpl. auto.\n        intros. simpl. auto.\n        auto.\n      }\n      assert (Hp2l2_remove: fits_upath remove_b l2 p2). { apply (fits_upath_transfer' p2 l2 M).\n        intros. do 2 rewrite vert_bound; split; auto.\n        intros. simpl. unfold graph_gen.addValidFunc, graph_gen.removeValidFunc.\n        split. apply (fits_upath_evalid M p2 l2); auto. unfold not; intros; subst e; contradiction.\n        intros. simpl. auto.\n        intros. simpl. auto.\n        auto.\n      }\n      assert (Hp1p2': (connected_by_path remove_b p1 (Znth u parents) (fst b) /\\ connected_by_path remove_b p2 (snd b) u) \\/\n        (connected_by_path remove_b p1 (Znth u parents) (snd b) /\\ connected_by_path remove_b p2 (fst b) u)). {\n        rewrite (edge_src_fst M), (edge_dst_snd M) in Hp1p2.\n        destruct Hp1p2; [left | right].\n        destruct H22. split. split. apply (fits_upath_valid_upath remove_b p1 l1); auto. apply H22.\n        split. apply (fits_upath_valid_upath remove_b p2 l2); auto. apply H23.\n        destruct H22. split. split. apply (fits_upath_valid_upath remove_b p1 l1); auto. apply H22.\n        split. apply (fits_upath_valid_upath remove_b p2 l2); auto. apply H23.\n      }\n      assert (labeled_spanning_uforest swap g). {\n        assert (is_partial_lgraph swap g). {\n          assert (Hedge_valid: forall e, evalid swap e -> evalid g e).\n          intros. simpl in H22. unfold graph_gen.addValidFunc, graph_gen.removeValidFunc in H22. destruct H22.\n          destruct H22. apply Hmsf_M. auto. rewrite <- surjective_pairing in H22. subst e. auto.\n          split. split. 2: split3.\n          intros. rewrite vert_bound; rewrite vert_bound in H22. lia. auto.\n          intros. rewrite (edge_src_fst swap), (edge_src_fst g); auto.\n          intros. rewrite (edge_dst_snd swap), (edge_dst_snd g); auto.\n          unfold preserve_vlabel, preserve_elabel; split; intros. destruct vlabel; destruct vlabel; auto.\n          simpl. unfold graph_gen.update_elabel, EquivDec.equiv_dec. rewrite <- surjective_pairing.\n          simpl in H22. unfold graph_gen.addValidFunc, graph_gen.removeValidFunc in H22.\n          destruct (E_EqDec a e). hnf in e0; subst e. unfold w; auto.\n          unfold RelationClasses.complement, Equivalence.equiv in c. destruct H22.\n          destruct H22. destruct (E_EqDec e b). hnf in e0; subst e. contradiction.\n          apply Hmsf_M; auto.\n          symmetry in H22; rewrite <- surjective_pairing in H22; contradiction.\n        }\n        assert (uforest' swap). {\n          assert (uforest' remove_b /\\ ~ connected remove_b (src M b) (dst M b)). {\n            apply remove_edge_uforest'. apply Hmsf_M. auto. }\n          destruct H23. rewrite (edge_src_fst M), (edge_dst_snd M) in H24.\n          apply add_edge_uforest'; auto.\n          unfold not; intros; destruct H25 as [pa ?]. apply H24. clear H24.\n          destruct Hp1p2'.\n          ++destruct H24. apply (connected_trans _ _ (Znth u parents)). apply connected_symm; exists p1; auto.\n            apply (connected_trans _ _ u). unfold a in H25. destruct (Z.le_ge_cases u (Znth u parents)).\n            rewrite eformat1 in H25 by auto. apply connected_symm; exists pa; apply H25.\n            rewrite eformat2 in H25 by auto. exists pa; apply H25.\n            apply connected_symm; exists p2; apply H26.\n          ++destruct H24. apply (connected_trans _ _ u). exists p2; auto.\n            apply (connected_trans _ _ (Znth u parents)). unfold a in H25. destruct (Z.le_ge_cases u (Znth u parents)).\n            rewrite eformat1 in H25 by auto. exists pa; apply H25.\n            rewrite eformat2 in H25 by auto. apply connected_symm; exists pa; apply H25.\n            exists p1; auto.\n        }\n        assert (Hremove_a: ~ evalid remove_b a). { unfold not; intros. apply n.\n          simpl in H24. unfold graph_gen.removeValidFunc in H24. apply H24. }\n        assert (Hswap_a: evalid swap a). { simpl. rewrite <- surjective_pairing.\n          unfold graph_gen.addValidFunc. right; auto. }\n        assert (Hconnected_b: connected swap (fst b) (snd b)). {\n          destruct Hp1p2'; destruct H24.\n          ++apply (connected_trans _ _ (Znth u parents)).\n          apply connected_symm; exists p1. split. 2: apply H24.\n          apply add_edge_valid_upath. rewrite <- surjective_pairing; auto. apply H24.\n          apply (connected_trans _ _ u). apply adjacent_connected. rewrite eformat_adj, eformat_symm. auto.\n          apply connected_symm; exists p2. split. 2: apply H25.\n          apply add_edge_valid_upath. rewrite <- surjective_pairing; auto. apply H25.\n          ++apply (connected_trans _ _ u).\n          exists p2. split. 2: apply H25.\n          apply add_edge_valid_upath. rewrite <- surjective_pairing; auto. apply H25.\n          apply (connected_trans _ _ (Znth u parents)). apply adjacent_connected. rewrite eformat_adj; auto.\n          exists p1. split. 2: apply H24.\n          apply add_edge_valid_upath. rewrite <- surjective_pairing; auto. apply H24.\n        } clear Hp1p2' Hp1p2.\n        split. split. apply H22. split. auto.\n        (*spanning*) { unfold spanning; intros x y.\n          split; intros. 2: apply (is_partial_lgraph_connected swap); auto.\n          apply Hmsf_M in H24.\n          destruct H24 as [p' ?]. apply (connected_by_upath_exists_simple_upath) in H24.\n          clear p'. destruct H24 as [p' [? ?]].\n          assert (exists l', fits_upath M l' p'). apply valid_upath_exists_list_edges. apply H24.\n          destruct H26 as [l' ?]. assert (NoDup l'). apply (simple_upath_list_edges_NoDup M p'); auto.\n          clear H H0 H1.\n          destruct (in_dec E_EqDec b l').\n          ++ (*b is in l', must take detour*)\n          assert (In b l'); auto. apply (fits_upath_split2 M p' l' b x y) in H; auto.\n          destruct H as [p1x [p2y [l1x [l2y [? [? [? [? ?]]]]]]]]. subst l'; subst p'.\n          rewrite (edge_src_fst M), (edge_dst_snd M) in H0.\n          assert (~ In b l1x). { unfold not; intros. apply (NoDup_app_not_in _ l1x ([b]++l2y) H27 b) in H. apply H. apply in_or_app; left; left; auto. }\n          assert (~ In b l2y). { apply NoDup_app_r in H27. apply (NoDup_app_not_in _ [b] l2y H27 b). left; auto. }\n          destruct H0; destruct H0.\n          ++++\n          apply (connected_trans _ _ (fst b)). exists p1x. split. 2: apply H0. apply add_edge_valid_upath.\n            rewrite <- surjective_pairing; auto. apply (remove_edge_valid_upath _ _ _ l1x); auto. apply H0.\n          apply (connected_trans _ _ (snd b)); auto.\n          exists p2y. split. 2: apply H30. apply add_edge_valid_upath. rewrite <- surjective_pairing; auto.\n          apply (remove_edge_valid_upath _ _ _ l2y); auto. apply H30.\n          ++++\n          apply (connected_trans _ _ (snd b)). exists p1x. split. 2: apply H0. apply add_edge_valid_upath.\n            rewrite <- surjective_pairing; auto. apply (remove_edge_valid_upath _ _ _ l1x); auto. apply H0.\n          apply (connected_trans _ _ (fst b)); apply connected_symm; auto.\n          apply connected_symm. exists p2y. split. 2: apply H30. apply add_edge_valid_upath. rewrite <- surjective_pairing; auto.\n          apply (remove_edge_valid_upath _ _ _ l2y); auto. apply H30.\n          ++ (*b isn't in l', transfer path*)\n          exists p'. split. 2: apply H24. apply add_edge_valid_upath. rewrite <- surjective_pairing; auto.\n          apply (remove_edge_valid_upath _ _ _ l'); auto. apply H24.\n        }\n        (*preserve labels*) unfold preserve_vlabel, preserve_elabel; split; intros.\n        destruct vlabel; destruct vlabel; auto.\n        simpl; simpl in H24. unfold graph_gen.addValidFunc, graph_gen.removeValidFunc in H24.\n        unfold graph_gen.update_elabel, EquivDec.equiv_dec.\n        rewrite <- surjective_pairing. rewrite <- surjective_pairing in H24.\n        destruct (E_EqDec a e). hnf in e0. subst e. unfold w; auto.\n        unfold RelationClasses.complement, Equivalence.equiv in c. destruct H24. 2: symmetry in H24; contradiction.\n        destruct H24. destruct (E_EqDec e b). hnf in e0; contradiction. apply Hmsf_M; auto.\n      }\n      exists swap. split; auto. apply (msf_if_le_msf' swap M g); auto.\n      unfold sum_DE, DEList. pose proof (finGraph swap) as fswap.\n      rewrite (map_ext_in (elabel swap) (elabel g)).\n      rewrite (map_ext_in (elabel M) (elabel g)).\n      rewrite (fold_left_comm _ (map (elabel g) (EList swap)) (map (elabel g) (a::(remove E_EqDec b (EList M))))).\n      simpl.\n      (**) {\n        set (k:=EList M).\n        rewrite fold_left_accum_Zadd.\n        rewrite fold_left_Zadd_map_remove. 2: unfold k; rewrite EList_evalid; auto. 2: unfold k; apply NoDup_EList.\n        apply (Z.le_trans _ (fold_left Z.add (map (elabel g) k) 0 - elabel g b + elabel g b)).\n        apply Zplus_le_compat_l. auto.\n        rewrite Z.sub_add. apply Z.eq_le_incl. (*and... I can't reflexivity!*)\n        apply fold_left_comm. intros; lia.\n        apply Permutation_map. unfold k. apply NoDup_Permutation. apply NoDup_EList. apply NoDup_EList.\n        intros. do 2 rewrite EList_evalid. split; intros; auto.\n      }\n      intros; lia.\n      apply Permutation_map. { apply NoDup_Permutation. apply NoDup_EList.\n        apply NoDup_cons. unfold not; intros. rewrite remove_In_iff in H23. destruct H23.\n        rewrite EList_evalid in H23. contradiction.\n        apply nodup_remove_nodup. apply NoDup_EList.\n        intros. rewrite EList_evalid; simpl; unfold graph_gen.addValidFunc, graph_gen.removeValidFunc.\n        rewrite remove_In_iff, EList_evalid, <- surjective_pairing. split; intros; destruct H23; auto.\n      }\n      { intros. rewrite EList_evalid in H23. apply Hmsf_M; auto. }\n      {  intros. rewrite EList_evalid in H23. apply H22; auto. }\n  }\n  assert (Hpartial: is_partial_lgraph adde_u g). {\n    apply adde_partial_lgraph. auto. rewrite <- surjective_pairing; auto. rewrite <- surjective_pairing; auto. }\n  assert (Huforest_adde: uforest' adde_u). {\n    apply add_edge_uforest'; auto.\n    unfold not; intros. destruct (Z.le_ge_cases u (Znth u parents)).\n      ****\n      rewrite eformat1 in *; try (simpl; lia).\n      destruct H9 as [p [? [? ?]]]. destruct p. inversion H11.\n      destruct p. inversion H11; inversion H12. subst v.\n      rewrite H15 in Hu_unpopped; contradiction.\n      destruct H9. inversion H11. subst v.\n      apply (Hinv_13 u v0). auto. apply H9.\n      ****\n      rewrite eformat2 in *; try (simpl; lia).\n      simpl in H9. apply connected_symm in H9.\n      destruct H9 as [p [? [? ?]]]. destruct p. inversion H11.\n      destruct p. inversion H11; inversion H12. subst v.\n      rewrite H15 in Hu_unpopped; contradiction.\n      destruct H9. inversion H11. subst v.\n      apply (Hinv_13 u v0). auto. apply H9.\n  }\n  assert (Hu_new: evalid adde_u (eformat (u, Znth u parents))). {\n    simpl. unfold graph_gen.addValidFunc. right; rewrite <- surjective_pairing. auto. }\n  assert (Hsrc: src adde_u (eformat (u, Znth u parents)) = fst (eformat (u, Znth u parents))). {\n    apply (edge_src_fst adde_u). }\n  assert (Hdst: dst adde_u (eformat (u, Znth u parents)) = snd (eformat (u, Znth u parents))). {\n    apply (edge_dst_snd adde_u). }\n  assert (Hnot_adj: forall u0 v : V, In u0 (remove V_EqDec u unpopped_vertices) -> ~ adjacent adde_u u0 v). {\n    intros. rewrite remove_In_iff in H9; destruct H9.\n    assert (~ adjacent mst' u0 v). apply Hinv_13. auto.\n    unfold not; intros. destruct H12 as [e ?]. destruct (E_EqDec (eformat (u,Znth u parents)) e).\n    hnf in e0. subst e.\n    destruct H12. rewrite Hsrc, Hdst in H13.\n    destruct (Z.le_ge_cases u (Znth u parents)).\n      rewrite eformat1 in H13 by (simpl; lia). simpl in H13.\n      destruct H13; destruct H13. symmetry in H13; contradiction.\n      subst u0. contradiction.\n      rewrite eformat2 in H13 by (simpl; lia). simpl in H13.\n      destruct H13; destruct H13. subst u0; contradiction.\n      symmetry in H15; contradiction.\n    unfold RelationClasses.complement, Equivalence.equiv in c. apply H11.\n    exists e. apply add_edge_adj_edge2 in H12; auto.\n    rewrite <- surjective_pairing; auto.\n  }\n  assert (Hconnnected: (forall u0 v : V,\n    In u0 (popped_vertices +:: u) ->\n    In v (popped_vertices +:: u) -> connected g u0 v <-> connected adde_u u0 v)). {\n    intros. apply in_app_or in H9; apply in_app_or in H10. destruct H9; destruct H10.\n    ****(*both in popped vertices, reuse invariant*)\n        split; intros.\n        apply Hinv_10 in H11; auto. apply add_edge_connected; auto.\n        rewrite <- surjective_pairing; auto.\n        apply (is_partial_lgraph_connected adde_u); auto.\n    ****(*v=u*) destruct H10. 2: contradiction. subst v.\n        split; intros.\n        (*g -> adde*)\n        (* u0 is popped, so is Znth u parents, thus use invariant on them by adding eformat (u, Znth u parents) to the path\n            Then add it again to go back to u*)\n        apply (connected_trans adde_u u0 (Znth u parents) u).\n        apply add_edge_connected. rewrite <- surjective_pairing. auto.\n        rewrite <- Hinv_10; auto. apply (connected_trans g u0 u).\n        auto. apply adjacent_connected. rewrite eformat_adj. apply H7.\n        apply connected_symm. apply adjacent_connected. rewrite eformat_adj. auto.\n        (*adde -> g*)\n        apply (is_partial_lgraph_connected adde_u); auto.\n    ****(*u0=u, repeat of above*) destruct H9. 2: contradiction. subst u0. rename H10 into H9.\n        split; intros.\n        apply (connected_trans adde_u u (Znth u parents) v).\n        apply adjacent_connected. rewrite eformat_adj. auto.\n        apply add_edge_connected. rewrite <- surjective_pairing; auto.\n        rewrite <- Hinv_10; auto.\n        apply (connected_trans g (Znth u parents) u).\n        apply adjacent_connected. rewrite eformat_adj, eformat_symm. apply H7. auto.\n        apply (is_partial_lgraph_connected adde_u); auto.\n    ****destruct H9. 2: contradiction. destruct H10. 2: contradiction. subst u0. subst v.\n        split; intros; apply connected_refl; rewrite vert_bound; lia.\n  }\n  time \"end of pop loop (adde_u) (did not record original):\" entailer!.\n\n  remember (Zlength parents) as size.\n  clear H9 H10 H11 H12 H13 H14 H15 H16 H17 H18 H19 H20 H21 H22.\n\n  (*permutation of EList*)\n    apply (Permutation_trans (l':=(eformat (u,Znth u parents))::(EList mst'))).\n    apply Permutation_sym.\n    { apply NoDup_Permutation. apply NoDup_cons. rewrite EList_evalid; auto. apply NoDup_EList. apply NoDup_EList.\n      intros; split; intros. rewrite EList_evalid. simpl. unfold graph_gen.addValidFunc. destruct H9.\n      rewrite <- surjective_pairing. right; symmetry; auto. left; rewrite EList_evalid in H9; auto.\n      rewrite EList_evalid in H9; simpl in H9. unfold graph_gen.addValidFunc in H9; destruct H9.\n      right; rewrite EList_evalid; auto. left; symmetry; auto. rewrite <- surjective_pairing in H9; auto.\n    }\n    apply (Permutation_trans (l':=(eformat (u, Znth u parents)) :: (map (fun v : Z => eformat (v, Znth v parents))\n       (filter (fun v : Z => Znth v parents <? size) (popped_vertices))))).\n    { apply Permutation_cons. auto. apply Hinv_9. }\n    apply (Permutation_trans (l':=(map (fun v : Z => eformat (v, Znth v parents))\n       (filter (fun v : Z => Znth v parents <? size) (popped_vertices)))+::(eformat (u, Znth u parents)))).\n    { apply Permutation_cons_append. }\n    replace (map (fun v : Z => eformat (v, Znth v parents))\n       (filter (fun v : Z => Znth v parents <? size) popped_vertices) +:: \n     (eformat (u, Znth u parents))) with (map (fun v : Z => eformat (v, Znth v parents'))\n       (filter (fun v : Z => Znth v parents' <? size) (popped_vertices +:: u))). apply Permutation_refl.\n    replace [eformat (u,Znth u parents)] with (map (fun v : Z => eformat (v, Znth v parents)) [u]). 2: { simpl; auto. }\n    rewrite <- list_append_map.\n    replace (filter (fun v : Z => Znth v parents' <? size) (popped_vertices +:: u)) with (filter (fun v : Z => Znth v parents <? size) (popped_vertices +:: u)).\n    2: {\n      apply filter_ext_in. intros. replace (Znth a parents) with (Znth a parents'). auto.\n      apply Hinv2_1. 2: right; auto. apply in_app_or in H9; destruct H9.\n      rewrite <- (vert_bound g). apply Hpopped_vvalid; auto.\n      destruct H9. 2: contradiction. subst a; lia.\n    }\n    replace (filter (fun v : Z => Znth v parents <? size) popped_vertices +:: u) with (filter (fun v : Z => Znth v parents <? size) (popped_vertices +:: u)).\n    2: { rewrite filter_app. simpl. destruct (Znth u parents <? size) eqn: bool. auto.\n      rewrite Z.ltb_ge in bool; lia. }\n    apply map_ext_in; intros. rewrite filter_In in H9. destruct H9.\n    replace (Znth a parents) with (Znth a parents'). auto.\n    apply Hinv2_1.\n    rewrite <- (vert_bound g). apply in_app_or in H9. destruct H9.\n    apply Hpopped_vvalid; auto.\n    destruct H9. 2: contradiction. subst a. apply Hunpopped_vvalid; auto.\n    right; auto.\n  ++ (*Znth u keys = inf. Implies u has no other vertices from the mst that can connect to it. Thus, no change to graph*)\n  Exists mst' fmst' parents' keys' pq_state' (popped_vertices+::u) (remove V_EqDec u unpopped_vertices).\n  assert (Permutation (EList mst')\n      (map (fun v : Z => eformat (v, Znth v parents'))\n         (filter (fun v : Z => Znth v parents' <? size) (popped_vertices +:: u)))). {\n    replace (filter (fun v : Z => Znth v parents' <? size) (popped_vertices +:: u)) with\n      (filter (fun v : Z => Znth v parents' <? size) (popped_vertices)).\n    2: { rewrite filter_app. simpl. destruct (Znth u parents' <? size) eqn: bool.\n    rewrite Z.ltb_lt in bool; lia.\n    rewrite app_nil_r; auto. }\n    replace (filter (fun v : Z => Znth v parents' <? size) popped_vertices) with\n      (filter (fun v : Z => Znth v parents <? size) popped_vertices).\n    2: { apply filter_ext_in. intros.\n      replace (Znth a parents) with (Znth a parents'). auto.\n      apply Hinv2_1. rewrite <- (vert_bound g). apply Hpopped_vvalid; auto.\n      right; apply in_or_app; left; auto. }\n    replace (map (fun v : Z => eformat (v, Znth v parents'))\n     (filter (fun v : Z => Znth v parents <? size) popped_vertices)) with\n      (map (fun v : Z => eformat (v, Znth v parents))\n     (filter (fun v : Z => Znth v parents <? size) popped_vertices)). apply Hinv_9.\n    apply map_ext_in. intros. rewrite filter_In in H5. destruct H5.\n      replace (Znth a parents) with (Znth a parents'). auto.\n      apply Hinv2_1. rewrite <- (vert_bound g). apply Hpopped_vvalid; auto.\n      right; apply in_or_app; left; auto.\n  }\n  assert (Hconnected: forall u0 v : V,\n    In u0 (popped_vertices +:: u) ->\n    In v (popped_vertices +:: u) -> connected g u0 v <-> connected mst' u0 v). {\n    intros. apply in_app_or in H6; apply in_app_or in H7.\n    destruct H6; destruct H7.\n    ****(*both in popped_vertices*)apply Hinv_10; auto.\n    ****(*v=u*) destruct H7. 2: contradiction. subst v.\n      (*In this case, because Znth u parents = inf, NOTHING in popped_vertices should be connected to it in g or mst*)\n      split; intros.\n      (*get a contradiction about ~connected g u0 u*)\n      destruct H7 as [p ?].\n      apply (path_partition_checkpoint g popped_vertices unpopped_vertices p u0 u) in H7; auto.\n      destruct H7 as [v1 [v2 [? [? [? [? ?]]]]]].\n      (*\n        Znth v2 pq_state = keys, because it is unpopped\n        Znth v2 keys >= Znth u keys = inf, because u is popped first\n        Then Znth v2 parents =size using Hinv_7 and stuff\n        but that violates Hinv_8\n      *)\n      assert (0 <= v2 < size). rewrite <- (vert_bound g); apply Hunpopped_vvalid; auto.\n      assert (Hv2_notin: ~ In v2 popped_vertices). {\n      apply (NoDup_app_not_in V unpopped_vertices). apply (Permutation_NoDup (l:=popped_vertices++unpopped_vertices)).\n      apply Permutation_app_comm. apply (Permutation_NoDup (l:=VList g)). apply Permutation_sym; apply Hinv_3.\n      apply NoDup_VList. auto.\n      }\n      assert (Znth v2 parents = size). {\n        assert (0<=Znth v2 parents <= size). apply Hinv_4; auto.\n        destruct H13. apply Z.le_lteq in H14. destruct H14. 2: auto. exfalso.\n        assert (Znth v2 pq_state = Znth v2 keys). rewrite Hinv_6 by lia.\n          destruct (in_dec V_EqDec v2 popped_vertices). contradiction. auto.\n        assert (Znth u pq_state = Znth u keys). rewrite Hinv_6 by lia.\n          destruct (in_dec V_EqDec u popped_vertices). contradiction. auto.\n        assert (Znth u keys <= Znth v2 keys). rewrite <- H15, <- H16. apply Hu_min; lia.\n        assert (Znth v2 keys < inf). rewrite Hinv_5 by lia. destruct (V_EqDec v2 r).\n        lia.\n        apply (evalid_meaning g). apply Hinv_7; lia.\n        (*now so Znth u keys = inf*)\n        destruct popped_vertices. contradiction.\n        (*case u=r, then Znth v2 pq_state = Znth v2 keys should be = inf, lia. Easiest way to solve this is to hack Hinv_11*)\n        (*edit: ok that was unnecessary, lots of things to kill off u=r*)\n        (*case u<>r, then Znth u keys = elabel g (eformat (u, Znth u parents)), but Znth u parents = inf, so Znth u keys = inf. Then inf < inf*)\n        assert( Znth u keys = elabel g (eformat (u,Znth u parents))). rewrite Hinv_5 by lia.\n        destruct (V_EqDec u r). hnf in e.\n          assert (In r (v::popped_vertices)). apply hd_error_In. apply Hr2.\n          unfold not; intros. assert (In v (v::popped_vertices)). left; auto.\n          rewrite H19 in H20; contradiction. subst u. contradiction.\n          auto.\n        rewrite H19 in H17. replace (elabel g (eformat (u, Znth u parents))) with inf in H17. lia.\n        symmetry; apply (invalid_edge_weight g).\n        unfold not; intros. rewrite H4 in H20. apply eformat_evalid_vvalid in H20. destruct H20.\n        rewrite vert_bound in H21; lia.\n      }\n      exfalso. apply (Hinv_8 v2 H12 H13 v1).\n      rewrite find_notIn, Z.add_0_r, sublist_same. auto. auto. auto.\n      auto. auto.\n      (*mst' -> g*) apply connected_symm in H7. destruct H7 as [p [? [? ?]]]. destruct p. inversion H8.\n      inversion H8. destruct p. inversion H9. subst v. subst u0. apply connected_refl. rewrite vert_bound; lia.\n      subst v. destruct H7. exfalso. apply (Hinv_13 u v0); auto.\n    ****(*u0=u, which is repeat of above*) destruct H6. 2: contradiction. subst u0. rename H7 into H6.\n      split; intros.\n      (*g -> mst'*)\n      apply connected_symm in H7. destruct H7 as [p ?].\n      apply (path_partition_checkpoint g popped_vertices unpopped_vertices p v u) in H7; auto.\n      destruct H7 as [v1 [v2 [? [? [? [? ?]]]]]].\n      (*\n        Znth v2 pq_state = keys, because it is unpopped\n        Znth v2 keys >= Znth u keys = inf, because u is popped first\n        Then Znth v2 parents =size using Hinv_7 and stuff\n        but that violates Hinv_8\n      *)\n      assert (0 <= v2 < size). rewrite <- (vert_bound g); apply Hunpopped_vvalid; auto.\n      assert (Hv2_notin: ~ In v2 popped_vertices). {\n      apply (NoDup_app_not_in V unpopped_vertices). apply (Permutation_NoDup (l:=popped_vertices++unpopped_vertices)).\n      apply Permutation_app_comm. apply (Permutation_NoDup (l:=VList g)). apply Permutation_sym; apply Hinv_3.\n      apply NoDup_VList. auto.\n      }\n      assert (Znth v2 parents = size). {\n        assert (0<=Znth v2 parents <= size). apply Hinv_4; auto.\n        destruct H13. apply Z.le_lteq in H14. destruct H14. 2: auto. exfalso.\n        assert (Znth v2 pq_state = Znth v2 keys). rewrite Hinv_6 by lia.\n          destruct (in_dec V_EqDec v2 popped_vertices). contradiction. auto.\n        assert (Znth u pq_state = Znth u keys). rewrite Hinv_6 by lia.\n          destruct (in_dec V_EqDec u popped_vertices). contradiction. auto.\n        assert (Znth u keys <= Znth v2 keys). rewrite <- H15, <- H16. apply Hu_min; lia.\n        assert (Znth v2 keys < inf). rewrite Hinv_5 by lia. destruct (V_EqDec v2 r).\n        lia.\n        apply (evalid_meaning g). apply Hinv_7; lia.\n        (*now so Znth u keys = inf*)\n        destruct popped_vertices. contradiction.\n        (*case u=r, then Znth v2 pq_state = Znth v2 keys should be = inf, lia. Easiest way to solve this is to hack Hinv_11*)\n        (*edit: ok that was unnecessary, lots of things to kill off u=r*)\n        (*case u<>r, then Znth u keys = elabel g (eformat (u, Znth u parents)), but Znth u parents = inf, so Znth u keys = inf. Then inf < inf*)\n        assert( Znth u keys = elabel g (eformat (u,Znth u parents))). rewrite Hinv_5 by lia.\n        destruct (V_EqDec u r). hnf in e.\n          assert (In r (v0::popped_vertices)). apply hd_error_In. apply Hr2.\n          unfold not; intros. assert (In v0 (v0::popped_vertices)). left; auto.\n          rewrite H19 in H20; contradiction. subst u. contradiction.\n          auto.\n        rewrite H19 in H17. replace (elabel g (eformat (u, Znth u parents))) with inf in H17. lia.\n        symmetry; apply (invalid_edge_weight g).\n        unfold not; intros. rewrite H4 in H20. apply eformat_evalid_vvalid in H20. destruct H20.\n        rewrite vert_bound in H21; lia.\n      }\n      exfalso. apply (Hinv_8 v2 H12 H13 v1).\n      rewrite find_notIn, Z.add_0_r, sublist_same. auto. auto. auto.\n      auto. auto.\n      (*mst' -> g*) destruct H7 as [p [? [? ?]]]. destruct p. inversion H8.\n      inversion H8. destruct p. inversion H9. subst v0. subst v. apply connected_refl. rewrite vert_bound; lia.\n      subst v0. destruct H7. exfalso. apply (Hinv_13 u v1); auto.\n    ****(*both=u*)destruct H6. 2: contradiction. destruct H7. 2: contradiction. subst u0; subst v.\n    split; intros; apply connected_refl; rewrite vert_bound; lia.\n  }\n  assert (Hnot_adj: forall u0 v : V, In u0 (remove V_EqDec u unpopped_vertices) -> ~ adjacent mst' u0 v). {\n    intros. apply Hinv_13. rewrite remove_In_iff in H6; apply H6.\n  }\n  time \"End of pop loop (same msf) (originally 150s):\" entailer!.\n  }\n  { (*break*) forward. (*no more vertices in queue*)\n    assert (Hempty: @isEmpty inf pq_state = Vone). {\n      destruct (@isEmptyTwoCases inf pq_state);\n      rewrite H1 in H0; simpl in H0; now inversion H0.\n    } clear H0.\n    rewrite (@isEmptyMeansInf inf pq_state) in Hempty.\n    rename Hempty into H0. rewrite Forall_forall in H0.\n    assert (Permutation popped_vertices (VList mst')). {\n      apply NoDup_Permutation.\n      apply Permutation_sym, Permutation_NoDup, NoDup_app_l in Hinv_3. auto. apply NoDup_VList.\n      apply NoDup_VList. intros; split; intros.\n      apply VList_vvalid. rewrite vert_bound. rewrite <- (vert_bound g). apply Hpopped_vvalid; auto.\n      rewrite VList_vvalid, vert_bound, <- (vert_bound g), vert_bound in H1.\n      assert (Znth x pq_state = (if in_dec V_EqDec x popped_vertices then inf + 1 else Znth x keys)). apply Hinv_6; auto.\n      destruct (in_dec V_EqDec x popped_vertices). auto. exfalso. rewrite Hinv_5 in H2.\n      assert (Znth x pq_state > inf). apply H0. apply Znth_In. unfold V in *. rewrite HZlength_pq_state. auto. 2: auto.\n      destruct (V_EqDec x r).\n      lia.\n      rewrite H2 in H3. pose proof (weight_inf_bound g (eformat (x, Znth x parents))).\n      apply Zgt_not_le in H3. contradiction.\n    }\n    Exists mst'. Exists fmst'. Exists popped_vertices. Exists parents. Exists keys.\n    (*SEP matters*)\n    replace (map Vint (map Int.repr pq_state)) with (list_repeat (Z.to_nat size) (Vint (Int.repr (inf + 1)))). 2: {\n      apply list_eq_Znth. do 2 rewrite Zlength_map.\n      unfold V in *. rewrite Zlength_list_repeat; lia.\n      intros. rewrite Zlength_list_repeat in H2 by lia.\n      rewrite Znth_list_repeat_inrange by lia. rewrite Znth_map. 2: unfold V in *; rewrite Zlength_map; lia.\n      unfold V in *. rewrite Znth_map by lia. rewrite Hinv_6 by lia.\n      unfold V in *.\n      destruct (@in_dec Z V_EqDec i popped_vertices). auto.\n      exfalso; apply n. apply (Permutation_in (l:=VList mst')). apply Permutation_sym; auto.\n      rewrite VList_vvalid, vert_bound; auto.\n    }\n    replace (map (fun x : V =>\n      if in_dec V_EqDec x popped_vertices then Vint (Int.repr 1) else Vint (Int.repr 0))\n     (nat_inc_list (Z.to_nat size))) with (list_repeat (Z.to_nat size) (Vint (Int.repr 1))). 2: {\n      apply list_eq_Znth. rewrite Zlength_map, Zlength_list_repeat, nat_inc_list_Zlength, Z2Nat.id by lia; auto.\n      intros. rewrite Zlength_list_repeat in H2 by lia. rewrite Znth_list_repeat_inrange by lia.\n      rewrite Znth_map. 2: rewrite nat_inc_list_Zlength, Z2Nat.id; lia.\n      rewrite nat_inc_list_i. 2: rewrite Z2Nat.id; lia.\n      destruct (in_dec V_EqDec i popped_vertices). auto.\n      exfalso; apply n. apply (Permutation_in (l:=VList mst')). apply Permutation_sym; auto.\n      rewrite VList_vvalid, vert_bound; auto.\n    }\n    assert (spanning mst' g). {\n      unfold spanning; intros.\n      split; intros. assert (vvalid g u /\\ vvalid g v). apply connected_vvalid; auto. destruct H3.\n      rewrite vert_bound, <- (vert_bound mst'), <- VList_vvalid in H3, H4.\n      apply Hinv_10; auto.\n      apply (Permutation_in (l:=VList mst')). apply Permutation_sym; auto. apply H3.\n      apply (Permutation_in (l:=VList mst')). apply Permutation_sym; auto. apply H4.\n      assert (vvalid mst' u /\\ vvalid mst' v). apply connected_vvalid; auto. destruct H3.\n      rewrite <- VList_vvalid in H3, H4.\n      apply Hinv_10; auto.\n      apply (Permutation_in (l:=VList mst')). apply Permutation_sym; auto. apply H3.\n      apply (Permutation_in (l:=VList mst')). apply Permutation_sym; auto. apply H4.\n    }\n    assert (hd_error popped_vertices = Some r). {\n      destruct popped_vertices. assert (vvalid mst' 0). rewrite vert_bound; lia.\n      rewrite <- VList_vvalid in H3. apply (Permutation_in (l':=[])) in H3. contradiction.\n      apply Permutation_sym; apply H1.\n      apply Hr2. unfold not; intros. assert (In v (v::popped_vertices)) by (left; auto).\n      rewrite H3 in H4; contradiction.\n    }\n    time entailer!. (*was 55 seconds without PROP*)\n  }\n}\n(*POST-LOOP*) {\nclear Hstarting_keys HZlength_starting_keys starting_keys.\nIntros mst fmst popped_vertices parents keys.\nrename H into Hinv_1; rename H0 into Hinv_2;\nrename H1 into Hinv_3; rename H2 into Hinv_4;\nrename H3 into Hinv_5; rename H4 into Hinv_6;\nrename H5 into Hinv_7; rename H6 into Hinv_8;\nrename H7 into Hinv_9; rename H8 into Hinv_10;\nrename H9 into Hinv_11.\nassert (labeled_spanning_uforest mst g). {\n  split. split. apply Hinv_1. split. apply Hinv_2. apply Hinv_7.\n  split. unfold preserve_vlabel; intros. destruct vlabel. destruct vlabel. auto.\n  unfold preserve_elabel; intros. apply Hinv_1. auto.\n}\nassert (minimum_spanning_forest mst g). {\n  destruct Hinv_11 as [M [? ?]].\n  apply (partial_lgraph_spanning_mst mst M g); auto.\n}\nassert (Permutation (EList mst)\n          (map (fun v : Z => eformat (v, Znth v parents))\n             (filter (fun v : Z => Znth v parents <? size) (nat_inc_list (Z.to_nat size))))). {\napply (Permutation_trans (l':= (map (fun v : Z => eformat (v, Znth v parents))\n              (filter (fun v : Z => Znth v parents <? size) popped_vertices)))).\nauto. apply Permutation_map. apply NoDup_Permutation.\napply NoDup_filter. apply (Permutation_NoDup (l:=VList mst)). apply Permutation_sym; auto. apply NoDup_VList.\napply NoDup_filter. apply nat_inc_list_NoDup.\nintros. do 2 rewrite filter_In. rewrite nat_inc_list_in_iff by auto. rewrite Z2Nat.id by lia.\nsplit; intros; destruct H1; split; auto.\napply (Permutation_in (l':=VList mst)) in H1. 2: auto. rewrite VList_vvalid, vert_bound in H1. lia.\napply (Permutation_in (l:=VList mst)). apply Permutation_sym; auto. rewrite VList_vvalid, vert_bound; lia.\n}\nrepeat rewrite Heqv_pq, Heqv_out, Heqv_key.\nfreeze FR := (data_at _ _ _ (pointer_val_val out))\n               (data_at _ _ _ (pointer_val_val parent_ptr))\n               (data_at _ _ _ (pointer_val_val key))\n               (SpaceAdjMatGraph' _ _ _ _)\n               (free_tok (pointer_val_val out) _)\n               (free_tok (pointer_val_val key) _).\nforward_call (Tsh, priq_ptr, size, (list_repeat (Z.to_nat size) (inf + 1))).\nrewrite map_map, map_list_repeat.\nentailer!.\nthaw FR.\nfreeze FR := (data_at _ _ _ (pointer_val_val parent_ptr))\n               (data_at _ _ _ (pointer_val_val key))\n               (SpaceAdjMatGraph' _ _ _ _)\n               (free_tok (pointer_val_val key) _).\nforward_call (Tsh, out, size, (list_repeat (Z.to_nat size) 1)).\nrewrite map_map, map_list_repeat, Z.mul_comm. simpl. entailer!.\nthaw FR.\nfreeze FR := (data_at _ _ _ (pointer_val_val parent_ptr))\n               (SpaceAdjMatGraph' _ _ _ _).\nrewrite <- map_map.\nforward_call (Tsh, key, size, keys).\nrewrite Z.mul_comm. simpl. entailer!.\nforward. \nExists mst fmst parents. thaw FR.\nTransparent size.\nentailer!.\nGlobal Opaque size.\n}\nQed.\n\nEnd PrimProof.\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/prim/verif_prim1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.235177960093217}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.load_demo.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs.  mk_varspecs prog. Defined.\n\nDefinition pair_pair_t := (Tstruct _pair_pair noattr).\n\nDefinition array_size := 100.\n\nDefinition get22_spec :=\n DECLARE _get22\n  WITH pps: val, i: Z, x11: int, x12: int, x21: int, x22: int, sh : share\n  PRE [ _pps OF (tptr pair_pair_t), _i OF tint ]\n    PROP  (readable_share sh; 0 <= i < array_size)\n    LOCAL (temp _pps pps; temp _i (Vint (Int.repr i)))\n    SEP   (field_at sh (tarray pair_pair_t array_size) [ArraySubsc i]\n                    ((Vint x11, Vint x12), (Vint x21, Vint x22)) pps)\n  POST [ tint ]\n        PROP () LOCAL (temp ret_temp (Vint x22))\n    SEP   (field_at sh (tarray pair_pair_t array_size) [ArraySubsc i]\n                    ((Vint x11, Vint x12), (Vint x21, Vint x22)) pps).\n\nDefinition uint_sum (contents : list Z) : int :=\n  fold_right (fun el sum => Int.add sum (Int.repr el)) Int.zero contents.\n\nDefinition fiddle_spec :=\n DECLARE _fiddle\n  WITH p: val, n: Z, tag: Z, contents: list Z\n  PRE [ _p OF tptr tuint ]\n          PROP  (Int.unsigned (Int.shru (Int.repr tag) (Int.repr 10)) = n)\n          LOCAL (temp _p p)\n          SEP (data_at Ews (tarray tuint (1+n)) \n                      (map Vint (map Int.repr (tag::contents)))\n                      (offset_val (-sizeof tuint) p))\n  POST [ tint ]\n          PROP ( )\n          LOCAL (temp ret_temp (Vint (Int.add (Int.repr (Z.land tag 255)) (uint_sum contents))))\n          SEP (data_at Ews (tarray tuint (1+n)) \n                      (map Vint (map Int.repr (tag::contents)))\n                      (offset_val (-sizeof tuint) p)).\n\nDefinition get_uint32_le (arr: list Z) : int :=\n (Int.or (Int.or (Int.or\n            (Int.repr (Znth 0 arr 0))\n   (Int.shl (Int.repr (Znth 1 arr 0)) (Int.repr  8)))\n   (Int.shl (Int.repr (Znth 2 arr 0)) (Int.repr 16)))\n   (Int.shl (Int.repr (Znth 3 arr 0)) (Int.repr 24))).\n\nDefinition get_little_endian_spec :=\n  DECLARE _get_little_endian\n  WITH input : val, in_sh : share, arr : list Z\n  PRE [ _input OF (tptr tuchar) ]\n    PROP (Zlength arr = 4;\n          readable_share in_sh;\n          forall i, 0 <= i < 4 -> 0 <= Znth i arr 0 <= Byte.max_unsigned)\n    LOCAL (temp _input input)\n    SEP (data_at in_sh (tarray tuchar 4) (map Vint (map Int.repr arr)) input)\n  POST [ tuint ]\n    PROP() LOCAL(temp ret_temp (Vint (get_uint32_le arr)))\n    SEP (data_at in_sh (tarray tuchar 4) (map Vint (map Int.repr arr)) input).\n\nDefinition Gprog : funspecs := ltac:(with_library prog\n  [get22_spec; fiddle_spec; get_little_endian_spec]).\n\n\nLtac solve_arr_range H := \n match goal with |- context [Znth ?i _ 0] => \n   specialize (H i); spec H; [ computable | ];\n   rewrite Int.unsigned_repr; rep_omega\n end.\n\nLemma body_get_little_endian: semax_body Vprog Gprog f_get_little_endian get_little_endian_spec.\nProof.\nstart_function.\nassert (BMU: Byte.max_unsigned=255) by reflexivity.\nforward.\nentailer!. solve_arr_range H0.\nforward.\nforward.\nentailer!. solve_arr_range H0.\nforward.\nforward.\nentailer!. solve_arr_range H0.\nforward.\nentailer!. solve_arr_range H0.\nforward.\nQed.\n\nLemma uint_sum_app: forall a b, uint_sum (a++b) = Int.add (uint_sum a) (uint_sum b).\nProof.\n  intros. induction a; simpl.\n  - symmetry. apply Int.add_zero_l.\n  - rewrite IHa. rewrite !Int.add_assoc. f_equal. apply Int.add_commut.\nQed.\n\nLemma body_fiddle: semax_body Vprog Gprog f_fiddle fiddle_spec.\nProof.\nstart_function.\nrename H into Htag.\nassert_PROP (Zlength contents = n) as LEN. {\n  entailer!.\n  forget (Int.unsigned (Int.shru (Int.repr tag) (Int.repr 10))) as n.\n  clear - H0.\n  rewrite Zlength_cons in H0.\n  rewrite !Zlength_map in H0.\n  destruct (zlt n 0); [elimtype False | ].\n  rewrite Z.max_l in H0 by omega.\n  pose proof (Zlength_nonneg contents).\n  omega.\n  rewrite Z.max_r in H0 by omega. omega.  \n}\nassert (Zlength (tag :: contents) = 1 + n) as LEN1. {\n  rewrite Zlength_cons. omega.\n}\nassert (N0: 0 <= n). {\n  pose proof (Zlength_nonneg contents). omega.\n}\nassert_PROP (isptr p) as P by entailer!.\n\n(* forward fails, but tells us to prove this: *)\nassert_PROP (force_val (sem_add_ptr_int tuint Signed p (eval_unop Oneg tint (Vint (Int.repr 1)))) \n  = field_address (tarray tuint (1+n)) [ArraySubsc 0] (offset_val (-sizeof tuint) p)). {\n  entailer!.\n  destruct p; inversion P. simpl.\n  rewrite field_compatible_field_address by auto with field_compatible.\n  simpl.\n  rewrite ptrofs_add_repr_0_r. reflexivity.\n}\nforward.\n(* sum = tagword & 0xff; *)\nforward.\n(* size = tagword >> 10; *)\nforward.\nrewrite !Znth_0_cons.\n\nforward_for_simple_bound (Int.unsigned (Int.shru (Int.repr tag) (Int.repr 10))) (EX i: Z,\n  PROP ( )\n  LOCAL (\n    temp _size (Vint (Int.shru (Int.repr tag) (Int.repr 10)));\n    temp _sum (Vint (Int.add (Int.and (Int.repr tag) (Int.repr 255))\n                             (uint_sum (sublist 0 i contents))));\n    temp _tagword (Vint (Int.repr tag));\n    temp _p p\n  )\n  SEP (data_at Ews (tarray tuint (1 + n)) (map Vint (map Int.repr (tag :: contents)))\n          (offset_val (- sizeof tuint) p))).\n- pose proof (Int.unsigned_range (Int.shru (Int.repr tag) (Int.repr 10))). rep_omega.\n- (* precondition implies invariant: *)\n  entailer!. f_equal. apply Int.repr_unsigned.\n- (* body preserves invariant: *)\n  (* forward fails, but tells us to prove this: *)\n  assert_PROP (force_val (sem_add_ptr_int tuint Unsigned p (Vint (Int.repr i)))\n    = field_address (tarray tuint (1 + n)) [ArraySubsc (1 + i)] (offset_val (- sizeof tuint) p)). {\n    entailer!.\n    destruct p; inversion P. simpl.\n    rewrite field_compatible_field_address by auto with field_compatible.\n    simpl.\n    rewrite Ptrofs.add_assoc, ptrofs_add_repr. \n    f_equal. f_equal. f_equal. omega.\n  }\n  forward.\n  forward.\n  entailer!. split.\n  + f_equal. apply Int.repr_unsigned.\n  + f_equal. rewrite Int.add_assoc. f_equal.\n    rewrite (sublist_split 0 i (i+1)) by omega.\n    rewrite sublist_len_1 with (d := 0) by omega.\n    rewrite Znth_pos_cons by omega.\n    replace (1 + i - 1) with i by omega.\n    rewrite uint_sum_app. f_equal. simpl. apply Int.add_zero_l.\n- (* return sum; *)\n  forward. rewrite sublist_same by auto. entailer!.\nQed.\n\nLemma body_get22_root_expr: semax_body Vprog Gprog f_get22 get22_spec.\n Proof.\n start_function.\n (* int_pair_t* p = &pps[i].right; *)\n forward.\n simpl (temp _p _).\n (* Assert_PROP what forward asks us for (only for the root expression \"p\"):  *)\n assert_PROP (offset_val 8 (force_val (sem_add_ptr_int (Tstruct _pair_pair noattr) Signed pps (Vint (Int.repr i))))\n   = field_address (tarray pair_pair_t array_size) [StructField _right; ArraySubsc i] pps) as E. {\n   entailer!. rewrite field_compatible_field_address by auto with field_compatible.\n  simpl. normalize.\n }\n (* int res = p->snd; *)\n forward.\n (* return res; *)\n forward.\n Qed.\n \n\nLemma body_get22_full_expr: semax_body Vprog Gprog f_get22 get22_spec.\nProof.\nstart_function.\n(* int_pair_t* p = &pps[i].right; *)\nforward.\nsimpl (temp _p _).\n\n(* Assert_PROP what forward asks us for (for the full expression \"p->snd\"): *)\nassert_PROP (\n  offset_val 4 (offset_val 8 (force_val\n    (sem_add_ptr_int (Tstruct _pair_pair noattr) Signed pps (Vint (Int.repr i)))))\n  = (field_address (tarray pair_pair_t array_size)\n                   [StructField _snd; StructField _right; ArraySubsc i] pps)). {\n  entailer!. rewrite field_compatible_field_address by auto with field_compatible.\n  simpl. f_equal. omega.\n}\n(* int res = p->snd; *)\nforward.\n(* return res; *)\nforward.\nQed.\n\nLemma body_get22_alt: semax_body Vprog Gprog f_get22 get22_spec.\nProof.\nstart_function.\n(* int_pair_t* p = &pps[i].right; *)\nforward.\nsimpl (temp _p _).\n\n(* Alternative: Make p nice enough so that no hint is required: *)\nassert_PROP (offset_val 8 (force_val (sem_add_ptr_int (Tstruct _pair_pair noattr) Signed pps (Vint (Int.repr i))))\n  = field_address (tarray pair_pair_t array_size) [StructField _right; ArraySubsc i] pps) as E. {\n  entailer!. rewrite field_compatible_field_address by auto with field_compatible.\n  simpl.\n  normalize.\n}\nrewrite E. clear E.\n(* int res = p->snd; *)\nforward.\n(* return res; *)\nforward.\nQed.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/progs/verif_load_demo.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.235177960093217}}
{"text": "From Coq Require Import Bool List ListSet Reals FinFun RelationClasses Relations Relations_1 Sorting Basics Lia.\nImport ListNotations.\n\nFrom CasperCBC\nRequire Import\n  Lib.Preamble\n  Lib.ListExtras\n  Lib.ListSetExtras\n  Lib.SortedLists\n  Lib.Measurable\n  VLSM.Common\n  VLSM.Plans\n  VLSM.ProjectionTraces\n  VLSM.Composition\n  VLSM.Equivocation\n  VLSM.ListValidator.ListValidator\n  VLSM.ListValidator.Equivocation\n  VLSM.ListValidator.Observations\n  VLSM.ListValidator.EquivocationAwareListValidator\n  VLSM.ObservableEquivocation\n  .\n\n(** * VLSM Free Composition of List Validators *)\n\n(**   This file describes a free composition <X> of List Validator nodes, each using\n   an [equivocation_aware_estimator]. Also see:\n\n   - [Observations.v] for the observation model used here\n   - [EquivocationAwareListValidator.v] for the used estimators\n   - [Equivocation.v] and [ListValidator.v] for some general\n     facts about List Validators.\n*)\n\nSection Composition.\nContext\n  {index : Type}\n  {i0 : Inhabited index}\n  {index_listing : list index}\n  {Hfinite : Listing index_listing}\n  {idec : EqDecision index}\n  {Mindex : Measurable index}\n  {Rindex : ReachableThreshold index}\n  (est' := fun (i : index) => (@EquivocationAwareListValidator.equivocation_aware_estimator _ i _ Hfinite _ _ _ ))\n  (IM_index := fun (i : index) => @VLSM_list index i index_listing idec (est' i))\n  (has_been_sent_capabilities := fun i : index => @lv_sent_capability index i index_listing Hfinite idec (est' i))\n  (has_been_received_capabilities := fun i : index => @lv_received_capability index i index_listing Hfinite idec (est' i))\n  (X := composite_vlsm IM_index (free_constraint IM_index))\n  (preX := pre_loaded_with_all_messages_vlsm X)\n  (Hevents_set' := fun (i : index) => @simp_lv_observable_events index i index_listing _)\n  (Hstate_events_set := fun (i : index) => @simp_lv_state_observations index i index_listing _)\n  (Hevidence := fun (i : index) => @simp_observable_full index i index_listing idec)\n  (Hstate_events_fn := fun (i : index) => (@simp_lv_observations index i index_listing _))\n  (Hbasic := fun (i : index) => @simp_lv_basic_equivocation index i index_listing Hfinite idec Mindex Rindex).\n\n  Local Notation in_listing := (proj2 Hfinite).\n\n  (**  We begin with some basic facts about the given composition. *)\n\n  (**  Protocol states are never bottom *)\n\n  Lemma protocol_state_component_no_bottom\n    (s : vstate X)\n    (i : index)\n    (Hprs : protocol_state_prop X s) :\n    (s i) <> Bottom.\n  Proof.\n    apply (@protocol_prop_no_bottom index i _ _ (est' i)).\n    apply protocol_state_projection with (j := i) in Hprs.\n    unfold protocol_state_prop in Hprs.\n    destruct Hprs as [om Hprs] in Hprs.\n    apply proj_pre_loaded_with_all_messages_protocol_prop in Hprs.\n    unfold protocol_state_prop.\n    exists om.\n    assumption.\n  Qed.\n\n  Proposition Hsnb\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s) :\n    forall (i : index), (s i) <> Bottom.\n  Proof.\n    intros i.\n    apply protocol_state_component_no_bottom. intuition.\n  Qed.\n\n  (**  Applying a protocol plan of receive transitions do not alter the nodes'\n     self-projections (i.e, <<project (s i) i >> *)\n\n  Proposition self_projections_same_after_receive\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (i : index)\n    (ai : vplan_item X)\n    (Hrec : projT2 (label_a ai) = receive)\n    (Hprai : finite_protocol_plan_from X s [ai]) :\n    project ((snd (apply_plan X s [ai])) i) i = project (s i) i.\n  Proof.\n    apply finite_protocol_plan_from_one in Hprai.\n    destruct Hprai as [Hprotocol Htransition].\n    unfold protocol_valid in Hprotocol.\n    unfold valid in Hprotocol.\n    simpl in Hprotocol.\n    unfold constrained_composite_valid in Hprotocol.\n    unfold composite_valid in Hprotocol.\n    unfold vvalid in Hprotocol.\n    unfold valid in Hprotocol.\n    simpl in Hprotocol.\n    simpl in Hrec.\n    destruct ai. simpl in *.\n    destruct label_a. simpl in *. subst v. simpl in *.\n    destruct input_a eqn : eq_input.\n    + simpl in Htransition.\n      assert (x <> fst m) by intuition.\n      simpl.\n      destruct (decide (i = x)).\n      * subst x. rewrite state_update_eq.\n        rewrite (@project_different index index_listing Hfinite).\n        intuition. intuition.\n        apply protocol_state_component_no_bottom. intuition.\n     * rewrite state_update_neq by intuition.\n       intuition.\n    + intuition.\n  Qed.\n\n  Proposition self_projections_same_after_receives\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (a : plan X)\n    (Hpra : finite_protocol_plan_from X s a)\n    (Hrec : forall (ai : vplan_item X), In ai a -> projT2 (label_a ai) = receive) :\n    let res := snd (apply_plan X s a) in\n    forall (i : index), project (res i) i = project (s i) i.\n  Proof.\n    induction a using rev_ind.\n    - intuition.\n    - simpl in *.\n      intros.\n      rewrite apply_plan_app.\n      destruct (apply_plan X s a) as (tr_long, res_long) eqn : eq_long.\n      destruct (apply_plan X res_long [x]) as (tr_short, res_short) eqn : eq_short.\n\n      assert (Hres_long : res_long = snd ((apply_plan X s a))) by (rewrite eq_long; intuition).\n      assert (Hres_short : res_short = snd (apply_plan X res_long [x])) by (rewrite eq_short; intuition).\n      simpl in *.\n\n      apply finite_protocol_plan_from_app_iff in Hpra.\n      destruct Hpra as [Hpra_long Hpra_short].\n\n      specialize (IHa Hpra_long).\n\n      spec IHa. {\n        intros. specialize (Hrec ai).\n        spec Hrec. apply in_app_iff. intuition. intuition.\n      }\n\n      specialize (IHa i).\n      rewrite <- IHa.\n\n      assert (Hpr_long : protocol_state_prop X res_long). {\n        rewrite Hres_long.\n        apply apply_plan_last_protocol.\n        all : intuition.\n      }\n\n      specialize (self_projections_same_after_receive res_long Hpr_long i x) as Hone.\n      spec Hone. {\n        specialize (Hrec x). spec Hrec. apply in_app_iff. intuition.\n        intuition.\n     }\n     rewrite Hres_long in Hone.\n     specialize (Hone Hpra_short).\n     rewrite Hres_short.\n     rewrite Hres_long.\n     intuition.\n  Qed.\n\n  (**  Applying a plan of send/update transitions does not alter\n     non-self projections. *)\n\n  Proposition non_self_projections_same_after_send\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (i j : index)\n    (Hdif : i <> j)\n    (ai : vplan_item X)\n    (Hrec : exists (c : bool), projT2 (label_a ai) = update c)\n    (Hprai : finite_protocol_plan_from X s [ai]) :\n    project ((snd (apply_plan X s [ai])) i) j = project (s i) j.\n  Proof.\n    apply finite_protocol_plan_from_one in Hprai.\n    destruct Hprai as [Hprotocol Htransition].\n    unfold protocol_valid in Hprotocol.\n    unfold valid in Hprotocol.\n    simpl in Hprotocol.\n    unfold constrained_composite_valid in Hprotocol.\n    unfold composite_valid in Hprotocol.\n    unfold vvalid in Hprotocol.\n    unfold valid in Hprotocol.\n    simpl in Hprotocol.\n    simpl in Hrec.\n    destruct ai. simpl in *.\n    destruct label_a. simpl in *.\n    destruct Hrec as [c Heqv].\n    subst v. simpl in *.\n    destruct input_a eqn : eq_input.\n    + simpl in Htransition.\n      intuition congruence.\n    + destruct (decide (x = i)).\n      * subst x.\n        rewrite state_update_eq.\n        rewrite <- update_consensus_clean with (value := c).\n        rewrite (@project_different index index_listing Hfinite).\n        intuition. intuition.\n        apply protocol_state_component_no_bottom. intuition.\n      * rewrite state_update_neq by intuition.\n        intuition.\n  Qed.\n\n  Proposition non_self_projections_same_after_sends\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (a : plan X)\n    (Hpra : finite_protocol_plan_from X s a)\n    (Hrec : forall (ai : vplan_item X), In ai a -> exists (c : bool), projT2 (label_a ai) = update c) :\n    let res := snd (apply_plan X s a) in\n    forall (i j : index), i <> j -> project (res i) j = project (s i) j.\n  Proof.\n    induction a using rev_ind.\n    - intuition.\n    - simpl in *.\n      intros.\n      rewrite apply_plan_app.\n      destruct (apply_plan X s a) as (tr_long, res_long) eqn : eq_long.\n      destruct (apply_plan X res_long [x]) as (tr_short, res_short) eqn : eq_short.\n\n      assert (Hres_long : res_long = snd ((apply_plan X s a))) by (rewrite eq_long; intuition).\n      assert (Hres_short : res_short = snd (apply_plan X res_long [x])) by (rewrite eq_short; intuition).\n      simpl in *.\n\n      apply finite_protocol_plan_from_app_iff in Hpra.\n      destruct Hpra as [Hpra_long Hpra_short].\n\n      specialize (IHa Hpra_long).\n\n      spec IHa. {\n        intros. specialize (Hrec ai).\n        spec Hrec. apply in_app_iff. intuition. intuition.\n      }\n\n      specialize (IHa i).\n      rewrite <- IHa.\n\n      assert (Hpr_long : protocol_state_prop X res_long). {\n        rewrite Hres_long.\n        apply apply_plan_last_protocol.\n        all : intuition.\n      }\n\n      specialize (non_self_projections_same_after_send res_long Hpr_long i j H x) as Hone.\n      spec Hone. {\n        specialize (Hrec x). spec Hrec. apply in_app_iff. intuition.\n        intuition.\n     }\n     rewrite Hres_long in Hone.\n     specialize (Hone Hpra_short).\n     rewrite Hres_short.\n     rewrite Hres_long.\n     intuition.\n     intuition.\n  Qed.\n\n  Local Notation component_list s li := (List.map s li).\n\n  Section EquivObsUtils.\n\n  (** Here we instantiate the observation-based equivocation model for our composition.\n     The implicit <<ws>> stands for \"witness set\" and it means, in short, that we only\n     take into account validators in <<ws>> when gathering observations for the composite state.\n     Note that these observations can concern anyone, but they can only be taken from local\n     observations of validators in <<ws>>. *)\n\n  Context\n  {ws : set index}.\n\n  Definition Hstate_validators := fun (i : index) => (fun (s : vstate (IM_index i)) => index_listing).\n\n  Program Instance lv_composed_observable_events :\n     observable_events (vstate X) simp_lv_event :=\n     composite_state_observable_events_instance\n     index_listing\n     ws\n     IM_index\n     Hstate_events_fn\n     Hstate_validators.\n\n  Definition ce :=\n  @composite_observable_events_equivocation_evidence\n    message index simp_lv_event\n    decide_eq\n    index index_listing ws IM_index\n    Hstate_events_fn\n    Hstate_validators\n    decide_eq\n    simp_lv_event_lt\n    simp_lv_event_lt_dec\n    get_simp_event_subject_some.\n\n  (** The honest set: Validators for which there is no evidence of equivocation.\n     Note that some of these may actually be equivocating if we were to\n     take into account observations originating outside of <<ws>> *)\n\n  Definition wH (s : vstate X) : set index :=\n    List.filter (fun i : index => negb (\n    @bool_decide _ (@composite_observable_events_equivocation_evidence_dec\n      message index simp_lv_event\n      decide_eq\n      index index_listing ws IM_index\n      Hstate_events_fn\n      Hstate_validators\n      decide_eq\n      simp_lv_event_lt\n      simp_lv_event_lt_dec\n      get_simp_event_subject_some s i))) index_listing.\n\n  (** The equivocating set : Validators for which there is evidence of equivocation. *)\n\n  Definition wE (s : vstate X) : set index :=\n    List.filter (fun i : index =>\n    @bool_decide _ (@composite_observable_events_equivocation_evidence_dec\n      message index simp_lv_event\n      decide_eq\n      index index_listing ws IM_index\n      Hstate_events_fn\n      Hstate_validators\n      decide_eq\n      simp_lv_event_lt\n      simp_lv_event_lt_dec\n      get_simp_event_subject_some s i)) index_listing.\n\n  (** Shorthands for the union of observations. *)\n\n  Definition wcobs :=\n    (composite_state_events_fn ws IM_index Hstate_events_fn).\n\n  Definition wcobs_messages\n    (s : vstate X)\n    (target : index) :=\n  fold_right (set_union decide_eq) [] (List.map (fun (i : index) => (simp_lv_message_observations (s i) target)) ws).\n\n  Definition wcobs_states\n    (s : vstate X)\n    (target : index) : set simp_lv_event :=\n    fold_right (set_union decide_eq) [] (List.map (fun (i : index) => (@simp_lv_state_observations index i index_listing _) (s i) target) ws).\n\n  Remark cobs_single\n    (s : vstate X)\n    (target : index)\n    (e : simp_lv_event) :\n    In e (wcobs s target) <->\n    exists (i : index), (In i ws) /\\ (In e (@simp_lv_observations index i index_listing _ (s i) target)).\n  Proof.\n    split; intros.\n    - apply set_union_in_iterated in H. rewrite Exists_exists in H.\n      destruct H as [le [Hinle Hine]].\n      apply in_map_iff in Hinle.\n      destruct Hinle as [ii [Heqle Hini]].\n      exists ii. rewrite <- Heqle in Hine. intuition.\n    - apply set_union_in_iterated. rewrite Exists_exists.\n      destruct H as [i Hi].\n      exists (@simp_lv_observations index i index_listing _ (s i) target).\n      split.\n      + apply in_map_iff. exists i. split;intuition.\n      + intuition.\n  Qed.\n\n  Remark cobs_single_s\n    (s : vstate X)\n    (target : index)\n    (e : simp_lv_event) :\n    In e (wcobs_states s target) <->\n    exists (i : index), (In i ws) /\\ (In e (@simp_lv_state_observations index i index_listing _ (s i) target)).\n  Proof.\n    split; intros.\n    - apply set_union_in_iterated in H. rewrite Exists_exists in H.\n      destruct H as [le [Hinle Hine]].\n      apply in_map_iff in Hinle.\n      destruct Hinle as [ii [Heqle Hini]].\n      exists ii. rewrite <- Heqle in Hine. intuition.\n    - apply set_union_in_iterated. rewrite Exists_exists.\n      destruct H as [i Hi].\n      exists (@simp_lv_state_observations index i index_listing _ (s i) target).\n      split.\n      + apply in_map_iff. exists i. split;intuition.\n      + intuition.\n  Qed.\n\n  Remark cobs_single_m\n    (s : vstate X)\n    (target : index)\n    (e : simp_lv_event) :\n    In e (wcobs_messages s target) <->\n    exists (i : index), (In i ws) /\\ (In e (simp_lv_message_observations (s i) target)).\n  Proof.\n    split; intros.\n    - apply set_union_in_iterated in H. rewrite Exists_exists in H.\n      destruct H as [le [Hinle Hine]].\n      apply in_map_iff in Hinle.\n      destruct Hinle as [ii [Heqle Hini]].\n      exists ii. rewrite <- Heqle in Hine. intuition.\n    - apply set_union_in_iterated. rewrite Exists_exists.\n      destruct H as [i Hi].\n      exists (simp_lv_message_observations (s i) target).\n      split.\n      + apply in_map_iff. exists i. split;intuition.\n      + intuition.\n  Qed.\n\n  Remark in_cobs_messages\n    (s : vstate X)\n    (target : index)\n    (e : simp_lv_event)\n    (Hin : In e (wcobs_messages s target)) :\n    get_simp_event_type e = Message'.\n  Proof.\n    apply cobs_single_m in Hin.\n    destruct Hin as [i [Hini Hine]].\n    apply in_simp_lv_message_observations in Hine.\n    intuition.\n  Qed.\n\n  Remark in_cobs_states\n    (s : vstate X)\n    (target : index)\n    (e : simp_lv_event)\n    (Hin : In e (wcobs_states s target)) :\n    get_simp_event_type e = State'.\n  Proof.\n    apply cobs_single_s in Hin.\n    destruct Hin as [i [Hini Hine]].\n    apply in_simp_lv_state_observations in Hine.\n    intuition.\n  Qed.\n\n  Remark cobs_messages_states\n    (s : vstate X)\n    (target : index) :\n    set_eq (wcobs s target) (set_union decide_eq (wcobs_states s target) (wcobs_messages s target)).\n  Proof.\n    apply set_eq_extract_forall. intros.\n    split; intros.\n    - apply cobs_single in H.\n      destruct H as [i [Hini Hobsi]].\n      unfold simp_lv_observations in Hobsi.\n      apply set_union_iff in Hobsi.\n      apply set_union_iff.\n      destruct Hobsi.\n      + right. apply cobs_single_m.\n        exists i. intuition.\n      + left. apply cobs_single_s.\n        exists i. intuition.\n     - apply set_union_iff in H.\n       destruct H.\n       + apply cobs_single_s in H.\n         destruct H as [i [Hini Hobsi]].\n         apply cobs_single.\n         exists i. split;[intuition|].\n         apply in_simp_lv_state_observations'.\n         intuition.\n       + apply cobs_single_m in H.\n         destruct H as [i [Hini Hobsi]].\n         apply cobs_single.\n         exists i. split;[intuition|].\n         apply in_simp_lv_message_observations'.\n         intuition.\n  Qed.\n\n  Remark in_cobs_and_message\n    (s : vstate X)\n    (target : index)\n    (e : simp_lv_event)\n    (Hm : get_simp_event_type e = Message')\n    (Hin : In e (wcobs s target)) :\n    In e (wcobs_messages s target).\n  Proof.\n    setoid_rewrite cobs_messages_states in Hin.\n    apply set_union_iff in Hin.\n    destruct Hin.\n    - apply in_cobs_states in H. congruence.\n    - intuition.\n  Qed.\n\n  Remark in_cobs_states'\n    (s : vstate X)\n    (target : index)\n    (e : simp_lv_event)\n    (Hin : In e (wcobs_states s target)) :\n    In e (wcobs s target).\n  Proof.\n    setoid_rewrite cobs_messages_states.\n    apply set_union_iff.\n    left. intuition.\n  Qed.\n\n  Remark in_cobs_messages'\n    (s : vstate X)\n    (target : index)\n    (e : simp_lv_event)\n    (Hin : In e (wcobs_messages s target)) :\n    In e (wcobs s target).\n  Proof.\n    setoid_rewrite cobs_messages_states.\n    apply set_union_iff.\n    right. intuition.\n  Qed.\n\n  Definition cequiv_evidence\n    := (@equivocation_evidence\n    (vstate X) index simp_lv_event\n    _ decide_eq\n    simp_lv_event_lt simp_lv_event_lt_dec\n    get_simp_event_subject_some ce).\n\n  (** There's at most one state observation\n     regarding a fixed validator. *)\n\n  Lemma unique_state_observation\n    (s : vstate X)\n    (i : index)\n    (e : simp_lv_event)\n    (Hin : In e (wcobs_states s i)) :\n    e = SimpObs State' i (s i).\n  Proof.\n    unfold wcobs in Hin.\n    unfold composite_state_events_fn in Hin; simpl in Hin.\n    apply cobs_single_s in Hin.\n    destruct Hin as [j [Hinj Hine]].\n    unfold simp_lv_state_observations in Hine.\n    destruct (decide (i = j)).\n    - subst j.\n      destruct Hine; intuition.\n    - intuition.\n  Qed.\n\n  (** And if said validator is in <<ws>>,\n     it's always there. *)\n\n  Lemma state_obs_present\n    (s : vstate X)\n    (i : index)\n    (Hin : In i ws) :\n    In (SimpObs State' i (s i)) (wcobs_states s i).\n  Proof.\n    apply cobs_single_s.\n    exists i.\n    split;[intuition|].\n    unfold simp_lv_state_observations.\n    rewrite decide_True by intuition.\n    intuition.\n  Qed.\n\n  Remark GE_direct\n    (s : vstate X)\n    (i : index) :\n    In i (wE s) <-> (cequiv_evidence s i).\n  Proof.\n    split; intros.\n    - unfold wE in H.\n      unfold wH in H.\n      apply filter_In in H.\n      destruct H as [_ H].\n      apply bool_decide_eq_true in H.\n      intuition.\n    - unfold wE.\n      apply filter_In.\n      split.\n      apply ((proj2 Hfinite) i).\n      apply bool_decide_eq_true.\n      intuition.\n  Qed.\n\n  (** Shortcircuiting the lengthy translation\n     between the observation typeclass and\n     the above definitions. *)\n\n  Remark hbo_cobs\n    (s : vstate X)\n    (e : simp_lv_event) :\n    has_been_observed s e <->\n    In e (wcobs s (get_simp_event_subject e)).\n  Proof.\n    unfold has_been_observed in *. simpl in *.\n    unfold observable_events_has_been_observed in *.\n    unfold state_observable_events_fn in *. simpl in *.\n    unfold composite_state_events_fn in *. simpl in *.\n    split; intros Hine.\n    - apply set_union_in_iterated in Hine.\n      rewrite Exists_exists in Hine.\n      destruct Hine as [le [Hinle Hine]].\n      apply in_map_iff in Hinle.\n      destruct Hinle as [i [Heqle Hini]].\n      assert (i = get_simp_event_subject e). {\n        destruct (decide (i = get_simp_event_subject e)); [intuition|].\n        rewrite <- Heqle in Hine.\n        apply set_union_in_iterated in Hine.\n        rewrite Exists_exists in Hine.\n        destruct Hine as [le' [Hinle' Hine']].\n        apply in_map_iff in Hinle'.\n        destruct Hinle' as [k [Heqk Hink]].\n        unfold Hstate_events_fn in Heqk.\n        rewrite <- Heqk in Hine'.\n        apply in_simp_lv_observations in Hine'.\n        congruence.\n      }\n      rewrite <- H.\n      unfold wcobs.\n      unfold composite_state_events_fn.\n      rewrite <- Heqle in Hine.\n      intuition.\n    - apply set_union_in_iterated.\n      rewrite Exists_exists.\n      exists (wcobs s (get_simp_event_subject e)).\n      split.\n      + apply in_map_iff.\n        exists (get_simp_event_subject e).\n        split.\n        * intuition.\n        * unfold composite_validators.\n          unfold Hstate_validators.\n          apply set_union_in_iterated.\n          rewrite Exists_exists.\n          exists index_listing.\n          split.\n          -- apply in_map_iff.\n             exists inhabitant.\n             split;[intuition|]. apply (proj2 Hfinite).\n          -- apply ((proj2 Hfinite) (get_simp_event_subject e)).\n     + intuition.\n  Qed.\n\n  (** We have actual equality due to these\n     sets being the results of [filter]s. *)\n\n  Remark wE_eq_equality\n    (s s' : vstate X) :\n    set_eq (wE s) (wE s') -> (wE s) = (wE s').\n  Proof.\n    intros.\n    apply filter_set_eq.\n    unfold wE in H.\n    intuition.\n  Qed.\n\n  Remark wH_eq_equality\n    (s s' : vstate X)\n    (i : index) :\n    set_eq (wH s) (wH s') -> (wH s) = (wH s').\n  Proof.\n    intros.\n    apply filter_set_eq.\n    unfold wH in H.\n    intuition.\n  Qed.\n\n  Remark wH_wE'\n    (s : vstate X)\n    (i : index) :\n    In i (wH s) <-> ~ In i (wE s).\n  Proof.\n    unfold wH.\n    unfold wE.\n    split; intros.\n    - apply filter_In in H.\n      intros contra.\n      apply filter_In in contra.\n      destruct H as [_ H].\n      destruct contra as [_ contra].\n      rewrite contra in H.\n      unfold negb in H. congruence.\n    - apply filter_In.\n      split; [apply (proj2 Hfinite)|].\n      rewrite negb_true_iff.\n      match goal with\n      |- ?e = _ =>\n         destruct e eqn : eq_d end.\n      + contradict H.\n        apply filter_In.\n        split; [apply (proj2 Hfinite)|].\n        intuition.\n      + intuition.\n  Qed.\n\n  Remark wE_wH'\n    (s : vstate X)\n    (i : index) :\n    In i (wE s) <-> ~ In i (wH s).\n  Proof.\n    unfold wH.\n    unfold wE.\n    split; intros.\n    - apply filter_In in H.\n      intros contra.\n      apply filter_In in contra.\n      destruct H as [_ H].\n      destruct contra as [_ contra].\n      rewrite bool_decide_eq_true in H.\n      rewrite negb_true_iff in contra.\n      rewrite bool_decide_eq_false in contra.\n      intuition.\n    - apply filter_In.\n      split; [apply (proj2 Hfinite)|].\n      match goal with\n      |- ?e = _ =>\n        destruct e eqn : eq_d end.\n      + intuition.\n      + contradict H.\n        apply filter_In.\n        split;[apply in_listing|].\n        rewrite negb_true_iff.\n        intuition.\n  Qed.\n\n  Remark wH_wE\n    (s : vstate X) :\n    set_eq (wH s) (set_diff decide_eq index_listing (wE s)).\n  Proof.\n    apply set_eq_extract_forall.\n    intros i.\n    split; intros H.\n    - apply set_diff_intro.\n      apply (proj2 Hfinite i).\n      apply wH_wE' in H.\n      intuition.\n    - apply set_diff_iff in H.\n      destruct H as [_ H].\n      apply wH_wE'.\n      intuition.\n  Qed.\n\n  Remark HE_eq_equiv\n    (s s' : vstate X) :\n    (wH s) = (wH s') <-> (wE s) = (wE s').\n  Proof.\n    unfold wH. unfold wE.\n    symmetry. apply filter_complement.\n  Qed.\n\n  (** We start to describe what happens to observations\n     when doing composite updates (similarly to results in [Observations.v]). Some results\n     that don't hold for arbitrary <<ws>> live outside\n     this section. *)\n\n  Lemma cobs_message_existing_other_lf\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (so : state)\n    (i j target : index)\n    (Hdif : i <> j)\n    (s' := state_update IM_index s i (update_state (s i) so j))\n    (Hfull : project (s i) j = project so j)\n    (Hhave : In (SimpObs Message' j so) (wcobs s j)) :\n    incl (wcobs_messages s' target) (wcobs_messages s target).\n  Proof.\n    assert (Hsnb : forall (k : index), (s k) <> Bottom). {\n      intros k.\n      apply protocol_state_component_no_bottom. intuition.\n    }\n\n    assert (Hsonb : so <> Bottom). {\n        apply in_cobs_and_message in Hhave.\n        apply cobs_single_m in Hhave.\n        destruct Hhave as [k Hhave].\n        destruct Hhave as [_ Hhave].\n        apply (@in_message_observations_nb index index_listing Hfinite) in Hhave.\n        all : intuition.\n    }\n    unfold incl.\n    intros e.\n    intros H.\n    unfold wcobs_messages in H.\n    apply cobs_single_m in H.\n    destruct H as [k Hink].\n    destruct (decide (k = i)).\n    - subst k.\n      unfold s' in Hink.\n      rewrite state_update_eq in Hink.\n      destruct (decide (j = target)).\n      + subst target.\n        destruct Hink as [Hink' Hink].\n        apply (@new_incl_rest_same index index_listing Hfinite) in Hink.\n        2 : {\n          split. apply Hsnb; intuition. intuition.\n        }\n        2 : intuition.\n\n        apply set_union_iff in Hink.\n        destruct Hink as [Hink|Hink].\n        * apply set_union_iff in Hink.\n          destruct Hink as [Hink|Hink].\n          -- apply cobs_single_m.\n             exists i. intuition.\n          -- apply in_cobs_and_message in Hhave.\n             apply cobs_single_m in Hhave.\n             destruct Hhave as [l Hhave].\n             apply cobs_single_m.\n             exists l.\n             split;[intuition|].\n             apply (@message_cross_observations index index_listing Hfinite) with (e1 := (SimpObs Message' j so)) (i := j).\n             all : intuition.\n       * destruct Hink;[|intuition].\n         rewrite <- H.\n         apply in_cobs_and_message in Hhave.\n         all : intuition.\n\n      + destruct Hink as [Hink' Hink].\n        apply (@new_incl_rest_diff index index_listing Hfinite) in Hink.\n        2 : {\n          split. apply Hsnb; intuition. intuition.\n        }\n        2 : intuition.\n\n        apply set_union_iff in Hink.\n        destruct Hink as [Hink|Hink].\n        apply cobs_single_m.\n        exists i.\n        split;[intuition|].\n        intuition.\n        apply in_cobs_and_message in Hhave.\n        2 : intuition.\n        apply cobs_single_m in Hhave.\n        destruct Hhave as [l Hhave].\n        apply cobs_single_m.\n        exists l.\n        split;[intuition|].\n        apply (@message_cross_observations index index_listing Hfinite) with (e1 := (SimpObs Message' j so)) (i := j).\n        intuition.\n        simpl.\n        intuition.\n        intuition.\n    - unfold s' in Hink.\n      rewrite state_update_neq in Hink by intuition.\n      apply cobs_single_m.\n      exists k.\n      intuition.\n  Qed.\n\n  Lemma cobs_message_existing_other_rt\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (so : state)\n    (i j target : index)\n    (Hdif : i <> j)\n    (s' := state_update IM_index s i (update_state (s i) so j))\n    (Hfull : project (s i) j = project so j)\n    (Hhave : In (SimpObs Message' j so) (wcobs s j)) :\n    incl (wcobs_messages s target) (wcobs_messages s' target).\n  Proof.\n    assert (Hsnb : forall (k : index), (s k) <> Bottom). {\n      intros k.\n      apply protocol_state_component_no_bottom. intuition.\n    }\n\n    assert (Hsonb : so <> Bottom). {\n        apply in_cobs_and_message in Hhave.\n        apply cobs_single_m in Hhave.\n        destruct Hhave as [k Hhave].\n        destruct Hhave as [_ Hhave].\n        apply (@in_message_observations_nb index index_listing Hfinite) in Hhave.\n        all : intuition.\n    }\n\n    unfold incl.\n    intros.\n    apply cobs_single_m in H.\n    destruct H as [k H].\n    destruct (decide (i = k)).\n    - subst k.\n      apply cobs_single_m.\n      exists i.\n      split;[intuition|].\n      destruct H as [_ H].\n      apply (@old_incl_new index index_listing Hfinite) with (so := so) (i := j) in H.\n      unfold s'.\n      rewrite state_update_eq.\n      intuition.\n      split. apply Hsnb. intuition.\n      intuition.\n   - apply cobs_single_m.\n     exists k.\n     unfold s'.\n     rewrite state_update_neq.\n     all : intuition.\n  Qed.\n\n  Lemma cobs_message_existing_other_rt'\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (so : state)\n    (Hsonb : so <> Bottom)\n    (i j target : index)\n    (Hdif : i <> j)\n    (s' := state_update IM_index s i (update_state (s i) so j))\n    (Hfull : project (s i) j = project so j) :\n    incl (wcobs_messages s target) (wcobs_messages s' target).\n  Proof.\n    assert (Hsnb : forall (k : index), (s k) <> Bottom). {\n      intros k.\n      apply protocol_state_component_no_bottom. intuition.\n    }\n\n    unfold incl.\n    intros.\n    apply cobs_single_m in H.\n    destruct H as [k H].\n    destruct (decide (i = k)).\n    - subst k.\n      apply cobs_single_m.\n      exists i.\n      split;[intuition|].\n      destruct H as [_ H].\n      apply (@old_incl_new index index_listing Hfinite) with (so := so) (i := j) in H.\n      unfold s'.\n      rewrite state_update_eq.\n      intuition.\n      split. apply Hsnb. intuition.\n      intuition.\n   - apply cobs_single_m.\n     exists k.\n     unfold s'.\n     rewrite state_update_neq.\n     all : intuition.\n  Qed.\n\n  Lemma cobs_message_existing_other\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (so : state)\n    (i j target : index)\n    (Hdif : i <> j)\n    (s' := state_update IM_index s i (update_state (s i) so j))\n    (Hfull : project (s i) j = project so j)\n    (Hhave : In (SimpObs Message' j so) (wcobs s j)) :\n    set_eq (wcobs_messages s target) (wcobs_messages s' target).\n  Proof.\n    unfold set_eq.\n    split.\n    - apply cobs_message_existing_other_rt.\n      all : intuition.\n    - apply cobs_message_existing_other_lf.\n      all : intuition.\n  Qed.\n\n  Lemma wcobs_message_existing_same1\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (b : bool)\n    (i target : index)\n    (Hdif : i <> target)\n    (s' := state_update IM_index s i (update_consensus (update_state (s i) (s i) i) b)) :\n    incl (wcobs_messages s target) (wcobs_messages s' target).\n  Proof.\n    assert (Hsnb : forall (k : index), (s k) <> Bottom). {\n      intros k.\n      apply protocol_state_component_no_bottom. intuition.\n    }\n\n    intros e.\n    intros H.\n    - apply cobs_single_m in H.\n      destruct H as [k H].\n      destruct (decide (k = i)).\n      + subst k.\n        destruct H as [H' H].\n        apply (@old_incl_new index index_listing Hfinite) with (so := (s i)) (i := i) in H.\n        apply cobs_single_m.\n        exists i.\n        unfold s'.\n        rewrite state_update_eq.\n        rewrite cons_clean_message_obs with (b0 := b) in H.\n        split;[intuition|].\n        intuition.\n        split; apply Hsnb.\n        intuition.\n      + apply cobs_single_m.\n        exists k.\n        unfold s'.\n        rewrite state_update_neq.\n        all : intuition.\n  Qed.\n\n  Lemma wcobs_message_existing_same2\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (b : bool)\n    (i : index)\n    (s' := state_update IM_index s i (update_consensus (update_state (s i) (s i) i) b)) :\n    incl (wcobs_messages s i) (wcobs_messages s' i).\n  Proof.\n    assert (Hsnb : forall (k : index), (s k) <> Bottom). {\n      intros k.\n      apply protocol_state_component_no_bottom. intuition.\n    }\n    intros e.\n    intros H.\n    -\n      + apply cobs_single_m in H.\n        destruct H as [k [H' H]].\n        destruct (decide (i = k)).\n        * subst k.\n          apply (@old_incl_new index index_listing Hfinite) with (so := (s i)) (i := i) in H.\n          apply cobs_single_m.\n          exists i.\n          unfold s'.\n          rewrite state_update_eq.\n          rewrite cons_clean_message_obs with (b0 := b) in H.\n          split;[intuition|].\n          intuition.\n          split; apply Hsnb.\n          intuition.\n        * apply cobs_single_m.\n          exists k.\n          unfold s'.\n          rewrite state_update_neq.\n          split;[intuition|].\n          all : intuition.\n  Qed.\n\n  Lemma in_future_message_obs\n    (s s' : vstate X)\n    (target : index)\n    (Hf : in_futures X s s')\n    (e : simp_lv_event)\n    (Hin : In e (wcobs_messages s target)) :\n    In e (wcobs_messages s' target).\n  Proof.\n    unfold in_futures in Hf.\n    destruct Hf as [tr Hpr].\n    induction Hpr.\n    - assumption.\n    - apply IHHpr; clear IHHpr.\n      apply protocol_transition_origin in H as Hprs'.\n      destruct H as [Hproto Htrans].\n      unfold transition in Htrans.\n      simpl in Htrans.\n      destruct l. simpl in *.\n      unfold constrained_composite_valid in Hproto.\n      unfold composite_valid in Hproto.\n      unfold vvalid in Hproto. unfold valid in Hproto. simpl in *.\n      unfold vtransition in Htrans.\n      unfold transition in Htrans. simpl in Htrans.\n      destruct v eqn : eq_v.\n      + subst v.\n        inversion Htrans.\n        destruct (decide (x = target)).\n        * subst x.\n          apply wcobs_message_existing_same2. intuition. intuition.\n        * apply wcobs_message_existing_same1; intuition.\n      + destruct iom eqn : eq_iom;[|solve[intuition]].\n        inversion Htrans;clear Htrans;subst s oom.\n        specialize (cobs_message_existing_other_rt' s' Hprs' (snd m)) as Hex.\n        spec Hex. apply Hproto.\n        specialize (Hex x (fst m) target).\n        spec Hex. apply Hproto. simpl in Hex.\n        spec Hex. apply Hproto.\n        apply Hex. assumption.\n  Qed.\n\n  End EquivObsUtils.\n\n  Lemma ws_incl_cobs\n    (s : vstate X)\n    (i : index)\n    (ws ws' : set index)\n    (Hincl : incl ws' ws)\n    (e : simp_lv_event) :\n    In e (@wcobs ws' s i) -> In e (@wcobs ws s i).\n  Proof.\n    intros.\n    unfold wcobs in *.\n    unfold composite_state_events_fn in *.\n    apply set_union_in_iterated in H; rewrite Exists_exists in H.\n    apply set_union_in_iterated. apply Exists_exists.\n    destruct H as [le [H1 H2]].\n    exists le.\n    apply in_map_iff in H1. destruct H1 as [j [Hj Hinj]].\n    split.\n    - apply in_map_iff.\n      exists j. intuition.\n    - intuition.\n  Qed.\n\n  Lemma ws_incl_wE\n    (s : vstate X)\n    (ws ws' : set index)\n    (Hincl : incl ws' ws) :\n    incl (@wE ws' s) (@wE ws s).\n  Proof.\n    unfold incl. intros.\n    apply GE_direct in H.\n    apply GE_direct.\n    unfold cequiv_evidence in *.\n    unfold equivocation_evidence in *.\n    setoid_rewrite hbo_cobs.\n    setoid_rewrite hbo_cobs in H.\n    destruct H as [e1 [He1 [He1' [e2 [He2 [He2' Hcomp]]]]]].\n    exists e1.\n    apply ws_incl_cobs with (ws := ws) in He1. 2 : intuition.\n    split;[intuition|].\n    split;[intuition|].\n    exists e2.\n    apply ws_incl_cobs with (ws := ws) in He2. 2 : intuition.\n    intuition.\n  Qed.\n\n  (** GH := the set of globally honest validators: no evidence of equiv. exists at all.\n     HH := the set of honest-looking-for-the-honest validators: members of GH have\n     no evidence of equiv. regarding these validators.\n     LH i := the set of locally honest validators (<<ws>> is a singleton). *)\n\n  Definition GE := @wE index_listing.\n  Definition GH := @wH index_listing.\n  Definition cobs (s : vstate X) := @wcobs index_listing s.\n  Definition cobs_messages (s : vstate X) := @wcobs_messages index_listing s.\n  Definition cobs_states (s : vstate X) := @wcobs_states index_listing s.\n\n  Definition HE (s : vstate X) := @wE (GH s) s.\n  Definition HH (s : vstate X) := @wH (GH s) s.\n\n  Definition hcobs (s : vstate X) := @wcobs (GH s) s.\n  Definition hcobs_messages (s : vstate X) := @wcobs_messages (GH s) s.\n  Definition hcobs_states (s : vstate X) := @wcobs_states (GH s) s.\n\n  Definition LE (i : index) := (@wE [i]).\n  Definition LH (i : index) := (@wH [i]).\n\n  Remark GH_NoDup\n    (s : vstate X) :\n    NoDup (GH s).\n  Proof.\n    unfold GH.\n    apply NoDup_filter.\n    apply (proj1 Hfinite).\n  Qed.\n\n  Lemma cobs_message_existing_same1\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (b : bool)\n    (i target : index)\n    (Hdif : i <> target)\n    (s' := state_update IM_index s i (update_consensus (update_state (s i) (s i) i) b)) :\n    set_eq (cobs_messages s' target) (cobs_messages s target).\n  Proof.\n    apply set_eq_extract_forall.\n    intros e.\n    split; intros H.\n    - apply cobs_single_m in H.\n      destruct H as [k H].\n      destruct (decide (k = i)).\n      + subst k.\n        unfold s' in H.\n        rewrite state_update_eq in H.\n        rewrite <- cons_clean_message_obs in H.\n        destruct H as [_ H].\n        apply (@new_incl_rest_diff index index_listing Hfinite) in H.\n        apply set_union_iff in H.\n        destruct H; (apply cobs_single_m; exists i; split;[apply in_listing|intuition]).\n        split; apply Hsnb.\n        all :intuition.\n      + unfold s' in H.\n        rewrite state_update_neq in H.\n        apply cobs_single_m.\n        exists k. all : intuition.\n    - apply wcobs_message_existing_same1; intuition.\n  Qed.\n\n  Lemma cobs_message_existing_same2\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (b : bool)\n    (i : index)\n    (s' := state_update IM_index s i (update_consensus (update_state (s i) (s i) i) b)) :\n    set_eq (cobs_messages s' i) (set_union decide_eq (cobs_messages s i) [SimpObs Message' i (s i)]).\n  Proof.\n    apply set_eq_extract_forall.\n    intros e.\n    split; intros H.\n    - apply cobs_single_m in H.\n      apply set_union_iff.\n      destruct H as [k H].\n      destruct (decide (i = k)).\n      + subst k.\n        unfold s' in H.\n        rewrite state_update_eq in H by intuition.\n        rewrite <- cons_clean_message_obs with (b0 := b) in H.\n        destruct H as [_ H].\n        apply (@new_incl_rest_same index index_listing Hfinite) in H.\n        apply set_union_iff in H.\n        destruct H as [H|H];[|right;intuition].\n        apply set_union_iff in H.\n        destruct H; left; apply cobs_single_m; exists i; (split;[apply in_listing|intuition]).\n        split; apply Hsnb; intuition.\n        intuition.\n      + left.\n        unfold s' in H.\n        rewrite state_update_neq in H by intuition.\n        apply cobs_single_m. exists k. intuition.\n    -  apply set_union_iff in H.\n      destruct H as [H | H].\n      + apply wcobs_message_existing_same2; intuition.\n      + apply cobs_single_m.\n        exists i.\n        unfold s'.\n        rewrite state_update_eq by intuition.\n        destruct H;[|intuition].\n        rewrite <- cons_clean_message_obs with (b0 := b).\n        assert (project (update_state (s i) (s i) i) i = s i). {\n          rewrite (@project_same index index_listing).\n          intuition.\n          intuition.\n          apply Hsnb; intuition.\n        }\n        split;[apply in_listing|].\n        apply refold_simp_lv_observations1.\n        unfold update_state.\n        destruct (s i) eqn : eq_si.\n        specialize (Hsnb s Hpr i). congruence.\n        congruence.\n        rewrite H0.\n        apply Hsnb; intuition.\n        rewrite H0.\n        intuition.\n  Qed.\n\n  (** The following set of results allow us to conclude that our\n     common future-finding procedure maintains the same set of globally\n     honest validators. *)\n\n  Lemma GE_existing_same_state_message\n    (s : vstate X)\n    (es2 : state)\n    (Hprs : protocol_state_prop X s)\n    (b : bool)\n    (i v : index)\n    (s' := state_update IM_index s i (update_consensus (update_state (s i) (s i) i) b))\n    (Hine2 : In (SimpObs Message' v es2) (cobs_messages s' v))\n    (Hcomp : ~ comparable simp_lv_event_lt (SimpObs State' v (s' v)) (SimpObs Message' v es2)) :\n    @cequiv_evidence index_listing s v.\n  Proof.\n    unfold cequiv_evidence.\n    unfold equivocation_evidence.\n    setoid_rewrite hbo_cobs.\n    destruct (decide (i = v)).\n    - subst i.\n      unfold s' in Hine2.\n      setoid_rewrite cobs_message_existing_same2 in Hine2.\n      2 : intuition.\n      apply set_union_iff in Hine2.\n      destruct Hine2 as [Hine2|Hine2].\n      + exists (SimpObs State' v (s v)).\n        split.\n            * simpl.\n              apply in_cobs_states'.\n              apply state_obs_present.\n              apply in_listing.\n            * split; [simpl;intuition|].\n                exists (SimpObs Message' v es2).\n                split.\n                -- simpl. apply in_cobs_messages'. intuition.\n                -- split;[simpl;intuition|].\n                   intros contra.\n                   apply comparable_commutative in contra.\n                   apply (@state_obs_stuff_cons index v index_listing Hfinite) with (so := (s v)) (i := v) (b := b) in contra.\n                   unfold s' in Hcomp.\n                   apply comparable_commutative in contra.\n                   rewrite state_update_eq in Hcomp.\n                   intuition.\n                   split;apply Hsnb; intuition.\n                   intuition.\n                   simpl. congruence.\n                   simpl. congruence.\n          +  destruct Hine2; [|intuition].\n             inversion H.\n             subst es2.\n             contradict Hcomp.\n             unfold comparable.\n             right. right.\n             unfold simp_lv_event_lt.\n             rewrite decide_True by intuition.\n             unfold s'.\n             rewrite state_update_eq.\n             unfold state_lt'.\n             rewrite history_disregards_cv.\n             rewrite (@unfold_history_cons index index_listing Hfinite).\n             simpl. left.\n             rewrite (@project_same index index_listing Hfinite).\n             intuition.\n             apply Hsnb; intuition.\n             rewrite (@project_same index index_listing Hfinite).\n             apply Hsnb; intuition.\n             apply Hsnb; intuition.\n         - unfold s' in Hine2.\n           setoid_rewrite cobs_message_existing_same1 in Hine2.\n           2, 3 : intuition.\n           exists (SimpObs State' v (s v)).\n             split.\n             * simpl.\n                apply in_cobs_states'.\n                apply state_obs_present.\n                apply in_listing.\n             * split; [simpl;intuition|].\n                exists (SimpObs Message' v es2).\n                split.\n                -- simpl. apply in_cobs_messages'. intuition.\n                -- split;[simpl;intuition|].\n                   intros contra.\n                   apply comparable_commutative in contra.\n                   unfold s' in Hcomp.\n                   rewrite state_update_neq in Hcomp.\n                   apply comparable_commutative in contra.\n                   all : intuition.\n  Qed.\n\n  Lemma GE_existing_same\n    (s : vstate X)\n    (Hprs : protocol_state_prop X s)\n    (b : bool)\n    (i : index)\n    (s' := state_update IM_index s i (update_consensus (update_state (s i) (s i) i) b)) :\n    incl (GE s') (GE s).\n  Proof.\n    unfold incl; intros v H.\n    apply GE_direct in H as Hev.\n    apply GE_direct.\n    unfold cequiv_evidence in *.\n    unfold equivocation_evidence in *.\n    destruct Hev as [e1 [Hine1 [He1subj Hrem]]].\n    destruct Hrem as [e2 [Hine2 [He2subj Hcomp]]].\n    destruct e1 as [et1 ev1 es1] eqn : eq_e1.\n    destruct e2 as [et2 ev2 es2] eqn : eq_e2.\n    apply hbo_cobs in Hine1.\n    apply hbo_cobs in Hine2.\n\n    setoid_rewrite hbo_cobs.\n    unfold get_simp_event_subject_some.\n\n    assert (Hv : ev1 = v /\\ ev2 = v). {\n      rewrite <- He2subj in He1subj.\n      unfold get_simp_event_subject_some in He1subj.\n      inversion He1subj.\n      unfold get_simp_event_subject_some in He2subj.\n      inversion He2subj.\n      intuition.\n    }\n\n    destruct Hv as [Hv1 Hv2].\n    subst ev1. subst ev2.\n\n    setoid_rewrite cobs_messages_states in Hine1.\n    setoid_rewrite cobs_messages_states in Hine2.\n    apply set_union_iff in Hine1.\n    apply set_union_iff in Hine2.\n    simpl in *.\n    destruct Hine1 as [Hine1|Hine1].\n    - apply in_cobs_states in Hine1 as Het1.\n      simpl in Het1.\n      subst et1.\n      apply unique_state_observation in Hine1.\n      simpl in Hine1.\n      inversion Hine1.\n      subst es1.\n      destruct Hine2 as [Hine2|Hine2].\n      + (** State and state : immediate contradiction *)\n        apply in_cobs_states in Hine2 as Het2.\n        simpl in Het2.\n        subst et2.\n        apply unique_state_observation in Hine2.\n        simpl in Hine2.\n        inversion Hine2.\n        subst es2.\n        unfold comparable in Hcomp.\n        contradict Hcomp.\n        left. intuition.\n      + (*State and message *)\n        apply in_cobs_messages in Hine2 as Het2.\n        simpl in Het2. subst et2.\n        specialize (GE_existing_same_state_message s es2 Hprs b i v Hine2 Hcomp) as Hev.\n        unfold cequiv_evidence in Hev. unfold equivocation_evidence in Hev.\n        setoid_rewrite hbo_cobs in Hev. intuition.\n     - apply in_cobs_messages in Hine1 as Het1.\n       simpl in Het1. subst et1.\n       destruct Hine2 as [Hine2|Hine2].\n       + apply in_cobs_states in Hine2 as Het2.\n         simpl in Het2. subst et2.\n         apply unique_state_observation in Hine2.\n         inversion Hine2. subst es2.\n         rewrite comparable_commutative in Hcomp.\n         specialize (GE_existing_same_state_message s es1 Hprs b i v Hine1 Hcomp) as Hev.\n         unfold cequiv_evidence in Hev. unfold equivocation_evidence in Hev.\n         setoid_rewrite hbo_cobs in Hev. intuition.\n       + apply in_cobs_messages in Hine2 as Het2.\n         simpl in Het2. subst et2.\n         destruct (decide (i = v)).\n         * subst v.\n           unfold s' in Hine1, Hine2.\n           setoid_rewrite cobs_message_existing_same2 in Hine1.\n           2 : intuition.\n           setoid_rewrite cobs_message_existing_same2 in Hine2.\n           2 : intuition.\n           apply set_union_iff in Hine1.\n           apply set_union_iff in Hine2.\n\n           destruct Hine1 as [Hine1|Hine1].\n           -- destruct Hine2 as [Hine2|Hine2].\n              ++ exists e1. subst e1. simpl.\n                 split;[apply in_cobs_messages' in Hine1; intuition|].\n                 split;[intuition|].\n                 exists e2. subst e2. simpl.\n                 split;[apply in_cobs_messages' in Hine2; intuition|].\n                 split;[intuition|].\n                 intuition.\n              ++ destruct Hine2;[|intuition].\n                 inversion H0. subst es2.\n                 exists e1. subst e1. simpl.\n                 split;[apply in_cobs_messages' in Hine1; intuition|].\n                 split;[intuition|].\n                 exists (SimpObs State' i (s i)). simpl.\n                 split;[apply in_cobs_states';apply state_obs_present; intuition|].\n                 apply in_listing.\n                 split;[intuition|].\n                 intros contra.\n                 unfold comparable in contra.\n                 destruct contra as [contra|contra];[congruence|].\n                 destruct contra as [contra|contra].\n                 ** unfold simp_lv_event_lt in contra.\n                    rewrite decide_True in contra by intuition.\n                    contradict Hcomp.\n                    unfold comparable.\n                    right. left.\n                    unfold simp_lv_event_lt.\n                    rewrite decide_True by intuition.\n                    intuition.\n                 ** unfold simp_lv_event_lt in contra.\n                    rewrite decide_True in contra by intuition.\n                    intuition.\n           -- destruct Hine2 as [Hine2|Hine2].\n              ++ destruct Hine1;[|intuition].\n                 inversion H0. subst es1.\n                 exists e2. subst e2. simpl.\n                 split;[apply in_cobs_messages' in Hine2; intuition|].\n                 split;[intuition|].\n                 exists (SimpObs State' i (s i)). simpl.\n                 split;[apply in_cobs_states';apply state_obs_present; intuition|].\n                 apply in_listing.\n                 split;[intuition|].\n                 intros contra.\n                 unfold comparable in contra.\n                 destruct contra as [contra|contra];[congruence|].\n                 destruct contra as [contra|contra].\n                 ** unfold simp_lv_event_lt in contra.\n                    rewrite decide_True in contra by intuition.\n                    contradict Hcomp.\n                    unfold comparable.\n                    right. right.\n                    unfold simp_lv_event_lt.\n                    rewrite decide_True by intuition.\n                    intuition.\n                 ** unfold simp_lv_event_lt in contra.\n                    rewrite decide_True in contra by intuition.\n                    intuition.\n              ++ destruct Hine1 as [Hine1|];[|intuition].\n                 destruct Hine2 as [Hine2|];[|intuition].\n                 inversion Hine1. inversion Hine2.\n                 subst es1. subst es2.\n                 contradict Hcomp.\n                 unfold comparable.\n                 left. intuition.\n        * unfold s' in Hine1, Hine2.\n          setoid_rewrite cobs_message_existing_same1 in Hine1.\n          2, 3 : intuition.\n          setoid_rewrite cobs_message_existing_same1 in Hine2.\n          2, 3 : intuition.\n          exists e1. subst e1. simpl.\n          split;[apply in_cobs_messages';intuition|].\n          split;[intuition|].\n          exists e2. subst e2. simpl.\n          split;[apply in_cobs_messages';intuition|].\n          split;[intuition|].\n          intuition.\n  Qed.\n\n  Lemma GE_existing_different_state_message\n    (s : vstate X)\n    (Hprs : protocol_state_prop X s)\n    (i j v : index)\n    (Hdif : i <> j)\n    (es2 so : state)\n    (s' := state_update IM_index s i (update_state (s i) so j))\n    (Hfull : project (s i) j = project so j)\n    (Hhave : In (SimpObs Message' j so) (cobs s j))\n    (Hine2 : In (SimpObs Message' v es2) (cobs_messages s' v))\n    (Hcomp : ~ comparable simp_lv_event_lt (SimpObs State' v (s' v)) (SimpObs Message' v es2)) :\n    @cequiv_evidence index_listing s v.\n  Proof.\n    assert (Hsnb : forall (k : index), (s k) <> Bottom). {\n      intros k.\n      apply protocol_state_component_no_bottom. intuition.\n    }\n\n    assert (Hsonb : so <> Bottom). {\n        apply in_cobs_and_message in Hhave.\n        apply cobs_single_m in Hhave.\n        destruct Hhave as [k [_ Hhave]].\n        apply (@in_message_observations_nb index index_listing Hfinite) in Hhave.\n        all : intuition.\n    }\n\n    unfold cequiv_evidence.\n    unfold equivocation_evidence. setoid_rewrite hbo_cobs.\n    unfold s' in Hine2.\n        setoid_rewrite <- cobs_message_existing_other in Hine2.\n        2, 3, 4, 5: intuition.\n        exists (SimpObs Message' v es2). simpl.\n        split;[apply in_cobs_messages';intuition|].\n        split;[intuition|].\n        destruct (decide (i = v)).\n        * exists (SimpObs State' v (s v)). simpl.\n          subst v.\n          split;[apply in_cobs_states'; apply state_obs_present|].\n          apply in_listing.\n          split;[intuition|].\n          intros contra.\n          apply (@state_obs_stuff index i index_listing Hfinite) with (so := so) (i0 := j) in contra.\n          unfold s' in Hcomp.\n          apply comparable_commutative in contra.\n          rewrite state_update_eq in Hcomp by intuition.\n          intuition.\n          split;[apply Hsnb|intuition].\n          intuition.\n          simpl. congruence.\n          simpl. intuition.\n        * unfold s' in *.\n          rewrite state_update_neq in Hcomp.\n          exists (SimpObs State' v (s v)).\n          simpl.\n          split;[apply in_cobs_states';apply state_obs_present|].\n          apply in_listing.\n          split;[simpl;intuition|].\n          intros contra.\n          apply comparable_commutative in contra.\n          all : intuition.\n  Qed.\n\n  Lemma GE_existing_different\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (so : state)\n    (i j : index)\n    (Hdif : i <> j)\n    (s' := state_update IM_index s i (update_state (s i) so j))\n    (Hfull : project (s i) j = project so j)\n    (Hhave : In (SimpObs Message' j so) (cobs s j)) :\n    incl (GE s') (GE s).\n  Proof.\n    unfold incl; intros v H.\n    apply GE_direct in H as Hev.\n    apply GE_direct.\n    unfold cequiv_evidence in *.\n    unfold equivocation_evidence in *.\n    destruct Hev as [e1 [Hine1 [He1subj Hrem]]].\n    destruct Hrem as [e2 [Hine2 [He2subj Hcomp]]].\n    destruct e1 as [et1 ev1 es1] eqn : eq_e1.\n    destruct e2 as [et2 ev2 es2] eqn : eq_e2.\n    apply hbo_cobs in Hine1.\n    apply hbo_cobs in Hine2.\n\n    setoid_rewrite hbo_cobs.\n    unfold get_simp_event_subject_some.\n\n    assert (Hv : ev1 = v /\\ ev2 = v). {\n      rewrite <- He2subj in He1subj.\n      unfold get_simp_event_subject_some in He1subj.\n      inversion He1subj.\n      unfold get_simp_event_subject_some in He2subj.\n      inversion He2subj.\n      intuition.\n    }\n\n    destruct Hv as [Hv1 Hv2].\n    subst ev1. subst ev2.\n\n    setoid_rewrite cobs_messages_states in Hine1.\n    setoid_rewrite cobs_messages_states in Hine2.\n    apply set_union_iff in Hine1.\n    apply set_union_iff in Hine2.\n\n    destruct Hine1 as [Hine1|Hine1].\n    - apply in_cobs_states in Hine1 as Het1.\n      simpl in Het1. subst et1.\n      apply unique_state_observation in Hine1. simpl in Hine1.\n      inversion Hine1. subst es1.\n      destruct Hine2 as [Hine2|Hine2].\n      + apply in_cobs_states in Hine2 as Het2.\n        simpl in Het2. subst et2.\n        apply unique_state_observation in Hine2. simpl in Hine2.\n        inversion Hine2. subst es2.\n        contradict Hcomp.\n        unfold comparable. left. intuition.\n      + apply in_cobs_messages in Hine2 as Het2.\n        simpl in Het2. subst et2. simpl in Hine2.\n        specialize (GE_existing_different_state_message s Hpr i j v Hdif es2 so Hfull Hhave Hine2 Hcomp) as Hev.\n        setoid_rewrite <- hbo_cobs. intuition.\n    - apply in_cobs_messages in Hine1 as Het1.\n      simpl in Het1. subst et1. simpl in Hine1.\n      destruct Hine2 as [Hine2|Hine2].\n      + apply in_cobs_states in Hine2 as Het2.\n        simpl in Het2. subst et2.\n        apply unique_state_observation in Hine2. simpl in Hine2.\n        inversion Hine2. subst es2.\n        rewrite comparable_commutative in Hcomp.\n        specialize (GE_existing_different_state_message s Hpr i j v Hdif es1 so Hfull Hhave Hine1 Hcomp) as Hev.\n        setoid_rewrite <- hbo_cobs. intuition.\n      + apply in_cobs_messages in Hine2 as Het2.\n        simpl in Het2. subst et2. simpl in Hine2.\n        unfold s' in Hine2. unfold s' in Hine1.\n        setoid_rewrite <- cobs_message_existing_other in Hine2.\n        setoid_rewrite <- cobs_message_existing_other in Hine1.\n        2, 3, 4, 5: intuition.\n        2, 3, 4, 5: intuition.\n        exists e1. subst e1. simpl.\n        split;[apply in_cobs_messages';intuition|].\n        split;[intuition|].\n        exists e2. subst e2. simpl.\n        split;[apply in_cobs_messages';intuition|].\n        split;[intuition|].\n        intuition.\n  Qed.\n\n  Lemma GE_existing_same_rev\n    (s : vstate X)\n    (Hprs : protocol_state_prop X s)\n    (b : bool)\n    (i : index)\n    (Hhonest : ~ In i (GE s))\n    (s' := state_update IM_index s i (update_consensus (update_state (s i) (s i) i) b)) :\n    incl (GE s) (GE s').\n  Proof.\n    unfold incl; intros v H.\n    apply GE_direct in H as Hev.\n    apply GE_direct.\n    unfold cequiv_evidence in *.\n    unfold equivocation_evidence in *.\n    destruct Hev as [e1 [Hine1 [He1subj Hrem]]].\n    destruct Hrem as [e2 [Hine2 [He2subj Hcomp]]].\n    destruct e1 as [et1 ev1 es1] eqn : eq_e1.\n    destruct e2 as [et2 ev2 es2] eqn : eq_e2.\n    apply hbo_cobs in Hine1.\n    apply hbo_cobs in Hine2.\n\n    setoid_rewrite hbo_cobs.\n    unfold get_simp_event_subject_some.\n\n    assert (Hv : ev1 = v /\\ ev2 = v). {\n      rewrite <- He2subj in He1subj.\n      unfold get_simp_event_subject_some in He1subj.\n      inversion He1subj.\n      unfold get_simp_event_subject_some in He2subj.\n      inversion He2subj.\n      intuition.\n    }\n\n    destruct Hv as [Hv1 Hv2].\n    subst ev1. subst ev2.\n\n    setoid_rewrite cobs_messages_states in Hine1.\n    setoid_rewrite cobs_messages_states in Hine2.\n    apply set_union_iff in Hine1.\n    apply set_union_iff in Hine2.\n\n    destruct Hine1 as [Hine1|Hine1].\n    - apply in_cobs_states in Hine1 as Het1.\n      simpl in Het1.\n      subst et1.\n      apply unique_state_observation in Hine1.\n      simpl in Hine1.\n      inversion Hine1.\n      subst es1.\n      destruct Hine2 as [Hine2|Hine2].\n      + apply in_cobs_states in Hine2 as Het2.\n        simpl in Het2.\n        subst et2.\n        apply unique_state_observation in Hine2.\n        simpl in Hine2.\n        inversion Hine2.\n        subst es2.\n        unfold comparable in Hcomp.\n        contradict Hcomp.\n        left. intuition.\n      + apply in_cobs_messages in Hine2 as Het2.\n        simpl in Het2.\n        subst et2.\n        destruct (decide (i = v)).\n        * subst v.\n          intuition.\n        * exists (SimpObs State' v (s' v)).\n          split;[apply in_cobs_states';apply state_obs_present|].\n          apply in_listing.\n          split;[intuition|].\n          exists e2. subst e2.\n          simpl in *.\n          unfold s'.\n          rewrite state_update_neq by intuition.\n          split.\n          -- apply in_cobs_messages'.\n             setoid_rewrite cobs_message_existing_same1.\n             all : intuition.\n          -- split;intuition.\n     - apply in_cobs_messages in Hine1 as Het1.\n       simpl in Het1. subst et1.\n       destruct Hine2 as [Hine2|Hine2].\n       + apply in_cobs_states in Hine2 as Het2.\n         simpl in Het2. subst et2.\n         apply unique_state_observation in Hine2.\n         simpl in Hine2.\n         inversion Hine2. subst es2.\n         destruct (decide (i = v)).\n        * subst v.\n          intuition.\n        * exists (SimpObs State' v (s' v)).\n          split;[apply in_cobs_states';apply state_obs_present|].\n          apply in_listing.\n          split;[intuition|].\n          exists e1. subst e1.\n          simpl in *.\n          unfold s'.\n          rewrite state_update_neq by intuition.\n          split.\n          -- apply in_cobs_messages'.\n             setoid_rewrite cobs_message_existing_same1.\n             all : intuition.\n          -- split;[intuition|].\n             intros contra.\n             apply comparable_commutative in contra.\n             intuition.\n       + apply in_cobs_messages in Hine2 as Het2.\n         simpl in Het2.\n         subst et2.\n\n         destruct (decide (i = v)); [subst v;intuition|].\n\n         exists e1. subst e1. simpl in *.\n         split.\n         * apply in_cobs_messages'.\n           unfold s'.\n           setoid_rewrite cobs_message_existing_same1.\n           all : intuition.\n         * split;[intuition|].\n           exists e2. subst e2. simpl in *.\n           split.\n           -- apply in_cobs_messages'.\n              unfold s'.\n              setoid_rewrite cobs_message_existing_same1.\n              all : intuition.\n           -- intuition.\n  Qed.\n\n  Lemma GE_existing_different_rev\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (so : state)\n    (i j : index)\n    (Hdif : i <> j)\n    (s' := state_update IM_index s i (update_state (s i) so j))\n    (Hfull : project (s i) j = project so j)\n    (Hhave : In (SimpObs Message' j so) (cobs s j)) :\n    incl (GE s) (GE s').\n  Proof.\n    assert (Hsonb : so <> Bottom). {\n        apply in_cobs_and_message in Hhave.\n        apply cobs_single_m in Hhave.\n        destruct Hhave as [k [_ Hhave]].\n        apply (@in_message_observations_nb index index_listing Hfinite) in Hhave.\n        all : intuition.\n    }\n\n    unfold incl; intros v H.\n    apply GE_direct in H as Hev.\n    apply GE_direct.\n    unfold cequiv_evidence in *.\n    unfold equivocation_evidence in *.\n    destruct Hev as [e1 [Hine1 [He1subj Hrem]]].\n    destruct Hrem as [e2 [Hine2 [He2subj Hcomp]]].\n    destruct e1 as [et1 ev1 es1] eqn : eq_e1.\n    destruct e2 as [et2 ev2 es2] eqn : eq_e2.\n    apply hbo_cobs in Hine1.\n    apply hbo_cobs in Hine2.\n\n    setoid_rewrite hbo_cobs.\n    unfold get_simp_event_subject_some.\n\n    assert (Hv : ev1 = v /\\ ev2 = v). {\n      rewrite <- He2subj in He1subj.\n      unfold get_simp_event_subject_some in He1subj.\n      inversion He1subj.\n      unfold get_simp_event_subject_some in He2subj.\n      inversion He2subj.\n      intuition.\n    }\n\n    destruct Hv as [Hv1 Hv2].\n    subst ev1. subst ev2.\n\n    setoid_rewrite cobs_messages_states in Hine1.\n    setoid_rewrite cobs_messages_states in Hine2.\n    apply set_union_iff in Hine1.\n    apply set_union_iff in Hine2.\n\n    destruct Hine1 as [Hine1|Hine1].\n    - apply in_cobs_states in Hine1 as Het1.\n      simpl in Het1. subst et1.\n      apply unique_state_observation in Hine1. simpl in Hine1.\n      inversion Hine1. subst es1.\n      destruct Hine2 as [Hine2|Hine2].\n      + apply in_cobs_states in Hine2 as Het2.\n        simpl in Het2. subst et2.\n        apply unique_state_observation in Hine2. simpl in Hine2.\n        inversion Hine2. subst es2.\n        contradict Hcomp.\n        unfold comparable. left. intuition.\n      + apply in_cobs_messages in Hine2 as Het2.\n        simpl in Het2. subst et2. simpl in Hine2.\n\n        exists (SimpObs State' v (s' v)). simpl.\n        split;[apply in_cobs_states';apply state_obs_present|].\n        apply in_listing.\n        split;[intuition|].\n        exists e2. subst e2. simpl in *.\n        split.\n        * apply in_cobs_messages'.\n          unfold s'.\n          setoid_rewrite <- cobs_message_existing_other.\n          all :intuition.\n        * split;[intuition|].\n          unfold s'.\n          destruct (decide (i = v)).\n          -- subst v.\n             rewrite state_update_eq.\n             intros contra.\n             unfold comparable in contra.\n             destruct contra as [contra|contra];[congruence|].\n             unfold simp_lv_event_lt in contra.\n             rewrite decide_True in contra by intuition.\n             destruct contra as [contra|contra];[intuition|].\n             rewrite decide_True in contra by intuition.\n             unfold state_lt' in contra.\n\n             contradict Hcomp.\n             unfold comparable.\n             right.\n             right.\n             unfold simp_lv_event_lt.\n             rewrite decide_True by intuition.\n             unfold state_lt'.\n\n             assert (get_history (update_state (s i) so j) i = get_history (s i) i). {\n              apply (@eq_history_eq_project index index_listing Hfinite).\n              rewrite (@project_different index index_listing Hfinite).\n              intuition.\n              intuition.\n              apply Hsnb; intuition.\n             }\n\n             rewrite <- H0.\n             intuition.\n          -- rewrite state_update_neq by intuition.\n             intuition.\n    - apply in_cobs_messages in Hine1 as Het1.\n      simpl in Het1. subst et1. simpl in Hine1.\n\n      destruct Hine2 as [Hine2|Hine2].\n      + apply in_cobs_states in Hine2 as Het2.\n        simpl in Het2. subst et2.\n        apply unique_state_observation in Hine2. simpl in Hine2.\n        inversion Hine2. subst es2.\n\n        exists (SimpObs State' v (s' v)). simpl.\n        split;[apply in_cobs_states';apply state_obs_present|].\n        apply in_listing.\n        split;[intuition|].\n        exists e1. subst e1. simpl in *.\n        split.\n        * apply in_cobs_messages'.\n          unfold s'.\n          setoid_rewrite <- cobs_message_existing_other.\n          all :intuition.\n        * split;[intuition|].\n          unfold s'.\n          destruct (decide (i = v)).\n          -- subst v.\n             rewrite state_update_eq.\n             intros contra.\n             unfold comparable in contra.\n             destruct contra as [contra|contra];[congruence|].\n             unfold simp_lv_event_lt in contra.\n             rewrite decide_True in contra by intuition.\n             destruct contra as [contra|contra];[intuition|].\n             rewrite decide_True in contra by intuition.\n             unfold state_lt' in contra.\n\n             contradict Hcomp.\n             unfold comparable.\n             right.\n             left.\n             unfold simp_lv_event_lt.\n             rewrite decide_True by intuition.\n             unfold state_lt'.\n\n             assert (get_history (update_state (s i) so j) i = get_history (s i) i). {\n              apply (@eq_history_eq_project index index_listing Hfinite).\n              rewrite (@project_different index index_listing Hfinite).\n              intuition.\n              intuition.\n              apply Hsnb; intuition.\n             }\n\n             rewrite <- H0.\n             intuition.\n          -- rewrite state_update_neq by intuition.\n             intros contra.\n             apply comparable_commutative in contra.\n             intuition.\n      + apply in_cobs_messages in Hine2 as Het2.\n        simpl in Het2. subst et2. simpl in Hine2.\n\n        exists e1. subst e1. simpl in *.\n        split.\n        * apply in_cobs_messages'.\n          unfold s'.\n          setoid_rewrite <- cobs_message_existing_other.\n          all :intuition.\n        * split;[intuition|].\n          exists e2. subst e2. simpl in *.\n          split.\n          -- apply in_cobs_messages'.\n             unfold s'.\n             setoid_rewrite <- cobs_message_existing_other.\n             all : intuition.\n          -- split;[intuition|].\n             intuition.\n  Qed.\n\n  Lemma receive_plan_preserves_equivocation\n    (s : vstate X)\n    (Hpr : protocol_state_prop X s)\n    (a : plan X)\n    (Hpr_a : finite_protocol_plan_from X s a)\n    (Hgood : forall (ai : vplan_item X), In ai a ->\n      (projT2 (label_a ai)) = receive /\\\n      exists (so : state) (from : index),\n      input_a ai = Some (from, so) /\\\n      In (SimpObs Message' from so) (cobs_messages s from)) :\n    let res := snd (apply_plan X s a) in\n    set_eq (GE s) (GE res).\n  Proof.\n    simpl.\n    induction a using rev_ind.\n    - simpl in *. intuition.\n    - assert (Hpr_a' := Hpr_a).\n      apply finite_protocol_plan_from_app_iff in Hpr_a.\n      spec IHa. intuition.\n\n      rewrite apply_plan_app.\n      destruct (apply_plan X s a) as (tr_long, res_long) eqn : eq_long.\n      destruct (apply_plan X res_long [x]) as (tr_short, res_short) eqn : eq_short.\n\n      assert (res_long = snd (apply_plan X s a)) by (rewrite eq_long; intuition).\n      assert (res_short = snd (apply_plan X res_long [x])) by (rewrite eq_short; intuition).\n\n      simpl.\n      apply set_eq_tran with (s2 := GE res_long).\n      + spec IHa. {\n          intros ai Hai.\n          specialize (Hgood ai).\n          spec Hgood. apply in_app_iff. left. intuition.\n          intuition.\n        }\n        simpl in IHa.\n        intuition.\n      + rewrite H0.\n        unfold apply_plan, _apply_plan. simpl.\n\n        specialize (Hgood x).\n        spec Hgood. {\n          apply in_app_iff. right. intuition.\n        }\n\n        destruct x. simpl in *.\n\n        destruct (vtransition X label_a (res_long, input_a)) eqn : eq_trans.\n        unfold vtransition in eq_trans.\n        unfold transition in eq_trans.\n        simpl in eq_trans.\n        unfold vtransition in eq_trans.\n        unfold transition in eq_trans.\n        simpl in eq_trans.\n        destruct label_a. simpl in *.\n        destruct Hgood as [Hv Hgood].\n        destruct Hpr_a as [Hpr_a2 Hpr_a].\n        apply finite_protocol_plan_from_one in Hpr_a. simpl in Hpr_a.\n        move Hpr_a at bottom.\n        destruct Hpr_a as [Hpr_a _].\n        unfold protocol_valid in Hpr_a.\n        unfold valid in Hpr_a.\n        simpl in Hpr_a.\n        unfold constrained_composite_valid in Hpr_a.\n        unfold composite_valid in Hpr_a.\n        unfold vvalid in Hpr_a.\n        unfold valid in Hpr_a. simpl in Hpr_a.\n        subst v.\n        destruct input_a eqn : eq_input\n        ; [| intuition].\n        destruct Hgood as [so [from [Heqm Hinso]]].\n        inversion Heqm.\n        subst m. simpl in *.\n        unfold set_eq.\n        inversion eq_trans. clear H3.\n        assert (In (SimpObs Message' from so) (cobs res_long from)). {\n          specialize (@in_future_message_obs index_listing s res_long from) as Hf.\n          spec Hf. {\n            unfold in_futures.\n            exists (fst (apply_plan X s a)).\n            apply ptrace_add_last.\n            - assert (finite_protocol_plan_from X s a). {\n                intuition.\n              }\n              unfold finite_protocol_plan_from in H1.\n              intuition.\n            - rewrite H.\n              apply apply_plan_last.\n          }\n          specialize (Hf (SimpObs Message' from so)).\n          apply in_cobs_messages'.\n          apply Hf.\n          intuition.\n        }\n        split.\n        * apply GE_existing_different_rev.\n          all : intuition.\n        * apply GE_existing_different.\n          all : intuition.\n  Qed.\n\nEnd Composition.\n", "meta": {"author": "zunction", "repo": "casper-cbc-proofs", "sha": "92493810dd32a8301882f9eb8a0488a6ac9d0cd1", "save_path": "github-repos/coq/zunction-casper-cbc-proofs", "path": "github-repos/coq/zunction-casper-cbc-proofs/casper-cbc-proofs-92493810dd32a8301882f9eb8a0488a6ac9d0cd1/VLSM/ListValidator/EquivocationAwareComposition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.23513079557918584}}
{"text": "\n(**\n    VerifiedDSP\n    Copyright (C) {2015}  {Jeremy L Rubin}\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\n**)\n(* Copyright (c) 2011. Greg Morrisett, Gang Tan, Joseph Tassarotti, \n   Jean-Baptiste Tristan, and Edward Gan.\n\n   This file is part of RockSalt.\n\n   This file is free software; you can redistribute it and/or\n   modify it under the terms of the GNU General Public License as\n   published by the Free Software Foundation; either version 2 of\n   the License, or (at your option) any later version.\n*)\n\nRequire Import List.\nRequire Import Bits.\nRequire Import ZArith.\nRequire Import Parser.\nRequire Import String.\nRequire Import Monad.\nRequire Import Maps.\nRequire Import i8051Syntax.\nRequire Import Eqdep.\nSet Implicit Arguments.\nUnset Automatic Introduction.\n\nDefinition size1 := 0.\nDefinition size4 := 3.\nDefinition size8 := 7.\nDefinition size16 := 15.\nDefinition size32 := 31.\nDefinition int n := Word.int n.\n\nModule Type MACHINE_SIG.\n  (** We abstract over locations which include things like registers, flags, the pc, \n      segment registers, etc.  Our only assumption is that updates to distinct locations\n      commute. *)\n  Variable location : nat -> Set.  (* registers, flags, etc. *)\n\n  (** We also abstract over the size of memory, by parameterizing the RTLs over the\n      number of bits in addresses. *)\n  Variable size_addr : nat.  (* number of bits in a memory adress minus one *)\n  Variable size_pc : nat.\n  (** We assume some type for the machine state *)\n  Variable mach_state : Type.\n  (** And operations for reading/writing locations *)\n  Variable get_location : forall s, location s -> mach_state -> Word.int s.\n  Variable set_location : forall s, location s -> Word.int s -> mach_state -> mach_state.\nEnd MACHINE_SIG.\n\n(** Generic register-transfer language *)    \nModule RTL(M : MACHINE_SIG).\n  Import M.\n  Local Open Scope Z_scope.\n  Module AddrIndexed.\n    Definition t := int size_addr.\n    Definition index(i:int size_addr) : positive := ZIndexed.index (Word.unsigned i).\n    Lemma index_inj : forall (x y : int size_addr), index x = index y -> x = y.\n    Proof.\n      unfold index. destruct x; destruct y ; simpl ; intros.\n      generalize intrange intrange0. clear intrange intrange0.\n      rewrite (ZIndexed.index_inj intval intval0 H). intros.\n      rewrite (Coqlib.proof_irrelevance _ intrange intrange0). auto.\n    Qed.\n    Definition eq := @Word.eq_dec size_addr.\n  End AddrIndexed.\n\n  Module CodeIndexed.\n    Definition t := int size_pc.\n    Definition index(i:int size_pc) : positive := ZIndexed.index (Word.unsigned i).\n    Lemma index_inj : forall (x y : int size_pc), index x = index y -> x = y.\n    Proof.\n      unfold index. destruct x; destruct y ; simpl ; intros.\n      generalize intrange intrange0. clear intrange intrange0.\n      rewrite (ZIndexed.index_inj intval intval0 H). intros.\n      rewrite (Coqlib.proof_irrelevance _ intrange intrange0). auto.\n    Qed.\n    Definition eq := @Word.eq_dec size_pc.\n  End CodeIndexed.\n  Module AddrMap := IMap(AddrIndexed).\n  Module CodeMap := IMap(CodeIndexed).\n\n  (** RTL instructions form a RISC-like core language that operate over pseudo-registers.\n      We assume that we're working under an environment that holds an infinite number of\n      pseudo registers for each bit-vector size of interest.  The instructions include\n      arithmetic operations over bitvectors, test instructions, a primitive conditional\n      instruction, signed and unsigned conversions of bitvectors from one size to another,\n      the ability to read/write locations in the machine state, the ability to read/write\n      locations in memory, the ability to non-deterministically choose a bit-vector, \n      and an error. *)\n  Inductive bit_vector_op : Set := \n    add_op | sub_op | mul_op | divs_op | divu_op | modu_op | mods_op\n  | and_op | or_op | xor_op | shl_op | shr_op | shru_op | ror_op | rol_op.\n\n  Inductive test_op : Set := eq_op | lt_op | ltu_op.\n\n  Inductive pseudo_reg (s:nat) : Set := \n  | ps_reg : Z -> pseudo_reg s.\n\n  Inductive rtl_instr : Type := \n  | arith_rtl : forall s (b:bit_vector_op)(r1 r2:pseudo_reg s)(rd:pseudo_reg s), rtl_instr\n  | test_rtl : forall s (top:test_op)(r1 r2:pseudo_reg s)(rd:pseudo_reg size1), rtl_instr\n  | if_rtl : pseudo_reg size1 -> rtl_instr -> rtl_instr\n  | cast_s_rtl : forall s1 s2 (r1:pseudo_reg s1) (rd:pseudo_reg s2),  rtl_instr\n  | cast_u_rtl : forall s1 s2 (r1:pseudo_reg s1) (rd:pseudo_reg s2),  rtl_instr\n  | load_imm_rtl : forall s (i:int s) (rd:pseudo_reg s),  rtl_instr\n  | set_loc_rtl : forall s (rs:pseudo_reg s) (l:location s), rtl_instr\n  | get_loc_rtl : forall s (l:location s) (rd:pseudo_reg s), rtl_instr\n  | set_byte_rtl: forall (rs:pseudo_reg size8)(addr:pseudo_reg size_addr), rtl_instr\n  | get_byte_rtl: forall (addr:pseudo_reg size_addr)(rd:pseudo_reg size8), rtl_instr\n  | choose_rtl : forall s (rd:pseudo_reg s), rtl_instr\n  | error_rtl : rtl_instr\n  | safe_fail_rtl : rtl_instr.\n\n  (** Next, we give meaning to RTL instructions as transformers over an\n      environment for pseudo-registers and a machine state. *)\n  Definition pseudo_env := forall s, pseudo_reg s -> int s.\n  Definition empty_env : pseudo_env := fun s _ => Word.zero.\n  Definition eq_pseudo_reg s : forall (r1 r2:pseudo_reg s), {r1 = r2} + {r1 <> r2}.\n    intros. destruct r1. destruct r2. destruct (Z_eq_dec z z0). subst. left. auto.\n    right. intro. apply n. congruence.\n  Defined.\n  Definition update_env s (r:pseudo_reg s) (v:int s) (env:pseudo_env) : pseudo_env.\n    intros s r v env s' r'.\n    destruct (eq_nat_dec s s'). subst. destruct (eq_pseudo_reg r r'). subst. apply v.\n    apply (env s' r').\n    apply (env s' r').\n  Defined.\n\n\n  Record oracle := { \n    oracle_bits : forall s, Z -> int s ; \n    oracle_offset : Z\n  }.\n\n  Record rtl_state := { \n    rtl_oracle : oracle ; \n    rtl_env : pseudo_env ; \n    rtl_mach_state : mach_state ; \n    rtl_memory : AddrMap.t int8;\n    rtl_code : CodeMap.t int8\n  }. \n\n  Inductive RTL_ans(A:Type) : Type := \n  | Fail_ans : RTL_ans A\n  | SafeFail_ans : RTL_ans A\n  | Okay_ans : A -> RTL_ans A.\n\n  Definition RTL(T:Type) := rtl_state -> (RTL_ans T * rtl_state).\n\n  Instance RTL_monad : Monad RTL := { \n    Return := fun A (x:A) (rs:rtl_state) => (Okay_ans x, rs) ;\n    Bind := fun A B (c:RTL A) (f:A -> RTL B) (rs:rtl_state) => \n      match c rs with\n        | (Okay_ans v, rs') => f v rs'\n        | (Fail_ans, rs') => (Fail_ans _, rs')\n        | (SafeFail_ans, rs') => (SafeFail_ans _, rs')\n      end\n  }.\n  intros ; apply Coqlib.extensionality. auto.\n  intros ; apply Coqlib.extensionality. intros. destruct (c x) ; auto. destruct r ; auto.\n  intros ; apply Coqlib.extensionality. intros. destruct (f x) ; auto.\n    destruct r ; auto.\n  Defined.\n\n  Definition Fail T : RTL T := fun rs => (Fail_ans T,rs).\n  Definition SafeFail T : RTL T := fun rs => (SafeFail_ans T,rs).\n\n  Definition flush_env : RTL unit :=\n    fun rs => (Okay_ans tt, {| rtl_oracle := rtl_oracle rs ; \n                           rtl_env := empty_env;\n                           rtl_mach_state := rtl_mach_state rs ; \n                           rtl_code := rtl_code rs ; \n                           rtl_memory := rtl_memory rs |}).\n  Definition set_ps s (r:pseudo_reg s) (v:int s) : RTL unit := \n    fun rs => (Okay_ans tt, {| rtl_oracle := rtl_oracle rs ; \n                           rtl_env := update_env r v (rtl_env rs) ;\n                           rtl_mach_state := rtl_mach_state rs ; \n                           rtl_code := rtl_code rs ; \n                           rtl_memory := rtl_memory rs |}).\n  Definition set_loc s (l:location s) (v:int s) : RTL unit := \n    fun rs => (Okay_ans tt, {| rtl_oracle := rtl_oracle rs ; \n                           rtl_env := rtl_env rs ; \n                           rtl_mach_state := set_location l v (rtl_mach_state rs) ; \n                           rtl_code := rtl_code rs ; \n                           rtl_memory := rtl_memory rs |}).\n\n  Definition set_byte (addr:int size_addr) (v:int size8) : RTL unit := \n    fun rs => (Okay_ans tt, {| rtl_oracle := rtl_oracle rs ; \n                           rtl_env := rtl_env rs ; \n                           rtl_mach_state := rtl_mach_state rs ;\n                           rtl_code := rtl_code rs ; \n                           rtl_memory := AddrMap.set addr v (rtl_memory rs) |}).\n\n  Definition set_code_byte (addr:int size_pc) (v:int size8) : RTL unit := \n    fun rs => (Okay_ans tt, {| rtl_oracle := rtl_oracle rs ; \n                           rtl_env := rtl_env rs ; \n                           rtl_mach_state := rtl_mach_state rs ;\n                           rtl_code := CodeMap.set addr v (rtl_code rs) ; \n                           rtl_memory := rtl_memory rs |}).\n  Definition get_ps s (r:pseudo_reg s) : RTL (int s) := \n    fun rs => (Okay_ans (rtl_env rs r), rs).\n  Definition get_loc s (l:location s) : RTL (int s) :=\n    fun rs => (Okay_ans (get_location l (rtl_mach_state rs)), rs).\n  Definition get_byte (addr:int size_addr) : RTL (int size8) := \n    fun rs => (Okay_ans (AddrMap.get addr (rtl_memory rs)), rs).\n\n\n  Definition get_code_byte (addr:int size_pc) : RTL (int size8) := \n    fun rs => (Okay_ans (CodeMap.get addr (rtl_code rs)), rs).\n  Definition choose_bits (s:nat) : RTL (int s) := \n    fun rs => \n      let o := rtl_oracle rs in \n      let o' := {| oracle_bits := oracle_bits o; oracle_offset := oracle_offset o + 1 |} in\n        (Okay_ans (oracle_bits o s (oracle_offset o)), \n          {| rtl_oracle := o' ;\n             rtl_env := rtl_env rs ; \n             rtl_mach_state := rtl_mach_state rs ;\n             rtl_code := rtl_code rs ; \n             rtl_memory := rtl_memory rs |}).\n  \n  Definition interp_arith s (b:bit_vector_op)(v1 v2:int s) : int s := \n    match b with \n      | add_op => Word.add v1 v2\n      | sub_op => Word.sub v1 v2\n      | mul_op => Word.mul v1 v2\n      | divs_op => Word.divs v1 v2\n      | divu_op => Word.divu v1 v2\n      | modu_op => Word.modu v1 v2\n      | mods_op => Word.mods v1 v2\n      | and_op => Word.and v1 v2\n      | or_op => Word.or v1 v2\n      | xor_op => Word.xor v1 v2\n      | shl_op => Word.shl v1 v2\n      | shr_op => Word.shr v1 v2\n      | shru_op => Word.shru v1 v2\n      | ror_op => Word.ror v1 v2\n      | rol_op => Word.rol v1 v2\n    end.\n\n  Definition interp_test s (t:test_op)(v1 v2:int s) : int size1 := \n    if (match t with \n      | eq_op => Word.eq v1 v2 \n      | lt_op => Word.lt v1 v2\n      | ltu_op => Word.ltu v1 v2\n        end) then Word.one else Word.zero.\n\n  Local Open Scope monad_scope.\n\n  Fixpoint interp_rtl (instr:rtl_instr) : RTL unit := \n    match instr with \n      | arith_rtl s b r1 r2 rd => \n        v1 <- get_ps r1 ; v2 <- get_ps r2 ; set_ps rd (interp_arith b v1 v2)\n      | test_rtl s t r1 r2 rd => \n        v1 <- get_ps r1 ; v2 <- get_ps r2 ; set_ps rd (interp_test t v1 v2)\n      | if_rtl r i => \n        v <- get_ps r ; if (Word.eq v Word.one) then interp_rtl i else ret tt\n      | cast_s_rtl s1 s2 rs rd => \n        v <- get_ps rs ; \n        set_ps rd (Word.repr (Word.signed v))\n      | cast_u_rtl s1 s2 rs rd => \n        v <- get_ps rs ; \n        set_ps rd (Word.repr (Word.unsigned v))\n      | load_imm_rtl s i rd => set_ps rd i\n      | set_loc_rtl s rs l => v <- get_ps rs ; set_loc l v\n      | get_loc_rtl s l rd => v <- get_loc l ; set_ps rd v\n      | set_byte_rtl rs addr => v <- get_ps rs ; a <- get_ps addr ; set_byte a v\n      | get_byte_rtl addr rd => a <- get_ps addr ; v <- get_byte a ; set_ps rd v\n      | choose_rtl s rd => v <- choose_bits s ; set_ps rd v\n      | error_rtl => Fail unit\n      | safe_fail_rtl => SafeFail unit\n    end.\n\n  (** We collect all of the information for an instruction into a record\n      satisfying this interface. *)\n  Record instruction := { \n    instr_assembly : string ;  (* for printing/debugging *)\n    instr_rtl : list rtl_instr (* semantics as RTL instructions *)\n  }.\nEnd RTL.\n\n", "meta": {"author": "JeremyRubin", "repo": "VerifiedDSP", "sha": "a28fb79035bf5689fb9285c5581d5c1bc1a0b0db", "save_path": "github-repos/coq/JeremyRubin-VerifiedDSP", "path": "github-repos/coq/JeremyRubin-VerifiedDSP/VerifiedDSP-a28fb79035bf5689fb9285c5581d5c1bc1a0b0db/Model/RTL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.23500371748992466}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.floyd.library.\nRequire Import VST.progs.list_dt.  Import LsegSpecial.\nRequire Import VST.progs.queue2.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition t_struct_elem := Tstruct _elem noattr.\nDefinition t_struct_fifo := Tstruct _fifo noattr.\n\nInstance QS: listspec _elem _next (fun sh => malloc_token Ews t_struct_elem).\nProof. eapply mk_listspec; reflexivity. Defined.\n\nLemma isnil: forall {T: Type} (s: list T), {s=nil}+{s<>nil}.\nProof. intros. destruct s; [left|right]; auto. intro Hx; inv Hx. Qed.\n\nLemma field_at_list_cell:\n  forall sh i v p,\n  data_at sh t_struct_elem (i,v) p\n  = list_cell QS sh i p *\n  field_at sh t_struct_elem [StructField _next] v p.\nProof.\nintros.\nunfold_data_at (data_at _ _ _ _).\nf_equal.\nunfold field_at, list_cell.\nautorewrite with gather_prop.\nf_equal.\napply ND_prop_ext.\nrewrite field_compatible_cons; simpl.\nintuition.\nleft; auto.\nQed.\n\nDefinition surely_malloc_spec :=\n  DECLARE _surely_malloc\n   WITH t:type, gv: globals\n   PRE [ _n OF tuint ]\n       PROP (0 <= sizeof t <= Int.max_unsigned;\n                complete_legal_cosu_type t = true;\n                natural_aligned natural_alignment t = true)\n       LOCAL (temp _n (Vint (Int.repr (sizeof t))); gvars gv)\n       SEP (mem_mgr gv)\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (mem_mgr gv; malloc_token Ews t p * data_at_ Ews t p).\n\nDefinition fifo_body (contents: list val) (hd tl : val) :=\n     (if isnil contents\n      then (!!(hd=nullval) && emp)\n      else (EX prefix: list val, EX last: val,\n              !!(contents = prefix++last::nil)\n            &&  (lseg QS Ews prefix hd tl\n                   * malloc_token Ews t_struct_elem tl\n                   * data_at Ews t_struct_elem (last, nullval) tl)))%logic.\n\nDefinition fifo (contents: list val) (p: val) : mpred :=\n  EX ht: (val*val), let (hd,tl) := ht in\n      !! is_pointer_or_null hd && !! is_pointer_or_null tl &&\n      data_at Ews t_struct_fifo (hd, tl) p * malloc_token Ews t_struct_fifo p *\n      fifo_body contents hd tl.\n\nDefinition fifo_new_spec :=\n DECLARE _fifo_new\n  WITH gv: globals\n  PRE  [  ]\n       PROP() LOCAL(gvars gv) SEP (mem_mgr gv)\n  POST [ (tptr t_struct_fifo) ]\n    EX v:val, PROP() LOCAL(temp ret_temp v) SEP (mem_mgr gv; fifo nil v).\n\nDefinition fifo_put_spec :=\n DECLARE _fifo_put\n  WITH q: val, contents: list val, p: val, last: val\n  PRE  [ _Q OF (tptr t_struct_fifo) , _p OF (tptr t_struct_elem) ]\n          PROP () LOCAL (temp _Q q; temp _p p)\n          SEP (fifo contents q;\n                 malloc_token Ews t_struct_elem p;\n                 data_at Ews t_struct_elem (last,Vundef) p)\n  POST [ tvoid ]\n          PROP() LOCAL() SEP (fifo (contents++(last :: nil)) q).\n\nDefinition fifo_empty_spec :=\n DECLARE _fifo_empty\n  WITH q: val, contents: list val\n  PRE  [ _Q OF (tptr t_struct_fifo) ]\n     PROP() LOCAL (temp _Q q) SEP(fifo contents q)\n  POST [ tint ]\n      PROP ()\n      LOCAL(temp ret_temp (if isnil contents then Vtrue else Vfalse))\n      SEP (fifo (contents) q).\n\nDefinition fifo_get_spec :=\n DECLARE _fifo_get\n  WITH q: val, contents: list val, first: val\n  PRE  [ _Q OF (tptr t_struct_fifo) ]\n       PROP() LOCAL (temp _Q q) SEP (fifo (first :: contents) q)\n  POST [ (tptr t_struct_elem) ]\n      EX p:val,\n       PROP ()\n       LOCAL(temp ret_temp p)\n       SEP (fifo contents q;\n              malloc_token Ews t_struct_elem p;\n              data_at Ews t_struct_elem (first,Vundef) p).\n\nDefinition make_elem_spec :=\n DECLARE _make_elem\n  WITH i: int, gv: globals\n  PRE  [ _data OF tint ]\n        PROP() LOCAL(temp _data (Vint i); gvars gv) SEP(mem_mgr gv)\n  POST [ (tptr t_struct_elem) ]\n    EX p:val,\n       PROP()\n       LOCAL (temp ret_temp p)\n       SEP (mem_mgr gv; \n              malloc_token Ews t_struct_elem p;\n              data_at Ews t_struct_elem (Vint i, Vundef) p).\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv: globals\n  PRE  [] main_pre prog nil gv\n  POST [ tint ]\n       PROP() LOCAL (temp ret_temp (Vint (Int.repr 1))) SEP(TT).\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog\n    [surely_malloc_spec; fifo_new_spec; fifo_put_spec;\n     fifo_empty_spec; fifo_get_spec; make_elem_spec;\n     main_spec]).\n\nLemma body_surely_malloc: semax_body Vprog Gprog f_surely_malloc surely_malloc_spec.\nProof.\n  start_function.\n  forward_call (* p = malloc(n); *)\n     (t,gv).\n  Intros p.\n  forward_if\n  (PROP ( )\n   LOCAL (temp _p p)\n   SEP (mem_mgr gv; malloc_token Ews t p * data_at_ Ews t p)).\n*\n  if_tac.\n    subst p. entailer!.\n    entailer!.\n*\n    forward_call tt.\n    contradiction.\n*\n    if_tac.\n    + forward. subst p. congruence.\n    + Intros. forward. entailer!.\n*\n  forward. Exists p; entailer!.\nQed.\n\nLemma fifo_isptr: forall al q, fifo al q |-- !! isptr q.\nProof.\nintros.\n unfold fifo, fifo_body.\n if_tac; entailer; destruct ht; entailer!.\nQed.\n\nHint Resolve fifo_isptr : saturate_local.\n\nLemma body_fifo_empty: semax_body Vprog Gprog f_fifo_empty fifo_empty_spec.\nProof.\nstart_function.\nunfold fifo.\nIntros ht; destruct ht as [hd tl].\nIntros.\nforward. (* h = Q->head; *)\nforward. (* return (h == NULL); *)\n{\nunfold fifo, fifo_body.\ndestruct (isnil contents).\n+ normalize; auto with valid_pointer.\n+ entailer!.\n  destruct hd; inv PNhd; entailer!.\n}\nunfold fifo, fifo_body.\nExists (hd,tl).\ndestruct (isnil contents).\n* entailer!.\n* Intros prefix last.\nExists prefix last.\n  assert_PROP (isptr hd).\n    destruct prefix; entailer.\n    rewrite @lseg_cons_eq by auto. Intros y.\n    entailer.\n destruct hd; try contradiction.\n entailer!.\nQed.\n\nLemma body_fifo_new: semax_body Vprog Gprog f_fifo_new fifo_new_spec.\nProof.\n  start_function.\n\n  forward_call (* Q = surely_malloc(sizeof ( *Q)); *)\n     (t_struct_fifo, gv).\n    split3; simpl; auto; computable.\n  Intros q.\n  assert_PROP (field_compatible t_struct_fifo [] q).\n   entailer!.\n  forward. (* Q->head = NULL; *)\n  forward. (* Q->tail = NULL; *)\n  forward. (* return Q; *)\n  Exists q. unfold fifo, fifo_body. Exists (nullval,nullval).\n  rewrite if_true by auto.\n  simpl sizeof.\n  entailer!.\nQed.\n\nLemma body_fifo_put: semax_body Vprog Gprog f_fifo_put fifo_put_spec.\nProof.\nstart_function.\nunfold fifo at 1.\nIntros ht; destruct ht as [hd tl].\nIntros.\nforward. (* p->next = NULL; *)\nforward. (*   h = Q->head; *)\nforward_if\n  (PROP() LOCAL () SEP (fifo (contents ++ last :: nil) q))%assert.\n* unfold fifo_body; if_tac; entailer.  (* typechecking clause *) \n      (* TODO: In the line above, entailer works but not entailer! *)\n* (* then clause *)\n  subst.\n  forward. (* Q->head=p; *)\n  forward. (* Q->tail=p; *)\n  entailer.\n  unfold fifo, fifo_body.\n  destruct (isnil contents).\n  + subst. Exists (p,p).\n     simpl. rewrite if_false by congruence.\n     Exists (@nil val) last.\n      rewrite @lseg_nil_eq by auto.\n      entailer!.\n   + Intros prefix last0.\n      destruct prefix;\n      entailer!.\n      rewrite @lseg_cons_eq by auto. simpl.\n      Intros y.\n      entailer!.\n* (* else clause *)\n  forward. (*  t = Q->tail; *)\n  unfold fifo_body.\n  destruct (isnil contents).\n  + Intros. contradiction H; auto.\n  + Intros prefix last0.\n     forward. (*  t->next=p; *)\n     forward. (* Q->tail=p; *)\n     entailer!.\n     unfold fifo, fifo_body. Exists (hd, p).\n     rewrite if_false by (clear; destruct prefix; simpl; congruence).\n     Exists  (prefix ++ last0 :: nil) last.\n     entailer.\n     rewrite (field_at_list_cell Ews last0 p).\n     unfold_data_at (@data_at CompSpecs Ews t_struct_elem (last,nullval) p).\n     unfold_data_at (data_at _ _ _ p).\n     simpl sizeof.\n     match goal with\n     | |- _ |-- _ * _ * (_ * ?AA) => remember AA as A\n     end.     (* prevent it from canceling! *)\n     cancel. subst A.\n     eapply derives_trans;\n        [ | apply (lseg_cons_right_neq QS Ews prefix hd last0 tl nullval p ); auto].\n     simpl sizeof.  cancel.\n* (* after the if *)\n     forward. (* return ; *)\nQed.\n\nLemma body_fifo_get: semax_body Vprog Gprog f_fifo_get fifo_get_spec.\nProof.\nstart_function.\nunfold fifo at 1, fifo_body.\nIntros ht; destruct ht as [hd tl].\nrewrite if_false by congruence.\nIntros prefix last.\nforward.  (*   h = Q->head; *)\ndestruct prefix; inversion H; clear H.\n+\n   rewrite @lseg_nil_eq by auto.\n   Intros.\n   subst_any.\n   forward. (*  n=h->next; *)\n   forward. (* Q->head=n; *)\n   forward. (* return p; *)\n   unfold fifo, fifo_body. Exists tl (nullval, tl).\n   rewrite if_true by congruence.\n   entailer!. simpl sizeof.\n   do 2 unfold_data_at (data_at _ _ _ _). cancel.\n+ rewrite @lseg_cons_eq by auto.\n    Intros x.\n    simpl @valinject. (* can we make this automatic? *)\n    subst_any.\n    forward. (*  n=h->next; *)\n    forward. (* Q->head=n; *)\n    forward. (* return p; *)\n    Exists hd. unfold fifo, fifo_body. Exists (x, tl).\n    rewrite if_false by (destruct prefix; simpl; congruence).\n    Exists prefix last.\n    entailer!.\n    rewrite field_at_list_cell. simpl sizeof. cancel.\nQed.\n\nLemma body_make_elem: semax_body Vprog Gprog f_make_elem make_elem_spec.\nProof.\nstart_function.\nforward_call (*  p = surely_malloc(sizeof ( *p));  *)\n    (t_struct_elem, gv).\n split3; simpl; auto; computable.\n Intros p.\nforward.  (*  p->data=i; *)\nsimpl.\nforward. (* return p; *)\nExists p.\nentailer!.\nQed.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nsep_apply (create_mem_mgr gv).\nforward_call (* Q = fifo_new(); *)  gv.\nIntros q.\n\nforward_call  (*  p = make_elem(1); *)\n     (Int.repr 1, gv).\nIntros p'.\nforward_call (* fifo_put(Q,p);*)\n    ((q, @nil val),p', Vint (Int.repr 1)).\n\nforward_call  (*  p = make_elem(2); *)\n     (Int.repr 2, gv).\nIntros p2.\nsimpl app.\n forward_call  (* fifo_put(Q,p); *)\n    (((q,[Vint (Int.repr 1)]),p2), Vint (Int.repr 2)).\nsimpl app.\nforward_call  (*   p' = fifo_get(Q); p = p'; *)\n    ((q,[Vint (Int.repr 2)]), Vint (Int.repr 1)).\nIntros p3.\nforward. (*   i = p->data;  *)\nforward_call (*  free(p); *)\n   (t_struct_elem, p3, gv).\nassert_PROP (isptr p3); [entailer! | rewrite if_false by (intro; subst; contradiction) ]; cancel.\nforward. (* return i; *)\nQed.\n\nExisting Instance NullExtension.Espec.\n\nLemma prog_correct:\n  semax_prog prog Vprog Gprog.\nProof.\nprove_semax_prog.\nsemax_func_cons body_malloc. apply semax_func_cons_malloc_aux.\nsemax_func_cons body_free.\nsemax_func_cons body_exit.\nsemax_func_cons body_surely_malloc.\nsemax_func_cons body_fifo_new.\nsemax_func_cons body_fifo_put.\nsemax_func_cons body_fifo_empty.\nsemax_func_cons body_fifo_get.\nsemax_func_cons body_make_elem.\nsemax_func_cons body_main.\nQed.\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/progs/verif_queue2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23493508547998257}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.lib.Axioms.\n\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\nRequire Import VST.msl.Extensionality.\n\nRequire Import VST.sepcomp.mem_lemmas.\nRequire Import VST.sepcomp.semantics.\n\nRequire Import VST.concurrency.machine_semantics.\n\nRequire Import VST.msl.Coqlib2.\n\nSection thread_stepN.\n  Context {G TID SCH TR C M E:Type} (Sem:@ConcurSemantics G TID SCH TR C M) (ge:G).\n\n  Fixpoint thread_stepN (n:nat) : SCH -> C -> M -> C -> M -> Prop :=\n    match n with\n      | O => fun U c m c' m' => (c,m) = ( c',m')\n      | S k => fun U c1 m1 c3 m3 => exists c2, exists m2,\n        @thread_step _ _ _ _ _ _ Sem ge U c1 m1 c2 m2 /\\\n        thread_stepN k U c2 m2 c3 m3\n    end.\n\n  Lemma thread_stepN_add : forall n m U c1 m1 c3 m3,\n    thread_stepN (n+m) U c1 m1 c3 m3 <->\n    exists c2, exists m2,\n      thread_stepN n U c1 m1 c2 m2 /\\\n      thread_stepN m U c2 m2 c3 m3.\n  Proof.\n    induction n; simpl; intuition.\n    firstorder. firstorder.\n    inv H. auto.\n    decompose [ex and] H. clear H.\n    destruct (IHn m U x x0 c3 m3).\n    apply H in H2.\n    decompose [ex and] H2. clear H2.\n    repeat econstructor; eauto.\n    decompose [ex and] H. clear H.\n    exists x1. exists x2; split; auto.\n    destruct (IHn m U x1 x2 c3 m3).\n    eauto.\n  Qed.\n\n  Definition thread_step_plus U c m c' m' :=\n    exists n, thread_stepN (S n) U c m c' m'.\n\n  Definition thread_step_star U c m c' m' :=\n    exists n, thread_stepN n U c m c' m'.\n\n  Lemma thread_step_plus_star : forall U c1 c2 m1 m2,\n    thread_step_plus U c1 m1 c2 m2 -> thread_step_star U c1 m1 c2 m2.\n  Proof. intros. destruct H as [n1 H1]. eexists. apply H1. Qed.\n\n  Lemma thread_step_plus_trans : forall U c1 c2 c3 m1 m2 m3,\n    thread_step_plus U c1 m1 c2 m2 -> thread_step_plus U c2 m2 c3 m3 ->\n    thread_step_plus U c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (thread_stepN_add (S n1) (S n2) U  c1 m1 c3 m3) as [_ H].\n    eexists. apply H. exists c2. exists m2. split; assumption.\n  Qed.\n\n  Lemma thread_step_star_plus_trans : forall U c1 c2 c3 m1 m2 m3,\n    thread_step_star U c1 m1 c2 m2 -> thread_step_plus U c2 m2 c3 m3 ->\n    thread_step_plus U c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (thread_stepN_add n1 (S n2) U  c1 m1 c3 m3) as [_ H].\n    rewrite <- plus_n_Sm in H.\n    eexists. apply H.  exists c2. exists m2.  split; assumption.\n  Qed.\n\n  Lemma thread_step_plus_star_trans: forall U c1 c2 c3 m1 m2 m3,\n    thread_step_plus U c1 m1 c2 m2 -> thread_step_star U c2 m2 c3 m3 ->\n    thread_step_plus U c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (thread_stepN_add (S n1) n2 U c1 m1 c3 m3) as [_ H].\n    rewrite plus_Sn_m in H.\n    eexists. apply H.  exists c2. exists m2.  split; assumption.\n  Qed.\n\n  Lemma thread_step_star_trans: forall U c1 c2 c3 m1 m2 m3,\n    thread_step_star U c1 m1 c2 m2 -> thread_step_star U c2 m2 c3 m3 ->\n    thread_step_star U c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    destruct (thread_stepN_add n1 n2 U c1 m1 c3 m3) as [_ H].\n    eexists. apply H.  exists c2. exists m2.  split; assumption.\n  Qed.\n\n  Lemma thread_step_plus_one: forall U c m c' m',\n    thread_step  Sem ge U c m c' m' -> thread_step_plus U c m c' m'.\n  Proof. intros. unfold thread_step_plus, thread_stepN. simpl.\n    exists O. exists c'. exists m'. eauto.\n  Qed.\n\n  Lemma thread_step_plus_two: forall U c m c' m' c'' m'',\n    thread_step  Sem ge U c m c' m' -> thread_step  Sem ge U c' m' c'' m'' ->\n    thread_step_plus U c m c'' m''.\n  Proof. intros.\n    exists (S O). exists c'. exists m'. split; trivial.\n    exists c''. exists m''. split; trivial. reflexivity.\n  Qed.\n\n  Lemma thread_step_star_zero: forall U c m, thread_step_star U c m c m.\n  Proof. intros. exists O. reflexivity. Qed.\n\n  Lemma thread_step_star_one: forall U c m c' m',\n    thread_step  Sem ge U c m c' m' -> thread_step_star U c m c' m'.\n  Proof. intros.\n    exists (S O). exists c'. exists m'. split; trivial. reflexivity.\n  Qed.\n\n  Lemma thread_step_plus_split: forall U c m c' m',\n    thread_step_plus U c m c' m' ->\n    exists c'', exists m'', thread_step  Sem ge U c m c'' m'' /\\\n      thread_step_star U  c'' m'' c' m'.\n  Proof. intros.\n    destruct H as [n [c2 [m2 [Hstep Hstar]]]]. simpl in*.\n    exists c2. exists m2. split. assumption. exists n. assumption.\n  Qed.\n\nEnd thread_stepN.", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/concurrency/machine_semantics_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23493508547998251}}
{"text": "(**\n * Queue.v\n *\n * Low level queue representation.\n *)\n\n(** Compcert helper lib *)\nRequire Import Coqlib.\nRequire Import Maps.\n(** Compcert types and semantics *)\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Globalenvs.\nRequire Import Clight.\nRequire Import Ctypes.\nRequire Import Cop.\nRequire Import Smallstep.\n(** CertiKOS layer library *)\nRequire Import Semantics.\nRequire Import Structures.\nRequire Import GenSem.\nRequire Import CGenSem.\nRequire Import CPrimitives.\nRequire Import SimulationRelation.\nRequire Import SimrelInvariant.\nRequire Import LayerLogicImpl.\nRequire Import ClightModules.\nRequire Import ClightXSemantics.\nRequire Import MakeProgramSpec.\nRequire Import AbstractData.\nRequire Import AbstractionRelation.\n\nRequire Import TutoLib.\nRequire Import QueueData.\nRequire Import Node.\nRequire Import QueueIntro.\n\n(** In this file we implement the [enqueue] and [dequeue] primitives on the\n  low-level linked-list representation of the queue. *)\n\nOpen Scope Z_scope.\n\nDefinition enqueue : ident := 31%positive.\nDefinition dequeue : ident := 32%positive.\n\nSection Queue.\n\n  Context `{Hmem: BaseMemoryModel}.\n  Context `{MakeProgramSpec.MakeProgram}.\n\n  (** ** Abstract Data *)\n  Section AbsData.\n\n    Definition intro_L := node_L ⊕ queue_intro_L.\n\n    Definition intro_M := node_M ⊕ queue_intro_M.\n\n    Lemma intro_pres_inv :\n      ForallPrimitive _ (CPrimitivePreservesInvariant _) intro_L.\n    Proof. unfold intro_L, node_L, queue_intro_L. typeclasses eauto. Qed.\n\n    (** We now require that once initialized, all nodes in range are valid,\n      and everything else is undefined. *)\n    Record queue_inv (d: abs_data) : Prop := {\n      npool_valid: forall node,\n        init_flag d = true ->\n        0 <= node < MAX_NODES ->\n        node_valid (ZMap.get node (npool d));\n      npool_range: forall node,\n        ~(0 <= node < MAX_NODES) ->\n        ZMap.get node (npool d) = NodeUndef;\n      preinit_q: init_flag d = false -> queue d = QueueUndef;\n      q_valid: init_flag d = true -> queue_valid (queue d);\n    }.\n\n    Instance queue_data_ops : AbstractDataOps abs_data :=\n      {|\n        init_data := abs_data_init;\n        data_inv := queue_inv;\n        data_inject := fun _ _ _ => True\n      |}.\n\n    Instance queue_data_data : AbstractData abs_data.\n    Proof.\n      constructor; constructor; cbn; intros; try congruence.\n      rewrite ZMap.gi; reflexivity.\n    Qed.\n\n    Definition queue_layerdata : layerdata :=\n      {|\n        ldata_type := abs_data;\n        ldata_ops  := queue_data_ops;\n        ldata_prf  := queue_data_data\n      |}.\n\n  End AbsData.\n\n  (** ** High Level Specifications *)\n  Section HighSpec.\n\n    (** The two possibilities for [enqueue] are:\n        - Queue is empty: set head and tail equal to the new node\n        - Queue is not empty: set tail to the new node and make the new node\n          and the old tail point to each other *)\n    Definition enqueue_high_spec (node: Z) (abs: queue_layerdata)\n        : option queue_layerdata :=\n      if init_flag abs\n        then if decide (0 <= node < MAX_NODES)\n          then match queue abs, ZMap.get node (npool abs) with\n            | Queue hd tl, Node dat _ _ =>\n                if decide (tl = MAX_NODES)\n                  then let n := Node dat MAX_NODES MAX_NODES in\n                    Some abs {queue: Queue node node}\n                             {npool: ZMap.set node n (npool abs)}\n                  else match ZMap.get tl (npool abs) with\n                    | Node tldat _ tlprv =>\n                        let n := Node dat MAX_NODES tl in\n                        let tl' := Node tldat node tlprv in\n                        Some abs {queue: Queue hd node}\n                                 {npool: ZMap.set node n (ZMap.set tl tl' (npool abs))}\n                    | _ => None\n                  end\n            | _, _ => None\n          end\n          else None\n        else None.\n\n    Definition enqueue_high_sem : cprimitive queue_layerdata :=\n      cgensem _ enqueue_high_spec.\n\n    Global Instance enqueue_pres_inv :\n      GenSemPreservesInvariant queue_layerdata enqueue_high_spec.\n    Proof.\n      split; auto.\n      intros ? ? ? ? ? Hsem ? Hinv.\n      inv_generic_sem Hsem.\n      unfold enqueue_high_spec in H2.\n      destruct Hinv.\n      repeat destr_in H2; inv H2.\n      - (** tl = MAX_NODES *)\n        constructor; cbn; intros; auto; try congruence.\n        + (** npool_valid *)\n          destr_eq node (Int.unsigned i); [subst |].\n          * rewrite ZMap.gss; constructor; omega.\n          * rewrite ZMap.gso; auto.\n        + (** npool_range *)\n          destr_eq node (Int.unsigned i); [subst |].\n          * omega.\n          * rewrite ZMap.gso; auto.\n        + (** q_valid *)\n          constructor; omega.\n      - (** tl <> MAX_NODES *)\n        constructor; cbn; intros; auto; try congruence.\n        + (** npool_valid *)\n          destr_eq node (Int.unsigned i); [subst |].\n          * rewrite ZMap.gss; constructor; try omega.\n            specialize (q_valid0 eq_refl).\n            inv q_valid0; auto.\n          * rewrite ZMap.gso; auto.\n            destr_eq node tail; [subst |].\n            -- rewrite ZMap.gss.\n               apply npool_valid0 in H2; auto; inv H2.\n               constructor; (omega || congruence).\n            -- rewrite ZMap.gso; auto.\n        + (** npool_range *)\n          destr_eq node (Int.unsigned i); [subst |].\n          * omega.\n          * rewrite ZMap.gso; auto.\n            destr_eq node tail; [subst |].\n            -- apply npool_range0 in H1. congruence.\n            -- rewrite ZMap.gso; auto.\n        + (** q_valid *)\n          constructor; try omega.\n          specialize (q_valid0 eq_refl).\n          inv q_valid0; auto.\n    Qed.\n\n    (** [dequeue] also has two cases:\n        - Queue has 1 element: set head and tail to [MAX_NODES]\n        - Queue has more elements: set head to the old head's next node node\n          and set the new head's prev to [MAX_NODES]\n\n        One subtlety is that the order we update hd and hdnxt in the second\n        case is important. We want to ensure that the node that is returned has\n        its next and prev fields set to [MAX_NODES] so only nodes actually in\n        the queue point to other nodes. Since we do not yet require that there\n        are no cycles at this layer, it is possible for hd.next = hd in which\n        case updating hd, then hd.next would undo the first step. Of course it\n        is possible to design the specification to allow this behaviour, but it\n        would require a change in the C code.\n\n        TUTORIAL (optional):\n        If you feel adventurous, uncomment the alternative version below and\n        see how far through the proofs you get before you are stuck. You will\n        find that at some point in the code proof you have to prove something\n        like:\n        [ZMap.set hd (Node data MAX_NODES MAX_NODES) =\n         ZMap.set hd (Node data hd MAX_NODES)] *)\n    Definition dequeue_high_spec (abs: queue_layerdata)\n        : option (queue_layerdata * Z) :=\n      if init_flag abs\n        then match queue abs with\n          | Queue hd tl =>\n              if decide (hd <> MAX_NODES)\n                then match ZMap.get hd (npool abs) with\n                  | Node hddat hdnxt _ =>\n                      let n := Node hddat MAX_NODES MAX_NODES in\n                      let pool' := ZMap.set hd n (npool abs) in\n                      if decide (hdnxt = MAX_NODES)\n                        then Some (abs {queue: Queue MAX_NODES MAX_NODES}\n                                       {npool: pool'},\n                                   hd)\n                        else match ZMap.get hdnxt (npool abs) with\n                          | Node nxtdat nxtnxt _ =>\n                              Some (abs {queue: Queue hdnxt tl}\n                                        (** Swap these npools to see why the\n                                           order matters *)\n                                        (** {npool: ZMap.set hdnxt (Node nxtdat nxtnxt MAX_NODES ) pool'}, *)\n                                        {npool: ZMap.set hd n\n                                                  (ZMap.set hdnxt\n                                                            (Node nxtdat nxtnxt MAX_NODES)\n                                                            (npool abs))},\n                                    hd)\n                          | _ => None\n                        end\n                  | _ => None\n                end\n                else None\n          | _ => None\n        end\n        else None.\n\n    Definition dequeue_high_sem : cprimitive queue_layerdata :=\n      cgensem _ dequeue_high_spec.\n\n    Global Instance dequeue_pres_inv :\n      GenSemPreservesInvariant queue_layerdata dequeue_high_spec.\n    Proof.\n      Opaque Z.mul.\n      split; auto.\n      intros ? ? ? ? ? Hsem ? Hinv.\n      inv_generic_sem Hsem.\n      unfold dequeue_high_spec in H2.\n      destruct Hinv.\n      pose proof MAX_NODES_range as Hmn_range.\n      repeat destr_in H2; inv H2.\n      - constructor; cbn; intros; auto; try congruence.\n        + (** npool_valid *)\n          destr_eq node (Int.unsigned z); [subst |].\n          * rewrite ZMap.gss; constructor; omega.\n          * rewrite ZMap.gso; auto.\n        + (** npool_range *)\n          destr_eq node (Int.unsigned z); [subst |].\n          * apply npool_range0 in H1. congruence.\n          * rewrite ZMap.gso; auto.\n        + (** q_valid *)\n          constructor; omega.\n      - constructor; cbn; intros; auto; try congruence.\n        + (** npool_valid *)\n          destr_eq node (Int.unsigned z); [subst |].\n          * rewrite ZMap.gss.\n            constructor; omega.\n          * rewrite ZMap.gso; auto.\n            destr_eq node next; [subst |].\n            -- rewrite ZMap.gss.\n               apply npool_valid0 in H2; auto; inv H2.\n               constructor; (omega || congruence).\n            -- rewrite ZMap.gso; auto.\n        + (** npool_range *)\n          destr_eq node (Int.unsigned z); [subst |].\n          * apply npool_range0 in H1. congruence.\n          * rewrite ZMap.gso; auto.\n            destr_eq node next; [subst |].\n            -- apply npool_range0 in H1. congruence.\n            -- rewrite ZMap.gso; auto.\n        + (** q_valid *)\n          specialize (q_valid0 eq_refl).\n          inv q_valid0.\n          assert (Hz: 0 <= Int.unsigned z < MAX_NODES).\n          { cut (0 <= Int.unsigned z <= MAX_NODES /\\ Int.unsigned z <> MAX_NODES);\n            [omega | split]; eauto. }\n          apply npool_valid0 in Hz; auto; inv Hz.\n          constructor; congruence.\n      Qed.\n\n  End HighSpec.\n\n  (** ** Module Implementation *)\n  Section Code.\n\n    Definition e_node : ident := 35%positive.\n    Definition e_tail : ident := 36%positive.\n\n    Definition f_enqueue' :=\n      {|\n        fn_return := tvoid;\n        fn_callconv := cc_default;\n        fn_params := (e_node, tuint) :: nil;\n        fn_vars := nil;\n        fn_temps := (e_tail, tuint) :: nil;\n        fn_body :=\n          Ssequence\n           (Scall (Some e_tail)\n             (Evar get_tail (Tfunction Ctypes.Tnil tuint cc_default)) nil)\n           (Sifthenelse (Ebinop Oeq (Etempvar e_tail tuint)\n                          (Econst_int (Int.repr MAX_NODES) tint) tint)\n             (Ssequence\n               (Scall None\n                 (Evar set_next (Tfunction (Ctypes.Tcons tuint (Ctypes.Tcons tuint Ctypes.Tnil)) tvoid\n                                   cc_default))\n                 ((Etempvar e_node tuint) :: (Econst_int (Int.repr MAX_NODES) tint) :: nil))\n               (Ssequence\n                 (Scall None\n                   (Evar set_prev (Tfunction (Ctypes.Tcons tuint (Ctypes.Tcons tuint Ctypes.Tnil)) tvoid\n                                     cc_default))\n                   ((Etempvar e_node tuint) :: (Econst_int (Int.repr MAX_NODES) tint) ::\n                    nil))\n                 (Ssequence\n                   (Scall None\n                     (Evar set_head (Tfunction (Ctypes.Tcons tuint Ctypes.Tnil) tvoid cc_default))\n                     ((Etempvar e_node tuint) :: nil))\n                   (Scall None\n                     (Evar set_tail (Tfunction (Ctypes.Tcons tuint Ctypes.Tnil) tvoid cc_default))\n                     ((Etempvar e_node tuint) :: nil)))))\n             (Ssequence\n               (Scall None\n                 (Evar set_next (Tfunction (Ctypes.Tcons tuint (Ctypes.Tcons tuint Ctypes.Tnil)) tvoid\n                                   cc_default))\n                 ((Etempvar e_tail tuint) :: (Etempvar e_node tuint) :: nil))\n               (Ssequence\n                 (Scall None\n                   (Evar set_prev (Tfunction (Ctypes.Tcons tuint (Ctypes.Tcons tuint Ctypes.Tnil)) tvoid\n                                     cc_default))\n                   ((Etempvar e_node tuint) :: (Etempvar e_tail tuint) :: nil))\n                 (Ssequence\n                   (Scall None\n                     (Evar set_next (Tfunction (Ctypes.Tcons tuint (Ctypes.Tcons tuint Ctypes.Tnil)) tvoid\n                                       cc_default))\n                     ((Etempvar e_node tuint) :: (Econst_int (Int.repr MAX_NODES) tint) ::\n                      nil))\n                   (Scall None\n                     (Evar set_tail (Tfunction (Ctypes.Tcons tuint Ctypes.Tnil) tvoid cc_default))\n                     ((Etempvar e_node tuint) :: nil))))))\n      |}.\n\n    Program Definition f_enqueue : function :=\n      inline f_enqueue' _.\n\n    Definition d_head : ident := 37%positive.\n    Definition d_next : ident := 38%positive.\n    Definition d_node : ident := 39%positive.\n\n    Definition f_dequeue' :=\n      {|\n        fn_return := tuint;\n        fn_callconv := cc_default;\n        fn_params := nil;\n        fn_vars := nil;\n        fn_temps := (d_head, tuint) :: (d_next, tuint) :: (d_node, tuint) :: nil;\n        fn_body :=\n          Ssequence\n           (Sset d_node (Econst_int (Int.repr MAX_NODES) tint))\n           (Ssequence\n             (Scall (Some d_head)\n               (Evar get_head (Tfunction Ctypes.Tnil tuint cc_default)) nil)\n             (Ssequence\n               (Sifthenelse (Ebinop One (Etempvar d_head tuint)\n                              (Econst_int (Int.repr MAX_NODES) tint) tint)\n                 (Ssequence\n                   (Sset d_node (Etempvar d_head tuint))\n                   (Ssequence\n                     (Scall (Some d_next)\n                       (Evar get_next (Tfunction (Ctypes.Tcons tuint Ctypes.Tnil) tuint\n                                         cc_default))\n                       ((Etempvar d_head tuint) :: nil))\n                     (Ssequence\n                       (Sifthenelse (Ebinop Oeq (Etempvar d_next tuint)\n                                      (Econst_int (Int.repr MAX_NODES) tint) tint)\n                         (Ssequence\n                           (Scall None\n                             (Evar set_head (Tfunction (Ctypes.Tcons tuint Ctypes.Tnil) tvoid\n                                               cc_default))\n                             ((Econst_int (Int.repr MAX_NODES) tint) :: nil))\n                           (Scall None\n                             (Evar set_tail (Tfunction (Ctypes.Tcons tuint Ctypes.Tnil) tvoid\n                                               cc_default))\n                             ((Econst_int (Int.repr MAX_NODES) tint) :: nil)))\n                         (Ssequence\n                           (Scall None\n                             (Evar set_prev (Tfunction\n                                               (Ctypes.Tcons tuint (Ctypes.Tcons tuint Ctypes.Tnil)) tvoid\n                                               cc_default))\n                             ((Etempvar d_next tuint) ::\n                              (Econst_int (Int.repr MAX_NODES) tint) :: nil))\n                           (Scall None\n                             (Evar set_head (Tfunction (Ctypes.Tcons tuint Ctypes.Tnil) tvoid\n                                               cc_default))\n                             ((Etempvar d_next tuint) :: nil))))\n                       (Ssequence\n                         (Scall None\n                           (Evar set_next (Tfunction (Ctypes.Tcons tuint (Ctypes.Tcons tuint Ctypes.Tnil))\n                                             tvoid cc_default))\n                           ((Etempvar d_node tuint) ::\n                            (Econst_int (Int.repr MAX_NODES) tint) :: nil))\n                         (Scall None\n                           (Evar set_prev (Tfunction (Ctypes.Tcons tuint (Ctypes.Tcons tuint Ctypes.Tnil))\n                                             tvoid cc_default))\n                           ((Etempvar d_node tuint) ::\n                            (Econst_int (Int.repr MAX_NODES) tint) :: nil))))))\n                 Sskip)\n               (Sreturn (Some (Etempvar d_node tuint)))))\n      |}.\n\n    Program Definition f_dequeue : function :=\n      inline f_dequeue' _.\n\n  End Code.\n\n  (** ** Low Level Specifications *)\n  Section LowSpec.\n\n    Definition enqueue_csig :=\n      mkcsig (type_of_list_type (tuint :: nil)) tvoid.\n\n    Inductive enqueue_step :\n      csignature -> list val * mwd intro_layerdata -> val * mwd intro_layerdata -> Prop :=\n    | enqueue_step_intro m d nd d':\n        enqueue_high_spec (Int.unsigned nd) d = Some d' ->\n        enqueue_step enqueue_csig\n                     (Vint nd :: nil, (m, d))\n                     (Vundef, (m, d')).\n\n    Definition dequeue_csig :=\n      mkcsig (type_of_list_type nil) tuint.\n\n    Inductive dequeue_step :\n      csignature -> list val * mwd intro_layerdata -> val * mwd intro_layerdata -> Prop :=\n    | dequeue_step_intro m d nd d':\n        dequeue_high_spec d = Some (d', Int.unsigned nd) ->\n        dequeue_step dequeue_csig\n                     (nil, (m, d))\n                     (Vint nd, (m, d')).\n\n    Program Definition enqueue_cprim : cprimitive intro_layerdata :=\n      mkcprimitive _ enqueue_step enqueue_csig _.\n    Next Obligation.\n      now inv H0.\n    Qed.\n\n    Program Definition dequeue_cprim : cprimitive intro_layerdata :=\n      mkcprimitive _ dequeue_step dequeue_csig _.\n    Next Obligation.\n      now inv H0.\n    Qed.\n\n    Global Instance enqueue_cprim_pres_inv : CPrimitivePreservesInvariant _ enqueue_cprim.\n    Proof.\n      constructor; intros.\n      - inv H0. unfold enqueue_high_spec in H4.\n        inv H1. inv cprimitive_inv_init_state_data_inv.\n        repeat destr_in H4; inv H4.\n        { (** tail = MAX_NODES *)\n          constructor; auto.\n          constructor; cbn; try congruence; intros.\n          - destr_eq node (Int.unsigned nd); subst.\n            + rewrite ZMap.gss. right. constructor; omega.\n            + rewrite ZMap.gso; auto.\n          - constructor; omega.\n        }\n        { (** tail <> MAX_NODES *)\n          constructor; auto.\n          specialize (q_valid0 eq_refl); inv q_valid0.\n          constructor; cbn; try congruence; intros.\n          - destr_eq node (Int.unsigned nd); subst.\n            + rewrite ZMap.gss.\n              right. constructor; omega.\n            + rewrite ZMap.gso; auto.\n              destr_eq node tail; subst.\n              * rewrite ZMap.gss.\n                apply npool_valid0 in H0.\n                destruct H0; try congruence.\n                inv H0. rewrite Heqn0 in H1; inv H1.\n                right. constructor; try omega.\n              * rewrite ZMap.gso; auto.\n          - constructor; omega.\n        }\n      - inv H0; reflexivity.\n    Qed.\n\n    Global Instance dequeue_cprim_pres_inv : CPrimitivePreservesInvariant _ dequeue_cprim.\n    Proof.\n      Opaque Z.mul.\n      pose proof MAX_NODES_range as Hmn_range.\n      constructor; intros.\n      - inv H0. unfold dequeue_high_spec in H4.\n        inv H1. inv cprimitive_inv_init_state_data_inv.\n        repeat destr_in H4; inv H4.\n        { (** next = MAX_NODES *)\n          constructor; auto.\n          constructor; cbn; try congruence; intros.\n          - destr_eq node (Int.unsigned nd); subst.\n            + rewrite ZMap.gss. right. constructor; omega.\n            + rewrite ZMap.gso; auto.\n          - constructor; omega.\n        }\n        { (** next <> MAX_NODES *)\n          constructor; auto.\n          specialize (q_valid0 eq_refl); inv q_valid0.\n          constructor; cbn; try congruence; intros.\n          - destr_eq node (Int.unsigned nd); subst.\n            + rewrite ZMap.gss.\n              right. constructor; omega.\n            + rewrite ZMap.gso; auto.\n              destr_eq node next; subst.\n              * rewrite ZMap.gss.\n                apply npool_valid0 in H0.\n                destruct H0; try congruence.\n                inv H0. rewrite Heqn1 in H1; inv H1.\n                right. constructor; try omega.\n              * rewrite ZMap.gso; auto.\n          - assert (0 <= Int.unsigned nd < MAX_NODES) by omega.\n            apply npool_valid0 in H1.\n            destruct H1; try congruence.\n            inv H1. rewrite Heqn0 in H4; inv H4.\n            constructor; omega.\n        }\n      - inv H0; reflexivity.\n      Qed.\n\n  End LowSpec.\n\n  (** ** Code Proofs *)\n  Section CodeLowSpecSim.\n\n    Context `{ce: ClightCompositeEnv}.\n\n    (** We can automatically solve the additional goal introduced by\n      [code_proof_tac] by using a hint. *)\n    Hint Resolve intro_pres_inv : linking.\n\n    Lemma enqueue_code :\n      intro_L ⊢ (inv, enqueue ↦ f_enqueue) : (enqueue ↦ enqueue_cprim).\n    Proof.\n      Opaque Z.mul.\n      code_proof_tac.\n      find_prim get_tail.\n      find_prim set_next.\n      find_prim set_prev.\n      find_prim set_head.\n      find_prim set_tail.\n      inv Hmatch; inv CStep.\n      destruct cprimitive_inv_init_state_data_inv.\n      unfold enqueue_high_spec in H2.\n      do 4 (destr_in H2; try discriminate).\n      rename Heqb into Hinit;\n      rename Heqq into Hqueue;\n      rename Heqn into Hnode;\n      rename Heqs into Hnode_range.\n      cprim_step.\n      pose proof MAX_NODES_range as Hmn_range.\n      repeat (destr_in H2; inv H2).\n      { (** tail = MAX_NODES *)\n        repeat step_tac.\n        - unfold get_tail_high_spec.\n          rewrite Hinit, Hqueue.\n          rewrite Int.unsigned_repr; [reflexivity | cbn; omega].\n        - reflexivity.\n        - repeat step_tac.\n          + unfold set_next_high_spec.\n            rewrite Hnode_range, Hnode.\n            rewrite Int.unsigned_repr; try (cbn; omega). destr; try omega.\n            reflexivity.\n          + unfold set_prev_high_spec; cbn.\n            rewrite Hnode_range.\n            rewrite Int.unsigned_repr; try (cbn; omega). destr; try omega.\n            rewrite ZMap.gss.\n            reflexivity.\n          + unfold set_head_high_spec; cbn.\n            rewrite Hinit, Hqueue.\n            destr; try omega.\n            reflexivity.\n          + unfold set_tail_high_spec; cbn.\n            rewrite Hinit.\n            destr; try omega.\n            unfold update_queue, update_npool; cbn.\n            rewrite ZMap.set2.\n            reflexivity.\n      }\n      { (** tail <> MAX_NODES *)\n        (** Need invariant to prove *)\n        assert (Htail_range: 0 <= tail <= MAX_NODES).\n        { specialize (q_valid0 eq_refl); inv q_valid0; auto. }\n        destr_in H1; inv H1.\n        rename Heqn0 into Htail.\n        repeat step_tac.\n        - unfold get_tail_high_spec.\n          rewrite Hinit, Hqueue.\n          rewrite Int.unsigned_repr; [reflexivity | cbn; omega].\n        - rewrite Int.eq_false; [reflexivity |].\n          red; intros.\n          apply (f_equal Int.unsigned) in H0.\n          repeat (rewrite Int.unsigned_repr in H0; try (cbn; omega)).\n        - destr_eq tail (Int.unsigned nd); [subst |].\n          + repeat step_tac.\n            * unfold set_next_high_spec.\n              rewrite Int.unsigned_repr; try (cbn; omega).\n              rewrite Htail.\n              repeat destr; try omega.\n              reflexivity.\n            * unfold set_prev_high_spec; cbn.\n              rewrite Hnode_range.\n              rewrite Int.unsigned_repr; try (cbn; omega). destr; try omega.\n              subst; rewrite ZMap.gss. reflexivity.\n            * unfold set_next_high_spec.\n              rewrite Int.unsigned_repr; try (cbn; omega).\n              rewrite Hnode_range.\n              destr; try omega.\n              rewrite ZMap.gss. reflexivity.\n            * unfold set_tail_high_spec; cbn.\n              rewrite Hinit, Hqueue.\n              destr; try omega.\n              unfold update_npool, update_queue; cbn.\n              repeat rewrite ZMap.set2.\n              congruence.\n          + repeat step_tac.\n            * unfold set_next_high_spec.\n              rewrite Int.unsigned_repr; try (cbn; omega).\n              rewrite Htail.\n              repeat destr; try omega.\n              reflexivity.\n            * unfold set_prev_high_spec; cbn.\n              rewrite Hnode_range.\n              rewrite Int.unsigned_repr; try (cbn; omega). destr; try omega.\n              subst; rewrite ZMap.gso; auto. rewrite Hnode.\n              reflexivity.\n            * unfold set_next_high_spec.\n              rewrite Int.unsigned_repr; try (cbn; omega).\n              rewrite Hnode_range.\n              destr; try omega.\n              rewrite ZMap.gss. reflexivity.\n            * unfold set_tail_high_spec; cbn.\n              rewrite Hinit, Hqueue.\n              destr; try omega.\n              unfold update_npool, update_queue; cbn.\n              repeat rewrite ZMap.set2.\n              congruence.\n      }\n    Qed.\n\n    Lemma dequeue_code :\n      intro_L ⊢ (inv, dequeue ↦ f_dequeue) : (dequeue ↦ dequeue_cprim).\n    Proof.\n      Opaque Z.mul.\n      code_proof_tac.\n      find_prim get_head.\n      find_prim get_next.\n      find_prim set_next.\n      find_prim set_prev.\n      find_prim set_head.\n      find_prim set_tail.\n      inv Hmatch; inv CStep.\n      destruct cprimitive_inv_init_state_data_inv.\n      unfold dequeue_high_spec in H2.\n      do 4 (destr_in H2; try discriminate).\n      rename Heqb into Hinit;\n      rename Heqq into Hqueue;\n      rename Heqn0 into Hnode.\n      cprim_step.\n      pose proof MAX_NODES_range as Hmn_range.\n      (** Need invariant to prove *)\n      assert (Hhead_range: 0 <= head < MAX_NODES).\n      { cut (0 <= head <= MAX_NODES /\\ head <> MAX_NODES);\n        [omega | split]; auto.\n        specialize (q_valid0 eq_refl); inv q_valid0; auto.\n      }\n      repeat (destr_in H2; inv H2).\n      { (** next = MAX_NODES *)\n        repeat step_tac.\n        - unfold get_head_high_spec.\n          rewrite Hinit, Hqueue.\n          reflexivity.\n        - rewrite Int.eq_false; [reflexivity |].\n          red; intros Heq.\n          pose proof n as Hneq; rewrite Heq in Hneq.\n          rewrite Int.unsigned_repr in Hneq; [contradiction | cbn; omega].\n        - repeat step_tac.\n          + unfold get_next_high_spec.\n            rewrite Hnode.\n            destruct (decide (_ <= _ < _)); try omega.\n            rewrite Int.unsigned_repr; [reflexivity | cbn; omega].\n          + reflexivity.\n          + repeat step_tac.\n            * unfold set_head_high_spec.\n              rewrite Hinit, Hqueue.\n              rewrite Int.unsigned_repr; try (cbn; omega).\n              destr; try omega.\n              reflexivity.\n            * unfold set_tail_high_spec; cbn.\n              rewrite Hinit.\n              rewrite Int.unsigned_repr; try (cbn; omega).\n              destr; try omega.\n              reflexivity.\n            * unfold set_next_high_spec; cbn.\n              rewrite Hnode.\n              rewrite Int.unsigned_repr; try (cbn; omega).\n              destr; try omega. destr; try omega.\n              reflexivity.\n            * unfold set_prev_high_spec; cbn.\n              rewrite ZMap.gss.\n              rewrite Int.unsigned_repr; try (cbn; omega).\n              destr; try omega. destr; try omega.\n              unfold update_queue, update_npool; cbn.\n              rewrite ZMap.set2.\n              reflexivity.\n      }\n      { (** next <> MAX_NODES *)\n        (** Need invariant to prove *)\n        assert (Hnext_range: 0 <= next <= MAX_NODES).\n        { apply npool_valid0 in Hhead_range. rewrite Hnode in Hhead_range.\n          destruct Hhead_range as [Hvalid | Hvalid]; inv Hvalid; auto.\n        }\n        destr_in H1; inv H1.\n        rename Heqn1 into Hnext.\n        repeat step_tac.\n        - unfold get_head_high_spec.\n          rewrite Hinit, Hqueue.\n          rewrite Int.unsigned_repr; [reflexivity | cbn; omega].\n        - rewrite Int.eq_false; [reflexivity |].\n          red; intros Heq.\n          apply (f_equal Int.unsigned) in Heq.\n          repeat (rewrite Int.unsigned_repr in Heq; try (cbn; omega)).\n        - repeat step_tac.\n          + unfold get_next_high_spec.\n            rewrite Int.unsigned_repr; try (cbn; omega).\n            rewrite Hnode.\n            destruct (decide (_ <= _ < _)); try omega.\n            rewrite Int.unsigned_repr; [reflexivity | cbn; omega].\n          + rewrite Int.eq_false; [reflexivity |].\n            red; intros Heq.\n            apply (f_equal Int.unsigned) in Heq.\n            repeat (rewrite Int.unsigned_repr in Heq; try (cbn; omega)).\n          + destr_eq next (Int.unsigned nd); [subst |].\n            * repeat step_tac.\n              -- unfold set_prev_high_spec.\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 rewrite Hnext.\n                 destr; try omega. destr; try omega.\n                 reflexivity.\n              -- unfold set_head_high_spec; cbn.\n                 rewrite Hinit, Hqueue.\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 destr; try omega.\n                 reflexivity.\n              -- unfold set_next_high_spec; cbn.\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 destr; try omega. destr; try omega.\n                 rewrite ZMap.gss. reflexivity.\n              -- unfold set_prev_high_spec; cbn.\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 destr; try omega. destr; try omega.\n                 rewrite ZMap.gss. reflexivity.\n              -- unfold update_queue, update_npool; cbn.\n                 repeat rewrite ZMap.set2.\n                 rewrite Hnext in Hnode. inv Hnode.\n                 rewrite Int.repr_unsigned.\n                 step_tac.\n            * repeat step_tac.\n              -- unfold set_prev_high_spec.\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 rewrite Hnext.\n                 destr; try omega. destr; try omega.\n                 reflexivity.\n              -- unfold set_head_high_spec; cbn.\n                 rewrite Hinit, Hqueue.\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 destr; try omega.\n                 reflexivity.\n              -- unfold set_next_high_spec; cbn.\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 destr; try omega. destr; try omega.\n                 rewrite ZMap.gso; auto. rewrite Hnode.\n                 reflexivity.\n              -- unfold set_prev_high_spec; cbn.\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 rewrite Int.unsigned_repr; try (cbn; omega).\n                 destr; try omega. destr; try omega.\n                 rewrite ZMap.gss. reflexivity.\n              -- unfold update_queue, update_npool; cbn.\n                 repeat rewrite ZMap.set2.\n                 rewrite Int.repr_unsigned.\n                 step_tac.\n      }\n    Qed.\n\n  End CodeLowSpecSim.\n\n  (** ** Layer Relation *)\n  Section LowHighSpecRel.\n\n    Inductive match_data : queue_layerdata -> mem -> Prop :=\n    | match_data_intro: forall m abs,\n        match_data abs m.\n\n    Record relate_data (hadt: queue_layerdata) (ladt: intro_layerdata) := {\n      init_rel: init_flag hadt = init_flag ladt;\n      npool_rel: npool hadt = npool ladt;\n      queue_rel: queue hadt = queue ladt\n    }.\n\n    Definition abrel_components_queue_intro :\n      abrel_components queue_layerdata intro_layerdata :=\n      {|\n        abrel_relate := relate_data;\n        abrel_match  := match_data;\n        abrel_new_glbl := nil\n      |}.\n\n    Global Instance rel_ops :\n      AbstractionRelation _ _ abrel_components_queue_intro.\n    Proof. repeat constructor. Qed.\n\n    Definition abrel_queue_intro : abrel queue_layerdata intro_layerdata :=\n      {|\n        abrel_ops := abrel_components_queue_intro;\n        abrel_prf := rel_ops\n      |}.\n\n    Definition queue_R : simrel _ _ := abrel_simrel _ _ abrel_queue_intro.\n\n  End LowHighSpecRel.\n\n  (** ** Refinement Proofs *)\n  Section LowHighSpecSim.\n\n    Context `{ce: ClightCompositeEnv}.\n\n    Lemma enqueue_refine :\n      (enqueue ↦ enqueue_cprim) ⊢ (queue_R, ∅) : (enqueue ↦ enqueue_high_sem).\n    Proof.\n      refine_proof_tac.\n      inv CStep. inv_generic_sem H8.\n      inverse_hyps.\n      inversion MemRel.\n      inv abrel_match_mem_match.\n      inv abrel_match_mem_relate.\n      unfold enqueue_high_spec in H1.\n      repeat destr_in H1; inv H1;\n      rename Heqn into Hnode.\n      { (** tail = MAX_NODES *)\n        do 3 eexists; split.\n        - econstructor. unfold enqueue_high_spec.\n          rewrite <- init_rel0, <- queue_rel0, <- npool_rel0, Hnode.\n          destr; try omega. destr; try omega.\n          reflexivity.\n        - repeat (constructor; auto).\n          cbn; congruence.\n      }\n      { (** tail <> MAX_NODES *)\n        rename Heqn0 into Htail.\n        do 3 eexists; split.\n        - econstructor. unfold enqueue_high_spec.\n          rewrite <- init_rel0, <- queue_rel0, <- npool_rel0, Hnode, Htail.\n          destr; try omega. destr; try omega.\n          reflexivity.\n        - repeat (constructor; auto).\n          cbn; congruence.\n      }\n    Qed.\n\n    Lemma dequeue_refine :\n      (dequeue ↦ dequeue_cprim) ⊢ (queue_R, ∅) : (dequeue ↦ dequeue_high_sem).\n    Proof.\n      refine_proof_tac.\n      inv CStep. inv_generic_sem H8.\n      inverse_hyps.\n      inversion MemRel.\n      inv abrel_match_mem_match.\n      inv abrel_match_mem_relate.\n      unfold dequeue_high_spec in H1.\n      repeat destr_in H1; inv H1;\n      rename Heqs into Hz_neq;\n      rename Heqn0 into Hnode.\n      { (** tail = MAX_NODES *)\n        do 3 eexists; split.\n        - econstructor. unfold dequeue_high_spec.\n          rewrite <- init_rel0, <- queue_rel0, <- npool_rel0, Hz_neq, Hnode.\n          destr; try omega.\n          reflexivity.\n        - repeat (constructor; auto).\n          cbn; congruence.\n      }\n      { (** tail <> MAX_NODES *)\n        rename Heqn1 into Hnext.\n        rename  Heqs0 into Hnext_neq.\n        do 3 eexists; split.\n        - econstructor. unfold dequeue_high_spec.\n          rewrite <- init_rel0, <- queue_rel0, <- npool_rel0, Hz_neq, Hnode,\n                  Hnext, Hnext_neq.\n          reflexivity.\n        - repeat (constructor; auto).\n          cbn; congruence.\n      }\n    Qed.\n\n  End LowHighSpecSim.\n\n  (** ** Linking *)\n  Section Linking.\n\n    Context `{ce: ClightCompositeEnv}.\n    Hypothesis Hce :\n      build_composite_env (node_t_comp :: queue_t_comp :: nil) = OK ce.\n\n    Definition queue_L : clayer queue_layerdata :=\n      enqueue ↦ enqueue_high_sem\n      ⊕ dequeue ↦ dequeue_high_sem.\n\n    Definition queue_Σ : clayer intro_layerdata :=\n      enqueue ↦ enqueue_cprim\n      ⊕ dequeue ↦ dequeue_cprim.\n\n    Definition queue_M : cmodule :=\n      enqueue ↦ f_enqueue\n      ⊕ dequeue ↦ f_dequeue.\n\n    Hint Resolve enqueue_code enqueue_refine\n                 dequeue_code dequeue_refine : linking.\n\n    (** [link_tac] still works even though [queue_L] is built on top of a\n      composition of layers. *)\n    Theorem queue_link :\n      intro_L ⊢ (inv ∘ queue_R ∘ inv, queue_M) : queue_L.\n    Proof. link_tac queue_Σ. Qed.\n\n    Lemma queue_pres_inv :\n      ForallPrimitive _ (CPrimitivePreservesInvariant _) queue_L.\n    Proof. unfold queue_L. typeclasses eauto. Qed.\n\n    Hint Resolve node_link queue_intro_link queue_link : linking.\n\n    Theorem queue_boot_link :\n      boot_L ⊢ (intro_R ∘ inv ∘ queue_R ∘ inv, intro_M ⊕ queue_M) : queue_L.\n    Proof.\n      apply (vdash_rel_equiv _ _ (intro_R ∘ (inv ∘ queue_R ∘ inv))).\n      rewrite cat_compose_assoc; rewrite cat_compose_assoc; reflexivity.\n      eapply vcomp_rule; eauto with linking.\n      unfold intro_M, intro_L.\n      apply hcomp_rule; auto with linking.\n    Qed.\n\n  End Linking.\n\nEnd Queue.\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/CAL/tutorial/queue/Queue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.234850525268132}}
{"text": "From melocoton.language Require Export weakestpre lifting.\nFrom melocoton.c_lang Require Export lang.\nFrom melocoton.c_lang Require Import tactics notation.\nFrom iris.prelude Require Import options.\n\nSection pure_exec.\n  Variable (p:language.prog C_lang).\n  Local Ltac solve_exec_safe := intros; subst; do 2 eexists; try (repeat (econstructor; eauto); done).\n  Local Ltac solve_exec_puredet := simpl; intros; inv_head_step; try done.\n  Local Ltac solve_pure_exec :=\n    subst; intros ?; apply nsteps_once, pure_head_step_pure_step;\n      constructor; [solve_exec_safe | solve_exec_puredet].\n\n  Local Ltac destruct_bool_decide := repeat (let H := fresh \"Heq\" in \n    try destruct bool_decide eqn:H; \n    [apply bool_decide_eq_true_1 in H| apply bool_decide_eq_false_1 in H]).\n\n  Global Instance pure_unop op v v' :\n    PureExec (un_op_eval op v = Some v') 1 p (UnOp op (Val v)) (Val v').\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_binop op v1 v2 v' :\n    PureExec (bin_op_eval op v1 v2 = Some v') 1 p (BinOp op (Val v1) (Val v2)) (Val (LitV v')) | 10.\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_if_true v e1 e2 : asTruth v = true ->\n    PureExec True 1 p (If (Val $ v) e1 e2) e1.\n  Proof. intros H. solve_pure_exec. congruence. Qed.\n  Global Instance pure_if_non_zero (v0:Z) e1 e2 : v0 ≠ 0%Z ->\n    PureExec True 1 p (If (Val $ LitV $ LitInt v0) e1 e2) e1.\n  Proof. intros H. apply pure_if_true. destruct v0; cbn; congruence. Qed.\n  Global Instance pure_if_true_bool e1 e2 :\n    PureExec True 1 p (If (Val $ LitV $ LitBool true) e1 e2) e1.\n  Proof. apply pure_if_true. easy. Qed.\n  Global Instance pure_if_false v e1 e2 : asTruth v = false ->\n    PureExec True 1 p (If (Val $ v) e1 e2) e2.\n  Proof. intros H. solve_pure_exec. congruence. Qed.\n  Global Instance pure_if_zero e1 e2 : \n    PureExec True 1 p (If (Val $ LitV $ LitInt (0%Z)) e1 e2) e2.\n  Proof. apply pure_if_false. easy. Qed.\n  Global Instance pure_if_false_bool e1 e2 :\n    PureExec True 1 p (If (Val $ LitV $ LitBool false) e1 e2) e2.\n  Proof. apply pure_if_zero. Qed.\n\n  Global Instance pure_while e1 e2 : \n    PureExec True 1 p (While e1 e2) (If e1 (Let BAnon e1 (While e1 e2)) (Val $ LitV $ LitInt 0)).\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_let x (v1:val) e2 : \n    PureExec True 1 p (Let x v1 e2) (subst' x v1 e2).\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_funcall s va args res e : \n    PureExec ((p : gmap.gmap string function) !! s = Some (Fun args e) ∧ zip_args args va = Some res) 1 p (FunCall (Val $ LitV $ LitFunPtr s) (map Val va)) (subst_all res e).\n  Proof. solve_pure_exec; destruct H as [H1 H2].\n    1: econstructor; first done.\n    + unfold apply_function. rewrite H2. reflexivity.\n    + repeat split; try congruence. destruct (zip_args args0 va) eqn:Heq; last congruence.\n      congruence.\n  Qed.\nEnd pure_exec.\n", "meta": {"author": "logsem", "repo": "melocoton", "sha": "b77eecc3381f53db0eb3c4cf1314e881a8dc41b3", "save_path": "github-repos/coq/logsem-melocoton", "path": "github-repos/coq/logsem-melocoton/melocoton-b77eecc3381f53db0eb3c4cf1314e881a8dc41b3/theories/c_lang/class_instances.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23484043695244028}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool eqtype seq.\nRequire Import Init_ext ZArith_ext uniq_tac machine_int multi_int encode_decode integral_type.\nImport MachineInt.\nRequire Import mips_bipl mips_seplog mips_tactics mips_syntax mips_mint.\nImport mips_bipl.expr_m.\nRequire Import simu.\nImport simu.simu_m.\nRequire Import multi_zero_u_prg multi_zero_u_triple multi_zero_u_termination.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope assoc_scope.\nLocal Open Scope uniq_scope.\n\nLemma multi_zero_u_safe_termination a0 a1 rx x rk d : uniq(rk, rx, a0, a1, r0) ->\n  safe_termination\n  (state_mint (x |=> unsign rk rx \\U+ d)) (multi_zero_u rk rx a0 a1).\nProof.\nmove=> Hset.\nrewrite /safe_termination => st s h st_s_h.\nset code := multi_zero_u _ _ _ _.\nmove: (multi_zero_u_termination s h _ _ _ _ Hset) => [x0 Htermi].\nhave H1 : (u2Z ([ rx ]_ s) + 4 * Z_of_nat (Z.abs_nat (u2Z ([rk ]_ s))) < Zbeta 1)%asm_expr.\n  apply state_mint_head_unsign_fit with x d st h.\n  by apply st_s_h.\nhave H2 : (size (Z2ints 32 (Z.abs_nat (u2Z ([ rk ]_ s))) ([ x ]_st)%pseudo_expr) =\n  Z.abs_nat (u2Z ([rk ]_ s)))%asm_expr.\n  by rewrite size_Z2ints.\nmove: (multi_zero_u_triple _ _ _ _ Hset _ _ _ H2 H1) => triple_hoare.\napply constructive_indefinite_description'.\napply (mips_syntax.triple_exec_precond _ _ _ triple_hoare _ _ _ Htermi (List.seq\n      (Z.abs_nat (u2Z ([rx ]_ s) / 4)) (Z.abs_nat (u2Z ([rk ]_ s))))%asm_expr).\nsplit; first done.\nsplit.\n- rewrite Z_of_nat_Zabs_nat //; by apply min_u2Z.\n- apply (state_mint_var_mint _ _ _ _ x (unsign rk rx)) in st_s_h; last by assoc_get_Some.\n  by apply st_s_h.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/begcd/multi_zero_u_safe_termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23484043695244028}}
{"text": "From iris.algebra Require Import auth agree excl csum.\nFrom Perennial.base_logic Require Import ae_invariants.\nFrom iris.bi Require Export weakestpre.\nFrom iris.proofmode Require Import base tactics classes.\nFrom Perennial.base_logic Require Export invariants fancy_updates2.\nFrom Perennial.program_logic Require Import step_fupd_extra ae_invariants_mutable.\nFrom Perennial.algebra Require Export own_discrete.\nFrom Perennial.base_logic.lib Require Export ncfupd.\nFrom iris.prelude Require Import options.\nImport uPred.\n\n(* first, define a modality for establishing crash conditions *)\nSection cfupd.\n  Context `{crashGS Σ} `{invGS Σ}.\n  Implicit Types (P: iProp Σ).\n\n  Definition cfupd E1 :=\n    λ P, (C -∗ |={E1}=> P)%I.\n\n  Lemma cfupd_wand  (E1 E1' : coPset) P Q:\n    E1' ⊆ E1 →\n    cfupd E1' P -∗\n    (P -∗ Q) -∗\n    cfupd E1 Q.\n  Proof.\n    iIntros (?) \"HP HPQ\".\n    iIntros \"HC\". iSpecialize (\"HP\" with \"[$]\").\n    iMod (fupd_mask_mono with \"HP\") as \"HP\"; auto.\n    iModIntro. by iApply \"HPQ\".\n  Qed.\n\n  Global Instance cfupd_proper_ent E1 :\n    Proper ((⊢) ==> (⊢)) (cfupd E1).\n  Proof.\n    iIntros (P Q Hent) \"Hfupd\".\n    iApply (cfupd_wand with \"Hfupd\"); eauto.\n    iApply Hent.\n  Qed.\n\n  Global Instance cfupd_proper_equiv E1 :\n    Proper ((⊣⊢) ==> (⊣⊢)) (cfupd E1).\n  Proof.\n    intros P Q Hequiv.\n    iSplit; iIntros \"H\".\n    - iApply (cfupd_wand with \"H\"); eauto.\n      rewrite Hequiv; auto.\n    - iApply (cfupd_wand with \"H\"); eauto.\n      rewrite Hequiv; auto.\n  Qed.\n\n  Global Instance from_modal_fupd_iter k E P :\n    FromModal True modality_id\n              (Nat.iter k (fupd E E) P)\n              (Nat.iter k (fupd E E) P) P.\n  Proof.\n    rewrite /FromModal /=.\n    iIntros (_) \"HP\".\n    iInduction k as [|k] \"IH\".\n    - simpl; auto.\n    - simpl.\n      iModIntro.\n      iApply \"IH\"; iFrame.\n  Qed.\n\n  Theorem step_fupd_iter_intro k E1 E2 P :\n    E2 ⊆ E1 →\n    ▷^k P -∗ (Nat.iter k (fun P : iProp Σ =>\n                        fupd E1 E2 (▷ (fupd E2 E1 P))) P).\n  Proof.\n    iIntros (?) \"HP\".\n    iInduction k as [|k] \"IH\".\n    - simpl; auto.\n    - simpl.\n      iMod (fupd_mask_subseteq E2) as \"Hclo\"; auto.\n      iModIntro.\n      iModIntro.\n      iMod \"Hclo\" as \"_\".\n      iModIntro.\n      iApply (\"IH\" with \"HP\").\n  Qed.\n\n  Lemma fupd_iter_intro E1 k P :\n    ▷^k P -∗ |={E1,E1}_(k)=> P.\n  Proof.\n    iIntros \"HP\".\n    iMod (fupd_mask_subseteq ∅) as \"Hclo\"; first by set_solver.\n    iModIntro.\n    iApply step_fupd_iter_intro; first by set_solver.\n    iModIntro.\n    iMod \"Hclo\" as \"_\".\n    by iFrame.\n  Qed.\n\n  Lemma step_fupd_mask_weaken_iter k E1 E2 P :\n    E1 ⊆ E2 →\n    ▷^k P -∗ |={E2,E1}_k=> P.\n  Proof.\n    iIntros (?) \"HP\".\n    iApply step_fupd_iter_intro; first by set_solver.\n    iMod (fupd_mask_subseteq ∅) as \"Hclo\"; first by set_solver.\n    iModIntro. iModIntro.\n    iMod \"Hclo\" as \"_\".\n    iApply fupd_mask_intro_discard; auto.\n  Qed.\n\n  Global Instance from_modal_cfupd E1 P :\n    FromModal True modality_id (cfupd E1 P) (cfupd E1 P) (P).\n  Proof.\n    rewrite /FromModal /=.\n    iIntros (_) \"HP\".\n    iIntros \"_\".\n    iModIntro. by iFrame.\n  Qed.\n\n  Lemma ineq_to_diff n1 n2 :\n    (n1 ≤ n2)%nat →\n    ∃ n1' d,\n      (n2 - n1 = d) ∧\n      n1 = n1' ∧\n      n2 = n1' + d.\n  Proof.\n    intros.\n    exists n1, (n2-n1); lia.\n  Qed.\n\n  Theorem elim_modal_step_fupdN_subtract E1 E2 k1 k2 P Q :\n    (k1 ≤ k2)%nat →\n    (|={E1}[E2]▷=>^k1 P) -∗\n    (P -∗ |={E1}[E2]▷=>^(k2-k1) Q) -∗\n    |={E1}[E2]▷=>^k2 Q.\n  Proof.\n    iIntros (Hle) \"HP HQ\".\n    destruct (ineq_to_diff _ _ Hle) as (k&kd&->&?&?); subst.\n    clear Hle.\n    iInduction k as [|k] \"IH\"; simpl.\n    - iApply \"HQ\"; auto.\n    - iMod \"HP\"; iModIntro. iNext.\n      iMod \"HP\"; iModIntro.\n      iApply (\"IH\" with \"HP HQ\").\n  Qed.\n\n  Theorem elim_modal_step_fupdN_mono E1 E2 k P Q :\n    (|={E1}[E2]▷=>^k P) -∗\n    (P -∗ Q) -∗\n    |={E1}[E2]▷=>^k Q.\n  Proof.\n    iIntros \"HP HQ\".\n    iApply (elim_modal_step_fupdN_subtract with \"HP\"); auto.\n    replace (k-k) with 0 by lia; simpl.\n    auto.\n  Qed.\n\n  Theorem elim_modal_step_fupd_masks k1 k2 E1 E2 P Q :\n    (k1 ≤ k2)%nat →\n    E1 ⊆ E2 →\n    (|={E1,E2}_k1=> P) -∗\n    (P -∗ (|={E1,E2}_(k2-k1)=> Q)) -∗\n    (|={E1,E2}_k2=> Q).\n  Proof.\n    iIntros (Hle ?) \"Hfupd HQ\".\n    (* rearrange theorem to an addition rather than a subtraction *)\n    destruct (ineq_to_diff _ _ Hle) as (k&kd&->&?&?); subst; clear Hle.\n    iApply step_fupdN_inner_add.\n    iMod \"Hfupd\". iModIntro.\n    iApply (elim_modal_step_fupdN_mono with \"Hfupd\").\n    iIntros \"HP\".\n    iMod \"HP\".\n    iSpecialize (\"HQ\" with \"HP\").\n    iApply fupd_mask_intro_discard; auto.\n  Qed.\n\n  Lemma step_fupdN_fupd E1 E2 k P :\n    E1 ⊆ E2 →\n    (|={E1}▷=>^k |={E1,E2}=> P) ⊣⊢ (|={E1}=> |={E1}▷=>^k |={E1,E2}=> P).\n  Proof.\n    intros Hsub.\n    destruct k; simpl.\n    - iSplit; iIntros \"H\".\n      + iMod \"H\".\n        iApply fupd_mask_intro_subseteq; auto.\n      + iMod \"H\"; auto.\n    - iSplit; iIntros \"H\".\n      + by iFrame.\n      + by iMod \"H\".\n  Qed.\n\n  Lemma step_fupdN_fupd_empty E2 k P :\n    (|={∅}▷=>^k |={∅,E2}=> P) ⊣⊢ (|={∅}=> |={∅}▷=>^k |={∅,E2}=> P).\n  Proof.\n    apply step_fupdN_fupd; set_solver.\n  Qed.\n\n  Theorem elim_modal_step_fupd_masks_trans k1 k2 E1 E2 E3 P Q :\n    (k1 ≤ k2)%nat →\n    (|={E1,E2}_k1=> P) -∗\n    (P -∗ (|={E2,E3}_(k2-k1)=> Q)) -∗\n    (|={E1,E3}_k2=> Q).\n  Proof.\n    iIntros (Hle) \"Hfupd HQ\".\n    (* rearrange theorem to an addition rather than a subtraction *)\n    destruct (ineq_to_diff _ _ Hle) as (k&kd&->&?&?); subst; clear Hle.\n    iApply (elim_modal_step_fupdN_subtract with \"Hfupd\"); first lia.\n    iIntros \"HP\".\n    iEval (rewrite step_fupdN_fupd_empty).\n    iMod \"HP\".\n    iMod (\"HQ\" with \"HP\") as \"HQ\".\n    iModIntro.\n    iApply (elim_modal_step_fupdN_subtract with \"HQ\"); first lia.\n    iIntros \"HQ\".\n    iApply step_fupd_iter_intro; auto.\n  Qed.\n\n  Lemma step_fupdN_weaken_mask E1 E1' k P :\n    E1' ⊆ E1 →\n    (|={E1',E1'}_k=> P) -∗\n    |={E1,E1}_k=> P.\n  Proof.\n    iIntros (?) \"HP\".\n    iMod (fupd_mask_subseteq E1') as \"Hclo\"; first auto.\n    iApply (elim_modal_step_fupdN_mono with \"HP\").\n    iIntros \"HP\".\n    iMod \"HP\".\n    iMod \"Hclo\" as \"_\".\n    auto.\n  Qed.\n\n  Theorem cfupd_weaken_mask E1 E1' P :\n    E1' ⊆ E1 →\n    cfupd  E1'  P -∗ cfupd E1 P.\n  Proof.\n    iIntros (?) \"H\".\n    iApply (cfupd_wand with \"[$]\"); eauto.\n  Qed.\n\n  (* these instances are local to avoid breaking the proofs in this file *)\n\n  Local Instance elim_modal_step_fupd p k1 k2 E P Q :\n    ElimModal (k1 ≤ k2)%nat p false (|={E,E}_k1=> P) P\n              (|={E,E}_k2=> Q) (|={E,E}_(k2-k1)=> Q).\n  Proof.\n    rewrite /ElimModal intuitionistically_if_elim /=.\n    iIntros (?) \"[Hfupd HQ]\".\n    iApply (elim_modal_step_fupd_masks with \"Hfupd\"); auto.\n  Qed.\n\n  Local Instance elim_modal_step_fupd_same p k E P Q :\n    ElimModal True p false (|={E,E}_k=> P) P\n              (|={E,E}_k=> Q) (|={E}=> Q).\n  Proof.\n    rewrite /ElimModal intuitionistically_if_elim.\n    iIntros (?) \"[Hfupd HQ]\".\n    iMod \"Hfupd\" as \"HP\".\n    replace (k-k) with 0 by lia.\n    simpl.\n    iSpecialize (\"HQ\" with \"HP\").\n    iMod \"HQ\".\n    iApply fupd_mask_intro_subseteq; first set_solver; auto.\n  Qed.\n\n  Global Instance elim_modal_cfupd p E1 P Q :\n    ElimModal True p false (cfupd E1 P) (P)\n              (cfupd E1 Q) (cfupd E1 Q).\n  Proof.\n    rewrite /ElimModal intuitionistically_if_elim /cfupd /=.\n    iIntros (?) \"[Hfupd HQ]\".\n    iIntros \"#HC\".\n    iSpecialize (\"Hfupd\" with \"HC\").\n    iMod \"Hfupd\".\n    iMod (\"HQ\" with \"Hfupd HC\") as \"HQ\".\n    iModIntro. auto.\n  Qed.\n\n  Global Instance cfupd_frame p E1 R P Q :\n    Frame p R P Q →\n    Frame p R (cfupd E1 P) (cfupd E1 Q).\n  Proof.\n    rewrite /Frame.\n    iIntros (Hframe) \"[HR Hfupd]\".\n    iIntros \"HC\".\n    iSpecialize (\"Hfupd\" with \"HC\").\n    iMod \"Hfupd\". iModIntro. iApply Hframe; by iFrame.\n  Qed.\n\n  Lemma cfupd_big_sepL_aux {A} (l: list A) (Φ: nat → A → iProp Σ) n E1 :\n    ([∗ list] i↦a ∈ l, cfupd E1 (Φ (n + i) a)) -∗\n    cfupd E1 ([∗ list] i↦a ∈ l, Φ (n + i) a).\n  Proof.\n    iIntros \"H\".\n    iInduction l as [| x l] \"IH\" forall (n).\n    - iModIntro.\n      simpl; auto.\n    - rewrite -> !big_sepL_cons by set_solver.\n      simpl.\n      iDestruct \"H\" as \"(Hx & Hrest)\".\n      iMod \"Hx\".\n      iFrame \"Hx\".\n      assert (forall k, n + S k = S n + k) as Harith by lia.\n      setoid_rewrite Harith.\n      iMod (\"IH\" with \"Hrest\") as \"Hrest\".\n      iModIntro. eauto.\n  Qed.\n\n  Lemma cfupd_big_sepL {A} (l: list A) (Φ: nat → A → iProp Σ) E1 :\n    ([∗ list] i↦a ∈ l, cfupd E1 (Φ i a)) -∗\n    cfupd E1 ([∗ list] i↦a ∈ l, Φ i a).\n  Proof. iApply (cfupd_big_sepL_aux _ _ 0). Qed.\n\n  Lemma cfupd_big_sepS `{Countable A} (σ: gset A)(P: A → iProp Σ) E1  :\n    ([∗ set] a ∈ σ, cfupd E1 (P a)) -∗\n    cfupd E1 ([∗ set] a ∈ σ, P a).\n  Proof. rewrite big_op.big_opS_unseal. apply cfupd_big_sepL. Qed.\n\n  Lemma is_except_0_wand {PROP:bi} (P Q: PROP) :\n    IsExcept0 Q → IsExcept0 (P -∗ Q).\n  Proof.\n    rewrite /IsExcept0.\n    intros HQ.\n    rewrite -{2}HQ.\n    iIntros \">HQ HP !>\".\n    iApply (\"HQ\" with \"HP\").\n  Qed.\n\n  Global Instance cfupd_is_except0 E Q : IsExcept0 (cfupd E Q).\n  Proof.\n    rewrite /cfupd.\n    apply is_except_0_wand.\n    apply _.\n  Qed.\n\n  Global Instance from_pure_cfupd a E P φ :\n    FromPure a P φ → FromPure a (cfupd E P) φ.\n  Proof.\n    rewrite /FromPure=> HP. iIntros \"? !>\". by iApply HP.\n  Qed.\n\nEnd cfupd.\n\n(* Open to alternative notation for this. *)\nNotation \"|C={ E1 }=> P\" := (cfupd E1 P)\n      (at level 99, E1 at level 50, P at level 200,\n       format \"'[  ' |C={ E1 }=>  '/' P ']'\").\n\nGlobal Hint Extern 1 (environments.envs_entails _ (|C={_}=> _)) => iModIntro : core.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_logic/cfupd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23484043695244028}}
{"text": "Require Import Utf8 List Basics FinFun.\nImport ListNotations.\nRequire Import CpdtTactics.\nRequire Import LibLN.\nSet Implicit Arguments.\n\nImplicit Types EP EV LV V L : Set.\n\nNotation \"x ∈ E\" := (mem x E) (at level 39) : fset_scope.\nNotation \"x ∉ E\" := (notin x E) (at level 39) : fset_scope.\nNotation \"E ⊆ F\" := (subset E F) (at level 38) : fset_scope.\n\n(** * Syntax *)\n\n(**\nIf [V] is the type of the representation of a variable, then [inc V]\nis the type of the representation of the same variable after the free\nvariable environment is extended by one.\n*)\nInductive inc (V : Set) : Set :=\n| VZ : inc V\n| VS : V → inc V\n.\n\nArguments VZ [V].\nArguments VS [V].\n\nFixpoint incn V (n : nat) : Set :=\n  match n with\n  | O => V\n  | S m => inc (incn V m)\n  end\n.\n\nLemma incSn n : ∀ L, inc (incn L n) = incn (inc L) n.\ninduction n ; crush.\nDefined.\n\nNotation \"∅\" := Empty_set.\nNotation incN := (incn ∅).\n\n(** Introduce [n] more free variables *)\nFixpoint nVS (n : nat) V {struct n} : V → incn V n.\nProof.\ndestruct n as [ | n ] ; simpl.\n+ refine (λ x, x).\n+ intro x.\n  refine (VS (nVS n V x)).\nDefined.\n\nDefinition empty_fun {T} : ∅ → T :=\n  λ y, match y with end.\n\nNotation \"∅→\" := empty_fun.\n\nLemma empty_fun_is_injective T : Injective (∅→ : ∅ → T).\nProof. intro x ; destruct x. Qed.\n\n(** Extend a variable mapping. *)\nDefinition env_ext (V : Set) (T : Type) (env : V → T) (t : T) :\n    inc V → T :=\n  λ y, match y with\n  | VZ => t\n  | VS x => env x\n  end.\n\nParameter 𝔽 : Set.\n\nInductive\n(** label identifiers *)\nlid L : Set :=\n| lid_b : L → lid L\n| lid_f : var → lid L\n.\n\nInductive\n(** labels *)\nlbl LV L : Set :=\n| lbl_var : LV → lbl LV L\n| lbl_id : lid L → lbl LV L\n.\n\nInductive\n  (** effects *)\n  ef EP EV LV L : Set :=\n  | ef_par : EP → ef EP EV LV L\n  | ef_var : EV → ef EP EV LV L\n  | ef_lbl : lbl LV L → ef EP EV LV L\n.\n\n(** effect sequences *)\nNotation eff EP EV LV L := (list (ef EP EV LV L)).\n\nInductive\n  (** signature kind *)\n  sk : Set :=\n  | sk_ms : sk\n  | sk_ep : sk → sk\n.\n\nNotation \"'𝕄'\" := sk_ms.\nNotation \"'𝔼' → κ\" := (sk_ep κ) (at level 60).\n\nParameter (IKind : 𝔽 → sk).\n\nInductive\n  (** interfaces *)\n  it EP EV LV L : sk → Set :=\n  | it_name : ∀ F, it EP EV LV L (IKind F)\n  | it_inst : ∀ κ, it EP EV LV L (𝔼 → κ) → eff EP EV LV L → it EP EV LV L κ\n.\n\nInductive\n  (** types *)\n  ty EP EV LV L : Set :=\n  | ty_unit : ty EP EV LV L\n  | ty_cont : ty EP EV LV L → eff EP EV LV L → ty EP EV LV L → eff EP EV LV L → ty EP EV LV L\n  | ty_it   : it EP EV LV L 𝕄 → lbl LV L → ty EP EV LV L\n  | ty_ms   : ms EP EV LV L → lbl LV L → ty EP EV LV L\nwith\n  (** method signatures *)\n  ms EP EV LV L : Set :=\n  | ms_ev : ms EP (inc EV) LV L → ms EP EV LV L\n  | ms_lv : ms EP EV (inc LV) L → ms EP EV LV L\n  | ms_tm  : ty EP EV LV L → ms EP EV LV L → ms EP EV LV L\n  | ms_res : ty EP EV LV L → eff EP EV LV L → ms EP EV LV L\n.\n\nInductive\n  (** method definitions *)\n  md EV LV V L : Set :=\n  | md_ev : md (inc EV) LV V L → md EV LV V L\n  | md_lv : md EV (inc LV) V L → md EV LV V L\n  | md_tm  : md EV LV (inc V) L → md EV LV V L\n  | md_res : tm EV LV (inc V) L → md EV LV V L\nwith\n  (** evaluation contexts *)\n  ktx EV LV V L : Set :=\n  | ktx_hole    : ktx EV LV V L\n  | ktx_op      : ktx EV LV V L → ktx EV LV V L\n  | ktx_up      : ktx EV LV V L → ktx EV LV V L\n  | ktx_down    : ktx EV LV V L → var → ktx EV LV V L\n  | ktx_let     : ktx EV LV V L → tm EV LV (inc V) L → ktx EV LV V L\n  | ktx_throw   : ktx EV LV V L → tm EV LV V L → ktx EV LV V L\n  | ktx_app_eff : ktx EV LV V L → eff ∅ EV LV L → ktx EV LV V L\n  | ktx_app_lbl : ktx EV LV V L → lbl LV L → ktx EV LV V L\n  | ktx_app_tm1 : ktx EV LV V L → tm EV LV V L → ktx EV LV V L\n  | ktx_app_tm2 : ktx EV LV V L → val EV LV V L → ktx EV LV V L\nwith\n  (** values *)\n  val EV LV V L : Set :=\n  | val_unit : val EV LV V L\n  | val_var  : V → val EV LV V L\n  | val_cont : ktx EV LV V L → val EV LV V L\n  | val_md   : md EV LV V L → lid L → val EV LV V L\n  | val_fix  : md EV LV (inc V) L → lid L → val EV LV V L\nwith\n  (** terms *)\n  tm EV LV V L : Set :=\n  | tm_val     : val EV LV V L → tm EV LV V L\n  | tm_op      : tm EV LV V L → tm EV LV V L\n  | tm_up      : tm EV LV V L → tm EV LV V L\n  | tm_Down    : tm EV LV V (inc L) → tm EV LV V L\n  | tm_down    : var → tm EV LV V L → tm EV LV V L\n  | tm_let     : tm EV LV V L → tm EV LV (inc V) L → tm EV LV V L\n  | tm_throw   : tm EV LV V L → tm EV LV V L → tm EV LV V L\n  | tm_app_eff : tm EV LV V L → eff ∅ EV LV L → tm EV LV V L\n  | tm_app_lbl : tm EV LV V L → lbl LV L → tm EV LV V L\n  | tm_app_tm  : tm EV LV V L → tm EV LV V L → tm EV LV V L\n.\n\nArguments lid_f [L].\nArguments lbl_var [LV L].\nArguments lbl_id [LV L].\nArguments ef_par  [EP EV LV L].\nArguments ef_var  [EP EV LV L].\nArguments ef_lbl  [EP EV LV L].\nArguments it_name [EP EV LV L].\nArguments it_inst [EP EV LV L κ].\nArguments ty_unit [EP EV LV L].\nArguments ty_it [EP EV LV L].\n\nArguments ktx_hole [EV LV V L].\nArguments val_unit [EV LV V L].\nArguments val_var  [EV LV V L].\n\nCoercion val_cont : ktx >-> val.\nCoercion tm_val : val >-> tm.\n\nNotation \"𝟙\" := ty_unit.\nNotation \"⇧\" := tm_up.\nNotation \"⬇\" := tm_Down.\nNotation \"⇩\" := tm_down.\nNotation \"'λₜ'\" := md_tm.\nNotation \"'λₑ'\" := md_ev.\nNotation \"'λₗ'\" := md_lv.\nNotation \"'λᵣ'\" := md_res.\n\n(** Syntactic objects that do not contain any kind of free variables. *)\nNotation lid0 := (lid ∅).\nNotation lbl0 := (lbl ∅ ∅).\nNotation ef0 := (ef ∅ ∅ ∅ ∅).\nNotation eff0 := (eff ∅ ∅ ∅ ∅).\nNotation it0 := (it ∅ ∅ ∅ ∅).\nNotation ty0 := (ty ∅ ∅ ∅ ∅).\nNotation ms0 := (ms ∅ ∅ ∅ ∅).\nNotation tm0 := (tm ∅ ∅ ∅ ∅).\nNotation val0 := (val ∅ ∅ ∅ ∅).\nNotation md0 := (md ∅ ∅ ∅ ∅).\nNotation ktx0 := (ktx ∅ ∅ ∅ ∅).\n\nInductive\n(** interface signatures *)\nis EP EV LV L : Set :=\n| is_ms : ms EP EV LV L → is EP EV LV L\n| is_ep : is (inc EP) EV LV L → is EP EV LV L\n.\n\nFixpoint sk_is EP EV LV L (Σ : is EP EV LV L) : sk :=\nmatch Σ with\n| is_ms σ => 𝕄\n| is_ep Σ => 𝔼 → sk_is Σ\nend.\n\nNotation is0 := (is ∅ ∅ ∅ ∅).\n\nParameter (Signature : 𝔽 → is0).\nParameter (SignatureKind : ∀ F, IKind F = sk_is (Signature F)).\n\n(** label-identifier environments *)\nNotation XEnv EV LV := (env (ty ∅ EV LV ∅ * eff ∅ EV LV ∅)).\n\nInductive LEnv EV LV : Set → Type :=\n| LEnv_empty : LEnv EV LV ∅\n| LEnv_push  : ∀ L, LEnv EV LV L → ty ∅ EV LV L → eff ∅ EV LV L → LEnv EV LV (inc L)\n.\n\nArguments LEnv_empty [EV LV].\n\n(** Well-founded measures *)\n\nFixpoint size_eff EP EV LV L (E : eff EP EV LV L) : nat :=\nmatch E with\n| [] => 0\n| e :: E => 1 + size_eff E\nend.\n\nFixpoint size_it EP EV LV L κ (N : it EP EV LV L κ) : nat :=\nmatch N with\n| it_name _ => 0\n| it_inst N E => 1 + size_it N + size_eff E\nend.\n\nFixpoint\n  size_ty EP EV LV L (T : ty EP EV LV L) : nat :=\n  match T with\n  | ty_unit => 0\n  | ty_cont Ta Ea Tb Eb => 1 + size_ty Ta + size_eff Ea + size_ty Tb + size_eff Eb\n  | ty_it N _ => 1 + size_it N\n  | ty_ms σ _ => 1 + size_ms σ\n  end\nwith\n  size_ms EP EV LV L (σ : ms EP EV LV L) : nat :=\n  match σ with\n  | ms_ev σ => 1 + size_ms σ\n  | ms_lv σ => 1 + size_ms σ\n  | ms_tm T σ => 1 + size_ty T + size_ms σ\n  | ms_res T E => 1 + size_ty T + size_eff E\n  end\n.\n\nDefinition size_lbl EV LV (Ξ : XEnv EV LV) (ℓ : lbl LV ∅) :=\nmatch ℓ with\n| lbl_id (lid_f X) =>\n  match (get X Ξ) with\n  | Some (T, E) => 1 + size_ty T + size_eff E\n  | None => 0\n  end\n| _ => 0\nend.\n\nRequire Export Utf8 List Basics.\nExport ListNotations.\nRequire Export CpdtTactics.\nRequire Export LibLN.\nOpen Scope program_scope.\n\nHint Extern 1 => match goal with\n| [ |- ∀ x : ∅, _ ] => let x := fresh \"x\" in (intro x ; destruct x)\n| [ x : ∅ |- _ ] => destruct x\n| [ x : inc ?V |- _ ] => destruct x ; simpl ; crush\n| [ |- context[ _ ∘ _ ] ] => unfold compose ; crush\nend.\n", "meta": {"author": "yizhouzhang", "repo": "olaf-coq", "sha": "03090a5e60e739dfa45ad60322d848c18faad48d", "save_path": "github-repos/coq/yizhouzhang-olaf-coq", "path": "github-repos/coq/yizhouzhang-olaf-coq/olaf-coq-03090a5e60e739dfa45ad60322d848c18faad48d/coq-src/UFO/Lang/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.23484043695244025}}
{"text": "(* TRINC instance *)\n\nRequire Export TrInc.\nRequire Export TrInctacs.\nRequire Export TrIncbreak.\nRequire Export MinBFTrep.\nRequire Export MinBFTsim1.\nRequire Export ComponentAxiom.\nRequire Export ComponentSM3.\n\n\n\n(* Move to ComponentSM2 *)\nHint Resolve are_procs_empty_ls : comp.\nHint Resolve wf_empty_ls : comp.\n\n\nSection TrIncsubs.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext        }.\n  Context { minbft_context      : MinBFT_context      }.\n  Context { m_initial_keys      : MinBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys   }.\n  Context { usig_hash           : USIG_hash           }.\n  Context { minbft_auth         : MinBFT_auth         }.\n\n\n\n  Definition is_replica {eo : EventOrdering} (e : Event) :=\n    exists r, loc e = MinBFT_replica r.\n\n  Lemma in_output_implies_is_replica :\n    forall {eo : EventOrdering} (e : Event) o,\n      In o (M_output_sys_on_event MinBFTsys e)\n      -> is_replica e.\n  Proof.\n    introv h.\n    unfold M_output_sys_on_event in *.\n    unfold is_replica.\n    remember (loc e) as w; destruct w; simpl in *; tcsp; eauto.\n    apply not_in_M_output_ls_on_event_empty_ls in h; tcsp.\n  Qed.\n  Hint Resolve in_output_implies_is_replica : minbft.\n\n  Lemma local_pred_preserves_is_replica :\n    forall {eo : EventOrdering} (e1 e2 : Event),\n      e1 ⊂ e2\n      -> is_replica e2\n      -> is_replica e1.\n  Proof.\n    introv lte isrep.\n    unfold is_replica in *; exrepnd; exists r; rewrite <- isrep0; eauto 3 with eo.\n  Qed.\n  Hint Resolve local_pred_preserves_is_replica : minbft.\n\n  Lemma are_procs_MinBFTls : forall n, are_procs_n_procs (MinBFTlocalSys n).\n  Proof.\n    introv; simpl;\n      try (complete (eexists; introv; unfold proc2upd; simpl; try reflexivity));\n      try (complete (introv i; simpl in *; repndors; subst; tcsp; simpl;\n                     eexists; introv; unfold proc2upd;  reflexivity)).\n  Qed.\n  Hint Resolve are_procs_MinBFTls : minbft.\n\n  Lemma wf_MinBFTls : forall n, wf_procs (MinBFTlocalSys n).\n  Proof.\n    repeat introv; unfold wf_procs; simpl;\n      dands; try (complete (introv xx; repndors; tcsp; ginv));\n        repeat constructor; simpl; tcsp;\n          try (complete (introv xx; repndors; tcsp; ginv)).\n  Qed.\n  Hint Resolve wf_MinBFTls : minbft.\n\n  Lemma are_procs_MinBFTsys : are_procs_sys MinBFTsys.\n  Proof.\n    introv; destruct n; simpl; eauto 3 with comp minbft.\n  Qed.\n  Hint Resolve are_procs_MinBFTsys : minbft.\n\n  Lemma wf_MinBFTsys : wf_sys MinBFTsys.\n  Proof.\n    introv; destruct n; simpl; eauto 3 with comp minbft.\n  Qed.\n  Hint Resolve wf_MinBFTsys : minbft.\n\n  Lemma MinBFTsys_preserves_subs :\n    sys_preserves_subs MinBFTsys.\n  Proof.\n    introv; eauto 3 with comp minbft.\n  Qed.\n  Hint Resolve MinBFTsys_preserves_subs : minbft.\n\n  Lemma similar_minbft_implies_subs :\n    forall (subs : n_procs 1) r,\n      similar_subs subs (MinBFTsubs r)\n      -> exists (s1 : TRINC_state) (s2 : LOG_state),\n        subs = MinBFTsubs_new s1 s2.\n  Proof.\n    introv sim.\n    inversion sim; subst; clear sim.\n    inversion sims; subst; clear sims.\n    inversion sims0; subst; clear sims0.\n    applydup @similar_procs_implies_same_name in simp; simpl in *.\n    applydup @similar_procs_implies_same_name in simp0; simpl in *.\n    destruct p1, p0; simpl in *; subst; simpl in *.\n    destruct pp_proc, pp_proc0; simpl in *; tcsp;[].\n    apply @similar_procs_implies_same_proc in simp.\n    apply @similar_procs_implies_same_proc in simp0.\n    simpl in *; repnd; subst.\n    destruct a, a0; simpl in *; subst; simpl in *; tcsp;[].\n    unfold similar_sms_at in *; repnd; simpl in *; subst; tcsp.\n    unfold MinBFTsubs_new, build_m_sm, build_mp_sm, at2sm; simpl; eauto.\n  Qed.\n\n  Lemma similar_subs_MinBFTlocalSys_implies :\n    forall r (ls : n_procs 2),\n      similar_subs (MinBFTlocalSys r) ls\n      -> exists s s1 s2, ls = MinBFTlocalSys_new r s s1 s2.\n  Proof.\n    introv sim.\n    apply similar_subs_MinBFTlocalSysP  in sim; exrepnd; subst.\n    apply similar_subs_sym in sim1; apply similar_minbft_implies_subs in sim1; exrepnd; subst.\n    exists s s1 s2; auto.\n  Qed.\n\n  (* We can also prove some preservation lemmas:\n       for example that the replica field in the USIG does not change *)\n  Lemma M_run_ls_before_event_ls_is_minbft :\n    forall {eo : EventOrdering}\n           (e  : Event)\n           (r  : Rep)\n           (ls : MinBFTls),\n      M_run_ls_before_event (MinBFTlocalSys r) e = Some ls\n      ->\n      exists (s : MAIN_state) (s1 : TRINC_state) (s2 : LOG_state),\n        ls = MinBFTlocalSys_new r s s1 s2.\n  Proof.\n    introv run.\n    apply M_run_ls_before_event_preserves_subs in run; eauto 3 with comp minbft.\n    repnd; simpl in *.\n    apply similar_subs_MinBFTlocalSys_implies in run2; auto.\n  Qed.\n\n  Lemma M_run_ls_on_event_ls_is_minbft :\n    forall {eo : EventOrdering}\n           (e  : Event)\n           (r  : Rep)\n           (ls : MinBFTls),\n      M_run_ls_on_event (MinBFTlocalSys r) e = Some ls\n      ->\n      exists (s : MAIN_state) (s1 : TRINC_state) (s2 : LOG_state),\n        ls = MinBFTlocalSys_new r s s1 s2.\n  Proof.\n    introv run.\n    apply M_run_ls_on_event_preserves_subs in run; eauto 3 with comp minbft.\n    repnd; simpl in *.\n    apply similar_subs_MinBFTlocalSys_implies in run2; auto.\n  Qed.\n\n  Lemma similar_minbft_implies_level :\n    forall r {n} (subs : n_procs n),\n      similar_subs subs (MinBFTsubs r)\n      -> n = 1.\n  Proof.\n    introv sim.\n    applydup @similar_subs_implies_same_level in sim; auto.\n    destruct subs; simpl in *; auto; try omega.\n    inversion sim.\n  Qed.\n\n(*  Lemma call_usig_preserves_subs :\n    forall r i o {n} (subs1 subs2 : n_procs n),\n      call_proc USIGname i subs1 = (subs2, o)\n      -> similar_subs subs1 (MinBFTsubs r)\n      -> similar_subs subs1 subs2.\n  Proof.\n    introv c sim.\n    unfold call_proc in c; smash_minbft; eauto 3 with comp;[].\n    applydup similar_minbft_implies_level in sim; subst n.\n    applydup similar_minbft_implies_subs in sim; exrepnd; subst; simpl in *.\n    repndors; subst; tcsp; ginv.\n    inversion Heqx; subst; simpl in *; clear Heqx.\n    unfold USIG_update in *; simpl in *.\n    destruct i; simpl in *; smash_minbft; simpl in *;\n      unfold build_mp_sm, decr_n_procs, sm_s_to_sm, bind, lift_M_O in Heqx1; simpl in *;\n        inversion Heqx1; substs; simpl in *; repeat constructor.\n  Qed.\n  Hint Resolve call_usig_preserves_subs : minbft.\n\n  Lemma call_log_preserves_subs :\n    forall r i o {n} (subs1 subs2 : n_procs n),\n      call_proc LOGname i subs1 = (subs2, o)\n      -> similar_subs subs1 (MinBFTsubs r)\n      -> similar_subs subs1 subs2.\n  Proof.\n    introv c sim.\n    unfold call_proc in c; smash_minbft; eauto 3 with comp;[].\n    applydup similar_minbft_implies_level in sim; subst n.\n    applydup similar_minbft_implies_subs in sim; exrepnd; subst; simpl in *.\n    repndors; subst; tcsp; ginv.\n    inversion Heqx; subst; simpl in *; clear Heqx.\n    unfold USIG_update in *; simpl in *.\n    destruct i; simpl in *; smash_minbft; simpl in *;\n      unfold build_mp_sm, decr_n_procs, sm_s_to_sm, bind, lift_M_O in Heqx1; simpl in *;\n        inversion Heqx1; substs; simpl in *; repeat constructor.\n  Qed.\n  Hint Resolve call_log_preserves_subs : minbft.*)\n\n  Lemma implies_similar_subs_MinBFTsubs_new :\n    forall s1 s2 s3 s4,\n      similar_subs (MinBFTsubs_new s1 s2) (MinBFTsubs_new s3 s4).\n  Proof.\n    introv.\n    repeat constructor.\n  Qed.\n  Hint Resolve implies_similar_subs_MinBFTsubs_new : minbft.\n\n  Lemma is_trusted_ls_usig :\n    forall n, is_trusted_ls USIGname (MinBFTlocalSys n).\n  Proof.\n    introv; tcsp.\n  Qed.\n  Hint Resolve is_trusted_ls_usig : minbft.\n\n  Definition USIG_sm_new s :=\n    build_m_sm USIG_update s.\n\n(*  Lemma trusted_run_sm_on_inputs_usig :\n    forall s n l,\n      trusted_run_sm_on_inputs s (USIG_comp n) l\n      = Some (run_sm_on_inputs_trusted (USIG_sm_new s) l).\n  Proof.\n    tcsp.\n  Qed.*)\n\n  Lemma usig_id_try_update_USIG :\n    forall cid old new s,\n      trinc_id (try_update_TRINC cid old new s) = trinc_id s.\n  Proof.\n    introv; unfold try_update_TRINC; smash_minbft.\n  Qed.\n  Hint Rewrite usig_id_try_update_USIG : minbft.\n\n(*  Lemma run_sm_on_inputs_trusted_usig_preserves_id :\n    forall l s,\n      trinc_id (run_sm_on_inputs_trusted (USIG_sm_new s) l) = trinc_id s.\n  Proof.\n    induction l; introv; simpl in *; tcsp;[].\n    pose proof (run_sm_on_inputs_trusted_cons _ _ _ (USIG_sm_new s) a l) as xx.\n    simpl in *; rewrite xx; auto; clear xx.\n    match goal with\n    | [ |- context[fst ?x]] => remember (fst x) as w; symmetry in Heqw\n    end.\n    unfold update_state_op_m; dest_cases z; symmetry in Heqz.\n    subst.\n    rewrite IHl.\n\n    unfold USIG_update in Heqw.\n    destruct a; simpl in *; repnd; simpl in *; inversion Heqw; simpl in *;\n      autorewrite with minbft; auto.\n  Qed.*)\n\n  Lemma similar_sms_at_log :\n    forall s p,\n      similar_sms_at (build_mp_sm LOG_update s) p\n      <-> exists s', p = build_mp_sm LOG_update s'.\n  Proof.\n    introv; split; intro h; exrepnd; subst; eauto.\n\n    { inversion h; subst.\n      destruct p as [up st]; simpl in *; subst; eauto.\n      exists st; auto. }\n\n    { constructor; auto. }\n  Qed.\n  Hint Rewrite similar_sms_at_log : minbft.\n\n  Lemma similar_sms_at_usig :\n    forall s p,\n      similar_sms_at (build_mp_sm USIG_update s) p\n      <-> exists s', p = build_mp_sm USIG_update s'.\n  Proof.\n    introv; split; intro h; exrepnd; subst; eauto.\n\n    { inversion h; subst.\n      destruct p as [up st]; simpl in *; subst; eauto.\n      exists st; auto. }\n\n    { constructor; auto. }\n  Qed.\n  Hint Rewrite similar_sms_at_usig : minbft.\n\nEnd TrIncsubs.\n\n\nHint Resolve in_output_implies_is_replica : minbft.\nHint Resolve local_pred_preserves_is_replica : minbft.\nHint Resolve are_procs_MinBFTls : minbft.\nHint Resolve wf_MinBFTls : minbft.\nHint Resolve are_procs_MinBFTsys : minbft.\nHint Resolve wf_MinBFTsys : minbft.\n(*Hint Resolve call_usig_preserves_subs : minbft.\nHint Resolve call_log_preserves_subs : minbft.*)\nHint Resolve MinBFTsys_preserves_subs : minbft.\nHint Resolve implies_similar_subs_MinBFTsubs_new : minbft.\nHint Resolve is_trusted_ls_usig : minbft.\n\n\nHint Rewrite @similar_sms_at_log : minbft.\nHint Rewrite @similar_sms_at_usig : minbft.\nHint Rewrite @usig_id_try_update_USIG : minbft.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/TrIncsubs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2348404308777496}}
{"text": "(* ** Reduction from ZF' to finite ZF *)\n\nFrom Undecidability.FOL\n     Require Import Syntax.Facts Semantics.Tarski.FullFacts Deduction.FullNDFacts.\n\nFrom Undecidability.FOL.Sets\n     Require Import ZF.\nRequire Import Undecidability.FOL.ZF.\n\nRequire Import Lia.\n\nFrom Undecidability Require Import Shared.ListAutomation.\nImport ListAutomationNotations ListAutomationHints ListAutomationInstances.\n\nLocal Set Implicit Arguments.\nLocal Unset Strict Implicit.\n\nDefinition add_om phi :=\n  ax_om1 → ax_om2 → phi.\n\nTheorem reduction_entailment phi :\n  entailment_ZF' phi <-> entailment_HF (add_om phi).\nProof.\n  split; intros Hp D I rho HE HI.\n  - intros H1 H2. apply Hp; trivial.\n    intros sigma psi [<-|[<-|[<-|[<-|[<-|[<-|[<-|[]]]]]]]]; trivial.\n    all: apply HI; unfold HF; intuition.\n  - apply Hp; fold sat; trivial. 2,3: apply HI; unfold ZF'; intuition eauto 7.\n    intros sigma psi [<-|[<-|[<-|[<-|[<-|[]]]]]].\n    all: apply HI; unfold ZF'; intuition.\nQed.\n\nTheorem reduction_deduction phi :\n  deduction_ZF' phi <-> deduction_HF (add_om phi).\nProof.\n  unfold deduction_ZF', deduction_HF, add_om. rewrite !imps.\n  split; intros H; apply (Weak H); unfold ZFeq', HFeq, ZF', HF; firstorder.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-library-undecidability", "sha": "4547d325e8ce7a6d841fbfe5df4429ee9cb6f214", "save_path": "github-repos/coq/uds-psl-coq-library-undecidability", "path": "github-repos/coq/uds-psl-coq-library-undecidability/coq-library-undecidability-4547d325e8ce7a6d841fbfe5df4429ee9cb6f214/theories/FOL/Reductions/ZF_to_HF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23473637915483503}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Lists.ListSet.\nRequire Import Coq.Strings.String.\nRequire Import BinInt.\nRequire Import VerifiedVerifier.Machine.\nRequire Import VerifiedVerifier.Bits.\nRequire Import VerifiedVerifier.Maps.\n\nType map.\n(*TODO: figure out if we need uints vs ints*)\nDefinition registers_ty := total_map register int64.\n\nDefinition stack_ty := list int64.\n\nDefinition heap_ty := total_map int64 int64.\n\nDefinition flags_ty := total_map flag int1.\n\nDefinition function_table_ty := partial_map int64 string.\n\nRecord state := {\n  regs : registers_ty;\n  flags : flags_ty;\n  stack : stack_ty;\n  heap : heap_ty;\n  heap_base : int64;\n  function_table : function_table_ty;\n  error_state : bool;\n}.\n\nFixpoint value_to_int64 (s : state) (v :value) : int64 :=\nmatch v with\n| Const c => c\nend.\n\nDefinition get_register (s : state) (r : register) : int64 :=\n  s.(regs) r.\n\nDefinition set_register (s : state) (r : register) (v : int64) : state :=\n{| regs := t_update register_eq_dec s.(regs) r v;\n   flags := s.(flags);\n   stack := s.(stack);\n   heap := s.(heap);\n   heap_base := s.(heap_base);\n   function_table := s.(function_table);\n   error_state := s.(error_state) |}.\n\nDefinition set_flags (s : state) (f : flags_ty) : state :=\n{| regs := s.(regs);\n   flags := f;\n   stack := s.(stack);\n   heap := s.(heap);\n   heap_base := s.(heap_base) ;\n   function_table := s.(function_table);\n   error_state := s.(error_state) |}.\n\nDefinition expand_stack (s : state) (i : nat) : state :=\n{| regs := s.(regs);\n   flags := s.(flags);\n   stack := s.(stack) ++ (repeat Word.zero i);\n   heap := s.(heap);\n   heap_base := s.(heap_base) ;\n   function_table := s.(function_table);\n   error_state := s.(error_state) |}.\n\nFixpoint contract_stack (s : state) (i : nat) : state :=\nmatch i with\n| 0 => s\n| S n =>\ncontract_stack {| regs := s.(regs);\n   flags := s.(flags);\n   stack := removelast s.(stack);\n   heap := s.(heap);\n   heap_base := s.(heap_base) ;\n   function_table := s.(function_table);\n   error_state := s.(error_state) |}\n n\nend.\n\nDefinition read_stack (s : state) (i : nat) : int64 :=\nnth_default Word.zero s.(stack) i.\n\nDefinition write_stack (s : state) (i : nat) (val : int64) : state :=\n{| regs := s.(regs);\n   flags := s.(flags);\n   stack := Machine.update s.(stack) i val;\n   heap := s.(heap);\n   heap_base := s.(heap_base) ;\n   function_table := s.(function_table);\n   error_state := s.(error_state) |}.\n\nDefinition read_heap (s : state) (i : int64) : int64 :=\ns.(heap) i.\n\nDefinition write_heap (s : state) (i : int64) (v : int64) : state :=\n{| regs := s.(regs);\n\t flags := s.(flags);\n\t stack := s.(stack);\n\t heap := t_update int64_eq_dec s.(heap) i v;\n   heap_base := s.(heap_base);\n   function_table := s.(function_table);\n   error_state := s.(error_state) |}.\n\nDefinition set_error_state (s : state) : state :=\n{| regs := s.(regs);\n\t flags := s.(flags);\n\t stack := s.(stack);\n\t heap := s.(heap);\n   heap_base := s.(heap_base);\n   function_table := s.(function_table);\n   error_state := true |}.\n\nDefinition fourGB : int64 := (Word.shl (Word.repr 2) (Word.repr 32)).\n\n(*TODO: This doesn't handle signed/unsigned conversions correctly*)\nDefinition run_conditional (c : conditional) (s : state) : bool :=\n  match c with\n| Not_Equal r1 r2 => negb (Word.eq (get_register s r1) (get_register s r2))\n| Equal r1 r2 => Word.eq (get_register s r1) (get_register s r2)\n| Greater r1 r2 => Word.lt (get_register s r2) (get_register s r1)\n| Greater_Equal r1 r2 => orb (Word.lt (get_register s r2) (get_register s r1)) (Word.eq (get_register s r1) (get_register s r2))\n| Above r1 r2 => Word.ltu (get_register s r2) (get_register s r1)\n| Above_Equal r1 r2 => orb (Word.ltu (get_register s r2) (get_register s r1)) (Word.eq (get_register s r1) (get_register s r2))\n| Lesser r1 r2 => Word.lt (get_register s r1) (get_register s r2)\n| Lesser_Equal r1 r2 => orb (Word.lt (get_register s r1) (get_register s r2)) (Word.eq (get_register s r1) (get_register s r2))\n| Below r1 r2 => Word.ltu (get_register s r1) (get_register s r2)\n| Below_Equal r1 r2 => orb (Word.ltu (get_register s r1) (get_register s r2)) (Word.eq (get_register s r1) (get_register s r2))\n| Counter_Register_Zero => Word.eq (get_register s rcx) (Word.repr 0)\nend.\n\nDefinition run_instr (inst : instr_class) (s : state) : state := \n  match inst with \n| Heap_Read r_dst r_src r_base => set_register s r_dst (read_heap s (Word.add (get_register s r_src) (get_register s r_base)))\n| Heap_Write r_dst r_val r_base => write_heap s (Word.add (get_register s r_dst) (get_register s r_base)) (get_register s r_val)\n| Heap_Check r => set_register s r (Word.modu (get_register s r) fourGB)\n| Call_Check r => s (*TODO: Figure out wtf to do.*)\n| Reg_Write r v => set_register s r (value_to_int64 s v)\n| Reg_Move r_dst r_src => set_register s r_dst (get_register s r_src)\n| Stack_Expand i => expand_stack s i\n| Stack_Contract i => contract_stack s i\n| Stack_Read r i => set_register s r (read_stack s i)\n| Stack_Write i r => write_stack s i (get_register s r)\n(*TODO: Make sure calls are right*)\n| Indirect_Call r => s\n| Direct_Call name => s\n| Branch c => s\n| UniOp op r_dst => s\n| BinOp op r_dst r_src => s\n| DivOp r_dst => s\n| Ret => s\nend.\n\nTheorem run_instr_deterministic : forall init_st st st' i, \n  run_instr i init_st = st ->\n  run_instr i init_st = st' ->\n  st = st'.\nProof.\n  intros init_st st st' i H1 H2. rewrite <- H1, H2. auto.\nQed.\n\nReserved Notation \" i '/' st 'i-->' st' \"\n                  (at level 40, st' at level 39).\nInductive instr_class_istep : instr_class -> state -> state -> Prop := \n| I_Heap_Read: forall st r_base r_src r_dst,\n    Heap_Read r_dst r_src r_base / st i--> set_register st r_dst (read_heap st (Word.add (get_register st r_src) (get_register st r_base)))\n| I_Heap_Write: forall st r_base r_val r_dst,\n    Heap_Write r_dst r_val r_base / st i--> write_heap st (Word.add (get_register st r_dst) (get_register st r_base)) (get_register st r_val)\n| I_Heap_Check: forall st r_src,\n    Heap_Check r_src / st i--> set_register st r_src (Word.modu (get_register st r_src) fourGB)\n| I_Call_Check: forall st r_src,\n    Call_Check r_src / st i--> st (* probably wrong *)\n| I_Reg_Move: forall st r_src r_dst,\n    Reg_Move r_dst r_src / st i--> set_register st r_dst (get_register st r_src)\n| I_Reg_Write: forall st r_dst val,\n    Reg_Write r_dst val / st i--> set_register st r_dst (value_to_int64 st val)\n| I_Stack_Expand: forall st i,\n    Stack_Expand i / st i--> expand_stack st i\n| I_Stack_Contract: forall st i,\n    Stack_Contract i / st i--> contract_stack st i\n| I_Stack_Read: forall st i r_dst,\n    Stack_Read r_dst i / st i--> set_register st r_dst (read_stack st i)\n| I_Stack_Write: forall st i r_src,\n    Stack_Write i r_src / st i--> write_stack st i (get_register st r_src)\n(* those calls might also be wrong *)\n| I_Indirect_Call: forall st reg,\n    Indirect_Call reg / st i-->  st\n| I_Direct_Call: forall st name,\n    Direct_Call name / st i-->  st\n| I_Branch: forall st c,\n    (Branch c) / st i--> st\n| I_UniOp: forall st op r_dst,\n    (UniOp op r_dst) / st i--> st\n| I_BinOp: forall st op r_dst r_src,\n    (BinOp op r_dst r_src) / st i--> st\n| I_DivOp : forall st r_dst,\n    (DivOp r_dst) / st i--> st\n| I_Ret: forall st,\n    Ret / st i-->  st\n  where \" i '/' st 'i-->' st'\" := (instr_class_istep i st st').\n\nTheorem instr_class_istep_deterministic : forall init_st st st' i, \n  i / init_st i--> st ->\n  i / init_st i--> st' ->\n  st = st'.\nProof.\n  intros init_st st st' i H1 H2. inversion H1; inversion H2; subst; \n  try (inversion H8; auto);\n  try (inversion H7; auto);\n  try (inversion H6; auto);\n  try (inversion H5; auto);\n  try (inversion H4; auto).\nQed.\n\nTheorem instr_class_always_isteps : forall st i,\n  exists st', i / st i--> st'.\nProof.\n  intros st i. induction i; eexists.\n- apply I_Heap_Read.\n- apply I_Heap_Write.\n- apply I_Heap_Check.\n- apply I_Call_Check.\n- apply I_Reg_Move.\n- apply I_Reg_Write. \n- apply I_Stack_Expand.\n- apply I_Stack_Contract.\n- apply I_Stack_Read.\n- apply I_Stack_Write.\n- apply I_Indirect_Call.\n- apply I_Direct_Call.\n- apply I_Branch.\n- apply I_UniOp.\n- apply I_BinOp.\n- apply I_DivOp.\n- apply I_Ret.\nQed.\n\nDefinition run_basic_block (bb : basic_block) (s : state) : state :=\n  fold_left (fun s i => run_instr i s) bb s.\n\n(* TODO: Not sure why this is necessary, but it won't go through\n * if I try to inline node_ty_eqb_dec *)\nDefinition node_ty_eqb (a : node_ty) (b : node_ty) : bool :=\n  if node_ty_eq_dec a b\n  then true\n  else false.\n\n(* TODO: Not sure why this is necessary, but it won't go through\n * if I try to inline edge_class_eqb_dec *)\nDefinition edge_class_eqb (a : edge_class) (b : edge_class) : bool :=\n  if edge_class_eq_dec a b\n  then true\n  else false.\n\nDefinition find_edge (cfg : cfg_ty) (n : node_ty) (e : edge_class) : option node_ty :=\n  match find (fun x => andb (node_ty_eqb (fst (fst x)) n)\n                            (edge_class_eqb (snd x) e))\n             cfg.(edges) with\n  | Some edge => Some (snd (fst edge))\n  | None => None\n  end.\n\nDefinition next_node (cfg : cfg_ty) (s : state) (n : node_ty) : option node_ty :=\n  match last (fst n) Ret with\n  | Branch c => if run_conditional c s\n                then find_edge cfg n True_Branch\n                else find_edge cfg n False_Branch\n  | Ret => None\n  | _ => find_edge cfg n Non_Branch\n  end.\n\nDefinition get_function_from_name (p : program_ty) (name : string) : option function_ty :=\n  find (fun x => eqb (snd x) name) p.(funs).\n\nDefinition function_lookup (p : program_ty) (s : state) (i : int64) : option function_ty :=\nmatch (s.(function_table) i) with\n| Some name => get_function_from_name p name\n| None => get_function_from_name p \"trap\"\nend.\n\n(* TODO: Make sure we are handling errors correctly *)\nFixpoint run_program (p : program_ty) (cfg : cfg_ty) (n : node_ty) (s : state) (fuel : nat) : state :=\n  match fuel with\n  | 0 => set_error_state s\n  | S fuel' =>\n    let bb := fst n in\n    let s' := run_basic_block bb s in\n    let s'' := match last bb Ret with\n               | Direct_Call name =>\n                   match get_function_from_name p name with\n                   | Some f => run_program p (fst f) (fst f).(start_node) s' fuel'\n                   | None => set_error_state s'\n                   end\n               | Indirect_Call r =>\n                   match function_lookup p s' (get_register s r) with\n                   | Some f => run_program p (fst f) (fst f).(start_node) s' fuel'\n                   | None => set_error_state s'\n                   end\n               | _ => s'\n               end in\n    match next_node cfg s n with\n    | Some n' => run_program p cfg n' s'' fuel'\n    | None => s''\n    end\n  end.\n", "meta": {"author": "yalhessi", "repo": "verified-verifier", "sha": "6471820d21feeac2766944f506ec9304558442c5", "save_path": "github-repos/coq/yalhessi-verified-verifier", "path": "github-repos/coq/yalhessi-verified-verifier/verified-verifier-6471820d21feeac2766944f506ec9304558442c5/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2347363734556794}}
{"text": "Require Import\n        Fiat.Common.ilist\n        Fiat.Common.SumType\n        Fiat.Narcissus.Common.Specs.\n\nRequire Import\n        Coq.Sets.Ensembles\n        Bedrock.Word.\n\nSection SumType.\n\n  Context {B : Type}.\n  Context {cache : Cache}.\n  Context {cacheAddNat : CacheAdd cache nat}.\n  Context {monoid : Monoid B}.\n  Context {monoidUnit : MonoidUnit monoid bool}.\n\n  Definition format_SumType {m}\n             (types : Vector.t Type m)\n             (formatrs : ilist (B := fun T => T -> CacheFormat -> B * CacheFormat) types)\n             (st : SumType types)\n    : CacheFormat -> B * CacheFormat :=\n    ith formatrs (SumType_index types st) (SumType_proj types st).\n\n  Definition decode_SumType {m}\n             (types : Vector.t Type m)\n             (decoders : ilist (B := fun T => B -> CacheDecode -> T * B * CacheDecode) types)\n             (idx : Fin.t m)\n             (b : B)\n             (cd : CacheDecode)\n    : SumType types * B * CacheDecode :=\n    let z := (ith decoders idx b cd) in\n    (inj_SumType types idx (fst (fst z)), snd (fst z), snd z).\n\n  Lemma tri_proj_eq {A C D} : forall a c d (acd : A * C * D),\n      a = fst (fst acd)\n      -> c = snd (fst acd)\n      -> d = snd acd\n      -> acd = ((a, c), d).\n  Proof.\n    intros; subst; intuition.\n  Qed.\n\n  Theorem SumType_decode_correct {m}\n          (types : Vector.t Type m)\n          (formatrs : ilist (B := fun T => T -> CacheFormat -> B * CacheFormat) types)\n          (decoders : ilist (B := fun T => B -> CacheDecode -> T * B * CacheDecode) types)\n          (invariants : forall idx, Vector.nth types idx -> Prop)\n          (formatrs_decoders_correct : forall idx,\n              format_decode_correct\n                monoid\n                (fun st => invariants idx st)\n                (ith formatrs idx)\n                (ith decoders idx))\n          idx\n    :\n    format_decode_correct monoid (fun st => SumType_index types st = idx /\\ invariants _ (SumType_proj types st))\n                          (format_SumType types formatrs)\n                          (decode_SumType types decoders idx).\n  Proof.\n    revert types formatrs decoders invariants formatrs_decoders_correct.\n    unfold format_decode_correct, format_SumType, decode_SumType.\n    induction types.\n    - inversion idx.\n    - revert types IHtypes h; pattern n, idx; apply Fin.caseS;\n        clear n idx; intros; destruct H0.\n      + (* First element *)\n        destruct types.\n        * unfold SumType in data, data'.\n          eapply (formatrs_decoders_correct Fin.F1); eauto.\n          injection H2; intros; subst.\n          apply tri_proj_eq; eauto.\n        * destruct data; try discriminate.\n          injection H2; intros; subst.\n          repeat split; try f_equal;\n          eapply (formatrs_decoders_correct Fin.F1) with\n          (ext := ext)\n            (ext' := snd (fst (prim_fst decoders (mappend bin ext) env')))\n            (data' := fst (fst (prim_fst decoders (mappend bin ext) env'))); intuition eauto; apply tri_proj_eq; eauto.\n      + (* Second element *)\n        destruct types; try discriminate.\n        destruct data as [s | s]; try discriminate.\n        destruct data' as [s' | s']; try discriminate.\n        assert (p = SumType_index (Vector.cons Type h0 n types) s) by\n            (apply Fin.FS_inj in H0;\n             rewrite <- H0; reflexivity).\n        assert (invariants\n                  (Fin.FS (SumType_index (Vector.cons Type h0 n types) s))\n                  (SumType_proj (Vector.cons Type h0 n types) s)) as H3' by\n            eapply H3.\n        assert (ith formatrs\n                    (Fin.FS (SumType_index (Vector.cons Type h0 n types) s))\n                    (SumType_proj (Vector.cons Type h0 n types) s) env =\n                (bin, xenv)) as H1' by apply H1; clear H1.\n        assert (Equiv xenv xenv' /\\ s = s' /\\ ext = ext').\n        eapply IHtypes; eauto.\n        intros; eapply (fun idx => formatrs_decoders_correct (Fin.FS idx));\n          eauto.\n        eapply H5.\n        split.\n        symmetry; apply H4.\n        apply H3'.\n        eapply tri_proj_eq;\n          try solve [injection H2; intros; subst; eauto].\n        intuition.\n        congruence.\n  Qed.\nEnd SumType.\n\nArguments SumType : simpl never.\n", "meta": {"author": "PRECISE", "repo": "smedl-fiat-code", "sha": "0c382ae9aa40df08c982fe0659a09544c69dc479", "save_path": "github-repos/coq/PRECISE-smedl-fiat-code", "path": "github-repos/coq/PRECISE-smedl-fiat-code/smedl-fiat-code-0c382ae9aa40df08c982fe0659a09544c69dc479/fiat/src/Narcissus/Formats/SumType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2347358089433618}}
{"text": "(*===========================================================================\n  Macros for defining and calling functions using x86 calling conventions\n  used by C compilers.\n  ===========================================================================*)\nRequire Import ssreflect ssrbool ssrfun ssrnat eqtype seq fintype tuple.\nRequire Import procstate procstatemonad bitsrep bitsops bitsprops bitsopsprops.\nRequire Import SPred septac spec safe basic program macros call.\nRequire Import instr instrsyntax.\nRequire Import NaryFunctions.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nLocal Open Scope instr_scope.\n\n(*---------------------------------------------------------------------------\n    Calling-convention-independent definitions\n  ---------------------------------------------------------------------------*)\n\n(* A function signature is simply an arity and a bool\n   denoting the presence or absence of a return value. In future we could\n   extend this to deal with other types e.g. floats, 64-bit integers *)\n(*=FunSig *)\nStructure FunSig := mkFunSig { arity: nat; nonvoid: bool }.\n(*=End *)\n\n(* A function body can be defined independently of calling convention by\n   parameterizing it on InstrSrc arguments. Result is assumed to be in EAX. *)\nDefinition programWithSig sig :=\n  InstrSrc ^^ arity sig --> program.\n\n(* Here is an example: \\n.n+1 *)\nExample incBody : programWithSig (mkFunSig 1 true) :=\n  fun arg => makeMOV EAX arg;; INC EAX.\n\n(*---------------------------------------------------------------------------\n    Helpers for calling\n  ---------------------------------------------------------------------------*)\n\n(* Push n arguments on the stack *)\nFixpoint pushArgs n (p:program) : nfun Src n program :=\n  if n is n.+1\n  then fun arg => pushArgs n (PUSH arg;; p)\n  else p.\n\nDefinition makeMOVsrc (r:Reg) (s: Src) : program :=\n  match s with\n  | SrcI c => MOV r, c\n  | SrcM m => MOV r, m\n  | SrcR r' => if r==r' then prog_skip else MOV r, r'\n  end.\n\n(* Put first argument in ECX, second in EDX, and the rest on the stack *)\nDefinition pushFastArgs n (p:program) : nfun Src n program :=\n  match n with\n  | 0 => p\n  | 1 => fun arg => (makeMOVsrc ECX arg;; p)\n  | n.+2 => fun arg1 arg2 => pushArgs n (makeMOVsrc ECX arg1;; makeMOVsrc EDX arg2;; p)\n  end.\n\n(*---------------------------------------------------------------------------\n    We support three x86 calling conventions:\n    * cdecl\n      - arguments pushed right to left\n      - result (if any) in EAX\n      - EAX, ECX, EDX are caller-saved, rest callee-saved\n      - caller cleans up stack (typically using ADD ESP, n)\n    * stdcall\n      - arguments pushed right to left\n      - result (if any) in EAX\n      - EAX, ECX, EDX are caller-saved, rest callee-saved\n      - callee cleans up stack (typically using RET n)\n    * fastcall\n      - first argument passed in ECX, second in EDX, remainder pushed right to left\n      - result (if any) in EAX\n      - EAX, ECX, EDX are caller-saved, rest callee-saved\n      - callee cleans up stack (typically using RET n)\n  ---------------------------------------------------------------------------*)\n\n(*=CallConv *)\nInductive CallConv := cdecl | stdcall | fastcall.\n(*=End *)\n\n(*---------------------------------------------------------------------------\n    Generate calling sequence for cdecl, stdcall and fastcall conventions\n  ---------------------------------------------------------------------------*)\nDefinition call_cdecl_with (n:nat) (f:JmpTgt) :=\n  pushArgs n (CALL f;; ADD ESP, n*4).\n\nDefinition call_std_with (n:nat) (f: JmpTgt) :=\n  pushArgs n (CALL f).\n\nDefinition call_fast_with (n:nat) (f: JmpTgt) :=\n  pushFastArgs n (CALL f).\n\nDefinition call_with (cc: CallConv) :=\n  match cc with\n  | cdecl => call_cdecl_with\n  | stdcall => call_std_with\n  | fastcall => call_fast_with\n  end.\n\n\n(*---------------------------------------------------------------------------\n    Helper for creating function prologues and epilogues\n  ---------------------------------------------------------------------------*)\nFixpoint introParams n offset : InstrSrc ^^ n --> program -> program :=\n  if n is n'.+1\n  then fun p => introParams (offset + 4) (p [EBP + offset]%ms)\n  else fun p => p.\nImplicit Arguments introParams [].\n\n\n(*---------------------------------------------------------------------------\n    Create function definitions for cdecl, stdcall and fastcall conventions\n  ---------------------------------------------------------------------------*)\nDefinition def_cdecl sig : programWithSig sig -> program :=\n  match sig return programWithSig sig -> program with\n  | mkFunSig n _ =>\n    fun body =>\n    PUSH EBP;; MOV EBP, ESP;;\n    introParams n 8 body;; POP EBP;; RET 0\n  end.\nImplicit Arguments def_cdecl [].\n\nDefinition def_std sig : programWithSig sig -> program :=\n  match sig return programWithSig sig -> program with\n  | mkFunSig n _ =>\n    fun body =>\n    PUSH EBP;; MOV EBP, ESP;;\n    introParams n 8 body;; POP EBP;; RET (n*4)\n\n  end.\nImplicit Arguments def_std [].\n\nDefinition def_fast sig :=\n  match sig return programWithSig sig -> program with\n  | mkFunSig 0 _ => fun body => body;; RET 0\n  | mkFunSig 1 _ => fun body => body ECX;; RET 0\n  | mkFunSig 2 _ => fun body => body ECX EDX;; RET 0\n  | mkFunSig n.+2 _ =>\n    fun body => PUSH EBP;; MOV EBP, ESP;; introParams n 8 (body ECX EDX);; POP EBP;; RET 0\n  end.\nImplicit Arguments def_fast [].\n\nDefinition def_fun cc :=\n  match cc with\n  | cdecl => def_cdecl\n  | stdcall => def_std\n  | fastcall => def_fast\n  end.\nImplicit Arguments def_fun [].\n\nDefinition callconv cc sig := (call_with cc sig.(arity), def_fun cc sig).\n\n(* Examples: compare http://en.wikibooks.org/wiki/X86_Disassembly/Calling_Conventions *)\n\n(*=addfun *)\nExample addfun (cc: CallConv) :=\n  let (call, def) := callconv cc (mkFunSig 3 true) in\n  LOCAL AddThree; LOCAL ExampleUse;\n    AddThree:;;\n      def (fun a b c =>  MOV EAX, a;; ADD EAX, b;; ADD EAX, c);;\n    ExampleUse:;;\n      call AddThree 2 3 4.\n(*=End *)\n\n(*\nEval showinstr in linearize (addfun cdecl).\nEval showinstr in linearize (addfun stdcall).\nEval showinstr in linearize (addfun fastcall).\n*)\n", "meta": {"author": "jbj", "repo": "x86proved", "sha": "d314fa6d23c064a2be4bf686ac7da16a591fda01", "save_path": "github-repos/coq/jbj-x86proved", "path": "github-repos/coq/jbj-x86proved/x86proved-d314fa6d23c064a2be4bf686ac7da16a591fda01/src/x86/cfunc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.44167300566462564, "lm_q1q2_score": 0.2346208405752093}}
{"text": "From sflib Require Import sflib.\nRequire Import Coq.Classes.RelationClasses.\nFrom Fairness Require Import Axioms NatStructs.\nFrom Fairness Require Import LPCM World.\nFrom Fairness Require Import Mod.\nRequire Import String Lia Program.\n\nSet Implicit Arguments.\n\nSection THREADS_RA_DEF.\n\n  Inductive threadsRA_car : Type :=\n  | global_local\n      (ths_ctx ths_usr : TIdSet.t)\n      (ths_ctx' ths_usr' : TIdSet.t)\n  | local (ths_ctx' ths_usr' : TIdSet.t)\n  | boom\n  .\n\n  Inductive threadsRA_wf : threadsRA_car -> Prop :=\n  | wf_global_local ths_ctx ths_usr ths_ctx' ths_usr'\n      (DISJOINT : NatMapP.Disjoint ths_ctx ths_usr)\n      (LE_CTX : KeySetLE ths_ctx' ths_ctx)\n      (LE_USR : KeySetLE ths_usr' ths_usr)\n    : threadsRA_wf (global_local ths_ctx ths_usr ths_ctx' ths_usr')\n  | wf_local ths_ctx' ths_usr'\n    : threadsRA_wf (local ths_ctx' ths_usr')\n  .\n\n  Definition add (r1 r2 : threadsRA_car) : threadsRA_car :=\n    match r1, r2 with\n    | global_local ths_ctx ths_usr ths_ctx' ths_usr', global_local _ _ _ _      => boom\n    | global_local ths_ctx ths_usr ths_ctx' ths_usr', local ths_ctx'' ths_usr'' =>\n        if (disjoint ths_ctx' ths_ctx'' && disjoint ths_usr' ths_usr'')%bool\n        then global_local ths_ctx ths_usr (NatMapP.update ths_ctx' ths_ctx'') (NatMapP.update ths_usr' ths_usr'')\n        else boom\n    | global_local ths_ctx ths_usr ths_ctx' ths_usr', boom                      => boom\n    | local ths_ctx' ths_usr', global_local ths_ctx ths_usr ths_ctx'' ths_usr'' =>\n        if (disjoint ths_ctx' ths_ctx'' && disjoint ths_usr' ths_usr'')%bool\n        then global_local ths_ctx ths_usr (NatMapP.update ths_ctx' ths_ctx'') (NatMapP.update ths_usr' ths_usr'')\n        else boom\n    | local ths_ctx' ths_usr', local ths_ctx'' ths_usr''                        =>\n        if (disjoint ths_ctx' ths_ctx'' && disjoint ths_usr' ths_usr'')%bool\n        then local (NatMapP.update ths_ctx' ths_ctx'') (NatMapP.update ths_usr' ths_usr'')\n        else boom\n    | local ths_ctx' ths_usr', boom                                             => boom\n    | boom, _                                                                   => boom\n    end.\n  Program Instance threadsRA: URA.t :=\n    {|\n      URA.car := threadsRA_car;\n      URA.unit := local NatSet.empty NatSet.empty;\n      URA._wf := threadsRA_wf;\n      URA._add := add;\n      URA.core := fun _ => local NatSet.empty NatSet.empty;\n    |}.\n  Next Obligation.\n    destruct a, b; ss.\n    all: rewrite disjoint_comm with (x := ths_ctx').\n    all: rewrite disjoint_comm with (x := ths_usr').\n    all: rewrite union_comm with (x := ths_ctx').\n    all: rewrite union_comm with (x := ths_usr').\n    all: ss.\n  Qed.\n  Next Obligation.\n    destruct a, b, c; try (ss; des_ifs; fail).\n    all: unfold add; des_ifs; try (rewrite 2 union_assoc; ss); solve_disjoint!.\n  Qed.\n  Next Obligation.\n    unseal \"ra\". destruct a; try easy.\n    all:\n      unfold add; des_ifs; try (do 2 rewrite union_comm, union_empty; ss);\n      unfold NatSet.empty in Heq; solve_disjoint!.\n  Qed.\n  Next Obligation.\n    unseal \"ra\". econs.\n  Qed.\n  Next Obligation.\n    unseal \"ra\". destruct a, b; inv H; unfold add; des_ifs; econs; ss.\n    - assert (KeySetLE ths_ctx' (NatMapP.update ths_ctx' ths_ctx'0)) by eapply union_KeySetLE.\n      unfold KeySetLE in *. auto.\n    - assert (KeySetLE ths_usr' (NatMapP.update ths_usr' ths_usr'0)) by eapply union_KeySetLE.\n      unfold KeySetLE in *. auto.\n  Qed.\n  Next Obligation.\n    unseal \"ra\". destruct a; ss.\n    - f_equal; rewrite union_comm; ss.\n    - f_equal; rewrite union_comm; ss.\n  Qed.\n  Next Obligation.\n    exists (local NatSet.empty NatSet.empty). unseal \"ra\". ss.\n  Qed.\n\nEnd THREADS_RA_DEF.\n\nSection THREADS_RA.\n\n  Definition global_th (ths_ctx ths_usr : TIdSet.t) : threadsRA := global_local ths_ctx ths_usr TIdSet.empty TIdSet.empty.\n\n  Definition local_th_context (tid: thread_id): threadsRA := local (TIdSet.add tid TIdSet.empty) TIdSet.empty.\n\n  Definition local_th_user (tid: thread_id): threadsRA := local TIdSet.empty (TIdSet.add tid TIdSet.empty).\n\n  Lemma local_th_context_in_context ths_ctx ths_usr tid r_ctx\n        (VALID: URA.wf (global_th ths_ctx ths_usr ⋅ local_th_context tid ⋅ r_ctx))\n    :\n    TIdSet.In tid ths_ctx.\n  Proof.\n    eapply URA.wf_mon in VALID. unfold URA.add, URA.wf in VALID. unseal \"ra\".\n    unfold global_th, local_th_context in *. ss.\n    inv VALID. eapply LE_CTX. (do 3 econs); ss.\n  Qed.\n\n  Lemma local_th_user_in_user ths_ctx ths_usr tid r_ctx\n        (VALID: URA.wf (global_th ths_ctx ths_usr ⋅ local_th_user tid ⋅ r_ctx))\n    :\n    TIdSet.In tid ths_usr.\n    eapply URA.wf_mon in VALID. unfold URA.add, URA.wf in VALID. unseal \"ra\".\n    inv VALID. eapply LE_USR. (do 3 econs); ss.\n  Qed.\n\n  Lemma initial_global_th_valid\n    :\n    URA.wf (global_th TIdSet.empty TIdSet.empty).\n  Proof.\n    unfold URA.wf. unseal \"ra\". econs; eauto using Disjoint_empty, KeySetLE_empty.\n  Qed.\n\n  Lemma global_th_alloc_context ths_ctx0 ths_usr r_ctx\n        tid ths_ctx1\n        (VALID: URA.wf (global_th ths_ctx0 ths_usr ⋅ r_ctx))\n        (ADD: TIdSet.add_new tid ths_ctx0 ths_ctx1)\n        (NONE: ~ TIdSet.In tid ths_usr)\n    :\n    URA.wf (global_th ths_ctx1 ths_usr ⋅ local_th_context tid ⋅ r_ctx).\n  Proof.\n    unfold URA.wf, URA.add in *. unseal \"ra\". destruct r_ctx; ss.\n    rewrite ! union_empty in *. unfold union, NatMap.fold; ss. inv VALID. inv ADD. des_ifs.\n    - econs; ss.\n      + ii. des. eapply NatMapP.F.add_in_iff in H. des.\n        * subst. eauto.\n        * eapply DISJOINT. eauto.\n      + ii. eapply NatMapP.F.add_in_iff. rewrite union_comm in H. eapply NatMapP.F.add_in_iff in H. des; eauto.\n    - eapply NatMapP.F.not_find_in_iff in NEW. solve_andb.\n      + eapply disjoint_false_iff' in H. des.\n        eapply NatMapP.F.add_in_iff in H. rewrite NatMapP.F.empty_in_iff in H.\n        des; ss; subst. firstorder.\n      + unfold TIdSet.empty in H. solve_disjoint.\n  Qed.\n\n  Lemma global_th_alloc_user ths_ctx ths_usr0 r_ctx\n        tid ths_usr1\n        (VALID: URA.wf (global_th ths_ctx ths_usr0 ⋅ r_ctx))\n        (ADD: TIdSet.add_new tid ths_usr0 ths_usr1)\n        (NONE: ~ TIdSet.In tid ths_ctx)\n    :\n    URA.wf (global_th ths_ctx ths_usr1 ⋅ local_th_user tid ⋅ r_ctx).\n  Proof.\n    unfold URA.wf, URA.add in *. unseal \"ra\". destruct r_ctx; ss.\n    rewrite ! union_empty in *. unfold union, NatMap.fold; ss. inv VALID. inv ADD. des_ifs.\n    - econs; ss.\n      + ii. des. eapply NatMapP.F.add_in_iff in H0. des.\n        * subst. eauto.\n        * eapply DISJOINT. eauto.\n      + ii. eapply NatMapP.F.add_in_iff. rewrite union_comm in H. eapply NatMapP.F.add_in_iff in H. des; eauto.\n    - eapply NatMapP.F.not_find_in_iff in NEW.\n      eapply disjoint_false_iff' in Heq. des.\n      eapply NatMapP.F.add_in_iff in Heq. rewrite NatMapP.F.empty_in_iff in Heq.\n      des; ss; subst. firstorder.\n  Qed.\n\n  Lemma global_th_dealloc_context ths_ctx0 ths_usr r_ctx\n        tid ths_ctx1\n        (VALID: URA.wf (global_th ths_ctx0 ths_usr ⋅ local_th_context tid ⋅ r_ctx))\n        (REMOVE: TIdSet.remove tid ths_ctx0 = ths_ctx1)\n    :\n    URA.wf (global_th ths_ctx1 ths_usr ⋅ URA.unit ⋅ r_ctx).\n\n  Proof.\n    rewrite URA.unit_id. unfold URA.wf, URA.add in *. unseal \"ra\". destruct r_ctx; ss.\n    rewrite ! union_empty in *. unfold union, NatMap.fold in VALID; ss. des_ifs; inv VALID.\n    econs; ss.\n    - ii. des. eapply NatMapP.F.remove_in_iff in H; des. firstorder.\n    - unfold TIdSet.empty, TIdSet.add in *. solve_andb; solve_disjoint.\n      ii. eapply NatMapP.F.remove_in_iff. assert (tid = k \\/ tid <> k) by lia; des.\n      + subst. tauto.\n      + unfold KeySetLE in LE_CTX. rewrite union_comm in LE_CTX. setoid_rewrite NatMapP.F.add_in_iff in LE_CTX. eauto.\n  Qed.\n\n  Lemma global_th_dealloc_user ths_ctx ths_usr0 r_ctx\n        tid ths_usr1\n        (VALID: URA.wf (global_th ths_ctx ths_usr0 ⋅ local_th_user tid ⋅ r_ctx))\n        (REMOVE: TIdSet.remove tid ths_usr0 = ths_usr1)\n    :\n    URA.wf (global_th ths_ctx ths_usr1 ⋅ URA.unit ⋅ r_ctx).\n  Proof.\n    rewrite URA.unit_id. unfold URA.wf, URA.add in *. unseal \"ra\". destruct r_ctx; ss.\n    rewrite ! union_empty in *. unfold union, NatMap.fold in VALID; ss. des_ifs; inv VALID.\n    unfold TIdSet.empty, TIdSet.add in *. solve_disjoint.\n    unfold KeySetLE in LE_USR. rewrite union_comm in LE_USR. setoid_rewrite NatMapP.F.add_in_iff in LE_USR.\n    econs; ss.\n    - ii. des. eapply NatMapP.F.remove_in_iff in H1. firstorder.\n    - ii. rewrite NatMapP.F.remove_in_iff. split.\n      + ii. subst. tauto.\n      + firstorder.\n  Qed.\n\nEnd THREADS_RA.\n", "meta": {"author": "damhiya", "repo": "fairness", "sha": "279dcc679bd18b85666b97d6b540d94299c5d66e", "save_path": "github-repos/coq/damhiya-fairness", "path": "github-repos/coq/damhiya-fairness/fairness-279dcc679bd18b85666b97d6b540d94299c5d66e/src/simulation/AddWorld.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.23462084057520918}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  Ifnot, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export stronger_continuity_rule.\n\nUnset Regular Subst Tactic.\n\nDefinition mk_nat2T {o} T : @NTerm o := mk_fun mk_tnat T.\nDefinition mk_natk2T {o} (t : @NTerm o) T : @NTerm o := mk_fun (mk_natk t) T.\n\nDefinition natk2T {o} (t T : @CTerm o) := mkc_fun (mkc_natk t) T.\nDefinition nat2T {o} (T : @CTerm o) := mkc_fun mkc_tnat T.\n\nDefinition mod_fun_type_v2 {o} (x : NVar) (T : @NTerm o) : NTerm :=\n  mk_function\n    mk_tnat\n    x\n    (mk_fun (mk_natk2T (mk_var x) T) mk_natU).\n\nLemma wf_term_mk_natk2T {o} :\n  forall (t T : @NTerm o),\n    wf_term (mk_natk2T t T) <=> (wf_term t # wf_term T).\nProof.\n  introv.\n  rw @wf_fun_iff.\n  rw @wf_term_mk_natk; sp.\nQed.\n\nLemma wf_term_mk_zero {o} :\n  @wf_term o mk_zero.\nProof.\n  introv.\n  unfold mk_zero.\n  eauto 3 with slow.\nQed.\nHint Resolve wf_term_mk_zero : slow.\n\nLemma wf_term_mk_tnat {o} :\n  @wf_term o mk_tnat.\nProof.\n  introv.\n  unfold mk_tnat.\n  apply wf_set; auto.\n  - apply wf_int.\n  - apply wf_le; dands; eauto 3 with slow.\nQed.\nHint Resolve wf_term_mk_tnat : slow.\n\nLemma wf_term_mk_nat2T {o} :\n  forall (T : @NTerm o),\n    wf_term (mk_nat2T T) <=> wf_term T.\nProof.\n  introv.\n  rw @wf_fun_iff.\n  split; intro k; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma wf_term_mk_natU {o} :\n  @wf_term o mk_natU.\nProof.\n  introv.\n  unfold mk_natU.\n  apply wf_bunion; dands; eauto 3 with slow.\nQed.\nHint Resolve wf_term_mk_natU.\n\nLemma wf_term_mod_fun_type_v2 {o} :\n  forall v (T : @NTerm o),\n    wf_term (mod_fun_type_v2 v T) <=> wf_term T.\nProof.\n  introv.\n  unfold mod_fun_type_v2.\n  rw <- @wf_function_iff.\n  rw @wf_fun_iff.\n  rw @wf_term_mk_natk2T.\n  split; intro k; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma cover_vars_upto_union {o} :\n  forall a b (s : @CSub o) vs,\n    cover_vars_upto (mk_union a b) s vs\n    <=> (cover_vars_upto a s vs # cover_vars_upto b s vs).\nProof.\n  introv.\n  unfold cover_vars_upto; simpl.\n  allrw remove_nvars_nil_l; allrw app_nil_r.\n  rw subvars_app_l; sp.\nQed.\n\nLemma cover_vars_upto_bool {o} :\n  forall (s : @CSub o) vs, cover_vars_upto mk_bool s vs.\nProof.\n  introv.\n  unfold mk_bool.\n  apply cover_vars_upto_union; dands; eauto 3 with slow.\nQed.\nHint Resolve cover_vars_upto_bool : slow.\n\nLemma cover_vars_upto_csub_filter_single_cons_disj {o} :\n  forall (t : @NTerm o) s v vs,\n    !LIn v (free_vars t)\n    -> (cover_vars_upto t (csub_filter s [v]) (v :: vs)\n        <=> cover_vars_upto t s vs).\nProof.\n  introv niv.\n  unfold cover_vars_upto; simpl.\n  rw @dom_csub_csub_filter.\n  allrw subvars_eq.\n  split; intros ss i x; applydup ss in x; allsimpl;\n  allrw in_app_iff; allrw in_remove_nvars; allsimpl;\n  allrw not_over_or; repndors; subst; tcsp.\n  right; right.\n  dands; tcsp.\n  intro xx; subst; tcsp.\nQed.\n\nLemma cover_vars_upto_bunion {o} :\n  forall a b (s : @CSub o) vs,\n    cover_vars_upto (mk_bunion a b) s vs\n    <=> (cover_vars_upto a s vs # cover_vars_upto b s vs).\nProof.\n  introv.\n  unfold mk_bunion.\n  rw @cover_vars_upto_tunion.\n  rw @cover_vars_upto_ite.\n  rw @cover_vars_upto_var.\n\n  pose proof (newvarlst_prop [a,b]) as p.\n  remember (newvarlst [a,b]) as v; clear Heqv.\n  allsimpl; allrw app_nil_r; allrw in_app_iff; allrw not_over_or; repnd.\n\n  rw (cover_vars_upto_csub_filter_single_cons_disj a s v vs p0).\n  rw (cover_vars_upto_csub_filter_single_cons_disj b s v vs p).\n\n  split; intro k; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma cover_vars_upto_int {o} :\n  forall (s : @CSub o) vs, cover_vars_upto mk_int s vs.\nProof.\n  introv.\n  unfold cover_vars_upto; simpl; auto.\nQed.\nHint Resolve cover_vars_upto_int : slow.\n\nLemma cover_vars_upto_tnat {o} :\n  forall (s : @CSub o) vs, cover_vars_upto mk_tnat s vs.\nProof.\n  introv.\n  unfold mk_tnat.\n  apply cover_vars_upto_set; dands; eauto 3 with slow.\n  apply cover_vars_upto_le; dands; eauto 3 with slow.\n  apply cover_vars_upto_var; simpl; tcsp.\nQed.\nHint Resolve cover_vars_upto_tnat : slow.\n\nLemma cover_vars_upto_natU {o} :\n  forall (s : @CSub o) vs, cover_vars_upto mk_natU s vs.\nProof.\n  introv.\n  unfold mk_natU.\n  apply cover_vars_upto_bunion; dands; eauto 3 with slow.\nQed.\nHint Resolve cover_vars_upto_natU : slow.\n\nLemma cover_vars_upto_natk {o} :\n  forall (t : @NTerm o) s vs,\n    cover_vars_upto (mk_natk t) s vs\n    <=> cover_vars_upto t s vs.\nProof.\n  introv.\n  unfold mk_natk, mk_natk_aux.\n  rw @cover_vars_upto_set.\n  rw @cover_vars_upto_prod.\n  rw @cover_vars_upto_le.\n  rw @cover_vars_upto_less_than.\n  rw @cover_vars_upto_var.\n\n  pose proof (newvar_prop t) as p.\n  remember (newvar t) as v; clear Heqv.\n\n  rw (cover_vars_upto_csub_filter_single_cons_disj t s v vs p).\n  simpl.\n\n  split; intro k; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma cover_vars_upto_natk2T {o} :\n  forall (t1 t2 : @NTerm o) s vs,\n    cover_vars_upto (mk_natk2T t1 t2) s vs\n    <=> (cover_vars_upto t1 s vs # cover_vars_upto t2 s vs).\nProof.\n  introv.\n  unfold mk_natk2T.\n  rw @cover_vars_upto_fun.\n  rw @cover_vars_upto_natk; sp.\nQed.\n\nLemma cover_vars_upto_nat2T {o} :\n  forall (t : @NTerm o) s vs,\n    cover_vars_upto (mk_nat2T t) s vs\n    <=> cover_vars_upto t s vs.\nProof.\n  introv.\n  unfold mk_nat2T.\n  rw @cover_vars_upto_fun.\n  split; introv k; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma cover_vars_nat2T {o} :\n  forall (t : @NTerm o) s,\n    cover_vars (mk_nat2T t) s\n    <=> cover_vars t s.\nProof.\n  introv.\n  allrw <- @cover_vars_upto_nil_iff.\n  apply cover_vars_upto_nat2T.\nQed.\n\nLemma cover_vars_mod_fun_type_v2 {o} :\n  forall v (T : @NTerm o) s,\n    !LIn v (free_vars T)\n    -> (cover_vars (mod_fun_type_v2 v T) s <=> cover_vars T s).\nProof.\n  introv niv; unfold mod_fun_type_v2.\n  rw @cover_vars_function.\n  rw @cover_vars_upto_fun.\n  rw @cover_vars_upto_natk2T.\n  rw @cover_vars_upto_var.\n  rw (cover_vars_upto_csub_filter_single_cons_disj T s v [] niv).\n  simpl.\n  split; intro k; repnd; dands; eauto 3 with slow.\nQed.\n\nDefinition modulus_fun_type_u_v2 {o} (T : @CTerm o) : CTerm :=\n  mkc_function\n    mkc_tnat\n    nvarx\n    (mkcv_fun\n       [nvarx]\n       (mkcv_fun [nvarx] (mkcv_natk [nvarx] (mkc_var nvarx)) (mk_cv [nvarx] T))\n       (mk_cv [nvarx] (mkc_bunion mkc_tnat mkc_unit))).\n\nLemma cl_lsubst_aux_cons_weak {o} :\n  forall (t : @NTerm o) sub v u,\n    cl_sub sub\n    -> closed u\n    -> !LIn v (free_vars t)\n    -> lsubst_aux t ((v, u) :: sub) = lsubst_aux t sub.\nProof.\n  nterm_ind t as [v|f|op bs ind] Case; introv cls clu ni; allsimpl; auto.\n\n  - Case \"vterm\".\n    boolvar; auto.\n    allrw not_over_or; repnd; tcsp.\n\n  - Case \"oterm\".\n    f_equal.\n    apply eq_maps; introv i.\n    destruct x as [l t]; simpl.\n    f_equal; simpl.\n    boolvar; tcsp.\n\n    eapply ind; eauto with slow.\n    intro j; destruct ni.\n    rw lin_flat_map; eexists; dands; eauto.\n    simpl.\n    rw in_remove_nvars; sp.\nQed.\n\nLemma lsubstc_mk_natk2T_sp1 {o} :\n  forall v T (t : @CTerm o) w s c w' c',\n    !LIn v (free_vars T) ->\n    alphaeqc\n      (lsubstc (mk_natk2T (mk_var v) T) w ((v,t) :: s) c)\n      (natk2T t (lsubstc T w' s c')).\nProof.\n  introv niv.\n  unfold alphaeqc; simpl.\n  unfold csubst.\n  repeat (rw @cl_lsubst_lsubst_aux; eauto 3 with slow).\n  simpl.\n  allrw @sub_filter_nil_r.\n  allrw @sub_find_sub_filter_trivial.\n  allrw @sub_find_sub_filter_trivial2.\n  allrw memvar_singleton.\n  repeat (rw @beq_var_newvar_trivial1; simpl; tcsp;[]).\n  allrw memvar_singleton.\n  repeat (rw @beq_var_newvar_trivial1; simpl; tcsp;[]).\n  allrw @sub_find_sub_filter_trivial.\n  allrw @sub_find_sub_filter_trivial2.\n  allrw <- beq_var_refl.\n  fold_terms.\n\n  destruct_cterms; allsimpl.\n  unfold mk_fun, mk_function, nobnd.\n  prove_alpha_eq4.\n\n  introv j.\n  repeat (destruct n; tcsp; try omega); clear j;[|].\n\n  { apply alphaeqbt_nilv2.\n\n    unfold mk_natk, mk_natk_aux, mk_set, nobnd.\n    prove_alpha_eq4;[].\n    introv j.\n    repeat (destruct n; tcsp; try omega); clear j;[].\n\n    pose proof (ex_fresh_var (newvar (mk_less_than (mk_var (newvar (@mk_var o v))) (@mk_var o v))\n                                     :: (newvar (mk_less_than (mk_var (newvar x)) x))\n                                     :: (all_vars\n                                           (@mk_product o\n                                                        (mk_function (mk_less_than (mk_var (newvar (@mk_var o v))) mk_zero)\n                                                                     (newvar (@mk_void o)) mk_void)\n                                                        (newvar (mk_less_than (mk_var (newvar (@mk_var o v))) (@mk_var o v)))\n                                                        (mk_less_than (mk_var (newvar (@mk_var o v))) x)) ++\n                                           all_vars\n                                           (mk_prod (mk_le mk_zero (mk_var (newvar x)))\n                                                    (mk_less_than (mk_var (newvar x)) x))))) as fv.\n    exrepnd.\n    rw @in_cons_iff in fv0.\n    rw @in_cons_iff in fv0.\n    rw not_over_or in fv0.\n    rw not_over_or in fv0.\n    repnd.\n\n    apply (al_bterm_aux [v0]); auto.\n\n    { apply disjoint_singleton_l; fold_terms; auto. }\n\n    simpl.\n    allrw @sub_filter_nil_r.\n    allrw memvar_singleton.\n    fold_terms.\n    repeat (rw @beq_var_newvar_trivial1; simpl; tcsp;[]).\n    allrw <- beq_var_refl.\n    repeat (rw (beq_var_newvar_trivial1 (newvar (@mk_var o v))\n                                        (mk_less_than (mk_var (newvar (@mk_var o v))) (@mk_var o v)));\n            simpl; tcsp;[]).\n    repeat (rw (beq_var_newvar_trivial1 (newvar x)\n                                        (mk_less_than (mk_var (newvar x)) x));\n            simpl; tcsp;[]).\n    allrw <- beq_var_refl.\n    allrw memvar_singleton; simpl.\n\n    repeat (rw (lsubst_aux_trivial_cl_term2 x); eauto 2 with slow;[]).\n\n    unfold mk_product, nobnd.\n    prove_alpha_eq4.\n    introv j.\n    repeat (destruct n; tcsp; try omega); clear j;[|].\n\n    { apply alphaeqbt_nilv2.\n\n      unfold mk_function, nobnd.\n      prove_alpha_eq4.\n      introv j.\n      repeat (destruct n; tcsp; try omega); clear j;[|].\n\n      { apply alphaeqbt_nilv2.\n        unfold mk_less, nobnd.\n        prove_alpha_eq4.\n        introv j.\n        repeat (destruct n; tcsp; try omega); clear j;[].\n\n        apply alphaeqbt_nilv2.\n        prove_alpha_eq4.\n        introv j.\n        repeat (destruct n; tcsp; try omega); clear j;[].\n\n        apply alphaeqbt_nilv2.\n        prove_alpha_eq4.\n        introv j.\n        repeat (destruct n; tcsp; try omega); clear j;[].\n\n        apply alphaeqbt_nilv2.\n        prove_alpha_eq4.\n        introv j.\n        repeat (destruct n; tcsp; try omega); clear j;[].\n\n        apply alpha_eq_bterm_congr.\n        repeat (boolvar; simpl); tcsp.\n      }\n\n      { apply alpha_eq_bterm_congr.\n        prove_alpha_eq4.\n        introv j.\n        repeat (destruct n; tcsp; try omega); clear j;[].\n\n        apply alpha_eq_bterm_congr.\n        prove_alpha_eq4.\n        introv j.\n        repeat (destruct n; tcsp; try omega); clear j;[].\n\n        apply alpha_eq_bterm_congr.\n        prove_alpha_eq4.\n        introv j.\n        repeat (destruct n; tcsp; try omega); clear j;[].\n\n        apply alpha_eq_bterm_congr.\n        repeat (boolvar; simpl); tcsp.\n      }\n    }\n\n    { pose proof (ex_fresh_var ((newvar (mk_less_than (mk_var (newvar (@mk_var o v))) (@mk_var o v)))\n                                :: (newvar (mk_less_than (mk_var (newvar x)) x))\n                                :: (all_vars\n                                      (mk_less (mk_var v0) x\n                                               mk_true\n                                               (mk_approx mk_axiom\n                                                          (mk_fix\n                                                             (mk_lam nvarx\n                                                                     match\n                                                                       sub_find\n                                                                         (if beq_var (newvar (@mk_var o v)) nvarx\n                                                                          then []\n                                                                          else [(newvar (@mk_var o v), mk_var v0)]) nvarx\n                                                                     with\n                                                                       | Some t => t\n                                                                       | None => mk_var nvarx\n                                                                     end)))) ++\n                                      all_vars\n                                      (mk_less (mk_var v0) x mk_true\n                                               (mk_approx mk_axiom\n                                                          (mk_fix\n                                                             (mk_lam nvarx\n                                                                     match\n                                                                       sub_find\n                                                                         (if beq_var (newvar x) nvarx\n                                                                          then []\n                                                                          else [(newvar x, mk_var v0)]) nvarx\n                                                                     with\n                                                                       | Some t => t\n                                                                       | None => mk_var nvarx\n                                                                     end))))))) as fv.\n      exrepnd.\n      rw @in_cons_iff in fv3.\n      rw @in_cons_iff in fv3.\n      rw not_over_or in fv3.\n      rw not_over_or in fv3.\n      repnd.\n\n      apply (al_bterm_aux [v1]); auto.\n\n      { apply disjoint_singleton_l; fold_terms; auto. }\n\n      simpl.\n      fold_terms.\n      repeat (rw not_eq_beq_var_false;tcsp;[]).\n      repeat (rw (not_eq_beq_var_false (newvar (mk_less_than (mk_var (newvar x)) x))); tcsp;[]).\n\n      repeat (rw (lsubst_aux_trivial_cl_term2 x); eauto 2 with slow;[]).\n\n      unfold mk_less, nobnd.\n      prove_alpha_eq4.\n      introv j.\n      repeat (destruct n; tcsp; try omega); clear j;[].\n\n      apply alpha_eq_bterm_congr.\n      prove_alpha_eq4.\n      introv j.\n      repeat (destruct n; tcsp; try omega); clear j;[].\n\n      apply alpha_eq_bterm_congr.\n      prove_alpha_eq4.\n      introv j.\n      repeat (destruct n; tcsp; try omega); clear j;[].\n\n      apply alpha_eq_bterm_congr.\n      prove_alpha_eq4.\n      introv j.\n      repeat (destruct n; tcsp; try omega); clear j;[].\n\n      apply alpha_eq_bterm_congr.\n      repeat (boolvar; subst; simpl; tcsp);\n        try (complete (rw not_over_or in Heqb; tcsp));\n        try (complete (rw not_over_or in Heqb0; tcsp)).\n    }\n  }\n\n  { boolvar.\n\n    { pose proof (ex_fresh_var (all_vars (lsubst_aux T (sub_filter (csub2sub s) [newvar T])) ++\n       all_vars (csubst T s))) as fvs; exrepnd.\n      apply (al_bterm_aux [v]); simpl; auto.\n      { apply disjoint_singleton_l.\n        allrw in_app_iff; sp. }\n\n      rw @lsubst_aux_sub_filter;[|apply disjoint_singleton_r;apply newvar_prop].\n\n      rw (lsubst_aux_trivial_cl_term (lsubst_aux T (csub2sub s)));\n        [|simpl;rw @free_vars_lsubst_aux_cl; eauto 2 with slow;\n          apply disjoint_singleton_r;\n          rw in_remove_nvars; intro k; repnd;\n          apply newvar_prop in k0; sp].\n\n      rw (lsubst_aux_trivial_cl_term (csubst T s));\n        [|simpl; apply disjoint_singleton_r;\n          apply newvar_prop].\n\n      unfold csubst.\n      unflsubst.\n    }\n\n    { pose proof (ex_fresh_var (all_vars (lsubst_aux T ((v,x) :: sub_filter (csub2sub s) [newvar T])) ++\n       all_vars (csubst T s))) as fvs; exrepnd.\n      apply (al_bterm_aux [v0]); simpl; auto.\n      { apply disjoint_singleton_l.\n        allrw in_app_iff; sp; allrw not_over_or; sp. }\n\n      rw @cl_lsubst_aux_cons_weak; eauto 3 with slow.\n\n      rw @lsubst_aux_sub_filter;[|apply disjoint_singleton_r;apply newvar_prop].\n\n      rw (lsubst_aux_trivial_cl_term (lsubst_aux T (csub2sub s)));\n        [|simpl;rw @free_vars_lsubst_aux_cl; eauto 2 with slow;\n          apply disjoint_singleton_r;\n          rw in_remove_nvars; intro k; repnd;\n          apply newvar_prop in k0; sp].\n\n      rw (lsubst_aux_trivial_cl_term (csubst T s));\n        [|simpl; apply disjoint_singleton_r;\n          apply newvar_prop].\n\n      unfold csubst.\n      unflsubst.\n    }\n  }\nQed.\n\nLemma lsubstc_mod_fun_type_v2_aux {o} :\n  forall v T w (s : @CSub o) c w' c',\n    !LIn v (free_vars T) ->\n    alphaeqc\n      (lsubstc (mod_fun_type_v2 v T) w s c)\n      (modulus_fun_type_u_v2 (lsubstc T w' s c')).\nProof.\n  introv niv.\n\n  unfold mod_fun_type_v2.\n  lsubst_tac.\n  allrw @lsubstc_mkc_tnat.\n  unfold modulus_fun_type_u_v2.\n\n  apply implies_alphaeqc_mkc_function; eauto 2 with slow.\n  introv.\n  repeat substc_lsubstc_vars3.\n  eapply alphaeqc_trans;[|apply alphaeqc_sym;apply substc_mkcv_fun].\n\n  match goal with\n    | [ |- context[lsubstc (mk_fun ?a ?b) ?w ?s ?c] ] =>\n      pose proof (lsubstc_mk_fun_ex a b s w c) as h;\n        exrepnd; clear_irr\n  end.\n  eapply alphaeqc_trans;[exact h1|]; clear h1.\n\n  apply alphaeqc_mkc_fun.\n\n  - eapply alphaeqc_trans;[|apply alphaeqc_sym;apply substc_mkcv_fun].\n    eapply alphaeqc_trans;\n      [|apply alphaeqc_sym;apply alphaeqc_mkc_fun;\n        [apply mkcv_natk_substc\n        |apply alphaeqc_refl]\n      ].\n    rw @mkc_var_substc.\n    rw @csubst_mk_cv.\n\n    eapply alphaeqc_trans;[apply lsubstc_mk_natk2T_sp1; eauto|].\n    apply alphaeqc_refl.\n\n  - eapply alphaeqc_trans;[apply lsubstc_mk_natU|].\n    rw @csubst_mk_cv; eauto 3 with slow.\nQed.\n\nLemma lsubstc_mod_fun_type_v2 {o} :\n  forall v T w (s : @CSub o) c,\n    !LIn v (free_vars T) ->\n    {w' : wf_term T\n     & {c' : cover_vars T s\n     &  alphaeqc\n          (lsubstc (mod_fun_type_v2 v T) w s c)\n          (modulus_fun_type_u_v2 (lsubstc T w' s c')) }}.\nProof.\n  introv niv.\n\n  dup w as w'.\n  apply @wf_term_mod_fun_type_v2 in w'.\n\n  dup c as c'.\n  apply (cover_vars_mod_fun_type_v2 v T s niv) in c'.\n\n  exists w' c'.\n\n  apply lsubstc_mod_fun_type_v2_aux; auto.\nQed.\n\nLemma lsubstc_mk_nat2T_sp1 {o} :\n  forall (T : @NTerm o) w s c w' c',\n    alphaeqc\n      (lsubstc (mk_nat2T T) w s c)\n      (nat2T (lsubstc T w' s c')).\nProof.\n  introv.\n  unfold alphaeqc; simpl.\n  unfold csubst.\n  repeat (rw @cl_lsubst_lsubst_aux; eauto 3 with slow).\n  simpl.\n  allrw @sub_filter_nil_r.\n  allrw @sub_find_sub_filter_trivial.\n  allrw @sub_find_sub_filter_trivial2.\n  allrw memvar_singleton.\n  repeat (rw @beq_var_newvar_trivial1; simpl; tcsp;[]).\n  allrw memvar_singleton.\n  repeat (rw @beq_var_newvar_trivial1; simpl; tcsp;[]).\n  allrw @sub_find_sub_filter_trivial.\n  allrw @sub_find_sub_filter_trivial2.\n  allrw <- beq_var_refl.\n  fold_terms.\n\n  destruct_cterms; allsimpl.\n  unfold mk_fun, mk_function, nobnd.\n  repeat prove_alpha_eq4.\n\n  pose proof (ex_fresh_var (all_vars (lsubst_aux T (sub_filter (csub2sub s) [newvar T])) ++\n                                     all_vars (lsubst_aux T (csub2sub s)))) as fvs; exrepnd.\n  apply (al_bterm_aux [v]); simpl; auto.\n  { apply disjoint_singleton_l.\n    allrw in_app_iff; sp; allrw not_over_or; sp. }\n\n  rw @lsubst_aux_sub_filter;[|apply disjoint_singleton_r;apply newvar_prop].\n\n  rw (lsubst_aux_trivial_cl_term (lsubst_aux T (csub2sub s)));\n    [|simpl;rw @free_vars_lsubst_aux_cl; eauto 2 with slow;\n      apply disjoint_singleton_r;\n      rw in_remove_nvars; intro k; repnd;\n      apply newvar_prop in k0; sp].\n\n  rw (lsubst_aux_trivial_cl_term (lsubst_aux T (csub2sub s)));\n    [|simpl; apply disjoint_singleton_r;\n      apply newvar_prop].\n  auto.\nQed.\n\nLemma tequality_modulus_fun_type_u_v2 {o} :\n  forall (lib : @library o) T1 T2,\n    tequality lib (modulus_fun_type_u_v2 T1) (modulus_fun_type_u_v2 T2)\n    <=> tequality lib T1 T2.\nProof.\n  introv.\n  unfold modulus_fun_type_u_v2.\n  rw @tequality_function.\n\n  split; intro k; repnd; dands; eauto 3 with slow;\n  try (apply type_tnat).\n\n  - pose proof (k (mkc_nat 1) (mkc_nat 1)) as h; clear k.\n    autodimp h hyp; eauto 3 with slow.\n    eapply tequality_respects_alphaeqc_left in h;[|apply substc_mkcv_fun].\n    eapply tequality_respects_alphaeqc_right in h;[|apply substc_mkcv_fun].\n    allrw @csubst_mk_cv.\n    apply tequality_fun in h; repnd; clear h.\n    eapply tequality_respects_alphaeqc_left in h0;[|apply substc_mkcv_fun].\n    eapply tequality_respects_alphaeqc_right in h0;[|apply substc_mkcv_fun].\n    apply tequality_fun in h0; repnd; clear h1.\n    allrw @csubst_mk_cv.\n    autodimp h0 hyp.\n    eapply inhabited_type_respects_alphaeqc;\n      [apply alphaeqc_sym; apply mkcv_natk_substc|].\n    allrw @mkc_var_substc.\n    exists (@mkc_zero o).\n    apply equality_in_natk.\n    exists 0 (Z.of_nat 1).\n    rw @mkc_zero_eq.\n    dands; spcast; try (apply computes_to_valc_refl; eauto 3 with slow).\n    apply Znat.inj_lt; auto.\n\n  - introv e.\n    eapply tequality_respects_alphaeqc_left;[apply alphaeqc_sym;apply substc_mkcv_fun|].\n    eapply tequality_respects_alphaeqc_right;[apply alphaeqc_sym;apply substc_mkcv_fun|].\n\n    apply tequality_fun.\n    dands.\n\n    + eapply tequality_respects_alphaeqc_left;[apply alphaeqc_sym;apply substc_mkcv_fun|].\n      eapply tequality_respects_alphaeqc_right;[apply alphaeqc_sym;apply substc_mkcv_fun|].\n      allrw @mkcv_tnat_substc.\n\n      apply tequality_fun.\n      dands.\n\n      * eapply tequality_respects_alphaeqc_left;[apply alphaeqc_sym;apply mkcv_natk_substc|].\n        eapply tequality_respects_alphaeqc_right;[apply alphaeqc_sym;apply mkcv_natk_substc|].\n        allrw @mkc_var_substc.\n\n        apply equality_in_tnat in e.\n        unfold equality_of_nat in e; exrepnd; spcast.\n        apply tequality_mkc_natk.\n        allrw @mkc_nat_eq.\n        exists (Z.of_nat k0) (Z.of_nat k0); dands; spcast; auto.\n        introv i.\n        destruct (Z_lt_le_dec k1 (Z.of_nat k0)); tcsp.\n\n      * introv inh.\n        allrw @csubst_mk_cv; auto.\n\n    + introv inh.\n      allrw @csubst_mk_cv.\n      apply tequality_bunion; dands.\n      * apply type_tnat.\n      * apply type_mkc_unit.\nQed.\n\nLemma tequality_nat2T {o} :\n  forall (lib : @library o) T1 T2,\n    tequality lib (nat2T T1) (nat2T T2)\n    <=> tequality lib T1 T2.\nProof.\n  introv.\n  unfold nat2T.\n  rw @tequality_fun.\n\n  split; intro k; repnd; dands; eauto 3 with slow;\n  try (apply type_tnat).\n\n  autodimp k hyp; eauto 3 with slow.\n  exists (@mkc_nat o 0); unfold member; eauto 3 with slow.\nQed.\n\nLemma inhabited_type_tnat {o} :\n  forall (lib : @library o), inhabited_type lib mkc_tnat.\nProof.\n  introv.\n  exists (@mkc_nat o 0).\n  unfold member; eauto 3 with slow.\nQed.\nHint Resolve inhabited_type_tnat : slow.\n\nLemma equality_nat2T_to_natk2T {o} :\n  forall lib (n f g : @CTerm o) T,\n    member lib n mkc_tnat\n    -> equality lib f g (nat2T T)\n    -> equality lib f g (natk2T n T).\nProof.\n  introv m e.\n\n  allrw @equality_in_tnat.\n  allunfold @equality_of_nat; exrepnd; spcast; GC.\n\n  allrw @equality_in_fun; repnd; dands; eauto 3 with slow.\n  { apply type_mkc_natk.\n    exists (Z.of_nat k); spcast; auto. }\n\n  introv en.\n  apply equality_natk_to_tnat in en; apply e in en; auto.\nQed.\n\nLemma equality_in_natk2T_implies_equality_bound {o} :\n  forall lib (f g : @CTerm o) k T,\n    type lib T\n    -> value_type lib T\n    -> equality lib f g (natk2T (mkc_nat k) T)\n    -> forall a x,\n         equality lib\n                  (bound_c (mkc_utoken a) (mkc_nat k) f x)\n                  (bound_c (mkc_utoken a) (mkc_nat k) g x)\n                  (nat2TE a T).\nProof.\n  introv tT vT equ; introv.\n  unfold nat2TE.\n\n  apply equality_in_fun.\n  dands; eauto 3 with slow.\n  { introv inh; apply tequality_TE; auto. }\n  introv i.\n\n  (* beta reduce *)\n  eapply equality_respects_cequivc_left;\n    [apply cequivc_sym;apply cequivc_apply_bound_c|].\n  eapply equality_respects_cequivc_right;\n    [apply cequivc_sym;apply cequivc_apply_bound_c|].\n  allrw @boundl_c_eq.\n\n  (* let's get rid of [a0] and [a'] *)\n  rw @equality_in_tnat in i.\n  unfold equality_of_nat in i; exrepnd; spcast.\n  eapply equality_respects_cequivc_left;\n    [apply cequivc_sym;apply cequivc_mkc_less;\n     [apply computes_to_valc_implies_cequivc;exact i1\n     |apply cequivc_refl\n     |apply implies_cequivc_apply;\n       [apply cequivc_refl|apply computes_to_valc_implies_cequivc;exact i1]\n     |apply cequivc_refl]\n    |].\n  eapply equality_respects_cequivc_right;\n    [apply cequivc_sym;apply cequivc_mkc_less;\n     [apply computes_to_valc_implies_cequivc;exact i0\n     |apply cequivc_refl\n     |apply implies_cequivc_apply;\n       [apply cequivc_refl|apply computes_to_valc_implies_cequivc;exact i0]\n     |apply cequivc_refl]\n    |].\n  clear dependent a0.\n  clear dependent a'.\n\n  allrw @mkc_nat_eq.\n  eapply equality_respects_cequivc_left;\n    [apply cequivc_sym; apply cequivc_mkc_less_int|].\n  eapply equality_respects_cequivc_right;\n    [apply cequivc_sym; apply cequivc_mkc_less_int|].\n  allrw <- @mkc_nat_eq.\n\n  boolvar.\n\n  - assert (k0 < k) as ltk by omega.\n    unfold natk2T in equ.\n    apply equality_in_fun in equ; repnd.\n    clear equ0 equ1.\n    pose proof (equ (mkc_nat k0) (mkc_nat k0)) as h; clear equ.\n    autodimp h hyp.\n    { apply equality_in_natk.\n      exists k0 (Z.of_nat k); dands; spcast; tcsp; allrw <- @mkc_nat_eq;\n      apply computes_to_valc_refl; eauto 2 with slow. }\n    allrw @equality_in_tnat.\n    apply equality_in_TE; tcsp.\n\n  - apply equality_in_TE;auto.\n    right.\n    fold (spexc a); dands; spcast; eauto with slow.\nQed.\n\nLemma ccequivc_as_approx {o} :\n  forall lib (t1 t2 : @CTerm o),\n    ccequivc lib t1 t2 <=> (capproxc lib t1 t2 # capproxc lib t2 t1).\nProof.\n  introv; split; intro k; dands; repnd; spcast; auto.\n  - destruct k; auto.\n  - destruct k; auto.\n  - split; auto.\nQed.\n\nLemma reduces_in_atmost_k_steps_exc_impossible2 {o} :\n  forall lib v a k1 k2 (t : @NTerm o),\n    iscan v\n    -> reduces_in_atmost_k_steps_exc lib t (spexc a) k1\n    -> reduces_in_atmost_k_steps_exc lib t v k2\n    -> False.\nProof.\n  induction k1; introv isc r1 r2.\n\n  - allrw @reduces_in_atmost_k_steps_exc_0; subst.\n    apply reduces_in_atmost_k_steps_exc_done in r2; eauto 3 with slow; ginv.\n    subst; allsimpl; tcsp.\n\n  - allrw @reduces_in_atmost_k_steps_exc_S;\n    repndors; exrepnd; subst; repndors; exrepnd; subst; allsimpl.\n\n    + destruct k2.\n\n      * allrw @reduces_in_atmost_k_steps_exc_0; ginv.\n\n      * allrw @reduces_in_atmost_k_steps_exc_S;\n        repndors; exrepnd; subst; repndors; exrepnd; subst; allsimpl; tcsp;\n        eauto 3 with slow; ginv.\n\n        { rw r7 in r4; ginv.\n          eapply IHk1 in r1; eauto. }\n\n        { apply isvalue_like_implies_not_isnoncan_like in r0; sp. }\n\n    + destruct k2.\n\n      * allrw @reduces_in_atmost_k_steps_exc_0; ginv.\n\n      * allrw @reduces_in_atmost_k_steps_exc_S;\n        repndors; exrepnd; subst; repndors; exrepnd; subst; allsimpl; tcsp;\n        eauto 3 with slow; ginv.\n\n        { apply isvalue_like_implies_not_isnoncan_like in r6; sp. }\n\n        { rw r7 in r4; ginv.\n          eapply IHk1 in r1; eauto. }\n\n    + destruct k2.\n\n      * allrw @reduces_in_atmost_k_steps_exc_0; ginv; subst; allsimpl; tcsp; GC.\n        apply iscan_implies in isc; repndors; exrepnd; subst;\n        csunf r1; allsimpl; ginv;\n        apply reduces_in_atmost_k_steps_exc_iscan in r3; subst; tcsp; ginv.\n\n      * allrw @reduces_in_atmost_k_steps_exc_S;\n        repndors; exrepnd; subst; repndors; exrepnd; subst; allsimpl; tcsp;\n        eauto 3 with slow; ginv.\n        rw r1 in r2; ginv.\n        eapply IHk1 in r3; eauto.\nQed.\n\nLemma reduces_in_atmost_k_steps_excc_impossible2 {o} :\n  forall lib v a k1 k2 (t : @CTerm o),\n    iscanc v\n    -> reduces_in_atmost_k_steps_excc lib t (spexcc a) k1\n    -> reduces_in_atmost_k_steps_excc lib t v k2\n    -> False.\nProof.\n  introv isc r1 r2; destruct_cterms.\n  allunfold @reduces_in_atmost_k_steps_excc; allsimpl.\n  eapply (reduces_in_atmost_k_steps_exc_impossible2 lib x0) in r1; eauto.\nQed.\n\nLemma member_in_TE_implies {o} :\n  forall lib (t : @CTerm o) a T,\n    value_type lib T\n    -> member lib t (TE a T)\n    -> hasvaluec lib t [+] cequivc lib t (spexcc a).\nProof.\n  introv vT equ.\n\n  applydup @inhabited_implies_tequality in equ as tT.\n  apply tequality_TE in tT.\n\n  apply equality_in_TE in equ; auto.\n\n  assert {k : nat\n          , {v : CTerm , reduces_ksteps_excc lib t v k # iscanc v}\n            {+} reduces_ksteps_excc lib t (spexcc a) k } as j.\n  { repndors.\n\n    - apply vT in equ.\n      apply hasvaluec_computes_to_valc_implies in equ; exrepnd.\n      rw @computes_to_valc_iff_reduces_in_atmost_k_stepsc in equ0; exrepnd.\n      exists k; left.\n      exists b.\n      dands; eauto 3 with slow; spcast.\n      apply reduces_in_atmost_k_steps_excc_can; eauto 3 with slow.\n\n    - repnd; spcast.\n      clear equ0.\n      apply cequivc_spexcc in equ.\n      exrepnd.\n      allrw @computes_to_valc_iff_reduces_in_atmost_k_stepsc; exrepnd.\n      allrw @computes_to_excc_iff_reduces_in_atmost_k_stepsc; exrepnd.\n\n      exists (k1 + k + k0).\n      right; dands; spcast.\n\n      apply (reduces_in_atmost_k_steps_excc_le_exc _ (k1 + k + k0));\n        eauto 3 with slow; tcsp;\n        try (apply Nat.le_max_l; auto).\n      pose proof (reduces_in_atmost_k_steps_excc_exception\n                    lib k k0 n e (mkc_utoken a) mkc_axiom) as h.\n      repeat (autodimp h hyp); tcsp; exrepnd.\n      pose proof (reduces_in_atmost_k_steps_excc_trans2\n                    lib k1 i\n                    t\n                    (mkc_exception n e)\n                    (mkc_exception (mkc_utoken a) mkc_axiom)) as q.\n      repeat (autodimp q hyp); exrepnd.\n      apply (reduces_in_atmost_k_steps_excc_le_exc _ i0); tcsp; try omega.\n  }\n\n  apply (constructive_indefinite_ground_description nat (fun x => x) (fun x => x))\n    in j; auto.\n\n  { exrepnd.\n    pose proof (dec_reduces_ksteps_excc lib x t (spexcc a)) as q.\n    autodimp q hyp; simpl; try (fold (spexc a)); eauto 3 with slow.\n\n    destruct q as [q|q];[right|left].\n\n    { apply reduces_ksteps_excc_spexcc_decompose in q.\n      exrepnd.\n      allunfold @reduces_in_atmost_k_stepsc; allsimpl.\n      allrw @get_cterm_apply; allsimpl.\n      allrw @get_cterm_mkc_exception; allsimpl.\n      dands;\n        apply cequiv_spexc_if;\n        try (apply isprog_apply);\n        try (apply isprog_mk_nat);\n        eauto 3 with slow.\n      exists (get_cterm a') (get_cterm e'); dands; eauto 3 with slow.\n      unfold computes_to_exception; exists k1; auto. }\n\n    { pose proof (dec_ex_reduces_in_atmost_k_steps_excc lib x t) as h.\n      clear equ.\n      destruct h as [h|h].\n      - exrepnd.\n        destruct (dec_iscanc v) as [i|i].\n        + apply (computes_to_valc_implies_hasvaluec lib t v).\n          apply computes_to_valc_iff_reduces_in_atmost_k_stepsc.\n          dands; eauto 3 with slow.\n          exists x.\n          apply reduces_in_atmost_k_steps_excc_can_implies; auto.\n        + provefalse.\n          destruct j0 as [j0|j0]; exrepnd; spcast.\n          * destruct_cterms.\n            allunfold @reduces_in_atmost_k_steps_excc; allsimpl.\n            allunfold @reduces_in_atmost_k_steps_exc.\n            rw j0 in h0; ginv.\n          * destruct q; spcast; auto.\n      - provefalse; repndors; exrepnd; spcast.\n        + destruct h.\n          exists v; auto.\n        + destruct q; auto; spcast; auto.\n    }\n  }\n\n  { clear j; introv.\n\n    pose proof (dec_ex_reduces_in_atmost_k_steps_excc lib x t) as h.\n    pose proof (dec_reduces_ksteps_excc lib x t (spexcc a)) as q.\n    autodimp q hyp; simpl; try (fold (spexc a)); eauto 3 with slow.\n\n    clear equ.\n\n    destruct h as [h|h];\n      destruct q as [q|q];\n      exrepnd;\n      try (destruct (deq_nat n0 n) as [d|d]); subst;\n      tcsp;\n      try (complete (eapply reduces_ksteps_excc_impossible1 in h0; eauto; tcsp));\n      try (complete (eapply reduces_ksteps_excc_impossible1 in j0; eauto; tcsp));\n      try (complete (provefalse; repndors; repnd; tcsp));\n      try (complete (right; intro xx; exrepnd; repndors; repnd; tcsp;\n                     try (complete (destruct h; eexists; eauto));\n                     try (complete (destruct j; eexists; eauto))));\n      try (complete (left; exists n; left; tcsp));\n      try (complete (left; exists 0; right; tcsp)).\n\n    - destruct (dec_iscanc v) as [i|i].\n\n      + left; left.\n        exists v; dands; auto.\n        spcast; auto.\n\n      + right.\n        introv r; repndors; exrepnd; spcast; tcsp.\n\n        * destruct_cterms.\n          allunfold @reduces_in_atmost_k_steps_excc; allsimpl.\n          allunfold @reduces_in_atmost_k_steps_exc.\n          rw r1 in h0; ginv.\n\n        * destruct q; spcast; auto.\n\n    - right.\n      introv r; repndors; exrepnd; spcast; tcsp.\n\n      * destruct h; exists v; auto.\n\n      * destruct q; spcast; auto.\n  }\nQed.\n\nLemma reduces_in_atmost_k_steps_exc_eq {o} :\n  forall lib (t : @NTerm o) v1 v2 k,\n    reduces_in_atmost_k_steps_exc lib t v1 k\n    -> reduces_in_atmost_k_steps_exc lib t v2 k\n    -> v1 = v2.\nProof.\n  introv r1 r2.\n  allunfold @reduces_in_atmost_k_steps_exc.\n  rw r1 in r2; ginv.\nQed.\n\nLemma cequivc_bound_nat_c_sp_bound_nat_c_v2 {o} :\n  forall lib a (f : @CTerm o) x e z T,\n    e <> x\n    -> value_type lib T\n    -> member lib f (nat2TE a T)\n    -> cequivc\n         lib\n         (bound_nat_c a x e z f)\n         (sp_bound_nat_c x z f).\nProof.\n  introv d1 vT mem.\n\n  applydup @inhabited_implies_tequality in mem as tT.\n  apply tequality_fun in tT; repnd.\n  clear tT0.\n  autodimp tT hyp; eauto 3 with slow.\n  apply tequality_TE in tT.\n\n  unfold bound_nat_c, sp_bound_nat_c.\n\n  apply cequivc_lam; introv.\n  allrw @mkcv_cbv_substc_same.\n  allrw @mkcv_cont1_dup1.\n  allrw @mkcv_less_substc.\n  allrw @substc_mkcv_zero.\n  allrw @mkcv_apply_substc.\n  allrw @csubst_mk_cv.\n  allrw @mkc_var_substc.\n  allrw @mkcv_vbot_substc.\n\n  apply approxc_implies_cequivc; apply approxc_assume_hasvalue; intro hv.\n\n  - apply @hasvalue_likec_cbv in hv.\n    apply @hasvalue_likec_implies_or in hv.\n    repndors.\n\n    + apply hasvaluec_computes_to_valc_implies in hv; exrepnd.\n      eapply cequivc_approxc_trans;\n        [apply simpl_cequivc_mkc_cbv;\n          apply computes_to_valc_implies_cequivc;\n          exact hv0|].\n      eapply approxc_cequivc_trans;\n        [|apply cequivc_mkc_less;\n           [apply cequivc_sym\n           |apply cequivc_refl\n           |apply cequivc_refl\n           |apply cequivc_refl];\n           apply computes_to_valc_implies_cequivc;\n           exact hv0\n        ].\n      rw @computes_to_valc_iff_reduces_toc in hv0; repnd.\n      eapply cequivc_approxc_trans;\n        [apply cequivc_mkc_cbv;complete auto|].\n\n      allrw @mkcv_less_substc.\n      rw @mkcv_try_substc; try (complete (intro xx; ginv)).\n      allrw @mkcv_apply_substc.\n      allrw @substc_mkcv_zero.\n      allrw @mkc_var_substc.\n      allrw @mkcv_vbot_substc.\n      allrw @csubst_mk_cv.\n      allrw @mkcv_utoken_substc.\n      unfold spexccv; rw @substc2_mk_cv; fold (spexccv [nvare] a).\n\n      apply approxc_assume_hasvalue; intro hv.\n\n      apply hasvalue_likec_less in hv; repndors; exrepnd.\n\n      * eapply cequivc_approxc_trans;\n        [apply cequivc_mkc_less;\n          [apply reduces_toc_implies_cequivc;exact hv2\n          |apply cequivc_refl\n          |apply cequivc_refl\n          |apply cequivc_refl]\n        |].\n        eapply approxc_cequivc_trans;\n          [|apply cequivc_sym;\n             apply cequivc_mkc_less;\n             [apply reduces_toc_implies_cequivc;exact hv2\n             |apply cequivc_refl\n             |apply cequivc_refl\n             |apply cequivc_refl]\n          ].\n        rw @mkc_zero_eq.\n        rw @mkc_nat_eq.\n        eapply cequivc_approxc_trans;\n          [apply cequivc_mkc_less_int|].\n        eapply approxc_cequivc_trans;\n          [|apply cequivc_sym;apply cequivc_mkc_less_int].\n\n        clear hv3.\n\n        boolvar; eauto 3 with slow; try (apply approxc_refl).\n\n        pose proof (Wf_Z.Z_of_nat_complete_inf i1) as q.\n        autodimp q hyp;[]; exrepnd; subst.\n        rw <- @mkc_nat_eq in hv2.\n\n        eapply cequivc_approxc_trans;\n          [apply simpl_cequivc_mkc_try;\n            [apply implies_cequivc_apply;\n              [apply cequivc_refl\n              |apply reduces_toc_implies_cequivc;exact hv2]\n            |apply cequivc_refl]\n          |].\n\n        eapply approxc_cequivc_trans;\n          [|apply cequivc_sym;\n             apply implies_cequivc_apply;\n             [apply cequivc_refl\n             |apply reduces_toc_implies_cequivc;\n               eapply reduces_toc_trans;\n               [exact hv1|exact hv2]\n             ]\n          ].\n\n        apply equality_in_fun in mem; repnd.\n        clear mem0 mem1.\n        pose proof (mem (mkc_nat n) (mkc_nat n)) as h.\n        autodimp h hyp; eauto 3 with slow.\n        allrw @member_eq.\n\n        applydup @member_in_TE_implies in h; auto; repndors;[|].\n\n        { apply hasvaluec_computes_to_valc_implies in h0; exrepnd.\n          eapply cequivc_approxc_trans;\n            [apply computes_to_valc_implies_cequivc;\n              eapply computes_to_valc_mkc_try;\n              [exact h1|apply computes_to_pkc_refl;apply mkc_utoken_eq_pk2termc]\n            |].\n          apply computes_to_valc_implies_approxc in h1; sp. }\n\n        { repnd; GC.\n          eapply approxc_cequivc_trans;\n            [|apply cequivc_sym;exact h0].\n\n          eapply cequivc_approxc_trans;\n            [apply simpl_cequivc_mkc_try;\n              [exact h0\n              |apply cequivc_refl]\n            |].\n          unfold spexcc.\n          eapply cequivc_approxc_trans;\n            [apply reduces_toc_implies_cequivc;\n              apply reduces_toc_mkc_try_exc\n            |].\n          unfold spexccv; rw @csubst_mk_cv.\n          apply approxc_refl. }\n\n      * assert (computes_to_excc lib a0 b e0) as comp.\n        { allrw @computes_to_excc_iff_reduces_toc.\n          eapply reduces_toc_trans;[exact hv2|].\n          apply reduces_toc_refl. }\n        clear hv1 hv2.\n\n        allrw @computes_to_excc_iff_reduces_toc.\n\n        eapply cequivc_approxc_trans;\n        [apply cequivc_mkc_less;\n          [apply reduces_toc_implies_cequivc;exact comp\n          |apply cequivc_refl\n          |apply cequivc_refl\n          |apply cequivc_refl]\n        |].\n        eapply approxc_cequivc_trans;\n          [|apply cequivc_sym;\n             apply cequivc_mkc_less;\n             [apply reduces_toc_implies_cequivc;exact comp\n             |apply cequivc_refl\n             |apply cequivc_refl\n             |apply cequivc_refl]\n          ].\n\n        eapply cequivc_approxc_trans;\n          [apply cequivc_mkc_less_exc|].\n        eapply approxc_cequivc_trans;\n          [|apply cequivc_sym; apply cequivc_mkc_less_exc].\n        apply approxc_refl.\n\n      * apply (computes_to_valc_and_excc_false _ _ _ mkc_zero) in hv4; tcsp.\n        apply computes_to_valc_refl; eauto 3 with slow.\n\n    + allrw @raises_exceptionc_as_computes_to_excc; exrepnd.\n      allrw @computes_to_excc_iff_reduces_toc.\n\n      eapply cequivc_approxc_trans;\n        [apply simpl_cequivc_mkc_cbv;\n          apply reduces_toc_implies_cequivc;\n          exact hv1|].\n      eapply approxc_cequivc_trans;\n        [|apply cequivc_mkc_less;\n           [apply cequivc_sym\n           |apply cequivc_refl\n           |apply cequivc_refl\n           |apply cequivc_refl];\n           apply reduces_toc_implies_cequivc;\n           exact hv1\n        ].\n      eapply approxc_cequivc_trans;\n        [|apply cequivc_sym; apply cequivc_mkc_less_exc].\n      eapply cequivc_approxc_trans;\n        [apply cequivc_mkc_cbv_exc|].\n      apply approxc_refl.\n\n  - apply hasvalue_likec_less in hv.\n    repndors; exrepnd.\n\n    + eapply cequivc_approxc_trans;\n      [apply cequivc_mkc_less;\n        [apply reduces_toc_implies_cequivc;exact hv0\n        |apply cequivc_refl\n        |apply cequivc_refl\n        |apply cequivc_refl]\n      |].\n      eapply approxc_cequivc_trans;\n        [|apply cequivc_sym;\n           apply simpl_cequivc_mkc_cbv;\n           apply reduces_toc_implies_cequivc;exact hv0\n        ].\n      rw @mkc_zero_eq.\n      rw @mkc_nat_eq.\n      eapply cequivc_approxc_trans;\n        [apply cequivc_mkc_less_int|].\n      eapply approxc_cequivc_trans;\n        [|apply cequivc_sym; apply cequivc_mkc_cbv]; eauto 3 with slow;[].\n\n      allrw @mkcv_less_substc.\n      rw @mkcv_try_substc; try (complete (intro xx; ginv)).\n      allrw @mkcv_apply_substc.\n      allrw @substc_mkcv_zero.\n      allrw @mkc_var_substc.\n      allrw @mkcv_vbot_substc.\n      allrw @csubst_mk_cv.\n      allrw @mkcv_utoken_substc.\n      unfold spexccv; rw @substc2_mk_cv; fold (spexccv [nvare] a).\n      rw @mkc_zero_eq.\n      rw @mkc_nat_eq.\n      eapply approxc_cequivc_trans;\n        [|apply cequivc_sym; apply cequivc_mkc_less_int].\n\n      clear hv1.\n\n      boolvar; eauto 3 with slow; try (apply approxc_refl).\n\n      pose proof (Wf_Z.Z_of_nat_complete_inf i1) as q.\n      autodimp q hyp;[]; exrepnd; subst.\n      allrw <- @mkc_nat_eq.\n\n      eapply cequivc_approxc_trans;\n        [apply implies_cequivc_apply;\n          [apply cequivc_refl\n          |apply reduces_toc_implies_cequivc;exact hv0]\n        |].\n\n      apply equality_in_fun in mem; repnd.\n      clear mem0 mem1.\n      pose proof (mem (mkc_nat n) (mkc_nat n)) as h.\n      autodimp h hyp; eauto 3 with slow.\n\n      applydup @member_in_TE_implies in h; auto; repndors;[|].\n\n      { apply hasvaluec_computes_to_valc_implies in h0; exrepnd.\n        eapply approxc_cequivc_trans;\n          [|apply cequivc_sym;\n             apply computes_to_valc_implies_cequivc;\n             eapply computes_to_valc_mkc_try;\n             [exact h1|apply computes_to_pkc_refl;apply mkc_utoken_eq_pk2termc]\n          ].\n        apply computes_to_valc_implies_approxc in h1; sp. }\n\n      { repnd; GC.\n        eapply cequivc_approxc_trans;[exact h0|].\n\n        eapply approxc_cequivc_trans;\n          [|apply cequivc_sym;\n             apply simpl_cequivc_mkc_try;\n             [exact h0\n             |apply cequivc_refl]\n          ].\n        unfold spexcc.\n        eapply approxc_cequivc_trans;\n          [|apply cequivc_sym;\n             apply reduces_toc_implies_cequivc;\n             apply reduces_toc_mkc_try_exc\n          ].\n        unfold spexccv; rw @csubst_mk_cv.\n        apply approxc_refl. }\n\n    + clear hv1.\n\n      allrw @computes_to_excc_iff_reduces_toc.\n\n      eapply cequivc_approxc_trans;\n        [apply cequivc_mkc_less;\n          [apply reduces_toc_implies_cequivc;exact hv0\n          |apply cequivc_refl\n          |apply cequivc_refl\n          |apply cequivc_refl]\n        |].\n      eapply cequivc_approxc_trans;\n        [apply cequivc_mkc_less_exc|].\n\n      eapply approxc_cequivc_trans;\n        [|apply cequivc_sym;\n           apply simpl_cequivc_mkc_cbv;\n           apply reduces_toc_implies_cequivc;exact hv0\n        ].\n      eapply approxc_cequivc_trans;\n        [|apply cequivc_sym;\n           apply cequivc_mkc_cbv_exc\n        ].\n      apply approxc_refl.\n\n    + apply (computes_to_valc_and_excc_false _ _ _ mkc_zero) in hv2; tcsp.\n      apply computes_to_valc_refl; eauto 3 with slow.\nQed.\n\nDefinition bound_nat_try_c_v2 {o} (a : get_patom_set o) x e z (f : @CTerm o) t :=\n  mkc_lam x (mkcv_cbv [x]\n                      (mkc_var x)\n                      x\n                      (mkcv_dup1\n                         x\n                         (mkcv_less [x]\n                                    (mkc_var x)\n                                    (mkcv_zero [x])\n                                    (mkcv_vbot [x] z)\n                                    (mkcv_try [x]\n                                              (mkcv_apply [x] (mk_cv [x] f) (mkc_var x))\n                                              (mkcv_utoken [x] a)\n                                              e\n                                              (mk_cv [e,x] t))))).\n\nLemma implies_equal_bound_nat_try_aux_c_v2 {o} :\n  forall lib a x e z (f g : @CTerm o) T t,\n    e <> x\n    -> value_type lib T\n    -> member lib t T\n    -> equality lib f g (nat2TE a T)\n    -> equality lib (bound_nat_try_c_v2 a x e z f t) (bound_nat_try_c_v2 a x e z g t) (nat2T T).\nProof.\n  introv d vT mtT equ.\n  unfold nat2T.\n  unfold nat2TE in equ.\n  allrw @equality_in_fun; repnd.\n  autodimp equ1 hyp.\n  { apply inhabited_type_tnat. }\n  apply tequality_TE in equ1.\n  dands; tcsp.\n\n  introv en.\n  unfold bound_nat_try_c.\n  eapply equality_respects_cequivc_left;\n    [apply cequivc_sym;apply cequivc_beta|].\n  eapply equality_respects_cequivc_right;\n    [apply cequivc_sym;apply cequivc_beta|].\n\n  repeat (rw @mkcv_cbv_substc_same).\n  repeat (rw @mkc_var_substc).\n  allrw @mkcv_cont1_dup1.\n\n  apply equality_in_tnat in en.\n  unfold equality_of_nat in en; exrepnd; spcast.\n  pose proof (equ (mkc_nat k) (mkc_nat k)) as eqn.\n  autodimp eqn hyp.\n  { apply equality_in_tnat; unfold equality_of_nat.\n    exists k; dands; spcast; apply computes_to_valc_refl;\n    eauto 3 with slow. }\n\n  eapply equality_respects_cequivc_left;\n    [apply simpl_cequivc_mkc_cbv;\n      apply cequivc_sym;\n      apply computes_to_valc_implies_cequivc;\n      exact en1|].\n  eapply equality_respects_cequivc_right;\n    [apply simpl_cequivc_mkc_cbv;\n      apply cequivc_sym;\n      apply computes_to_valc_implies_cequivc;\n      exact en0|].\n\n  eapply equality_respects_cequivc_left;\n    [apply cequivc_sym;apply cequivc_mkc_cbv|]; eauto 3 with slow.\n  eapply equality_respects_cequivc_right;\n    [apply cequivc_sym;apply cequivc_mkc_cbv|]; eauto 3 with slow.\n\n  repeat (rw @mkcv_less_substc).\n  repeat (rw @mkcv_try_substc; auto).\n  repeat (rw @mkcv_apply_substc).\n  repeat (rw @csubst_mk_cv).\n  repeat (rw @mkc_var_substc).\n  repeat (rw @mkcv_utoken_substc).\n  repeat (rw @mkcv_vbot_substc).\n  repeat (rw @mkcv_zero_substc).\n  unfold mkcv_zero.\n  repeat (rw @substc2_mk_cv).\n  fold (@mkcv_zero o [e]).\n\n  allrw @mkc_zero_eq.\n  eapply equality_respects_cequivc_left;\n    [apply cequivc_sym;apply cequivc_mkc_less_nat|].\n  eapply equality_respects_cequivc_right;\n    [apply cequivc_sym;apply cequivc_mkc_less_nat|].\n  boolvar; tcsp;[].\n\n  apply @equality_in_TE in eqn; auto.\n  repndors.\n\n  - pose proof (vT (mkc_apply f (mkc_nat k))) as hv1.\n    pose proof (vT (mkc_apply g (mkc_nat k))) as hv2.\n    autodimp hv1 hyp.\n    { apply equality_refl in eqn; auto. }\n    autodimp hv2 hyp.\n    { apply equality_sym in eqn; apply equality_refl in eqn; auto. }\n    allapply @hasvaluec_computes_to_valc_implies; exrepnd.\n    eapply equality_respects_cequivc_left;\n      [apply cequivc_sym;\n        apply computes_to_valc_implies_cequivc;\n        eapply computes_to_valc_mkc_try;\n        [exact hv2|apply computes_to_pkc_refl;apply mkc_utoken_eq_pk2termc]\n      |].\n    eapply equality_respects_cequivc_right;\n      [apply cequivc_sym;\n        apply computes_to_valc_implies_cequivc;\n        eapply computes_to_valc_mkc_try;\n        [exact hv0|apply computes_to_pkc_refl;apply mkc_utoken_eq_pk2termc]\n      |].\n    eapply equality_respects_cequivc_left;\n      [apply computes_to_valc_implies_cequivc;exact hv2|].\n    eapply equality_respects_cequivc_right;\n      [apply computes_to_valc_implies_cequivc;exact hv0|].\n    auto.\n\n  - repnd; spcast.\n    eapply equality_respects_cequivc_left;\n      [apply cequivc_sym;\n        apply simpl_cequivc_mkc_try;[exact eqn0|apply cequivc_refl]\n      |].\n    eapply equality_respects_cequivc_right;\n      [apply cequivc_sym;\n        apply simpl_cequivc_mkc_try;[exact eqn|apply cequivc_refl]\n      |].\n\n    eapply equality_respects_cequivc_left;\n      [apply cequivc_sym;\n        apply reduces_toc_implies_cequivc;\n        apply reduces_toc_mkc_try_exc\n      |].\n    eapply equality_respects_cequivc_right;\n      [apply cequivc_sym;\n        apply reduces_toc_implies_cequivc;\n        apply reduces_toc_mkc_try_exc\n      |].\n    allrw @csubst_mk_cv; auto.\nQed.\n\nDefinition bound_nat_try_v2 {o} (a : get_patom_set o) x e z (f : @NTerm o) t :=\n  mk_lam x (bound_nat_try_aux a (mk_var x) x e z f t).\n\nLemma wf_bound_nat_try_v2 {o} :\n  forall a x e z (f : @NTerm o) t,\n    wf_term f\n    -> wf_term t\n    -> wf_term (bound_nat_try_v2 a x e z f t).\nProof.\n  introv wf wt.\n  apply wf_lam.\n  apply wf_bound_nat_try_aux; eauto 3 with slow.\nQed.\nHint Resolve wf_bound_nat_try_v2 : slow.\n\nLemma differ_try_compute_to_valc_nat_v2 {o} :\n  forall lib a (F f g : @CTerm o) k x e z t T,\n    !LIn a (getc_utokens F)\n    -> eq_value_type_na lib a T\n    -> equality lib f g (nat2TE a T)\n    -> computes_to_valc\n         lib\n         (mkc_apply F (bound_nat_try_c_v2 a x e z f t))\n         (mkc_nat k)\n    -> {v1 : CTerm\n        & {v2 : CTerm\n        & reduces_toc lib (mkc_apply F (bound_nat_c a x e z f)) v1\n        # reduces_toc lib (mkc_apply F (bound_nat_c a x e z g)) v2\n        # ((v1 = mkc_nat k # v2 = mkc_nat k)\n           [+] (cequivc lib v1 (spexcc a) # cequivc lib v2 (spexcc a)))}}.\nProof.\n  introv nia vT equ comp.\n  apply equality_in_nat2TE_implies in equ; auto.\n  destruct_cterms.\n  unfold computes_to_valc in comp; unfold reduces_toc; allsimpl.\n  unfold getc_utokens in nia; allsimpl.\n  unfold cequivc; simpl; try (fold (spexc a)).\n\n  fold (@mk_vbot o z) in comp.\n  fold (bound_nat_try_aux a (mk_var x) x e z x3 x1) in comp.\n  fold (bound_nat_try_v2 a x e z x3 x1) in comp.\n\n  fold (@mk_vbot o z).\n  fold (spexc a).\n  fold (bound_nat_aux a (mk_var x) x e z x3).\n  fold (bound_nat_aux a (mk_var x) x e z x2).\n  fold (bound_nat a x e z x3).\n  fold (bound_nat a x e z x2).\n\n  unfold computes_to_value, reduces_to in comp; exrepnd.\n\n  pose proof (differ_try_reduces_in_atmost_k_steps_aux\n                lib a x3 x2 x1 k0\n                (mk_apply x4 (bound_nat_try_v2 a x e z x3 x1))\n                (mk_apply x4 (bound_nat a x e z x3))\n                (mk_apply x4 (bound_nat a x e z x2))\n                (mk_nat k)) as h.\n  repeat (autodimp h hyp); eauto 3 with slow.\n  { apply wf_apply; eauto 4 with slow. }\n  { apply wf_apply; eauto 3 with slow. }\n  { apply wf_apply; eauto 3 with slow. }\n  { apply differ_try_oterm; simpl; tcsp.\n    introv xx; repndors; tcsp; ginv.\n    - constructor; apply differ_try_refl; auto.\n    - constructor.\n      apply differ_try_oterm; simpl; tcsp.\n      introv xx; repndors; tcsp; ginv.\n      constructor.\n      apply differ_try_base; auto. }\n\n  exrepnd.\n  apply differ_try_alpha_nat in h1; repndors; exrepnd; subst.\n\n  - exists (@mkc_nat o k) (@mkc_nat o k); simpl; dands; auto.\n\n  - applydup @reduces_to_preserves_isprog in h0;\n    [|apply isprog_apply; complete (eauto 3 with slow)].\n    applydup @reduces_to_preserves_isprog in h2;\n    [|apply isprog_apply; complete (eauto 3 with slow)].\n\n    exists (exist _ t2' h3) (exist _ t3' h4); simpl.\n    unfold spfexc_pair in h1; exrepnd; subst.\n    dands; auto.\n    right; dands; tcsp; apply cequiv_spfexc.\nQed.\n\nLemma apply_nat2natE_aux_v2 {o} :\n  forall lib t T (F : @CTerm o) f g a x e z,\n    e <> x\n    -> !LIn a (getc_utokens F)\n    -> member lib t T\n    -> eq_value_type_na lib a T\n    -> member lib F (mkc_fun (nat2T T) mkc_tnat)\n    -> equality lib f g (nat2TE a T)\n    -> equality\n         lib\n         (mkc_apply F (bound_nat_c a x e z f))\n         (mkc_apply F (bound_nat_c a x e z g))\n         (natE a).\nProof.\n  introv d nia mtT vT mem equ.\n  rw @equality_in_fun in mem; repnd.\n  clear mem0 mem1.\n\n  applydup (implies_equal_bound_nat_try_aux_c_v2 lib a x e z f g T t)\n    in equ as eqtry;\n    eauto 3 with slow;\n    try (complete (intro k; ginv)).\n  applydup mem in eqtry as eqn.\n  allrw @equality_in_tnat; allunfold @equality_of_nat; exrepnd; spcast.\n\n  pose proof (differ_try_compute_to_valc_nat_v2 lib a F f g k x e z t T) as h.\n  repeat (autodimp h hyp); exrepnd.\n\n  apply equality_in_natE; repndors; repnd; subst.\n  - left.\n    unfold equality_of_nat; exists k; dands; spcast;\n    apply computes_to_valc_iff_reduces_toc; dands; auto.\n  - right; dands; spcast;\n    eapply cequivc_trans;[|exact h3|idtac|exact h1];[|];\n    apply reduces_toc_implies_cequivc; auto.\nQed.\n\nLemma apply_nat2TE_aux2_v2 {o} :\n  forall lib (F : @CTerm o) f g a x z t T,\n    !LIn a (getc_utokens F)\n    -> eq_value_type_na lib a T\n    -> member lib t T\n    -> member lib F (mkc_fun (nat2T T) mkc_tnat)\n    -> equality lib f g (nat2TE a T)\n    -> equality\n         lib\n         (mkc_apply F (sp_bound_nat_c x z f))\n         (mkc_apply F (sp_bound_nat_c x z g))\n         (natE a).\nProof.\n  introv nia vT mT mem equ.\n  pose proof (ex_fresh_var [x]) as fv.\n  exrepnd; allsimpl; allrw not_over_or; repnd; GC.\n\n  applydup @inhabited_implies_tequality in mem as tT.\n  apply tequality_fun in tT; repnd.\n  clear tT.\n  rw @tequality_nat2T in tT0.\n\n  eapply equality_respects_cequivc_left;\n    [apply implies_cequivc_apply;\n      [apply cequivc_refl\n      |apply (cequivc_bound_nat_c_sp_bound_nat_c_v2 _ a _ x v z T);tcsp;\n       apply equality_refl in equ;auto\n      ]\n    |]; eauto 3 with slow.\n  eapply equality_respects_cequivc_right;\n    [apply implies_cequivc_apply;\n      [apply cequivc_refl\n      |apply (cequivc_bound_nat_c_sp_bound_nat_c_v2 _ a _ x v z T);tcsp;\n       apply equality_sym in equ; apply equality_refl in equ;auto\n      ]\n    |]; eauto 3 with slow.\n  apply (apply_nat2natE_aux_v2 lib t T); auto.\nQed.\n\nDefinition no_utokens_t {o} (t : @NTerm o) :=\n  get_utokens t = [].\n\nDefinition no_utokens_tc {o} (t : @CTerm o) :=\n  getc_utokens t = [].\n\nDefinition compute_to_eqvals_nut {o} lib (t1 t2 : @CTerm o) :=\n  {v : CTerm\n   & computes_to_valc lib t1 v\n   # computes_to_valc lib t2 v\n   # noconstc v\n   # noseqc v\n   # no_utokens_tc v }.\n\nDefinition eq_value_type_nut {o} lib (T : @CTerm o) :=\n  forall t1 t2,\n    equality lib t1 t2 T\n    -> compute_to_eqvals_nut lib t1 t2.\n\nLemma eq_value_type_nut_implies_na {o} :\n  forall lib (T : @CTerm o),\n    eq_value_type_nut lib T -> forall a, eq_value_type_na lib a T.\nProof.\n  introv eqv equ.\n  apply eqv in equ.\n  unfold compute_to_eqvals_nut in equ; exrepnd.\n  exists v; dands; auto.\n  rw equ0; simpl; tcsp.\nQed.\nHint Resolve eq_value_type_nut_implies_na : slow.\n\nLemma eq_value_type_nut_implies_value_type {o} :\n  forall lib (T : @CTerm o),\n    eq_value_type_nut lib T -> value_type lib T.\nProof.\n  introv eqv equ.\n  apply eqv in equ.\n  unfold compute_to_eqvals_nut in equ; exrepnd.\n  eapply computes_to_valc_implies_hasvaluec; eauto.\nQed.\nHint Resolve eq_value_type_nut_implies_na : slow.\n\nLemma spM_in_modulus_fun_type_u_v2 {o} :\n  forall lib (F : @CTerm o) t T,\n    member lib t T\n    -> eq_value_type_nut lib T (* so that T is disjoint from exceptions *)\n    -> member lib F (mkc_fun (nat2T T) mkc_tnat)\n    -> member lib (spM_c F) (modulus_fun_type_u_v2 T).\nProof.\n  introv mt vTnut mF.\n\n  applydup @eq_value_type_nut_implies_value_type in vTnut as vT.\n\n  applydup @inhabited_implies_tequality in mF as tT.\n  apply tequality_fun in tT; repnd.\n  clear tT.\n  rw @tequality_nat2T in tT0.\n  rename tT0 into tT.\n\n  unfold modulus_fun_type_u_v2.\n  apply equality_in_function2.\n  fold (@modulus_fun_type_u_v2 o T).\n  dands; try (apply tequality_modulus_fun_type_u_v2; auto).\n  introv e.\n  rename a into n.\n  rename a' into m.\n  eapply alphaeqc_preserving_equality;[|apply alphaeqc_sym;apply substc_mkcv_fun].\n  allrw @csubst_mk_cv.\n  apply equality_in_fun.\n  dands.\n\n  - eapply type_respects_alphaeqc;[apply alphaeqc_sym;apply substc_mkcv_fun|].\n    allrw @mkcv_tnat_substc.\n    apply type_mkc_fun.\n    dands.\n    + eapply type_respects_alphaeqc;[apply alphaeqc_sym;apply mkcv_natk_substc|].\n      rw @mkc_var_substc.\n      apply equality_in_tnat in e.\n      unfold equality_of_nat in e; exrepnd; spcast.\n      apply type_mkc_natk.\n      allrw @mkc_nat_eq.\n      exists (Z.of_nat k); spcast; auto.\n    + introv inh.\n      allrw @csubst_mk_cv; auto.\n\n  - introv inh.\n      apply tequality_bunion; dands.\n      * apply type_tnat.\n      * apply type_mkc_unit.\n\n  - introv e1.\n    allrw <- @mkc_apply2_eq.\n    rename a into f.\n    rename a' into g.\n    eapply alphaeqc_preserving_equality in e1;[|apply substc_mkcv_fun].\n    eapply alphaeqc_preserving_equality in e1;\n      [|apply alphaeqc_mkc_fun;[apply mkcv_natk_substc|apply alphaeqc_refl] ].\n    allrw @mkcv_tnat_substc.\n    allrw @mkc_var_substc.\n    allrw @csubst_mk_cv; auto.\n\n    apply equality_in_tnat in e.\n    unfold equality_of_nat in e; exrepnd; spcast.\n\n    (* let's get rid of [n] and [m] now *)\n    eapply cequivc_preserving_equality in e1;\n      [|apply cequivc_mkc_fun;[|apply cequivc_refl];\n        apply cequivc_mkc_natk;\n        apply computes_to_valc_implies_cequivc; exact e2].\n\n    fold (@natk2T o (mkc_nat k) T) in e1.\n\n    eapply equality_respects_cequivc_left;\n      [apply implies_cequivc_apply2;[apply cequivc_refl|idtac|apply cequivc_refl];\n       apply cequivc_sym; apply computes_to_valc_implies_cequivc; exact e2|].\n\n    eapply equality_respects_cequivc_right;\n      [apply implies_cequivc_apply2;[apply cequivc_refl|idtac|apply cequivc_refl];\n       apply cequivc_sym; apply computes_to_valc_implies_cequivc; exact e0|].\n\n    clear dependent n.\n    clear dependent m.\n\n    (* let's beta-reduce *)\n    eapply equality_respects_cequivc_left;\n      [apply cequivc_sym; apply cequivc_apply2_spM_c|].\n    eapply equality_respects_cequivc_right;\n      [apply cequivc_sym; apply cequivc_apply2_spM_c|].\n\n    (* now let's apply bound to [f] and [g] *)\n    pose proof (equality_in_natk2T_implies_equality_bound lib f g k T tT vT e1) as h.\n    allrw @test_c_eq.\n\n    destruct (fresh_atom o (getc_utokens F ++ getc_utokens f ++ getc_utokens g)) as [a nia].\n    allrw in_app_iff; allrw not_over_or; repnd.\n\n    (* let's get rid of fresh in the conclusion *)\n    assert (equality\n              lib\n              (substc (mkc_utoken a) nvare (test_try2_cv F nvarc nvarx nvarz nvare (mkc_nat k) f))\n              (substc (mkc_utoken a) nvare (test_try2_cv F nvarc nvarx nvarz nvare (mkc_nat k) g))\n              (mkc_bunion mkc_tnat mkc_unit)) as equ;\n      [|pose proof (cequivc_fresh_subst2 lib nvare (test_try2_cv F nvarc nvarx nvarz nvare (mkc_nat k) f) a) as h1;\n         repeat (autodimp h1 hyp);\n         [ destruct_cterms; allsimpl;\n           allunfold @getcv_utokens; allunfold @getc_utokens; allsimpl; allrw app_nil_r;\n           allrw in_app_iff; tcsp\n         | apply equality_refl in equ; apply member_bunion_nat_unit_implies_cis_spcan_not_atom; auto\n         |];\n         pose proof (cequivc_fresh_subst2 lib nvare (test_try2_cv F nvarc nvarx nvarz nvare (mkc_nat k) g) a) as h2;\n         repeat (autodimp h2 hyp);\n         [ destruct_cterms; allsimpl;\n           allunfold @getcv_utokens; allunfold @getc_utokens; allsimpl; allrw app_nil_r;\n           allrw in_app_iff; tcsp\n         | apply equality_sym in equ; apply equality_refl in equ; apply member_bunion_nat_unit_implies_cis_spcan_not_atom; auto\n         |];\n         spcast;\n         eapply equality_respects_cequivc_left;[apply cequivc_sym;exact h1|];\n         eapply equality_respects_cequivc_right;[apply cequivc_sym;exact h2|];\n         complete auto\n      ].\n\n    repeat (rw @substc_test_try2_cv).\n\n    pose proof (h a nvarx) as q.\n    clear h.\n\n    (* This is where we use vTnut *)\n    pose proof (apply_nat2TE_aux2_v2\n                  lib F\n                  (bound_c (mkc_utoken a) (mkc_nat k) f nvarx)\n                  (bound_c (mkc_utoken a) (mkc_nat k) g nvarx)\n                  a nvarx nvarz\n                  t T) as ee.\n    repeat (autodimp ee hyp); try (complete (intro xx; ginv)); eauto 3 with slow;[].\n    clear q.\n\n    eapply equality_respects_cequivc_left in ee;\n      [|apply implies_cequivc_apply;\n         [apply cequivc_refl\n         |apply cequiv_sp_bound_nat_c_bound_c]\n      ].\n\n    eapply equality_respects_cequivc_right in ee;\n      [|apply implies_cequivc_apply;\n         [apply cequivc_refl\n         |apply cequiv_sp_bound_nat_c_bound_c]\n      ].\n\n    apply equality_in_natE_implies in ee; repndors.\n\n    { unfold equality_of_nat_tt in ee; exrepnd.\n      eapply equality_respects_cequivc_left;\n        [apply cequivc_sym;\n          apply computes_to_valc_implies_cequivc;\n          eapply computes_to_valc_mkc_try;\n          [exact ee1|apply computes_to_pkc_refl;apply mkc_utoken_eq_pk2termc]\n        |].\n      eapply equality_respects_cequivc_right;\n        [apply cequivc_sym;\n          apply computes_to_valc_implies_cequivc;\n          eapply computes_to_valc_mkc_try;\n          [exact ee0|apply computes_to_pkc_refl;apply mkc_utoken_eq_pk2termc]\n        |].\n      apply equality_in_disjoint_bunion; eauto 3 with slow.\n      dands; eauto 3 with slow. }\n\n    { repnd.\n      eapply equality_respects_cequivc_left;\n        [apply cequivc_sym;\n          apply simpl_cequivc_mkc_try;\n          [exact ee0|apply cequivc_refl]\n        |].\n      eapply equality_respects_cequivc_right;\n        [apply cequivc_sym;\n          apply simpl_cequivc_mkc_try;\n          [exact ee|apply cequivc_refl]\n        |].\n\n      eapply equality_respects_cequivc_left;\n        [apply cequivc_sym;\n          apply reduces_toc_implies_cequivc;\n          apply reduces_toc_mkc_try_exc\n        |].\n      eapply equality_respects_cequivc_right;\n        [apply cequivc_sym;\n          apply reduces_toc_implies_cequivc;\n          apply reduces_toc_mkc_try_exc\n        |].\n\n      allrw @substc_mkcv_axiom.\n      apply equality_in_disjoint_bunion; eauto 3 with slow.\n      dands; eauto 3 with slow.\n      right.\n      apply equality_in_unit; dands; spcast; apply computes_to_valc_refl; eauto 3 with slow. }\nQed.\n\nLemma equality_lam_force_nat_c_in_nat2nat_v2 {o} :\n  forall lib x z (f : @CTerm o) T,\n    member lib f (nat2T T)\n    -> equality lib f (lam_force_nat_c x z f) (nat2T T).\nProof.\n  introv mem.\n\n  applydup @inhabited_implies_tequality in mem as teq.\n  apply tequality_fun in teq; repnd.\n  clear teq0.\n  autodimp teq hyp; eauto 2 with slow.\n\n  apply equality_in_fun; dands; eauto 3 with slow.\n  introv equ.\n  apply equality_in_tnat in equ.\n  unfold equality_of_nat in equ; exrepnd; spcast.\n\n  eapply equality_respects_cequivc_left;\n    [apply cequivc_sym;\n      apply implies_cequivc_apply;\n      [apply cequivc_refl\n      |apply computes_to_valc_implies_cequivc;exact equ1]\n    |].\n\n  eapply equality_respects_cequivc_right;\n    [apply cequivc_sym;apply cequivc_mkc_apply_lam_force_nat_c|].\n\n  unfold force_nat_c.\n  eapply equality_respects_cequivc_right;\n    [apply cequivc_sym;apply simpl_cequivc_mkc_cbv;\n     apply computes_to_valc_implies_cequivc;exact equ0|].\n  eapply equality_respects_cequivc_right;\n    [apply cequivc_sym;apply cequivc_mkc_cbv|]; eauto 3 with slow;[].\n  rw @mkcv_less_substc.\n  rw @substc_mkcv_zero.\n  rw @mkcv_vbot_substc.\n  rw @mkcv_apply_substc.\n  rw @csubst_mk_cv.\n  rw @mkc_var_substc.\n\n  rw @mkc_zero_eq.\n\n  eapply equality_respects_cequivc_right;\n    [apply cequivc_sym;apply cequivc_mkc_less_nat|].\n  boolvar; tcsp.\n\n  allrw @equality_in_fun; repnd.\n  clear mem1 mem0.\n  apply mem; eauto 3 with slow.\nQed.\n\nLemma spM_cond_v2 {o} :\n  forall lib (F f : @CTerm o) T,\n    member lib F (mkc_fun (nat2T T) mkc_tnat)\n    -> member lib f (nat2T T)\n    -> {n : nat\n        & equality lib\n                   (mkc_apply2 (spM_c F) (mkc_nat n) f)\n                   (mkc_apply F f)\n                   (mkc_bunion mkc_tnat mkc_unit) }.\nProof.\n  introv mF mf.\n\n  (* Do we want to constrain the f? *)\n\n  apply equality_in_fun in mF; repnd.\n  clear mF0 mF1.\n  applydup mF in mf.\n  dup mf0 as ma; apply equality_refl in ma.\n  apply equality_in_tnat in mf0.\n  apply equality_of_nat_imp_tt in mf0.\n  unfold equality_of_nat_tt in mf0; exrepnd; GC.\n\n  pose proof (equality_lam_force_nat_c_in_nat2nat_v2 lib nvarx nvarz f T mf) as q.\n  applydup mF in q.\n  apply equality_in_tnat in q0.\n  apply equality_of_nat_imp_tt in q0.\n  unfold equality_of_nat_tt in q0; exrepnd; spcast.\n  computes_to_eqval.\n  allapply @eq_mkc_nat_implies; subst; GC.\n\n  pose proof (exists_bigger_than_list_Z\n                (get_ints_from_computes_to_valc\n                   lib\n                   (mkc_apply F (lam_force_nat_c nvarx nvarz f))\n                   (mkc_nat k)\n                   q1)) as h; exrepnd.\n\n  exists n.\n\n  eapply equality_respects_cequivc_left;\n    [apply cequivc_sym;apply cequivc_apply2_spM_c\n    |].\n\n  apply equality_in_disjoint_bunion; eauto 3 with slow.\n  dands; eauto 3 with slow.\n  left.\n\n  rw @test_c_eq.\n\n  destruct (fresh_atom o (getc_utokens F ++ getc_utokens f)) as [a nia].\n  allrw in_app_iff; allrw not_over_or; repnd.\n\n  assert (equality\n            lib\n            (substc (mkc_utoken a) nvare (test_try2_cv F nvarc nvarx nvarz nvare (mkc_nat n) f))\n            (mkc_apply F f)\n            (mkc_tnat)) as comp;\n    [|pose proof (cequivc_fresh_subst2 lib nvare (test_try2_cv F nvarc nvarx nvarz nvare (mkc_nat n) f) a) as h;\n       repeat (autodimp h hyp);\n       [destruct_cterms;allsimpl;\n        allunfold @getcv_utokens; allunfold @getc_utokens;\n        allsimpl; allrw app_nil_r;\n        allrw in_app_iff; complete sp\n       |exists (@mkc_nat o k); dands; spcast; tcsp;\n        allrw @substc_test_try2_cv;\n        apply equality_in_tnat in comp;\n        apply equality_of_nat_imp_tt in comp;\n        unfold equality_of_nat_tt in comp; exrepnd; auto;\n        computes_to_eqval; complete ginv\n       |spcast; allrw @substc_test_try2_cv;\n        eapply equality_respects_cequivc_left;[apply cequivc_sym;exact h|];\n        complete auto\n       ]\n    ];[].\n\n  allrw @substc_test_try2_cv.\n\n  assert (equality\n            lib\n            (mkc_apply F (bound2_c nvarx nvarz (mkc_nat n) f (mkc_utoken a)))\n            (mkc_apply F f)\n            mkc_tnat) as equ;\n    [|apply equality_in_tnat in equ;\n       unfold equality_of_nat in equ; exrepnd; spcast;\n       eapply equality_respects_cequivc_left;\n       [apply cequivc_sym;\n         apply computes_to_valc_implies_cequivc;\n         eapply computes_to_valc_mkc_try;[exact equ1|];\n         apply computes_to_pkc_refl;\n         complete (apply mkc_utoken_eq_pk2termc)\n       |eapply equality_respects_cequivc_right;\n         [apply cequivc_sym;apply computes_to_valc_implies_cequivc;exact equ0|];\n         eauto 3 with slow\n       ]\n    ].\n\n  eapply equality_respects_cequivc_left;\n    [apply cequivc_sym;\n      apply implies_cequivc_apply;\n      [apply cequivc_refl\n      |apply cequiv_bound2_c_cbv]\n    |].\n\n  apply equality_in_tnat.\n  exists k; dands; spcast; auto;[].\n\n  pose proof (reduces_toc_nat_differ_force\n                lib\n                (mkc_apply F (lam_force_nat_c nvarx nvarz f))\n                (mkc_apply F (bound2_cbv_c nvarx nvarz (mkc_nat n) f (mkc_utoken a)))\n                k q1 n a f) as h.\n  repeat (autodimp h hyp).\n\n  allrw @get_cterm_apply; simpl.\n  apply differ_force_oterm; simpl; tcsp.\n  introv i; repndors; tcsp; ginv; constructor; eauto 3 with slow.\n  apply differ_force_oterm; simpl; tcsp.\n  introv i; repndors; tcsp; ginv; constructor; eauto 3 with slow.\n  apply differ_force_nat; auto.\nQed.\n\n\n\n(* XXXXXXXXXXXXXXXXX *)\n\n\nDefinition has_eq_value_type_nut {o} lib (T : @NTerm o) :=\n  forall w s c, eq_value_type_nut lib (lsubstc T w s c).\n\nDefinition strong_continuous_type_v2 {o} (x M f n : NVar) (F : @NTerm o) T :=\n  mk_sqexists\n    (mod_fun_type_v2 x T)\n    M\n    (mk_all\n       (mk_nat2T T)\n       f\n       (mk_sqexists\n          mk_tnat\n          n\n          (mk_equality\n             (mk_apply2 (mk_var M) (mk_var n) (mk_var f))\n             (mk_apply F (mk_var f))\n             mk_natU))).\n\nDefinition rule_strong_continuity_v2 {o}\n           (F T t : @NTerm o)\n           (x M f n : NVar)\n           (H : barehypotheses)\n           (i : nat) :=\n    mk_rule\n      (mk_baresequent H (mk_conclax (strong_continuous_type_v2 x M f n F T)))\n      [ mk_baresequent H (mk_conclax (mk_member F (mk_fun (mk_nat2T T) mk_tnat))),\n        mk_baresequent H (mk_conclax (mk_member t T)) ]\n      [].\n\n\nLemma rule_strong_continuity_true_v2 {p} :\n  forall lib\n         (F T t : NTerm)\n         (x M f n : NVar)\n         (H : @barehypotheses p)\n         (i : nat)\n         (d1 : M <> f)\n         (d2 : n <> f)\n         (d3 : n <> M)\n         (d4 : !LIn M (free_vars F))\n         (d5 : !LIn f (free_vars F))\n         (d6 : !LIn n (free_vars F))\n         (d7 : !LIn x (free_vars T))\n         (d8 : !LIn M (free_vars T))\n         (nut : has_eq_value_type_nut lib T),\n    rule_true lib (rule_strong_continuity_v2\n                     F T t\n                     x M f n\n                     H i).\nProof.\n  unfold rule_strong_continuity_v2, rule_true, closed_type_baresequent, closed_extract_baresequent; simpl.\n  intros.\n  clear cargs.\n\n  (* We prove the well-formedness of things *)\n  destseq; allsimpl.\n  dLin_hyp.\n  rename Hyp into hyp1.\n  destruct hyp1 as [wc1 hyp1].\n  rename Hyp0 into hyp2.\n  destruct hyp2 as [wc2 hyp2].\n  destseq; allsimpl; proof_irr; GC.\n  unfold closed_extract; simpl.\n\n  exists (@covered_axiom p (nh_vars_hyps H)).\n\n  (* We prove some simple facts on our sequents *)\n  (* done with proving these simple facts *)\n\n  vr_seq_true.\n\n  vr_seq_true in hyp1.\n  pose proof (hyp1 s1 s2 eqh sim) as h; exrepnd; clear hyp1.\n\n  vr_seq_true in hyp2.\n  pose proof (hyp2 s1 s2 eqh sim) as hTT; exrepnd; clear hyp2.\n\n  allunfold @strong_continuous_type_v2.\n  allunfold @mk_sqexists.\n  lsubst_tac.\n\n  apply equality_in_member in hTT1; repnd.\n  apply tequality_mkc_member_sp in hTT0; repnd.\n  clear hTT0 hTT2 hTT3.\n\n  apply member_if_inhabited in h1.\n  apply tequality_mkc_member_sp in h0; repnd.\n  allrw @fold_equorsq.\n  clear h2.\n\n  lsubst_tac.\n  allrw @lsubstc_mkc_tnat.\n\n  eapply member_respects_alphaeqc_r in h1;\n    [|apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n      apply (lsubstc_mk_nat2T_sp1 T w0 s1 c2 wT cT)].\n  eapply respects_alphaeqc_equorsq3 in h0;\n    [|apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n      apply (lsubstc_mk_nat2T_sp1 T w0 s1 c2 wT cT)].\n\n  dup h1 as memF.\n  eapply cequorsq_equality_trans1 in memF;[|apply equorsq_sym;exact h0].\n  apply equality_sym in memF.\n  clear h0.\n\n  prove_and teq.\n\n  - apply tequality_mkc_squash.\n\n    unfold mk_exists.\n    lsubst_tac.\n\n    apply tequality_product.\n    dands.\n\n    + eapply tequality_respects_alphaeqc_left;\n      [apply alphaeqc_sym; apply (lsubstc_mod_fun_type_v2_aux x T w3 s1 c4 wT cT);auto|].\n      eapply tequality_respects_alphaeqc_right;\n        [apply alphaeqc_sym; apply (lsubstc_mod_fun_type_v2_aux x T w3 s2 c6 wT cT1);auto|].\n      apply tequality_modulus_fun_type_u_v2; auto.\n\n    + intros M1 M2 em.\n      eapply alphaeqc_preserving_equality in em;\n        [|apply (lsubstc_mod_fun_type_v2_aux x T w3 s1 c4 wT cT);auto].\n      repeat substc_lsubstc_vars3.\n\n      unfold mk_all.\n      lsubst_tac.\n\n      apply tequality_function; dands.\n\n      * eapply tequality_respects_alphaeqc_left;\n        [apply alphaeqc_sym;apply (lsubstc_mk_nat2T_sp1 T w0 s1 c2 wT cT)|].\n        eapply tequality_respects_alphaeqc_right;\n          [apply alphaeqc_sym;apply (lsubstc_mk_nat2T_sp1 T w0 s2 c13 wT cT1)|].\n        apply tequality_nat2T; auto.\n\n      * intros f1 f2 en2n.\n        eapply alphaeqc_preserving_equality in en2n;\n          [|apply (lsubstc_mk_nat2T_sp1 T w0 s1 c2 wT cT)].\n        repeat substc_lsubstc_vars3.\n        lsubst_tac.\n        apply tequality_mkc_squash.\n        allrw @lsubstc_mkc_tnat.\n\n        apply tequality_product; dands; eauto 3 with slow.\n        { apply type_tnat. }\n\n        intros n1 n2 en.\n        repeat substc_lsubstc_vars3.\n        a_lsubst_tac.\n\n        apply tequality_mkc_equality_if_equal.\n\n        { eapply tequality_respects_alphaeqc_left;\n          [apply alphaeqc_sym; apply lsubstc_mk_natU|].\n          eapply tequality_respects_alphaeqc_right;\n            [apply alphaeqc_sym; apply lsubstc_mk_natU|].\n          apply type_natU. }\n\n        { eapply alphaeqc_preserving_equality;\n          [|apply alphaeqc_sym; apply lsubstc_mk_natU].\n\n          apply equality_in_function2 in em; repnd.\n          clear em0.\n          applydup em in en as e.\n          eapply alphaeqc_preserving_equality in e;[|apply substc_mkcv_fun].\n          rw @csubst_mk_cv in e.\n\n          try (fold (@natU p) in e).\n          eapply alphaeqc_preserving_equality in e;\n            [|apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n              apply substc_mkcv_fun].\n          eapply alphaeqc_preserving_equality in e;\n            [|apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n              apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n              apply mkcv_natk_substc\n            ].\n          allrw @mkc_var_substc.\n          allrw @mkcv_tnat_substc.\n\n          try (fold (natk2nat n1) in e).\n\n          applydup @equality_refl in en.\n          apply (equality_nat2T_to_natk2T lib n1) in en2n; auto;[].\n\n          apply equality_in_fun in e; repnd; clear e0 e1.\n          allrw @csubst_mk_cv.\n          apply e in en2n.\n          allrw <- @mkc_apply2_eq; auto. }\n\n        { eapply alphaeqc_preserving_equality;\n          [|apply alphaeqc_sym; apply lsubstc_mk_natU].\n          apply equality_in_fun in memF; repnd; clear memF0 memF1.\n          apply memF in en2n; auto.\n          apply equality_in_bunion_left; eauto 2 with slow. }\n\n  - apply equality_in_mkc_squash; dands;\n    try (spcast; apply computes_to_valc_refl; eauto 3 with slow);[].\n\n    unfold mk_exists.\n    lsubst_tac.\n\n    exists (mkc_pair (spM_c (lsubstc F wt0 s1 ct2))\n                     (mkc_lam f (mkcv_axiom f))).\n\n    apply equality_in_product.\n    dands.\n\n    + eapply type_respects_alphaeqc;\n      [apply alphaeqc_sym;apply (lsubstc_mod_fun_type_v2_aux x T w3 s1 c4 wT cT);auto|].\n      apply tequality_modulus_fun_type_u_v2; eauto 3 with slow.\n      eapply tequality_refl; eauto.\n\n    + intros M1 M2 em.\n      eapply alphaeqc_preserving_equality in em;\n        [|apply (lsubstc_mod_fun_type_v2_aux x T w3 s1 c4 wT cT);auto].\n      repeat substc_lsubstc_vars3.\n\n      unfold mk_all.\n      lsubst_tac.\n\n      apply tequality_function; dands.\n\n      * eapply tequality_respects_alphaeqc_left;\n        [apply alphaeqc_sym;apply (lsubstc_mk_nat2T_sp1 T w0 s1 c2 wT cT)|].\n        eapply tequality_respects_alphaeqc_right;\n          [apply alphaeqc_sym;apply (lsubstc_mk_nat2T_sp1 T w0 s1 c2 wT cT)|].\n        apply tequality_nat2T.\n        eapply tequality_refl; eauto.\n\n      * intros f1 f2 en2n.\n        eapply alphaeqc_preserving_equality in en2n;\n          [|apply (lsubstc_mk_nat2T_sp1 T w0 s1 c2 wT cT)].\n        repeat substc_lsubstc_vars3.\n        lsubst_tac.\n        apply tequality_mkc_squash.\n        allrw @lsubstc_mkc_tnat.\n\n        apply tequality_product; dands; eauto 3 with slow.\n        { apply type_tnat. }\n\n        intros n1 n2 en.\n        repeat substc_lsubstc_vars3.\n        a_lsubst_tac.\n\n        apply tequality_mkc_equality_if_equal.\n\n        { eapply tequality_respects_alphaeqc_left;\n          [apply alphaeqc_sym; apply lsubstc_mk_natU|].\n          eapply tequality_respects_alphaeqc_right;\n            [apply alphaeqc_sym; apply lsubstc_mk_natU|].\n          apply type_natU. }\n\n        { eapply alphaeqc_preserving_equality;\n          [|apply alphaeqc_sym; apply lsubstc_mk_natU].\n\n          apply equality_in_function2 in em; repnd.\n          clear em0.\n          applydup em in en as e.\n          eapply alphaeqc_preserving_equality in e;[|apply substc_mkcv_fun].\n          rw @csubst_mk_cv in e.\n\n          try (fold (@natU p) in e).\n          eapply alphaeqc_preserving_equality in e;\n            [|apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n              apply substc_mkcv_fun].\n          eapply alphaeqc_preserving_equality in e;\n            [|apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n              apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n              apply mkcv_natk_substc\n            ].\n          allrw @mkc_var_substc.\n          allrw @mkcv_tnat_substc.\n\n          try (fold (natk2nat n1) in e).\n\n          applydup @equality_refl in en.\n          apply (equality_nat2T_to_natk2T lib n1) in en2n; auto;[].\n\n          apply equality_in_fun in e; repnd; clear e0 e1.\n          allrw @csubst_mk_cv.\n          apply e in en2n.\n          allrw <- @mkc_apply2_eq; auto. }\n\n        { eapply alphaeqc_preserving_equality;\n          [|apply alphaeqc_sym; apply lsubstc_mk_natU].\n          apply equality_refl in memF.\n          apply equality_in_fun in memF; repnd; clear memF0 memF1.\n          apply memF in en2n; auto.\n          apply equality_in_bunion_left; eauto 2 with slow. }\n\n    + eexists; eexists; eexists; eexists; dands; spcast;\n      try (apply computes_to_valc_refl; eauto 3 with slow).\n\n      * eapply alphaeqc_preserving_equality;\n        [|apply alphaeqc_sym;apply (lsubstc_mod_fun_type_v2_aux x T w3 s1 c4 wT cT);auto].\n\n        apply (spM_in_modulus_fun_type_u_v2 _ _ (lsubstc t wt s1 ct1)); auto.\n\n      * repeat substc_lsubstc_vars3.\n        unfold mk_all.\n        lsubst_tac.\n\n        apply equality_in_function.\n        dands.\n\n        { eapply type_respects_alphaeqc;\n          [apply alphaeqc_sym;apply (lsubstc_mk_nat2T_sp1 T w0 s1 c2 wT cT)|];\n          eauto 3 with slow.\n          apply tequality_nat2T; eauto 3 with slow.\n          eapply tequality_refl; eauto. }\n\n        { intros f1 f2 en2n.\n          eapply alphaeqc_preserving_equality in en2n;\n            [|apply (lsubstc_mk_nat2T_sp1 T w0 s1 c2 wT cT)].\n          repeat substc_lsubstc_vars3.\n          lsubst_tac.\n          apply tequality_mkc_squash.\n          allrw @lsubstc_mkc_tnat.\n\n          apply tequality_product; dands; eauto 3 with slow.\n          { apply type_tnat. }\n\n          intros n1 n2 en.\n          repeat substc_lsubstc_vars3.\n          a_lsubst_tac.\n\n          apply tequality_mkc_equality_if_equal.\n\n          { eapply tequality_respects_alphaeqc_left;\n            [apply alphaeqc_sym; apply lsubstc_mk_natU|].\n            eapply tequality_respects_alphaeqc_right;\n              [apply alphaeqc_sym; apply lsubstc_mk_natU|].\n            apply type_natU. }\n\n          { eapply alphaeqc_preserving_equality;\n            [|apply alphaeqc_sym; apply lsubstc_mk_natU].\n\n            pose proof (spM_in_modulus_fun_type_u_v2\n                          lib\n                          (lsubstc F wt0 s1 ct2)\n                          (lsubstc t wt s1 ct1)\n                          (lsubstc T wT s1 cT)) as h.\n            repeat (autodimp h hyp);[].\n            rw @equality_in_function in h; repnd.\n            applydup h in en as e.\n            eapply alphaeqc_preserving_equality in e;[|apply substc_mkcv_fun].\n            rw @csubst_mk_cv in e.\n\n            try (fold (@natU p) in e).\n            eapply alphaeqc_preserving_equality in e;\n              [|apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n                apply substc_mkcv_fun].\n            eapply alphaeqc_preserving_equality in e;\n              [|apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n                apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n                apply mkcv_natk_substc\n              ].\n            allrw @mkc_var_substc.\n            allrw @mkcv_tnat_substc.\n\n            try (fold (natk2nat n1) in e).\n\n            applydup @equality_refl in en.\n            apply (equality_nat2T_to_natk2T lib n1) in en2n; auto;[].\n\n            apply equality_in_fun in e; repnd; clear e0 e1.\n            allrw @csubst_mk_cv.\n            apply e in en2n.\n            allrw <- @mkc_apply2_eq; auto. }\n\n          { eapply alphaeqc_preserving_equality;\n            [|apply alphaeqc_sym; apply lsubstc_mk_natU].\n            apply equality_refl in memF.\n            apply equality_in_fun in memF; repnd; clear memF0 memF1.\n            apply memF in en2n; auto.\n            apply equality_in_bunion_left; eauto 2 with slow. }\n        }\n\n        { intros f1 f2 en2n.\n          eapply alphaeqc_preserving_equality in en2n;\n            [|apply (lsubstc_mk_nat2T_sp1 T w0 s1 c2 wT cT)].\n          repeat substc_lsubstc_vars3.\n          lsubst_tac.\n\n          eapply equality_respects_cequivc_left;\n            [apply cequivc_sym;apply cequivc_beta|].\n          eapply equality_respects_cequivc_right;\n            [apply cequivc_sym;apply cequivc_beta|].\n          allrw @substc_mkcv_axiom.\n\n          apply equality_in_mkc_squash; dands; spcast;\n          try (apply computes_to_valc_refl; eauto 3 with slow);[].\n\n          applydup @equality_refl in en2n as mf1.\n          pose proof (spM_cond_v2 lib (lsubstc F wt0 s1 ct2) f1 (lsubstc T wT s1 cT) h1 mf1) as h.\n          exrepnd.\n\n          allrw @lsubstc_mkc_tnat.\n\n          exists (mkc_pair (mkc_nat n0) (@mkc_axiom p)).\n\n          apply equality_in_product; dands; eauto 3 with slow.\n\n          - intros n1 n2 en.\n            repeat substc_lsubstc_vars3.\n            a_lsubst_tac.\n\n            apply tequality_mkc_equality_if_equal.\n\n            { eapply tequality_respects_alphaeqc_left;\n              [apply alphaeqc_sym; apply lsubstc_mk_natU|].\n              eapply tequality_respects_alphaeqc_right;\n              [apply alphaeqc_sym; apply lsubstc_mk_natU|].\n              apply type_natU. }\n\n            { eapply alphaeqc_preserving_equality;\n              [|apply alphaeqc_sym; apply lsubstc_mk_natU].\n\n              pose proof (spM_in_modulus_fun_type_u_v2\n                            lib\n                            (lsubstc F wt0 s1 ct2)\n                            (lsubstc t wt s1 ct1)\n                            (lsubstc T wT s1 cT)) as h.\n              repeat (autodimp h hyp);[].\n              rw @equality_in_function in h; repnd.\n              applydup h in en as e.\n              eapply alphaeqc_preserving_equality in e;[|apply substc_mkcv_fun].\n              rw @csubst_mk_cv in e.\n\n              try (fold (@natU p) in e).\n              eapply alphaeqc_preserving_equality in e;\n                [|apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n                  apply substc_mkcv_fun].\n              eapply alphaeqc_preserving_equality in e;\n                [|apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n                  apply alphaeqc_mkc_fun;[|apply alphaeqc_refl];\n                  apply mkcv_natk_substc\n                ].\n              allrw @mkc_var_substc.\n              allrw @mkcv_tnat_substc.\n              allrw @csubst_mk_cv.\n\n              try (fold (natk2T n1 (lsubstc T wT s1 cT)) in e).\n\n              applydup @equality_refl in en.\n              apply (equality_nat2T_to_natk2T lib n1) in en2n; auto;[].\n\n              apply equality_in_fun in e; repnd; clear e0 e1.\n              applydup @equality_refl in en2n as ef.\n              allrw @csubst_mk_cv.\n              apply e in ef.\n              allrw <- @mkc_apply2_eq; auto. }\n\n            { eapply alphaeqc_preserving_equality;\n              [|apply alphaeqc_sym; apply lsubstc_mk_natU].\n              apply equality_refl in memF.\n              apply equality_in_fun in memF; repnd; clear memF0 memF1.\n              apply memF in en2n; auto.\n              apply equality_in_bunion_left; eauto 2 with slow. }\n\n          - eexists; eexists; eexists; eexists; dands; spcast;\n            try (apply computes_to_valc_refl; eauto 3 with slow);\n            eauto 3 with slow.\n\n            repeat substc_lsubstc_vars3.\n            a_lsubst_tac.\n\n            apply member_equality.\n            eapply alphaeqc_preserving_equality;\n              [|apply alphaeqc_sym; apply lsubstc_mk_natU].\n            auto.\n        }\nQed.\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"./close/\")\n*** End:\n*)\n", "meta": {"author": "coq-contribs", "repo": "intuitionistic-nuprl", "sha": "6279ed83244dc4aec2e23ffb4c87e3f10a50326d", "save_path": "github-repos/coq/coq-contribs-intuitionistic-nuprl", "path": "github-repos/coq/coq-contribs-intuitionistic-nuprl/intuitionistic-nuprl-6279ed83244dc4aec2e23ffb4c87e3f10a50326d/stronger_continuity_rule_v2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.23462084057520918}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\nRequire Import omega.Omega.\nRequire Import Setoid.\nRequire Import ZArith.\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith. \nLocal Open Scope struct_scope.\nRequire Import FinProof.CommonProofs.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolClass.\nRequire Import depoolContract.SolidityNotations.\nRequire Import depoolContract.DePoolFunc.\nRequire Import depoolContract.DePoolConsts.\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\nRequire Import depoolContract.Scenarios.ScenarioCommon.\nImport DePoolSpec.LedgerClass.SolidityNotations. \nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope solidity_scope.\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\nSet Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100.\nModule Scenario8  (dc : DePoolConstsTypesSig XTypesSig StateMonadSig).\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig dc.\nImport dc.\nModule ScenarioCommon := ScenarioCommon dc.\nImport ScenarioCommon.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\nLemma Scenario_StakeLose_ParticipantVestingValidatorOrdinary: forall \n                        (minStake validatorAssurance proxyCode validatorWallet   participantRewardFraction : Z)\n                        (proxyCode : TvmCell)\n                        (now_constructor msg_pubkey_constructor : Z)\n                        (NetParams_init : NetParams)\n                        (stakeV :Z )\n                        (NetParams_addOrdinaryStake :  NetParams)\n                        (now_addOrdinaryStake msg_value_addOrdinaryStake msg_sender_addOrdinaryStake : Z)\n                        (stake beneficiary withdrawalPeriod totalPeriod : Z )\n                        (now_addVestingOrLock msg_value_addVestingOrLock msg_sender_addVestingOrLock : Z)\n                        (now_round1  msg_value_round1 msg_sender_round1 : Z)\n                        (NetParams_round1 :  NetParams)\n                        (queryId0 validatorKey stakeAt maxFactor adnlAddr : Z)\n                        ( signature : XList XInteger8 )\n                        (now_participateInElections  msg_value_participateInElections msg_sender_participateInElections : Z)\n                        (NetParams_participateInElections :  NetParams)                        \n                        (queryId comment elector : Z)\n                        (now_onStakeAccept  msg_value_onStakeAccept msg_sender_onStakeAccept : Z)\n                        (NetParams_onStakeAccept :  NetParams)\n                        (stake beneficiary withdrawalPeriod totalPeriod : Z )\n                        (NetParams_addVestingOrLock :  NetParams)\n                        (now_addVestingOrLock msg_value_addVestingOrLock msg_sender_addVestingOrLock : Z)\n                        (now_toWaitingIfValidatorWinElections  msg_value_toWaitingIfValidatorWinElections msg_sender_toWaitingIfValidatorWinElections : Z)\n                        (NetParams_toWaitingIfValidatorWinElections :  NetParams)\n                        (now_onSuccessToRecoverStake  msg_value_onSuccessToRecoverStake msg_sender_onSuccessToRecoverStake : Z)\n                        (NetParams_onSuccessToRecoverStake :  NetParams)\n                        (now_toWaitingReward  msg_value_toWaitingReward msg_sender_toWaitingReward : Z)\n                        (NetParams_toWaitingReward :  NetParams),\nlet l_init_NetParams := withNetParams default NetParams_init in\nlet l_init := {$ l_init_NetParams With (VMState_ι_now,   now_constructor); \n                                       (VMState_ι_msg_pubkey,   msg_pubkey_constructor)$} in \nlet l_constructor:= exec_state (DePoolContract_Ф_Constructor6 minStake validatorAssurance proxyCode validatorWallet   participantRewardFraction  ) l_init in \nlet (r, l_fin) := run  (modify (fun l => withNetParams l NetParams_addOrdinaryStake) >>\n                        modify (fun l => {$ l With (VMState_ι_now,   now_addOrdinaryStake);\n                                                   (VMState_ι_msg_value , msg_value_addOrdinaryStake);\n                                                   (VMState_ι_msg_sender , msg_sender_addOrdinaryStake) $}) >>\n                        do _ ← DePoolContract_Ф_addOrdinaryStake'' stakeV ??;\n                        modify (fun l => withNetParams l NetParams_addVestingOrLock) >>\n                        modify (fun l => {$ l With (VMState_ι_now,   now_addVestingOrLock);\n                                                   (VMState_ι_msg_value , msg_value_addVestingOrLock);\n                                                   (VMState_ι_msg_sender , msg_sender_addVestingOrLock) $}) >>\n                        do _ ← DePoolContract_Ф_addVestingOrLock'' stakeV beneficiary withdrawalPeriod totalPeriod true ??;\n                        modify (fun l => {$ l With (VMState_ι_now,   now_addVestingOrLock);\n                                                   (VMState_ι_msg_value , msg_value_addVestingOrLock);\n                                                   (VMState_ι_msg_sender , msg_sender_addVestingOrLock) $}) >>\n                        do _ ← DePoolContract_Ф_addVestingOrLock'' stake beneficiary withdrawalPeriod totalPeriod true ??;\n                        modify (fun l => withNetParams l NetParams_round1) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_round1);\n                                                   (VMState_ι_msg_value ,   msg_value_round1);\n                                                   (VMState_ι_msg_sender ,  msg_sender_round1) $}) >>\n                        do _ ← DePoolContract_Ф_ticktock ??;\n                        modify (fun l => withNetParams l NetParams_participateInElections) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_participateInElections);\n                                                   (VMState_ι_msg_value ,   msg_value_participateInElections);\n                                                   (VMState_ι_msg_sender ,  msg_sender_participateInElections) $}) >>\n                        do _ ← DePoolContract_Ф_participateInElections'' queryId0 validatorKey stakeAt maxFactor adnlAddr signature ??;\n                        modify (fun l => withNetParams l NetParams_onStakeAccept) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_onStakeAccept);\n                                                   (VMState_ι_msg_value ,   msg_value_onStakeAccept);\n                                                   (VMState_ι_msg_sender ,  msg_sender_onStakeAccept) $}) >>\n                        do _ ← DePoolContract_Ф_onStakeAccept queryId comment elector ??;\n                        modify (fun l => withNetParams l NetParams_toWaitingIfValidatorWinElections) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_toWaitingIfValidatorWinElections);\n                                                   (VMState_ι_msg_value ,   msg_value_toWaitingIfValidatorWinElections);\n                                                   (VMState_ι_msg_sender ,  msg_sender_toWaitingIfValidatorWinElections) $}) >>\n                        do _ ← DePoolContract_Ф_ticktock ??;\n                        modify (fun l => withNetParams l NetParams_onSuccessToRecoverStake) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_onSuccessToRecoverStake);\n                                                   (VMState_ι_msg_value ,   msg_value_onSuccessToRecoverStake);\n                                                   (VMState_ι_msg_sender ,  msg_sender_onSuccessToRecoverStake) $}) >>\n                        do _ ← DePoolContract_Ф_onSuccessToRecoverStake queryId elector ??;\n                        modify (fun l => withNetParams l NetParams_toWaitingReward) >>\n                        modify (fun l => {$ l With (VMState_ι_now,          now_toWaitingReward);\n                                                   (VMState_ι_msg_value ,   msg_value_toWaitingReward);\n                                                   (VMState_ι_msg_sender ,  msg_sender_toWaitingReward) $}) >>\n                        do _ ← DePoolContract_Ф_ticktock ?;\n                        $ I )  l_constructor in errorValueIsValue r = true ->\nmsg_sender_addOrdinaryStake = validatorWallet ->  \nmsg_sender_addVestingOrLock <> validatorWallet ->  \nbeneficiary <> validatorWallet ->\n(now_round1 >=? NetParams_round1 ->> NetParams_ι_utime_until - NetParams_round1 ->> NetParams_ι_electionsStartBefore) = true -> \n((negb (tvm_hash (NetParams_init ->> NetParams_ι_curValidatorData) =? tvm_hash (NetParams_round1 ->> NetParams_ι_curValidatorData))) &&\n(negb (tvm_hash (NetParams_init ->> NetParams_ι_prevValidatorData) =? tvm_hash (NetParams_round1 ->> NetParams_ι_curValidatorData))))%bool= true ->    \n(stakeV >=? validatorAssurance) = true -> \n( tvm_hash  (NetParams_round1 ->> NetParams_ι_curValidatorData)  =?  tvm_hash  (NetParams_toWaitingIfValidatorWinElections ->> NetParams_ι_prevValidatorData))  = true ->\n(now_toWaitingIfValidatorWinElections >=? NetParams_toWaitingIfValidatorWinElections ->> NetParams_ι_utime_until - NetParams_toWaitingIfValidatorWinElections ->> NetParams_ι_electionsStartBefore) = true ->\n(negb (0 =? tvm_hash ((NetParams_toWaitingIfValidatorWinElections ->> NetParams_ι_curValidatorData)))) = true ->\n((negb (tvm_hash ((NetParams_toWaitingReward ->> NetParams_ι_curValidatorData)) =? tvm_hash ((NetParams_round1 ->> NetParams_ι_curValidatorData)))) &&\n(negb (tvm_hash ((NetParams_toWaitingReward ->> NetParams_ι_prevValidatorData)) =? tvm_hash ((NetParams_round1 ->> NetParams_ι_curValidatorData)))))%bool= true ->    \n(now_toWaitingReward >=? NetParams_toWaitingReward ->> NetParams_ι_utime_since + NetParams_round1 ->> NetParams_ι_stakeHeldFor + DePoolLib_ι_ELECTOR_UNFREEZE_LAG) = true ->\n(msg_value_onSuccessToRecoverStake + DePoolLib_ι_PROXY_FEE >=? stake/2 + stakeV) = true ->\nlet reward := 0  in\nlet rewardV := 0  in\nlet optRound := eval_state ( ↓ ( RoundsBase_Ф_fetchRound queryId ) ) l_fin in                  \nlet round := maybeGet optRound in \nlet stakes :=  round ->> RoundsBase_ι_Round_ι_stakes in\nlet optStake := stakes ->fetch beneficiary in\nlet optStakeV := stakes ->fetch validatorWallet in\nlet current_stakes := maybeGet optStake in\nlet current_stakesV := maybeGet optStakeV in \nnow_onSuccessToRecoverStake > now_addVestingOrLock ->\nlet periodQty := (now_onSuccessToRecoverStake - now_addVestingOrLock) / withdrawalPeriod in\nlet p := (maybeGet (current_stakes ->> RoundsBase_ι_StakeValue_ι_vesting)) in\nlet withdrawalValue := stake/2 * withdrawalPeriod / totalPeriod in \nlet withdrawalTons := intMin  (periodQty * withdrawalValue)  (stake/2)  in\nlet remainingAmount := stake/2 - withdrawalTons in\nremainingAmount < minStake ->\n(round ->> RoundsBase_ι_Round_ι_stake = stake/2 + stakeV)\n/\\ (p ->> RoundsBase_ι_InvestParams_ι_remainingAmount  = remainingAmount)\n/\\ (current_stakesV ->> RoundsBase_ι_StakeValue_ι_ordinary  = withdrawalTons + reward)\n/\\ (current_stakesV ->> RoundsBase_ι_StakeValue_ι_ordinary  = stakeV + rewardV).\nProof.\n\nAbort.\n\nEnd Scenario8.", "meta": {"author": "Pruvendo", "repo": "depool_contract", "sha": "6afe23011d62f65921ac2493df691ab888ffeb95", "save_path": "github-repos/coq/Pruvendo-depool_contract", "path": "github-repos/coq/Pruvendo-depool_contract/depool_contract-6afe23011d62f65921ac2493df691ab888ffeb95/src/Scenarios/Scenario8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2345946652125849}}
{"text": "From hahn Require Import Hahn.\nRequire Import Events.\nRequire Import Execution.\nRequire Import AuxRel2.\n\nSet Implicit Arguments.\n\nSection CO.\n\nVariables G : execution.\nVariable I : actid -> Prop.  (* issued *)\nVariable T : actid -> Prop.  (* all writes in certified thread *)\n\nNotation \"'E'\" := (acts_set G).\nNotation \"'lab'\" := (lab G).\nNotation \"'sb'\" := (sb G).\nNotation \"'rf'\" := (rf G).\nNotation \"'co'\" := (co G).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'loc'\" := (loc lab).\nNotation \"'same_loc'\" := (same_loc lab).\nNotation \"'Loc_' l\" := (fun x => loc x = Some l) (at level 1).\nNotation \"'W_' l\" := (W ∩₁ Loc_ l) (at level 1).\n\nHypothesis IT: I ∪₁ T ≡₁ E ∩₁ W.\n\nLemma IN_I: I ⊆₁ E ∩₁ W.\nProof using IT.\nrewrite <- IT; basic_solver 21.\nQed.\n\nLemma IN_T: T ⊆₁ E ∩₁ W.\nProof using IT.\nrewrite <- IT; basic_solver 21.\nQed.\n\nHypothesis wf_coE : co ≡ ⦗E⦘ ⨾ co ⨾ ⦗E⦘.\nHypothesis wf_coD : co ≡ ⦗W⦘ ⨾ co ⨾ ⦗W⦘.\nHypothesis wf_col : co ⊆ same_loc.\nHypothesis co_trans : transitive co.\nHypothesis wf_co_total : forall ol, is_total (E ∩₁ W ∩₁ (fun x => loc x = ol)) co.\nHypothesis co_irr : irreflexive co.\n\nDefinition col l := (⦗Loc_ l⦘ ⨾ co ⨾ ⦗Loc_ l⦘).\n\nDefinition col0 l := (⦗I⦘ ⨾ col l ⨾ ⦗I⦘ ∪ ⦗T⦘ ⨾ col l ⨾ ⦗T⦘ ∪ ⦗I⦘ ⨾ col l ⨾ ⦗T⦘)⁺.\n\nDefinition new_col l := pref_union (col0 l) ((I ∩₁ Loc_ l) × (E ∩₁ W ∩₁ Loc_ l \\₁ I)).\n\nDefinition new_co x y := exists l, (new_col l) x y.\n\nLemma col_in_co l : col l ⊆ co.\nProof using. \nunfold col; basic_solver. \nQed.\n\nLemma co_in_col x y : co x y -> exists l, col l x y.\nProof using wf_coD wf_col.\nunfold new_co, col; ins; unfolder; ins; desf.\nhahn_rewrite (dom_l wf_coD) in H; unfolder in H; desc.\ngeneralize (is_w_loc lab x H); ins; desf.\neexists; splits; eauto.\neexists; splits; eauto.\neexists; splits; eauto.\napply wf_col in H0; unfold Events.same_loc in H0; congruence.\nQed.\n\nLemma wf_colE l : col l ≡ ⦗E⦘ ⨾ col l ⨾ ⦗E⦘.\nProof using wf_coE. \napply dom_helper_3; unfold col; rewrite wf_coE; basic_solver. \nQed.\n\nLemma wf_colD l : col l ≡ ⦗W_ l⦘ ⨾ col l ⨾ ⦗W_ l⦘.\nProof using wf_coD.\napply dom_helper_3; unfold col; rewrite wf_coD; basic_solver. \nQed.\n\nLemma wf_coll l : col l ⊆ same_loc.\nProof using wf_col.\nunfold col; rewrite wf_col; basic_solver. \nQed.\n\nLemma col_trans l : transitive (col l).\nProof using co_trans.\nunfold col.\nrewrite <- restr_relE.\nby apply transitive_restr.\nQed.\n\nLemma wf_col_total l : is_total (E ∩₁ W ∩₁ Loc_ l) (col l).\nProof using wf_coD wf_coE wf_co_total.\nrewrite wf_colD, wf_colE.\nunfold col; rewrite !seqA.\narewrite (⦗W_ l⦘ ⨾ ⦗E⦘ ⨾ ⦗Loc_ l⦘ ≡ ⦗E ∩₁ W ∩₁ Loc_ l⦘) by basic_solver.\narewrite (⦗Loc_ l⦘ ⨾ ⦗E⦘ ⨾ ⦗W_ l⦘ ≡ ⦗E ∩₁ W ∩₁ Loc_ l⦘) by basic_solver.\nrewrite <- restr_relE.\napply is_total_restr.\napply wf_co_total.\nQed.\n\nLemma col_irr l: irreflexive (col l).\nProof using co_irr.\nunfold col.\nrewrite <- restr_relE.\nby apply irreflexive_restr.\nQed.\n\nLemma acyclic_new_col l : acyclic (new_col l).\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\neapply acyclic_pref_union with (dom:=I ∩₁ Loc_ l).\n- unfold col0.\n  arewrite_id ⦗I⦘.\n  arewrite_id ⦗T⦘.\n  relsf.\n  generalize (@col_trans l); ins; relsf; apply col_irr.\n- unfold col0; relsf.\n- assert (XX: restr_rel (I ∩₁ Loc_ l) (col l) ⊆ col0 l).\n  by unfold col0; rewrite <- ct_step; basic_solver 21.\n  rewrite <- XX.\n  apply is_total_restr.\n  rewrite IN_I.\n  eapply wf_col_total.\n- unfolder; ins; desf; splits; eauto; intro; desf.\nQed.\n\nLemma wf_new_colE l : new_col l ≡ ⦗E⦘ ⨾ new_col l ⨾ ⦗E⦘.\nProof using IT wf_coE.\napply dom_helper_3.\nunfold new_col, pref_union, col0; unfolder; ins; desf.\n2: by generalize (IN_I H); basic_solver 12.\ninduction H; [|basic_solver].\ndesf; apply (wf_colE l) in H0; unfolder in H0; desf; eauto.\nQed.\n\nLemma wf_new_colD l : new_col l ≡ ⦗W_ l⦘ ⨾ new_col l ⨾ ⦗W_ l⦘.\nProof using IT wf_coD.\napply dom_helper_3.\nunfold new_col, pref_union, col0; unfolder; ins; desf.\n2: by generalize (IN_I H); basic_solver 12.\ninduction H; [|basic_solver].\ndesf; apply (wf_colD l) in H0; unfolder in H0; desf; eauto.\nQed.\n\nLemma wf_new_coll l : new_col l ⊆ same_loc.\nProof using IT wf_coD.\nrewrite wf_new_colD; unfold Events.same_loc.\nunfolder; ins; desf; congruence.\nQed.\n\nLemma wf_new_col_total l : is_total (E ∩₁ W ∩₁ Loc_ l) (new_col l).\nProof using IT wf_coD wf_coE wf_co_total.\nunfold new_col, pref_union.\nunfolder; ins; desf.\ndestruct (classic (col0 l a b)) as [|X]; eauto 8.\ndestruct (classic (col0 l b a)) as [|Y]; eauto 8.\nassert (XX: ~ (⦗I⦘ ⨾ col l ⨾ ⦗I⦘ ∪ ⦗T⦘ ⨾ col l ⨾ ⦗T⦘ ∪ ⦗I⦘ ⨾ col l ⨾ ⦗T⦘) a b).\nby intro; eapply X; vauto.\nassert (YY: ~ (⦗I⦘ ⨾ col l ⨾ ⦗I⦘ ∪ ⦗T⦘ ⨾ col l ⨾ ⦗T⦘ ∪ ⦗I⦘ ⨾ col l ⨾ ⦗T⦘) b a).\nby intro; eapply Y; vauto.\n \nassert (Ta: ~ I a -> T a).\nby assert (S: (E ∩₁ W) a) by basic_solver; apply IT in S; unfolder in S; ins; desf.\nassert (Tb: ~ I b -> T b).\nby assert (S: (E ∩₁ W) b) by basic_solver; apply IT in S; unfolder in S; ins; desf.\n\nassert (TOT: col l a b \\/ col l b a).\nby apply wf_col_total; basic_solver.\ndestruct (classic (I a)), (classic (I b)); desf.\n- exfalso; unfolder in XX; basic_solver 22.\n- exfalso; unfolder in YY; basic_solver 22.\n- exfalso; unfolder in XX; basic_solver 22.\n- eauto 20.\n- eauto 20.\n- exfalso; unfolder in YY; basic_solver 22.\n- exfalso; unfolder in XX; basic_solver 22.\n- exfalso; unfolder in YY; basic_solver 22.\nQed.\n\n\nLemma new_col_trans l : transitive (new_col l).\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\napply transitiveI; unfolder; ins; desf.\neapply tot_ex.\n- apply wf_new_col_total.\n- hahn_rewrite wf_new_colE in H0.\nhahn_rewrite wf_new_colD in H0.\nunfolder in H0; basic_solver 21.\n- hahn_rewrite wf_new_colE in H.\nhahn_rewrite wf_new_colD in H.\nunfolder in H; basic_solver 21.\n- intro.\neapply acyclic_new_col.\neapply t_trans, t_trans; vauto.\n- intro.\neapply acyclic_new_col.\neapply t_trans; vauto.\nQed.\n\nLemma new_col_irr l : irreflexive (new_col l).\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\nred; ins; eapply acyclic_new_col; vauto.\nQed.\n\nLemma wf_new_coE : new_co ≡ ⦗E⦘ ⨾ new_co ⨾ ⦗E⦘.\nProof using IT wf_coE.\nunfold new_co; unfolder; ins; desf; splits; ins; desf; eauto.\napply (wf_new_colE l) in H; unfolder in H; desf; eauto.\nQed.\n\nLemma wf_new_coD : new_co ≡ ⦗W⦘ ⨾ new_co ⨾ ⦗W⦘.\nProof using IT wf_coD.\nunfold new_co; unfolder; ins; desf; splits; ins; desf; eauto.\napply (wf_new_colD l) in H; unfolder in H; desf; eauto.\nQed.\n\nLemma wf_new_col : new_co ⊆ same_loc.\nProof using IT wf_coD.\nunfold new_co; unfolder; ins; desf; splits; ins; desf; eauto.\napply (@wf_new_coll l) in H; unfolder in H; desf; eauto.\nQed.\n\nLemma new_co_trans : transitive new_co.\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\nunfold new_co; unfolder; ins; desf; splits; ins; desf; eauto.\nhahn_rewrite wf_new_colD in H0.\nhahn_rewrite wf_new_colD in H.\nunfolder in H0; unfolder in H; desf.\nexists l; eapply new_col_trans; eauto.\nQed.\n\nLemma wf_new_co_total : forall ol, is_total (E ∩₁ W ∩₁ (fun x => loc x = ol)) new_co.\nProof using IT wf_coD wf_coE wf_co_total.\nunfold new_co; ins; unfolder; ins; desf.\ngeneralize (is_w_loc lab a IWa1); ins; desf.\ncut (new_col l a b \\/ new_col l b a); [by basic_solver 21|].\napply wf_new_col_total; auto.\nbasic_solver.\nunfolder; splits; ins; desf; congruence.\nQed.\n\nLemma new_co_irr : irreflexive new_co.\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\nunfold new_co; ins; unfolder; ins; desf.\neapply new_col_irr; eauto.\nQed.\n\nLemma new_co_I : new_co ⨾ ⦗ I ⦘  ⊆ co ⨾ ⦗ I ⦘.\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\nunfolder; intros x y [R K]; desf.\nunfold new_co in R; desc.\nhahn_rewrite wf_new_colE in R.\nhahn_rewrite wf_new_colD in R.\nunfolder in R; desf; splits; auto.\neapply tot_ex.\n- apply wf_co_total.\n- basic_solver.\n- unfolder; splits; eauto; congruence.\n- intro.\nassert (S: (E ∩₁ W) z) by basic_solver.\napply IT in S; unfolder in S; ins; desf.\n* eapply new_col_irr, new_col_trans; try edone.\nred; red; unfold col0, col; left; apply t_step; basic_solver 12.\n* eapply new_col_irr, new_col_trans; try edone.\nred; red; unfold col0, col; left; apply t_step; basic_solver 12.\n- intro; subst.\neby eapply new_col_irr.\nQed.\n\nLemma T_new_co : ⦗ T ⦘ ⨾ new_co  ⊆ ⦗ T ⦘ ⨾ co.\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\nunfolder; intros x y [K1 R]; desf.\nunfold new_co in R; desc.\nhahn_rewrite wf_new_colE in R.\nhahn_rewrite wf_new_colD in R.\nunfolder in R; desf; splits; auto.\neapply tot_ex.\n- apply wf_co_total.\n- basic_solver.\n- unfolder; splits; eauto; congruence.\n- intro.\nassert (S: (E ∩₁ W) z) by basic_solver.\napply IT in S; unfolder in S; ins; desf.\n* eapply new_col_irr, new_col_trans; try edone.\n\nred; red; unfold col0, col. left; apply t_step.\nassert (I y \\/ T y) by (apply IT; basic_solver).\ndesf; basic_solver 12.\n* eapply new_col_irr, new_col_trans; try edone.\nred; red; unfold col0, col; left; apply t_step.\nassert (I y \\/ T y) by (apply IT; basic_solver).\ndesf; basic_solver 12.\n- intro; subst.\neby eapply new_col_irr.\nQed.\n\nLemma new_co_in : new_co  ⊆ co ⨾ ⦗ I ⦘ ∪ \n⦗ T ⦘ ⨾ co ∪ ⦗ I \\₁ T ⦘ ⨾ new_co ⨾ ⦗ T \\₁ I ⦘.\nProof using IT co_irr co_trans wf_coD wf_coE wf_co_total.\nrewrite (wf_new_coD), (wf_new_coE) at 1.\nrewrite !seqA.\narewrite (⦗W⦘ ⨾ ⦗E⦘ ⊆ ⦗E ∩₁ W⦘) by basic_solver.\narewrite (⦗E⦘ ⨾ ⦗W⦘ ⊆ ⦗E ∩₁ W⦘) by basic_solver.\nrewrite <- IT.\n\narewrite (I ∪₁ T ⊆₁ (I \\₁ T) ∪₁ T) at 1.\nunfolder; ins; desf; tauto.\n\narewrite (I ∪₁ T ⊆₁ (T \\₁ I) ∪₁ I) at 1.\nunfolder; ins; desf; tauto.\n\nrewrite !id_union; relsf.\n\nsin_rewrite !T_new_co.\nsin_rewrite new_co_I.\nbasic_solver 21.\nQed.\n\nLemma T_I_col0_I_T l : \n  ⦗ T \\₁ I ⦘ ⨾ col0 l ⨾ ⦗ I \\₁ T ⦘  ⊆ \n  ⦗ T \\₁ I ⦘ ⨾ col l ⨾ ⦗ I ∩₁ T ⦘ ⨾ col l ⨾ ⦗ I \\₁ T ⦘.\nProof using co_trans.\nunfold col0 at 1.\narewrite (⦗T⦘ ⊆ ⦗T \\₁ I⦘ ∪ ⦗I ∩₁ T⦘) at 2.\nunfolder; ins ;desf; tauto.\nrelsf.\nrewrite <- !unionA.\nrewrite unionC.\nrewrite <- !unionA.\nrewrite path_ut_first; relsf; unionL.\n- transitivity (∅₂ : actid -> actid -> Prop); [|basic_solver].\n  rewrite path_ut_last; relsf; unionL.\n  rewrite ct_begin; basic_solver.\n  rewrite (rtE (⦗I⦘ ⨾ col l ⨾ ⦗T⦘ ∪ ⦗I⦘ ⨾ col l ⨾ ⦗I⦘)).\n  relsf; unionL.\n  basic_solver.\n  rewrite ct_begin; basic_solver.\n- arewrite (⦗I⦘ ⨾ col l ⨾ ⦗T⦘ ∪ ⦗I⦘ ⨾ col l ⨾ ⦗I⦘ ∪ ⦗T⦘ ⨾ col l ⨾ ⦗T \\₁ I⦘ ⊆ col l).\n  basic_solver.\n  arewrite (col l ∪ ⦗T⦘ ⨾ col l ⨾ ⦗I ∩₁ T⦘ ⊆ col l).\n  basic_solver.\n  generalize (@col_trans l); ins; relsf.\n  basic_solver 21.\nQed.\n\nLemma T_I_new_col_I_T l : \n  ⦗ T \\₁ I ⦘ ⨾ new_col l ⨾ ⦗ I \\₁ T ⦘  ⊆ \n  col l ⨾ ⦗ I ∩₁ T ⦘ ⨾ col l.\nProof using co_trans.\nunfold new_col, pref_union.\nunfolder; ins; desf.\nassert (A: (⦗ T \\₁ I ⦘ ⨾ col0 l ⨾ ⦗ I \\₁ T ⦘) x y) by basic_solver.\napply T_I_col0_I_T in A; unfolder in A; basic_solver 10.\nQed.\n\nLemma T_I_new_co_I_T : \n  ⦗ T \\₁ I ⦘ ⨾ new_co ⨾ ⦗ I \\₁ T ⦘  ⊆ \n  co ⨾ ⦗ I ∩₁ T ⦘ ⨾ co.\nProof using co_trans.\nunfold new_co.\nunfolder; ins; desf.\nassert (A: (⦗ T \\₁ I ⦘ ⨾ new_col l ⨾ ⦗ I \\₁ T ⦘) x y) by basic_solver.\napply T_I_new_col_I_T in A; unfolder in A; desf.\nunfold col in *; unfolder in *; desf; eauto 10.\nQed.\n\nLemma co_for_split: codom_rel (⦗set_compl I⦘ ⨾ (immediate new_co)) ⊆₁ T.\nProof using IT wf_coD wf_coE.\nunfolder; ins; desf.\ndestruct (classic (T x)) as [|X]; auto.\nexfalso.\nhahn_rewrite wf_new_coE in H0.\nhahn_rewrite wf_new_coD in H0.\nunfolder in H0; desf.\nassert (Ix: I x).\nby assert (S: (E ∩₁ W) x) by basic_solver; apply IT in S; unfolder in S; ins; desf.\nunfold new_co, new_col, pref_union in *; desc.\ndestruct H4 as [K|]; cycle 1.\nby unfolder in H2; basic_solver 21.\nunfold col0 in *.\ndestruct K.\nunfolder in H2; basic_solver 21.\neauto 12.\nQed.\n\nLemma new_col_helper l : ⦗ T ⦘ ⨾ col l ⨾ ⦗ I ∩₁ T ⦘ ⨾ col l ⨾ ⦗ I ⦘ ⊆ new_col l.\nProof using.\nunfold new_col, pref_union, col0.\nunfolder; ins; left; desf.\neapply t_trans; apply t_step; eauto 15.\nQed.\n\nLemma new_co_helper : ⦗ T ⦘ ⨾ co ⨾ ⦗ I ∩₁ T ⦘ ⨾ co ⨾ ⦗ I ⦘ ⊆ new_co.\nProof using wf_coD wf_col.\nunfold new_co.\nunfolder; ins; desf.\napply co_in_col in H0.\napply co_in_col in H2.\ndesf.\nassert (l = l0); subst.\n{ hahn_rewrite wf_colD in H0.\n  hahn_rewrite wf_colD in H2.\n  unfolder in *; desf. }\nexists l0.\napply new_col_helper.\nbasic_solver 12.\nQed.\n\nLemma I_co_in_new_co : ⦗ I ⦘ ⨾ co ⊆ new_co.\nProof using IT wf_coD wf_coE wf_col.\nunfold new_co.\nunfolder; ins; desf.\napply co_in_col in H0.\ndesf.\nexists l.\nunfold new_col, pref_union, col0.\nleft.\napply t_step.\ndestruct (classic (I y)).\nbasic_solver 11.\nright; unfolder; splits; eauto.\nhahn_rewrite (wf_colE) in H0.\nhahn_rewrite (wf_colD) in H0.\nunfolder in H0; desf.\nassert ((I ∪₁ T) y).\neapply IT; basic_solver.\nunfolder in *; desf.\nQed.\n\nEnd CO.\n\nGlobal Add Parametric Morphism : col0 with signature\n    eq ==> (@set_subset actid) ==> (@set_subset actid) ==> eq ==>\n       (@inclusion actid) as col0_mori.\nProof using.\n  ins. unfold col0. rewrite H, H0. basic_solver. \nQed. \n\nGlobal Add Parametric Morphism : col0 with signature\n    eq ==> (@set_equiv actid) ==> (@set_equiv actid) ==> eq ==>\n       (@same_relation actid) as col0_more.\nProof using.\n  ins. destruct H, H0. \n  split; apply col0_mori; basic_solver. \nQed.\n  \nGlobal Add Parametric Morphism : new_co with signature\n    eq ==> (@set_equiv actid) ==> (@set_equiv actid) ==>\n       (@inclusion actid) as new_co_more_impl.\nProof using.\n  ins. unfold new_co, new_col.\n  unfolder. ins. desc. red in H1.\n  destruct H, H0.\n  exists l. des.\n  { left. eapply col0_mori; eauto. }\n  apply pref_union_alt.\n  right. split.\n  { splits; vauto.\n    { by apply H. }\n    intro. apply H6. basic_solver. }\n  intro. apply H4. eapply col0_mori; eauto. \nQed.  \n\nGlobal Add Parametric Morphism : new_co with signature\n    eq ==> (@set_equiv actid) ==> (@set_equiv actid) ==>\n       (@same_relation actid) as new_co_more.\nProof using.\n  ins. split; [| symmetry in H, H0]; eapply new_co_more_impl; eauto.\nQed. \n\n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/simhelpers/CertCOhelper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23459465350336461}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Mem.\nRequire Import Prog.\nRequire Import List.\nRequire Import Word.\nRequire Import Rec.\nRequire Import BFile.\nRequire Import BasicProg.\nRequire Import Log.\nRequire Import Hoare.\nRequire Import Pred PredCrash.\nRequire Import Omega.\nRequire Import Rec.\nRequire Import Array.\nRequire Import ListPred.\nRequire Import GenSepN.\nRequire Import BFile.\nRequire Import FileRecArray.\nRequire Import Bool.\nRequire Import SepAuto.\nRequire Import Log.\nRequire Import Cache.\nRequire Import ListUtils.\nRequire Import AsyncDisk.\nRequire Import Errno.\nRequire Import DestructVarname.\nImport ListNotations.\nRequire HexString.\n\nSet Implicit Arguments.\n\n\n\nModule DIR.\n\n  Definition filename_len := (HexString.to_nat \"0x400\" (* 1024 *) - addrlen - addrlen).\n  Definition filename := word filename_len.\n\n\n  Module DentSig <: FileRASig.\n\n    Definition itemtype : Rec.type := Rec.RecF\n        ([(\"name\",  Rec.WordF filename_len);\n          (\"inum\",  Rec.WordF addrlen);\n          (\"valid\", Rec.WordF 1);\n          (\"isdir\", Rec.WordF 1);\n          (\"unused\", Rec.WordF (addrlen - 2))\n         ]).\n\n    Definition items_per_val := valulen / (Rec.len itemtype).\n\n    Theorem blocksz_ok : valulen = Rec.len (Rec.ArrayF itemtype items_per_val).\n    Proof.\n      unfold items_per_val; simpl.\n      rewrite valulen_is. apply Nat.eqb_eq.\n      compute; reflexivity.\n    Qed.\n\n  End DentSig.\n\n  Module Dent := FileRecArray DentSig.\n\n\n  (*************  dirent accessors  *)\n\n  Definition dent := Dent.Defs.item.\n  Definition dent0 := Dent.Defs.item0.\n\n  Fact resolve_selN_dent0 : forall l i d,\n    d = dent0 -> selN l i d = selN l i dent0.\n  Proof.\n    intros; subst; auto.\n  Qed.\n\n  Hint Rewrite resolve_selN_dent0 using reflexivity : defaults.\n\n\n  Definition bit2bool bit := if (bit_dec bit) then false else true.\n  Definition bool2bit bool : word 1 := if (bool_dec bool true) then $1 else $0.\n\n  Definition DEIsDir (de : dent) := Eval compute_rec in de :-> \"isdir\".\n  Definition DEValid (de : dent) := Eval compute_rec in de :-> \"valid\".\n  Definition DEName  (de : dent) := Eval compute_rec in de :-> \"name\".\n  Definition DEInum  (de : dent) := Eval compute_rec in # (de :-> \"inum\").\n  Definition mk_dent (name : filename) inum isdir : dent := Eval cbn in\n      dent0 :=> \"valid\" := $1 :=>\n                \"name\" := name :=>\n                \"inum\" := $ inum :=>\n                \"isdir\" := bool2bit isdir.\n\n  Definition is_dir   (de : dent) := bit2bool (DEIsDir de).\n  Definition is_valid (de : dent) := bit2bool (DEValid de).\n  Definition name_is  (n : filename) (de : dent) :=\n      if (weq n (DEName de)) then true else false.\n\n\n  (*************  rep invariant  *)\n\n  Definition dmatch (de: dent) : @pred filename (@weq filename_len) (addr * bool) :=\n    if bool_dec (is_valid de) false then emp\n    else (DEName de) |-> (DEInum de, is_dir de) * [[ DEInum de <> 0 ]].\n\n  Definition rep f dmap :=\n    exists delist,\n    (Dent.rep f delist)%pred (list2nmem (BFILE.BFData f)) /\\\n    listpred dmatch delist dmap.\n\n  Definition rep_macro Fm Fi m bxp ixp inum dmap ilist frees f ms sm : (@pred _ addr_eq_dec valuset) :=\n    (exists flist,\n    [[[ m ::: Fm * BFILE.rep bxp sm ixp flist ilist frees (BFILE.MSAllocC ms) (BFILE.MSCache ms) (BFILE.MSICache ms) (BFILE.MSDBlocks ms) ]]] *\n    [[[ flist ::: Fi * inum |-> f ]]] *\n    [[ rep f dmap ]])%pred.\n\n\n  (*************  program  *)\n\n\n  Definition lookup_f name de (_ : addr) := (is_valid de) && (name_is name de).\n\n  Definition ifind_lookup_f lxp ixp dnum name ms :=\n    Dent.ifind lxp ixp dnum (lookup_f name) ms.\n\n  Definition ifind_invalid lxp ixp dnum ms :=\n    Dent.ifind lxp ixp dnum (fun de _ => negb (is_valid de)) ms.\n\n  Definition lookup lxp ixp dnum name ms :=\n    let^ (ms, r) <- ifind_lookup_f lxp ixp dnum name ms;\n    match r with\n    | None => Ret ^(ms, None)\n    | Some (_, de) => Ret ^(ms, Some (DEInum de, is_dir de))\n    end.\n\n  Definition readent := (filename * (addr * bool))%type.\n\n  Definition readdir lxp ixp dnum ms :=\n    let^ (ms, dents) <- Dent.readall lxp ixp dnum ms;\n    let r := map (fun de => (DEName de, (DEInum de, is_dir de))) (filter is_valid dents) in\n    Ret ^(ms, r).\n\n  Definition unlink lxp ixp dnum name ms :=\n    let^ (ms, r) <- ifind_lookup_f lxp ixp dnum name ms;\n    match r with\n    | None => Ret ^(ms, 0, Err ENOENT)\n    | Some (ix, _) =>\n        ms <- Dent.put lxp ixp dnum ix dent0 ms;\n        Ret ^(ms, ix, OK tt)\n    end.\n\n  Definition link' lxp bxp ixp dnum name inum isdir ms :=\n    let de := mk_dent name inum isdir in\n    let^ (ms, r) <- ifind_invalid lxp ixp dnum ms;\n    match r with\n    | Some (ix, _) =>\n        ms <- Dent.put lxp ixp dnum ix de ms;\n        Ret ^(ms, ix+1, OK tt)\n    | None =>\n        let^ (ms, ok) <- Dent.extend lxp bxp ixp dnum de ms;\n        Ret ^(ms, 0, ok)\n    end.\n\n  (* link without hint *)\n  Definition link'' lxp bxp ixp dnum name inum isdir (ix0:addr) ms :=\n    let^ (ms, ix, r0) <- link' lxp bxp ixp dnum name inum isdir ms;\n    Ret ^(ms, ix, r0).\n\n  (* link with hint *)\n  Definition link lxp bxp ixp dnum name inum isdir ix0 ms :=\n    let de := mk_dent name inum isdir in\n    let^ (ms, len) <- BFILE.getlen lxp ixp dnum ms;\n    If (lt_dec ix0 (len * Dent.RA.items_per_val)) {\n      let^ (ms, res) <- Dent.get lxp ixp dnum ix0 ms;\n      match (is_valid res) with\n      | true =>\n        let^ (ms, ix, r0) <- link' lxp bxp ixp dnum name inum isdir ms;\n        Ret ^(ms, ix, r0)\n      | false => \n        ms <- Dent.put lxp ixp dnum ix0 de ms;\n        Ret ^(ms, ix0+1, OK tt)\n      end\n    } else {\n(* calling extend here slows down performance drastically.\n        let^ (ms, ok) <- Dent.extend lxp bxp ixp dnum de ms;\n        Ret ^(ms, ix0+1, ok)  *)\n      let^ (ms, ix, r0) <- link' lxp bxp ixp dnum name inum isdir ms;\n      Ret ^(ms, ix, r0) \n    }.\n\n  (*************  basic lemmas  *)\n\n\n  Fact bit2bool_0 : bit2bool $0 = false.\n  Proof.\n    unfold bit2bool; destruct (bit_dec $0); auto.\n    contradict e; apply natToWord_discriminate; auto.\n  Qed.\n\n  Fact bit2bool_1 : bit2bool $1 = true.\n  Proof.\n    unfold bit2bool; destruct (bit_dec $1); auto.\n    apply eq_sym in e; contradict e.\n    apply natToWord_discriminate; auto.\n  Qed.\n\n  Fact bit2bool_1_ne : bit2bool $1 <> false.\n  Proof. rewrite bit2bool_1; congruence. Qed.\n\n  Fact bit2bool_0_ne : bit2bool $0 <> true.\n  Proof. rewrite bit2bool_0; congruence. Qed.\n\n  Local Hint Resolve bit2bool_0 bit2bool_1 bit2bool_0_ne bit2bool_1_ne.\n\n  Lemma bit2bool2bit : forall b, bit2bool (bool2bit b) = b.\n  Proof.\n    destruct b; cbn; auto.\n  Qed.\n\n  Lemma bool2bit2bool : forall b,  bool2bit (bit2bool b) = b.\n  Proof.\n    unfold bit2bool; intros.\n    destruct (bit_dec b); subst; auto.\n  Qed.\n\n  Lemma lookup_f_ok: forall name de a,\n    lookup_f name de a = true ->\n    is_valid de = true /\\ DEName de = name.\n  Proof.\n    unfold lookup_f, name_is; intuition.\n    apply andb_true_iff in H; tauto.\n    destruct (weq name (DEName de)); auto.\n    contradict H.\n    rewrite andb_true_iff; easy.\n  Qed.\n\n  Lemma lookup_f_nf: forall name de a,\n    lookup_f name de a = false ->\n    is_valid de = false \\/ DEName de <> name.\n  Proof.\n    unfold lookup_f, name_is; intuition.\n    apply andb_false_iff in H; intuition.\n    destruct (weq name (DEName de)); intuition.\n  Qed.\n\n  Lemma lookup_notindomain': forall l ix name,\n    Forall (fun e => (lookup_f name e ix) = false) l\n    -> listpred dmatch l =p=> notindomain name.\n  Proof.\n    induction l; unfold pimpl; simpl; intros.\n    apply emp_notindomain; auto.\n    inversion H; subst.\n\n    destruct (Sumbool.sumbool_of_bool (is_valid a)).\n    destruct (lookup_f_nf name a ix); try congruence.\n    eapply notindomain_mem_except; eauto.\n    eapply ptsto_mem_except.\n    pred_apply; unfold dmatch at 1.\n    rewrite e, IHl by eauto; simpl; cancel.\n\n    pred_apply; rewrite IHl by eauto; cancel.\n    unfold dmatch; rewrite e; simpl; auto.\n  Qed.\n\n  Lemma lookup_notindomain: forall l name,\n    (forall i, i < length l -> lookup_f name (selN l i dent0) i = false) ->\n    listpred dmatch l =p=> notindomain name.\n  Proof.\n    intros.\n    eapply lookup_notindomain' with (ix := 0).\n    eapply selN_Forall; eauto.\n  Qed.\n\n\n\n  Definition dmatch_ex name (de: dent) : @pred filename (@weq filename_len) (addr * bool) :=\n    if (name_is name de) then emp\n    else dmatch de.\n\n  Definition dmatch_ex_same : forall de,\n    dmatch_ex (DEName de) de = emp.\n  Proof.\n    unfold dmatch_ex, name_is; intros.\n    destruct (weq (DEName de) (DEName de)); congruence.\n  Qed.\n\n  Definition dmatch_ex_diff : forall name de,\n    name <> (DEName de) ->\n    dmatch_ex name de = dmatch de.\n  Proof.\n    unfold dmatch_ex, name_is; intros.\n    destruct (weq name (DEName de)); congruence.\n  Qed.\n\n  Lemma dmatch_ex_ptsto : forall l name v,\n    (name |-> v * listpred dmatch l) \n    =p=> (name |-> v * listpred (dmatch_ex name) l).\n  Proof.\n    induction l; simpl; intros; auto.\n    unfold dmatch_ex at 1, dmatch at 1, dmatch at 2, name_is.\n    destruct (bool_dec (is_valid a) false).\n    destruct (weq name (DEName a));\n    rewrite sep_star_comm, sep_star_assoc;\n    setoid_rewrite sep_star_comm at 2; rewrite IHl; cancel.\n\n    destruct (weq name (DEName a)); subst.\n    unfold pimpl; intros; exfalso.\n    eapply ptsto_conflict_F with (m := m) (a := DEName a).\n    pred_apply; cancel.\n    eapply pimpl_trans with (b := (name |-> v * listpred dmatch l * [[DEInum a <> 0 ]] * _)%pred).\n    cancel. rewrite IHl. cancel.\n  Qed.\n\n  Lemma lookup_ptsto: forall l name ix,\n    ix < length l ->\n    lookup_f name (selN l ix dent0) ix = true ->\n    listpred dmatch l =p=> listpred (dmatch_ex name) l *\n       (name |-> (DEInum (selN l ix dent0), is_dir (selN l ix dent0))).\n  Proof.\n    induction l; intros.\n    simpl; inversion H.\n    pose proof (lookup_f_ok _ _ _ H0) as [Hx Hy].\n    destruct ix; subst; simpl in *.\n    unfold dmatch at 1; rewrite Hx, dmatch_ex_same; simpl.\n    eapply pimpl_trans with (b := (DEName a |-> _ * listpred dmatch l * _)%pred).\n    cancel. rewrite dmatch_ex_ptsto; cancel.\n\n    assert (ix < length l) by omega.\n    rewrite IHl; eauto; try solve [ cancel ].\n    unfold dmatch_ex at 2, dmatch, name_is.\n    destruct (bool_dec (is_valid _) false);\n    destruct (weq (DEName _) _); try solve [ cancel ].\n    rewrite e; repeat destruct_prod.\n    unfold pimpl; intros; exfalso.\n    eapply ptsto_conflict_F with (m := m) (a := DEName (w, (w0, (w1, (w2, (w3, u)))))).\n    pred_apply; cancel.\n  Qed.\n\n\n  Definition readmatch (de: readent) : @pred _ (@weq filename_len) _ :=\n    fst de |-> snd de.\n\n  Lemma readmatch_ok : forall l,\n    listpred dmatch l =p=> listpred readmatch\n      (map (fun de => (DEName de, (DEInum de, is_dir de))) (filter is_valid l)).\n  Proof.\n    induction l; simpl; auto.\n    unfold dmatch at 1; destruct (is_valid a); simpl.\n    rewrite IHl; cancel.\n    cancel.\n  Qed.\n\n\n  Lemma dmatch_dent0_emp :  dmatch dent0 = emp.\n  Proof.\n    unfold dmatch, dent0.\n    destruct (bool_dec (is_valid _) false); auto.\n    contradict n.\n    compute; auto.\n  Qed.\n\n  Lemma listpred_dmatch_dent0_emp : forall l i dmap,\n    listpred dmatch l dmap ->\n    is_valid (selN l i dent0) = true ->\n    i < length l ->\n    listpred dmatch (updN l i dent0) (mem_except dmap (DEName (selN l i dent0))).\n  Proof.\n    intros.\n    apply listpred_updN; auto.\n    rewrite dmatch_dent0_emp.\n    eapply ptsto_mem_except; pred_apply.\n    rewrite listpred_isolate by eauto.\n    unfold dmatch at 2; rewrite H0; simpl.\n    repeat cancel.\n  Qed.\n\n\n  Lemma dmatch_mk_dent : forall name inum isdir,\n    goodSize addrlen inum ->\n    dmatch (mk_dent name inum isdir) = (name |-> (inum, isdir) * [[ inum <> 0 ]])%pred.\n  Proof.\n    unfold dmatch, mk_dent, is_valid, is_dir; intros; cbn.\n    rewrite bit2bool_1, wordToNat_natToWord_idempotent', bit2bool2bit; auto.\n  Qed.\n\n  Lemma listpred_dmatch_mem_upd : forall l i dmap name inum isdir,\n    notindomain name dmap ->\n    negb (is_valid (selN l i dent0)) = true ->\n    listpred dmatch l dmap ->\n    i < length l -> inum <> 0 ->\n    goodSize addrlen inum ->\n    listpred dmatch (updN l i (mk_dent name inum isdir)) (Mem.upd dmap name (inum, isdir)).\n  Proof.\n    intros.\n    apply listpred_updN; auto.\n    rewrite dmatch_mk_dent by auto.\n    eapply pimpl_apply. cancel.\n    apply ptsto_upd_disjoint.\n    apply negb_true_iff in H0.\n    pred_apply.\n    setoid_rewrite listpred_isolate with (def := dent0) at 1; eauto.\n    unfold dmatch at 2; rewrite H0; cancel.\n    eauto.\n  Qed.\n\n  Lemma listpred_dmatch_repeat_dent0 : forall n,\n    listpred dmatch (repeat dent0 n) <=p=> emp.\n  Proof.\n    induction n; intros; simpl; eauto.\n    split; rewrite dmatch_dent0_emp, IHn; cancel.\n  Qed.\n\n  Lemma listpred_dmatch_ext_mem_upd : forall l dmap name inum isdir,\n    notindomain name dmap ->\n    (forall i, i < length l -> negb (is_valid (selN l i dent0)) = false) ->\n    listpred dmatch l dmap ->\n    goodSize addrlen inum -> inum <> 0 ->\n    listpred dmatch (l ++ @updN (Rec.data Dent.RA.itemtype) (Dent.Defs.block0) 0 (mk_dent name inum isdir))\n                    (Mem.upd dmap name (inum, isdir)).\n  Proof.\n    intros.\n    pose proof (Dent.Defs.items_per_val_gt_0).\n    erewrite <- Nat.sub_diag, <- updN_app2, Dent.Defs.block0_repeat by auto.\n    apply listpred_updN; auto.\n    rewrite app_length, repeat_length; omega.\n\n    replace (length l) with (length l + 0) by omega.\n    rewrite removeN_app_r, removeN_repeat, listpred_app by auto.\n    rewrite listpred_dmatch_repeat_dent0.\n    rewrite dmatch_mk_dent by auto.\n    eapply pimpl_apply. cancel.\n    apply ptsto_upd_disjoint; auto.\n  Qed.\n\n  Lemma listpred_dmatch_eq_mem : forall l m m',\n    listpred dmatch l m -> listpred dmatch l m' ->\n    m = m'.\n  Proof.\n    induction l; cbn; intros m m' H H'.\n    - apply emp_empty_mem_only in H.\n      apply emp_empty_mem_only in H'.\n      congruence.\n    - unfold dmatch at 1 in H.\n      unfold dmatch at 1 in H'.\n      destruct bool_dec.\n      apply IHl; pred_apply; cancel.\n      eapply pimpl_trans in H; [| cancel..].\n      eapply pimpl_trans in H'; [| cancel..].\n      revert H. revert H'.\n      unfold_sep_star.\n      intros. repeat deex.\n      match goal with H1 : (ptsto _ _ ?m), H2 : (ptsto _ _ ?m') |- _ =>\n        assert (m = m') by (eapply ptsto_complete; eauto); subst\n      end.\n      f_equal.\n      eauto.\n  Qed.\n\n  Lemma listpred_dmatch_notindomain: forall delist dmap name x,\n    notindomain name dmap ->\n    listpred dmatch delist (upd dmap name x) ->\n    listpred dmatch delist =p=> notindomain name * name |-> x.\n  Proof.\n    intros. intros m ?.\n    replace m with (upd dmap name x) in * by (eauto using listpred_dmatch_eq_mem).\n    apply ptsto_upd_disjoint; auto.\n  Qed.\n\n  Lemma dmatch_no_0_inum: forall f m, dmatch f m ->\n    forall name isdir, m name = Some (0, isdir) -> False.\n  Proof.\n    unfold dmatch.\n    intros; destruct bool_dec; destruct_lifts.\n    congruence.\n    unfold ptsto in *. intuition.\n    destruct (weq name (DEName f)); subst.\n    congruence.\n    denote (m name = Some _) as Hm.\n    denote (m _ = None) as Ha.\n    rewrite Ha in Hm by auto.\n    congruence.\n  Unshelve.\n    all: auto; repeat constructor.\n  Qed.\n\n  Lemma listpred_dmatch_no_0_inum: forall dmap m,\n    listpred dmatch dmap m ->\n    forall name isdir, m name = Some (0, isdir) -> False.\n  Proof.\n    induction dmap; cbn; intros.\n    congruence.\n    revert H.\n    unfold_sep_star.\n    intros. repeat deex.\n    unfold mem_union in *.\n    destruct (m1 name) eqn:?.\n    denote (Some _ = Some _) as Hs; inversion Hs; subst; clear Hs.\n    eauto using dmatch_no_0_inum.\n    eauto.\n  Unshelve.\n    all: eauto.\n  Qed.\n\n  (*************  correctness theorems  *)\n\n  Notation MSLL := BFILE.MSLL.\n  Notation MSAlloc := BFILE.MSAlloc.\n  Notation MSCache := BFILE.MSCache.\n  Notation MSAllocC := BFILE.MSAllocC.\n  Notation MSIAllocC := BFILE.MSIAllocC.\n  Notation MSDBlocks := BFILE.MSDBlocks.\n\n  Theorem lookup_ok : forall lxp bxp ixp dnum name ms,\n    {< F Fm Fi m0 sm m dmap ilist frees f,\n    PRE:hm LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms) sm hm *\n           rep_macro Fm Fi m bxp ixp dnum dmap ilist frees f ms sm\n    POST:hm' RET:^(ms',r)\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms') sm hm' *\n           rep_macro Fm Fi m bxp ixp dnum dmap ilist frees f ms' sm *\n           [[ MSAlloc ms' = MSAlloc ms ]] *\n           [[ MSAllocC ms' = MSAllocC ms ]] *\n         ( [[ r = None /\\ notindomain name dmap ]] \\/\n           exists inum isdir Fd,\n           [[ r = Some (inum, isdir) /\\ inum <> 0 /\\\n                   (Fd * name |-> (inum, isdir))%pred dmap ]])\n    CRASH:hm'  exists ms',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms') sm hm'\n    >} lookup lxp ixp dnum name ms.\n  Proof.\n    unfold lookup, ifind_lookup_f, rep_macro, rep.\n    safestep.\n    safestep.\n    or_r; cancel.\n    eapply listpred_dmatch_no_0_inum; eauto.\n    eapply ptsto_valid'.\n    denote DEInum as Hd.\n    erewrite selN_inb in Hd by auto.\n    rewrite <- Hd.\n    eapply lookup_ptsto; eauto.\n    eapply lookup_ptsto; eauto.\n    or_l; cancel.\n    apply lookup_notindomain; auto.\n  Unshelve.\n    all: try (exact false || exact emp).\n    all: eauto.\n  Qed.\n\n\n  Theorem readdir_ok : forall lxp bxp ixp dnum ms,\n    {< F Fm Fi m0 sm m dmap ilist frees f,\n    PRE:hm   LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms) sm hm *\n             rep_macro Fm Fi m bxp ixp dnum dmap ilist frees f ms sm\n    POST:hm' RET:^(ms',r)\n             LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms') sm hm' *\n             rep_macro Fm Fi m bxp ixp dnum dmap ilist frees f ms' sm *\n             [[ listpred readmatch r dmap ]] *\n             [[ MSAlloc ms' = MSAlloc ms ]] *\n             [[ MSCache ms' = MSCache ms ]] *\n             [[ MSAllocC ms' = MSAllocC ms ]] *\n             [[ MSIAllocC ms' = MSIAllocC ms ]] *\n             [[ MSDBlocks ms' = MSDBlocks ms ]]\n    CRASH:hm'  exists ms',\n           LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms') sm hm'\n    >} readdir lxp ixp dnum ms.\n  Proof.\n    unfold readdir, rep_macro, rep.\n    safestep.\n    step.\n    apply readmatch_ok.\n  Qed.\n\n  Local Hint Resolve mem_except_notindomain.\n\n  Theorem unlink_ok : forall lxp bxp ixp dnum name ms,\n    {< F Fm Fi m0 sm m dmap ilist frees,\n    PRE:hm   LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms) sm hm *\n             exists f, rep_macro Fm Fi m bxp ixp dnum dmap ilist frees f ms sm\n    POST:hm' RET:^(ms', hint, r) exists m' dmap',\n             LOG.rep lxp F (LOG.ActiveTxn m0 m') (MSLL ms') sm hm' *\n             exists f', rep_macro Fm Fi m' bxp ixp dnum dmap' ilist frees f' ms' sm *\n             [[ dmap' = mem_except dmap name ]] *\n             [[ notindomain name dmap' ]] *\n             [[ r = OK tt -> indomain name dmap ]] *\n             [[ MSAlloc ms' = MSAlloc ms ]] *\n             [[ MSAllocC ms' = MSAllocC ms ]] *\n             [[ MSIAllocC ms' = MSIAllocC ms ]]\n    CRASH:hm' LOG.intact lxp F m0 sm hm'\n    >} unlink lxp ixp dnum name ms.\n  Proof.\n    unfold unlink, ifind_lookup_f, rep_macro, rep.\n    step.\n    step.\n\n    apply Dent.Defs.item0_wellformed.\n    msalloc_eq.\n\n    denote (lookup_f) as HH.\n    pose proof (lookup_f_ok _ _ _ HH) as [Hx Hy].\n\n    step.\n\n    eexists; split; eauto.\n    apply listpred_dmatch_dent0_emp; auto.\n\n    rewrite lookup_ptsto by eauto.\n    unfold pimpl; intros.\n    eapply sep_star_ptsto_indomain.\n    pred_apply; cancel.\n\n    rewrite <- notindomain_mem_eq; auto.\n    eapply lookup_notindomain; eauto.\n    eapply lookup_notindomain; eauto.\n\n  Unshelve.\n    all: easy.\n  Qed.\n\n  Theorem link'_ok : forall lxp bxp ixp dnum name inum isdir ms,\n    {< F Fm Fi m0 sm m dmap ilist frees,\n    PRE:hm   LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms) sm hm *\n             exists f, rep_macro Fm Fi m bxp ixp dnum dmap ilist frees f ms sm *\n             [[ notindomain name dmap ]] *\n             [[ goodSize addrlen inum ]] *\n             [[ inum <> 0 ]]\n    POST:hm' RET:^(ms', ixhint', r) exists m',\n             [[ MSAlloc ms' = MSAlloc ms ]] *\n             [[ MSIAllocC ms' = MSIAllocC ms ]] *\n           (([[ isError r ]] * LOG.rep lxp F (LOG.ActiveTxn m0 m') (MSLL ms') sm hm')\n        \\/  ([[ r = OK tt ]] *\n             exists dmap' Fd ilist' frees' f',\n             LOG.rep lxp F (LOG.ActiveTxn m0 m') (MSLL ms') sm hm' *\n             rep_macro Fm Fi m' bxp ixp dnum dmap' ilist' frees' f' ms' sm *\n             [[ dmap' = Mem.upd dmap name (inum, isdir) ]] *\n             [[ (Fd * name |-> (inum, isdir))%pred dmap' ]] *\n             [[ (Fd dmap /\\ notindomain name dmap) ]] *\n             [[ BFILE.ilist_safe ilist  (BFILE.pick_balloc frees  (MSAlloc ms'))\n                                 ilist' (BFILE.pick_balloc frees' (MSAlloc ms')) ]] *\n             [[ BFILE.treeseq_ilist_safe dnum ilist ilist' ]] ))\n    CRASH:hm' LOG.intact lxp F m0 sm hm'\n    >} link' lxp bxp ixp dnum name inum isdir ms.\n  Proof.\n    unfold link', ifind_lookup_f, ifind_invalid, rep_macro, rep.\n    step.\n    step; msalloc_eq.\n\n    (* case 1: use avail entry *)\n    cbv; tauto.\n    step; msalloc_eq.\n    or_r; cancel.\n    eexists; split; eauto.\n    apply listpred_dmatch_mem_upd; auto.\n    eapply ptsto_upd_disjoint; eauto.\n    apply BFILE.ilist_safe_refl.\n    apply BFILE.treeseq_ilist_safe_refl.\n\n    (* case 2: extend new entry *)\n    cbv; tauto.\n\n    step; msalloc_eq.\n    or_r; cancel; eauto.\n    eexists; split; eauto.\n    eapply listpred_dmatch_ext_mem_upd; eauto.\n    eapply ptsto_upd_disjoint; eauto.\n  Unshelve.\n    all: eauto.\n  Qed.\n\n  Hint Extern 1 ({{ _ }} Bind (link' _ _ _ _ _ _ _ _) _) => apply link'_ok : prog.\n\n  Theorem link_ok : forall lxp bxp ixp dnum name inum isdir ixhint ms,\n    {< F Fm Fi m0 sm m dmap ilist frees,\n    PRE:hm   LOG.rep lxp F (LOG.ActiveTxn m0 m) (MSLL ms) sm hm *\n             exists f, rep_macro Fm Fi m bxp ixp dnum dmap ilist frees f ms sm *\n             [[ notindomain name dmap ]] *\n             [[ goodSize addrlen inum ]] *\n             [[ inum <> 0 ]]\n    POST:hm' RET:^(ms', ixhint', r) exists m',\n             [[ MSAlloc ms' = MSAlloc ms ]] *\n             [[ MSIAllocC ms' = MSIAllocC ms ]] *\n           (([[ isError r ]] * LOG.rep lxp F (LOG.ActiveTxn m0 m') (MSLL ms') sm hm')\n        \\/  ([[ r = OK tt ]] * \n             exists dmap' Fd ilist' frees' f',\n             LOG.rep lxp F (LOG.ActiveTxn m0 m') (MSLL ms') sm hm' *\n             rep_macro Fm Fi m' bxp ixp dnum dmap' ilist' frees' f' ms' sm *\n             [[ dmap' = Mem.upd dmap name (inum, isdir) ]] *\n             [[ (Fd * name |-> (inum, isdir))%pred dmap' ]] *\n             [[ (Fd dmap /\\ notindomain name dmap) ]] *\n             [[ BFILE.ilist_safe ilist  (BFILE.pick_balloc frees  (MSAlloc ms'))\n                                 ilist' (BFILE.pick_balloc frees' (MSAlloc ms')) ]] *\n             [[ BFILE.treeseq_ilist_safe dnum ilist ilist' ]] ))\n    CRASH:hm' LOG.intact lxp F m0 sm hm'\n    >} link lxp bxp ixp dnum name inum isdir ixhint ms.\n  Proof.\n    unfold link, rep_macro, rep.\n    step.\n    step; msalloc_eq.\n\n    (* case 1: try entry hint *)\n    step.\n    erewrite Dent.items_length_ok with (xp := f) (m := (list2nmem (BFILE.BFData f))).\n    unfold Dent.RA.RALen. auto.\n    pred_apply; cancel.\n    destruct is_valid eqn:?.\n    (* working around a 'not found' Coq bug, probably #4202 in simpl *)\n    prestep. unfold rep_macro, rep. norm. cancel.\n    intuition ((pred_apply; cancel) || eauto).\n    step.\n    or_r. cancel.\n    eauto.\n    eapply listpred_dmatch_notindomain; eauto.\n    eauto.\n    cancel.\n\n    (* case 2: use hinted entry *)\n    step; msalloc_eq.\n    erewrite Dent.items_length_ok with (xp := f) (m := (list2nmem (BFILE.BFData f))).\n    unfold Dent.RA.RALen. auto.\n    pred_apply; cancel.\n    cbv; tauto.\n    step.\n    or_r; cancel.\n    eexists; split; eauto.\n    apply listpred_dmatch_mem_upd; auto.\n    rewrite Bool.negb_true_iff; auto.\n    erewrite Dent.items_length_ok with (xp := f) (m := (list2nmem (BFILE.BFData f))).\n    unfold Dent.RA.RALen. auto.\n    pred_apply; cancel.\n    eapply ptsto_upd_disjoint; auto.\n    apply BFILE.ilist_safe_refl.\n    apply BFILE.treeseq_ilist_safe_refl.\n\n    (* case 3: hint was out of bounds, so ignore it *)\n    (* working around a 'not found' Coq bug, probably #4202 in simpl *)\n    prestep. unfold rep_macro, rep. norm. cancel.\n    intuition ((pred_apply; cancel) || eauto).\n    step.\n    or_r. cancel.\n    eauto.\n    eapply listpred_dmatch_notindomain; eauto.\n    eauto.\n    cancel.\n  Unshelve.\n    all: eauto.\n  Qed.\n\n\n  Hint Extern 1 ({{_}} Bind (lookup _ _ _ _ _) _) => apply lookup_ok : prog.\n  Hint Extern 1 ({{_}} Bind (unlink _ _ _ _ _) _) => apply unlink_ok : prog.\n  Hint Extern 1 ({{_}} Bind (link _ _ _ _ _ _ _ _ _) _) => apply link_ok : prog.\n  Hint Extern 1 ({{_}} Bind (readdir _ _ _ _) _) => apply readdir_ok : prog.\n\n  Hint Extern 0 (okToUnify (rep ?f _) (rep ?f _)) => constructor : okToUnify.\n\n\n  (*************  Lemma for callers *)\n\n  Theorem dmatch_complete : forall de m1 m2, dmatch de m1 -> dmatch de m2 -> m1 = m2.\n  Proof.\n    unfold dmatch, is_dir; intros.\n    destruct (bool_dec (is_valid de) false).\n    apply emp_complete; eauto.\n    eapply ptsto_complete; pred_apply; cancel.\n  Qed.\n\n  Lemma listpred_dmatch_eq : forall l m1 m2,\n    listpred dmatch l m1\n    -> listpred dmatch l m2\n    -> m1 = m2.\n  Proof.\n    induction l; simpl; auto.\n    apply emp_complete; auto.\n    intros m1 m2.\n    unfold_sep_star; intuition.\n    repeat deex; f_equal.\n    eapply dmatch_complete; eauto.\n    eapply IHl; eauto.\n  Qed.\n\n  Lemma rep_mem_eq : forall f m1 m2,\n    rep f m1 ->\n    rep f m2 ->\n    m1 = m2.\n  Proof.\n    unfold rep; intros.\n    repeat deex.\n    pose proof (Dent.rep_items_eq H0 H1); subst.\n    eapply listpred_dmatch_eq; eauto.\n  Qed.\n\n  Theorem bfile0_empty : rep BFILE.bfile0 empty_mem.\n  Proof.\n    unfold rep, Dent.rep, Dent.items_valid.\n    exists nil; firstorder.\n    exists nil; simpl.\n    setoid_rewrite Dent.Defs.ipack_nil.\n    assert (emp (list2nmem (@nil valuset))) by firstorder.\n    pred_apply; cancel.\n    apply Forall_nil.\n  Qed.\n\n  Theorem rep_no_0_inum: forall f m, rep f m ->\n    forall name isdir, m name = Some (0, isdir) -> False.\n  Proof.\n    unfold rep. intros. repeat deex.\n    eauto using listpred_dmatch_no_0_inum.\n  Qed.\n\n  Theorem crash_eq : forall f f' m1 m2,\n    BFILE.file_crash f f' ->\n    rep f m1 ->\n    rep f' m2 ->\n    m1 = m2.\n  Proof.\n    intros.\n    apply eq_sym.\n    eapply rep_mem_eq; eauto.\n\n    unfold rep in *.\n    repeat deex.\n    eexists; intuition eauto.\n    assert (delist0 = delist).\n    eapply Dent.file_crash_rep_eq; eauto.\n    subst; eauto.\n  Qed.\n\n  Theorem crash_rep : forall f f' m,\n    BFILE.file_crash f f' ->\n    rep f m ->\n    rep f' m.\n  Proof.\n    unfold rep; intros.\n    repeat deex.\n    eexists; intuition eauto.\n    eapply Dent.file_crash_rep; eauto.\n  Qed.\n\nEnd DIR.\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/Dir.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.2345045635442024}}
{"text": " Require Import Coqlib AList.\nRequire Import STS.\nRequire Import Behavior.\nRequire Import ModSem.\nRequire Import Skeleton.\nRequire Import PCM.\nFrom Ordinal Require Export Ordinal Arithmetic Inaccessible.\nRequire Import Any.\nRequire Import IRed.\n\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Maps\n     Data.Map.FMapAList.\n\nSet Implicit Arguments.\n\n\n\n(*** TODO: move to ITreelib, and replace raw definitions with this ***)\nDefinition trivial_Handler `{E -< F}: Handler E F := fun T X => trigger X.\n\nInductive ord: Type :=\n| ord_pure (n: Ord.t)\n| ord_top\n.\n\nDefinition is_pure (o: ord): bool := match o with | ord_pure _ => true | _ => false end.\n\nDefinition ord_lt (next cur: ord): Prop :=\n  match next, cur with\n  | ord_pure next, ord_pure cur => (next < cur)%ord\n  | _, ord_top => True\n  | _, _ => False\n  end\n.\n\n(**\n(defface hi-light-green-b\n  '((((min-colors 88)) (:weight bold :foreground \"dark magenta\"))\n    (t (:weight bold :foreground \"dark magenta\")))\n  \"Face for hi-lock mode.\"\n  :group 'hi-lock-faces)\n\n **)\n\n\nSection PSEUDOTYPING.\n\n(*** execute following commands in emacs (by C-x C-e)\n     (progn (highlight-phrase \"Any\" 'hi-red-b) (highlight-phrase \"Any_src\" 'hi-green-b) (highlight-phrase \"Any_tgt\" 'hi-blue-b)\n            (highlight-phrase \"Any_mid\" 'hi-light-green-b)\n            (highlight-phrase \"Y\" 'hi-green-b) (highlight-phrase \"Z\" 'hi-green-b)) ***)\nLet Any_src := Any.t. (*** src argument (e.g., List nat) ***)\nLet Any_mid := Any.t. (*** src argument (e.g., List nat) ***)\nLet Any_tgt := Any.t. (*** tgt argument (i.e., list val) ***)\n\nRequire Import IPM.\n\nSection FSPEC.\n  Context `{Σ: GRA.t}.\n\n  (*** spec table ***)\n  Record fspec: Type := mk_fspec {\n    meta: Type;\n    measure: meta -> ord;\n    precond: option mname -> meta -> Any.t -> Any_tgt -> iProp; (*** meta-variable -> new logical arg -> current logical arg -> resource arg -> Prop ***)\n    postcond: option mname -> meta -> Any.t -> Any_tgt -> iProp; (*** meta-variable -> new logical ret -> current logical ret -> resource ret -> Prop ***)\n  }\n  .\n\n  Definition mk (X AA AR: Type) (measure: X -> ord) (precond: X -> AA -> Any_tgt -> iProp) (postcond: X -> AR -> Any_tgt -> iProp) :=\n    @mk_fspec\n      X\n      measure\n      (fun _ x arg_src arg_tgt => (∃ (aa: AA), ⌜arg_src = aa↑⌝ ∧ precond x aa arg_tgt)%I)\n      (fun _ x ret_src ret_tgt => (∃ (ar: AR), ⌜ret_src = ar↑⌝ ∧ postcond x ar ret_tgt)%I)\n  .\n\n  Definition fspec_trivial: fspec :=\n    mk_fspec (meta:=unit) (fun _ => ord_top) (fun _ _ argh argl => (⌜argh = argl⌝: iProp)%I)\n             (fun _ _ reth retl => (⌜reth = retl⌝: iProp)%I)\n  .\nEnd FSPEC.\n\n\nSection PROOF.\n  (* Context {myRA} `{@GRA.inG myRA Σ}. *)\n  Context {Σ: GRA.t}.\n  Let GURA: URA.t := GRA.to_URA Σ.\n  Local Existing Instance GURA.\n\n\n  Definition mput E `{pE -< E} `{eventE -< E} (mr: Σ): itree E unit :=\n    st <- trigger PGet;; '(mp, _) <- ((Any.split st)?);;\n    trigger (PPut (Any.pair mp mr↑))\n  .\n\n  Definition mget E `{pE -< E} `{eventE -< E}: itree E Σ :=\n    st <- trigger PGet;; '(_, mr) <- ((Any.split st)?);;\n    mr↓?\n  .\n\n  Definition pput E `{pE -< E} `{eventE -< E} (mp: Any.t): itree E unit :=\n    st <- trigger PGet;; '(_, mr) <- ((Any.split st)?);;\n    trigger (PPut (Any.pair mp mr))\n  .\n\n  Definition pget E `{pE -< E} `{eventE -< E}: itree E Any.t :=\n    st <- trigger PGet;; '(mp, _) <- ((Any.split st)?);;\n    Ret mp\n  .\n\n\n\n  Definition ASSUME (Cond: Any.t -> Any.t -> iProp) (valp: Any.t): stateT Σ (itree Es) Any.t :=\n    fun fr =>\n      '(cres, ctx) <- trigger (Take (Σ * Σ));;\n      mr <- mget;;\n      assume(URA.wf (cres ⋅ fr ⋅ ctx ⋅ mr));;;\n      valv <- trigger (Take Any.t);;\n      assume(Cond valv valp cres);;;\n      Ret (ctx, valv)\n  .\n\n  Definition ASSERT (Cond: Any.t -> Any.t -> iProp) (valv: Any.t): stateT Σ (itree Es) Any.t :=\n    fun ctx =>\n      '(cres, fr, mr) <- trigger (Choose (Σ * Σ * Σ));;\n      mput mr;;;\n      guarantee(URA.wf (cres ⋅ fr ⋅ ctx ⋅ mr));;;\n      valp <- trigger (Choose Any.t);;\n      guarantee(Cond valv valp cres);;;\n      Ret (fr, valp)\n  .\n\n\n  Definition HoareCall\n             (mn: mname)\n             (tbr: bool)\n             (ord_cur: ord)\n             (fsp: fspec):\n    gname -> Any.t -> stateT (Σ) (itree Es) Any.t :=\n    fun fn varg_src ctx =>\n\n      x <- trigger (Choose fsp.(meta));;\n      '(fr, varg_tgt) <- (ASSERT (fsp.(precond) (Some mn) x) varg_src ctx);;\n\n      let ord_next := fsp.(measure) x in\n      guarantee(ord_lt ord_next ord_cur /\\ (tbr = true -> is_pure ord_next) /\\ (tbr = false -> ord_next = ord_top));;;\n\n      vret_tgt <- trigger (Call fn varg_tgt);;\n\n      ASSUME (fsp.(postcond) (Some mn) x) vret_tgt fr\n  .\n\nEnd PROOF.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n(*** TODO: Move to Coqlib. TODO: Somehow use case_ ??? ***)\n(* Definition map_fst A0 A1 B (f: A0 -> A1): (A0 * B) -> (A1 * B) := fun '(a, b) => (f a, b). *)\n(* Definition map_snd A B0 B1 (f: B0 -> B1): (A * B0) -> (A * B1) := fun '(a, b) => (a, f b). *)\n\nVariant hCallE: Type -> Type :=\n| hCall (tbr: bool) (fn: gname) (varg_src: Any_src): hCallE Any_src\n(*** tbr == to be removed ***)\n.\n\nVariant hAPCE: Type -> Type :=\n| hAPC: hAPCE unit\n.\n\nNotation Es' := (hCallE +' pE +' eventE).\n\nDefinition hEs := (hAPCE +' Es).\n\nDefinition hcall {X Y} (fn: gname) (varg: X): itree (hCallE +' pE +' eventE) Y :=\n  vret <- trigger (hCall false fn varg↑);; vret <- vret↓ǃ;; Ret vret.\n\nProgram Fixpoint _APC (at_most: Ord.t) {wf Ord.lt at_most}: itree Es' unit :=\n  break <- trigger (Choose _);;\n  if break: bool\n  then Ret tt\n  else\n    n <- trigger (Choose Ord.t);;\n    trigger (Choose (n < at_most)%ord);;;\n    '(fn, varg) <- trigger (Choose _);;\n    trigger (hCall true fn varg);;;\n    _APC n.\nNext Obligation.\n  i. auto.\nQed.\nNext Obligation.\n  eapply Ord.lt_well_founded.\nQed.\n\nDefinition APC: itree Es' unit :=\n  at_most <- trigger (Choose _);;\n  _APC at_most\n.\n\nLemma unfold_APC:\n  forall at_most, _APC at_most =\n                  break <- trigger (Choose _);;\n                  if break: bool\n                  then Ret tt\n                  else\n                    n <- trigger (Choose Ord.t);;\n                    guarantee (n < at_most)%ord;;;\n                    '(fn, varg) <- trigger (Choose _);;\n                    trigger (hCall true fn varg);;;\n                    _APC n.\nProof.\n  i. unfold _APC. rewrite Fix_eq; eauto.\n  { repeat f_equal. extensionality break. destruct break; ss.\n    repeat f_equal. extensionality n.\n    unfold guarantee. rewrite bind_bind.\n    repeat f_equal. extensionality p.\n    rewrite bind_ret_l. repeat f_equal. extensionality x. destruct x. auto. }\n  { i. replace g with f; auto. extensionality o. eapply H. }\nQed.\nGlobal Opaque _APC.\n\n\n\n\n\nSection CANCEL.\n\n  Context `{Σ: GRA.t}.\n\n\n  Record fspecbody: Type := mk_specbody {\n    fsb_fspec:> fspec;\n    fsb_body: (option mname * Any.t) -> itree (hAPCE +' Es) Any.t;\n  }\n  .\n\n  (*** argument remains the same ***)\n  (* Definition mk_simple (mn: string) {X: Type} (P: X -> Any_tgt -> Σ -> ord -> Prop) (Q: X -> Any_tgt -> Σ -> Prop): fspec. *)\n  (*   econs. *)\n  (*   { apply mn. } *)\n  (*   { i. apply (P X0 X2 X3 H /\\ X1↑ = X2). } *)\n  (*   { i. apply (Q X0 X2 X3 /\\ X1↑ = X2). } *)\n  (* Unshelve. *)\n  (*   apply (list val). *)\n  (*   apply (val). *)\n  (* Defined. *)\n  Definition mk_simple {X: Type} (DPQ: X -> ord * (Any_tgt -> iProp) * (Any_tgt -> iProp)): fspec :=\n    mk_fspec (fst ∘ fst ∘ DPQ)\n             (fun _ x y a => (((snd ∘ fst ∘ DPQ) x a: iProp) ∧ ⌜y = a⌝)%I)\n             (fun _ x z a => (((snd ∘ DPQ) x a: iProp) ∧ ⌜z = a⌝)%I)\n  .\n\n  Section INTERP.\n  (* Variable stb: gname -> option fspec. *)\n  (*** TODO: I wanted to use above definiton, but doing so makes defining ms_src hard ***)\n  (*** We can fix this by making ModSemL.fnsems to a function, but doing so will change the type of\n       ModSemL.add to predicate (t -> t -> t -> Prop), not function.\n       - Maybe not. I thought one needed to check uniqueness of gname at the \"add\",\n         but that might not be the case.\n         We may define fnsems: string -> option (list val -> itree Es val).\n         When adding two ms, it is pointwise addition, and addition of (option A) will yield None when both are Some.\n ***)\n  (*** TODO: try above idea; if it fails, document it; and refactor below with alist ***)\n\n  Variable mn: mname.\n  Variable stb: gname -> option fspec.\n\n  Definition handle_hAPCE_src: hAPCE ~> itree Es :=\n    fun _ '(hAPC) => Ret tt.\n\n  Definition interp_hEs_src: itree hEs ~> itree Es :=\n    interp (case_ handle_hAPCE_src trivial_Handler)\n  .\n\n  Definition body_to_src {X} (body: X -> itree hEs Any.t): X -> itree Es Any.t :=\n    (@interp_hEs_src _) ∘ body\n  .\n\n  Definition fun_to_src (body: (option mname * Any.t) -> itree hEs Any.t): ((option mname * Any.t) -> itree Es Any_src) :=\n    (body_to_src body)\n  .\n\n\n\n  Definition handle_hAPCE_tgt: hAPCE ~> itree Es' :=\n    fun _ '(hAPC) => APC.\n\n  Definition handle_callE_hEs: callE ~> itree Es' :=\n    fun _ '(Call fn arg) => trigger (hCall false fn arg).\n\n  Definition interp_hEs_tgt: itree (hAPCE +' Es) ~> itree Es' :=\n    interp (case_ (bif:=sum1) (handle_hAPCE_tgt)\n                  (case_ (bif:=sum1) (handle_callE_hEs)\n                         trivial_Handler)).\n\n\n  Definition handle_hCallE_mid2: hCallE ~> itree Es :=\n    fun _ '(hCall tbr fn varg_src) =>\n      match tbr with\n      | true => tau;; trigger (Choose _)\n      | false => trigger (Call fn varg_src)\n      end\n  .\n\n  Definition interp_hCallE_mid2: itree Es' ~> itree Es :=\n    interp (case_ (bif:=sum1) (handle_hCallE_mid2)\n                  trivial_Handler)\n  .\n\n  Definition body_to_mid2 {X} (body: X -> itree (hCallE +' pE +' eventE) Any.t): X -> itree Es Any.t :=\n    (@interp_hCallE_mid2 _) ∘ body\n  .\n\n  Definition fun_to_mid2 (body: (option mname * Any.t) -> itree hEs Any.t): (option mname * Any_src -> itree Es Any_src) :=\n    body_to_mid2 ((@interp_hEs_tgt _) ∘ body)\n  .\n\n\n  Definition handle_hCallE_mid (ord_cur: ord): hCallE ~> itree Es :=\n    fun _ '(hCall tbr fn varg_src) =>\n      tau;;\n      f <- (stb fn)ǃ;; guarantee (tbr = true -> ~ (forall x, f.(measure) x = ord_top));;;\n      ord_next <- (if tbr then o0 <- trigger (Choose _);; Ret (ord_pure o0) else Ret ord_top);;\n      guarantee(ord_lt ord_next ord_cur);;;\n      let varg_mid: Any_mid := Any.pair ord_next↑ varg_src in\n      trigger (Call fn varg_mid)\n  .\n\n  Definition interp_hCallE_mid (ord_cur: ord): itree Es' ~> itree Es :=\n    interp (case_ (bif:=sum1) (handle_hCallE_mid ord_cur)\n                  ((fun T X => trigger X): _ ~> itree Es))\n  .\n\n  Definition body_to_mid (ord_cur: ord) {X} (body: X -> itree (hCallE +' pE +' eventE) Any.t): X -> itree Es Any.t :=\n    fun varg_mid => interp_hCallE_mid ord_cur (body varg_mid)\n  .\n\n  Definition fun_to_mid (body: (option mname * Any.t) -> itree hEs Any.t): (option mname * Any_mid -> itree Es Any_src) :=\n    fun '(mn, ord_varg_src) =>\n      '(ord_cur, varg_src) <- (Any.split ord_varg_src)ǃ;; ord_cur <- ord_cur↓ǃ;;\n      interp_hCallE_mid ord_cur (interp_hEs_tgt\n                                   (match ord_cur with\n                                    | ord_pure n => _ <- trigger hAPC;; trigger (Choose _)\n                                    | _ => body (mn, varg_src)\n                                    end)).\n\n  Definition handle_hCallE_tgt (ord_cur: ord): hCallE ~> stateT (Σ) (itree Es) :=\n    fun _ '(hCall tbr fn varg_src) 'ctx =>\n      f <- (stb fn)ǃ;;\n      HoareCall mn tbr ord_cur f fn varg_src ctx\n  .\n\n  Definition handle_pE_tgt: pE ~> itree Es :=\n    Eval unfold pput, pget in\n      (fun _ e =>\n         match e with\n         | PPut st => pput st\n         | PGet => pget\n         end).\n\n  Definition interp_hCallE_tgt (ord_cur: ord): itree Es' ~> stateT Σ (itree Es) :=\n    interp_state (case_ (bif:=sum1) (handle_hCallE_tgt ord_cur)\n                        (case_ (bif:=sum1)\n                               ((fun T X s => x <- handle_pE_tgt X;; Ret (s, x)): _ ~> stateT Σ (itree Es))\n                               ((fun T X s => x <- trigger X;; Ret (s, x)): _ ~> stateT Σ (itree Es))))\n  .\n\n  Definition body_to_tgt (ord_cur: ord)\n             {X} (body: X -> itree (hCallE +' pE +' eventE) Any_src): X -> stateT Σ (itree Es) Any_src :=\n    (@interp_hCallE_tgt ord_cur _) ∘ body.\n\n\n  Definition HoareFun\n             {X: Type}\n             (D: X -> ord)\n             (P: option mname -> X -> Any.t -> Any_tgt -> iProp)\n             (Q: option mname -> X -> Any.t -> Any_tgt -> iProp)\n             (body: (option mname * Any.t) -> itree hEs Any.t): option mname * Any_tgt -> itree Es Any_tgt := fun '(mn_caller, varg_tgt) =>\n    x <- trigger (Take X);;\n    '(ctx, varg_src) <- (ASSUME (P mn_caller x) varg_tgt ε);;\n\n    let ord_cur := D x in\n    '(ctx, vret_src) <- interp_hCallE_tgt\n                          ord_cur\n                          (interp_hEs_tgt\n                             (match ord_cur with\n                              | ord_pure n => _ <- trigger hAPC;; trigger (Choose _)\n                              | _ => body (mn_caller, varg_src)\n                              end)) ctx;;\n\n    '(_, vret_tgt) <- (ASSERT (Q mn_caller x) vret_src ctx);;\n    Ret vret_tgt\n  .\n\n  Definition fun_to_tgt (sb: fspecbody): (option mname * Any_tgt -> itree Es Any_tgt) :=\n    let fs: fspec := sb.(fsb_fspec) in\n    (HoareFun (fs.(measure)) (fs.(precond)) (fs.(postcond)) (sb.(fsb_body)))\n  .\n\n(*** NOTE:\nbody can execute eventE events.\nNotably, this implies it can also execute UB.\nWith this flexibility, the client code can naturally be included in our \"type-checking\" framework.\nAlso, note that body cannot execute \"rE\" on its own. This is intended.\n\nNOTE: we can allow normal \"callE\" in the body too, but we need to ensure that it does not call \"HoareFun\".\nIf this feature is needed; we can extend it then. At the moment, I will only allow hCallE.\n***)\n\n\n  Definition HoareFunArg\n             {X: Type}\n             (P: option mname -> X -> Any.t -> Any_tgt -> iProp):\n    option mname * Any_tgt -> itree Es ((Σ) * (option mname * X * Any.t)) := fun '(mn_caller, varg_tgt) =>\n    x <- trigger (Take X);;\n    '(ctx, varg_src) <- (ASSUME (P mn_caller x) varg_tgt ε);;\n    Ret (ctx, (mn_caller, x, varg_src))\n  .\n\n  Definition HoareFunRet\n             {X: Type}\n             (Q: option mname -> X -> Any.t -> Any_tgt -> iProp):\n    option mname -> X -> ((Σ) * Any.t) -> itree Es Any_tgt := fun mn x '(ctx, vret_src) =>\n    '(_, vret_tgt) <- (ASSERT (Q mn x) vret_src ctx);;\n    Ret vret_tgt\n  .\n\n  Lemma HoareFun_parse\n        {X: Type}\n        (D: X -> ord)\n        (P: option mname -> X -> Any.t -> Any_tgt -> iProp)\n        (Q: option mname -> X -> Any.t -> Any_tgt -> iProp)\n        (body: (option mname * Any.t) -> itree hEs Any.t)\n        (varg_tgt: option mname * Any_tgt)\n    :\n      HoareFun D P Q body varg_tgt =\n      '(ctx, (mn_caller, x, varg_src)) <- HoareFunArg P varg_tgt;;\n      interp_hCallE_tgt (D x)\n                        (interp_hEs_tgt\n                           (match D x with\n                            | ord_pure n => _ <- trigger hAPC;; trigger (Choose _)\n                            | _ => body (mn_caller, varg_src)\n                            end)) ctx >>= (HoareFunRet Q mn_caller x).\n  Proof.\n    unfold HoareFun, HoareFunArg, HoareFunRet. grind.\n  Qed.\n\n  End INTERP.\n\n\n\n  Variable md_tgt: ModL.t.\n  Let ms_tgt: ModSemL.t := (ModL.get_modsem md_tgt md_tgt.(ModL.sk)).\n\n  Variable sbtb: alist gname fspecbody.\n  Let stb: alist gname fspec := List.map (fun '(gn, fsb) => (gn, fsb_fspec fsb)) sbtb.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nEnd CANCEL.\n\nEnd PSEUDOTYPING.\n\n\n\n\n\n\n\nModule SModSem.\nSection SMODSEM.\n\n  Context `{Σ: GRA.t}.\n\n  Record t: Type := mk {\n    fnsems: list (gname * fspecbody);\n    mn: mname;\n    initial_mr: Σ;\n    initial_st: Any.t;\n  }\n  .\n\n  Definition transl (tr: mname -> fspecbody -> (option mname * Any.t -> itree Es Any.t)) (mst: t -> Any.t) (ms: t): ModSem.t := {|\n    ModSem.fnsems := List.map (fun '(fn, sb) => (fn, tr ms.(mn) sb)) ms.(fnsems);\n    ModSem.mn := ms.(mn);\n    ModSem.initial_st := mst ms;\n  |}\n  .\n\n  Definition to_src (ms: t): ModSem.t := transl (fun mn => fun_to_src ∘ fsb_body) initial_st ms.\n  Definition to_mid (stb: gname -> option fspec) (ms: t): ModSem.t := transl (fun mn => fun_to_mid stb ∘ fsb_body) initial_st ms.\n  Definition to_mid2 (stb: gname -> option fspec) (ms: t): ModSem.t := transl (fun mn => fun_to_mid2 ∘ fsb_body) initial_st ms.\n  Definition to_tgt (stb: gname -> option fspec) (ms: t): ModSem.t := transl (fun mn => fun_to_tgt mn stb) (fun ms => Any.pair ms.(initial_st) ms.(initial_mr)↑) ms.\n\n  Definition main (mainpre: Any.t -> iProp) (mainbody: (option mname * Any.t) -> itree hEs Any.t): t := {|\n      fnsems := [(\"main\", (mk_specbody (mk_simple (fun (_: unit) => (ord_top, mainpre, fun _ => (⌜True⌝: iProp)%I))) mainbody))];\n      mn := \"Main\";\n      initial_mr := ε;\n      initial_st := tt↑;\n    |}\n  .\n\nEnd SMODSEM.\nEnd SModSem.\n\n\n\nModule SMod.\nSection SMOD.\n\n  Context `{Σ: GRA.t}.\n\n  Record t: Type := mk {\n    get_modsem: Sk.t -> SModSem.t;\n    sk: Sk.t;\n  }\n  .\n\n  Definition transl (tr: Sk.t -> mname -> fspecbody -> (option mname * Any.t -> itree Es Any.t)) (mst: SModSem.t -> Any.t) (md: t): Mod.t := {|\n    Mod.get_modsem := fun sk => SModSem.transl (tr sk) mst (md.(get_modsem) sk);\n    Mod.sk := md.(sk);\n  |}\n  .\n\n  Definition to_src (md: t): Mod.t := transl (fun _ _ => fun_to_src ∘ fsb_body) SModSem.initial_st md.\n  Definition to_mid (stb: gname -> option fspec) (md: t): Mod.t := transl (fun _ _ => fun_to_mid stb ∘ fsb_body) SModSem.initial_st md.\n  Definition to_mid2 (stb: gname -> option fspec) (md: t): Mod.t := transl (fun _ _ => fun_to_mid2 ∘ fsb_body) SModSem.initial_st md.\n  Definition to_tgt (stb: Sk.t -> gname -> option fspec) (md: t): Mod.t :=\n    transl (fun sk mn => fun_to_tgt mn (stb sk)) (fun ms => Any.pair ms.(SModSem.initial_st) ms.(SModSem.initial_mr)↑) md.\n\n\n  Definition get_stb (mds: list t): Sk.t -> alist gname fspec :=\n    fun sk => map (map_snd fsb_fspec) (flat_map (SModSem.fnsems ∘ (flip get_modsem sk)) mds).\n\n  Definition get_sk (mds: list t): Sk.t :=\n    Sk.sort (fold_right Sk.add Sk.unit (List.map sk mds)).\n\n  Definition get_initial_mrs (mds: list t): Sk.t -> Σ :=\n    fun sk => fold_left (⋅) (List.map (SModSem.initial_mr ∘ (flip get_modsem sk)) mds) ε.\n\n\n  (* Definition transl (tr: SModSem.t -> ModSem.t) (md: t): Mod.t := {| *)\n  (*   Mod.get_modsem := (SModSem.transl tr) ∘ md.(get_modsem); *)\n  (*   Mod.sk := md.(sk); *)\n  (* |} *)\n  (* . *)\n\n  (* Definition to_src (md: t): Mod.t := transl SModSem.to_src md. *)\n  (* Definition to_mid (md: t): Mod.t := transl SModSem.to_mid md. *)\n  (* Definition to_tgt (stb: list (gname * fspec)) (md: t): Mod.t := transl (SModSem.to_tgt stb) md. *)\n  Lemma to_src_comm: forall sk smd,\n      (SModSem.to_src) (get_modsem smd sk) = (to_src smd).(Mod.get_modsem) sk.\n  Proof. refl. Qed.\n  Lemma to_mid_comm: forall sk stb smd,\n      (SModSem.to_mid stb) (get_modsem smd sk) = (to_mid stb smd).(Mod.get_modsem) sk.\n  Proof. refl. Qed.\n  Lemma to_tgt_comm: forall sk stb smd,\n      (SModSem.to_tgt (stb sk)) (get_modsem smd sk) = (to_tgt stb smd).(Mod.get_modsem) sk.\n  Proof. refl. Qed.\n\n\n\n\n\n\n\n\n\n\n  (* Definition l_bind A B (x: list A) (f: A -> list B): list B := List.flat_map f x. *)\n  (* Definition l_ret A (a: A): list A := [a]. *)\n\n  Declare Scope l_monad_scope.\n  Local Open Scope l_monad_scope.\n  Notation \"'do' X <- A ; B\" := (List.flat_map (fun X => B) A) : l_monad_scope.\n  Notation \"'do' ' X <- A ; B\" := (List.flat_map (fun _x => match _x with | X => B end) A) : l_monad_scope.\n  Notation \"'ret'\" := (fun X => [X]) (at level 60) : l_monad_scope.\n\n  Lemma unconcat\n        A (xs: list A)\n    :\n      List.concat (List.map (fun x => [x]) xs) = xs\n  .\n  Proof.\n    induction xs; ii; ss. f_equal; ss.\n  Qed.\n\n  Lemma red_do_ret A B (xs: list A) (f: A -> B)\n    :\n      (do x <- xs; ret (f x)) = List.map f xs\n  .\n  Proof.\n    rewrite flat_map_concat_map.\n    erewrite <- List.map_map with (f:=f) (g:=ret).\n    rewrite unconcat. ss.\n  Qed.\n\n  Lemma red_do_ret2 A0 A1 B (xs: list (A0 * A1)) (f: A0 -> A1 -> B)\n    :\n      (do '(x0, x1) <- xs; ret (f x0 x1)) = List.map (fun '(x0, x1) => f x0 x1) xs\n  .\n  Proof.\n    induction xs; ss. rewrite IHxs. destruct a; ss.\n  Qed.\n\n\n\n\n\n\n\n\n\n\n\n\n  Local Opaque Mod.add_list.\n\n  Lemma transl_sk\n        tr0 mr0 mds\n    :\n      <<SK: ModL.sk (Mod.add_list (List.map (transl tr0 mr0) mds)) = fold_right Sk.add Sk.unit (List.map sk mds)>>\n  .\n  Proof.\n    induction mds; ii; ss.\n    rewrite Mod.add_list_cons. ss. r. f_equal. ss.\n  Qed.\n\n  Lemma transl_sk_stable\n        tr0 tr1 mr0 mr1 mds\n    :\n      ModL.sk (Mod.add_list (List.map (transl tr0 mr0) mds)) =\n      ModL.sk (Mod.add_list (List.map (transl tr1 mr1) mds))\n  .\n  Proof. rewrite ! transl_sk. ss. Qed.\n\n  Definition load_fnsems (sk: Sk.t) (mds: list t) (tr0: mname -> fspecbody -> option mname * Any.t -> itree Es Any.t) :=\n    do md <- mds;\n    let ms := (get_modsem md sk) in\n      (do '(fn, fsb) <- ms.(SModSem.fnsems);\n       let fsem := tr0 ms.(SModSem.mn) fsb in\n       ret (fn, transl_all (T:=_) ms.(SModSem.mn) ∘ fsem))\n  .\n\n  Let transl_fnsems_aux\n        tr0 mr0 mds\n        (sk: Sk.t)\n    :\n      (ModSemL.fnsems (ModL.get_modsem (Mod.add_list (List.map (transl tr0 mr0) mds)) sk)) =\n      (load_fnsems sk mds (tr0 sk))\n  .\n  Proof.\n    induction mds; ii; ss.\n    rewrite Mod.add_list_cons. cbn. f_equal; ss.\n    rewrite ! List.map_map.\n\n    rewrite flat_map_concat_map.\n    replace (fun _x: string * fspecbody => let (fn, fsb) := _x in [(fn, transl_all (T:=_) (SModSem.mn (get_modsem a sk)) ∘ (tr0 sk (get_modsem a sk).(SModSem.mn) fsb))]) with\n        (ret ∘ (fun _x: string * fspecbody => let (fn, fsb) := _x in (fn, transl_all (T:=_) (SModSem.mn (get_modsem a sk)) ∘ (tr0 sk (get_modsem a sk).(SModSem.mn) fsb))));\n      cycle 1.\n    { apply func_ext. i. des_ifs. }\n    erewrite <- List.map_map with (g:=ret).\n    rewrite unconcat.\n    apply map_ext. ii. des_ifs.\n  Qed.\n\n  Lemma transl_fnsems\n        tr0 mr0 mds\n    :\n      (ModSemL.fnsems (ModL.enclose (Mod.add_list (List.map (transl tr0 mr0) mds)))) =\n      (load_fnsems (Sk.sort (List.fold_right Sk.add Sk.unit (List.map sk mds))) mds (tr0 (Sk.sort (List.fold_right Sk.add Sk.unit (List.map sk mds)))))\n  .\n  Proof.\n    unfold ModL.enclose.\n    rewrite transl_fnsems_aux. do 2 f_equal. rewrite transl_sk. ss.\n    rewrite transl_sk. auto.\n  Qed.\n\n  Lemma flat_map_assoc\n        A B C\n        (f: A -> list B)\n        (g: B -> list C)\n        (xs: list A)\n    :\n      (do y <- (do x <- xs; f x); g y) =\n      (do x <- xs; do y <- (f x); g y)\n  .\n  Proof.\n    induction xs; ii; ss.\n    rewrite ! flat_map_concat_map in *. rewrite ! map_app. rewrite ! concat_app. f_equal; ss.\n  Qed.\n\n  Lemma transl_fnsems_stable\n        tr0 tr1 mr0 mr1 mds\n    :\n      List.map fst (ModL.enclose (Mod.add_list (List.map (transl tr0 mr0) mds))).(ModSemL.fnsems) =\n      List.map fst (ModL.enclose (Mod.add_list (List.map (transl tr1 mr1) mds))).(ModSemL.fnsems)\n  .\n  Proof.\n    rewrite ! transl_fnsems.\n    unfold load_fnsems.\n    rewrite <- ! red_do_ret.\n    rewrite ! flat_map_assoc. eapply flat_map_ext. i.\n    rewrite ! flat_map_assoc. eapply flat_map_ext. i.\n    des_ifs.\n  Qed.\n\n\n\n\n  Definition load_initial_mrs {A} (sk: Sk.t) (mds: list t) (mr0: SModSem.t -> A): list (string * A) :=\n    do md <- mds;\n    let ms := (get_modsem md sk) in\n    ret (ms.(SModSem.mn), mr0 ms)\n  .\n\n  Let transl_initial_mrs_aux\n        tr0 mr0 mds\n        (sk: Sk.t)\n    :\n      (ModSemL.initial_mrs (ModL.get_modsem (Mod.add_list (List.map (transl tr0 mr0) mds)) sk)) =\n      (load_initial_mrs sk mds mr0)\n  .\n  Proof.\n    induction mds; ii; ss.\n    rewrite Mod.add_list_cons. cbn. f_equal; ss.\n  Qed.\n\n  Lemma transl_initial_mrs\n        tr0 mr0 mds\n    :\n      (ModSemL.initial_mrs (ModL.enclose (Mod.add_list (List.map (transl tr0 mr0) mds)))) =\n      (load_initial_mrs (Sk.sort (List.fold_right Sk.add Sk.unit (List.map sk mds))) mds mr0)\n  .\n  Proof.\n    unfold ModL.enclose.\n    rewrite transl_initial_mrs_aux. do 2 f_equal. rewrite transl_sk. ss.\n  Qed.\n\n  Lemma transl_stable_mn\n        tr0 tr1 mr0 mr1 mds\n    :\n      List.map fst (ModL.enclose (Mod.add_list (List.map (transl tr0 mr0) mds))).(ModSemL.initial_mrs) =\n      List.map fst (ModL.enclose (Mod.add_list (List.map (transl tr1 mr1) mds))).(ModSemL.initial_mrs)\n  .\n  Proof.\n    rewrite ! transl_initial_mrs. unfold load_initial_mrs. rewrite <- ! red_do_ret.\n    rewrite ! flat_map_assoc. eapply flat_map_ext. i. ss.\n  Qed.\n\n  Definition main (mainpre: Any.t -> iProp) (mainbody: (option mname * Any.t) -> itree hEs Any.t): t := {|\n    get_modsem := fun _ => (SModSem.main mainpre mainbody);\n    sk := Sk.unit;\n  |}\n  .\n\nEnd SMOD.\nEnd SMod.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n  Hint Resolve Ord.lt_le_lt Ord.le_lt_lt OrdArith.lt_add_r OrdArith.le_add_l\n       OrdArith.le_add_r Ord.lt_le\n       Ord.lt_S\n       Ord.S_lt\n       Ord.S_supremum\n       Ord.S_pos\n    : ord.\n  Hint Resolve Ord.le_trans Ord.lt_trans: ord_trans.\n  Hint Resolve OrdArith.add_base_l OrdArith.add_base_r: ord_proj.\n\n  Global Opaque EventsL.interp_Es.\n\n\n\n\n\n\n  Require Import Red.\n\n  Ltac interp_red := erewrite interp_vis ||\n                              erewrite interp_ret ||\n                              erewrite interp_tau ||\n                              erewrite interp_trigger ||\n                              erewrite interp_bind.\n\n  (* TODO: remove it *)\n  Ltac interp_red2 := rewrite interp_vis ||\n                              rewrite interp_ret ||\n                              rewrite interp_tau ||\n                              rewrite interp_trigger ||\n                              rewrite interp_bind.\n\n  Ltac _red_itree f :=\n    match goal with\n    | [ |- ?itr >>= _ = _] =>\n      match itr with\n      | _ >>= _ =>\n        instantiate (f:=_continue); apply bind_bind; fail\n      | Tau _ =>\n        instantiate (f:=_break); apply bind_tau; fail\n      | Ret _ =>\n        instantiate (f:=_continue); apply bind_ret_l; fail\n      | _ =>\n        fail\n      end\n    | _ => fail\n    end.\n\n\n\nSection AUX.\n\nContext `{Σ: GRA.t}.\n(* itree reduction *)\nLemma interp_tgt_bind\n      (R S: Type)\n      (s : itree (hCallE +' pE +' eventE) R) (k : R -> itree (hCallE +' pE +' eventE) S)\n      mn stb o ctx\n  :\n    (interp_hCallE_tgt mn stb o (s >>= k)) ctx\n    =\n    st <- interp_hCallE_tgt mn stb o s ctx;; interp_hCallE_tgt mn stb o (k st.2) st.1.\nProof.\n  unfold interp_hCallE_tgt in *. eapply interp_state_bind.\nQed.\n\nLemma interp_tgt_tau mn stb o ctx\n      (U: Type)\n      (t : itree _ U)\n  :\n    (interp_hCallE_tgt mn stb o (Tau t) ctx)\n    =\n    (Tau (interp_hCallE_tgt mn stb o t ctx)).\nProof.\n  unfold interp_hCallE_tgt in *. eapply interp_state_tau.\nQed.\n\nLemma interp_tgt_ret mn stb o ctx\n      (U: Type)\n      (t: U)\n  :\n    (interp_hCallE_tgt mn stb o (Ret t) ctx)\n    =\n    Ret (ctx, t).\nProof.\n  unfold interp_hCallE_tgt in *. eapply interp_state_ret.\nQed.\n\nLemma interp_tgt_triggerp mn stb o ctx\n      (R: Type)\n      (i: pE R)\n  :\n    (interp_hCallE_tgt mn stb o (trigger i) ctx)\n    =\n    (handle_pE_tgt i >>= (fun r => tau;; Ret (ctx, r))).\nProof.\n  unfold interp_hCallE_tgt. rewrite interp_state_trigger. cbn. grind.\nQed.\n\nLemma interp_tgt_triggere mn stb o ctx\n      (R: Type)\n      (i: eventE R)\n  :\n    (interp_hCallE_tgt mn stb o (trigger i) ctx)\n    =\n    (trigger i >>= (fun r => tau;; Ret (ctx, r))).\nProof.\n  unfold interp_hCallE_tgt. rewrite interp_state_trigger. cbn. grind.\nQed.\n\nLemma interp_tgt_hcall mn stb o ctx\n      (R: Type)\n      (i: hCallE R)\n  :\n    (interp_hCallE_tgt mn stb o (trigger i) ctx)\n    =\n    ((handle_hCallE_tgt mn stb o i ctx) >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hCallE_tgt in *. rewrite interp_state_trigger. cbn. auto.\nQed.\n\nLemma interp_tgt_triggerUB mn stb o ctx\n      (R: Type)\n  :\n    (interp_hCallE_tgt mn stb o (triggerUB) ctx)\n    =\n    triggerUB (A:=Σ*R).\nProof.\n  unfold interp_hCallE_tgt, triggerUB in *. rewrite unfold_interp_state. cbn. grind.\nQed.\n\nLemma interp_tgt_triggerNB mn stb o ctx\n      (R: Type)\n  :\n    (interp_hCallE_tgt mn stb o (triggerNB) ctx)\n    =\n    triggerNB (A:=Σ*R).\nProof.\n  unfold interp_hCallE_tgt, triggerNB in *. rewrite unfold_interp_state. cbn. grind.\nQed.\n\nLemma interp_tgt_unwrapU mn stb o ctx\n      (R: Type)\n      (i: option R)\n  :\n    (interp_hCallE_tgt mn stb o (@unwrapU (hCallE +' pE +' eventE) _ _ i) ctx)\n    =\n    r <- (unwrapU i);; Ret (ctx, r).\nProof.\n  unfold interp_hCallE_tgt, unwrapU in *. des_ifs.\n  { etrans.\n    { eapply interp_tgt_ret. }\n    { grind. }\n  }\n  { etrans.\n    { eapply interp_tgt_triggerUB. }\n    { unfold triggerUB. grind. }\n  }\nQed.\n\nLemma interp_tgt_unwrapN mn stb o ctx\n      (R: Type)\n      (i: option R)\n  :\n    (interp_hCallE_tgt mn stb o (@unwrapN (hCallE +' pE +' eventE) _ _ i) ctx)\n    =\n    r <- (unwrapN i);; Ret (ctx, r).\nProof.\n  unfold interp_hCallE_tgt, unwrapN in *. des_ifs.\n  { etrans.\n    { eapply interp_tgt_ret. }\n    { grind. }\n  }\n  { etrans.\n    { eapply interp_tgt_triggerNB. }\n    { unfold triggerNB. grind. }\n  }\nQed.\n\nLemma interp_tgt_assume mn stb o ctx\n      P\n  :\n    (interp_hCallE_tgt mn stb o (assume P) ctx)\n    =\n    (assume P;;; tau;; Ret (ctx, tt))\n.\nProof.\n  unfold assume. rewrite interp_tgt_bind. rewrite interp_tgt_triggere. grind. eapply interp_tgt_ret.\nQed.\n\nLemma interp_tgt_guarantee mn stb o ctx\n      P\n  :\n    (interp_hCallE_tgt mn stb o (guarantee P) ctx)\n    =\n    (guarantee P;;; tau;; Ret (ctx, tt)).\nProof.\n  unfold guarantee. rewrite interp_tgt_bind. rewrite interp_tgt_triggere. grind. eapply interp_tgt_ret.\nQed.\n\nLemma interp_tgt_ext mn stb o ctx\n      R (itr0 itr1: itree _ R)\n      (EQ: itr0 = itr1)\n  :\n    (interp_hCallE_tgt mn stb o itr0 ctx)\n    =\n    (interp_hCallE_tgt mn stb o itr1 ctx)\n.\nProof. subst; et. Qed.\n\nGlobal Program Instance interp_hCallE_tgt_rdb: red_database (mk_box (@interp_hCallE_tgt)) :=\n  mk_rdb\n    1\n    (mk_box interp_tgt_bind)\n    (mk_box interp_tgt_tau)\n    (mk_box interp_tgt_ret)\n    (mk_box interp_tgt_hcall)\n    (mk_box interp_tgt_triggere)\n    (mk_box interp_tgt_triggerp)\n    (mk_box interp_tgt_triggerp)\n    (mk_box interp_tgt_triggerUB)\n    (mk_box interp_tgt_triggerNB)\n    (mk_box interp_tgt_unwrapU)\n    (mk_box interp_tgt_unwrapN)\n    (mk_box interp_tgt_assume)\n    (mk_box interp_tgt_guarantee)\n    (mk_box interp_tgt_ext)\n.\n\nEnd AUX.\n\n\n\nSection AUX.\n\nContext `{Σ: GRA.t}.\nVariable stb: gname -> option fspec.\n(* itree reduction *)\nLemma interp_mid_bind\n      (R S: Type)\n      (s : itree (hCallE +' pE +' eventE) R) (k : R -> itree (hCallE +' pE +' eventE) S)\n      o\n  :\n    (interp_hCallE_mid stb o (s >>= k))\n    =\n    ((interp_hCallE_mid stb o s) >>= (fun r => interp_hCallE_mid stb o (k r))).\nProof.\n  unfold interp_hCallE_mid in *. grind.\nQed.\n\nLemma interp_mid_tau o\n      (U: Type)\n      (t : itree _ U)\n  :\n    (interp_hCallE_mid stb o (Tau t))\n    =\n    (Tau (interp_hCallE_mid stb o t)).\nProof.\n  unfold interp_hCallE_mid in *. grind.\nQed.\n\nLemma interp_mid_ret o\n      (U: Type)\n      (t: U)\n  :\n    ((interp_hCallE_mid stb o (Ret t)))\n    =\n    Ret t.\nProof.\n  unfold interp_hCallE_mid in *. grind.\nQed.\n\nLemma interp_mid_triggerp o\n      (R: Type)\n      (i: pE R)\n  :\n    (interp_hCallE_mid stb o (trigger i))\n    =\n    (trigger i >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hCallE_mid in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_mid_triggere o\n      (R: Type)\n      (i: eventE R)\n  :\n    (interp_hCallE_mid stb o (trigger i))\n    =\n    (trigger i >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hCallE_mid in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_mid_hcall o\n      (R: Type)\n      (i: hCallE R)\n  :\n    (interp_hCallE_mid stb o (trigger i))\n    =\n    ((handle_hCallE_mid stb o i) >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hCallE_mid in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_mid_triggerUB o\n      (R: Type)\n  :\n    (interp_hCallE_mid stb o (triggerUB))\n    =\n    triggerUB (A:=R).\nProof.\n  unfold interp_hCallE_mid, triggerUB in *. rewrite unfold_interp. cbn. grind.\nQed.\n\nLemma interp_mid_triggerNB o\n      (R: Type)\n  :\n    (interp_hCallE_mid stb o (triggerNB))\n    =\n    triggerNB (A:=R).\nProof.\n  unfold interp_hCallE_mid, triggerNB in *. rewrite unfold_interp. cbn. grind.\nQed.\n\nLemma interp_mid_unwrapU o\n      (R: Type)\n      (i: option R)\n  :\n    (interp_hCallE_mid stb o (@unwrapU (hCallE +' pE +' eventE) _ _ i))\n    =\n    (unwrapU i).\nProof.\n  unfold interp_hCallE_mid, unwrapU in *. des_ifs.\n  { etrans.\n    { eapply interp_mid_ret. }\n    { grind. }\n  }\n  { etrans.\n    { eapply interp_mid_triggerUB. }\n    { unfold triggerUB. grind. }\n  }\nQed.\n\nLemma interp_mid_unwrapN o\n      (R: Type)\n      (i: option R)\n  :\n    (interp_hCallE_mid stb o (@unwrapN (hCallE +' pE +' eventE) _ _ i))\n    =\n    (unwrapN i).\nProof.\n  unfold interp_hCallE_mid, unwrapN in *. des_ifs.\n  { etrans.\n    { eapply interp_mid_ret. }\n    { grind. }\n  }\n  { etrans.\n    { eapply interp_mid_triggerNB. }\n    { unfold triggerNB. grind. }\n  }\nQed.\n\nLemma interp_mid_assume o\n      P\n  :\n    (interp_hCallE_mid stb o (assume P))\n    =\n    (assume P;;; tau;; Ret tt)\n.\nProof.\n  unfold assume. rewrite interp_mid_bind. rewrite interp_mid_triggere. grind. eapply interp_mid_ret.\nQed.\n\nLemma interp_mid_guarantee o\n      P\n  :\n    (interp_hCallE_mid stb o (guarantee P))\n    =\n    (guarantee P;;; tau;; Ret tt).\nProof.\n  unfold guarantee. rewrite interp_mid_bind. rewrite interp_mid_triggere. grind. eapply interp_mid_ret.\nQed.\n\nLemma interp_mid_ext o\n      R (itr0 itr1: itree _ R)\n      (EQ: itr0 = itr1)\n  :\n    (interp_hCallE_mid stb o itr0)\n    =\n    (interp_hCallE_mid stb o itr1)\n.\nProof. subst; et. Qed.\n\nEnd AUX.\n\n\nGlobal Program Instance interp_hCallE_mid_rdb `{Σ: GRA.t}: red_database (mk_box (@interp_hCallE_mid)) :=\n  mk_rdb\n    0\n    (mk_box interp_mid_bind)\n    (mk_box interp_mid_tau)\n    (mk_box interp_mid_ret)\n    (mk_box interp_mid_hcall)\n    (mk_box interp_mid_triggere)\n    (mk_box interp_mid_triggerp)\n    (mk_box interp_mid_triggerp)\n    (mk_box interp_mid_triggerUB)\n    (mk_box interp_mid_triggerNB)\n    (mk_box interp_mid_unwrapU)\n    (mk_box interp_mid_unwrapN)\n    (mk_box interp_mid_assume)\n    (mk_box interp_mid_guarantee)\n    (mk_box interp_mid_ext)\n.\n\nSection AUX.\n\nContext `{Σ: GRA.t}.\nVariable stb: gname -> option fspec.\n(* itree reduction *)\nLemma interp_mid2_bind\n      (R S: Type)\n      (s : itree (hCallE +' pE +' eventE) R) (k : R -> itree (hCallE +' pE +' eventE) S)\n  :\n    (interp_hCallE_mid2 (s >>= k))\n    =\n    ((interp_hCallE_mid2 s) >>= (fun r => interp_hCallE_mid2 (k r))).\nProof.\n  unfold interp_hCallE_mid2 in *. grind.\nQed.\n\nLemma interp_mid2_tau\n      (U: Type)\n      (t : itree _ U)\n  :\n    (interp_hCallE_mid2 (Tau t))\n    =\n    (Tau (interp_hCallE_mid2 t)).\nProof.\n  unfold interp_hCallE_mid2 in *. grind.\nQed.\n\nLemma interp_mid2_ret\n      (U: Type)\n      (t: U)\n  :\n    ((interp_hCallE_mid2 (Ret t)))\n    =\n    Ret t.\nProof.\n  unfold interp_hCallE_mid2 in *. grind.\nQed.\n\nLemma interp_mid2_triggerp\n      (R: Type)\n      (i: pE R)\n  :\n    (interp_hCallE_mid2 (trigger i))\n    =\n    (trigger i >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hCallE_mid2 in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_mid2_triggere\n      (R: Type)\n      (i: eventE R)\n  :\n    (interp_hCallE_mid2 (trigger i))\n    =\n    (trigger i >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hCallE_mid2 in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_mid2_hcall\n      (R: Type)\n      (i: hCallE R)\n  :\n    (interp_hCallE_mid2 (trigger i))\n    =\n    ((handle_hCallE_mid2 i) >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hCallE_mid2 in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_mid2_triggerUB\n      (R: Type)\n  :\n    (interp_hCallE_mid2 (triggerUB))\n    =\n    triggerUB (A:=R).\nProof.\n  unfold interp_hCallE_mid2, triggerUB in *. rewrite unfold_interp. cbn. grind.\nQed.\n\nLemma interp_mid2_triggerNB\n      (R: Type)\n  :\n    (interp_hCallE_mid2 (triggerNB))\n    =\n    triggerNB (A:=R).\nProof.\n  unfold interp_hCallE_mid2, triggerNB in *. rewrite unfold_interp. cbn. grind.\nQed.\n\nLemma interp_mid2_unwrapU\n      (R: Type)\n      (i: option R)\n  :\n    (interp_hCallE_mid2 (@unwrapU (hCallE +' pE +' eventE) _ _ i))\n    =\n    (unwrapU i).\nProof.\n  unfold interp_hCallE_mid2, unwrapU in *. des_ifs.\n  { etrans.\n    { eapply interp_mid2_ret. }\n    { grind. }\n  }\n  { etrans.\n    { eapply interp_mid2_triggerUB. }\n    { unfold triggerUB. grind. }\n  }\nQed.\n\nLemma interp_mid2_unwrapN\n      (R: Type)\n      (i: option R)\n  :\n    (interp_hCallE_mid2 (@unwrapN (hCallE +' pE +' eventE) _ _ i))\n    =\n    (unwrapN i).\nProof.\n  unfold interp_hCallE_mid2, unwrapN in *. des_ifs.\n  { etrans.\n    { eapply interp_mid2_ret. }\n    { grind. }\n  }\n  { etrans.\n    { eapply interp_mid2_triggerNB. }\n    { unfold triggerNB. grind. }\n  }\nQed.\n\nLemma interp_mid2_assume\n      P\n  :\n    (interp_hCallE_mid2 (assume P))\n    =\n    (assume P;;; tau;; Ret tt)\n.\nProof.\n  unfold assume. rewrite interp_mid2_bind. rewrite interp_mid2_triggere. grind. eapply interp_mid2_ret.\nQed.\n\nLemma interp_mid2_guarantee\n      P\n  :\n    (interp_hCallE_mid2 (guarantee P))\n    =\n    (guarantee P;;; tau;; Ret tt).\nProof.\n  unfold guarantee. rewrite interp_mid2_bind. rewrite interp_mid2_triggere. grind. eapply interp_mid2_ret.\nQed.\n\nLemma interp_mid2_ext\n      R (itr0 itr1: itree _ R)\n      (EQ: itr0 = itr1)\n  :\n    (interp_hCallE_mid2 itr0)\n    =\n    (interp_hCallE_mid2 itr1)\n.\nProof. subst; et. Qed.\n\nEnd AUX.\n\n\nGlobal Program Instance interp_hCallE_mid2_rdb `{Σ: GRA.t}: red_database (mk_box (@interp_hCallE_mid2)) :=\n  mk_rdb\n    0\n    (mk_box interp_mid2_bind)\n    (mk_box interp_mid2_tau)\n    (mk_box interp_mid2_ret)\n    (mk_box interp_mid2_hcall)\n    (mk_box interp_mid2_triggere)\n    (mk_box interp_mid2_triggerp)\n    (mk_box interp_mid2_triggerp)\n    (mk_box interp_mid2_triggerUB)\n    (mk_box interp_mid2_triggerNB)\n    (mk_box interp_mid2_unwrapU)\n    (mk_box interp_mid2_unwrapN)\n    (mk_box interp_mid2_assume)\n    (mk_box interp_mid2_guarantee)\n    (mk_box interp_mid2_ext)\n.\n\n\n\nSection AUX.\n\nContext `{Σ: GRA.t}.\n(* itree reduction *)\nLemma interp_src_bind\n      (R S: Type)\n      (s : itree hEs R) (k : R -> itree hEs S)\n  :\n    (interp_hEs_src (s >>= k))\n    =\n    ((interp_hEs_src s) >>= (fun r => interp_hEs_src (k r))).\nProof.\n  unfold interp_hEs_src in *. grind.\nQed.\n\nLemma interp_src_tau\n      (U: Type)\n      (t : itree _ U)\n  :\n    (interp_hEs_src (Tau t))\n    =\n    (Tau (interp_hEs_src t)).\nProof.\n  unfold interp_hEs_src in *. grind.\nQed.\n\nLemma interp_src_ret\n      (U: Type)\n      (t: U)\n  :\n    ((interp_hEs_src (Ret t)))\n    =\n    Ret t.\nProof.\n  unfold interp_hEs_src in *. grind.\nQed.\n\nLemma interp_src_triggerp\n      (R: Type)\n      (i: pE R)\n  :\n    (interp_hEs_src (trigger i))\n    =\n    (trigger i >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hEs_src in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_src_triggere\n      (R: Type)\n      (i: eventE R)\n  :\n    (interp_hEs_src (trigger i))\n    =\n    (trigger i >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hEs_src in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_src_call\n      (R: Type)\n      (i: callE R)\n  :\n    (interp_hEs_src (trigger i))\n    =\n    (trigger i >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hEs_src in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_src_hapc\n      (R: Type)\n      (i: hAPCE R)\n  :\n    (interp_hEs_src (trigger i))\n    =\n    ((handle_hAPCE_src i) >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hEs_src in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_src_triggerUB\n      (R: Type)\n  :\n    (interp_hEs_src (triggerUB))\n    =\n    triggerUB (A:=R).\nProof.\n  unfold interp_hEs_src, triggerUB in *. rewrite unfold_interp. cbn. grind.\nQed.\n\nLemma interp_src_triggerNB\n      (R: Type)\n  :\n    (interp_hEs_src (triggerNB))\n    =\n    triggerNB (A:=R).\nProof.\n  unfold interp_hEs_src, triggerNB in *. rewrite unfold_interp. cbn. grind.\nQed.\n\nLemma interp_src_unwrapU\n      (R: Type)\n      (i: option R)\n  :\n    (interp_hEs_src (@unwrapU hEs _ _ i))\n    =\n    (unwrapU i).\nProof.\n  unfold interp_hEs_src, unwrapU in *. des_ifs.\n  { etrans.\n    { eapply interp_src_ret. }\n    { grind. }\n  }\n  { etrans.\n    { eapply interp_src_triggerUB. }\n    { unfold triggerUB. grind. }\n  }\nQed.\n\nLemma interp_src_unwrapN\n      (R: Type)\n      (i: option R)\n  :\n    (interp_hEs_src (@unwrapN hEs _ _ i))\n    =\n    (unwrapN i).\nProof.\n  unfold interp_hEs_src, unwrapN in *. des_ifs.\n  { etrans.\n    { eapply interp_src_ret. }\n    { grind. }\n  }\n  { etrans.\n    { eapply interp_src_triggerNB. }\n    { unfold triggerNB. grind. }\n  }\nQed.\n\nLemma interp_src_assume\n      P\n  :\n    (interp_hEs_src (assume P))\n    =\n    (assume P;;; tau;; Ret tt)\n.\nProof.\n  unfold assume. rewrite interp_src_bind. rewrite interp_src_triggere. grind. eapply interp_src_ret.\nQed.\n\nLemma interp_src_guarantee\n      P\n  :\n    (interp_hEs_src (guarantee P))\n    =\n    (guarantee P;;; tau;; Ret tt).\nProof.\n  unfold guarantee. rewrite interp_src_bind. rewrite interp_src_triggere. grind. eapply interp_src_ret.\nQed.\n\nLemma interp_src_ext\n      R (itr0 itr1: itree _ R)\n      (EQ: itr0 = itr1)\n  :\n    (interp_hEs_src itr0)\n    =\n    (interp_hEs_src itr1)\n.\nProof. subst; et. Qed.\n\nGlobal Program Instance interp_hEs_src_rdb: red_database (mk_box (@interp_hEs_src)) :=\n  mk_rdb\n    0\n    (mk_box interp_src_bind)\n    (mk_box interp_src_tau)\n    (mk_box interp_src_ret)\n    (mk_box interp_src_call)\n    (mk_box interp_src_triggere)\n    (mk_box interp_src_triggerp)\n    (mk_box interp_src_hapc)\n    (mk_box interp_src_triggerUB)\n    (mk_box interp_src_triggerNB)\n    (mk_box interp_src_unwrapU)\n    (mk_box interp_src_unwrapN)\n    (mk_box interp_src_assume)\n    (mk_box interp_src_guarantee)\n    (mk_box interp_src_ext)\n.\n\nEnd AUX.\n\n\nSection AUX.\n\nContext `{Σ: GRA.t}.\n(* itree reduction *)\nLemma interp_hEs_tgt_bind\n      (R S: Type)\n      (s : itree hEs R) (k : R -> itree hEs S)\n  :\n    (interp_hEs_tgt (s >>= k))\n    =\n    ((interp_hEs_tgt s) >>= (fun r => interp_hEs_tgt (k r))).\nProof.\n  unfold interp_hEs_tgt in *. grind.\nQed.\n\nLemma interp_hEs_tgt_tau\n      (U: Type)\n      (t : itree _ U)\n  :\n    (interp_hEs_tgt (Tau t))\n    =\n    (Tau (interp_hEs_tgt t)).\nProof.\n  unfold interp_hEs_tgt in *. grind.\nQed.\n\nLemma interp_hEs_tgt_ret\n      (U: Type)\n      (t: U)\n  :\n    ((interp_hEs_tgt (Ret t)))\n    =\n    Ret t.\nProof.\n  unfold interp_hEs_tgt in *. grind.\nQed.\n\nLemma interp_hEs_tgt_triggerp\n      (R: Type)\n      (i: pE R)\n  :\n    (interp_hEs_tgt (trigger i))\n    =\n    (trigger i >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hEs_tgt in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_hEs_tgt_triggere\n      (R: Type)\n      (i: eventE R)\n  :\n    (interp_hEs_tgt (trigger i))\n    =\n    (trigger i >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hEs_tgt in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_hEs_tgt_call\n      (R: Type)\n      (i: callE R)\n  :\n    (interp_hEs_tgt (trigger i))\n    =\n    (handle_callE_hEs i >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hEs_tgt in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_hEs_tgt_hapc\n      (R: Type)\n      (i: hAPCE R)\n  :\n    (interp_hEs_tgt (trigger i))\n    =\n    ((handle_hAPCE_tgt i) >>= (fun r => tau;; Ret r)).\nProof.\n  unfold interp_hEs_tgt in *.\n  repeat rewrite interp_trigger. grind.\nQed.\n\nLemma interp_hEs_tgt_triggerUB\n      (R: Type)\n  :\n    (interp_hEs_tgt (triggerUB))\n    =\n    triggerUB (A:=R).\nProof.\n  unfold interp_hEs_tgt, triggerUB in *. rewrite unfold_interp. cbn. grind.\nQed.\n\nLemma interp_hEs_tgt_triggerNB\n      (R: Type)\n  :\n    (interp_hEs_tgt (triggerNB))\n    =\n    triggerNB (A:=R).\nProof.\n  unfold interp_hEs_tgt, triggerNB in *. rewrite unfold_interp. cbn. grind.\nQed.\n\nLemma interp_hEs_tgt_unwrapU\n      (R: Type)\n      (i: option R)\n  :\n    (interp_hEs_tgt (@unwrapU hEs _ _ i))\n    =\n    (unwrapU i).\nProof.\n  unfold interp_hEs_tgt, unwrapU in *. des_ifs.\n  { etrans.\n    { eapply interp_hEs_tgt_ret. }\n    { grind. }\n  }\n  { etrans.\n    { eapply interp_hEs_tgt_triggerUB. }\n    { unfold triggerUB. grind. }\n  }\nQed.\n\nLemma interp_hEs_tgt_unwrapN\n      (R: Type)\n      (i: option R)\n  :\n    (interp_hEs_tgt (@unwrapN hEs _ _ i))\n    =\n    (unwrapN i).\nProof.\n  unfold interp_hEs_tgt, unwrapN in *. des_ifs.\n  { etrans.\n    { eapply interp_hEs_tgt_ret. }\n    { grind. }\n  }\n  { etrans.\n    { eapply interp_hEs_tgt_triggerNB. }\n    { unfold triggerNB. grind. }\n  }\nQed.\n\nLemma interp_hEs_tgt_assume\n      P\n  :\n    (interp_hEs_tgt (assume P))\n    =\n    (assume P;;; tau;; Ret tt)\n.\nProof.\n  unfold assume. rewrite interp_hEs_tgt_bind. rewrite interp_hEs_tgt_triggere. grind. eapply interp_hEs_tgt_ret.\nQed.\n\nLemma interp_hEs_tgt_guarantee\n      P\n  :\n    (interp_hEs_tgt (guarantee P))\n    =\n    (guarantee P;;; tau;; Ret tt).\nProof.\n  unfold guarantee. rewrite interp_hEs_tgt_bind. rewrite interp_hEs_tgt_triggere. grind. eapply interp_hEs_tgt_ret.\nQed.\n\nLemma interp_hEs_tgt_ext\n      R (itr0 itr1: itree _ R)\n      (EQ: itr0 = itr1)\n  :\n    (interp_hEs_tgt itr0)\n    =\n    (interp_hEs_tgt itr1)\n.\nProof. subst; et. Qed.\n\nGlobal Program Instance interp_hEs_tgt_rdb: red_database (mk_box (@interp_hEs_tgt)) :=\n  mk_rdb\n    0\n    (mk_box interp_hEs_tgt_bind)\n    (mk_box interp_hEs_tgt_tau)\n    (mk_box interp_hEs_tgt_ret)\n    (mk_box interp_hEs_tgt_call)\n    (mk_box interp_hEs_tgt_triggere)\n    (mk_box interp_hEs_tgt_triggerp)\n    (mk_box interp_hEs_tgt_hapc)\n    (mk_box interp_hEs_tgt_triggerUB)\n    (mk_box interp_hEs_tgt_triggerNB)\n    (mk_box interp_hEs_tgt_unwrapU)\n    (mk_box interp_hEs_tgt_unwrapN)\n    (mk_box interp_hEs_tgt_assume)\n    (mk_box interp_hEs_tgt_guarantee)\n    (mk_box interp_hEs_tgt_ext)\n.\n\nEnd AUX.\n\n\n\n(*** TODO: move to ITreeLib ***)\nLemma bind_eta E X Y itr0 itr1 (ktr: ktree E X Y): itr0 = itr1 -> itr0 >>= ktr = itr1 >>= ktr. i; subst; refl. Qed.\n\nLtac ired_l := try (prw _red_gen 2 0).\nLtac ired_r := try (prw _red_gen 1 0).\n\nLtac ired_both := ired_l; ired_r.\n\n  Ltac mred := repeat (cbn; ired_both).\n  Ltac Esred :=\n            try rewrite ! EventsL.interp_Es_pE;\n            try rewrite ! EventsL.interp_Es_eventE; try rewrite ! EventsL.interp_Es_callE;\n            try rewrite ! EventsL.interp_Es_triggerNB; try rewrite ! EventsL.interp_Es_triggerUB (*** igo ***).\n  (*** step and some post-processing ***)\n  Ltac _step :=\n    match goal with\n    (*** terminal cases ***)\n    | [ |- gpaco6 _ _ _ _ _ _ _ _ (triggerUB >>= _) _ ] =>\n      unfold triggerUB; mred; _step; ss; fail\n    | [ |- gpaco6 _ _ _ _ _ _ _ _ _ (triggerNB >>= _) ] =>\n      unfold triggerNB; mred; _step; ss; fail\n    | [ |- gpaco6 _ _ _ _ _ _ _ _ (triggerNB >>= _) _ ] =>\n      exfalso\n    | [ |- gpaco6 _ _ _ _ _ _ _ _ _ (triggerUB >>= _) ] =>\n      exfalso\n\n    (*** assume/guarantee ***)\n    | [ |- gpaco6 _ _ _ _ _ _ _ _ (assume ?P ;;; _) _ ] =>\n      let tvar := fresh \"tmp\" in\n      let thyp := fresh \"TMP\" in\n      remember (assume P) as tvar eqn:thyp; unfold assume in thyp; subst tvar\n    | [ |- gpaco6 _ _ _ _ _ _ _ _ (guarantee ?P ;;; _) _ ] =>\n      let tvar := fresh \"tmp\" in\n      let thyp := fresh \"TMP\" in\n      remember (guarantee P) as tvar eqn:thyp; unfold guarantee in thyp; subst tvar\n    | [ |- gpaco6 _ _ _ _ _ _ _ _ _ (assume ?P ;;; _) ] =>\n      let tvar := fresh \"tmp\" in\n      let thyp := fresh \"TMP\" in\n      remember (assume P) as tvar eqn:thyp; unfold assume in thyp; subst tvar\n    | [ |- gpaco6 _ _ _ _ _ _ _ _ _ (guarantee ?P ;;; _) ] =>\n      let tvar := fresh \"tmp\" in\n      let thyp := fresh \"TMP\" in\n      remember (guarantee P) as tvar eqn:thyp; unfold guarantee in thyp; subst tvar\n\n    (*** default cases ***)\n    | _ =>\n      (gstep; econs; eauto; try (by eapply OrdArith.lt_from_nat; ss);\n       (*** some post-processing ***)\n       i;\n       try match goal with\n           | [ |- (eq ==> _)%signature _ _ ] =>\n             let v_src := fresh \"v_src\" in\n             let v_tgt := fresh \"v_tgt\" in\n             intros v_src v_tgt ?; subst v_tgt\n           end)\n    end\n  .\n  Ltac steps := repeat (mred; try _step; des_ifs_safe).\n  Ltac seal_left :=\n    match goal with\n    | [ |- gpaco6 _ _ _ _ _ _ _ _ ?i_src ?i_tgt ] => seal i_src\n    end.\n  Ltac seal_right :=\n    match goal with\n    | [ |- gpaco6 _ _ _ _ _ _ _ _ ?i_src ?i_tgt ] => seal i_tgt\n    end.\n  Ltac unseal_left :=\n    match goal with\n    | [ |- gpaco6 _ _ _ _ _ _ _ _ (@Seal.sealing _ _ ?i_src) ?i_tgt ] => unseal i_src\n    end.\n  Ltac unseal_right :=\n    match goal with\n    | [ |- gpaco6 _ _ _ _ _ _ _ _ ?i_src (@Seal.sealing _ _ ?i_tgt) ] => unseal i_tgt\n    end.\n  Ltac force_l := seal_right; _step; unseal_right.\n  Ltac force_r := seal_left; _step; unseal_left.\n  (* Ltac mstep := gstep; econs; eauto; [eapply from_nat_lt; ss|]. *)\n\n  From ExtLib Require Import\n       Data.Map.FMapAList.\n\n  Hint Resolve cpn3_wcompat: paco.\n  Ltac init :=\n    split; ss; ii; clarify; rename y into varg; eexists 100%nat; ss; des; clarify;\n    ginit; []; unfold alist_add, alist_remove; ss;\n    unfold fun_to_tgt, cfunN; ss.\n\n\nNotation Es' := (hCallE +' pE +' eventE).\n\nModule IPCNotations.\n  Notation \";;; t2\" :=\n    (ITree.bind (trigger hAPC) (fun _ => t2))\n      (at level 63, t2 at next level, right associativity) : itree_scope.\n  Notation \"` x : t <- t1 ;;; t2\" :=\n    (ITree.bind t1 (fun x : t => ;;; t2))\n      (at level 62, t at next level, t1 at next level, x ident, right associativity) : itree_scope.\n  Notation \"x <- t1 ;;; t2\" :=\n    (ITree.bind t1 (fun x => ;;; t2))\n      (at level 62, t1 at next level, right associativity) : itree_scope.\n  Notation \"' p <- t1 ;;; t2\" :=\n    (ITree.bind t1 (fun x_ => match x_ with p => ;;; t2 end))\n      (at level 62, t1 at next level, p pattern, right associativity) : itree_scope.\nEnd IPCNotations.\n\nExport IPCNotations.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/spc/HoareDef.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2344835254892603}}
{"text": "Require Import Smallstep.\nRequire Import Machregs.\nRequire Import Asm.\nRequire Import Integers.\nRequire Import List.\nRequire Import ZArith.\nRequire Import Memtype.\nRequire Import Memory.\nRequire Import Archi.\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Globalenvs.\nRequire Import Events.\nRequire Import Values.\nRequire Import Conventions1.\nRequire Import SSAsm AsmFacts AsmRegs.\n\nSection WFASM.\n\n\n  Fixpoint in_builtin_arg (b: builtin_arg preg) (r: preg) :=\n    match b with\n    | BA x => if preg_eq r x then True else False\n    | BA_splitlong ba1 ba2 => in_builtin_arg ba1 r \\/ in_builtin_arg ba2 r\n    | BA_addptr ba1 ba2 => in_builtin_arg ba1 r \\/ in_builtin_arg ba2 r\n    | _ => False\n    end.\n\n  Inductive is_alloc : instruction -> Prop :=\n    is_alloc_intro sz ora olink:\n      is_alloc (Pallocframe sz ora olink).\n\n  Definition make_palloc f  : instruction :=\n    let sz := fn_stacksize f in\n    (Pallocframe sz (Ptrofs.sub (Ptrofs.repr (align sz 8)) (Ptrofs.repr (size_chunk Mptr))) (fn_ofs_link f)).\n\n  Lemma make_palloc_is_alloc:\n    forall f,\n      is_alloc (make_palloc f).\n  Proof. constructor. Qed.\n\n  Inductive is_free : instruction -> Prop :=\n    is_free_intro sz ora olink:\n      is_free (Pfreeframe sz ora olink).\n\n  Lemma is_free_dec:\n    forall i,\n      {is_free i} + {~ is_free i}.\n  Proof.\n    destruct i; try now (right; intro A; inv A).\n    left. econstructor; eauto.\n  Defined.\n  Inductive is_jmp: instruction -> Prop :=\n  | is_jmps_intro: forall i sg, is_jmp (Pjmp_s i sg)\n  | is_jmpr_intro: forall ir sg, is_jmp (Pjmp_r ir sg).\n\n\n  Inductive intermediate_instruction : instruction -> Prop :=\n  | ii_alloc i: is_alloc i -> intermediate_instruction i\n  | ii_jmp i: i = Pret \\/ is_jmp i -> intermediate_instruction i.\n\n  Record wf_asm_function (f: function): Prop :=\n    {\n\n      wf_asm_alloc_only_at_beginning:\n        forall o sz ora olink,\n          find_instr o (fn_code f) = Some (Pallocframe sz ora olink) ->\n          o = 0;\n\n      wf_asm_alloc_at_beginning:\n        find_instr 0 (fn_code f) = Some (make_palloc f);\n\n      wf_asm_after_freeframe:\n        forall i o,\n          find_instr (Ptrofs.unsigned o) (fn_code f) = Some i ->\n          is_free i ->\n          exists i' ,\n            find_instr (Ptrofs.unsigned (Ptrofs.add o (Ptrofs.one))) (fn_code f) = Some i' /\\\n            (i' = Pret \\/ is_jmp i' );\n\n      wf_asm_ret_jmp_comes_after_freeframe:\n        forall i o,\n          find_instr (Ptrofs.unsigned o) (fn_code f) = Some i ->\n          i = Pret \\/ is_jmp i ->\n          exists o' ifree,\n            find_instr (Ptrofs.unsigned o') (fn_code f) = Some ifree /\\\n            is_free ifree /\\\n            Ptrofs.unsigned o' + 1 = Ptrofs.unsigned o;\n\n      wf_asm_code_bounded:\n        0 <= code_size (fn_code f) <= Ptrofs.max_unsigned;\n\n      wf_asm_builtin_not_PC:\n        forall o ef args res,\n          find_instr o (fn_code f) = Some (Pbuiltin ef args res) ->\n          ~ in_builtin_res res PC /\\\n          ~ in_builtin_res res RSP\n          /\\ Forall (fun arg : builtin_arg preg => ~ in_builtin_arg arg RA) args;\n\n      wf_asm_jmp_no_rsp:\n        forall o (r: ireg) sg,\n          find_instr o (fn_code f) = Some (Pjmp_r r sg) ->\n          r <> RSP;\n\n      wf_asm_call_no_rsp:\n        forall o (r: ireg) sg,\n          find_instr o (fn_code f) = Some (Pcall_r r sg) ->\n          r <> RSP;\n\n      wf_asm_free_spec:\n        forall o sz ora olink,\n          find_instr o (fn_code f) = Some (Pfreeframe sz ora olink) ->\n          sz = fn_stacksize f /\\ ora = Ptrofs.sub (Ptrofs.repr (align sz 8)) (Ptrofs.repr (size_chunk Mptr));\n\n      wf_allocframe_repr:\n        forall o sz ora olink,\n          find_instr o (fn_code f) = Some (Pallocframe sz ora olink) ->\n          align sz 8 - size_chunk Mptr =\n          Ptrofs.unsigned (Ptrofs.sub (Ptrofs.repr (align sz 8)) (Ptrofs.repr (size_chunk Mptr)));\n\n      wf_freeframe_repr:\n        forall o sz ora olink,\n          find_instr o (fn_code f) = Some (Pfreeframe sz ora olink) ->\n          Ptrofs.repr (align sz 8 - size_chunk Mptr) = Ptrofs.sub (Ptrofs.repr (align sz 8)) (Ptrofs.repr (size_chunk Mptr));\n    }.\n\n  Definition is_make_palloc a f :=  a = make_palloc f /\\\n                                    align (fn_stacksize f) 8 - size_chunk Mptr =\n                                    Ptrofs.unsigned (Ptrofs.sub (Ptrofs.repr (align (fn_stacksize f) 8)) (Ptrofs.repr (size_chunk Mptr))).\n(*\n  Lemma pair_eq: forall {A B}\n                   (Adec: forall (a b: A), {a = b} + {a <> b})\n                   (Bdec: forall (a b: B), {a = b} + {a <> b}),\n      forall (a b: A * B), {a = b} + {a <> b}.\n  Proof.\n    intros.\n    destruct a, b.\n    destruct (Adec a a0), (Bdec b b0); subst;\n      first [ now (right; inversion 1; congruence)\n            | left; reflexivity ].\n  Defined.\n*)\n  Definition pallocframe_dec s s' o o' l l':\n    {Pallocframe s o l= Pallocframe s' o' l'} + {Pallocframe s o l <> Pallocframe s' o' l'}.\n  Proof.\n    destruct (zeq s s'); subst. 2: (now right; inversion 1).\n    destruct (Ptrofs.eq_dec o o'); subst. 2: (now right; inversion 1).\n    destruct (Ptrofs.eq_dec l l'); subst. 2: (now right; inversion 1).\n    left; reflexivity.\n  Defined.\n\n  Lemma and_dec: forall {A B: Prop},\n      { A } + { ~ A } ->\n      { B } + { ~ B } ->\n      { A /\\ B } + { ~ (A /\\ B) }.\n  Proof.\n    intros. destruct H, H0; [left|right|right|right]; intuition.\n  Qed.\n\n  Definition is_make_palloc_dec a f : { is_make_palloc a f } + { ~ is_make_palloc a f }.\n  Proof.\n    unfold is_make_palloc, make_palloc.\n    destruct a; try (now right; inversion 1).\n    apply and_dec.\n    apply pallocframe_dec.\n    apply zeq.\n  Defined.\n\n  Definition check_ret_or_jmp roj :=\n    match roj with\n    | Pret |Pjmp_r _ _ | Pjmp_s _ _=> true\n    | _ => false\n    end.\n\n  Definition valid_ret_or_jmp roj :=\n    match roj with\n    | Pjmp_r r _ =>  negb (preg_eq r RSP)\n    | _ => true\n    end.\n\n  Definition check_free f sz ora :=\n      sz = fn_stacksize f /\\ ora = Ptrofs.sub (Ptrofs.repr (align sz 8)) (Ptrofs.repr (size_chunk Mptr)) /\\\n      Ptrofs.repr (align sz 8 - size_chunk Mptr) = Ptrofs.sub (Ptrofs.repr (align sz 8)) (Ptrofs.repr (size_chunk Mptr)).\n\n  Definition check_free_dec f sz ora : { check_free f sz ora } + { ~ check_free f sz ora }.\n  Proof.\n    unfold check_free.\n    apply and_dec. 2: apply and_dec.\n    apply zeq. apply Ptrofs.eq_dec. apply Ptrofs.eq_dec.\n  Defined.\n\n  Definition check_builtin args res :=\n    ~ in_builtin_res res PC /\\\n    ~ in_builtin_res res RSP\n    /\\ Forall (fun arg : builtin_arg preg => ~ in_builtin_arg arg RA) args.\n\n  Lemma not_in_builtin_res_dec res r:\n    {~ in_builtin_res res r} + {~ ~ in_builtin_res res r}.\n  Proof.\n    induction res; simpl.\n    destruct (preg_eq x r); subst; intuition. left; inversion 1.\n    destruct IHres1, IHres2; try (right; now intuition). left. intuition congruence.\n  Qed.\n\n\n  Lemma not_in_builtin_arg_dec arg r:\n    {~ in_builtin_arg arg r} + {~ ~ in_builtin_arg arg r}.\n  Proof.\n    induction arg; simpl; try (try destr; left; now inversion 1).\n    destruct IHarg1, IHarg2; try (right; now intuition). left. intuition congruence.\n    destruct IHarg1, IHarg2; try (right; now intuition). left. intuition congruence.\n  Qed.\n\n  Definition check_builtin_dec args res: {check_builtin args res} + { ~ check_builtin args res}.\n  Proof.\n    unfold check_builtin.\n    repeat apply and_dec.\n    apply not_in_builtin_res_dec.\n    apply not_in_builtin_res_dec.\n    apply Forall_dec. intros.\n    apply not_in_builtin_arg_dec.\n  Defined.\n\n  Lemma find_instr_bound:\n    forall c o i,\n      find_instr o c = Some i ->\n      o + (instr_size i) <= code_size c.\n  Proof.\n    induction c; simpl; intros; eauto. congruence.\n    destr_in H. inv H. generalize (code_size_non_neg c). lia.\n    apply IHc in H. unfold instr_size in *. lia.\n  Qed.\n\n  Lemma find_instr_pos_positive:\n        forall c o i,\n          find_instr o c = Some i ->\n          0 <= o.\n   Proof.\n     induction c; intros; simpl; inv H. destr_in H1. lia.\n     eapply IHc in H1. lia.\n   Qed.\n  Lemma code_bounded_repr':\n    forall c\n      (RNG: 0 <= code_size c <= Ptrofs.max_unsigned)\n      i o\n      (FI: find_instr o c = Some i)\n      sz\n      (LE: 0 <= sz <= instr_size i),\n      Ptrofs.unsigned (Ptrofs.add (Ptrofs.repr o) (Ptrofs.repr sz)) = o + sz.\n  Proof.\n    intros.\n    unfold Ptrofs.add.\n    rewrite (Ptrofs.unsigned_repr sz). 2:generalize (instr_size_repr i); lia.\n    generalize (find_instr_bound _ _ _ FI) (find_instr_pos_positive _ _ _ FI). intros.\n    rewrite (Ptrofs.unsigned_repr o) by lia.\n    apply Ptrofs.unsigned_repr; lia.\n  Qed.\n\n  Lemma code_bounded_repr:\n    forall c\n      (RNG: 0 <= code_size c <= Ptrofs.max_unsigned)\n      i o\n      (FI: find_instr (Ptrofs.unsigned o) c = Some i)\n      sz\n      (LE: 0 <= sz <= instr_size i),\n      Ptrofs.unsigned (Ptrofs.add o (Ptrofs.repr sz)) = Ptrofs.unsigned o + sz.\n  Proof.\n    intros.\n    erewrite <- code_bounded_repr'; eauto.\n    unfold Ptrofs.add.\n    rewrite Ptrofs.repr_unsigned. reflexivity.\n  Qed.\n\n  Lemma wf_asm_pc_repr' : forall f : function,\n       wf_asm_function f ->\n       forall (i : instruction) (o : ptrofs),\n       find_instr (Ptrofs.unsigned o) (fn_code f) = Some i ->\n       forall sz : Z, 0 <= sz <= instr_size i ->\n       Ptrofs.unsigned (Ptrofs.add o (Ptrofs.repr sz)) = Ptrofs.unsigned o + sz.\n  Proof.\n    intros; eapply code_bounded_repr; eauto.\n    apply wf_asm_code_bounded; eauto.\n  Qed.\n\n  Fixpoint check_asm_body (f: function) (next_roj: bool) (r: code) : bool :=\n    match r with\n    | nil => negb next_roj\n    | i :: r =>\n      let roj := proj_sumbool (is_free_dec i) in\n      check_asm_body f roj r &&\n      if next_roj then check_ret_or_jmp i && valid_ret_or_jmp i\n      else\n        negb (check_ret_or_jmp i) &&\n        match i with\n        | Pfreeframe sz ora olink =>     (* after a free, ret or jmp *)\n          check_free_dec f sz ora\n        | Pallocframe _ _ _ => false (* no alloc in body *)\n        | Pcall_r r sg => negb (preg_eq r RSP)\n        | Pbuiltin _ args res => check_builtin_dec args res\n        | _ => true\n      end\n    end.\n\n  Definition wf_asm_function_check (f: function) : bool :=\n    match fn_code f with\n    | nil => false\n    | a::r => is_make_palloc_dec a f && check_asm_body f false r\n    end && zle (code_size (fn_code f)) Ptrofs.max_unsigned.\n\n  Lemma check_asm_body_no_alloc:\n    forall f c b i,\n      check_asm_body f b c = true ->\n      In i c ->\n      ~ is_alloc i.\n  Proof.\n    induction c; simpl; intros. easy.\n    intro IA. inv IA.\n    assert (exists b, check_asm_body f b c = true).\n    {\n      eexists. refine (proj1 _); apply andb_true_iff; eauto.\n    }\n    destruct H1.\n    destruct H0. subst. simpl in *.\n    apply andb_true_iff in H. destruct H. destr_in H0.\n    eapply IHc in H0; eauto. apply H0; constructor.\n  Qed.\n\n  Lemma find_instr_app:\n    forall a o b,\n      0 <= o ->\n      find_instr (o + code_size a) (a ++ b) = find_instr o b.\n  Proof.\n    induction a; simpl; intros; eauto.\n    f_equal. lia.\n    rewrite pred_dec_false.\n    rewrite <- (IHa o b). f_equal. unfold instr_size. lia. lia.\n    generalize (code_size_non_neg a0). unfold instr_size. lia.\n  Qed.\n\n  Lemma find_instr_app':\n    forall a o b,\n      code_size a <= o ->\n      find_instr o (a ++ b) = find_instr (o - code_size a) b.\n  Proof.\n    intros.\n    rewrite <- (find_instr_app a _ b). f_equal. lia. lia.\n  Qed.\n\n  Lemma find_instr_split:\n    forall c o i,\n      find_instr o c = Some i ->\n      exists a b, c = a ++ i :: b /\\ o = code_size a.\n  Proof.\n    induction c; simpl; intros; eauto. congruence.\n    destr_in H. inv H. eexists nil, c; simpl. split; auto.\n    edestruct IHc as (aa & b & EQ & SZ). apply H. subst.\n    exists (a::aa), b; simpl; split; auto. unfold instr_size. lia.\n  Qed.\n\n  Lemma find_instr_app_pres: forall f1 f2 ofs i,\n      find_instr ofs f1 = Some i ->\n      find_instr ofs (f1 ++ f2) = Some i.\n  Proof.\n    induction f1 as [|i1 f1].\n    - cbn. intros; congruence.\n    - cbn. intros f2 i FI.\n      destr. eauto.\n  Qed.\n\n  Lemma code_size_app:\n    forall c1 c2,\n      code_size (c1 ++ c2) = code_size c1 + code_size c2.\n  Proof.\n    induction c1; simpl; intros; eauto. rewrite IHc1. lia.\n  Qed.\n\n  Lemma check_asm_body_after_free:\n    forall f a i b roj,\n      check_asm_body f roj (a ++ i :: b) = true ->\n      is_free i ->\n      check_asm_body f true b = true.\n  Proof.\n    induction a; simpl; intros; eauto.\n    apply andb_true_iff in H. destruct H as (H & _).\n    inv H0. simpl in *. auto.\n    apply andb_true_iff in H. destruct H as (H & B).\n    destruct (is_free_dec a); simpl in *. inv i0.\n    eapply IHa; eauto.\n    eapply IHa; eauto.\n  Qed.\n\n\n  Lemma check_asm_body_call:\n    forall f c b r sg,\n      check_asm_body f b c = true ->\n      In (Pcall_r r sg) c ->\n      r <> RSP.\n  Proof.\n    induction c; simpl; intros. easy.\n    assert (exists b, check_asm_body f b c = true).\n    {\n      eexists. refine (proj1 _); apply andb_true_iff; eauto.\n    }\n    apply andb_true_iff in H. destruct H. destruct H1. destruct H0; eauto. subst. simpl in *.\n    destr_in H2; simpl in *.\n    unfold proj_sumbool in H2; destr_in H2. simpl in H2. congruence.\n  Qed.\n\n  Lemma check_asm_body_free:\n    forall f c b sz ora olink,\n      check_asm_body f b c = true ->\n      In (Pfreeframe sz ora olink) c ->\n      check_free f sz ora.\n  Proof.\n    induction c; simpl; intros. easy.\n    assert (exists b, check_asm_body f b c = true).\n    {\n      eexists. refine (proj1 _); apply andb_true_iff; eauto.\n    }\n    apply andb_true_iff in H. destruct H. destruct H1. destruct H0; eauto. subst. simpl in *.\n    destr_in H2; simpl in *.\n    unfold proj_sumbool in H2; destr_in H2.\n  Qed.\n\n  Lemma check_asm_body_before_roj:\n    forall f a i b roj,\n      check_asm_body f roj (a ++ i :: b) = true ->\n      i = Pret \\/ is_jmp i ->\n      (a = nil /\\ roj = true) \\/ exists a0 i0, a = a0 ++ i0 :: nil /\\ is_free i0.\n  Proof.\n    induction a; simpl; intros; eauto.\n    - apply andb_true_iff in H. destruct H as (A & B).\n      destruct H0 as [ROJ|ROJ]; inv ROJ; simpl in *. destr_in B.\n      destruct roj. auto. congruence. destr_in B.\n    - apply andb_true_iff in H. destruct H as (A & B).\n      destruct (is_free_dec a); simpl in *. inv i0.\n      + simpl in *. destr_in B. right.\n        destruct a0. clear IHa. simpl in *.\n        eexists nil, _. split. simpl. eauto. constructor.\n        edestruct IHa as [ROJ|(a1 & i1 & EQ & IFR)]; eauto.\n        destruct ROJ; congruence. rewrite EQ.\n        eexists (_ :: a1), i1; split. simpl. reflexivity. auto.\n      + edestruct IHa as [ROJ|(a1 & i1 & EQ & IFR)]; eauto.\n        destruct ROJ; congruence. subst. right.\n        eexists (_ :: a1), i1; split. simpl. reflexivity. auto.\n  Qed.\n\n  Lemma check_asm_body_builtin:\n    forall f c b ef args res,\n      check_asm_body f b c = true ->\n      In (Pbuiltin ef args res) c ->\n      check_builtin args res.\n  Proof.\n    induction c; simpl; intros. easy.\n    assert (exists b, check_asm_body f b c = true).\n    {\n      eexists. refine (proj1 _); apply andb_true_iff; eauto.\n    }\n    destruct H1.\n    destruct H0. subst. simpl in *.\n    apply andb_true_iff in H. destruct H. destr_in H0.\n    unfold proj_sumbool in H0; destr_in H0.\n    eapply IHc in H0; eauto.\n  Qed.\n\n  Lemma check_asm_body_jmp:\n    forall f c b r sg,\n      check_asm_body f b c = true ->\n      In (Pjmp_r  r sg) c ->\n      r <> RSP.\n  Proof.\n    induction c; simpl; intros. easy.\n    assert (exists b, check_asm_body f b c = true).\n    {\n      eexists. refine (proj1 _); apply andb_true_iff; eauto.\n    }\n    apply andb_true_iff in H. destruct H. destruct H1. destruct H0; eauto. subst. simpl in *.\n    destr_in H2; simpl in *.\n    unfold proj_sumbool in H2; destr_in H2. simpl in H2. congruence.\n  Qed.\n\n  Lemma wf_asm_function_check_correct f:\n    wf_asm_function_check f = true ->\n    wf_asm_function f.\n  Proof.\n    unfold wf_asm_function_check. destr. simpl. congruence.\n    rewrite ! andb_true_iff. intros ((A & B) & C).\n    unfold proj_sumbool in A, C. destr_in A; destr_in C.\n    clear A C. rename Heqc into CODE. rename l into SIZE.\n    constructor.\n    - rewrite CODE. simpl. intros. destr_in H.\n      apply Asmgenproof0.find_instr_in in H.\n      eapply check_asm_body_no_alloc in H; eauto. contradict H. constructor.\n    - rewrite CODE; simpl. clear - i0. destruct i0 as (A & B). subst. reflexivity.\n    - destruct i0 as (i0 & _). subst. rewrite CODE. simpl.\n      intros. destr_in H. inv H. inv H0.\n      simpl in SIZE.\n      rewrite pred_dec_false. unfold Ptrofs.one.\n      replace (Ptrofs.unsigned (Ptrofs.add o (Ptrofs.repr 1)) - 1)\n        with (Ptrofs.unsigned (Ptrofs.add (Ptrofs.repr (Ptrofs.unsigned o - 1)) (Ptrofs.repr 1))).\n      revert H.\n      generalize (Ptrofs.unsigned o - 1).\n      intros.\n      edestruct find_instr_split as (a & b & EQ & SZ). apply H. subst.\n      rewrite find_instr_app'.\n      simpl. rewrite pred_dec_false.\n      eapply check_asm_body_after_free in B; eauto.\n      destruct b; simpl in B. congruence. simpl. rewrite pred_dec_true. eexists; split; eauto.\n      apply andb_true_iff in B. destruct B as (B & CHK).\n      unfold check_ret_or_jmp in CHK. apply andb_true_iff in CHK. destruct CHK as (CHK & _). destr_in CHK; try (right; constructor).\n      unfold Ptrofs.add.\n      rewrite (Ptrofs.unsigned_repr (code_size a) ).\n      setoid_rewrite (Ptrofs.unsigned_repr 1).\n      rewrite Ptrofs.unsigned_repr. lia.\n      simpl in SIZE. rewrite code_size_app in SIZE. simpl in SIZE.\n      generalize (code_size_non_neg a) (instr_size_positive i) (instr_size_positive i0) (code_size_non_neg b)\n                 (instr_size_positive (make_palloc f)). lia.\n      vm_compute. split; congruence.\n      simpl in SIZE. rewrite code_size_app in SIZE. simpl in SIZE.\n      generalize (code_size_non_neg a) (instr_size_positive i) (instr_size_positive i0) (code_size_non_neg b)\n                 (instr_size_positive (make_palloc f)). lia.\n      unfold Ptrofs.add.\n      rewrite (Ptrofs.unsigned_repr (code_size a)).\n      rewrite (Ptrofs.unsigned_repr 1).\n      rewrite Ptrofs.unsigned_repr. generalize (instr_size_positive i); lia.\n      simpl in SIZE. rewrite code_size_app in SIZE. simpl in SIZE.\n      generalize (code_size_non_neg a) (instr_size_positive i) (code_size_non_neg b)\n                 (instr_size_positive (make_palloc f)). lia.\n      vm_compute. split; congruence.\n      simpl in SIZE. rewrite code_size_app in SIZE. simpl in SIZE.\n      generalize (code_size_non_neg a) (instr_size_positive i) (code_size_non_neg b)\n                 (instr_size_positive (make_palloc f)). simpl in SIZE. lia.\n      unfold Ptrofs.add.\n      rewrite (Ptrofs.unsigned_repr (code_size a)).\n      rewrite (Ptrofs.unsigned_repr 1).\n      rewrite Ptrofs.unsigned_repr. generalize (instr_size_positive i); lia.\n      simpl in SIZE. rewrite code_size_app in SIZE. simpl in SIZE.\n      generalize (code_size_non_neg a) (instr_size_positive i) (code_size_non_neg b)\n                 (instr_size_positive (make_palloc f)). lia.\n      vm_compute. split; congruence.\n      simpl in SIZE. rewrite code_size_app in SIZE. simpl in SIZE.\n      generalize (code_size_non_neg a) (instr_size_positive i) (code_size_non_neg b)\n                 (instr_size_positive (make_palloc f)). lia.\n      unfold Ptrofs.add.\n      rewrite (Ptrofs.unsigned_repr 1).\n      rewrite (Ptrofs.unsigned_repr (Ptrofs.unsigned o - _)).\n      rewrite ! Ptrofs.unsigned_repr. lia.\n      generalize (find_instr_bound _ _ _ H) (find_instr_pos_positive _ _ _ H).\n      generalize (instr_size_positive i)\n                 (instr_size_positive (make_palloc f)). lia.\n      generalize (find_instr_bound _ _ _ H) (find_instr_pos_positive _ _ _ H).\n      generalize (instr_size_positive i)\n                 (instr_size_positive (make_palloc f)). lia.\n      generalize (find_instr_bound _ _ _ H) (find_instr_pos_positive _ _ _ H).\n      generalize (instr_size_positive i)\n                 (instr_size_positive (make_palloc f)). lia.\n      vm_compute. split; congruence.\n      unfold Ptrofs.add. unfold Ptrofs.one.\n      rewrite (Ptrofs.unsigned_repr 1).\n      rewrite Ptrofs.unsigned_repr.\n      generalize (Ptrofs.unsigned_range o) (instr_size_positive i); lia.\n      generalize (find_instr_bound _ _ _ H) (find_instr_pos_positive _ _ _ H).\n      generalize (instr_size_positive i)\n                 (instr_size_positive (make_palloc f)). lia.\n      vm_compute. split; congruence.\n    - destruct i0 as (i0 & _). subst. rewrite CODE. simpl.\n      intros i o FI ROJ.\n      destr_in FI. inv FI. destruct ROJ as [ROJ|ROJ]; inv ROJ.\n      edestruct find_instr_split as (a & b & EQ & SZ). apply FI. subst.\n      destruct (check_asm_body_before_roj _ _ _ _ _ B ROJ) as [(NIL & ROJFALSE)|(a0 & i0 & EQ & IFR)]. congruence.\n      subst.\n      exists (Ptrofs.sub o (Ptrofs.repr (instr_size i0))), i0.\n      rewrite pred_dec_false.\n      replace (Ptrofs.unsigned (Ptrofs.sub o (Ptrofs.repr (instr_size i0))) - 1)\n        with (0 + code_size a0). rewrite app_ass.\n      rewrite find_instr_app. simpl. split; auto. split. auto.\n      unfold Ptrofs.sub.\n      rewrite (Ptrofs.unsigned_repr _ (instr_size_repr i0)).\n      rewrite Ptrofs.unsigned_repr. unfold instr_size. lia.\n      generalize (find_instr_bound _ _ _ FI) (find_instr_pos_positive _ _ _ FI). intros.\n      simpl in *. rewrite ! code_size_app in *. simpl in *.\n      generalize (code_size_non_neg a0) (instr_size_positive i) (instr_size_positive i0) (code_size_non_neg b)\n                 (instr_size_positive (make_palloc f)). lia.\n      lia.\n      unfold Ptrofs.sub.\n      rewrite (Ptrofs.unsigned_repr _ (instr_size_repr i0)).\n      rewrite Ptrofs.unsigned_repr.\n      simpl in *. rewrite ! code_size_app in *. simpl in *. lia.\n      generalize (find_instr_bound _ _ _ FI) (find_instr_pos_positive _ _ _ FI). intros.\n      simpl in *. rewrite ! code_size_app in *. simpl in *.\n      generalize (code_size_non_neg a0) (instr_size_positive i) (instr_size_positive i0) (code_size_non_neg b)\n                 (instr_size_positive (make_palloc f)). lia.\n      unfold Ptrofs.sub.\n      rewrite (Ptrofs.unsigned_repr _ (instr_size_repr i0)).\n      rewrite Ptrofs.unsigned_repr.\n      simpl in *. rewrite ! code_size_app in *. simpl in *.\n      generalize (find_instr_bound _ _ _ FI) (find_instr_pos_positive _ _ _ FI). intros.\n      simpl in *. rewrite ! code_size_app in *. simpl in *.\n      generalize (code_size_non_neg a0) (instr_size_positive i) (instr_size_positive i0) (code_size_non_neg b)\n                 (instr_size_positive (make_palloc f)). lia.\n      generalize (find_instr_bound _ _ _ FI) (find_instr_pos_positive _ _ _ FI). intros.\n      simpl in *. rewrite ! code_size_app in *. simpl in *.\n      generalize (code_size_non_neg a0) (instr_size_positive i) (instr_size_positive i0) (code_size_non_neg b)\n                 (instr_size_positive (make_palloc f)). lia.\n    - rewrite CODE; split; auto.\n      generalize (code_size_non_neg (i::c)). lia.\n    - destruct i0 as (i0 & _). subst. rewrite CODE. simpl.\n      intros o ef args res FI.\n      destr_in FI. inv FI.\n      apply Asmgenproof0.find_instr_in in FI.\n      eapply check_asm_body_builtin in FI; eauto.\n    - destruct i0 as (i0 & _). subst. rewrite CODE. simpl.\n      intros o r sg FI.\n      destr_in FI. inv FI.\n      apply Asmgenproof0.find_instr_in in FI.\n      eapply check_asm_body_jmp in FI; eauto.\n    - destruct i0 as (i0 & _). subst. rewrite CODE. simpl.\n      intros o r sg FI.\n      destr_in FI. inv FI.\n      apply Asmgenproof0.find_instr_in in FI.\n      eapply check_asm_body_call in FI; eauto.\n    - destruct i0 as (i0 & _). subst. rewrite CODE. simpl.\n      intros o sz ora olink FI.\n      destr_in FI. inv FI.\n      apply Asmgenproof0.find_instr_in in FI.\n      edestruct check_asm_body_free as (A & BB & C); subst; eauto.\n    - destruct i0 as (i0 & PA). subst. rewrite CODE. simpl.\n      intros o sz pubrange ora FI.\n      destr_in FI. inv FI; auto.\n      apply Asmgenproof0.find_instr_in in FI.\n      eapply check_asm_body_no_alloc in FI; eauto. contradict FI; constructor.\n    - destruct i0 as (i0 & _). subst. rewrite CODE. simpl.\n      intros o sz ora olink FI.\n      destr_in FI. inv FI.\n      apply Asmgenproof0.find_instr_in in FI.\n      edestruct check_asm_body_free as (A & BB & C); subst; eauto.\n  Qed.\n\n  Lemma wf_asm_pc_repr:\n    forall f (WF: wf_asm_function f) i o,\n      find_instr (Ptrofs.unsigned o) (fn_code f) = Some i ->\n      Ptrofs.unsigned (Ptrofs.add o (Ptrofs.repr (instr_size i))) = Ptrofs.unsigned o + instr_size i.\n  Proof.\n    intros; eapply wf_asm_pc_repr'; eauto. generalize (instr_size_positive i); lia.\n  Qed.\n\n  Lemma wf_asm_wf_allocframe:\n    forall f (WF: wf_asm_function f) o sz ora olink\n      (FI: find_instr o (fn_code f) = Some (Pallocframe sz ora olink)),\n      make_palloc f = Pallocframe sz ora olink.\n  Proof.\n    intros.\n    exploit wf_asm_alloc_only_at_beginning; eauto. intro; subst.\n    erewrite wf_asm_alloc_at_beginning in FI; eauto. inv FI; auto.\n  Qed.\n\nEnd WFASM.\n\nSection WITHGE.\n  Variable ge : Genv.t Asm.fundef unit.\n\n  Definition exec_instr f i rs (m: mem) :=\n    match i with\n    | Pallocframe sz ofs_ra ofs_link =>\n      let aligned_sz := align sz 8 in\n      let psp := (Val.offset_ptr (rs#RSP) (Ptrofs.repr (size_chunk Mptr))) in (* parent stack pointer *)\n      let sp := Val.offset_ptr (rs#RSP) (Ptrofs.neg (Ptrofs.sub (Ptrofs.repr aligned_sz) (Ptrofs.repr (size_chunk Mptr)))) in\n      match Mem.storev Mptr m (Val.offset_ptr sp ofs_link) psp with\n        |None => Stuck\n        |Some m1 =>\n      Next (nextinstr (rs #RAX <- (Val.offset_ptr (rs RSP) (Ptrofs.repr (size_chunk Mptr))) #RSP <- sp)) m1\n      end\n    | Pfreeframe sz ofs_ra ofs_link =>\n      let sp := Val.offset_ptr (rs RSP) (Ptrofs.sub (Ptrofs.repr (align sz 8)) (Ptrofs.repr (size_chunk Mptr))) in\n      Next (nextinstr (rs#RSP <- sp)) m\n    | Pcall_s i sg =>\n      let sp := Val.offset_ptr (rs RSP) (Ptrofs.neg (Ptrofs.repr (size_chunk Mptr))) in\n      match Mem.storev Mptr m sp (Val.offset_ptr rs#PC Ptrofs.one) with\n        |None => Stuck\n        |Some m1 =>\n        Next (rs#RA <- (Val.offset_ptr rs#PC Ptrofs.one)\n                #PC <- (Genv.symbol_address ge i Ptrofs.zero)\n                #RSP <- sp) m1\n      end\n    |Pcall_r r sg =>\n      let sp := Val.offset_ptr (rs RSP) (Ptrofs.neg (Ptrofs.repr (size_chunk Mptr))) in\n      match Mem.storev Mptr m sp (Val.offset_ptr rs#PC Ptrofs.one) with\n        |None => Stuck\n        |Some m1 =>\n        Next (rs#RA <- (Val.offset_ptr rs#PC Ptrofs.one)\n                #PC <- (rs r)\n                #RSP <- sp) m1\n      end\n    | Pret =>\n      match loadvv Mptr m rs#RSP with\n      | None => Stuck\n      | Some ra =>\n        let sp := Val.offset_ptr (rs RSP) (Ptrofs.repr (size_chunk Mptr)) in\n        Next (rs #RSP <- sp\n                 #PC <- ra\n                 #RA <- Vundef) m\n      end\n    | _ => Asm.exec_instr ge f i rs m\n    end.\n\n  Inductive step  : state -> trace -> state -> Prop :=\n  | exec_step_internal:\n      forall b ofs f i rs m rs' m',\n        rs PC = Vptr b ofs ->\n        Genv.find_funct_ptr ge b = Some (Internal f) ->\n        find_instr (Ptrofs.unsigned ofs) (fn_code f) = Some i ->\n        exec_instr f i rs m = Next rs' m' ->\n        step (State rs m) E0 (State rs' m')\n  | exec_step_builtin:\n      forall b ofs f ef args res rs m vargs t vres rs' m',\n        rs PC = Vptr b ofs ->\n        Genv.find_funct_ptr ge b = Some (Internal f) ->\n        find_instr (Ptrofs.unsigned ofs) f.(fn_code) = Some (Pbuiltin ef args res) ->\n        eval_builtin_args ge rs (rs RSP) m args vargs ->\n        external_call ef ge vargs m t vres m' ->\n        rs' = nextinstr_nf\n                (set_res res vres\n                         (undef_regs (map preg_of (destroyed_by_builtin ef)) rs)) ->\n        step (State rs m) t (State rs' m')\n  | exec_step_external:\n      forall b ef args res rs m t rs' m',\n      rs PC = Vptr b Ptrofs.zero ->\n      Genv.find_funct_ptr ge b = Some (External ef) ->\n      extcall_arguments\n        (rs # RSP <- (Val.offset_ptr (rs RSP) (Ptrofs.repr (size_chunk Mptr)))) m (ef_sig ef) args ->\n        forall (SP_TYPE: Val.has_type (rs RSP) Tptr)\n          ra (LOADRA: Mem.loadv Mptr m (rs RSP) = Some ra)\n          (SP_NOT_VUNDEF: rs RSP <> Vundef)\n          (RA_NOT_VUNDEF: ra <> Vundef),\n      external_call ef ge args m t res m' ->\n      rs' = (set_pair (loc_external_result (ef_sig ef))\n                      res (undef_caller_save_regs rs))\n              #PC <- ra\n              #RA <- Vundef\n              #RSP <- (Val.offset_ptr (rs RSP) (Ptrofs.repr (size_chunk Mptr)))\n      ->\n      step (State rs m) t (State rs' m').\n\nEnd WITHGE.\n\nInductive initial_state (p: Asm.program): state -> Prop :=\n  | initial_state_intro: forall m0 m1 m2 stk bmain,\n      Genv.init_mem p = Some m0 ->\n      Mem.alloc m0 0 (max_stacksize + (align (size_chunk Mptr)8)) = (m1, stk) ->\n      Mem.storev Mptr m1 (Vptr stk (Ptrofs.repr (max_stacksize + align (size_chunk Mptr) 8 - size_chunk Mptr))) Vnullptr = Some m2 ->\n      let ge := Genv.globalenv p in\n      Genv.find_symbol ge p.(prog_main) = Some bmain ->\n      let rs0 :=\n        (Pregmap.init Vundef)\n        # PC <- (Vptr bmain Ptrofs.zero)\n        # RA <- Vnullptr\n        # RSP <- (Val.offset_ptr\n                   (Vptr stkblock ((Ptrofs.repr (max_stacksize + align (size_chunk Mptr) 8))))\n                   (Ptrofs.neg (Ptrofs.repr (size_chunk Mptr)))) in\n      initial_state p (State rs0 m2).\n\nDefinition semantics prog :=\n  Semantics step (initial_state prog) final_state (Genv.globalenv prog).\n\nDefinition rs_state s :=\n  let '(State rs _) := s in rs.\nDefinition m_state s :=\n  let '(State _ m) := s in m.\n\n  Section INVARIANT.\n\n    Variable prog: Asm.program.\n    Let ge := Genv.globalenv prog.\n\n    Definition rsp_ptr (s: state) : Prop :=\n      exists o, rs_state s RSP = Vptr stkblock  o /\\ (align_chunk Mptr | Ptrofs.unsigned o).\n\n    Definition bstack_perm (s: state) : Prop :=\n      forall o k p,\n        Mem.perm (m_state s) stkblock o k p ->\n        Mem.perm (m_state s) stkblock o k Writable.\n\n    Definition stack_top_state (s: state) : Prop :=\n      exists tl st, Mem.stack(Mem.support (m_state s))= Node None (1%positive::nil) tl st.\n\n    Definition fix_sid (s:state) : Prop :=\n      Mem.sid (Mem.support (m_state s)) = Mem.tid.\n\n    Inductive real_asm_inv : state -> Prop :=\n    | real_asm_inv_intro:\n        forall s\n          (RSPPTR: rsp_ptr s)\n          (BSTACKPERM: bstack_perm s)\n          (STOP: stack_top_state s)\n          (SID: fix_sid s),\n          real_asm_inv s.\n\n    Lemma storev_perm :\n      forall m chunk addr v m', Mem.storev chunk m addr v = Some m' ->\n                           (forall b o k p, Mem.perm m' b o k p <-> Mem.perm m b o k p).\n      Proof.\n        intros. unfold Mem.storev in H. destr_in H. split.\n        eapply Mem.perm_store_2; eauto. eapply Mem.perm_store_1; eauto.\n      Qed.\n\n    Lemma real_initial_inv:\n      forall is,\n        initial_state prog is -> real_asm_inv is.\n    Proof.\n      intros. inv H.\n      apply Genv.init_mem_stack in H0 as STK.\n      apply Genv.init_mem_sid in H0 as SID.\n      constructor.\n      - red.\n        simpl; unfold rs0; simpl_regs. eexists. split. reflexivity.\n        apply div_ptr_add.\n        apply div_unsigned_repr.\n        apply Z.divide_add_r. apply align_Mptr_stack_limit. apply align_Mptr_align8.\n        apply align_Mptr_modulus. unfold Ptrofs.neg. apply div_unsigned_repr.\n        apply Zdivide_opp_r.\n        apply div_unsigned_repr.\n        apply align_size_chunk_divides.\n        apply align_Mptr_modulus.\n        apply align_Mptr_modulus.\n        apply align_Mptr_modulus.\n      - exploit Mem.alloc_result; eauto. intro. subst.\n        unfold Mem.nextblock in H1. unfold Mem.fresh_block in H1.\n        rewrite STK in H1. destr_in H1. simpl in Heqp. inv Heqp.\n        red. unfold stkblock. intros o k p. rewrite SID in *.\n        repeat erewrite (storev_perm _ _ _ _ _ H2). eauto.\n        intro. exploit Mem.perm_alloc_3; eauto.\n        intro. exploit Mem.perm_alloc_2; eauto. simpl. intro. eapply Mem.perm_implies; eauto.\n        apply perm_F_any.\n      - red. simpl. apply Mem.stack_alloc in H1. rewrite STK in H1.\n        exists nil, None. simpl in H1. erewrite <- Mem.support_storev; eauto.\n      - red. simpl. erewrite <- Mem.support_storev. 2: eauto. erewrite Mem.sid_alloc; eauto.\n    Qed.\n\n    Lemma exec_instr_invar_same:\n      forall f i rs1 m1,\n        stk_unrelated_instr i = true ->\n        exec_instr ge f i rs1 m1 = SSAsm.exec_instr ge f i rs1 m1.\n    Proof.\n      intros f i rs1 m1 SI.\n      destruct i; simpl in SI; simpl; congruence.\n    Qed.\n(*\n    Inductive is_load_parent_pointer: instruction -> Prop :=\n    | ilpp_intro i z: is_load_parent_pointer (Pload_parent_pointer i z).\n\n    Lemma is_load_parent_pointer_dec i: { is_load_parent_pointer i } + { ~ is_load_parent_pointer i }.\n    Proof.\n      destruct i; first [ now (right; inversion 1) | left; econstructor ].\n    Defined.\n*)\n    Lemma exec_instr_invar_same':\n      forall f i rs1 m1,\n        stk_unrelated_instr i = true ->\n        Asm.exec_instr ge f i rs1 m1 = SSAsm.exec_instr ge f i rs1 m1.\n    Proof.\n      intros f i rs1 m1 SI.\n      destruct i; simpl in SI; simpl; try congruence.\n    Qed.\n\n    Lemma exec_instr_invar_inv:\n      forall f i rs1 m1 rs2 m2,\n        asm_instr_unchange_rsp i ->\n        stk_unrelated_instr i = true ->\n        exec_instr ge f i rs1 m1 = Next rs2 m2 ->\n        real_asm_inv (State rs1 m1) ->\n        real_asm_inv (State rs2 m2).\n    Proof.\n      intros f i rs1 m1 rs2 m2 NORSP INVAR EI RAI; inv RAI.\n      erewrite exec_instr_invar_same in EI; eauto.\n      erewrite <- exec_instr_invar_same' in EI; eauto.\n      exploit NORSP; eauto. intro EQ.\n      generalize (asm_prog_unchange_sup i INVAR _ _ _ _ _ _ EI). intros (A & B).\n      constructor.\n      + red in RSPPTR; red. simpl in *; rewrite <- EQ. eauto.\n      + red in BSTACKPERM; red. simpl in *. setoid_rewrite <- B. eauto.\n      + red in STOP; red; simpl in *. rewrite <- A; eauto.\n      + red in SID; red; simpl in *. rewrite <- A; eauto.\n    Qed.\n\n    Lemma align_Mptr_sub:\n      forall o,\n        (align_chunk Mptr | Ptrofs.unsigned o) ->\n        (align_chunk Mptr | Ptrofs.unsigned (Ptrofs.add o (Ptrofs.neg (Ptrofs.repr (size_chunk Mptr))))).\n    Proof.\n      intros.\n      apply div_ptr_add; auto.\n      apply div_unsigned_repr.\n      apply Z.divide_opp_r.\n      apply div_unsigned_repr.\n      apply align_size_chunk_divides.\n      apply align_Mptr_modulus.\n      apply align_Mptr_modulus.\n      apply align_Mptr_modulus.\n    Qed.\n\n    Lemma align_Mptr_add:\n      forall o,\n        (align_chunk Mptr | Ptrofs.unsigned o) ->\n        (align_chunk Mptr | Ptrofs.unsigned (Ptrofs.add o (Ptrofs.repr (size_chunk Mptr)))).\n    Proof.\n      intros.\n      apply div_ptr_add; auto.\n      apply div_unsigned_repr.\n      apply align_size_chunk_divides.\n      apply align_Mptr_modulus.\n      apply align_Mptr_modulus.\n    Qed.\n\n    Lemma align_Mptr_add_gen:\n      forall o d,\n        (align_chunk Mptr | Ptrofs.unsigned o) ->\n        (align_chunk Mptr | Ptrofs.unsigned d) ->\n        (align_chunk Mptr | Ptrofs.unsigned (Ptrofs.add o d)).\n    Proof.\n      intros.\n      apply div_ptr_add; auto.\n      apply align_Mptr_modulus.\n    Qed.\n\n    Definition asm_prog_no_rsp (ge: Genv.t Asm.fundef unit):=\n      forall b f,\n        Genv.find_funct_ptr ge b = Some (Internal f) ->\n        asm_code_no_rsp (fn_code f).\n\n    Definition wf_asm_prog (ge: Genv.t Asm.fundef unit):=\n      forall b f,\n        Genv.find_funct_ptr ge b = Some (Internal f) ->\n        wf_asm_function f.\n\n    Lemma real_asm_inv_inv:\n      forall (prog_no_rsp: asm_prog_no_rsp ge) (WF: wf_asm_prog ge) s1 t s2,\n        step ge s1 t s2 ->\n        real_asm_inv s1 ->\n        real_asm_inv s2.\n    Proof.\n      intros prog_no_rsp WF s1 t s2 STEP INV; inv STEP.\n      - destruct (stk_unrelated_instr i) eqn:INVAR.\n        eapply exec_instr_invar_inv; eauto.\n        eapply prog_no_rsp; eauto. eapply Asmgenproof0.find_instr_in; eauto.\n        destruct i; simpl in INVAR; try congruence.\n        + (* call_s *)\n          simpl in H2. destr_in H2. inv H2. inv INV; constructor; simpl.\n          * red. simpl. simpl_regs. destruct RSPPTR as (o & EQ & AL); simpl in *; rewrite EQ.\n            simpl. eexists; split; eauto. apply align_Mptr_sub; auto.\n          * red in BSTACKPERM; red; simpl in *.\n            intros o k p. erewrite storev_perm; eauto. intro. erewrite storev_perm; eauto.\n          * red in STOP; red; simpl in *. erewrite <- Mem.support_storev; eauto.\n          * red in SID; red; simpl in *. erewrite <- Mem.support_storev; eauto.\n        + (* call_r *)\n          simpl in H2. destr_in H2. inv H2. inv INV; constructor; simpl.\n          * red. simpl. simpl_regs. destruct RSPPTR as (o & EQ & AL); simpl in *; rewrite EQ.\n            simpl. eexists; split; eauto. apply align_Mptr_sub; auto.\n          * red in BSTACKPERM; red; simpl in *.\n            intros o k p. erewrite storev_perm; eauto. intro. erewrite storev_perm; eauto.\n          * red in STOP; red; simpl in *. erewrite <- Mem.support_storev; eauto.\n          * red in SID; red; simpl in *. erewrite <- Mem.support_storev; eauto.\n        + (* ret *)\n          simpl in H2; repeat destr_in H2; inv INV; constructor; simpl.\n          * red. simpl. simpl_regs. destruct RSPPTR as (o & EQ & AL); simpl in *; rewrite EQ.\n            simpl. eexists; split; eauto. apply align_Mptr_add; auto.\n          * red in BSTACKPERM; red; simpl in *.\n            intros o k p. eauto.\n          * red in STOP; red; simpl in *. eauto.\n          * red in STOP; red; simpl in *. eauto.\n        + (* allocframe *)\n          simpl in H2; repeat destr_in H2; inv INV; constructor; simpl.\n          * red. simpl. simpl_regs. destruct RSPPTR as (o & EQ & AL); simpl in *; rewrite EQ.\n            simpl. eexists; split; eauto. apply align_Mptr_add_gen; auto.\n            unfold Ptrofs.neg. apply div_unsigned_repr; auto. apply Z.divide_opp_r.\n            unfold Ptrofs.sub. apply div_unsigned_repr; auto.\n            apply Z.divide_sub_r.\n            apply div_unsigned_repr; auto.\n            transitivity 8. unfold Mptr. destr; simpl. exists 1; lia. exists 2; lia. apply align_divides. lia.\n            apply align_Mptr_modulus.\n            apply div_unsigned_repr; auto.\n            apply align_size_chunk_divides.\n            apply align_Mptr_modulus.\n            apply align_Mptr_modulus.\n            apply align_Mptr_modulus.\n          * red in BSTACKPERM; red; simpl in *.\n            intros o k p. erewrite storev_perm; eauto. intro. erewrite storev_perm; eauto.\n          * red in STOP; red; simpl in *. erewrite <- Mem.support_storev; eauto.\n          * red in STOP; red; simpl in *. erewrite <- Mem.support_storev; eauto.\n        + (* freeframe *)\n          simpl in H2; repeat destr_in H2; inv INV; constructor; simpl.\n          * red. simpl. simpl_regs. destruct RSPPTR as (o & EQ & AL); simpl in *; rewrite EQ.\n            simpl. eexists; split; eauto. apply align_Mptr_add_gen; auto.\n            unfold Ptrofs.sub. apply div_unsigned_repr; auto.\n            apply Z.divide_sub_r.\n            apply div_unsigned_repr; auto.\n            transitivity 8. unfold Mptr. destr; simpl. exists 1; lia. exists 2; lia. apply align_divides. lia.\n            apply align_Mptr_modulus.\n            apply div_unsigned_repr; auto.\n            apply align_size_chunk_divides.\n            apply align_Mptr_modulus.\n            apply align_Mptr_modulus.\n          * red in BSTACKPERM; red; eauto.\n          * red in STOP; red; eauto.\n          * red; eauto.\n      - inv INV; constructor.\n        + red in RSPPTR; red; simpl in *. unfold nextinstr_nf. repeat simpl_regs.\n          rewrite Asmgenproof0.undef_regs_other.\n          2: simpl; intuition subst; congruence.\n          exploit wf_asm_builtin_not_PC; eauto.\n          intros (NPC & NRSP & NRA).\n          rewrite set_res_other; auto.\n          rewrite Asmgenproof0.undef_regs_other.\n          eauto. setoid_rewrite in_map_iff. intros r' (x & PREG & IN). subst.\n          intro EQ. symmetry in EQ. apply preg_of_not_rsp in EQ. congruence.\n        + red in BSTACKPERM; red. simpl in *. intros o k p.\n          repeat erewrite (external_perm_stack _ _ _ _ _ _ _ _ _ _ _ H3); eauto.\n           simpl. auto. red in STOP; simpl in STOP.  unfold stkblock.\n           simpl. destruct STOP as (tl & st & STOP). red in SID. simpl in SID. destr.\n           rewrite STOP. split. auto. left. auto. rewrite SID in Heqb0.\n           apply Nat.eqb_neq in Heqb0. congruence.\n           simpl. auto. red in STOP; simpl in STOP.  unfold stkblock.\n           simpl. destruct STOP as (tl & st & STOP). rewrite STOP. destr.\n           split. auto. left. auto. red in SID; simpl in SID. rewrite SID in Heqb0.\n           apply Nat.eqb_neq in Heqb0. congruence.\n        + red in STOP; red; simpl in *. destruct STOP as (tl & st & STOP).\n          exploit external_call_stack; eauto. destr. intros.\n          rewrite STOP in H4. simpl in H4. destruct st. eauto. eauto.\n          intros. rewrite H4. eauto.\n        + red; eauto. simpl. erewrite <- external_call_mem_sid; eauto.\n      - inv INV; constructor.\n        + Opaque destroyed_at_call.\n          red in RSPPTR; red; simpl in *. repeat simpl_regs.\n          destruct RSPPTR as (o & EQ & AL); simpl in *. rewrite EQ.\n          simpl. eexists; split; eauto. apply align_Mptr_add; auto.\n        + red in BSTACKPERM; red. simpl in *. intros o k p.\n          repeat erewrite (external_perm_stack _ _ _ _ _ _ _ _ _ _ _ H2); eauto.\n           simpl. auto. red in STOP; simpl in STOP.  unfold stkblock.\n           simpl. destruct STOP as (tl & st & STOP). rewrite STOP. destr.\n           split. auto. left. auto. red in SID; simpl in *. rewrite SID in Heqb0.\n           apply Nat.eqb_neq in Heqb0. congruence.\n           simpl. auto. red in STOP; simpl in STOP.  unfold stkblock.\n           simpl. destruct STOP as (tl & st & STOP). rewrite STOP. destr.\n           split. auto. left. auto. red in SID. simpl in *. rewrite SID in Heqb0.\n           apply Nat.eqb_neq in Heqb0. congruence.\n        + red in STOP; red; simpl in *. destruct STOP as (tl & st & STOP).\n          exploit external_call_stack; eauto. destr. intros.\n          rewrite STOP in H3. simpl in H3. destruct st. eauto. eauto.\n          intros. rewrite H3. eauto.\n        + red. simpl. eauto. erewrite <- external_call_mem_sid; eauto.\n    Qed.\n\nEnd INVARIANT.\n\n\nSection WITHGETGE.\n\n    Variable (ge tge: Genv.t Asm.fundef unit).\n    Hypothesis (SADDR_EQ: forall id ofs, Genv.symbol_address tge id ofs = Genv.symbol_address ge id ofs).\n    Hypothesis (FPTR_EQ: forall b, Genv.find_funct_ptr ge b = None <-> Genv.find_funct_ptr tge b = None).\n\n    Lemma fptr_some_eq:\n      forall b f, Genv.find_funct_ptr ge b = Some f ->\n             exists f', Genv.find_funct_ptr tge b = Some f'.\n    Proof.\n      intros.\n      destruct (Genv.find_funct_ptr tge b) eqn:EQ; eauto.\n      rewrite <- FPTR_EQ in EQ. congruence.\n    Qed.\n\n    Lemma funct_some_eq:\n      forall b f, Genv.find_funct ge b = Some f ->\n             exists f', Genv.find_funct tge b = Some f'.\n    Proof.\n      unfold Genv.find_funct.\n      intros. destruct b; auto; try congruence.\n      destr_in H; eauto.\n      subst.\n      eapply fptr_some_eq; eauto.\n    Qed.\n\n    Lemma funct_none_eq: forall b, Genv.find_funct ge b = None <-> Genv.find_funct tge b = None.\n    Proof.\n      intros. unfold Genv.find_funct.\n      destruct b; split; eauto.\n      destr; eauto.\n      subst. intros. rewrite <- FPTR_EQ. auto.\n      destr; eauto.\n      subst. intros. rewrite FPTR_EQ. auto.\n    Qed.\n\n (*   Lemma goto_ofs_eq: forall sz ofs rs m,\n        goto_ofs ge sz ofs rs m = goto_ofs tge sz ofs rs m.\n    Proof.\n      intros. unfold goto_ofs. destr; auto.\n      destr. \n      exploit fptr_some_eq; eauto.\n      intros (f1 & FT). rewrite FT. auto.\n      rewrite FPTR_EQ in Heqo. rewrite Heqo. auto.\n    Qed.\n*)\n    Ltac unfold_loadstore :=\n      match goal with\n      | [ |- context[ exec_load _ _ _ _ _  _] ] =>\n        unfold exec_load\n      | [ |- context[ exec_store _ _ _ _  _ _ _] ] =>\n        unfold exec_store\n      end.\n\n    Ltac rewrite_eval_addrmode :=\n      match goal with\n      | [ |- context[ eval_addrmode _ _ _ ] ] =>\n        erewrite eval_addrmode_same; eauto\n      end.\n\n    Lemma exec_valid_instr_same : forall (i:instruction) f f' i rs m,\n        instr_valid i ->\n        exec_instr ge f i rs m = exec_instr tge f' i rs m.\n    Proof.\n      intros i f f' i0 rs m VI.\n      destruct i0; cbn; auto;\n        try (unfold_loadstore; rewrite_eval_addrmode);\n        try (red in VI; cbn in VI; contradiction).\n      - congruence.\n      - erewrite eval_addrmode32_same; eauto.\n      - erewrite eval_addrmode64_same; eauto.\n      - erewrite SADDR_EQ. unfold Genv.find_funct.\n        destruct (Genv.symbol_address ge symb Ptrofs.zero); auto.\n        destruct (Ptrofs.eq_dec i0 Ptrofs.zero); auto.\n        destr; destr.\n        apply FPTR_EQ in Heqo0. congruence.\n        apply FPTR_EQ in Heqo. congruence.\n      - unfold Genv.find_funct.\n        destruct (rs r); auto.\n        destruct (Ptrofs.eq_dec i0 Ptrofs.zero); auto.\n        destr; destr.\n        apply FPTR_EQ in Heqo0. congruence.\n        apply FPTR_EQ in Heqo. congruence.\n      - erewrite SADDR_EQ. auto.\n    Qed.\n\n    Lemma goto_label_eq : forall (i:instruction) f f' l rs m,\n        (forall lbl ofs, label_pos lbl ofs (fn_code f) = label_pos lbl ofs (fn_code f')) ->\n        goto_label ge f l rs m = goto_label tge f' l rs m.\n    Proof.\n      intros.\n      unfold goto_label. destr.\n      - rewrite <- H. rewrite Heqo.\n        destr; auto.\n        destr.\n        exploit fptr_some_eq; eauto.\n        intros (f1 & FT). rewrite FT. auto.\n        rewrite FPTR_EQ in Heqo0. rewrite Heqo0. auto.\n      - rewrite <- H. rewrite Heqo. auto.\n    Qed.\n\n    Lemma exec_instr_same : forall (i:instruction) f f' i rs m,\n        (forall lbl ofs, label_pos lbl ofs (fn_code f) = label_pos lbl ofs (fn_code f')) ->\n        exec_instr ge f i rs m = exec_instr tge f' i rs m.\n    Proof.\n      intros i f f' i0 rs m LP.\n      destruct (instr_valid_dec i0).\n      eapply exec_valid_instr_same; eauto.\n      unfold instr_valid in n.\n      destruct i0; try tauto.\n      - cbn. eapply goto_label_eq; eauto.\n      - cbn. destr; auto. destr; auto.\n        eapply goto_label_eq; eauto.\n      - cbn. destr; auto. destr; auto.\n        destr; auto. destr; auto.\n        eapply goto_label_eq; eauto.\n      - cbn. destr; auto. cbn. destr; auto.\n        eapply goto_label_eq; eauto.\n    Qed.\n\nEnd WITHGETGE.\n\nSection RECEPTIVEDET.\n\n  Theorem real_asm_single_events p:\n    single_events (semantics p).\n  Proof.\n    red. simpl. intros s t s' STEP.\n    inv STEP; simpl. lia.\n    eapply external_call_trace_length; eauto.\n    eapply external_call_trace_length; eauto.\n  Qed.\n\n  Theorem real_asm_receptive p:\n    receptive (semantics p).\n  Proof.\n    split.\n    - simpl. intros s t1 s1 t2 STEP MT.\n      inv STEP.\n      inv MT. eexists. eapply exec_step_internal; eauto.\n      edestruct external_call_receptive as (vres2 & m2 & EC2); eauto.\n      eexists. eapply exec_step_builtin; eauto.\n      edestruct external_call_receptive as (vres2 & m2 & EC2); eauto.\n      eexists. eapply exec_step_external; eauto.\n    - eapply real_asm_single_events; eauto.\n  Qed.\n\n  Theorem real_asm_determinate p :\n    determinate (semantics p).\n  Proof.\n    split.\n    - simpl; intros s t1 s1 t2 s2 STEP1 STEP2.\n      inv STEP1.\n      + inv STEP2; rewrite_hyps. split. constructor.  congruence.\n        simpl in H2. inv H2.\n      + inv STEP2; rewrite_hyps. inv H11.\n        exploit eval_builtin_args_determ. apply H2. apply H9. intro; subst.\n        exploit external_call_determ. apply H3. apply H10. intros (A & B); split; auto. intro C.\n        destruct B; auto. congruence.\n      + inv STEP2; rewrite_hyps.\n        exploit extcall_arguments_determ. apply H1. apply H7. intro; subst.\n        exploit external_call_determ. apply H2. apply H8. intros (A & B); split; auto. intro C.\n        destruct B; auto. congruence.\n    - apply real_asm_single_events.\n    - simpl. intros s1 s2 IS1 IS2; inv IS1; inv IS2. rewrite_hyps.\n      inv H0. rewrite_hyps. unfold rs0, rs1, ge, ge0 in *. rewrite_hyps. congruence.\n    - simpl. intros s r FS.\n      red. intros t s' STEP.\n      inv FS. inv STEP; rewrite_hyps.\n    - simpl. intros s r1 r2 FS1 FS2.\n      inv FS1; inv FS2. congruence.\n  Qed.\n\nEnd RECEPTIVEDET.\n", "meta": {"author": "SJTU-PLV", "repo": "nominal-compcert-popl22-artifact", "sha": "b2d2ee12497ac86c59034d042ef142cc3a123752", "save_path": "github-repos/coq/SJTU-PLV-nominal-compcert-popl22-artifact", "path": "github-repos/coq/SJTU-PLV-nominal-compcert-popl22-artifact/nominal-compcert-popl22-artifact-b2d2ee12497ac86c59034d042ef142cc3a123752/Multi-Stack-CompCert/x86/RealAsm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723316991792861, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.23440518079991088}}
{"text": "Require Import compcert.lib.Axioms.\n\nRequire Import concurrency.sepcomp. Import SepComp.\nRequire Import sepcomp.semantics_lemmas.\n\n\nRequire Import concurrency.pos.\nRequire Import concurrency.concurrent_machine.\nRequire Import Coq.Program.Program.\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\n(*NOTE: because of redefinition of [val], these imports must appear\n  after Ssreflect eqtype.*)\nRequire Import compcert.common.AST.     (*for typ*)\nRequire Import compcert.common.Values. (*for val*)\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Memory.\nRequire Import compcert.lib.Integers.\nRequire Import veric.shares msl.msl_standard.\nRequire Import concurrency.threads_lemmas.\n\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import (*compcert_linking*) concurrency.permissions.\n\nModule ThreadPool.\n  Section ThreadPool.\n\n    Variable cT : Type.\n\n    Record t := mk\n                  { num_threads : pos\n                    ; pool :> 'I_num_threads -> (@ctl cT)\n                    ; share_maps : 'I_num_threads -> share_map\n                  }.\n\n    Definition containsThread: t -> nat -> Prop:=\n      fun tp tid => tid < (num_threads tp).\n\n  End ThreadPool.\nEnd ThreadPool.\n\nSection poolDefs.\n\n  Variable cT : Type.\n\n  Import ThreadPool.\n\n  Notation \"x <= y\" := (x <= y)%nat.\n  Notation \"x < y\" := (x < y)%nat.\n  Notation thread_pool := (t cT).\n\n  Variable (tp : thread_pool).\n  Notation num_threads := (ThreadPool.num_threads tp).\n\n  (* Per-thread disjointness definition*)\n  Definition race_free (tp : thread_pool) :=\n    forall tid0 tid0' (Htid0 : containsThread tp tid0)\n      (Htid0' : containsThread tp tid0')\n      (Htid: tid0 <> tid0'),\n      shareMapsJoins (share_maps tp (Ordinal Htid0))\n                       (share_maps tp (Ordinal Htid0')).\n\n  Definition newShareMap_wf smap :=\n    forall tid0 (Htid0 : containsThread tp tid0),\n      shareMapsJoins ((share_maps tp) (Ordinal Htid0)) smap.\n\n  Require Import fintype.\n\n  Lemma unlift_m_inv : forall tid (Htid : tid < num_threads.+1) ord\n                         (Hunlift: unlift (ordinal_pos_incr num_threads)\n                                          (Ordinal (n:=num_threads.+1) (m:=tid) Htid)\n                                   = Some ord),\n                         nat_of_ord ord = tid.\n  Proof.\n    intros.\n    assert (Hcontra:\n              unlift_spec (ordinal_pos_incr num_threads)\n                          (Ordinal (n:=num_threads.+1) (m:=tid) Htid) (Some ord)).\n    rewrite <- Hunlift.\n    apply/unliftP.\n    inversion Hcontra; subst.\n    inversion H0.\n    unfold bump.\n    assert (pf: ord < num_threads)\n      by (by rewrite ltn_ord).\n    assert (H: num_threads <= ord = false).\n    rewrite ltnNge in pf.\n    rewrite <- Bool.negb_true_iff. auto.\n    rewrite H. simpl. rewrite add0n. reflexivity.\n  Defined.\n\n  Definition addThread (c : cT) (smap : share_map) : thread_pool :=\n    let: new_num_threads := pos_incr num_threads in\n    let: new_tid := ordinal_pos_incr num_threads in\n    mk new_num_threads\n        (fun (n : 'I_new_num_threads) =>\n           match unlift new_tid n with\n             | None => Kresume c (*Could be a new state Kinit?? *)\n             | Some n' => tp n'\n           end)\n        (fun (n : 'I_new_num_threads) =>\n           match unlift new_tid n with\n             | None => smap\n             | Some n' => (share_maps tp) n'\n           end).\n\n  Lemma addThread_racefree :\n    forall c p (Hwf: newShareMap_wf p) (Hrace: race_free tp),\n      race_free (addThread c p).\n  Proof.\n    unfold race_free in *. intros.\n    simpl.\n    match goal with\n      | [ |- context[ match ?Expr with _ => _ end]] =>\n        destruct Expr as [ord0|] eqn:Hget0\n    end;\n      match goal with\n        | [ |- context[ match ?Expr with _ => _ end]] =>\n          destruct Expr as [ord1|] eqn:Hget1\n      end; simpl in *.\n    - apply unlift_m_inv in Hget0.\n      apply unlift_m_inv in Hget1. subst.\n      destruct ord0 as [tid0 pf0], ord1 as [tid1 pf1]; simpl in Htid.\n      eapply Hrace; eauto.\n    - apply unlift_m_inv in Hget0.\n      subst. unfold newShareMap_wf in Hwf.\n      destruct ord0. eapply Hwf; eauto.\n    - apply unlift_m_inv in Hget1.\n      subst. unfold newShareMap_wf in Hwf.\n      destruct ord1. apply shareMapsJoins_comm. eapply Hwf; eauto.\n    - destruct (tid0 == num_threads) eqn:Heq0.\n      + move/eqP:Heq0=>Heq0. subst.\n        assert (Hcontra: (ordinal_pos_incr num_threads) !=\n                                                        (Ordinal (n:=num_threads.+1) (m:=tid0') Htid0')).\n        { apply/eqP. intros Hcontra.\n          unfold ordinal_pos_incr in Hcontra.\n          inversion Hcontra; auto.\n        }\n        exfalso. apply unlift_some in Hcontra. rewrite Hget1 in Hcontra.\n        destruct Hcontra. discriminate.\n      + move/eqP:Heq0=>Heq0.\n        assert (Hcontra: (ordinal_pos_incr num_threads) !=\n                                                        (Ordinal (n:=num_threads.+1) (m:=tid0) Htid0)).\n        { apply/eqP. intros Hcontra.\n          unfold ordinal_pos_incr in Hcontra. inversion Hcontra. subst. auto. }\n        exfalso. apply unlift_some in Hcontra. rewrite Hget0 in Hcontra. destruct Hcontra.\n        discriminate.\n  Defined.\n\n  Definition updThreadC tid (cont: containsThread tp tid) (c' : ctl) : thread_pool :=\n    mk num_threads (fun (n : 'I_num_threads) =>\n                      if n == (Ordinal cont) then c' else tp n) (share_maps tp).\n\n  Definition updThreadS tid (cont: containsThread tp tid) (smap' : share_map) :\n    thread_pool :=\n    mk num_threads (pool tp) (fun (n : 'I_num_threads) =>\n                                if n == (Ordinal cont) then smap'\n                                else (share_maps tp) n).\n\n  Definition shareMap_wf smap tid :=\n    forall tid0 (Htid0 : tid0 < num_threads) (Hneq: tid <> tid0),\n      shareMapsJoins ((share_maps tp) (Ordinal Htid0)) smap.\n\n  Definition updThread tid (cont : containsThread tp tid) (c' : ctl)\n             (smap : share_map) : thread_pool :=\n    mk num_threads\n        (fun (n : 'I_num_threads) =>\n           if n == (Ordinal cont) then c' else tp n)\n        (fun (n : 'I_num_threads) =>\n           if n == (Ordinal cont) then smap else (share_maps tp) n).\n\n  Lemma updThread_wf : forall tid (pf : containsThread tp tid) smap\n                         (Hwf: shareMap_wf smap tid)\n                         c'\n                         (Hrace_free: race_free tp),\n                         race_free (updThread pf c' smap).\n  Proof.\n    intros.\n    unfold race_free. intros.\n    simpl.\n    destruct (Ordinal (n:=num_threads) (m:=tid0) Htid0 ==  Ordinal (n:=num_threads) (m:=tid) pf) eqn:Heq0,\n                                                                                                     (Ordinal (n:=num_threads) (m:=tid0') Htid0' == Ordinal (n:=num_threads) (m:=tid) pf) eqn:Heq0'.\n    - move/eqP:Heq0 => Heq0. subst.\n      move/eqP:Heq0' => Heq0'. inversion Heq0'. inversion Heq0; subst. exfalso; auto.\n    - move/eqP:Heq0=>Heq0. inversion Heq0. subst.\n      apply shareMapsJoins_comm.\n      eapply Hwf. simpl; auto.\n    - move/eqP:Heq0'=>Heq0'. inversion Heq0'. subst.\n      eapply Hwf. simpl; auto.\n    - simpl in *. eapply Hrace_free; eauto.\n  Defined.\n\n\n  Definition getThreadC tid (cont : containsThread tp tid) : ctl :=\n    tp (Ordinal cont).\n\n  Definition getThreadS tid (cont : containsThread tp tid) : share_map :=\n    (share_maps tp) (Ordinal cont).\n\n  Import Maps.\n\n  Definition perm_compatible p :=\n    forall tid (cont : containsThread tp tid) (b : positive) (ofs : Z) ,\n      Mem.perm_order'' (Maps.PMap.get b p ofs)\n                       (Maps.PMap.get b (share_to_access_map (getThreadS cont)) ofs).\n\n  Record mem_compatible m :=\n    { perm_comp: perm_compatible (getMaxPerm m);\n      mem_canonical: isCanonical (getMaxPerm m)\n    }.\n\nEnd poolDefs.\n\nSection poolLemmas.\n\n  Context {cT : Type} (tp : ThreadPool.t cT).\n\n  Import ThreadPool.\n\n  Lemma updThreadS_cnt : forall tid tp' (cnt: containsThread tp tid) smap\n                           (Hupd: tp' = updThreadS cnt smap),\n      containsThread tp' tid.\n  Proof.\n    intros. unfold containsThread, updThreadS in *. subst. now simpl.\n  Defined.\n\n\n  (*This broke owhen lifting getters and setters for ThreadC. Should be fixed. Nick\n    suggested to abstract the machine_state for both machines and have only one set\n    of proofs.*)\n  (*\n  Lemma gssThreadCode (tid : 'I_(num_threads tp)) c' p' counter' :\n    getThreadC (updThread tp tid c' p' counter') tid = c'.\n  Proof. by rewrite /getThreadC /updThread /= eq_refl. Defined.\n\n  Lemma gsoThread (tid tid' : 'I_(num_threads tp)) c' p' counter':\n    tid' != tid -> getThreadC (updThread tp tid c' p' counter') tid' = getThreadC tp tid'.\n  Proof. by rewrite /getThreadC /updThread /=; case Heq: (tid' == tid). Defined.\n\n  Lemma gssThreadPerm (tid : 'I_(num_threads tp)) c' p' counter' :\n    getThreadPerm (updThread tp tid c' p' counter') tid = p'.\n  Proof. by rewrite /getThreadC /updThread /= eq_refl. Defined.\n\n  Lemma gsoThreadPerm (tid tid' : 'I_(num_threads tp)) c' p' counter':\n    tid' != tid -> getThreadPerm (updThread tp tid c' p' counter') tid' = getThreadPerm tp tid'.\n  Proof. by rewrite /getThreadPerm /updThread /=; case Heq: (tid' == tid). Defined.\n\n  Lemma getAddThread c pmap tid :\n    tid = ordinal_pos_incr (num_threads tp) ->\n    getThreadC (addThread tp c pmap) tid = c.\n  Proof. by rewrite /getThreadC /addThread /= => <-; rewrite unlift_none. Qed. *)\n\n  Lemma permMapsInv_lt : forall p (Hinv: perm_compatible tp p) tid\n                           (cont : containsThread tp tid),\n      permMapLt (share_to_access_map (getThreadS cont)) p.\n  Proof.\n    intros.\n    unfold permMapLt; auto.\n  Qed.\n\n  Definition restrPermMap p' m (Hlt: permMapLt p' (getMaxPerm m)) : mem.\n  Proof.\n    refine ({|\n               Mem.mem_contents := Mem.mem_contents m;\n               Mem.mem_access :=\n                 (fun ofs k =>\n                    match k with\n                      | Cur => None\n                      | Max => fst (Mem.mem_access m) ofs k\n                    end, Maps.PTree.map (fun b f =>\n                                           fun ofs k =>\n                                             match k with\n                                               | Cur =>\n                                                 (Maps.PMap.get b p') ofs\n                                               | Max =>\n                                                 f ofs Max\n                                             end) (Mem.mem_access m).2);\n               Mem.nextblock := Mem.nextblock m;\n               Mem.access_max := _;\n               Mem.nextblock_noaccess := _;\n               Mem.contents_default := Mem.contents_default m |}).\n    - unfold permMapLt in Hlt.\n      assert (Heq: forall b ofs, Maps.PMap.get b (getMaxPerm m) ofs =\n                            Maps.PMap.get b (Mem.mem_access m) ofs Max).\n      { unfold getMaxPerm. intros.\n        rewrite Maps.PMap.gmap. reflexivity. }\n      intros.\n      specialize (Hlt b ofs).\n      specialize (Heq b ofs).\n      unfold getMaxPerm in Hlt.\n      unfold Maps.PMap.get in *. simpl in *.\n      rewrite Maps.PTree.gmap; simpl.\n      match goal with\n        | [|- context[match Coqlib.option_map ?Expr1 ?Expr2  with _ => _ end]] =>\n          destruct (Coqlib.option_map Expr1 Expr2) as [f|] eqn:?\n      end; auto; unfold Coqlib.option_map in Heqo.\n      destruct (Maps.PTree.get b (Mem.mem_access m).2) eqn:?; try discriminate.\n      + inversion Heqo; subst; clear Heqo.\n        rewrite Heq in Hlt. auto.\n      + unfold Mem.perm_order''. by destruct ((Mem.mem_access m).1 ofs Max).\n    - intros b ofs k Hnext.\n    - unfold permMapLt in Hlt.\n      assert (Heq: forall b ofs, Maps.PMap.get b (getMaxPerm m) ofs =\n                            Maps.PMap.get b (Mem.mem_access m) ofs Max).\n      { unfold getMaxPerm. intros.\n        rewrite Maps.PMap.gmap. reflexivity. }\n      specialize (Hlt b ofs).\n      specialize (Heq b ofs).\n      unfold Maps.PMap.get in *.\n      simpl in *.\n      rewrite Maps.PTree.gmap; simpl.\n      assert (H := Mem.nextblock_noaccess m).\n      specialize (H b). unfold Maps.PMap.get in H.\n      match goal with\n        | [|- context[match Coqlib.option_map ?Expr1 ?Expr2  with _ => _ end]] =>\n          destruct (Coqlib.option_map Expr1 Expr2) as [f|] eqn:?\n      end; auto; unfold Coqlib.option_map in Heqo;\n      destruct (Maps.PTree.get b (Mem.mem_access m).2) eqn:Heqo2; try discriminate.\n      inversion Heqo. subst f. clear Heqo.\n      destruct k; auto.\n      rewrite Heq in Hlt.\n      specialize (H ofs Max). rewrite H in Hlt; auto.\n      unfold Mem.perm_order'' in Hlt. destruct (Maps.PTree.get b p'.2).\n      destruct (o0 ofs); tauto.\n      destruct (p'.1 ofs); tauto.\n      rewrite H; auto. destruct k; auto.\n  Defined.\n\n  Lemma restrPermMap_nextblock :\n    forall p' m (Hlt: permMapLt p' (getMaxPerm m)),\n      Mem.nextblock (restrPermMap Hlt) = Mem.nextblock m.\n  Proof.\n    intros. unfold restrPermMap. reflexivity.\n  Qed.\n\n  Lemma restrPermMap_irr : forall p' p'' m\n                             (Hlt : permMapLt p' (getMaxPerm m))\n                             (Hlt': permMapLt p'' (getMaxPerm m))\n                             (Heq_new: p' = p''),\n                             restrPermMap Hlt = restrPermMap Hlt'.\n  Proof.\n    intros. subst.\n    apply f_equal. by apply proof_irr.\n  Qed.\n\n  Lemma restrPermMap_disjoint_inv:\n    forall (mi mj m : mem) (pi pj : access_map)\n      (Hcan_m: isCanonical (getMaxPerm m))\n      (Hltj: permMapLt pj (getMaxPerm m))\n      (Hlti: permMapLt pi (getMaxPerm m))\n      (Hdisjoint: permMapsDisjoint pi pj)\n      (Hrestrj: restrPermMap Hltj = mj)\n      (Hrestri: restrPermMap Hlti = mi),\n      permMapsDisjoint (getCurPerm mi) (getCurPerm mj).\n  Proof.\n    intros. rewrite <- Hrestri. rewrite <- Hrestrj.\n    unfold restrPermMap, getCurPerm, permMapsDisjoint. simpl in *.\n    intros b ofs.\n    do 2 rewrite Maps.PMap.gmap.\n    clear Hrestrj Hrestri.\n    unfold permMapLt, Mem.perm_order'' in *.\n    specialize (Hltj b ofs); specialize (Hlti b ofs).\n    unfold getMaxPerm in *; simpl in *.\n    rewrite Maps.PMap.gmap in Hlti, Hltj.\n    unfold permMapsDisjoint, Maps.PMap.get in *; simpl in *.\n    do 2 rewrite Maps.PTree.gmap. unfold Coqlib.option_map.\n    specialize (Hdisjoint b ofs).\n    assert (Hnone: (Mem.mem_access m).1 ofs Max = None)\n      by (unfold isCanonical in Hcan_m; simpl in Hcan_m;\n            by apply equal_f with (x:=ofs) in Hcan_m).\n    destruct (Maps.PTree.get b (Mem.mem_access m).2) eqn:?; auto.\n    rewrite Hnone in Hlti, Hltj;\n      destruct (Maps.PTree.get b pi.2)\n      as [f1 |] eqn:?;\n                destruct (Maps.PTree.get b pj.2) as [f2|] eqn:?;\n      repeat match goal with\n               | [H: match ?Expr with _ => _ end |- _] => destruct Expr\n             end; tauto.\n  Qed.\n\n  Lemma no_race_wf : forall tid (cont: containsThread tp tid) (Hrace: race_free tp),\n                       shareMap_wf tp (getThreadS cont) tid.\n  Proof.\n    intros; unfold shareMap_wf, getThreadS in *; auto.\n  Defined.\n\nEnd poolLemmas.\n\nModule Concur.\n  Section Concur.\n\n    Import ThreadPool.\n    Context {cT G : Type} {the_sem : CoreSemantics G cT Mem.mem}.\n\n    Notation thread_pool := (t cT).\n    Notation perm_map := access_map.\n\n    Variable the_ge : G.\n    Definition ls_id : nat := 0.\n    Definition sp_id : nat := 1.\n\n    Record invariant (tp : thread_pool) :=\n      { no_race : race_free tp;\n        lock_set : forall (cont : containsThread tp ls_id), exists c,\n              getThreadC cont = Krun c /\\ halted the_sem c;\n        share_pool : forall (cont : containsThread tp sp_id), exists c,\n              getThreadC cont = Krun c /\\ halted the_sem c }.\n\n    (* Semantics of the coarse-grained concurrent machine*)\n    (* Definition cont2ord {ms tid0} (cnt: containsThread ms tid0) := *)\n    (*   Ordinal cnt. *)\n\n    Inductive dry_step {tid0 tp m} (cnt: containsThread tp tid0)\n      (Hcompatible: mem_compatible tp m) : thread_pool -> mem  -> Prop :=\n    | step_dry :\n        forall (tp':thread_pool) c m1 m' (c' : cT),\n          let: smap := getThreadS cnt in\n          forall (Hrestrict_pmap:\n               restrPermMap (permMapsInv_lt (perm_comp Hcompatible) cnt) = m1)\n            (Hinv : invariant tp)\n            (Hthread: getThreadC cnt = Krun c)\n            (Hcorestep: corestep the_sem the_ge c m1 c' m')\n            (Htp': tp' = updThread cnt (Krun c')\n                                   (access_to_share_map smap (getCurPerm m'))),\n            dry_step cnt Hcompatible tp' m'.\n\n    (*missing lock-ranges*)\n    Inductive ext_step {tid0 tp m}\n              (cnt0: containsThread tp tid0) (Hcompat: mem_compatible tp m):\n      thread_pool -> mem -> Prop :=\n    | step_lock :\n        forall (tp' tp'':thread_pool) m1 c c' m' b ofs smap_sp' smap_tid' tmap\n          (cnt_ls: containsThread tp ls_id)\n          (cnt_sp: containsThread tp sp_id),\n          let: smap_tid := getThreadS cnt0 in\n          let: smap_sp := getThreadS cnt_sp in\n          forall\n            (Hinv : invariant tp)\n            (Hthread: getThreadC cnt0 = Kstop c)\n            (Hat_external: at_external the_sem c =\n                           Some (LOCK, ef_sig LOCK, Vptr b ofs::nil))\n            (Hcompatible: mem_compatible tp m)\n            (Hrestrict_pmap:\n               restrPermMap (permMapsInv_lt (perm_comp Hcompatible) cnt_ls) = m1)\n            (Hload: Mem.load Mint32 m1 b (Int.intval ofs) = Some (Vint Int.one))\n            (Hstore: Mem.store Mint32 m1 b (Int.intval ofs) (Vint Int.zero) = Some m')\n            (Hat_external: after_external the_sem (Some (Vint Int.zero)) c = Some c')\n            (Hjoin1: shareMapsJoin smap_sp' tmap smap_sp)\n            (Hjoin2: shareMapsJoin smap_tid tmap smap_tid')\n            (Htp': tp' = updThreadS cnt_sp smap_sp')\n            (Htp'': tp'' = updThread (updThreadS_cnt Htp') (Kresume c')\n                                     smap_tid'),\n            ext_step cnt0 Hcompat tp'' m'\n\n    | step_unlock :\n        forall  (tp' tp'':thread_pool) m1 c c' m' b ofs smap_sp' smap_tid' tmap\n           (cnt_ls: containsThread tp ls_id)\n           (cnt_sp: containsThread tp sp_id),\n          let: smap_tid := getThreadS cnt0 in\n          let: smap_sp := getThreadS cnt_sp in\n          forall\n            (Hinv : invariant tp)\n            (Hthread: getThreadC cnt0 = Kstop c)\n            (Hat_external: at_external the_sem c =\n                           Some (UNLOCK, ef_sig UNLOCK, Vptr b ofs::nil))\n            (Hrestrict_pmap:\n               restrPermMap (permMapsInv_lt (perm_comp Hcompat) cnt_ls) = m1)\n            (Hload: Mem.load Mint32 m1 b (Int.intval ofs) = Some (Vint Int.zero))\n            (Hstore: Mem.store Mint32 m1 b (Int.intval ofs) (Vint Int.one) = Some m')\n            (Hat_external: after_external the_sem (Some (Vint Int.zero)) c = Some c')\n            (Hjoin1: shareMapsJoin smap_tid' tmap smap_tid)\n            (Hjoin2: shareMapsJoin smap_sp tmap smap_sp')\n            (Htp': tp' = updThreadS cnt_sp smap_sp')\n            (Htp'': tp'' = updThread (updThreadS_cnt Htp') (Kresume c')\n                                   smap_tid'),\n            ext_step cnt0 Hcompat tp'' m'\n\n    | step_create :\n        forall  (tp_upd tp':thread_pool) c c' c_new vf arg smap_tid' tmap\n           (cnt_ls: containsThread tp ls_id)\n           (cnt_sp: containsThread tp sp_id),\n          let: smap_tid := getThreadS cnt0 in\n          forall\n            (Hinv : invariant tp)\n            (Hthread: getThreadC cnt0 = Kstop c)\n            (Hat_external: at_external the_sem c =\n                           Some (CREATE, ef_sig CREATE, vf::arg::nil))\n            (Hinitial: initial_core the_sem the_ge vf (arg::nil) = Some c_new)\n            (Hafter_external: after_external the_sem\n                                             (Some (Vint Int.zero)) c = Some c')\n            (Hjoin: shareMapsJoin smap_tid' tmap smap_tid)\n            (Htp_upd: tp_upd = updThread cnt0 (Kresume c') smap_tid')\n            (Htp': tp' = addThread tp_upd c_new tmap),\n            ext_step cnt0 Hcompat tp' m\n\n    | step_mklock :\n        forall  (tp' tp'': thread_pool) m1 c c' m' b ofs smap_tid' smap_ls'\n           (cnt_ls: containsThread tp ls_id),\n          let: smap_tid := getThreadS cnt0 in\n          let: smap_ls := getThreadS cnt_ls in\n          forall\n            (Hinv : invariant tp)\n            (Hthread: getThreadC cnt0 = Kstop c)\n            (Hat_external: at_external the_sem c =\n                           Some (MKLOCK, ef_sig MKLOCK, Vptr b ofs::nil))\n            (Hrestrict_pmap: restrPermMap\n                               (permMapsInv_lt (perm_comp Hcompat) cnt_ls) = m1)\n            (Hstore: Mem.store Mint32 m1 b (Int.intval ofs) (Vint Int.zero) = Some m')\n            (Hdrop_share:\n               setShare extern_retainer b (Int.intval ofs) smap_tid = smap_tid')\n            (Hlp_share: setShare Ews\n                               b (Int.intval ofs) smap_ls = smap_ls')\n            (Hafter_external: after_external\n                                the_sem (Some (Vint Int.zero)) c = Some c')\n            (Htp': tp' = updThreadS cnt_ls smap_ls')\n            (Htp'':\n               tp'' = updThread (updThreadS_cnt Htp') (Kresume c') smap_tid'),\n            ext_step cnt0 Hcompat tp'' m'\n\n    | step_freelock :\n        forall  (tp' tp'': thread_pool) c c' b ofs smap_tid' smap_ls'\n           (cnt_ls: containsThread tp ls_id),\n          let: smap_tid := getThreadS cnt0 in\n          let: smap_ls := getThreadS cnt_ls in\n          forall\n            (Hinv : invariant tp)\n            (Hthread: getThreadC cnt0 = Kstop c)\n            (Hat_external: at_external the_sem c =\n                           Some (FREE_LOCK, ef_sig FREE_LOCK, Vptr b ofs::nil))\n            (Hdrop_share:\n               setShare Share.bot b (Int.intval ofs) smap_ls = smap_ls')\n            (Hafter_external: after_external\n                                the_sem (Some (Vint Int.zero)) c = Some c')\n            (Htp': tp' = updThreadS cnt_ls smap_ls')\n            (Htp'':\n               tp'' = updThread (updThreadS_cnt Htp') (Kresume c') smap_tid'),\n            ext_step cnt0 Hcompat  tp'' m\n\n    | step_lockfail :\n        forall  c b ofs m1\n           (cnt_ls: containsThread tp ls_id),\n          forall\n            (Hinv : invariant tp)\n            (Hthread: getThreadC cnt0 = Kstop c)\n            (Hat_external: at_external the_sem c =\n                           Some (LOCK, ef_sig LOCK, Vptr b ofs::nil))\n            (Hrestrict_pmap: restrPermMap\n                               (permMapsInv_lt (perm_comp Hcompat) cnt_ls) = m1)\n            (Hload: Mem.load Mint32 m1 b (Int.intval ofs) = Some (Vint Int.zero)),\n            ext_step cnt0 Hcompat tp m.\n  End Concur.\n\n  Module ShareMachineSig (Sem: Semantics) <: ConcurrentMachineSig NatTID.\n    (*TID = NAT*)\n    Definition tid := nat.\n    (*Memories*)\n    Definition richMem: Type:= Sem.M.\n    Definition dryMem: richMem -> mem:= fun x => x.\n\n    (*CODE*)\n    Definition cT: Type:= Sem.C.\n    Definition G: Type:= Sem.G.\n    Definition Sem := Sem.Sem.\n    Definition cT': Type := @ctl cT.\n\n    (*thread pool*)\n    Import ThreadPool.\n    Notation thread_pool := (t cT).\n\n    (*MACHINE VARIABLES*)\n    Definition machine_state: Type:= thread_pool.\n    Definition containsThread: machine_state -> tid -> Prop:=\n      fun ms tid0 => tid0 < (num_threads ms).\n    Definition ls_id : tid:= 0.\n    Definition sp_id : tid:= 1.\n\n    (*INVARIANTS*)\n    (*The state respects the memory*)\n    Definition mem_compatible: machine_state -> mem -> Prop:=\n      @mem_compatible cT.\n\n    (*CODE GETTER AND SETTER*)\n    Definition getThreadC: forall {ms tid0}, containsThread ms tid0 -> @ctl cT:= @getThreadC cT.\n    Definition updThreadC: forall {ms tid0}, containsThread ms tid0 -> @ctl cT -> machine_state:= @updThreadC cT.\n\n    (*Steps*)\n    Definition cstep (genv:G): forall {tid0 ms m},\n                                 containsThread ms tid0 -> mem_compatible ms m ->\n                                 machine_state -> mem -> Prop:=\n      @dry_step cT G Sem genv.\n\n    Definition conc_call (genv:G):\n      forall {tid0 ms m},\n        containsThread ms tid0 -> mem_compatible ms m ->\n        machine_state -> mem -> Prop:=\n      fun tid ms m => @ext_step cT G Sem genv tid ms m.\n\n    Inductive threadHalted': forall {tid0 ms},\n                               containsThread ms tid0 -> Prop:=\n    | thread_halted':\n        forall tp c tid0\n          (cnt: containsThread tp tid0),\n          let: tid := Ordinal cnt in\n          forall\n            (Hthread: getThreadC cnt = Krun c)\n            (Hcant: halted Sem c),\n            threadHalted' cnt.\n    Definition threadHalted: forall {tid0 ms},\n                               containsThread ms tid0 -> Prop:= @threadHalted'.\n\n    Lemma onePos: (0<1)%coq_nat. auto. Qed.\n    Definition initial_machine c:=\n      @mk cT (mkPos onePos) (fun _ => c) (fun _ => empty_share_map) .\n    Definition init_mach  (genv:G)(v:val)(args:list val):option machine_state:=\n      match initial_core Sem genv v args with\n      | Some c => Some (initial_machine (Kresume c) )\n      | None => None\n      end.\n  End ShareMachineSig.\n\n\n  (* Here I make the core semantics*)\n  Variable example_G: Type.\n  Variable example_C: Type.\n  Variable example_sem: CoreSemantics example_G example_C mem.\n  Module Sem: Semantics.\n    Definition G:= example_G.\n    Definition C:= example_C.\n    Definition M:= mem.\n    Definition Sem:=example_sem.\n  End Sem.\n  Module mySchedule := ListScheduler NatTID.\n  Module mySem := ShareMachineSig Sem.\n  Module myCoarseSemantics :=\n    CoarseMachine NatTID mySchedule mySem.\n  Module myFineSemantics :=\n    FineMachine NatTID mySchedule mySem.\n\n  Definition coarse_semantics:=\n    myCoarseSemantics.MachineSemantics.\n  Definition fine_semantics:=\n    myFineSemantics.MachineSemantics.\n\nEnd Concur.\n\n\n\n(* After this there needs to be some cleaning. *)\n\n\n\n\n\n\n\n\n\n\n(* Section InitialCore. *)\n\n(*   Context {cT G : Type} {the_sem : CoreSemantics G cT Mem.mem}. *)\n(*   Import ThreadPool. *)\n\n\n(*   Notation thread_pool := (t cT). *)\n(*   Notation perm_map := access_map. *)\n\n(*   Definition at_external (st : (list nat) * thread_pool) *)\n(*   : option (external_function * signature * seq val) := None. *)\n\n(*   Definition after_external (ov : option val) (st : list nat * thread_pool) : *)\n(*     option (list nat * thread_pool) := None. *)\n\n(*   Definition two_pos : pos := mkPos NPeano.Nat.lt_0_2. *)\n\n(*   Definition ord1 := Ordinal (n := two_pos) (m := 1) (leqnn two_pos). *)\n\n(*   (*not clear what the value of halted should be*) *)\n(*   Definition halted (st : list nat * thread_pool) : option val := None. *)\n\n(*   Variable compute_init_perm : G -> access_map. *)\n(*   Variable lp_code : cT. *)\n(*   Variable sched : list nat. *)\n\n(*   Definition initial_core the_ge (f : val) (args : list val) : option (list nat * thread_pool) := *)\n(*     match initial_core the_sem the_ge f args with *)\n(*       | None => None *)\n(*       | Some c => *)\n(*         Some (sched, ThreadPool.mk *)\n(*                        two_pos *)\n(*                        (fun tid => if tid == ord0 then lp_code *)\n(*                                 else if tid == ord1 then c *)\n(*                                      else c (*bogus value; can't occur*)) *)\n(*                        (fun tid => if tid == ord0 then empty_map else *)\n(*                                   if tid == ord1 then compute_init_perm the_ge *)\n(*                                   else empty_map) *)\n(*                        0) *)\n(*     end. *)\n\n(*   Variable aggelos : nat -> access_map. *)\n\n(*   Definition cstep (the_ge : G) (st : list nat * thread_pool) m *)\n(*              (st' : list nat * thread_pool) m' := *)\n(*     @step cT G the_sem the_ge aggelos (@coarse_step cT G the_sem the_ge) *)\n(*           (fst st) (snd st) m (fst st') (snd st') m'. *)\n\n(*   Definition fstep (the_ge : G) (st : list nat * thread_pool) m *)\n(*              (st' : list nat * thread_pool) m' := *)\n(*     @step cT G the_sem the_ge aggelos (@fine_step cT G the_sem the_ge) *)\n(*           (fst st) (snd st) m (fst st') (snd st') m'. *)\n\n(*   Program Definition coarse_semantics : *)\n(*     CoreSemantics G (list nat * thread_pool) mem := *)\n(*     Build_CoreSemantics _ _ _ *)\n(*                         initial_core *)\n(*                         at_external *)\n(*                         after_external *)\n(*                         halted *)\n(*                         cstep *)\n(*                         _ _ _. *)\n\n(*   Program Definition fine_semantics : *)\n(*     CoreSemantics G (list nat * thread_pool) mem := *)\n(*     Build_CoreSemantics _ _ _ *)\n(*                         initial_core *)\n(*                         at_external *)\n(*                         after_external *)\n(*                         halted *)\n(*                         fstep *)\n(*                         _ _ _. *)\n\n(* End InitialCore. *)\n\n(* End Concur. *)", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/concurrency/compcert_threads.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.23435878005960464}}
{"text": "Require Import BinNat.\nRequire Import Bool.\nRequire Import Omega.\nRequire Import sflib.\n\nRequire Import Common.\nRequire Import Value.\nRequire Import Memory.\nRequire Import State.\nRequire Import Behaviors.\nRequire Import SmallStep.\n\nModule Ir.\n\nModule Refinement.\n\nDefinition refines_value (v_tgt v_src:Ir.val): bool :=\n  match (v_tgt, v_src) with\n  | (_, Ir.poison) => true\n  | (Ir.num ntgt, Ir.num nsrc) => Nat.eqb ntgt nsrc\n  | (Ir.ptr ptgt, Ir.ptr psrc) => Ir.ptr_eqb ptgt psrc\n  | (_, _) => false\n  end.\n\nDefinition refines_bit (b_tgt b_src:Ir.Bit.t): bool :=\n  match (b_src, b_tgt) with\n  | (Ir.Bit.bpoison, _) => true\n  | (_, Ir.Bit.bpoison) => false\n  | (Ir.Bit.bint b1, Ir.Bit.bint b2) => Bool.eqb b1 b2\n  | (Ir.Bit.baddr p1 o1, Ir.Bit.baddr p2 o2) =>\n    Nat.eqb o1 o2 && Ir.ptr_eqb p1 p2\n  | (_, _) => false\n  end.\n\nDefinition refines_byte (b_tgt b_src:Ir.Byte.t): bool :=\n  refines_bit b_tgt.(Ir.Byte.b0) b_src.(Ir.Byte.b0) &&\n  refines_bit b_tgt.(Ir.Byte.b1) b_src.(Ir.Byte.b1) &&\n  refines_bit b_tgt.(Ir.Byte.b2) b_src.(Ir.Byte.b2) &&\n  refines_bit b_tgt.(Ir.Byte.b3) b_src.(Ir.Byte.b3) &&\n  refines_bit b_tgt.(Ir.Byte.b4) b_src.(Ir.Byte.b4) &&\n  refines_bit b_tgt.(Ir.Byte.b5) b_src.(Ir.Byte.b5) &&\n  refines_bit b_tgt.(Ir.Byte.b6) b_src.(Ir.Byte.b6) &&\n  refines_bit b_tgt.(Ir.Byte.b7) b_src.(Ir.Byte.b7).\n\nDefinition refines_event (e_tgt e_src:Ir.event): bool :=\n  match (e_tgt, e_src) with\n  | (Ir.e_some vtgt, Ir.e_some vsrc) => Nat.eqb vtgt vsrc\n  | (Ir.e_none, Ir.e_none) => true\n  | _ => false\n  end.\n\nDefinition refines_trace (tr_tgt tr_src:Ir.trace):bool :=\n  let tr_tgt' := List.filter Ir.not_none tr_tgt in\n  let tr_src' := List.filter Ir.not_none tr_src in\n  if Nat.eqb (List.length tr_tgt') (List.length tr_src') then\n    List.forallb (fun ee => refines_event ee.(fst) ee.(snd))\n                 (List.combine tr_tgt' tr_src')\n  else false.\n\n(* If tgts_prefix is true, check whether tr_tgt has a prefix\n   that refines tr_src.\n   If tgts_prefix is false, check whether tr_src has a prefix\n   so tr_tgt refines the prefix. *)\nDefinition refines_trace_prefix (tr_tgt tr_src:Ir.trace) (tgts_prefix:bool)\n: bool :=\n  let tr_tgt' := List.filter Ir.not_none tr_tgt in\n  let tr_src' := List.filter Ir.not_none tr_src in\n  let (tr_tgt', tr_src') :=\n      if tgts_prefix then (List.firstn (List.length tr_src') tr_tgt', tr_src')\n      else (tr_tgt', List.firstn (List.length tr_tgt') tr_src') in\n  refines_trace tr_tgt' tr_src'.\n\n\n(* Checks whether the behavior of a target program refines the behavior of a source program. *)\nDefinition refines (pb_tgt pb_src:Ir.program_behavior):bool :=\n  match (pb_tgt, pb_src) with\n  | (Ir.b_terminates tr_tgt ret_tgt, Ir.b_terminates tr_src ret_src) =>\n    refines_trace tr_tgt tr_src && refines_value ret_tgt ret_src\n\n  | (Ir.b_terminates tr_tgt ret_tgt, Ir.b_diverges tr_src) =>\n    (* infinite loop without any event is UB.\n       Chech whether target's trace has a prefix that refines trace of the source. *)\n    refines_trace_prefix tr_tgt tr_src true\n\n  | (Ir.b_terminates tr_tgt ret_tgt, Ir.b_goes_wrong tr_src) =>\n    refines_trace_prefix tr_tgt tr_src true\n\n  | (Ir.b_diverges tr_tgt, Ir.b_diverges tr_src) =>\n    refines_trace tr_tgt tr_src\n\n  | (Ir.b_diverges tr_tgt, Ir.b_goes_wrong tr_src) =>\n    refines_trace tr_tgt tr_src\n\n  | (Ir.b_goes_wrong tr_tgt, Ir.b_diverges tr_src) =>\n    refines_trace tr_tgt tr_src\n\n  | (Ir.b_goes_wrong tr_tgt, Ir.b_goes_wrong tr_src) =>\n    refines_trace tr_tgt tr_src\n\n  | (Ir.b_oom tr_tgt, Ir.b_terminates tr_src ret_src) =>\n    refines_trace_prefix tr_tgt tr_src false\n\n  | (Ir.b_oom tr_tgt, Ir.b_diverges tr_src) =>\n    (* If source has UB and target has OOM,\n       either the trace of source may be the prefix of the trace of target,\n       or the trace of target may be the prefix of the trace of source. *)\n    refines_trace_prefix tr_tgt tr_src true ||\n    refines_trace_prefix tr_tgt tr_src false\n\n  | (Ir.b_oom tr_tgt, Ir.b_goes_wrong tr_src) =>\n    refines_trace_prefix tr_tgt tr_src true ||\n    refines_trace_prefix tr_tgt tr_src false\n\n  | (Ir.b_oom tr_tgt, Ir.b_oom tr_src) =>\n    (* target trace should be prefix of source trace. *)\n    refines_trace_prefix tr_tgt tr_src true\n\n  | (_, _) => false\n  end.\n\n(***********************************************************\n   Propositional definition of refinements on memory, state\n ***********************************************************)\n\nDefinition refines_memblock (mb_tgt mb_src:Ir.MemBlock.t) :=\n  mb_tgt.(Ir.MemBlock.bt) = mb_src.(Ir.MemBlock.bt) /\\\n  mb_tgt.(Ir.MemBlock.r) = mb_src.(Ir.MemBlock.r) /\\\n  mb_tgt.(Ir.MemBlock.n) = mb_src.(Ir.MemBlock.n) /\\\n  mb_tgt.(Ir.MemBlock.a) = mb_src.(Ir.MemBlock.a) /\\\n  List.Forall2 (fun b1 b2 => refines_byte b1 b2 = true)\n               mb_tgt.(Ir.MemBlock.c) mb_src.(Ir.MemBlock.c) /\\\n  mb_tgt.(Ir.MemBlock.P) = mb_src.(Ir.MemBlock.P).\n\nDefinition refines_memory (m_tgt m_src:Ir.Memory.t) :=\n  m_tgt.(Ir.Memory.mt) = m_src.(Ir.Memory.mt) /\\\n  List.Forall2 (fun mbid_tgt mbid_src =>\n                  fst mbid_tgt = fst mbid_src /\\\n                  refines_memblock (snd mbid_tgt) (snd mbid_src))\n               m_tgt.(Ir.Memory.blocks) m_src.(Ir.Memory.blocks) /\\\n  m_tgt.(Ir.Memory.calltimes) = m_src.(Ir.Memory.calltimes) /\\\n  m_tgt.(Ir.Memory.fresh_bid) = m_src.(Ir.Memory.fresh_bid).\n\nDefinition refines_regfile (rf_tgt rf_src:Ir.Regfile.t) :=\n  forall regid,\n    (Ir.Regfile.get rf_tgt regid = None <-> Ir.Regfile.get rf_src regid = None) /\\\n    (forall vtgt\n            (HGET:Ir.Regfile.get rf_tgt regid = Some vtgt),\n        exists vsrc, Ir.Regfile.get rf_src regid = Some vsrc /\\\n                     refines_value vtgt vsrc = true).\n\nDefinition refines_stack (s_tgt s_src:Ir.Stack.t) :=\n  List.Forall2 (fun itm_tgt itm_src =>\n                  fst itm_tgt = fst itm_src /\\\n                  fst (snd itm_tgt) = fst (snd itm_src) /\\\n                  refines_regfile (snd (snd itm_tgt)) (snd (snd itm_src)))\n               s_tgt s_src.\n\nDefinition refines_state (s_tgt s_src:Ir.Config.t) :=\n  refines_memory s_tgt.(Ir.Config.m) s_src.(Ir.Config.m) /\\\n  refines_stack s_tgt.(Ir.Config.s) s_src.(Ir.Config.s) /\\\n  s_tgt.(Ir.Config.cid_to_f) = s_src.(Ir.Config.cid_to_f) /\\\n  s_tgt.(Ir.Config.cid_fresh) = s_src.(Ir.Config.cid_fresh).\n\nImport Ir.SmallStep.\n\n(* refines_step_res <tgt> <src> *)\nInductive refines_step_res: step_res -> step_res -> Prop :=\n| srref_tgt_oom:\n    forall sr_src,\n      refines_step_res sr_oom sr_src\n| srref_src_goes_wrong:\n    forall sr_tgt,\n      refines_step_res sr_tgt sr_goes_wrong\n| srref_finish:\n    forall v_tgt v_src\n           (HREFV:refines_value v_tgt v_src),\n    refines_step_res (sr_prog_finish v_tgt) (sr_prog_finish v_src)\n| srref_success:\n    forall e_tgt e_src s_tgt s_src\n           (HREFE:refines_event e_tgt e_src)\n           (HREFS:refines_state s_tgt s_src), (* Just checks equality. *)\n    refines_step_res (sr_success e_tgt s_tgt) (sr_success e_src s_src).\n\n\n\n(***********************************************************\n               Lemmas about refinement.\n ***********************************************************)\n\nTheorem refines_value_refl:\n  forall (v:Ir.val), refines_value v v = true.\nProof.\n  intros.\n  destruct v; unfold refines_value.\n  - rewrite Nat.eqb_eq. auto.\n  - rewrite Ir.ptr_eqb_refl. reflexivity.\n  - reflexivity.\nQed.\n\nTheorem refines_value_trans:\n  forall (v1 v2 v3:Ir.val)\n         (HREF1:refines_value v1 v2 = true)\n         (HREF2:refines_value v2 v3 = true),\n    refines_value v1 v3 = true.\nProof.\n  intros.\n  unfold refines_value in *.\n  des_ifs.\n  rewrite PeanoNat.Nat.eqb_eq in *.\n  congruence.\n  unfold Ir.ptr_eqb in *.\n  des_ifs; try rewrite andb_true_iff in *;\n    repeat (rewrite PeanoNat.Nat.eqb_eq in *);\n    destruct HREF1; destruct HREF2;\n    try congruence.\n  split; congruence.\n  repeat (rewrite andb_true_iff in *);\n    repeat (rewrite PeanoNat.Nat.eqb_eq in *).\n  destruct H. destruct H. destruct H1.  destruct H1.\n  split; try congruence.\n  split; try congruence.\n  split; try congruence.\n  eapply list_inclb_trans. eapply H4. ss.\n  eapply list_inclb_trans. eapply H5. ss.\n  split; try ss.\n  repeat (rewrite andb_true_iff in *).\n  repeat (rewrite PeanoNat.Nat.eqb_eq in *).\n  intuition.\n  eapply list_inclb_trans. eapply H6. ss.\n  eapply list_inclb_trans. eapply H5. ss.\nQed.\n\nTheorem refines_bit_refl:\n  forall b, refines_bit b b = true.\nProof.\n  unfold refines_bit.\n  intros.\n  destruct b. destruct b; reflexivity.\n  unfold Ir.ptr_eqb.\n  destruct p; repeat (rewrite PeanoNat.Nat.eqb_refl); try reflexivity.\n  repeat (rewrite Common.list_inclb_refl).\n  destruct o. rewrite PeanoNat.Nat.eqb_refl. reflexivity.\n  reflexivity.\n  reflexivity.\nQed.\n\nLemma ptr_eqb_trans:\n  forall p1 p2 p3\n         (H1:Ir.ptr_eqb p1 p2 = true)\n         (H2:Ir.ptr_eqb p2 p3 = true),\n    Ir.ptr_eqb p1 p3 = true.\nProof.\n  intros.\n  unfold Ir.ptr_eqb in *.\n  des_ifs; repeat (rewrite andb_true_iff in *);\n           repeat (rewrite PeanoNat.Nat.eqb_eq in *);\n           try (inv H1; inv H0; fail);\n           try (inv H2; inv H0; fail).\n  intuition.\n  { inv H1. inv H. inv H0.\n    inv H2. inv H. inv H0. \n    split; try ss.\n    split. { split. congruence.\n             eapply list_inclb_trans. eapply H3. ss. }\n           { eapply list_inclb_trans. eapply H2. ss. }\n  }\n  { inv H1. inv H. inv H1.\n    inv H2. inv H. inv H2. \n    split; try ss.\n    split. { split. congruence.\n             eapply list_inclb_trans. eapply H4. ss. }\n           { eapply list_inclb_trans. eapply H5. ss. }\n  }\nQed.\n\nTheorem refines_bit_trans:\n  forall b1 b2 b3\n         (HREF1:refines_bit b1 b2 = true)\n         (HREF2:refines_bit b2 b3 = true),\n    refines_bit b1 b3 = true.\nProof.\n  intros.\n  unfold refines_bit in *.\n  des_ifs.\n  unfold eqb in *. des_ifs.\n  rewrite andb_true_iff in *.\n  repeat (rewrite PeanoNat.Nat.eqb_eq in *).\n  intuition.\n  eapply ptr_eqb_trans. eassumption. ss.\nQed.\n\nLtac unfold_all_ands_H :=\n  repeat (match goal with\n  | [ H : _ /\\ _ |- _ ] => destruct H\n  end).\n\nTheorem refines_byte_trans:\n  forall b1 b2 b3\n         (HREF1:refines_byte b1 b2 = true)\n         (HREF2:refines_byte b2 b3 = true),\n    refines_byte b1 b3 = true.\nProof.\n  intros.\n  unfold refines_byte in *.\n  repeat (rewrite andb_true_iff in *).\n  unfold_all_ands_H.\n  repeat (split; try (eapply refines_bit_trans; try eassumption; assumption)).\nQed.\n\nTheorem refines_memblock_refl:\n  forall mb1,\n    refines_memblock mb1 mb1.\nProof.\n  intros.\n  repeat (split;try congruence).\n  apply Forall2_samelist.\n  intros.\n  unfold refines_byte.\n  repeat (rewrite andb_true_iff).\n  repeat (rewrite refines_bit_refl).\n  repeat (split; try reflexivity).\nQed.\n\nTheorem refines_memblock_trans:\n  forall mb1 mb2 mb3\n         (HREF1:refines_memblock mb1 mb2)\n         (HREF1:refines_memblock mb2 mb3),\n    refines_memblock mb1 mb3.\nProof.\n  intros.\n  inv HREF1. inv H0. inv H2. inv H3.\n  inv HREF0. inv H5. inv H7. inv H8.\n  inv H4. inv H9.\n  repeat (split;try congruence).\n  eapply Forall2_trans.\n  { intros. eapply refines_byte_trans. eassumption. ss.\n  }\n  eassumption. assumption.\nQed.\n\nTheorem refines_memory_refl:\n  forall (m1:Ir.Memory.t),\n    refines_memory m1 m1.\nProof.\n  intros.\n  split.\n  { congruence. }\n  split.\n  { eapply Forall2_samelist.\n    intros. split. reflexivity. apply refines_memblock_refl.\n  }\n  split; reflexivity.\nQed.\n    \nTheorem refines_memory_trans:\n  forall m1 m2 m3\n         (HREF1:refines_memory m1 m2)\n         (HREF1:refines_memory m2 m3),\n    refines_memory m1 m3.\nProof.\n  intros.\n  destruct HREF1.\n  destruct HREF0.\n  unfold_all_ands_H.\n  repeat (split; try congruence).\n  eapply Forall2_trans.\n  { intros.\n    unfold_all_ands_H.\n    split. congruence. eapply refines_memblock_trans. eassumption. ss.\n  }\n  eassumption. assumption.\nQed.\n\nTheorem refines_event_refl:\n  forall (e:Ir.event), refines_event e e = true.\nProof.\n  intros.\n  destruct e. unfold refines_event. reflexivity.\n  unfold refines_event. rewrite Nat.eqb_eq. reflexivity.\nQed.\n\nTheorem refines_trace_refl:\n  forall (t:Ir.trace), refines_trace t t = true.\nProof.\n  intros.\n  induction t.\n  - reflexivity.\n  - unfold refines_trace in *.\n    assert (forall {X:Type} (l:list X), (List.length l =? List.length l) = true).\n    { intros.\n      rewrite Nat.eqb_eq. reflexivity. }\n    rewrite H. rewrite H in IHt.\n    simpl.\n    destruct (Ir.not_none a) eqn:HNN.\n    simpl. rewrite IHt. rewrite refines_event_refl. reflexivity.\n    assumption.\nQed.\n\nTheorem refines_trace_prefix_refl:\n  forall (t:Ir.trace) b, refines_trace_prefix t t b = true.\nProof.\n  intros.\n  destruct b; unfold refines_trace_prefix in *;\n    rewrite List.firstn_all in *;\n    rewrite refines_trace_refl;\n    reflexivity.\nQed.\n\nLemma regfile_eq_empty_false:\n  forall st1 st,\n    ~ Ir.Regfile.eq (st::st1) [].\nProof.\n  intros.\n  intros HEQ.\n  unfold Ir.Regfile.eq in HEQ.\n  destruct st.\n  assert (H := HEQ n).\n  unfold Ir.Regfile.get in H.\n  simpl in H. rewrite PeanoNat.Nat.eqb_refl in H. inv H.\nQed.\n\nTheorem refines_regfile_eq:\n  forall st1 st2 (HEQ:Ir.Regfile.eq st1 st2),\n    refines_regfile st1 st2.\nProof.\n  intros.\n  unfold Ir.Regfile.eq in HEQ.\n  unfold refines_regfile.\n  intros.\n  assert (HEQ' := HEQ regid).\n  split.\n  { split; intros; congruence. }\n  { intros.\n    eexists. rewrite HEQ' in HGET. split. eassumption.\n    eapply refines_value_refl. }\nQed.\n\nTheorem refines_regfile_trans:\n  forall st1 st2 st3\n         (HREF1:refines_regfile st1 st2)\n         (HREF2:refines_regfile st2 st3),\n    refines_regfile st1 st3.\nProof.\n  intros.\n  unfold refines_regfile in *.\n  unfold_all_ands_H.\n  intros.\n  assert (H1 := HREF1 regid).\n  assert (H2 := HREF2 regid).\n  unfold_all_ands_H.\n\n  split.\n  { \n    destruct H1. destruct H.\n    split.\n    { intros. apply H. apply H1. assumption. }\n    { intros. apply H3. apply H4. assumption. }\n  }\n  intros.\n  apply H2 in HGET.\n  destruct HGET. destruct H3.\n  apply H0 in H3. destruct H3. destruct H3.\n  eexists. split. eassumption.\n  eapply refines_value_trans. eassumption. ss.\nQed.\n\nTheorem refines_stack_eq:\n  forall st1 st2 (HEQ:Ir.Stack.eq st1 st2),\n    refines_stack st1 st2.\nProof.\n  intros.\n  generalize dependent st1.\n  induction st2.\n  { intros. destruct st1. constructor.\n    inv HEQ. }\n  { intros.\n    destruct st1. inv HEQ.\n    inv HEQ.\n    inv H2. inv H0.\n    constructor.\n    { split.  congruence. split. congruence.\n      apply refines_regfile_eq. assumption. }\n    eapply Forall2_implies.\n    eapply H4.\n    { intros.\n      destruct x. destruct y. simpl in *.\n      inv H0. inv H5. split. congruence. split. congruence.\n      apply refines_regfile_eq. assumption.\n    }\n  }\nQed.\n\nTheorem refines_stack_trans:\n  forall st1 st2 st3\n         (HREF1:refines_stack st1 st2)\n         (HREF1:refines_stack st2 st3),\n    refines_stack st1 st3.\nProof.\n  intros.\n  generalize dependent st2.\n  generalize dependent st3.\n  induction st1.\n  { intros. inv HREF1. assumption. }\n  { intros.\n    destruct st2. inv HREF1.\n    destruct st3. inv HREF0.\n    inv HREF1. inv HREF0.\n    unfold_all_ands_H.\n    constructor.\n    { split. congruence. split. congruence.\n      eapply refines_regfile_trans. eassumption. ss. }\n    { eapply Forall2_trans.\n      intros.\n      unfold_all_ands_H.\n      split. congruence. split. congruence.\n      eapply refines_regfile_trans. eassumption. ss.\n      eassumption. ss.\n    }\n  }\nQed.\n\nTheorem refines_state_eq:\n  forall st1 st2 (HEQ:Ir.Config.eq st1 st2),\n    refines_state st1 st2.\nProof.\n  intros.\n  inv HEQ.\n  split.\n  { rewrite H. eapply refines_memory_refl. }\n  inv H0. split.\n  apply refines_stack_eq. assumption.\n  assumption.\nQed.\n\nTheorem refines_refl:\n  forall (pb:Ir.program_behavior), refines pb pb = true.\nProof.\n  intros.\n  destruct pb; unfold refines.\n  - rewrite refines_trace_refl.\n    rewrite refines_value_refl. reflexivity.\n  - rewrite refines_trace_refl. reflexivity.\n  - rewrite refines_trace_refl. reflexivity.\n  - rewrite refines_trace_prefix_refl. reflexivity.\nQed.\n\nTheorem refines_trace_none:\n  forall (t1 t2:Ir.trace)\n         (HREF:refines_trace t1 t2 = true),\n    refines_trace (Ir.e_none::t1) t2 = true.\nProof. intros. unfold refines_trace in *.\n       simpl. assumption.\nQed.\n\nTheorem refines_trace_none2:\n  forall (t1 t2:Ir.trace)\n         (HREF:refines_trace t1 t2 = true),\n    refines_trace t1 (Ir.e_none::t2) = true.\nProof. intros. unfold refines_trace in *.\n       simpl. assumption.\nQed.\n\n\nEnd Refinement.\n\nEnd Ir.", "meta": {"author": "aqjune", "repo": "twinsem", "sha": "c9cc45994bbc7545d32cad0a918492666e6bb69f", "save_path": "github-repos/coq/aqjune-twinsem", "path": "github-repos/coq/aqjune-twinsem/twinsem-c9cc45994bbc7545d32cad0a918492666e6bb69f/Refinement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.23430833831372216}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.PropExtensionality.\nRequire Import riscv.Utility.Monads.\nRequire Import riscv.Utility.MonadNotations.\nRequire Import riscv.Spec.Decode.\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Spec.Primitives.\nRequire Import riscv.Spec.MetricPrimitives.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Export riscv.Platform.RiscvMachine.\nRequire Export riscv.Platform.MetricRiscvMachine.\nRequire Import riscv.Platform.MinimalNoMul.\nRequire Import riscv.Platform.MetricLogging.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Tactics.Tactics.\nImport MetricRiscvMachine.\n\nLocal Open Scope Z_scope.\nLocal Open Scope bool_scope.\n\nSection Riscv.\n  Import List.\n  Import free.\n\n  Context {width: Z} {BW: Bitwidth width} {word: word width} {word_ok: word.ok word}.\n  Context {Mem: map.map word byte}.\n  Context {Registers: map.map Register word}.\n\n  Local Notation M := (free riscv_primitive primitive_result).\n\n  Definition metrics_of(p: riscv_primitive): MetricLog -> MetricLog :=\n    match p with\n    | GetRegister a => id\n    | SetRegister a b => id\n    | LoadByte a b => addMetricLoads 1\n    | LoadHalf a b => addMetricLoads 1\n    | LoadWord a b => addMetricLoads 1\n    | LoadDouble a b => addMetricLoads 1\n    | StoreByte a b c => addMetricStores 1\n    | StoreHalf a b c => addMetricStores 1\n    | StoreWord a b c => addMetricStores 1\n    | StoreDouble a b c => addMetricStores 1\n    | MakeReservation a => id\n    | ClearReservation a => id\n    | CheckReservation a => id\n    | GetCSRField f => id\n    | SetCSRField f v => id\n    | GetPrivMode => id\n    | SetPrivMode m => id\n    | Fence a b => id\n    | GetPC => id\n    | SetPC a => addMetricJumps 1\n    | StartCycle => id\n    | EndCycleNormal => addMetricInstructions 1\n    | EndCycleEarly A => addMetricInstructions 1\n    end.\n\n  Definition interp_action p (m: MetricRiscvMachine) post :=\n    interpret_action p m.(getMachine)\n      (fun r mach => post r (mkMetricRiscvMachine mach (metrics_of p m.(getMetrics))))\n      (fun _ => False).\n\n  Arguments Memory.load_bytes: simpl never.\n  Arguments Memory.store_bytes: simpl never.\n  Arguments LittleEndian.combine: simpl never.\n\n  Global Instance MetricMinimalNoMulPrimitivesParams: PrimitivesParams M MetricRiscvMachine :=\n  {\n    Primitives.mcomp_sat := @free.interp _ _ _ interp_action;\n    Primitives.is_initial_register_value x := True;\n    Primitives.nonmem_load := Primitives.nonmem_load (PrimitivesParams := MinimalNoMulPrimitivesParams);\n    Primitives.nonmem_store := Primitives.nonmem_store (PrimitivesParams := MinimalNoMulPrimitivesParams);\n    Primitives.valid_machine mach := no_M mach.(getMachine);\n  }.\n\n  Global Instance MinimalNoMulSatisfies_mcomp_sat_spec: mcomp_sat_spec MetricMinimalNoMulPrimitivesParams.\n  Proof.\n    split; cbv [mcomp_sat MetricMinimalNoMulPrimitivesParams Monad_free Bind Return].\n    { symmetry. eapply interp_bind_ex_mid; intros.\n      eapply MinimalNoMul.interpret_action_weaken_post; eauto; cbn; eauto. }\n    { symmetry. rewrite interp_ret; eapply iff_refl. }\n  Qed.\n\n  Lemma interp_action_weaken_post a (post1 post2:_->_->Prop)\n    (H: forall r s, post1 r s -> post2 r s) s\n    : interp_action a s post1 -> interp_action a s post2.\n  Proof. eapply MinimalNoMul.interpret_action_weaken_post; eauto. Qed.\n  Lemma interp_action_appendonly' a s post :\n    interp_action a s post ->\n    interp_action a s (fun v s' => post v s' /\\ endswith s'.(getLog) s.(getLog)).\n  Proof. eapply MinimalNoMul.interpret_action_appendonly''; eauto. Qed.\n  Lemma interp_action_total{memOk: map.ok Mem} a (s: MetricRiscvMachine) post :\n    no_M s ->\n    interp_action a s post ->\n    exists v s, post v s /\\ no_M s.\n  Proof.\n    intros H H1.\n    unshelve epose proof (MinimalNoMul.interpret_action_total _ _ _ _ _ H1) as H0; eauto.\n    destruct H0 as (?&?&[[]|(?&?)]); eauto.\n  Qed.\n  Lemma interp_action_preserves_valid{memOk: map.ok Mem} a s post :\n    no_M s.(getMachine) ->\n    interp_action a s post ->\n    interp_action a s (fun v s' => post v s' /\\ no_M s'.(getMachine)).\n  Proof.\n    intros D I.\n    unshelve epose proof (MinimalNoMul.interpret_action_preserves_valid' _ _ _ D I) as H0; eauto.\n  Qed.\n\n  Global Instance MetricMinimalNoMulPrimitivesSane{memOk: map.ok Mem} :\n    MetricPrimitivesSane MetricMinimalNoMulPrimitivesParams.\n  Proof.\n    split; cbv [mcomp_sane valid_machine MetricMinimalNoMulPrimitivesParams];\n      intros *; intros D M;\n      (split; [ exact (interp_action_total _ st _ D M)\n              | eapply interp_action_preserves_valid; try eassumption;\n                eapply interp_action_appendonly'; try eassumption ]).\n  Qed.\n\n  Global Instance MetricMinimalNoMulSatisfiesPrimitives{memOk: map.ok Mem}:\n    MetricPrimitives MetricMinimalNoMulPrimitivesParams.\n  Proof.\n    split; try exact _.\n    all : cbv [mcomp_sat spec_load spec_store MetricMinimalNoMulPrimitivesParams invalidateWrittenXAddrs].\n    all: intros; destruct initialL;\n      repeat match goal with\n      | _ => progress subst\n      | _ => Option.inversion_option\n      | _ => progress cbn -[Memory.load_bytes Memory.store_bytes HList.tuple] in *\n      | _ => progress cbv [id valid_register is_initial_register_value load store Memory.loadByte Memory.loadHalf Memory.loadWord Memory.loadDouble Memory.storeByte Memory.storeHalf Memory.storeWord Memory.storeDouble] in *\n      | H : exists _, _ |- _ => destruct H\n      | H : _ /\\ _ |- _ => destruct H\n      | |- _ => solve [ intuition (eauto || blia) ]\n      | H : _ \\/ _ |- _ => destruct H\n      | |- context[match ?x with _ => _ end] => destruct x eqn:?\n      | |- _ => progress unfold getReg, setReg\n      | |-_ /\\ _ => split\n      end.\n      (* setRegister *)\n      destruct getMachine; eassumption.\n  Qed.\n\nEnd Riscv.\n", "meta": {"author": "mit-plv", "repo": "riscv-coq", "sha": "55c9cc88a6734550bdd913bfdf482d498c6354e6", "save_path": "github-repos/coq/mit-plv-riscv-coq", "path": "github-repos/coq/mit-plv-riscv-coq/riscv-coq-55c9cc88a6734550bdd913bfdf482d498c6354e6/src/riscv/Platform/MetricMinimalNoMul.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6859494550081925, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.23430832933004977}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of CFGV project.\n\n  CFGV is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  CFGV is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with CFGV.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/CFGVLFMTP2014/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\nRequire Export AlphaEquality.\nRequire Export SwapProps.\n\nSet Implicit Arguments.\n\n(** (re)defining it this way enables coq to successfully\n    match the statement of [alphaEqTransitive]\n    with the lemma [GAlphaInd] *)\nDefinition transRel {T : [univ]} (R : bin_rel T) :=  \nforall x y : T, \n  R x y \n  -> forall z : T,\n     R y z -> R x z.\n\nLemma MakeAbsPnodeSame : forall \n  {G : CFGV} {vc : VarSym G}\n  (lps : list (GSym G))\n  (m: Mixture (map (fun x : GSym G => (true, x)) (lps))),\n  (MakeAbstractionsPNode vc m)\n    = (MakeAbstractionsTNodeAux vc [] m).\nProof.\n  induction m; cpx.\nQed.\n\nLtac remAlphaRight Hyp name :=  \n  match type of Hyp with\n  | pAlphaEq _ _ ?r => remember r as name\n  | tAlphaEq _ _ ?r => remember r as name\n  end.\n\nLtac remAlphaLeft Hyp name :=  \n  match type of Hyp with\n  | pAlphaEq _ ?l _ => remember l as name\n  | tAlphaEq _ ?l _ => remember l as name\n  end.\n\n\nSection AlphaProps.\nContext {G : CFGV} {vc  : VarSym G}.\n\nLemma alphaEquiVariant :\n( \n  (forall (s : GSym G) ,\n      EquiVariantRelSame (@tSwap G vc s) (tAlphaEq vc)) \n   *\n  (forall (s : GSym G),\n      EquiVariantRelSame (@pSwap G vc s) (pAlphaEq vc))\n  *\n  (EquiVariantRelSame (@swapAbs G vc) (@AlphaEqAbs G vc))\n  *\n  (EquiVariantRelSame (@swapLAbs G vc) (@lAlphaEqAbs G vc))\n).\nProof.\n  intros. GAlphaInd; introns Hyp; intros; \n  allsimpl; try (econstructor; eauto; fail);[| | |].\n- Case \"tnode\". constructor.\n  unfold allBndngVars.\n  rw <- swapLBoundVarsCommute.\n  rw <- swapLBoundVarsCommute.\n  rewrite <- MakeLAbsSwapCommute.\n  rewrite <- MakeLAbsSwapCommute.\n  cpx.\n- Case \"pnode\". constructor.\n  rewrite <- MakeAbsPNodeCommute.\n  rewrite <- MakeAbsPNodeCommute.\n  cpx.\n- Case \"termAbs\".\n  specialize (Hyp4 sw).\n  rewrite (tcase swap_app) in Hyp4.\n  rewrite (tcase swap_app) in Hyp4.\n  rewrite (tcase swap_prop_e1Stronger) in Hyp4.\n  match type of Hyp4 with\n  tAlphaEq _ _ ?b => pattern b in Hyp4\n  end.\n  rewrite (tcase swap_prop_e1Stronger) in Hyp4.\n  rewrite <- (tcase swap_app) in Hyp4.\n  rewrite <- (tcase swap_app) in Hyp4.\n\n  unfold swapSwap in Hyp4. rewrite map_combine in Hyp4.\n  rewrite map_combine in Hyp4.\n  fold (swapLVar sw lbva) in Hyp4.\n  fold (swapLVar sw lbvb) in Hyp4.\n  fold (swapLVar sw lbnew) in Hyp4.\n  remember (swapLVar sw lbnew) as lbns.\n  repnud Hyp1.\n  allsimpl.\n  eapply  alAbT with (lbnew := lbns); eauto;\n  try ( subst; unfold swapLVar; \n    autorewrite with fast; congruence; fail); cpx;\n  subst;[unfolds_base; allsimpl;\n  dands|];repeat (disjoint_reasoning);[ | | | | ].\n  + rewrite <- (tcase AllVarsEquivariant).\n    apply DisjointEquivariant; trivial.\n  + rewrite <- (tcase AllVarsEquivariant).\n    apply DisjointEquivariant; trivial.\n  + apply NoRepeatsEquivariant; trivial.\n  + apply DisjointEquivariant; trivial.\n  + apply DisjointEquivariant; trivial.\n\n- Case \"patAbs\".\n  specialize (Hyp4 sw).\n  rewrite (pcase swap_app) in Hyp4.\n  rewrite (pcase swap_app) in Hyp4.\n  rewrite (pcase swap_prop_e1Stronger) in Hyp4.\n  match type of Hyp4 with\n  pAlphaEq _ _ ?b => pattern b in Hyp4\n  end.\n  rewrite (pcase swap_prop_e1Stronger) in Hyp4.\n  rewrite <- (pcase swap_app) in Hyp4.\n  rewrite <- (pcase swap_app) in Hyp4.\n\n  unfold swapSwap in Hyp4. rewrite map_combine in Hyp4.\n  rewrite map_combine in Hyp4.\n  fold (swapLVar sw lbva) in Hyp4.\n  fold (swapLVar sw lbvb) in Hyp4.\n  fold (swapLVar sw lbnew) in Hyp4.\n  remember (swapLVar sw lbnew) as lbns.\n  repnud Hyp1.\n  allsimpl.\n  eapply  alAbP with (lbnew := lbns); eauto;\n  try ( subst; unfold swapLVar; \n    autorewrite with fast; congruence; fail); cpx;\n  subst;[unfolds_base; allsimpl;\n  dands|];repeat (disjoint_reasoning);[ | | | | ].\n  + rewrite <- (pcase AllVarsEquivariant).\n    apply DisjointEquivariant; trivial.\n  + rewrite <- (pcase AllVarsEquivariant).\n    apply DisjointEquivariant; trivial.\n  + apply NoRepeatsEquivariant; trivial.\n  + apply DisjointEquivariant; trivial.\n  + apply DisjointEquivariant; trivial.\nQed.\n\nLemma tAlphaEqEquivariantRev : forall \n  (sw : Swapping vc) s (ta tb : Term s),\n  tAlphaEq vc (tSwap ta sw) (tSwap tb sw)\n  -> tAlphaEq vc ta tb.\nProof.\n  introv Hd.\n  apply (tcase alphaEquiVariant) in Hd.\n  specialize (Hd (rev sw)).\n  autorewrite with SwapAppR in Hd.\n  autorewrite with fast in Hd.\n  trivial.\nQed.\n\nLemma pAlphaEqEquivariantRev : forall \n  (sw : Swapping vc) s (ta tb : Pattern s),\n  pAlphaEq vc (pSwap ta sw) (pSwap tb sw)\n  -> pAlphaEq vc ta tb.\nProof.\n  introv Hd.\n  apply (tcase alphaEquiVariant) in Hd.\n  specialize (Hd (rev sw)).\n  autorewrite with SwapAppR in Hd.\n  autorewrite with fast in Hd.\n  trivial.\nQed.\n\n(** todo : better name .. [lv] is not nil anymore *)\nLemma AlphaEqNilAbsT : forall \n(gs : GSym G) (tma tmb : Term gs)\n(lv : list (vType vc)),\ntAlphaEq vc tma tmb \n-> AlphaEqAbs (termAbs vc lv tma) (termAbs vc lv tmb).\nProof.\n  introv Ha.\n  pose proof (GFreshDistRenWSpec vc lv \n  (tAllVars tma++tAllVars tmb++lv))\n    as XX.\n  exrepnd. repeat (disjoint_reasoning).\n  eapply  alAbT with (lbnew := lvn); eauto;\n  unfold tFresh; dands;allsimpl;\n  repeat(disjoint_reasoning); auto;[].\n  apply alphaEquiVariant; cpx.\nQed.\n\nLemma AlphaEqNilAbsP : forall \n(gs : GSym G) (tma tmb : Pattern gs)\n(lv : list (vType vc)),\npAlphaEq vc tma tmb \n-> AlphaEqAbs (patAbs vc lv tma) (patAbs vc lv tmb).\nProof.\n  introv Ha.\n  pose proof (GFreshDistRenWSpec vc lv \n  (pAllVars tma++pAllVars tmb++lv))\n    as XX.\n  exrepnd. repeat (disjoint_reasoning).\n  eapply  alAbP with (lbnew := lvn); eauto;\n  unfold pFresh; dands;allsimpl;\n  repeat(disjoint_reasoning); auto;[].\n  apply alphaEquiVariant; cpx.\nQed.\n  \n  \nNotation vcType := (vType vc).\nNotation vcAbstraction := (@Abstraction G vc).\n\nLemma alphaEqRefl : \n     (  (forall (s : GSym G) (t : Term s),\n            tAlphaEq vc t t)\n         *\n        (forall (s : GSym G) (pt : Pattern s),\n            pAlphaEq vc pt pt)\n         *\n        (forall (l : MixtureParam) (m : Mixture l) \n        (lbv : list (list (vType vc))),\n           lAlphaEqAbs (MakeAbstractions vc m lbv) \n                       (MakeAbstractions vc m lbv))).\nProof.\n  GInduction; introns Hyp; intros; cpx; allsimpl;\n  try dlist_len lbv;  try (econstructor; eauto with slow; fail).\n- Case \"mtcons\". econstructor; eauto;[].\n  remember (lhead lbv) as lbvh.\n  apply AlphaEqNilAbsT;cpx.\n- Case \"mpcons\". econstructor; eauto;[].\n  remember (lhead lbv) as lbvh.\n  apply AlphaEqNilAbsP;cpx.\nQed.\n\n\n\nHint Resolve\n(tcase alphaEqRefl)\n(pcase alphaEqRefl)\n(mcase alphaEqRefl)\n  AlphaEqNilAbsT\n  AlphaEqNilAbsP\n\n : Alpha.\n\nLemma talphaEqRefl : forall (s : GSym G) \n  (ta tb : Term s),\n  ta=tb -> tAlphaEq vc ta tb.\nProof.\n  intros. subst. eauto with Alpha.\nQed.\n\n\nRequire Import Eqdep_dec.\n\n\n\nHint Resolve deqMixP: Deq.\n\nLemma alphaEqSym :\n(  (forall (s : GSym G) (ta tb : Term s),\n      tAlphaEq vc ta tb -> tAlphaEq vc tb ta)\n   *\n  (forall (s : GSym G) (pta ptb : Pattern s),\n      pAlphaEq vc pta ptb -> pAlphaEq vc ptb pta)\n   *\n  (forall (aa ab : Abstraction G vc),\n      AlphaEqAbs aa ab -> AlphaEqAbs ab aa)\n   *\n  (forall (la lb : list (Abstraction G vc)),\n      lAlphaEqAbs la lb -> lAlphaEqAbs lb la)).\nProof.\n  intros. GAlphaInd; introns Hyp; intros; \n    try (econstructor; eauto; fail);[|].\n- Case \"termAbs\".  eapply  alAbT with (lbnew := lbnew); eauto;\n  [eauto with SetReasoning | repeat(disjoint_reasoning)].\n- Case \"patAbs\".  eapply  alAbP with (lbnew := lbnew); eauto;\n  [eauto with SetReasoning | repeat(disjoint_reasoning)].\nQed.\n\n\n\nLemma AlphaEqAbsTSameParam : forall (gsa gsb : GSym G)\n  (lbva lbvb: list vcType)\n  (tma : Term gsa) (tmb : Term gsb),\n  AlphaEqAbs \n      (termAbs vc lbva tma) \n      (termAbs vc lbvb tmb)\n  -> gsa =gsb.\nProof.\n  introv Hal.\n  inversion Hal.\n  auto.\nQed.\n\nLemma AlphaEqAbsPSameParam : forall (gsa gsb : GSym G)\n  (lbva lbvb: list vcType)\n  (tma : Pattern gsa) (tmb : Pattern gsb),\n  AlphaEqAbs \n      (patAbs vc lbva tma) \n      (patAbs vc lbvb tmb)\n  -> gsa =gsb.\nProof.\n  introv Hal.\n  inversion Hal.\n  auto.\nQed.\n\nLemma betterAbsTElim : forall (gs : GSym G)\n  (lbva lbvb lvAvoid: list vcType)\n  (tma tmb : Term gs),\n  AlphaEqAbs \n      (termAbs vc lbva tma) \n      (termAbs vc lbvb tmb)\n->{lbnew : list vcType $\n      let swapa := combine lbva lbnew in\n      let swapb := combine lbvb lbnew in\n      length lbva = length lbnew #\n      length lbvb = length lbnew #\n      tFresh lbnew [tma, tmb] #\n      (** naive elimination does not give the [lvAvoid] in the\n         next hypothesis *)\n      disjoint (lvAvoid++lbva++lbvb) lbnew #\n      tAlphaEq vc (tSwap tma swapa) (tSwap tmb swapb)}.\nProof.\n  introv Hab.\n  inversion Hab. clear Hab.\n  EqDecSndEq. subst.\n  subst swapa. subst swapb.\n  pose proof (GFreshDistRenWSpec vc lbnew \n              (tAllVars tma++tAllVars tmb++ \n                    lbnew ++lbva ++ lbvb++ lvAvoid))\n    as Hfr.\n  exrepnd. exists lvn. simpl.\n  dands; try congruence; unfold tFresh;\n  allsimpl; dands; repeat(disjoint_reasoning);[].\n  rename X0 into Htal.\n  apply (tcase alphaEquiVariant ) in Htal.\n  specialize (Htal (combine lbnew lvn)).\n  rewrite (tcase swap_app) in Htal.\n  rewrite (tcase swap_app) in Htal.\n  unfold tFresh in X.\n  allsimpl. repnd.\n  autorewrite with slow in Htal; try congruence;\n  cpx; repeat (disjoint_reasoning).\nQed.\n\nLemma betterAbsPElim : forall (gs : GSym G)\n  (lbva lbvb lvAvoid: list vcType)\n  (tma tmb : Pattern gs),\n  AlphaEqAbs\n      (patAbs vc lbva tma) \n      (patAbs vc lbvb tmb)\n->{lbnew : list vcType $\n      let swapa := combine lbva lbnew in\n      let swapb := combine lbvb lbnew in\n      length lbva = length lbnew #\n      length lbvb = length lbnew #\n      pFresh lbnew [tma, tmb] #\n      (** naive elimination does not give thhe next hypothesis *)\n      disjoint (lvAvoid++lbva++lbvb) lbnew #\n      pAlphaEq vc (pSwap tma swapa) (pSwap tmb swapb)}.\nProof.\n  introv Hab.\n  inversion Hab. clear Hab.\n  EqDecSndEq. subst.\n  subst swapa. subst swapb.\n  pose proof (GFreshDistRenWSpec vc lbnew \n              (pAllVars tma++pAllVars tmb++ \n                    lbnew ++lbva ++ lbvb++ lvAvoid))\n    as Hfr.\n  exrepnd. exists lvn. simpl.\n  dands; try congruence; unfold pFresh;\n  allsimpl; dands; repeat(disjoint_reasoning);[].\n  rename X0 into Htal.\n  apply (tcase alphaEquiVariant ) in Htal.\n  specialize (Htal (combine lbnew lvn)).\n  rewrite (pcase swap_app) in Htal.\n  rewrite (pcase swap_app) in Htal.\n  unfold pFresh in X.\n  allsimpl. repnd.\n  autorewrite with slow in Htal; try congruence;\n  cpx; repeat (disjoint_reasoning).\nQed.\n\nLemma alphaEqTransitive :\n( \n  (forall (s : GSym G) ,\n      transRel (@tAlphaEq _ vc s))\n   *\n  (forall (s : GSym G),\n      transRel (@pAlphaEq _ vc s))\n  *\n      transRel (@AlphaEqAbs G vc)\n  *\n      transRel (@lAlphaEqAbs G vc)\n).\nProof.\n  intros.\n  GAlphaInd; introns Hyp; intros; \n  allsimpl; trivial; try (econstructor; eauto; fail);\n    [ | | | | | |].\n- Case \"tnode\". inverts Hyp1.\n  EqDecSndEq. subst.\n  rename mb0 into mc.\n  econstructor; eauto with slow.\n\n- Case \"pvleaf\".  inverts Hyp.\n  EqDecSndEq. subst.\n  constructor.\n  \n- Case \"pembed\".  inverts Hyp1;\n  EqDecSndEq; subst;\n  econstructor; eauto with slow.\n\n- Case \"pnode\". inverts Hyp1.\n  EqDecSndEq. subst.\n  rename mb0 into mc.\n  econstructor; eauto with slow.\n\n- Case \"termAbs\".\n  destruct z as [ss lbvc tmc|];[|inversion Hyp5].\n  duplicate Hyp5 as Htal.\n  apply AlphaEqAbsTSameParam in Hyp5.\n  symmetry in Hyp5. subst.\n  apply (betterAbsTElim (lbnew ++ lbva++ (tAllVars tma))) in Htal.\n  allsimpl. exrepnd.\n  rename lbnew0 into lbcnew.\n  (** we need to prepare lhs of [Htal0] so that it can match\n    the inductive hypothessis [Hyp4].\n    then we can undo the extra swappings done\n    to rhs in this process *)\n  apply (tcase alphaEquiVariant ) in Htal0.\n  specialize (Htal0 (combine lbcnew lbnew)).\n  rewrite (tcase swap_app) in Htal0.\n  rewrite (tcase swap_app) in Htal0.\n  unfold tFresh in Htal3.\n  unfold tFresh in Hyp1.\n  allsimpl. repnd.\n  remAlphaRight Htal0 ll.\n  autorewrite with slow in Htal0; try congruence;\n  cpx; repeat (disjoint_reasoning).\n  apply Hyp4 in Htal0.  subst.\n  (* undo the changes done to RHS of [Htal0]*)\n  apply (tcase alphaEquiVariant ) in Htal0.\n  specialize (Htal0 (combine lbnew lbcnew)).\n  remAlphaRight Htal0 ll.\n  rewrite (tcase swap_app) in Htal0.\n  autorewrite with slow in Htal0; try congruence;\n  cpx; repeat (disjoint_reasoning).\n  rewrite (tcase swap_app) in Heqll.\n  rw <- app_assoc in Heqll.\n  rewrite <- (tcase swap_app) in Heqll.\n  rewrite <- (tcase swap_app) in Heqll.\n  rewrite (tcase swapSwitch) in Heqll.\n  rewrite <- AssociationList.ALSwitchCombine in Heqll.\n  rewrite (tcase swapRevNoRep) in Heqll; auto;\n  autorewrite with fast; cpx;[| disjoint_reasoning; fail].\n  rewrite (tcase swap_app) in Heqll.\n  rewrite (tcase swap_prop_s2Stronger) in Heqll.\n  subst.\n  apply alAbT with (lbnew:=lbcnew); try congruence;\n  [unfolds_base; simpl; dands |]; cpx;\n  repeat (disjoint_reasoning).\n- Case \"patAbs\".\n  destruct z as [|ss lbvc tmc];[inversion Hyp5|];[].\n  duplicate Hyp5 as Htal.\n  apply AlphaEqAbsPSameParam in Hyp5.\n  symmetry in Hyp5. subst.\n  apply (betterAbsPElim (lbnew ++ lbva++ (pAllVars tma))) in Htal.\n  allsimpl. exrepnd.\n  rename lbnew0 into lbcnew.\n  (** we need to prepare lhs of [Htal0] so that it can match\n    the inductive hypothessis [Hyp4].\n    then we can undo the extra swappings done\n    to rhs in this process *)\n  apply (tcase alphaEquiVariant ) in Htal0.\n  specialize (Htal0 (combine lbcnew lbnew)).\n  rewrite (pcase swap_app) in Htal0.\n  rewrite (pcase swap_app) in Htal0.\n  unfold pFresh in Htal3.\n  unfold pFresh in Hyp1.\n  allsimpl. repnd.\n  remAlphaRight Htal0 ll.\n  autorewrite with slow in Htal0; try congruence;\n  cpx; repeat (disjoint_reasoning).\n  apply Hyp4 in Htal0.  subst.\n\n  apply (tcase alphaEquiVariant ) in Htal0.\n  specialize (Htal0 (combine lbnew lbcnew)).\n  remAlphaRight Htal0 ll.\n  rewrite (pcase swap_app) in Htal0.\n  autorewrite with slow in Htal0; try congruence;\n  cpx; repeat (disjoint_reasoning).\n  rewrite (pcase swap_app) in Heqll.\n  rw <- app_assoc in Heqll.\n  rewrite <- (pcase swap_app) in Heqll.\n  rewrite <- (pcase swap_app) in Heqll.\n  rewrite (pcase swapSwitch) in Heqll.\n  rewrite <- AssociationList.ALSwitchCombine in Heqll.\n  rewrite (pcase swapRevNoRep) in Heqll; auto;\n  autorewrite with fast; cpx;[| disjoint_reasoning; fail].\n  rewrite (pcase swap_app) in Heqll.\n  rewrite (pcase swap_prop_s2Stronger) in Heqll.\n  subst.\n  apply alAbP with (lbnew:=lbcnew); try congruence;\n  [unfolds_base; simpl; dands |]; cpx;\n  repeat (disjoint_reasoning).\n- Case \"laCons\".  inverts Hyp3.\n  subst. constructor; auto.\nQed.\n\n\n\n\n(*\nLemma alphaEqSym : \n     (  (forall (s : GSym G) (ta tb : Term s)\n        (lvA : list vcType),\n            tAlphaEq lvA ta tb -> tAlphaEq lvA tb ta)\n         *\n        (forall (s : GSym G) (pta ptb : Pattern s)\n        (lvA : list vcType),\n            pAlphaEq lvA pta ptb -> pAlphaEq lvA ptb pta)\n         *\n        (forall (l : MixtureParam) (ma mb : Mixture l) \n        (lvA : list vcType)\n        (lbva lbvb : list (list (vType vc))),\n           lAlphaEqAbs lvA (MakeAbstractions ma lbva) \n                           (MakeAbstractions mb lbvb)\n        -> lAlphaEqAbs lvA (MakeAbstractions mb lbvb) \n                           (MakeAbstractions ma lbva))).\nProof.\n  GInductionS; introns Hyp; cpx; allsimpl;\n  try (inversion Hyp; EqDecSndEq; subst; econstructor; eauto; fail);\n  try (inversion Hyp0; EqDecSndEq; subst; inversion Hyp0;\n  subst; EqDecSndEq; subst; econstructor; eauto; fail);[|].\n- inversion Hyp1. EqDecSndEq. subst. econstructor; eauto.\n  inversion X. subst. subst swapa. subst swapb.\n  EqDecSndEq. subst. econstructor; eauto.\n  + eauto with SetReasoning.\n  + apply Hyp; auto; autorewrite with fast. auto.\n  + inversion mb. subst. destruct mb;\n    inverts H. subst. duplicate X0 as XX.\n    inversion X0;subst; cpx.\n\n\n(* apply Hyp0.\n\n\napply Hyp0. \n- inversion Hyp1. EqDecSndEq. subst. econstructor; eauto.\n  inversion X. subst. subst swapa. subst swapb.\n  EqDecSndEq. subst. econstructor; eauto.\n  + eauto with SetReasoning.\n  + apply Hyp; auto; autorewrite with fast. auto.\nQed.\n*)\n\nAbort.\n*)\n\n\nLemma eqset_subtractv_if_left :\n  forall l l1 l2,\n    eqset l1 l2 -> eqset (@subtractv G vc l1 l) (subtractv l2 l).\nProof.\n  unfold subtractv.\n  apply eqset_diff_if_left.\nQed.\n\nLemma eqset_subtractv_if_right :\n  forall l l1 l2,\n    eqset l1 l2 -> eqset (@subtractv G vc l l1) (subtractv l l2).\nProof.\n  unfold subtractv.\n  apply eqset_diff_if_right.\nQed.\n\nLemma eq_subtractv_if_left :\n  forall l l1 l2,\n    l1 = l2 -> @subtractv G vc l1 l = subtractv l2 l.\nProof.\n  sp; subst; sp.\nQed.\n\nLemma eq_subtractv_if_right :\n  forall l l1 l2,\n    l1 = l2 -> @subtractv G vc l l1 = subtractv l l2.\nProof.\n  sp; subst; sp.\nQed.\n\nLemma subtractv_nil :\n  forall l,\n    @subtractv G vc l [] = l.\nProof.\n  unfold subtractv; sp.\nQed.\n\nLemma subtractv_nil_l :\n  forall l,\n    @subtractv G vc [] l = [].\nProof.\n  unfold subtractv; sp.\n  rw diff_nil; auto.\nQed.\n\nLemma subtractv_app_l :\n  forall l1 l2 l,\n    @subtractv G vc (l1 ++ l2) l = subtractv l1 l ++ subtractv l2 l.\nProof.\n  unfold subtractv; introv.\n  rw diff_app_r; auto.\nQed.\n\nDefinition freevars_abs (a : Abstraction G vc) :=\n  match a with\n    | termAbs _ vars t => subtractv (tfreevars vc t) vars\n    | patAbs  _ vars p => subtractv (pfreevars vc p) vars\n  end.\n\nFixpoint freevars_labs (l : list (Abstraction G vc)) :=\n  match l with\n    | [] => []\n    | a :: l => freevars_abs a ++ freevars_labs l\n  end.\n\n\n\n\n\n\n(* bad duplicate: this equality holds unconditionally\n    see freevarsEquivariant in SwapProps.v*)\nLemma freevars_swap_eq :\n  (\n    (forall (gs : GSym G) (t : Term gs),\n     forall (l1 l : list vcType),\n       length l1 = length l\n       -> disjoint l1 l\n       -> tFresh l [t]\n       -> tfreevars vc (tSwap t (combine l1 l))\n          = swapLVar (combine l1 l) (tfreevars vc t))\n    *\n    (forall (gs : GSym G) (p : Pattern gs),\n     forall (l1 l : list vcType),\n       length l1 = length l\n       -> disjoint l1 l\n       -> pFresh l [p]\n       -> pfreevars vc (pSwap p (combine l1 l))\n          = swapLVar (combine l1 l) (pfreevars vc p))\n    *\n    (forall (lgs : list (bool * GSym G)) (m : Mixture lgs) lbvars,\n     forall (l1 l : list vcType),\n       length l1 = length l\n       -> disjoint l1 l\n       -> mFresh l [m]\n       -> mfreevars vc (mSwap m (combine l1 l)) (swapLLVar (combine l1 l) lbvars)\n          = swapLVar (combine l1 l) (mfreevars vc m lbvars))\n  ).\nProof.\n  GInduction; auto; introv;\n  try (complete (allsimpl; cpx));\n  try (complete (allsimpl; introv f e; DDeqs; cpx; rw subtractv_nil_l; auto)).\n\n  - Case \"tnode\".\n    allsimpl.\n    introv M len disj f.\n    unfold allBndngVars.\n    rewrite lBoundVars_swap.\n    rw M; auto.\n\n  - Case \"pnode\".\n    allsimpl.\n    introv M len disj f.\n    apply (M []); auto.\n\n  - Case \"mtcons\".\n    allsimpl.\n    introv T M len disj f.\n    destruct lbvars; simpl;\n    rewrite swapLVar_app;\n    apply app_if.\n\n    + apply T; auto;\n      try (complete (unfold mFresh in f; unfold mFresh, tFresh;\n                     allsimpl; allrw disjoint_app_r; sp)).\n\n    + apply (M []); auto;\n      try (complete (unfold mFresh in f; unfold mFresh;\n                     allsimpl; allrw disjoint_app_r; sp)).\n\n    + rewrite swapLVar_subtractv.\n      rw T; auto;\n      try (complete (unfold mFresh in f; unfold mFresh, tFresh;\n                     allsimpl; allrw disjoint_app_r; sp)).\n\n    + apply M; auto;\n      try (complete (unfold mFresh in f; unfold mFresh;\n                     allsimpl; allrw disjoint_app_r; sp)).\n\n  - Case \"mpcons\".\n    allsimpl.\n    introv P M len disj f.\n    destruct lbvars; simpl;\n    rewrite swapLVar_app;\n    apply app_if.\n\n    + apply P; auto;\n      try (complete (unfold mFresh in f; unfold mFresh, pFresh;\n                     allsimpl; allrw disjoint_app_r; sp)).\n\n    + apply (M []); auto;\n      try (complete (unfold mFresh in f; unfold mFresh;\n                     allsimpl; allrw disjoint_app_r; sp)).\n\n    + rewrite swapLVar_subtractv.\n      rw P; auto;\n      try (complete (unfold mFresh in f; unfold mFresh, pFresh;\n                     allsimpl; allrw disjoint_app_r; sp)).\n\n    + apply M; auto;\n      try (complete (unfold mFresh in f; unfold mFresh;\n                     allsimpl; allrw disjoint_app_r; sp)).\nQed.\n\n\nLemma tFresh_app :\n  forall g l (l1 l2 : list (Term g)),\n    @tFresh G vc g l (l1 ++ l2) <=> (tFresh l l1 # tFresh l l2).\nProof.\n  introv.\n  unfold tFresh.\n  rw flat_map_app.\n  rw disjoint_app_r.\n  split; sp.\nQed.\n\nLemma pFresh_app :\n  forall g l (l1 l2 : list (Pattern g)),\n    @pFresh G vc g l (l1 ++ l2) <=> (pFresh l l1 # pFresh l l2).\nProof.\n  introv.\n  unfold pFresh.\n  rw flat_map_app.\n  rw disjoint_app_r.\n  split; sp.\nQed.\n\n\n(* duplicate *)\nLemma swapVar_unchanged :\n  forall v l1 l2,\n    !LIn v l1\n    -> !LIn v l2\n    -> @swapVar G vc (combine l1 l2) v = v.\nProof.\n  induction l1; introv ni1 ni2; allsimpl; auto.\n  allrw not_over_or; repnd.\n  destruct l2; allsimpl; auto.\n  allrw not_over_or; repnd.\n  DDeqs; sp.\nQed.\n(* duplicate *)\nLemma swapVar_in :\n  forall l1 l2 v,\n    LIn v l1\n    -> disjoint l1 l2\n    -> length l1 = length l2\n    -> no_repeats l2\n    -> LIn (@swapVar G vc (combine l1 l2) v) l2.\nProof.\n  induction l1 as [|x1 l1]; introv i1 disj len norep; allsimpl; tcsp.\n  destruct l2 as [|x2 l2]; allsimpl; cpx.\n  allrw disjoint_cons_l; allrw disjoint_cons_r; repnd; allsimpl.\n  allrw not_over_or; repnd.\n  allrw no_repeats_cons; repnd.\n  DDeqs; sp; GC; rw (swapVar_unchanged x2); auto.\nQed.\n\nLemma eq_subtractv :\n  forall vs1 vs2 l1 l2 l,\n    disjoint l vs1\n    -> disjoint l vs2\n    -> disjoint l l1\n    -> disjoint l l2\n    -> length l = length l1\n    -> length l = length l2\n    -> no_repeats l\n    -> @swapLVar G vc (combine l1 l) vs1 = swapLVar (combine l2 l) vs2\n    -> subtractv vs1 l1 = subtractv vs2 l2.\nProof.\n  induction vs1; introv disj1 disj2 disj3 disj4 len1 len2 norep e;\n  allsimpl; destruct vs2; allsimpl;\n  allrw subtractv_nil; allrw subtractv_nil_l; auto; inj.\n  allapply cons_inj; repnd.\n  repeat (rewrite subtractv_cons).\n  allrw disjoint_cons_r; repnd.\n  DDeqs; try (complete (eapply IHvs1; eauto)).\n\n  - rw (swapVar_unchanged v) in e0; auto.\n\n    pose proof (@swapVar_in l1 l a) as h;\n      repeat (autodimp h hyp);\n      try (complete (apply disjoint_sym; auto)).\n    rw e0 in h; sp.\n\n  - rw (swapVar_unchanged a) in e0; auto.\n\n    pose proof (@swapVar_in l2 l v) as h;\n      repeat (autodimp h hyp);\n      try (complete (apply disjoint_sym; auto)).\n    rw <- e0 in h; sp.\n\n  - rw (swapVar_unchanged v) in e0; auto.\n    rw (swapVar_unchanged a) in e0; auto.\n    subst.\n    apply eq_cons; auto.\n    apply IHvs1 with (l := l); auto.\nQed.\n\nLemma freevars_in_allvars :\n  (\n    (forall (gs : GSym G) (t : Term gs),\n       subset (tfreevars vc t) (tAllVars t))\n    *\n    (forall (gs : GSym G) (p : Pattern gs),\n       subset (pfreevars vc p) (pAllVars p))\n    *\n    (forall (lgs : list (bool * GSym G)) (m : Mixture lgs) lbvars,\n       subset (mfreevars vc m lbvars) (mAllVars m))\n  ).\nProof.\n  GInduction; auto; introv;\n  try (complete (allsimpl; cpx));\n  try (complete (allsimpl; introv f e; DDeqs; cpx; rw subtractv_nil_l; auto)).\n\n  - Case \"mtcons\".\n    allsimpl.\n    introv ss M; introv.\n    destruct lbvars; allsimpl; apply subset_app_lr; auto.\n    unfold subtractv.\n    apply subset_diff.\n    apply subset_app_r; auto.\n\n  - Case \"mpcons\".\n    allsimpl.\n    introv ss M; introv.\n    destruct lbvars; allsimpl; apply subset_app_lr; auto.\n    unfold subtractv.\n    apply subset_diff.\n    apply subset_app_r; auto.\nQed.\n\nLemma alpha_preserves_free_vars :\n  (\n    (forall (s : GSym G) (t1 t2 : Term s),\n       tAlphaEq vc t1 t2 -> tfreevars vc t1 = tfreevars vc t2)\n    *\n    (forall (s : GSym G) (p1 p2 : Pattern s),\n       pAlphaEq vc p1 p2 -> pfreevars vc p1 = pfreevars vc p2)\n    *\n    (forall a1 a2,\n       AlphaEqAbs a1 a2 -> freevars_abs a1 = freevars_abs a2)\n    *\n    (forall l1 l2,\n       lAlphaEqAbs l1 l2 -> freevars_labs l1 = freevars_labs l2)\n  ).\nProof.\n  intros.\n  GAlphaInd; introns Hyp; intros;\n  try (complete (allsimpl; auto; ddeq; auto)).\n\n  - Case \"tnode\".\n    allsimpl.\n    allunfold MakeAbstractionsTNode.\n    allunfold MakeAbstractionsTNodeAux.\n    clear Hyp.\n\n    assert (forall ma : Mixture (tpRhsAugIsPat p),\n              freevars_labs\n                (MakeAbstractions vc ma\n                                  (lBoundVars vc (bndngPatIndices p) ma))\n              = mfreevars vc ma (lBoundVars vc (bndngPatIndices p) ma)) as eqs.\n    (* begin proof of assert *)\n    clear ma mb Hyp0.\n    introv.\n    remember (lBoundVars vc (bndngPatIndices p) ma); clear Heql.\n    revert l.\n    induction ma; introv; simpl; auto.\n    destruct l; allsimpl.\n    rw subtractv_nil; apply app_if; auto.\n    apply app_if; auto.\n    destruct l; allsimpl.\n    rw subtractv_nil; apply app_if; auto.\n    apply app_if; auto.\n    (* end proof of assert *)\n\n    repeat (rw <- eqs); auto.\n\n  - Case \"pnode\".\n    allsimpl.\n    allunfold MakeAbstractionsPNode.\n    clear Hyp.\n\n    assert (forall ma : Mixture (map (fun x : GSym G => (true, x)) (ppRhsSym p)),\n              freevars_labs (MakeAbstractions vc ma [])\n              = mfreevars vc ma []) as eqs.\n    (* begin proof of assert *)\n    clear ma mb Hyp0.\n    introv.\n    induction ma; introv; simpl; auto.\n    rw subtractv_nil; apply app_if; auto.\n    apply app_if; auto.\n    (* end proof of assert *)\n\n    repeat (rw <- eqs); auto.\n\n  - Case \"termAbs\".\n    allsimpl.\n    allrw disjoint_app_l; repnd.\n    rw two_as_app in Hyp1.\n    apply tFresh_app in Hyp1; repnd.\n    repeat (rw (fst (fst freevars_swap_eq)) in Hyp4; auto).\n\n    apply eq_subtractv with (l := lbnew); auto;\n    try (complete (apply disjoint_sym; auto));\n    unfold tFresh in Hyp1; unfold tFresh in Hyp6; repnd; auto;\n    allrw disjoint_flat_map_r;\n    pose proof (Hyp7 tmb) as h1; simpl in h1; autodimp h1 hyp;\n    pose proof (Hyp8 tma) as h2; simpl in h2; autodimp h2 hyp.\n\n    pose proof (fst (fst freevars_in_allvars) gs tma) as h.\n    apply subset_disjoint_r with (l2 := tAllVars tma); auto.\n\n    pose proof (fst (fst freevars_in_allvars) gs tmb) as h.\n    apply subset_disjoint_r with (l2 := tAllVars tmb); auto.\n\n  - Case \"patAbs\".\n    allsimpl.\n    allrw disjoint_app_l; repnd.\n    rw two_as_app in Hyp1.\n    apply pFresh_app in Hyp1; repnd.\n    repeat (rw (snd (fst freevars_swap_eq)) in Hyp4; auto).\n\n    apply eq_subtractv with (l := lbnew); auto;\n    try (complete (apply disjoint_sym; auto));\n    unfold pFresh in Hyp1; unfold pFresh in Hyp6; repnd; auto;\n    allrw disjoint_flat_map_r;\n    pose proof (Hyp7 tmb) as h1; simpl in h1; autodimp h1 hyp;\n    pose proof (Hyp8 tma) as h2; simpl in h2; autodimp h2 hyp.\n\n    pose proof (snd (fst freevars_in_allvars) gs tma) as h.\n    apply subset_disjoint_r with (l2 := pAllVars tma); auto.\n\n    pose proof (snd (fst freevars_in_allvars) gs tmb) as h.\n    apply subset_disjoint_r with (l2 := pAllVars tmb); auto.\n\n  - Case \"laCons\".\n    allsimpl.\n    apply app_if; auto.\nQed.\n\n\n\n\n\nLtac dvlin v l := destruct (in_deq _ (DeqVtype vc) v l).\n\n(* duplicate : do SearchAbout tFresh app *)\nLemma tFresh_app_l :\n  forall g l1 l2 ts,\n    @tFresh G vc g (l1 ++ l2) ts\n    <=>\n    (tFresh l1 ts # tFresh l2 ts # disjoint l1 l2 # no_repeats l1 # no_repeats l2).\nProof.\n  unfold tFresh; introv.\n  rw disjoint_app_l.\n  rw no_repeats_app; split; sp.\nQed.\n\n\nLemma simple_combine_app_app :\n  forall T (l1 l2 l3 l4 : list T),\n    length l1 = length l3\n    -> combine (l1 ++ l2) (l3 ++ l4)\n       = combine l1 l3 ++ combine l2 l4.\nProof.\n  induction l1; simpl; introv len; destruct l3; allsimpl; cpx.\n  rw IHl1; sp.\nQed.\n\n\n\nEnd AlphaProps.\n\nLemma tAlphaEqTransEauto:\n forall \n  {G : CFGV} {vc : VarSym G}\n   (s : GSym G) (a b c : Term s),\n   tAlphaEq vc a b\n   -> tAlphaEq vc b c\n   -> tAlphaEq vc a c.\nProof.\n  introns Hyp.\n  pose proof (@alphaEqTransitive G vc) as Hpr.\n  repnd. unfold transRel in Hpr2.\n  eauto.\nQed.\n  \nLemma pAlphaEqTransEauto:\n forall \n  {G : CFGV} {vc : VarSym G}\n   (s : GSym G) (a b c : Pattern s),\n   pAlphaEq vc a b\n   -> pAlphaEq vc b c\n   -> pAlphaEq vc a c.\nProof.\n  introns Hyp.\n  pose proof (@alphaEqTransitive G vc) as Hpr.\n  repnd. unfold transRel in Hpr1.\n  eauto.\nQed.\n\n\nDefinition ALtcase \n  {A B C D} (t:A*B*C*D) : A\n  := fst (fst (fst t)).\n\nDefinition ALpcase \n  {A B C D} (t:A*B*C*D) : B\n  := snd (fst (fst t)).\n\nDefinition Abcase \n  {A B C D} (t:A*B*C*D) : C\n  := (snd (fst t)).\n\nDefinition LAbcase \n  {A B C D} (t:A*B*C*D) : D\n  := ((snd t)).\n\n\n\nHint Resolve\n(tcase alphaEqRefl)\n(pcase alphaEqRefl)\n(mcase alphaEqRefl)\n  (ALtcase alphaEqSym)\n  (ALpcase alphaEqSym)\n  (Abcase alphaEqSym)\n  (LAbcase alphaEqSym)\n  AlphaEqNilAbsT\n  AlphaEqNilAbsP\n  tAlphaEqTransEauto\n  pAlphaEqTransEauto : Alpha.\n\n\nLemma pAlphaSwapEmSwap\n : forall {G : CFGV} {vc : VarSym G},\n(  (forall (s : GSym G) (ta : Term s), True)\n   *\n  (forall (s : GSym G) (pta : Pattern s)\n  (sw : Swapping vc),\n      pAlphaEq vc (pSwapEmbed pta sw)\n                  (pSwap pta sw))\n   *\n  (forall (mp : MixtureParam) (ma: Mixture mp)\n  (llbv : list (list (vType vc)))\n  (sw : Swapping vc),\n  (forall b s, LIn (b,s) mp -> b= true)\n   -> lAlphaEqAbs (MakeAbstractions vc (mSwapEmbed ma sw) llbv) \n                (MakeAbstractions vc (mSwap ma sw) llbv))).\nProof.\nintros. \nGInduction; cpx; allsimpl;\n  try (econstructor; eauto with Alpha; fail).\n- Case \"pnode\". introns Hyp.\n  allsimpl. constructor.\n  unfold MakeAbstractionsPNode.  \n  apply Hyp.\n  introv Hin.\n  apply in_map_iff in Hin; exrepnd; cpx.\n- Case \"mtcons\". introns Hyp.\n   pose proof (Hyp1 _ _ (inl eq_refl)). cpx.\nQed.\n\n\n(** swapping by swapping that leaves the\n    free vars unchanged results in an alpha equal term.\n    A swapping with whose both domain and range\n    are disjoint from freevars can be used *)\nLemma alphaEqSwapNonFree : forall {G : CFGV} {vc : VarSym G},\n(  (forall (s : GSym G) (t : Term s) (sw : Swapping vc),\n      leavesLVarUnchanged sw (tfreevars vc t)\n      -> tAlphaEq vc t (tSwap t sw))\n   *\n  (forall (s : GSym G) (pt : Pattern s) (sw : Swapping vc),\n     leavesLVarUnchanged sw (pfreevars vc pt)\n      -> pAlphaEq vc pt (pSwap pt sw))\n   *\n  (forall (l : MixtureParam) (m : Mixture l) (sw : Swapping vc)\n  (lbv : list (list (vType vc))),\n      leavesLVarUnchanged sw (mfreevars vc m lbv)\n      -> lAlphaEqAbs \n            (MakeAbstractions vc m lbv)\n            (MakeAbstractions vc (mSwap m sw) (swapLLVar sw lbv)))).\nProof.\n  intros.\n  GInduction; introns Hyp; intros; cpx; allsimpl;\n  try dlist_len lbv;  try (econstructor; eauto with slow; fail).\n\n- Case \"vleaf\".\n  rewrite DeqSym.\n  ddeq; sp;[| eauto with Alpha; fail].\n  destruct e. allsimpl.\n  repeat (disjoint_reasoning).\n  rewrite Hyp; cpx.\n  eauto 1 with Alpha.\n\n- Case \"tnode\". constructor. allunfold mAlphaEq.\n  unfold MakeAbstractionsTNode.\n  unfold MakeAbstractionsTNodeAux.\n  unfold allBndngVars.\n   rewrite <- lBoundVars_equivariant.\n  cpx.\n\n- Case \"pnode\". constructor. allunfold mAlphaEq.\n  unfold MakeAbstractionsPNode.\n  specialize (Hyp sw nil).\n  simpl in Hyp. cpx.\n\n- Case \"mtcons\". destruct lbv; cpx;\n  apply lforallApp in Hyp1; repnd;\n  [ allsimpl; specialize (Hyp0 sw []); simpl in Hyp0;\n    constructor; cpx ; \n     apply AlphaEqNilAbsT;\n      apply Hyp; cpx|].\n\n    constructor; cpx.\n  allsimpl. \n  pose proof  (GFreshDistRenWSpec vc l\n            (tAllVars ph++tAllVars  (tSwap ph sw)++ \n              (swapLVar sw l)++ l ++ (tfreevars vc ph)++\n                  ALDom sw ++ ALRange sw ++ l))\n      as Hfr.\n  exrepnd.\n  apply alAbT with (lbnew:=lvn); \n    try (unfold swapLVar ; autorewrite with fast;\n      congruence; fail);\n  [unfolds_base; simpl; dands | | ]; cpx;\n  try (autorewrite with fast;\n  repeat (disjoint_reasoning); fail);[].\n  autorewrite with SwapAppR.\n  assert (lvn = swapLVar sw lvn ) as XX by\n    (symmetry; apply swapLVarNoChange;\n        repeat (disjoint_reasoning)).\n\n  remember (combine l lvn) as swt.\n  rewrite XX.\n  unfold swapLVar. rewrite <- map_combine.\n  fold (swapSwap sw (combine l lvn)).\n  rewrite <- (tcase swap_prop_e1Stronger).\n  subst swt.\n  apply tAlphaEqEquivariantRev with \n    (sw0:=rev (combine l lvn)).\n  autorewrite with SwapAppR.\n  autorewrite with fast.\n  apply Hyp.\n  intros v Hin.\n  unfolds_base.\n  autorewrite with SwapAppL.\n  assert (disjoint l lvn) as Xd by repeat(disjoint_reasoning).\n  destruct (in_deq _ (DeqVtype vc) v l) as [Xin | Xnot].\n  + dimp (@swapVar_in G vc l lvn v); cpx.\n    remember (swapVar (combine l lvn) v) as vs.\n    assert (leavesLVarUnchanged sw lvn)  as Xun by\n    (apply leavesLVarUnchanged1;repeat (disjoint_reasoning)).\n    apply Xun in hyp.\n    repnud hyp. rw hyp. subst vs.\n    autorewrite with SwapAppR.\n    autorewrite with fast. refl.\n  + assert (disjoint (tfreevars vc ph) lvn) as Hdiss by\n      repeat (disjoint_reasoning).\n    assert (LIn v (tfreevars vc ph -- l)) as Hins by\n    (apply in_diff; dands; cpx).\n    apply Hdiss in Hin.\n    pattern ((swapVar (combine l lvn) v)).\n    rewrite swapVarNoChange; cpx;\n    autorewrite with fast; try congruence.\n    apply Hyp2 in Hins.\n    rewrite Hins. apply swapVarNonChangeRev.\n    rewrite swapVarNoChange; cpx;\n    autorewrite with fast; try congruence.\n\n(** exactly same as [mtcons] case *)\n- Case \"mpcons\". destruct lbv; cpx;\n  apply lforallApp in Hyp1; repnd;\n  [ allsimpl; specialize (Hyp0 sw []); simpl in Hyp0;\n    constructor; cpx ; \n     apply AlphaEqNilAbsP;\n      apply Hyp; cpx|].\n\n    constructor; cpx.\n  allsimpl. \n  pose proof  (GFreshDistRenWSpec vc l\n            (pAllVars ph++pAllVars  (pSwap ph sw)++ \n              (swapLVar sw l)++ l ++ (pfreevars vc ph)++\n                  ALDom sw ++ ALRange sw ++ l))\n      as Hfr.\n  exrepnd.\n  apply alAbP with (lbnew:=lvn); \n    try (unfold swapLVar ; autorewrite with fast;\n      congruence; fail);\n  [unfolds_base; simpl; dands | | ]; cpx;\n  try (autorewrite with fast;\n  repeat (disjoint_reasoning); fail);[].\n  autorewrite with SwapAppR.\n  assert (lvn = swapLVar sw lvn ) as XX by\n    (symmetry; apply swapLVarNoChange;\n        repeat (disjoint_reasoning)).\n\n  remember (combine l lvn) as swt.\n  rewrite XX.\n  unfold swapLVar. rewrite <- map_combine.\n  fold (swapSwap sw (combine l lvn)).\n  rewrite <- (pcase swap_prop_e1Stronger).\n  subst swt.\n  apply pAlphaEqEquivariantRev with \n    (sw0:=rev (combine l lvn)).\n  autorewrite with SwapAppR.\n  autorewrite with fast.\n  apply Hyp.\n  intros v Hin.\n  unfolds_base.\n  autorewrite with SwapAppL.\n  assert (disjoint l lvn) as Xd by repeat(disjoint_reasoning).\n  destruct (in_deq _ (DeqVtype vc) v l) as [Xin | Xnot].\n  + dimp (@swapVar_in G vc l lvn v); cpx.\n    remember (swapVar (combine l lvn) v) as vs.\n    assert (leavesLVarUnchanged sw lvn)  as Xun by\n    (apply leavesLVarUnchanged1;repeat (disjoint_reasoning)).\n    apply Xun in hyp.\n    repnud hyp. rw hyp. subst vs.\n    autorewrite with SwapAppR.\n    autorewrite with fast. refl.\n  + assert (disjoint (pfreevars vc ph) lvn) as Hdiss by\n      repeat (disjoint_reasoning).\n    assert (LIn v (pfreevars vc ph -- l)) as Hins by\n    (apply in_diff; dands; cpx).\n    apply Hdiss in Hin.\n    pattern ((swapVar (combine l lvn) v)).\n    rewrite swapVarNoChange; cpx;\n    autorewrite with fast; try congruence.\n    apply Hyp2 in Hins.\n    rewrite Hins. apply swapVarNonChangeRev.\n    rewrite swapVarNoChange; cpx;\n    autorewrite with fast; try congruence.\nQed.\n\nLemma freeVarsSuppAux:\nforall {G : CFGV} {vc : VarSym G},\n((forall (s : GSym G) (t : Term s),\n    forall v, ! LIn v (tfreevars vc t)\n      -> (finite \n             (fun b => !(tAlphaEq vc t \n                              (tSwap t [(v,b)])))))).\nProof.\n  introv Hin.\n  exists (tfreevars vc t).\n  introv Hntal.\n  destruct (in_deq _ (DeqVtype vc) a \n    (tfreevars vc t)) as [ ? | Hneq]; cpx.\n  provefalse.\n  apply Hntal.\n  apply (tcase alphaEqSwapNonFree).\n  apply leavesLVarUnchanged1.\n  allsimpl. repeat (disjoint_reasoning); cpx.\nQed.\n\nLemma freeVarsSuppAux2:\nforall {G : CFGV} {vc : VarSym G},\n((forall (s : GSym G) (t : Term s),\n    forall v, LIn v (tfreevars vc t)\n      -> ! (finite \n             (fun b => !(tAlphaEq vc t \n                              (tSwap t [(v,b)])))))).\nProof.\n  introv Hin. introv Hc.\n  repnud Hc.\n  exrepnd.\n  pose proof (vFreshVarSpec\n      ([v]++la ++ (tfreevars vc t)) v) as XX.\n  remember (vFreshVar ([v]++la ++ tfreevars vc t) v) as vn.\n  clear Heqvn.\n  rw in_app_iff in XX.\n  rw in_app_iff in XX.\n  apply XX. right. left.\n  apply Hc0. introv Hal.\n  apply (ALtcase alpha_preserves_free_vars) in Hal.\n  rewrite Hal in Hin. clear Hal.\n  rewrite <- (tcase freevarsEquivariant) in Hin.\n  rw in_map_iff in Hin.\n  exrepnd.\n  pose proof (swapVarInOrEq2 [(v,vn)] a) as Hs.\n  rewrite <- Hin0 in Hs.\n  clear Hin0.\n  dimp Hs; simpl; cpx; try (constructor; auto; cpx; fail);\n\n  [|]; cpx;\n  repeat (disjoint_reasoning);cpx.\n  introv Hc. dorn Hc; cpx.\n  subst. clear Hs. \n  apply XX. cpx.\nQed.\n\nLemma freeVarsSupp:\nforall {G : CFGV} {vc : VarSym G},\n((forall (s : GSym G) (t : Term s),\n    forall v, LIn v (tfreevars vc t)\n      <=> !(finite \n             (fun b => !(tAlphaEq vc t \n                              (tSwap t [(v,b)])))))).\nProof.\n  intros. split.\n  - apply freeVarsSuppAux2.\n  - introv Hin. destruct (in_deq _ (DeqVtype vc) v\n    (tfreevars vc t)) as [ ? | Hneq]; cpx.\n    provefalse. apply Hin.\n    apply freeVarsSuppAux.\n    trivial.\nQed.\n\n\n(*\n   \n(forall (s : GSym G) (pt : Pattern s) (sw : Swapping vc),\n  forall v, LIn v (pfreevars vc pt)\n    <=> !(finite \n           (fun b => !(pAlphaEq vc pt \n                            (pSwap pt [(v,b)])))))\n   *\n(forall (l : MixtureParam) (m : Mixture l) (sw : Swapping vc)\n  (lbv : list (list (vType vc))),\n  forall v, LIn v (mfreevars vc m lbv)\n    <=> !(finite \n           (fun b => !(mAlphaEq vc m \n                            (mSwap m [(v,b)])))))\n.\n\n*)\n  \n(*\n*** Local Variables:\n*** coq-load-path: (\"../\")\n*** End:\n*)\n\n", "meta": {"author": "aa755", "repo": "CFGV", "sha": "440965e85e0d7107a8f0cfef5d14b895979716e5", "save_path": "github-repos/coq/aa755-CFGV", "path": "github-repos/coq/aa755-CFGV/CFGV-440965e85e0d7107a8f0cfef5d14b895979716e5/AlphaEqProps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.23427866639181408}}
{"text": "(* This software is governed by the CeCILL license under French law and\n * abiding by the rules of distribution of free software.  You can  use,\n * modify and/ or redistribute the software under the terms of the CeCILL\n * license as circulated by CEA, CNRS and INRIA at the following URL\n * \"http://www.cecill.info\".\n\n * As a counterpart to the access to the source code and  rights to copy,\n * modify and redistribute granted by the license, users are provided only\n * with a limited warranty  and the software's author,  the holder of the\n * economic rights,  and the successive licensors  have only  limited\n * liability.\n\n * In this respect, the user's attention is drawn to the risks associated\n * with loading,  using,  modifying and/or developing or reproducing the\n * software by the user in light of its specific status of free software,\n * that may mean  that it is complicated to manipulate,  and  that  also\n * therefore means  that it is reserved for developers  and  experienced\n * professionals having in-depth computer knowledge. Users are therefore\n * encouraged to load and test the software's suitability as regards their\n * requirements in conditions enabling the security of their systems and/or\n * data to be ensured and,  more generally, to use and operate it in the\n * same conditions as regards security.\n\n * The fact that you are presently reading this means that you have had\n * knowledge of the CeCILL license and that you accept its terms.\n *)\n\n(* /!\\ Proof related content on Jobs are located in proof/JobsAxioms.v *)\n\nFrom Scheduler.Model Require Import PureFunctionModels.\nFrom Scheduler.Model.Interface.Types Require Import TypesModel.\nFrom Scheduler.Model.Interface.Types Require Import Jobs.\nRequire Import List.\nModule Type JobsAxiomsMod.\n\n  (* job_id -> job *)\n  (*Parameter Jobs : nat -> Job.*)\n\n  (* oracle from scheduling plan *)\n  Parameter jobs_arriving_at :\n    forall (t:nat), list nat.\n\n  Axiom job_duration_gt_0 : forall n, duration (Jobs n) > 0.\n\n  Axiom job_budget_enough : forall n, budget (Jobs n) >= duration (Jobs n).\n\n\n  Axiom job_arrival_plus_duration_le_deadline :\n    forall i,\n      arrival (Jobs i) + duration (Jobs i) <= deadline (Jobs i).\n\n  Axiom jobs_id_index : forall i,   jobid (Jobs i) = i.\n\n\n  (* In should be defined for C lists ? TODO *)\n Axiom jobs_arriving_at_prop : forall  t i,\n      In i (jobs_arriving_at t) <-> arrival (Jobs i) = t.\n\n  (* nth should be defined for C lists ? TODO *)\n\n  Axiom jobs_arriving_at_unique : forall i i' t t',\n      i < length (jobs_arriving_at t) ->  i' < length (jobs_arriving_at t') ->\n      nth i (jobs_arriving_at t) 0 = nth i' (jobs_arriving_at t') 0 ->\n      (t = t' /\\ i = i').\n\nEnd JobsAxiomsMod.\n", "meta": {"author": "2xs", "repo": "pip_edf_scheduler", "sha": "e9036e82e8e35aadbcadb45dc24e4c344dd71e88", "save_path": "github-repos/coq/2xs-pip_edf_scheduler", "path": "github-repos/coq/2xs-pip_edf_scheduler/pip_edf_scheduler-e9036e82e8e35aadbcadb45dc24e4c344dd71e88/proof/JobsAxioms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.23427866639181408}}
{"text": "(* This file is generated by Why3's Coq driver *)\n(* Beware! Only edit allowed sections below    *)\nRequire Import BuiltIn.\nRequire BuiltIn.\nRequire int.Int.\nRequire list.List.\nRequire list.Length.\nRequire list.Mem.\nRequire map.Map.\nRequire list.Append.\nRequire list.Distinct.\n\n(* Why3 assumption *)\nDefinition unit := unit.\n\nAxiom qtmark : Type.\nParameter qtmark_WhyType : WhyType qtmark.\nExisting Instance qtmark_WhyType.\n\n(* Why3 assumption *)\nInductive array (a:Type) :=\n  | mk_array : Z -> (map.Map.map Z a) -> array a.\nAxiom array_WhyType : forall (a:Type) {a_WT:WhyType a}, WhyType (array a).\nExisting Instance array_WhyType.\nImplicit Arguments mk_array [[a]].\n\n(* Why3 assumption *)\nDefinition elts {a:Type} {a_WT:WhyType a} (v:(array a)): (map.Map.map Z a) :=\n  match v with\n  | (mk_array x x1) => x1\n  end.\n\n(* Why3 assumption *)\nDefinition length {a:Type} {a_WT:WhyType a} (v:(array a)): Z :=\n  match v with\n  | (mk_array x x1) => x\n  end.\n\n(* Why3 assumption *)\nDefinition get {a:Type} {a_WT:WhyType a} (a1:(array a)) (i:Z): a :=\n  (map.Map.get (elts a1) i).\n\n(* Why3 assumption *)\nDefinition set {a:Type} {a_WT:WhyType a} (a1:(array a)) (i:Z) (v:a): (array\n  a) := (mk_array (length a1) (map.Map.set (elts a1) i v)).\n\n(* Why3 assumption *)\nDefinition make {a:Type} {a_WT:WhyType a} (n:Z) (v:a): (array a) :=\n  (mk_array n (map.Map.const v: (map.Map.map Z a))).\n\n(* Why3 assumption *)\nInductive tree :=\n  | Empty : tree\n  | Node : tree -> tree -> tree.\nAxiom tree_WhyType : WhyType tree.\nExisting Instance tree_WhyType.\n\n(* Why3 assumption *)\nFixpoint size (t:tree) {struct t}: Z :=\n  match t with\n  | Empty => 0%Z\n  | (Node l r) => ((1%Z + (size l))%Z + (size r))%Z\n  end.\n\nAxiom size_nonneg : forall (t:tree), (0%Z <= (size t))%Z.\n\nAxiom size_left : forall (t:tree), (0%Z < (size t))%Z -> exists l:tree,\n  exists r:tree, (t = (Node l r)) /\\ ((size l) < (size t))%Z.\n\n(* Why3 assumption *)\nDefinition all_trees (n:Z) (l:(list tree)): Prop := (list.Distinct.distinct\n  l) /\\ forall (t:tree), ((size t) = n) <-> (list.Mem.mem t l).\n\nAxiom all_trees_0 : (all_trees 0%Z\n  (Init.Datatypes.cons Empty Init.Datatypes.nil)).\n\nAxiom tree_diff : forall (l1:tree) (l2:tree), (~ ((size l1) = (size l2))) ->\n  forall (r1:tree) (r2:tree), ~ ((Node l1 r1) = (Node l2 r2)).\n\n(* Why3 goal *)\nTheorem WP_parameter_combine : forall (i1:Z) (l1:(list tree)) (i2:Z)\n  (l2:(list tree)), ((0%Z <= i1)%Z /\\ ((all_trees i1 l1) /\\ ((0%Z <= i2)%Z /\\\n  (all_trees i2 l2)))) -> forall (l11:(list tree)), (list.Distinct.distinct\n  l11) -> forall (x:tree) (x1:(list tree)),\n  (l11 = (Init.Datatypes.cons x x1)) -> forall (l21:(list tree)),\n  (list.Distinct.distinct l21) -> forall (x2:tree) (x3:(list tree)),\n  (l21 = (Init.Datatypes.cons x2 x3)) -> ((list.Distinct.distinct x3) ->\n  forall (o:(list tree)), ((list.Distinct.distinct o) /\\ forall (t:tree),\n  (list.Mem.mem t o) <-> exists r:tree, (t = (Node x r)) /\\ (list.Mem.mem r\n  x3)) -> forall (t:tree), (list.Mem.mem t (Init.Datatypes.cons (Node x\n  x2) o)) -> exists r:tree, (t = (Node x r)) /\\ (list.Mem.mem r l21)).\nintros i1 l1 i2 l2 (h1,(h2,(h3,h4))) l11 h5 x x1 h6 l21 h7 x2 x3 h8\n        h9 o (h10,h11) t h12.\nsubst.\nunfold Mem.mem in h12; fold @Mem.mem in h12.\ndestruct h12.\nexists x2; intuition.\nred; intuition.\ngeneralize (h11 t). intuition.\ndestruct H0 as (r,h); exists r; intuition.\nred; intuition.\nQed.\n\n", "meta": {"author": "ssaavedra", "repo": "why3", "sha": "e28f4cda05925849c1c203f56b9f9b49e4bfe5b4", "save_path": "github-repos/coq/ssaavedra-why3", "path": "github-repos/coq/ssaavedra-why3/why3-e28f4cda05925849c1c203f56b9f9b49e4bfe5b4/examples/generate_all_trees/generate_all_trees_WP_GenerateAllTrees_WP_parameter_combine_2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.23427866639181408}}
{"text": "Require Import Coq.Sorting.Permutation.\nRequire Import Coq.Sorting.Sorting.\nRequire Import Coq.Structures.Orders.\nRequire Import VST.veric.base.\n\nRequire Import compcert.cfrontend.Ctypes. \n\n(* TODO: This is obviously true. Ask Xavior to remove the definition list_norepet.*)\nLemma list_norepet_NoDup: forall {A: Type} (l: list A), list_norepet l <-> NoDup l.\nProof.\nintros; split; intro;\ninduction H; constructor; auto.\nQed.\n\nLemma PTree_In_fst_elements {A: Type}: forall (T: PTree.t A) i,\n  In i (map fst (PTree.elements T)) <-> exists a, PTree.get i T = Some a.\nProof.\n  intros.\n  split; intros.\n  + apply list_in_map_inv in H.\n    destruct H as [[i0 a] [? ?]].\n    simpl in H; subst i0.\n    apply PTree.elements_complete in H0.\n    eauto.\n  + destruct H as [a ?].\n    apply PTree.elements_correct in H.\n    apply (in_map fst) in H.\n    auto.\nQed.\n\nLemma PTree_gs {A: Type}: forall (T: PTree.t A) i j x,\n  (exists a, PTree.get i T= Some a) ->\n  exists a, PTree.get i (PTree.set j x T) = Some a.\nProof.\n  intros.\n  destruct H.\n  destruct (Pos.eq_dec i j).\n  + subst.\n    rewrite PTree.gss; eauto.\n  + rewrite PTree.gso; eauto.\nQed.\n\nLemma PTree_gs_equiv {A: Type}: forall (T: PTree.t A) i j x,\n  (exists a, PTree.get i T= Some a) \\/ i = j <->\n  exists a, PTree.get i (PTree.set j x T) = Some a.\nProof.\n  intros.\n  split; intros.\n  + destruct H; [apply PTree_gs; auto |].\n    subst; rewrite PTree.gss; eauto.\n  + destruct (Pos.eq_dec i j); auto.\n    rewrite PTree.gso in H by auto.\n    auto.\nQed.\n\nLemma PTree_set_In_fst_elements {A: Type}: forall (T: PTree.t A) i i' a',\n  In i (map fst (PTree.elements T)) ->\n  In i (map fst (PTree.elements (PTree.set i' a' T))).\nProof.\n  intros.\n  rewrite PTree_In_fst_elements in H |- *.\n  apply PTree_gs; auto.\nQed.\n  \nFixpoint relative_defined_type {A: Type} (l: list (ident * A)) (t: type): Prop :=\n  match t with\n  | Tarray t' _ _ => relative_defined_type l t'\n  | Tstruct id _ => In id (map fst l)\n  | Tunion id _ => In id (map fst l)\n  | _ => True\n  end.\n\nLemma relative_defined_type_mono: forall {A B: Type} (l1: list (ident * A)) (l2: list (ident * B)) (t: type),\n  (forall i, In i (map fst l1) -> In i (map fst l2)) ->\n  relative_defined_type l1 t ->\n  relative_defined_type l2 t.\nProof.\n  intros.\n  induction t; auto.\n  + simpl in *.\n    firstorder.\n  + simpl in *.\n    firstorder.\nQed.\n\nLemma relative_defined_type_equiv: forall {A B: Type} (l1: list (ident * A)) (l2: list (ident * B)) (t: type),\n  (forall i, In i (map fst l1) <-> In i (map fst l2)) ->\n  (relative_defined_type l1 t <-> relative_defined_type l2 t).\nProof.\n  intros.\n  split; apply relative_defined_type_mono;\n  firstorder.\nQed.\n\nInductive ordered_composite: list (positive * composite) -> Prop :=\n| ordered_composite_nil: ordered_composite nil\n| ordered_composite_cons: forall i co l,\n    Forall (relative_defined_type l) (map snd (co_members co)) ->\n    ordered_composite l ->\n    ordered_composite ((i, co) :: l).\n\nModule composite_reorder.\n\n(* Use merge sort instead *)\n(* Sort rank from higher to lower *)\nModule CompositeRankOrder <: TotalLeBool.\n  Definition t := (positive * composite)%type.\n  Definition leb (x y: t) := Nat.leb (co_rank (snd y)) (co_rank (snd x)).\n\n  Theorem leb_total : forall a1 a2, leb a1 a2 = true \\/ leb a2 a1 = true.\n  Proof.\n    intros.\n    unfold leb.\n    rewrite !Nat.leb_le.\n    lia.\n  Qed.\n\n  Theorem leb_trans: Transitive (fun x y => is_true (leb x y)).\n  Proof.\n    hnf; intros; unfold leb, is_true in *.\n    rewrite !Nat.leb_le in *.\n    lia.\n  Qed.\n\nEnd CompositeRankOrder.\n\nModule CompositeRankSort := Sort CompositeRankOrder.\n\nSection composite_reorder.\n\nContext (cenv: composite_env)\n        (cenv_consistent: composite_env_consistent cenv).\n\nDefinition rebuild_composite_elements := CompositeRankSort.sort (PTree.elements cenv).\n\nInductive ordered_and_complete: list (positive * composite) -> Prop :=\n| ordered_and_complete_nil: ordered_and_complete nil\n| ordered_and_complete_cons: forall i co l,\n    (forall i' co',\n        cenv ! i' = Some co' ->\n        (co_rank co' < co_rank co)%nat ->\n        In (i', co') l) ->\n    ordered_and_complete l ->\n    ordered_and_complete ((i, co) :: l).\n\nTheorem RCT_Permutation: Permutation rebuild_composite_elements (PTree.elements cenv).\nProof.\n  symmetry.\n  apply CompositeRankSort.Permuted_sort.\nQed.\n\nLemma RCT_ordered_and_complete: ordered_and_complete rebuild_composite_elements.\nProof.\n  pose proof RCT_Permutation.\n  assert (forall i co, cenv ! i = Some co -> In (i, co) rebuild_composite_elements).\n  {\n    intros.\n    eapply Permutation_in.\n    + symmetry; apply RCT_Permutation.\n    + apply PTree.elements_correct; auto.\n  } \n  clear H.\n  pose proof CompositeRankSort.StronglySorted_sort (PTree.elements cenv) CompositeRankOrder.leb_trans.\n  pose proof app_nil_l rebuild_composite_elements.\n  unfold rebuild_composite_elements in *.\n  set (l := (CompositeRankSort.sort (PTree.elements cenv))) in H1 at 1 |- *.\n  revert H1; generalize (@nil (positive * composite)).\n  clearbody l.\n  induction l; intros.\n  + constructor.\n  + specialize (IHl (l0 ++ a :: nil)).\n    rewrite <- app_assoc in IHl.\n    specialize (IHl H1).\n    destruct a as [i co]; constructor; auto.\n    intros.\n    apply H0 in H2.\n    rewrite <- H1 in H2, H.\n    clear - H2 H3 H.\n    induction l0.\n    - destruct H2; auto.\n      exfalso; inv H0.\n      lia.\n    - inv H.\n      destruct H2.\n      * exfalso.\n        subst.\n        rewrite Forall_forall in H5.\n        specialize (H5 (i, co)).\n        rewrite in_app in H5.\n        specialize (H5 (or_intror (or_introl eq_refl))).\n        unfold is_true in H5.\n        rewrite Nat.leb_le in H5; simpl in H5.\n        lia.\n      * apply IHl0; auto.\nQed.\n\nTheorem RCT_ordered: ordered_composite rebuild_composite_elements.\nProof.\n  pose proof RCT_ordered_and_complete.\n  assert (forall i co, In (i, co) rebuild_composite_elements -> complete_members cenv (co_members co) = true /\\ co_rank co = rank_members cenv (co_members co)).\n  {\n    intros.\n    eapply Permutation_in in H0; [| exact RCT_Permutation].\n    apply PTree.elements_complete in H0; auto.\n    split.\n    + apply co_consistent_complete.\n      eapply cenv_consistent; eauto.\n    + apply co_consistent_rank.\n      eapply cenv_consistent; eauto.\n  }\n  induction H.\n  + constructor.\n  + specialize (IHordered_and_complete (fun i co HH => H0 i co (or_intror HH))).\n    constructor; auto.\n    clear IHordered_and_complete H1.\n    specialize (H0 _ _ (or_introl eq_refl)).\n    assert (rank_members cenv (co_members co) <= co_rank co)%nat by lia.\n    destruct H0 as [? _].\n    induction (co_members co) as [| [i0 t0] ?].\n    - constructor.\n    - simpl in H0; rewrite andb_true_iff in H0; destruct H0.\n      simpl in H1; pose proof Max.max_lub_r _ _ _ H1.\n      apply Max.max_lub_l in H1.\n      constructor; auto; clear IHm H2 H3.\n      simpl.\n      induction t0; try solve [simpl; auto].\n      * (* array *)\n        spec IHt0; auto.\n        spec IHt0; [simpl in H1; lia |].\n        auto.\n      * (* struct *)\n        simpl in H0, H1 |- *.\n        destruct (cenv ! i1) eqn:?H; [| inv H0].\n        specialize (H _ _ H2).\n        spec H; [lia |].\n        apply (in_map fst) in H; auto.\n      * (* union *)\n        simpl in H0, H1 |- *.\n        destruct (cenv ! i1) eqn:?H; [| inv H0].\n        specialize (H _ _ H2).\n        spec H; [lia |].\n        apply (in_map fst) in H; auto.\nQed.\n\nEnd composite_reorder.\n\nEnd composite_reorder.\n\nModule type_func.\nSection type_func.\n\nContext {A: Type}\n        (f_default: type -> A)\n        (f_array: A -> type -> Z -> attr -> A)\n        (f_struct: A -> ident -> attr -> A)\n        (f_union: A -> ident -> attr -> A)\n        (f_member: struct_or_union -> list (ident * type * A) -> A).\n\nFixpoint F (env: PTree.t A) (t: type): A :=\n  match t with\n  | Tarray t n a => f_array (F env t) t n a\n  | Tstruct id a =>\n      match env ! id with\n      | Some v => f_struct v id a\n      | None => f_default t\n      end\n  | Tunion id a =>\n      match env ! id with\n      | Some v => f_union v id a\n      | None => f_default t\n      end\n  | _ => f_default t\n  end.\n\nDefinition Complete (cenv: composite_env) (env: PTree.t A): Prop :=\n  forall i,\n    (exists co, PTree.get i cenv = Some co) <->\n    (exists a, PTree.get i env = Some a).\n\nDefinition Consistent (cenv: composite_env) (env: PTree.t A): Prop :=\n  forall i co a,\n    PTree.get i cenv = Some co ->\n    PTree.get i env = Some a ->\n    a = f_member (co_su co) (map\n                              (fun it0: positive * type =>\n                                 let (i0, t0) := it0 in\n                                 (i0, t0, F env t0))\n                              (co_members co)).\n\nDefinition env_rec (i: positive) (co: composite) (env: PTree.t A): PTree.t A :=\n  PTree.set i\n    (f_member (co_su co) (map\n                              (fun it0: positive * type =>\n                                 let (i0, t0) := it0 in (i0, t0, F env t0))\n                              (co_members co)))\n    env.\n\nDefinition Env (l: list (positive * composite)): PTree.t A :=\n  fold_right\n    (fun (ic: positive * composite) =>\n       let (i, co) := ic in env_rec i co)\n    (PTree.empty A)\n    l.\n\nLemma F_PTree_set: forall t env i a,\n  ~ In i (map fst (PTree.elements env)) ->\n  relative_defined_type (PTree.elements env) t ->\n  F env t = F (PTree.set i a env) t.\nProof.\n  intros.\n  induction t; auto.\n  + simpl.\n    apply IHt in H0.\n    rewrite H0; auto.\n  + simpl in H0 |- *.\n    rewrite PTree.gso; auto.\n    intro; subst; tauto.\n  + simpl in H0 |- *.\n    rewrite PTree.gso; auto.\n    intro; subst; tauto.\nQed.\n\nLemma relative_defined_type_PTree_set: forall t (env: PTree.t A) i a,\n  relative_defined_type (PTree.elements env) t ->\n  relative_defined_type (PTree.elements (PTree.set i a env)) t.\nProof.\n  intros.\n  revert H; apply relative_defined_type_mono.\n  intros; apply PTree_set_In_fst_elements; auto.\nQed.\n\nSection Consistency_Induction_Step.\n\nContext (cenv: composite_env)\n        (env: PTree.t A)\n        (l: list (positive * composite))\n        (i0: positive)\n        (co0: composite).\n\nHypothesis NOT_IN_LIST: ~ In i0 (map fst l).\n\nHypothesis RDT_list: Forall (relative_defined_type l) (map snd (co_members co0)).\n\nHypothesis CENV0: PTree.get i0 cenv = Some co0.\n\nHypothesis IH_In_equiv: forall i, In i (map fst l) <-> In i (map fst (PTree.elements env)).\n\nHypothesis IH_RDT:\n  forall i co a,\n    PTree.get i cenv = Some co ->\n    PTree.get i env = Some a ->\n    Forall (relative_defined_type (PTree.elements env)) (map snd (co_members co)).\n\nHypothesis IH_main:\n  Consistent cenv env.\n\nLemma NOT_IN: ~ In i0 (map fst (PTree.elements env)).\nProof.\n  intros.\n  rewrite <- IH_In_equiv; auto.\nQed.\n\nLemma RDT_PTree: Forall (relative_defined_type (PTree.elements env)) (map snd (co_members co0)).\nProof.\n  intros.\n  revert RDT_list; apply Forall_impl.\n  intros t.\n  apply relative_defined_type_mono.\n  firstorder.\nQed.\n\nLemma establish_In_equiv:\n  forall i, In i (map fst ((i0, co0) :: l)) <-> In i (map fst (PTree.elements (env_rec i0 co0 env))).\nProof.\n  intros.\n  specialize (IH_In_equiv i).\n  rewrite PTree_In_fst_elements in IH_In_equiv |- *.\n  unfold env_rec.\n  rewrite <- PTree_gs_equiv.\n  simpl In.\n  assert (i0 = i <-> i = i0) by (split; intros; congruence).\n  tauto.\nQed.\n\nLemma establish_RDT:\n  forall i co a,\n    PTree.get i cenv = Some co ->\n    PTree.get i (env_rec i0 co0 env) = Some a ->\n    Forall (relative_defined_type (PTree.elements (env_rec i0 co0 env))) (map snd (co_members co)).\nProof.\n  pose proof RDT_PTree as RDT_PTree.\n  intros i co a CENV ENV.\n  unfold env_rec in ENV.\n  destruct (Pos.eq_dec i i0).\n  + subst i0; rewrite CENV in CENV0; inversion CENV0; subst co0; clear CENV0.\n    rewrite PTree.gss in ENV.\n    inversion ENV; clear a ENV H0.\n    revert RDT_PTree.\n    apply Forall_impl; intros t.\n    apply relative_defined_type_PTree_set.\n  + rewrite PTree.gso in ENV by auto.\n    specialize (IH_RDT _ _ _ CENV ENV).\n    revert IH_RDT.\n    apply Forall_impl; intros t.\n    apply relative_defined_type_PTree_set.\nQed.\n\nLemma establish_main:\n  Consistent cenv (env_rec i0 co0 env).\nProof.\n  pose proof NOT_IN as NOT_IN.\n  pose proof RDT_PTree as RDT_PTree.\n  intros i co a CENV ENV.\n  unfold env_rec in ENV.\n  destruct (Pos.eq_dec i i0).\n  + subst i0; rewrite CENV in CENV0; inversion CENV0; subst co0; clear CENV0.\n    rewrite PTree.gss in ENV.\n    inversion ENV; clear a ENV H0.\n    f_equal.\n    auto.\n    apply map_ext_in.\n    intros (i1, t1) ?.\n    f_equal.\n    apply F_PTree_set; auto.\n    rewrite Forall_forall in RDT_PTree; apply RDT_PTree.\n    apply (in_map snd) in H; auto.\n  + rewrite PTree.gso in ENV by auto.\n    specialize (IH_main _ _ _ CENV ENV).\n    subst a.\n    f_equal.\n    apply map_ext_in.\n    intros (i1, t1) ?.\n    f_equal.\n    apply F_PTree_set; auto.\n    specialize (IH_RDT _ _ _ CENV ENV).\n    rewrite Forall_forall in IH_RDT; apply IH_RDT.\n    apply (in_map snd) in H; auto.\nQed.\n\nEnd Consistency_Induction_Step.\n\nLemma Consistency: forall cenv l,\n  Permutation l (PTree.elements cenv) ->\n  ordered_composite l ->\n  Consistent cenv (Env l).\nProof.\n  intros.\n  assert (forall i co, In (i, co) l -> PTree.get i cenv = Some co).\n  {\n    intros.\n    apply PTree.elements_complete.\n    eapply Permutation_in; eauto.\n  }\n  assert (NoDup (map fst l)).\n  {\n    eapply Permutation_NoDup; [symmetry; apply Permutation_map; eassumption |].\n    rewrite <- list_norepet_NoDup.\n    apply PTree.elements_keys_norepet.\n  }\n  clear H.\n  assert (\n    (forall i, In i (map fst l) <-> In i (map fst (PTree.elements (Env l)))) /\\\n    (forall i co a,\n      PTree.get i cenv = Some co ->\n      PTree.get i (Env l) = Some a ->\n      Forall (relative_defined_type (PTree.elements (Env l))) (map snd (co_members co))) /\\\n    Consistent cenv (Env l)); [| tauto].\n  induction l as [| [i0 co0] l].\n  + split; [| split]; hnf; intros.\n    - simpl; tauto.\n    - unfold Env in H3; simpl in H3.\n      rewrite PTree.gempty in H3; inv H3.\n    - unfold Env in H3; simpl in H3.\n      rewrite PTree.gempty in H3; inv H3.\n  + inv H0.\n    rename H4 into RDT_list; specialize (IHl H6); clear H6.\n    assert (CENV0: PTree.get i0 cenv = Some co0).\n    { apply H1; left; auto. }\n    spec IHl; [| clear H1].\n    { intros; apply H1; right; auto. } \n    inv H2.\n    rename H1 into NOT_IN_LIST; specialize (IHl H3); clear H3.\n    destruct IHl as [IH_In_equiv [IH_RDT IH_main]].\n    split; [| split].\n    - apply establish_In_equiv; auto.\n    - eapply establish_RDT; eauto.\n    - eapply establish_main; eauto.\nQed.\n\nLemma Completeness: forall cenv l,\n  Permutation l (PTree.elements cenv) ->\n  Complete cenv (Env l).\nProof.\n  intros.\n  intro.\n  rewrite <- !PTree_In_fst_elements.\n  pose proof PTree.elements_keys_norepet cenv.\n  rewrite list_norepet_NoDup in H0.\n  rewrite <- H in H0 |- *; clear H.\n  induction l.\n  + simpl; tauto.\n  + destruct a as [i0 co0].\n    inv H0.\n    specialize (IHl H3).\n    simpl.\n    unfold env_rec.\n    rewrite PTree_In_fst_elements, <- PTree_gs_equiv, <- PTree_In_fst_elements.\n    assert (i = i0 <-> i0 = i) by (split; intros; congruence).\n    tauto.\nQed.\n\nEnd type_func.\n\nEnd type_func.\n\nCorollary composite_reorder_consistent {A: Type}:\n  forall cenv f_default f_array f_struct f_union f_members,\n    composite_env_consistent cenv ->\n    type_func.Consistent f_default f_array f_struct f_union f_members cenv (@type_func.Env A f_default f_array f_struct f_union f_members (composite_reorder.rebuild_composite_elements cenv)).\nProof.\n  intros.\n  apply type_func.Consistency.\n  + apply composite_reorder.RCT_Permutation.\n  + apply composite_reorder.RCT_ordered; auto.\nQed.\n\nCorollary composite_reorder_complete {A: Type}:\n  forall cenv f_default f_array f_struct f_union f_members,\n    type_func.Complete cenv (@type_func.Env A f_default f_array f_struct f_union f_members (composite_reorder.rebuild_composite_elements cenv)).\nProof.\n  intros.\n  apply type_func.Completeness.\n  apply composite_reorder.RCT_Permutation.\nQed.\n\nSection cuof.\n\nContext (cenv: composite_env).\n\nFixpoint complete_legal_cosu_type t :=\n  match t with\n  | Tarray t' _ _ => complete_legal_cosu_type t'\n  | Tstruct id _ => match cenv ! id with\n                    | Some co => match co_su co with\n                                 | Struct => true\n                                 | Union => false\n                                 end\n                    | _ => false\n                    end\n  | Tunion id _ => match cenv ! id with\n                   | Some co => match co_su co with\n                                | Struct => false\n                                | Union => true\n                                end\n                   | _ => false\n                   end\n  | Tfunction _ _ _\n  | Tvoid => false\n  | _ => true\n  end.\n\nFixpoint composite_complete_legal_cosu_type (m: members): bool :=\n  match m with\n  | nil => true\n  | (_, t) :: m' => complete_legal_cosu_type t && composite_complete_legal_cosu_type m'\n  end.\n\nDefinition composite_env_complete_legal_cosu_type: Prop :=\n  forall (id : positive) (co : composite),\n    cenv ! id = Some co -> composite_complete_legal_cosu_type (co_members co) = true.\n  \nEnd cuof.\n\nLemma complete_legal_cosu_type_complete_type: forall cenv: composite_env,\n  forall t,\n    complete_legal_cosu_type cenv t = true ->\n    complete_type cenv t = true.\nProof.\n  intros.\n  induction t; auto.\n  + simpl in *.\n    destruct (cenv ! i); auto.\n  + simpl in *.\n    destruct (cenv ! i); auto.\nQed.\n\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/veric/composite_compute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23427866639181405}}
{"text": "(* Distributed under the terms of the MIT license. *)\n\n(** Generic transofmations from one language to another,\n    preserving an evaluation relation up-to some observational equality. *)\n\nFrom Coq Require Import Program ssreflect ssrbool.\nFrom Equations Require Import Equations.\nFrom MetaCoq.Utils Require Import utils.\nImport bytestring.\nLocal Open Scope bs.\nLocal Open Scope string_scope2.\n\n(* Used to show timings of the ML execution *)\n\nDefinition time : forall {A B}, string -> (A -> B) -> A -> B :=\n  fun A B s f x => f x.\n\nExtract Constant time =>\n  \"(fun c f x -> let s = Caml_bytestring.caml_string_of_bytestring c in Tm_util.time (Pp.str s) f x)\".\n\nModule Transform.\n  Section Opt.\n     Context {program program' : Type}.\n     Context {value value' : Type}.\n     Context {eval :  program -> value -> Prop}.\n     Context {eval' : program' -> value' -> Prop}.\n\n     Definition preserves_eval pre (transform : forall p : program, pre p -> program') obseq :=\n      forall p v (pr : pre p),\n        eval p v ->\n        let p' := transform p pr in\n        exists v', eval' p' v' /\\ obseq p p' v v'.\n\n    Record t :=\n    { name : string;\n      pre : program -> Prop;\n      transform : forall p : program, pre p -> program';\n      post : program' -> Prop;\n      correctness : forall input (p : pre input), post (transform input p);\n      obseq : program -> program' -> value -> value' -> Prop;\n      preservation : preserves_eval pre transform obseq; }.\n\n    Definition run (x : t) (p : program) (pr : pre x p) : program' :=\n      time x.(name) (fun _ => x.(transform) p pr) tt.\n\n  End Opt.\n  Arguments t : clear implicits.\n\n  Definition self_transform program value eval eval' := t program program value value eval eval'.\n\n  Section Comp.\n    Context {program program' program'' : Type}.\n    Context {value value' value'' : Type}.\n    Context {eval : program -> value -> Prop}.\n    Context {eval' : program' -> value' -> Prop}.\n    Context {eval'' : program'' -> value'' -> Prop}.\n\n    Local Obligation Tactic := idtac.\n    Program Definition compose (o : t program program' value value' eval eval') (o' : t program' program'' value' value'' eval' eval'')\n      (hpp : (forall p, o.(post) p -> o'.(pre) p)) : t program program'' value value'' eval eval'' :=\n      {|\n        name := (o.(name) ^ \" -> \" ^ o'.(name))%bs;\n        transform p hp := run o' (run o p hp) (hpp _ (o.(correctness) _ hp));\n        pre := o.(pre);\n        post := o'.(post);\n        obseq g g' v v' := exists g'' v'', o.(obseq) g g'' v v'' × o'.(obseq) g'' g' v'' v'\n        |}.\n    Next Obligation.\n      intros o o' hpp inp pre.\n      eapply o'.(correctness).\n    Qed.\n    Next Obligation.\n      red. intros o o' hpp.\n      intros p v pr ev.\n      eapply (o.(preservation) _ _ pr) in ev; auto.\n      cbn in ev. destruct ev as [v' [ev]].\n      epose proof (o'.(preservation) (o.(transform) p pr) v').\n      specialize (H0 (hpp _ (o.(correctness) _ pr)) ev).\n      destruct H0 as [v'' [ev' obs']].\n      exists v''. constructor => //.\n      exists (transform o p pr), v'. now split.\n    Qed.\n  End Comp.\n\n  Declare Scope transform_scope.\n  Bind Scope transform_scope with t.\n\n  Notation \" o ▷ o' \" := (Transform.compose o o' _) (at level 50, left associativity) : transform_scope.\n\n  Open Scope transform_scope.\nEnd Transform.\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/common/theories/Transform.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23427865989988356}}
{"text": "\nRequire Import Clightdefs.\nLocal Open Scope Z_scope.\nRequire Import aes.aes.\n\nDefinition encryption_loop_body :=\n   (Ssequence (Sset _t'5 (Etempvar _RK (tptr tuint)))\n       (Ssequence (Sset _RK (Ebinop Oadd (Etempvar _t'5 (tptr tuint)) (Econst_int (Int.repr 1) tint) (tptr tuint)))\n          (Ssequence (Sset _rk (Ederef (Etempvar _t'5 (tptr tuint)) tuint))\n             (Ssequence\n                (Sset _b0__4\n                   (Ederef\n                      (Ebinop Oadd (Efield (Evar _tables (Tstruct _aes_tables_struct noattr)) _FT0 (tarray tuint 256))\n                         (Ebinop Oand (Etempvar _X0 tuint) (Econst_int (Int.repr 255) tint) tuint) (tptr tuint)) tuint))\n                (Ssequence\n                   (Sset _b1__4\n                      (Ederef\n                         (Ebinop Oadd (Efield (Evar _tables (Tstruct _aes_tables_struct noattr)) _FT1 (tarray tuint 256))\n                            (Ebinop Oand (Ebinop Oshr (Etempvar _X1 tuint) (Econst_int (Int.repr 8) tint) tuint) (Econst_int (Int.repr 255) tint) tuint)\n                            (tptr tuint)) tuint))\n                   (Ssequence\n                      (Sset _b2__4\n                         (Ederef\n                            (Ebinop Oadd (Efield (Evar _tables (Tstruct _aes_tables_struct noattr)) _FT2 (tarray tuint 256))\n                               (Ebinop Oand (Ebinop Oshr (Etempvar _X2 tuint) (Econst_int (Int.repr 16) tint) tuint) (Econst_int (Int.repr 255) tint) tuint)\n                               (tptr tuint)) tuint))\n                      (Ssequence\n                         (Sset _b3__4\n                            (Ederef\n                               (Ebinop Oadd (Efield (Evar _tables (Tstruct _aes_tables_struct noattr)) _FT3 (tarray tuint 256))\n                                  (Ebinop Oand (Ebinop Oshr (Etempvar _X3 tuint) (Econst_int (Int.repr 24) tint) tuint) (Econst_int (Int.repr 255) tint) tuint)\n                                  (tptr tuint)) tuint))\n                         (Ssequence\n                            (Sset _Y0\n                               (Ebinop Oxor\n                                  (Ebinop Oxor (Ebinop Oxor (Ebinop Oxor (Etempvar _rk tuint) (Etempvar _b0__4 tuint) tuint) (Etempvar _b1__4 tuint) tuint)\n                                     (Etempvar _b2__4 tuint) tuint) (Etempvar _b3__4 tuint) tuint))\n                            (Ssequence (Sset _t'6 (Etempvar _RK (tptr tuint)))\n                               (Ssequence (Sset _RK (Ebinop Oadd (Etempvar _t'6 (tptr tuint)) (Econst_int (Int.repr 1) tint) (tptr tuint)))\n                                  (Ssequence (Sset _rk (Ederef (Etempvar _t'6 (tptr tuint)) tuint))\n                                     (Ssequence\n                                        (Sset _b0__4\n                                           (Ederef\n                                              (Ebinop Oadd (Efield (Evar _tables (Tstruct _aes_tables_struct noattr)) _FT0 (tarray tuint 256))\n                                                 (Ebinop Oand (Etempvar _X1 tuint) (Econst_int (Int.repr 255) tint) tuint) (tptr tuint)) tuint))\n                                        (Ssequence\n                                           (Sset _b1__4\n                                              (Ederef\n                                                 (Ebinop Oadd (Efield (Evar _tables (Tstruct _aes_tables_struct noattr)) _FT1 (tarray tuint 256))\n                                                    (Ebinop Oand (Ebinop Oshr (Etempvar _X2 tuint) (Econst_int (Int.repr 8) tint) tuint)\n                                                       (Econst_int (Int.repr 255) tint) tuint) (tptr tuint)) tuint))\n                                           (Ssequence\n                                              (Sset _b2__4\n                                                 (Ederef\n                                                    (Ebinop Oadd (Efield (Evar _tables (Tstruct _aes_tables_struct noattr)) _FT2 (tarray tuint 256))\n                                                       (Ebinop Oand (Ebinop Oshr (Etempvar _X3 tuint) (Econst_int (Int.repr 16) tint) tuint)\n                                                          (Econst_int (Int.repr 255) tint) tuint) (tptr tuint)) tuint))\n                                              (Ssequence\n                                                 (Sset _b3__4\n                                                    (Ederef\n                                                       (Ebinop Oadd (Efield (Evar _tables (Tstruct _aes_tables_struct noattr)) _FT3 (tarray tuint 256))\n                                                          (Ebinop Oand (Ebinop Oshr (Etempvar _X0 tuint) (Econst_int (Int.repr 24) tint) tuint)\n                                                             (Econst_int (Int.repr 255) tint) tuint) (tptr tuint)) tuint))\n                                                 (Ssequence\n                                                    (Sset _Y1\n                                                       (Ebinop Oxor\n                                                          (Ebinop Oxor\n                                                             (Ebinop Oxor (Ebinop Oxor (Etempvar _rk tuint) (Etempvar _b0__4 tuint) tuint)\n                                                                (Etempvar _b1__4 tuint) tuint) (Etempvar _b2__4 tuint) tuint) (Etempvar _b3__4 tuint) tuint))\n                                                    (Ssequence (Sset _t'7 (Etempvar _RK (tptr tuint)))\n                                                       (Ssequence\n                                                          (Sset _RK (Ebinop Oadd (Etempvar _t'7 (tptr tuint)) (Econst_int (Int.repr 1) tint) (tptr tuint)))\n                                                          (Ssequence (Sset _rk (Ederef (Etempvar _t'7 (tptr tuint)) tuint))\n                                                             (Ssequence\n                                                                (Sset _b0__4\n                                                                   (Ederef\n                                                                      (Ebinop Oadd\n                                                                         (Efield (Evar _tables (Tstruct _aes_tables_struct noattr)) _FT0 (tarray tuint 256))\n                                                                         (Ebinop Oand (Etempvar _X2 tuint) (Econst_int (Int.repr 255) tint) tuint) \n                                                                         (tptr tuint)) tuint))\n                                                                (Ssequence\n                                                                   (Sset _b1__4\n                                                                      (Ederef\n                                                                         (Ebinop Oadd\n                                                                            (Efield (Evar _tables (Tstruct _aes_tables_struct noattr)) _FT1 (tarray tuint 256))\n                                                                            (Ebinop Oand\n                                                                               (Ebinop Oshr (Etempvar _X3 tuint) (Econst_int (Int.repr 8) tint) tuint)\n                                                                               (Econst_int (Int.repr 255) tint) tuint) (tptr tuint)) tuint))\n                                                                   (Ssequence\n                                                                      (Sset _b2__4\n                                                                         (Ederef\n                                                                            (Ebinop Oadd\n                                                                               (Efield (Evar _tables (Tstruct _aes_tables_struct noattr)) _FT2\n                                                                                  (tarray tuint 256))\n                                                                               (Ebinop Oand\n                                                                                  (Ebinop Oshr (Etempvar _X0 tuint) (Econst_int (Int.repr 16) tint) tuint)\n                                                                                  (Econst_int (Int.repr 255) tint) tuint) (tptr tuint)) tuint))\n                                                                      (Ssequence\n                                                                         (Sset _b3__4\n                                                                            (Ederef\n                                                                               (Ebinop Oadd\n                                                                                  (Efield (Evar _tables (Tstruct _aes_tables_struct noattr)) _FT3\n                                                                                     (tarray tuint 256))\n                                                                                  (Ebinop Oand\n                                                                                     (Ebinop Oshr (Etempvar _X1 tuint) (Econst_int (Int.repr 24) tint) tuint)\n                                                                                     (Econst_int (Int.repr 255) tint) tuint) (tptr tuint)) tuint))\n                                                                         (Ssequence\n                                                                            (Sset _Y2\n                                                                               (Ebinop Oxor\n                                                                                  (Ebinop Oxor\n                                                                                     (Ebinop Oxor\n                                                                                        (Ebinop Oxor (Etempvar _rk tuint) (Etempvar _b0__4 tuint) tuint)\n                                                                                        (Etempvar _b1__4 tuint) tuint) (Etempvar _b2__4 tuint) tuint)\n                                                                                  (Etempvar _b3__4 tuint) tuint))\n                                                                            (Ssequence (Sset _t'8 (Etempvar _RK (tptr tuint)))\n                                                                               (Ssequence\n                                                                                  (Sset _RK\n                                                                                     (Ebinop Oadd (Etempvar _t'8 (tptr tuint)) (Econst_int (Int.repr 1) tint)\n                                                                                        (tptr tuint)))\n                                                                                  (Ssequence (Sset _rk (Ederef (Etempvar _t'8 (tptr tuint)) tuint))\n                                                                                     (Ssequence\n                                                                                        (Sset _b0__4\n                                                                                           (Ederef\n                                                                                              (Ebinop Oadd\n                                                                                                 (Efield (Evar _tables (Tstruct _aes_tables_struct noattr))\n                                                                                                    _FT0 (tarray tuint 256))\n                                                                                                 (Ebinop Oand (Etempvar _X3 tuint)\n                                                                                                    (Econst_int (Int.repr 255) tint) tuint) \n                                                                                                 (tptr tuint)) tuint))\n                                                                                        (Ssequence\n                                                                                           (Sset _b1__4\n                                                                                              (Ederef\n                                                                                                 (Ebinop Oadd\n                                                                                                    (Efield (Evar _tables (Tstruct _aes_tables_struct noattr))\n                                                                                                       _FT1 (tarray tuint 256))\n                                                                                                    (Ebinop Oand\n                                                                                                       (Ebinop Oshr (Etempvar _X0 tuint)\n                                                                                                          (Econst_int (Int.repr 8) tint) tuint)\n                                                                                                       (Econst_int (Int.repr 255) tint) tuint) \n                                                                                                    (tptr tuint)) tuint))\n                                                                                           (Ssequence\n                                                                                              (Sset _b2__4\n                                                                                                 (Ederef\n                                                                                                    (Ebinop Oadd\n                                                                                                       (Efield\n                                                                                                          (Evar _tables (Tstruct _aes_tables_struct noattr))\n                                                                                                          _FT2 (tarray tuint 256))\n                                                                                                       (Ebinop Oand\n                                                                                                          (Ebinop Oshr (Etempvar _X1 tuint)\n                                                                                                             (Econst_int (Int.repr 16) tint) tuint)\n                                                                                                          (Econst_int (Int.repr 255) tint) tuint) \n                                                                                                       (tptr tuint)) tuint))\n                                                                                              (Ssequence\n                                                                                                 (Sset _b3__4\n                                                                                                    (Ederef\n                                                                                                       (Ebinop Oadd\n                                                                                                          (Efield\n                                                                                                             (Evar _tables (Tstruct _aes_tables_struct noattr))\n                                                                                                             _FT3 (tarray tuint 256))\n                                                                                                          (Ebinop Oand\n                                                                                                             (Ebinop Oshr (Etempvar _X2 tuint)\n                                                                                                                (Econst_int (Int.repr 24) tint) tuint)\n                                                                                                             (Econst_int (Int.repr 255) tint) tuint)\n                                                                                                          (tptr tuint)) tuint))\n                                                                                                 (Ssequence\n                                                                                                    (Sset _Y3\n                                                                                                       (Ebinop Oxor\n                                                                                                          (Ebinop Oxor\n                                                                                                             (Ebinop Oxor\n                                                                                                                (Ebinop Oxor (Etempvar _rk tuint)\n                                                                                                                   (Etempvar _b0__4 tuint) tuint)\n                                                                                                                (Etempvar _b1__4 tuint) tuint)\n                                                                                                             (Etempvar _b2__4 tuint) tuint)\n                                                                                                          (Etempvar _b3__4 tuint) tuint))\n                                                                                                    (Ssequence (Sset _t'9 (Etempvar _RK (tptr tuint)))\n                                                                                                       (Ssequence\n                                                                                                          (Sset _RK\n                                                                                                             (Ebinop Oadd (Etempvar _t'9 (tptr tuint))\n                                                                                                                (Econst_int (Int.repr 1) tint) \n                                                                                                                (tptr tuint)))\n                                                                                                          (Ssequence\n                                                                                                             (Sset _rk__1\n                                                                                                                (Ederef (Etempvar _t'9 (tptr tuint)) tuint))\n                                                                                                             (Ssequence\n                                                                                                                (Sset _b0__5\n                                                                                                                   (Ederef\n                                                                                                                      (Ebinop Oadd\n                                                                                                                         (Efield\n                                                                                                                            (Evar _tables\n                                                                                                                               (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT0\n                                                                                                                            (tarray tuint 256))\n                                                                                                                         (Ebinop Oand \n                                                                                                                            (Etempvar _Y0 tuint)\n                                                                                                                            (Econst_int (Int.repr 255) tint)\n                                                                                                                            tuint) \n                                                                                                                         (tptr tuint)) tuint))\n                                                                                                                (Ssequence\n                                                                                                                   (Sset _b1__5\n                                                                                                                      (Ederef\n                                                                                                                         (Ebinop Oadd\n                                                                                                                            (Efield\n                                                                                                                               (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT1\n                                                                                                                               (tarray tuint 256))\n                                                                                                                            (Ebinop Oand\n                                                                                                                               (Ebinop Oshr\n                                                                                                                                  (Etempvar _Y1 tuint)\n                                                                                                                                  (Econst_int (Int.repr 8) tint)\n                                                                                                                                  tuint)\n                                                                                                                               (Econst_int (Int.repr 255) tint)\n                                                                                                                               tuint) \n                                                                                                                            (tptr tuint)) tuint))\n                                                                                                                   (Ssequence\n                                                                                                                      (Sset _b2__5\n                                                                                                                         (Ederef\n                                                                                                                            (Ebinop Oadd\n                                                                                                                               (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT2\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                               (Ebinop Oand\n                                                                                                                                  (Ebinop Oshr\n                                                                                                                                  (Etempvar _Y2 tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 16) tint) tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                               (tptr tuint)) tuint))\n                                                                                                                      (Ssequence\n                                                                                                                         (Sset _b3__5\n                                                                                                                            (Ederef\n                                                                                                                               (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT3\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Ebinop Oshr\n                                                                                                                                  (Etempvar _Y3 tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 24) tint) tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                         (Ssequence\n                                                                                                                            (Sset _X0\n                                                                                                                               (Ebinop Oxor\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Etempvar _rk__1 tuint)\n                                                                                                                                  (Etempvar _b0__5 tuint) tuint)\n                                                                                                                                  (Etempvar _b1__5 tuint) tuint)\n                                                                                                                                  (Etempvar _b2__5 tuint) tuint)\n                                                                                                                                  (Etempvar _b3__5 tuint) tuint))\n                                                                                                                            (Ssequence\n                                                                                                                               (Sset _t'10\n                                                                                                                                  (Etempvar _RK (tptr tuint)))\n                                                                                                                               (Ssequence\n                                                                                                                                  (Sset _RK\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Etempvar _t'10 (tptr tuint))\n                                                                                                                                  (Econst_int (Int.repr 1) tint)\n                                                                                                                                  (tptr tuint)))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _rk__1\n                                                                                                                                  (Ederef\n                                                                                                                                  (Etempvar _t'10 (tptr tuint))\n                                                                                                                                  tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _b0__5\n                                                                                                                                  (Ederef\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT0\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Etempvar _Y1 tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _b1__5\n                                                                                                                                  (Ederef\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT1\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Ebinop Oshr\n                                                                                                                                  (Etempvar _Y2 tuint)\n                                                                                                                                  (Econst_int (Int.repr 8) tint)\n                                                                                                                                  tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _b2__5\n                                                                                                                                  (Ederef\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT2\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Ebinop Oshr\n                                                                                                                                  (Etempvar _Y3 tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 16) tint) tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _b3__5\n                                                                                                                                  (Ederef\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT3\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Ebinop Oshr\n                                                                                                                                  (Etempvar _Y0 tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 24) tint) tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _X1\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Etempvar _rk__1 tuint)\n                                                                                                                                  (Etempvar _b0__5 tuint) tuint)\n                                                                                                                                  (Etempvar _b1__5 tuint) tuint)\n                                                                                                                                  (Etempvar _b2__5 tuint) tuint)\n                                                                                                                                  (Etempvar _b3__5 tuint) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _t'11\n                                                                                                                                  (Etempvar _RK (tptr tuint)))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _RK\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Etempvar _t'11 (tptr tuint))\n                                                                                                                                  (Econst_int (Int.repr 1) tint)\n                                                                                                                                  (tptr tuint)))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _rk__1\n                                                                                                                                  (Ederef\n                                                                                                                                  (Etempvar _t'11 (tptr tuint))\n                                                                                                                                  tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _b0__5\n                                                                                                                                  (Ederef\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT0\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Etempvar _Y2 tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _b1__5\n                                                                                                                                  (Ederef\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT1\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Ebinop Oshr\n                                                                                                                                  (Etempvar _Y3 tuint)\n                                                                                                                                  (Econst_int (Int.repr 8) tint)\n                                                                                                                                  tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _b2__5\n                                                                                                                                  (Ederef\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT2\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Ebinop Oshr\n                                                                                                                                  (Etempvar _Y0 tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 16) tint) tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _b3__5\n                                                                                                                                  (Ederef\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT3\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Ebinop Oshr\n                                                                                                                                  (Etempvar _Y1 tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 24) tint) tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _X2\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Etempvar _rk__1 tuint)\n                                                                                                                                  (Etempvar _b0__5 tuint) tuint)\n                                                                                                                                  (Etempvar _b1__5 tuint) tuint)\n                                                                                                                                  (Etempvar _b2__5 tuint) tuint)\n                                                                                                                                  (Etempvar _b3__5 tuint) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _t'12\n                                                                                                                                  (Etempvar _RK (tptr tuint)))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _RK\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Etempvar _t'12 (tptr tuint))\n                                                                                                                                  (Econst_int (Int.repr 1) tint)\n                                                                                                                                  (tptr tuint)))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _rk__1\n                                                                                                                                  (Ederef\n                                                                                                                                  (Etempvar _t'12 (tptr tuint))\n                                                                                                                                  tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _b0__5\n                                                                                                                                  (Ederef\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT0\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Etempvar _Y3 tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _b1__5\n                                                                                                                                  (Ederef\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT1\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Ebinop Oshr\n                                                                                                                                  (Etempvar _Y0 tuint)\n                                                                                                                                  (Econst_int (Int.repr 8) tint)\n                                                                                                                                  tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _b2__5\n                                                                                                                                  (Ederef\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT2\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Ebinop Oshr\n                                                                                                                                  (Etempvar _Y1 tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 16) tint) tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                                  (Ssequence\n                                                                                                                                  (Sset _b3__5\n                                                                                                                                  (Ederef\n                                                                                                                                  (Ebinop Oadd\n                                                                                                                                  (Efield\n                                                                                                                                  (Evar _tables\n                                                                                                                                  (Tstruct _aes_tables_struct\n                                                                                                                                  noattr)) _FT3\n                                                                                                                                  (tarray tuint 256))\n                                                                                                                                  (Ebinop Oand\n                                                                                                                                  (Ebinop Oshr\n                                                                                                                                  (Etempvar _Y2 tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 24) tint) tuint)\n                                                                                                                                  (Econst_int \n                                                                                                                                  (Int.repr 255) tint) tuint)\n                                                                                                                                  (tptr tuint)) tuint))\n                                                                                                                                  (Sset _X3\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Ebinop Oxor\n                                                                                                                                  (Etempvar _rk__1 tuint)\n                                                                                                                                  (Etempvar _b0__5 tuint) tuint)\n                                                                                                                                  (Etempvar _b1__5 tuint) tuint)\n                                                                                                                                  (Etempvar _b2__5 tuint) tuint)\n                                                                                                                                  (Etempvar _b3__5 tuint) tuint))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))).\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/aes/aes_encryption_loop_body.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23427261885712974}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.strlib.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition strchr_spec :=\n DECLARE _strchr\n  WITH sh: share, str : val, s : list byte, c : byte\n  PRE  [ _str OF tptr tschar, _c OF tint ]\n    PROP (readable_share sh; c <> Byte.zero)\n    LOCAL (temp _str str; temp _c (Vbyte c))\n    SEP (cstring sh s str)\n  POST [ tptr tschar ]\n   EX r : val,\n    PROP ((exists i, Znth i s = c /\\ Forall (fun d => d<>c) (sublist 0 i s)\n                     /\\ r = offset_val i str)\n       \\/ (Forall (fun d => d<>c) s /\\ r = nullval))\n    LOCAL (temp ret_temp r)\n    SEP (cstring sh s str).\n\nDefinition strcat_spec :=\n DECLARE _strcat\n  WITH sh: share, sh': share, dest : val, sd : list byte, n : Z, src : val, ss : list byte\n  PRE  [ _dest OF tptr tschar, _src OF tptr tschar ]\n    PROP (writable_share sh; readable_share sh'; Zlength sd + Zlength ss < n)\n    LOCAL (temp _dest dest; temp _src src)\n    SEP (cstringn sh sd n dest; cstring sh' ss src)\n  POST [ tptr tschar ]\n    PROP ()\n    LOCAL (temp ret_temp dest)\n    SEP (cstringn sh (sd ++ ss) n dest; cstring sh' ss src).\n\nDefinition strcmp_spec :=\n DECLARE _strcmp\n  WITH sh1: share, sh2: share, str1 : val, s1 : list byte, str2 : val, s2 : list byte\n  PRE [ _str1 OF tptr tschar, _str2 OF tptr tschar ]\n    PROP (readable_share sh1; readable_share sh2)\n    LOCAL (temp _str1 str1; temp _str2 str2)\n    SEP (cstring sh1 s1 str1; cstring sh2 s2 str2)\n  POST [ tint ]\n   EX i : int,\n    PROP (if Int.eq_dec i Int.zero then s1 = s2 else s1 <> s2)\n    LOCAL (temp ret_temp (Vint i))\n    SEP (cstring sh1 s1 str1; cstring sh2 s2 str2).\n\nDefinition strcpy_spec :=\n DECLARE _strcpy\n  WITH sh: share, sh': share, dest : val, n : Z, src : val, s : list byte\n  PRE [ _dest OF tptr tschar, _src OF tptr tschar ]\n    PROP (writable_share sh; readable_share sh'; Zlength s < n)\n    LOCAL (temp _dest dest; temp _src src)\n    SEP (data_at_ sh (tarray tschar n) dest; cstring sh' s src)\n  POST [ tptr tschar ]\n    PROP ()\n    LOCAL (temp ret_temp dest)\n    SEP (cstringn sh s n dest; cstring sh' s src).\n\nDefinition strlen_spec :=\n DECLARE _strlen\n  WITH sh: share, s : list byte, str: val\n  PRE [ _str OF tptr tschar ]\n    PROP (readable_share sh)\n    LOCAL (temp _str str)\n    SEP (cstring sh s str)\n  POST [ tptr tschar ]\n    PROP ()\n    LOCAL (temp ret_temp (Vptrofs (Ptrofs.repr (Zlength s))))\n    SEP (cstring sh s str).\n\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ strchr_spec; strcat_spec; strcmp_spec ]).\n\nHint Rewrite Z.add_simpl_r Z.sub_simpl_r : norm entailer_rewrite.\n\nLemma body_strlen: semax_body Vprog Gprog f_strlen strlen_spec.\nProof.\nstart_function.\nunfold cstring in *.\nrename s into ls.\nIntros.\nforward.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1)\n  LOCAL (temp _str str; temp _i (Vptrofs (Ptrofs.repr i)))\n  SEP (data_at sh (tarray tschar (Zlength ls + 1))\n          (map Vbyte (ls ++ [Byte.zero])) str))\n continue: (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1)\n  LOCAL (temp _str str; temp _i (Vptrofs (Ptrofs.repr (i-1))))\n  SEP (data_at sh (tarray tschar (Zlength ls + 1))\n          (map Vbyte (ls ++ [Byte.zero])) str)).\n*\nExists 0. entailer!.\n*\nIntros i.\nassert (Zlength (ls ++ [Byte.zero]) = Zlength ls + 1) by (autorewrite with sublist; auto).\nforward.\nforward_if.\nforward.\nentailer!. f_equal. f_equal. cstring.\nforward. \nExists (i+1).\nentailer!. cstring.\n*\nIntros i.\nforward.\nExists i.\nentailer!.\nQed.\n\nLemma body_strchr: semax_body Vprog Gprog f_strchr strchr_spec.\nProof.\nstart_function.\nforward.\nunfold cstring in *.\nrename s into ls.\nIntros.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1; Forall (fun d => d <> c) (sublist 0 i ls))\n  LOCAL (temp _str str; temp _c (Vbyte c); temp _i (Vint (Int.repr i)))\n  SEP (data_at sh (tarray tschar (Zlength ls + 1))\n          (map Vbyte (ls ++ [Byte.zero])) str))\n continue: (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1; Forall (fun d => d <> c) (sublist 0 i ls))\n  LOCAL (temp _str str; temp _c (Vbyte c); temp _i (Vint (Int.repr (i-1))))\n  SEP (data_at sh (tarray tschar (Zlength ls + 1))\n          (map Vbyte (ls ++ [Byte.zero])) str)).\n  Exists 0; rewrite sublist_nil; entailer!.\n- Intros i. \n  assert (Zlength (ls ++ [Byte.zero]) = Zlength ls + 1) by (autorewrite with sublist; auto).\n  forward. normalize.\n  forward. fold_Vbyte.\n forward_if.\n  { forward. simpl. \n    Exists (offset_val i str).\n    entailer!.\n    left. exists i. split3; auto. rewrite app_Znth1; auto. cstring. }\n  { forward_if.\n    { forward.\n      Exists nullval; rewrite !map_app; entailer!.\n      right. split; auto.\n      assert (i = Zlength ls) by cstring.\n      subst i.\n     autorewrite with sublist in H2; auto. }\n  forward.\n  Exists (i+1); entailer!.\n  assert (i <> Zlength ls) by cstring.\n  split. omega.\n  rewrite (sublist_split 0 i) by rep_omega. rewrite Forall_app. split; auto.\n  rewrite sublist_len_1 by rep_omega. repeat constructor.\n  rewrite app_Znth1 in H4 by rep_omega. auto.\n  }\n-\n  Intros i.\n  forward.\n  Exists i.\n entailer!.\nQed.\n\nLemma split_data_at_app_tschar:\n forall sh n (al bl: list val) p ,\n   n = Zlength (al++bl) ->\n   data_at sh (tarray tschar n) (al++bl) p = \n         data_at sh (tarray tschar (Zlength al)) al p\n        * data_at sh (tarray tschar (n - Zlength al)) bl\n                 (field_address0 (tarray tschar n) [ArraySubsc (Zlength al)] p).\nProof.\nintros.\napply (split2_data_at_Tarray_app _ n  sh tschar al bl ); auto.\nrewrite Zlength_app in H.\nchange ( Zlength bl = n - Zlength al); omega.\nQed.\n\nLemma body_strcat: semax_body Vprog Gprog f_strcat strcat_spec.\nProof.\nstart_function.\nunfold cstringn, cstring in *.\nrename sd into ld. rename ss into ls.\nIntros.\nforward.\nforward_loop (EX i : Z,\n    PROP (0 <= i < Zlength ld + 1)\n    LOCAL (temp _i (Vint (Int.repr i)); temp _dest dest; temp _src src)\n    SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ [Byte.zero]) ++\n           list_repeat (Z.to_nat (n - (Zlength ld + 1))) Vundef) dest;\n   data_at sh' (tarray tschar (Zlength ls + 1))\n     (map Vbyte (ls ++ [Byte.zero])) src))\n continue: (EX i : Z,\n    PROP (0 <= i < Zlength ld + 1)\n    LOCAL (temp _i (Vint (Int.repr (i-1))); temp _dest dest; temp _src src)\n    SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ [Byte.zero]) ++\n           list_repeat (Z.to_nat (n - (Zlength ld + 1))) Vundef) dest;\n   data_at sh' (tarray tschar (Zlength ls + 1))\n     (map Vbyte (ls ++ [Byte.zero])) src))\n  break: (PROP ( )\n   LOCAL (temp _i (Vint (Int.repr (Zlength ld))); temp _dest dest; \n   temp _src src)\n   SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ [Byte.zero]) ++\n           list_repeat (Z.to_nat (n - (Zlength ld + 1))) Vundef) dest;\n   data_at sh' (tarray tschar (Zlength ls + 1))\n     (map Vbyte (ls ++ [Byte.zero])) src)).\n-\n  Exists 0; entailer!.\n-\n  Intros i.\n  forward.\n  { entailer!. }\n  { entailer!. autorewrite with sublist. normalize.  }\n  autorewrite with sublist; normalize.\n  forward.\n  forward_if.\n  + forward.\n    entailer!. f_equal. f_equal. cstring.\n  +\n    forward.\n    Exists (i+1); entailer!. cstring.\n- Intros i.\n   forward.\n   Exists i. entailer!. \n-\n  abbreviate_semax.\n  forward.\n  forward_loop (EX j : Z,\n    PROP (0 <= j < Zlength ls + 1)\n    LOCAL (temp _j (Vint (Int.repr j)); temp _i (Vint (Int.repr (Zlength ld)));\n           temp _dest dest; temp _src src)\n    SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ sublist 0 j ls) ++\n           list_repeat (Z.to_nat (n - (Zlength ld + j))) Vundef) dest;\n         data_at sh' (tarray tschar (Zlength ls + 1))\n           (map Vbyte (ls ++ [Byte.zero])) src))\n   continue: (EX j : Z,\n    PROP (0 <= j < Zlength ls + 1)\n    LOCAL (temp _j (Vint (Int.repr (j-1))); temp _i (Vint (Int.repr (Zlength ld)));\n           temp _dest dest; temp _src src)\n    SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ sublist 0 j ls) ++\n           list_repeat (Z.to_nat (n - (Zlength ld + j))) Vundef) dest;\n         data_at sh' (tarray tschar (Zlength ls + 1))\n           (map Vbyte (ls ++ [Byte.zero])) src)).\n  { Exists 0; entailer!.  autorewrite with sublist.\n    rewrite !map_app. rewrite <- app_assoc.\n    rewrite split_data_at_app_tschar by list_solve.\n    rewrite (split_data_at_app_tschar _ n) by list_solve.\n    autorewrite with sublist.\n    cancel.    \n   }\n  { Intros j.\n  assert (Zlength (ls ++ [Byte.zero]) = Zlength ls + 1) by (autorewrite with sublist; auto).\n  forward. normalize.\n  forward. fold_Vbyte.\n  forward.\n  entailer!.\n  clear H3.\n  rewrite upd_Znth_app2 by list_solve.\n  autorewrite with sublist.\n  forward_if.\n  + forward.\n      autorewrite with sublist.\n      rewrite prop_true_andp \n        by (intro Hx; apply in_app in Hx; destruct Hx; contradiction).\n      cancel.\n    assert (j = Zlength ls) by cstring; subst.\n    autorewrite with sublist.\n    apply derives_refl'.\n    unfold data_at; f_equal. \n    replace (n - (Zlength ld + Zlength ls))\n     with (1 + (n - (Zlength ld + Zlength ls+1))) by rep_omega.\n    rewrite <- list_repeat_app' by rep_omega.\n    rewrite upd_Znth_app1 by list_solve.\n    rewrite app_assoc.\n    simpl.\n    rewrite !map_app.\n    reflexivity.\n +\n  forward.\n  Exists (j+1).\n  destruct (zlt j (Zlength ls)); [ | cstring].\n  entailer!.\n  change (field_at Tsh (tarray tschar n) []) with (data_at Tsh (tarray tschar n)).\n  rewrite (sublist_split 0 j (j+1)) by rep_omega.\n  rewrite (app_assoc ld). rewrite !map_app.\n  rewrite <- (app_assoc (_ ++ _)).\n  rewrite (split_data_at_app_tschar _ n) by list_solve.\n  rewrite (split_data_at_app_tschar _ n) by list_solve.\n  replace (n - (Zlength ld + j))\n    with (1 + (n - (Zlength ld + (j + 1)))) by rep_omega.\n  rewrite <- list_repeat_app' by rep_omega.\n  cancel.\n  rewrite upd_Znth_app1 by (autorewrite with sublist; rep_omega).\n  rewrite app_Znth1 by list_solve.\n  rewrite sublist_len_1 by rep_omega.\n  cancel.\n  }\n + Intros j. forward. Exists j. entailer!.\nQed.\n\nLemma body_strcmp: semax_body Vprog Gprog f_strcmp strcmp_spec.\nProof.\nstart_function.\nunfold cstring in *.\nrename s1 into ls1. rename s2 into ls2.\nforward.\nIntros.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls1 + 1; 0 <= i < Zlength ls2 + 1;\n        sublist 0 i ls1 = sublist 0 i ls2)\n  LOCAL (temp _str1 str1; temp _str2 str2; temp _i (Vint (Int.repr i)))\n  SEP (data_at sh1 (tarray tschar (Zlength ls1 + 1))\n          (map Vbyte (ls1 ++ [Byte.zero])) str1;\n       data_at sh2 (tarray tschar (Zlength ls2 + 1))\n          (map Vbyte (ls2 ++ [Byte.zero])) str2))\n  continue: (EX i : Z,\n  PROP (0 <= i < Zlength ls1 + 1; 0 <= i < Zlength ls2 + 1;\n        sublist 0 i ls1 = sublist 0 i ls2)\n  LOCAL (temp _str1 str1; temp _str2 str2; temp _i (Vint (Int.repr (i-1))))\n  SEP (data_at sh1 (tarray tschar (Zlength ls1 + 1))\n          (map Vbyte (ls1 ++ [Byte.zero])) str1;\n       data_at sh2 (tarray tschar (Zlength ls2 + 1))\n          (map Vbyte (ls2 ++ [Byte.zero])) str2)).\n- Exists 0; entailer!.\n- Intros i.\n  assert (Zlength (ls1 ++ [Byte.zero]) = Zlength ls1 + 1) by (autorewrite with sublist; auto).\n  forward. normalize.\n  assert (Zlength (ls2 ++ [Byte.zero]) = Zlength ls2 + 1) by (autorewrite with sublist; auto).\n  forward. fold_Vbyte.\n  assert (Znth i (ls1 ++ [Byte.zero]) = Byte.zero <-> i = Zlength ls1) as Hs1.\n  { split; [|intro; subst; rewrite app_Znth2, Zminus_diag by omega; auto].\n    destruct (zlt i (Zlength ls1)); [|omega].\n    intro X; lapply (Znth_In i ls1); [|omega]. cstring. }\n  assert (Znth i (ls2 ++ [Byte.zero]) = Byte.zero <-> i = Zlength ls2) as Hs2.\n  { split; [|intro; subst; rewrite app_Znth2, Zminus_diag by omega; auto].\n    destruct (zlt i (Zlength ls2)); [|omega].\n    intro X; lapply (Znth_In i ls2); [|omega]. cstring. }\n  forward. normalize.\n  forward. fold_Vbyte.\n  forward_if (temp _t'1 (Val.of_bool (Z.eqb i (Zlength ls1) && Z.eqb i (Zlength ls2)))).\n  { forward.\n    simpl force_val.\n    rewrite Hs1 in *.\n    destruct (Byte.eq_dec (Znth i (ls2 ++ [Byte.zero])) Byte.zero).\n    + rewrite e; simpl force_val.\n         assert (i = Zlength ls2) by cstring.\n        rewrite  (proj2 Hs1 H6).\n     rewrite (proj2 (Z.eqb_eq i (Zlength ls1)) H6).\n     rewrite (proj2 (Z.eqb_eq i (Zlength ls2)) H7).\n     entailer!.\n  +\n    rewrite Int.eq_false.\n     rewrite (proj2 (Z.eqb_eq i (Zlength ls1)) H6).\n     rewrite Hs2 in n.\n     rewrite (proj2 (Z.eqb_neq i (Zlength ls2))) by auto.\n    entailer!.\n     contradict n.\n     apply repr_inj_signed in n; try rep_omega. normalize in n.\n }\n  { forward.\n    entailer!.\n    destruct (i =? Zlength ls1) eqn: Heq; auto.\n    rewrite Z.eqb_eq in Heq; tauto. }\n  forward_if.\n +\n  rewrite andb_true_iff in H6; destruct H6.\n  rewrite Z.eqb_eq in H6,H7.\n  forward.\n  Exists (Int.repr 0).\n  entailer!. simpl.\n  autorewrite with sublist in H3.\n  auto.\n +\n  deadvars!.\n  rewrite andb_false_iff in H6. rewrite !Z.eqb_neq in H6.\n  forward_if.\n  *\n    forward. Exists (Int.repr (-1)). entailer!.\n    simpl. intro; subst. omega.\n *\n   forward_if.\n   forward.\n   Exists (Int.repr 1). entailer!. simpl. intro. subst. omega.\n\n   assert (H17: Byte.signed (Znth i (ls1 ++ [Byte.zero])) =\n     Byte.signed (Znth i (ls2 ++ [Byte.zero]))) by omega.\n   normalize in H17. clear H7 H8.\n   forward.\n   Exists (i+1).\n   entailer!.\n   clear H7 H8.\n   clear H13 H14 H12 PNstr1 PNstr2.\n   clear H10 H11 H9.\n   destruct (zlt i (Zlength ls1)).\n  2:{\n         rewrite app_Znth2 in Hs1 by rep_omega.\n         destruct (zeq i (Zlength ls1)); [ | omega].\n         subst.\n         destruct H6; [congruence | ].\n         assert (Zlength ls1 < Zlength ls2) by omega.\n         rewrite app_Znth2 in H17 by rep_omega.\n         rewrite app_Znth1 in H17 by rep_omega.\n         rewrite Z.sub_diag in H17. contradiction H0.\n         change (Znth 0 [Byte.zero]) with Byte.zero in H17. rewrite H17.\n         apply Znth_In. omega.\n   }\n  destruct (zlt i (Zlength ls2)).\n  2:{\n         rewrite app_Znth2 in Hs2 by rep_omega.\n         destruct (zeq i (Zlength ls2)); [ | omega].\n         subst.\n         destruct H6; [ | congruence].\n         assert (Zlength ls1 > Zlength ls2) by omega.\n         rewrite app_Znth1 in H17 by rep_omega.\n         rewrite app_Znth2 in H17 by rep_omega.\n         rewrite Z.sub_diag in H17. contradiction H.\n         change (Znth 0 [Byte.zero]) with Byte.zero in H17. rewrite <- H17.\n         apply Znth_In. omega.\n   }\n  rewrite (sublist_split 0 i (i+1)) by omega.\n  rewrite (sublist_split 0 i (i+1)) by omega.\n  f_equal; auto.\n  rewrite !sublist_len_1 by omega.\n  rewrite !app_Znth1 in H17 by list_solve.\n  split. rep_omega. split. rep_omega.\n  f_equal; auto. f_equal. auto.\n -\n  Intros i.\n  forward.\n  Exists i.\n  entailer!.\nQed.\n\nLemma body_strcpy: semax_body Vprog Gprog f_strcpy strcpy_spec.\nProof.\nstart_function.\nunfold cstring,cstringn in *.\nrename s into ls.\nforward.\nIntros.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1)\n  LOCAL (temp _i (Vint (Int.repr i)); temp _dest dest; temp _src src)\n  SEP (data_at sh (tarray tschar n)\n        (map Vbyte (sublist 0 i ls) ++ list_repeat (Z.to_nat (n - i)) Vundef) dest;\n       data_at sh' (tarray tschar (Zlength ls + 1)) (map Vbyte (ls ++ [Byte.zero])) src))\n continue: (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1)\n  LOCAL (temp _i (Vint (Int.repr (i-1))); temp _dest dest; temp _src src)\n  SEP (data_at sh (tarray tschar n)\n        (map Vbyte (sublist 0 i ls) ++ list_repeat (Z.to_nat (n - i)) Vundef) dest;\n       data_at sh' (tarray tschar (Zlength ls + 1)) (map Vbyte (ls ++ [Byte.zero])) src)).\n*\n Exists 0. rewrite Z.sub_0_r; entailer!. simpl. entailer!.\n*\n Intros i.\n assert (Zlength (ls ++ [Byte.zero]) = Zlength ls + 1) by (autorewrite with sublist; auto).\n forward. normalize.\n forward. fold_Vbyte.\n forward.\n forward_if.\n+ forward.\n   entailer!.\n  assert (i = Zlength ls) by cstring. subst i.\n  change (field_at Tsh (tarray tschar n) []) with (data_at Tsh (tarray tschar n)).\n  rewrite upd_Znth_app2 by list_solve.\n  autorewrite with sublist.\n  rewrite !map_app.\n  rewrite <- app_assoc.\n   rewrite (split_data_at_app_tschar _ n) by list_solve.\n   rewrite (split_data_at_app_tschar _ n) by list_solve.\n   autorewrite with sublist.\n   replace (n - Zlength ls) with (1 + (n - (Zlength ls + 1))) at 2 by list_solve.\n  rewrite <- list_repeat_app' by omega.\n  rewrite upd_Znth_app1 by list_solve.\n  rewrite !split_data_at_app_tschar by list_solve.\n  cancel.\n+\n   assert (i < Zlength ls) by cstring.\n  forward.\n  Exists (i+1). entailer!. \n  autorewrite with sublist.\n  rewrite (sublist_split 0 i (i+1)) by list_solve.\n  rewrite !map_app. rewrite <- app_assoc.\n  autorewrite with sublist.\n  change (field_at Tsh (tarray tschar n) []) with (data_at Tsh (tarray tschar n)).\n  rewrite !(split_data_at_app_tschar _ n) by list_solve.\n  autorewrite with sublist.\n   replace (n - i) with (1 + (n-(i+ 1))) at 2 by list_solve.\n  rewrite <- list_repeat_app' by omega.\n  autorewrite with sublist.\n  cancel.\n  rewrite !split_data_at_app_tschar by list_solve.\n  autorewrite with sublist.\n  rewrite sublist_len_1 by omega.\n  simpl. cancel.\n*\n  Intros i.\n  forward.\n  Exists i.\n  entailer!.\nQed.\n\nModule Alternate.\n\n(* Alternate proofs of these functions, using the form of \"forward_loop\"\n  that relies on semax_loop_nocontinue *)\n\nLemma body_strlen: semax_body Vprog Gprog f_strlen strlen_spec.\nProof.\nstart_function.\nunfold cstring in *.\nrename s into ls.\nIntros.\nforward.\nforward_loop  (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1)\n  LOCAL (temp _str str; temp _i (Vptrofs (Ptrofs.repr i)))\n  SEP (data_at sh (tarray tschar (Zlength ls + 1))\n          (map Vbyte (ls ++ [Byte.zero])) str)).\n*\nExists 0. entailer!.\n*\nIntros i.\nassert (Zlength (ls ++ [Byte.zero]) = Zlength ls + 1) by (autorewrite with sublist; auto).\nforward.\nnormalize.\nforward_if.\nforward.\nentailer!. f_equal. f_equal. cstring.\nforward. (* entailer!.  *)\nExists (i+1).\nentailer!. cstring.\nQed.\n\nLemma body_strchr: semax_body Vprog Gprog f_strchr strchr_spec.\nProof.\nstart_function.\nforward.\nunfold cstring in *.\nrename s into ls.\nIntros.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1; Forall (fun d => d <> c) (sublist 0 i ls))\n  LOCAL (temp _str str; temp _c (Vbyte c); temp _i (Vint (Int.repr i)))\n  SEP (data_at sh (tarray tschar (Zlength ls + 1))\n          (map Vbyte (ls ++ [Byte.zero])) str)).\n  Exists 0; rewrite sublist_nil; entailer!.\n- Intros i. \n  assert (Zlength (ls ++ [Byte.zero]) = Zlength ls + 1) by (autorewrite with sublist; auto).\n  forward. normalize.\n  forward. fold_Vbyte.\n  forward_if (Znth i (ls ++ [Byte.zero]) <> c).\n\n  { forward. simpl.\n    Exists (offset_val i str).\n    entailer!.\n    left. exists i. split3; auto. rewrite app_Znth1; auto. cstring. }\n  { forward.\n    entailer!. }\n  Intros.\n  forward_if. \n  { forward.\n    Exists nullval; rewrite !map_app; entailer!.\n    right. split; auto.\n    assert (i = Zlength ls) by cstring.\n    subst i.\n    autorewrite with sublist in H2; auto. }\n  forward. (* entailer!. *)\n  Exists (i+1); entailer!.\n  assert (i <> Zlength ls) by cstring.\n  split. omega.\n  rewrite (sublist_split 0 i) by rep_omega. rewrite Forall_app. split; auto.\n  rewrite sublist_len_1 by rep_omega. repeat constructor.\n  rewrite app_Znth1 in H4 by rep_omega. auto.\nQed.\n\nLemma body_strcat: semax_body Vprog Gprog f_strcat strcat_spec.\nProof.\nstart_function.\nunfold cstringn, cstring in *.\nrename sd into ld. rename ss into ls.\nIntros.\nforward.\nforward_loop (EX i : Z,\n    PROP (0 <= i < Zlength ld + 1)\n    LOCAL (temp _i (Vint (Int.repr i)); temp _dest dest; temp _src src)\n    SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ [Byte.zero]) ++\n           list_repeat (Z.to_nat (n - (Zlength ld + 1))) Vundef) dest;\n   data_at sh' (tarray tschar (Zlength ls + 1))\n     (map Vbyte (ls ++ [Byte.zero])) src))\n  break: (PROP ( )\n   LOCAL (temp _i (Vint (Int.repr (Zlength ld))); temp _dest dest; \n   temp _src src)\n   SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ [Byte.zero]) ++\n           list_repeat (Z.to_nat (n - (Zlength ld + 1))) Vundef) dest;\n   data_at sh' (tarray tschar (Zlength ls + 1))\n     (map Vbyte (ls ++ [Byte.zero])) src)).\n-\n  Exists 0; entailer!.\n-\n  Intros i.\n  forward.\n  { entailer!. }\n  { entailer!. autorewrite with sublist. normalize.  }\n  autorewrite with sublist; normalize.\n  forward.\n  forward_if (*  (Znth i (ld ++ [Byte.zero]) Byte.zero <> Byte.zero). *)\n  + forward.\n   (*  entailer!. f_equal. f_equal. cstring. *)\n  +\n    forward. entailer!. f_equal. f_equal. cstring. \n  +\n    forward.\n    Exists (i+1); entailer!. cstring.\n-\n  abbreviate_semax.\n  forward.\n  forward_loop (EX j : Z,\n    PROP (0 <= j < Zlength ls + 1)\n    LOCAL (temp _j (Vint (Int.repr j)); temp _i (Vint (Int.repr (Zlength ld)));\n           temp _dest dest; temp _src src)\n    SEP (data_at sh (tarray tschar n)\n          (map Vbyte (ld ++ sublist 0 j ls) ++\n           list_repeat (Z.to_nat (n - (Zlength ld + j))) Vundef) dest;\n         data_at sh' (tarray tschar (Zlength ls + 1))\n           (map Vbyte (ls ++ [Byte.zero])) src)).\n  { Exists 0; entailer!.  autorewrite with sublist.\n    rewrite !map_app. rewrite <- app_assoc.\n    rewrite split_data_at_app_tschar by list_solve.\n    rewrite (split_data_at_app_tschar _ n) by list_solve.\n    autorewrite with sublist.\n    cancel.    \n   }\n  { Intros j.\n  assert (Zlength (ls ++ [Byte.zero]) = Zlength ls + 1) by (autorewrite with sublist; auto).\n  forward. normalize.\n  forward. fold_Vbyte.\n  forward.\n  entailer!.\n  clear H3.\n  rewrite upd_Znth_app2 by list_solve.\n  autorewrite with sublist.\n  forward_if.\n  + forward.\n      autorewrite with sublist.\n      rewrite prop_true_andp \n        by (intro Hx; apply in_app in Hx; destruct Hx; contradiction).\n      cancel.\n    assert (j = Zlength ls) by cstring; subst.\n    autorewrite with sublist.\n    apply derives_refl'.\n    unfold data_at; f_equal. \n    replace (n - (Zlength ld + Zlength ls))\n     with (1 + (n - (Zlength ld + Zlength ls+1))) by rep_omega.\n    rewrite <- list_repeat_app' by rep_omega.\n    rewrite upd_Znth_app1 by list_solve.\n    rewrite app_assoc.\n    simpl.\n    rewrite !map_app.\n    reflexivity.\n +\n  forward. (* entailer!. *)\n  Exists (j+1).\n  destruct (zlt j (Zlength ls)); [ | cstring].\n  entailer!.\n  rewrite (sublist_split 0 j (j+1)) by rep_omega.\n  rewrite (app_assoc ld). rewrite !map_app.\n  rewrite <- (app_assoc (_ ++ _)).\n  rewrite (split_data_at_app_tschar _ n) by list_solve.\n  rewrite (split_data_at_app_tschar _ n) by list_solve.\n  replace (n - (Zlength ld + j))\n    with (1 + (n - (Zlength ld + (j + 1)))) by rep_omega.\n  rewrite <- list_repeat_app' by rep_omega.\n  cancel.\n  rewrite upd_Znth_app1 by (autorewrite with sublist; rep_omega).\n  rewrite app_Znth1 by list_solve.\n  rewrite sublist_len_1 by rep_omega.\n  cancel.\n }\nQed.\n\nLemma body_strcmp: semax_body Vprog Gprog f_strcmp strcmp_spec.\nProof.\nstart_function.\nunfold cstring in *.\nrename s1 into ls1. rename s2 into ls2.\nforward.\nIntros.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls1 + 1; 0 <= i < Zlength ls2 + 1;\n        sublist 0 i ls1 = sublist 0 i ls2)\n  LOCAL (temp _str1 str1; temp _str2 str2; temp _i (Vint (Int.repr i)))\n  SEP (data_at sh1 (tarray tschar (Zlength ls1 + 1))\n          (map Vbyte (ls1 ++ [Byte.zero])) str1;\n       data_at sh2 (tarray tschar (Zlength ls2 + 1))\n          (map Vbyte (ls2 ++ [Byte.zero])) str2)).\n- Exists 0; entailer!.\n- Intros i.\n  assert (Zlength (ls1 ++ [Byte.zero]) = Zlength ls1 + 1) by (autorewrite with sublist; auto).\n  forward. normalize.\n  assert (Zlength (ls2 ++ [Byte.zero]) = Zlength ls2 + 1) by (autorewrite with sublist; auto).\n  forward. fold_Vbyte.\n  assert (Znth i (ls1 ++ [Byte.zero]) = Byte.zero <-> i = Zlength ls1) as Hs1.\n  { split; [|intro; subst; rewrite app_Znth2, Zminus_diag by omega; auto].\n    destruct (zlt i (Zlength ls1)); [|omega].\n    intro X; lapply (Znth_In i ls1); [|omega]. cstring. }\n  assert (Znth i (ls2 ++ [Byte.zero]) = Byte.zero <-> i = Zlength ls2) as Hs2.\n  { split; [|intro; subst; rewrite app_Znth2, Zminus_diag by omega; auto].\n    destruct (zlt i (Zlength ls2)); [|omega].\n    intro X; lapply (Znth_In i ls2); [|omega]. cstring. }\n  forward. normalize.\n  forward. fold_Vbyte.\n  forward_if (temp _t'1 (Val.of_bool (Z.eqb i (Zlength ls1) && Z.eqb i (Zlength ls2)))).\n  { forward.\n    simpl force_val. normalize.\n    rewrite Hs1 in *.\n    destruct (Byte.eq_dec (Znth i (ls2 ++ [Byte.zero])) Byte.zero).\n    + rewrite e; simpl force_val.\n         assert (i = Zlength ls2) by cstring.\n        rewrite  (proj2 Hs1 H6).\n     rewrite (proj2 (Z.eqb_eq i (Zlength ls1)) H6).\n     rewrite (proj2 (Z.eqb_eq i (Zlength ls2)) H7).\n     entailer!.\n  +\n    rewrite Int.eq_false.\n     rewrite (proj2 (Z.eqb_eq i (Zlength ls1)) H6).\n     rewrite Hs2 in n.\n     rewrite (proj2 (Z.eqb_neq i (Zlength ls2))) by auto.\n    entailer!.\n     contradict n.\n     apply repr_inj_signed in n; try rep_omega. normalize in n.\n }\n  { forward.\n    entailer!.\n    destruct (i =? Zlength ls1) eqn: Heq; auto.\n    rewrite Z.eqb_eq in Heq; tauto. }\n  forward_if. \n +\n  rewrite andb_true_iff in H6; destruct H6.\n  rewrite Z.eqb_eq in H6,H7.\n  forward.\n  Exists (Int.repr 0).\n  entailer!. simpl.\n  autorewrite with sublist in H3.\n  auto.\n +\n  rewrite andb_false_iff in H6. rewrite !Z.eqb_neq in H6.\n  forward_if.\n  *\n    forward. Exists (Int.repr (-1)). entailer!.\n    simpl. intro; subst. omega.\n *\n   forward_if.\n   forward.\n   Exists (Int.repr 1). entailer!. simpl. intro. subst. omega.\n\n   assert (H17: Byte.signed (Znth i (ls1 ++ [Byte.zero])) =\n     Byte.signed (Znth i (ls2 ++ [Byte.zero]))) by omega.\n   normalize in H17. clear H7 H8.\n   forward.\n   Exists (i+1).\n   entailer!.\n   clear - H17 H6 Hs1 Hs2 H3 H1 H2 H H0.\n   destruct (zlt i (Zlength ls1)).\n  2:{\n         assert (i = Zlength ls1) by omega. subst.\n         destruct H6; [congruence | ].\n         assert (Zlength ls1 < Zlength ls2) by omega.\n         rewrite app_Znth2 in H17 by rep_omega.\n         rewrite app_Znth1 in H17 by rep_omega.\n         rewrite Z.sub_diag in H17. contradiction H0.\n         change (Znth 0 [Byte.zero]) with Byte.zero in H17.\n         rewrite H17. apply Znth_In. omega.\n   }\n  destruct (zlt i (Zlength ls2)).\n  2:{\n         assert (i = Zlength ls2) by omega. subst.\n         destruct H6; [ | congruence].\n         assert (Zlength ls1 > Zlength ls2) by omega.\n         rewrite app_Znth1 in H17 by rep_omega.\n         rewrite app_Znth2 in H17 by rep_omega.\n         rewrite Z.sub_diag in H17. contradiction H.\n         change (Znth 0 [Byte.zero]) with Byte.zero in H17.\n         rewrite <- H17.  apply Znth_In. omega.\n   }\n  rewrite (sublist_split 0 i (i+1)) by omega.\n  rewrite (sublist_split 0 i (i+1)) by omega.\n  f_equal; auto.\n  rewrite !sublist_len_1 by omega.\n  autorewrite with sublist in H17.\n  split. rep_omega. split. rep_omega.\n  f_equal; auto. f_equal. auto.\nQed.\n\nLemma body_strcpy: semax_body Vprog Gprog f_strcpy strcpy_spec.\nProof.\nstart_function.\nunfold cstring,cstringn in *.\nrename s into ls.\nforward.\nIntros.\nforward_loop (EX i : Z,\n  PROP (0 <= i < Zlength ls + 1)\n  LOCAL (temp _i (Vint (Int.repr i)); temp _dest dest; temp _src src)\n  SEP (data_at sh (tarray tschar n)\n        (map Vbyte (sublist 0 i ls) ++ list_repeat (Z.to_nat (n - i)) Vundef) dest;\n       data_at sh' (tarray tschar (Zlength ls + 1)) (map Vbyte (ls ++ [Byte.zero])) src)).\n*\n Exists 0. rewrite Z.sub_0_r; entailer!. simpl; entailer!.\n*\n Intros i.\n assert (Zlength (ls ++ [Byte.zero]) = Zlength ls + 1) by (autorewrite with sublist; auto).\n forward. normalize.\n forward. fold_Vbyte.\n forward.\n forward_if.\n+ forward.\n   entailer!.\n  assert (i = Zlength ls) by cstring. subst i.\n  autorewrite with sublist.\n  rewrite !map_app.\n  rewrite <- app_assoc.\n   rewrite (split_data_at_app_tschar _ n) by list_solve.\n   rewrite (split_data_at_app_tschar _ n) by list_solve.\n   autorewrite with sublist.\n   replace (n - Zlength ls) with (1 + (n - (Zlength ls + 1))) at 2 by list_solve.\n  rewrite <- list_repeat_app' by omega.\n  autorewrite with sublist.\n  rewrite !split_data_at_app_tschar by list_solve.\n  cancel.\n+\n   assert (i < Zlength ls) by cstring.\n  forward.\n  Exists (i+1). entailer!.\n  rewrite upd_Znth_app2 by list_solve.\n  assert (i < Zlength ls) by cstring.\n  rewrite (sublist_split 0 i (i+1)) by list_solve.\n  rewrite !map_app. rewrite <- app_assoc.\n  autorewrite with sublist.\n  rewrite !(split_data_at_app_tschar _ n) by list_solve.\n  autorewrite with sublist.\n   replace (n - i) with (1 + (n-(i+ 1))) at 2 by list_solve.\n  rewrite <- list_repeat_app' by omega.\n  autorewrite with sublist.\n  cancel.\n  rewrite !split_data_at_app_tschar by list_solve.\n  autorewrite with sublist.\n  rewrite sublist_len_1 by omega.\n  simpl. cancel.\nQed.\n\nEnd Alternate.\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/progs/verif_strlib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2342667705037162}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of CFGV project.\n\n  CFGV is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  CFGV is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with CFGV.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/CFGVLFMTP2014/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\nRequire Export AlphaEqProps.\nRequire Import Omega.\nSet Implicit Arguments.\n\n(* [lVars] is explicitly a function on [vc].\n    the typechecker will then happily export\n    the transport in the [pvleaf] clause of [pRenBinders]. *)\nDefinition lVars {G : CFGV} \n  ( vc  : VarSym G) := list (vType vc).\n  \n(** renames all binding variables\n    to distinct ones that are not \n    in [lvAvoid] *)\nFixpoint pRenBinders {G : CFGV} \n  { vc  : VarSym G}\n  {gs : (GSym G)} \n  (lvAvoid : lVars vc)\n  (p : Pattern gs)\n   {struct p} : Pattern gs  :=\nmatch p in Pattern gs return Pattern gs with\n| ptleaf tc t =>  ptleaf tc t\n| pvleaf vcc var => pvleaf vcc\n                    (match (DeqVarSym vc vcc) with\n                    | left eqq => (vFreshVar (transport eqq lvAvoid) var)\n                    | right _ => var\n                    end) \n| pnode p mix => pnode p (mRenBinders lvAvoid mix)\n| embed p t => embed p t\nend\nwith mRenBinders {G : CFGV} \n  { vc  : VarSym G}\n  {lgs : list (bool * GSym G)} \n  (lvAvoid : list (vType vc))\n   (pts : Mixture lgs)\n   {struct pts} : Mixture lgs  := \nmatch pts with\n| mnil => mnil\n| mtcons _ _ ph ptl =>  mtcons ph (mRenBinders lvAvoid ptl)\n| mpcons _ _ ph ptl => let phr := (pRenBinders lvAvoid ph) in\n                       let phrb := pBndngVars vc phr in\n                       mpcons phr  \n                              (mRenBinders (lvAvoid ++ phrb) ptl)\nend.\n\n\nLemma RenBindersSpec : forall {G : CFGV} (vc  : VarSym G), \n(   forall (s : GSym G) (nt : Term s), True)\n*\n(   forall (s : GSym G) (pt : Pattern s)  (lvAvoid : lVars vc),\n    let ptr := (pRenBinders lvAvoid pt) in\n    no_repeats (pBndngVars vc ptr)\n    # disjoint (pBndngVars vc ptr) lvAvoid\n)\n*\n(   forall (l : list (bool # GSym G)) (m : Mixture l)\n    (lvAvoid : lVars vc),\n    let mr := (mRenBinders lvAvoid m) in\n    no_repeats (mBndngVars vc mr)\n    # disjoint (mBndngVars vc mr) lvAvoid\n).\nProof. \n intros. GInduction; cpx;[|].\n- Case \"pvleaf\".  allsimpl. intros.\n  dands; rewrite DeqSym; ddeq; subst; \n  allsimpl; try constructor; cpx.\n  repeat (disjoint_reasoning).\n  apply vFreshVarSpec.\n\n- Case \"mpcons\".\n  introns Hyp.\n  allsimpl. intros.\n  specialize (Hyp0 (lvAvoid ++ (pBndngVars vc (pRenBinders lvAvoid ph)))).\n  specialize (Hyp lvAvoid ).\n  allrw no_repeats_app.\n  repnd; dands;cpx; repeat (disjoint_reasoning); cpx.\nQed.\n\n\nLemma RenBindersSpec2 : forall {G : CFGV} (vc  : VarSym G),  \n(   forall (s : GSym G) (nt : Term s), True)\n*\n(   forall (s : GSym G) (pt : Pattern s)  (lvAvoid : lVars vc),\n    pAlreadyBndBinders vc pt\n      = pAlreadyBndBinders vc (pRenBinders lvAvoid pt)\n)\n*\n(   forall (l : list (bool # GSym G)) (m : Mixture l)\n    (lvAvoid : lVars vc),\n    mAlreadyBndBinders vc m\n      = mAlreadyBndBinders vc (mRenBinders lvAvoid m)\n).\nProof.\n  intros; GInduction; allsimpl; cpx;[|]; intros; f_equal; cpx.\nQed.\n\nLemma RenBindersSpec3 : forall {G : CFGV} (vc  : VarSym G),  \n(   forall (s : GSym G) (nt : Term s), True)\n*\n(   forall (s : GSym G) (pt : Pattern s)  (lvAvoid : lVars vc),\n    pAllButBinders vc pt\n      = pAllButBinders vc (pRenBinders lvAvoid pt)\n)\n*\n(   forall (l : list (bool # GSym G)) (m : Mixture l)\n    (lvAvoid : lVars vc),\n    mAllButBinders vc m\n      = mAllButBinders vc (mRenBinders lvAvoid m)\n).\nProof.\n  intros; GInduction; allsimpl; cpx;\n      [|]; intros; f_equal; cpx.\nQed.\n\n(*\nFixpoint mSwapTermEmbed\n       {G  : CFGV}\n       {vc : VarSym G}\n       {lgs : list (bool * GSym G)}\n       (pts : Mixture lgs)\n       (sw : list (Swapping vc))\n       {struct pts}\n     : Mixture lgs  :=\nmatch pts with\n| mnil => mnil\n| mtcons _ _ th ttl => \n    mtcons (tSwap th (lhead sw))\n           (mSwapTermEmbed ttl (tail sw))\n| mpcons _ _ ph ptl => \n    mpcons (pSwapEmbed ph  (lhead sw))\n           (mSwapTermEmbed ptl  (tail sw))\nend.\n*)\n\nFixpoint mLSwapTermEmbed\n       {G  : CFGV}\n       {vc : VarSym G}\n       {lgs : list (bool * GSym G)}\n       (pts : Mixture lgs)\n       (llbvOld llbvNew : list (lVars vc))\n       {struct pts}\n     : Mixture lgs  :=\nmatch pts with\n| mnil => mnil\n| mtcons _ _ th ttl => \n    mtcons (tSwap th (combine (lhead llbvOld) (lhead llbvNew)))\n           (mLSwapTermEmbed ttl (tail llbvOld) (tail llbvNew))\n| mpcons _ _ ph ptl => \n    mpcons (pSwapEmbed ph (combine (lhead llbvOld) (lhead llbvNew)))\n           (mLSwapTermEmbed ptl (tail llbvOld) (tail llbvNew))\nend.\n\nDefinition nodeRenAlphaAux \n   {G : CFGV} {vc : VarSym G}\n   {mp : MixtureParam}\n   (lln : list (list nat))\n   (rmix : Mixture mp)\n   (lvAvoid : list (vType vc))\n  : Mixture mp :=\n\n  if (decDisjointV vc (mBndngVars vc rmix) lvAvoid)\n  then\n    rmix\n  else\n    let llbvOld := lBoundVars vc lln rmix in\n    let rmixPR := mRenBinders (lvAvoid ++ (mAllVars rmix)) rmix in\n    let llbvNew := lBoundVars vc lln rmixPR in\n    mLSwapTermEmbed rmixPR llbvOld llbvNew.\n\n\nFixpoint tRenAlpha {G : CFGV} {vc : VarSym G}\n  {gs : (GSym G)} (pt : Term gs) \n   (lvAvoid : list (vType vc))\n   {struct pt} :  Term gs :=\nmatch pt in Term gs return Term gs with\n| tleaf a b => tleaf a b \n| vleaf vcc var => vleaf vcc var\n| tnode p mix => tnode p \n      ( let rmix := mRenAlpha mix lvAvoid in\n        nodeRenAlphaAux (bndngPatIndices p) rmix lvAvoid\n        )\nend\n\nwith pRenAlpha {G : CFGV} {vc : VarSym G}\n  {gs : (GSym G)} (pt : Pattern gs)\n  (lvAvoid : list (vType vc)) {struct pt} : Pattern gs  :=\nmatch pt with\n| ptleaf a v => ptleaf a v\n| pvleaf vcc var => pvleaf vcc var\n| pnode p lpt => pnode p (mRenAlpha lpt lvAvoid)\n| embed p nt => embed p (tRenAlpha nt lvAvoid)\nend\n\nwith mRenAlpha {G : CFGV} {vc : VarSym G}\n  {lgs : list (bool * GSym G)} (pts : Mixture lgs)\n  (lvAvoid : list (vType vc))\n {struct pts}\n      : Mixture lgs  := \nmatch pts in Mixture lgs return Mixture lgs with\n| mnil  => mnil\n| mtcons _ _ th ttl => \n        mtcons (tRenAlpha th lvAvoid)\n               (mRenAlpha ttl lvAvoid)\n| mpcons _ _ ph ptl =>\n        mpcons  (pRenAlpha ph lvAvoid)\n                (mRenAlpha ptl lvAvoid)\nend.\n\n\nDefinition AvRenaming {G : CFGV} {vc : VarSym G}\n(lvA : list (vType vc)) (sw : Swapping vc)\n:= no_repeats (ALRange sw)\n    # disjoint (ALDom sw) (ALRange sw) \n    # disjoint (ALRange sw) lvA .\n\nLemma AvRenamingSubset : forall\n   {G : CFGV} {vc : VarSym G}\n(lvl lvr : list (vType vc)) \n(sw : Swapping vc),\nsubset lvr lvl\n-> AvRenaming lvl sw\n-> AvRenaming lvr sw.\nProof.\n  unfold AvRenaming.\n  introv Hs Hav. repnd.\n  dands; cpx.\n  SetReasoning.\nQed.\n\n\n\nLemma ndRenAlAxSpecDisjAux : forall\n   {G : CFGV} {vc : VarSym G}\n   {mp : MixtureParam}\n   (pts : Mixture mp)\n  (llbvOld llbvNew : list (lVars vc))\n  (lvA : list (vType vc)),\n  disjoint (mAlreadyBndBinders vc pts) lvA\n  -> lForall no_repeats llbvNew\n  -> disjoint (flatten llbvNew) (lvA ++ \n          mAllButBinders vc pts ++ flatten llbvOld)\n  -> map (@length _) llbvOld =  map (@length _) llbvNew\n  -> length llbvOld = length mp\n  -> disjoint (mAlreadyBndBinders vc pts ++ mBndngVars vc pts) lvA\n  -> disjoint (mBndngVarsDeep vc (mLSwapTermEmbed pts llbvOld llbvNew)) \n             lvA.\nProof.\n  induction pts; cpx;[|].\n- introv H1a H2a H3a H4a H5a H6a.\n  applydup map_eq_length_eq in H4a.\n  allsimpl. dlist_len llbvOld. allsimpl.\n  dlist_len llbvNew. allsimpl.\n  inverts H4a.\n  allrw no_repeats_app.\n  repeat (disjoint_reasoning).\n  + GC. \n    apply tSwapBndngVarsDisjoint; cpx;\n    repeat(disjoint_reasoning).\n  + allsimpl. exrepnd.\n    apply IHpts; cpx; repeat(disjoint_reasoning).\n\n- introv H1a H2a H3a H4a H5a H6a.\n  applydup map_eq_length_eq in H4a.\n  allsimpl. dlist_len llbvOld. allsimpl.\n  dlist_len llbvNew. allsimpl.\n  inverts H4a.\n  allrw no_repeats_app.\n  repeat (disjoint_reasoning).\n  + GC. apply disjoint_sym.\n    apply (pcase SwapEmbedSpec); cpx;\n    autorewrite with fast; try congruence;\n     cpx;  repeat (disjoint_reasoning).\n  + allsimpl. exrepnd.\n    apply IHpts; cpx; repeat(disjoint_reasoning).\nQed.\n\n\nLemma mRenBindersSpec3 : forall\n  {G : CFGV} {vc  : VarSym G}\n   {mp : MixtureParam}\n   (pts : Mixture mp)\n   (lln : list (list nat))\n   (lvAvoid : list (vType vc)),\n   validBsl (length mp) lln \n  -> \nlForall no_repeats\n  (lBoundVars vc lln (mRenBinders (lvAvoid) pts)).\nProof.\n  intros.\n  pose proof  ((mcase (RenBindersSpec vc)) _ pts lvAvoid)  as Hs.\n  simpl in Hs.\n  repnd. \n  rewrite mBndngVarsAsNth in Hs0. clear Hs. \n  rw (@lForallSame (list (vType vc))).\n  unfold lBoundVars.\n  introv Hin.\n  apply in_map_iff in Hin.\n  exrepnd. subst. rename a0 into ln.\n  apply X in Hin1.\n  repnud Hin1.\n  induction ln; cpx.\n  allrw no_repeats_cons.\n  allsimpl. repnd.\n  apply IHln in Hin2; cpx;[].\n  clear IHln.\n  allrw no_repeats_app.\n  dands;cpx.\n  - apply  no_rep_flat_map_seq1 with (n:=0) (len := length mp); sp.\n    apply LInSeqIff; dands; omega.\n  - intros. introv Hin Hinc.\n    apply lin_flat_map in Hinc.\n    exrepnd.\n    destruct (deq_nat x a); subst; cpx.\n    (* for diff indices, they are disjoint *)\n    eapply no_rep_flat_map_seq2 in n; eauto.\n    + disjoint_lin_contra.\n    + rw (@lForallSame nat) in Hin1.\n      apply Hin1 in Hinc1.\n      apply LInSeqIff; dands; omega.\n    + apply LInSeqIff; dands; omega.\nQed.\n\nTheorem renBindersSameLength: forall\n{G : CFGV} {vc : VarSym G},\n(   forall (s : GSym G) (nt : Term s), True)\n*\n(   forall (s : GSym G) (pt : Pattern s) (lvA : lVars vc),\n    length (pBndngVars vc pt) \n      = length (pBndngVars  vc (pRenBinders lvA pt))\n)\n*\n(   forall (l : list (bool # GSym G)) (m : Mixture l) \n    (lvA : lVars vc)\n    (nn : nat),\n    length (getBVarsNth vc m nn) = \n        length (getBVarsNth vc (mRenBinders lvA m) nn)\n).\nProof.\n  intros.\n GInduction; allsimpl; introns Hyp; intros; cpx;\n[ | | | ].\n  - Case \"pvleaf\". rewrite DeqSym.\n    symmetry. rewrite DeqSym.\n    ddeq; subst; sp.\n\n  - Case \"pnode\".\n    simpl. simpl pBndngVars.\n    rewrite mBndngVarsAsNth.\n    rewrite mBndngVarsAsNth.\n    rewrite len_flat_map.\n    rewrite len_flat_map.\n    f_equal.\n    apply eq_maps.\n    cpx.\n  - simpl. destruct nn; cpx.\n  - simpl. destruct nn; cpx.\nQed.\n\nLemma renBindersLBVLenSame :\nforall {G : CFGV} {vc : VarSym G}\n(l : list (bool # GSym G)) (pts : Mixture l) \n    (lvA : lVars vc)\n    (lln : list (list nat)),\nmap (@length _) (lBoundVars vc lln pts) =\nmap (@length _) (lBoundVars vc lln (mRenBinders lvA pts)).\nProof.\n  intros.\n  apply lBoundVarsLenSameifNth.\n  pose proof (@renBindersSameLength G vc).\n  dands; cpx.\nQed.\n\nHint Resolve (fun G vc => mcase (@ bindersAllvarsSubset G vc)) \n lBoundVarsmBndngVars :\n  SetReasoning.\n\n\n\n\n\n\nLemma ndRenAlAxSpecDisj : forall \n  {G : CFGV} {vc  : VarSym G}\n   {mp : MixtureParam}\n   (pts : Mixture mp)\n   (lln : list (list nat))\n   (lvAvoid : list (vType vc)),\n   validBsl (length mp) lln \n  -> length lln = length mp\n  -> disjoint (mAlreadyBndBinders vc pts) lvAvoid\n  -> disjoint (mBndngVarsDeep vc (nodeRenAlphaAux lln pts lvAvoid)) \n             lvAvoid.\nProof.\n  introv Hnr Hlen Hdis.\n  unfold nodeRenAlphaAux.\n  cases_ifd Hdddd; cpx;\n    [ apply disjointDeepShallowPlusAlready; \n      repeat (disjoint_reasoning) |].\n  pose proof ((mcase (RenBindersSpec vc)) _ pts (lvAvoid ++ mAllVars pts))  as Hs.\n  simpl in Hs. exrepnd.\n  apply ndRenAlAxSpecDisjAux; \n  try rewrite <- (mcase (RenBindersSpec2 vc));\n  try rewrite <- (mcase (RenBindersSpec3 vc)); cpx.\n  - apply mRenBindersSpec3; cpx.\n  - eapply subset_disjointLR; eauto.\n    + apply lBoundVarsmBndngVars.\n    + apply subset_app_lr; eauto;[].\n      apply subset_app. dands;\n      eauto 2 with SetReasoning.\n  - apply renBindersLBVLenSame.\n  - unfold lBoundVars.\n    autorewrite with fast. trivial.\n  - repeat (disjoint_reasoning).\nQed.\n\n\n\n\n\nLemma RenAlphaAvoid : forall {G : CFGV} {vc  : VarSym G},\n(  (forall (s : GSym G) (ta : Term s)\n  (lvA : list (vType vc)),\n      disjoint (tBndngVarsDeep vc (tRenAlpha ta lvA)) lvA)\n   *\n  (forall (s : GSym G) (pta : Pattern s)\n  (lvA : list (vType vc)),\n      disjoint (pAlreadyBndBinders vc (pRenAlpha pta lvA)) lvA)\n\n   *\n  (forall (l : MixtureParam) (ma: Mixture l) \n  (lvA : list (vType vc)),\n      disjoint (mAlreadyBndBinders vc (mRenAlpha ma lvA)) lvA)).\nProof.\nintros. GInduction; intros; cpx; \n  try (allsimpl; repeat (disjoint_reasoning); cpx; fail);[].\n  Case \"tnode\".\n  allsimpl. \n  specialize (H lvA).\n  remember (mRenAlpha m lvA) as pts.\n  apply ndRenAlAxSpecDisj; auto.\n  - rewrite length_pRhsAugIsPat.\n    apply bndngPatIndicesValid2; auto.\n    \n  - unfold bndngPatIndices.\n    unfold tpRhsAugIsPat. unfold prhsIsBound.\n    rw combine_length.\n    unfold tpRhsSym. simpl.\n    autorewrite with fast.\n    rw min_eq; auto.\nQed.\n\n\nTheorem lbShallowNoChange: forall \n  {G : CFGV} {vc : VarSym G},\n(   forall (s : GSym G) (nt : Term s), True)\n*\n(   forall (s : GSym G) (pt : Pattern s) \n    (lvA : list (vType vc)),\n    pBndngVars vc pt = pBndngVars  vc (pRenAlpha pt lvA)\n)\n*\n(   forall (l : list (bool # GSym G)) (m : Mixture l) \n    (lvA : list (vType vc))\n    (nn : nat),\n    getBVarsNth vc m nn = @getBVarsNth \n                            _ vc _ (mRenAlpha m lvA) nn\n).\n intros. \n  GInduction; allsimpl; introns Hyp; intros; cpx;[ | | ].\n  - Case \"pnode\". simpl. simpl pBndngVars. \n    rewrite mBndngVarsAsNth.\n    rewrite mBndngVarsAsNth.\n    autorewrite with fast.\n    apply eq_flat_maps.\n    intros nn Hin. cpx.\n  - simpl. destruct nn; cpx.\n  - simpl. destruct nn; cpx.\nQed.\n\nLemma  mRenlBinderShallowSame : forall\n  {G : CFGV} {vc : VarSym G}\n (l : MixtureParam) (m : Mixture l)\n (lvA : list (vType vc))\n  (la : list (list nat)),\nlBoundVars vc la m =  lBoundVars vc la (mRenAlpha m lvA).\nProof.\n  intros. apply lBoundVarsSameifNth.\n  apply (mcase lbShallowNoChange).\nQed.\n\nLemma  mBndngVarsShallowSame : forall\n  {G : CFGV} {vc : VarSym G}\n (l : MixtureParam) (m : Mixture l)\n (lvA : list (vType vc)),\n  mBndngVars vc m =  mBndngVars vc (mRenAlpha m lvA).\nProof.\n  intros. apply mBndngVarsSameIfNth.\n  apply (mcase lbShallowNoChange).\nQed.\n\n\nLemma mLSwapTermEmbedSameBinders : forall\n   {G : CFGV} {vc : VarSym G}\n   {mp : MixtureParam}\n   (m : Mixture mp)\n   (lla llb : list (list (vType vc))),\n(mBndngVars vc (mLSwapTermEmbed m lla llb))\n  = mBndngVars vc m.\nProof.\n  induction m; cpx;[].\n  simpl. intros.\n  f_equal; cpx;[].\n  symmetry.\n  apply (pcase SwapEmbedSameBinders).\nQed.\n\nLemma mLSwapTermEmbedSameNthBinder : forall\n   {G : CFGV} {vc : VarSym G}\n   {mp : MixtureParam}\n   (m : Mixture mp)\n   (lla llb : list (list (vType vc)))\n   (nn : nat),\n    getBVarsNth vc m nn = getBVarsNth \n                             vc (mLSwapTermEmbed m lla llb) nn.\nProof.\n  induction m; cpx; intros ; destruct nn; allsimpl; cpx.\n  apply (pcase SwapEmbedSameBinders).\nQed.\n\n\nLemma pRenBindersAlpha : forall {G : CFGV} {vc : VarSym G},\n(  (forall (s : GSym G) (ta : Term s), True)\n   *\n  (forall (s : GSym G) (pta : Pattern s)\n  (lvA : list (vType vc)),\n      pAlphaEq vc pta (pRenBinders lvA pta))\n   *\n  (forall (mp : MixtureParam) (ma: Mixture mp)\n  (llbv : list (list (vType vc)))\n  (lvA : list (vType vc)),\n  (forall b s, LIn (b,s) mp -> b= true)\n  -> let maR := mRenBinders lvA ma in\n    lAlphaEqAbs (MakeAbstractions vc ma llbv) \n                (MakeAbstractions vc maR llbv))).\nProof.\nintros. \nGInduction; cpx; allsimpl;\n  try (econstructor; eauto with Alpha; fail).\n- Case \"pnode\". introns Hyp.\n  allsimpl. constructor.\n  unfold MakeAbstractionsPNode.  \n  apply Hyp.\n  introv Hin.\n  apply in_map_iff in Hin; exrepnd; cpx.\nQed.\n\n\nLemma mLSwapTermEmbedSameLBV : forall\n   {G : CFGV} {vc : VarSym G}\n   {mp : MixtureParam}\n   (m : Mixture mp)\n   (lla llb : list (list (vType vc)))\n   (lln : list (list nat)),\n    lBoundVars vc lln m = lBoundVars\n                             vc  lln (mLSwapTermEmbed m lla llb).\nProof.\n  intros.\n  apply lBoundVarsSameifNth.\n  apply mLSwapTermEmbedSameNthBinder.\nQed.\n  \n\nDefinition swapEmbedAbs {G : CFGV} {vc : VarSym G}\n           (a : Abstraction G vc)\n           (sw : Swapping vc)\n    : (Abstraction G vc):=\nmatch a with\n| termAbs _ lbv t =>  termAbs _ lbv t\n| patAbs _ lbv t => patAbs _ lbv (pSwapEmbed t sw)\nend.\n\nDefinition swapEmbedLAbs {G : CFGV} {vc : VarSym G}\n           (la : list (Abstraction G vc))\n           (sw : Swapping vc)\n    : list (Abstraction G vc):=\nmap (fun x => swapEmbedAbs x sw) la.\n\nLemma MakeLAbsSwapCommute:\nforall {G : CFGV} {vc : VarSym G} (mp : MixtureParam) \n  (sw : Swapping vc) (m : Mixture mp)\n  (lbv : list (lVars vc)),\nswapEmbedLAbs (MakeAbstractions vc m lbv) sw =\nMakeAbstractions vc (mSwapEmbed m sw) lbv.\nProof.\n  unfold swapEmbedLAbs.\n  intros G vc np sw m.\n  induction m;  intros; allsimpl; cpx; f_equal; cpx;\n   destruct lbv; allsimpl; cpx.\nQed.\n\n\n\nLemma ndRenAlAxAlpha : forall\n   {G : CFGV} {vc : VarSym G}\n   {mp : MixtureParam}\n   (m : Mixture mp)\n   (lln : list (list nat))\n   (lvA : list (vType vc)),\n   validBsl (length mp) lln \n  -> \nlAlphaEqAbs (MakeAbstractionsTNodeAux vc lln m)\n  (MakeAbstractionsTNodeAux vc lln (nodeRenAlphaAux lln m lvA)).\nProof.\n  unfold MakeAbstractionsTNodeAux.\n  introv Hv.\n  unfold nodeRenAlphaAux.\n  cases_ifd Hdddd; cpx; eauto with Alpha;[]; clear Hddddf.\n  rewrite <- mLSwapTermEmbedSameLBV.\n  pose proof (renBindersLBVLenSame m (lvA ++ mAllVars m) lln) as Hlen.\n  pose proof (@mRenBindersSpec3 G vc \n      mp m lln (lvA ++ mAllVars m)) as Hnr.\n  apply Hnr in Hv.\n  clear Hnr.\n  pose proof \n    ((mcase (RenBindersSpec vc)) _ \n      m (lvA ++ mAllVars m))  as Hd.\n  simpl in Hd.\n  repnd. clear Hd0.\n  assert (\n      disjoint \n        (flatten (lBoundVars vc lln \n          (mRenBinders (lvA ++ mAllVars m) m)))\n       (lvA ++ (flatten (lBoundVars vc lln m)))\n    ) as Hld by\n    (apply (subset_disjointLR Hd); auto;\n    [ eauto with SetReasoning |\n    apply subset_app_lr; eauto 2 with SetReasoning]).\n    \n  assert (\n      disjoint \n        (flatten (lBoundVars vc lln \n          (mRenBinders (lvA ++ mAllVars m) m)))\n       (lvA ++ (mAllVars m))\n    ) as Had by\n    (apply (subset_disjointLR Hd); eauto with SetReasoning).\n\n    clear Hd.\n  repeat disjoint_reasoning.\n  clear Had0 Hld0.\n  remember (lBoundVars vc lln m) as lbva.\n  remember (lBoundVars vc lln \n    (mRenBinders (lvA ++ mAllVars m) m)) as lbvb.\n  applydup map_eq_length_eq in Hlen.\n  clear Heqlbvb.\n  clear Heqlbva.\n  remember (lvA ++ mAllVars m) as lv.\n  clear Heqlv.\n  revert lv.\n  generalize dependent lbvb.\n  generalize dependent lbva.\n  clear lln lvA.\n  induction m as [ | ? ? ph ptl Hind| ? ? ph ptl Hind]; cpx.\n- allsimpl. intros. constructor; cpx.\n  + destruct lbva as [|la lvba]; allsimpl; \n    destruct lbvb as [|lb lbvv];\n    inverts Hlen0;\n    autorewrite with fast; simpl;\n    [apply AlphaEqNilAbsT; eauto with Alpha; fail|].\n    pose proof (GFreshDistRenWSpec vc la\n                (tAllVars ph++\n                (tAllVars (tSwap ph (combine la lb)))\n                    ++ la ++lb)) as Hfr.\n    exrepnd.\n    allsimpl. inverts Hlen.\n    apply alAbT with (lbnew:=lvn); try congruence;\n    repeat (disjoint_reasoning);\n    [unfolds_base; simpl; dands; cpx;\n    autorewrite with fast;\n    repeat(disjoint_reasoning); fail |].\n\n    rewrite (tcase swap_app).\n    autorewrite with slow; try congruence;\n    cpx; repeat (disjoint_reasoning);\n    eauto with Alpha.\n\n  + apply Hind; destruct lbva; destruct lbvb;\n    allsimpl; repeat (disjoint_reasoning);\n    inverts Hlen0; inverts Hlen; cpx.\n\n- allsimpl. intros. constructor; cpx.\n  + eapply alphaEqTransitive.\n    instantiate (1 :=\n    (patAbs vc (lhead lbvb)\n       (pSwap ph\n        (combine (lhead lbva) (lhead lbvb))))\n   ).\n\n\n   *  destruct lbva as [|la lvba]; allsimpl; \n      destruct lbvb as [|lb lbvv];\n      inverts Hlen0;\n      autorewrite with fast; simpl;\n      [apply AlphaEqNilAbsP; eauto with Alpha; fail|].\n      pose proof (GFreshDistRenWSpec vc la\n                  (pAllVars ph++\n                  (pAllVars (pSwap ph (combine la lb)))\n                      ++ la ++lb)) as Hfr.\n      exrepnd.\n      allsimpl. inverts Hlen.\n      apply alAbP with (lbnew:=lvn); try congruence;\n      repeat (disjoint_reasoning);\n      [unfolds_base; simpl; dands; cpx;\n      autorewrite with fast;\n      repeat(disjoint_reasoning) |].\n   \n      rewrite (pcase swap_app).\n      autorewrite with slow; try congruence;\n      cpx; repeat (disjoint_reasoning);\n      eauto with Alpha.\n\n   * apply AlphaEqNilAbsP.\n     apply alphaEqSym.\n  eapply alphaEqTransitive.\n    instantiate (1 :=\n        (pSwap (pRenBinders lv ph) \n            (combine (lhead lbva) (lhead lbvb))) \n   ).\n     apply  (pcase (@pAlphaSwapEmSwap G vc)).\n     apply alphaEqSym.\n     apply alphaEquiVariant.\n     apply pRenBindersAlpha.\n  + apply Hind; destruct lbva; destruct lbvb;\n    allsimpl; repeat (disjoint_reasoning);\n    inverts Hlen0; inverts Hlen; cpx.\nQed.\n\n\n\n\nLemma RenAlphaAlpha : forall {G : CFGV} {vc : VarSym G},\n(  (forall (s : GSym G) (ta : Term s)\n  (lvA : list (vType vc)),\n      tAlphaEq vc ta (tRenAlpha ta lvA))\n   *\n  (forall (s : GSym G) (pta : Pattern s)\n  (lvA : list (vType vc)),\n      pAlphaEq vc pta (pRenAlpha pta lvA))\n   *\n  (forall (l : MixtureParam) (ma: Mixture l)\n  (llbv : list (list (vType vc)))\n  (lvA : list (vType vc)),\n  let maR := mRenAlpha ma lvA in\n    lAlphaEqAbs (MakeAbstractions vc ma llbv) \n                (MakeAbstractions vc maR llbv))).\nProof.\nintros. GInduction; intros; cpx; \n  try (econstructor; eauto; fail);[| |].\n\n- Case \"tnode\".\n  allsimpl.\n  constructor.\n  unfold MakeAbstractionsTNode.\n  unfold nodeRenAlphaAux.\n  \n  eapply (alphaEqTransitive);\n  [ |apply ndRenAlAxAlpha with (lvA0 := lvA); eauto].\n  unfold MakeAbstractionsTNodeAux.\n  rw <- (@mRenlBinderShallowSame G vc).\n  apply X; cpx.\n  unfold tpRhsAugIsPat. unfold prhsIsBound.\n  rw combine_length.\n  unfold tpRhsSym.\n  autorewrite with fast.\n  rw min_eq; auto.\n  apply bndngPatIndicesValid2; auto.\n- Case \"mtcons\".\n  subst maR.\n  allunfold MakeAbstractionsTNodeAux.\n  simpl. constructor; cpx.\n  apply AlphaEqNilAbsT; cpx.\n\n- Case \"mpcons\".\n  subst maR.\n  allunfold MakeAbstractionsTNodeAux.\n  simpl. constructor; cpx.\n  apply AlphaEqNilAbsP; cpx.\n\nQed.\n\nLtac addRenSpec :=\nmatch goal with\n[ |- context [@tRenAlpha ?G ?vc ?gs ?a ?lv] ]\n  =>  let Hala := fresh \"Hal\" a in \n      let Hdis := fresh \"Hdis\" a in \n      pose proof ((tcase (@RenAlphaAlpha G vc))\n              gs a lv) as Hala;\n      pose proof ((tcase (@RenAlphaAvoid G vc))\n              gs a lv) as Hdisa\nend.\n\nLemma RenAlphaNoChange : forall {G : CFGV} {vc : VarSym G},\n(  (forall (s : GSym G) (ta : Term s)\n  (lvA : list (vType vc)),\n    disjoint (tBndngVarsDeep vc ta) lvA \n      -> ta = (tRenAlpha ta lvA))\n   *\n  (forall (s : GSym G) (pta : Pattern s)\n  (lvA : list (vType vc)),\n    disjoint (pBndngVarsDeep vc pta) lvA \n      -> pta = (pRenAlpha pta lvA))\n   *\n  (forall (l : MixtureParam) (ma: Mixture l)\n  (lvA : list (vType vc)),\n    disjoint (mBndngVarsDeep vc ma) lvA \n    -> ma = mRenAlpha ma lvA)).\nProof.\n  intros.\n  GInduction; introns Hyp; allsimpl; \n  try (f_equal; cpx; fail);[ | | ].\n\n- Case \"tnode\". f_equal.\n  unfolds_base.\n  cases_ifd Hdd; cpx.\n  rewrite <- mBndngVarsShallowSame in Hddf.\n  provefalse. apply Hddf.\n  SetReasoning.\n\n- Case \"mtcons\". allsimpl. repeat (disjoint_reasoning).\n  f_equal; cpx.\n\n- Case \"mpcons\". allsimpl. repeat (disjoint_reasoning).\n  f_equal; cpx.\nQed.\n\nLemma tRenWithSpec :\n  forall  {G : CFGV} {vc : VarSym G}\n     (s : GSym G) (ta : Term s)\n     (lvA : list (vType vc)),\n  {tar : Term s $ tAlphaEq vc ta tar #\n          disjoint (tBndngVarsDeep vc tar) lvA}.\nProof.\n  intros.\n  exists (tRenAlpha ta lvA).\n  pose proof (@RenAlphaAlpha G vc).\n  pose proof (@RenAlphaAvoid G vc).\n  repnd.\n  dands; cpx.\nQed.\n\n(* only comments below *)\n\n(*\nLemma AllVarsEquivariant :\n  forall {G : CFGV} {vc : VarSym G}\n  (sw : Swapping vc),\n    (forall (gs : GSym G) (t : Term gs), True)\n    *\n    (forall (gs : GSym G),\n    EquiVariantFn (@pSwap _ vc gs)\n                  (@pSwap _ vc gs)\n                  (fun t => pSwapEmbed t sw))\n    *\n    (forall (lgs : list (bool * GSym G)),\n     EquiVariantFn (@mSwap _ vc lgs)\n                (@mSwap _ vc lgs)\n                (fun t => mSwapEmbed t sw)).\nProof.\n  intros.\n  GInduction; auto; introns Hyp; intros; allsimpl ; auto.\n\n- Case \"pembed\". f_equal.\n  \nsimpl. rewrite DeqSym. symmetry. rewrite DeqSym.\n  destruct_head_match; try subst;  cpx.\n\n- simpl. rewrite DeqSym. symmetry. rewrite DeqSym.\n  destruct_head_match; try subst;  cpx.\n\n- unfold swapLVar. rw map_app.\n  unfold swapLVar in Hyp0. \n  unfold swapLVar in Hyp. \n  f_equal; cpx.\n\n- unfold swapLVar. rw map_app.\n  unfold swapLVar in Hyp0. \n  unfold swapLVar in Hyp. \n  f_equal; cpx.\nQed.\n*)\n\n(*\nLemma swapDisjChain : forall  {G : CFGV} {vc : VarSym G}\n  (vsa vs vsb : lVars vc),\n    length vs = length vsa\n    -> length vs = length vsb\n    -> no_repeats vs\n    -> no_repeats vsb\n    -> \n  ((forall (gs : GSym G) (t : Term gs), True)\n  *\n  (forall (gs : GSym G) (t : Pattern gs),\n       disjoint vs (vsa ++ vsb ++ (pAllVars t))\n       -> disjoint vsb (vsa ++ pAllVars t)\n       -> (pSwap (pSwapEmbed t (combine vsa vs)) (combine vs vsb))\n            = pSwap t (combine vsa vsb))\n\n    *\n  (forall (lgs : MixtureParam) (m : Mixture lgs) ,\n       disjoint vs (vsa ++ vsb ++ (mAllVars m))\n       -> disjoint vsb (vsa ++ mAllVars m)\n       -> (mSwap (mSwapEmbed m (combine vsa vs)) (combine vs vsb))\n            = mSwap m (combine vsa vsb))).\nProof.\n  introv Hlena Hlenb Hnr Hnrb.\n  apply GInduction; auto; introns Hdis; allsimpl.\n\n  - Case \"vleaf\". simpl. f_equal. rewrite DeqSym. symmetry.  rewrite DeqSym.\n    destruct_head_match; cpx.\n    subst.\n    allsimpl. symmetry. \n    rewrite swapVarNoChange; allsimpl;\n    repeat(disjoint_reasoning); cpx.\n    allrewrite (@DeqTrue (VarSym G)); allsimpl;\n    repeat(disjoint_reasoning).\n\n  - Case \"pnode\".\n    rw Hdis; simpl; auto.\n\n  - Case \"pvleaf\". simpl. f_equal. rewrite DeqSym. symmetry.  rewrite DeqSym.\n    destruct_head_match; cpx.\n    subst.\n    simpl. symmetry. apply swapVarDisjChain; auto;\n    repeat(disjoint_reasoning); allsimpl;\n    allrewrite (@DeqTrue (VarSym G)); allsimpl;\n    repeat(disjoint_reasoning).\n\n  - rw Hdis; simpl; auto.\n  - rw Hdis; simpl; auto.\n  - f_equal.\n    + apply Hdis; repeat(disjoint_reasoning).\n    + apply Hdis0; repeat(disjoint_reasoning).\n\n  - f_equal.\n    + apply Hdis; repeat(disjoint_reasoning).\n    + apply Hdis0; repeat(disjoint_reasoning).\nQed.\n*)\n\n(*\nLemma alphaSwapEmbedCongr : forall {G : CFGV} {vc : VarSym G},\n( \n  (forall (s : GSym G) (a b : Term s), tAlphaEq vc a b -> True)\n   *\n  (forall (s : GSym G),\n      EquiVariantRelSame (@pSwapEmbed G vc s) (pAlphaEq vc))\n  *\n  (EquiVariantRelSame (@swapEmbedAbs G vc) (@AlphaEqAbs G vc))\n  *\n  (EquiVariantRelSame (@swapEmbedLAbs G vc) (@lAlphaEqAbs G vc))\n).\nProof.\n  intros. GAlphaInd; introns Hyp; intros; \n  allsimpl; try (econstructor; eauto with Alpha; fail);[ | |].\n- Case \"pembed\". constructor.\n  apply alphaEquiVariant; eauto.\n- Case \"pnode\". constructor.\n  unfold MakeAbstractionsPNode.\n  rewrite <-  MakeLAbsSwapCommute.\n  rewrite <-  MakeLAbsSwapCommute.\n  cpx.\n\n- Case \"patAbs\".\n  specialize (Hyp4 sw).\nQed.\n*)\n", "meta": {"author": "coq-contribs", "repo": "cfgv", "sha": "d9f4d58ddf571639217f0ba1706e1141921a693a", "save_path": "github-repos/coq/coq-contribs-cfgv", "path": "github-repos/coq/coq-contribs-cfgv/cfgv-d9f4d58ddf571639217f0ba1706e1141921a693a/AlphaRen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.23426677050371617}}
{"text": "Require Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Coq.Strings.String.\n\nRequire Import FFI.\nRequire Import CakeSem.Namespace.\nRequire Import CakeSem.CakeAST.\nRequire Import CakeSem.SemanticsAux.\nRequire Import CakeSem.Evaluate.\n\nRequire Import NoBasis.\n\n\nDefinition init_env : sem_env val := empty_sem_env.\nDefinition init_store := empty_store val.\n\nParameter A : Type.\nParameter init_ffi_st : ffi_state A.\nDefinition init_state := Build_state 0 init_store init_ffi_st 0 0.\n\nDefinition noBasisProg := evaluate_decs 100 init_state init_env [ dec_def_0\n                                                                ; dec_def_1\n                                                                ; dec_def_2\n                                                                ; dec_def_3\n                                                                ; dec_def_4\n                                                                ; dec_def_5\n                                                                ; dec_def_6\n                                                                ; dec_def_7\n                                                                ; dec_def_8\n                                                                ; dec_def_9\n                                                                ; dec_def_10\n                                                                ].\n\nDefinition noBasisProg' := evaluate_decs 19 init_state init_env [ dec_def_0\n                                                                ; dec_def_1\n                                                                ; dec_def_2\n                                                                ; dec_def_3\n                                                                ; dec_def_4\n                                                                ; dec_def_5\n                                                                ; dec_def_6\n                                                                ; dec_def_7\n                                                                ; dec_def_8\n                                                                ; dec_def_9\n                                                                ].\nEval cbv in noBasisProg.\n\nDefinition my_env :=   {|\n         sev := [(Short \"answer\",\n                 Conv (Some (TypeStamp \"S\" 0))\n                   [Conv (Some (TypeStamp \"S\" 0))\n                      [Conv (Some (TypeStamp \"S\" 0))\n                         [Conv (Some (TypeStamp \"S\" 0)) [Conv (Some (TypeStamp \"S\" 0)) [Conv (Some (TypeStamp \"O\" 0)) []]]]]]);\n                (Short \"three\",\n                Conv (Some (TypeStamp \"S\" 0))\n                  [Conv (Some (TypeStamp \"S\" 0)) [Conv (Some (TypeStamp \"S\" 0)) [Conv (Some (TypeStamp \"O\" 0)) []]]]);\n                (Short \"two\",\n                Conv (Some (TypeStamp \"S\" 0)) [Conv (Some (TypeStamp \"S\" 0)) [Conv (Some (TypeStamp \"O\" 0)) []]]);\n                (Short \"abs_minus\",\n                Recclosure\n                  {|\n                  sev := [(Short \"minus\",\n                          Recclosure\n                            {|\n                            sev := [];\n                            sec := [(Short \"SubtrahendLargerThanMinuend\", (0, ExnStamp 0));\n                                   (Short \"S\", (1, TypeStamp \"S\" 0)); (Short \"O\", (0, TypeStamp \"O\" 0))] |}\n                            [(\"minus\", \"x\",\n                             EFun \"y\"\n                               (ELannot\n                                  (EMat (ELannot (EVar (Short \"y\")) [0])\n                                     [(Pcon (Some (Short \"O\")) [], ELannot (EVar (Short \"x\")) [0]);\n                                     (Pcon (Some (Short \"S\")) [Pvar \"yp\"],\n                                     ELannot\n                                       (EMat (ELannot (EVar (Short \"x\")) [0])\n                                          [(Pcon (Some (Short \"O\")) [],\n                                           ELannot\n                                             (ERaise (ELannot (ECon (Some (Short \"SubtrahendLargerThanMinuend\")) []) [0]))\n                                             [0]);\n                                          (Pcon (Some (Short \"S\")) [Pvar \"xp\"],\n                                          ELannot\n                                            (EApp Opapp\n                                               [ELannot\n                                                  (EApp Opapp\n                                                     [ELannot (EVar (Short \"minus\")) [0]; ELannot (EVar (Short \"xp\")) [0]])\n                                                  [0]; ELannot (EVar (Short \"yp\")) [0]]) [0])]) [0])]) [0]))] \"minus\");\n                         (Short \"minus\",\n                         Recclosure\n                           {|\n                           sev := [];\n                           sec := [(Short \"SubtrahendLargerThanMinuend\", (0, ExnStamp 0));\n                                  (Short \"S\", (1, TypeStamp \"S\" 0)); (Short \"O\", (0, TypeStamp \"O\" 0))] |}\n                           [(\"minus\", \"x\",\n                            EFun \"y\"\n                              (ELannot\n                                 (EMat (ELannot (EVar (Short \"y\")) [0])\n                                    [(Pcon (Some (Short \"O\")) [], ELannot (EVar (Short \"x\")) [0]);\n                                    (Pcon (Some (Short \"S\")) [Pvar \"yp\"],\n                                    ELannot\n                                      (EMat (ELannot (EVar (Short \"x\")) [0])\n                                         [(Pcon (Some (Short \"O\")) [],\n                                          ELannot\n                                            (ERaise (ELannot (ECon (Some (Short \"SubtrahendLargerThanMinuend\")) []) [0]))\n                                            [0]);\n                                         (Pcon (Some (Short \"S\")) [Pvar \"xp\"],\n                                         ELannot\n                                           (EApp Opapp\n                                              [ELannot\n                                                 (EApp Opapp\n                                                    [ELannot (EVar (Short \"minus\")) [0]; ELannot (EVar (Short \"xp\")) [0]])\n                                                 [0]; ELannot (EVar (Short \"yp\")) [0]]) [0])]) [0])]) [0]))] \"minus\")];\n                  sec := [(Short \"SubtrahendLargerThanMinuend\", (0, ExnStamp 0)); (Short \"S\", (1, TypeStamp \"S\" 0));\n                         (Short \"O\", (0, TypeStamp \"O\" 0))] |}\n                  [(\"abs_minus\", \"x\",\n                   EFun \"y\"\n                     (ELannot\n                        (EHandle\n                           (ELannot\n                              (EApp Opapp\n                                 [ELannot (EApp Opapp [ELannot (EVar (Short \"minus\")) [0]; ELannot (EVar (Short \"x\")) [0]])\n                                    [0]; ELannot (EVar (Short \"y\")) [0]]) [0])\n                           [(Pcon (Some (Short \"SubtrahendLargerThanMinuend\")) [],\n                            ELannot\n                              (EApp Opapp\n                                 [ELannot (EApp Opapp [ELannot (EVar (Short \"minus\")) [0]; ELannot (EVar (Short \"y\")) [0]])\n                                    [0]; ELannot (EVar (Short \"x\")) [0]]) [0])]) [0]))] \"abs_minus\");\n                (Short \"minus\",\n                Recclosure\n                  {|\n                  sev := [];\n                  sec := [(Short \"SubtrahendLargerThanMinuend\", (0, ExnStamp 0)); (Short \"S\", (1, TypeStamp \"S\" 0));\n                         (Short \"O\", (0, TypeStamp \"O\" 0))] |}\n                  [(\"minus\", \"x\",\n                   EFun \"y\"\n                     (ELannot\n                        (EMat (ELannot (EVar (Short \"y\")) [0])\n                           [(Pcon (Some (Short \"O\")) [], ELannot (EVar (Short \"x\")) [0]);\n                           (Pcon (Some (Short \"S\")) [Pvar \"yp\"],\n                           ELannot\n                             (EMat (ELannot (EVar (Short \"x\")) [0])\n                                [(Pcon (Some (Short \"O\")) [],\n                                 ELannot (ERaise (ELannot (ECon (Some (Short \"SubtrahendLargerThanMinuend\")) []) [0])) [0]);\n                                (Pcon (Some (Short \"S\")) [Pvar \"xp\"],\n                                ELannot\n                                  (EApp Opapp\n                                     [ELannot\n                                        (EApp Opapp [ELannot (EVar (Short \"minus\")) [0]; ELannot (EVar (Short \"xp\")) [0]])\n                                        [0]; ELannot (EVar (Short \"yp\")) [0]]) [0])]) [0])]) [0]))] \"minus\");\n                (Short \"mult\",\n                Recclosure\n                  {|\n                  sev := [(Short \"plus\",\n                          Recclosure\n                            {| sev := []; sec := [(Short \"S\", (1, TypeStamp \"S\" 0)); (Short \"O\", (0, TypeStamp \"O\" 0))] |}\n                            [(\"plus\", \"x\",\n                             EFun \"y\"\n                               (ELannot\n                                  (EMat (ELannot (EVar (Short \"x\")) [0])\n                                     [(Pcon (Some (Short \"O\")) [], ELannot (EVar (Short \"y\")) [0]);\n                                     (Pcon (Some (Short \"S\")) [Pvar \"xp\"],\n                                     ELannot\n                                       (ECon (Some (Short \"S\"))\n                                          [EApp Opapp\n                                             [ELannot\n                                                (EApp Opapp\n                                                   [ELannot (EVar (Short \"plus\")) [0]; ELannot (EVar (Short \"xp\")) [0]]) [0];\n                                             ELannot (EVar (Short \"y\")) [0]]]) [0])]) [0]))] \"plus\")];\n                  sec := [(Short \"S\", (1, TypeStamp \"S\" 0)); (Short \"O\", (0, TypeStamp \"O\" 0))] |}\n                  [(\"mult\", \"x\",\n                   EFun \"y\"\n                     (ELannot\n                        (EMat (ELannot (EVar (Short \"x\")) [0])\n                           [(Pcon (Some (Short \"O\")) [], ELannot (ECon (Some (Short \"O\")) []) [0]);\n                           (Pcon (Some (Short \"S\")) [Pvar \"xp\"],\n                           ELannot\n                             (ELet (Some \"z\")\n                                (ELannot\n                                   (EApp Opapp\n                                      [ELannot\n                                         (EApp Opapp [ELannot (EVar (Short \"mult\")) [0]; ELannot (EVar (Short \"xp\")) [0]])\n                                         [0]; ELannot (EVar (Short \"y\")) [0]]) [0])\n                                (ELannot\n                                   (EApp Opapp\n                                      [ELannot\n                                         (EApp Opapp [ELannot (EVar (Short \"plus\")) [0]; ELannot (EVar (Short \"y\")) [0]])\n                                         [0]; ELannot (EVar (Short \"z\")) [0]]) [0])) [0])]) [0]))] \"mult\");\n                (Short \"plus2\",\n                Recclosure\n                  {|\n                  sev := [(Short \"succ\",\n                          Closure\n                            {| sev := []; sec := [(Short \"S\", (1, TypeStamp \"S\" 0)); (Short \"O\", (0, TypeStamp \"O\" 0))] |}\n                            \"x\" (ELannot (ECon (Some (Short \"S\")) [EVar (Short \"x\")]) [0]));\n                         (Short \"plus\",\n                         Recclosure\n                           {| sev := []; sec := [(Short \"S\", (1, TypeStamp \"S\" 0)); (Short \"O\", (0, TypeStamp \"O\" 0))] |}\n                           [(\"plus\", \"x\",\n                            EFun \"y\"\n                              (ELannot\n                                 (EMat (ELannot (EVar (Short \"x\")) [0])\n                                    [(Pcon (Some (Short \"O\")) [], ELannot (EVar (Short \"y\")) [0]);\n                                    (Pcon (Some (Short \"S\")) [Pvar \"xp\"],\n                                    ELannot\n                                      (ECon (Some (Short \"S\"))\n                                         [EApp Opapp\n                                            [ELannot\n                                               (EApp Opapp\n                                                  [ELannot (EVar (Short \"plus\")) [0]; ELannot (EVar (Short \"xp\")) [0]]) [0];\n                                            ELannot (EVar (Short \"y\")) [0]]]) [0])]) [0]))] \"plus\")];\n                  sec := [(Short \"S\", (1, TypeStamp \"S\" 0)); (Short \"O\", (0, TypeStamp \"O\" 0))] |}\n                  [(\"plus2\", \"x\",\n                   EFun \"y\"\n                     (ELannot\n                        (EMat (ELannot (EVar (Short \"x\")) [0])\n                           [(Pcon (Some (Short \"O\")) [], ELannot (EVar (Short \"y\")) [0]);\n                           (Pcon (Some (Short \"S\")) [Pvar \"xp\"],\n                           ELannot\n                             (EApp Opapp\n                                [ELannot (EVar (Short \"succ\")) [0];\n                                ELannot\n                                  (EApp Opapp\n                                     [ELannot\n                                        (EApp Opapp [ELannot (EVar (Short \"plus\")) [0]; ELannot (EVar (Short \"xp\")) [0]])\n                                        [0]; ELannot (EVar (Short \"y\")) [0]]) [0]]) [0])]) [0]))] \"plus2\");\n                (Short \"plus\",\n                Recclosure {| sev := []; sec := [(Short \"S\", (1, TypeStamp \"S\" 0)); (Short \"O\", (0, TypeStamp \"O\" 0))] |}\n                  [(\"plus\", \"x\",\n                   EFun \"y\"\n                     (ELannot\n                        (EMat (ELannot (EVar (Short \"x\")) [0])\n                           [(Pcon (Some (Short \"O\")) [], ELannot (EVar (Short \"y\")) [0]);\n                           (Pcon (Some (Short \"S\")) [Pvar \"xp\"],\n                           ELannot\n                             (ECon (Some (Short \"S\"))\n                                [EApp Opapp\n                                   [ELannot\n                                      (EApp Opapp [ELannot (EVar (Short \"plus\")) [0]; ELannot (EVar (Short \"xp\")) [0]]) [0];\n                                   ELannot (EVar (Short \"y\")) [0]]]) [0])]) [0]))] \"plus\");\n                (Short \"succ\",\n                Closure {| sev := []; sec := [(Short \"S\", (1, TypeStamp \"S\" 0)); (Short \"O\", (0, TypeStamp \"O\" 0))] |} \"x\"\n                  (ELannot (ECon (Some (Short \"S\")) [EVar (Short \"x\")]) [0]))];\n         sec := [(Short \"SubtrahendLargerThanMinuend\", (0, ExnStamp 0)); (Short \"S\", (1, TypeStamp \"S\" 0));\n                (Short \"O\", (0, TypeStamp \"O\" 0))] |}.\n\nDefinition my_st := {| clock := 0; refs := []; ffi := init_ffi_st; next_type_stamp := 1; next_exn_stamp := 1 |}.\n\nInductive nat_rel_cake_nat (typestamp : nat) : nat -> val -> Prop :=\n| zero_rel : nat_rel_cake_nat typestamp 0 (Conv (Some (TypeStamp \"O\" typestamp)) [])\n| suc_rel  : forall (n : nat) (prev : val), nat_rel_cake_nat typestamp n prev -> nat_rel_cake_nat typestamp (S n) (Conv (Some (TypeStamp \"S\" typestamp)) [prev]).\n\nTheorem plus_vs_cake_plus : forall (m n t : nat) (m_exp n_exp : exp) (m_val n_val m_n_val : val),\n    (exists (mf : nat), evaluate_opt my_st my_env [m_exp] mf = (my_st, Rval [m_val])) ->\n    (exists (nf : nat), evaluate_opt my_st my_env [n_exp] nf = (my_st, Rval [n_val])) ->\n    nat_rel_cake_nat t m m_val ->\n    nat_rel_cake_nat t n n_val ->\n    (exists (mnf : nat), evaluate_opt my_st my_env [(EApp (Opapp) ((EApp (Opapp) ((EVar (Short (\"plus\"%string)))::m_exp::nil))::n_exp::nil))] mnf =\n    (my_st, Rval [m_n_val])) ->\n    nat_rel_cake_nat t (m+n) m_n_val.\nProof.\n  intros m n t m_exp n_exp m_val n_val m_n_val.\nAbort.\n", "meta": {"author": "ku-sldg", "repo": "cakeml-coq", "sha": "46256bebe3e151a75956e379d236c44f58e255de", "save_path": "github-repos/coq/ku-sldg-cakeml-coq", "path": "github-repos/coq/ku-sldg-cakeml-coq/cakeml-coq-46256bebe3e151a75956e379d236c44f58e255de/examples/noBasis/EvaluateTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.23426677050371617}}
{"text": "Set Implicit Arguments.\n\nRequire Import util.\nRequire Import Le.\nRequire Import Plus.\nRequire Import Minus.\nRequire Import Lt.\nRequire Import Arith.\nRequire Import Recdef.\nRequire Import Bool_nat.\nRequire Import List.\nRequire Import monads.\nRequire Import Relation_Definitions.\nRequire Import monoid_monad_trans.\nRequire Import expec.\nRequire Import monoid_expec.\nRequire Import nat_seqs.\nRequire Import list_utils.\nRequire Import sums_and_averages.\nRequire qs_definitions.\nRequire qs_parts.\nRequire U.\nRequire Import sort_order.\nRequire Import indices.\nRequire Import qs_sound_cmps.\nRequire Import Fourier.\nRequire Import Rbase.\nRequire Import skip_list.\nRequire Import nat_below.\nRequire Vector.\n\nImport qs_definitions.mon_nondet.\n\nSection contents.\n\n  Variables (ee: E) (ol: list ee) (i j: Index ee ol).\n\n  Variable n: nat.\n  Variable v: Vector.t (Index ee ol) (S n).\n  Variable iltj: (i < j)%nat.\n\n  Let flt x0 cr := filter (fun f: Index ee ol => unsum_bool (cmp_cmp (Ecmp (UE ee ol) f (vec.nth v x0)) cr)) (vec.remove v x0).\n\n  Variable IH: forall (x0: natBelow (S n)) (cr: comparison) (b: nat),\n    IndexSeq b (flt x0 cr) ->\n    monoid_expec (U.ijcount i j) (qs (U.cmp (e:=ee) (ol:=ol)) U.pick (flt x0 cr)) <= 2 / INR (S (j - i)).\n\n  Variables (b: nat) (is: IndexSeq b v).\n\n  Lemma ndi: NoDup v.\n    apply IndexSeq_NoDup with b.\n    assumption.\n  Qed.\n\n  Variable iin: In i v.\n  Variable jin: In j v.\n  Variable pi: natBelow (S n).\n\n  Lemma not_In_flt (k: Index ee ol) (dr: comparison) (H0: dr <> Ecmp (UE ee ol) k (vec.nth v pi)):\n    ~ In k (flt pi dr).\n  Proof with auto.\n    unfold flt.\n    intros.\n    intro.\n    destruct (proj1_conj (filter_In _ _ _) H). clear H.\n    simpl in H0.\n    simpl in H2.\n    destruct (Ecmp ee (subscript k) (subscript (vec.nth v pi))); destruct dr; auto; simpl in H2; try discriminate...\n  Qed.\n\n  Lemma ndi_flt: forall x0 cr, NoDup (flt x0 cr).\n  Proof.\n    unfold flt.\n    intros.\n    apply NoDup_filter.\n    apply (NoDup_SkipList ndi).\n    cset (vec.SkipList_remove x0 v).\n    assumption.\n  Qed.\n\n  Hint Immediate ndi_flt.\n\n  Lemma partition_0: nb_val (vec.nth v pi) <> i -> nb_val (vec.nth v pi) <> j ->\n    U.ijcount i j (map (fun i0: Index ee ol => U.unordered_nat_pair i0 (vec.nth v pi)) (vec.remove v pi)) = 0%nat.\n  Proof.\n    intros.\n    apply (U.ijcount_0).\n    intro.\n    destruct (In_map_inv H1). clear H1.\n    destruct H2.\n    unfold U.unordered_nat_pair in H1.\n    destruct (le_lt_dec x (vec.nth v pi)); inversion H1; auto.\n  Qed.\n\n  Hint Immediate U.hom_ijcount.\n  Hint Immediate vec.remove_perm.\n\n  Lemma pivot_not_In_flt cr: ~ In (vec.nth v pi) (flt pi cr).\n  Proof with auto.\n    intros H.\n    pose proof ndi as H0.\n    rewrite (Permutation.Permutation_sym (vec.List_Permutation (vec.remove_perm pi v))) in H0.\n    inversion_clear H0...\n    destruct (In_filter_inv _ _ _ H)...\n  Qed.\n\n  Lemma NoDup_comparisons (x: Index ee ol) (l: list (Index ee ol)):\n    NoDup (x :: l) -> NoDup (map (fun i: Index ee ol => U.unordered_nat_pair i x) l).\n  Proof with auto.\n    intros.\n    inversion_clear H.\n    apply NoDup_map'...\n    intros.\n    unfold U.unordered_nat_pair.\n    intro.\n    apply H3.\n    unfold Index in *.\n    apply natBelow_unique.\n    destruct (le_lt_dec x0 x); destruct (le_lt_dec y x); inversion H4; reflexivity.\n  Qed.\n\n  Lemma case_A: (vec.nth v pi < i)%nat ->\n    INR (U.ijcount i j (map (fun i0: Index ee ol => U.unordered_nat_pair i0 (vec.nth v pi)) (vec.remove v pi))) +\n    monoid_expec (U.ijcount i j)\n      (foo <- @U.qs ee ol (flt pi Lt);\n      bar <- @U.qs ee ol (flt pi Gt);\n      ret  (foo ++ (vec.nth v pi :: flt pi Eq) ++ bar))\n    <= 2 * / INR (S (j - i)).\n  Proof with auto with real.\n    intros.\n    rewrite partition_0...\n      Focus 2.\n      intro.\n      rewrite H0 in H.\n      apply (lt_asym _ _ H iltj).\n    rewrite Rplus_0_l.\n    rewrite monoid_expec_plus... Focus 2. intros. repeat rewrite monoid_expec_plus...\n    rewrite monoid_expec_plus...\n    rewrite monoid_expec_ret...\n    rewrite Rplus_0_r.\n    rewrite sound_cmp_expec_0...\n      Focus 2.\n      left.\n      apply not_In_flt...\n      intro.\n      apply (lt_asym _ _ H).\n      symmetry in H0.\n      apply (IndicesCorrect _ _ H0).\n    rewrite Rplus_0_l.\n    case_eq (Ecmp ee (subscript i) (subscript (vec.nth v pi))); intro.\n        (* i in the Eq part *)\n        unfold Rdiv.\n        rewrite sound_cmp_expec_0...\n        left.\n        apply not_In_flt...\n        simpl.\n        simpl in H0.\n        rewrite H0. intro. discriminate.\n      (* in the Lt part, impossible *)\n      elimtype False.\n      apply (lt_irrefl i).\n      apply lt_trans with (vec.nth v pi)...\n      apply (IndicesCorrect i (vec.nth v pi))...\n    (* i in the Gt part. recursive sorting of upper part: *)\n    assert (IndexSeq b (vec.nth v pi :: vec.remove v pi)).\n      apply IndexSeq_perm with v...\n      cset (vec.List_Permutation (vec.remove_perm pi v))...\n    apply (IH _ Gt (@InvIndexSeq_filterGt' ee ol (vec.nth v pi) (vec.remove v pi) b H1))...\n  Qed.\n\n  Lemma case_E: (j < vec.nth v pi)%nat ->\n    INR (U.ijcount i j (map (fun i0: Index ee ol => U.unordered_nat_pair i0 (vec.nth v pi)) (vec.remove v pi))) +\n    monoid_expec (U.ijcount i j)\n      (foo <- @U.qs ee ol (flt pi Lt);\n      bar <- @U.qs ee ol (flt pi Gt);\n      ret (foo ++ (vec.nth v pi :: flt pi Eq) ++ bar))\n    <= 2 * / INR (S (j - i)).\n  Proof with auto with real.\n    intros.\n    rewrite partition_0...\n      Focus 2.\n      intro.\n      cset (natBelow_unique _ _ H0).\n      subst i.\n      apply (lt_asym _ _ H iltj).\n    rewrite Rplus_0_l.\n    rewrite monoid_expec_plus...\n      rewrite monoid_expec_plus...\n      rewrite monoid_expec_ret...\n      rewrite Rplus_0_r.\n      rewrite (@sound_cmp_expec_0 ee ol i j (flt pi Gt))...\n        Focus 2.\n        right.\n        apply not_In_flt.\n        intro.\n        apply (lt_asym _ _ H).\n        cset (Ecmp_sym ee (subscript (vec.nth v pi)) (subscript j)).\n        simpl in H0.\n        simpl in H1.\n        rewrite <- H0 in H1.\n        simpl in H1.\n        apply (IndicesCorrect _ _ H1).\n      rewrite Rplus_0_r.\n      case_eq (Ecmp ee (subscript j) (subscript (vec.nth v pi))); intro.\n          (* j in the Eq part *)\n          unfold Rdiv.\n          rewrite sound_cmp_expec_0...\n          right.\n          apply not_In_flt...\n          simpl.\n          simpl in H0. simpl.\n          rewrite H0. intro. discriminate.\n        Focus 2.\n        (* in the Gt part, impossible *)\n        elimtype False.\n        cset (Ecmp_sym ee (subscript (vec.nth v pi)) (subscript j)).\n        rewrite H0 in H1.\n        simpl in H1.\n        apply (lt_asym _ _ H).\n        apply (IndicesCorrect _ _ H1)...\n      (* in the Lt part *)\n      apply IH with b...\n      unfold flt.\n      assert (length (vec.nth v pi :: vec.remove v pi) = S n).\n        simpl @length. rewrite vec.length...\n      assert (IndexSeq b (vec.nth v pi :: vec.remove v pi)).\n        apply IndexSeq_perm with v...\n        apply (vec.List_Permutation (vec.remove_perm pi v)).\n      cset (@IndexSeq_filterLt ee ol (vec.nth v pi) (S n) b (vec.nth v pi :: vec.remove v pi) H1 H2).\n      simpl filter in H3.\n      rewrite Ecmp_refl in H3...\n    intros.\n    repeat rewrite monoid_expec_plus...\n  Qed.\n\n  Lemma case_C: (i < vec.nth v pi)%nat -> (vec.nth v pi < j)%nat ->\n    INR (U.ijcount i j (map (fun i0: Index ee ol => U.unordered_nat_pair i0 (vec.nth v pi)) (vec.remove v pi))) +\n    monoid_expec (U.ijcount i j)\n      (foo <- @U.qs ee ol (flt pi Lt);\n      bar <- @U.qs ee ol (flt pi Gt);\n      ret (foo ++ (vec.nth v pi :: flt pi Eq) ++ bar))\n    = 0.\n  Proof with auto with real.\n  intros.\n    rewrite partition_0...\n    rewrite Rplus_0_l.\n    unfold U.M.\n    rewrite monoid_expec_bind_0_r...\n      apply sound_cmp_expec_0...\n      right.\n      apply not_In_flt.\n      intro.\n      apply (lt_asym _ _ H0).\n      symmetry in H1.\n      apply (IndicesCorrect _ _ H1).\n    intros.\n    rewrite monoid_expec_plus...\n    rewrite (monoid_expec_ret (U.hom_ijcount i j)).\n    rewrite Rplus_0_r.\n    apply sound_cmp_expec_0...\n    left.\n    apply not_In_flt.\n    intro.\n    cset (Ecmp_sym ee (subscript (vec.nth v pi)) (subscript i)).\n    simpl in H1. simpl in H2.\n    rewrite <- H1 in H2.\n    simpl in H2.\n    apply (lt_asym _ _ H).\n    apply (IndicesCorrect _ _ H2).\n  Qed.\n\n  Lemma case_BD: (i = vec.nth v pi \\/ j = vec.nth v pi) ->\n    INR (U.ijcount i j (map (fun i0: Index ee ol => U.unordered_nat_pair i0 (vec.nth v pi)) (vec.remove v pi))) +\n    monoid_expec (U.ijcount i j)\n      (foo <- @U.qs ee ol (flt pi Lt);\n      bar <- @U.qs ee ol (flt pi Gt);\n      ret (foo ++ (vec.nth v pi :: flt pi Eq) ++ bar))\n    <= 1.\n  Proof with auto with real.\n    intros.\n    rewrite (monoid_expec_bind_0_r (U.hom_ijcount i j)).\n      rewrite sound_cmp_expec_0...\n        rewrite Rplus_0_r.\n        rewrite U.ijcount_eq_count.\n        replace 1 with (INR 1)...\n        apply le_INR.\n        apply eq_count_NoDup.\n        apply NoDup_comparisons.\n        rewrite (vec.List_Permutation (vec.remove_perm pi v)).\n        apply IndexSeq_NoDup with b...\n      destruct H; subst; [left | right]; apply pivot_not_In_flt.\n    intros.\n    unfold U.M.\n    rewrite monoid_expec_plus...\n    rewrite (monoid_expec_ret (U.hom_ijcount i j)).\n    rewrite sound_cmp_expec_0...\n    destruct H; subst; [left | right]; apply pivot_not_In_flt.\n  Qed.\n\nEnd contents.\n", "meta": {"author": "coq-contribs", "repo": "quicksort-complexity", "sha": "bf0205e5fcfec6d6c6017da071960594de79e0da", "save_path": "github-repos/coq/coq-contribs-quicksort-complexity", "path": "github-repos/coq/coq-contribs-quicksort-complexity/quicksort-complexity-bf0205e5fcfec6d6c6017da071960594de79e0da/qs_cases.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6926419704455588, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.2341664100531908}}
{"text": "From Test Require Import tactic.\n\nSection FOFProblem.\n\nVariable Universe : Set.\nVariable UniverseElement : Universe.\n\nVariable wd_ : Universe -> Universe -> Prop.\nVariable col_ : Universe -> Universe -> Universe -> Prop.\n\n\nVariable col_swap1_1 : (forall A B C : Universe, (col_ A B C -> col_ B A C)).\nVariable col_swap2_2 : (forall A B C : Universe, (col_ A B C -> col_ B C A)).\nVariable col_triv_3 : (forall A B : Universe, col_ A B B).\nVariable wd_swap_4 : (forall A B : Universe, (wd_ A B -> wd_ B A)).\nVariable col_trans_5 : (forall P Q A B C : Universe, ((wd_ P Q /\\ (col_ P Q A /\\ (col_ P Q B /\\ col_ P Q C))) -> col_ A B C)).\n\nTheorem pipo_6 : (forall P Q A B C Dprime Pprime Cprime Dprimeprime Pprimeprime Z Zprime T : Universe, ((wd_ P Q /\\ (wd_ T Z /\\ (wd_ T Zprime /\\ (wd_ T Pprimeprime /\\ (wd_ A B /\\ (wd_ B C /\\ (wd_ A C /\\ (wd_ Zprime Z /\\ (wd_ B T /\\ (wd_ Cprime Pprimeprime /\\ (wd_ B Pprime /\\ (wd_ B Cprime /\\ (wd_ Dprimeprime Cprime /\\ (wd_ Dprime B /\\ (wd_ Zprime B /\\ (wd_ Z B /\\ (wd_ B Pprimeprime /\\ (wd_ B Dprimeprime /\\ (wd_ Cprime C /\\ (wd_ A Dprime /\\ (wd_ Pprime Cprime /\\ (col_ A B Zprime /\\ (col_ Z B T /\\ (col_ B Pprimeprime T /\\ (col_ Zprime T Z /\\ (col_ B C Z /\\ (col_ Cprime Dprimeprime Pprimeprime /\\ (col_ B Cprime A /\\ col_ B Dprime Pprime)))))))))))))))))))))))))))) -> col_ A B C)).\nProof.\n  time tac.\nQed.\n\nEnd FOFProblem.\n", "meta": {"author": "janicicpredrag", "repo": "Larus", "sha": "a095ca588fbb0e4a64a26d92946485bbf85e1e08", "save_path": "github-repos/coq/janicicpredrag-Larus", "path": "github-repos/coq/janicicpredrag-Larus/Larus-a095ca588fbb0e4a64a26d92946485bbf85e1e08/benchmarks/coq-problems/col-trans/col_trans_0575.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419958239132, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.2341664093943058}}
{"text": "(* Cyclone Semantics using TLC/LN in Coq Version 4 *)\n(* \"SAFE PROGRAMMING AT THE C LEVEL OF ABSTRACTION\".   Daniel Grossman, August 2003 *)\n(* Brian Milnes 2016 *)\n(* Lemmas for get. *)\n\nSet Implicit Arguments.\nRequire Import TLC.LibEnv LibVarPathEnv Cyclone_LN_Tactics Cyclone_Fset_Lemmas.\nRequire Import Cyclone_Admit_Environment.\nClose Scope list_scope.\nImport LibEnvNotations.\nImport LVPE.LibVarPathEnvNotations.\n\nLtac get_empty:=\n  match goal with\n  | H: get _ empty = Some _ |- _ =>\n    rewrite get_empty in H; inversion H\n  end.\n\nLtac lvpe_get_empty:=\n  match goal with\n  | H: LVPE.V.get _ empty = Some _ |- _ =>\n    rewrite LVPE.get_empty in H; inversion H\nend.\n\nLtac simpl_get ::=\n  (* idtac \"simpl_get\";*)\n  trace_goal;\n  timeout 2\n  repeat\n    match goal with\n  | |- context [get ?a empty]           => trace_goal; rewrite~ get_empty\n  | |- context [get ?a empty]           => trace_goal; rewrite~ get_empty  \n  | |- context [get ?a empty]           => trace_goal; rewrite~ get_empty\n  | |- context [get ?a (_ & (_ ~ _)) ]      => trace_goal;\n    rewrite~ get_push; try repeat case_var~\n\n  | |- context [get ?a ((?b ~ _) & _)] => trace_goal;\n    rewrite~ get_concat; try repeat case_var~\n\n  | |- context [get ?a _ = None] => trace_goal;\n   apply* get_none\n\n  | H: context[get _ empty = Some _] |- _ => \n    rewrite get_empty in H; inversion H\nend.\n\nLemma get_fv_delta:\n  forall v d k,\n    get v d = Some k ->\n    \\{v} \\c fv_delta d.\nProof.\n  intros.\n  unfold fv_delta.\n  induction d using env_ind.\n  rewrite get_empty in H.\n  inversion H.\n  rewrite get_push in H.\n  case_var.\n  inversion H.\n  subst.\n  rewrite dom_push.\n  fset.\n  apply IHd in H.\n  rewrite dom_push.\n  apply* subset_weakening.\nQed.\nLtac get_fv_delta :=\n  match goal with \n  | H: get ?v ?d = Some ?k' |- \\{?v} \\c fv_delta ?d =>\n    apply get_fv_delta with (k:= k'); assumption; auto with fset\nend.                                                \nHint Extern 1 (\\{_} \\c fv_delta _) => get_fv_delta.\nHint Extern 1 (T.fv _ \\c fv_delta _) => simpl; get_fv_delta.\n\nLemma get_dom:\n  forall A alpha (d : env A)  k,\n    get alpha d = Some k ->\n    \\{alpha} \\c dom d.\nProof.\n  intros.\n  induction d using env_ind.\n  rewrite get_empty in H.\n  inversion H.\n  destruct (classicT(alpha = x)).\n  subst.\n  rewrite dom_push.\n  fset.\n  rewrite get_push in H.\n  rewrite* If_r in H.\n  apply IHd in H.\n  rewrite dom_push.\n  apply* subset_weakening.\nQed.\nLtac get_dom :=\n  match goal with\n  | H: get ?a ?d = Some ?k' \n  |- \\{?a} \\c dom ?d =>\n    apply get_dom with (k:= k')\n  end.\nHint Extern 1 (\\{_} \\c dom _) => get_dom.\n\n(* Arthur's binds theorems redone in get. *)\n\nSection GetProperties.\nVariable A B' : Type.\nImplicit Types E F : env A.\nImplicit Types x : var.\nImplicit Types v : A.\n\n(** Constructor forms *)\n\nLemma get_empty_inv : forall x v,\n  get x empty = Some v -> False.\nProof using.\n  introv H. rewrite get_empty in H. false.\nQed.\n\nLemma get_single_eq : forall x v,\n  get x (x ~ v) = Some v.\nProof using.\n  intros.  rewrite get_single. case_if~.\nQed.\n\nLemma get_single_inv : forall x1 x2 v1 v2,\n  get x1 (x2 ~ v2) = Some v1 ->\n  x1 = x2 /\\ v1 = v2.\nProof using.\n   introv H. rewrite get_single in H.\n  case_if; inversions~ H.\nQed.\n\nLemma get_push_inv : forall x1 v1 x2 v2 E,\n  get x1 (E & x2 ~ v2) = Some v1 ->\n     (x1 = x2 /\\ v1 = v2)\n  \\/ (x1 <> x2 /\\ get x1 E = Some v1).\nProof using.\n  introv H.  rewrite get_push in H. case_if.\n  inverts~ H. auto.\nQed.\n\nLemma get_push_eq : forall x v E,\n  get x (E & x ~ v) = Some v.\nProof using. intros.  rewrite get_push. case_if~. Qed.\n\nLemma get_push_eq_inv : forall x v1 v2 E,\n  get x (E & x ~ v2) = Some v1 -> v1 = v2.\nProof using.\n  introv H. forwards [|]: get_push_inv H. autos*. intros [? _]. false.\nQed.\n\nLemma get_push_neq_inv : forall x1 x2 v1 v2 E,\n  get x1 (E & x2 ~ v2) = Some v1 -> x1 <> x2 -> get x1 E = Some v1.\nProof using.\n  introv H. forwards [|]: get_push_inv H.\n  intros [? ?] ?. false. autos*.\nQed.\n\nLemma get_tail : forall x v E,\n  get x (E & x ~ v) = Some v.\nProof using. intros. rewrite get_push. cases_if~. Qed.\n\nLemma get_push_neq : forall x1 x2 v1 v2 E,\n  get x1 E = Some v1 -> x1 <> x2 -> get x1 (E & x2 ~ v2) = Some v1.\nProof using.\n  introv H N.  rewrite get_push. case_if~.\nQed.\n\nLemma get_concat_inv : forall x v E1 E2,\n  get x (E1 & E2) = Some v ->\n     (get x E2 = Some v)\n  \\/ (x # E2 /\\ get x E1 = Some v).\nProof using.\n  introv H. induction E2 using env_ind.\n  rewrite~ concat_empty_r in H.\n  rewrite concat_assoc in H.\n   forwards [[? ?]|[? M]]: get_push_inv H.\n     subst. left. apply get_tail.\n     forwards [?|[? ?]]: IHE2 M.\n       left. applys~ get_push_neq.\n       right.\n       auto.\nQed.\n\n(* Typing env vs list issues. \nLemma get_map : forall x v (f : A -> B) E,\n  get x E = Some v -> get x (map f E) = Some (f v).\nProof using.\n  introv H.  rew_env_defs.\n  induction E as [|[x' v'] E']; simpls.\n  false.\n  cases_if~. inverts~ H.\nQed.\n*)\n\nLemma get_func : forall x v1 v2 E,\n  get x E = Some v1 -> get x E = Some v2 -> v1 = v2.\nProof using.\n  introv H1 H2.\n  induction E as [|E' x' v'] using env_ind.\n  rewrite get_empty in H1. false.\n  rewrite get_push in H1,H2. case_if~.\n   inverts H1. inverts~ H2.\nQed.\n\nLemma get_fresh_inv : forall x v E,\n  get x E = Some v -> x # E -> False.\nProof using.\n  introv H F.\n  induction E as [|E' x' v'] using env_ind.\n  rewrite get_empty in H. false.\n  rewrite get_push in H. case_if~. subst.\n   simpl_dom; notin_false.\nQed.\n\n(** Derived forms *)\n\nLemma get_single_eq_inv : forall x v1 v2,\n  get x (x ~ v2) = Some v1 ->\n  v1 = v2.\nProof using.\n  introv H. rewrite get_single in H.\n  case_if. inverts~ H.\nQed.\n\nLemma get_concat_left : forall x v E1 E2,\n  get x E1 = Some v ->\n  x # E2 ->\n  get x (E1 & E2) = Some v.\nProof using.\n  introv H F. induction E2 using env_ind.\n  rewrite~ concat_empty_r.\n  rewrite concat_assoc.\n  applys~ get_push_neq.\n  subst.\n  simpl_dom.\n  apply notin_union in F.\n  inversion F.\n  apply notin_singleton_r in H0; auto.\nQed.\n\nLemma get_concat_left_ok : forall x v E1 E2,\n  ok (E1 & E2) ->\n  get x E1 = Some v ->\n  get x (E1 & E2) = Some v.\nProof using.\n  introv O H. induction E2 using env_ind.\n  rewrite~ concat_empty_r.\n  rewrite concat_assoc in O|-*. lets [_ ?]: ok_push_inv O.\n  applys~ get_push_neq. subst. \n  intro_subst.\n  applys~ get_fresh_inv H.\nQed.\n\nLemma get_concat_left_inv : forall x v E1 E2,\n  get x (E1 & E2) = Some v ->\n  x # E2 ->\n  get x E1 = Some v.\nProof using.\n  introv H F. lets~ [M|[? ?]]: get_concat_inv H.\n    false. applys~ get_fresh_inv M.\nQed.\n\nLemma get_concat_right : forall x v E1 E2,\n  get x E2 = Some v ->\n  get x (E1 & E2) = Some v.\nProof using.\n  introv H. induction E2 using env_ind.\n  false. apply get_empty_inv with (x:=x) (v:=v); auto.\n  rewrite concat_assoc. lets [[? ?]|[? ?]]: get_push_inv H.\n    subst. applys get_tail.\n    applys* get_push_neq.\nQed.\n\nLemma get_concat_right_inv : forall x v E1 E2,\n  get x (E1 & E2) = Some v ->\n  x # E1 ->\n  get x E2 = Some v.\nProof using.\n  introv H F. lets~ [?|[? M]]: get_concat_inv H.\n    false. applys~ get_fresh_inv M.\nQed.\n\nLemma get_middle_eq : forall x E1 E2 v,\n  x # E2 ->\n  get x (E1 & x ~ v & E2) = Some v.\nProof using.\n  introv F. applys~ get_concat_left.\nQed.\n\n(** Metatheory proof forms *)\n\n(** Interaction between binds and the insertion of bindings.\n  In theory we don't need this lemma since it would suffice\n  to use the get_cases tactics, but since weakening is a\n  very common operation we provide a lemma for it. *)\n\nLemma get_weaken : forall x a E F G,\n  get x (E & G) = Some a -> ok (E & F & G) ->\n  get x (E & F & G) = Some a.\nProof using.\n  introv H O. lets [?|[? ?]]: get_concat_inv H.\n    applys~ get_concat_right.\n    applys~ get_concat_left. applys~ get_concat_left_ok.\nQed.\n\nLemma get_remove : forall E2 E1 E3 x v,\n  get x (E1 & E2 & E3) = Some v ->\n  x # E2 ->\n  get x (E1 & E3) = Some v.\nProof using.\n  introv H F. lets [?|[? M]]: get_concat_inv H.\n    applys~ get_concat_right.\n    forwards: get_concat_left_inv M; auto.\n    applys~ get_concat_left.\nQed.\n\nLemma get_subst : forall x2 v2 x1 v1 E1 E2,\n  get x1 (E1 & x2 ~ v2 & E2) = Some v1 ->\n  x1 <> x2 ->\n  get x1 (E1 & E2) = Some v1.\nProof using.\n  introv H N.\n  applys~ get_remove H. \nQed.\n\nLemma get_middle_eq_inv : forall x E1 E2 v1 v2,\n  get x (E1 & x ~ v2 & E2) = Some v1 ->\n  ok (E1 & x ~ v2 & E2) ->\n  v1 = v2.\nProof using.\n  introv H O. lets [? ?]: ok_middle_inv O.\n  forwards~ M: get_concat_left_inv H.\n  applys~ get_push_eq_inv M.\nQed.\n\nLemma get_middle_inv : forall x1 v1 x2 v2 E1 E2,\n  get x1 (E1 & x2 ~ v2 & E2) = Some v1 ->\n     (get x1 E2 = Some v1)\n  \\/ (x1 # E2 /\\ x1 = x2 /\\ v1 = v2)\n  \\/ (x1 # E2 /\\ x1 <> x2 /\\ get x1 E1 = Some v1).\nProof using.\n  introv H. lets [?|[? M]]: (get_concat_inv H).\n    left~.\n    right. lets [N|[? N]]: (get_concat_inv M).\n      lets [? ?]: (get_single_inv N). subst~.\n      right. simpl_dom. split~.\nQed.\n\nLemma get_not_middle_inv : forall x v E1 E2 E3,\n  get x (E1 & E2 & E3) = Some v ->\n  x # E2 ->\n     (get x E3 = Some v)\n  \\/ (x # E3 /\\ get x E1 = Some v).\nProof using.\n  introv H F. lets [?|[? M]]: (get_concat_inv H).\n    left~.\n    right. forwards~ N: (get_concat_left_inv M).\nQed.\n\nLemma fv_in_values_get : forall y fv x v E,\n  get x E = Some v -> y \\notin fv_in_values fv E -> y \\notin fv v.\nProof using.\n  unfold fv_in_values. introv H.\n  induction E using env_ind; introv M.\n  false. apply get_empty_inv with (x:= x) (v:= v); auto.\n  rewrite values_def in M,IHE.\n  rewrite concat_def, single_def in M. rew_list in M. simpl in M.\n  lets [[? ?]|[? ?]]: (get_push_inv H); subst~.\nQed.\n\nEnd GetProperties.\n\nLemma ok_contradict:\n  forall A (d : env A) alpha0 k' k, \n  ok (d & alpha0 ~ k') ->\n  get alpha0 d  = Some k ->\n  False.\nProof.\n  introv okd getd.\n  induction d using env_ind.\n  rewrite get_empty in getd.\n  inversion getd.\n  destruct(classicT(x = alpha0)); subst.\n  apply ok_push_inv  in okd.\n  inversion okd.\n  unfolds in H0.\n  unfolds in H0.\n  rewrite dom_push in H0.\n  contradict H0.\n  rewrite in_union.\n  left.\n  apply in_singleton_self.\n  applys IHd; auto.\n  rewrite get_push in getd.\n  auto.\nQed.\n\nLemma get_strength:\n  forall A alpha (d : env A) k, \n    get alpha d = Some k -> \n    forall alpha0 k',\n      ok (d & alpha0 ~ k') ->\n      get alpha (d & alpha0 ~ k') = Some k.\nProof.\n  intros.\n  inversion H0.\n  apply empty_push_inv in H2.\n  inversion H2.\n  rewrite get_push.\n  case_var*.\n  apply eq_inversion_env in H1.\n  inversions H1.\n  inversions H5.\n  apply ok_contradict with (k:= k) in H0; auto.\n  inversion H0.\n  apply eq_inversion_env in H1.\n  inversions* H1.\nQed.\nLtac get_strength:=\n  match goal with \n  | H: get ?alpha ?d = Some ?k |-\n    get ?alpha (?d & _ ~ _) = Some ?k\n    => apply* get_strength\nend.\nHint Extern 2 (get _ (_ & _ ~ _) = Some _) => try get_strength.\n\nLemma get_middle_strength:\n  forall A alpha0 (d : env A) alpha k d' k', \n    alpha0 <> alpha ->\n    get alpha0 (d & alpha ~ k & d') = Some k' ->\n    get alpha0 (d & d') = Some k'.\nAdmitted.\n\nLemma get_middle_k:\n  forall A (d : env A) alpha k d',\n    ok (d & alpha ~ k & d') ->\n    forall k', \n      get alpha (d & alpha ~ k & d') = Some k' ->\n      k = k'.\nAdmitted.\n\n", "meta": {"author": "briangmilnes", "repo": "CycloneCoqSemantics", "sha": "190c0fc57d5aebfde244efb06a119f108de7a150", "save_path": "github-repos/coq/briangmilnes-CycloneCoqSemantics", "path": "github-repos/coq/briangmilnes-CycloneCoqSemantics/CycloneCoqSemantics-190c0fc57d5aebfde244efb06a119f108de7a150/4.6/Cyclone_Get_Lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.23410979016658173}}
{"text": "(* Copyright (c) 2012-2015, Robbert Krebbers. *)\n(* This file is distributed under the terms of the BSD license. *)\nRequire Export memory_separation expression_eval.\n\nLemma expr_eval_subseteq `{EnvSpec K} Γ Δ ρ m1 m2 e ν τlr :\n  ✓ Γ → ✓{Γ,Δ} m1 → ✓{Δ}* ρ → (Γ,Δ,ρ.*2) ⊢ e : τlr →\n  ⟦ e ⟧ Γ ρ m1 = Some ν → m1 ⊆ m2 → ⟦ e ⟧ Γ ρ m2 = Some ν.\nProof.\n  intros. eapply expr_eval_weaken; eauto using cmap_subseteq_index_alive,\n    mem_lookup_subseteq, mem_forced_subseteq.\nQed.\n", "meta": {"author": "robbertkrebbers", "repo": "ch2o", "sha": "1afb3f615db053b741341e9bfd1d5c65bddea641", "save_path": "github-repos/coq/robbertkrebbers-ch2o", "path": "github-repos/coq/robbertkrebbers-ch2o/ch2o-1afb3f615db053b741341e9bfd1d5c65bddea641/axiomatic/expression_eval_separation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2341097901665817}}
{"text": "From Coq Require Import Strings.String Logic.FunctionalExtensionality.\nFrom Rupicola.Lib Require Import Core.\n\nSet Implicit Arguments.\n\nClass Monad (M: Type -> Type) :=\n  { mret {A} : A -> M A;\n    mbind {A B} : M A -> (A -> M B) -> M B;\n    mbindn {A B} (vars: list string) (ma: M A) (kA: A -> M B) : M B :=\n      mbind ma kA;\n\n    mbind_mret {A} (ma: M A) : mbind ma mret = ma;\n    mret_mbind {A B} a (k: A -> M B) : mbind (mret a) k = k a;\n    mbind_mbind {A B C} ma (ka: A -> M B) (kb: B -> M C) :\n      mbind (mbind ma ka) kb = mbind ma (fun a => mbind (ka a) kb);\n\n    mbindn_mret {A} vars (ma: M A) : mbindn vars ma mret = ma :=\n      mbind_mret _;\n    mret_mbindn {A B} vars a (k: A -> M B) : mbindn vars (mret a) k = nlet vars a k :=\n      mret_mbind _ _;\n    mbindn_mbindn {A B C} varsa varsb ma (ka: A -> M B) (kb: B -> M C) :\n      mbindn varsb (mbindn varsa ma ka) kb = mbindn varsa ma (fun a => mbindn varsb (ka a) kb) :=\n      mbind_mbind _ _ _;\n  }.\n\nArguments mret : simpl never.\nArguments mbind : simpl never.\nArguments mbindn : simpl never.\n\nModule Free.\n  Section Free.\n    Context {F: Type -> Type}.\n\n    Inductive M (A: Type) : Type :=\n    | Pure (a: A) : M A\n    | Impure X (f: F X) (k: X -> M A) : M A.\n\n    Definition Call {A} (f: F A) := Impure f (@Pure _).\n\n    Definition ret {A} (a: A) : M A := Pure a.\n\n    Fixpoint bind {A B} (f: M A) (kA: A -> M B) : M B :=\n      match f with\n      | Pure a => kA a\n      | Impure f kX => Impure f (fun x => bind (kX x) kA)\n      end.\n\n    Ltac s :=\n      simpl; eauto using f_equal, FunctionalExtensionality.functional_extensionality.\n\n    Global Program Instance MonadM : Monad M :=\n      {| mret := @ret;\n         mbind := @bind |}.\n    Obligation 1. Proof. induction ma; s. Qed.\n    Obligation 3. Proof. induction ma; s. Qed.\n\n    Context {M': Type -> Type} {MM': Monad M'}.\n    Context (interpF: forall {A}, F A -> M' A).\n\n    Fixpoint interp {A: Type} (f: M A) : M' A :=\n      match f with\n      | Pure a => mret a\n      | Impure f k => mbind (@interpF _ f) (fun x => interp (k x))\n      end.\n\n    Lemma interp_mbind {A B} (ma: M A) (k: A -> M B) :\n      mbind (M := M') (interp ma) (fun a => interp (k a)) =\n      interp (mbind (M := M) ma k).\n    Proof.\n      induction ma; simpl; intros.\n      all: repeat rewrite ?mret_mbind, ?mbind_mret, ?mbind_mbind; s.\n    Qed.\n\n    Lemma interp_mbindn {A B} vars (ma: M A) (k: A -> M B) :\n      mbindn vars (M := M') (interp ma) (fun a => interp (k a)) =\n      interp (mbindn vars (M := M) ma k).\n    Proof. apply interp_mbind. Qed.\n  End Free.\nEnd Free.\n\n#[export] Hint Extern 2 (IsRupicolaBinding (mbindn (A := ?A) ?vars _ _)) => exact (RupicolaBinding A vars) : typeclass_instances.\n\n#[global]\nHint Rewrite @mbindn_mbindn @mret_mbindn : compiler_cleanup.\n", "meta": {"author": "mit-plv", "repo": "rupicola", "sha": "3f59b3d2404ce425ddf4fd55ad2314996a573dc3", "save_path": "github-repos/coq/mit-plv-rupicola", "path": "github-repos/coq/mit-plv-rupicola/rupicola-3f59b3d2404ce425ddf4fd55ad2314996a573dc3/src/Rupicola/Lib/Monads.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2341097901665817}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.nest2.\n\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nLocal Open Scope logic.\n\nDefinition t_struct_b := Tstruct _b noattr.\n\nDefinition get_spec :=\n DECLARE _get\n  WITH v : reptype' t_struct_b, gv: globals\n  PRE  []\n        PROP ()\n        PARAMS() GLOBALS (gv)\n        SEP(data_at Ews t_struct_b (repinj _ v) (gv _p))\n  POST [ tint ]\n         PROP()\n         RETURN (Vint (snd (snd v)))\n         SEP (data_at Ews t_struct_b (repinj _ v) (gv _p)).\n\nDefinition get_spec' :=\n DECLARE _get\n  WITH v : (int * (float * int))%type, gv: globals\n  PRE  []\n        PROP ()\n        PARAMS() GLOBALS (gv)\n        SEP(data_at Ews t_struct_b (repinj t_struct_b v) (gv _p))\n  POST [ tint ]\n         PROP()\n         RETURN (Vint (snd (snd v)))\n         SEP (data_at Ews t_struct_b (repinj t_struct_b v) (gv _p)).\n\nDefinition update22 (i: int) (v: reptype' t_struct_b) : reptype' t_struct_b :=\n   (fst v, (fst (snd v), i)).\n\nDefinition set_spec :=\n DECLARE _set\n  WITH i : int, v : reptype' t_struct_b, gv: globals\n  PRE  [ tint ]\n         PROP  ()\n         PARAMS (Vint i) GLOBALS (gv)\n         SEP   (data_at Ews t_struct_b (repinj _ v) (gv _p))\n  POST [ tvoid ]\n         PROP() RETURN()\n        SEP(data_at Ews t_struct_b (repinj _ (update22 i v)) (gv _p)).\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [get_spec; set_spec]).\n\nLemma body_get:  semax_body Vprog Gprog f_get get_spec.\nProof.\nstart_function.\nsimpl in v.\nunfold_repinj.\nTime forward. (* 5.989 sec  -> 2.6 -> 1.5 *)\nTime forward. (* 11.1118 sec -> 7.5 *)\nTime Qed.\n\nLemma body_get':  semax_body Vprog Gprog f_get get_spec'.\nProof.\nstart_function.\nsimpl in v.\nunfold_repinj.\nTime forward. (* 5.989 sec  -> 2.6*)\nTime forward. (* 11.1118 sec -> 7.5 *)\nQed.\n\nLemma body_set:  semax_body Vprog Gprog f_set set_spec.\nProof.\n start_function.\nsimpl in v.\n(*destruct v as [a [b c]]; simpl in *. *)\nunfold_repinj.\nTime forward. (* 1.23 sec *)\nentailer!!.\nTime Qed.  (*  28 sec -> 3.45 sec *)\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/verif_nest2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2341097901665817}}
{"text": "From mathcomp Require Import ssreflect seq ssrint ssrfun.  \nFrom Coq.Strings Require Import Ascii String.\nRequire Import Coq.Program.Basics.  \n \nRequire Import Syntax Common State Types State Memory.  \n    \n\nRequire Import Operational.     \n\nOpen Scope string.\n\nDefinition iptr b o := AnyPtr Int64 $ Goodptr Int64 b o.\n\n\nDefinition testfun instr := mk_fun 0 \"main\" nil instr.\nDefinition tproc pid  cont : proc_state := mk_proc_state pid nil nil nil nil nil nil cont nil nil nil.\nDefinition teststate instr := MGood  [:: tproc 0 nil ; tproc 1 [:: instr ] ]\n                                     [:: testfun instr].\nDefinition empty2 instr := MGood [:: tproc 0 nil ; tproc 1 nil ] [:: testfun instr].\n\nTheorem test_skip:  ss_reduce (teststate Skip) (empty2 Skip).\n    by eapply ( ss_skip _ _ 1). Qed.\n\nImport Relation_Operators.\n\nTheorem ss_implies_bs s s': ss_reduce s s' -> bs_reduce s s'.\n  move=> H.\n  eapply rt1n_trans.\n  eapply H.\n  eapply rt1n_refl.\nQed.\n\nTheorem test_skip_bs: bs_reduce (teststate Skip) (empty2 Skip).\n  by eapply ss_implies_bs ; eapply (ss_skip _ _ 1).\nQed.\n\nDefinition reduce_interp s := ss_reduce s (interpret_ss s 1).\n\n\n\n\n\n(*** TESTS ***)\n\n\nTheorem test_skip': reduce_interp (teststate Skip).\n  by eapply (ss_skip _ _ 1).\nQed.  \n\nTheorem test_alloc_anon: reduce_interp (teststate (Alloc Stack Int64 None 1)).\n    by eapply (ss_alloc_anon _ _ 1).\nQed.\n\nTheorem test_alloc: reduce_interp (teststate (Alloc Stack Int64 (Some \"hey\") 1)).\n    by eapply (ss_alloc _ _ 1).\nQed.\n\nDefinition prog_if_true := If (Lit (ValueI64 (Posz 4))) (Alloc Stack Int64 None 1) (Alloc Stack Int64 None 2).\n\nTheorem test_if_true: reduce_interp (teststate prog_if_true).\n    by eapply (ss_if_true _ _ 1).\nQed.\n\nCompute interpret_ss (teststate prog_if_true) 1.\n\nDefinition prog_if_false := If (Lit (ValueI8 (Posz 0))) (Alloc Stack Int64 None 1) (Alloc Stack Int64 None 2).\n\nTheorem test_if_false: reduce_interp (teststate prog_if_false).\n    by eapply (ss_if_false _ _ 1).\nQed.\n\nDefinition prog_while_true := While (Lit (ValueI64 (Posz 1))) (Alloc Stack Int64 None 0).\nDefinition prog_while_false := While (Lit (ValueI64 (Posz 0))) (Alloc Stack Int64 None 0).\n\nTheorem test_while_true: reduce_interp (teststate prog_while_true).\n    by eapply (ss_while_true _ _ 1).\nQed.\n\n\nTheorem test_while_false: reduce_interp (teststate prog_while_false).\n    by eapply (ss_while_false _ _ 1).\nQed.\n\nTheorem test_codeblock: reduce_interp (teststate $ CodeBlock [:: Alloc Stack Int64 None 0 ] ).\n    by eapply (ss_codeblock _ _ 1).\nQed.\n\nDefinition state_with_mem := interpret_ss (teststate $ Alloc Stack Int64 (Some \"x\") 1) 1.\n\nDefinition mix_statement ms pid stat := ms_mod_proc pid (ps_mod_cont (cons stat)) ms.\n\nCompute  mix_statement state_with_mem 1 $ Assign (Lit (ValuePtr (AnyPtr Int64 (Goodptr Int64 0 0)))) (Lit (ValueI64 (Posz 11))).\nCompute interpret_ss  ( mix_statement state_with_mem 1 $ Assign (Lit (ValuePtr (AnyPtr Int64 (Goodptr Int64 0 0)))) (Lit (ValueI64 (Posz 11)))) 1.\n\nTheorem test_assign: reduce_interp (mix_statement state_with_mem 1 $ Assign (Lit (ValuePtr (AnyPtr Int64 (Goodptr Int64 0 0)))) (Lit (ValueI64 (Posz 11)))).\n  by eapply (ss_assign _ _ 1).\nQed.\n\nTheorem test_assign_type_conv: reduce_interp (mix_statement state_with_mem 1 $ Assign (Lit (ValuePtr (AnyPtr Int32 (Goodptr _ 0 0)))) (Lit (ValueI64 (Posz 11)))).\n  by eapply (ss_assign _ _ 1).\nQed.\n\nDefinition simple_state pid vars mem cont := mk_proc_state pid vars nil nil nil nil mem cont nil nil nil.\n\nDefinition call_state := MGood [::\n                                  simple_state 0 nil nil nil;\n                                 simple_state 1 nil nil [:: Call \"f\" nil] \n                               ] [:: mk_fun 0 \"main\" nil Skip;\n                                   mk_fun 1 \"f\" nil $ Alloc Stack Int64 (Some \"x\") 1 ].\n\nTheorem test_call: reduce_interp call_state.\n   by eapply (ss_call _ _ 1).\nQed.\n\nTheorem test_enter: reduce_interp (teststate Enter).\n by eapply (ss_enter _ _ 1).\nQed.\n\nDefinition LocVarBlock id t v := mk_block Stack id (size_of t) t [:: v].\nDefinition LocVarBlockInt64 id v := LocVarBlock id Int64 (ValueI64 v).\n\nDefinition test_leave_state := MGood\n                                 [::\n                                    simple_state 0 nil nil nil;\n                                   simple_state 1 [:: [:: declare_var \"x\" Int64 0 ] ; [:: declare_var \"y\" Int32 1 ] ]\n                                                [:: LocVarBlockInt64 0 6; LocVarBlockInt64 1 4]\n                                                    [:: Leave] \n                                 ] [:: ].\nCompute interpret_ss test_leave_state 1.\n\nTheorem test_leave: reduce_interp test_leave_state.\n    by  eapply (ss_leave _ _ 1).\nQed.\n\nDefinition pushreg_state := MGood [::\n                                     simple_state 0 nil nil nil;\n                                    simple_state 1 nil [:: LocVarBlockInt64 0 6 ]\n                                                 [::\n                                                    BspPushReg\n                                                    (Lit (ValuePtr (AnyPtr Int32 (Goodptr _ 0 0))))\n                                                    (Lit (ValueI64 (Posz (size_of Int64)))) ]\n                                  ]\n                                  nil.\n\nTheorem test_pushreg: reduce_interp pushreg_state.\n    by eapply (ss_bsp_push _ _ 1).\nQed.\n\nCompute interpret_ss pushreg_state 1.\n\nDefinition popreg_state := MGood [::\n                                     simple_state 0 nil nil nil;\n                                    simple_state 1 nil [:: LocVarBlockInt64 0 6 ]\n                                                 [::\n                                                    BspPopReg\n                                                    (Lit (ValuePtr (AnyPtr Int32 (Goodptr _ 0 0)))) ]\n                                  ]\n                                  nil.\n\nTheorem test_popreg: reduce_interp popreg_state.\n    by eapply (ss_bsp_pop _ _ 1).\nQed.\n\nDefinition IntPtr b o:=  AnyPtr Int64 ( Goodptr _ b o).\nDefinition VIntPtr b o := ValuePtr $ IntPtr b o.\n\nTheorem test_get: reduce_interp ( teststate $\n                                             BspGet\n                                             (Lit $ ValueI64 0)\n                                             (Lit $ VIntPtr 0 0)\n                                             (Lit $ ValueI64 0)\n                                             (Lit $ VIntPtr 0 0)\n                                             (Lit $ ValueI64 (Posz 0))).\n    by  eapply (ss_bsp_get _ _ 1).\nQed.\n\nNotation \"{* b o : t }\" := (AnyPtr t (Goodptr t b o)) (at level 55, no associativity).\n\nDefinition test_put_state := MGood\n                                     [::\n                                        mk_proc_state\n                                        0\n                                        nil\n                                        nil\n                                        [:: nil ; nil ]\n                                        nil\n                                        nil\n                                        [:: LocVarBlockInt64 0 10; LocVarBlockInt64 1 11]\n                                        nil\n                                        [:: ( IntPtr 0 0, 8 )]\n                                        nil\n                                        nil ;\n                                       mk_proc_state\n                                         1\n                                         nil\n                                         nil\n                                         [:: nil; nil]\n                                         nil\n                                         nil\n                                         [:: LocVarBlockInt64 0 4; LocVarBlockInt64 1 5; LocVarBlockInt64 2 6 ]\n                                         [:: BspPut (Lit $ ValueI64 0)\n                                            (Lit $ VIntPtr 2 0)\n                                            (Lit $ ValueI64 0)\n                                            (Lit $ VIntPtr 1 0)\n                                            (Lit $ ValueI64 8) ]\n                                        \n                                         [:: ( IntPtr 2 0, 8 )]\n\n                                         nil\n                                         nil ] nil.     \n\nCompute interpret_ss test_put_state 1.\n\nDefinition test_put: reduce_interp test_put_state.\n  by eapply (ss_bsp_put _ _ 1).\nQed.\n\nTheorem test_sync_end1 : ss_reduce (MGood [::\n                                             simple_state 0 nil nil  [:: BspSync] ;\n                                            simple_state 1 nil nil [:: BspSync]\n                                          ]\n                                          nil)\n                                   (MGood [::\n                                             simple_state 0 nil nil  nil ;\n                                            simple_state 1 nil nil nil\n                                          ]\n                                          nil).\nby  eapply (ss_sync_end ).\nQed.\n(*\nDefinition test_sync_pop_state :=\n  ms_mod_proc 1 (\n                ps_mod_queue_pop (cons $ Pop $  IntPtr 0 0 )\nc                                 \\o ps_mod_reg_loc ( cons ( IntPtr 0 0 , 8) )\n                                 \\o ps_mod_cont (cons BspSync)\n                                 \\o ps_mod_mem (const \n              )\n$  empty_state 2.*)\n\nDefinition test_sync_pop_state := MGood [::\n                                              mk_proc_state\n                                                0\n                                                nil\n                                                nil\n                                                nil\n                                                [:: Pop $ IntPtr 0 0]\n                                                nil\n                                                [:: LocVarBlockInt64 0 10; LocVarBlockInt64 1 11]\n                                                [:: BspSync]\n                                                [:: ( IntPtr 0 0, 8 )]\n                                                nil\n                                                nil ;\n                                             mk_proc_state\n                                                1\n                                                nil\n                                                nil\n                                                nil\n                                                [:: Pop $ IntPtr 1 0]\n                                                nil\n                                                [:: LocVarBlockInt64 0 11; LocVarBlockInt64 1 4; LocVarBlockInt64 2 13 ]\n                                                [:: BspSync]\n                                                [:: ( IntPtr 1 0, 8 )]\n                                                nil\n                                                nil ] nil.\n\nTheorem test_sync_pop : ss_reduce test_sync_pop_state  (apply_pop_regs_one test_sync_pop_state).\n  eapply (ss_sync_pop _ _); try done.\nQed.\n\nDefinition test_sync_push_state := MGood\n                                     [::\n                                        mk_proc_state\n                                        0\n                                        nil\n                                        nil\n                                        nil\n                                        nil\n                                        [:: Push (IntPtr 0 0) (size_of Int64) ]\n                                        [:: LocVarBlockInt64 0 10; LocVarBlockInt64 1 11]\n                                        [:: BspSync]\n                                        nil\n                                        nil\n                                        nil ;\n                                       mk_proc_state\n                                         1\n                                         nil\n                                         nil\n                                         nil\n                                         nil\n                                         [:: Push (IntPtr 1 0) (size_of Int64) ]\n                                         [:: LocVarBlockInt64 0 11; LocVarBlockInt64 1 4; LocVarBlockInt64 2 13 ]\n                                         [:: BspSync]\n                                         nil\n                                         nil\n                                         nil ] nil.\n\nDefinition test_sync_push_state' := MGood\n                                     [::\n                                        mk_proc_state\n                                        0\n                                        nil\n                                        nil\n                                        nil\n                                        nil\n                                        nil\n                                        [:: LocVarBlockInt64 0 10; LocVarBlockInt64 1 11]\n                                        [:: BspSync]\n                                        [:: ( IntPtr 0 0, 8 )]\n                                        nil\n                                        nil ;\n                                       mk_proc_state\n                                         1\n                                         nil\n                                         nil\n                                         nil\n                                         nil\n                                         nil\n                                         [:: LocVarBlockInt64 0 11; LocVarBlockInt64 1 4; LocVarBlockInt64 2 13 ]\n                                         [:: BspSync]\n                                         [:: ( IntPtr 1 0, 8 )]\n\n                                         nil\n                                         nil ] nil.\n\n\nTheorem test_sync_push: ss_reduce test_sync_push_state test_sync_push_state'.\n    by eapply (ss_sync_push _ _). Qed.\n\nDefinition test_sync_get_state := MGood\n                                     [::\n                                        mk_proc_state\n                                        0\n                                        nil\n                                        [:: Get _ 1 (Goodptr Int64 0 0) (Posz 0) (Goodptr Int64 0 0) 8 ]\n                                        nil\n                                        nil\n                                        nil\n                                        [:: LocVarBlockInt64 0 10; LocVarBlockInt64 1 11]\n                                        [:: BspSync]\n                                        [:: ( IntPtr 0 0, 8 )]\n                                        nil\n                                        nil ;\n                                       mk_proc_state\n                                         1\n                                         nil\n                                         nil\n                                         nil\n                                         nil\n                                         nil\n                                         [:: LocVarBlockInt64 0 4; LocVarBlockInt64 1 5; LocVarBlockInt64 2 6 ]\n                                         [:: BspSync]\n                                         [:: ( IntPtr 1 0, 8 )]\n\n                                         nil\n                                         nil ] nil.     \nDefinition test_sync_get_state':= MGood\n                                     [::\n                                        mk_proc_state\n                                        0\n                                        nil\n                                        [:: Get _ 1 (Goodptr Int64 0 0) (Posz 0) (Goodptr Int64 0 0) 8 ]\n                                        nil\n                                        nil\n                                        nil\n                                        [:: LocVarBlockInt64 0 10; LocVarBlockInt64 1 11]\n                                        [:: BspSync]\n                                        [:: ( IntPtr 0 0, 8 )]\n                                        nil\n                                        nil ;\n                                       mk_proc_state\n                                         1\n                                         nil\n                                         nil\n                                         nil\n                                         nil\n                                         nil\n                                         [:: LocVarBlockInt64 0 4; LocVarBlockInt64 1 5; LocVarBlockInt64 2 6 ]\n                                         [:: BspSync]\n                                         [:: ( IntPtr 1 0, 8 ) ]\n\n                                         nil\n                                         nil ] nil.     \n\n\nTheorem test_sync_get : ss_reduce  test_sync_get_state test_sync_get_state'.\n    by eapply (ss_sync_get _ _ 0).\nQed.\n\nDefinition test_sync_put_state :=  MGood\n                                     [::\n                                        mk_proc_state\n                                        0\n                                        nil\n                                        nil\n                                        [:: nil; [:: Put  _ (ValueI64 6) (Goodptr Int64 0 0) 0 ]]\n                                        nil\n                                        nil\n                                        [:: LocVarBlockInt64 0 10; LocVarBlockInt64 1 11]\n                                        [:: BspSync]\n                                        [:: ( IntPtr 0 0, 8 )]\n                                        nil\n                                        nil ;\n                                       mk_proc_state\n                                         1\n                                         nil\n                                         nil\n                                         nil\n                                         nil\n                                         nil\n                                         [:: LocVarBlockInt64 0 4; LocVarBlockInt64 1 5; LocVarBlockInt64 2 6 ]\n                                         [:: BspSync]\n                                         [:: ( IntPtr 1 0, 8 ) ]\n\n                                         nil\n                                         nil ] nil.\nDefinition test_sync_put_state' :=  MGood\n                                     [::\n                                        mk_proc_state\n                                        0\n                                        nil\n                                        nil\n                                        [:: nil; nil]\n                                        nil\n                                        nil\n                                        [:: LocVarBlockInt64 0 6; LocVarBlockInt64 1 11]\n                                        [:: BspSync]\n                                        [:: ( IntPtr 0 0, 8 )]\n                                        nil\n                                        nil ;\n                                       mk_proc_state\n                                         1\n                                         nil\n                                         nil\n                                         nil\n                                         nil\n                                         nil\n                                         [:: LocVarBlockInt64 0 4; LocVarBlockInt64 1 5; LocVarBlockInt64 2 6 ]\n                                         [:: BspSync]\n                                         [:: ( IntPtr 1 0, 8 ) ]\n\n                                         nil\n                                         nil ] nil. \n\nTheorem test_sync_put : ss_reduce test_sync_put_state test_sync_put_state'.\nby  eapply (ss_sync_put _ _ 0 1).\nQed.\n\n\n\nDefinition test_hpput_state :=  MGood [::\n                                        mk_proc_state\n                                        0\n                                        nil\n                                        nil\n                                        [:: nil ; nil ]\n                                        nil\n                                        nil\n                                        [:: LocVarBlockInt64 0 10; LocVarBlockInt64 1 11]\n                                        nil\n                                        [:: ( IntPtr 0 0, 8 )]\n                                        nil\n                                        nil ;\n                                       mk_proc_state\n                                         1\n                                         nil\n                                         nil\n                                         [:: nil; nil]\n                                         nil\n                                         nil\n                                         [:: LocVarBlockInt64 0 4; LocVarBlockInt64 1 5; LocVarBlockInt64 2 6 ]\n                                         [:: BspHpPut (Lit $ ValueI64 0)\n                                            (Lit $ VIntPtr 2 0)\n                                            (Lit $ ValueI64 0)\n                                            (Lit $ VIntPtr 1 0)\n                                            (Lit $ ValueI64 8) ]\n                                        \n                                         [:: ( IntPtr 2 0, 8 )]\n\n                                         nil\n                                         nil ] nil.     \n\nTheorem test_hpput: reduce_interp test_hpput_state.\n    by  eapply (ss_bsp_hpput _ _ 1).\nQed.\n\n\n\n\n\n\nDefinition test_hpget_state :=  MGood [::\n                                        mk_proc_state\n                                        0\n                                        nil\n                                        nil\n                                        [:: nil ; nil ]\n                                        nil\n                                        nil\n                                        [:: LocVarBlockInt64 0 10; LocVarBlockInt64 1 11]\n                                        nil\n                                        [:: ( IntPtr 0 0, 8 )]\n                                        nil\n                                        nil ;\n                                       mk_proc_state\n                                         1\n                                         nil\n                                         nil\n                                         [:: nil; nil]\n                                         nil\n                                         nil\n                                         [:: LocVarBlockInt64 0 4; LocVarBlockInt64 1 5; LocVarBlockInt64 2 6 ]\n                                         [:: BspHpGet (Lit $ ValueI64 0)\n                                            (Lit $ VIntPtr 2 0)\n                                            (Lit $ ValueI64 0)\n                                            (Lit $ VIntPtr 1 0)\n                                            (Lit $ ValueI64 8) ]\n                                        \n                                         [:: ( IntPtr 2 0, 8 )]\n\n                                         nil\n                                         nil ] nil.     \n\nCompute interpret_ss test_hpget_state 1.\n\nTheorem test_hpget: reduce_interp test_hpget_state.\n  by  eapply (ss_bsp_hpget _ _ 1); try done.\nQed.\n\n  \n\n\nDefinition test_hpput_sync: ss_reduce ( MGood [::\n                                                 mk_proc_state 0 nil nil nil nil nil\n                                                 [:: LocVarBlockInt64 0 10; LocVarBlockInt64 1 11;\n                                                  LocVarBlockInt64 2 12; LocVarBlockInt64 3 13 ]\n                                                 [:: BspSync]\n                                                 [:: (iptr 0 0, 8 ) ]\n                                                 [:: nil; [::\n                                                             HpPutQuery\n                                                             (iptr 1 0)\n                                                             (iptr 0 0)\n                                                             0] ]\n                                                 nil ;\n                                                \n                                                 mk_proc_state 1 nil nil nil nil nil\n                                                 [:: LocVarBlockInt64 0 20; LocVarBlockInt64 1 21;\n                                                  LocVarBlockInt64 2 22; LocVarBlockInt64 3 23 ]\n                                                 [:: BspSync]\n                                                 [:: ( iptr 1 0 , 8 ) ]\n                                                 [:: nil; nil]\n                                                 nil \n                                              ] [::] )\n                                      (\n                                        MGood [::\n                                                 mk_proc_state 0 nil nil nil nil nil\n                                                 [:: LocVarBlockInt64 0 21; LocVarBlockInt64 1 11;\n                                                  LocVarBlockInt64 2 12; LocVarBlockInt64 3 13 ]\n                                                 [:: BspSync]\n                                                 [:: ( iptr 0 0, 8 ) ]\n                                                 [:: nil; [::] ]\n                                                 nil ;\n                                                \n                                                 mk_proc_state 1 nil nil nil nil nil\n                                                 [:: LocVarBlockInt64 0 20; LocVarBlockInt64 1 21;\n                                                  LocVarBlockInt64 2 22; LocVarBlockInt64 3 23 ]\n                                                 [:: BspSync]\n                                                 [:: ( iptr 1 0 , 8 ) ]\n                                                 [:: nil; nil]\n                                                 nil \n      ] [::] ).\n by eapply (ss_sync_hpput _ _ 0 1).\nQed.\n\n\nDefinition test_hpget_sync: ss_reduce ( MGood [::\n                                                 mk_proc_state 0 nil nil nil nil nil\n                                                 [:: LocVarBlockInt64 0 10; LocVarBlockInt64 1 11;\n                                                  LocVarBlockInt64 2 12; LocVarBlockInt64 3 13 ]\n                                                 [:: BspSync]\n                                                 [:: (iptr 0 0, 8 ) ]\n                                                 nil\n                                                 [:: nil; [::\n                                                             HpGetQuery\n                                                             (iptr 1 0)\n                                                             (iptr 0 0)\n                                                             0] ]\n                                                 ;\n                                                \n                                                 mk_proc_state 1 nil nil nil nil nil\n                                                 [:: LocVarBlockInt64 0 20; LocVarBlockInt64 1 21;\n                                                  LocVarBlockInt64 2 22; LocVarBlockInt64 3 23 ]\n                                                 [:: BspSync]\n                                                 [:: ( iptr 1 0 , 8 ) ]\n                                                 nil\n                                                 nil \n                                              ] [::] )\n                                      (\n                                        MGood [::\n                                                 mk_proc_state 0 nil nil nil nil nil\n                                                 [:: LocVarBlockInt64 0 21; LocVarBlockInt64 1 11;\n                                                  LocVarBlockInt64 2 12; LocVarBlockInt64 3 13 ]\n                                                 [:: BspSync]\n                                                 [:: ( iptr 0 0, 8 ) ]\n                                                 nil\n                                                 [:: nil; nil]  ;\n                                                \n                                                 mk_proc_state 1 nil nil nil nil nil\n                                                 [:: LocVarBlockInt64 0 20; LocVarBlockInt64 1 21;\n                                                  LocVarBlockInt64 2 22; LocVarBlockInt64 3 23 ]\n                                                 [:: BspSync]\n                                                 [:: ( iptr 1 0 , 8 ) ]\n                                                 nil\n                                                 nil\n      ] [::] ).\n  by eapply (ss_sync_hpget _ _ 0 1).\nQed.\n", "meta": {"author": "sayon", "repo": "mini-c", "sha": "802cd66231053b9835ad83794ebd364224839432", "save_path": "github-repos/coq/sayon-mini-c", "path": "github-repos/coq/sayon-mini-c/mini-c-802cd66231053b9835ad83794ebd364224839432/bsp_pred/TestOperational.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2341097901665817}}
{"text": "Require Import Bool.\nRequire Import Word.\nRequire Import Balloc.\nRequire Import BFile Bytes Rec Inode.\nRequire Import String.\nRequire Import Pred.\nRequire Import Arith.\nRequire Import List ListUtils.\nRequire Import FunctionalExtensionality.\nRequire Import AsyncDisk.\nRequire Import DirCache.\nRequire Import DirTreeDef.\nRequire Import FSLayout.\nRequire Import GenSepN.\nRequire Import SepAuto.\nRequire Import DirTreePred.\n\n\nImport ListNotations.\n\nSet Implicit Arguments.\n\n  (**\n   *\n   * The dirtree representation invariant \n   *\n   * [F] represents the other parts of the file system above [tree],\n   * in cases where [tree] is a subdirectory somewhere in the tree.\n   *)\n\n  Definition rep fsxp F tree ilist frees ms sm :=\n    (exists bflist freeinodes freeinode_pred,\n     BFILE.rep (FSXPBlockAlloc fsxp) sm fsxp.(FSXPInode) bflist ilist frees\n        (BFILE.MSAllocC ms) (BFILE.MSCache ms) (BFILE.MSICache ms) (BFILE.MSDBlocks ms) *\n     IAlloc.rep BFILE.freepred fsxp freeinodes freeinode_pred (IAlloc.Alloc.mk_memstate (BFILE.MSLL ms) (BFILE.MSIAllocC ms)) *\n     [[ (F * tree_pred fsxp tree * freeinode_pred)%pred (list2nmem bflist) ]]\n    )%pred.\n\n  Theorem rep_length : forall fsxp F tree ilist frees ms sm,\n    rep fsxp F tree ilist frees ms sm =p=>\n    (rep fsxp F tree ilist frees ms sm *\n     [[ length ilist = ((INODE.IRecSig.RALen (FSXPInode fsxp)) * INODE.IRecSig.items_per_val)%nat ]])%pred.\n  Proof.\n    unfold rep; intros.\n    norml; unfold stars; simpl.\n    rewrite BFILE.rep_length_pimpl at 1.\n    cancel.\n  Qed.\n\n  Theorem dirtree_update_free : forall tree fsxp F F0 ilist freeblocks ms sm v bn m flag,\n    (F0 * rep fsxp F tree ilist freeblocks ms sm)%pred (list2nmem m) ->\n    BFILE.block_is_unused (BFILE.pick_balloc freeblocks flag) bn ->\n    (F0 * rep fsxp F tree ilist freeblocks ms sm)%pred (list2nmem (updN m bn v)).\n  Proof.\n    intros.\n    unfold rep in *.\n    destruct_lift H.\n    eapply pimpl_apply; [ | eapply BFILE.rep_safe_unused; eauto; pred_apply; cancel ].\n    cancel.\n  Qed.\n\n  Theorem dirtree_rep_used_block_eq : forall pathname F0 tree fsxp F ilist freeblocks ms inum off bn m sm f,\n    (F0 * rep fsxp F tree ilist freeblocks ms sm)%pred (list2nmem m) ->\n    find_subtree pathname tree = Some (TreeFile inum f) ->\n    BFILE.block_belong_to_file ilist bn inum off ->\n    selN (DFData f) off ($0, nil) = selN m bn ($0, nil).\n  Proof.\n    intros.\n\n    unfold rep in *.\n    destruct_lift H.\n\n    erewrite <- BFILE.rep_used_block_eq with (m := m).\n    2: pred_apply; cancel.\n    2: eauto.\n    f_equal.\n    f_equal.\n\n    rewrite subtree_extract in * by eassumption.\n    simpl in *.\n    apply eq_sym.\n    eapply BFILE.rep_used_block_eq_Some_helper.\n\n    destruct_lifts.\n    assert (inum < Datatypes.length dummy) as Hlt by ( eapply list2nmem_inbound; pred_apply; cancel ).\n\n    pose proof (list2nmem_sel_inb dummy BFILE.bfile0 Hlt) as Hx.\n    eapply pimpl_trans in H2; [ | apply pimpl_refl | ].\n    eapply ptsto_valid in H2.\n    rewrite Hx in H2; clear Hx.\n    2: cancel.\n    inversion H2; clear H2.\n    rewrite H4; simpl.\n    auto.\n  Qed.\n\n  Lemma tree_pred_ino_goodSize : forall F Fm xp tree m d frees prd allocc,\n    (Fm * (IAlloc.rep BFILE.freepred xp frees prd allocc))%pred m ->\n    (F * tree_pred xp tree)%pred d ->\n    goodSize addrlen (dirtree_inum tree).\n  Proof.\n    induction tree using dirtree_ind2; simpl; intros.\n    destruct_lift H0.\n    eapply IAlloc.ino_valid_goodSize; eauto.\n    unfold tree_dir_names_pred in H1; destruct_lift H1.\n    eapply IAlloc.ino_valid_goodSize; eauto.\n  Qed.\n\n  Lemma find_subtree_inum_valid : forall F F' xp m s tree inum f,\n    find_subtree s tree = Some (TreeFile inum f)\n    -> (F * tree_pred xp tree * F')%pred m\n    -> IAlloc.ino_valid xp inum.\n  Proof.\n    unfold rep; intros.\n    destruct_lift H0.\n    rewrite subtree_extract in H0 by eauto.\n    simpl in H0; destruct_lift H0; auto.\n  Qed.\n\n  Theorem mscs_same_except_log_rep' : forall mscs1 mscs2 fsxp F tree ilist frees sm,\n    BFILE.mscs_same_except_log mscs1 mscs2 ->\n    rep fsxp F tree ilist frees mscs1 sm =p=> rep fsxp F tree ilist frees mscs2 sm.\n  Proof.\n    unfold BFILE.mscs_same_except_log; unfold rep; intros.\n    intuition msalloc_eq.\n    apply pimpl_refl.\n  Qed.\n\n  Theorem mscs_same_except_log_rep : forall mscs1 mscs2 fsxp F tree ilist frees sm,\n    BFILE.mscs_same_except_log mscs1 mscs2 ->\n    rep fsxp F tree ilist frees mscs1 sm <=p=> rep fsxp F tree ilist frees mscs2 sm.\n  Proof.\n    split; eapply mscs_same_except_log_rep'; eauto.\n    unfold BFILE.mscs_same_except_log in *; intuition eauto.\n  Qed.\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/DirTreeRep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.23409269191848353}}
{"text": "Require Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import Global.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import SimMemory.\nRequire Import SimGlobal.\n\nSet Implicit Arguments.\n\n\nVariant sim_local (lc_src lc_tgt: Local.t): Prop :=\n| sim_local_intro\n    (TVIEW: TView.le (Local.tview lc_src) (Local.tview lc_tgt))\n    (PROMISES: Local.promises lc_src = Local.promises lc_tgt)\n    (RESERVES: Local.reserves lc_src = Local.reserves lc_tgt)\n.\n#[export] Hint Constructors sim_local: core.\n\nGlobal Program Instance sim_local_PreOrder: PreOrder sim_local.\nNext Obligation.\n  ii. destruct x. econs; refl.\nQed.\nNext Obligation.\n  ii. destruct x, y, z. inv H. inv H0. ss. subst.\n  econs; ss. etrans; eauto.\nQed.\n\nLemma sim_local_promises_bot\n      lc_src lc_tgt\n      (SIM: sim_local lc_src lc_tgt):\n  Local.promises lc_src = BoolMap.bot <->\n  Local.promises lc_tgt = BoolMap.bot.\nProof.\n  inv SIM. rewrite PROMISES. ss.\nQed.\n\nLemma sim_local_is_terminal\n      lc_src lc_tgt\n      (SIM: sim_local lc_src lc_tgt):\n  Local.is_terminal lc_src <-> Local.is_terminal lc_tgt.\nProof.\n  exploit sim_local_promises_bot; eauto. i. des.\n  split; i; inv H; eauto.\nQed.\n\nLemma sim_local_internal\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt gl2_tgt\n      e\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (WF1_SRC: Local.wf lc1_src gl1_src)\n      (WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL1_SRC: Global.wf gl1_src)\n      (GL1_TGT: Global.wf gl1_tgt)\n      (STEP_TGT: Local.internal_step e lc1_tgt gl1_tgt lc2_tgt gl2_tgt):\n  exists lc2_src gl2_src,\n    <<STEP_SRC: Local.internal_step e lc1_src gl1_src lc2_src gl2_src >> /\\\n    <<LOCAL2: sim_local lc2_src lc2_tgt>> /\\\n    <<GL2: sim_global gl2_src gl2_tgt>>.\nProof.\n  inv LOCAL1. inv GLOBAL1. inv STEP_TGT.\n  { inv LOCAL. inv PROMISE. esplits; eauto.\n    { econs 1; eauto. econs; eauto. econs; eauto.\n      { rewrite PROMISES. eauto. }\n      { rewrite PROMISES0. eauto. }\n    }\n    { econs; eauto. }\n    { econs; eauto. }\n  }\n  { inv LOCAL. inv RESERVE.\n    hexploit sim_memory_add_exists; eauto. i. des. esplits.\n    { econs 2. econs; eauto. econs; eauto.\n      rewrite RESERVES. eauto.\n    }\n    { econs; eauto. }\n    { econs; eauto. }\n  }\n  { inv LOCAL. inv CANCEL.\n    hexploit Memory.remove_exists.\n    { eapply WF1_SRC. rewrite RESERVES. eapply Memory.remove_get0. eauto. }\n    i. des.\n    hexploit sim_memory_remove; try exact MEMORY; eauto.\n    i. esplits.\n    { econs 3. econs; eauto. econs; eauto.\n      rewrite RESERVES. eauto.\n    }\n    { econs; eauto. }\n    { econs; eauto. }\n  }\nQed.\n\nLemma sim_local_read\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt\n      loc ts val released_tgt ord_src ord_tgt\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_TGT: Global.wf gl1_tgt)\n      (STEP_TGT: Local.read_step lc1_tgt gl1_tgt loc ts val released_tgt ord_tgt lc2_tgt):\n  exists released_src lc2_src,\n    <<REL: View.opt_le released_src released_tgt>> /\\\n    <<STEP_SRC: Local.read_step lc1_src gl1_src loc ts val released_src ord_src lc2_src>> /\\\n    <<LOCAL2: sim_local lc2_src lc2_tgt>>.\nProof.\n  inv LOCAL1. inv GLOBAL1. inv STEP_TGT.\n  exploit sim_memory_get; try apply GET; eauto. i. des.\n  inv MSG. esplits; eauto.\n  - econs; eauto; (try by etrans; eauto).\n    eapply TViewFacts.readable_mon; eauto. apply TVIEW.\n  - econs; eauto. s. apply TViewFacts.read_tview_mon; auto.\n    + apply LC_WF1_TGT.\n    + inv GL_WF1_TGT. inv MEM_CLOSED.\n      exploit CLOSED; eauto. i. des. inv MSG_WF. auto.\nQed.\n\nLemma ord_implb\n      ord_src ord_tgt ord\n      (ORD: Ordering.le ord_src ord_tgt):\n  implb (Ordering.le ord_tgt ord) (Ordering.le ord_src ord).\nProof.\n  destruct ord_src, ord_tgt, ord; ss.\nQed.\n\nLemma sim_local_fulfill\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc ord_src ord_tgt prm2 gprm2\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (FULFILL_TGT: Promises.fulfill lc1_tgt.(Local.promises) gl1_tgt.(Global.promises) loc ord_tgt prm2 gprm2):\n  Promises.fulfill lc1_src.(Local.promises) gl1_src.(Global.promises) loc ord_src prm2 gprm2.\nProof.\n  destruct lc1_src, lc1_tgt, gl1_src, gl1_tgt.\n  inv LOCAL1. inv GLOBAL1. ss. subst.\n  inv FULFILL_TGT; eauto.\nQed.\n\nLemma sim_local_write\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt gl2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (RELM: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF_SRC: View.opt_wf releasedm_src)\n      (RELM_WF_TGT: View.opt_wf releasedm_tgt)\n      (STEP_TGT: Local.write_step lc1_tgt gl1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt gl2_tgt):\n  exists released_src lc2_src gl2_src,\n    <<STEP_SRC: Local.write_step lc1_src gl1_src loc from to val releasedm_src released_src ord_src lc2_src gl2_src>> /\\\n    <<RELEASED: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local lc2_src lc2_tgt>> /\\\n    <<GLOBAL2: sim_global gl2_src gl2_tgt>>.\nProof.\n  inv STEP_TGT.\n  exploit sim_local_fulfill; eauto. intro FULFILL_SRC.\n  assert (RELT_LE:\n   View.opt_le\n     (TView.write_released (Local.tview lc1_src) loc to releasedm_src ord_src)\n     (TView.write_released (Local.tview lc1_tgt) loc to releasedm_tgt ord_tgt)).\n  { apply TViewFacts.write_released_mon; ss.\n    - apply LOCAL1.\n    - apply LC_WF1_TGT.\n  }\n  assert (RELT_WF:\n   View.opt_wf (TView.write_released (Local.tview lc1_src) loc to releasedm_src ord_src)).\n  { unfold TView.write_released. condtac; econs.\n    repeat (try condtac; viewtac; try apply LC_WF1_SRC).\n  }\n  exploit sim_memory_add_exists; try exact WRITE.\n  { econs 1. exact RELT_WF. }\n  { econs 1; try exact RELT_LE; try refl.\n    eapply ord_implb. eassumption.\n  }\n  { apply GLOBAL1. }\n  i. des. esplits.\n  - econs; eauto.\n    eapply TViewFacts.writable_mon; try exact WRITABLE; eauto. apply LOCAL1.\n  - ss.\n  - econs; eauto; s; try apply LOCAL1.\n    apply TViewFacts.write_tview_mon; ss; try apply LOCAL1.\n    apply LC_WF1_TGT.\n  - econs; ss; try apply GLOBAL1.\nQed.\n\nLemma sim_local_update\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc ts1 val1 released1_tgt ord1_src ord1_tgt lc2_tgt\n      from2 to2 val2 released2_tgt ord2_src ord2_tgt lc3_tgt gl3_tgt\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (ORD1: Ordering.le ord1_src ord1_tgt)\n      (ORD2: Ordering.le ord2_src ord2_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF1_SRC: Global.wf gl1_src)\n      (GL_WF1_TGT: Global.wf gl1_tgt)\n      (STEP1_TGT: Local.read_step lc1_tgt gl1_tgt loc ts1 val1 released1_tgt ord1_tgt lc2_tgt)\n      (STEP2_TGT: Local.write_step lc2_tgt gl1_tgt loc from2 to2 val2\n                    released1_tgt released2_tgt ord2_tgt lc3_tgt gl3_tgt):\n  exists released1_src released2_src lc2_src lc3_src gl3_src,\n    <<STEP1_SRC: Local.read_step lc1_src gl1_src loc ts1 val1 released1_src ord1_src lc2_src>> /\\\n    <<STEP2_SRC: Local.write_step lc2_src gl1_src loc from2 to2 val2 \n                   released1_src released2_src ord2_src lc3_src gl3_src>> /\\\n    <<REL1: View.opt_le released1_src released1_tgt>> /\\\n    <<REL2: View.opt_le released2_src released2_tgt>> /\\\n    <<LOCAL3: sim_local lc3_src lc3_tgt>> /\\\n    <<GLOBAL3: sim_global gl3_src gl3_tgt>>.\nProof.\n  exploit sim_local_read; try exact STEP1_TGT; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP1_TGT; eauto. i. des.\n  exploit Local.read_step_future; try exact STEP_SRC; eauto. i. des.\n  hexploit sim_local_write; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_local_fence\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      lc2_tgt gl2_tgt\n      ordr_src ordw_src\n      ordr_tgt ordw_tgt\n      (STEP_TGT: Local.fence_step lc1_tgt gl1_tgt ordr_tgt ordw_tgt lc2_tgt gl2_tgt)\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (LC_WF1_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF1_TGT: Local.wf lc1_tgt gl1_tgt)\n      (ORDR: Ordering.le ordr_src ordr_tgt)\n      (ORDW: Ordering.le ordw_src ordw_tgt):\n  exists lc2_src gl2_src,\n    <<STEP_SRC: Local.fence_step lc1_src gl1_src ordr_src ordw_src lc2_src gl2_src>> /\\\n    <<LOCAL2: sim_local lc2_src lc2_tgt>> /\\\n    <<GLOBAL2: sim_global gl2_src gl2_tgt>>.\nProof.\n  inv GLOBAL1. inv STEP_TGT.\n  esplits; eauto.\n  - econs; eauto. i.\n    erewrite sim_local_promises_bot; eauto.\n  - econs; try apply LOCAL1. s.\n    apply TViewFacts.write_fence_tview_mon; auto; try refl; cycle 1.\n    { eapply TViewFacts.read_fence_future; apply LC_WF1_SRC. }\n    apply TViewFacts.read_fence_tview_mon; auto; try refl.\n    + apply LOCAL1.\n    + apply LC_WF1_TGT.\n  - econs; ss.\n    apply TViewFacts.write_fence_sc_mon; auto; try refl.\n    apply TViewFacts.read_fence_tview_mon; auto; try refl.\n    + apply LOCAL1.\n    + apply LC_WF1_TGT.\nQed.\n\nLemma sim_local_is_racy\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to ord_src ord_tgt\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (RACE_TGT: Local.is_racy lc1_tgt gl1_tgt loc to ord_tgt):\n  <<RACE_SRC: Local.is_racy lc1_src gl1_src loc to ord_src>>.\nProof.\n  inv LOCAL1. inv GLOBAL1.\n  inv RACE_TGT; [econs 1; congr|].\n  exploit sim_memory_get; eauto. i. des. inv MSG0.\n  econs; eauto.\n  - eapply TViewFacts.racy_view_mon; eauto. apply TVIEW.\n  - i. exploit MSG; try by destruct ord_src, ord_tgt; ss.\n    i. subst. destruct na1; ss.\nQed.\n\nLemma sim_local_racy_read\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to val ord_src ord_tgt\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (STEP_TGT: Local.racy_read_step lc1_tgt gl1_tgt loc to val ord_tgt):\n  <<STEP_SRC: Local.racy_read_step lc1_src gl1_src loc to val ord_src>>.\nProof.\n  inv STEP_TGT.\n  exploit sim_local_is_racy; eauto.\nQed.\n\nLemma sim_local_racy_write\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to ord_src ord_tgt\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (STEP_TGT: Local.racy_write_step lc1_tgt gl1_tgt loc to ord_tgt):\n  <<STEP_SRC: Local.racy_write_step lc1_src gl1_src loc to ord_src>>.\nProof.\n  inv STEP_TGT.\n  exploit sim_local_is_racy; eauto.\nQed.\n\nLemma sim_local_racy_update\n      lc1_src gl1_src\n      lc1_tgt gl1_tgt\n      loc to ordr_src ordw_src ordr_tgt ordw_tgt\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (GLOBAL1: sim_global gl1_src gl1_tgt)\n      (ORDR: Ordering.le ordr_src ordr_tgt)\n      (ORDW: Ordering.le ordw_src ordw_tgt)\n      (STEP_TGT: Local.racy_update_step lc1_tgt gl1_tgt loc to ordr_tgt ordw_tgt):\n  <<STEP_SRC: Local.racy_update_step lc1_src gl1_src loc to ordr_src ordw_src>>.\nProof.\n  inv STEP_TGT; eauto.\n  exploit sim_local_is_racy; try exact RACE; eauto.\nQed.\n\nLemma sim_local_program_step\n      lang\n      th1_src\n      th1_tgt th2_tgt e_tgt\n      (STATE1: (Thread.state th1_src) = (Thread.state th1_tgt))\n      (LOCAL1: sim_local (Thread.local th1_src) (Thread.local th1_tgt))\n      (GLOBAL1: sim_global (Thread.global th1_src) (Thread.global th1_tgt))\n      (LC_WF1_SRC: Local.wf (Thread.local th1_src) (Thread.global th1_src))\n      (LC_WF1_TGT: Local.wf (Thread.local th1_tgt) (Thread.global th1_tgt))\n      (GL_WF1_SRC: Global.wf (Thread.global th1_src))\n      (GL_WF1_TGT: Global.wf (Thread.global th1_tgt))\n      (STEP_TGT: @Thread.step lang e_tgt th1_tgt th2_tgt)\n      (EVENT: ThreadEvent.is_program e_tgt):\n  exists e_src th2_src,\n    <<STEP_SRC: @Thread.step lang e_src th1_src th2_src>> /\\\n    <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n    <<STATE2: (Thread.state th2_src) = (Thread.state th2_tgt)>> /\\\n    <<LOCAL2: sim_local (Thread.local th2_src) (Thread.local th2_tgt)>> /\\\n    <<GLOBAL2: sim_global (Thread.global th2_src) (Thread.global th2_tgt)>>.\nProof.\n  destruct th1_src as [st1_src lc1_src gl1_src],\n      th1_tgt as [st1_tgt lc1_tgt gl1_tgt]. ss. subst.\n  inv STEP_TGT; ss.\n  { exploit sim_local_internal; eauto. i. des.\n    esplits; eauto.\n  }\n  inv LOCAL; ss.\n  - esplits; (try by econs; [|econs 1]; eauto); ss.\n  - exploit sim_local_read; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 2]; eauto); ss.\n  - exploit sim_local_write; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 3]; eauto); ss.\n  - exploit sim_local_update; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 4]; eauto); ss.\n  - exploit sim_local_fence; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 5]; eauto); ss.\n  - exploit sim_local_fence; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 6]; eauto); ss.\n  - esplits; (try by econs; [|econs 7]; eauto); ss.\n  - exploit sim_local_racy_read; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 8]; eauto); ss.\n  - exploit sim_local_racy_write; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 9]; eauto); ss.\n  - exploit sim_local_racy_update; eauto; try refl. i. des.\n    esplits; (try by econs; [|econs 10]; eauto); ss.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/trans/SimLocal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.35936415202123906, "lm_q1q2_score": 0.23407358860562552}}
{"text": "Set Implicit Arguments.\n\nFrom ITree Require Import\n     ITree ITreeFacts.\nImport ITreeNotations.\nLocal Open Scope itree_scope.\n\nFrom Paco Require Import paco.\n\nFrom Coq Require Import\n     Basics\n     Morphisms\n     List\n     PeanoNat.\n\nRequire Import misc.\nRequire Import tree.\nRequire Import unbiased_itree.\n\nSection itree_notau.\n  Context {A : Type} {E : Type -> Type}.\n\n  Inductive itree_notauF (R : itree E A -> Prop) : itree' E A -> Prop :=\n  | itree_notauF_ret : forall x, itree_notauF R (RetF x)\n  | itree_notauF_vis : forall {A} (e : E A) f,\n      (forall x, R (f x)) ->\n      itree_notauF R (VisF e f).\n\n  Definition itree_notau_ R : itree E A -> Prop :=\n    fun t => itree_notauF R (observe t).\n\n  Lemma itree_notauF_mono R R' t\n        (IN: itree_notauF R t)\n        (LE: R <1= R') :\n    itree_notauF R' t.\n  Proof. intros; induction IN; econstructor; eauto. Qed.\n\n  Lemma itree_notau__mono : monotone1 (itree_notau_).\n  Proof. do 2 red. intros. eapply itree_notauF_mono; eauto. Qed.\n  Hint Resolve itree_notau__mono : paco.\n\n  Definition itree_notau : itree E A -> Prop :=\n    paco1 itree_notau_ bot1.\n\n  Global Instance Proper_itree_notau\n    : Proper (eq_itree eq ==> iff) itree_notau.\n  Proof.\n    intros x y Heq; split.\n    - revert x y Heq; pcofix CH; intros x y Heq Hnotau.\n      punfold Hnotau; unfold itree_notau_ in Hnotau.\n      punfold Heq; unfold eqit_ in Heq.\n      pstep; unfold itree_notau_.\n      destruct (observe x).\n      + inversion Heq; subst; try congruence; constructor.\n      + inversion Hnotau.\n      + inversion Heq; subst; try congruence.\n        apply Eqdep.EqdepTheory.inj_pair2 in H1; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n        inversion Hnotau; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n        unfold id in REL.\n        constructor; intro z.\n        specialize (H1 z).\n        specialize (REL z).\n        repeat destruct_upaco.\n        right; eapply CH; eauto.\n    - revert x y Heq; pcofix CH; intros x y Heq Hnotau.\n      punfold Hnotau; unfold itree_notau_ in Hnotau.\n      punfold Heq; unfold eqit_ in Heq.\n      pstep; unfold itree_notau_.\n      destruct (observe y).\n      + inversion Heq; subst; try congruence; constructor.\n      + inversion Hnotau.\n      + inversion Heq; subst; try congruence.\n        apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n        inversion Hnotau; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n        unfold id in REL.\n        constructor; intro z.\n        specialize (H1 z).\n        specialize (REL z).\n        repeat destruct_upaco.\n        right; eapply CH; eauto.\n  Qed.\nEnd itree_notau.\nHint Resolve itree_notau__mono : paco.\n\nSection itree_onetau.\n  Context {A : Type} {E : Type -> Type}.\n\n  Definition notau (t : itree E A) : Prop :=\n    match observe t with\n    | RetF _ => True\n    | TauF _ => False\n    | VisF _ _ => True\n    end.\n\n  Lemma notau_eq_itree (t1 t2 : itree E A) :\n    eq_itree eq t1 t2 ->\n    notau t1 ->\n    notau t2.\n  Proof.\n    unfold notau; intros Heq Hnotau.\n    punfold Heq; unfold eqit_ in Heq.\n    destruct (observe t1); inversion Heq; congruence.\n  Qed.\n\n  Inductive itree_onetauF (R : itree E A -> Prop) : itree' E A -> Prop :=\n  | itree_onetauF_ret : forall x, itree_onetauF R (RetF x)\n  | itree_onetauF_tau : forall t,\n      R t ->\n      notau t ->\n      itree_onetauF R (TauF t)\n  | itree_onetauF_vis : forall {A} (e : E A) f,\n      (forall x, R (f x)) ->\n      itree_onetauF R (VisF e f).\n\n  Definition itree_onetau_ R : itree E A -> Prop :=\n    fun t => itree_onetauF R (observe t).\n\n  Lemma itree_onetauF_mono R R' t\n        (IN: itree_onetauF R t)\n        (LE: R <1= R') :\n    itree_onetauF R' t.\n  Proof. intros; induction IN; econstructor; eauto. Qed.\n\n  Lemma itree_onetau__mono : monotone1 itree_onetau_.\n  Proof. do 2 red. intros. eapply itree_onetauF_mono; eauto. Qed.\n  Hint Resolve itree_onetau__mono : paco.\n\n  Definition itree_onetau : itree E A -> Prop :=\n    paco1 itree_onetau_ bot1.\n\n  Global Instance Proper_itree_onetau\n    : Proper (eq_itree eq ==> iff) itree_onetau.\n  Proof.\n    intros x y Heq; split.\n    - revert x y Heq; pcofix CH; intros x y Heq Htau.\n      punfold Htau; unfold itree_onetau_ in Htau.\n      punfold Heq; unfold eqit_ in Heq.\n      pstep; unfold itree_onetau_.\n      destruct (observe x).\n      + inversion Heq; subst; try congruence; constructor.\n      + inversion Htau; subst.\n        inversion Heq; subst; try congruence.\n        repeat destruct_upaco.\n        constructor.\n        * right; eapply CH; eauto.\n        * eapply notau_eq_itree; eauto.\n      + inversion Heq; subst; try congruence.\n        apply Eqdep.EqdepTheory.inj_pair2 in H1; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n        inversion Htau; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n        unfold id in REL.\n        constructor; intro z.\n        specialize (H1 z).\n        specialize (REL z).\n        repeat destruct_upaco.\n        right; eapply CH; eauto.\n    - revert x y Heq; pcofix CH; intros x y Heq Htau.\n      punfold Htau; unfold itree_onetau_ in Htau.\n      punfold Heq; unfold eqit_ in Heq.\n      pstep; unfold itree_onetau_.\n      destruct (observe y).\n      + inversion Heq; subst; try congruence; constructor.\n      + inversion Htau; subst.\n        inversion Heq; subst; try congruence.\n        repeat destruct_upaco.\n        constructor.\n        * right; eapply CH; eauto.\n        * eapply notau_eq_itree; eauto.\n          symmetry; auto.\n      + inversion Heq; subst; try congruence.\n        apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n        inversion Htau; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n        unfold id in REL.\n        constructor; intro z.\n        specialize (H1 z).\n        specialize (REL z).\n        repeat destruct_upaco.\n        right; eapply CH; eauto.\n  Qed.\nEnd itree_onetau.\nHint Resolve itree_onetau__mono : paco.\n\nSection itree_fintau.\n  Context {A : Type} {E : Type -> Type}.\n\n  (* Finite number of taus at the head. *)\n  Inductive fintau : itree E A -> Prop :=\n  | fintau_ret : forall t x,\n      observe t = RetF x ->\n      fintau t\n  | fintau_tau : forall t t',\n      observe t = TauF t' ->\n      fintau t' ->\n      fintau t\n  | fintau_vis : forall X t (e : E X) (k : X -> itree E A),\n      observe t = VisF e k ->\n      fintau t.\n\n  Lemma fintau_eq_itree (t1 t2 : itree E A) :\n    eq_itree eq t1 t2 ->\n    fintau t1 ->\n    fintau t2.\n  Proof.\n    intros Heq Hfintau.\n    revert Heq. revert t2.\n    induction Hfintau; intros t2 Heq.\n    - punfold Heq; unfold eqit_ in Heq; rewrite H in Heq.\n      inversion Heq; subst; try congruence.\n      econstructor; eauto.\n    - punfold Heq; unfold eqit_ in Heq; rewrite H in Heq.\n      inversion Heq; subst; try congruence.\n      destruct_upaco.\n      eapply fintau_tau; eauto.\n    - punfold Heq; unfold eqit_ in Heq; rewrite H in Heq.\n      inversion Heq; subst; try congruence.\n      apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n      apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n      eapply fintau_vis; eauto.\n  Qed.\n\n  Inductive itree_fintauF (R : itree E A -> Prop) : itree' E A -> Prop :=\n  | itree_fintauF_ret : forall x, itree_fintauF R (RetF x)\n  | itree_fintauF_tau : forall t,\n      R t ->\n      fintau t ->\n      itree_fintauF R (TauF t)\n  | itree_fintauF_vis : forall {A} (e : E A) f,\n      (forall x, R (f x)) ->\n      itree_fintauF R (VisF e f).\n\n  Definition itree_fintau_ R : itree E A -> Prop :=\n    fun t => itree_fintauF R (observe t).\n\n  Lemma itree_fintauF_mono R R' t\n        (IN: itree_fintauF R t)\n        (LE: R <1= R') :\n    itree_fintauF R' t.\n  Proof. intros; induction IN; econstructor; eauto. Qed.\n\n  Lemma itree_fintau__mono : monotone1 itree_fintau_.\n  Proof. do 2 red. intros. eapply itree_fintauF_mono; eauto. Qed.\n  Hint Resolve itree_fintau__mono : paco.\n\n  Definition itree_fintau : itree E A -> Prop :=\n    paco1 itree_fintau_ bot1.\n  \n  Global Instance Proper_fintau\n    : Proper (eq_itree eq ==> iff) fintau.\n  Proof.\n    intros x y Heq; split.\n    - intro Hfin; revert Heq. revert y.\n      induction Hfin; intros y Heq; punfold Heq; unfold eqit_ in Heq;\n        rewrite H in Heq; inversion Heq; subst; try congruence.\n      + econstructor; eauto.\n      + destruct_upaco; eapply fintau_tau; eauto.\n      + eapply fintau_vis; eauto.\n    - intro Hfin; revert Heq. revert x.\n      induction Hfin; intros z Heq; punfold Heq; unfold eqit_ in Heq;\n        rewrite H in Heq; inversion Heq; subst; try congruence.\n      + econstructor; eauto.\n      + destruct_upaco; eapply fintau_tau; eauto.\n      + eapply fintau_vis; eauto.\n  Qed.\n  \n  Global Instance Proper_itree_fintau\n    : Proper (eq_itree eq ==> iff) itree_fintau.\n  Proof.\n    intros x y Heq; split; revert Heq; revert x y;\n      pcofix CH; intros x y Heq Hfin;\n        punfold Heq; unfold eqit_ in Heq;\n          punfold Hfin; unfold itree_fintau_ in Hfin;\n            pstep; unfold itree_fintau_.\n    - destruct (observe x); inversion Heq; subst; try congruence.\n      + constructor.\n      + inversion Hfin; subst.\n        repeat destruct_upaco.\n        constructor; eauto.\n        rewrite <- REL; auto.\n      + apply Eqdep.EqdepTheory.inj_pair2 in H1; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n        inversion Hfin; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n        constructor; intro z.\n        specialize (REL z); specialize (H1 z); unfold id in REL.\n        repeat destruct_upaco.\n        right; eapply CH; eauto.\n    - destruct (observe y); inversion Heq; subst; try congruence.\n      + constructor.\n      + inversion Hfin; subst.\n        repeat destruct_upaco.\n        constructor; eauto.\n        rewrite  REL; auto.\n      + apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n        inversion Hfin; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n        apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n        constructor; intro z.\n        specialize (REL z); specialize (H1 z); unfold id in REL.\n        repeat destruct_upaco.\n        right; eapply CH; eauto.\n  Qed.\nEnd itree_fintau.\nHint Resolve itree_fintau__mono : paco.\n\nLemma onetau_fintau {E : Type -> Type} {A : Type} (t : itree E A) :\n  notau t ->\n  fintau t.\nProof.\n  unfold notau.\n  destruct (observe t) eqn:Ht; try contradiction; intros _.\n  - eapply fintau_ret; eauto.\n  - eapply fintau_vis; eauto.\nQed.\n\nLemma itree_onetau_itree_fintau {E : Type -> Type} {A : Type} (t : itree E A) :\n  itree_onetau t ->\n  itree_fintau t.\nProof.\n  revert t; pcofix CH; intros t Hone.\n  punfold Hone; unfold itree_onetau_ in Hone.\n  pstep; unfold itree_fintau_.\n  destruct (observe t).\n  - constructor.\n  - inversion Hone; subst.\n    destruct_upaco.\n    constructor; auto.\n    apply onetau_fintau; auto.\n  - inversion Hone; subst.\n    apply Eqdep.EqdepTheory.inj_pair2 in H1; subst.\n    apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n    constructor; intro x; right.\n    apply CH; specialize (H0 x); destruct_upaco; auto.\nQed.\n\n(** [itree_reachable P t] iff [Ret x] is finitely reachable in t for\n    some x such that [P x]. *)\nInductive itree_reachable {E : Type -> Type} {A : Type} (P : A -> Prop) : itree E A -> Prop :=\n| itree_reachable_ret : forall x t,\n    P x ->\n    observe t = RetF x ->\n    itree_reachable P t\n| itree_reachable_tau : forall t t',\n    observe t = TauF t' ->\n    itree_reachable P t' ->\n    itree_reachable P t\n| itree_reachable_vis : forall t X (e : E X) k y,\n    observe t = VisF e k ->\n    itree_reachable P (k y) ->\n    itree_reachable P t.\n\n(* Helper definition for reasoning about iter. *)\nDefinition ret_reachable {E I R} : itree E (I + R) -> Prop :=\n  itree_reachable (fun s => match s with\n                         | inl _ => False\n                         | inr _ => True\n                         end).\n\nLemma itree_fintau_impl {E A} (t : itree E A) (r1 r2 : itree E A -> Prop) :\n  (forall t, r1 t -> r2 t) ->\n  paco1 itree_fintau_ r1 t ->\n  paco1 itree_fintau_ r2 t.\nProof.\n  revert t.\n  pcofix CH; intros t Himpl Hfin.\n  punfold Hfin; unfold itree_fintau_ in Hfin.\n  pstep; unfold itree_fintau_.\n  destruct (observe t) eqn:Ht.\n  - constructor.\n  - inversion Hfin; subst.\n    constructor; auto.\n    destruct H0 as [H0 | H0]; right; auto.\n  - inversion Hfin; subst.\n    apply Eqdep.EqdepTheory.inj_pair2 in H1; subst.\n    apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n    constructor; intro x.\n    specialize (H0 x); destruct H0; right; auto.\nQed.\n\nLemma itree_fintau_unfold_iter {E : Type -> Type} {A B : Type} (f : A -> itree E (A + B)) x r :\n  paco1 itree_fintau_ r (lr <- f x ;; match lr with\n                                     | inl l => Tau (ITree.iter f l)\n                                     | inr r => Ret r\n                                     end) ->\n  paco1 itree_fintau_ r (ITree.iter f x).\nProof.\n  revert f x r.\n  pcofix CH; intros f x H.\n  punfold H; unfold itree_fintau_ in H.\n  unfold ITree.bind in H.\n  unfold ITree.subst in H.\n  compute in H.\n  pstep; unfold itree_fintau_.\n  rewrite 2!_observe_observe in H.\n  unfold ITree.iter. compute.\n  rewrite 2!_observe_observe.\n  destruct (observe (f x)) eqn:Hfx; simpl in *.\n  - destruct r1; simpl in *.\n    + inversion H; subst.\n      constructor; auto.\n      destruct H1 as [H1 | H1]; auto.\n      left; eapply itree_fintau_impl; eauto.\n    + constructor.\n  - inversion H; subst.\n    constructor; auto.\n    destruct H1 as [H1 | H1]; auto.\n    left; eapply itree_fintau_impl; eauto.\n  - inversion H; subst.\n    apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n    apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n    constructor.\n    intro y; specialize (H1 y).\n    destruct H1 as [H1 | H1]; auto.\n    left; eapply itree_fintau_impl; eauto.\nQed.\n\nLemma fintau_subst {E I R} t k :\n  fintau t ->\n  (forall i, fintau (k i)) ->\n  fintau\n    ((cofix _subst (u : itree E (I + R)) : itree E R :=\n        match _observe u with\n        | RetF (inl l) => Tau (k l)\n        | RetF (inr r2) => Ret r2\n        | TauF t0 => Tau (_subst t0)\n        | @VisF _ _ _ X e h => Vis e (fun x : X => _subst (h x))\n        end) t).\nProof.\n  intro Hfin; revert k; induction Hfin; intros f Hk.\n  - destruct x.\n    + eapply fintau_tau; compute.\n      * rewrite 2!_observe_observe.\n        rewrite H; reflexivity.\n      * auto.\n    + eapply fintau_ret; compute.\n      * rewrite 2!_observe_observe.\n        rewrite H; reflexivity.\n  - eapply fintau_tau; compute.\n    * rewrite 2!_observe_observe.\n      rewrite H; reflexivity.\n    * apply IHHfin; auto.\n  - eapply fintau_vis; compute.\n    * rewrite 2!_observe_observe.\n      rewrite H; reflexivity.\nQed.\n\nLemma itree_fintau_bind {E I R} (t : itree E (I + R)) k (r : itree E R -> Prop) :\n  itree_fintau t ->\n  (forall i, r (k i)) ->\n  (forall i, fintau (k i)) ->\n  paco1 itree_fintau_ r\n        (lr <- t;; match lr with\n                  | inl l => Tau (k l)\n                  | inr r0 => Ret r0\n                  end).\nProof.\n  revert t k r; pcofix CH; intros t k Hfintau Hr Hfin.\n  (* revert t k r; pcofix CH; intros t k Hr Hfin. *)\n  unfold ITree.bind, ITree.subst.\n  pstep; unfold itree_fintau_.\n  compute.\n  rewrite 2!_observe_observe.\n  destruct (observe t) eqn:Ht; simpl.\n  - destruct r1; constructor; auto.\n  - punfold Hfintau; unfold itree_fintau_ in Hfintau.\n    rewrite Ht in Hfintau; inversion Hfintau; subst.\n    destruct_upaco.\n    constructor.\n    + right; apply CH; auto.\n    + apply fintau_subst; auto.\n  - constructor; intro x.\n    punfold Hfintau; unfold itree_fintau_ in Hfintau.\n    rewrite Ht in Hfintau; inversion Hfintau; subst.\n    apply Eqdep.EqdepTheory.inj_pair2 in H1; subst.\n    apply Eqdep.EqdepTheory.inj_pair2 in H2; subst.\n    right; apply CH; auto.\n    + specialize (H0 x); destruct_upaco; auto.\nQed.\n\nLemma itree_fintau_iter {E I R} (k : I -> itree E (I + R)) (i : I) :\n  (forall j, itree_fintau (k j)) ->\n  (forall j, fintau (ITree.iter k j)) ->\n  (forall j, ret_reachable (k j)) ->\n  itree_fintau (ITree.iter k i).\nProof.\n  revert k i; pcofix CH; intros k i Hfin Hfin' Hreach.\n  apply itree_fintau_unfold_iter.\n  apply itree_fintau_bind; auto.\nQed.\n\nLemma fintau_bind {E A B} (t : itree E A) (f : A -> itree E B) :\n  fintau t ->\n  (forall x, fintau (f x)) ->\n  fintau (x <- t;; f x).\nProof.\n  induction 1; intros Hfin.\n  - unfold ITree.bind, ITree.subst.\n    destruct (observe (f x)) eqn:Hfx.\n    + eapply fintau_ret; compute.\n      rewrite 2!_observe_observe, H; eauto.\n    + eapply fintau_tau; compute.\n      rewrite 2!_observe_observe, H; eauto.\n      specialize (Hfin x).\n      inversion Hfin; congruence.\n    + eapply fintau_vis; compute.\n      rewrite 2!_observe_observe, H; eauto.\n  - unfold ITree.bind, ITree.subst.\n    eapply fintau_tau.\n    + compute; rewrite 2!_observe_observe, H; reflexivity.\n    + apply IHfintau; auto.\n  - eapply fintau_vis; compute.\n    rewrite 2!_observe_observe; rewrite H; reflexivity.\nQed.\n\nLemma itree_fintau_fintau {E A} (t : itree E A) :\n  itree_fintau t ->\n  fintau t.\nProof.\n  intro Hfin.\n  punfold Hfin; unfold itree_fintau_ in Hfin.\n  destruct (observe t) eqn:Ht.\n  - eapply fintau_ret; eauto.\n  - inversion Hfin; subst; eapply fintau_tau; eauto.\n  - eapply fintau_vis; eauto.\nQed.\n\nLemma itree_fintau_bind' {E A B} (t : itree E A) (f : A -> itree E B) :\n  itree_fintau t ->\n  (forall x, itree_fintau (f x)) ->\n  itree_fintau (x <- t;; f x).\nProof.\n  revert t f.\n  pcofix CH; intros t f H0 H1.\n  punfold H0; unfold itree_fintau_ in H0.\n  pstep; unfold itree_fintau_.\n  compute.\n  rewrite 2!_observe_observe.\n  destruct (observe t) eqn:Ht.\n  - specialize (H1 r0).\n    eapply itree_fintau_impl in H1.\n    + punfold H1.\n    + intros ? [].\n  - inversion H0; subst.\n    destruct_upaco.\n    constructor.\n    + right; apply CH; auto.\n    + apply fintau_bind; auto.\n      intro x; apply itree_fintau_fintau; auto.\n  - inversion H0; subst.\n    apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n    apply Eqdep.EqdepTheory.inj_pair2 in H4; subst.\n    constructor; intro x.\n    specialize (H2 x); destruct_upaco; right; apply CH; auto.\nQed.\n\nInstance Proper_itree_reachable {E A P} : Proper (eq_itree eq ==> iff) (@itree_reachable E A P).\nProof.\n  intros x y Heq; split; intro H.\n  - revert Heq. revert y.\n    induction H; intros z Heq.\n    + punfold Heq; unfold eqit_ in Heq; rewrite H0 in Heq.\n      inversion Heq; subst; try congruence.\n      eapply itree_reachable_ret; eauto.\n    + punfold Heq; unfold eqit_ in Heq; rewrite H in Heq.\n      inversion Heq; subst; try congruence.\n      destruct_upaco.\n      eapply itree_reachable_tau; eauto.\n    + punfold Heq; unfold eqit_ in Heq; rewrite H in Heq.\n      inversion Heq; subst; try congruence.\n      apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n      apply Eqdep.EqdepTheory.inj_pair2 in H4; subst.\n      eapply itree_reachable_vis; eauto.\n      specialize (REL y); unfold id in REL.\n      destruct_upaco.\n      apply IHitree_reachable; eauto.\n  - revert Heq. revert x.\n    induction H; intros z Heq.\n    + punfold Heq; unfold eqit_ in Heq; rewrite H0 in Heq.\n      inversion Heq; subst; try congruence.\n      eapply itree_reachable_ret; eauto.\n    + punfold Heq; unfold eqit_ in Heq; rewrite H in Heq.\n      inversion Heq; subst; try congruence.\n      destruct_upaco.\n      eapply itree_reachable_tau; eauto.\n    + symmetry in Heq; punfold Heq; unfold eqit_ in Heq; rewrite H in Heq.\n      inversion Heq; subst; try congruence.\n      apply Eqdep.EqdepTheory.inj_pair2 in H3; subst.\n      apply Eqdep.EqdepTheory.inj_pair2 in H4; subst.\n      eapply itree_reachable_vis; eauto.\n      specialize (REL y); unfold id in REL.\n      destruct_upaco.\n      apply IHitree_reachable; eauto.\n      symmetry; eauto.\nQed.\n\nInstance Proper_ret_reachable {E I R} : Proper (eq_itree eq ==> iff) (@ret_reachable E I R).\nProof. apply Proper_itree_reachable. Qed.\n\nLemma ret_reachable_bind {E A B C} (t : itree E (A + (B + C))) (k : A -> itree E (B + C)) :\n  itree_reachable (fun x => match x with\n                         | inr (inr _) => True\n                         | _ => False\n                         end) t ->\n  ret_reachable (lr <- t;; match lr with\n                          | inl l => k l\n                          | inr r => Ret r\n                          end).\nProof.\n  unfold ret_reachable.\n  intro H.\n  induction H.\n  - destruct x; try contradiction.\n    destruct s; try contradiction.\n    econstructor.\n    2: { compute; rewrite 2!_observe_observe, H0; reflexivity. }\n    apply I.\n  - eapply itree_reachable_tau; eauto.\n    compute; rewrite 2!_observe_observe, H; reflexivity.\n  - eapply itree_reachable_vis.\n    + compute; rewrite 2!_observe_observe, H; reflexivity.\n    + apply IHitree_reachable.\nQed.\n\nLemma itree_reachable_bind' {E A B} (t : itree E (A + B)) (k : A -> itree E B) :\n  itree_reachable (fun x => match x with\n                         | inr _ => True\n                         | _ => False\n                         end) t ->\n  itree_reachable (const True) (lr <- t;; match lr with\n                                      | inl l => k l\n                                      | inr r => Ret r\n                                      end).\nProof.\n  unfold ret_reachable.\n  intro H.\n  induction H.\n  - destruct x; try contradiction.\n    econstructor.\n    2: { compute; rewrite 2!_observe_observe, H0; reflexivity. }\n    apply I.\n  - eapply itree_reachable_tau; eauto.\n    compute; rewrite 2!_observe_observe, H; reflexivity.\n  - eapply itree_reachable_vis.\n    + compute; rewrite 2!_observe_observe, H; reflexivity.\n    + apply IHitree_reachable.\nQed.\n\nLemma ret_reachable_iter {E A B} (k : unit -> itree E (unit + (A + B))) :\n  itree_reachable (fun x => match x with\n                         | inr (inr _) => True\n                         | _ => False\n                         end) (k tt) ->\n  ret_reachable (ITree.iter k tt).\nProof. rewrite unfold_iter; apply ret_reachable_bind. Qed.\n\nLemma ret_reachable_iter' {E R} (k : unit -> itree E (unit + R)) :\n  itree_reachable (fun x => match x with\n                         | inr _ => True\n                         | _ => False\n                         end) (k tt) ->\n  itree_reachable (const True) (ITree.iter k tt).\nProof. rewrite unfold_iter; apply itree_reachable_bind'. Qed.\n\nLemma ret_reachable_bind' {E A} (t : itree E (nat + A)) n :\n  ret_reachable t ->\n  itree_reachable\n    (fun x : unit + (nat + A) => match x with\n                                 | inr (inr _) => True\n                                 | _ => False\n                                 end)\n    (x <- t;;\n     match x with\n     | inl n0 => if PeanoNat.Nat.eqb n0 n then Ret (inl tt) else Ret (inr (inl n0))\n     | inr y => Ret (inr (inr y))\n     end).\nProof.\n  intro H; induction H; subst.\n  - destruct x; try contradiction.\n    eapply itree_reachable_ret.\n    2: { compute; rewrite 2!_observe_observe, H0; reflexivity. }\n    apply I.\n  - eapply itree_reachable_tau; eauto.\n    compute; rewrite 2!_observe_observe, H; reflexivity.\n  - eapply itree_reachable_vis.\n    + compute; rewrite 2!_observe_observe, H; reflexivity.\n    + apply IHitree_reachable.\nQed.\n                  \nLemma leaf_reachable'_ret_reachable {A : Type} (t : tree A) :\n  leaf_reachable' t ->\n  ret_reachable (unbiased_tree_to_itree t).\nProof.\n  induction 1; simpl.\n  - econstructor.\n    2: reflexivity.\n    apply I.\n  - eapply itree_reachable_vis with (y:=true).\n    + reflexivity.\n    + apply IHleaf_reachable'.\n  - eapply itree_reachable_vis with (y:=false).\n    + reflexivity.\n    + apply IHleaf_reachable'.\n  - apply ret_reachable_iter.\n    apply ret_reachable_bind'; auto.\nQed.\n\nLemma itree_reachable_fintau {E A} P (t : itree E A) :\n  itree_reachable P t ->\n  fintau t.\nProof.\n  induction 1.\n  - econstructor; eauto.\n  - eapply fintau_tau; eauto.\n  - eapply fintau_vis; eauto.\nQed.\n\nLemma itree_reachable_impl {E A} (P Q : A -> Prop) (t : itree E A) :\n  (forall x, P x -> Q x) ->\n  itree_reachable P t ->\n  itree_reachable Q t.\nProof.\n  intros Himpl H; induction H.\n  - eapply itree_reachable_ret; eauto.\n  - eapply itree_reachable_tau; eauto.\n  - eapply itree_reachable_vis; eauto.\nQed.\n\nLemma itree_reachable_n_bind {E A} (t : itree E (nat + A)) (n : nat) :\n  itree_reachable (fun x => match x with\n                         | inl m => m <> n\n                         | _ => False\n                         end) t ->\n  itree_reachable (fun x => match x with\n                         | inl _ => False\n                         | inr _ => True\n                         end)\n                  (x <- t;;\n                   match x with\n                   | inl n1 => if n1 =? n then Ret (inl tt) else Ret (inr (inl n1))\n                   | inr y => Ret (inr (inr y))\n                   end).\nProof.\n  induction 1.\n  - destruct x; try contradiction.\n    eapply itree_reachable_ret.\n    2: { compute; rewrite 2!_observe_observe, H0.\n         apply Nat.eqb_neq in H; compute in H; rewrite H; reflexivity. }\n    apply I.\n  - eapply itree_reachable_tau; eauto.\n    compute; rewrite 2!_observe_observe, H; reflexivity.\n  - eapply itree_reachable_vis.\n    { compute; rewrite 2!_observe_observe, H; reflexivity. }\n    apply IHitree_reachable.\nQed.\n\nLemma itree_reachable_n_bind' {E A} (t : itree E (nat + A)) (n k : nat) :\n  k <> n ->\n  itree_reachable (fun x => match x with\n                         | inl m => m = k\n                         | _ => False\n                         end) t ->\n  itree_reachable (fun x => match x with\n                         | inl _ => False\n                         | inr _ => True\n                         end)\n                  (x <- t;;\n                   match x with\n                   | inl n1 => if n1 =? n then Ret (inl tt) else Ret (inr (inl n1))\n                   | inr y => Ret (inr (inr y))\n                   end).\nProof.\n  intros Hneq H. revert Hneq. revert n.\n  induction H; intros n Hneq.\n  - destruct x; subst; try contradiction.\n    eapply itree_reachable_ret.\n    2: { compute; rewrite 2!_observe_observe, H0.\n         apply Nat.eqb_neq in Hneq; compute in Hneq; rewrite Hneq; reflexivity. }\n    apply I.\n  - eapply itree_reachable_tau; eauto.\n    compute; rewrite 2!_observe_observe, H; reflexivity.\n  - eapply itree_reachable_vis.\n    { compute; rewrite 2!_observe_observe, H; reflexivity. }\n    apply IHitree_reachable; auto.\nQed.\n\nLemma itree_reachable_bind {E A B} (t : itree E (unit + (A + B))) k P :\n  itree_reachable (fun x => match x with\n                         | inl _ => False\n                         | inr y => P y\n                         end) t ->\n  itree_reachable P\n    (lr <- t;; match lr with\n              | inl l => k l\n              | inr r => Ret r\n              end).\nProof.\n  induction 1.\n  - destruct x; try contradiction.\n    eapply itree_reachable_ret; eauto.\n    compute; rewrite 2!_observe_observe, H0; reflexivity.\n  - eapply itree_reachable_tau; eauto.\n    compute; rewrite 2!_observe_observe, H; reflexivity.\n  - eapply itree_reachable_vis.\n    { compute; rewrite 2!_observe_observe, H; reflexivity. }\n    apply IHitree_reachable.\nQed.\n\nLemma itree_reachable_iter {E A B} (k : unit -> itree E (unit + (A + B))) P :\n  itree_reachable (fun x => match x with\n                         | inr y => P y\n                         | _ => False\n                         end) (k tt) ->\n  itree_reachable P (ITree.iter k tt).\nProof. rewrite unfold_iter; apply itree_reachable_bind. Qed.\n\nLemma itree_reachable_n_bind'' {E A} (t : itree E (nat + A)) (f : unit -> itree E (nat + A)) (k n : nat) :\n  k <> n ->\n  itree_reachable (fun x => match x with\n                         | inl m => m = k\n                         | inr _ => False\n                         end) t ->\n  itree_reachable (fun x => match x with\n                         | inl m => m = k\n                         | inr _ => False\n                         end)\n                  (lr <-\n                   (x <- t;;\n                    match x with\n                    | inl n0 => if n0 =? n then Ret (inl tt) else Ret (inr (inl n0))\n                    | inr y => Ret (inr (inr y))\n                    end);;\n                   match lr with\n                   | inl l => f l\n                   | inr r => Ret r\n                   end).\nProof.\n  intros Hneq H.\n  revert Hneq. revert n.\n  induction H; intros n Hneq.\n  - destruct x; try contradiction; subst.\n    eapply itree_reachable_ret.\n    2: { compute; rewrite 3!_observe_observe, H0.\n         apply Nat.eqb_neq in Hneq; compute in Hneq; rewrite Hneq.\n         reflexivity. }\n    reflexivity.\n  - eapply itree_reachable_tau.\n    { compute; rewrite 3!_observe_observe, H.\n      reflexivity. }\n    apply IHitree_reachable; auto.\n  - eapply itree_reachable_vis.\n    { compute; rewrite 3!_observe_observe, H.\n      reflexivity. }\n    apply IHitree_reachable; auto.\nQed.\n\nLemma itree_reachable_n_iter {E A} (t : itree E (nat + A)) k n :\n  k <> n ->\n  itree_reachable (fun x => match x with\n                         | inl m => m = k\n                         | inr _ => False\n                         end) t ->\n  itree_reachable (fun x => match x with\n                         | inl m => m = k\n                         | inr _ => False\n                         end)\n    (ITree.iter\n       (fun _ : unit =>\n        x <- t;;\n        match x with\n        | inl n0 => if n0 =? n then Ret (inl tt) else Ret (inr (inl n0))\n        | inr y => Ret (inr (inr y))\n        end) tt).\nProof.\n  intros Hneq H.\n  rewrite unfold_iter.\n  apply itree_reachable_n_bind''; auto.\nQed.\n\nLemma fail_reachable'_itree_reachable {A} (t : tree A) (k : nat) :\n  not_bound_in k t ->\n  fail_reachable' k t ->\n  itree_reachable (fun x => match x with\n                         | inl m => m = k\n                         | inr _ => False\n                         end) (unbiased_tree_to_itree t).\nProof.\n  intros Hnotbound H.\n  revert Hnotbound.\n  induction H; simpl; intros Hnotbound.\n  - eapply itree_reachable_ret; try reflexivity.\n    apply eq_refl.\n  - inversion Hnotbound; subst.\n    eapply itree_reachable_vis with (y:=true); try reflexivity.\n    apply IHfail_reachable'; auto.\n  - inversion Hnotbound; subst.\n    eapply itree_reachable_vis with (y:=false); try reflexivity.\n    apply IHfail_reachable'; auto.\n  - inversion Hnotbound; subst.\n    apply itree_reachable_n_iter; auto.\nQed.\n\nLemma kdfg {A} (t : tree A) (k n : nat) :\n  not_bound_in k t ->\n  fail_reachable' k t ->\n  k <> n ->\n  itree_reachable (const True)\n                  (ITree.iter\n                     (fun _ : unit =>\n                        x <- unbiased_tree_to_itree t;;\n                        match x with\n                        | inl n1 => if n1 =? n then Ret (inl tt) else Ret (inr (inl n1))\n                        | inr y => Ret (inr (inr y))\n                        end) tt).\nProof.\n  intros Hnotbound Hfail Hneq.\n  apply ret_reachable_iter'.\n  apply itree_reachable_n_bind' with k; auto.\n  apply fail_reachable'_itree_reachable; auto.\nQed.\n\nLemma nondivergent'_itree_fintau {A : Type} (t : tree A) (lbls : list nat) :\n  wf_tree t ->\n  (forall n, bound_in n t -> ~ In n lbls) ->\n  nondivergent' lbls t ->\n  itree_fintau (unbiased_tree_to_itree t).\nProof.\n  revert lbls.\n  induction t; simpl; intros lbls Hwf Hnotin Hnd.\n  - pstep; constructor.\n  - pstep; constructor.\n  - inversion Hnd; subst.\n    inversion Hwf; subst.\n    pstep; constructor; intros []; left.\n    + eapply IHt1; eauto.\n      intros n Hbound Hin; eapply Hnotin; eauto; constructor; auto.\n    + eapply IHt2; eauto.\n      intros n Hbound Hin; eapply Hnotin; eauto; solve[constructor; auto].\n  - inversion Hnd; subst.\n    inversion Hwf; subst.\n    destruct H2 as [Hleaf | [k [Hin Hreach]]].\n    + apply itree_fintau_iter.\n      * intros _; apply itree_fintau_bind'; eauto.\n        -- eapply IHt; eauto.\n           intros m Hbound Hin.\n           destruct (Nat.eqb_spec n m); subst.\n           ++ apply bound_in_not_bound_in in H4; congruence.\n           ++ destruct Hin; try congruence.\n              eapply Hnotin; eauto; constructor; auto.\n        -- intros [m | x].\n           ++ destruct (PeanoNat.Nat.eqb m n); pstep; constructor.\n           ++ pstep; constructor.\n      * intros [].\n        eapply itree_reachable_fintau, ret_reachable_iter, ret_reachable_bind'.\n        apply leaf_reachable'_ret_reachable, leaf_reachable_leaf_reachable'; auto.\n      * intros _.\n        eapply itree_reachable_impl.\n        2: { apply ret_reachable_bind'.\n             apply leaf_reachable'_ret_reachable.\n             apply leaf_reachable_leaf_reachable'; auto. }\n        intros [? | [? | ?]]; auto.\n    + destruct (Nat.eqb_spec k n); subst.\n      { exfalso; eapply Hnotin; eauto; constructor. }\n      apply itree_fintau_iter.\n      * intros _; apply itree_fintau_bind'; eauto.\n        -- eapply IHt; eauto.\n           intros m Hbound Hin'.\n           destruct (Nat.eqb_spec m n); subst.\n           ++ apply bound_in_not_bound_in in H4; congruence.\n           ++ destruct Hin'; try congruence.\n              eapply Hnotin; eauto; constructor; auto.\n        -- intros [m | x].\n           ++ destruct (PeanoNat.Nat.eqb m n); pstep; constructor.\n           ++ pstep; constructor.\n      * intros [].\n        eapply itree_reachable_fintau.\n        eapply kdfg.\n        2: { apply fail_reachable_fail_reachable'; eauto. }\n        -- apply bound_in_not_bound_in; intro Hbound.\n           eapply Hnotin; eauto.\n           constructor; auto.\n        -- auto.\n      * intros [].\n        eapply itree_reachable_impl.\n        2: {\n          eapply itree_reachable_n_bind'; eauto.\n          apply fail_reachable'_itree_reachable; auto.\n          -- apply bound_in_not_bound_in; intro Hbound.\n             eapply Hnotin; eauto.\n             constructor; auto.\n          -- apply fail_reachable_fail_reachable'; auto. }\n        intros [? | [? | ?]]; auto.\nQed.\n\nLemma itree_reachable_bind'' {E A} (t : itree E (nat + A)) :\n  itree_reachable (fun x => match x with\n                         | inl _ => False\n                         | inr _ => True\n                         end) t ->\n  itree_reachable (fun x : unit + A => match x with\n                                    | inl _ => False\n                                    | inr _ => True\n                                    end)\n                  (x <- t;;\n                   match x with\n                   | inl _ => ret (inl tt)\n                   | inr r => ret (inr r)\n                   end).\nProof.\n  induction 1.\n  - destruct x; try contradiction.\n    eapply itree_reachable_ret.\n    2: { compute; rewrite 2!_observe_observe, H0; reflexivity. }\n    apply I.\n  - eapply itree_reachable_tau.\n    { compute; rewrite 2!_observe_observe, H; reflexivity. }\n    apply IHitree_reachable.\n  - eapply itree_reachable_vis.\n    { compute; rewrite 2!_observe_observe, H; reflexivity. }\n    apply IHitree_reachable.\nQed.\n\nTheorem nondivergent''_itree_fintau {A : Type} (t : tree A) (n : nat) :\n  wf_tree t ->\n  not_bound_in n t ->\n  nondivergent'' n t ->\n  itree_fintau (unbiased_tree_to_itree' t).\nProof.\n  intros Hwf Hnotbound Hnd.\n  unfold nondivergent'' in Hnd.\n  unfold unbiased_tree_to_itree'.\n  unfold tie_itree'.\n  inversion Hnd; subst.\n  apply itree_fintau_iter.\n  - intros _.\n    apply itree_fintau_bind'.\n    + eapply nondivergent'_itree_fintau; eauto.\n      intros m Hbound [? | []]; subst.\n      apply bound_in_not_bound_in in Hnotbound; congruence.\n    + intros []; pstep; constructor.\n  - intros [].\n    destruct H2 as [Hleaf | [k [Hin Hreach]]].\n    + eapply itree_reachable_fintau, ret_reachable_iter', itree_reachable_bind''.\n      apply leaf_reachable'_ret_reachable, leaf_reachable_leaf_reachable'; auto.\n    + inversion Hin.\n  - intros [].\n    destruct H2 as [Hleaf | [k [Hin Hreach]]].\n    + apply itree_reachable_bind''.\n      apply leaf_reachable'_ret_reachable, leaf_reachable_leaf_reachable'; auto.\n    + inversion Hin.\nQed.\n", "meta": {"author": "OUPL", "repo": "Zar", "sha": "9243f9d77d0c8af99afa4f536156a3e23b1c40e1", "save_path": "github-repos/coq/OUPL-Zar", "path": "github-repos/coq/OUPL-Zar/Zar-9243f9d77d0c8af99afa4f536156a3e23b1c40e1/theory/cwp/nondivergent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23400269564086656}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.AllEntriesTermSanityInterface.\n\nSection AllEntriesTermSanity.\n\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri: raft_refinement_interface}.\n\n  Lemma handleAppendEntries_currentTerm_monotonic:\n    forall h st (d : raft_data) \n      (m : msg) (t : term) (n : name) (pli : logIndex) \n      (plt : term) (es : list entry) (ci : logIndex),\n      handleAppendEntries h st t n pli plt es\n                          ci = (d, m) ->\n      currentTerm st <= currentTerm d.\n  Proof using. \n    intros.\n    unfold handleAppendEntries in *.\n    repeat break_match; simpl in *; do_bool; repeat find_inversion; auto; try lia;\n    simpl in *;\n    unfold advanceCurrentTerm in *; repeat break_match; do_bool; auto.\n  Qed.\n\n  Lemma allEntries_term_sanity_append_entries :\n    refined_raft_net_invariant_append_entries allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_eapply_lem_hyp update_elections_data_appendEntries_allEntries_term'; eauto.\n    intuition.\n    find_apply_lem_hyp handleAppendEntries_currentTerm_monotonic;\n      find_apply_hyp_hyp; lia.\n  Qed.\n\n  Lemma allEntries_term_sanity_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_apply_lem_hyp handleAppendEntriesReply_type_term. intuition; repeat find_rewrite; eauto.\n    find_apply_hyp_hyp. lia.\n  Qed.\n\n  Lemma allEntries_term_sanity_request_vote :\n    refined_raft_net_invariant_request_vote allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_rewrite_lem update_elections_data_requestVote_allEntries.\n    find_apply_lem_hyp handleRequestVote_type_term. intuition; repeat find_rewrite; eauto.\n    find_apply_hyp_hyp. lia.\n  Qed.\n\n  Lemma allEntries_term_sanity_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_rewrite_lem update_elections_data_requestVoteReply_allEntries.\n    find_apply_hyp_hyp.\n    unfold handleRequestVoteReply, advanceCurrentTerm.\n    repeat break_match; simpl in *; repeat find_inversion; do_bool; simpl in *; auto.\n    lia.\n  Qed.\n\n  Lemma allEntries_term_sanity_client_request :\n    refined_raft_net_invariant_client_request allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_copy_apply_lem_hyp update_elections_data_client_request_allEntries.\n    find_apply_lem_hyp handleClientRequest_type.\n    intuition; repeat find_rewrite;\n    try find_apply_hyp_hyp; auto.\n    break_exists.\n    intuition; repeat find_rewrite;\n    simpl in *.\n    intuition; simpl in *;\n    try match goal with\n      | H : context [ _ :: _ ] |- _ => clear H\n    end; repeat tuple_inversion; eauto.\n  Qed.\n\n  Lemma allEntries_term_sanity_timeout :\n    refined_raft_net_invariant_timeout allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_rewrite_lem update_elections_data_timeout_allEntries.\n    find_apply_lem_hyp handleTimeout_type_strong.\n    intuition; repeat find_rewrite; eauto.\n  Qed.\n\n  Lemma allEntries_term_sanity_do_leader :\n    refined_raft_net_invariant_do_leader allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_apply_lem_hyp doLeader_type. intuition.\n    repeat find_rewrite. eauto.\n  Qed.\n    \n\n  Lemma allEntries_term_sanity_do_generic_server :\n    refined_raft_net_invariant_do_generic_server allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n    find_apply_lem_hyp doGenericServer_type. intuition.\n    repeat find_rewrite. eauto.\n  Qed.\n  \n\n  Lemma allEntries_term_sanity_reboot :\n    refined_raft_net_invariant_reboot allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto.\n  Qed.\n      \n\n  Lemma allEntries_term_sanity_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros.\n    find_reverse_higher_order_rewrite. eauto.\n  Qed.\n\n\n  Lemma allEntries_term_sanity_init :\n    refined_raft_net_invariant_init allEntries_term_sanity.\n  Proof using. \n    red. unfold allEntries_term_sanity. intros. simpl in *. intuition.\n  Qed.\n  \n  Instance aetsi : allEntries_term_sanity_interface.\n  Proof.\n    split.\n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply allEntries_term_sanity_init.\n    - apply allEntries_term_sanity_client_request.\n    - apply allEntries_term_sanity_timeout.\n    - apply allEntries_term_sanity_append_entries.\n    - apply allEntries_term_sanity_append_entries_reply.\n    - apply allEntries_term_sanity_request_vote.\n    - apply allEntries_term_sanity_request_vote_reply.\n    - apply allEntries_term_sanity_do_leader.\n    - apply allEntries_term_sanity_do_generic_server.\n    - apply allEntries_term_sanity_state_same_packet_subset.\n    - apply allEntries_term_sanity_reboot.\n  Qed. \nEnd AllEntriesTermSanity.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft-proofs/AllEntriesTermSanityProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331606115021, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23400269564086656}}
{"text": "Require Import ModelProperties.\n\n (*SUBJECT, Property and TransFunc*)\nLtac OpDontChangeStPSS :=\n  intros s t Sub SS TF; inversion TF;\n   match goal with\n   | id:(s = t) |- _ => rewrite <- id; auto\n   end.\n \nLtac OpDontChangeStPSP :=\n  intros s t Sub SP TF;  (* SUBJECT, Property and TransFunc *)\n   inversion TF; match goal with\n                 | id:(s = t) |- _ => rewrite <- id; auto\n                 end. \n\nLtac StartPSS := intros s t Sub SS TF; inversion TF. \n\nLtac BreakSS :=\n  match goal with\n  | SS:(SecureState _) |- _ =>\n      unfold SecureState in SS; elim SS; intros DAC MAC\n  end. \n\nLtac StartPSP := intros s t Sub SP TF; inversion TF. \n  \n \nLemma ReadWriteImpRead :\n forall s : SFSstate,\n DACSecureState s ->\n forall (u : SUBJECT) (o : OBJECT),\n match fsecmat (secmat s) o with\n | Some y => set_In u (ActReaders y) -> PreDACRead s u o\n | None => True\n end. \nunfold DACSecureState in |- *. \nintros. \ncut\n match fsecmat (secmat s) o with\n | Some y =>\n     (set_In u (ActReaders y) -> PreDACRead s u o) /\\\n     (set_In u (ActWriters y) -> PreDACWrite s u o)\n | None => True\n end. \nelim (fsecmat (secmat s) o). \nintros. \nelim H0; intros. \nauto. \n \nauto. \n \napply H. \n \nQed. \n \n \nLemma ReadWriteImpWrite :\n forall s : SFSstate,\n DACSecureState s ->\n forall (u : SUBJECT) (o : OBJECT),\n match fsecmat (secmat s) o with\n | Some y => set_In u (ActWriters y) -> PreDACWrite s u o\n | None => True\n end. \nunfold DACSecureState in |- *. \nintros. \ncut\n match fsecmat (secmat s) o with\n | Some y =>\n     (set_In u (ActReaders y) -> PreDACRead s u o) /\\\n     (set_In u (ActWriters y) -> PreDACWrite s u o)\n | None => True\n end. \nelim (fsecmat (secmat s) o). \nintros. \nelim H0; intros. \nauto. \n \nauto. \n \napply H. \n \nQed. \n \n \nLemma TwoImpLeft :\n forall (s : SFSstate) (u : SUBJECT),\n (forall rw : ReadersWriters,\n  set_In rw (ransecmat (secmat s)) ->\n  ~ set_In u (ActReaders rw) /\\ ~ set_In u (ActWriters rw)) ->\n forall rw : ReadersWriters,\n set_In rw (ransecmat (secmat s)) -> ~ set_In u (ActReaders rw). \nintros. \ncut (~ set_In u (ActReaders rw) /\\ ~ set_In u (ActWriters rw)). \ntauto. \n \nauto. \n \nQed. \n \n \nLemma TwoImpRight :\n forall (s : SFSstate) (u : SUBJECT),\n (forall rw : ReadersWriters,\n  set_In rw (ransecmat (secmat s)) ->\n  ~ set_In u (ActReaders rw) /\\ ~ set_In u (ActWriters rw)) ->\n forall rw : ReadersWriters,\n set_In rw (ransecmat (secmat s)) -> ~ set_In u (ActWriters rw). \nintros. \ncut (~ set_In u (ActReaders rw) /\\ ~ set_In u (ActWriters rw)). \ntauto. \n \nauto. \n \nQed. \n \n \nLemma UniqNames :\n forall (s : SFSstate) (o : OBJECT),\n FuncPre1 s ->\n ~ set_In (ObjName o, File) (domf (files s)) ->\n ~ set_In (ObjName o, Directory) (domd (directories s)) ->\n ~ set_In o (DOM OBJeq_dec (acl s)). \nintro; intro; unfold FuncPre1 in |- *; elim o; simpl in |- *; intros. \ncut\n ((forall o : OBJECT,\n   set_In o (DOM OBJeq_dec (directories s)) -> ObjType o = Directory) /\\\n  (forall o : OBJECT, set_In o (DOM OBJeq_dec (files s)) -> ObjType o = File) /\\\n  DOM OBJeq_dec (acl s) =\n  set_union OBJeq_dec (DOM OBJeq_dec (files s))\n    (DOM OBJeq_dec (directories s))). \nintro CUT; elim CUT; intros. \nelim H3; intros. \nrewrite H5; intro. \ncut\n (set_In (a, File) (domf (files s)) \\/\n  set_In (a, Directory) (domd (directories s))). \nintro H7; elim H7; intro. \nauto. \n \nauto. \n \ngeneralize H6; elim b; intro. \nleft; cut (~ set_In (a, File) (DOM OBJeq_dec (directories s))). \nintro; unfold domf in |- *. \ncut\n (set_In (a, File)\n    (set_union OBJeq_dec (DOM OBJeq_dec (directories s))\n       (DOM OBJeq_dec (files s)))). \nintro; eauto. \n \nauto. \n \nintro; absurd (ObjType (a, File) = Directory). \nsimpl in |- *. \nintro H11; discriminate H11. \n \nauto. \n \nauto. \nright. \ncut (~ set_In (a, Directory) (DOM OBJeq_dec (files s))). \nintro; unfold domd in |- *; eauto. \n \nintro; absurd (ObjType (a, Directory) = File). \nsimpl in |- *. \nintro H11; discriminate H11. \n \nauto. \n \nauto. \n \nQed. \n \n \nHint Resolve UniqNames. \n \n \nLemma eq_scIMPLYle_sc : forall a b : SecClass, eq_sc a b -> le_sc a b. \nunfold eq_sc, le_sc in |- *; intros. \nelim H; intros. \nrewrite H0; rewrite H1. \nauto. \nQed. \n \n \nLemma NotInDOMIsUndef2 :\n forall (s : SFSstate) (o1 o2 : OBJECT),\n ~ set_In o1 (domsecmat (secmat s)) ->\n o1 = o2 -> None = fsecmat (secmat s) o2. \nintros. \nsymmetry  in |- *. \nrewrite H0 in H. \nunfold fsecmat in |- *; apply NotInDOMIsUndef; auto. \n \nQed. \n \nLemma NotInDOMIsUndef3 :\n forall (s : SFSstate) (p : OBJNAME) (o : OBJECT),\n FuncPre1 s ->\n FuncPre3 s ->\n ~ set_In (p, File) (domf (files s)) ->\n ~ set_In (p, Directory) (domd (directories s)) ->\n p = ObjName o -> None = fsecmat (secmat s) o. \nintros until o; elim o; simpl in |- *. \nintros until b; elim b; intros. \nrewrite <- H3. \nsymmetry  in |- *; unfold fsecmat in |- *; apply NotInDOMIsUndef. \ncut (~ set_In (p, File) (DOM OBJeq_dec (acl s))). \nunfold FuncPre3, Included in H3. \nunfold FuncPre3, Included in H0. \nauto. \n \napply UniqNames; auto. \n \nrewrite <- H3. \nsymmetry  in |- *; unfold fsecmat in |- *; apply NotInDOMIsUndef. \ncut (~ set_In (p, Directory) (DOM OBJeq_dec (acl s))). \nunfold FuncPre3, Included in H3. \nunfold FuncPre3, Included in H0. \nauto. \n \napply UniqNames; auto. \n \nQed. \n \n \nLemma EqfOSC6 :\n forall (s : SFSstate) (o1 o2 : OBJECT) (sc : SecClass),\n o1 <> o2 -> fOSC (objectSC s) o2 = fOSC (chobjsc_SC s o1 sc) o2. \nintros; unfold fOSC, chobjsc_SC in |- *. \nelim (fOSC (objectSC s) o1). \nintro; apply AddRemEq; auto. \n \nauto. \n \nQed. \n \n \nLemma EqfOSC5 :\n forall (s : SFSstate) (o : OBJECT) (p : OBJNAME),\n FuncPre1 s ->\n FuncPre2 s ->\n ~ set_In (p, File) (domf (files s)) ->\n ~ set_In (p, Directory) (domd (directories s)) ->\n p = ObjName o -> None = fOSC (objectSC s) o. \nintros. \nsymmetry  in |- *; unfold fOSC in |- *; apply NotInDOMIsUndef. \nreplace (DOM OBJeq_dec (objectSC s)) with (DOM OBJeq_dec (acl s)). \nrewrite H3 in H1; rewrite H3 in H2. \nauto. \n \nQed. \n \n \nLemma EqfOSC1 :\n forall (s : SFSstate) (o : OBJECT) (p : OBJNAME) (u : SUBJECT),\n p <> ObjName o -> fOSC (objectSC s) o = fOSC (create_oSC s u p) o. \nintros. \nunfold create_oSC in |- *. \nelim (fSSC (subjectSC s) u); elim (fsecmat (secmat s) (MyDir p)). \nintros; unfold fOSC in |- *; apply AddEq. \nintro; apply H. \nrewrite H0; simpl in |- *; auto. \n \nauto. \n \nauto. \n \nauto. \n \nQed. \n \n \nLemma EqfOSC2 :\n forall (s : SFSstate) (o : OBJECT) (p : OBJNAME) (u : SUBJECT),\n p <> ObjName o -> fOSC (objectSC s) o = fOSC (mkdir_oSC s u p) o. \nintros. \nunfold mkdir_oSC in |- *. \nelim (fSSC (subjectSC s) u); elim (fsecmat (secmat s) (MyDir p)). \nintros; unfold fOSC in |- *; apply AddEq. \nintro; apply H. \nrewrite H0; simpl in |- *; auto. \n \nauto. \n \nauto. \n \nauto. \n \nQed. \n \n \nLemma EqfOSC3 :\n forall (s : SFSstate) (o1 o2 : OBJECT),\n o1 <> o2 -> fOSC (objectSC s) o2 = fOSC (unlink_oSC s o1) o2. \nintros. \nunfold unlink_oSC in |- *. \nelim (fOSC (objectSC s) o1). \nintro; unfold fOSC in |- *; apply RemEq. \nauto. \n \nauto. \n \nQed. \n \n \nLemma Eqfacl1 :\n forall (s : SFSstate) (o : OBJECT) (p : OBJNAME) (u : SUBJECT)\n   (perms : PERMS),\n p <> ObjName o -> facl (acl s) o = facl (create_acl s u p perms) o. \nintros. \nunfold create_acl in |- *. \nelim (fSSC (subjectSC s) u); elim (fsecmat (secmat s) (MyDir p)). \nintros; unfold facl in |- *; apply AddEq. \nintro y1; apply H; rewrite y1; simpl in |- *; auto. \n \nauto. \n \nauto. \n \nauto. \n \nQed. \n \n \nLemma Eqfacl2 :\n forall (s : SFSstate) (o : OBJECT) (p : OBJNAME) (u : SUBJECT)\n   (perms : PERMS),\n p <> ObjName o -> facl (acl s) o = facl (mkdir_acl s u p perms) o. \nintros. \nunfold mkdir_acl in |- *. \nelim (fSSC (subjectSC s) u); elim (fsecmat (secmat s) (MyDir p)). \nintros; unfold facl in |- *; apply AddEq. \nintro y1; apply H; rewrite y1; simpl in |- *; auto. \n \nauto. \n \nauto. \n \nauto. \n \nQed. \n \n \nLemma Eqfacl3 :\n forall (s : SFSstate) (o1 o2 : OBJECT),\n o1 <> o2 -> facl (acl s) o2 = facl (unlink_acl s o1) o2. \nintros. \nunfold unlink_acl in |- *. \nelim (facl (acl s) o1). \nintros; unfold facl in |- *; apply RemEq. \nauto. \n \nauto. \n \nQed. \n \n (*Seguir aqui*)\nLemma Eqfacl4 :\n forall (s : SFSstate) (o : OBJECT) (y z : AccessCtrlListData),\n FuncPre4 s ->\n facl (acl s) o = Some y -> facl (rmdir_acl s o) o = Some z -> False. \nunfold facl in |- *. \nintros until z. \ncut\n match PARTFUNC OBJeq_dec (acl s) o with\n | Some y => set_In (o, y) (acl s)\n | None => ~ set_In o (DOM OBJeq_dec (acl s))\n end. \nunfold rmdir_acl in |- *. \nunfold facl in |- *. \nelim (PARTFUNC OBJeq_dec (acl s) o). \nintros. \ncut (PARTFUNC OBJeq_dec (set_remove ACLeq_dec (o, a) (acl s)) o = None). \nrewrite H2. \nintro. \ndiscriminate H3. \n \nauto. \n \nintros. \ndiscriminate H1. \n \napply DOMFuncRel4. \nQed. \n \n \nLemma Eqfacl5 :\n forall (s : SFSstate) (o : OBJECT) (y z : AccessCtrlListData),\n FuncPre4 s ->\n facl (acl s) o = Some y -> facl (unlink_acl s o) o = Some z -> False. \nunfold facl in |- *. \nintros until z. \ncut\n match PARTFUNC OBJeq_dec (acl s) o with\n | Some y => set_In (o, y) (acl s)\n | None => ~ set_In o (DOM OBJeq_dec (acl s))\n end. \nunfold unlink_acl in |- *. \nunfold facl in |- *. \nelim (PARTFUNC OBJeq_dec (acl s) o). \nintros. \ncut (PARTFUNC OBJeq_dec (set_remove ACLeq_dec (o, a) (acl s)) o = None). \nrewrite H2. \nintro. \ndiscriminate H3. \n \nauto. \n \nintros. \ndiscriminate H1. \n \napply DOMFuncRel4. \nQed. \n \n \nLemma EqfOSC4 :\n forall (s : SFSstate) (o : OBJECT) (y z : SecClass),\n FuncPre6 s ->\n fOSC (objectSC s) o = Some y -> fOSC (rmdir_oSC s o) o = Some z -> False. \nunfold fOSC in |- *. \nintros until z. \ncut\n match PARTFUNC OBJeq_dec (objectSC s) o with\n | Some y => set_In (o, y) (objectSC s)\n | None => ~ set_In o (DOM OBJeq_dec (objectSC s))\n end. \nunfold rmdir_oSC in |- *. \nunfold fOSC in |- *. \nelim (PARTFUNC OBJeq_dec (objectSC s) o). \nintros. \ncut (PARTFUNC OBJeq_dec (set_remove OSCeq_dec (o, a) (objectSC s)) o = None). \nrewrite H2. \nintro. \ndiscriminate H3. \n \nauto. \n \nintros. \ndiscriminate H1. \n \napply DOMFuncRel4. \nQed. \n \n \nLemma EqfOSC7 :\n forall (s : SFSstate) (o : OBJECT) (y z : SecClass),\n FuncPre6 s ->\n fOSC (objectSC s) o = Some y -> fOSC (unlink_oSC s o) o = Some z -> False. \nunfold fOSC in |- *. \nintros until z. \ncut\n match PARTFUNC OBJeq_dec (objectSC s) o with\n | Some y => set_In (o, y) (objectSC s)\n | None => ~ set_In o (DOM OBJeq_dec (objectSC s))\n end. \nunfold unlink_oSC in |- *. \nunfold fOSC in |- *. \nelim (PARTFUNC OBJeq_dec (objectSC s) o). \nintros. \ncut (PARTFUNC OBJeq_dec (set_remove OSCeq_dec (o, a) (objectSC s)) o = None). \nrewrite H2. \nintro. \ndiscriminate H3. \n \nauto. \n \nintros. \ndiscriminate H1. \n \napply DOMFuncRel4. \nQed. \n \n \nLemma NoDACChange :\n forall (s : SFSstate) (o : OBJECT) (SSC : set (SUBJECT * SecClass))\n   (OSC : set (OBJECT * SecClass)) (FILES : set (OBJECT * FILECONT))\n   (DIRECTS : set (OBJECT * DIRCONT)) (SM : set (OBJECT * ReadersWriters)),\n ~\n DACCtrlAttrHaveChanged s\n   (mkSFS (groups s) (primaryGrp s) SSC (AllGrp s) \n      (RootGrp s) (SecAdmGrp s) OSC (acl s) SM FILES DIRECTS) o. \nintros. \nintro. \ninversion H; simpl in H1; cut (y = z). \nintro EQ; rewrite EQ in H2; inversion H2; auto. \n \nrewrite H0 in H1; injection H1; auto. \n \nintro EQ; rewrite EQ in H2; inversion H2; auto. \n \nrewrite H0 in H1; injection H1; auto. \n \nQed. \n \n \nLemma NoDACChange2 :\n forall (s : SFSstate) (o : OBJECT), ~ DACCtrlAttrHaveChanged s s o. \nintros; intro;\n eapply\n  (NoDACChange s o (subjectSC s) (objectSC s) (files s) \n     (directories s) (secmat s)). \ngeneralize H; elim s; simpl in |- *; auto. \n \nQed. \n \n \nLemma NoMACObjChange :\n forall (s : SFSstate) (o : OBJECT) (FILES : set (OBJECT * FILECONT))\n   (DIRECTS : set (OBJECT * DIRCONT))\n   (ACL : set (OBJECT * AccessCtrlListData)) (SSC : set (SUBJECT * SecClass))\n   (SM : set (OBJECT * ReadersWriters)),\n ~\n MACObjCtrlAttrHaveChanged s\n   (mkSFS (groups s) (primaryGrp s) SSC (AllGrp s) \n      (RootGrp s) (SecAdmGrp s) (objectSC s) ACL SM FILES DIRECTS) o. \nintros; intro. \ninversion H; simpl in H1. \ncut (x = y). \nintro EQ; rewrite EQ in H2; inversion H2; auto. \n \nrewrite H0 in H1; injection H1; auto. \n \nQed. \n \n \nLemma NoMACObjChange2 :\n forall (s : SFSstate) (o : OBJECT), ~ MACObjCtrlAttrHaveChanged s s o. \nintros; intro;\n eapply\n  (NoMACObjChange s o (files s) (directories s) (acl s) \n     (subjectSC s) (secmat s)). \ngeneralize H; elim s; simpl in |- *; auto. \n \nQed. \n \n \nLemma NoMACSubChange :\n forall (s : SFSstate) (u : SUBJECT)\n   (ACL : set (OBJECT * AccessCtrlListData)) (OSC : set (OBJECT * SecClass))\n   (FILES : set (OBJECT * FILECONT)) (DIRECTS : set (OBJECT * DIRCONT))\n   (SM : set (OBJECT * ReadersWriters)),\n ~\n MACSubCtrlAttrHaveChanged s\n   (mkSFS (groups s) (primaryGrp s) (subjectSC s) (AllGrp s) \n      (RootGrp s) (SecAdmGrp s) OSC ACL SM FILES DIRECTS) u. \nintros; intro; inversion H. \nsimpl in H1. \ncut (x = y). \nintro EQ; rewrite EQ in H2; inversion H2; auto. \n \nrewrite H0 in H1; injection H1; auto. \n \nQed. \n \n \nLemma NoMACSubChange2 :\n forall (s : SFSstate) (u : SUBJECT), ~ MACSubCtrlAttrHaveChanged s s u. \nintros; intro;\n eapply\n  (NoMACSubChange s u (acl s) (objectSC s) (files s) \n     (directories s) (secmat s)). \ngeneralize H; elim s; simpl in |- *; auto. \n \nQed. \n \n \nLemma eq_scSym : forall a b : SecClass, eq_sc a b -> eq_sc b a. \nunfold eq_sc in |- *; intros. \nelim H; intros. \nrewrite H0; rewrite H1. \nauto. \nQed. \n \n \nLemma ChsubscPSS1 :\n forall (s : SFSstate) (u : SUBJECT) (y : ReadersWriters),\n (forall rw : ReadersWriters,\n  ~ set_In u (ActReaders rw) /\\ ~ set_In u (ActWriters rw)) ->\n ~ (set_In u (ActReaders y) \\/ set_In u (ActWriters y)). \nintros. \ncut (~ set_In u (ActReaders y) /\\ ~ set_In u (ActWriters y)). \ntauto. \n \nauto. \n \nQed. \n \n \nLemma EqfSSC1 :\n forall (s : SFSstate) (u u0 : SUBJECT) (sc : SecClass),\n u <> u0 -> fSSC (subjectSC s) u0 = fSSC (chsubsc_SC s u sc) u0. \nintros; unfold chsubsc_SC in |- *. \nelim (fSSC (subjectSC s) u). \nintros; unfold fSSC in |- *; apply AddRemEq; auto. \n \nauto. \n \nQed. \n \n \nLemma Close_smCorr :\n forall (s : SFSstate) (Sub : SUBJECT) (o : OBJECT),\n FuncPre5 s ->\n match fsecmat (secmat s) o with\n | Some y => set_In Sub (set_union SUBeq_dec (ActReaders y) (ActWriters y))\n | None => False\n end ->\n match fsecmat (close_sm s Sub o) o with\n | None => True\n | Some y => ~ set_In Sub (ActReaders y) /\\ ~ set_In Sub (ActWriters y)\n end. \nintros until o. \ncut\n match fsecmat (secmat s) o with\n | Some y => set_In (o, y) (secmat s)\n | None => ~ set_In o (DOM OBJeq_dec (secmat s))\n end. \nunfold close_sm in |- *. \nelim (fsecmat (secmat s) o); intros. \nelim (set_remove SUBeq_dec Sub (ActReaders a));\n elim (set_remove SUBeq_dec Sub (ActWriters a)). \nreplace (fsecmat (set_remove SECMATeq_dec (o, a) (secmat s)) o) with\n (None (A:=ReadersWriters)). \nauto. \n \nsymmetry  in |- *; unfold fsecmat in |- *; unfold FuncPre5 in H0; auto. \n \nintros. \nreplace\n (fsecmat\n    (set_add SECMATeq_dec (o, NEWRW Sub o a)\n       (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n (Some (NEWRW Sub o a)). \nunfold NEWRW in |- *; simpl in |- *; split; apply Set_remove1. \n \nunfold fsecmat in |- *; apply AddEq1. \nauto. \n \nintros;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec (o, NEWRW Sub o a)\n        (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n  (Some (NEWRW Sub o a)). \nunfold NEWRW in |- *; simpl in |- *; split; apply Set_remove1. \n \nunfold fsecmat in |- *; apply AddEq1. \nauto. \n \nintros;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec (o, NEWRW Sub o a)\n        (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n  (Some (NEWRW Sub o a)). \nunfold NEWRW in |- *; simpl in |- *; split; apply Set_remove1. \n \nunfold fsecmat in |- *; apply AddEq1. \nauto. \n \ntauto. \n \nunfold fsecmat in |- *; apply DOMFuncRel4. \n \nQed. \n \n \nLemma Close_smCorr2 :\n forall (s : SFSstate) (Sub u0 : SUBJECT) (o : OBJECT),\n FuncPre5 s ->\n match fsecmat (secmat s) o with\n | Some y => set_In Sub (set_union SUBeq_dec (ActReaders y) (ActWriters y))\n | None => False\n end ->\n match fsecmat (close_sm s Sub o) o, fsecmat (secmat s) o with\n | _, None => False\n | None, Some z => True\n | Some y, Some z =>\n     (set_In u0 (ActReaders y) -> set_In u0 (ActReaders z)) /\\\n     (set_In u0 (ActWriters y) -> set_In u0 (ActWriters z))\n end. \nintros until o. \ncut\n match fsecmat (secmat s) o with\n | Some y => set_In (o, y) (secmat s)\n | None => ~ set_In o (DOM OBJeq_dec (secmat s))\n end. \nunfold close_sm in |- *. \nelim (fsecmat (secmat s) o); intros. \nelim (set_remove SUBeq_dec Sub (ActReaders a));\n elim (set_remove SUBeq_dec Sub (ActWriters a)). \nreplace (fsecmat (set_remove SECMATeq_dec (o, a) (secmat s)) o) with\n (None (A:=ReadersWriters)). \nauto. \n \nsymmetry  in |- *; unfold fsecmat in |- *; unfold FuncPre5 in H; auto. \n \nintros. \nreplace\n (fsecmat\n    (set_add SECMATeq_dec (o, NEWRW Sub o a)\n       (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n (Some (NEWRW Sub o a)). \nunfold NEWRW in |- *; simpl in |- *. \nsplit;\n [ intro;\n    eapply\n     (Set_remove2 (A:=SUBJECT) (Aeq_dec:=SUBeq_dec) (B:=\n        ActReaders a) (x:=u0) (y:=Sub)); auto\n | intro;\n    eapply\n     (Set_remove2 (A:=SUBJECT) (Aeq_dec:=SUBeq_dec) (B:=\n        ActWriters a) (x:=u0) (y:=Sub)); auto ]. \n \nunfold fsecmat in |- *; apply AddEq1. \nauto. \n \nintros. \nreplace\n (fsecmat\n    (set_add SECMATeq_dec (o, NEWRW Sub o a)\n       (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n (Some (NEWRW Sub o a)). \nunfold NEWRW in |- *; simpl in |- *. \nsplit;\n [ intro;\n    eapply\n     (Set_remove2 (A:=SUBJECT) (Aeq_dec:=SUBeq_dec) (B:=\n        ActReaders a) (x:=u0) (y:=Sub)); auto\n | intro;\n    eapply\n     (Set_remove2 (A:=SUBJECT) (Aeq_dec:=SUBeq_dec) (B:=\n        ActWriters a) (x:=u0) (y:=Sub)); auto ]. \n \n \nunfold fsecmat in |- *; apply AddEq1. \nauto. \n \nintros. \nreplace\n (fsecmat\n    (set_add SECMATeq_dec (o, NEWRW Sub o a)\n       (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n (Some (NEWRW Sub o a)). \nunfold NEWRW in |- *; simpl in |- *. \nsplit;\n [ intro;\n    eapply\n     (Set_remove2 (A:=SUBJECT) (Aeq_dec:=SUBeq_dec) (B:=\n        ActReaders a) (x:=u0) (y:=Sub)); auto\n | intro;\n    eapply\n     (Set_remove2 (A:=SUBJECT) (Aeq_dec:=SUBeq_dec) (B:=\n        ActWriters a) (x:=u0) (y:=Sub)); auto ]. \n \nunfold fsecmat in |- *; apply AddEq1. \nauto. \n \ntauto. \n \nunfold fsecmat in |- *; apply DOMFuncRel4. \n \nQed. \n \n \nLemma Eqfsecmat1 :\n forall (s : SFSstate) (o1 o2 : OBJECT) (u : SUBJECT),\n o1 <> o2 -> fsecmat (secmat s) o2 = fsecmat (close_sm s u o1) o2. \nunfold close_sm, fsecmat in |- *; intros;\n elim (PARTFUNC OBJeq_dec (secmat s) o1). \nintro; elim (set_remove SUBeq_dec u (ActReaders a));\n elim (set_remove SUBeq_dec u (ActWriters a)). \nauto. \n \nauto. \n \nauto. \n \nauto. \n \nauto. \n \nQed. \n \n \nLemma Close_smCorr3 :\n forall (s : SFSstate) (Sub : SUBJECT) (o : OBJECT),\n fsecmat (secmat s) o = None -> fsecmat (close_sm s Sub o) o = None. \nintros until o; unfold close_sm in |- *. \nintro. \ngeneralize H. \nelim (fsecmat (secmat s) o). \nintros y H0; discriminate H0. \n \nauto. \n \nQed. \n \n \nLemma OwnerClose_smCorr2 :\n forall (s : SFSstate) (Sub u0 : SUBJECT) (o : OBJECT),\n FuncPre5 s ->\n match fsecmat (secmat s) o with\n | Some y => set_In Sub (set_union SUBeq_dec (ActReaders y) (ActWriters y))\n | None => False\n end ->\n match fsecmat (ownerclose_sm s Sub o) o, fsecmat (secmat s) o with\n | _, None => False\n | None, Some z => True\n | Some y, Some z =>\n     (set_In u0 (ActReaders y) -> set_In u0 (ActReaders z)) /\\\n     (set_In u0 (ActWriters y) -> set_In u0 (ActWriters z))\n end. \nintros until o. \ncut\n match fsecmat (secmat s) o with\n | Some y => set_In (o, y) (secmat s)\n | None => ~ set_In o (DOM OBJeq_dec (secmat s))\n end. \nunfold ownerclose_sm in |- *. \nelim (fsecmat (secmat s) o); intros. \nelim (set_remove SUBeq_dec Sub (ActReaders a));\n elim (set_remove SUBeq_dec Sub (ActWriters a)). \nreplace (fsecmat (set_remove SECMATeq_dec (o, a) (secmat s)) o) with\n (None (A:=ReadersWriters)). \nauto. \n \nsymmetry  in |- *; unfold fsecmat in |- *; unfold FuncPre5 in H0; auto. \n \nintros. \nreplace\n (fsecmat\n    (set_add SECMATeq_dec (o, NEWRWOC Sub o a)\n       (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n (Some (NEWRWOC Sub o a)). \nunfold NEWRWOC in |- *; simpl in |- *. \nsplit;\n [ intro;\n    eapply\n     (Set_remove2 (A:=SUBJECT) (Aeq_dec:=SUBeq_dec) (B:=\n        ActReaders a) (x:=u0) (y:=Sub)); auto\n | intro;\n    eapply\n     (Set_remove2 (A:=SUBJECT) (Aeq_dec:=SUBeq_dec) (B:=\n        ActWriters a) (x:=u0) (y:=Sub)); auto ]. \n \nunfold fsecmat in |- *; apply AddEq1. \nauto. \n \nintros. \nreplace\n (fsecmat\n    (set_add SECMATeq_dec (o, NEWRWOC Sub o a)\n       (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n (Some (NEWRWOC Sub o a)). \nunfold NEWRWOC in |- *; simpl in |- *. \nsplit;\n [ intro;\n    eapply\n     (Set_remove2 (A:=SUBJECT) (Aeq_dec:=SUBeq_dec) (B:=\n        ActReaders a) (x:=u0) (y:=Sub)); auto\n | intro;\n    eapply\n     (Set_remove2 (A:=SUBJECT) (Aeq_dec:=SUBeq_dec) (B:=\n        ActWriters a) (x:=u0) (y:=Sub)); auto ]. \n \n \nunfold fsecmat in |- *; apply AddEq1. \nauto. \n \nintros. \nreplace\n (fsecmat\n    (set_add SECMATeq_dec (o, NEWRWOC Sub o a)\n       (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n (Some (NEWRWOC Sub o a)). \nunfold NEWRWOC in |- *; simpl in |- *. \nsplit;\n [ intro;\n    eapply\n     (Set_remove2 (A:=SUBJECT) (Aeq_dec:=SUBeq_dec) (B:=\n        ActReaders a) (x:=u0) (y:=Sub)); auto\n | intro;\n    eapply\n     (Set_remove2 (A:=SUBJECT) (Aeq_dec:=SUBeq_dec) (B:=\n        ActWriters a) (x:=u0) (y:=Sub)); auto ]. \n \nunfold fsecmat in |- *; apply AddEq1. \nauto. \n \ntauto. \n \nunfold fsecmat in |- *; apply DOMFuncRel4. \n \nQed. \n \n \nLemma Eqfsecmat2 :\n forall (s : SFSstate) (o1 o2 : OBJECT) (u : SUBJECT),\n o1 <> o2 -> fsecmat (secmat s) o2 = fsecmat (ownerclose_sm s u o1) o2. \nunfold ownerclose_sm, fsecmat in |- *; intros;\n elim (PARTFUNC OBJeq_dec (secmat s) o1). \nintro; elim (set_remove SUBeq_dec u (ActReaders a));\n elim (set_remove SUBeq_dec u (ActWriters a)). \nauto. \n \nauto. \n \nauto. \n \nauto. \n \nauto. \n \nQed. \n \n \nLemma OwnerClose_smCorr3 :\n forall (s : SFSstate) (Sub : SUBJECT) (o : OBJECT),\n fsecmat (secmat s) o = None -> fsecmat (ownerclose_sm s Sub o) o = None. \nintros until o; unfold ownerclose_sm in |- *. \nintro. \ngeneralize H. \nelim (fsecmat (secmat s) o). \nintros y H0; discriminate H0. \n \nauto. \n \nQed. \n \n \nLemma Open_smCorr3 :\n forall (s : SFSstate) (Sub : SUBJECT) (o : OBJECT) (m : MODE),\n FuncPre5 s ->\n fsecmat (open_sm s Sub o m) o = None -> fsecmat (secmat s) o = None. \nintros until m; intro; unfold open_sm in |- *. \ncut\n match fsecmat (secmat s) o with\n | Some y => set_In (o, y) (secmat s)\n | None => ~ set_In o (DOM OBJeq_dec (secmat s))\n end. \nelim m; elim (fsecmat (secmat s) o). \nintro; intro;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec\n        (o, mkRW (set_add SUBeq_dec Sub (ActReaders a)) (ActWriters a))\n        (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n  (Some (mkRW (set_add SUBeq_dec Sub (ActReaders a)) (ActWriters a))). \nintros H2; discriminate H2. \n \nunfold fsecmat in |- *; apply AddEq1; auto. \n \nintro;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec\n        (o,\n        mkRW (set_add SUBeq_dec Sub (empty_set SUBJECT)) (empty_set SUBJECT))\n        (secmat s)) o) with\n  (Some\n     (mkRW (set_add SUBeq_dec Sub (empty_set SUBJECT)) (empty_set SUBJECT))). \nintro H2; discriminate H2. \n \nunfold fsecmat in |- *; apply AddEq1; auto. \n \nintro; intro;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec\n        (o, mkRW (ActReaders a) (set_add SUBeq_dec Sub (ActWriters a)))\n        (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n  (Some (mkRW (ActReaders a) (set_add SUBeq_dec Sub (ActWriters a)))). \nintro H2; discriminate H2. \n \nunfold fsecmat in |- *; apply AddEq1; auto. \nintro;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec\n        (o,\n        mkRW (empty_set SUBJECT) (set_add SUBeq_dec Sub (empty_set SUBJECT)))\n        (secmat s)) o) with\n  (Some\n     (mkRW (empty_set SUBJECT) (set_add SUBeq_dec Sub (empty_set SUBJECT)))). \nintro H2; discriminate H2. \n \nunfold fsecmat in |- *; apply AddEq1; auto. \n \nunfold fsecmat in |- *; apply DOMFuncRel4. \n \nQed. \n \n \nLemma Open_smCorr21 :\n forall (s : SFSstate) (Sub u0 : SUBJECT) (o : OBJECT) (m : MODE),\n Sub <> u0 ->\n FuncPre5 s ->\n match fsecmat (open_sm s Sub o READ) o, fsecmat (secmat s) o with\n | Some y, None =>\n     ActReaders y = set_add SUBeq_dec Sub (empty_set SUBJECT) /\\\n     ActWriters y = empty_set SUBJECT\n | None, _ => False\n | Some y, Some z =>\n     (set_In u0 (ActReaders y) -> set_In u0 (ActReaders z)) /\\\n     (set_In u0 (ActWriters y) -> set_In u0 (ActWriters z))\n end. \nintros. \ncut\n match fsecmat (secmat s) o with\n | Some y => set_In (o, y) (secmat s)\n | None => ~ set_In o (DOM OBJeq_dec (secmat s))\n end. \nunfold open_sm in |- *. \nelim (fsecmat (secmat s) o). \nintros;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec\n        (o, mkRW (set_add SUBeq_dec Sub (ActReaders a)) (ActWriters a))\n        (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n  (Some (mkRW (set_add SUBeq_dec Sub (ActReaders a)) (ActWriters a))). \nsimpl in |- *. \nsplit; (intros; eauto). \n \nunfold fsecmat in |- *; apply AddEq1; auto. \n \nintros;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec\n        (o,\n        mkRW (set_add SUBeq_dec Sub (empty_set SUBJECT)) (empty_set SUBJECT))\n        (secmat s)) o) with\n  (Some\n     (mkRW (set_add SUBeq_dec Sub (empty_set SUBJECT)) (empty_set SUBJECT))). \nauto. \n \nunfold fsecmat in |- *; apply AddEq1; auto. \n \nunfold fsecmat in |- *; apply DOMFuncRel4. \n \nQed. \n \n \nLemma Open_smCorr22 :\n forall (s : SFSstate) (Sub u0 : SUBJECT) (o : OBJECT) (m : MODE),\n Sub <> u0 ->\n FuncPre5 s ->\n match fsecmat (open_sm s Sub o WRITE) o, fsecmat (secmat s) o with\n | Some y, None =>\n     ActWriters y = set_add SUBeq_dec Sub (empty_set SUBJECT) /\\\n     ActReaders y = empty_set SUBJECT\n | None, _ => False\n | Some y, Some z =>\n     (set_In u0 (ActReaders y) -> set_In u0 (ActReaders z)) /\\\n     (set_In u0 (ActWriters y) -> set_In u0 (ActWriters z))\n end. \nintros. \ncut\n match fsecmat (secmat s) o with\n | Some y => set_In (o, y) (secmat s)\n | None => ~ set_In o (DOM OBJeq_dec (secmat s))\n end. \nunfold open_sm in |- *. \nelim (fsecmat (secmat s) o). \nintros;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec\n        (o, mkRW (ActReaders a) (set_add SUBeq_dec Sub (ActWriters a)))\n        (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n  (Some (mkRW (ActReaders a) (set_add SUBeq_dec Sub (ActWriters a)))). \nsimpl in |- *. \nsplit; (intro; eauto). \n \nunfold fsecmat in |- *; apply AddEq1; auto. \n \nintros;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec\n        (o,\n        mkRW (empty_set SUBJECT) (set_add SUBeq_dec Sub (empty_set SUBJECT)))\n        (secmat s)) o) with\n  (Some\n     (mkRW (empty_set SUBJECT) (set_add SUBeq_dec Sub (empty_set SUBJECT)))). \nauto. \n \nunfold fsecmat in |- *; apply AddEq1; auto. \n \nunfold fsecmat in |- *; apply DOMFuncRel4. \n \nQed. \n \n \nLemma Eqfsecmat3 :\n forall (s : SFSstate) (o1 o2 : OBJECT) (u : SUBJECT) (m : MODE),\n o1 <> o2 -> fsecmat (secmat s) o2 = fsecmat (open_sm s u o1 m) o2. \nintros until m; unfold fsecmat, open_sm in |- *. \nelim m; elim (fsecmat (secmat s) o1). \nintros; apply AddRemEq; auto. \n \nintros; apply AddEq; auto. \n \nintros; apply AddRemEq; auto. \n \nintros; apply AddEq; auto. \n \nQed. \n \n \nLemma Chobjsc_Corr :\n forall (s : SFSstate) (o : OBJECT) (sc : SecClass),\n FuncPre6 s ->\n (fOSC (objectSC s) o = None <-> fOSC (chobjsc_SC s o sc) o = None). \nintros; unfold chobjsc_SC in |- *. \ncut\n match fOSC (objectSC s) o with\n | Some y => set_In (o, y) (objectSC s)\n | None => ~ set_In o (DOM OBJeq_dec (objectSC s))\n end. \nsplit. \nintro H1; rewrite H1; auto. \n \ngeneralize H0; elim (fOSC (objectSC s) o). \nintro; intro;\n replace\n  (fOSC\n     (set_add OSCeq_dec (o, sc) (set_remove OSCeq_dec (o, a) (objectSC s))) o)\n  with (Some sc). \nintro H2; discriminate H2. \n \nunfold fOSC in |- *; apply AddEq1. \nauto. \n \nauto. \n \nunfold fOSC in |- *; apply DOMFuncRel4. \n \nQed. \n \n \nLemma Aux1 :\n forall y : SecClass, ~ (Some y = None <-> None = None :>option SecClass). \nintro; unfold iff in |- *; intro H; elim H; intros. \nabsurd (Some y = None); auto. \nintro D; discriminate D. \n \nQed. \n \n \nLemma Chsubsc_Corr :\n forall (s : SFSstate) (u : SUBJECT) (sc : SecClass),\n FuncPre7 s ->\n (fSSC (subjectSC s) u = None <-> fSSC (chsubsc_SC s u sc) u = None). \nintros; unfold chsubsc_SC in |- *. \ncut\n match fSSC (subjectSC s) u with\n | Some y => set_In (u, y) (subjectSC s)\n | None => ~ set_In u (DOM SUBeq_dec (subjectSC s))\n end. \nsplit. \nintro H1; rewrite H1; auto. \n \ngeneralize H0; elim (fSSC (subjectSC s) u). \nintro; intro;\n replace\n  (fSSC\n     (set_add SSCeq_dec (u, sc) (set_remove SSCeq_dec (u, a) (subjectSC s)))\n     u) with (Some sc). \nintro H2; discriminate H2. \n \nunfold fSSC in |- *; apply AddEq1; auto. \nauto. \n \nauto. \n \nunfold fSSC in |- *; apply DOMFuncRel4. \n \nQed. \n \n \nLemma Open_smCorr31 :\n forall (s : SFSstate) (Sub u0 : SUBJECT) (o : OBJECT) (m : MODE),\n FuncPre5 s ->\n match fsecmat (open_sm s Sub o READ) o, fsecmat (secmat s) o with\n | Some y, None =>\n     ActReaders y = set_add SUBeq_dec Sub (empty_set SUBJECT) /\\\n     ActWriters y = empty_set SUBJECT\n | None, _ => False\n | Some y, Some z => set_In u0 (ActWriters y) -> set_In u0 (ActWriters z)\n end. \nintros. \ncut\n match fsecmat (secmat s) o with\n | Some y => set_In (o, y) (secmat s)\n | None => ~ set_In o (DOM OBJeq_dec (secmat s))\n end. \nunfold open_sm in |- *. \nelim (fsecmat (secmat s) o). \nintros;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec\n        (o, mkRW (set_add SUBeq_dec Sub (ActReaders a)) (ActWriters a))\n        (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n  (Some (mkRW (set_add SUBeq_dec Sub (ActReaders a)) (ActWriters a))). \nsimpl in |- *; auto. \n \nunfold fsecmat in |- *; apply AddEq1; auto. \n \nintros;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec\n        (o,\n        mkRW (set_add SUBeq_dec Sub (empty_set SUBJECT)) (empty_set SUBJECT))\n        (secmat s)) o) with\n  (Some\n     (mkRW (set_add SUBeq_dec Sub (empty_set SUBJECT)) (empty_set SUBJECT))). \nsimpl in |- *; auto. \n \nunfold fsecmat in |- *; apply AddEq1; auto. \n \nunfold fsecmat in |- *; apply DOMFuncRel4. \n \nQed. \n \n \nLemma Open_smCorr32 :\n forall (s : SFSstate) (Sub u0 : SUBJECT) (o : OBJECT) (m : MODE),\n FuncPre5 s ->\n match fsecmat (open_sm s Sub o WRITE) o, fsecmat (secmat s) o with\n | Some y, None =>\n     ActWriters y = set_add SUBeq_dec Sub (empty_set SUBJECT) /\\\n     ActReaders y = empty_set SUBJECT\n | None, _ => False\n | Some y, Some z => set_In u0 (ActReaders y) -> set_In u0 (ActReaders z)\n end. \nintros. \ncut\n match fsecmat (secmat s) o with\n | Some y => set_In (o, y) (secmat s)\n | None => ~ set_In o (DOM OBJeq_dec (secmat s))\n end. \nunfold open_sm in |- *. \nelim (fsecmat (secmat s) o). \nintros;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec\n        (o, mkRW (ActReaders a) (set_add SUBeq_dec Sub (ActWriters a)))\n        (set_remove SECMATeq_dec (o, a) (secmat s))) o) with\n  (Some (mkRW (ActReaders a) (set_add SUBeq_dec Sub (ActWriters a)))). \nsimpl in |- *; auto. \n \nunfold fsecmat in |- *; apply AddEq1; auto. \n \nintros;\n replace\n  (fsecmat\n     (set_add SECMATeq_dec\n        (o,\n        mkRW (empty_set SUBJECT) (set_add SUBeq_dec Sub (empty_set SUBJECT)))\n        (secmat s)) o) with\n  (Some\n     (mkRW (empty_set SUBJECT) (set_add SUBeq_dec Sub (empty_set SUBJECT)))). \nsimpl in |- *; auto. \n \nunfold fsecmat in |- *; apply AddEq1; auto. \n \nunfold fsecmat in |- *; apply DOMFuncRel4. \n \nQed. \n \nHint Resolve eq_scIMPLYle_sc eq_scSym Eqfsecmat1 Close_smCorr3 TwoImpLeft\n  TwoImpRight EqfOSC1 ChsubscPSS1 Eqfsecmat2 NoMACObjChange NoDACChange\n  NoMACSubChange EqfOSC6 Eqfacl1 Eqfacl2 Eqfacl3 EqfOSC1 EqfOSC2 EqfOSC3 Aux1\n  NotInDOMIsUndef2 Eqfacl4 EqfOSC4 EqfOSC5 EqfSSC1 OwnerClose_smCorr3\n  Open_smCorr3 Eqfsecmat3 Chobjsc_Corr NoMACObjChange2 NoDACChange2\n  NoMACSubChange2 Chsubsc_Corr NotInDOMIsUndef3 Eqfacl5 EqfOSC7. \n", "meta": {"author": "coq-contribs", "repo": "fssec-model", "sha": "9c1148bf33f69f2e3ca4937e2243200a10c849c0", "save_path": "github-repos/coq/coq-contribs-fssec-model", "path": "github-repos/coq/coq-contribs-fssec-model/fssec-model-9c1148bf33f69f2e3ca4937e2243200a10c849c0/AuxiliaryLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23400269001205848}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.client_lemmas.\nRequire Import VST.floyd.fieldlist.\nRequire Import VST.floyd.type_induction.\nRequire Import VST.floyd.nested_pred_lemmas.\nOpen Scope Z.\n\nModule Type ACR_DEC.\n\n  Parameter align_compatible_rec_dec:\n    forall {cs: compspecs},\n      forall t z, {align_compatible_rec cenv_cs t z} + {~ align_compatible_rec cenv_cs t z}.\n\nEnd ACR_DEC.\n\nModule align_compatible_rec_dec: ACR_DEC.\n\nSection align_compatible_rec_dec.\n\nContext {cs: compspecs}.\n\nDefinition dec_type := sigT (fun P: Z -> Prop => forall z: Z, {P z} + {~ P z}).\n\nDefinition dec_by_value (ch: memory_chunk): dec_type :=\n  existT (fun P: Z -> Prop => forall z: Z, {P z} + {~ P z}) (fun z => (Memdata.align_chunk ch | z)) (fun z => Zdivide_dec (Memdata.align_chunk ch) z (Memdata.align_chunk_pos _)).\n\nDefinition dec_False: dec_type :=\n  existT (fun P: Z -> Prop => forall z: Z, {P z} + {~ P z}) (fun z => False) (fun z => right (fun H => H)).\n\nDefinition dec_True: dec_type :=\n  existT (fun P: Z -> Prop => forall z: Z, {P z} + {~ P z}) (fun z => True) (fun z => left I).\n\nFixpoint cons_in_list {A} (a: A) (al' al: list A) (H: forall x, In x al' -> In x al) (bl: list {x:A| In x al'}) : list {x: A | In x al} :=\n  match bl with\n  | nil => nil\n  | exist x i :: bl0 =>exist _ x (H x i)  :: cons_in_list a al' al H bl0\n  end.\n\nFixpoint make_in_list {A} (al: list A) : list {x: A | In x al} := \n  match al as ax return (al = ax -> list {x : A | In x ax}) with\n           | nil => fun _ => nil\n           | a::al' => fun H: al = a::al' =>\n                      exist _ a (or_introl eq_refl) ::\n                         eq_rect al (fun l : list A => list {x : A | In x l}) \n                          (cons_in_list a al' al (fun (x : A) (H0 : In x al') =>\n                                 eq_ind_r (fun al0 : list A => In x al0) (in_cons _ _ _ H0) H)\n                               (make_in_list al'))\n                        (a :: al') H\n           end (eq_refl _).\n\nLemma in_make_in_list: forall {A} (a: A) (al: list A) H,\n   In (exist (fun x => In x al) a H) (make_in_list al).\nProof.\ninduction al; intros.\ninv H.\ndestruct H.\nsubst a0.\nsimpl.\nleft; auto.\nunfold make_in_list; fold @make_in_list.\nright.\nspecialize (IHal i).\nunfold eq_rect.\nforget (make_in_list al) as bl.\nunfold eq_ind_r.\nunfold eq_ind.\nsimpl.\ninduction bl.\ninv IHal.\ndestruct IHal.\nsubst a1.\nleft. \napply exist_ext; auto.\nspecialize (IHbl H).\nunfold cons_in_list; fold @cons_in_list.\ndestruct a1.\nright. auto.\nQed.\n\nLemma field_type_in_members_strong:\n forall i t m, Ctypes.field_type i m = Errors.OK t ->\n          In (i,t) m.\nProof.\ninduction m; intros.\ninv H.\nsimpl in H.\ndestruct a. if_tac in H. subst. inv H. left; auto.\nright. apply IHm; auto.\nQed.\n\nLemma align_compatible_dec_aux:\n   forall n t, (rank_type cenv_cs t < n)%nat ->\n    forall z, {align_compatible_rec cenv_cs t z} + {~ align_compatible_rec cenv_cs t z}.\nProof.\ninduction n; intros; [ omega | ].\nrename H into Hrank.\ndestruct t  as [ | [ | | | ] [ | ]| [ | ] | [ | ] | | | | | ] eqn:Ht; intros;\ntry solve [\nclear IHn Hrank;\nmatch goal with |- context [align_compatible_rec _ ?t _] =>\nevar (ch: memory_chunk);\nassert (access_mode t = By_value ch) by (subst ch; reflexivity);\n(destruct (Zdivide_dec (Memdata.align_chunk ch) z (Memdata.align_chunk_pos _));\n   [left; econstructor; try reflexivity; eassumption\n   |right;  contradict n; inv n; inv H0; auto])\nend];\ntry solve [right; intro H; inv H; inv H0].\n* (* Tarray *)\nspecialize (IHn t0).\nsimpl in Hrank. spec IHn; [omega | ]. clear Hrank.\npose proof (Zrange_pred_dec (fun ofs => align_compatible_rec cenv_cs t0 (z + sizeof t0 * ofs))).\nspec H.\nintro; apply IHn.\nspecialize (H 0 z0).\ndestruct H as [H|H]; [left|right].\n+\neapply align_compatible_rec_Tarray; intros.\napply H; auto.\n+\ncontradict H.\nintros.\neapply align_compatible_rec_Tarray_inv in H.\napply H.\nsplit; try omega.\n* (* Tstruct *)\ndestruct (cenv_cs ! i) eqn:?H;\n [ | right; intro H0; inv H0; [inv H1 | congruence]].\nsimpl in Hrank. rewrite H in Hrank.\npose (FO id := match Ctypes.field_offset cenv_cs id (co_members c) with\n                      | Errors.OK z0 => z0 | _ => 0 end).\npose (D := fun x: {it: ident*type | In it (co_members c)} =>\n                align_compatible_rec cenv_cs (snd (proj1_sig x)) (z + FO (fst (proj1_sig x)))).\nassert (H1: forall x, {D x} + {~ D x}). {\n subst D. intros. destruct x as [[id t0] ?]. simpl.\n apply IHn.\n assert (H1:= rank_union_member cenv_cs _ a _ _ _ cenv_consistent H i0).\n simpl in H1. rewrite H in H1. omega.\n}\ndestruct (Forall_dec D H1 (make_in_list (co_members c))) as [H2|H2]; clear H1; [left|right].\n+\n eapply align_compatible_rec_Tstruct.\n eassumption.\n assert (H1 := proj1 (Forall_forall _ _) H2); clear H2.\n intros.\n specialize (H1 (exist _ (i0,t0) (field_type_in_members_strong _ _ _ H0))).\n specialize (H1 (in_make_in_list _ _ _)).\n subst D.\n simpl in H1.\n replace z0 with (FO i0).\n apply H1.\n unfold FO. rewrite H2. auto.\n+\n contradict H2.\n apply Forall_forall.\n intros.\n subst D. simpl.\n destruct x as [[id t0] ?].\n eapply align_compatible_rec_Tstruct_inv in H2; try eassumption.\n instantiate (1:=id). simpl.\n pose proof (get_co_members_no_replicate i).\n unfold get_co in H1. rewrite H in H1. unfold members_no_replicate in H1.\n clear - i0 H1.\n induction (co_members c). inv i0. simpl. destruct a.\n if_tac. subst. \n simpl in H1. destruct (id_in_list i (map fst m)) eqn:?; try discriminate.\n destruct i0. inv H. auto.\n apply id_in_list_false in Heqb.\n elimtype False. apply Heqb. apply (in_map fst) in H. apply H.\n apply IHm.\n destruct i0. inv H0. contradiction. auto.\n simpl in H1. destruct (id_in_list i (map fst m)) eqn:?; try discriminate.\n auto.\n unfold FO; simpl.\n clear - i0.\n destruct (Ctypes.field_offset cenv_cs id (co_members c) ) eqn:?H; auto.\n elimtype False.\n unfold Ctypes.field_offset in H. forget 0 as z.\n revert z i0 H; induction (co_members c); intros. inv i0.\n simpl in H. destruct a. if_tac in H. inv H.\n destruct i0. inv H1. contradiction. apply IHm in H. auto. auto.\n* (* Tunion *)\ndestruct (cenv_cs ! i) eqn:?H;\n [ | right; intro H0; inv H0; [inv H1 | congruence]].\nsimpl in Hrank. rewrite H in Hrank.\npose (D := fun x: {it: ident*type | In it (co_members c)} =>\n                align_compatible_rec cenv_cs (snd (proj1_sig x)) z).\nassert (H1: forall x, {D x} + {~ D x}). {\n subst D. intros. destruct x as [[id t0] ?]. simpl.\n apply IHn.\n assert (H1:= rank_union_member cenv_cs _ a _ _ _ cenv_consistent H i0).\n simpl in H1. rewrite H in H1. omega.\n}\ndestruct (Forall_dec D H1 (make_in_list (co_members c))) as [H2|H2]; clear H1; [left|right].\n+\n eapply align_compatible_rec_Tunion.\n eassumption.\n assert (H1 := proj1 (Forall_forall _ _) H2); clear H2.\n intros.\n specialize (H1 (exist _ (i0,t0) (field_type_in_members_strong _ _ _ H0))).\n specialize (H1 (in_make_in_list _ _ _)).\n apply H1.\n+\n contradict H2.\n apply Forall_forall.\n intros.\n subst D. simpl.\n destruct x as [[id t0] ?].\n eapply align_compatible_rec_Tunion_inv in H2; try eassumption.\n instantiate (1:=id). simpl.\n pose proof (get_co_members_no_replicate i).\n unfold get_co in H1. rewrite H in H1. unfold members_no_replicate in H1.\n clear - i0 H1.\n induction (co_members c). inv i0. simpl. destruct a.\n if_tac. subst. \n simpl in H1. destruct (id_in_list i (map fst m)) eqn:?; try discriminate.\n destruct i0. inv H. auto.\n apply id_in_list_false in Heqb.\n elimtype False. apply Heqb. apply (in_map fst) in H. apply H.\n apply IHm.\n destruct i0. inv H0. contradiction. auto.\n simpl in H1. destruct (id_in_list i (map fst m)) eqn:?; try discriminate.\n auto.\nQed.\n\nLemma align_compatible_rec_dec: forall t z, {align_compatible_rec cenv_cs t z} + {~ align_compatible_rec cenv_cs t z}.\nProof.\nintros.\napply align_compatible_dec_aux with (S (rank_type cenv_cs t)).\nomega.\nQed.\n\nEnd align_compatible_rec_dec.\n\nEnd align_compatible_rec_dec.\n\nLemma align_compatible_dec: forall {cs: compspecs} t p, {align_compatible t p} + {~ align_compatible t p}.\nProof.\n  intros.\n  destruct p; try solve [left; unfold align_compatible; simpl; tauto].\n  simpl.\n  apply align_compatible_rec_dec.align_compatible_rec_dec.\nQed.", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/floyd/align_compatible_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544335934766, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.2339631502298544}}
{"text": "Parameter T : Prop.\nParameter t : T.\n\nHint Extern 1 (T) => apply t.\nLtac diverge a := diverge a.\nHint Extern 2 (T) => diverge idtac.\n\nLemma test : T.\nProof.\n  auto. (* executes the first hint, succeeds, and never executes\n           the second hint. *)\nQed.\n\nLemma test2 : T.\nProof.\n  eauto. (* executes the first and second hint;\n            the latter of which results in a \"stack overflow\",\n            and eauto does not solve the goal. *)\nAbort.", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/tests/Test3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23393025824581298}}
{"text": "Require Import CertiGraph.unionfind.env_unionfind_arr.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.UnionFind.\nRequire Import CertiGraph.msl_application.ArrayGraph.\nRequire Import CertiGraph.floyd_ext.share.\nRequire Import VST.floyd.library.\nRequire Import CertiGraph.unionfind.spatial_array_graph.\n\nLocal Coercion UFGraph_LGraph: UFGraph >-> LGraph.\nLocal Identity Coercion ULGraph_LGraph: LGraph >-> UnionFindGraph.LGraph.\nLocal Identity Coercion LGraph_LabeledGraph: UnionFindGraph.LGraph >-> LabeledGraph.\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n#[export] Existing Instances maGraph finGraph liGraph.\n\nLocal Open Scope Z_scope.\n\n(*There is a full definition in the verified malloc, but it's impl-specific*)\n(*Parameter malloc_token': share -> Z -> val -> mpred.*)\n\nDefinition mallocN_spec :=\n DECLARE _mallocN\n  WITH sh:share, n: Z(*, gv:globals*)\n  PRE [tint]\n     PROP (writable_share sh;\n            4 <= n <= Int.max_unsigned\n          )\n     PARAMS (Vint (Int.repr n))\n     GLOBALS ((*gv*))\n     SEP (\n          )\n  POST [ tptr tvoid ]\n     EX v: pointer_val,\n     PROP (malloc_compatible n (pointer_val_val v))\n     LOCAL (temp ret_temp (pointer_val_val v))\n     SEP (\n          memory_block sh n (pointer_val_val v)\n         ).\n(*\nDefinition mallocK_spec :=\n DECLARE _mallocK\n  WITH gv: globals, sh: share, n: Z\n  PRE [tint]\n     PROP (writable_share sh;\n           4 <= n <= Ptrofs.max_unsigned - 12 (*we don't want to malloc 0. The 12 is just some constant from the verified malloc*)\n          )\n     PARAMS (Vptrofs (Ptrofs.repr n))\n     GLOBALS (gv)\n     SEP (mem_mgr gv)\n  POST [ tptr tvoid ]\n     EX v: _,\n     PROP (malloc_compatible n v)\n     LOCAL (temp ret_temp v)\n     SEP (mem_mgr gv; malloc_token' sh n v; memory_block sh n v).\n*)\n(*Basically collapses everything into the mpred defined by SAG_VST\ntakes in a lst of rank-parent pairs(from where? g?)\n  which is converted into the Cdata structures\nsh is the only parameter needed\ndata_at sh (tarray vertex_type (Z.of_nat (length lst)))\n                               (map vgamma2cdata lst) (pointer_val_val x)\n*)\nDefinition whole_graph sh g x :=\n  (@full_graph_at mpred SAGA_VST pointer_val (SAG_VST sh) g x).\n\nDefinition makeSet_spec :=\n  DECLARE _makeSet\n  WITH gv:globals, sh: share, V: Z\n    PRE [tint]\n      PROP (writable_share sh; readable_share sh;\n            0 < V <= Int.max_signed / 8)\n      PARAMS (Vint (Int.repr V))\n      GLOBALS ()\n      SEP ((*mem_mgr gv*))\n    POST [tptr vertex_type]\n      EX rt: pointer_val, (*creates a graph where*)\n      PROP (forall i: Z, 0 <= i < V -> vvalid (makeSet_discrete_Graph (Z.to_nat V)) i) (*anything between 0 and V is a vertex*)\n      LOCAL (temp ret_temp (pointer_val_val rt))\n      SEP (\n           (*mem_mgr gv; malloc_token' sh (V*4) (pointer_val_val rt);*)\n           whole_graph sh (makeSet_discrete_Graph (Z.to_nat V)) rt). (*representation in heap...*)\n\nDefinition freeSet_spec :=\n  DECLARE _freeSet\n  WITH sh: share, p: pointer_val, g: ArrayGraph.UFGraph(*, gv: globals*)\n    PRE [tptr vertex_type]\n    PROP () PARAMS ((pointer_val_val p)) GLOBALS ((*gv*))\n    SEP ((*mem_mgr gv;\n          malloc_token' sh (Z.of_nat (numV' g)) (pointer_val_val p);*)\n          whole_graph sh g p)\n  POST [tvoid]\n    PROP () LOCAL () SEP ((*mem_mgr gv*)).\n\nDefinition find_spec :=\n  DECLARE _find\n  WITH sh: share, g: UFGraph, subsets: pointer_val, i: Z\n    PRE [tptr vertex_type, tint]\n      PROP (writable_share sh; vvalid g i)\n      PARAMS (pointer_val_val subsets; Vint (Int.repr i))\n      GLOBALS ()\n      SEP (whole_graph sh g subsets)\n    POST [tint]\n      EX g': UFGraph, EX rt: Z,\n      PROP (uf_equiv g g' ; uf_root g' i rt)\n      LOCAL (temp ret_temp (Vint (Int.repr rt)))\n      SEP (whole_graph sh g' subsets).\n\nDefinition union_spec :=\n DECLARE _Union\n  WITH sh: share, g: UFGraph, subsets: pointer_val, x: Z, y: Z\n  PRE [tptr vertex_type, tint, tint]\n          PROP  (writable_share sh; vvalid g x; vvalid g y)\n          PARAMS (pointer_val_val subsets; Vint (Int.repr x); Vint (Int.repr y))\n          GLOBALS ()\n          SEP   (whole_graph sh g subsets)\n  POST [ Tvoid ]\n        EX g': UFGraph,\n        PROP (uf_union g x y g')\n        LOCAL ()\n        SEP (whole_graph sh g' subsets).\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/unionfind/uf_arr_specs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2339302466756703}}
{"text": "(*\n    Copyright (C) 2012  G. Gonthier, B. Ziliani, A. Nanevski, D. Dreyer\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n*)\n\nFrom mathcomp\nRequire Import ssreflect ssrbool seq ssrfun.\nFrom LemmaOverloading\nRequire Import heaps rels hprop stmod stsep.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLemma bnd_is_try (A B : Type) (s1 : spec A) (s2 : A -> spec B) i r :\n        verify (try_s s1 s2 (fun y => fr (throw_s B y))) i r ->\n        verify (bind_s s1 s2) i r.\nProof.\nmove=>H; apply: frame0=>D.\ncase: {H D} (H D) (D)=>[[i1]][i2][->][[H1 [H2 H3]]] _ T D.\nsplit=>[|y m].\n- split=>[|x m]; first by apply: fr_pre H1.\n  by case/(locality D H1)=>m1 [->][_]; move/H2; apply: fr_pre.\nmove=>{D} H; apply: T=>h1 h2 E.\nrewrite {i1 i2 H1 H2 H3}E in H * => D1 [H1][H2] H3.\ncase: H=>[[x][h][]|[e][->]]; move/(locality D1 H1);\ncase=>[m1][->][D2] T1; move: (T1); [move/H2 | move/H3]=>H4.\n- move=>T2; case/(locality D2 H4): (T2)=>m3 [->][D3].\n  by exists m3; do !split=>//; left; exists x; exists m1.\nexists m1; do !split=>//; right; exists e; exists m1; split=>//.\nmove=>j1 j2 E D _; rewrite {m1 D2}E in T1 D H4 *.\nexists j1; do !split=>//; move=>k1 k2 -> D2 ->.\nby exists empty; rewrite un0h; do !split=>//; apply: defUnr D2.\nQed.\n\nLocal Notation cont A := (ans A -> heap -> Prop).\n\nSection EvalDo.\nVariables (A B : Type).\n\nLemma val_do (s : spec A) i j (r : cont A) :\n         s.1 i ->\n         (forall x m, s.2 (Val x) i m -> def (m :+ j) -> r (Val x) (m :+ j)) ->\n         (forall e m, s.2 (Exn e) i m -> def (m :+ j) -> r (Exn e) (m :+ j)) ->\n         verify s (i :+ j) r.\nProof.\nmove=>H1 H2 H3; apply: frame; apply: frame0; split=>//.\nby case=>x m H4 D1 D2; [apply: H2 | apply: H3].\nQed.\n\nLemma try_do (s : spec A) s1 s2 i j (r : cont B) :\n        s.1 i ->\n        (forall x m, s.2 (Val x) i m -> verify (s1 x) (m :+ j) r) ->\n        (forall e m, s.2 (Exn e) i m -> verify (s2 e) (m :+ j) r) ->\n        verify (try_s s s1 s2) (i :+ j) r.\nProof.\nmove=>H1 H2 H3; apply: frame0=>D; split=>[|y m].\n- split; first by apply: fr_pre; exists i; exists empty; rewrite unh0.\n  by split=>y m; case/(_ i j (erefl _) D H1)=>m1 [->][D2]; [case/H2 | case/H3].\nby case=>[[x]|[e]][h][]; case/(_ i j (erefl _) D H1)=>m1 [->][D2];\n   [case/H2 | case/H3]=>// _; apply.\nQed.\n\nLemma bnd_do (s : spec A) s2 i j (r : cont B) :\n        s.1 i ->\n        (forall x m, s.2 (Val x) i m -> verify (s2 x) (m :+ j) r) ->\n        (forall e m, s.2 (Exn e) i m -> def (m :+ j) -> r (Exn e) (m :+ j)) ->\n        verify (bind_s s s2) (i :+ j) r.\nProof.\nmove=>H1 H2 H3; apply: bnd_is_try.\napply: try_do=>// e m H4; apply: frame0; apply: frame1=>_.\nby split=>// y m1 [->] -> _; rewrite un0h; apply: H3.\nQed.\n\nEnd EvalDo.\n\nSection EvalReturn.\nVariables (A B : Type).\n\nLemma val_ret v i (r : cont A) :\n       (def i -> r (Val v) i) -> verify (ret_s v) i r.\nProof.\nby rewrite -[i]un0h=>H; apply: val_do=>// x m [->] // [->].\nQed.\n\nLemma try_ret s1 s2 (v : A) i (r : cont B) :\n        verify (s1 v) i r -> verify (try_s (ret_s v) s1 s2) i r.\nProof.\nby rewrite -[i]un0h=>H; apply: try_do=>// x m [->] // [->].\nQed.\n\nLemma bnd_ret s (v : A) i (r : cont B) :\n        verify (s v) i r -> verify (bind_s (ret_s v) s) i r.\nProof. by move=>H; apply: bnd_is_try; apply: try_ret. Qed.\n\nEnd EvalReturn.\n\nSection EvalRead.\nVariables (A B : Type).\n\nLemma val_read v x i (r : cont A) :\n        (def (x :-> v :+ i) -> r (Val v) (x :-> v :+ i)) ->\n        verify (read_s A x) (x :-> v :+ i) r.\nProof.\nmove=>*; apply: val_do; first by [exists v];\nby move=>y m [<-]; move/(_ v (erefl _))=>// [->].\nQed.\n\nLemma try_read s1 s2 v x i (r : cont B) :\n        verify (s1 v) (x :-> v :+ i) r ->\n        verify (try_s (read_s A x) s1 s2) (x :-> v :+ i) r.\nProof.\nmove=>*; apply: try_do; first by [exists v];\nby move=>y m [<-]; move/(_ v (erefl _))=>// [->].\nQed.\n\nLemma bnd_read s v x i (r : cont B) :\n        verify (s v) (x :-> v :+ i) r ->\n        verify (bind_s (read_s A x) s) (x :-> v :+ i) r.\nProof. by move=>*; apply: bnd_is_try; apply: try_read. Qed.\n\nEnd EvalRead.\n\nSection EvalWrite.\nVariables (A B C : Type).\n\nLemma val_write (v : A) (w : B) x i (r : cont unit) :\n        (def (x :-> v :+ i) -> r (Val tt) (x :-> v :+ i)) ->\n        verify (write_s x v) (x :-> w :+ i) r.\nProof.\nmove=>*; apply: val_do; first by [exists B; exists w];\nby move=>y m [// [->] ->].\nQed.\n\nLemma try_write s1 s2 (v: A) (w : C) x i (r : cont B) :\n        verify (s1 tt) (x :-> v :+ i) r ->\n        verify (try_s (write_s x v) s1 s2) (x :-> w :+ i) r.\nProof.\nmove=>*; apply: try_do; first by [exists C; exists w];\nby move=>y m [// [->] ->].\nQed.\n\nLemma bnd_write s (v : A) (w : C) x i (r : cont B) :\n        verify (s tt) (x :-> v :+ i) r ->\n        verify (bind_s (write_s x v) s) (x :-> w :+ i) r.\nProof. by move=>*; apply: bnd_is_try; apply: try_write. Qed.\n\nEnd EvalWrite.\n\nSection EvalAlloc.\nVariables (A B : Type).\n\nLemma val_alloc (v : A) i (r : cont ptr) :\n        (forall x, def (x :-> v :+ i) -> r (Val x) (x :-> v :+ i)) ->\n        verify (alloc_s v) i r.\nProof.\nmove=>H; rewrite -[i]un0h; apply: val_do=>//;\nby move=>y m [x][//][-> ->]; apply: H.\nQed.\n\nLemma try_alloc s1 s2 (v : A) i (r : cont B) :\n        (forall x, verify (s1 x) (x :-> v :+ i) r) ->\n        verify (try_s (alloc_s v) s1 s2) i r.\nProof.\nmove=>H; rewrite -[i]un0h; apply: try_do=>//;\nby move=>y m [x][//][-> ->]; apply: H.\nQed.\n\nLemma bnd_alloc s (v : A) i (r : cont B) :\n        (forall x, verify (s x) (x :-> v :+ i) r) ->\n        verify (bind_s (alloc_s v) s) i r.\nProof. by move=>*; apply: bnd_is_try; apply: try_alloc. Qed.\n\nEnd EvalAlloc.\n\nSection EvalBlockAlloc.\nVariables (A B : Type).\n\nLemma val_allocb (v : A) n i (r : cont ptr) :\n        (forall x, def (updi x (nseq n v) :+ i) ->\n           r (Val x) (updi x (nseq n v) :+ i)) ->\n        verify (allocb_s v n) i r.\nProof.\nmove=>H; rewrite -[i]un0h; apply: val_do=>//;\nby move=>y m [x][//][->]->; apply: H.\nQed.\n\nLemma try_allocb s1 s2 (v : A) n i (r : cont B) :\n        (forall x, verify (s1 x) (updi x (nseq n v) :+ i) r) ->\n        verify (try_s (allocb_s v n) s1 s2) i r.\nProof.\nmove=>H; rewrite -[i]un0h; apply: try_do=>//;\nby move=>y m [x][//][->]->; apply: H.\nQed.\n\nLemma bnd_allocb s (v : A) n i (r : cont B) :\n        (forall x, verify (s x) (updi x (nseq n v) :+ i) r) ->\n        verify (bind_s (allocb_s v n) s) i r.\nProof. by move=>*; apply: bnd_is_try; apply: try_allocb. Qed.\n\nEnd EvalBlockAlloc.\n\nSection EvalDealloc.\nVariables (A B : Type).\n\nLemma val_dealloc (v : A) x i (r : cont unit) :\n        (def i -> r (Val tt) i) ->\n        verify (dealloc_s x) (x :-> v :+ i) r.\nProof.\nmove=>H; apply: val_do; first by [exists A; exists v];\nby move=>y m [//][->] ->; rewrite un0h.\nQed.\n\nLemma try_dealloc s1 s2 (v : B) x i (r : cont A) :\n        verify (s1 tt) i r ->\n        verify (try_s (dealloc_s x) s1 s2) (x :-> v :+ i) r.\nProof.\nmove=>H; apply: try_do; first by [exists B; exists v];\nby move=>y m [//][->] ->; rewrite un0h.\nQed.\n\nLemma bnd_dealloc s (v : B) x i (r : cont A) :\n        verify (s tt) i r ->\n        verify (bind_s (dealloc_s x) s) (x :-> v :+ i) r.\nProof. by move=>*; apply: bnd_is_try; apply: try_dealloc. Qed.\n\nEnd EvalDealloc.\n\nSection EvalThrow.\nVariables (A B : Type).\n\nLemma val_throw e i (r : cont A) :\n        (def i -> r (Exn e) i) -> verify (throw_s A e) i r.\nProof.\nmove=>H; rewrite -[i]un0h; apply: val_do=>//;\nby move=>y m [->] // [->]; rewrite un0h.\nQed.\n\nLemma try_throw s1 s2 e i (r : cont B) :\n        verify (s2 e) i r ->\n        verify (try_s (throw_s A e) s1 s2) i r.\nProof.\nmove=>H; rewrite -[i]un0h; apply: try_do=>//;\nby move=>y m [->] // [->]; rewrite un0h.\nQed.\n\nLemma bnd_throw s e i (r : cont B) :\n        (def i -> r (Exn e) i) ->\n        verify (bind_s (throw_s A e) s) i r.\nProof.\nmove=>H; apply: bnd_is_try; apply: try_throw; apply: frame0.\nby rewrite -[i]un0h; apply: val_do=>// y m [->] // [->]; rewrite un0h.\nQed.\n\nEnd EvalThrow.\n\n(* specialized versions of do lemmas, to handle ghost variables. *)\n\nSection EvalGhost.\nVariables (A B C : Type) (t : C) (p : C -> Pred heap) (q : C -> post A).\nVariables (s1 : A -> spec B) (s2 : exn -> spec B) (i j : heap) (P : Pred heap).\n\nLemma val_gh (r : cont A) :\n        let: s := (fun i => exists x, i \\In p x,\n                   fun y i m => forall x, i \\In p x -> q x y i m) in\n        (forall x m, q t (Val x) i m -> def (m :+ j) -> r (Val x) (m :+ j)) ->\n        (forall e m, q t (Exn e) i m -> def (m :+ j) -> r (Exn e) (m :+ j)) ->\n        i \\In p t ->\n        verify s (i :+ j) r.\nProof. by move=>*; apply: val_do=>/=; eauto. Qed.\n\nLemma val_gh1 (r : cont A) :\n        let: Q := fun y i m => forall x, i \\In p x -> q x y i m in\n        (i \\In p t -> P i) ->\n        (forall x m, q t (Val x) i m -> def (m :+ j) -> r (Val x) (m :+ j)) ->\n        (forall e m, q t (Exn e) i m -> def (m :+ j) -> r (Exn e) (m :+ j)) ->\n        i \\In p t ->\n        verify (P, Q) (i :+ j) r.\nProof. by move=>*; apply: val_do=>/=; eauto. Qed.\n\nLemma try_gh (r : cont B) :\n        let: s := (fun i => exists x, i \\In p x,\n                   fun y i m => forall x, i \\In p x -> q x y i m) in\n        (forall x m, q t (Val x) i m -> verify (s1 x) (m :+ j) r) ->\n        (forall e m, q t (Exn e) i m -> verify (s2 e) (m :+ j) r) ->\n        i \\In p t ->\n        verify (try_s s s1 s2) (i :+ j) r.\nProof. by move=>*; apply: try_do=>/=; eauto. Qed.\n\nLemma try_gh1 (r : cont B) :\n        let: Q := fun y i m => forall x, i \\In p x -> q x y i m in\n        (i \\In p t -> P i) ->\n        (forall x m, q t (Val x) i m -> verify (s1 x) (m :+ j) r) ->\n        (forall e m, q t (Exn e) i m -> verify (s2 e) (m :+ j) r) ->\n        i \\In p t ->\n        verify (try_s (P, Q) s1 s2) (i :+ j) r.\nProof. by move=>*; apply: try_do=>/=; eauto. Qed.\n\nLemma bnd_gh (r : cont B) :\n        let: s := (fun i => exists x, i \\In p x,\n                   fun y i m => forall x, i \\In p x -> q x y i m) in\n        (forall x m, q t (Val x) i m -> verify (s1 x) (m :+ j) r) ->\n        (forall e m, q t (Exn e) i m -> def (m :+ j) -> r (Exn e) (m :+ j)) ->\n        i \\In p t ->\n        verify (bind_s s s1) (i :+ j) r.\nProof. by move=>*; apply: bnd_do=>/=; eauto. Qed.\n\nLemma bnd_gh1 (r : cont B) :\n        let: Q := fun y i m => forall x, i \\In p x -> q x y i m in\n        (i \\In p t -> P i) ->\n        (forall x m, q t (Val x) i m -> verify (s1 x) (m :+ j) r) ->\n        (forall e m, q t (Exn e) i m -> def (m :+ j) -> r (Exn e) (m :+ j)) ->\n        i \\In p t ->\n        verify (bind_s (P, Q) s1) (i :+ j) r.\nProof. by move=>*; apply: bnd_do=>/=; eauto. Qed.\n\nEnd EvalGhost.\n\n(*****************************************************************************)\n(* associativity lemmas should go here, but I don't want to bother right now *)\n(*****************************************************************************)\n\n(* packaging up the lemmas into a tactic that selects them appropriately *)\n\nDefinition pull (A : Type) x (v:A) := (unC (x :-> v), unCA (x :-> v)).\nDefinition push (A : Type) x (v:A) := (unCA (x :-> v), unC (x :-> v)).\n\nLtac hstep :=\n  match goal with\n    | |- verify ?h (ret_s _) _ =>\n      apply: val_ret\n    | |- verify ?h (try_s (ret_s _) _ _) _ =>\n      apply: try_ret\n    | |- verify ?h (bind_s (ret_s _) _) _ =>\n      apply: bnd_ret\n\n    | |- verify ?h (read_s _ ?l) _ =>\n      rewrite -?(pull l); apply: val_read\n    | |- verify ?h (try_s (read_s _ ?l) _ _) _ =>\n      rewrite -?(pull l); apply: try_read\n    | |- verify (?h) (bind_s (read_s _ ?l) _) _ =>\n      rewrite -?(pull l); apply: bnd_read\n\n    | |- verify (?h) (write_s ?l _) _ =>\n      rewrite -?(pull l); apply: val_write\n    | |- verify (?h) (try_s (write_s ?l _) _ _) _ =>\n      rewrite -?(pull l); apply: try_write\n    | |- verify (?h) (bind_s (write_s ?l _) _) _ =>\n      rewrite -?(pull l); apply: bnd_write\n\n    | |- verify ?h (alloc_s _) _ =>\n      apply: val_alloc\n    | |- verify ?h (try_s (alloc_s _) _ _) _ =>\n      apply: try_alloc\n    | |- verify ?h (bind_s (alloc_s _) _) _ =>\n      apply: bnd_alloc\n\n    | |- verify ?h (allocb_s _ _) _ =>\n      apply: val_allocb\n    | |- verify ?h (try_s (allocb_s _ _) _ _) _ =>\n      apply: try_allocb\n    | |- verify ?h (bind_s (allocb_s _ _) _) _ =>\n      apply: bnd_allocb\n\n    | |- verify ?h (dealloc_s ?l) _ =>\n      rewrite -?(pull l); apply: val_dealloc\n    | |- verify ?h (try_s (dealloc_s ?l) _ _) _ =>\n      rewrite -?(pull l); apply: try_dealloc\n    | |- verify ?h (bind_s (dealloc_s ?l) _) _ =>\n      rewrite -?(pull l); apply: bnd_dealloc\n\n    | |- verify ?h (throw_s _ _) _ =>\n      apply: val_throw\n    | |- verify ?h (try_s (throw_s _ _) _ _) _ =>\n      apply: try_throw\n    | |- verify ?h (bind_s (throw_s _ _) _) _ =>\n      apply: bnd_throw\n  end.\n\nLemma swp : forall (A : Type) (v : A) x h, h \\In x :--> v <-> h = x :-> v.\nProof. by move=>A v x h; split; rewrite InE /pts /=; unlock. Qed.\n\nLemma opn : forall (A : Type) (v : A) x h, h \\In x :--> v <-> x :-> v = h.\nProof. by move=>A v x h; split=>[|H]; rewrite InE /= /pts; unlock. Qed.\n\nPrenex Implicits swp opn.\n\n\nLemma blah (A : Type) (p : ptr) (l : A) : def (p :-> l) -> (p :-> l) \\In p :--> l.\nProof. by move=>H; apply/swp. Qed.\n\nHint Immediate blah : core.\n\nLemma blah2 (A : Type) (v1 v2 : A) q :\n        def (q :-> v1) -> v1 = v2 -> q :-> v1 \\In q :--> v2.\nProof. by move=>D E; apply/swp; rewrite E. Qed.\n\nHint Immediate blah2 : core.\n\nLtac hauto := (do ?econstructor=>//;\n                try by [defcheck; auto |\n                       eapply blah2; defcheck; auto])=>//.\n\nLtac hhauto := (do ?econstructor=>//; try by [heap_congr])=>//.\nLtac hdone := repeat progress hhauto=>//=.\nLtac heval := do ![hstep | by hhauto].\n", "meta": {"author": "coq-community", "repo": "lemma-overloading", "sha": "e1c8bb876c7a26b90181d165f606cd35912ffa74", "save_path": "github-repos/coq/coq-community-lemma-overloading", "path": "github-repos/coq/coq-community-lemma-overloading/lemma-overloading-e1c8bb876c7a26b90181d165f606cd35912ffa74/theories/stlog.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.23392444862057515}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import CRelationClasses ProofIrrelevance ssreflect ssrbool.\nFrom MetaCoq.Template Require Import config Universes utils BasicAst.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICInduction\n     PCUICReflect PCUICLiftSubst PCUICUnivSubst PCUICTyping PCUICUnivSubstitutionConv\n     PCUICUnivSubstitutionTyp\n     PCUICCumulativity PCUICPosition PCUICEquality PCUICSigmaCalculus\n     PCUICInversion PCUICCumulativity PCUICReduction\n     PCUICConfluence PCUICConversion PCUICContextConversion\n     PCUICWeakeningEnvConv PCUICWeakeningEnvTyp PCUICClosed PCUICClosedTyp PCUICSubstitution PCUICWfUniverses\n     PCUICWeakeningConv PCUICWeakeningTyp PCUICGeneration PCUICUtils PCUICContexts\n     PCUICWellScopedCumulativity PCUICConversion PCUICOnFreeVars.\n\nRequire Import Equations.Prop.DepElim.\nRequire Import Equations.Type.Relation_Properties.\nFrom Equations Require Import Equations.\n\nImplicit Types cf : checker_flags.\n\nNotation isWAT := (isWfArity typing).\n\nLemma isType_Sort {cf:checker_flags} {Σ Γ s} :\n  wf_universe Σ s ->\n  wf_local Σ Γ ->\n  isType Σ Γ (tSort s).\nProof.\n  intros wfs wfΓ.\n  eexists; econstructor; eauto.\nQed.\n#[global] Hint Resolve isType_Sort : pcuic.\n\nDefinition wf_typing_spine {cf} {Σ Γ T args T'} :=\n  isType Σ Γ T × typing_spine Σ Γ T args T'.\n\nLemma isArity_it_mkProd_or_LetIn Γ t : isArity t -> isArity (it_mkProd_or_LetIn Γ t).\nProof.\n  intros isA. induction Γ using rev_ind; simpl; auto.\n  rewrite it_mkProd_or_LetIn_app. simpl; auto.\n  destruct x as [? [?|] ?]; simpl; auto.\nQed.\n\nInductive typing_spine {cf} Σ (Γ : context) : term -> list term -> term -> Type :=\n| type_spine_nil ty ty' :\n    isType Σ Γ ty ->\n    isType Σ Γ ty' ->\n    Σ ;;; Γ ⊢ ty ≤ ty' ->\n    typing_spine Σ Γ ty [] ty'\n\n| type_spine_cons ty hd tl na A B B' :\n    isType Σ Γ ty ->\n    isType Σ Γ (tProd na A B) ->\n    Σ ;;; Γ ⊢ ty ≤ tProd na A B ->\n    Σ ;;; Γ |- hd : A ->\n    typing_spine Σ Γ (subst10 hd B) tl B' ->\n    typing_spine Σ Γ ty (hd :: tl) B'.\n\nDerive Signature NoConfusion for typing_spine.\n\nLemma typing_spine_isType_codom {cf} {Σ : global_env_ext} {wfΣ : wf Σ} {Γ T args U} :\n  typing_spine Σ Γ T args U -> isType Σ Γ U.\nProof.\n  induction 1; auto.\nQed.\n\nLemma subslet_inds_gen {cf} {Σ : global_env} {wfΣ : wf Σ} ind mdecl idecl :\n  declared_inductive Σ ind mdecl idecl ->\n  let u := abstract_instance (ind_universes mdecl) in\n  subslet (Σ, ind_universes mdecl) [] (inds (inductive_mind ind) u (ind_bodies mdecl))\n    (arities_context (ind_bodies mdecl)).\nProof.\n  intros isdecl u.\n  unfold inds.\n  pose proof (proj1 isdecl) as declm'.\n  apply on_declared_minductive in declm' as [oind oc]; auto.\n  clear oc.\n  assert (Alli (fun i x =>\n  (Σ, ind_universes mdecl) ;;; [] |- tInd {| inductive_mind := inductive_mind ind; inductive_ind := i |} u : (ind_type x)) 0 (ind_bodies mdecl)).\n  { apply forall_nth_error_Alli. intros.\n    eapply Alli_nth_error in oind; eauto. simpl in oind.\n    destruct oind. destruct onArity as [s Hs].\n    eapply type_Cumul; eauto.\n    econstructor; eauto. split; eauto with pcuic.\n    eapply consistent_instance_ext_abstract_instance; eauto.\n    eapply declared_inductive_wf_global_ext; eauto with pcuic.\n    rewrite (subst_instance_ind_type_id Σ _ {| inductive_mind := inductive_mind ind; inductive_ind := i |}); eauto.\n    destruct isdecl. split; eauto. reflexivity. }\n  clear oind.\n  revert X. clear onNpars.\n  generalize (le_n #|ind_bodies mdecl|).\n  generalize (ind_bodies mdecl) at 1 3 4 5.\n  induction l using rev_ind; simpl; first constructor.\n  rewrite /subst_instance /= /map_context.\n  simpl. rewrite /arities_context rev_map_spec /=.\n  rewrite map_app /= rev_app_distr /=.\n  rewrite /= app_length /= Nat.add_1_r.\n  constructor.\n  - rewrite -rev_map_spec. apply IHl; try lia.\n    eapply Alli_app in X; intuition auto.\n  - eapply Alli_app in X as [oind Hx].\n    depelim Hx. clear Hx.\n    rewrite Nat.add_0_r in t.\n    rewrite subst_closedn; auto.\n    + eapply typecheck_closed in t as [? ?]; auto.\n      destruct p as [? ?].\n      now move/andb_and: i0=> [? ?].\nQed.\n\nSection WfEnv.\n  Context {cf:checker_flags} {Σ : global_env_ext} {wfΣ : wf Σ}.\n\n  Lemma ws_cumul_ctx_pb_vass {Γ Γ' na na' A A'} le :\n    eq_binder_annot na na' ->\n    Σ ⊢ Γ ≤[le] Γ' ->\n    Σ ;;; Γ ⊢ A ≤[le] A' ->\n    Σ ⊢ Γ ,, vass na A ≤[le] Γ' ,, vass na' A'.\n  Proof using Type.\n    repeat (constructor; auto).\n  Qed.\n\n  Lemma ws_cumul_ctx_pb_app {le Γ Γ' Δ Δ'} :\n    #|Δ| = #|Δ'| ->\n    Σ ⊢ Γ ,,, Δ ≤[le] Γ' ,,, Δ' <~>\n    Σ ⊢ Γ ≤[le] Γ' × ws_cumul_ctx_pb_rel le Σ Γ Δ Δ'.\n  Proof using wfΣ.\n    move => hlen; split.\n    - move/All2_fold_app_inv. move/(_ hlen) => [] onΓ onΔ; split => //.\n      split; eauto with fvs.\n    - move=> [] onΓ [_ onΔ].\n      apply All2_fold_app; auto.\n  Qed.\n\n\n  Lemma invert_cumul_arity_l (Γ : context) (C : term) T :\n    Σ;;; Γ ⊢ C ≤ T ->\n    match destArity [] C with\n    | Some (ctx, s) =>\n      ∑ T' ctx' s',\n        [× Σ ;;; Γ ⊢ T ⇝ T', (destArity [] T' = Some (ctx', s')),\n          Σ ⊢ Γ ,,, smash_context [] ctx = Γ ,,, ctx' &\n          leq_universe (global_ext_constraints Σ) s s']\n    | None => unit\n    end.\n  Proof using wfΣ.\n    intros CT.\n    generalize (destArity_spec [] C). destruct destArity as [[ctx p]|].\n    simpl. intros ->. 2:intros _; exact tt.\n    revert Γ T CT.\n    generalize (@le_n #|ctx|).\n    generalize (#|ctx|) at 2. intros n; revert ctx.\n    induction n; intros ctx Hlen Γ T HT.\n    - destruct ctx; simpl in Hlen; try lia.\n      eapply ws_cumul_pb_Sort_l_inv in HT as [u' [redT leqT]].\n      exists (tSort u'), [], u'; split; auto.\n      cbn. eapply ws_cumul_ctx_pb_refl; eauto with fvs.\n    - destruct ctx using rev_ind.\n      * eapply ws_cumul_pb_Sort_l_inv in HT as [u' [redT leqT]].\n        exists (tSort u'), [], u'; split; auto; cbn.\n        apply ws_cumul_ctx_pb_refl; eauto with fvs.\n      * rewrite it_mkProd_or_LetIn_app in HT; simpl in HT.\n        destruct x as [na [b|] ty]; unfold mkProd_or_LetIn in HT; simpl in *.\n        + eapply ws_cumul_pb_LetIn_l_inv in HT; auto.\n          unfold subst1 in HT; rewrite subst_it_mkProd_or_LetIn in HT.\n          rewrite app_length /= Nat.add_1_r in Hlen.\n          simpl in HT. specialize (IHn (subst_context [b] 0 ctx) ltac:(rewrite\n          subst_context_length; lia) Γ T HT).\n          destruct IHn as [T' [ctx' [s' [redT destT convctx leq]]]].\n          clear IHctx.\n          exists T', ctx', s'. split; auto.\n          rewrite smash_context_app. simpl.\n          now rewrite -smash_context_subst_empty.\n        + eapply ws_cumul_pb_Prod_l_inv in HT; auto.\n          rewrite -> app_length in Hlen.\n          rewrite Nat.add_1_r in Hlen.\n          destruct HT as [na' [A' [B' [redT convT HT]]]].\n          specialize (IHn ctx ltac:(lia) (Γ ,, vass na' A') B').\n          forward IHn. eapply ws_cumul_pb_ws_cumul_ctx; eauto.\n          { apply ws_cumul_ctx_pb_vass; eauto. now symmetry.\n            eapply ws_cumul_ctx_pb_refl. eauto with fvs.\n            now symmetry. }\n          clear IHctx.\n          destruct IHn as [T' [ctx' [s' [redT' destT convctx leq]]]].\n          exists (tProd na' A' T'), (ctx' ++ [vass na' A']), s'. split; auto. 2:simpl.\n          -- transitivity (tProd na' A' B'); auto.\n            split.\n            3:eapply red_prod; [reflexivity|apply redT'].\n            all:eauto with fvs.\n          -- now rewrite destArity_app destT.\n          -- rewrite smash_context_app /= .\n            rewrite !app_context_assoc.\n            assert (#|smash_context [] ctx| = #|ctx'|).\n            { apply All2_fold_length in convctx.\n              autorewrite with len in convctx |- *.\n              simpl in convctx. simpl. lia. }\n            etransitivity; tea.\n            apply ws_cumul_ctx_pb_app; auto.\n            split. apply ws_cumul_ctx_pb_vass; auto.\n            apply ws_cumul_ctx_pb_refl; eauto with fvs.\n            eapply ws_cumul_ctx_pb_app; eauto.\n            eapply ws_cumul_ctx_pb_refl; eauto with fvs.\n            eapply ws_cumul_ctx_pb_closed_left in convctx.\n            move: convctx.\n            rewrite !on_free_vars_ctx_app. autorewrite with fvs.\n            move/andP => [] /andP[] -> /=; cbn; rewrite andb_true_r => onA' ->.\n            rewrite shiftnP0 andb_true_r; eauto with fvs.\n  Qed.\n\n  Lemma isType_tProd {Γ} {na A B} :\n    isType Σ Γ (tProd na A B) <~> (isType Σ Γ A × isType Σ (Γ,, vass na A) B).\n  Proof.\n    split; intro HH.\n    - destruct HH as [s H].\n      apply inversion_Prod in H; tas. destruct H as [s1 [s2 [HA [HB Hs]]]].\n      split.\n      * eexists; tea.\n      * eexists; tea.\n    - destruct HH as [HA HB].\n      destruct HA as [sA HA], HB as [sB HB].\n      eexists. econstructor; eassumption.\n  Defined.\n\n  Lemma isType_subst {Γ Δ A} s :\n    subslet Σ Γ s Δ ->\n    isType Σ (Γ ,,, Δ) A ->\n    isType Σ Γ (subst0 s A).\n  Proof using wfΣ.\n    intros sub HT.\n    apply infer_typing_sort_impl with id HT; intros Hs.\n    have wf := typing_wf_local Hs.\n    now eapply (substitution (Δ := []) (T := tSort _)).\n  Qed.\n\n  Lemma isType_subst_gen {Γ Δ Δ'} {A} s :\n    subslet Σ Γ s Δ ->\n    isType Σ (Γ ,,, Δ ,,, Δ') A ->\n    isType Σ (Γ ,,, subst_context s 0 Δ') (subst s #|Δ'| A).\n  Proof using wfΣ.\n    intros sub HT.\n    apply infer_typing_sort_impl with id HT; intros Hs.\n    now eapply (substitution (T:=tSort _)).\n  Qed.\n\n  Lemma type_ws_cumul_pb {pb Γ t} T {U} :\n    Σ ;;; Γ |- t : T ->\n    isType Σ Γ U ->\n    Σ ;;; Γ ⊢ T ≤[pb] U ->\n    Σ ;;; Γ |- t : U.\n  Proof using Type.\n    intros.\n    eapply type_Cumul; tea. apply X0.π2.\n    destruct pb.\n    - eapply ws_cumul_pb_eq_le in X1.\n      now eapply cumulAlgo_cumulSpec in X1.\n    - now eapply cumulAlgo_cumulSpec.\n  Qed.\n\n  Lemma isType_tLetIn_red {Γ} (HΓ : wf_local Σ Γ) {na t A B}\n    : isType Σ Γ (tLetIn na t A B) -> isType Σ Γ (B {0:=t}).\n  Proof using wfΣ.\n    intro HH.\n    apply infer_typing_sort_impl with id HH; intros H.\n    assert (Hs := typing_wf_universe _ H).\n    apply inversion_LetIn in H; tas. destruct H as (s1 & A' & HA & Ht & HB & H).\n    eapply (type_ws_cumul_pb (pb:=Cumul)) with (A' {0 := t}). eapply substitution_let in HB; eauto.\n    * econstructor; eauto with pcuic. econstructor; eauto.\n    * eapply ws_cumul_pb_Sort_r_inv in H as [s' [H H']].\n      transitivity (tSort s'); eauto.\n      eapply red_ws_cumul_pb.\n      apply invert_red_letin in H as [H|H] => //.\n      destruct H as (d' & ty' & b' & [reds ]).\n      discriminate.\n      repeat constructor; eauto with fvs.\n  Qed.\n\n  Lemma isType_tLetIn_dom {Γ} (HΓ : wf_local Σ Γ) {na t A B}\n    : isType Σ Γ (tLetIn na t A B) -> Σ ;;; Γ |- t : A.\n  Proof using wfΣ.\n    intros (s & H).\n    apply inversion_LetIn in H; tas. now destruct H as (s1 & A' & HA & Ht & HB & H).\n  Qed.\n\n  Lemma wf_local_ass {Γ na A} :\n    wf_local Σ Γ ->\n    isType Σ Γ A ->\n    wf_local Σ (Γ ,, vass na A).\n  Proof using Type.\n    constructor; eauto with pcuic.\n  Qed.\n\n  Lemma wf_local_def {Γ na d ty} :\n    wf_local Σ Γ ->\n    isType Σ Γ ty ->\n    Σ ;;; Γ |- d : ty ->\n    wf_local Σ (Γ ,, vdef na d ty).\n  Proof using Type.\n    constructor; eauto with pcuic.\n  Qed.\n\n  Hint Resolve wf_local_ass wf_local_def : pcuic.\n  Hint Transparent snoc : pcuic.\n\n  Lemma isType_apply {Γ na A B t} :\n    isType Σ Γ (tProd na A B) ->\n    Σ ;;; Γ |- t : A ->\n    isType Σ Γ (B {0 := t}).\n  Proof using wfΣ.\n    move/isType_tProd => [hA hB] ht.\n    eapply (isType_subst (Δ:= [vass na A])); eauto with pcuic.\n  Qed.\n\n  Hint Resolve isType_wf_local : pcuic.\n\n  Lemma typing_spine_letin_inv {Γ na b B T args S} :\n    typing_spine Σ Γ (tLetIn na b B T) args S ->\n    typing_spine Σ Γ (T {0 := b}) args S.\n  Proof using wfΣ.\n    intros Hsp.\n    depelim Hsp.\n    constructor; auto.\n    eapply isType_tLetIn_red in i; eauto with pcuic.\n    now eapply ws_cumul_pb_LetIn_l_inv in w.\n    econstructor; eauto.\n    eapply isType_tLetIn_red in i; eauto with pcuic.\n    now eapply ws_cumul_pb_LetIn_l_inv in w.\n  Qed.\n\n  Lemma typing_spine_letin {Γ na b B T args S} :\n    isType Σ Γ (tLetIn na b B T) ->\n    typing_spine Σ Γ (T {0 := b}) args S ->\n    typing_spine Σ Γ (tLetIn na b B T) args S.\n  Proof using wfΣ.\n    intros Hty Hsp.\n    depelim Hsp.\n    constructor; auto.\n    - etransitivity; tea. eapply into_ws_cumul_pb.\n      eapply red_cumul, red1_red, red_zeta. all:eauto with fvs.\n    - econstructor; eauto.\n      etransitivity; tea.\n      eapply into_ws_cumul_pb.\n      eapply red_cumul. eapply red1_red, red_zeta.\n      all:eauto with fvs.\n  Qed.\n\n  Lemma typing_spine_weaken_concl {Γ T args S S'} :\n    typing_spine Σ Γ T args S ->\n    Σ ;;; Γ ⊢ S ≤ S' ->\n    isType Σ Γ S' ->\n    typing_spine Σ Γ T args S'.\n  Proof using wfΣ.\n    induction 1 in S' => cum.\n    constructor; auto. transitivity ty'; auto.\n    intros isType.\n    econstructor; eauto.\n  Qed.\n\n  Lemma typing_spine_prod {Γ na b B T args S} :\n    typing_spine Σ Γ (T {0 := b}) args S ->\n    isType Σ Γ (tProd na B T) ->\n    Σ ;;; Γ |- b : B ->\n    typing_spine Σ Γ (tProd na B T) (b :: args) S.\n  Proof using wfΣ.\n    intros Hsp.\n    depelim Hsp.\n    econstructor; eauto with pcuic.\n    - constructor; auto with pcuic.\n    - intros Har.\n      destruct (fst isType_tProd Har) as [? ?]; eauto using typing_wf_local.\n      intros Hb.\n      econstructor; eauto with pcuic.\n      econstructor; revgoals; eauto with pcuic.\n  Qed.\n\n  Lemma typing_spine_WAT_concl {Γ T args S} :\n    typing_spine Σ Γ T args S ->\n    isType Σ Γ S.\n  Proof using Type.\n    induction 1; auto.\n  Qed.\n\n  Lemma typing_spine_isType_dom {Γ T args S} :\n    typing_spine Σ Γ T args S ->\n    isType Σ Γ T.\n  Proof using Type.\n    induction 1; auto.\n  Qed.\n\n  Lemma type_mkProd_or_LetIn {Γ} d {u t s} :\n    Σ ;;; Γ |- decl_type d : tSort u ->\n    Σ ;;; Γ ,, d |- t : tSort s ->\n    match decl_body d return Type with\n    | Some b => Σ ;;; Γ |- mkProd_or_LetIn d t : tSort s\n    | None => Σ ;;; Γ |- mkProd_or_LetIn d t : tSort (Universe.sort_of_product u s)\n    end.\n  Proof using wfΣ.\n    destruct d as [na [b|] dty] => [Hd Ht|Hd Ht]; rewrite /mkProd_or_LetIn /=.\n    - have wf := typing_wf_local Ht.\n      depelim wf. clear l.\n      eapply type_Cumul. econstructor; eauto.\n      econstructor; eauto. now eapply typing_wf_universe in Ht; pcuic.\n      eapply convSpec_cumulSpec, red1_cumulSpec. constructor.\n    - have wf := typing_wf_local Ht.\n      depelim wf; clear l.\n      eapply type_Prod; eauto.\n  Qed.\n\n  Lemma type_it_mkProd_or_LetIn {Γ Γ' u t s} :\n    wf_universe Σ u ->\n    type_local_ctx (lift_typing typing) Σ Γ Γ' u ->\n    Σ ;;; Γ ,,, Γ' |- t : tSort s ->\n    Σ ;;; Γ |- it_mkProd_or_LetIn Γ' t : tSort (Universe.sort_of_product u s).\n  Proof using wfΣ.\n    revert Γ u s t.\n    induction Γ'; simpl; auto; move=> Γ u s t wfu equ Ht.\n    - eapply type_Cumul; eauto.\n      econstructor; eauto using typing_wf_local with pcuic.\n      eapply typing_wf_universe in Ht; auto with pcuic.\n      eapply cumul_Sort. eapply leq_universe_product.\n    - specialize (IHΓ' Γ  u (Universe.sort_of_product u s)); auto.\n      unfold app_context in Ht.\n      eapply type_Cumul.\n      eapply IHΓ'; auto.\n      destruct a as [na [b|] ty]; intuition auto.\n      destruct a as [na [b|] ty]; intuition auto.\n      { apply typing_wf_local in Ht as XX. inversion XX; subst.\n        eapply (type_mkProd_or_LetIn {| decl_body := Some b |}); auto.\n        + simpl. exact X0.π2.\n        + eapply type_Cumul; eauto.\n          econstructor; eauto with pcuic.\n          eapply cumul_Sort. eapply leq_universe_product. }\n      eapply (type_mkProd_or_LetIn {| decl_body := None |}) => /=; eauto.\n      econstructor; eauto with pcuic.\n      eapply typing_wf_local in Ht.\n      depelim Ht; eapply All_local_env_app_inv in Ht; intuition auto.\n      now rewrite sort_of_product_twice.\n  Qed.\n\n  Fixpoint sort_of_products us s :=\n    match us with\n    | [] => s\n    | u :: us => sort_of_products us (Universe.sort_of_product u s)\n    end.\n\n  Lemma leq_universe_sort_of_products_mon {u u' v v'} :\n    Forall2 (leq_universe Σ) u u' ->\n    leq_universe Σ v v' ->\n    leq_universe Σ (sort_of_products u v) (sort_of_products u' v').\n  Proof using Type.\n    intros hu; induction hu in v, v' |- *; simpl; auto with pcuic.\n    intros lev. eapply IHhu.\n    eapply leq_universe_product_mon => //.\n  Qed.\n\n  Lemma type_it_mkProd_or_LetIn_sorts {Γ Γ' us t s} :\n    sorts_local_ctx (lift_typing typing) Σ Γ Γ' us ->\n    Σ ;;; Γ ,,, Γ' |- t : tSort s ->\n    Σ ;;; Γ |- it_mkProd_or_LetIn Γ' t : tSort (sort_of_products us s).\n  Proof using wfΣ.\n    revert Γ us s t.\n    induction Γ'; simpl; auto; move=> Γ us s t equ Ht.\n    - destruct us => //.\n    - destruct a as [na [b|] ty]; intuition auto.\n      * destruct a0 as [s' Hs].\n        eapply IHΓ'; eauto.\n        eapply (type_mkProd_or_LetIn {| decl_body := Some b |}); auto.\n        simpl. exact Hs.\n      * destruct us => //. destruct equ.\n        simpl.\n        eapply IHΓ'; eauto.\n        apply (type_mkProd_or_LetIn {| decl_body := None |}) => /=; eauto.\n  Qed.\n\n  Lemma isType_it_mkProd_or_LetIn {Γ Γ' us t} :\n    sorts_local_ctx (lift_typing typing) Σ Γ Γ' us ->\n    isType Σ (Γ ,,, Γ') t ->\n    isType Σ Γ (it_mkProd_or_LetIn Γ' t).\n  Proof using cf Σ wfΣ.\n    move=> equs [s ttyp]; exists (sort_of_products us s).\n    apply: type_it_mkProd_or_LetIn_sorts=> //.\n  Qed.\n\n  Lemma app_context_push Γ Δ Δ' d : (Γ ,,, Δ ,,, Δ') ,, d = (Γ ,,, Δ ,,, (Δ' ,, d)).\n  Proof using Type.\n    reflexivity.\n  Qed.\n\n  Hint Extern 4 (_ ;;; _ |- _ <= _) => reflexivity : pcuic.\n  Ltac pcuic := eauto 5 with pcuic.\n\n  Lemma subslet_app_closed {Γ s s' Δ Δ'} :\n    subslet Σ Γ s Δ ->\n    subslet Σ Γ s' Δ' ->\n    closed_ctx Δ ->\n    subslet Σ Γ (s ++ s') (Δ' ,,, Δ).\n  Proof using Type.\n    induction 1 in s', Δ'; simpl; auto; move=> sub' => /andb_and [clctx clt];\n    try constructor; auto.\n    - pose proof (subslet_length X). rewrite Nat.add_0_r in clt.\n      rewrite /= -H in clt.\n      rewrite subst_app_simpl /= (subst_closedn s') //.\n    - pose proof (subslet_length X). rewrite Nat.add_0_r in clt.\n      rewrite /= -H in clt. move/andb_and: clt => [clt clT].\n      replace (subst0 s t) with (subst0 (s ++ s') t).\n      + constructor; auto.\n        rewrite !subst_app_simpl /= !(subst_closedn s') //.\n      + rewrite !subst_app_simpl /= !(subst_closedn s') //.\n  Qed.\n\n  Hint Constructors subslet : core pcuic.\n\n  Lemma subslet_app_inv {Γ Δ Δ' s} :\n    subslet Σ Γ s (Δ ,,, Δ') ->\n    subslet Σ Γ (skipn #|Δ'| s) Δ *\n    subslet Σ Γ (firstn #|Δ'| s) (subst_context (skipn #|Δ'| s) 0 Δ').\n  Proof using Type.\n    intros sub. split.\n    - induction Δ' in Δ, s, sub |- *; simpl; first by rewrite skipn_0.\n      depelim sub; rewrite skipn_S; auto.\n    - induction Δ' in Δ, s, sub |- *; simpl; first by constructor.\n      destruct s; depelim sub.\n      * rewrite subst_context_snoc. constructor; eauto.\n        rewrite skipn_S Nat.add_0_r /=.\n        assert(#|Δ'| = #|firstn #|Δ'| s|).\n        { pose proof (subslet_length sub).\n          rewrite app_context_length in H.\n          rewrite firstn_length_le; lia. }\n        rewrite {3}H.\n        rewrite -subst_app_simpl.\n        now rewrite firstn_skipn.\n      * rewrite subst_context_snoc.\n        rewrite skipn_S Nat.add_0_r /=.\n        rewrite /subst_decl /map_decl /=.\n        specialize (IHΔ' _ _ sub).\n        epose proof (cons_let_def _ _ _ _ _ (subst (skipn #|Δ'| s0) #|Δ'| t0)\n        (subst (skipn #|Δ'| s0) #|Δ'| T) IHΔ').\n        assert(#|Δ'| = #|firstn #|Δ'| s0|).\n        { pose proof (subslet_length sub).\n          rewrite app_context_length in H.\n          rewrite firstn_length_le; lia. }\n        rewrite {3 6}H in X.\n        rewrite - !subst_app_simpl in X.\n        rewrite !firstn_skipn in X.\n        specialize (X t1).\n        rewrite {3}H in X.\n        now rewrite - !subst_app_simpl firstn_skipn in X.\n  Qed.\n\n  Lemma subslet_inds {ind u mdecl idecl} :\n    declared_inductive Σ.1 ind mdecl idecl ->\n    consistent_instance_ext Σ (ind_universes mdecl) u ->\n    subslet Σ [] (inds (inductive_mind ind) u (ind_bodies mdecl))\n      (subst_instance u (arities_context (ind_bodies mdecl))).\n  Proof using wfΣ.\n    intros isdecl univs.\n    unfold inds.\n    pose proof (proj1 isdecl) as declm.\n    apply on_declared_minductive in declm as [oind oc]; auto.\n    clear oc.\n    assert (Alli (fun i x =>\n      Σ ;;; [] |- tInd {| inductive_mind := inductive_mind ind; inductive_ind := i |} u : subst_instance u (ind_type x)) 0 (ind_bodies mdecl)).\n    { apply forall_nth_error_Alli.\n      econstructor; eauto. split; eauto. simpl. eapply isdecl. }\n    clear oind.\n    revert X. clear onNpars.\n    generalize (le_n #|ind_bodies mdecl|).\n    generalize (ind_bodies mdecl) at 1 3 4 5.\n    induction l using rev_ind; simpl; first constructor.\n    rewrite /subst_instance /= /map_context.\n    simpl. rewrite /arities_context rev_map_spec /=.\n    rewrite map_app /= rev_app_distr /=.\n    rewrite {1}/map_decl /= app_length /= Nat.add_1_r.\n    constructor.\n    - rewrite -rev_map_spec. apply IHl; try lia.\n      eapply Alli_app in X; intuition auto.\n    - eapply Alli_app in X as [oind Hx].\n      depelim Hx. clear Hx.\n      rewrite Nat.add_0_r in t.\n      rewrite subst_closedn; auto.\n      + now eapply type_closed in t.\n  Qed.\n\n  Lemma weaken_subslet {s Δ Γ} :\n    wf_local Σ Γ ->\n    subslet Σ [] s Δ -> subslet Σ Γ s Δ.\n  Proof using wfΣ.\n    intros wfΔ.\n    induction 1; constructor; auto.\n    + eapply (weaken_ctx (Γ:=[]) Γ); eauto.\n    + eapply (weaken_ctx (Γ:=[]) Γ); eauto.\n  Qed.\n\n  Set Default Goal Selector \"1\".\n\n  Lemma isType_substitution_it_mkProd_or_LetIn {Γ Δ T s} :\n    subslet Σ Γ s Δ ->\n    isType Σ Γ (it_mkProd_or_LetIn Δ T) ->\n    isType Σ Γ (subst0 s T).\n  Proof using wfΣ.\n    intros sub HT.\n    apply infer_typing_sort_impl with id HT; intros Hs.\n    destruct HT as (s' & t); cbn in Hs |- *; clear t.\n    revert Γ s sub Hs.\n    generalize (le_n #|Δ|).\n    generalize #|Δ| at 2.\n    induction n in Δ, T |- *.\n    - destruct Δ; simpl; intros; try (elimtype False; lia).\n      depelim sub.\n      rewrite subst_empty; auto.\n    - destruct Δ using rev_ind; try clear IHΔ.\n      + intros Hn Γ s sub; now depelim sub; rewrite subst_empty.\n      + rewrite app_length Nat.add_1_r /= => Hn Γ s sub.\n      pose proof (subslet_length sub). rewrite app_length /= Nat.add_1_r in H.\n      have Hl : #|l| = #|firstn #|l| s|.\n      { rewrite firstn_length_le; lia. }\n      destruct x as [na [b|] ty] => /=;\n      rewrite it_mkProd_or_LetIn_app /= /mkProd_or_LetIn /=.\n\n      intros Hs.\n      assert (wfs' := typing_wf_universe wfΣ Hs).\n      eapply inversion_LetIn in Hs as (? & ? & ? & ? & ? & ?); auto.\n      eapply substitution_let in t1; auto.\n      eapply ws_cumul_pb_LetIn_l_inv in w; auto.\n      pose proof (subslet_app_inv sub) as [subl subr].\n      depelim subl. depelim subl. rewrite subst_empty in H0. rewrite H0 in subr.\n      specialize (IHn (subst_context [b] 0 l) (subst [b] #|l| T) ltac:(rewrite subst_context_length; lia)).\n      specialize (IHn _ _ subr).\n      rewrite /subst1 subst_it_mkProd_or_LetIn Nat.add_0_r in t1.\n      rewrite !subst_empty in t3.\n      forward IHn.\n      eapply type_Cumul. eapply t1. econstructor; intuition eauto using typing_wf_local with pcuic.\n      eapply (cumulAlgo_cumulSpec _ (pb:=Cumul)), w. rewrite {2}Hl in IHn.\n      now rewrite -subst_app_simpl -H0 firstn_skipn in IHn.\n\n      intros Hs.\n      assert (wfs' := typing_wf_universe wfΣ Hs).\n      eapply inversion_Prod in Hs as (? & ? & ? & ? & ?); auto.\n      pose proof (subslet_app_inv sub) as [subl subr].\n      depelim subl; depelim subl. rewrite subst_empty in t2. rewrite H0 in subr.\n      epose proof (substitution0 t0 t2).\n      specialize (IHn (subst_context [t1] 0 l) (subst [t1] #|l| T)).\n      forward IHn. rewrite subst_context_length; lia.\n      specialize (IHn _ _ subr).\n      rewrite /subst1 subst_it_mkProd_or_LetIn Nat.add_0_r in X.\n      forward IHn.\n      eapply type_Cumul. simpl in X. eapply X.\n      econstructor; eauto with pcuic.\n      eapply ws_cumul_pb_Sort_inv in w. eapply cumul_Sort.\n      transitivity (Universe.sort_of_product x x0).\n      eapply leq_universe_product. auto.\n      rewrite {2}Hl in IHn.\n      now rewrite -subst_app_simpl -H0 firstn_skipn in IHn.\n  Qed.\n\n  Lemma on_minductive_wf_params {ind mdecl} {u} :\n    declared_minductive Σ.1 ind mdecl ->\n    consistent_instance_ext Σ (ind_universes mdecl) u ->\n    wf_local Σ (subst_instance u (ind_params mdecl)).\n  Proof using wfΣ.\n    intros. eapply (wf_local_instantiate (decl := InductiveDecl mdecl)); eauto.\n    eapply on_declared_minductive in H; auto.\n    now apply onParams in H.\n  Qed.\n\n  Lemma it_mkProd_or_LetIn_wf_local {Γ Δ T U} :\n    Σ ;;; Γ |- it_mkProd_or_LetIn Δ T : U -> wf_local Σ (Γ ,,, Δ).\n  Proof using wfΣ.\n    move: Γ T U.\n    induction Δ using rev_ind => Γ T U.\n    + simpl. intros. now eapply typing_wf_local in X.\n    + rewrite it_mkProd_or_LetIn_app.\n      destruct x as [na [b|] ty]; cbn; move=> H.\n      * apply inversion_LetIn in H as (s1 & A & H0 & H1 & H2 & H3); auto.\n        eapply All_local_env_app; split; pcuic.\n        eapply All_local_env_app. split. repeat constructor. now exists s1.\n        auto. apply IHΔ in H2.\n        eapply All_local_env_app_inv in H2. intuition auto.\n        eapply All_local_env_impl; eauto. simpl. intros.\n        now rewrite app_context_assoc.\n      * apply inversion_Prod in H as (s1 & A & H0 & H1 & H2); auto.\n        eapply All_local_env_app; split; pcuic.\n        eapply All_local_env_app. split. repeat constructor. now exists s1.\n        apply IHΔ in H1.\n        eapply All_local_env_app_inv in H1. intuition auto.\n        eapply All_local_env_impl; eauto. simpl. intros.\n        now rewrite app_context_assoc.\n  Qed.\n\n  Lemma isType_it_mkProd_or_LetIn_wf_local {Γ Δ T} :\n    isType Σ Γ (it_mkProd_or_LetIn Δ T) -> wf_local Σ (Γ ,,, Δ).\n  Proof using wfΣ.\n    move=> [s Hs].\n    now eapply it_mkProd_or_LetIn_wf_local in Hs.\n  Qed.\n\n  Lemma isType_weaken {Γ T} :\n    wf_local Σ Γ ->\n    isType Σ [] T ->\n    isType Σ Γ T.\n  Proof using wfΣ.\n    intros wfΓ HT.\n    apply infer_typing_sort_impl with id HT; intros hs.\n    unshelve epose proof (subject_closed hs); eauto.\n    eapply (weakening _ _ Γ) in hs => //.\n    rewrite lift_closed in hs => //.\n    now rewrite app_context_nil_l in hs.\n    now rewrite app_context_nil_l.\n  Qed.\n\n  Lemma subst_telescope_subst_instance u s k Γ :\n    subst_telescope (map (subst_instance u) s) k\n      (subst_instance u Γ) =\n    subst_instance u (subst_telescope s k Γ).\n  Proof using Type.\n    rewrite /subst_telescope /subst_instance /= /subst_instance_context /map_context.\n    rewrite map_mapi mapi_map. apply mapi_ext.\n    intros. rewrite !compose_map_decl; apply map_decl_ext => ?.\n    now rewrite -subst_instance_subst.\n  Qed.\nEnd WfEnv.\n", "meta": {"author": "SwampertX", "repo": "undergraduate-thesis", "sha": "b0c78984b94e56f1372a7195bd0babaab10fca8d", "save_path": "github-repos/coq/SwampertX-undergraduate-thesis", "path": "github-repos/coq/SwampertX-undergraduate-thesis/undergraduate-thesis-b0c78984b94e56f1372a7195bd0babaab10fca8d/final-report-new/code/v2/pcuic/theories/PCUICArities.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2339087340462815}}
{"text": "Require Import oeuf.Common.\nRequire oeuf.StepLib.\nRequire Import Psatz.\n\nRequire Import oeuf.Utopia.\nRequire Import oeuf.Monads.\n\nRequire Export oeuf.HigherValue.\nRequire Import oeuf.AllValues.\nRequire Import oeuf.OpaqueOps.\n\nInductive insn :=\n| Block (code : list insn)\n| Arg\n| Self\n| Deref (off : nat)\n| Call\n| MkConstr (tag : nat) (nargs : nat)\n| Switch (cases : list (list insn))\n| MkClose (f : function_name) (nfree : nat)\n| OpaqueOp (op : opaque_oper_name) (nargs : nat)\n.\n\nDefinition env := list (list insn).\n\n\n(* Continuation-based step relation *)\n\nRecord frame := Frame {\n    arg : value;\n    self : value;\n    stack : list value\n}.\n\nDefinition push f v :=\n    Frame (arg f) (self f) (v :: stack f).\n\n\nInductive state :=\n| Run (i : list insn) (f : frame) (k : value -> state)\n| Stop (v : value).\n\nInductive sstep (E : env) : state -> state -> Prop :=\n| SBlock : forall code is f k,\n        sstep E (Run (Block code :: is) f k)\n                (Run code (Frame (arg f) (self f) []) (fun v => Run is (push f v) k))\n\n| SArg : forall f k,\n        stack f = [] ->\n        sstep E (Run [Arg] f k) (k (arg f))\n| SSelf : forall f k,\n        stack f = [] ->\n        sstep E (Run [Self] f k) (k (self f))\n\n| SDerefinateConstr : forall off f k  tag args v,\n        stack f = [Constr tag args] ->\n        nth_error args off = Some v ->\n        sstep E (Run [Deref off] f k) (k v)\n| SDerefinateClose : forall off f k  fname free v,\n        stack f = [Close fname free] ->\n        nth_error free off = Some v ->\n        sstep E (Run [Deref off] f k) (k v)\n\n| SConstrDone : forall tag nargs f k,\n        length (stack f) = nargs ->\n        sstep E (Run [MkConstr tag nargs] f k)\n                (k (Constr tag (rev (stack f))))\n| SCloseDone : forall fname nfree f k,\n        length (stack f) = nfree ->\n        sstep E (Run [MkClose fname nfree] f k)\n                (k (Close fname (rev (stack f))))\n| SOpaqueOpDone : forall op nargs f k v,\n        length (stack f) = nargs ->\n        opaque_oper_denote_higher op (rev (stack f)) = Some v ->\n        sstep E (Run [OpaqueOp op nargs] f k)\n                (k v)\n\n| SMakeCall : forall f k  fname free body argv,\n        stack f = [argv; Close fname free] ->\n        nth_error E fname = Some body ->\n        sstep E (Run [Call] f k)\n                (Run body (Frame argv (Close fname free) []) k)\n\n(* NB: `Switch` still has an implicit target of `Arg` *)\n| SSwitchinate : forall cases f k  tag args case,\n        stack f = [] ->\n        arg f = Constr tag args ->\n        nth_error cases tag = Some case ->\n        sstep E (Run [Switch cases] f k)\n                (Run case (Frame (arg f) (self f) []) k)\n.\n\n\n\nDefinition sstar BE := StepLib.sstar (sstep BE).\nDefinition SStarNil := @StepLib.SStarNil state.\nDefinition SStarCons := @StepLib.SStarCons state.\n\nDefinition splus BE := StepLib.splus (sstep BE).\nDefinition SPlusOne := @StepLib.SPlusOne state.\nDefinition SPlusCons := @StepLib.SPlusCons state.\n\n\n\nRequire Import oeuf.Metadata.\nRequire oeuf.Semantics.\n\nDefinition prog_type : Type := env * list metadata.\nDefinition val_level := VlHigher.\nDefinition valtype := value_type val_level.\n\nInductive is_callstate (prog : prog_type) : valtype -> valtype -> state -> Prop :=\n| IsCallstate : forall fname free av body,\n        nth_error (fst prog) fname = Some body ->\n        let fv := Close fname free in\n        HigherValue.public_value (snd prog) fv ->\n        HigherValue.public_value (snd prog) av ->\n        is_callstate prog fv av\n            (Run body\n                 (Frame av fv [])\n                 Stop).\n\nInductive final_state (prog : prog_type) : state -> valtype -> Prop :=\n| FinalState : forall v,\n        HigherValue.public_value (snd prog) v ->\n        final_state prog (Stop v) v.\n\nDefinition initial_env (prog : prog_type) : env := fst prog.\n\nDefinition semantics (prog : prog_type) : Semantics.semantics :=\n  @Semantics.Semantics_gen state env val_level\n                 (is_callstate prog)\n                 (sstep)\n                 (final_state prog)\n                 (initial_env prog).\n\n\n\n\n(*\n * Mutual recursion/induction schemes for expr\n *)\n\nDefinition insn_rect_mut\n        (P : insn -> Type)\n        (Pl : list insn -> Type)\n        (Pll : list (list insn) -> Type)\n    (HBlock :   forall code, Pl code -> P (Block code))\n    (HArg :     P Arg)\n    (HSelf :    P Self)\n    (HDeref :   forall off, P (Deref off))\n    (HCall :    P Call)\n    (HConstr :  forall tag nargs, P (MkConstr tag nargs))\n    (HSwitch :  forall cases, Pll cases -> P (Switch cases))\n    (HClose :   forall fname nfree, P (MkClose fname nfree))\n    (HOpaqueOp : forall op nargs, P (OpaqueOp op nargs))\n    (Hnil :     Pl [])\n    (Hcons :    forall i is, P i -> Pl is -> Pl (i :: is))\n    (Hnil2 :    Pll [])\n    (Hcons2 :   forall is iss, Pl is -> Pll iss -> Pll (is :: iss))\n    (i : insn) : P i :=\n    let fix go i :=\n        let fix go_list is :=\n            match is as is_ return Pl is_ with\n            | [] => Hnil\n            | i :: is => Hcons i is (go i) (go_list is)\n            end in\n        let fix go_list_list iss :=\n            match iss as iss_ return Pll iss_ with\n            | [] => Hnil2\n            | is :: iss => Hcons2 is iss (go_list is) (go_list_list iss)\n            end in\n        match i as i_ return P i_ with\n        | Block code => HBlock code (go_list code)\n        | Arg => HArg\n        | Self => HSelf\n        | Deref off => HDeref off\n        | Call => HCall\n        | MkConstr tag nargs => HConstr tag nargs\n        | Switch cases => HSwitch cases (go_list_list cases)\n        | MkClose fname nfree => HClose fname nfree\n        | OpaqueOp op nargs => HOpaqueOp op nargs\n        end in go i.\n\n(* Useful wrapper for `expr_rect_mut with (Pl := Forall P)` *)\nDefinition insn_ind' (P : insn -> Prop)\n    (HBlock :   forall code, Forall P code -> P (Block code))\n    (HArg :     P Arg)\n    (HSelf :    P Self)\n    (HDeref :   forall off, P (Deref off))\n    (HCall :    P Call)\n    (HConstr :  forall tag nargs, P (MkConstr tag nargs))\n    (HSwitch :  forall cases, Forall (Forall P) cases -> P (Switch cases))\n    (HClose :   forall fname nfree, P (MkClose fname nfree))\n    (HOpaqueOp : forall op nargs, P (OpaqueOp op nargs))\n    (i : insn) : P i :=\n    ltac:(refine (@insn_rect_mut P (Forall P) (Forall (Forall P))\n        HBlock HArg HSelf HDeref HCall HConstr HSwitch HClose HOpaqueOp _ _ _ _ i); eauto).\n\nDefinition insn_list_rect_mut\n        (P : insn -> Type)\n        (Pl : list insn -> Type)\n        (Pll : list (list insn) -> Type)\n    (HBlock :   forall code, Pl code -> P (Block code))\n    (HArg :     P Arg)\n    (HSelf :    P Self)\n    (HDeref :   forall off, P (Deref off))\n    (HCall :    P Call)\n    (HConstr :  forall tag nargs, P (MkConstr tag nargs))\n    (HSwitch :  forall cases, Pll cases -> P (Switch cases))\n    (HClose :   forall fname nfree, P (MkClose fname nfree))\n    (HOpaqueOp : forall op nargs, P (OpaqueOp op nargs))\n    (Hnil :     Pl [])\n    (Hcons :    forall i is, P i -> Pl is -> Pl (i :: is))\n    (Hnil2 :    Pll [])\n    (Hcons2 :   forall is iss, Pl is -> Pll iss -> Pll (is :: iss))\n    (is : list insn) : Pl is :=\n    let go := insn_rect_mut P Pl Pll\n            HBlock HArg HSelf HDeref HCall HConstr HSwitch HClose HOpaqueOp\n            Hnil Hcons Hnil2 Hcons2 in\n    let fix go_list is :=\n        match is as is_ return Pl is_ with\n        | [] => Hnil\n        | i :: is => Hcons i is (go i) (go_list is)\n        end in go_list is.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/StackMach.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23390873404628146}}
{"text": "From Mtac2 Require Import Mtac2.\n\nClass Test := { val : nat }.\n\n#[global] Instance Zero : Test := {| val := 0 |}.\n\nImport M.notations.\n\nDefinition CouldntFindTC : Exception. exact exception. Qed.\n\nDefinition fail_solve_tc A :=\n  M.solve_typeclass A >>= fun x=>\n  match x with\n  | mSome v => M.ret v\n  | mNone => M.raise CouldntFindTC\n  end.\n\nDefinition zero := ltac:(mrun (fail_solve_tc Test >>= fun x=>M.ret (@val x))).\n\nGoal zero = 0.\nMProof.\n  T.reflexivity.\nQed.\n\nClass TestFail := { valF : nat }.\n\nDefinition fail_but_caught := ltac: (mrun (\n  mtry fail_solve_tc TestFail;; M.ret 1\n  with CouldntFindTC => M.ret 0 end)).\n\nGoal fail_but_caught = 0.\nMProof.\n  T.reflexivity.\nQed.\n", "meta": {"author": "Mtac2", "repo": "Mtac2", "sha": "d16c2e682d5ab18ed77b13b4fd60a42a65c4f958", "save_path": "github-repos/coq/Mtac2-Mtac2", "path": "github-repos/coq/Mtac2-Mtac2/Mtac2-d16c2e682d5ab18ed77b13b4fd60a42a65c4f958/tests/typeclass.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23390872761876408}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness proof for code linearization *)\n\nRequire Import FSets.\nRequire Import Coqlib Maps Ordered Errors Lattice Kildall Integers.\nRequire Import AST Linking.\nRequire Import Values Memory Events Globalenvs Smallstep.\nRequire Import Op Locations LTL Linear.\nRequire Import Linearize.\n\nModule NodesetFacts := FSetFacts.Facts(Nodeset).\n\nDefinition match_prog (p: LTL.program) (tp: Linear.program) :=\n  match_program (fun ctx f tf => transf_fundef f = OK tf) eq p tp.\n\nLemma transf_program_match:\n  forall p tp, transf_program p = OK tp -> match_prog p tp.\nProof.\n  intros. eapply match_transform_partial_program; eauto.\nQed.\n\nSection LINEARIZATION.\n\nVariable fn_stack_requirements: ident -> Z.\nVariable prog: LTL.program.\nVariable tprog: Linear.program.\n\nHypothesis TRANSF: match_prog prog tprog.\n\nLet ge := Genv.globalenv prog.\nLet tge := Genv.globalenv tprog.\n\nLemma functions_translated:\n  forall v f,\n  Genv.find_funct ge v = Some f ->\n  exists tf,\n  Genv.find_funct tge v = Some tf /\\ transf_fundef f = OK tf.\nProof (Genv.find_funct_transf_partial TRANSF).\n\nLemma function_ptr_translated:\n  forall v f,\n  Genv.find_funct_ptr ge v = Some f ->\n  exists tf,\n  Genv.find_funct_ptr tge v = Some tf /\\ transf_fundef f = OK tf.\nProof (Genv.find_funct_ptr_transf_partial TRANSF).\n\nLemma symbols_preserved:\n  forall id,\n  Genv.find_symbol tge id = Genv.find_symbol ge id.\nProof (Genv.find_symbol_transf_partial TRANSF).\n\nLemma senv_preserved:\n  Senv.equiv ge tge.\nProof (Genv.senv_transf_partial TRANSF).\n\nLemma sig_preserved:\n  forall f tf,\n  transf_fundef f = OK tf ->\n  Linear.funsig tf = LTL.funsig f.\nProof.\n  unfold transf_fundef, transf_partial_fundef; intros.\n  destruct f. monadInv H. monadInv EQ. reflexivity.\n  inv H. reflexivity.\nQed.\n\nLemma stacksize_preserved:\n  forall f tf,\n  transf_function f = OK tf ->\n  Linear.fn_stacksize tf = LTL.fn_stacksize f.\nProof.\n  intros. monadInv H. auto.\nQed.\n\nLemma find_function_translated:\n  forall ros ls f,\n  LTL.find_function ge ros ls = Some f ->\n  exists tf,\n  find_function tge ros ls = Some tf /\\ transf_fundef f = OK tf.\nProof.\n  unfold LTL.find_function; intros; destruct ros; simpl.\n  apply functions_translated; auto.\n  rewrite symbols_preserved. destruct (Genv.find_symbol ge i).\n  apply function_ptr_translated; auto.\n  congruence.\nQed.\n\n(** * Correctness of reachability analysis *)\n\n(** The entry point of the function is reachable. *)\n\nLemma reachable_entrypoint:\n  forall f, (reachable f)!!(f.(fn_entrypoint)) = true.\nProof.\n  intros. unfold reachable.\n  caseEq (reachable_aux f).\n  unfold reachable_aux; intros reach A.\n  assert (LBoolean.ge reach!!(f.(fn_entrypoint)) true).\n  eapply DS.fixpoint_entry. eexact A. auto.\n  unfold LBoolean.ge in H. tauto.\n  intros. apply PMap.gi.\nQed.\n\n(** The successors of a reachable instruction are reachable. *)\n\nLemma reachable_successors:\n  forall f pc pc' b,\n  f.(LTL.fn_code)!pc = Some b -> In pc' (successors_block b) ->\n  (reachable f)!!pc = true ->\n  (reachable f)!!pc' = true.\nProof.\n  intro f. unfold reachable.\n  caseEq (reachable_aux f).\n  unfold reachable_aux. intro reach; intros.\n  assert (LBoolean.ge reach!!pc' reach!!pc).\n  change (reach!!pc) with ((fun pc r => r) pc (reach!!pc)).\n  eapply DS.fixpoint_solution; eauto. intros; apply DS.L.eq_refl.\n  elim H3; intro. congruence. auto.\n  intros. apply PMap.gi.\nQed.\n\n(** * Properties of node enumeration *)\n\n(** An enumeration of CFG nodes is correct if the following conditions hold:\n- All nodes for reachable basic blocks must be in the list.\n- The list is without repetition (so that no code duplication occurs).\n\nWe prove that the result of the [enumerate] function satisfies both\nconditions. *)\n\nLemma nodeset_of_list_correct:\n  forall l s s',\n  nodeset_of_list l s = OK s' ->\n  list_norepet l\n  /\\ (forall pc, Nodeset.In pc s' <-> Nodeset.In pc s \\/ In pc l)\n  /\\ (forall pc, In pc l -> ~Nodeset.In pc s).\nProof.\n  induction l; simpl; intros.\n  inv H. split. constructor. split. intro; tauto. intros; tauto.\n  generalize H; clear H; caseEq (Nodeset.mem a s); intros.\n  inv H0.\n  exploit IHl; eauto. intros [A [B C]].\n  split. constructor; auto. red; intro. elim (C a H1). apply Nodeset.add_1. hnf. auto.\n  split. intros. rewrite B. rewrite NodesetFacts.add_iff.\n  unfold Nodeset.E.eq. unfold OrderedPositive.eq. tauto.\n  intros. destruct H1. subst pc. rewrite NodesetFacts.not_mem_iff. auto.\n  generalize (C pc H1). rewrite NodesetFacts.add_iff. tauto.\nQed.\n\nLemma check_reachable_correct:\n  forall f reach s pc i,\n  check_reachable f reach s = true ->\n  f.(LTL.fn_code)!pc = Some i ->\n  reach!!pc = true ->\n  Nodeset.In pc s.\nProof.\n  intros f reach s.\n  assert (forall l ok,\n    List.fold_left (fun a p => check_reachable_aux reach s a (fst p) (snd p)) l ok = true ->\n    ok = true /\\\n    (forall pc i,\n     In (pc, i) l ->\n     reach!!pc = true ->\n     Nodeset.In pc s)).\n  induction l; simpl; intros.\n  split. auto. intros. destruct H0.\n  destruct a as [pc1 i1]. simpl in H.\n  exploit IHl; eauto. intros [A B].\n  unfold check_reachable_aux in A.\n  split. destruct (reach!!pc1). elim (andb_prop _ _ A). auto. auto.\n  intros. destruct H0. inv H0. rewrite H1 in A. destruct (andb_prop _ _ A).\n  apply Nodeset.mem_2; auto.\n  eauto.\n\n  intros pc i. unfold check_reachable. rewrite PTree.fold_spec. intros.\n  exploit H; eauto. intros [A B]. eapply B; eauto.\n  apply PTree.elements_correct. eauto.\nQed.\n\nLemma enumerate_complete:\n  forall f enum pc i,\n  enumerate f = OK enum ->\n  f.(LTL.fn_code)!pc = Some i ->\n  (reachable f)!!pc = true ->\n  In pc enum.\nProof.\n  intros until i. unfold enumerate.\n  set (reach := reachable f).\n  intros. monadInv H.\n  generalize EQ0; clear EQ0. caseEq (check_reachable f reach x); intros; inv EQ0.\n  exploit check_reachable_correct; eauto. intro.\n  exploit nodeset_of_list_correct; eauto. intros [A [B C]].\n  rewrite B in H2. destruct H2. elim (Nodeset.empty_1 H2). auto.\nQed.\n\nLemma enumerate_norepet:\n  forall f enum,\n  enumerate f = OK enum ->\n  list_norepet enum.\nProof.\n  intros until enum. unfold enumerate.\n  set (reach := reachable f).\n  intros. monadInv H.\n  generalize EQ0; clear EQ0. caseEq (check_reachable f reach x); intros; inv EQ0.\n  exploit nodeset_of_list_correct; eauto. intros [A [B C]]. auto.\nQed.\n\n(** * Properties related to labels *)\n\n(** If labels are globally unique and the Linear code [c] contains\n  a subsequence [Llabel lbl :: c1], then [find_label lbl c] returns [c1].\n*)\n\nFixpoint unique_labels (c: code) : Prop :=\n  match c with\n  | nil => True\n  | Llabel lbl :: c => ~(In (Llabel lbl) c) /\\ unique_labels c\n  | i :: c => unique_labels c\n  end.\n\nLemma find_label_unique:\n  forall lbl c1 c2 c3,\n  is_tail (Llabel lbl :: c1) c2 ->\n  unique_labels c2 ->\n  find_label lbl c2 = Some c3 ->\n  c1 = c3.\nProof.\n  induction c2.\n  simpl; intros; discriminate.\n  intros c3 TAIL UNIQ. simpl.\n  generalize (is_label_correct lbl a). case (is_label lbl a); intro ISLBL.\n  subst a. intro. inversion TAIL. congruence.\n  elim UNIQ; intros. elim H4. apply is_tail_in with c1; auto.\n  inversion TAIL. congruence. apply IHc2. auto.\n  destruct a; simpl in UNIQ; tauto.\nQed.\n\n(** Correctness of the [starts_with] test. *)\n\nLemma starts_with_correct:\n  forall lbl c1 c2 c3 s f sp ls m,\n  is_tail c1 c2 ->\n  unique_labels c2 ->\n  starts_with lbl c1 = true ->\n  find_label lbl c2 = Some c3 ->\n  plus (step fn_stack_requirements) tge (State s f sp c1 ls m)\n             E0 (State s f sp c3 ls m).\nProof.\n  induction c1.\n  simpl; intros; discriminate.\n  simpl starts_with. destruct a; try (intros; discriminate).\n  intros.\n  apply plus_left with E0 (State s f sp c1 ls m) E0.\n  simpl. constructor.\n  destruct (peq lbl l).\n  subst l. replace c3 with c1. constructor.\n  apply find_label_unique with lbl c2; auto.\n  apply plus_star.\n  apply IHc1 with c2; auto. eapply is_tail_cons_left; eauto.\n  traceEq.\nQed.\n\n(** Connection between [find_label] and linearization. *)\n\nLemma find_label_add_branch:\n  forall lbl k s,\n  find_label lbl (add_branch s k) = find_label lbl k.\nProof.\n  intros. unfold add_branch. destruct (starts_with s k); auto.\nQed.\n\nLemma find_label_lin_block:\n  forall lbl k b,\n  find_label lbl (linearize_block b k) = find_label lbl k.\nProof.\n  intros lbl k. generalize (find_label_add_branch lbl k); intro.\n  induction b; simpl; auto. destruct a; simpl; auto.\n  case (starts_with s1 k); simpl; auto.\nQed.\n\nRemark linearize_body_cons:\n  forall f pc enum,\n  linearize_body f (pc :: enum) =\n  match f.(LTL.fn_code)!pc with\n  | None => linearize_body f enum\n  | Some b => Llabel pc :: linearize_block b (linearize_body f enum)\n  end.\nProof.\n  intros. unfold linearize_body. rewrite list_fold_right_eq.\n  unfold linearize_node. destruct (LTL.fn_code f)!pc; auto.\nQed.\n\nLemma find_label_lin_rec:\n  forall f enum pc b,\n  In pc enum ->\n  f.(LTL.fn_code)!pc = Some b ->\n  exists k, find_label pc (linearize_body f enum) = Some (linearize_block b k).\nProof.\n  induction enum; intros.\n  elim H.\n  rewrite linearize_body_cons.\n  destruct (peq a pc).\n  subst a. exists (linearize_body f enum).\n  rewrite H0. simpl. rewrite peq_true. auto.\n  assert (In pc enum). simpl in H. tauto.\n  destruct (IHenum pc b H1 H0) as [k FIND].\n  exists k. destruct (LTL.fn_code f)!a.\n  simpl. rewrite peq_false. rewrite find_label_lin_block. auto. auto.\n  auto.\nQed.\n\nLemma find_label_lin:\n  forall f tf pc b,\n  transf_function f = OK tf ->\n  f.(LTL.fn_code)!pc = Some b ->\n  (reachable f)!!pc = true ->\n  exists k,\n  find_label pc (fn_code tf) = Some (linearize_block b k).\nProof.\n  intros. monadInv H. simpl.\n  rewrite find_label_add_branch. apply find_label_lin_rec.\n  eapply enumerate_complete; eauto. auto.\nQed.\n\nLemma find_label_lin_inv:\n  forall f tf pc b k,\n  transf_function f = OK tf ->\n  f.(LTL.fn_code)!pc = Some b ->\n  (reachable f)!!pc = true ->\n  find_label pc (fn_code tf) = Some k ->\n  exists k', k = linearize_block b k'.\nProof.\n  intros. exploit find_label_lin; eauto. intros [k' FIND].\n  exists k'. congruence.\nQed.\n\n(** Unique label property for linearized code. *)\n\nLemma label_in_add_branch:\n  forall lbl s k,\n  In (Llabel lbl) (add_branch s k) -> In (Llabel lbl) k.\nProof.\n  intros until k; unfold add_branch.\n  destruct (starts_with s k); simpl; intuition congruence.\nQed.\n\nLemma label_in_lin_block:\n  forall lbl k b,\n  In (Llabel lbl) (linearize_block b k) -> In (Llabel lbl) k.\nProof.\n  induction b; simpl; intros. auto.\n  destruct a; simpl in H; try (intuition congruence).\n  apply label_in_add_branch with s; intuition congruence.\n  destruct (starts_with s1 k); simpl in H.\n  apply label_in_add_branch with s1; intuition congruence.\n  apply label_in_add_branch with s2; intuition congruence.\nQed.\n\nLemma label_in_lin_rec:\n  forall f lbl enum,\n  In (Llabel lbl) (linearize_body f enum) -> In lbl enum.\nProof.\n  induction enum.\n  simpl; auto.\n  rewrite linearize_body_cons. destruct (LTL.fn_code f)!a.\n  simpl. intros [A|B]. left; congruence.\n  right. apply IHenum. eapply label_in_lin_block; eauto.\n  intro; right; auto.\nQed.\n\nLemma unique_labels_add_branch:\n  forall lbl k,\n  unique_labels k -> unique_labels (add_branch lbl k).\nProof.\n  intros; unfold add_branch.\n  destruct (starts_with lbl k); simpl; intuition.\nQed.\n\nLemma unique_labels_lin_block:\n  forall k b,\n  unique_labels k -> unique_labels (linearize_block b k).\nProof.\n  induction b; intros; simpl. auto.\n  destruct a; auto; try (apply unique_labels_add_branch; auto).\n  case (starts_with s1 k); simpl; apply unique_labels_add_branch; auto.\nQed.\n\nLemma unique_labels_lin_rec:\n  forall f enum,\n  list_norepet enum ->\n  unique_labels (linearize_body f enum).\nProof.\n  induction enum.\n  simpl; auto.\n  rewrite linearize_body_cons.\n  intro. destruct (LTL.fn_code f)!a.\n  simpl. split. red. intro. inversion H. elim H3.\n  apply label_in_lin_rec with f.\n  apply label_in_lin_block with b. auto.\n  apply unique_labels_lin_block. apply IHenum. inversion H; auto.\n  apply IHenum. inversion H; auto.\nQed.\n\nLemma unique_labels_transf_function:\n  forall f tf,\n  transf_function f = OK tf ->\n  unique_labels (fn_code tf).\nProof.\n  intros. monadInv H. simpl.\n  apply unique_labels_add_branch.\n  apply unique_labels_lin_rec. eapply enumerate_norepet; eauto.\nQed.\n\n(** Correctness of [add_branch]. *)\n\nLemma is_tail_find_label:\n  forall lbl c2 c1,\n  find_label lbl c1 = Some c2 -> is_tail c2 c1.\nProof.\n  induction c1; simpl.\n  intros; discriminate.\n  case (is_label lbl a). intro. injection H; intro. subst c2.\n  constructor. constructor.\n  intro. constructor. auto.\nQed.\n\nLemma is_tail_add_branch:\n  forall lbl c1 c2, is_tail (add_branch lbl c1) c2 -> is_tail c1 c2.\nProof.\n  intros until c2. unfold add_branch. destruct (starts_with lbl c1).\n  auto. eauto with coqlib.\nQed.\n\nLemma is_tail_lin_block:\n  forall b c1 c2,\n  is_tail (linearize_block b c1) c2 -> is_tail c1 c2.\nProof.\n  induction b; simpl; intros.\n  auto.\n  destruct a; eauto with coqlib.\n  eapply is_tail_add_branch; eauto.\n  destruct (starts_with s1 c1); eapply is_tail_add_branch; eauto with coqlib.\nQed.\n\nLemma add_branch_correct:\n  forall lbl c k s f tf sp ls m,\n  transf_function f = OK tf ->\n  is_tail k tf.(fn_code) ->\n  find_label lbl tf.(fn_code) = Some c ->\n  plus (step fn_stack_requirements) tge (State s tf sp (add_branch lbl k) ls m)\n             E0 (State s tf sp c ls m).\nProof.\n  intros. unfold add_branch.\n  caseEq (starts_with lbl k); intro SW.\n  eapply starts_with_correct; eauto.\n  eapply unique_labels_transf_function; eauto.\n  apply plus_one. apply exec_Lgoto. auto.\nQed.\n\n(** * Correctness of linearization *)\n\n(** The proof of semantic preservation is a simulation argument of the \"star\" kind:\n<<\n           st1 --------------- st2\n            |                   |\n           t|                  t| + or ( 0 \\/ |st1'| < |st1| )\n            |                   |\n            v                   v\n           st1'--------------- st2'\n>>\n  The invariant (horizontal lines above) is the [match_states]\n  predicate defined below.  It captures the fact that the flow\n  of data is the same in the source and linearized codes.\n  Moreover, whenever the source state is at node [pc] in its\n  control-flow graph, the transformed state is at a code\n  sequence [c] that starts with the label [pc]. *)\n\nInductive match_stackframes: LTL.stackframe -> Linear.stackframe -> Prop :=\n  | match_stackframe_intro:\n      forall f sp bb ls tf c,\n      transf_function f = OK tf ->\n      (forall pc, In pc (successors_block bb) -> (reachable f)!!pc = true) ->\n      is_tail c tf.(fn_code) ->\n      match_stackframes\n        (LTL.Stackframe f sp ls bb)\n        (Linear.Stackframe tf sp ls (linearize_block bb c)).\n\nInductive match_states: LTL.state -> Linear.state -> Prop :=\n  | match_states_add_branch:\n      forall s f sp pc ls m tf ts c\n        (STACKS: list_forall2 match_stackframes s ts)\n        (TRF: transf_function f = OK tf)\n        (REACH: (reachable f)!!pc = true)\n        (TAIL: is_tail c tf.(fn_code)),\n      match_states (LTL.State s f sp pc ls m)\n                   (Linear.State ts tf sp (add_branch pc c) ls m)\n  | match_states_cond_taken:\n      forall s f sp pc ls m tf ts cond args c\n        (STACKS: list_forall2 match_stackframes s ts)\n        (TRF: transf_function f = OK tf)\n        (REACH: (reachable f)!!pc = true)\n        (JUMP: eval_condition cond (reglist ls args) m = Some true),\n      match_states (LTL.State s f sp pc (undef_regs (destroyed_by_cond cond) ls) m)\n                   (Linear.State ts tf sp (Lcond cond args pc :: c) ls m)\n  | match_states_jumptable:\n      forall s f sp pc ls m tf ts arg tbl c n\n        (STACKS: list_forall2 match_stackframes s ts)\n        (TRF: transf_function f = OK tf)\n        (REACH: (reachable f)!!pc = true)\n        (ARG: ls (R arg) = Vint n)\n        (JUMP: list_nth_z tbl (Int.unsigned n) = Some pc),\n      match_states (LTL.State s f sp pc (undef_regs destroyed_by_jumptable ls) m)\n                   (Linear.State ts tf sp (Ljumptable arg tbl :: c) ls m)\n  | match_states_block:\n      forall s f sp bb ls m tf ts c\n        (STACKS: list_forall2 match_stackframes s ts)\n        (TRF: transf_function f = OK tf)\n        (REACH: forall pc, In pc (successors_block bb) -> (reachable f)!!pc = true)\n        (TAIL: is_tail c tf.(fn_code)),\n      match_states (LTL.Block s f sp bb ls m)\n                   (Linear.State ts tf sp (linearize_block bb c) ls m)\n  | match_states_call:\n      forall s f ls m tf ts id,\n      list_forall2 match_stackframes s ts ->\n      transf_fundef f = OK tf ->\n      match_states (LTL.Callstate s f ls m id)\n                   (Linear.Callstate ts tf ls m id)\n  | match_states_return:\n      forall s ls m ts,\n      list_forall2 match_stackframes s ts ->\n      match_states (LTL.Returnstate s ls m)\n                   (Linear.Returnstate ts ls m).\n\nDefinition measure (S: LTL.state) : nat :=\n  match S with\n  | LTL.State s f sp pc ls m => 0%nat\n  | LTL.Block s f sp bb ls m => 1%nat\n  | _ => 0%nat\n  end.\n\nRemark match_parent_locset:\n  forall s ts, list_forall2 match_stackframes s ts -> parent_locset ts = LTL.parent_locset s.\nProof.\n  induction 1; simpl. auto. inv H; auto.\nQed.\n\nTheorem transf_step_correct:\n  forall s1 t s2, LTL.step fn_stack_requirements ge s1 t s2 ->\n  forall s1' (MS: match_states s1 s1'),\n  (exists s2', plus (Linear.step fn_stack_requirements) tge s1' t s2' /\\ match_states s2 s2')\n  \\/ (measure s2 < measure s1 /\\ t = E0 /\\ match_states s2 s1')%nat.\nProof.\n  induction 1; intros; try (inv MS).\n\n  (* start of block, at an [add_branch] *)\n  exploit find_label_lin; eauto. intros [k F].\n  left; econstructor; split.\n  eapply add_branch_correct; eauto.\n  econstructor; eauto.\n  intros; eapply reachable_successors; eauto.\n  eapply is_tail_lin_block; eauto. eapply is_tail_find_label; eauto.\n\n  (* start of block, target of an [Lcond] *)\n  exploit find_label_lin; eauto. intros [k F].\n  left; econstructor; split.\n  apply plus_one. eapply exec_Lcond_true; eauto.\n  econstructor; eauto.\n  intros; eapply reachable_successors; eauto.\n  eapply is_tail_lin_block; eauto. eapply is_tail_find_label; eauto.\n\n  (* start of block, target of an [Ljumptable] *)\n  exploit find_label_lin; eauto. intros [k F].\n  left; econstructor; split.\n  apply plus_one. eapply exec_Ljumptable; eauto.\n  econstructor; eauto.\n  intros; eapply reachable_successors; eauto.\n  eapply is_tail_lin_block; eauto. eapply is_tail_find_label; eauto.\n\n  (* Lop *)\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor; eauto.\n  instantiate (1 := v); rewrite <- H; apply eval_operation_preserved.\n  exact symbols_preserved.\n  econstructor; eauto.\n\n  (* Lload *)\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor.\n  instantiate (1 := a). rewrite <- H; apply eval_addressing_preserved.\n  exact symbols_preserved. eauto. eauto.\n  econstructor; eauto.\n\n  (* Lgetstack *)\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor; eauto.\n  econstructor; eauto.\n\n  (* Lsetstack *)\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor; eauto.\n  econstructor; eauto.\n\n  (* Lstore *)\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor.\n  instantiate (1 := a). rewrite <- H; apply eval_addressing_preserved.\n  exact symbols_preserved. eauto. eauto.\n  econstructor; eauto.\n\n  (* Lcall *)\n  exploit find_function_translated; eauto. intros [tfd [A B]].\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor; eauto.\n  symmetry; eapply sig_preserved; eauto.\n  econstructor; eauto. constructor; auto. econstructor; eauto.\n\n  (* Ltailcall *)\n  exploit find_function_translated; eauto. intros [tfd [A B]].\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor; eauto.\n  destruct ros; simpl in *; eauto.\n  rewrite (match_parent_locset _ _ STACKS). eauto.\n  rewrite (match_parent_locset _ _ STACKS). eauto.\n  symmetry; eapply sig_preserved; eauto.\n  rewrite (stacksize_preserved _ _ TRF); eauto.\n  rewrite (match_parent_locset _ _ STACKS).\n  econstructor; eauto.\n\n  (* Lbuiltin *)\n  left; econstructor; split. simpl.\n  apply plus_one. eapply exec_Lbuiltin; eauto.\n  eapply eval_builtin_args_preserved with (ge1 := ge); eauto. exact symbols_preserved.\n  eapply external_call_symbols_preserved; eauto. apply senv_preserved.\n  econstructor; eauto.\n\n  (* Lbranch *)\n  assert ((reachable f)!!pc = true). apply REACH; simpl; auto.\n  right; split. simpl; lia. split. auto. simpl. econstructor; eauto.\n\n  (* Lcond *)\n  assert (REACH1: (reachable f)!!pc1 = true) by (apply REACH; simpl; auto).\n  assert (REACH2: (reachable f)!!pc2 = true) by (apply REACH; simpl; auto).\n  simpl linearize_block.\n  destruct (starts_with pc1 c).\n  (* branch if cond is false *)\n  assert (DC: destroyed_by_cond (negate_condition cond) = destroyed_by_cond cond).\n    destruct cond; reflexivity.\n  destruct b.\n  (* cond is true: no branch *)\n  left; econstructor; split.\n  apply plus_one. eapply exec_Lcond_false.\n  rewrite eval_negate_condition. rewrite H. auto. eauto.\n  rewrite DC. econstructor; eauto.\n  (* cond is false: branch is taken *)\n  right; split. simpl; lia. split. auto.  rewrite <- DC. econstructor; eauto.\n  rewrite eval_negate_condition. rewrite H. auto.\n  (* branch if cond is true *)\n  destruct b.\n  (* cond is true: branch is taken *)\n  right; split. simpl; lia. split. auto. econstructor; eauto.\n  (* cond is false: no branch *)\n  left; econstructor; split.\n  apply plus_one. eapply exec_Lcond_false. eauto. eauto.\n  econstructor; eauto.\n\n  (* Ljumptable *)\n  assert (REACH': (reachable f)!!pc = true).\n    apply REACH. simpl. eapply list_nth_z_in; eauto.\n  right; split. simpl; lia. split. auto. econstructor; eauto.\n\n  (* Lreturn *)\n  left; econstructor; split.\n  simpl. apply plus_one. econstructor; eauto.\n  rewrite (stacksize_preserved _ _ TRF). eauto.\n  rewrite (match_parent_locset _ _ STACKS). econstructor; eauto.\n\n  (* internal functions *)\n  assert (REACH: (reachable f)!!(LTL.fn_entrypoint f) = true).\n    apply reachable_entrypoint.\n  monadInv H10.\n  left; econstructor; split.\n  apply plus_one. eapply exec_function_internal; eauto.\n  rewrite (stacksize_preserved _ _ EQ). eauto.\n  generalize EQ; intro EQ'; monadInv EQ'. simpl.\n  econstructor; eauto. simpl. eapply is_tail_add_branch. constructor.\n\n  (* external function *)\n  monadInv H9. left; econstructor; split.\n  apply plus_one. eapply exec_function_external; eauto.\n  eapply external_call_symbols_preserved; eauto. apply senv_preserved.\n  econstructor; eauto.\n\n  (* return *)\n  inv H3. inv H1.\n  left; econstructor; split.\n  apply plus_one. econstructor.\n  econstructor; eauto.\nQed.\n\nLemma transf_initial_states:\n  forall st1, LTL.initial_state prog st1 ->\n  exists st2, Linear.initial_state tprog st2 /\\ match_states st1 st2.\nProof.\n  intros. inversion H.\n  exploit function_ptr_translated; eauto. intros [tf [A B]].\n  exists (Callstate nil tf (Locmap.init Vundef) m1 (prog_main tprog)); split.\n  econstructor; eauto. eapply (Genv.init_mem_transf_partial TRANSF); eauto.\n  rewrite (match_program_main TRANSF).\n  rewrite symbols_preserved. eauto.\n  rewrite <- H3. apply sig_preserved. auto.\n  rewrite (match_program_main TRANSF).\n  constructor. constructor. auto.\nQed.\n\nLemma transf_final_states:\n  forall st1 st2 r,\n  match_states st1 st2 -> LTL.final_state st1 r -> Linear.final_state st2 r.\nProof.\n  intros. inv H0. inv H. inv H5. econstructor; eauto.\nQed.\n\nTheorem transf_program_correct:\n  forward_simulation (LTL.semantics fn_stack_requirements prog)\n                     (Linear.semantics fn_stack_requirements tprog).\nProof.\n  eapply forward_simulation_star.\n  apply senv_preserved.\n  eexact transf_initial_states.\n  eexact transf_final_states.\n  eexact transf_step_correct.\nQed.\n\nEnd LINEARIZATION.\n", "meta": {"author": "SJTU-PLV", "repo": "nominal-compcert-popl22-artifact", "sha": "b2d2ee12497ac86c59034d042ef142cc3a123752", "save_path": "github-repos/coq/SJTU-PLV-nominal-compcert-popl22-artifact", "path": "github-repos/coq/SJTU-PLV-nominal-compcert-popl22-artifact/nominal-compcert-popl22-artifact-b2d2ee12497ac86c59034d042ef142cc3a123752/Stack-Aware-Nominal-CompCert/backend/Linearizeproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23390872761876408}}
{"text": "From SegmentQueue.lib.blocking_pool\n     Require Export outer_storage_interfaces.\nFrom iris.program_logic Require Import atomic.\nFrom iris.heap_lang Require Export proofmode notation lang.\nOpen Scope nat.\n\nSection impl.\n\nDefinition tryInsertStack: val :=\n  rec: \"loop\" \"top\" \"x\" :=\n    let: \"t\" := !\"top\" in\n    let: \"node\" := ref (SOME \"x\", \"t\") in\n    match: \"t\" with\n      SOME \"tn\" => let: \"topNode\" := !\"tn\" in\n                  let: \"element\" := Fst \"topNode\" in\n                  let: \"next\" := Snd \"topNode\" in\n                  match: \"element\" with\n                    SOME \"value\" => if: CAS \"top\" \"t\" (SOME \"node\")\n                                    then #true\n                                    else \"loop\" \"top\" \"x\"\n                  | NONE => if: CAS \"top\" \"t\" \"next\"\n                            then #false\n                            else \"loop\" \"top\" \"x\"\n                  end\n    | NONE => if: CAS \"top\" \"t\" (SOME \"node\")\n              then #true\n              else \"loop\" \"top\" \"x\"\n    end.\n\nDefinition tryRetrieveStack: val :=\n  rec: \"loop\" \"top\" :=\n    let: \"t\" := !\"top\" in\n    let: \"node\" := ref (NONE, \"t\") in\n    match: \"t\" with\n      SOME \"tn\" => let: \"topNode\" := !\"tn\" in\n                  let: \"element\" := Fst \"topNode\" in\n                  let: \"next\" := Snd \"topNode\" in\n                  match: \"element\" with\n                    SOME \"value\" => if: CAS \"top\" \"t\" \"next\"\n                                   then SOME \"value\"\n                                   else \"loop\" \"top\"\n                  | NONE => if: CAS \"top\" \"t\" (SOME \"node\")\n                           then NONE\n                           else \"loop\" \"top\"\n                  end\n    | NONE => if: CAS \"top\" \"t\" (SOME \"node\")\n             then NONE\n             else \"loop\" \"top\"\n    end.\n\nDefinition newStack: val :=\n  λ: <>, ref NONE.\n\nDefinition stackOuterStorageImpl :=\n  {|\n   tryInsert := tryInsertStack;\n   tryRetrieve := tryRetrieveStack;\n   newStorage := newStack;\n  |}.\n\nEnd impl.\n\nFrom iris.algebra Require Import cmra auth list agree csum numbers gmap excl.\nFrom iris.base_logic Require Import lib.invariants.\nFrom iris.bi.lib Require Import fractional.\nFrom SegmentQueue.lib.blocking_pool Require Export outer_storage_spec.\n\nSection proof.\n\nContext `{heapG Σ}.\n\nNotation stack_element_algebra :=\n  (agreeR (prodO (optionO valO) (optionO locO))).\n\nInductive nonEmpty t :=\n  NonEmpty: t -> list t -> nonEmpty t.\n\nDefinition hdNonEmpty {t} (xs: nonEmpty t) :=\n  match xs with NonEmpty _ x _ => x end.\n\nDefinition tlNonEmpty {t} (xs: nonEmpty t) :=\n  match xs with NonEmpty _ _ xs => xs end.\n\nDefinition nonEmptyToList {t} (xs: nonEmpty t) :=\n  match xs with NonEmpty _ x xs => x :: xs end.\n\nDefinition lengthNonEmpty {A : Type} (xs: nonEmpty A): positive :=\n  Pos.of_nat (S (length (tlNonEmpty xs))).\n\nDefinition mapNonEmpty {A B : Type} (f: A -> B) (xs: nonEmpty A): nonEmpty B :=\n  match xs with\n    NonEmpty _ x xs => NonEmpty _ (f x) (f <$> xs)\n  end.\n\nDefinition consNonEmpty {A : Type} (x : A) (xs : nonEmpty A): nonEmpty A :=\n  match xs with NonEmpty _ y ys => NonEmpty _ x (y::ys) end.\n\n\nInductive stackState :=\n| StackEmpty : stackState\n| StackWithValues : nonEmpty (loc * val) -> stackState\n| StackWithFailures : nonEmpty loc -> stackState.\n\nCanonical Structure stackStateO := leibnizO stackState.\n\nNotation algebra := (authUR (prodUR (gmapUR locO stack_element_algebra)\n                                    (optionUR (exclR stackStateO))\n                    )).\n\nInstance algebra_discrete: ∀ (x: algebra), Discrete x.\nProof. apply _. Qed.\n\nClass iStackG Σ := IStackG { iStack_inG :> inG Σ algebra }.\nDefinition iStackΣ : gFunctors := #[GFunctor algebra].\nInstance subG_iStackΣ : subG iStackΣ Σ → iStackG Σ.\nProof. solve_inG. Qed.\nContext `{iStackG Σ}.\n\nNotation iProp := (iProp Σ).\n\nVariable (N: namespace).\n\nDefinition has_contents γ (nodeℓ: loc) (value: option val) (tail: option loc)\n  : iProp := own γ (◯ ({[ nodeℓ := to_agree (value, tail) ]}, None)).\n\nTheorem has_contents_agrees γ ℓ value value' tail tail':\n  has_contents γ ℓ value tail -∗ has_contents γ ℓ value' tail' -∗\n               ⌜value = value' ∧ tail = tail'⌝.\nProof.\n  iIntros \"H◯1 H◯2\". iDestruct (own_valid_2 with \"H◯1 H◯2\") as %HValid.\n  iPureIntro. move: HValid. rewrite -auth_frag_op -pair_op singleton_op.\n  rewrite auth_frag_valid pair_valid singleton_valid. case=> HPf _.\n  apply agree_op_invL' in HPf. by case: HPf=> -> ->.\nQed.\n\nDefinition stack_state_ownership γ (state: stackState): iProp :=\n  own γ (◯ (ε, Excl' state)).\n\nDefinition stack_as_outer_storage (state: stackState): outerStorageState :=\n  match state with\n  | StackEmpty => OuterStorageState 0 ∅\n  | StackWithFailures p => OuterStorageState (length (nonEmptyToList p)) ∅\n  | StackWithValues val =>\n    OuterStorageState 0 (list_to_set_disj (snd <$> nonEmptyToList val))\n  end.\n\nDefinition outer_storage_state γ (state: outerStorageState): iProp :=\n  ∃ s, ⌜stack_as_outer_storage s = state⌝ ∧ stack_state_ownership γ s.\n\nFixpoint list_contains γ (values: list (loc * val))\n  : iProp :=\n  match values with\n    nil => True\n  | cons (ℓ, v) values' =>\n    has_contents γ ℓ (Some v) (hd_error (fst <$> values'))\n                 ∗ list_contains γ values'\n  end.\n\nInstance list_contains_persistent γ values :\n  Persistent (list_contains γ values).\nProof. elim: values. apply _. move=> [? ?]. apply _. Qed.\n\nInstance list_contains_timeless γ values :\n  Timeless (list_contains γ values).\nProof. elim: values. apply _. move=> [? ?]. apply _. Qed.\n\nFixpoint list_failures γ (values: list loc) : iProp :=\n  match values with\n    nil => True\n  | cons ℓ values' =>\n    has_contents γ ℓ None (hd_error values') ∗ list_failures γ values'\n  end.\n\nInstance list_failures_persistent γ values :\n  Persistent (list_failures γ values).\nProof. elim: values; apply _. Qed.\n\nInstance list_failures_timeless γ values :\n  Timeless (list_failures γ values).\nProof. elim: values; apply _. Qed.\n\nDefinition stack_top_value' (state: stackState): option loc :=\n  match state with\n  | StackEmpty => None\n  | StackWithValues ct => Some (fst (hdNonEmpty ct))\n  | StackWithFailures ct => Some (hdNonEmpty ct)\n  end.\n\nDefinition list_state γ (state: stackState): iProp :=\n  match state with\n  | StackEmpty => True\n  | StackWithValues ct => list_contains γ (nonEmptyToList ct)\n  | StackWithFailures ct => list_failures γ (nonEmptyToList ct)\n  end.\n\nInstance list_state_timeless γ state: Timeless (list_state γ state).\nProof. by case: state; apply _. Qed.\n\nInstance list_state_persistent γ state: Persistent (list_state γ state).\nProof. by case: state; apply _. Qed.\n\nDefinition heap_to_ra (heap: gmap loc (option val * option loc)):\n  gmapUR locO stack_element_algebra :=\n  to_agree <$> heap.\n\nDefinition option_to_value (v: option val): val :=\n  match v with\n    None => NONEV\n  | Some v => SOMEV v\n  end.\n\nTheorem option_to_value_inj:\n  FinFun.Injective option_to_value.\nProof.\n  intros a b. rewrite /option_to_value.\n  case: a; case: b=> //=.\n  move=> a b. case. by intros ->.\nQed.\n\nDefinition loc_to_value (v: option loc): val :=\n  option_to_value ((fun x => LitV (LitLoc x)) <$> v).\n\nTheorem loc_to_value_inj:\n  FinFun.Injective loc_to_value.\nProof.\n  intros a b HInj. apply option_to_value_inj in HInj. move: HInj.\n  case: a; case: b=> //=. move=> a b. case. by intros ->.\nQed.\n\nDefinition stack_top_value (state: stackState): val :=\n  loc_to_value (stack_top_value' state).\n\nDefinition heap_value (ℓ: loc) (c: option val * option loc): iProp :=\n  ℓ ↦ (option_to_value (fst c), loc_to_value (snd c)).\n\nDefinition heap_values (heap: gmap loc (option val * option loc)): iProp :=\n  [∗ map] ℓ ↦ c ∈ heap, heap_value ℓ c.\n\nDefinition stack_invariant γ topℓ: iProp :=\n  ∃ heap (state: stackState),\n    own γ (● (heap_to_ra heap, Excl' state))\n        ∗ heap_values heap\n        ∗ topℓ ↦ stack_top_value state ∗ list_state γ state.\n\nDefinition is_stack γ v: iProp :=\n  ∃ (topℓ: loc), ⌜v = #topℓ⌝ ∧ inv N (stack_invariant γ topℓ).\n\nGlobal Instance is_stack_persistent γ v: Persistent (is_stack γ v).\nProof. apply _. Qed.\n\nLemma stack_top_value_inj γ a b:\n  ⌜stack_top_value a = stack_top_value b⌝ -∗\n    list_state γ a -∗ list_state γ b -∗\n    ⌜a = b⌝.\nProof.\n  iIntros (HTopValue) \"H1 H2\".\n  apply loc_to_value_inj in HTopValue. move: HTopValue.\n  rewrite /stack_top_value'.\n  case: a; case: b=> //=; move=> a' b'; case.\n  all: case: a'=> x xs; case: b'=> y ys=> /=.\n  - case: y; case: x=> /=. move=> a1 a2 b1 b2 Heq. subst.\n    iInduction (xs) as [|x xs] \"IH\" forall (a1 a2 b2 ys).\n    * iDestruct \"H1\" as \"[H1h H1t]\". iDestruct \"H2\" as \"[H2h H2t]\".\n      iDestruct (has_contents_agrees with \"H1h H2h\") as %[H1 H2].\n      move: H1 H2=> /=. case: ys=> /=; last done.\n      by case=> ->.\n    * iDestruct \"H1\" as \"[H1h H1t]\". iDestruct \"H2\" as \"[H2h H2t]\".\n      iDestruct (has_contents_agrees with \"H1h H2h\") as %[H1 H2].\n      move: H1 H2=> /=. case: ys=> /=; first done. move=> y ys.\n      case=> HEq; subst. case: y; case: x=> a b c d. case=> HEq; subst.\n      simpl.\n      iDestruct (\"IH\" with \"H1t H2t\") as %HOk. move: HOk. case=> ? ?.\n      by subst.\n  - case: y=> /= a1 a2 HEq. subst.\n    iDestruct \"H1\" as \"[H1h H1t]\". iDestruct \"H2\" as \"[H2h H2t]\".\n    iDestruct (has_contents_agrees with \"H1h H2h\") as %[H1 H2].\n    done.\n  - case: x=> /= a1 a2 HEq. subst.\n    iDestruct \"H1\" as \"[H1h H1t]\". iDestruct \"H2\" as \"[H2h H2t]\".\n    iDestruct (has_contents_agrees with \"H1h H2h\") as %[H1 H2].\n    done.\n  - move=> HEq. subst.\n    iInduction (xs) as [|x' xs] \"IH\" forall (x ys).\n    * iDestruct \"H1\" as \"[H1h H1t]\". iDestruct \"H2\" as \"[H2h H2t]\".\n      iDestruct (has_contents_agrees with \"H1h H2h\") as %[H1 H2].\n      move: H1 H2=> /=. case: ys=> //=.\n    * iDestruct \"H1\" as \"[H1h H1t]\". iDestruct \"H2\" as \"[H2h H2t]\".\n      iDestruct (has_contents_agrees with \"H1h H2h\") as %[H1 H2].\n      move: H1 H2=> /=. case: ys=> /=; first done. move=> y ys _.\n      case=> HEq; subst.\n      iDestruct (\"IH\" with \"H1t H2t\") as %HOk. move: HOk. case=> ?.\n      by subst.\nQed.\n\nTheorem update_stack_state state γ topℓ storageState state':\n  list_state γ state -∗\n  list_state γ state' -∗\n  stack_invariant γ topℓ -∗\n  outer_storage_state γ storageState ==∗\n  (⌜storageState = stack_as_outer_storage state⌝ ∧\n    topℓ ↦ stack_top_value state ∗\n        (topℓ ↦ stack_top_value state' -∗ stack_invariant γ topℓ)\n        ∗ outer_storage_state γ (stack_as_outer_storage state') ∨\n   ∃ state'', ⌜state'' ≠ state⌝ ∧ list_state γ state'' ∗\n        topℓ ↦ stack_top_value state'' ∗\n        (topℓ ↦ stack_top_value state'' -∗ stack_invariant γ topℓ)\n        ∗ outer_storage_state γ storageState).\nProof.\n  iIntros \"#HList #HList' HInv H◯\".\n  iDestruct \"HInv\" as (heap currentState) \"(H● & HHeap & Htopℓ & #HList'')\".\n  iDestruct \"H◯\" as (currentState' <-) \"H◯\".\n  destruct (decide (stack_top_value currentState = stack_top_value state))\n    as [eq|neq].\n  - iDestruct (stack_top_value_inj with \"[%] [#] [#]\") as %HEq; try done.\n    subst.\n    iLeft. iFrame \"Htopℓ\".\n    iDestruct (own_valid_2 with \"H● H◯\")\n      as %[[_ HValid%Excl_included]%prod_included _]%auth_both_valid.\n    apply leibniz_equiv in HValid. subst.\n    iSplitR; first done.\n    iMod (own_update_2 with \"H● H◯\") as \"[H● H◯]\".\n    2: {\n      iModIntro. iSplitR \"H◯\".\n      - iIntros \"Htopℓ\". iExists heap, _. by iFrame.\n      - iExists state'. by iFrame.\n    }\n    apply auth_update, prod_local_update_2.\n    apply option_local_update.\n    by apply exclusive_local_update.\n  - iRight. iExists currentState. iFrame \"Htopℓ HList''\".\n    iSplitR.\n    { iPureIntro. intros heq. subst. done. }\n    iSplitR \"H◯\"; last by iExists _; iFrame.\n    iModIntro. iIntros \"Htopℓ\". iExists _, _. by iFrame.\nQed.\n\nTheorem register_heap_value (v: option val) (ℓ': option loc) γ ℓ heap state:\n  ℓ ↦ (option_to_value v,\n       option_to_value ((fun x => LitV (LitLoc x)) <$> ℓ'))\n    -∗ own γ (● (heap_to_ra heap, state))\n    -∗ heap_values heap\n    ==∗\n    ∃ heap', own γ (● (heap_to_ra heap', state)) ∗ heap_values heap' ∗\n    has_contents γ ℓ v ℓ'.\nProof.\n  iIntros \"Hℓ H● HHeap\". rewrite /heap_values /heap_value.\n  iAssert (⌜heap !! ℓ = None⌝)%I as %HNone.\n  {\n    destruct (heap !! ℓ) eqn:E; last done. iExFalso.\n    iDestruct (big_sepM_lookup with \"HHeap\") as \"HContra\"; first done.\n    by iDestruct (mapsto_valid_2 with \"Hℓ HContra\") as %[].\n  }\n  remember (<[ℓ := (v, ℓ')]> heap) as heap'.\n  iAssert ([∗ map] ℓ ↦ c ∈ heap', heap_value ℓ c)%I\n    with \"[Hℓ HHeap]\" as \"HHeap'\".\n  { subst. rewrite big_sepM_insert; last done. iFrame. }\n  iMod (own_update with \"H●\") as \"[H● H◯]\".\n  2: { iFrame \"H◯\". iExists heap'. by iFrame. }\n  subst. rewrite /heap_to_ra -map_fmap_singleton fmap_insert.\n  rewrite map_fmap_singleton.\n  apply auth_update_alloc, prod_local_update_1.\n  apply alloc_singleton_local_update.\n  by rewrite lookup_fmap HNone.\n  done.\nQed.\n\nTheorem hasContents_load γ ℓ topℓ (x: option val) (y: option loc):\n  {{{ inv N (stack_invariant γ topℓ) ∗ has_contents γ ℓ x y }}}\n    ! #ℓ\n  {{{ RET (option_to_value x, loc_to_value y); True }}}.\nProof.\n  iIntros (Φ) \"[#HInv #H◯] HΦ\". iInv N as \">HOpen\".\n  iDestruct \"HOpen\" as (heap state) \"(H● & HHeap & HRest)\".\n  rewrite /heap_values.\n  iDestruct (own_valid_2 with \"H● H◯\")\n    as %[[HValid%singleton_included_l _]%prod_included\n                                        HAuthValid]%auth_both_valid.\n  simpl in *. destruct HValid as (e & HLookup & HInc).\n  move: HInc. rewrite Some_included. move=> HAgree.\n  move: HAuthValid. case=> /= heapValid _.\n  assert (heap_to_ra heap !! ℓ ≡ Some (to_agree (x, y))) as HLookup'.\n  {\n    case: HAgree.\n    - move=> HAg; move: HLookup. by rewrite -HAg.\n    - destruct (to_agree_uninj e) as [HH HH1].\n      {\n        eapply lookup_valid_Some. 2: apply HLookup. done.\n      }\n      rewrite HLookup. rewrite -HH1. clear. case: HH=> x' y'.\n      rewrite to_agree_included. case=> /= -> -> //.\n  }\n  clear HLookup HAgree.\n  rewrite lookup_fmap in HLookup'.\n  destruct (decide (heap !! ℓ = Some (x, y))) as [eq|neq].\n  2: {\n    exfalso. destruct (heap !! ℓ) as [[a b]|] eqn:Z.\n    2: rewrite Z in HLookup'; inversion HLookup'.\n    rewrite Z in HLookup'. simpl in HLookup'.\n    apply Some_equiv_inj in HLookup'.\n    apply to_agree_inj in HLookup'. case: HLookup'. simpl.\n    move=> A B. move: neq.\n    apply leibniz_equiv in A. apply leibniz_equiv in B. by subst.\n  }\n  iDestruct (big_sepM_lookup_acc with \"HHeap\") as \"[HEl HRestore]\";\n    first done.\n  wp_load.\n  iSpecialize (\"HRestore\" with \"HEl\"). iModIntro.\n  iSpecialize (\"HΦ\" with \"[$]\"). iFrame.\n  iExists _, _. iFrame.\nQed.\n\nTheorem tryInsertStack_spec γ stack (value : val):\n  is_stack γ stack -∗\n  <<< ∀ state, ▷ outer_storage_state γ state >>>\n      tryInsert stackOuterStorageImpl stack value @ ⊤∖↑N\n        <<< ∃ (b: bool),\n                if b then\n                  outer_storage_state γ (insertionAddsValue state value)\n                else match insertionRemovesFailure state with\n                       None => False\n                     | Some state' => outer_storage_state γ state'\n                     end, RET #b >>>.\nProof.\n  iIntros \"#HIsStack\" (Φ) \"AU\". iDestruct \"HIsStack\" as (topℓ ->) \"HInv\".\n  wp_lam. wp_pures. iLöb as \"IH\". wp_bind (!#topℓ)%E.\n  iInv N as \">HOpen\" \"HClose\".\n  iDestruct \"HOpen\" as (heap1 state1) \"(H● & HHeap & Htopℓ & #HList)\".\n  wp_load.\n  iMod (\"HClose\" with \"[H● HHeap Htopℓ]\") as \"_\".\n  { iExists _, _. by iFrame. }\n  iModIntro. wp_pures. wp_alloc node as \"HNode\". iApply fupd_wp.\n  iInv N as \">HOpen\" \"HClose\".\n  iDestruct \"HOpen\" as (heap2 state2) \"(H● & HHeap & Htopℓ & HList')\".\n  iMod (register_heap_value (Some value) with \"HNode H● HHeap\")\n    as (?) \"(H● & HHeap & #HNode)\".\n  iMod (\"HClose\" with \"[Htopℓ HList' H● HHeap]\") as \"_\".\n  by iExists _, _; iFrame.\n  iModIntro. wp_pures.\n  destruct state1 as [|[[loc stored] values]|[failure failures]].\n  - wp_pures. wp_bind (CmpXchg _ _ _).\n    iInv N as \">HOpen\" \"HClose\".\n    iMod \"AU\" as (outerState) \"[>outerState HAuClose]\".\n    iAssert (list_state γ (StackWithValues (NonEmpty _ (node, value) [])))\n      with \"[#]\" as \"HList'\".\n    by simpl; iFrame \"HNode\".\n    iMod (update_stack_state with \"HList HList' HOpen outerState\")\n      as \"[(% & Htopℓ & HRestore & outerState)|H]\".\n    * subst. wp_cmpxchg_suc.\n      iDestruct \"HAuClose\" as \"[_ HAuClose]\".\n      iMod (\"HAuClose\" with \"[outerState]\") as \"HΦ\".\n      2: {\n        iModIntro.\n        iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n        by iSpecialize (\"HRestore\" with \"Htopℓ\").\n        iModIntro. by wp_pures.\n      }\n      simpl. iFrame.\n    * iDestruct \"H\"\n        as (state'') \"(% & #HList'' & Htopℓ & HRestore & outerStorage)\".\n      iAssert (⌜stack_top_value StackEmpty = stack_top_value state''⌝ -∗ False)%I\n        with \"[#]\" as %HNe.\n      {\n        iIntros (HTop).\n        by iDestruct (stack_top_value_inj with \"[%] [] []\") as %HContra.\n      }\n      wp_cmpxchg_fail.\n      iDestruct \"HAuClose\" as \"[HAuClose _]\".\n      iMod (\"HAuClose\" with \"outerStorage\") as \"AU\".\n      iModIntro.\n      iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n      by iSpecialize (\"HRestore\" with \"Htopℓ\").\n      iModIntro. wp_pures. wp_lam. wp_pures.\n      by iApply \"IH\".\n  - wp_pures. wp_apply hasContents_load. simpl.\n    { iFrame \"HInv\". iDestruct \"HList\" as \"[$ _]\". }\n    iIntros \"_\".\n    wp_pures. wp_bind (CmpXchg _ _ _).\n    iInv N as \">HOpen\" \"HClose\".\n    iMod \"AU\" as (outerState) \"[>outerState HAuClose]\".\n    iAssert (list_state γ (StackWithValues (NonEmpty _ (node, value)\n            ((loc, stored)::values))))\n      with \"[#]\" as \"HList'\".\n    by simpl; iFrame \"HNode\".\n    iMod (update_stack_state with \"HList HList' HOpen outerState\")\n      as \"[(% & Htopℓ & HRestore & outerState)|H]\".\n    * simpl. subst. wp_cmpxchg_suc.\n      iDestruct \"HAuClose\" as \"[_ HAuClose]\".\n      iMod (\"HAuClose\" with \"[outerState]\") as \"HΦ\".\n      2: {\n        iModIntro.\n        iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n        by iSpecialize (\"HRestore\" with \"Htopℓ\").\n        iModIntro. by wp_pures.\n      }\n      iFrame.\n    * iDestruct \"H\"\n        as (state'') \"(% & #HList'' & Htopℓ & HRestore & outerStorage)\".\n      iAssert (⌜stack_top_value _ = stack_top_value state''⌝ -∗ False)%I\n        with \"[#]\" as %HNe.\n      {\n        iIntros (HTop).\n        iDestruct (stack_top_value_inj with \"[%] [] []\") as %HContra.\n        apply HTop. iApply \"HList\". iApply \"HList''\". done.\n      }\n      wp_cmpxchg_fail.\n      iDestruct \"HAuClose\" as \"[HAuClose _]\".\n      iMod (\"HAuClose\" with \"outerStorage\") as \"AU\".\n      iModIntro.\n      iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n      by iSpecialize (\"HRestore\" with \"Htopℓ\").\n      iModIntro. wp_pures. wp_lam. wp_pures.\n      by iApply \"IH\".\n  - wp_pures. wp_apply hasContents_load.\n    { simpl. iFrame \"HInv\". iDestruct \"HList\" as \"[$ _]\". }\n    iIntros \"_\".\n    wp_pures. wp_bind (CmpXchg _ _ _).\n    iInv N as \">HOpen\" \"HClose\".\n    iMod \"AU\" as (outerState) \"[>outerState HAuClose]\".\n    destruct failures as [|failure' failures].\n    + iAssert (list_state γ StackEmpty) with \"[$]\" as \"HList'\".\n      iMod (update_stack_state with \"HList HList' HOpen outerState\")\n        as \"[(% & Htopℓ & HRestore & outerState)|H]\".\n      * subst. wp_cmpxchg_suc.\n        iDestruct \"HAuClose\" as \"[_ HAuClose]\".\n        iMod (\"HAuClose\" with \"[outerState]\") as \"HΦ\".\n        2: {\n          iModIntro.\n          iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n          by iSpecialize (\"HRestore\" with \"Htopℓ\").\n          iModIntro. by wp_pures.\n        }\n        iFrame.\n      * iDestruct \"H\"\n          as (state'') \"(% & #HList'' & Htopℓ & HRestore & outerStorage)\".\n        iAssert (⌜stack_top_value _ = stack_top_value state''⌝ -∗ False)%I\n          with \"[#]\" as %HNe.\n        {\n          iIntros (HTop).\n          iDestruct (stack_top_value_inj with \"[%] [] []\") as %HContra.\n          apply HTop. iApply \"HList\". iApply \"HList''\". done.\n        }\n        wp_cmpxchg_fail.\n        iDestruct \"HAuClose\" as \"[HAuClose _]\".\n        iMod (\"HAuClose\" with \"outerStorage\") as \"AU\".\n        iModIntro.\n        iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n        by iSpecialize (\"HRestore\" with \"Htopℓ\").\n        iModIntro. wp_pures. wp_lam. wp_pures.\n        by iApply \"IH\".\n    + iAssert (list_state γ (StackWithFailures (NonEmpty _ failure' failures)))\n        with \"[#]\" as \"HList'\".\n      { simpl. iDestruct \"HList\" as \"[_ $]\". }\n      iMod (update_stack_state with \"HList HList' HOpen outerState\")\n        as \"[(% & Htopℓ & HRestore & outerState)|H]\".\n      * subst. wp_cmpxchg_suc.\n        iDestruct \"HAuClose\" as \"[_ HAuClose]\".\n        iMod (\"HAuClose\" with \"[outerState]\") as \"HΦ\".\n        2: {\n          iModIntro.\n          iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n          by iSpecialize (\"HRestore\" with \"Htopℓ\").\n          iModIntro. by wp_pures.\n        }\n        iFrame.\n      * iDestruct \"H\"\n          as (state'') \"(% & #HList'' & Htopℓ & HRestore & outerStorage)\".\n        iAssert (⌜stack_top_value _ = stack_top_value state''⌝ -∗ False)%I\n          with \"[#]\" as %HNe.\n        {\n          iIntros (HTop).\n          iDestruct (stack_top_value_inj with \"[%] [] []\") as %HContra.\n          apply HTop. iApply \"HList\". iApply \"HList''\". done.\n        }\n        wp_cmpxchg_fail.\n        iDestruct \"HAuClose\" as \"[HAuClose _]\".\n        iMod (\"HAuClose\" with \"outerStorage\") as \"AU\".\n        iModIntro.\n        iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n        by iSpecialize (\"HRestore\" with \"Htopℓ\").\n        iModIntro. wp_pures. wp_lam. wp_pures.\n        by iApply \"IH\".\nQed.\n\nSection XX.\nContext `{Countable A}.\nImplicit Types x y : A.\nImplicit Types X Y : gmultiset A.\nLemma gmultiset_difference_disj_union X Y : Y = (X ⊎ Y) ∖ X.\nProof.\n  apply gmultiset_eq. move=> x.\n  rewrite multiplicity_difference multiplicity_disj_union. lia.\nQed.\nEnd XX.\n\nTheorem tryRetrieveStack_spec γ stack:\n  is_stack γ stack -∗\n  <<< ∀ state, ▷ outer_storage_state γ state >>>\n      tryRetrieve stackOuterStorageImpl stack @ ⊤∖↑N\n  <<< ∃ (v : option val),\n          match v with\n            | Some v' => match retrievalRemovesValue state v' with\n                          | None => False\n                          | Some state' => outer_storage_state γ state'\n                        end\n            | None => outer_storage_state γ (retrievalAddsFailure state)\n          end, RET option_to_value v >>>.\nProof.\n  iIntros \"#HIsStack\" (Φ) \"AU\". iDestruct \"HIsStack\" as (topℓ ->) \"HInv\".\n  wp_lam. wp_pures. iLöb as \"IH\". wp_bind (!#topℓ)%E.\n  iInv N as \">HOpen\" \"HClose\".\n  iDestruct \"HOpen\" as (heap1 state1) \"(H● & HHeap & Htopℓ & #HList)\".\n  wp_load.\n  iMod (\"HClose\" with \"[H● HHeap Htopℓ]\") as \"_\".\n  { iExists _, _. by iFrame. }\n  iModIntro. wp_pures. wp_alloc node as \"HNode\". iApply fupd_wp.\n  iInv N as \">HOpen\" \"HClose\".\n  iDestruct \"HOpen\" as (heap2 state2) \"(H● & HHeap & Htopℓ & HList')\".\n  iMod (register_heap_value None with \"HNode H● HHeap\")\n    as (?) \"(H● & HHeap & #HNode)\".\n  iMod (\"HClose\" with \"[Htopℓ HList' H● HHeap]\") as \"_\".\n  by iExists _, _; iFrame.\n  iModIntro. wp_pures.\n  destruct state1 as [|[[loc stored] values]|[failure failures]].\n  - wp_pures. wp_bind (CmpXchg _ _ _).\n    iInv N as \">HOpen\" \"HClose\".\n    iMod \"AU\" as (outerState) \"[>outerState HAuClose]\".\n    iAssert (list_state γ (StackWithFailures (NonEmpty _ node [])))\n      with \"[#]\" as \"HList'\".\n    by simpl; iFrame \"HNode\".\n    iMod (update_stack_state with \"HList HList' HOpen outerState\")\n      as \"[(% & Htopℓ & HRestore & outerState)|H]\".\n    * subst. wp_cmpxchg_suc.\n      iDestruct \"HAuClose\" as \"[_ HAuClose]\".\n      iMod (\"HAuClose\" $! None with \"[outerState]\") as \"HΦ\".\n      2: {\n        iModIntro.\n        iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n        by iSpecialize (\"HRestore\" with \"Htopℓ\").\n        iModIntro. by wp_pures.\n      }\n      iFrame.\n    * iDestruct \"H\"\n        as (state'') \"(% & #HList'' & Htopℓ & HRestore & outerStorage)\".\n      iAssert (⌜stack_top_value StackEmpty = stack_top_value state''⌝ -∗ False)%I\n        with \"[#]\" as %HNe.\n      {\n        iIntros (HTop).\n        by iDestruct (stack_top_value_inj with \"[%] [] []\") as %HContra.\n      }\n      wp_cmpxchg_fail.\n      iDestruct \"HAuClose\" as \"[HAuClose _]\".\n      iMod (\"HAuClose\" with \"outerStorage\") as \"AU\".\n      iModIntro.\n      iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n      by iSpecialize (\"HRestore\" with \"Htopℓ\").\n      iModIntro. wp_pures. wp_lam. wp_pures.\n      by iApply \"IH\".\n  - wp_pures. wp_apply hasContents_load.\n    { simpl. iFrame \"HInv\". iDestruct \"HList\" as \"[$ _]\". }\n    iIntros \"_\".\n    wp_pures. wp_bind (CmpXchg _ _ _).\n    iInv N as \">HOpen\" \"HClose\".\n    iMod \"AU\" as (outerState) \"[>outerState HAuClose]\".\n    destruct values as [|value' values].\n    + iAssert (list_state γ StackEmpty) with \"[$]\" as \"HList'\".\n      iMod (update_stack_state with \"HList HList' HOpen outerState\")\n        as \"[(% & Htopℓ & HRestore & outerState)|H]\".\n      * subst. wp_cmpxchg_suc.\n        iDestruct \"HAuClose\" as \"[_ HAuClose]\".\n        iMod (\"HAuClose\" $! (Some stored) with \"[outerState]\") as \"HΦ\".\n        2: {\n          iModIntro.\n          iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n          by iSpecialize (\"HRestore\" with \"Htopℓ\").\n          iModIntro. by wp_pures.\n        }\n        rewrite /retrievalRemovesValue. simpl.\n        rewrite gmultiset_disj_union_right_id.\n        rewrite multiplicity_singleton.\n        rewrite gmultiset_difference_diag.\n        iFrame.\n      * iDestruct \"H\"\n          as (state'') \"(% & #HList'' & Htopℓ & HRestore & outerStorage)\".\n        iAssert (⌜stack_top_value _ = stack_top_value state''⌝ -∗ False)%I\n          with \"[#]\" as %HNe.\n        {\n          iIntros (HTop).\n          iDestruct (stack_top_value_inj with \"[%] [] []\") as %HContra.\n          apply HTop. iApply \"HList\". iApply \"HList''\". done.\n        }\n        wp_cmpxchg_fail.\n        iDestruct \"HAuClose\" as \"[HAuClose _]\".\n        iMod (\"HAuClose\" with \"outerStorage\") as \"AU\".\n        iModIntro.\n        iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n        by iSpecialize (\"HRestore\" with \"Htopℓ\").\n        iModIntro. wp_pures. wp_lam. wp_pures.\n        by iApply \"IH\".\n    + iAssert (list_state γ (StackWithValues (NonEmpty _ value' values)))\n        with \"[#]\" as \"HList'\".\n      { simpl. iDestruct \"HList\" as \"[_ $]\". }\n      iMod (update_stack_state with \"HList HList' HOpen outerState\")\n        as \"[(% & Htopℓ & HRestore & outerState)|H]\".\n      * subst. wp_cmpxchg_suc.\n        iDestruct \"HAuClose\" as \"[_ HAuClose]\".\n        iMod (\"HAuClose\" $! (Some stored) with \"[outerState]\") as \"HΦ\".\n        2: {\n          iModIntro.\n          iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n          by iSpecialize (\"HRestore\" with \"Htopℓ\").\n          iModIntro. by wp_pures.\n        }\n        iFrame.\n        rewrite /retrievalRemovesValue. simpl.\n        rewrite multiplicity_disj_union multiplicity_singleton /=.\n        rewrite -gmultiset_difference_disj_union. iFrame.\n      * iDestruct \"H\"\n          as (state'') \"(% & #HList'' & Htopℓ & HRestore & outerStorage)\".\n        iAssert (⌜stack_top_value _ = stack_top_value state''⌝ -∗ False)%I\n          with \"[#]\" as %HNe.\n        {\n          iIntros (HTop).\n          iDestruct (stack_top_value_inj with \"[%] [] []\") as %HContra.\n          apply HTop. iApply \"HList\". iApply \"HList''\". done.\n        }\n        wp_cmpxchg_fail.\n        iDestruct \"HAuClose\" as \"[HAuClose _]\".\n        iMod (\"HAuClose\" with \"outerStorage\") as \"AU\".\n        iModIntro.\n        iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n        by iSpecialize (\"HRestore\" with \"Htopℓ\").\n        iModIntro. wp_pures. wp_lam. wp_pures.\n        by iApply \"IH\".\n  - wp_pures. wp_apply hasContents_load. simpl.\n    { iFrame \"HInv\". iDestruct \"HList\" as \"[$ _]\". }\n    iIntros \"_\".\n    wp_pures. wp_bind (CmpXchg _ _ _).\n    iInv N as \">HOpen\" \"HClose\".\n    iMod \"AU\" as (outerState) \"[>outerState HAuClose]\".\n    iAssert (list_state γ (StackWithFailures (NonEmpty _ node\n            (failure::failures))))\n      with \"[#]\" as \"HList'\".\n    by simpl; iFrame \"HNode\".\n    iMod (update_stack_state with \"HList HList' HOpen outerState\")\n      as \"[(% & Htopℓ & HRestore & outerState)|H]\".\n    * simpl. subst. wp_cmpxchg_suc.\n      iDestruct \"HAuClose\" as \"[_ HAuClose]\".\n      iMod (\"HAuClose\" $! None with \"[outerState]\") as \"HΦ\".\n      2: {\n        iModIntro.\n        iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n        by iSpecialize (\"HRestore\" with \"Htopℓ\").\n        iModIntro. by wp_pures.\n      }\n      iFrame.\n    * iDestruct \"H\"\n        as (state'') \"(% & #HList'' & Htopℓ & HRestore & outerStorage)\".\n      iAssert (⌜stack_top_value _ = stack_top_value state''⌝ -∗ False)%I\n        with \"[#]\" as %HNe.\n      {\n        iIntros (HTop).\n        iDestruct (stack_top_value_inj with \"[%] [] []\") as %HContra.\n        apply HTop. iApply \"HList\". iApply \"HList''\". done.\n      }\n      wp_cmpxchg_fail.\n      iDestruct \"HAuClose\" as \"[HAuClose _]\".\n      iMod (\"HAuClose\" with \"outerStorage\") as \"AU\".\n      iModIntro.\n      iMod (\"HClose\" with \"[Htopℓ HRestore]\") as \"_\".\n      by iSpecialize (\"HRestore\" with \"Htopℓ\").\n      iModIntro. wp_pures. wp_lam. wp_pures.\n      by iApply \"IH\".\nQed.\n\nTheorem newStack_spec:\n  {{{ True }}}\n    newStorage stackOuterStorageImpl #()\n  {{{ γ v, RET v; is_stack γ v ∗\n                  outer_storage_state γ (OuterStorageState 0 ∅) }}}.\nProof.\n  iIntros (Φ) \"_ HΦ\". wp_lam. rewrite -wp_fupd.\n  wp_alloc ℓ as \"Hℓ\".\n  iMod (own_alloc (● (ε, Excl' StackEmpty) ⋅ ◯ (ε, Excl' StackEmpty)))\n    as (γ) \"[H● H◯]\".\n  by apply auth_both_valid.\n  iMod (inv_alloc N _ (stack_invariant γ ℓ) with \"[Hℓ H●]\") as \"HInv\".\n  { iExists ∅, StackEmpty. rewrite /heap_to_ra fmap_empty. iFrame.\n    rewrite /heap_values. by iApply big_sepM_empty.\n  }\n  iApply \"HΦ\". iSplitL \"HInv\".\n  - iExists _. by iFrame.\n  - iExists _. by iFrame.\nQed.\n\nEnd proof.\n\nCanonical Structure stack_outerStorage `{!heapG Σ} `{!iStackG Σ}:\n  outerStorageSpec Σ stackOuterStorageImpl :=\n  {|\n    is_outer_storage := is_stack;\n    outer_storage_contents := outer_storage_state;\n    tryInsert_spec := tryInsertStack_spec;\n    tryRetrieve_spec := tryRetrieveStack_spec;\n    newStorage_spec := newStack_spec;\n  |}.\n", "meta": {"author": "anonymousPldiSubmitterCQS", "repo": "proofs", "sha": "7dc09221303978c5918b5064ba787bc2268fa0bb", "save_path": "github-repos/coq/anonymousPldiSubmitterCQS-proofs", "path": "github-repos/coq/anonymousPldiSubmitterCQS-proofs/proofs-7dc09221303978c5918b5064ba787bc2268fa0bb/theories/lib/blocking_pool/stack_outer_storage.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.23390872761876405}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        Coq.Strings.String\n        Coq.Arith.Mult\n        Coq.Vectors.Vector.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Common.BoundedLookup\n        Fiat.Common.ilist\n        Fiat.Common.DecideableEnsembles\n        Fiat.Common.IterateBoundedIndex\n        Fiat.Common.Tactics.CacheStringConstant\n        Fiat.Computation\n        Fiat.QueryStructure.Specification.Representation.Notations\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.Narcissus.BinLib.Core\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Automation.Solver\n        Fiat.Narcissus.Formats.WordOpt\n        Fiat.Narcissus.Formats.NatOpt\n        Fiat.Narcissus.Formats.StringOpt\n        Fiat.Narcissus.Formats.EnumOpt\n        Fiat.Narcissus.Formats.FixListOpt\n        Fiat.Narcissus.Formats.SumTypeOpt\n        Fiat.Narcissus.Formats.DomainNameOpt\n        Fiat.Narcissus.Examples.DNS.DNSPacket.\n\nRequire Import\n        Bedrock.Word.\n\nSection DnsPacket.\n\n  Open Scope Tuple_scope.\n\n  Definition association_list K V := list (K * V).\n\n  Fixpoint association_list_find_first {K V}\n           {K_eq : Query_eq K}\n           (l : association_list K V)\n           (k : K) : option V :=\n    match l with\n    | (k', v) :: l' => if A_eq_dec k k' then Some v else association_list_find_first l' k\n    | _ => None\n    end.\n\n  Fixpoint association_list_find_all {K V}\n           {K_eq : Query_eq K}\n           (l : association_list K V)\n           (k : K) : list V :=\n    match l with\n    | (k', v) :: l' => if A_eq_dec k k' then v :: association_list_find_all l' k\n                       else association_list_find_all l' k\n    | _ => nil\n    end.\n\n  Fixpoint association_list_add {K V}\n           {K_eq : DecideableEnsembles.Query_eq K}\n           (l : association_list K V)\n           (k : K) (v : V) : list (K * V)  :=\n    (k, v) :: l.\n\n  Instance dns_list_cache : Cache :=\n    {| CacheFormat := option (word 17) * association_list string pointerT;\n       CacheDecode := option (word 17) * association_list pointerT string;\n       Equiv ce cd := fst ce = fst cd\n                      /\\ (snd ce) = (map (fun ps => match ps with (p, s) => (s, p) end) (snd cd))\n                      /\\ NoDup (map fst (snd cd))\n    |}%type.\n\n  Definition list_CacheFormat_empty : CacheFormat := (Some (wzero _), nil).\n  Definition list_CacheDecode_empty : CacheDecode := (Some (wzero _), nil).\n\n  Lemma list_cache_empty_Equiv : Equiv list_CacheFormat_empty list_CacheDecode_empty.\n  Proof.\n    simpl; intuition; simpl; econstructor.\n  Qed.\n\n  Local Opaque pow2.\n  Arguments natToWord : simpl never.\n  Arguments wordToNat : simpl never.\n\n  (* pointerT2Nat (Nat2pointerT (NPeano.div (wordToNat w) 8)) *)\n\n  Instance cacheAddNat : CacheAdd _ nat :=\n    {| addE ce n := (Ifopt (fst ce) as m Then\n                                         let n' := (wordToNat m) + n in\n                     if Compare_dec.lt_dec n' (pow2 17)\n                     then Some (natToWord _ n')\n                     else None\n                            Else None, snd ce);\n       addD cd n := (Ifopt (fst cd) as m Then\n                                         let n' := (wordToNat m) + n in\n                     if Compare_dec.lt_dec n' (pow2 17)\n                     then Some (natToWord _ n')\n                     else None\n                            Else None, snd cd) |}.\n  Proof.\n    simpl; intuition eauto; destruct a; destruct a0;\n      simpl in *; eauto; try congruence.\n    injections.\n    find_if_inside; eauto.\n  Defined.\n\n  Instance Query_eq_string : Query_eq string :=\n    {| A_eq_dec := string_dec |}.\n\n  Instance : Query_eq pointerT :=\n    {| A_eq_dec := pointerT_eq_dec |}.\n\n  Instance cachePeekDNPointer : CachePeek _ (option pointerT) :=\n    {| peekE ce := Ifopt (fst ce) as m Then Some (Nat2pointerT (wordToNat (wtl (wtl (wtl m))))) Else None;\n       peekD cd := Ifopt (fst cd) as m Then Some\n                                       (Nat2pointerT (wordToNat (wtl (wtl (wtl m)))))\n                                       Else None |}.\n  Proof.\n    abstract (simpl; intros; intuition; rewrite H0; auto).\n  Defined.\n\n  Lemma cacheGetDNPointer_pf\n    : forall (ce : CacheFormat) (cd : CacheDecode)\n             (p : string) (q : pointerT),\n      Equiv ce cd ->\n      (association_list_find_first (snd cd) q = Some p <-> List.In q (association_list_find_all (snd ce) p)).\n  Proof.\n    intros [? ?] [? ?] ? ?; simpl; intuition eauto; subst.\n    - subst; induction a0; simpl in *; try congruence.\n      destruct a; simpl in *; find_if_inside; subst.\n      + inversion H2; subst; intros.\n        find_if_inside; subst; simpl; eauto.\n      + inversion H2; subst; intros.\n        find_if_inside; subst; simpl; eauto; congruence.\n    - subst; induction a0; simpl in *; intuition.\n      destruct a; simpl in *; find_if_inside.\n      + inversion H2; subst; intros.\n        find_if_inside; subst; simpl; eauto; try congruence.\n        apply IHa0 in H1; eauto.\n        exfalso; apply H3; revert H1; clear.\n        induction a0; simpl; intros; try congruence.\n        destruct a; find_if_inside; injections; auto.\n      + inversion H2; subst; intros.\n        find_if_inside; subst; simpl; eauto; try congruence.\n        simpl in H1; intuition eauto; subst.\n        congruence.\n  Qed.\n\n  Instance cacheGetDNPointer : CacheGet dns_list_cache string pointerT :=\n    {| getE ce p := @association_list_find_all string _ _ (snd ce) p;\n       getD ce p := association_list_find_first (snd ce) p;\n       get_correct := cacheGetDNPointer_pf |}.\n\n  Lemma cacheAddDNPointer_pf\n    : forall (ce : CacheFormat) (cd : CacheDecode) (t : string * pointerT),\n   Equiv ce cd ->\n   add_ptr_OK t ce cd ->\n   Equiv (fst ce, association_list_add (snd ce) (fst t) (snd t))\n     (fst cd, association_list_add (snd cd) (snd t) (fst t)).\n  Proof.\n    simpl; intuition eauto; simpl in *; subst; eauto.\n    unfold add_ptr_OK in *.\n    destruct t; simpl in *; simpl; econstructor; eauto.\n    clear H3; induction b0; simpl.\n    - intuition.\n    - simpl in H0; destruct a; find_if_inside;\n        try discriminate.\n      intuition.\n  Qed.\n\n  Instance cacheAddDNPointer\n    : CacheAdd_Guarded _ add_ptr_OK :=\n    {| addE_G ce sp := (fst ce, association_list_add (snd ce) (fst sp) (snd sp));\n       addD_G cd sp := (fst cd, association_list_add (snd cd) (snd sp) (fst sp));\n       add_correct_G := cacheAddDNPointer_pf\n    |}.\n\n  Lemma IndependentCaches :\n    forall env p (b : nat),\n      getD (addD env b) p = getD env p.\n  Proof.\n    simpl; intros; eauto.\n  Qed.\n\n  Lemma IndependentCaches' :\n    forall env p (b : nat),\n      getE (addE env b) p = getE env p.\n  Proof.\n    simpl; intros; eauto.\n  Qed.\n\n  Lemma IndependentCaches''' :\n    forall env b,\n      peekE (addE_G env b) = peekE env.\n  Proof.\n    simpl; intros; eauto.\n  Qed.\n\n  Lemma getDistinct :\n    forall env l p p',\n      p <> p'\n      -> getD (addD_G env (l, p)) p' = getD env p'.\n  Proof.\n    simpl; intros; eauto.\n    find_if_inside; try congruence.\n  Qed.\n\n  Lemma getDistinct' :\n    forall env l p p' l',\n      List.In p (getE (addE_G env (l', p')) l)\n      -> p = p' \\/ List.In p (getE env l).\n  Proof.\n    simpl in *; intros; intuition eauto.\n    find_if_inside; simpl in *; intuition eauto.\n  Qed.\n\n  Arguments NPeano.div : simpl never.\n\n  Lemma mult_pow2 :\n    forall m n,\n      pow2 m * pow2 n = pow2 (m + n).\n  Proof.\n    Local Transparent pow2.\n    induction m; simpl; intros.\n    - omega.\n    - rewrite <- IHm.\n      rewrite <- !plus_n_O.\n      rewrite Mult.mult_plus_distr_r; omega.\n  Qed.\n\n  Corollary mult_pow2_8 : forall n,\n      8 * (pow2 n) = pow2 (3 + n).\n  Proof.\n    intros; rewrite <- mult_pow2.\n    reflexivity.\n  Qed.\n\n  Local Opaque pow2.\n\n  Lemma pow2_div\n    : forall m n,\n      lt (m + n * 8) (pow2 17)\n      -> lt (NPeano.div m 8) (pow2 14).\n  Proof.\n    intros.\n    eapply (NPeano.Nat.mul_lt_mono_pos_l 8); try omega.\n    rewrite mult_pow2_8.\n    eapply le_lt_trans.\n    apply NPeano.Nat.mul_div_le; try omega.\n    simpl.\n    omega.\n  Qed.\n\n  Lemma addPeekNone :\n    forall env n,\n      peekD env = None\n      -> peekD (addD env n) = None.\n  Proof.\n    simpl; intros.\n    destruct (fst env); simpl in *; congruence.\n  Qed.\n\n  Lemma wtl_div\n    : forall n (w : word (S (S (S n)))),\n      wordToNat (wtl (wtl (wtl w))) = NPeano.div (wordToNat w) 8.\n  Proof.\n    intros.\n    pose proof (shatter_word_S w); destruct_ex; subst.\n    pose proof (shatter_word_S x0); destruct_ex; subst.\n    pose proof (shatter_word_S x2); destruct_ex; subst.\n    simpl wtl.\n    rewrite <- (NPeano.Nat.div_div _ 2 4) by omega.\n    rewrite <- (NPeano.Nat.div_div _ 2 2) by omega.\n    rewrite <- !NPeano.Nat.div2_div.\n    rewrite !div2_WS.\n    reflexivity.\n  Qed.\n\n  Lemma mult_lt_compat_l'\n    : forall (m n p : nat),\n      lt 0 p\n      -> lt (p * n)  (p * m)\n      -> lt n m.\n  Proof.\n    induction m; simpl; intros; try omega.\n    rewrite (mult_comm p 0) in H0; simpl in *; try omega.\n    destruct p; try (exfalso; auto with arith; omega).\n    inversion H0.\n    rewrite (mult_comm p (S m)) in H0.\n    simpl in H0.\n    destruct n; try omega.\n    rewrite (mult_comm p (S n)) in H0; simpl in H0.\n    apply plus_lt_reg_l in H0.\n    rewrite <- NPeano.Nat.succ_lt_mono.\n    eapply (IHm n p); try eassumption; try omega.\n    rewrite mult_comm.\n    rewrite (mult_comm p m); auto.\n  Qed.\n\n  Lemma mult_lt_compat_l''\n    : forall (p m k n : nat),\n      lt 0 p\n      -> lt n m\n      -> lt k p\n      -> lt ((p * n) + k) (p * m).\n  Proof.\n    induction p; intros; try omega.\n    simpl.\n    inversion H; subst; simpl.\n    inversion H1; subst; omega.\n    destruct k; simpl.\n    - rewrite <- plus_n_O.\n      eapply (mult_lt_compat_l n m (S p)); auto.\n    - assert (lt (p * n + k) (p * m)) by\n          (apply IHp; try omega).\n      omega.\n  Qed.\n\n  Lemma addPeekNone' :\n    forall env n m,\n      peekD env = Some m\n      -> ~ lt (n + (pointerT2Nat m)) (pow2 14)\n      -> peekD (addD env (n * 8)) = None.\n  Proof.\n    simpl; intros; subst.\n    destruct (fst env); simpl in *; try discriminate.\n    injections.\n    find_if_inside; try reflexivity.\n    unfold If_Opt_Then_Else.\n    rewrite !wtl_div in *.\n    exfalso; apply H0.\n    rewrite pointerT2Nat_Nat2pointerT in *;\n      try (eapply pow2_div; eassumption).\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    destruct n; try omega.\n    exfalso; apply H0.\n    simpl.\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    - eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      simpl in l.\n      rewrite mult_pow2_8; simpl; omega.\n    - rewrite mult_plus_distr_l.\n      assert (8 <> 0) by omega.\n      pose proof (NPeano.Nat.mul_div_le (wordToNat w) 8 H).\n      apply le_lt_trans with (8 * S n + (wordToNat w)).\n      omega.\n      rewrite mult_pow2_8; simpl; omega.\n  Qed.\n\n  Lemma addPeekSome :\n    forall env n m,\n      peekD env = Some m\n      -> lt (n + (pointerT2Nat m)) (pow2 14)\n      -> exists p',\n          peekD (addD env (n * 8)) = Some p'\n          /\\ pointerT2Nat p' = n + (pointerT2Nat m).\n  Proof.\n    simpl; intros; subst.\n    destruct (fst env); simpl in *; try discriminate.\n    injections.\n    find_if_inside.\n    - rewrite !wtl_div in *.\n      rewrite pointerT2Nat_Nat2pointerT in *;\n        try (eapply pow2_div; eassumption).\n      unfold If_Opt_Then_Else.\n      eexists; split; try reflexivity.\n      rewrite wtl_div.\n      rewrite wordToNat_natToWord_idempotent.\n      rewrite pointerT2Nat_Nat2pointerT in *; try omega.\n      rewrite NPeano.Nat.div_add; try omega.\n      rewrite NPeano.Nat.div_add; try omega.\n      apply Nomega.Nlt_in.\n      rewrite Nnat.Nat2N.id, Npow2_nat; auto.\n    - exfalso; apply n0.\n      rewrite !wtl_div in *.\n      rewrite pointerT2Nat_Nat2pointerT in *.\n      rewrite (NPeano.div_mod (wordToNat w) 8); try omega.\n      pose proof (mult_pow2_8 14) as H'; simpl plus in H'; rewrite <- H'.\n      replace (8 * NPeano.div (wordToNat w) 8 + NPeano.modulo (wordToNat w) 8 + n * 8)\n      with (8 * (NPeano.div (wordToNat w) 8 + n) + NPeano.modulo (wordToNat w) 8)\n        by omega.\n      eapply mult_lt_compat_l''; try omega.\n      apply NPeano.Nat.mod_upper_bound; omega.\n      eapply (mult_lt_compat_l' _ _ 8); try omega.\n      eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      rewrite mult_pow2_8; simpl.\n      apply wordToNat_bound.\n  Qed.\n\n  Lemma addZeroPeek :\n    forall xenv,\n      peekD xenv = peekD (addD xenv 0).\n  Proof.\n    simpl; intros.\n    destruct (fst xenv); simpl; eauto.\n    find_if_inside; unfold If_Opt_Then_Else.\n    rewrite <- plus_n_O, natToWord_wordToNat; auto.\n    exfalso; apply n.\n    rewrite <- plus_n_O.\n    apply wordToNat_bound.\n  Qed.\n\n  Local Opaque wordToNat.\n  Local Opaque natToWord.\nv\n  Lemma boundPeekSome :\n    forall env n m m',\n      peekD env = Some m\n      -> peekD (addD env (n * 8)) = Some m'\n      -> lt (n + (pointerT2Nat m)) (pow2 14).\n  Proof.\n    simpl; intros; subst.\n    destruct (fst env); simpl in *; try discriminate.\n    injections.\n    find_if_inside; unfold If_Opt_Then_Else in *; try congruence.\n    injections.\n    rewrite !wtl_div in *.\n    rewrite pointerT2Nat_Nat2pointerT in *;\n      try (eapply pow2_div; eassumption).\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    - rewrite mult_plus_distr_l.\n      assert (8 <> 0) by omega.\n      pose proof (NPeano.Nat.mul_div_le (wordToNat w) 8 H).\n      apply le_lt_trans with (8 * n + (wordToNat w)).\n      omega.\n      rewrite mult_pow2_8.\n      simpl plus at -1.\n      omega.\n  Qed.\n\n  Lemma addPeekESome :\n    forall env n m,\n      peekE env = Some m\n      -> lt (n + (pointerT2Nat m)) (pow2 14)%nat\n      -> exists p',\n          peekE (addE env (n * 8)) = Some p'\n          /\\ pointerT2Nat p' = n + (pointerT2Nat m).\n  Proof.\n        simpl; intros; subst.\n    destruct (fst env); simpl in *; try discriminate.\n    injections.\n    find_if_inside.\n    - rewrite !wtl_div in *.\n      rewrite pointerT2Nat_Nat2pointerT in *;\n        try (eapply pow2_div; eassumption).\n      unfold If_Opt_Then_Else.\n      eexists; split; try reflexivity.\n      rewrite wtl_div.\n      rewrite wordToNat_natToWord_idempotent.\n      rewrite pointerT2Nat_Nat2pointerT in *; try omega.\n      rewrite NPeano.Nat.div_add; try omega.\n      rewrite NPeano.Nat.div_add; try omega.\n      apply Nomega.Nlt_in.\n      rewrite Nnat.Nat2N.id, Npow2_nat; auto.\n    - exfalso; apply n0.\n      rewrite !wtl_div in *.\n      rewrite pointerT2Nat_Nat2pointerT in *.\n      rewrite (NPeano.div_mod (wordToNat w) 8); try omega.\n      pose proof (mult_pow2_8 14) as H'; simpl plus in H'; rewrite <- H'.\n      replace (8 * NPeano.div (wordToNat w) 8 + NPeano.modulo (wordToNat w) 8 + n * 8)\n      with (8 * (NPeano.div (wordToNat w) 8 + n) + NPeano.modulo (wordToNat w) 8)\n        by omega.\n      eapply mult_lt_compat_l''; try omega.\n      apply NPeano.Nat.mod_upper_bound; omega.\n      eapply (mult_lt_compat_l' _ _ 8); try omega.\n      eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      rewrite mult_pow2_8; simpl.\n      apply wordToNat_bound.\n  Qed.\n\n  Lemma boundPeekESome :\n    forall env n m m',\n      peekE env = Some m\n      -> peekE (addE env (n * 8)) = Some m'\n      -> lt (n + (pointerT2Nat m)) (pow2 14).\n  Proof.\n    simpl; intros; subst.\n    destruct (fst env); simpl in *; try discriminate.\n    injections.\n    find_if_inside; unfold If_Opt_Then_Else in *; try congruence.\n    injections.\n    rewrite !wtl_div in *.\n    rewrite pointerT2Nat_Nat2pointerT in *;\n      try (eapply pow2_div; eassumption).\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    - rewrite mult_plus_distr_l.\n      assert (8 <> 0) by omega.\n      pose proof (NPeano.Nat.mul_div_le (wordToNat w) 8 H).\n      apply le_lt_trans with (8 * n + (wordToNat w)).\n      omega.\n      rewrite mult_pow2_8.\n      simpl plus at -1.\n      omega.\n  Qed.\n\n  Lemma addPeekENone :\n      forall env n,\n        peekE env = None\n        -> peekE (addE env n) = None.\n  Proof.\n    simpl; intros.\n    destruct (fst env); simpl in *; congruence.\n  Qed.\n\n  Lemma addPeekENone' :\n    forall env n m,\n      peekE env = Some m\n      -> ~ lt (n + (pointerT2Nat m)) (pow2 14)%nat\n      -> peekE (addE env (n * 8)) = None.\n  Proof.\n    simpl; intros; subst.\n    destruct (fst env); simpl in *; try discriminate.\n    injections.\n    find_if_inside; try reflexivity.\n    unfold If_Opt_Then_Else.\n    rewrite !wtl_div in *.\n    exfalso; apply H0.\n    rewrite pointerT2Nat_Nat2pointerT in *;\n      try (eapply pow2_div; eassumption).\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    destruct n; try omega.\n    exfalso; apply H0.\n    simpl.\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    - eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      simpl in l.\n      rewrite mult_pow2_8; simpl; omega.\n    - rewrite mult_plus_distr_l.\n      assert (8 <> 0) by omega.\n      pose proof (NPeano.Nat.mul_div_le (wordToNat w) 8 H).\n      apply le_lt_trans with (8 * S n + (wordToNat w)).\n      omega.\n      rewrite mult_pow2_8; simpl; omega.\n  Qed.\n\n  Lemma addZeroPeekE :\n    forall xenv,\n      peekE xenv = peekE (addE xenv 0).\n  Proof.\n    simpl; intros.\n    destruct (fst xenv); simpl; eauto.\n    find_if_inside; unfold If_Opt_Then_Else.\n    rewrite <- plus_n_O, natToWord_wordToNat; auto.\n    exfalso; apply n.\n    rewrite <- plus_n_O.\n    apply wordToNat_bound.\n  Qed.\n\n  Import Vectors.Vector.VectorNotations.\n\n  Definition GoodCache (env : CacheDecode) :=\n    forall domain p,\n      getD env p = Some domain\n      -> ValidDomainName domain\n         /\\ (String.length domain > 0)%nat\n         /\\ (getD env p = Some domain\n             -> forall p' : pointerT, peekD env = Some p' -> lt (pointerT2Nat p) (pointerT2Nat p')).\n\n  Lemma cacheIndependent_add\n    : forall (b : nat) (cd : CacheDecode),\n      GoodCache cd -> GoodCache (addD cd b).\n  Proof.\n    unfold GoodCache; intros.\n    rewrite IndependentCaches in *;\n      eapply H in H0; intuition eauto.\n    simpl in *.\n    destruct (fst cd); simpl in *; try discriminate.\n    find_if_inside; simpl in *; try discriminate.\n    injections.\n    pose proof (H4 _ (eq_refl _)).\n    eapply lt_le_trans; eauto.\n    rewrite !pointerT2Nat_Nat2pointerT in *;\n      rewrite !wtl_div in *.\n    rewrite wordToNat_natToWord_idempotent.\n    apply NPeano.Nat.div_le_mono; omega.\n    apply Nomega.Nlt_in.\n    rewrite Nnat.Nat2N.id, Npow2_nat; auto.\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    + eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      rewrite wordToNat_natToWord_idempotent.\n      rewrite mult_pow2_8; simpl; omega.\n      apply Nomega.Nlt_in.\n      rewrite Nnat.Nat2N.id, Npow2_nat; auto.\n    + eapply (mult_lt_compat_l' _ _ 8); try omega.\n      eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      rewrite mult_pow2_8; simpl; omega.\n    + eapply (mult_lt_compat_l' _ _ 8); try omega.\n      eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      rewrite mult_pow2_8; simpl; omega.\n    + eapply (mult_lt_compat_l' _ _ 8); try omega.\n      eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      rewrite mult_pow2_8; simpl; omega.\n  Qed.\n\n  Lemma cacheIndependent_add_2\n    : forall cd p (b : nat) domain,\n      GoodCache cd\n      -> getD (addD cd b) p = Some domain\n      -> forall pre label post : string,\n          domain = (pre ++ label ++ post)%string ->\n          ValidLabel label -> (String.length label <= 63)%nat.\n  Proof.\n    unfold GoodCache; intros.\n    rewrite IndependentCaches in *; eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_3\n    : forall cd p (b : nat) domain,\n      GoodCache cd\n      -> getD (addD cd b) p = Some domain\n      -> ValidDomainName domain.\n  Proof.\n    unfold GoodCache; intros.\n    rewrite IndependentCaches in *; eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_4\n    : forall cd p (b : nat) domain,\n      GoodCache cd\n      -> getD (addD cd b) p = Some domain\n      -> gt (String.length domain) 0.\n  Proof.\n    unfold GoodCache; intros.\n    rewrite IndependentCaches in *; eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_5\n    : forall cd p domain,\n      GoodCache cd\n      -> getD cd p = Some domain\n      -> ValidDomainName domain.\n  Proof.\n    unfold GoodCache; intros.\n    eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_6\n    : forall cd p domain,\n      GoodCache cd\n      -> getD cd p = Some domain\n      -> gt (String.length domain) 0.\n  Proof.\n    unfold GoodCache; intros.\n    eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_7\n    : forall cd p domain,\n      GoodCache cd\n      -> getD cd p = Some domain\n      -> forall pre label post : string,\n          domain = (pre ++ label ++ post)%string ->\n          ValidLabel label -> (String.length label <= 63)%nat.\n  Proof.\n    unfold GoodCache; intros.\n    eapply H; eauto.\n  Qed.\n\n  Lemma ptr_eq_dec :\n    forall (p p' : pointerT),\n      {p = p'} + {p <> p'}.\n  Proof.\n    decide equality.\n    apply weq.\n    destruct a; destruct s; simpl in *.\n    destruct (weq x x0); subst.\n    left; apply ptr_eq; reflexivity.\n    right; unfold not; intros; apply n.\n    congruence.\n  Qed.\n\n  Lemma cacheIndependent_add_8\n    : forall cd p p0 domain domain',\n      GoodCache cd\n      -> ValidDomainName domain' /\\ (String.length domain' > 0)%nat\n      -> getD (addD_G cd (domain', p0)) p = Some domain\n      -> forall pre label post : string,\n          domain = (pre ++ label ++ post)%string ->\n          ValidLabel label -> (String.length label <= 63)%nat.\n  Proof.\n    unfold GoodCache; simpl; intros.\n    destruct (pointerT_eq_dec p p0); subst.\n    - injections; intuition.\n      eapply H1; eauto.\n    - eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_9\n    : forall cd p p0 domain domain',\n      GoodCache cd\n      -> ValidDomainName domain' /\\ (String.length domain' > 0)%nat\n      -> getD (addD_G cd (domain', p0)) p = Some domain\n      -> ValidDomainName domain.\n  Proof.\n    unfold GoodCache; simpl; intros.\n    destruct (pointerT_eq_dec p p0); subst.\n    - injections; intuition.\n    - eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_10\n    : forall cd p p0 domain domain',\n      GoodCache cd\n      -> ValidDomainName domain' /\\ (String.length domain' > 0)%nat\n      -> getD (addD_G cd (domain', p0)) p = Some domain\n      -> gt (String.length domain) 0.\n  Proof.\n    unfold GoodCache; simpl; intros.\n    destruct (pointerT_eq_dec p p0); subst.\n    - injections; intuition.\n    - eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_11\n    : forall (b : nat)\n             (cd : CacheDecode)\n             (domain : string)\n             (p : pointerT),\n      GoodCache cd\n      -> getD (addD cd b) p = Some domain ->\n      forall p' : pointerT, peekD (addD cd b) = Some p' -> lt (pointerT2Nat p) (pointerT2Nat p').\n  Proof.\n    intros.\n    eapply (cacheIndependent_add b) in H.\n    eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_12\n      : forall (p : pointerT) (cd : CacheDecode) (domain : string),\n        GoodCache cd ->\n        getD cd p = Some domain\n        -> forall p' : pointerT,\n            peekD cd = Some p'\n            -> lt (pointerT2Nat p) (pointerT2Nat p').\n    Proof.\n      unfold GoodCache; simpl; intros; intuition eauto.\n      eapply H; eauto.\n    Qed.\n\n    Lemma cacheIndependent_add_13\n      : forall  (env : CacheDecode)\n                (p : pointerT)\n                (domain : string)\n                (H : GoodCache env)\n                (H0 : ValidDomainName domain /\\ (String.length domain > 0)%nat)\n                (H1 : getD env p = None)\n                (H2 : forall p' : pointerT, peekD env = Some p' -> lt (pointerT2Nat p) (pointerT2Nat p'))\n                (domain0 : string)\n                (p0 : pointerT)\n                (H3 : getD (addD_G env (domain, p)) p0 = Some domain0)\n                (p' : pointerT),\n        peekD (addD_G env (domain, p)) = Some p'\n        -> lt (pointerT2Nat p0) (pointerT2Nat p').\n    Proof.\n      simpl; intros.\n      destruct (fst env) eqn: ?; simpl in *; try discriminate.\n      find_if_inside; subst.\n      - injections.\n        apply (H2 _ (eq_refl _)).\n      - injections.\n        pose proof (H2 _ (eq_refl _)).\n        unfold GoodCache in *; intuition.\n        eapply H; simpl.\n        eassumption.\n        eassumption.\n        rewrite Heqo; simpl; reflexivity.\n    Qed.\n\n    Ltac solve_GoodCache_inv foo :=\n    lazymatch goal with\n      |- cache_inv_Property ?Z _ =>\n      unify Z GoodCache;\n      unfold cache_inv_Property; repeat split;\n      eauto using cacheIndependent_add, cacheIndependent_add_2, cacheIndependent_add_4, cacheIndependent_add_6, cacheIndependent_add_7, cacheIndependent_add_8, cacheIndependent_add_10, cacheIndependent_add_11, cacheIndependent_add_12, cacheIndependent_add_13;\n      try match goal with\n            H : _ = _ |- _ =>\n            try solve [ eapply cacheIndependent_add_3 in H; intuition eauto ];\n            try solve [ eapply cacheIndependent_add_9 in H; intuition eauto ];\n            try solve [ eapply cacheIndependent_add_5 in H; intuition eauto ]\n          end;\n      try solve [instantiate (1 := fun _ => True); exact I]\n    end.\n\n  Definition monoid : Monoid ByteString := ByteStringQueueMonoid.\n\n  Opaque pow2. (* Don't want to be evaluating this. *)\n\n  Lemma validDomainName_proj1_OK\n    : forall domain,\n      ValidDomainName domain\n      -> decides true\n                 (forall pre label post : string,\n                     domain = (pre ++ label ++ post)%string ->\n                     ValidLabel label -> (String.length label <= 63)%nat).\n  Proof.\n    simpl; intros; eapply H; eauto.\n  Qed.\n\n  Lemma validDomainName_proj2_OK\n    : forall domain,\n      ValidDomainName domain\n      ->\n      decides true\n              (forall pre post : string,\n                  domain = (pre ++ \".\" ++ post)%string ->\n                  post <> \"\"%string /\\\n                  pre <> \"\"%string /\\\n                  ~ (exists s' : string, post = String \".\" s') /\\\n                  ~ (exists s' : string, pre = (s' ++ \".\")%string)).\n  Proof.\n    simpl; intros; apply H; eauto.\n  Qed.\n\n  Hint Resolve validDomainName_proj1_OK : decide_data_invariant_db.\n  Hint Resolve validDomainName_proj2_OK : decide_data_invariant_db.\n  Hint Resolve FixedList_predicate_rest_True : data_inv_hints.\n\n  Definition resourceRecord_OK (rr : resourceRecord) :=\n    ith\n      (icons (B := fun T => T -> Prop) (fun a : DomainName => ValidDomainName a)\n      (icons (B := fun T => T -> Prop) (fun _ : Memory.W => True)\n             (icons (B := fun T => T -> Prop) (fun a : DomainName => ValidDomainName a)\n                           (icons (B := fun T => T -> Prop) (fun a : SOA_RDATA =>\n                                                               (True /\\ ValidDomainName a!\"contact_email\") /\\ ValidDomainName a!\"sourcehost\")\n                                  (icons (B := fun T => T -> Prop) (fun a : WKS_RDATA => True /\\ (lt (|a!\"Bit-Map\" |)  (pow2 16)))\n                                         (icons (B := fun T => T -> Prop) (fun a : DomainName => ValidDomainName a)\n                                                (icons (B := fun T => T -> Prop) (fun a : HINFO_RDATA =>\n                                                                                    (True /\\ True /\\ (lt (String.length a!\"OS\") (pow2 8))) /\\\n                                                                                    True /\\ (lt (String.length a!\"CPU\") (pow2 8)))\n                                                       (icons (B := fun T => T -> Prop) (fun a : MINFO_RDATA =>\n                                                                                           (True /\\ ValidDomainName a!\"eMailBx\") /\\\n                                                                                           ValidDomainName a!\"rMailBx\")\n                                                              (icons (B := fun T => T -> Prop) (fun a : MX_RDATA => True /\\ ValidDomainName a!\"Exchange\")\n                                                                     (icons (B := fun T => T -> Prop) (fun a : string =>\n                                                                                                         True /\\ True /\\ (lt (String.length a) (pow2 8))) inil))))))))))\n      (SumType_index\n         (DomainName\n            :: (Memory.W : Type)\n            :: DomainName\n            :: SOA_RDATA\n            :: WKS_RDATA\n            :: DomainName :: HINFO_RDATA :: MINFO_RDATA :: MX_RDATA :: [string : Type])\n         rr!sRDATA)\n      (SumType_proj\n         (DomainName\n            :: (Memory.W : Type)\n            :: DomainName\n            :: SOA_RDATA\n            :: WKS_RDATA\n            :: DomainName :: HINFO_RDATA :: MINFO_RDATA :: MX_RDATA :: [string : Type])\n         rr!sRDATA)\n    /\\ ValidDomainName rr!sNAME.\n\n  Lemma resourceRecordOK_1\n    : forall data : resourceRecord,\n      resourceRecord_OK data -> (fun domain : string => ValidDomainName domain) data!sNAME.\n  Proof.\n    unfold resourceRecord_OK; intuition eauto.\n  Qed.\n  Hint Resolve resourceRecordOK_1 : data_inv_hints.\n\n  Lemma resourceRecordOK_3\n    : forall rr : resourceRecord,\n      resourceRecord_OK rr ->\n      ith\n        (icons (B := fun T => T -> Prop) (fun a : DomainName => ValidDomainName a)\n               (icons (B := fun T => T -> Prop) (fun _ : Memory.W => True)\n                      (icons (B := fun T => T -> Prop) (fun a : DomainName => ValidDomainName a)\n                             (icons (B := fun T => T -> Prop) (fun a : SOA_RDATA =>\n                                                                 (True /\\ ValidDomainName a!\"contact_email\") /\\ ValidDomainName a!\"sourcehost\")\n                                    (icons (B := fun T => T -> Prop) (fun a : WKS_RDATA => True /\\ (lt (|a!\"Bit-Map\" |)  (pow2 16)))\n                                           (icons (B := fun T => T -> Prop) (fun a : DomainName => ValidDomainName a)\n                                                  (icons (B := fun T => T -> Prop) (fun a : HINFO_RDATA =>\n                                                                                      (True /\\ True /\\ (lt (String.length a!\"OS\") (pow2 8))) /\\\n                                                                                      True /\\ (lt (String.length a!\"CPU\") (pow2 8)))\n                                                         (icons (B := fun T => T -> Prop) (fun a : MINFO_RDATA =>\n                                                                                             (True /\\ ValidDomainName a!\"eMailBx\") /\\\n                                                                                             ValidDomainName a!\"rMailBx\")\n                                                                (icons (B := fun T => T -> Prop) (fun a : MX_RDATA => True /\\ ValidDomainName a!\"Exchange\")\n                                                                       (icons (B := fun T => T -> Prop) (fun a : string =>\n                                                                                                           True /\\ True /\\ (lt (String.length a) (pow2 8))) inil))))))))))\n        (SumType_index ResourceRecordTypeTypes rr!sRDATA)\n        (SumType_proj ResourceRecordTypeTypes rr!sRDATA).\n    intros ? H; apply H.\n  Qed.\n  Hint Resolve resourceRecordOK_3 : data_inv_hints.\n\n  Lemma length_app_3 {A}\n    : forall n1 n2 n3 (l1 l2 l3 : list A),\n      length l1 = n1\n      -> length l2 = n2\n      -> length l3 = n3\n      -> length (l1 ++ l2 ++ l3) = n1 + n2 + n3.\n  Proof.\n    intros; rewrite !app_length; subst; omega.\n  Qed.\n  Hint Resolve length_app_3 : data_inv_hints .\n\n  Definition DNS_Packet_OK (data : packet) :=\n    lt (|data!\"answers\" |) (pow2 16)\n    /\\ lt (|data!\"authority\" |) (pow2 16)\n    /\\ lt (|data!\"additional\" |) (pow2 16)\n    /\\ ValidDomainName (data!\"question\")!\"qname\"\n    /\\ forall (rr : resourceRecord),\n        In rr (data!\"answers\" ++ data!\"additional\" ++ data!\"authority\")\n        -> resourceRecord_OK rr.\n\n  Ltac decompose_parsed_data :=\n    repeat match goal with\n           | H : (?x ++ ?y ++ ?z)%list = _ |- _ =>\n             eapply firstn_skipn_self in H; try eassumption;\n             destruct H as [? [? ?] ]\n           | H : WS _ WO = _ |- _ =>\n             apply (f_equal (@whd 0)) in H;\n             simpl in H; rewrite H in *; clear H\n           | H : length _ = _ |- _ => clear H\n           end;\n    subst.\n\n  Lemma decides_resourceRecord_OK\n    : forall l n m o,\n      length l = n + m + o\n      -> (forall x : resourceRecord, In x l -> resourceRecord_OK x)\n      -> decides true\n                 (forall rr : resourceRecord,\n                     In rr\n                        (firstn n l ++\n                                firstn m (skipn n l) ++ firstn o (skipn (n + m) l)) ->\n                     resourceRecord_OK rr).\n  Proof.\n    simpl; intros.\n    rewrite firstn_skipn_self' in H1; eauto.\n  Qed.\n\n  Hint Resolve decides_resourceRecord_OK : decide_data_invariant_db .\n\n  (* Resource Record <character-string>s are a byte, *)\n  (* followed by that many characters. *)\n  Definition format_characterString_Spec (s : string) :=\n    format_nat 8 (String.length s)\n                    ThenC format_string s\n                    DoneC.\n\n  Definition format_question_Spec (q : question) :=\n    format_DomainName q!\"qname\"\n                           ThenC format_enum QType_Ws q!\"qtype\"\n                           ThenC format_enum QClass_Ws q!\"qclass\"\n                           DoneC.\n\n\n  Definition format_TXT_Spec (s : string) :=\n    format_unused_word 16 (* Unusued RDLENGTH Field *)\n                            ThenC format_characterString_Spec s\n                            DoneC.\n\n  Definition format_SOA_RDATA_Spec (soa : SOA_RDATA) :=\n    format_unused_word 16 (* Unusued RDLENGTH Field *)\n                            ThenC format_DomainName soa!\"sourcehost\"\n                            ThenC format_DomainName soa!\"contact_email\"\n                            ThenC format_word soa!\"serial\"\n                            ThenC format_word soa!\"refresh\"\n                            ThenC format_word soa!\"retry\"\n                            ThenC format_word soa!\"expire\"\n                            ThenC format_word soa!\"minTTL\"\n                            DoneC.\n\n  Definition format_WKS_RDATA_Spec (wks : WKS_RDATA) :=\n    format_nat 16 (length (wks!\"Bit-Map\"))\n                    ThenC format_word wks!\"Address\"\n                    ThenC format_word wks!\"Protocol\"\n                    ThenC (format_list format_word wks!\"Bit-Map\")\n                    DoneC.\n\n  Definition format_HINFO_RDATA_Spec (hinfo : HINFO_RDATA) :=\n    format_unused_word 16 (* Unusued RDLENGTH Field *)\n                            ThenC format_characterString_Spec hinfo!\"CPU\"\n                            ThenC format_characterString_Spec hinfo!\"OS\"\n                            DoneC.\n\n  Definition format_MX_RDATA_Spec (mx : MX_RDATA) :=\n    format_unused_word 16 (* Unusued RDLENGTH Field *)\n                            ThenC format_word mx!\"Preference\"\n                            ThenC format_DomainName mx!\"Exchange\"\n                            DoneC.\n\n  Definition format_MINFO_RDATA_Spec (minfo : MINFO_RDATA) :=\n    format_unused_word 16 (* Unusued RDLENGTH Field *)\n                            ThenC format_DomainName minfo!\"rMailBx\"\n                            ThenC format_DomainName minfo!\"eMailBx\"\n                            DoneC.\n\n  Definition format_A_Spec (a : Memory.W) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_word a\n                            DoneC.\n\n  Definition format_NS_Spec (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_CNAME_Spec (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_PTR_Spec (domain : DomainName) :=\n    format_unused_word 16 (* Unused RDLENGTH Field *)\n                            ThenC format_DomainName domain\n                            DoneC.\n\n  Definition format_rdata_Spec :=\n    format_SumType ResourceRecordTypeTypes\n                        (icons (format_CNAME_Spec)  (* CNAME; canonical name for an alias \t[RFC1035] *)\n                        (icons format_A_Spec (* A; host address \t[RFC1035] *)\n                        (icons (format_NS_Spec) (* NS; authoritative name server \t[RFC1035] *)\n                        (icons format_SOA_RDATA_Spec  (* SOA rks the start of a zone of authority \t[RFC1035] *)\n                        (icons format_WKS_RDATA_Spec (* WKS  well known service description \t[RFC1035] *)\n                        (icons (format_PTR_Spec) (* PTR domain name pointer \t[RFC1035] *)\n                        (icons format_HINFO_RDATA_Spec (* HINFO host information \t[RFC1035] *)\n                        (icons (format_MINFO_RDATA_Spec) (* MINFO mailbox or mail list information \t[RFC1035] *)\n                        (icons format_MX_RDATA_Spec  (* MX  mail exchange \t[RFC1035] *)\n                        (icons format_TXT_Spec inil)))))))))). (*TXT text strings \t[RFC1035] *)\n\n  Definition format_resource_Spec(r : resourceRecord) :=\n    format_DomainName r!sNAME\n                           ThenC format_enum RRecordType_Ws (RDataTypeToRRecordType r!sRDATA)\n                           ThenC format_enum RRecordClass_Ws r!sCLASS\n                           ThenC format_word r!sTTL\n                           ThenC format_rdata_Spec r!sRDATA\n                           DoneC.\n\n  Definition format_packet_Spec (p : packet) :=\n    format_word p!\"id\"\n                     ThenC format_word (WS p!\"QR\" WO)\n                     ThenC format_enum Opcode_Ws p!\"Opcode\"\n                     ThenC format_word (WS p!\"AA\" WO)\n                     ThenC format_word (WS p!\"TC\" WO)\n                     ThenC format_word (WS p!\"RD\" WO)\n                     ThenC format_word (WS p!\"RA\" WO)\n                     ThenC format_word (WS false (WS false (WS false WO))) (* 3 bits reserved for future use *)\n                     ThenC format_enum RCODE_Ws p!\"RCODE\"\n                     ThenC format_nat 16 1 (* length of question field *)\n                     ThenC format_nat 16 (|p!\"answers\"|)\n                     ThenC format_nat 16 (|p!\"authority\"|)\n                     ThenC format_nat 16 (|p!\"additional\"|)\n                     ThenC format_question_Spec p!\"question\"\n                     ThenC (format_list format_resource_Spec (p!\"answers\" ++ p!\"additional\" ++ p!\"authority\"))\n                     DoneC.\n\n  Ltac decode_DNS_rules g :=\n    (* Processes the goal by either: *)\n    lazymatch goal with\n    | |- appcontext[CorrectDecoder _ _ _ _ format_DomainName _ _ ] =>\n      eapply (DomainName_decode_correct\n                IndependentCaches IndependentCaches' IndependentCaches'''\n                getDistinct getDistinct' addPeekSome\n                boundPeekSome addPeekNone addPeekNone'\n                addZeroPeek addPeekESome boundPeekESome\n                addPeekENone addPeekENone' addZeroPeekE)\n    | |- appcontext [CorrectDecoder _ _ _ _ (format_list format_resource_Spec) _ _] =>\n      intros; apply FixList_decode_correct with (A_predicate := resourceRecord_OK)\n    end.\n\n  Definition packet_decoder\n    : CorrectDecoderFor DNS_Packet_OK format_packet_Spec.\n  Proof.\n    synthesize_decoder_ext monoid\n                           decode_DNS_rules\n                           decompose_parsed_data\n                           solve_GoodCache_inv.\n  Defined.\n\n  Definition packetDecoderImpl := Eval simpl in (projT1 packet_decoder).\n\nEnd DnsPacket.\n\nPrint packetDecoderImpl.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Narcissus/Examples/DNS/DnsOpt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23390872119124662}}
{"text": "From compcert Require Import Maps AST Values Memory Globalenvs Ctypes.\nFrom compcert Require Coqlib Clight Clightdefs.\n\nRequire Import String List ZArith Lia.\n\nRequire Import sflib.\nRequire Import StdlibExt IntegersExt.\nRequire Import IPModel IntByteModel.\n\nRequire Import NWSysModel.\nRequire Import RTSysEnv.\nRequire Import MWITree.\n\nRequire Import VerifProgBase.\nRequire Import config_prm main_prm SystemProgs.\n\nLocal Open Scope Z.\nLocal Opaque Z.of_nat Z.to_nat.\nArguments Z.add: simpl nomatch.\n\nSection INIT_DATA_LEMMAS.\n  Context `{SystemEnv}.\n\n  Variable p: Clight.program.\n  Let ge := Genv.globalenv p.\n\n  Variable m: Mem.mem.\n  Hypothesis INIT_MEM: Genv.init_mem p = Some m.\n\n  Section TASK_ID.\n    (* App is responsible to define TASK_ID  *)\n\n    Variable tid: nat.\n    Hypothesis RANGE_TID: (Z.of_nat tid <= Byte.max_signed)%Z.\n\n    Hypothesis DEFMAP: (prog_defmap p) ! main_prm._TASK_ID =\n                       Some (Gvar (v_TASK_ID_p (Z.of_nat tid))).\n\n    Lemma _init_mem_tid\n      : exists b_tid,\n        Genv.find_symbol ge main_prm._TASK_ID = Some b_tid /\\\n        (b_tid < Genv.genv_next ge)%positive /\\\n        Mem.load Mint8signed m b_tid 0%Z =\n        Some (Vint (IntNat.of_nat tid)).\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      esplits; eauto.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      hexploit LOAD_STORE.\n      { ss. }\n      clear LOAD_STORE. clear - RANGE_TID.\n      intro LOAD_STORE. ss. des.\n      rewrite Mem.load_int8_signed_unsigned.\n      rewrite LOAD_STORE. ss.\n\n      repeat f_equal.\n      rewrite Int.sign_ext_zero_ext by ss.\n\n      apply sign_ext_byte_range.\n      r. split; ss.\n      etransitivity.\n      - instantiate (1:= 0%Z). ss.\n      - nia.\n    Qed.\n  End TASK_ID.\n\n  (** ** pals_period *)\n\n  Section PALS_PERIOD.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._PALS_PERIOD =\n      Some (Gvar (config_prm.v_PALS_PERIOD (Z.of_nat period))).\n\n    Lemma _init_mem_pals_period\n      : exists b_pprd,\n        Genv.find_symbol ge main_prm._PALS_PERIOD = Some b_pprd /\\\n        (b_pprd < Genv.genv_next ge)%positive /\\\n        Mem.load Mint64 m b_pprd 0%Z =\n        Some (Vlong (IntNat.of_nat64 period)).\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      esplits; eauto.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      hexploit LOAD_STORE.\n      { ss. }\n      clear LOAD_STORE.\n      intro LOAD_STORE. ss. des.\n      rewrite LOAD_STORE. ss.\n    Qed.\n  End PALS_PERIOD.\n\n  Section MAX_CSKEW.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._MAX_CSKEW =\n      Some (Gvar (config_prm.v_MAX_CSKEW (Z.of_nat max_clock_skew))).\n\n    Lemma _init_mem_max_cskew\n      : exists b_sk,\n        Genv.find_symbol ge main_prm._MAX_CSKEW = Some b_sk /\\\n        (b_sk < Genv.genv_next ge)%positive /\\\n        Mem.load Mint64 m b_sk 0%Z =\n        Some (Vlong (IntNat.of_nat64 max_clock_skew)).\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      esplits; eauto.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      hexploit LOAD_STORE.\n      { ss. }\n      clear LOAD_STORE.\n      intro LOAD_STORE. ss. des.\n      rewrite LOAD_STORE. ss.\n    Qed.\n  End MAX_CSKEW.\n\n\n  Section MAX_NWDELAY.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._MAX_NWDELAY =\n      Some (Gvar (config_prm.v_MAX_NWDELAY (Z.of_nat max_nw_delay))).\n\n    Lemma _init_mem_max_nwdelay\n      : exists b_nd,\n        Genv.find_symbol ge main_prm._MAX_NWDELAY = Some b_nd /\\\n        (b_nd < Genv.genv_next ge)%positive /\\\n        Mem.load Mint64 m b_nd 0%Z =\n        Some (Vlong (IntNat.of_nat64 max_nw_delay)).\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      esplits; eauto.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      hexploit LOAD_STORE.\n      { ss. }\n      clear LOAD_STORE.\n      intro LOAD_STORE. ss. des.\n      rewrite LOAD_STORE. ss.\n    Qed.\n  End MAX_NWDELAY.\n\n  Section NUM_TASKS.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._NUM_TASKS =\n      Some (Gvar (config_prm.v_NUM_TASKS (Z.of_nat num_tasks))).\n\n    Lemma _init_mem_num_tasks\n      : exists b_nt,\n        Genv.find_symbol ge main_prm._NUM_TASKS = Some b_nt /\\\n        (b_nt < Genv.genv_next ge)%positive /\\\n        Mem.load Mint32 m b_nt 0%Z =\n        Some (Vint (IntNat.of_nat num_tasks)).\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      esplits; eauto.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      hexploit LOAD_STORE.\n      { ss. }\n      clear LOAD_STORE.\n      intro LOAD_STORE. ss. des.\n      rewrite LOAD_STORE. ss.\n    Qed.\n  End NUM_TASKS.\n\n  Section NUM_MCASTS.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._NUM_MCASTS =\n      Some (Gvar (config_prm.v_NUM_MCASTS (Z.of_nat num_mcasts))).\n\n    Lemma _init_mem_num_mcasts\n      : exists b_nmc,\n        Genv.find_symbol ge main_prm._NUM_MCASTS = Some b_nmc /\\\n        (b_nmc < Genv.genv_next ge)%positive /\\\n        Mem.load Mint32 m b_nmc 0%Z =\n        Some (Vint (IntNat.of_nat num_mcasts)).\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      esplits; eauto.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      hexploit LOAD_STORE.\n      { ss. }\n      clear LOAD_STORE.\n      intro LOAD_STORE. ss. des.\n      rewrite LOAD_STORE. ss.\n    Qed.\n  End NUM_MCASTS.\n\n  Section MSG_SIZE.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._MSG_SIZE =\n      Some (Gvar (config_prm.v_MSG_SIZE (Z.of_nat msg_size))).\n\n    Lemma _init_mem_msg_size\n      : exists b_msz,\n        Genv.find_symbol ge main_prm._MSG_SIZE = Some b_msz /\\\n        (b_msz < Genv.genv_next ge)%positive /\\\n        Mem.load Mint32 m b_msz 0%Z =\n        Some (Vint (IntNat.of_nat msg_size)).\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      esplits; eauto.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      hexploit LOAD_STORE.\n      { ss. }\n      clear LOAD_STORE.\n      intro LOAD_STORE. ss. des.\n      rewrite LOAD_STORE. ss.\n    Qed.\n  End MSG_SIZE.\n\n\n  Section PORT.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._PORT =\n      Some (Gvar (config_prm.v_PORT (Z.of_nat port))).\n\n    Lemma _init_mem_port\n      : exists b_pn,\n        Genv.find_symbol ge main_prm._PORT = Some b_pn /\\\n        (b_pn < Genv.genv_next ge)%positive /\\\n        Mem.load Mint32 m b_pn 0%Z =\n        Some (Vint (IntNat.of_nat port)).\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      esplits; eauto.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      hexploit LOAD_STORE.\n      { ss. }\n      clear LOAD_STORE.\n      intro LOAD_STORE. ss. des.\n      rewrite LOAD_STORE. ss.\n    Qed.\n  End PORT.\n\n  Section IP_ADDR.\n    Let v_IP_ADDR_i: globvar type :=\n      config_prm.v_IP_ADDR (Z.of_nat max_num_tasks)\n                           (Z.of_nat max_num_mcasts)\n                           dest_ips_brep.\n\n    Hypothesis DEFMAP: (prog_defmap p) ! main_prm._IP_ADDR =\n                       Some (Gvar v_IP_ADDR_i).\n\n    Lemma _init_mem_ip_addr\n      : exists b_ip_addr,\n        Genv.find_symbol ge main_prm._IP_ADDR = Some b_ip_addr /\\\n        (b_ip_addr < Genv.genv_next ge)%positive /\\\n        iForall (fun n ip_bs =>\n                   Mem.loadbytes\n                     m b_ip_addr (Z.of_nat (n * 16))\n                     (Zlength ip_bs + 1) =\n                   Some (inj_bytes (snoc ip_bs Byte.zero)))\n                0 (task_ips_brep ++ (map fst mcasts))\n    .\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      eexists. split; eauto.\n      split.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      hexploit LOADBYTES.\n      { eauto. }\n\n      clear - ge.\n      replace (init_data_list_size (gvar_init v_IP_ADDR_i))\n        with (Z.of_nat (max_num_tasks + max_num_mcasts) * 16)%Z.\n      2: { ss.\n           rewrite init_data_list_size_app. ss.\n           rewrite flat_map_concat_map.\n           erewrite init_data_list_size_concat.\n           2: { i. rewrite in_map_iff in IN. des.\n                unfold ip_init_data in IN. subst.\n                ss. }\n           rewrite Zlength_correct.\n           rewrite map_length.\n\n           assert (length dest_ips_brep <= max_num_tasks + max_num_mcasts)%nat.\n           { pose proof num_tasks_bound as NT.\n             pose proof num_mcasts_bound as NMC.\n             pose proof task_ips_convert_brep as CONV_T.\n             pose proof mcast_ips_convert_brep as CONV_M.\n             apply Forall2_length in CONV_T.\n             apply Forall2_length in CONV_M.\n\n             unfold dest_ips_brep.\n             rewrite app_length. rewrite map_length.\n             unfold bytes in *. nia.\n           }\n           unfold bytes in *.\n           rewrite Zlength_correct. nia.\n      }\n\n      ss.\n      clear. intros LOADBYTES.\n\n      apply iForall_nth. i. r.\n      destruct (nth_error (task_ips_brep ++ map fst mcasts) n)\n        as [ip_bs| ] eqn: IP_BS.\n      2: { desf.\n           exfalso.\n           unfold bytes in *.\n           congruence. }\n      fold bytes in *.\n      rewrite IP_BS. ss.\n\n      assert (LEN_IP: Forall (fun ip_bs' => (length ip_bs' < 16)%nat) dest_ips_brep).\n      { apply Forall_forall.\n        unfold dest_ips_brep.\n        intros bs IN.\n        apply in_app_or in IN.\n        des.\n        - apply In_nth_error in IN. des.\n          pose proof task_ips_convert_brep as CONV.\n          eapply Forall2_nth1 in CONV; eauto. des.\n          hexploit IP.valid_ip_brep_spec; eauto. i. des.\n          unfold IP.max_byte_length in *. ss.\n        - apply In_nth_error in IN. des.\n          pose proof mcast_ips_convert_brep as CONV.\n          apply map_nth_error_iff in IN. des.\n          destruct a as [ip' mbrs]. ss. subst.\n\n          eapply Forall2_nth1 in CONV; eauto. des.\n          hexploit IP.valid_ip_brep_spec; eauto. i. des.\n          unfold IP.max_byte_length in *. ss.\n      }\n\n\n      eapply Mem_loadbytes_sublist with\n          (n1:= Z.of_nat (n * 16)) (n2:= (Zlength ip_bs + 1)%Z)\n        in LOADBYTES; cycle 1.\n      { nia. }\n      { rewrite Zlength_correct. nia. }\n      { match goal with\n        | |- (?lhs <= _)%Z => replace lhs with (Z.of_nat (n * 16 + S (length ip_bs)))\n        end.\n        2: { rewrite Zlength_correct. nia. }\n\n        assert (length ip_bs < 16)%nat.\n        { rewrite Forall_nth in LEN_IP.\n          specialize (LEN_IP n). r in LEN_IP.\n          unfold dest_ips_brep in LEN_IP.\n          unfold bytes in *.\n          rewrite IP_BS in LEN_IP. ss. }\n        assert (n < max_num_tasks + max_num_mcasts)%nat.\n        { apply nth_error_Some1' in IP_BS.\n          rewrite app_length in IP_BS.\n          rewrite map_length in IP_BS.\n\n          pose proof task_ips_convert_brep as CONV_T.\n          apply Forall2_length in CONV_T.\n          pose proof mcast_ips_convert_brep as CONV_M.\n          apply Forall2_length in CONV_M.\n\n          pose proof num_tasks_bound.\n          pose proof num_mcasts_bound.\n          unfold bytes in *. nia.\n        }\n        nia.\n      }\n      ss.\n      rewrite LOADBYTES.\n      f_equal.\n      clear LOADBYTES.\n      fold dest_ips_brep in IP_BS.\n\n      match goal with\n      | |- context[flat_map _ _ ++ ?x] => generalize x as rest\n      end.\n\n      revert n IP_BS LEN_IP.\n      generalize dest_ips_brep.\n      intro l.\n\n      induction l as [| h t IH]; i.\n      { exfalso.\n        destruct n; ss. }\n\n      destruct n as [| n'].\n      { simpl in IP_BS. clarify. ss.\n        assert (LEN_IP_BS: (length ip_bs < 16)%nat).\n        { inv LEN_IP. ss. }\n        clear LEN_IP IH.\n        rewrite Zlength_correct. ss.\n\n        match goal with\n        | |- context [firstn ?n] => replace n with (length ip_bs + 1)%nat by nia\n        end.\n\n        repeat rewrite Int.unsigned_repr by apply ubyte_in_uint_range.\n        repeat rewrite simpl_init_byte.\n        destruct ip_bs as [| h1 tl]; ss.\n        do 15 (destruct tl as [| ? tl]; ss; []).\n        exfalso. nia.\n      }\n      { simpl in IP_BS.\n        hexploit IH; eauto.\n        { inv LEN_IP. ss. }\n        intro FN.\n        rewrite flat_map_concat_map. ss.\n        replace (S n' * 16)%nat with (16 + n' * 16)%nat by ss.\n\n        repeat rewrite Int.unsigned_repr by apply ubyte_in_uint_range.\n        repeat rewrite simpl_init_byte. ss.\n        rewrite Nat2Z.id. ss.\n        rewrite <- flat_map_concat_map.\n        rewrite Nat2Z.id in FN.  eauto.\n      }\n    Qed.\n  End IP_ADDR.\n\n\n  Lemma load_store_init_data_mcmem\n        b ofs\n        mip_bs mbrs tid'\n        (VALID_TID: (tid' < num_tasks)%nat)\n        (MCMEM: Genv.load_store_init_data\n                  ge m b ofs (mcmem_init_data\n                                (Z.of_nat max_num_tasks)\n                                (group_memflags (mip_bs, mbrs))))\n    : Mem.load Mint8signed m b (ofs + Z.of_nat tid') =\n      Some (Vint (if existsb (Nat.eqb tid') mbrs\n                  then Int.one else Int.zero)).\n  Proof.\n    unfold group_memflags in MCMEM. ss.\n    unfold mcmem_init_data in *.\n    apply load_store_init_data_app in MCMEM. des.\n\n    clear MCMEM0.\n\n    assert (AUX: forall nt ofs' tid' i\n                   (TID: (tid' < nt)%nat)\n                   (MCMEM : Genv.load_store_init_data\n                              ge m b ofs'\n                              (map (fun b: bool =>\n                                      Init_int8 (Int.repr (if b then 1 else 0)))\n                                   (imap (fun n _ => existsb (Nat.eqb n) mbrs)\n                                         i (repeat tt nt))))\n             ,\n               Mem.load Mint8signed m b (ofs' + Z.of_nat tid') =\n               Some (Vint (if existsb (Nat.eqb (i + tid')) mbrs\n                           then Int.one else Int.zero))).\n    { clear.\n      intro nt.\n      induction nt as [| nt' IH]; i; ss.\n      { nia. }\n      destruct tid' as [| tid']; ss.\n      { des.\n        rewrite plus_0_r. rewrite Z.add_0_r.\n        rewrite Mem.load_int8_signed_unsigned.\n        rewrite MCMEM. ss.\n        desf. }\n      des.\n\n      hexploit (IH (ofs' + 1)%Z tid' (S i)).\n      { nia. }\n      { eauto. }\n      intro LOAD.\n\n      replace (Z.of_nat (S tid')) with (1 + Z.of_nat tid')%Z by nia.\n      replace (i + S tid')%nat with (S i + tid')%nat by nia.\n      rewrite Z.add_assoc. apply LOAD.\n    }\n    hexploit AUX; eauto.\n  Qed.\n\n\n  Lemma mcmem_init_data_list_size\n        ginfo\n    : init_data_list_size\n        (mcmem_init_data (Z.of_nat max_num_tasks)\n                         (group_memflags ginfo)) =\n      (Z.of_nat max_num_tasks).\n  Proof.\n    assert (LEN_GMFS: length (group_memflags ginfo) = num_tasks).\n    { unfold group_memflags.\n      rewrite imap_length.\n      apply repeat_length. }\n\n    unfold mcmem_init_data.\n    rewrite init_data_list_size_app.\n\n    match goal with\n    | |- (init_data_list_size (map ?f ?l) + _)%Z = _ =>\n      replace (init_data_list_size (map f l)) with (Zlength l)\n    end.\n    2: { clear.\n         induction (group_memflags ginfo) as [| h t IH]; ss.\n         rewrite Zlength_cons.\n         rewrite <- IH. nia. }\n\n    rewrite Zlength_correct.\n    rewrite LEN_GMFS.\n\n    assert (NT_BOUND: (num_tasks <= max_num_tasks)%nat).\n    { pose proof num_tasks_bound.\n      unfold num_tasks. ss. }\n\n    destruct (Z.ltb_spec (Z.of_nat num_tasks)\n                         (Z.of_nat max_num_tasks)) as [LT|GE].\n    - ss. nia.\n    - ss. nia.\n  Qed.\n\n\n  Lemma load_store_init_data_flatmap_mcmem\n        b ofs mcasts'\n        midx mip_bs mbrs tid'\n        (MCMEM: Genv.load_store_init_data\n                  ge m b ofs\n                  (flat_map (mcmem_init_data\n                               (Z.of_nat max_num_tasks))\n                            (map group_memflags mcasts')))\n        (MIDX: nth_error mcasts' midx = Some (mip_bs, mbrs))\n        (* (MAX_NUM_MEMBERS: (length mbrs <= num_tasks)%nat) *)\n        (TID': (tid' < num_tasks)%nat)\n    : Mem.load Mint8signed m b\n               (ofs + Z.of_nat ((max_num_tasks * midx + tid'))) =\n      Some (Vint (if existsb (Nat.eqb tid') mbrs\n                  then Int.one else Int.zero)).\n  Proof.\n    depgen ofs. revert midx MIDX.\n    induction mcasts' as [| h_mc t_mc IH]; i; ss.\n    { destruct midx; ss. }\n\n    destruct midx as [| midx]; ss.\n    { clarify.\n      apply load_store_init_data_app in MCMEM. des.\n      rewrite Nat.mul_0_r. ss.\n      eapply load_store_init_data_mcmem; eauto.\n    }\n    apply load_store_init_data_app in MCMEM. des.\n\n    rewrite mcmem_init_data_list_size in *.\n    hexploit IH; eauto. intro LOAD.\n    match goal with\n    | LOAD: Mem.load _ m b ?ofs1 = Some ?a |-\n      Mem.load _ m b ?ofs2 = Some ?a =>\n      replace ofs2 with ofs1 by nia\n    end.\n    congruence.\n  Qed.\n\n  Section MCAST_MEMBER.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._MCAST_MEMBER =\n      Some (Gvar (config_prm.v_MCAST_MEMBER\n                    (Z.of_nat max_num_tasks)\n                    (Z.of_nat max_num_mcasts)\n                    mcast_memflags)).\n\n    Lemma _init_mem_mcm\n      : exists b_mcm,\n        Genv.find_symbol ge main_prm._MCAST_MEMBER = Some b_mcm /\\\n        (b_mcm < Genv.genv_next ge)%positive /\\\n        (forall mid midx tid' mip_bs mbrs\n           (MCAST_ID: mid = (num_tasks + midx)%nat)\n           (MCASTS_MID: nth_error mcasts midx = Some (mip_bs, mbrs))\n           (RANGE_TID: (tid' < num_tasks)%nat),\n            Mem.load Mint8signed m b_mcm\n                     (Z.of_nat (max_num_tasks * midx + tid')) =\n            Some (Vint (if existsb (Nat.eqb tid') mbrs\n                        then Int.one else Int.zero)))\n    .\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      eexists.\n      split; eauto.\n      split.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n      ss.\n      hexploit LOAD_STORE.\n      { ss. }\n      clear LOAD_STORE. clear LOADBYTES.\n      intro LOAD_STORE.\n      apply load_store_init_data_app in LOAD_STORE. des.\n\n      i. hexploit load_store_init_data_flatmap_mcmem; eauto.\n    Qed.\n  End MCAST_MEMBER.\n\n\n  (* writable *)\n\n  Section SEND_BUF.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._send_buf =\n      Some (Gvar (main_prm.v_send_buf (Z.of_nat msg_size_k))).\n\n    Lemma _init_mem_send_buf\n      : exists b_sbuf,\n        Genv.find_symbol ge main_prm._send_buf = Some b_sbuf /\\\n        (b_sbuf < Genv.genv_next ge)%positive /\\\n        Mem.loadbytes m b_sbuf 0 8 = Some (inj_bytes (IntByte.to_bytes64 Int64.zero)) /\\\n        (* Mem.load Mint64 m b_sbuf 0 = Some (Vlong Int64.zero) /\\ *)\n        Mem.load Mint8signed m b_sbuf 8 = Some (Vint Int.zero) /\\\n        Mem.loadbytes m b_sbuf 9 (Z.of_nat msg_size) =\n        Some (inj_bytes (List.repeat Byte.zero msg_size)) /\\\n        Mem.range_perm m b_sbuf 0 (Z.of_nat pld_size) Cur Writable\n    .\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      eexists.\n      split; eauto.\n      split.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      hexploit LOADBYTES; ss.\n      clear LOADBYTES.\n\n      assert (STRT_SZ_EQ: msg_struct_sz (Z.of_nat msg_size_k) =\n                          Z.of_nat max_pld_size).\n      { unfold msg_struct_sz, max_pld_size.\n        unfold max_msg_size. nia. }\n      rewrite STRT_SZ_EQ in *.\n      rewrite Z.max_l in * by nia.\n      rewrite Z.add_0_r in *.\n      rewrite app_nil_r.\n      rewrite Nat2Z.id.\n      rewrite list_repeat_eq.\n\n      intro LOADBYTES.\n      assert (SIZE_DIV: exists rest,\n                 (max_pld_size = 8 + (1 + (msg_size + rest)))%nat).\n      { clear.\n        unfold max_pld_size.\n        exists (max_msg_size - msg_size)%nat.\n        unfold max_msg_size.\n        pose proof msg_size_bound. nia. }\n      des.\n      rewrite SIZE_DIV in LOADBYTES.\n\n      rewrite Nat2Z.inj_add in LOADBYTES.\n      eapply Mem_loadbytes_split' in LOADBYTES; cycle 1.\n      { nia. }\n      { nia. }\n\n      replace (Z.of_nat 8) with 8%Z in * by ss.\n      replace (Z.to_nat 8) with 8%nat in * by ss.\n\n      destruct LOADBYTES as [LOAD_TIME LOADBYTES].\n      split.\n      { erewrite LOAD_TIME. ss. }\n\n      rewrite Nat2Z.inj_add in LOADBYTES.\n      eapply Mem_loadbytes_split' in LOADBYTES; ss.\n      2: { nia. }\n\n      destruct LOADBYTES as [LOAD_TID LOADBYTES].\n      split.\n      { erewrite Mem.loadbytes_load; eauto; ss.\n        solve_divide. }\n\n      rewrite Nat2Z.inj_add in LOADBYTES.\n      replace (Z.of_nat 1) with 1%Z in * by ss.\n      replace (Z.to_nat 1) with 1%nat in * by ss.\n      eapply Mem_loadbytes_split' in LOADBYTES; cycle 1.\n      { nia. }\n      { nia. }\n      destruct LOADBYTES as [LOADBYTES LOADBYTES_REST].\n\n      split; ss.\n      { rewrite LOADBYTES. f_equal.\n        rewrite Nat2Z.id.\n        unfold inj_bytes.\n        rewrite map_repeat.\n        rewrite repeat_app.\n        rewrite firstn_app_exact.\n        2: { rewrite repeat_length. ss. }\n        ss.\n      }\n      clear - RANGE_PERM.\n\n      assert (pld_size <= max_pld_size)%nat.\n      { unfold max_pld_size, pld_size.\n        unfold max_msg_size.\n        pose proof msg_size_bound. nia. }\n\n      unfold v_send_buf in RANGE_PERM.\n      unfold Genv.perm_globvar in RANGE_PERM. ss.\n\n      ii. apply RANGE_PERM. nia.\n    Qed.\n  End SEND_BUF.\n\n\n\n  Lemma _init_Mem_msg_entries\n        b ofs\n        (LBS: Mem.loadbytes m b ofs inb_sz =\n              Some (repeat (Byte Byte.zero) inb_nsz))\n    : iForall (Mem_msg_entry m b ofs) 0\n              (repeat None num_tasks).\n  Proof.\n    apply iForall_nth. ss. i.\n    destruct (lt_ge_dec n num_tasks).\n    2: { rewrite repeat_nth_error_None; ss. }\n    rewrite repeat_nth_error_Some by ss.\n    ss.\n\n    erewrite Mem_loadbytes_sublist; eauto; cycle 1.\n    { nia. }\n    { nia. }\n    { hexploit (within_inb_nsz2 n mentry_ensz); eauto.\n      { apply range_mentry_ensz. }\n      unfold mentry_ensz. nia. }\n\n    f_equal.\n    rewrite Nat2Z.id.\n\n    pose proof num_tasks_bound' as NT_BOUND.\n    replace inb_nsz with (mentry_nsz * n +\n                          mentry_nsz * (max_num_tasks - n))%nat.\n    2: { unfold inb_nsz. nia. }\n\n    rewrite repeat_app.\n    rewrite skipn_app_exact.\n    2: { rewrite repeat_length. nia. }\n\n    destruct (max_num_tasks - n)%nat as [|n'] eqn: SUB.\n    { exfalso. nia. }\n\n    replace (mentry_nsz * S n')%nat with\n        (S (max_msg_size + mentry_nsz * n'))%nat.\n    2: { unfold mentry_nsz. nia. }\n    ss.\n  Qed.\n\n  (* assert (MENTRY_SZ_DIV: exists rest, *)\n  (*            (mentry_nsz = mentry_ensz + rest)%nat). *)\n  (* { exists (mentry_nsz - mentry_ensz)%nat. *)\n  (*   clear. *)\n  (*   pose proof range_mentry_ensz. nia. } *)\n\n  (*   des. rewrite MENTRY_SZ_DIV. *)\n\n  (*   rewrite <- Nat.add_assoc. *)\n  (*   rewrite repeat_app. *)\n  (*   rewrite firstn_app_exact. *)\n  (*   2: { rewrite repeat_length. ss. } *)\n\n  (*   unfold inj_bytes, mentry_to_bytes. ss. *)\n  (*   unfold mentry_ensz. rewrite plus_comm. ss. *)\n  (*   rewrite map_repeat. ss. *)\n  (* Qed. *)\n\n\n  Section MSTORE.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._mstore =\n      Some (Gvar (main_prm.v_mstore (Z.of_nat msg_size_k)\n                                    (Z.of_nat max_num_tasks))).\n\n    Lemma _init_mem_mstore\n      : exists b_mst,\n        Genv.find_symbol ge main_prm._mstore = Some b_mst /\\\n        (b_mst < Genv.genv_next ge)%positive /\\\n        Mem.load Mint32 m b_mst 0 = Some (Vint Int.zero) /\\\n        Mem.range_perm m b_mst 0 4 Cur Writable /\\\n        Mem_inbox m b_mst 4 (List.repeat None num_tasks) /\\\n        Mem_inbox m b_mst (4 + inb_sz) (List.repeat None num_tasks)\n    .\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      eexists.\n      split; eauto.\n      split.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      (* assert (INBOX_SZ_NNEG: 0 <= inb_sz). *)\n      (* { apply range_inb_sz_precise. } *)\n\n      hexploit LOADBYTES; ss.\n      rewrite <- inb_sz_eq.\n\n      clear LOADBYTES.\n      rewrite Z.max_l by nia.\n      rewrite app_nil_r.\n      rewrite list_repeat_eq.\n      rewrite Z2Nat.inj_add by nia.\n      rewrite Z.add_0_r in *.\n      (* rewrite <- Z2Nat.inj_add by nia. *)\n\n      intro LOADBYTES.\n      eapply Mem_loadbytes_split' in LOADBYTES; ss.\n      2: { nia. }\n\n      rewrite repeat_app in LOADBYTES.\n      rewrite firstn_app_exact in LOADBYTES.\n      2: { rewrite repeat_length. ss. }\n      rewrite skipn_app_exact in LOADBYTES.\n      2: { rewrite repeat_length. ss. }\n\n      change (Z.to_nat 4) with 4%nat in LOADBYTES.\n      destruct LOADBYTES as [LOAD_RCV LOADBYTES].\n\n      split.\n      { erewrite Mem.loadbytes_load; eauto; ss.\n        solve_divide. }\n      split.\n      { ii. apply RANGE_PERM.\n        rewrite <- inb_sz_eq.\n        rewrite Z.max_l by nia.\n        nia. }\n\n      rewrite <- Zplus_diag_eq_mult_2 in LOADBYTES.\n      eapply Mem_loadbytes_split' in LOADBYTES; try nia.\n      rewrite Z2Nat.inj_add in LOADBYTES by nia.\n      rewrite repeat_app in LOADBYTES.\n      rewrite firstn_app_exact in LOADBYTES.\n      2: { rewrite repeat_length. ss. }\n      rewrite skipn_app_exact in LOADBYTES.\n      2: { rewrite repeat_length. ss. }\n\n      rewrite Nat2Z.id in LOADBYTES by ss.\n      destruct LOADBYTES as [LOAD_INB1 LOAD_INB2].\n\n      split.\n      - clear LOAD_INB2.\n        r. splits; ss; cycle 1.\n        { (* unfold empty_msg_entry. *)\n          rewrite repeat_length. ss. }\n        { clear - RANGE_PERM.\n          ii. apply RANGE_PERM.\n          rewrite <- inb_sz_eq. nia. }\n        eapply _init_Mem_msg_entries; eauto.\n      - clear LOAD_INB1.\n        r. splits; ss; cycle 1.\n        { (* unfold empty_msg_entry. *)\n          rewrite repeat_length. ss. }\n        { clear - RANGE_PERM.\n          ii. apply RANGE_PERM.\n          rewrite <- inb_sz_eq. nia. }\n        eapply _init_Mem_msg_entries; eauto.\n    Qed.\n\n  End MSTORE.\n\n  Section SEND_HIST.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._send_hist =\n      Some (Gvar (main_prm.v_send_hist (Z.of_nat max_num_tasks))).\n\n    Lemma _init_mem_send_hist\n      : exists b_sh,\n        Genv.find_symbol ge main_prm._send_hist = Some b_sh /\\\n        (b_sh < Genv.genv_next ge)%positive /\\\n        Mem.loadbytes m b_sh 0 (Z.of_nat num_tasks) =\n        Some (map bool2memval (List.repeat false num_tasks)) /\\\n        Mem.range_perm m b_sh 0 (Z.of_nat num_tasks) Cur Writable\n    .\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      eexists.\n      split; eauto.\n      split.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n      ss.\n      assert (MAX_NT_DIV: exists rst, (max_num_tasks = num_tasks + rst)%nat).\n      { clear. pose proof num_tasks_bound'.\n        exists (max_num_tasks - num_tasks)%nat. nia. }\n      des.\n\n      split.\n      - hexploit LOADBYTES; eauto.\n        rewrite Z.max_l by nia.\n        rewrite Z.add_0_r.\n        rewrite MAX_NT_DIV.\n        rewrite Nat2Z.inj_add.\n        rewrite list_repeat_eq.\n        rewrite Z2Nat.inj_add by nia.\n        rewrite app_nil_r.\n        rewrite repeat_app.\n\n        intro LB1.\n        apply Mem_loadbytes_split' in LB1; try nia.\n        destruct LB1 as [LB LB_R].\n        rewrite Nat2Z.id in *.\n        rewrite firstn_app_exact in LB.\n        2: { rewrite repeat_length. ss. }\n\n        rewrite LB. f_equal.\n        rewrite map_repeat. ss.\n      - ii. apply RANGE_PERM.\n        rewrite Z.max_l by nia.\n        rewrite Z.add_0_r. nia.\n    Qed.\n\n  End SEND_HIST.\n\n  Section TXS.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._txs =\n      Some (Gvar (main_prm.v_txs)).\n\n    Lemma _init_mem_txs\n      : exists b_txs,\n        Genv.find_symbol ge main_prm._txs = Some b_txs /\\\n        (b_txs < Genv.genv_next ge)%positive /\\\n        Mem.load Mint32 m b_txs 0%Z = Some (Vint Int.zero) /\\\n        Mem.range_perm m b_txs 0%Z 4 Cur Writable.\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      eexists.\n      split; eauto.\n      split.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      hexploit LOAD_STORE.\n      { ss. }\n      clear LOAD_STORE.\n      intro LOAD_STORE. ss. des.\n      splits; eauto.\n      rr in LOAD_STORE.\n      rewrite LOAD_STORE; ss.\n      solve_divide.\n    Qed.\n  End TXS.\n\n  Section RXS.\n    Hypothesis DEFMAP:\n      (prog_defmap p) ! main_prm._rxs =\n      Some (Gvar (main_prm.v_rxs)).\n\n    Lemma _init_mem_rxs\n      : exists b_rxs,\n        Genv.find_symbol ge main_prm._rxs = Some b_rxs /\\\n        (b_rxs < Genv.genv_next ge)%positive /\\\n        Mem.load Mint32 m b_rxs 0%Z = Some (Vint Int.zero) /\\\n        Mem.range_perm m b_rxs 0%Z 4 Cur Writable.\n    Proof.\n      apply Genv.find_def_symbol in DEFMAP.\n      destruct DEFMAP as (b & FSYMB & FDEF).\n\n      eexists.\n      split; eauto.\n      split.\n      { eapply Genv.genv_symb_range. eauto. }\n\n      eapply Genv.init_mem_characterization_gen in FDEF; eauto.\n      destruct FDEF as (RANGE_PERM & PERM_ORDER &\n                        LOAD_STORE & LOADBYTES).\n\n      hexploit LOAD_STORE.\n      { ss. }\n      clear LOAD_STORE.\n      intro LOAD_STORE. ss. des.\n      splits; eauto.\n      rr in LOAD_STORE.\n      rewrite LOAD_STORE; ss.\n      solve_divide.\n    Qed.\n  End RXS.\n\nEnd INIT_DATA_LEMMAS.\n\n\nSection INIT_MEM_INVERSION.\n  Import Clight.\n  Context `{SystemEnv}.\n  (* Context `{CProgSysEvent}. *)\n  Variable cprog: Clight.program.\n  Variable m_i: mem.\n  Let ge := globalenv cprog.\n\n  Hypothesis INIT_MEM: Genv.init_mem cprog = Some m_i.\n  (* Variable gvars: list (ident * cglobvar). *)\n  Variable tid: nat.\n  Variable gfuns: list (ident * fundef).\n  Variable cenvs: list (ident * composite).\n  Hypothesis RANGE_TID: (tid < num_tasks)%nat.\n\n  Context `{genv_props ge (main_gvar_ilist tid) gfuns cenvs}.\n\n  (* (* init_mem_inversion *) *)\n  (* Let glob_init: Genv.globals_initialized ge ge m_i. *)\n  (* Proof. *)\n  (*   apply Genv.init_mem_characterization_gen; eauto. *)\n  (* Qed. *)\n\n  Lemma main_gvar_find_def\n        i gv b\n        (FSYMB: Genv.find_symbol ge i = Some b)\n        (IN: In (i, gv) (main_gvar_ilist tid))\n    : Genv.find_def ge b = Some (Gvar gv).\n  Proof.\n    hexploit (in_gvar_ilist i); eauto.\n    i. des. clarify.\n    apply Genv.find_var_info_iff; eauto.\n  Qed.\n\n  Lemma bytes_of_init_data_list_map\n        (ge': genv) l\n    : Genv.bytes_of_init_data_list ge' l =\n      concat (map (Genv.bytes_of_init_data ge') l).\n  Proof.\n    induction l as [| h t IH]; ss.\n    rewrite IH. ss.\n  Qed.\n\n  (* Lemma loadbytes_ip_aux *)\n  (*       (ge': genv) m (ip_bs: bytes) b ofs *)\n  (*       (LEN_BD: length ip_bs < 16) *)\n  (*       (LBS: Mem.loadbytes m b ofs 16 = *)\n  (*             Some (concat (map (Genv.bytes_of_init_data ge') *)\n  (*                               (ip_init_data ip_bs)))) *)\n  (*   : Mem.loadbytes m b ofs (Zlength ip_bs + 1)%Z = *)\n  (*     Some (inj_bytes (snoc ip_bs Byte.zero)). *)\n  (* Proof. *)\n  (*   ss. unfold encode_int in *. ss. *)\n  (*   repeat rewrite rev_if_be_single in *. ss. *)\n  (*   unfold app in LBS. *)\n  (*   repeat (rewrite Int.unsigned_repr in LBS *)\n  (*            by eapply ubyte_in_uint_range). *)\n  (*   repeat rewrite Byte.repr_unsigned in LBS. *)\n\n  (*   pose (k:= (16 - (Zlength ip_bs + 1))%Z). *)\n  (*   assert (k >= 0)%Z. *)\n  (*   { subst k. rewrite Zlength_correct. nia. } *)\n\n  (*   replace 16%Z with (Zlength ip_bs + 1 + k)%Z in LBS. *)\n  (*   2: { subst k. nia. } *)\n  (*   apply Mem.loadbytes_split in LBS; ss. *)\n  (*   2: { rewrite Zlength_correct. nia. } *)\n\n  (*   des. rewrite LBS. *)\n  (*   apply Mem.loadbytes_length in LBS. *)\n\n  (*   unfold snoc. unfold inj_bytes. *)\n  (*   rewrite map_app. *)\n  (*   f_equal. *)\n  (*   eapply (ip_bytes_aux ip_bs 16). *)\n  (*   { ss. rewrite LBS1. eauto. } *)\n  (*   { rewrite LBS. *)\n  (*     rewrite Zlength_correct. nia. } *)\n  (* Qed. *)\n\n  Lemma init_mem_consts: mem_consts ge m_i tid.\n  Proof.\n    (* r in glob_init. *)\n    econs.\n    - i. ss.\n      hexploit _init_mem_tid; eauto.\n      { instantiate (1:= tid).\n        pose proof range_num_tasks.\n        range_stac. }\n      { apply Genv.find_def_symbol.\n        esplits; eauto.\n        eapply main_gvar_find_def; eauto.\n        sIn. }\n      i. des. fold fundef in *. clarify.\n    - i. ss.\n      hexploit _init_mem_pals_period; eauto.\n      { apply Genv.find_def_symbol.\n        esplits; eauto.\n        eapply main_gvar_find_def; eauto.\n        sIn. }\n      i. des. fold fundef in *. clarify.\n    - i. ss.\n      hexploit _init_mem_max_cskew; eauto.\n      { apply Genv.find_def_symbol.\n        esplits; eauto.\n        eapply main_gvar_find_def; eauto.\n        sIn. }\n      i. des. fold fundef in *. clarify.\n    - i. ss.\n      hexploit _init_mem_max_nwdelay; eauto.\n      { apply Genv.find_def_symbol.\n        esplits; eauto.\n        eapply main_gvar_find_def; eauto.\n        sIn. }\n      i. des. fold fundef in *. clarify.\n    - i. ss.\n      hexploit _init_mem_num_tasks; eauto.\n      { apply Genv.find_def_symbol.\n        esplits; eauto.\n        eapply main_gvar_find_def; eauto.\n        sIn. }\n      i. des. fold fundef in *. clarify.\n    - i. ss.\n      hexploit _init_mem_num_mcasts; eauto.\n      { apply Genv.find_def_symbol.\n        esplits; eauto.\n        eapply main_gvar_find_def; eauto.\n        sIn. }\n      i. des. fold fundef in *. clarify.\n    - i. ss.\n      hexploit _init_mem_msg_size; eauto.\n      { apply Genv.find_def_symbol.\n        esplits; eauto.\n        eapply main_gvar_find_def; eauto.\n        sIn. }\n      i. des. fold fundef in *. clarify.\n    - i. ss.\n      hexploit _init_mem_port; eauto.\n      { apply Genv.find_def_symbol.\n        esplits; eauto.\n        eapply main_gvar_find_def; eauto.\n        sIn. }\n      i. des. fold fundef in *. clarify.\n    - i. ss.\n      hexploit _init_mem_ip_addr; eauto.\n      { apply Genv.find_def_symbol.\n        esplits; eauto.\n        eapply main_gvar_find_def; eauto.\n        sIn. }\n      i. des. fold fundef in *. clarify.\n    - i. ss.\n      hexploit _init_mem_mcm; eauto.\n      { apply Genv.find_def_symbol.\n        esplits; eauto.\n        eapply main_gvar_find_def; eauto.\n        sIn. }\n      intros (b_mcm' & FSYMB2 & NBLK & INIT).\n      fold fundef in *. clarify.\n      eapply INIT; eauto.\n  Qed.\n\n  Lemma init_mem_mstore\n    : mem_mstore ge m_i\n                 false 4%Z (4 + inb_sz)%Z\n                 MWITree.init_inbox MWITree.init_inbox.\n  Proof.\n    ii.\n    hexploit _init_mem_mstore; eauto.\n    { apply Genv.find_def_symbol.\n      esplits; eauto.\n      eapply main_gvar_find_def; eauto.\n      sIn. }\n\n    i. des. ss.\n    fold fundef in *. clarify.\n  Qed.\n\n  Lemma init_mem_sbuf\n    : mem_sbuf ge m_i 0 0 (List.repeat Byte.zero msg_size).\n  Proof.\n    ii.\n    hexploit _init_mem_send_buf; eauto.\n    { apply Genv.find_def_symbol.\n      esplits; eauto.\n      eapply main_gvar_find_def; eauto.\n      sIn. }\n\n    i. des. ss.\n    fold fundef in *. clarify.\n  Qed.\n\n  Lemma init_mem_sh\n    : mem_sh ge m_i (List.repeat false num_tasks).\n  Proof.\n    ii.\n    hexploit _init_mem_send_hist; eauto.\n    { apply Genv.find_def_symbol.\n      esplits; eauto.\n      eapply main_gvar_find_def; eauto.\n      sIn. }\n\n    i. des. ss.\n    fold fundef in *. clarify.\n  Qed.\n\n  Lemma init_mem_txs: mem_txs ge m_i 0.\n  Proof.\n    ii.\n    hexploit _init_mem_txs; eauto.\n    { apply Genv.find_def_symbol.\n      esplits; eauto.\n      eapply main_gvar_find_def; eauto.\n      sIn. }\n\n    i. des. ss.\n    fold fundef in *. clarify.\n  Qed.\n\n  Lemma init_mem_rxs: mem_rxs ge m_i 0.\n  Proof.\n    ii.\n    hexploit _init_mem_rxs; eauto.\n    { apply Genv.find_def_symbol.\n      esplits; eauto.\n      eapply main_gvar_find_def; eauto.\n      sIn. }\n\n    i. des. ss.\n    fold fundef in *. clarify.\n  Qed.\n\nEnd INIT_MEM_INVERSION.\n", "meta": {"author": "kim-yoonseung", "repo": "pals-thesis-dev", "sha": "1a165028f5461ed4d00a1e2720b3b1e4542f5dc2", "save_path": "github-repos/coq/kim-yoonseung-pals-thesis-dev", "path": "github-repos/coq/kim-yoonseung-pals-thesis-dev/pals-thesis-dev-1a165028f5461ed4d00a1e2720b3b1e4542f5dc2/src/mw_verif/VerifInitBase.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.23389693929398553}}
{"text": "Require Import Coq.Program.Equality.\nRequire Import Language Notations Auxiliaries Subtyping Automations.\nRequire Import Strings.String.\n\nSet Printing Parentheses.\n\nLemma tred_ord_toplike : forall (e e' : trm) (A : typ),\n    ordinary A -> toplike A -> typedred e A e' -> e' = (trm_anno (trm_nat 1) A).\nProof.\n  intros e e' A H_ord H_top H_tred.\n  dependent induction H_tred; subst; eauto.\n  - inversion H_top.\n  - inversion H_top. contradiction.\n  - inversion H_ord.\nQed.\n\nLemma tred_toplike :\n  forall (A : typ),\n    toplike A ->\n    forall e1 e2 e1' e2' : trm, typedred e1 A e1' -> typedred e2 A e2' -> e1' = e2'.\nProof.\n  intros A Htop.\n  dependent induction Htop; intros e1 e2 e1' e2' H_tred1 H_tred2.\n  - eapply tred_ord_toplike in H_tred1. eapply tred_ord_toplike in H_tred2.\n    rewrite H_tred1. rewrite H_tred2. reflexivity.\n    constructor. constructor. constructor. constructor.\n  - inversion H_tred1; subst; eauto 3.\n    + inversion H0.\n    + inversion H0.\n    + inversion H0.\n    + inversion H_tred2; subst; eauto 3.\n      * inversion H0.\n      * inversion H0.\n      * inversion H0.\n      * assert (Heq1: v1 = v0).\n        eapply IHHtop1; eauto 3.\n        assert (Heq2: v2 = v3).\n        eapply IHHtop2; eauto 3.\n        rewrite Heq1. rewrite Heq2. reflexivity.\n  - assert (HAB: toplike (typ_arrow A B)).\n    constructor. assumption.\n    eapply tred_ord_toplike in H_tred2; eauto.\n    eapply tred_ord_toplike in H_tred1; eauto.\n    rewrite H_tred1. rewrite H_tred2. reflexivity.\nQed.\n\nLemma tred_sub :\n  forall (A B : typ) (v1 v2 : trm),\n    value v1 -> typedred v1 A v2 ->\n    typing nil nil infer_mode v1 B ->\n    sub B A.\nProof.\n  intros A B v1 v2 Hval Hred Htyp.\n  generalize dependent B.\n  induction Hred; eauto.\n  - intros B Htyp.\n    inversion Htyp; subst.\n    inversion H3; subst. constructor.\n  - intros B Htyp.\n    eapply toplike_sub in H.\n    eapply sub_transitivity; eauto 3.\n  - intros B0 Htyp.\n    inversion Hval; subst; clear Hval.\n    inversion Htyp; subst; clear Htyp.\n    inversion H7; subst; clear H7.\n    + eapply sub_arrow; eauto 3.\n    (* + dependent destruction H2. eapply toplike_sub_toplike in H2; eauto. contradiction. *)\n  - intros B0 Htyp.\n    inversion Hval; subst; clear Hval.\n    inversion Htyp; subst; clear Htyp.\n    + apply sub_and_l.\n      eapply IHHred; eauto 3.\n    + apply sub_and_l.\n      eapply IHHred; eauto 3.\n  - intros B0 Htyp.\n    inversion Hval; subst; clear Hval.\n    inversion Htyp; subst; clear Htyp.\n    + apply sub_and_r.\n      eapply IHHred; eauto 3.\n    + apply sub_and_r.\n      eapply IHHred; eauto 3.\nQed.\n\nLemma disjoint_value_consistent :\n  forall (A B : typ) (v1 v2 : trm),\n    disjoint_spec A B -> value v1 -> value v2 ->\n    typing nil nil infer_mode v1 A ->\n    typing nil nil infer_mode v2 B ->\n    consistency_spec v1 v2.\nProof.\n  intros A B v1 v2 Hdis Hv1 Hv2 Htyp1 Htyp2.\n  unfold consistency_spec.\n  intros A0 e1' e2'. intros Hred1 Hred2.\n  assert (Hsub1: sub A A0).\n  eapply tred_sub. apply Hv1. apply Hred1. apply Htyp1.\n  assert (Hsub2: sub B A0).\n  eapply tred_sub. apply Hv2. apply Hred2. apply Htyp2.\n  assert (Htop : toplike A0).\n  unfold disjoint_spec in Hdis.\n  apply Hdis. assumption. assumption.\n  eapply tred_toplike. apply Htop. apply Hred1. apply Hred2.\nQed.\n\nLemma tred_determinism :\n  forall (v v1 v2 : trm) (A : typ),\n    value v -> (exists B, typing nil nil infer_mode v B) ->\n    typedred v A v1 -> typedred v A v2 -> v1 = v2.\nProof.\n  intros v v1 v2 A Hval Htyp Hred1.\n  generalize dependent v2.\n  induction Hred1.\n  - intros v2 Hred2.\n    inversion Hred2; subst.\n    + reflexivity.\n    + inversion H.\n  - intros v2 Hred2.\n    inversion Hred2; subst; clear Hred2; eauto.\n    + inversion H.\n    + inversion H. contradiction.\n    + symmetry. eapply tred_ord_toplike; eauto.\n    + symmetry. eapply tred_ord_toplike; eauto.\n    + inversion H0.\n  - intros v2 Hred2.\n    inversion Hred2; subst; clear Hred2.\n    + inversion H2. contradiction.\n    + reflexivity.\n  - intros v0 Hred2.\n    inversion Hred2; subst; eauto.\n    + eapply tred_ord_toplike; eauto 3.\n    + eapply IHHred1; eauto.\n      * inversion Hval; assumption.\n      * destruct Htyp. inversion H0; subst.\n        exists A0. assumption.\n        exists A0. assumption.\n    + destruct Htyp.\n      inversion H0; subst.\n      * inversion Hval; subst; clear Hval.\n        assert (Hcons: consistency_spec v1 v2).\n        eapply disjoint_value_consistent; eauto 3.\n        eapply Hcons; eauto 3.\n      * eapply H11; eauto 3.\n    + inversion H.\n  - intros v0 Hred2.\n    inversion Hred2; subst; eauto.\n    + eapply tred_ord_toplike; eauto 3.\n    + destruct Htyp.\n      inversion H0; subst; eauto.\n      * inversion Hval; subst; clear Hval.\n        assert(Hcons: consistency_spec v1 v2).\n        eapply disjoint_value_consistent; eauto 3.\n        unfold consistency_spec in Hcons.\n        symmetry. eapply Hcons; eauto 3.\n      * unfold consistency_spec in H10.\n        symmetry. eapply H11; eauto.\n    + inversion Hval; subst; clear Hval.\n      eapply IHHred1.\n      * assumption.\n      * destruct Htyp. inversion H0; subst.\n        exists B. assumption.\n        exists B. assumption.\n      * assumption.\n    + inversion H.\n  - intros v0 Hred2.\n    inversion Hred2; subst; clear Hred2.\n    + inversion H0.\n    + inversion H0.\n    + inversion H0.\n    + assert (Heq1: v1 = v3).\n      eapply IHHred1_1; eauto 3.\n      assert (Heq2: v2 = v4).\n      eapply IHHred1_2; eauto 3.\n      rewrite Heq1. rewrite Heq2. reflexivity.\nQed.\n\nLemma tred_value :\n  forall (v v' : trm) (A : typ),\n    value v -> typedred v A v' -> value v'.\nProof.\n  intros v v' A Hval Hred.\n  induction Hred; eauto.\n  + apply IHHred. inversion Hval; eauto.\n  + apply IHHred. inversion Hval; eauto.\nQed.\n\nLemma tred_transitivity : forall (v1 v2 v3 : trm) (A B : typ),\n    value v1 -> typedred v1 A v2 -> typedred v2 B v3 -> typedred v1 B v3.\nProof.\n  intros v1 v2 v3 A B Hval Hred1 Hred2.\n  generalize dependent v3.\n  generalize dependent B.\n  dependent induction Hred1; eauto.\n  - intros B v3 Hred2. dependent induction Hred2; eauto.\n  - intros B0 v3 Hred2. dependent induction Hred2; eauto.\n    + constructor. assumption.\n      eapply sub_transitivity; eauto.\n      eapply sub_transitivity; eauto.\n  - intros B v3 Hred2.\n    inversion Hval; subst; clear Hval.\n    induction Hred2; eauto.\n  - intros B v3 Hred2. inversion Hval; subst; clear Hval.\n    induction Hred2; eauto.\n  - intros B0 v0 Hred2.\n    generalize dependent v0.\n    induction B0; intros v0 Hred2; eauto.\n    + inversion Hred2; subst; clear Hred2; eauto.\n    + inversion Hred2; subst; clear Hred2; eauto.\n    + inversion Hred2; subst; clear Hred2; eauto.\n    + inversion Hred2; subst; clear Hred2; eauto.\nQed.\n\nLemma tred_consistency :\n  forall (v v1 v2 : trm) (A B C : typ),\n    value v -> typing nil nil infer_mode v C ->\n    typedred v A v1 ->\n    typedred v B v2 ->\n    consistency_spec v1 v2.\nProof.\n  intros v v1 v2 A B C Hval Htyp Hred1 Hred2.\n  unfold consistency_spec.\n  intros D v1' v2' Hred1' Hred2'.\n  assert (Htrans1: typedred v D v1').\n  eapply tred_transitivity. apply Hval. apply Hred1. apply Hred1'.\n  assert (Htrans2: typedred v D v2').\n  eapply tred_transitivity. apply Hval. apply Hred2. apply Hred2'.\n  eapply tred_determinism; eauto 3.\nQed.\n\nLemma typing_merge_inversion:\n  forall (v1 v2 : trm),\n    (exists (A : typ), typing nil nil infer_mode (trm_merge v1 v2) A) ->\n    (exists (B : typ), typing nil nil infer_mode v1 B) /\\\n    (exists (C : typ), typing nil nil infer_mode v2 C).\nProof.\n  intros v1 v2 Htyp.\n  destruct Htyp.\n  inversion H; subst.\n  - split. eauto. eauto.\n  - split. eauto. eauto.\nQed.\n\nLemma ptype_determinsm :\n  forall (e : trm) (A B : typ),\n    ptype e A -> ptype e B -> A = B.\nProof.\n  intros e A B Hp1 Hp2.\n  generalize dependent B.\n  dependent induction Hp1.\n  - intros. inversion Hp2. reflexivity.\n  - intros. inversion Hp2. reflexivity.\n  - intros. inversion Hp2; subst.\n    assert (A = A0).\n    eapply IHHp1_1; eauto.\n    assert (B = B1).\n    eapply IHHp1_2; eauto.\n    rewrite H. rewrite H0. reflexivity.\nQed.\n\nLemma appsub_determinism :\n  forall (A : typ) (B1 B2 : typ) (S : arg),\n    appsub S A B1 ->\n    appsub S A B2 ->\n    B1 = B2.\nProof.\n  intros A B1 B2 S Has1 Has2.\n  generalize dependent B2.\n  dependent induction Has1; intros.\n  - dependent destruction Has2.\n    + reflexivity.\n  - dependent destruction Has2.\n    + assert (Heq: D = D0).\n      eapply IHHas1; eauto.\n      rewrite Heq. reflexivity.\n  - dependent destruction Has2.\n    + eapply IHHas1; eauto.\n    + admit. \n  - dependent destruction Has2.\n    + admit.\n    + eapply IHHas1; eauto.\nAdmitted.\n\nLemma ptype_merge_same :\n  forall (v1 v2 : trm) (A : typ),\n    value v1 -> value v2 -> ptype (trm_merge v1 v2) (typ_and A A) ->\n    v1 = v2.\nProof.\nAdmitted.\n\nLemma papp_determinism :\n  forall (v vl e1 e2 : trm),\n    value v -> value vl ->\n    (exists (B : typ), typing nil nil infer_mode vl B) ->\n    papp v vl e1 -> papp v vl e2 -> e1 = e2.\nProof.\n intros v vl e1 e2 Hrv Hv Htyp Hp1 Hp2.\n  generalize dependent e2.\n  dependent induction Hp1.\n  - intros. inversion Hp2; subst.\n    + assert (A = A0). eapply ptype_determinsm; eauto.\n      rewrite H3. reflexivity.\n    + dependent destruction H. dependent destruction H0. contradiction.\n    + assert (Heq: A = C). eapply ptype_determinsm; eauto. subst.\n      contradiction.\n    + assert (Heq: A = C). eapply ptype_determinsm; eauto. subst.\n      contradiction.\n  - intros. dependent destruction Hp2.\n    + dependent destruction H1. dependent destruction H2. contradiction.\n    + assert (v' = v'0). eapply tred_determinism; eauto.\n      rewrite H3; eauto.\n  - intros. apply IHHp1; eauto.\n    + dependent destruction Hrv. assumption.\n    + dependent destruction Hp2; eauto.\n      * assert (Heq: A0 = C). eapply ptype_determinsm; eauto. subst.\n        contradiction.\n      * assert (B = B0). eapply ptype_determinsm; eauto. subst.\n        assert (C = C0). eapply ptype_determinsm; eauto. subst.\n        assert (A = A0). eapply appsub_determinism; eauto. subst.\n        dependent destruction H6.\n        assert (A = B).\n        assert (A = A0). eapply ptype_determinsm; eauto. subst.\n        assert (B = A0). eapply ptype_determinsm; eauto. subst.\n        reflexivity. subst.\n        dependent destruction Hrv.\n        assert (v1 = v2). eapply ptype_merge_same; eauto. subst. eauto.\n  - intros. apply IHHp1; eauto.\n    + dependent destruction Hrv. assumption.\n    + dependent destruction Hp2; eauto.\n      * assert (Heq: A0 = C). eapply ptype_determinsm; eauto. subst.\n        contradiction.\n      * assert (B = B0). eapply ptype_determinsm; eauto. subst.\n        assert (C = C0). eapply ptype_determinsm; eauto. subst.\n        assert (A = A0). eapply appsub_determinism; eauto. subst.\n        dependent destruction H6.\n        assert (A = B).\n        assert (A = A0). eapply ptype_determinsm; eauto. subst.\n        assert (B = A0). eapply ptype_determinsm; eauto. subst.\n        reflexivity. subst.\n        dependent destruction Hrv.\n        assert (v1 = v2). eapply ptype_merge_same; eauto. subst. eauto.\nQed.\n\nLemma value_cannot_step_further :\n  forall (v : trm),\n    value v -> forall (e : trm), not (step v e).\nProof.\n  intros v Hval.\n  induction v.\n  - inversion Hval.\n  - inversion Hval.\n  - inversion Hval.\n  - unfold not. intros. inversion H.\n  - inversion Hval.\n  - inversion Hval; subst.\n    intros. unfold not. intros.\n    inversion H; subst.\n    + eapply IHv1; eauto 3.\n    + eapply IHv2; eauto 3.\n  - inversion Hval; subst; clear Hval.\n    induction H0.\n    + intros. unfold not. intros.\n      inversion H; subst.\n      * inversion H2.\n      * apply H2. constructor. constructor.\n    + intros. unfold not. intros.\n      inversion H; subst.\n      * inversion H2.\n      * apply H2. constructor. constructor.\nQed.\n\nLemma app_check_inversion :\n  forall (v vl : trm) (A : typ),\n    value v -> value vl -> typing nil nil check_mode (trm_app v vl) A ->\n    exists (B : typ), typing nil nil infer_mode vl B.\nProof.\n  intros r vl A Hrv Hv Hchk.\n  dependent destruction Hchk.\n  - inversion H0.\n  - exists A. auto.\n  - dependent destruction Hchk.\n    exists A0. eauto.\nQed.\n\n(* aux lemma for anno_check_to_infer *)\nLemma value_with_anno_is_not_value :\n  forall (v : trm) (A : typ),\n    value v -> not (value (trm_anno v A)).\nProof.\n  intros v A Hv.\n  unfold not. intro.\n  dependent destruction H.\n  dependent induction H.\n  - inversion Hv.\n  - inversion Hv.\nQed.\n\n(* this case have conflict with typing rule: any value can be checked by lemma *)\n(* current workaround is add a premise not-toplike *)\nLemma anno_check_to_infer :\n  forall (v : trm) (A B : typ),\n    value v -> typing nil nil check_mode (trm_anno v A) B ->\n    (exists (C : typ), typing nil nil infer_mode v C).\nProof.\n  intros v A B Hv Htyp.\n  dependent destruction Htyp.\n  inversion H0.\n  dependent destruction Htyp.\n  dependent destruction Htyp.\n  - dependent destruction H1; try solve [inversion Hv].\n  - inversion Hv. \n  - exists B0; eauto.\nQed.\n\n(* aux lemma for step_determinism *)\nLemma lambda_typing1 :\n  forall (e : trm) (A B : typ),\n    typing nil (cons A nil) infer_mode e B ->\n    (exists C, typing nil nil check_mode e C).\nProof.\n  intros e A B Htyp.\n  dependent induction Htyp.\n  - simpl in *.\n    exists (typ_arrow A0 B). eapply typing_sub.\n    assert (Habs: typing nil nil infer_mode (trm_abs A0 e) (typ_arrow A0 B)).\n    eapply typing_abs1; eauto. eapply Habs. eapply sub_reflexivity.\n  - dependent destruction H.\n    + dependent destruction H0.\n      exists (typ_arrow A0 A1). eapply typing_sub; eauto.\n      eapply sub_reflexivity.\n    + clear IHHtyp. exists (typ_and A0 B). eapply typing_sub; eauto.\n      eapply sub_reflexivity.\n    + clear IHHtyp. exists (typ_and A0 B). eapply typing_sub; eauto.\n      eapply sub_reflexivity.\n  - exists B. eapply typing_app2.\n    + eapply Htyp1.\n    + admit.\n  - clear IHHtyp1 IHHtyp2.\n    exists B. eapply typing_sub; eauto.\nAdmitted.\n\nLemma step_determinism :\n  forall (e e1 e2 : trm) (A : typ),\n    typing nil nil check_mode e A ->\n    step e e1 -> step e e2 -> e1 = e2.\nProof.\n  intros e e1 e2 A Htyp Hred1.\n  generalize dependent e2.\n  generalize dependent A.\n  induction Hred1.\n  - intros A Htyp e2 Hred2.\n    inversion Hred2; subst.\n    reflexivity.\n  - intros A Htyp e2 Hred2.\n    inversion Hred2; subst. (* papp and 2 congruence rules *)\n    + eapply app_check_inversion in Htyp; eauto.\n      apply papp_determinism with (v:=v) (vl:=vl); eauto.\n    + eapply value_cannot_step_further in H5. inversion H5. auto.\n    + eapply value_cannot_step_further in H6. inversion H6. auto.\n  - intros A0 Htyp e2 Hred2.\n    dependent destruction Hred2.\n    + eapply tred_determinism; eauto 3.\n      eapply anno_check_to_infer in Htyp; eauto.\n    + eapply value_cannot_step_further in Hred2; eauto. contradiction.\n  - intros A0 Htyp e2 Hred2.\n    dependent destruction Hred2.\n    + eapply value_cannot_step_further in Hred1. contradiction.\n      auto.\n    + assert (Heq: e' = e'0).\n      dependent destruction Htyp.\n      * inversion H1.\n      * dependent destruction Htyp.\n        eapply IHHred1; eauto.\n      * rewrite Heq. reflexivity.\n  - intros A Htyp e0 Hred2.\n    dependent destruction Hred2.\n    + eapply value_cannot_step_further in Hred1; eauto. contradiction.\n    + assert (Heq: e1' = e1'0).\n      dependent destruction Htyp.\n      * inversion H0.\n      * eapply IHHred1; eauto 3.\n      * dependent destruction Htyp.\n        assert (exists C, typing nil nil check_mode e1 C).\n        eapply lambda_typing1; eauto 3.\n        destruct H0.\n        eapply IHHred1; eauto 3.        \n      * rewrite Heq; eauto.\n    + eapply value_cannot_step_further in Hred1. contradiction. assumption.\n  - intros A Htyp e0 Hred2.\n    dependent destruction Hred2.\n    + eapply value_cannot_step_further in Hred1. contradiction. assumption.\n    + eapply value_cannot_step_further in Hred2. contradiction. assumption.\n    + assert (Heq: e2' = e2'0).\n      dependent destruction Htyp.\n      * inversion H1.\n      * eapply IHHred1; eauto 3.\n      * dependent destruction Htyp.\n        eapply IHHred1; eauto 3.\n      * rewrite Heq. reflexivity.\n  - intros A Htyp e0 Hred2.\n    dependent destruction Hred2.\n    + assert (Heq: e1' = e1'0).\n      dependent destruction Htyp.\n      inversion H0.\n      dependent destruction Htyp.\n      * eapply IHHred1; eauto.\n      * eapply IHHred1; eauto.\n      * rewrite Heq. reflexivity.\n    + eapply value_cannot_step_further in Hred1. contradiction. assumption.\n  - intros A Htyp e0 Hred2.\n    dependent destruction Hred2.\n    + eapply value_cannot_step_further in Hred2.\n      contradiction. assumption.\n    + assert (Heq: e2' = e2'0).\n      dependent destruction Htyp.\n      inversion H1.\n      dependent destruction Htyp.\n      * eapply IHHred1; eauto.\n      * eapply IHHred1; eauto.\n      * rewrite Heq. reflexivity.\nQed.\n", "meta": {"author": "juniorxxue", "repo": "applicative-intersection", "sha": "6b6f8fc3d78657e5a527e60b97465a2f96bcc606", "save_path": "github-repos/coq/juniorxxue-applicative-intersection", "path": "github-repos/coq/juniorxxue-applicative-intersection/applicative-intersection-6b6f8fc3d78657e5a527e60b97465a2f96bcc606/archive/applicative-intersection/Deterministic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.23389693382428298}}
{"text": "Require Import\n        Coq.Strings.String\n        Coq.Vectors.Vector.\n\nRequire Import\n        Fiat.Computation\n        Fiat.BinEncoders.Env.Common.Specs\n        Fiat.BinEncoders.Env.Common.WordFacts\n        Fiat.BinEncoders.Env.Common.ComposeIf\n        Fiat.BinEncoders.Env.Common.ComposeOpt\n        Fiat.BinEncoders.Env.Automation.Solver\n        Fiat.BinEncoders.Env.BinLib.AlignedByteString\n        Fiat.BinEncoders.Env.BinLib.AlignWord\n        Fiat.BinEncoders.Env.BinLib.AlignedDecoders\n        Fiat.BinEncoders.Env.Lib2.WordOpt\n        Fiat.BinEncoders.Env.Lib2.NatOpt\n        Fiat.BinEncoders.Env.Lib2.FixListOpt.\n\nInstance ByteStringQueueTransformer : Transformer ByteString := ByteStringQueueTransformer.\n\nDefinition simple_record := ((word 16) * list (word 8))%type.\n\nDefinition Simple_Format_Spec\n           (p : simple_record) :=\n        encode_nat_Spec 8 (|snd p|)\n  ThenC encode_word_Spec (fst p)\n  ThenC encode_list_Spec encode_word_Spec (snd p)\n  DoneC.\n\nDefinition Simply_OK (p : simple_record) :=\n  ((|snd p|) < pow2 8)%nat.\n\nArguments split1' : simpl never.\nArguments split2' : simpl never.\nArguments weq : simpl never.\nArguments natToWord : simpl never.\nArguments Guarded_Vector_split : simpl never.\nArguments Core.append_word : simpl never.\n\nDefinition refine_simple_encode\n  : { b : _ & forall (p : simple_record)\n                     (p_OK : Simply_OK p),\n          refine (Simple_Format_Spec p ())\n                 (ret (b p)) }.\nProof.\n  unfold Simple_Format_Spec.\n  eexists; intros.\n  eapply AlignedEncodeChar; eauto.\n  eapply AlignedEncode2Char; eauto.\n  etransitivity.\n  apply refine_under_bind_both.\n  eapply optimize_align_encode_list.\n  etransitivity.\n  eapply aligned_encode_char_eq.\n  instantiate (1 := fun a ce => (existT _ _ _, _)); simpl.\n  reflexivity.\n  intros; unfold Bind2; simplify with monad laws; higher_order_reflexivity.\n  simpl.\n  match goal with\n    |- context [let (v, c) := ?z in ret (@?b v c)] =>\n    rewrite (zeta_inside_ret z _)\n  end.\n  simplify with monad laws; simpl.\n  rewrite zeta_to_fst; simpl.\n  replace ByteString_id\n  with (build_aligned_ByteString (Vector.nil _)).\n  erewrite <- build_aligned_ByteString_append.\n  reflexivity.\n  eapply ByteString_f_equal;\n    instantiate (1 := eq_refl _); reflexivity.\nDefined.\n\nDefinition byte_aligned_simple_encoder\n             (r : simple_record)\n  := Eval simpl in (projT1 refine_simple_encode r).\n\nImport Vectors.VectorDef.VectorNotations.\nPrint byte_aligned_simple_encoder.\n\nDefinition Simple_Format_decoder\n  : CorrectDecoderFor Simply_OK Simple_Format_Spec.\nProof.\n  start_synthesizing_decoder.\n  normalize_compose transformer.\n  repeat decode_step idtac.\n  intros; eauto using FixedList_predicate_rest_True.\n  synthesize_cache_invariant.\n  cbv beta; optimize_decoder_impl.\nDefined.\n\nDefinition SimpleDecoderImpl\n    := Eval simpl in (projT1 Simple_Format_decoder).\n\n  Ltac rewrite_DecodeOpt2_fmap :=\n    set_refine_evar;\n    progress rewrite ?BindOpt_map, ?DecodeOpt2_fmap_if,\n    ?DecodeOpt2_fmap_if_bool;\n    subst_refine_evar.\n\nDefinition ByteAligned_SimpleDecoderImpl {A}\n           (f : _ -> A)\n           n\n  : {impl : _ & forall (v : Vector.t _ (3 + n)),\n         f (fst SimpleDecoderImpl (build_aligned_ByteString v) ()) =\n         impl v () }.\nProof.\n  eexists _; intros.\n  etransitivity.\n  set_refine_evar; simpl.\n  unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n  rewrite (@AlignedDecodeNat NoCache.test_cache).\n  subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n  unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n  rewrite (@AlignedDecode2Char NoCache.test_cache).\n  subst_refine_evar; apply rewrite_under_LetIn; intros; set_refine_evar.\n  unfold DecodeBindOpt2 at 1; rewrite_DecodeOpt2_fmap.\n  erewrite optimize_align_decode_list.\n  rewrite Ifopt_Ifopt; simpl.\n  etransitivity.\n  eapply optimize_under_if_opt; simpl; intros.\n  higher_order_reflexivity.\n  reflexivity.\n  Focus 2.\n  clear H; intros.\n  etransitivity.\n  match goal with\n    |- ?b = _ =>\n    let b' := (eval pattern (build_aligned_ByteString v0) in b) in\n    let b' := match b' with ?f _ => f end in\n      eapply (@optimize_Guarded_Decode n0 _ 1 b')\n  end.\n  destruct n0 as [ | [ | ?] ]; intros; try omega.\n  apply (@decode_word_aligned_ByteString_overflow NoCache.test_cache) with (sz := 1); auto.\n  destruct n0 as [ | ?]; intros; try omega.\n  higher_order_reflexivity.\n  instantiate (1 := fun n1 v1 (cd0 : CacheDecode) =>\n                      If NPeano.leb 1 n1 Then (Some ((Vector.hd (Guarded_Vector_split 1 n1 v1), @existT _ (Vector.t _) _ (Vector.tl (Guarded_Vector_split 1 n1 v1))), cd0)) Else None).\n  simpl; find_if_inside; simpl; try reflexivity.\n  pattern n0, v0; apply Vector.caseS; simpl; intros.\n  unfold decode_word, WordOpt.decode_word.\n  rewrite aligned_decode_char_eq; reflexivity.\n  subst_refine_evar; higher_order_reflexivity.\n  higher_order_reflexivity.\nDefined.\n\nDefinition ByteAligned_SimpleDecoderImpl' n :=\n  Eval simpl in (projT1 (ByteAligned_SimpleDecoderImpl id n)).\n\nPrint ByteAligned_SimpleDecoderImpl'.\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/BinEncoders/Env/Examples/ByteAlignedExample.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.23389693382428298}}
{"text": "Require Export MinBFTass_tknows.\nRequire Export MinBFTass_knew.\nRequire Export MinBFTass_diss.\nRequire Export ComponentAxiom.\n\n\nSection MinBFTass_tlearn.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext        }.\n  Context { minbft_context      : MinBFT_context      }.\n  Context { m_initial_keys      : MinBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys   }.\n  Context { usig_hash           : USIG_hash           }.\n  Context { minbft_auth         : MinBFT_auth         }.\n\n\n  Lemma ASSUMPTION_trusted_learns_if_gen_true :\n    forall (eo : EventOrdering),\n      AXIOM_authenticated_messages_were_sent_or_byz eo MinBFTsys\n      -> assume_eo eo (KE_ALL_TRUST ASSUMPTION_trusted_learns_if_gen).\n  Proof.\n    introv sendbyz; introv.\n    rewrite <- sequent_true_iff_interpret.\n    apply DERIVED_RULE_implies_all_trusted_learns_if_gen2_true; simseqs j;\n      apply sequent_true_iff_interpret; eauto 3 with minbft;\n      try (apply ASSUMPTION_in_knows_implies_trusted_knows_true);\n      try (apply ASSUMPTION_diss_correct_implies_knows_true);\n      try (apply ASSUMPTION_all_knew_or_learns_or_gen_true).\n\n    { apply ASSUMPTION_authenticated_messages_were_sent_or_byz_true; simpl; auto; tcsp;\n        try (complete (introv h q; destruct a as [a x], a; simpl in *; ginv; simpl in *; tcsp; eauto));\n        try (complete (introv h q; destruct m; simpl in *; tcsp; repndors; subst; tcsp;\n                       try (destruct p as [p a], p, a);\n                       try (destruct c as [c a], c, a);\n                       simpl in *; repndors; subst; simpl in *; tcsp)). }\n  Qed.\n\nEnd MinBFTass_tlearn.\n\n\nHint Resolve ASSUMPTION_trusted_learns_if_gen_true : minbft.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MinBFTass_tlearn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2337697930922392}}
{"text": "Require Export MicroBFTprops2.\nRequire Export ComponentAxiom.\n\n\nSection MicroBFTass_tlearn.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext          }.\n  Context { microbft_context    : MicroBFT_context      }.\n  Context { m_initial_keys      : MicroBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys     }.\n  Context { usig_hash           : USIG_hash             }.\n  Context { microbft_auth       : MicroBFT_auth         }.\n\n\n  Opaque KE_TOWNS.\n  Opaque KE_TGENS.\n\n\n  Lemma ASSUMPTION_trusted_learns_if_gen_true :\n    forall (eo : EventOrdering),\n      AXIOM_authenticated_messages_were_sent_or_byz eo MicroBFTsys\n      -> assume_eo eo (KE_ALL_TRUST ASSUMPTION_trusted_learns_if_gen).\n  Proof.\n    introv sendbyz; introv lrn.\n    destruct e as [e exe].\n\n    simpl in *; exrepnd; GC.\n    unfold learns_data in *; exrepnd; GC.\n\n    pose proof (sendbyz e a (const_opTrust lrn3)) as sendbyz.\n    simpl in *.\n    repeat (autodimp sendbyz hyp).\n    exrepnd; repndors; exrepnd; ginv;[|].\n\n    {\n      autodimp sendbyz5 hyp; eauto 3 with microbft.\n\n\n      assert (exists k, loc e' = MicroBFTheader.node2name k) as eqloc'.\n      { destruct a as [a tok], a, m; simpl in *; tcsp; ginv;\n          try (complete (inversion sendbyz4; eauto)). }\n      exrepnd.\n\n      unfold M_output_sys_on_event in sendbyz5; simpl in *.\n      rewrite eqloc'0 in *; simpl in *.\n      apply M_output_ls_on_event_as_run in sendbyz5; exrepnd.\n      applydup M_run_ls_before_event_ls_is_microbft in sendbyz5; exrepnd; subst; simpl in *.\n\n      unfold M_output_ls_on_this_one_event in sendbyz6.\n      remember (trigger_op e') as trig; symmetry in Heqtrig.\n      destruct trig; simpl in *; tcsp;[].\n\n      (* XXXXXXXXXXX *)\n      unfold M_run_ls_on_input_out in *.\n      unfold M_run_ls_on_input in *.\n      autorewrite with comp microbft in *.\n      Time microbft_dest_msg Case; [|].\n\n      { Case \"Request\".\n\n        inversion sendbyz6; subst; simpl in *; clear sendbyz6.\n        repeat (repndors; subst; tcsp; simpl in *; ginv);[].\n\n        assert (ex_node_e e') as exe' by (eexists; allrw; simpl; eauto).\n\n        exists (MkEventN e' exe'); dands;\n          allrw interp_owns; simpl; eauto 3 with minbft;\n            try (complete (unfold data_is_owned_by; simpl; unfold ui2rep; simpl; eauto));[ | unfold data_is_owned_by; smash_microbft].\n\n        unfold disseminate_data; simpl.\n        unfold M_byz_output_sys_on_event; simpl.\n        allrw; simpl.\n        rewrite M_byz_output_ls_on_event_as_run.\n        applydup @M_run_ls_before_event_M_byz_run_ls_before_event in sendbyz5 as byz.\n        applydup trigger_op_Some_implies_trigger_message in Heqtrig as trig'.\n        unfold M_byz_output_ls_on_this_one_event; simpl.\n        unfold M_byz_run_ls_on_one_event; simpl.\n        repeat (allrw; simpl).\n        unfold data_is_in_out, event2out; rewrite trig'; simpl.\n        unfold M_run_ls_on_input; simpl.\n        autorewrite with comp microbft.\n        repeat unfold_handler_concl.\n        smash_microbft.\n        eexists; dands; try reflexivity; dands; tcsp.\n      }\n\n      {\n        Case \"Commit\".\n\n        repeat (simpl in *; try autorewrite with comp minbft in *; smash_microbft2);\n          try (complete (inversion sendbyz6; subst; simpl in *; tcsp)).\n      }\n    }\n\n    {\n      ginv.\n      assert (ex_node_e e') as exe' by (eexists; allrw; simpl; eauto).\n      exists (MkEventN e' exe'); simpl; allrw interp_towns; dands; eauto 3 with minbft;\n        try (complete (unfold data_is_owned_by; simpl; unfold ui2rep; simpl; eauto));[].\n\n      unfold M_byz_output_sys_on_event in *; simpl in *.\n      rewrite sendbyz7 in *; simpl in *.\n\n      assert (MicroBFTsys (MicroBFTheader.node2name (ui2rep t)) = MicroBFTlocalSys (ui2rep t)) as temp by auto.\n      rewrite temp in *.\n\n      unfold disseminate_data.\n      unfold M_byz_output_sys_on_event; simpl.\n      allrw.\n      exists o; dands; auto.\n      clear sendbyz4.\n\n      revert dependent o.\n      unfold is_trusted_event in *.\n      unfold data_is_in_out, trusted_is_in_out, event2out; simpl in *; rewrite p; simpl in *.\n      introv xx; subst; simpl in *.\n      allrw; simpl; tcsp.\n    }\n  Qed.\n  Hint Resolve ASSUMPTION_trusted_learns_if_gen_true : microbft.\n\nEnd MicroBFTass_tlearn.\n\n\nHint Resolve ASSUMPTION_trusted_learns_if_gen_true : microbft.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MicroBFTass_tlearn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23376979309223914}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import TableDataOpsIntro.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition data_create_unknown1_spec0 (g_rd: Pointer) (data_addr: Z64) (map_addr: Z64) (g_data: Pointer) (adt: RData) : option (RData * Z64) :=\n    match g_rd, data_addr, map_addr, g_data with\n    | (_g_rd_base, _g_rd_ofst), VZ64 _data_addr, VZ64 _map_addr, (_g_data_base, _g_data_ofst) =>\n      rely is_int64 _data_addr;\n      rely is_int64 _map_addr;\n      when' _t'1, adt == data_create_unknown_spec (_g_rd_base, _g_rd_ofst) (VZ64 _data_addr) (VZ64 _map_addr) (_g_data_base, _g_data_ofst) adt;\n      rely is_int64 _t'1;\n      Some (adt, (VZ64 _t'1))\n     end\n    .\n\nEnd SpecLow.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef1/LowSpecs/data_create_unknown1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2337697869380713}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation, either version 2 of the License, or  *)\n(*  (at your option) any later version.  This file is also distributed *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Whole-program behaviors *)\n\n(* Adapted to our customSmallstep library *)\n\nRequire Import Classical.\nRequire Import ClassicalEpsilon.\nRequire Import Coqlib.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Integers.\nRequire Import customSmallstep.\n\nSet Implicit Arguments.\n\n(** * Behaviors for program executions *)\n\n(** The four possible outcomes for the execution of a program:\n- Termination, with a finite trace of observable events\n  and an integer value that stands for the process exit code\n  (the return value of the main function).\n- Divergence with a finite trace of observable events.\n  (At some point, the program runs forever without doing any I/O.)\n- Reactive divergence with an infinite trace of observable events.\n  (The program performs infinitely many I/O operations separated\n   by finite amounts of internal computations.)\n- Going wrong, with a finite trace of observable events\n  performed before the program gets stuck.\n*)\n\nInductive program_behavior: Type :=\n  | Terminates: trace -> int -> program_behavior\n  | Diverges: trace -> program_behavior\n  | Reacts: traceinf -> program_behavior\n  | Goes_wrong: trace -> program_behavior.\n\n(** Operations and relations on behaviors *)\n\nDefinition not_wrong (beh: program_behavior) : Prop :=\n  match beh with\n  | Terminates _ _ => True\n  | Diverges _ => True\n  | Reacts _ => True\n  | Goes_wrong _ => False\n  end.\n\nDefinition behavior_app (t: trace) (beh: program_behavior): program_behavior :=\n  match beh with\n  | Terminates t1 r => Terminates (t ** t1) r\n  | Diverges t1 => Diverges (t ** t1)\n  | Reacts T => Reacts (t *** T)\n  | Goes_wrong t1 => Goes_wrong (t ** t1)\n  end.\n\nLemma behavior_app_assoc:\n  forall t1 t2 beh,\n  behavior_app (t1 ** t2) beh = behavior_app t1 (behavior_app t2 beh).\nProof.\n  intros. destruct beh; simpl; f_equal; traceEq.\nQed.\n\nLemma behavior_app_E0:\n  forall beh, behavior_app E0 beh = beh.\nProof.\n  destruct beh; auto.\nQed.\n\nDefinition behavior_prefix (t: trace) (beh: program_behavior) : Prop :=\n  exists beh', beh = behavior_app t beh'.\n\nDefinition behavior_improves (beh1 beh2: program_behavior) : Prop :=\n  beh1 = beh2 \\/ exists t, beh1 = Goes_wrong t /\\ behavior_prefix t beh2.\n\nLemma behavior_improves_refl:\n  forall beh, behavior_improves beh beh.\nProof.\n  intros; red; auto.\nQed.\n\nLemma behavior_improves_trans:\n  forall beh1 beh2 beh3,\n  behavior_improves beh1 beh2 -> behavior_improves beh2 beh3 ->\n  behavior_improves beh1 beh3.\nProof.\n  intros. red. destruct H; destruct H0; subst; auto.\n  destruct H as [t1 [EQ1 [beh2' EQ1']]].\n  destruct H0 as [t2 [EQ2 [beh3' EQ2']]].\n  subst. destruct beh2'; simpl in EQ2; try discriminate. inv EQ2.\n  right. exists t1; split; auto. exists (behavior_app t beh3'). apply behavior_app_assoc.\nQed.\n\nLemma behavior_improves_bot:\n  forall beh, behavior_improves (Goes_wrong E0) beh.\nProof.\n  intros. right. exists E0; split; auto. exists beh. rewrite behavior_app_E0; auto.\nQed.\n\nLemma behavior_improves_app:\n  forall t beh1 beh2,\n  behavior_improves beh1 beh2 ->\n  behavior_improves (behavior_app t beh1) (behavior_app t beh2).\nProof.\n  intros. red; destruct H. left; congruence.\n  destruct H as [t' [A [beh' B]]]. subst.\n  right; exists (t ** t'); split; auto. exists beh'. rewrite behavior_app_assoc; auto.\nQed.\n\n(** Associating behaviors to programs. *)\n\nSection PROGRAM_BEHAVIORS.\n\nVariable L: semantics.\n\nInductive state_behaves (s: state L): program_behavior -> Prop :=\n  | state_terminates: forall t s' r,\n      Star L s t s' ->\n      final_state L s' r ->\n      state_behaves s (Terminates t r)\n  | state_diverges: forall t s',\n      Star L s t s' -> Forever_silent L s' ->\n      state_behaves s (Diverges t)\n  | state_reacts: forall T,\n      Forever_reactive L s T ->\n      state_behaves s (Reacts T)\n  | state_goes_wrong: forall t s',\n      Star L s t s' ->\n      Nostep L s' ->\n      (forall r, ~final_state L s' r) ->\n      state_behaves s (Goes_wrong t).\n\nInductive program_behaves: program_behavior -> Prop :=\n  | program_runs: forall s beh,\n      initial_state L s -> state_behaves s beh ->\n      program_behaves beh\n  | program_goes_initially_wrong:\n      (forall s, ~initial_state L s) ->\n      program_behaves (Goes_wrong E0).\n\nLemma state_behaves_app:\n  forall s1 t s2 beh,\n  Star L s1 t s2 -> state_behaves s2 beh -> state_behaves s1 (behavior_app t beh).\nProof.\n  intros. inv H0; simpl; econstructor; eauto; try (eapply star_trans; eauto).\n  eapply star_forever_reactive; eauto.\nQed.\n\n(** * Existence of behaviors *)\n\n(** We now show that any program admits at least one behavior.\n  The proof requires classical logic: the axiom of excluded middle\n  and an axiom of description. *)\n\n(** The most difficult part of the proof is to show the existence\n  of an infinite trace in the case of reactive divergence. *)\n\nSection TRACEINF_REACTS.\n\nVariable s0: state L.\n\nHypothesis reacts:\n  forall s1 t1, Star L s0 t1 s1 ->\n  exists s2, exists t2, Star L s1 t2 s2 /\\ t2 <> E0.\n\nLemma reacts':\n  forall s1 t1, Star L s0 t1 s1 ->\n  { s2 : state L & { t2 : trace | Star L s1 t2 s2 /\\ t2 <> E0 } }.\nProof.\n  intros.\n  destruct (constructive_indefinite_description _ (reacts H)) as [s2 A].\n  destruct (constructive_indefinite_description _ A) as [t2 [B C]].\n  exists s2; exists t2; auto.\nQed.\n\nCoFixpoint build_traceinf' (s1: state L) (t1: trace) (ST: Star L s0 t1 s1) : traceinf' :=\n  match reacts' ST with\n  | existT _ s2 (exist _ t2 (conj A B)) =>\n      Econsinf' t2\n                (build_traceinf' (star_trans ST A (refl_equal _)))\n                B\n  end.\n\nLemma reacts_forever_reactive_rec:\n  forall s1 t1 (ST: Star L s0 t1 s1),\n  Forever_reactive L s1 (traceinf_of_traceinf' (build_traceinf' ST)).\nProof.\n  cofix COINDHYP; intros.\n  rewrite (unroll_traceinf' (build_traceinf' ST)). simpl.\n  destruct (reacts' ST) as [s2 [t2 [A B]]].\n  rewrite traceinf_traceinf'_app.\n  econstructor. eexact A. auto. apply COINDHYP.\nQed.\n\nLemma reacts_forever_reactive:\n  exists T, Forever_reactive L s0 T.\nProof.\n  exists (traceinf_of_traceinf' (build_traceinf' (star_refl (step L) (globalenv L) s0))).\n  apply reacts_forever_reactive_rec.\nQed.\n\nEnd TRACEINF_REACTS.\n\nLemma diverges_forever_silent:\n  forall s0,\n  (forall s1 t1, Star L s0 t1 s1 -> exists s2, Step L s1 E0 s2) ->\n  Forever_silent L s0.\nProof.\n  cofix COINDHYP; intros.\n  destruct (H s0 E0) as [s1 ST]. constructor.\n  econstructor. eexact ST. apply COINDHYP.\n  intros. eapply H. eapply star_left; eauto.\nQed.\n\nLemma state_behaves_exists:\n  forall s, exists beh, state_behaves s beh.\nProof.\n  intros s0.\n  destruct (classic (forall s1 t1, Star L s0 t1 s1 -> exists s2, exists t2, Step L s1 t2 s2)).\n(* 1 Divergence (silent or reactive) *)\n  destruct (classic (exists s1, exists t1, Star L s0 t1 s1 /\\\n                       (forall s2 t2, Star L s1 t2 s2 ->\n                        exists s3, Step L s2 E0 s3))).\n(* 1.1 Silent divergence *)\n  destruct H0 as [s1 [t1 [A B]]].\n  exists (Diverges t1); econstructor; eauto.\n  apply diverges_forever_silent; auto.\n(* 1.2 Reactive divergence *)\n  destruct (@reacts_forever_reactive s0) as [T FR].\n  intros.\n  generalize (not_ex_all_not _ _ H0 s1). intro A; clear H0.\n  generalize (not_ex_all_not _ _ A t1). intro B; clear A.\n  destruct (not_and_or _ _ B). contradiction.\n  destruct (not_all_ex_not _ _ H0) as [s2 C]; clear H0.\n  destruct (not_all_ex_not _ _ C) as [t2 D]; clear C.\n  destruct (imply_to_and _ _ D) as [E F]; clear D.\n  destruct (H s2 (t1 ** t2)) as [s3 [t3 G]]. eapply star_trans; eauto.\n  exists s3; exists (t2 ** t3); split.\n  eapply star_right; eauto.\n  red; intros. destruct (app_eq_nil t2 t3 H0). subst. elim F. exists s3; auto.\n  exists (Reacts T); econstructor; eauto.\n(* 2 Termination (normal or by going wrong) *)\n  destruct (not_all_ex_not _ _ H) as [s1 A]; clear H.\n  destruct (not_all_ex_not _ _ A) as [t1 B]; clear A.\n  destruct (imply_to_and _ _ B) as [C D]; clear B.\n  destruct (classic (exists r, final_state L s1 r)) as [[r FINAL] | NOTFINAL].\n(* 2.1 Normal termination *)\n  exists (Terminates t1 r); econstructor; eauto.\n(* 2.2 Going wrong *)\n  exists (Goes_wrong t1); econstructor; eauto. red. intros.\n  generalize (not_ex_all_not _ _ D s'); intros.\n  generalize (not_ex_all_not _ _ H t); intros.\n  auto.\nQed.\n\nTheorem program_behaves_exists:\n  exists beh, program_behaves beh.\nProof.\n  destruct (classic (exists s, initial_state L s)) as [[s0 INIT] | NOTINIT].\n(* 1. Initial state is defined. *)\n  destruct (state_behaves_exists s0) as [beh SB].\n  exists beh; econstructor; eauto.\n(* 2. Initial state is undefined *)\n  exists (Goes_wrong E0). apply program_goes_initially_wrong.\n  intros. eapply not_ex_all_not; eauto.\nQed.\n\nEnd PROGRAM_BEHAVIORS.\n\n(** * Forward simulations and program behaviors *)\n\nSection FORWARD_SIMULATIONS.\n\nVariable L1: semantics.\nVariable L2: semantics.\nVariable S: forward_simulation L1 L2.\n\nLemma forward_simulation_state_behaves:\n  forall i s1 s2 beh1,\n  S i s1 s2 -> state_behaves L1 s1 beh1 ->\n  exists beh2, state_behaves L2 s2 beh2 /\\ behavior_improves beh1 beh2.\nProof.\n  intros. inv H0.\n(* termination *)\n  exploit simulation_star; eauto. intros [i' [s2' [A B]]].\n  exists (Terminates t r); split.\n  econstructor; eauto. eapply fsim_match_final_states; eauto.\n  apply behavior_improves_refl.\n(* silent divergence *)\n  exploit simulation_star; eauto. intros [i' [s2' [A B]]].\n  exists (Diverges t); split.\n  econstructor; eauto. eapply simulation_forever_silent; eauto.\n  apply behavior_improves_refl.\n(* reactive divergence *)\n  exists (Reacts T); split.\n  econstructor. eapply simulation_forever_reactive; eauto.\n  apply behavior_improves_refl.\n(* going wrong *)\n  exploit simulation_star; eauto. intros [i' [s2' [A B]]].\n  destruct (state_behaves_exists L2 s2') as [beh' SB].\n  exists (behavior_app t beh'); split.\n  eapply state_behaves_app; eauto.\n  replace (Goes_wrong t) with (behavior_app t (Goes_wrong E0)).\n  apply behavior_improves_app. apply behavior_improves_bot.\n  simpl. decEq. traceEq.\nQed.\n\nTheorem forward_simulation_behavior_improves:\n  forall beh1, program_behaves L1 beh1 ->\n  exists beh2, program_behaves L2 beh2 /\\ behavior_improves beh1 beh2.\nProof.\n  intros. inv H.\n(* initial state defined *)\n  exploit (fsim_match_initial_states S); eauto. intros [i [s' [INIT MATCH]]].\n  exploit forward_simulation_state_behaves; eauto. intros [beh2 [A B]].\n  exists beh2; split; auto. econstructor; eauto.\n(* initial state undefined *)\n  destruct (classic (exists s', initial_state L2 s')).\n  destruct H as [s' INIT].\n  destruct (state_behaves_exists L2 s') as [beh' SB].\n  exists beh'; split. econstructor; eauto. apply behavior_improves_bot.\n  exists (Goes_wrong E0); split.\n  apply program_goes_initially_wrong.\n  intros; red; intros. elim H; exists s; auto.\n  apply behavior_improves_refl.\nQed.\n\nCorollary forward_simulation_same_safe_behavior:\n  forall beh,\n  program_behaves L1 beh -> not_wrong beh ->\n  program_behaves L2 beh.\nProof.\n  intros. exploit forward_simulation_behavior_improves; eauto.\n  intros [beh' [A B]]. destruct B.\n  congruence.\n  destruct H1 as [t [C D]]. subst. contradiction.\nQed.\n\nEnd FORWARD_SIMULATIONS.\n\n(** * Backward simulations and program behaviors *)\n\nSection BACKWARD_SIMULATIONS.\n\nVariable L1: semantics.\nVariable L2: semantics.\nVariable S: backward_simulation L1 L2.\n\nDefinition safe_along_behavior (s: state L1) (b: program_behavior) : Prop :=\n  forall t1 s' b2, Star L1 s t1 s' -> b = behavior_app t1 b2 ->\n     (exists r, final_state L1 s' r)\n  \\/ (exists t2, exists s'', Step L1 s' t2 s'').\n\nRemark safe_along_safe:\n  forall s b, safe_along_behavior s b -> safe L1 s.\nProof.\n  intros; red; intros. eapply H; eauto. symmetry; apply behavior_app_E0.\nQed.\n\nRemark star_safe_along:\n  forall s b t1 s' b2,\n  safe_along_behavior s b ->\n  Star L1 s t1 s' -> b = behavior_app t1 b2 ->\n  safe_along_behavior s' b2.\nProof.\n  intros; red; intros. eapply H. eapply star_trans; eauto.\n  subst. rewrite behavior_app_assoc. eauto.\nQed.\n\nRemark not_safe_along_behavior:\n  forall s b,\n  ~ safe_along_behavior s b ->\n  exists t, exists s',\n     behavior_prefix t b\n  /\\ Star L1 s t s'\n  /\\ Nostep L1 s'\n  /\\ (forall r, ~(final_state L1 s' r)).\nProof.\n  intros.\n  destruct (not_all_ex_not _ _ H) as [t1 A]; clear H.\n  destruct (not_all_ex_not _ _ A) as [s' B]; clear A.\n  destruct (not_all_ex_not _ _ B) as [b2 C]; clear B.\n  destruct (imply_to_and _ _ C) as [D E]; clear C.\n  destruct (imply_to_and _ _ E) as [F G]; clear E.\n  destruct (not_or_and _ _ G) as [P Q]; clear G.\n  exists t1; exists s'.\n  split. exists b2; auto.\n  split. auto.\n  split. red; intros; red; intros. elim Q. exists t; exists s'0; auto.\n  intros; red; intros. elim P. exists r; auto.\nQed.\n\nLemma backward_simulation_star:\n  forall s2 t s2', Star L2 s2 t s2' ->\n  forall i s1 b, S i s1 s2 -> safe_along_behavior s1 (behavior_app t b) ->\n  exists i', exists s1', Star L1 s1 t s1' /\\ S i' s1' s2'.\nProof.\n  induction 1; intros.\n  exists i; exists s1; split; auto. apply star_refl.\n  exploit (bsim_simulation S); eauto. eapply safe_along_safe; eauto.\n  intros [i' [s1' [A B]]].\n  assert (Star L1 s0 t1 s1'). intuition. apply plus_star; auto.\n  exploit IHstar; eauto. eapply star_safe_along; eauto.\n  subst t; apply behavior_app_assoc.\n  intros [i'' [s2'' [C D]]].\n  exists i''; exists s2''; split; auto. eapply star_trans; eauto.\nQed.\n\nLemma backward_simulation_forever_silent:\n  forall i s1 s2,\n  Forever_silent L2 s2 -> S i s1 s2 -> safe L1 s1 ->\n  Forever_silent L1 s1.\nProof.\n  assert (forall i s1 s2,\n         Forever_silent L2 s2 -> S i s1 s2 -> safe L1 s1 ->\n         forever_silent_N (step L1) (bsim_order S) (globalenv L1) i s1).\n    cofix COINDHYP; intros.\n    inv H.  destruct (bsim_simulation S _ _ _ H2 _ H0 H1) as [i' [s2' [A B]]].\n    destruct A as [C | [C D]].\n    eapply forever_silent_N_plus; eauto. eapply COINDHYP; eauto.\n      eapply star_safe; eauto. apply plus_star; auto.\n    eapply forever_silent_N_star; eauto. eapply COINDHYP; eauto.\n      eapply star_safe; eauto.\n  intros. eapply forever_silent_N_forever; eauto. apply bsim_order_wf.\nQed.\n\nLemma backward_simulation_forever_reactive:\n  forall i s1 s2 T,\n  Forever_reactive L2 s2 T -> S i s1 s2 -> safe_along_behavior s1 (Reacts T) ->\n  Forever_reactive L1 s1 T.\nProof.\n  cofix COINDHYP; intros. inv H.\n  destruct (backward_simulation_star H2 _ (Reacts T0) H0) as [i' [s1' [A B]]]; eauto.\n  econstructor; eauto. eapply COINDHYP; eauto. eapply star_safe_along; eauto.\nQed.\n\nLemma backward_simulation_state_behaves:\n  forall i s1 s2 beh2,\n  S i s1 s2 -> state_behaves L2 s2 beh2 ->\n  exists beh1, state_behaves L1 s1 beh1 /\\ behavior_improves beh1 beh2.\nProof.\n  intros. destruct (classic (safe_along_behavior s1 beh2)).\n(* 1. Safe along *)\n  exists beh2; split; [idtac|apply behavior_improves_refl].\n  inv H0.\n(* termination *)\n  assert (Terminates t r = behavior_app t (Terminates E0 r)).\n    simpl. rewrite E0_right; auto.\n  rewrite H0 in H1.\n  exploit backward_simulation_star; eauto.\n  intros [i' [s1' [A B]]].\n  exploit (bsim_match_final_states S); eauto.\n    eapply safe_along_safe. eapply star_safe_along; eauto.\n  intros [s1'' [C D]].\n  econstructor. eapply star_trans; eauto. traceEq. auto.\n(* silent divergence *)\n  assert (Diverges t = behavior_app t (Diverges E0)).\n    simpl. rewrite E0_right; auto.\n  rewrite H0 in H1.\n  exploit backward_simulation_star; eauto.\n  intros [i' [s1' [A B]]].\n  econstructor. eauto. eapply backward_simulation_forever_silent; eauto.\n  eapply safe_along_safe. eapply star_safe_along; eauto.\n(* reactive divergence *)\n  econstructor. eapply backward_simulation_forever_reactive; eauto.\n(* goes wrong *)\n  assert (Goes_wrong t = behavior_app t (Goes_wrong E0)).\n    simpl. rewrite E0_right; auto.\n  rewrite H0 in H1.\n  exploit backward_simulation_star; eauto.\n  intros [i' [s1' [A B]]].\n  exploit (bsim_progress S); eauto. eapply safe_along_safe. eapply star_safe_along; eauto.\n  intros [[r FIN] | [t' [s2' STEP2]]].\n  elim (H4 _ FIN).\n  elim (H3 _ _ STEP2).\n\n(* 2. Not safe along *)\n  exploit not_safe_along_behavior; eauto.\n  intros [t [s1' [PREF [STEPS [NOSTEP NOFIN]]]]].\n  exists (Goes_wrong t); split.\n  econstructor; eauto.\n  right. exists t; auto.\nQed.\n\nTheorem backward_simulation_behavior_improves:\n  forall beh2, program_behaves L2 beh2 ->\n  exists beh1, program_behaves L1 beh1 /\\ behavior_improves beh1 beh2.\nProof.\n  intros. inv H.\n(* L2's initial state is defined. *)\n  destruct (classic (exists s1, initial_state L1 s1)) as [[s1 INIT] | NOINIT].\n(* L1's initial state is defined too. *)\n  exploit (bsim_match_initial_states S); eauto. intros [i [s1' [INIT1' MATCH]]].\n  exploit backward_simulation_state_behaves; eauto. intros [beh1 [A B]].\n  exists beh1; split; auto. econstructor; eauto.\n(* L1 has no initial state *)\n  exists (Goes_wrong E0); split.\n  apply program_goes_initially_wrong.\n  intros; red; intros. elim NOINIT; exists s0; auto.\n  apply behavior_improves_bot.\n(* L2 has no initial state *)\n  exists (Goes_wrong E0); split.\n  apply program_goes_initially_wrong.\n  intros; red; intros.\n  exploit (bsim_initial_states_exist S); eauto. intros [s2 INIT2].\n  elim (H0 s2); auto.\n  apply behavior_improves_refl.\nQed.\n\nCorollary backward_simulation_same_safe_behavior:\n  (forall beh, program_behaves L1 beh -> not_wrong beh) ->\n  (forall beh, program_behaves L2 beh -> program_behaves L1 beh).\nProof.\n  intros. exploit backward_simulation_behavior_improves; eauto.\n  intros [beh' [A B]]. destruct B.\n  congruence.\n  destruct H1 as [t [C D]]. subst. elim (H (Goes_wrong t)). auto.\nQed.\n\nEnd BACKWARD_SIMULATIONS.\n\n(** * Program behaviors for the \"atomic\" construction *)\n\nSection ATOMIC.\n\nVariable L: semantics.\nHypothesis Lwb: well_behaved_traces L.\n\nRemark atomic_finish: forall s t, output_trace t -> Star (atomic L) (t, s) t (E0, s).\nProof.\n  induction t; intros.\n  apply star_refl.\n  simpl in H; destruct H. eapply star_left; eauto.\n  simpl. apply atomic_step_continue; auto. simpl; auto. auto.\nQed.\n\nLemma step_atomic_plus:\n  forall s1 t s2, Step L s1 t s2 -> SPlus (atomic L) (E0,s1) t (E0,s2).\nProof.\n  intros.  destruct t.\n  apply plus_one. simpl; apply atomic_step_silent; auto.\n  exploit Lwb; eauto. simpl; intros.\n  eapply plus_left. eapply atomic_step_start; eauto. eapply atomic_finish; eauto. auto.\nQed.\n\nLemma star_atomic_star:\n  forall s1 t s2, Star L s1 t s2 -> Star (atomic L) (E0,s1) t (E0,s2).\nProof.\n  induction 1. apply star_refl. eapply star_trans with (s2 := (E0,s2)).\n  apply plus_star. eapply step_atomic_plus; eauto. eauto. auto.\nQed.\n\nLemma atomic_forward_simulation: forward_simulation L (atomic L).\nProof.\n  set (ms := fun (s: state L) (ts: state (atomic L)) => ts = (E0,s)).\n  apply forward_simulation_plus with ms; intros.\n  auto.\n  exists (E0,s1); split. simpl; auto. red; auto.\n  red in H. subst s2. simpl; auto.\n  red in H0. subst s2. exists (E0,s1'); split.\n  apply step_atomic_plus; auto. red; auto.\nQed.\n\nLemma atomic_star_star_gen:\n  forall ts1 t ts2, Star (atomic L) ts1 t ts2 ->\n  exists t', Star L (snd ts1) t' (snd ts2) /\\ fst ts1 ** t' = t ** fst ts2.\nProof.\n  induction 1.\n  exists E0; split. apply star_refl. traceEq.\n  destruct IHstar as [t' [A B]].\n  simpl in H; inv H; simpl in *.\n  exists t'; split. eapply star_left; eauto. auto.\n  exists (ev :: t0 ** t'); split. eapply star_left; eauto. rewrite B; auto.\n  exists t'; split. auto. rewrite B; auto.\nQed.\n\nLemma atomic_star_star:\n  forall s1 t s2, Star (atomic L) (E0,s1) t (E0,s2) -> Star L s1 t s2.\nProof.\n  intros. exploit atomic_star_star_gen; eauto. intros [t' [A B]].\n  simpl in *. replace t with t'. auto. subst; traceEq.\nQed.\n\nLemma atomic_forever_silent_forever_silent:\n  forall s, Forever_silent (atomic L) s -> Forever_silent L (snd s).\nProof.\n  cofix COINDHYP; intros. inv H. inv H0.\n  apply forever_silent_intro with (snd (E0, s')). auto. apply COINDHYP; auto.\nQed.\n\nRemark star_atomic_output_trace:\n  forall s t t' s',\n  Star (atomic L) (E0, s) t (t', s') -> output_trace t'.\nProof.\n  assert (forall ts1 t ts2, Star (atomic L) ts1 t ts2 ->\n          output_trace (fst ts1) -> output_trace (fst ts2)).\n  induction 1; intros. auto. inv H; simpl in *.\n  apply IHstar. auto.\n  apply IHstar. exploit Lwb; eauto.\n  destruct H2. apply IHstar. auto.\n  intros. change t' with (fst (t',s')). eapply H; eauto. simpl; auto.\nQed.\n\nLemma atomic_forever_reactive_forever_reactive:\n  forall s T, Forever_reactive (atomic L) (E0,s) T -> Forever_reactive L s T.\nProof.\n  assert (forall t s T, Forever_reactive (atomic L) (t,s) T ->\n          exists T', Forever_reactive (atomic L) (E0,s) T' /\\ T = t *** T').\n  induction t; intros. exists T; auto.\n  inv H. inv H0. congruence. simpl in H; inv H.\n  destruct (IHt s (t2***T0)) as [T' [A B]]. eapply star_forever_reactive; eauto.\n  exists T'; split; auto. simpl. congruence.\n\n  cofix COINDHYP; intros. inv H0. destruct s2 as [t2 s2].\n  destruct (H _ _ _ H3) as [T' [A B]].\n  assert (Star (atomic L) (E0, s) (t**t2) (E0, s2)).\n    eapply star_trans. eauto. apply atomic_finish. eapply star_atomic_output_trace; eauto. auto.\n  replace (t *** T0) with ((t ** t2) *** T'). apply forever_reactive_intro with s2.\n  apply atomic_star_star; auto. destruct t; simpl in *; unfold E0 in *; congruence.\n  apply COINDHYP. auto.\n  subst T0; traceEq.\nQed.\n\nTheorem atomic_behaviors:\n  forall beh, program_behaves L beh <-> program_behaves (atomic L) beh.\nProof.\n  intros; split; intros.\n  (* L -> atomic L *)\n  exploit forward_simulation_behavior_improves. eapply atomic_forward_simulation. eauto.\n  intros [beh2 [A B]]. red in B. destruct B as [EQ | [t [C D]]].\n  congruence.\n  subst beh. inv H. inv H1.\n  apply program_runs with (E0,s). simpl; auto.\n  apply state_goes_wrong with (E0,s'). apply star_atomic_star; auto.\n  red; intros; red; intros. inv H. eelim H3; eauto. eelim H3; eauto.\n  intros; red; intros. simpl in H. destruct H. eelim H4; eauto.\n  apply program_goes_initially_wrong.\n  intros; red; intros. simpl in H; destruct H. eelim H1; eauto.\n  (* atomic L -> L *)\n  inv H.\n  (* initial state defined *)\n  destruct s as [t s]. simpl in H0. destruct H0; subst t.\n  apply program_runs with s; auto.\n  inv H1.\n  (* termination *)\n  destruct s' as [t' s']. simpl in H2; destruct H2; subst t'.\n  econstructor. eapply atomic_star_star; eauto. auto.\n  (* silent divergence *)\n  destruct s' as [t' s'].\n  assert (t' = E0). inv H2. inv H1; auto. subst t'.\n  econstructor. eapply atomic_star_star; eauto.\n  change s' with (snd (E0,s')). apply atomic_forever_silent_forever_silent. auto.\n  (* reactive divergence *)\n  econstructor. apply atomic_forever_reactive_forever_reactive. auto.\n  (* going wrong *)\n  destruct s' as [t' s'].\n  assert (t' = E0).\n    destruct t'; auto. eelim H2. simpl. apply atomic_step_continue.\n    eapply star_atomic_output_trace; eauto.\n  subst t'. econstructor. apply atomic_star_star; eauto.\n  red; intros; red; intros. destruct t0.\n  elim (H2 E0 (E0,s'0)). constructor; auto.\n  elim (H2 (e::nil) (t0,s'0)). constructor; auto.\n  intros; red; intros. elim (H3 r). simpl; auto.\n  (* initial state undefined *)\n  apply program_goes_initially_wrong.\n  intros; red; intros. elim (H0 (E0,s)); simpl; auto.\nQed.\n\nEnd ATOMIC.\n\n(** * Additional results about infinite reduction sequences *)\n\n(** We now show that any infinite sequence of reductions is either of\n  the \"reactive\" kind or of the \"silent\" kind (after a finite number\n  of non-silent transitions).  The proof necessitates the axiom of\n  excluded middle.  This result is used below to relate\n  the coinductive big-step semantics for divergence with the\n  small-step notions of divergence. *)\n\nUnset Implicit Arguments.\n\nSection INF_SEQ_DECOMP.\n\nVariable genv: Type.\nVariable state: Type.\nVariable step: genv -> state -> trace -> state -> Prop.\n\nVariable ge: genv.\n\nInductive tstate: Type :=\n  ST: forall (s: state) (T: traceinf), forever step ge s T -> tstate.\n\nDefinition state_of_tstate (S: tstate): state :=\n  match S with ST s T F => s end.\nDefinition traceinf_of_tstate (S: tstate) : traceinf :=\n  match S with ST s T F => T end.\n\nInductive tstep: trace -> tstate -> tstate -> Prop :=\n  | tstep_intro: forall s1 t T s2 S F,\n      tstep t (ST s1 (t *** T) (@forever_intro genv state step ge s1 t s2 T S F))\n              (ST s2 T F).\n\nInductive tsteps: tstate -> tstate -> Prop :=\n  | tsteps_refl: forall S, tsteps S S\n  | tsteps_left: forall t S1 S2 S3, tstep t S1 S2 -> tsteps S2 S3 -> tsteps S1 S3.\n\nRemark tsteps_trans:\n  forall S1 S2, tsteps S1 S2 -> forall S3, tsteps S2 S3 -> tsteps S1 S3.\nProof.\n  induction 1; intros. auto. econstructor; eauto.\nQed.\n\nLet treactive (S: tstate) : Prop :=\n  forall S1,\n  tsteps S S1 ->\n  exists S2, exists S3, exists t, tsteps S1 S2 /\\ tstep t S2 S3 /\\ t <> E0.\n\nLet tsilent (S: tstate) : Prop :=\n  forall S1 t S2, tsteps S S1 -> tstep t S1 S2 -> t = E0.\n\nLemma treactive_or_tsilent:\n  forall S, treactive S \\/ (exists S', tsteps S S' /\\ tsilent S').\nProof.\n  intros. destruct (classic (exists S', tsteps S S' /\\ tsilent S')).\n  auto.\n  left. red; intros.\n  generalize (not_ex_all_not _ _ H S1). intros.\n  destruct (not_and_or _ _ H1). contradiction.\n  unfold tsilent in H2.\n  generalize (not_all_ex_not _ _ H2). intros [S2 A].\n  generalize (not_all_ex_not _ _ A). intros [t B].\n  generalize (not_all_ex_not _ _ B). intros [S3 C].\n  generalize (imply_to_and _ _ C). intros [D F].\n  generalize (imply_to_and _ _ F). intros [G J].\n  exists S2; exists S3; exists t. auto.\nQed.\n\nLemma tsteps_star:\n  forall S1 S2, tsteps S1 S2 ->\n  exists t, star step ge (state_of_tstate S1) t (state_of_tstate S2)\n         /\\ traceinf_of_tstate S1 = t *** traceinf_of_tstate S2.\nProof.\n  induction 1.\n  exists E0; split. apply star_refl. auto.\n  inv H. destruct IHtsteps as [t' [A B]].\n  exists (t ** t'); split.\n  simpl; eapply star_left; eauto.\n  simpl in *. subst T. traceEq.\nQed.\n\nLemma tsilent_forever_silent:\n  forall S,\n  tsilent S -> forever_silent step ge (state_of_tstate S).\nProof.\n  cofix COINDHYP; intro S. case S. intros until f. simpl. case f. intros.\n  assert (tstep t (ST s1 (t *** T0) (forever_intro s1 t s0 f0))\n                  (ST s2 T0 f0)).\n    constructor.\n  assert (t = E0).\n    red in H. eapply H; eauto. apply tsteps_refl.\n  apply forever_silent_intro with (state_of_tstate (ST s2 T0 f0)).\n  rewrite <- H1. assumption.\n  apply COINDHYP.\n  red; intros. eapply H. eapply tsteps_left; eauto. eauto.\nQed.\n\nLemma treactive_forever_reactive:\n  forall S,\n  treactive S -> forever_reactive step ge (state_of_tstate S) (traceinf_of_tstate S).\nProof.\n  cofix COINDHYP; intros.\n  destruct (H S) as [S1 [S2 [t [A [B C]]]]]. apply tsteps_refl.\n  destruct (tsteps_star _ _ A) as [t' [P Q]].\n  inv B. simpl in *. rewrite Q. rewrite <- Eappinf_assoc.\n  apply forever_reactive_intro with s2.\n  eapply star_right; eauto.\n  red; intros. destruct (Eapp_E0_inv _ _ H0). contradiction.\n  change (forever_reactive step ge (state_of_tstate (ST s2 T F)) (traceinf_of_tstate (ST s2 T F))).\n  apply COINDHYP.\n  red; intros. apply H.\n  eapply tsteps_trans. eauto.\n  eapply tsteps_left. constructor. eauto.\nQed.\n\nTheorem forever_silent_or_reactive:\n  forall s T,\n  forever step ge s T ->\n  forever_reactive step ge s T \\/\n  exists t, exists s', exists T',\n  star step ge s t s' /\\ forever_silent step ge s' /\\ T = t *** T'.\nProof.\n  intros.\n  destruct (treactive_or_tsilent (ST s T H)).\n  left.\n  change (forever_reactive step ge (state_of_tstate (ST s T H)) (traceinf_of_tstate (ST s T H))).\n  apply treactive_forever_reactive. auto.\n  destruct H0 as [S' [A B]].\n  exploit tsteps_star; eauto. intros [t [C D]]. simpl in *.\n  right. exists t; exists (state_of_tstate S'); exists (traceinf_of_tstate S').\n  split. auto.\n  split. apply tsilent_forever_silent. auto.\n  auto.\nQed.\n\nEnd INF_SEQ_DECOMP.\n\nSet Implicit Arguments.\n\n(** * Big-step semantics and program behaviors *)\n\nSection BIGSTEP_BEHAVIORS.\n\nVariable B: bigstep_semantics.\nVariable L: semantics.\nHypothesis sound: bigstep_sound B L.\n\nLemma behavior_bigstep_terminates:\n  forall t r,\n  bigstep_terminates B t r -> program_behaves L (Terminates t r).\nProof.\n  intros. exploit (bigstep_terminates_sound sound); eauto.\n  intros [s1 [s2 [P [Q R]]]].\n  econstructor; eauto. econstructor; eauto.\nQed.\n\nLemma behavior_bigstep_diverges:\n  forall T,\n  bigstep_diverges B T ->\n  program_behaves L (Reacts T)\n  \\/ exists t, program_behaves L (Diverges t) /\\ traceinf_prefix t T.\nProof.\n  intros. exploit (bigstep_diverges_sound sound); eauto. intros [s1 [P Q]].\n  exploit forever_silent_or_reactive; eauto. intros [X | [t [s' [T' [X [Y Z]]]]]].\n  left. econstructor; eauto. constructor; auto.\n  right. exists t; split. econstructor; eauto. econstructor; eauto. exists T'; auto.\nQed.\n\nEnd BIGSTEP_BEHAVIORS.\n", "meta": {"author": "Aurele-Barriere", "repo": "JIThm", "sha": "ad3ae5a3d6759a070195815e321df1b372d982b9", "save_path": "github-repos/coq/Aurele-Barriere-JIThm", "path": "github-repos/coq/Aurele-Barriere-JIThm/JIThm-ad3ae5a3d6759a070195815e321df1b372d982b9/coqjit/customBehaviors.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23376978693807124}}
{"text": "From Tealeaves Require Export\n  Functors.List\n  Categories.TypeFamilies\n  Classes.Kleisli.Decorated.Monad (* preincr *)\n  Multisorted.Classes.DTM.\n\nFrom Tealeaves.Backends.LN Require Import\n  Atom AtomSet AssocList Multisorted.LN.\n\nImport AtomSet.Notations.\nImport Tealeaves.Classes.Monoid.Notations.\nImport Tealeaves.Data.Product.Notations.\nImport Tealeaves.Classes.Applicative.Notations.\nImport Multisorted.Classes.DTM.Notations.\nImport List.ListNotations.\n\n#[local] Generalizable Variables F G A B C ϕ.\n\n(** * The index [K] *)\n(******************************************************************************)\nInductive K2 : Type := KType | KTerm.\n\n#[export] Instance Keq : EqDec K2 eq.\nProof.\n  change (forall x y : K2, {x = y} + {x <> y}).\n  decide equality.\nDefined.\n\n#[export] Instance I2 : Index := {| K := K2 |}.\n\n(** * System F syntax and typeclass instances *)\n(******************************************************************************)\nParameter base_typ : Type.\n\nSection syntax.\n\n  Context\n    {V : Type}.\n\n  Inductive typ : Type :=\n  | ty_c : base_typ -> typ\n  | ty_v : V -> typ\n  | ty_ar : typ -> typ -> typ\n  | ty_univ : typ -> typ.\n\n  Inductive term : Type :=\n  | tm_var : V -> term\n  | tm_abs : typ -> term -> term\n  | tm_app : term -> term -> term\n  | tm_tab : term -> term\n  | tm_tap : term -> typ -> term.\n\nEnd syntax.\n\n(** Clear the implicit arguments to the type constructors. This keeps <<V>>\n    implicit for the constructors. *)\nArguments typ V : clear implicits.\nArguments term V : clear implicits.\n\nDefinition SystemF (k : K) (v : Type) : Type :=\n  match k with\n  | KType => typ v\n  | KTerm => term v\n  end.\n\n(** ** Notations *)\n(******************************************************************************)\nModule Notations.\n\n  Declare Scope SystemF_scope.\n\n  (** *** Notations for type expressions *)\n  Notation \"A ⟹ B\" := (ty_ar A B) (at level 51, right associativity) : SystemF_scope.\n  Notation \"∀ τ\" := (ty_univ τ) (at level 60) : SystemF_scope.\n\n  (** *** Notations for term expressions *)\n  Notation \"'λ' X ⋅ body\" := (tm_abs X body) (at level 45) : SystemF_scope.\n  Notation \"t1 @ t2\" := (tm_app t1 t2) (at level 40) : SystemF_scope.\n  Notation \"'Λ' body\" := (tm_tab body) (at level 45) : SystemF_scope.\n  Notation \"t1 @@ t2\" := (tm_tap t1 t2) (at level 40) : SystemF_scope.\n\n  (** *** Coercions from variables to leaves *)\n  Coercion Fr : atom >-> LN.\n  Coercion Bd : nat >-> LN.\n\n  (** *** Coercions from leaves to term expressions *)\n  Definition tm_var_ : LN -> term LN := @tm_var LN.\n  Coercion tm_var_ : LN >-> term.\n\n  (** *** Coercions from leaves to type expressions *)\n  Definition c_base_type: base_typ -> typ LN := @ty_c LN.\n  Definition c_LN_type : LN -> typ LN := @ty_v LN.\n  Coercion c_base_type : base_typ >-> typ.\n  Coercion c_LN_type : LN >-> typ.\n\nEnd Notations.\n\nOpen Scope SystemF_scope.\nImport Notations.\n\n(** ** Example expressions *)\n(******************************************************************************)\nModule examples.\n\n  Context\n    (x y z : atom)\n    (c1 c2 c3 : base_typ).\n\n  (** *** Raw abstract syntax *)\n  (** Abstract syntax trees without notations or coercions *)\n  (******************************************************************************)\n\n  (** *** Constants and variables *)\n  Example typ_1 : typ LN := ty_v (Fr x).\n  Example typ_2 : typ LN := ty_v (Fr y).\n  Example typ_3 : typ LN := ty_v (Fr z).\n  Example typ_4 : typ LN := ty_v (Bd 0).\n  Example typ_5 : typ LN := ty_v (Bd 1).\n  Example typ_6 : typ LN := ty_v (Bd 2).\n  Example typ_7 : typ LN := ty_c c1.\n  Example typ_8 : typ LN := ty_c c2.\n\n  (** *** Simple types *)\n  Example typ_9  : typ LN := ty_ar (ty_v (Fr x))\n                                     (ty_v (Fr x)).\n  Example typ_10 : typ LN := ty_ar (ty_v (Fr x))\n                                     (ty_v (Fr y)).\n  Example typ_11 : typ LN := ty_ar (ty_v (Fr x))\n                                     (ty_v (Bd 1)).\n  Example typ_12 : typ LN := ty_ar (ty_v (Bd 1))\n                                     (ty_c c1).\n  Example typ_13 : typ LN := ty_ar (ty_ar (ty_v (Bd 0))\n                                            (ty_v (Fr x)))\n                                     (ty_v (Bd 1)).\n  Example typ_14 : typ LN := ty_ar (ty_c c2)\n                                     (ty_ar (ty_v (Fr x))\n                                            (ty_v (Bd 1))).\n  Example typ_15 : typ LN := ty_ar (ty_ar (ty_v (Bd 2))\n                                            (ty_c c1))\n                                     (ty_ar (ty_v (Fr y))\n                                            (ty_v (Fr x))).\n  Example typ_16 : typ LN := ty_ar (ty_ar (ty_v (Bd 2))\n                                            (ty_v (Bd 1)))\n                                     (ty_ar (ty_v (Fr y))\n                                            (ty_v (Fr x))).\n\n  (** *** Universal types *)\n  Example typ_17 : typ LN := ty_univ (ty_ar (ty_v (Bd 0))\n                                              (ty_v (Bd 0))).\n  Example typ_18 : typ LN := ty_univ (ty_ar (ty_ar (ty_v (Bd 2))\n                                                     (ty_v (Bd 1)))\n                                              (ty_ar (ty_v (Fr y))\n                                                     (ty_v (Fr x)))).\n\n  (** *** Printy printed syntax *)\n  (******************************************************************************)\n  Module pretty.\n\n    #[local] Open Scope SystemF_scope.\n\n    Compute (0 : typ LN).\n    Compute (x : typ LN).\n    Compute (c1 : typ LN).\n\n    (** Constants and variables *)\n    Example typ_1 : typ LN := x.\n    Example typ_2 : typ LN := y.\n    Example typ_3 : typ LN := Fr z.\n    Example typ_4 : typ LN := 0.\n    Example typ_5 : typ LN := Bd 1.\n    Example typ_6 : typ LN := 2.\n    Example typ_7 : typ LN := c1.\n    Example typ_8 : typ LN := c2.\n\n    (** Simple types *)\n    Example typ_9  : typ LN := x ⟹ x.\n    Example typ_10 : typ LN := x ⟹ y.\n\n    Goal ((x ⟹ x : typ LN) = Fr x ⟹ Fr x). reflexivity. Qed.\n    Goal ((x ⟹ 1 : typ LN) = Fr x ⟹ Bd 1). reflexivity. Qed.\n\n    Example typ_11 : typ LN := x ⟹ 1.\n    Example typ_12 : typ LN := x ⟹ c1.\n    Example typ_13 : typ LN := (x ⟹ 0) ⟹ 1.\n    Example typ_14 : typ LN := c2 ⟹ (x ⟹ 1).\n\n    Goal c2 ⟹ x ⟹ 1 = c2 ⟹ (x ⟹ 1). reflexivity. Qed.\n\n    Example typ_15 : typ LN := (2 ⟹ c1) ⟹ (y ⟹ x).\n    Example typ_16 : typ LN := (2 ⟹ 1) ⟹ (y ⟹ x).\n\n    (** Universal types *)\n    Example typ_17 : typ LN := ∀ (0 ⟹ 0).\n    Goal ∀ (0 ⟹ 0) = ∀ 0 ⟹ 0. reflexivity. Qed.\n\n    Example typ_18 : typ LN := ∀ (2 ⟹ 1) ⟹ (y ⟹ x).\n    Goal ∀ (2 ⟹ 1) ⟹ (y ⟹ x) = ∀ ((2 ⟹ 1) ⟹ (y ⟹ x)). reflexivity. Qed.\n\n    Example typ_19 : typ LN := (∀ 2 ⟹ 1) ⟹ (y ⟹ x).\n    Example typ_20 : typ LN := (2 ⟹ 1) ⟹ ∀ y ⟹ x.\n\n  End pretty.\n\n  Example term_1 : term LN := tm_var (Fr x).\n  Example term_2 : term LN := tm_var (Bd 0).\n  Example term_3 : term LN := tm_app term_1 term_2.\n  Example term_4 : term LN := tm_app term_3 term_3.\n\n  (** Identity function on type [c1]. *)\n  Example term_5 : term LN := tm_abs (ty_c c1) (tm_var (Bd 0)).\n  Example term_6 : term LN := tm_app term_5 term_3.\n\n  (** Polymorphic identity function. *)\n  Example term_7 : term LN := tm_tab (tm_abs (ty_v (Bd 0))(tm_var (Bd 0))).\n\n  (** Instantiate identity at <<c1>> *)\n  Example term_8 : term LN := tm_tap term_7 c1.\n\n  #[local] Open Scope SystemF_scope.\n\n  Example term_9 : term LN := (Λ λ 0 ⋅ 0).\n\nEnd examples.\n\n(** ** <<binddt>> operations *)\n(******************************************************************************)\nSection operations.\n\n  Context\n    (F : Type -> Type)\n    `{Applicative F}\n    {A B : Type}.\n\n  Fixpoint bind_type (f : forall (k : K), list K2 * A -> F (SystemF k B)) (t : typ A) : F (typ B) :=\n    match t with\n    | ty_c t =>\n      pure F (ty_c t)\n    | ty_v a =>\n      f KType (nil, a)\n    | ty_ar t1 t2 =>\n      pure F (ty_ar) <⋆> (bind_type f t1) <⋆> (bind_type f t2)\n    | ty_univ body =>\n      pure F (ty_univ) <⋆> (bind_type (fun k => preincr [KType] (f k)) body)\n    end.\n\n  Fixpoint bind_term (f : forall (k : K), list K2 * A -> F (SystemF k B)) (t : term A) : F (term B) :=\n    match t with\n    | tm_var a =>\n      f KTerm (nil, a)\n    | tm_abs ty body =>\n      pure F (tm_abs)\n           <⋆> bind_type (fun k => f k) ty\n           <⋆> bind_term (fun k => f k ∘ incr [KTerm]) body\n    | tm_app t1 t2 =>\n      pure F tm_app <⋆> bind_term f t1 <⋆> bind_term f t2\n    | tm_tab body =>\n      pure F tm_tab <⋆> (bind_term (fun k => f k ∘ incr [KType]) body)\n    | tm_tap t1 ty =>\n      pure F tm_tap <⋆> bind_term f t1 <⋆> bind_type f ty\n    end.\n\nEnd operations.\n\n#[export] Instance MReturn_SystemF : MReturn SystemF :=\n  fun A k => match k with\n          | KType => ty_v\n          | KTerm => tm_var\n          end.\n\n#[export] Instance MBind_type : MBind (list K2) SystemF typ := @bind_type.\n#[export] Instance MBind_term : MBind (list K2) SystemF term := @bind_term.\n#[export] Instance MBind_SystemF : forall k, MBind (list K2) SystemF (SystemF k) :=\n  ltac:(intros [|]; typeclasses eauto).\n\n(** ** Example computations *)\n(******************************************************************************)\nSection example_computations.\n\n  Open Scope SystemF_scope.\n\n  Context\n    (x y z : atom)\n    (c1 c2 c3 : base_typ).\n\n  (** ** Demo of opening operation *)\n  Goal open (T := SystemF) typ KType (Fr x) (Bd 0) = Fr x. reflexivity. Qed.\n  Goal open typ KType (Fr x) (Bd 1) = Bd 0. reflexivity. Qed.\n  Goal open typ KType (Fr x) (Fr x) = Fr x. reflexivity. Qed.\n  Goal open typ KType (Fr x) (Fr y) = Fr y. reflexivity. Qed.\n  Goal open typ KType (Fr y) (Fr x) = Fr x. reflexivity. Qed.\n  Goal open typ KType (Fr y) (Fr y) = Fr y. reflexivity. Qed.\n  Goal open typ KType (Fr x) (∀ Bd 0) = (∀ (Bd 0)). reflexivity. Qed.\n  Goal open typ KType (Fr x) (∀ Bd 1) = (∀ (Fr x)). reflexivity. Qed.\n  Goal open typ KType (Fr x) (∀ (Bd 1 ⟹ Bd 0)) = (∀ Fr x ⟹ Bd 0). reflexivity. Qed.\n  Goal open typ KType (Fr x) (∀ Bd 1 ⟹ Bd 2) = (∀ Fr x ⟹ Bd 1). reflexivity. Qed.\n\nEnd example_computations.\n\n(** * Proofs of the DTM axioms *)\n(******************************************************************************)\n\n(** ** Helper lemmas for proving DTM axioms *)\n(******************************************************************************)\nSection DTM_instance_lemmas.\n\n  Context\n    (W : Type)\n    (S : Type -> Type)\n    (T : K -> Type -> Type)\n    `{! MReturn T}\n    `{! MBind W T S}\n    `{! forall k, MBind W T (T k)}\n    {mn_op : Monoid_op W}\n    {mn_unit : Monoid_unit W}.\n\n  Lemma mbinddt_inst_law1_case1 : forall (A : Type) (t : S A) (w : W),\n      (mbinddt S (fun A => A) (fun k => mret T k ∘ extract (W ×)) t = t) ->\n      (mbinddt S (fun A => A) (fun k => mret T k ∘ extract (W ×) ∘ incr w) t = t).\n  Proof.\n    introv IH. rewrite <- IH at 2.\n    fequal. ext k [w' a]. easy.\n  Qed.\n\n  Lemma mbinddt_inst_law1_case12 : forall (A : Type) (w : W),\n      mbinddt S (fun A => A) (fun k => mret T k ∘ extract (W ×)) (A := A) =\n      mbinddt S (fun A => A) (fun k => mret T k ∘ extract (W ×) ∘ incr w).\n  Proof.\n    introv. fequal. now ext k [w' a].\n  Qed.\n\n  Context\n    `{Applicative G}\n    `{Applicative F}\n    `{! Monoid W}\n    {A B C : Type}\n    (g : forall k, W * B -> G (T k C))\n    (f : forall k, W * A -> F (T k B)).\n\n  (* for Var case *)\n  Lemma mbinddt_inst_law2_case2 : forall (a : A) (k : K),\n    fmap F (mbinddt (T k) G g) (f k (Ƶ, a)) =\n    fmap F (mbinddt (T k) G (fun k => g k ∘ const (incr Ƶ) k)) (f k (Ƶ, a)).\n  Proof.\n    intros. repeat fequal. ext k' [w b].\n    unfold compose. cbn. now simpl_monoid.\n  Qed.\n\n  Lemma compose_dtm_incr : forall (w : W),\n      (fun k => (g ⋆dtm f) k ∘ incr w) =\n      ((fun k => g k ∘ incr w) ⋆dtm (fun k => f k ∘ incr w)).\n  Proof.\n    intros. ext k [w' a].\n    cbn. do 2 fequal.\n    ext j [w'' b].\n    unfold compose. cbn. fequal.\n    now rewrite monoid_assoc.\n  Qed.\n\nEnd DTM_instance_lemmas.\n\nArguments compose_dtm_incr {W}%type_scope {T}%function_scope {H}%function_scope {mn_op mn_unit}\n  {G}%function_scope {H0 H1 H2} {F}%function_scope {H4 H5 H6 Monoid0} {A B C}%type_scope (_\n  _)%function_scope _.\n\n(** ** <<mbinddt_mret>> *)\n(******************************************************************************)\nLemma mbinddt_mret_typ : forall (A : Type),\n    mbinddt typ (fun A => A) (fun k => mret SystemF k ∘ extract (list K2 ×)) = @id (typ A).\nProof.\n  intros. ext t. unfold id. induction t.\n  - cbn. reflexivity.\n  - cbn. reflexivity.\n  - cbn. fequal.\n    + apply IHt1.\n    + apply IHt2.\n  - cbn. fequal.\n    unfold preincr.\n    rewrite <- mbinddt_inst_law1_case12.\n    apply IHt.\nQed.\n\nLemma mbinddt_mret_term : forall (A : Type),\n    mbinddt term (fun A => A) (fun k => mret SystemF k ∘ extract (list K2 ×)) = @id (term A).\nProof.\n  intros. ext t. unfold id. induction t.\n  - easy.\n  - cbn. fequal.\n    + change (bind_type ?F ?f) with (mbinddt typ F f).\n      now rewrite mbinddt_mret_typ.\n    + rewrite <- mbinddt_inst_law1_case12.\n      apply IHt.\n  - cbn. fequal.\n    + apply IHt1.\n    + apply IHt2.\n  - cbn. fequal.\n    rewrite <- mbinddt_inst_law1_case12.\n    apply IHt.\n  - cbn. fequal.\n    + apply IHt.\n    + now rewrite mbinddt_mret_typ.\nQed.\n\n(** ** <<mbinddt_mbinddt>> *)\n(******************************************************************************)\nLemma mbinddt_mbinddt_typ :\n  forall (F : Type -> Type)\n    (G : Type -> Type)\n    `{Applicative F}\n    `{Applicative G}\n    `(g : forall k, list K2 * B -> G (SystemF k C))\n    `(f : forall k, list K2 * A -> F (SystemF k B)),\n    fmap F (mbinddt typ G g) ∘ mbinddt typ F f =\n    mbinddt typ (F ∘ G) (g ⋆dtm f).\nProof.\n  intros. ext t. generalize dependent f. generalize dependent g.\n  unfold compose at 1. induction t; intros g f.\n  - cbn.\n    rewrite (app_pure_natural F).\n    reflexivity.\n  - cbn.\n    change (MBind_type ?G H3 H4 H5 ?A ?B) with (mbinddt typ G (A := A) (B := B)).\n    change [] with (Ƶ : list K2).\n    change typ with (SystemF KType).\n    rewrite <- (mbinddt_inst_law2_case2 (list K2) SystemF (H := MBind_SystemF )).\n    reflexivity.\n  - cbn.\n    rewrite <- IHt1.\n    rewrite <- IHt2.\n    do 2 rewrite (ap_compose2 G F).\n    rewrite <- (ap_fmap (G := F)).\n    rewrite <- (ap_fmap (G := F)).\n    do 2 rewrite fmap_ap.\n    do 2 rewrite fmap_ap.\n    do 3 (compose near (pure (F ∘ G) (ty_ar (V := C)));\n          rewrite (fun_fmap_fmap F)).\n    unfold_ops @Pure_compose.\n    rewrite (app_pure_natural F).\n    rewrite (app_pure_natural F).\n    reflexivity.\n  - cbn. setoid_rewrite compose_dtm_incr.\n    rewrite <- IHt.\n    rewrite (ap_compose2 G F).\n    rewrite <- (ap_fmap (G := F)).\n    compose near (pure (F ∘ G) (ty_univ (V := C))).\n    rewrite (fun_fmap_fmap F).\n    unfold_ops @Pure_compose.\n    rewrite (app_pure_natural F).\n    rewrite fmap_ap.\n    rewrite (app_pure_natural F).\n    reflexivity.\nQed.\n\nLemma mbinddt_mbinddt_term :\n  forall (F : Type -> Type)\n    (G : Type -> Type)\n    `{Applicative F}\n    `{Applicative G}\n    `(g : forall k, list K2 * B -> G (SystemF k C))\n    `(f : forall k, list K2 * A -> F (SystemF k B)),\n    fmap F (mbinddt term G g) ∘ mbinddt term F f =\n    mbinddt term (F ∘ G) (g ⋆dtm f).\nProof.\n  intros. ext t. generalize dependent f. generalize dependent g.\n  unfold compose at 1. induction t; intros g f.\n  - cbn.\n    change (MBind_term ?G H3 H4 H5 ?A ?B) with (mbinddt term G (A := A) (B := B)).\n    fequal. fequal. now ext k [w a].\n  - cbn.\n    change (bind_type ?F ?f) with (mbinddt typ F f).\n    setoid_rewrite compose_dtm_incr.\n    rewrite <- IHt.\n    rewrite <- (mbinddt_mbinddt_typ F G).\n    unfold compose at 6.\n    do 2 rewrite (ap_compose2 G F).\n    unfold compose.\n    do 2 rewrite <- (ap_fmap (G := F)).\n    unfold_ops @Pure_compose.\n    rewrite (app_pure_natural F).\n    do 4 rewrite fmap_ap.\n    compose near ((pure F (ap G (pure G (@tm_abs C))))).\n    rewrite (fun_fmap_fmap F).\n    do 3 rewrite (app_pure_natural F).\n    reflexivity.\n  - cbn.\n    rewrite <- IHt1.\n    rewrite <- IHt2.\n    do 2 rewrite (ap_compose2 G F).\n    do 2 rewrite <- (ap_fmap (G := F)).\n    do 4 rewrite fmap_ap.\n    compose near (pure (F ∘ G) (@tm_app C)).\n    rewrite (fun_fmap_fmap F).\n    compose near (pure (F ∘ G) (@tm_app C)).\n    rewrite (fun_fmap_fmap F).\n    compose near (pure (F ∘ G) (@tm_app C)).\n    rewrite (fun_fmap_fmap F).\n    unfold_ops @Pure_compose.\n    do 2 rewrite (app_pure_natural F).\n    reflexivity.\n  - cbn.\n    setoid_rewrite compose_dtm_incr.\n    rewrite <- IHt.\n    rewrite (ap_compose2 G F).\n    rewrite <- (ap_fmap (G := F)).\n    rewrite fmap_ap.\n    unfold_ops @Pure_compose.\n    do 3 rewrite (app_pure_natural F).\n    reflexivity.\n  - cbn.\n    rewrite <- IHt.\n    rewrite <- (mbinddt_mbinddt_typ F G).\n    unfold compose at 4.\n    do 2 rewrite (ap_compose2 G F).\n    repeat rewrite <- (ap_fmap (G := F)).\n    change (bind_type ?F ?f) with (mbinddt typ F f).\n    do 4 rewrite fmap_ap.\n    compose near (pure (F ∘ G) (@tm_tap C)).\n    rewrite (fun_fmap_fmap F).\n    compose near (pure (F ∘ G) (@tm_tap C)).\n    rewrite (fun_fmap_fmap F).\n    compose near (pure (F ∘ G) (@tm_tap C)).\n    rewrite (fun_fmap_fmap F).\n    unfold_ops @Pure_compose.\n    rewrite (app_pure_natural F).\n    rewrite (app_pure_natural F).\n    reflexivity.\nQed.\n\n(** ** <<mbinddt_morphism>> *)\n(******************************************************************************)\n\n#[local] Set Keyed Unification.\n\nLemma mbinddt_morphism_typ :\n  forall (F : Type -> Type)\n    (G : Type -> Type)\n    `{ApplicativeMorphism F G ϕ}\n    `(f : forall k, list K2 * A -> F (SystemF k B)),\n    ϕ (typ B) ∘ mbinddt typ F f =\n    mbinddt typ G (fun k => ϕ (SystemF k B) ∘ f k).\nProof.\n  intros. ext t. generalize dependent f. unfold compose. induction t; intro f.\n  - cbn. rewrite (appmor_pure F G). reflexivity.\n  - reflexivity.\n  - cbn.\n    rewrite <- IHt1. clear IHt1.\n    rewrite <- IHt2. clear IHt2.\n    rewrite ap_morphism_1.\n    rewrite ap_morphism_1.\n    rewrite (appmor_pure F G).\n    reflexivity.\n  - cbn.\n    rewrite <- IHt. clear IHt.\n    rewrite ap_morphism_1.\n    rewrite (appmor_pure F G).\n    reflexivity.\nQed.\n\nLemma mbinddt_morphism_term :\n  forall (F : Type -> Type)\n    (G : Type -> Type)\n    `{ApplicativeMorphism F G ϕ}\n    `(f : forall k, list K2 * A -> F (SystemF k B)),\n    ϕ (term B) ∘ mbinddt term F f =\n    mbinddt term G (fun k => ϕ (SystemF k B) ∘ f k).\nProof.\n  intros. ext t. generalize dependent f. unfold compose. induction t; intro f.\n  - reflexivity.\n  - cbn.\n    rewrite <- IHt. clear IHt.\n    do 2 rewrite ap_morphism_1.\n    rewrite (appmor_pure F G).\n    change (bind_type ?F ?f) with (mbinddt typ F f).\n    compose near t on left.\n    rewrite (mbinddt_morphism_typ F G).\n    reflexivity.\n  - cbn.\n    rewrite <- IHt1. clear IHt1.\n    rewrite <- IHt2. clear IHt2.\n    rewrite ap_morphism_1.\n    rewrite ap_morphism_1.\n    rewrite (appmor_pure F G).\n    reflexivity.\n  - cbn.\n    rewrite <- IHt. clear IHt.\n    rewrite ap_morphism_1.\n    rewrite (appmor_pure F G).\n    reflexivity.\n  - cbn.\n    rewrite <- IHt. clear IHt.\n    do 2 rewrite ap_morphism_1.\n    rewrite (appmor_pure F G).\n    change (bind_type ?F ?f) with (mbinddt typ F f).\n    compose near t0 on left.\n    rewrite (mbinddt_morphism_typ F G).\n    reflexivity.\nQed.\n\n#[local] Unset Keyed Unification.\n\n(** ** <<mbinddt_comp_mret>> *)\n(******************************************************************************)\nLemma mbinddt_comp_mret_typ :\n  forall (F : Type -> Type)\n    `{Applicative F}\n    `(f : forall k, list K2 * A -> F (SystemF k B)),\n    mbinddt typ F f ∘ mret SystemF KType = f KType ∘ pair nil.\nProof.\n  reflexivity.\nQed.\n\nLemma mbinddt_comp_mret_term :\n  forall (F : Type -> Type)\n    `{Applicative F}\n    `(f : forall k, list K2 * A -> F (SystemF k B)),\n    mbinddt term F f ∘ mret SystemF KTerm = f KTerm ∘ pair nil.\nProof.\n  reflexivity.\nQed.\n\nCorollary mbinddt_comp_mret_F :\n  forall k F `{Applicative F}\n    `(f : forall k, (list K2) * A -> F (SystemF k B)),\n    mbinddt (W := list K2) (T := SystemF) (SystemF k) F f ∘ mret SystemF k = (fun a => f k (Ƶ, a)).\nProof.\n  intro k. destruct k.\n  - apply mbinddt_comp_mret_typ.\n  - apply mbinddt_comp_mret_term.\nQed.\n\n(** ** <<DTPreModule>> instances *)\n(******************************************************************************)\n#[export] Instance DTP_typ: DTPreModule (list K2) typ SystemF :=\n  {| dtp_mbinddt_mret := @mbinddt_mret_typ;\n     dtp_mbinddt_mbinddt := @mbinddt_mbinddt_typ;\n     dtp_mbinddt_morphism := @mbinddt_morphism_typ;\n  |}.\n\n#[export] Instance DTP_term: DTPreModule (list K2) term SystemF :=\n  {| dtp_mbinddt_mret := @mbinddt_mret_term;\n     dtp_mbinddt_mbinddt := @mbinddt_mbinddt_term;\n     dtp_mbinddt_morphism := @mbinddt_morphism_term;\n  |}.\n\n#[export] Instance: forall k, DTPreModule (list K2) (SystemF k) SystemF :=\n  fun k => match k with\n        | KType => DTP_typ\n        | KTerm => DTP_term\n        end.\n\n#[export] Instance: DTM (list K2) SystemF :=\n  {| dtm_mbinddt_comp_mret := mbinddt_comp_mret_F;\n  |}.\n\n(** * System F type system and operational rules *)\n(******************************************************************************)\nReserved Notation \"Δ ; Γ ⊢ t : τ\" (at level 90, t at level 99).\n\nImport Tealeaves.Classes.Setlike.Functor.Notations.\nExport LN.AtomSet.Notations.\nExport LN.AssocList.Notations.\n\n(** ** Contexts and well-formedness predicates *)\n(******************************************************************************)\n\n(** *** Context of type variables *)\nDefinition kind_ctx := alist unit.\n\n(** *** Context of term variables *)\nDefinition type_ctx := alist (typ LN).\n\n(** *** Well-formedness for kinding contexts *)\n(** A kinding context is well-formed when its keys, i.e. type\n    variables, are unique. *)\nDefinition ok_kind_ctx : kind_ctx -> Prop := uniq.\n\n(** *** Well-formedness of type expressions in a kinding context *)\n(** A type is well-formed in a kinding context <<Δ>> when all of its\n    type variables appear in Δ and the type is locally closed. *)\nDefinition ok_type : kind_ctx -> typ LN -> Prop :=\n  fun Δ τ => scoped typ KType τ (domset Δ) /\\ locally_closed typ KType τ.\n\n(** *** Well-formedness for typing contexts *)\n(** A typing context <<Γ>> is well-formed in kinding context <<Δ>>\n    when the keys of <<Γ>> (i.e. term variables) are unique, and each\n    associated type is itself well-formed in context <<Δ>>. *)\nDefinition ok_type_ctx : kind_ctx -> type_ctx -> Prop :=\n  fun Δ Γ => uniq Γ /\\ forall τ, τ ∈ range Γ -> ok_type Δ τ.\n\n(** *** Well-formedness of term expressions in context *)\n(** A term <<t>> is well-formed in contexts <<Δ>> and <<Γ>> when its\n    type variables are declared in <<Δ>>, its term variables are\n    declared in <<Γ>>, and it is locally closed with respect to both\n    kinds of variables. *)\nDefinition ok_term : kind_ctx -> type_ctx -> term LN -> Prop :=\n  fun Δ Γ t => scoped term KType t (domset Δ) /\\\n            scoped term KTerm t (domset Γ) /\\\n            locally_closed term KTerm t /\\\n            locally_closed term KType t.\n\n(** ** Typing judgments *)\n(******************************************************************************)\nImplicit Types (Δ : kind_ctx) (Γ : type_ctx) (τ : typ LN).\n\nInductive Judgment : kind_ctx -> type_ctx -> term LN -> typ LN -> Prop :=\n| j_var :\n    forall Δ Γ x τ,\n      ok_kind_ctx Δ ->\n      ok_type_ctx Δ Γ ->\n      (x, τ) ∈ (Γ : list (atom * typ LN)) ->\n      (Δ ; Γ ⊢ tm_var (Fr x) : τ)\n| j_abs :\n    forall Δ Γ L t τ1 τ2,\n      (forall x, ~ x ∈@ L  ->\n            Δ ; Γ ++ x ~ τ1 ⊢ open term KTerm (tm_var (Fr x)) t : τ2) ->\n      (Δ ; Γ ⊢ tm_abs τ1 t : ty_ar τ1 τ2)\n| j_app :\n    forall Δ Γ t1 t2 τ1 τ2,\n      (Δ ; Γ ⊢ t1 : ty_ar τ1 τ2) ->\n      (Δ ; Γ ⊢ t2 : τ1) ->\n      (Δ ; Γ ⊢ tm_app t1 t2 : τ2)\n| j_univ :\n    forall Δ Γ L τ t,\n      (forall x, ~ x ∈@ L ->\n            Δ ++ x ~ tt ; Γ ⊢ open term KType (ty_v (Fr x)) t\n                          : open typ KType (ty_v (Fr x)) τ) ->\n      (Δ ; Γ ⊢ tm_tab t : ty_univ τ)\n| j_inst :\n    forall Δ Γ t τ1 τ2,\n      ok_type Δ τ1 ->\n      (Δ ; Γ ⊢ t : ty_univ τ2) ->\n      (Δ ; Γ ⊢ tm_tap t τ1 : open typ KType τ1 τ2)\nwhere \"Δ ; Γ ⊢ t : τ\" := (Judgment Δ Γ t τ).\n\n(** ** Values and reduction rules *)\n(******************************************************************************)\nInductive value : term LN -> Prop :=\n| val_abs : forall T t, value (tm_abs T t)\n| val_tab : forall t, value (tm_tab t).\n\nInductive red : term LN -> term LN -> Prop :=\n| red_app_l : forall t1 t1' t2,\n    red t1 t1' ->\n    red (tm_app t1 t2) (tm_app t1' t2)\n| red_app_r : forall t1 t2 t2',\n    value t1 ->\n    red t2 t2' ->\n    red (tm_app t1 t2) (tm_app t1 t2')\n| red_abs : forall T t1 t2,\n    value t2 ->\n    red (tm_app (tm_abs T t1) t2) (open term KTerm t2 t1)\n| red_tapl : forall t t' T,\n    red t t' ->\n    red (tm_tap t T) (tm_tap t' T)\n| red_tab : forall T t,\n    red (tm_tap (tm_tab t) T) (open term KType T t).\n\nDefinition preservation := forall t t' τ,\n    (nil ; nil ⊢ t : τ) ->\n    red t t' ->\n    (nil ; nil ⊢ t' : τ).\n\nDefinition progress := forall t τ,\n    (nil ; nil ⊢ t : τ) ->\n    value t \\/ exists t', red t t'.\n\n(*\n(** ** Example: Typing the polymorphic identity *)\n(******************************************************************************)\nExample polymorphic_identity_function :\n  (nil ; nil ⊢ (Λ λ 0 ⋅ 0) : (∀ 0 ⟹ 0)).\nProof.\n  apply j_univ with (L := ∅). introv _.\n  cbn. apply j_abs with (L := ∅).\n  - introv _. apply j_var.\n    + auto with sysf_ctx.\n    + simpl_alist. apply ok_tmv_tm_one.\n      unfold ok_type, scoped_env, scoped.\n      autorewrite with sysf_rw tea_rw_dom.\n      split; [fsetdec | apply lc_ty_ty_Fr].\n    + simpl_alist. now autorewrite with tea_list.\nQed.\n*)\n", "meta": {"author": "dunnl", "repo": "tealeaves", "sha": "8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b", "save_path": "github-repos/coq/dunnl-tealeaves", "path": "github-repos/coq/dunnl-tealeaves/tealeaves-8dd6ba8acdd097f6e474ae2a1a9b10f5cc9ca65b/Tealeaves/Examples/SystemF/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23376978693807124}}
{"text": "From Bremen.theories.rhythm Require Import Duration.\nFrom Bremen.theories.physics Require Import Dynamics.\nFrom Bremen.theories.structure Require Import MelodicPart.\nRequire Import List.\nImport ListNotations.\n\nInductive harmonic_part : Type :=\n  | first_melodic_part_at_start : melodic_part -> harmonic_part\n  | melodic_part_at_start       : melodic_part -> harmonic_part -> harmonic_part\n  | melodic_part_later          : duration -> melodic_part -> harmonic_part -> harmonic_part.\n\nDefinition harmonic_part1 := \n  melodic_part_later (Whole_) melody1 (\n  melodic_part_at_start melody1 (\n  first_melodic_part_at_start (melody1))).\n\n\nFixpoint part_durations (h : harmonic_part) : list duration :=\n  match h with\n  | first_melodic_part_at_start x => match duration_of x with\n    | None => []\n    | Some z => [z]\n    end\n  | melodic_part_at_start x y => match duration_of x with\n    | None => part_durations y\n    | Some z => concat [[z]; part_durations y]\n    end\n  | melodic_part_later d x y =>  match duration_of x with\n    | None => part_durations y\n    | Some z => concat [[tie z d]; part_durations y]\n    end\n  end.\n\nFixpoint max_duration (dl : list duration) (default : duration ): duration :=\n  match dl with\n  | [] => default\n  | x :: rest => match max_duration rest default with | y =>\n    if longer_equal x y then x else y end\n  end.\n\nDefinition duration_of (h : harmonic_part) : duration :=\n  max_duration (part_durations h) (Quarter_).\n\nEval compute in duration_of harmonic_part1.\n", "meta": {"author": "fajtaiandris", "repo": "bremen", "sha": "49d9324e5894d86966884f681c09d9db876a6d09", "save_path": "github-repos/coq/fajtaiandris-bremen", "path": "github-repos/coq/fajtaiandris-bremen/bremen-49d9324e5894d86966884f681c09d9db876a6d09/theories/structure/HarmonicPart.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23376978078390337}}
{"text": "Require Import Poulet4.P4light.Syntax.P4defs.\nRequire Import Poulet4.P4light.Semantics.Semantics.\nRequire Import ProD3.core.Core.\nRequire Import ProD3.core.Tofino.\nRequire Import ProD3.examples.sbf.p4ast.\nRequire Import ProD3.examples.sbf.ConFilter.\nRequire Import ProD3.examples.sbf.common.\nRequire Import ProD3.examples.sbf.FilterRepr.\nRequire Import ProD3.examples.sbf.verif_Win1.\nRequire Import ProD3.examples.sbf.verif_Win2.\nRequire Import ProD3.examples.sbf.verif_Win3.\nRequire Import ProD3.examples.sbf.verif_Win4.\nRequire Import Hammer.Plugin.Hammer.\nRequire Export Coq.Program.Program.\nImport ListNotations.\n\nNotation ident := string.\nNotation path := (list ident).\nNotation Val := (@ValueBase bool).\nNotation Sval := (@ValueBase (option bool)).\n\nDefinition p := [\"pipe\"; \"ingress\"; \"bf2_ds\"].\n\nDefinition act_hash_index_1_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"act_hash_index_1\"] ge).\n\nDefinition act_hash_index_1_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"]; [\"act_hash_index_1\"; \"t'0\"]]) []\n    WITH (key : Val) (ds_md : Sval),\n      PRE\n        (ARG []\n        (MEM [([\"ds_key\"], eval_val_to_sval key); ([\"ds_md\"], ds_md)]\n        (EXT [])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"ds_md\"], update \"hash_index_1\" (P4Bit index_w (hash1 key)) ds_md)]\n        (EXT []))).\n\n(*  action act_hash_index_1() {\n        ds_md.hash_index_1 = hash_idx_1.get(ds_key)[17:0];\n    }\n*)\n\nLemma act_hash_index_1_body :\n  func_sound ge act_hash_index_1_fd nil act_hash_index_1_spec.\nProof.\n  start_function.\n  step_call @Hash_get_body.\n  { entailer. }\n  { compute. reflexivity. }\n  { compute. reflexivity. }\n  step.\n  step.\n  simpl sval_to_bits_width.\n  cbv match.\n  rewrite bitstring_slice_lower_bit with (w' := index_w) by lia.\n  entailer.\n  { apply sval_refine_refl'.\n    f_equal.\n    apply P4Bit_mod_eq.\n    unfold hash1.\n    rewrite Z.mod_mod by lia.\n    auto.\n  }\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_hash_index_1_body) : func_specs.\n\nDefinition tbl_hash_index_1_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"tbl_hash_index_1\"; \"apply\"] ge).\n\nDefinition tbl_hash_index_1_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"]; [\"act_hash_index_1\"; \"t'0\"]]) []\n    WITH (key : Val) (ds_md : Sval),\n      PRE\n        (ARG []\n        (MEM [([\"ds_key\"], eval_val_to_sval key); ([\"ds_md\"], ds_md)]\n        (EXT [])))\n      POST\n        (EX retv,\n        (ARG_RET [] retv\n        (MEM [([\"ds_md\"], update \"hash_index_1\" (P4Bit index_w (hash1 key)) ds_md)]\n        (EXT []))))%arg_ret_assr.\n\nLemma tbl_hash_index_1_body :\n  func_sound ge tbl_hash_index_1_fd nil tbl_hash_index_1_spec.\nProof.\n  start_function.\n  table_action act_hash_index_1_body.\n  { entailer. }\n  { entailer. }\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_1_body) : func_specs.\n\nDefinition act_hash_index_2_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"act_hash_index_2\"] ge).\n\nDefinition act_hash_index_2_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"]; [\"act_hash_index_2\"; \"t'1\"]]) []\n    WITH (key : Val) (ds_md : Sval),\n      PRE\n        (ARG []\n        (MEM [([\"ds_key\"], eval_val_to_sval key); ([\"ds_md\"], ds_md)]\n        (EXT [])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"ds_md\"], update \"hash_index_2\" (P4Bit index_w (hash2 key)) ds_md)]\n        (EXT []))).\n\n(*  action act_hash_index_2() {\n        ds_md.hash_index_2 = hash_idx_2.get(ds_key)[17:0];\n    }\n*)\n\nLemma act_hash_index_2_body :\n  func_sound ge act_hash_index_2_fd nil act_hash_index_2_spec.\nProof.\n  start_function.\n  step_call @Hash_get_body.\n  { entailer. }\n  { compute. reflexivity. }\n  { compute. reflexivity. }\n  step.\n  step.\n  simpl sval_to_bits_width.\n  cbv match.\n  rewrite bitstring_slice_lower_bit with (w' := index_w) by lia.\n  entailer.\n  { apply sval_refine_refl'.\n    f_equal.\n    apply P4Bit_mod_eq.\n    unfold hash2.\n    rewrite Z.mod_mod by lia.\n    auto.\n  }\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_hash_index_2_body) : func_specs.\n\nDefinition tbl_hash_index_2_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"tbl_hash_index_2\"; \"apply\"] ge).\n\nDefinition tbl_hash_index_2_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"]; [\"act_hash_index_2\"; \"t'1\"]]) []\n    WITH (key : Val) (ds_md : Sval),\n      PRE\n        (ARG []\n        (MEM [([\"ds_key\"], eval_val_to_sval key); ([\"ds_md\"], ds_md)]\n        (EXT [])))\n      POST\n        (EX retv,\n        (ARG_RET [] retv\n        (MEM [([\"ds_md\"], update \"hash_index_2\" (P4Bit index_w (hash2 key)) ds_md)]\n        (EXT []))))%arg_ret_assr.\n\nLemma tbl_hash_index_2_body :\n  func_sound ge tbl_hash_index_2_fd nil tbl_hash_index_2_spec.\nProof.\n  start_function.\n  table_action act_hash_index_2_body.\n  { entailer. }\n  { entailer. }\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_2_body) : func_specs.\n\nDefinition act_hash_index_3_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"act_hash_index_3\"] ge).\n\nDefinition act_hash_index_3_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"]; [\"act_hash_index_3\"; \"t'2\"]]) []\n    WITH (key : Val) (ds_md : Sval),\n      PRE\n        (ARG []\n        (MEM [([\"ds_key\"], eval_val_to_sval key); ([\"ds_md\"], ds_md)]\n        (EXT [])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"ds_md\"], update \"hash_index_3\" (P4Bit index_w (hash3 key)) ds_md)]\n        (EXT []))).\n\n(*  action act_hash_index_3() {\n        ds_md.hash_index_3 = hash_idx_3.get(ds_key)[17:0];\n    }\n*)\n\nLemma act_hash_index_3_body :\n  func_sound ge act_hash_index_3_fd nil act_hash_index_3_spec.\nProof.\n  start_function.\n  step_call @Hash_get_body.\n  { entailer. }\n  { compute. reflexivity. }\n  { compute. reflexivity. }\n  step.\n  step.\n  simpl sval_to_bits_width.\n  cbv match.\n  rewrite bitstring_slice_lower_bit with (w' := index_w) by lia.\n  entailer.\n  { apply sval_refine_refl'.\n    f_equal.\n    apply P4Bit_mod_eq.\n    unfold hash3.\n    rewrite Z.mod_mod by lia.\n    auto.\n  }\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_hash_index_3_body) : func_specs.\n\nDefinition tbl_hash_index_3_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"tbl_hash_index_3\"; \"apply\"] ge).\n\nDefinition tbl_hash_index_3_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"]; [\"act_hash_index_3\"; \"t'2\"]]) []\n    WITH (key : Val) (ds_md : Sval),\n      PRE\n        (ARG []\n        (MEM [([\"ds_key\"], eval_val_to_sval key); ([\"ds_md\"], ds_md)]\n        (EXT [])))\n      POST\n        (EX retv,\n        (ARG_RET [] retv\n        (MEM [([\"ds_md\"], update \"hash_index_3\" (P4Bit index_w (hash3 key)) ds_md)]\n        (EXT []))))%arg_ret_assr.\n\nLemma tbl_hash_index_3_body :\n  func_sound ge tbl_hash_index_3_fd nil tbl_hash_index_3_spec.\nProof.\n  start_function.\n  table_action act_hash_index_3_body.\n  { entailer. }\n  { entailer. }\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_3_body) : func_specs.\n\nDefinition regact_clear_index_apply_body :=\n  ltac:(auto_regact ge am_ge (p ++ [\"regact_clear_index\"])).\n\nDefinition regact_clear_index_execute_body :=\n  ltac:(build_execute_body ge regact_clear_index_apply_body).\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply regact_clear_index_execute_body) : func_specs.\n\nDefinition act_clear_index_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"act_clear_index\"] ge).\n\nDefinition act_clear_index_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"]; [\"act_clear_index\"; \"t'3\"]]) [p ++ [\"reg_clear_index\"]]\n    WITH (i : Z) (ds_md : Sval),\n      PRE\n        (ARG []\n        (MEM [([\"ds_md\"], ds_md)]\n        (EXT [fil_clear_index_repr p index_w i])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"ds_md\"], update \"clear_index_1\" (P4Bit index_w i) ds_md)]\n        (EXT [fil_clear_index_repr p index_w (update_clear_index (num_slots := num_slots) i)]))).\n\nLemma act_clear_index_body :\n  func_sound ge act_clear_index_fd nil act_clear_index_spec.\nProof.\n  start_function.\n  unfold fil_clear_index_repr.\n  Intros i'.\n  normalize_EXT.\n  Intros_prop.\n  step_call regact_clear_index_execute_body.\n  { entailer. }\n  { reflexivity. }\n  { simpl; lia. }\n  { simpl. list_solve. }\n  step.\n  step.\n  entailer.\n  { apply sval_refine_refl'.\n    f_equal.\n    cbn [sval_to_bits_width P4Bit].\n    rewrite bitstring_slice_lower_bit with (w' := index_w). 2, 3 : lia.\n    apply P4Bit_mod_eq.\n    pose proof (Z.mod_pos_bound i' (2 ^ Z.of_N index_w) ltac:(lia)).\n    replace (i mod 2 ^ Z.of_N index_w) with i. 2 : {\n      symmetry; apply Z.mod_small; lia.\n    }\n    auto.\n  }\n  { simpl.\n    Exists (i' + 1).\n    normalize_EXT.\n    entailer.\n    apply ext_implies_prop_intro.\n    unfold update_clear_index.\n    change (Z.pow_pos 2 _) with (2 ^ Z.of_N index_w).\n    assert (0 <= i < num_slots) by (subst; apply Z.mod_pos_bound; reflexivity).\n    rewrite Zplus_mod, H. clear H.\n    destruct (i + 1 =? num_slots) eqn:?H.\n    - assert (i = num_slots - 1) by lia.\n      subst; auto.\n    - rewrite Z.mod_small with (a := i + 1); auto.\n      lia.\n  }\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_clear_index_body) : func_specs.\n\nDefinition tbl_clear_index_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"tbl_clear_index\"; \"apply\"] ge).\n\nDefinition tbl_clear_index_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"]; [\"act_clear_index\"; \"t'3\"]]) [p ++ [\"reg_clear_index\"]]\n    WITH (i : Z) (ds_md : Sval),\n      PRE\n        (ARG []\n        (MEM [([\"ds_md\"], ds_md)]\n        (EXT [fil_clear_index_repr p index_w i])))\n      POST\n        (EX retv,\n        (ARG_RET [] retv\n        (MEM [([\"ds_md\"], update \"clear_index_1\" (P4Bit index_w i) ds_md)]\n        (EXT [fil_clear_index_repr p index_w (update_clear_index (num_slots := num_slots) i)]))))%arg_ret_assr.\n\nLemma tbl_clear_index_body :\n  func_sound ge tbl_clear_index_fd nil tbl_clear_index_spec.\nProof.\n  start_function.\n  table_action act_clear_index_body.\n  { entailer. }\n  { entailer. }\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_clear_index_body) : func_specs.\n\nDefinition regact_clear_window_signal_0_apply_fd :=\n  ltac:(get_am_fd ge am_ge (p ++ [\"regact_clear_window_signal_0\"; \"apply\"])).\n\nNotation update_timer := (@update_timer num_frames frame_tick_tocks).\n\nDefinition regact_clear_window_signal_0_apply_spec : func_spec :=\n  RegisterAction_apply_spec' (p ++ [\"regact_clear_window_signal_0\"]) (fun t => 0 <= fst t < 28136) timer_repr_val\n    (fun t => update_timer t false) (fun t => P4Bit 16 (fst (update_timer t false))).\n\n(*  RegisterAction<window_pair_t, bit<1>, window_t>(reg_clear_window) regact_clear_window_signal_0 = {\n        void apply(inout window_pair_t val, out window_t rv) {\n            if ((val.lo != 16w0))\n            {\n                val.hi = (val.hi + 16w1);\n                val.lo = 16w0;\n            }\n            rv = val.hi;\n        }\n    };\n*)\n\nLemma regact_clear_window_signal_0_apply_body :\n  func_sound am_ge regact_clear_window_signal_0_apply_fd nil regact_clear_window_signal_0_apply_spec.\nProof.\n  start_function.\n  rename old_value into t.\n  change (eval_val_to_sval (timer_repr_val t)) with (timer_repr_sval t).\n  unfold timer_repr_sval in *.\n  step.\n  step.\n  step.\n  (* TODO fix this bug in semantics:\n    why we have [\"rv\"] here?\n    when generating uninitialized value for out parameters, the locators in these are not properly set.\n  *)\n  step_if (MEM [([\"apply\"; \"val\"], timer_repr_sval (update_timer t false))]\n          (EXT [])).\n  { unfold timer_repr_sval in *.\n    step.\n    step_if.\n    { step.\n      step.\n      step.\n      step.\n      destruct t as [? []]; inv H.\n      simpl fst in *.\n      change (P4Arith.BitArith.mod_bound 16 28135) with 28135 in H0.\n      replace (P4Arith.BitArith.mod_bound 16 z) with z in H0. 2 : {\n        unfold P4Arith.BitArith.mod_bound.\n        rewrite Z.mod_small; auto.\n        change (P4Arith.BitArith.upper_bound 16) with 65536.\n        lia.\n      }\n      unfold update_timer.\n      simpl.\n      destruct (z =? 28135); inv H0.\n      entailer.\n    }\n    { step.\n      step.\n      step.\n      step.\n      destruct t as [? []]; inv H.\n      simpl fst in *.\n      change (P4Arith.BitArith.mod_bound 16 28135) with 28135 in H0.\n      replace (P4Arith.BitArith.mod_bound 16 z) with z in H0. 2 : {\n        unfold P4Arith.BitArith.mod_bound.\n        rewrite Z.mod_small; auto.\n        change (P4Arith.BitArith.upper_bound 16) with 65536.\n        lia.\n      }\n      unfold update_timer.\n      simpl.\n      destruct (z =? 28135); inv H0.\n      entailer.\n    }\n  }\n  { unfold timer_repr_sval in *.\n    step.\n    step.\n    step.\n    step.\n    destruct t as [? []]; inv H.\n    entailer.\n  }\n  step.\n  step.\n  entailer.\nQed.\n\nDefinition regact_clear_window_signal_0_execute_body :=\n  ltac:(build_execute_body ge regact_clear_window_signal_0_apply_body).\n\nDefinition regact_clear_window_signal_1_apply_fd :=\n  ltac:(get_am_fd ge am_ge (p ++ [\"regact_clear_window_signal_1\"; \"apply\"])).\n\nDefinition regact_clear_window_signal_1_apply_spec : func_spec :=\n  RegisterAction_apply_spec (p ++ [\"regact_clear_window_signal_1\"]) timer_repr_val\n    (fun t => update_timer t true) (fun t => P4Bit 16 (fst (update_timer t true))).\n\n(*  RegisterAction<window_pair_t, bit<1>, window_t>(reg_clear_window) regact_clear_window_signal_1 = {\n        void apply(inout window_pair_t val, out window_t rv) {\n            if ((val.hi == 16w28136))\n            {\n                val.hi = 16w0;\n            }\n            if ((val.lo != 16w1))\n            {\n                val.lo = 16w1;\n            }\n            rv = val.hi;\n        }\n    };\n*)\n\nLemma regact_clear_window_signal_1_apply_body :\n  func_sound am_ge regact_clear_window_signal_1_apply_fd nil regact_clear_window_signal_1_apply_spec.\nProof.\n  start_function.\n  rename old_value into t.\n  change (eval_val_to_sval (timer_repr_val t)) with (timer_repr_sval t).\n  unfold timer_repr_sval in *.\n  step.\n  step_if (MEM [([\"apply\"; \"val\"], timer_repr_sval (update_timer t true))]\n          (EXT [])).\n  { step.\n    step.\n    step.\n    destruct t as [? []]; inv H.\n    entailer.\n  }\n  { step.\n    destruct t as [? []]; inv H.\n    entailer.\n  }\n  step.\n  step.\n  entailer.\nQed.\n\nDefinition regact_clear_window_signal_1_execute_body :=\n  ltac:(build_execute_body ge regact_clear_window_signal_1_apply_body).\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply regact_clear_window_signal_0_execute_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply regact_clear_window_signal_1_execute_body) : func_specs.\n\nDefinition act_clear_window_signal_0_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"act_clear_window_signal_0\"] ge).\n\nNotation timer_repr := (@timer_repr num_frames frame_tick_tocks).\n\nDefinition act_clear_window_signal_0_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"]]) [p ++ [\"reg_clear_window\"]]\n    WITH (t : Z * bool) (ds_md : Sval),\n      PRE\n        (ARG []\n        (MEM [([\"ds_md\"], ds_md)]\n        (EXT [timer_repr p t])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"ds_md\"], update \"clear_window\" (P4Bit 16 (fst (update_timer t false))) ds_md)]\n        (EXT [timer_repr p (update_timer t false)]))).\n\n(*  action act_clear_window_signal_0() {\n        ds_md.clear_window = regact_clear_window_signal_0.execute(1w0);\n    }\n*)\n\nLemma act_clear_window_signal_0_body :\n  func_sound ge act_clear_window_signal_0_fd nil act_clear_window_signal_0_spec.\nProof.\n  start_function.\n  unfold timer_repr.\n  normalize_EXT.\n  Intros_prop.\n  step_call regact_clear_window_signal_0_execute_body.\n  { entailer. }\n  { auto. }\n  { lia. }\n  { reflexivity. }\n  { auto. }\n  step.\n  entailer.\n  simpl ext_exclude.\n  apply ext_implies_prop_intro.\n  apply update_timer_wf; auto; lia.\nQed.\n\nDefinition act_clear_window_signal_1_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"act_clear_window_signal_1\"] ge).\n\nDefinition act_clear_window_signal_1_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"]]) [p ++ [\"reg_clear_window\"]]\n    WITH (t : Z * bool) (ds_md : Sval),\n      PRE\n        (ARG []\n        (MEM [([\"ds_md\"], ds_md)]\n        (EXT [timer_repr p t])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"ds_md\"], update \"clear_window\" (P4Bit 16 (fst (update_timer t true))) ds_md)]\n        (EXT [timer_repr p (update_timer t true)]))).\n\n(*  action act_clear_window_signal_1() {\n        ds_md.clear_window = regact_clear_window_signal_1.execute(1w0);\n    }\n*)\n\nLemma act_clear_window_signal_1_body :\n  func_sound ge act_clear_window_signal_1_fd nil act_clear_window_signal_1_spec.\nProof.\n  start_function.\n  unfold timer_repr.\n  normalize_EXT.\n  Intros_prop.\n  step_call regact_clear_window_signal_1_execute_body.\n  { entailer. }\n  { auto. }\n  { lia. }\n  { reflexivity. }\n  step.\n  entailer.\n  apply ext_implies_prop_intro.\n  apply update_timer_wf; auto; lia.\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_clear_window_signal_0_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_clear_window_signal_1_body) : func_specs.\n\nDefinition tbl_clear_window_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"tbl_clear_window\"; \"apply\"] ge).\n\nDefinition tbl_clear_window_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"]]) [p ++ [\"reg_clear_window\"]]\n    WITH (t : Z * bool) (ds_md : Sval) (tstamp : Z),\n      PRE\n        (ARG []\n        (MEM [([\"ds_md\"], ds_md); ([\"ingress_mac_tstamp\"], P4Bit 48 tstamp)]\n        (EXT [timer_repr p t])))\n      POST\n        (EX retv,\n        (ARG_RET [] retv\n        (MEM [([\"ds_md\"], update \"clear_window\" (P4Bit 16 (fst (update_timer t (Z.odd (tstamp / 2097152))))) ds_md)]\n        (EXT [timer_repr p (update_timer t (Z.odd (tstamp / 2097152)))]))))%arg_ret_assr.\n\n(*  table tbl_clear_window {\n        key = {\n            ingress_mac_tstamp : ternary;\n        }\n        actions = {\n            act_clear_window_signal_0();\n            act_clear_window_signal_1();\n        }\n        const entries = {\n            48w0 &&& 48w2097152 : act_clear_window_signal_0();\n            _ : act_clear_window_signal_1();\n        }\n        default_action = act_clear_window_signal_1();\n        size = 2;\n    }\n*)\n\nLemma tbl_clear_window_body :\n  func_sound ge tbl_clear_window_fd nil tbl_clear_window_spec.\nProof.\n  start_function; elim_trivial_cases.\n  { repeat rewrite Z.div_div in H by lia.\n    simpl in H.\n    destruct (Z.odd (tstamp / 2097152)); try solve [inv H].\n    table_action act_clear_window_signal_0_body.\n    { entailer. }\n    { entailer. }\n  }\n  { repeat rewrite Z.div_div in H by lia.\n    simpl in H.\n    destruct (Z.odd (tstamp / 2097152)); try solve [inv H].\n    table_action act_clear_window_signal_1_body.\n    { entailer. }\n    { entailer. }\n  }\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_clear_window_body) : func_specs.\n\nDefinition act_set_clear_win_1_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"act_set_clear_win_1\"] ge).\n\n(* Definition act_set_clear_win_1_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"];\n               [\"act_set_clear_win_1\"; \"api_1\"];\n               [\"act_set_clear_win_1\"; \"api_2\"];\n               [\"act_set_clear_win_1\"; \"api_3\"];\n               [\"act_set_clear_win_1\"; \"api_4\"]]) []\n    WITH (ds_md : Sval) (api_1 api_2 api_3 api_4 : Sval),\n      PRE\n        (ARG [api_1; api_2; api_3; api_4]\n        (MEM [([\"ds_md\"], ds_md)]\n        (EXT [])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [\n          ([\"ds_md\"], update \"win_1\" (\n            update \"index_1\" (get \"clear_index_1\" ds_md)\n            (update \"index_2\" (get \"clear_index_1\" ds_md)\n            (update \"index_3\" (get \"clear_index_1\" ds_md) (get \"win_1\" ds_md))))\n            ds_md)]\n        (EXT []))).\n\nLemma act_set_clear_win_1_body :\n  func_sound ge act_set_clear_win_1_fd nil act_set_clear_win_1_spec.\nProof.\n  start_function.\n  assert (has_field \"win_1\" ds_md) by admit.\n  assert (has_field \"win_2\" ds_md) by admit.\n  assert (has_field \"win_3\" ds_md) by admit.\n  assert (has_field \"win_4\" ds_md) by admit.\n  simpl.\n  Time step.\n  simpl.\n  Time step.\n  simpl.\n\nLtac rewrite_get_update_same :=\n  rewrite get_update_same by (auto using has_field_update).\n\nLtac rewrite_get_update_diff :=\n  rewrite get_update_diff; [ | auto using has_field_update | discriminate].\n\nLtac rewrite_update_update_same :=\n  rewrite update_update_same by (auto using has_field_update).\n\nLtac get_update_simpl :=\n  repeat first [\n    rewrite_get_update_same\n  | rewrite_get_update_diff\n  | rewrite_update_update_same\n  ].\n\n  get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  Time step.\n  Time simpl; get_update_simpl.\n  (* Then we need a update_update_diff rule and guide it nicely. *)\nAbort. *)\n\nDefinition P4_bf2_win_md_t_ :=\n  ValBaseStruct\n    [(\"api\", P4Bit_ 8);\n     (\"index_1\", P4Bit_ index_w);\n     (\"index_2\", P4Bit_ index_w);\n     (\"index_3\", P4Bit_ index_w);\n     (\"rw_1\", P4Bit_ 8);\n     (\"rw_2\", P4Bit_ 8);\n     (\"rw_3\", P4Bit_ 8)].\n\nDefinition P4_bf2_win_md_t (op : Sval) (is : list Sval) :=\n  ValBaseStruct\n    [(\"api\", op);\n     (\"index_1\", Znth 0 is);\n     (\"index_2\", Znth 1 is);\n     (\"index_3\", Znth 2 is);\n     (\"rw_1\", P4Bit_ 8);\n     (\"rw_2\", P4Bit_ 8);\n     (\"rw_3\", P4Bit_ 8)].\n\nDefinition act_set_clear_win_1_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"];\n               [\"act_set_clear_win_1\"; \"api_1\"];\n               [\"act_set_clear_win_1\"; \"api_2\"];\n               [\"act_set_clear_win_1\"; \"api_3\"];\n               [\"act_set_clear_win_1\"; \"api_4\"]]) []\n    WITH (clear_window clear_index_1 hash_index_1 hash_index_2 hash_index_3: Sval) (api_1 api_2 api_3 api_4 : Sval),\n      PRE\n        (ARG [api_1; api_2; api_3; api_4]\n        (MEM [([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", clear_window);\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"win_1\", P4_bf2_win_md_t_);\n                  (\"win_2\", P4_bf2_win_md_t_);\n                  (\"win_3\", P4_bf2_win_md_t_);\n                  (\"win_4\", P4_bf2_win_md_t_)])]\n        (EXT [])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", clear_window);\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"win_1\", P4_bf2_win_md_t api_1 [clear_index_1; clear_index_1; clear_index_1]);\n                  (\"win_2\", P4_bf2_win_md_t api_2 [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_3\", P4_bf2_win_md_t api_3 [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_4\", P4_bf2_win_md_t api_4 [hash_index_1; hash_index_2; hash_index_3])])]\n        (EXT []))).\n\nLemma act_set_clear_win_1_body :\n  func_sound ge act_set_clear_win_1_fd nil act_set_clear_win_1_spec.\nProof.\n  start_function.\n  unfold P4_bf2_win_md_t_.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  entailer.\nQed.\n\nDefinition act_set_clear_win_2_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"act_set_clear_win_2\"] ge).\n\nDefinition act_set_clear_win_2_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"];\n               [\"act_set_clear_win_2\"; \"api_1\"];\n               [\"act_set_clear_win_2\"; \"api_2\"];\n               [\"act_set_clear_win_2\"; \"api_3\"];\n               [\"act_set_clear_win_2\"; \"api_4\"]]) []\n    WITH (clear_window clear_index_1 hash_index_1 hash_index_2 hash_index_3: Sval) (api_1 api_2 api_3 api_4 : Sval),\n      PRE\n        (ARG [api_1; api_2; api_3; api_4]\n        (MEM [([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", clear_window);\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"win_1\", P4_bf2_win_md_t_);\n                  (\"win_2\", P4_bf2_win_md_t_);\n                  (\"win_3\", P4_bf2_win_md_t_);\n                  (\"win_4\", P4_bf2_win_md_t_)])]\n        (EXT [])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", clear_window);\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"win_1\", P4_bf2_win_md_t api_1 [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_2\", P4_bf2_win_md_t api_2 [clear_index_1; clear_index_1; clear_index_1]);\n                  (\"win_3\", P4_bf2_win_md_t api_3 [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_4\", P4_bf2_win_md_t api_4 [hash_index_1; hash_index_2; hash_index_3])])]\n        (EXT []))).\n\nLemma act_set_clear_win_2_body :\n  func_sound ge act_set_clear_win_2_fd nil act_set_clear_win_2_spec.\nProof.\n  start_function.\n  unfold P4_bf2_win_md_t_.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  entailer.\nQed.\n\nDefinition act_set_clear_win_3_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"act_set_clear_win_3\"] ge).\n\nDefinition act_set_clear_win_3_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"];\n               [\"act_set_clear_win_3\"; \"api_1\"];\n               [\"act_set_clear_win_3\"; \"api_2\"];\n               [\"act_set_clear_win_3\"; \"api_3\"];\n               [\"act_set_clear_win_3\"; \"api_4\"]]) []\n    WITH (clear_window clear_index_1 hash_index_1 hash_index_2 hash_index_3: Sval) (api_1 api_2 api_3 api_4 : Sval),\n      PRE\n        (ARG [api_1; api_2; api_3; api_4]\n        (MEM [([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", clear_window);\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"win_1\", P4_bf2_win_md_t_);\n                  (\"win_2\", P4_bf2_win_md_t_);\n                  (\"win_3\", P4_bf2_win_md_t_);\n                  (\"win_4\", P4_bf2_win_md_t_)])]\n        (EXT [])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", clear_window);\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"win_1\", P4_bf2_win_md_t api_1 [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_2\", P4_bf2_win_md_t api_2 [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_3\", P4_bf2_win_md_t api_3 [clear_index_1; clear_index_1; clear_index_1]);\n                  (\"win_4\", P4_bf2_win_md_t api_4 [hash_index_1; hash_index_2; hash_index_3])])]\n        (EXT []))).\n\nLemma act_set_clear_win_3_body :\n  func_sound ge act_set_clear_win_3_fd nil act_set_clear_win_3_spec.\nProof.\n  start_function.\n  unfold P4_bf2_win_md_t_.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  entailer.\nQed.\n\nDefinition act_set_clear_win_4_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"act_set_clear_win_4\"] ge).\n\nDefinition act_set_clear_win_4_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"];\n               [\"act_set_clear_win_4\"; \"api_1\"];\n               [\"act_set_clear_win_4\"; \"api_2\"];\n               [\"act_set_clear_win_4\"; \"api_3\"];\n               [\"act_set_clear_win_4\"; \"api_4\"]]) []\n    WITH (clear_window clear_index_1 hash_index_1 hash_index_2 hash_index_3: Sval) (api_1 api_2 api_3 api_4 : Sval),\n      PRE\n        (ARG [api_1; api_2; api_3; api_4]\n        (MEM [([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", clear_window);\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"win_1\", P4_bf2_win_md_t_);\n                  (\"win_2\", P4_bf2_win_md_t_);\n                  (\"win_3\", P4_bf2_win_md_t_);\n                  (\"win_4\", P4_bf2_win_md_t_)])]\n        (EXT [])))\n      POST\n        (ARG_RET [] ValBaseNull\n        (MEM [([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", clear_window);\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"win_1\", P4_bf2_win_md_t api_1 [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_2\", P4_bf2_win_md_t api_2 [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_3\", P4_bf2_win_md_t api_3 [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_4\", P4_bf2_win_md_t api_4 [clear_index_1; clear_index_1; clear_index_1])])]\n        (EXT []))).\n\nLemma act_set_clear_win_4_body :\n  func_sound ge act_set_clear_win_4_fd nil act_set_clear_win_4_spec.\nProof.\n  start_function.\n  unfold P4_bf2_win_md_t_.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  step.\n  entailer.\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_1_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_2_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_3_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_4_body) : func_specs.\n\nDefinition tbl_set_win_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"tbl_set_win\"; \"apply\"] ge).\n\nNotation get_clear_frame := (get_clear_frame frame_tick_tocks).\nNotation get_insert_frame := (get_insert_frame num_frames).\n\nLemma Z_div_squeeze_pos : forall a b lo hi res,\n  0 < b ->\n  lo <= a <= hi ->\n  lo / b = res ->\n  hi / b = res ->\n  a / b = res.\nProof.\n  intros.\n  pose proof (Z.div_le_mono lo a b ltac:(auto) ltac:(lia)).\n  pose proof (Z.div_le_mono a hi b ltac:(auto) ltac:(lia)).\n  lia.\nQed.\n\nLemma Z_div_squeeze : forall a b lo hi res,\n  lo <= a <= hi ->\n  lo / b = res ->\n  hi / b = res ->\n  a / b = res.\nProof.\n  intros.\n  destruct b.\n  - rewrite Zdiv_0_r in *. auto.\n  - eapply Z_div_squeeze_pos; eauto; lia.\n  - rewrite <- Zdiv_opp_opp in *.\n    eapply Z_div_squeeze_pos with (-hi) (-lo); lia.\nQed.\n\nLemma Z_div_squeeze' : forall a b lo hi res,\n  (lo <=? a) && (a <=? hi) ->\n  lo / b = res ->\n  hi / b = res ->\n  a / b = res.\nProof.\n  intros.\n  apply Z_div_squeeze with lo hi; lia.\nQed.\n\nDefinition Filter_fd :=\n  ltac:(get_fd [\"Bf2BloomFilter\"; \"apply\"] ge).\n\nProgram Definition hashes (key : Val) : listn Z num_rows := (exist _ [hash1 key; hash2 key; hash3 key] eq_refl).\n\nNotation filter_repr := (filter_repr (frame_tick_tocks := frame_tick_tocks)).\n", "meta": {"author": "verified-network-toolchain", "repo": "VerifiableP4", "sha": "87afa7bef7d88da2e9a642e37c0ddb2412b57509", "save_path": "github-repos/coq/verified-network-toolchain-VerifiableP4", "path": "github-repos/coq/verified-network-toolchain-VerifiableP4/VerifiableP4-87afa7bef7d88da2e9a642e37c0ddb2412b57509/examples/sbf/verif_Filter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23376978078390329}}
{"text": "(** * Properties about Context Free Grammars *)\nRequire Import Fiat.Parsers.StringLike.Core Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Transfer.\nRequire Import Fiat.Parsers.ContextFreeGrammar.SimpleCorrectness.\n\nLocal Coercion is_true : bool >-> Sortclass.\n\nSet Implicit Arguments.\n\nSection cfg.\n  Context {Char} {HSLM1 HSLM2 : StringLikeMin Char}\n          {HSL1 : @StringLike _ HSLM1}\n          {HSL2 : @StringLike _ HSLM2}\n          (G : @grammar Char).\n  Context (R : @String _ HSLM1 -> @String _ HSLM2 -> Prop).\n  Context {is_respectful : transfer_respectful R}.\n\n  Local Ltac t' :=\n    repeat match goal with\n           | _ => assumption\n           | [ |- context[match ?e with _ => _ end] ]\n             => is_var e; destruct e\n           | _ => tauto\n           | _ => solve [ eauto with nocore ]\n           | _ => intro\n           | [ H : and _ _ |- _ ] => destruct H\n           | [ H : ex _ |- _ ] => destruct H\n           | [ H : transfer_respectful _ |- _ ] => destruct H; try clear H\n           | [ |- and _ _ ] => split\n           | [ |- ex _ ] => eexists; solve [ t' ]\n           | [ H : is_true (andb ?x _) |- is_true (andb ?x _) ]\n             => destruct x eqn:?; simpl in *\n           end.\n\n  Local Ltac t :=\n    lazymatch goal with\n    | [ p : _ |- _ ] => destruct p\n    end;\n    simpl_simple_parse_of_correct;\n    t'.\n\n  Fixpoint transfer_simple_parse_of_correct {str1 str2 pats} (H : R str1 str2) (p : @simple_parse_of Char)\n    : simple_parse_of_correct G str1 pats p -> simple_parse_of_correct G str2 pats p\n  with transfer_simple_parse_of_production_correct {str1 str2 pat} (H : R str1 str2) (p : @simple_parse_of_production Char)\n    : simple_parse_of_production_correct G str1 pat p -> simple_parse_of_production_correct G str2 pat p\n  with transfer_simple_parse_of_item_correct {str1 str2 it} (H : R str1 str2) (p : @simple_parse_of_item Char)\n    : simple_parse_of_item_correct G str1 it p -> simple_parse_of_item_correct G str2 it p.\n  Proof.\n    { t. }\n    { t. }\n    { t. }\n  Defined.\nEnd cfg.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/ContextFreeGrammar/SimpleTransfer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4532618480153862, "lm_q1q2_score": 0.23371083587415178}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n(** * interImplement\n\nPierre Letouzey & Laurent Thery\n\nImplement the intersection (2 files)\n\nIn this file we simply show that to build the intersection, we simply need for\nevery a, first find the maller b that is in relation with a in both arrays and\nadd the equation a=b\n*)\n\nFrom Stalmarck Require Export addArray.\nFrom Stalmarck Require Export interState.\nFrom Stalmarck Require Export memoryImplement.\n\nSection inter.\n\n(** Return the equivalent class of an element plus the polarity *)\nDefinition getEquiv (Ar : rArray vM) (a : rNat) : list rZ * bool :=\n  match rArrayGet vM Ar a with\n  | ref r =>\n      match r with\n      | rZPlus r0 =>\n          match rArrayGet vM Ar r0 with\n          | ref _ => (nil, true)\n          | class L => (rZPlus r0 :: L, false)\n          end\n      | rZMinus r0 =>\n          match rArrayGet vM Ar r0 with\n          | ref _ => (nil, true)\n          | class L => (rZPlus r0 :: L, true)\n          end\n      end\n  | class L => (rZPlus a :: L, false)\n  end.\n\nDefinition getEquivProp :\n  forall Ar : rArray vM,\n  wellFormedArray Ar ->\n  forall a : rNat,\n  match getEquiv Ar a with\n  | (L, true) =>\n      OlistRz L /\\\n      (forall c : rZ, In (rZComp c) L <-> evalZ Ar c = evalZ Ar (rZPlus a))\n  | (L, false) =>\n      OlistRz L /\\\n      (forall c : rZ, In c L <-> evalZ Ar c = evalZ Ar (rZPlus a))\n  end.\nintros Ar War a; unfold getEquiv in |- *; CaseEq (rArrayGet _ Ar a).\nintros r; case r.\nintros r0 H'; CaseEq (rArrayGet _ Ar r0).\nintros r1 H'0; absurd False; auto with stalmarck.\nContradict H'0.\napply wfPcr with (2 := H'); auto with stalmarck.\nintros L HL; split; auto with stalmarck.\ngeneralize HL; case L; auto with stalmarck.\nintros H'0; red in |- *; apply OlistOne; auto with stalmarck.\nintros r1 l H'0.\nred in |- *; apply OlistCons; auto with stalmarck.\napply wfOl with (2 := H'0); auto with stalmarck.\nred in |- *; apply wellFormedArrayInImpLt with (2 := H'0); simpl in |- *;\n auto with stalmarck.\nintros c; case c; simpl in |- *; split.\nintros H'0; Elimc H'0; intros H'0.\ninversion H'0; rewrite <- H0.\nunfold evalN in |- *; rewrite HL; rewrite H'; auto with stalmarck.\nunfold evalN in |- *; rewrite H'; generalize (wfPcc1 _ War _ _ _ HL H'0);\n simpl in |- *; intros H'1; rewrite H'1; auto with stalmarck.\nunfold evalN in |- *; rewrite H'; auto with stalmarck.\nCaseEq (rArrayGet vM Ar r1); auto with stalmarck.\nintros r2 H'0 H'1; right.\nreplace (rZPlus r1) with (samePol (rZPlus r0) r1).\napply wfPcc2 with (Ar := Ar); auto with stalmarck.\nrewrite <- H'1; auto with stalmarck.\nsimpl in |- *; auto with stalmarck.\nintros H'0; Elimc H'0; intros H'0.\ndiscriminate.\nunfold evalN in |- *; rewrite H'; generalize (wfPcc1 _ War _ _ _ HL H'0);\n simpl in |- *; intros H'1; rewrite H'1; auto with stalmarck.\nunfold evalN in |- *; rewrite H'; auto with stalmarck.\nCaseEq (rArrayGet vM Ar r1); auto with stalmarck.\nintros r2 H'0 H'1; right.\nreplace (rZMinus r1) with (samePol (rZComp (rZPlus r0)) r1).\napply wfPcc2 with (Ar := Ar); auto with stalmarck.\nrewrite <- H'1; rewrite rZCompInv; auto with stalmarck.\nsimpl in |- *; auto with stalmarck.\nintros r0 H'; CaseEq (rArrayGet _ Ar r0).\nintros r1 H'0; absurd False; auto with stalmarck.\nContradict H'0.\napply wfPcr with (2 := H'); auto with stalmarck.\nintros L HL; split; auto with stalmarck.\ngeneralize HL; case L; auto with stalmarck.\nintros H'0; red in |- *; apply OlistOne; auto with stalmarck.\nintros r1 l H'0.\nred in |- *; apply OlistCons; auto with stalmarck.\napply wfOl with (2 := H'0); auto with stalmarck.\nred in |- *; apply wellFormedArrayInImpLt with (2 := H'0); simpl in |- *;\n auto with stalmarck.\nintros c; case c; simpl in |- *; split.\nintros H'0; Elimc H'0; intros H'0.\ndiscriminate.\nunfold evalN in |- *; rewrite H'; generalize (wfPcc1 _ War _ _ _ HL H'0);\n simpl in |- *; intros H'1; rewrite H'1; auto with stalmarck.\nunfold evalN in |- *; rewrite H'; auto with stalmarck.\nCaseEq (rArrayGet vM Ar r1); auto with stalmarck.\nintros r2 H'0 H'1; right.\nreplace (rZMinus r1) with (samePol (rZMinus r0) r1).\napply wfPcc2 with (Ar := Ar); auto with stalmarck.\nrewrite <- H'1; auto with stalmarck.\nsimpl in |- *; auto with stalmarck.\nintros l H'0 H'1; discriminate.\nintros H'0; Elimc H'0; intros H'0.\ninversion H'0; rewrite <- H0.\nunfold evalN in |- *; rewrite HL; rewrite H'; auto with stalmarck.\nunfold evalN in |- *; rewrite H'; generalize (wfPcc1 _ War _ _ _ HL H'0);\n simpl in |- *; intros H'1; rewrite H'1; auto with stalmarck.\nunfold evalN in |- *; rewrite H'; auto with stalmarck.\nCaseEq (rArrayGet vM Ar r1); auto with stalmarck.\nintros r2 H'0 H'1; right.\nreplace (rZPlus r1) with (samePol (rZComp (rZMinus r0)) r1).\napply wfPcc2 with (Ar := Ar); auto with stalmarck.\nrewrite <- H'1; rewrite rZCompInv; auto with stalmarck.\nsimpl in |- *; auto with stalmarck.\nsimpl in |- *; intros l H'0 H'1; inversion H'1; auto with stalmarck.\nintros L H'; split.\ngeneralize H'; case L.\nintros H'0; red in |- *; apply OlistOne; auto with stalmarck.\nintros r l H'0; red in |- *; apply OlistCons; auto with stalmarck.\napply wfOl with (2 := H'0); auto with stalmarck.\nred in |- *; apply wellFormedArrayInImpLt with (2 := H'0); simpl in |- *;\n auto with stalmarck.\nintros c; case c; simpl in |- *; split.\nintros H'0; Elimc H'0; intros H'0.\ninversion H'0; rewrite <- H0; auto with stalmarck.\nunfold evalN in |- *; rewrite H'; generalize (wfPcc1 _ War _ _ _ H' H'0);\n simpl in |- *; intros H'1; rewrite H'1; auto with stalmarck.\nunfold evalN in |- *; rewrite H'; auto with stalmarck.\nCaseEq (rArrayGet vM Ar r); auto with stalmarck.\nintros r0 H'0 H'1; right.\nreplace (rZPlus r) with (samePol (rZPlus a) r).\napply wfPcc2 with (Ar := Ar); auto with stalmarck.\nrewrite <- H'1; auto with stalmarck.\nsimpl in |- *; auto with stalmarck.\nintros H'0; Elimc H'0; intros H'0.\ndiscriminate.\nunfold evalN in |- *; rewrite H'; generalize (wfPcc1 _ War _ _ _ H' H'0);\n simpl in |- *; intros H'1; rewrite H'1; auto with stalmarck.\nunfold evalN in |- *; rewrite H'; auto with stalmarck.\nCaseEq (rArrayGet vM Ar r); auto with stalmarck.\nintros r0 H'0 H'1; right.\nreplace (rZMinus r) with (samePol (rZComp (rZPlus a)) r).\napply wfPcc2 with (Ar := Ar); auto with stalmarck.\nrewrite <- H'1; rewrite rZCompInv; auto with stalmarck.\nsimpl in |- *; auto with stalmarck.\nDefined.\n\nTheorem getEquivProp1 :\n forall (Ar : rArray vM) (War : wellFormedArray Ar) (a : rNat) (c : rZ),\n snd (getEquiv Ar a) = true ->\n (In (rZComp c) (fst (getEquiv Ar a)) <-> evalZ Ar c = evalZ Ar (rZPlus a)).\nProof.\nintros Ar War a c; generalize (getEquivProp Ar War a); case (getEquiv Ar a);\n auto with stalmarck.\nintros x; case x; auto with stalmarck.\nintros b; case b; simpl in |- *; auto with stalmarck.\nintros H'; elim H'; auto with stalmarck.\nintros H' H'0; discriminate.\nintros r l b; case b; simpl in |- *; auto with stalmarck.\nintros H'; elim H'; auto with stalmarck.\nintros H' H'0; discriminate.\nQed.\n\nTheorem getEquivProp2 :\n forall (Ar : rArray vM) (War : wellFormedArray Ar) (a : rNat) (c : rZ),\n snd (getEquiv Ar a) = false ->\n (In c (fst (getEquiv Ar a)) <-> evalZ Ar c = evalZ Ar (rZPlus a)).\nProof.\nintros Ar War a c; generalize (getEquivProp Ar War a); case (getEquiv Ar a);\n auto with stalmarck.\nintros x; case x; auto with stalmarck.\nintros b; case b; simpl in |- *; auto with stalmarck.\nintros H' H'0; discriminate.\nintros H'; elim H'; auto with stalmarck.\nintros r l b; case b; simpl in |- *; auto with stalmarck.\nintros H' H'0; discriminate.\nintros H'; elim H'; auto with stalmarck.\nQed.\n\nTheorem getEquivProp3 :\n forall (Ar : rArray vM) (War : wellFormedArray Ar) (a : rNat),\n OlistRz (fst (getEquiv Ar a)).\nProof.\nintros Ar War a; generalize (getEquivProp Ar War a); case (getEquiv Ar a);\n auto with stalmarck.\nintros x; case x; auto with stalmarck.\nintros b; case b; intros H'; elim H'; auto with stalmarck.\nintros r l b; case b; intros H'; elim H'; auto with stalmarck.\nQed.\n\n(** Given an element of rZ compute its equivalent class *)\nDefinition getEquivList (Ar : rArray vM) (a : rZ) : \n  list rZ :=\n  match a with\n  | rZPlus a' =>\n      match getEquiv Ar a' with\n      | (L, true) => map rZComp L\n      | (L, false) => L\n      end\n  | rZMinus a' =>\n      match getEquiv Ar a' with\n      | (L, true) => L\n      | (L, false) => map rZComp L\n      end\n  end.\n\nTheorem inMapComp :\n forall (a : rZ) (L : list rZ), In (rZComp a) (map rZComp L) -> In a L.\nProof.\nintros a L; elim L; simpl in |- *; auto with stalmarck.\nintros a0 l H' H'0; Elimc H'0; auto with stalmarck.\nleft; apply rZCompEq; auto with stalmarck.\nQed.\n\nTheorem getEquivListProp1 :\n forall (Ar : rArray vM) (War : wellFormedArray Ar) (a c : rZ),\n In c (getEquivList Ar a) <-> evalZ Ar c = evalZ Ar a.\nProof.\nintros Ar War a; unfold getEquivList in |- *; case a; intros a';\n generalize (getEquivProp1 Ar War a'); generalize (getEquivProp2 Ar War a');\n case (getEquiv Ar a'); simpl in |- *; auto with stalmarck; intros l b; \n case b; auto with stalmarck.\nintros H' H'0 c.\nlapply (H'0 c); [ intros H'1; red in H'1 | idtac ]; auto with stalmarck.\nElimc H'1; intros H'1 H'2.\nred in |- *; split; intros H'3; auto with stalmarck.\napply H'1; auto with stalmarck.\napply inMapComp; rewrite <- rZCompInvol; auto with stalmarck.\nrewrite (rZCompInvol c); apply in_map; auto with stalmarck.\nintros H' H'0 c.\nlapply (H'0 (rZComp c));\n [ rewrite <- rZCompInvol; intros H'1; red in H'1 | idtac ]; \n auto with stalmarck.\nElimc H'1; intros H'1 H'2.\nred in |- *; split; intros H'3; auto with stalmarck.\nrewrite <- H'1; auto with stalmarck.\nrewrite (evalZComp Ar c); auto with stalmarck.\napply H'2; auto with stalmarck.\nrewrite (evalZComp Ar c); auto with stalmarck.\nrewrite H'3; auto with stalmarck.\nintros H' H'0 c.\nlapply (H' (rZComp c)); [ intros H'1; red in H'1 | idtac ]; auto with stalmarck.\nElimc H'1; intros H'1 H'2.\nred in |- *; split; intros H'3; auto with stalmarck.\nrewrite <- H'1; auto with stalmarck.\nrewrite (evalZComp Ar c); auto with stalmarck.\napply inMapComp; rewrite <- rZCompInvol; auto with stalmarck.\nrewrite (rZCompInvol c); apply in_map; auto with stalmarck.\napply H'2; auto with stalmarck.\nrewrite (evalZComp Ar c); auto with stalmarck.\nrewrite H'3; auto with stalmarck.\nQed.\n\nTheorem getEquivListProp2 :\n forall (Ar : rArray vM) (War : wellFormedArray Ar) (a : rZ),\n OlistRz (getEquivList Ar a).\nProof.\nintros Ar War a; unfold getEquivList in |- *; case a; intros a';\n generalize (getEquivProp3 Ar War a'); case (getEquiv Ar a'); \n simpl in |- *; auto with stalmarck; intros l b; case b; auto with stalmarck; intros H'; \n red in |- *; apply Olistf with (eqA := eqRz); auto with stalmarck; \n exact rZltEqComp.\nQed.\n\nTheorem getEquivListProp3 :\n forall (Ar : rArray vM) (War : wellFormedArray Ar) (a : rZ),\n In a (getEquivList Ar a).\nProof.\nintros Ar War a.\ncase (getEquivListProp1 _ War a a); auto with stalmarck.\nQed.\n\nTheorem getEquivListProp4 :\n forall (Ar : rArray vM) (War : wellFormedArray Ar) (S : State),\n rArrayState Ar S ->\n forall a b : rZ, eqStateRz S a b <-> getEquivList Ar a = getEquivList Ar b.\nProof.\nintros Ar War S Sar a b; red in |- *; split; intros H'1; auto with stalmarck.\ncut (EqL _ (eq (A:=rZ)) (getEquivList Ar a) (getEquivList Ar b)).\nintros H'; elim H'; simpl in |- *; auto with stalmarck.\nintros a0 b0 L1 L2 H'0 H'2 H'3; rewrite H'0; rewrite H'3; auto with stalmarck.\napply EqLOlist with (ltA := rZlt); try (red in |- *; auto with stalmarck; fail); auto with stalmarck.\nintros a0 b0 H'; red in |- *; intros H'0; absurd (rZlt a0 b0); auto with stalmarck;\n rewrite H'0; auto with stalmarck.\nintros a0 b0 c d H' H'0 H'2; rewrite <- H'0; rewrite <- H'2; auto with stalmarck.\napply getEquivListProp2; auto with stalmarck.\napply getEquivListProp2; auto with stalmarck.\napply InclEqDef; auto with stalmarck.\nintros a0 H'; apply inImpInEq; auto with stalmarck.\nred in |- *; auto with stalmarck.\ncase (getEquivListProp1 Ar War b a0).\nintros H'0 H'2; apply H'2; auto with stalmarck.\napply trans_equal with (evalZ Ar a).\ncase (getEquivListProp1 Ar War a a0).\nintros H'3 H'4; apply H'3.\nelim H'; simpl in |- *; auto with stalmarck.\napply rArrayStateDef1 with (S := S); auto with stalmarck.\napply InclEqDef; auto with stalmarck.\nintros a0 H'; apply inImpInEq; auto with stalmarck.\nred in |- *; auto with stalmarck.\ncase (getEquivListProp1 Ar War a a0).\nintros H'0 H'2; apply H'2.\napply trans_equal with (evalZ Ar b).\ncase (getEquivListProp1 Ar War b a0).\nintros H'3 H'4; apply H'3.\nelim H'; simpl in |- *; auto with stalmarck.\napply rArrayStateDef1 with (S := S); auto with stalmarck.\napply rArrayStateDef2 with (Ar := Ar); auto with stalmarck.\ncase (getEquivListProp1 Ar War b a); auto with stalmarck.\nintros H' H'0; apply H'.\nrewrite <- H'1.\napply getEquivListProp3; auto with stalmarck.\nQed.\n\nDefinition getMinId :=\n  getMin _ rZlt eqRz rZltEDec (eq (A:=rZ)) (fun (a b : rZ) _ => rZDec a b).\n\nTheorem getMinIdSym :\n forall L1 L2 : list rZ,\n OlistRz L1 -> OlistRz L2 -> getMinId L1 L2 = getMinId L2 L1.\nProof.\nintros L1 L2 H' H'0; CaseEq (getMinId L1 L2).\nCaseEq (getMinId L2 L1).\nintros x H'1 x0 H'2.\ncase (rZltEDec x0 x); auto with stalmarck.\nintros H'3; case H'3.\nintros H'4.\nabsurd (x0 = x0); auto with stalmarck.\nunfold getMinId in H'1; apply getMinMin with (10 := H'1); auto with stalmarck.\nintros a b H'5; rewrite H'5; auto with stalmarck.\nunfold getMinId in H'2; case getMinComp with (4 := H'2); auto with stalmarck.\nintros x1 H'5; elim H'5; intros H'6 H'7; rewrite H'6; auto with stalmarck.\nunfold getMinId in H'2; apply geMinIn with (4 := H'2); auto with stalmarck.\nintros H'4.\nabsurd (x = x); auto with stalmarck.\nunfold getMinId in H'2; apply getMinMin with (10 := H'2); auto with stalmarck.\nintros a b H'5; rewrite H'5; auto with stalmarck.\nunfold getMinId in H'1; case getMinComp with (4 := H'1); auto with stalmarck.\nintros x1 H'5; elim H'5; intros H'6 H'7; rewrite H'6; auto with stalmarck.\nunfold getMinId in H'1; apply geMinIn with (4 := H'1); auto with stalmarck.\nintros H'3; rewrite (OlistIn _ rZlt eqRz) with (L := L1) (7 := H'3); auto with stalmarck.\nunfold getMinId in H'2; apply geMinIn with (4 := H'2); auto with stalmarck.\nunfold getMinId in H'1; case getMinComp with (4 := H'1); auto with stalmarck.\nintros x1 H'5; elim H'5; intros H'6 H'7; rewrite H'6; auto with stalmarck.\nintros H'1 x H'2; absurd (x = x); auto with stalmarck.\nunfold getMinId in H'1; apply getMinNone with (8 := H'1); auto with stalmarck.\nintros a b H'3; rewrite H'3; auto with stalmarck.\nunfold getMinId in H'2; case getMinComp with (4 := H'2); auto with stalmarck.\nintros x1 H'5; elim H'5; intros H'6 H'7; rewrite H'6; auto with stalmarck.\nunfold getMinId in H'2; apply geMinIn with (4 := H'2); auto with stalmarck.\nintros H'1; CaseEq (getMinId L2 L1); auto with stalmarck.\nintros x H'2; absurd (x = x); auto with stalmarck.\nunfold getMinId in H'1; apply getMinNone with (8 := H'1); auto with stalmarck.\nintros a b H'3; rewrite H'3; auto with stalmarck.\nunfold getMinId in H'2; case getMinComp with (4 := H'2); auto with stalmarck.\nintros x1 H'5; elim H'5; intros H'6 H'7; rewrite H'6; auto with stalmarck.\nunfold getMinId in H'2; apply geMinIn with (4 := H'2); auto with stalmarck.\nQed.\n\nDefinition getMinInv :=\n  getMin _ rZlt eqRz rZltEDec (fun a b : rZ => a = rZComp b)\n    (fun (a b : rZ) (_ : eqRz a b) => rZDec a (rZComp b)).\n\nTheorem getMinInvSym :\n forall L1 L2 : list rZ,\n OlistRz L1 ->\n OlistRz L2 ->\n match getMinInv L1 L2 with\n | None => getMinInv L2 L1 = None\n | Some a => getMinInv L2 L1 = Some (rZComp a)\n end.\nProof.\nintros L1 L2 H' H'0; CaseEq (getMinInv L1 L2).\nCaseEq (getMinInv L2 L1).\nintros x H'1 x0 H'2.\ncase (rZltEDec x0 x); auto with stalmarck.\nintros H'3; case H'3.\nintros H'4.\nabsurd (rZComp x0 = rZComp x0); auto with stalmarck.\nunfold getMinInv in H'1; apply getMinMin with (10 := H'1); auto with stalmarck.\nintros a b H'5; rewrite H'5; auto with stalmarck.\napply rZltEqComp with (a := x0) (b := x); auto with stalmarck.\nunfold getMinInv in H'2; case getMinComp with (4 := H'2); auto with stalmarck.\nintros x1 H'5; elim H'5; intros H'6 H'7; rewrite H'6; rewrite rZCompInv; auto with stalmarck.\nunfold getMinInv in H'2; apply geMinIn with (4 := H'2); auto with stalmarck.\nintros H'4.\nabsurd (rZComp x = rZComp x); auto with stalmarck.\nunfold getMinInv in H'2; apply getMinMin with (10 := H'2); auto with stalmarck.\nintros a b H'5; rewrite H'5; auto with stalmarck.\napply rZltEqComp with (a := x) (b := x0); auto with stalmarck.\nunfold getMinInv in H'1; case getMinComp with (4 := H'1); auto with stalmarck.\nintros x1 H'5; elim H'5; intros H'6 H'7; rewrite H'6; rewrite rZCompInv; auto with stalmarck.\nunfold getMinInv in H'1; apply geMinIn with (4 := H'1); auto with stalmarck.\nintros H'3;\n rewrite (OlistIn _ rZlt eqRz) with (L := L1) (a := x0) (b := rZComp x); \n auto using f_equal with stalmarck.\nunfold getMinInv in H'2; apply geMinIn with (4 := H'2); auto with stalmarck.\nunfold getMinInv in H'1; case getMinComp with (4 := H'1); auto with stalmarck.\nintros x1 H'5; elim H'5; intros H'6 H'7; rewrite H'6; rewrite rZCompInv; auto with stalmarck.\napply eqrZTrans with (1 := H'3); auto with stalmarck.\nintros H'1 x H'2; absurd (rZComp x = rZComp x); auto with stalmarck.\nunfold getMinInv in H'1; apply getMinNone with (8 := H'1); auto with stalmarck.\nintros a b H'3; rewrite H'3; auto with stalmarck.\nunfold getMinInv in H'2; case getMinComp with (4 := H'2); auto with stalmarck.\nintros x1 H'5; elim H'5; intros H'6 H'7; rewrite H'6; rewrite rZCompInv; auto with stalmarck.\nunfold getMinInv in H'2; apply geMinIn with (4 := H'2); auto with stalmarck.\nintros H'1; CaseEq (getMinInv L2 L1); auto with stalmarck.\nintros x H'2; absurd (rZComp x = rZComp x); auto with stalmarck.\nunfold getMinInv in H'1; apply getMinNone with (8 := H'1); auto with stalmarck.\nintros a b H'3; rewrite H'3; auto with stalmarck.\nunfold getMinInv in H'2; case getMinComp with (4 := H'2); auto with stalmarck.\nintros x1 H'5; elim H'5; intros H'6 H'7; rewrite H'6; rewrite rZCompInv; auto with stalmarck.\nunfold getMinInv in H'2; apply geMinIn with (4 := H'2); auto with stalmarck.\nQed.\n\n(** Given two arrays and a rNat find the smallest element that are in\n    both equivalent classes of a *)\nDefinition getEquivMin (Ar1 Ar2 : rArray vM) (a : rNat) : rZ :=\n  match getEquiv Ar1 a with\n  | (L1, true) =>\n      match getEquiv Ar2 a with\n      | (L2, true) =>\n          match getMinId L1 L2 with\n          | Some b => rZComp b\n          | None => rZPlus zero\n          end\n      | (L2, false) =>\n          match getMinInv L1 L2 with\n          | Some b => rZComp b\n          | None => rZPlus zero\n          end\n      end\n  | (L1, false) =>\n      match getEquiv Ar2 a with\n      | (L2, true) =>\n          match getMinInv L1 L2 with\n          | Some b => b\n          | None => rZPlus zero\n          end\n      | (L2, false) =>\n          match getMinId L1 L2 with\n          | Some b => b\n          | None => rZPlus zero\n          end\n      end\n  end.\n\nTheorem getEquivMinSym :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (a : rNat),\n getEquivMin Ar1 Ar2 a = getEquivMin Ar2 Ar1 a.\nProof.\nintros Ar1 Ar2 War1 War2 a; unfold getEquivMin in |- *;\n generalize (getEquivProp3 Ar1 War1 a); generalize (getEquivProp3 Ar2 War2 a);\n case (getEquiv Ar1 a); case (getEquiv Ar2 a); simpl in |- *.\nintros L1 b1 L2 b2 OL1 OL2; case b1; case b2; auto with stalmarck;\n try rewrite (getMinIdSym L1 L2); auto with stalmarck; generalize (getMinInvSym L1 L2); \n auto with stalmarck; case (getMinInv L1 L2); auto with stalmarck; case (getMinInv L2 L1); \n auto with stalmarck; intros x1 x2 Hx1 || intros x1 Hx1; auto with stalmarck; generalize (Hx1 OL1 OL2);\n intros Inv0; inversion Inv0; auto with stalmarck.\nQed.\n\nTheorem rZCompInvolList : forall L : list rZ, L = map rZComp (map rZComp L).\nProof.\nintros L; elim L; simpl in |- *; auto with stalmarck.\nintros a l H'; rewrite <- H'; auto with datatypes stalmarck.\nrewrite <- rZCompInvol; auto with stalmarck.\nQed.\n\nTheorem getEquivMinIn1 :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (a : rNat),\n In (getEquivMin Ar1 Ar2 a) (getEquivList Ar1 (rZPlus a)).\nProof.\nintros Ar1 Ar2 War1 War2 a;\n generalize (getEquivListProp2 Ar1 War1 (rZPlus a));\n generalize (getEquivListProp3 Ar1 War1 (rZPlus a));\n generalize (getEquivListProp2 Ar2 War2 (rZPlus a));\n generalize (getEquivListProp3 Ar2 War2 (rZPlus a)); \n simpl in |- *; unfold getEquivMin in |- *; case (getEquiv Ar1 a); \n intros l b; case b; case (getEquiv Ar2 a); intros l0 b0; \n case b0; auto with stalmarck.\nCaseEq (getMinId l l0); auto with stalmarck.\nintros x H' H'0 H'1 H'2 H'3; apply in_map; auto with stalmarck.\nunfold getMinId in H'; apply geMinIn with (4 := H'); auto with stalmarck.\nrewrite (rZCompInvolList l); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\nrewrite (rZCompInvolList l0); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\nintros H' H'0 H'1 H'2 H'3.\nunfold getMinId in H';\n case getMinNone with (8 := H') (a := rZMinus a) (b := rZMinus a); \n auto with stalmarck.\nintros a0 b1 H'4; rewrite H'4; auto with stalmarck.\nrewrite (rZCompInvolList l); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\nrewrite (rZCompInvolList l0); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\napply inMapComp; auto with stalmarck.\napply inMapComp; auto with stalmarck.\nCaseEq (getMinInv l l0); auto with stalmarck.\nintros x H' H'0 H'1 H'2 H'3; apply in_map; auto with stalmarck.\nunfold getMinInv in H'; apply geMinIn with (4 := H'); auto with stalmarck.\nrewrite (rZCompInvolList l); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\nintros H' H'0 H'1 H'2 H'3.\nunfold getMinInv in H';\n case getMinNone with (8 := H') (a := rZMinus a) (b := rZPlus a); \n auto with stalmarck.\nintros a0 b1 H'4; rewrite H'4; auto with stalmarck.\nrewrite (rZCompInvolList l); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\napply inMapComp; auto with stalmarck.\nCaseEq (getMinInv l l0); auto with stalmarck.\nintros x H' H'0 H'1 H'2 H'3.\nunfold getMinInv in H'; apply geMinIn with (4 := H'); auto with stalmarck.\nrewrite (rZCompInvolList l0); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\nintros H' H'0 H'1 H'2 H'3.\nunfold getMinInv in H';\n case getMinNone with (8 := H') (a := rZPlus a) (b := rZMinus a); \n auto with stalmarck.\nintros a0 b1 H'4; rewrite H'4; auto with stalmarck.\nrewrite (rZCompInvolList l0); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\napply inMapComp; auto with stalmarck.\nCaseEq (getMinId l l0); auto with stalmarck.\nintros x H' H'0 H'1 H'2 H'3.\nunfold getMinId in H'; apply geMinIn with (4 := H'); auto with stalmarck.\nintros H' H'0 H'1 H'2 H'3.\nunfold getMinId in H';\n case getMinNone with (8 := H') (a := rZPlus a) (b := rZPlus a); \n auto with stalmarck.\nintros a0 b1 H'4; rewrite H'4; auto with stalmarck.\nQed.\n\nTheorem getEquivMinIn2 :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (a : rNat),\n In (getEquivMin Ar1 Ar2 a) (getEquivList Ar2 (rZPlus a)).\nProof.\nintros Ar1 Ar2 War1 War2 a;\n generalize (getEquivListProp2 Ar1 War1 (rZPlus a));\n generalize (getEquivListProp3 Ar1 War1 (rZPlus a));\n generalize (getEquivListProp2 Ar2 War2 (rZPlus a));\n generalize (getEquivListProp3 Ar2 War2 (rZPlus a)); \n simpl in |- *; unfold getEquivMin in |- *; case (getEquiv Ar1 a); \n intros l b; case b; case (getEquiv Ar2 a); intros l0 b0; \n case b0; auto with stalmarck.\nCaseEq (getMinId l l0); auto with stalmarck.\nintros x H' H'0 H'1 H'2 H'3; apply in_map; auto with stalmarck.\nunfold getMinId in H'; case getMinComp with (4 := H'); auto with stalmarck.\nrewrite (rZCompInvolList l); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\nrewrite (rZCompInvolList l0); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\nintros x0 H'4; elim H'4; intros H'5 H'6; rewrite H'5; auto with stalmarck.\nintros H' H'0 H'1 H'2 H'3.\nunfold getMinId in H';\n case getMinNone with (8 := H') (a := rZMinus a) (b := rZMinus a); \n auto with stalmarck.\nintros a0 b1 H'4; rewrite H'4; auto with stalmarck.\nrewrite (rZCompInvolList l); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\nrewrite (rZCompInvolList l0); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\napply inMapComp; auto with stalmarck.\napply inMapComp; auto with stalmarck.\nCaseEq (getMinInv l l0); auto with stalmarck.\nintros x H' H'0 H'1 H'2 H'3.\nunfold getMinInv in H'; case getMinComp with (4 := H'); auto with stalmarck.\nrewrite (rZCompInvolList l); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\nintros x0 H'4; elim H'4; intros H'5 H'6; rewrite H'5; rewrite rZCompInv; auto with stalmarck.\nintros H' H'0 H'1 H'2 H'3.\nunfold getMinInv in H';\n case getMinNone with (8 := H') (a := rZMinus a) (b := rZPlus a); \n auto with stalmarck.\nintros a0 b1 H'4; rewrite H'4; auto with stalmarck.\nrewrite (rZCompInvolList l); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\napply inMapComp; auto with stalmarck.\nCaseEq (getMinInv l l0); auto with stalmarck.\nintros x H' H'0 H'1 H'2 H'3.\nunfold getMinInv in H'; case getMinComp with (4 := H'); auto with stalmarck.\nrewrite (rZCompInvolList l0); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\nintros x0 H'4; elim H'4; intros H'5 H'6; rewrite H'5.\napply inMapComp; rewrite <- (rZCompInvolList l0); rewrite rZCompInv; auto with stalmarck.\nintros H' H'0 H'1 H'2 H'3.\nunfold getMinInv in H';\n case getMinNone with (8 := H') (a := rZPlus a) (b := rZMinus a); \n auto with stalmarck.\nintros a0 b1 H'4; rewrite H'4; auto with stalmarck.\nrewrite (rZCompInvolList l0); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\napply inMapComp; auto with stalmarck.\nCaseEq (getMinId l l0); auto with stalmarck.\nintros x H' H'0 H'1 H'2 H'3.\nunfold getMinId in H'; case getMinComp with (4 := H'); auto with stalmarck.\nintros x0 H'4; elim H'4; intros H'5 H'6; rewrite H'5; auto with stalmarck.\nintros H' H'0 H'1 H'2 H'3.\nunfold getMinId in H';\n case getMinNone with (8 := H') (a := rZPlus a) (b := rZPlus a); \n auto with stalmarck.\nintros a0 b1 H'4; rewrite H'4; auto with stalmarck.\nQed.\n\nTheorem getEquivMinMin :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (a : rNat) (c : rZ),\n rZlt c (getEquivMin Ar1 Ar2 a) ->\n ~ (In c (getEquivList Ar1 (rZPlus a)) /\\ In c (getEquivList Ar2 (rZPlus a))).\nProof.\nintros Ar1 Ar2 War1 War2 a;\n generalize (getEquivListProp2 Ar1 War1 (rZPlus a));\n generalize (getEquivListProp3 Ar1 War1 (rZPlus a));\n generalize (getEquivListProp2 Ar2 War2 (rZPlus a));\n generalize (getEquivListProp3 Ar2 War2 (rZPlus a)); \n simpl in |- *; unfold getEquivMin in |- *; case (getEquiv Ar1 a); \n intros l b; case b; case (getEquiv Ar2 a); intros l0 b0; \n case b0; auto with stalmarck.\nCaseEq (getMinId l l0).\nintros x H' H'0 H'1 H'2 H'3 c H'4; red in |- *; intros H'5; Elimc H'5;\n intros H'5 H'6.\nabsurd (rZComp c = rZComp c); auto with stalmarck.\nunfold getMinId in H'; apply getMinMin with (10 := H'); auto with stalmarck.\nintros a0 b1 H'7; rewrite H'7; auto with stalmarck.\nrewrite (rZCompInvolList l); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\nrewrite (rZCompInvolList l0); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\napply rZltEqComp with (a := c) (b := rZComp x); auto with stalmarck.\napply inMapComp; rewrite <- rZCompInvol; auto with stalmarck.\napply inMapComp; rewrite <- rZCompInvol; auto with stalmarck.\nintros H' H'0 H'1 H'2 H'3.\nunfold getMinId in H';\n case getMinNone with (8 := H') (a := rZMinus a) (b := rZMinus a); \n auto with stalmarck.\nintros a0 b1 H'4; rewrite H'4; auto with stalmarck.\nrewrite (rZCompInvolList l); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\nrewrite (rZCompInvolList l0); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\napply inMapComp; auto with stalmarck.\napply inMapComp; auto with stalmarck.\nCaseEq (getMinInv l l0).\nintros x H' H'0 H'1 H'2 H'3 c H'4; red in |- *; intros H'5; Elimc H'5;\n intros H'5 H'6; auto with stalmarck.\nabsurd (rZComp c = rZComp c); auto with stalmarck.\nunfold getMinInv in H'; apply getMinMin with (10 := H'); auto with stalmarck.\nintros a0 b1 H'7; rewrite H'7; auto with stalmarck.\nrewrite (rZCompInvolList l); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\napply rZltEqComp with (a := c) (b := rZComp x); auto with stalmarck.\napply inMapComp; rewrite <- rZCompInvol; auto with stalmarck.\nintros H' H'0 H'1 H'2 H'3.\nunfold getMinInv in H';\n case getMinNone with (8 := H') (a := rZMinus a) (b := rZPlus a); \n auto with stalmarck.\nintros a0 b1 H'4; rewrite H'4; auto with stalmarck.\nrewrite (rZCompInvolList l); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\napply inMapComp; auto with stalmarck.\nCaseEq (getMinInv l l0).\nintros x H' H'0 H'1 H'2 H'3 c H'4; red in |- *; intros H'5; Elimc H'5;\n intros H'5 H'6.\nabsurd (c = rZComp (rZComp c)); auto with stalmarck.\nunfold getMinInv in H'; apply getMinMin with (10 := H'); auto with stalmarck.\nintros a0 b1 H'7; rewrite H'7; auto with stalmarck.\nrewrite (rZCompInvolList l0); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\napply inMapComp; rewrite <- rZCompInvol; auto with stalmarck.\nintros H' H'0 H'1 H'2 H'3.\nunfold getMinInv in H';\n case getMinNone with (8 := H') (a := rZPlus a) (b := rZMinus a); \n auto with stalmarck.\nintros a0 b1 H'4; rewrite H'4; auto with stalmarck.\nrewrite (rZCompInvolList l0); auto with stalmarck.\napply Olistf with (eqA := eqRz); auto with stalmarck.\ntry exact rZltEqComp.\napply inMapComp; auto with stalmarck.\nCaseEq (getMinId l l0).\nintros x H' H'0 H'1 H'2 H'3 c H'4; red in |- *; intros H'5; Elimc H'5;\n intros H'5 H'6.\nabsurd (c = c); auto with stalmarck.\nunfold getMinId in H'; apply getMinMin with (10 := H'); auto with stalmarck.\nintros a0 b1 H'7; rewrite H'7; auto with stalmarck.\nintros H' H'0 H'1 H'2 H'3.\nunfold getMinId in H';\n case getMinNone with (8 := H') (a := rZPlus a) (b := rZPlus a); \n auto with stalmarck.\nintros a0 b1 H'4; rewrite H'4; auto with stalmarck.\nQed.\n\nTheorem getEquivMinEq1 :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (S : State),\n rArrayState Ar1 S ->\n forall a : rNat, eqStateRz S (rZPlus a) (getEquivMin Ar1 Ar2 a).\nProof.\nintros Ar1 Ar2 War1 War2 S H' a.\napply rArrayStateDef2 with (Ar := Ar1); auto with stalmarck.\ncase (getEquivListProp1 Ar1 War1 (rZPlus a) (getEquivMin Ar1 Ar2 a)).\nintros H'0; rewrite H'0; auto with stalmarck.\napply getEquivMinIn1; auto with stalmarck.\nQed.\n\nTheorem getEquivMinEq2 :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (S : State),\n rArrayState Ar2 S ->\n forall a : rNat, eqStateRz S (rZPlus a) (getEquivMin Ar1 Ar2 a).\nProof.\nintros Ar1 Ar2 War1 War2 S H' a.\napply rArrayStateDef2 with (Ar := Ar2); auto with stalmarck.\ncase (getEquivListProp1 Ar2 War2 (rZPlus a) (getEquivMin Ar1 Ar2 a)).\nintros H'0; rewrite H'0; auto with stalmarck.\nrewrite getEquivMinSym; auto with stalmarck.\napply getEquivMinIn1; auto with stalmarck.\nQed.\n\nTheorem getEquivMinMinEq :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (S1 S2 : State),\n rArrayState Ar1 S1 ->\n rArrayState Ar2 S2 ->\n forall (a : rNat) (c : rZ),\n rZlt c (getEquivMin Ar1 Ar2 a) ->\n ~ (eqStateRz S1 (rZPlus a) c /\\ eqStateRz S2 (rZPlus a) c).\nProof.\nintros Ar1 Ar2 War1 War2 S1 S2 H' H'0 a c H'1; red in |- *; intros H'2;\n Elimc H'2; intros H'2 H'3; auto with stalmarck.\nabsurd\n (In c (getEquivList Ar1 (rZPlus a)) /\\ In c (getEquivList Ar2 (rZPlus a)));\n auto with stalmarck.\napply getEquivMinMin; auto with stalmarck.\nsplit; auto with stalmarck.\ncase (getEquivListProp1 Ar1 War1 (rZPlus a) c).\nintros H'4 H'5; apply H'5; auto with stalmarck.\napply rArrayStateDef1 with (S := S1); auto with stalmarck.\ncase (getEquivListProp1 Ar2 War2 (rZPlus a) c).\nintros H'4 H'5; apply H'5; auto with stalmarck.\napply rArrayStateDef1 with (S := S2); auto with stalmarck.\nQed.\n\nTheorem eqNotltRz : forall a b : rZ, rZlt a b -> a <> b.\nProof.\nintros a b H'; red in |- *; intros H'0; absurd (rZlt a b); auto with stalmarck.\nrewrite H'0; auto with stalmarck.\nQed.\n\n#[local] Hint Resolve eqNotltRz : stalmarck.\n\nTheorem evalZMin :\n forall (Ar : rArray vM) (War : wellFormedArray Ar) (S : State),\n rArrayState Ar S ->\n forall a c : rZ, rZlt c (evalZ Ar a) -> ~ eqStateRz S a c.\nProof.\nintros Ar War S H'0 a c H'1; red in |- *; intros H'2.\nabsurd (evalZ Ar c = evalZ Ar a); auto with stalmarck.\ngeneralize H'1 H'2; clear H'1 H'2.\ncase c; case a; simpl in |- *; intros a' c'; unfold evalN in |- *;\n CaseEq (rArrayGet vM Ar a'); CaseEq (rArrayGet vM Ar c'); \n auto with stalmarck; intros r H' r0 H'1 H'2 H'3; red in |- *; intros H'4;\n (absurd (rVlt r c'); [ idtac | apply wfPd with (Ar := Ar) ]); \n auto with stalmarck; try (rewrite H'4; unfold rVlt in |- *; apply rltAntiSym; auto with stalmarck);\n rewrite (rZCompInvol r); rewrite H'4; unfold rVlt in |- *; \n apply rltAntiSym; generalize H'2; case r0; simpl in |- *; \n auto with stalmarck.\napply rArrayStateDef1 with (S := S); auto with stalmarck.\nQed.\n\nTheorem getEquivIdR :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (S1 S2 : State),\n rArrayState Ar1 S1 ->\n rArrayState Ar2 S2 ->\n forall a : rNat,\n eqStateRz S2 (rZPlus a) (evalZ Ar1 (rZPlus a)) ->\n getEquivMin Ar1 Ar2 a = evalZ Ar1 (rZPlus a).\nProof.\nintros Ar1 Ar2 War1 War2 S1 S2 Sar1 Sar2 a H'0;\n case (rZltEDec (getEquivMin Ar1 Ar2 a) (evalZ Ar1 (rZPlus a))); \n intros s; [ Casec s; intros s | idtac ].\ncase evalZMin with (3 := s) (S := S1); auto with stalmarck.\napply getEquivMinEq1; auto with stalmarck.\ncase getEquivMinMinEq with (5 := s) (S1 := S1) (S2 := S2); auto with stalmarck; split; auto with stalmarck.\napply rArrayStateDef2 with (Ar := Ar1); auto with stalmarck.\nrewrite evalZInv; auto with stalmarck.\ncase (eqRzElim _ _ s); auto with stalmarck.\nintros H'1; absurd (contradictory S1); auto with stalmarck.\nred in |- *; intros H'; elim H'.\nintros x H'2; absurd (evalZ Ar1 x = evalZ Ar1 (rZComp x)).\nrewrite evalZComp; auto with stalmarck.\napply rArrayStateDef1 with (S := S1); auto with stalmarck.\nred in |- *; auto with stalmarck.\nexists (rZPlus a); auto with stalmarck.\napply eqStateRzTrans with (b := evalZ Ar1 (rZPlus a)); auto with stalmarck.\napply rArrayStateDef2 with (Ar := Ar1); auto with stalmarck.\nrewrite evalZInv; auto with stalmarck.\napply eqStateInvInv; auto with stalmarck.\nrewrite <- H'1; auto with stalmarck.\nrewrite <- rZCompInvol; auto with stalmarck.\napply eqStateRzSym.\napply getEquivMinEq1; auto with stalmarck.\nQed.\n\nTheorem getEquivIdL :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (S1 S2 : State),\n rArrayState Ar1 S1 ->\n rArrayState Ar2 S2 ->\n forall a : rNat,\n eqStateRz S1 (rZPlus a) (evalZ Ar2 (rZPlus a)) ->\n getEquivMin Ar1 Ar2 a = evalZ Ar2 (rZPlus a).\nProof.\nintros Ar1 Ar2 War1 War2 S1 S2 H' H'0 a H'1.\nrewrite getEquivMinSym; auto with stalmarck.\napply getEquivIdR with (S1 := S2) (S2 := S1); auto with stalmarck.\nQed.\n\nTheorem getMinInvInd :\n forall L1 L2 : list rZ,\n OlistRz L1 -> OlistRz L2 -> getMinInv L1 (map rZComp L2) = getMinId L1 L2.\nProof.\nintros L1 L2 Ol1 Ol2; auto with stalmarck.\ncut (OlistRz (map rZComp L2));\n [ intros Ol2'\n | red in |- *; apply Olistf with (eqA := eqRz); auto with stalmarck; exact rZltEqComp ].\nCaseEq (getMinInv L1 (map rZComp L2)); auto with stalmarck.\nCaseEq (getMinId L1 L2); auto with stalmarck.\nintros x H' x0 H'0.\ncase (rZltEDec x0 x); intros s; [ Casec s; intros s | idtac ].\nabsurd (x0 = x0); auto with stalmarck.\nunfold getMinId in H'; apply getMinMin with (10 := H'); auto with stalmarck.\nintros a b H'1; rewrite H'1; auto with stalmarck.\nunfold getMinInv in H'0; apply geMinIn with (4 := H'0); auto with stalmarck.\nunfold getMinInv in H'0; elim getMinComp with (4 := H'0); auto with stalmarck.\nintros x1 H'1; Elimc H'1; intros H'1 H'2; rewrite H'1.\napply inMapComp; rewrite <- rZCompInvol; auto with stalmarck.\nabsurd (x = rZComp (rZComp x)); auto with stalmarck.\nunfold getMinInv in H'0; apply getMinMin with (10 := H'0); auto with stalmarck.\nintros a b H'1; rewrite H'1; auto with stalmarck.\nunfold getMinId in H'; apply geMinIn with (4 := H'); auto with stalmarck.\napply in_map; auto with stalmarck.\nunfold getMinId in H'; elim getMinComp with (4 := H'); auto with stalmarck.\nintros x1 H'1; Elimc H'1; intros H'1 H'2; rewrite H'1; auto with stalmarck.\nrewrite (OlistIn _ rZlt eqRz) with (a := x0) (b := x) (L := L1); auto with stalmarck.\nunfold getMinInv in H'0; apply geMinIn with (4 := H'0); auto with stalmarck.\nunfold getMinId in H'; apply geMinIn with (4 := H'); auto with stalmarck.\nintros H' x H'0; absurd (x = x); auto with stalmarck.\nunfold getMinId in H'; apply getMinNone with (8 := H'); auto with stalmarck.\nintros a b H'1; rewrite H'1; auto with stalmarck.\nunfold getMinInv in H'0; apply geMinIn with (4 := H'0); auto with stalmarck.\napply inMapComp; auto with stalmarck.\nunfold getMinInv in H'0; elim getMinComp with (4 := H'0); auto with stalmarck.\nintros x0 H'1; Elimc H'1; intros H'1 H'2; rewrite H'1; rewrite <- rZCompInvol;\n auto with stalmarck.\nCaseEq (getMinId L1 L2); auto with stalmarck.\nintros x H' H'0.\nabsurd (x = rZComp (rZComp x)); auto with stalmarck.\nunfold getMinInv in H'0; apply getMinNone with (8 := H'0); auto with stalmarck.\nintros a b H'1; rewrite H'1; auto with stalmarck.\nunfold getMinId in H'; apply geMinIn with (4 := H'); auto with stalmarck.\napply in_map; auto with stalmarck.\nunfold getMinId in H'; elim getMinComp with (4 := H'); auto with stalmarck.\nintros x0 H'1; Elimc H'1; intros H'1 H'2; rewrite H'1; auto with stalmarck.\nQed.\n\n(** List the function getEquivMin to rZ *)\nDefinition getRzMin (Ar1 Ar2 : rArray vM) (a : rZ) : rZ :=\n  match a with\n  | rZPlus a' => getEquivMin Ar1 Ar2 a'\n  | rZMinus a' => rZComp (getEquivMin Ar1 Ar2 a')\n  end.\n\nTheorem getRzMinSym :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (a : rZ),\n getRzMin Ar1 Ar2 a = getRzMin Ar2 Ar1 a.\nProof.\nintros Ar1 Ar2 War1 War2 a; case a; simpl in |- *; intros a';\n rewrite getEquivMinSym; auto with stalmarck.\nQed.\n\nTheorem getRzMinIn1 :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (a : rZ),\n In (getRzMin Ar1 Ar2 a) (getEquivList Ar1 a).\nProof.\nintros Ar1 Ar2 War1 War2 a; case a; intros a';\n generalize (getEquivMinIn1 Ar1 Ar2 War1 War2 a'); \n simpl in |- *; auto with stalmarck.\ncase (getEquiv Ar1 a'); auto with stalmarck.\nintros l b; case b; intros H'; auto with stalmarck.\napply inMapComp; rewrite <- rZCompInvol; auto with stalmarck.\napply in_map; auto with stalmarck.\nQed.\n\nTheorem getRzMinIn2 :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (a : rZ),\n In (getRzMin Ar1 Ar2 a) (getEquivList Ar2 a).\nProof.\nintros Ar1 Ar2 War1 War2 a; case a; intros a';\n generalize (getEquivMinIn2 Ar1 Ar2 War1 War2 a'); \n simpl in |- *; auto with stalmarck.\ncase (getEquiv Ar2 a'); auto with stalmarck.\nintros l b; case b; intros H'; auto with stalmarck.\napply inMapComp; rewrite <- rZCompInvol; auto with stalmarck.\napply in_map; auto with stalmarck.\nQed.\n\nTheorem getRzMinMin :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (a c : rZ),\n rZlt c (getRzMin Ar1 Ar2 a) ->\n ~ (In c (getEquivList Ar1 a) /\\ In c (getEquivList Ar2 a)).\nProof.\nintros Ar1 Ar2 War1 War2 a c; case a; intros a';\n generalize (getEquivMinMin Ar1 Ar2 War1 War2 a'); \n simpl in |- *; auto with stalmarck.\ncase (getEquiv Ar1 a'); case (getEquiv Ar2 a'); intros l b l0 b0; case b;\n case b0; simpl in |- *; intros H' H'0; red in |- *; \n intros H'1; Elimc H'1; intros H'1 H'2;\n (case (H' (rZComp c)); [ apply rZltEqComp with (1 := H'0); auto with stalmarck | idtac ]);\n split; try apply in_map; auto with stalmarck; apply inMapComp; rewrite <- rZCompInvol; \n auto with stalmarck.\nQed.\n\nTheorem getRzMinEq1 :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (S : State),\n rArrayState Ar1 S -> forall a : rZ, eqStateRz S a (getRzMin Ar1 Ar2 a).\nProof.\nintros Ar1 Ar2 War1 War2 S H' a; case a; intros a';\n generalize (getEquivMinEq1 Ar1 Ar2 War1 War2 S H' a'); \n simpl in |- *; auto with stalmarck.\nQed.\n\nTheorem getRzMinEq2 :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (S : State),\n rArrayState Ar2 S -> forall a : rZ, eqStateRz S a (getRzMin Ar1 Ar2 a).\nProof.\nintros Ar1 Ar2 War1 War2 S H' a; case a; intros a';\n generalize (getEquivMinEq2 Ar1 Ar2 War1 War2 S H' a'); \n simpl in |- *; auto with stalmarck.\nQed.\n\nTheorem getRzMinMinEq :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (S1 S2 : State),\n rArrayState Ar1 S1 ->\n rArrayState Ar2 S2 ->\n forall a c : rZ,\n rZlt c (getRzMin Ar1 Ar2 a) -> ~ (eqStateRz S1 a c /\\ eqStateRz S2 a c).\nProof.\nintros Ar1 Ar2 War1 War2 S1 S2 H' H'0 a c; case a; intros a';\n generalize (getEquivMinMinEq Ar1 Ar2 War1 War2 S1 S2 H' H'0 a').\nauto with stalmarck.\nintros H'1 H'2; red in |- *; intros H'3; Elimc H'3; intros H'3 H'4.\ncase (H'1 (rZComp c));\n [ apply rZltEqComp with (1 := H'2); simpl in |- *; auto with stalmarck | idtac ]; \n split; auto with stalmarck.\nQed.\n\nTheorem getRzMinUnique :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (S1 S2 : State),\n rArrayState Ar1 S1 ->\n rArrayState Ar2 S2 ->\n forall a b : rZ,\n eqStateRz S1 a b ->\n eqStateRz S2 a b -> getRzMin Ar1 Ar2 a = getRzMin Ar1 Ar2 b.\nProof.\nintros Ar1 Ar2 War1 War2 S1 S2 H' H'0 a b H'1 H'2.\ncut (getEquivList Ar1 a = getEquivList Ar1 b);\n [ intros Eq1 | case (getEquivListProp4 Ar1 War1 S1 H' a b) ]; \n auto with stalmarck.\ncut (getEquivList Ar2 a = getEquivList Ar2 b);\n [ intros Eq2 | case (getEquivListProp4 Ar2 War2 S2 H'0 a b) ]; \n auto with stalmarck.\ncase (rZltEDec (getRzMin Ar1 Ar2 a) (getRzMin Ar1 Ar2 b)); intros s;\n [ Casec s; intros s | idtac ].\ncase getRzMinMinEq with (5 := s) (S1 := S1) (S2 := S2); auto with stalmarck; split; auto with stalmarck.\napply eqStateRzTrans with (b := a); auto with stalmarck.\napply getRzMinEq1; auto with stalmarck.\napply eqStateRzTrans with (b := a); auto with stalmarck.\napply getRzMinEq2; auto with stalmarck.\ncase getRzMinMinEq with (5 := s) (S1 := S1) (S2 := S2); auto with stalmarck; split; auto with stalmarck.\napply eqStateRzTrans with (b := b); auto with stalmarck.\napply getRzMinEq1; auto with stalmarck.\napply eqStateRzTrans with (b := b); auto with stalmarck.\napply getRzMinEq2; auto with stalmarck.\napply OlistIn with (ltA := rZlt) (eqA := eqRz) (L := getEquivList Ar1 b);\n auto with stalmarck.\nrewrite <- Eq1.\napply getRzMinIn1; auto with stalmarck.\napply getRzMinIn1; auto with stalmarck.\napply getEquivListProp2; auto with stalmarck.\nQed.\n\nTheorem forallgetEquivgetRzMin :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (S : State),\n (forall a : rNat, eqStateRz S (rZPlus a) (getEquivMin Ar1 Ar2 a)) ->\n forall a : rZ, eqStateRz S a (getRzMin Ar1 Ar2 a).\nProof.\nintros Ar1 Ar2 War1 War2 S H' a; case a; intros a'; simpl in |- *; auto with stalmarck.\napply eqStateRzInv with (1 := H' a'); auto with stalmarck.\nQed.\n\n(** here where we wanted to arrive a state S that is included is S1 and S2\n   and for every a, a is in relation with the intersection of the equivalent classes,\n  then S is the intersection *)\nTheorem getEquivInter :\n forall (Ar1 Ar2 : rArray vM) (War1 : wellFormedArray Ar1)\n   (War2 : wellFormedArray Ar2) (S S1 S2 : State),\n rArrayState Ar1 S1 ->\n rArrayState Ar2 S2 ->\n (forall a : rNat, eqStateRz S (rZPlus a) (getEquivMin Ar1 Ar2 a)) ->\n inclState (interState S1 S2) S.\nProof.\nintros Ar1 Ar2 War1 War2 S S1 S2 H' H'0 H'1.\nred in |- *; auto with stalmarck.\nintros i j H'2.\ncut (eqStateRz S1 i j); [ intros Em1 | apply eqStateIncl with (2 := H'2) ];\n auto with stalmarck.\ncut (eqStateRz S2 i j); [ intros Em2 | apply eqStateIncl with (2 := H'2) ];\n auto with stalmarck.\ncase (rZDec i j); intros Eqij; auto with stalmarck.\nrewrite Eqij; auto with stalmarck.\napply eqStateRzTrans with (b := getRzMin Ar1 Ar2 i).\napply forallgetEquivgetRzMin; auto with stalmarck.\nrewrite (getRzMinUnique Ar1 Ar2 War1 War2 S1 S2 H' H'0 i j); auto with stalmarck.\napply eqStateRzSym; auto with stalmarck.\napply forallgetEquivgetRzMin; auto with stalmarck.\nQed.\n\nEnd inter.\n", "meta": {"author": "coq-community", "repo": "stalmarck", "sha": "9e6cd57df21f991ca5cdd54800707b96fba16ced", "save_path": "github-repos/coq/coq-community-stalmarck", "path": "github-repos/coq/coq-community-stalmarck/stalmarck-9e6cd57df21f991ca5cdd54800707b96fba16ced/theories/Algorithm/interImplement.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23371083587415176}}
{"text": "Require Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.Util.Compat.\nRequire Import MirrorCore.Views.Ptrns.\nRequire Import MirrorCore.Lambda.ExprCore.\nRequire Import MirrorCore.Lambda.ExprD.\nRequire Import MirrorCore.Lambda.RedAll.\nRequire Import MirrorCore.Lambda.RewriteRelations.\nRequire Import MirrorCore.Lambda.RewriteStrat.\nRequire Import MirrorCore.Lambda.Red.\nRequire Import MirrorCore.Lambda.Ptrns.\nRequire Import MirrorCore.Lambda.Rewrite.HintDbs.\nRequire Import MirrorCore.Reify.Reify.\nRequire Import MirrorCore.RTac.IdtacK.\nRequire Import MirrorCore.RTac.Intro.\nRequire Import MirrorCore.RTac.Then.\nRequire Import MirrorCore.RTac.RunOnGoals.\nRequire Import MirrorCore.RTac.PApply.\nRequire Import MirrorCore.CTypes.CoreTypes.\nRequire Import MirrorCore.Polymorphic.\nRequire Import MirrorCore.PLemma.\n\nRequire Import McExamples.PolyRewrite.MSimple.\nRequire Import McExamples.PolyRewrite.MSimpleReify.\n\nExisting Instance RType_typ.\nExisting Instance Expr.Expr_expr.\nExisting Instance Expr.ExprOk_expr.\nExisting Instance Typ2_Fun.\nExisting Instance Typ2Ok_Fun.\n\nRequire Import MirrorCore.VariablesI.\nRequire Import MirrorCore.Lambda.ExprVariables.\n\nGlobal Instance ExprVar_expr : ExprVar (expr typ func) := _.\nGlobal Instance ExprVarOk_expr : ExprVarOk ExprVar_expr := _.\n\nGlobal Instance ExprUVar_expr : ExprUVar (expr typ func) := _.\nGlobal Instance ExprUVarOk_expr : ExprUVarOk ExprUVar_expr := _.\n\nDefinition subst : Type :=\n  FMapSubst.SUBST.raw (expr typ func).\nGlobal Instance SS : SubstI.Subst subst (expr typ func) :=\n  @FMapSubst.SUBST.Subst_subst _.\nGlobal Instance SU : SubstI.SubstUpdate subst (expr typ func) :=\n  @FMapSubst.SUBST.SubstUpdate_subst _ _ _ _.\nGlobal Instance SO : @SubstI.SubstOk _ _ _ _ _ SS :=\n  @FMapSubst.SUBST.SubstOk_subst typ RType_typ (expr typ func) _.\nGlobal Instance SUO : @SubstI.SubstUpdateOk _ _ _ _ _ _ SU SO :=  @FMapSubst.SUBST.SubstUpdateOk_subst typ RType_typ (expr typ func) _ _.\n\nDefinition fintro (e : expr typ func) : option (@OpenAs typ (expr typ func)) :=\n  match e with\n  | App (Inj (Ex t)) P => Some (AsEx t (fun x => beta (App P x)))\n  | App (Inj (All t)) P => Some (AsAl t (fun x => beta (App P x)))\n  | App (App (Inj Impl) P) Q => Some (AsHy P Q)\n  | _ => None\n  end.\n\nDefinition INTRO := @INTRO typ (expr typ func) ExprVar_expr ExprUVar_expr fintro.\n\n\nLemma forall_exists_eq {A : Type} : forall x : A, exists y, x = y.\nProof.\n  intros.\n  exists x. reflexivity.\nQed.\n\nDefinition lem_forall_exists_eq : polymorphic typ 1 (Lemma.lemma typ (expr typ func) (expr typ func)) :=\n  Eval unfold Lemma.add_var, Lemma.add_prem , Lemma.vars , Lemma.concl , Lemma.premises in\n  <:: @forall_exists_eq ::>.\n\nDefinition p_lem_forall_exists_eq : PolyLemma typ (expr typ func) (expr typ func) :=\n {| p_n := 1;\n    p_lem := lem_forall_exists_eq;\n    p_tc := fun _ => true\n |}.\n\nPrint lem_forall_exists_eq.\n\nLet tyBNat := CoreTypes.tyBase0 tyNat.\nLet tyBBool := CoreTypes.tyBase0 tyBool.\n\nDefinition fAnd a b : expr typ func := App (App (Inj MSimple.And) a) b.\nDefinition fOr a b : expr typ func := App (App (Inj MSimple.And) a) b.\nDefinition fAll t P : expr typ func := App (Inj (MSimple.All t)) (Abs t P).\nDefinition fEx t P : expr typ func := App (Inj (MSimple.Ex t)) (Abs t P).\nDefinition fEq t : expr typ func := (Inj (MSimple.Eq t)).\nDefinition fImpl : expr typ func := (Inj MSimple.Impl).\nDefinition mkEq t a b : expr typ func := App (App (fEq t) a) b.\nDefinition fN n : expr typ func := Inj (MSimple.N n).\n\nRequire Import MirrorCore.RTac.PApply.\nRequire Import MirrorCore.Lambda.ExprUnify_simple.\nAbout func.\n\nDefinition PAPPLY (plem : PolyLemma typ (expr typ func) (expr typ func)) :=\n  PAPPLY\n    (fun subst SS SU tus tvs n l r t s =>\n              @exprUnify subst typ func RType_typ RSym_func Typ2_Fun\n                         SS SU 10 tus tvs n l r t s) func_unify plem.\n\nEval vm_compute in\n    (THEN INTRO (runOnGoals (PAPPLY p_lem_forall_exists_eq)))\n      (CTop nil nil)\n      (TopSubst _ nil nil)\n      (fAll tyBNat (fEx tyBNat (mkEq tyBNat (Var 1) (Var 0)))).\n", "meta": {"author": "gmalecha", "repo": "mirror-core", "sha": "b962fbca15b0b5a4653f66d29d7115bb04ebd4f3", "save_path": "github-repos/coq/gmalecha-mirror-core", "path": "github-repos/coq/gmalecha-mirror-core/mirror-core-b962fbca15b0b5a4653f66d29d7115bb04ebd4f3/examples/PolyApply/DemoPolyApply.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23371083587415173}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Relations.Relation_Definitions.\nRequire Import \"Misc/Tactics\".\nRequire Import \"Calculus/Sets\".\nRequire Import \"Calculus/Definitions\".\nRequire Import \"Calculus/Monad\".\nRequire Import \"Calculus/MultiStaged/Definitions\".\n\nModule Type DataGathering (R:Replacement) \n  (S:ReplacementCalculus R).\n\n  Parameter dg_t: Type.\n  Parameter dg_empty: dg_t.\n  Parameter dg_eabs: dg_t -> S.var -> dg_t.\n  Parameter dg_efix: dg_t -> S.var -> S.var -> dg_t.\n  Parameter dg_eapp_l: dg_t -> dg_t.\n  Parameter dg_eapp_r: dg_t -> dg_t.\n  Parameter dg_eref: dg_t -> dg_t.\n  Parameter dg_ederef: dg_t -> dg_t.\n  Parameter dg_eassign_l: dg_t -> dg_t.\n  Parameter dg_eassign_r: dg_t -> dg_t.\n  Parameter dg_erun: dg_t -> dg_t.\n  Parameter dg_elift: dg_t -> dg_t.\n  Parameter dg_ebox: dg_t -> dg_t.\n\nEnd DataGathering.\n\nModule Type DataGatheringPredicates (R:Replacement) \n  (S:ReplacementCalculus R) (DG:DataGathering R S).\n\n  Import DG.\n\n  (**\n  All predicates aim to express well-formness properties\n  of data gathering values. As we have no information\n  about data gathering types, we need those properties\n  in a quite complicated way, controlling the tree\n  of applications of abstract operations over those types.\n  *)\n\n  (**\n  dg_comp dg1 dg2 is true iff dg2 is resulting from dg1\n  by composing it with arbitrary number of dg_.. operations.\n  *)\n  Inductive dg_comp : dg_t -> dg_t -> Prop :=\n  | DgCompId : forall (dg:dg_t), dg_comp dg dg\n  | DgCompEAbs : forall (dg1 dg2:dg_t) (x:S.var),\n    dg_comp dg1 dg2 -> dg_comp dg1 (dg_eabs dg2 x)\n  | DgCompEFix : forall (dg1 dg2:dg_t) (f x:S.var),\n    dg_comp dg1 dg2 -> dg_comp dg1 (dg_efix dg2 f x)\n  | DgCompEAppL : forall (dg1 dg2:dg_t),\n    dg_comp dg1 dg2 -> dg_comp dg1 (dg_eapp_l dg2)\n  | DgCompEAppR : forall (dg1 dg2:dg_t),\n    dg_comp dg1 dg2 -> dg_comp dg1 (dg_eapp_r dg2)\n  | DgCompERef : forall (dg1 dg2:dg_t),\n    dg_comp dg1 dg2 -> dg_comp dg1 (dg_eref dg2)\n  | DgCompEDeref : forall (dg1 dg2:dg_t),\n    dg_comp dg1 dg2 -> dg_comp dg1 (dg_ederef dg2)\n  | DgCompEAssignL : forall (dg1 dg2:dg_t),\n    dg_comp dg1 dg2 -> dg_comp dg1 (dg_eassign_l dg2)\n  | DgCompEAssignR : forall (dg1 dg2:dg_t),\n    dg_comp dg1 dg2 -> dg_comp dg1 (dg_eassign_r dg2)\n  | DgCompERun : forall (dg1 dg2:dg_t),\n    dg_comp dg1 dg2 -> dg_comp dg1 (dg_erun dg2)\n  | DgCompELift : forall (dg1 dg2:dg_t),\n    dg_comp dg1 dg2 -> dg_comp dg1 (dg_elift dg2).\n\n  (**\n  dg_comp_lst is the list closure of dg_comp. It checks pairwise\n  wether elements of lists are obtained from each other\n  by arbitrary composition of dg_... operations.\n  *)\n  Inductive dg_comp_lst (dg:dg_t) : (list dg_t) -> Prop :=\n  | DgCompLstNil : dg_comp_lst dg nil\n  | DgCompLstCons : forall (dg1:dg_t) (dgs:list dg_t),\n    dg_comp_lst dg1 dgs -> dg_comp (dg_ebox dg1) dg -> dg_comp_lst dg (dg1::dgs).\n\n  (**\n  dg_nth_empty dg n checks whether dg is obtained\n  by applying n occurrences of dg_ebox (modulo dg_comp).\n  *)\n  Inductive dg_nth_empty : dg_t -> nat -> Prop :=\n  | DgNthEmpty0 : dg_nth_empty dg_empty 0\n  | DgNthEmptyS : forall (dg1 dg2:dg_t) (n:nat),\n      dg_nth_empty dg1 n -> dg_comp (dg_ebox dg1) dg2 -> \n      dg_nth_empty dg2 (S n).\n\nEnd DataGatheringPredicates.\n\nModule Type DataGatheringRequirements (R:Replacement) \n  (S:ReplacementCalculus R) (DG:DataGathering R S)\n  (DGP:DataGatheringPredicates R S DG).\n\n  Import DG.\n  Import DGP.\n\n  Parameter dg_eabs_empty : \n    forall (x:S.var), dg_eabs dg_empty x = dg_empty.\n\n  Parameter dg_efix_empty :\n    forall (f x:S.var), dg_efix dg_empty f x = dg_empty.\n\n  Parameter dg_eapp_l_empty : dg_eapp_l dg_empty = dg_empty.\n  Parameter dg_eapp_r_empty : dg_eapp_r dg_empty = dg_empty.\n  Parameter dg_eref_empty : dg_eref dg_empty = dg_empty.\n  Parameter dg_ederef_empty : dg_ederef dg_empty = dg_empty.\n  Parameter dg_eassign_l_empty : dg_eassign_l dg_empty = dg_empty.\n  Parameter dg_eassign_r_empty : dg_eassign_r dg_empty = dg_empty.\n  Parameter dg_erun_empty : dg_erun dg_empty = dg_empty.\n  Parameter dg_elift_empty : dg_elift dg_empty = dg_empty.\n\n  Parameter dg_ebox_empty :\n    forall (dg:dg_t) (n:nat), R.rho (S n) = true ->\n    dg_nth_empty dg n -> dg_ebox dg = dg_empty.\n\nEnd DataGatheringRequirements.\n\nModule DataGatheringProperties (R:Replacement)\n  (S:ReplacementCalculus R) (DG:DataGathering R S) \n  (DGP:DataGatheringPredicates R S DG)\n  (DGR:DataGatheringRequirements R S DG DGP).\n\n  Import DG.\n  Import DGP.\n  Import DGR.\n\n  Definition valid_dgs (n:nat) (dg:dg_t) (dgs:list dg_t) :=\n    n <= length dgs /\\\n    dg_comp_lst dg dgs /\\\n    forall (m:nat), m <= n -> R.rho m = true -> \n    match (n - m) with\n    | 0 => dg = dg_empty\n    | S n => nth n dgs dg_empty = dg_empty\n    end.\n\n  Lemma dg_comp_trans:\n    forall (dg1 dg2 dg3:dg_t),\n    dg_comp dg1 dg2 -> dg_comp dg2 dg3 -> dg_comp dg1 dg3.\n  Proof.\n    intros ; generalize dependent dg1.\n    induction H0 ; intros ; auto ;\n    try(constructor ; auto ; fail).\n  Qed.\n\n  Lemma dg_comp_lst_trans:\n    forall (dg1 dg2:dg_t) (dgs:list dg_t),\n    dg_comp dg1 dg2 -> dg_comp_lst dg1 dgs -> dg_comp_lst dg2 dgs.\n  Proof.\n    intros ; generalize dependent dgs.\n    inverts H ; intros ; auto ;\n    try(destruct dgs ; inverts H1 ; constructor ; auto ;\n    apply dg_comp_trans with (dg2:=dg1) ; auto ;\n    constructor ; auto).\n  Qed.\n\n  Lemma dg_comp_empty_ind:\n    forall (dg1 dg2:dg_t), dg_comp dg1 dg2 -> dg1 = dg_empty -> dg2 = dg_empty.\n  Proof.\n    assert(dg_empty = dg_empty) as Eq1.\n    reflexivity.\n\n    intros ; induction H ; subst ; auto ~ ;\n    specialize (IHdg_comp Eq1) ; subst.\n    apply dg_eabs_empty.\n    apply dg_efix_empty.\n    apply dg_eapp_l_empty.\n    apply dg_eapp_r_empty.\n    apply dg_eref_empty.\n    apply dg_ederef_empty.\n    apply dg_eassign_l_empty.\n    apply dg_eassign_r_empty.\n    apply dg_erun_empty.\n    apply dg_elift_empty.\n  Qed.\n\n  Lemma dg_comp_empty:\n    forall (dg:dg_t), dg_comp dg_empty dg -> dg = dg_empty.\n  Proof.\n     intros ; apply dg_comp_empty_ind with (dg1:=dg_empty) ; auto ~.\n  Qed.\n\n  Lemma valid_dgs_trans:\n    forall (n:nat) (dg1 dg2:dg_t) (dgs:list dg_t),\n    dg_comp dg1 dg2 -> valid_dgs n dg1 dgs -> valid_dgs n dg2 dgs.\n  Proof.\n    unfold valid_dgs ; intros ; repeat(split) ; auto ~ ; intros.\n    destruct H0 ; auto ~.\n    destruct H0 ; destruct H1.\n    apply dg_comp_lst_trans with (dg1:=dg1) ; auto ~.\n    destruct H0 ; destruct H3.\n    specialize (H4 m H1 H2).\n    destruct (n-m) ; subst ; auto ~.\n    apply dg_comp_empty ; auto ~.\n  Qed.\n\n  Lemma valid_dgs_eunbox:\n    forall (n:nat) (dg1 dg2:dg_t) (dgs:list dg_t),\n    valid_dgs (S n) dg1 (dg2::dgs) -> valid_dgs n dg2 dgs.\n  Proof.\n    unfold valid_dgs ; intros ; repeat(split) ; auto ~ ; intros.\n    destruct H ; simpl in *|-* ; omega.\n    destruct H ; destruct H0 ; inverts H0 ; auto ~.\n    destruct H ; destruct H2.\n    assert(m <= S n) as Eq1.\n    omega.\n    specialize (H3 m Eq1 H1).\n    rewrite <- minus_Sn_m in H3 ; auto ~.\n    destruct (n - m) ; auto ~.\n  Qed.\n\n  Lemma dg_nth_empty_lst:\n    forall (n:nat) (dg:dg_t) (dgs:list dg_t),\n    length dgs >= n ->\n    dg_comp_lst dg dgs ->\n    nth n (dg::dgs) dg_empty = dg_empty -> \n    dg_nth_empty dg n.\n  Proof.\n    induction n ; simpl ; intros.\n    subst ; constructor.\n    destruct dgs.\n    exfalso ; simpl in *|-* ; omega.\n    simpl in H ; apply le_S_n in H.\n    inverts H0.\n    specialize (IHn d dgs H H4).\n    apply DgNthEmptyS with (dg1:=d) ; auto ~.\n  Qed.\n\n  Lemma valid_dgs_ebox:\n    forall (n:nat) (dg:dg_t) (dgs:list dg_t),\n    valid_dgs n dg dgs -> valid_dgs (S n) (dg_ebox dg) (dg :: dgs).\n  Proof.\n    unfold valid_dgs ; intros ; repeat(split) ; auto ~ ; intros.\n    simpl ; omega.\n    destruct H ; destruct H0 ; constructor ; auto ~ ; repeat(constructor).\n    case_beq_nat m (S n).\n    rewrite minus_diag.\n    apply dg_ebox_empty with (n:=n) ; auto ~.\n    destruct H ; destruct H2.\n    assert(0 <= n) as Eq1.\n    omega.\n    specialize (H3 0 Eq1 R.rho_O).\n    apply dg_nth_empty_lst with (dgs:=dgs) ; auto ~.\n    rewrite <- minus_n_O in H3 ; destruct n ; auto ~.\n    assert(m <= n) as Eq1.\n    omega.\n    rewrite <- minus_Sn_m ; auto ~.\n    destruct H ; destruct H2 ; specialize (H3 m Eq1 H1).\n    destruct (n-m) ; auto ~.\n  Qed.\n\n  Lemma dg_valid_dgs_nil: valid_dgs 0 dg_empty nil.\n  Proof.\n    repeat(split) ; intros ; auto ~.\n    constructor.\n  Qed.\n\n  Lemma dg_valid_dgs_empty: \n    forall (dg:dg_t) (dgs:list dg_t),\n    valid_dgs 0 dg dgs -> dg = dg_empty.\n  Proof.\n    intros ; destruct H.\n    destruct H0.\n    specialize (H1 0) ; simpl in *|-*.\n    apply H1 ; auto.\n    apply R.rho_O.\n  Qed.\n  \nEnd DataGatheringProperties.\n", "meta": {"author": "GitoriousLispBackup", "repo": "monadic-translation", "sha": "662661b323f61250ba91c364fdd0b76dd663e57c", "save_path": "github-repos/coq/GitoriousLispBackup-monadic-translation", "path": "github-repos/coq/GitoriousLispBackup-monadic-translation/monadic-translation-662661b323f61250ba91c364fdd0b76dd663e57c/Calculus/MultiStaged/DataGathering.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23371083587415173}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\n\nFrom Ltac2 Require Import Ltac2.\n\nRequire Import Equations.Prop.Equations.\n\nFrom Coq Require Import String Ensembles Setoid.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Logic.Classical_Prop.\nFrom Coq.Logic Require Import FunctionalExtensionality Eqdep_dec.\nFrom Coq.Classes Require Import Morphisms_Prop.\nFrom Coq.Unicode Require Import Utf8.\nFrom Coq.micromega Require Import Lia.\n\nFrom stdpp Require Import base fin_sets sets propset proof_irrel option list coGset finite infinite gmap.\n\nFrom MatchingLogic Require Import Logic ProofMode.MLPM.\nFrom MatchingLogic.Theories Require Import Definedness_Syntax.\nFrom MatchingLogic.Utils Require Import stdpp_ext.\nImport extralibrary.\n\nImport MatchingLogic.Logic.Notations.\nImport MatchingLogic.DerivedOperators_Syntax.Notations.\nImport MatchingLogic.Syntax.BoundVarSugar.\n\nSet Default Proof Mode \"Classic\".\n\nClose Scope equations_scope. (* Because of [!] *)\n\nImport Notations.\n\nSection ProofSystemTheorems.\n\nContext\n  {Σ : Signature}\n  {syntax : Syntax}\n.\n\n\nDefinition defFP : coWfpSet := {[(exist (λ p, well_formed p = true) (patt_sym (Definedness_Syntax.inj definedness)) erefl)]}. \n\nLemma phi_impl_total_phi_meta Γ φ i:\n  well_formed φ ->\n  ProofInfoLe BasicReasoning i -> \n  Γ ⊢i φ using i ->\n  Γ ⊢i ⌊ φ ⌋ using i.\nProof.\n  intros wfφ pile Hφ.\n  pose proof (ANNA := A_implies_not_not_A_ctx Γ (φ) AC_patt_defined).\n  apply ANNA.\n  { simpl. try_solve_pile. }\n  { apply wfφ. }\n  exact Hφ.\nDefined.\n\nLemma patt_iff_implies_equal :\n  forall (φ1 φ2 : Pattern) Γ i,\n    well_formed φ1 ->\n    well_formed φ2 ->\n    ProofInfoLe BasicReasoning i ->\n    Γ ⊢i (φ1 <---> φ2) using i ->\n    Γ ⊢i φ1 =ml φ2 using i .\nProof.\n  intros φ1 φ2 Γ i WF1 WF2 pile H.\n  pose proof (ANNA := A_implies_not_not_A_ctx Γ (φ1 <---> φ2) AC_patt_defined).\n  apply ANNA.\n  { eapply pile_trans;[|apply pile]. try_solve_pile. }\n  { wf_auto2. }\n  { exact H. }\nDefined.\n\nLemma patt_equal_refl :\n  forall φ Γ,\n  well_formed φ ->\n  Γ ⊢i φ =ml φ\n  using BasicReasoning.\nProof.\n  intros φ Γ WF. pose proof (IFF := pf_iff_equiv_refl Γ φ WF).\n  eapply useBasicReasoning in IFF.\n  apply patt_iff_implies_equal in IFF.\n  { apply IFF. }\n  { exact WF. }\n  { exact WF. }\n  { apply pile_refl. }\nQed.\n\nLemma use_defined_axiom Γ:\n  theory ⊆ Γ ->\n  Γ ⊢i patt_defined p_x\n  using BasicReasoning.\nProof.\n  intros HΓ.\n  apply BasicProofSystemLemmas.hypothesis; auto. unfold theory,theory_of_NamedAxioms in HΓ. simpl in HΓ.\n  eapply elem_of_weaken.\n  2: { apply HΓ. }\n  unfold axiom.\n  apply elem_of_PropSet.\n  exists AxDefinedness.\n  reflexivity.\nDefined.\n\nDefinition BasicReasoningWithDefinedness := (ExGen := {[ev_x]}, SVSubst := ∅, KT := false, AKT := false).\n\nLemma defined_evar Γ x:\n  theory ⊆ Γ ->\n  Γ ⊢i ⌈ patt_free_evar x ⌉\n  using  (ExGen := {[ev_x]}, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ.\n  assert(S1: Γ ⊢i patt_defined p_x using BasicReasoningWithDefinedness).\n  {\n    useBasicReasoning.\n    apply use_defined_axiom.\n    apply HΓ.\n  }\n\n  apply universal_generalization with (x := ev_x) in S1 as S1'.\n  3: { wf_auto2. }\n  2: { try_solve_pile. }\n  eapply MP.\n  exact S1'.\n  simpl in S1'. case_match. 2: congruence.\n  toMLGoal. case_match. 2: congruence. wf_auto2.\n  mlIntro \"H\".\n  mlSpecialize \"H\" with x.\n  mlSimpl. simpl. case_match. 2: congruence.\n  mlAssumption.\nDefined.\n  \nLemma in_context_impl_defined Γ AC φ x:\n  theory ⊆ Γ ->\n  x ∉ (free_evars φ ∪ AC_free_evars AC) ->\n  well_formed φ ->\n  Γ ⊢i (subst_ctx AC φ) ---> ⌈ φ ⌉\n  using  (ExGen := {[ev_x]} ∪ {[x]}, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ Hx Hwfφ.\n  assert(S1: Γ ⊢i patt_defined p_x using BasicReasoning).\n  {\n    apply use_defined_axiom.\n    apply HΓ.\n  }\n\n  pose proof (S1' := S1).\n  apply useBasicReasoning with (i := (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false)) in S1'.\n  apply universal_generalization with (x := ev_x) in S1'.\n  3: { wf_auto2. }\n  2: { try_solve_pile. }\n\n  assert (Hx1': evar_is_fresh_in x φ).\n  {\n    unfold evar_is_fresh_in. set_solver.\n  }\n\n  assert (Hx'2: x ∉ AC_free_evars AC).\n  { \n    unfold evar_is_fresh_in. set_solver.\n  }\n\n  remember ( (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false)) as i.\n  assert (S1'' : Γ ⊢i ⌈ patt_free_evar x ⌉ using i).\n  {\n    gapply defined_evar. try_solve_pile. assumption.\n  }\n  \n  assert(S2: Γ ⊢i ⌈ patt_free_evar x ⌉ or ⌈ φ ⌉ using i).\n  {\n    toMLGoal.\n    { wf_auto2. }\n    mlLeft.\n    fromMLGoal.\n    apply S1''.\n  }\n\n  assert(S3: Γ ⊢i ⌈ patt_free_evar x or φ ⌉ using i).\n  {\n    pose proof (Htmp := (prf_prop_or_iff Γ AC_patt_defined) (patt_free_evar x) φ ltac:(auto) ltac:(auto)).\n    simpl in Htmp.\n    apply pf_conj_elim_r_meta in Htmp.\n    2-3: wf_auto2.\n    apply useGenericReasoning with (i := i) in Htmp.\n    2: {\n      subst i. try_solve_pile.\n    }\n    subst i.\n    eapply MP.\n    1: apply S2.\n    1: {\n      apply Htmp.\n    }\n  }\n\n  assert(S4: Γ ⊢i ⌈ ((patt_free_evar x) and (! φ)) or φ ⌉ using i).\n  {\n    assert(Htmp1: Γ ⊢i (patt_free_evar x or φ) ---> (patt_free_evar x and ! φ or φ) using i).\n    {\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro \"H0\".\n      mlClassic (φ) as \"Hφ\" \"Hnotφ\".\n      { wf_auto2. }\n      - mlRight. mlExact \"Hφ\".\n      - mlLeft. mlIntro \"H1\".\n        mlDestructOr \"H0\" as \"H01\" \"H02\".\n        + mlDestructOr \"H1\" as \"H10\" \"H11\".\n          * mlApply \"H10\". mlExact \"H01\".\n          * mlApply \"H11\". mlExact \"Hnotφ\".\n        + mlApply \"Hnotφ\".\n          mlExact \"H02\".\n    }\n\n    assert(Htmp2: Γ ⊢i (⌈ patt_free_evar x or φ ⌉) ---> (⌈ patt_free_evar x and ! φ or φ ⌉) using i).\n    {\n      unshelve (eapply Framing_right).\n      { wf_auto2. }\n      {\n        try_solve_pile.\n      }\n      apply Htmp1.\n    }\n\n    eapply MP.\n    2: apply Htmp2.\n    1: apply S3.\n  }\n\n  assert(S5: Γ ⊢i ⌈ (patt_free_evar x and (! φ)) ⌉ or ⌈ φ ⌉ using i).\n  {\n    pose proof (Htmp := (prf_prop_or_iff Γ AC_patt_defined) (patt_free_evar x and ! φ) φ ltac:(auto) ltac:(auto)).\n    simpl in Htmp.\n    apply pf_conj_elim_l_meta in Htmp;[|wf_auto2|wf_auto2].\n    apply useGenericReasoning with (i := i) in Htmp.\n    2: {\n      subst i. try_solve_pile.\n    }\n    subst i.\n    eapply MP.\n    2: {\n      apply Htmp.\n    }\n    1: apply S4.\n  }\n\n  assert(S6: Γ ⊢i subst_ctx AC (patt_free_evar x and φ) ---> ! ⌈ patt_free_evar x and ! φ ⌉ using i).\n  {\n    pose proof (Htmp := Singleton_ctx Γ AC AC_patt_defined φ x).\n    simpl in Htmp.\n    unfold patt_and in Htmp at 1.\n    apply not_not_elim_meta in Htmp.\n    3: { wf_auto2. }\n    2: { wf_auto2. }\n    replace (patt_sym (Definedness_Syntax.inj definedness) $ (patt_free_evar x and ! φ))%ml\n      with (patt_defined (patt_free_evar x and ! φ)) in Htmp by reflexivity.\n    \n    toMLGoal.\n    { wf_auto2. }\n    mlIntro.\n    remember (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false) as gpi.\n    rewrite Heqi.\n    mlAdd (useBasicReasoning gpi Htmp).\n    mlApply \"1\". mlIntro. mlApply \"2\".\n    mlExactn 1.\n  }\n\n  pose proof (S7 := S5). unfold patt_or in S7.\n\n  assert(S8: Γ ⊢i subst_ctx AC (patt_free_evar x and φ) ---> ⌈ φ ⌉ using i).\n  {\n    eapply syllogism_meta.\n    5: apply S7.\n    4: apply S6.\n    1-3: wf_auto2.\n  }\n  assert (S9: Γ ⊢i all, (subst_ctx AC (patt_bound_evar 0 and φ) ---> ⌈ φ ⌉) using i).\n  {\n    eapply universal_generalization with (x := x) in S8.\n    3: { wf_auto2. }\n    2: { try_solve_pile. }\n    simpl in S8.\n\n    rewrite evar_quantify_subst_ctx in S8;[assumption|].\n\n    simpl in S8.\n    case_match; try contradiction.\n    rewrite evar_quantify_fresh in S8; [assumption|].\n    apply S8.\n  }\n\n  assert(S10: Γ ⊢i (ex, subst_ctx AC (b0 and φ)) ---> ⌈ φ ⌉ using i).\n  {\n    unfold patt_forall in S9.\n    unfold patt_not in S9 at 1.\n\n    assert (Heq: (subst_ctx AC (patt_free_evar x and φ))^{{evar: x ↦ 0}} = subst_ctx AC (b0 and φ)).\n    {\n      rewrite evar_quantify_subst_ctx;[assumption|].\n      f_equal.\n      simpl.\n      case_match; [|congruence].\n      rewrite evar_quantify_fresh; [assumption|].\n      reflexivity.\n    }\n    rewrite <- Heq.\n    apply BasicProofSystemLemmas.Ex_gen.\n    2: {simpl. unfold evar_is_fresh_in in Hx1'. clear -Hx1'. set_solver. }\n    1: { try_solve_pile. }\n    assumption.\n  }\n\n  assert (S11: Γ ⊢i φ ---> ((ex, patt_bound_evar 0) and φ) using i).\n  {\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro.\n    mlAdd (useBasicReasoning i (conj_intro Γ (ex, b0) φ ltac:(auto) ltac:(auto))).\n\n    mlAssert ((φ ---> (ex , b0) and φ)).\n    { wf_auto2. }\n    {  mlApply \"1\".\n        subst i.\n       (* TODO mlAdd should do the cast automatically *)\n       mlAdd (useBasicReasoning (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false) (Existence Γ)).\n       mlExactn 0.\n    }\n    mlApply \"2\". mlExactn 1.\n  }\n\n  assert (well_formed (ex , (b0 and φ))).\n  {\n    unfold well_formed,well_formed_closed in *.\n    destruct_and!.\n    simpl; split_and!; auto.\n    eapply well_formed_closed_ex_aux_ind. 2: eassumption. lia.\n  }\n\n  assert (S12: Γ ⊢i φ ---> ex, (b0 and φ) using i).\n  {\n\n    assert(well_formed (ex , ((patt_free_evar x)^{{evar: x ↦ 0}} and φ))).\n    {\n      unfold well_formed,well_formed_closed in *. simpl in *.\n      destruct_and!. split_and!; auto.\n      all: repeat case_match; auto.\n    }\n\n    assert(Htmp: Γ ⊢i ((ex, b0) and φ ---> (ex, (b0 and φ))) using i).\n    {\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro.\n      mlDestructAnd \"0\".\n      fromMLGoal.\n      replace b0 with ((patt_free_evar x)^{{evar: x ↦ 0}}).\n      2: { simpl. case_match;[reflexivity|congruence]. }\n      apply BasicProofSystemLemmas.Ex_gen.\n      2: { simpl. case_match;[|congruence]. simpl.\n           unfold evar_is_fresh_in in Hx1'. clear -Hx1'. set_solver.\n      }\n      1: {\n        try_solve_pile.\n      }\n      toMLGoal.\n      { wf_auto2. }\n      do 2 mlIntro.\n      mlAssert ((patt_free_evar x and φ)) using first 2.\n      { wf_auto2. }\n      { unfold patt_and. unfold patt_not at 1. mlIntro.\n        mlDestructOr \"2\".\n        - mlApply \"3\". mlExactn 0.\n        - mlApply \"4\". mlExactn 1.\n      }\n      mlClear \"1\". mlClear \"0\".\n      fromMLGoal.\n      case_match;[|congruence].\n\n      replace (patt_free_evar x and φ)\n        with (instantiate (ex, (patt_bound_evar 0 and φ)) (patt_free_evar x)).\n      2: {\n        simpl. rewrite bevar_subst_not_occur.\n        { unfold well_formed, well_formed_closed in *.\n          destruct_and!. auto.\n        }\n        reflexivity.\n      }\n      subst i.\n      useBasicReasoning.\n      apply BasicProofSystemLemmas.Ex_quan.\n      { wf_auto2. }\n    }\n    eapply syllogism_meta.\n    5: { apply Htmp. }\n    4: assumption.\n    1-3: wf_auto2.\n  }\n\n  assert(S13: Γ ⊢i (subst_ctx AC φ) ---> (subst_ctx AC (ex, (b0 and φ))) using i).\n  {\n    apply Framing.\n    {\n      try_solve_pile.\n    }\n    apply S12.\n  }\n\n  assert(S14: Γ ⊢i (subst_ctx AC (ex, (b0 and φ))) ---> (⌈ φ ⌉) using i).\n  {\n    pose proof (Htmp := prf_prop_ex_iff Γ AC (b0 and φ) x).\n    feed specialize Htmp.\n    { unfold evar_is_fresh_in in *.\n      rewrite free_evars_subst_ctx. clear -Hx1' Hx'2. simpl. set_solver.\n    }\n    { auto. }\n    unfold exists_quantify in Htmp.\n    rewrite evar_quantify_subst_ctx in Htmp.\n    { assumption. }\n\n    assert (well_formed (ex , subst_ctx AC (b0 and φ))).\n    {\n      unfold well_formed,well_formed_closed in *. destruct_and!.\n      split_and!; simpl; auto.\n      3: { apply wcex_sctx.\n           simpl. split_and!; auto.\n           eapply well_formed_closed_ex_aux_ind. 2: eassumption. lia.\n      }\n      2: {\n        apply wcmu_sctx.\n        simpl. split_and!; auto.\n      }\n      1: {\n        apply wp_sctx. simpl. split_and!; auto.\n      }\n    }\n\n    rewrite -> evar_quantify_evar_open in Htmp.\n    2: { simpl. unfold evar_is_fresh_in in Hx1'. clear -Hx1'. set_solver. }\n    apply pf_iff_proj1 in Htmp; auto.\n    {\n      eapply syllogism_meta.\n      5: { apply S10. }\n      4: { subst i. eapply useGenericReasoning. 2: apply Htmp.\n        try_solve_pile.\n      }\n      1-3: wf_auto2.\n    }\n    unfold patt_and,patt_or,patt_not.\n    simpl. split_and!; auto.\n    apply well_formed_closed_ex_aux_ind with (ind_evar1 := 0); auto.\n    wf_auto2.\n  }\n\n  eapply syllogism_meta.\n  5: apply S14.\n  4: assumption.\n  1-3: wf_auto2.\nDefined.\n\nLemma elements_union_empty φ:\n  elements (free_evars φ ∪ ∅) = elements (free_evars φ).\nProof.\n  apply f_equal.\n  set_solver.\nQed.\n\nLemma phi_impl_defined_phi Γ φ x:\n  theory ⊆ Γ ->\n  x ∉ free_evars φ ->\n  well_formed φ ->\n  Γ ⊢i φ ---> ⌈ φ ⌉\n  using \n                     (ExGen := {[ev_x;x]},\n                      SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ Hx wfφ.\n  eapply cast_proof'.\n  {\n    replace φ with (subst_ctx box φ) at 1 by reflexivity.\n    reflexivity.\n  }\n  eapply useGenericReasoning.\n  2: {\n    apply in_context_impl_defined; try assumption.\n    cbn. instantiate (1:=x). set_solver.\n  }\n  {\n    simpl. replace (free_evars φ ∪ ∅) with (free_evars φ) by set_solver.\n    try_solve_pile.\n  }\nDefined.\n\nLemma total_phi_impl_phi Γ φ x:\n  theory ⊆ Γ ->\n  x ∉ free_evars φ -> \n  well_formed φ ->\n  Γ ⊢i ⌊ φ ⌋ ---> φ\n  using \n  (ExGen := {[ev_x; x]},\n   SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ Hx wfφ.\n  unfold patt_total.\n  pose proof (Htmp := phi_impl_defined_phi Γ (! φ) x HΓ ltac:(set_solver) ltac:(wf_auto2)).\n  apply A_impl_not_not_B_meta.\n  1,2: wf_auto2.\n  apply modus_tollens.\n  simpl in Htmp. assumption.\nDefined.\n\nLemma total_phi_impl_phi_meta Γ φ i x:\n  theory ⊆ Γ ->\n  x ∉ free_evars φ ->\n  well_formed φ ->\n  ProofInfoLe\n  (ExGen := {[ev_x; x]},\n   SVSubst := ∅, KT := false, AKT := false) i ->\n  Γ ⊢i ⌊ φ ⌋ using i ->\n  Γ ⊢i φ using i.\nProof.\n  intros HΓ Hx wfφ pile H.\n  eapply MP.\n  1: exact H.\n  eapply useGenericReasoning.\n  2: apply total_phi_impl_phi.\n  {\n    eapply pile_trans. 2: apply pile.\n    try_solve_pile.\n  }\n  all: assumption.\nDefined.\n\n  Lemma framing_left_under_tot_impl Γ ψ phi1 phi2 psi:\n    well_formed ψ = true ->\n    well_formed phi1 = true ->\n    well_formed phi2 = true ->\n    well_formed psi = true ->\n    theory ⊆ Γ ->\n    Γ ⊢ ⌊ ψ ⌋ ---> phi1 ---> phi2 ->\n    Γ ⊢ ⌊ ψ ⌋ ---> (phi1 $ psi) ---> (phi2 $ psi)\n  .\n  Proof.\n    intros Hwfψ Hwfphi1 Hwfphi2 Hwfpsi HΓ H.\n    assert (S2: Γ ⊢ phi1 ---> (phi2 or ⌈ ! ψ ⌉)).\n    { toMLGoal.\n      { wf_auto2. }\n      mlAdd H as \"H\". mlIntro \"Hphi1\".\n      mlClassic (⌈ ! ψ ⌉) as \"Hcl1\" \"Hcl2\".\n      { wf_auto2. }\n      - mlRight. mlExact \"Hcl1\".\n      - mlLeft.\n        mlApply \"H\".\n        mlSplitAnd.\n        { mlExact \"Hcl2\". }\n        { mlExact \"Hphi1\". }\n    }\n\n    assert (S3: Γ ⊢ (⌈ ! ψ ⌉ $ psi) ---> ⌈ ! ψ ⌉).\n    {\n      replace (⌈ ! ψ ⌉ $ psi)\n        with (subst_ctx (ctx_app_l AC_patt_defined psi ltac:(assumption)) (! ψ))\n        by reflexivity.\n      remember (evar_fresh (elements (free_evars ψ ∪ free_evars psi))) as x.\n      gapply (in_context_impl_defined _ _ _ x).\n      4: { wf_auto2. }\n      2: { exact HΓ. }\n      1: { apply pile_any. }\n      subst x.\n      cbn.\n      eapply not_elem_of_larger_impl_not_elem_of.\n      2: { apply set_evar_fresh_is_fresh'. }\n      clear.\n      set_solver.\n    }\n\n    assert (S4: Γ ⊢ (phi1 $ psi) ---> ((phi2 or ⌈ ! ψ ⌉) $ psi)).\n    { \n      unshelve (eapply Framing_left).\n      { wf_auto2. }\n      { apply pile_any. }\n      { exact S2. }\n    }\n\n    assert (S5: Γ ⊢ (phi1 $ psi) ---> ((phi2 $ psi) or (⌈ ! ψ ⌉ $ psi))).\n    {\n      pose proof (Htmp := prf_prop_or_iff Γ (ctx_app_l box psi ltac:(assumption)) phi2 (⌈! ψ ⌉)).\n      feed specialize Htmp.\n      { wf_auto2. }\n      { wf_auto2. }\n      simpl in Htmp.\n      apply pf_iff_proj1 in Htmp.\n      3: { wf_auto2. }\n      2: { wf_auto2. }\n      eapply syllogism_meta.\n      5: {\n        gapply Htmp.\n        apply pile_any.\n      }\n      4: { exact S4. }\n      all: wf_auto2.\n    }\n\n    assert (S6: Γ ⊢ ((phi2 $ psi) or (⌈ ! ψ ⌉ $ psi)) ---> ((phi2 $ psi) or (⌈ ! ψ ⌉))).\n    {\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro \"H\". mlAdd S3 as \"S3\".\n      mlClassic (phi2 $ psi) as \"Hc1\" \"Hc2\".\n      { wf_auto2. }\n      - mlLeft. mlExact \"Hc1\".\n      - mlRight. mlApply \"S3\". mlApply \"H\". mlExact \"Hc2\".\n    }\n\n    assert (S7: Γ ⊢ (phi1 $ psi) ---> ((phi2 $ psi)  or ⌈ ! ψ ⌉)).\n    {\n      toMLGoal.\n      { wf_auto2. }\n      mlAdd S5 as \"S5\".\n      mlAdd S6 as \"S6\".\n      mlIntro \"H\".\n      mlAssert (\"Ha\" : ((phi2 $ psi) or (⌈ ! ψ ⌉ $ psi))).\n      { wf_auto2. }\n      { mlApply \"S5\". mlExact \"H\". }\n      mlDestructOr \"Ha\" as \"Ha1\" \"Ha2\".\n      - mlLeft. mlExact \"Ha1\".\n      - mlApply \"S6\". mlRight. mlExact \"Ha2\".\n    }\n\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro \"H1\".\n    mlIntro \"H2\".\n    mlAdd S7 as \"S7\".\n    mlAssert (\"Ha\" : (phi2 $ psi or ⌈ ! ψ ⌉)).\n    { wf_auto2. }\n    { mlApply \"S7\". mlExact \"H2\". }\n    mlDestructOr \"Ha\" as \"Ha1\" \"Ha2\".\n    { mlExact \"Ha1\". }\n    { mlAssert (\"Ha'\" : (phi2 $ psi or ⌈ ! ψ ⌉)).\n      { wf_auto2. }\n      { mlApply \"S7\". mlExact \"H2\". }\n      mlClassic (phi2 $ psi) as \"Hc1\" \"Hc2\".\n      { wf_auto2. }\n      { mlExact \"Hc1\". }\n      {\n        mlExFalso.\n        mlApply \"H1\".\n        mlExact \"Ha2\".\n      }\n    }\n  Defined.\n\n  Lemma framing_right_under_tot_impl Γ ψ phi1 phi2 psi:\n    well_formed ψ = true ->\n    well_formed phi1 = true ->\n    well_formed phi2 = true ->\n    well_formed psi = true ->\n    theory ⊆ Γ ->\n    Γ ⊢ ⌊ ψ ⌋ ---> phi1 ---> phi2 ->\n    Γ ⊢ ⌊ ψ ⌋ ---> (psi $ phi1) ---> (psi $ phi2)\n  .\n  Proof.\n    intros Hwfψ Hwfphi1 Hwfphi2 Hwfpsi HΓ H.\n    assert (S2: Γ ⊢ phi1 ---> (phi2 or ⌈ ! ψ ⌉)).\n    { toMLGoal.\n      { wf_auto2. }\n      mlAdd H as \"H\". mlIntro \"Hphi1\".\n      mlClassic (⌈ ! ψ ⌉) as \"Hc1\" \"Hc2\".\n      { wf_auto2. }\n      - mlRight. mlExact \"Hc1\".\n      - mlLeft.\n        mlApply \"H\".\n        mlSplitAnd.\n        { mlExact \"Hc2\". }\n        { mlExact \"Hphi1\". }\n    }\n\n    assert (S3: Γ ⊢ (psi $ ⌈ ! ψ ⌉) ---> ⌈ ! ψ ⌉).\n    {\n      replace (psi $ ⌈ ! ψ ⌉)\n      with (subst_ctx (ctx_app_r psi AC_patt_defined ltac:(assumption)) (! ψ))\n        by reflexivity.\n      \n      remember (evar_fresh (elements (free_evars ψ ∪ free_evars psi))) as x.\n      gapply (in_context_impl_defined _ _ _ x).\n      4: { wf_auto2. }\n      2: { exact HΓ. }\n      1: { apply pile_any. }\n      subst x.\n      cbn.\n      eapply not_elem_of_larger_impl_not_elem_of.\n      2: { apply set_evar_fresh_is_fresh'. }\n      clear.\n      set_solver.\n    }\n\n    assert (S4: Γ ⊢ (psi $ phi1) ---> (psi $ (phi2 or ⌈ ! ψ ⌉))).\n    { \n      (* TODO: have a variant of apply which automatically solves all wf constraints.\n         Like: unshelve (eapply H); try_wfauto\n      *)\n      unshelve (eapply Framing_right).\n      { wf_auto2. }\n      2: exact S2.\n      apply pile_any.\n    }\n\n    assert (S5: Γ ⊢ (psi $ phi1) ---> ((psi $ phi2) or (psi $ ⌈ ! ψ ⌉))).\n    {\n      pose proof (Htmp := prf_prop_or_iff Γ (ctx_app_r psi box ltac:(assumption)) phi2 (⌈! ψ ⌉)).\n      feed specialize Htmp.\n      { wf_auto2. }\n      { wf_auto2. }\n      simpl in Htmp.\n      apply pf_iff_proj1 in Htmp.\n      2,3: wf_auto2.\n      eapply syllogism_meta.\n      5: gapply Htmp; apply pile_any.\n      1-3: wf_auto2.\n      exact S4.\n    }\n\n    assert (S6: Γ ⊢ ((psi $ phi2) or (psi $ ⌈ ! ψ ⌉)) ---> ((psi $ phi2) or (⌈ ! ψ ⌉))).\n    {\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro \"H1\". mlAdd S3 as \"S3\".\n      mlClassic (psi $ phi2) as \"Hc1\" \"Hc2\".\n      { wf_auto2. }\n      - mlLeft. mlExact \"Hc1\".\n      - mlRight. mlApply \"S3\". mlApply \"H1\". mlExact \"Hc2\".\n    }\n\n    assert (S7: Γ ⊢ (psi $ phi1) ---> ((psi $ phi2)  or ⌈ ! ψ ⌉)).\n    {\n      toMLGoal.\n      { wf_auto2. }\n      mlAdd S5 as \"S5\". mlAdd S6 as \"S6\". mlIntro \"H\".\n      (* TODO: a tactic mlFeedImpl *)\n      mlAssert (\"Ha\" : ((psi $ phi2) or (psi $ ⌈ ! ψ ⌉))).\n      { wf_auto2. }\n      { mlApply \"S5\". mlExact \"H\". }\n      mlDestructOr \"Ha\" as \"Ha1\" \"Ha2\".\n      - mlLeft. mlExact \"Ha1\".\n      - mlApply \"S6\". mlRight. mlExact \"Ha2\".\n    }\n\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro \"H1\".\n    mlIntro \"H2\".\n    mlAdd S7 as \"S7\".\n    mlAssert (\"Ha\" : (psi $ phi2 or ⌈ ! ψ ⌉)).\n    { wf_auto2. }\n    { mlApply \"S7\". mlExact \"H2\". }\n    mlDestructOr \"Ha\" as \"Ha1\" \"Ha2\".\n    { mlExact \"Ha1\". }\n    + mlAssert (\"Ha'\" : (psi $ phi2 or ⌈ ! ψ ⌉)).\n      { wf_auto2. }\n      { mlApply \"S7\". mlExact \"H2\". }\n      mlClassic (psi $ phi2) as \"Hc1\" \"Hc2\".\n      { wf_auto2. }\n      { mlExact \"Hc1\". }\n      {\n        mlExFalso.\n        mlApply \"H1\".\n        mlExact \"Ha2\".\n      }\n  Defined.\n\n  Theorem deduction_theorem_noKT Γ φ ψ\n    (gpi : ProofInfo)\n    (pf : Γ ∪ {[ ψ ]} ⊢i φ using  gpi) :\n    well_formed φ ->\n    well_formed ψ ->\n    theory ⊆ Γ ->\n    (* x ∈ pi_generalized_evars gpi -> *)\n    pi_generalized_evars gpi ## (gset_to_coGset (free_evars ψ)) ->\n    pi_substituted_svars gpi ## (gset_to_coGset (free_svars ψ)) ->\n    pi_uses_kt gpi = false ->\n    Γ ⊢i ⌊ ψ ⌋ ---> φ\n    using AnyReasoning.\n    (* (ExGen :=\n      (\n        {[ev_x; x]}\n        ∪ pi_generalized_evars gpi\n        ∪ gset_to_coGset (free_evars ψ)\n      ),\n     SVSubst := (pi_substituted_svars gpi ∪ (gset_to_coGset (free_svars ψ))),\n     KT := false\n    ). *)\n    (** TODO: for this proof, the free variables in patterns of Framing need to be\n              traced!!!!\n     **)\n  Proof.\n    intros wfφ wfψ HΓ Hgen Hsubst Hkt.\n    destruct pf as [pf Hpf]. simpl.\n    induction pf.\n    - (* hypothesis *)\n      rename axiom into axiom0.\n      (* We could use [apply elem_of_union in e; destruct e], but that would be analyzing Prop\n         when building Set, which is prohibited. *)\n      destruct (decide (axiom0 = ψ)).\n      + subst.\n        eapply useGenericReasoning.\n        2: {\n          apply total_phi_impl_phi; try assumption.\n          instantiate (1 := evar_fresh (elements (free_evars ψ))).\n          apply set_evar_fresh_is_fresh'.\n        }\n        { try_solve_pile. }\n\n      + assert (axiom0 ∈ Γ).\n        { clear -e n. set_solver. }\n        toMLGoal.\n        { wf_auto2. }\n        mlIntro. mlClear \"0\". fromMLGoal.\n        eapply useGenericReasoning.\n        2: apply (BasicProofSystemLemmas.hypothesis Γ axiom0 i H).\n        try_solve_pile.\n    - (* P1 *)\n      toMLGoal.\n      { wf_auto2. }\n      do 3 mlIntro. mlExactn 1.\n    - (* P2 *)\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\". fromMLGoal.\n      useBasicReasoning.\n      apply P2; assumption.\n    - (* P3 *)\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\". fromMLGoal.\n      useBasicReasoning.\n      apply P3; assumption.\n    - (* Modus Ponens *)\n      assert (well_formed phi2).\n      { unfold well_formed, well_formed_closed in *. simpl in *.\n        destruct_and!. split_and!; auto.\n      }\n      assert (well_formed phi1).\n      {\n        clear -pf1. apply proved_impl_wf in pf1. exact pf1.\n      }\n\n      remember_constraint as i'.\n\n      destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n      simpl in Hpf2, Hpf3, Hpf4.\n      feed specialize IHpf1.\n      {\n        constructor; simpl.\n        { set_solver. }\n        { set_solver. }\n        { unfold implb in *.\n          destruct (uses_kt pf1) eqn:Hktpf1;[|reflexivity]. simpl in *.\n          exact Hpf4.\n        }\n        { unfold implb in *.\n          destruct (uses_kt_unreasonably pf1) eqn:Hktpf1;[|reflexivity]. simpl in *.\n          rewrite Hktpf1 in Hpf5. simpl in Hpf5.\n          unfold is_true in Hpf5.\n          rewrite andb_true_iff in Hpf5.\n          destruct Hpf5 as [HH1 HH2].\n          rewrite HH1. simpl.\n          apply kt_unreasonably_implies_somehow.\n          exact Hktpf1.\n        }\n      }\n      { assumption. }\n      feed specialize IHpf2.\n      {\n        constructor; simpl.\n        { set_solver. }\n        { set_solver. }\n        { unfold implb in *.\n          destruct (uses_kt pf2) eqn:Hktpf2;[|reflexivity].\n          rewrite orb_comm in Hpf4. simpl in *.\n          exact Hpf4.\n        }\n        { unfold implb in *.\n          destruct (uses_kt_unreasonably pf2) eqn:Hktpf2;[|reflexivity]. simpl in *.\n          rewrite Hktpf2 in Hpf5. rewrite orb_true_r in Hpf5.\n          unfold is_true in Hpf5.\n          rewrite andb_true_iff in Hpf5.\n          destruct Hpf5 as [HH1 HH2].\n          rewrite HH1. simpl.\n          apply kt_unreasonably_implies_somehow.\n          exact Hktpf2.\n        }\n      }\n      { wf_auto2. }\n\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro.\n      subst i'. mlAdd IHpf2.\n      mlAssert ((phi1 ---> phi2)).\n      { wf_auto2. }\n      { mlApply \"1\". mlExactn 1. }\n      mlApply \"2\". (* TODO: proof infos are transformed? Why? *)\n      mlAdd IHpf1.\n      mlApply \"3\".\n      mlExactn 2.\n    - (* Existential Quantifier *)\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\". fromMLGoal.\n      useBasicReasoning.\n      apply BasicProofSystemLemmas.Ex_quan. wf_auto2.\n    - (* Existential Generalization *)\n      destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n      simpl in Hpf2, Hpf3, Hpf4.\n      (*\n      simpl in HnoExGen.\n      case_match;[congruence|]. *)\n      feed specialize IHpf.\n      {\n        constructor; simpl.\n        { clear -Hpf2. set_solver. }\n        { clear -Hpf3. set_solver. }\n        { apply Hpf4. }\n        { apply Hpf5. }\n      }\n      { clear Hpf5. wf_auto2. }\n\n\n      apply reorder_meta in IHpf.\n      2-4: clear Hpf5; wf_auto2.\n\n      apply BasicProofSystemLemmas.Ex_gen with (x := x) in IHpf.\n      3: { simpl. set_solver. }\n      2: { try_solve_pile. }\n      apply reorder_meta in IHpf.\n      2-4: clear Hpf5; wf_auto2.\n      exact IHpf.\n      \n    - (* Propagation of ⊥, left *)\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\". fromMLGoal.\n      useBasicReasoning.\n      apply Prop_bott_left; assumption.\n    - (* Propagation of ⊥, right *)\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\"; auto. fromMLGoal.\n      useBasicReasoning.\n      apply Prop_bott_right; assumption.\n    - (* Propagation of 'or', left *)\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\"; auto. fromMLGoal.\n      useBasicReasoning.\n      apply Prop_disj_left; assumption.\n    - (* Propagation of 'or', right *)\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\"; auto. fromMLGoal.\n      useBasicReasoning.\n      apply Prop_disj_right; assumption.\n    - (* Propagation of 'exists', left *)\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\"; auto. fromMLGoal.\n      useBasicReasoning.\n      apply Prop_ex_left; assumption.\n    - (* Propagation of 'exists', right *)\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\"; auto. fromMLGoal.\n      useBasicReasoning.\n      apply Prop_ex_right; assumption.\n    - (* Framing left *)\n      assert (well_formed (phi1)).\n      { unfold well_formed,well_formed_closed in *. simpl in *.\n        destruct_and!. split_and!; auto. }\n\n      assert (well_formed (phi2)).\n      { unfold well_formed,well_formed_closed in *. simpl in *.\n        destruct_and!. split_and!; auto. }\n\n      assert (well_formed (psi)).\n      { unfold well_formed,well_formed_closed in *. simpl in *.\n        destruct_and!. split_and!; auto. }\n      \n      assert (well_formed (phi1 ---> phi2)).\n      { unfold well_formed,well_formed_closed in *. simpl in *.\n        destruct_and!. split_and!; auto. }\n      destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n      simpl in Hpf2,Hpf3,Hpf4.\n      feed specialize IHpf.\n      {\n        constructor; simpl.\n        { set_solver. }\n        { set_solver. }\n        { apply Hpf4. }\n        { apply Hpf5. }\n      }\n      { clear Hpf5; wf_auto2. }\n      \n      apply framing_left_under_tot_impl.\n      1-4: wf_auto2.\n      { exact HΓ. }\n      { exact IHpf. }\n\n    - (* Framing right *)\n      assert (well_formed (phi1)).\n      { unfold well_formed,well_formed_closed in *. simpl in *.\n        destruct_and!. split_and!; auto. }\n\n      assert (well_formed (phi2)).\n      { unfold well_formed,well_formed_closed in *. simpl in *.\n        destruct_and!. split_and!; auto. }\n\n      assert (well_formed (psi)).\n      { unfold well_formed,well_formed_closed in *. simpl in *.\n        destruct_and!. split_and!; auto. }\n\n      assert (well_formed (phi1 ---> phi2)).\n      { unfold well_formed,well_formed_closed in *. simpl in *.\n        destruct_and!. split_and!; auto. }\n\n      destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n      simpl in Hpf2,Hpf3,Hpf4,Hpf5.\n      feed specialize IHpf.\n      {\n        constructor; simpl.\n        { set_solver. }\n        { set_solver. }\n        { apply Hpf4. }\n        { apply Hpf5. }\n      }\n      { wf_auto2. }\n\n      apply framing_right_under_tot_impl.\n      1-4: wf_auto2.\n      { exact HΓ. }\n      { exact IHpf. }\n      \n    - (* Set variable substitution *)\n      destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n      simpl in Hpf2, Hpf3, Hpf4.\n      feed specialize IHpf.\n      {\n        constructor; simpl.\n        { exact Hpf2. }\n        { clear -Hpf3. set_solver. }\n        { exact Hpf4. }\n        { exact Hpf5. }\n      }\n      {\n        wf_auto2.\n      }\n      \n      remember_constraint as i'.\n\n      replace (⌊ ψ ⌋ ---> phi^[[svar: X ↦ psi]])\n        with ((⌊ ψ ⌋ ---> phi)^[[svar: X ↦ psi]]).\n      2: {  simpl.\n           rewrite [ψ^[[svar: X ↦ psi]]]free_svar_subst_fresh.\n           {\n            unfold svar_is_fresh_in. set_solver.\n           }\n           reflexivity.\n      }\n      apply Svar_subst.\n      3: {\n        apply IHpf.\n      }\n      {\n        subst i'.\n        try_solve_pile.\n      }\n      { wf_auto2. }\n\n    - (* Prefixpoint *)\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\". fromMLGoal.\n      apply useBasicReasoning.\n      apply Pre_fixp. wf_auto2.\n    - (* Knaster-Tarski *)\n      destruct Hpf as [Hpf2 Hpf3 Hpf4].\n      simpl in Hpf2, Hpf3, Hpf4.\n      clear -Hkt Hpf4.\n      exfalso. congruence.\n    - (* Existence *)\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\". fromMLGoal.\n      apply useBasicReasoning.\n      apply Existence.\n    - (* Singleton *)\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\". fromMLGoal.\n      apply useBasicReasoning.\n      apply Singleton_ctx. wf_auto2.\n  Defined.\n\n  Lemma membership_introduction Γ φ i:\n    ProofInfoLe \n    (ExGen := {[ev_x; fresh_evar φ]},\n     SVSubst := ∅,\n     KT := false,\n     AKT := false\n    ) i ->\n    well_formed φ ->\n    theory ⊆ Γ ->\n    Γ ⊢i φ using i ->\n    Γ ⊢i all, ((patt_bound_evar 0) ∈ml φ)\n    using i.\n  Proof.\n    intros pile wfφ HΓ Hφ.\n\n    remember (fresh_evar φ) as x.\n\n    replace φ with (φ^{{evar: x ↦ 0}}).\n    2: {\n      rewrite evar_quantify_fresh.\n      subst; auto. reflexivity.\n    }\n    \n    assert (S2: Γ ⊢i (φ ---> (patt_free_evar x ---> φ)) using i).\n    {\n      useBasicReasoning.\n      apply P1.\n      { wf_auto2. }\n      { wf_auto2. }\n    }\n\n    assert(S3: Γ ⊢i patt_free_evar x ---> φ using i).\n    {\n      eapply MP. 2: apply S2. apply Hφ.\n    }\n\n    assert(S4: Γ ⊢i patt_free_evar x ---> patt_free_evar x using i).\n    {\n      useBasicReasoning.\n      apply A_impl_A.\n      wf_auto2.\n    }\n\n    assert(S5: Γ ⊢i patt_free_evar x ---> (patt_free_evar x and φ) using i).\n    {\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. unfold patt_and. mlIntro.\n      mlAssert ((! φ)).\n      { wf_auto2. }\n      { mlApply \"1\". mlIntro. mlApply \"2\". mlExactn 0.  }\n      mlApply \"2\".\n      mlAdd Hφ. mlExactn 0.\n    }\n\n    assert(S6: Γ ⊢i ⌈ patt_free_evar x ⌉ ---> ⌈ (patt_free_evar x and φ) ⌉ using i).\n    {\n      unshelve (eapply Framing_right). \n      { try_wfauto2. }\n      { eapply pile_trans. 2: apply pile. try_solve_pile. }\n      apply S5.\n    }\n    \n    assert(S7: Γ ⊢i ⌈ patt_free_evar x ⌉ using i).\n    {\n      eapply useGenericReasoning.\n      2: apply defined_evar; assumption.\n      try_solve_pile.\n    }\n\n    assert(S9: Γ ⊢i (patt_free_evar x) ∈ml φ using i).\n    {\n      eapply MP. 2: apply S6.\n      apply S7.\n    }\n\n    eapply universal_generalization with (x := x) in S9.\n    3: { wf_auto2. }\n    1: { simpl in S9. case_match;[|congruence]. exact S9. }\n    eapply pile_trans. 2: apply pile.\n    try_solve_pile.\n  Defined.\n\n  Lemma membership_implies_implication Γ ϕ x:\n    well_formed ϕ ->\n    Γ ⊢i patt_free_evar x ∈ml ϕ ---> patt_free_evar x ---> ϕ using BasicReasoning.\n  Proof.\n    intro WF.\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlIntro.\n    pose proof (S5 := Singleton_ctx Γ AC_patt_defined box ϕ x ltac:(wf_auto2)).\n    mlAdd S5.\n    simpl.\n    mlApplyMeta P3. mlIntro.\n    mlApply \"2\". mlSplitAnd.\n    * mlAssumption.\n    * mlSplitAnd; mlAssumption.\n  Defined.\n\n  Lemma membership_implies_implication_meta Γ ϕ x i:\n    well_formed ϕ ->\n    Γ ⊢i patt_free_evar x ∈ml ϕ using i ->\n    Γ ⊢i patt_free_evar x ---> ϕ using i.\n  Proof.\n    intros WF H.\n    eapply MP. 2: gapply membership_implies_implication.\n    assumption.\n    try_solve_pile.\n    wf_auto2.\n  Defined.\n\n  Lemma membership_elimination Γ φ i x:\n    x ∉ free_evars φ ->\n    ProofInfoLe \n    (ExGen := {[ev_x; x]},\n    SVSubst := ∅,\n     KT := false,\n     AKT := false\n    ) i ->\n\n    well_formed φ ->\n    theory ⊆ Γ ->\n    Γ ⊢i all, ((patt_bound_evar 0) ∈ml φ) using i ->\n    Γ ⊢i φ using i.\n  Proof.\n    intros Hp pile wfφ HΓ H.\n    eapply forall_variable_substitution_meta with (x := x) in H.\n    2: wf_auto2.\n    assert (S1 : Γ ⊢i patt_free_evar x ∈ml φ using i). {\n      cbn in H. rewrite bevar_subst_not_occur in H. wf_auto2. assumption.\n    }\n    clear H.\n    apply membership_implies_implication_meta in S1 as S1'. 2: wf_auto2.\n    eapply Ex_gen with (x := x) in S1'.\n    2: try_solve_pile.\n    2: solve_free_evars 1.\n    mlApplyMeta S1'.\n    unfold exists_quantify. simpl. case_match. 2: congruence.\n    mlExactMeta (useBasicReasoning i (Existence Γ)).\n  Defined.\n\n  Lemma membership_not_1 Γ φ x:\n    well_formed φ ->\n    theory ⊆ Γ ->\n    Γ ⊢i ((patt_free_evar x) ∈ml (! φ)) ---> ! ((patt_free_evar x) ∈ml φ)\n    using BasicReasoning.\n  Proof.\n    intros Hwf HΓ.\n\n    pose proof (S1 := Singleton_ctx Γ AC_patt_defined AC_patt_defined φ x ltac:(wf_auto2)).\n    simpl in S1.\n\n    assert (S2: Γ ⊢i ⌈ patt_free_evar x and ! φ ⌉ ---> ! ⌈ patt_free_evar x and φ ⌉ using BasicReasoning).\n    {\n\n      replace (patt_sym (Definedness_Syntax.inj definedness) $ (patt_free_evar x and φ))\n        with (⌈ patt_free_evar x and φ ⌉) in S1 by reflexivity.\n\n      replace (patt_sym (Definedness_Syntax.inj definedness) $ (patt_free_evar x and ! φ))\n        with (⌈ patt_free_evar x and ! φ ⌉) in S1 by reflexivity.\n\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlAdd S1.\n      unfold patt_and at 1.\n      mlAssert ((! ⌈ patt_free_evar x and φ ⌉ or ! ⌈ patt_free_evar x and ! φ ⌉))\n               using first 1.\n      { wf_auto2. }\n      {\n        fromMLGoal.\n        useBasicReasoning.\n        apply not_not_elim.\n        wf_auto2.\n      }\n      mlClear \"1\".\n\n      (* Symmetry of Or *)\n      mlAssert ((! ⌈ patt_free_evar x and ! φ ⌉ or ! ⌈ patt_free_evar x and φ ⌉))\n               using first 1.\n      { wf_auto2. }\n      {\n        mlAdd (A_or_notA Γ (! ⌈ patt_free_evar x and φ ⌉) ltac:(wf_auto2)).\n        mlDestructOr \"0\".\n        - mlRight. mlExactn 0.\n        - mlLeft. mlApply \"2\". mlExactn 0.\n      }\n      mlClear \"2\".\n\n      mlApply \"1\". mlClear \"1\". fromMLGoal.\n      useBasicReasoning.\n      apply not_not_intro. wf_auto2.\n    }\n    apply S2.\n  Qed.\n\n  Lemma membership_not_2 Γ (φ : Pattern) x:\n    well_formed φ = true ->\n    theory ⊆ Γ ->\n    Γ ⊢i ((!(patt_free_evar x ∈ml φ)) ---> (patt_free_evar x ∈ml (! φ)))%ml\n    using  (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false).\n  Proof.\n    intros wfφ HΓ.\n    pose proof (S1 := defined_evar Γ x HΓ).\n    remember_constraint as i.\n    assert (S2: Γ ⊢i ⌈ (patt_free_evar x and φ) or (patt_free_evar x and (! φ)) ⌉ using i).\n    {\n      assert(H: Γ ⊢i (patt_free_evar x ---> ((patt_free_evar x and φ) or (patt_free_evar x and (! φ)))) using BasicReasoning).\n      {\n        toMLGoal.\n        { wf_auto2. }\n        mlIntro. mlAdd (A_or_notA Γ φ ltac:(auto)).\n        mlDestructOr \"1\".\n        - mlLeft. unfold patt_and. mlIntro. unfold patt_or.\n          mlAssert ((! φ)).\n          { wf_auto2. }\n          {\n            mlApply \"1\". mlClear \"2\". mlClear \"1\". fromMLGoal.\n            apply not_not_intro; auto.\n          }\n          mlApply \"3\". mlExactn 0.\n        - mlRight. unfold patt_and. mlIntro. unfold patt_or.\n          mlApply \"3\". mlApplyMetaRaw (not_not_elim Γ φ ltac:(auto)).\n          mlApply \"1\". mlIntro. mlApply \"2\". mlExactn 1.\n      }\n      apply useBasicReasoning with (i := i) in H.\n      subst i.\n      eapply Framing_right in H.\n      eapply MP. 2: apply H.\n      1: gapply S1; try_solve_pile.\n      { wf_auto2. }\n      { try_solve_pile. }\n    }\n\n    pose proof (Htmp := prf_prop_or_iff Γ AC_patt_defined (patt_free_evar x and φ) (patt_free_evar x and ! φ)\n                                        ltac:(wf_auto2) ltac:(wf_auto2)).\n    simpl in Htmp.\n    apply pf_iff_proj1 in Htmp.\n    2-3: wf_auto2.\n    subst i.\n    eapply MP.\n    2: gapply Htmp; try_solve_pile.\n    assumption.\n  Defined.\n\n  Lemma membership_not_iff Γ φ x:\n    well_formed φ ->\n    theory ⊆ Γ ->\n    Γ ⊢i ((patt_free_evar x) ∈ml (! φ)) <---> ! ((patt_free_evar x) ∈ml φ)\n    using  (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false).\n  Proof.\n    intros Hwf HΓ.\n    apply pf_iff_split.\n    1,2: wf_auto2.\n    - useBasicReasoning; apply membership_not_1; assumption.\n    - apply membership_not_2; assumption.\n  Defined.\n  \n  Lemma membership_or_1 Γ x φ₁ φ₂:\n    well_formed φ₁ ->\n    well_formed φ₂ ->\n    theory ⊆ Γ ->\n    Γ ⊢i (patt_free_evar x ∈ml (φ₁ or φ₂)) ---> ((patt_free_evar x ∈ml φ₁) or (patt_free_evar x ∈ml φ₂))\n    using BasicReasoning.\n  Proof.\n    intros wfφ₁ wfφ₂ HΓ.\n    unfold patt_in.\n    eapply syllogism_meta.\n    5: gapply Prop_disj_right. 5: try_solve_pile.\n    1,2,3,5,6,7: wf_auto2.\n    unshelve (eapply Framing_right).\n    { wf_auto2. }\n    { try_solve_pile. }\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlDestructAnd \"0\".\n    mlDestructOr \"2\".\n    - mlLeft. unfold patt_and. mlIntro.\n      mlDestructOr \"2\".\n      + mlApply \"3\". mlExactn 0.\n      + mlApply \"4\". mlExactn 1.\n    - mlRight. unfold patt_and. mlIntro.\n      mlDestructOr \"0\".\n      + mlApply \"2\". mlExactn 0.\n      + mlApply \"4\". mlExactn 1.\n  Defined.\n\n  Lemma membership_or_2 Γ x φ₁ φ₂:\n    well_formed φ₁ ->\n    well_formed φ₂ ->\n    theory ⊆ Γ ->\n    Γ ⊢i ((patt_free_evar x ∈ml φ₁) or (patt_free_evar x ∈ml φ₂)) ---> (patt_free_evar x ∈ml (φ₁ or φ₂))\n    using BasicReasoning.\n  Proof.\n    intros wfφ₁ wfφ₂ HΓ.\n    unfold patt_in.\n    pose proof (H1 := prf_prop_or_iff Γ AC_patt_defined (patt_free_evar x and φ₁) (patt_free_evar x and φ₂)\n                                      ltac:(auto) ltac:(auto)).\n    apply pf_iff_proj2 in H1.\n    2,3: wf_auto2.\n    eapply syllogism_meta.\n    4: gapply H1; try_solve_pile.\n    1-3: wf_auto2.\n    simpl.\n    unshelve (eapply Framing_right).\n    { wf_auto2. }\n    { unfold BasicReasoning. try_solve_pile. }\n\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlDestructOr \"0\".\n    - mlDestructAnd \"1\". unfold patt_and. mlIntro. mlDestructOr \"1\".\n      + mlApply \"3\". mlExactn 0.\n      + mlApply \"4\". mlLeft. mlExactn 1.\n    - mlDestructAnd \"2\". unfold patt_and. mlIntro. mlDestructOr \"2\".\n      + mlApply \"3\". mlExactn 0.\n      + mlApply \"4\". mlRight. mlExactn 1.\n  Defined.\n\n  Lemma membership_or_iff Γ x φ₁ φ₂:\n    well_formed φ₁ ->\n    well_formed φ₂ ->\n    theory ⊆ Γ ->\n    Γ ⊢i (patt_free_evar x ∈ml (φ₁ or φ₂)) <---> ((patt_free_evar x ∈ml φ₁) or (patt_free_evar x ∈ml φ₂))\n    using BasicReasoning.\n  Proof.\n    intros wfφ₁ wfφ₂ HΓ.\n    apply pf_iff_split.\n    1,2: wf_auto2.\n    + apply membership_or_1; assumption.\n    + apply membership_or_2; assumption.\n  Defined.\n\n\n  Lemma membership_and_1 Γ x φ₁ φ₂:\n    well_formed φ₁ ->\n    well_formed φ₂ ->\n    theory ⊆ Γ ->\n    Γ ⊢i (patt_free_evar x ∈ml (φ₁ and φ₂)) ---> ((patt_free_evar x ∈ml φ₁) and (patt_free_evar x ∈ml φ₂))\n    using  (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false).\n  Proof.\n    intros wfφ₁ wfφ₂ HΓ.\n\n    epose proof (Htmp1 := (membership_or_2 _ _ _ _ _ _ HΓ)).\n    (* TODO: [change constraint in _] should work even in proof mode! *)\n    change constraint in Htmp1.\n    remember_constraint as gpi.\n\n    unfold patt_and.\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro.\n    assert (wfφ : well_formed (! φ₁ or ! φ₂)).\n    { wf_auto2. }\n    unshelve (mlApplyMetaRaw (useBasicReasoning gpi (membership_not_1 _ _ _ wfφ HΓ)) in \"0\").\n    mlIntro. mlApply \"0\". mlClear \"0\".\n    mlApplyMetaRaw Htmp1.\n    mlDestructOr \"1\"; subst gpi.\n    - mlLeft.\n      unshelve (mlApplyMetaRaw (membership_not_2 _ _ _ wfφ₁ HΓ) in \"0\").\n      mlExactn 0.\n    - mlRight.\n      unshelve (mlApplyMetaRaw (membership_not_2 _ _ _ wfφ₂ HΓ) in \"2\").\n      mlExactn 0.\n      Unshelve. all: wf_auto2.\n  Defined.\n\n  Lemma membership_and_2 Γ x φ₁ φ₂:\n    well_formed φ₁ ->\n    well_formed φ₂ ->\n    theory ⊆ Γ ->\n    Γ ⊢i ((patt_free_evar x ∈ml φ₁) and (patt_free_evar x ∈ml φ₂)) ---> (patt_free_evar x ∈ml (φ₁ and φ₂))\n    using  (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false).\n  Proof.\n    intros wfφ₁ wfφ₂ HΓ.\n\n    epose proof (Htmp1 := (membership_or_1 _ _ _ _ _ _ HΓ)).\n    change constraint in Htmp1.\n    epose proof (Htmp2 := (membership_not_1 _ _ _ _ HΓ)).\n    change constraint in Htmp2.\n    epose proof (Htmp3 := (membership_not_1 _ _ _ _ HΓ)).\n    change constraint in Htmp3.\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro.\n    mlDestructAnd \"0\".\n    unfold patt_and.\n\n    unshelve (mlApplyMetaRaw (membership_not_2 _ _ _ _ HΓ)).\n    { wf_auto2. }\n    mlIntro.\n\n    mlApplyMetaRaw Htmp1 in \"0\".\n    mlDestructOr \"0\".\n    - mlApplyMetaRaw Htmp2 in \"3\".\n      mlApply \"3\". mlExactn 0.\n    -\n      mlApplyMetaRaw Htmp3 in \"4\".\n      mlApply \"4\". mlExactn 1.\n      Unshelve. all: wf_auto2.\n  Defined.\n\n  Lemma membership_and_iff Γ x φ₁ φ₂:\n    well_formed φ₁ ->\n    well_formed φ₂ ->\n    theory ⊆ Γ ->\n    Γ ⊢i (patt_free_evar x ∈ml (φ₁ and φ₂)) <---> ((patt_free_evar x ∈ml φ₁) and (patt_free_evar x ∈ml φ₂))\n    using  (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false).\n  Proof.\n    intros wfφ₁ wfφ₂ HΓ.\n    apply pf_iff_split.\n    1,2: wf_auto2.\n    + apply membership_and_1; assumption.\n    + apply membership_and_2; assumption.\n  Defined.\n\n  Lemma mu_free_in_path φ:\n    mu_free φ = true -> forall x, mu_in_evar_path x φ 0 = false.\n  Proof.\n    intros H x.\n    induction φ; unfold mu_in_evar_path in *; cbn in *; try congruence; try reflexivity.\n    case: decide => H0; reflexivity.\n    1-2: apply andb_true_iff in H as [H1 H2];\n    rewrite /=; do 2 case_match; auto.\n    eapply IHφ in H. apply H.\n  Qed.\n\n  Lemma equality_elimination_basic_mfpath Γ φ1 φ2 C\n    (HΓ : theory ⊆ Γ)\n    (WF1 : well_formed φ1)\n    (WF2 :  well_formed φ2)\n    (WFC : PC_wf C) :\n    mu_in_evar_path (pcEvar C) (pcPattern C) 0 = false ->\n    Γ ⊢i (φ1 =ml φ2) --->\n      (emplace C φ1) <---> (emplace C φ2)\n    using AnyReasoning.\n      (* using (\n    (ExGen := {[ev_x]}\n              ∪ {[evar_fresh (elements (free_evars φ1 ∪ free_evars φ2))]}\n              ∪ (gset_to_coGset (free_evars φ1))\n              ∪ (gset_to_coGset (free_evars φ2))\n              ∪ (gset_to_coGset (list_to_set\n                (evar_fresh_seq\n                   (free_evars (pcPattern C) ∪ free_evars φ1 ∪ free_evars φ2\n                    ∪ {[pcEvar C]})\n                   (maximal_exists_depth_of_evar_in_pattern \n                      (pcEvar C) (pcPattern C)))))\n              ∪ (gset_to_coGset (list_to_set (map\n                  (fun psi : wfPattern => evar_fresh (elements (free_evars φ1 ∪ free_evars φ2 ∪ free_evars (`psi))))\n                  ((elements\n                  (frames_on_the_way_to_hole'\n                     (free_evars (pcPattern C) ∪ free_evars φ1\n                      ∪ free_evars φ2 ∪ {[\n                      pcEvar C]})\n                     (free_svars (pcPattern C) ∪ free_svars φ1\n                      ∪ free_svars φ2) (pcEvar C) \n                     (pcPattern C) φ1 φ2 WFC WF1 WF2)))\n                  )))\n              ,\n     SVSubst := list_to_set\n                  (svar_fresh_seq\n                     (free_svars (pcPattern C) ∪ free_svars φ1\n                      ∪ free_svars φ2)\n                     (maximal_mu_depth_of_evar_in_pattern \n                        (pcEvar C) (pcPattern C)))\n                ∪ (gset_to_coGset\n                (free_svars φ1 ∪ free_svars φ2)),\n     KT := (if\n             decide\n               (0 =\n                maximal_mu_depth_of_evar_in_pattern (pcEvar C) (pcPattern C))\n            is left _\n            then false\n            else true),\n     FP := ⊤\n    )). *)\n  Proof.\n    intros Hmf.\n\n    eapply useGenericReasoning.\n    2: {\n      unshelve(eapply deduction_theorem_noKT).\n      2: {\n        remember (Γ ∪ {[ (φ1 <---> φ2) ]}) as Γ'.\n        remember_constraint as i.\n        assert (Γ' ⊢i (φ1 <---> φ2) using i). {\n          subst i. useBasicReasoning.\n          apply BasicProofSystemLemmas.hypothesis.\n          - abstract (now apply well_formed_iff).\n          - abstract (rewrite HeqΓ'; apply elem_of_union_r; constructor).\n        }\n        subst i.\n        unshelve (eapply prf_equiv_congruence).\n        { apply WF1. }\n        { apply WF2. }\n        { apply WFC. }\n        2: apply H.\n        apply pile_refl.\n      }\n    { \n      abstract (\n        apply well_formed_and; apply well_formed_imp; unfold emplace;\n        apply well_formed_free_evar_subst_0; auto\n      ).\n    }\n    { abstract (wf_auto2). }\n    { exact HΓ. }\n    {\n      simpl.\n      unfold PC_wf in WFC.\n      destruct C; simpl in *.\n      replace (free_evars φ1 ∪ free_evars φ2 ∪ ∅ ∪ ∅\n      ∪ (free_evars φ2 ∪ free_evars φ1 ∪ ∅) ∪ ∅)\n      with (free_evars φ1 ∪ free_evars φ2)\n      by set_solver.\n\n      pose proof (evar_fresh_seq_disj (free_evars pcPattern ∪ free_evars φ1 ∪ free_evars φ2 ∪ {[pcEvar]}) (maximal_exists_depth_to 0 pcEvar pcPattern)).\n      set_solver.\n    }\n    {\n      simpl.\n      unfold PC_wf in WFC.\n      destruct C; simpl in *.\n\n      pose proof (svar_fresh_seq_disj (free_svars pcPattern ∪ free_svars φ1 ∪ free_svars φ2) (maximal_mu_depth_to 0 pcEvar pcPattern)).\n      set_solver.\n    }\n    {\n      simpl. exact Hmf.\n    }\n  }\n  {\n    try_solve_pile.\n    (* simpl.\n    unfold dt_exgen_from_fp. simpl.\n    repeat rewrite union_empty_r_L.\n    replace (free_evars φ1 ∪ free_evars φ2\n    ∪ (free_evars φ2 ∪ free_evars φ1))\n    with (free_evars φ1 ∪ free_evars φ2) by set_solver.\n    apply pile_evs_svs_kt.\n    {\n      clear. set_solver.\n    }\n    {\n      clear. set_solver.\n    }\n    {\n      reflexivity.\n    }\n    {\n      clear. set_solver.\n    } *)\n  }\n  Defined.\n\n  Lemma equality_elimination_basic Γ φ1 φ2 C\n  (HΓ : theory ⊆ Γ)\n  (WF1 : well_formed φ1)\n  (WF2 :  well_formed φ2)\n  (WFC : PC_wf C) :\n  mu_free (pcPattern C) ->\n  Γ ⊢i (φ1 =ml φ2) --->\n    (emplace C φ1) <---> (emplace C φ2)\n  using AnyReasoning.\n  Proof.\n    intros.\n    apply equality_elimination_basic_mfpath; try assumption.\n    now apply mu_free_in_path.\n  Defined.\n\n\n  Lemma equality_elimination_basic_ar Γ φ1 φ2 C:\n    theory ⊆ Γ ->\n    well_formed φ1 ->\n    well_formed φ2 ->\n    PC_wf C ->\n    mu_in_evar_path (pcEvar C) (pcPattern C) 0 = false ->\n    Γ ⊢i (φ1 =ml φ2) --->\n      (emplace C φ1) <---> (emplace C φ2)\n    using AnyReasoning.\n  Proof.\n    intros.\n    unshelve (gapply equality_elimination_basic_mfpath); try assumption.\n    unfold AnyReasoning.\n    try_solve_pile.\n  Defined.\n\n  (* NOTE: could this also be solved withouth induction? *)\n  Lemma equality_elimination_basic_ar_iter_1 Γ φ₁ φ₂ l C :\n    theory ⊆ Γ ->\n    well_formed φ₁ ->\n    well_formed φ₂ ->\n    Pattern.wf l ->\n    PC_wf C ->\n    mu_in_evar_path (pcEvar C) (pcPattern C) 0 = false ->\n    Γ ⊢i foldr patt_imp ((emplace C φ₁) <---> (emplace C φ₂)) ((φ₁ =ml φ₂) :: l)\n    using AnyReasoning.\n  Proof.\n    intros HΓ wfφ₁ wfφ₂ wfl wfC Hmf.\n    induction l; simpl.\n    - apply equality_elimination_basic_ar; assumption.\n    - pose proof (wfal := wfl). apply andb_prop in wfl as [wfa wfl].\n      specialize (IHl wfl).\n      simpl in IHl.\n      pose proof (proved_impl_wf _ _ (proj1_sig IHl)).\n\n      assert (well_formed (emplace C φ₁) = true) by (unfold emplace; wf_auto2).\n      assert (well_formed (emplace C φ₂) = true) by (unfold emplace; wf_auto2).\n      \n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlIntro. mlClear \"1\".\n      fromMLGoal.\n      apply IHl.\n  Defined.\n\n  (* TODO: this should NOT be done this way probably. There should be a general lemma, which can propagate another \"foldr\" lemma inside l₁, since there are other theorems that use the same scheme *)\n  Lemma equality_elimination_basic_ar_iter Γ φ₁ φ₂ l₁ l₂ C :\n    theory ⊆ Γ ->\n    well_formed φ₁ ->\n    well_formed φ₂ ->\n    Pattern.wf l₁ ->\n    Pattern.wf l₂ ->\n    PC_wf C ->\n    mu_in_evar_path (pcEvar C) (pcPattern C) 0 = false ->\n    Γ ⊢i foldr patt_imp ((emplace C φ₁) <---> (emplace C φ₂)) (l₁ ++ (φ₁ =ml φ₂)::l₂)\n    using AnyReasoning.\n  Proof.\n    intros HΓ wfφ₁ wfφ₂ wfl₁ wfl₂ wfC Hmf.\n    induction l₁; simpl.\n    - apply equality_elimination_basic_ar_iter_1; assumption.\n    - pose proof (wfal := wfl₁). unfold wf in wfl₁. simpl in wfl₁. apply andb_prop in wfl₁ as [wfa wfl].\n      specialize (IHl₁ wfl).\n      pose proof (proved_impl_wf _ _ (proj1_sig IHl₁)).\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\".\n      fromMLGoal.\n      apply IHl₁.\n  Defined.\n\n  Corollary equality_elimination_proj Γ φ1 φ2 ψ:\n    theory ⊆ Γ ->\n    mu_free ψ ->\n    well_formed φ1 -> well_formed φ2 -> well_formed_closed_ex_aux ψ 1 -> well_formed_closed_mu_aux ψ 0 ->\n    Γ ⊢i (φ1 =ml φ2) ---> \n      (ψ^[evar: 0 ↦ φ1]) ---> (ψ^[evar: 0 ↦ φ2])\n    using AnyReasoning.\n  Proof.\n    intros HΓ MF WF1 WF2 WF3 WF4. remember (fresh_evar ψ) as x.\n    assert (x ∉ free_evars ψ) by now apply x_eq_fresh_impl_x_notin_free_evars.\n    rewrite (bound_to_free_variable_subst ψ x 1 0 φ1 ltac:(lia)); auto.\n    { unfold well_formed,well_formed_closed in *. destruct_and!. assumption. }\n    rewrite (bound_to_free_variable_subst ψ x 1 0 φ2 ltac:(lia)); auto.\n    { unfold well_formed,well_formed_closed in *. destruct_and!. assumption. }\n    (* needed for wf_auto2: *)\n    have Hmf1 : well_formed_positive ψ = true by apply mu_free_wfp. \n    have Hmf2 : mu_free (pcPattern {| pcEvar := x; pcPattern := ψ^{evar:0↦x} |}) by apply mu_free_evar_open.\n    have H0 := equality_elimination_basic Γ φ1 φ2 {|pcEvar := x; pcPattern := ψ^{evar:0 ↦ x}|} HΓ WF1 WF2 ltac:(wf_auto2) Hmf2.\n\n    toMLGoal. wf_auto2.\n      mlIntro.\n\n      mlApplyMeta (pf_conj_elim_l Γ\n         (ψ^{evar:0↦x}^[[evar:x↦φ1]] ---> ψ^{evar:0↦x}^[[evar:x↦φ2]])\n         (ψ^{evar:0↦x}^[[evar:x↦φ2]] ---> ψ^{evar:0↦x}^[[evar:x↦φ1]])\n                  ).\n      mlApplyMeta H0. mlExact \"0\".\n  Defined.\n\n  (* TODO: proof infos *)\n  Lemma patt_equal_sym Γ φ1 φ2:\n    theory ⊆ Γ ->\n    well_formed φ1 -> well_formed φ2 ->\n    Γ ⊢i φ1 =ml φ2 ---> φ2 =ml φ1\n    using AnyReasoning.\n  Proof.\n    intros HΓ WF1 WF2.\n    unshelve (gapply deduction_theorem_noKT).\n    4,5: abstract(wf_auto2).\n    4: exact HΓ.\n    3: {\n      remember_constraint as i'.\n      remember (Γ ∪ {[ (φ1 <---> φ2) ]}) as Γ'.\n      assert (Γ' ⊢i (φ1 <---> φ2) using i'). {\n        subst i'. useBasicReasoning.\n        apply BasicProofSystemLemmas.hypothesis. apply well_formed_iff; auto.\n        rewrite HeqΓ'. apply elem_of_union_r. constructor.\n      }\n      apply pf_iff_equiv_sym in H; auto.\n      apply patt_iff_implies_equal; auto.\n      subst i'. apply pile_refl.\n    }\n    {\n      apply pile_any.\n    }\n    {\n      simpl. set_solver.\n    }\n    {\n      simpl. set_solver.\n    }\n    {\n      simpl. reflexivity.\n    }\n  Defined.\n\n  Lemma evar_quantify_equal_simpl : forall φ1 φ2 x n,\n      evar_quantify x n (φ1 =ml φ2) = (evar_quantify x n φ1) =ml (evar_quantify x n φ2).\n  Proof. auto. Qed.\n\n  Definition is_functional φ : Pattern :=\n    (ex, φ =ml b0).\n\n  Lemma patt_equal_comm φ φ' Γ:\n    theory ⊆ Γ ->\n    well_formed φ ->\n    well_formed φ' ->\n    Γ ⊢ (φ =ml φ') <---> (φ' =ml φ).\n  Proof.\n    intros HΓ wfφ wfφ'.\n    pose proof (SYM1 := @patt_equal_sym Γ φ' φ HΓ wfφ' wfφ).\n    pose proof (SYM2 := @patt_equal_sym Γ φ φ' HΓ wfφ wfφ').\n    apply pf_iff_split. 3,4: assumption. 1,2: wf_auto2. \n  Defined.\n\n  Lemma exists_functional_subst φ φ' Γ :\n    theory ⊆ Γ ->\n    mu_free φ -> well_formed φ' -> well_formed_closed_ex_aux φ 1 -> well_formed_closed_mu_aux φ 0 ->\n    Γ ⊢i ((instantiate (patt_exists φ) φ') and is_functional φ') ---> (patt_exists φ)\n    using AnyReasoning.\n  Proof.\n    intros HΓ MF WF WFB WFM.\n    remember (fresh_evar (φ $ φ')) as Zvar.\n    remember (patt_free_evar Zvar) as Z.\n    assert (well_formed Z) as WFZ.\n    { rewrite HeqZ. auto. }\n\n    assert (well_formed (instantiate (ex , φ) φ')) as WF1. {\n      unfold instantiate.\n      unfold well_formed, well_formed_closed.\n      apply andb_true_iff in WF as [E1 E2].\n      unfold well_formed_closed in *. destruct_and!.\n      erewrite bevar_subst_closed_mu, bevar_subst_positive, bevar_subst_closed_ex; auto.\n      now apply mu_free_wfp.\n    }\n    assert (well_formed (instantiate (ex , φ) Z)) as WF2. {\n      unfold instantiate.\n      unfold well_formed, well_formed_closed.\n      apply andb_true_iff in WF as [E1 E2]. simpl in E1, E2.\n      unfold well_formed_closed in *. destruct_and!.\n      erewrite bevar_subst_closed_mu, bevar_subst_positive, bevar_subst_closed_ex; auto.\n      all: try rewrite HeqZ; auto.\n      now apply mu_free_wfp.\n    }\n    \n    assert (well_formed (ex, φ)) as WFEX.\n    { wf_auto2. }\n    pose proof (EQ := BasicProofSystemLemmas.Ex_quan Γ φ Zvar WFEX).\n    change constraint in EQ.\n    epose proof (PC := prf_conclusion Γ (patt_equal φ' Z) (instantiate (ex , φ) (patt_free_evar Zvar) ---> ex , φ) AnyReasoning ltac:(apply well_formed_equal;wf_auto2) _ EQ).\n\n    assert (Γ ⊢ patt_equal φ' Z ---> (ex , φ) ^ [φ'] ---> ex , φ) as HSUB.\n    {\n      pose proof (EE := equality_elimination_proj Γ φ' Z φ HΓ\n                                               ltac:(auto) ltac:(auto) ltac:(auto) WFB WFM).\n\n      epose proof (PSP := prf_strenghten_premise Γ ((patt_equal φ' Z) and (instantiate (ex , φ) Z))\n                                                 ((patt_equal φ' Z) and (instantiate (ex , φ) φ'))\n                                                 (ex , φ) _ _ _).\n      eapply MP.\n      2: useBasicReasoning; apply and_impl.\n      2,3,4: wf_auto2.\n      eapply MP.\n      2: eapply MP.\n      3: useBasicReasoning; exact PSP.\n\n      * unshelve (epose proof (AI := and_impl' Γ (patt_equal φ' Z) (φ^[evar: 0 ↦ Z]) (ex , φ) _ _ _)).\n        1,2,3: wf_auto2.\n        unfold instantiate.\n        (* TODO: tactic for modus ponens *)\n        eapply MP. 2: useBasicReasoning; exact AI.\n        rewrite <- HeqZ in PC.\n        exact PC.\n      * apply and_drop. 1-3: wf_auto2.\n        unshelve(epose proof (AI := and_impl' Γ (patt_equal φ' Z) (instantiate (ex , φ) φ') (instantiate (ex , φ) Z) _ _ _)).\n        1-3: wf_auto2.\n        eapply MP. 2: useBasicReasoning; exact AI.\n        { exact EE. }\n    }\n\n    eapply (BasicProofSystemLemmas.Ex_gen Γ _ _ Zvar) in HSUB.\n    3: {\n      rewrite HeqZvar. unfold fresh_evar. simpl.\n      apply not_elem_of_union.\n      split.\n      - eapply stdpp_ext.not_elem_of_larger_impl_not_elem_of.\n        2: { apply set_evar_fresh_is_fresh'. }\n        rewrite comm.\n        apply free_evars_bevar_subst.\n      - eapply stdpp_ext.not_elem_of_larger_impl_not_elem_of.\n        2: { apply set_evar_fresh_is_fresh'. }\n        clear. set_solver.\n\n    }\n    2: { apply pile_any. }\n    \n    unfold exists_quantify in HSUB.\n    mlSimpl in HSUB.\n    rewrite -> HeqZ, -> HeqZvar in HSUB.\n    simpl evar_quantify in HSUB.\n    rewrite decide_eq_same in HSUB.\n\n    rewrite evar_quantify_fresh in HSUB.\n    { solve_fresh. }\n\n    (* TODO do something like this, but we need more general mlApplyMeta\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro \"H\".\n    mlDestructAnd \"H\" as \"H1\" \"H2\".\n\n    mlApplyMeta (reshape_lhs_imp_to_and_forward _ _ _ _ _ _ _ _ _ HSUB).\n    eapply reshape_lhs_imp_to_and_forward in HSUB; try_wfauto2; simpl in HSUB.\n    mlApplyMeta HSUB.\n    *)\n    eapply MP. 2: useBasicReasoning; apply and_impl'; try_wfauto2.\n    apply reorder_meta; try_wfauto2.\n    exact HSUB.\n    Unshelve.\n    all: wf_auto2.\n  Defined.\n\n  Corollary forall_functional_subst φ φ' Γ :\n    theory ⊆ Γ ->\n    mu_free φ -> well_formed φ' -> well_formed_closed_ex_aux φ 1 -> well_formed_closed_mu_aux φ 0 ->\n    Γ ⊢i ((patt_forall φ) and (patt_exists (patt_equal φ' (patt_bound_evar 0)))) ---> (φ^[evar: 0 ↦ φ'])\n    using AnyReasoning.\n  Proof.\n    intros HΓ MF WF WFB WFM. unfold patt_forall.\n    assert (well_formed (φ^[evar: 0 ↦ φ'])) as BWF. {\n      unfold well_formed, well_formed_closed in *.\n      destruct_and!.\n      split_and!.\n      - apply well_formed_positive_bevar_subst; auto.\n        now apply mu_free_wfp.\n      - auto.\n      - apply wfc_ex_aux_bevar_subst; auto.\n    }\n    assert (well_formed (ex , patt_equal φ' b0)) as SWF. {\n      unfold well_formed, well_formed_closed.\n      apply andb_true_iff in WF as [E1 E2]. unfold well_formed_closed in E2.\n      simpl. rewrite E1.\n      unfold well_formed,well_formed_closed in *. destruct_and!.\n      split_and!; auto.\n      - eapply well_formed_closed_ex_aux_ind. 2: eassumption. lia.\n      - eapply well_formed_closed_ex_aux_ind. 2: eassumption. lia.\n    }\n    assert (well_formed (ex , (φ ---> ⊥))) as NWF. {\n      unfold well_formed, well_formed_closed in *.\n      clear BWF SWF.\n      destruct_and!. split_and!; auto.\n      apply mu_free_wfp; simpl; now rewrite MF.\n      all: simpl; wf_auto2.\n    }\n    unshelve (epose proof (H := exists_functional_subst (! φ) φ' Γ HΓ _ WF _ _)).\n    { simpl. rewrite andbT. exact MF. }\n    { wf_auto2. }\n    { wf_auto2. }\n    simpl in H.\n    epose proof (H0 := and_impl _ _ _ _ _ _ _).\n    epose proof (H0' := and_impl _ _ _ _ _ _ _).\n    eapply useBasicReasoning with (i := AnyReasoning) in H0.\n    eapply MP in H0. 2: apply H.\n    apply reorder_meta in H0.\n    2-4: wf_auto2.\n\n    epose proof (H1 := and_impl' _ _ _ _ _ _ _).\n    eapply useBasicReasoning with (i := AnyReasoning) in H1.\n    eapply MP in H1. exact H1.\n\n    apply reorder_meta. 1-3: wf_auto2.\n    epose proof (H2 := P4 Γ (φ^[evar: 0 ↦ φ']) (! ex , patt_not (φ)) _ _).\n    clear H H1.\n    epose proof (otherH := prf_weaken_conclusion Γ (ex , patt_equal φ' b0) ((φ^[evar: 0 ↦ φ'] ---> ⊥) ---> ex , (! φ)) ((φ^[evar: 0 ↦ φ'] ---> ⊥) ---> ! ! ex , (! φ)) _ _ _).\n    eapply MP in otherH.\n    2: {\n      epose proof (H1 := prf_weaken_conclusion Γ (φ^[evar: 0 ↦ φ'] ---> ⊥) (ex , (! φ)) (! ! ex , (! φ)) _ _ _).\n      eapply MP. 2: apply H1.\n      apply not_not_intro.\n      wf_auto2.\n    }\n\n    eapply useBasicReasoning with (i := AnyReasoning) in otherH.\n    eapply MP in otherH.\n    {\n      eapply useBasicReasoning with (i := AnyReasoning) in H2.\n      eapply syllogism_meta in H2.\n      3,4: wf_auto2.\n      3: apply otherH.\n      2: wf_auto2.\n      exact H2.\n    }\n    exact H0.\n    Unshelve.\n    (* I do not like this. Why do we have unification variables on which nothing depends? *)\n    4,5,6: apply well_formed_bott.\n    4: exact Γ.\n    all: wf_auto2.\n  Defined.\n\nEnd ProofSystemTheorems.\n\n\nLemma MLGoal_rewriteBy {Σ : Signature} {syntax : Syntax}\n    (Γ : Theory) (l₁ l₂ : hypotheses) name (φ₁ φ₂ : Pattern) (C : PatternCtx) :\n  theory ⊆ Γ ->\n  mu_in_evar_path (pcEvar C) (pcPattern C) 0 = false ->\n  mkMLGoal Σ Γ (l₁ ++ (mkNH _ name (φ₁ =ml φ₂)) :: l₂) (emplace C φ₂) AnyReasoning ->\n  mkMLGoal Σ Γ (l₁ ++ (mkNH _ name (φ₁ =ml φ₂)) :: l₂) (emplace C φ₁) AnyReasoning .\nProof.\n  intros HΓ HmfC H.\n  mlExtractWF wfl wfg.\n  unfold patterns_of in wfl. rewrite map_app in wfl.\n  pose proof (wfl₁ := wfapp_proj_1 _ _ wfl).\n  apply wfapp_proj_2 in wfl.\n  unfold wf in wfl. simpl in wfl.\n  apply andb_prop in wfl.\n  destruct wfl as [wfeq wfl₂].\n  pose proof (wfC := wf_emplaced_impl_wf_context _ _ wfg).\n  remember C as C'.\n  destruct C as [CE Cψ]. unfold PC_wf in wfC. simpl in *.\n\n  lazymatch goal with\n    | [ |- of_MLGoal (mkMLGoal _ _ ?l _ _) ]\n      => remember (names_of l) as names_of_l \n  end.\n\n  _mlAssert_nocheck ((fresh names_of_l) : (emplace C' φ₁ <---> emplace C' φ₂)). (* !!! *)\n  { unfold emplace in *. wf_auto2. }\n  { fromMLGoal.\n    unfold patterns_of.\n    rewrite map_app.\n    simpl.\n    apply equality_elimination_basic_ar_iter; auto.\n    { wf_auto2. }\n    { wf_auto2. }\n  }\n  unfold patt_iff.\n  epose proof (Htmp := (pf_conj_elim_r _ _ _ _ _)).\n  apply @useBasicReasoning with (i := AnyReasoning) in Htmp.\n  eapply (MLGoal_applyMetaIn Γ _ _ (fresh names_of_l) _ _ Htmp).\n  clear Htmp.\n\n  replace (l₁ ++ (mkNH _ name (φ₁ =ml φ₂)) :: l₂)\n     with ((l₁ ++ (mkNH _ name (φ₁ =ml φ₂)) :: l₂) ++ [])\n     in H\n    by (rewrite app_nil_r; reflexivity).\n  apply mlGoal_clear_hyp with (h := (mkNH _ (fresh names_of_l) ((emplace C' φ₂) ---> (emplace C' φ₁)))) in H.\n\n  lazymatch goal with\n    | [ |- of_MLGoal (mkMLGoal _ _ ?l _ _) ]\n      => remember (names_of l) as names_of_l' \n  end.\n\n  eapply mlGoal_assert with (name := (fresh names_of_l')).\n  2: {\n    apply H.\n  }\n  { wf_auto2. }\n\n  simpl.\n  rewrite -app_assoc.\n  simpl.\n  eapply MLGoal_weakenConclusion.\n\n  replace ((l₁ ++ (mkNH _ name (φ₁ =ml φ₂)) :: l₂)\n            ++ [(mkNH _ (fresh names_of_l) ((emplace C' φ₂) ---> (emplace C' φ₁)));\n                (mkNH _ (fresh names_of_l') (emplace C' φ₂))])\n  with (((l₁ ++ (mkNH _ name (φ₁ =ml φ₂)) :: l₂)\n        ++ [mkNH _ (fresh names_of_l) ((emplace C' φ₂) ---> (emplace C' φ₁))])\n        ++ [mkNH _ (fresh names_of_l') (emplace C' φ₂)]).\n  2: {  rewrite -app_assoc. simpl. reflexivity. }\n  useBasicReasoning.\n  apply MLGoal_exactn.\n  Unshelve.\n  all: abstract (wf_auto2).\nDefined.\n\nLtac2 mlRewriteBy (name' : constr) (atn : int) :=\n_mlReshapeHypsByName name';\nlazy_match! goal with\n| [ |- @of_MLGoal ?sgm (@mkMLGoal ?sgm ?g (?l₁ ++ (mkNH _ _ (?a' =ml ?a))::?l₂) ?p AnyReasoning)]\n  => \n    let hr : HeatResult := heat atn a' p in\n    let heq := Control.hyp (hr.(equality)) in\n    let pc := (hr.(pc)) in\n    eapply (@cast_proof_ml_goal _ $g) >\n      [ rewrite $heq; reflexivity | ()];\n    Std.clear [hr.(equality)];\n    apply MLGoal_rewriteBy\n    > [ ()\n      | ()\n      | lazy_match! goal with\n        | [ |- of_MLGoal (@mkMLGoal ?sgm ?g ?l ?p AnyReasoning)]\n          =>\n            let heq2 := Fresh.in_goal ident:(heq2) in\n            let plugged := Pattern.instantiate (hr.(ctx)) a in\n            assert(heq2: ($p = $plugged))\n            > [\n                abstract (ltac1:(star |- simplify_emplace_2 star) (Ltac1.of_ident (hr.(star_ident)));\n                          reflexivity\n                         )\n              | ()\n              ];\n            let heq2_pf := Control.hyp heq2 in\n            eapply (@cast_proof_ml_goal _ $g) >\n              [ rewrite $heq2_pf; reflexivity | ()];\n            Std.clear [heq2 ; (hr.(star_ident)); (hr.(star_eq))];\n            _mlReshapeHypsBack ()\n        end\n      ]\nend\n.\n\nTactic Notation \"mlRewriteBy\" constr(name') \"at\" constr(atn) :=\n(let ff := ltac2:(name'' atn |-\n                    mlRewriteBy\n                      (Option.get (Ltac1.to_constr(name'')))\n                      (constr_to_int (Option.get (Ltac1.to_constr(atn))))\n                 ) in\n ff name' atn).\n\n\n\nLocal Example ex_rewriteBy {Σ : Signature} {syntax : Syntax} Γ a a' b:\n  theory ⊆ Γ ->\n  well_formed a ->\n  well_formed a' ->\n  well_formed b ->\n  mu_free b ->\n  Γ ⊢i a $ b ---> (a' =ml a) ---> a' $ b\n  using AnyReasoning.\nProof.\n  intros HΓ wfa wfa' wfb mfb.\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H0\". mlIntro \"H1\".\n  mlRewriteBy \"H1\" at 1.\n  { assumption. }\n  { apply mu_free_in_path.\n    simpl.\n  assumption.\n  }\n  mlExactn 0.\nDefined.\n\nLemma patt_equal_implies_iff\n  {Σ : Signature} {syntax : Syntax} (φ1 φ2 : Pattern) (Γ : Theory) (i : ProofInfo) x :\n  theory ⊆ Γ ->\n  x ∉ (free_evars φ1 ∪ free_evars φ2) ->\n  ProofInfoLe\n    (ExGen := {[ev_x; x]},\n      SVSubst := ∅, KT := false, AKT := false) i ->\n  well_formed φ1 ->\n  well_formed φ2 ->\n  Γ ⊢i φ1 =ml φ2 using i ->\n  Γ ⊢i (φ1 <---> φ2) using i.\nProof.\n  intros HΓ Hx pile wfφ1 wfφ2 H.\n  unfold \"=ml\" in H.\n  apply total_phi_impl_phi_meta with (Γ := Γ) (i := i) (x := x) in H.\n  { assumption. }\n  { assumption. }\n  { simpl. set_solver. }\n  { wf_auto2. }\n  { simpl.\n    replace (free_evars φ1 ∪ free_evars φ2 ∪ ∅ ∪ ∅\n    ∪ (free_evars φ2 ∪ free_evars φ1 ∪ ∅) ∪ ∅)\n    with (free_evars φ1 ∪ free_evars φ2)\n    by set_solver.\n    apply pile.\n  }\nDefined.\n\n\nLemma disj_equals_greater_1_meta {Σ : Signature} {syntax : Syntax} Γ φ₁ φ₂ i x:\n  theory ⊆ Γ ->\n  x ∉ free_evars φ₁ ∪ free_evars φ₂ ->\n  ProofInfoLe\n       (ExGen := {[ev_x; x]},\n        SVSubst := ∅, KT := false, AKT := false) i ->\n  well_formed φ₁ ->\n  well_formed φ₂ ->\n  Γ ⊢i φ₁ ⊆ml φ₂ using i ->\n  Γ ⊢i (φ₁ or φ₂) =ml φ₂ using i.\nProof.\n  intros HΓ Hx pile wfφ₁ wfφ₂ Hsub.\n  apply patt_iff_implies_equal; try_wfauto2.\n  { eapply pile_trans;[|apply pile].\n    try_solve_pile.\n  }\n  apply pf_iff_split; try_wfauto2.\n  + toMLGoal.\n    { wf_auto2. }\n    mlIntro \"H0\". mlDestructOr \"H0\".\n    * apply total_phi_impl_phi_meta with (x := x) in Hsub;[ | auto |assumption|try_wfauto2|idtac].\n      { fromMLGoal. apply Hsub. }\n      { simpl. apply pile. }\n    * fromMLGoal. useBasicReasoning; apply A_impl_A;try_wfauto2.\n  + toMLGoal.\n    { wf_auto2. }\n    mlIntro \"H0\". mlRight.\n    fromMLGoal. \n    useBasicReasoning.\n    apply A_impl_A; try_wfauto2.\nDefined.\n\nLemma def_not_phi_impl_not_total_phi {Σ : Signature} {syntax : Syntax} Γ φ:\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i ⌈ ! φ ⌉ ---> ! ⌊ φ ⌋ using BasicReasoning.\nProof.\n  intros HΓ wfφ.\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H0\".\n  unfold patt_total. (* TODO need an [mlUnfold in _] tactic *)\n  unfold patt_not.\n  mlIntro \"H1\".\n  mlApply \"H1\".\n  mlExact \"H0\".\nDefined.\n\nLemma def_def_phi_impl_def_phi\n  {Σ : Signature} {syntax : Syntax} {Γ : Theory} (φ : Pattern) x :\n  theory ⊆ Γ ->\n  x ∉ free_evars φ ->\n  well_formed φ ->\n    Γ ⊢i ⌈ ⌈ φ ⌉ ⌉ ---> ⌈ φ ⌉\n  using \n    (ExGen := {[ev_x; x]},\n     SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ Hx wfφ.\n  eapply (cast_proof').\n  { \n    remember (ctx_app_r (patt_sym (Definedness_Syntax.inj definedness)) box ltac:(wf_auto2)) as AC1.\n    remember (ctx_app_r (patt_sym (Definedness_Syntax.inj definedness)) AC1 ltac:(wf_auto2)) as AC2.\n    replace (⌈ ⌈ φ ⌉ ⌉) with (subst_ctx AC2 φ) by (subst; reflexivity).\n    subst. reflexivity.\n  }\n  gapply in_context_impl_defined.\n  {\n    simpl. try_solve_pile.\n  }\n  { exact HΓ. }\n  { set_solver. }\n  { exact wfφ. }\nDefined.\n\nLemma bott_not_defined {Σ : Signature} {syntax : Syntax} Γ :\n  Γ ⊢i ! ⌈ ⊥ ⌉ using BasicReasoning.\nProof.\n  apply Prop_bott_right.\n  { wf_auto2. }\nDefined.\n\nLemma not_def_phi_impl_not_phi {Σ : Signature} {syntax : Syntax} Γ φ x :\n  theory ⊆ Γ ->\n  x ∉ free_evars φ ->\n  well_formed φ ->\n  Γ ⊢i ! ⌈ φ ⌉ ---> ! φ\n  using \n  (ExGen := {[ev_x; x]},\n   SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ Hx wfφ.\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H0\".\n  mlIntro \"H1\".\n  mlApply \"H0\".\n  mlClear \"H0\".\n  mlApplyMeta phi_impl_defined_phi; auto. mlExact \"H1\".\nDefined.\n\nLemma tot_phi_impl_tot_def_phi {Σ : Signature} {syntax : Syntax} Γ φ x :\n  theory ⊆ Γ ->\n  x ∉ free_evars φ ->\n  well_formed φ ->\n  Γ ⊢i ⌊ φ ⌋ ---> ⌊ ⌈ φ ⌉ ⌋\n  using \n     (ExGen := {[ev_x; x]},\n      SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ Hx wfφ.\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H0\".\n  mlIntro \"H1\".\n  mlApply \"H0\".\n  mlClear \"H0\".\n  fromMLGoal.\n  gapply Framing_right.\n  { apply pile_refl. }\n  { wf_auto2. }\n  {\n    try_solve_pile.\n  }\n  apply not_def_phi_impl_not_phi; assumption.\nDefined.\n\nLemma def_of_pred_impl_pred {Σ : Signature} {syntax : Syntax} Γ ψ :\n  theory ⊆ Γ ->\n  well_formed ψ ->\n  Γ ⊢i (ψ =ml patt_bott) or (ψ =ml patt_top) using AnyReasoning ->\n  Γ ⊢i ⌈ ψ ⌉ ---> ψ using AnyReasoning.\nProof.\n  intros HΓ wfψ H.\n  toMLGoal.\n  {wf_auto2. }\n  mlAdd H as \"H0\".\n  mlDestructOr \"H0\" as \"H1\" \"H1\".\n  - mlRewriteBy \"H1\" at 2.\n    { exact HΓ. }\n    { simpl. unfold mu_in_evar_path. cbn. case_match;[reflexivity|].\n      case_match;[|contradiction].\n      rewrite Nat.max_0_r in H0.\n      rewrite maximal_mu_depth_to_0 in H0.\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          simpl. set_solver.\n        }\n      }\n      inversion H0.\n    }\n    mlRewriteBy \"H1\" at 1.\n    { exact HΓ. }\n    { simpl.\n    unfold mu_in_evar_path. cbn. case_match;[reflexivity|].\n      case_match;[|contradiction].\n      simpl in H0. inversion H0.\n    }\n    mlClear \"H1\".\n    fromMLGoal.\n    aapply bott_not_defined.\n  - mlRewriteBy \"H1\" at 2.\n    { exact HΓ. }\n    { simpl. unfold mu_in_evar_path. cbn. case_match;[reflexivity|].\n      case_match;[|contradiction].\n      rewrite Nat.max_0_r in H0.\n      rewrite maximal_mu_depth_to_0 in H0.\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          simpl. set_solver.\n        }\n      }\n      inversion H0.\n    }\n    mlClear \"H1\".\n    unfold patt_top. mlIntro. mlIntro. mlExactn 1.\nDefined.\n\n(* TODO need this non-meta *)\nLemma subseteq_antisym_meta {Σ : Signature} {syntax : Syntax} Γ φ₁ φ₂:\n  theory ⊆ Γ ->\n  well_formed φ₁ ->\n  well_formed φ₂ ->\n  Γ ⊢i (φ₁ ⊆ml φ₂) and (φ₂ ⊆ml φ₁) using AnyReasoning ->\n  Γ ⊢i φ₁ =ml φ₂ using AnyReasoning.\nProof.\n  intros HΓ wfφ₁ wfφ₂ H.\n  unfold \"=ml\".\n  apply phi_impl_total_phi_meta.\n  { wf_auto2. }\n  { apply pile_any. }\n  toMLGoal.\n  { wf_auto2. }\n  mlAdd H as \"H0\".\n  mlDestructAnd \"H0\" as \"H1\" \"H2\".\n  remember (fresh_evar (φ₁ $ φ₂)) as x.\n\n  epose proof (Htmp := (total_phi_impl_phi Γ _ x HΓ _)).\n  apply useGenericReasoning with (i := AnyReasoning) in Htmp.\n  2: { apply pile_any. }\n  mlApplyMetaRaw Htmp in \"H1\".\n  clear Htmp.\n\n  epose proof (Htmp := (total_phi_impl_phi Γ _ x HΓ _)).\n  apply useGenericReasoning with (i := AnyReasoning) in Htmp.\n  2: { apply pile_any. }\n  unshelve (mlApplyMetaRaw Htmp in \"H2\"). 2-3: wf_auto2.\n  clear Htmp.\n  mlSplitAnd.\n  - mlExact \"H1\".\n  - mlExact \"H2\".\n  Unshelve.\n  all: wf_auto2.\n  exact (set_evar_fresh_is_fresh (φ₁ $ φ₂)).\n  pose proof (set_evar_fresh_is_fresh (φ₁ $ φ₂)).\n  unfold evar_is_fresh_in in H. set_solver.\nDefined.\n\nLemma propagate_membership_conjunct_1 {Σ : Signature} {syntax : Syntax}\n    Γ AC x φ₁ φ₂ :\n  theory ⊆ Γ ->\n  well_formed φ₁ ->\n  well_formed φ₂ ->\n  Γ ⊢i (subst_ctx AC (φ₁ and ((patt_free_evar x) ∈ml φ₂))) ---> ((patt_free_evar x) ∈ml φ₂)\n  using AnyReasoning.\nProof.\n  intros HΓ wfφ₁ wfφ₂.\n  unfold patt_in.\n  eapply syllogism_meta.\n  1,3 : wf_auto2.\n  2: apply Framing.\n  2: { apply pile_any. }\n  2: useBasicReasoning; apply pf_conj_elim_r.\n  1-3: wf_auto2.\n  eapply syllogism_meta.\n  1,3: wf_auto2.\n  2: gapply in_context_impl_defined.\n  3: exact HΓ.\n  4: wf_auto2.\n  2: apply pile_any.\n  1: wf_auto2.\n  instantiate (1 :=  evar_fresh (elements ({[x]} ∪ free_evars φ₂ ∪ AC_free_evars AC))).\n  { simpl. eapply not_elem_of_larger_impl_not_elem_of.\n    2: apply set_evar_fresh_is_fresh'. set_solver. }\n  gapply def_def_phi_impl_def_phi.\n  { apply pile_any. }\n  { assumption. }\n  { instantiate (1 := evar_fresh (elements ({[x]} ∪ free_evars φ₂))). \n    simpl.  eapply not_elem_of_larger_impl_not_elem_of.\n    2: apply set_evar_fresh_is_fresh'. set_solver. }\n  { wf_auto2. }\nDefined.\n\n\nLemma ceil_monotonic {Σ : Signature} {syntax : Syntax} Γ φ₁ φ₂ i :\n  theory ⊆ Γ ->\n  well_formed φ₁ ->\n  well_formed φ₂ ->\n  Γ ⊢i φ₁ ---> φ₂ using i ->\n  Γ ⊢i ⌈ φ₁ ⌉ ---> ⌈ φ₂ ⌉ using i.\nProof.\n  intros HΓ wfφ₁ wfφ₂ H.\n  unshelve (eapply Framing_right).\n  { wf_auto2. }\n  { try_solve_pile. }\n  exact H.\nDefined.\n\nLemma floor_monotonic {Σ : Signature} {syntax : Syntax} Γ φ₁ φ₂ i :\n  theory ⊆ Γ ->\n  well_formed φ₁ ->\n  well_formed φ₂ ->\n  Γ ⊢i φ₁ ---> φ₂ using i ->\n  Γ ⊢i ⌊ φ₁ ⌋ ---> ⌊ φ₂ ⌋ using i.\nProof.\n  intros HΓ wfφ₁ wfφ₂ H.\n  unfold patt_total.\n  apply BasicProofSystemLemmas.modus_tollens.\n  apply ceil_monotonic.\n  { assumption. }\n  { wf_auto2. }\n  { wf_auto2. }\n  apply BasicProofSystemLemmas.modus_tollens.\n  exact H.\nDefined.\n\nLemma double_not_ceil_alt {Σ : Signature} {syntax : Syntax} Γ φ i :\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i ( ⌈ ! ⌈ φ ⌉ ⌉ ---> (! ⌈ φ ⌉)) using i ->\n  Γ ⊢i ( ⌈ φ ⌉ ---> ! ( ⌈ ! ⌈ φ ⌉ ⌉)) using i.\nProof.\n  intros HΓ wfφ H.\n  toMLGoal.\n  { wf_auto2. }\n  mlRewrite (useBasicReasoning i (not_not_iff Γ (⌈ φ ⌉) ltac:(wf_auto2))) at 1.\n  fromMLGoal.\n  apply BasicProofSystemLemmas.modus_tollens.\n  exact H.\nDefined.\n\n\nLemma membership_imp {Σ : Signature} {syntax : Syntax} Γ x φ₁ φ₂:\n  theory ⊆ Γ ->\n  well_formed φ₁ ->\n  well_formed φ₂ ->\n  Γ ⊢i (patt_free_evar x ∈ml (φ₁ ---> φ₂)) <---> ((patt_free_evar x ∈ml φ₁) ---> (patt_free_evar x ∈ml φ₂))\n  using (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ₁ wfφ₂.\n\n  toMLGoal.\n  { wf_auto2. }\n  mlRewrite (useBasicReasoning (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false) (@impl_iff_notp_or_q Σ Γ φ₁ φ₂ ltac:(wf_auto2) ltac:(wf_auto2))) at 1.\n  mlRewrite (useBasicReasoning (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false) (@membership_or_iff Σ syntax Γ x (! φ₁) φ₂ ltac:(wf_auto2) ltac:(wf_auto2) HΓ)) at 1.\n  mlRewrite (@membership_not_iff Σ syntax Γ φ₁ x ltac:(wf_auto2) HΓ) at 1.\n  mlRewrite <- (useBasicReasoning (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false) (@impl_iff_notp_or_q Σ Γ (patt_free_evar x ∈ml φ₁) (patt_free_evar x ∈ml φ₂) ltac:(wf_auto2) ltac:(wf_auto2))) at 1.\n  fromMLGoal.\n  useBasicReasoning.\n  apply pf_iff_equiv_refl.\n  { wf_auto2. }\nDefined.\n\nLemma ceil_propagation_exists_1 {Σ : Signature} {syntax : Syntax} Γ φ:\n  theory ⊆ Γ ->\n  well_formed (ex, φ) ->\n  Γ ⊢i (⌈ ex, φ ⌉) ---> (ex, ⌈ φ ⌉)\n  using BasicReasoning.\nProof.\n  intros HΓ wfφ.\n  apply Prop_ex_right.\n  { wf_auto2. }\n  { wf_auto2. }\nDefined.\n\n(* I think that lemmas like this one should not generate fresh variable themselves,\n   but should be given them (ala \"dependency injection\").\n   We can always have a wrapper that generates the fresh variables.\n   But a concrete solution for this is for another PR.\n   What I want to avoid is annotations that contain fresh variable generation.\n   Maybe lemmas could be parameterized by a vector of a particular length\n   of distinct fresh variables. We could have a type for that.\n   Like, there would be a parameter\n   [fresh_vars : n_fresh_vars n [φ1; φ2]].\n   And maybe the whole Definedness module should be parameterized by a variable\n   which is used in the definedness axiom. This way, every lemma will be parameterized\n   twice - or, in general, multiple times.\n\n   This lemma is interesting in that the fresh variable that it generates\n   may be the same as the fresh variable that is used for the definedness axiom.\n   But in general, we may want to have a disjoint set of fresh variables...\n *)\nLemma ceil_propagation_exists_2 {Σ : Signature} {syntax : Syntax} Γ φ:\n  theory ⊆ Γ ->\n  well_formed (ex, φ) ->\n  Γ ⊢i (ex, ⌈ φ ⌉) ---> (⌈ ex, φ ⌉)\n  using  (ExGen := {[ev_x; fresh_evar φ]}, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n\n  remember (fresh_evar φ) as x.\n  replace (⌈ φ ⌉) with (⌈ φ ⌉^{evar: 0 ↦ x}^{{evar: x ↦ 0}}).\n  2: {\n    rewrite evar_quantify_evar_open.\n       {\n         pose proof (set_evar_fresh_is_fresh φ).\n         unfold evar_is_fresh_in in H.\n         simpl. set_solver.\n       }\n       { wf_auto2. }\n       reflexivity.\n  }\n  apply BasicProofSystemLemmas.Ex_gen.\n  { try_solve_pile. }\n  {  simpl.\n        pose proof (Hfr := set_evar_fresh_is_fresh φ).\n        unfold evar_is_fresh_in in Hfr.\n        simpl. set_solver.\n  }\n  mlSimpl.\n  apply ceil_monotonic.\n  { assumption. }\n  { wf_auto2. }\n  { wf_auto2. }\n  useBasicReasoning.\n  apply BasicProofSystemLemmas.Ex_quan.\n  { wf_auto2. }\nDefined.\n\nLemma ceil_propagation_exists_iff {Σ : Signature} {syntax : Syntax} Γ φ:\n  theory ⊆ Γ ->\n  well_formed (ex, φ) ->\n  Γ ⊢i (⌈ ex, φ ⌉) <---> (ex, ⌈ φ ⌉)\n  using  (ExGen := {[ev_x; fresh_evar φ]}, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  apply pf_iff_split.\n  { wf_auto2. }\n  { wf_auto2. }\n  - useBasicReasoning. apply ceil_propagation_exists_1; assumption.\n  - apply ceil_propagation_exists_2; assumption.\nDefined.\n\nLemma membership_exists {Σ : Signature} {syntax : Syntax} Γ x φ:\n  theory ⊆ Γ ->\n  well_formed (ex, φ) ->\n  Γ ⊢i (patt_free_evar x ∈ml (ex, φ)) <---> (ex, patt_free_evar x ∈ml φ)\n  using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  unfold \"∈ml\".\n  toMLGoal.\n  { wf_auto2. }\n  mlRewrite <- (@liftProofInfoLe Σ Γ _ (ExGen := {[ev_x; fresh_evar (patt_free_evar x and φ)]}, SVSubst := ∅, KT := false, AKT := false) (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) ltac:(try_solve_pile) (@ceil_propagation_exists_iff Σ syntax Γ (patt_free_evar x and φ) HΓ ltac:(wf_auto2))) at 1.\n  fromMLGoal.\n  assert (Htmp: Γ ⊢i (patt_free_evar x and ex, φ) <---> (ex, (patt_free_evar x and φ)) using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false)).\n  { (* prenex-exists-and *)\n    toMLGoal.\n    { wf_auto2. }\n    mlRewrite (useBasicReasoning (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) (patt_and_comm Γ (patt_free_evar x) (ex, φ) ltac:(wf_auto2) ltac:(wf_auto2))) at 1.\n    mlRewrite <- (@liftProofInfoLe Σ Γ _ (ExGen := {[fresh_evar (φ and patt_free_evar x)]}, SVSubst := ∅, KT := false, AKT := false) (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) ltac:(try_solve_pile) (@prenex_exists_and_iff Σ Γ φ (patt_free_evar x) ltac:(wf_auto2) ltac:(wf_auto2))) at 1.\n    remember (evar_fresh (elements ({[x]} ∪ (free_evars φ)))) as y.\n    mlSplitAnd; fromMLGoal.\n    - apply (strip_exists_quantify_l Γ y).\n      { subst y. simpl.\n        eapply not_elem_of_larger_impl_not_elem_of.\n        2: { apply set_evar_fresh_is_fresh'. }\n        clear. set_solver.\n      }\n      { wf_auto2. }\n      apply (strip_exists_quantify_r Γ y).\n      { subst y. simpl.\n        eapply not_elem_of_larger_impl_not_elem_of.\n        2: { apply set_evar_fresh_is_fresh'. }\n        clear. set_solver.\n      }\n      { wf_auto2. }\n      apply ex_quan_monotone.\n      { try_solve_pile. }\n      mlSimpl.\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro \"H0\". mlDestructAnd \"H0\" as \"H1\" \"H2\". mlSplitAnd.\n      + mlExact \"H2\".\n      + mlExact \"H1\".\n    - apply (strip_exists_quantify_l Γ y).\n      { subst y. simpl.\n        eapply not_elem_of_larger_impl_not_elem_of.\n        2: { apply set_evar_fresh_is_fresh'. }\n        clear. set_solver.\n      }\n      { wf_auto2. }\n      apply (strip_exists_quantify_r Γ y).\n      { subst y. simpl.\n        eapply not_elem_of_larger_impl_not_elem_of.\n        2: { apply set_evar_fresh_is_fresh'. }\n        clear. set_solver.\n      }\n      { wf_auto2. }\n      apply ex_quan_monotone.\n      { try_solve_pile. }\n      mlSimpl.\n      toMLGoal.\n      { wf_auto2. }\n      (* TODO: Isn't this just a commutativity of [patt_and]? *)\n      mlIntro \"H0\".\n      mlDestructAnd \"H0\" as \"H1\" \"H2\".\n      mlSplitAnd.\n      + mlExact \"H2\".\n      + mlExact \"H1\".\n  }\n  toMLGoal.\n  { wf_auto2. }\n  mlRewrite Htmp at 1.\n  fromMLGoal.\n  aapply pf_iff_equiv_refl.\n  { try_solve_pile. }\n  { wf_auto2. }\nDefined.\n\n\nLemma membership_symbol_ceil_aux_aux_0 {Σ : Signature} {syntax : Syntax} Γ x φ:\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i ((⌈ patt_free_evar x and φ ⌉) ---> (⌊ ⌈ patt_free_evar x and φ ⌉  ⌋))\n  using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  unfold patt_total.\n  eapply syllogism_meta.\n  { wf_auto2. }\n  2: { wf_auto2. }\n  3: {\n    apply BasicProofSystemLemmas.modus_tollens.\n    {\n      apply ceil_monotonic.\n      { exact HΓ. }\n      { wf_auto2. }\n      2: {\n        gapply membership_not_2.\n        { try_solve_pile. }\n        { wf_auto2. }\n        { exact HΓ. }\n      }\n      { wf_auto2. }\n    }\n  }\n  { wf_auto2. }\n  toMLGoal.\n  { wf_auto2. }\n\n  mlRewrite (useBasicReasoning (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) (not_not_iff Γ (⌈patt_free_evar x and φ ⌉) ltac:(wf_auto2))) at 1.\n  fold (! ⌈ patt_free_evar x and φ ⌉ or ! ⌈ patt_free_evar x ∈ml (! φ) ⌉).\n  mlRewrite (useBasicReasoning (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) (not_not_iff Γ (! ⌈ patt_free_evar x and φ ⌉ or ! ⌈ patt_free_evar x ∈ml (! φ) ⌉) ltac:(wf_auto2))) at 1.\n  fold ((⌈ patt_free_evar x and φ ⌉ and ⌈ patt_free_evar x ∈ml (! φ) ⌉)).\n  unfold \"∈ml\".\n  fromMLGoal.\n  eapply cast_proof'.\n  {\n    replace (⌈ patt_free_evar x and φ ⌉)\n            with (subst_ctx AC_patt_defined (patt_free_evar x and φ))\n                 by reflexivity.\n    replace (⌈ ⌈ patt_free_evar x and ! φ ⌉ ⌉)\n            with (subst_ctx (ctx_app_r ((patt_sym (Definedness_Syntax.inj definedness))) AC_patt_defined ltac:(wf_auto2)) (patt_free_evar x and ! φ))\n      by reflexivity.\n    reflexivity.\n  }\n  gapply Singleton_ctx.\n  { try_solve_pile. }\n  { exact wfφ. }\n  all: try_solve_pile.\nDefined.\n\nLemma ceil_compat_in_or {Σ : Signature} {syntax : Syntax} Γ φ₁ φ₂:\n  theory ⊆ Γ ->\n  well_formed φ₁ ->\n  well_formed φ₂ ->\n  Γ ⊢i ( (⌈ φ₁ or φ₂ ⌉) <---> (⌈ φ₁ ⌉ or ⌈ φ₂ ⌉))\n  using (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ₁ wfφ₂.\n  toMLGoal.\n  { wf_auto2. }\n  mlSplitAnd; mlIntro \"H0\".\n  - mlApplyMeta (useBasicReasoning (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false) (Prop_disj_right Γ φ₁ φ₂ (patt_sym (Definedness_Syntax.inj definedness)) ltac:(wf_auto2) ltac:(wf_auto2) ltac:(wf_auto2) )).\n    mlExact \"H0\".\n  - mlDestructOr \"H0\" as \"H1\" \"H2\"; fromMLGoal.\n    + unshelve (eapply Framing_right).\n      * wf_auto2.\n      * try_solve_pile.\n      * toMLGoal. wf_auto2. mlIntro \"H0'\". mlLeft. mlExact \"H0'\".\n    + unshelve (eapply Framing_right).\n      * wf_auto2.\n      * try_solve_pile.\n      * toMLGoal. wf_auto2. mlIntro \"H0'\". mlRight. mlExact \"H0'\".\nDefined.\n\nLemma membership_symbol_ceil_aux_0 {Σ : Signature} {syntax : Syntax} Γ x y φ:\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i (⌈ patt_free_evar x and φ ⌉) ---> ⌈ patt_free_evar y and ⌈ patt_free_evar x and φ ⌉ ⌉\n  using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H0\".\n  mlApplyMeta (membership_symbol_ceil_aux_aux_0 Γ x φ HΓ wfφ) in \"H0\".\n  fromMLGoal.\n  unfold patt_total.\n  fold (⌈ ! ⌈ patt_free_evar x and φ ⌉ ⌉ or ⌈ patt_free_evar y and ⌈ patt_free_evar x and φ ⌉ ⌉).\n  toMLGoal.\n  { wf_auto2. }\n  mlRewrite <- (@liftProofInfoLe _ _ _ (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false) (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) ltac:(try_solve_pile) (ceil_compat_in_or Γ (! ⌈ patt_free_evar x and φ ⌉) (patt_free_evar y and ⌈ patt_free_evar x and φ ⌉) HΓ ltac:(wf_auto2) ltac:(wf_auto2))) at 1.\n\n  unshelve (mlApplyMetaRaw (ceil_monotonic Γ\n  (patt_free_evar y)\n  (! ⌈ patt_free_evar x and φ ⌉ or patt_free_evar y and ⌈ patt_free_evar x and φ ⌉)\n  (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) HΓ ltac:(wf_auto2) ltac:(wf_auto2) _)).\n  {\n\n    assert (Helper: forall φ₁ φ₂, well_formed φ₁ -> well_formed φ₂ -> Γ ⊢i (! φ₁ or φ₂) ---> (! φ₁ or (φ₂ and φ₁)) using (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false)).\n    {\n      intros φ₁ φ₂ wfφ₁ wfφ₂.\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro \"H0\".\n      mlAdd (useBasicReasoning (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false) (A_or_notA Γ φ₁ ltac:(wf_auto2))) as \"H1\".\n      mlDestructOr \"H0\" as \"H0'\" \"H0'\"; mlDestructOr \"H1\" as \"H1'\" \"H1'\".\n      - mlExFalso.\n        mlApply \"H0'\". mlExact \"H1'\".\n      - mlLeft. mlExactn 0.\n      - mlRight.\n        mlSplitAnd.\n        + mlExact \"H0'\".\n        + mlExact \"H1'\".\n      - mlLeft.\n        mlExact \"H1'\". \n    }\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro \"H0\".\n    mlApplyMeta Helper.\n    mlRight.\n    mlExact \"H0\".\n  }\n  fromMLGoal.\n  gapply defined_evar.\n  { try_solve_pile. }\n  { exact HΓ. }\nDefined.\n\n\nLemma membership_symbol_ceil_left_aux_0 {Σ : Signature} {syntax : Syntax} Γ φ:\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i φ ---> (ex, ⌈ b0 and φ ⌉)\n  using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  apply membership_elimination with (x := fresh_evar (φ ---> (ex , ⌈ b0 and φ ⌉))).\n  { solve_fresh. }\n  { try_solve_pile. }\n  { wf_auto2. }\n  { assumption. }\n  remember (fresh_evar φ) as x.\n  replace (b0 ∈ml (φ ---> ex , ⌈ b0 and φ ⌉))\n    with ((b0 ∈ml (φ ---> ex , ⌈ b0 and φ ⌉))^{evar: 0 ↦ x}^{{evar: x ↦ 0}}).\n  2: { rewrite evar_quantify_evar_open.\n       {\n         pose proof (set_evar_fresh_is_fresh φ).\n         unfold evar_is_fresh_in in H.\n         simpl. set_solver.\n       }\n       wf_auto2.\n       reflexivity.\n  }\n\n  apply universal_generalization.\n  { try_solve_pile. }\n  { wf_auto2. }\n  unfold evar_open. mlSimpl. simpl.\n  rewrite bevar_subst_not_occur.\n  { wf_auto2. }\n  rewrite bevar_subst_not_occur.\n  { wf_auto2. }\n  toMLGoal.\n  { wf_auto2. }\n  pose proof (Htmp := @liftProofInfoLe Σ Γ _ (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false) (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) ltac:(try_solve_pile) (@membership_imp Σ syntax Γ x φ (ex, ⌈ b0 and φ ⌉) HΓ ltac:(wf_auto2) ltac:(wf_auto2))).\n  mlRewrite Htmp at 1. clear Htmp.\n  pose proof (Htmp := @liftProofInfoLe Σ Γ _ (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) ltac:(try_solve_pile) (@membership_exists Σ syntax Γ x (⌈ b0 and φ ⌉) HΓ ltac:(wf_auto2))).\n  mlRewrite Htmp at 1.\n  mlIntro \"H0\".\n  remember (fresh_evar φ) as y.\n  mlApplyMeta (useBasicReasoning (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) (Ex_quan Γ (patt_free_evar x ∈ml ⌈ b0 and φ ⌉) y ltac:(wf_auto2))).\n  unfold instantiate. mlSimpl. simpl.\n  rewrite bevar_subst_not_occur.\n  { wf_auto2. }\n\n  unshelve (mlApplyMetaRaw (liftProofInfoLe _ _ _ _ (membership_symbol_ceil_aux_0 Γ y x φ HΓ wfφ))).\n  { try_solve_pile. }\n  subst y. subst x.\n  mlExact \"H0\".\n  all: try_solve_pile.\nDefined.\n\nLemma ceil_and_x_ceil_phi_impl_ceil_phi {Σ : Signature} {syntax : Syntax} Γ (φ : Pattern) x:\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i ( (⌈ patt_free_evar x and ⌈ φ ⌉ ⌉) ---> (⌈ φ ⌉))\n  using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  eapply syllogism_meta.\n  { wf_auto2. }\n  2: { wf_auto2. }\n  3: {\n    gapply def_def_phi_impl_def_phi.\n    { shelve. (* B is not known here *) }\n    { assumption. }\n    { shelve. (* B is not known here *) }\n    { assumption. }\n  }\n  { wf_auto2. }\n  apply ceil_monotonic.\n  { exact HΓ. }\n  { wf_auto2. }\n  { wf_auto2. }\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H0\".\n  mlDestructAnd \"H0\" as \"H1\" \"H2\".\n  mlExact \"H2\".\nUnshelve.\n  exact (fresh_evar φ).\n  try_solve_pile.\n  solve_fresh.\nDefined.\n\nLemma membership_monotone {Σ : Signature} {syntax : Syntax} Γ (φ₁ φ₂ : Pattern) x i:\n  theory ⊆ Γ ->\n  well_formed φ₁ ->\n  well_formed φ₂ ->\n  Γ ⊢i (φ₁ ---> φ₂) using i ->\n  Γ ⊢i (patt_free_evar x ∈ml φ₁) ---> (patt_free_evar x ∈ml φ₂) using i.\nProof.\n  intros HΓ wfφ₁ wfφ₂ H.\n  unfold patt_in.\n  apply ceil_monotonic.\n  { exact HΓ. }\n  { wf_auto2. }\n  { wf_auto2. }\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H0\".\n  mlDestructAnd \"H0\" as \"H1\" \"H2\".\n  mlSplitAnd.\n  - mlExact \"H1\".\n  - mlApplyMetaRaw H in \"H2\".\n    mlExact \"H2\".\nDefined.\n\nLemma membership_symbol_ceil_left {Σ : Signature} {syntax : Syntax} Γ φ x:\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i (patt_free_evar x ∈ml ⌈ φ ⌉) ---> (ex, (patt_bound_evar 0 ∈ml φ))\n  using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  eapply syllogism_meta.\n  { wf_auto2. }\n  2: { wf_auto2. }\n  2: {\n    apply membership_monotone.\n    { exact HΓ. }\n    { wf_auto2. }\n    2: {\n      apply ceil_monotonic.\n      { exact HΓ. }\n      { assumption. }\n      2: {\n        apply membership_symbol_ceil_left_aux_0.\n        { wf_auto2. }\n        { wf_auto2. }\n      }\n      wf_auto2.\n    }\n    wf_auto2.\n  }\n  { wf_auto2. }\n\n  eapply syllogism_meta.\n  { wf_auto2. }\n  2: { wf_auto2. }\n  2: {\n    apply membership_monotone.\n    { exact HΓ. }\n    { wf_auto2. }\n    2: {\n      gapply ceil_propagation_exists_1.\n      { try_solve_pile. }\n      { exact HΓ. }\n      { wf_auto2. }\n    }\n    { wf_auto2. }\n  }\n  { wf_auto2. }\n\n  remember (evar_fresh (elements ({[x]} ∪ (free_evars φ)))) as y.\n  eapply syllogism_meta.\n  { wf_auto2. }\n  2: { wf_auto2. }\n  2: {\n    apply membership_monotone.\n    { exact HΓ. }\n    { wf_auto2. }\n    2: {\n      eapply cast_proof'.\n      {\n        rewrite -[⌈ ⌈ b0 and φ ⌉ ⌉](evar_quantify_evar_open y 0).\n        { simpl.\n          pose proof (Hfr := set_evar_fresh_is_fresh' ({[x]} ∪ (free_evars φ))).\n          subst y. clear -Hfr. set_solver.\n        }\n        simpl. split_and!; auto.\n        unfold well_formed, well_formed_closed in wfφ. destruct_and!.\n        eapply well_formed_closed_ex_aux_ind; try eassumption; lia.\n        reflexivity.\n      }\n      apply ex_quan_monotone.\n      { try_solve_pile. }\n      {\n        unfold evar_open. mlSimpl. simpl.\n        rewrite bevar_subst_not_occur.\n        { wf_auto2. }\n        gapply def_def_phi_impl_def_phi.\n        { shelve. }\n        { exact HΓ. }\n        { shelve. }\n        { wf_auto2. }\n      }\n    }\n    {\n      unfold exists_quantify.\n      unfold well_formed. split_and!.\n      { wf_auto2; case_match; wf_auto2. }\n      unfold well_formed_closed. split_and!.\n      { simpl; case_match; wf_auto2. }\n      { simpl; case_match; try congruence. simpl.\n        wf_auto2.\n      }\n    }\n  }\n  {\n      unfold exists_quantify.\n      unfold well_formed. split_and!.\n      { wf_auto2; case_match; wf_auto2. }\n      unfold well_formed_closed. split_and!.\n      { simpl; case_match; wf_auto2. }\n      { simpl; case_match; try congruence. simpl.\n        wf_auto2.\n      }\n  }\n\n  toMLGoal.\n  {\n    unfold exists_quantify.\n    unfold well_formed. split_and!.\n    { wf_auto2; case_match; wf_auto2. }\n    unfold well_formed_closed. split_and!.\n    { simpl; case_match; wf_auto2. }\n    { simpl; case_match; try congruence. simpl.\n      split_and!; auto; wf_auto2.\n    }\n  }\n\n  unfold exists_quantify.\n  pose proof (Htmp := membership_exists Γ x (evar_quantify y 0 ⌈ patt_free_evar y and φ ⌉) HΓ).\n  feed specialize Htmp.\n  { \n      unfold exists_quantify.\n      unfold well_formed. split_and!.\n      { wf_auto2; case_match; wf_auto2. }\n      unfold well_formed_closed. split_and!.\n      { simpl; case_match; wf_auto2. }\n      { simpl; case_match; try congruence. simpl.\n        split_and!; auto; wf_auto2.\n      }\n  }\n  mlRewrite -> Htmp at 1. clear Htmp.\n\n  fromMLGoal.\n  case_match; try congruence.\n  rewrite evar_quantify_fresh.\n  { subst y. solve_fresh. }\n  fold (patt_not b0).\n  fold (patt_not (patt_not b0)).\n  fold (patt_not φ).\n  fold (! b0 or ! φ).\n  fold (!(! b0 or ! φ)).\n  fold (b0 and φ).\n  fold (patt_defined (b0 and φ)).\n  unfold patt_in.\n\n  apply (strip_exists_quantify_l Γ y).\n  { simpl.\n    pose proof (Hfr := set_evar_fresh_is_fresh' ({[x]} ∪ (free_evars φ))).\n    rewrite -Heqy in Hfr.\n    clear -Hfr.\n    set_solver.\n  }\n  { simpl. split_and!; auto; wf_auto2. }\n\n  apply (strip_exists_quantify_r Γ y).\n  { simpl.\n    pose proof (Hfr := @set_evar_fresh_is_fresh' Σ ({[x]} ∪ (free_evars φ))).\n    rewrite -Heqy in Hfr.\n    clear -Hfr.\n    set_solver.\n  }\n  { simpl. split_and!; auto; wf_auto2. }\n  apply ex_quan_monotone.\n  { try_solve_pile. }\n  unfold evar_open. mlSimpl. simpl.\n  rewrite bevar_subst_not_occur.\n  { wf_auto2. }\n\n  apply ceil_and_x_ceil_phi_impl_ceil_phi.\n  { exact HΓ. }\n  { wf_auto2. }\nUnshelve.\n  exact (fresh_evar (patt_free_evar y and φ)).\n  try_solve_pile.\n  solve_fresh.\nDefined.\n\n\nLemma membership_symbol_ceil_right_aux_0 {Σ : Signature} {syntax : Syntax} Γ φ:\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i (ex, (⌈ b0 and  φ ⌉ and b0)) ---> φ\n  using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  apply prenex_forall_imp.\n  1,2: wf_auto2.\n  { try_solve_pile. }\n  remember (fresh_evar (⌈ b0 and φ ⌉ and b0 ---> φ)) as x.\n  eapply cast_proof'.\n  {\n    rewrite -[HERE in (all, HERE)](evar_quantify_evar_open x 0).\n    { subst x. apply set_evar_fresh_is_fresh. }\n    unfold well_formed, well_formed_closed in wfφ. destruct_and!. simpl.\n    split_and!; auto.\n    1-2: eapply well_formed_closed_ex_aux_ind; try eassumption; lia.\n    reflexivity.\n  }\n  apply universal_generalization.\n  { try_solve_pile. }\n  { wf_auto2. }\n  assert (Htmp: forall (φ₁ φ₂ φ₃ : Pattern),\n             well_formed φ₁ ->\n             well_formed φ₂ ->\n             well_formed φ₃ ->\n             Γ ⊢i ((! (φ₁ and (φ₂ and !φ₃))) ---> ((φ₁ and φ₂) ---> φ₃)) using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false)).\n  {\n    intros φ₁ φ₂ φ₃ wfφ₁ wfφ₂ wfφ₃.\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro \"H0\".\n    mlIntro \"H1\".\n    mlDestructAnd \"H1\" as \"H2\" \"H3\".\n    mlApplyMetaRaw (useBasicReasoning _ (not_not_elim Γ φ₃ wfφ₃)).\n    mlIntro \"H4\".\n    mlApply \"H0\".\n    mlClear \"H0\".\n    mlSplitAnd.\n    { mlExact \"H2\". }\n    mlSplitAnd.\n    { mlExact \"H3\". }\n    { mlExact \"H4\". }\n  }\n  eapply MP.\n  2: apply Htmp.\n  all: fold bevar_subst.\n  2,3,4: wf_auto2.\n  mlSimpl. simpl.\n  rewrite bevar_subst_not_occur.\n  { wf_auto2. }\n  replace (⌈ patt_free_evar x and φ ⌉) with (subst_ctx AC_patt_defined (patt_free_evar x and φ)) by reflexivity.\n  replace (patt_free_evar x and ! φ) with (subst_ctx box (patt_free_evar x and ! φ)) by reflexivity.\n  gapply Singleton_ctx.\n  { try_solve_pile. }\n  exact wfφ.\nDefined.\n\nLemma membership_symbol_ceil_right {Σ : Signature} {syntax : Syntax} Γ φ x:\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i ((ex, (BoundVarSugar.b0 ∈ml φ)) ---> (patt_free_evar x ∈ml ⌈ φ ⌉))\n  using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  remember (evar_fresh (elements ({[x]} ∪ (free_evars φ)))) as y.\n  pose proof (Htmp := set_evar_fresh_is_fresh' ({[x]} ∪ free_evars φ)).\n  rewrite -Heqy in Htmp.\n  assert (x <> y).\n  { solve_fresh_neq. }\n\n  eapply syllogism_meta.\n  1,3: wf_auto2.\n  2: {\n    apply (strip_exists_quantify_l Γ y).\n    { simpl. clear -Htmp. set_solver. }\n    { simpl. split_and!; try reflexivity. wf_auto2. }\n    apply ex_quan_monotone.\n    { try_solve_pile. }\n    {\n      unfold evar_open. mlSimpl. simpl.\n      rewrite bevar_subst_not_occur.\n      { wf_auto2. }\n      eapply liftProofInfoLe.\n      2: apply membership_symbol_ceil_aux_0 with (y := x); assumption.\n      try_solve_pile.\n    }\n  }\n  { unfold exists_quantify. simpl. repeat case_match; try congruence; wf_auto2. }\n\n  eapply syllogism_meta.\n  3: wf_auto2.\n  1: { unfold exists_quantify. simpl. repeat case_match; try congruence; wf_auto2. }\n  2: {\n    apply pf_iff_proj2.\n    2: { unfold exists_quantify. simpl. repeat case_match; try congruence; wf_auto2. }\n    2: { \n      unfold exists_quantify. simpl.\n      repeat case_match; try congruence; try contradiction.\n      apply membership_exists.\n      { exact HΓ. }\n      { wf_auto2. }\n    }\n    { wf_auto2. }\n  }\n  { wf_auto2. }\n\n  eapply syllogism_meta.\n  1,3: wf_auto2.\n  2: {\n    apply membership_monotone.\n    { exact HΓ. }\n    { wf_auto2. }\n    2: {\n      apply (strip_exists_quantify_l Γ y).\n      { simpl.\n        rewrite evar_quantify_fresh.\n        { subst y. solve_fresh. }\n        set_solver.\n      }\n      { simpl. split_and!; try reflexivity. wf_auto2. }\n      apply ex_quan_monotone.\n      { try_solve_pile. }\n      {\n        eapply syllogism_meta.\n        1: wf_auto2.\n        3: {\n          unfold evar_open. mlSimpl. simpl.\n          rewrite bevar_subst_evar_quantify_free_evar.\n          { wf_auto2. }\n          apply membership_symbol_ceil_aux_0 with (y := y); assumption.\n        }\n        { wf_auto2. }\n        2: {\n          apply ceil_monotonic.\n          { exact HΓ. }\n          { wf_auto2. }\n          2: {\n            eapply pf_iff_proj1.\n            { wf_auto2. }\n            2: {\n              (* TODO I think we should have an easier way of applying commutativity of [and] *)\n              useBasicReasoning. apply patt_and_comm.\n              { wf_auto2. }\n              { wf_auto2. }\n            }\n            { wf_auto2. }\n          }\n          { wf_auto2. }\n        }\n        { wf_auto2. }\n      }\n    }\n    { unfold exists_quantify. simpl. repeat case_match; try congruence; wf_auto2. }\n  }\n  { unfold exists_quantify. simpl. repeat case_match; try congruence; wf_auto2. }\n\n  eapply syllogism_meta.\n  { unfold exists_quantify. simpl. repeat case_match; try congruence; wf_auto2. }\n  2: { wf_auto2. }\n  2: {\n    apply membership_monotone.\n    { exact HΓ. }\n    { unfold exists_quantify. simpl. repeat case_match; try congruence; wf_auto2. } \n    2: {\n      unfold exists_quantify.\n      simpl.\n      repeat case_match; try congruence.\n      rewrite evar_quantify_fresh.\n      { subst y. solve_fresh. }\n      gapply ceil_propagation_exists_2.\n      { try_solve_pile. }\n      { exact HΓ. }\n      { wf_auto2. }\n    }\n    { wf_auto2. }\n  }\n  { wf_auto2. }\n  apply membership_monotone.\n  { exact HΓ. }\n  { wf_auto2. }\n  { wf_auto2. }\n  apply ceil_monotonic.\n  { exact HΓ. }\n  { wf_auto2. }\n  { wf_auto2. }\n  unshelve eapply (liftProofInfoLe Γ _ (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) (membership_symbol_ceil_right_aux_0 Γ _ HΓ wfφ)).\n  try_solve_pile.\nDefined.\n\nLemma def_phi_impl_tot_def_phi {Σ : Signature} {syntax : Syntax} Γ φ :\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i ⌈ φ ⌉ ---> ⌊ ⌈ φ ⌉ ⌋\n  using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  unfold patt_total.\n  apply double_not_ceil_alt.\n  { assumption. }\n  { assumption. }\n  apply membership_elimination with (x := fresh_evar (⌈ ! ⌈ φ ⌉ ⌉ ---> ! ⌈ φ ⌉)).\n  { solve_fresh. }\n  { try_solve_pile. }\n  { wf_auto2. }\n  { assumption. }\n\n  remember (fresh_evar φ) as x.\n  eapply cast_proof'.\n  { \n    rewrite -[b0 ∈ml _](evar_quantify_evar_open x 0).\n    { subst x. solve_fresh. }\n    unfold well_formed, well_formed_closed in wfφ. destruct_and!.\n    simpl; split_and!; auto.\n    1-2: eapply well_formed_closed_ex_aux_ind; try eassumption; lia.\n    reflexivity.\n  }\n  apply universal_generalization.\n  { try_solve_pile. }\n  { wf_auto2. }\n  unfold evar_open. mlSimpl. simpl.\n  rewrite bevar_subst_not_occur.\n  { wf_auto2. }\n\n  toMLGoal.\n  { wf_auto2. }\n  pose proof (Htmp := @liftProofInfoLe Σ Γ _ (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false) (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) ltac:(try_solve_pile) (membership_imp Γ x (⌈ ! ⌈ φ ⌉ ⌉) (! ⌈ φ ⌉) HΓ ltac:(wf_auto2) ltac:(wf_auto2))).\n  mlRewrite Htmp at 1. clear Htmp.\n  mlIntro \"H0\".\n  mlApplyMeta (@membership_symbol_ceil_left Σ syntax Γ (! ⌈ φ ⌉) x HΓ ltac:(wf_auto2)) in \"H0\".\n  mlRewrite (@liftProofInfoLe Σ Γ _ (ExGen := {[ev_x; x]}, SVSubst := ∅, KT := false, AKT := false) (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) ltac:(try_solve_pile) (membership_not_iff Γ (⌈ φ ⌉) x ltac:(wf_auto2) HΓ)) at 1.\n\n  remember (evar_fresh (elements ({[x]} ∪ (free_evars φ)))) as y.\n  pose proof (Hfr := set_evar_fresh_is_fresh' ({[x]} ∪ (free_evars φ))).\n  eapply cast_proof_ml_hyps.\n  {\n    rewrite <- (evar_quantify_evar_open y 0 (b0 ∈ml (! ⌈ φ ⌉))).\n    2: { subst x y. solve_fresh. }\n    reflexivity.\n    unfold well_formed, well_formed_closed in wfφ. destruct_and!.\n    simpl; split_and!; auto.\n    eapply well_formed_closed_ex_aux_ind; try eassumption; lia.\n  }\n\n  assert (Htmp: Γ ⊢i (((b0 ∈ml (! ⌈ φ ⌉))^{evar: 0 ↦ y}) ---> ((! (b0 ∈ml ⌈ φ ⌉))^{evar: 0 ↦ y})) using (ExGen := {[y]}, SVSubst := ∅, KT := false, AKT := false)).\n  {\n    unfold evar_open. mlSimpl. simpl. gapply membership_not_1.\n    { try_solve_pile. }\n    { wf_auto2. }\n    exact HΓ.\n  }\n\n  mlApplyMeta (ex_quan_monotone Γ y _ _ _ ltac:(try_solve_pile) Htmp) in \"H0\".\n  clear Htmp.\n\n\n  eapply cast_proof_ml_hyps.\n  {\n    unfold exists_quantify.\n    rewrite -> (evar_quantify_evar_open y 0 (! b0 ∈ml (⌈ φ ⌉))).\n    2: { simpl. rewrite <- Heqy in Hfr. clear -Hfr. set_solver. }\n    reflexivity.\n    unfold well_formed, well_formed_closed in wfφ. destruct_and!.\n    simpl; split_and!; auto.\n    eapply well_formed_closed_ex_aux_ind; try eassumption; lia.\n  }\n  mlApplyMeta (useBasicReasoning (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) (not_not_intro Γ (ex , (! b0 ∈ml ⌈ φ ⌉)) ltac:(wf_auto2))) in \"H0\".\n  eapply cast_proof_ml_hyps.\n  {\n    replace (! ! ex , (! b0 ∈ml ⌈ φ ⌉)) with (! all , (b0 ∈ml ⌈ φ ⌉)) by reflexivity.\n    reflexivity.\n  }\n\n  eassert (Htmp: Γ ⊢i (! (ex, b0 ∈ml φ)) ---> (! (patt_free_evar x ∈ml ⌈ φ ⌉)) using _).\n  {\n    apply BasicProofSystemLemmas.modus_tollens.\n    apply membership_symbol_ceil_left; assumption.\n  }\n  mlApplyMeta Htmp.\n  fromMLGoal.\n  apply BasicProofSystemLemmas.modus_tollens.\n\n  pose proof (Hfr' := @set_evar_fresh_is_fresh Σ φ).\n  eapply cast_proof'.\n  {\n    rewrite -[THIS in (patt_exists THIS)](evar_quantify_evar_open x 0).\n    { subst x. solve_fresh. }\n    {\n      unfold well_formed, well_formed_closed in wfφ. destruct_and!.\n      simpl; split_and!; auto.\n      eapply well_formed_closed_ex_aux_ind; try eassumption; lia.\n    }\n    rewrite -[THIS in (patt_forall THIS)](evar_quantify_evar_open y 0).\n    { subst y. solve_fresh. }\n    {\n      unfold well_formed, well_formed_closed in wfφ. destruct_and!.\n      simpl; split_and!; auto.\n      eapply well_formed_closed_ex_aux_ind; try eassumption; lia.\n    }\n    reflexivity.\n  }\n  apply forall_gen.\n  { simpl. case_match;[|congruence].\n    subst x y.\n    eapply evar_is_fresh_in_richer'.\n    2: { eapply set_evar_fresh_is_fresh'. }\n    simpl.\n    rewrite free_evars_evar_quantify.\n    pose proof (Hsub := free_evars_bevar_subst φ (patt_free_evar (fresh_evar φ)) 0).\n    rewrite !simpl_free_evars.\n    set_solver.\n  }\n  { try_solve_pile. }\n\n  rewrite evar_quantify_evar_open.\n  { subst x. solve_fresh. }\n  {\n    unfold well_formed, well_formed_closed in wfφ. destruct_and!.\n    simpl; split_and!; auto.\n    eapply well_formed_closed_ex_aux_ind; try eassumption; lia.\n  }\n  mlSimpl. unfold evar_open. simpl. rewrite bevar_subst_not_occur.\n  { wf_auto2. }\n  apply membership_symbol_ceil_right; assumption.\n  try_solve_pile.\nDefined.\n\nLemma def_tot_phi_impl_tot_phi {Σ : Signature} {syntax : Syntax} Γ φ :\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i ⌈ ⌊ φ ⌋ ⌉ ---> ⌊ φ ⌋ using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H0\".\n  mlApplyMeta (useBasicReasoning (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) (not_not_intro Γ (⌈ ⌊ φ ⌋ ⌉) ltac:(wf_auto2))) in \"H0\".\n  mlIntro \"H1\". mlApply \"H0\". mlClear \"H0\".\n  fromMLGoal.\n  apply def_phi_impl_tot_def_phi.\n  { exact HΓ. }\n  { wf_auto2. }\nDefined.\n\nLemma floor_is_predicate {Σ : Signature} {syntax : Syntax} Γ φ :\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i is_predicate_pattern (⌊ φ ⌋)\n  using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  unfold is_predicate_pattern.\n  unfold \"=ml\".\n  toMLGoal.\n  { wf_auto2. }\n\n  mlRewrite (pf_iff_equiv_sym Γ (⌊ φ ⌋) (⌊ φ ⌋ <---> Top) (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) ltac:(wf_auto2) ltac:(wf_auto2) (useBasicReasoning _ (phi_iff_phi_top Γ (⌊ φ ⌋) ltac:(wf_auto2)))) at 1.\n  mlRewrite (pf_iff_equiv_sym Γ (! ⌊ φ ⌋) (⌊ φ ⌋ <---> ⊥) (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false) ltac:(wf_auto2) ltac:(wf_auto2) (useBasicReasoning _ (not_phi_iff_phi_bott Γ (⌊ φ ⌋) ltac:(wf_auto2)))) at 1.\n\n  fromMLGoal.\n\n  unfold patt_total at 1.\n  unfold patt_total at 2.\n  unfold patt_or.\n  apply BasicProofSystemLemmas.modus_tollens.\n\n  assert (Γ ⊢i (! ! ⌊ φ ⌋) <---> ⌊ φ ⌋ using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false)).\n  { toMLGoal.\n    { wf_auto2. }\n    mlSplitAnd; mlIntro \"H0\".\n    - fromMLGoal.\n      useBasicReasoning.\n      apply not_not_elim.\n      { wf_auto2. }\n    - mlIntro \"H1\". mlApply \"H1\". mlClear \"H1\". mlExact \"H0\".\n  }\n\n  toMLGoal.\n  { wf_auto2. }\n  mlRewrite H at 1.\n  clear H.\n  mlIntro \"H0\".\n  mlApplyMeta (def_phi_impl_tot_def_phi Γ (⌊ φ ⌋) HΓ ltac:(wf_auto2)) in \"H0\".\n  fromMLGoal.\n  apply floor_monotonic.\n  { exact HΓ. }\n  { wf_auto2. }\n  { wf_auto2. }\n  apply def_tot_phi_impl_tot_phi; assumption.\nDefined.\n\nLemma def_propagate_not {Σ : Signature} {syntax : Syntax} Γ φ:\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i (! ⌈ φ ⌉) <---> (⌊ ! φ ⌋)\n  using (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  toMLGoal.\n  { wf_auto2. }\n  mlRewrite (useBasicReasoning (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false) (not_not_iff Γ φ wfφ)) at 1.\n  mlSplitAnd; mlIntro; mlExactn 0.\nDefined.\n\nLemma def_def_phi_impl_tot_def_phi {Σ : Signature} {syntax : Syntax} Γ φ :\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i ⌈ ⌈ φ ⌉ ⌉ ---> ⌊ ⌈ φ ⌉ ⌋\n  using (ExGen := ⊤, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros HΓ wfφ.\n  eapply syllogism_meta.\n  1,3: wf_auto2.\n  2: { gapply def_def_phi_impl_def_phi. shelve. assumption. shelve. assumption. }\n  { wf_auto2. }\n  apply def_phi_impl_tot_def_phi; assumption.\nUnshelve.\n  exact (fresh_evar φ).\n  try_solve_pile.\n  solve_fresh.\nDefined.\n\n\nLemma ceil_is_predicate {Σ : Signature} {syntax : Syntax} Γ φ :\n  theory ⊆ Γ ->\n  well_formed φ ->\n  Γ ⊢i is_predicate_pattern (⌈ φ ⌉)\n  using AnyReasoning.\nProof.\n  intros HΓ wfφ.\n  unfold is_predicate_pattern.\n  apply or_comm_meta.\n  { wf_auto2. }\n  { wf_auto2. }\n  unfold patt_or.\n  apply @syllogism_meta with (B := ⌈ ⌈ φ ⌉ ⌉).\n  1,2,3: wf_auto2.\n  - toMLGoal.\n    { wf_auto2. }\n\n    mlRewrite (useBasicReasoning AnyReasoning (not_not_iff Γ (⌈ ⌈ φ ⌉ ⌉) ltac:(wf_auto2))) at 1.\n    mlIntro \"H0\".\n    mlIntro \"H1\".\n    mlApply \"H0\".\n    mlClear \"H0\".\n    mlRevertLast.\n    pose proof (Htmp := def_propagate_not Γ (⌈ φ ⌉) HΓ ltac:(wf_auto2)).\n    use AnyReasoning in Htmp.\n    mlRewrite Htmp at 1.\n    clear Htmp.\n    mlIntro \"H0\".\n    epose proof (Htmp := @liftProofInfoLe _ _ _ (ExGen := {[ev_x; evar_fresh (elements (free_evars (! ⌈ φ ⌉)))]}, SVSubst := ∅, KT := false, AKT := false) (ExGen := ⊤, SVSubst := ⊤, KT := false, AKT := false) ltac:(try_solve_pile) (total_phi_impl_phi Γ (! ⌈ φ ⌉) _ HΓ _ ltac:(wf_auto2))).\n    mlApplyMeta Htmp in \"H0\".\n    clear Htmp.\n    mlRevertLast.\n    pose proof (Htmp := @liftProofInfoLe _ _ _ (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false) AnyReasoning ltac:(try_solve_pile) (def_propagate_not Γ φ HΓ ltac:(wf_auto2))).\n    mlRewrite Htmp at 1.\n    clear Htmp.\n    fromMLGoal.\n    unshelve (gapply deduction_theorem_noKT).\n    6: exact HΓ.\n    4,5: wf_auto2.\n    3: { apply patt_iff_implies_equal.\n      1,2: wf_auto2.\n      { apply pile_refl. }\n      remember_constraint as i'.\n      toMLGoal.\n      { wf_auto2. }\n      mlSplitAnd; mlIntro \"H0\".\n      2: { \n        useBasicReasoning.\n        mlExFalso.\n        mlExact \"H0\".\n      }\n      assert (Htmp: ((Γ ∪ {[! φ]})) ⊢i ! φ using i').\n      { gapply BasicProofSystemLemmas.hypothesis. subst i'. try_solve_pile. wf_auto2. clear. set_solver. }\n      apply phi_impl_total_phi_meta in Htmp.\n      2: { wf_auto2. }\n      2: { subst i'. apply pile_refl.  }\n      mlAdd Htmp as \"H1\".  mlApply \"H1\". mlClear \"H1\".\n      fromMLGoal.\n      subst i'. \n      gapply Framing_right.\n      { apply pile_refl. }\n      { wf_auto2. }\n      { try_solve_pile. }\n      useBasicReasoning.\n      apply not_not_intro.\n      assumption.\n    }\n    { simpl. clear. try_solve_pile. }\n    { set_solver. }\n    { set_solver. }\n    { reflexivity. }\n    - eapply @syllogism_meta with (B := ⌊ ⌈ φ ⌉ ⌋).\n      1,2,3: wf_auto2.\n      { eapply liftProofInfoLe. 2: apply def_def_phi_impl_tot_def_phi; assumption. try_solve_pile. }\n      unshelve (gapply deduction_theorem_noKT).\n      4,5: wf_auto2.\n      4: exact HΓ.\n      3: {\n        apply phi_impl_total_phi_meta.\n        { wf_auto2. }\n        { apply pile_refl. }\n        apply pf_iff_split.\n        1,2: wf_auto2.\n        + toMLGoal. wf_auto2.\n          (* use [mlIntro _] *)\n          mlIntro \"H1\". mlClear \"H1\". fromMLGoal.\n          useBasicReasoning. apply top_holds.\n        + toMLGoal. wf_auto2.\n          mlIntro \"H0\". mlClear \"H0\". fromMLGoal.\n          gapply BasicProofSystemLemmas.hypothesis.\n          { try_solve_pile. }\n          { wf_auto2. }\n          clear. set_solver.\n      }\n      { try_solve_pile. }\n      {\n        simpl. clear. set_solver.\n      }\n      { simpl. clear. set_solver. }\n      { reflexivity. }\nUnshelve.\n  solve_fresh.\nDefined.\n\nLemma predicate_elim\n  {Σ : Signature} {syntax : Syntax} Γ (C : PatternCtx) (ψ : Pattern):\n  theory ⊆ Γ ->\n  well_formed (pcPattern C) ->\n  well_formed ψ ->\n  mu_in_evar_path (pcEvar C) (pcPattern C) 0 = false ->\n  Γ ⊢ is_predicate_pattern ψ ->\n  Γ ⊢ emplace C patt_bott ->\n  Γ ⊢ emplace C patt_top ->\n  Γ ⊢ emplace C ψ\n.\nProof.\n  intros HΓ HwfC Hwfψ HmfC Hpredψ Hb Ht.\n  toMLGoal.\n  { wf_auto2. }\n  mlAdd Hpredψ as \"Hψ\".\n  mlDestructOr \"Hψ\" as \"H1\" \"H2\".\n  {\n    mlAssert (\"H\": (emplace C ψ <---> emplace C Top )).\n    { wf_auto2. }\n    {\n      pose proof (Htmp := equality_elimination_basic_mfpath Γ ψ Top C HΓ ltac:(wf_auto2) ltac:(wf_auto2)).\n      feed specialize Htmp.\n      {\n        unfold PC_wf. exact HwfC.\n      }\n      { exact HmfC. }\n      mlApplyMeta Htmp.\n      mlExact \"H1\".\n    }\n    mlDestructAnd \"H\" as \"HA\" \"HB\".\n    mlApply \"HB\".\n    mlExactMeta Ht.\n  }\n  {\n    mlAssert (\"H\": (emplace C ψ <---> emplace C Bot )).\n    { wf_auto2. }\n    {\n      pose proof (Htmp := equality_elimination_basic_mfpath Γ ψ Bot C HΓ ltac:(wf_auto2) ltac:(wf_auto2)).\n      feed specialize Htmp.\n      {\n        unfold PC_wf. exact HwfC.\n      }\n      { exact HmfC. }\n      mlApplyMeta Htmp.\n      mlExact \"H2\".\n    }\n    mlDestructAnd \"H\" as \"HA\" \"HB\".\n    mlApply \"HB\".\n    mlExactMeta Hb.\n  }\nDefined.\n\nLemma predicate_propagate_right_2 {Σ : Signature} {syntax : Syntax} Γ ϕ ψ P :\n  theory ⊆ Γ ->\n  well_formed ϕ ->\n  well_formed ψ ->\n  well_formed P ->\n  Γ ⊢ is_predicate_pattern ψ ->\n  Γ ⊢ ψ and P $ ϕ <---> P $ (ψ and ϕ).\nProof.\n  intros HΓ wfϕ wfψ wfP predψ.\n  toMLGoal.\n  { wf_auto2. }\n  mlAdd predψ as \"Htmp\".\n  mlDestructOr \"Htmp\" as \"Htmp1\" \"Htmp2\".\n  {\n    mlRewriteBy \"Htmp1\" at 1.\n    { exact HΓ. }\n    { cbn. unfold mu_in_evar_path. cbn.\n      rewrite !Nat.max_0_r.\n      rewrite !maximal_mu_depth_to_0.\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        cbn.\n        repeat case_match; try reflexivity; lia.\n      }\n    }\n    mlRewriteBy \"Htmp1\" at 1.\n    { exact HΓ. }\n    { cbn. unfold mu_in_evar_path. cbn.\n      rewrite !Nat.max_0_r.\n      rewrite !maximal_mu_depth_to_0.\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        cbn.\n        repeat case_match; try reflexivity; lia.\n      }\n    }\n    mlClear \"Htmp1\".\n    mlRewrite (top_and Γ ϕ ltac:(wf_auto2)) at 1.\n    mlRewrite (top_and Γ (P $ ϕ) ltac:(wf_auto2)) at 1.\n    fromMLGoal.\n    useBasicReasoning.\n    apply pf_iff_equiv_refl.\n    wf_auto2.\n  }\n  {\n    mlRewriteBy \"Htmp2\" at 1.\n    { exact HΓ. }\n    { cbn. unfold mu_in_evar_path. cbn.\n      rewrite !Nat.max_0_r.\n      rewrite !maximal_mu_depth_to_0.\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        cbn.\n        repeat case_match; try reflexivity; lia.\n      }\n    }\n    mlRewriteBy \"Htmp2\" at 1.\n    { exact HΓ. }\n    { cbn. unfold mu_in_evar_path. cbn.\n      rewrite !Nat.max_0_r.\n      rewrite !maximal_mu_depth_to_0.\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        cbn.\n        repeat case_match; try reflexivity; lia.\n      }\n    }\n    mlClear \"Htmp2\".\n    mlRewrite (bott_and Γ ϕ ltac:(wf_auto2)) at 1.\n    mlRewrite (bott_and Γ (P $ ϕ) ltac:(wf_auto2)) at 1.\n    fromMLGoal.\n    mlSplitAnd.\n    {\n      mlIntro \"H\". mlDestructBot \"H\".\n    }\n    {\n      fromMLGoal.\n      useBasicReasoning.\n      apply Prop_bott_right.\n      wf_auto2.\n    }\n  }\nDefined.\n\n\nLemma predicate_propagate_left_2 {Σ : Signature} {syntax : Syntax} Γ ϕ ψ P :\n  theory ⊆ Γ ->\n  well_formed ϕ ->\n  well_formed ψ ->\n  well_formed P ->\n  Γ ⊢ is_predicate_pattern ψ ->\n  Γ ⊢ ψ and P $ ϕ <---> (ψ and P) $ ϕ.\nProof.\n  intros HΓ wfϕ wfψ wfP predψ.\n  toMLGoal.\n  { wf_auto2. }\n  mlAdd predψ as \"Htmp\".\n  mlDestructOr \"Htmp\" as \"Htmp1\" \"Htmp2\".\n  {\n    mlRewriteBy \"Htmp1\" at 1.\n    { exact HΓ. }\n    { cbn. unfold mu_in_evar_path. cbn.\n      rewrite !Nat.max_0_r.\n      rewrite !maximal_mu_depth_to_0.\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        cbn.\n        repeat case_match; try reflexivity; lia.\n      }\n    }\n    mlRewriteBy \"Htmp1\" at 1.\n    { exact HΓ. }\n    { cbn. unfold mu_in_evar_path. cbn.\n      rewrite !Nat.max_0_r.\n      rewrite !maximal_mu_depth_to_0.\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        cbn.\n        repeat case_match; try reflexivity; lia.\n      }\n    }\n    mlClear \"Htmp1\".\n    mlRewrite (top_and Γ P ltac:(wf_auto2)) at 1.\n    mlRewrite (top_and Γ (P $ ϕ) ltac:(wf_auto2)) at 1.\n    fromMLGoal.\n    useBasicReasoning.\n    apply pf_iff_equiv_refl.\n    wf_auto2.\n  }\n  {\n    mlRewriteBy \"Htmp2\" at 1.\n    { exact HΓ. }\n    { cbn. unfold mu_in_evar_path. cbn.\n      rewrite !Nat.max_0_r.\n      rewrite !maximal_mu_depth_to_0.\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        cbn.\n        repeat case_match; try reflexivity; lia.\n      }\n    }\n    mlRewriteBy \"Htmp2\" at 1.\n    { exact HΓ. }\n    { cbn. unfold mu_in_evar_path. cbn.\n      rewrite !Nat.max_0_r.\n      rewrite !maximal_mu_depth_to_0.\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        subst star. clear.\n        eapply evar_is_fresh_in_richer'.\n        2: {\n          apply set_evar_fresh_is_fresh.\n        }\n        {\n          cbn. set_solver.\n        }\n      }\n      {\n        cbn.\n        repeat case_match; try reflexivity; lia.\n      }\n    }\n    mlClear \"Htmp2\".\n    mlRewrite (bott_and Γ P ltac:(wf_auto2)) at 1.\n    mlRewrite (bott_and Γ (P $ ϕ) ltac:(wf_auto2)) at 1.\n    fromMLGoal.\n    mlSplitAnd.\n    {\n      mlIntro \"H\". mlDestructBot \"H\".\n    }\n    {\n      fromMLGoal.\n      useBasicReasoning.\n      apply Prop_bott_left.\n      wf_auto2.\n    }\n  }\nDefined.\n\n(* TODO: Put in a different file? *)\nLemma predicate_propagate_right {Σ : Signature} {syntax : Syntax} Γ ϕ ψ P :\n  theory ⊆ Γ ->\n  well_formed ϕ ->\n  well_formed ψ ->\n  well_formed P ->\n  mu_free ϕ ->\n  mu_free ψ ->\n  mu_free P ->\n  Γ ⊢ is_predicate_pattern ψ ->\n  Γ ⊢ ψ and P $ ϕ <---> P $ (ψ and ϕ).\nProof.\n  intros HΓ wfϕ wfψ wfP mϕ mψ mP predψ.\n  toMLGoal.\n  { wf_auto2. }\n  mlAdd predψ as \"P\"; clear predψ.\n  unfold is_predicate_pattern.\n  mlDestructOr \"P\" as \"T\" \"B\".\n  {\n    mlRewriteBy \"T\" at 1.\n    { set_solver. }\n    {\n      apply mu_free_in_path. simpl. split_and!; reflexivity || assumption.\n    }\n    mlRewriteBy \"T\" at 1.\n    { set_solver. }\n    {\n      apply mu_free_in_path. simpl. split_and!; reflexivity || assumption.\n    }\n    mlClear \"T\".\n    pose proof (Ht := top_and Γ (P $ ϕ) ltac:(wf_auto2)).\n    mlRewrite Ht at 1; clear Ht.\n    pose proof (Ht := top_and Γ ϕ ltac:(wf_auto2)).\n    mlRewrite Ht at 1; clear Ht.\n    fromMLGoal.\n    aapply pf_iff_equiv_refl; wf_auto2.\n  }\n  {\n    mlRewriteBy \"B\" at 1.\n    { set_solver. }\n    {\n      apply mu_free_in_path. simpl. split_and!; reflexivity || assumption.\n    }\n    mlRewriteBy \"B\" at 1.\n    { set_solver. }\n    {\n      apply mu_free_in_path. simpl. split_and!; reflexivity || assumption.\n    }\n    mlClear \"B\".\n    pose proof (Hb := bott_and Γ (P $ ϕ) ltac:(wf_auto2)).\n    mlRewrite Hb at 1; clear Hb.\n    pose proof (Hb := bott_and Γ ϕ ltac:(wf_auto2)).\n    mlRewrite Hb at 1; clear Hb.\n    fromMLGoal.\n    apply pf_iff_equiv_sym;[wf_auto2|wf_auto2|].\n    pose proof (Hiff := prf_prop_bott_iff).\n    specialize Hiff with (AC := ctx_app_r P box ltac:(wf_auto2)).\n    simpl in Hiff.\n    aapply Hiff.\n  }\nDefined.\n\n\nLemma equal_imp_membership {Σ : Signature} {syntax : Syntax} Γ φ φ' :\n  theory ⊆ Γ -> \n  well_formed φ -> well_formed φ' ->\n  Γ ⊢ ⌈ φ' ⌉  ->\n  Γ ⊢ (φ =ml φ') ---> (φ ∈ml φ').\nProof.\n  intros HΓ WF1 WF2 Def.\n  toMLGoal. wf_auto2.\n  mlIntro \"H0\".\n  mlRewriteBy \"H0\" at 1; cbn; try_wfauto2; try assumption.\n  {\n    unfold mu_in_evar_path. simpl.\n    rewrite decide_eq_same. simpl.\n    case_match;[reflexivity|].\n    rewrite 2!Nat.max_0_r in H.\n    rewrite maximal_mu_depth_to_0 in H.\n    2: { inversion H. }\n    subst star. clear.\n    eapply evar_is_fresh_in_richer'.\n    2: { apply set_evar_fresh_is_fresh. }\n    {\n      cbn. set_solver.\n    }\n  }\n  mlClear \"H0\". unfold patt_in.\n  assert (Γ ⊢ ( φ' and φ' <---> φ') ) as H1.\n  {\n    toMLGoal. wf_auto2.\n    mlSplitAnd; mlIntro \"H1\".\n    - mlDestructAnd \"H1\" as \"H2\" \"H3\". mlExact \"H3\".\n    - mlSplitAnd; mlExact \"H1\".\n  }\n  now mlRewrite H1 at 1.\nDefined.\n\nLemma phi_impl_ex_in_phi {Σ : Signature} {syntax : Syntax} Γ ϕ:\n  theory ⊆ Γ ->\n  well_formed ϕ ->\n  Γ ⊢ ϕ ---> (ex , b0 ∈ml ϕ and b0).\nProof.\n  intros HΓ wfϕ.\n  aapply (membership_elimination _ _ _ (fresh_evar (ϕ ---> (ex , b0 ∈ml ϕ and b0)))).\n  { solve_fresh. }\n  { wf_auto2. }\n  { assumption. }\n  remember (fresh_evar ϕ) as x.\n  rewrite <- evar_quantify_evar_open with (x := x) (n := 0) (phi := b0 ∈ml (ϕ ---> (ex , b0 ∈ml ϕ and b0))).\n  2: {\n    subst x.\n    eapply evar_is_fresh_in_richer'.\n    2: apply set_evar_fresh_is_fresh'.\n    clear. set_solver.\n  }\n  2: wf_auto2.\n  aapply universal_generalization;[wf_auto2|].\n  unfold evar_open. mlSimpl. simpl.\n  rewrite bevar_subst_not_occur;[wf_auto2|].\n  rewrite bevar_subst_not_occur;[wf_auto2|].\n  toMLGoal.\n  { wf_auto2. }\n  pose proof (H := membership_imp Γ x ϕ (ex , b0 ∈ml ϕ and b0)).\n  feed specialize H.\n  { set_solver. }\n  { wf_auto2. }\n  { wf_auto2. }\n  apply pf_iff_proj2 in H;[|wf_auto2|wf_auto2].\n  mlApplyMeta H; clear H.\n  mlIntro \"H\".\n  pose proof (H := membership_exists Γ x (b0 ∈ml ϕ and b0)).\n  feed specialize H.\n  { set_solver. }\n  { wf_auto2. }\n  use AnyReasoning in H.\n  mlRewrite H at 1; clear H.\n  pose proof (H := Ex_quan).\n  specialize H with (y := x).\n  mlApplyMeta H; clear H.\n  unfold instantiate. mlSimpl. simpl.\n  rewrite bevar_subst_not_occur;[wf_auto2|].\n  pose proof (H := membership_and_iff Γ x (patt_free_evar x ∈ml ϕ) (patt_free_evar x)).\n  feed specialize H.\n  { wf_auto2. }\n  { wf_auto2. }\n  { set_solver. }\n  use AnyReasoning in H.\n  mlRewrite H at 1; clear H.\n  mlSplitAnd.\n  + fromMLGoal.\n    aapply ceil_monotonic;[set_solver|wf_auto2|wf_auto2|].\n    toMLGoal. wf_auto2.\n    mlIntro \"H\".\n    mlSplitAnd.\n    * mlDestructAnd \"H\" as \"x\" \"p\". mlExact \"x\".\n    * mlApplyMeta phi_impl_defined_phi;[mlExact \"H\"| | assumption].\n      instantiate (1 := fresh_evar (patt_free_evar x and ϕ)). solve_fresh.\n  + mlClear \"H\".\n    mlApplyMeta equal_imp_membership.\n    fromMLGoal.\n    aapply patt_equal_refl.\n    wf_auto2.\n    aapply defined_evar.\n    { exact HΓ. }\n    { exact HΓ. }\nDefined.\n\nLemma membership_symbol_right {Σ : Signature} {syntax : Syntax} Γ ϕ ψ x :\n  theory ⊆ Γ ->\n  well_formed ϕ ->\n  well_formed ψ ->\n  mu_free ϕ ->\n  mu_free ψ ->\n  Γ ⊢ (patt_free_evar x ∈ml ψ $ ϕ) ---> (ex , (b0 ∈ml ϕ and patt_free_evar x ∈ml ψ $ b0)).\nProof.\n  intros HΓ wfϕ wfψ mϕ mψ.\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H0\".\n  mlAssert (\"H1\" : (patt_free_evar x ∈ml ψ $ (ex , b0 ∈ml ϕ and b0))).\n  { wf_auto2. }\n  {\n    fromMLGoal.\n    aapply membership_monotone;[set_solver|wf_auto2|wf_auto2|].\n    apply Framing_right with (ψ := ψ); auto. apply pile_any.\n    aapply phi_impl_ex_in_phi;[set_solver|wf_auto2].\n  } mlClear \"H0\".\n  mlAssert (\"H2\" : (patt_free_evar x ∈ml (ex, ψ $ (b0 ∈ml ϕ and b0)))).\n  { wf_auto2. }\n  {\n    fromMLGoal.\n    aapply membership_monotone;[set_solver|wf_auto2|wf_auto2|].\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro \"H\".\n    mlApplyMeta Prop_ex_right.\n    mlExact \"H\".\n  } mlClear \"H1\".\n  pose proof (H := membership_exists Γ x (ψ $ (b0 ∈ml ϕ and b0))).\n  feed specialize H.\n  { set_solver. }\n  { wf_auto2. }\n  use AnyReasoning in H.\n  mlRevertLast.\n  mlRewrite H at 1; clear H.\n  fromMLGoal.\n  remember (fresh_evar ((patt_free_evar x) and ϕ and ψ)) as y.\n  rewrite <- evar_quantify_evar_open with (x := y) (n := 0) (phi := patt_free_evar x ∈ml ψ $ (b0 ∈ml ϕ and b0)).\n  2: {\n    subst y.\n    eapply evar_is_fresh_in_richer'.\n    2: apply set_evar_fresh_is_fresh'.\n    clear. set_solver.\n  }\n  2: wf_auto2.\n  rewrite <- evar_quantify_evar_open with (x := y) (n := 0) (phi := b0 ∈ml ϕ and patt_free_evar x ∈ml ψ $ b0).\n  2: {\n    subst y.\n    eapply evar_is_fresh_in_richer'.\n    2: apply set_evar_fresh_is_fresh'.\n    clear. set_solver.\n  }\n  2: wf_auto2.\n  aapply ex_quan_monotone.\n  mlSimpl. unfold evar_open. simpl.\n  repeat (rewrite bevar_subst_not_occur;[wf_auto2|]).\n\n  toMLGoal.\n  { wf_auto2. }\n  pose proof (H := predicate_propagate_right Γ (patt_free_evar y) (patt_free_evar y ∈ml ϕ) ψ).\n  feed specialize H.\n  { set_solver. }\n  { wf_auto2. }\n  { wf_auto2. }\n  { wf_auto2. }\n  { reflexivity. }\n  { simpl. split_and!;reflexivity || assumption. }\n  { assumption. }\n  { aapply ceil_is_predicate;[set_solver|wf_auto2]. }\n  mlRewrite <- H at 1; clear H.\n\n  mlIntro \"H\".\n  mlApplyMeta membership_and_1 in \"H\";[|set_solver].\n  mlDestructAnd \"H\" as \"H0\" \"H1\".\n  mlApplyMeta ceil_and_x_ceil_phi_impl_ceil_phi in \"H0\";[|set_solver].\n  mlSplitAnd.\n  + mlExact \"H0\".\n  + mlExact \"H1\".\nDefined.\n\nLemma disj_equals_greater_1 {Σ : Signature} {syntax : Syntax} Γ φ₁ φ₂:\n  theory ⊆ Γ ->\n  well_formed φ₁ ->\n  well_formed φ₂ ->\n  Γ ⊢i (φ₁ ⊆ml φ₂) ---> ((φ₁ or φ₂) =ml φ₂)\n  using AnyReasoning.\nProof.\n  intros HΓ wfφ₁ wfφ₂.\n  unshelve (gapply deduction_theorem_noKT).\n  2: { apply pile_any. }\n  3,4: wf_auto2.\n  3: exact HΓ.\n  2: {\n    apply phi_impl_total_phi_meta.\n    { wf_auto2. }\n    { apply pile_refl. }\n    apply pf_iff_split.\n    1,2: wf_auto2.\n    - toMLGoal. wf_auto2. mlIntro \"H0\". mlDestructOr \"H0\" as \"H0'\" \"H0'\".\n      + assert (Γ ∪ {[φ₁ ---> φ₂]} ⊢i φ₁ ---> φ₂ using ( (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false))).\n        {\n          gapply BasicProofSystemLemmas.hypothesis.\n          { try_solve_pile. }\n          { wf_auto2. }\n          clear. set_solver.\n        }\n        mlApplyMetaRaw H. mlExact \"H0'\".\n      + mlExact \"H0'\".\n    - useBasicReasoning. apply disj_right_intro; assumption.\n  }\n  { simpl. clear. set_solver. }\n  { simpl. clear. set_solver. }\n  { reflexivity. }\nDefined.\n\n\nLemma disj_equals_greater_2_meta {Σ : Signature} {syntax : Syntax} Γ φ₁ φ₂:\n  theory ⊆ Γ ->\n  well_formed φ₁ ->\n  well_formed φ₂ ->\n  Γ ⊢i (φ₁ or φ₂) =ml φ₂ using AnyReasoning ->\n  Γ ⊢i φ₁ ⊆ml φ₂ using AnyReasoning.\nProof.\n  intros HΓ wfφ₁ wfφ₂ Heq.\n  toMLGoal.\n  { wf_auto2. }\n  unshelve (epose proof (Htmp := patt_equal_implies_iff _ _ _ _ (fresh_evar (φ₁ or φ₂)) HΓ _ _ _ _ Heq)).\n  { solve_fresh. }\n  { apply pile_any. }\n  { wf_auto2. }\n  { wf_auto2. }\n  apply pf_iff_equiv_sym in Htmp.\n  3: { wf_auto2. }\n  2: { wf_auto2. }\n  mlRewrite Htmp at 1.\n  fromMLGoal.\n  unfold \"⊆ml\".\n  apply phi_impl_total_phi_meta.\n  { wf_auto2. }\n  { apply pile_any. }\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H0\". mlLeft. mlExact \"H0\".\nDefined.\n\nLemma disj_equals_greater_2 {Σ : Signature} {syntax : Syntax} Γ φ₁ φ₂:\n  theory ⊆ Γ ->\n  well_formed φ₁ ->\n  well_formed φ₂ ->\n  mu_free φ₁ -> (* TODO get rid of it *)\n  Γ ⊢i ((φ₁ or φ₂) =ml φ₂) ---> (φ₁ ⊆ml φ₂)\n  using AnyReasoning.\nProof.\n  intros HΓ wfφ₁ wfφ₂ mfφ₁.\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H0\".\n\n  unshelve(mlApplyMeta patt_equal_sym in \"H0\").\n  2: { assumption. }\n  mlRewriteBy \"H0\" at 1.\n  { assumption. }\n  { apply mu_free_in_path. simpl. rewrite mfφ₁. reflexivity. }\n  mlClear \"H0\".\n\n  fromMLGoal.\n  unfold \"⊆ml\".\n  apply phi_impl_total_phi_meta.\n  { wf_auto2. }\n  { apply pile_any. }\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H0\". mlLeft. mlExact \"H0\".\nDefined.\n\nLemma bott_not_total {Σ : Signature} {syntax : Syntax}:\n  forall Γ, theory ⊆ Γ ->\n  Γ ⊢i ! ⌊ ⊥ ⌋\n  using AnyReasoning.\nProof.\n  intros Γ SubTheory.\n  toMLGoal. wf_auto2.\n  mlIntro \"H0\". mlApply \"H0\".\n  mlApplyMetaRaw (liftProofInfoLe _ _ _ AnyReasoning (phi_impl_defined_phi _ (! ⊥) _ SubTheory _ ltac:(wf_auto2))).\n  mlIntro \"H1\". mlExact \"H1\".\nUnshelve.\n  2: exact (fresh_evar ⊥).\n  try_solve_pile.\n  solve_fresh.\nDefined.\n\nLemma defined_not_iff_not_total {Σ : Signature} {syntax : Syntax}:\n  ∀ (Γ : Theory) (φ : Pattern),\n  theory ⊆ Γ → well_formed φ → Γ ⊢i ⌈ ! φ ⌉ <---> ! ⌊ φ ⌋\n  using AnyReasoning.\nProof.\n  intros Γ φ HΓ Wf. toMLGoal. wf_auto2.\n  mlSplitAnd.\n  * mlIntro \"H0\".\n    mlApplyMetaRaw (liftProofInfoLe _ _ _ AnyReasoning (def_not_phi_impl_not_total_phi Γ φ HΓ Wf)).\n    mlExact \"H0\".\n  * unfold patt_total.\n    epose proof (liftProofInfoLe _ _ _ AnyReasoning (not_not_iff Γ ⌈ ! φ ⌉ ltac:(wf_auto2))) as H.\n    mlRewrite <- H at 1.\n    mlIntro \"H0\".\n    mlExact \"H0\".\n  Unshelve.\n  all: try_solve_pile.\nDefined.\n\nLemma patt_or_total {Σ : Signature} {syntax : Syntax}:\n  forall Γ φ ψ,\n  theory ⊆ Γ ->\n  well_formed φ -> well_formed ψ ->\n  Γ ⊢i  ⌊ φ ⌋ or ⌊ ψ ⌋ ---> ⌊ φ or ψ ⌋\n  using AnyReasoning.\nProof.\n  intros Γ φ ψ HΓ Wf1 Wf2. toMLGoal. wf_auto2.\n  mlIntro \"H0\".\n  mlDestructOr \"H0\" as \"H0'\" \"H0'\".\n  * epose proof (liftProofInfoLe _ _ _ AnyReasoning (disj_left_intro Γ φ ψ Wf1 Wf2)) as H.\n    apply floor_monotonic in H. 3-4: try wf_auto2.\n    2: { exact HΓ. }\n    mlApplyMetaRaw H.\n    mlExact \"H0'\".\n  * epose proof (liftProofInfoLe _ _ _ AnyReasoning (disj_right_intro Γ φ ψ Wf1 Wf2)) as H.\n    apply floor_monotonic in H.\n    3,4: wf_auto2.\n    2: { exact HΓ. }\n    mlApplyMetaRaw H.\n    mlExact \"H0'\".\nUnshelve.\n  all: try_solve_pile.\nDefined.\n\nLemma patt_defined_and {Σ : Signature} {syntax : Syntax}:\n  forall Γ φ ψ,\n  theory ⊆ Γ ->\n  well_formed φ -> well_formed ψ ->\n  Γ ⊢i ⌈ φ and ψ ⌉ ---> ⌈ φ ⌉ and ⌈ ψ ⌉\n  using AnyReasoning.\nProof.\n  intros Γ φ ψ HΓ Wf1 Wf2. toMLGoal. wf_auto2.\n  unfold patt_and.\n\n  epose proof (liftProofInfoLe _ _ _ AnyReasoning (defined_not_iff_not_total Γ (! φ or ! ψ) HΓ ltac:(wf_auto2))) as H.\n  mlRewrite H at 1.\n  mlIntro \"H0\".\n  mlIntro \"H1\".\n  mlApply \"H0\".\n  mlClear \"H0\".\n  mlApplyMeta (patt_or_total _ (! φ) (! ψ) HΓ).\n  mlDestructOr \"H1\" as \"H1'\" \"H1'\".\n  * mlLeft. unfold patt_total.\n    epose proof (liftProofInfoLe _ _ _ AnyReasoning (not_not_iff Γ φ Wf1)) as H0.\n    mlRewrite <- H0 at 1.\n    mlExact \"H1'\".\n  * mlRight. unfold patt_total.\n    epose proof ((liftProofInfoLe _ _ _ AnyReasoning (not_not_iff Γ ψ Wf2))) as H1.\n    mlRewrite <- H1 at 1.\n    mlExact \"H1'\".\nUnshelve.\n  all: try_solve_pile.\nDefined.\n\nLemma patt_total_and {Σ : Signature} {syntax : Syntax}:\n  forall Γ φ ψ,\n  theory ⊆ Γ ->\n  well_formed φ -> well_formed ψ ->\n  Γ ⊢i ⌊ φ and ψ ⌋ <---> ⌊ φ ⌋ and ⌊ ψ ⌋\n  using (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false).\nProof.\n  intros Γ φ ψ HΓ Wf1 Wf2. toMLGoal. wf_auto2.\n  mlSplitAnd.\n  * unfold patt_and.\n    pose proof (Htmp := def_propagate_not Γ (! φ or ! ψ) HΓ ltac:(wf_auto2)).\n    mlRewrite <- Htmp at 1.\n    mlIntro \"H1\".\n    mlIntro \"H2\".\n    mlApply \"H1\".\n    mlClear \"H1\".\n    mlRewrite (ceil_compat_in_or Γ (! φ) (! ψ) HΓ ltac:(wf_auto2) ltac:(wf_auto2)) at 1.\n    mlDestructOr \"H2\" as \"H2'\" \"H2'\".\n    - mlLeft. mlRevertLast. unfold patt_total.\n      mlRewrite <- (useBasicReasoning (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false) (not_not_iff Γ ⌈ ! φ ⌉ ltac:(wf_auto2))) at 1.\n      mlIntro \"H3\". mlExact \"H3\".\n    - mlRight. mlRevertLast. unfold patt_total.\n      mlRewrite <- (useBasicReasoning (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false) (not_not_iff Γ ⌈ ! ψ ⌉ ltac:(wf_auto2))) at 1.\n      mlIntro \"H3\". mlExact \"H3\".\n  * mlIntro \"H0\". mlDestructAnd \"H0\" as \"H1\" \"H2\".\n    unfold patt_and.\n    pose proof (Htmp := def_propagate_not Γ (! φ or ! ψ) HΓ ltac:(wf_auto2)).\n    mlRewrite <- Htmp at 1.\n    mlRewrite (ceil_compat_in_or Γ (! φ) (! ψ) HΓ ltac:(wf_auto2) ltac:(wf_auto2)) at 1.\n    mlIntro \"H3\". mlDestructOr \"H3\" as \"H3'\" \"H3'\".\n    - mlRevertLast. mlExact \"H1\".\n    - mlRevertLast. mlExact \"H2\".\nDefined.\n\nDefinition overlaps_with {Σ : Signature} {syntax : Syntax} (p q : Pattern) : Pattern\n:= ⌈ p and q ⌉.\n\nLemma overlapping_variables_equal {Σ : Signature} {syntax : Syntax} :\n  forall x y Γ,\n  theory ⊆ Γ ->\n  Γ ⊢ overlaps_with (patt_free_evar y) (patt_free_evar x) ---> patt_free_evar y =ml patt_free_evar x.\nProof.\n  intros x y Γ HΓ.\n\n  remember (patt_free_evar x) as pX. assert (well_formed pX) by (rewrite HeqpX;auto).\n  remember (patt_free_evar y) as pY. assert (well_formed pY) by (rewrite HeqpY;auto).\n  unfold overlaps_with.\n  toMLGoal. wf_auto2.\n  unfold patt_equal, patt_iff.\n  epose proof (H2 := liftProofInfoLe _ _ _ AnyReasoning (patt_total_and Γ\n                            (pY ---> pX)\n                            (pX ---> pY) HΓ\n                            ltac:(wf_auto2) ltac:(wf_auto2))).\n  mlRewrite H2 at 1.\n  mlIntro \"H0\".\n  mlIntro \"H1\".\n  mlDestructOr \"H1\" as \"H1'\" \"H1'\".\n  * mlApply \"H1'\".\n    mlClear \"H1'\".\n    mlIntro \"H2\".\n    pose proof (MH := nimpl_eq_and Γ pY pX\n                  ltac:(wf_auto2) ltac:(wf_auto2)).\n    use AnyReasoning in MH.\n    mlRevertLast.\n    mlRewrite MH at 1. fold AnyReasoning.\n    unshelve (epose proof (MH1 := Singleton_ctx Γ \n           (⌈_⌉ $ᵣ □)\n           (⌈_⌉ $ᵣ □) pX y ltac:(wf_auto2))). 1-2: wf_auto2.\n    rewrite -HeqpY in MH1.\n    use AnyReasoning in MH1. simpl in MH1.\n    (* TODO: having mlExactMeta would help here *)\n    mlRevertLast. unfold patt_defined. unfold patt_not in *.\n    mlIntro \"H1\". mlIntro \"H2\".\n    mlApplyMeta MH1. simpl. mlSplitAnd. mlExact \"H1\". mlExact \"H2\".\n  * mlApply \"H1'\".\n    mlClear \"H1'\".\n    mlIntro \"H2\".\n    pose proof (MH := nimpl_eq_and Γ pX pY\n                  ltac:(wf_auto2) ltac:(wf_auto2)).\n    mlRevertLast. use AnyReasoning in MH.\n    mlRewrite MH at 1.\n    pose proof (MH1 := patt_and_comm Γ pY pX ltac:(wf_auto2) ltac:(wf_auto2)).\n    mlRevertLast. use AnyReasoning in MH1. mlRewrite MH1 at 1.\n    unshelve (epose proof (Singleton_ctx Γ \n           (⌈_⌉ $ᵣ □)\n           (⌈_⌉ $ᵣ □) pY x ltac:(wf_auto2)) as MH2). 1-2: wf_auto2.\n    rewrite -HeqpX in MH2.\n    use AnyReasoning in MH2.\n    mlIntro \"H1\". mlIntro \"H2\".\n    mlApplyMeta MH2. simpl. mlSplitAnd. mlExact \"H1\". mlExact \"H2\".\nUnshelve.\n  try_solve_pile.\nDefined.\n\nLemma mlSpecializeMeta {Σ : Signature} {syntax : Syntax} :\n  forall Γ φ ψ, theory ⊆ Γ-> \n  well_formed (ex , φ) -> well_formed ψ -> mu_free φ ->\n  Γ ⊢i (all , φ) using AnyReasoning -> \n  Γ ⊢i ex , ψ =ml b0 using AnyReasoning ->\n  Γ ⊢i φ^[evar: 0 ↦ ψ] using AnyReasoning.\nProof.\n  intros Γ φ ψ HΓ WF1 WF2 MF P1 P2.\n  toMLGoal. wf_auto2.\n  mlApplyMeta forall_functional_subst.\n  mlSplitAnd; fromMLGoal; auto.\n  Unshelve. all: auto. all: wf_auto2.\nDefined.\n\n(* TODO: make sure that the final [assumption] does not solve goals we do not want to solve. *)\nTactic Notation \"mgSpecMeta\" ident(hyp) \"with\" constr(t) := \n  unshelve (eapply (@mlSpecializeMeta _ _ _ _ t) in hyp); try_wfauto2; try assumption.\n\nLocal Lemma test_spec {Σ : Signature} {syntax : Syntax}:\n  forall Γ φ ψ, theory ⊆ Γ-> \n  well_formed (ex , φ) -> well_formed ψ -> mu_free φ ->\n  Γ ⊢i (all , φ) using AnyReasoning -> \n  Γ ⊢i ex , ψ =ml b0 using AnyReasoning ->\n  Γ ⊢i φ^[evar: 0 ↦ ψ] using AnyReasoning.\nProof.\n  intros. mgSpecMeta H3 with ψ.\nDefined.\n\nLemma MLGoal_mlSpecialize {Σ : Signature} {syntax : Syntax} Γ l₁ l₂ p t g name:\n  theory ⊆ Γ ->\n  mu_free p -> well_formed t ->\n  mkMLGoal Σ Γ (l₁ ++ (mkNH _ name p^[evar: 0 ↦ t]) ::l₂ ) g AnyReasoning ->\n  mkMLGoal Σ Γ (l₁ ++ (mkNH _ name ((all, p) and (ex , t =ml b0)))::l₂) g AnyReasoning.\nProof.\n  intros HΓ MF WF MG.\n  unfold of_MLGoal in *. simpl in *. intros H H0.\n  assert (well_formed (ex , p)). {\n    unfold patterns_of in H0. rewrite map_app in H0.\n    apply wfl₁hl₂_proj_h in H0; simpl in H0.\n    apply andb_true_iff in H0 as [H0'' H0'].\n    apply andb_true_iff in H0' as [H0_1 H0_2]; simpl in *; repeat rewrite andb_true_r in H0_1, H0_2; repeat rewrite andb_true_iff in H0_1, H0_2; \n    destruct_and!;\n    wf_auto2.\n  }\n  unshelve (epose proof (MG H _) as MG').\n  {\n    unfold patterns_of in *; rewrite -> map_app in *; simpl in H0; wf_auto2.\n  }\n  clear MG.\n  unfold patterns_of in *. rewrite -> map_app in *. simpl.\n  eapply prf_strenghten_premise_iter_meta_meta.\n  7: exact MG'.\n  5: assumption.\n  1: now apply wfl₁hl₂_proj_l₁ in H0.\n  1: now apply wfl₁hl₂_proj_l₂ in H0.\n  1,2: wf_auto2.\n  simpl.\n  apply forall_functional_subst. 1-3: assumption.\n  all: wf_auto2.\nDefined.\n\n(**\n  This tactic can be used on local hypotheses shaped in the following way:\n     (all , φ) and ex , t = b0\n*)\nTactic Notation \"mlSpecn\" constr(n) := \n  _mlReshapeHypsByIdx n;\n  apply MLGoal_mlSpecialize; [ auto | wf_auto2 | wf_auto2 | _mlReshapeHypsBack ].\n\nTactic Notation \"mlSpec\" constr(name') :=\n  _mlReshapeHypsByName name';\n  apply MLGoal_mlSpecialize; [ auto | wf_auto2 | wf_auto2 | _mlReshapeHypsBack ].\n\n\nGoal forall (Σ : Signature) (syntax : Syntax) Γ φ t, \n  theory ⊆ Γ -> mu_free φ -> well_formed t -> well_formed (ex , φ) ->\n  Γ ⊢i (all , φ) ---> (ex , t =ml b0) ---> φ^[evar: 0 ↦ t] using AnyReasoning.\nProof.\n  intros. toMLGoal. wf_auto2.\n  mlIntro \"mH\". mlIntro \"mH0\".\n  mlAssert (\"mH1\" : ((all , φ) and ex , t =ml b0)). wf_auto2. mlSplitAnd; mlAssumption.\n  mlClear \"mH\". mlClear \"mH0\".\n  mlSpec \"mH1\". mlExact \"mH1\".\nDefined.\n\n(** \n  TODO: why should x be introduced for proof info (it could be constructed \"ony the fly\")? Could we avoid this?\n *)\nLemma forall_defined {Σ : Signature} {syntax : Syntax}:\n  forall Γ i, theory ⊆ Γ ->\n  ProofInfoLe (ExGen := {[ev_x]}, SVSubst := ∅, KT := false, AKT := false) i  ->\n  Γ ⊢i all , ⌈b0⌉ using i.\nProof.\n  intros Γ i HΓ PI.\n  (* remember (fresh_evar ⊥) as x. *)\n  toMLGoal. wf_auto2.\n  epose proof (BasicProofSystemLemmas.Ex_gen Γ (! ⌈patt_free_evar ev_x⌉) ⊥ ev_x i _ _).\n  unfold exists_quantify in H. cbn in H. case_match. 2: congruence.\n  mlIntro \"H\". mlApplyMeta H. fold (patt_defined b0) (patt_not ⌈b0⌉).\n  mlExact \"H\".\n    Unshelve.\n    * eapply pile_trans. 2: exact PI. try_solve_pile.\n    * set_solver.\n    * toMLGoal. wf_auto2. mlIntro \"H\". mlApply \"H\".\n      pose proof (defined_evar _ ev_x HΓ).\n      eapply liftProofInfoLe in H. mlExactMeta H.\n      eapply pile_trans. 2: exact PI.\n      try_solve_pile.\nDefined.\n\nLemma membership_refl {Σ : Signature} {syntax : Syntax}:\n  forall Γ t, well_formed t -> \n  theory ⊆ Γ-> Γ ⊢i ((ex , t =ml b0) ---> t ∈ml t) using AnyReasoning.\nProof.\n  intros Γ t WF HΓ.\n  unfold \"∈ml\". toMLGoal. wf_auto2.\n  mlIntro \"mH\".\n  pose proof (and_singleton Γ t WF). use AnyReasoning in H.\n  mlRewrite H at 1.\n  remember (fresh_evar t) as x.\n  mlAssert (\"mH1\" : ((all, ⌈patt_bound_evar 0⌉) and ex, t =ml b0)). wf_auto2. {\n    mlSplitAnd.\n    * mlClear \"mH\".\n      epose proof (forall_defined Γ AnyReasoning HΓ _).\n      mlExactMeta H0.\n      Unshelve.\n      apply pile_any.\n    * mlAssumption.\n  }\n  mlClear \"mH\".\n  mlSpec \"mH1\".\n  mlExact \"mH1\".\nDefined.\n\nLemma MLGoal_reflexivity {Σ : Signature} {syntax : Syntax} Γ l ϕ i :\n  theory ⊆ Γ ->\n  mkMLGoal _ Γ l (ϕ =ml ϕ) i.\nProof.\n  intros HΓ. unfold of_MLGoal. simpl. intros wfl wfg.\n  eapply MP. 2: gapply nested_const.\n  2: try_solve_pile. 2-3: wf_auto2.\n  gapply patt_equal_refl. try_solve_pile. wf_auto2.\nDefined.\n\nTactic Notation \"mlReflexivity\" :=\n  _ensureProofMode;\n  apply MLGoal_reflexivity; try assumption; set_solver.\n\nLocal Example mlReflexivity_test {Σ : Signature} {syntax : Syntax} Γ ϕ ψ :\n  theory ⊆ Γ -> well_formed ϕ -> well_formed ψ ->\n  Γ ⊢i ϕ ---> ψ ---> ψ =ml ψ using BasicReasoning.\nProof.\n  intros.\n  do 2 mlIntro.\n  mlReflexivity.\nDefined.\n\n(* TODO: strengthen proof info about this: *)\nLemma MLGoal_symmetry {Σ : Signature} {syntax : Syntax} Γ l ϕ ψ :\n  theory ⊆ Γ ->\n  mkMLGoal _ Γ l (ϕ =ml ψ) AnyReasoning ->\n  mkMLGoal _ Γ l (ψ =ml ϕ) AnyReasoning.\nProof.\n  unfold of_MLGoal. simpl.\n  intros HΓ H wfl wfg.\n  eapply prf_weaken_conclusion_iter_meta_meta. 5: apply H.\n  1-3,5,6: wf_auto2.\n  apply patt_equal_sym; auto.\n  1-2: wf_auto2.\nDefined.\n\n(* TODO: strengthen proof info about this: *)\nLemma MLGoal_symmetryIn {Σ : Signature} {syntax : Syntax} name Γ l1 l2 ϕ ψ g  :\n  theory ⊆ Γ ->\n  mkMLGoal _ Γ (l1 ++ (mkNH _ name (ϕ =ml ψ)) :: l2) g AnyReasoning ->\n  mkMLGoal _ Γ (l1 ++ (mkNH _ name (ψ =ml ϕ)) :: l2) g AnyReasoning.\nProof.\n  unfold of_MLGoal. simpl.\n  intros HΓ H wfl wfg.\n  unfold patterns_of in *. rewrite -> map_app in *. simpl in *.\n  eapply prf_strenghten_premise_iter_meta_meta.\n  6 : apply patt_equal_sym; auto.\n  8: apply H.\n  all: wf_auto2.\nDefined.\n\n\nTactic Notation \"mlSymmetry\" :=\n  _ensureProofMode;\n  apply MLGoal_symmetry; [try assumption; set_solver|].\n\nTactic Notation \"mlSymmetry\" \"in\" constr(name) :=\n  _ensureProofMode;\n  _mlReshapeHypsByName name;\n  apply (MLGoal_symmetryIn name); [try assumption; set_solver|];\n  _mlReshapeHypsBack.\n\nLocal Example mlSymmetry_test {Σ : Signature} {syntax : Syntax} Γ ϕ ψ :\n  theory ⊆ Γ -> well_formed ϕ -> well_formed ψ ->\n  Γ ⊢i ϕ =ml ψ ---> ϕ =ml ψ using AnyReasoning.\nProof.\n  intros.\n  mlIntro \"H\".\n  mlSymmetry.\n  mlSymmetry in \"H\".\n  mlAssumption.\nDefined.\n\n\n(* TODO: eliminate mu_free *)\nLemma patt_equal_trans {Σ : Signature} {syntax : Syntax} Γ φ1 φ2 φ3:\n  theory ⊆ Γ ->\n  well_formed φ1 -> well_formed φ2 -> well_formed φ3 ->\n  mu_free φ1 -> mu_free φ2 -> mu_free φ3 ->\n  Γ ⊢i φ1 =ml φ2 ---> φ2 =ml φ3 ---> φ1 =ml φ3\n  using AnyReasoning.\nProof.\n  intros HΓ WF1 WF2 WF3 MF1 MF2 MF3.\n  mlIntro \"H\". mlIntro \"H0\".\n  mlAssert (\"H1\" : ⌊ (φ1 <---> φ2) and (φ2 <---> φ3) ⌋). wf_auto2. {\n    pose proof (patt_total_and Γ (φ1 <---> φ2) (φ2 <---> φ3) HΓ ltac:(wf_auto2) ltac:(wf_auto2)).\n    apply pf_iff_proj2 in H. 2-3: wf_auto2.\n    use AnyReasoning in H. mlApplyMeta H. mlSplitAnd; mlAssumption.\n  }\n  mlClear \"H\". mlClear \"H0\". fromMLGoal.\n  unshelve (gapply deduction_theorem_noKT). exact BasicReasoning. try_solve_pile.\n  2-3: abstract(wf_auto2).\n  2: exact HΓ.\n  {\n    remember (Γ ∪ {[(φ1 <---> φ2) and (φ2 <---> φ3)]}) as Γ'.\n    assert (Γ' ⊢i ((φ1 <---> φ2) and (φ2 <---> φ3)) using BasicReasoning). {\n      apply BasicProofSystemLemmas.hypothesis. wf_auto2.\n      rewrite HeqΓ'. apply elem_of_union_r. constructor. \n    }\n    epose proof (pf_conj_elim_l _ _ _ _ _) as H'.\n    eapply MP in H'.\n    2: { exact H. }\n    epose proof (pf_conj_elim_r _ _ _ _ _) as H''.\n    eapply MP in H''.\n    2: { exact H. }\n    clear H.\n    apply pf_iff_equiv_sym in H'; auto.\n    apply pf_iff_equiv_sym in H''; auto.\n    apply patt_iff_implies_equal; auto.\n    2 : {\n    toMLGoal. wf_auto2. mlSplitAnd.\n    * apply pf_iff_proj2 in H'. apply pf_iff_proj2 in H''. 2-5: wf_auto2.\n      mlIntro. mlApplyMeta H''. mlApplyMeta H'. mlAssumption.\n    * apply pf_iff_proj1 in H'. apply pf_iff_proj1 in H''. 2-5: wf_auto2.\n      mlIntro. mlApplyMeta H'. mlApplyMeta H''. mlAssumption.\n    }\n    try_solve_pile.\n  }\n  1-2: set_solver.\n  auto.\n  Unshelve.\n  1-4: wf_auto2.\nDefined.\n\nClose Scope ml_scope.\nClose Scope string_scope.\nClose Scope list_scope.\n", "meta": {"author": "harp-project", "repo": "AML-Formalization", "sha": "ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d", "save_path": "github-repos/coq/harp-project-AML-Formalization", "path": "github-repos/coq/harp-project-AML-Formalization/AML-Formalization-ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d/matching-logic/src/Theories/Definedness_ProofSystem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23367837624056534}}
{"text": "(** * NOT instruction *)\nRequire Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype tuple.\nRequire Import procstate procstatemonad bitsops bitsprops bitsopsprops.\nRequire Import spec SPred septac spec safe triple basic basicprog spectac.\nRequire Import instr instrcodec eval monad monadinst reader pointsto cursor.\nRequire Import Setoid RelationClasses Morphisms.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import Relations.\nRequire Import instrsyntax.\n\nLocal Open Scope instr_scope.\n\nRequire Import x86.instrrules.core.\n\nLemma NOT_rule d (src:RegMem d) v:\n  |-- specAtRegMemDst src (fun V => basic (V v) (UOP d OP_NOT src) (V (invB v))).\nProof. do_instrrule_triple. Qed.\n\nLtac basicNOT :=\n  rewrite /makeUOP;\n  let R := lazymatch goal with\n             | |- |-- basic ?p (@UOP ?d OP_NOT ?a) ?q => constr:(@NOT_rule d a)\n           end in\n  basicapply R.\n\n\n(** We open a section in order to localize the hints *)\nSection InstrRules.\n\nHint Unfold\n  specAtDstSrc specAtSrc specAtRegMemDst specAtMemSpec specAtMemSpecDst\n  DWORDRegMemR BYTERegMemR DWORDRegMemM DWORDRegImmI fromSingletonMemSpec\n  DWORDorBYTEregIs natAsDWORD BYTEtoDWORD\n  makeMOV makeBOP makeUOP\n  : basicapply.\nHint Rewrite\n  addB0 low_catB : basicapply.\n\n(** Special case for not *)\nLemma NOT_R_rule (r:Reg) (v:DWORD):\n  |-- basic (r~=v) (NOT r) (r~=invB v).\nProof. basicNOT. Qed.\n\nCorollary NOT_M_rule (r:Reg) (offset:nat) (v pbase:DWORD):\n  |-- basic (r~=pbase ** pbase +# offset :-> v) (NOT [r + offset])\n            (r~=pbase ** pbase +# offset :-> invB v).\nProof. basicNOT. Qed.\nEnd InstrRules.\n", "meta": {"author": "jbj", "repo": "x86proved", "sha": "d314fa6d23c064a2be4bf686ac7da16a591fda01", "save_path": "github-repos/coq/jbj-x86proved", "path": "github-repos/coq/jbj-x86proved/x86proved-d314fa6d23c064a2be4bf686ac7da16a591fda01/src/x86/instrrules/not.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23367837624056526}}
{"text": "Require Import RRR.Lebesgue.Lebesgue.\nRequire Import RRR.Lang.Lang.\nRequire Import RRR.Rel.Relations.\nRequire Import RRR.Rel.Compatibility.\nRequire Import RRR.Rel.Fundamental.\nRequire Import RRR.Rel.Adequacy.\nRequire Import Omega.\n\nSection section_congruence.\n\nHint Constructors wf_exp wf_val wf_ctx : core.\n\nFixpoint congruence V (e₁ e₂ : exp V)\n(Γ : V → ty) (T T₀ : ty) (C : ctx V)\n(W : wf_ctx C Γ T T₀) {struct W} :\nERel_open Γ T e₁ e₂ →\nERel_open ∅→ T₀ (ctx_plug C e₁) (ctx_plug C e₂).\nProof.\nintro He.\nspecialize He as Wf_e. destruct Wf_e as [[Wf_e₁ Wf_e₂] _].\ndestruct W ; simpl.\n+ apply He.\n+ eapply congruence; eauto.\n  apply compat_exp_val.\n  2:{ constructor; assumption.  }\n  1:{ constructor; assumption.  }\n  apply compat_val_fun; auto.\n+ eapply congruence; eauto.\n  apply compat_exp_val.\n  2:{ constructor; assumption.  }\n  1:{ constructor; assumption.  }\n  apply compat_val_fix; auto.\n+ eapply congruence; eauto.\n  apply compat_exp_val.\n  2:{ constructor; assumption.  }\n  1:{ constructor; assumption.  }\n  apply compat_val_query; assumption.\n+ eapply congruence; eauto.\n  eapply compat_exp_app.\n  2:{ apply exp_fundamental. eassumption. }\n  apply He.\n+ eapply congruence; eauto.\n  eapply compat_exp_app.\n  1:{ apply exp_fundamental. eassumption. }\n  apply He.\n+ eapply congruence; eauto.\n  eapply compat_exp_let.\n  2:{ apply exp_fundamental. eassumption. }\n  apply He.\n+ eapply congruence; eauto.\n  eapply compat_exp_let.\n  1:{ apply exp_fundamental. eassumption. }\n  apply He.\n+ eapply congruence; eauto.\n  eapply compat_exp_binop.\n  2:{ apply exp_fundamental. eassumption. }\n  apply He.\n+ eapply congruence; eauto.\n  eapply compat_exp_binop.\n  1:{ apply exp_fundamental. eassumption. }\n  apply He.\n+ eapply congruence; eauto.\n  apply compat_exp_proj. apply He.\n+ eapply congruence; eauto.\n  apply compat_exp_if. apply He.\n  eapply exp_fundamental; assumption.\n  eapply exp_fundamental; assumption.\n  + eapply congruence; eauto.\n    apply compat_exp_if.\n    eapply exp_fundamental; assumption.\n    assumption.\n    eapply exp_fundamental; assumption.\n  + eapply congruence; eauto.\n    apply compat_exp_if.\n    eapply exp_fundamental; assumption.\n    eapply exp_fundamental; assumption.\n    assumption.\n+ eapply congruence; eauto.\n  apply compat_exp_sample. apply He.\n+ eapply congruence; eauto.\n  apply compat_exp_score. apply He.\nQed.\n\nEnd section_congruence.\n\nTheorem soundness (V : Set) (Γ : V → ty) T e₁ e₂ :\nERel_open Γ T e₁ e₂ →\nctx_approx Γ T e₁ e₂.\nProof.\nintro He.\nintros C W.\napply adequacy.\neapply congruence; eassumption.\nQed.\n\nDefinition Ciu_equiv (V : Set) (Γ : V → 𝕋) (τ : 𝕋) (e₁ e₂ : exp V) :=\n(wf_exp Γ e₁ τ ∧ wf_exp Γ e₂ τ) ∧\n∀ γ K, wf_env γ Γ →\nμNS_inf (ktx_plug K (V_bind_exp γ e₁)) = μNS_inf (ktx_plug K (V_bind_exp γ e₂)) ∧\nμTV_sup (ktx_plug K (V_bind_exp γ e₁)) = μTV_sup (ktx_plug K (V_bind_exp γ e₂)).\n\nLemma Ciu_open_antisym :\n∀ (V : Set) (Γ : V → 𝕋) (τ : 𝕋) (e₁ e₂ : exp V),\nCiu_equiv V Γ τ e₁ e₂ →\nCiu_open Γ τ e₁ e₂ ∧ Ciu_open Γ τ e₂ e₁.\nProof.\n  intros V Γ τ e₁ e₂ H.\n  destruct H.\n  split.\n  + split.\n    - tauto.\n    - intros n γ wf_env.\n      split; specialize H0 with (γ := γ) (K := K);\n      apply H0 in wf_env; destruct wf_env.\n      * eapply ennr_le_trans.\n        2:{\n          apply μNS_inf_le_μNS.\n        }\n        rewrite H1.\n        auto.\n      * intro Ev.\n        eapply ennr_le_trans.\n        1:{\n          apply μTV_sup_ge_μTV.\n        }\n        rewrite H2.\n        auto.\n  + split.\n    - tauto.\n    - intros n γ wf_env.\n      split; specialize H0 with (γ := γ) (K := K);\n      apply H0 in wf_env; destruct wf_env.\n      * eapply ennr_le_trans.\n        2:{\n          apply μNS_inf_le_μNS.\n        }\n        rewrite H1.\n        auto.\n      * intro Ev.\n        eapply ennr_le_trans.\n        1:{\n          apply μTV_sup_ge_μTV.\n        }\n        rewrite H2.\n        auto.\nQed.\n\nLemma Ciu_equiv_ctx_equiv :\n∀ V Γ τ e₁ e₂,\n@Ciu_equiv V Γ τ e₁ e₂ → ctx_equiv Γ τ e₁ e₂.\nProof.\n  intros V Γ τ e₁ e₂ H.\n  apply ctx_approx_antisym.\n  split;\n  apply soundness;\n  apply Ciu_in_ERel;\n  apply Ciu_open_antisym in H;\n  tauto.\nQed.", "meta": {"author": "yizhouzhang", "repo": "rrr-popl2022-coq", "sha": "cef22234d660de992f89e151a394e556ddd84831", "save_path": "github-repos/coq/yizhouzhang-rrr-popl2022-coq", "path": "github-repos/coq/yizhouzhang-rrr-popl2022-coq/rrr-popl2022-coq-cef22234d660de992f89e151a394e556ddd84831/coq-src/RRR/Rel/Soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23367837624056526}}
{"text": "\n\n(**\n    VerifiedDSP\n    Copyright (C) {2015}  {Jeremy L Rubin}\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\n**)\n(* Copyright (c) 2011. Greg Morrisett, Gang Tan, Joseph Tassarotti, \n   Jean-Baptiste Tristan, and Edward Gan.\n\n   This file is part of RockSalt.\n\n   This file is free software; you can redistribute it and/or\n   modify it under the terms of the GNU General Public License as\n   published by the Free Software Foundation; either version 2 of\n   the License, or (at your option) any later version.\n*)\n\n\n(** VerifierDFA.v:  \n    This file contains definitions of the parsers used to build the DFAs\n    used in FastVerifier.\n*)\nAdd LoadPath \"../Model\".\nRequire Import Coqlib.\nRequire Import Parser.\nRequire Import Ascii.\nRequire Import String.\nRequire Import List.\nRequire Import Bits.\nRequire Import Hex.\nRequire Import Decode.\nRequire Import Eqdep.\nRequire Import Int32.\nUnset Automatic Introduction.\nSet Implicit Arguments.\nOpen Scope char_scope.\nRequire ExtrOcamlString.\nRequire ExtrOcamlNatBigInt.\nRequire ExtrOcamlNatInt.\nImport i8051_PARSER_ARG.\nImport i8051_PARSER.\nImport i8051_BASE_PARSER.\n\nRequire Import i8051Syntax.\n\n(* In NaCl, ChunkSize is either 16 or 32 *)\nDefinition logChunkSize := 5%nat.\nDefinition chunkSize := two_power_nat logChunkSize.\nNotation int8_of_nat n := (@repr 7 (Z_of_nat n)).\nDefinition safeMask := shl (Word.mone 7) (int8_of_nat logChunkSize).\n\nFixpoint int2bools_aux (bs : Z -> bool) (n: nat) : list bool :=\n  match n with\n    | O => bs 0 :: nil\n    | S n' => bs (Z_of_nat n) :: int2bools_aux bs n'\n  end.\n\nDefinition int_to_bools {s} (x: Word.int s) : list bool :=\n  int2bools_aux (Word.bits_of_Z (s+1) (Word.unsigned x)) s.\n\nDefinition nat2bools(n:nat) : list bool := \n  let bs := Word.bits_of_Z 8 (Z_of_nat n) in\n    (bs 7)::(bs 6)::(bs 5)::(bs 4)::(bs 3)::(bs 2)::(bs 1)::(bs 0)::nil.\n\nDefinition make_dfa t (p:parser t) := build_dfa 256 nat2bools 400 (par2rec p).\nImplicit Arguments make_dfa [t].\n\n\n\nDefinition non_cflow_instrs : list (parser instruction_t) := \n    SETB_p::CLR_p::NOP_p::ANL_p::ADD_p::nil.\n\nDefinition instrs : list (parser instruction_t) := \n    LJMP_p::JMP_p::SETB_p::CLR_p::NOP_p::ANL_p::ADD_p::nil.\nDefinition non_cflow_instr i :=\n  match i with\n      | SETB _ | CLR _ | NOP  | ANL _ _ | ADD _ _ => true\n      | _ => false\n  end.\n(** The list of valid prefix and instruction parsers for non-control-flow\n    operations. *)\n\nDefinition non_cflow_parser := alts non_cflow_instrs.\nDefinition all_parsers := alts instrs.\n\nDefinition non_cflow_parser_list :=\n  (List.map (fun (p:parser instruction_t) =>  p)\n            non_cflow_instrs).\n    (* Direct jumps. Destinations will be checked to see if \n   they are known, valid starts of instructions. *)\n\n(* We only want to allow \"near\" jumps to direct, relative offsets *)\n\nDefinition dir_cflow : list (parser instruction_t) :=\n LJMP_p :: JMP_p ::nil. (* dir_near_JMP_p :: dir_near_Jcc_p :: dir_near_CALL_p :: nil.*)\nImport i8051Syntax.\nLemma register_to_Z_identity1: forall r, Z_to_register (register_to_Z r) = r.\nProof. destruct r; auto.\nQed. \n\nDefinition register_to_bools (r: register) := \n  let bs := Word.bits_of_Z 3 (register_to_Z r) in\n    (bs 2) :: (bs 1) :: (bs 0) :: nil.\n\nFixpoint bitslist (bs: list bool) : parser unit_t :=\n  match bs with\n    | nil => Eps_p\n    | b::bs' => Cat_p (Char_p b) (bitslist bs') @ (fun _ => tt %% unit_t)\n  end.\n\nFixpoint bitslist' (bs: list bool) : string :=\n  match bs with\n    | nil => EmptyString\n    | true::bs' => append \"1\" (bitslist' bs')\n    | false::bs' => append \"0\" (bitslist' bs')\n  end.\n\nDefinition b8 := true::false::false::false::nil.\nDefinition b3 := false::false::true::true::nil.\nDefinition be := true::true::true::false::nil.\nDefinition b0 := false::false::false::false::nil.\nDefinition bf := true::true::true::true::nil.\n\nDefinition mybits := b8 ++ b3 ++ be ++ b0 ++ be ++ b0 ++ bf ++ bf ++ be ++ b0.\n\n\n(* These are akin to the NaCl \"pseudo-instruction\" nacljmp. We will\n   check if the jump destination is appropriately masked by the\n   preceding AND *)\n\n  Fixpoint parseloop ps bytes := \n    match bytes with \n      | nil => None\n      | b::bs => match Decode.i8051_PARSER.parse_byte ps b with \n                   | (ps', nil) => parseloop ps' bs\n                     (* JGM: FIX!  What to do with prefix? *)\n                   | (ps',(LJMP  (Imm_op disp) )::_) => \n                     match bs with \n                       | nil => Some disp\n                       | _ => None\n                     end\n                   | (ps', _) => None\n                 end\n    end.\n\n(** Next, we define a boolean-valued test that tells whether an instruction\n    is a valid non-control-flow instruction.  We should have the property\n    that the [non_cflow_parser] only builds instructions that satisfy this\n    predicate (as shown below.)  Furthermore, we should be able to argue\n    that for each of these instructions, the NaCL SFI invariants are preserved. \n*)\nDefinition no_imm_op(op1:operand) : bool := \n  match op1 with \n    | Imm_op _ => false\n    | _ => true\n  end.\n\n\nDefinition no_prefix (p : prefix) : bool :=  true.\n\n(** We rule out JMPs and CALLs that are far (i.e., not near), that\n    are absolute instead of relative, that don't have an immediate\n    operand, or that have a selector. *)\nDefinition dir_cflow_instr (pre:prefix) (ins: instr) : bool :=\n  match ins with\n    | LJMP (Imm_op _)  => true\n    | _ => false\n  end.\n\n(** This predicate is defined on a pair of prefixes and instructions and\n    captures the legal masked indirect jumps. *)\nDefinition nacljmp_mask_instr (pfx1:prefix) (ins1:instr) (pfx2:prefix) (ins2:instr) :=\n  no_prefix pfx1 && no_prefix pfx2 && \n  match ins1 with\n    | ANL (Reg_op r1) (Imm_op wd) => \n      zeq (Word.signed wd) (Word.signed safeMask) &&\n      (if register_eq_dec r1 r1 then false else true)\n    | _ => false\n  end.\nDefinition nacl_MASK_p : parser (pair_t instruction_t instruction_t):=\n  let imMask := (Imm_op (Word.repr hF0)) in\n  ( bits (\"01010100\"++\"11110000\") @ (fun _ => ANL Acc_op imMask %% instruction_t))\n    $ ((\"01010011\") $$ bitslist' (int_to_bools (@Word.repr 7 Alias.DPL)) $$ bits \"11110000\" @ (fun _ => ANL (Direct_op (Word.repr Alias.DPL)) imMask %% instruction_t)).\n\nDefinition nacl_JMP_p  :=\n  JMP_p.\n  \nDefinition nacljmp_p  :\n  parser (pair_t (pair_t instruction_t instruction_t) instruction_t) :=\n    nacl_MASK_p $ (nacl_JMP_p).\nDefinition nacljmp_mask :\n  list (parser (pair_t (pair_t instruction_t instruction_t) instruction_t))\n  := nacljmp_p :: nil.\n \n\nDefinition dfas := (make_dfa non_cflow_parser, make_dfa (alts dir_cflow), make_dfa (alts nacljmp_mask)).\n(* Extraction \"tables.ml\" dfas.*)\n\n\n", "meta": {"author": "JeremyRubin", "repo": "VerifiedDSP", "sha": "a28fb79035bf5689fb9285c5581d5c1bc1a0b0db", "save_path": "github-repos/coq/JeremyRubin-VerifiedDSP", "path": "github-repos/coq/JeremyRubin-VerifiedDSP/VerifiedDSP-a28fb79035bf5689fb9285c5581d5c1bc1a0b0db/Verif/VerifierDFA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23367837030262317}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\n(** * Implementation of simply-typed interface of the parser *)\nRequire Import Coq.ZArith.ZArith.\nRequire Export Fiat.Parsers.ParserInterface.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Properties.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.BooleanRecognizer Fiat.Parsers.BooleanRecognizerCorrect.\nRequire Import Fiat.Parsers.RecognizerPreOptimized.\nRequire Fiat.Parsers.SimpleRecognizer.\nRequire Fiat.Parsers.SimpleRecognizerExt.\nRequire Fiat.Parsers.SimpleBooleanRecognizerEquality.\nRequire Fiat.Parsers.SimpleRecognizerCorrect.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.BaseTypes Fiat.Parsers.CorrectnessBaseTypes.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Parsers.MinimalParseOfParse.\nRequire Import Fiat.Common.\n\nSet Implicit Arguments.\n\nLocal Open Scope list_scope.\n\nSection implementation.\n  Context {Char}\n          {G : pregrammar' Char}.\n\n  Context (splitter : Splitter G).\n\n  Let predata := @rdp_list_predata _ G.\n  Local Existing Instance predata.\n\n  Let parser_presplit_data : @split_dataT Char (string_type_min splitter) _.\n  Proof.\n    refine {| split_string_for_production idx str\n              := splits_for splitter str idx |}.\n  Defined.\n\n  Local Instance parser_split_data : @split_dataT Char splitter predata\n    := @optsplitdata _ _ _ parser_presplit_data.\n\n  Local Instance preparser_data : @boolean_parser_dataT Char _ :=\n    { predata := rdp_list_predata (G := G);\n      split_data := parser_presplit_data }.\n\n  Local Instance parser_data : @boolean_parser_dataT Char _ :=\n    { predata := rdp_list_predata (G := G);\n      split_data := parser_split_data }.\n\n  Local Arguments split_string_for_production : simpl never.\n\n  Local Obligation Tactic := intros.\n\n  Local Program Instance parser_precompleteness_data : @boolean_parser_completeness_dataT' Char _ _ G preparser_data\n    := { split_string_for_production_complete len0 valid str offset len pf nt Hvalid := _ }.\n  Next Obligation.\n    apply initial_nonterminals_correct in Hvalid.\n    generalize (fun it its idx offset len Hvalid' Heqb n pf pf' pit pits prefix H' => @splits_for_complete Char G splitter str idx offset len Hvalid' Heqb it its n pf pf' (ex_intro _ nt (ex_intro _ prefix (conj Hvalid H'))) pit pits).\n    clear Hvalid.\n    induction (G nt) as [ | x xs IHxs ].\n    { intros; constructor. }\n    { intros H'.\n      simpl.\n      split;\n        [ clear IHxs\n        | apply IHxs; trivial;\n          intros; eapply H'; try eassumption; [ right; eassumption ] ].\n      specialize (fun prefix idx it its H Hvalid' n offset len Heqb pf pf' pit pits => H' it its idx offset len Hvalid' Heqb n pf pf' pit pits prefix (or_introl H)).\n      clear -H' H.\n      induction x as [ | it its IHx ].\n      { simpl; constructor. }\n      { simpl.\n        split;\n          [ clear IHx\n          | apply IHx;\n            intros; subst; eapply (H' (_::_)); try eassumption; reflexivity ].\n        intros idx Hvalid Heqb.\n        specialize (H' nil idx _ _ eq_refl).\n        specialize_by assumption.\n        specialize (H' _ _ H).\n        hnf.\n        intros [ n [ pit pits ] ]; simpl in * |- .\n        destruct (Compare_dec.le_ge_dec n (length (substring offset len str))).\n        { exists n; repeat split; eauto.\n          specialize (fun pf =>\n                        H' _ pf\n                           (parse_of_item__of__minimal_parse_of_item pit)\n                           (parse_of_production__of__minimal_parse_of_production pits)).\n          specialize_by assumption.\n          rewrite Min.min_r by assumption.\n          apply H'; eauto. }\n        { exists (length (substring offset len str)).\n          specialize (H' _ (reflexivity _)).\n          rewrite Min.min_idempotent.\n          rewrite !substring_length_no_min in * by assumption.\n          repeat match goal with\n                   | [ H : context[length (substring _ _ _)] |- _ ] => rewrite !substring_length_no_min in H by assumption\n                 end.\n          pose proof (fun H => expand_minimal_parse_of_item (str' := take len (substring offset len str)) (or_introl (reflexivity _)) (reflexivity _) (or_introl (reflexivity _)) H pit) as pit'; clear pit.\n          pose proof (fun H => expand_minimal_parse_of_production (str' := drop len (substring offset len str)) (or_introl (reflexivity _)) (reflexivity _) (or_introl (reflexivity _)) H pits) as pits'; clear pits.\n          set (s := substring offset len str) in *.\n          specialize_by\n                 (first [ rewrite ?take_long, ?drop_long\n                          by first [ subst s; reflexivity\n                                   | subst s; rewrite substring_length_no_min by assumption; omega ];\n                          reflexivity\n                        | apply bool_eq_empty; rewrite ?drop_length; subst s;\n                          rewrite substring_length_no_min by assumption;\n                          omega ]).\n          specialize_by assumption.\n          repeat split; try assumption.\n          apply H'.\n          { eapply (@parse_of_item__of__minimal_parse_of_item Char splitter _ _ _ _); eassumption. }\n          { eapply (@parse_of_production__of__minimal_parse_of_production Char splitter _ _ _ _ _); eassumption. } } } }\n  Qed.\n\n  Local Instance parser_completeness_data : @boolean_parser_completeness_dataT' Char _ _ G parser_data\n    := optsplitdata_correct.\n\n  Local Obligation Tactic := program_simpl.\n\n  Program Definition parser : Parser G splitter\n    := {| has_parse str := parse_nonterminal (data := parser_data) str (Start_symbol G);\n          parse str := option_map (SimpleParseNonTerminal (Start_symbol G)) (SimpleRecognizer.parse_nonterminal (data := parser_data) str (Start_symbol G));\n          has_parse_sound str Hparse := parse_nonterminal_sound (data := parser_data) _ _ Hparse;\n          has_parse_complete str p := _;\n          parse_sound str p := _ |}.\n  Next Obligation.\n  Proof.\n    dependent destruction p.\n    pose proof (fun pf => @parse_of_nonterminal_complete Char splitter _ _ G _ _ rdp_list_rdata' str (Start_symbol G) pf p) as H'.\n    apply H'; assumption.\n  Qed.\n  Next Obligation.\n  Proof.\n    erewrite SimpleBooleanRecognizerEquality.parse_nonterminal_eq; simpl;\n    unfold option_map.\n    destruct SimpleRecognizer.parse_nonterminal; reflexivity.\n  Qed.\n  Next Obligation.\n  Proof.\n    eapply SimpleRecognizerCorrect.parse_item_correct.\n    unfold option_map in *; simpl in *.\n    unfold SimpleRecognizer.parse_nonterminal, GenericRecognizer.parse_nonterminal in *; simpl in *.\n    rewrite <- H; clear H p.\n    repeat match goal with\n           | _ => reflexivity\n           | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n           | _ => progress simpl in *\n           end.\n    unfold SimpleRecognizer.parse_nonterminal', SimpleRecognizer.parse_nonterminal_or_abort, GenericRecognizer.parse_nonterminal', GenericRecognizer.parse_nonterminal_or_abort in *.\n    let H := match goal with H : context[Fix] |- _ => H end in\n    rewrite Common.Wf1.Fix5_eq\n      in H\n      by (intros; eapply SimpleRecognizerExt.parse_nonterminal_step_ext; assumption);\n      unfold GenericRecognizer.parse_nonterminal_step at 1 in H.\n    simpl in *.\n    edestruct Compare_dec.lt_dec; simpl in *; try omega; [].\n    edestruct dec; simpl in *; try congruence; [].\n    edestruct negb; simpl in *; congruence.\n    Unshelve.\n    assumption.\n    assumption.\n  Qed.\nEnd implementation.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/ParserImplementation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.23361477879485967}}
{"text": "\nRequire Export Iron.Language.SystemF2Effect.Type.\nRequire Export Iron.Language.SystemF2Effect.Value.Exp.\nRequire Export Iron.Language.SystemF2Effect.Value.Relation.Wf.\nRequire Export Iron.Language.SystemF2Effect.Value.Operator.LiftX.\nRequire Export Iron.Language.SystemF2Effect.Store.Prop.\n\n\n(* Store Environment holds the types of locations. *)\nDefinition stenv := list ty.\n\n\n(* Types of primops. \n   We keep this separate from the main typing judgement to make it easy\n   to add new primops. *)\nFixpoint typeOfOp1 (op : op1) : ty\n := match op with\n    | OSucc    => TFun TNat TNat  (TBot KEffect)\n    | OIsZero  => TFun TNat TBool (TBot KEffect)\n    end.\n\n\n(* Types of Value expressions *)\nInductive \n  TYPEV : kienv -> tyenv -> stenv -> stprops \n        -> val  -> ty    -> ty\n        -> Prop := \n\n  (* Variables.\n     We get the type of a variable from the type environment. *)\n  | TvVar\n    :  forall ke te se sp i t\n    ,  get i te = Some t\n    -> KindT  ke sp t KData\n    -> TYPEV  ke te se sp (VVar i) t (TDeepUse t)\n\n  (* Store locations.\n     We get the type of a location from the store typing.\n     The type of a location must be a Reference because we need somewhere\n     to attach the region variable. Our primitive types don't have region\n     annotations themselves. *)\n  | TvLoc \n    :  forall ke te se sp i r t\n    ,  get i se = Some (TRef r t)\n    -> KindT  ke sp       (TRef r t) KData       \n    -> TYPEV  ke te se sp\n              (VLoc i) (TRef r t) (TSum KClosure (TUse r) (TDeepUse t))\n\n  (* Value abstraction.\n     The body is checked in an environment extended with the type of\n     of the formal parameter. *)\n  | TvLam\n    :  forall ke te se sp t1 t2 x2 e2\n    ,  KindT   ke sp t1 KData\n    -> TYPEX  ke (te :> t1) se sp x2 t2 TPure TEmpty\n    -> TYPEV  ke te         se sp (VLam t1 x2) (TFun t1 t2) TEmpty\n\n  (* Type abstraction.\n     The body is checked in an environemnt extended with the kind of\n     the formal parameter. As the parameter kind is pushed onto the base\n     of the kind environment we need to lift any references to kinds \n     higher in the stack across the new one. The body expression must\n     be pure because we don't have anywhere to store the effect of the\n     body in the type of the overall abstraction. This is different for\n     value abstractions, where the function constructor has an effect \n     annotation. *) \n  | TvLAM\n    :  forall ke te se sp k1 t2 x2\n    ,  TYPEX (ke :> k1) (liftTE 0 te) (liftTE 0 se) sp x2 t2 TPure TEmpty\n    -> TYPEV ke te se sp (VLAM k1 x2) (TForall k1 t2) TEmpty\n\n  (* Primitive constants. \n     We get the types of these from the 'typeOfConst' function so we can\n     add new sorts of constants without changing the proof. *)\n  | TvConst\n    :  forall ke te se sp c t\n    ,  t = typeOfConst c\n    -> TYPEV  ke te se sp (VConst c) t\n\n\n  with TYPEX :  kienv -> tyenv -> stenv -> stprops \n             -> exp   -> ty -> ty -> ty\n             -> Prop :=\n\n  (* Embed values in the expression language.\n     All values are pure because they can't be stepped further, which \n     in turn means they can't perform any more effectful actions. *)\n  | TxVal\n    :  forall ke te se sp v1 t1\n    ,  TYPEV  ke te se sp v1 t1\n    -> TYPEX  ke te se sp (XVal v1) t1 (TBot KEffect)\n\n  (* Let-bindings. *)\n  | TxLet\n    :  forall ke te se sp t1 x1 t2 x2 e1 e2\n    ,  KindT  ke sp t1 KData\n    -> TYPEX  ke te         se sp x1 t1 e1\n    -> TYPEX  ke (te :> t1) se sp x2 t2 e2\n    -> TYPEX  ke te         se sp (XLet t1 x1 x2) t2 (TSum e1 e2)\n\n  (* Value application. *)\n  | TxApp\n    :  forall ke te se sp t11 t12 v1 v2 e1\n    ,  TYPEV  ke te se sp v1 (TFun t11 e1 t12) \n    -> TYPEV  ke te se sp v2 t11\n    -> TYPEX  ke te se sp (XApp v1 v2) t12 e1\n\n  (* Type application. *)\n  | TvAPP\n    :  forall ke te se sp v1 k11 t12 t2\n    ,  TYPEV  ke te se sp v1 (TForall k11 t12)\n    -> KindT  ke sp t2 k11\n    -> TYPEX  ke te se sp (XAPP v1 t2) (substTT 0 t2 t12) (TBot KEffect)\n\n  (* Store Operators ******************)\n  (* Create a new region. *)\n  | TxNew\n    :  forall ke te se sp x t tL e eL\n    ,  lowerTT 0 t               = Some tL\n    -> lowerTT 0 (maskOnVarT 0 e) = Some eL\n    -> TYPEX (ke :> KRegion) (liftTE 0 te) (liftTE 0 se) sp x        t  e\n    -> TYPEX ke              te             se           sp (XNew x) tL eL\n\n  (* Allocate a new heap binding. *)\n  | TxOpAlloc \n    :  forall ke te se sp r1 v2 t2\n    ,  KindT  ke sp r1 KRegion\n    -> TYPEV  ke te se sp v2 t2\n    -> TYPEX  ke te se sp (XAlloc r1 v2) (TRef r1 t2) (TAlloc r1)\n\n  (* Read a value from a heap binding. *)\n  | TxOpRead\n    :  forall ke te se sp v1 r1 t2\n    ,  KindT  ke sp r1 KRegion\n    -> TYPEV  ke te se sp v1 (TRef r1 t2)\n    -> TYPEX  ke te se sp (XRead r1 v1)     t2    (TRead r1)\n\n  (* Write a value to a heap binding. *)\n  | TxOpWrite\n    :  forall ke te se sp v1 v2 r1 t2\n    ,  KindT  ke sp r1 KRegion\n    -> TYPEV  ke te se sp v1 (TRef r1 t2)\n    -> TYPEV  ke te se sp v2 t2\n    -> TYPEX  ke te se sp (XWrite r1 v1 v2) TUnit (TWrite r1)\n\n  (* Primtive Operators ***************)\n  | TxOpPrim\n    :  forall ke te se sp op v1 t11 t12 e\n    ,  typeOfOp1 op = TFun t11 t12 e\n    -> TYPEV  ke te se sp v1 t11\n    -> TYPEX  ke te se sp (XOp1 op v1) t12 e.\n\n(*\n  | TxCastEffect\n    :  TYPEX  ke te se sp x t1 e1\n    -> SubsT  ke te se sp x e2 e1          (* also use to fix equiv of effect *)\n    -> TYPEX  ke te se sp x (casteff e2 t1) e2\n*)\nHint Constructors TYPEV.\nHint Constructors TYPEX.\n\n\n(* Invert all hypothesis that are compound typing statements. *)\nLtac inverts_type :=\n repeat \n  (match goal with \n   | [ H: TYPEV _ _ _ _ (VVar   _)     _    |- _ ] => inverts H\n   | [ H: TYPEV _ _ _ _ (VLoc   _)     _    |- _ ] => inverts H\n   | [ H: TYPEV _ _ _ _ (VLam   _ _)   _    |- _ ] => inverts H\n   | [ H: TYPEV _ _ _ _ (VLAM   _ _)   _    |- _ ] => inverts H\n   | [ H: TYPEV _ _ _ _ (VConst _)     _    |- _ ] => inverts H\n   | [ H: TYPEX _ _ _ _ (XVal   _)     _ _  |- _ ] => inverts H\n   | [ H: TYPEX _ _ _ _ (XLet   _ _ _) _ _  |- _ ] => inverts H \n   | [ H: TYPEX _ _ _ _ (XApp   _ _)   _ _  |- _ ] => inverts H \n   | [ H: TYPEX _ _ _ _ (XAPP   _ _)   _ _  |- _ ] => inverts H \n   | [ H: TYPEX _ _ _ _ (XNew   _)     _ _  |- _ ] => inverts H\n   | [ H: TYPEX _ _ _ _ (XAlloc _ _)   _ _  |- _ ] => inverts H\n   | [ H: TYPEX _ _ _ _ (XRead  _ _)   _ _  |- _ ] => inverts H\n   | [ H: TYPEX _ _ _ _ (XWrite _ _ _) _ _  |- _ ] => inverts H\n   | [ H: TYPEX _ _ _ _ (XOp1   _ _)   _ _  |- _ ] => inverts H \n   end).\n\n\n", "meta": {"author": "Warbo", "repo": "iron", "sha": "69997b162a52e07456562d00908ef4791b47a15a", "save_path": "github-repos/coq/Warbo-iron", "path": "github-repos/coq/Warbo-iron/iron-69997b162a52e07456562d00908ef4791b47a15a/devel/Iron/SystemF2Closure/Value/TyJudge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.2335289509776597}}
{"text": "Require Export IGrammar.\nRequire Import MyUtils.\nRequire Import IGrammarTheorems.\n\nSection IGrammarBonusTheorems.\n\nCreate HintDb IGrammar.\nHint Resolve CPrio1 : IGrammar.\nHint Resolve CPrio2 : IGrammar.\nHint Resolve CLeft : IGrammar.\nHint Resolve CRight : IGrammar.\nHint Resolve HMatch : IGrammar.\nHint Resolve InfixMatch : IGrammar.\n\nDefinition safe_cpatterns {O} (pr : drules O) : Prop :=\n  forall (o1 o2 : O), (conflict_pattern pr (CR o1 o2) /\\ conflict_pattern pr (CL o2 o1) -> False).\n\nLemma safe_cpatterns_pr {O} (pr : drules O) :\n  safe_cpatterns pr ->\n  safe_pr pr.\nProof.\n  unfold safe_cpatterns. unfold safe_pr. intros.\n  destruct H0; destruct H1; eapply H; eauto with IGrammar.\nQed.\n\nLemma safe_filter_cpatterns {L O} (pr : drules O) :\n  (exists (l : L), True) ->\n  safe L pr ->\n  safe_cpatterns pr.\nProof.\n  unfold safe, safe_cpatterns. intros. destruct H as [l].\n  inv H1.\n  specialize H0 with [inl l; inr o1; inl l; inr o2; inl l].\n  assert (language [inl l; inr o1; inl l; inr o2; inl l]). {\n    unfold language. exists (InfixNode (InfixNode (AtomicNode l) o1 (AtomicNode l)) o2 (AtomicNode l)).\n    reflexivity.\n  }\n  apply H0 in H1. unfold dlanguage in H1. destruct H1 as [t]. inv H1.\n  destruct t; simplify_list_eq.\n  destruct t1; simplify_list_eq.\n  - destruct t2; simplify_list_eq.\n    destruct t2_1; simplify_list_eq.\n    + destruct t2_2; simplify_list_eq.\n      * inv H5. destruct H7. eexists. eauto with IGrammar.\n      * destruct (yield t2_2_1); simplify_list_eq. destruct w; simplify_list_eq.\n    + destruct (yield t2_1_1); simplify_list_eq.\n      destruct w; simplify_list_eq.\n      * destruct (yield t2_1_2); simplify_list_eq.\n        destruct w; simplify_list_eq.\n      * destruct w; simplify_list_eq.\n        destruct w; simplify_list_eq.\n  - destruct t1_1; simplify_list_eq.\n    + destruct t1_2; simplify_list_eq.\n      * destruct t2; simplify_list_eq.\n        **inv H5. destruct H7. eexists. eauto with IGrammar.\n        **destruct (yield t2_1); simplify_list_eq.\n          destruct w; simplify_list_eq.\n      * destruct (yield t1_2_1); simplify_list_eq.\n        destruct w; simplify_list_eq.\n        **destruct (yield t1_2_2); simplify_list_eq.\n          destruct w; simplify_list_eq.\n        **destruct w; simplify_list_eq.\n          destruct w; simplify_list_eq.\n    + destruct (yield t1_1_1); simplify_list_eq.\n      destruct w; simplify_list_eq.\n      * destruct (yield t1_1_2); simplify_list_eq.\n        destruct w; simplify_list_eq.\n        **destruct (yield t1_2); simplify_list_eq.\n          destruct w; simplify_list_eq.\n        **destruct w; simplify_list_eq.\n          destruct w; simplify_list_eq.\n      * destruct w; simplify_list_eq.\n        destruct w; simplify_list_eq.\n        **destruct (yield t1_1_2); simplify_list_eq.\n          destruct w; simplify_list_eq.\n        **destruct w; simplify_list_eq.\n          destruct w; simplify_list_eq.\nQed.\n\nRecord complete_cpatterns {O} (pr : drules O) := mkCompleteCpatterns {\n  com1 : forall o1 o2, (conflict_pattern pr (CR o1 o2) \\/ conflict_pattern pr (CL o2 o1));\n  com2 : forall o1 o2 o3, conflict_pattern pr (CR o1 o2) ->\n                          conflict_pattern pr (CR o2 o3) ->\n                          conflict_pattern pr (CR o1 o3);\n  com3 : forall o1 o2 o3, conflict_pattern pr (CL o1 o2) ->\n                          conflict_pattern pr (CL o2 o3) ->\n                          conflict_pattern pr (CL o1 o3)\n}.\n\nRecord wf_drules {O} (pr : drules O) := mkWfDrules {\n  wf_drules1 : forall o1 o2 : O, left_a pr o1 o2 /\\ right_a pr o1 o2 -> False;\n  wf_drules2 : forall o1 o2 : O, left_a pr o1 o2 /\\ prio pr o1 o2 -> False;\n  wf_drules3 : forall o1 o2 : O, prio pr o1 o2 /\\ right_a pr o1 o2 -> False;\n}.\n\nLemma complete_cpatterns_pr {O} (pr : drules O) :\n  wf_drules pr ->\n  safe_cpatterns pr ->\n  complete_cpatterns pr ->\n  complete_pr pr.\nProof.\n  intros. apply mkComplete_pr; intros.\n  - inv H1. specialize com4 with o1 o2. destruct com4.\n    + inv H1; auto.\n    + inv H1; auto.\n  - inv H1. specialize com5 with o1 o2 o3. specialize com6 with o1 o2 o3.\n    apply CPrio1 in H2 as ?. apply CPrio2 in H2 as ?. apply CPrio1 in H3 as ?. apply CPrio2 in H3 as ?.\n    apply com5 in H4; auto. apply com6 in H1; auto.\n    inv H1; auto. inv H4; auto.\n    exfalso. eapply H; eauto.\n  - apply CPrio1 in H2 as ?. apply CPrio2 in H2 as ?. apply CLeft in H3.\n    inv H1. eapply com5 in H3 as ?; eauto.\n    inv H1; eauto.\n    specialize com4 with o3 o1. destruct com4.\n    + eapply com5 in H1; eauto. exfalso. eapply H0; eauto.\n    + inv H1; auto.\n      exfalso. eapply H; eauto.\n  - apply CPrio1 in H2 as ?. apply CPrio2 in H2 as ?. apply CRight in H3.\n    inv H1. eapply com6 in H3 as ?; eauto.\n    inv H1; eauto.\n    specialize com4 with o1 o3. destruct com4.\n    + inv H1; auto.\n      exfalso. eapply H; eauto.\n    + eapply com6 in H1; eauto. exfalso. eapply H0; eauto.\n  - apply CLeft in H2. apply CPrio1 in H3 as ?. apply CPrio2 in H3.\n    inv H1. eapply com5 in H3 as ?; eauto.\n    inv H1; eauto.\n    specialize com4 with o3 o1. destruct com4.\n    + exfalso. eauto.\n    + inv H1; eauto. exfalso. eapply H. eauto.\n  - apply CLeft in H2 as ?. apply CLeft in H3 as ?. inv H1.\n    eapply com5 in H5 as ?; eauto. inv H1; auto. apply CPrio1 in H7 as ?.\n    exfalso.\n    specialize com4 with o2 o1 as ?. destruct H6.\n    + specialize com4 with o3 o2 as ?. destruct H8.\n      * eapply com5 in H6; eauto.\n      * inv H. inv H8; eauto.\n    + inv H. inv H6; eauto.\n  - apply CLeft in H2 as ?. apply CRight in H3 as ?.\n    inv H1. specialize com4 with o1 o3 as ?. destruct H1; eauto.\n    inv H. apply H0 with o2 o3. split; auto.\n    + apply com5 with o1; auto.\n      specialize com4 with o2 o1. destruct com4; auto. exfalso. inv H; eauto.\n    + specialize com4 with o2 o3. destruct com4; auto. exfalso. inv H; eauto.\nQed.\n\nLtac cp_cases H := eapply conflict_pattern_cases in H; try eassumption; intros; subst.\n\nLemma complete_filter_cpatterns {L O} (pr : drules O) :\n  safe_cpatterns pr ->\n  (exists (l : L), True) ->\n  complete L pr ->\n  complete_cpatterns pr.\nProof.\n  intros. destruct H0 as [l]. unfold complete in H1.\n  apply mkCompleteCpatterns; intros.\n  - specialize H1 with\n      (InfixNode (AtomicNode l) o1 (InfixNode (AtomicNode l) o2 (AtomicNode l)))\n      (InfixNode (InfixNode (AtomicNode l) o1 (AtomicNode l)) o2 (AtomicNode l)).\n    simpl in H1.\n    destruct (is_conflict_pattern pr (CR o1 o2)) eqn:E1; try apply is_conflict_pattern_true in E1; auto.\n    apply is_conflict_pattern_false in E1.\n    destruct (is_conflict_pattern pr (CL o2 o1)) eqn:E2; try apply is_conflict_pattern_true in E2; auto.\n    apply is_conflict_pattern_false in E2.\n    assert ([inl l; inr o1; inl l; inr o2; inl l] = [inl l; inr o1; inl l; inr o2; inl l]). {\n      reflexivity.\n    }\n    apply H1 in H2.\n    + inv H2.\n    + apply Infix_cf; auto using Atomic_cf.\n      * intro. inv H3. inv H4. cp_cases H3; inv H5.\n        **inv H7.\n        **inv H12. contradiction.\n      * apply Infix_cf; auto using Atomic_cf.\n        intro. inv H3. inv H4. cp_cases H3; inv H5.\n        **inv H7.\n        **inv H12.\n    + apply Infix_cf; auto using Atomic_cf.\n      * intro. inv H3. inv H4. cp_cases H3.\n        **inv H5. inv H7. contradiction.\n        **inv H5. inv H12.\n      * apply Infix_cf; auto using Atomic_cf.\n        intro. inv H3. inv H4. cp_cases H3; inv H5.\n        **inv H7.\n        **inv H12.\n  - specialize H1 with\n      (InfixNode (InfixNode (InfixNode (AtomicNode l) o1 (AtomicNode l)) o2 (AtomicNode l)) o3 (AtomicNode l))\n      (InfixNode (AtomicNode l) o1 (InfixNode (InfixNode (AtomicNode l) o2 (AtomicNode l)) o3 (AtomicNode l))).\n    simpl in H1.\n    destruct (is_conflict_pattern pr (CR o1 o3)) eqn:E; try apply is_conflict_pattern_true in E; auto.\n    apply is_conflict_pattern_false in E. exfalso.\n    unfold safe_cpatterns in H.\n    assert (~ conflict_pattern pr (CL o2 o1)); eauto.\n    assert (~ conflict_pattern pr (CL o3 o2)); eauto.\n    assert ([inl l; inr o1; inl l; inr o2; inl l; inr o3; inl l]\n            = [inl l; inr o1; inl l; inr o2; inl l; inr o3; inl l]); auto.\n    apply H1 in H6.\n    + inv H6.\n    + apply Infix_cf; auto using Atomic_cf.\n      * intro. inv H7. inv H8. cp_cases H7; inv H9. inv H11. contradiction. inv H16.\n      * apply Infix_cf; auto using Atomic_cf.\n        **intro. inv H7. inv H8. cp_cases H7; inv H9. inv H11. contradiction. inv H16.\n        **apply Infix_cf; auto using Atomic_cf.\n          intro. inv H7. inv H8. cp_cases H7; inv H9. inv H11. inv H16.\n    + apply Infix_cf; auto using Atomic_cf.\n      * intro. inv H7. inv H8. cp_cases H7; inv H9. inv H11. inv H16. contradiction.\n      * apply Infix_cf; auto using Atomic_cf.\n        **intro. inv H7. inv H8. cp_cases H7; inv H9. inv H11. contradiction. inv H16.\n        **apply Infix_cf; auto using Atomic_cf.\n          intro. inv H7. inv H8. cp_cases H7; inv H9. inv H11. inv H16.\n  - specialize H1 with\n      (InfixNode (AtomicNode l) o3 (InfixNode (AtomicNode l) o2 (InfixNode (AtomicNode l) o1 (AtomicNode l))))\n      (InfixNode (InfixNode (AtomicNode l) o3 (InfixNode (AtomicNode l) o2 (AtomicNode l))) o1 (AtomicNode l)).\n    simpl in H1.\n    destruct (is_conflict_pattern pr (CL o1 o3)) eqn:E; try apply is_conflict_pattern_true in E; auto.\n    apply is_conflict_pattern_false in E. exfalso.\n    unfold safe_cpatterns in H.\n    assert (~ conflict_pattern pr (CR o2 o1)); eauto.\n    assert (~ conflict_pattern pr (CR o3 o2)); eauto.\n    assert ([inl l; inr o3; inl l; inr o2; inl l; inr o1; inl l]\n            = [inl l; inr o3; inl l; inr o2; inl l; inr o1; inl l]); auto.\n    apply H1 in H6.\n    + inv H6.\n    + apply Infix_cf; auto using Atomic_cf.\n      * intro. inv H7. inv H8. cp_cases H7; inv H9. inv H11. inv H16. contradiction.\n      * apply Infix_cf; auto using Atomic_cf.\n        **intro. inv H7. inv H8. cp_cases H7; inv H9. inv H11. inv H16. contradiction.\n        **apply Infix_cf; auto using Atomic_cf.\n          intro. inv H7. inv H8. cp_cases H7; inv H9. inv H11. inv H16.\n    + apply Infix_cf; auto using Atomic_cf.\n      * intro. inv H7. inv H8. cp_cases H7; inv H9. inv H11. contradiction. inv H16.\n      * apply Infix_cf; auto using Atomic_cf.\n        **intro. inv H7. inv H8. cp_cases H7; inv H9. inv H11. inv H16. contradiction.\n        **apply Infix_cf; auto using Atomic_cf.\n          intro. inv H7. inv H8. cp_cases H7; inv H9. inv H11. inv H16.\nQed.\n\nEnd IGrammarBonusTheorems.\n", "meta": {"author": "metaborg", "repo": "disamb-verification", "sha": "e7fecc14f2c85879ae4b1e50849b86d1e3ce4c15", "save_path": "github-repos/coq/metaborg-disamb-verification", "path": "github-repos/coq/metaborg-disamb-verification/disamb-verification-e7fecc14f2c85879ae4b1e50849b86d1e3ce4c15/IGrammarBonusTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.23346905553266567}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import List.\nRequire Import DistributedReferenceCounting.machine2.invariant8.\n\nUnset Standard Proposition Elimination Names.\n\n(** \n\nHere, we study liveness of the algorithm.\nWe prove \n\n1. If there is a message in a queue, there always exists a transition\n   that can consume that message.\n\n2. We can define notion of measure and prove that every transition\n   (except copy) decrease the mesure.\n  \n3. Then, the idea was to use the notion of well_found relation so\n   a to prove that if we prevent copy transitions, we always reach\n   a final configuration where no message can be processed.\n\n   There was a bit of 'coding' to use these well-founded relations.\n   \n   I needed to talk about configuration which were legal.  So\n   I defined a inductive type (a strong dependent sum), legal_config,\n   which contains a configuration and a proof that it is legal.\n\n   I then reached two problems, one easy to solve (I think), and\n   more difficult.\n\n   a.  I need to convert Z numbers into nat, and I don;t know\n       how to do it.\n      I had to assume the existence of the following axiom:\n     Axiom Z_nat_axiom:\n    (x,y:Z)  `0<=x` -> `0<=y` -> `y<x` -> (lt (convert_to_nat y) (convert_to_nat x)).\n\n   b.  Well founded relations must be decidable:\n      Definition decidable_relation:=\n      [E:Set] [R:E->E->Prop] (x:E){y:E | (R y x)}+{((y:E)~(R y x))}.\n\n     In order to prove that, I had to eliminate H in lemma decidable_no_copy_succ.\n\n     H : (EX t:(class_trans c) | ~(copy_p c t)/\\(legal (transition c t)))\n          \\/((t:(class_trans c))(copy_p c t))\n \n     Unfortunately, H is a propositition and  and the Well founded\n     relation is a set.  Therefore, we cannot perform an elimination.\n  \n     So I assumed I has axioms ex_rec and or_rec.  \n     Why was legal defined as a Config->Prop and not a set?\n     Why not do everything with set?\n\n\n  BUT, HAVE I PROVED that all no_copy sequences terminate?\n\nThere are still more things to prove:\n- what's happening when we introduce copy, can we say\n  anything about infinite transitions?\n\n*)\n\n\n\n\nLemma always_process_messages :\n forall c : Config,\n legal c ->\n forall (s1 s2 : Site) (m : Message),\n first Message (bm c s1 s2) = value Message m ->\n exists t : class_trans c,\n   legal (transition c t) /\\\n   bm (transition c t) s1 s2 = first_out Message (bm c s1 s2).\nProof.\n  intros c H.\n  generalize H.\n  elim H.\n  simpl in |- *.\n  intros; discriminate.\n  \n  intros c0 t H0 H1 H2 s1 s2 m.\n  case m.\n  \n  (* dec *)\n  \n  intro.\n  split with (receive_dec (transition c0 t) s1 s2 H3).\n  split.\n  apply after.\n  auto.\n  \n  simpl in |- *.\n  rewrite collect_here.\n  auto.\n  \n  (* inc_dec *)\n  \n  intros.\n  case (eq_site_dec s2 owner); intro.\n  rewrite e in H3.\n  split with (receive_inc (transition c0 t) s1 s H3).\n  split.\n  apply after.\n  auto.\n  \n  simpl in |- *.\n  rewrite post_elsewhere.\n  rewrite e.\n  rewrite collect_here.\n  auto.\n  \n  left; unfold not in |- *; intro.\n  generalize H3; rewrite H4; rewrite empty_q_to_me.\n  simpl in |- *.\n  intro; discriminate.\n  \n  auto.\n  \n  generalize (inc_dec_owner3 (transition c0 t) s1 s2 H2 n); intro.\n  elim (H4 s).\n  apply first_in.\n  auto.\n\n  (* copy *)\n  \n  elim (decide_rt (transition c0 t) s2); intro.\n  case (eq_site_dec s1 owner); intro.\n  intro.\n  rewrite e in H3.\n  split with (receive_copy2 (transition c0 t) s2 a H3).\n  split.\n  apply after.\n  auto.\n  \n  simpl in |- *.\n  rewrite e; rewrite collect_here; auto.\n  \n  intro.\n  cut (s2 <> owner).\n  intro.\n  split with (receive_copy3 (transition c0 t) s1 s2 a n H4 H3).\n  split.\n  apply after.\n  auto.\n  \n  simpl in |- *.\n  rewrite post_elsewhere.\n  rewrite collect_here; auto.\n  left. (* (Left; Auto). *)\n  unfold not in |- *; intro; generalize H3.\n  rewrite H5; rewrite empty_q_to_me.\n  simpl in |- *; intro.\n  discriminate.\n  \n  auto.\n  \n  unfold not in |- *; intro; generalize a.\n  rewrite H4; rewrite owner_rt_true.\n  auto with bool.\n  \n  auto.\n  \n  intro.\n  split with (receive_copy1 (transition c0 t) s1 s2 b H3).\n  split.\n  apply after; auto.\n  \n  simpl in |- *.\n  rewrite post_elsewhere.\n  rewrite collect_here.\n  auto.\n  \n  case (eq_site_dec s1 s2); intro.\n  generalize H3; rewrite e; rewrite empty_q_to_me.\n  simpl in |- *; intro; discriminate.\n  \n  auto.\n  \n  auto.\nQed.\n\n(* copy predicate *)\n\nDefinition copy_p (c : Config) (t : class_trans c) :=\n  match t with\n  | make_copy s1 s2 h1 h2 => True\n  | _ => False\n  end.\n\n\nSection LEGAL_NO_COPY.\n\n(** this inductive definition defines legal_no_copy\n   as a predicate over a configuration c, which is accessible\n   with legal transitions from a legal config c0,\n   without using any copy transition *)\n\nVariable c0 : Config.\n\n\n\nInductive legal_no_copy : Config -> Prop :=\n  | no_copy_init : legal c0 -> legal_no_copy c0\n  | after_no_copy :\n      forall (c : Config) (t : class_trans c),\n      ~ copy_p c t -> legal_no_copy c -> legal_no_copy (transition c t).\n\nEnd LEGAL_NO_COPY.\n\n\nLemma legal_no_copy_is_legal :\n forall c c0 : Config, legal_no_copy c0 c -> legal c.\nProof.\n  intros.\n  elim H.\n  auto.\n  intros.\n  apply after.\n  auto.\nQed.\n\n\nLemma decide_empty_queue :\n forall (c : Config) (s1 s2 : Site),\n {bm c s1 s2 = empty Message} + {bm c s1 s2 <> empty Message}.\nProof.\n  intros.\n  elim (bm c s1 s2).\n  left; auto.\n  \n  simpl in |- *; right.\n  discriminate.\nQed.\n\n\nDefinition no_message (c : Config) :=\n  forall s1 s2 : Site, In s1 LS -> In s2 LS -> bm c s1 s2 = empty Message.\n\nLemma decide_no_message :\n forall c : Config, {no_message c} + {~ no_message c}.\nProof.\n  intros.\n  unfold no_message in |- *.\n  simpl in |- *.\n  pattern LS at 1 3 in |- *.\n  elim LS.\n  simpl in |- *.\n  left; intros; contradiction.\n  \n  simpl in |- *.\n  intros.\n  elim H.\n  clear H.\n  elim LS.\n  simpl in |- *.\n  intro.\n  left.\n  intros; contradiction.\n  \n  intros.\n  elim H.\n  intros.\n  elim (decide_empty_queue c a a0); intro.\n  left.\n  simpl in |- *.\n  intros.\n  elim H0; intro.\n  elim H1; intro.\n  rewrite <- H2; rewrite <- H3; auto.\n  \n  apply a2.\n  auto.\n  \n  auto.\n  \n  elim H1; intro.\n  apply a1.\n  auto.\n  \n  simpl in |- *.\n  auto.\n  \n  apply a2.\n  auto.\n  \n  auto.\n  \n  right.\n  unfold not in |- *.\n  intro.\n  generalize (H0 a a0).\n  intro.\n  elim b.\n  apply H1.\n  auto.\n  \n  simpl in |- *; auto.\n  \n  intro.\n  right.\n  unfold not in |- *; intro.\n  elim b.\n  intros.\n  apply H0.\n  auto.\n  \n  simpl in |- *; auto.\n  \n  intros.\n  apply a1.\n  auto.\n  \n  simpl in |- *; auto.\n  \n  intro.\n  right.\n  unfold not in |- *; intro.\n  elim b.\n  intros.\n  apply H0.\n  auto.\n  \n  auto.\nQed.\n\nLemma decide_exist_non_empty_queue1 :\n forall (c : Config) (a : Site),\n legal c ->\n {(forall s2 : Site, In s2 LS -> bm c a s2 = empty Message)} +\n {~ (forall s2 : Site, In s2 LS -> s2 <> a -> bm c a s2 = empty Message)}.\nProof.\n  intros.\n  elim LS.\n  simpl in |- *.\n  left; intros; contradiction.\n  \n  simpl in |- *.\n  intros.\n  elim (decide_empty_queue c a a0); intro.\n  case (eq_site_dec a a0); intro.\n  elim H0; intro.\n  left; intros.\n  elim H1; intros.\n  rewrite <- H2.\n  auto.\n  \n  apply a2.\n  auto.\n  \n  right.\n  unfold not in |- *; intros.\n  elim b; intros.\n  unfold not in |- *.\n  apply H1.\n  auto.\n  \n  intro.\n  elim H3; auto.\n  \n  elim H0; intros.\n  left; intros.\n  case (eq_site_dec s2 a0); intro.\n  rewrite e; auto.\n  \n  elim H1; intro.\n  elim n0; auto.\n  \n  apply a2; auto.\n  \n  right.\n  unfold not in |- *; intros.\n  elim b; intros.\n  unfold not in |- *.\n  apply H1.\n  auto.\n  \n  intro; elim H3; auto.\n  \n  elim H0; intros.\n  case (eq_site_dec a a0); intro.\n  elim b.\n  rewrite e.\n  rewrite empty_q_to_me.\n  auto.\n  \n  auto.\n  \n  right.\n  unfold not in |- *; intros.\n  generalize (H1 a0); intro.\n  cut (a0 = a0 \\/ In a0 l).\n  intro.\n  generalize (H2 H3); intro.\n  decompose [and] H4.\n  elim b; auto.\n  \n  auto.\n  \n  right.\n  unfold not in |- *; intro.\n  elim b0.\n  unfold not in |- *; intros.\n  apply H1.\n  auto.\n  \n  auto.\n\nQed.\n\n\nLemma exist_non_empty_queue :\n forall c : Config,\n legal c ->\n ~ no_message c ->\n exists s1 : Site,\n   (exists s2 : Site, s1 <> s2 /\\ bm c s1 s2 <> empty Message).\n\nProof.\n  unfold no_message in |- *.\n  intro.\n  pattern LS at 1 in |- *.\n  elim LS.\n  simpl in |- *.\n  intros.\n  elim H0.\n  intros; contradiction.\n  \n  simpl in |- *.\n  intros a l H HLeg.\n  elim (decide_exist_non_empty_queue1 c a HLeg); intro.\n  intro.\n  apply H.\n  auto.\n  \n  unfold not in |- *; intro.\n  elim H0; intros.\n  elim H2; intro.\n  rewrite <- H4.\n  apply a0.\n  auto.\n  \n  apply H1.\n  auto.\n  \n  auto.\n  \n  intros.\n  split with a.\n  generalize b.\n  elim LS.\n  simpl in |- *.\n  intro.\n  elim b0; intros; contradiction.\n  \n  clear H.\n  clear H0.\n  clear b.\n  simpl in |- *.\n  intros.\n  elim (decide_empty_queue c a a0); intro.\n  apply H.\n  unfold not in |- *; intros.\n  elim b; intros.\n  elim H1; intro.\n  rewrite <- H3; auto.\n  \n  apply H0.\n  auto.\n  \n  auto.\n  \n  case (eq_site_dec a a0); intro.\n  elim b0; rewrite e; rewrite empty_q_to_me; auto.\n  \n  split with a0.\n  split; auto.\nQed.\n\n\n(**\n\nDefine a measure:\n  for instance: 2 for inc_dec\n                1 for dec.\n                2 for rt=true\n  Show that any legal_no_copy transition\n  decreases the measure.\n  By induction, there is a minimum.\n*)\n\n\nDefinition termination_count (m : Message) :=\n  match m with\n  | copy => 5%Z\n  | dec => 1%Z\n  | inc_dec s3 => 2%Z\n  end.\n\nDefinition termination_q_count (s1 s2 : Site) (q : queue Message) :=\n  reduce Message termination_count q.\n\nDefinition termination_q_measure (bm : Bag_of_message) :=\n  sigma2_table Site LS LS (queue Message) termination_q_count bm.\nDefinition termination_rt_count (b : bool) := if b then 2%Z else 0%Z.\n\nDefinition termination_rt_measure (t : Site -> bool) :=\n  sigma_table Site LS Z (Z_id Site)\n    (fun s : Site => termination_rt_count (t s)).\n\nDefinition termination_measure (c : Config) :=\n  (termination_rt_measure (rt c) + termination_q_measure (bm c))%Z.\n\nInductive legal_no_copy2 : Config -> Config -> Prop :=\n  | no_copy_init2 : forall c : Config, legal c -> legal_no_copy2 c c\n  | after_no_copy2 :\n      forall (c c0 : Config) (t : class_trans c),\n      ~ copy_p c t ->\n      legal_no_copy2 c c0 -> legal_no_copy2 (transition c t) c0.\n\n\nLemma legal_no_copy_transitive2 :\n forall c0 : Config,\n legal c0 ->\n forall c1 c2 : Config,\n legal_no_copy2 c1 c0 -> legal_no_copy2 c2 c1 -> legal_no_copy2 c2 c0.\nProof.\n  intros.\n  generalize H0.\n  elim H1.\n  auto.\n  \n  intros.\n  apply after_no_copy2.\n  auto.\n  \n  apply H4.\n  auto.\nQed.\n\nRemark add_reduce2 :\n forall x y z a : Z, x = a -> (x + (y + z))%Z = (a + y + z)%Z.\nProof.\nintros; omega.\nQed.\n\nRemark add_reduce3 :\n forall x y z a : Z, x = a -> y = z -> (x + y)%Z = (a + z)%Z.\nProof.\nintros; omega.\nQed.\n\nRemark add_reduce10 :\n forall x y w z a : Z,\n w = y -> (a > 0)%Z -> (x + (y + (z - a)) < x + (w + z))%Z.\nProof.\nintros; omega.\nQed.\n\nRemark add_reduce11 :\n forall x1 x2 y w z a b : Z,\n x1 = x2 ->\n w = y -> (b - a < 0)%Z -> (x1 + b + (y + (z - a)) < x2 + (w + z))%Z.\nProof.\nintros; omega.\nQed.\n\nRemark add_reduce12 : forall x y : Z, x = y -> x = (y + 0)%Z.\nProof.\nintros; omega.\nQed.\n\nRemark add_reduce13 :\n forall x1 x2 y w z a b : Z,\n x1 = x2 ->\n w = y -> (b + a < 0)%Z -> (x1 + b + (y + (z + a)) < x2 + (w + z))%Z.\nProof.\nintros; omega.\nQed.\n\n\nRemark add_reduce14 :\n forall x1 x2 x3 y w z a b : Z,\n x1 = x2 ->\n w = y -> (b + a < x3)%Z -> (x1 + b + (y + (z + a)) < x2 + x3 + (w + z))%Z.\nProof.\nintros; omega.\nQed.\n\n\nRemark add_reduce15 : forall x y a : Z, (x < y)%Z -> (a + x < a + y)%Z.\nProof.\nintros; omega.\nQed.\n\nRemark add_reduce16 :\n forall x1 x2 y b : Z,\n x1 = x2 -> (1 - b < 0)%Z -> (x1 - b + (y + 1) < x2 + y)%Z.\nProof.\nintros; omega.\nQed.\n\nRemark add_reduce17 : forall x y a : Z, x = y -> (x + a)%Z = (y + a)%Z.\nProof.\nintros; omega.\nQed.\n\nRemark add_reduce18 : forall x y a : Z, x = y -> a = 0%Z -> x = (y + a)%Z.\nProof.\nintros; omega.\nQed.\n\nRemark add_reduce19 :\n forall x1 x2 x3 y1 y2 y3 y4 : Z,\n x1 = y1 ->\n (y2 - y4 + (y3 + 1) < x2 + x3)%Z ->\n (y1 + (y2 - y4) + (y3 + 1) < x1 + x2 + x3)%Z.\nProof.\nintros; omega.\nQed.\n\nRemark add_reduce22 :\n forall a b x0 y0 x1 x2 x3 y1 y2 y3 y4 : Z,\n x1 = y1 ->\n a = b ->\n (x0 + (y2 - y4) + (y3 + 2) < y0 + x2 + x3)%Z ->\n (a + x0 + (y1 + (y2 - y4) + (y3 + 2)) < b + y0 + (x1 + x2 + x3))%Z.\nProof.\nintros; omega.\nQed.\n\nRemark add_reduce23 :\n forall x y : Z, (x >= 0)%Z -> (y >= 0)%Z -> (0 <= x + y)%Z.\nProof.\nintros; omega.\nQed.\n\n(* \nSection BUT_XY.\n\nVariable Data: Set.\nLocal Table2:=  Site ->  Site -> Data.\nVariable f: Site -> Site -> Data->Z.\n\n\nLemma sigma2_sigma2_but_x_y:\n (s0,s1:Site) (t:Table2)\n (sigma2_table Site LS LS Data f t) = `(sigma2_but_table Site eq_site_dec LS LS Data s0 s1 f t) \n                                       + (f s0 s1 (t s0 s1))`.\nProof.\n  Intro.\n  Intro.\n  Intro.\n  Generalize (finite_site s1).\n  Generalize (finite_site s0).\n  (Pattern 1 3 5 LS; Elim LS).\n  Simpl.\n  (Intros; Contradiction).\n  \n  Intros.\n  Unfold sigma2_table sigma2_but_table.\n  Simpl.\n  (Case (eq_site_dec a s0); Intro).\n  Unfold sigma_table.\n  Rewrite (sigma_sigma_but Site a eq_site_dec).\n  Rewrite (sigma_sigma_but Site a eq_site_dec) with l:=(cons a l).\n  Simpl.\n  Case (eq_site_dec a a).\n  Intro.\n  Case (eq_site_dec a s0).\n  Intro.\n  Rewrite <- sigma_sigma_but_not_in with x0:=a.\n  Rewrite <- sigma_sigma_but_not_in with x0:=a.\n  Rewrite (sigma_sigma_but Site s1 eq_site_dec) with l:=LS.\n  Unfold sigma_but_table.\n  Rewrite e1.\n  Unfold Z_id.\n  Apply add_reduce2.\n  Apply sigma_simpl.\n  Intros.\n  Case (eq_site_dec x s0).\n  Intro.\n  (Generalize H0; Rewrite e1).\n  Simpl.\n  (Case (eq_site_dec s0 s0); Intro).\n  Intro.\n  (Elim H3; Rewrite <- e2; Auto).\n  \n  (Elim n; Auto).\n  \n  Intro.\n  Auto.\n  \n  Auto.\n  \n  (Generalize H0; Simpl).\n  Rewrite e.\n  (Case (eq_site_dec s0 s0); Intro).\n  Auto.\n  \n  (Elim n; Auto).\n  \n  (Generalize H0; Simpl).\n  (Case (eq_site_dec s0 a); Intro).\n  (Rewrite e; Auto).\n  \n  (Elim n; Auto).\n  \n  Intro.\n  (Elim n; Auto).\n  \n  Intro.\n  (Elim n; Auto).\n  \n  (Rewrite e; Auto).\n  (Generalize H0; Rewrite e; Auto).\n  \n  (Generalize H0; Rewrite e).\n  Auto.\n  \n  (Unfold sigma_table; Simpl).\n  Generalize H.\n  Unfold sigma2_table.\n  Unfold sigma_table.\n  Intro.\n  Rewrite H2.\n  (Unfold Z_id; Simpl).\n  (Case (eq_site_dec a s0); Intro).\n  (Elim n; Auto).\n  \n  Unfold sigma2_but_table.\n  Unfold sigma_table.\n  Unfold Z_id.\n  Omega.\n  \n  (Generalize H0; Simpl).\n  (Case (eq_site_dec s0 a); Intro).\n  (Elim n; Auto).\n  \n  Auto.\n  \n  Auto.\n    \nSave.\n\nLemma sigma2_but_simpl : (s0,s1:Site) (t:Table2) (f,g:Site->Site->Data->Z)\n ((x,y:Site) ~((x=s0)/\\(y=s1))->(f x y (t x y))=(g x y (t x y)))->\n  (sigma2_but_table Site eq_site_dec LS LS Data s0 s1 f t)\n  =\n  (sigma2_but_table Site eq_site_dec LS LS Data s0 s1 g t ).\nProof.\n  Intros.\n  Generalize (finite_site s1).\n  Generalize (finite_site s0).\n  (Pattern 1 3 5 LS; Elim LS).\n  Simpl.\n  (Intros; Contradiction).\n  \n  Simpl.\n  Intros a l.\n  (Case (eq_site_dec s0 a); Intro).\n  Rewrite e.\n  Simpl.\n  Intros.\n  Unfold sigma2_but_table.\n  (Unfold sigma_table; Simpl).\n  Unfold Z_id.\n  (Case (eq_site_dec a a); Intro).\n  Apply add_reduce3.\n  Generalize H2.\n  (Elim LS; Simpl).\n  (Intro; Contradiction).\n  \n  Intros.\n  (Unfold sigma_but_table; Simpl).\n  Generalize H4.\n  (Case (eq_site_dec a0 s1); Intro).\n  Rewrite e1.\n  (Case (eq_site_dec s1 s1); Intros).\n  Rewrite <- (sigma_sigma_but_not_in Site s1 eq_site_dec).\n  Rewrite <- (sigma_sigma_but_not_in Site s1 eq_site_dec).\n  Apply sigma_simpl.\n  Intros.\n  Apply H.\n  (Unfold not; Intro).\n  Decompose [and] H7.\n  (Elim H5; Rewrite <- H10; Auto).\n  \n  Auto.\n  \n  Exact H5.\n  \n  (Elim n; Auto).\n  \n  (Case (eq_site_dec s1 a0); Intro).\n  (Elim n; Auto).\n  \n  Intros.\n  Apply add_reduce3.\n  Apply H.\n  (Unfold not; Intro).\n  Decompose [and] H6.\n  (Elim n; Auto).\n  \n  Generalize H3.\n  Unfold sigma_but_table.\n  Auto.\n  \n  Apply sigma_simpl.\n  Intros.\n  (Case (eq_site_dec x a); Intro).\n  (Elim H1; Rewrite <- e1; Auto).\n  \n  Apply sigma_simpl.\n  Intros.\n  Apply H.\n  (Unfold not; Intro).\n  (Decompose [and] H5; Elim n; Rewrite <- e; Auto).\n  \n  (Elim n; Auto).\n  \n  Unfold sigma2_but_table.\n  (Unfold sigma_table; Simpl).\n  Intros.\n  (Case (eq_site_dec a s0); Intro).\n  (Elim n; Auto).\n  \n  Rewrite H0.\n  Apply add_reduce3.\n  Unfold Z_id.\n  Apply sigma_simpl.\n  Intros.\n  Apply H.\n  (Unfold not; Intro; Elim n0).\n  (Decompose [and] H4; Auto).\n  \n  Auto.\n  \n  Auto.\n  \n  Auto.\n\nSave.\n\n(* Interestingly, the proof of the following Lemma is exactly the same\nas the proof of the previous lemma *)\n\nLemma sigma2_but_simpl2 : (s0,s1:Site) (t1,t2:Table2) (f:Site->Site->Data->Z)\n ((x,y:Site) ~((x=s0)/\\(y=s1))->(f x y (t1 x y))=(f x y (t2 x y)))->\n  (sigma2_but_table Site eq_site_dec LS LS Data s0 s1 f t1)\n  =\n  (sigma2_but_table Site eq_site_dec LS LS Data s0 s1 f t2 ).\nProof.\n  Intros.\n  Generalize (finite_site s1).\n  Generalize (finite_site s0).\n  (Pattern 1 3 5 LS; Elim LS).\n  Simpl.\n  (Intros; Contradiction).\n  \n  Simpl.\n  Intros a l.\n  (Case (eq_site_dec s0 a); Intro).\n  Rewrite e.\n  Simpl.\n  Intros.\n  Unfold sigma2_but_table.\n  (Unfold sigma_table; Simpl).\n  Unfold Z_id.\n  (Case (eq_site_dec a a); Intro).\n  Apply add_reduce3.\n  Generalize H2.\n  (Elim LS; Simpl).\n  (Intro; Contradiction).\n  \n  Intros.\n  (Unfold sigma_but_table; Simpl).\n  Generalize H4.\n  (Case (eq_site_dec a0 s1); Intro).\n  Rewrite e1.\n  (Case (eq_site_dec s1 s1); Intros).\n  Rewrite <- (sigma_sigma_but_not_in Site s1 eq_site_dec).\n  Rewrite <- (sigma_sigma_but_not_in Site s1 eq_site_dec).\n  Apply sigma_simpl.\n  Intros.\n  Apply H.\n  (Unfold not; Intro).\n  Decompose [and] H7.\n  (Elim H5; Rewrite <- H10; Auto).\n  \n  Auto.\n  \n  Exact H5.\n  \n  (Elim n; Auto).\n  \n  (Case (eq_site_dec s1 a0); Intro).\n  (Elim n; Auto).\n  \n  Intros.\n  Apply add_reduce3.\n  Apply H.\n  (Unfold not; Intro).\n  Decompose [and] H6.\n  (Elim n; Auto).\n  \n  Generalize H3.\n  Unfold sigma_but_table.\n  Auto.\n  \n  Apply sigma_simpl.\n  Intros.\n  (Case (eq_site_dec x a); Intro).\n  (Elim H1; Rewrite <- e1; Auto).\n  \n  Apply sigma_simpl.\n  Intros.\n  Apply H.\n  (Unfold not; Intro).\n  (Decompose [and] H5; Elim n; Rewrite <- e; Auto).\n  \n  (Elim n; Auto).\n  \n  Unfold sigma2_but_table.\n  (Unfold sigma_table; Simpl).\n  Intros.\n  (Case (eq_site_dec a s0); Intro).\n  (Elim n; Auto).\n  \n  Rewrite H0.\n  Apply add_reduce3.\n  Unfold Z_id.\n  Apply sigma_simpl.\n  Intros.\n  Apply H.\n  (Unfold not; Intro; Elim n0).\n  (Decompose [and] H4; Auto).\n  \n  Auto.\n  \n  Auto.\n  \n  Auto.\nSave.\n\nEnd BUT_XY.\n\n*)\n\n(* another way of defining sigma_but:\n\n   On the one hand, it is less convenient, because the functional\n   argument is changed, which later, if we use sigma2_simpl, will\n   imply a tedious case analysis.\n\n\n   On the other hand, it is more convenient, because I can\n   apply sigma2_but several times, there are transformed into\n   a sigma2_table.\n*)\n(*\nLemma new_sigma2_sigma2_but_x_y:\n (s0,s1:Site)(Data:Set) (f:Site->Site->Data->Z)\n (t:Site ->  Site -> Data)\n (sigma2_table Site LS LS Data f t) = `(new_sigma2_but_table Site eq_site_dec LS LS Data s0 s1 f t) \n                                       + (f s0 s1 (t s0 s1))`.\nProof.\n  Intros.\n  Unfold new_sigma2_but_table.\n  Rewrite sigma2_sigma2_but_x_y with s0:=s0 s1:=s1.\n  Apply add_reduce17.\n  Rewrite sigma2_sigma2_but_x_y with s0:=s0 s1:=s1.\n  Apply add_reduce18.\n  Apply sigma2_but_simpl.\n  Intros.\n  (Case (eq_site_dec x s0); Intro).\n  (Case (eq_site_dec y s1); Intro).\n  (Elim H; Auto).\n  Auto.\n  Auto.\n  Rewrite case_eq.\n  Rewrite case_eq.\n  Auto.\nSave.\n\n*)\n\n\nLemma termination_measure_decreases :\n forall (c : Config) (t : class_trans c),\n legal c ->\n ~ copy_p c t ->\n (termination_measure (transition c t) < termination_measure c)%Z.\n\nProof.\n  simple induction t; simpl in |- *;\n   unfold termination_measure, termination_rt_measure, termination_q_measure\n    in |- *; simpl in |- *; intros.\n\n  (* 1 *)\n\n  elim H0; auto.\n\n  (* 2 *)\n  \n  rewrite\n   sigma2_sigma2_but_x_y\n                         with\n                         (s0 := s1)\n                        (s1 := s2)\n                        (eq_site_dec := eq_site_dec).\n  rewrite collect_here.\n  unfold termination_q_count in |- *.\n  rewrite reduce_first_out with (m := dec).\n  rewrite\n   sigma2_sigma2_but_x_y\n                         with\n                         (s0 := s1)\n                        (s1 := s2)\n                        (eq_site_dec := eq_site_dec).\n  apply add_reduce10.\n  apply sigma2_but_simpl2.\n  intros.\n  rewrite collect_elsewhere.\n  auto.\n  \n  case (eq_queue_dec s1 x s2 y); intro.\n  elim H1; auto.\n  decompose [and] a; split; auto.\n  \n  auto.\n  apply finite_site.\n  apply finite_site.\n\n  \n  unfold termination_count in |- *; simpl in |- *.\n  omega.\n  apply finite_site.\n  apply finite_site.\n\n  auto.\n  apply finite_site.\n  apply finite_site.\n\n  (* 3 *)\n\n  apply add_reduce15.\n  rewrite\n   new_sigma2_sigma2_but_x_y\n                             with\n                             (s0 := owner)\n                            (s1 := s3)\n                            (eq_site_dec := eq_site_dec).\n  rewrite\n   new_sigma2_sigma2_but_x_y\n                             with\n                             (s0 := owner)\n                            (s1 := s3)\n                            (eq_site_dec := eq_site_dec).\n  unfold new_sigma2_but_table in |- *.\n  rewrite post_here.\n  unfold termination_q_count in |- *; simpl in |- *.\n  rewrite collect_elsewhere.\n  rewrite\n   new_sigma2_sigma2_but_x_y\n                             with\n                             (s0 := s1)\n                            (s1 := owner)\n                            (eq_site_dec := eq_site_dec).\n  rewrite\n   new_sigma2_sigma2_but_x_y\n                             with\n                             (s0 := s1)\n                            (s1 := owner)\n                            (eq_site_dec := eq_site_dec).\n  unfold new_sigma2_but_table in |- *.\n  case (eq_site_dec s1 owner); intro.\n  generalize e; rewrite e0.\n  rewrite empty_q_to_me; simpl in |- *.\n  intro; discriminate.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_here.\n  rewrite reduce_first_out with (m := inc_dec s3).\n  apply add_reduce19.\n  unfold sigma2_table in |- *.\n  apply sigma_table_simpl.\n  apply funct_eq.\n  intro.\n  unfold sigma_table in |- *.\n  apply sigma_simpl.\n  intros.\n  case (eq_site_dec e0 s1); intro.\n  case (eq_site_dec x owner); intro.\n  auto.\n  case (eq_site_dec e0 owner); intro.\n  case (eq_site_dec x s3); intro.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_elsewhere; auto.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_elsewhere; auto.\n  auto.\n  case (eq_site_dec e0 owner); intro.\n  case (eq_site_dec x s3); intro.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_elsewhere; auto.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_elsewhere; auto.\n  auto.\n  unfold termination_count in |- *; simpl in |- *.\n  omega.\n  auto.\n  auto.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  left; unfold not in |- *; intro.\n  generalize e; rewrite H1; rewrite empty_q_to_me.\n  simpl in |- *; intro; discriminate.\n  auto.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n\n  (* 4 *)\n\n  apply add_reduce15.\n  rewrite\n   new_sigma2_sigma2_but_x_y\n                             with\n                             (s0 := s2)\n                            (s1 := s1)\n                            (eq_site_dec := eq_site_dec).\n  rewrite\n   new_sigma2_sigma2_but_x_y\n                             with\n                             (s0 := s2)\n                            (s1 := s1)\n                            (eq_site_dec := eq_site_dec).\n  unfold new_sigma2_but_table in |- *.\n  rewrite post_here.\n  unfold termination_q_count in |- *; simpl in |- *.\n  rewrite collect_elsewhere.\n  rewrite\n   new_sigma2_sigma2_but_x_y\n                             with\n                             (s0 := s1)\n                            (s1 := s2)\n                            (eq_site_dec := eq_site_dec).\n  rewrite\n   new_sigma2_sigma2_but_x_y\n                             with\n                             (s0 := s1)\n                            (s1 := s2)\n                            (eq_site_dec := eq_site_dec).\n  unfold new_sigma2_but_table in |- *.\n  case (eq_site_dec s1 s2); intro.\n  generalize e0; rewrite e1; rewrite empty_q_to_me; simpl in |- *.\n  intro; discriminate.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_here.\n  rewrite reduce_first_out with (m := copy).\n  apply add_reduce19.\n  unfold sigma2_table in |- *.\n  apply sigma_table_simpl.\n  apply funct_eq.\n  intro.\n  unfold sigma_table in |- *.\n  apply sigma_simpl.\n  intros.\n  case (eq_site_dec e1 s1); intro.\n  case (eq_site_dec x s2); intro.\n  auto.\n  case (eq_site_dec e1 s2); intro.\n  case (eq_site_dec x s1); intro.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_elsewhere; auto.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_elsewhere; auto.\n  auto.\n  case (eq_site_dec e1 s2); intro.\n  case (eq_site_dec x s1); intro.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_elsewhere; auto.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_elsewhere; auto.\n  auto.\n  unfold termination_count in |- *; simpl in |- *.\n  omega.\n  auto.\n  auto.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  left; unfold not in |- *; intro.\n  generalize e0; rewrite H1; rewrite empty_q_to_me; simpl in |- *.\n  intro; discriminate.\n  auto.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n\n  (* 5 *)\n  \n  rewrite\n   sigma2_sigma2_but_x_y\n                         with\n                         (s0 := owner)\n                        (s1 := s2)\n                        (eq_site_dec := eq_site_dec).\n  rewrite collect_here.\n  unfold termination_q_count in |- *.\n  rewrite reduce_first_out with (m := copy).\n  unfold sigma_table in |- *.\n  rewrite (sigma_sigma_but Site s2 eq_site_dec).\n  unfold Z_id in |- *.\n  rewrite\n   sigma2_sigma2_but_x_y\n                         with\n                         (s0 := owner)\n                        (s1 := s2)\n                        (eq_site_dec := eq_site_dec).\n  apply add_reduce11.\n  rewrite (sigma_sigma_but Site s2 eq_site_dec).\n  rewrite e; unfold termination_rt_count in |- *.\n  simpl in |- *.\n  apply add_reduce12.\n  apply sigma_but_simpl.\n  intros.\n  unfold Set_rec_table in |- *.\n  cut (change_site bool (rt c) s2 true s = rt c s).\n  intro.\n  rewrite H2.\n  auto.\n  \n  rewrite other_site.\n  auto.\n  auto.\n  apply finite_site.\n  apply sigma2_but_simpl2.\n  intros.\n  case (eq_queue_dec owner x s2 y); intro.\n  elim H1; decompose [and] a.\n  split; auto.\n  rewrite collect_elsewhere.\n  auto.\n  auto.\n apply finite_site.\n apply finite_site.\n  unfold termination_rt_count in |- *; unfold Set_rec_table in |- *.\n  unfold termination_count in |- *; simpl in |- *.\n  cut (change_site bool (rt c) s2 true s2 = true).\n  intro.\n  rewrite H1.\n  omega.\n  rewrite that_site; auto.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  auto.\n  apply finite_site.\n  apply finite_site.\n\n  (* 6 *)\n\n  unfold sigma_table in |- *.\n  rewrite (sigma_sigma_but Site s2 eq_site_dec).\n  unfold Z_id in |- *.\n  rewrite\n   new_sigma2_sigma2_but_x_y\n                             with\n                             (s0 := s2)\n                            (s1 := owner)\n                            (eq_site_dec := eq_site_dec).\n  rewrite\n   new_sigma2_sigma2_but_x_y\n                             with\n                             (s0 := s2)\n                            (s1 := owner)\n                            (eq_site_dec := eq_site_dec).\n  unfold new_sigma2_but_table in |- *.\n  rewrite post_here.\n  unfold termination_q_count in |- *; simpl in |- *.\n  rewrite collect_elsewhere.\n  rewrite\n   new_sigma2_sigma2_but_x_y\n                             with\n                             (s0 := s1)\n                            (s1 := s2)\n                            (eq_site_dec := eq_site_dec).\n  rewrite\n   new_sigma2_sigma2_but_x_y\n                             with\n                             (s0 := s1)\n                            (s1 := s2)\n                            (eq_site_dec := eq_site_dec).\n  unfold new_sigma2_but_table in |- *.\n  case (eq_site_dec s1 s2); intro.\n  generalize e0; rewrite e1; rewrite empty_q_to_me; simpl in |- *.\n  intro; discriminate.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_here.\n  rewrite reduce_first_out with (m := copy).\n  rewrite (sigma_sigma_but Site s2 eq_site_dec).\n  apply add_reduce22.\n  unfold sigma2_table in |- *.\n  apply sigma_table_simpl.\n  apply funct_eq.\n  intro.\n  unfold sigma_table in |- *.\n  apply sigma_simpl.\n  intros.\n  case (eq_site_dec e1 s1); intro.\n  case (eq_site_dec x s2); intro.\n  auto.\n  case (eq_site_dec e1 s2); intro.\n  case (eq_site_dec x owner); intro.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_elsewhere; auto.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_elsewhere; auto.\n  auto.\n  case (eq_site_dec e1 s2); intro.\n  case (eq_site_dec x owner); intro.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_elsewhere; auto.\n  auto.\n  rewrite post_elsewhere.\n  rewrite collect_elsewhere; auto.\n  auto.\n  apply sigma_but_simpl.\n  intros.\n  unfold Set_rec_table in |- *; rewrite other_site.\n  auto.\n  auto.\n  unfold Set_rec_table in |- *; rewrite that_site.\n  rewrite e.\n  unfold termination_rt_count in |- *.\n  cut (termination_count copy > 4)%Z.\n  intro.\n  omega.\n  simpl in |- *.\n  omega.\n  apply finite_site.\n  auto.\n  auto.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  left; unfold not in |- *; intro; generalize e0.\n  rewrite H1; rewrite empty_q_to_me.\n  simpl in |- *; intro; discriminate.\n  auto.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n\n\n  (* 7 *)\n  \n  rewrite\n   sigma2_sigma2_but_x_y\n                         with\n                         (s0 := s)\n                        (s1 := owner)\n                        (eq_site_dec := eq_site_dec).\n  rewrite post_here.\n  rewrite\n   sigma2_sigma2_but_x_y\n                         with\n                         (s0 := s)\n                        (s1 := owner)\n                        (eq_site_dec := eq_site_dec).\n  unfold termination_q_count in |- *.\n  simpl in |- *.\n  unfold sigma_table in |- *.\n  rewrite (sigma_sigma_but Site s eq_site_dec).\n  unfold Z_id in |- *.\n  unfold sigma_table in |- *.\n  rewrite (sigma_sigma_but Site s eq_site_dec).\n  apply add_reduce14.\n  apply sigma_but_simpl.\n  intros.\n  unfold Reset_rec_table in |- *.\n  rewrite other_site.\n  auto.\n  auto.\n  apply sigma2_but_simpl2.\n  intros.\n  case (eq_queue_dec s x owner y); intro.\n  elim H1; decompose [and] a.\n  split; auto.\n  rewrite post_elsewhere; auto.\n  apply finite_site.\n  apply finite_site.\n unfold Reset_rec_table in |- *; rewrite that_site.\n  rewrite e0.\n  unfold termination_rt_count in |- *; simpl in |- *.\n  omega.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\n  apply finite_site.\nQed.\n\nLemma termination_measure_positive :\n forall c : Config, (0 <= termination_measure c)%Z.\nProof.\n  unfold termination_measure in |- *.\n  unfold termination_rt_measure, termination_q_measure in |- *.\n  intros.\n  apply add_reduce23.\n  unfold sigma_table in |- *.\n  apply sigma_pos.\n  intros.\n  unfold Z_id in |- *.\n  unfold termination_rt_count in |- *.\n  case (rt c x_).\n  omega.\n  \n  omega.\n  \n  unfold sigma2_table in |- *.\n  unfold sigma_table in |- *.\n  apply sigma_pos.\n  intros.\n  unfold Z_id in |- *.\n  apply sigma_pos.\n  intros.\n  unfold termination_q_count in |- *.\n  apply reduce_positive_or_null.\n  intros.\n  unfold termination_count in |- *.\n  case a.\n  omega.\n  \n  intro; omega.\n  \n  omega.\nQed.\n\nDefinition no_rt (c : Config) :=\n  forall s1 : Site, In s1 LS -> s1 <> owner -> rt c s1 = false.\n\nLemma decide_no_rt :\n forall c : Config,\n {no_rt c} + {(exists s1 : Site, s1 <> owner /\\ rt c s1 = true)}.\nProof.\n  intros.\n  unfold no_rt in |- *.\n  elim LS.\n  simpl in |- *.\n  left; contradiction.\n  \n  intros.\n  case (eq_site_dec a owner); intro.\n  elim H; intro.\n  left.\n  intros.\n  generalize H0; simpl in |- *.\n  case (eq_site_dec s1 a); intro.\n  elim H1; rewrite e0; auto.\n  \n  intro.\n  elim H2; auto.\n  intro; elim n; auto.\n  \n  right; auto.\n  \n  elim (decide_rt c a); intro.\n  elim H; intro.\n  left; intros.\n  case (eq_site_dec s1 a); intro.\n  rewrite e; auto.\n  \n  apply a1.\n  generalize H0; simpl in |- *; intro.\n  elim H2; intro; auto.\n  elim n0; auto.\n  \n  auto.\n  \n  right; auto.\n  \n  right.\n  split with a.\n  auto.\nQed.\n\n\n(** to be complete, we might represent explicitly a local gc! \nand we could try to prove something like this.\n If there is a s1, it means that the gc is has kicked in \n\n\nVariable local_gc: Config -> Site -> bool.\n\n\nLemma decide_no_rt_gc:\n  (c:Config) \n   {(s1:Site) (In s1 LS) -> ~(s1=owner) ->  (rt c s1)=true -> (local_gc c s1)=false}\n   +\n   {(EX s1:Site |  (In s1 LS) -> ~(s1=owner) /\\ (rt c s1)=true /\\ (local_gc c s1)=true)}.\n\n*)\n\nLemma blocked_config :\n forall c : Config,\n legal c ->\n no_message c -> no_rt c -> ~ (exists t : class_trans c, ~ copy_p c t).\nProof.\n  unfold no_message, no_rt in |- *.\n  intros.\n  unfold not in |- *; intro.\n  elim H2.\n  simple induction x; simpl in |- *; intros.\n  apply H3; auto.\n  generalize e.\n  rewrite H0.\n  simpl in |- *.\n  intro; discriminate.\n  apply in_s_LS.\n  apply in_s_LS.\n  generalize e.\n  rewrite H0.\n  simpl in |- *.\n  intro; discriminate.\n  apply in_s_LS.\n  apply in_s_LS.\n  generalize e0.\n  rewrite H0.\n  simpl in |- *.\n  intro; discriminate.\n  apply in_s_LS.\n  apply in_s_LS.\n  generalize e0.\n  rewrite H0.\n  simpl in |- *.\n  intro; discriminate.\n  apply in_s_LS.\n  apply in_s_LS.\n  generalize e0.\n  rewrite H0.\n  simpl in |- *.\n  intro; discriminate.\n  apply in_s_LS.\n  apply in_s_LS.\n  generalize e0; rewrite H1.\n  discriminate.\n  apply in_s_LS.\n  auto.\nQed.\n\nLemma blocked_config2 :\n forall c : Config,\n legal c -> no_message c -> no_rt c -> forall t : class_trans c, copy_p c t.\nProof.\n  unfold no_message, no_rt in |- *.\n  simple induction t; simpl in |- *; intros; auto.\n  generalize e.\n  rewrite H0.\n  simpl in |- *.\n  intro; discriminate.\n  apply in_s_LS.\n  apply in_s_LS.\n  generalize e.\n  rewrite H0.\n  simpl in |- *.\n  intro; discriminate.\n  apply in_s_LS.\n  apply in_s_LS.\n  generalize e0.\n  rewrite H0.\n  simpl in |- *.\n  intro; discriminate.\n  apply in_s_LS.\n  apply in_s_LS.\n  generalize e0.\n  rewrite H0.\n  simpl in |- *.\n  intro; discriminate.\n  apply in_s_LS.\n  apply in_s_LS.\n  generalize e0.\n  rewrite H0.\n  simpl in |- *.\n  intro; discriminate.\n  apply in_s_LS.\n  apply in_s_LS.\n  generalize e0; rewrite H1.\n  discriminate.\n  apply in_s_LS.\n  auto.\nQed.\n\n\n\nSection LOGIC.\nVariable U : Set.\n\nLemma ex_not_not_all :\n forall P : U -> Prop, (exists n : U, ~ P n) -> ~ (forall n : U, P n).\nProof.\nunfold not in |- *; intros P exnot allP.\nelim exnot; auto.\nQed.\n\n\nLemma ex_not_not_all2 :\n forall P : U -> Prop, (exists n : U, P n) -> ~ (forall n : U, ~ P n).\nProof.\n  unfold not in |- *; intros P exnot allP.\n  elim exnot; auto.\nQed.\n\nLemma PNNP : forall p : Prop, p -> ~ ~ p.\nProof.\nintros.\nauto.\nQed.\n\nEnd LOGIC.\n\n\nLemma sigma_f_null :\n forall (E : Set) (f : E -> Z) (l : list E),\n (forall x_ : E, f x_ = 0%Z) -> sigma E l f = 0%Z.\nProof.\n intros; elim l; simpl in |- *.\n omega.\n\n intros; generalize (H a); omega.\nQed.\n\n\nLemma null_st :\n forall (c0 : Config) (s0 : Site),\n legal c0 -> s0 <> owner -> no_message c0 -> st c0 s0 = 0%Z.\nProof.\n  intros.\n  rewrite invariant2.\n  unfold sigma_rooted in |- *.\n  unfold sigma2_table in |- *.\n  unfold sigma_table in |- *.\n  unfold Z_id in |- *.\n  apply sigma_f_null.\n  intros.\n  apply sigma_f_null.\n  intros.\n  generalize H1; unfold no_message in |- *.\n  intro.\n  rewrite H2.\n  simpl in |- *.\n  auto.\n  apply in_s_LS.\n  apply in_s_LS.\n  auto.\n  auto.\nQed.\n\nLemma not_empty_implies_last :\n forall (E : Set) (q : queue E),\n q <> empty E -> exists x : E, first E q = value E x.\nProof.\n  intro.\n  simple induction q.\n  auto.\n  intros.\n  elim H; auto.\n  intros d q0.\n  case q0.\n  simpl in |- *.\n  intros.\n  split with d.\n  auto.\n  simpl in |- *.\n  intros.\n  apply H.\n  discriminate.\nQed.\n\nLemma different_queue1 :\n forall (E : Set) (q : queue E) (m : E), input E m q <> first_out E q.\nProof.\n  intro.\n  simple induction q.\n  simpl in |- *.\n  intros.\n  discriminate.\n  intros.\n  simpl in |- *.\n  generalize H.\n  case q0.\n  simpl in |- *.\n  intros.\n  discriminate.\n  intros.\n  cut (input E d (input E e q1) <> first_out E (input E e q1)).\n  intro.\n  injection.\n  intros.\n  elim H1; auto.\n  auto.\nQed.\n\nLemma different_queue2 :\n forall (E : Set) (q : queue E) (m : E),\n first E q = value E m -> q <> first_out E q.\nProof.\n  intro.\n  simple induction q.\n  simpl in |- *; intros; discriminate.\n  \n  intro; intro.\n  case q0.\n  simpl in |- *.\n  intros.\n  discriminate.\n  \n  intros.\n  cut\n   (first_out E (input E d (input E e q1)) =\n    input E d (first_out E (input E e q1))).\n  intro.\n  rewrite H1.\n  injection.\n  generalize H; unfold not in |- *; intro.\n  intro.\n  apply (H3 m).\n  auto.\n  \n  auto.\n  \n  simpl in |- *; auto.\nQed.\n\n(** decide if there is a legal successor \n   Ideally, I should have introduce a decidable predicate\n   to decide if Delete transitions were permitted. *)\n\nLemma decide_no_copy_successor :\n forall c : Config,\n legal c ->\n (exists t : class_trans c, ~ copy_p c t /\\ legal (transition c t)) \\/\n (forall t : class_trans c, copy_p c t).\n\nProof.\n  intros.\n  elim (decide_no_message c); intro.\n  elim (decide_no_rt c); intro.\n  right.\n  intros.\n  apply blocked_config2.\n  auto.\n  auto.\n  auto.\n  elim b.\n  intros.\n  decompose [and] H0.\n  generalize (null_st c x H H1 a).\n  intro.\n  left.\n  split with (delete_entry c x H3 H2 H1).\n  split.\n  unfold copy_p in |- *.\n  unfold not in |- *; contradiction.\n  \n  apply after.\n  auto.\n  \n  elim (exist_non_empty_queue c H b).\n  intros.\n  elim H0.\n  intros.\n  decompose [and] H1.\n  generalize (not_empty_implies_last Message (bm c x x0) H3).\n  intro.\n  elim H4.\n  intros.\n  generalize (always_process_messages c H x x0 x1 H5).\n  intro.\n  elim H6.\n  intros.\n  decompose [and] H7.\n  left.\n  split with x2.\n  split.\n  unfold copy_p in |- *.\n  generalize H9.\n  case x2.\n  simpl in |- *.\n  intros.\n  generalize H10.\n  case (eq_queue_dec s1 x s2 x0); intro.\n  decompose [and] a0.\n  rewrite H11; rewrite H12.\n  rewrite post_here.\n  generalize (different_queue1 Message (bm c x x0) copy).\n  intros.\n  elim H11; auto.\n  \n  rewrite post_elsewhere.\n  generalize (different_queue2 Message (bm c x x0) x1 H5).\n  intros.\n  elim H11; auto.\n  \n  auto.\n  \n  intros; unfold not in |- *; auto.\n  \n  intros; unfold not in |- *; auto.\n  \n  intros; unfold not in |- *; auto.\n  \n  intros; unfold not in |- *; auto.\n  \n  intros; unfold not in |- *; auto.\n  \n  intros; unfold not in |- *; auto.\n  \n  auto.\nQed.\n\n\nSection ROOT_SUCC.\n\nInductive legal_as_set : Config -> Set :=\n    intro_leg : forall c : Config, legal c -> legal_as_set c.\n\n\n\nDefinition legal_config := sigS legal_as_set.\n\nDefinition get_c (lc : sigS legal_as_set) :=\n  match lc with\n  | existS c L => c\n  end.\n\n(* WATCH OUT: successor is first argument, predecessor is second *)\nDefinition no_copy_succ (lc2 lc1 : legal_config) :=\n  exists t : class_trans (get_c lc1),\n    get_c lc2 = transition (get_c lc1) t /\\ ~ copy_p (get_c lc1) t.\n\n\n\nDefinition convert_to_nat (n : Z) :=\n  match n with\n  | Zpos x => nat_of_P x\n  | _ => 0\n  end.\n\n\nDefinition no_copy_measure (lc : legal_config) :=\n  match lc with\n  | existS c _ => convert_to_nat (termination_measure c)\n  end.\n\nDefinition decidable_relation (E : Set) (R : E -> E -> Prop) :=\n  forall x : E, {y : E | R y x} + {(forall y : E, ~ R y x)}.\n\n\nAxiom\n  or_rec : forall (A B : Prop) (P : Set), (A -> P) -> (B -> P) -> A \\/ B -> P.\nAxiom\n  ex_rec :\n    forall (A : Set) (P : A -> Prop) (P0 : Set),\n    (forall x : A, P x -> P0) -> ex P -> P0.\n\n\nLemma decidable_no_copy_succ : decidable_relation legal_config no_copy_succ.\nProof.\n  unfold decidable_relation in |- *.\n  intro.\n  elim x.\n  intros.\n  elim p.\n  intros.\n  generalize (decide_no_copy_successor c l).\n  intro.\n  elim H.\n  intro.\n  elim H0.\n  intros.\n  left.\n  decompose [and] H1.\n  split\n   with\n     (existS legal_as_set (transition c x1) (intro_leg (transition c x1) H3)).\n  unfold no_copy_succ in |- *.\n  unfold get_c in |- *.\n  split with x1.\n  split; auto.\n  intro.\n  right.\n  intro.\n  unfold no_copy_succ in |- *.\n  unfold get_c in |- *.\n  unfold not in |- *; intro.\n  elim H1.\n  intros.\n  decompose [and] H2.\n  apply H4.\n  auto.\nQed.\n\nDefinition relation_decreases (E : Set) (R : E -> E -> Prop)\n  (f : E -> nat) := forall x y : E, R x y -> f x < f y.\n\n\nLemma Z_nat_business :\n forall x y : positive, nat_of_P y < nat_of_P x -> (Zpos y < Zpos x)%Z.\nProof.\n  intros.\n  unfold Zlt in |- *.\n  unfold Zcompare in |- *.\n  apply nat_of_P_lt_Lt_compare_complement_morphism.\n  auto.\nQed.\n\nLemma Z_nat_business1 :\n forall x y : positive, (Zpos y < Zpos x)%Z -> nat_of_P y < nat_of_P x.\nProof.\n  intros.\n  apply nat_of_P_lt_Lt_compare_morphism.\n  generalize H.\n  unfold Zlt in |- *.\n  unfold Zcompare in |- *.\n  auto.\nQed.\n\nAxiom\n  Z_nat_axiom :\n    forall x y : Z,\n    (0 <= x)%Z ->\n    (0 <= y)%Z -> (y < x)%Z -> convert_to_nat y < convert_to_nat x.\n\n\n(*  What I want to prove.\nLemma Z_nat_business2:\n (x:Z)  `0<=x` -> `0<x` -> (lt (0) (convert_to_nat `x`)).\n\nLemma Z_nat_business3:\n (x,y:Z)  `0<=x` -> `0<=y` -> `y<x` -> (lt (convert y) (convert x)).\n\nLemma Z_nat_business4:\n (x,y:positive)  (lt (convert y) (convert x)) -> (lt (convert y) (convert x)).\n\n*)\n(* use Theorem bij1 : (m:nat) (convert (anti_convert m)) = (S m). *)\n\n\nLemma no_copy_succ_decreases :\n relation_decreases legal_config no_copy_succ no_copy_measure.\nProof.\n  unfold relation_decreases in |- *.\n  intro.\n  elim x.\n  intro.\n  intro.\n  elim p.\n  intro; intro; intro.\n  elim y.\n  intro; intro.\n  elim p0.\n  intro; intro.\n  unfold no_copy_succ in |- *.\n  unfold get_c in |- *.\n  intro.\n  unfold no_copy_measure in |- *.\n  elim H.\n  intros.\n  decompose [and] H0.\n  generalize (termination_measure_decreases c0 x2 l0 H2).\n  rewrite <- H1.\n  intro.\n  apply Z_nat_axiom.\n  apply termination_measure_positive.\n  apply termination_measure_positive.\n  auto.\nQed.\n\nDefinition last_successor :=\n  root legal_config no_copy_measure no_copy_succ decidable_no_copy_succ\n    no_copy_succ_decreases.\n\n\nLemma last_successor_is_last :\n forall y0 y : legal_config, ~ no_copy_succ y (last_successor y0).\nProof.\n  intros.\n  unfold last_successor in |- *.\n  apply root_no_R.\nQed.\n\n\n(* QUESTION:  What does the following lemma mean?  \n  That there is a given transition sequence that terminates\n  or that all of them terminate?\n*)\n\nLemma last_successor_has_no_message :\n forall y0 : legal_config, no_message (get_c (last_successor y0)).\nProof.\n  intros.\n  generalize (last_successor_is_last y0).\n  intro.\n  elim (decide_no_message (get_c (last_successor y0))).\n  auto.\n  \n  generalize H.\n  elim (last_successor y0).\n  simpl in |- *.\n  intro; intro.\n  elim p.\n  intros.\n  generalize (exist_non_empty_queue c l b).\n  intro.\n  elim H1; intro.\n  intro.\n  elim H2.\n  intro.\n  intros.\n  decompose [and] H3.\n  generalize (not_empty_implies_last Message (bm c x0 x1) H5); intro.\n  elim H6.\n  intros.\n  generalize (always_process_messages c l x0 x1 x2 H7); intro.\n  elim H8; intro.\n  intro.\n  decompose [and] H9.\n  elim\n   (H0\n      (existS legal_as_set (transition c x3)\n         (intro_leg (transition c x3) H10))).\n  unfold no_copy_succ in |- *.\n  unfold get_c in |- *.\n  split with x3.\n  split.\n  auto.\n  \n  unfold copy_p in |- *.\n  generalize H11.\n  elim x3; simpl in |- *; intros.\n  generalize H12.\n  case (eq_queue_dec s1 x0 s2 x1); intro.\n  decompose [and] a0.\n  rewrite H13; rewrite H14.\n  rewrite post_here.\n  generalize (different_queue1 Message (bm c x0 x1) copy).\n  intros.\n  elim H13; auto.\n  rewrite post_elsewhere.\n  generalize (different_queue2 Message (bm c x0 x1) x2 H7).\n  intros.\n  elim H13; auto.\n  auto.\n  tauto.\n  tauto.\n  tauto.\n  tauto.\n  tauto.\n  tauto.\nQed.\n\nEnd ROOT_SUCC.\n\n\n", "meta": {"author": "coq-contribs", "repo": "distributed-reference-counting", "sha": "6552f14cce0ea374c98adcbee0476ae268d64a7e", "save_path": "github-repos/coq/coq-contribs-distributed-reference-counting", "path": "github-repos/coq/coq-contribs-distributed-reference-counting/distributed-reference-counting-6552f14cce0ea374c98adcbee0476ae268d64a7e/machine2/liveness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.23346905553266567}}
{"text": "Require Import Lexicals.\nRequire Import String.\nRequire Import List.\nRequire Import Exceptions.\nRequire Import MyUtils.\nRequire Import Monad.\nRequire Import ZArith.\n  \nModule Type PARSE.\n  \n  Parameter position : Set.\n  Parameter element : Set.\n  Parameter token : Set. \n  Parameter M : Type -> Type. \n  Definition Parse A (l:list token) := (A*{l' : list token | Suffix l' l})%type.\n  Definition Parser A := forall l, M (Parse A l). \n  Parameter id : Parser string.\n  Parameter num : Parser nat.\n  Parameter con : Parser string.\n  Parameter str : forall (s:string), Parser string.\n  Parameter alt : forall (A:Type), Parser A -> Parser A -> Parser A.\n  Parameter must : forall (A:Type), Parser A -> Parser A. \n  Parameter pair : forall (A B:Type), Parser A -> Parser B -> Parser (A * B). \n  Parameter s_pair : forall (A:Type), string -> Parser A -> Parser A.\n  Parameter pair_s : forall (A:Type), Parser A -> string -> Parser A. \n  Parameter appl : forall (A B:Type), Parser A -> (A -> B) -> Parser B.  \n  Parameter repeat : forall (A:Type), Parser A -> Parser (list A). \n  Parameter wrap : forall (A:Type), Parser A -> Parser (list A). \n  (* \n  Parameter infixes : forall (A:Set), Parser A -> (string -> Z) -> (string -> A -> A -> A) -> Parser A. \n  *)\n  Parameter reader : forall (A:Type), Parser A -> string -> M A.\nEnd PARSE.\n    \nModule Parse (Lex : LEXICAL) <: PARSE. \n  \n  Definition position := Lex.Position.\n  Definition element := Lex.Element.\n  Definition token := Lex.Token.\n\n  Definition M := ExceptionM. \n\n  Definition SyntaxErr := \"SyntaxErr\"%string.\n  Definition Fail := \"Fail\"%string. \n\n  Definition report_position r := \n    (\"(line,character): (\"++(string_of_nat (Lex.pos_lnum r))++\n     \",\"++(string_of_nat (Lex.pos_cnum r))++\")\")%string. \n\n  Definition Parse A (l:list token) := (A*{l' : list token | length l' < length l})%type.\n  Definition Parser (A:Type) := forall l, M (Parse A l).\n\n  (*Phrase consisting of an identifier*)\n  Definition id : Parser string. \n    unfold Parser.\n    refine \n      (fun l : list token => \n        match l return M (Parse string l) with \n          | nil => raise SyntaxErr \"Identifier expected, but at end of input.\"\n          | cons (Lex.Id a,_) toks => ret (a,(exist _ toks _))\n          | cons (_,pos) _ => \n            raise SyntaxErr (\"Identifier expected at \"++(report_position pos))%string\n        end). simpl ; auto.\n  Defined.\n\n  (*Phrase consisting of an number*)\n  (* Definition num (l:list token) : Parse nat l := *) \n  Definition num : Parser nat.\n    unfold Parser.\n    refine \n      (fun l : list token => \n        match l return M (Parse nat l) with \n          | nil => raise SyntaxErr \"Number expected, but at end of input.\"\n          | cons (Lex.Num n,_) toks => ret (n,(exist _ toks _))\n          | cons (_,pos) _ => \n            raise SyntaxErr (\"Number expected at \"++(report_position pos)) \n        end). simpl ; auto.\n  Defined.\n\n  (* Phrase consisting of a constructor *)\n  Definition con : Parser string.\n    unfold Parser.\n    refine \n      (fun l : list token => \n        match l return M (Parse string l) with \n          | nil => raise SyntaxErr \"Constructor expected, but at end of input.\"\n          | cons (Lex.Con c,_) toks => ret (c,(exist _ toks _))\n          | cons (_,pos) _ => \n            raise SyntaxErr (\"Constructor expected at \"++(report_position pos))\n        end). simpl ; auto. \n  Defined.\n\n  (*Phrase consisting of the keyword 'a' *)\n  Definition str (a:string) : Parser string.\n    unfold Parser. \n    refine \n      (fun (a:string) (l : list token) =>       \n        match l return M (Parse string l) with \n          | nil => raise SyntaxErr (a++\" expected, but at end of input.\")\n          | cons (Lex.Key b,pos) toks => \n            if string_dec a b then ret (a,(exist _ toks _))\n              else raise SyntaxErr (a++\" expected, \"++b++\" found at \"++(report_position pos))\n          | cons (_,pos) toks => \n            raise SyntaxErr (\"Keyword expected: \"++a++\" at \"++(report_position pos))\n        end). simpl ; auto.\n  Defined.\n\n  (* parsing disjunction *)\n  Definition alt `A` (ph1: Parser A) (ph2: Parser A) : Parser A := \n    (fun toks => \n      ph1 toks \n      |:| SyntaxErr, msg => ph2 toks). \n  Infix \"|+|\" := alt.\n  \n  (* fail if we can't parse with ph.  This is like prolog's cut and pretty nasty for the same reasons. *)\n  Definition must `A` (ph: Parser A) : Parser A :=\n    (fun toks => \n      ph toks \n      |:| SyntaxErr, msg => raise Fail msg). \n  Notation \"|!| ph\" := (must ph) (at level 0).\n\n  (*One phrase then another*)\n  Definition pair `A B` (ph1 : Parser A) (ph2 : Parser B) : Parser (A*B).  \n    unfold Parser.\n    refine \n      (fun (A B : Type) (ph1 : Parser A) (ph2 : Parser B) (toks : list token) => \n        px <- ph1 toks ;;\n        (match px with \n           | (x,(exist toks2 Hx)) => \n             py <- ph2 toks2 ;; \n             (match py with\n                | (y,(exist toks3 Hy)) => ret ((x,y),exist _ toks3 _)\n              end)\n         end)) ; eapply suffix_trans ; eauto.\n  Defined. \n  Infix \"--\" := pair (at level 55).\n\n  (*Application of f to the result of a phrase*)\n  Definition appl `A B` (ph : Parser A) (f : A -> B) : Parser B. \n    unfold Parser.\n    refine \n      (fun (A B : Type) (ph : Parser A) (f : A -> B) (toks : list token) => \n        px <- ph toks ;; \n        (match px with \n           | (x,(exist toks2 Hx)) => \n             ret (f x,exist _ toks2 _)\n         end)) ; auto.\n  Defined.\n  Infix \"|>|\" := appl (at level 55).\n  \n  Definition s_pair `A` (a:string) (ph: Parser A) : Parser A :=     \n    (str a) -- |!|ph |>| (fun (x:string*A) => snd x).\n  Infix \"@--\" := s_pair (at level 50).\n\n  Definition pair_s `A` (ph: Parser A) (a:string) : Parser A :=\n    |!|ph -- (str a) |>| (fun (x:A*string) => fst x).\n  Infix \"--@\" := pair_s (at level 50).\n\n  Require Import Recdef.\n  (* We don't use the ML definition of repeat because it doesn't necessarily make progress *)\n  Function repeat_aux (A:Type) (ph : Parser A) (toks : list token) {measure length toks} : M (Parse (list A) toks) :=\n    match ph toks with \n      | exn e => exn _ e\n      | no_exn (a,exist toks' Htoks') => \n        match repeat_aux A ph toks' with \n          | exn e => ret (cons a nil,exist _ toks' Htoks')\n          | no_exn (b,exist toks'' Htoks'') => ret ((cons a b), exist _ toks'' (suffix_trans _ toks toks' toks'' Htoks' Htoks''))\n        end\n    end. intros. apply suffix_smaller. auto.\n  Defined. \n\n  (* this just gives us implicit A and makes the type more readable. [Function is a bit ugly in that it changes the names of parameters] *) \n  Definition repeat `A` (ph:Parser A) : Parser (list A) := repeat_aux A ph.\n  \n  Definition wrap `A` (ph:Parser A) : Parser (list A).\n    unfold Parser.\n    refine \n      (fun (A:Type) (ph:Parser A) (toks:list token) => \n        (px <- ph toks ;;\n          (match px with \n             | (a,exist toks' Htoks') => ret (cons a nil, exist _ toks' Htoks') \n           end))).\n  Defined.\n\n  (* \n  fun infixes (ph,prec_of,apply) = \n    let fun over k toks = next k (ph toks)\n        and next k (x, (Lex.Key(a),pos)::toks) = \n              if prec_of a < k then (x, (Lex.Key a,pos) :: toks)\n              else next k ((over (prec_of a) >> apply a x) toks)\n          | next k (x, toks) = (x, toks)\n    in  over 0  end;\n\n    *) \n\n  (*Scan and parse, checking that no tokens remain*)\n  Definition reader `A` (ph : Parser A) str : M A := \n    (px <- ph (Lex.scan str) ;; \n      (match px with \n         | (x,exist nil H1) => ret x\n         | (_,exist (cons tok _) _) => \n           raise SyntaxErr (\"Extra characters in phrase: \" ++ (Lex.showToken tok) \n             ++ \"...\" ++ \"near \"++(report_position (snd tok)))\n       end))\n    (* Turn failures back into syntax errors *)\n    |:| Fail, msg => raise SyntaxErr msg. \n\nEnd Parse.", "meta": {"author": "GavinMendelGleason", "repo": "code", "sha": "db3e66c638ec0c2c60d726d99350463a21a774dc", "save_path": "github-repos/coq/GavinMendelGleason-code", "path": "github-repos/coq/GavinMendelGleason-code/code-db3e66c638ec0c2c60d726d99350463a21a774dc/coq/poitin-coq/Parsing2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2334690555326656}}
{"text": "Require Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.GenericBaseTypes.\nRequire Import Fiat.Parsers.GenericBoolCorrectnessBaseTypes.\nRequire Import Fiat.Parsers.GenericRecognizer.\nRequire Import Fiat.Parsers.GenericRecognizerExt.\nRequire Import Fiat.Common.\nRequire Import Fiat.Common.Wf1.\n\nSection eq.\n  Context {Char} {HSLM : StringLikeMin Char} {G : grammar Char}.\n  Context {data : @boolean_parser_dataT Char _}\n          {rdata : @parser_removal_dataT' _ G _}.\n  Context {gendata gendata' : @generic_parser_dataT Char}.\n  Context {genddata genddata'}\n          {gendcdata : @generic_parser_decidable_correctness_data Char gendata genddata}\n          {gendcdata' : @generic_parser_decidable_correctness_data Char gendata' genddata'}.\n  Context (str : String).\n\n  Local Ltac expand_once :=\n    idtac;\n    match goal with\n    | [ |- ?f ?x = ?g ?y ]\n      => let x' := head x in\n         let y' := head y in\n         unfold x', y'\n    end.\n\n  Local Ltac t' :=\n    idtac;\n    match goal with\n    | [ |- ?R ?x ?x ] => reflexivity\n    | _ => assumption\n    | [ |- ?f match ?x with _ => _ end = ?g match ?x with _ => _ end ]\n      => destruct x eqn:?\n    | _ => progress subst\n    | _ => progress autorewrite with generic_parser_decidable_correctness\n    | _ => progress simpl in *\n    | _ => solve [ auto with nocore ]\n    | _ => intro\n    | _ => rewrite List.map_map\n    | [ |- andb _ _ = andb _ _ ] => apply (f_equal2 andb)\n    | [ |- List.fold_right orb false _ = List.fold_right orb false _ ]\n      => apply (f_equal (List.fold_right orb false))\n    | [ |- List.map ?f ?ls = List.map ?g ?ls ] => apply List.map_ext\n    | [ |- ?f (option_rect _ _ _ (sumbool_rect _ _ _ ?x))\n           = ?g (option_rect _ _ _ (sumbool_rect _ _ _ ?x)) ]\n      => destruct x eqn:?\n    end.\n\n  Local Ltac t tac := intros; expand_once; repeat first [ progress t' | progress tac ].\n\n  Lemma parse_item'_eq\n        str_matches_nonterminal str_matches_nonterminal'\n        (str_matches_nonterminal_eq : forall nt,\n            parse_nt_T_to_bool (gendata := gendata) (str_matches_nonterminal nt)\n            = parse_nt_T_to_bool (gendata := gendata') (str_matches_nonterminal' nt))\n        (offset : nat) (len : nat)\n        (it : item Char)\n    : parse_item_T_to_bool (parse_item' (gendata := gendata) str str_matches_nonterminal offset len it)\n      = parse_item_T_to_bool (parse_item' (gendata := gendata') str str_matches_nonterminal' offset len it).\n  Proof. t I. Qed.\n\n  Section production.\n    Context {len0 : nat}\n            (parse_nonterminal\n             : forall (offset : nat) (len0_minus_len : nat),\n                nonterminal_carrierT\n                -> _)\n            (parse_nonterminal'\n             : forall (offset : nat) (len0_minus_len : nat),\n                nonterminal_carrierT\n                -> _)\n            (parse_nonterminal_eq\n             : forall offset len0_minus_len nt,\n                parse_nt_T_to_bool (gendata := gendata) (parse_nonterminal offset len0_minus_len nt)\n                = parse_nt_T_to_bool (gendata := gendata') (parse_nonterminal' offset len0_minus_len nt)).\n\n    Lemma parse_production'_for_eq\n          (splits : production_carrierT -> String -> nat -> nat -> list nat)\n          (offset : nat)\n          (len0_minus_len : nat)\n          (prod_idx : production_carrierT)\n      : parse_production_T_to_bool (parse_production'_for (len0 := len0) str parse_nonterminal splits offset len0_minus_len prod_idx)\n        = parse_production_T_to_bool (parse_production'_for (len0 := len0) str parse_nonterminal' splits offset len0_minus_len prod_idx).\n    Proof.\n      t I.\n      repeat match goal with\n             | [ |- context[list_rect ?P ?N ?C] ]\n               => not is_var C;\n                    let P' := fresh \"P'\" in\n                    let N' := fresh \"N'\" in\n                    let C' := fresh \"C'\" in\n                    set (P' := P);\n                      set (N' := N);\n                      set (C' := C)\n             end.\n      generalize (to_production prod_idx); intro ps.\n      revert prod_idx offset len0_minus_len.\n      induction ps as [|p ps IHps].\n      { simpl; t I. }\n      { simpl; t ltac:(apply parse_item'_eq). }\n    Qed.\n\n    Lemma parse_production'_eq\n          (offset : nat)\n          (len0_minus_len : nat)\n          (prod_idx : production_carrierT)\n      : parse_production_T_to_bool (parse_production' (len0 := len0) str parse_nonterminal offset len0_minus_len prod_idx)\n        = parse_production_T_to_bool (parse_production' (len0 := len0) str parse_nonterminal' offset len0_minus_len prod_idx).\n    Proof. t ltac:(apply parse_production'_for_eq). Qed.\n  End production.\n\n  Section productions.\n    Context {len0 : nat}\n            (parse_nonterminal\n             : forall (offset : nat)\n                      (len0_minus_len : nat),\n                nonterminal_carrierT -> _)\n            (parse_nonterminal'\n             : forall (offset : nat)\n                      (len0_minus_len : nat),\n                nonterminal_carrierT -> _)\n            (parse_nonterminal_eq\n             : forall offset len0_minus_len nt,\n                parse_nt_T_to_bool (gendata := gendata) (parse_nonterminal offset len0_minus_len nt)\n                = parse_nt_T_to_bool (gendata := gendata') (parse_nonterminal' offset len0_minus_len nt)).\n\n    Lemma parse_productions'_eq\n          (offset : nat)\n          (len0_minus_len : nat)\n          (prods : list production_carrierT)\n      : parse_productions_T_to_bool (parse_productions' (len0 := len0) str parse_nonterminal offset len0_minus_len prods)\n        = parse_productions_T_to_bool (parse_productions' (len0 := len0) str parse_nonterminal' offset len0_minus_len prods).\n    Proof. t ltac:(apply parse_production'_eq). Qed.\n  End productions.\n\n  Section nonterminals.\n    Section step.\n      Context {len0 valid_len}\n              (parse_nonterminal\n               : forall (p : nat * nat),\n                  Wf.prod_relation lt lt p (len0, valid_len)\n                  -> forall (valid : nonterminals_listT)\n                            (offset : nat) (len : nat),\n                    len <= fst p -> nonterminal_carrierT -> _)\n              (parse_nonterminal'\n               : forall (p : nat * nat),\n                  Wf.prod_relation lt lt p (len0, valid_len)\n                  -> forall (valid : nonterminals_listT)\n                            (offset : nat) (len : nat),\n                    len <= fst p -> nonterminal_carrierT -> _)\n              (parse_nonterminal_eq\n               : forall (p : nat * nat)\n                        (pf : Wf.prod_relation lt lt p (len0, valid_len))\n                        (valid : nonterminals_listT)\n                        (offset : nat) (len : nat)\n                        (pf' : len <= fst p)\n                        (nt : nonterminal_carrierT),\n                  parse_nt_T_to_bool (gendata := gendata) (parse_nonterminal p pf valid offset len pf' nt)\n                  = parse_nt_T_to_bool (gendata := gendata') (parse_nonterminal' p pf valid offset len pf' nt)).\n      Local Unset Keyed Unification.\n      Lemma parse_nonterminal_step_eq\n            (valid : nonterminals_listT)\n            (offset : nat)\n            (len : nat)\n            (pf : len <= len0)\n            (nt : nonterminal_carrierT)\n        : parse_nt_T_to_bool (parse_nonterminal_step str parse_nonterminal valid offset pf nt)\n          = parse_nt_T_to_bool (parse_nonterminal_step str parse_nonterminal' valid offset pf nt).\n      Proof. t ltac:(apply parse_productions'_eq). Qed.\n    End step.\n\n    Section wf.\n      Lemma parse_nonterminal_or_abort_eq\n      : forall (p : nat * nat)\n               (valid : nonterminals_listT)\n               (offset : nat) (len : nat)\n               (pf : len <= fst p)\n               (nt : nonterminal_carrierT),\n        parse_nt_T_to_bool (parse_nonterminal_or_abort (gendata := gendata) str p valid offset pf nt)\n        = parse_nt_T_to_bool (parse_nonterminal_or_abort (gendata := gendata') str p valid offset pf nt).\n      Proof.\n        t I.\n        lazymatch goal with\n        | [ |- ?f0 (Fix ?rwf ?P ?F ?x ?a ?b ?c ?d ?e)\n               = ?f1 (Fix ?rwf ?Q ?G ?x ?a ?b ?c ?d ?e) ]\n          => revert a b c d e;\n               induction (rwf x);\n               intros;\n               rewrite !Wf1.Fix5_eq\n                 by (intros; apply parse_nonterminal_step_ext; trivial)\n        end.\n        apply parse_nonterminal_step_eq.\n        auto with nocore.\n      Qed.\n\n      Lemma parse_nonterminal_or_abort_minus_eq\n      : forall (p : nat * nat)\n               (valid : nonterminals_listT)\n               (offset : nat) (len0_minus_len : nat)\n               (nt : nonterminal_carrierT),\n        parse_nt_T_to_bool (parse_nonterminal_or_abort_minus (gendata := gendata) str p valid offset len0_minus_len nt)\n        = parse_nt_T_to_bool (parse_nonterminal_or_abort_minus (gendata := gendata') str p valid offset len0_minus_len nt).\n      Proof.\n        intros; apply parse_nonterminal_or_abort_eq.\n      Qed.\n\n      Definition parse_nonterminal'_eq\n                 (nt : nonterminal_carrierT)\n        : parse_nt_T_to_bool (parse_nonterminal' (gendata := gendata) str nt)\n          = parse_nt_T_to_bool (parse_nonterminal' (gendata := gendata') str nt).\n      Proof. t ltac:(apply parse_nonterminal_or_abort_eq). Qed.\n\n      Definition parse_nonterminal_eq\n                 (nt : String.string)\n        : parse_nt_T_to_bool (parse_nonterminal (gendata := gendata) str nt)\n          = parse_nt_T_to_bool (parse_nonterminal (gendata := gendata') str nt).\n      Proof. t ltac:(apply parse_nonterminal'_eq). Qed.\n    End wf.\n  End nonterminals.\n\n  Definition parse_item_eq\n             (it : item Char)\n    : parse_item_T_to_bool (parse_item (gendata := gendata) str it)\n      = parse_item_T_to_bool (parse_item (gendata := gendata') str it)\n    := parse_item'_eq _ _ parse_nonterminal'_eq _ _ _.\n\n  Definition parse_production_eq\n             (pat : production_carrierT)\n    : parse_production_T_to_bool (parse_production (gendata := gendata) str pat)\n      = parse_production_T_to_bool (parse_production (gendata := gendata') str pat)\n    := parse_production'_eq _ _ (parse_nonterminal_or_abort_minus_eq _ _) _ _ _.\n\n  Definition parse_productions_eq\n             (pats : list production_carrierT)\n    : parse_productions_T_to_bool (parse_productions (gendata := gendata) str pats)\n      = parse_productions_T_to_bool (parse_productions (gendata := gendata') str pats)\n    := parse_productions'_eq _ _ (parse_nonterminal_or_abort_minus_eq _ _) _ _ _.\nEnd eq.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/GenericRecognizerBoolEquality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23324638743845463}}
{"text": "From Undecidability Require Import L.Functions.EqBool TM.Util.TM_facts.\nFrom Undecidability Require L.TM.TMEncoding.\nFrom Undecidability.L.Functions Require Import FinTypeLookup.\nFrom Complexity Require Import L.TM.TMflat.\nFrom Complexity.Libs Require Export PSLCompat.\n\nDefinition Vector_of_list_length A n (l:list A) : option (Vector.t A n) :=\n  match Nat.eq_dec (length l) n with\n    Specif.left H =>\n    Some (eq_rect _ (fun n => Vector.t A n) (Vector.of_list l) _ H)\n  | _ => None\n  end.\n\nLemma Vector_of_list_length_eq A (l:list A) :\n  Vector_of_list_length (length l) l = Some (Vector.of_list l).\nProof.\n  unfold Vector_of_list_length.\n  destruct _. 2:easy.\n  f_equal.\n  rewrite <- Eqdep_dec.eq_rect_eq_dec. easy. decide equality.\nQed.\n\nDefinition unflatten_symb (sig:finType)  (i:option nat): option sig:=\n  match i with\n    None => None\n  | Some i => nth i (map Some (elem _)) None\n  end.\n\nDefinition unflatten_acts' (sig:finType) (l__r : list (option nat * move)): (list (option sig * move)) :=\n  map (fun '(i,m) => (unflatten_symb sig i,m)) l__r.\n\nDefinition unflatten_acts (sig:finType) n (l__r : list (option nat * move)) : (Vector.t (option sig*move) n) :=\n  match Vector_of_list_length n  (unflatten_acts' sig l__r) with\n  | Some l__r => l__r\n  | _ => Vector.const (None,Nmove) n\n  end.\n\nDefinition unflatten_trans (states:finType) (sig:finType) d n (f:list (nat * list (option nat) * (nat * list (option nat * move))))\n  : states * Vector.t (option sig) n -> states * Vector.t (option sig * move) n :=\n  fun '(st,l) =>\n    let (st__o,l__r) := lookup (index st,map (option_map (fun x => index x)) (Vector.to_list l)) f (index st,repeat (None,Nmove) n) in\n    (nth st__o (elem _) d, unflatten_acts sig n l__r).\n\n\nDefinition unflatten_halt states (f: list bool) (i : (Fin.t states)) : bool :=\n  nth (index i) f false.\n\nLocal Definition def n : Fin.t (max 1 n).\nProof.\n  destruct n;cbn.\n  all:now constructor.\nDefined. (* because ?*)\n\nProgram Definition unflattenTM (M:flatTM) : TM (finType_CS (Fin.t (sig M))) (tapes M) :=\n  let d := def _ in\n  {|TM.state := (finType_CS ((Fin.t (max 1 (states M)))));\n    TM.trans := unflatten_trans d (trans M);\n    TM.start := nth (start M) (elem _) d;\n    TM.halt := unflatten_halt (halt M);\n  |}.\n\nLemma index_nth_elem (X:finType) i d:\n  i < | elem X |\n  -> index (nth (A:=X) i (elem _) d) = i.\nProof.\n  intros. unfold index. apply getPosition_nth.\n  - eapply dupfree_elements.\n  - assumption.\nQed.\n\nLemma index_nth_elem_fint i n d:\n  i < n\n  -> index (nth (A:=Fin.t n)i (elem _) d) = i.\nProof.\n  intros. eapply index_nth_elem.\n  now rewrite Fin_cardinality.\nQed.\n\nDefinition defFin (X:finType):\n  0 < | elem X | -> X.\nProof.\n  destruct (elem X); intro H.\n  - exfalso. eapply Nat.lt_irrefl. exact H.\n  - exact e.\nQed.\n\nDefinition unflatten_in (sig:finType) n (l__r : list (option nat)) : (Vector.t (option sig) n) :=\n  match Vector_of_list_length n  (map (unflatten_symb sig) l__r) with\n  | Some l__r => l__r\n  | _ => Vector.const None n\n  end.\n\nLemma unflatten_in_correct (sig:finType) n v:\n  length v = n ->\n  (forall a : nat, Some a el v -> a < | elem sig |) ->\n  map (option_map index) (Vector.to_list (unflatten_in sig n v)) = v.\nProof.\n  intros <-.\n  unfold unflatten_in.\n  erewrite <- (map_length (unflatten_symb sig) v).\n  rewrite Vector_of_list_length_eq, VectorSpec.to_list_of_list_opp.\n  rewrite map_map.\n  intros. \n  erewrite map_ext_in with (g:=fun x => x). now apply map_id.\n  \n  intros. destruct a. 2:easy.\n  apply H in H0. cbn.\n  unshelve erewrite nth_indep with (d':= Some _).\n  -eapply defFin. apply (Nat.lt_lt_0 _ _ H0).\n  -rewrite map_nth. cbn.\n   erewrite index_nth_elem. all:try easy.\n  -rewrite map_length. easy.\nQed.\n\nRecord validFlatTrans (sig n states:nat) (f:list (nat * list (option nat) * (nat * list (option nat * move)))) : Prop :=\n  {\n    flatTrans_inj:\n      (forall a' b1 b2 , (a', b1) el f -> (a', b2) el f -> b1 = b2);\n    flatTrans_bound: forall s s' v v',\n        ((s,v),(s',v')) el f\n        -> s < states\n          /\\ length v = n\n          /\\ (forall a, Some a el v -> a < sig)\n          /\\ s' < states\n          /\\ length v' = n\n          /\\ (forall a m, (Some a,m) el v' -> a < sig)   \n  }.\n\nDefinition validFlatTM (M:flatTM) :=\n  validFlatTrans M.(sig) M.(tapes) M.(states) M.(trans)\n  /\\ M.(start) < M.(states).\n\n(* Lemma flatTrans_in_ok states sig n f: *)\n(*   validFlatTrans sig n states f -> *)\n(*   forall s v r, *)\n(*   ((s,v),r) el f *)\n(*   -> s < states *)\n(*     /\\ length v = n *)\n(*     /\\ (forall a, Some a el v -> a < sig). *)\n(* Proof. *)\n(*   intros H s v r ?. *)\n(*   eapply flatTrans_tot. all:eauto. *)\n(* Qed.  *)\n(*\n\nLemma isFlattening_inv sig n (M':mTM sig n) d trans0 s s' v v':\n  isFlatteningTransOf trans0 (TM.trans (m:=M')) ->\n  ((s,v),(s',v')) el trans0 ->\n  s = index (nth s (elem (finType_CS (Fin.t (Cardinality (TM.states M'))))) d)\n  /\\ s' = index (nth s' (elem (finType_CS (Fin.t (Cardinality (TM.states M'))))) d)\n  /\\ v = map (option_map index) (unflatten_in (Cardinality sig) n v)\n  /\\ v' = map (map_fst (option_map index)) (unflatten_acts (Cardinality sig) n v').\nAdmitted.*)\n\n\n\nLemma unflatten_acts_correct (sig:finType) n v':\n  length v' = n ->\n  (forall a m , (Some a,m) el v' -> a < | elem sig |) ->\n  map (map_fst (option_map index)) (Vector.to_list (unflatten_acts sig n v')) = v'.\nProof.\n  intros <-.\n  unfold unflatten_acts,unflatten_acts'.\n  erewrite <- (map_length _ v').\n  rewrite Vector_of_list_length_eq,VectorSpec.to_list_of_list_opp.\n  rewrite map_map.\n  intros. \n  erewrite map_ext_in with (g:=fun x => x). now apply map_id.\n  \n  intros. destruct a as [[] ?]. 2:easy.\n  apply H in H0. \n  unfold Basics.compose. cbn.\n  unshelve erewrite nth_indep with (d':= Some ltac:(eapply defFin)).\n  abstract lia.\n  2:{ rewrite map_length. easy. }\n\n  rewrite map_nth. cbn.\n  rewrite index_nth_elem;easy.\nQed.\n\nLemma unflatten_trans_correct st sig n d trans0:\n  validFlatTrans sig n st trans0\n  -> isFlatteningTransOf trans0 (unflatten_trans (sig:=finType_CS (Fin.t sig)) (states := finType_CS (Fin.t st)) (n:=n) d trans0).\nProof.\n  intros H.\n  split.\n  -intros ? ? ? ? H'.\n   eexists (nth s (elem _) d),(nth s' (elem _) d).\n   eexists (unflatten_in _ _ v), (unflatten_acts _ _ v').\n   unfold unflatten_trans.\n   specialize (flatTrans_bound H H') as (?&<-&?&?&?&?).\n   rewrite !index_nth_elem_fint. 2,3:easy.\n   rewrite unflatten_in_correct. 2,3:now try rewrite Fin_cardinality;easy.\n   erewrite lookup_sound. 2:eapply flatTrans_inj;eassumption. 2:easy.\n   cbn -[finType_CS].\n   setoid_rewrite unflatten_in_correct. 2,3:now try rewrite Fin_cardinality;easy.\n   setoid_rewrite unflatten_acts_correct. 2,3:now try rewrite Fin_cardinality;easy.\n   repeat split.\n  -intros s0 v0.\n   unfold unflatten_trans.\n   edestruct lookup_complete with (def := (0,@nil (option nat * move))) as [H'|H'].\n   +erewrite lookup_sound. 3:eassumption. 2:eapply flatTrans_inj;eassumption.\n    edestruct lookup as (st0,l__r). left.\n    specialize (flatTrans_bound H H') as (?&?&?&?&?&?).\n    rewrite !index_nth_elem_fint. 2:easy. cbn -[finType_CS] in *.\n    replace ((index s0, map (option_map index) (Vector.to_list v0),\n              (st0, map (map_fst (option_map index)) (Vector.to_list (unflatten_acts (finType_CS (Fin.t sig)) n l__r)))))\n      with (index s0, map (option_map (fun x : Fin.t sig => index x)) (Vector.to_list v0), (st0, l__r)).\n    2:{ repeat f_equal. symmetry. rewrite unflatten_acts_correct. 1,2:easy. rewrite Fin_cardinality. easy. }\n    eassumption.\n   +erewrite lookup_sound'. 2:eapply flatTrans_inj;eassumption.\n    2:{right. easy. }\n    cbn -[finType_CS]. right.\n    setoid_rewrite index_nth. split. easy.\n    clear. unfold unflatten_acts,unflatten_acts'.\n    rewrite map_repeat. cbn.\n    (*Set Printing Implicit.*)\n    pattern n at 1 2 4 5 6 7.\n    replace n with (length (@repeat (option (Fin.t sig) * move) (@None (Fin.t sig), Nmove) n)) at 1.\n    2:now rewrite repeat_length.\n    rewrite Vector_of_list_length_eq.\n    now induction n;cbn.\nQed.\n\nLemma isFlatteningTrans_validFlatTrans n sig' (M' : TM sig' n) f:\nisFlatteningTransOf f (TM.trans (m:=M'))\n-> validFlatTrans (| elem sig' |) n (| elem (TM.state M')|) f.\nProof.\n  intros [H'].\n  split.\n  -intros [] [] [] (?&?&?&?&?&->&->&->&->)%H' (?&?&?&?&?&eq1&->&eq2&->)%H'.\n   apply injective_index in eq1 as <-.\n   enough (x1=x5) by congruence.\n   clear - eq2.\n   eapply map_injective in eq2.\n   + now apply vector_to_list_inj.\n   +intros [] [] [=]. 2:easy.\n    f_equal;eauto using injective_index.\n  -intros. eapply H' in H as (?&?&?&?&?&->&->&->&->).\n   repeat split.\n   +eapply index_le.\n   +now rewrite map_length,Vector.length_to_list.\n   +intros ? ([]&[=<- ]&?)%in_map_iff. eapply index_le.\n   +eapply index_le.\n   +rewrite map_length,Vector.length_to_list. easy.\n   +intros ? ? ([[]]&[= <- <-]&?)%in_map_iff. eapply index_le.\nQed.\n\nLemma unflattenTM_correct M:\n  validFlatTM M\n  -> isFlatteningTMOf M (unflattenTM M).\nProof.\n  intros (?&?). destruct M.\n  cbn in *.\n  assert (H_st:(Init.Nat.max 1 states) = states) by now destruct states.\n  econstructor; cbn - [finType_CS max].\n  -easy.\n  -now rewrite Fin_cardinality.\n  -rewrite H_st.\n   setoid_rewrite <- Fin_cardinality at 1. easy.\n  -eapply unflatten_trans_correct. \n   rewrite H_st. easy.\n  -generalize (def states).\n   rewrite H_st. intros ?.\n   unfold index. setoid_rewrite getPosition_nth. easy.\n   +apply dupfree_elements.\n   +now setoid_rewrite Fin_cardinality at 1.\n  - now econstructor.\nQed.\n\nLemma isFlattening_is_valid M sig n (M':TM sig n):\n  isFlatteningTMOf M M'\n  -> validFlatTM M.\nProof.\n  intros []. destruct M.\n  cbn in *;subst.\n  split;cbn.\n  -now apply isFlatteningTrans_validFlatTrans.\n  -apply index_le.\nQed.\n\nDefinition allSameEntry {X Y} eqbX eqbY `{_:eqbClass (X:=X) eqbX} `{eqbClass (X:=Y) eqbY} x y (f : list (X*Y)) :=\n  forallb (fun '(x',y') => implb (eqbX x x') (eqbY y y')) f.\n\nDefinition isInjFinfuncTable {X Y} eqbX eqbY `{_:eqbClass (X:=X) eqbX} `{eqbClass (X:=Y) eqbY}\n  := fix isInjFinfuncTable (f : list (X*Y)) : bool :=\n  match f with\n    [] => true\n  | (x,y)::f => allSameEntry x y f\n              && isInjFinfuncTable f\n  end.\n\nLemma allSameEntry_spec X Y eqbX eqbY `{Hx:eqbClass (X:=X) eqbX} `{Hy:eqbClass (X:=Y) eqbY} x y (f:list (X*Y)):\n  reflect (forall (y' : Y), (x, y') el f -> y = y') (allSameEntry x y f).\nProof.\n  unfold allSameEntry.\n  apply iff_reflect. rewrite forallb_forall.\n  transitivity (forall x' y',  (x',y') el f -> implb (eqbX x x') (eqbY y y') = true).\n  2:{split. now intros ? [].\n     intros H x' y'. specialize (H (x',y'));cbn in H. easy. }\n  split.\n  -intros H x' y' ?.\n   destruct (Hx x x'). 2:easy.\n   edestruct (Hy y y') as [ | []]. easy.\n   subst. eauto.\n  -intros H y' ?.\n   specialize (H x y').\n   destruct (Hx x x). 2:easy.\n   edestruct (Hy y y') as [ | ]. easy.\n   apply H in H0. easy.\nQed.\n\nLemma isInjFinfuncTable_spec X Y eqbX eqbY `{Hx:eqbClass (X:=X) eqbX} `{Hy:eqbClass (X:=Y) eqbY} (f:list (X*Y)):\n  reflect (forall (a : X) (b b' : Y), (a, b) el f -> (a, b') el f -> b = b') (isInjFinfuncTable f).\nProof.\n  induction f as [ |[x y] f].\n  cbn;constructor. easy.\n  cbn.\n  edestruct (allSameEntry_spec x y f) as [H' | H'].\n  2:{cbn. constructor.\n     intros H. eapply H'.  intros.\n     eapply H;[left|right].  all:easy.\n  }\n  cbn.\n  eapply ssrbool.equivP. eassumption.\n  split. 2:now firstorder.\n  intros ? ? ? ? [[= -> ->]| ] [[= ->] | ]. all:subst.\n  3:symmetry. all:easy.\nQed.           \n\nDefinition isBoundTransTable (sig n states : nat) (f : list (nat * list (option nat) * (nat * list (option nat * move)))) :=\n  forallb (fun '((s,v),(s',v')) =>\n             (s <? states)\n               && (length v =? n)\n               && (forallb (fun a => match a with None => true | Some a => a <? sig end) v)\n               && (s' <? states)\n               && (length v' =? n)\n               && (forallb (fun a => match fst a with None => true | Some a  => a <? sig end) v')) f.\n\nLemma isBoundTransTable_spec sig n states f:\n  reflect (forall (s s' : nat) (v : list (option nat)) (v' : list (option nat * move)),\n              (s, v, (s', v')) el f ->\n              s < states /\\\n          | v | = n /\\\n                (forall a : nat, Some a el v -> a < sig) /\\\n                s' < states /\\ | v' | = n /\\ (forall (a : nat) (m : move), (Some a, m) el v' -> a < sig))\n          (isBoundTransTable sig n states f).\nProof.\n  unfold isBoundTransTable.\n  apply iff_reflect. rewrite forallb_forall.\n  transitivity (forall (s s' : nat) (v : list (option nat)) (v' : list (option nat * move)),\n                    (s, v, (s', v')) el f \n     -> (((s <? states) && (| v | =? n) && forallb (fun a : option nat => match a with\n                                                                     | Some a => a <? sig\n                                                                     | None => true\n                                                                     end) v && (s' <? states) && (| v' | =? n) &&\n     forallb (fun a : option nat * move => match fst a with\n                                           | Some a => a <? sig\n                                           | None => true\n                                      end) v') = true)).\n  2:{split. now intros H [[] []]. \n     intros H s s' v v'. specialize (H ((s,v),(s',v')));cbn in H. easy. }\n  do 4 (eapply Morphisms_Prop.all_iff_morphism;intros ?).\n  eapply Morphisms_Prop.iff_iff_iff_impl_morphism. easy.\n  rewrite <- !andb_assoc. rewrite !andb_true_iff. \n  repeat apply Morphisms_Prop.and_iff_morphism.\n  1,4:now rewrite Nat.ltb_lt.\n  1,3:now rewrite Nat.eqb_eq.\n  all:rewrite forallb_forall.\n  {split.\n   -intros ? []. rewrite Nat.ltb_lt. all:easy.\n   -intros H ? ?%H. now rewrite <- Nat.ltb_lt.\n  }\n  {split.\n   -intros ? [[] ]; cbn - [Nat.ltb]. rewrite Nat.ltb_lt. all:easy.\n   -intros H ? ? ?%H. now rewrite <- Nat.ltb_lt.\n  }\nQed.   \n\nDefinition isValidFlatTrans sig n states (f : list (nat * list (option nat) * (nat * list (option nat * move)))) :=\n  isInjFinfuncTable  f && isBoundTransTable sig n states f.\n\nLemma isValidFlatTrans_spec sig n states f:\n  reflect (validFlatTrans sig n states f)\n          (isValidFlatTrans sig n states f).\nProof.\n  unfold isValidFlatTrans.\n  eapply iff_reflect.\n  rewrite andb_true_iff. rewrite <- !reflect_iff.\n  2:{ eapply isBoundTransTable_spec. }\n  2:{ eapply isInjFinfuncTable_spec. }\n  split.\n  -now intros [].\n  -econstructor. all:easy.\nQed.\n\nDefinition isValidFlatTM M :=\n  isValidFlatTrans M.(sig) M.(tapes) M.(states) M.(trans) && (M.(start) <? M.(states)).\n\nLemma isValidFlatTM_spec M:\n  reflect (validFlatTM M)\n          (isValidFlatTM M).\nProof.\n  unfold isValidFlatTM.\n  eapply iff_reflect.\n  destruct M; cbn -[Nat.ltb].\n  rewrite andb_true_iff. rewrite <- !reflect_iff.\n  2:{ apply Nat.ltb_spec0. }\n  2:{ apply isValidFlatTrans_spec. }\n  split;intros []. all:easy.\nQed.\n\n(** ** unflatten Tapes *)\n\nDefinition isValidFlatTape (sig:nat) (t:tape nat):=\n  forallb (fun x => Nat.ltb x sig) (tapeToList t).\n\nDefinition isValidFlatTapes (sig:nat) n (t:list (tape nat)):=\n  if length t =? n then forallb (isValidFlatTape sig) t else false.\n\nLemma tapeToList_map_commute sig sig' (f : sig -> sig') t :\n  tapeToList (mapTape f t) = map f (tapeToList t).\nProof.\n  destruct t;cbn. all:simpl_list.\n  all:try rewrite !map_rev. all:easy.\nQed.\n\nLemma flatteningTapeIsValid (sig:finType) n t (t' : TM_facts.tapes sig n):\n  isFlatteningTapesOf t t' ->\n  isValidFlatTapes (| elem sig |) n t = true.\nProof.\n  intros H. inv H.\n  unfold isValidFlatTapes.\n  rewrite Vector.length_to_list. rewrite Nat.eqb_refl.\n  induction t' as [ |t];cbn. easy.\n  rewrite andb_true_iff. split.\n  2:{easy. }\n  unfold isValidFlatTape.\n  rewrite tapeToList_map_commute.\n  setoid_rewrite forallb_forall.\n  intros ? (?&?&?)%in_map_iff.\n  rewrite Nat.ltb_lt.\n  subst. eapply index_le.\nQed.\n\n\nLemma isUnflattableTape sig t:\n  isValidFlatTape (| elem sig |) t = true -> {t' & t = (mapTape (index (F:=sig)) t')}.\nProof.\n  cbn. unfold isValidFlatTape.\n  intros H. rewrite forallb_forall in H. setoid_rewrite Nat.ltb_lt in H.\n  destruct t;cbn - [Nat.ltb].\n  -exists (niltape _). easy.\n  -eexists (leftof _ _). cbn. f_equal.\n   +symmetry;eapply index_nth_elem. apply H. cbn;easy.\n   +erewrite map_map. erewrite map_ext_in. now rewrite map_id.\n    intros. cbn. unfold Basics.compose. eapply index_nth_elem. apply H. cbn;easy.\n  -eexists (rightof _ _). cbn. f_equal.\n   +symmetry;eapply index_nth_elem. apply H. cbn;easy.\n   +erewrite map_map. erewrite map_ext_in. now rewrite map_id.\n    intros. cbn. unfold Basics.compose. eapply index_nth_elem. apply H. cbn. rewrite in_app_iff, <- in_rev. eauto. \n  -eexists (midtape _ _ _). cbn. f_equal.\n   +erewrite map_map. erewrite map_ext_in. now rewrite map_id.\n    intros. cbn. unfold Basics.compose. eapply index_nth_elem. apply H. cbn. rewrite in_app_iff, <- in_rev. eauto. \n   +symmetry;eapply index_nth_elem. apply H. cbn;easy.\n   +erewrite map_map. erewrite map_ext_in. now rewrite map_id.\n    intros. cbn. unfold Basics.compose. eapply index_nth_elem. apply H. cbn. rewrite in_app_iff, <- in_rev. eauto.\n    Unshelve.\n    all:cbn in H.\n    all:eapply defFin.\n    all:eapply Nat.le_lt_trans;[ | eapply H;easy].\n    all:Lia.lia.\nQed.\n   \nLemma isUnflattableTapes sig n t :\n  isValidFlatTapes (| elem sig |) n t = true -> {t' & isFlatteningTapesOf (sig:=sig) (n:=n) t t'}.\nProof.\n  cbn. unfold isValidFlatTapes.\n  intros H. destruct (Nat.eqb_spec (length t) n). 2:easy. subst n.\n  induction t.\n  -eexists [| |]. rewrite isFlatteningTapesOf_iff. easy.\n  -cbn in H.\n   rewrite !andb_true_iff in H. destruct H as (H'&H).\n   apply IHt in H as (v'&Hv).\n   apply isUnflattableTape in H' as (t0&Ht0).\n   eexists (t0:::v').\n   rewrite isFlatteningTapesOf_iff in *. cbn. f_equal. all: now cbv.\nQed.\n\n(** ** unflatten Conf *)\n\nDefinition validFlatTape sig (t : tape nat) :=\n  forall n, n el tapeToList t -> n < sig.\n\nLemma isValidFlatTape_spec sig t :\n  reflect (validFlatTape sig t) (isValidFlatTape sig t).\nProof.\n  unfold validFlatTape, isValidFlatTape.\n  apply iff_reflect. rewrite forallb_forall. setoid_rewrite Nat.ltb_lt. easy.\nQed.\n      \n\nDefinition validFlatConf M (c:mconfigFlat):=\n  let (s,ts) := c in\n   length ts = M.(tapes) /\\ Forall (validFlatTape M.(sig)) ts /\\ s < M.(states).\n\n(*\nLemma isValidFatConf_spec M c:\n  reflect (validFlatConf M c) (isFlatteningConfigOf (M.(states)) M.(sig) M.(tapes) c).\nProof.\n  unfold validFlatTape, isValidFlatTape.\n  apply iff_reflect. rewrite forallb_forall. setoid_rewrite Nat.ltb_lt. easy.\nQed.\n*)\n", "meta": {"author": "uds-psl", "repo": "coq-library-complexity", "sha": "5a996877f16fd6fe16dc5f0c3b933486957869df", "save_path": "github-repos/coq/uds-psl-coq-library-complexity", "path": "github-repos/coq/uds-psl-coq-library-complexity/coq-library-complexity-5a996877f16fd6fe16dc5f0c3b933486957869df/theories/L/TM/TMunflatten.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23324638135158382}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The L2C verified compiler                              *)\n(*                                                                     *)\n(*            L2C Group, Tsinghua University                           *)\n(*                                                                     *)\n(*  Copyright Tsinghua University.  All rights reserved.  This file is *)\n(*  distributed under the terms of the GNU General Public License as   *)\n(*  published by the Free Software Foundation, either version 2 of the *)\n(*  License, or (at your option) any later version.  This file is also *)\n(*  distributed under the terms of the INRIA Non-Commercial License    *)\n(*  Agreement.                                                         *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness proof for output parameters classification. *)\n\nRequire Import AST.\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Memdata.\nRequire Import Ctypes.\nRequire Import Cltypes.\nRequire Import List.\nRequire Import Lint.\nRequire Import ExtraList.\nRequire Import Ltypes.\nRequire Import Lident.\nRequire Import Lustre.\nRequire Import LustreF.\nRequire Import Lvalues.\nRequire Import Lenv.\nRequire Import Lenvmatch.\nRequire Import Lsem.\nRequire Import LsemF.\nRequire Import LsemD.\nRequire Import LsemE.\nRequire Import ClassifyRetsVar.\n\nSection CORRECTNESS.\n\nVariable prog1 prog2: program.\n\nHypothesis TRANSL: \n  trans_program prog1 = prog2.\n\nInductive mvl_match: mvl -> mvl -> type -> Prop :=\n  | mvl_match_val: forall m ty,\n     is_arystr ty = false ->\n     Z_of_nat (length m) = sizeof ty ->\n     mvl_match m m ty\n  | mvl_match_undef: forall m1 m2 ty,\n     is_arystr ty = false ->\n     is_undefs m1 ->\n     length m1 = length m2 ->\n     Z_of_nat (length m1) = sizeof ty ->\n     mvl_match m1 m2 ty\n  | mvl_match_ary: forall m1 m2 aid aty num,\n     mvl_array_match m1 m2 aty (nat_of_Z (Z.max 0 num)) ->\n     mvl_match m1 m2 (Tarray aid aty num)\n  | mvl_type_str: forall m1 m2 sid fld,\n     mvl_struct_match m1 m2 fld fld 0 ->\n     mvl_match m1 m2 (Tstruct sid fld)\n\nwith mvl_array_match: mvl -> mvl -> type -> nat -> Prop :=\n  | mvl_array_match_nil: forall ty,\n     mvl_array_match nil nil ty O \n  | mvl_array_match_cons: forall m1 m2 ml1 ml2 ty n,\n     mvl_match m1 m2 ty ->\n     mvl_array_match ml1 ml2 ty n ->\n     mvl_array_match (m1++ml1) (m2++ml2) ty (S n)\n\nwith mvl_struct_match: mvl -> mvl -> fieldlist -> fieldlist -> Z -> Prop :=\n  | mvl_struct_match_nil: forall m fld pos,\n     is_undefs m ->\n     Z_of_nat (length m) = align pos (alignof_fields fld) - pos  ->\n     mvl_struct_match m m Fnil fld pos \n  | mvl_struct_match_cons: forall m m1 m2 ml1 ml2 pos i t ftl fld,\n     is_undefs m ->\n     Z_of_nat (length m) = align pos (alignof t) - pos ->\n     mvl_match m1 m2 t ->\n     mvl_struct_match ml1 ml2 ftl fld (align pos (alignof t) + sizeof t) ->\n     mvl_struct_match (m++m1++ml1) (m++m2++ml2) (Fcons i t ftl) fld pos.\n\nScheme mvl_match_ind2 := Minimality for mvl_match Sort Prop\n  with mvl_array_match_ind2 := Minimality for mvl_array_match Sort Prop\n  with mvl_struct_match_ind2 := Minimality for mvl_struct_match Sort Prop.\nCombined Scheme mvl_match_arystr_ind2 from mvl_match_ind2, mvl_array_match_ind2, mvl_struct_match_ind2.\n\nDefinition ptree_vars_some(l: list (ident*type))(e: locenv): Prop :=\n  forall id ty, In (id,ty) l -> \n  exists m, e ! id = Some (m,ty) /\\ mvl_alloc m ty.\n\nDefinition locenv_mvl_alloc(te: locenv): Prop :=\n  forall id m ty, te ! id = Some (m,ty) -> mvl_alloc m ty.\n\nLemma mvl_match_length:\n(\n  forall m1 m2 ty, mvl_match m1 m2 ty -> length m1 = length m2\n)\n/\\\n(\n  forall m1 m2 ty n, mvl_array_match m1 m2 ty n -> length m1 = length m2\n)\n/\\\n(\n  forall m1 m2 fld f pos, mvl_struct_match m1 m2 fld f pos -> length m1 = length m2\n).\nProof.\n  apply mvl_match_arystr_ind2; intros; auto.\n  +repeat rewrite app_length. omega.\n  +repeat rewrite app_length. omega.\nQed.\n\nLemma mvl_match_sizeof:\n(\n  forall m1 m2 ty, mvl_match m1 m2 ty -> Z_of_nat (length m1) = sizeof ty \n)\n/\\\n(\n  forall m1 m2 ty n, mvl_array_match m1 m2 ty n ->\n  Z_of_nat (length m1) = sizeof ty * (Z_of_nat n) \n)\n/\\\n(\n  forall m1 m2 fld f pos, mvl_struct_match m1 m2 fld f pos -> Z_of_nat (length m1) =  align (sizeof_struct fld pos) (alignof_fields f) - pos\n). \nProof.\n  apply mvl_match_arystr_ind2; intros; auto.\n  +simpl. rewrite nat_of_Z_eq in H0; try xomega.\n  +simpl. omega.\n  +simpl. omega.\n  +rewrite app_length. rewrite Nat2Z.inj_add.\n   rewrite Nat2Z.inj_succ.\n   rewrite H0,H2. ring.\n  +rewrite app_length. rewrite Nat2Z.inj_add.\n   rewrite app_length. rewrite Nat2Z.inj_add.\n   rewrite H0,H2,H4. simpl. ring.\nQed.\n\nLemma mvl_match_mvl_type_eq:\n(\n  forall m1 m2 t,\n  mvl_match m1 m2 t ->\n  mvl_type true m1 t ->\n  m2 = m1\n)\n/\\\n(\n  forall m1 m2 t i,\n  mvl_array_match m1 m2 t i->\n  mvl_array true m1 t i ->\n  m2 = m1\n)\n/\\\n(\n  forall m1 m2 fld f pos,\n  mvl_struct_match m1 m2 fld f pos ->\n  mvl_struct true m1 fld f pos ->\n  m2 = m1\n).\nProof.\n  apply mvl_match_arystr_ind2; intros; auto.\n  +inv H3; simpl in *; try congruence.\n   destruct m1,m2; simpl in *; try omega; auto.\n   inv H0. inv H5. destruct m; simpl in *; tauto.\n  +inv H1; auto. simpl in *; congruence.\n  +inv H1; auto. simpl in *; congruence.\n  +inv H3. apply app_length_equal_inv in H4; auto.\n   destruct H4; subst. f_equal; auto.\n   left. apply mvl_match_sizeof in H.\n   apply mvl_type_length in H6.\n   apply Nat2Z.inj; congruence.\n  +f_equal. inv H5. apply app_length_equal_inv in H6; auto.\n   destruct H6; subst.\n   apply app_length_equal_inv in H6; auto.\n   destruct H6; subst. f_equal; auto.\n   -left. apply mvl_match_sizeof in H1.\n    apply mvl_type_length in H14. \n    apply Nat2Z.inj. congruence.\n   -left. apply Nat2Z.inj. congruence.\nQed.\n\nLemma mvl_match_self:\nforall b,\n(\n  forall m t,\n  mvl_type b m t ->\n  mvl_match m m t\n)\n/\\\n(\n  forall m t i,\n  mvl_array b m t i->\n  mvl_array_match m m t i\n)\n/\\\n(\n  forall m fld f pos,\n  mvl_struct b m fld f pos ->\n  mvl_struct_match m m fld f pos\n).\nProof.\n  intros b. apply mvl_type_arystr_ind2; intros;\n  try (econstructor; eauto; fail).\n +econstructor 3; eauto.\n +econstructor 4; eauto.\nQed.\n\nLemma mvl_match_mvl_alloc:\n(\n  forall m1 m2 t,\n  mvl_match m1 m2 t ->\n  mvl_type false m1 t /\\ mvl_type false m2 t\n)\n/\\\n(\n  forall m1 m2 t i,\n  mvl_array_match m1 m2 t i ->\n  mvl_array false m1 t i /\\ mvl_array false m2 t i\n) \n/\\\n(\n  forall m1 m2 fld f pos,\n  mvl_struct_match m1 m2 fld f pos ->\n  mvl_struct false m1 fld f pos /\\ mvl_struct false m2 fld f pos\n).\nProof.\n  apply mvl_match_arystr_ind2; intros; split;\n  try (econstructor; eauto; fail).\n +econstructor 1; eauto. congruence.\n +destruct H0. econstructor 2; eauto.\n +destruct H0. econstructor 2; eauto.\n +destruct H0. econstructor 3; eauto.\n +destruct H0. econstructor 3; eauto.\n +destruct H0,H2. econstructor 2; eauto.\n +destruct H0,H2. econstructor 2; eauto.\n +destruct H2, H4. econstructor 2; eauto.\n +destruct H2, H4. econstructor 2; eauto.\nQed.\n\nLemma mvl_match_alloc:\n(\n  forall m t,\n  mvl_type false m t ->\n  mvl_match (alloc (sizeof t)) m t\n)\n/\\\n(\n  forall m t i,\n  mvl_array false m t i ->\n  mvl_array_match (alloc (sizeof t * (Z_of_nat i))) m t i\n)\n/\\\n(\n  forall m fld f pos,\n  mvl_struct false m fld f pos ->\n  mvl_struct_match (alloc (align (sizeof_struct fld pos) (alignof_fields f) - pos)) m fld f pos\n).\nProof.\n  apply mvl_type_arystr_ind2; intros.\n  +constructor 2; auto.\n   apply is_undefs_alloc; auto.\n   rewrite <-H1. unfold alloc.\n   rewrite length_list_repeat, nat_of_Z_of_nat; auto.\n   rewrite <-H1. unfold alloc.\n   rewrite length_list_repeat, nat_of_Z_of_nat; auto.\n  +econstructor 3; eauto. simpl. \n   rewrite nat_of_Z_eq in H0; auto. xomega.\n  +constructor 4; auto. simpl.\n   rewrite Z.sub_0_r in H0. auto.\n  +simpl. rewrite Zmult_0_r.\n   unfold alloc. simpl. constructor.\n  +rewrite Nat2Z.inj_succ.\n   replace (sizeof ty * Z.succ (Z.of_nat n)) with (sizeof ty + sizeof ty * Z.of_nat n) by ring.\n   generalize (sizeof_pos ty); intros.\n   unfold alloc in *. rewrite Z2Nat.inj_add, list_repeat_app.\n   econstructor; eauto.\n   omega. apply Zmult_le_0_compat; omega.\n  +simpl. rewrite <-H0.\n   rewrite alloc_is_undefs; auto. econstructor; eauto.\n  +assert (align (sizeof_struct (Fcons i t ftl) pos) (alignof_fields fld) - pos =\n           Z_of_nat (length m) + Z_of_nat (length m1) + Z_of_nat (length ml)).\n    apply mvl_type_length in H1. apply mvl_type_length in H3.\n    rewrite H0, H1, H3. simpl. ring.\n   rewrite H5.\n   repeat rewrite Z2Nat.inj_add; try omega.\n   repeat rewrite alloc_app; try omega. \n   rewrite alloc_is_undefs; auto. rewrite app_ass.\n   econstructor; eauto.\n   apply mvl_type_length in H1. congruence.\n   apply mvl_type_length in H3. congruence.\nQed.\n\nLemma mvl_array_match_getN:\n  forall n i o m1 m2 t,\n  mvl_array_match (getN (nat_of_Z (sizeof t) * n) o m1) (getN (nat_of_Z (sizeof t) * n) o m2) t n ->\n  (i < n)%nat ->\n  length m1 = length m2 ->\n  (o + (nat_of_Z (sizeof t) * n) <= length m1)%nat ->\n  mvl_match (getN (nat_of_Z (sizeof t)) (o + (nat_of_Z (sizeof t)) * i) m1) (getN (nat_of_Z (sizeof t)) (o + (nat_of_Z (sizeof t)) * i) m2) t.\nProof.\n  induction n; intros; try omega.\n  change (S n) with (1 + n)%nat in *.\n  rewrite mult_plus_distr_l, mult_1_r in H.\n  repeat rewrite getN_add in H. inv H.\n  generalize H6 H6 H8 H8; intros A A1 A2 A3.\n  apply mvl_match_length in A. apply mvl_match_length in A2.\n  apply mvl_match_sizeof in A1. apply mvl_match_sizeof in A3.\n  cut (length m3 = length (getN (nat_of_Z (sizeof t)) o m2)). intros A4.\n  apply app_length_equal_inv in H3.\n  apply app_length_equal_inv in H4; auto.\n  destruct H3,H4. subst.\n  destruct n.\n  +destruct i; try omega.\n   rewrite mult_0_r, plus_0_r in *; auto.\n  +destruct i.\n   -rewrite mult_0_r, plus_0_r in *; auto.\n   -change (S i) with (1 + i)%nat.\n    rewrite mult_plus_distr_l, mult_1_r, plus_assoc in *.\n    apply IHn; auto. omega.\n  +left. rewrite A, A4. unfold getN, getn.\n   repeat rewrite firstn_length, skipn_length. congruence.\n  +rewrite <-nat_of_Z_of_nat with o.\n   rewrite <-getN_length; try omega. rewrite <-A1.\n   rewrite nat_of_Z_of_nat; auto.\n   generalize (sizeof_pos t); intros.\n   rewrite mult_plus_distr_l, mult_1_r in H2.\n   apply Nat2Z.inj_le in H2.\n   repeat rewrite Nat2Z.inj_add in H2.\n   rewrite nat_of_Z_eq in H2; try omega. \nQed.\n\nLemma mvl_struct_match_getN:\n  forall f fld m1 m2 pos i delta t,\n  mvl_struct_match m1 m2 fld f pos ->\n  length m1 = length m2 ->\n  0 <= pos ->\n  field_offset_rec i fld pos = OK delta ->\n  field_type i fld = OK t ->\n  mvl_match (getN (nat_of_Z (sizeof t)) (nat_of_Z (delta-pos)) m1) \n            (getN (nat_of_Z (sizeof t)) (nat_of_Z (delta-pos)) m2) t.\nProof.\n  induction fld; simpl; intros; try congruence.\n  compare i i0; intros; subst.\n  +rewrite peq_true in *. inv H3. inv H2.\n   inv H. rewrite <-H8. rewrite nat_of_Z_of_nat.\n   replace (length m) with (0+length m)%nat by omega.\n   repeat rewrite getN_app_skipn. rewrite skipn_length_app; try omega.\n   rewrite minus_diag. simpl. rewrite skipn_length_app; try omega.\n   rewrite minus_diag. simpl.\n   unfold getN,getn. simpl. generalize H11 H11; intros A A1.\n   apply mvl_match_sizeof in A1. apply mvl_match_length in A.\n   rewrite <-A1. rewrite nat_of_Z_of_nat. rewrite A at 2.\n   repeat rewrite firstn_length_app2; try omega.\n   repeat rewrite minus_diag. simpl.\n   repeat rewrite <-app_nil_end. auto.\n  +rewrite peq_false in *; auto. inv H.\n   generalize H13 H13; intros A A1.\n   apply mvl_match_sizeof in A. apply mvl_match_length in A1.\n   replace (delta - pos) with ((delta - (align pos (alignof t) + sizeof t)) + (align pos (alignof t) - pos + sizeof t)) by omega.\n   rewrite <-H10. rewrite <-A. rewrite <-Nat2Z.inj_add.\n   cut (0 <= delta - align pos (alignof t) - Z.of_nat (length m0)). intros A2.\n   rewrite A1 at 4. repeat rewrite Z2Nat.inj_add; try omega.\n   repeat rewrite nat_of_Z_of_nat, <-app_length.\n   repeat rewrite getN_app_skipn, <-app_ass.   \n   repeat rewrite skipn_length_app; try omega.\n   repeat rewrite minus_diag. simpl.\n   apply IHfld with i0; try omega; try congruence.\n   -eapply mvl_match_length in H14; eauto.\n   -eapply field_offset_rec_in_range in H3; eauto. omega.\nQed.\n\nLemma eval_offset_mvl_match_sube:\n  forall t a o,\n  eval_offset t a o ->\n  forall m1 m2,\n  mvl_match m1 m2 t ->\n  mvl_match (getN (nat_of_Z (sizeof (typeof a))) (nat_of_Z o) m1) (getN (nat_of_Z (sizeof (typeof a))) (nat_of_Z o) m2) (typeof a).\nProof.\n  induction 1; intros.\n  +simpl. generalize H H; intros. apply mvl_match_length in H.\n   apply mvl_match_sizeof in H1.\n   rewrite <-H1, nat_of_Z_of_nat.\n   rewrite getN_full; auto.\n   rewrite H. rewrite getN_full; auto.\n  +simpl. generalize H H; intros. apply mvl_match_length in H.\n   apply mvl_match_sizeof in H1.\n   rewrite <-H1, nat_of_Z_of_nat.\n   rewrite getN_full; auto.\n   rewrite H. rewrite getN_full; auto.\n  +rewrite H0 in *. simpl in *.\n   generalize H. intros.\n   generalize H2; intros.\n   apply IHeval_offset in H2; auto.\n   apply eval_offset_pos in H3.\n   generalize (sizeof_pos t0). intros.\n   rewrite H0 in *. simpl in *.\n   generalize (Zle_max_l 1 z) (Zle_max_r 1 z); intros.\n   rewrite Z2Nat.inj_add; try omega.\n   rewrite Z2Nat.inj_mul in *; try omega.\n   inv H2; simpl in *; try congruence.\n   apply mvl_array_match_getN with (nat_of_Z (Z.max 0 z)); auto.\n   apply Z2Nat.inj_lt; try omega.\n   eapply mvl_match_length in H4; eauto.\n   apply mvl_match_sizeof in H4. rewrite <-H4 in *.\n   apply Nat2Z.inj_le. rewrite Nat2Z.inj_add, nat_of_Z_eq; try omega.\n   rewrite Nat2Z.inj_mul; try omega. repeat rewrite nat_of_Z_eq; try omega.\n   apply Zmult_le_0_compat; omega.\n  +rewrite H0 in *. simpl typeof in *.\n   generalize H; intros A. apply eval_offset_pos in A.\n   apply IHeval_offset in H3; auto.\n   change (sizeof (Tstruct sid fld)) with (sizeof_fld fld) in *.\n   inv H3; simpl in *; try congruence.\n   generalize H1; intros. eapply field_offset_in_range_simpl in H3; eauto.\n   rewrite Z2Nat.inj_add; try omega.\n   generalize (sizeof_pos t0). intros.\n   cut ((Z.to_nat delta + nat_of_Z (sizeof t0) <= nat_of_Z (sizeof_fld fld))%nat). intros.\n   repeat rewrite getN_app with (n1:=nat_of_Z (sizeof_fld fld)); auto.\n   replace delta with (delta - 0) by omega.\n   eapply mvl_struct_match_getN; eauto; try omega.\n   -apply mvl_match_length in H7; auto.\n   -apply Nat2Z.inj_le. rewrite Nat2Z.inj_add.\n    repeat rewrite nat_of_Z_eq; try omega.\nQed.\n\nLemma eval_offset_mvl_alloc_sube:\n  forall t a o,\n  eval_offset t a o ->\n  forall m,\n  mvl_alloc m t ->\n  mvl_alloc (getN (nat_of_Z (sizeof (typeof a))) (nat_of_Z o) m) (typeof a).\nProof.\n  intros.\n  apply mvl_match_mvl_alloc with (m1:=getN (nat_of_Z (sizeof (typeof a))) (nat_of_Z o) m).\n  eapply eval_offset_mvl_match_sube; eauto.\n  eapply mvl_match_self; eauto.\nQed.\n\nLemma getN_first_app:\n  forall n1 n2 l1 l2, n1 = length l1 ->\n  getN (n1+n2) 0 (l1 ++ l2) = l1 ++ getN n2 0 l2.\nProof.\n  unfold getN, getn. intros. subst. simpl.\n  rewrite firstn_length_app2; try omega.\n  f_equal. f_equal. omega.\nQed.\n\nLemma getN_first_simpl:\n  forall n l1 l2, n = length l1 ->\n  getN n 0 (l1 ++ l2) = l1.\nProof.\n  intros. replace n with (n + 0)%nat; try omega.\n  rewrite getN_first_app; auto.\n  unfold getN,getn. simpl. rewrite <-app_nil_end; auto.\nQed.\n\nLemma mvl_array_match_setn:\n  forall m m' t n m1 m2 m3 m1' m2' m3' i,\n  mvl_array_match (m1 ++ m2 ++ m3) (m1' ++ m2' ++ m3') t n ->\n  mvl_match m m' t ->\n  length m1 = length m1' -> \n  length m2 = length m2' ->\n  length m3 = length m3' ->\n  length m2 = length m' ->\n  (length m1 = nat_of_Z (sizeof t) * i)%nat ->\n  mvl_array_match (m1 ++ m ++ m3) (m1' ++ m' ++ m3') t n.\nProof.\n  induction n; simpl; intros; inv H; try omega.\n  +destruct m1,m2,m3, m1', m2', m3'; simpl in *; try congruence.\n   apply mvl_match_length in H0.\n   destruct m, m'; simpl in *; try omega.\n   constructor.\n  +destruct i.\n   -rewrite mult_0_r in H5. \n    destruct m1,m1'; simpl in *; try omega.\n    econstructor; eauto.\n    apply app_length_equal_inv in H6. destruct H6. subst.\n    apply app_length_equal_inv in H7. destruct H7. subst.\n    auto.\n    left. rewrite <-H2. apply mvl_match_length in H9; auto.\n    left. apply mvl_match_sizeof in H9. generalize H0; intros A.\n    apply mvl_match_sizeof in H0. apply mvl_match_length in A. \n    rewrite <-H9 in H0. apply Nat2Z.inj in H0. congruence.\n   -change (S i) with (1 + i)%nat in *.\n    rewrite mult_plus_distr_l, mult_1_r in H5.\n    generalize (firstn_skipn (nat_of_Z (sizeof t)) m1).\n    generalize (firstn_skipn (nat_of_Z (sizeof t)) m1').\n    intros A A1. rewrite <-A,<-A1. rewrite <-A in H7.\n    rewrite <-A1 in H6. repeat rewrite app_ass in *.\n    assert(A2: forall (l1:mvl) l2 l3 l4, l1++l2 ++ l3 ++ l4 = l1 ++ (l2++l3)++l4).\n     intros. repeat rewrite <-app_ass. auto.\n    repeat rewrite A2.\n    apply app_length_equal_inv in H6. destruct H6. subst m0 ml1.\n    apply app_length_equal_inv in H7. destruct H7. subst m4 ml2.\n    econstructor 2; eauto.\n    *repeat rewrite app_ass. apply IHn with m2 m2' i; auto.\n     repeat rewrite skipn_length. congruence.\n     rewrite skipn_length. rewrite min_l.\n     rewrite H5. eauto with *.\n     rewrite H5. eauto with *.\n    *left. apply mvl_match_length in H9. rewrite <-H9. \n     repeat rewrite firstn_length. congruence.\n    *left. rewrite firstn_length. rewrite min_l; try omega.\n     apply mvl_match_sizeof in H9. rewrite <-H9.\n      rewrite nat_of_Z_of_nat. auto.\n     rewrite H5. eauto with *.\nQed.\n\nLemma mvl_struct_match_setn:\n  forall m m' f fld m1 m2 m3 m1' m2' m3' pos i t delta,\n  mvl_struct_match (m1 ++ m2 ++ m3) (m1' ++ m2' ++ m3') fld f pos ->\n  mvl_match m m' t ->\n  field_offset_rec i fld pos = OK delta ->\n  field_type i fld = OK t ->\n  length m1 = length m1' -> \n  length m2 = length m2' ->\n  length m3 = length m3' ->\n  length m2 = length m' ->\n  (length m1 = nat_of_Z (delta - pos))%nat ->\n  mvl_struct_match (m1 ++ m ++ m3) (m1' ++ m' ++ m3') fld f pos.\nProof.\n  induction fld; simpl; intros; inv H; try congruence.\n  generalize H17 H17 H0 H0. intros A A1 A2 A3.\n  apply mvl_match_length in A. apply mvl_match_sizeof in A1.\n  apply mvl_match_sizeof in A2. apply mvl_match_length in A3.\n  compare i0 i; intros; subst.\n  +rewrite peq_true in *. inv H1. inv H2.\n   apply app_length_equal_inv in H8; auto. destruct H8. subst.\n   apply app_length_equal_inv in H9; auto. destruct H9. subst.\n   apply app_length_equal_inv in H1; auto. destruct H1. subst.\n   apply app_length_equal_inv in H2; auto. destruct H2. subst.\n   econstructor 2; eauto.\n   -left. congruence.\n   -left. rewrite <-A1 in A2. apply Nat2Z.inj in A2. congruence.\n   -left. rewrite <-H14 in H7. rewrite nat_of_Z_of_nat in H7; auto.\n  +rewrite peq_false in *; auto.\n   generalize (firstn_skipn (length m0) m1).\n   generalize (firstn_skipn (length m0) m1').\n   intros A4 A5. rewrite <-A4,<-A5. rewrite <-A4 in H9.\n   rewrite <-A5 in H8. repeat rewrite app_ass in *.\n   generalize (firstn_skipn (length m4) (skipn (length m0) m1)).\n   generalize (firstn_skipn (length m4) (skipn (length m0) m1')).\n   intros A6 A7. rewrite <-A6,<-A7. rewrite <-A6 in H9.\n   rewrite <-A7 in H8. repeat rewrite app_ass in *.\n   assert(A8: forall (l1:mvl) l2 l3 l4 l5, l1++l2 ++ l3 ++ l4 ++ l5 = l1 ++ l2 ++(l3++l4++l5)).\n     intros. repeat rewrite <-app_ass. auto.\n   repeat rewrite A8.\n   generalize H1; intros A9. eapply field_offset_rec_in_range in A9; eauto.\n   cut ((length m0 + length m4 <= length m1)%nat). intros A10.\n   apply app_length_equal_inv in H8. destruct H8. rewrite <-H in *.\n   apply app_length_equal_inv in H9. destruct H9. rewrite <-H9 in *.\n   apply app_length_equal_inv in H8. destruct H8. rewrite <-H8 in *.\n   apply app_length_equal_inv in H10. destruct H10. rewrite <-H10 in *.\n   repeat rewrite <-skipn_add in *.\n   econstructor 2; eauto.\n   -apply IHfld with m2 m2' i0 t0 delta; auto.\n    *congruence.\n    *repeat rewrite skipn_length. congruence.\n    *rewrite skipn_length. rewrite min_l; try omega.\n     apply Nat2Z.inj. rewrite nat_of_Z_eq.\n     rewrite Nat2Z.inj_sub, Nat2Z.inj_add; try omega.\n     rewrite H14,A1, H7. rewrite nat_of_Z_eq; try omega.\n     omega.\n   -left. rewrite firstn_length. rewrite min_l; auto.\n    rewrite skipn_length. rewrite min_l; try omega.\n   -left. rewrite firstn_length. rewrite min_l; auto.\n    rewrite skipn_length. rewrite min_l; try omega.\n   -left. rewrite firstn_length. rewrite min_l; omega.\n   -left. rewrite firstn_length. rewrite min_l; omega.\n   -apply Nat2Z.inj_le. rewrite Nat2Z.inj_add. \n    rewrite H14,A1,H7. rewrite nat_of_Z_eq; try omega.\nQed.\n\nLemma mvl_match_setn_sube:\n  forall t a ofs,\n  eval_offset t a ofs ->\n  forall m1 m2 m3 m1' m2' m3' m m',\n  mvl_match (m1++m2++m3) (m1'++m2'++m3') t ->\n  mvl_match m m' (typeof a) ->\n  length m1 = length m1' ->\n  length m2 = length m2' ->\n  length m3 = length m3' ->\n  length m2 = length m' ->\n  length m1 = nat_of_Z ofs -> \n  mvl_match (m1++m++m3) (m1'++m'++m3') t.\nProof.\n  induction 1; simpl; intros.\n  +destruct m1, m1'; simpl in *; try omega.\n   generalize H H0 H0; intros. apply mvl_match_sizeof in H.\n   apply mvl_match_sizeof in H0. apply mvl_match_length in H7.\n   rewrite app_length,H4, <-H0 in *.\n   apply Nat2Z.inj in H.\n   destruct m3,m3'; simpl in *; try omega.\n   repeat rewrite <-app_nil_end; auto.\n  +destruct m1, m1'; simpl in *; try omega.\n   generalize H H0 H0; intros. apply mvl_match_sizeof in H.\n   apply mvl_match_sizeof in H0. apply mvl_match_length in H7.\n   rewrite app_length,H4, <-H0 in *.\n   apply Nat2Z.inj in H.\n   destruct m3,m3'; simpl in *; try omega.\n   repeat rewrite <-app_nil_end; auto.\n  +rewrite H0 in *. generalize H. intros A.\n   apply eval_offset_pos in A.\n   generalize H3 H3 H2; intros B B1 B3.\n   apply mvl_match_sizeof in B. apply mvl_match_length in B1.\n   apply mvl_match_sizeof in B3. repeat rewrite app_length in B3.\n   rewrite <-firstn_skipn with (l:=m1) (n:=nat_of_Z ofs).\n   rewrite <-firstn_skipn with (l:=m1') (n:=nat_of_Z ofs).\n   rewrite <-firstn_skipn with (l:=m3) (n:=nat_of_Z (sizeof t0 * Z.max 0 z - (sizeof t0 + sizeof t0 * i))).\n   rewrite <-firstn_skipn with (l:=m3') (n:=nat_of_Z (sizeof t0 * Z.max 0 z - (sizeof t0 + sizeof t0 * i))).\n   rewrite <-firstn_skipn with (l:=m1) (n:=nat_of_Z ofs) in H2.\n   rewrite <-firstn_skipn with (l:=m1') (n:=nat_of_Z ofs) in H2.\n   rewrite <-firstn_skipn with (l:=m3) (n:=nat_of_Z (sizeof t0 * Z.max 0 z - (sizeof t0 + sizeof t0 * i))) in H2.\n   rewrite <-firstn_skipn with (l:=m3') (n:=nat_of_Z (sizeof t0 * Z.max 0 z - (sizeof t0 + sizeof t0 * i))) in H2.\n   assert(A1: forall (l1:mvl) l2 l3 l4 l5, (l1++l2) ++ l3 ++ (l4++l5) = l1 ++ (l2++l3++l4) ++l5).\n     intros. repeat rewrite <-app_ass. auto.\n   repeat rewrite A1 in *.\n   rewrite Z2Nat.inj_add in H8; try omega.\n   cut (length (firstn (nat_of_Z ofs) m1) = nat_of_Z ofs).\n   cut (length (firstn (nat_of_Z ofs) m1') = nat_of_Z ofs). intros A2 A3.\n   cut (0 <= sizeof t0 * i). intros A4.\n   generalize (sizeof_pos t0). intros A5.\n   cut (sizeof t0 + sizeof t0 * i <= sizeof t0 * Z.max 0 z). intros A6.\n   cut (Z.to_nat (sizeof t0 * Z.max 0 z) - Z.to_nat (sizeof t0 + sizeof t0 * i) <=length m3')%nat. intros A7.\n   eapply IHeval_offset; eauto.\n   -eapply eval_offset_mvl_match_sube in H2; eauto.\n    rewrite H0 in *.\n    rewrite <-plus_0_l with (nat_of_Z ofs) in H2.\n    repeat rewrite getN_app_skipn in H2. simpl in *.\n    rewrite skipn_length_app in H2; try omega. rewrite A3, minus_diag in H2. simpl in *.\n    rewrite skipn_length_app in H2; try omega. rewrite A2, minus_diag in H2. simpl in *.\n    inv H2; simpl in *; try congruence. constructor 3; auto.\n    assert (A8: (nat_of_Z (sizeof t0 * Z.max 0 z) =\n                nat_of_Z (sizeof t0 * i) + (nat_of_Z (sizeof t0) + nat_of_Z (sizeof t0 * Z.max 0 z - (sizeof t0 + sizeof t0 * i))))%nat).\n      rewrite <-Z2Nat.inj_add; try omega.\n      rewrite <-Z2Nat.inj_add; try omega.\n      change nat_of_Z with Z.to_nat. f_equal. omega.\n    rewrite A8 in H12. repeat rewrite app_ass in H12.\n    change nat_of_Z with Z.to_nat in *.\n    rewrite getN_first_app, getN_first_app, getN_first_app, getN_first_app in H12.\n    rewrite getN_first_simpl, getN_first_simpl in H12.\n    *eapply mvl_array_match_setn with (i:=nat_of_Z i); eauto.\n     repeat rewrite skipn_length. congruence.\n     repeat rewrite firstn_length. congruence.\n     rewrite skipn_length. \n     rewrite <-Z2Nat.inj_mul; try omega.\n     rewrite min_l; try omega.\n    *rewrite firstn_length. rewrite min_l; try omega.\n     rewrite Z2Nat.inj_sub; try omega.\n    *rewrite firstn_length. rewrite min_l; try omega.\n     rewrite Z2Nat.inj_sub; try omega.\n    *rewrite <-B. rewrite nat_of_Z_of_nat. congruence.\n    *rewrite skipn_length. rewrite min_l; try omega.\n    *rewrite H7. rewrite <-B. rewrite nat_of_Z_of_nat; try omega. \n    *rewrite skipn_length. rewrite min_l; try omega.\n   -repeat rewrite firstn_length. congruence.\n   -repeat rewrite app_length. repeat rewrite firstn_length.\n    repeat rewrite skipn_length. congruence.\n   -repeat rewrite skipn_length. congruence.\n   -repeat rewrite app_length. repeat rewrite firstn_length.\n    repeat rewrite skipn_length. congruence.\n   -rewrite H7, H8,<-B1 in B3. \n    repeat rewrite Nat2Z.inj_add in B3; try omega.\n    rewrite B in B3. rewrite <-B3, H0 in A.\n    simpl in A. \n    rewrite nat_of_Z_eq in A; try omega.\n    rewrite nat_of_Z_eq in A; try omega. \n    apply Nat2Z.inj_le. rewrite Nat2Z.inj_sub; try omega.\n    rewrite nat_of_Z_eq; try omega.\n    rewrite nat_of_Z_eq; try omega.\n    apply Z2Nat.inj_le; auto; try omega.\n   -apply Zle_trans with (sizeof t0 * (1 + i)).\n    rewrite Z.mul_add_distr_l; omega.\n    apply Zmult_le_compat_l; try omega.\n   -apply Zmult_le_0_compat; omega.\n   -rewrite firstn_length. rewrite min_l; try omega.\n    change nat_of_Z with Z.to_nat. omega.\n   -rewrite firstn_length. rewrite min_l; try omega.\n    change nat_of_Z with Z.to_nat. omega.\n   -apply Zmult_le_0_compat; omega.\n  +rewrite H0 in *. generalize H. intros A.\n   apply eval_offset_pos in A.\n   generalize H4 H4 H3; intros B B1 B3.\n   apply mvl_match_sizeof in B. apply mvl_match_length in B1.\n   apply mvl_match_sizeof in B3. repeat rewrite app_length in B3.\n   generalize H1; intros B4.\n   eapply field_offset_in_range with (sid:=sid) in B4; eauto.\n   rewrite <-firstn_skipn with (l:=m1) (n:=nat_of_Z ofs).\n   rewrite <-firstn_skipn with (l:=m1') (n:=nat_of_Z ofs).\n   rewrite <-firstn_skipn with (l:=m3) (n:=nat_of_Z (sizeof (Tstruct sid fld) - (delta + sizeof t0))).\n   rewrite <-firstn_skipn with (l:=m3') (n:=nat_of_Z (sizeof (Tstruct sid fld) - (delta + sizeof t0))).\n   rewrite <-firstn_skipn with (l:=m1) (n:=nat_of_Z ofs) in H3.\n   rewrite <-firstn_skipn with (l:=m1') (n:=nat_of_Z ofs) in H3.\n   rewrite <-firstn_skipn with (l:=m3) (n:=nat_of_Z (sizeof (Tstruct sid fld) - (delta + sizeof t0))) in H3.\n   rewrite <-firstn_skipn with (l:=m3') (n:=nat_of_Z (sizeof (Tstruct sid fld) - (delta + sizeof t0))) in H3.\n   assert(A1: forall (l1:mvl) l2 l3 l4 l5, (l1++l2) ++ l3 ++ (l4++l5) = l1 ++ (l2++l3++l4) ++l5).\n     intros. repeat rewrite <-app_ass. auto.\n   repeat rewrite A1 in *.\n   rewrite Z2Nat.inj_add in H9; try omega.\n   cut (length (firstn (nat_of_Z ofs) m1) = nat_of_Z ofs).\n   cut (length (firstn (nat_of_Z ofs) m1') = nat_of_Z ofs). intros A2 A3.\n   generalize (sizeof_pos t0). intros A5.\n   cut (Z.to_nat (sizeof (Tstruct sid fld)) - Z.to_nat (delta + sizeof t0) <=length m3')%nat. intros A7.\n   eapply IHeval_offset; eauto.\n   -eapply eval_offset_mvl_match_sube in H3; eauto.\n    rewrite H0 in *.\n    rewrite <-plus_0_l with (nat_of_Z ofs) in H3.\n    repeat rewrite getN_app_skipn in H3. rewrite plus_0_l in H3.\n    rewrite skipn_length_app in H3; try omega. rewrite A3, minus_diag in H3. simpl in H3.\n    rewrite skipn_length_app in H3; try omega. rewrite A2, minus_diag in H3. simpl in H3.\n    inv H3; simpl in *; try congruence. constructor 4; auto.\n    remember (align (sizeof_struct _ _) _).\n    assert (A8: (nat_of_Z z =\n                nat_of_Z delta + (nat_of_Z (sizeof t0) + nat_of_Z (z - (delta + (sizeof t0)))))%nat).\n      rewrite <-Z2Nat.inj_add; try omega.\n      rewrite <-Z2Nat.inj_add; try omega.\n      change nat_of_Z with Z.to_nat. f_equal. omega.\n    rewrite A8 in H13. repeat rewrite app_ass in H13.\n    change nat_of_Z with Z.to_nat in *.\n    rewrite getN_first_app, getN_first_app,getN_first_app,getN_first_app in H13.\n    rewrite getN_first_simpl, getN_first_simpl in H13.\n    *eapply mvl_struct_match_setn; eauto.\n     repeat rewrite skipn_length. congruence.\n     repeat rewrite firstn_length. congruence.\n     rewrite skipn_length. rewrite min_l; try omega.\n     rewrite Zminus_0_r. rewrite H9. eauto with *. \n    *rewrite firstn_length. rewrite min_l; try omega.\n     rewrite Z2Nat.inj_sub; try omega.\n    *rewrite firstn_length. rewrite min_l; try omega.\n     rewrite Z2Nat.inj_sub; try omega.\n    *rewrite <-B. rewrite nat_of_Z_of_nat. congruence.\n    *rewrite skipn_length. rewrite min_l; try omega.\n    *rewrite H8. rewrite <-B. rewrite nat_of_Z_of_nat; try omega. \n    *rewrite skipn_length. rewrite min_l; try omega.\n   -repeat rewrite firstn_length. congruence.\n   -repeat rewrite app_length. repeat rewrite firstn_length.\n    repeat rewrite skipn_length. congruence.\n   -repeat rewrite skipn_length. congruence.\n   -repeat rewrite app_length. repeat rewrite firstn_length.\n    repeat rewrite skipn_length. congruence.\n   -rewrite H7, H8,H9,<-B1 in B3. \n    repeat rewrite Nat2Z.inj_add in B3; try omega.\n    rewrite B in B3. rewrite <-B3, H0 in A. \n    rewrite nat_of_Z_eq in A; try omega.\n    rewrite nat_of_Z_eq in A; try omega.\n    apply Nat2Z.inj_le. rewrite Nat2Z.inj_sub; try omega.\n    rewrite nat_of_Z_eq; try omega.\n    rewrite nat_of_Z_eq; try omega.\n    apply Z2Nat.inj_le; auto; try omega.\n   -rewrite firstn_length. rewrite min_l; try omega.\n    change nat_of_Z with Z.to_nat. omega.\n   -rewrite firstn_length. rewrite min_l; try omega.\n    change nat_of_Z with Z.to_nat. omega.\nQed.\n\nLemma mvl_match_setn:\n  forall t a ofs,\n  eval_offset t a ofs ->\n  forall m1 m2 m',\n  mvl_match m1 m2 t ->\n  mvl_alloc m' (typeof a) ->\n  mvl_match (setN m' (nat_of_Z ofs) m1) (setN m' (nat_of_Z ofs) m2) t.\nProof.\n  unfold setN, replace_map. intros.\n  generalize H0 H0 H1 H; intros A A1 A2 A3.\n  apply mvl_match_length in A. apply mvl_match_sizeof in A1.\n  apply mvl_type_length in A2. apply eval_offset_pos in A3.\n  rewrite <-firstn_skipn with (l:=m1) (n:=nat_of_Z ofs) in H0.\n  rewrite <-firstn_skipn with (l:=m2) (n:=nat_of_Z ofs) in H0.\n  rewrite <-firstn_skipn with (l:=skipn (nat_of_Z ofs) m1) (n:=length m') in H0.\n  rewrite <-firstn_skipn with (l:=skipn (nat_of_Z ofs) m2) (n:=length m') in H0.\n  repeat rewrite <-skipn_add in H0.\n  destruct A3 as [A3 A4]. rewrite <-A1 in A4.\n  rewrite <-A2 in *. generalize A4; intros A5.\n  apply Z2Nat.inj_le in A4; try omega.\n  rewrite Z2Nat.inj_add, nat_of_Z_of_nat,nat_of_Z_of_nat in A4; try omega.\n  eapply mvl_match_setn_sube; eauto.\n  +eapply mvl_match_self; eauto.\n  +repeat rewrite firstn_length. congruence.\n  +repeat rewrite firstn_length.\n   repeat rewrite skipn_length. congruence.\n  +repeat rewrite skipn_length. congruence.\n  +rewrite firstn_length, skipn_length.\n   rewrite min_l; try omega.\n   change nat_of_Z with Z.to_nat.\n   rewrite min_l; try omega.\n  +rewrite firstn_length.\n   change nat_of_Z with Z.to_nat.\n   rewrite min_l; try omega.\nQed.\n\nLemma mvl_alloc_setn:\n  forall t a ofs m,\n  eval_offset t a (Int.unsigned ofs) ->\n  mvl_alloc m t ->\n  forall m', mvl_alloc m' (typeof a) ->\n  (nat_of_Z (Int.unsigned ofs) + length m' <= length m)%nat ->\n  mvl_alloc (setN m' (nat_of_Z (Int.unsigned ofs)) m) t.\nProof.\n  intros. \n  eapply mvl_match_mvl_alloc with (m1:=setN m' (nat_of_Z (Int.unsigned ofs)) m); eauto.\n  eapply mvl_match_setn; eauto.\n  eapply mvl_match_self; eauto.\nQed.\n\nDefinition locenv_match_ret(te eh: locenv)(id: ident): Prop :=\n  exists m1 m2 t, te ! id = Some (m1,t)\n    /\\ eh ! id = Some (m2,t)\n    /\\ mvl_match m1 m2 t.\n\nDefinition locenv_match_rets(te eh: locenv)(ids: list ident): Prop :=\n  forall id, In id ids -> locenv_match_ret te eh id.\n\n\nDefinition subenv_ids(P: ident*func -> env -> Prop) (se: subenv)(l: list calldef): Prop :=\n  forall c, In c l -> \n    exists fd el,  find_funct (node_block prog1) (callid c) = Some fd\n     /\\ se ! (instid c) = Some el\n     /\\ Forall (P fd) el.\n\nInductive env_ids_none(nd: ident*func): env ->  Prop :=\n  | env_ids_none_: forall eh1 se1,\n     ptree_ids_none (map fst (nd_rets (snd nd))) eh1 ->\n     subenv_ids env_ids_none se1 (if nd_kind (snd nd) then instidof (nd_stmt (snd nd)) else nil) ->\n     env_ids_none nd (mkenv eh1 se1).\n\nInductive env_ids_some(nd: ident*func): env ->  Prop :=\n  | env_ids_some_: forall eh2 se2,\n     ptree_vars_some (nd_rets (snd nd)) eh2 ->\n     subenv_ids env_ids_some se2 (if nd_kind (snd nd) then instidof (nd_stmt (snd nd)) else nil) ->\n     env_ids_some nd (mkenv eh2 se2).\n\nLemma encode_val_mvl_type:\n  forall ty chunk v,\n  access_mode ty = By_value chunk ->\n  mvl_alloc (encode_val chunk v) ty.\nProof.\n  intros. constructor; auto.\n  destruct ty; auto; inv H.\n  rewrite encode_val_length. unfold size_chunk_nat.\n  erewrite sizeof_chunk_eq;eauto.\n  generalize (sizeof_pos ty). intros.\n  rewrite nat_of_Z_eq; try omega.\nQed.\n\nLemma store_env_ptree_vars_some:\n  forall gc eh2 id ofs v eh2' rets te2 a,\n  store_env (typeof a) eh2 id ofs v eh2' ->\n  ptree_vars_some rets eh2 ->\n  has_type v (typeof a) ->\n  eval_lvalue gc te2 eh2 a id ofs Sid ->\n  ptree_vars_some rets eh2'.\nProof.\n  intros. inv H. red; intros.\n  apply H0 in H. destruct H as [m1 [? ?]].\n  compare id id0; intros; subst.   \n  +rewrite PTree.gss. rewrite H3 in H. inv H.\n   exists m'. split; auto.\n   generalize (sizeof_pos ty) (Int.unsigned_range ofs). intros A A1.\n   inv H5. \n   -unfold store in *. destruct (valid_access_dec _ _ _); inv H7.\n    apply mvl_alloc_setn with a; eauto.\n    *eapply eval_lvalue_eval_offset; eauto.\n    *eapply encode_val_mvl_type; eauto.\n    *rewrite encode_val_length. unfold size_chunk_nat.\n     destruct v0 as [[? [? ?]] ?].\n     rewrite <-Z2Nat.inj_add; try omega.\n     apply Nat2Z.inj_le. rewrite nat_of_Z_eq; try omega.\n   -unfold storebytes in *. destruct (range_perm_dec _ _ _); inv H7.\n    apply mvl_alloc_setn with a; auto.\n    *eapply eval_lvalue_eval_offset; eauto.\n    *eapply mvl_type_alloc; eauto.\n     eapply has_type_mvl_inv; eauto.\n    *destruct r as [? [? ?]].\n     apply Nat2Z.inj_le; try omega.\n     rewrite Nat2Z.inj_add. \n     rewrite nat_of_Z_eq; try omega.\n   +rewrite PTree.gso; eauto.\nQed.\n\nLemma alloc_variables_ptree_vars_some:\n  forall e al e',\n  alloc_variables e al e' -> \n  list_norepet (map fst al) ->\n  ptree_vars_some al e'.\nProof.\n  induction 1; simpl; intros; auto.\n  +red; intros. inv H0.\n  +inv H0. red; simpl; intros. destruct H0.\n   -inv H0. exists (alloc (sizeof ty0)).\n    split. erewrite alloc_variables_notin_eq; eauto.\n    rewrite PTree.gss; auto. \n    apply mvl_alloc_self; auto.\n   -eapply IHalloc_variables; eauto.\nQed.\n\nLemma mvl_match_is_byte_eq:\n  forall m1 m2 t chunk,\n  mvl_match m1 m2 t -> \n  access_mode t = By_value chunk ->\n  is_bytes m1 ->\n  m2 = m1.\nProof.\n  induction 1; simpl; intros; try congruence.\n  destruct m1,m2; simpl in *; try omega.\n  auto.\n  inv H0. inv H4. destruct m; simpl in *; tauto.\nQed.\n\nLemma mvl_match_load_mvl:\n  forall a m1 ofs v m2 t,\n  load_mvl (typeof a) m1 ofs v ->\n  eval_offset t a (Int.unsigned ofs) ->\n  mvl_match m1 m2 t ->\n  has_type v (typeof a) ->\n  load_mvl (typeof a) m2 ofs v.\nProof.\n  intros.\n  eapply eval_offset_mvl_match_sube in H0; eauto.\n  inv H.\n  +constructor 1 with chunk;auto.\n   unfold load in *.\n   destruct (valid_access_dec m1 chunk _); try congruence.\n   rewrite pred_dec_true; auto.\n   -rewrite <-H4. f_equal.\n    unfold size_chunk_nat in *. erewrite sizeof_chunk_eq in *; eauto.\n    eapply mvl_match_is_byte_eq; eauto.\n    unfold decode_val in *. destruct (proj_bytes _) eqn:?; try congruence.\n    eapply proj_bytes_is_bytes; eauto.\n   -eapply length_valid_access; eauto.\n    eapply mvl_match_length in H1; eauto.\n  +constructor 2; auto.\n   unfold loadbytes in *.\n   destruct (range_perm_dec m1 _ _); inv H4.\n   rewrite pred_dec_true.\n   -eapply has_type_mvl_inv in H2; eauto. destruct H2.\n    f_equal. eapply mvl_match_mvl_type_eq in H0; eauto.\n   -eapply length_range_perm; eauto.\n    apply mvl_match_length with (ty:=t); eauto.\nQed.\n\nLemma locenv_match_rets_in:\n  forall te1 eh2 ids id,\n  locenv_match_rets te1 eh2 ids ->\n  in_list id ids = true ->\n  locenv_match_ret te1 eh2 id.\nProof.\n  intros. apply H.\n  apply in_list_true_in; auto.\nQed.\n\nLemma locenv_match_ret_set_same:\n  forall id t m1 m2 te1 eh2, \n  mvl_match m1 m2 t ->\n  locenv_match_ret (PTree.set id (m1,t) te1) (PTree.set id (m2,t) eh2) id.\nProof.\n  unfold locenv_match_ret. intros.\n  repeat rewrite PTree.gss in *. exists m1,m2,t; eauto.\nQed.\n\nLemma locenv_match_rets_set_other_left:\n  forall te1 eh2 ids b m,\n  locenv_match_rets te1 eh2 ids ->\n  in_list b ids = false ->\n  locenv_match_rets (PTree.set b m te1) eh2 ids.\nProof.\n  intros. red; intros.\n  apply in_list_false_notin in H0.\n  red; intros. rewrite PTree.gso.\n  apply H; auto. congruence.\nQed.\n\nLemma locenv_match_rets_set_other_right:\n  forall te1 eh2 ids b m,\n  locenv_match_rets te1 eh2 ids ->\n  in_list b ids = false ->\n  locenv_match_rets te1 (PTree.set b m eh2) ids.\nProof.\n  intros. red; intros.\n  apply in_list_false_notin in H0.\n  red; intros. rewrite PTree.gso.\n  apply H; auto. congruence.\nQed.\n\nLemma store_env_locenv_match_ret:\n  forall gc a te1 id ofs v te1' te2 eh2,\n  store_env (typeof a) te1 id ofs v te1' ->\n  locenv_match_ret te1 eh2 id ->\n  has_type v (typeof a) ->\n  eval_lvalue gc te2 eh2 a id ofs Sid ->\n  exists eh2', store_env (typeof a) eh2 id ofs v eh2' \n    /\\ locenv_match_ret te1' eh2' id.\nProof.\n  intros. inv H.\n  destruct H0 as [m0 [m1 [? [? [? ?]]]]]; auto.\n  generalize H6; intros.\n  rewrite H in H3. inv H3.\n  apply mvl_match_length in H6.\n  generalize (Int.unsigned_range ofs) (sizeof_pos (typeof a)). intros A A1.\n  inv H5.\n  +destruct valid_access_store with m1 chunk (Int.unsigned ofs) v as [m1' ?]; auto.\n   apply length_valid_access with m; auto.\n   eapply store_valid_access_2;eauto.\n   eapply store_valid_access;eauto.\n   exists (PTree.set id (m1',t) eh2). split.\n   -constructor 1 with m1; auto. congruence.\n    constructor 1 with chunk; auto.\n   -apply locenv_match_ret_set_same; auto.\n    unfold store in *.\n    destruct (valid_access_dec m chunk _); inv H8.\n    destruct (valid_access_dec m1 chunk _); inv e.\n    apply mvl_match_setn with a; auto.\n    *eapply eval_lvalue_eval_offset; eauto.\n    *econstructor; eauto.\n     destruct (typeof a); auto; inv H3.\n     rewrite encode_val_length.\n     unfold size_chunk_nat. erewrite sizeof_chunk_eq; eauto.\n     rewrite nat_of_Z_eq; try omega.\n  +destruct range_perm_store_bytes with m1 (Int.unsigned ofs) m0 as [m1' ?];auto.\n   apply length_range_perm with m; auto.\n   eapply storebytes_range_perm_2;eauto.\n   eapply storebytes_range_perm;eauto.\n   exists (PTree.set id (m1',t) eh2). split.\n   -constructor 1 with m1; auto. congruence.\n    constructor 2; auto.\n   -apply locenv_match_ret_set_same; auto.\n    unfold storebytes in *.\n    destruct (range_perm_dec m _ _); inv H8.\n    destruct (range_perm_dec m1 _ _); inv e.\n    apply mvl_match_setn with a; auto.\n    *eapply eval_lvalue_eval_offset; eauto.\n    *eapply mvl_type_alloc; eauto.\n     apply has_type_mvl_inv; auto.\nQed.\n\nLemma loenv_match_rets_getvars:\n  forall te rets vrs,\n  Lsem.locenv_getvars te rets vrs ->\n  has_types vrs (map snd rets) ->\n  forall eh, locenv_match_rets te eh (map fst rets) ->\n  Lsem.locenv_getvars eh rets vrs.\nProof.\n  induction 1; simpl; intros.\n  +constructor.\n  +inv H1. constructor 2; auto.\n   -destruct H as [m1 [? [? ?]]].\n    destruct H2 with (id:=fst x) as [m0 [m2 [t0 [? [? ?]]]]]; simpl; auto.\n    rewrite H4 in H. inv H.\n    exists m2. repeat split; auto.\n    apply mvl_match_length in H7. congruence.\n    change (snd x) with (typeof (Svar (fst x) (snd x))); auto.\n    eapply mvl_match_load_mvl; eauto.\n    constructor 1; auto.\n   -apply IHForall2; auto.\n    red; intros. apply H2; simpl; auto.\nQed.\n\nLemma ptree_match_eval_lvalue:\n  forall gc te1 id m ty ids te2 eh2,\n  te1 ! id = Some (m, ty) ->\n  ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 eh2 ids ->\n  eval_lvalue gc te2 eh2 (trans_v ids id ty) id Int.zero (if in_list id ids then Sid else Lid).\nProof.\n  unfold trans_v. intros. remember (in_list id ids).\n  destruct b; symmetry in Heqb.\n  +apply in_list_true_in in Heqb.\n   apply H1 in Heqb.\n   destruct Heqb as [m0 [m1 [? [? [? ?]]]]]; auto.\n   rewrite H2 in H. inv H.\n   constructor 3 with m1; auto. \n  +constructor 1 with m; auto.\n   rewrite <-H0; auto. apply in_list_false_notin; auto.\nQed.\n\nLemma eval_sexp_match:\nforall gc te1 eh1,\n(\n  forall a v,\n  eval_sexp gc te1 eh1 a v ->\n  forall te2 eh2 ids, locenv_match eh1 eh2 ->\n  ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 eh2 ids ->\n  ptree_ids_none ids te2 ->\n  eval_sexp gc te2 eh2 (trans_sexp (trans_v ids) a) v\n)\n/\\\n(\n  forall a id o k,\n  eval_lvalue gc te1 eh1 a id o k ->\n  forall te2 eh2 ids, locenv_match eh1 eh2 ->\n  ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 eh2 ids ->\n  ptree_ids_none ids te2 ->\n  match k with\n  | Gid | Sid =>\n    eval_lvalue gc te2 eh2 (trans_sexp (trans_v ids) a) id o k\n  | Lid =>\n    eval_lvalue gc te2 eh2 (trans_sexp (trans_v ids) a) id o (if in_list id ids then Sid else k)\n  | Aid => False\n  end\n).\nProof.\n intros until eh1.\n apply eval_sexp_lvalue_ind; intros; simpl in *.\n +constructor; simpl; auto.\n +constructor 2 with v1; auto.\n  rewrite trans_sexp_typeof; auto.\n +constructor 3 with v1 v2; auto;\n  repeat rewrite trans_sexp_typeof; auto.\n +constructor 4 with v1; auto.\n  rewrite trans_sexp_typeof; auto.\n +generalize H3; intros A1. eapply H0 in A1; eauto.\n  assert(A: (k = Gid \\/ k = Sid) \\/ (k = Lid \\/ k = Aid)).\n     destruct k; auto.\n  destruct A as [A | A].\n  -apply eval_Rlvalue with id ofs k; auto; \n   destruct A; subst; simpl in *; auto;\n   rewrite trans_sexp_typeof; auto.\n   eapply load_env_match; eauto.\n  -destruct A; subst; simpl in *; try tauto.\n   destruct H1 as [m [t [? [? ?]]]].\n   apply eval_Rlvalue with id ofs (if in_list id ids then Sid else Lid); auto;\n   rewrite trans_sexp_typeof; auto.\n   destruct (in_list id ids) eqn:?.   \n   *eapply locenv_match_rets_in in Heqb; eauto.\n    destruct Heqb as [m0 [m2 [t0 [? [? ?]]]]]; auto.\n    rewrite H9 in H1. inv H1.\n    exists m2, t. repeat split; auto.\n    apply mvl_match_length in H11. congruence.\n    eapply mvl_match_load_mvl; eauto.\n    eapply eval_lvalue_eval_offset; eauto.\n   *exists m, t; repeat split; simpl; auto.\n    rewrite <-H4; auto. apply in_list_false_notin; auto.\n +apply ptree_match_eval_lvalue with te1 m; auto.\n +unfold trans_v. destruct (in_list id ids) eqn:?.\n  -apply in_list_true_in in Heqb.\n   destruct H3 with id as [m0 [m1 [? [? [? ?]]]]]; auto.\n   congruence.\n  -constructor 2 with m; auto.\n   eapply ptree_noids_match_ids_none; eauto.\n +constructor 3 with m; auto. \n +generalize H6; intros A. eapply H0 in A; eauto.\n  destruct k; try tauto; apply eval_Saryacc with aid z; auto;\n  rewrite trans_sexp_typeof; auto.\n +eapply H0 in H5; eauto.\n  destruct k; try tauto; apply eval_Sfield with sid fld; auto;\n  rewrite trans_sexp_typeof; auto.\nQed.\n\nLemma eval_sexps_match:\n  forall gc te1 eh1 al vl,\n  eval_sexps gc te1 eh1 al vl ->\n  forall te2 eh2 ids, locenv_match eh1 eh2 ->\n  ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 eh2 ids ->\n  ptree_ids_none ids te2 ->\n  eval_sexps gc te2 eh2 (trans_sexps (trans_v ids) al) vl.\nProof.\n  induction 1; simpl; intros.\n  +constructor.\n  +constructor 2; auto.\n   eapply eval_sexp_match; eauto.\n   eapply IHForall2; eauto.\nQed.\n\nLemma store_env_ptree_match_exists_right:\n  forall gc a te1 b ofs v te1',\n  store_env (typeof a) te1 b ofs v te1' ->\n  forall ids te2 eh2, in_list b ids = true -> \n  ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 eh2 ids ->\n  has_type v (typeof a) ->\n  eval_lvalue gc te2 eh2 a b ofs Sid ->\n  exists eh2', store_env (typeof a) eh2 b ofs v eh2' \n    /\\ locenv_match_rets te1' eh2' ids\n    /\\ ptree_noids_match ids te1' te2.\nProof.\n  intros. generalize H0; intros A.\n  apply in_list_true_in in A.\n  apply H2 in A.\n  eapply store_env_locenv_match_ret in A; eauto.\n  destruct A as [eh2' [A A1]].\n  exists eh2'. split; [| split]; auto.\n  +inv H. inv A. red; intros. apply H2 in H10.\n   compare b id; intros; subst; auto.\n   red; intros. repeat rewrite PTree.gso; auto.\n  +inv H. inv A. red. intros. rewrite PTree.gso; auto.\n   apply in_list_true_in in H0. red; intros; subst; auto.\nQed.\n\nLemma store_env_ptree_match_exists_left:\n  forall a te1 b ofs v te1' gc eh1,\n  store_env (typeof a) te1 b ofs v te1' ->\n  forall ids te2 eh2, in_list b ids = false -> \n  ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 eh2 ids ->\n  locenv_mvl_alloc te2 ->\n  has_type v (typeof a) ->\n  eval_lvalue gc te1 eh1 a b ofs Lid ->\n  exists te2', store_env (typeof a) te2 b ofs v te2' \n    /\\ locenv_match_rets te1' eh2 ids\n    /\\ ptree_noids_match ids te1' te2'\n    /\\ locenv_mvl_alloc te2'.\nProof.\n  intros. inv H.\n  exists (PTree.set b (m',t) te2). repeat (split; auto).\n  +constructor 1 with m; eauto.\n   rewrite <-H1; auto. apply in_list_false_notin; auto.\n  +apply locenv_match_rets_set_other_left; auto.\n  +apply ptree_noids_match_setsame; auto.\n  +red; intros. compare b id; intros; subst.\n   -rewrite PTree.gss in H. inv H.\n    generalize H6; intros A.\n    rewrite H1 in H6. eapply H3 in H6; eauto. \n    eapply eval_lvalue_eval_offset in H5; eauto.   \n    inv H8. \n    *unfold store in *. destruct (valid_access_dec _ _ _); inv H9.\n     apply mvl_alloc_setn with a; auto.\n     eapply encode_val_mvl_type; eauto.\n     rewrite encode_val_length. unfold size_chunk_nat.\n     destruct v0 as [[? [? ?]] ?].\n     rewrite <-Z2Nat.inj_add; try omega.\n     apply Nat2Z.inj_le. rewrite nat_of_Z_eq; try omega.\n    *unfold storebytes in *. destruct (range_perm_dec _ _ _); inv H9.\n     apply mvl_alloc_setn with a; auto.\n     eapply mvl_type_alloc; eauto.\n     eapply has_type_mvl_inv; eauto.\n     destruct r as [? [? ?]].\n     apply Nat2Z.inj_le; try omega.\n     rewrite Nat2Z.inj_add. \n     rewrite nat_of_Z_eq; try omega.\n    *apply in_list_false_notin; auto.\n   -rewrite PTree.gso in H; auto.\n    eapply H3; eauto.\nQed.\n\nLemma locenv_setvarf_exists:\n  forall gc te1 te1' eh1 eh1' a v,\n  locenv_setvarf gc te1 eh1 a v te1' eh1' ->\n  forall te2 eh2 ids, ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 eh2 ids ->\n  locenv_match eh1 eh2 ->\n  ptree_ids_none ids eh1 ->\n  ptree_ids_none ids te2 ->\n  has_type v (typeof a) ->\n  locenv_mvl_alloc te2 ->\n  exists te2' eh2', locenv_setvarf gc te2 eh2 (trans_sexp (trans_v ids) a) v te2' eh2'\n    /\\ ptree_noids_match ids te1' te2'\n    /\\ locenv_match_rets te1' eh2' ids\n    /\\ locenv_match eh1' eh2'\n    /\\ ptree_ids_none ids eh1'\n    /\\ ptree_ids_none ids te2'\n    /\\ locenv_mvl_alloc te2'.\nProof.\n  intros. inv H.\n  +generalize H7; intros A.\n   eapply eval_sexp_match in H7; eauto.\n   destruct (in_list id ids) eqn:?.\n   -exists te2.\n    rewrite <-trans_sexp_typeof with (ids:=ids) in H8.\n    eapply store_env_ptree_match_exists_right in H8; eauto.\n    destruct H8 as [eh2' [? [? ?]]].\n    exists eh2'. repeat (split; auto). \n    *constructor 2 with id ofs; auto.\n    *inv H. eapply locenv_match_addnewid; eauto.\n     apply H3. apply in_list_true_in; auto.\n    *rewrite trans_sexp_typeof; auto.\n   -eapply store_env_ptree_match_exists_left in H8; eauto.\n    destruct H8 as [te2' [? [? [? ?]]]].\n    exists te2', eh2. repeat (split; auto). \n    constructor 1 with id ofs; auto.\n    *rewrite trans_sexp_typeof; auto.\n    *inv H. eapply ptree_ids_none_set_other; eauto.\n  +exists te2.\n   destruct locenv_match_store_env_exists with (typeof a) eh1 id ofs v eh1' eh2\n    as [eh2' [? ?]]; auto.\n   exists eh2'. repeat (split; auto). \n   -constructor 2 with id ofs;auto.\n    eapply eval_sexp_match in H7; eauto.\n    rewrite trans_sexp_typeof; auto.\n   -inv H. inv H8.\n    eapply locenv_match_rets_set_other_right; eauto. \n    eapply ptree_ids_none_in_list_false with (eh1:=eh1); eauto.\n   -inv H8. eapply ptree_ids_none_set_other; eauto.\nQed.\n\nLemma lvalue_disjoint_match:\n  forall gc te1 e1 a1 a2,\n  lvalue_disjoint (eval_lvalue gc te1 e1) a1 a2 ->\n  forall te2 e2 ids, locenv_match e1 e2 ->\n  ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 e2 ids ->\n  ptree_ids_none ids te2 ->\n  lvalue_disjoint (eval_lvalue gc te2 e2) (trans_sexp (trans_v ids) a1) (trans_sexp (trans_v ids) a2).\nProof.\n  induction 1. intros.\n  eapply eval_sexp_match in H; eauto.\n  eapply eval_sexp_match in H0; eauto.\n  destruct H1, k2; subst; try tauto; destruct (in_list id1 ids);\n  econstructor 1; try repeat rewrite trans_sexp_typeof; eauto.\nQed.\n\nLemma assign_disjoint_match:\n  forall gc te1 e1 a1 a2,\n  assign_disjoint (eval_lvalue gc te1 e1) a1 a2 ->\n  forall te2 e2 ids, locenv_match e1 e2 ->\n  ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 e2 ids ->\n  ptree_ids_none ids te2 ->\n  assign_disjoint (eval_lvalue gc te2 e2) (trans_sexp (trans_v ids) a1) (trans_sexp (trans_v ids) a2).\nProof.\n  induction 1; intros.\n  +constructor 1 with chunk; auto.\n   rewrite trans_sexp_typeof; auto.\n  +constructor 2; auto.\n   rewrite trans_sexp_typeof; auto.\n   eapply lvalue_disjoint_match; eauto.\nQed.\n\nLemma eval_eqf_exists:\n  forall gc te1 eh1 te1' eh1' a,\n  eval_eqf gc te1 eh1 te1' eh1' a ->\n  forall te2 eh2 ids, ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 eh2 ids ->\n  locenv_match eh1 eh2 ->\n  ptree_ids_none ids eh1 ->\n  ptree_ids_none ids te2 ->\n  locenv_mvl_alloc te2 ->\n  exists te2' eh2', eval_eqf gc te2 eh2 te2' eh2' (trans_eqf (trans_v ids) a) \n    /\\ ptree_noids_match ids te1' te2'\n    /\\ locenv_match_rets te1' eh2' ids\n    /\\ locenv_match eh1' eh2'\n    /\\ ptree_ids_none ids eh1'\n    /\\ ptree_ids_none ids te2'\n    /\\ locenv_mvl_alloc te2'.\nProof.\n  intros. inv H. unfold trans_eqf. simpl.\n  eapply locenv_setvarf_exists in H10; eauto.\n  destruct H10 as [te2' [eh2' [? [? [? [? [? ?]]]]]]].\n  exists te2', eh2'. repeat (split; auto). \n  constructor 1 with v v'; auto.\n  +eapply eval_sexp_match; eauto.\n  +repeat rewrite trans_sexp_typeof; auto.\n  +eapply assign_disjoint_match; eauto.\n  +rewrite trans_sexp_typeof; auto.\n  +eapply eval_cast_has_type; eauto.\n   rewrite H7. eapply eval_sexp_has_type; eauto.\nQed.  \n\nLemma locenv_setvarfs_exists:\n  forall gc te1 te1' eh1 eh1' al vl,\n  LsemF.locenv_setvarfs gc te1 eh1 al vl te1' eh1' ->\n  forall te2 eh2 ids, ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 eh2 ids ->\n  locenv_match eh1 eh2 ->\n  ptree_ids_none ids eh1 ->\n  ptree_ids_none ids te2 ->\n  has_types vl (map typeof al) ->\n  locenv_mvl_alloc te2 ->\n  exists te2' eh2', LsemF.locenv_setvarfs gc te2 eh2 (trans_sexps (trans_v ids) al) vl te2' eh2'\n    /\\ ptree_noids_match ids te1' te2'\n    /\\ locenv_match_rets te1' eh2' ids\n    /\\ locenv_match eh1' eh2'\n    /\\ ptree_ids_none ids eh1'\n    /\\ ptree_ids_none ids te2' \n    /\\ locenv_mvl_alloc te2'.\nProof.\n  induction 1; simpl; intros.\n  +exists te2, eh2. repeat (split; auto).\n   constructor.\n  +inv H6.\n   eapply locenv_setvarf_exists in H; eauto.\n   destruct H as [te21 [eh21 [? [? [? [? [? [? ?]]]]]]]].\n   destruct IHlocenv_setvarfs with te21 eh21 ids as [te2' [eh2' [? [? [? [? [? [? ?]]]]]]]]; auto.\n   exists te2', eh2'. repeat (split; auto).\n   constructor 2 with te21 eh21; auto.\nQed.\n\nLemma env_ids_none_callnd_inst_env_match:\n  forall nd fd le1 se1 c i ef1,\n  env_ids_none nd (mkenv le1 se1) ->\n  callnd_inst_env c i se1 ef1 ->\n  In c (instidof (nd_stmt (snd nd))) ->\n  nd_kind (snd nd) = true ->\n  find_funct (node_block prog1) (callid c) = Some fd ->\n  env_ids_none fd ef1.\nProof.\n  intros. inv H.\n  inv H0. destruct H7 with c as [fd1 [el1 [? [? ?]]]]; auto.\n  rewrite H2; auto.\n  rewrite H0 in H3. inv H3.\n  rewrite H8 in H. inv H.\n  eapply Forall_forall; eauto.\n  eapply nth_error_in; eauto.\nQed.\n\nLemma env_ids_some_callnd_inst_env_match:\n  forall nd fd le1 se1 c i ef1,\n  env_ids_some nd (mkenv le1 se1) ->\n  callnd_inst_env c i se1 ef1 ->\n  In c (instidof (nd_stmt (snd nd))) ->\n  nd_kind (snd nd) = true ->\n  find_funct (node_block prog1) (callid c) = Some fd ->\n  env_ids_some fd ef1.\nProof.\n  intros. inv H. inv H0.\n  destruct H7 with c as [fd1 [el1 [? [? ?]]]]; auto.\n  rewrite H2; auto.\n  rewrite H0 in H3. inv H3.\n  rewrite H8 in H. inv H.\n  eapply Forall_forall; eauto.\n  eapply nth_error_in; eauto. \nQed.\n\nLemma env_ids_none_update:\n  forall cdef i se se' ef ef' eh eh' nd fd,\n  callnd_env cdef i se se' ef ef' ->\n  env_ids_none nd (mkenv eh se) ->\n  find_funct (node_block prog1) (callid cdef) = Some fd ->\n  env_ids_none fd ef' ->\n  ptree_ids_none (map fst (nd_rets (snd nd))) eh' ->\n  list_norepet (map instid (instidof (nd_stmt (snd nd)))) ->\n  In cdef (instidof (nd_stmt (snd nd))) ->\n  nd_kind (snd nd) = true ->\n  env_ids_none nd (mkenv eh' se').\nProof.\n  intros. inv H. inv H0. constructor; auto.\n  red; intros. rewrite H6 in *.\n  compare (instid c) (instid cdef); intros.\n  +eapply map_nodup_find_eq in e; eauto.\n   subst. destruct H12 with cdef as [fd1 [el1 [? [? ?]]]]; auto.\n   rewrite H0 in H1. inv H1. rewrite H9 in H7. inv H7.\n   exists fd. rewrite PTree.gss.  \n   exists (replace_nth efs (nat_of_int i) ef'). repeat (split; auto).\n   eapply Forall_replace; eauto.\n   eapply list_norepet_nodup; eauto.\n  +destruct H12 with c as [fd1 [el1 [? [? ?]]]]; auto.\n   exists fd1. rewrite PTree.gso; auto.  \n   exists el1. repeat (split; auto).\nQed.  \n\nLemma env_ids_some_update:\n  forall cdef i se se' ef ef' eh eh' nd fd,\n  callnd_env cdef i se se' ef ef' ->\n  env_ids_some nd (mkenv eh se) ->\n  find_funct (node_block prog1) (callid cdef) = Some fd ->\n  env_ids_some fd ef' ->\n  ptree_vars_some (nd_rets (snd nd)) eh' ->\n  list_norepet (map instid (instidof (nd_stmt (snd nd)))) ->\n  In cdef (instidof (nd_stmt (snd nd))) ->\n  nd_kind (snd nd) = true ->\n  env_ids_some nd (mkenv eh' se').\nProof.\n  intros. inv H. inv H0; try congruence. constructor; auto.\n  red; intros. rewrite H6 in *.\n  compare (instid c) (instid cdef); intros.\n  +eapply map_nodup_find_eq in e; eauto.\n   subst. destruct H12 with cdef as [fd1 [el1 [? [? ?]]]]; auto.\n   rewrite H0 in H1. inv H1. rewrite H9 in H7. inv H7.\n   exists fd. rewrite PTree.gss.  \n   exists (replace_nth efs (nat_of_int i) ef'). repeat (split; auto).\n   eapply Forall_replace; eauto.\n   eapply list_norepet_nodup; eauto.\n  +destruct H12 with c as [fd1 [el1 [? [? ?]]]]; auto.\n   exists fd1. rewrite PTree.gso; auto.  \n   exists el1. repeat (split; auto).\nQed.  \n\nLemma locenv_match_setvars_exists:\n  forall te1 al vas te1',\n  locenv_setvars te1 al vas te1' ->\n  forall ids te2 eh2, ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 eh2 ids ->\n  list_disjoint (map fst al) ids -> \n  locenv_mvl_alloc te2 ->\n  has_types vas (map snd al) ->\n  exists te2', locenv_setvars te2 al vas te2'\n     /\\ ptree_noids_match ids te1' te2'\n     /\\ locenv_match_rets te1' eh2 ids\n     /\\ locenv_mvl_alloc te2'.\nProof.\n  induction 1; simpl; intros.\n  +exists te2. repeat (split; auto).\n   constructor.\n  +apply list_disjoint_appa_left in H4. destruct H4.\n   apply in_list_false_notin in H4. inv H6.\n   eapply store_env_ptree_match_exists_left with (gc:= empty_locenv) (eh1:=empty_locenv) (a:=Svar id ty) in H0; eauto.\n   destruct H0 as [te21 [? [? [? ?]]]].\n   destruct IHlocenv_setvars with ids te21 eh2 as [te2' [? [? [? ?]]]]; auto.\n   exists te2'. repeat (split; auto).\n   constructor 2 with te21 m; auto.\n   rewrite <- H2; auto. apply in_list_false_notin; auto.\n   constructor 1 with m; auto.\nQed.\n\nLemma alloc_variables_ptree_match:\n  forall l1 l2 te1' te2' eh2, \n  alloc_variables empty_locenv (l1++l2) te1' ->\n  alloc_variables empty_locenv l1 te2' ->\n  list_disjoint (map fst l1) (map fst l2) ->\n  list_norepet (map fst l2) ->\n  ptree_vars_some l2 eh2 -> \n  ptree_noids_match (map fst l2) te1' te2' \n    /\\ locenv_match_rets te1' eh2 (map fst l2).\nProof.\n  intros. apply alloc_variables_app in H. \n  destruct H as [te1 [? ?]].\n  eapply alloc_variables_determ in H; eauto.\n  subst. split; red; intros.\n  +eapply alloc_variables_notin_eq; eauto.\n  +generalize H; intros.\n   apply in_map_iff in H. destruct H as [? [? ?]].\n   subst. destruct x. simpl in *.\n   eapply alloc_variables_norepeat_in_eq in H4; eauto.\n   apply H3 in H6. destruct H6 as [m [? ?]].\n   red. intros. exists (alloc (sizeof t)), m, t.\n   repeat split; auto.\n   eapply mvl_match_alloc; eauto.\nQed.\n\nLemma alloc_variables_locenv_mvl_alloc:\n  forall te l te', \n  alloc_variables te l te' ->\n  locenv_mvl_alloc te ->\n  locenv_mvl_alloc te'.\nProof.\n  induction 1; intros; auto.\n  apply IHalloc_variables. red; intros.\n  compare id id0; intros; subst.\n  rewrite PTree.gss in H1. inv H1.\n  apply mvl_alloc_self.\n  rewrite PTree.gso in H1; auto. apply H0 in H1; auto.\nQed.\n\nLemma locenv_setvarf_ptree_vars_some:\n  forall gc te2 eh2 a v te2' eh2' rets,\n  locenv_setvarf gc te2 eh2 a v te2' eh2' ->\n  ptree_vars_some rets eh2 ->\n  has_type v (typeof a) ->\n  ptree_vars_some rets eh2'.\nProof.\n  intros. inv H; auto.\n  eapply store_env_ptree_vars_some; eauto.\nQed.\n\nLemma locenv_setvarfs_ptree_vars_some:\n  forall gc te2 eh2 al vl te2' eh2',\n  LsemF.locenv_setvarfs gc te2 eh2 al vl te2' eh2' ->\n  forall rets, ptree_vars_some rets eh2 ->\n  has_types vl (map typeof al) ->\n  ptree_vars_some rets eh2'.\nProof.\n  induction 1; simpl; intros; auto.\n  inv H2. apply IHlocenv_setvarfs; auto.\n  eapply locenv_setvarf_ptree_vars_some; eauto.\nQed.\n\nLemma eval_eqf_ptree_vars_some:\n  forall gc vars te2 te2' eh2 eh2' a,\n  ptree_vars_some vars eh2 ->\n  eval_eqf gc te2 eh2 te2' eh2' a ->\n  ptree_vars_some vars eh2'.\nProof.\n  intros. inv H0.\n  eapply locenv_setvarf_ptree_vars_some; eauto.\n  eapply eval_cast_has_type; eauto.\n  rewrite H2. eapply eval_sexp_has_type; eauto.\nQed. \n\nLemma length_eq_loadbytes_exists:\n  forall m1 m2 o size v1,\n  length m1 = length m2 ->\n  loadbytes m1 o size = Some v1 ->\n  exists v2, loadbytes m2 o size = Some v2.\nProof.\n  intros. \n  apply loadbytes_range_perm in H0.\n  econstructor. unfold loadbytes.\n  rewrite pred_dec_true; auto.\n  eapply length_range_perm; eauto.\nQed.\n\nLemma locenv_getmvl_match:\n  forall gc te1 lh v1,\n  Lsem.locenv_getmvl gc te1 lh v1 ->\n  forall te2 e1 e2 ids, locenv_match e1 e2 ->\n  ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 e2 ids ->\n  ptree_ids_none ids te2 ->\n  locenv_mvl_alloc te2 ->\n  exists v2, locenv_getmvl gc te2 e2 (trans_sexp (trans_v ids) lh) v2\n    /\\ mvl_alloc v2 (typeof lh).\nProof.\n  intros. inv H.\n  generalize H5; intros A.\n  apply eval_lvalue_lvalue with (eh:=e1) in A.\n  eapply eval_sexp_match in A; eauto. \n  destruct (in_list id ids) eqn:?.\n  +destruct H2 with id as [? [? [? [? [? ?]]]]]; auto.\n   apply in_list_true_in; auto.\n   rewrite H in H6. inv H6.\n   apply length_eq_loadbytes_exists with (m2:=x0) in H7.\n   destruct H7 as [v2 ?].\n   exists v2. split. constructor 1 with id ofs Sid x0 t; auto.\n   -rewrite trans_sexp_typeof; auto.\n   -erewrite loadbytes_contents with (bytes:=v2); eauto.\n    apply eval_offset_mvl_alloc_sube with (t:=t); auto.\n    eapply Lsem.eval_lvalue_eval_offset in H5; eauto.\n    eapply mvl_match_mvl_alloc; eauto.\n   -eapply mvl_match_length in H9; eauto.\n  +exists v1. split; auto. constructor 1 with id ofs Lid m t; auto.\n   -rewrite <-H1; auto.\n    apply in_list_false_notin; auto.\n   -rewrite trans_sexp_typeof; auto.\n   -generalize H6; intros A1. rewrite H1 in H6. apply H4 in H6.\n    erewrite loadbytes_contents with (bytes:=v1); eauto.\n    eapply eval_offset_mvl_alloc_sube; eauto.\n    eapply Lsem.eval_lvalue_eval_offset in H5; eauto.\n    apply in_list_false_notin; auto.\nQed.\n\nLemma locenv_getmvls_match:\n  forall gc te1 lhs vl1,\n  Lsem.locenv_getmvls gc te1 lhs vl1 ->\n  forall te2 e1 e2 ids, locenv_match e1 e2 ->\n  ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 e2 ids ->\n  ptree_ids_none ids te2 ->\n  locenv_mvl_alloc te2 ->\n  exists vl2, locenv_getmvls gc te2 e2 (trans_sexps (trans_v ids) lhs) vl2\n    /\\ Forall2 mvl_alloc vl2 (map typeof lhs).\nProof.\n  induction 1; intros.\n  +exists nil. split; constructor.\n  +simpl. eapply locenv_getmvl_match in H; eauto.\n   destruct H as [v2 [? ?]].\n   destruct IHForall2 with te2 e1 e2 ids as [vl2 [? ?]]; auto.\n   exists (v2::vl2). split; constructor 2; auto.\nQed.\n\nLemma locenv_setmvls_ptree_vars_some:\n  forall e al vl e',\n  locenv_setmvls e al vl e' -> \n  list_norepet (map fst al) ->\n  Forall2 mvl_alloc vl (map snd al) ->\n  ptree_vars_some al e'.\nProof.\n  induction 1; simpl; intros; auto.\n  +red; simpl; intros. tauto.\n  +inv H1. inv H2. red; simpl; intros. destruct H1.\n   -inv H. inv H8. exists mv.\n    split; auto. erewrite locenv_setmvls_notin_eq; eauto.\n    rewrite PTree.gss; auto.\n   -eapply IHlocenv_setmvls; eauto.\nQed.\n\nLemma lvalue_list_norepet_match:\n  forall gc te1 e1 l,\n  lvalue_list_norepet (eval_lvalue gc te1 e1) l ->\n  forall te2 e2 ids, locenv_match e1 e2 ->\n  ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 e2 ids ->\n  ptree_ids_none ids te2 ->\n  lvalue_list_norepet (eval_lvalue gc te2 e2) (trans_sexps (trans_v ids) l).\nProof.\n  induction 1; simpl; intros.\n  +constructor. \n  +constructor 2; eauto.\n   unfold trans_sexps. red; intros.\n   apply in_map_iff in H5. destruct H5 as [? [? ?]].\n   subst. apply in_split in H6. destruct H6 as [? [? ?]].\n   subst. eapply lvalue_disjoint_match; eauto.\n   apply H; apply in_or_app; simpl; auto.\nQed.\n\nLemma assign_list_disjoint_match:\n  forall gc te1 e1 l al, \n  assign_list_disjoint (eval_lvalue gc te1 e1) l al ->\n  forall te2 e2 ids, locenv_match e1 e2 ->\n  ptree_noids_match ids te1 te2 ->\n  locenv_match_rets te1 e2 ids ->\n  ptree_ids_none ids te2 ->\n  assign_list_disjoint (eval_lvalue gc te2 e2) (trans_sexps (trans_v ids) l) (trans_sexps (trans_v ids) al).\nProof.\n  intros.\n  unfold trans_sexps. red; intros.\n  apply in_map_iff in H4. destruct H4 as [? [? ?]].\n  apply in_map_iff in H5. destruct H5 as [? [? ?]].\n  subst. apply in_split in H6. destruct H6 as [? [? ?]].\n  apply in_split in H7. destruct H7 as [? [? ?]].\n  subst. eapply assign_disjoint_match; eauto.\n  apply H; apply in_or_app; simpl; auto.\nQed.\n\nLemma trans_call_node:\n  forall nid cdef nd fd,\n  call_node (node_block prog1) nid cdef nd fd ->\n  call_node (node_block prog2) nid cdef (trans_node nd) (trans_node fd).\nProof.\n  unfold call_node, call_func. intros.\n  subst; intuition.\n  eapply trans_funcs_find with _ func _ trans_node _ _   in H0; eauto.\n  eapply trans_funcs_find with _ func _ trans_node _ _   in H2; eauto.\nQed.\n\nLemma trans_call_func:\n  forall cdef fd,\n  call_func (node_block prog1) cdef fd ->\n  call_func (node_block prog2) cdef (trans_node fd).\nProof.\n  unfold call_func. intros.\n  subst; intuition.\n  eapply trans_funcs_find with _ func _ trans_node _ _   in H0; eauto.\nQed.\n\nLemma trans_node_all_correct:\n  forall gc eL eL' fd vargs vrets,\n  LsemF.eval_node true prog1 gc eL eL' fd vargs vrets ->\n  find_funct (node_block prog1) (fst fd) = Some fd ->\n  forall eR,  \n  env_match eL eR ->\n  env_ids_none fd eL ->\n  env_ids_some fd eR ->\n  has_types vargs (map snd (nd_args (snd fd))) ->\n  exists eR', eval_node prog2 gc eR eR' (trans_node fd) vargs vrets\n     /\\ env_match eL' eR'\n     /\\ env_ids_none fd eL'\n     /\\ env_ids_some fd eR'.\nProof.\n  intros gc.\n  induction 1 using LsemF.eval_node_ind2 with \n  ( P0 := fun nid teL eL teL' eL' s =>\n      forall nd eR teR, \n      find_funct (node_block prog1) nid = Some nd ->\n      env_match eL eR ->\n      env_ids_none nd eL ->\n      ptree_noids_match (map fst (nd_rets (snd nd))) teL teR ->\n      locenv_match_rets teL (le eR) (map fst (nd_rets (snd nd))) ->\n      incl (instidof s) (instidof (nd_stmt (snd nd))) ->\n      list_norepet (map instid (instidof (nd_stmt (snd nd)))) ->\n      env_ids_some nd eR ->\n      ptree_ids_none (map fst (nd_rets (snd nd))) teR ->\n      ~ In ACG_I (map fst (nd_rets (snd nd))) ->\n      locenv_mvl_alloc teR ->\n      exists eR' teR',\n         eval_stmt prog2 gc nid teR eR teR' eR'\n            (trans_stmt (trans_v (map fst (nd_rets (snd nd)))) s)\n      /\\ env_ids_none nd eL'\n      /\\ env_match eL' eR'\n      /\\ ptree_noids_match (map fst (nd_rets (snd nd))) teL' teR'\n      /\\ locenv_match_rets teL' (le eR') (map fst (nd_rets (snd nd)))\n      /\\ env_ids_some nd eR'\n      /\\ ptree_ids_none (map fst (nd_rets (snd nd))) teR'\n      /\\ locenv_mvl_alloc teR'\n   ); simpl; intros.\n +(*eval_node*)\n  destruct alloc_variables_exists with (lvarsof f) empty_locenv as [teR A].\n  assert (B: ptree_noids_match (map fst (nd_rets f)) te teR\n             /\\ locenv_match_rets te (le eR) (map fst (nd_rets f))).\n    unfold allvarsof, lvarsof in *.\n    eapply alloc_variables_ptree_match; eauto. \n    apply ids_norepet_vars_args_rets_disjoint; auto.\n    apply ids_norepet_rets_norepet; auto.\n    inv H10; auto.\n  destruct B as [B B1].\n  destruct locenv_match_setvars_exists with te (nd_args f) vas te1 (map fst (nd_rets f)) teR (le eR)\n    as [teR1 [A1 [? [? ?]]]]; auto.\n    apply ids_norepet_args_rets_disjoint; auto.\n    eapply alloc_variables_locenv_mvl_alloc; eauto.\n     red; intros. rewrite PTree.gempty in *. congruence.\n  destruct IHeval_node with (nid,f) eR teR1 as [eR' [teR' [A2 [A3 [A4 [A5 [A6 [A7 A8]]]]]]]]; simpl; auto.\n    red; intros; auto.\n    apply ids_norepet_instid; auto.\n    eapply locenv_setvars_ptree_ids_none; eauto.\n    eapply alloc_variables_ptree_ids_none; eauto.\n    apply list_disjoint_sym.\n    apply ids_norepet_vars_args_rets_disjoint; auto.\n    eapply ids_norepet_loopid_notin_rets; eauto.\n  exists eR'. split;[| split]; auto.\n  destruct eR, eR'. econstructor; eauto.\n  apply trans_body_ids_norepet; auto.\n  eapply loenv_match_rets_getvars; eauto.\n +(*eval_Sassign*)\n  eapply eval_eqf_exists in H; eauto.\n  destruct H as [teR' [ehR' [? [? [? [? [? [? ?]]]]]]]]; auto.\n  inv H1.\n  exists (mkenv ehR' se2), teR'. split; [| split; [| split; [| split; [| split; [| split; [| split]]]]]]; auto. \n  -apply eval_Sassign; auto.\n  -inv H2. constructor; auto.\n  -constructor; auto. \n  -inv H7. constructor; auto.\n   eapply eval_eqf_ptree_vars_some; eauto.\n  -inv H1; auto.\n  -inv H2; auto.\n +(*eval_Scall*)\n  simpl in *.\n  inversion H1.\n  -(*node*)\n   subst se1 se2 e1 e2. rewrite H24 in *.\n   assert(nd0 = nd).\n    destruct H0 as [A1 [? [? ?]]].\n    unfold func in *; try rewrite H13 in A1; inv A1; auto.\n   subst nd0. \n   generalize H25 H0 H25; intros A A1 A5.\n   apply callnd_inst_env_eq in A. \n   eapply trans_call_node in H0; eauto.\n   destruct A1 as [A1 [A2 [[A3 [A7 [A8 A9]]] [A4 A6]]]].\n   assert(A10: In cdef (instidof (nd_stmt (snd nd)))).\n     eapply cons_inst_incl; eauto.\n   destruct eR as [ehR seR].\n   assert (B: exists ef2, callnd_inst_env cdef i seR ef2). \n     eapply env_match_callnd_inst_env_exists; eauto.\n   destruct B as [ef2 B].\n   assert (B1: env_match ef ef2).\n     eapply env_match_callnd_inst_env_match; eauto.\n   assert (B2: env_ids_none fd ef).\n     eapply env_ids_none_callnd_inst_env_match with (nd:=nd); eauto.\n   assert (B3: env_ids_some fd ef2).\n     eapply env_ids_some_callnd_inst_env_match; eauto.\n   destruct ef as [ehf sef]. destruct ef' as [ehf' sef'].\n   destruct IHeval_node with ef2 as [efR' [? [? [? ?]]]]; auto.\n     eapply find_funct_eq;eauto. \n     rewrite <-H8.\n     eapply eval_casts_has_types; eauto.\n     eapply eval_sexps_has_types; eauto.\n   eapply callnd_env_exists_se in H27; eauto.\n   destruct H27 as [seR' [? ?]].\n   cut(locenv_match eh ehR); intros C.     \n   eapply locenv_setvarfs_exists in H5; eauto.\n   destruct H5 as [teR' [ehR' [? [? [? [? [? [? ?]]]]]]]].\n   exists (mkenv ehR' seR'), teR'. split; [| split; [| split; [| split; [| split; [| split; [| split]]]]]]; auto. \n   *eapply eval_Scall with _ _ (trans_node fd) (trans_node nd) vargs vargs' vrets i; eauto.\n    inv H; simpl. constructor 1; auto.\n     eapply eval_sexp_ptree_ids_match; eauto.\n      red; simpl; intros ? C1. destruct C1; try tauto; subst; auto.\n     constructor 2.\n    eapply eval_sexps_match; eauto.\n    rewrite trans_sexps_typeof; auto.\n    eapply trans_sexps_lid_disjoint; eauto.\n    rewrite trans_sexps_typeof; auto.\n    rewrite trans_sexps_typeof; auto.\n    eapply lvalue_list_norepet_match; eauto.\n    eapply assign_list_disjoint_match; eauto.\n    assert(D: In (callid cdef) (map fst (nd_rets (snd nd))) \\/ ~ In (callid cdef) (map fst (nd_rets (snd nd)))) by tauto.\n     destruct D. apply H21; simpl; auto. rewrite <-H16; auto.\n   *eapply env_ids_none_update; eauto.\n   *inv H30; constructor; auto.\n   *eapply env_ids_some_update; eauto.\n    eapply locenv_setvarfs_ptree_vars_some; eauto.\n    inv H20; auto.\n    rewrite trans_sexps_typeof. rewrite H7. inv H4; auto.\n   *inv H15; auto.\n   *rewrite H7. inv H4; auto.\n   *inv H30; auto.\n  -(*func*)\n   subst se0 se ef ef'. generalize H0; intros A.\n   rewrite H24 in *. eapply trans_call_func in H0; eauto.\n   destruct A as [A1 [A2 [A3 [A4 [A5 A6]]]]].\n   cut (locenv_match eh (le eR)). intros C.\n   eapply locenv_getmvls_match in H9; eauto.\n   destruct H9 as [vl2 [A C2]].\n   generalize H5; intros C1.\n   eapply locenv_setvarfs_exists in H5; eauto.\n   destruct H5 as [teR' [ehR' [? [? [? [? [? [? ?]]]]]]]]. \n   assert (A9: exists efR, locenv_setmvls empty_locenv (nd_rets (snd fd)) vl2 efR).\n    eapply locenv_getmvls_set_mvls_exists; eauto.\n    rewrite trans_sexps_typeof; auto.\n   destruct A9 as [efR A9]. destruct eR as [ehR seR].\n   cut (nd_kind (snd fd) = false); intros.\n   destruct IHeval_node with (mkenv efR empty_subenv) as [efR' [? [? [? ?]]]]; auto.\n     eapply find_funct_eq;eauto.\n     constructor; auto; red; intros. rewrite PTree.gempty in *. congruence.\n       split; intros; auto. rewrite PTree.gempty in *. congruence.\n     constructor 1; auto; red; intros. rewrite PTree.gempty; auto.\n       rewrite H30 in *. tauto.\n     constructor 1; auto. eapply locenv_setmvls_ptree_vars_some; eauto.\n       apply ids_norepet_rets_norepet; auto. inv H4; auto.\n       congruence. red. rewrite H30. intros. tauto.\n     rewrite <-H8. eapply eval_casts_has_types; eauto.\n      eapply eval_sexps_has_types; eauto.\n   exists (mkenv ehR' seR), teR'. split; [| split; [| split; [| split; [| split; [| split; [| split]]]]]]; auto.  \n   *apply eval_Fcall with efR efR' vl2 (trans_node fd) vargs vargs' vrets; auto. \n    destruct H0 as [? [? [? ?]]]. auto.\n    eapply eval_sexps_match; eauto.\n    rewrite trans_sexps_typeof; auto.\n    eapply trans_sexps_lid_disjoint; eauto. \n    rewrite trans_sexps_typeof; auto.\n    rewrite trans_sexps_typeof; auto.\n    eapply lvalue_list_norepet_match; eauto.\n    eapply assign_list_disjoint_match; eauto.\n    assert(D: In (callid cdef) (map fst (nd_rets (snd nd0))) \\/ ~ In (callid cdef) (map fst (nd_rets (snd nd0)))) by tauto.\n     destruct D. apply H21; simpl; auto. rewrite <-H16; auto.\n   *inv H15; constructor 1; auto. \n   *inv H14; constructor; auto.\n   *inv H20; constructor 1; auto;\n    eapply locenv_setvarfs_ptree_vars_some; eauto;\n    rewrite trans_sexps_typeof; rewrite H7; inv H4; auto.\n   *unfold func in *. congruence.\n   *inv H15; auto.\n   *rewrite H7. inv H4; auto.\n   *inv H14; auto. \n +(*eval_Sfor_start*)\n  eapply eval_eqf_exists in H; eauto.\n  destruct H as [teR1 [ehR1 [A [A1 [A2 [A3 [? [? ?]]]]]]]].\n  destruct eR as [ehR seR].\n  destruct IHeval_node with nd (mkenv ehR1 seR) teR1 as [eR' [teR' [A4 [A5 [A6 [A7 [A8 [? ?]]]]]]]]; auto.\n    inv H2; constructor; auto.\n    inv H3. constructor; auto.\n    inv H8. constructor; auto.\n    eapply eval_eqf_ptree_vars_some; eauto.\n  exists eR', teR'. split; [| split; [| split]]; auto.\n  apply eval_Sfor_start with teR1 ehR1; auto.\n  inv H2; auto.\n  inv H3; auto.\n +(*eval_Sfor_false*)\n  exists eR, teR. repeat (split; auto). \n  destruct eR as [ehR seR].\n  apply eval_Sfor_false; auto.\n  eapply eval_sexp_match; eauto.\n  inv H1; auto.\n +(*eval_Sfor_loop*)\n  destruct IHeval_node with nd eR teR\n    as [eR1 [teR1 [? [? [? [? [? [? [? ?]]]]]]]]]; auto.\n  destruct eR1 as [ehR1 seR1].\n  eapply eval_eqf_exists with (eh1:=eh1) (eh2:=ehR1) in H1; eauto.\n  destruct H1 as [teR2 [ehR2 [? [? [? [? [? [? ?]]]]]]]].\n  destruct IHeval_node0 with nd (mkenv ehR2 seR1) teR2\n    as [eR' [teR' [? [? [? [? [? [? [? ?]]]]]]]]]; auto.\n    inv H16; constructor; auto.\n    inv H15. constructor; auto.\n    inv H19. constructor; auto.\n    eapply eval_eqf_ptree_vars_some; eauto.\n  exists eR', teR'. repeat (split; auto).\n  destruct eR as [ehR seR]. \n  eapply eval_Sfor_loop; eauto.\n  eapply eval_sexp_match; eauto.\n  inv H4; auto.\n  inv H16;auto.\n  inv H15; auto.\n +(*eval_Sskip*)\n  exists eR, teR. repeat (split; auto).\n  constructor.\n +(*eval_Sseq *)\n  destruct IHeval_node with nd eR teR as [eR1 [teR1 [? [? [? [? [? [? [? ?]]]]]]]]]; simpl; auto.\n    eapply incl_app_inv_l; eauto.\n  destruct IHeval_node0 with nd eR1 teR1 as [eR' [teR' [? [? [? [? [? [? [? ?]]]]]]]]]; simpl; auto.\n    eapply incl_app_inv_r; eauto.\n  exists eR', teR'. repeat (split; auto). \n  apply eval_Sseq with teR1 eR1; auto.   \n +(*eval_Sif*)\n  destruct IHeval_node with nd eR teR as [eR1 [teR1 [? [? [? [? [? [? ?]]]]]]]]; simpl; auto.\n    destruct b; [eapply incl_app_inv_l | eapply incl_app_inv_r]; eauto.\n  exists eR1, teR1. split; [| split]; auto.\n  destruct eR as [ehR seR]. \n  apply eval_Sif with v b; auto.\n  -eapply eval_sexp_match; eauto.\n   inv H3; auto.\n  -rewrite trans_sexp_typeof; auto.\n  -destruct b; auto.\n +(*eval_Scase*)\n  inv H1. destruct eR as [ehR seR].\n  eapply eval_eqf_exists in H18; eauto.\n  destruct H18 as [teR' [ehR' [? [? [? [? [? [? ?]]]]]]]]; auto.\n  exists (mkenv ehR' seR), teR'. split; [| split; [| split; [| split; [| split; [| split; [| split]]]]]]; auto.   \n  -apply eval_Scase with i (trans_sexp (trans_v (map fst (nd_rets (snd nd))))  a); eauto.\n   *eapply eval_sexp_match; eauto.\n    inv H3; auto.\n   *eapply trans_select_case; eauto.  \n   *apply eval_Sassign; auto.\n  -inv H3; constructor; auto.\n  -inv H9. constructor; auto.\n   eapply eval_eqf_ptree_vars_some; eauto.\n  -inv H3; auto.\n  -inv H4; auto.\nQed.\n\nLemma alloc_variables_locenv_match:\n  forall e1 l e1',\n  alloc_variables e1 l e1' ->\n  forall e2 e2', locenv_match e1 e2 ->\n  alloc_variables e2 l e2' ->\n  locenv_match e1' e2'.\nProof.\n  induction 1; simpl; intros.\n  inv H0. auto.\n  inv H1. eapply IHalloc_variables; eauto.\n  apply locenv_match_addsameid; auto.\nQed.\n\nLemma alloc_variables_init_match:\n  forall l1 l2 te1 te2, \n  alloc_variables empty_locenv l2 te1 ->\n  alloc_variables empty_locenv (l1++l2) te2 ->\n  locenv_match te1 te2.\nProof.\n  intros. apply alloc_variables_app in H0. \n  destruct H0 as [te [? ?]].\n  eapply alloc_variables_locenv_match; eauto.\n  red; intros. rewrite PTree.gempty in H2. congruence.\nQed.\n\nLemma locenv_setvars_match:\n  forall e1 l vl e1',\n  locenv_setvars e1 l vl e1' ->\n  forall e2, locenv_match e1 e2 ->\n  exists e2', locenv_setvars e2 l vl e2'\n    /\\ locenv_match e1' e2'.\nProof.\n  induction 1; simpl; intros; auto.\n  exists e2. split; auto. constructor. \n  destruct locenv_match_store_env_exists with ty e id Int.zero v e1 e2 as [e21 [? ?]]; auto.  \n  destruct IHlocenv_setvars with e21 as [e2' [? ?]]; auto.\n  exists e2'. split; auto.\n  constructor 2 with e21 m; auto.\nQed.\n\nLemma locenv_setvars_ptree_vars_some:\n  forall e l1 vl e',\n  locenv_setvars e l1 vl e' ->\n  forall l2, ptree_vars_some l2 e ->\n  list_disjoint (map fst l1) (map fst l2) ->\n  ptree_vars_some l2 e'.\nProof.\n  induction 1; simpl; intros; auto.\n  apply IHlocenv_setvars; auto.\n  inv H0. red; intros. rewrite PTree.gso; auto.\n  apply list_disjoint_sym in H3. eapply H3; simpl; eauto.\n  apply in_map with (f:=fst) in H0; auto.\n  red; intros. eapply H3; simpl; eauto.\nQed.\n\nLemma eval_init_exists:\n  forall (f:func) eh1,\n  eval_init empty_locenv (nd_flags f) (nd_svars f) eh1 ->\n  ids_norepet f ->\n  exists eh eh2, alloc_variables empty_locenv (nd_rets f) eh \n    /\\ eval_init eh (nd_flags f) (nd_svars f) eh2 \n    /\\ locenv_match eh1 eh2\n    /\\ ptree_vars_some (nd_rets f) eh2.\nProof.\n  intros.\n  destruct alloc_variables_exists with (nd_rets (trans_body f)) empty_locenv as [eh A].\n  exists eh. inv H.\n  destruct alloc_variables_exists with (nd_flags (trans_body f) ++ nd_svars (trans_body f)) eh as [eh3 A1].\n  cut (locenv_match eh2 eh3); intros.\n  apply locenv_setvars_match with (e2:=eh3) in H3; auto.\n  destruct H3 as [eh3' [? ?]].\n  exists eh3'. repeat split; auto. simpl in *.\n  +constructor 1 with eh3; auto.\n  +apply ids_norepet_rets_svars in H0. unfold svarsof in *.\n   rewrite map_app in H0. apply list_norepet_app in H0.\n   destruct H0 as [A2 [A3 A4]].\n   eapply locenv_setvars_ptree_vars_some; eauto.\n   simpl in *. eapply alloc_variables_ptree_vars_some in A; eauto.\n   red; intros. destruct A with id ty as [m [? ?]]; auto.\n   exists m; split; auto. apply in_map with (B:=ident) (f:=fst) in H0.\n   erewrite alloc_variables_notin_eq; eauto.\n   eapply list_disjoint_notin; eauto.\n   apply list_disjoint_sym.\n   red; intros. apply A4; eauto.\n   rewrite map_app. apply in_or_app; auto.\n  +apply alloc_variables_init_match with (nd_rets f) (nd_flags f ++ nd_svars f); eauto.\n   apply alloc_variables_trans with eh; auto.\nQed.\n\nLemma init_node_correct:\n  forall eL fd,\n  LsemF.init_node true prog1 eL fd ->\n  exists eR, init_node prog2 eR (trans_node fd) \n   /\\ env_match eL eR\n   /\\ env_ids_none fd eL\n   /\\ env_ids_some fd eR.\nProof. \n  intros gc.\n  induction 1 using LsemF.init_node_ind2 with \n  ( P0 := fun nid eL eL' l =>\n      forall ehL seL seL' ehR seR, \n      eL = mkenv ehL seL ->\n      eL' = mkenv ehL seL' ->\n      env_match eL (mkenv ehR seR)  ->\n      list_norepet (map instid l) ->\n      exists seR', init_stmt prog2 nid (mkenv ehR seR) (mkenv ehR seR') l\n       /\\ env_match eL' (mkenv ehR seR')\n       /\\ subenv_ids env_ids_none seL' l\n       /\\ subenv_ids env_ids_some seR' l\n       /\\ ptree_noids_match (map instid l) seL seL' \n       /\\ ptree_noids_match (map instid l) seR seR'\n   ); intros.\n +(*init_node*)\n  generalize H; intros B.\n  apply trans_body_ids_norepet in H; auto.\n  destruct eval_init_exists with f eh1 as [eh [eh2 [A [A1 [A2 A3]]]]]; auto.\n  destruct IHinit_node with eh1 empty_subenv se eh2 empty_subenv as [seR' [? [? [? [? [? ?]]]]]]; auto.\n    constructor; auto. apply subenv_match_empty.\n    apply ids_norepet_instid; auto.\n  exists (mkenv eh2 seR'). repeat (split; auto).\n  constructor 1 with eh; simpl; auto.\n  -rewrite trans_stmt_instidof_eq. auto.\n  -red; intros.\n   cut (~ In id (map fst (nd_flags f++nd_svars f))). intros B1.\n   inv H0. \n   erewrite locenv_setvars_notin_eq; eauto.\n   erewrite alloc_variables_notin_eq; eauto.\n   rewrite PTree.gempty. auto.\n   red; intros; subst. apply B1; simpl.\n   rewrite map_app. apply in_or_app; auto.\n   eapply list_disjoint_notin; eauto.\n   eapply ids_norepet_rets_svars_disjoint; auto.\n  -simpl. destruct (nd_kind f) eqn:?; auto. red; intros. tauto. \n  -simpl. destruct (nd_kind f) eqn:?; auto. red; intros. tauto.\n +(*nil*)\n  subst. inv H0.\n  exists seR. repeat (split; auto).\n  -constructor.\n  -red. intros ? A. inv A.\n  -red. intros ? A. inv A.\n +(*cons*)\n  generalize H; intros A.\n  eapply trans_call_node in H; eauto.\n  destruct A as [A [A1 [[A2 [A4 [A5 [A6 A7]]]] A3]]].\n  inv H3. inv H4. inv H6.\n  destruct IHinit_node as [efR [? [? [? ?]]]]; auto.\n  remember (PTree.set _ _ _) as se1.\n  destruct IHinit_node0 with ehL se1 seL' ehR (PTree.set (instid c) (list_repeat (nat_of_int (intof_opti (callnum c))) efR) seR) \n    as [seR' [? [? [? [? [? ?]]]]]]; auto.\n    inv H5. constructor;auto. eapply subenv_match_setsame; eauto.\n      eapply Forall2_list_repeat; eauto.\n  exists seR'. split; [| split; [| split; [| split; [| split]]]]; auto.\n  -econstructor 2 with _ (trans_node nd) (trans_node fd) efR; eauto.\n  -red; simpl; intros ? B. destruct B; subst; auto.\n   exists fd, (list_repeat (nat_of_int (intof_opti (callnum c0))) ef).\n   repeat split; auto.\n   rewrite <-H13; auto. rewrite PTree.gss; auto.\n   eapply Forall_list_repeat; eauto.\n  -red; simpl; intros ? B. destruct B; subst; auto.\n   exists fd, (list_repeat (nat_of_int (intof_opti (callnum c0))) efR).\n   repeat split; auto.\n   rewrite <-H14; auto. rewrite PTree.gss; auto.\n   eapply Forall_list_repeat; eauto.\n  -simpl. red; simpl; intros. subst.\n   rewrite <-H13; auto. rewrite PTree.gso; auto.\n  -simpl. red; simpl; intros. subst.\n   rewrite <-H14; auto. rewrite PTree.gso; auto.\nQed.\n\nLemma initial_states_match:\n  forall gc main1 eL,\n  Lenv.initial_state1 prog1 gc (fun p e fd => LsemF.init_node true p e fd) main1 eL ->\n  exists main2 eR, Lenv.initial_state1 prog2 gc (fun p e fd => LsemE.init_node p e fd) main2 eR\n    /\\ trans_node main1 = main2\n    /\\ env_match eL eR\n    /\\ env_ids_none main1 eL\n    /\\ env_ids_some main1 eR.\nProof.\n  intros. inversion_clear H.\n  destruct init_node_correct with eL main1 as [eR [? [? [? ?]]]]; auto.\n  exists (trans_node main1), eR. split; auto.\n  subst. constructor 1; auto.\n  eapply trans_funcs_find; eauto.\nQed.\n\nLemma exec_prog_correct:\n  forall gc main1 eL n maxn vass vrss,\n  Lenv.exec_prog1 prog1 gc (LsemF.eval_node true) main1 eL n maxn vass vrss ->\n  forall eR, env_match eL eR ->\n  env_ids_none main1 eL ->\n  env_ids_some main1 eR ->\n  find_funct (node_block prog1) (fst main1) = Some main1 ->\n  Lenv.exec_prog1 prog2 gc eval_node (trans_node main1) eR n maxn vass vrss.\nProof.\n  induction 1; intros; try congruence.\n  +constructor 1 with mrss; auto.\n  +destruct e as [ehL seL]. destruct e' as [ehL' seL'].\n   destruct eR as [ehR seR].\n   eapply trans_node_all_correct in H1; eauto.\n   destruct H1 as [eR' [? [? [? ?]]]].\n   econstructor 2; eauto.\nQed.\n\nTheorem trans_program_correct:\n  forall gc eL main1 vass vrss maxn,\n  Lenv.initial_state1 prog1 gc (fun p e fd => LsemF.init_node true p e fd) main1 eL ->\n  Lenv.exec_prog1 prog1 gc (LsemF.eval_node true) main1 eL 1 maxn vass vrss ->\n  exists main2 eR, Lenv.initial_state1 prog2 gc (fun p e fd => LsemE.init_node p e fd) main2 eR\n    /\\ Lenv.exec_prog1 prog2 gc LsemE.eval_node main2 eR 1 maxn vass vrss\n    /\\ nd_rets (snd main2) = nd_rets (snd main1)\n    /\\ nd_fld (snd main2) = nd_fld (snd main1)\n    /\\ nd_kind (snd main2) = nd_kind (snd main1).\nProof.\n  intros.\n  destruct initial_states_match with gc main1 eL as [main2 [eR [? [? [? [? ?]]]]]]; auto.\n  exists main2, eR; split; [| split]; auto.\n  subst main2. apply exec_prog_correct with eL; auto.\n  inv H; try congruence. eapply find_funct_eq; eauto.\n  subst. auto.\nQed.\n\nEnd CORRECTNESS.\n", "meta": {"author": "linusboyle", "repo": "L2CDisplay", "sha": "4eb5b4dbb01da56534c0b0a1560dec8c715a68a4", "save_path": "github-repos/coq/linusboyle-L2CDisplay", "path": "github-repos/coq/linusboyle-L2CDisplay/L2CDisplay-4eb5b4dbb01da56534c0b0a1560dec8c715a68a4/src/ClassifyRetsVarProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23324638135158382}}
{"text": "Require Import include_frm.\nRequire Import os_inv.\nRequire Import abs_op.\nRequire Import sep_auto.\nRequire Import ucos_frmaop.\nRequire Import abs_step.\nRequire Import os_code_defs.\n\nLocal Open Scope int_scope.\n\nLemma absimp_toy:\n  forall P tls qls curtid tm s sch,\n    can_change_aop P ->\n    absinfer sch\n             ( <||toyint_spec (|nil|) ;; s||> ** HECBList qls **  HTCBList tls ** HTime tm **  HCurTCB curtid ** P)\n             ( <||END None;;s ||> ** HECBList qls** HTCBList tls **  HTime tm ** HCurTCB curtid **P).\nProof.\n  intros.\n  apply absinfer_seq.\n  can_change_aop_solver.\n  can_change_aop_solver.\n  infer_solver 0%nat.\nQed.\n\n\nLemma  tcbjoinsig_set_sub_sub:\n  forall t x tcbls tcbls' tls y tls',\n    TcbMod.joinsig t x tcbls tcbls' ->\n    TcbMod.set tls t y = tls' ->\n    TcbMod.sub tcbls' tls ->\n    TcbMod.sub tcbls tls'.\nProof.\n  intros.\n  unfolds; intros.\n  unfold TcbMod.joinsig in H.\n  unfold TcbMod.sub in H1.\n  unfold TcbMod.lookup in *.\n  pose proof H a.\n  substs.\n  rewrite H2 in H3.\n  destruct (tidspec.beq t a) eqn : eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite TcbMod.set_a_get_a; auto.\n  rewrite TcbMod.get_sig_some in H3; tryfalse.\n  pose proof tidspec.beq_false_neq _ _ eq1.\n  rewrite TcbMod.get_sig_none in H3; auto.\n  destruct (TcbMod.get tcbls' a) eqn : eq2; tryfalse.\n  apply H1 in eq2; substs.\n  rewrite TcbMod.set_a_get_a'; auto.\nQed.\n\n\n\nLemma tickstep_eqdomtls:\n  forall (tls tls_sub:TcbMod.map) qls tls' qls' ,\n    TcbMod.sub tls_sub tls ->\n    tickstep' tls qls tls' qls' tls_sub->\n    eqdomtls tls tls'.\nProof.\n  intros.\n  inductions H0.\n  unfolds.\n  intros.\n  split;intros.\n  unfolds;unfolds in H0.\n  simpljoin.\n  eexists;eauto.\n  unfolds in H0.\n  unfolds;simpljoin;eauto.\n  assert (eqdomtls tls tls').\n  subst tls'.\n  eapply tls_get_set_indom;eauto.\n  instantiate (1:=(p, st, msg0)).\n  eapply TcbMod.get_sub_get;eauto.\n  eapply TcbMod.join_get_l.\n  eauto.\n  eapply TcbMod.get_a_sig_a.\n  apply CltEnvMod.beq_refl.\n  lets Hx: tcbjoinsig_set_sub_sub H0 H2 H.\n  apply IHtickstep' in Hx.\n  clear -H4 Hx.\n  unfold eqdomtls in *.\n  intros.\n  lets Ha: H4 tid.\n  lets Hb: Hx tid.\n  clear H4 Hx.\n  split;\n    destruct Ha,Hb.\n  intros.\n\n  apply H in H3.\n  apply H1 in H3;auto.\n  intros.\n  apply H2 in H3.\n  apply H0 in H3.\n  auto.\nQed.\n\n\n\n\nLemma absimp_timetick:\n  forall P tls qls tls' qls' curtid tm s sch,\n    can_change_aop P ->\n    tickstep tls qls tls' qls' ->\n    absinfer sch ( <|| timetick_spec (|nil|);;s ||>\n                 ** HECBList qls **  HTCBList tls ** HTime tm **  HCurTCB curtid ** P)\n           ( <|| END None;;s ||> **                                                                                                                 \n                 HECBList qls'** HTCBList tls' **  HTime (Int.add tm Int.one) **\n                 HCurTCB curtid **P).\nProof.\n  intros.\n  apply absinfer_seq.\n  can_change_aop_solver.\n  can_change_aop_solver.\n\n  idtac.\n  (* ** ac: Print absinfer. *)\n  eapply absinfer_prim.\n  can_change_aop_solver.\n  can_change_aop_solver.\n  (* ** ac: Print absimp. *)\n  unfold absimp.\n  intros.\n  eexists; exgamma.\n  (* infer_part1 0%nat. *)\n  (* eexists; exgamma. *)\n  splits.\n  hmstep_solver.\n  assert (eqdomO  \n        (set (set O absecblsid (absecblist qls'))\n                       abtcblsid (abstcblist tls'))\n                  (set\n        (set (set O absecblsid (absecblist qls'))\n                       abtcblsid (abstcblist tls')) ostmid (ostm (tm+ᵢInt.one)))).\n  {\n    eapply abst_get_set_eqdom.\n    absdata_solver.\n    simpl;auto.\n  }\n  \n  assert (eqdomO  (set O absecblsid (absecblist qls')) (set (set O absecblsid (absecblist qls'))\n                                                                                abtcblsid (abstcblist tls'))).\n  {\n    eapply abst_get_set_eqdom.\n    absdata_solver.\n    simpl.\n  \n    eapply tickstep_eqdomtls;eauto.\n    apply TcbMod.sub_refl.\n  }\n  \n  assert (eqdomO O (set O absecblsid (absecblist qls'))).\n  {\n    eapply abst_get_set_eqdom.\n    absdata_solver.\n    simpl;auto.\n  }\n\n  (* ** ac: Check tickstep_eqdomtls. *)\n  eapply tickstep_eqdomtls;eauto.\n  apply TcbMod.sub_refl.\n  \n  (* eapply eqdomO_trans;eauto. *)\n  assert (tidsame (set (set O absecblsid (absecblist qls'))\n                                 abtcblsid (abstcblist tls'))\n                  (set\n                     (set (set O absecblsid (absecblist qls'))\n                                    abtcblsid (abstcblist tls')) ostmid (ostm (tm+ᵢInt.one)))).\n  {\n    tidsame_solver.\n  }\n  assert (tidsame O\n                  (set (set O absecblsid (absecblist qls'))\n                       abtcblsid (abstcblist tls'))).\n  {\n    tidsame_solver.\n  }\n  \n  eapply tidsame_trans; eauto.\n  repeat simpl_absdata_sep; sep auto.\nQed.\n\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/spec/absoprules/int_absop_rules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.23324402138587397}}
{"text": "Require Import Coq.Lists.List.\n\nRequire Export SystemFR.ReducibilityLemmas.\nRequire Export SystemFR.CloseLemmas.\nRequire Export SystemFR.SubstitutionErase.\nRequire Export SystemFR.Functional.\n\nOpaque reducible_values.\n\nFixpoint T_existss n T1 T2 :=\n  match n with\n  | 0 => T2\n  | S n' => T_exists T1 (T_existss n' T1 T2)\n  end.\n\nDefinition T_exists_vars xs T1 T2 :=\n  T_existss (List.length xs) T1 (closes 0 T2 (rev xs)).\n\nLemma psubstitute_texistss:\n  forall n T1 T2 l tag,\n    psubstitute (T_existss n T1 T2) l tag =\n    T_existss n (psubstitute T1 l tag) (psubstitute T2 l tag).\nProof.\n  induction n; repeat step || rewrite_any.\nQed.\n\nLemma substitute_closes:\n  forall xs t l tag k,\n    (forall x, x ∈ support l -> x ∈ xs -> False) ->\n    pclosed_mapping l term_var ->\n    psubstitute (closes k t xs) l tag = closes k (psubstitute t l tag) xs.\nProof.\n  induction xs;\n    repeat step || rewrite substitute_close by (steps; eauto);\n    try solve [ rewrite_any; steps; eauto ].\nQed.\n\nLemma psubstitute_texists_vars:\n  forall xs T1 T2 l tag,\n    (forall x, x ∈ support l -> x ∈ xs -> False) ->\n    pclosed_mapping l term_var ->\n    psubstitute (T_exists_vars xs T1 T2) l tag =\n    T_exists_vars xs (psubstitute T1 l tag) (psubstitute T2 l tag).\nProof.\n  unfold T_exists_vars; intros; rewrite psubstitute_texistss; apply f_equal.\n  rewrite substitute_closes; repeat step || rewrite <- in_rev in *; eauto.\nQed.\n\nLemma is_erased_type_existss:\n  forall n T1 T2,\n    is_erased_type T1 ->\n    is_erased_type T2 ->\n    is_erased_type (T_existss n T1 T2).\nProof.\n  induction n; repeat step || apply_any.\nQed.\n\n#[export]\nHint Resolve is_erased_type_existss: erased.\n\nLemma open_existss:\n  forall n T1 T2 k rep,\n    wf T1 0 ->\n    open k (T_existss n T1 T2) rep =\n    T_existss n T1 (open (n + k) T2 rep).\nProof.\n  induction n; steps; repeat step || t_equality || open_none || rewrite_any ||\n                             rewrite PeanoNat.Nat.add_succ_r.\nQed.\n\nLemma reducible_exists_vars:\n  forall xs ρ v vs T1 T2,\n    wf T1 0 ->\n    wf T2 0 ->\n    is_erased_type T1 ->\n    is_erased_type T2 ->\n    List.Forall (fun v => [ ρ ⊨ v : T1 ]v) vs ->\n    List.length xs = List.length vs ->\n    valid_interpretation ρ ->\n    (forall z v', z ∈ xs -> v' ∈ vs -> z ∈ fv v' -> False) ->\n    [ ρ ⊨ v : psubstitute T2 (List.combine xs vs) term_var ]v ->\n    [ ρ ⊨ v : T_exists_vars xs T1 T2 ]v.\nProof.\n  induction xs; repeat step || t_substitutions.\n  unshelve epose proof\n    (IHxs ρ v l T1 (psubstitute T2 ((a,t) :: nil) term_var) _ _ _ _ _ _ _ _ _); steps; eauto;\n    try solve [\n      rewrite <- substitute_cons2; repeat step || rewrite support_combine in * by auto; eauto\n    ];\n    eauto 3 with erased step_tactic;\n    eauto 3 with wf step_tactic.\n\n  unfold T_exists_vars in *.\n  simp_red_goal; steps; eauto 4 with erased; eauto using reducible_values_closed.\n  exists t; repeat step || rewrite open_existss; eauto with erased fv wf.\n  rewrite <- rev_length at 2.\n  rewrite open_closes; steps; eauto with wf fv.\nQed.\n\nLemma reducible_exists_vars2_helper:\n  forall xs ρ v T1 T2,\n    wf T1 0 ->\n    wf T2 0 ->\n    is_erased_type T1 ->\n    is_erased_type T2 ->\n    valid_interpretation ρ ->\n    [ ρ ⊨ v : T_exists_vars xs T1 T2 ]v ->\n    (exists vs,\n      List.Forall (fun v => [ ρ ⊨ v : T1 ]v) vs /\\\n      length vs = length xs /\\\n      [ ρ ⊨ v : psubstitute T2 (combine xs vs) term_var ]v).\nProof.\n  induction xs; repeat step || t_substitutions || simp_red_top_level_hyp;\n    eauto 2 with step_tactic.\n\n  rewrite open_existss in *; eauto with wf.\n  rewrite <- rev_length in * at 2.\n  rewrite open_closes in *; eauto with wf fv.\n  rewrite rev_length in *.\n\n  unshelve epose proof (IHxs _ _ _ _ _ _ _ _ _ H9); steps;\n    eauto 2 with wf step_tactic;\n    eauto 2 with erased step_tactic.\n\n  exists (a0 :: vs); steps; eauto.\n  rewrite substitute_cons2; repeat step || (erewrite reducible_val_fv in * by eauto).\nQed.\n\nLemma reducible_exists_vars2:\n  forall xs ρ v T1 T2,\n    wf T1 0 ->\n    wf T2 0 ->\n    is_erased_type T1 ->\n    is_erased_type T2 ->\n    valid_interpretation ρ ->\n    [ ρ ⊨ v : T_exists_vars xs T1 T2 ]v ->\n    (exists vs,\n      List.Forall (fun v => [ ρ ⊨ v : T1 ]v) vs /\\\n      functional (combine xs vs) /\\\n      length vs = length xs /\\\n      [ ρ ⊨ v : psubstitute T2 (combine xs vs) term_var ]v).\nProof.\n  intros.\n  apply_anywhere reducible_exists_vars2_helper; steps.\n  pose proof (functionalize (combine xs vs)); repeat step || list_utils2.\n  exists (range l'); repeat step || list_utils || list_utils2 || rewrite Forall_forall in *.\n  erewrite subst_permutation in * |-; eauto.\nQed.\n", "meta": {"author": "epfl-lara", "repo": "SystemFR", "sha": "a68d12d6360f395958506deea66112c46be492a0", "save_path": "github-repos/coq/epfl-lara-SystemFR", "path": "github-repos/coq/epfl-lara-SystemFR/SystemFR-a68d12d6360f395958506deea66112c46be492a0/Existss.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.233244015827522}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssrZ ZArith_ext seq_ext ssrnat_ext uniq_tac machine_int.\nRequire Import multi_int.\nImport MachineInt.\nRequire Import mips_bipl mips_seplog mips_mint.\nImport expr_m.\nRequire Import simu.\nImport simu_m.\nFrom mathcomp Require Import seq.\nRequire Import multi_add_s_u_prg multi_add_s_u_triple.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope asm_expr_scope.\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope assoc_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope simu_scope.\nLocal Open Scope asm_cmd_scope.\nLocal Open Scope uniq_scope.\n\n(** x <- x + y, x signed, y unsigned *)\n\nLemma pfwd_sim_multi_add_s_u (x y : assoc.l) d k rk rx ry a0 a1 a2 a3 a4 a5 rX :\n  uniq(x, y) ->\n  uniq(rk, rx, ry, a0, a1, a2, a3, a4, a5, rX, r0) ->\n  disj (mints_regs (assoc.cdom d)) (a0 :: a1 :: a2 :: a3 :: a4 :: a5 :: rX :: nil) ->\n  x \\notin assoc.dom d -> y \\notin assoc.dom d ->\n  signed k rx \\notin assoc.cdom d -> unsign rk ry \\notin assoc.cdom d ->\n  (x <- var_e x \\+ var_e y)%pseudo_expr%pseudo_cmd\n    <=p( state_mint (x |=> signed k rx \\U+ (y |=> unsign rk ry \\U+ d)),\n         fun st s _ => [rk ]_ s <> zero32 /\\\n                        u2Z ([rk ]_ s) < 2 ^^ 31 /\\\n                        k = '|u2Z ([rk ]_ s)| /\\\n                        `| ([x ]_ st)%pseudo_expr | < \\B^k /\\\n                        0 <= ([y ]_ st)%pseudo_expr < \\B^k /\\\n                        `| ([x ]_ st + [y ]_ st)%pseudo_expr | < \\B^k)\n  multi_add_s_u rk rx ry a0 a1 a2 a3 a4 a5 rX.\nProof.\nmove=> Hvars Hregs Hd x_d y_d rx_d rk_ry_d.\nrewrite /pfwd_sim.\nmove=> st s h [st_s_h [rk_st_neq0 [rk_st_max [k_rk [x_k [y_st x_y_st]]]]]] st' exec_pseudo s' h' exec_asm.\n\nhave Hd_unchanged : forall v r, assoc.get v d = Some r ->\n  disj (mint_regs r) (mips_frame.modified_regs (multi_add_s_u rk rx ry a0 a1 a2 a3 a4 a5 rX)).\n  move=> v r Hvr; rewrite [mips_frame.modified_regs _]/=; Disj_remove_dup.\n  apply (disj_incl_LR Hd); last by apply incl_refl_Permutation; PermutProve.\n  apply/incP/inc_mint_regs.\n  by move/assoc.get_Some_in_cdom : Hvr.\nset vx := [rx ]_ s.\nset vy := [ry ]_ s.\n\nlapply (state_mint_var_mint _ _ _ _ x (signed k rx) st_s_h); [move=> var_mint_x | by assoc_get_Some].\nrewrite /var_mint in var_mint_x.\ncase: var_mint_x => slen ptr X vx_fit [X_k Hlen Hsgn Sum_X] ptr_fit Hmem.\n\nhave : k <> 0%nat.\n  contradict rk_st_neq0. apply u2Z_inj. rewrite rk_st_neq0 in k_rk.\n  symmetry in k_rk. apply Zabs_nat_0_inv in k_rk. by rewrite Z2uK.\nmove/(multi_add_s_u_triple_gen rk rx ry a0 a1 a2 a3 a4 a5 rX Hregs).\nmove/(_ vx vy ptr).\nhave : Z<=nat k < 2 ^^ 31.\n  rewrite k_rk Z_of_nat_Zabs_nat //; by apply min_u2Z.\nlet x := fresh in move=> x; move/(_ x); clear x.\nmove/(_ ptr_fit).\nhave : Z<=u vy + 4 * Z<=nat k < \\B^1.\n  rewrite assoc_prop_m.swap_heads in st_s_h; last by [].\n  move: (state_mint_head_unsign_fit _ _ _ _ _ _ _ st_s_h); by rewrite k_rk.\nlet x := fresh in move=> x; move/(_ x); clear x.\nmove/(_ X (Z2ints 32 k ([ y ]_ st)%pseudo_expr) X_k).\nrewrite size_Z2ints.\nmove/(_ Logic.eq_refl slen Hlen).\nrewrite -Sum_X.\nmove/(_ Hsgn) => Hhoare_multi_add_s_u.\n\nhave [s'' [h'' exec_asm_proj]] : exists s'' h'',\n  (Some (s, h |P| heap.dom (heap_mint (unsign rk ry) s h \\U heap_mint (signed k rx) s h))\n    -- multi_add_s_u rk rx ry a0 a1 a2 a3 a4 a5 rX --->\n    Some (s'', h''))%asm_cmd.\n  exists s', (h' |P| heap.dom (heap_mint (unsign rk ry) s h \\U heap_mint (signed k rx) s h)).\n  apply (mips_syntax.triple_exec_proj _ _ _ Hhoare_multi_add_s_u) => {Hhoare_multi_add_s_u} //.\n  split; first by [].\n  split; first by [].\n  split.\n    rewrite k_rk Z_of_nat_Zabs_nat //; exact/min_u2Z.\n  rewrite heap.proj_dom_union; last first.\n    apply (proj2 st_s_h y x); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n  rewrite heap.unionC; last first.\n    apply heap.dis_disj_proj.\n    rewrite -heap.disjE.\n    apply (proj2 st_s_h y x); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n  apply assert_m.con_cons.\n    apply heap.dis_disj_proj.\n    rewrite -heap.disjE.\n    apply (proj2 st_s_h x y); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n  move: (heap_inclu_heap_mint_signed h s k rx).\n  move/heap.incluE => ->; exact Hmem.\n  (* TODO: can't use heap_inclu_heap_mint_unsign? like in copy_signed_unsign? *)\n  have y_ry : var_mint y (unsign rk ry) st s (heap_mint (unsign rk ry) s h).\n    apply (state_mint_var_mint _ _ _ _ _ _ st_s_h); by assoc_get_Some.\n  case: (y_ry) => _ [] _ Hry.\n  rewrite /heap_mint /heap_cut in y_ry.\n  by rewrite k_rk (var_mint_unsign_dom_heap_mint _ _ _ _ _ _ y_ry).\nhave ry_s_s' : [ry]_ s = [ry]_ s'.\n  mips_syntax.Reg_unchanged. simpl mips_frame.modified_regs. by Uniq_not_In.\nhave rk_s_s' : [rk ]_ s = [rk ]_ s'.\n  mips_syntax.Reg_unchanged. simpl mips_frame.modified_regs. by Uniq_not_In.\nhave y_st_st' : ([y ]_ st = [y ]_ st')%pseudo_expr.\n  Var_unchanged. simpl syntax_m.seplog_m.modified_vars.\n  move/inP.\n  rewrite -/(~ _).\n  by Uniq_not_In.\nhave rx_s_s' : [rx ]_ s = [rx ]_ s'.\n  mips_syntax.Reg_unchanged. simpl mips_frame.modified_regs. by Uniq_not_In.\nset postcond := (fun s h => exists _, _) in Hhoare_multi_add_s_u.\nhave {Hhoare_multi_add_s_u}hoare_triple_post_condition : (\n  postcond ** assert_m.TT)%asm_assert s' h'.\n    move: {Hhoare_multi_add_s_u}(mips_frame.frame_rule_R _ _ _ Hhoare_multi_add_s_u assert_m.TT (assert_m.inde_TT _) (mips_frame.inde_cmd_mult_TT _)).\n    move/mips_seplog.hoare_prop_m.soundness.\n    rewrite /while.hoare_semantics.\n    move/(_ s h) => Hmulti_add_s_u.\n    lapply Hmulti_add_s_u; last first.\n      exists (heap_mint (signed k rx) s h \\U heap_mint (unsign rk ry) s h),\n       (h \\D\\ heap.dom (heap_mint (signed k rx) s h \\U heap_mint (unsign rk ry) s h)).\n      split; first by apply heap.disj_difs', seq_ext.inc_refl.\n      split.\n        apply heap.union_difsK; last by [].\n        apply heap_prop_m.inclu_union; by [apply heap_inclu_heap_mint_signed | apply heap.inclu_proj].\n      split; last by [].\n      repeat (split=> //).\n      rewrite k_rk Z_of_nat_Zabs_nat //; by apply min_u2Z.\n      apply assert_m.con_cons.\n      + apply (proj2 st_s_h x y); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n      + exact Hmem.\n      + move: (proj1 st_s_h y (unsign rk ry)).\n        rewrite assoc.get_union_sing_neq; last by Uniq_neq.\n        rewrite assoc.get_union_sing_eq.\n        case/(_ (refl_equal _))=> _ [] _; by rewrite -k_rk.\n    case=> _.\n    by move/(_ _ _ exec_asm).\nrewrite /state_mint; split.\n- move=> z rz z_rz.\n  have [z_d | z_x ] : z \\in assoc.dom (y |=> unsign rk ry \\U+ d) \\/ z = x.\n    rewrite assoc.unionC in z_rz; last first.\n      apply assoc.disjhU.\n      apply assoc.disj_sing.\n      apply/eqP; by Uniq_neq.\n      by apply assoc.disj_sym, assoc.disj_sing_R.\n    case/assoc.get_union_Some_inv : z_rz => z_rz.\n    left.\n    by apply assoc.get_Some_in_dom with rz.\n    case/assoc.get_sing_inv : z_rz => ? ?; subst z rz.\n    by right.\n  + (* NB: it is about proving that x is unchanged, which is true since\n       neither y nor d are touched by execution *)\n    have z_x : z <> x.\n      move=> ?; subst z.\n      case/assoc.in_dom_union_inv : z_d.\n      * case/assoc.in_dom_get_Some => z.\n        case/assoc.get_sing_inv => z_d _.\n        move: z_d.\n        rewrite -/(~ _); by Uniq_neq.\n      * by rewrite (negbTE x_d).\n    case/orP : (orbN (z == y)) => z_y.\n    * (* z = y *) move/eqP : z_y => ?; subst z.\n      rewrite assoc.unionC in z_rz; last first.\n        apply assoc.disjhU.\n        apply assoc.disj_sing; by apply/eqP/nesym.\n        by apply assoc.disj_sym, assoc.disj_sing_R.\n      rewrite -assoc.unionA assoc.get_union_sing_eq in z_rz.\n      case: z_rz => ?; subst rz.\n      case : hoare_triple_post_condition => h1 [h2 [h1_d_h2 [h1_U_h2 [Hh1 Hh2]]]].\n      case: Hh1 => X' [slen' Hh1].\n      decompose [and] Hh1; clear Hh1.\n      case: H4 => h11 [h12 [h11_d_h12 [h11_U_h12 [Hh11 Hh12]]]].\n      move: (proj1 st_s_h y (unsign rk ry)).\n      rewrite assoc.get_union_sing_neq; last by Uniq_neq.\n      rewrite assoc.get_union_sing_eq.\n      move/(_ (refl_equal _)).\n      have <- : heap_mint (unsign rk ry) s h = heap_mint (unsign rk ry) s' h'.\n        rewrite {2}/heap_mint /heap_cut h1_U_h2 h11_U_h12.\n        move/assert_m.mapstos_inv_dom : (Hh12) => Hh12'.\n        have : u2Z [var_e ry ]e_ s' +\n          4 * Z_of_nat (size (Z2ints 32 k ([y ]_ st)%pseudo_expr)) < \\B^1.\n          rewrite [u2Z _]/= size_Z2ints -ry_s_s'.\n          move: (proj1 st_s_h y (unsign rk ry)).\n          rewrite assoc.get_union_sing_neq; last by Uniq_neq.\n          rewrite assoc.get_union_sing_eq k_rk.\n          by case/(_ (refl_equal _)).\n        move/Hh12' => {}Hh12'.\n        rewrite size_Z2ints k_rk rk_s_s' in Hh12'.\n        rewrite {}Hh12'.\n        rewrite heap.proj_union_L; last by rewrite -heap.disjE; heap_tac_m.Disj.\n        rewrite heap.proj_union_R_dom; last by heap_tac_m.Disj.\n        move: (proj1 st_s_h y (unsign rk ry)).\n        rewrite assoc.get_union_sing_neq; last by auto.\n        rewrite assoc.get_union_sing_eq.\n        move/(_ (refl_equal _)).\n        case=> X1 X2 X3.\n        rewrite -k_rk in X3.\n        rewrite heap.proj_itself.\n        apply: (assert_m.strictly_exact_mapstos (Z2ints 32 k ([y ]_ st)%pseudo_expr) (var_e ry) s).\n        split; first by [].\n        move: Hh12; by apply assert_m.mapstos_ext.\n        apply var_mint_invariant_unsign; [exact ry_s_s' | exact rk_s_s' | exact y_st_st'].\n    * (* z <> y *) move: {st_s_h}(proj1 st_s_h _ _ z_rz) (proj2 st_s_h) => st_s_h1 st_s_h2.\n      have z_unchanged : ( [ z ]_ st = [ z ]_ st' )%pseudo_expr.\n        Var_unchanged. rewrite /= mem_seq1; exact/negP/eqP.\n      case: (mips_syntax.exec_deter_proj _ _ _ _ _ exec_asm\n        (heap.dom (heap_mint (unsign rk ry) s h \\U heap_mint (signed k rx) s h)) _ _\n        exec_asm_proj) => H4 [H5 H_h_h'].\n      have <- : heap_mint rz s h = heap_mint rz s' h'.\n        apply (heap_mint_state_invariant (heap_mint (unsign rk ry) s h \\U\n          heap_mint (signed k rx) s h) z st) => //.\n        move=> rx0 Hrx0; mips_syntax.Reg_unchanged.\n        apply (@disj_not_In _ (mint_regs rz)); last by [].\n        apply/disj_sym/(Hd_unchanged z).\n        rewrite assoc.get_union_sing_neq in z_rz; last by [].\n        rewrite assoc.get_union_sing_neq // in z_rz.\n        by apply/eqP.\n        apply heap.disjhU.\n        apply st_s_h2 with z y => //.\n        by apply/eqP.\n        rewrite assoc.get_union_sing_neq; last by Uniq_neq.\n        by rewrite assoc.get_union_sing_eq.\n        apply st_s_h2 with z x => //.\n      by rewrite assoc.get_union_sing_eq.\n      move: st_s_h1; apply var_mint_invariant; last exact z_unchanged.\n      move=> rx0 Hrx0; mips_syntax.Reg_unchanged.\n      apply (@disj_not_In _ (mint_regs rz)); last by [].\n      apply/disj_sym/(Hd_unchanged z) => //.\n      rewrite assoc.get_union_sing_neq in z_rz; last by [].\n      rewrite assoc.get_union_sing_neq // in z_rz.\n      by apply/eqP.\n  + (* NB: z is changed but stays a mint *) subst z.\n    have rz_rx : rz = signed k rx.\n      rewrite assoc.get_union_sing_eq in z_rz; by case: z_rz.\n    subst rz.\n    move: (proj1 st_s_h x (signed k rx) z_rz).\n    rewrite /var_mint.\n    case: hoare_triple_post_condition => [h1 [h2 [Hdisj [Hunion [[X' [slen' [Hadd_s_us_1 [r_x [r_y [Hadd_s_us_2 [Hadd_s_us_3 [Hadd_s_us_4 [Hadd_s_us_5 Hadd_s_us_6]]]]]]]]]] HTT]]]].\n    move=> ?.\n    have x'_x_y : ([ x ]_ st' = [ x ]_ st + [y ]_ st )%pseudo_expr.\n      move/syntax_m.seplog_m.semop_prop_m.exec_cmd0_inv : exec_pseudo.\n      case/syntax_m.seplog_m.exec0_assign_inv => _ -> /=.\n      by syntax_m.seplog_m.assert_m.expr_m.Store_upd.\n    apply (mkVarSigned _ _ _ _ _ slen' ptr X') => //.\n    + by rewrite /vx -rx_s_s'.\n    + apply mkSignMagn.\n      * exact Hadd_s_us_1.\n      * exact Hadd_s_us_2.\n      * rewrite !lSum_Z2ints_pos in Hadd_s_us_6 Hadd_s_us_3; last by exact y_st.\n        by rewrite Hadd_s_us_3 x'_x_y.\n      * rewrite !lSum_Z2ints_pos in Hadd_s_us_6 Hadd_s_us_3; last by exact y_st.\n        rewrite -x'_x_y in Hadd_s_us_6.\n        case: (Z_zerop (s2Z slen')) => slen'_neq0.\n          rewrite -Hadd_s_us_6 slen'_neq0 /=; ring.\n        have Hi : u2Z [a3 ]_ s' = 0.\n          have : `| sgZ (s2Z slen') * (lSum k X' + u2Z [ a3 ]_ s' * \\B^k) | < \\B^k.\n            by rewrite Hadd_s_us_6 x'_x_y.\n          rewrite Zabs_Zmult Zabs_Zsgn_1 // mul1Z addZC.\n          apply: poly_Zlt1_Zabs_inv => //.\n          by apply min_lSum.\n          by apply min_u2Z.\n        by rewrite Hi mul0Z addZ0 in Hadd_s_us_6.\n    + case: Hadd_s_us_4 => h11 [h12 [h11_d_h12 [h11_U_h12 [Hh11 Hh12]]]].\n      apply con_heap_mint_signed_cons with h11.\n      * rewrite Hunion.\n        apply heap.inclu_union_L => //.\n        rewrite h11_U_h12.\n        apply heap.inclu_union_L => //.\n        exact/heap.inclu_refl.\n      * by rewrite -rx_s_s'.\n      * by rewrite Hadd_s_us_1.\n      * exact Hadd_s_us_1.\n      * exact Hh11.\n- case: hoare_triple_post_condition => [h1 [h2 [Hdisj [Hunion [[X' [slen' [Hadd_s_us_1 [r_x [r_y [Hadd_s_us_2 [Hadd_s_us_3 [Hadd_s_us_4 [Hadd_s_us_5 Hadd_s_us_6]]]]]]]]]] HTT]]]].\n  have Hslen' : heap.get '|u2Z ([ rx ]_ s') / 4| h' = Some slen'.\n    rewrite Hunion.\n    apply heap.get_union_L => //.\n    rewrite assert_m.conAE in Hadd_s_us_4.\n    by apply assert_m.mapstos_get1 in Hadd_s_us_4.\n  have Hptr : heap.get '|u2Z ([ rx ]_ s' `+ four32) / 4| h' = Some ptr.\n    rewrite Hunion.\n    apply heap.get_union_L => //.\n    rewrite assert_m.conAE in Hadd_s_us_4.\n    by apply assert_m.mapstos_get2 in Hadd_s_us_4.\n  apply state_mint_part2_two_variables with st s h => //.\n  + move/assert_m.mapstos_get2 : (Hmem).\n    move/heap_get_heap_mint_inv => ptr_vx4.\n    move/assert_m.mapstos_get1 : (Hmem).\n    move/heap_get_heap_mint_inv => slen_vx.\n    symmetry.\n    apply dom_heap_mint_sign_state_invariant with x st slen slen'.\n    exact rx_s_s'.\n    exact slen_vx.\n    exact Hslen'.\n    by rewrite Hptr.\n    rewrite assoc_prop_m.swap_heads in st_s_h; last by [].\n    apply (state_mint_var_mint _ _ _ _ _ _ st_s_h).\n    rewrite assoc.get_union_sing_neq; last by Uniq_neq.\n    by rewrite assoc.get_union_sing_eq.\n    by apply (mips_syntax.dom_heap_invariant _ _ _ _ _ exec_asm).\n  + symmetry.\n    apply dom_heap_mint_unsign_state_invariant with y st.\n    exact rk_s_s'.\n    exact ry_s_s'.\n    apply (state_mint_var_mint _ _ _ _ _ _ st_s_h).\n    rewrite assoc.get_union_sing_neq; last by Uniq_neq.\n    by rewrite assoc.get_union_sing_eq.\n    by apply (mips_syntax.dom_heap_invariant _ _ _ _ _ exec_asm).\n  + move=> t Ht x0 Hx0.\n    mips_syntax.Reg_unchanged. simpl mips_frame.modified_regs.\n    case/assoc.in_cdom_union_inv : Ht => Ht.\n    * rewrite assoc.cdom_sing /= seq.mem_seq1 in Ht.\n      move/eqP in Ht; subst t.\n      apply (@disj_not_In _ (mint_regs (signed k rx))); last by [].\n      Disj_remove_dup.\n      rewrite /=.\n      apply uniq_disj. rewrite [cat _ _]/=. by Uniq_uniq r0.\n    * case/assoc.in_cdom_union_inv : Ht => Ht.\n      - rewrite assoc.cdom_sing /= seq.mem_seq1 in Ht.\n        move/eqP : Ht => Ht; subst t.\n        apply (@disj_not_In _ (mint_regs (unsign rk ry))); last by [].\n        Disj_remove_dup.\n        rewrite /=.\n        apply uniq_disj. rewrite [cat _ _]/=. by Uniq_uniq r0.\n      - apply (@disj_not_In _ (mint_regs t)); last by [].\n        Disj_remove_dup.\n        apply disj_sym.\n        apply (disj_incl_LR Hd); last by apply incl_refl_Permutation; PermutProve.\n        exact/incP/inc_mint_regs.\n  + by Uniq_neq.\n  + move: (mips_syntax.exec_deter_proj _ _ _ _ _ exec_asm _ _ _ exec_asm_proj); tauto.\nQed.\n\nLemma pfwd_sim_multi_add_s_u_wo_overflow (x y : assoc.l) d k rk rx ry a0 a1 a2 a3 a4 a5 rX :\n  uniq(x, y) ->\n  uniq(rk, rx, ry, a0, a1, a2, a3, a4, a5, rX, r0) ->\n  disj (mints_regs (assoc.cdom d)) (a0 :: a1 :: a2 :: a3 :: a4 :: a5 :: rX :: nil)%list ->\n  x \\notin assoc.dom d -> y \\notin assoc.dom d ->\n  signed k rx \\notin assoc.cdom d -> unsign rk ry \\notin assoc.cdom d ->\n  (x <- var_e x \\+ var_e y)%pseudo_expr%pseudo_cmd\n    <=p( state_mint (x |=> signed k rx \\U+ (y |=> unsign rk ry \\U+ d)),\n         fun s st _ => [rk ]_ st <> zero32 /\\\n         u2Z ([rk ]_ st) < 2 ^^ 31 /\\\n         k = '|u2Z ([rk ]_ st)| /\\\n         `| ([x ]_ s)%pseudo_expr | < \\B^(k - 1) /\\\n         0 <= ([y ]_ s)%pseudo_expr < \\B^(k - 1))\n  multi_add_s_u rk rx ry a0 a1 a2 a3 a4 a5 rX.\nProof.\nmove=> Hvars Hregs Hd A_d y_d rA_d rk_ry_d.\neapply pfwd_sim_stren; last by apply pfwd_sim_multi_add_s_u.\nmove=> s st h [rk_neq0 [rk_max [k_rk [A_max y_bounds]]]].\nsplit; first by [].\nsplit; first by [].\nsplit; first by [].\nhave k_neq0 : k <> O.\n  rewrite k_rk.\n  contradict rk_neq0.\n  apply Zabs_nat_0_inv in rk_neq0.\n  rewrite (_ : 0 = u2Z (Z2u 32 0)) in rk_neq0; last by rewrite Z2uK.\n  by move/u2Z_inj : rk_neq0.\nsplit.\n  apply/(ltZ_trans A_max)/Zbeta_lt; ssromega.\nsplit.\n  split; first tauto.\n  apply/(ltZ_trans (proj2 y_bounds))/Zbeta_lt; ssromega.\napply: leZ_ltZ_trans; first exact: Z.abs_triangle.\nrewrite (geZ0_norm ([y ]_ s)%pseudo_expr); last lia.\napply: ltZ_trans.\n  apply: ltZ_add; [exact: A_max | exact: (proj2 y_bounds)].\nrewrite /Zbeta Zpower_plus.\napply expZ_2_lt; ssromega.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/begcd/multi_add_s_u_simu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.23324401026916994}}
{"text": "Require Import ReflParam.common.\nRequire Import ReflParam.templateCoqMisc.\nRequire Import String.\nRequire Import List.\nRequire Import Template.Ast.\nRequire Import SquiggleEq.terms.\nRequire Import ReflParam.paramDirect.\nRequire Import SquiggleEq.substitution.\nImport ListNotations.\nOpen Scope string_scope.\n\nDefinition capture (T: nat -> Set) (x:nat) (x: T x) := x.\n\n\nRun TemplateProgram (printTermSq \"capture\").\n\nDefinition captureSyntax :=\n(mkLamS (0, nNamed \"T\")\n   (mkPiS (0, nAnon) (mkConstInd (mkInd \"Coq.Init.Datatypes.nat\" 0)) \n      (Some sSet) (mkSort sSet) None) None\n   (mkLamS (3, nNamed \"x\") (mkConstInd (mkInd \"Coq.Init.Datatypes.nat\" 0)) \n      (Some sSet)\n      (mkLamS (3, nNamed \"x\") (* changed 6 to 3*)\n         (oterm (CApply 1)\n            [bterm [] (vterm (0, nNamed \"T\")); bterm [] (vterm (3, nNamed \"x\"))])\n         (Some sSet) (vterm (3, nNamed \"x\"))))).\n\nEval vm_compute in (inBarendredgtConvention captureSyntax). (* false *)\n\nEval vm_compute in (translate false [] captureSyntax).\n\nDefinition captureTranslateSyntax\n     := mkLamS (0, nNamed \"T\")\n         (mkPiS (0, nAnon) (mkConstInd (mkInd \"Coq.Init.Datatypes.nat\" 0)) \n            (Some sSet) (mkSort sSet) None) None\n         (mkLamS (1, nNamed \"T₂\")\n            (mkPiS (1, nAnon) (mkConstInd (mkInd \"Coq.Init.Datatypes.nat\" 0)) \n               (Some sSet) (mkSort sSet) None) None\n            (mkLamS (2, nNamed \"T_R\")\n               (oterm (CApply 2)\n                  [bterm []\n                     (mkLamS (30, nNamed \"ff\")\n                        (mkPiS (0, nAnon) (mkConstInd (mkInd \"Coq.Init.Datatypes.nat\" 0))\n                           None\n                           (oterm (CApply 1)\n                              [bterm []\n                                 (mkLamS (0, nAnon)\n                                    (mkConstInd (mkInd \"Coq.Init.Datatypes.nat\" 0)) None\n                                    (mkSort sSet)); bterm [] (vterm (0, nAnon))]) None) None\n                        (mkLamS (31, nNamed \"ff₂\")\n                           (mkPiS (1, nAnon) (mkConstInd (mkInd \"Coq.Init.Datatypes.nat\" 0))\n                              None\n                              (oterm (CApply 1)\n                                 [bterm []\n                                    (mkLamS (1, nAnon)\n                                       (mkConstInd (mkInd \"Coq.Init.Datatypes.nat\" 0)) None\n                                       (mkSort sSet)); bterm [] (vterm (1, nAnon))]) None)\n                           None\n                           (mkPiS (0, nAnon) (mkConstInd (mkInd \"Coq.Init.Datatypes.nat\" 0))\n                              None\n                              (mkPiS (1, nAnon)\n                                 (mkConstInd (mkInd \"Coq.Init.Datatypes.nat\" 0)) None\n                                 (mkPiS (2, nAnon)\n                                    (oterm (CApply 2)\n                                       [bterm [] (mkConst \"Coq_Init_Datatypes_nat_RR0\");\n                                       bterm [] (vterm (0, nAnon));\n                                       bterm [] (vterm (1, nAnon))]) None\n                                    (oterm (CApply 2)\n                                       [bterm []\n                                          (oterm (CApply 3)\n                                             [bterm []\n                                                (mkLamS (0, nAnon)\n                                                   (mkConstInd\n                                                      (mkInd \"Coq.Init.Datatypes.nat\" 0))\n                                                   None\n                                                   (mkLamS (1, nAnon)\n                                                      (mkConstInd\n                                                         (mkInd \"Coq.Init.Datatypes.nat\" 0))\n                                                      None\n                                                      (mkLamS (2, nAnon)\n                                                         (oterm \n                                                            (CApply 2)\n                                                            [bterm []\n                                                               (mkConst\n                                                               \"Coq_Init_Datatypes_nat_RR0\");\n                                                            bterm [] (vterm (0, nAnon));\n                                                            bterm [] (vterm (1, nAnon))])\n                                                         None\n                                                         (mkLamS \n                                                            (0, nAnon) \n                                                            (mkSort sSet) None\n                                                            (mkLamS \n                                                               (3, nAnon) \n                                                               (mkSort sSet) None\n                                                               (mkPiS \n                                                               (6, nAnon) \n                                                               (vterm (0, nAnon)) None\n                                                               (mkPiS \n                                                               (9, nAnon) \n                                                               (vterm (3, nAnon)) None\n                                                               (mkSort sProp) None) None))))));\n                                             bterm [] (vterm (0, nAnon));\n                                             bterm [] (vterm (1, nAnon));\n                                             bterm [] (vterm (2, nAnon))]);\n                                       bterm []\n                                         (oterm (CApply 1)\n                                            [bterm [] (vterm (30, nNamed \"ff\"));\n                                            bterm [] (vterm (0, nAnon))]);\n                                       bterm []\n                                         (oterm (CApply 1)\n                                            [bterm [] (vterm (31, nNamed \"ff₂\"));\n                                            bterm [] (vterm (1, nAnon))])]) None) None) None)));\n                  bterm [] (vterm (0, nNamed \"T\")); bterm [] (vterm (1, nNamed \"T₂\"))]) None\n               (mkLamS (3, nNamed \"x\") (mkConstInd (mkInd \"Coq.Init.Datatypes.nat\" 0)) None\n                  (mkLamS (4, nNamed \"x₂\") (mkConstInd (mkInd \"Coq.Init.Datatypes.nat\" 0))\n                     None\n                     (mkLamS (5, nNamed \"x_R\")\n                        (oterm (CApply 2)\n                           [bterm [] (mkConst \"Coq_Init_Datatypes_nat_RR0\");\n                           bterm [] (vterm (3, nNamed \"x\"));\n                           bterm [] (vterm (4, nNamed \"x₂\"))]) None\n                        (mkLamS (3, nNamed \"x\")\n                           (oterm (CApply 1)\n                              [bterm [] (vterm (0, nNamed \"T\"));\n                              bterm [] (vterm (3, nNamed \"x\"))]) None\n                           (mkLamS (4, nNamed \"x₂\")\n                              (oterm (CApply 1)\n                                 [bterm [] (vterm (1, nNamed \"T₂\"));\n                                 bterm [] (vterm (4, nNamed \"x₂\"))]) None\n                              (mkLamS (5, nNamed \"x_R\")\n                                 (oterm (CApply 2)\n                                    [bterm []\n                                       (oterm (CApply 3)\n                                          [bterm [] (vterm (2, nNamed \"T_R\"));\n                                          bterm [] (vterm (3, nNamed \"x\"));\n                                          bterm [] (vterm (4, nNamed \"x₂\")); (* capture *)\n                                          bterm [] (vterm (5, nNamed \"x_R\"))]);\n                                    bterm [] (vterm (3, nNamed \"x\"));\n                                    bterm [] (vterm (4, nNamed \"x₂\"))]) None\n                                 (vterm (5, nNamed \"x_R\")))))))))).\n\nRun TemplateProgram (genParam [] false true \"capture\").\nPrint capture_RR.\nRun TemplateProgram (tmMkDefinitionSq \"captureFromSyn\" captureSyntax).\nRun TemplateProgram (tmMkDefinitionSq \"captureTranslate\" captureTranslateSyntax).\n(*\nIn environment\nT : nat -> Set\nT₂ : nat -> Set\nT_R : forall H H0 : nat, Coq_Init_Datatypes_nat_RR0 H H0 -> T H -> T₂ H0 -> Prop\nx : nat\nx₂ : nat\nx_R : Coq_Init_Datatypes_nat_RR0 x x₂\nx0 : T x\nx₂0 : T₂ x₂\nThe term \"x0\" has type \"T x\" while it is expected to have type \"nat\".\n*)\n\n\n\n\n\n\n\n", "meta": {"author": "aa755", "repo": "paramcoq-iff", "sha": "3ec9ce96fd5233c0a1c7e83b1dab8e526e4bcad8", "save_path": "github-repos/coq/aa755-paramcoq-iff", "path": "github-repos/coq/aa755-paramcoq-iff/paramcoq-iff-3ec9ce96fd5233c0a1c7e83b1dab8e526e4bcad8/examples/capture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.23324401026916988}}
{"text": "(** * Facts about H-VHDL Environment *)\n\nRequire Import common.CoqLib.\nRequire Import common.proofs.CoqTactics.\nRequire Import common.NatSet.\n\nRequire Import common.NatMap.\nRequire Import common.proofs.NatMapTactics.\nRequire Import common.NatSet.\n\nRequire Import hvhdl.HVhdlTypes.\nRequire Import hvhdl.Environment.\nRequire Import hvhdl.SemanticalDomains.\n\n(** ** Equivalence Relations between Elaborated Designs *)\n\n(** *** Generic Constant Set Equivalence *)\n\nDefinition EqGens (Δ Δ' : ElDesign) :=\n  forall id t v,\n    MapsTo id (Generic t v) Δ <-> MapsTo id (Generic t v) Δ'.\n\nDefinition EqGens_refl : forall (Δ : ElDesign), EqGens Δ Δ. firstorder. Defined.\nDefinition EqGens_trans : forall (Δ Δ' Δ'' : ElDesign), EqGens Δ Δ' -> EqGens Δ' Δ'' -> EqGens Δ Δ''.\n  unfold EqGens; intros; transitivity (MapsTo id (Generic t0 v) Δ'); auto.\nDefined.\nDefinition EqGens_sym : forall (Δ Δ' : ElDesign), EqGens Δ Δ' -> EqGens Δ' Δ.\n  unfold EqGens; symmetry; auto.\nDefined.\n\nAdd Parametric Relation : (ElDesign) (EqGens)\n    reflexivity proved by EqGens_refl\n    symmetry proved by EqGens_sym\n    transitivity proved by EqGens_trans\n      as EqGens_rel.           \n\n(** Enable rewriting [MapsTo id (Generic t v) Δ1] into  \n    [MapsTo id (Generic t) Δ2] if [EqGens Δ1 Δ2]. *)\n\nAdd Parametric Morphism (id : ident) (t : type) (v : value) : (MapsTo id (Generic t v)) \n    with signature (@EqGens ==> impl) as eqgens_mapsto_mor.\nProof. intros x y H; rewrite (H id t); unfold impl; auto. Qed.\n\n#[export] Hint Resolve EqGens_refl : hvhdl.\n#[export] Hint Resolve EqGens_trans : hvhdl.\n#[export] Hint Resolve EqGens_sym : hvhdl.\n\n(** *** Input Port Set Equivalence *)\n\nDefinition EqIns (Δ Δ' : ElDesign) :=\n  forall id t,\n    MapsTo id (Input t) Δ <-> MapsTo id (Input t) Δ'.\n\nDefinition EqIns_refl : forall (Δ : ElDesign), EqIns Δ Δ. firstorder. Defined.\nDefinition EqIns_trans : forall (Δ Δ' Δ'' : ElDesign), EqIns Δ Δ' -> EqIns Δ' Δ'' -> EqIns Δ Δ''.\n  unfold EqIns; intros; transitivity (MapsTo id (Input t0) Δ'); auto.\nDefined.\nDefinition EqIns_sym : forall (Δ Δ' : ElDesign), EqIns Δ Δ' -> EqIns Δ' Δ.\n  unfold EqIns; symmetry; auto.\nDefined.\n\nAdd Parametric Relation : (ElDesign) (EqIns)\n    reflexivity proved by EqIns_refl\n    symmetry proved by EqIns_sym\n    transitivity proved by EqIns_trans\n      as EqIns_rel.\n\n(** Rewrite [MapsTo id (Input t) Δ1] into  \n    [MapsTo id (Input t) Δ2] if [EqIns Δ1 Δ2]. *)\n\nAdd Parametric Morphism (id : ident) (t : type) : (MapsTo id (Input t)) \n    with signature (@EqIns ==> impl) as eqins_mapsto_in_mor.\nProof. intros x y H; rewrite (H id t); unfold impl; auto. Qed.\n\n(** *** Output Port Set Equivalence *)\n\nDefinition EqOuts (Δ Δ' : ElDesign) :=\n  forall id t,\n    MapsTo id (Output t) Δ <-> MapsTo id (Output t) Δ'.\n\nDefinition EqOuts_refl : forall (Δ : ElDesign), EqOuts Δ Δ. firstorder. Defined.\nDefinition EqOuts_trans : forall (Δ Δ' Δ'' : ElDesign), EqOuts Δ Δ' -> EqOuts Δ' Δ'' -> EqOuts Δ Δ''.\n  unfold EqOuts; intros; transitivity (MapsTo id (Output t0) Δ'); auto.\nDefined.\nDefinition EqOuts_sym : forall (Δ Δ' : ElDesign), EqOuts Δ Δ' -> EqOuts Δ' Δ.\n  unfold EqOuts; symmetry; auto.\nDefined.\n\nAdd Parametric Relation : (ElDesign) (EqOuts)\n    reflexivity proved by EqOuts_refl\n    symmetry proved by EqOuts_sym\n    transitivity proved by EqOuts_trans\n      as EqOuts_rel.\n\n(** Rewrite [MapsTo id (Output t) Δ1] into  \n    [MapsTo id (Output t) Δ2] if [EqOuts Δ1 Δ2]. *)\n\nAdd Parametric Morphism (id : ident) (t : type) : (MapsTo id (Output t)) \n    with signature (@EqOuts ==> impl) as eqouts_mapsto_out_mor.\nProof. intros x y H; rewrite (H id t); unfold impl; auto. Qed.\n\n(** *** Internal Signal Set Equivalence *)\n\nDefinition EqDecls (Δ Δ' : ElDesign) :=\n  forall id t,\n    MapsTo id (Internal t) Δ <-> MapsTo id (Internal t) Δ'.\n\nDefinition EqDecls_refl : forall (Δ : ElDesign), EqDecls Δ Δ. firstorder. Defined.\nDefinition EqDecls_trans : forall (Δ Δ' Δ'' : ElDesign), EqDecls Δ Δ' -> EqDecls Δ' Δ'' -> EqDecls Δ Δ''.\n  unfold EqDecls; intros; transitivity (MapsTo id (Internal t0) Δ'); auto.\nDefined.\nDefinition EqDecls_sym : forall (Δ Δ' : ElDesign), EqDecls Δ Δ' -> EqDecls Δ' Δ.\n  unfold EqDecls; symmetry; auto.\nDefined.\n\nAdd Parametric Relation : (ElDesign) (EqDecls)\n    reflexivity proved by EqDecls_refl\n    symmetry proved by EqDecls_sym\n    transitivity proved by EqDecls_trans\n      as EqDecls_rel.\n\n(** Enable rewriting [MapsTo id (Internal t) Δ1] into  \n    [MapsTo id (Internal t) Δ2] if [EqDecls Δ1 Δ2]. *)\n\nAdd Parametric Morphism (id : ident) (t : type) : (MapsTo id (Internal t)) \n    with signature (@EqDecls ==> impl) as eqdecls_mapsto_decl_mor.\nProof. intros x y H; rewrite (H id t); unfold impl; auto. Qed.\n\n(** *** Signal (Input, Output and Internal) Set Equivalence *)\n\nDefinition EqSigs (Δ Δ' : ElDesign) :=\n  EqIns Δ Δ' /\\ EqOuts Δ Δ' /\\ EqDecls Δ Δ'.\n\nDefinition EqSigs_refl : forall (Δ : ElDesign), EqSigs Δ Δ. firstorder. Defined.\nDefinition EqSigs_trans : forall (Δ Δ' Δ'' : ElDesign), EqSigs Δ Δ' -> EqSigs Δ' Δ'' -> EqSigs Δ Δ''.\n  unfold EqSigs; intros; decompose [and] H; decompose [and] H0.\n  split_and; transitivity Δ'; auto.\nDefined.\nDefinition EqSigs_sym : forall (Δ Δ' : ElDesign), EqSigs Δ Δ' -> EqSigs Δ' Δ.\n  unfold EqSigs; intros; decompose [and] H.\n  split_and; symmetry; auto.\nDefined.\n\nAdd Parametric Relation : (ElDesign) (EqSigs)\n    reflexivity proved by EqSigs_refl\n    symmetry proved by EqSigs_sym\n    transitivity proved by EqSigs_trans\n      as EqSigs_rel.\n\n(** Enable rewriting [MapsTo id (Internal t) Δ1] into  \n    [MapsTo id (Internal t) Δ2] if [EqSigs Δ1 Δ2]. *)\n\nAdd Parametric Morphism (id : ident) (t : type) : (MapsTo id (Internal t)) \n    with signature (@EqSigs ==> impl) as eqsigs_mapsto_decl_mor.\nProof. intros x y H; do 2 (apply proj2 in H); rewrite (H id t); unfold impl; auto. Qed.\n\n(** Enable rewriting [MapsTo id (Output t) Δ1] into  \n    [MapsTo id (Output t) Δ2] if [EqSigs Δ1 Δ2]. *)\n\nAdd Parametric Morphism (id : ident) (t : type) : (MapsTo id (Output t)) \n    with signature (@EqSigs ==> impl) as eqsigs_mapsto_out_mor.\nProof. intros x y H; apply proj2, proj1 in H. rewrite (H id t); unfold impl; auto. Qed.\n\n(** Enable rewriting [MapsTo id (Input t) Δ1] into  \n    [MapsTo id (Input t) Δ2] if [EqSigs Δ1 Δ2]. *)\n\nAdd Parametric Morphism (id : ident) (t : type) : (MapsTo id (Input t)) \n    with signature (@EqSigs ==> impl) as eqsigs_mapsto_in_mor.\nProof. intros x y H; apply proj1 in H; rewrite (H id t); unfold impl; auto. Qed.\n\n(** *** Process and Component Instance Set Equivalence *)\n\nDefinition EqPs (Δ Δ' : ElDesign) :=\n  forall id Λ,\n    MapsTo id (Process Λ) Δ <-> MapsTo id (Process Λ) Δ'.\n\nDefinition EqComps (Δ Δ' : ElDesign) :=\n  forall id Δ__c,\n    MapsTo id (Component Δ__c) Δ <-> MapsTo id (Component Δ__c) Δ'.\n\n(** ** Equivalence Relations between Design States *)\n\n(** *** Signal Store Equivalence *)\n\nDefinition EqSStore (σ σ' : DState) :=\n  forall id v,\n    MapsTo id v (sstore σ) <-> MapsTo id v (sstore σ').\n\nDefinition EqSStore_refl : forall (σ : DState), EqSStore σ σ. firstorder. Defined.\nDefinition EqSStore_trans : forall (σ σ' σ'' : DState), EqSStore σ σ' -> EqSStore σ' σ'' -> EqSStore σ σ''.\n  unfold EqSStore; intros; transitivity (MapsTo id v (sstore σ')); auto.\nDefined.\nDefinition EqSStore_sym : forall (σ σ' : DState), EqSStore σ σ' -> EqSStore σ' σ.\n  unfold EqSStore; symmetry; auto.\nDefined.\n\nAdd Parametric Relation : (DState) (EqSStore)\n    reflexivity proved by EqSStore_refl\n    symmetry proved by EqSStore_sym\n    transitivity proved by EqSStore_trans\n      as EqSStore_rel.\n\n(** Enable rewriting [MapsTo id v (sstore σ1)] into  \n    [MapsTo id v (sstore σ2)] if [EqSStore σ1 σ2]. *)\n\nAdd Parametric Morphism (id : ident) (v : value) : (fun σ => MapsTo id v (sstore σ)) \n    with signature (@EqSStore ==> impl) as eqsstore_mapsto_mor.\nProof. intros x y H; unfold EqSStore in H; erewrite H; unfold impl; eauto. Qed.\n\n(** *** Component Store Equivalence *)\n\nDefinition EqCStore (σ σ' : DState) :=\n  forall id σ__c,\n    MapsTo id σ__c (cstore σ) <-> MapsTo id σ__c (cstore σ').\n\nDefinition EqCStore_refl : forall (σ : DState), EqCStore σ σ. firstorder. Defined.\nDefinition EqCStore_trans : forall (σ σ' σ'' : DState), EqCStore σ σ' -> EqCStore σ' σ'' -> EqCStore σ σ''.\n  unfold EqCStore; intros; transitivity (MapsTo id σ__c (cstore σ')); auto.\nDefined.\nDefinition EqCStore_sym : forall (σ σ' : DState), EqCStore σ σ' -> EqCStore σ' σ.\n  unfold EqCStore; symmetry; auto.\nDefined.\n\nAdd Parametric Relation : (DState) (EqCStore)\n    reflexivity proved by EqCStore_refl\n    symmetry proved by EqCStore_sym\n    transitivity proved by EqCStore_trans\n      as EqCStore_rel.\n\n(** Enable rewriting [MapsTo id v (cstore σ1)] into  \n    [MapsTo id v (cstore σ2)] if [EqSStore σ1 σ2]. *)\n\nAdd Parametric Morphism (id : ident) (σ__c : DState) : (fun σ => MapsTo id σ__c (cstore σ)) \n    with signature (@EqCStore ==> impl) as eqcstore_mapsto_mor.\nProof. intros x y H; unfold EqCStore in H; erewrite H; unfold impl; eauto. Qed.\n\n(** *** Design State Equivalence *)\n\nDefinition EqDState (σ σ' : DState) :=\n  EqSStore σ σ' /\\ EqCStore σ σ'.\n\nDefinition EqDState_refl : forall (σ : DState), EqDState σ σ. firstorder. Defined.\nDefinition EqDState_trans : forall (σ σ' σ'' : DState), EqDState σ σ' -> EqDState σ' σ'' -> EqDState σ σ''.\n  unfold EqDState; intros; decompose [and] H; decompose [and] H0.\n  split_and; transitivity σ'; auto.\nDefined.\nDefinition EqDState_sym : forall (σ σ' : DState), EqDState σ σ' -> EqDState σ' σ.\n  unfold EqDState; intros; decompose [and] H.\n  split_and; symmetry; auto.\nDefined.\n\nAdd Parametric Relation : (DState) (EqDState)\n    reflexivity proved by EqDState_refl\n    symmetry proved by EqDState_sym\n    transitivity proved by EqDState_trans\n      as EqDState_rel.\n\n(** Enable rewriting [MapsTo id v (sstore σ1)] into  \n    [MapsTo id v (sstore σ2)] if [EqDState σ1 σ2]. *)\n\nAdd Parametric Morphism (id : ident) (v : value) : (fun σ => MapsTo id v (sstore σ)) \n    with signature (@EqDState ==> impl) as eqdstate_mapsto_sstore_mor.\nProof. intros x y H; apply proj1 in H; intro; pattern y; rewrite <- H; auto. Qed.\n\n(** Enable rewriting [MapsTo id σ__c (cstore σ1)] into  \n    [MapsTo id σ__c (cstore σ2)] if [EqDState σ1 σ2]. *)\n\nAdd Parametric Morphism (id : ident) (σ__c : DState) : (fun σ => MapsTo id σ__c (cstore σ)) \n    with signature (@EqDState ==> impl) as eqdstate_mapsto_cstore_mor.\nProof. intros x y H; apply proj2 in H; intro; pattern y; rewrite <- H; auto. Qed.\n\n(** ** Facts about [EqualDom] equivalence *)\n\nLemma EqualDom_add_1 :\n  forall {A : Type} {k} {e : A} {m},\n    NatMap.In k m ->\n    EqualDom m (NatMap.add k e m).\nProof.\n  split; intros.\n  destruct (Nat.eq_dec k k0); try subst.\n  exists e; apply NatMap.add_1; auto.\n  rewrite add_in_iff; right; auto.\n  destruct (Nat.eq_dec k k0); try subst; auto.\n  erewrite add_in_iff in *; firstorder.\nQed.\n\n(** ** Facts about [merge_natmap] *)\n\n(* Ltac simpl_merge_map := *)\n(*   unfold merge_natmap; *)\n(*   unfold fold; *)\n(*   unfold Raw.fold; *)\n(*   unfold flip; *)\n(*   try (progress simpl). *)\n\n(* Lemma merge_natmap_id_notin_set : *)\n(*   forall {A : Type} (s : list ident) (m1 m2 : IdMap A) (k : ident) (a : A), *)\n(*     let f := fun m k1 => *)\n(*                match find k1 m1 with *)\n(*                | Some a1 => NatMap.add k1 a1 m *)\n(*                | _ => m *)\n(*                end *)\n(*     in *)\n(*     ~InA Logic.eq k s -> *)\n(*     MapsTo k a m2 -> *)\n(*     MapsTo k a (fold_left f s m2). *)\n(* Proof. *)\n(*   induction s. *)\n\n(*   (* BASE CASE *) *)\n(*   - simpl; auto. *)\n\n(*   (* IND. CASE *) *)\n(*   - simpl; intros. *)\n(*     eapply IHs; eauto. *)\n(*     destruct (find (elt:=A) a m1); auto. *)\n(*     eapply NatMap.add_2; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_natmap_id_notin_set_2 : *)\n(*   forall {A : Type} {s m1 m2 k} {x y : A}, *)\n(*     let f := fun m k1 => match find k1 m1 with *)\n(*                          | Some a1 => NatMap.add k1 a1 m *)\n(*                          | _ => m *)\n(*                          end *)\n(*     in *)\n(*     ~InA Logic.eq k s -> *)\n(*     MapsTo k x m2 -> *)\n(*     MapsTo k y (fold_left f s m2) -> *)\n(*     x = y. *)\n(* Proof. *)\n(*   induction s. *)\n\n(*   (* BASE CASE *) *)\n(*   - simpl; intros; eapply MapsTo_fun; eauto. *)\n\n(*   (* IND. CASE *) *)\n(*   - simpl; intros. *)\n(*     eapply IHs with (m2 := match find (elt:=A) a m1 with *)\n(*             | Some a1 => NatMap.add a a1 m2 *)\n(*             | None => m2 *)\n(*                            end); *)\n(*       eauto. *)\n(*     destruct (find (elt:=A) a m1); auto. *)\n(*     eapply NatMap.add_2; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_natmap_notin_m1 : *)\n(*   forall {A : Type} {s m1 m2 k} {a : A}, *)\n(*     let f := fun m k1 => match find k1 m1 with *)\n(*                          | Some a1 => NatMap.add k1 a1 m *)\n(*                          | _ => m *)\n(*                          end *)\n(*     in *)\n(*     ~NatMap.In k m1 -> *)\n(*     MapsTo k a (fold_left f s m2) -> *)\n(*     NatMap.In k m2. *)\n(* Proof. *)\n(*   induction s; simpl; intros. *)\n(*   (* BASE CASE *) *)\n(*   - exists a; auto. *)\n(*   (* IND. CASE *) *)\n(*   - case_eq (find (elt:=A) a m1). *)\n(*     (* find = Some x *) *)\n(*     intros x e. *)\n(*     erewrite <- add_neq_in_iff with (x := a) (e := x); eauto. *)\n(*     rewrite e in *; eapply IHs; eauto. *)\n(*     intros e1; try subst. *)\n(*     match goal with *)\n(*     | [ H: ~NatMap.In _ _ |- _ ] => *)\n(*       apply H; exists x; eapply find_2; eauto *)\n(*     end.     *)\n(*     (* find = None *) *)\n(*     intros e; rewrite e in *; eapply IHs; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_natmap_EqualDom_1 : *)\n(*   forall {A: Type} {s m1 m2 m3}, *)\n(*     EqualDom m3 m1 -> *)\n(*     EqualDom m3 m2 -> *)\n(*     EqualDom m1 (@merge_natmap A s m2 m3). *)\n(* Proof. *)\n(*   destruct s; induction this0. *)\n(*   (* BASE CASE *) *)\n(*   - simpl_merge_map; intros; firstorder.  *)\n(*   (* IND. CASE *) *)\n(*   - simpl_merge_map; intros; case_eq (find (elt:=A) a m2); intros; eapply IHthis0; eauto. *)\n(*     rewrite <- H; symmetry; eapply EqualDom_add_1; eauto. *)\n(*     rewrite (H0 a); exists a0; eapply find_2; eauto. *)\n(*     rewrite <- H0; symmetry; eapply EqualDom_add_1; eauto. *)\n(*     rewrite (H0 a); exists a0; eapply find_2; eauto. *)\n(*     Unshelve. *)\n(*     inversion_clear is_ok0; auto. *)\n(*     inversion_clear is_ok0; auto. *)\n(* Qed. *)\n\n(* Lemma merge_natmap_compl_1 : *)\n(*   forall {A : Type} s m1 m2 k (a : A), *)\n(*     NatSet.In k s -> *)\n(*     MapsTo k a m1 -> *)\n(*     MapsTo k a (merge_natmap s m1 m2). *)\n(* Proof. *)\n(*   destruct s; induction this0. *)\n(*   (* BASE CASE *) *)\n(*   - inversion 1. *)\n(*   (* IND. CASE *) *)\n(*   - intros; unfold merge_natmap; unfold fold; unfold Raw.fold; unfold flip. *)\n(*     simpl. *)\n(*     inversion_clear H; try subst. *)\n(*     (* k = a *) *)\n(*     + erewrite find_1; eauto. *)\n(*       eapply merge_natmap_id_notin_set; eauto. *)\n(*       inversion_clear is_ok0; auto. *)\n(*       eapply NatMap.add_1; eauto. *)\n(*     (* use ind. hyp. *) *)\n(*     + eapply IHthis0; eauto. *)\n(*       Unshelve. *)\n(*       inversion_clear is_ok0; auto. *)\n(* Qed. *)\n\n(* Lemma merge_natmap_compl_2 : *)\n(*   forall {A : Type} s m1 m2 k (a : A), *)\n(*     ~NatSet.In k s -> *)\n(*     MapsTo k a m2 -> *)\n(*     MapsTo k a (merge_natmap s m1 m2). *)\n(* Proof. *)\n(*   unfold merge_natmap; unfold fold; unfold Raw.fold; unfold flip. *)\n(*   intros; eapply merge_natmap_id_notin_set; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_natmap_sound_1 : *)\n(*   forall {A : Type} s m1 m2 k (a : A), *)\n(*     NatSet.In k s -> *)\n(*     EqualDom m1 m2 -> *)\n(*     MapsTo k a (merge_natmap s m1 m2) -> *)\n(*     MapsTo k a m1. *)\n(* Proof. *)\n(*   destruct s; induction this0. *)\n(*   (* BASE CASE *) *)\n(*   - inversion 1. *)\n(*   (* IND. CASE *) *)\n(*   - simpl_merge_map; inversion_clear 1; try subst. *)\n(*     (* CASE k = a *) *)\n(*     + case_eq (find (elt:=A) a m1).  *)\n(*       (* find = Some a *) *)\n(*       intros x e EqualDom_m1m2 MapsTo_foldl. *)\n(*       erewrite <- @merge_natmap_id_notin_set_2 with (k := a) (x := x) (y := a0); eauto; *)\n(*         [ eapply find_2; eauto | inversion is_ok0; auto | eapply NatMap.add_1; eauto]. *)\n(*       (* find = None *) *)\n(*       intros e EqualDom_m1m2 MapsTo_foldl. *)\n(*       assert (NatMap.In a m2) by (eapply merge_natmap_notin_m1; eauto; *)\n(*                                   erewrite not_find_in_iff; eauto). *)\n(*       assert (~NatMap.In a m1) by (erewrite not_find_in_iff; eauto). *)\n(*       assert (NatMap.In a m1) by (unfold EqualDom in EqualDom_m1m2; erewrite EqualDom_m1m2; eauto). *)\n(*       contradiction. *)\n\n(*     (* CASE use ind. hyp. *) *)\n(*     + intros EqualDom_m1m2 MapsTo_foldl; *)\n(*         eapply IHthis0 with (m2 := match find (elt:=A) a m1 with *)\n(*                                    | Some a1 => NatMap.add a a1 m2 *)\n(*                                    | None => m2 end); *)\n(*         eauto. *)\n(*       case_eq (find (elt:=A) a m1); auto. *)\n(*       intros x e; split; erewrite add_in_iff. *)\n(*       right; unfold EqualDom in EqualDom_m1m2; erewrite <- EqualDom_m1m2; assumption. *)\n(*       inversion_clear 1; [ try subst | unfold EqualDom in EqualDom_m1m2; erewrite EqualDom_m1m2; assumption]. *)\n(*       exists x; eapply find_2; assumption. *)\n(*       Unshelve. inversion_clear is_ok0; auto. *)\n(* Qed. *)\n\n(* Lemma merge_natmap_sound_2 : *)\n(*   forall {A : Type} s m1 m2 k (a : A), *)\n(*     ~NatSet.In k s -> *)\n(*     EqualDom m1 m2 -> *)\n(*     MapsTo k a (merge_natmap s m1 m2) -> *)\n(*     MapsTo k a m2. *)\n(* Proof. *)\n(*   destruct s; induction this0. *)\n(*   (* BASE CASE *) *)\n(*   - simpl_merge_map; auto. *)\n(*   (* IND. CASE *) *)\n(*   - simpl_merge_map; do 5 intro; intros EqualDom_m1m2; intros. *)\n(*     case_eq (find (elt:=A) a m1).  *)\n(*     (* find = Some a *) *)\n(*     intros x e; rewrite e in *. *)\n(*     eapply NatMap.add_3 with (x := a) (e' := x). *)\n(*     intro; try subst; apply H; auto with set. *)\n(*     eapply IHthis0; eauto. *)\n(*     intro; apply H; eapply InA_cons_tl; auto. *)\n(*     erewrite EqualDom_m1m2. *)\n(*     eapply EqualDom_add_1. *)\n(*     unfold  EqualDom in EqualDom_m1m2. *)\n(*     erewrite <- EqualDom_m1m2. *)\n(*     exists x; eapply find_2; eauto. *)\n(*     (* find = None *) *)\n(*     intros e; rewrite e in *. *)\n(*     eapply IHthis0; eauto. *)\n(*     intro; apply H; eapply InA_cons_tl; auto. *)\n(*     Unshelve. inversion_clear is_ok0; auto. *)\n(*     inversion_clear is_ok0; auto. *)\n(* Qed. *)\n\n(* Lemma merge_sstore_compl_1 : *)\n(*   forall {id v σ__o σ σ'}, *)\n(*     In id (events σ) -> *)\n(*     MapsTo id v (sstore σ) -> *)\n(*     MapsTo id v (merge_sstore σ__o σ σ'). *)\n(* Proof. *)\n(*   unfold merge_sstore; intros. *)\n(*   eapply merge_natmap_compl_1; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_sstore_compl_2 : *)\n(*   forall {id v σ__o σ σ'}, *)\n(*     ~In id (events σ) -> *)\n(*     In id (events σ') -> *)\n(*     MapsTo id v (sstore σ') -> *)\n(*     MapsTo id v (merge_sstore σ__o σ σ'). *)\n(* Proof. *)\n(*   unfold merge_sstore; intros. *)\n(*   eapply merge_natmap_compl_2; eauto. *)\n(*   eapply merge_natmap_compl_1; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_sstore_compl_3 : *)\n(*   forall {id v σ__o σ σ'}, *)\n(*     ~In id (events σ U events σ') -> *)\n(*     MapsTo id v (sstore σ__o) -> *)\n(*     MapsTo id v (merge_sstore σ__o σ σ'). *)\n(* Proof. *)\n(*   intros; eapply merge_natmap_compl_2; eauto. *)\n(*   eapply proj1; eapply not_in_union_2; eauto. *)\n(*   eapply merge_natmap_compl_2; eauto. *)\n(*   eapply proj2; eapply not_in_union_2; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_sstore_sound_1 : *)\n(*   forall {id v σ__o σ σ'}, *)\n(*     EqualDom (sstore σ__o) (sstore σ) -> *)\n(*     EqualDom (sstore σ__o) (sstore σ') -> *)\n(*     In id (events σ) -> *)\n(*     MapsTo id v (merge_sstore σ__o σ σ') -> *)\n(*     MapsTo id v (sstore σ). *)\n(* Proof. *)\n(*   intros; eapply merge_natmap_sound_1; eauto. *)\n(*   eapply merge_natmap_EqualDom_1; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_sstore_sound_2 : *)\n(*   forall {id v σ__o σ σ'}, *)\n(*     EqualDom (sstore σ__o) (sstore σ) -> *)\n(*     EqualDom (sstore σ__o) (sstore σ') -> *)\n(*     In id (events σ') -> *)\n(*     ~In id (events σ) -> *)\n(*     MapsTo id v (merge_sstore σ__o σ σ') -> *)\n(*     MapsTo id v (sstore σ'). *)\n(* Proof. *)\n(*   intros; eapply merge_natmap_sound_1 with (m2 := (sstore σ__o)); eauto. *)\n(*   symmetry; auto. *)\n(*   eapply merge_natmap_sound_2; eauto. *)\n(*   eapply merge_natmap_EqualDom_1; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_sstore_sound_3 : *)\n(*   forall {id v σ__o σ σ'}, *)\n(*     EqualDom (sstore σ__o) (sstore σ) -> *)\n(*     EqualDom (sstore σ__o) (sstore σ') -> *)\n(*     ~In id (events σ U events σ') -> *)\n(*     MapsTo id v (merge_sstore σ__o σ σ') -> *)\n(*     MapsTo id v (sstore σ__o). *)\n(* Proof. *)\n(*   unfold merge_sstore; intros. *)\n(*   eapply merge_natmap_sound_2 with (s := events σ') (m1 := sstore σ'); eauto. *)\n(*   eapply not_in_union_2; eauto. *)\n(*   symmetry; assumption. *)\n(*   eapply merge_natmap_sound_2 with (s := events σ) (m1 := sstore σ); eauto. *)\n(*   eapply not_in_union_2 with (s := events σ) (s' := events σ'); eauto. *)\n(*   eapply merge_natmap_EqualDom_1; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_cstore_compl_1 : *)\n(*   forall {id v σ__o σ σ'}, *)\n(*     In id (events σ) -> *)\n(*     MapsTo id v (cstore σ) -> *)\n(*     MapsTo id v (merge_cstore σ__o σ σ'). *)\n(* Proof. *)\n(*   intros; eapply merge_natmap_compl_1; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_cstore_compl_2 : *)\n(*   forall {id v σ__o σ σ'}, *)\n(*     ~In id (events σ) -> *)\n(*     In id (events σ') -> *)\n(*     MapsTo id v (cstore σ') -> *)\n(*     MapsTo id v (merge_cstore σ__o σ σ'). *)\n(* Proof. *)\n(*   intros; eapply merge_natmap_compl_2; eauto. *)\n(*   eapply merge_natmap_compl_1; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_cstore_compl_3 : *)\n(*   forall {id v σ__o σ σ'}, *)\n(*     ~In id (events σ U events σ') -> *)\n(*     MapsTo id v (cstore σ__o) -> *)\n(*     MapsTo id v (merge_cstore σ__o σ σ'). *)\n(* Proof. *)\n(*   intros; eapply merge_natmap_compl_2; eauto. *)\n(*   eapply proj1; eapply not_in_union_2; eauto. *)\n(*   eapply merge_natmap_compl_2; eauto. *)\n(*   eapply proj2; eapply not_in_union_2; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_cstore_sound_1 : *)\n(*   forall {id v σ__o σ σ'}, *)\n(*     EqualDom (cstore σ__o) (cstore σ) -> *)\n(*     EqualDom (cstore σ__o) (cstore σ') -> *)\n(*     In id (events σ) -> *)\n(*     MapsTo id v (merge_cstore σ__o σ σ') -> *)\n(*     MapsTo id v (cstore σ). *)\n(* Proof. *)\n(*   intros; eapply merge_natmap_sound_1; eauto. *)\n(*   eapply merge_natmap_EqualDom_1; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_cstore_sound_2 : *)\n(*   forall {id v σ__o σ σ'}, *)\n(*     EqualDom (cstore σ__o) (cstore σ) -> *)\n(*     EqualDom (cstore σ__o) (cstore σ') -> *)\n(*     In id (events σ') -> *)\n(*     ~In id (events σ) -> *)\n(*     MapsTo id v (merge_cstore σ__o σ σ') -> *)\n(*     MapsTo id v (cstore σ'). *)\n(* Proof. *)\n(*   unfold merge_sstore; intros. *)\n(*   eapply merge_natmap_sound_1 with (m2 := (cstore σ__o)); eauto. *)\n(*   symmetry; auto. *)\n(*   eapply merge_natmap_sound_2; eauto. *)\n(*   eapply merge_natmap_EqualDom_1; eauto. *)\n(* Qed. *)\n\n(* Lemma merge_cstore_sound_3 : *)\n(*   forall {id v σ__o σ σ'}, *)\n(*     EqualDom (cstore σ__o) (cstore σ) -> *)\n(*     EqualDom (cstore σ__o) (cstore σ') -> *)\n(*     ~In id (events σ U events σ') -> *)\n(*     MapsTo id v (merge_cstore σ__o σ σ') -> *)\n(*     MapsTo id v (cstore σ__o). *)\n(* Proof. *)\n(*   unfold merge_sstore; intros. *)\n(*   eapply merge_natmap_sound_2 with (s := events σ') (m1 := cstore σ'); eauto. *)\n(*   eapply not_in_union_2; eauto. *)\n(*   symmetry; assumption. *)\n(*   eapply merge_natmap_sound_2 with (s := events σ) (m1 := cstore σ); eauto. *)\n(*   eapply not_in_union_2 with (s := events σ) (s' := events σ'); eauto. *)\n(*   eapply merge_natmap_EqualDom_1; eauto. *)\n(* Qed. *)\n\n(* (** ** Facts about the [IsMergedDState] relation *) *)\n\n(* Ltac decompose_IMDS := *)\n(*   match goal with *)\n(*   | [ H: IsMergedDState _ _ _ _ |- _ ] => *)\n(*     unfold IsMergedDState in H; decompose [and] H; clear H *)\n(*   end. *)\n\n(* Lemma IsMergedDState_comm : *)\n(*   forall {σ__o σ σ' σ__m}, *)\n(*     IsMergedDState σ__o σ σ' σ__m <-> *)\n(*     IsMergedDState σ__o σ' σ σ__m. *)\n(* Proof. *)\n(*   split; intros; decompose_IMDS; *)\n(*     let rec solve_imds := *)\n(*         match goal with *)\n(*         | |- IsMergedDState _ _ _ _ => split; solve_imds *)\n(*         | |- _ /\\ _ => split; [solve_imds | solve_imds] *)\n(*         | |- _ -> _ -> ~NatSet.In _ (_ U _) -> _ <-> _ => *)\n(*           intros; *)\n(*             match goal with *)\n(*             | [ H: _ -> _ -> ~NatSet.In _ _ -> _ <-> MapsTo _ _ (?f _), H': ~NatSet.In _ _ |- _ <-> MapsTo _ _ (?f _) ] => *)\n(*               apply H; auto; do 1 intro; apply H'; *)\n(*                 match goal with *)\n(*                 | [ H'': NatSet.In _ (_ U _) |- _ ] => *)\n(*                   rewrite union_spec in H''; inversion H''; rewrite union_spec; [right; assumption | left; assumption] *)\n(*                 end *)\n(*             end *)\n(*         | |- Equal _ (events ?σ U events ?σ') => *)\n(*           transitivity (events σ' U events σ); auto with set *)\n(*         | _ => firstorder *)\n(*         end in solve_imds. *)\n(* Qed. *)\n\n(* Lemma IsMergedDState_ex : *)\n(*   forall {σ__o σ σ'}, *)\n(*     EqualDom (sstore σ__o) (sstore σ) -> *)\n(*     EqualDom (sstore σ__o) (sstore σ') -> *)\n(*     EqualDom (cstore σ__o) (cstore σ) -> *)\n(*     EqualDom (cstore σ__o) (cstore σ') -> *)\n(*     Equal (inter (events σ) (events σ')) {[]} ->  *)\n(*     exists σ__m, IsMergedDState σ__o σ σ' σ__m. *)\n(* Proof. *)\n(*   unfold IsMergedDState; intros. *)\n(*   exists (MkDState (merge_sstore σ__o σ σ') (merge_cstore σ__o σ σ') (events σ U events σ')). *)\n(*   simpl; split_and; (auto || (try reflexivity)). *)\n(*   - eapply merge_natmap_EqualDom_1; symmetry; *)\n(*       eapply merge_natmap_EqualDom_1; (eauto || reflexivity). *)\n(*   - eapply merge_natmap_EqualDom_1; symmetry; *)\n(*       eapply merge_natmap_EqualDom_1; (eauto || reflexivity). *)\n(*   - split; [eapply merge_sstore_compl_1; eauto | eapply merge_sstore_sound_1; eauto]. *)\n(*   - split; [ eapply merge_sstore_compl_2; eauto; eapply inter_empty_2; eauto *)\n(*            | eapply merge_sstore_sound_2; eauto; eapply inter_empty_2; eauto]. *)\n(*   - split; [ eapply merge_sstore_compl_3; eauto | eapply merge_sstore_sound_3; eauto]. *)\n(*   - split; [ eapply merge_cstore_compl_1; eauto | eapply merge_cstore_sound_1; eauto]. *)\n(*   - split; [ eapply merge_cstore_compl_2; eauto; eapply inter_empty_2; eauto *)\n(*            | eapply merge_cstore_sound_2; eauto; eapply inter_empty_2; eauto ]. *)\n(*   - split; [ eapply merge_cstore_compl_3; eauto | eapply merge_cstore_sound_3; eauto ]. *)\n(* Qed. *)\n\n(* Lemma IsMergedDState_assoc_1 : *)\n(*   forall {σ σ0 σ1 σ2 σ12 σ01 σ012}, *)\n(*     IsMergedDState σ σ1 σ2 σ12 -> *)\n(*     IsMergedDState σ σ0 σ12 σ012 -> *)\n(*     IsMergedDState σ σ0 σ1 σ01 -> *)\n(*     IsMergedDState σ σ01 σ2 σ012. *)\n(* Proof. *)\n(*   intros; *)\n(*     do 3 decompose_IMDS; *)\n(*     let rec solve_imds := *)\n(*         match goal with *)\n(*         | |- IsMergedDState _ _ _ _ => split; solve_imds *)\n(*         | |- _ /\\ _ => split; [solve_imds | solve_imds] *)\n(*         | |- Equal _ (events ?σ U events ?σ') =>  *)\n(*           match goal with *)\n(*           | [ H: Equal ?ev012 (_ U ?ev12), H': Equal ?ev01 _, H'': Equal ?ev12 _ *)\n(*               |- Equal ?ev012 (?ev01 U _) ] => *)\n(*             rewrite H; rewrite H'; rewrite H''; auto with set *)\n(*           end *)\n(*         | _ => auto *)\n(*         end in solve_imds. *)\n\n(*         (* [∀ id ∈ (events σ01) -> (sstore σ01) (id) = (sstore σ012) (id)] *) *)\n(*         - intros; *)\n(*             match goal with *)\n(*             | [ H: Equal (events ?σ) (_ U _), H': NatSet.In _ (_ ?σ) |- MapsTo _ _ (_ ?σ) <-> _ ] => *)\n(*               rewrite H, union_spec in H'; inversion H' *)\n(*             end. *)\n\n(*           (* CASE [id ∈ (events σ0)] *) *)\n(*           transitivity (MapsTo id v (sstore σ0)); rw_mapsto. *)\n          \n(*           (* CASE [id ∈ (events σ1) ] *) *)\n(*           transitivity (MapsTo id v (sstore σ1)); [rw_mapsto | auto]. *)\n(*           transitivity (MapsTo id v (sstore σ12)); rw_mapsto; *)\n(*             match goal with *)\n(*             | [ H: Equal (events ?σ12) _ |- NatSet.In _ (events ?σ12) ] => *)\n(*               rewrite H; auto with set *)\n(*             end. *)\n\n(*         (* [∀ id ∈ (events σ2) -> (sstore σ2) (id) = (sstore σ012) (id)] *) *)\n(*         - intros; *)\n(*             transitivity (MapsTo id v (sstore σ12)); rw_mapsto; *)\n(*               match goal with *)\n(*               | [ H: Equal (events ?σ12) _ |- NatSet.In _ (events ?σ12) ] => *)\n(*                 rewrite H; auto with set *)\n(*               end. *)\n\n(*         (* [∀ id ∉ (events σ01) U (events σ2) -> (sstore σ) (id) = (sstore σ012) (id)] *) *)\n(*         - intros id v; intros; rw_mapsto. *)\n(*           match goal with *)\n(*           | [ H: Equal (events ?σ12) _, H': Equal (events ?σ01) _, H'': ~NatSet.In _ (events ?σ01 U _) *)\n(*               |- ~NatSet.In _ (_ U events ?σ12) ] => *)\n(*             rewrite H' in H''; rewrite H; erewrite <- union_assoc; eauto *)\n(*           end. *)\n\n(*         (* [∀ id ∈ (events σ01) -> (cstore σ01) (id) = (cstore σ012) (id)] *) *)\n(*         - intros id v; intros; *)\n(*             match goal with *)\n(*             | [ H: Equal (events ?σ) (_ U _), H': NatSet.In _ (_ ?σ) |- MapsTo _ _ (_ ?σ) <-> _ ] => *)\n(*               rewrite H, union_spec in H'; inversion H' *)\n(*             end. *)\n\n(*           (* CASE [id ∈ (events σ0)] *) *)\n(*           transitivity (MapsTo id v (cstore σ0)); rw_mapsto. *)\n          \n(*           (* CASE [id ∈ (events σ1) ] *) *)\n(*           transitivity (MapsTo id v (cstore σ1)); [rw_mapsto | auto]. *)\n(*           transitivity (MapsTo id v (cstore σ12)); rw_mapsto; *)\n(*             match goal with *)\n(*             | [ H: Equal (events ?σ12) _ |- NatSet.In _ (events ?σ12) ] => *)\n(*               rewrite H; auto with set *)\n(*             end. *)\n\n(*         (* [∀ id ∈ (events σ2) -> (cstore σ2) (id) = (cstore σ012) (id)] *) *)\n(*         - intros id v; intros; *)\n(*             transitivity (MapsTo id v (cstore σ12)); rw_mapsto; *)\n(*               match goal with *)\n(*               | [ H: Equal (events ?σ12) _ |- NatSet.In _ (events ?σ12) ] => *)\n(*                 rewrite H; auto with set *)\n(*               end. *)\n\n(*         (* [∀ id ∉ (events σ01) U (events σ2) -> (cstore σ) (id) = (cstore σ012) (id)] *) *)\n(*         - intros id v; intros; rw_mapsto. *)\n(*           match goal with *)\n(*           | [ H: Equal (events ?σ12) _, H': Equal (events ?σ01) _, H'': ~NatSet.In _ (events ?σ01 U _) *)\n(*               |- ~NatSet.In _ (_ U events ?σ12) ] => *)\n(*             rewrite H' in H''; rewrite H; erewrite <- union_assoc; eauto *)\n(*           end. *)\n(* Qed. *)\n\n(* Lemma IsMergedDState_assoc_2 : *)\n(*   forall {σ σ0 σ1 σ2 σ12 σ01 σ012}, *)\n(*     IsMergedDState σ σ0 σ1 σ01 -> *)\n(*     IsMergedDState σ σ01 σ2 σ012 -> *)\n(*     IsMergedDState σ σ1 σ2 σ12 -> *)\n(*     IsMergedDState σ σ0 σ12 σ012. *)\n(* Proof. *)\n(*   intros; *)\n(*     do 3 decompose_IMDS; *)\n(*     let rec solve_imds := *)\n(*         match goal with *)\n(*         | |- IsMergedDState _ _ _ _ => split; solve_imds *)\n(*         | |- _ /\\ _ => split; [solve_imds | solve_imds] *)\n(*         | |- Equal _ (events ?σ U events ?σ') => *)\n(*           match goal with *)\n(*           | [ H: Equal ?ev012 (?ev01 U _), H': Equal ?ev01 _, H'': Equal ?ev12 _ *)\n(*               |- Equal ?ev012 (_ U ?ev12) ] => *)\n(*             rewrite H; rewrite H'; rewrite H''; auto with set *)\n(*           end *)\n(*         | _ => auto *)\n(*         end in solve_imds. *)\n\n(*         (* [∀ id ∈ (events σ0) -> (sstore σ0) (id) = (sstore σ012) (id)] *) *)\n(*         - intros; *)\n(*             transitivity (MapsTo id v (sstore σ01)); rw_mapsto; *)\n(*               match goal with *)\n(*               | [ H: Equal (events ?σ01) _ |- NatSet.In _ (events ?σ01) ] => *)\n(*                 rewrite H; auto with set *)\n(*               end. *)\n        \n(*         (* [∀ id ∈ (events σ12) -> (sstore σ12) (id) = (sstore σ012) (id)] *) *)\n(*         - intros; *)\n(*           match goal with *)\n(*           | [ H: Equal (events ?σ) (_ U _), H': NatSet.In _ (_ ?σ) |- MapsTo _ _ (_ ?σ) <-> _ ] => *)\n(*             rewrite H, union_spec in H'; inversion H' *)\n(*           end. *)\n\n(*           (* CASE [id ∈ (events σ1)] *) *)\n(*           transitivity (MapsTo id v (sstore σ1)); [ rw_mapsto | auto]. *)\n(*           transitivity (MapsTo id v (sstore σ01)); rw_mapsto; *)\n(*             match goal with *)\n(*             | [ H: Equal (events ?σ12) _ |- NatSet.In _ (events ?σ12) ] => *)\n(*               rewrite H; auto with set *)\n(*             end. *)\n          \n(*           (* CASE [id ∈ (events σ2) ] *) *)\n(*           transitivity (MapsTo id v (sstore σ2)); rw_mapsto. *)\n          \n(*         (* [∀ id ∉ (events σ0) U (events σ12) -> (sstore σ) (id) = (sstore σ012) (id)] *) *)\n(*         - intros id v; intros; rw_mapsto. *)\n(*           match goal with *)\n(*           | [ H: Equal (events ?σ01) _, H': Equal (events ?σ12) _, H'': ~NatSet.In _ (_ U events ?σ12) *)\n(*               |- ~NatSet.In _ (events ?σ01 U _) ] => *)\n(*             rewrite H' in H''; rewrite H; erewrite union_assoc; eauto *)\n(*           end. *)\n\n(*         (* [∀ id ∈ (events σ0) -> (cstore σ0) (id) = (cstore σ012) (id)] *) *)\n(*         - intros id v; intros; *)\n(*             transitivity (MapsTo id v (cstore σ01)); rw_mapsto; *)\n(*               match goal with *)\n(*               | [ H: Equal (events ?σ01) _ |- NatSet.In _ (events ?σ01) ] => *)\n(*                 rewrite H; auto with set *)\n(*               end. *)\n          \n(*         (* [∀ id ∈ (events σ12) -> (cstore σ12) (id) = (cstore σ012) (id)] *) *)\n(*         - intros id v; intros; *)\n(*             match goal with *)\n(*             | [ H: Equal (events ?σ) (_ U _), H': NatSet.In _ (_ ?σ) |- MapsTo _ _ (_ ?σ) <-> _ ] => *)\n(*               rewrite H, union_spec in H'; inversion H' *)\n(*             end. *)\n\n(*           (* CASE [id ∈ (events σ1)] *) *)\n(*           transitivity (MapsTo id v (cstore σ1)); [ rw_mapsto | auto]. *)\n(*           transitivity (MapsTo id v (cstore σ01)); rw_mapsto; *)\n(*             match goal with *)\n(*             | [ H: Equal (events ?σ12) _ |- NatSet.In _ (events ?σ12) ] => *)\n(*               rewrite H; auto with set *)\n(*             end. *)\n          \n(*           (* CASE [id ∈ (events σ2) ] *) *)\n(*           transitivity (MapsTo id v (cstore σ2)); rw_mapsto. *)\n          \n(*         (* [∀ id ∉ (events σ0) U (events σ12) -> (cstore σ) (id) = (cstore σ012) (id)] *) *)\n(*         - intros id v; intros; rw_mapsto. *)\n(*           match goal with *)\n(*           | [ H: Equal (events ?σ01) _, H': Equal (events ?σ12) _, H'': ~NatSet.In _ (_ U events ?σ12) *)\n(*               |- ~NatSet.In _ (events ?σ01 U _) ] => *)\n(*             rewrite H' in H''; rewrite H; erewrite union_assoc; eauto *)\n(*           end. *)\n(* Qed. *)\n\n", "meta": {"author": "viampietro", "repo": "ver-hilecop", "sha": "cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4", "save_path": "github-repos/coq/viampietro-ver-hilecop", "path": "github-repos/coq/viampietro-ver-hilecop/ver-hilecop-cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4/hvhdl/proofs/EnvironmentFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.2331992313161927}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\nRequire Import omega.Omega.\nRequire Import Setoid.\nRequire Import ZArith.\n\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith. \n\nLocal Open Scope struct_scope.\n\nRequire Import FinProof.CommonProofs.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolClass.\nRequire Import depoolContract.SolidityNotations.\n\nRequire Import depoolContract.DePoolFunc.\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\n\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\nRequire Import depoolContract.Lib.CommonCommon.\nRequire Import depoolContract.Lib.CommonStateProofs.\n(* Require Import depoolContract.Lib.tvmFunctionsProofs. *)\n\nImport DePoolSpec.LedgerClass.SolidityNotations. \n\nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope solidity_scope.\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\n\nSet Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100.\n \n \n \n(* function getProxy(uint64 roundId) internal view inline returns (address) {\n        return m_proxies[roundId % 2];\n    } *) \n(* Definition ProxyBase_Ф_getProxy ( Л_roundId : XInteger64 ) : LedgerT XAddress := \n        ↑3 D2! ProxyBase_ι_m_proxies [[  $ Л_roundId !% $xInt2 ]].\n\n*)\n\n Lemma ProxyBase_Ф_getProxy_exec : forall ( Л_roundId : XInteger64 ) (l: Ledger) , \n \t exec_state (ProxyBase_Ф_getProxy Л_roundId ) l = l .  \n Proof. \n   intros. unfold ProxyBase_Ф_getProxy.\n   compute. destructIf; auto; destruct l ; auto.\nQed. \n\nLemma ProxyBase_Ф_getProxy_eval : forall ( Л_roundId : XInteger64 ) (l: Ledger) , \n    eval_state (ProxyBase_Ф_getProxy Л_roundId) l = \n       ( eval_state ( ↑3 ε ProxyBase_ι_m_proxies ) l ) [ xIntMod Л_roundId 2 ] .\nProof. \n   intros. \n   compute; destructIf; auto.\nQed. \n \n (* function ProxyBase._recoverStake ( address proxy ,  uint64 requestId ,  address elector )  internal  { \n        IProxy ( proxy )  . recover_stake { value :  DePoolLib . ELECTOR_FEE  +  DePoolLib . PROXY_FEE }  ( requestId ,  elector )  ; \n     } *) \n(* Definition ProxyBase_Ф__recoverStake ( Л_proxy : XAddress )( Л_requestId : XInteger64 )( Л_elector : XAddress ) : LedgerT True :=\nU0! Л_value := ↑ε9 DePoolLib_ι_ELECTOR_FEE !+ ↑ε9 DePoolLib_ι_PROXY_FEE ;\nsendMessage {| contractAddress :=  Л_proxy;\n               contractFunction := DePoolProxyContract_Ф_recover_stakeF Л_requestId Л_elector ;\n\t\t\t   contractMessage := {$ default with  messageValue := Л_value $} |}  . \n*)\n\n Lemma ProxyBase_Ф__recoverStake_exec : forall ( Л_proxy : XAddress ) ( Л_requestId : XInteger64 ) ( Л_elector : XAddress ) (l: Ledger) , \n    let oldMessages := eval_state (↑16 D2! VMState_ι_messages) l in\n    let value := eval_state (↑9 D2! DePoolLib_ι_ELECTOR_FEE) l + \n                 eval_state (↑9 D2! DePoolLib_ι_PROXY_FEE) l in \n    let newMessage  := {| contractAddress :=  Л_proxy;\n                          contractFunction := DePoolProxyContract_Ф_recover_stakeF Л_requestId Л_elector ;\n                          contractMessage := {$ default with messageValue := value $} |} in \n    exec_state (ProxyBase_Ф__recoverStake Л_proxy Л_requestId Л_elector ) l = \n    {$ l With VMState_ι_messages := newMessage :: oldMessages $} .  \n Proof. \n   intros. auto. \n Qed. \n \nLemma ProxyBase_Ф__recoverStake_eval : forall ( Л_proxy : XAddress ) ( Л_requestId : XInteger64 ) ( Л_elector : XAddress ) (l: Ledger) , \n \t eval_state (  ProxyBase_Ф__recoverStake Л_proxy Л_requestId Л_elector ) l = I . \n Proof. \n   intros.  auto. \n Qed. \n \n (* function ProxyBase._sendElectionRequest ( \n        address proxy , \n        uint64 requestId , \n        uint64 validatorStake , \n        DePoolLib . Request req , \n        address elector\n     ) \n        internal\n     { \n                        IProxy ( proxy )  . process_new_stake { value :  validatorStake  +  DePoolLib . ELECTOR_FEE  +  DePoolLib . PROXY_FEE }  ( \n            requestId , \n            req . validatorKey , \n            req . stakeAt , \n            req . maxFactor , \n            req . adnlAddr , \n            req . signature , \n            elector\n         )  ; \n     } *) \n     \n(*  Definition ProxyBase_Ф__sendElectionRequest ( Л_proxy : XAddress )\n                                            ( Л_requestId : XInteger64 )\n                                            ( Л_validatorStake : XInteger64 )\n                                            ( Л_req : DePoolLib_ι_Request ) \n                                            (Л_elector: XAddress) \n: LedgerT True := \n\tU0! Л_value := $ Л_validatorStake !+ ↑ε9 DePoolLib_ι_ELECTOR_FEE !+ ↑ε9 DePoolLib_ι_PROXY_FEE  ;\n\tsendMessage {| contractAddress := Л_proxy;\n\t               contractFunction := DePoolProxyContract_Ф_process_new_stakeF  Л_requestId (Л_req ->> DePoolLib_ι_Request_ι_validatorKey) (Л_req ->> DePoolLib_ι_Request_ι_stakeAt) (Л_req ->> DePoolLib_ι_Request_ι_maxFactor) (Л_req ->> DePoolLib_ι_Request_ι_adnlAddr) (Л_req ->> DePoolLib_ι_Request_ι_signature) Л_elector;\n\t\t\t\t   contractMessage := {$ default with  messageValue := Л_value $} |}.  *)   \n\n      \n Lemma ProxyBase_Ф__sendElectionRequest_exec : forall ( Л_proxy : XAddress ) \n                                                      ( Л_requestId : XInteger64 ) \n                                                      ( Л_validatorStake : XInteger64 ) \n                                                      ( Л_req : DePoolLib_ι_Request ) \n                                                      ( Л_elector : XAddress ) (l: Ledger) , \n let oldMessages := eval_state (↑16 D2! VMState_ι_messages) l in\n let value := Л_validatorStake + \n              eval_state (↑9 D2! DePoolLib_ι_ELECTOR_FEE) l + \n              eval_state (↑9 D2! DePoolLib_ι_PROXY_FEE) l in \n let newMessage  := {| contractAddress :=  Л_proxy;\n                       contractFunction := DePoolProxyContract_Ф_process_new_stakeF  Л_requestId \n                                                                                     (Л_req ->> DePoolLib_ι_Request_ι_validatorKey) \n                                                                                     (Л_req ->> DePoolLib_ι_Request_ι_stakeAt) \n                                                                                     (Л_req ->> DePoolLib_ι_Request_ι_maxFactor) \n                                                                                     (Л_req ->> DePoolLib_ι_Request_ι_adnlAddr) \n                                                                                     (Л_req ->> DePoolLib_ι_Request_ι_signature) \n                                                                                     Л_elector ;\n                       contractMessage := {$ default with messageValue := value $} |} in \n    exec_state (ProxyBase_Ф__sendElectionRequest Л_proxy Л_requestId Л_validatorStake Л_req Л_elector) l = \n    {$ l With VMState_ι_messages := newMessage :: oldMessages $} .  \n Proof. \n   intros. auto. \n Qed. \n \n Lemma ProxyBase_Ф__sendElectionRequest_eval : forall ( Л_proxy : XAddress ) \n                                                      ( Л_requestId : XInteger64 ) \n                                                      ( Л_validatorStake : XInteger64 ) \n                                                      ( Л_req : DePoolLib_ι_Request ) \n                                                      ( Л_elector : XAddress ) (l: Ledger) , \n \t eval_state (ProxyBase_Ф__sendElectionRequest Л_proxy Л_requestId Л_validatorStake Л_req Л_elector ) l = I . \n Proof. \n   intros. auto. \n Qed. \n \n", "meta": {"author": "Pruvendo", "repo": "depool_contract_scenarios", "sha": "f0146bda676f3a1a35a7695b9598c7d2e337bbc2", "save_path": "github-repos/coq/Pruvendo-depool_contract_scenarios", "path": "github-repos/coq/Pruvendo-depool_contract_scenarios/depool_contract_scenarios-f0146bda676f3a1a35a7695b9598c7d2e337bbc2/src/Proofs/ProxyBaseProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23319923131619266}}
{"text": "Require Import floyd.proofauto.\nRequire Import sha.SHA256.\nRequire Import sha.spec_sha.\nRequire Import sha.sha.\nRequire Export sha.pure_lemmas.\nRequire Export sha.general_lemmas.\nExport ListNotations.\n\nLocal Open Scope logic.\n\nGlobal Opaque K256.\n\nTransparent peq.\n\nLemma mapsto_tc_val:\n  forall sh t p v,\n  readable_share sh ->\n  v <> Vundef ->\n  mapsto sh t p v = !! tc_val t v && mapsto sh t p v .\nProof.\nintros.\napply pred_ext.\napply andp_right; auto.\nunfold mapsto; simpl.\ndestruct (access_mode t); try apply FF_left.\ndestruct (type_is_volatile t); try apply FF_left.\ndestruct p; try apply FF_left.\nif_tac; try contradiction. apply orp_left.\nnormalize.\nnormalize.\nnormalize.\nQed.\n\nFixpoint loops (s: statement) : list statement :=\n match s with\n  | Ssequence a b => loops a ++ loops b\n  | Sloop _ _ => [s]\n  | Sifthenelse _ a b => loops a ++ loops b\n  | _ => nil\n  end.\n\nLemma nth_big_endian_integer:\n  forall i bl w,\n   nth_error bl i = Some w ->\n    w = big_endian_integer\n                   (sublist (Z.of_nat i * WORD)\n                        (Z.succ (Z.of_nat i) * WORD)\n                   (map Int.repr (intlist_to_Zlist bl))).\nProof.\ninduction i; destruct bl; intros; inv H.\n*\n unfold sublist; simpl.\n rewrite big_endian_integer4.\n repeat rewrite Int.repr_unsigned.\n assert (Int.zwordsize=32)%Z by reflexivity.\n unfold Z_to_Int, Shr; simpl.\n change 255%Z with (Z.ones 8).\n apply Int.same_bits_eq; intros;\n autorewrite with testbit.\n if_tac; simpl.\n if_tac; simpl.\n if_tac; simpl; autorewrite with testbit. auto. f_equal; omega.\n rewrite if_false by omega. autorewrite with testbit. f_equal; omega.\n rewrite if_false by omega. rewrite if_false by omega.\n autorewrite with testbit. f_equal; omega.\n*\nspecialize (IHi _ _ H1); clear H1.\nsimpl map.\nrewrite IHi.\nunfold sublist.\nreplace (Z.to_nat (Z.of_nat (S i) * WORD)) with (4 + Z.to_nat (Z.of_nat i * WORD))%nat\n  by (rewrite plus_comm, inj_S; unfold Z.succ; rewrite Z.mul_add_distr_r;\n        rewrite Z2Nat.inj_add by (change WORD with 4; omega); reflexivity).\nrewrite <- skipn_skipn.\nsimpl skipn.\nf_equal. f_equal. f_equal. rewrite inj_S.  unfold Z.succ.\nrewrite !Z.mul_add_distr_r; omega.\nQed.\n\nLemma Znth_big_endian_integer:\n  forall i bl,\n   0 <= i < Zlength bl ->\n   Znth i bl Int.zero =\n     big_endian_integer\n                   (sublist (i * WORD) (Z.succ i * WORD)\n                   (map Int.repr (intlist_to_Zlist bl))).\nProof.\nintros.\nunfold Znth.\n rewrite if_false by omega.\npose proof (nth_error_nth _ Int.zero (Z.to_nat i) bl).\nrewrite <- (Z2Nat.id i) at 2 3 by omega.\napply nth_big_endian_integer.\napply H0.\napply Nat2Z.inj_lt.\nrewrite Z2Nat.id by omega.\nrewrite <- Zlength_correct; omega.\nQed.\n\nFixpoint sequence (cs: list statement) s :=\n match cs with\n | nil => s\n | c::cs' => Ssequence c (sequence cs' s)\n end.\n\nFixpoint rsequence (cs: list statement) s :=\n match cs with\n | nil => s\n | c::cs' => Ssequence (rsequence cs' s) c\n end.\n\nLemma sequence_rsequence:\n forall Espec CS Delta P cs s0 s R,\n    @semax CS Espec Delta P (Ssequence s0 (sequence cs s)) R  <->\n  @semax CS Espec Delta P (Ssequence (rsequence (rev cs) s0) s) R.\nProof.\nintros.\nrevert Delta P R s0 s; induction cs; intros.\nsimpl. apply iff_refl.\nsimpl.\nrewrite seq_assoc.\nrewrite IHcs; clear IHcs.\nreplace (rsequence (rev cs ++ [a]) s0) with\n    (rsequence (rev cs) (Ssequence s0 a)); [apply iff_refl | ].\nrevert s0 a; induction (rev cs); simpl; intros; auto.\nrewrite IHl. auto.\nQed.\n\nLemma seq_assocN:\n  forall {Espec: OracleKind} CS,\n   forall Q Delta P cs s R,\n        @semax CS Espec Delta P (sequence cs Sskip) (normal_ret_assert Q) ->\n         @semax CS Espec\n       (update_tycon Delta (sequence cs Sskip)) Q s R ->\n        @semax CS Espec Delta P (sequence cs s) R.\nProof.\nintros.\nrewrite semax_skip_seq.\nrewrite sequence_rsequence.\nrewrite semax_skip_seq in H.\nrewrite sequence_rsequence in H.\nrewrite <- semax_seq_skip in H.\neapply semax_seq'; [apply H | ].\neapply semax_extensionality_Delta; try apply H0.\nclear.\nrevert Delta; induction cs; simpl; intros.\napply tycontext_sub_refl.\neapply tycontext_sub_trans; [apply IHcs | ].\nclear.\nrevert Delta; induction (rev cs); simpl; intros.\napply tycontext_sub_refl.\napply update_tycon_sub.\napply IHl.\nQed.\n\nFixpoint sequenceN (n: nat) (s: statement) : list statement :=\n match n, s with\n | S n', Ssequence a s' => a::sequenceN n' s'\n | _, _ => nil\n end.\n\nLemma data_block_local_facts:\n forall {cs: compspecs} sh f data,\n  data_block sh f data |--\n   prop (field_compatible (tarray tuchar (Zlength f)) [] data\n           /\\ Forall isbyteZ f).\nProof.\nintros. unfold data_block, array_at.\nsimpl.\nentailer.\nQed.\nHint Resolve @data_block_local_facts : saturate_local.\n\nRequire Import JMeq.\n\nLemma reptype_tarray {cs: compspecs}:\n   forall t len, reptype (tarray t len) = list (reptype t).\nProof.\nintros.\nrewrite reptype_eq. simpl. reflexivity.\nQed.\n\nLocal Open Scope nat.\n\n(*** Application of Omega stuff ***)\n\nLemma CBLOCKz_eq : CBLOCKz = 64%Z.\nProof. reflexivity. Qed.\nLemma LBLOCKz_eq : LBLOCKz = 16%Z.\nProof. reflexivity. Qed.\n\nLtac helper2 :=\n match goal with\n   | |- context [CBLOCK] => add_nonredundant (CBLOCK_eq)\n   | |- context [LBLOCK] => add_nonredundant (LBLOCK_eq)\n   | |- context [CBLOCKz] => add_nonredundant (CBLOCKz_eq)\n   | |- context [LBLOCKz] => add_nonredundant (LBLOCKz_eq)\n   | H: context [CBLOCK] |- _ => add_nonredundant (CBLOCK_eq)\n   | H: context [LBLOCK] |- _ => add_nonredundant (LBLOCK_eq)\n   | H: context [CBLOCKz] |- _ => add_nonredundant (CBLOCKz_eq)\n   | H: context [LBLOCKz] |- _ => add_nonredundant (LBLOCKz_eq)\n  end.\n\nLtac Omega1 := Omega (helper1 || helper2).\n\nLtac MyOmega :=\n  rewrite ?length_list_repeat, ?skipn_length, ?map_length,\n   ?Zlength_map, ?Zlength_nil;\n  pose proof CBLOCK_eq;\n  pose proof CBLOCKz_eq;\n  pose proof LBLOCK_eq;\n  pose proof LBLOCKz_eq;\n  Omega1.\n(*** End Omega stuff ***)\n\nLocal Open Scope Z.\n\nLocal Open Scope logic.\n\nLemma data_block_valid_pointer sh l p: sepalg.nonidentity sh -> Zlength l > 0 ->\n      data_block sh l p |-- valid_pointer p.\nProof. unfold data_block. simpl; intros.\n  apply andp_valid_pointer2. apply data_at_valid_ptr; auto; simpl.\n  rewrite Z.max_r, Z.mul_1_l; omega.\nQed.\n\nLemma data_block_isbyteZ:\n forall sh data v, data_block sh data v = !! Forall isbyteZ data && data_block sh data v.\nProof.\nunfold data_block; intros.\nsimpl.\nnormalize.\nf_equal. f_equal. apply prop_ext. intuition.\nQed.\n\nLemma sizeof_tarray_tuchar:\n forall (n:Z), (n>=0)%Z -> (sizeof (tarray tuchar n) =  n)%Z.\nProof. intros.\n unfold sizeof,tarray; cbv beta iota.\n  rewrite Z.max_r by omega.\n  unfold alignof, tuchar; cbv beta iota.\n  rewrite Z.mul_1_l. auto.\nQed.\n\nLemma isbyte_value_fits_tuchar:\n  forall x, isbyteZ x -> value_fits tuchar (Vint (Int.repr x)).\nProof.\nintros. hnf in H|-*; intros.\nsimpl. rewrite Int.unsigned_repr by repable_signed.\n  change Byte.max_unsigned with 255%Z. omega.\nQed.\n\nLemma Zlength_Zlist_to_intlist:\n  forall (n:Z) (l: list Z),\n   (Zlength l = WORD*n)%Z -> Zlength (Zlist_to_intlist l) = n.\nProof.\nintros.\nrewrite Zlength_correct in *.\nassert (0 <= n)%Z by ( change WORD with 4%Z in H; omega).\nrewrite (length_Zlist_to_intlist (Z.to_nat n)).\napply Z2Nat.id; auto.\napply Nat2Z.inj. rewrite H.\nrewrite Nat2Z.inj_mul.\nf_equal. rewrite Z2Nat.id; omega.\nQed.\n\nLemma nth_intlist_to_Zlist_eq:\n forall d (n i j k: nat) al, (i < n)%nat -> (i < j*4)%nat -> (i < k*4)%nat ->\n    nth i (intlist_to_Zlist (firstn j al)) d = nth i (intlist_to_Zlist (firstn k al)) d.\nProof.\n induction n; destruct i,al,j,k; simpl; intros; auto; try omega.\n destruct i; auto. destruct i; auto. destruct i; auto.\n apply IHn; omega.\nQed.\n\n\nHint Resolve isbyteZ_sublist.\n\n\nLemma split2_data_block:\n  forall  {cs: compspecs}  n sh data d,\n  (0 <= n <= Zlength data)%Z ->\n  data_block sh data d =\n  (data_block sh (sublist 0 n data) d *\n   data_block sh (sublist n (Zlength data) data)\n   (field_address0 (tarray tuchar (Zlength data)) [ArraySubsc n] d))%logic.\nProof.\n  intros.\n  unfold data_block. simpl. normalize.\n  f_equal. f_equal.\n  apply prop_ext.\n  split; intro. split; apply Forall_sublist; auto.\n  erewrite <- (sublist_same 0 (Zlength data)); auto.\n  rewrite (sublist_split 0 n) by omega.\n  apply Forall_app; auto.\n  rewrite <- !sublist_map.\n  unfold tarray.\n  rewrite split2_data_at_Tarray_tuchar with (n1:=n) by (autorewrite with sublist; auto).\n  autorewrite with sublist.\n  reflexivity.\nQed.\n\nLemma split3_data_block:\n  forall  {cs: compspecs} lo hi sh data d,\n  0 <= lo <= hi ->\n  hi <= Zlength data  ->\n  data_block sh data d =\n  (data_block sh (sublist 0 lo data) d *\n   data_block sh (sublist lo hi data)\n   (field_address0 (tarray tuchar (Zlength data)) [ArraySubsc lo] d) *\n   data_block sh (sublist hi (Zlength data) data)\n   (field_address0 (tarray tuchar (Zlength data)) [ArraySubsc hi] d))%logic.\nProof.\n  intros.\n  unfold data_block. simpl. normalize.\n  f_equal. f_equal.\n  apply prop_ext.\n  split; intro. split3; apply Forall_sublist; auto.\n  erewrite <- (sublist_same 0 (Zlength data)); auto.\n  rewrite (sublist_split 0 lo (Zlength data)) by omega.\n  rewrite (sublist_split lo hi (Zlength data)) by omega.\n  destruct H1 as [? [? ?]].\n  repeat (apply Forall_app; split);  auto.\n  rewrite <- !sublist_map.\n  unfold tarray.\n  rewrite split3_data_at_Tarray_tuchar with (n1:=lo)(n2:=hi) by (autorewrite with sublist; auto).\n  autorewrite with sublist.\n  reflexivity.\nQed.\n\nGlobal Opaque WORD.\n\nLemma S256abs_data:\n  forall hashed data,\n   (LBLOCKz | Zlength hashed) ->\n   Zlength data < CBLOCKz ->\n   s256a_data (S256abs hashed data) = data.\nProof.\nintros. unfold S256abs, s256a_data.\nrewrite Zlength_app.\nrewrite Zlength_intlist_to_Zlist.\ndestruct H as [n ?].\nrewrite H.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (n * CBLOCKz + Zlength data) CBLOCKz H1).\npose proof (Zmod_eq (Zlength data) CBLOCKz H1).\npose proof (Zlength_nonneg data).\nrewrite sublist_app2; rewrite Zlength_intlist_to_Zlist; rewrite H;\n rewrite <- Z.mul_assoc; change (LBLOCKz * 4)%Z with CBLOCKz.\napply sublist_same.\nrewrite Z.div_add_l by omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega. omega.\nomega.\nrewrite Z.div_add_l by  omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega.\nsplit; [ | omega].\napply Z.mul_nonneg_nonneg.\nclear - H.\nassert (n < 0 \\/ 0 <= n) by omega.\ndestruct H0; auto.\npose proof (Zlength_nonneg hashed).\nassert (n * LBLOCKz < 0).\napply Z.mul_neg_pos; auto.\nomega.\nomega.\nQed.\n\nLemma S256abs_hashed:\n  forall hashed data,\n   (LBLOCKz | Zlength hashed) ->\n   Zlength data < CBLOCKz ->\n   s256a_hashed (S256abs hashed data) = hashed.\nProof.\nintros;  unfold S256abs, s256a_hashed.\nrewrite Zlength_app.\nrewrite Zlength_intlist_to_Zlist.\ndestruct H as [n ?].\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (n * CBLOCKz + Zlength data) CBLOCKz H1).\npose proof (Zmod_eq (Zlength data) CBLOCKz H1).\npose proof (Zlength_nonneg data).\nrewrite sublist_app1; rewrite ?Zlength_intlist_to_Zlist;\n  rewrite H.\nrewrite sublist_same; try omega.\napply intlist_to_Zlist_to_intlist.\nrewrite Zlength_intlist_to_Zlist.\n  rewrite H.\nrewrite <- Z.mul_assoc; change (LBLOCKz*4)%Z with CBLOCKz.\nrewrite Z.div_add_l by omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega.  omega.\nsplit; [omega | ].\nrewrite <- Z.mul_assoc; change (LBLOCKz*4)%Z with CBLOCKz.\nrewrite Z.div_add_l by omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega.\nclear - H.\nassert (n < 0 \\/ 0 <= n) by omega.\nsimpl.\ndestruct H0.\npose proof (Zlength_nonneg hashed).\nassert (n * LBLOCKz < 0).\napply Z.mul_neg_pos; auto.\nomega.\nrewrite Z.add_0_r.\napply Z.mul_nonneg_nonneg; auto.\nrewrite <- Z.mul_assoc; change (LBLOCKz*4)%Z with CBLOCKz.\nrewrite Z.div_add_l by omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega.  omega.\nQed.\n\nLemma s256a_hashed_divides:\n  forall a, (LBLOCKz | Zlength (s256a_hashed a)).\nProof.\nintros. unfold s256a_hashed.\nexists (Zlength a / CBLOCKz)%Z.\nerewrite Zlength_Zlist_to_intlist; [reflexivity |].\nrewrite Zlength_sublist.\nrewrite (Z.mul_comm WORD).\nrewrite <- Z.mul_assoc.\nchange (LBLOCKz * WORD)%Z with CBLOCKz.\nomega.\nsplit; [ omega  |] .\napply Z.mul_nonneg_nonneg; auto.\napply Z.div_pos.\napply Zlength_nonneg.\nrewrite CBLOCKz_eq; omega.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (Zlength a) CBLOCKz H).\npose proof (Z_mod_lt (Zlength a) CBLOCKz H).\nomega.\nQed.\n\nLemma s256a_data_len:\n  forall a: s256abs,\n  Zlength (s256a_data a) = Zlength a mod CBLOCKz.\nProof.\nintros.\nunfold s256a_data.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (Zlength a) CBLOCKz H).\npose proof (Z_mod_lt (Zlength a) CBLOCKz H).\nrewrite H0.\nrewrite Zlength_sublist; try omega.\nsplit; try omega.\napply Z.mul_nonneg_nonneg.\napply Z.div_pos.\napply Zlength_nonneg.\nomega. omega.\nQed.\n\nLemma s256a_data_Zlength_less:\n  forall a, Zlength (s256a_data a) < CBLOCKz.\nProof.\nintros.\nrewrite s256a_data_len.\napply Z_mod_lt.\nrewrite CBLOCKz_eq; omega.\nQed.\n\nLemma hashed_data_recombine:\n  forall a,\n     Forall isbyteZ a ->\n    intlist_to_Zlist (s256a_hashed a) ++ s256a_data a = a.\nProof.\nintros. rename H into BYTES.\nunfold s256a_hashed, s256a_data.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\nrewrite Zlist_to_intlist_to_Zlist.\nrewrite sublist_rejoin.\nautorewrite with sublist. auto.\nsplit; [ omega  |] .\napply Z.mul_nonneg_nonneg; auto.\napply Z.div_pos.\napply Zlength_nonneg.\nrewrite CBLOCKz_eq; omega.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (Zlength a) CBLOCKz H).\npose proof (Z_mod_lt (Zlength a) CBLOCKz H).\nomega.\nrewrite Zlength_sublist.\nrewrite Z.sub_0_r.\napply Z.divide_mul_r.\nexists LBLOCKz. reflexivity.\nsplit; [ omega  |] .\napply Z.mul_nonneg_nonneg; auto.\napply Z.div_pos.\napply Zlength_nonneg.\nomega.\npose proof (Zmod_eq (Zlength a) CBLOCKz H).\npose proof (Z_mod_lt (Zlength a) CBLOCKz H).\nomega.\napply Forall_sublist.\nauto.\nQed.\n\nDefinition bitlength (hashed: list int) (data: list Z) : Z :=\n   ((Zlength hashed * WORD + Zlength data) * 8)%Z.\n\nLemma bitlength_eq:\n  forall hashed data,\n  bitlength hashed data = s256a_len (S256abs hashed data).\nProof.\nintros.\nunfold bitlength, s256a_len, S256abs.\nrewrite Zlength_app.\nrewrite Zlength_intlist_to_Zlist.\nreflexivity.\nQed.\n\nLemma S256abs_recombine:\n forall a, Forall isbyteZ a ->\n    S256abs (s256a_hashed a) (s256a_data a) = a.\nProof.\nintros.\napply hashed_data_recombine; auto.\nQed.\n\nLemma Zlist_to_intlist_app:\n  forall a b,\n  (WORD | Zlength a) ->\n   Zlist_to_intlist (a++b) = Zlist_to_intlist a ++ Zlist_to_intlist b.\nProof.\nintros.\ndestruct H as [na H].\nrewrite <- (Z2Nat.id na) in H.\nFocus 2.\ndestruct (zlt na 0); try omega.\nassert (na * WORD < 0); [apply Z.mul_neg_pos; auto | ].\npose proof (Zlength_nonneg a); omega.\nrevert a H; induction (Z.to_nat na); intros.\nsimpl in H. destruct a. simpl. auto. rewrite Zlength_cons in H.\npose proof (Zlength_nonneg a); omega.\nrewrite inj_S in H.\nunfold Z.succ in H. rewrite Z.mul_add_distr_r in H.\nchange (1*WORD)%Z with 4 in H.\nassert (Zlength a >= 4).\nassert (0 <= Z.of_nat n * WORD); [ | omega].\napply Z.mul_nonneg_nonneg; try omega.\nchange WORD with 4%Z; omega.\ndo 4 (destruct a; [rewrite Zlength_nil in H0; omega | rewrite Zlength_cons in H,H0  ]).\nsimpl.\ndo 4 f_equal. apply IHn.\nomega.\nQed.\n\nLemma round_range:\n forall {A} (a: list A) (N:Z),\n  N > 0 ->\n   0 <= Zlength a / N * N <= Zlength a.\nProof.\nintros.\nsplit.\napply Z.mul_nonneg_nonneg; auto; try omega.\napply Z.div_pos; try omega.\napply Zlength_nonneg.\npose proof (Zmod_eq (Zlength a) N H).\npose proof (Z_mod_lt (Zlength a) N H).\nomega.\nQed.\n\nLemma CBLOCKz_gt: CBLOCKz > 0.\nProof. rewrite CBLOCKz_eq; omega.\nQed.\n\nLemma Zlist_to_intlist_inj:\n  forall a b,\n   (WORD | Zlength a) ->\n   (WORD | Zlength b) ->\n   Forall isbyteZ a ->\n   Forall isbyteZ b ->\n   Zlist_to_intlist a = Zlist_to_intlist b ->\n   a=b.\nProof.\nintros.\nrewrite <- (Zlist_to_intlist_to_Zlist a) by auto.\nrewrite H3.\napply Zlist_to_intlist_to_Zlist; auto.\nQed.\n\nDefinition update_abs (incr: list Z) (a: list Z) (a': list Z) :=\n    a' = a ++ incr.\n\nLemma update_abs_eq:\n  forall msg a a',\n Forall isbyteZ (a++msg) ->\n Forall isbyteZ a' ->\n (update_abs msg a a' <->\n  exists blocks,\n    s256a_hashed a' = s256a_hashed a ++ blocks /\\\n    s256a_data a ++ msg = intlist_to_Zlist blocks ++ s256a_data a').\nProof.\nintros. rename H0 into H'.\nunfold update_abs.\nassert (0 <= 0 <= Zlength a / CBLOCKz * CBLOCKz). {\n split; [omega | ].\n apply Z.mul_nonneg_nonneg.\n apply Z.div_pos.\n apply Zlength_nonneg.\n rewrite CBLOCKz_eq; omega.\n rewrite CBLOCKz_eq; omega.\n}\npose proof (round_range a _ CBLOCKz_gt).\npose proof (round_range (a++msg) _ CBLOCKz_gt).\nsplit; intro.\n*\nsubst a'.\nunfold s256a_hashed.\nexists (Zlist_to_intlist\n            (sublist (Zlength a / CBLOCKz * CBLOCKz) (Zlength (a++msg) / CBLOCKz * CBLOCKz)\n                  (a++msg))).\nsplit.\n +\n rewrite (sublist_split 0 (Zlength a / CBLOCKz * CBLOCKz)); auto.\n rewrite Zlist_to_intlist_app.\n f_equal.\n rewrite sublist_app1; auto. omega.\n rewrite Zlength_sublist; auto.\n rewrite Z.sub_0_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n rewrite Zlength_app.\n pose proof (Zlength_nonneg msg); omega.\n split; [ | apply round_range; apply CBLOCKz_gt].\n apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].\n rewrite Zlength_app; Omega1.\n +\n rewrite Zlist_to_intlist_to_Zlist.\n Focus 2. rewrite Zlength_sublist. rewrite <- Z.mul_sub_distr_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n split; [Omega1 | ].\n apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].\n rewrite Zlength_app; Omega1.\n apply round_range. apply CBLOCKz_gt.\n 2: apply Forall_sublist; auto.\n unfold s256a_data.\n destruct (zlt   (Zlength (a ++ msg) / CBLOCKz * CBLOCKz) (Zlength a) ).\n  -\n   rewrite sublist_app1; try omega.\n   rewrite (sublist_split (Zlength (a ++ msg) / CBLOCKz * CBLOCKz)\n               (Zlength a) (Zlength (a ++ msg))); try omega.\n   rewrite sublist_app1; try omega.\n   rewrite sublist_app2 by omega.\n   autorewrite with sublist.\n   rewrite (sublist_same 0) by omega.\n   rewrite <- app_ass. f_equal.\n   rewrite sublist_rejoin; try omega. auto.\n   split. apply round_range; apply CBLOCKz_gt.\n apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].\n  Omega1.\n  rewrite Zlength_app in l; omega.\n  rewrite Zlength_app; Omega1.\n   split. apply round_range; apply CBLOCKz_gt.\n apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].\n  rewrite Zlength_app; Omega1.\n -\n   rewrite (sublist_split (Zlength a / CBLOCKz * CBLOCKz) (Zlength a)\n                  (Zlength (a ++ msg) / CBLOCKz * CBLOCKz) ); auto.\n   rewrite app_ass.\n   rewrite sublist_app1; try omega.\n   rewrite sublist_app2; try omega.\n   rewrite Z.sub_diag.\n   f_equal.\n   rewrite sublist_app2; try omega.\n   rewrite sublist_rejoin.\n   autorewrite with sublist. auto.\n   omega.\n  split; try omega. rewrite Zlength_app; Omega1.\n   omega.\n*\ndestruct H3 as [blocks [? ?]].\nmatch type of H3 with ?A = ?B =>\n  assert (Zlength A * WORD = Zlength B * WORD)%Z by congruence\nend.\nmatch type of H4 with ?A = ?B =>\n  assert (sublist 0 (Zlength a / CBLOCKz * CBLOCKz) a ++ A =\n              sublist 0 (Zlength a / CBLOCKz * CBLOCKz) a ++ B) by congruence\nend.\nunfold s256a_hashed, s256a_data in *.\nrewrite <- app_ass in H6.\nrewrite sublist_rejoin in H6 by omega.\nrewrite sublist_same in H6 by omega.\nrewrite H6.\nclear H6 H4.\nrewrite <- (sublist_same 0 (Zlength a') a') at 1; auto.\nrewrite <- app_ass.\nrewrite (sublist_split 0 (Zlength a' / CBLOCKz * CBLOCKz) (Zlength a')); try omega.\nf_equal.\napply Zlist_to_intlist_inj.\nrewrite Zlength_sublist.\n rewrite Z.sub_0_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n split; [clear; omega | ].\n apply Z.mul_nonneg_nonneg; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_pos; [ | rewrite CBLOCKz_eq; omega].\n apply Zlength_nonneg.\n apply round_range; apply CBLOCKz_gt.\n rewrite Zlength_app.\n apply Z.divide_add_r.\nrewrite Zlength_sublist.\n rewrite Z.sub_0_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n split; [clear; omega | ].\n apply Z.mul_nonneg_nonneg; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_pos; [ | rewrite CBLOCKz_eq; omega].\n apply Zlength_nonneg.\n apply round_range; apply CBLOCKz_gt.\n exists (Zlength blocks).\n apply Zlength_intlist_to_Zlist.\n apply Forall_sublist; auto.\n apply Forall_app; split.\n apply Forall_app in H; destruct H;\n apply Forall_sublist; auto.\n apply isbyte_intlist_to_Zlist.\n rewrite H3.\n rewrite Zlist_to_intlist_app. f_equal.\n symmetry; apply intlist_to_Zlist_to_intlist.\nrewrite Zlength_sublist.\n rewrite Z.sub_0_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n auto.\n omega.\n split; [clear; omega |].\n apply round_range; apply CBLOCKz_gt.\n split; [ | clear; omega].\n apply round_range; apply CBLOCKz_gt.\nQed.\n\nLemma array_at_memory_block:\n forall {cs: compspecs} sh t gfs lo hi v p n,\n  sizeof (nested_field_array_type t gfs lo hi) = n ->\n  lo <= hi ->\n  array_at sh t gfs lo hi v p |--\n  memory_block sh n (field_address0 t (ArraySubsc lo :: gfs) p).\nProof.\nintros.\nrewrite  array_at_data_at by auto.\nnormalize.\nunfold at_offset.\nrewrite field_address0_offset by auto.\nsubst n.\napply data_at_memory_block.\nQed.\n\nHint Extern 2 (array_at _ _ _ _ _ _ _ |-- memory_block _ _ _) =>\n   (apply array_at_memory_block; try reflexivity; try omega) : cancel.\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/sha/sha_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23319922469185136}}
{"text": "Require Import floyd.proofauto.\nRequire Import progs.field_loadstore.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nLocal Open Scope logic.\n\nLemma Znth_map: forall {A B} n xs d (f: A -> B),\n  Znth n (map f xs) (f d) = f (Znth n xs d).\nProof.\n  intros.\n  unfold Znth.\n  if_tac.\n  + reflexivity.\n  + apply map_nth.\nQed.\n\nLemma legal_Znth_map: forall {A B} n xs dA dB (f: A -> B),\n  0 <= n < Zlength xs ->\n  Znth n (map f xs) dB = f (Znth n xs dA).\nProof.\n  intros.\n  unfold Znth.\n  if_tac.\n  + omega.\n  + apply nth_map'.\n    rewrite Zlength_correct in H.\n    destruct H.\n    apply Z2Nat.inj_lt in H1; [ | omega | omega].\n    rewrite Nat2Z.id in H1.\n    exact H1.\nQed.\n\nDefinition t_struct_b := Tstruct _b noattr.\n\nDefinition sub_spec (sub_id: ident) :=\n DECLARE sub_id\n  WITH v : val * list (val*val) , p: val\n  PRE  []\n        PROP  (is_int I8 Signed (snd (nth 1%nat (snd v) (Vundef, Vundef))))\n        LOCAL (gvar _p p)\n        SEP   (data_at Ews t_struct_b v p)\n  POST [ tint ]\n        PROP() LOCAL()\n        SEP(data_at Ews t_struct_b (snd (nth 1%nat (snd v) (Vundef, Vundef)), snd v) p).\n\nDefinition sub_spec' (sub_id: ident) :=\n DECLARE sub_id\n  WITH v : reptype t_struct_b, p: val\n  PRE  []\n        PROP  (is_int I8 Signed (proj_reptype _ (DOT _y2 SUB 1 DOT _x2) v))\n        LOCAL (gvar _p p)\n        SEP   (data_at Ews t_struct_b v p)\n  POST [ tint ]\n        PROP() LOCAL()\n        SEP(data_at Ews t_struct_b\n           (upd_reptype t_struct_b (DOT _y1) v\n             (proj_reptype t_struct_b (StructField _x2 :: ArraySubsc 1 :: StructField _y2 :: nil) v))\n           p).\n\nLemma spec_coincide: sub_spec' = sub_spec.\nProof.\n(*reflexivity.*)\nAbort.\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [\n    sub_spec _sub1; sub_spec _sub2; sub_spec _sub3]).\n\nLemma body_sub1:  semax_body Vprog Gprog f_sub1 (sub_spec _sub1).\nProof.\n  unfold sub_spec.\n  start_function.\n  forward.\n  forward.\n  forward.\nQed.\n\nLemma body_sub2:  semax_body Vprog Gprog f_sub2 (sub_spec _sub2).\nProof.\n  unfold sub_spec.\n  start_function.\n  forward.\n  forward.\n  forward.\nQed.\n\nLemma body_sub3:  semax_body Vprog Gprog f_sub3 (sub_spec _sub3).\nProof.\n  unfold sub_spec.\n  start_function.\n  forward.\n  forward.\n  forward.\n  forward.\nQed.\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/progs/verif_field_loadstore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.23319922469185134}}
{"text": "From Coq Require Import List ListSet Lia.\n\nFrom CasperCBC\nRequire Import\n  Lib.Preamble\n  Lib.Classes\n  Lib.ListSetExtras\n  Lib.Measurable\n  CBC.FullNode.Validator.State\n  VLSM.Common\n  VLSM.Liveness\n  VLSM.Composition\n  VLSM.Equivocation (* for has_been_sent *)\n.\n\n(** * VLSM Simple Live Protocol *)\n\n(**\nThis module defines a simple consensus protocol, and\nproves that it is live when there are no synchronization faults.\n *)\n\n(** ** Validators\n\nThe components are similar to [CBC.FullNode.Validator], except\nthat the states and messages all carry times, and the nodes\nonly send messages at the times given in a [Plan].\n *)\nSection Define_Component.\n\n  Context\n    {C V:Type}\n    {EqC: EqDecision C}\n    {EqV: EqDecision V}\n    (c0:C)\n    (plan : nat -> V -> Prop)\n  .\n\n  Inductive validator_message : Type :=\n    Msg {message_time:nat;\n         message_proposal: C;\n         message_sender: V;\n         message_justification: list validator_message\n        }.\n  Global Instance validator_message_eq_dec : EqDecision validator_message.\n  Proof using C V EqC EqV.\n  refine (fix validator_message_eq_dec (m n : validator_message) {struct m} : Decision (m=n) :=\n    match m, n with\n    | Msg t1 c1 v1 msgs1, Msg t2 c2 v2 msgs2 =>\n      if decide (t1 = t2) then\n        if decide (c1 = c2) then\n          if decide (v1 = v2) then\n            if list_eq_dec validator_message_eq_dec msgs1 msgs2 then\n              left _\n            else right _\n          else right _\n        else right _\n      else right _\n    end);congruence.\n  Defined.\n\n  Definition message_slot (m : validator_message) : (nat * V) :=\n    let '(Msg t _ v _) := m in (t, v).\n\n  Fixpoint message_height (m: validator_message) {struct m}: nat :=\n    S (list_max (map message_height (message_justification m))).\n\n  Lemma validator_message_well_founded:\n    forall time c v history,\n      ~In (Msg time c v history) history.\n  Proof.\n    intros t c v hist Hin.\n    apply in_map with (f:=message_height) in Hin.\n    assert (Forall (fun k => k <= list_max (map message_height hist)) (map message_height hist))\n      by (apply list_max_le;reflexivity).\n    rewrite Forall_forall in H.\n    specialize (H _ Hin).\n    revert H.\n    apply PeanoNat.Nat.nle_succ_diag_l.\n  Qed.\n\n  Inductive validator_state : Type :=\n    State (time:nat)\n          (received:list validator_message)\n          (sent:list validator_message)\n          (finished_send:bool).\n\n  Definition validator_time : validator_state -> nat :=\n    fun '(State t _ _ _) => t.\n\n  Definition validator_sends : validator_state -> list validator_message :=\n    fun '(State _ _ sends _) => sends.\n\n  Definition validator_received : validator_state -> list validator_message :=\n    fun '(State _ received _ _) => received.\n\n  Definition initial_validator_state (s:validator_state) : Prop :=\n    let (t,msgs,log,flag) := s in t = 0 /\\ msgs = nil /\\ log = nil /\\ ~flag.\n  Definition initial_validator_message (m:validator_message) : Prop := False.\n  Inductive validator_label : Type :=\n  | Proposal (c:C)\n  | Tick.\n\n  Definition record_receive\n    : validator_message -> validator_state -> validator_state :=\n    fun msg '(State t msgs log flag) =>\n      State t (set_add decide_eq msg msgs) log flag.\n\n  Context\n    (estimator: list validator_message -> C -> Prop)\n    (v:V)\n    .\n\n  Definition validator_transition (l:option validator_label) (sim:(validator_state * option validator_message)) : (validator_state * option validator_message) :=\n    let (s,im) := sim in\n    match l with\n    | None =>\n      (* Label is None for receiving messages *)\n      match im with\n      (* Receive the message *)\n      | Some m => (record_receive m s,None)\n      (* Receiving with no message will actually be ruled out\n         by the validity predicate, just leave s unchanged *)\n      | None => (s,None)\n      end\n    | Some Tick =>\n      (* Advance clock *)\n      let (n,msgs,log,f) := s in ((State (1+n) msgs log false),None)\n    | Some (Proposal c) =>\n      (* Send a proposal *)\n      let (n,known,sent,_) := s in\n      let m := Msg n c v known in\n      (State n\n             (set_add decide_eq m known)\n             (m::sent)\n             true,\n       Some m)\n    end.\n\n\n  (** \"Mandatory flip-flopping\"\n     If the estimator allows multiple consensus values\n     and the state has previously sent a proposals,\n     the new proposal cannot match the immediately\n     preceeding proposal.\n\n     TODO: Is this sufficient for non-binary decisions?\n   *)\n  Definition flip_condition : validator_state -> C -> Prop :=\n    fun '(State _ msgs log _) c =>\n      match log with\n      | nil => True\n      | (Msg _ c' _ _::_) =>\n        c <> c' \\/ (forall c2, estimator msgs c2 -> c2 = c)\n      end.\n\n  Definition validator_valid (l:option validator_label)\n             (sim:(validator_state * option validator_message)) : Prop :=\n    let (s,im) := sim in\n    match l with\n    | None =>\n      match im with\n        (* May not receive with no message *)\n      | None => False\n        (* A recevied message must\n           (1) have not already been received,\n           (2) satisfy the full node condition\n           (3) must come from a time no earlier later than the clock of s,\n               and can only be received from the current clock if either\n               s has already produced its own mesage for this time,\n               or this validator is not in the plan for this time at all\n         *)\n      | Some ((Msg n  _ _ msg_just) as m) => let (n',msgs,log,f) := s in\n                              ~In m msgs\n                              /\\ incl msg_just msgs (* \"full node condition\" *)\n                              /\\ (n < n' \\/ (n = n' /\\ (f \\/ ~plan n v)))\n      end\n    | Some Tick =>\n      match im with\n      | None =>\n        (let (n,_,_,f) := s in f \\/ ~plan n v)\n        /\\ (let (t,received,_,_) := s in\n            forall v, plan t v -> In (t,v) (map message_slot received))\n      | Some _ => False\n      end\n    | Some (Proposal c) =>\n      match im with\n      | None => let (n,msgs,log,f) := s in\n                estimator msgs c\n                /\\ flip_condition s c\n                /\\ plan n v /\\ ~f\n      | Some _ => False\n      end\n    end.\n\n  Instance Validator_type : VLSM_type validator_message :=\n    {| state := validator_state;\n       label:= option validator_label\n    |}.\n  Instance Validator_sign : VLSM_sign Validator_type :=\n    {| initial_state_prop := initial_validator_state;\n       initial_message_prop := initial_validator_message;\n       s0 := exist initial_validator_state (State 0 nil nil false)\n                   (conj (eq_refl _) (conj (eq_refl _) (conj (eq_refl _) (fun H => H))));\n       m0 := (Msg 0 c0 v nil);\n       l0 := None\n   |}.\n\n  Instance Validator_machine : VLSM_class Validator_sign :=\n    {| transition := validator_transition;\n       valid := validator_valid\n    |}.\n\n  Definition Validator : VLSM validator_message :=\n    mk_vlsm Validator_machine.\n\n  Lemma validator_clock_monotone: forall l s om s' om',\n      vtransition Validator l (s,om) = (s',om') -> validator_time s <= validator_time s'.\n  Proof using C V.\n    intros l s om s' om' H.\n    apply (f_equal fst) in H.\n    simpl in H. subst s'.\n    destruct s.\n    unfold vtransition. simpl.\n    repeat lazymatch goal with |- context [fst (match ?X with _ => _ end)] => destruct X end;\n      simpl;solve[auto].\n  Defined.\n\n  Definition validator_clock: ClockFor Validator :=\n    {| clock := validator_time: vstate Validator -> nat;\n       clock_monotone := validator_clock_monotone\n    |}.\n\n  Definition validator_has_been_sent : state_message_oracle Validator :=\n    fun '(State _ _ sent _) m => In m sent.\n  Definition validator_has_been_sent_dec : RelDecision validator_has_been_sent :=\n    fun s m => let '(State _ _ sent _) := s in in_dec decide_eq m sent.\n\n  Lemma validator_initial_not_sent:\n    forall (s : vstate Validator),\n      initial_state_prop s -> forall m : validator_message, ~ validator_has_been_sent s m.\n  Proof using.\n    intros [] Hinit m.\n    simpl. assert (sent = nil) as -> by apply Hinit. tauto.\n  Qed.\n\n  Lemma validator_transition_updates_sent:\n       forall l s im s' om,\n         vtransition Validator l (s,im) = (s',om) ->\n         forall msg, validator_has_been_sent s' msg\n                     <-> (om = Some msg \\/ validator_has_been_sent s msg).\n  Proof using.\n    intros l s im s' om Htrans msg.\n    destruct s.\n    unfold vtransition in Htrans.\n    simpl in Htrans.\n    destruct l as [[]|];[| |destruct im];\n      inversion_clear Htrans;simpl;\n      firstorder congruence.\n  Qed.\n\n  Definition validator_sent_stepwise_props:\n    has_been_sent_stepwise_props validator_has_been_sent :=\n    {| oracle_no_inits := validator_initial_not_sent;\n       oracle_step_update l s im s' om H :=\n         (validator_transition_updates_sent l s im s' om (proj2 H));\n    |}.\n\n  Global Instance validator_has_been_sent_capability : has_been_sent_capability Validator\n    := has_been_sent_capability_from_stepwise\n         validator_has_been_sent_dec\n         validator_sent_stepwise_props.\n\n  Definition validator_has_been_observed : validator_state -> validator_message -> Prop\n    := fun '(State _ received _ _) m => In m received.\n  Definition validator_has_been_observed_dec : RelDecision validator_has_been_observed\n    := fun s m => let '(State _ received _ _) := s in in_dec decide_eq m received.\n\n  Lemma validator_initial_not_observed:\n    forall (s : vstate Validator),\n      initial_state_prop s -> forall m : validator_message, ~ validator_has_been_observed s m.\n  Proof using.\n    intros [] Hinit m.\n    simpl. assert (received = nil) as -> by apply Hinit. tauto.\n  Qed.\n\n  Lemma validator_transition_updates_observed\n        [l s im s' om]\n        (Hptrans: protocol_transition (pre_loaded_with_all_messages_vlsm Validator) l (s,im) (s',om)):\n    forall msg, validator_has_been_observed s' msg\n                <-> ((im = Some msg \\/ om = Some msg) \\/ validator_has_been_observed s msg).\n  Proof using.\n    intro msg.\n    destruct Hptrans as [[_ [_ Hvalid]] Htrans].\n    destruct s.\n    unfold vtransition in Htrans.\n    simpl in Htrans.\n    cbn -[In flip_condition] in Hvalid.\n    destruct l as [l'|].\n    - destruct l'.\n      + destruct im;[exfalso;assumption|clear Hvalid].\n        inversion_clear Htrans.\n        simpl;rewrite set_add_iff.\n        clear;intuition congruence.\n      + destruct im;[exfalso;assumption|clear Hvalid].\n        inversion_clear Htrans.\n        simpl.\n        clear;intuition congruence.\n    - destruct im;[|exfalso;assumption].\n      inversion_clear Htrans;simpl.\n      rewrite set_add_iff.\n      destruct v0.\n      clear.\n      clear;intuition congruence.\n  Qed.\n\n  Definition validator_observed_stepwise_props :\n    oracle_stepwise_props (vlsm:=Validator) item_sends_or_receives validator_has_been_observed\n    := {| oracle_no_inits := validator_initial_not_observed;\n          oracle_step_update := validator_transition_updates_observed|}.\n\n  Global Instance validator_has_been_observed_capability:\n    has_been_observed_capability Validator :=\n      {|has_been_observed := validator_has_been_observed: state_message_oracle Validator;\n        has_been_observed_dec := validator_has_been_observed_dec;\n        has_been_observed_stepwise_props :=\n          validator_observed_stepwise_props |}.\n\n  Definition unsent_time (s:validator_state) :=\n    let (t,_,_,f) := s in\n    (if f then 1 else 0) + t.\n\n  Definition sends_respect_plan (s: validator_state) : Prop :=\n    forall m, validator_has_been_sent s m ->\n              plan (message_time m) v\n              /\\ message_sender m = v\n              /\\ message_time m < unsent_time s.\n\n  Definition sends_fill_plan (s: validator_state) : Prop :=\n    forall t, plan t v -> t < unsent_time s ->\n    exists m, message_slot m = (t,v) /\\ validator_has_been_sent s m.\n\n  Definition sends_unique (s: validator_state) : Prop :=\n    forall m1, validator_has_been_sent s m1 ->\n    forall m2, validator_has_been_sent s m2 ->\n               message_slot m1 = message_slot m2 -> m1 = m2.\n\n  Lemma message_send_invariant_init s:\n    initial_validator_state s ->\n    sends_respect_plan s /\\ sends_fill_plan s /\\ sends_unique s.\n  Proof.\n    destruct s; simpl.\n    intros (-> & -> & -> & Hfinished).\n    destruct finished_send;[elim Hfinished;exact I|clear Hfinished].\n    unfold sends_respect_plan, sends_fill_plan, sends_unique;simpl.\n    pose proof PeanoNat.Nat.nlt_0_r.\n    firstorder.\n  Qed.\n\n  Lemma message_send_invariant_maintained\n        l s im s' om:\n    validator_valid l (s,im) ->\n    validator_transition l (s,im) = (s',om) ->\n    sends_respect_plan s /\\ sends_fill_plan s /\\ sends_unique s ->\n    sends_respect_plan s' /\\ sends_fill_plan s' /\\ sends_unique s'.\n  Proof.\n    intros Hvalid Htrans IH.\n    destruct l as [[c|]|].\n    + (* sending a proposal message, unsent_time advances and\n           the set of sent messages grows *)\n      destruct s.\n      simpl in Htrans.\n      inversion_clear Htrans.\n      simpl in Hvalid.\n      destruct im;[exfalso;exact Hvalid|].\n      destruct Hvalid as [_ [_ [Hplan Hflag]]].\n      destruct finished_send;[elim Hflag;exact I|clear Hflag].\n      destruct IH as [Hrespect [Hfill Hunique]].\n      split;[|split].\n      * unfold sends_respect_plan;simpl.\n        intros m [<-|Hsent];[solve[auto with arith]|].\n        apply Hrespect in Hsent.\n        simpl in Hsent.\n        pose proof (PeanoNat.Nat.lt_lt_succ_r (message_time m) time).\n        tauto.\n      * unfold sends_fill_plan;simpl.\n        intros t Hplan_t Hlt.\n        apply le_S_n, Lt.le_lt_or_eq in Hlt.\n        destruct Hlt as [H| ->].\n        -- specialize (Hfill t Hplan_t H).\n           simpl in Hfill. firstorder.\n        -- eexists;split;[|left;reflexivity].\n           simpl. congruence.\n      * revert Hunique;unfold sends_unique;simpl;intros Hunique.\n        assert (forall m, message_slot m = (time,v) -> ~In m sent).\n        {\n          clear -Hrespect.\n          intros m Hslot Hsent.\n          assert (message_time m < time) by (apply Hrespect;assumption).\n          apply PeanoNat.Nat.lt_neq in H.\n          revert Hslot H.\n          clear.\n          destruct m;simpl;congruence.\n        }\n        intros m1 [<-|Hm1] m2 [<-|Hm2].\n        -- congruence.\n        -- simpl. intro Hslot. symmetry in Hslot.\n           destruct (H m2 Hslot);assumption.\n        -- simpl. intro Hslot.\n           destruct (H m1 Hslot);assumption.\n        -- auto.\n    + assert (validator_sends s = validator_sends s'\n              /\\ forall t, plan t v -> t < unsent_time s <-> t < unsent_time s').\n      {\n        destruct s.\n        simpl in Htrans.\n        inversion_clear Htrans.\n        split;[reflexivity|].\n        destruct finished_send;[reflexivity|].\n        simpl.\n        clear IH.\n        split;[auto with arith|].\n        intro Hle.\n        apply le_S_n, Lt.le_lt_or_eq in Hle.\n        destruct Hle;[assumption|exfalso;subst t].\n        simpl in Hvalid.\n        destruct im;[solve[destruct Hvalid]|].\n        tauto.\n      }\n      clear Htrans.\n      revert IH.\n      unfold sends_respect_plan, sends_fill_plan, sends_unique.\n      set (st := unsent_time s) in H |- *.\n      set (s't := unsent_time s') in H |- *.\n      clearbody st s't.\n      destruct s, s';simpl in * |- *.\n      destruct H as [<- H].\n      intros [Ha [Hb Hc]].\n      firstorder.\n    + (* receiving a message, none of the parts of\n           the state mentioned in these properties change *)\n      destruct s.\n      simpl in Htrans.\n      destruct im;inversion_clear Htrans;assumption.\n  Qed.\n\n  Lemma message_send_invariant (s : validator_state) :\n    protocol_state_prop Validator s ->\n    sends_respect_plan s /\\ sends_fill_plan s /\\ sends_unique s.\n  Proof.\n    intro Hproto.\n    induction Hproto using @protocol_state_prop_ind.\n    - apply message_send_invariant_init;assumption.\n    - revert IHHproto;apply (message_send_invariant_maintained l s om s' om');apply Ht.\n  Qed.\n  Lemma message_send_invariant_preloaded (s : validator_state) :\n    protocol_state_prop (pre_loaded_with_all_messages_vlsm Validator) s ->\n    sends_respect_plan s /\\ sends_fill_plan s /\\ sends_unique s.\n  Proof.\n    intro Hproto.\n    induction Hproto using @protocol_state_prop_ind.\n    - apply message_send_invariant_init;assumption.\n    - revert IHHproto;apply (message_send_invariant_maintained l s om s' om');apply Ht.\n  Qed.\n\nEnd Define_Component.\nArguments validator_message _ _ : clear implicits.\nArguments validator_state _ _ : clear implicits.\nArguments Validator {C V} {EqC EqV} _ _ _ _.\n\n\n(** ** Composition and Proofs\n\nThis section defines the composed protocol,\nand gives proofs about it.\n*)\n\nSection Protocol_Proofs.\n  Context\n    (C V:Type)\n    {EqC: EqDecision C}\n    {EqV: EqDecision V}\n    (c0:C)\n    {Hweights: Measurable.Measurable V}\n    (plan : nat -> V -> Prop)\n    {plan_dec : RelDecision plan}\n    {HPlan : Plan V plan}\n    (ClientState := State.justification C V)\n    (estimator: list (validator_message C V) -> C -> Prop)\n    (validator_list: list V)\n    (validators_finite: FinFun.Listing validator_list)\n    {v0: Inhabited V}\n  .\n\n  Definition IM : V -> VLSM (validator_message C V) :=\n    fun v => Validator c0 plan estimator v.\n\n  Definition simple_liveness_VLSM :=\n    (Composition.composite_vlsm IM).\n\n  (** Constructing a variant to show that\n      a component's clock eventually ticks.\n   *)\n\n  Definition message_slots_before (t:nat) : list (nat * V) :=\n    filter (fun '(n,v) => bool_decide (plan n v)) (set_prod (seq 0 t) validator_list).\n\n  Lemma In_message_slots_before tm v t :\n    In (tm,v) (message_slots_before t) <-> (plan tm v /\\ tm < t).\n  Proof.\n    split.\n    - intro Hin.\n      apply filter_In in Hin.\n      destruct Hin as [Hin Hplan].\n      split.\n      + apply bool_decide_eq_true in Hplan.\n        assumption.\n      + rewrite in_prod_iff in Hin.\n        destruct Hin as [Hin_t _].\n        apply in_seq in Hin_t.\n        destruct Hin_t.\n        assumption.\n    - intros [Hplan Htime].\n      apply filter_In.\n      split.\n      + apply in_prod_iff.\n        split.\n        * apply in_seq. lia.\n        * apply validators_finite.\n      + apply bool_decide_eq_true.\n        assumption.\n  Qed.\n\n  Definition unreceived_message_count_before (t:nat) (s: validator_state C V) : nat :=\n    length (set_diff_filter (message_slots_before t)\n                            (map message_slot (validator_received s))).\n\n  Definition validator_ticks_before (t:nat) (s: validator_state C V) : nat :=\n     t - validator_time s.\n\n  (** The component variant is an upper bound on the number of transitions the component\n      can take before its clock exceeds <<t>>, by counting the number of plan\n      slots for which it hasn't sent or received a message, and the number\n      of times it can tick.\n   *)\n  Definition validator_variant (t:nat) (s: validator_state C V) : nat :=\n    unreceived_message_count_before t s\n    + validator_ticks_before t s.\n\n  Context\n    (constraint : composite_label IM -> composite_state IM * option (validator_message C V) -> Prop\n       := no_synch_faults_no_equivocation_constraint validators_finite IM\n                 (validator_clock c0 plan estimator)\n             message_time)\n    (X: VLSM (validator_message C V) := composite_vlsm IM constraint)\n  .\n\n  (** The overall variant used to show a given component eventually\n      ticks adds up the bound for each component.\n      To show that a given component eventually reaches a time <<t0>>,\n      an argument about the structure of the plan\n   *)\n  Definition eventually_ticks_variant t (s: vstate X) : nat :=\n    list_sum (map (fun v => validator_variant t (s v)) validator_list).\n\n  Lemma state_update_variant_progress:\n    forall t s i si',\n      validator_variant t si' < validator_variant t (s i) ->\n      eventually_ticks_variant t (state_update IM s i si') < eventually_ticks_variant t s.\n  Proof.\n    clear -validators_finite.\n    intros t s i si' Hs'.\n    set (s' := state_update IM s i si').\n    assert (forall v, validator_variant t (s' v) <= validator_variant t (s v)).\n    {\n      intro v.\n      unfold s',state_update.\n      destruct (decide (v = i)).\n      - destruct e. unfold eq_rect_r. simpl. apply PeanoNat.Nat.lt_le_incl. assumption.\n      - apply le_n.\n    }\n    unfold eventually_ticks_variant.\n    assert (In i validator_list) by (apply validators_finite).\n    revert H0.\n    clear X constraint validators_finite.\n    induction validator_list;simpl;intro Hin.\n    - exfalso;exact Hin.\n    - destruct Hin as [->|Hin].\n      + apply PeanoNat.Nat.add_lt_le_mono.\n        * replace (s' i) with si'. assumption.\n          unfold s',state_update.\n          destruct (decide (i = i));[|congruence].\n          destruct e.\n          reflexivity.\n        * clear -H.\n          induction l as [|a l'];simpl;[|specialize (H a)];Lia.lia.\n      + apply PeanoNat.Nat.add_le_lt_mono;auto.\n  Qed.\n\n  Definition received_were_sent s : Prop :=\n    forall i msg, validator_has_been_observed (s i) msg ->\n    let j := message_sender msg in has_been_sent (IM j) (s j) msg.\n\n  Lemma received_were_sent_invariant s:\n    protocol_state_prop X s ->\n    received_were_sent s.\n  Proof.\n    intro H.\n    pose (composite_has_been_sent_capability _ _ validators_finite _\n         : has_been_sent_capability X) as Hhbs.\n    pose (composite_has_been_observed_capability _ _ validators_finite _\n         : has_been_observed_capability X) as Hhbo.\n    assert (observed_were_sent_or_initial _ X _ _ s).\n    {\n      apply observed_were_sent_invariant;[|assumption].\n      clear.\n      intros l s om [_ [H _]].\n      exact H.\n    }\n    intros i msg Hi.\n    specialize (H0 msg (ex_intro _ i Hi)).\n    destruct H0 as [H0 | [k [[mk Hmk] H0]]]; [|inversion Hmk].\n    destruct H0 as [j Hj].\n    (* The [observed_were_sent_invariant] only says that\n       some component sent the message.\n       To finish, use the property from [message_send_invariant]\n       that the [message_sender] meaches the component ID.\n     *)\n    enough (message_sender msg = j) as <- by assumption.\n    apply protocol_state_project_preloaded with (i:=j) in H.\n    apply message_send_invariant_preloaded in H.\n    destruct H as [Hresp _].\n    specialize (Hresp msg Hj).\n    apply Hresp.\n  Qed.\n\n  Definition clock_limit_invariant (s: vstate X): Prop\n    := forall v t,\n      plan t v ->\n      validator_time (s v) < t ->\n      forall i, validator_time (s i) <= t.\n\n  Lemma clock_limit_invariant_init (s: vstate X):\n    vinitial_state_prop X s ->\n    clock_limit_invariant s.\n  Proof.\n    intros Hinit _ t _ _ i.\n    specialize (Hinit i).\n    cbn in Hinit.\n    destruct (s i).\n    simpl.\n    destruct Hinit as [-> _].\n    auto with arith.\n  Qed.\n\n  Lemma clock_limit_invariant_step l s im s' om:\n    protocol_transition X l (s,im) (s',om) ->\n    clock_limit_invariant s ->\n    clock_limit_invariant s'.\n  Proof.\n    intros Hptrans IH v t Hplan Hlt i.\n    specialize (IH v t Hplan).\n    assert (validator_time (s v) < t) as Hlt2.\n    {\n      apply PeanoNat.Nat.le_lt_trans with (validator_time (s' v));[|assumption].\n      apply (protocol_transition_project_any v) in Hptrans.\n      destruct Hptrans as [?|[lj [-> ?]]].\n      - rewrite H. reflexivity.\n      - destruct H as [_ Htrans].\n        revert Htrans.\n        apply validator_clock_monotone.\n    }\n    assert (forall i msg, message_slot msg = (t,v) ->\n                          ~has_been_observed (IM i) (s i) msg)\n           as Hunknown.\n    {\n      destruct Hptrans as [[Hproto _] _].\n      clear i.\n      intros i msg Hslot Hobserved.\n      pose proof (received_were_sent_invariant s Hproto i msg Hobserved) as Hsent.\n      replace (message_sender msg) with v in Hsent\n        by (destruct msg;simpl in Hslot |- *;congruence).\n      simpl in Hsent.\n      apply protocol_state_project_preloaded with (i:=v) in Hproto.\n      pose proof (message_send_invariant_preloaded _ _ _ _ _ Hproto) as Hsend_inv.\n      destruct Hsend_inv as [Hsend_inv _].\n      specialize (Hsend_inv msg Hsent).\n      destruct Hsend_inv as [_ [_ Hsend_early]].\n      clear -Hlt2 Hsend_early Hslot.\n      replace (message_time msg) with t in Hsend_early\n        by (destruct msg; simpl in Hslot |- *; congruence).\n      clear Hslot.\n      destruct (s v);simpl in Hlt2, Hsend_early.\n      destruct finished_send;lia.\n    }\n    specialize (IH Hlt2 i).\n    apply (protocol_transition_project_any i) in Hptrans.\n    destruct Hptrans as [|[li [-> Hptrans]]].\n    - rewrite <- H;assumption.\n    - simpl in Hptrans.\n      destruct Hptrans as [[_ [_ Hvalid]] Htrans].\n\n      specialize (Hunknown i).\n      set (si := s i) in *;clearbody si.\n      set (si' := s' i) in *;clearbody si'.\n      clear Hlt Hlt2.\n      clear s s'.\n\n      destruct li as [[c|]|].\n      + (* protosal *)\n        replace (validator_time si') with (validator_time si);[assumption|].\n        destruct si.\n        cbn in Htrans;inversion_clear Htrans;reflexivity.\n      + (* tick *)\n        destruct si.\n        cbn in Htrans; inversion_clear Htrans.\n        simpl in Hunknown, IH |- *.\n        fold (time < t).\n        apply PeanoNat.Nat.le_lteq in IH.\n        destruct IH as [| ->];[assumption|exfalso].\n\n        cbn in Hvalid.\n        destruct im;[exfalso;assumption|].\n        destruct Hvalid as [_ Hhave_plan].\n        specialize (Hhave_plan v Hplan).\n        apply in_map_iff in Hhave_plan.\n        destruct Hhave_plan as [m [Hslot HIn]].\n        exact (Hunknown m Hslot HIn).\n      + (* receive *)\n        replace (validator_time si') with (validator_time si);[assumption|].\n        destruct si.\n        destruct im;cbn in Htrans;inversion_clear Htrans;reflexivity.\n  Qed.\n\n  Lemma early_validator_limits_clock_advance\n        v t (H_plan : plan t v)\n        (s:vstate X):\n    protocol_state_prop X s ->\n    validator_time (s v) < t ->\n    forall i, validator_time (s i) <= t.\n  Proof.\n    intros Hproto H_time.\n    revert v t H_plan H_time.\n    change (clock_limit_invariant s).\n    apply protocol_state_has_trace in Hproto.\n    destruct Hproto as [is [tr [Htr Hinit]]].\n    apply clock_limit_invariant_init in Hinit.\n    induction Htr.\n    - assumption.\n    - apply IHHtr.\n      revert H Hinit.\n      apply clock_limit_invariant_step.\n  Qed.\n\n  Lemma sending_decreases_validator_variant t i c (si si':vstate (IM i)) im om\n        (H_protocol: protocol_state_prop (pre_loaded_with_all_messages_vlsm (IM i)) si)\n        (H_valid: validator_valid plan estimator i (Some (Proposal c)) (si, im))\n        (H_time: validator_time si < t)\n        (H_know_own_sends: forall m,\n            message_sender m = i ->\n            validator_has_been_observed si m ->\n            validator_has_been_sent c0 plan estimator i si m)\n    (H_transition: validator_transition i (Some (Proposal c)) (si, im) = (si', om))\n    :\n    validator_variant t si' < validator_variant t si.\n  Proof.\n    destruct si eqn:Heq_si.\n    destruct im;[solve[exfalso;exact H_valid]|].\n    assert (finished_send = false)\n      by (apply Bool.not_true_is_false;intro;subst finished_send;apply H_valid;exact I).\n    subst finished_send.\n    assert (plan time i) as H_plan by apply H_valid;clear H_valid.\n    simpl in H_transition.\n    inversion_clear H_transition.\n    unfold validator_variant.\n    unfold validator_ticks_before.\n    apply Plus.plus_lt_compat_r.\n\n    unfold unreceived_message_count_before.\n    assert (~In (time,i) (map message_slot received)) as H_msg_new.\n    {\n      (* by known_own_sends, we already sent it *)\n      assert (unsent_time si = time) as H_unsent_time by (rewrite Heq_si;reflexivity).\n      apply message_send_invariant_preloaded in H_protocol.\n      destruct H_protocol as [H_inv _].\n      unfold sends_respect_plan in H_inv.\n      intro H_in.\n      apply in_map_iff in H_in.\n      destruct H_in as [old_msg [H_old_slot H_in]].\n      destruct old_msg.\n      injection H_old_slot;clear H_old_slot;intros -> ->.\n      apply H_know_own_sends in H_in;[|reflexivity].\n      simpl in H_in.\n      apply H_inv in H_in.\n      simpl in H_in.\n      apply (PeanoNat.Nat.lt_irrefl time).\n      apply H_in.\n    }\n\n    simpl validator_received.\n    apply len_set_diff_map_set_add.\n    - assumption.\n    - apply In_message_slots_before.\n      split;assumption.\n  Qed.\n\n  (** If all validator clock are below the time used in the\n      variant, the the variant decreases.\n   *)\n  Lemma eventually_ticks_variant_progress t\n        l (s:vstate X) im s' om\n        (H_times : forall i, validator_time (s i) < t)\n    :\n    protocol_transition X l (s,im) (s',om) ->\n    eventually_ticks_variant t s' < eventually_ticks_variant t s.\n  Proof.\n    intros [Hvalid Htrans].\n    assert (received_were_sent s) as H_received_were_sent\n        by apply received_were_sent_invariant, Hvalid.\n    destruct l as [i li] eqn:Heq_l.\n    simpl in Htrans.\n    rename om into _om.\n    destruct (vtransition (IM i) li (s i, im)) as [si' om] eqn:H_transition.\n    inversion_clear Htrans.\n    destruct li as [[c|]|].\n    - (* When sending a message, the sender recording their\n         own message decreases the number of unreceived slots\n         in their own variant *)\n      apply state_update_variant_progress.\n      apply sending_decreases_validator_variant with c im om.\n      + apply protocol_state_project_preloaded.\n        apply Hvalid.\n      + apply Hvalid.\n      + apply H_times.\n      + clear -H_received_were_sent.\n        intros m Hsender Hobs.\n        rewrite <- Hsender.\n        apply (H_received_were_sent _ _ Hobs).\n      + apply H_transition.\n    - (* A node ticking decreases the clock-based apart\n         of the variant *)\n      apply state_update_variant_progress.\n      unfold vtransition in H_transition.\n      specialize (H_times i).\n      destruct (s i).\n      simpl in Hvalid, H_times, H_transition.\n      inversion_clear H_transition.\n      unfold validator_variant.\n      unfold validator_ticks_before.\n      apply Plus.plus_lt_compat_l.\n      simpl.\n      lia.\n    - (* Receiving a message fills one of the\n         receivers slots *)\n      apply state_update_variant_progress.\n      unfold vtransition in H_transition.\n      destruct (s i) eqn:Heq_si.\n      simpl in Hvalid.\n      simpl in H_transition.\n      (* message cannot be None *)\n      destruct im;[|solve[exfalso;apply Hvalid]].\n      inversion_clear H_transition.\n      unfold validator_variant.\n      apply Plus.plus_lt_compat_r.\n\n      rename Hvalid into Hcomposite_valid.\n      destruct (id Hcomposite_valid)\n        as [Hproto [_ [Hvalidator_valid [[[ix Hsent]| [k [[mk Hmk] _]]] _]]]]\n        ; [| inversion Hmk].\n      simpl in Hvalidator_valid.\n      (* The validity condition ensures that the exact\n         message has not been received before, but to\n         show there is also no previously-received message\n         for that slot we need to use the invariants *)\n      apply protocol_state_project_preloaded with (i:=ix) in Hproto.\n      pose Hproto as Hinvariants;apply message_send_invariant_preloaded in Hinvariants.\n\n      assert (message_sender v = ix) as Hsender.\n      {\n        destruct Hinvariants as [Hsend _].\n        apply Hsend in Hsent.\n        apply Hsent.\n      }\n      assert (~In (message_slot v) (map message_slot received)).\n      {\n        intro H_in.\n        apply in_map_iff in H_in.\n        destruct H_in as [v2 [Hslots Hin2]].\n        assert (v <> v2) as Hneq.\n        { (* because by the validity condition, new message [v]\n             cannot have already been received, but [Hin2: In v2 received]. *)\n          cbn in Hvalidator_valid.\n          rewrite Heq_si in Hvalidator_valid.\n          destruct v.\n          destruct Hvalidator_valid as [H_not_in _].\n          congruence.\n        }\n        assert (has_been_sent (IM (message_sender v2)) (s (message_sender v2)) v2).\n        {\n          apply H_received_were_sent with (i:=i).\n          rewrite Heq_si.\n          simpl.\n          assumption.\n        }\n        replace (message_sender v2) with ix in H\n          by (destruct v,v2;simpl in Hsender, Hslots |- *;congruence).\n        destruct Hinvariants as [_ [_ Hunique]].\n        unfold sends_unique in Hunique.\n        specialize (Hunique v Hsent v2 H).\n        symmetry in Hslots.\n        apply Hneq, Hunique, Hslots.\n      }\n      apply len_set_diff_map_set_add.\n      assumption.\n      apply (proj1 Hinvariants) in Hsent.\n      destruct v.\n      simpl in Hsent.\n      destruct Hsent as [Hplan [-> Htime_ix]].\n      apply In_message_slots_before.\n      split.\n      assumption.\n      apply PeanoNat.Nat.lt_le_trans with (unsent_time (s ix)).\n      apply Htime_ix.\n      clear -H_times.\n      specialize (H_times ix).\n      revert H_times.\n      destruct (s ix);simpl.\n      destruct finished_send;lia.\n  Qed.\n\n  Theorem eventually_ticks\n          s (Hproto: protocol_state_prop X s)\n          tr (Htr: infinite_protocol_trace_from X s tr):\n    forall v, exists n, validator_time (s v) < validator_time (destination (Streams.Str_nth n tr) v).\n  Proof.\n    intro v.\n    (* First, find a time greater than v's current clock for which it is in the plan *)\n    destruct (recurring_sends _ _ HPlan (validator_time (s v)) v) as [t [Hlt Hplan]].\n    (* Then strengthen the goal to finding a step where <<v>>'s clock is at least\n       <<t>> *)\n    cut (exists n, t <= validator_time (destination (Streams.Str_nth n tr) v));\n      [intros [n Hn];exists n;lia|].\n    (* Use [early_validator_limits_clock_advance] to reduce that to\n       to finding a time where any validators clock is greater than <<t>> *)\n    assert (forall n, protocol_state_prop X (destination (Streams.Str_nth n tr))) as Hall_proto.\n    {\n      intro n.\n      clear Hproto Hlt.\n      revert s tr Htr.\n      clear -n.\n      induction n;intros s tr Htr.\n      - destruct Htr.\n        simpl.\n        revert H.\n        apply protocol_transition_destination.\n      - destruct Htr.\n        apply (IHn s tl Htr).\n    }\n    pose proof (early_validator_limits_clock_advance _ _ Hplan) as clocks_inv.\n    cut (exists n, ~(forall i, validator_time (destination (Streams.Str_nth n tr) i) < S t)).\n    {\n      intros [n Htimes];exists n.\n      apply PeanoNat.Nat.nlt_ge.\n      contradict Htimes.\n      intro i.\n      apply le_n_S.\n      apply (clocks_inv _ (Hall_proto n)).\n      assumption.\n    }\n    (*\n       This happens within <<validator_variant (S t) s>> steps, by well-foudned\n       induction on the remaining value of the variant.\n       First sharpen the claim to existing in a given prefix of the stream.\n     *)\n    remember (eventually_ticks_variant (S t) s) as len.\n    set (P := fun (s:vstate X) => forall i, validator_time (s i) < S t).\n    cut (Exists (fun item => ~P (destination item))\n                (StreamExtras.stream_prefix tr len)).\n    {\n      intro H.\n      apply Exists_exists in H.\n      destruct H as [x [Hin HP]].\n      apply StreamExtras.stream_prefix_in in Hin.\n      destruct Hin as [k [_ Hnth]].\n      exists k.\n      rewrite Hnth.\n      assumption.\n    }\n    (*\n      Now we set up for the induction.\n     *)\n    assert (P s) as Hstart.\n    {\n      intro i.\n      apply le_n_S.\n      apply clocks_inv;assumption.\n    }\n    assert (forall s, Decision (P s)) as P_dec.\n    {\n      intros s0.\n      unfold P.\n      eapply Decision_iff.\n      symmetry.\n      eapply ListExtras.forall_finite;apply validators_finite.\n      apply Forall_dec.\n      intro x.\n      apply Compare_dec.lt_dec.\n    }\n    clear Hall_proto clocks_inv Hproto Hlt.\n    revert s Heqlen tr Htr Hstart.\n    clear -P_dec.\n    apply (Wf_nat.lt_wf_ind len);clear len.\n    intros len IH s Hlen tr Htr HP.\n    destruct Htr.\n    pose proof (eventually_ticks_variant_progress _ _ _ _ _ _ HP H).\n    rewrite <- Hlen in H0.\n    specialize (IH _ H0 s (eq_refl _) tl Htr).\n    destruct (decide (P s));last first.\n    - destruct len;[exfalso;lia|].\n      apply Exists_cons_hd.\n      assumption.\n    - remember (eventually_ticks_variant (S t) s) as len' in IH, H0.\n      specialize (IH p).\n      clear -H IH H0.\n      unfold lt in H0.\n      destruct len;[exfalso;lia|].\n      apply le_S_n in H0.\n      simpl.\n      apply Exists_cons_tl.\n      pose proof @StreamExtras.stream_prefix_segment as Hprefix.\n      specialize (Hprefix _ tl len' len H0).\n      progress simpl in Hprefix.\n      rewrite <- Hprefix.\n      apply Exists_app.\n      left.\n      assumption.\n  Qed.\nEnd Protocol_Proofs.\n", "meta": {"author": "zunction", "repo": "casper-cbc-proofs", "sha": "92493810dd32a8301882f9eb8a0488a6ac9d0cd1", "save_path": "github-repos/coq/zunction-casper-cbc-proofs", "path": "github-repos/coq/zunction-casper-cbc-proofs/casper-cbc-proofs-92493810dd32a8301882f9eb8a0488a6ac9d0cd1/VLSM/Liveness/SimpleFragileProtocol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.34158249273565866, "lm_q1q2_score": 0.23315523767644913}}
{"text": "Require Import Util SizeInduction Get MapDefined Coq.Classes.RelationClasses.\nRequire Import IL Var Val OptionR AllInRel.\nRequire Import CMap CMapDomain CMapPartialOrder CMapJoinSemiLattice.\nRequire Import Analysis AnalysisForwardSSA Subterm CSet MapAgreement RenamedApart.\nRequire Import Infra.PartialOrder Infra.Lattice Infra.WithTop.\nRequire Import LabelsDefined Annotation.\nRequire Import Reachability ReachabilityAnalysisCorrectSSA.\nRequire Import ConstantPropagation ConstantPropagationSound ConstantPropagationAnalysis.\nRequire Import DomainSSA FiniteFixpointIteration.\n\nLocal Arguments proj1_sig {A} {P} e.\nLocal Arguments length {A} e.\nLocal Arguments forward {sT} {D} {H} {H0} exp_transf reach_transf ZL ZLIncl st ST d anr.\n\nNotation \"'getAE' X\" := (proj1_sig (fst (fst X))) (at level 10, X at level 0).\n\nLocal Arguments exist {A} {P} x _.\n\nLemma domenv_map_proper D `{PartialOrder D} Z\n  : Proper (poEq ==> poEq) (fun AE => domenv AE ⊝ Z).\nProof.\n  unfold Proper, respectful; intros.\n  general induction Z; simpl; eauto using poEq_list_struct.\nQed.\n\n\nLemma domjoin_list_domenv D `{JoinSemiLattice D} Z (Y:list (option D)) AE\n  (ND : NoDupA eq Z)\n  (LEN : ❬Z❭ = ❬Y❭)\n  : Y ⊑ domenv (domjoin_list AE Z Y) ⊝ Z.\nProof.\n  general induction LEN; simpl; eauto.\n  eapply poLe_list_struct.\n  - unfold domenv at 1.\n    rewrite domupd_var_eq; eauto.\n  - eapply PIR2_get; eauto with len.\n    intros; inv_get.\n    unfold domenv. rewrite domupd_var_ne; eauto.\n    exploit IHLEN; eauto.\n    + eapply PIR2_nth in H3; eauto; dcr; inv_get.\n      eapply H6.\n    + intro EQ; invc EQ. inv ND. eapply H5.\n      eapply get_InA in H2. eauto.\nQed.\n\nLemma cp_sound sT AE ZL s (ST:subTerm s sT) ZLIncl ra anr\n  : let X := @forward sT _ _ _ (@cp_trans) (@cp_reach) ZL ZLIncl s ST AE anr in\n    renamedApart s ra\n    -> annotation s anr\n    -> labelsDefined s (length ZL)\n    -> poEq (fst X) (AE,anr)\n    -> disj (list_union (of_list ⊝ ZL)) (snd (getAnn ra))\n    -> paramsMatch s (length ⊝ ZL)\n    -> (forall n Z, get ZL n Z -> NoDupA eq Z)\n    -> cp_sound (domenv (proj1_sig AE))\n               (zip pair ZL (lookup_list (domenv (proj1_sig AE)) ⊝ ZL)) s anr.\nProof.\n  intros LET RA ANN LD EQ1 DISJ PM NODUP. subst LET.\n  general induction LD; invt @renamedApart;\n    try invt @annotation; simpl in *; simpl; invt @paramsMatch;\n      simpl in *; dcr;\n        repeat let_pair_case_eq; repeat let_case_eq; repeat simpl_pair_eqs; subst;\n          simpl in *; try invtc @ann_R; subst.\n  - set_simpl. clear_trivial_eqs.\n    + pose proof EQ1 as EQ3.\n      eapply forward_domupdd_eq in EQ3; eauto.\n      * econstructor; eauto.\n        eapply IHLD; eauto.\n        split; simpl. rewrite <- EQ1 at 2.\n        eapply forward_ext; eauto using cp_trans_ext, cp_reach_ext.\n        rewrite <- EQ3. symmetry; eauto.\n        rewrite <- H10 at 2.\n        eapply forward_ext; eauto using cp_trans_ext, cp_reach_ext.\n        rewrite <- EQ3. symmetry; eauto.\n        pe_rewrite. eapply disj_2_incl; eauto with cset.\n        intros.\n        rewrite EQ1 in EQ3.\n        specialize (EQ3 x). unfold domenv.\n        eapply option_R_inv in EQ3.\n        rewrite EQ3. simpl. rewrite domupd_var_eq; try reflexivity.\n      * rewrite renamedApart_occurVars; eauto. pe_rewrite.\n        eapply renamedApart_disj in H4; eauto.\n        pe_rewrite. revert DISJ H4; clear_all; cset_tac.\n  - clear_trivial_eqs.\n    set_simpl.\n    exploit (forward_if_inv _ _ _ _ _ _ EQ1); eauto.\n    repeat rewrite renamedApart_occurVars; eauto;\n      pe_rewrite; eauto.\n    repeat rewrite renamedApart_occurVars; eauto;\n      pe_rewrite; eauto with cset.\n    rewrite forward_ext in EQ1; try eapply H; try reflexivity; eauto using cp_reach_ext, cp_trans_ext; try reflexivity.\n    econstructor; eauto.\n    + eapply IHLD1; eauto.\n      split; eauto. pe_rewrite. eapply disj_2_incl; eauto.\n    + eapply IHLD2; eauto.\n      split; eauto.\n      rewrite forward_ext; eauto using cp_reach_ext, cp_trans_ext. symmetry; eauto.\n      pe_rewrite. symmetry. eapply disj_2_incl; eauto with cset.\n  - econstructor; eauto.\n  - inv_get.\n    econstructor; eauto using zip_get_eq.\n    intros. cases in EQ1. inv_get.\n    set_simpl.\n    unfold domjoin_listd in EQ1.\n    destruct AE as [AE pf]; simpl in *; clear_trivial_eqs.\n    unfold poEq in EQ1. simpl in EQ1.\n    rewrite (get_nth nil H3) in *.\n    exploit NODUP; eauto.\n    rewrite lookup_list_map.\n    symmetry in EQ1.\n    rewrite domenv_map_proper; eauto.\n    eapply domjoin_list_domenv; eauto with len.\n  - clear_trivial_eqs.\n    eapply PIR2_get in H21; try eassumption. clear H20.\n    exploit (snd_forwardF_inv _ _ _ _ _ _ _ H21); eauto with len.\n    exploit (snd_forwardF_inv' _ _ _ _ _ _ _ H21); eauto with len.\n    Transparent poEq. simpl poEq in H21.\n    repeat PIR2_eq_simpl. repeat ST_pat.\n    Opaque poEq.\n    set (FWt:=(forward cp_trans cp_reach (fst ⊝ F ++ ZL) ZLIncl0 t ST0 AE ta)) in *.\n    set (FWF:=forwardF (snd FWt) (forward cp_trans cp_reach (fst ⊝ F ++ ZL) ZLIncl0)\n                       F sa (fst (fst FWt)) STF) in *.\n    assert (fst (fst (FWt)) ≣ AE /\\\n            forall (n : nat) (Zs : params * stmt) (r : ann bool) (ST0 : subTerm (snd Zs) sT),\n              get F n Zs ->\n              get sa n r ->\n              fst\n                (fst\n                   (forward cp_trans cp_reach (fst ⊝ F ++ ZL) (ZLIncl_ext ZL eq_refl ST ZLIncl) (snd Zs) ST0 AE r))\n                ≣ AE). {\n      pe_rewrite. set_simpl.\n      eapply forwardF_agree_get; try eassumption.\n      - eauto with len.\n      - rewrite <- EQ1. unfold FWF. reflexivity.\n      - unfold FWt. reflexivity.\n      - pe_rewrite. eauto with ren.\n      - pe_rewrite.\n        eapply disj_Dt_getAnn; eauto.\n      - eapply funConstr_disj_ZL_getAnn; eauto.\n      - eapply disj_1_incl.\n        eapply funConstr_disj_ZL_getAnn; eauto.\n        rewrite List.map_app. rewrite list_union_app.\n        clear_all. cset_tac.\n      - eapply cp_trans_ext.\n      - eapply cp_reach_ext.\n    } dcr.\n\n    assert (forall (n : nat) (r : ann bool) (Zs : params * stmt),\n       get sa n r ->\n       get F n Zs ->\n       forall STZs : subTerm (snd Zs) sT,\n         (snd\n            (fst\n               (forward cp_trans cp_reach (fst ⊝ F ++ ZL)\n                        ZLIncl0 (snd Zs) STZs AE r))) ≣ r). {\n      eapply (@snd_forwardF_inv_get) with (BL:=(snd FWt)); eauto.\n      subst FWt; eauto with len.\n      subst FWt; eauto with len.\n      rewrite <- H2 at 2. unfold FWF.\n      rewrite forwardF_ext'; try reflexivity; eauto.\n      eapply cp_trans_ext; eauto.\n      eapply cp_reach_ext; eauto.\n      symmetry; eauto.\n      eapply cp_trans_ext; eauto.\n      eapply cp_reach_ext; eauto.\n    }\n    econstructor; eauto.\n    + intros. inv_get. exploit H7; eauto.\n      assert (EQ:\n                ((fun Zs0 : params * stmt =>\n      (fst Zs0, lookup_list (domenv (proj1_sig AE)) (fst Zs0))) ⊝ F ++\n     pair ⊜ ZL (lookup_list (domenv (proj1_sig AE)) ⊝ ZL))\n              = zip pair (fst ⊝ F ++ ZL) (lookup_list (domenv (proj1_sig AE)) ⊝ (fst ⊝ F ++ ZL))). {\n        rewrite !List.map_app. rewrite !zip_app; eauto with len.\n        rewrite !zip_map_l. rewrite !zip_map_r.\n        f_equal; eauto.\n        clear_all. general induction F; simpl; f_equal; eauto.\n      }\n      rewrite EQ.\n      eapply H0; try eassumption.\n      -- eauto.\n      -- eauto.\n      -- eauto with len.\n      -- split; simpl; eauto.\n      -- set_simpl.\n         eapply disj_2_incl.\n         eapply funConstr_disj_ZL_getAnn; eauto with ren.\n         eapply incl_list_union; eauto using zip_get.\n      -- eauto.\n      -- intros ? ? GET2. eapply get_app_cases in GET2. destruct GET2.\n         inv_get. edestruct H5; eauto.\n         dcr. inv_get. eapply NODUP; eauto.\n    + assert (EQ:\n                (fun Zs : params * stmt => (fst Zs, lookup_list (domenv (proj1_sig AE)) (fst Zs)))\n                  ⊝ F ++ pair ⊜ ZL (lookup_list (domenv (proj1_sig AE)) ⊝ ZL)\n                = zip pair (fst ⊝ F ++ ZL) (lookup_list (domenv (proj1_sig AE)) ⊝ (fst ⊝ F ++ ZL))). {\n        rewrite !List.map_app. rewrite !zip_app; eauto with len.\n        rewrite !zip_map_l. rewrite !zip_map_r.\n        f_equal; eauto.\n        clear_all. general induction F; simpl; f_equal; eauto.\n      }\n      rewrite EQ.\n      eapply IHLD; eauto with len.\n      * split; simpl; eauto.\n      * pe_rewrite. set_simpl.\n        rewrite List.map_app. rewrite list_union_app.\n        eapply disj_union_left.\n        -- symmetry.\n           eapply funConstr_disj_Dt; eauto.\n        -- symmetry. eapply disj_incl; eauto.\n      * intros ? ? GET2. eapply get_app_cases in GET2. destruct GET2.\n        inv_get. edestruct H5; eauto.\n        dcr. inv_get. eapply NODUP; eauto.\n        Grab Existential Variables.\n        eauto.\nQed.\n\nDefinition cp_reachability_sound (sT:stmt)\n           ZL BL s (d:VDom (occurVars sT) _) r (ST:subTerm s sT) ZLIncl\n           (EQ:(fst (forward cp_trans cp_reach ZL ZLIncl s ST d r)) ≣ (d,r)) ra\n    (Ann: annotation s r) (RA:renamedApart s ra)\n    (DefZL: labelsDefined s (length ZL))\n    (DefBL: labelsDefined s (length BL))\n    (BL_le: poLe (snd (forward cp_trans cp_reach ZL ZLIncl s ST d r)) BL)\n    (Disj:disj (list_union (of_list ⊝ ZL)) (snd (getAnn ra)))\n  : reachability (cop2bool (domenv (proj1_sig d))) Sound BL s r.\nProof.\n  eapply reachability_sound with (pr:=fun d => cop2bool (domenv (proj1_sig d)));\n    eauto using cp_trans_ext, cp_reach_ext.\n  - unfold cp_reach, cop2bool, Dom; intros;\n      repeat cases; simpl in *; unfold Dom in *; clear_trivial_eqs; eauto.\n    + exfalso. eapply H. rewrite COND; simpl. eauto.\n    + exfalso. eapply H. rewrite COND; simpl. eauto.\n    + exfalso. eapply H. rewrite COND; simpl. eauto.\n  - unfold cp_reach, cop2bool, Dom; intros;\n      repeat cases; simpl in *; unfold Dom in *; clear_trivial_eqs; eauto.\n    + exfalso. eapply H. rewrite COND; simpl. eauto.\n    + exfalso. eapply H. rewrite COND0; simpl. eauto.\n    + exfalso. eapply H. rewrite COND; simpl. eauto.\nQed.\n\nLemma cp_sound_reorga s (a:ann bool) ra (RA:renamedApart s ra)\n      (AE : VDom (occurVars s) (withTop val)) an\n      (EQ : @step _ (constant_propagation_analysis RA) (AE, @exist _ _ a an)\n                  ≣ (AE, @exist _ _ a an))\n  : fst\n      (forward cp_trans cp_reach nil (incl_empty positive (occurVars s)) s (subTerm_refl s) AE a)\n      ≣ (AE, a).\nProof.\n  rewrite pair_eta at 1.\n  eapply poEq_struct.\n  - eapply poEq_fst in EQ. simpl fst at 2 in EQ.\n    etransitivity; eauto.\n  - eapply poEq_snd in EQ. simpl snd at 2 in EQ.\n    revert EQ.\n    case_eq (snd (@step _ (constant_propagation_analysis RA) (AE, exist a an))); intros.\n    etransitivity; eauto; swap 1 2.\n    + eapply poEq_sig_struct'. eauto.\n    + unfold step in H. simpl in H.\n      eapply poEq_sig_struct'. rewrite H. rewrite EQ. reflexivity.\nQed.\n\nLemma cp_sound_nil s (AEanr:VDom (occurVars s) (withTop val) * {a : ann bool | annotation s a})\n      ra\n      (RA:renamedApart s ra)\n  : poEq (@step _ (constant_propagation_analysis RA) (AEanr)) (AEanr)\n    -> paramsMatch s nil\n    -> ConstantPropagationSound.cp_sound (domenv (proj1_sig (fst AEanr)))\n                                        nil s (proj1_sig (snd AEanr)).\nProof.\n  intros. destruct AEanr as [AE [anr an]].\n  eapply cp_sound with (ZL:=nil) (ST:=@subTerm_refl _); eauto.\n  - eapply cp_sound_reorga. eauto.\n  - simpl. cset_tac.\n  - isabsurd.\nQed.\n\nDefinition cp_reachability_sound_nil s\n           (AEanr:VDom (occurVars s) (withTop val) * {a : ann bool | annotation s a})\n           ra\n           (RA:renamedApart s ra)\n  : poEq (@step _ (constant_propagation_analysis RA) (AEanr)) (AEanr)\n    -> paramsMatch s nil\n    -> reachability (cop2bool (domenv (proj1_sig (fst AEanr))))\n                   Sound nil s (proj1_sig (snd AEanr)).\nProof.\n  intros. destruct AEanr as [AE [anr an]].\n  eapply cp_reachability_sound with (BL:=nil) (ZL:=nil); eauto.\n  - eapply cp_sound_reorga. eapply H.\n  - assert (❬snd\n    (forward cp_trans cp_reach nil (incl_empty positive (occurVars s)) s\n             (subTerm_refl s) (fst (AE, exist anr an)) (proj1_sig (snd (AE, exist anr an))))❭ = 0).\n    eauto with len.\n    destruct (snd\n    (forward cp_trans cp_reach nil (incl_empty positive (occurVars s)) s\n             (subTerm_refl s) (fst (AE, exist anr an)) (proj1_sig (snd (AE, exist anr an)))));\n      eauto. isabsurd.\n  - simpl. cset_tac.\nQed.\n\nLemma constantPropagationAnalysis_getAnn s ra\n      (RA:renamedApart s ra)\n  :  getAnn\n       (proj1_sig (snd (constantPropagationAnalysis RA))) = true.\nProof.\n  unfold constantPropagationAnalysis.\n  eapply safeFixpoint_induction.\n  - simpl. rewrite getAnn_setTopAnn. reflexivity.\n  - intros. simpl.\n    rewrite forward_fst_snd_getAnn. eauto.\nQed.\n\nLemma constantPropagation_init_inv s ra (RA:renamedApart s ra)\n  : forall x : var,\n    x \\In freeVars s ->\n    (DomainSSA.domenv\n       (proj1_sig (fst (constantPropagationAnalysis RA)))) x === ⎣Top⎦.\nProof.\n  intros. unfold constantPropagationAnalysis, domenv, constant_propagation_analysis.\n  eapply makeForwardAnalysisSSA_init_env. eauto.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/ValueOpts/ConstantPropagationAnalysisCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.23313040745105107}}
{"text": "From VLSM.Lib Require Import Itauto.\nFrom Coq Require Import FunctionalExtensionality.\nFrom stdpp Require Import prelude finite.\nFrom VLSM.Lib Require Import Preamble ListExtras StdppExtras.\nFrom VLSM.Core Require Import VLSM VLSMProjections Composition.\nFrom VLSM.Core Require Import Validator ProjectionTraces.\nFrom VLSM.Core Require Import BaseELMO UMO.\n\n(** * MO Protocol Definitions and Properties\n\n  This module contains definitions and properties of MO components and\n  the MO protocol.\n*)\n\nSection sec_MO.\n\nContext\n  {Address : Type}\n  `{EqDecision Address}\n  (State := @State Address)\n  (Observation := @Observation Address)\n  (Message := @Message Address).\n\n(**\n  A message is valid for MO if one of the following is the case:\n\n  - it has no observations and its address belongs to the set of allowed\n    addresses (as determined by the predicate <<P>>)\n  - its last observation was another valid message which was sent\n  - its last observation was another valid message which was received\n    and the messages observed previously are also valid\n*)\nInductive MO_msg_valid (P : Address -> Prop) : Message -> Prop :=\n| MO_mv_nil :\n    forall m : Message,\n      obs (state m) = [] -> P (adr (state m)) -> MO_msg_valid P m\n| MO_mv_send :\n    forall m : Message,\n      MO_msg_valid P m -> MO_msg_valid P (m <*> MkObservation Send m)\n| MO_mv_recv :\n    forall m mr : Message,\n      MO_msg_valid P m -> MO_msg_valid P mr -> MO_msg_valid P (m <*> MkObservation Receive mr).\n\nSection sec_alternative_definition_of_validity.\n\n(** ** Alternative definition of validity\n\n  The above constructors of [MO_msg_valid] may not be the most readable,\n  so we will provide an alternative version of this inductive\n  definition (called [MO_msg_valid_alt]) and prove them equivalent.\n\n  If [MO_msg_valid_alt_sends] holds for <<m>>, then every possible suffix of\n  observations from <<m>> is the same as the observations from a message <<m'>>\n  which was the next message that was sent after the suffix. Also, the addresses\n  of <<m>> and <<m'>> have to agree.\n*)\nDefinition MO_msg_valid_alt_sends (m : Message) : Prop :=\n  forall (k : nat) (suffix : list Observation) (m' : Message),\n    lastn k (obs (state m)) = addObservation' (MkObservation Send m') suffix ->\n      obs (state m') = suffix /\\ adr (state m') = adr (state m).\n\n(**\n  If [MO_msg_valid_alt_recvs'] holds for <<valid>> and <<m>>, this means\n  that for every suffix of observations from <<m>>, the message <<m'>>, which\n  was the next message received after the suffix, is valid.\n\n  Here, validity is determined by an arbitrary predicate. Ultimately, we want\n  to replace this arbitrary predicate with [MO_msg_valid_alt], the alternative\n  definition of message validity for MO.\n*)\nDefinition MO_msg_valid_alt_recvs' (valid : Message -> Prop) (m : Message) : Prop :=\n  forall (k : nat) (suffix : list Observation) (m' : Message),\n    lastn k (obs (state m)) = addObservation' (MkObservation Receive m') suffix ->\n      valid m'.\n\n(**\n  A message is valid for MO (according to the alternative definition) if one\n  of the following holds:\n\n  - its address belongs to the set of allowed addresses (as determined by <<P>>)\n  - it satisfies [MO_msg_valid_alt_sends]\n  - it satisfies [MO_msg_valid_alt_recvs'], with [MO_msg_valid_alt] applied to\n    <<P>> used as the validity predicate\n*)\nInductive MO_msg_valid_alt (P : Address -> Prop) (m : Message) : Prop :=\n{\n  P_adr_state : P (adr (state m));\n  MO_msg_valid_alt_sends' : MO_msg_valid_alt_sends m;\n  MO_msg_valid_alt_recvs'' : MO_msg_valid_alt_recvs' (MO_msg_valid_alt P) m;\n}.\n\n(**\n  Now we just need to define the final version of [MO_msg_valid_alt_recvs],\n  in which the validity predicate is set to [MO_msg_valid_alt].\n*)\nDefinition MO_msg_valid_alt_recvs (P : Address -> Prop) (m : Message) : Prop :=\n  MO_msg_valid_alt_recvs' (MO_msg_valid_alt P) m.\n\n(**\n  For some proofs to go through, we will need \"bounded\" versions of the\n  [Send] and [Receive] parts of the alternative definition.\n\n  By bounded, we mean that we will only look for suffixes at most as long\n  as the whole list of observations of the given message (the suffix can't\n  be any longer than that of course; this matters for purely technical\n  reasons).\n*)\n\nDefinition MO_msg_valid_alt_sends_bounded (m : Message) : Prop :=\n  forall (k : nat) (suffix : list Observation) (m' : Message),\n    k <= length (obs (state m)) ->\n    lastn k (obs (state m)) = addObservation' (MkObservation Send m') suffix ->\n      obs (state m') = suffix /\\ adr (state m') = adr (state m).\n\nDefinition MO_msg_valid_alt_recvs_bounded (P : Address -> Prop) (m : Message) : Prop :=\n  forall (k : nat) (suffix : list Observation) (m' : Message),\n    k <= length (obs (state m)) ->\n    lastn k (obs (state m)) = addObservation' (MkObservation Receive m') suffix ->\n      MO_msg_valid_alt P m'.\n\n(** The bounded versions are equivalent to the original ones. *)\n\nLemma MO_msg_valid_alt_sends_shorten :\n  forall (m : Message),\n    MO_msg_valid_alt_sends m <-> MO_msg_valid_alt_sends_bounded m.\nProof.\n  split.\n  - unfold MO_msg_valid_alt_sends, MO_msg_valid_alt_sends_bounded.\n    by intros Hs k suffix m' _ Hlast; eapply Hs.\n  - unfold MO_msg_valid_alt_sends, MO_msg_valid_alt_sends_bounded.\n    intros Hs k suffix m' Hlast.\n    destruct (decide (k <= length (obs (state m)))).\n    + by eapply Hs.\n    + apply (Hs (length (obs (state m)))); [lia |].\n      by rewrite lastn_ge in *; [| lia | lia].\nQed.\n\nLemma MO_msg_valid_alt_recvs_shorten :\n  forall (P : Address -> Prop) (m : Message),\n    MO_msg_valid_alt_recvs P m <-> MO_msg_valid_alt_recvs_bounded P m.\nProof.\n  split.\n  - unfold MO_msg_valid_alt_recvs, MO_msg_valid_alt_recvs', MO_msg_valid_alt_recvs_bounded.\n    by intros Hr k suffix m' _ Hlast; eapply Hr.\n  - unfold MO_msg_valid_alt_recvs, MO_msg_valid_alt_recvs', MO_msg_valid_alt_recvs_bounded.\n    intros Hr k suffix m' Hlast.\n    destruct (decide (k <= length (obs (state m)))).\n    + by eapply Hr.\n    + apply (Hr (length (obs (state m))) suffix); [lia |].\n      by rewrite lastn_ge in *; [| lia | lia].\nQed.\n\n(**\n  Now we need a collection of lemmas that tell us what happens when we extend\n  a message with a new observation of a sent message. We need to do this\n  separately for both the \"sends\" and the \"recvs\" parts of the alternative\n  definition.\n*)\n\nLemma MO_msg_valid_alt_sends_Send :\n  forall m : Message,\n    MO_msg_valid_alt_sends m -> MO_msg_valid_alt_sends (m <*> MkObservation Send m).\nProof.\n  unfold MO_msg_valid_alt_sends; cbn; unfold addObservation'.\n  intros m Hvalid k suffix m' Hlast.\n  rewrite lastn_cons in Hlast; case_decide.\n  - by inversion Hlast.\n  - by eapply Hvalid.\nQed.\n\nLemma MO_msg_valid_alt_recvs_Send :\n  forall (P : Address -> Prop) (m : Message),\n    MO_msg_valid_alt_recvs P m -> MO_msg_valid_alt_recvs P (m <*> MkObservation Send m).\nProof.\n  unfold MO_msg_valid_alt_recvs, MO_msg_valid_alt_recvs'; cbn; unfold addObservation'.\n  intros P m Hvalid k suffix m' Hlast.\n  rewrite lastn_cons in Hlast; case_decide.\n  - by inversion Hlast.\n  - by eapply Hvalid.\nQed.\n\n(**\n  When we put the above lemmas together, we get a lemma for [MO_msg_valid_alt]\n  which corresponds to one of the constructors of [MO_msg_valid].\n*)\n\nLemma MO_msg_valid_alt_Send :\n  forall (P : Address -> Prop) (m : Message),\n    MO_msg_valid_alt P m -> MO_msg_valid_alt P (m <*> MkObservation Send m).\nProof.\n  intros P m [Hs Hr]; constructor; cbn; [done | |].\n  - by apply MO_msg_valid_alt_sends_Send.\n  - by apply MO_msg_valid_alt_recvs_Send.\nQed.\n\n(** We will also need the converses of all these lemmas. *)\n\nLemma MO_msg_valid_alt_sends_Send_conv :\n  forall m : Message,\n    MO_msg_valid_alt_sends (m <*> MkObservation Send m) -> MO_msg_valid_alt_sends m.\nProof.\n  intros m.\n  rewrite (MO_msg_valid_alt_sends_shorten m).\n  unfold MO_msg_valid_alt_sends; cbn; unfold addObservation'.\n  intros Hv k suffix m' Hlen Hlast.\n  destruct (decide (1 + length (obs (state m)) <= k)); [lia |].\n  apply Hv with k. rewrite lastn_cons. by case_decide; [lia |].\nQed.\n\nLemma MO_msg_valid_alt_recvs_Send_conv :\n  forall (P : Address -> Prop) (m : Message),\n    MO_msg_valid_alt_recvs P (m <*> MkObservation Send m) -> MO_msg_valid_alt_recvs P m.\nProof.\n  intros P m.\n  rewrite (MO_msg_valid_alt_recvs_shorten P m).\n  unfold MO_msg_valid_alt_recvs, MO_msg_valid_alt_recvs'; cbn; unfold addObservation'.\n  intros Hv k suffix m' Hlen Hlast.\n  destruct (decide (1 + length (obs (state m)) <= k)); [lia |].\n  apply (Hv k suffix). rewrite lastn_cons.\n  by case_decide; [lia |].\nQed.\n\nLemma MO_msg_valid_alt_Send_conv :\n  forall (P : Address -> Prop) (m : Message),\n    MO_msg_valid_alt P (m <*> MkObservation Send m) -> MO_msg_valid_alt P m.\nProof.\n  intros P m [Hvs Hvr]; split; [done | |].\n  - by apply MO_msg_valid_alt_sends_Send_conv.\n  - by apply MO_msg_valid_alt_recvs_Send_conv.\nQed.\n\n(**\n  We need another collection of lemmas, but this time for the case when a new\n  observation was a received message.\n*)\n\nLemma MO_msg_valid_alt_sends_Receive :\n  forall m mr : Message,\n    MO_msg_valid_alt_sends m ->\n      MO_msg_valid_alt_sends (m <*> MkObservation Receive mr).\nProof.\n  unfold MO_msg_valid_alt_sends; cbn; unfold addObservation'.\n  intros m mr Hm k suffix m' Hlast.\n  rewrite lastn_cons in Hlast; case_decide.\n  - by inversion Hlast.\n  - by apply Hm with k.\nQed.\n\nLemma MO_msg_valid_alt_recvs_Receive :\n  forall (P : Address -> Prop) (m mr : Message),\n    MO_msg_valid_alt_recvs P m -> MO_msg_valid_alt P mr ->\n      MO_msg_valid_alt_recvs P (m <*> MkObservation Receive mr).\nProof.\n  unfold MO_msg_valid_alt_recvs, MO_msg_valid_alt_recvs'; cbn; unfold addObservation'.\n  intros P m mr Hm Hmr k suffix m' Hlast.\n  rewrite lastn_cons in Hlast; case_decide.\n  - by inversion Hlast; subst; clear Hlast.\n  - by apply (Hm k suffix).\nQed.\n\nLemma MO_msg_valid_alt_Receive :\n  forall (P : Address -> Prop) (m mr : Message),\n    MO_msg_valid_alt P m -> MO_msg_valid_alt P mr ->\n      MO_msg_valid_alt P (m <*> MkObservation Receive mr).\nProof.\n  intros P m mr [Hs Hr] Hmr; split; cbn; [done | |].\n  - by apply MO_msg_valid_alt_sends_Receive.\n  - by apply MO_msg_valid_alt_recvs_Receive.\nQed.\n\n(** We need the converses of these lemmas too. *)\n\nLemma MO_msg_valid_alt_sends_Receive_conv :\n  forall m mr : Message,\n    MO_msg_valid_alt_sends (m <*> MkObservation Receive mr) ->\n      MO_msg_valid_alt_sends m.\nProof.\n  intros m mr.\n  rewrite (MO_msg_valid_alt_sends_shorten m).\n  unfold MO_msg_valid_alt_sends; cbn; unfold addObservation'.\n  intros Hv k suffix m' Hlen Hlast.\n  destruct (decide (1 + length (obs (state m)) <= k)); [lia |].\n  apply Hv with k.\n  by rewrite lastn_cons; case_decide; [lia |].\nQed.\n\nLemma MO_msg_valid_alt_recvs_Receive_conv :\n  forall (P : Address -> Prop) (m mr : Message),\n    MO_msg_valid_alt_recvs P (m <*> MkObservation Receive mr) ->\n      MO_msg_valid_alt_recvs P m /\\ MO_msg_valid_alt P mr.\nProof.\n  intros P m mr.\n  rewrite (MO_msg_valid_alt_recvs_shorten P m).\n  unfold MO_msg_valid_alt_recvs, MO_msg_valid_alt_recvs'; cbn; unfold addObservation'.\n  intros Hv; split.\n  - intros k suffix m' Hlen Hlast.\n    destruct (decide (1 + length (obs (state m)) <= k)); [lia |].\n    apply (Hv k suffix). rewrite lastn_cons.\n    by case_decide; [lia |].\n  - apply (Hv (1 + length (obs (state m))) (obs (state m))).\n    by rewrite lastn_ge; cbn; [| lia].\nQed.\n\nLemma MO_msg_valid_alt_Receive_conv :\n  forall (P : Address -> Prop) (m mr : Message),\n    MO_msg_valid_alt P (m <*> MkObservation Receive mr) ->\n      MO_msg_valid_alt P m /\\ MO_msg_valid_alt P mr.\nProof.\n  intros P m mr [HP Hms Hmr]; cbn in *.\n  apply MO_msg_valid_alt_sends_Receive_conv in Hms.\n  apply MO_msg_valid_alt_recvs_Receive_conv in Hmr as [].\n  by split; [constructor |].\nQed.\n\n(**\n  Last but not least, we need an inversion lemma which tells us that,\n  if from the state of a message <<m1>> we sent the message <<m2>>, then\n  <<m1>> must be equal to <<m2>>.\n*)\nLemma MO_msg_valid_alt_Send_inv :\n  forall (P : Address -> Prop) (m1 m2 : Message),\n    MO_msg_valid_alt P (m1 <*> MkObservation Send m2) -> m1 = m2.\nProof.\n  intros P m1 m2 [_ Hvs _].\n  unfold MO_msg_valid_alt_sends in Hvs; cbn in *; unfold addObservation' in Hvs.\n  specialize (Hvs (1 + length (obs (state m1))) (obs (state m1)) m2).\n  rewrite lastn_cons in Hvs; case_decide; [| lia].\n  destruct (Hvs eq_refl) as [].\n  by destruct m1 as [[]], m2 as [[]]; cbn in *; congruence.\nQed.\n\n(**\n  We now have, by previous lemmas, that [MO_msg_valid] and [MO_msg_valid_alt]\n  are equivalent. The proof of the equivalence lemma is structured as follows:\n\n  - the [MO_msg_valid] to [MO_msg_valid_alt] direction is by induction on\n    [MO_msg_valid] for <<P>> and <<m>>\n  - the [MO_msg_valid_alt] to [MO_msg_valid] direction is by well-founded\n    induction on the size of the message <<m>>\n*)\nLemma MO_msg_valid__MO_msg_valid_alt :\n  forall (P : Address -> Prop) (m : Message),\n    MO_msg_valid P m <-> MO_msg_valid_alt P m.\nProof.\n  split; [| revert m].\n  - induction 1 as [m Hobs | m Hm IH | m mr Hm IHm Hmr IHmr].\n    + by constructor; [done | |]\n      ; intros k suffix m' Hlast\n      ; rewrite Hobs, lastn_nil in Hlast; inversion Hlast.\n    + by apply MO_msg_valid_alt_Send.\n    + by apply MO_msg_valid_alt_Receive.\n  - assert (Hwf := well_founded_lt_compat _ (fun m => @sizeMessage Address m)\n      (fun m1 m2 => sizeMessage m1 < sizeMessage m2) (fun _ _ H => H)).\n    apply (@well_founded_induction _ (fun m1 m2 => sizeMessage m1 < sizeMessage m2) Hwf\n      (fun m => MO_msg_valid_alt P m -> MO_msg_valid P m)).\n    intros [[[| [[] m'] obs'] adr']] IH Hvalid.\n    + by constructor; [| inversion Hvalid].\n    + change (MkMessage _) with (MkMessage (MkState obs' adr') <*> MkObservation Receive m') in *.\n      apply MO_msg_valid_alt_Receive_conv in Hvalid as [].\n      by constructor 3; (apply IH; [unfold sizeMessage; cbn; lia |]).\n    + change (MkMessage _) with (MkMessage (MkState obs' adr') <*> MkObservation Send m') in *.\n      replace (MkMessage (MkState obs' adr')) with m' in *\n        by (apply MO_msg_valid_alt_Send_inv in Hvalid; done).\n      apply MO_msg_valid_alt_Send_conv in Hvalid.\n      by constructor 2; apply IH; [unfold sizeMessage; cbn; lia |].\nQed.\n\nEnd sec_alternative_definition_of_validity.\n\nInductive MOComponentValid (P : Address -> Prop) : Label -> State -> option Message -> Prop :=\n| MOCV_Receive :\n    forall (s : State) (m : Message),\n      MO_msg_valid P m -> MOComponentValid P Receive s (Some m)\n| MOCV_Send :\n    forall s : State,\n      MOComponentValid P Send s None.\n\nLtac invert_MOComponentValid :=\nrepeat match goal with\n| H : MOComponentValid _ Receive _ None  |- _ => inversion H; subst; clear H\n| H : MOComponentValid _ Send _ (Some _) |- _ => inversion H; subst; clear H\nend.\n\nDefinition MOComponentMachine (P : Address -> Prop) (i : Address) : VLSMMachine ELMOComponentType :=\n{|\n  initial_state_prop := UMOComponent_initial_state_prop i;\n  initial_message_prop := const False;\n  s0 := Inhabited_UMOComponent_initial_state_type i;\n  transition := fun l '(st, om) => UMOComponent_transition l st om;\n  valid := fun l '(st, om) => MOComponentValid P l st om;\n|}.\n\nDefinition MOComponent (P : Address -> Prop) (i : Address) : VLSM Message :=\n{|\n  vtype := ELMOComponentType;\n  vmachine := MOComponentMachine P i;\n|}.\n\nSection sec_MOComponent_lemmas.\n\n(** ** Component lemmas\n\n  We will use the notation [Mi] for a [MOComponent] of address [i].\n\n  We will use [RMi] to denote the corresponding pre-loaded VLSM, which is\n  used to model reachability.\n\n  There is a VLSM inclusion from [Mi] to [RMi].\n*)\n\nContext\n  {i : Address}\n  {P : Address -> Prop}\n  (Mi : VLSM Message := MOComponent P i)\n  (RMi : VLSM Message := pre_loaded_with_all_messages_vlsm Mi).\n\n(** The VLSM [Mi] embeds into [RMi]. *)\nLemma VLSM_incl_Mi_RMi :\n  VLSM_incl_part (vmachine Mi) (vmachine RMi).\nProof.\n  by apply vlsm_incl_pre_loaded_with_all_messages_vlsm.\nQed.\n\n(** The initial state of [RMi] is unique. *)\nLemma vs0_uniqueness :\n  forall is : State,\n    UMOComponent_initial_state_prop i is ->\n      is = ``(vs0 RMi).\nProof.\n  by intros []; inversion 1; cbv in *; subst.\nQed.\n\n(** *** Properties of transitions and traces *)\n\n(** In a valid state <<s>>, we can send a message containing this state. *)\nLemma input_valid_transition_Send_RMi :\n  forall s : State,\n    valid_state_prop RMi s ->\n      input_valid_transition RMi Send\n        (s, None)\n        (s <+> MkObservation Send (MkMessage s), Some (MkMessage s)).\nProof.\n  intros s Hvsp.\n  red; cbn; split_and!; [done | | | done].\n  - by exists (MkState [] i); constructor.\n  - by do 2 constructor.\nQed.\n\n(** In a valid state <<s>>, we can receive any valid message. *)\nLemma input_valid_transition_Receive_RMi :\n  forall (s : State) (m : Message),\n    valid_state_prop RMi s -> MO_msg_valid P m ->\n      input_valid_transition RMi Receive\n        (s, Some m)\n        (s <+> MkObservation Receive m, None).\nProof.\n  intros s m Hvsp Hvalid.\n  red; cbn; split_and!; [done | | | done].\n  - by exists (MkState [] i); constructor.\n  - by constructor.\nQed.\n\n(** If a message <<m>> is valid, its [state] is reachable. *)\nLemma valid_state_prop_MO_msg_valid_RMi :\n  forall m : Message,\n    MO_msg_valid P m -> adr (state m) = i ->\n      valid_state_prop RMi (state m).\nProof.\n  induction 1 as [m Hobs | m Hm IH | m mr Hm IHm Hmr IHmr]; cbn; intros Hadr.\n  - by exists None; constructor.\n  - apply (@input_valid_transition_destination _ RMi Send (state m) _ None (Some m)).\n    destruct m as [s]; cbn in *.\n    by apply input_valid_transition_Send_RMi, IH.\n  - apply (@input_valid_transition_destination _ RMi Receive (state m) _ (Some mr) None).\n    destruct m as [s]; cbn in *.\n    by apply input_valid_transition_Receive_RMi; itauto.\nQed.\n\n(** Valid transitions and valid traces lead to bigger states. *)\n\nLemma MOComponent_valid_transition_size :\n  forall (s1 s2 : State) (iom oom : option Message) (lbl : Label),\n    MOComponentValid P lbl s1 iom ->\n    UMOComponent_transition lbl s1 iom = (s2, oom) ->\n      sizeState s1 < sizeState s2.\nProof.\n  by intros [] s2 [im |] oom []; do 2 inversion_clear 1; cbn; lia.\nQed.\n\nLemma input_valid_transition_size_RMi :\n  forall (s1 s2 : State) (iom oom : option Message) (lbl : Label),\n    input_valid_transition RMi lbl (s1, iom) (s2, oom) ->\n      sizeState s1 < sizeState s2.\nProof.\n  by intros s1 s2 iom oom lbl [(_ & _ & ?) Ht]; cbn in *\n  ; eapply MOComponent_valid_transition_size.\nQed.\n\nLemma finite_valid_trace_from_to_size_RMi :\n  forall (s1 s2 : State) (tr : list transition_item),\n    finite_valid_trace_from_to RMi s1 s2 tr ->\n      s1 = s2 /\\ tr = []\n        \\/\n      sizeState s1 < sizeState s2.\nProof.\n  induction 1; [by left |].\n  assert (sizeState s' < sizeState s)\n      by (eapply input_valid_transition_size_RMi; done).\n  by destruct IHfinite_valid_trace_from_to; [itauto congruence | itauto lia].\nQed.\n\n(**\n  The final state of a valid transition determines the label, initial state,\n  input message and output message.\n*)\nLemma input_valid_transition_deterministic_conv_RMi :\n  forall (s1 s2 f : State) (iom1 iom2 oom1 oom2 : option Message) (lbl1 lbl2 : Label),\n    input_valid_transition RMi lbl1 (s1, iom1) (f, oom1) ->\n    input_valid_transition RMi lbl2 (s2, iom2) (f, oom2) ->\n      lbl1 = lbl2 /\\ s1 = s2 /\\ iom1 = iom2 /\\ oom1 = oom2.\nProof.\n  intros s1 s2 f iom1 iom2 oom1 oom2 lbl1 lbl2 Hivt1 Hivt2\n  ; inversion Hivt1 as [(_ & _ & Hvalid1) Ht1]; subst\n  ; inversion Hivt2 as [(_ & _ & Hvalid2) Ht2]; subst.\n  destruct lbl1, lbl2, iom1, iom2; cbn in *\n  ; inversion Ht1; subst; clear Ht1\n  ; inversion Ht2; subst; clear Ht2\n  ; inversion Hvalid1; inversion Hvalid2; invert_MOComponentValid; auto.\n  by destruct s1, s2; cbn in *; subst; itauto.\nQed.\n\n(** Trace segments between any two states are unique. *)\nLemma finite_valid_trace_from_to_unique_RMi :\n  forall (s1 s2 : State) (tr1 tr2 : list transition_item),\n    finite_valid_trace_from_to RMi s1 s2 tr1 ->\n    finite_valid_trace_from_to RMi s1 s2 tr2 ->\n      tr1 = tr2.\nProof.\n  intros s1 s2 tr1 tr2 Hfvt1 Hfvt2; revert tr2 Hfvt2.\n  induction Hfvt1 using finite_valid_trace_from_to_rev_ind; intros.\n  - by apply finite_valid_trace_from_to_size_RMi in Hfvt2; itauto (congruence + lia).\n  - destruct Hfvt2 using finite_valid_trace_from_to_rev_ind; [| clear IHHfvt2].\n    + apply finite_valid_trace_from_to_size_RMi in Hfvt1.\n      apply input_valid_transition_size_RMi in Ht.\n      by decompose [and or] Hfvt1; subst; clear Hfvt1; lia.\n    + assert (l = l0 /\\ s = s0 /\\ iom = iom0 /\\ oom = oom0)\n          by (eapply input_valid_transition_deterministic_conv_RMi; done).\n      decompose [and] H; subst; clear H.\n      by f_equal; apply IHHfvt1.\nQed.\n\n(** Traces between any two states are unique. *)\n\nLemma finite_valid_trace_init_to_unique_RMi :\n  forall (s1 s2 s : State) (tr1 tr2 : list transition_item),\n    finite_valid_trace_init_to RMi s1 s tr1 ->\n    finite_valid_trace_init_to RMi s2 s tr2 ->\n      tr1 = tr2.\nProof.\n  intros [] [] s tr1 tr2 [Ht1 []] [Ht2 []]; cbn in *; subst.\n  by eapply finite_valid_trace_from_to_unique_RMi.\nQed.\n\n(** All above properties also hold for [Mi]. *)\n\nLemma input_valid_transition_Send_Mi :\n  forall s : State,\n    valid_state_prop Mi s ->\n      input_valid_transition Mi Send\n        (s, None)\n        (s <+> MkObservation Send (MkMessage s), Some (MkMessage s)).\nProof.\n  intros s Hvsp.\n  red; cbn; split_and!; [done | | | done].\n  - by exists (MkState [] i); constructor.\n  - by do 2 constructor.\nQed.\n\nLemma input_valid_transition_size_Mi :\n  forall (s1 s2 : State) (iom oom : option Message) (lbl : Label),\n    input_valid_transition Mi lbl (s1, iom) (s2, oom) ->\n      sizeState s1 < sizeState s2.\nProof.\n  intros s1 s2 iom oom lbl Hivt.\n  eapply input_valid_transition_size_RMi.\n  by apply (@VLSM_incl_input_valid_transition _ (vtype Mi) (vmachine Mi) (vmachine RMi))\n  ; eauto using VLSM_incl_Mi_RMi.\nQed.\n\nLemma finite_valid_trace_from_to_size_Mi :\n  forall (s1 s2 : State) (tr : list transition_item),\n    finite_valid_trace_from_to Mi s1 s2 tr ->\n      s1 = s2 /\\ tr = []\n        \\/\n      sizeState s1 < sizeState s2.\nProof.\n  intros s1 s2 tr Hfvt.\n  eapply finite_valid_trace_from_to_size_RMi.\n  by apply (@VLSM_incl_finite_valid_trace_from_to _ (vtype Mi) (vmachine Mi) (vmachine RMi))\n  ; eauto using VLSM_incl_Mi_RMi.\nQed.\n\nLemma input_valid_transition_deterministic_conv_Mi :\n  forall (s1 s2 f : State) (iom1 iom2 oom1 oom2 : option Message) (lbl1 lbl2 : Label),\n    input_valid_transition Mi lbl1 (s1, iom1) (f, oom1) ->\n    input_valid_transition Mi lbl2 (s2, iom2) (f, oom2) ->\n      lbl1 = lbl2 /\\ s1 = s2 /\\ iom1 = iom2 /\\ oom1 = oom2.\nProof.\n  intros s1 s2 f iom1 iom2 oom1 oom2 lbl1 lbl2 Hivt1 Hivt2.\n  by eapply input_valid_transition_deterministic_conv_RMi\n  ; apply (@VLSM_incl_input_valid_transition _ (vtype Mi) (vmachine Mi) (vmachine RMi))\n  ; eauto using VLSM_incl_Mi_RMi.\nQed.\n\nLemma finite_valid_trace_from_to_unique_Mi :\n  forall (s1 s2 : State) (l1 l2 : list transition_item),\n    finite_valid_trace_from_to Mi s1 s2 l1 ->\n    finite_valid_trace_from_to Mi s1 s2 l2 ->\n      l1 = l2.\nProof.\n  by intros s1 s2 l1 l2 Hfvt1 Hfvt2\n  ; eapply finite_valid_trace_from_to_unique_RMi\n  ; apply VLSM_incl_finite_valid_trace_from_to\n  ; eauto using VLSM_incl_Mi_RMi.\nQed.\n\nLemma finite_valid_trace_init_to_unique_Mi :\n  forall (s f : State) (l1 l2 : list transition_item),\n    finite_valid_trace_init_to Mi s f l1 ->\n    finite_valid_trace_init_to Mi s f l2 ->\n      l1 = l2.\nProof.\n  by intros s f l1 l2 Hfvit1 Hfvit2\n  ; eapply finite_valid_trace_init_to_unique_RMi\n  ; apply VLSM_incl_finite_valid_trace_init_to\n  ; eauto using VLSM_incl_Mi_RMi.\nQed.\n\n(** *** Extracting a trace from a state *)\n\n(** If a valid trace leads to state s, the trace extracted from s also leads to s. *)\n\nLemma finite_valid_trace_init_to_state2trace_RMi :\n  forall (is s : State) (tr : list transition_item),\n    finite_valid_trace_init_to RMi is s tr ->\n      finite_valid_trace_init_to RMi is s (state2trace s).\nProof.\n  intros is s tr [Hfv Hinit]; cbn in *; revert Hinit.\n  induction Hfv using finite_valid_trace_from_to_rev_ind; intros.\n  - inversion Hinit; clear Hinit.\n    destruct si; cbn in *; subst; cbn.\n    repeat constructor. exists None.\n    by repeat constructor.\n  - specialize (IHHfv Hinit).\n    destruct Ht as [Hvalid Ht]; cbn in Ht.\n    destruct s as [obs adr], l, iom as [im |]\n    ; inversion Ht; subst; clear Ht; cbn in *\n    ; cycle 1; [done | done | |].\n    + constructor; [| done].\n      by eapply extend_right_finite_trace_from_to; [apply IHHfv |]; auto.\n    + constructor; [| done].\n      by eapply extend_right_finite_trace_from_to; [apply IHHfv |]; auto.\nQed.\n\n(** The trace extracted from the final state of another trace is equal to that trace. *)\n\nLemma finite_valid_trace_init_to_state2trace_RMi_inv :\n  forall (is s : State) (tr : list transition_item),\n    finite_valid_trace_init_to RMi is s tr ->\n      state2trace s = tr.\nProof.\n  intros is s tr Hfvti.\n  assert (Hfvti' : finite_valid_trace_init_to RMi is s (state2trace s))\n      by (eapply finite_valid_trace_init_to_state2trace_RMi; done).\n  by eapply finite_valid_trace_init_to_unique_RMi.\nQed.\n\n(** The trace extracted from a ram-state <<s>> leads to <<s>>. *)\n\nLemma finite_valid_trace_init_to_state2trace_RMi' :\n  forall (s : State),\n    valid_state_prop RMi s ->\n      finite_valid_trace_init_to RMi (``(vs0 RMi)) s (state2trace s).\nProof.\n  intros s Hs.\n  apply valid_state_has_trace in Hs as (is & tr & Htr).\n  apply finite_valid_trace_init_to_state2trace_RMi_inv in Htr as Heqtr; subst.\n  replace (``(vs0 RMi)) with is; [done |].\n  by apply vs0_uniqueness, Htr.\nQed.\n\nLemma valid_state_contains_unique_valid_trace_RMi :\n  forall s : State,\n    valid_state_prop RMi s ->\n      exists tr : list transition_item,\n        finite_valid_trace_init_to RMi (``(vs0 RMi)) s tr\n          /\\\n        forall tr' : list transition_item,\n          finite_valid_trace_init_to RMi (``(vs0 RMi)) s tr' -> tr' = tr.\nProof.\n  intros s Hvsp.\n  exists (state2trace s); split.\n  - by eapply finite_valid_trace_init_to_state2trace_RMi'.\n  - intros tr' Hfvt. symmetry.\n    by eapply finite_valid_trace_init_to_state2trace_RMi_inv.\nQed.\n\n(** *** State and message suffix relations *)\n\nLemma state_suffix_totally_orders_valid_sent_messages :\n  forall (m m1 m2 : Message) (obs1 obs2 obs3 : list Observation),\n    m = MkMessage (MkState [] i) <**>\n      obs1 <*> MkObservation Send m1 <**> obs2 <*> MkObservation Send m2 <**> obs3 ->\n    MO_msg_valid_alt_sends m ->\n      state_suffix (state m1) (state m2) /\\ state_suffix (state m2) (state m).\nProof.\n  intros m m1 m2 obs1 obs2 obs3 Heq Hvalid.\n  red in Hvalid.\n  assert (H2 :\n    obs (state m2) =\n    obs (state (MkMessage (MkState [] i) <**> obs1 <*> MkObservation Send m1 <**> obs2))\n    /\\ adr (state m2) = i).\n  {\n    replace i with (adr (state m)) at 2 by (subst; done).\n    apply (Hvalid (1 + length\n      (obs (state (MkMessage (MkState [] i) <**> obs1 <*> MkObservation Send m1 <**> obs2))))).\n    rewrite Heq; simpl.\n    rewrite lastn_app_le by (cbn; lia).\n    by rewrite lastn_ge; [| cbn; lia].\n  }\n  assert (H1 :\n    obs (state m1) = obs (state (MkMessage (MkState [] i) <**> obs1))\n    /\\ adr (state m1) = i).\n  {\n    replace i with (adr (state m)) at 2 by (subst; done).\n    apply (Hvalid (1 + length (obs (state (MkMessage (MkState [] i) <**> obs1))))).\n    rewrite Heq; simpl.\n    unfold addObservation'.\n    rewrite <- (app_cons (MkObservation Send m2)),\n            <- (app_cons (MkObservation Send m1)), 2!app_assoc.\n    rewrite lastn_app_le by (cbn; lia).\n    by rewrite lastn_ge; [| cbn; lia].\n  }\n  destruct H1 as [H11 H12], H2 as [H21 H22].\n  split.\n  - constructor; [by congruence |].\n    rewrite H11, H21; cbn.\n    split.\n    + by apply suffix_app_r, suffix_cons_r.\n    + intros []. apply (f_equal length) in H.\n      rewrite !app_length in H; cbn in H; rewrite app_length in H; cbn in H.\n      by lia.\n  - constructor; [by subst |].\n    rewrite H21, Heq; cbn.\n    split.\n    + by apply suffix_app_r, suffix_cons_r.\n    + intros []. apply (f_equal length) in H.\n      unfold addObservation' in H.\n      by rewrite <- (app_cons (MkObservation _ m1)),\n                 <- (app_cons (MkObservation _ m2)), !app_length in H\n      ; cbn in H; lia.\nQed.\n\nDefinition MO_msg_suffix (m : Message) : Prop :=\n  forall k1 k2 : nat, k1 < k2 ->\n  forall ob1 ob2 : Observation,\n    obs (state m) !! k1 = Some ob1 -> label ob1 = Send ->\n    obs (state m) !! k2 = Some ob2 -> label ob2 = Send ->\n      state_suffix (state (message ob2)) (state (message ob1)).\n\nLemma state_suffix_totally_orders_valid_sent_messages' :\n  forall m : Message, MO_msg_valid_alt_sends m -> MO_msg_suffix m.\nProof.\n  unfold MO_msg_valid_alt_sends, MO_msg_suffix.\n  intros m H k1 k2 Hlt ob1 ob2 Heq1 Hlbl1 Heq2 Hlbl2.\n  remember (length (obs (state m))) as K.\n  destruct (H (K - k1) (lastn (K - S k1) (obs (state m))) (message ob1)) as [Hobs1 Hadr1]\n  ; [by destruct ob1; cbn in *; subst; apply lastn_length_cons |].\n  destruct (H (K - k2) (lastn (K - S k2) (obs (state m))) (message ob2)) as [Hobs2 Hadr2]\n  ; [by destruct ob2; cbn in *; subst; apply lastn_length_cons |].\n  constructor; [by congruence |].\n  constructor; rewrite Hobs1, Hobs2.\n  - by apply suffix_lastn; lia.\n  - intros Hsuf. apply suffix_length in Hsuf.\n    rewrite 2!length_lastn in Hsuf.\n    apply lookup_lt_Some in Heq1, Heq2.\n    unfold Observation in *.\n    by destruct (Nat.min_spec (K - S k1) (length (obs (state m)))) as [[H11 H12] | [H11 H12]],\n             (Nat.min_spec (K - S k2) (length (obs (state m)))) as [[H21 H22] | [H21 H22]]\n    ; rewrite ?H12, ?H22 in Hsuf; lia.\nQed.\n\nEnd sec_MOComponent_lemmas.\n\nSection sec_MOProtocol.\n\nContext\n  (index : Type)\n  `{finite.Finite index}\n  (idx : index -> Address)\n  `{!Inj (=) (=) idx}\n  (P : Address -> Prop)\n  (P' := fun adr => P adr /\\ exists i : index, idx i = adr)\n  (M : index -> VLSM Message := fun i => MOComponent P' (idx i))\n  (RM : index -> VLSM Message := fun i => pre_loaded_with_all_messages_vlsm (M i)).\n\n(** ** Protocol\n\n  The MO protocol is a free composition of finitely many MO components (each\n  with the same predicate <<P>>.\n\n  To talk about reachable states in the MO protocol, we will use [RMO],\n  which is MO preloaded with all messages.\n*)\n\nDefinition MO : VLSM Message := free_composite_vlsm M.\nDefinition RMO : VLSM Message := pre_loaded_with_all_messages_vlsm MO.\n\n(** We set up aliases for some functions operating on free VLSM composition. *)\n\nDefinition MO_state : Type := composite_state M.\nDefinition MO_label : Type := composite_label M.\nDefinition MO_transition_item : Type := composite_transition_item M.\n\n(** We can lift labels, states and traces from an MO component to the MO protocol. *)\n\nDefinition lift_to_MO_label\n  (i : index) (li : vlabel (M i)) : MO_label :=\n    lift_to_composite_label M i li.\n\nDefinition lift_to_MO_state\n  (us : MO_state) (i : index) (si : vstate (M i)) : MO_state :=\n    lift_to_composite_state M us i si.\n\nDefinition lift_to_MO_trace\n  (us : MO_state) (i : index) (tr : list (vtransition_item (M i)))\n  : list MO_transition_item :=\n    pre_VLSM_embedding_finite_trace_project\n      _ _ (lift_to_MO_label i) (lift_to_MO_state us i) tr.\n\n#[local] Hint Rewrite @state_update_twice : state_update.\n\n#[local] Hint Unfold lift_to_MO_label : state_update.\n#[local] Hint Unfold lift_to_MO_state : state_update.\n#[local] Hint Unfold lift_to_MO_trace : state_update.\n\n(**\n  We can also lift properties from MO components to the MO protocol, among\n  them [valid_state_prop], [valid_message_prop], [input_valid_transition]\n  and the various kinds of traces.\n*)\n\nLemma lift_to_MO :\n  forall (us : MO_state) (Hus : valid_state_prop MO us) (i : index),\n    VLSM_weak_embedding (M i) MO (lift_to_MO_label i) (lift_to_MO_state us i).\nProof. by intros; apply lift_to_free_weak_embedding. Qed.\n\nLemma lift_to_MO_valid_state_prop :\n  forall (i : index) (s : State) (us : MO_state),\n    valid_state_prop MO us -> valid_state_prop (M i) s ->\n      valid_state_prop MO (lift_to_MO_state us i s).\nProof.\n  intros is s us Hvsp.\n  by eapply VLSM_weak_embedding_valid_state, lift_to_MO.\nQed.\n\nLemma lift_to_MO_valid_message_prop :\n  forall (i : index) (om : option Message),\n    option_valid_message_prop (M i) om ->\n      option_valid_message_prop MO om.\nProof.\n  intros i [] Hovmp; cycle 1.\n  - by exists (``(vs0 MO)); constructor.\n  - eapply VLSM_weak_embedding_valid_message.\n    + by apply (lift_to_MO (``(vs0 MO))); exists None; constructor.\n    + by inversion 1.\n    + by apply Hovmp.\nQed.\n\nLemma lift_to_MO_input_valid_transition :\n  forall (i : index) (lbl : Label) (s1 s2 : State) (iom oom : option Message) (us : MO_state),\n    valid_state_prop MO us ->\n    input_valid_transition (M i) lbl (s1, iom) (s2, oom) ->\n      input_valid_transition MO\n        (lift_to_MO_label i lbl)\n        (lift_to_MO_state us i s1, iom)\n        (lift_to_MO_state us i s2, oom).\nProof.\n  intros i lbl s1 s2 iom oom us Hivt.\n  by apply @VLSM_weak_embedding_input_valid_transition, lift_to_MO.\nQed.\n\nLemma lift_to_MO_finite_valid_trace_from_to :\n  forall (i : index) (s1 s2 : State) (tr : list (vtransition_item (M i))) (us : MO_state),\n    valid_state_prop MO us ->\n    finite_valid_trace_from_to (M i) s1 s2 tr ->\n      finite_valid_trace_from_to\n        MO (lift_to_MO_state us i s1) (lift_to_MO_state us i s2) (lift_to_MO_trace us i tr).\nProof.\n  intros i s1 s2 tr us Hvsp Hfvt.\n  by eapply (VLSM_weak_embedding_finite_valid_trace_from_to (lift_to_MO _ Hvsp i)).\nQed.\n\n(** We could prove the same lifting lemmas for [RMO], but we won't need them. *)\n\nLemma lift_to_RMO\n  (us : MO_state) (Hus : valid_state_prop RMO us) (i : index) :\n  VLSM_weak_embedding (RM i) RMO (lift_to_MO_label i) (lift_to_MO_state us i).\nProof. by apply lift_to_preloaded_free_weak_embedding. Qed.\n\nLemma lift_to_RMO_valid_state_prop :\n  forall (i : index) (s : State) (us : MO_state),\n    valid_state_prop RMO us -> valid_state_prop (RM i) s ->\n      valid_state_prop RMO (lift_to_MO_state us i s).\nProof.\n  intros is s us Hvsp.\n  by eapply VLSM_weak_embedding_valid_state, lift_to_RMO.\nQed.\n\nLemma lift_to_RMO_valid_message_prop :\n  forall (i : index) (om : option Message),\n    option_valid_message_prop (RM i) om ->\n      option_valid_message_prop RMO om.\nProof.\n  intros i [] Hovmp; cycle 1.\n  - by exists (``(vs0 MO)); constructor.\n  - eapply VLSM_weak_embedding_valid_message.\n    + by apply (lift_to_RMO (``(vs0 MO))); exists None; constructor.\n    + by inversion 1.\n    + by apply Hovmp.\nQed.\n\nLemma lift_to_RMO_input_valid_transition :\n  forall (i : index) (lbl : Label) (s1 s2 : State) (iom oom : option Message) (us : MO_state),\n    valid_state_prop RMO us ->\n    input_valid_transition (RM i) lbl (s1, iom) (s2, oom) ->\n      input_valid_transition RMO\n        (lift_to_MO_label i lbl)\n        (lift_to_MO_state us i s1, iom)\n        (lift_to_MO_state us i s2, oom).\nProof.\n  intros i lbl s1 s2 iom oom us Hivt.\n  by apply @VLSM_weak_embedding_input_valid_transition, lift_to_RMO.\nQed.\n\nLemma lift_to_RMO_finite_valid_trace_from_to :\n  forall (i : index) (s1 s2 : State) (tr : list (vtransition_item (RM i))) (us : MO_state),\n    valid_state_prop RMO us ->\n    finite_valid_trace_from_to (RM i) s1 s2 tr ->\n      finite_valid_trace_from_to\n        RMO (lift_to_MO_state us i s1) (lift_to_MO_state us i s2) (lift_to_MO_trace us i tr).\nProof.\n  intros i s1 s2 tr us Hvsp Hfvt.\n  by apply (VLSM_weak_embedding_finite_valid_trace_from_to (lift_to_RMO _ Hvsp i)).\nQed.\n\n(** *** Lifting lemmas for validating theorem *)\n\nLemma initial_state_prop_lift_RM_to_MO :\n  forall (i : index) (s : State),\n    vinitial_state_prop (RM i) s ->\n      vinitial_state_prop MO (lift_to_MO_state (``(vs0 MO)) i s).\nProof.\n  intros i s Hisp j; cbn.\n  by destruct (decide (i = j)); subst; state_update_simpl.\nQed.\n\nLemma finite_valid_trace_lift_RM_to_MO :\n  forall (i : index) (s : State),\n    vinitial_state_prop (RM i) s ->\n      finite_valid_trace_init_to MO\n        (lift_to_MO_state (``(vs0 MO)) i s) (lift_to_MO_state (``(vs0 MO)) i s) [].\nProof.\n  constructor; cycle 1.\n  - by apply initial_state_prop_lift_RM_to_MO.\n  - constructor; exists None; constructor; [| done].\n    by apply initial_state_prop_lift_RM_to_MO.\nQed.\n\nLemma option_valid_message_prop_initial :\n  forall i : index,\n    option_valid_message_prop MO (Some (MkMessage (MkState [] (idx i)))).\nProof.\n  intros i.\n  remember (MkMessage (MkState [] (idx i))) as m.\n  exists (state_update M (``(vs0 MO)) i (state m <+> MkObservation Send m)).\n  by econstructor 2 with\n    (s := ``(vs0 MO)) (_om := None) (_s := ``(vs0 MO)) (om := None) (l := existT i Send);\n    [by repeat split; constructor.. | rewrite Heqm].\nQed.\n\nLemma option_valid_message_prop_addObservationToMessage_Send :\n  forall m : Message,\n    option_valid_message_prop MO (Some m) ->\n      option_valid_message_prop MO (Some (m <*> MkObservation Send m)).\nProof.\n  intros m [s' IH].\n  inversion IH; subst; [by inversion Hom as [j []]; inversion x |].\n  destruct l as [k []], om as [m' |];\n    destruct Hv as [Hv _]; inversion Hv; subst; clear Hv;\n    inversion Ht; subst; clear Ht.\n  unfold addObservationToMessage; cbn; red.\n  remember (s k <+> MkObservation Send (MkMessage (s k))) as sk'.\n  remember (state_update M s k sk') as ss.\n  assert (Heq : ss k = sk') by (subst; state_update_simpl; done).\n  rewrite <- Heq in *; clear Heqsk'.\n  exists (state_update M ss k (ss k <+> MkObservation Send (MkMessage (ss k)))).\n  by econstructor 2 with (s := ss) (_s := ``(vs0 MO)) (om := None) (l := existT k Send);\n    [| constructor | repeat split; constructor |].\nQed.\n\nLemma option_valid_message_prop_addObservationToMessage_Receive :\n  forall m mr : Message,\n    MO_msg_valid P' mr ->\n    option_valid_message_prop MO (Some m) ->\n    option_valid_message_prop MO (Some mr) ->\n      option_valid_message_prop MO (Some (m <*> MkObservation Receive mr)).\nProof.\n  intros m mr Hvalid [sm IH1] [smr IH2].\n  inversion IH1; subst; [by inversion Hom as [j []]; inversion x |].\n  destruct l as [k []], om as [m' |];\n    destruct Hv as [Hv _]; inversion Hv; subst; clear Hv;\n    inversion Ht; subst; clear Ht.\n  exists (state_update M s k (s k <+> MkObservation Receive mr <+>\n    MkObservation Send (MkMessage (s k <+> MkObservation Receive mr)))).\n  econstructor 2 with\n    (s := state_update M s k (s k <+> MkObservation Receive mr)) (_om := None)\n    (_s := ``(vs0 MO)) (om := None) (l := existT k Send); cycle 1.\n  - by constructor.\n  - by repeat split; constructor.\n  - by cbn; state_update_simpl.\n  - by econstructor 2 with (s := s) (om := Some mr) (l := existT k Receive);\n      [| | repeat split; constructor |].\nQed.\n\nLemma option_valid_message_prop_MO_msg_valid :\n  forall m : Message,\n    MO_msg_valid P' m -> option_valid_message_prop MO (Some m).\nProof.\n  induction 1.\n  - destruct H1 as (_ & i & Heq).\n    replace m with (MkMessage (MkState [] (idx i))) by (apply eq_Message; done).\n    by apply option_valid_message_prop_initial.\n  - by apply option_valid_message_prop_addObservationToMessage_Send.\n  - by apply option_valid_message_prop_addObservationToMessage_Receive.\nQed.\n\nLemma lift_to_MO_finite_valid_trace_init_to :\n  forall (i : index) (s1 s2 : State) (tr : list (vtransition_item (M i))),\n    finite_valid_trace_init_to (RM i) s1 s2 tr ->\n      finite_valid_trace_init_to MO (lift_to_MO_state (``(vs0 MO)) i s1)\n        (lift_to_MO_state (``(vs0 MO)) i s2) (lift_to_MO_trace (``(vs0 MO)) i tr).\nProof.\n  intros i s1 s2 tr [Hfvt Hisp].\n  induction Hfvt using finite_valid_trace_from_to_rev_ind; cbn;\n    [by apply finite_valid_trace_lift_RM_to_MO |].\n  constructor; [| by apply initial_state_prop_lift_RM_to_MO].\n  unfold lift_to_MO_trace, pre_VLSM_embedding_finite_trace_project.\n  rewrite map_app.\n  eapply finite_valid_trace_from_to_app; cbn; [by apply IHHfvt |].\n  apply valid_trace_add_last; [| done].\n  apply first_transition_valid; cbn.\n  destruct Ht as [(Hvsp & _ & Hvalid) Ht], l, iom as [im |]; cbn in *;\n    inversion Hvalid; subst; clear Hvalid;\n    inversion Ht; subst; cbn in *; clear Ht; cycle 1.\n  - repeat split.\n    + by eapply finite_valid_trace_from_to_last_pstate, IHHfvt.\n    + by apply option_valid_message_None.\n    + by constructor.\n    + by cbn; state_update_simpl.\n  - repeat split.\n    + by eapply finite_valid_trace_from_to_last_pstate, IHHfvt.\n    + by apply option_valid_message_prop_MO_msg_valid.\n    + by constructor.\n    + by cbn; state_update_simpl.\nQed.\n\nLemma lift_RM_to_MO :\n  forall i : index,\n    VLSM_embedding (RM i) MO (lift_to_MO_label i) (lift_to_MO_state (``(vs0 MO)) i).\nProof.\n  constructor; intros.\n  by eapply valid_trace_forget_last, lift_to_MO_finite_valid_trace_init_to,\n    valid_trace_add_default_last.\nQed.\n\n(**\n  Every state in a MO component gives rise to a unique trace leading to this\n  state, which we can then lift to the MO protocol.\n*)\nDefinition MOComponent_state2trace\n  (s : MO_state) (i : index) : list MO_transition_item :=\n    lift_to_MO_trace s i (state2trace (s i)).\n\n(**\n  Iterating [MOComponent_state2trace] shows that every reachable MO state contains a\n  trace that leads to this state. However, this trace is not unique, because\n  we can concatenate the lifted traces in any order.\n*)\nFixpoint MO_state2trace_aux\n  (us : MO_state) (is : list index) : list MO_transition_item :=\nmatch is with\n| [] => []\n| i :: is' =>\n  MO_state2trace_aux (state_update _ us i (MkState [] (idx i))) is' ++ MOComponent_state2trace us i\nend.\n\nDefinition MO_state2trace\n  (us : MO_state) : list MO_transition_item :=\n    MO_state2trace_aux us (enum index).\n\nLemma finite_valid_trace_from_to_MO_state2trace_RMO :\n  forall us : MO_state,\n    valid_state_prop RMO us ->\n      finite_valid_trace_init_to RMO (``(vs0 RMO)) us (MO_state2trace us).\nProof.\n  intros us Hvsp; split; [| done].\n  unfold MO_state2trace.\n  assert (Hall : forall i, i ∉ enum index -> us i = MkState [] (idx i))\n    by (intros i Hin; contradict Hin; apply elem_of_enum).\n  revert us Hall Hvsp.\n  generalize (enum index) as is.\n  induction is as [| i is']; cbn; intros us Hall Hvsp.\n  - replace us with (fun n : index => MkState [] (idx n)).\n    + by constructor; apply initial_state_is_valid; compute.\n    + extensionality i; rewrite Hall; [done |].\n      by apply not_elem_of_nil.\n  - eapply finite_valid_trace_from_to_app.\n    + apply IHis'.\n      * intros j Hj. destruct (decide (i = j)); subst; state_update_simpl; [done |].\n        by apply Hall; rewrite elem_of_cons; intros [].\n      * apply (VLSM_eq_valid_state (pre_loaded_with_all_messages_vlsm_is_pre_loaded_with_True MO)).\n        apply pre_composite_free_update_state_with_initial; [| by compute].\n        by apply (VLSM_eq_valid_state (pre_loaded_with_all_messages_vlsm_is_pre_loaded_with_True MO)).\n    + replace us with (state_update M us i (us i)) at 2 by (state_update_simpl; done).\n      apply lift_to_RMO_finite_valid_trace_from_to; [done |].\n      apply (valid_state_project_preloaded_to_preloaded _ _ _ us i) in Hvsp as Hvsp'.\n      apply valid_state_has_trace in Hvsp' as (s & tr & [Hfvt Hinit]).\n      replace s with (MkState [] (idx i)) in *; cycle 1.\n      * by inversion Hinit; destruct s; cbn in *; subst.\n      * by eapply finite_valid_trace_init_to_state2trace_RMi.\nQed.\n\n(** *** Validators *)\n\nLemma MO_component_validating :\n  forall i : index, component_projection_validator_prop M (free_constraint M) i.\nProof.\n  unfold component_projection_validator_prop.\n  intros i lj sj omi * Hiv.\n  apply input_valid_transition_iff in Hiv as [[s m] Ht].\n  apply exists_right_finite_trace_from in Ht as (s' & tr & Hfvt & Hlast).\n  apply lift_to_MO_finite_valid_trace_init_to in Hfvt as [Hfvt _].\n  unfold lift_to_MO_trace, pre_VLSM_embedding_finite_trace_project in Hfvt;\n    rewrite map_app in Hfvt.\n  apply finite_valid_trace_from_to_app_split in Hfvt as [_ Hfvt].\n  remember (finite_trace_last _ _) as ftl.\n  change (finite_trace_last _ _)\n    with (finite_trace_last\n            (lift_to_MO_state (fun j : index => MkState [] (idx j)) i s')\n            (lift_to_MO_trace (fun j : index => MkState [] (idx j)) i tr)) in Heqftl.\n  apply valid_trace_forget_last, first_transition_valid in Hfvt; cbn in *.\n  destruct Hfvt as [[Hvps [Hovmp [Hv1 Hv2]]] Ht]; cbn in Hv1, Hv2.\n  unfold lift_to_MO_trace in Heqftl; cbn in Heqftl.\n  rewrite <- pre_VLSM_embedding_finite_trace_last, Hlast in Heqftl.\n  exists ftl; split; [| done].\n  by rewrite Heqftl; state_update_simpl.\nQed.\n\n(** *** Equivocation *)\n\nLemma rec_obs_input_valid_transition :\n  forall (i : index) (s1 s2 : State) (m1 m2 : option Message) (lbl : Label),\n    input_valid_transition (RM i) lbl (s1, m1) (s2, m2) ->\n      forall ob : Observation, rec_obs s1 ob -> rec_obs s2 ob.\nProof.\n  intros i s1 s2 m1 m2 lbl Hivt ob Hro.\n  destruct Hivt as [(_ & _ & Hvalid) Ht]; cbn in *.\n  by inversion Hvalid; subst; inversion Ht; subst; cbn in *; constructor.\nQed.\n\nRecord incomparable_state (s1 s2 : State) : Prop :=\n{\n  incs_not_state_suffix12 : ~ state_suffix s1 s2;\n  incs_not_state_suffix21 : ~ state_suffix s2 s1;\n  incs_not_equal : s1 <> s2;\n}.\n\nLemma rec_obs_send_inv\n  (Q : State -> Observation -> Prop) s ob\n  (Hnew : Q s (MkObservation Send (MkMessage s)))\n  (Hprev : rec_obs s ob -> Q s ob) :\n  rec_obs (s <+> MkObservation Send (MkMessage s)) ob -> Q s ob.\nProof.\n  by inversion 1; (replace s with s0 in *; [auto | apply eq_State]).\nQed.\n\nLemma rec_obs_recv_inv\n  (Q : State -> Message -> Observation -> Prop) s m ob\n  (Hnew : Q s m (MkObservation Receive m))\n  (Hprev : rec_obs s ob -> Q s m ob)\n  (Hrecv : rec_obs (state m) ob -> Q s m ob) :\n  rec_obs (s <+> MkObservation Receive m) ob -> Q s m ob.\nProof.\n  by inversion 1; (replace s with s0 in *; [auto | apply eq_State]).\nQed.\n\nLemma rec_obs_addObservation_iff (s : State) (ob' ob : Observation) :\n  rec_obs (s <+> ob) ob'\n    <->\n  rec_obs s ob' \\/ ob' = ob \\/ label ob = Receive /\\ rec_obs (state (message ob)) ob'.\nProof.\n  split.\n  - inversion 1; subst.\n    + by right; left.\n    + by left; replace s with s0 by (apply eq_State; done).\n    + by right; right.\n  - destruct 1 as [Hprev | [-> | Hob]].\n    + by apply rec_prev.\n    + by apply rec_new.\n    + destruct ob as [l m]; cbn in Hob.\n      destruct Hob as [-> Hm].\n      by apply rec_recv.\nQed.\n\nLemma unfold_rec_obs :\n  forall (s : State) (ob : Observation),\n    rec_obs s ob\n      <->\n    ob ∈ obs s \\/ exists m, MkObservation Receive m ∈ obs s /\\ rec_obs (state m) ob.\nProof using. clear. (* avoid unneccessary dependence on section variables *)\n  intros s ob; split.\n  - induction 1.\n    + by left; constructor.\n    + by setoid_rewrite elem_of_addObservation; firstorder.\n    + by setoid_rewrite elem_of_addObservation; firstorder.\n  - induction s using addObservation_ind.\n    + by firstorder using elem_of_nil.\n    + setoid_rewrite elem_of_addObservation.\n      rewrite rec_obs_addObservation_iff.\n      by firstorder; subst; auto.\nQed.\n\nSet Warnings \"-cannot-define-projection\".\nRecord local_equivocators (s : State) (i : Address) : Prop :=\n{\n  lceqv_ob1 : Observation;\n  lceqv_ob2 : Observation;\n  lceqv_adr1 : adr (state (message lceqv_ob1)) = i;\n  lceqv_adr2 : adr (state (message lceqv_ob2)) = i;\n  lceqv_rec_obs1 : rec_obs s lceqv_ob1;\n  lceqv_rec_obs2 : rec_obs s lceqv_ob2;\n  lceqv_incomparable : incomparable (message lceqv_ob1) (message lceqv_ob2);\n}.\nSet Warnings \"cannot-define-projection\".\n\nDefinition composite_rec_observation\n  (s : vstate MO) (ob : Observation) : Prop :=\n    exists i : index, rec_obs (s i) ob.\n\nDefinition state_after_sending (m : Message) : State :=\n  state m <+> MkObservation Send m.\n\nSet Warnings \"-cannot-define-projection\".\nRecord global_equivocators\n  (sigma : vstate MO) (i : index) : Prop :=\n{\n  globeqv_ob : Observation;\n  globeqv_adr : adr (state (message globeqv_ob)) = idx i;\n  globeqv_cro : composite_rec_observation sigma globeqv_ob;\n  s := state_after_sending (message globeqv_ob);\n  globeqv_nss : ~ state_suffix s (sigma i);\n  globeqv_neq : s <> sigma i;\n}.\nSet Warnings \"cannot-define-projection\".\n\nLemma obs_rec_obs :\n  forall (s : State) ob,\n    ob ∈ obs s -> rec_obs s ob.\nProof.\n  intros s ob.\n  induction s using addObservation_ind.\n  - by inversion 1.\n  - intros [<- | Hob]%elem_of_cons.\n    + by apply rec_new.\n    + by apply rec_prev, IHs, Hob.\nQed.\n\nLemma messages_rec_obs :\n  forall i (s : vstate (RM i)),\n    valid_state_prop (RM i) s ->\n    forall (m' : Message) (ob : Observation),\n      m' ∈ messages s ->\n      rec_obs (state m') ob ->\n      rec_obs s ob.\nProof.\n  intros i s Hs.\n  induction Hs using valid_state_prop_ind.\n  - destruct s as [ol a].\n    assert (ol = []) as -> by apply Hs.\n    by inversion 1.\n  - intros m' ob Hm' Hob.\n    destruct Ht as [(_ & _ & Hvalid) Ht], Hvalid as [s m _ | s];\n      cbn in Ht; injection Ht as [= <- <-].\n    + change (m' ∈ m :: messages s) in Hm'.\n      apply elem_of_cons in Hm' as [-> | Hm'].\n      * by apply rec_recv.\n      * by eapply rec_prev, IHHs.\n    + change (m' ∈ MkMessage s :: messages s) in Hm'.\n      apply elem_of_cons in Hm' as [-> | Hm'].\n      * by apply rec_prev.\n      * by eapply rec_prev, IHHs.\nQed.\n\nLemma unfold_robs_fwd :\n  forall (s : State) ob,\n    rec_obs s ob ->\n      ob ∈ obs s \\/ exists (m' : Message), m' ∈ messages s /\\ rec_obs (state m') ob.\nProof.\n  intros s ob.\n  induction s using addObservation_ind; [by inversion 1 |].\n  intro Hob; inversion Hob; subst; clear Hob\n  ; replace s0 with s in * by (apply eq_State; done); clear H2 H3.\n  - by left; constructor.\n  - destruct (IHs H4) as [Hob | (m' & Hm & Hob)].\n    + by left; constructor.\n    + by right; exists m'; split; [constructor |].\n  - by right; exists m; split; [constructor |].\nQed.\n\nLemma unfold_robs_rev :\n  forall [Q : State -> Message -> Prop] [s : State],\n    UMO_reachable Q s ->\n    forall ob,\n      (ob ∈ obs s \\/ exists (m' : Message), m' ∈ messages s /\\ rec_obs (state m') ob) ->\n        rec_obs s ob.\nProof.\n  by induction 1; intros ob [Hob | [m' [Hob ?]]];\n    apply (@not_elem_of_nil, @elem_of_addObservation, @elem_of_messages_addObservation) in Hob;\n    destruct Hob; subst; constructor; eauto.\nQed.\n\nLemma unfold_robs :\n  forall (Q : State -> Message -> Prop) (s : State),\n    UMO_reachable Q s ->\n    forall ob,\n      rec_obs s ob\n        <->\n      ob ∈ obs s \\/ exists (m' : Message), m' ∈ messages s /\\ rec_obs (state m') ob.\nProof.\n  split.\n  - by apply unfold_robs_fwd.\n  - by eapply unfold_robs_rev.\nQed.\n\nLemma rec_obs_size_desc (s : State) (ob : Observation) :\n  rec_obs s ob -> sizeState (state (message ob)) < sizeState s.\nProof.\n  by induction 1; rewrite addObservation_size, sizeObservation_unfold; cbn; lia.\nQed.\n\nLemma rec_obs_acyclic (s : State) :\n  forall l, ~ rec_obs s (MkObservation l (MkMessage s)).\nProof.\n  by intros l Hrobs; apply rec_obs_size_desc, Nat.lt_irrefl in Hrobs.\nQed.\n\nEnd sec_MOProtocol.\n\nEnd sec_MO.\n\nArguments rec_obs_send_inv : clear implicits.\nArguments rec_obs_recv_inv : clear implicits.\n", "meta": {"author": "runtimeverification", "repo": "vlsm", "sha": "9115beb539257427467872ce65a224a0268cdae7", "save_path": "github-repos/coq/runtimeverification-vlsm", "path": "github-repos/coq/runtimeverification-vlsm/vlsm-9115beb539257427467872ce65a224a0268cdae7/theories/VLSM/Core/ELMO/MO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23308628595773057}}
{"text": "(*\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\nRequire Import String.\nRequire Import List.\nRequire Import Compare_dec.\nRequire Import DataSystem.\nRequire Import NRAExt.\nRequire Import TNRA.\n\nSection TNRAExt.\n  Local Open Scope nraext_scope.\n  \n  (** Typing for NRA *)\n\n  Context {m:basic_model}.\n\n  Definition nraext_type Op C A B := nra_type C (nra_of_nraext Op) A B.\n\n  Notation \"Op ▷ A >=> B ⊣ C\" := (nraext_type Op C A B) (at level 70) : nraext_scope.\n\n  (** Main typing soundness theorem for the Extended NRA *)\n\n  Theorem typed_nraext_yields_typed_data {τc} {τin τout} (d:data) c (op:nraext):\n    (bindings_type c τc) ->\n    (d ▹ τin) -> (op ▷ τin >=> τout ⊣ τc) ->\n    (exists x, (brand_relation_brands ⊢ op @ₓ d ⊣ c = Some x /\\ (x ▹ τout))).\n  Proof.\n    unfold nraext_eval, nraext_type; intros.\n    apply (@typed_nra_yields_typed_data m τc τin τout); assumption.\n  Qed.\n\n  (** Corrolaries of the main type soudness theorem *)\n\n  Definition typed_nraext_total {τc} {τin τout} (op:nraext) (d:data) c :\n    (bindings_type c τc) ->\n    (d ▹ τin) -> (op ▷ τin >=> τout ⊣ τc) ->             \n    { x:data | x ▹ τout }.\n  Proof.\n    unfold nraext_eval, nraext_type; intros.\n    apply (@typed_nra_total m τc τin τout (nra_of_nraext op) H1 c d); assumption.\n  Defined.\n\n  Definition tnraext_eval {τc} {τin τout} (op:nraext) (d:data) c :\n    (bindings_type c τc) ->\n    (d ▹ τin) -> (op ▷ τin >=> τout ⊣ τc) -> data.\n  Proof.\n    unfold nraext_eval, nraext_type; intros.\n    apply (@tnra_eval m τc τin τout (nra_of_nraext op) H1 c d); assumption.\n  Defined.\nEnd TNRAExt.\n\n(* Typed algebraic plan *)\n\nNotation \"Op ▷ A >=> B ⊣ C\" := (nraext_type Op C A B) (at level 70) : nraext_scope.\nNotation \"Op @▷ d ⊣ c\" := (tnraext_eval Op d c) (at level 70) : nraext_scope.\n\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/NRA/Typing/TNRAExt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23308627966055245}}
{"text": "From mathcomp Require Import\n     all_ssreflect.\n\nFrom AUChain Require Import\n     Messages\n     Parameters.\n\nFrom RecordUpdate Require Import RecordSet. \n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** * MessageTuple \n    This file contains the wrapper around messages used\n    by the network functionality.  \n**)\n\nRecord MessageTuple :=\n  mkMessageTuple\n    { msg : Message\n    ; rcv : Party\n    ; cd : Delay }.\n\nInstance MessageTupleSettable : Settable MessageTuple :=\n  settable! mkMessageTuple <msg; rcv; cd>. \n\nDefinition MessagePool := seq MessageTuple.\n\nModule MessageTupleEq.\n\nDefinition eq_msg_tuple a b :=\n  [&& msg a == msg b\n   , rcv a == rcv b\n   & cd a  == cd b ].\n\nLemma eq_msg_tupleP : Equality.axiom eq_msg_tuple.\nProof.\n  case => ???; case => ???. rewrite /eq_msg_tuple /=.\n  do ! (case: _ /eqP; [move => -> |by constructor; case]).\n  by constructor.\nQed.\n\nCanonical MessageTuple_eqMixin := Eval hnf in EqMixin eq_msg_tupleP.\nCanonical MessageTuple_eqType := Eval hnf in EqType MessageTuple MessageTuple_eqMixin.\n\nEnd MessageTupleEq.\nExport MessageTupleEq.\n", "meta": {"author": "AU-COBRA", "repo": "PoS-NSB", "sha": "8cb62e382f17626150a4b75e44af4d270474d3e7", "save_path": "github-repos/coq/AU-COBRA-PoS-NSB", "path": "github-repos/coq/AU-COBRA-PoS-NSB/PoS-NSB-8cb62e382f17626150a4b75e44af4d270474d3e7/Model/MessageTuple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23308627966055243}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Export Typing. \n\nSet Implicit Arguments.\nUnset Standard Proposition Elimination Names.\n\n(* Redefinition of pairs on [Type] instead of [Set] *)\n\nInductive prod (A B:Type) : Type :=\n    pair : A -> B -> prod A B.\nNotation \"x * y\" := (prod x y) : type_scope.\n\nDefinition fst (A B:Type)(ab:prod A B) := let (a,_) := ab in a.\nDefinition snd (A B:Type)(ab:prod A B) := let (_,b) := ab in b.\n\nInductive halfprod (A:Prop)(B:Type) : Type := \n   halfpair : A -> B -> halfprod A B. \nNotation \"x ** y\" := (halfprod x y) (at level 40) : type_scope.\n\nDefinition F (rhos:context)(rho:type)(r:term)(k:nat) := \n  TypJ rhos r rho /\\ length rhos <= k.\n\nHint Unfold F.\n\nLemma F_occurs : forall r rhos rho k, \n  F rhos rho r k -> occurs k r = false.\nProof.\n  induction r; destruct 1; simpl; intros.\n  case (eq_nat_dec n k); auto.\n  intros; subst.\n  destruct H; inversion_clear H.\n  cut False; try contradiction.\n  omega. \n\n  rewrite (IHr1 rhos (typ rhos r2 --> rho)); [simpl|red; intuition eauto].\n  apply (IHr2 rhos (typ rhos r2)); red; intuition eauto.\n \n  rename rho into sigma; rename t into rho.\n  destruct H; simpl in *. \n  inversion_clear H.\n  apply (IHr (rho::rhos) (typ (rho::rhos) r) (S k)); red; intuition eauto.\n  simpl; auto with arith.\nQed.  \n\n\nModule Type Requirements.\n\n Parameter abstr : nat -> type -> term -> term. \n Notation \" \\! k : rho , r \" := (abstr k rho r) (at level 20, k at level 99).\n\n Parameter N : context -> type -> term -> term -> Prop.\n Parameter A : context -> type -> term -> term -> Prop.\n Parameter H : context -> type -> term -> term -> Prop.\n\n Axiom Ax1 : forall r t rhos rho sigma k, F rhos (rho-->sigma) r k -> \n  N (rhos++ext_ctx rhos k rho) sigma (r;k) t -> \n  N rhos (rho-->sigma) r (\\!k:rho, t).\n\n Axiom Ax2 : forall rhos r s,  A rhos Iota r s -> N rhos Iota r s.\n\n Axiom Ax3 : forall rhos rho k, TypJ rhos [k] rho ->  A rhos rho [k] [k].\n\n Axiom Ax4 : forall rhos rho sigma r r' s s', TypJ rhos s rho -> \n  A rhos (rho-->sigma) r r' -> N rhos rho s s' -> A rhos sigma (r;s) (r';s').\n\n Axiom Ax5 : forall rhos rho r s t, \n  H rhos rho r s -> N rhos rho s t -> N rhos rho r t.\n\n Axiom Ax6 : forall rhos rho sigma r s rs, \n  H rhos sigma ((sub (\\rho,r) rs);s) \n  (sub r ((s::rs)#rs.(shift))).\n\n Axiom Ax7 : forall rhos rho sigma r s t, \n  H rhos (rho-->sigma) r s -> H rhos sigma (r;t) (s;t).\n\n Axiom Ax_H_ext_ctx :  forall rhos sigmas rho r s, TypJ rhos r rho -> \n  H rhos rho r s -> H (rhos++sigmas) rho r s.\n\nEnd Requirements.\n\nModule NormalizationProof (R:Requirements).\n\nImport R.\n\nDefinition SN (rhos:context)(rho:type)(r:term) := \n  forall k sigmas, F (rhos++sigmas) rho r k -> \n    { s:term | N (rhos++sigmas) rho r s }. \n\nDefinition SA (rhos:context)(rho:type)(r:term) := \n forall k sigmas, F (rhos++sigmas) rho r k -> \n    { s:term | A (rhos++sigmas) rho r s }. \n\nOpen Scope type_scope.\n\nFixpoint SC (rhos:context)(rho:type)(r:term) {struct rho} : Type := \n  (TypJ rhos r rho) **\n  match rho with \n  | Iota => SN rhos Iota r\n  | rho-->sigma => \n    forall s sigmas, SC (rhos++sigmas) rho s -> \n      SC (rhos++sigmas) sigma (r;s)\n  end.\n\nLemma SN_ext_ctx : forall rho rhos sigmas r, \n TypJ rhos r rho -> SN rhos rho r -> SN (rhos++sigmas) rho r.\nProof.\nunfold SN; intros.\nrewrite app_ass in H2; rewrite app_ass. \napply (H1 k _ H2); auto.\nQed.\nHint Resolve SN_ext_ctx.\n\nLemma SC_TypJ : forall rhos rho r, SC rhos rho r -> TypJ rhos r rho.\nProof.\n destruct rho; destruct 1; auto.\nQed. \nHint Resolve SC_TypJ.\n\nLemma SC_ext_ctx : forall rho rhos sigmas r, \n SC rhos rho r -> SC (rhos++sigmas) rho r.\nProof.\ndestruct rho; simpl; intuition.\ndestruct a; auto.\nrewrite app_ass; rewrite app_ass in X; auto.\nQed.\n\nLemma one :  \n forall rho rhos r, TypJ rhos r rho -> \n (SC rhos rho r -> SN rhos rho r)*(SA rhos rho r -> SC rhos rho r).\nProof.\ninduction rho.\nsimpl.\nsplit.\nintuition.\nunfold SA, SN.\nintros.\nsplit; auto.\nintros.\ndestruct (H1 k _ H2) as [s Hs].\nexists s.\napply Ax2; auto.\n\nrename rho1 into rho.\nrename rho2 into sigma.\nsplit.\nrename H0 into T.\nsimpl.\nunfold SN.\ndestruct 1 as [_ X].\nintros k mus; intros.\nset (rhos':=rhos++mus).\nset (sigmas := ext_ctx rhos' k rho).\nassert (T' : TypJ (rhos'++sigmas) k rho).\n unfold sigmas; apply ext_ctx_TypJ; destruct H0; auto.\nassert (SA (rhos'++sigmas) rho [k]). \n red; intros.\n exists [k].\n apply Ax3.\n destruct H1; auto.\nassert (SC (rhos'++sigmas) sigma (r;k)).  \n unfold rhos' in *.\n assert (Eq:=app_ass rhos mus sigmas); rewrite_all Eq; clear Eq.\n apply X.\n refine (snd (IHrho1 (rhos++mus++sigmas) [k] _) _); auto.\nassert (SN (rhos'++sigmas) sigma (r;k)).\n refine (fst (IHrho2 (rhos'++sigmas) (r;k) _) _); eauto.\ntry rename X2 into H2.\ndestruct (H2 (S k) nil) as [t Ht]; auto.\n simpl_list.\n split; auto.\n unfold sigmas; rewrite ext_ctx_length; auto.\n unfold F in *; intuition.\nexists (\\!k:rho,t); auto.\ndo_in Ht simpl_list.\napply Ax1; auto.\n\nunfold SA; simpl; split; auto; intros.\nrename H0 into T.\nrefine (snd (IHrho2 (rhos++sigmas) (r;s) _) _); eauto.\nred; intros.\ndestruct (H1 k (sigmas++sigmas0)) as [r' Hr'].\n rewrite <- app_ass.\n split; auto.\n unfold F in *; intuition.\nrewrite <- app_ass in Hr'.\nassert (IH: SN (rhos++sigmas) rho s).\n refine (fst (IHrho1 (rhos++sigmas) s _) _); eauto.\ndestruct (IH k sigmas0) as [s' Hs']; auto.\n unfold F in *; intuition.\nexists (r';s').\neapply Ax4; eauto.\nDefined.\n\nLemma two : forall rho rhos r r', TypJ rhos r rho -> \n  SC rhos rho r' -> H rhos rho r r' -> SC rhos rho r.\nProof.\ninduction rho; simpl; unfold SN; split; auto; intros.\ntry rename X into H1.\ndestruct H1 as [T H4].\ndestruct (H4 k sigmas) as [s Hs]; auto.\nunfold F in *; intuition.\nexists s.\neapply Ax5; eauto.\napply Ax_H_ext_ctx; auto.\napply IHrho2 with (r':= r';s); intuition.\neauto.\neapply Ax7; eapply Ax_H_ext_ctx; eauto.\nDefined.\n\nFixpoint SCs (sigmas rhos: context)(rs: list term) {struct rhos} : Type := \n match rhos, rs with \n | nil,nil => True\n | nil, _ => False\n | _, nil => False \n | rho::rhos, r::rs => (SC sigmas rho r)*(SCs sigmas rhos rs)\nend.\n\nLemma SCs_length : forall sigmas rhos rs, SCs sigmas rhos rs -> \n length rhos = length rs.\nProof.\ninduction rhos; destruct rs; auto; simpl; destruct 1; firstorder.\nQed.\n \nLemma SCs_nth : forall sigmas rhos rho rs r n, n < length rhos ->\n  SCs sigmas rhos rs -> SC sigmas (nth n rhos rho)  (nth n rs r). \nProof.\ninduction rhos; destruct rs.\nintros.\nelimtype False.\ninversion H0.\ncontradiction.\ncontradiction.\nintros.\nsimpl in X; destruct X.\ndestruct n.\nsimpl.\nauto.\nsimpl.\nfirstorder.\nDefined.\n\nLemma SCs_ext_ctx : forall sigmas sigmas0 rhos rs, \n SCs sigmas rhos rs -> SCs (sigmas++sigmas0) rhos rs.\nProof.\ninduction rhos; destruct rs; simpl; intuition.\napply SC_ext_ctx; auto.\nQed.\n\nLemma three : forall r (rs:substitution) rhos sigmas rho, \n SCs sigmas rhos rs -> \n TypJ rhos r rho ->  SC sigmas rho (sub r rs).\nProof.\ninduction r.\nsimpl.\nintros.\ndestruct H0.\nsimpl in H1.\nsubst rho.\napply SCs_nth; auto.\ninversion_clear H0; auto.\n\nsimpl.\nintros.\nset (sigma := typ rhos r2).\nassert (H1: TypJ rhos r1 (sigma-->rho)). eauto.\nassert (H2: TypJ rhos r2 (typ rhos r2)). eauto.\nassert (IH1:= IHr1 rs rhos sigmas (sigma --> rho) X H1).\nassert (IH2:= IHr2 rs rhos sigmas (typ rhos r2) X H2). \nsimpl in IH1.\ndestruct IH1 as [_ B].\nreplace sigmas with (sigmas++nil); [idtac|simpl_list;auto].\napply (B (sub r2 rs) nil); simpl_list; auto.\n\nrename t into rho.\nintros.\ndestruct H0.\nsubst rho0.\nset (freeze:= sub (\\ rho, r) rs).\nassert (TypJ sigmas (sub (\\ rho, r) rs) (rho --> typ (rho::rhos) r)).\n apply TypJ_sub2 with rhos.\n rewrite (SCs_length _ _ _ X); auto with arith.\n split; auto.\n intros.\n lapply (@SCs_nth sigmas rhos d' rs d n); auto.\nsimpl; split; auto; intros.\ndestruct (@one rho (sigmas ++ sigmas0) s); auto.\napply two with (sub r ((s::rs)#(rs.(shift)))); eauto.\napply IHr with (rhos:=rho::rhos).\nsimpl.\nsplit; auto.\napply SCs_ext_ctx; auto.\ninversion_clear H0; split; auto.\nunfold freeze.\napply Ax6; auto.\nQed.\n\nLemma SCs_seq : forall rhos sigmas, \n  SCs (sigmas++rhos) rhos\n   (map Var (seq (length sigmas) (length rhos))). \nProof.\ninduction rhos.\nsimpl; auto.\nsimpl.\nsplit.\ndestruct (@one a (sigmas++a::rhos) (length sigmas)).\nsplit.\nconstructor.\nsimpl_list; simpl; omega.\nsimpl; simpl_list; auto.\nrewrite app_nth2; auto.\nsimpl_arith; simpl; auto.\napply s0.\nunfold SA.\nexists [length sigmas].\napply Ax3.\ndestruct H0; auto.\nreplace (a::rhos) with ((a::nil) ++ rhos); auto.\nrewrite <- app_ass.\nreplace (S (length sigmas)) with (length (sigmas++a::nil)); auto.\nsimpl_list; simpl; simpl_arith; auto.\nDefined.\n\nLemma normalizeTheorem : \n forall rhos rho r, TypJ rhos r rho -> { s:term | N rhos rho r s }. \nProof.\nintros.\ndestruct (@one rho rhos r); auto.\nassert (SC rhos rho r).\nrewrite <- (sub_id r (length rhos)).\napply three with rhos; auto.\nunfold id; simpl.\ngeneralize (SCs_seq rhos nil); simpl_list; simpl; auto.\ngeneralize (s X (length rhos) nil); simpl_list; intuition.\nDefined.\n\nEnd NormalizationProof.\n", "meta": {"author": "coq-contribs", "repo": "tait", "sha": "1505eb9e6af0c14892c9fe2bd1021b56dc65c409", "save_path": "github-repos/coq/coq-contribs-tait", "path": "github-repos/coq/coq-contribs-tait/tait-1505eb9e6af0c14892c9fe2bd1021b56dc65c409/TaitCore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2330862796605524}}
{"text": "From Coq Require Import ZArith List.\nFrom mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq.\nFrom BitBlasting Require Import QFBV CNF BBCommon.\nFrom ssrlib Require Import ZAriths Tactics Bools Seqs.\nFrom nbits Require Import NBits.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* ===== bit_blast_eq ===== *)\n\nFixpoint bit_blast_eq_eq_zip r lsp : cnf :=\n  match lsp with\n  | [::] => [::]\n  | (l1, l2)::tl =>\n    let cs_hd := List.map (fun cs => neg_lit r::cs) (cnf_lit_eq l1 l2) in\n    let cs_tl := bit_blast_eq_eq_zip r tl in\n    catrev cs_hd cs_tl\n  end.\n\nDefinition bit_blast_eq_choice r (auxs: word) : cnf :=\n  [:: r::auxs].\n\nFixpoint bit_blast_eq_neq_zip g lsp : generator * cnf * word :=\n  match lsp with\n  | [::] => (g, [::], [::])\n  | (l1, l2)::tl =>\n    let (g_hd, auxs_hd) := gen g in\n    let cs_hd := [:: [:: neg_lit auxs_hd; l1; l2];\n                    [:: neg_lit auxs_hd; neg_lit l1; neg_lit l2];\n                    [:: auxs_hd; neg_lit l1; l2];\n                    [:: auxs_hd; l1; neg_lit l2] ] in\n    let '(g_tl, cs_tl, auxs_tl) := bit_blast_eq_neq_zip g_hd tl in\n    (g_tl, catrev cs_hd cs_tl, auxs_hd :: auxs_tl)\n  end.\n\nFixpoint mk_env_eq_neq_zip E g lsp : env * generator * cnf * word :=\n  match lsp with\n  | [::] => (E, g, [::], [::])\n  | (l1, l2)::tl =>\n    let (g_hd, auxs_hd) := gen g in\n    let E' := env_upd E (var_of_lit auxs_hd)\n                      (xorb (interp_lit E l1) (interp_lit E l2)) in\n    let cs_hd := [:: [:: neg_lit auxs_hd; l1; l2];\n                    [:: neg_lit auxs_hd; neg_lit l1; neg_lit l2];\n                    [:: auxs_hd; neg_lit l1; l2];\n                    [:: auxs_hd; l1; neg_lit l2] ] in\n    let '(E_tl, g_tl, cs_tl, auxs_tl) := mk_env_eq_neq_zip E' g_hd tl in\n    (E_tl, g_tl, catrev cs_hd cs_tl, auxs_hd :: auxs_tl)\n  end.\n\nDefinition bit_blast_eq_zip (g : generator) lsp : generator * cnf * literal :=\n  let (g_r, r) := gen g in\n  let '(g_aux, cs_neq, auxs) := bit_blast_eq_neq_zip g_r lsp in\n  let cs_aux := bit_blast_eq_choice r auxs in\n  let cs_eq := bit_blast_eq_eq_zip r lsp in\n  (g_aux, catrev cs_neq (catrev cs_aux cs_eq), r).\n\nDefinition mk_env_eq_zip E g lsp : env * generator * cnf * literal :=\n  let (g_r, r) := gen g in\n  let E' := env_upd E (var_of_lit r) (interp_word E (unzip1 lsp) == interp_word E (unzip2 lsp)) in\n  let '(E_aux, g_aux, cs_neq, auxs) := mk_env_eq_neq_zip E' g_r lsp in\n  let cs_aux := bit_blast_eq_choice r auxs in\n  let cs_eq := bit_blast_eq_eq_zip r lsp in\n  (E_aux, g_aux, catrev cs_neq (catrev cs_aux cs_eq), r).\n\nDefinition bit_blast_eq g ls1 ls2 := bit_blast_eq_zip g (extzip_ff ls1 ls2).\n\nDefinition mk_env_eq E g ls1 ls2 := mk_env_eq_zip E g (extzip_ff ls1 ls2).\n\nLemma bit_blast_eq_eq_zip_correct E bsp lsp lr:\n  enc_bits E (unzip1 lsp) (unzip1 bsp) ->\n  enc_bits E (unzip2 lsp) (unzip2 bsp) ->\n  interp_cnf E (add_prelude (bit_blast_eq_eq_zip lr lsp)) ->\n  interp_lit E lr ->\n  (unzip1 bsp) = (unzip2 bsp).\nProof.\n  elim: lsp E bsp lr => [| [ls1_hd ls2_hd] lsp_tl IH] E bsp lr.\n  - rewrite !enc_bits_nil_l unzip1_l_nil.\n      by case/eqP => ->.\n  - rewrite /=.\n    case: bsp => [| [bsp_hd1 bsp_hd2] bsp_tl] //=.\n    rewrite !enc_bits_cons. move=> /andP [Henc1hd Henc1tl] /andP [Henc2hd Henc2tl].\n    move=> Hcnf Hlr.\n    rewrite add_prelude_cons in Hcnf. move/andP: Hcnf => [Hcnf_hd1 Hcnf_tl].\n    rewrite add_prelude_cons in Hcnf_tl. move/andP: Hcnf_tl => [Hcnf_hd2 Hcnf_tl].\n    have Heqhd: bsp_hd1 = bsp_hd2.\n    {\n      rewrite 2!add_prelude_singleton in Hcnf_hd1 Hcnf_hd2.\n      rewrite /= in Hcnf_hd1 Hcnf_hd2. split_andb_hyps.\n      rewrite !interp_lit_neg_lit in H0 H2. rewrite Hlr /= !orbF in H0 H2.\n      move: (expand_eq (interp_lit E ls1_hd) (interp_lit E ls2_hd)).\n      rewrite H0 H2 /= => /eqP Heq. exact: (enc_bit_eq_bit Heq Henc1hd Henc2hd).\n    }\n    move: (IH _ _ _ Henc1tl Henc2tl Hcnf_tl Hlr) => Heqtl.\n    rewrite Heqhd Heqtl. reflexivity.\nQed.\n\nLemma bit_blast_eq_neq_zip_correct E g bsp lsp g' cs lauxs:\n  bit_blast_eq_neq_zip g lsp = (g', cs, lauxs) ->\n  enc_bits E (unzip1 lsp) (unzip1 bsp) ->\n  enc_bits E (unzip2 lsp) (unzip2 bsp) ->\n  interp_cnf E (add_prelude cs) ->\n  (exists laux : literal, laux \\in lauxs /\\ interp_lit E laux) ->\n  (unzip1 bsp) <> (unzip2 bsp).\nProof.\n  elim: lsp E g bsp g' cs lauxs  => [| [ls1_hd ls2_hd] lsp_tl IH] E g bsp g' cs lauxs /=.\n  - case=> _ _ <- _ _ _ Hcontra.\n    destruct Hcontra.\n    rewrite in_nil in H. by destruct H.\n  - dcase (bit_blast_eq_neq_zip (g + 1)%positive lsp_tl) => [[[g_tl cs_tl] auxs_tl] Hblast].\n    case=> Hg Hcs Hlauxs.\n    case: bsp => [| [bsp_hd1 bsp_hd2] bsp_tl] //=.\n    rewrite !enc_bits_cons. move=> /andP [Henc1hd Henc1tl] /andP [Henc2hd Henc2tl].\n    move=> Hcnf Hlr.\n    move: Hlr => [laux [Hin Haux]].\n    rewrite -Hlauxs in_cons in Hin.\n    case/orP: Hin.\n    + move=> /eqP Hin. rewrite -Hcs in Hcnf. rewrite -/(neg_lit (Pos g)) in Hcnf.\n      rewrite  -Hin in Hcnf.\n      rewrite add_prelude_expand /= in Hcnf.\n      rewrite !interp_lit_neg_lit in Hcnf. rewrite Haux /= !orbF in Hcnf. split_andb_hyps.\n      move=> Heq. injection Heq => Heqtl Heqhd. move: H0 H1.\n      move: (enc_bit_eq_lit Heqhd Henc1hd Henc2hd) => ->.\n        by case: (interp_lit E ls2_hd).\n    + move=> Hin.\n      have Hexists: (exists laux : literal,\n                        laux \\in auxs_tl /\\ interp_lit E laux).\n      {\n        exists laux. split; last by exact: Haux.\n        exact: Hin.\n      }\n      have Hcnftl: interp_cnf E (add_prelude cs_tl).\n      {\n        rewrite -Hcs in Hcnf.\n        rewrite add_prelude_cons in Hcnf.\n        move/andP: Hcnf => [Hcnf1 Hcnf]. rewrite add_prelude_cons in Hcnf.\n        move/andP: Hcnf => [Hcnf2 Hcnf]. rewrite add_prelude_cons in Hcnf.\n        move/andP: Hcnf => [Hcnf3 Hcnf]. rewrite add_prelude_cons in Hcnf.\n        move/andP: Hcnf => [Hcnf4 Hcnf]. exact: Hcnf.\n      }\n      move: (IH _ _ _ _ _ _ Hblast Henc1tl Henc2tl Hcnftl Hexists) => Hne Heq.\n      apply: Hne. injection Heq => Heqtl Heqhd. exact: Heqtl.\nQed.\n\nLemma bit_blast_eq_choice_correct E r auxs:\n  interp_cnf E (add_prelude (bit_blast_eq_choice r auxs)) ->\n  interp_lit E r \\/ (exists aux : literal,\n                       aux \\in auxs /\\ interp_lit E aux).\nProof.\n  rewrite /bit_blast_eq_choice.\n  rewrite add_prelude_expand.\n  rewrite interp_cnf_cons /= -/(interp_clause E (r::auxs)).\n  rewrite !andbT.\n  move/andP=> [_ H].\n  case/orP: H => H.\n  - by left.\n  - right.\n    move: (interp_clause_mem H).\n    destruct 1.\n    exists x; done.\nQed.\n\nLemma bit_blast_eq_zip_correct E g bsp lsp g' cs lr:\n  bit_blast_eq_zip g lsp = (g', cs, lr) ->\n  enc_bits E (unzip1 lsp) (unzip1 bsp) ->\n  enc_bits E (unzip2 lsp) (unzip2 bsp) ->\n  interp_cnf E (add_prelude cs) ->\n  enc_bit E lr (unzip1 bsp == unzip2 bsp).\nProof.\n  rewrite /bit_blast_eq_zip.\n  rewrite /gen. case Hneq: (bit_blast_eq_neq_zip (g+1)%positive lsp) =>\n                [[g_aux cs_neq] auxs]. set r := Pos g.\n  case=> _ <- <- Henc1 Henc2 Hcnf.\n  rewrite add_prelude_catrev add_prelude_cons in Hcnf.\n  move/andP: Hcnf=> [Hcnf_neq Hcnf]. move/andP: Hcnf=> [Hcnf_auxs Hcnf_eq].\n  rewrite /enc_bit. case Hr: (interp_lit E r).\n  - apply/eqP; symmetry. apply/eqP.\n    exact: (bit_blast_eq_eq_zip_correct Henc1 Henc2 Hcnf_eq Hr).\n  - move: (bit_blast_eq_choice_correct Hcnf_auxs). rewrite Hr.\n    case => H; first by elim H. apply/eqP; symmetry. apply/eqP.\n    exact: (bit_blast_eq_neq_zip_correct Hneq Henc1 Henc2 Hcnf_neq H).\nQed.\n\nLemma bit_blast_eq_correct g bs1 bs2 E ls1 ls2 g' cs lr :\n  bit_blast_eq g ls1 ls2 = (g', cs, lr) ->\n  size ls1 = size ls2 ->\n  enc_bits E ls1 bs1 -> enc_bits E ls2 bs2 -> interp_cnf E (add_prelude cs) ->\n  enc_bit E lr (bs1 == bs2).\nProof.\n  rewrite /bit_blast_eq => Hbb Hsz Henc1 Henc2 Hcs.\n  move: (enc_bits_size Henc1) (enc_bits_size Henc2) => Hs1 Hs2.\n  move: (add_prelude_enc_bit_tt Hcs) => Henctt.\n  move: (bit_blast_eq_zip_correct Hbb\n                                  (enc_bits_unzip1_extzip Henctt Henc1 Henc2)\n                                  (enc_bits_unzip2_extzip Henctt Henc1 Henc2) Hcs).\n\n  have H1: (size bs2 <= size bs1) by rewrite -Hs1 -Hs2 Hsz.\n  have H2: (size bs1 <= size bs2) by rewrite -Hs1 -Hs2 Hsz.\n  rewrite /extzip0.\n  rewrite (unzip1_extzip_ll b0 b0 H1).\n  rewrite (unzip2_extzip_rl b0 b0 H2).\n  done.\nQed.\n\nLemma mk_env_eq_neq_zip_is_bit_blast_eq_neq_zip E g lsp E' g' cs lr:\n  mk_env_eq_neq_zip E g lsp = (E', g', cs, lr) ->\n  bit_blast_eq_neq_zip g lsp = (g', cs, lr).\nProof.\n  elim: lsp E g E' g' cs lr => [| [ls1_hd ls2_hd] lsp_tl IH ]E g E' g' cs lr //=.\n  - intros; dcase_hyps; subst; reflexivity.\n  - dcase (mk_env_eq_neq_zip\n             (env_upd E g (xorb (interp_lit E ls1_hd) (interp_lit E ls2_hd)))\n             (g + 1)%positive lsp_tl) => [[[[E_tl g_tl] cs_tl] auxs_tl] Henv_tl].\n    rewrite (IH _ _ _ _ _ _ Henv_tl).\n      by case=> _ <- <- <-.\nQed.\n\nLemma mk_env_eq_zip_is_bit_blast_eq_zip E g lsp E' g' cs lrs:\n  mk_env_eq_zip E g lsp = (E', g', cs, lrs) ->\n  bit_blast_eq_zip g lsp = (g', cs, lrs).\nProof.\n  rewrite /mk_env_eq_zip /bit_blast_eq_zip /=; intros; dcase_hyps; subst.\n  move: H.\n  dcase (mk_env_eq_neq_zip\n           (env_upd E g\n                    (interp_word E (unzip1 lsp) == interp_word E (unzip2 lsp)))\n           (g + 1)%positive lsp) => [[[[? ?] ?] ?] H].\n  rewrite (mk_env_eq_neq_zip_is_bit_blast_eq_neq_zip H).\n    by case=> _ <- <- <-.\nQed.\n\nLemma mk_env_eq_is_bit_blast_eq E g ls1 ls2 E' g' cs lr:\n  mk_env_eq E g ls1 ls2 = (E', g', cs, lr) ->\n  bit_blast_eq g ls1 ls2 = (g', cs, lr).\nProof.\n  exact: mk_env_eq_zip_is_bit_blast_eq_zip.\nQed.\n\nLemma mk_env_eq_neq_zip_newer_gen E g lsp E' g' cs lr:\n  mk_env_eq_neq_zip E g lsp = (E', g', cs, lr) ->\n  (g <=? g')%positive.\nProof.\n  elim: lsp E g E' g' cs lr => [| [ls1_hd ls2_hd] lsp_tl IH] E g E' g' cs lr /=.\n  - case; t_auto_newer.\n  - dcase (mk_env_eq_neq_zip\n             (env_upd E g (xorb (interp_lit E ls1_hd) (interp_lit E ls2_hd)))\n             (g + 1)%positive lsp_tl) => [[[[E_tl g_tl] cs_tl] auxs_tl] Henv_tl].\n    case=> _ <- _ _.\n    move: (IH _ _ _ _ _ _ Henv_tl) => H.\n    t_auto_newer.\nQed.\n\nLemma mk_env_eq_zip_newer_gen E g lsp E' g' cs lrs:\n  mk_env_eq_zip E g lsp = (E', g', cs, lrs) ->\n  (g <=? g')%positive.\nProof.\n  rewrite /mk_env_eq_zip /gen /=.\n  dcase (mk_env_eq_neq_zip\n           (env_upd E g\n                    (interp_word E (unzip1 lsp) == interp_word E (unzip2 lsp)))\n           (g + 1)%positive lsp) => [[[[? ?] ?] ?] H].\n  case=> _ <- _ _.\n  move: (mk_env_eq_neq_zip_newer_gen H).\n  by t_auto_newer.\nQed.\n\nLemma mk_env_eq_newer_gen E g ls1 ls2 E' g' cs lr:\n  mk_env_eq E g ls1 ls2 = (E', g', cs, lr) ->\n  (g <=? g')%positive.\nProof.\n  exact: mk_env_eq_zip_newer_gen.\nQed.\n\nLemma mk_env_eq_neq_zip_newer_res E g lsp E' g' cs lr:\n  mk_env_eq_neq_zip E g lsp = (E', g', cs, lr) ->\n  newer_than_lits g' lr.\nProof.\n  elim: lsp E g E' g' cs lr => [| [ls1_hd ls2_hd] lsp_tl IH] E g E' g' cs lr /=.\n  - by case=> _ <- _ <-.\n  - dcase (mk_env_eq_neq_zip\n             (env_upd E g (xorb (interp_lit E ls1_hd) (interp_lit E ls2_hd)))\n             (g + 1)%positive lsp_tl) => [[[[E_tl g_tl] cs_tl] auxs_tl] Henv_tl].\n    case=> _ <- _ <-.\n    move: (IH _ _ _ _ _ _ Henv_tl) => H.\n    move: (mk_env_eq_neq_zip_newer_gen Henv_tl) => H2.\n    t_auto_newer.\n    rewrite /newer_than_lit /newer_than_var /=.\n    by t_auto_newer.\nQed.\n\nLemma mk_env_eq_zip_newer_res E g lsp E' g' cs lr:\n  mk_env_eq_zip E g lsp = (E', g', cs, lr) ->\n  newer_than_lit g' lr.\nProof.\n  rewrite /mk_env_eq_zip /gen /=.\n  dcase (mk_env_eq_neq_zip\n           (env_upd E g\n                    (interp_word E (unzip1 lsp) == interp_word E (unzip2 lsp)))\n           (g + 1)%positive lsp) => [[[[E_aux g_aux] cs_neq] auxs] H].\n  case=> _ <- _ <-.\n  move: (mk_env_eq_neq_zip_newer_gen H).\n  t_auto_newer.\n    rewrite /newer_than_lit /newer_than_var /=.\n  by t_auto_newer.\nQed.\n\nLemma mk_env_eq_newer_res E g ls1 ls2 E' g' cs lr:\n  mk_env_eq E g ls1 ls2 = (E', g', cs, lr) ->\n  newer_than_lit g' lr.\nProof.\n  exact: mk_env_eq_zip_newer_res.\nQed.\n\nLemma bit_blast_eq_eq_zip_newer_cnf g lsp g':\n  (g <? g')%positive ->\n  newer_than_lits g (unzip1 lsp) -> newer_than_lits g (unzip2 lsp) ->\n  newer_than_cnf g' (bit_blast_eq_eq_zip (Pos g) lsp).\nProof.\n  elim: lsp g g' => [| [ls1_hd ls2_hd] lsp_tl IH] g g' //=.\n  move=> Hgg' /andP [Hnew_gls1hd Hnew_gls1tl] /andP [Hnew_gls2hd Hnew_gls2tl].\n  rewrite !newer_than_lit_neg.\n  split_andb_goal; t_auto_newer.\n  by apply: IH.\nQed.\n\nLemma mk_env_eq_neq_zip_newer_cnf E g lsp E' g' cs lr:\n  mk_env_eq_neq_zip E g lsp = (E', g', cs, lr) ->\n  newer_than_lits g (unzip1 lsp) -> newer_than_lits g (unzip2 lsp) ->\n  newer_than_cnf g' cs.\nProof.\n  elim: lsp E g E' g' cs lr => [| [ls1_hd ls2_hd] lsp_tl IH] E g  E' g' cs lr //=.\n  - by case=> _ <- <- _.\n  - dcase (mk_env_eq_neq_zip\n             (env_upd E g (xorb (interp_lit E ls1_hd) (interp_lit E ls2_hd)))\n             (g + 1)%positive lsp_tl) => [[[[E_tl g_tl] cs_tl] auxs_tl] Henv_tl].\n    case=> _ <- <- _.\n    move: (IH _ _ _ _ _ _ Henv_tl) => H.\n    move: (mk_env_eq_neq_zip_newer_gen Henv_tl) => H2.\n    move=> /andP [Hnew_gls1hd Hnew_gls1tl] /andP [Hnew_gls2hd Hnew_gls2tl].\n    rewrite /= !newer_than_lit_neg.\n    split_andb_goal; t_auto_newer.\n    all:  rewrite /newer_than_lit /newer_than_var /=; t_auto_newer.\n      by apply: H; t_auto_newer.\nQed.\n\nLemma mk_env_eq_zip_newer_cnf E g lsp E' g' cs lr:\n  mk_env_eq_zip E g lsp = (E', g', cs, lr) ->\n  newer_than_lits g (unzip1 lsp) -> newer_than_lits g (unzip2 lsp) ->\n  newer_than_cnf g' cs.\nProof.\n  rewrite /mk_env_eq_zip /gen /=.\n  dcase (mk_env_eq_neq_zip\n           (env_upd E g\n                    (interp_word E (unzip1 lsp) == interp_word E (unzip2 lsp)))\n           (g + 1)%positive lsp) => [[[[E_aux g_aux] cs_neq] auxs] H].\n  case=> _ <- <- _.\n  move: (mk_env_eq_neq_zip_newer_gen H) => Hg1gg Hnew_gls1 Hnew_gls2.\n  move: (mk_env_eq_neq_zip_newer_res H) => Hnres_eq_neq.\n  move: (mk_env_eq_neq_zip_newer_cnf H) => Hncnf_eq_neq.\n  have Hggaux: (g <? g_aux)%positive by t_auto_newer.\n  move: (bit_blast_eq_eq_zip_newer_cnf Hggaux Hnew_gls1 Hnew_gls2) => Hncnf_eq_eq.\n  t_auto_newer.\n  by apply: Hncnf_eq_neq; t_auto_newer.\nQed.\n\nLemma mk_env_eq_newer_cnf E g ls1 ls2 E' g' cs lr:\n  mk_env_eq E g ls1 ls2 = (E', g', cs, lr) ->\n  newer_than_lit g lit_tt ->\n  newer_than_lits g ls1 -> newer_than_lits g ls2 ->\n  newer_than_cnf g' cs.\nProof.\n  rewrite /mk_env_eq.\n  move=> Hzip.\n  move: (mk_env_eq_zip_newer_cnf Hzip) => Hncnf_zip.\n  move=> Hgtt Hgls1 Hgls2.\n    by apply: Hncnf_zip; t_auto_newer.\nQed.\n\nLemma mk_env_eq_neq_zip_preserve E g lsp E' g' cs lr:\n  mk_env_eq_neq_zip E g lsp = (E', g', cs, lr) ->\n  env_preserve E E' g.\nProof.\n  elim: lsp E g E' g' cs lr => [| [ls1_hd ls2_hd] lsp_tl IH] E g  E' g' cs lr //=.\n  - by case=> <- _ _ _.\n  - dcase (mk_env_eq_neq_zip\n             (env_upd E g (xorb (interp_lit E ls1_hd) (interp_lit E ls2_hd)))\n             (g + 1)%positive lsp_tl) => [[[[E_tl g_tl] cs_tl] auxs_tl] Henv_tl].\n    case=> <- _ _ _.\n    move: (IH _ _ _ _ _ _ Henv_tl) => H.\n    have H2: (env_preserve\n        (env_upd E g (xorb (interp_lit E ls1_hd) (interp_lit E ls2_hd)))\n        E_tl (g)\n) by t_auto_preserve.\n    by t_auto_preserve.\nQed.\n\nLemma mk_env_eq_zip_preserve E g lsp E' g' cs lr:\n  mk_env_eq_zip E g lsp = (E', g', cs, lr) ->\n  env_preserve E E' g.\nProof.\n  rewrite /mk_env_eq_zip /gen /=.\n  dcase (mk_env_eq_neq_zip\n           (env_upd E g\n                    (interp_word E (unzip1 lsp) == interp_word E (unzip2 lsp)))\n           (g + 1)%positive lsp) => [[[[E_aux g_aux] cs_neq] auxs] H].\n  case=> <- _ _ _.\n  move: (mk_env_eq_neq_zip_preserve H) => Hpre_eq_neq.\n  eapply env_preserve_env_upd_succ.\n  exact: Hpre_eq_neq.\nQed.\n\nLemma mk_env_eq_preserve E g ls1 ls2 E' g' cs lr:\n  mk_env_eq E g ls1 ls2 = (E', g', cs, lr) ->\n  env_preserve E E' g.\nProof.\n  exact: mk_env_eq_zip_preserve.\nQed.\n\nLemma mk_env_eq_neq_zip_sat E g lsp E' g' cs lr:\n  mk_env_eq_neq_zip E g lsp = (E', g', cs, lr) ->\n  newer_than_lits g (unzip1 lsp) -> newer_than_lits g (unzip2 lsp) ->\n  interp_cnf E' cs.\nProof.\n  elim: lsp E g E' g' cs lr => [| [ls1_hd ls2_hd] lsp_tl IH] E g  E' g' cs lr //=.\n  - by case=> <- _ <- _.\n  - dcase (mk_env_eq_neq_zip\n             (env_upd E g (xorb (interp_lit E ls1_hd) (interp_lit E ls2_hd)))\n             (g + 1)%positive lsp_tl) => [[[[E_tl g_tl] cs_tl] auxs_tl] Henv_tl].\n    case=> <- _ <- _.\n    move: (IH _ _ _ _ _ _ Henv_tl) => IHH.\n    move: (mk_env_eq_neq_zip_newer_gen Henv_tl) => H2.\n    move=> /andP [Hnew_gls1hd Hnew_gls1tl] /andP [Hnew_gls2hd Hnew_gls2tl].\n    rewrite /=.\n    have -> : (interp_cnf E_tl cs_tl) by apply: IHH; t_auto_newer.\n    rewrite /= !interp_lit_neg_lit.\n    move: (mk_env_eq_neq_zip_preserve Henv_tl) => Hpre.\n    move: (env_preserve_lit Hpre (newer_than_lit_add_diag_r (Pos g) 1))=> /= H_etlg.\n    rewrite env_upd_eq in H_etlg.\n    rewrite H_etlg.\n    have Hnew_g1ls1hd: (newer_than_lit (g+1) ls1_hd) by t_auto_newer.\n    have Hnew_g1ls2hd: (newer_than_lit (g+1) ls2_hd) by t_auto_newer.\n    move: (env_preserve_lit Hpre Hnew_g1ls1hd) (env_preserve_lit Hpre Hnew_g1ls2hd).\n    rewrite (interp_lit_env_upd_neq _ _ (newer_than_lit_neq Hnew_gls1hd)).\n    rewrite (interp_lit_env_upd_neq _ _ (newer_than_lit_neq Hnew_gls2hd)).\n    move=> -> ->.\n    by case: (interp_lit E ls1_hd); case: (interp_lit E ls2_hd).\nQed.\n\nLemma bit_blast_eq_eq_zip_sat_eq (E:env) g lsp:\n  E g ->\n  interp_word E (unzip1 lsp) == interp_word E (unzip2 lsp) ->\n  interp_cnf E (bit_blast_eq_eq_zip (Pos g) lsp).\nProof.\n  elim: lsp E g => [| [ls1_hd ls2_hd] lsp_tl IH] E g //=.\n  move=> Heg.\n  move/eqP => Heq_tl.\n  inversion Heq_tl.\n  move/eqP: H1 => H1.\n  rewrite (IH E _  Heg H1).\n  rewrite !interp_lit_neg_lit.\n  by rewrite Heg -H0; case: (interp_lit E ls1_hd).\nQed.\n\nLemma bit_blast_eq_eq_zip_sat_neq (E:env) g lsp:\n  ~~ E g ->\n  interp_cnf E (bit_blast_eq_eq_zip (Pos g) lsp).\nProof.\n  elim: lsp E g => [| [ls1_hd ls2_hd] lsp_tl IH] E g //=.\n  move=> Heg.\n  rewrite (IH E _  Heg).\n  rewrite !interp_lit_neg_lit.\n  by rewrite Heg.\nQed.\n\nLemma mk_env_eq_neq_zip_sat_neq E g lsp E' g' cs lrs:\n  mk_env_eq_neq_zip E g lsp = (E', g', cs, lrs) ->\n  newer_than_lits g (unzip1 lsp) -> newer_than_lits g (unzip2 lsp) ->\n  interp_word E' (unzip1 lsp) != interp_word E' (unzip2 lsp) ->\n  interp_clause E' lrs.\nProof.\n  elim: lsp E g E' g' cs lrs => [| [ls1_hd ls2_hd] lsp_tl IH] E g  E' g' cs lrs //=.\n  dcase (mk_env_eq_neq_zip\n           (env_upd E g (xorb (interp_lit E ls1_hd) (interp_lit E ls2_hd)))\n           (g + 1)%positive lsp_tl) => [[[[E_tl g_tl] cs_tl] auxs_tl] Henv_tl].\n  case=> <- _ _ <-.\n  move: (IH _ _ _ _ _ _ Henv_tl) => IHH.\n  move: (mk_env_eq_neq_zip_newer_gen Henv_tl) => H2.\n  move=> /andP [Hnew_gls1hd Hnew_gls1tl] /andP [Hnew_gls2hd Hnew_gls2tl].\n  rewrite /=.\n  move=> Hneq.\n  rewrite seq_neq_split in Hneq.\n  case/orP: Hneq => Hneq.\n  - move: (mk_env_eq_neq_zip_preserve Henv_tl) => Hpre.\n    move: (env_preserve_lit Hpre (newer_than_lit_add_diag_r (Pos g) 1))=> /= H_etlg.\n    rewrite env_upd_eq in H_etlg.\n    rewrite H_etlg.\n    have Hpre2: (env_preserve (env_upd E g (xorb (interp_lit E ls1_hd) (interp_lit E ls2_hd))) E_tl g) by t_auto_preserve.\n    have Hpre3: (env_preserve E E_tl g) by t_auto_preserve.\n    move: (env_preserve_lit Hpre3 Hnew_gls1hd) (env_preserve_lit Hpre3 Hnew_gls2hd).\n    move=> <- <-.\n      by move: Hneq; case: (interp_lit E_tl ls1_hd); case: (interp_lit E_tl ls2_hd).\n  - apply /orP; right.\n    by apply IHH; t_auto_newer.\nQed.\n\nLemma mk_env_eq_zip_sat E g lsp E' g' cs lr:\n  mk_env_eq_zip E g lsp = (E', g', cs, lr) ->\n  newer_than_lits g (unzip1 lsp) -> newer_than_lits g (unzip2 lsp) ->\n  interp_cnf E' cs.\nProof.\n  rewrite /mk_env_eq_zip /gen /=.\n  dcase (mk_env_eq_neq_zip\n           (env_upd E g\n                    (interp_word E (unzip1 lsp) == interp_word E (unzip2 lsp)))\n           (g + 1)%positive lsp) => [[[[E_aux g_aux] cs_neq] auxs] H].\n  case=> <- _ <- _ Hnew_gls1 Hnew_gls2.\n  move: (mk_env_eq_neq_zip_newer_gen H) => Hg1gg.\n  move: (mk_env_eq_neq_zip_newer_res H) => Hnres_eq_neq.\n  move: (mk_env_eq_neq_zip_newer_cnf H) => Hncnf_eq_neq.\n  move: (mk_env_eq_neq_zip_sat H) => Hsat_eq_neq.\n  have Hggaux: (g <? g_aux)%positive by t_auto_newer.\n  rewrite interp_cnf_catrev interp_cnf_cons.\n  have -> : interp_cnf E_aux cs_neq by apply Hsat_eq_neq; t_auto_newer.\n  rewrite andTb.\n  rewrite interp_clause_cons.\n  move: (mk_env_eq_neq_zip_preserve H) => Hpre.\n  move: (env_preserve_lit Hpre (newer_than_lit_add_diag_r (Pos g) 1))=> /= H_etlg.\n  rewrite env_upd_eq in H_etlg.\n  move: H_etlg.\n  move: (env_preserve_env_upd_succ Hpre) => Hpre2.\n  rewrite -(env_preserve_word Hpre2 Hnew_gls1) -(env_preserve_word Hpre2 Hnew_gls2).\n  case Heg: (E_aux g).\n  - rewrite /=. move=> Heq. move: (Logic.eq_sym Heq) => {Heq} Heq.\n    exact: (bit_blast_eq_eq_zip_sat_eq Heg Heq).\n  - rewrite /=. move=> Hne. move: (Logic.eq_sym Hne) => {Hne} Hne.\n    move/idP/negP: Hne => Hne. move/idP/negP: Heg => Heg.\n    rewrite (bit_blast_eq_eq_zip_sat_neq lsp Heg) andbT.\n    by apply: (mk_env_eq_neq_zip_sat_neq H _ _ Hne); t_auto_newer.\nQed.\n\nLemma mk_env_eq_sat E g ls1 ls2 E' g' cs lr:\n  mk_env_eq E g ls1 ls2 = (E', g', cs, lr) ->\n  newer_than_lit g lit_tt ->\n  newer_than_lits g ls1 -> newer_than_lits g ls2 ->\n  interp_cnf E' cs.\nProof.\n  rewrite /mk_env_eq.\n  move=> Hzip.\n  move: (mk_env_eq_zip_sat Hzip) => Hsat_zip.\n  move=> Hgtt Hgls1 Hgls2.\n    by apply: Hsat_zip; t_auto_newer.\nQed.\n\nLemma mk_env_eq_neq_zip_env_equal E1 E2 g lsp E1' E2' g1' g2' cs1 cs2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_eq_neq_zip E1 g lsp = (E1', g1', cs1, lrs1) ->\n  mk_env_eq_neq_zip E2 g lsp = (E2', g2', cs2, lrs2) ->\n  env_equal E1' E2' /\\ g1' = g2' /\\ cs1 = cs2 /\\ lrs1 = lrs2.\nProof.\n  elim: lsp E1 E2 g E1' E2' g1' g2' cs1 cs2 lrs1 lrs2 =>\n  [| [l1 l2] lsp IH] //= E1 E2 g E1' E2' g1' g2' cs1 cs2 lrs1 lrs2 Heq.\n  - case=> ? ? ? ?; case=> ? ? ? ?; subst. done.\n  - rewrite (env_equal_interp_lit l1 Heq) (env_equal_interp_lit l2 Heq).\n    dcase (mk_env_eq_neq_zip (env_upd E1 g (xorb (interp_lit E2 l1) (interp_lit E2 l2)))\n                             (g + 1)%positive lsp) => [[[[E_tl1 g_tl1] cs_tl1] lrs_tl1] Hbb_tl1].\n    dcase (mk_env_eq_neq_zip (env_upd E2 g (xorb (interp_lit E2 l1) (interp_lit E2 l2)))\n                             (g + 1)%positive lsp) => [[[[E_tl2 g_tl2] cs_tl2] lrs_tl2] Hbb_tl2].\n    case=> ? ? ? ?; case=> ? ? ? ?; subst.\n    move: (env_equal_upd g (xorb (interp_lit E2 l1) (interp_lit E2 l2)) Heq) => Heq1.\n    move: (IH _ _ _ _ _ _ _ _ _ _ _ Heq1 Hbb_tl1 Hbb_tl2) => [Heq2 [? [? ?]]]; subst.\n    done.\nQed.\n\nLemma mk_env_eq_zip_env_equal E1 E2 g lsp E1' E2' g1' g2' cs1 cs2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_eq_zip E1 g lsp = (E1', g1', cs1, lrs1) ->\n  mk_env_eq_zip E2 g lsp = (E2', g2', cs2, lrs2) ->\n  env_equal E1' E2' /\\ g1' = g2' /\\ cs1 = cs2 /\\ lrs1 = lrs2.\nProof.\n  rewrite /mk_env_eq_zip => Heq. dcase (gen g) => [[g1 r1] Hg1].\n  dcase (mk_env_eq_neq_zip\n           (env_upd E1 (var_of_lit r1)\n                    (interp_word E1 (unzip1 lsp) == interp_word E1 (unzip2 lsp)))\n           g1 lsp) => [[[[E_aux1 g_aux1] cs_aux1] lrs_aux1] Hbb_aux1].\n  dcase (mk_env_eq_neq_zip\n           (env_upd E2 (var_of_lit r1)\n                    (interp_word E2 (unzip1 lsp) == interp_word E2 (unzip2 lsp)))\n           g1 lsp) => [[[[E_aux2 g_aux2] cs_aux2] lrs_aux2] Hbb_aux2].\n  case=> ? ? ? ?; case=> ? ? ? ?; subst.\n  rewrite !(env_equal_interp_word _ Heq) in Hbb_aux1.\n  move: (env_equal_upd (var_of_lit lrs2)\n                       (interp_word E2 (unzip1 lsp) == interp_word E2 (unzip2 lsp)) Heq) => Heq1.\n  move: (mk_env_eq_neq_zip_env_equal Heq1 Hbb_aux1 Hbb_aux2) => [Heq2 [? [? ?]]]; subst.\n  done.\nQed.\n\nLemma mk_env_eq_env_equal E1 E2 g ls1 ls2 E1' E2' g1' g2' cs1 cs2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_eq E1 g ls1 ls2 = (E1', g1', cs1, lrs1) ->\n  mk_env_eq E2 g ls1 ls2 = (E2', g2', cs2, lrs2) ->\n  env_equal E1' E2' /\\ g1' = g2' /\\ cs1 = cs2 /\\ lrs1 = lrs2.\nProof. exact: mk_env_eq_zip_env_equal. Qed.\n", "meta": {"author": "fmlab-iis", "repo": "coq-qfbv", "sha": "0e9521febd1564747723a773d25e54781e81b762", "save_path": "github-repos/coq/fmlab-iis-coq-qfbv", "path": "github-repos/coq/fmlab-iis-coq-qfbv/coq-qfbv-0e9521febd1564747723a773d25e54781e81b762/src/BBEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2330862796605524}}
{"text": "(************************************************************************)\n(* Copyright (c) 2022, Gergei Bana, Rohit Chadha, Ajay Kumar Eeralla,   *)\n(* Qianli Zhang                                                         *)\n(*                                                                      *)\n(* This work is licensed under the MIT license. The license is          *)\n(* described in the file \"LICENSE\" available at the root of the source  *)\n(* or at https://opensource.org/licenses/MIT                            *)\n(************************************************************************)\n\n\nRequire Import Coq.micromega.Lia.\nRequire Export prop21.\nImport ListNotations.\n\n\n\n(***********************************************************************************************************************************)\n\n\n(**)\nLemma elim_isinkc0_under_bcheck0_in_ELSE_branch : forall s,\n  (fun c0 c1 => ((fun enco1 => (fun o1 o2 o3 => Do o1 o2 o3  ) (FGO1 c0 c1 ⫠ enco1) (FGO2 c0 c1 ⫠ enco1) (FGO3 c0 c1 ⫠ enco1)) (enco1 c0 c1 kc1))\n           = ((fun enco1 => (fun o1 o2 o3 => FIDO o1 o2 o3) (FGO1 c0 c1 ⫠ enco1) (FGO2 c0 c1 ⫠ enco1) (FGO3 c0 c1 ⫠ enco1)) (enco1 c0 c1 kc1))) (c0 s) (c1 s).\nProof.\n  intros; simpl.\n  unfold Do.\n  unfold isinkc.\n  assert (isin kc0 (＜ π2 (π1 FGO1 (c0 s) (c1 s) ⫠ (enco1 (c0 s) (c1 s) kc1)), π2 (π1 FGO2 (c0 s) (c1 s) ⫠ (enco1 (c0 s) (c1 s) kc1)), π2 (π1 FGO3 (c0 s) (c1 s) ⫠ (enco1 (c0 s) (c1 s) kc1)) ＞) = FAlse).\n    unfold isin.\n    rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n    rewrite Freshkc0FGO1_15, Freshkc0FGO2_15, Freshkc0FGO3_15.\n    repeat rewrite If_false.\n    reflexivity.\n  rewrite H. clear H.\n  rewrite If_false.\n  reflexivity.\nQed.\n\n\n\n\n\n(* actually the encryption enco0 can be anything excludes kc0  *)\n(*  *)\nLemma GIIO_GIO_equiv_under_FIDO: forall s,\n    (fun c0 c1 => ((fun enco1 m => (fun o1 o2 o3 => FIDO o1 o2 o3) (GIIO1 c0 c1 enco1 m) (GIIO2 c0 c1 enco1 m) (GIIO3 c0 c1 enco1 m))  (enco1 c0 c1 kc1')\n                                                                                                                           (＜ ＜ label c1 (fΦΦ3 c0 c1), kc1 ＞, ph3 ＞))\n             = ((fun enco1 =>   (fun o1 o2 o3 => FIDO o1 o2 o3) (GIO1 c0 c1 enco1)    (GIO2 c0 c1 enco1)    (GIO3 c0 c1 enco1))  (enco1 c0 c1 kc1'))) (c0 s) (c1 s).\nProof.\n  intros. simpl.\n\n  pose (ContextPhase5_15 s) as HH.\n  pose (ContextEnco1 s) as HH0.\n  pose (ContextPhase3_15 s) as HH1.\n\n(* left hand side *)\n  rewrite (GuardAhead' (FIDO (GIIO1 (c0 s) (c1 s) (enco1 (c0 s) (c1 s) kc1') (＜ ＜ label (c1 s) (fΦΦ3 (c0 s) (c1 s)), kc1 ＞, ph3 ＞))\n                             (GIIO2 (c0 s) (c1 s) (enco1 (c0 s) (c1 s) kc1') (＜ ＜ label (c1 s) (fΦΦ3 (c0 s) (c1 s)), kc1 ＞, ph3 ＞))\n                             (GIIO3 (c0 s) (c1 s) (enco1 (c0 s) (c1 s) kc1') (＜ ＜ label (c1 s) (fΦΦ3 (c0 s) (c1 s)), kc1 ＞, ph3 ＞)))\n                       (τ1 (FGΦΦ5 (c0 s) (c1 s) ⫠ (enco1 (c0 s) (c1 s) kc1')) ≟ enco1 (c0 s) (c1 s) kc1')\n                       (τ2 (FGΦΦ5 (c0 s) (c1 s) ⫠ (enco1 (c0 s) (c1 s) kc1')) ≟ enco1 (c0 s) (c1 s) kc1' )\n                       (τ3 (FGΦΦ5 (c0 s) (c1 s) ⫠ (enco1 (c0 s) (c1 s) kc1')) ≟ enco1 (c0 s) (c1 s) kc1' )).\n  unfold GIIO3. repeat rewrite decSimpl.\n  rewrite (@If_eval (fun b3 =>  FIDO _ _ (If b3 Then _ Else _)) (fun b3 => FIDO _ _ (If b3 Then _ Else _))).\n  rewrite If_true, If_false.\n  unfold GIIO2. repeat rewrite decSimpl.\n  rewrite (@If_eval (fun b2 => If _ Then FIDO _ (If b2 Then _ Else _) _ Else FIDO _ (If b2 Then _ Else _) _)\n                    (fun b2 => If _ Then FIDO _ (If b2 Then _ Else _) _ Else FIDO _ (If b2 Then _ Else _) _)).\n  rewrite If_true, If_false.\n  unfold GIIO1. repeat rewrite decSimpl.\n  rewrite (@If_eval (fun b1 => If _ Then If _ Then FIDO (If b1 Then _ Else _) _ _ Else FIDO (If b1 Then _ Else _) _ _\n                                 Else If _ Then FIDO (If b1 Then _ Else _) _ _ Else FIDO (If b1 Then _ Else _) _ _ )\n                    (fun b1 => If _ Then If _ Then FIDO (If b1 Then _ Else _) _ _ Else FIDO (If b1 Then _ Else _) _ _\n                                 Else If _ Then FIDO (If b1 Then _ Else _) _ _ Else FIDO (If b1 Then _ Else _) _ _ )).\n  rewrite If_true, If_false.\n\n  unfold FIDO at 1 2 3 4 5 6 7. unfold isin.\n  repeat rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n  repeat rewrite proj1pair.\n  repeat rewrite proj2pair.\n  repeat rewrite ceqeq.\n  repeat rewrite If_true.\n  repeat rewrite If_same.\n  repeat rewrite If_true.\n  repeat rewrite If_false.\n  repeat rewrite If_same.\n  repeat rewrite If_false.\n  repeat rewrite If_same.\n\n\n(* Right hand side *)\n  rewrite (GuardAhead' (FIDO (GIO1 (c0 s) (c1 s) (enco1 (c0 s) (c1 s) kc1')) (GIO2 (c0 s) (c1 s) (enco1 (c0 s) (c1 s) kc1')) (GIO3 (c0 s) (c1 s) (enco1 (c0 s) (c1 s) kc1')))\n                       (τ1 (FGΦΦ5 (c0 s) (c1 s) ⫠ (enco1 (c0 s) (c1 s) kc1')) ≟ (enco1 (c0 s) (c1 s) kc1'))\n                       (τ2 (FGΦΦ5 (c0 s) (c1 s) ⫠ (enco1 (c0 s) (c1 s) kc1')) ≟ (enco1 (c0 s) (c1 s) kc1'))\n                       (τ3 (FGΦΦ5 (c0 s) (c1 s) ⫠ (enco1 (c0 s) (c1 s) kc1')) ≟ (enco1 (c0 s) (c1 s) kc1'))).\n  unfold GIO3.\n  rewrite (@If_eval (fun b3 =>  FIDO _ _ (If b3 Then _ Else _)) (fun b3 => FIDO _ _ (If b3 Then _ Else _))).\n  rewrite If_true, If_false.\n  unfold GIO2.\n  rewrite (@If_eval (fun b2 => If _ Then FIDO _ (If b2 Then _ Else _) _ Else FIDO _ (If b2 Then _ Else _) _)\n                    (fun b2 => If _ Then FIDO _ (If b2 Then _ Else _) _ Else FIDO _ (If b2 Then _ Else _) _)).\n  rewrite If_true, If_false.\n  unfold GIO1.\n  rewrite (@If_eval (fun b1 => If _ Then If _ Then FIDO (If b1 Then _ Else _) _ _ Else FIDO (If b1 Then _ Else _) _ _\n                                 Else If _ Then FIDO (If b1 Then _ Else _) _ _ Else FIDO (If b1 Then _ Else _) _ _ )\n                    (fun b1 => If _ Then If _ Then FIDO (If b1 Then _ Else _) _ _ Else FIDO (If b1 Then _ Else _) _ _\n                                 Else If _ Then FIDO (If b1 Then _ Else _) _ _ Else FIDO (If b1 Then _ Else _) _ _ )).\n  rewrite If_true, If_false.\n\n  unfold FIDO at 2 3 4 5 6 7 8. unfold pchko.\n  repeat rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n  repeat rewrite proj2pair.\n  repeat rewrite ph2Neqph3.\n  repeat rewrite If_false.\n  repeat rewrite If_same.\n  repeat rewrite If_false.\n  repeat rewrite If_same.\n  repeat rewrite If_false.\n  repeat rewrite If_same.\n  reflexivity.\n\n\n  all: time ProveboolandContext. (* 11.55 secs *)\n\nQed.\n\n\n\n\n\n\n(* *)\nLemma elim_isinkc1_after_CCA2 : forall s,\n    (fun c0 c1 => ((fun enco1 => (fun o1 o2 o3 => FIDO o1 o2 o3) (GIO1 c0 c1 enco1)  (GIO2 c0 c1 enco1)  (GIO3 c0 c1 enco1))  (enco1 c0 c1 kc1'))\n             = ((fun enco1 => (fun o1 o2 o3 => FDO o1 o2 o3)  (GIO1 c0 c1 enco1)  (GIO2 c0 c1 enco1)  (GIO3 c0 c1 enco1))  (enco1 c0 c1 kc1'))) (c0 s) (c1 s).\nProof.\n  intros. simpl.\n  unfold FIDO.\n\n  assert (isin kc1 (＜ π2 (π1 GIO1 (c0 s) (c1 s) (enco1 (c0 s) (c1 s) kc1')), π2 (π1 GIO2 (c0 s) (c1 s) (enco1 (c0 s) (c1 s) kc1')), π2 (π1 GIO3 (c0 s) (c1 s) (enco1 (c0 s) (c1 s) kc1')) ＞) = FAlse).\n    unfold isin.\n    rewrite Tau1Tri, Tau2Tri, Tau3Tri.\n    rewrite kc1FreshGIO1, kc1FreshGIO2, kc1FreshGIO3.\n    repeat rewrite If_false.\n    reflexivity.\n\n  rewrite H; clear H.\n  rewrite If_false. rewrite <- If_tf.\n  reflexivity.\n  unfold pchko. Provebool.\nQed.\n\n\n(* *)\n\n(* *)\n\n(* *)\n\n\n\n(* first we use CCA2 for the second encryption of the opening phase *)\nLemma prop26_formula15_helper:  forall s, (fun c0 c1 =>\n     ((fun enco1 => (fun o1 o2 o3 =>\n       [b0 c0; b1 c1; acc0 c0 c1 & acc1 c0 c1; bnlcheck c0 n0 (fΦΦ3 c0 c1); bnlcheck c1 n1 (fΦΦ3 c0 c1);\n  ＜ ＜ e0 c0 c1 n0, e1 c0 c1 n1, dv (v1 c0 c1) (v2 c0 c1) (v3 c0 c1) (s26 c0 c1 (v3 c0 c1)) ＞,\n  ＜ ⫠, enco1, Do o1 o2 o3 ＞ ＞]) (FGO1 c0 c1 ⫠ enco1 ) (FGO2 c0 c1 ⫠ enco1) (FGO3 c0 c1 ⫠ enco1)) (enco1 c0 c1 kc1))\n ~\n    ((fun enco1 => (fun o1 o2 o3 =>\n    [b0 c0; b1 c1; acc0 c0 c1 & acc1 c0 c1; bnlcheck c0 n0 (fΦΦ3 c0 c1); bnlcheck c1 n1 (fΦΦ3 c0 c1);\n  ＜ ＜ e0 c0 c1 n0, e1 c0 c1 n1, dv (v1 c0 c1) (v2 c0 c1) (v3 c0 c1) (s26 c0 c1 (v3 c0 c1)) ＞,\n  ＜ ⫠, enco1, FDO o1 o2 o3 ＞ ＞]) (GIO1 c0 c1 enco1) (GIO2 c0 c1 enco1) (GIO3 c0 c1 enco1)) (enco1 c0 c1 kc1'))) (c0 s) (c1 s).\nProof.\n  intros s. simpl.\n\n(* elim the isinkc1 check in Do, change Do to GIDO *)\n  rewrite (elim_isinkc0_under_bcheck0_in_ELSE_branch s).\n\n\n(* usc CCA2 to substitute (FGO enco0) to (FGIIO enco0') on the left hand side*)\n  unfold FGO1.\n  rewrite (decIfThenElse (＜ ＜ label (c1 s) (fΦΦ3 (c0 s) (c1 s)), kc1 ＞, ph3 ＞) 11 (τ1 (FGΦΦ5 (c0 s) (c1 s) ⫠ (enco1 (c0 s) (c1 s) kc1)))).\n  unfold FGO2.\n  rewrite (decIfThenElse (＜ ＜ label (c1 s) (fΦΦ3 (c0 s) (c1 s)), kc1 ＞, ph3 ＞) 11 (τ2 (FGΦΦ5 (c0 s) (c1 s) ⫠ (enco1 (c0 s) (c1 s) kc1)))).\n  unfold FGO3.\n  rewrite (decIfThenElse (＜ ＜ label (c1 s) (fΦΦ3 (c0 s) (c1 s)), kc1 ＞, ph3 ＞) 11 (τ3 (FGΦΦ5 (c0 s) (c1 s) ⫠ (enco1 (c0 s) (c1 s) kc1)))).\n  pose (cca2 [nonce 6] [nonce 11]\n            (fun enco1 => [b0 (c0 s); b1 (c1 s); acc0 (c0 s) (c1 s) & acc1 (c0 s) (c1 s);\n                                   bnlcheck (c0 s) n0 (fΦΦ3 (c0 s) (c1 s)); bnlcheck (c1 s) n1 (fΦΦ3 (c0 s) (c1 s));\n                                   ＜ ＜ e0 (c0 s) (c1 s) n0, e1 (c0 s) (c1 s) n1, dv (v1 (c0 s) (c1 s)) (v2 (c0 s) (c1 s)) (v3 (c0 s) (c1 s)) (s26 (c0 s) (c1 s) (v3 (c0 s) (c1 s))) ＞,\n                                   ＜ ⫠,  enco1 , (FIDO (GIIO1 (c0 s) (c1 s) enco1 (＜ ＜ label (c1 s) (fΦΦ3 (c0 s) (c1 s)), kc1 ＞, ph3 ＞))\n                                                       (GIIO2 (c0 s) (c1 s) enco1 (＜ ＜ label (c1 s) (fΦΦ3 (c0 s) (c1 s)), kc1 ＞, ph3 ＞)) (* shit, here should be FIIO2!!!*)\n                                                       (GIIO3 (c0 s) (c1 s) enco1 (＜ ＜ label (c1 s) (fΦΦ3 (c0 s) (c1 s)), kc1 ＞, ph3 ＞)))＞＞])\n             (＜ ＜ label (c1 s) (fΦΦ3 (c0 s) (c1 s)), kc1 ＞, ph3 ＞) (＜ ＜ label (c1 s) (fΦΦ3 (c0 s) (c1 s)), kc1' ＞, ph3 ＞)) as claim0; simpl in claim0.\n  rewrite claim0. clear claim0.\n\n\n(* reduce (FGIIO enco0') to (FGIO enco0')*)\n  rewrite GIIO_GIO_equiv_under_FIDO.\n\n(* change FIIO*)\n  rewrite elim_isinkc1_after_CCA2.\n  reflexivity.\n\n  clear claim0.\n  4: apply (CCA2Beforekc1_formula15).\n  4: apply (CCA2Beforekc1'_formula15).\n  4: apply CCA2AfterLemma26_formula15.\n\n  all : ProveCCA2.\n  ProveListFresh; try lia; constructor.\n\n  apply PairLen.\n  - apply PairLen.\n    + reflexivity.\n    + apply ComkLen.\n  - reflexivity.\nQed.\n\n\n\n\n(*  *)\n\n(* formula 15  on page 40  *)\nProposition prop26_formula15 :\n  (fun c0 c1 => ((fun enco1 => (fun o1 o2 o3 =>\n       [b0 c0; b1 c1; acc0 c0 c1 & acc1 c0 c1; bnlcheck c0 n0 (fΦΦ3 c0 c1); bnlcheck c1 n1 (fΦΦ3 c0 c1);\n  ＜ ＜ e0 c0 c1 n0, e1 c0 c1 n1, dv (v1 c0 c1) (v2 c0 c1) (v3 c0 c1) (s26 c0 c1 (v3 c0 c1)) ＞,\n  ＜ ⫠, enco1, Do o1 o2 o3 ＞ ＞]) (FGO1 c0 c1 ⫠ enco1) (FGO2 c0 c1 ⫠ enco1) (FGO3 c0 c1 ⫠ enco1)) (enco1 c0 c1 kc1))) (c0 lhs) (c1 lhs)\n ~\n   (fun c0 c1 => ((fun enco1 => (fun o1 o2 o3 =>\n       [b0 c0; b1 c1; acc0 c0 c1 & acc1 c0 c1; bnlcheck c0 n0 (fΦΦ3 c0 c1); bnlcheck c1 n1 (fΦΦ3 c0 c1);\n  ＜ ＜ e0 c0 c1 n0, e1 c0 c1 n1, dv (v1 c0 c1) (v2 c0 c1) (v3 c0 c1) (s26 c0 c1 (v3 c0 c1)) ＞,\n  ＜ ⫠, enco1, Do o1 o2 o3 ＞ ＞]) (FGO1 c0 c1 ⫠ enco1) (FGO2 c0 c1 ⫠ enco1) (FGO3 c0 c1 ⫠ enco1)) (enco1 c0 c1 kc1))) (c0 rhs) (c1 rhs).\n\nProof.\n  intros.\n(* use prop26_lemma14_helper to change both sides from {Do FGO} to {FDO FIO} *)\n  rewrite (prop26_formula15_helper lhs).\n  rewrite (prop26_formula15_helper rhs).\n\n(* use commitment hidding *)\n   apply (@CompHidEx (fun lx => let c0 := Nth 0 lx in let c1 := Nth 1 lx in\n         [b0 c0; b1 c1; acc0 c0 c1 & acc1 c0 c1; bnlcheck c0 n0 (fΦΦ3 c0 c1); bnlcheck c1 n1 (fΦΦ3 c0 c1);\n          ＜ ＜ e0 c0 c1 n0, e1 c0 c1 n1, dv (v1 c0 c1) (v2 c0 c1) (v3 c0 c1) (s26 c0 c1 (v3 c0 c1)) ＞,\n             ＜ ⫠, enco1 c0 c1 kc1',  FDO (GIO1 c0 c1 (enco1 c0 c1 kc1')) (GIO2 c0 c1 (enco1 c0 c1 kc1')) (GIO3 c0 c1 (enco1 c0 c1 kc1')) ＞ ＞])\n                    vot0 vot1 0 1).\n  apply voteLen.\n  lia. ProveFresh.\n  apply Freshc_kc0_Lemma26_15.\n  ProveFresh.\n  apply Freshc_kc1_Lemma26_15.\nQed.\n", "meta": {"author": "kmilesz", "repo": "CCSA_FOO_Verification", "sha": "bb33875f975bcb266acacec1980b13c9631c273e", "save_path": "github-repos/coq/kmilesz-CCSA_FOO_Verification", "path": "github-repos/coq/kmilesz-CCSA_FOO_Verification/CCSA_FOO_Verification-bb33875f975bcb266acacec1980b13c9631c273e/FOO/lemma26_15.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23305798757479917}}
{"text": "Require Import String.\nRequire Import NPeano.\nRequire Import PeanoNat.\nRequire Import Coq.Strings.Ascii.\nRequire FMapWeakList.\nRequire Export Coq.Structures.OrderedTypeEx.\nRequire Import Lists.List.\nImport ListNotations.\nRequire Import JaSyntax.\nRequire Import JaTypes.\nRequire Import JaProgram.\nRequire Import JaEnvs.\nRequire Import Jafun.\nRequire Import JaIrisCommon.\nRequire Import JaIrisPermutation.\nRequire Import JaEval.\nRequire Import JaIris.\nRequire Import JaSubtype.\nRequire Import Bool.\nRequire Import Classical_Prop.\nRequire Import Classical_Pred_Type.\n\nRequire Export FMapAVL.\nRequire Export Coq.Structures.OrderedTypeEx.\nRequire Import FMapFacts.\n\n\nModule HeapFacts := JaIrisCommon.HeapFacts.\nModule StrMapFacts := JaIrisCommon.StrMapFacts.\nModule NatMapFacts := JaIrisCommon.NatMapFacts.\nModule JFXIdMapFacts := Facts JFXIdMap.\n\nDefinition JFISemanticallyImplies (gamma : JFITypeEnv) (s : JFITerm) (p : JFITerm) (CC : JFProgram) :=\n  forall env this h,\n    JFIGammaMatchEnv h gamma env ->\n    JFIHeapSatisfiesInEnv h s env this CC ->\n    JFIHeapSatisfiesInEnv h p env this CC.\n\nDefinition JFISemanticallyImpliesOuter (gamma : JFITypeEnv) (s : JFIOuterTerm) (p : JFIOuterTerm) (CC : JFProgram) :=\n  forall env this h,\n    (JFIGammaMatchEnv h gamma env) ->\n    (JFIHeapSatisfiesOuterInEnv h s env this CC) ->\n     JFIHeapSatisfiesOuterInEnv h p env this CC.\n\nLtac unfoldSubstitutions :=\n  unfold JFITermSubstituteVals;\n  unfold JFITermSubstituteVar;\n  unfold JFITermSubstituteVal;\n  unfold JFIExprSubstituteVar;\n  unfold JFIValSubstituteVal;\n  unfold JFIStringSubstitute;\n  simpl.\n\nLemma LocNotNullIff : forall loc,\n  (exists n, loc = JFLoc n) <-> (loc <> null).\nProof.\n  intro loc .\n  split.\n  + intros (n & loc_is_n).\n    rewrite loc_is_n.\n    unfold not.\n    discriminate.\n  + intros loc_is_not_null.\n    destruct loc.\n    ++ exfalso.\n       apply loc_is_not_null.\n       trivial.\n    ++ exists n.\n       trivial.\nQed.\n\n(* =============== StrMap Lemmas =============== *)\n\nLemma StrMap_in_find_iff : forall t m x,\n  (StrMap.In x m) <-> (exists e : t, StrMap.find x m = Some e).\nProof.\n  intros t m x.\n  split.\n  + intros x_in_m.\n    apply StrMapFacts.elements_in_iff in x_in_m.\n    destruct x_in_m as ( e & e_in_elements ).\n    apply StrMapFacts.elements_mapsto_iff in e_in_elements.\n    apply StrMapFacts.find_mapsto_iff in e_in_elements.\n    exists e.\n    exact e_in_elements.\n  + intros find_gives_some.\n    apply StrMapFacts.elements_in_iff.\n    destruct find_gives_some as ( e & find_gives_e).\n    exists e.\n    apply StrMapFacts.elements_mapsto_iff.\n    apply StrMapFacts.find_mapsto_iff.\n    exact find_gives_e.\nQed.\n\n(* =============== Gamma Match Env Lemmas =============== *)\n\nLemma ExtendedGammaMatchesExtendedEnv : forall x l type env gamma h,\n  (JFIGammaMatchEnv h gamma env) ->\n  (JFILocOfType l h type) ->\n  (JFIGammaMatchEnv h (JFIGammaAdd x type gamma) ((StrMap.add x l env))).\nProof.\n  intros x l type env gamma h.\n  intros gamma_match_env loc_of_type.\n  unfold JFIGammaAdd.\n  unfold JFIGammaMatchEnv.\n  intros var_name.\n  split.\n  + split;\n      (intros x_in;\n       apply StrMapFacts.add_in_iff in x_in;\n       apply StrMapFacts.add_in_iff;\n       rewrite <- String.eqb_eq in *;\n       destruct (String.eqb x var_name); auto;\n       destruct x_in as [ false_eq_true | var_in]; try discriminate false_eq_true;\n       apply or_intror;\n       assert (in_iff := (proj1 (gamma_match_env var_name)));\n       apply in_iff;\n       assumption).\n  + intros var_loc var_type var_is_some_type.\n    intros var_is_some_loc.\n    rewrite StrMapFacts.find_mapsto_iff, StrMapFacts.add_o in var_is_some_type, var_is_some_loc.\n    destruct (StrMapFacts.eq_dec x var_name).\n    ++ injection var_is_some_type as type_eq_var_type.\n       injection var_is_some_loc as l_eq_var_loc.\n       rewrite <- type_eq_var_type, <- l_eq_var_loc.\n       assumption.\n    ++ apply (proj2 (gamma_match_env var_name)); rewrite StrMapFacts.find_mapsto_iff; try assumption.\nQed.\n\nLemma StrictlyExtendedGammaMatchesExtendedEnv : forall x l type env gamma gamma_x h,\n  (JFIGammaMatchEnv h gamma env) ->\n  (JFILocOfType l h type) ->\n  (JFIGammaAddNew x type gamma = Some gamma_x) ->\n  (JFIGammaMatchEnv h gamma_x ((StrMap.add x l env))).\nProof.\n  intros x l type env gamma gamma_x h.\n  intros gamma_match_env loc_of_type add_new_x.\n  replace gamma_x with (StrMap.add x type gamma). \n  + apply ExtendedGammaMatchesExtendedEnv.\n    ++ exact gamma_match_env.\n    ++ exact loc_of_type.\n  + unfold JFIGammaAddNew in add_new_x.\n    destruct (StrMap.mem (elt:=JFClassName) x gamma).\n    ++ discriminate add_new_x.\n    ++ injection add_new_x. trivial.\nQed.\n\n\n(* Framework for heap satisfying equivalence lemmas *)\n\nDefinition HeapEnvEquivalent h h' env env' this this' t CC :=\n  JFIHeapSatisfiesInEnv h t env this CC <-> JFIHeapSatisfiesInEnv h' t env' this' CC.\n\nDefinition HeapEnvEquivalentOuter h h' env env' this this' t CC :=\n  JFIHeapSatisfiesOuterInEnv h t env this CC <-> JFIHeapSatisfiesOuterInEnv h' t env' this' CC.\n\nLemma TrueEquivalence : forall h h' env env' this this' CC,\n  HeapEnvEquivalent h h' env env' this this' JFITrue CC.\nProof.\n  intros.\n  easy.\nQed.\nHint Resolve TrueEquivalence : core.\n\nLemma FalseEquivalence : forall h h' env env' this this' CC,\n  HeapEnvEquivalent h h' env env' this this' JFIFalse CC.\nProof.\n  intros.\n  easy.\nQed.\nHint Resolve FalseEquivalence : core.\n\nLemma AndPreservesEquivalence : forall h h' env env' this this' t1 t2 CC,\n  HeapEnvEquivalent h h' env env' this this' t1 CC ->\n  HeapEnvEquivalent h h' env env' this this' t2 CC ->\n  HeapEnvEquivalent h h' env env' this this' (JFIAnd t1 t2) CC.\nProof.\n  intros h h' env env' this this' t1 t2 CC.\n  intros t1_equivalence t2_equivalence.\n  unfold HeapEnvEquivalent in *.\n  split; intro; split; destruct H.\n  + now apply t1_equivalence.\n  + now apply t2_equivalence.\n  + now apply t1_equivalence.\n  + now apply t2_equivalence.\nQed.\nHint Resolve AndPreservesEquivalence : core.\n\nLemma OrPreservesEquivalence : forall h h' env env' this this' t1 t2 CC,\n  HeapEnvEquivalent h h' env env' this this' t1 CC ->\n  HeapEnvEquivalent h h' env env' this this' t2 CC ->\n  HeapEnvEquivalent h h' env env' this this' (JFIOr t1 t2) CC.\nProof.\n  intros h h' env env' this this' t1 t2 CC.\n  intros t1_equivalence t2_equivalence.\n  unfold HeapEnvEquivalent in *.\n  split; intro; simpl; destruct H.\n  + apply or_introl; now apply t1_equivalence.\n  + apply or_intror; now apply t2_equivalence.\n  + apply or_introl; now apply t1_equivalence.\n  + apply or_intror; now apply t2_equivalence.\nQed.\nHint Resolve OrPreservesEquivalence : core.\n\nLemma ImpliesPreservesEquivalence : forall h h' env env' this this' t1 t2 CC,\n  HeapEnvEquivalent h h' env env' this this' t1 CC ->\n  HeapEnvEquivalent h h' env env' this this' t2 CC ->\n  HeapEnvEquivalent h h' env env' this this' (JFIImplies t1 t2) CC.\nProof.\n  intros h h' env env' this this' t1 t2 CC.\n  intros t1_equivalence t2_equivalence.\n  unfold HeapEnvEquivalent in *.\n  split; intro; simpl; destruct H.\n  + apply or_introl. intro. apply H. now apply t1_equivalence.\n  + apply or_intror; now apply t2_equivalence.\n  + apply or_introl. intro. apply H. now apply t1_equivalence.\n  + apply or_intror; now apply t2_equivalence.\nQed.\nHint Resolve ImpliesPreservesEquivalence : core.\n\n(* =============== Env Lemmas =============== *)\n\nLemma DifferentVarIsFresh : forall v w,\n  (w <> JFIVar v) -> JFIVarFreshInVal v w.\nProof.\n  intros v w.\n  intros w_is_not_v.\n  unfold JFIVarFreshInVal.\n  destruct w; try trivial.\n  unfold not.\n  intros v_eq_x.\n  apply f_equal with (f := fun x => JFIVar x) in v_eq_x.\n  symmetry in v_eq_x.\n  exact (w_is_not_v v_eq_x).\nQed.\n\nLemma AddingFreshVarPreservesValToLoc : forall x l val env this,\n  (JFIVarFreshInVal x val) ->\n   JFIValToLoc val env this = JFIValToLoc val (StrMap.add x l env) this.\nProof.\n  intros x l val env this.\n  intros x_fresh.\n  unfold JFIValToLoc.\n  destruct val as [ |  | loc]; trivial.\n  + symmetry.\n    apply StrMapFacts.add_neq_o.\n    unfold JFIVarFreshInVal in x_fresh.\n    exact x_fresh.\nQed.\n\nLemma AddingFreshVarPreservesHeapSatisfyingEq : forall val1 val2 x l env this h CC,\n  (JFIVarFreshInTerm x (JFIEq val1 val2)) ->\n    ((JFIHeapSatisfiesInEnv h (JFIEq val1 val2) env this CC) <->\n      JFIHeapSatisfiesInEnv h (JFIEq val1 val2) (StrMap.add x l env) this CC).\nProof.\n  intros val1 val2 x l env this h CC.\n  intros x_fresh.\n  split.\n  + intros h_satisfies_eq.\n    simpl.\n    simpl in h_satisfies_eq.\n    replace (JFIValToLoc val1 (StrMap.add x l env) this) with (JFIValToLoc val1 env this).\n    replace (JFIValToLoc val2 (StrMap.add x l env) this) with (JFIValToLoc val2 env this).\n    ++ exact h_satisfies_eq.\n    ++ apply AddingFreshVarPreservesValToLoc.\n       apply x_fresh.\n    ++ apply AddingFreshVarPreservesValToLoc.\n       apply x_fresh.\n  + intros h_satisfies_eq.\n    simpl.\n    simpl in h_satisfies_eq.\n    now rewrite <-2!AddingFreshVarPreservesValToLoc with (x := x) (l := l) in h_satisfies_eq; try apply x_fresh.\nQed.\n\nLemma AddingFreshVarPreservesHeapSatisfyingFieldEq : forall obj field val x l env this h CC,\n  (JFIVarFreshInTerm x (JFIFieldEq obj field val)) ->\n    ((JFIHeapSatisfiesInEnv h (JFIFieldEq obj field val) env this CC) <->\n      JFIHeapSatisfiesInEnv h (JFIFieldEq obj field val) (StrMap.add x l env) this CC).\nProof.\n  intros obj field val x l env this h CC.\n  intros (x_fresh_in_obj & x_fresh_in_val).\n  split.\n  + intros h_satisfies_eq.\n    simpl.\n    simpl in h_satisfies_eq.\n    now rewrite <-2!AddingFreshVarPreservesValToLoc.\n  + intros h_satisfies_eq.\n    simpl.\n    simpl in h_satisfies_eq.\n    now rewrite <-2!AddingFreshVarPreservesValToLoc in h_satisfies_eq.\nQed.\n\nDefinition EnvEq (env1 : JFITermEnv) (env2 : JFITermEnv) := \n  forall x, StrMap.find x env1 = StrMap.find x env2.\n\nDefinition EqualEnvsEquivalentInTermForHeap (t : JFITerm) CC :=\n  forall h env1 env2 this, \n    (EnvEq env1 env2) -> ((JFIHeapSatisfiesInEnv h t env1 this CC) <-> (JFIHeapSatisfiesInEnv h t env2 this CC)).\n\nDefinition EqualEnvsEquivalentInOuterTermForHeap (t : JFIOuterTerm) CC :=\n  forall h env1 env2 this, \n    (EnvEq env1 env2) -> ((JFIHeapSatisfiesOuterInEnv h t env1 this CC) <-> (JFIHeapSatisfiesOuterInEnv h t env2 this CC)).\n\nLemma EnvEqSymmetry : forall env1 env2,\n  (EnvEq env1 env2) -> (EnvEq env2 env1).\nProof.\n  intros env1 env2.\n  intros env1_eq_env2.\n  unfold EnvEq.\n  intros x.\n  symmetry.\n  apply env1_eq_env2.\nQed.\n\nLemma AddPreservesEnvEq : forall x l env1 env2,\n  (EnvEq env1 env2) -> (EnvEq (StrMap.add x l env1) (StrMap.add x l env2)).\nProof.\n  intros x l env1 env2.\n  intros env1_eq_env2.\n  intros y.\n  rewrite 2!StrMapFacts.add_o.\n  destruct (StrMapFacts.eq_dec x y); trivial.\nQed.\n\nLemma RemovePreservesEnvEq : forall x env1 env2,\n  (EnvEq env1 env2) -> (EnvEq (StrMap.remove x env1) (StrMap.remove x env2)).\nProof.\n  intros x env1 env2.\n  intros env_eq.\n  intros y.\n  rewrite 2!StrMapFacts.remove_o.\n  destruct (StrMapFacts.eq_dec x y); trivial.\nQed.\n\nLemma AddOrderChangePreservesEnvEq : forall x1 l1 x2 l2 env,\n  (x2 <> x1) ->\n  EnvEq (StrMap.add x1 l1 (StrMap.add x2 l2 env)) (StrMap.add x2 l2 (StrMap.add x1 l1 env)).\nProof.\n  intros x1 l1 x2 l2 env.\n  intros x2_neq_x1.\n  unfold EnvEq.\n  intros x.\n  destruct (Classical_Prop.classic (x1 = x)) as [x1_eq_x | x1_neq_x].\n  + rewrite StrMapFacts.add_eq_o.\n    symmetry.\n    rewrite StrMapFacts.add_neq_o.\n    rewrite StrMapFacts.add_eq_o.\n    ++ trivial.\n    ++ exact x1_eq_x.\n    ++ replace x with x1.\n       exact x2_neq_x1.\n    ++ exact x1_eq_x.\n  + destruct (Classical_Prop.classic (x2 = x)) as [x2_eq_x | x2_neq_x].\n    ++ rewrite StrMapFacts.add_neq_o.\n       rewrite StrMapFacts.add_eq_o.\n       symmetry.\n       rewrite StrMapFacts.add_eq_o.\n       +++ trivial.\n       +++ exact x2_eq_x.\n       +++ exact x2_eq_x.\n       +++ exact x1_neq_x.\n    ++ rewrite StrMapFacts.add_neq_o.\n       rewrite StrMapFacts.add_neq_o.\n       symmetry.\n       rewrite StrMapFacts.add_neq_o.\n       rewrite StrMapFacts.add_neq_o.\n       +++ trivial.\n       +++ exact x1_neq_x.\n       +++ exact x2_neq_x.\n       +++ exact x2_neq_x.\n       +++ exact x1_neq_x.\nQed.\n\nLemma EnvEqGivesValSubstEnvEq : forall env1 env2 this v,\n  (EnvEq env1 env2) ->\n  (JFIValSubstituteEnv env1 this v = JFIValSubstituteEnv env2 this v).\nProof.\n  intros env1 env2 this v.\n  intros env_eq.\n  destruct v as [ | x]; try destruct x.\n  + rewrite 2!ValEnvSubstitutionPreservesVLoc.\n    trivial.\n  + destruct (Classical_Prop.classic (StrMap.In x env1)) as [x_in_env1 | x_not_in_env1].\n    ++ apply StrMap_in_find_iff in x_in_env1 as (l & x_l_in_env1).\n       assert (x_l_in_env2 := env_eq x).\n       rewrite x_l_in_env1 in x_l_in_env2.\n       symmetry in x_l_in_env2.\n       rewrite 2!ValEnvSubstitutionReplacesVarInEnv with (l := l); trivial.\n    ++ rewrite 2!(ValEnvSubstitutionPreservesVarNotInEnv); try assumption; trivial.\n       intros x_in_env2.\n       apply StrMapFacts.not_find_mapsto_iff in x_not_in_env1 as x_is_none.\n       apply StrMap_in_find_iff in x_in_env2 as (l & x_is_l).\n       rewrite <- (env_eq x) in x_is_l.\n       rewrite x_is_none in x_is_l.\n       discriminate x_is_l.\n  + now rewrite 2!ValEnvSubstitutionSubstitutesThis.\nQed.\n\nLemma EnvEqGivesMapValSubstEq : forall env1 env2 this vs,\n  (EnvEq env1 env2) ->\n  (map (JFIValSubstituteEnv env1 this) vs = map (JFIValSubstituteEnv env2 this) vs).\nProof.\n  intros env1 env2 this vs.\n  intros env_eq.\n  induction vs; try trivial.\n  rewrite 2!List.map_cons.\n  rewrite IHvs.\n  rewrite EnvEqGivesValSubstEnvEq with (env2 := env2); trivial.\nQed.\n\nLemma EnvEqGivesExprSubstEnvEq : forall e env1 env2 this,\n  (EnvEq env1 env2) ->\n  (JFIExprSubstituteEnv env1 this e =  JFIExprSubstituteEnv env2 this e).\nProof.\n  intros e.\n  induction e; intros env1 env2 this env_eq; simpl;\n    try rewrite ?(EnvEqGivesValSubstEnvEq env1 env2);\n    try rewrite (EnvEqGivesMapValSubstEq env1 env2);\n    try assumption;\n    trivial.\n  + rewrite (IHe1 env1 env2); try assumption.\n    rewrite (IHe2 (StrMap.remove x env1) (StrMap.remove x env2)); trivial.\n    apply RemovePreservesEnvEq; try assumption.\n  + rewrite <- (IHe1 env1 env2), <- (IHe2 env1 env2); try assumption.\n    trivial.\n  + destruct vx.\n    rewrite (EnvEqGivesValSubstEnvEq env1 env2); try assumption.\n    trivial.\n  + destruct vx.\n    rewrite (EnvEqGivesValSubstEnvEq env1 env2); try assumption.\n    trivial.\n  + rewrite (IHe1 env1 env2); try assumption.\n    rewrite (IHe2 (StrMap.remove x env1) (StrMap.remove x env2)); trivial.\n    apply RemovePreservesEnvEq; try assumption.\nQed.\n\nLemma EnvEqGivesEvalEq : forall confs h e hn ex res env1 env2 this CC,\n  (EnvEq env1 env2) ->\n  (JFIEvalInEnv h e confs hn ex res env1 this CC) ->\n  (JFIEvalInEnv h e confs hn ex res env2 this CC).\nProof.\n  intros confs.\n  induction confs; intros h e hn ex res env1 env2 this CC env_eq.\n  + unfold JFIEvalInEnv, JFIEval, JFIPartialEval.\n    intros (h_eq & f_eq).\n    rewrite h_eq.\n    split; trivial.\n    rewrite <- f_eq.\n    symmetry.\n    rewrite EnvEqGivesExprSubstEnvEq with (env2 := env2); trivial.\n  + intros e_eval.\n    unfold JFIEvalInEnv, JFIEval, JFIPartialEval in *.\n    destruct a.\n    fold JFIPartialEval in *.\n    destruct e_eval as (h_eq & f_eq & red_is_some).\n    rewrite h_eq, <-f_eq in *.\n    apply EnvEqSymmetry in env_eq.\n    split; try split; try rewrite EnvEqGivesExprSubstEnvEq with (env2 := env1); try trivial.\nQed.\n\nLemma EnvEqGivesExistsImplication : forall h type x t env1 env2 this CC,\n  (EnvEq env1 env2) ->\n  (EqualEnvsEquivalentInOuterTermForHeap t CC) ->\n  (JFIHeapSatisfiesOuterInEnv h (JFIExists type x t) env1 this CC) ->\n   JFIHeapSatisfiesOuterInEnv h (JFIExists type x t) env2 this CC.\nProof.\n  intros h type x t env1 env2 this CC.\n  intros env1_eq_env2 t_equivalence h_satisfies_exists_t.\n  simpl.\n  simpl in h_satisfies_exists_t.\n  destruct h_satisfies_exists_t as ( loc & (loc_of_type & h_satisfies_t)).\n  unfold EqualEnvsEquivalentInTermForHeap in t_equivalence.\n  exists loc.\n  split.\n  + exact loc_of_type.\n  + apply (t_equivalence h (StrMap.add x loc env1) (StrMap.add x loc env2)).\n    ++ apply AddPreservesEnvEq.\n       exact env1_eq_env2.\n    ++ exact h_satisfies_t.\nQed.\n\nLemma EnvEqGivesHoareImplication : forall h t1 e ex v t2 env1 env2 this CC,\n  (EnvEq env1 env2) ->\n  (EqualEnvsEquivalentInTermForHeap t1 CC) ->\n  (EqualEnvsEquivalentInTermForHeap t2 CC) ->\n  (JFIHeapSatisfiesInEnv h (JFIHoare t1 e ex v t2) env1 this CC) ->\n   JFIHeapSatisfiesInEnv h (JFIHoare t1 e ex v t2) env2 this CC.\nProof.\n  intros h t1 e ex v t2 env1 env2 this CC.\n  intros env_eq t1_equivalence t2_equivalence.\n  simpl.\n  intros h_satisfies_hoare h_satisfies_t1.\n  assert (h_satisfies_t1_in_env1 := proj2 (t1_equivalence h env1 env2 this env_eq) h_satisfies_t1).\n  destruct (h_satisfies_hoare h_satisfies_t1_in_env1) as\n    (confs & hn & res_ex & res & eval & ex_eq & hn_satisfies_t2).\n  exists confs, hn, res_ex, res.\n  split; try split; try easy.\n  + now apply EnvEqGivesEvalEq with (env1 := env1).\n  + apply (t2_equivalence hn (StrMap.add v res env1) (StrMap.add v res env2)); try assumption.\n    now apply AddPreservesEnvEq.\nQed.\n\nLemma EnvEqGivesEqualValToLoc : forall val env1 env2 this,\n  (EnvEq env1 env2) ->\n  (JFIValToLoc val env1 this) = (JFIValToLoc val env2 this).\nProof.\n  unfold JFIValToLoc.\n  now destruct val.\nQed.\n\nLemma EnvEqGivesEqImplication : forall h env1 env2 this val1 val2 CC,\n  (EnvEq env1 env2) ->\n  (JFIHeapSatisfiesInEnv h (JFIEq val1 val2) env1 this CC) ->\n   JFIHeapSatisfiesInEnv h (JFIEq val1 val2) env2 this CC.\nProof.\n  intros h env1 env2 this val1 val2 CC.\n  intros env_eq.\n  apply EnvEqSymmetry in env_eq.\n  simpl.\n  now rewrite EnvEqGivesEqualValToLoc with (val := val1) (env2 := env2),\n              EnvEqGivesEqualValToLoc with (val := val2) (env2 := env2).\nQed.\n\nLemma EnvEqGivesFieldEqImplication : forall h env1 env2 this obj field val CC,\n  (EnvEq env1 env2) ->\n  (JFIHeapSatisfiesInEnv h (JFIFieldEq obj field val) env1 this CC) ->\n   JFIHeapSatisfiesInEnv h (JFIFieldEq obj field val) env2 this CC.\nProof.\n  intros h env1 env2 this obj field val CC.\n  intros env_eq.\n  apply EnvEqSymmetry in env_eq.\n  simpl.\n  now rewrite EnvEqGivesEqualValToLoc with (val := obj) (env2 := env2),\n              EnvEqGivesEqualValToLoc with (val := val) (env2 := env2).\nQed.\n\nLemma EnvEqGivesSepImplication : forall h t1 t2 env1 env2 this CC,\n  (EnvEq env1 env2) ->\n  (EqualEnvsEquivalentInTermForHeap t1 CC) ->\n  (EqualEnvsEquivalentInTermForHeap t2 CC) ->\n  (JFIHeapSatisfiesInEnv h (JFISep t1 t2) env1 this CC) ->\n   JFIHeapSatisfiesInEnv h (JFISep t1 t2) env2 this CC.\nProof.\n  intros h t1 t2 env1 env2 this CC.\n  intros env_eq t1_equivalence t2_equivalence.\n  simpl.\n  intros (h1 & h2 & hs_consistent & disjoint_unions & h1_satisfies_t1 & h2_satisfies_t2).\n  exists h1, h2.\n  split; [ | split; [ | split]]; try easy.\n  now apply (t1_equivalence h1 env1 env2).\n  now apply (t2_equivalence h2 env1 env2).\nQed.\n\nLemma EnvEqGivesWandImplication : forall h t1 t2 env1 env2 this CC,\n  (EnvEq env1 env2) ->\n  (EqualEnvsEquivalentInTermForHeap t1 CC) ->\n  (EqualEnvsEquivalentInTermForHeap t2 CC) ->\n  (JFIHeapSatisfiesInEnv h (JFIWand t1 t2) env1 this CC) ->\n   JFIHeapSatisfiesInEnv h (JFIWand t1 t2) env2 this CC.\nProof.\n  intros h t1 t2 env1 env2 this CC.\n  intros env_eq t1_equivalence t2_equivalence.\n  simpl.\n  intros wand h' h'_consistent disjoint_h_h' h'_satisfies_t1.\n  unfold EqualEnvsEquivalentInTermForHeap in t1_equivalence.\n  apply (t1_equivalence h' env1 env2 this env_eq) in h'_satisfies_t1.\n  destruct (wand h' h'_consistent disjoint_h_h' h'_satisfies_t1) as (h_h' & union_h_h' & h_h'_satisfies_t2).\n  apply (t2_equivalence h_h' env1 env2 this env_eq) in h_h'_satisfies_t2.\n  now exists h_h'.\nQed.\n\nLemma EqualEnvsAreEquivalent : forall t CC h env1 env2 this,\n  (EnvEq env1 env2) -> HeapEnvEquivalent h h env1 env2 this this t CC.\nProof.\n  intros t CC.\n  induction t; intros h env1 env2 this env1_eq_env2; auto.\n  (* JFIHoare *)\n + split; apply EnvEqGivesHoareImplication; try assumption.\n   exact (EnvEqSymmetry env1 env2 env1_eq_env2).\n  (* JFIEq *)\n  + split; apply EnvEqGivesEqImplication; try assumption.\n    exact (EnvEqSymmetry env1 env2 env1_eq_env2).\n  (* JFIFieldEq *)\n  + split; apply EnvEqGivesFieldEqImplication; try assumption.\n    exact (EnvEqSymmetry env1 env2 env1_eq_env2).\n  (* JFISep*)\n  + split; apply EnvEqGivesSepImplication; try assumption.\n    exact (EnvEqSymmetry env1 env2 env1_eq_env2).\n  (* JFIWand *)\n  + split; apply EnvEqGivesWandImplication; try assumption.\n    exact (EnvEqSymmetry env1 env2 env1_eq_env2).\nQed.\n\nLemma EnvOrderChangePreservesHeapSatisfying : forall h t x1 l1 x2 l2 env this CC,\n  (x1 <> x2) ->\n  (JFIHeapSatisfiesInEnv h t (StrMap.add x1 l1 (StrMap.add x2 l2 env)) this CC) <->\n  (JFIHeapSatisfiesInEnv h t (StrMap.add x2 l2 (StrMap.add x1 l1 env)) this CC).\nProof.\n  intros h t x1 l1 x2 l2 env this CC.\n  intros x1_neq_x2.\n  apply EqualEnvsAreEquivalent.\n  apply AddOrderChangePreservesEnvEq.\n  apply neq_symmetry.\n  exact x1_neq_x2.\nQed.\n\nLemma FreshEnvOrderChangePreservesHeapSatisfying : forall h t x1 l1 x2 l2 env this CC,\n  (JFIVarFreshInTerm x1 t) ->\n  (JFIHeapSatisfiesInEnv h t (StrMap.add x1 l1 (StrMap.add x2 l2 env)) this CC) <->\n  (JFIHeapSatisfiesInEnv h t (StrMap.add x2 l2 (StrMap.add x1 l1 env)) this CC).\nProof.\nAdmitted.\n\nDefinition FreshVarPreservesTermSatysfying t CC :=\nforall h x l env this,\n        JFIVarFreshInTerm x t ->\n        JFIHeapSatisfiesInEnv h t env this CC <->\n        JFIHeapSatisfiesInEnv h t (StrMap.add x l env) this CC.\n\nLemma FreshVarPreservesEval : forall h e confs hn ex res x l env this CC,\n  JFIVarFreshInExpr x e ->\n  JFIEvalInEnv h e confs hn ex res env this CC <->\n  JFIEvalInEnv h e confs hn ex res (StrMap.add x l env) this CC.\nProof.\nAdmitted.\n\nLemma FreshVarPreservesHoareSatystying : forall t1 e ex v t2 CC,\n  FreshVarPreservesTermSatysfying t1 CC ->\n  FreshVarPreservesTermSatysfying t2 CC ->\n  FreshVarPreservesTermSatysfying (JFIHoare t1 e ex v t2) CC.\nProof.\n  intros t1 e ex v t2 CC.\n  intros IH_t1 IH_t2.\n  unfold FreshVarPreservesTermSatysfying.\n  intros h x l env this x_fresh_in_hoare.\n  simpl in x_fresh_in_hoare.\n  destruct (String.eqb v x); destruct x_fresh_in_hoare.\n  destruct H0 as (x_fresh_in_t2 & x_fresh_in_e).\n  assert (t1_preserves := IH_t1 h x l env this H).\n  simpl.\n  split.\n  + intros h_satisfies_hoare_in_env.\n    intros h_satisfies_t1.\n    apply t1_preserves in h_satisfies_t1.\n    destruct (h_satisfies_hoare_in_env h_satisfies_t1)\n      as (confs & hn & res_ex & res & eval & ex_eq & hn_satisfies_t2).\n    exists confs, hn, res_ex, res.\n    assert (t2_preserves := IH_t2 hn x l (StrMap.add v res env) this x_fresh_in_t2).\n    split; try split; try easy.\n    ++ now apply FreshVarPreservesEval.\n    ++ apply FreshEnvOrderChangePreservesHeapSatisfying with (x1 := x); try assumption.\n       now apply t2_preserves.\n  + intros h_satisfies_hoare_in_env.\n    intros h_satisfies_t1.\n    apply t1_preserves in h_satisfies_t1.\n    destruct (h_satisfies_hoare_in_env h_satisfies_t1)\n      as (confs & hn & res_ex & res & eval & ex_eq & hn_satisfies_t2).\n    exists confs, hn, res_ex, res.\n    assert (t2_preserves := IH_t2 hn x l (StrMap.add v res env) this x_fresh_in_t2).\n    split; try split; try easy.\n    ++ now apply FreshVarPreservesEval in eval.\n    ++ apply t2_preserves.\n       now apply FreshEnvOrderChangePreservesHeapSatisfying.\nQed.\n\nLemma FreshVarPreservesSepSatystying : forall t1 t2 CC,\n  FreshVarPreservesTermSatysfying t1 CC ->\n  FreshVarPreservesTermSatysfying t2 CC ->\n  FreshVarPreservesTermSatysfying (JFISep t1 t2) CC.\nProof.\n  intros t1 t2 CC.\n  intros t1_preserves t2_preserves.\n  unfold FreshVarPreservesTermSatysfying.\n  intros h x l env this (x_fresh_in_t1 & x_fresh_in_t2).\n  split.\n  + simpl.\n    intros (h1 & h2 & hs_consistent & disjoint_union & h1_satisfies_t1 & h2_satisfies_t2).\n    assert (h1_satisfies_t1_in_env_x := proj1 (t1_preserves h1 x l env this x_fresh_in_t1) h1_satisfies_t1).\n    assert (h2_satisfies_t2_in_env_x := proj1 (t2_preserves h2 x l env this x_fresh_in_t2) h2_satisfies_t2).\n    now exists h1, h2.\n  + simpl.\n    intros (h1 & h2 & hs_consistent & disjoint_union & h1_satisfies_t1 & h2_satisfies_t2).\n    assert (h1_satisfies_t1_in_env := proj2 (t1_preserves h1 x l env this x_fresh_in_t1) h1_satisfies_t1).\n    assert (h2_satisfies_t2_in_env := proj2 (t2_preserves h2 x l env this x_fresh_in_t2) h2_satisfies_t2).\n    now exists h1, h2.\nQed.\n\nLemma FreshVarPreservesWandSatystying : forall t1 t2 CC,\n  FreshVarPreservesTermSatysfying t1 CC ->\n  FreshVarPreservesTermSatysfying t2 CC ->\n  FreshVarPreservesTermSatysfying (JFIWand t1 t2) CC.\nProof.\n  intros t1 t2 CC.\n  intros t1_preserves t2_preserves.\n  unfold FreshVarPreservesTermSatysfying.\n  intros h x l env this (x_fresh_in_t1 & x_fresh_in_t2).\n  split.\n  + intros h_satisfies_wand h' h'_consistent h_h'_disjoint h'_satisfies_t1.\n    apply t1_preserves in h'_satisfies_t1; try assumption.\n    destruct (h_satisfies_wand h' h'_consistent h_h'_disjoint h'_satisfies_t1) as (h_h' & h_h'_union & h_h'_satisfies_t2).\n    exists h_h'.\n    unfold FreshVarPreservesTermSatysfying in t2_preserves.\n    now apply t2_preserves with (x := x) (l := l) in h_h'_satisfies_t2; try assumption.\n  + intros h_satisfies_wand h' h'_consistent h_h'_disjoint h'_satisfies_t1.\n    apply t1_preserves with (x := x) (l := l) in h'_satisfies_t1; try assumption.\n    destruct (h_satisfies_wand h' h'_consistent h_h'_disjoint h'_satisfies_t1) as (h_h' & h_h'_union & h_h'_satisfies_t2).\n    exists h_h'.\n    unfold FreshVarPreservesTermSatysfying in t2_preserves.\n    now apply t2_preserves with (x := x) (l := l) in h_h'_satisfies_t2; try assumption.\nQed.\n\nLemma AddingFreshVarPreservesHeapSatisfying : forall q CC h x l env this,\n  JFIVarFreshInTerm x q ->\n  HeapEnvEquivalent h h env (StrMap.add x l env) this this q CC.\nProof.\n  intros t CC.\n  induction t; intros h x l env this x_fresh; try destruct x_fresh; auto.\n  (* JFIHoare *)\n  + apply FreshVarPreservesHoareSatystying; assumption.\n  (* JFIEq *)\n  + split;\n    now apply AddingFreshVarPreservesHeapSatisfyingEq with (x := x) (l := l).\n  (* JFIFieldEq *)\n  + split;\n    apply AddingFreshVarPreservesHeapSatisfyingFieldEq with (x := x) (l := l);\n    exact (conj H H0).\n  (* JFISep*)\n  + now apply FreshVarPreservesSepSatystying.\n  (* JFIWand *)\n  + now apply FreshVarPreservesWandSatystying.\nQed.\n\nLemma AddingFreshVarPreservesHeapSatisfyingOuter : forall q CC h x l env this,\n  JFIVarFreshInOuterTerm x q ->\n  HeapEnvEquivalentOuter h h env (StrMap.add x l env) this this q CC.\nProof.\nAdmitted.\n\nLemma HeapSatisfiesSubstIffVarMovedToEnv : forall h x v l p env this CC,\n  (StrMap.find v env = Some l) ->\n  (JFIHeapSatisfiesOuterInEnv h (JFIOuterTermSubstituteVal x (JFIVar v) p) env this CC <->\n   JFIHeapSatisfiesOuterInEnv h p (StrMap.add x l env) this CC).\nProof.\nAdmitted.\n\nLemma HeapSatisfiesSubstIffThisMovedToEnv : forall h p x env this CC,\n  JFIHeapSatisfiesOuterInEnv h (JFIOuterTermSubstituteVal x JFIThis p) env this CC <->\n  JFIHeapSatisfiesOuterInEnv h p (StrMap.add x (JFLoc this) env) this CC.\nProof.\nAdmitted.\n\n(* =============== Equality Lemmas =============== *)\n\nLemma EqSymmetry : forall h v1 v2 env this CC,\n  (JFIHeapSatisfiesInEnv h (JFIEq v1 v2) env this CC) -> \n   JFIHeapSatisfiesInEnv h (JFIEq v2 v1) env this CC.\nProof.\n  intros h v1 v2 env this CC.\n  intros v1_eq_v2.\n  unfold JFIHeapSatisfiesInEnv.\n  unfold JFIHeapSatisfiesInEnv in v1_eq_v2.\n  now destruct (JFIValToLoc v1 env), (JFIValToLoc v2 env).\nQed.\n\n(* =============== Soundness of basic logical rules =============== *)\n\nLemma AsmRuleSoundness : forall gamma p CC,\n  JFISemanticallyImplies gamma p p CC.\nProof.\n  intros gamma p CC.\n  intros env this h gamma_match_env h_satisfies_p.\n  exact h_satisfies_p.\nQed.\n\nLemma TransRuleSoundness : forall gamma p q r CC,\n  (JFISemanticallyImplies gamma p q CC) ->\n  (JFISemanticallyImplies gamma q r CC) ->\n   JFISemanticallyImplies gamma p r CC.\nProof.\n  intros gamma p q r CC.\n  intros p_implies_q.\n  intros q_implies_r.\n  intros env this h gamma_match_env h_satisfies_p.\nunfold JFISemanticallyImplies in p_implies_q.\n  apply (q_implies_r env this h gamma_match_env).\n  apply (p_implies_q env this h gamma_match_env).\n  exact h_satisfies_p.\nQed.\n\nLemma ValIsLoc : forall v h gamma env this,\n  FreeVarsInValAreInGamma v gamma ->\n  JFIGammaMatchEnv h gamma env ->\n  exists l, JFIValToLoc v env this = Some l.\nProof.\n  intros v h gamma env this.\n  intros free_in_v gamma_match_env.\n  destruct v.\n  + now exists null.\n  + now exists (JFLoc this).\n  + unfold FreeVarsInValAreInGamma in free_in_v.\n    assert (var_in_gamma := free_in_v var).\n    apply (gamma_match_env var) in var_in_gamma as var_in_env; try easy.\n    apply StrMapFacts.elements_in_iff in var_in_env as (l & var_l); try easy.\n    exists l.\n    now apply StrMapFacts.elements_mapsto_iff, StrMapFacts.find_mapsto_iff in var_l.\nQed.\n\nLemma EqReflRuleSoundness : forall gamma p v CC,\n  FreeVarsInValAreInGamma v gamma ->\n  JFISemanticallyImplies gamma p (JFIEq v v) CC.\nProof.\n  intros gamma p v CC.\n  intros free_vars_in_v env this h gamma_match_env h_satisfies_p.\n  unfold JFIHeapSatisfiesInEnv.\n  destruct (ValIsLoc v h gamma env this) as (l & v_is_l); try easy.\n  now rewrite v_is_l.\nQed.\n\nLemma EqSymRuleSoundness : forall gamma p v1 v2 CC,\n  JFISemanticallyImplies gamma p (JFIEq v1 v2) CC ->\n  JFISemanticallyImplies gamma p (JFIEq v2 v1) CC.\nProof.\n  intros gamma p v1 v2 CC.\n  intros v1_eq_v2.\n  intros env this h gamma_match_env h_satisfies_p.\n  apply EqSymmetry.\n  now apply (v1_eq_v2 env this h).\nQed.\n\nLemma FalseElimRuleSoundness : forall gamma p q CC,\n  (JFISemanticallyImplies gamma p JFIFalse CC) ->\n   JFISemanticallyImplies gamma p q CC.\nProof.\n  intros gamma p q CC.\n  intros p_implies_false.\n  intros env this h gamma_match_env h_satisfies_p.\n  set (h_satisfies_false := p_implies_false env this h gamma_match_env h_satisfies_p).\n  simpl in h_satisfies_false.\n  destruct h_satisfies_false.\nQed.\n\nLemma TrueIntroRuleSoundness : forall gamma p CC,\n  JFISemanticallyImplies gamma p JFITrue CC.\nProof.\n  intros gamma p CC.\n  intros env this h gamma_match_env h_satisfies_p.\n  unfold JFIHeapSatisfiesInEnv.\n  trivial.\nQed.\n\nLemma AndIntroRuleSoundness : forall gamma p q r CC,\n  (JFISemanticallyImplies gamma r p CC) ->\n  (JFISemanticallyImplies gamma r q CC) ->\n   JFISemanticallyImplies gamma r (JFIAnd p q) CC.\nProof.\n  intros gamma p q r CC.\n  intros r_implies_p r_implies_q.\n  intros env this h gamma_match_env h_satisfies_r.\n  simpl.\n  split.\n  now apply r_implies_p.\n  now apply r_implies_q.\nQed.\n\nLemma AndElimRuleSoundness : forall gamma p q r CC,\n  (JFISemanticallyImplies gamma r (JFIAnd p q) CC) ->\n   JFISemanticallyImplies gamma r p CC /\\ JFISemanticallyImplies gamma r q CC.\nProof.\n  intros gamma p q r CC.\n  intros r_implies_p_and_q.\n  split;\n  intros env this h gamma_match_env h_satisfies_r;\n  now apply r_implies_p_and_q.\nQed.\n\nLemma OrIntroRuleSoundness : forall gamma p q r CC,\n  (JFISemanticallyImplies gamma r p CC \\/ JFISemanticallyImplies gamma r q CC) ->\n   JFISemanticallyImplies gamma r (JFIOr p q) CC.\nProof.\n  intros gamma p q r CC.\n  intros [r_implies_p | r_implies_q]; intros env this h gamma_match_env h_satisfies_r; simpl.\n  now apply or_introl, r_implies_p.\n  now apply or_intror, r_implies_q.\nQed.\n\nLemma OrElimRuleSoundness : forall gamma p q r s CC,\n  (JFISemanticallyImplies gamma s (JFIOr p q) CC) ->\n  (JFISemanticallyImplies gamma (JFIAnd s p) r CC) ->\n  (JFISemanticallyImplies gamma (JFIAnd s q) r CC) ->\n   JFISemanticallyImplies gamma s r CC.\nProof.\n  intros gamma p q r s CC.\n  intros s_implies_p_or_q s_and_p_implies_r s_and_q_implies_r.\n  intros env this h gamma_match_env h_satisfies_s.\n  set (p_or_q := s_implies_p_or_q env this h gamma_match_env h_satisfies_s).\n  destruct p_or_q as [h_satisfies_p | h_satisfies_q].\n  + now apply (s_and_p_implies_r env this h gamma_match_env).\n  + now apply (s_and_q_implies_r env this h gamma_match_env).\nQed.\n\nLemma ImpliesIntroRuleSoundness : forall gamma p q r CC,\n  (JFISemanticallyImplies gamma (JFIAnd r p) q CC) ->\n   JFISemanticallyImplies gamma r (JFIImplies p q) CC.\nProof.\n  intros gamma p q r CC.\n  intros r_and_p_implies_q.\n  intros env this h gamma_match_env h_satisfies_r.\n  simpl.\n  simpl in r_and_p_implies_q.\n  apply Classical_Prop.imply_to_or.\n  intros h_satisfies_p.\n  now apply r_and_p_implies_q.\nQed.\n\nLemma ImpliesElimRuleSoundness : forall gamma p q r CC,\n  (JFISemanticallyImplies gamma r (JFIImplies p q) CC) ->\n  (JFISemanticallyImplies gamma r p CC) ->\n   JFISemanticallyImplies gamma r q CC.\nProof.\n  intros gamma p q r CC.\n  intros r_implies_p_implies_q r_implies_p.\n  intros env this h gamma_match_env h_satisfies_r.\n  apply (Classical_Prop.or_to_imply (JFIHeapSatisfiesInEnv h p env this CC)).\n  now apply r_implies_p_implies_q.\n  now apply r_implies_p.\nQed.\n\n(* =============h gamma_match_env===============*)\n\nLemma EqualHeapsAreEquivalent : forall t CC h1 h2 env this,\n  (HeapEq h1 h2) ->\n    ((JFIHeapSatisfiesInEnv h1 t env this CC) <-> (JFIHeapSatisfiesInEnv h2 t env this CC)).\nProof.\nAdmitted.\n\nLemma InSuperheap : forall h1 h2 l,\n  JFISubheap h1 h2 -> Heap.In l h1 -> Heap.In l h2.\nProof.\n  intros h1 h2 l.\n  intros subheap_h1_h2 l_in_h1.\n  unfold JFISubheap in subheap_h1_h2.\n  apply HeapFacts.elements_in_iff in l_in_h1.\n  apply HeapFacts.elements_in_iff.\n  destruct l_in_h1 as (o & l_o_h1).\n  exists o.\n  apply HeapFacts.elements_mapsto_iff in l_o_h1.\n  apply HeapFacts.elements_mapsto_iff.\n  apply (subheap_h1_h2 l o l_o_h1).\nQed.\n\nLemma SubheapTransitive : forall h1 h2 h3,\n  (JFISubheap h1 h2) -> (JFISubheap h2 h3) -> (JFISubheap h1 h3).\nProof.\n  intros h1 h2 h3.\n  intros subheap_h1_h2 subheap_h2_h3.\n  intros l o l_o_h1.\n  apply (subheap_h2_h3 l o).\n  now apply (subheap_h1_h2 l o).\nQed.\n\nLemma UnionSubheap : forall h1 h2 h12 h,\n  (JFIHeapsUnion h1 h2 h12) ->\n  (JFISubheap h12 h) <-> (JFISubheap h1 h /\\ JFISubheap h2 h).\nProof.\n  intros h1 h2 h12 h.\n  intros (subheap_h1_h12 & subheap_h2_h12 & union_h1_h2).\n  split.\n    intros subheap_h12_h.\n    split.\n  + intros l o l_o_h1.\n    apply (subheap_h12_h l o).\n    now apply (subheap_h1_h12 l o).\n  + intros l o l_o_h2.\n    apply (subheap_h12_h l o).\n    now apply (subheap_h2_h12 l o).\n  + intros (subheap_h1_h & subheap_h2_h).\n    intros l o l_o_h12.\n    apply HeapFacts.elements_mapsto_iff in l_o_h12.\n    assert (l_in_h12 : exists o, InA (Heap.eq_key_elt (elt:=Obj)) \n            (l, o) (Heap.elements (elt:=Obj) h12)).\n      now exists o.\n    apply HeapFacts.elements_in_iff in l_in_h12.\n    destruct (union_h1_h2 l l_in_h12).\n    ++ apply (subheap_h1_h l o).\n\n       apply HeapFacts.elements_in_iff in H.\n       destruct H as (o' & l_o'_h1).\n       apply HeapFacts.elements_mapsto_iff in l_o'_h1.\n       apply HeapFacts.elements_mapsto_iff in l_o_h12.\n       assert (l_o'_h12 := l_o'_h1).\n       apply subheap_h1_h12 in l_o'_h12.\n       apply HeapFacts.find_mapsto_iff in l_o_h12.\n       apply HeapFacts.find_mapsto_iff in l_o'_h12.\n       rewrite l_o'_h12 in l_o_h12.\n       injection l_o_h12 as o_eq_o'.\n       now rewrite o_eq_o' in *.\n    ++ apply (subheap_h2_h l o).\n\n       apply HeapFacts.elements_in_iff in H.\n       destruct H as (o' & l_o'_h2).\n       apply HeapFacts.elements_mapsto_iff in l_o'_h2.\n       apply HeapFacts.elements_mapsto_iff in l_o_h12.\n       assert (l_o'_h12 := l_o'_h2).\n       apply subheap_h2_h12 in l_o'_h12.\n       apply HeapFacts.find_mapsto_iff in l_o_h12.\n       apply HeapFacts.find_mapsto_iff in l_o'_h12.\n       rewrite l_o'_h12 in l_o_h12.\n       injection l_o_h12 as o_eq_o'.\n       now rewrite o_eq_o' in *.\nQed.\n\nLemma UnionSymmetry : forall h1 h2 h,\n  JFIHeapsUnion h1 h2 h <-> JFIHeapsUnion h2 h1 h.\nProof.\n  assert (one_way : forall h1 h2 h, JFIHeapsUnion h1 h2 h -> JFIHeapsUnion h2 h1 h).\n  + intros h1 h2 h (subheap_h1_h & subheap_h2_h & union_h1_h2).\n    split; try split; try assumption.\n    intros l l_in_h.\n    destruct (union_h1_h2 l l_in_h).\n    ++ now apply or_intror.\n    ++ now apply or_introl.\n  + intros h1 h2 h.\n    split; apply one_way.\nQed.\n\nLemma UnionAssoc : forall h1 h2 h3 h12 h23 h,\n  (JFIHeapsUnion h1 h2 h12 /\\ JFIHeapsUnion h2 h3 h23) ->\n  (JFIHeapsUnion h1 h23 h) <-> (JFIHeapsUnion h12 h3 h).\nProof.\n  intros h1 h2 h3 h12 h23 h.\n  intros (union_h1_h2, union_h2_h3).\n  split.\n  + intros union_h1_h23.\n    unfold JFIHeapsUnion in *.\n    destruct union_h1_h2, union_h2_h3, union_h1_h23.\n    destruct H0, H2, H4.\n    split; try split.\n    ++ apply (UnionSubheap h1 h2 h12 h).\n       now unfold JFIHeapsUnion.\n       split; try assumption.\n       now apply (SubheapTransitive h2 h23 h).\n    ++ apply (UnionSubheap h2 h3 h23 h); try assumption.\n       now unfold JFIHeapsUnion.\n    ++ intros l l_in_h.\n       destruct (H7 l l_in_h) as [l_in_h1 | l_in_h23].\n       +++ apply or_introl.\n           now apply (InSuperheap h1 h12 l).\n       +++ destruct (H6 l l_in_h23) as [l_in_h2 | l_in_h3].\n           - apply or_introl.\n             now apply (InSuperheap h2 h12 l).\n           - now apply or_intror.\n  + intros union_h12_h3.\n    unfold JFIHeapsUnion in *.\n    destruct union_h1_h2, union_h2_h3, union_h12_h3.\n    destruct H0, H2, H4.\n    split; try split.\n    ++ now apply (UnionSubheap h1 h2 h12 h).\n    ++ apply (UnionSubheap h2 h3 h23 h); try assumption.\n       now unfold JFIHeapsUnion.\n       split; try assumption.\n       now apply (SubheapTransitive h2 h12 h).\n    ++ intros l l_in_h.\n       destruct (H7 l l_in_h) as [l_in_h12 | l_in_h3].\n       +++ destruct (H5 l l_in_h12) as [l_in_h1 | l_in_h2].\n           - now apply or_introl.\n           - apply or_intror.\n             now apply (InSuperheap h2 h23 l).\n       +++ apply or_intror.\n           now apply (InSuperheap h3 h23 l).\nQed.\n\nLemma UnionDisjoint : forall h1 h2 h12 h,\n  JFIHeapsUnion h1 h2 h12 ->\n  JFIHeapsDisjoint h1 h ->\n  JFIHeapsDisjoint h2 h ->\n  JFIHeapsDisjoint h12 h.\nProof.\n  intros h1 h2 h12 h.\n  intros (_ & _ & union) disj_h1_h disj_h2_h.\n  intros l.\n  intros (l_in_h12 & l_in_h).\n  destruct (union l); try assumption.\n  + now apply (disj_h1_h l).\n  + now apply (disj_h2_h l).\nQed.\n\nLemma UnionUnique : forall h1 h2 h h',\n  JFIHeapsUnion h1 h2 h ->\n  JFIHeapsUnion h1 h2 h' ->\n  HeapEq h h'.\nProof.\n  intros h1 h2 h h'.\n  intros (subheap_h1_h & subheap_h2_h & union_h) (subheap_h1_h' & subheap_h2_h' & union_h').\n  intros l.\n  destruct (Classical_Prop.classic (Heap.In l h)) as [l_in_h | not_l_in_h].\n  + destruct (union_h l l_in_h).\n    ++ apply HeapFacts.elements_in_iff in H.\n       destruct H as (o & l_o_h1).\n       apply HeapFacts.elements_mapsto_iff in l_o_h1.\n       assert (l_o_h := l_o_h1).\n       apply subheap_h1_h' in l_o_h1.\n       apply subheap_h1_h in l_o_h.\n       apply HeapFacts.find_mapsto_iff in l_o_h1.\n       apply HeapFacts.find_mapsto_iff in l_o_h.\n       rewrite l_o_h1, l_o_h.\n       trivial.\n    ++ apply HeapFacts.elements_in_iff in H.\n       destruct H as (o & l_o_h2).\n       apply HeapFacts.elements_mapsto_iff in l_o_h2.\n       assert (l_o_h := l_o_h2).\n       apply subheap_h2_h' in l_o_h2.\n       apply subheap_h2_h in l_o_h.\n       apply HeapFacts.find_mapsto_iff in l_o_h2.\n       apply HeapFacts.find_mapsto_iff in l_o_h.\n       rewrite l_o_h2, l_o_h.\n       trivial.\n  + apply HeapFacts.not_find_mapsto_iff in not_l_in_h.\n    rewrite not_l_in_h.\n    symmetry.\n    apply HeapFacts.not_find_mapsto_iff.\n    intros l_in_h'.\n    apply HeapFacts.not_find_mapsto_iff in not_l_in_h.\n    apply not_l_in_h.\n    destruct (union_h' l l_in_h').\n    ++ apply HeapFacts.elements_in_iff.\n       apply HeapFacts.elements_in_iff in H.\n       destruct H as (o & l_o_h1).\n       exists o.\n       apply HeapFacts.elements_mapsto_iff.\n       apply HeapFacts.elements_mapsto_iff in l_o_h1.\n       now apply (subheap_h1_h l).\n    ++ apply HeapFacts.elements_in_iff.\n       apply HeapFacts.elements_in_iff in H.\n       destruct H as (o & l_o_h2).\n       exists o.\n       apply HeapFacts.elements_mapsto_iff.\n       apply HeapFacts.elements_mapsto_iff in l_o_h2.\n       now apply (subheap_h2_h l).\nQed.\n\nLemma SubheapDisjoint : forall h1 h2 h12 h,\n  JFIHeapsUnion h1 h2 h12 ->\n  JFIHeapsDisjoint h12 h ->\n  JFIHeapsDisjoint h1 h.\nProof.\n  intros h1 h2 h12 h.\n  intros (subheap_h1_h12 & _ & _) disj_h12_h.\n  intros l (l_in_h1 & l_in_h).\n  apply (disj_h12_h l).\n  split; try assumption.\n  apply HeapFacts.elements_in_iff.\n  apply HeapFacts.elements_in_iff in l_in_h1.\n  destruct l_in_h1 as (o & l_o_h1).\n  exists o.\n  apply HeapFacts.elements_mapsto_iff.\n  apply HeapFacts.elements_mapsto_iff in l_o_h1.\n  now apply (subheap_h1_h12 l).\nQed.\n\nLemma DisjointSymmetry : forall h1 h2,\n  JFIHeapsDisjoint h1 h2 <-> JFIHeapsDisjoint h2 h1.\nProof.\n  assert (one_way : forall h1 h2, JFIHeapsDisjoint h1 h2 -> JFIHeapsDisjoint h2 h1).\n  + intros h1 h2 disj.\n    intros l (l_in_h2 & l_in_h1).\n    now apply (disj l).\n  + intros h1 h2.\n    split; apply one_way.\nQed.\n\nDefinition EnvRestrictedToHeap (env : JFITermEnv) (h' : Heap)  (env' : JFITermEnv):=\n  (forall x, StrMap.In x env <-> StrMap.In x env') /\\\n  (forall x l, StrMap.MapsTo x (JFLoc l) env' -> Heap.In l h') /\\\n  (forall x l, StrMap.MapsTo x (JFLoc l) env' -> StrMap.MapsTo x (JFLoc l) env).\n\nDefinition RestrictEnv (env : JFITermEnv) (h' : Heap) :=\n  StrMap.map (fun l =>\n    match l with\n    | null => null\n    | JFLoc n => if Heap.mem n h' then l else null\n    end\n  ) env.\n\nLemma ExistsRestrictedEnv : forall env h', exists env', EnvRestrictedToHeap env h' env'.\nProof.\n  intros env h'.\n  exists (RestrictEnv env h').\n  unfold EnvRestrictedToHeap, RestrictEnv.\n  split; [ | split].\n  + intros x.\n    split;\n    apply StrMapFacts.map_in_iff with (x := x) (m := env).\n  + intros x n.\n    intros x_mapsto_n.\n    apply StrMapFacts.map_mapsto_iff in x_mapsto_n.\n    destruct x_mapsto_n as (l & match_is_loc & x_mapsto_l).\n    apply HeapFacts.mem_in_iff.\n    destruct l; try discriminate match_is_loc.\n    assert (n_eq_n0 : n = n0).\n    ++ destruct (Heap.mem (elt:=Obj) n0 h'); try discriminate match_is_loc.\n       now injection match_is_loc as n_eq_n0.\n    ++ rewrite <-n_eq_n0 in *.\n       now destruct (Heap.mem (elt:=Obj) n h'); try discriminate match_is_loc.\n  + intros x n x_n_env'.\n    apply StrMapFacts.map_mapsto_iff in x_n_env'.\n    destruct x_n_env' as (l & match_is_loc & x_mapsto_l).\n    destruct l; try discriminate match_is_loc.\n    destruct (Heap.mem n0 h'); try discriminate match_is_loc.\n    injection match_is_loc as n_eq_n0.\n    now rewrite n_eq_n0.\nQed.\n\nLemma RestrictedEnvMatchesGamma : forall gamma env h env' h',\n  JFIGammaMatchEnv h gamma env ->\n  JFISubheap h' h ->\n  EnvRestrictedToHeap env h' env' ->\n  JFIGammaMatchEnv h' gamma env'.\nProof.\n  intros gamma env h env' h'.\n  intros gamma_match_env subheap_h'_h env'_restricted.\n  intros x.\n  split; try split.\n  + intros x_in_gamma.\n    apply env'_restricted.\n    now apply gamma_match_env.\n  + intros x_in_env'.\n    apply env'_restricted in x_in_env'.\n    now apply gamma_match_env.\n  + intros loc type.\n    intros t_type_gamma x_loc_env'.\n    destruct env'_restricted as (same_vars & env'_match_h' & env'_subenv).\n    destruct loc; try easy.\n    assert (n_of_type := proj2 (gamma_match_env x) (JFLoc n) type t_type_gamma (env'_subenv x n x_loc_env')).\n    apply env'_match_h' in x_loc_env'.\n    simpl.\n    simpl in n_of_type.\n    apply HeapFacts.elements_in_iff in x_loc_env'.\n    destruct x_loc_env' as (o & l_o_h').\n    apply HeapFacts.elements_mapsto_iff in l_o_h'.\n    assert (l_o_h := l_o_h').\n    apply subheap_h'_h in l_o_h.\n    apply HeapFacts.find_mapsto_iff in l_o_h'.\n    apply HeapFacts.find_mapsto_iff in l_o_h.\n    rewrite l_o_h'.\n    now rewrite l_o_h in n_of_type.\nQed.\n\nLemma AddingNullPreservesRestrictedEnv : forall env h env' name,\n  EnvRestrictedToHeap env h env' ->\n  EnvRestrictedToHeap (StrMap.add name null env) h (StrMap.add name null env').\nProof.\nAdmitted.\n\nLemma AddingHeapLocPreservesRestrictedEnv : forall env h env' name n,\n  Heap.In n h ->\n  EnvRestrictedToHeap env h env' ->\n  EnvRestrictedToHeap (StrMap.add name (JFLoc n) env) h (StrMap.add name (JFLoc n) env').\nProof.\nAdmitted.\n\nLemma LocOfTypeImpliesLocInHeap : forall n h type,\n  JFILocOfType (JFLoc n) h type -> Heap.In n h.\nProof.\nAdmitted.\n\nLemma LocOfTypeImpliesExtendedRestricted : forall name l h type env env',\n  JFILocOfType l h type ->\n  EnvRestrictedToHeap env h env' ->\n  EnvRestrictedToHeap (StrMap.add name l env) h (StrMap.add name l env').\nProof.\n  intros name l h type env env' env_restricted l_of_type.\n  destruct l.\n  now apply AddingNullPreservesRestrictedEnv.\n  apply AddingHeapLocPreservesRestrictedEnv; try assumption.\n  now apply LocOfTypeImpliesLocInHeap with (type := type).\nQed.\n\n(* TODO to jest szczególny przypadek ExtendingHeapPreservesHeapSatisfying *)\nLemma RestrictedEnvPreservesHeapSatisfying : forall p h env env' this CC,\n  EnvRestrictedToHeap env h env' ->\n  (JFIHeapSatisfiesInEnv h p env this CC <-> JFIHeapSatisfiesInEnv h p env' this CC).\nProof.\n  intros p.\n  induction p; intros h env env' this CC env_restricted.\n  + split; auto.\n  + split; auto.\n  + split.\n    ++ simpl.\n       intros (h_satisfies_p1 & h_satisfies_p2).\n        split.\n        now apply (IHp1 h env).\n        now apply (IHp2 h env).\n    ++ simpl.\n       intros (h_satisfies_p1 & h_satisfies_p2).\n        split.\n        now apply (IHp1 h env env').\n        now apply (IHp2 h env env').\n  + split; simpl.\n    ++ destruct 1.\n       apply or_introl. now apply (IHp1 h env).\n       apply or_intror. now apply (IHp2 h env).\n    ++ destruct 1.\n       apply or_introl. now apply (IHp1 h env env').\n       apply or_intror. now apply (IHp2 h env env').\n  + split; simpl.\n    ++ destruct 1.\n       apply or_introl.\n       intros h_p1_env.\n       apply H. now apply (IHp1 h env env').\n       apply or_intror.\n       now apply (IHp2 h env env').\n    ++ destruct 1.\n       apply or_introl.\n       intros h_p1_env.\n       apply H. now apply (IHp1 h env env').\n       apply or_intror.\n       now apply (IHp2 h env env'). \n  + admit.\n  + admit. (* TODO to jeszcze nie dziala, x -> l spoza h w env, x -> null w env'.\n                   Trzeba dolozyc założenie że wszystkie zmienne wolne są w h *)\n  + admit. (* TODO jw *)\n  + admit.\n  + admit.\nAdmitted.\n\nLemma EveryHeapSatisfiesPersistentTerm : forall p h h' env this CC,\n  JFITermPersistent p ->\n  (JFIHeapSatisfiesInEnv h  p env this CC <->\n   JFIHeapSatisfiesInEnv h' p env this CC).\nProof.\nAdmitted.\n\nLemma SepAssoc1Soundness : forall decls gamma p1 p2 p3,\n  JFISemanticallyImplies gamma\n    (JFISep p1 (JFISep p2 p3))\n    (JFISep (JFISep p1 p2) p3) (JFIDeclsProg decls).\nProof.\n  intros decls gamma p1 p2 p3.\n  intros env this h gamma_match_env h_satisfies_q.\n  destruct h_satisfies_q as\n         (h1 & h23 & (h1_consistent & h23_consistent) & (union_h1_h23 & disj_h1_h23) & h1_satisfies_p1 &\n          h2 & h3 & (h2_consistent & h3_consistent) & (union_h2_h3 & disj_h2_h3) & h_2_satisfies_p2 & h3_satisfies_p3).\n  simpl.\n  destruct (ExistsUnion h1 h2) as (h12, union_h1_h2).\n  + apply DisjointSymmetry.\n    apply (SubheapDisjoint h2 h3 h23 h1); try assumption.\n    now apply DisjointSymmetry.\n  + exists h12, h3.\n    split; split; [ | | split | split]; trivial.\n    ++ admit. (* TODO union of consistent heaps is consistent *)\n    ++ now apply (UnionAssoc h1 h2 h3 h12 h23).\n    ++ apply (UnionDisjoint h1 h2 h12 h3); try assumption.\n       apply DisjointSymmetry.\n       apply (SubheapDisjoint h3 h2 h23 h1); try (apply DisjointSymmetry; assumption).\n       now apply UnionSymmetry.\n    ++ exists h1, h2.\n       split; split; [ | | split | split]; trivial.\n       apply DisjointSymmetry.\n       apply (SubheapDisjoint h2 h3 h23 h1); try apply DisjointSymmetry; assumption.\nAdmitted.\nHint Resolve SepAssoc1Soundness : core.\n\nLemma SepAssoc2Soundness : forall decls gamma p1 p2 p3,\n  JFISemanticallyImplies gamma\n    (JFISep (JFISep p1 p2) p3)\n    (JFISep p1 (JFISep p2 p3)) (JFIDeclsProg decls).\nProof.\n  intros decls gamma p1 p2 p3.\n  intros env this h gamma_match_env h_satisfies_q.\n  destruct h_satisfies_q as (h12 & h3 & (h12_consistent & h3_consistent) & (union_h1_h23 & disj_h1_h23) &\n      ((h1 & h2 & (h1_consistent & h2_consistent) & (union_h1_h2 & disjoint_h1_h2) & (h1_satisfies_p1 & h2_satisfies_p2)) &\n       h3_satisfies_p3)).\n  simpl.\n  destruct (ExistsUnion h2 h3) as (h23 & h2_h3_union).\n  + apply (SubheapDisjoint h2 h1 h12 h3); try assumption.\n    now apply UnionSymmetry.\n  + exists h1, h23.\n    split; split; [ | | split | split]; trivial.\n    ++ admit. (* TODO union of consistent heaps is consistent *)\n    ++ now apply (UnionAssoc h1 h2 h3 h12 h23).\n    ++ apply DisjointSymmetry.\n        apply (UnionDisjoint h2 h3 h23 h1); try assumption.\n        +++ now apply DisjointSymmetry.\n        +++ apply DisjointSymmetry.\n            apply (SubheapDisjoint h1 h2 h12 h3); try assumption.\n    ++ exists h2, h3.\n       split; split; [ | | split | split]; trivial.\n       apply (SubheapDisjoint h2 h1 h12 h3); try apply UnionSymmetry; assumption.\nAdmitted.\nHint Resolve SepAssoc2Soundness : core.\n\nLemma SepSymRuleSoundness : forall decls gamma p1 p2,\n  JFISemanticallyImplies gamma (JFISep p1 p2) (JFISep p2 p1) (JFIDeclsProg decls).\nProof.\n  intros decls gamma p1 p2.\n  intros env this h gamma_match_env h_satisfies_sep.\n  destruct h_satisfies_sep as (h1 & h2 & (h1_consistent & h2_consistent) & (union_h2_h2 & disjoint_h1_h2) & h_satisfies_p1 & h2_satisfies_p2).\n  exists h2, h1.\n  split; split; [ | | split | split]; trivial.\n  + apply UnionSymmetry.\n    assumption.\n  + apply DisjointSymmetry.\n    assumption.\nQed.\nHint Resolve SepSymRuleSoundness : core.\n\nLemma ImplicationToRestrictedImplication : forall gamma env this h h' p q CC,\n  JFISubheap h' h ->\n  JFIGammaMatchEnv h gamma env ->\n  JFISemanticallyImplies gamma p q CC ->\n  JFIHeapSatisfiesInEnv h' p env this CC ->\n  JFIHeapSatisfiesInEnv h' q env this CC.\nProof.\n  intros gamma env this h h' p q CC.\n  intros h'_subheap gamma_match_env p_implies_q h'_satisfies_p.\n  destruct (ExistsRestrictedEnv env h') as (env1 & env1_restricted).\n  apply RestrictedEnvPreservesHeapSatisfying with (env' := env1); try easy.\n  apply p_implies_q; try easy.\n  apply RestrictedEnvMatchesGamma with (env := env) (h := h); try easy.\n  apply RestrictedEnvPreservesHeapSatisfying with (env := env); try easy.\nQed.\n\nLemma SepIntroSoundness : forall decls gamma p1 q1 p2 q2,\n  let CC := JFIDeclsProg decls in\n  JFISemanticallyImplies gamma p1 q1 CC ->\n  JFISemanticallyImplies gamma p2 q2 CC ->\n  JFISemanticallyImplies gamma (JFISep p1 p2) (JFISep q1 q2) CC.\nProof.\n  intros decls gamma p1 q1 p2 q2 CC.\n  intros p1_implies_q1 p2_implies_q2.\n  intros env this h gamma_match_env h_satisfies_sep.\n  destruct h_satisfies_sep as (h1 & h2 & hs_consistent & (union_h1_h2 & disjoint_h1_h2) & h1_satisfies_p1 & h2_satisfies_p2).\n  exists h1, h2.\n  split; [ | split; [ | split]]; try easy.\n  + apply ImplicationToRestrictedImplication with (h := h) (gamma := gamma) (p := p1); try easy.\n    now apply union_h1_h2.\n  + apply ImplicationToRestrictedImplication with (h := h) (gamma := gamma) (p := p2); try easy.\n    now apply union_h1_h2.\nQed.\nHint Resolve SepIntroSoundness : core.\n\nLemma SepIntroPersistentSoundness : forall decls gamma p q,\n  let CC := (JFIDeclsProg decls) in\n  JFITermPersistent p ->\n  JFISemanticallyImplies gamma (JFIAnd p q) (JFISep p q) CC.\nProof.\n  intros decls gamma p q CC.\n  intros p_persistent.\n  intros env this h gamma_match_env h_satisfies_and.\n  exists (Heap.empty Obj), h.\n  split; split; [ | | split | split]; try easy.\n  + admit. (* TODO empty heap is consistent *)\n  + admit. (* TODO h consistent *)\n  + apply UnionIdentity.\n  + apply JFIEmptyHeapDisjoint.\n  + apply EveryHeapSatisfiesPersistentTerm with (h := h); try assumption.\n    apply h_satisfies_and.\n  + simpl in h_satisfies_and.\n    apply h_satisfies_and.\nAdmitted.\nHint Resolve SepIntroPersistentSoundness : core.\n\nLemma WandIntroSoundness : forall decls gamma p q r,\n  let CC := JFIDeclsProg decls in\n  JFISemanticallyImplies gamma (JFISep r p) q CC ->\n  JFISemanticallyImplies gamma r (JFIWand p q) CC.\nProof.\n  intros decls gamma p q r CC.\n  intros sep_implies_q.\n  intros env this h gamma_match_env h_satisfies_r.\n  intros h' h'_consistent h_disjoint h'_satisfies_p.\n  destruct (ExistsUnion h h') as (h_h', union_h_h'); try assumption.\n  exists h_h'.\n  split; try assumption.\n  apply (sep_implies_q env this h_h').\n  + unfold JFIGammaMatchEnv.\n    intros var_name.\n    destruct (gamma_match_env var_name) as (gamma_keys_match_env & types_match).\n    split; try exact gamma_keys_match_env.\n    intros var_loc var_type var_is_type var_is_loc.\n    unfold JFILocOfType.\n    destruct var_loc; try trivial.\n    assert (var_name_type := types_match (JFLoc n) var_type var_is_type var_is_loc).\n    unfold JFILocOfType in var_name_type.\n    unfold JFIHeapsUnion, JFISubheap in union_h_h'.\n    destruct union_h_h' as (h_subheap & h'_subheap & _).\n    destruct (Classical_Prop.classic (exists o, Heap.find n h = Some o)).\n    ++ destruct H as (o & n_is_o).\n       assert (o_in_union := h_subheap n o).\n       rewrite n_is_o in var_name_type.\n       rewrite <- HeapFacts.find_mapsto_iff in n_is_o.\n       apply o_in_union in n_is_o.\n       rewrite HeapFacts.find_mapsto_iff in n_is_o.\n       rewrite n_is_o.\n       destruct o.\n       exact var_name_type.\n    ++ destruct (Heap.find n h); try destruct var_name_type.\n       exfalso.\n       apply H.\n       exists o.\n       trivial.\n  + exists h, h'.\n    split; split; [ | | split | split]; try assumption.\n    admit. (* TODO h consistent *)\nAdmitted.\nHint Resolve WandIntroSoundness : core.\n\nLemma WandElimSoundness : forall decls gamma p q r1 r2,\n  let CC := JFIDeclsProg decls in\n  JFISemanticallyImplies gamma r1 (JFIWand p q) CC ->\n  JFISemanticallyImplies gamma r2 p CC ->\n  JFISemanticallyImplies gamma (JFISep r1 r2) q CC.\nProof.\n  intros decls gamma p q r1 r2 CC.\n  intros r1_implies_wand r2_implies_p.\n  intros env this h gamma_match_env h_satisfies_r.\n\n  simpl in h_satisfies_r.\n  destruct h_satisfies_r as (h1 & h2 &  (h1_consistent & h2_consistent) & (union_h1_h2 & disjoint_h1_h2) & h1_satisfies_r1 & h2_satisfies_r2).\n\n  destruct (ExistsRestrictedEnv env h1) as (env1 & env1_restricted).\n  assert (gamma_match_env1 := RestrictedEnvMatchesGamma gamma env h env1 h1 gamma_match_env (proj1 union_h1_h2) env1_restricted).\n  apply RestrictedEnvPreservesHeapSatisfying with (env' := env1) in h1_satisfies_r1; try assumption.\n  unfold JFISemanticallyImplies in r1_implies_wand.\n  assert (h1_satisfies_wand := r1_implies_wand env1 this h1 gamma_match_env1 h1_satisfies_r1).\n  apply RestrictedEnvPreservesHeapSatisfying with (env := env) in h1_satisfies_wand; try assumption.\n\n  destruct (ExistsRestrictedEnv env h2) as (env2 & env2_restricted).\n  assert (gamma_match_env2 := RestrictedEnvMatchesGamma gamma env h env2 h2 gamma_match_env (proj1 (proj2 union_h1_h2)) env2_restricted).\n  apply RestrictedEnvPreservesHeapSatisfying with (env' := env2) in h2_satisfies_r2; try assumption.\n  assert (h2_satisfies_p := r2_implies_p env2 this h2 gamma_match_env2 h2_satisfies_r2).\n  apply RestrictedEnvPreservesHeapSatisfying with (env := env) in h2_satisfies_p; try assumption.\n\n  simpl in h1_satisfies_wand.\n  destruct (h1_satisfies_wand h2 h2_consistent disjoint_h1_h2 h2_satisfies_p) as (h' & union_h1_h2_h' & h'_satisfies_q).\n  apply EqualHeapsAreEquivalent with (h1 := h) (h2 := h'); try assumption.\n  apply UnionUnique with (h1 := h1) (h2 := h2); assumption.\nQed.\nHint Resolve WandElimSoundness : core.\n\n\n(* =============== Jafun reduction Lemmas =============== *)\nLtac Loc_dec_eq l1 l2 l1_eq_l2 :=\n  destruct Loc_dec as [_ | l1_neq_l2];\n  [ | exfalso; apply l1_neq_l2; exact l1_eq_l2].\n\nLtac Loc_dec_neq l1 l2 l1_neq_l2 :=\n  destruct Loc_dec as [l1_eq_l2 | _];\n  [exfalso; apply l1_neq_l2; exact l1_eq_l2 | ].\n\nLemma IfReductionEq : forall h l1 l2 e1 e2 Ctx Cc env this CC,\n  (l1 = l2) ->\n   red CC (h, (Ctx[[ JFIExprSubstituteEnv env this (JFIf (JFVLoc l1) (JFVLoc l2) e1 e2) ]]_ None) :: Cc) = Some (h, Ctx[[JFIExprSubstituteEnv env this e1]]_ None :: Cc).\nProof.\n  intros h l1 l2 e1 e2 Ctx Cc env this CC.\n  intros l1_eq_l2.\n  simpl.\n  rewrite ValEnvSubstitutionPreservesVLoc.\n  rewrite ValEnvSubstitutionPreservesVLoc.\n  Loc_dec_eq l1 l2 l1_eq_l2.\n  destruct Ctx.\n  trivial.\n  destruct j; trivial.\nQed.\n\nLemma IfReductionNeq : forall h l1 l2 e1 e2 Ctx Cc env this CC,\n  (l1 <> l2) ->\n   red CC (h, (Ctx[[ JFIExprSubstituteEnv env this (JFIf (JFVLoc l1) (JFVLoc l2) e1 e2) ]]_ None) :: Cc) = Some (h, Ctx[[JFIExprSubstituteEnv env this e2]]_ None :: Cc).\nProof.\n  intros h l1 l2 e1 e2 Ctx Cc env this CC.\n  intros l1_neq_l2.\n  simpl.\n  rewrite ValEnvSubstitutionPreservesVLoc.\n  rewrite ValEnvSubstitutionPreservesVLoc.\n  Loc_dec_neq l1 l2 l1_neq_l2.\n  destruct Ctx.\n  trivial.\n  destruct j; trivial.\nQed.\n\nLemma AllocSucceedsInCorrectProgram : forall prog h cn vs,\n  exists newloc newheap, alloc_init prog h cn vs = Some (newloc, newheap).\nProof.\nAdmitted.\n\nLemma SuccessfullAllocIsNotNull : forall prog h cn vs newloc newheap,\n  (alloc_init prog h cn vs = Some (newloc, newheap)) ->\n   newloc <> null.\nProof.\nAdmitted.\n\nLemma SuccessfullAllocSetsFields : forall decls h cn vs newloc newheap objflds n field l,\n  (alloc_init (JFIDeclsProg decls) h cn vs = Some (newloc, newheap)) ->\n  (flds (JFIDeclsProg decls) (JFClass cn) = Some objflds) ->\n  (nth_error objflds n = Some field) ->\n  (nth_error vs n = Some l) ->\n   JFIObjFieldEq newloc field l newheap.\nProof.\nAdmitted.\n\n(* =============== JFIEval Lemmas =============== *)\n\nLemma IfEvaluationStepEq : forall l1 l2 e1 e2 h h' st' confs hn ex res env this CC,\n  (l1 = l2) ->\n  (JFIEvalInEnv h (JFIf (JFVLoc l1) (JFVLoc l2) e1 e2) ((h', st')::confs) hn ex res env this CC) ->\n  (h = h' /\\ JFIEvalInEnv h' e1 confs hn ex res env this CC).\nProof.\n  intros l1 l2 e1 e2 h h' st' confs hn ex res env this CC.\n  intros l1_eq_l2 if_eval.\n  unfold JFIEvalInEnv, JFIEval, JFIPartialEval in if_eval.\n  rewrite IfReductionEq in if_eval.\n  + fold JFIPartialEval in if_eval.\n    destruct if_eval as (h_eq_h' & (_ & e1_eval)).\n    rewrite <- h_eq_h'.\n    unfold JFIEval. \n    apply (conj eq_refl e1_eval).\n  + exact l1_eq_l2.\nQed.\n\nLemma IfEvaluationStepNeq : forall l1 l2 e1 e2 h h' st' confs hn ex res env this CC,\n  (l1 <> l2) ->\n  (JFIEvalInEnv h (JFIf (JFVLoc l1) (JFVLoc l2) e1 e2) ((h', st')::confs) hn ex res env this CC) ->\n  (h = h' /\\ JFIEvalInEnv h' e2 confs hn ex res env this CC).\nProof.\n  intros l1 l2 e1 e2 h h' st' confs hn ex res env this CC.\n  intros l1_eq_l2 if_eval.\n  unfold JFIEvalInEnv, JFIEval, JFIPartialEval in if_eval.\n  rewrite IfReductionNeq in if_eval.\n  + fold JFIPartialEval in if_eval.\n    destruct if_eval as (h_eq_h' & (_ & e2_eval)).\n    rewrite <- h_eq_h'.\n       unfold JFIEval.\n       apply (conj eq_refl e2_eval).\n  + exact l1_eq_l2.\nQed.\n\nLemma NewEvaluationStep : forall prog h ls newloc newheap mu cn vs env this CC,\n  (alloc_init prog h cn ls = Some (newloc, newheap)) ->\n   JFIEvalInEnv h (JFNew mu cn vs) [(h, [ [] [[ JFIExprSubstituteEnv env this (JFNew mu cn vs) ]]_ None])] newheap None newloc env this CC.\nProof.\nAdmitted.\n\nLemma EvaluationPreservesGammaMatching : forall gamma env h e confs hn ex res CC,\n  (JFIGammaMatchEnv h gamma env) ->\n  (JFIEval h e confs hn ex res CC) ->\n  (JFIGammaMatchEnv hn gamma env).\nProof.\nAdmitted.\n\nLemma EvaluationPreservesPersistentTerms : forall env this s h e confs hn ex res CC,\n  (JFITermPersistent s) ->\n  (JFIHeapSatisfiesInEnv h s env this CC) ->\n  (JFIEval h e confs hn ex res CC) ->\n   JFIHeapSatisfiesInEnv hn s env this CC.\nProof.\nAdmitted.\n\n(* =============== Soundness of Hoare triple rules =============== *)\n\nLemma JFIExistsValToLoc : forall v v_expr h gamma env this,\n  v_expr = JFIValToJFVal v ->\n  FreeVarsInValAreInGamma v gamma ->\n  JFIGammaMatchEnv h gamma env ->\n  exists l, JFIValToLoc v env this = Some l /\\ JFIValSubstituteEnv env this v_expr = (JFVLoc l).\nProof.\n  intros v v_expr h gamma env this v_expr_val free_in_v gamma_match_env.\n  destruct v; simpl in v_expr_val; rewrite v_expr_val.\n  + exists null.\n    split; trivial.\n    unfold JFIExprSubstituteEnv.\n    now rewrite ValEnvSubstitutionPreservesVLoc.\n  + exists (JFLoc this).\n    split; try easy.\n    apply ValEnvSubstitutionSubstitutesThis.\n  + destruct (ValIsLoc (JFIVar var) h gamma env this free_in_v gamma_match_env) as (l & var_l_env).\n    exists l.\n    now rewrite ValEnvSubstitutionReplacesVarInEnv with (l := l).\nQed.\n\nLemma ValToLoc_neq_o : forall x u v env this,\n  x <> (JFIVar u) ->\n  JFIValToLoc x (StrMap.add u v env) this = JFIValToLoc x env this.\nProof.\n  intros.\n  destruct x; try easy.\n  simpl.\n  rewrite StrMapFacts.add_neq_o; trivial.\n  intros u_eq_var.\n  apply H.\n  now rewrite u_eq_var.\nQed.\n\nLemma EnsureValsMapIsLocsMap : forall vs env this,\n  exists ls, map (JFIValSubstituteEnv env this) vs = map JFVLoc ls.\nProof.\nAdmitted.\n\nLemma EnsureValsListIsLocsList : forall ls vs n l env this,\n  map (JFIValSubstituteEnv env this) vs = map JFVLoc ls ->\n  (nth_error ls n = Some l <-> nth_error (map (JFIValSubstituteEnv env this) vs) n = Some (JFVLoc l)).\n(*   exists ls, forall n l, nth_error ls n = Some l <-> nth_error (map (JFIValSubstituteEnv env) vs) n = Some (JFVLoc l). *)\nProof.\n  intros ls vs n l env this.\n  intros vs_is_ls.\n  split.\n  + intros nth_ls_is_l.\n    rewrite vs_is_ls.\n    apply List.map_nth_error.\n    assumption.\n  + intros nth_map.\n    rewrite vs_is_ls in nth_map.\n    set (JFVLoc_inverse := fun v =>\n            match v with\n            | JFVLoc l => l\n            | _ => null\n            end).\n    replace l with (JFVLoc_inverse (JFVLoc l)).\n    replace ls with (map JFVLoc_inverse (map JFVLoc ls)).\n    ++ apply map_nth_error.\n       exact nth_map.\n    ++ rewrite List.map_map.\n       simpl.\n       rewrite List.map_id.\n       trivial.\n    ++ trivial.\nQed.\n\nLemma EnsureLocInHeap : forall x h gamma env this (n : nat),\n  JFIValToLoc x env this = Some (JFLoc n) ->\n  JFIGammaMatchEnv h gamma env ->\n  exists (o : Obj), Heap.find n h = Some o.\nProof.\n  intros x h gamma env this n.\n  intros x_is_n gamma_match_env.\n  unfold JFIValToLoc in x_is_n.\n  destruct x; try easy.\n  + admit. (* TODO this in heap *)\n  + destruct (gamma_match_env var) as (same_keys & types_match).\n    assert (StrMap.In var gamma).\n      apply same_keys.\n      apply StrMapFacts.elements_in_iff.\n      exists (JFLoc n).\n      now apply StrMapFacts.elements_mapsto_iff, StrMapFacts.find_mapsto_iff.\n    apply StrMapFacts.elements_in_iff in H as (type & var_type).\n    apply StrMapFacts.elements_mapsto_iff in var_type.\n    apply LocOfTypeImpliesLocInHeap with (n := n) (type := type) in types_match; try easy.\n    ++ apply HeapFacts.elements_in_iff in types_match as (o & n_o).\n       exists o.\n       now apply HeapFacts.find_mapsto_iff, HeapFacts.elements_mapsto_iff.\n    ++ now apply StrMapFacts.find_mapsto_iff.\nAdmitted.\n\n(* Heaps and envs permutation *)\n\nDefinition PermutationPreservesSatisfying t :=\n  forall h h_perm env env_perm this pi CC,\n    HeapsPermuted h h_perm pi ->\n    EnvsPermuted env env_perm pi ->\n    HeapEnvEquivalent h h_perm env env_perm this this t CC.\n\nDefinition PermutationPreservesSatisfyingOuter t :=\n  forall h h_perm env env_perm this pi CC,\n    HeapsPermuted h h_perm pi ->\n    EnvsPermuted env env_perm pi ->\n    HeapEnvEquivalentOuter h h_perm env env_perm this this t CC.\n\nLemma PermutationPreservesExistsSatisfying : forall type x t,\n  PermutationPreservesSatisfyingOuter t ->\n  PermutationPreservesSatisfyingOuter (JFIExists type x t).\nProof.\n  intros type name t IHt h h_perm env env_perm this pi CC pi_h pi_env.\n  split.\n  + intros (l & l_of_type & h_satisfies_t).\n    destruct (PiMapsToSameType h h_perm pi l type pi_h l_of_type)\n      as (l_perm & pi_l & l_perm_of_type).\n    exists l_perm.\n    simpl.\n    split; trivial.\n    set (env' := StrMap.add name l env).\n    set (env_perm' := StrMap.add name l_perm env_perm).\n    apply (IHt h h_perm env' env_perm' this pi CC); trivial.\n    unfold env', env_perm'.\n    now apply ExtendedEnvsPermuted.\n  + intros (l_perm & l_perm_of_type & h_satisfies_t).\n    destruct (InvertPermutation pi) as (pi' & pi'_heaps & pi'_envs).\n    apply pi'_heaps in pi_h.\n    apply pi'_envs in pi_env.\n    destruct (PiMapsToSameType h_perm h pi' l_perm type pi_h l_perm_of_type)\n      as (l & pi_l & l_of_type).\n    exists l.\n    simpl.\n    split; trivial.\n    set (env' := StrMap.add name l env).\n    set (env_perm' := StrMap.add name l_perm env_perm).\n    apply (IHt h_perm h env_perm' env' this pi' CC); trivial.\n    unfold env', env_perm'.\n    now apply ExtendedEnvsPermuted.\nQed.\n\nLemma ExistsVarInEnvPerm : forall env env_perm pi var l,\n  EnvsPermuted env env_perm pi ->\n  StrMap.MapsTo var l env ->\n  exists l', StrMap.MapsTo var l' env_perm.\nProof.\n  intros env env_perm pi var l.\n  intros pi_env env_eq.\n  destruct pi_env as (bijection & same_vars & pi_env).\n  assert (var_in_env_perm : StrMap.In var env_perm).\n  apply same_vars.\n  apply StrMapFacts.elements_in_iff.\n  exists l.\n  now apply StrMapFacts.elements_mapsto_iff.\n  apply StrMapFacts.elements_in_iff in var_in_env_perm as (l' & var_l'_env_perm).\n  apply StrMapFacts.elements_mapsto_iff in var_l'_env_perm.\n  now exists l'.\nQed.\n\nLemma PermutationPreservesValToLocEq : forall x1 x2 env env_perm this pi,\n  EnvsPermuted env env_perm pi ->\n  JFIValToLoc x1 env this = JFIValToLoc x2 env this ->\n  JFIValToLoc x1 env_perm this = JFIValToLoc x2 env_perm this.\nProof.\n  intros x1 x2 env env_perm this pi.\n  intros pi_env env_eq.\n  unfold JFIValToLoc in *.\n  assert (pi_this : PiMapsTo (JFLoc this) (JFLoc this) pi).\n    admit. (* TODO this pi mapsto this*)\n  assert (pi_env' : forall x l1 l2, PiMapsTo l1 l2 pi -> StrMap.MapsTo x l1 env -> StrMap.MapsTo x l2 env_perm).\n    admit. (* TODO this extend permuted envs definition*)\n  destruct pi_env as (bijection & same_vars & pi_env).\n  destruct x1, x2; try discriminate env_eq; trivial.\n  + symmetry in env_eq.\n    apply StrMapFacts.find_mapsto_iff in env_eq.\n    destruct (ExistsVarInEnvPerm env env_perm pi var null) as (l & var_l_env); try easy.\n    assert (l_mapsto := pi_env var null l env_eq var_l_env).\n    unfold PiMapsTo in l_mapsto.\n    destruct l; try destruct l_mapsto.\n    now apply StrMapFacts.find_mapsto_iff in var_l_env.\n  + symmetry in env_eq |- *.\n    rewrite <-StrMapFacts.find_mapsto_iff in env_eq |- *.\n    now apply pi_env' with (l1 := (JFLoc this)).\n  + apply StrMapFacts.find_mapsto_iff in env_eq.\n    destruct (ExistsVarInEnvPerm env env_perm pi var null) as (l & var_l_env); try easy.\n    assert (l_mapsto := pi_env var null l env_eq var_l_env).\n    unfold PiMapsTo in l_mapsto.\n    destruct l; try destruct l_mapsto.\n    now apply StrMapFacts.find_mapsto_iff in var_l_env.\n  + rewrite <-StrMapFacts.find_mapsto_iff in env_eq |- *.\n    now apply pi_env' with (l1 := (JFLoc this)).\n  + destruct (Classical_Prop.classic (exists l0, StrMap.find var0 env = Some l0))\n      as [(l & var0_l_env) | ].\n    ++ apply StrMapFacts.find_mapsto_iff in var0_l_env.\n       destruct (ExistsVarInEnvPerm env env_perm pi var0 l) as (l' & var0_l'_env); try easy.\n       assert (l_l' := pi_env var0 l l' var0_l_env var0_l'_env).\n       apply StrMapFacts.find_mapsto_iff in var0_l'_env.\n       rewrite var0_l'_env.\n       apply StrMapFacts.find_mapsto_iff in var0_l_env.\n       rewrite var0_l_env in env_eq.\n       apply StrMapFacts.find_mapsto_iff in env_eq.\n       destruct (ExistsVarInEnvPerm env env_perm pi var l) as (l'' & var_l''_env); try easy.\n       assert (l_l'' := pi_env var l l'' env_eq var_l''_env).\n       assert (l_eq : l' = l'').\n       +++ unfold PiMapsTo in l_l', l_l''.\n           destruct l, l', l''; try easy.\n           apply NatMapFacts.find_mapsto_iff in l_l'.\n           apply NatMapFacts.find_mapsto_iff in l_l''.\n           rewrite l_l'' in l_l'.\n           injection l_l' as n_eq.\n           now rewrite n_eq.\n       +++ apply StrMapFacts.find_mapsto_iff in var_l''_env.\n           rewrite var_l''_env.\n           now rewrite l_eq.\n    ++ assert (var0_not_in_env : ~StrMap.In var0 env).\n       intros var0_in_env.\n       apply H.\n       apply StrMapFacts.elements_in_iff in var0_in_env as (l0 & var0_l0_env).\n       apply StrMapFacts.elements_mapsto_iff, StrMapFacts.find_mapsto_iff in var0_l0_env.\n       now exists l0.\n       assert (var0_not_in_env_perm : ~StrMap.In var0 env_perm).\n       intros var0_in_env_perm.\n       now apply var0_not_in_env, same_vars.\n       apply StrMapFacts.not_find_mapsto_iff in var0_not_in_env_perm.\n       rewrite var0_not_in_env_perm.\n       apply StrMapFacts.not_find_mapsto_iff in var0_not_in_env.\n       rewrite <-env_eq in var0_not_in_env.\n       apply StrMapFacts.not_find_mapsto_iff in var0_not_in_env.\n       assert (var_not_in_env_perm : ~StrMap.In var env_perm).\n       intros var_in_env_perm.\n       now apply var0_not_in_env, same_vars.\n       now apply StrMapFacts.not_find_mapsto_iff in var_not_in_env_perm.\nAdmitted.\n\nLemma PermutationPreservesElements : forall x env env_perm pi,\n  EnvsPermuted env env_perm pi ->\n  (exists l, StrMap.find x env = Some l) ->\n  exists l_perm, StrMap.find x env_perm = Some l_perm.\nProof.\n  intros x env env_perm pi pi_env (l & x_l_env).\n  destruct pi_env as (bijection & same_vars & pi_env).\n  apply StrMapFacts.find_mapsto_iff in x_l_env.\n  destruct (ExistsVarInEnvPerm env env_perm pi x l) as (l' & x_l'_env); try easy.\n  apply StrMapFacts.find_mapsto_iff in x_l'_env.\n  now exists l'.\nQed.\n\nLemma ExistsInEnvPerm : forall var env env_perm l pi,\n  EnvsPermuted env env_perm pi ->\n  StrMap.find var env = Some l ->\n  (exists l_perm, StrMap.find var env_perm = Some l_perm /\\ PiMapsTo l l_perm pi).\nProof.\n  intros var env env_perm l pi (bijection & same_vars & pi_env) var_l_env.\n  apply StrMapFacts.find_mapsto_iff in var_l_env.\n  destruct (ExistsVarInEnvPerm env env_perm pi var l) as (l' & var_l'_env); try easy.\n  apply StrMapFacts.find_mapsto_iff in var_l'_env.\n  exists l'.\n  split; trivial.\n  apply StrMapFacts.find_mapsto_iff in var_l'_env.\n  now apply pi_env with (x := var).\nQed.\n\nLemma PermutationEqImplication : forall h h' x1 x2 env env_perm this pi CC,\n  EnvsPermuted env env_perm pi ->\n  JFIHeapSatisfiesInEnv h (JFIEq x1 x2) env this CC ->\n  JFIHeapSatisfiesInEnv h' (JFIEq x1 x2) env_perm this CC.\nProof.\n  intros h h' x1 x2 env env_perm this pi CC.\n  simpl.\n  intros pi_env eq_in_env.\n  rewrite <-PermutationPreservesValToLocEq with (x1 := x1) (x2 := x2) (env := env) (pi := pi); trivial.\n  + unfold JFIValToLoc in eq_in_env |- *.\n    destruct x1; try destruct l; trivial.\n    destruct (Classical_Prop.classic (exists l_perm, StrMap.find var env_perm = Some l_perm))\n      as [(l_perm & x_l_perm_env) | not_exists_l_perm].\n    ++ now rewrite x_l_perm_env.\n    ++ exfalso; apply not_exists_l_perm.\n       apply PermutationPreservesElements with (env := env) (pi := pi); trivial.\n       destruct (StrMap.find var env); try destruct eq_in_env.\n       now exists l.\n  + destruct (JFIValToLoc x1 env), (JFIValToLoc x2 env); try easy.\n    now rewrite eq_in_env.\nQed.\n\nLemma PermutationPreservesEqSatisfying : forall x1 x2,\n  PermutationPreservesSatisfying (JFIEq x1 x2).\nProof.\n  intros x1 x2 h h_perm env env_perm this pi CC pi_h pi_env.\n  split.\n  + now apply PermutationEqImplication with (pi := pi).\n  + destruct (InvertPermutation pi) as (pi' & pi'_heaps & pi'_envs).\n    apply pi'_envs in pi_env.\n    now apply PermutationEqImplication with (pi := pi').\nQed.\n\nLemma PermFieldEq : forall o o' f v v' h h' pi,\n  JFIObjFieldEq o f v h ->\n  HeapsPermuted h h' pi ->\n  PiMapsTo o o' pi ->\n  PiMapsTo v v' pi ->\n  JFIObjFieldEq o' f v' h'.\nProof.\n  intros o o' f v v' h h' pi.\n  intros field_eq pi_h pi_o pi_v.\n  unfold JFIObjFieldEq in *.\n  destruct o as [ | n], o' as [ | n']; try easy.\n  destruct pi_h as (bijection & fst_h & snd_h & objs_h).\n  destruct (Classical_Prop.classic (exists o', Heap.find n' h' = Some o'))\n    as [(o' & n'_o'_h') | ].\n  + rewrite n'_o'_h'.\n    destruct o' as (o' & cn').\n    unfold LocsPermuted in fst_h.\n    assert (n'_in_h' : Heap.In n' h').\n      apply HeapFacts.elements_in_iff.\n      apply HeapFacts.find_mapsto_iff in n'_o'_h'.\n      apply HeapFacts.elements_mapsto_iff in n'_o'_h'.\n      now exists (o', cn').\n    destruct (snd_h n' n'_in_h') as (n'' & n'_n''_pi & n''_in_h).\n    unfold PiMapsTo in pi_o.\n    apply bijection in pi_o.\n    apply NatMapFacts.find_mapsto_iff in n'_n''_pi.\n    apply NatMapFacts.find_mapsto_iff in pi_o.\n    unfold NatMap.key in pi_o.\n    rewrite n'_n''_pi in pi_o.\n    injection pi_o as n_eq.\n    rewrite n_eq in *.\n    apply NatMapFacts.elements_in_iff in n''_in_h as (o & n_o_h).\n    apply NatMapFacts.elements_mapsto_iff in n_o_h.\n    apply NatMapFacts.find_mapsto_iff in n_o_h.\n    rewrite n_o_h in field_eq.\n    destruct o as (o & cn).\n    assert (JFXIdMap.find (elt:=Loc) f o = Some v) as f_v_o.\n      destruct (JFXIdMap.find (elt:=Loc) f o); try destruct field_eq; trivial.\n    unfold ObjsPermuted in *.\n    apply NatMapFacts.find_mapsto_iff, bijection in n'_n''_pi as n_n'_pi.\n    apply HeapFacts.find_mapsto_iff in n_o_h.\n    apply HeapFacts.find_mapsto_iff in n'_o'_h'.\n    destruct (objs_h n n' (o, cn) (o', cn')) as (cn_eq & fields_results); trivial.\n    destruct (fields_results f) as (o1_fields & o2_fields & fields_map).\n    apply JFXIdMapFacts.find_mapsto_iff in f_v_o.\n    destruct (o1_fields v f_v_o) as (v'' & f_v''_o').\n    apply JFXIdMapFacts.find_mapsto_iff in f_v''_o'.\n    rewrite f_v''_o'.\n    apply JFXIdMapFacts.find_mapsto_iff in f_v''_o'.\n    assert (v_v'' := fields_map v v'' f_v_o f_v''_o').\n    unfold PiMapsTo in v_v'', pi_v.\n    destruct v, v', v''; try easy.\n    apply NatMapFacts.find_mapsto_iff in pi_v.\n    apply NatMapFacts.find_mapsto_iff in v_v''.\n    rewrite pi_v in v_v''.\n    injection v_v'' as n1_eq.\n    now rewrite n1_eq.\n  + exfalso.\n    apply H.\n    unfold LocsPermuted in fst_h.\n    destruct (Classical_Prop.classic (exists o, Heap.find n h = Some o)) as [(o & n_o_h) | ].\n    ++ apply HeapFacts.find_mapsto_iff, HeapFacts.elements_mapsto_iff in n_o_h.\n       assert (n_in_h : Heap.In n h).\n         apply HeapFacts.elements_in_iff.\n         now exists o.\n       destruct (fst_h n) as (n'' & n_n''_pi & n''_in_h'); trivial.\n       unfold PiMapsTo in pi_o.\n       apply NatMapFacts.find_mapsto_iff in n_n''_pi.\n       apply NatMapFacts.find_mapsto_iff in pi_o.\n       rewrite n_n''_pi in pi_o.\n       injection pi_o as n_eq.\n       rewrite n_eq in n''_in_h'.\n       apply NatMapFacts.elements_in_iff in n''_in_h' as (o' & n'_o'_h').\n       apply NatMapFacts.elements_mapsto_iff, NatMapFacts.find_mapsto_iff in n'_o'_h'.\n       now exists o'.\n    ++ exfalso.\n       apply H0.\n       destruct (Heap.find (elt:=Obj) n h); try destruct field_eq.\n       now exists o.\nQed.\n\nLemma FieldEqFindObj : forall env env_perm h h_perm var l l_perm f pi,\n  EnvsPermuted env env_perm pi ->\n  HeapsPermuted h h_perm pi ->\n  PiMapsTo l l_perm pi ->\n  match StrMap.find var env with\n  | Some objLoc => JFIObjFieldEq objLoc f l h\n  | None => False\n  end ->\n  match StrMap.find var env_perm with\n  | Some objLoc => JFIObjFieldEq objLoc f l_perm h_perm\n  | None => False\n  end.\nProof.\n  intros env env_perm h h_perm var l l_perm f pi.\n  intros pi_env pi_h pi_l env_eq.\n  assert (exists o, StrMap.find var env = Some o).\n    destruct (StrMap.find var env); try destruct env_eq.\n    now exists l0.\n  destruct H as (l' & var_l'_env).\n  destruct (ExistsInEnvPerm var env env_perm l' pi pi_env var_l'_env) as (l'_perm & var_l'_env_perm & pi_l').\n    rewrite var_l'_env_perm.\n    rewrite var_l'_env in env_eq.\n    now apply PermFieldEq with (o := l') (v := l) (h := h) (pi := pi).\nQed.\n\nLemma FieldEqFindVal : forall env env_perm h h_perm var o o_perm f pi,\n  EnvsPermuted env env_perm pi ->\n  HeapsPermuted h h_perm pi ->\n  PiMapsTo o o_perm pi ->\n  match StrMap.find var env with\n  | Some valLoc => JFIObjFieldEq o f valLoc h\n  | None => False\n  end ->\n  match StrMap.find var env_perm with\n  | Some valLoc => JFIObjFieldEq o_perm f valLoc h_perm\n  | None => False\n  end.\nProof.\n  intros env env_perm h h_perm var o o_perm f pi.\n  intros pi_env pi_h pi_o env_eq.\n  assert (exists o, StrMap.find var env = Some o).\n    destruct (StrMap.find var env); try destruct env_eq.\n    now exists l.\n  destruct H as (l & var_l_env).\n  destruct (ExistsInEnvPerm var env env_perm l pi pi_env var_l_env) as (l_perm & var_l_env_perm & pi_l).\n  rewrite var_l_env_perm.\n  rewrite var_l_env in env_eq.\n  now apply PermFieldEq with (o := o) (v := l) (h := h) (pi := pi).\nQed.\n\nLemma PermutationFieldEqImplication : forall h h_perm o f v env env_perm this pi CC,\n  EnvsPermuted env env_perm pi ->\n  HeapsPermuted h h_perm pi ->\n  JFIHeapSatisfiesInEnv h (JFIFieldEq o f v) env this CC ->\n  JFIHeapSatisfiesInEnv h_perm (JFIFieldEq o f v) env_perm this CC.\nProof.\n  intros h h_perm o f v env env_perm this pi CC.\n  intros pi_env pi_h env_eq.\n  simpl in *.\n  unfold EnvsPermuted in pi_env.\n  unfold HeapsPermuted in pi_h.\n  unfold JFIValToLoc in *.\n  assert (pi_this : PiMapsTo (JFLoc this) (JFLoc this) pi).\n    admit. (* TODO this pi mapsto this*)\n  destruct o, v; try easy.\n  + now apply FieldEqFindVal with (env := env) (h := h) (o := null) (pi := pi).\n  + now apply PermFieldEq with (h := h) (o := (JFLoc this)) (v := null) (pi := pi).\n  + now apply PermFieldEq with (h := h) (o := (JFLoc this)) (v := (JFLoc this)) (pi := pi); try easy.\n  + now apply FieldEqFindVal with (env := env) (h := h) (o := (JFLoc this)) (pi := pi).\n  + now apply FieldEqFindObj with (env := env) (h := h) (l := null) (pi := pi).\n  + now apply FieldEqFindObj with (env := env) (h := h) (l := (JFLoc this)) (pi := pi).\n  + destruct (Classical_Prop.classic (exists l, StrMap.find var env = Some l)) as [ (o & var_o_env) | not_find ].\n    ++ destruct (ExistsInEnvPerm var env env_perm o pi pi_env var_o_env) as (o_perm & var_o_env_perm & pi_o).\n       rewrite var_o_env_perm.\n       rewrite var_o_env in env_eq.\n       now apply FieldEqFindVal with (env := env) (h := h) (o := o) (pi := pi).\n    ++ exfalso.\n       apply not_find.\n       destruct (StrMap.find (elt:=Loc) var env).\n       now exists l.\n       destruct env_eq.\nAdmitted.\n\nLemma PermutationPreservesFieldEqSatisfying : forall o f v,\n  PermutationPreservesSatisfying (JFIFieldEq o f v).\nProof.\n  intros o f v h h_perm env env_perm this pi CC pi_h pi_env.\n  split.\n  + now apply PermutationFieldEqImplication with (pi := pi).\n  + destruct (InvertPermutation pi) as (pi' & pi'_heaps & pi'_envs).\n    apply pi'_envs in pi_env.\n    apply pi'_heaps in pi_h.\n    now apply PermutationFieldEqImplication with (pi := pi').\nQed.\n\nLemma PermutationSepImplication : forall t1 t2 h h_perm env env_perm this pi CC,\n  PermutationPreservesSatisfying t1 ->\n  PermutationPreservesSatisfying t2 ->\n  HeapsPermuted h h_perm pi ->\n  EnvsPermuted env env_perm pi ->\n  JFIHeapSatisfiesInEnv h (JFISep t1 t2) env this CC ->\n  JFIHeapSatisfiesInEnv h_perm (JFISep t1 t2) env_perm this CC.\nProof.\n  intros t1 t2 h h_perm env env_perm this pi CC IH_t1 IH_t2 pi_h pi_env.\n  intros sep_in_env.\n  assert (pi_correct := proj1 pi_h).\n  destruct sep_in_env as (h1 & h2 & hs_consistent & disj_union & h1_satisfies_t1 & h2_satisfies_t2).\n  assert (covers_h := PermutedHeapCovered h h_perm pi pi_h).\n  destruct (proj1 (PermutationCoversUnion h1 h2 h pi (proj1 disj_union)) covers_h).\n  destruct (ExistsPermutedHeap h1 pi) as (h1_perm & pi_h1); trivial.\n  destruct (ExistsPermutedHeap h2 pi) as (h2_perm & pi_h2); trivial.\n  exists h1_perm, h2_perm.\n  split; split.\n  + admit. (* TODO permutation consistent *)\n  + admit. (* TODO permutation consistent *)\n  + now apply DisjointUnionPermuted with (h1 := h1) (h2 := h2) (h := h) (pi := pi).\n  + split.\n    now apply (IH_t1 h1 h1_perm env env_perm this pi CC).\n    now apply (IH_t2 h2 h2_perm env env_perm this pi CC).\nAdmitted.\n\nLemma PermutationPreservesSepSatisfying : forall t1 t2,\n  PermutationPreservesSatisfying t1 ->\n  PermutationPreservesSatisfying t2 ->\n  PermutationPreservesSatisfying (JFISep t1 t2).\nProof.\n  intros t1 t2 IH_t1 IH_t2 h h_perm env env_perm this pi CC pi_h pi_env.\n  split.\n  + now apply PermutationSepImplication with (pi := pi).\n  + destruct (InvertPermutation pi) as (pi' & pi'_heaps & pi'_envs).\n    apply pi'_envs in pi_env.\n    apply pi'_heaps in pi_h.\n    now apply PermutationSepImplication with (pi := pi').\nQed.\n\nLemma PermutationWandImplication : forall t1 t2 h h_perm env env_perm this pi CC,\n  PermutationPreservesSatisfying t1 ->\n  PermutationPreservesSatisfying t2 ->\n  HeapsPermuted h h_perm pi ->\n  EnvsPermuted env env_perm pi ->\n  JFIHeapSatisfiesInEnv h (JFIWand t1 t2) env this CC ->\n  JFIHeapSatisfiesInEnv h_perm (JFIWand t1 t2) env_perm this CC.\nProof.\n  intros t1 t2 h h_perm env env_perm this pi CC IH_t1 IH_t2 pi_h pi_env.\n  intros wand_in_env.\n  assert (bijection := proj1 pi_h).\n  intros h'_perm h'_perm_consistent disj_perm h'_satisfies_t1.\n  destruct (InvertPermutation pi) as (pi' & pi'_heaps & pi'_envs).\n  assert (pi'_h := pi_h).\n  apply pi'_heaps in pi'_h.\n  destruct (ExistsPermutedHeap h'_perm pi') as (h' & pi_h'); trivial.\n  now apply pi'_h.\n  apply pi'_heaps in pi'_h.\n  admit. (* TODO extend pi' *)\n  assert (h_h'_disj : JFIHeapsDisjoint h h').\n  now apply DisjointPermuted with (h1 := h_perm) (h2 := h'_perm) (pi := pi').\n\n  simpl in wand_in_env.\n  assert (pi'_h' := pi_h').\n  apply pi'_heaps in pi_h'.\n  assert (pi'_env := pi_env).\n  apply pi'_envs in pi'_env.\n  apply (IH_t1 h'_perm h' env_perm env this pi' CC) in h'_satisfies_t1; try easy.\n  assert (h'_consistent : HeapConsistent h').\n    admit. (* TODO permutation consistent *)\n  destruct (wand_in_env h' h'_consistent h_h'_disj h'_satisfies_t1) as (h_h' & union_h_h' & h_h'_satisfies_t2).\n  assert (covers_h := PermutedHeapCovered h h_perm pi pi_h).\n  assert (covers_h' := PermutedHeapCovered h' h'_perm pi pi_h').\n  assert (covers_h_h' : PiCoversHeap pi h_h').\n  now apply (PermutationCoversUnion h h' h_h' pi union_h_h').\n  destruct (ExistsPermutedHeap h_h' pi) as (h_h'_perm & pi_h_h'); trivial.\n  exists h_h'_perm.\n  split; trivial.\n  now apply UnionPermuted with (h1 := h) (h2 := h') (h := h_h') (pi := pi).\n  now apply (IH_t2 h_h' h_h'_perm env env_perm this pi CC).\nAdmitted.\n\nLemma PermutationPreservesWandSatisfying : forall t1 t2,\n  PermutationPreservesSatisfying t1 ->\n  PermutationPreservesSatisfying t2 ->\n  PermutationPreservesSatisfying (JFIWand t1 t2).\nProof.\n  intros t1 t2 IH_t1 IH_t2 h h_perm env env_perm this pi CC pi_h pi_env.\n  split.\n  + now apply PermutationWandImplication with (pi := pi).\n  + destruct (InvertPermutation pi) as (pi' & pi'_heaps & pi'_envs).\n    apply pi'_envs in pi_env.\n    apply pi'_heaps in pi_h.\n    now apply PermutationWandImplication with (pi := pi').\nQed.\n\nLemma PermutationPreservesHeapSatisfying : forall t,\n  PermutationPreservesSatisfying t .\nProof.\n  intros t.\n  induction t; intros h h_perm env env_perm this pi CC pi_h pi_env; eauto.\n  + admit. (* TODO hoare *)\n  + now apply PermutationPreservesEqSatisfying with (pi := pi).\n  + now apply PermutationPreservesFieldEqSatisfying with (pi := pi).\n  + now apply PermutationPreservesSepSatisfying with (pi := pi).\n  + now apply PermutationPreservesWandSatisfying with (pi := pi).\nAdmitted.\n\nLemma AddingNullPreservesHeapSatisfying : forall h t x env this CC,\n  JFIHeapSatisfiesInEnv h t env this CC ->\n  JFIHeapSatisfiesInEnv h t (StrMap.add x null env) this CC.\nProof.\nAdmitted.\n\nLemma HTFrameRuleSoundness : forall decls gamma s p r e ex v q,\n  let CC := JFIDeclsProg decls in\n  JFITermPersistent s ->\n  JFIVarFreshInTerm v r ->\n  JFISemanticallyImplies gamma s (JFIHoare         p    e ex v         q   ) CC ->\n  JFISemanticallyImplies gamma s (JFIHoare (JFISep p r) e ex v (JFISep q r)) CC.\nProof.\n  intros decls gamma s p r e ex v q CC.\n  intros s_persistent v_fresh_in_r hoare_p_e_q.\n  intros env this h gamma_match_env h_satisfies_s.\n  intros h_satisfies_sep.\n  destruct h_satisfies_sep as (hp & hr & (hp_consistent & hr_consistent) & union_hp_hr &\n    hp_satisfies_p & hr_satisfies_r).\n  assert (fake_gamma_match_env : JFIGammaMatchEnv hp gamma env). admit.\n  assert (hp_satisfies_s := h_satisfies_s).\n  apply (proj2 (EveryHeapSatisfiesPersistentTerm s hp h env this CC s_persistent)) in hp_satisfies_s.\n  assert (hp_satisfies_hoare := hoare_p_e_q env this hp fake_gamma_match_env hp_satisfies_s).\n  assert (hp_eval := hp_satisfies_hoare hp_satisfies_p).\n  fold JFIHeapSatisfiesInEnv in hp_eval.\n  destruct hp_eval as (confs & hn & res_ex & res & hp_eval & ex_eq & hn_satisfies_q).\n  rewrite ex_eq in *; clear ex_eq res_ex.\n  destruct (EvaluationOnExtendedHeap hp hr h e confs hn ex res env this CC)\n    as (confs_ext & hn_perm & hn_ext & res_ext & pi & eval_ext); try easy.\n    admit. (* TODO no hardcoded locs in e *)\n    admit. (* TODO free vars in e are in hp *)\n  destruct eval_ext as\n    (hn_pi & env_pi & res_pi & union_hn_perm_hr & eval_ext).\n  exists confs_ext, hn_ext, ex, res_ext.\n  simpl.\n  split; try split; try easy.\n  exists hn_perm, hr.\n  split; [ split | split; [ | split]]; try easy.\n  + admit. (* TODO permutation consistent *)\n  + apply (PermutationPreservesHeapSatisfying _  hn _ (StrMap.add v res env) _ _ pi CC); try easy.\n    now apply ExtendPermutedEnvs.\n  + destruct res_ext.\n    ++ now apply AddingNullPreservesHeapSatisfying.\n    ++ now apply AddingFreshVarPreservesHeapSatisfying.\nAdmitted.\nHint Resolve HTFrameRuleSoundness : core.\n\nLemma HTRetRuleSoundness : forall gamma s v w w_expr CC,\n  FreeVarsInValAreInGamma w gamma ->\n  w_expr = JFIValToJFVal w ->\n  JFISemanticallyImplies gamma s\n    (JFIHoare JFITrue (JFVal1 w_expr) None v (JFIEq (JFIVar v) w)) CC.\nProof.\n  intros gamma s v w w_expr CC.\n  intros w_in_gamma expr_val env this h gamma_match_env h_satisfies_s h_satisfies_true.\n\n  destruct (JFIExistsValToLoc w w_expr h gamma env this) as (l & w_is_l & subst_w); try easy.\n  exists [], h, None, l.\n  unfold JFIEvalInEnv, JFIExprSubstituteEnv.\n  rewrite subst_w.\n  split; try split; try easy.\n  simpl.\n  rewrite StrMapFacts.add_eq_o; trivial.\n  unfold JFIValToLoc in w_is_l |- *.\n  destruct w; try now injection w_is_l.\n  destruct (Classical_Prop.classic (v = var)).\n  + now rewrite StrMapFacts.add_eq_o.\n  + rewrite StrMapFacts.add_neq_o; trivial.\n    now rewrite w_is_l.\nQed.\n\nLemma HTPreconditionStrenghtenSoundness : forall gamma s p p' e ex v q CC,\n  (JFISemanticallyImplies gamma s (JFIImplies p p') CC) ->\n  (JFISemanticallyImplies gamma s (JFIHoare p' e ex v q) CC) ->\n   JFISemanticallyImplies gamma s (JFIHoare p e ex v q) CC.\nProof.\n  intros gamma s p p' e ex v q CC.\n  intros p_implies_p' hoare_p'.\n  intros env this h gamma_match_env h_satisfies_s.\n  simpl.\n  intros h_satisfies_p.\n  set (h_satisfies_hoare_p' := hoare_p' env this h gamma_match_env h_satisfies_s).\n  simpl in h_satisfies_hoare_p'.\n  apply h_satisfies_hoare_p'.\n  destruct (p_implies_p' env this h gamma_match_env h_satisfies_s) as [not_h_satisfies_p | h_satisfies_p'].\n  + destruct (not_h_satisfies_p h_satisfies_p).\n  + exact h_satisfies_p'.\nQed.\n\nLemma HTPostconditionWeakenSoundness : forall gamma s p e ex v q q' cn CC,\n  (JFITermPersistent s) ->\n  (JFIVarFreshInTerm v s) ->\n  (JFISemanticallyImplies gamma s (JFIHoare p e ex v q') CC) ->\n  (JFISemanticallyImplies (JFIGammaAdd v cn gamma) s (JFIImplies q' q) CC) ->\n   JFISemanticallyImplies gamma s (JFIHoare p e ex v q) CC.\nProof.\n  intros gamma s p e ex v q q' cn CC.\n  intros s_persistent v_fresh hoare_q' q'_implies_q.\n  intros env this h gamma_match_env h_satisfies_s.\n  simpl.\n  intros h_satisfies_p.\n  destruct (hoare_q' env this h gamma_match_env h_satisfies_s h_satisfies_p ) as\n    (confs & hn & res_ex & res & eval_e & res_eq & h_satisfies_q').\n  fold JFIHeapSatisfiesInEnv in h_satisfies_q'.\n  assert (gamma_match_env_in_hn := EvaluationPreservesGammaMatching gamma env h (JFIExprSubstituteEnv env this e) confs hn res_ex res CC gamma_match_env eval_e).\n  assert (hn_satisfies_s := EvaluationPreservesPersistentTerms env this s h (JFIExprSubstituteEnv env this e) confs hn res_ex res CC s_persistent h_satisfies_s eval_e).\n  apply AddingFreshVarPreservesHeapSatisfying with (x := v) (l := res) in hn_satisfies_s; trivial.\n  assert (gamma_v_match_env : JFIGammaMatchEnv hn (JFIGammaAdd v cn gamma) (StrMap.add v res env)). admit.\n  assert (hn_satisfies_implies := q'_implies_q (StrMap.add v res env) this hn gamma_v_match_env hn_satisfies_s).\n  exists confs, hn, res_ex, res.\n  split; try split; try easy.\n  simpl in hn_satisfies_implies.\n  now destruct hn_satisfies_implies.\nAdmitted.\n\nLemma HTCsqRuleSoundness : forall gamma s p p' e ex v q q' cn CC,\n  (JFITermPersistent s) ->\n  (JFIVarFreshInTerm v s) ->\n  (JFISemanticallyImplies gamma s (JFIImplies p p') CC) ->\n  (JFISemanticallyImplies gamma s (JFIHoare p' e ex v q') CC) ->\n  (JFISemanticallyImplies (JFIGammaAdd v cn gamma) s (JFIImplies q' q) CC) -> JFISemanticallyImplies gamma s (JFIHoare p e ex v q) CC.\nProof.\n  intros gamma s p p' e ex v q q' cn CC.\n  intros s_persistent p_implies_p' q_implies_q' hoare_p'q'.\n  apply HTPostconditionWeakenSoundness with (q':=q') (cn:=cn) (v:=v); try easy.\n  now apply HTPreconditionStrenghtenSoundness with (p':=p'); try easy.\nQed.\nHint Resolve HTCsqRuleSoundness : core.\n\nLemma HTDisjIntroRuleSoundness : forall gamma s p q e ex v r CC,\n  (JFISemanticallyImplies gamma s (JFIHoare p e ex v r) CC) ->\n  (JFISemanticallyImplies gamma s (JFIHoare q e ex v r) CC) ->\n   JFISemanticallyImplies gamma s (JFIHoare (JFIOr p q) e ex v r) CC.\nProof.\n  intros gamma s p q e ex v r CC.\n  intros hoare_p_r hoare_q_r.\n  intros env this h gamma_match_env h_satisfies_s.\n  simpl.\n  intros p_or_q.\n  destruct p_or_q.\n  + exact (hoare_p_r env this h gamma_match_env h_satisfies_s H).\n  + exact (hoare_q_r env this h gamma_match_env h_satisfies_s H).\nQed.\nHint Resolve HTDisjIntroRuleSoundness : core.\n\nLemma HTEqRule1Soundness : forall gamma s p v1 v2 e ex v q CC,\n  (JFISemanticallyImplies gamma (JFIAnd s (JFIEq v1 v2)) (JFIHoare p e ex v q) CC) ->\n  (JFISemanticallyImplies gamma s (JFIHoare (JFIAnd p (JFIEq v1 v2)) e ex v q) CC).\nProof.\n  intros gamma s p v1 v2 e ex v q CC.\n  intros p_eq_implies_hoare.\n  intros env this h gamma_match_env h_satisfies_s (h_satisfies_p & h_satisfies_eq).\n  simpl.\n  now apply p_eq_implies_hoare.\nQed.\nHint Resolve HTEqRule1Soundness : core.\n\nLemma HTEqRule2Soundness : forall gamma s p v1 v2 e ex v q CC,\n  (JFISemanticallyImplies gamma s (JFIHoare (JFIAnd p (JFIEq v1 v2)) e ex v q) CC) ->\n  (JFISemanticallyImplies gamma (JFIAnd s (JFIEq v1 v2)) (JFIHoare p e ex v q) CC).\nProof.\n  intros gamma s p v1 v2 e ex v q CC.\n  intros p_eq_implies_hoare.\n  intros env this h gamma_match_env (h_satisfies_s & h_satisfies_eq) h_satisfies_p.\n  now apply p_eq_implies_hoare.\nQed.\nHint Resolve HTEqRule2Soundness : core.\n\nLemma HTNewNotNullRuleSoundness : forall gamma s p mu cn vs v CC,\n  JFISemanticallyImplies gamma s\n    (JFIHoare p (JFNew mu cn vs) None v\n     (JFIImplies (JFIEq (JFIVar v) JFINull) JFIFalse)) CC.\nProof.\n  intros gamma s p mu cn vs v CC.\n  intros env this h gamma_match_env h_satisfies_s.\n  destruct (EnsureValsMapIsLocsMap vs env this) as (ls & vs_is_ls).\n  destruct (AllocSucceedsInCorrectProgram CC h cn ls)\n    as (newloc & (newheap & alloc_newloc_newheap)).\n  intros h_satisfies_p.\n  exists [(h, [ [] [[ JFIExprSubstituteEnv env this (JFNew mu cn vs) ]]_ None])],\n    newheap, None, newloc.\n  split; [ | split].\n  + apply NewEvaluationStep with (prog := CC) (ls := ls); assumption.\n  + trivial.\n  + simpl.\n    apply or_introl.\n    rewrite StrMapFacts.add_eq_o.\n    ++ apply (SuccessfullAllocIsNotNull CC h cn ls newloc newheap alloc_newloc_newheap).\n    ++ trivial.\nQed.\nHint Resolve HTNewNotNullRuleSoundness : core.\n\nLemma HTNewFieldRuleSoundness : forall decls gamma cn objflds vs n field value s p mu v CC,\n  (FreeVarsInValAreInGamma value gamma) ->\n  (flds (JFIDeclsProg decls) (JFClass cn) = Some objflds) ->\n  (nth_error objflds n = Some field) ->\n  (nth_error vs n = Some (JFIValToJFVal value)) ->\n  (value <> (JFIVar v)) ->\n    JFISemanticallyImplies gamma s\n      (JFIHoare p (JFNew mu cn vs) None v (JFIFieldEq (JFIVar v) field value)) CC.\nProof.\n  intros decls gamma cn objflds vs n field value s p mu v CC.\n  intros value_in_gamma fdls_of_cn nth_field nth_value value_not_v.\n  intros env this h gamma_match_env h_satisfies_s h_satisfies_p.\n  destruct (EnsureValsMapIsLocsMap vs env this) as (ls & vs_map_is_ls).\n  simpl.\n  unfold JFIHeapSatisfiesInEnv.\n\n  destruct (JFIExistsValToLoc value (JFIValToJFVal value) h gamma env this) as (l & value_is_l & subst_value); trivial.\n  assert (vs_is_ls := EnsureValsListIsLocsList ls vs n l env this vs_map_is_ls).\n  destruct (AllocSucceedsInCorrectProgram (JFIDeclsProg decls) h cn ls)\n    as (newloc & (newheap & alloc_newloc_newheap)).\n  exists [(h, [ [] [[ JFIExprSubstituteEnv env this (JFNew mu cn vs) ]]_ None])], newheap, None, newloc.\n  split; [ | split]; trivial.\n  + apply NewEvaluationStep with (prog := JFIDeclsProg decls) (ls := ls); assumption.\n  + rewrite StrMapFacts.add_eq_o; trivial.\n    rewrite ValToLoc_neq_o; trivial.\n    rewrite value_is_l.\n    apply (SuccessfullAllocSetsFields decls h cn ls newloc newheap objflds n field l); try assumption.\n    apply vs_is_ls.\n    rewrite <-subst_value.\n    now apply List.map_nth_error.\nQed.\nHint Resolve HTNewFieldRuleSoundness : core.\n\nLemma AddingFreshVarInsidePreservesHeapSatisfying : forall q h env this x1 l1 x2 l2 CC,\n   (JFIVarFreshInTerm x2 q) ->\n    JFIHeapSatisfiesInEnv h q (StrMap.add x1 l1 env) this CC <->\n   (JFIHeapSatisfiesInEnv h q (StrMap.add x1 l1 (StrMap.add x2 l2 env)) this CC).\nProof.\nAdmitted.\n\nLemma HTLetRuleSoundness : forall gamma s p e1 e2 class x q ex u r CC,\n  (JFITermPersistent s) ->\n  (JFIVarFreshInTerm x s) ->\n  (JFIVarFreshInTerm x r) ->\n  (JFISemanticallyImplies gamma s (JFIHoare p e1 None x q) CC) ->\n  (JFISemanticallyImplies (JFIGammaAdd x class gamma) s (JFIHoare q e2 ex u r) CC) ->\n  JFISemanticallyImplies gamma s (JFIHoare p (JFLet class x e1 e2) ex u r) CC.\nProof.\n  intros gamma s p e1 e2 class x q ex u r CC.\n  intros s_persistent x_fresh_in_s x_fresh_in_r IH_e1 IH_e2.\n  intros env this h gamma_match_env.\n  intros h_satisfies_s h_satisfies_p.\n\n  assert (tmp := IH_e1 env this h gamma_match_env h_satisfies_s h_satisfies_p).\n  fold JFIHeapSatisfiesInEnv in tmp.\n  destruct tmp as (e1_confs & h' & e1_ex & e1_res & e1_eval & e1_ex_is_none & h'_satisfies_q).\n  rewrite e1_ex_is_none in *; clear e1_ex_is_none.\n\n  assert (h'_gamma_match_env : JFIGammaMatchEnv h' (JFIGammaAdd x class gamma) (StrMap.add x e1_res env)).\n    admit.\n  assert (h'_satisfies_s : JFIHeapSatisfiesInEnv h' s (StrMap.add x e1_res env) this CC).\n  apply EvaluationPreservesPersistentTerms with (h := h) (e := (JFIExprSubstituteEnv env this e1))\n    (confs := e1_confs) (ex := None) (res := e1_res); try easy.\n  now apply AddingFreshVarPreservesHeapSatisfying.\n  assert (tmp := IH_e2 (StrMap.add x e1_res env) this h' h'_gamma_match_env h'_satisfies_s h'_satisfies_q).\n  fold JFIHeapSatisfiesInEnv in tmp.\n  simpl in tmp.\n  destruct tmp as (e2_confs & hn & res_ex & res & e2_eval & res_ex_eq & hn_satisfies_r).\n  rewrite res_ex_eq in *; clear res_ex_eq.\n  destruct (LetEvaluationNormal _ _ _ class _ _ _ _ _ _ _ _ _ _ _ e1_eval e2_eval)\n    as (let_confs & let_eval).\n  exists let_confs, hn, ex, res.\n  simpl.\n  split; [ | split]; trivial.\n  now apply AddingFreshVarInsidePreservesHeapSatisfying with (x2 := x) (l2 := e1_res).\nAdmitted.\nHint Resolve HTLetRuleSoundness : core.\n\nLemma HTLetExSoundness : forall gamma s p class x e1 e2 ex u q CC,\n  JFISemanticallyImplies gamma s (JFIHoare p e1 (Some ex) u q) CC ->\n  JFISemanticallyImplies gamma s (JFIHoare p (JFLet class x e1 e2) (Some ex) u q) CC.\nProof.\n  intros gamma s p class x e1 e2 ex u q CC.\n  intros IH_e1.\n  intros env this h gamma_match_env.\n  intros h_satisfies_s h_satisfies_p.\n\n  assert (tmp := IH_e1 env this h gamma_match_env h_satisfies_s h_satisfies_p).\n  fold JFIHeapSatisfiesInEnv in tmp.\n  destruct tmp as (e1_confs & hn & e1_ex & e1_res & e1_eval & ex_eq & h'_satisfies_q).\n  rewrite ex_eq in *.\n\n  destruct (LetEvaluationEx _ _ class x e1 e2 _ _ _ _ _ _ e1_eval) as (let_confs & let_eval).\n  exists let_confs, hn, e1_ex, e1_res.\n  simpl.\n  now rewrite ex_eq in *.\nQed.\nHint Resolve HTLetExSoundness : core.\n\nLemma HTFieldSetRuleSoundness : forall gamma s x x_expr field u v v_expr CC,\n  FreeVarsInValAreInGamma x gamma ->\n  FreeVarsInValAreInGamma v gamma ->\n  x_expr = JFIValToJFVal x ->\n  v_expr = JFIValToJFVal v ->\n  x <> (JFIVar u) ->\n  v <> (JFIVar u) ->\n  JFISemanticallyImplies gamma s\n    (JFIHoare (JFIImplies (JFIEq x JFINull) JFIFalse) (JFAssign (x_expr, field) v_expr)\n     None u (JFIFieldEq x field v)) CC.\nProof.\n  intros gamma s x x_expr field u v v_expr CC.\n  intros x_in_gamma v_in_gamma x_expr_val v_expr_val x_not_u v_not_u.\n  intros env this h gamma_match_env h_satisfies_s h_satisfies_p.\n\n  destruct (JFIExistsValToLoc x x_expr h gamma env this) as (xl & x_is_xl & subst_x); trivial.\n  destruct (JFIExistsValToLoc v v_expr h gamma env this) as (vl & v_is_vl & subst_v); trivial.\n  destruct xl as [ | xn].\n  + destruct h_satisfies_p; try easy. exfalso. apply H. simpl. now rewrite x_is_xl.\n  + destruct (EnsureLocInHeap x h gamma env this xn) as ((obj & cn) & x_points_to_o); try easy.\n    set (new_obj := ((JFXIdMap.add field vl obj), cn)).\n    set (new_h := Heap.add xn new_obj h).\n    exists [(h, [ [] [[ (JFAssign (JFVLoc (JFLoc xn), field) (JFVLoc vl)) ]]_ None])], new_h, None, vl.\n    simpl.\n    split; [ | split]; trivial.\n    ++ unfold JFIEvalInEnv, JFIEval, JFIPartialEval.\n       split; try trivial.\n       unfold JFIExprSubstituteEnv.\n       rewrite subst_x, subst_v.\n       split; trivial.\n       unfold red.\n       rewrite x_points_to_o.\n       now split.\n    ++ simpl.\n       rewrite 2!ValToLoc_neq_o; trivial.\n       rewrite x_is_xl, v_is_vl.\n       unfold JFIObjFieldEq.\n       unfold new_h.\n       rewrite HeapFacts.add_eq_o; try trivial.\n       unfold new_obj.\n       rewrite JFXIdMapFacts.add_eq_o; trivial.\nQed.\nHint Resolve HTFieldSetRuleSoundness : core.\n\nLemma ValEval : forall h v ex confs hn v' ex' CC,\n  JFIPartialEval h [ [] [[JFVal1 v ]]_ ex] confs hn [ [] [[JFVal1 v' ]]_ ex'] CC ->\n  (ex = ex' /\\ v = v').\nProof.\n  intros h v ex confs hn v' ex' CC.\n  intros eval.\n  unfold JFIPartialEval in eval.\n  destruct confs.\n  + destruct eval as (_ & st_eq).\n    injection st_eq.\n    intros ex_eq v_eq.\n    rewrite ex_eq, v_eq.\n    split; trivial.\n  + destruct p.\n    destruct eval as (_ & _ & val_red).\n    fold JFIPartialEval in val_red.\n    unfold red in val_red.\n    destruct v, ex; destruct val_red.\nQed.\n\nLemma HTNullFieldSetRuleSoundness : forall gamma s x x_expr field loc v CC,\n  x_expr = JFIValToJFVal x ->\n  JFISemanticallyImplies gamma s\n    (JFIHoare (JFIEq x JFINull) (JFAssign (x_expr, field) (JFVLoc loc))\n     NPE_mode v JFITrue) CC.\nProof.\n  intros gamma s x x_expr field loc v CC.\n  intros x_expr_val.\n  intros env this h gamma_match_env h_satisfies_s.\n  intros x_is_null.\n  simpl in x_is_null.\n  exists [(h, [ [] [[ JFIExprSubstituteEnv env this (JFAssign (x_expr, field) (JFVLoc loc)) ]]_ None])],\n    h, NPE_mode, (JFLoc NPE_object_loc).\n  simpl.\n  split; try split; try split; trivial.\n  destruct x; rewrite x_expr_val.\n  + simpl.\n    now rewrite 2!ValEnvSubstitutionPreservesVLoc.\n  + discriminate x_is_null.\n  + simpl in x_is_null.\n    simpl.\n    rewrite ValEnvSubstitutionReplacesVarInEnv with (l := null); trivial.\n    now rewrite ValEnvSubstitutionPreservesVLoc.\n    destruct (StrMap.find var env); try easy.\n    now rewrite x_is_null.\nQed.\nHint Resolve HTNullFieldSetRuleSoundness : core.\n\nLemma HTNullFieldGetRuleSoundness : forall gamma s x x_expr field v CC,\n  x_expr = JFIValToJFVal x ->\n  JFISemanticallyImplies gamma s\n    (JFIHoare (JFIEq x JFINull) (JFVal2 (x_expr, field))\n     NPE_mode v JFITrue) CC.\nProof.\n  intros gamma s x x_expr field v CC.\n  intros x_expr_val.\n  intros env this h gamma_match_env h_satisfies_s.\n  intros x_is_null.\n  simpl in x_is_null.\n  exists [(h, [ [] [[ JFIExprSubstituteEnv env this (JFVal2 (x_expr, field)) ]]_ None])],\n    h, NPE_mode, (JFLoc NPE_object_loc).\n  simpl.\n  split; try split; try split; trivial.\n  destruct x; rewrite x_expr_val.\n  + simpl.\n    now rewrite ValEnvSubstitutionPreservesVLoc.\n  + discriminate x_is_null.\n  + simpl in x_is_null.\n    simpl.\n    rewrite ValEnvSubstitutionReplacesVarInEnv with (l := null); try easy.\n    destruct (StrMap.find var env); try easy.\n    now rewrite x_is_null.\nQed.\nHint Resolve HTNullFieldGetRuleSoundness : core.\n\nLemma HTIfRuleSoundness : forall gamma v1 v1_expr v2 v2_expr e1 e2 p q s ex u CC,\n  (FreeVarsInValAreInGamma v1 gamma) ->\n  (FreeVarsInValAreInGamma v2 gamma) ->\n  (v1_expr = JFIValToJFVal v1) -> (v2_expr = JFIValToJFVal v2) ->\n  (JFISemanticallyImplies gamma s \n    (JFIHoare (JFIAnd p (JFIEq v1 v2)) e1 ex u q) CC) ->\n  (JFISemanticallyImplies gamma s\n    (JFIHoare (JFIAnd p (JFIImplies (JFIEq v1 v2) JFIFalse)) e2 ex u q) CC) ->\n   JFISemanticallyImplies gamma s\n    (JFIHoare p (JFIf v1_expr v2_expr e1 e2) ex u q) CC.\nProof.\n  intros gamma v1 v1_expr v2 v2_expr e1 e2 p q s ex u CC.\n  intros v1_in_gamma v2_in_gamma v1_expr_val v2_expr_val IH_if_eq IH_if_neq.\n  intros env this h gamma_match_env h_satisfies_s h_satisfies_p.\n\n  destruct (JFIExistsValToLoc v1 v1_expr h gamma env this) as (l1 & v1_is_l1 & v1_subst_eq); trivial.\n  destruct (JFIExistsValToLoc v2 v2_expr h gamma env this) as (l2 & v2_is_l2 & v2_subst_eq); trivial.\n\n  destruct (Classical_Prop.classic (l1 = l2)) as [l1_eq_l2 | l1_neq_l2].\n  + assert (h_satisfies_and : JFIHeapSatisfiesInEnv h (JFIAnd p (JFIEq v1 v2)) env this CC).\n    simpl.\n    now rewrite v1_is_l1, v2_is_l2.\n    assert (e1_eval := IH_if_eq env this h gamma_match_env h_satisfies_s h_satisfies_and).\n    fold JFIHeapSatisfiesInEnv in e1_eval.\n    destruct e1_eval as (e1_confs & hn & res_ex & res & e1_eval & res_eq & hn_satisfies_q).\n    set (first_st := [ [] [[JFIExprSubstituteEnv env this (JFIf (JFVLoc l1) (JFVLoc l2) e1 e2) ]]_ None]).\n    exists ((h, first_st)::e1_confs), hn, res_ex, res.\n    unfold first_st.\n    rewrite <-l1_eq_l2.\n    split; try split; try split; trivial; simpl.\n    rewrite ValEnvSubstitutionPreservesVLoc.\n    now rewrite v1_subst_eq, v2_subst_eq, l1_eq_l2.\n    simpl.\n    rewrite v1_subst_eq, v2_subst_eq, <-l1_eq_l2.\n    Loc_dec_eq l1 l1 (eq_refl l1).\n    now unfold JFIEvalInEnv, JFIEval in e1_eval.\n  + assert (h_satisfies_and : JFIHeapSatisfiesInEnv h\n      (JFIAnd p (JFIImplies (JFIEq v1 v2) JFIFalse)) env this CC).\n    simpl. rewrite v1_is_l1, v2_is_l2. simpl. split; trivial. now apply or_introl.\n    assert (e2_eval := IH_if_neq env this h gamma_match_env h_satisfies_s h_satisfies_and).\n    fold JFIHeapSatisfiesInEnv in e2_eval.\n    destruct e2_eval as (e2_confs & hn & res_ex & res & e2_eval & res_eq & hn_satisfies_q).\n    set (first_st := [ [] [[JFIExprSubstituteEnv env this (JFIf (JFVLoc l1) (JFVLoc l2) e1 e2) ]]_ None]).\n    exists ((h, first_st)::e2_confs), hn, res_ex, res.\n    unfold first_st.\n    simpl. split; try split; try split; trivial.\n    simpl.\n    rewrite 2!ValEnvSubstitutionPreservesVLoc.\n    now rewrite v1_subst_eq, v2_subst_eq.\n    simpl.\n    rewrite v1_subst_eq, v2_subst_eq.\n    Loc_dec_neq l1 l2 l1_neq_l2.\n    now unfold JFIEvalInEnv, JFIEval in e2_eval.\nQed.\n\nLemma HTNullInvokeSoundness : forall gamma s x x_expr mn vs v CC,\n  FreeVarsInValAreInGamma x gamma ->\n  x_expr = JFIValToJFVal x ->\n  JFISemanticallyImplies gamma s\n    (JFIHoare (JFIEq x JFINull) (JFInvoke x_expr mn vs)\n     NPE_mode v JFITrue) CC.\nProof.\n  intros gamma s x x_expr mn vs v CC.\n  intros x_in_gamma x_expr_val env this h gamma_match_env h_satisfies_s.\n  intros x_is_null.\n  simpl in x_is_null.\n  destruct (JFIExistsValToLoc x x_expr h gamma env this) as (l & x_is_l & x_subst_eq); trivial.\n  exists [(h, [ [] [[ JFIExprSubstituteEnv env this (JFInvoke x_expr mn vs) ]]_ None])],\n    h, NPE_mode, (JFLoc NPE_object_loc).\n  simpl.\n  split; try split; try split; trivial.\n  simpl.\n  unfold JFIValToLoc in x_is_null, x_is_l.\n  rewrite x_subst_eq.\n  destruct l.\n  destruct x; try discriminate x_is_null; try easy.\n  destruct x; try easy.\n  now rewrite x_is_l in x_is_null.\nQed.\nHint Resolve HTNullInvokeSoundness : core.\n\nLemma ValToLocImpliesSubstitute : forall v env this n,\n  JFIValToLoc v env this = Some (JFLoc n) ->\n  JFIValSubstituteEnv env this (JFIValToJFVal v) = JFVLoc (JFLoc n).\nProof.\n  intros v env this n v_to_loc.\n  destruct v; try discriminate v_to_loc; simpl in *.\n  + injection v_to_loc as n_eq.\n    now rewrite ValEnvSubstitutionSubstitutesThis, n_eq.\n  + now rewrite ValEnvSubstitutionReplacesVarInEnv with (l := (JFLoc n)).\nQed.\n\n(* TODO substitute this in p' *)\nLemma ParamsSubstitutionPreservesHeapSatisfying : forall h method vs p' env this params_env n CC,\n  JFIHeapSatisfiesInEnv h (JFITermSubstituteVals (params_of_md method) vs p') env this CC <->\n  JFIHeapSatisfiesInEnv h p' params_env n CC.\nProof.\nAdmitted.\n\nLemma SubstMethodWithParamsEnv : forall method params_env env this vs_expr n,\n  substList (map JFVar (params_of_md method)) (map (JFIValSubstituteEnv env this) vs_expr)\n                 (substExpr JFThis (JFLoc n) (body_of_md method)) =\n  Some (JFIExprSubstituteEnv params_env n (body_of_md method)).\nProof.\nAdmitted.\n\nLemma InvokeBodyEq : forall h n cn mn params_env env this vs_expr method CC,\n  getClassName h n = Some cn ->\n  methodLookup CC cn mn = Some method ->\n  getInvokeBody CC (getClassName h n) n mn (map (JFIValSubstituteEnv env this) vs_expr) h [] [] =\n  Some (h, [ [] [[JFIExprSubstituteEnv params_env n (body_of_md method) ]]_ None;\n             [] [[JFInvoke (JFVLoc (JFLoc n)) mn (map (JFIValSubstituteEnv env this) vs_expr) ]]_ None]).\nProof.\n  intros h n cn mn params_env env this vs_expr method CC.\n  intros class_name mn_method.\n  unfold getInvokeBody.\n  rewrite class_name, mn_method.\n  rewrite SubstMethodWithParamsEnv with (params_env := params_env); try easy.\nAdmitted.\n\nLemma HTInvokeRetSoundness : forall cn method rettypeCN ex w gamma s p q u v v_expr vs vs_expr mn decls invariants CC,\n  FreeVarsInValAreInGamma v gamma ->\n  v_expr = JFIValToJFVal v ->\n  vs_expr = JFIValsToJFVals vs ->\n  JFIValType decls gamma v = Some cn ->\n  methodLookup CC cn mn = Some method ->\n  fst (rettyp_of_md method) = JFClass rettypeCN ->\n  In (JFIInvariant cn mn p ex w q) invariants ->\n  JFISemanticallyImplies gamma (JFIAnd s p) (JFIImplies (JFIEq v JFINull) JFIFalse) CC ->\n  JFISemanticallyImplies gamma s (JFIHoare p (JFInvoke v_expr mn vs_expr) ex u q) CC.\nProof.\n  intros cn method rettypeCN ex w gamma s p q u v v_expr vs vs_expr mn decls invariants CC.\n  intros v_in_gamma v_expr_val vs_expr_val type_of_v mn_is_method ret_type_of_method in_invariants v_not_null.\n  intros env this h gamma_match_env h_satisfies_s h_satisfies_p.\n  unfold JFIEvalInEnv, JFIEval, JFIPartialEval.\n  fold JFIPartialEval.\n\n  set (params_env := StrMap.empty (Loc)). (* TODO new env for body *)\n  destruct (JFIExistsValToLoc v v_expr h gamma env this) as (l & x_is_l & x_subst_eq); trivial.\n  destruct l.\n    exfalso.\n    destruct (v_not_null env this h); try easy.\n    apply H.\n    simpl.\n    now rewrite x_is_l.\n  assert (hoare_body : JFIHeapSatisfiesInEnv h (JFIHoare p (body_of_md method) ex w q) params_env n CC).\n    admit. (* TODO invariant to Hoare *)\n  simpl in hoare_body.\n  destruct hoare_body as (confs & hn & res_ex & res & eval & ex_eq & hn_satisfies_q).\n    apply (ParamsSubstitutionPreservesHeapSatisfying h method vs p env this params_env n CC).\n    admit. (* TODO params env *)\n\n  rewrite ex_eq in *.\n  set (invoke_f := [ [] [[JFInvoke (JFIValSubstituteEnv env this v_expr) mn (map (JFIValSubstituteEnv env this) vs_expr) ]]_ None]).\n  destruct (ExistConfsExtendedBySt confs invoke_f) as (ext_confs & ext_confs_extended).\n\n  exists (((h, invoke_f)::ext_confs) ++ [(hn, ([] [[JFVal1 (JFVLoc res) ]]_ ex) :: invoke_f)]), hn, ex, res.\n  split; [ split; [ | split] | split]; try easy.\n  + unfold JFIEvalInEnv, JFIEval in eval.\n    simpl.\n    rewrite v_expr_val.\n    rewrite ValToLocImpliesSubstitute with (n := n); try easy.\n    unfold JFIEvalInEnv, JFIEval in eval.\n    rewrite InvokeBodyEq with (params_env := params_env) (cn := cn) (method := method); try easy.\n    ++ apply ExtendedStackEvaluationIsEvaluation\n          with (ext_st := invoke_f) (ext_confs := ext_confs) in eval; trivial.\n       simpl in eval.\n       apply EvaluationJoin with (h' := hn) (st' :=  (([] [[JFVal1 (JFVLoc res) ]]_ ex) :: invoke_f)); try easy.\n       +++ unfold invoke_f in eval |- *.\n           rewrite x_subst_eq in eval |- *.\n           apply eval.\n       +++ now destruct ex.\n    ++ admit. (* TODO type of v *)\n  + admit. (* TODO hn satisfies q *)\nAdmitted.\nHint Resolve HTInvokeRetSoundness : core.\n\nLemma HTThrowSoundness : forall decls gamma x x_expr cn s v CC,\n  FreeVarsInValAreInGamma x gamma ->\n  x_expr = JFIValToJFVal x ->\n  JFIValType decls gamma x = Some cn ->\n  JFISemanticallyImplies gamma s\n    (JFIHoare (JFIImplies (JFIEq x JFINull) JFIFalse) (JFThrow x_expr) \n     (Some cn) v (JFIEq (JFIVar v) x)) CC.\nProof.\n  intros decls gamma x x_expr cn s v CC.\n  intros x_in_gamma x_expr_val type_of_x.\n  intros env this h gamma_match_env h_satifsies_s.\n  intros x_not_null.\n  simpl in x_not_null.\n  destruct x_not_null as [x_not_null | x_null]; try destruct x_null.\n\n  destruct (JFIExistsValToLoc x x_expr h gamma env this) as (l & x_is_l & x_subst_eq); trivial.\n  rewrite x_is_l in x_not_null.\n  exists [(h, [ [] [[ JFIExprSubstituteEnv env this (JFThrow x_expr) ]]_ None])],\n    h, (Some cn), l.\n  simpl.\n  split; try split; try split; trivial.\n  + simpl.\n    rewrite x_subst_eq.\n    destruct l; try easy.\n    unfold class.\n    unfold JFIValType in type_of_x.\n    destruct x; try discriminate type_of_x.\n    ++ admit. (* TODO this type *)\n    ++ simpl in x_is_l.\n       rewrite <- StrMapFacts.find_mapsto_iff in type_of_x, x_is_l.\n       assert (type_of_n := (proj2 (gamma_match_env var)) (JFLoc n) cn type_of_x x_is_l).\n       unfold JFILocOfType in type_of_n.\n       destruct (Heap.find (elt:=Obj) n h); try destruct type_of_n.\n       destruct o.\n       now rewrite type_of_n.\n  + rewrite StrMapFacts.add_eq_o; trivial.\n    destruct x; try discriminate type_of_x.\n    ++ simpl in x_is_l |- *.\n       now injection x_is_l.\n    ++ simpl in x_is_l |- *.\n       destruct (Classical_Prop.classic (var = v)).\n       +++ rewrite StrMapFacts.add_eq_o; trivial; symmetry; trivial.\n       +++ rewrite StrMapFacts.add_neq_o; try (intros v_eq_x; symmetry in v_eq_x; destruct (H v_eq_x)).\n           now rewrite x_is_l.\nAdmitted.\nHint Resolve HTThrowSoundness : core.\n\nLemma HTNullThrowSoundness : forall gamma x x_expr s v CC,\n  FreeVarsInValAreInGamma x gamma ->\n  x_expr = JFIValToJFVal x -> \n  JFISemanticallyImplies gamma s\n    (JFIHoare (JFIEq x JFINull) (JFThrow x_expr)\n     NPE_mode v JFITrue) CC.\nProof.\n  intros gamma x x_expr s v CC.\n  intros x_in_gamma x_expr_val env this h gamma_match_env h_satifsies_s.\n  intros x_is_null.\n  simpl in x_is_null.\n  destruct (JFIExistsValToLoc x x_expr h gamma env this) as (l & x_is_l & x_subst_eq); trivial.\n  exists [(h, [ [] [[ JFIExprSubstituteEnv env this (JFThrow x_expr) ]]_ None])],\n    h, NPE_mode, (JFLoc NPE_object_loc).\n  simpl.\n  split; try split; try split; trivial.\n  + simpl.\n    unfold JFIValToLoc in x_is_null.\n    rewrite x_subst_eq.\n  destruct l.\n  destruct x; try discriminate x_is_null; try easy.\n  destruct x; try easy.\n  simpl in x_is_l.\n  now rewrite x_is_l in x_is_null.\nQed.\nHint Resolve HTNullThrowSoundness : core.\n\nLemma HTCatchNormalSoundness : forall gamma s p e1 mu ex x e2 u q CC,\n  JFISemanticallyImplies gamma s (JFIHoare p e1 None u q) CC ->\n  JFISemanticallyImplies gamma s (JFIHoare p (JFTry e1 mu ex x e2) None u q) CC.\nProof.\n  intros gamma s p e1 mu ex x e2 u q CC.\n  intros hoare_p_q.\n  intros env this h gamma_match_env h_satisfies_s.\n  intros h_satisfies_p.\n  assert (tmp := hoare_p_q env this h gamma_match_env h_satisfies_s h_satisfies_p).\n  fold JFIHeapSatisfiesInEnv in tmp.\n  destruct tmp as (e1_confs & hn & e1_ex & e1_res & e1_eval & e1_ex_eq & hn_satisfies_q).\n  rewrite e1_ex_eq in *.\n  destruct (TryEvaluationNormal h hn mu ex x e1 e2 e1_confs e1_res env this CC e1_eval)\n    as (try_confs & try_eval).\n  now exists try_confs, hn, None, e1_res.\nQed.\nHint Resolve HTCatchNormalSoundness : core.\n\nLemma HTCatchExSoundness : forall decls gamma s p e1 mu ex ex' ex'' x e2 u r q,\n  let CC := (JFIDeclsProg decls) in\n  JFITermPersistent s ->\n  JFIVarFreshInTerm x s ->\n  JFIVarFreshInTerm x r ->\n  Is_true (subtype_bool (JFIDeclsProg decls) (JFClass ex') (JFClass ex)) ->\n  JFISemanticallyImplies gamma s (JFIHoare p e1 (Some ex') x q) CC ->\n  JFISemanticallyImplies (JFIGammaAdd x ex gamma) s (JFIHoare q e2 ex'' u r) CC ->\n  JFISemanticallyImplies gamma s (JFIHoare p (JFTry e1 mu ex x e2) ex'' u r) CC.\nProof.\n  intros decls gamma s p e1 mu ex ex' ex'' x e2 u r q CC.\n  intros s_persistent x_fresh_in_s x_fresh_in_r is_subtype hoare_e1 hoare_e2.\n  intros env this h gamma_match_env h_satisfies_s.\n  intros h_satisfies_p.\n\n  assert (tmp := hoare_e1 env this h gamma_match_env h_satisfies_s h_satisfies_p).\n  fold JFIHeapSatisfiesInEnv in tmp.\n  destruct tmp as (e1_confs & h' & e1_ex & e1_res & e1_eval & e1_ex_is_none & h'_satisfies_q).\n  rewrite e1_ex_is_none in *; clear e1_ex_is_none.\n\n  assert (h'_gamma_match_env : JFIGammaMatchEnv h' (JFIGammaAdd x ex gamma) (StrMap.add x e1_res env)).\n    admit.\n\n  assert (h'_satisfies_s : JFIHeapSatisfiesInEnv h' s (StrMap.add x e1_res env) this CC).\n    apply EvaluationPreservesPersistentTerms with (h := h) (e := (JFIExprSubstituteEnv env this e1))\n    (confs := e1_confs) (ex := (Some ex')) (res := e1_res); trivial.\n    now apply AddingFreshVarPreservesHeapSatisfying.\n  assert (tmp := hoare_e2 (StrMap.add x e1_res env) this h' h'_gamma_match_env h'_satisfies_s h'_satisfies_q).\n  fold JFIHeapSatisfiesInEnv in tmp.\n  simpl in tmp.\n  destruct tmp as (e2_confs & hn & res_ex & res & e2_eval & res_ex_eq & hn_satisfies_r).\n  rewrite res_ex_eq in *; clear res_ex_eq.\n  destruct (TryEvaluationExCatch h h' hn mu ex' ex'' ex x e1 e2\n    e1_confs e2_confs e1_res res env this CC is_subtype e1_eval e2_eval) as (try_confs & try_eval).\n  exists try_confs, hn, ex'', res.\n  split; try split; try split; try easy.\n  now apply AddingFreshVarInsidePreservesHeapSatisfying with (x2 := x) (l2 := e1_res).\nAdmitted.\nHint Resolve HTCatchExSoundness : core.\n\nLemma HTCatchPassExSoundness : forall decls gamma s p e1 mu ex ex' x e2 u q,\n   let CC := (JFIDeclsProg decls) in\n  ~Is_true (subtype_bool (JFIDeclsProg decls) (JFClass ex') (JFClass ex)) ->\n   JFISemanticallyImplies gamma s (JFIHoare p e1 (Some ex') u q) CC ->\n   JFISemanticallyImplies gamma s (JFIHoare p (JFTry e1 mu ex x e2) (Some ex') u q) CC.\nProof.\n  intros decls gamma s p e1 mu ex ex' x e2 u q CC.\n  intros not_subtype hoare_p_q.\n  intros env this h gamma_match_env h_satisfies_s.\n  intros h_satisfies_p.\n  assert (tmp := hoare_p_q env this h gamma_match_env h_satisfies_s h_satisfies_p).\n  fold JFIHeapSatisfiesInEnv in tmp.\n  destruct tmp as (e1_confs & hn & e1_ex & e1_res & e1_eval & e1_ex_eq & hn_satisfies_q).\n  rewrite e1_ex_eq in *.\n  destruct (TryEvaluationExPass h hn mu ex' ex x e1 e2 e1_confs e1_res env this CC not_subtype e1_eval)\n    as (try_confs & try_eval).\n  now exists try_confs, hn, (Some ex'), e1_res.\nQed.\nHint Resolve HTCatchPassExSoundness : core.\n\n(* Soundness of weak rule *)\n\nDefinition EnvMapsToHeap env (h : Heap) := forall x l,\n  StrMap.MapsTo x l env -> LocMapsToHeap l h.\n\nDefinition FreeVarsInEnv t (env : JFITermEnv) := forall x,\n  VarFreeInTerm x t -> StrMap.In x env.\n\nDefinition ValInEnv x (env : JFITermEnv) :=\n  match x with\n  | JFIVar x => StrMap.In x env\n  | _ => True\n  end.\n\nLemma FreeVarsInEqThenValsInEnv : forall val1 val2 h env,\n  FreeVarsInTermAreInHeap (JFIEq val1 val2) h env ->\n  (ValInEnv val1 env /\\ ValInEnv val2 env).\nProof.\n  intros val1 val2 h env free_vars.\n  split.\n  + destruct val1; simpl; try easy.\n    destruct (free_vars var).\n    ++ now apply or_introl.\n    ++ apply StrMapFacts.elements_in_iff.\n       exists null.\n       now apply StrMapFacts.elements_mapsto_iff.\n    ++ apply StrMapFacts.elements_in_iff.\n       destruct H as (n & _ & var_n & _).\n       exists (JFLoc n).\n       now apply StrMapFacts.elements_mapsto_iff.\n  + destruct val2; simpl; try easy.\n    destruct (free_vars var).\n    ++ now apply or_intror.\n    ++ apply StrMapFacts.elements_in_iff.\n       exists null.\n       now apply StrMapFacts.elements_mapsto_iff.\n    ++ apply StrMapFacts.elements_in_iff.\n       destruct H as (n & _ & var_n & _).\n       exists (JFLoc n).\n       now apply StrMapFacts.elements_mapsto_iff.\nQed.\n\nLemma FreeVarsInFieldEqThenValsInEnv : forall obj field v h env,\n  FreeVarsInTermAreInHeap (JFIFieldEq obj field v) h env ->\n  (ValInEnv obj env /\\ ValInEnv v env).\nProof.\n  intros obj field v h env.\n  intros free_vars.\n  unfold FreeVarsInTermAreInHeap in free_vars.\n  unfold ValInEnv.\n  split.\n  + destruct obj; try easy; apply StrMapFacts.elements_in_iff.\n    destruct (free_vars var).\n    ++ now apply or_introl.\n    ++ exists null.\n       now apply StrMapFacts.elements_mapsto_iff.\n    ++ destruct H as (n & o & var_n & n_o).\n       exists (JFLoc n).\n       now apply StrMapFacts.elements_mapsto_iff.\n  + destruct v; try easy; apply StrMapFacts.elements_in_iff.\n    destruct (free_vars var).\n    ++ now apply or_intror.\n    ++ exists null.\n       now apply StrMapFacts.elements_mapsto_iff.\n    ++ destruct H as (n & o & var_n & n_o).\n       exists (JFLoc n).\n       now apply StrMapFacts.elements_mapsto_iff.\nQed.\n\nLemma SubenvValToLocEq : forall v env1 env2 this,\n  Subenv env1 env2 ->\n  ValInEnv v env1 ->\n  JFIValToLoc v env1 this = JFIValToLoc v env2 this.\nProof.\n  intros v env1 env2 this subenv v_env1.\n  destruct v as [ | | x ]; try easy.\n  simpl.\n  simpl in v_env1.\n  apply StrMapFacts.elements_in_iff in v_env1 as (l & x_l_env1).\n  apply StrMapFacts.elements_mapsto_iff in x_l_env1.\n  assert (x_l_env2 := subenv x l x_l_env1).\n  rewrite StrMapFacts.find_mapsto_iff in x_l_env1, x_l_env2.\n  now rewrite x_l_env1, x_l_env2.\nQed.\n\nLemma SubheapFieldEq : forall h1 h2 n f v,\n  JFISubheap h1 h2 ->\n  Heap.In n h1 ->\n  (JFIObjFieldEq (JFLoc n) f v h1 <-> JFIObjFieldEq (JFLoc n) f v h2).\nProof.\n  intros h1 h2 l f v subheap n_in_h1.\n  unfold JFIObjFieldEq.\n  apply HeapFacts.elements_in_iff in n_in_h1 as (o & l_o_h1).\n  apply HeapFacts.elements_mapsto_iff in l_o_h1.\n  assert (l_o_h2 := subheap l o l_o_h1).\n  rewrite HeapFacts.find_mapsto_iff in l_o_h1, l_o_h2.\n  now rewrite l_o_h1, l_o_h2.\nQed.\n\nLemma FreeVarsInHoarePrecondition : forall t1 e ex v t2 h env,\n  FreeVarsInTermAreInHeap (JFIHoare t1 e ex v t2) h env ->\n  FreeVarsInTermAreInHeap t1 h env.\nProof.\n  intros t1 e ex v t2 h env.\n  intros free_vars_hoare.\n  intros x x_free_in_t1.\n  unfold FreeVarsInEnv in free_vars_hoare.\n  apply (free_vars_hoare x).\n  now apply or_introl.\nQed.\n\nDefinition ExtendingHeapPreservesTermSatisfying t := forall h1 env1 h2 h env this CC,\n  FreeVarsInTermAreInHeap t h1 env1 ->\n  Subenv env1 env ->\n  JFIDisjointUnion h1 h2 h ->\n  HeapEnvEquivalent h1 h env1 env this this t CC.\n\nLemma FreeVarsInHoareExpr : forall env h1 t1 e ex v t2,\n  FreeVarsInTermAreInHeap (JFIHoare t1 e ex v t2) h1 env ->\n  FreeVarsInExprAreInHeap e h1 env.\nProof.\n  intros env h1 t1 e ex v t2 free_vars.\n  intros x x_free.\n  destruct (free_vars x).\n  + now apply or_intror, or_introl.\n  + now apply or_introl.\n  + now apply or_intror.\nQed.\n\nLemma FreeVarsInSuperenvAreInHeap : forall e h env1 env,\n  FreeVarsInExprAreInHeap e h env1 ->\n  Subenv env1 env ->\n  FreeVarsInExprAreInHeap e h env.\nProof.\n  intros e h env1 env free_vars subenv.\n  intros x x_free.\n  destruct (free_vars x x_free).\n  + now apply or_introl, subenv.\n  + destruct H as (n & o & x_n & n_o).\n    apply or_intror.\n    exists n, o.\n    split; trivial.\n    now apply subenv.\nQed.\n\nLemma ExtendingHeapPreservesHoareSatisfying : forall t1 e ex v t2,\n  ExtendingHeapPreservesTermSatisfying t1 ->\n  ExtendingHeapPreservesTermSatisfying t2 ->\n  ExtendingHeapPreservesTermSatisfying (JFIHoare t1 e ex v t2).\nProof.\n  intros t1 e ex v t2.\n  intros IHt1 IHt2.\n  intros h1 env1 h2 h env this CC.\n  intros free_vars subenv union.\n  unfold HeapEnvEquivalent.\n  assert (t1_equivalent : HeapEnvEquivalent h1 h env1 env this this t1 CC).\n    apply IHt1 with (h2 := h2); try easy.\n    now apply FreeVarsInHoarePrecondition in free_vars.\n  split.\n  + admit. (* evaluation on extended heap *)\n  + intros h_satisfies_hoare h1_satisfies_t1.\n    simpl in *.\n    destruct h_satisfies_hoare as (confs & hn & res_ex & res & h_eval & ex_eq & hn_satisfies_t2).\n      unfold ExtendingHeapPreservesTermSatisfying, HeapEnvEquivalent in IHt1.\n      now apply t1_equivalent.\n    destruct (EvaluationDependsOnFreeVars h1 h2 (Heap.empty Obj) h h1 e confs hn res_ex res env this CC)\n      as (hn_base & confs1 & hn1_base & hn1 & res1 & pi &\n          pi_env & pi_res & res_in_base & pi_hn_base & union_hn & union_hn1 & h1_eval);\n        try easy.\n      admit. (* h1 consistent *)\n      admit. (* no hardcoded locs in e *)\n      apply FreeVarsInSuperenvAreInHeap with (env1 := env1); try easy.\n        now apply FreeVarsInHoareExpr in free_vars.\n    now apply DisjointUnionSymmetry, DisjointUnionIdentity.\n    exists confs1, hn1, res_ex, res1.\n    split; [ | split]; trivial.\n    ++ admit. (* eval on restricted env *)\n    ++ apply (IHt2 hn_base (StrMap.add v res env1) h2 hn (StrMap.add v res env) this CC)\n         in hn_satisfies_t2; try easy.\n       +++ apply (PermutationPreservesHeapSatisfying t2 hn_base hn1 (StrMap.add v res env1) (StrMap.add v res1 env1) this pi CC); try easy.\n           - now apply EqPermuted2 with (h2 := hn1_base), UnionWithEmptyEq, union_hn1.\n           - apply ExtendPermutedEnvs; try easy.\n             now apply SubenvPermuted with (env2 := env).\n       +++ admit. (* Free vars in t2 are in hn_base *)\n       +++ now apply ExtendingSubenv.\nAdmitted.\n\nLemma ExtendingHeapPreservesHeapSatisfying : forall t,\n  ExtendingHeapPreservesTermSatisfying t.\nProof.\n  intros t.\n  induction t; intros h1 env1 h2 h env this CC free_vars subenv union; eauto.\n  + admit. (* easy *)\n  + admit. (* easy *)\n  + admit. (* easy *)\n  + now apply ExtendingHeapPreservesHoareSatisfying with (h2 := h2).\n  + unfold HeapEnvEquivalent.\n    simpl.\n    rewrite !SubenvValToLocEq with (env1 := env1) (env2 := env); try easy;\n    now apply FreeVarsInEqThenValsInEnv in free_vars.\n  + destruct union as ((subheap_h1 & subheap_h2 & same_keys) & disjoint).\n    unfold HeapEnvEquivalent.\n    simpl.\n    rewrite <-!SubenvValToLocEq with (env1 := env1) (env2 := env); try easy.\n    destruct obj.\n    ++ now destruct (JFIValToLoc v env).\n    ++ replace (JFIValToLoc JFIThis env1 this) with (Some (JFLoc this)); try easy.\n       destruct (JFIValToLoc v env1 this); try easy.\n       apply SubheapFieldEq; try easy.\n       admit. (* TODO this in heap*)\n    ++ simpl.\n       destruct (Classical_Prop.classic (StrMap.In var env1)).\n       +++ apply StrMapFacts.elements_in_iff in H as (l & var_l).\n           apply StrMapFacts.elements_mapsto_iff, StrMapFacts.find_mapsto_iff in var_l.\n           rewrite var_l in *.\n\n           destruct (JFIValToLoc v env1); try easy.\n           destruct l; try easy.\n           apply SubheapFieldEq; try easy.\n           unfold FreeVarsInTermAreInHeap in free_vars.\n           destruct (free_vars var); try now apply or_introl.\n             now rewrite StrMapFacts.find_mapsto_iff, var_l in H.\n           destruct H as (n' & o & var_n & n_o).\n           rewrite StrMapFacts.find_mapsto_iff, var_l in var_n.\n           injection var_n as n_eq.\n           rewrite <-n_eq in n_o.\n           apply HeapFacts.elements_in_iff.\n           exists o.\n           now apply HeapFacts.elements_mapsto_iff.\n       +++ apply StrMapFacts.not_find_mapsto_iff in H.\n           now rewrite H.\n    ++ now apply FreeVarsInFieldEqThenValsInEnv in free_vars.\n    ++ now apply FreeVarsInFieldEqThenValsInEnv in free_vars.\n  + unfold HeapEnvEquivalent.\n    simpl.\n    split.\n    ++ intros (h11 & h12 & (h11_consistent & h12_consistent) & disjoint_union_h1 & h11_satisfies_t1 & h12_satisfies_t2).\n       destruct (ExistsUnion h11 h2) as (h11_h2 & union_h11_h2). admit.\n       destruct (ExistsUnion h12 h2) as (h12_h2 & union_h12_h2). admit.\n       exists h11_h2, h12.\n       split; [ | split; [ | split]].\n       +++ admit. (* TODO h2 consistent, union consistent *)\n       +++ admit.\n       +++ apply (IHt1 h11 env1 h2 h11_h2 env this CC); try easy.\n           - admit. (* TODO envs in sep *)\n           - split; try easy.\n             apply SubheapDisjoint with (h2 := h12) (h12 := h1); try easy.\n             now apply union.\n       +++ admit. (* TODO envs in sep *)\n    ++ admit.\n  + admit.\nAdmitted.\n\nLemma FreeVarsInGammaToFreeVarsInHeap : forall p gamma h env,\n  FreeVarsInTermAreInGamma p gamma ->\n  JFIGammaMatchEnv h gamma env ->\n  FreeVarsInTermAreInHeap p h env.\nProof.\n  intros p gamma h env.\n  intros free_vars gamma_match_env.\n  intros x x_free.\n  assert (x_in_gamma := free_vars x x_free).\n  destruct (gamma_match_env x) as (same_keys & matching_types).\n  assert (x_in_env := (proj1 same_keys) x_in_gamma).\n  apply StrMapFacts.elements_in_iff in x_in_env as (l & x_l).\n  apply StrMapFacts.elements_in_iff in x_in_gamma as (type & x_type).\n  rewrite <-StrMapFacts.elements_mapsto_iff in x_l, x_type.\n  destruct l.\n    now apply or_introl.\n  apply or_intror.\n  assert (n_of_type := matching_types (JFLoc n) type x_type x_l).\n  unfold JFILocOfType in n_of_type.\n  assert (exists o, Heap.find n h = Some o).\n    destruct (Heap.find n h); try now destruct n_of_type.\n    now exists o.\n  destruct H as (o & n_o).\n  apply HeapFacts.find_mapsto_iff in n_o.\n  now exists n, o.\nQed.\n\nLemma GammaMatchEnvImpliesEnvMapsToHeap : forall h gamma env,\n  JFIGammaMatchEnv h gamma env ->\n  EnvMapsToHeap env h.\nProof.\n  intros h gamma env gamma_match_env.\n  intros x l x_l.\n  unfold JFIGammaMatchEnv in gamma_match_env.\n  destruct (gamma_match_env x) as (same_keys & types_match).\n  clear gamma_match_env.\n  assert (x_in_gamma : StrMap.In x gamma).\n    apply same_keys.\n    apply StrMapFacts.elements_in_iff.\n    exists l.\n    now apply StrMapFacts.elements_mapsto_iff.\n  apply StrMapFacts.elements_in_iff in x_in_gamma as (cn & x_cn).\n  apply StrMapFacts.elements_mapsto_iff in x_cn.\n  assert (type_of_l := types_match l cn x_cn x_l).\n  unfold JFILocOfType in type_of_l.\n  destruct l; try easy.\n  apply HeapFacts.elements_in_iff.\n  assert (exists o, Heap.find n h = Some o).\n    destruct (Heap.find n h); try now destruct type_of_l.\n    now exists o.\n  destruct H as (o & n_o).\n  exists o.\n  now apply HeapFacts.elements_mapsto_iff, HeapFacts.find_mapsto_iff.\nQed.\n\nLemma WeakRuleSoundness : forall gamma p1 p2 CC,\n  FreeVarsInTermAreInGamma p1 gamma ->\n  JFISemanticallyImplies gamma (JFISep p1 p2) p1 CC.\nProof.\n  intros gamma p1 p2 CC.\n  intros free_vars_p1 env this h gamma_match_env h_satisfies_sep.\n  destruct h_satisfies_sep as (h1 & h2 & disjoint_union & h1_satisfies_p1 & h2_satisfies_p2).\n  apply (ExtendingHeapPreservesHeapSatisfying p1 h1 env h2 h env); try easy.\n  apply FreeVarsInGammaToFreeVarsInHeap with (gamma := gamma); try easy.\n  admit. (* TODO envs in sep *)\nAdmitted.\nHint Resolve WeakRuleSoundness : core.\n\n(* Soudness of outer terms *)\n\nLemma OuterExistsIntroRuleSoundness : forall x v type decls gamma p q CC,\n  (JFIValType decls gamma v = Some type) ->\n  (JFISemanticallyImpliesOuter gamma q\n                (JFIOuterTermSubstituteVal x v p) CC) ->\n   JFISemanticallyImpliesOuter gamma q (JFIExists type x p) CC.\nProof.\n  intros x v type decls gamma p q CC.\n  intros type_of_v q_implies_p.\n  intros env this h gamma_match_env h_satisfies_q.\n  simpl.\n  simpl in type_of_v.\n\n  destruct v as [ | | v].\n  + exists null.\n    now split.\n  + exists (JFLoc this).\n    split.\n    ++ admit. (* TODO this type *)\n    ++ unfold JFISemanticallyImplies in q_implies_p.\n       apply q_implies_p in h_satisfies_q; trivial.\n       now apply HeapSatisfiesSubstIffThisMovedToEnv.\n  + destruct (proj1 (gamma_match_env v)) as (gamma_implies_env & _).\n    assert (v_in_gamma : StrMap.In v gamma);\n      try (apply StrMap_in_find_iff; exists type; assumption).\n    apply gamma_implies_env in v_in_gamma.\n    apply StrMap_in_find_iff in v_in_gamma.\n    destruct v_in_gamma as (l & v_is_l).\n    exists l.\n    split.\n    ++ simpl in type_of_v.\n       rewrite <- StrMapFacts.find_mapsto_iff in type_of_v, v_is_l.\n       exact (proj2 (gamma_match_env v) l type type_of_v v_is_l).\n    ++ unfold JFISemanticallyImplies in q_implies_p.\n       apply (HeapSatisfiesSubstIffVarMovedToEnv h x v l p env this CC v_is_l).\n       now apply q_implies_p.\nAdmitted.\nHint Resolve OuterExistsIntroRuleSoundness : core.\n\nLemma OuterExistsElimRuleSoundness : forall gamma decls p q r type x,\n  let CC := JFIDeclsProg decls in\n  JFIVarFreshInOuterTerm x r ->\n  JFIVarFreshInOuterTerm x q ->\n  JFISemanticallyImpliesOuter gamma r (JFIExists type x p) CC ->\n  JFISemanticallyImpliesOuter (JFIGammaAdd x type gamma) (JFIOuterAnd r p) q CC ->\n  JFISemanticallyImpliesOuter gamma r q CC.\nProof.\n  intros gamma decls p q r type x CC.\n  intros x_fresh_in_r x_fresh_in_q r_implies_exists and_implies_q.\n  intros env this h gamma_match_env h_satisfies_r.\n  assert (h_satisfies_exists := r_implies_exists env this h gamma_match_env h_satisfies_r).\n  destruct h_satisfies_exists as (l & l_of_type & h_satisfies_p).\n  assert (h_satisfies_q := and_implies_q (StrMap.add x l env) this h).\n  apply AddingFreshVarPreservesHeapSatisfyingOuter with (x := x) (l := l); try assumption.\n  apply h_satisfies_q.\n  + apply ExtendedGammaMatchesExtendedEnv; assumption.\n  + simpl.\n    split; try easy.\n    apply AddingFreshVarPreservesHeapSatisfyingOuter; assumption.\nQed.\nHint Resolve OuterExistsElimRuleSoundness : core.\n\nLemma OuterAndIntroRuleSoundness : forall gamma p q r CC,\n  (JFISemanticallyImpliesOuter gamma r p CC) ->\n  (JFISemanticallyImpliesOuter gamma r q CC) ->\n   JFISemanticallyImpliesOuter gamma r (JFIOuterAnd p q) CC.\nProof.\n  intros gamma p q r CC.\n  intros r_implies_p r_implies_q.\n  intros env this h gamma_match_env h_satisfies_r.\n  simpl.\n  split.\n  + apply r_implies_p.\n    ++ exact gamma_match_env.\n    ++ exact h_satisfies_r.\n  + apply r_implies_q.\n    ++ exact gamma_match_env.\n    ++ exact h_satisfies_r.\nQed.\nHint Resolve OuterAndIntroRuleSoundness : core.\n\nLemma OuterAndElimRuleSoundness : forall gamma p q r CC,\n  (JFISemanticallyImpliesOuter gamma r (JFIOuterAnd p q) CC) ->\n   JFISemanticallyImpliesOuter gamma r p CC /\\ JFISemanticallyImpliesOuter gamma r q CC.\nProof.\n  intros gamma p q r CC.\n  intros r_implies_p_and_q.\n  split;\n  intros env this h gamma_match_env h_satisfies_r;\n  apply r_implies_p_and_q.\n  + exact gamma_match_env.\n  + exact h_satisfies_r.\n  + exact gamma_match_env.\n  + exact h_satisfies_r.\nQed.\n\nLemma OuterOrIntroRuleSoundness : forall gamma p q r CC,\n  (JFISemanticallyImpliesOuter gamma r p CC \\/ JFISemanticallyImpliesOuter gamma r q CC) ->\n   JFISemanticallyImpliesOuter gamma r (JFIOuterOr p q) CC.\nProof.\n  intros gamma p q r CC.\n  intros [r_implies_p | r_implies_q]; intros env this h gamma_match_env h_satisfies_r; simpl.\n  + apply or_introl.\n    now apply r_implies_p.\n  + apply or_intror.\n    now apply r_implies_q.\nQed.\n\nLemma OuterOrElimRuleSoundness : forall gamma p q r s CC,\n  (JFISemanticallyImpliesOuter gamma s (JFIOuterOr p q) CC) ->\n  (JFISemanticallyImpliesOuter gamma (JFIOuterAnd s p) r CC) ->\n  (JFISemanticallyImpliesOuter gamma (JFIOuterAnd s q) r CC) ->\n   JFISemanticallyImpliesOuter gamma s r CC.\nProof.\n  intros gamma p q r s CC.\n  intros s_implies_p_or_q s_and_p_implies_r s_and_q_implies_r.\n  intros env this h gamma_match_env h_satisfies_s.\n  set (p_or_q := s_implies_p_or_q env this h gamma_match_env h_satisfies_s).\n  destruct p_or_q as [h_satisfies_p | h_satisfies_q].\n  + apply (s_and_p_implies_r env this h gamma_match_env).\n    simpl.\n    exact (conj h_satisfies_s h_satisfies_p).\n  + apply (s_and_q_implies_r env this h gamma_match_env).\n    simpl.\n    exact (conj h_satisfies_s h_satisfies_q).\nQed.\nHint Resolve OuterOrElimRuleSoundness : core.\n\n(* =============== Main theorems =============== *)\n\nTheorem JFISoundness : forall gamma decls p t,\n  let CC := JFIDeclsProg decls in\n  (JFIProves decls gamma p t) ->\n   JFISemanticallyImplies gamma p t CC.\nProof.\n  intros gamma decls p t CC.\n  unfold CC in *.\n  intros proof.\n  induction proof.\n  (* JFIAsmRule *)\n  + apply AsmRuleSoundness.\n  (* JFITransRule *)\n  + now apply (TransRuleSoundness gamma p q r).\n  (* JFIEqReflRule*)\n  + now apply EqReflRuleSoundness.\n  (* JFIEqSymRule *)\n  + now apply EqSymRuleSoundness.\n  (* JFIFalseElimRule *)\n  + now apply FalseElimRuleSoundness.\n  (* JFITrueIntroRule *)\n  + now apply TrueIntroRuleSoundness.\n  (* JFIAndIntroRule *)\n  + now apply AndIntroRuleSoundness.\n  (* JFIAndElimLRule *)\n  + now apply AndElimRuleSoundness with (q := q).\n  (* JFIAndElimRRule *)\n  + now apply AndElimRuleSoundness with (p := p).\n  (* JFIOrIntroLRule *)\n  + now apply OrIntroRuleSoundness, or_introl.\n  (* JFIOrIntroRRule *)\n  + now apply OrIntroRuleSoundness, or_intror.\n  (* JFIOrElimRule *)\n  + now apply OrElimRuleSoundness with (gamma := gamma) (p := p) (q := q).\n  (* JFIImpliesIntroRule *)\n  + now apply ImpliesIntroRuleSoundness.\n  (* JFIImpliesElimRule *)\n  + now apply ImpliesElimRuleSoundness with (p := p).\n  (* JFIWeakRule *)\n  + eauto.\n  (* JFISepAssoc1Rule *)\n  + eauto.\n  (* JFISepAssoc2Rule *)\n  + eauto.\n  (* JFISepSymRule *)\n  + eauto.\n  (* JFISepIntroRule *)\n  + eauto.\n  (* JFISepIntroPersistentRule *)\n  + eauto.\n  (* JFIWandIntroRule *)\n  + eauto.\n  (* JFIWandElimRule *)\n  + eauto.\n  (* JFIHTFrameRule *)\n  + eauto.\n  (* JFIHTRetRule *)\n  + now apply HTRetRuleSoundness.\n  (* JFIHTCsqRule: *)\n  + eauto.\n  (* JFIHTDisjIntroRule *)\n  + eauto.\n  (* JFIHTEqRule1 *)\n  + eauto.\n  (* JFIHTEqRule2 *)\n  + eauto.\n  (* JFIHTNewNotNullRule *)\n  + eauto.\n  (* JFIHTNewFieldRule *)\n  + apply HTNewFieldRuleSoundness with (decls := decls) (objflds := objflds) (n := n); assumption.\n  (* JFIHTLetRule *)\n  + eauto.\n  (* JFIHTLetExRule *)\n  + eauto.\n  (* JFIHTFieldSetRule *)\n  + eauto.\n  (* JFINullHTFieldSetRule *)\n  + eauto.\n  (* JFIHTFieldGetRule *)\n  + admit. (* TODO *)\n  (* JFIHTNullFieldGetRule *)\n  + eauto.\n  (* JFIHTIfRule *)\n  + now apply HTIfRuleSoundness with (v1 := v1) (v2 := v2).\n  (* JFIHTInvokeRetRule *)\n  + eauto.\n  (* JFIHTNullInvokeRule *)\n  + eauto.\n  (* JFIHTThrowRule *)\n  + eauto.\n  (* JFIHTNullThrowRule *)\n  + eauto.\n  (* JFIHTCatchNormalRule *)\n  + eauto.\n  (* JFIHTCatchExRule *)\n  + eauto.\n  (* JFIHTCatchPassExRule *)\n  + eauto.\nAdmitted.\n\nTheorem JFIOuterSoundness : forall gamma decls p t,\n  let CC := JFIDeclsProg decls in\n  (JFIProvesOuter decls gamma p t) ->\n   JFISemanticallyImpliesOuter gamma p t CC.\nProof.\n  intros gamma decls p t CC.\n  unfold CC in *.\n  intros proof.\n  induction proof; eauto.\n  (* JFIInnerOuterRule *)\n  + now apply JFISoundness.\n  (* JFIAndElimLRule *)\n  + now apply OuterAndElimRuleSoundness with (q := q).\n  (* JFIAndElimRRule *)\n  + now apply OuterAndElimRuleSoundness with (p := p).\n  (* JFIOrIntroLRule *)\n  + now apply OuterOrIntroRuleSoundness, or_introl.\n  (* JFIOrIntroRRule *)\n  + now apply OuterOrIntroRuleSoundness, or_intror.\nQed.\n", "meta": {"author": "jbujak", "repo": "jafun", "sha": "4b9b2d21ba06e6a98c885c8bf2cc202f52595058", "save_path": "github-repos/coq/jbujak-jafun", "path": "github-repos/coq/jbujak-jafun/jafun-4b9b2d21ba06e6a98c885c8bf2cc202f52595058/JaIrisSoundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.23299508874818597}}
{"text": " (*\n\n  Copyright 2014 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  Ifnot, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export cvterm.\nRequire Export csubst.\nRequire Export computation3.\nRequire Export list. (* WTF!!*)\n\n\nDefinition mkcv_tnat {o} (vs : list NVar) : @CVTerm o vs := mk_cv vs mkc_tnat.\n\nDefinition mk_isl {o} (t : @NTerm o) := mk_ite t mk_btrue mk_bfalse.\n\nLemma wf_term_decide_iff {p} :\n  forall (a : @NTerm p) v1 b1 v2 b2,\n    (wf_term a\n     # wf_term b1\n     # wf_term b2)\n    <=> wf_term (mk_decide a v1 b1 v2 b2).\nProof.\n  introv; split; intro wf; repnd.\n  - allrw @wf_term_eq.\n    constructor; simpl; unfold num_bvars; simpl; auto.\n    sp; subst; constructor; auto.\n  - allrw @wf_term_eq.\n    inversion wf as [| | o l bwf e ]; subst.\n    generalize (bwf (nobnd a)) (bwf (bterm [v1] b1)) (bwf (bterm [v2] b2)); clear bwf; intros bwf1 bwf2 bwf3.\n    autodimp bwf1 hyp; autodimp bwf2 hyp; autodimp bwf3 hyp; try (complete (simpl; sp)).\n    inversion bwf1; subst.\n    inversion bwf2; subst.\n    inversion bwf3; subst; sp.\nQed.\n\nLemma isprog_vars_decide_iff {p} :\n  forall vs (a : @NTerm p) v1 a1 v2 a2,\n    isprog_vars vs (mk_decide a v1 a1 v2 a2)\n    <=> (isprog_vars vs a\n         # isprog_vars (v1 :: vs) a1\n         # isprog_vars (v2 :: vs) a2).\nProof.\n  introv; split; intro k; try (repnd; apply isprog_vars_decide); auto.\n  allrw @isprog_vars_eq; allsimpl.\n  allrw remove_nvars_nil_l.\n  allrw subvars_eq.\n  allrw app_nil_r.\n  allrw subset_app; repnd.\n  allrw <- @wf_term_eq.\n  apply wf_term_decide_iff in k; repnd.\n  allrw <- subvars_eq.\n  allrw subvars_remove_nvars.\n  allrw subvars_eq.\n  dands; auto.\n  - introv i; simpl.\n    apply k2 in i; allrw in_app_iff; allsimpl; sp.\n  - introv i; simpl.\n    apply k0 in i; allrw in_app_iff; allsimpl; sp.\nQed.\n\nLemma isprog_vars_ite {p} :\n  forall vs (a b c : @NTerm p),\n    (isprog_vars vs a # isprog_vars vs b # isprog_vars vs c)\n    <=> isprog_vars vs (mk_ite a b c).\nProof.\n  introv.\n  unfold mk_ite.\n  rw @isprog_vars_decide_iff.\n  allrw @isprog_vars_cons_newvar; sp.\nQed.\n\nLemma isprog_vars_ite_implies {p} :\n  forall vs (a b c : @NTerm p),\n    isprog_vars vs a\n    -> isprog_vars vs b\n    -> isprog_vars vs c\n    -> isprog_vars vs (mk_ite a b c).\nProof.\n  intros; apply isprog_vars_ite; sp.\nQed.\n\nDefinition mkcv_ite {p} (vs : list NVar) (a b c : @CVTerm p vs) :=\n  let (t1,x1) := a in\n  let (t2,x2) := b in\n  let (t3,x3) := c in\n  exist (isprog_vars vs)\n        (mk_ite t1 t2 t3)\n        (isprog_vars_ite_implies vs t1 t2 t3 x1 x2 x3).\n\nLemma isprog_vars_isl {o} :\n  forall vs (t : @NTerm o), isprog_vars vs (mk_isl t) <=> isprog_vars vs t.\nProof.\n  introv.\n  unfold mk_isl.\n  rw <- @isprog_vars_ite.\n  split; intro k; repnd; dands; eauto 3 with slow.\nQed.\n\nLemma isprog_isl {o} :\n  forall (t : @NTerm o),\n    isprog (mk_isl t) <=> isprog t.\nProof.\n  introv; unfold mk_isl.\n  rw @isprog_decide_iff.\n  split; intro k; repnd; dands; tcsp; eauto 3 with slow.\nQed.\n\nLemma implies_isprog_isl {o} :\n  forall (t : @NTerm o), isprog t -> isprog (mk_isl t).\nProof.\n  introv isp; apply isprog_isl; auto.\nQed.\n\nDefinition mkc_isl {o} (t : @CTerm o) : CTerm :=\n  let (a,x) := t in exist isprog (mk_isl a) (implies_isprog_isl a x).\n\nDefinition mk_assert {o} (t : @NTerm o) := mk_ite t mk_unit mk_void.\n\nLemma isprog_vars_unit {o} :\n  forall vs, @isprog_vars o vs mk_unit.\nProof.\n  introv; rw @isprog_vars_eq; simpl; dands; eauto 3 with slow.\nQed.\nHint Resolve isprog_vars_unit : slow.\n\nLemma isprog_assert {o} :\n  forall (t : @NTerm o),\n    isprog (mk_assert t) <=> isprog t.\nProof.\n  introv; unfold mk_assert.\n  rw @isprog_decide_iff.\n  split; intro k; repnd; dands; tcsp; eauto 3 with slow.\nQed.\n\nLemma implies_isprog_assert {o} :\n  forall (t : @NTerm o), isprog t -> isprog (mk_assert t).\nProof.\n  introv isp; apply isprog_assert; auto.\nQed.\n\nDefinition mkc_assert {o} (t : @CTerm o) : CTerm :=\n  let (a,x) := t in exist isprog (mk_assert a) (implies_isprog_assert a x).\n\nDefinition mkcv_prod {p} vs (A B : @CVTerm p vs) : CVTerm vs :=\n  let (a,x) := A in\n  let (b,y) := B in\n  exist (isprog_vars vs) (mk_prod a b) (isprog_vars_prod_implies vs a b x y).\n\nDefinition mkcv_less_than {o} (vs : list NVar) (t1 t2 : @CVTerm o vs) : CVTerm vs :=\n  let (a,x) := t1 in\n  let (b,y) := t2 in\n    exist (isprog_vars vs) (mk_less_than a b) (isprog_vars_less_than_implies a b vs x y).\n\nLemma mkc_natk_eq {o} :\n  forall (t : @CTerm o),\n    mkc_natk t\n    = mkc_set\n        mkc_int\n        nvarx\n        (mkcv_prod\n           [nvarx]\n           (mkcv_le [nvarx] (mkcv_zero [nvarx]) (mkc_var nvarx))\n           (mkcv_less_than [nvarx] (mkc_var nvarx) (mk_cv [nvarx] t))).\nProof.\n  introv.\n  destruct_cterms.\n  apply cterm_eq; simpl; auto.\n  unfold mk_natk.\n  rw @newvar_prog; auto.\nQed.\n\nLemma closed_if_isprog {o} :\n  forall (t : @NTerm o),\n    isprog t -> closed t.\nProof.\n  introv isp.\n  apply closed_if_program.\n  apply isprogram_eq; auto.\nQed.\nHint Resolve closed_if_isprog : slow.\n\nLemma mkcv_prod_substc {o} :\n  forall v (a b : @CVTerm o [v]) t,\n    alphaeqc\n      (substc t v (mkcv_prod [v] a b))\n      (mkc_prod (substc t v a) (substc t v b)).\nProof.\n  introv.\n  destruct_cterms.\n  unfold alphaeqc; simpl.\n  unfold subst.\n  repeat (rw @cl_lsubst_lsubst_aux; eauto 3 with slow).\n  simpl; fold_terms; rw memvar_singleton.\n  constructor; simpl; auto.\n  introv k.\n  repeat (destruct n; tcsp).\n  unfold selectbt; simpl.\n\n  pose proof (newvar_prog (lsubst_aux x0 [(v, x)])) as h.\n  autodimp h hyp.\n  { apply isprog_vars_nil_implies_isprog.\n    rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n    apply csubst.isprog_vars_lsubst; allsimpl; auto .\n    introv j; repndors; subst; tcsp.\n    apply isprogram_eq; auto. }\n  rw h.\n\n  boolvar.\n\n  { rw @lsubst_aux_trivial_cl_term in h; allsimpl;\n    [|apply disjoint_singleton_r; apply newvar_prop].\n    rw (lsubst_aux_trivial_cl_term x0 [(newvar x0,x)]); allsimpl;\n    [|apply disjoint_singleton_r; apply newvar_prop].\n    rw h; rw @lsubst_aux_nil; auto. }\n\n  { pose proof (ex_fresh_var (nvarx\n                                :: (newvar x0)\n                                :: (all_vars (lsubst_aux x0 [(v, x)]))\n                                ++ (all_vars (lsubst_aux x0 [(v, x)])))) as fv;\n    exrepnd; allsimpl; allrw in_app_iff.\n    allrw not_over_or; repnd; GC.\n    apply (al_bterm _ _ [v0]); allsimpl; auto.\n    { rw disjoint_singleton_l; allrw in_app_iff; allrw not_over_or; sp. }\n    unfold var_ren; simpl.\n\n    assert (free_vars (lsubst_aux x0 [(v, x)]) = []) as f.\n    { apply null_iff_nil.\n      apply closed_null_free_vars.\n      apply closed_if_isprog.\n      apply isprog_vars_nil_implies_isprog.\n      rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n      apply csubst.isprog_vars_lsubst; allsimpl; auto .\n      introv j; repndors; subst; tcsp.\n      apply isprogram_eq; auto. }\n\n    repeat (rw @lsubst_trivial4; simpl; auto);\n      allrw disjoint_singleton_l; try (rw f); simpl; tcsp;\n      introv j; repndors; tcsp; ginv; simpl;\n      apply disjoint_singleton_l; auto. }\nQed.\n\nLemma mkcv_fun_substc {o} :\n  forall v (a b : @CVTerm o [v]) t,\n    alphaeqc\n      (substc t v (mkcv_fun [v] a b))\n      (mkc_fun (substc t v a) (substc t v b)).\nProof.\n  introv.\n  destruct_cterms.\n  unfold alphaeqc; simpl.\n  unfold subst.\n  repeat (rw @cl_lsubst_lsubst_aux; eauto 3 with slow).\n  simpl; fold_terms; rw memvar_singleton.\n  constructor; simpl; auto.\n  introv k.\n  repeat (destruct n; tcsp).\n  unfold selectbt; simpl.\n\n  pose proof (newvar_prog (lsubst_aux x0 [(v, x)])) as h.\n  autodimp h hyp.\n  { apply isprog_vars_nil_implies_isprog.\n    rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n    apply csubst.isprog_vars_lsubst; allsimpl; auto .\n    introv j; repndors; subst; tcsp.\n    apply isprogram_eq; auto. }\n  rw h.\n\n  boolvar.\n\n  { rw @lsubst_aux_trivial_cl_term in h; allsimpl;\n    [|apply disjoint_singleton_r; apply newvar_prop].\n    rw (lsubst_aux_trivial_cl_term x0 [(newvar x0,x)]); allsimpl;\n    [|apply disjoint_singleton_r; apply newvar_prop].\n    rw h; rw @lsubst_aux_nil; auto. }\n\n  { pose proof (ex_fresh_var (nvarx\n                                :: (newvar x0)\n                                :: (all_vars (lsubst_aux x0 [(v, x)]))\n                                ++ (all_vars (lsubst_aux x0 [(v, x)])))) as fv;\n    exrepnd; allsimpl; allrw in_app_iff.\n    allrw not_over_or; repnd; GC.\n    apply (al_bterm _ _ [v0]); allsimpl; auto.\n    { rw disjoint_singleton_l; allrw in_app_iff; allrw not_over_or; sp. }\n    unfold var_ren; simpl.\n\n    assert (free_vars (lsubst_aux x0 [(v, x)]) = []) as f.\n    { apply null_iff_nil.\n      apply closed_null_free_vars.\n      apply closed_if_isprog.\n      apply isprog_vars_nil_implies_isprog.\n      rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow.\n      apply csubst.isprog_vars_lsubst; allsimpl; auto .\n      introv j; repndors; subst; tcsp.\n      apply isprogram_eq; auto. }\n\n    repeat (rw @lsubst_trivial4; simpl; auto);\n      allrw disjoint_singleton_l; try (rw f); simpl; tcsp;\n      introv j; repndors; tcsp; ginv; simpl;\n      apply disjoint_singleton_l; auto. }\nQed.\n\nDefinition mkcv_not {p} vs (t : @CVTerm p vs) : CVTerm vs :=\n  let (a,x) := t in\n    exist (isprog_vars vs) (mk_not a) (implies_isprog_vars_not vs a x).\n\nLemma mkcv_le_eq {o} :\n  forall vs (a b : @CVTerm o vs),\n    mkcv_le vs a b = mkcv_not vs (mkcv_less_than vs b a).\nProof.\n  introv.\n  destruct_cterms.\n  apply cvterm_eq; simpl; auto.\nQed.\n\nLemma mkc_not_eq {o} :\n  forall (a : @CTerm o),\n    mkc_not a = mkc_fun a mkc_void.\nProof.\n  introv.\n  destruct_cterms.\n  apply cterm_eq; simpl; auto.\nQed.\n\nDefinition mkcv_void {o} (vs : list NVar) : @CVTerm o vs := mk_cv vs mkc_void.\n\nLemma mkcv_not_eq {o} :\n  forall vs (a : @CVTerm o vs),\n    mkcv_not vs a = mkcv_fun vs a (mkcv_void vs).\nProof.\n  introv.\n  destruct_cterms.\n  apply cvterm_eq; simpl; auto.\nQed.\n\nLemma mkcv_not_substc {o} :\n  forall v a (t : @CTerm o),\n    substc t v (mkcv_not [v] a)\n    = mkc_not (substc t v a).\nProof.\n  introv.\n  rw @mkc_not_eq.\n  rw @mkcv_not_eq.\n\n  destruct_cterms.\n  apply cterm_eq; simpl.\n  repeat unfsubst; simpl; fold_terms.\n  allrw @sub_filter_nil_r.\n  repeat (rw memvar_singleton; boolvar; allsimpl; tcsp).\n  boolvar; tcsp.\nQed.\n\nDefinition mkcv_false {o} (vs : list NVar) : @CVTerm o vs := mk_cv vs mkc_false.\nDefinition mkcv_true {o} (vs : list NVar) : @CVTerm o vs := mk_cv vs mkc_true.\n\nLemma mkcv_less_than_eq {o} :\n  forall vs (a b : @CVTerm o vs),\n    mkcv_less_than vs a b = mkcv_less vs a b (mkcv_true vs) (mkcv_false vs).\nProof.\n  introv.\n  destruct_cterms.\n  apply cvterm_eq; simpl; auto.\nQed.\n\nLemma mkc_less_than_eq {o} :\n  forall a b : @CTerm o, mkc_less_than a b = mkc_less a b mkc_true mkc_false.\nProof.\n  introv.\n  destruct_cterms.\n  apply cterm_eq; simpl; sp.\nQed.\n\nLemma mkcv_less_substc {o} :\n  forall v a b c d (t : @CTerm o),\n    substc t v (mkcv_less [v] a b c d)\n    = mkc_less (substc t v a) (substc t v b) (substc t v c) (substc t v d).\nProof.\n  introv.\n  destruct_cterms.\n  apply cterm_eq; simpl.\n  repeat unfsubst.\nQed.\n\nLemma mkcv_true_substc {o} :\n  forall v (t : @CTerm o),\n    substc t v (mkcv_true [v])\n    = mkc_true.\nProof.\n  introv.\n  destruct_cterms.\n  apply cterm_eq; tcsp.\nQed.\n\nLemma mkcv_false_substc {o} :\n  forall v (t : @CTerm o),\n    substc t v (mkcv_false [v])\n    = mkc_false.\nProof.\n  introv.\n  destruct_cterms.\n  apply cterm_eq; simpl.\n  unfsubst; simpl.\n  allrw memvar_singleton; boolvar; simpl; tcsp.\n  boolvar; simpl; tcsp.\nQed.\n\nLemma mkcv_less_than_substc {o} :\n  forall v a b (c : @CTerm o),\n    substc c v (mkcv_less_than [v] a b)\n    = mkc_less_than (substc c v a) (substc c v b).\nProof.\n  introv.\n  rw @mkcv_less_than_eq.\n  rw @mkc_less_than_eq.\n  rw @mkcv_less_substc.\n  rw @mkcv_true_substc.\n  rw @mkcv_false_substc.\n  auto.\nQed.\n\nLemma mkcv_le_substc2 {o} :\n  forall v a b (c : @CTerm o),\n    substc c v (mkcv_le [v] a b)\n    = mkc_le (substc c v a) (substc c v b).\nProof.\n  introv.\n  rw @mkcv_le_eq.\n  rw @mkc_le_eq.\n  rw @mkcv_not_substc.\n  rw @mkcv_less_than_substc.\n  auto.\nQed.\n\nLemma mkc_zero_eq {o} :\n  @mkc_zero o = mkc_nat 0.\nProof.\n  apply cterm_eq; simpl; auto.\nQed.\n\nLemma mkc_nat_eq {o} :\n  forall n, @mkc_nat o n = mkc_integer (Z.of_nat n).\nProof.\n  introv.\n  apply cterm_eq; simpl; auto.\nQed.\n\nLemma isvalue_zero {o} : @isvalue o mk_zero.\nProof.\n  unfold mk_zero; eauto with slow.\nQed.\nHint Resolve isvalue_zero : slow.\n\nLemma iscvalue_zero {o} : @iscvalue o mkc_zero.\nProof.\n  unfold iscvalue; simpl; eauto 3 with slow.\nQed.\nHint Resolve iscvalue_zero : slow.\n\nLemma wf_fix_iff {p} :\n  forall a : @NTerm p, wf_term (mk_fix a) <=> wf_term a.\nProof.\n  introv; split; intro i.\n  - allrw @wf_term_eq.\n    inversion i as [| | o lnt k e]; subst; allsimpl.\n    generalize (k (nobnd a)); intros k1.\n    repeat (dest_imp k1 hyp).\n    inversion k1; subst; sp.\n  - apply wf_fix; auto.\nQed.\n\nLemma isprog_vars_fix {p} :\n  forall (a : @NTerm p) vs,\n    isprog_vars vs (mk_fix a) <=> isprog_vars vs a.\nProof.\n  introv.\n  repeat (rw @isprog_vars_eq; simpl).\n  repeat (rw @remove_nvars_nil_l).\n  rw @app_nil_r.\n  allrw <- @wf_term_eq.\n  allrw @wf_fix_iff; split; sp.\nQed.\n\nLemma isprog_vars_fix_implies {p} :\n  forall (a : @NTerm p) vs,\n    isprog_vars vs a\n    -> isprog_vars vs (mk_fix a).\nProof.\n  introv ispa.\n  apply isprog_vars_fix; sp.\nQed.\n\nDefinition mkcv_fix {p} vs (t : @CVTerm p vs) : CVTerm vs :=\n  let (a,x) := t in\n    exist (isprog_vars vs) (mk_fix a) (isprog_vars_fix_implies a vs x).\n\nDefinition mkc_vbot {p} v : @CTerm p := mkc_fix (mkc_lam v (mkc_var v)).\n\nLemma isprog_get_cterm {o} :\n  forall (t : @CTerm o), isprog (get_cterm t).\nProof.\n  introv; destruct_cterms; auto.\nQed.\nHint Resolve isprog_get_cterm : slow.\n\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"./close/\")\n*** End:\n*)\n", "meta": {"author": "coq-contribs", "repo": "intuitionistic-nuprl", "sha": "6279ed83244dc4aec2e23ffb4c87e3f10a50326d", "save_path": "github-repos/coq/coq-contribs-intuitionistic-nuprl", "path": "github-repos/coq/coq-contribs-intuitionistic-nuprl/intuitionistic-nuprl-6279ed83244dc4aec2e23ffb4c87e3f10a50326d/cvterm2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2329014738176742}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\nRequire Import Setoid.\nRequire Import ZArith.\nRequire Import Psatz.\n\n\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith. \n\nLocal Open Scope struct_scope.\n\nRequire Import FinProof.CommonProofs.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolClass.\nRequire Import depoolContract.SolidityNotations.\n\nRequire Import depoolContract.NewProofs.ProofHelpers.\nRequire Import depoolContract.DePoolFunc.\n\n(* Set Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100. *)\n\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\nRequire Import depoolContract.Lib.CommonCommon.\n\n(* Require Import MultiSigWallet.Proofs.tvmFunctionsProofs. *)\n\nImport DePoolSpec.LedgerClass.SolidityNotations. \n\nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope solidity_scope.\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\n\nRequire Import depoolContract.DePoolConsts.\nModule DePoolContract_Ф__returnOrReinvest (dc : DePoolConstsTypesSig XTypesSig StateMonadSig).\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig dc.\nModule ProofHelpers := ProofHelpers dc.\n\nImport dc.\nImport ProofHelpers.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\nOpaque Z.eqb Z.add Z.sub Z.div Z.mul hmapLookup hmapInsert Z.ltb Z.geb Z.leb Z.gtb Z.modulo deleteListPair.\n\nDefinition DePoolContract_Ф__returnOrReinvest_while (Л_chunkSize Л_round1ValidatorsElectedFor: XInteger) : LedgerT (ErrorValue True XInteger) := \n    ( WhileE ( ( ↑17 D2! LocalState_ι__returnOrReinvest_Л_startIndex ?< $ Л_chunkSize ) !& \n    ( !¬ ( ( ↑17 D2! LocalState_ι__returnOrReinvest_Л_round2 ^^ RoundsBase_ι_Round_ι_stakes) ->empty ) ) ) \n do \n ( \n declareLocal {( Л_addr :>: XAddress , Л_stake :>: RoundsBase_ι_StakeValue )} := ( ↑17 U1! delMin LocalState_ι__returnOrReinvest_Л_round2 ^^ RoundsBase_ι_Round_ι_stakes ) (* ->get *) ; \n \n DePoolContract_Ф__returnOrReinvestForParticipant (!  \n          ↑17 D2! LocalState_ι__returnOrReinvest_Л_round2 , \n          ↑17 D2! LocalState_ι__returnOrReinvest_Л_round0 , \n          $ Л_addr , \n          $ Л_stake , \n          $ xBoolFalse , \n          $ Л_round1ValidatorsElectedFor !) >>= \n fun ea => xErrorMapDefaultF (fun a => (↑17 U1! {( LocalState_ι__returnOrReinvest_Л_round0 , LocalState_ι__returnOrReinvest_Л_round2 )} := $ a ) >> continue! (xValue I)) \n           ea (fun er => break! (xError er)))) >>= \n     fun r => return! (xProdSnd r).\n \n\nDefinition DePoolContract_Ф__returnOrReinvest_tailer ( Л_chunkSize Л_round1ValidatorsElectedFor: XInteger) : LedgerT (XErrorValue RoundsBase_ι_Round XInteger ) :=\n    do _ ← DePoolContract_Ф__returnOrReinvest_while Л_chunkSize Л_round1ValidatorsElectedFor ?; \n    ( RoundsBase_Ф_setRound0 (! ↑17 D2! LocalState_ι__returnOrReinvest_Л_round0 !) ) >> \n( If ( ( ↑17 D2! LocalState_ι__returnOrReinvest_Л_round2 ^^ RoundsBase_ι_Round_ι_stakes ) ->empty ) \nthen \n{ \n   (↑17 U1! LocalState_ι__returnOrReinvest_Л_round2 ^^ RoundsBase_ι_Round_ι_step := \n                      ξ$ RoundsBase_ι_RoundStepP_ι_Completed ) >> \n\n    this->sendMessage ( $ DePoolContract_Ф_ticktockF ) with {|| messageValue ::= $ DePool_ι_VALUE_FOR_SELF_CALL , \n                                       messageBounce ::= $ xBoolFalse||}  \n   } ) >> \nreturn!! ( ↑17 D2! LocalState_ι__returnOrReinvest_Л_round2 ) .\n\n\n\nDefinition DePoolContract_Ф__returnOrReinvest_header ( Л_round2 : RoundsBase_ι_Round ) ( Л_chunkSize : XInteger8 ) : LedgerT ( XErrorValue RoundsBase_ι_Round XInteger ) :=    \n\n( declareInit LocalState_ι__returnOrReinvest_Л_round2   := $ Л_round2 ) >> \ntvm_accept () >> \n( declareGlobal! LocalState_ι__returnOrReinvest_Л_round0 :>: RoundsBase_ι_Round := RoundsBase_Ф_getRound0 () ) >> \n U0! Л_round := ( RoundsBase_Ф_getRound1 () ) ; \n declareLocal Л_round1ValidatorsElectedFor :>: XInteger32 :=  $ Л_round ->> RoundsBase_ι_Round_ι_validatorsElectedFor ; \n( declareGlobal! LocalState_ι__returnOrReinvest_Л_startIndex :>: XInteger := $ xInt0 ) >> \nIf!! ( !¬ ( ↑17 D1! ( D2! LocalState_ι__returnOrReinvest_Л_round2 ) ^^ \n            RoundsBase_ι_Round_ι_isValidatorStakeCompleted ) ) \nthen \n{ \n  ( ↑17 U1! LocalState_ι__returnOrReinvest_Л_round2 ^^ \n        RoundsBase_ι_Round_ι_isValidatorStakeCompleted := $ xBoolTrue ) >> \n  declareLocal Л_optStake :>: (XMaybe RoundsBase_ι_StakeValue) := (D1! (↑17 D2! LocalState_ι__returnOrReinvest_Л_round2 ^^ \n                                                                           RoundsBase_ι_Round_ι_stakes) \n         ->fetch ( ↑2 D2! ValidatorBase_ι_m_validatorWallet ) ) ; \n   If! ( ( $ Л_optStake ) ->hasValue ) \n   then  \n   { \n    declareLocal Л_stake :>: RoundsBase_ι_StakeValue := ( $ Л_optStake ) ->get ; \n    ( ↑17 U1! LocalState_ι__returnOrReinvest_Л_startIndex := $ xInt1 ) >> \n    ( ↑↑17 U2! delete LocalState_ι__returnOrReinvest_Л_round2 ^^ \n             RoundsBase_ι_Round_ι_stakes [[ ↑2 D2! ValidatorBase_ι_m_validatorWallet ]] ) >> \n    U0! Л_rounds ?:= \n        DePoolContract_Ф__returnOrReinvestForParticipant (! \n         ↑17 D2! LocalState_ι__returnOrReinvest_Л_round2 , \n         ↑17 D2! LocalState_ι__returnOrReinvest_Л_round0 , \n         ↑2 D2! ValidatorBase_ι_m_validatorWallet , \n         $ Л_stake , \n         $ xBoolTrue , \n         $ Л_round1ValidatorsElectedFor !) ; \n( ↑17 U1! {( LocalState_ι__returnOrReinvest_Л_round0 , LocalState_ι__returnOrReinvest_Л_round2 )} := $ Л_rounds ) \n   } ; $ I \n} ;  DePoolContract_Ф__returnOrReinvest_tailer Л_chunkSize Л_round1ValidatorsElectedFor .\n\nLemma DePoolContract_Ф__returnOrReinvest_eq: \nDePoolContract_Ф__returnOrReinvest = DePoolContract_Ф__returnOrReinvest_header.\nProof.\n    unfold DePoolContract_Ф__returnOrReinvest.\n    unfold DePoolContract_Ф__returnOrReinvest_header.\n    unfold DePoolContract_Ф__returnOrReinvest_while.\n    auto.\nQed.\n\n\nOpaque DePoolContract_Ф__returnOrReinvest_while DePoolContract_Ф__returnOrReinvestForParticipant DePoolContract_Ф__returnOrReinvest_tailer.\n\nLemma DePoolContract_Ф__returnOrReinvest_header_exec : forall (Л_round2 : RoundsBase_ι_Round ) ( chunkSize : XInteger8 ) \n                                                        (l: Ledger) , \nlet round2 := Л_round2 in                                  \nlet la := exec_state tvm_accept l in\nlet round0 := eval_state (↓ RoundsBase_Ф_getRound0) la in\nlet round1 := eval_state (↓ RoundsBase_Ф_getRound1) la in\nlet round1ValidatorsElectedFor := round1 ->> RoundsBase_ι_Round_ι_validatorsElectedFor in\nlet if1 := negb (round2 ->> RoundsBase_ι_Round_ι_isValidatorStakeCompleted) in\nlet m_validatorWallet := eval_state (↑2 ε ValidatorBase_ι_m_validatorWallet) la in\nlet stakes :=  round2 ->> RoundsBase_ι_Round_ι_stakes in\nlet optStake := stakes ->fetch m_validatorWallet in\nlet if2 := isSome optStake in\nlet stake := maybeGet optStake in \nlet startIndex := if if1 then if if2 then 1 else 0 else 0 in\nlet stakes := if if1 then if if2 then stakes ->delete m_validatorWallet else stakes else stakes in\nlet round2 := if if1 then if if2 then \n            {$round2 with (RoundsBase_ι_Round_ι_isValidatorStakeCompleted, true);\n                          (RoundsBase_ι_Round_ι_stakes, stakes) $} else \n            {$round2 with (RoundsBase_ι_Round_ι_isValidatorStakeCompleted, true) $} else\n            round2 in                                     \nlet newl := {$la With (LocalState_ι__returnOrReinvest_Л_round2, round2);\n                      (LocalState_ι__returnOrReinvest_Л_round0, round0);\n                      (LocalState_ι__returnOrReinvest_Л_startIndex, startIndex)  $} in\n                      \nlet (erounds, newl) := if if1 then \n                            if if2 then \n                            run (↓ DePoolContract_Ф__returnOrReinvestForParticipant round2 round0 m_validatorWallet stake true round1ValidatorsElectedFor) newl\n                            else (Value (round0, round2), newl)\n                      else (Value (round0, round2), newl) in \nlet ml1 := newl in                      \nlet bRounds := errorValueIsValue erounds in                      \nlet (round0, round2)  := errorMapDefault Datatypes.id erounds (round0, round2) in                     \nlet newl := {$newl With (LocalState_ι__returnOrReinvest_Л_round2, round2);\n                        (LocalState_ι__returnOrReinvest_Л_round0, round0) $} in \nlet (eWhile, newl) := run (DePoolContract_Ф__returnOrReinvest_tailer chunkSize round1ValidatorsElectedFor) newl   in\nlet bl := exec_state (DePoolContract_Ф__returnOrReinvest_tailer chunkSize round1ValidatorsElectedFor) {$la With (LocalState_ι__returnOrReinvest_Л_startIndex, 0);\n                                (LocalState_ι__returnOrReinvest_Л_round2, round2);\n                                (LocalState_ι__returnOrReinvest_Л_round0, round0)  $} in\nexec_state (DePoolContract_Ф__returnOrReinvest_header Л_round2 chunkSize) l =\nif if1 then \n    if if2 then \n        if bRounds then newl \n        else ml1\n    else bl      \nelse bl .\nProof.\n\n    intros.\n    destructLedger l. \n    compute. idtac.\n  \n    Time repeat destructIf_solve2. idtac.\n    all: try destructFunction6 DePoolContract_Ф__returnOrReinvestForParticipant; auto. idtac. \n    all: try case_eq x; intros; auto. idtac.\n    destructFunction2 DePoolContract_Ф__returnOrReinvest_tailer; auto. idtac. \n    case_eq x0; intros; auto. idtac.\n    destructFunction2 DePoolContract_Ф__returnOrReinvest_tailer; auto. idtac. \n    destructFunction2 DePoolContract_Ф__returnOrReinvest_tailer; auto. idtac. \n    destructFunction2 DePoolContract_Ф__returnOrReinvest_tailer; auto. \n\nQed.\n\n\nLemma DePoolContract_Ф__returnOrReinvest_header_eval : forall (Л_round2 : RoundsBase_ι_Round ) ( chunkSize : XInteger8 ) \n                                                        (l: Ledger) , \nlet round2 := Л_round2 in                                  \nlet la := exec_state tvm_accept l in\nlet round0 := eval_state (↓ RoundsBase_Ф_getRound0) la in\nlet round1 := eval_state (↓ RoundsBase_Ф_getRound1) la in\nlet round1ValidatorsElectedFor := round1 ->> RoundsBase_ι_Round_ι_validatorsElectedFor in\nlet if1 := negb (round2 ->> RoundsBase_ι_Round_ι_isValidatorStakeCompleted) in\nlet m_validatorWallet := eval_state (↑2 ε ValidatorBase_ι_m_validatorWallet) la in\nlet stakes :=  round2 ->> RoundsBase_ι_Round_ι_stakes in\nlet optStake := stakes ->fetch m_validatorWallet in\nlet if2 := isSome optStake in\nlet stake := maybeGet optStake in \nlet startIndex := if if1 then if if2 then 1 else 0 else 0 in\nlet stakes := if if1 then if if2 then stakes ->delete m_validatorWallet else stakes else stakes in\nlet round2 := if if1 then if if2 then \n            {$round2 with (RoundsBase_ι_Round_ι_isValidatorStakeCompleted, true);\n                          (RoundsBase_ι_Round_ι_stakes, stakes) $} else \n            {$round2 with (RoundsBase_ι_Round_ι_isValidatorStakeCompleted, true) $} else\n            round2 in                                     \nlet newl := {$la With (LocalState_ι__returnOrReinvest_Л_round2, round2);\n                      (LocalState_ι__returnOrReinvest_Л_round0, round0);\n                      (LocalState_ι__returnOrReinvest_Л_startIndex, startIndex)  $} in\n                      \nlet (erounds, newl) := if if1 then \n                            if if2 then \n                            run (↓ DePoolContract_Ф__returnOrReinvestForParticipant round2 round0 m_validatorWallet stake true round1ValidatorsElectedFor) newl\n                            else (Value (round0, round2), newl)\n                      else (Value (round0, round2), newl) in \nlet ml1 := newl in                      \nlet bRounds := errorValueIsValue erounds in                      \nlet (round0, round2)  := errorMapDefault Datatypes.id erounds (round0, round2) in                     \nlet newl := {$newl With (LocalState_ι__returnOrReinvest_Л_round2, round2);\n                        (LocalState_ι__returnOrReinvest_Л_round0, round0) $} in \nlet (eWhile, newl) := run (DePoolContract_Ф__returnOrReinvest_tailer chunkSize round1ValidatorsElectedFor) newl   in\nlet br := eval_state (DePoolContract_Ф__returnOrReinvest_tailer chunkSize round1ValidatorsElectedFor) {$la With (LocalState_ι__returnOrReinvest_Л_startIndex, 0);\n                                (LocalState_ι__returnOrReinvest_Л_round2, round2);\n                                (LocalState_ι__returnOrReinvest_Л_round0, round0)  $} in\n\neval_state (DePoolContract_Ф__returnOrReinvest_header Л_round2 chunkSize) l =\nif if1 then \n    if if2 then \n        if bRounds then eWhile \n        else errorMapDefaultF (fun _ => Value default) erounds (fun e => Error e)\n    else br   \nelse br .\nProof.\n\n    intros.\n    destructLedger l. \n    compute. idtac.\n  \n    Time repeat destructIf_solve2. idtac.\n    all: try destructFunction6 DePoolContract_Ф__returnOrReinvestForParticipant; auto. idtac. \n    all: try case_eq x; intros; auto. idtac.\n    destructFunction2 DePoolContract_Ф__returnOrReinvest_tailer; auto. idtac. \n    case_eq x0; intros; auto. idtac.\n    destructFunction2 DePoolContract_Ф__returnOrReinvest_tailer; auto. idtac. \n    destructFunction2 DePoolContract_Ф__returnOrReinvest_tailer; auto. idtac. \n    destructFunction2 DePoolContract_Ф__returnOrReinvest_tailer; auto. \n\nQed.\n\nTransparent DePoolContract_Ф__returnOrReinvest_tailer.\n\nLemma DePoolContract_Ф__returnOrReinvest_tailer_exec : forall (chunkSize round1ValidatorsElectedFor : XInteger8 ) \n                                                        (l: Ledger) ,\nlet (eWhile, newl) := run (DePoolContract_Ф__returnOrReinvest_while chunkSize round1ValidatorsElectedFor) l in \nlet bWhile := errorValueIsValue eWhile in    \nlet ml2 := newl in \nlet round0 := eval_state (↑17 ε LocalState_ι__returnOrReinvest_Л_round0) newl in\nlet round2 := eval_state (↑17 ε LocalState_ι__returnOrReinvest_Л_round2) newl in \nlet if3 : bool := xHMapIsNull (round2 ->> RoundsBase_ι_Round_ι_stakes)  in \n\nlet newl := exec_state (↓ RoundsBase_Ф_setRound0 round0) newl in \nlet round2 := if if3 then {$ round2 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_Completed) $}\n                     else round2 in \n\nlet oldMessages := VMState_ι_messages ( Ledger_ι_VMState newl ) in\nlet newMessage  := {| contractAddress :=  0 ;\n                      contractFunction := DePoolContract_Ф_ticktockF  ;\n                      contractMessage := {| messageValue :=  DePool_ι_VALUE_FOR_SELF_CALL ;\n                                            messageFlag  := 0 ; \n                                            messageBounce := false\n                                            |} |} in  \nlet newl := if if3 then {$newl With (LocalState_ι__returnOrReinvest_Л_round2, round2);\n                                    (VMState_ι_messages, newMessage :: oldMessages) $} else newl in                                                  \nexec_state (DePoolContract_Ф__returnOrReinvest_tailer chunkSize round1ValidatorsElectedFor) l = \nif bWhile then newl\nelse ml2.\nProof.       \n    \n    intros.\n    destructLedger l. \n    compute. idtac.\n  \n    Time repeat destructIf_solve2. idtac.\n    destructFunction2 DePoolContract_Ф__returnOrReinvest_while; auto. idtac. \n    case_eq x; intros; auto. idtac.\n    Time repeat destructIf_solve2. \n   \nQed.    \n\nLemma DePoolContract_Ф__returnOrReinvest_tailer_eval : forall (chunkSize round1ValidatorsElectedFor : XInteger8 ) \n                                                        (l: Ledger) ,\nlet (eWhile, newl) := run (DePoolContract_Ф__returnOrReinvest_while chunkSize round1ValidatorsElectedFor) l in \nlet bWhile := errorValueIsValue eWhile in    \nlet ml2 := newl in \nlet round0 := eval_state (↑17 ε LocalState_ι__returnOrReinvest_Л_round0) newl in\nlet round2 := eval_state (↑17 ε LocalState_ι__returnOrReinvest_Л_round2) newl in \nlet if3 : bool := xHMapIsNull (round2 ->> RoundsBase_ι_Round_ι_stakes)  in \n\nlet newl := exec_state (↓ RoundsBase_Ф_setRound0 round0) newl in \nlet round2 := if if3 then {$ round2 with (RoundsBase_ι_Round_ι_step, RoundsBase_ι_RoundStepP_ι_Completed) $}\n                     else round2 in \n\nlet oldMessages := VMState_ι_messages ( Ledger_ι_VMState newl ) in\nlet newMessage  := {| contractAddress :=  0 ;\n                      contractFunction := DePoolContract_Ф_ticktockF  ;\n                      contractMessage := {| messageValue :=  DePool_ι_VALUE_FOR_SELF_CALL ;\n                                            messageFlag  := 0 ; \n                                            messageBounce := false\n                                            |} |} in  \nlet newl := if if3 then {$newl With (LocalState_ι__returnOrReinvest_Л_round2, round2);\n                                    (VMState_ι_messages, newMessage :: oldMessages) $} else newl in                                                  \neval_state (DePoolContract_Ф__returnOrReinvest_tailer chunkSize round1ValidatorsElectedFor) l = \nif bWhile then Value round2\nelse errorMapDefaultF (fun _ => Value default) eWhile (fun e => Error e).\nProof.       \n    \n    intros.\n    destructLedger l. \n    compute. idtac.\n  \n    Time repeat destructIf_solve2. idtac.\n    destructFunction2 DePoolContract_Ф__returnOrReinvest_while; auto. idtac. \n    case_eq x; intros; auto. idtac.\n    Time repeat destructIf_solve2. \n   \nQed.    \n\n\nEnd DePoolContract_Ф__returnOrReinvest.", "meta": {"author": "Pruvendo", "repo": "depool_contract", "sha": "6afe23011d62f65921ac2493df691ab888ffeb95", "save_path": "github-repos/coq/Pruvendo-depool_contract", "path": "github-repos/coq/Pruvendo-depool_contract/depool_contract-6afe23011d62f65921ac2493df691ab888ffeb95/src/NewProofs/DePoolContract_returnOrReinvest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.23272249983200893}}
{"text": "From Categories Require Import Essentials.Notations.\nFrom Categories Require Import Essentials.Types.\nFrom Categories Require Import Essentials.Facts_Tactics.\nFrom Categories Require Import Category.Main.\nFrom Categories Require Import Functor.Main.\nFrom Categories Require Import Ext_Cons.Arrow.\nFrom Categories Require Import Basic_Cons.Terminal.\nFrom Categories Require Import Basic_Cons.Equalizer.\nFrom Categories Require Import Basic_Cons.Facts.Equalizer_Monic.\nFrom Categories Require Import Coq_Cats.Type_Cat.Card_Restriction.\nFrom Categories Require Import Archetypal.Discr.Discr Archetypal.Discr.NatFacts.\n\nFrom Categories Require Import Limits.GenProd_GenSum.\nFrom Categories Require Import Limits.Limit.\n\nLocal Open Scope functor_scope.\n\nSection GenProd_Eq_Complete.\n  Context {C : Category}.\n\n  Local Ltac ElimUnit := repeat match goal with [H : unit |- _] => destruct H end.\n\n  Section GenProd_Eq_Limits.\n    Context {J : Category}.\n\n    Context {OProd : ∀ (map : J → C), (Π map)%object}\n            {HProd : ∀ (map : (Arrow J) → C), (Π map)%object}\n            {Eqs : Has_Equalizers C}\n    .\n\n    Section Limits_Exist.\n      Context (D : J –≻ C).\n\n      Local Notation DTarg := (fun f => (D _o (Targ f))%object) (only parsing).\n      Local Notation DF := Discr_Func (only parsing).\n      Local Notation OPR := (OProd (D _o)%object) (only parsing).\n      Local Notation HPR := (HProd DTarg) (only parsing).\n\n      Program Definition Projs_Cone : Cone (DF DTarg) :=\n        {|\n          cone_apex := Const_Func 1 (OPR _o tt);\n          cone_edge := {|Trans := fun f => Trans (cone_edge OPR) (Targ f)|}\n        |}.\n\n      Definition Projs : (OPR –≻ HPR)%morphism :=\n        Trans (LRKE_morph_ex HPR Projs_Cone) tt.\n\n      Program Definition D_imgs_Cone : Cone (DF DTarg) :=\n        {|\n          cone_apex := Const_Func 1 (OPR _o tt);\n          cone_edge :=\n            {|\n              Trans :=\n                fun f =>\n                  (D _a (Arr f) ∘ (Trans (cone_edge OPR) (Orig f)))%morphism\n            |}\n        |}.\n\n      Definition D_imgs : (OPR –≻ HPR)%morphism :=\n        Trans (LRKE_morph_ex HPR D_imgs_Cone) tt.\n\n      Program Definition Lim_Cone : Cone D :=\n        {|\n          cone_apex := Const_Func 1 (Eqs _ _ Projs D_imgs);\n          cone_edge :=\n            {|Trans :=\n                fun d => ((Trans (cone_edge OPR) d)\n                         ∘ (equalizer_morph (Eqs _ _ Projs D_imgs)))%morphism\n            |}\n        |}.\n\n      Next Obligation.\n      Proof.\n        simpl_ids.\n        set (W :=\n               f_equal\n                 (fun t :\n                        (((Const_Func 1 (((OProd (D _o)) _o) tt)%object)\n                             ∘ (Functor_To_1_Cat (Discr_Cat (Arrow J))))\n                          –≻ (DF DTarg))%nattrans\n                  =>\n                    ((Trans t {|Arr := h|})\n                       ∘ (equalizer_morph (Eqs _ _ Projs D_imgs)))%morphism\n                 )\n                 (cone_morph_com (LRKE_morph_ex HPR D_imgs_Cone))\n            ).\n        set (W' :=\n               f_equal\n                 (fun t :\n                        (((Const_Func 1 (((OProd (D _o)) _o) tt)%object)\n                             ∘ (Functor_To_1_Cat (Discr_Cat (Arrow J))))\n                          –≻ (DF DTarg))%nattrans\n                  =>\n                    (Trans t {|Arr := h|}\n                           ∘ (equalizer_morph (Eqs _ _ Projs D_imgs)))%morphism\n                 )\n                 (cone_morph_com (LRKE_morph_ex HPR Projs_Cone))\n            ).\n        clearbody W W'.\n        rewrite (assoc_sym _ _ ((D _a) h)).\n        cbn in *.\n        fold D_imgs in W.\n        fold Projs in W'.\n        rewrite W'.\n        etransitivity; [|symmetry; apply W].\n        clear W W'.\n        repeat rewrite assoc.\n        apply (\n            f_equal\n              (fun f =>\n                 compose f\n                         (Trans\n                            (HProd (fun f : Arrow J => (D _o)%object (Targ f)))\n                            {| Arr := h |}\n                         )\n              )\n          ).\n        apply (\n            f_equal (\n                fun f =>\n                  compose f\n                          (((HProd (fun f : Arrow J =>\n                                      (D _o)%object (Targ f))) _a) tt)\n              )\n          ).\n        apply equalizer_morph_com.\n      Qed.        \n\n      Next Obligation.\n      Proof.\n        symmetry.\n        apply Lim_Cone_obligation_1.\n      Qed.\n\n      Section Every_Cone_Equalizes.\n        Context (Cn : Cone D).\n\n        Local Hint Extern 1 => progress cbn.\n\n        Program Definition Cone_to_DF_DCone : Cone (DF (D _o)%object) :=\n          {|\n            cone_apex := Cn;\n            cone_edge :=\n              @NatTrans_compose\n                _ _\n                (Cn ∘ (Functor_To_1_Cat (Discr_Cat J)))\n                (Discr_Func ((Cn ∘ (Functor_To_1_Cat J))%functor _o)%object) _\n                {|Trans := fun _ => id |} (Discretize (cone_edge Cn))\n          |}.\n\n        Definition From_Cone_to_OPR : (Cn –≻ OPR)%morphism :=\n          Trans (LRKE_morph_ex OPR Cone_to_DF_DCone) tt.\n\n        Program Definition Cone_to_DF_DTrag_Cone : Cone (DF DTarg) :=\n          {|\n            cone_apex := Cn;\n            cone_edge := {|Trans :=\n                             fun c => Trans (Discretize (cone_edge Cn)) (Targ c)|}\n          |}.\n\n        Program Definition Cone_Morph_From_Cone_to_DF_DTrag_Cone_to_HPR_1 :\n          Cone_Morph _ Cone_to_DF_DTrag_Cone HPR :=\n          {|\n            cone_morph :=\n              {|Trans :=\n                  fun f =>\n                    match f as u return (((Cn _o) u)%object –≻ (_ u))%morphism\n                    with\n                    | tt => (Projs ∘ From_Cone_to_OPR)%morphism\n                    end\n              |}\n          |}.\n\n        Next Obligation.\n        Proof.\n          ElimUnit.\n          do 2 rewrite From_Term_Cat.\n          auto.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          symmetry.\n          apply Cone_Morph_From_Cone_to_DF_DTrag_Cone_to_HPR_1_obligation_1.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          apply NatTrans_eq_simplify.\n          extensionality x; cbn.\n          unfold Projs, From_Cone_to_OPR.\n          set (H :=\n                 f_equal\n                   (fun w :\n                        ((Projs_Cone\n                            ∘ (Functor_To_1_Cat (Discr_Cat (Arrow J)))\n                         ) –≻ (DF DTarg))%nattrans\n                    =>\n                      (\n                        (Trans w x)\n                          ∘ (Trans\n                               (LRKE_morph_ex\n                                  (OProd (D _o)%object) Cone_to_DF_DCone) tt)\n                      )%morphism\n                   )\n                   (\n                     cone_morph_com\n                       (\n                         LRKE_morph_ex\n                           (HProd (fun f : Arrow J => (D _o)%object (Targ f)))\n                           Projs_Cone\n                       )\n                   )\n              );\n            clearbody H; cbn in H.\n          repeat rewrite assoc_sym in H.\n          repeat rewrite assoc_sym.\n          etransitivity; [|apply H]; clear H.\n          set (H :=\n                 f_equal\n                   (\n                     fun w :\n                         ((Cone_to_DF_DCone\n                             ∘ (Functor_To_1_Cat (Discr_Cat J))\n                          ) –≻ (DF (D _o)%object))%nattrans\n                     =>\n                       Trans w (Targ x)\n                   )\n                   (cone_morph_com (LRKE_morph_ex\n                                      (OProd (D _o)%object) Cone_to_DF_DCone))\n              ).\n          cbn in *.\n          rewrite From_Term_Cat in H; simpl_ids in H.\n          trivial.\n        Qed.\n\n        Program Definition Cone_Morph_From_Cone_to_DF_DTrag_Cone_to_HPR_2 :\n          Cone_Morph _ Cone_to_DF_DTrag_Cone HPR :=\n          {|\n            cone_morph :=\n              {|Trans :=\n                  fun f =>\n                    match f as u return (((Cn _o)%object u) –≻ (_ u))%morphism\n                    with\n                    | tt => (D_imgs ∘ From_Cone_to_OPR)%morphism\n                    end\n              |}\n          |}.\n\n        Next Obligation.\n        Proof.\n          ElimUnit.\n          do 2 rewrite From_Term_Cat; simpl_ids; trivial.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          symmetry.\n          apply Cone_Morph_From_Cone_to_DF_DTrag_Cone_to_HPR_2_obligation_1.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          apply NatTrans_eq_simplify.\n          extensionality x.\n          cbn.\n          unfold D_imgs, From_Cone_to_OPR.\n          set (H :=\n                 f_equal\n                   (\n                     fun w :\n                         ((D_imgs_Cone\n                             ∘ (Functor_To_1_Cat (Discr_Cat (Arrow J)))\n                          ) –≻ (DF DTarg))%nattrans\n                     =>\n                       (\n                         (Trans w x)\n                           ∘ (Trans\n                                (LRKE_morph_ex\n                                   (OProd (D _o)%object) Cone_to_DF_DCone)tt)\n                       )%morphism\n                   )\n                   (\n                     cone_morph_com\n                       (LRKE_morph_ex\n                          (HProd (fun f : Arrow J =>\n                                    (D _o)%object (Targ f))) D_imgs_Cone )\n                   )\n              );\n            clearbody H; cbn in H.\n          repeat rewrite assoc_sym in H.\n          repeat rewrite assoc_sym.\n          etransitivity; [|apply H]; clear H.\n          set (H :=\n                 f_equal\n                   (\n                     fun w :\n                         ((Cone_to_DF_DCone\n                             ∘ (Functor_To_1_Cat (Discr_Cat J))\n                          ) –≻ (DF (D _o)%object))%nattrans\n                     =>\n                       (((D _a) (Arr x)) ∘ (Trans w (Orig x)))%morphism\n                   )\n                   (cone_morph_com\n                      (LRKE_morph_ex (OProd (D _o)%object) Cone_to_DF_DCone))\n              );\n            clearbody H; cbn in H.\n          rewrite From_Term_Cat in H; simpl_ids in H.\n          repeat rewrite assoc_sym in H.\n          repeat rewrite assoc_sym.\n          etransitivity; [|apply H]; clear H.\n          cbn_rewrite <- (@Trans_com _ _ _ _ Cn).\n          rewrite From_Term_Cat; auto.\n        Qed.\n\n        Lemma From_Cone_to_Obj_Prod_Equalizes :\n          (Projs ∘ From_Cone_to_OPR = D_imgs ∘ From_Cone_to_OPR)%morphism.\n        Proof.\n          match goal with\n            [|- ?A = ?B] =>\n            change A with\n            (Trans Cone_Morph_From_Cone_to_DF_DTrag_Cone_to_HPR_1 tt);\n              change B with\n              (Trans Cone_Morph_From_Cone_to_DF_DTrag_Cone_to_HPR_2 tt)\n          end.\n          match goal with\n            [|- Trans ?A tt = Trans ?B tt] =>\n            assert (A = B) as Heq; [|rewrite Heq]; trivial\n          end.\n          apply (LRKE_morph_unique HPR).\n        Qed.\n\n        Definition From_Cone_to_Lim_Cone : (Cn –≻ Lim_Cone)%morphism :=\n          equalizer_morph_ex _  From_Cone_to_Obj_Prod_Equalizes.\n\n        Program Definition Cone_Morph_to_Lim_Cone : Cone_Morph D Cn Lim_Cone :=\n          {|\n            cone_morph :=\n              {|\n                Trans :=\n                  fun c =>\n                    match c as u return ((Cn _o u)%object –≻ _)%morphism with\n                      tt => From_Cone_to_Lim_Cone\n                    end\n              |}\n          |}.\n\n        Next Obligation.\n        Proof.\n          ElimUnit.\n          rewrite From_Term_Cat; auto.\n        Qed.\n\n        Next Obligation.\n          symmetry.\n          apply Cone_Morph_to_Lim_Cone_obligation_1.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          apply NatTrans_eq_simplify.\n          extensionality x.\n          unfold From_Cone_to_Lim_Cone.\n          cbn in *.\n          set (H :=\n                 equalizer_morph_ex_com\n                   (Eqs _ _ Projs D_imgs)\n                   From_Cone_to_Obj_Prod_Equalizes\n              );\n            clearbody H; cbn in H.\n          simpl_ids.\n          rewrite assoc.\n          match goal with\n            [|- _ = (?A ∘ ?B)%morphism] =>\n            replace B with From_Cone_to_OPR\n          end.\n          clear H.\n          unfold From_Cone_to_OPR.\n          set (H :=\n                 f_equal\n                   (\n                     fun w :\n                         ((Cone_to_DF_DCone ∘ (Functor_To_1_Cat (Discr_Cat J))\n                          ) –≻ (DF (D _o)%object))%nattrans\n                     =>\n                       Trans w x\n                   )\n                   (cone_morph_com (LRKE_morph_ex\n                                      (OProd (D _o)%object) Cone_to_DF_DCone))\n              ).\n          cbn in H.\n          rewrite From_Term_Cat in H; simpl_ids in H.\n          trivial.\n        Qed.\n\n      End Every_Cone_Equalizes.\n\n      Section Cone_Morph_to_Lim_Cone_Cone_Morph_to_OPR.\n        Context {Cn : Cone D} (h : Cone_Morph _ Cn Lim_Cone).\n\n        Program Definition Cone_Morph_to_Lim_Cone_Cone_Morph_to_OPR :\n          Cone_Morph _ (Cone_to_DF_DCone Cn) OPR :=\n          {|\n            cone_morph :=\n              {|\n                Trans :=\n                  fun c =>\n                    match c as u return\n                          (((Cn _o) u)\n                             –≻ (((OProd (D _o)) _o) u))%object%morphism\n                    with\n                    | tt => (equalizer_morph (Eqs _ _ Projs D_imgs)\n                                            ∘ Trans h tt)%morphism\n                    end\n              |}\n          |}.\n\n        Next Obligation.\n        Proof.\n          ElimUnit.\n          rewrite From_Term_Cat; auto.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          symmetry.\n          apply Cone_Morph_to_Lim_Cone_Cone_Morph_to_OPR_obligation_1.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          apply NatTrans_eq_simplify.\n          extensionality x.\n          cbn.\n          set (H :=\n                 f_equal\n                   (fun w : ((Cn ∘ (Functor_To_1_Cat J)) –≻ D)%nattrans =>\n                      Trans w x)\n                   (cone_morph_com h)\n              ).\n          cbn in H.\n          simpl_ids in H.\n          rewrite From_Term_Cat; simpl_ids.\n          rewrite assoc in H.\n          trivial.\n        Qed.\n\n      End Cone_Morph_to_Lim_Cone_Cone_Morph_to_OPR.\n\n      Local Notation CMCOPR :=\n        Cone_Morph_to_Lim_Cone_Cone_Morph_to_OPR (only parsing).\n\n      Program Definition Lim_Cone_is_Limit : Limit D :=\n        {|\n          LRKE := Lim_Cone;\n          LRKE_morph_ex := Cone_Morph_to_Lim_Cone\n        |}.\n\n      Next Obligation.\n      Proof.\n        set (H := LRKE_morph_unique\n                    (OProd (D _o)%object) _ (CMCOPR h) (CMCOPR h')).\n        apply (\n            f_equal\n              (fun w : ((Cone_to_DF_DCone Cn) –≻ (OProd (D _o)%object))%nattrans =>\n                 Trans w tt)\n          ) in H.\n        cbn in H.\n        apply NatTrans_eq_simplify.\n        extensionality x; destruct x.\n        apply (@mono_morphism_monomorphic\n                 _ _ _ (@Equalizer_Monic _ _ _ _ _ (Eqs _ _ Projs D_imgs))).\n        trivial.\n      Qed.\n\n    End Limits_Exist.\n  End GenProd_Eq_Limits.\n\n  Section Restricted_Limits.\n    Context (P : Card_Restriction)\n            {CHRP : ∀ (A : Type) (map : A → C), (P A) → (Π map)%object}\n            {HE : Has_Equalizers C}\n    .\n\n    Definition Restr_GenProd_Eq_Restr_Limits : Has_Restr_Limits C P :=\n      fun J D PJ PA =>\n        @Lim_Cone_is_Limit\n          J\n          (fun map => CHRP J map PJ)\n          (fun map => CHRP (Arrow J) map PA)\n          HE\n          D\n    .\n\n  End Restricted_Limits.\n\n  Section Complete.\n    Context {CHAP : ∀ (A : Type) (map : A → C), (Π map)%object}\n            {HE : Has_Equalizers C}.\n\n    Definition GenProd_Eq_Complete : Complete C :=\n      fun J =>\n        Local_to_Global_Right\n          _\n          _\n          (fun D => @Lim_Cone_is_Limit J (CHAP J) (CHAP (Arrow J)) HE D)\n    .\n\n  End Complete.\n\nEnd GenProd_Eq_Complete.\n\nSection GenSum_CoEq_Complete.\n  Context {C : Category}.\n\n  Section GenSum_CoEq_CoLimits.\n    Context {J : Category}\n            {OSum : ∀ (map : J → C), (Σ map)%object}\n            {HSum : ∀ (map : (Arrow J) → C), (Σ map)%object}\n            {Eqs : Has_CoEqualizers C}\n    .\n\n    Section Limits_Exist.\n      Context (D : J –≻ C).\n\n      Program Definition CoLim_CoCone_is_CoLimit : CoLimit D :=\n        @Lim_Cone_is_Limit\n          (C^op)\n          (J^op)\n          (fun map => GenSum_to_GenProd (OSum map))\n          (fun map => GenSum_to_GenProd (GenSum_IsoType (Arrow_OP_Iso J) HSum map))\n          Eqs\n          (Opposite_Functor D)\n      .\n\n    End Limits_Exist.\n  End GenSum_CoEq_CoLimits.\n\n  Section Restricted_CoLimits.\n    Context (P : Card_Restriction)\n            {CHRP : ∀ (A : Type) (map : A → C), (P A) → (Σ map)%object}\n            {HE : Has_CoEqualizers C}\n    .\n\n    Definition Restr_GenSum_CoEq_Restr_CoLimits : Has_Restr_CoLimits C P :=\n      fun J D PJ PA =>\n        @CoLim_CoCone_is_CoLimit\n          J\n          (fun map => CHRP J map PJ)\n          (fun map => CHRP (Arrow J) map PA)\n          HE\n          D\n    .\n\n  End Restricted_CoLimits.\n\n  Section CoComplete.\n    Context {CHAP : ∀ (A : Type) (map : A → C), (Σ map)%object}\n            {HE : Has_CoEqualizers C}\n    .\n\n    Definition GenSum_CoEq_CoComplete : CoComplete C :=\n      fun J =>\n        Local_to_Global_Left\n          _\n          _\n          (fun D => @CoLim_CoCone_is_CoLimit J (CHAP J) (CHAP (Arrow J)) HE D)\n    .\n\n  End CoComplete.\n\nEnd GenSum_CoEq_Complete.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/Categories/Limits/GenProd_Eq_Limits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.23272248067283563}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, Collège de France and Inria Paris            *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU Lesser General Public License as        *)\n(*  published by the Free Software Foundation, either version 2.1 of   *)\n(*  the License, or  (at your option) any later version.               *)\n(*  This file is also distributed under the terms of the               *)\n(*  INRIA Non-Commercial License Agreement.                            *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Platform-specific built-in functions *)\n\nRequire Import String Coqlib.\nRequire Import AST Integers Floats Values.\nRequire Import Builtins0.\n\nInductive platform_builtin : Type :=\n  | BI_fmin\n  | BI_fmax.\n\nLocal Open Scope string_scope.\n\nDefinition platform_builtin_table : list (string * platform_builtin) :=\n     (\"__builtin_fmin\", BI_fmin)\n  :: (\"__builtin_fmax\", BI_fmax)\n  :: nil.\n\nDefinition platform_builtin_sig (b: platform_builtin) : signature :=\n  match b with\n  | BI_fmin | BI_fmax =>\n      mksignature (Tfloat :: Tfloat :: nil) Tfloat cc_default\n  end.\n\nDefinition platform_builtin_sem (b: platform_builtin) : builtin_sem (sig_res (platform_builtin_sig b)) :=\n  match b with\n  | BI_fmin =>\n      mkbuiltin_n2t Tfloat Tfloat Tfloat\n        (fun f1 f2 => match Float.compare f1 f2 with\n                      | Some Lt => f1\n                      | Some Eq | Some Gt | None => f2\n                      end)\n  | BI_fmax =>\n      mkbuiltin_n2t Tfloat Tfloat Tfloat\n        (fun f1 f2 => match Float.compare f1 f2 with\n                      | Some Gt => f1\n                      | Some Eq | Some Lt | None => f2\n                      end)\n  end.\n\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/x86/Builtins1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23269637200598775}}
{"text": "Require Import GMuAnnot.Prelude.\nRequire Import GMuAnnot.Infrastructure.\n\nOpen Scope list_scope.\n\n(* Proofs regarding proposition 2.1 from the paper *)\nSection SimpleEquationProperties.\n\n  Variable Σ : GADTEnv.\n\n  Lemma teq_reflexivity : forall Δ T,\n      entails_semantic Σ Δ (T ≡ T).\n    cbn.\n    intros.\n    auto.\n  Qed.\n\n  Lemma teq_symmetry : forall Δ T U,\n      entails_semantic Σ Δ (T ≡ U) ->\n      entails_semantic Σ Δ (U ≡ T).\n    cbn. intros.\n    symmetry.\n    auto.\n  Qed.\n\n  Lemma teq_transitivity : forall Δ T U V,\n      entails_semantic Σ Δ (T ≡ U) ->\n      entails_semantic Σ Δ (U ≡ V) ->\n      entails_semantic Σ Δ (T ≡ V).\n    cbn. intros.\n    transitivity (subst_tt' U Θ); auto.\n  Qed.\n\n  Lemma subst_has_no_fv : forall Σ Δ Θ,\n      subst_matches_typctx Σ Δ Θ ->\n      (forall X U, List.In (X, U) Θ -> fv_typ U = \\{}).\n    induction 1; introv Hin.\n    - false.\n    - cbn in Hin.\n      destruct Hin as [Hin | Hin].\n      + inversions Hin.\n        lets Hfv: wft_gives_fv H.\n        cbn in Hfv.\n        apply~ fset_extens.\n      + apply* IHsubst_matches_typctx.\n    - apply* IHsubst_matches_typctx.\n  Qed.\n\n  Lemma teq_axiom : forall Δ T U,\n      List.In (tc_eq (T ≡ U)) Δ ->\n      entails_semantic Σ Δ (T ≡ U).\n    unfold entails_semantic.\n    induction Δ; introv Hin M.\n    - contradiction.\n    - cbn in Hin.\n      destruct Hin as [Hin | Hin].\n      + subst. inversion M.\n        easy.\n      + inversion M; auto.\n        cbn.\n        repeat rewrite subst_tt_inside; auto.\n        * f_equal.\n          apply IHΔ; auto.\n        * introv Uin.\n          lets Fr: subst_has_no_fv Uin.\n          -- eauto.\n          -- rewrite Fr. apply notin_empty.\n        * introv Uin.\n          lets Fr: subst_has_no_fv Uin.\n          -- eauto.\n          -- rewrite Fr. apply notin_empty.\n  Qed.\n\nEnd SimpleEquationProperties.\n\nLtac fold_from_list :=\n  repeat progress match goal with\n  | [ H: context[LibList.fold_right (fun (x : var) (acc : fset var) => \\{ x} \\u acc) \\{} ?L]  |- _ ] =>\n    fold (from_list L) in H\n  | |- context[LibList.fold_right (fun (x : var) (acc : fset var) => \\{ x} \\u acc) \\{} ?L] =>\n    fold (from_list L)\n                  end.\n\nLemma notin_from_list : forall As (A : var),\n    ~ (List.In A As) ->\n    A \\notin from_list As.\n  intros.\n  intro HF.\n  lets [A' [Hin Heq]]: in_from_list HF.\n  subst.\n  auto.\nQed.\n\nLemma spawn_unit_subst : forall Σ As,\n    DistinctList As ->\n    exists Θ, length Θ = length As /\\ subst_matches_typctx Σ (tc_vars As) Θ /\\ substitution_sources Θ = from_list As.\n  induction As as [| Ah Ats]; introv ADist.\n  - cbn.\n    exists (@nil (var * typ)).\n    splits~.\n    constructor.\n  - inversions ADist.\n    destruct IHAts as [LT [Len [Match Src]]]; auto.\n    exists ((Ah, typ_unit) :: LT).\n    splits.\n    + cbn. auto.\n    + constructor;\n        fold (List.map tc_var Ats);\n        fold (tc_vars Ats);\n        auto.\n      * rewrite Src.\n        apply~ notin_from_list.\n      * apply notin_dom_tc_vars.\n        apply~ notin_from_list.\n    + cbn.\n      fold_from_list.\n      fold (substitution_sources LT).\n      rewrite Src.\n      trivial.\nQed.\n\nLemma only_vars_is_tc_vars : forall Δ,\n    (forall tc, List.In tc Δ -> exists A, tc = tc_var A) ->\n    exists As, Δ = tc_vars As.\n  induction Δ as [| [A | eq] Δt].\n  - cbn. intros. exists (@nil var). cbn. trivial.\n  - cbn. intro Hin.\n    lets* [Ats EQ]: IHΔt.\n    exists (A :: Ats). cbn.\n    fold (tc_vars Ats).\n    f_equal.\n    auto.\n  - cbn. intro Hin.\n    false~ Hin. congruence.\nQed.\n\nLemma contradictory_env_test_0 : forall Σ Δ,\n    entails_semantic Σ Δ (typ_unit ≡ (typ_unit ** typ_unit)) ->\n    contradictory_bounds Σ Δ.\n  introv Heq.\n  unfold contradictory_bounds.\n  intros.\n  unfold entails_semantic in *.\n  introv Hmatch.\n  exfalso.\n  lets HF: Heq Hmatch.\n  rewrite subst_ttΘ_fresh in HF.\n  - rewrite subst_ttΘ_fresh in HF.\n    + false.\n    + cbn. rewrite union_empty_r.\n      rewrite~ inter_empty_r.\n  - cbn.\n    rewrite~ inter_empty_r.\nQed.\n\nLemma subst_ttΘ_into_abs : forall Θ A B,\n    subst_tt' (A ==> B) Θ\n    =\n    (subst_tt' A Θ) ==> (subst_tt' B Θ).\n  induction Θ as [| [X T] Θ]; cbn in *; trivial.\nQed.\nLemma subst_ttΘ_into_tuple : forall Θ A B,\n    subst_tt' (A ** B) Θ\n    =\n    (subst_tt' A Θ) ** (subst_tt' B Θ).\n  induction Θ as [| [X T] Θ]; cbn in *; trivial.\nQed.\n\nLemma contradictory_env_test : forall Σ Δ A B C D,\n    entails_semantic Σ Δ ((A ==> B) ≡ (C ** D)) ->\n    contradictory_bounds Σ Δ.\n  introv Heq.\n  unfold contradictory_bounds.\n  intros.\n  unfold entails_semantic in *.\n  introv Hmatch.\n  exfalso.\n  lets HF: Heq Hmatch.\n  rewrite subst_ttΘ_into_abs in HF.\n  rewrite subst_ttΘ_into_tuple in HF.\n  congruence.\nQed.\n\nLemma empty_is_not_contradictory : forall Σ,\n    ~ (contradictory_bounds Σ emptyΔ).\n  intros.\n  intro HF.\n  unfold contradictory_bounds in HF.\n  asserts M: (subst_matches_typctx Σ emptyΔ (@nil (var*typ)));\n    try econstructor.\n  lets F: HF typ_unit (typ_unit ** typ_unit) (@nil (var * typ)) M.\n  cbn in F.\n  false.\nQed.\n\nLemma typing_exfalso : forall Σ Δ E e T1 T2 TT,\n    {Σ, Δ, E} ⊢(TT) e ∈ T1 ->\n    contradictory_bounds Σ Δ ->\n    wft Σ Δ T2 ->\n    {Σ, Δ, E} ⊢(Tgen) e ∈ T2.\n  introv Typ Bounds.\n  eapply typing_eq; eauto.\nQed.\n\nLemma inversion_typing_eq : forall Σ Δ E e T TT,\n    {Σ, Δ, E} ⊢(TT) e ∈ T ->\n    exists T',\n      {Σ, Δ, E} ⊢(Treg) e ∈ T' /\\ entails_semantic Σ Δ (T ≡ T').\n  introv Htyp.\n  lets Htyp2: Htyp.\n  induction Htyp;\n    try match goal with\n        | [ H: {Σ, Δ, E} ⊢(Treg) ?e ∈ ?T |- _ ] =>\n          exists T; split~; auto using teq_reflexivity\n        end.\n  lets [T' [IHTyp IHeq]]: IHHtyp Htyp.\n  exists T'.\n  split~.\n  eauto using teq_symmetry, teq_transitivity.\nQed.\n\nLemma subst_has_no_fv2 : forall Σ Δ Θ Y,\n    subst_matches_typctx Σ Δ Θ ->\n    (forall A U, List.In (A, U) Θ -> Y \\notin fv_typ U).\n  introv M Hin.\n  lets EQ: subst_has_no_fv M Hin.\n  rewrite EQ.\n  auto.\nQed.\n\nLemma inversion_eq_arrow : forall Σ Δ TA1 TB1 TA2 TB2,\n    entails_semantic Σ Δ ((TA1 ==> TB1) ≡ (TA2 ==> TB2)) ->\n    entails_semantic Σ Δ (TA1 ≡ TA2) /\\\n    entails_semantic Σ Δ (TB1 ≡ TB2).\n  introv Sem; cbn in *.\n  split~;\n       introv M;\n    lets EQ: Sem M;\n    repeat rewrite subst_tt_prime_reduce_arrow in EQ;\n    inversion~ EQ.\nQed.\n\nLemma inversion_eq_tuple : forall Σ Δ TA1 TB1 TA2 TB2,\n    entails_semantic Σ Δ ((TA1 ** TB1) ≡ (TA2 ** TB2)) ->\n    entails_semantic Σ Δ (TA1 ≡ TA2) /\\\n    entails_semantic Σ Δ (TB1 ≡ TB2).\n  introv Sem; cbn in *.\n  split~;\n       introv M;\n    lets EQ: Sem M;\n    repeat rewrite subst_tt_prime_reduce_tuple in EQ;\n    inversion~ EQ.\nQed.\n\nLemma inversion_eq_typ_all : forall Σ Δ T U,\n    entails_semantic Σ Δ (typ_all T ≡ typ_all U) ->\n    entails_semantic Σ Δ (T ≡ U).\n  introv Sem; cbn in *.\n  introv M;\n    lets EQ: Sem M;\n    repeat rewrite subst_tt_prime_reduce_typ_all in EQ;\n    inversion~ EQ.\nQed.\n\nLemma inversion_eq_typ_gadt : forall Σ Δ Ts Us N,\n    List.length Ts = List.length Us ->\n    entails_semantic Σ Δ (typ_gadt Ts N ≡ typ_gadt Us N) ->\n    List.Forall2 (fun T U => entails_semantic Σ Δ (T ≡ U)) Ts Us.\n  introv Len Sem.\n  apply F2_iff_In_zip.\n  split~.\n  intros T U In.\n  cbn in *.\n  introv M.\n  lets EQ: Sem M.\n  repeat rewrite subst_tt_prime_reduce_typ_gadt in EQ.\n  inversion EQ as [EQ2].\n  lets~ : lists_map_eq EQ2 In.\nQed.\n\nLemma equations_from_lists_map : forall F F1 F2 Ts Us,\n    List.length Ts = List.length Us ->\n    (forall T U, List.In (T,U) (zip Ts Us) -> F (tc_eq (T ≡ U)) = tc_eq (F1 T ≡ F2 U)) ->\n    List.map F (equations_from_lists Ts Us)\n    =\n    equations_from_lists (List.map F1 Ts) (List.map F2 Us).\n  induction Ts as [| T Ts]; destruct Us as [| U Us];\n    introv Len;  try solve [inversion~ Len].\n  introv EQ.\n  cbn.\n  fold (equations_from_lists Ts Us).\n  fold (equations_from_lists (List.map F1 Ts) (List.map F2 Us)).\n  f_equal.\n  - apply EQ. cbn. auto.\n  - apply* IHTs.\n    introv In.\n    apply EQ. cbn. auto.\nQed.\n", "meta": {"author": "radeusgd", "repo": "GADT-thesis", "sha": "18be642b1f9ef145c9fbc02f55eefb51d4bc1fdf", "save_path": "github-repos/coq/radeusgd-GADT-thesis", "path": "github-repos/coq/radeusgd-GADT-thesis/GADT-thesis-18be642b1f9ef145c9fbc02f55eefb51d4bc1fdf/lambda2Gmu_annotated/Equations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23269637200598775}}
{"text": "(*** Framework.v: Abstract framework where we prove non interference from unwindings lemmas *)\nRequire Export Wf_nat.\nRequire Export Omega.\nRequire Export Max.\nRequire Export Level.\nRequire Export cdr.\nRequire Export Axioms.\nRequire Export Tactics.\nRequire Import Setoid.\n\n Import L.\n\nSection A.\nVariable observable : L.t.\n\nVariable PC : Set.\nVariable Method : Type.\nVariable Kind: Set.\nVariable step : Method -> PC -> option PC -> Prop.\nVariable PM : Method -> Prop.\nVariable cdr : forall m, PM m -> CDR (step m).\nImplicit Arguments region.\n\nVariable Reg : Set.\n\nVariable Sign : Set.\n\nRecord SignedMethod : Type := SM {unSign:Method; sign:Sign}.\nCoercion unSign :  SignedMethod >-> Method.\n\nVariable istate rstate : Type.\nVariable exec : Method -> istate -> istate+rstate -> Prop.\n\nVariable pc : istate -> PC.\n\nNotation \"m |- p1 => p2\" := (step m p1 (Some p2)) (at level 30). \nNotation \"m |- p1 => \" := (step m p1 None) (at level 30).\nVariable exec_step_some : forall m s s',\n  PM m -> exec m (* kd *) s (inl _ s')-> m |- (pc s) => (pc s').\nVariable exec_step_none : forall m s s',\n  PM m -> exec m (* kd *) s (inr _ s')-> m |- (pc s) =>.\n\nVariable registertypes : Type.\n\nVariable texec : forall m, PM m ->\n      Sign -> (PC->L.t) -> PC ->\n      registertypes -> option registertypes -> Prop.\nVariable high_reg : registertypes -> Reg -> Prop.\nVariable indist_reg_val : istate -> istate -> Reg -> Prop.\nVariable indist_reg_val_trans : forall s1 s2 s3 r, \n  indist_reg_val s1 s2 r -> indist_reg_val s2 s3 r -> indist_reg_val s1 s3 r.\nVariable indist_reg_val_sym : forall s1 s2 r, \n  indist_reg_val s1 s2 r -> indist_reg_val s2 s1 r.\nInductive indist_reg : registertypes -> registertypes -> istate -> istate -> Reg -> Prop :=\n  | high_indist_reg : forall rt1 rt2 s1 s2 r,\n      high_reg rt1 r -> high_reg rt2 r -> indist_reg rt1 rt2 s1 s2 r\n  | low_indist_reg : forall rt1 rt2 s1 s2 r, indist_reg_val s1 s2 r -> indist_reg rt1 rt2 s1 s2 r.\nVariable indist : Sign -> registertypes -> registertypes -> istate -> istate -> Prop.\nVariable indist_from_reg : forall sgn rt1 rt2 s1 s2, \n  (forall r, indist_reg rt1 rt2 s1 s2 r) -> indist sgn rt1 rt2 s1 s2.\nVariable indist_reg_from_indist : forall sgn rt1 rt2 s1 s2,\n  indist sgn rt1 rt2 s1 s2 -> \n  forall r, \n    (high_reg rt1 r -> high_reg rt2 r -> indist_reg rt1 rt2 s1 s2 r) /\\ \n    ((~high_reg rt1 r /\\ ~high_reg rt2 r) \\/\n      (high_reg rt1 r /\\ ~high_reg rt2 r) \\/\n      (~high_reg rt1 r /\\ high_reg rt2 r) ->\n    indist_reg_val s1 s2 r).\nVariable rindist : Sign -> rstate -> rstate -> Prop.\nVariable indist_sym : forall m rt1 rt2 s1 s2,\n indist m rt1 rt2 s1 s2 -> indist m rt2 rt1 s2 s1.\nVariable rindist_sym : forall m s1 s2,\n rindist m s1 s2 -> rindist m s2 s1.\n\nVariable high_result : Sign -> rstate -> Prop.\n\nVariable rt0 : Method-> Sign -> registertypes.\nVariable init_pc : Method -> PC -> Prop.\n\nInductive evalsto (m:Method) : nat -> istate -> rstate -> Prop :=\n  | evalsto_res : forall (* k *) s res,\n      exec m (* k *) s (inr _ res) -> evalsto m 1 s res\n  | evalsto_intra : forall (* k *) n s1 s2 res,\n     exec m (* k *) s1 (inl _ s2) -> \n     evalsto m n s2 res ->\n     evalsto m (S n) s1 res.\n\nVariable P : SignedMethod -> Prop.\n\nVariable PM_P : forall m, P m -> PM m.\n\nDefinition ni :=\n  forall m p p' sgn s s' r r',\n  P (SM m sgn) ->\n(*   rt0 m sgn rt -> *)\n  indist sgn (rt0 m sgn) (rt0 m sgn) s s' ->\n  pc s = pc s' ->\n  init_pc m (pc s) ->\n  init_pc m (pc s') ->\n  evalsto m p s r ->\n  evalsto m p' s' r' ->\n  rindist sgn r r'.\n  \n  \n(* seems weird to have same rt *)\nVariable indist2_intra : forall m sgn se rt ut ut' s s' u u',\n  forall H0:P (SM m sgn), \n  indist sgn rt rt s s' ->\n  pc s = pc s' ->\n  exec m s (inl _ u) ->\n  exec m s' (inl _ u') ->\n  texec m (PM_P _ H0) sgn se (pc s) rt (Some ut) ->\n  texec m (PM_P _ H0) sgn se (pc s) rt (Some ut') ->\n    indist sgn ut ut' u u'.\n\nVariable indist2_return : forall m sgn se rt s s' u u',\n  forall H0:P (SM m sgn),\n  indist sgn rt rt s s' ->\n  pc s = pc s' ->\n  exec m s (inr _ u) -> \n  exec m s' (inr _ u')-> \n  texec m (PM_P _ H0) sgn se (pc s) rt None ->\n  texec m (PM_P _ H0) sgn se (pc s) rt None ->\n    rindist sgn u u'.\n\n(* high branching *)\nVariable soap2_basic_intra : forall m sgn se rt ut ut' s s' u u',\n  forall (h:P (SM m sgn)),\n  indist sgn rt rt s s' -> \n  pc s = pc s' ->\n  exec m s (inl _ u) -> \n  exec m s' (inl _ u') -> \n  texec m (PM_P _ h) sgn se (pc s) rt (Some ut) ->\n  texec m (PM_P _ h) sgn se (pc s) rt (Some ut') ->\n  pc u <> pc u' -> \n    (forall j:PC, (region (cdr m (PM_P _ h)) (pc s) j) -> ~ leql (se j) observable).\n\nVariable sub : registertypes -> registertypes -> Prop.\nVariable sub_simple : forall sgn rt rt' rt0 s s0,\n  indist sgn rt0 rt s0 s ->\n  sub rt rt' ->\n  indist sgn rt0 rt' s0 s.\n\nInductive typed_exec (m:Method) (H:PM m) (sgn:Sign) (se:PC->L.t) (RT:PC->registertypes) \n: istate -> istate + rstate -> Prop :=\n  typed_exec_def1 : forall s1 s2 rt',\n   exec m s1 (inl _ s2) ->\n   sub rt' (RT (pc s2)) ->\n   texec m H sgn se (pc s1) (RT (pc s1)) (Some rt') ->\n   typed_exec m H sgn se RT s1 (inl _ s2)\n| big_exec_def2 : forall s1 s2,\n   exec m s1 (inr _ s2) ->\n   texec m H sgn se (pc s1) (RT (pc s1)) None ->\n   typed_exec m H sgn se RT s1 (inr _ s2).\n\nInductive tevalsto (m:Method) (H:PM m) (sgn:Sign) (se:PC->L.t) (RT:PC->registertypes) : nat -> istate -> rstate -> Prop :=\n  | tevalsto_res : forall s res,\n      typed_exec m H sgn se RT s (inr _ res) -> tevalsto m H sgn se RT 1 s res\n  | tevalsto_intra : forall n s1 s2 res,\n     typed_exec m H sgn se RT s1 (inl _ s2) -> \n     tevalsto m H sgn se RT n s2 res ->\n     tevalsto m H sgn se RT (S n) s1 res.\n\n(* Hendra additional *)\nVariable tevalsto_high_result' : forall m sgn (H:PM m) se s RT res,\n  ~L.leql (se m sgn (pc s)) observable ->\n  exec m s (inr res) ->\n  texec m H sgn (se m sgn) (pc s) (RT m sgn (pc s)) None -> high_result sgn res.\n\nVariable tevalsto_diff_high_result : forall se RT m sgn s s' p res res' (H:PM m),\n  pc s = pc s' -> 1 < p ->\n  tevalsto m H sgn (se m sgn) (RT m sgn) 1 s res -> tevalsto m H sgn (se m sgn) (RT m sgn) p s' res' -> \n  high_result sgn res /\\ high_result sgn res'.\n\nVariable high_result_indist : forall sgn res res0,\n  high_result sgn res -> high_result sgn res0 -> rindist sgn res res0.\n\nVariable eq_map : registertypes -> registertypes -> Prop.\nVariable eq_map_refl : reflexive registertypes eq_map.\nVariable eq_map_sym : symmetric registertypes eq_map.\nVariable eq_map_trans : transitive registertypes eq_map.\nTheorem map_setoid: Setoid_Theory registertypes eq_map.\n split.\n exact eq_map_refl.\n exact eq_map_sym.\n exact eq_map_trans.\nQed.\nAdd Setoid registertypes eq_map map_setoid as eq_map_rel.\n\nVariable indist_morphism_proof : forall (y : Sign) (x y0 : registertypes),\neq_map x y0 ->\nforall x0 y1 : registertypes,\neq_map x0 y1 -> forall y2 y3 : istate, indist y x x0 y2 y3 <-> indist y y0 y1 y2 y3.\nAdd Morphism indist : indist_morphism. Proof. exact indist_morphism_proof. Qed.\n\nDefinition Typable (m:Method) (H:PM m) (sgn:Sign) (se:Method->Sign->PC->L.t) (RT:Method->Sign->PC->registertypes) : Prop :=\n  (forall i, init_pc m i -> eq_map (RT m sgn i) (rt0 m sgn)) /\\ \n  (forall i,\n     m |- i => ->\n     texec m H sgn (se m sgn) i (RT m sgn i) None) /\\\n  (forall i j,\n    m |- i =>j ->\n    exists rt,\n      texec m H sgn (se m sgn) i (RT m sgn i) (Some rt) \n      /\\ sub rt (RT m sgn j)).\n\nDefinition TypableProg se S := \n  forall m sgn (H:P (SM m sgn)), Typable m (PM_P _ H) sgn se S.\n\nLemma typable_evalsto : forall se RT m sgn n s r\n  (H:PM m),\n  Typable m H sgn se RT ->\n  evalsto m n s r -> \n  tevalsto m H sgn (se m sgn) (RT m sgn) n s r.\nProof.\n  intros until r; intros HP H.\n  destruct H as [_ [H0 H1]].\n  induction 1.\n  (* ret *)\n  constructor 1; auto.\n  constructor; auto.\n  apply H0; auto.\n  eapply exec_step_none; eauto.\n  (* next *)\n  constructor 2 with s2; auto.  \n  elim H1 with (pc s1) (pc s2).\n  intros st (HT,Hs).\n  constructor 1 with st; auto.\n  eapply exec_step_some; eauto.  \nQed.\n\nLemma tevalsto_evalsto : forall se RT m sgn p s r\n  (h:PM m),\n  tevalsto m h sgn (se m sgn) (RT m sgn) p s r ->\n  evalsto m p s r.\nProof.\n  induction 1.\n  inversion H. \n  constructor 1; auto.\n  inversion H.\n  constructor 2 with s2; auto. \nQed.\n\nLemma tevalsto_high_result : forall m sgn (H:PM m) se RT s res,\n  ~L.leql (se m sgn (pc s)) observable ->\n  tevalsto m H sgn (se m sgn) (RT m sgn) 1 s res -> high_result sgn res.\nProof.\n  intros.\n  apply tevalsto_high_result' with (m:=m) (H:=H) (sgn:=sgn) (se:=se) (s:=s) (RT:=RT); auto.\n  apply tevalsto_evalsto in H1. inversion H1; auto. inversion H4.\n  inversion H1; auto. inversion H2; auto. inversion H4.\nQed.\n\nImplicit Arguments tevalsto_evalsto.\n\nHint Resolve PM_P.\n\nSection TypableProg.\nVariable se : Method -> Sign -> PC -> L.t.\nVariable RT : Method -> Sign -> PC -> registertypes.\nVariable T : TypableProg se RT.\n\nDefinition high_region m (h:PM m) sgn (i:PC) := \n  forall j:PC, region (cdr m h) i j ->\n    ~ leql (se m sgn j) observable.\n\nHint Immediate indist_sym rindist_sym.\nHint Resolve exec_step_some exec_step_none.\n\nLemma final_bighighstep_aux : forall m sgn i p s res (H: P (SM m sgn)),\n  tevalsto m (PM_P _ H) sgn (se m sgn) (RT m sgn) p s res ->\n  region (cdr m (PM_P _ H)) i (pc s) ->\n  (forall jun, ~junc (cdr m (PM_P _ H)) i jun) ->\n  high_region m (PM_P _ H) sgn i ->\n  high_result sgn res.\nProof.\n  intros.\n  induction H0.\n  apply tevalsto_high_result with (m:=m) (H:=(PM_P _ H)) (se:=se) (RT:=RT) (s:=s); auto.\n    constructor 1; auto.\n  apply IHtevalsto; auto.\n  inversion H0.\n    eapply exec_step_some with (1:=PM_P _ H) in H6; eauto.\n    elim (soap2 (cdr m (PM_P _ H))) with i (pc s1) (pc s2); auto.\n    intros. unfold not in H2. apply H2 in H10. contradiction.\nQed.\n\nLemma final_bighighstep : forall m sgn p i s0 s res res0\n  (H:P (SM m sgn)),\n  pc s = pc s0 ->\n  evalsto m p s res-> \n  evalsto m 1 s0 res0 ->\n  region (cdr m (PM_P _ H)) i (pc s)-> \n  indist sgn (RT m sgn (pc s)) (RT m sgn (pc s0)) s s0 ->\n  high_region m (PM_P _ H) sgn i ->\n    rindist sgn res res0.\nProof.\n  intros.\n  inversion H2; try (inversion H8).\n  destruct (T m sgn H). inversion_mine H11.\n  apply high_result_indist.\n  (* high result res *)\n    apply final_bighighstep_aux with (m:=m) (i:=i) (p:=p) (s:=s) (H:=H); auto.\n    apply typable_evalsto; auto.\n    intros.\n    apply soap3 with (j:=pc s0).\n    rewrite <- H0; auto.\n    apply exec_step_none with (1:=PM_P _ H) in H6.\n    unfold result; eauto.\n  (* high result res0 *)\n    apply tevalsto_high_result with (m:=m) (H:=(PM_P _ H)) (se:=se) (RT:=RT) (s:=s0).\n        rewrite <- H0; auto.\n      apply typable_evalsto; auto.\nQed.\n\nLemma my_double_ind:forall P:(nat->nat->Prop),\n   (forall n m:nat, (forall p q:nat, lt p n -> lt q m -> P p q) -> P n m) -> \n   forall p q:nat, P p q.\nProof.\n  intros P0 H.\n  apply lt_wf_double_ind.\n  intros.\n  apply H.\n  intros.\n  apply H0.\n  assumption.\nQed.\n\nLemma execution_reach_junction_or_return_1 : forall m sgn ns i s res (H: P (SM m sgn)),\n  region (cdr m (PM_P _ H)) i (pc s) ->\n  evalsto m ns s res ->\n  (exists u, exists ps,\n    evalsto m ps u res /\\ ps < ns /\\\n    junc (cdr m (PM_P _ H)) i (pc u))\n  \\/ (forall jun, ~junc (cdr m (PM_P _ H)) i jun).\nProof.\n  intros m sgn ns.\n  pattern ns. apply lt_wf_ind.\n  clear ns; intros ns Hind; intros.  \n  inversion H1; auto.\n  right.\n  apply exec_step_none with (1:=PM_P _ H) in H2.\n  intros; apply soap3 with (k:=jun) in H0; auto.\n  elim (soap2 (cdr m (PM_P _ H))) with i (pc s) (pc s2); auto.\n  intros.\n  elim Hind with (m0:=n) (i:=i) (s:=s2) (res:=res) (H:=H); auto; try omega.\n  intros [U [ps [sH1 [sH2 sH3]]]].\n  left. exists U. exists ps. repeat (split; auto).\n  intros.\n  left. exists s2. exists n. repeat (split; auto).\n  apply exec_step_some with (1:=PM_P _ H) in H2; auto.\nQed.\n\nLemma execution_reach_junction_or_return_2 : forall m sgn ns ns' i s s' res res' (H: P (SM m sgn)),\n  region (cdr m (PM_P _ H)) i (pc s) ->\n  region (cdr m (PM_P _ H)) i (pc s') ->\n  evalsto m ns s res ->\n  evalsto m ns' s' res' ->\n  (exists u, exists u', exists ps, exists ps',\n    evalsto m ps u res /\\ ps < ns /\\\n    evalsto m ps' u' res' /\\ ps' < ns' /\\\n    junc (cdr m (PM_P _ H)) i (pc u) /\\ junc (cdr m (PM_P _ H)) i (pc u'))\n  \\/ (forall jun, ~junc (cdr m (PM_P _ H)) i jun).\nProof.\n    intros.\n  apply execution_reach_junction_or_return_1 with (sgn:=sgn) (i:=i) (H:=H) in H2; auto.\n  apply execution_reach_junction_or_return_1 with (sgn:=sgn) (i:=i) (H:=H) in H3; auto.\n  inversion H2; inversion H3; auto.\n  left.\n  inversion H4; inversion H6; inversion H5; inversion H8.\n  exists x; exists x1; exists x0; exists x2; auto.\n  Cleanexand.\n  repeat (split; auto).\nQed. \n\nLemma execution_reach_junction_or_return : forall m sgn ns ns' s s' u u' res res' (H: P (SM m sgn)),\n  pc s = pc s' ->  \n  exec m s (inl u) -> exec m s' (inl u') -> \n  pc u <> pc u' -> \n  evalsto m ns u res ->\n  evalsto m ns' u' res' ->\n  (exists v, exists v', exists ps, exists ps', \n    evalsto m ps v res /\\ ps <= ns /\\\n    evalsto m ps' v' res' /\\ ps' <= ns' /\\\n    junc (cdr m (PM_P _ H)) (pc s) (pc v) /\\ junc (cdr m (PM_P _ H)) (pc s') (pc v'))\n  \\/ (forall jun, ~junc (cdr m (PM_P _ H)) (pc s) jun /\\ forall jun, ~junc (cdr m (PM_P _ H)) (pc s') jun).\nProof.\n  intros.\n  apply exec_step_some with (1:=PM_P _ H) in H1; apply exec_step_some with (1:=PM_P _ H) in H2; auto.\n  elim (soap1 (cdr m (PM_P _ H))) with (pc s) (pc u) (pc u'); try (rewrite H0; auto; fail); auto; intros.\n  elim (soap1 (cdr m (PM_P _ H))) with (pc s) (pc u') (pc u); try (rewrite H0; auto; fail); auto; intros.\n  (* both are in the region *)\n  apply execution_reach_junction_or_return_2 with (ns:=ns) (ns':=ns') (s:=u) (s':=u') (res:=res) (res':=res') in H6; auto.\n  inversion H6.\n  left. \n  Cleanexand.\n  exists x; exists x0; exists x1; exists x2. repeat (split; auto). \n  omega. omega.\n  rewrite H0 in H13; auto. \n  right. split; auto. rewrite H0 in H8; auto.\n  (* one is in the region *)\n  apply execution_reach_junction_or_return_1 with (ns:=ns') (s:=u') (res:=res') in H6; auto.\n  inversion H6; Cleanexand.\n  left.\n  exists u; exists x; exists ns; exists x0; repeat (split; auto).\n  omega. rewrite H0 in H10; auto.\n  right. split; auto. rewrite H0 in H8; auto.\n  (* *)\n  elim (soap1 (cdr m (PM_P _ H))) with (pc s) (pc u') (pc u); try (rewrite H0; auto; fail); auto; intros.\n  (* one is in the region *)\n  apply execution_reach_junction_or_return_1 with (ns:=ns) (s:=u) (res:=res) in H7; auto.\n  inversion H7; Cleanexand.\n  left.\n  exists x; exists u'; exists x0; exists ns'; repeat (split; auto).\n  omega. rewrite H0 in H6; auto.\n  right. split; auto. rewrite H0 in H8; auto.\n  (* both are junction point *)\n  left. \n  exists u; exists u'; exists ns; exists ns'; repeat (split;auto).\n  rewrite H0 in H6; auto.\nQed.\n\nInductive path (m:Method) (i:istate) : istate -> Type :=\n  | path_base : forall j, exec m i (inl j) -> path m i j \n  | path_step : forall j k, path m k j -> exec m i (inl k) -> path m i j.\n\nInductive path_prop (m:Method) (i j:istate) (p:path m i j) : Prop := path_prop_cons : path_prop m i j p.\n\nInductive path_in_region (m:Method) (cdr: CDR (step m)) (s:PC) (i j:istate) : (path m i j) -> Prop :=\n  | path_in_reg_base : forall (Hexec:exec m i (inl j)), region cdr s (pc i) -> \n      path_in_region m cdr s i j (path_base m i j Hexec)\n  | path_in_reg_ind : forall k (Hexec:exec m i (inl k)) (p:path m k j), region cdr s (pc i) ->\n      path_in_region m cdr s k j p -> path_in_region m cdr s i j (path_step m i j k p Hexec).\n\nLemma evalsto_path : forall m sgn n s i res (H: P (SM m sgn)),\n  region (cdr m (PM_P _ H)) s (pc i) ->\n  evalsto m n i res ->\n  (exists j p, junc (cdr m (PM_P _ H)) s (pc j) /\\ path_prop m i j p /\\\n    path_in_region m (cdr m (PM_P _ H)) s i j p /\\\n    (exists n', evalsto m n' j res /\\ n' < n)) \n  \\/ (forall jun, ~junc (cdr m (PM_P _ H)) s jun).\nProof.\n  intros m sgn n. pattern n. apply lt_wf_ind.\n  clear n. intros n IH.\n  intros s i res H Hreg Hevalsto.\n  inversion Hevalsto.\n  (* the case where i is immediately a return point *)\n  apply exec_step_none with (1:=PM_P _ H) in H0.\n  right. intros. apply soap3 with (j:=pc i); auto.\n  (* inductive case *)\n  elim soap2 with PC (step m) (cdr m (PM_P _ H)) s (pc i) (pc s2); intros; auto.\n  (* path stays in region *)\n  elim IH with (H:=H) (s:=s) (m0:=n0) (i:=s2) (res:=res); simpl; intros; auto.\n  Cleanexand.\n  left. \n  exists x. exists (path_step m i x s2 x0 H0).\n  repeat (split; auto).\n  constructor 2; auto.\n  exists x1. split; auto.\n  omega.\n\n  (* path is the junction *) \n  left. exists s2. exists (path_base m i s2 H0).\n  repeat (split; auto).\n  constructor 1; auto. \n\n  (* final case *)\n  exists n0; repeat (split; auto).\n  apply exec_step_some with (1:=PM_P _ H); auto.\nQed.\n\nVariable changed : forall (m:Method) (i j:istate), path m i j -> Reg -> Prop.\nVariable changed_high : forall m sgn s i j r (H:P (SM m sgn)) (Hpath: path m i j), \n  (forall k:PC, region (cdr m (PM_P _ H)) s k -> ~ L.leql (se m sgn k) observable) ->\n  path_in_region m (cdr m (PM_P _ H)) s i j Hpath ->\n  region (cdr m (PM_P _ H)) s (pc i) ->\n  junc (cdr m (PM_P _ H)) s (pc j) ->\n  changed m i j Hpath r -> \n    high_reg (RT m sgn (pc j)) r.\nVariable not_changed_same : forall m sgn i j (Hpath: path m i j) r (H: P (SM m sgn)) ,\n  ~changed m i j Hpath r -> \n  (indist_reg_val i j r) /\\ (high_reg (RT m sgn (pc i)) r -> \n    high_reg (RT m sgn (pc j)) r). \nVariable high_reg_dec : forall rt r, high_reg rt r \\/ ~high_reg rt r.\nVariable changed_dec : forall m i j r (p:path m i j),\n  changed m i j (p) r \\/ ~changed m i j (p) r. \n\nLemma junction_indist : forall m sgn ns ns' s s' u u' res res' i (H: P (SM m sgn)),\n  indist sgn (RT m sgn (pc s)) (RT m sgn (pc s')) s s' ->\n  exec m s (inl u) -> exec m s' (inl u') ->\n  region (cdr m (PM_P _ H)) i (pc u) ->\n  region (cdr m (PM_P _ H)) i (pc u') ->\n  high_region m (PM_P _ H) sgn i ->\n  evalsto m ns u res ->\n  evalsto m ns' u' res' ->\n  indist sgn (RT m sgn (pc u)) (RT m sgn (pc u')) u u' ->\n  (exists v, exists v', exists ps, exists ps', \n    evalsto m ps v res /\\ ps <= ns /\\\n    evalsto m ps' v' res' /\\ ps' <= ns' /\\\n    junc (cdr m (PM_P _ H)) i (pc v) /\\ \n    junc (cdr m (PM_P _ H)) i (pc v') /\\\n    indist sgn (RT m sgn (pc v)) (RT m sgn (pc v')) v v')\n  \\/ (high_result sgn res /\\ high_result sgn res'). \nProof.\n  intros.\n  elim evalsto_path with (1:=H3) (2:=H6); \n  elim evalsto_path with (1:=H4) (2:=H7); intros.\n  left. destruct H10 as [v H10]; destruct H10 as [path H10]; destruct H9 as [v' H9]; destruct H9 as [path' H9].\n    exists v; exists v'.\n    Cleanexand.\n    exists x; exists x0. \n    repeat (split; auto).\n    omega. omega.\n    apply indist_from_reg.\n    intros.\n    elim changed_dec with (m:=m) (i:=u) (j:=v) (p:=path) (r:=r);\n    elim changed_dec with (m:=m) (i:=u') (j:=v') (p:=path') (r:=r); intros; auto.\n    apply changed_high with (m:=m) (sgn:=sgn) (s:=i) (H:=H) in H19; \n    apply changed_high with (m:=m) (sgn:=sgn) (s:=i) (H:=H) in H20; auto.\n    constructor; auto.\n    constructor 1; auto. \n    apply changed_high with (m:=m) (sgn:=sgn) (s:=i) (H:=H) in H20; auto.\n    apply changed_high with (m:=m) (sgn:=sgn) (s:=i) (H:=H) in H20; auto.\n    elim junc_func with (PC:=PC) (step:=step m) (c:=cdr m (PM_P _ H)) (i:=i) \n      (j1:=pc v) (j2:=pc v'); auto.\n    constructor 1; auto.\n    apply changed_high with (m:=m) (sgn:=sgn) (s:=i) (H:=H) in H19; auto.\n    elim junc_func with (PC:=PC) (step:=step m) (c:=cdr m (PM_P _ H)) (i:=i) \n      (j1:=pc v') (j2:=pc v); auto.\n    apply changed_high with (m:=m) (sgn:=sgn) (s:=i) (H:=H) in H19; auto.\n    apply not_changed_same with (m:=m) (sgn:=sgn) (i:=u') (j:=v') in H19; auto.\n    apply not_changed_same with (m:=m) (sgn:=sgn) (i:=u) (j:=v) in H20; auto.\n    inversion H19; inversion H20.\n    destruct high_reg_dec with (rt:=RT m sgn (pc u)) (r:=r);\n    destruct high_reg_dec with (rt:=RT m sgn (pc u')) (r:=r).\n    specialize H22 with (1:=H26); specialize H24 with (1:=H25).\n    constructor 1; auto.\n    specialize H24 with (1:=H25).\n    constructor 1; auto.\n    elim junc_func with (PC:=PC) (step:=step m) (c:=cdr m (PM_P _ H)) (i:=i) \n      (j1:=pc v) (j2:=pc v'); auto.\n    specialize H22 with (1:=H26).\n    elim junc_func with (PC:=PC) (step:=step m) (c:=cdr m (PM_P _ H)) (i:=i) \n      (j1:=pc v') (j2:=pc v); auto.\n    constructor 1; auto.\n    constructor 2; auto.\n    apply indist_reg_val_trans with (s2:=u).\n    apply indist_reg_val_sym; auto.\n    apply indist_reg_val_trans with (s2:=u'); auto.\n    apply indist_reg_from_indist with (r:=r) in H8.\n    Cleanexand.\n    apply H29; auto.\n  (* one of them doesn't have a junction point *)\n  Cleanexand. specialize H9 with (pc x). contradiction.\n  Cleanexand. specialize H10 with (pc x). contradiction.\n  (* both are junction points *)\n  right.\n  split.\n  apply typable_evalsto with (1:=T m sgn H) (se:=se) (RT:=RT) in H6. \n  apply final_bighighstep_aux with (m:=m) (sgn:=sgn) (H:=H) \n    (s:=u) (i:=i) (p:=ns); auto.\n  (* the other high result *)\n  apply typable_evalsto with (1:=T m sgn H) (se:=se) (RT:=RT) in H7. \n  apply final_bighighstep_aux with (m:=m) (sgn:=sgn) (H:=H) \n    (s:=u') (i:=i) (p:=ns'); auto.\nQed.\n\nLemma junction_indist_2 : forall m sgn ns ns' s s' u u' res res' i (H: P (SM m sgn)),\n  indist sgn (RT m sgn (pc s)) (RT m sgn (pc s')) s s' ->\n  exec m s (inl u) -> exec m s' (inl u') ->\n  region (cdr m (PM_P _ H)) i (pc u) ->\n  junc (cdr m (PM_P _ H)) i (pc u') ->\n  high_region m (PM_P _ H) sgn i ->\n  evalsto m ns u res ->\n  evalsto m ns' u' res' ->\n  indist sgn (RT m sgn (pc u)) (RT m sgn (pc u')) u u' ->\n  (exists v, exists ps, \n    evalsto m ps v res /\\ ps <= ns /\\\n    junc (cdr m (PM_P _ H)) i (pc v) /\\ \n    indist sgn (RT m sgn (pc v)) (RT m sgn (pc u')) v u').\nProof. \n  intros.\n  elim evalsto_path with (1:=H3) (2:=H6); intros.\n  destruct H9 as [v [Hpath H9]].\n  exists v.\n  Cleanexand.\n  exists x. repeat (split; auto).\n  omega.\n  apply indist_from_reg.\n  intro r.\n  elim changed_dec with (m:=m) (i:=u) (j:=v) (r:=r) (p:=Hpath); intros; auto.\n  constructor 1.\n  apply changed_high with (m:=m) (sgn:=sgn) (H:=H) (s:=i) in H14; auto.\n  apply changed_high with (m:=m) (sgn:=sgn) (H:=H) (s:=i) in H14; auto.\n  elim junc_func with (PC:=PC) (step:=step m) (c:=cdr m (PM_P _ H)) (i:=i) \n      (j1:=pc v) (j2:=pc u'); auto.\n  (* dealing with the value when it is not changed *)\n  apply not_changed_same with (m:=m) (sgn:=sgn) (i:=u) (j:=v) in H14; auto.\n  Cleanexand.\n  destruct high_reg_dec with (rt:=RT m sgn (pc u)) (r:=r);\n  destruct high_reg_dec with (rt:=RT m sgn (pc u')) (r:=r).\n  specialize H15 with (1:=H16).\n  constructor 1; auto.\n  constructor 1; auto.\n  elim junc_func with (PC:=PC) (step:=step m) (c:=cdr m (PM_P _ H)) (i:=i) \n    (j1:=pc v) (j2:=pc u'); auto.\n  constructor 1; auto.\n  elim junc_func with (PC:=PC) (step:=step m) (c:=cdr m (PM_P _ H)) (i:=i) \n    (j1:=pc u') (j2:=pc v); auto.\n  constructor 2; auto.\n  apply indist_reg_val_sym; auto.  \n  apply indist_reg_val_trans with (s2:=u).\n  apply indist_reg_from_indist with (r:=r) in H8.\n  Cleanexand. apply indist_reg_val_sym. apply H18; auto.\n  apply H14; auto.\n  specialize H9 with (pc u'); contradiction.\nQed. \n\nDefinition tni :=\n  forall m sgn p p' s s' r r' (H:P (SM m sgn)),\n  pc s = pc s' ->\n  indist sgn (RT m sgn (pc s)) (RT m sgn (pc s)) s s' ->\n  tevalsto m (PM_P _ H) sgn (se m sgn) (RT m sgn) p s r -> \n  tevalsto m (PM_P _ H) sgn (se m sgn) (RT m sgn) p' s' r' -> \n  rindist sgn r r'.\n\nLemma tni_ni : tni -> ni.\nProof.\n  unfold tni, ni; intros.\n  destruct (T _ _ H0) as [T1 [T2 T3]].\n  apply H with m p p' s s' H0; auto.\n  rewrite T1; auto.\n  apply typable_evalsto; auto.\n  apply typable_evalsto; auto.\nQed.\n\nVariable branch_indist : forall m sgn s s' u u' (H:P (SM m sgn)), \n  pc s = pc s' ->\n  indist sgn (RT m sgn (pc s)) (RT m sgn (pc s')) s s' ->\n  exec m s (inl u) ->\n  exec m s' (inl u') ->\n  pc u <> pc u' ->\n  indist sgn (RT m sgn (pc u)) (RT m sgn (pc u')) u u'.\n\nLemma ni_ind : tni.\nProof.\n  intros m sgn.\n  intros ns ns'. pattern ns, ns'. apply my_double_ind.\n  clear ns ns'; intros ns ns' Hind.\n  intros s s' r r' H Hpc Hindist Htevalsto Htevalsto'.\n  set (HM:=PM_P _ H).\n  inversion Htevalsto; inversion Htevalsto'.\n  (* *)\n  inversion H0; inversion H4.\n  subst. \n  rewrite <- Hpc in H15.\n  eapply indist2_return with (1:=Hindist) (5:=H11) (6:=H15); auto. \n  \n  (* *)\n  subst.\n  apply tevalsto_diff_high_result with (s:=s) (res:=r) in Htevalsto'; auto.\n  inversion Htevalsto'; apply high_result_indist; auto. \n  destruct n; auto. inversion H5. omega.\n  (* *)\n  subst.\n  apply tevalsto_diff_high_result with (s:=s') (res:=r') in Htevalsto; auto.\n  inversion Htevalsto; apply high_result_indist; auto.\n  destruct n; auto. inversion H1. omega.\n  (* *)\n  inversion H0; inversion H5; subst.\n  elim eq_excluded_middle with PC (pc s2) (pc s3); intros.\n  (* pc s = pc s' *)\n  rewrite <- Hpc in H19.\n  assert (H11':=H11). \n  apply indist2_intra with (1:=Hindist) (2:=Hpc) (4:=H16) (5:=H14) (6:=H19) in H11; \n    try (auto); try (rewrite <- Hpc; auto; fail).\n  apply Hind with (q:=n0) (p:=n) (s:=s2) (s':=s3) (r:=r) (r':=r') (H:=H); auto; try omega. \n  apply sub_simple with (rt:=rt'0).  \n  apply indist_sym. apply sub_simple with (rt:=rt'); auto.\n  rewrite H2; auto. \n\n  (* pc s <> pc s' *)\n  elim (soap1 (cdr m (PM_P _ H))) with (pc s) (pc s2) (pc s3); try (rewrite Hpc; auto; fail); auto; intros.\n  elim (soap1 (cdr m (PM_P _ H))) with (pc s) (pc s3) (pc s2); try (rewrite Hpc; auto; fail); auto; intros.\n  (* both are still in the region *)\n  elim junction_indist with (m:=m) (sgn:=sgn) (ns:=n) (ns':=n0) (s:=s) (s':=s')\n    (u:=s2) (u':=s3) (res:=r) (res':=r') (i:=pc s) (H:=H); auto.\n  intros. Cleanexand.\n  assert (pc x = pc x0) as Hpcx. apply junc_func with (step:=step m) (c:=cdr m (PM_P _ H)) (i:=pc s); auto.\n  apply Hind with (p:=x1) (q:=x2) (s:=x) (s':=x0) (r:=r) (r':=r') (H:=H); auto; try omega.\n  rewrite <- Hpcx in H18; auto.\n  apply typable_evalsto; auto.  \n  apply typable_evalsto; auto.\n  intros. inversion H7; apply high_result_indist; auto.\n  rewrite <- Hpc; auto.\n  assert ((forall j:PC, (region (cdr m (PM_P _ H)) (pc s) j) -> ~ leql (se m sgn j) observable)).\n    intros. apply soap2_basic_intra with (m:=m) (sgn:=sgn) (rt:=RT m sgn (pc s)) \n      (ut:=rt') (ut':=rt'0) (s:=s) (s':=s') (u:=s2) (u':=s3) (h:=H); auto.\n    rewrite Hpc; auto.\n    unfold high_region. auto.\n  apply tevalsto_evalsto with (se:=se) (RT:=RT) (sgn:=sgn) (h:=PM_P _ H); auto.\n  apply tevalsto_evalsto with (se:=se) (RT:=RT) (sgn:=sgn) (h:=PM_P _ H); auto.\n  apply branch_indist with (s:=s) (s':=s'); auto. rewrite <- Hpc; auto.\n  (* one region one junction *)\n  elim junction_indist_2 with (m:=m) (sgn:=sgn) (ns:=n0) (ns':=n) (s:=s') (s':=s)\n    (u:=s3) (u':=s2) (res:=r') (res':=r) (i:=pc s) (H:=H); auto.\n  intros. Cleanexand.\n  assert (pc x = pc s2) as Hpcx. apply junc_func with (step:=step m) (c:=cdr m (PM_P _ H)) (i:=pc s); auto.\n  apply Hind with (p:=n) (q:=x0) (s:=s2) (s':=x) (r:=r) (r':=r') (H:=H); auto; try omega.\n  apply indist_sym; rewrite Hpcx in H10; auto.\n  apply typable_evalsto; auto.  \n  apply indist_sym; rewrite <- Hpc; auto.\n  assert ((forall j:PC, (region (cdr m (PM_P _ H)) (pc s) j) -> ~ leql (se m sgn j) observable)).\n    intros. apply soap2_basic_intra with (m:=m) (sgn:=sgn) (rt:=RT m sgn (pc s)) \n      (ut:=rt') (ut':=rt'0) (s:=s) (s':=s') (u:=s2) (u':=s3) (h:=H); auto.\n    rewrite Hpc; auto.\n    unfold high_region; auto.\n  apply tevalsto_evalsto with (se:=se) (RT:=RT) (sgn:=sgn) (h:=PM_P _ H); auto.\n  apply tevalsto_evalsto with (se:=se) (RT:=RT) (sgn:=sgn) (h:=PM_P _ H); auto.\n  apply branch_indist with (s:=s') (s':=s); auto.\n  apply indist_sym. rewrite <- Hpc; auto.\n  elim (soap1 (cdr m (PM_P _ H))) with (pc s) (pc s3) (pc s2); try (rewrite H0; auto; fail); auto; intros.\n  (* one junction one region *)\n  elim junction_indist_2 with (m:=m) (sgn:=sgn) (ns:=n) (ns':=n0) (s:=s) (s':=s')\n    (u:=s2) (u':=s3) (res:=r) (res':=r') (i:=pc s) (H:=H); auto.\n  intros. Cleanexand.\n  assert (pc x = pc s3) as Hpcx. apply junc_func with (step:=step m) (c:=cdr m (PM_P _ H)) (i:=pc s); auto.\n  apply Hind with (p:=x0) (q:=n0) (s:=x) (s':=s3) (r:=r) (r':=r') (H:=H); auto; try omega.\n  rewrite <- Hpcx in H10; auto.\n  apply typable_evalsto; auto.  \n  rewrite <- Hpc; auto.\n  assert ((forall j:PC, (region (cdr m (PM_P _ H)) (pc s) j) -> ~ leql (se m sgn j) observable)).\n    intros. apply soap2_basic_intra with (m:=m) (sgn:=sgn) (rt:=RT m sgn (pc s)) \n      (ut:=rt') (ut':=rt'0) (s:=s) (s':=s') (u:=s2) (u':=s3) (h:=H); auto.\n    rewrite Hpc; auto.\n    unfold high_region; auto.\n  apply tevalsto_evalsto with (se:=se) (RT:=RT) (sgn:=sgn) (h:=PM_P _ H); auto.\n  apply tevalsto_evalsto with (se:=se) (RT:=RT) (sgn:=sgn) (h:=PM_P _ H); auto.\n  apply branch_indist with (s:=s) (s':=s'); auto.\n  rewrite <- Hpc; auto.\n  (* both are junctions *)\n  apply junc_func with (step:=step m) (c:=cdr m (PM_P _ H)) (i:=pc s) (j1:=pc s2) in H3; auto.\n  contradiction.\n  apply exec_step_some with (1:=PM_P _ H) in H16. rewrite Hpc; auto.\nQed.\n\nTheorem safe_ni : forall m sgn p p' s s' r r',\n  P (SM m sgn) ->\n  init_pc m (pc s) ->\n  init_pc m (pc s') ->\n  indist sgn (rt0 m sgn) (rt0 m sgn) s s' ->\n  pc s = pc s' ->\n  evalsto m p s r -> \n  evalsto m p' s' r' -> \n    rindist sgn r r'.\nProof.\n  intros.\n  apply (@ni_ind m sgn p p' s s' r r' H); auto.\n  destruct (T _ _ H) as [T1 _]. rewrite T1; auto.\n  apply typable_evalsto; auto.\n  apply typable_evalsto; auto.\nQed.\n\nEnd TypableProg.\nEnd A.", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/DEX_I/DEX_Framework.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23269637200598775}}
{"text": "Require Import Terms.\nRequire Import LNaVSyntax.\nRequire Import LThrowDBigStep. (* reusing helpers *)\n\n(** * Continuations and partial configurations *)\n\nInductive Frame : Type :=\n| RLet : Var -> Tm -> Frame\n| RRet : Env -> Frame\n| RBrk : Lab -> Lab -> Frame (* final label + original pc *)\n| RCatch : Var -> Tm -> Frame.\n\nDefinition Cont := list Frame.\n\nDefinition PCfg := prod (prod Lab Env) Cont.\n\nInductive RCfg : Type :=\n| CR : Tm -> RCfg    (* term to be reduced *)\n| CA : Atom -> RCfg  (* return atom *)\n| CT : Excp -> RCfg. (* thrown exception *)\n\nDefinition Cfg := prod PCfg RCfg.\n\nNotation \"v @ L\" := (v,L) (at level 5).\n\nNotation \"<< pc , r , k , X >>\" := (((pc, r), k), X) (at level 5).\n\nDefinition result_to_rcfg r :=\n  match r with\n  | Suc a => CA a\n  | Throw e => CT e\n  end.\n\n(** * Small-step semantics defined as a total(!) function *)\n\nDefinition step (c : Cfg) : Cfg :=\n  match c with\n  (* s_var *)\n  | << pc, rho, k, CR (TVar x) >> =>\n    match get rho x with\n    | Some a =>\n      << pc, rho, k, CA a >>\n    | None =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_const *)\n  | << pc, rho, k, CR (TConst c) >> =>\n    << pc, rho, k, CA (V (VConst c))@bot>>\n  (* s_let_start *)\n  | << pc, rho, k, CR (TLet x t1 t2) >> =>\n    << pc, rho, RLet x t2 :: k, CR t1 >>\n  (* s_let_bind *)\n  | << pc, rho, RLet x t :: k, CA a >> =>\n    << pc, (x,a) :: rho, RRet rho :: k, CR t >>\n  (* s_let_unwind *)\n  | << pc, rho, RLet x t :: k, CT e >> =>\n    << pc, rho, k, CT e >>\n  (* s_abs *)\n  | << pc, rho, k, CR (TAbs x t) >> =>\n    << pc, rho, k, CA (V (VClos rho x t))@bot >>\n  (* s_app *)\n  | << pc, rho, k, CR (TApp x1 x2) >> =>\n    match get rho x1, get rho x2 with\n    | Some ((V (VClos rho' x t))@L), Some a =>\n      << pc\\_/L, (x,a) :: rho', RRet rho :: k, CR t >>\n    | Some (b,L), Some a =>\n      << pc\\_/L, rho, k, CT (propagate_d b) >>\n    | _, _ => \n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_return *)\n  | << pc, rho, RRet rho' :: k, CA a >> =>\n    << pc, rho', k, CA a >>\n  (* s_return_unwind *)\n  | << pc, rho, RRet rho' :: k, CT e >> =>\n    << pc, rho', k, CT e >>\n  (* s_inx *)\n  | << pc, rho, k, CR (TInx d x) >> =>\n    match get rho x with\n    | Some a =>\n      << pc, rho, k, CA (V (VInx d a))@bot >>\n    | _ =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_match *)\n  | << pc, rho, k, CR (TMatch x x' t1 t2) >> =>\n    match get rho x with\n    | Some (V (VInx DLeft a), l) =>\n      << pc\\_/l, (x',a) :: rho, RRet rho :: k, CR t1 >>\n    | Some (V (VInx DRight a), l) =>\n      << pc\\_/l, (x',a) :: rho, RRet rho :: k, CR t2 >>\n    | Some (V _, l) =>\n      << pc\\_/l, rho, k, CT eType >>\n    | Some (D e, l) =>\n      << pc\\_/l, rho, k, CT e >>\n    | _ =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_tag *)\n  | << pc, rho, k, CR (TTag x) >> =>\n    match get rho x with\n    | Some (b,l) =>\n      << pc\\_/l, rho, k, result_to_rcfg (tag_res b) >>\n    | _ =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_bop *)\n  | << pc, rho, k, CR (TBOp bo x' x'') >> =>\n    match get rho x', get rho x'' with\n    | Some (b', l0'), Some (b'', l0'') =>\n      << pc\\_/l0' \\_/ l0'', rho, k, result_to_rcfg (bop_res bo b' b'') >>\n    | _, _ =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_bracket_start *)\n  | << pc, rho, k, CR (TBracket x t) >> =>\n    match get rho x with\n    | Some ((V (VConst (CLab L)))@L') =>\n      << pc\\_/L', rho, RBrk L (pc\\_/L') :: k, CR t >>\n    | Some (b,L') => \n      << pc\\_/L', rho, k, CT (propagate_d b) >>\n    | None =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_bracket_end *)\n  | << pc, rho, RBrk L' pc' :: k, CA b@L >> =>\n    << pc', rho, k, CA (bracket_box (Suc b@L) pc (L' \\_/ pc'))@L' >>\n  | << pc, rho, RBrk L' pc' :: k, CT e >> =>\n    << pc', rho, k, CA (bracket_box (Throw e) pc (L' \\_/ pc'))@L' >>\n  (* s_label_of *)\n  | << pc, rho, k, CR (TLabelOf x) >> =>\n    match get rho x with\n    | Some (_,l) =>\n      << pc, rho, k, CA (V (VConst (CLab l)))@bot >>\n    | _ =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_get_pc *)\n  | << pc, rho, k, CR TGetPc >> =>\n    << pc, rho, k, CA (V (VConst (CLab pc)))@bot >>\n  (* s_throw *)\n  | << pc, rho, k, CR (TThrow x) >> =>\n    match get rho x with\n    | Some (b,l) =>\n      << pc\\_/l, rho, k, CT (throw_excp b) >>\n    | _ =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_catch *)\n  | << pc, rho, k, CR (TCatch t x t') >> =>\n    << pc, rho, RCatch x t' :: k, CR t >>\n  (* s_catch_no_excp *)\n  | << pc, rho, RCatch x t' :: k, CA a >> =>\n    << pc, rho, k, CA a >>\n  (* s_catch_excp *)\n  | << pc, rho, RCatch x t' :: k, CT e >> =>\n    << pc, (x,((V (vExcp e))@bot)) :: rho, RRet rho :: k, CR t' >>\n  (* s_to_sum *)\n  | << pc, rho, k, CR (TToSum x) >> =>\n    match get rho x with\n    | Some (b,l) =>\n      << pc, rho, k, CA (to_sum_box b)@l >>\n    | _ =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* stack underflow (you're already done?) *)\n  | << pc, rho, nil, CA _ >> =>\n      << pc, rho, nil, CT eStack >>\n  | << pc, rho, nil, CT e >> =>\n      << pc, rho, nil, CT e >>\n  (* terms not from this language *)\n  (* s_mk_nav *)\n  | << pc, rho, k, CR (TMkNav _) >> =>\n      << pc, rho, k, CT eLanguage >>\n  end.\n\nDefinition final (c : Cfg) : bool :=\n  match c with\n  | << pc, rho, nil, CA _ >> => true\n  | << pc, rho, nil, CT _ >> => true\n  | _ => false\n  end.\n\nFixpoint nstep (n : nat) (cm : Cfg*nat) : Cfg*nat :=\n  match n with\n  | S n' =>\n    match cm with\n    | (c,m) => if final c then (c,m) else nstep n' (step c, m+1)\n    end\n  | O => cm\n  end.\n\nDefinition mstep (n : nat) (t : Tm) : Cfg*nat :=\n  nstep n (<< bot, nil, nil, CR t >>, 0).\n\nDefinition sstep (n : nat) (t : Tm) : option ((Result*Lab)*nat) :=\n  match mstep n t with\n  | (<< pc, rho, nil, CA a >>, m) => Some ((Suc a,pc),m) \n  | (<< pc, rho, nil, CT e >>, m) => Some ((Throw e,pc),m)\n  | _ => None (* looping or need more steps *)\n  end.\n", "meta": {"author": "mgree", "repo": "navdifc", "sha": "cde33f3ef7170b59653e252513ec6fc7ed78983a", "save_path": "github-repos/coq/mgree-navdifc", "path": "github-repos/coq/mgree-navdifc/navdifc-cde33f3ef7170b59653e252513ec6fc7ed78983a/LThrowDSmallStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093882168609, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23257595311142054}}
{"text": "From stdpp Require Import namespaces.\nFrom iris.algebra Require Import excl auth list.\nFrom iris.heap_lang Require Export lifting notation.\nFrom iris.base_logic.lib Require Import invariants.\nFrom iris.program_logic Require Import atomic.\nFrom iris.heap_lang Require Import proofmode atomic_heap.\nFrom iris_examples.logatom.elimination_stack Require spec.\nSet Default Proof Using \"Type\".\n\nModule logatom := elimination_stack.spec.\n\n(** A general HoCAP-style interface for a stack, modeled after the spec in\n[hocap/abstract_bag.v].  There are two differences:\n- We split [bag_contents] into an authoritative part and a fragment as this\n  slightly strnegthens the spec: The logically atomic spec only requires\n  [stack_content ∗ stack_content] to derive a contradiction, the abstract bag\n  spec requires to get *three* pieces which is only possible when actually\n  calling a bag operation.\n- We also slightly weaken the spec by adding [make_laterable], which is needed\n  because logical atomicity can only capture laterable resources, which is\n  needed when implementing e.g. the elimination stack on top of an abstract\n  logically atomic heap. *)\nRecord hocap_stack {Σ} `{!heapG Σ} := AtomicStack {\n  (* -- operations -- *)\n  new_stack : val;\n  push : val;\n  pop : val;\n  (* -- other data -- *)\n  name : Type;\n  name_eqdec : EqDecision name;\n  name_countable : Countable name;\n  (* -- predicates -- *)\n  is_stack (N : namespace) (γs : name) (v : val) : iProp Σ;\n  stack_content_frag (γs : name) (l : list val) : iProp Σ;\n  stack_content_auth (γs : name) (l : list val) : iProp Σ;\n  (* -- predicate properties -- *)\n  is_stack_persistent N γs v : Persistent (is_stack N γs v);\n  stack_content_frag_timeless γs l : Timeless (stack_content_frag γs l);\n  stack_content_auth_timeless γs l : Timeless (stack_content_auth γs l);\n  stack_content_frag_exclusive γs l1 l2 :\n    stack_content_frag γs l1 -∗ stack_content_frag γs l2 -∗ False;\n  stack_content_auth_exclusive γs l1 l2 :\n    stack_content_auth γs l1 -∗ stack_content_auth γs l2 -∗ False;\n  stack_content_agree γs l1 l2 :\n    stack_content_frag γs l1 -∗ stack_content_auth γs l2 -∗ ⌜l1 = l2⌝;\n  stack_content_update γs l l' :\n    stack_content_frag γs l -∗\n    stack_content_auth γs l -∗\n    |==> stack_content_frag γs l' ∗ stack_content_auth γs l';\n  (* -- operation specs -- *)\n  new_stack_spec N :\n    {{{ True }}} new_stack #() {{{ γs s, RET s; is_stack N γs s ∗ stack_content_frag γs [] }}};\n  push_spec N γs s (v : val) (Φ : val → iProp Σ) :\n    is_stack N γs s -∗\n    make_laterable (∀ l, stack_content_auth γs l ={⊤∖↑N}=∗ stack_content_auth γs (v::l) ∗ Φ #()) -∗\n    WP push s v {{ Φ }};\n  pop_spec N γs s (Φ : val → iProp Σ) :\n    is_stack N γs s -∗\n    make_laterable (∀ l, stack_content_auth γs l ={⊤∖↑N}=∗\n          match l with [] => stack_content_auth γs [] ∗ Φ NONEV\n                | v :: l' => stack_content_auth γs l' ∗ Φ (SOMEV v) end) -∗\n    WP pop s {{ Φ }};\n}.\nArguments hocap_stack _ {_}.\n\nExisting Instances\n  is_stack_persistent stack_content_frag_timeless stack_content_auth_timeless\n  name_eqdec name_countable.\n\n(** Show that our way of writing the [pop_spec] is equivalent to what is done in\n[concurrent_stack.spec].  IOW, the conjunction-vs-match doesn't matter.  Fixing\nthe postcondition (the [Q] in [concurrent_stack.spec]) still matters. *)\nSection pop_equiv.\n  Context `{invG Σ} (T : Type).\n\n  Lemma pop_equiv E (I : list T → iProp Σ) (Φemp : iProp Σ) (Φret : T → iProp Σ) :\n    (∀ l, I l ={E}=∗\n       match l with [] => I [] ∗ Φemp | v :: l' => I l' ∗ Φret v end)\n    ⊣⊢\n    (∀ v vs, I (v :: vs) ={E}=∗ Φret v ∗ I vs)\n    ∧ (I [] ={E}=∗ Φemp ∗ I []).\n  Proof.\n    iSplit.\n    - iIntros \"HΦ\". iSplit.\n      + iIntros (??) \"HI\". iMod (\"HΦ\" with \"HI\") as \"[$ $]\". done.\n      + iIntros \"HI\". iMod (\"HΦ\" with \"HI\") as \"[$ $]\". done.\n    - iIntros \"HΦ\" (l) \"HI\". destruct l; rewrite [(I _ ∗ _)%I]bi.sep_comm; by iApply \"HΦ\".\n  Qed.\nEnd pop_equiv.\n\n(** From a HoCAP stack we can directly implement the logically atomic\ninterface. *)\nSection hocap_logatom.\n  Context `{!heapG Σ} (stack: hocap_stack Σ).\n\n  Lemma logatom_push N γs s (v : val) :\n    stack.(is_stack) N γs s -∗\n    <<< ∀ l : list val, stack.(stack_content_frag) γs l >>>\n      stack.(push) s v @ ⊤∖↑N\n    <<< stack.(stack_content_frag) γs (v::l), RET #() >>>.\n  Proof.\n    iIntros \"Hstack\". iIntros (Φ) \"HΦ\".\n    iApply (push_spec with \"Hstack\").\n    iApply (make_laterable_intro with \"[] HΦ\"). iIntros \"!# >HΦ\" (l) \"Hauth\".\n    iMod \"HΦ\" as (l') \"[Hfrag [_ Hclose]]\".\n    iDestruct (stack_content_agree with \"Hfrag Hauth\") as %->.\n    iMod (stack_content_update with \"Hfrag Hauth\") as \"[Hfrag $]\".\n    iMod (\"Hclose\" with \"Hfrag\") as \"HΦ\". done.\n  Qed.\n\n  Lemma logatom_pop N γs (s : val) :\n    stack.(is_stack) N γs s -∗\n    <<< ∀ l : list val, stack.(stack_content_frag) γs l >>>\n      stack.(pop) s @ ⊤∖↑N\n    <<< stack.(stack_content_frag) γs (tail l),\n        RET match l with [] => NONEV | v :: _ => SOMEV v end >>>.\n  Proof.\n    iIntros \"Hstack\". iIntros (Φ) \"HΦ\".\n    iApply (pop_spec with \"Hstack\").\n    iApply (make_laterable_intro with \"[] HΦ\"). iIntros \"!# >HΦ\" (l) \"Hauth\".\n    iMod \"HΦ\" as (l') \"[Hfrag [_ Hclose]]\".\n    iDestruct (stack_content_agree with \"Hfrag Hauth\") as %->.\n    destruct l;\n    iMod (stack_content_update with \"Hfrag Hauth\") as \"[Hfrag $]\";\n    iMod (\"Hclose\" with \"Hfrag\") as \"HΦ\"; done.\n  Qed.\n\n  Definition hocap_logatom : logatom.atomic_stack Σ :=\n    {| logatom.new_stack_spec := stack.(new_stack_spec);\n       logatom.push_spec := logatom_push;\n       logatom.pop_spec := logatom_pop;\n       logatom.stack_content_exclusive := stack.(stack_content_frag_exclusive) |}.\n\nEnd hocap_logatom.\n\n(** From a logically atomic stack, we can implement a HoCAP stack by adding an\nauth invariant. *)\n\n(** The CMRA & functor we need. *)\nClass hocapG Σ := HocapG {\n  hocap_stateG :> inG Σ (authR (optionUR $ exclR (listO valO)));\n}.\nDefinition hocapΣ : gFunctors :=\n  #[GFunctor (exclR unitO); GFunctor (authR (optionUR $ exclR (listO valO)))].\n\nInstance subG_hocapΣ {Σ} : subG hocapΣ Σ → hocapG Σ.\nProof. solve_inG. Qed.\n\nSection logatom_hocap.\n  Context `{!heapG Σ} `{!hocapG Σ} (stack: logatom.atomic_stack Σ).\n\n  Definition hocap_name : Type := stack.(logatom.name) * gname.\n  Implicit Types γs : hocap_name.\n\n  Definition hocap_stack_content_auth γs l : iProp Σ := own γs.2 (● Excl' l).\n  Definition hocap_stack_content_frag γs l : iProp Σ := own γs.2 (◯ Excl' l).\n\n  Definition hocap_is_stack N γs v : iProp Σ :=\n    (stack.(logatom.is_stack) (N .@ \"stack\") γs.1 v ∗\n     inv (N .@ \"wrapper\") (∃ l, stack.(logatom.stack_content) γs.1 l ∗ hocap_stack_content_auth γs l))%I.\n\n  Lemma hocap_new_stack N :\n    {{{ True }}}\n      stack.(logatom.new_stack) #()\n    {{{ γs s, RET s; hocap_is_stack N γs s ∗ hocap_stack_content_frag γs [] }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\". iApply wp_fupd. iApply logatom.new_stack_spec; first done.\n    iIntros \"!>\" (γs s) \"[Hstack Hcont]\".\n    iMod (own_alloc (● Excl' [] ⋅ ◯ Excl' [])) as (γw) \"[Hs● Hs◯]\".\n    { apply auth_both_valid. split; done. }\n    iApply (\"HΦ\" $! (γs, γw)). rewrite /hocap_is_stack. iFrame.\n    iApply inv_alloc. eauto with iFrame.\n  Qed.\n\n  Lemma hocap_push N γs s (v : val) (Φ : val → iProp Σ) :\n    hocap_is_stack N γs s -∗\n    make_laterable (∀ l, hocap_stack_content_auth γs l ={⊤∖↑N}=∗ hocap_stack_content_auth γs (v::l) ∗ Φ #()) -∗\n    WP stack.(logatom.push) s v {{ Φ }}.\n  Proof using Type*.\n    iIntros \"#[Hstack Hwrap] Hupd\". awp_apply (logatom.push_spec with \"Hstack\").\n    iInv \"Hwrap\" as (l) \"[>Hcont >H●]\".\n    iAaccIntro with \"Hcont\"; first by eauto 10 with iFrame.\n    iIntros \"Hcont\".\n    iMod fupd_intro_mask' as \"Hclose\";\n      last iMod (make_laterable_elim with \"Hupd H●\") as \"[H● HΦ]\"; first solve_ndisj.\n    iMod \"Hclose\" as \"_\". iIntros \"!>\".\n    eauto with iFrame.\n  Qed.\n\n  Lemma hocap_pop N γs s (Φ : val → iProp Σ) :\n    hocap_is_stack N γs s -∗\n    make_laterable (∀ l, hocap_stack_content_auth γs l ={⊤∖↑N}=∗\n          match l with [] => hocap_stack_content_auth γs [] ∗ Φ NONEV\n                | v :: l' => hocap_stack_content_auth γs l' ∗ Φ (SOMEV v) end) -∗\n    WP stack.(logatom.pop) s {{ Φ }}.\n  Proof using Type*.\n    iIntros \"#[Hstack Hwrap] Hupd\". awp_apply (logatom.pop_spec with \"Hstack\").\n    iInv \"Hwrap\" as (l) \"[>Hcont >H●]\".\n    iAaccIntro with \"Hcont\"; first by eauto 10 with iFrame.\n    iIntros \"Hcont\". destruct l.\n    - iMod fupd_intro_mask' as \"Hclose\";\n        last iMod (make_laterable_elim with \"Hupd H●\") as \"[H● HΦ]\"; first solve_ndisj.\n       iMod \"Hclose\" as \"_\". iIntros \"!>\"; eauto with iFrame.\n    - iMod fupd_intro_mask' as \"Hclose\";\n        last iMod (make_laterable_elim with \"Hupd H●\") as \"[H● HΦ]\"; first solve_ndisj.\n       iMod \"Hclose\" as \"_\". iIntros \"!>\"; eauto with iFrame.\n  Qed.\n\n  Program Definition logatom_hocap : hocap_stack Σ :=\n    {| new_stack_spec := hocap_new_stack;\n       push_spec := hocap_push;\n       pop_spec := hocap_pop |}.\n  Next Obligation.\n    iIntros (???) \"Hf1 Hf2\". iDestruct (own_valid_2 with \"Hf1 Hf2\") as %[].\n  Qed.\n  Next Obligation.\n    iIntros (???) \"Ha1 Ha2\". by iDestruct (own_valid_2 with \"Ha1 Ha2\") as %[].\n  Qed.\n  Next Obligation.\n    iIntros (???) \"Hf Ha\". iDestruct (own_valid_2 with \"Ha Hf\") as\n      %[->%Excl_included%leibniz_equiv _]%auth_both_valid. done.\n  Qed.\n  Next Obligation.\n    iIntros (???) \"Hf Ha\". iMod (own_update_2 with \"Ha Hf\") as \"[? ?]\".\n    { eapply auth_update, option_local_update, (exclusive_local_update _ (Excl _)). done. }\n    by iFrame.\n  Qed.\n\nEnd logatom_hocap.\n", "meta": {"author": "anemoneflower", "repo": "IRIS-study", "sha": "63cbfee3959659074047682faeed7190b5be53df", "save_path": "github-repos/coq/anemoneflower-IRIS-study", "path": "github-repos/coq/anemoneflower-IRIS-study/IRIS-study-63cbfee3959659074047682faeed7190b5be53df/examples-master/theories/logatom/elimination_stack/hocap_spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23257594661276051}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.floyd.VSU.\nRequire Import fastpile.\nRequire Import spec_stdlib.\nRequire Import spec_fastpile_concrete.\n\n#[export] Instance FPileConcCompSpecs : compspecs. make_compspecs prog. Defined.\n\nSection FastpileConcrete_VSU.\nVariable M: MallocFreeAPD.\n\nDefinition crep (s: Z) (p: val) : mpred :=\n  EX s':Z, !! (0 <= s /\\ 0 <= s' <= Int.max_signed /\\\n                 (s <= Int.max_signed -> s'=s)) &&\n  data_at Ews tpile (Vint (Int.repr s')) p.\n\nDefinition cfreeable (p: val) :=\n   malloc_token M Ews tpile p.\n\nLemma crep_local_facts:\n  forall s p, crep s p |-- !! isptr p.\nProof.\nintros.\nunfold crep.\nIntros s'.\nentailer!.\nQed.\n\n#[export] Hint Resolve crep_local_facts : saturate_local.\n\nLemma crep_valid_pointer:\n  forall s p, crep s p |-- valid_pointer p.\nProof. \n intros.\n unfold crep. Intros s'.\n auto with valid_pointer.\nQed.\n#[export] Hint Resolve crep_valid_pointer : valid_pointer.\n\nDefinition FASTPILECONC: FastpileConcreteAPD :=\n  Build_FastpileConcreteAPD crep crep_local_facts crep_valid_pointer cfreeable.\n\nDefinition surely_malloc_spec :=\n  DECLARE _surely_malloc\n   WITH t:type, gv: globals\n   PRE [ size_t ]\n       PROP (0 <= sizeof t <= Ptrofs.max_unsigned;\n                complete_legal_cosu_type t = true;\n                natural_aligned natural_alignment t = true)\n       PARAMS (Vptrofs (Ptrofs.repr (sizeof t))) GLOBALS (gv)\n       SEP (mem_mgr M gv)\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (mem_mgr M gv; malloc_token M Ews t p * data_at_ Ews t p).\n\n  Definition FastpileConc_ASI: funspecs := FastpileConcreteASI M FASTPILECONC.\n\n  Definition fastpileconc_imported_specs:funspecs := MallocFreeASI M.\n\n  Definition fastpileconc_internal_specs: funspecs := surely_malloc_spec::FastpileConc_ASI.\n\n  Definition FastpileConcVprog: varspecs. mk_varspecs prog. Defined.\n  Definition FastpileConcGprog: funspecs := fastpileconc_imported_specs ++ fastpileconc_internal_specs.\n\nLemma body_Pile_new: semax_body FastpileConcVprog FastpileConcGprog f_Pile_new (Pile_new_spec M FASTPILECONC).\nProof.\nstart_function.\nforward_call (tpile, gv).\nsplit3; simpl; auto; computable.\nIntros p.\nforward.\nforward.\nsimpl countrep. unfold crep.\nsimpl count_freeable. unfold cfreeable.\nExists p 0.\nentailer!.\nQed.\n\nLemma body_Pile_add: semax_body FastpileConcVprog FastpileConcGprog f_Pile_add (Pile_add_spec M FASTPILECONC).\nProof.\nstart_function.\nsimpl countrep. unfold crep.\nIntros s'.\nforward.\nforward_if (temp _t'1 (if zle 0 n then if zle n (Int.max_signed-s') then Vtrue else Vfalse else Vfalse)).\n-\nforward.\nentailer!.\ndestruct (zle 0 n); [ | lia].\ndestruct (zle _ _).\nunfold Int.lt. rewrite zlt_false.\nreflexivity.\nnormalize. rep_lia.\nunfold Int.lt. rewrite zlt_true.\nreflexivity.\nnormalize.\nrep_lia.\n-\nforward.\nentailer!.\n-\ndestruct (zle 0 n); try lia.\nforward_if (PROP()LOCAL (temp _pp p)\n   SEP(crep (n+s) p; mem_mgr M gv)).\n+\nif_tac in H3; inv H3.\nforward.\nunfold crep. Exists (s'+n).\nentailer!.\n+\nforward.\nunfold crep.\nif_tac in H3; inv H3.\nExists s'. entailer!.\n+\nforward.\nQed.\n\nLemma body_Pile_count: semax_body FastpileConcVprog FastpileConcGprog f_Pile_count (Pile_count_spec FASTPILECONC).\nProof.\nstart_function.\nsimpl countrep. unfold crep.\nIntros s'.\nforward.\nforward.\nsimpl countrep. unfold crep.\nExists s' s'.\nentailer!.\nQed.\n\nLemma body_Pile_free: semax_body FastpileConcVprog FastpileConcGprog f_Pile_free (Pile_free_spec M FASTPILECONC).\nProof.\nstart_function.\nsimpl countrep. unfold crep.\nsimpl count_freeable. unfold cfreeable. Intros s'.\nassert_PROP (p<>nullval) by entailer!. \nforward_call (free_spec_sub M (Tstruct _pile noattr))  (p, gv).\nrewrite if_false by auto.\ncancel.\nforward.\nQed.\n\n(*Same statement and proof as verif_pile. Indeed, the C files have the same code duplication...*)\n(*Statement and proof also shared with verif_fastpile.v*)\nLemma body_surely_malloc: semax_body FastpileConcVprog FastpileConcGprog f_surely_malloc surely_malloc_spec.\nProof.\nstart_function.\nforward_call (malloc_spec_sub M t) gv.\nIntros p.\nif_tac.\n{ subst.\n  forward_if False.\n  - forward_call 1. contradiction.\n  - congruence. }\nforward_if True.\n+ contradiction.\n+ forward. entailer!.\n+ forward. Exists p. entailer!.\nQed.\n\n  Definition FastpileVSU: @VSU NullExtension.Espec\n      nil fastpileconc_imported_specs ltac:(QPprog prog) FastpileConc_ASI emp.\n  Proof. \n    mkVSU prog fastpileconc_internal_specs.\n    + solve_SF_internal body_surely_malloc.\n    + solve_SF_internal body_Pile_count.\n    + solve_SF_internal body_Pile_add.\n    + solve_SF_internal body_Pile_new.\n    + solve_SF_internal body_Pile_free.\n  Qed.\n\nEnd FastpileConcrete_VSU.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/VSUpile/fast/verif_fastpile_concrete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2325759401141004}}
{"text": "From stdpp Require Import fin_maps.\nFrom iris_time.heap_lang Require Export notation proofmode.\nFrom iris_time Require Import Reduction.\n\nImplicit Type e : expr.\nImplicit Type v : val.\nImplicit Type σ : state.\nImplicit Type t : list expr.\nImplicit Type K : ectx heap_ectx_lang.\nImplicit Type m n : nat.\n\n\n\n(*\n * Translation with any arbitrary expression for [tick]\n *)\n\n(* “tick” is a typeclass so that it can be made an implicit argument of the\n * translation and be inferred automatically from the context.\n   This also make it possible to share notations. *)\nClass Tick := tick : val.\n\nSection Translation.\n\n  Context {Htick : Tick}.\n\n  (* Unfortunately, the operational semantics of [match] in our language is\n   * ad-hoc somehow, as the rule is:\n   *     Case (InjL v) e1 e2  →  e1 v\n   * Instead of the more canonical rule:\n   *     Case (InjL v) (x1. e1) (x2. e2)  →  e1 [x1 := v]\n   * This means that the reduction of a match construct really takes two steps,\n   * since we still have to reduce the application; hence, in our time credit\n   * model, a match construct will cost two credits.\n   * It also means that the “branch” [e1] is not constrained be a λ-abstraction,\n   * and can reduce after the reduction of the [match] but before it is applied\n   * to [v]!\n   * This ad-hoc semantics calls for an ad-hoc definition of the translation in\n   * that case because, to observe the simulation lemma, the translation of\n   * [Case (InjL v) e1 e2] must reduce to the translation of [e1 v], which is\n   * [(tick «e1») «v»]. To do so --which means preserving the weird evaluation\n   * order--, we use the helper term below: *)\n  Definition tick_case_branch : val :=\n    (λ: \"f\" \"x\", tick (\"f\" #()) \"x\")%V.\n\n  Fixpoint translation (e : expr) : expr :=\n    match e with\n    (* Base lambda calculus *)\n    | Var _           => e\n    | Rec f x e       => tick $ Rec f x (translation e)\n    | App e1 e2       => (tick $ translation e1) (translation e2)\n    | Val v           => Val $ translationV v\n    (* Base types and their operations *)\n    | UnOp op e       => UnOp op (tick $ translation e)\n    | BinOp op e1 e2  => BinOp op (tick $ translation e1) (translation e2)\n    | If e0 e1 e2     => If (tick $ translation e0) (translation e1) (translation e2)\n    (* Products *)\n    | Pair e1 e2      => Pair (tick $ translation e1) (translation e2)\n    | Fst e           => Fst (tick $ translation e)\n    | Snd e           => Snd (tick $ translation e)\n    (* Sums *)\n    | InjL e          => InjL (tick $ translation e)\n    | InjR e          => InjR (tick $ translation e)\n    | Case e0 e1 e2   =>\n        Case (tick $ translation e0)\n          (tick_case_branch (λ: <>, translation e1))\n          (tick_case_branch (λ: <>, translation e2))\n    (* Concurrency *)\n    | Fork e          => tick $ Fork (translation e)\n    (* Heap *)\n    | Alloc e         => Alloc (tick $ translation e)\n    | Load e          => Load (tick $ translation e)\n    | Store e1 e2     => Store (tick $ translation e1) (translation e2)\n    | CAS e0 e1 e2    => CAS (tick $ translation e0) (translation e1) (translation e2)\n    | FAA e1 e2       => FAA (tick $ translation e1) (translation e2)\n    end %E\n  with translationV (v : val) : val :=\n    match v with\n    | RecV f x e    => RecV f x (translation e)\n    | LitV _        => v\n    | PairV v1 v2   => PairV (translationV v1) (translationV v2)\n    | InjLV v       => InjLV (translationV v)\n    | InjRV v       => InjRV (translationV v)\n    end.\n\n  Definition translationS (σ : state) : state :=\n    translationV <$> σ.\n\n  Let tickCtx : ectx_item := AppRCtx tick.\n\n  Definition translationKi (Ki : ectx_item) : ectx_item :=\n    match Ki with\n    | AppLCtx v2      => AppLCtx (translationV v2)\n    | AppRCtx e1      => AppRCtx (tick $ translation e1)\n    | UnOpCtx op      => UnOpCtx op\n    | BinOpLCtx op v2 => BinOpLCtx op (translationV v2)\n    | BinOpRCtx op e1 => BinOpRCtx op (tick $ translation e1)\n    | IfCtx e1 e2     => IfCtx (translation e1) (translation e2)\n    | PairLCtx v2     => PairLCtx (translationV v2)\n    | PairRCtx e1     => PairRCtx (tick $ translation e1)\n    | FstCtx          => FstCtx\n    | SndCtx          => SndCtx\n    | InjLCtx         => InjLCtx\n    | InjRCtx         => InjRCtx\n    | CaseCtx e1 e2   =>\n        CaseCtx\n          (tick_case_branch (λ: <>, translation e1))%E\n          (tick_case_branch (λ: <>, translation e2))%E\n    | AllocCtx        => AllocCtx\n    | LoadCtx         => LoadCtx\n    | StoreLCtx v2    => StoreLCtx (translationV v2)\n    | StoreRCtx e1    => StoreRCtx (tick $ translation e1)\n    | CasLCtx v0 v1   => CasLCtx (translationV v0) (translationV v1)\n    | CasMCtx e1 v1   => CasMCtx (tick $ translation e1) (translationV v1)\n    | CasRCtx e1 e2   => CasRCtx (tick $ translation e1) (translation e2)\n    | FaaLCtx v2      => FaaLCtx (translationV v2)\n    | FaaRCtx e1      => FaaRCtx (tick $ translation e1)\n    end.\n\n  Definition translationKi_aux (Ki : ectx_item) : ectx _ :=\n    if ectx_item_is_active Ki then\n      [ tickCtx ; translationKi Ki ]\n    else\n      [ translationKi Ki ].\n\n  Definition translationK (K : ectx heap_ectx_lang) : ectx _ :=\n    List.concat (translationKi_aux <$> K).\n\n(*\n * Lemmas about translation\n *)\n\n  Lemma translation_subst x e v :\n    translation (subst x v e) = subst x (translationV v) (translation e).\n  Proof.\n    induction e ;\n    unfold subst ; simpl ; fold subst ;\n    try case_match ; (* ← this handles the cases of Var and Rec *)\n    repeat f_equal ;\n    assumption.\n  Qed.\n\n  Lemma translation_subst' x e v :\n    translation (subst' x v e) = subst' x (translationV v) (translation e).\n  Proof.\n    destruct x.\n    - reflexivity.\n    - apply translation_subst.\n  Qed.\n\n  Lemma translation_injective :\n    ∀ e1 e2,\n      translation e1 = translation e2 →\n      e1 = e2\n  with translationV_injective :\n    ∀ v1 v2,\n      translationV v1 = translationV v2 →\n      v1 = v2.\n  Proof.\n    destruct e1, e2; try discriminate; intros [=]; subst; f_equal;\n      by (apply translation_injective || apply translationV_injective).\n    destruct v1, v2; try discriminate; intros [=]; subst; f_equal;\n      by (apply translation_injective || apply translationV_injective).\n  Qed.\n\n  Lemma translation_fill_item Ki e :\n    translation (fill_item Ki e) = fill (translationKi_aux Ki) (translation e).\n  Proof.\n    destruct Ki ; reflexivity.\n  Qed.\n\n  Lemma translation_fill_item_active (ki : ectx_item) v :\n    ectx_item_is_active ki →\n    translation (fill_item ki v) = fill_item (translationKi ki) (tick (translationV v)).\n  Proof.\n    rewrite translation_fill_item.\n    unfold translationKi_aux ; destruct (ectx_item_is_active ki) ; last contradiction.\n    reflexivity.\n  Qed.\n\n  Lemma is_active_translationKi ki :\n    ectx_item_is_active ki →\n    ectx_item_is_active (translationKi ki).\n  Proof.\n    by destruct ki.\n  Qed.\n\n  Lemma translation_fill K e :\n    translation (fill K e) = fill (translationK K) (translation e).\n  Proof.\n    revert e ; induction K ; intros e.\n    - done.\n    - rewrite /= fill_app - translation_fill_item //.\n  Qed.\n\n  Lemma lookup_translationS_None σ l :\n    σ !! l = None →\n    translationS σ !! l = None.\n  Proof.\n    intros H. by rewrite lookup_fmap H.\n  Qed.\n\n  Lemma lookup_translationS_Some σ l v :\n    σ !! l = Some v →\n    translationS σ !! l = Some (translationV v).\n  Proof.\n    intros H. by rewrite lookup_fmap H.\n  Qed.\n\n  Lemma lookup_translationS_is_Some σ l :\n    is_Some (σ !! l) →\n    is_Some (translationS σ !! l).\n  Proof.\n    destruct 1. eauto using lookup_translationS_Some.\n  Qed.\n\n  Lemma lookup_translationS_None_inv σ l :\n    translationS σ !! l = None →\n    σ !! l = None.\n  Proof.\n    unfold translationS ; rewrite lookup_fmap.\n    destruct (σ !! l) eqn:E ; rewrite E ; first discriminate.\n    done.\n  Qed.\n\n  Lemma lookup_translationS_Some_inv σ l v' :\n    translationS σ !! l = Some v' →\n    ∃ v,  σ !! l = Some v  ∧  v' = translationV v.\n  Proof.\n    rewrite lookup_fmap.\n    destruct (σ !! l) eqn:E ; rewrite E ; last discriminate.\n    intros ? % Some_inj ; eauto.\n  Qed.\n\n  Lemma lookup_translationS_is_Some_inv σ l :\n    is_Some (translationS σ !! l) →\n    is_Some (σ !! l).\n  Proof.\n    intros [_ (? & ? & _) % lookup_translationS_Some_inv]. eauto.\n  Qed.\n\n  Lemma translationS_insert l v σ :\n    translationS (<[l := v]> σ) = <[l := translationV v]> (translationS σ).\n  Proof.\n    apply fmap_insert.\n  Qed.\n\n  Lemma un_op_eval_translation op v v' :\n    un_op_eval op v = Some v' →\n    un_op_eval op (translationV v) = Some (translationV v').\n  Proof.\n    intros H.\n    destruct op ;\n    destruct v ; try discriminate H ;\n    simpl ; case_match ; simpl in *;\n      try discriminate H;\n      try match goal with\n          |- context [to_mach_int ?x] => destruct (to_mach_int x); [|discriminate] end;\n      try by injection H as <-.\n  Qed.\n\n  Local Lemma _eval_EqOp_bool_decide v1 v2 :\n    bin_op_eval EqOp v1 v2 = Some $ LitV $ LitBool $ bool_decide (v1 = v2).\n  Proof.\n    destruct v1, v2 ; try done ;\n    simpl ; case_match ; try done ;\n    simpl ; case_match ; try done ;\n    repeat f_equal ; apply bool_decide_iff ; naive_solver.\n  Qed.\n\n  Local Lemma _bool_decide_eq_translationV v1 v2 :\n    bool_decide (v1 = v2) = bool_decide (translationV v1 = translationV v2).\n  Proof.\n    apply bool_decide_iff ; split ; intros H.\n    - by rewrite H.\n    - by eapply translationV_injective.\n  Qed.\n\n  Lemma bin_op_eval_translation op v1 v2 v' :\n    bin_op_eval op v1 v2 = Some v' →\n    bin_op_eval op (translationV v1) (translationV v2) = Some (translationV v').\n  Proof.\n    intros H.\n    destruct op ; try (\n      destruct v1, v2 ; try discriminate H ;\n      unfold bin_op_eval in * ;\n      do 3 try (case_match ; try discriminate H) ;\n      simpl in *;\n      try match goal with\n          |- context [to_mach_int ?x] => destruct (to_mach_int x); [|discriminate] end;\n      by injection H as <-\n    ).\n    (* Remaining case: op = EqOp *)\n    rewrite _eval_EqOp_bool_decide in H ; injection H as <-.\n    by rewrite _eval_EqOp_bool_decide - _bool_decide_eq_translationV.\n  Qed.\n\n  Lemma un_op_eval_translation_inv op v v' :\n    un_op_eval op (translationV v) = Some v' →\n    un_op_eval op v = Some v'.\n  Proof.\n    intros H.\n    destruct op ;\n    destruct v ; try discriminate H ;\n    done.\n  Qed.\n\n  Lemma bin_op_eval_translation_inv op v1 v2 v' :\n    bin_op_eval op (translationV v1) (translationV v2) = Some v' →\n    bin_op_eval op v1 v2 = Some v'.\n  Proof.\n    intros H.\n    destruct op ; try (\n      destruct v1, v2 ; try discriminate H ;\n      done\n    ).\n    (* Remaining case: op = EqOp *)\n    rewrite -> _eval_EqOp_bool_decide in *. injection H as <-.\n    by rewrite - _bool_decide_eq_translationV.\n  Qed.\n\n  Lemma translationV_lit lit :\n    translationV #lit = #lit.\n  Proof.\n    done.\n  Qed.\n\n  Lemma translationV_lit_inv v lit :\n    translationV v = #lit →\n    v = #lit.\n  Proof.\n    destruct v ; try discriminate. done.\n  Qed.\n\n  Lemma vals_cas_compare_safe_translationV v1 v2 :\n    vals_cas_compare_safe v1 v2 →\n    vals_cas_compare_safe (translationV v1) (translationV v2).\n  Proof.\n    intros [].\n    - left. by destruct v1 as [| | |[]|[]].\n    - right. by destruct v2 as [| | |[]|[]].\n  Qed.\n  Lemma vals_cas_compare_safe_translationV_inv v1 v2 :\n    vals_cas_compare_safe (translationV v1) (translationV v2) →\n    vals_cas_compare_safe v1 v2.\n  Proof.\n    intros [].\n    - left. by destruct v1 as [| | |[]|[]].\n    - right. by destruct v2 as [| | |[]|[]].\n  Qed.\n\nEnd Translation.\n\n(*\n * Notations\n *)\n\nNotation \"E« e »\" := (translation e%E).\nNotation \"V« v »\" := (translationV v%V).\nNotation \"Ki« ki »\" := (translationKi ki).\nNotation \"K« K »\" := (translationK K).\nNotation \"S« σ »\" := (translationS σ%V).\nNotation \"T« t »\" := (translation <$> t%E).\n\nNotation \"« e »\" := (translation e%E).\nNotation \"« e »\" := (translation e%E) : expr_scope.\nNotation \"« v »\" := (translationV v%V) : val_scope.\n\n(* for some reason, these notations make parsing fail,\n * even if they only regard printing… *)\n(*\nNotation \"« e »\" := (translation e%E) (only printing).\nNotation \"« v »\" := (translationV v%V) (only printing).\nNotation \"« ki »\" := (translationKi ki) (only printing).\nNotation \"« K »\" := (translationK K) (only printing).\nNotation \"« σ »\" := (translationS σ%V) (only printing).\nNotation \"« t »\" := (translation <$> t%E) (only printing).\n*)\n\n(* FIXME : the way coercions should or should not be included in\n   notations so that notations are pretty-printed back is completely\n   non-predictible. *)\n\nNotation \"'tickrec:' f x y .. z := e\" :=\n  (tick (Rec f%bind x%bind (tick (Lam y%bind .. (tick (Lam z%bind e%E)) ..))))\n  (at level 200, f, x, y, z at level 1, e at level 200,\n   format \"'[' 'tickrec:'  f  x  y  ..  z  :=  '/  ' e ']'\") : expr_scope.\n\nNotation \"tickλ: x , e\" := (tick (Lam x%bind e%E))\n  (at level 200, x at level 1, e at level 200,\n   format \"'[' 'tickλ:'  x ,  '/  ' e ']'\") : expr_scope.\nNotation \"tickλ: x y .. z , e\" :=\n  (tick (Lam x%bind (tick (Lam y%bind .. (tick (Lam z%bind e%E)) ..))))\n  (at level 200, x, y, z at level 1, e at level 200,\n   format \"'[' 'tickλ:'  x  y  ..  z ,  '/  ' e ']'\") : expr_scope.\n\nNotation \"'lettick:' x := e1 'in' e2\" :=\n  ((tick (App (Val tick) (Lam x%bind e2%E))) e1%E)\n  (at level 200, x at level 1, e1, e2 at level 200,\n   format \"'[' 'lettick:'  x  :=  '[' e1 ']'  'in'  '/' e2 ']'\") : expr_scope.\n\nNotation \"e1 ;tick; e2\" :=\n  ((tick (App (Val tick) (Lam BAnon e2%E))) e1%E)\n  (at level 100, e2 at level 200,\n   format \"'[' '[hv' '[' e1 ']'  ;tick;  ']' '/' e2 ']'\") : expr_scope.\n\nNotation \"'tickmatch:' e0 'with' 'InjL' x1 => e1 | 'InjR' x2 => e2 'end'\" :=\n  (Case (App (Val tick) e0) (App (Val tick_case_branch) (λ: <>, App (Val tick) (λ: x1, e1))%E)\n                            (App (Val tick_case_branch) (λ: <>, App (Val tick) (λ: x2, e2))%E))\n  (e0, x1, e1, x2, e2 at level 200,\n   format \"'[hv' 'tickmatch:'  e0  'with'  '/  ' '[' 'InjL'  x1  =>  '/  ' e1 ']'  '/' '[' |  'InjR'  x2  =>  '/  ' e2 ']'  '/' 'end' ']'\") : expr_scope.\n\n(*\n  Typeclass instance for the proofmode\n *)\n\nInstance AsRecV_translationV `{Tick} v f x e :\n  AsRecV v f x e →\n  AsRecV « v » f x « e ».\nProof. by intros ->. Qed.\n\n(*\n * Simplification tactic\n *)\n\n(* simpl and cbn do not work well with mutual fixpoints... *)\nLtac simpl_trans :=\n  cbn [translation translationV]; fold translation translationV.\n\n(*\n * (Partial) Inverse translation\n *)\n\nSection InvTranslation.\n\n  Fixpoint invtranslation (e : expr) : expr :=\n    match e with\n    (* Concurrency -- This pattern has to appear before the pattern of\n      App, since it conflicts with it. *)\n    | App tick (Fork e)          => Fork (invtranslation e)\n    (* Base lambda calculus *)\n    | Var _                      => e\n    | App tick (Rec f x e)       => Rec f x (invtranslation e)\n    | App (App tick e1) e2       => (invtranslation e1) (invtranslation e2)\n    | Val v                      => Val (invtranslationV v)\n    (* Base types and their operations *)\n    | UnOp op (App tick e)       => UnOp op (invtranslation e)\n    | BinOp op (App tick e1) e2  => BinOp op (invtranslation e1) (invtranslation e2)\n    | If (App tick e0) e1 e2     => If (invtranslation e0) (invtranslation e1) (invtranslation e2)\n    (* Products *)\n    | Pair (App tick e1) e2      => Pair (invtranslation e1) (invtranslation e2)\n    | Fst (App tick e)           => Fst (invtranslation e)\n    | Snd (App tick e)           => Snd (invtranslation e)\n    (* Sums *)\n    | InjL (App tick e)          => InjL (invtranslation e)\n    | InjR (App tick e)          => InjR (invtranslation e)\n    | Case (App tick e0) (App tickaux1 (Rec BAnon BAnon e1)) (App tickaux2 (Rec BAnon BAnon e2)) =>\n        Case (invtranslation e0) (invtranslation e1) (invtranslation e2)\n    (* Heap *)\n    | Alloc (App tick e)         => Alloc (invtranslation e)\n    | Load (App tick e)          => Load (invtranslation e)\n    | Store (App tick e1) e2     => Store (invtranslation e1) (invtranslation e2)\n    | CAS (App tick e0) e1 e2    => CAS (invtranslation e0) (invtranslation e1) (invtranslation e2)\n    | FAA (App tick e1) e2       => FAA (invtranslation e1) (invtranslation e2)\n    | _ => #42\n    end %E\n  with invtranslationV v :=\n    match v with\n    | RecV f x e    => RecV f x (invtranslation e)\n    | LitV _        => v\n    | PairV v1 v2   => PairV (invtranslationV v1) (invtranslationV v2)\n    | InjLV v       => InjLV (invtranslationV v)\n    | InjRV v       => InjRV (invtranslationV v)\n    end.\n\n  Lemma invtranslation_translation {Htick : Tick} e :\n    invtranslation (translation e) = e\n  with invtranslationV_translationV {Htick : Tick} v :\n    invtranslationV (translationV v) = v.\n  Proof.\n    - specialize (invtranslation_translation Htick).\n      specialize (invtranslationV_translationV Htick).\n      destruct e;\n        try by rewrite /= ?invtranslation_translation ?invtranslationV_translationV.\n      (* Handle the App case by hand. *)\n      { simpl. rewrite !invtranslation_translation. case_match=>//.\n          by destruct e2. by destruct e2. }\n\n    - specialize (invtranslation_translation Htick).\n      specialize (invtranslationV_translationV Htick).\n      destruct v;\n        try by rewrite /= ?invtranslation_translation ?invtranslationV_translationV.\n  Qed.\nEnd InvTranslation.\n\n\n\n(*\n * Characterizing expressions that are left invariant by translation\n *)\n\nSection ClosureFree.\n\n  Fixpoint closure_free (v : val) : bool :=\n    match v with\n    | RecV _ _ _ => false\n    | LitV _ => true\n    | PairV v1 v2 => closure_free v1 && closure_free v2\n    | InjLV v1 => closure_free v1\n    | InjRV v1 => closure_free v1\n    end.\n\n  Lemma closure_free_is_translationV_invariant {Htick : Tick} v :\n    closure_free v →\n    translationV v = v.\n  Proof.\n    intros ?.\n    induction v as\n      [ (* LitV *) lit\n      | (* RecV *) f x e1\n      | (* PairV *) v1 IH1 v2 IH2\n      | (* InjLV *) v1 IH1\n      | (* InjRV *) v1 IH1\n      ] ; cbn in *.\n    - done.\n    - contradiction.\n    - rewrite IH1 ?IH2; naive_solver.\n    - rewrite IH1 ; naive_solver.\n    - rewrite IH1 ; naive_solver.\n  Qed.\n\n  Lemma closure_free_is_invtranslationV_invariant v :\n    closure_free v →\n    invtranslationV v = v.\n  Proof.\n    intros ?.\n    induction v as\n      [ (* LitV *) lit\n      | (* RecV *) f x e1\n      | (* PairV *) v1 IH1 v2 IH2\n      | (* InjLV *) v1 IH1\n      | (* InjRV *) v1 IH1\n      ] ; cbn.\n    - done.\n    - contradiction.\n    - rewrite -> IH1, IH2 ; naive_solver.\n    - rewrite IH1 ; naive_solver.\n    - rewrite IH1 ; naive_solver.\n  Qed.\n\n  Lemma closure_free_translationV {Htick : Tick} v :\n    closure_free v →\n    closure_free (translationV v).\n  Proof.\n    intros Hv. by rewrite (closure_free_is_translationV_invariant v Hv).\n  Qed.\n\n  Lemma closure_free_invtranslationV v :\n    closure_free v →\n    closure_free (invtranslationV v).\n  Proof.\n    intros Hv. by rewrite (closure_free_is_invtranslationV_invariant v Hv).\n  Qed.\n\n  Lemma closure_free_translationV_iff  {Htick : Tick} v :\n    closure_free v  ↔  closure_free (translationV v).\n  Proof.\n    split.\n    - apply closure_free_translationV.\n    - intros H % closure_free_invtranslationV. by rewrite invtranslationV_translationV in H.\n  Qed.\n\n  Lemma closure_free_predicate (φ : val → Prop) :\n    (∀ (v : val), φ v → closure_free v) →\n    ∀ (v : val),\n      φ v → φ (invtranslationV v).\n  Proof.\n    intros Hφ v H.\n    by specialize (Hφ _ H) as -> % closure_free_is_invtranslationV_invariant.\n  Qed.\n\nEnd ClosureFree.\n\n(*\n *  Proofmode wp_* tactics.\n *)\n\n(* wp_tick is a stub to be redefined for each particular definition of\n   the tick function. *)\nLtac wp_tick := idtac.\n\nLtac wp_tick_closure := wp_closure; wp_tick.\nLtac wp_tick_pair := wp_tick; wp_pair.\nLtac wp_tick_inj := wp_tick; wp_inj.\n\nLtac wp_tick_rec := wp_tick ; wp_rec; simpl_trans.\nLtac wp_tick_lam := wp_tick_rec.\nLtac wp_tick_let := wp_tick_closure; wp_tick_lam.\nLtac wp_tick_seq := wp_tick_let.\nLtac wp_tick_op := wp_tick ; wp_op.\nLtac wp_tick_if := wp_tick ; wp_if.\nLtac wp_tick_match :=\n  wp_tick; wp_match; (wp_let || wp_seq); wp_lam;\n  wp_closure; wp_tick; wp_tick; wp_lam.\nLtac wp_tick_proj := wp_tick ; wp_proj.\nLtac wp_tick_alloc loc := wp_tick ; wp_alloc loc.\nLtac wp_tick_load := wp_tick ; wp_load.\nLtac wp_tick_store := wp_tick ; wp_store.\n", "meta": {"author": "Ricagraca", "repo": "i-splay-tree", "sha": "263215b780f52dd0168143def37be537bb07e0ea", "save_path": "github-repos/coq/Ricagraca-i-splay-tree", "path": "github-repos/coq/Ricagraca-i-splay-tree/i-splay-tree-263215b780f52dd0168143def37be537bb07e0ea/theories/Translation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23252493517189746}}
{"text": "Require Import ExtLib.Data.Monads.OptionMonad.\nRequire Import ExtLib.Structures.Monads.\n\nFrom CHKC Require Import Tactics ListUtil Map.\nRequire Import Coq.FSets.FMapFacts.\n(** * Document Conventions *)\n\n(* \n\nThis is the Coq model for the Checked-C formalism.\n\nChecked-C is a backward compatable compiler with C. Its main feature\nis to compiled a program with enough dynamic checks to ensure that checked pointers are not misused\ndue to null-pointer deference or out-of-bound pointer dereference.\n*)\n\n(** * Syntax *)\n\n(** The types [var], [field], and [struct] are the (distinguished) syntactic classes of program variables ([x]), fields ([f]), and structures [T])\n    respectively. They are all implemented concretely as natural numbers. Each is a distinguished class of identifier in the syntax of\n    the language. *)\nRequire Export Psatz.\nRequire Export Bool.\nRequire Export Arith.\nRequire Export Psatz.\nRequire Export Program.\nRequire Export List.\nRequire Import ZArith.\nRequire Import ZArith.BinIntDef.\nRequire Export Reals.\nExport ListNotations.\n\nRequire Export BinNums.\nRequire Import BinPos BinNat.\n\nLocal Open Scope Z_scope.\n\n\nDefinition var    := nat.\nDefinition field  := nat.\nDefinition struct := nat.\nDefinition funid := nat.\n\n(* Useful shorthand in case we ever change representation. *)\nDefinition var_eq_dec := Nat.eq_dec.\n\n(** The Mode ([m]) is\n\nThe [mode], indicated by metavariable [m], is either [Checked] or [Unchecked]. *)\n\nInductive mode : Type :=\n  | Checked : mode\n  | Unchecked : mode.\n\n(** Types, <<w>>, are either a word type, [TNat, TPtr], a struct type, [TStruct],\n    or an array type, [TArray]. Struct types must be annotated with a struct identifier.\n    Array types are annotated with their lower-bound, upper-bound, and the (word) type of their elements.\n\n    The metavariable, [w], was chosen to abbreviate \"wide\" or compound types.\n\n    Notice that struct types can be self-referential. Furthermore, they are the only type\n    which may be self-referential.\n\n    Example:\n\n    In\n\n      struct foo {\n        self^struct foo\n      }\n\n      let my_foo = malloc@struct foo in\n      let my_foo_self = &my_foo->self in\n      *my_foo_self = my_foo\n\n    the memory location which holds the `self` field of `my_foo` contains a pointer which\n    refers back to `my_foo`. Thus, `my_foo` is self-referential. *)\n\n(* a bound is either a value or a expression as the form of var + num. *)\nInductive bound : Set := | Num : Z -> bound | Var : var -> Z -> bound.\n\nInductive type : Type :=\n  | TNat : type\n  | TPtr : mode -> type -> type\n  | TStruct : struct -> type\n  | TArray : bound -> bound -> type -> type\n  | TNTArray : bound -> bound -> type -> type.\n\nDefinition type_eq_dec (t1 t2 : type): {t1 = t2} + {~ t1 = t2}.\n  repeat decide equality.\nDefined.\n\n(** Word types, <<t>>, are either numbers, [WTNat], or pointers, [WTPtr].\n    Pointers must be annotated with a [mode] and a (compound) [type]. *)\n\n\nInductive word_type : type -> Prop :=\n  | WTNat : word_type (TNat)\n  | WTPtr : forall m w, word_type (TPtr m w).\n\nHint Constructors word_type.\n\n(** Fields, [fs], are a vector of fields paired with their (word) type.\n    We represent this as a finite list map. The keys are the field identifier, and the\n    values are its (word) type.\n *)\n\nRequire Import OrderedTypeEx.\n\nModule Fields := FMapList.Make Nat_as_OT.\n\nDefinition fields := Fields.t type.\n\n(** Structdefs, [D], are a map of structures to fields.\n\n    Structdefs also have a well-formedness predicate. This says that a structdef\n    cannot reference structures that it does not define. *)\n\nModule StructDef := Map.Make Nat_as_OT.\n\nDefinition structdef := StructDef.t fields.\n\n\nModule Env := Map.Make Nat_as_OT.\nModule EnvFacts := FMapFacts.Facts (Env).\nDefinition env := Env.t type.\n\nDefinition empty_env := @Env.empty type.\n\nDefinition venv := Env.t var.\n\nDefinition empty_venv := @Env.empty var.\n\n(* well_bound definition might not needed in the type system, since the new expr_wf will guarantee that. *)\nInductive well_bound_in : env -> bound -> Prop :=\n   | well_bound_in_num : forall env n, well_bound_in env (Num n)\n   | well_bound_in_var : forall env x y, Env.MapsTo x TNat env -> well_bound_in env (Var x y).\n\nInductive well_type_bound_in : env -> type -> Prop :=\n   | well_type_bound_in_nat : forall env, well_type_bound_in env TNat\n   | well_type_bound_in_ptr : forall m t env, well_type_bound_in env t -> well_type_bound_in env (TPtr m t)\n   | well_type_bound_in_struct : forall env T, well_type_bound_in env (TStruct T)\n   | well_type_bound_in_array : forall env l h t, well_bound_in env l -> well_bound_in env h -> \n                                      well_type_bound_in env t -> well_type_bound_in env (TArray l h t)\n   | well_type_bound_in_ntarray : forall env l h t, well_bound_in env l -> well_bound_in env h -> \n                                      well_type_bound_in env t -> well_type_bound_in env (TNTArray l h t).\n\n(* Definition of simple type meaning that the type has no bound variables. *)\nInductive simple_type : type -> Prop := \n  | SPTNat : simple_type TNat\n  | SPTPtr : forall m w, simple_type w -> simple_type (TPtr m w)\n  | SPTStruct : forall t, simple_type (TStruct t)\n  | SPTArray : forall l h t, simple_type t -> simple_type (TArray (Num l) (Num h) t)\n  | SPTNTArray : forall l h t, simple_type t -> simple_type (TNTArray (Num l) (Num h) t).\n\n\nInductive type_wf (D : structdef) : type -> Prop :=\n  | WFTNat : type_wf D (TNat)\n  | WFTPtr : forall m w, type_wf D w -> type_wf D (TPtr m w)\n  | WFTStruct : forall T,\n      (exists (fs : fields), StructDef.MapsTo T fs D) ->\n      type_wf D (TStruct T)\n  | WFArray : forall l h t,\n      word_type t ->\n      type_wf D t ->\n      type_wf D (TArray l h t)\n  | WFNTArry : forall l h t,       \n      word_type t ->\n      type_wf D t ->\n      type_wf D (TNTArray l h t).\n\nDefinition fields_wf (D : structdef) (fs : fields) : Prop :=\n  forall f t,\n    Fields.MapsTo f t fs ->\n    word_type t /\\ type_wf D t /\\ simple_type t.\n\nDefinition structdef_wf (D : structdef) : Prop :=\n  forall (T : struct) (fs : fields),\n    StructDef.MapsTo T fs D ->\n    fields_wf D fs.\n\n\nInductive theta_elem : Type := TopElem | GeZero.\n\nModule Theta := Map.Make Nat_as_OT.\n\nDefinition theta := Theta.t theta_elem.\n\nDefinition empty_theta := @Theta.empty theta_elem.\n\n(* This defines the subtyping relation. *)\nInductive nat_leq (T:theta) : bound -> bound -> Prop :=\n  | nat_leq_num : forall l h, l <= h -> nat_leq T (Num l) (Num h)\n  | nat_leq_var : forall x l h, l <= h -> nat_leq T (Var x l) (Var x h)\n  | nat_leq_num_var : forall x l h, Theta.MapsTo x GeZero T -> l <= h -> nat_leq T (Num l) (Var x h).\n\nLemma nat_leq_trans : forall T a b c,  nat_leq T a b -> nat_leq T b c -> nat_leq T a c.\nProof.\n  intros.\n  destruct a. destruct b. destruct c.\n  inv H. inv H0.\n  apply nat_leq_num. lia.\n  inv H. inv H0. apply nat_leq_num_var; try easy. lia.\n  destruct c. inv H0.\n  inv H. inv H0.\n  constructor. easy. lia.\n  inv H. inv H0.\n  constructor. lia.\nQed.\n\n(* This is the Checked-C subtyping relationship. If x <= y, then one can cast the pointer x to y, \n   and y is allowed to use in any context of using x. *)\nInductive subtype (D : structdef) (Q:theta) : type -> type -> Prop :=\n  | SubTyRefl : forall t, subtype D Q t t\n  | SubTyBot : forall m l h t, word_type t -> nat_leq Q (Num 0) l -> nat_leq Q h (Num 1)\n                           -> subtype D Q (TPtr m t) (TPtr m (TArray l h t))\n  | SubTyOne : forall m l h t, word_type t -> nat_leq Q l (Num 0) -> nat_leq Q (Num 1) h\n                             -> subtype D Q (TPtr m (TArray l h t)) (TPtr m t)\n  | SubTyOneNT : forall m l h t, word_type t -> nat_leq Q l (Num 0) ->nat_leq Q (Num 1) h\n                             -> subtype D Q (TPtr m (TNTArray l h t)) (TPtr m t)\n  | SubTySubsume : forall l h l' h' t m,\n    nat_leq Q l l' -> nat_leq Q h' h -> \n    subtype D Q (TPtr m (TArray l h t)) (TPtr m (TArray l' h' t))\n  | SubTyNtArray : forall l h l' h' t m,\n    nat_leq Q l l' -> nat_leq Q h' h ->\n                subtype D Q (TPtr m (TNTArray l h t)) (TPtr m (TArray l' h' t))\n  | SubTyNtSubsume : forall l h l' h' t m,\n    nat_leq Q l l' -> nat_leq Q h' h -> \n    subtype D Q (TPtr m (TNTArray l h t)) (TPtr m (TNTArray l' h' t))\n  | SubTyStructArrayField_1 : forall (T : struct) (fs : fields) m,\n    StructDef.MapsTo T fs D ->\n    Some (TNat) = (Fields.find 0%nat fs) ->\n    subtype D Q (TPtr m (TStruct T)) (TPtr m (TNat))\n  | SubTyStructArrayField_2 : forall (T : struct) (fs : fields) m l h,\n    StructDef.MapsTo T fs D ->\n    Some (TNat) = (Fields.find 0%nat fs) -> nat_leq Q (Num 0) l -> nat_leq Q h (Num 1) ->\n    subtype D Q (TPtr m (TStruct T)) (TPtr m (TArray l h (TNat))).\n\n(* Subtyping transitivity. *)\nLemma subtype_trans : forall D Q t t' m w, subtype D Q t (TPtr m w) -> subtype D Q (TPtr m w) t' -> subtype D Q t t'.\nProof.\n intros. inv H; inv H0.\n      * eapply SubTyRefl.\n      * eapply SubTyBot;eauto.\n      * eapply SubTyOne; eauto.\n      * eapply SubTyOneNT; eauto.\n      * eapply SubTySubsume; eauto.\n      * eapply SubTyNtArray; eauto.\n      * eapply SubTyNtSubsume; eauto.\n      * eapply SubTyStructArrayField_1; eauto.\n      * eapply SubTyStructArrayField_2; eauto.\n      * eapply SubTyBot; eauto.\n      * inv H2.\n      * eapply SubTyRefl.\n      * eapply SubTyBot;eauto. eapply nat_leq_trans. apply H5. assumption.\n         eapply nat_leq_trans. apply H9. assumption.\n      * eapply SubTyOne; eauto.\n      * eapply SubTySubsume;eauto.\n        eapply nat_leq_trans. apply H5. assumption.\n        eapply nat_leq_trans. apply H8. assumption.\n      * inv H3.\n      * inv H3.\n      * inv H3.\n      * inv H3.\n      * inv H3.\n      * inv H3.\n      * inv H3.\n      * eapply SubTyOneNT; eauto.\n      * eapply SubTyNtArray; eauto.\n        eapply nat_leq_trans. apply H5. assumption.\n        eapply nat_leq_trans. apply H8. assumption.\n      * inv H3.\n      * inv H3.\n      * inv H3.\n      * inv H3.\n      * inv H3.\n      * inv H3.\n      * inv H3.\n      * eapply SubTySubsume; eauto.\n      * inv H2.\n      * eapply SubTyOne; eauto.\n        eapply nat_leq_trans. apply H4. assumption.\n        eapply nat_leq_trans. apply H9. assumption.\n      * eapply SubTySubsume; eauto.\n        eapply nat_leq_trans. apply H4. assumption.\n        eapply nat_leq_trans. apply H8. assumption.\n      * eapply SubTyNtArray; eauto.\n      * inv H2.\n      * eapply SubTyOneNT; eauto.\n        eapply nat_leq_trans. apply H4. assumption.\n        eapply nat_leq_trans. apply H9. assumption.\n      * eapply SubTyNtArray; eauto.\n        eapply nat_leq_trans. apply H4. assumption.\n        eapply nat_leq_trans. apply H8. assumption.\n      * eapply SubTyNtSubsume; eauto.\n      * inv H2.\n      * eapply SubTyOneNT; eauto.\n        eapply nat_leq_trans. apply H4. assumption.\n        eapply nat_leq_trans. apply H9. assumption.\n      * eapply SubTyNtArray; eauto.\n        eapply nat_leq_trans. apply H4. assumption.\n        eapply nat_leq_trans. apply H8. assumption.\n      * eapply SubTyNtSubsume; eauto.\n        eapply nat_leq_trans. apply H4. assumption.\n        eapply nat_leq_trans. apply H8. assumption.\n      * eapply SubTyStructArrayField_1; eauto.\n      * eapply SubTyStructArrayField_2; eauto.\n      * eapply SubTyStructArrayField_2; eauto.\n      * inv H2.\n      * eapply SubTyStructArrayField_1; eauto.\n      * eapply SubTyStructArrayField_2; eauto.\n        eapply nat_leq_trans. apply H6. assumption.\n        eapply nat_leq_trans. apply H10. assumption.\nQed.\n\n\n\n(* Defining stack. *)\nModule Stack := Map.Make Nat_as_OT.\n\nDefinition stack := Stack.t (Z * type).\n\nDefinition empty_stack := @Stack.empty (Z * type).\n\nDefinition arg_stack := Stack.t bound.\n\nDefinition empty_arg_stack := @Stack.empty bound.\n\n(*\nDefinition dyn_env := Stack.t type.\n\nDefinition empty_dyn_env := @Stack.empty type.\n*)\n\nDefinition cast_bound (s:stack) (b:bound) : option bound :=\n   match b with Num n => Some (Num n)\n             | Var x n => (match (Stack.find x s) with Some (v,t) => Some (Num (n+v)) | None => None end)\n   end.\n\nInductive cast_type_bound (s:stack) : type -> type -> Prop :=\n   | cast_type_bound_nat : cast_type_bound s (TNat) (TNat)\n   | cast_type_bound_ptr : forall c t t', cast_type_bound s t t'\n                 -> cast_type_bound s (TPtr c t) (TPtr c t')\n   | cast_type_bound_array : forall l l' h h' t t', cast_bound s l = Some l' -> cast_bound s h = Some h' ->\n                  cast_type_bound s t t' -> cast_type_bound s (TArray l h t) (TArray l' h' t')\n   | cast_type_bound_ntarray : forall l l' h h' t t', cast_bound s l = Some l' -> cast_bound s h = Some h' ->\n                  cast_type_bound s t t' -> cast_type_bound s (TNTArray l h t) (TNTArray l' h' t')\n   | cast_type_bound_struct : forall t, cast_type_bound s (TStruct t) (TStruct t).\n\n\n(* Compared to the Checked-C in Redex, there are two difference.\n   First, function arguments are restricted to constants and variables.\n    We enforces this by argument well-formedness.\n    Second, We split if expression into EIfDef where it has the form: if *x then e1 else e2,\n    and EIf where it allows an arbitary expression with the type int.\n    We have the distinct for simplifying the proof. Now, the EIfDef represents the second semantic context rule in Fig.4,\n    while the latter represents the first one, and it will not have any side-effects. \n    *)\nInductive expression : Type :=\n  | ELit : Z -> type -> expression\n  | EVar : var -> expression\n  | EStrlen : var -> expression\n  | ECall : funid -> list expression -> expression\n  | ERet : var -> Z* type -> expression -> expression (* return new value, old value and the type. *)\n  | EDynCast : type -> expression -> expression\n  | ELet : var -> expression -> expression -> expression\n  | EMalloc : type -> expression\n  | ECast : type -> expression -> expression\n  | EPlus : expression -> expression -> expression\n  | EFieldAddr : expression -> field -> expression\n  | EDeref : expression -> expression (*  * e *)\n  | EAssign : expression -> expression -> expression (* *e = e *)\n  | EIfDef : var -> expression -> expression -> expression (* if * x then e1 else e2. *)\n  | EIf : expression -> expression -> expression -> expression (* if e1 then e2 else e3. *)\n  | EUnchecked : expression -> expression.\n\nParameter fenv : env -> funid -> option (list (var * type) * type * expression * mode).\n\nDefinition FEnv : Type := env -> funid -> option (list (var * type) * type * expression * mode).\n\nInductive gen_arg_env : env -> list (var * type) -> env -> Prop :=\n    gen_arg_env_empty : forall env, gen_arg_env env [] env\n  | gen_ar_env_many : forall env x t tvl env', gen_arg_env env tvl env' -> gen_arg_env env ((x,t)::tvl) (Env.add x t env').\n\n(* Well-formedness definition. *)\nDefinition is_check_array_ptr (t:type) : Prop :=\n  match t with TPtr Checked (TArray l h t') => True\n             | TPtr Checked (TNTArray l h t') => True\n             | _ => False\n  end.\n\nDefinition is_array_ptr (t:type) : Prop :=\n  match t with TPtr m (TArray l h t') => True\n             | TPtr m (TNTArray l h t') => True\n             | _ => False\n  end.\n\n(*\nepxression well-fromedness.\nThe main thing is that constants need to have a simple_type meaning that no type variables inside.\nThis is because constants represent program values.\nIt does not make sense to say that a value is\nan integer while the type of the value is some type constructs with variable bounds.\n*)\n\nInductive expr_wf (D : structdef) (F:FEnv) : expression -> Prop :=\n  | WFELit : forall n t,\n    word_type t ->\n    type_wf D t ->\n    simple_type t ->\n    expr_wf D F (ELit n t)\n  | WFEVar : forall x,\n      expr_wf D F (EVar x)\n  | WFEStr : forall x,\n      expr_wf D F (EStrlen x)\n  | WFECall : forall x el, \n      (forall env v, fenv env x = Some v) ->\n      (forall e, In e el -> (exists n t, e = ELit n t\n                 /\\ word_type t /\\ type_wf D t /\\ simple_type t) \\/ (exists y, e = EVar y)) ->\n      expr_wf D F (ECall x el)\n  | WFRet : forall x a e, word_type (snd a) /\\ type_wf D (snd a) /\\ simple_type (snd a)\n          -> expr_wf D F e -> expr_wf D F (ERet x a e)\n  | WFEDynCast : forall t e, \n     is_array_ptr t -> type_wf D t -> expr_wf D F e -> expr_wf D F (EDynCast t e)\n  | WFELet : forall x e1 e2,\n      expr_wf D F e1 ->\n      expr_wf D F e2 ->\n      expr_wf D F (ELet x e1 e2)\n  | WFEIFDef : forall x e1 e2,\n      expr_wf D F e1 ->\n      expr_wf D F e2 ->\n      expr_wf D F (EIfDef x e1 e2)\n  | WFEIF : forall e1 e2 e3,\n      expr_wf D F e1 ->\n      expr_wf D F e2 ->\n      expr_wf D F e3 ->\n      expr_wf D F (EIf e1 e2 e3)\n  | WFEMalloc : forall w,\n      type_wf D w -> expr_wf D F (EMalloc w)\n  | WFECast : forall t e,\n      word_type t ->\n      type_wf D t ->\n      expr_wf D F e ->\n      expr_wf D F (ECast t e)\n  | WFEPlus : forall e1 e2,\n      expr_wf D F e1 ->\n      expr_wf D F e2 ->\n      expr_wf D F (EPlus e1 e2)\n  | WFEFieldAddr : forall e f,\n      expr_wf D F e ->\n      expr_wf D F (EFieldAddr e f)\n  | WFEDeref : forall e,\n      expr_wf D F e ->\n      expr_wf D F (EDeref e)\n  | WFEAssign : forall e1 e2,\n      expr_wf D F e1 ->\n      expr_wf D F e2 ->\n      expr_wf D F (EAssign e1 e2)\n  | WFEUnchecked : forall e,\n      expr_wf D F e ->\n      expr_wf D F (EUnchecked e).\n\n\n(* Standard substitution.\n   In a let, if the bound variable is the same as the one we're substituting,\n   then we don't substitute under the lambda. *)\n \n\n(** Values, [v], are expressions [e] which are literals. *)\n\nInductive value (D : structdef) : expression -> Prop :=\n  VLit : forall (n : Z) (t : type),\n    word_type t ->\n    type_wf D t ->\n    simple_type t ->\n    value D (ELit n t).\n\nHint Constructors value.\n\n(** Note: Literal is a less strong version of value that doesn't\n    enforce the syntactic constraints on the literal type. *)\n\nInductive literal : expression -> Prop :=\n  Lit : forall (n : Z) (t : type),\n    literal (ELit n t).\n\nHint Constructors literal.\n\n(** * Dynamic Semantics *)\n\n(** Heaps, [H], are a list of literals indexed by memory location.\n    Memory locations are just natural numbers, and literals are\n    numbers paired with their type (same as [ELit] constructor).\n    Addresses are offset by 1 -- looking up address 7 will translate\n    to index 6 in the list.\nlls\n    Heaps also have a well-formedness predicate, which says that\n    all memory locations must be annotated with a well-formed word\n    type.\n\n    Finally, the only operation we can perform on a heap is allocation.\n    This operation is defined by the partial function [allocate]. This\n    function takes [D] a structdef, [H] a heap, and [w] a (compound) type.\n    The function is total assuming usual well-formedness conditions of [D] and\n    [w]. It gives back a pair [(base, H')] where [base] is the base pointer for\n    the allocated region and [H'] is [H] with the allocation. *)\n\n\nModule Heap := Map.Make Z_as_OT.\n\nDefinition heap : Type := Heap.t (Z * type).\n\nDefinition heap_wf (D : structdef) (H : heap) : Prop :=\n  forall (addr : Z), 0 < addr <= (Z.of_nat (Heap.cardinal H)) <-> Heap.In addr H.\n\nSection allocation.\n\nImport ListNotations.\nImport MonadNotation.\nLocal Open Scope monad_scope.\n\nPrint replicate.\nDefinition Zreplicate (z:Z) (T : type) : (list type) :=\nmatch z with\n  |Z.pos p => (replicate (Pos.to_nat p) T)\n  |_ => []\nend.\n\n(* Changed this, to return the lower bound *)\nDefinition allocate_meta (D : structdef) (w : type)\n  : option (Z * list type) :=\n  match w with\n  | TStruct T =>\n    fs <- StructDef.find T D ;;\n    ret (0, List.map snd (Fields.elements fs))\n  | TArray (Num l) (Num h) T =>\n    Some (l, Zreplicate (h - l) T)\n  | TNTArray (Num l) (Num h) T =>\n    Some (l, Zreplicate (h - l + 1) T)\n  | _ => Some (0, [w])\n  end.\n\n\nDefinition allocate_meta_no_bounds (D : structdef) (w : type)\n  : option (list type) :=\n  match (allocate_meta D w) with\n  | Some( _ , x) => Some x\n  | None => None\nend.\n\nLemma allocate_meta_implies_allocate_meta_no_bounds : forall D w ts b,\nallocate_meta D w = Some (b, ts) -> allocate_meta_no_bounds D w = Some ts.\nProof.\n  intros. unfold allocate_meta_no_bounds. rewrite H. reflexivity.\nQed.\n\n(* allocate_meta can succeed with bad bounds. allocate itself shouldn't *)\nDefinition allocate (D : structdef) (H : heap) (w : type) : option (Z * heap) :=\n  let H_size := Z.of_nat(Heap.cardinal H) in\n  let base   := H_size + 1 in\n  match allocate_meta D w with\n  | Some (0, am) => \n     let (_, H') := List.fold_left\n                  (fun (acc : Z * heap) (t : type) =>\n                     let (sizeAcc, heapAcc) := acc in\n                     let sizeAcc' := sizeAcc + 1 in\n                     let heapAcc' := Heap.add sizeAcc' (0, t) heapAcc in\n                     (sizeAcc', heapAcc'))\n                  am\n                  (H_size, H)\n     in\n     ret (base, H')\n  | _ => None\n  end.\n\nEnd allocation.\n\n(** Results, [r], are an expression ([RExpr]), null dereference error ([RNull]), or\n    array out-of-bounds error ([RBounds]). *)\n\nInductive result : Type :=\n  | RExpr : expression -> result\n  | RNull : result\n  | RBounds : result.\n\n(** Contexts, [E], are expressions with a hole in them. They are used in the standard way,\n    for lifting a small-step reduction relation to compound expressions.\n\n    We define two functions on contexts: [in_hole] and [mode_of]. The [in_hole] function takes a context,\n    [E] and an expression [e] and produces an expression [e'] which is [E] with its hole filled by [e].\n    The [mode_of] function takes a context, [E], and returns [m] (a mode) indicating whether the context has a\n    subcontext which is unchecked. *)\n\nInductive context : Type :=\n  | CHole : context\n  | CLet : var -> context -> expression -> context\n  | CPlusL : context -> expression -> context\n  | CPlusR : Z -> type -> context -> context\n  | CFieldAddr : context -> field -> context\n  | CDynCast : type -> context -> context\n  | CCast : type -> context -> context\n  | CDeref : context -> context\n  | CAssignL : context -> expression -> context\n  | CAssignR : Z -> type -> context -> context\n  | CRet : var -> (Z*type) -> context -> context\n  | CIf : context -> expression -> expression -> context\n  | CUnchecked : context -> context.\n\nFixpoint in_hole (e : expression) (E : context) : expression :=\n  match E with\n  | CHole => e\n  | CLet x E' e' => ELet x (in_hole e E') e'\n  | CPlusL E' e' => EPlus (in_hole e E') e'\n  | CPlusR n t E' => EPlus (ELit n t) (in_hole e E')\n  | CFieldAddr E' f => EFieldAddr (in_hole e E') f\n  | CDynCast t E' => EDynCast t (in_hole e E')\n  | CCast t E' => ECast t (in_hole e E')\n  | CDeref E' => EDeref (in_hole e E')\n  | CAssignL E' e' => EAssign (in_hole e E') e'\n  | CAssignR n t E' => EAssign (ELit n t) (in_hole e E')\n  | CRet x a E' => ERet x a (in_hole e E')\n  | CIf E' e1 e2 => EIf (in_hole e E') e1 e2\n  | CUnchecked E' => EUnchecked (in_hole e E')\n  end.\n\n\nFixpoint mode_of (E : context) : mode :=\n  match E with\n  | CHole => Checked\n  | CLet _ E' _ => mode_of E'\n  | CPlusL E' _ => mode_of E'\n  | CPlusR _ _ E' => mode_of E'\n  | CFieldAddr E' _ => mode_of E'\n  | CDynCast _ E' => mode_of E'\n  | CCast _ E' => mode_of E'\n  | CDeref E' => mode_of E'\n  | CAssignL E' _ => mode_of E'\n  | CAssignR _ _ E' => mode_of E'\n  | CRet x a E' => mode_of E'\n  | CIf E' e1 e2 => mode_of E'\n  | CUnchecked E' => Unchecked\n  end.\n\nFixpoint compose (E_outer : context) (E_inner : context) : context :=\n  match E_outer with\n  | CHole => E_inner\n  | CLet x E' e' => CLet x (compose E' E_inner) e'\n  | CPlusL E' e' => CPlusL (compose E' E_inner) e'\n  | CPlusR n t E' => CPlusR n t (compose E' E_inner)\n  | CFieldAddr E' f => CFieldAddr (compose E' E_inner) f\n  | CDynCast t E' => CDynCast t (compose E' E_inner)\n  | CCast t E' => CCast t (compose E' E_inner)\n  | CDeref E' => CDeref (compose E' E_inner)\n  | CAssignL E' e' => CAssignL (compose E' E_inner) e'\n  | CAssignR n t E' => CAssignR n t (compose E' E_inner)\n  | CRet x a E' => CRet x a (compose E' E_inner)\n  | CIf E' e1 e2 => CIf (compose E' E_inner) e1 e2\n  | CUnchecked E' => CUnchecked (compose E' E_inner)\n  end.\n\nLemma hole_is_id : forall e,\n    in_hole e CHole = e.\nProof.\n  intros.\n  reflexivity.\nQed.\n\nLemma compose_correct : forall E_outer E_inner e0,\n    in_hole (in_hole e0 E_inner) E_outer = in_hole e0 (compose E_outer E_inner).\nProof.\n  intros.\n  induction E_outer; try reflexivity; try (simpl; rewrite IHE_outer; reflexivity).\nQed.\n\nLemma compose_unchecked : forall E_outer E_inner,\n    mode_of E_inner = Unchecked ->\n    mode_of (compose E_outer E_inner) = Unchecked.\nProof.\n  intros.\n  induction E_outer; try reflexivity; try (simpl; rewrite IHE_outer; reflexivity); try assumption.\nQed.\n\n(* TODO: say more *)\n(** The single-step reduction relation, [H; e ~> H'; r]. *)\n\nDefinition eval_bound (s:stack) (b:bound) : option bound :=\n   match b with Num n => Some (Num n)\n             | Var x n => (match (Stack.find x s) with Some (v,t) => Some (Num (v + n)) | None => None end)\n   end.\n\nDefinition eval_type_bound (s : stack) (t : type) : option type := \n  match t with | TPtr c (TArray l h t) => \n                   match eval_bound s l with None => None\n                                         | Some l' => \n                     match eval_bound s h with None => None\n                                      | Some h' => \n                                Some (TPtr c (TArray l' h' t))\n                     end\n                   end\n              | TPtr c (TNTArray l h t) => \n                   match eval_bound s l with None => None\n                                         | Some l' => \n                     match eval_bound s h with None => None\n                                      | Some h' => \n                                Some (TPtr c (TNTArray l' h' t))\n                     end\n                   end\n              | _ => Some t\n  end.\n\n\nLemma eval_type_bound_array_ptr : forall s t,\n    eval_type_bound s t = None -> (exists  c l h t', t = TPtr c (TArray l h t') \\/ t = TPtr c (TNTArray l h t')).\nProof.\n intros. unfold eval_type_bound in H.\n destruct t; inversion H.\n destruct t; inversion H.\n exists m. exists b. exists b0. exists t.\n left. reflexivity.\n exists m. exists b. exists b0. exists t.\n right. reflexivity.\nQed.\n\n\nDefinition NTHit (s : stack) (x : var) : Prop :=\n   match Stack.find x s with | Some (v,TPtr m (TNTArray l (Num 0) t)) => True\n                          | _ => False\n   end.\n\nDefinition add_nt_one (s : stack) (x:var) : stack :=\n   match Stack.find x s with | Some (v,TPtr m (TNTArray l (Num h) t)) \n                         => Stack.add x (v,TPtr m (TNTArray l (Num (h+1)) t)) s\n                              (* This following case will never happen since the type in a stack is always evaluated. *)\n                             | _ => s\n   end.\n\nDefinition is_rexpr (r : result) : Prop :=\n   match r with RExpr x => True\n              | _ => False\n   end.\n\n\nDefinition sub_bound (b:bound) (n:Z) : (bound) :=\n  match b with Num m => Num (m - n)\n           | Var x m => Var x (m - n)\n  end.\n\nDefinition sub_type_bound (t:type) (n:Z) : type :=\n   match t with TPtr Checked (TArray l h t1) => TPtr Checked (TArray (sub_bound l n) (sub_bound h n) t1)\n              | TPtr Checked (TNTArray l h t1) => TPtr Checked (TNTArray (sub_bound l n) (sub_bound h n) t1)\n              | _ => t\n   end.\n\nDefinition malloc_bound (t:type) : Prop :=\n   match t with (TArray (Num l) (Num h) t) => (l = 0 /\\ h > 0)\n              | (TNTArray (Num l) (Num h) t) => (l = 0 /\\ h > 0)\n              | _ => True\n   end.\n\nDefinition change_strlen_stack (s:stack) (x : var) (m:mode) (t:type) (l n n' h:Z) :=\n     if n' <=? h then s else @Stack.add (Z * type) x (n,TPtr m (TNTArray (Num l) (Num n') t)) s. \n\nFixpoint gen_stack (vl:list var)  (es:list expression) (e:expression) : option expression := \n   match vl with [] => Some e\n              | (v::vl') => match es with [] => None | e1::el =>\n                                    match gen_stack vl' el e with None => None\n                                                    | Some new_e => Some (ELet v e1 new_e)\n                                    end\n                              end\n   end.\n\n\nDefinition get_high_ptr (t : type) := \n    match t with (TPtr a (TArray l h t')) => Some h\n              | (TPtr a (TNTArray l h t')) => Some h\n              | _ => None\n    end.\n\nDefinition get_high (t : type) := \n    match t with ((TArray l h t')) => Some h\n              | ((TNTArray l h t')) => Some h\n              | _ => None\n    end.\n\nDefinition get_low_ptr (t : type) := \n    match t with (TPtr a (TArray l h t')) => Some l\n              | (TPtr a (TNTArray l h t')) => Some l\n              | _ => None\n    end.\n\nDefinition get_low (t : type) := \n    match t with ((TArray l h t')) => Some l\n              | ((TNTArray l h t')) => Some l\n              | _ => None\n    end.\n\n(* TODO: say more *)\n(** The compatible closure of [H; e ~> H'; r], [H; e ->m H'; r].\n\n    We also define a convenience predicate, [reduces H e], which holds\n    when there's some [m], [H'], and [r] such that [H; e ->m H'; r]. *)\nDefinition get_good_dept (e:expression) :=\n  match e with ELit v t => Some (Num v)\n             | EVar x => Some (Var x 0)\n             | _ => None\n  end.\n\nFixpoint get_dept_map (l:list (var * type)) (es:list expression) :=\n   match l with [] => Some []\n       | (x,TNat)::xl => (match es with e::es' => match get_good_dept e with None => None \n                                                        | Some b => match (get_dept_map xl es') with None => None\n                                                                           | Some xl' => Some ((x,b)::xl')\n                                                                    end\n                                                  end\n                                      | _ => None\n                          end)\n       | (x,y)::xl => match es with (e::es') => get_dept_map xl es' \n                                 | _ => None\n                      end\n    end.\n\nDefinition subst_bound (b:bound) (x:var) (b1:bound) := \n   match b with Num n => (Num n)\n           | Var y n => \n        if var_eq_dec y x then\n           match b1 with (Num m) => (Num (n+m))\n                         | (Var z m) => (Var z (n+m))\n           end\n        else Var y n\n   end.\n\nFixpoint subst_bounds (b:bound) (s: list (var*bound)) :=\n  match s with [] => b\n            | (x,b1)::xs => subst_bounds (subst_bound b x b1) xs\n  end.\n\nFixpoint subst_type (s: list (var*bound)) (t:type) :=\n   match t with TNat => TNat\n            | TPtr m t' => TPtr m (subst_type s t')\n            | TStruct T => TStruct T\n            | TArray b1 b2 t => TArray (subst_bounds b1 s) (subst_bounds b2 s) (subst_type s t)\n            | TNTArray b1 b2 t => TNTArray (subst_bounds b1 s) (subst_bounds b2 s) (subst_type s t)\n  end.\n\nInductive eval_arg : stack -> expression -> type -> expression -> Prop :=\n    eval_lit : forall arg_s n t t' t'', cast_type_bound arg_s t t'' -> eval_arg arg_s (ELit n t') t (ELit n t'')\n  | eval_var : forall arg_s x n t t' t'', Stack.MapsTo x (n,t') arg_s\n            -> cast_type_bound arg_s t t'' -> eval_arg arg_s (EVar x) t (ELit n t'').\n\nInductive eval_el (AS: list (var*bound)) : stack -> list (var * type) -> list expression -> stack -> Prop :=\n    eval_el_empty : forall s, eval_el AS s [] [] s\n  | eval_el_many_2 : forall s s' e x n t t' tvl es, eval_arg s e (subst_type AS t) (ELit n t') ->\n              eval_el AS s tvl es s' -> \n              eval_el AS s ((x,t)::tvl) (e::es) (Stack.add x (n,t') s').\n\n\nDefinition is_nor_array_ptr (t:type) : Prop :=\n   match t with (TPtr m (TArray x y t')) => True\n              | _ => False\n   end.\n\nInductive get_root {D:structdef} : type -> type -> Prop :=\n    get_root_word : forall m t, word_type t -> get_root (TPtr m t) t\n  | get_root_array : forall m l h t, get_root (TPtr m (TArray l h t)) t\n  | get_root_ntarray : forall m l h t, get_root (TPtr m (TNTArray l h t)) t\n  | get_root_struct : forall m T f, StructDef.MapsTo T f D ->\n    Some (TNat) = (Fields.find 0%nat f) -> @get_root D (TPtr m (TStruct T)) TNat.\n\nInductive gen_rets  (AS: list (var*bound)) (S: stack) : list (var * type) -> list expression -> expression -> expression -> Prop :=\n   gen_rets_empty : forall e, gen_rets AS S [] [] e e\n  | gen_rets_many : forall x t t' xl e1 v es e2 e',  gen_rets AS S xl es e2 e' ->\n          eval_arg S e1 (subst_type AS t) (ELit v t') ->\n          gen_rets AS S ((x,t)::xl) (e1::es) e2 (ERet x (v,t') e').\n\n(* Checked C semantics. *)\nInductive step (D : structdef) (F:funid -> option (list (var * type) * type * expression * mode)) : stack -> heap \n                     -> expression -> stack -> heap -> result -> Prop :=\n  | SVar : forall s H x v t,\n      (Stack.MapsTo x (v,t) s) ->\n      step D F s H (EVar x) s H (RExpr (ELit v t))\n  | Strlen : forall s H x n n' m l h t t1, \n     h > 0 -> l <= 0 -> 0 <= n' ->\n     (Stack.MapsTo x (n,(TPtr m (TNTArray (Num l) (Num h) t))) s) ->\n     (forall i , n <= i < n+n' -> (exists n1, Heap.MapsTo i (n1,t1) H /\\ n1 <> 0))\n      -> Heap.MapsTo (n+n') (0,t1) H ->\n            step D F s H (EStrlen x) (change_strlen_stack s x m t l n n' h) H (RExpr (ELit n' TNat))\n  | StrlenHighOOB : forall s H x n t m l h,\n      h <= 0 ->\n     (Stack.MapsTo x (n,(TPtr m (TNTArray l (Num h) t))) s) ->\n      step D F s H (EStrlen x) s H RBounds\n  | StrlenLowOOB : forall s H x n t m l h,\n      l > 0 ->\n     (Stack.MapsTo x (n,(TPtr m (TNTArray (Num l) h t))) s) ->\n      step D F s H (EStrlen x) s H RBounds\n  | StrlenNull : forall s H x t n m l h,\n      n <= 0 -> \n     (Stack.MapsTo x (n,(TPtr m (TNTArray l h t))) s) ->\n      step D F s H (EStrlen x) s H RNull\n  | SCall : forall AS s s' H x el t tvl e e' m, \n           F x = Some (tvl,t,e,m) ->\n           get_dept_map tvl el = Some AS ->\n           eval_el AS s tvl el s' -> \n           gen_rets AS s tvl el e e' ->\n          step D F s H (ECall x el) s' H (RExpr (ECast (subst_type AS t) e'))\n  | SLet : forall s H x n t e t',\n      cast_type_bound s t t' ->\n      step D F s H (ELet x (ELit n t) e) (Stack.add x (n,t') s) H \n                     (RExpr (ERet x (n,t') e))\n(*\n  | SRetSome : forall s H x a ta ntb n t, \n          step D F s H (ERet x ntb (Some (a,ta)) (ELit n t))\n                  (Stack.add x (a,ta) s) H (RExpr (ELit n t))\n*)\n  | SRetNone : forall s H x ntb n t, \n          step D F s H (ERet x ntb (ELit n t))\n                  (Stack.remove x s) H (RExpr (ELit n t))\n  | SPlusChecked : forall s H n1 t1 n2,\n      n1 > 0 -> is_check_array_ptr t1 -> \n      step D F\n         s H (EPlus (ELit n1 t1) (ELit n2 TNat))\n         s H (RExpr (ELit (n1 + n2) (sub_type_bound t1 n2)))\n  | SPlus : forall s H t1 n1 n2,\n       ~ is_check_array_ptr t1 -> \n      step D F\n         s H (EPlus (ELit n1 t1) (ELit n2 TNat))\n         s H (RExpr (ELit (n1 + n2) t1))\n  | SPlusNull : forall s H n1 t n2,\n      n1 <= 0 -> is_check_array_ptr t ->\n      step D F s H (EPlus (ELit n1 t) (ELit n2 (TNat))) s H RNull\n  | SCast : forall s H t n t' t'',\n      cast_type_bound s t t'' ->\n      step D F\n         s H (ECast t (ELit n t'))\n         s H (RExpr (ELit n t''))\n\n  | SCastNoArray : forall s H x y t n m t' t'',\n     ~ is_array_ptr (TPtr m t') -> cast_type_bound s t t'' ->\n      step D F\n        s H (EDynCast (TPtr m (TArray x y t)) (ELit n (TPtr m t')))\n        s H (RExpr (ELit n (TPtr m (TArray (Num 0) (Num 1) t''))))\n\n  | SCastArray : forall s H t n l h w l' h' w',\n     cast_type_bound s t (TPtr Checked (TArray (Num l) (Num h) w)) ->\n          l' <= l -> l < h -> h <= h' ->\n      step D F\n         s H (EDynCast t (ELit n (TPtr Checked (TArray (Num l') (Num h') w'))))\n         s H (RExpr (ELit n (TPtr Checked (TArray (Num l) (Num h) w))))\n\n  | SCastArrayLowOOB1 : forall s H t n l h w l' h' w',\n     cast_type_bound s t (TPtr Checked (TArray (Num l) (Num h) w)) ->\n           l < l' -> \n           step D F s H (EDynCast t (ELit n (TPtr Checked (TArray (Num l') (Num h') w'))))  s H RBounds\n  | SCastArrayLowOOB2 : forall s H t n l h w l' h' w',\n     cast_type_bound s t (TPtr Checked (TArray (Num l) (Num h) w)) ->\n           h <= l -> \n           step D F s H (EDynCast t (ELit n (TPtr Checked (TArray (Num l') (Num h') w')))) s H RBounds\n  | SCastArrayHighOOB1 : forall s H t n l h w l' h' w',\n     cast_type_bound s t (TPtr Checked (TArray (Num l) (Num h) w)) ->\n           h' < h -> \n           step D F s H (EDynCast t (ELit n (TPtr Checked (TArray (Num l') (Num h') w')))) s H RBounds\n  | SCastNTArray : forall s H t n l h w l' h' w',\n     cast_type_bound s t (TPtr Checked (TNTArray (Num l) (Num h) w)) ->\n          l' <= l -> l < h -> h <= h' ->\n      step D F s H (EDynCast t (ELit n (TPtr Checked (TNTArray (Num l') (Num h') w'))))\n         s H (RExpr (ELit n (TPtr Checked (TNTArray (Num l) (Num h) w)) ))\n  | SCastNTArrayLowOOB1 : forall s H t n l h w l' h' w',\n     cast_type_bound s t (TPtr Checked (TNTArray (Num l) (Num h) w)) ->\n           l < l' -> \n           step D F s H (EDynCast t (ELit n (TPtr Checked (TNTArray (Num l') (Num h') w')) )) s H RBounds\n  | SCastNTArrayLowOOB2 : forall s H t n l h w l' h' w',\n     cast_type_bound s t (TPtr Checked (TNTArray (Num l) (Num h) w)) ->\n           h <= l -> \n           step D F s H (EDynCast t (ELit n (TPtr Checked (TNTArray (Num l') (Num h') w')))) s H RBounds\n  | SCastNTArrayHighOOB1 : forall s H t n l h w l' h' w',\n     cast_type_bound s t (TPtr Checked (TNTArray (Num l) (Num h) w)) ->\n           h' < h -> \n           step D F s H (EDynCast t (ELit n (TPtr Checked (TNTArray (Num l') (Num h') w')))) s H RBounds\n\n  | SDeref : forall s H n n1 t1 t t2 tv,\n      cast_type_bound s t t2 ->\n      Heap.MapsTo n (n1, t1) H ->\n      (forall l h t', t2 = TPtr Checked (TArray (Num l) (Num h) t') -> h > 0 /\\ l <= 0) ->\n      (forall l h t', t2 = TPtr Checked (TNTArray (Num l) (Num h) t') -> h >= 0 /\\ l <= 0) ->\n      @get_root D t2 tv ->\n      step D F s H (EDeref (ELit n t)) s H (RExpr (ELit n1 tv))\n  | SDerefHighOOB : forall s H n t t' h,\n      h <= 0 ->\n      eval_type_bound s t = Some t' ->\n      get_high_ptr t' = Some (Num h) ->\n      step D F s H (EDeref (ELit n t)) s H RBounds\n  | SDerefLowOOB : forall s H n t t' l,\n      l > 0 ->\n      eval_type_bound s t = Some t' ->\n      get_low_ptr t' = Some (Num l) ->\n      step D F s H (EDeref (ELit n t)) s H RBounds\n  | SDerefNull : forall s H t n,\n      n <= 0 -> \n      step D F s H (EDeref (ELit n (TPtr Checked t))) s H RNull\n\n  | SAssign : forall s H n t na ta tv n1 t1 tv' H',\n      Heap.MapsTo n (na,ta) H ->\n      cast_type_bound s t tv ->\n      (forall l h t', tv = TPtr Checked (TArray (Num l) (Num h) t') -> h > 0 /\\ l <= 0) -> \n      (forall l h t', tv = TPtr Checked (TNTArray (Num l) (Num h) t') -> h > 0 /\\ l <= 0) -> \n      @get_root D tv tv' ->\n      H' = Heap.add n (n1, ta) H ->\n      step D F\n         s H  (EAssign (ELit n t) (ELit n1 t1))\n         s H' (RExpr (ELit n1 tv'))\n  | SAssignHighOOB : forall s H n t t' n1 t1 h,\n      h <= 0 ->\n      eval_type_bound s t = Some t' ->\n      get_high_ptr t' = Some (Num h) ->\n      step D F\n        s H (EAssign (ELit n t) (ELit n1 t1))\n        s H RBounds\n  | SAssignLowOOB : forall s H n t t' n1 t1 l,\n      l > 0 ->\n      eval_type_bound s t = Some t' ->\n      get_low_ptr t' = Some (Num l) ->\n      step D F\n         s H (EAssign (ELit n t) (ELit n1 t1))\n         s H RBounds\n  | SAssignNull : forall s H t tv w n n1 t',\n      n1 <= 0 ->\n      eval_type_bound s t = Some tv ->\n      tv = TPtr Checked w ->\n      step D F\n         s H (EAssign (ELit n1 t) (ELit n t')) s H RNull\n\n  | SFieldAddrChecked : forall s H n t (fi : field) n0 t0 T fs i fi ti,\n      n > 0 ->\n      t = TPtr Checked (TStruct T) ->\n      StructDef.MapsTo T fs D ->\n      Fields.MapsTo fi ti fs ->\n      List.nth_error (Fields.this fs) i = Some (fi, ti) ->\n      n0 = n + Z.of_nat(i) ->\n      t0 = TPtr Checked ti ->\n      word_type ti ->\n      step D F\n         s H (EFieldAddr (ELit n t) fi)\n         s H (RExpr (ELit n0 t0))\n  | SFieldAddrNull : forall s H (fi : field) n T,\n      n <= 0 ->\n      step D F\n         s H (EFieldAddr (ELit n (TPtr Checked (TStruct T))) fi)\n         s H RNull\n  | SFieldAddr : forall s H n t (fi : field) n0 t0 T fs i fi ti,\n      t = TPtr Unchecked (TStruct T) ->\n      StructDef.MapsTo T fs D ->\n      Fields.MapsTo fi ti fs ->\n      List.nth_error (Fields.this fs) i = Some (fi, ti) ->\n      n0 = n + Z.of_nat(i) ->\n      t0 = TPtr Unchecked ti ->\n      word_type ti ->\n      step D F\n        s H (EFieldAddr (ELit n t) fi)\n        s H (RExpr (ELit n0 t0))\n  | SMalloc : forall s H w w' H' n1,\n      cast_type_bound s w w' -> malloc_bound w' ->\n      allocate D H w' = Some (n1, H') ->\n      step D F\n         s H (EMalloc w)\n         s H' (RExpr (ELit n1 (TPtr Checked w')))\n  | SMallocHighOOB : forall s H w t' h,\n      h <= 0 ->\n      cast_type_bound s w t' ->\n      get_high t' = Some (Num h) ->\n      step D F s H (EMalloc w)  s H RBounds\n  | SMallocLowOOB : forall s H w t' l,\n      l <> 0 ->\n      cast_type_bound s w t' ->\n      get_low t' = Some (Num l) ->\n      step D F s H (EMalloc w)  s H RBounds\n\n  | SUnchecked : forall s H n t,\n      step D F s H (EUnchecked (ELit n t)) s H (RExpr (ELit n t))\n   | SIfDefTrueNotNTHit : forall s H x n t e1 e2 n1 t1, \n           Stack.MapsTo x (n,t) s ->\n           step D F s H (EDeref (ELit n t)) s H (RExpr (ELit n1 t1)) ->\n           n1 <> 0 -> ~ (NTHit s x) -> step D F s H (EIfDef x e1 e2) s H (RExpr e1)\n   | SIfDefTrueNTHit : forall s H x n t e1 e2 n1 t1, \n           Stack.MapsTo x (n,t) s ->\n           step D F s H (EDeref (ELit n t)) s H (RExpr (ELit n1 t1)) ->\n           n1 <> 0 -> (NTHit s x) -> step D F s H (EIfDef x e1 e2) (add_nt_one s x) H (RExpr e1)\n   | SIfDefFalse : forall s H x n t e1 e2 t1, \n           Stack.MapsTo x (n,t) s ->\n           step D F s H (EDeref (ELit n t)) s H (RExpr (ELit 0 t1)) ->\n              step D F s H (EIfDef x e1 e2) s H (RExpr e2)\n   | SIfDefFail : forall s H x n t e1 e2 r,\n           Stack.MapsTo x (n,t) s ->\n              ~ is_rexpr r \n              -> step D F s H (EDeref (ELit n t)) s H r\n                 -> step D F s H (EIfDef x e1 e2) s H r\n   | SIfTrue : forall s H n t e1 e2, n <> 0 -> \n           step D F s H (EIf (ELit n t) e1 e2) s H (RExpr e1)\n   | SIfFalse : forall s H t e1 e2, \n              step D F s H (EIf (ELit 0 t) e1 e2) s H (RExpr e2).\n\nHint Constructors step.\n\nInductive reduce (D : structdef) (F:funid -> option (list (var * type) * type * expression * mode)) : stack -> heap -> expression\n                              -> mode -> stack -> heap -> result -> Prop :=\n  | RSExp : forall H s e m H' s' e' E,\n      step D F s H e s' H' (RExpr e') ->\n      m = mode_of(E) ->\n      reduce D F s\n        H (in_hole e E)\n        m  s'\n        H' (RExpr (in_hole e' E))\n  | RSHaltNull : forall H s e m H' s' E,\n      step D F s H e s' H' RNull ->\n      m = mode_of(E) ->\n      reduce D F s\n        H (in_hole e E)\n        m s'\n        H' RNull\n  | RSHaltBounds : forall H s e m H' s'  E,\n      step D F s H e s' H' RBounds ->\n      m = mode_of(E) ->\n      reduce D F s\n        H (in_hole e E)\n        m s'\n        H' RBounds.\n\nHint Constructors reduce.\n\nDefinition reduces (D : structdef) (F:funid -> option (list (var * type) * type * expression * mode)) \n    (s : stack) (H : heap) (e : expression) : Prop :=\n  exists (m : mode) (s' : stack) (H' : heap) (r : result), reduce D F s H e m s' H' r.\n\nHint Unfold reduces.\n\n\n(* Defining function calls. *)\n\n(** * Static Semantics *)\n\nRequire Import Lists.ListSet.\n\nDefinition eq_dec_nt (x y : Z * type) : {x = y} + { x <> y}.\nrepeat decide equality.\nDefined. \n\nDefinition scope := set (Z *type)%type. \nDefinition empty_scope := empty_set (Z * type).\n\nDefinition scope_set_add (v:Z) (t:type) (s:scope) :=\n     match t with TPtr m (TStruct x) => set_add eq_dec_nt (v,TPtr m (TStruct x)) s\n               | _ => s\n     end.\n\nDefinition nt_array_prop (H:heap) (n:Z) (t:type) :=\n   match t with TPtr m (TNTArray (Num l) (Num h) t) =>\n    exists n' t', (0 <= n' /\\ Heap.MapsTo (n+n') (0,t') H\n     /\\ (forall i , n <= i < n+n' -> (exists n1, Heap.MapsTo i (n1,t') H /\\ n1 <> 0)))\n   | _ => True\n   end.\n\n\n(* Type check for a literal + simplifying the type. *)\nInductive well_typed_lit (D : structdef) (Q:theta) (H : heap) : scope -> Z -> type -> Prop :=\n  | TyLitInt : forall s n,\n      well_typed_lit D Q H s n TNat\n  | TyLitU : forall s n w,\n      well_typed_lit D Q H s n (TPtr Unchecked w)\n  | TyLitZero : forall s t,\n      well_typed_lit D Q H s 0 t\n  | TyLitRec : forall s n w t,\n      set_In (n, t) s ->\n      subtype D Q t (TPtr Checked w) ->\n      well_typed_lit D Q H s n (TPtr Checked w)\n  | TyLitC : forall sc n w t b ts,\n      simple_type w ->\n      subtype D Q (TPtr Checked w) (TPtr Checked t) ->\n      Some (b, ts) = allocate_meta D w ->\n      nt_array_prop H n (TPtr Checked t) ->\n      (forall k, b <= k < b + Z.of_nat(List.length ts) ->\n                 exists n' t',\n                   Some t' = List.nth_error ts (Z.to_nat (k - b)) /\\\n                   Heap.MapsTo (n + k) (n', t') H /\\\n                   well_typed_lit D Q H (scope_set_add n (TPtr Checked w) sc) n' t') ->\n      well_typed_lit D Q H sc n (TPtr Checked t).\n\n\nHint Constructors well_typed_lit.\n\n(** It turns out, the induction principle that Coq generates automatically isn't very useful. *)\n\n(** In particular, the TyLitC case does not have an induction hypothesis.\n    So, we prove an alternative induction principle which is almost identical but includes\n    an induction hypothesis for the TyLitC case.\n\n    TODO: write blog post about this *)\n\nLemma well_typed_lit_ind' :\n  forall (D : structdef) (Q:theta) (H : heap) (P : scope -> Z -> type -> Prop),\n    (forall (s : scope) (n : Z), P s n TNat) ->\n       (forall (s : scope) (n : Z) (w : type), P s n (TPtr Unchecked w)) ->\n       (forall (s : scope) (t : type), P s 0 t) ->\n       (forall (s : scope) (n : Z) (w : type) (t : type), set_In (n, t) s -> subtype D Q t (TPtr Checked w) -> P s n (TPtr Checked w)) ->\n       (forall (s : scope) (n : Z) (w : type) (t: type) (ts : list type) (b : Z),\n        simple_type w ->\n        subtype D Q (TPtr Checked w) (TPtr Checked t) ->\n        Some (b, ts) = allocate_meta D w ->\n        nt_array_prop H n (TPtr Checked t) ->\n        (forall k : Z,\n         b <= k < b + Z.of_nat (length ts) ->\n         exists (n' : Z) (t' : type),\n           Some t' = nth_error ts (Z.to_nat (k - b)) /\\\n           Heap.MapsTo (n + k) (n', t') H /\\\n           well_typed_lit D Q H (scope_set_add n (TPtr Checked w) s) n' t' /\\\n           P (scope_set_add n (TPtr Checked w) s) n' t') ->\n        P s n (TPtr Checked t)) -> forall (s : scope) (n : Z) (w : type), well_typed_lit D Q H s n w -> P s n w.\nProof.\n  intros D Q H P.\n  intros HTyLitInt\n         HTyLitU\n         HTyLitZero\n         HTyLitRec\n         HTyLitC.\n  refine (fix F s n t Hwtl :=\n            match Hwtl with\n            | TyLitInt _ _ _ s' n' => HTyLitInt s' n'\n            | TyLitU _ _ _ s' n' w' => HTyLitU s' n' w'\n            | TyLitZero _ _ _ s' t' => HTyLitZero s' t'\n            | TyLitRec _ _ _ s' n' w' t' Hscope Hsub => HTyLitRec s' n' w' t' Hscope Hsub\n            | TyLitC _ _ _ s' n' w' t' b ts HSim Hsub Hts Hnt IH =>\n              HTyLitC s' n' w' t' ts b HSim Hsub Hts Hnt (fun k Hk =>\n                                         match IH k Hk with\n                                         | ex_intro _ n' Htmp =>\n                                           match Htmp with\n                                           | ex_intro _ t' Hn't' =>\n                                             match Hn't' with\n                                             | conj Ht' Hrest1 =>\n                                               match Hrest1 with\n                                               | conj Hheap Hwt =>\n                                                 ex_intro _ n' (ex_intro _ t' \n                     (conj Ht' (conj Hheap (conj Hwt (F (scope_set_add _ (TPtr Checked w') s') n' t' Hwt)))))\n                                               end\n                                             end\n                                           end\n                                         end)\n            end).\nQed.\n\nDefinition is_ptr (t : type) : Prop :=\n    match t with TPtr m x => True \n              | _ => False\n    end.\n\nDefinition is_nt_ptr (t : type) : Prop :=\n    match t with TPtr m (TNTArray l h t') => True \n              | _ => False\n    end.\n\n(* equivalence of type based on semantic meaning. *)\nInductive type_eq (S : stack) : type -> type -> Prop := \n     | type_eq_refl: forall t , type_eq S t t\n     | type_eq_left: forall t1 t2, simple_type t1 -> cast_type_bound S t2 t1 -> type_eq S t2 t1\n     | type_eq_right: forall t1 t2, simple_type t2 -> cast_type_bound S t1 t2 -> type_eq S t1 t2.\n\n(* subtyping relation based on types. *)\nInductive subtype_stack (D: structdef) (Q:theta) (S:stack) : type -> type -> Prop :=\n     | subtype_same : forall t t', subtype D Q t t' -> subtype_stack D Q S t t'\n     | subtype_left : forall t1 t2 t2', simple_type t1 -> cast_type_bound S t2 t2'\n            -> subtype D Q t1 t2' -> subtype_stack D Q S t1 t2\n     | subtype_right : forall t1 t1' t2, simple_type t2 -> cast_type_bound S t1 t1'\n            -> subtype D Q t1' t2 -> subtype_stack D Q S t1 t2.\n\n(* The join opeartions. *)\nInductive join_type (D : structdef) (Q:theta) (S:stack) : type -> type -> type -> Prop :=\n   join_type_front : forall a b, subtype_stack D Q S a b -> join_type D Q S a b b\n  | join_type_end : forall a b, subtype_stack D Q S b a -> join_type D Q S a b a.\n\nDefinition good_lit (H:heap) (n:Z) (t:type):=\n      match t with TNat => True\n               | _ => n <= (Z.of_nat (Heap.cardinal H))\n      end.\n\n\nInductive well_bound_vars {A:Type}: list (var * A) -> bound -> Prop :=\n  | well_bound_vars_num : forall l n, well_bound_vars l (Num n)\n  | well_bound_vars_var : forall l y n, (exists a, In (y,a) l) -> well_bound_vars l (Var y n).\n\nInductive well_bound_vars_type {A:Type}: list (var * A) -> type -> Prop :=\n  | well_bound_vars_nat : forall l, well_bound_vars_type l (TNat)\n  | well_bound_vars_ptr : forall l c t, well_bound_vars_type l t -> well_bound_vars_type l (TPtr c t)\n  | well_bound_vars_struct : forall l t, well_bound_vars_type l (TStruct t)\n  | well_bound_vars_array : forall l b1 b2 t, well_bound_vars l b1 -> well_bound_vars l b2\n                        -> well_bound_vars_type l t -> well_bound_vars_type l (TArray b1 b2 t)\n  | well_bound_vars_ntarray : forall l b1 b2 t, well_bound_vars l b1 -> well_bound_vars l b2\n                        -> well_bound_vars_type l t -> well_bound_vars_type l (TNTArray b1 b2 t).\n\n\n(* well-typed_arg is basically the well_typed relationship but it deals with the function arguments.\n   We use it to enforce the function argument well-formedness in Coq.\n   In addition, we use it to aovide the need of mutual recursive inductive relations in Coq.\n   Otherwise, in order to prove a theorem related to types, \n   we need to prove it for a list of function arguments,\n   each of which also needs a proof for expression types, which can again be a function call.\n*)\nInductive well_typed_arg (D: structdef) (Q:theta) (H : heap) (env:env): \n                 expression -> type -> Prop :=\n     | ArgLit : forall n t t',\n      simple_type t ->\n      @well_typed_lit D Q H empty_scope n t' ->\n      subtype D Q t' t ->\n      well_typed_arg D Q H env (ELit n t') t\n     | ArgVar : forall x t t',\n      Env.MapsTo x t' env -> \n      well_type_bound_in env t ->\n      subtype D Q t' t ->\n      well_typed_arg D Q H env (EVar x) t.\n\nInductive well_typed_args {D: structdef} {Q:theta} {H : heap}: \n                   env -> list (var * bound) -> list expression -> list (var * type) -> Prop :=\n     | args_empty : forall env s, well_typed_args env s [] []\n     | args_many : forall env s e es v t vl, \n                 well_typed_arg D Q H env e (subst_type s t) ->\n                        well_typed_args env s es vl\n                        -> well_typed_args env s (e::es) ((v,t)::vl).\n\nFixpoint eq_nat (s:stack) (e:expression) :=\n  match e with (ELit n TNat) => Some n\n             | EVar x => match Stack.find x s with None => None | Some (n,t) => Some n end\n             | EPlus e1 e2 => \n               (match eq_nat s e1 with Some n1 => \n                   match eq_nat s e2 with Some n2 => Some (n1 + n2)\n                       | _ => None\n                   end\n                  | _ => None\n                end)\n              | _ => None\n    end.\n\nDefinition NTHitVal (t:type) : Prop :=\n   match t with | (TPtr m (TNTArray l (Num 0) t)) => True\n                | _ => False\n   end.\n\nDefinition add_nt_one_env (s : env) (x:var) : env :=\n   match Env.find x s with | Some (TPtr m (TNTArray l (Num h) t)) \n                         => Env.add x (TPtr m (TNTArray l (Num (h+1)) t)) s\n                              (* This following case will never happen since the type in a stack is always evaluated. *)\n                             | _ => s\n   end.\n\nDefinition get_tvar_bound (b:bound) : list var :=\n     match b with Num n => [] | Var x n => [x]  end.\n\nFixpoint get_tvars (t:type) : (list var) :=\n   match t with TNat => []\n             | TPtr c t => get_tvars t\n             | TStruct t => []\n             | TArray l h t => get_tvar_bound l ++ get_tvar_bound h ++ get_tvars t\n             | TNTArray l h t => get_tvar_bound l ++ get_tvar_bound h ++ get_tvars t\n   end.\n\nFixpoint get_nat_vars (l : list (var * type)) : list var :=\n   match l with [] => []\n            | (x,TNat)::xl => x::(get_nat_vars xl)\n            | (x,t)::xl => (get_nat_vars xl)\n   end.\n\nDefinition elem_make_sense (D:structdef) (Q:theta) (H:heap) (a:option (Z*type)) : Prop :=\n      match a with None => True\n              | Some (n,t) => well_typed_lit D Q H empty_scope n t\n      end.\n\n\n(* The CoreChkC Type System. *)\nInductive well_typed { D : structdef } {F : FEnv} {S:stack} {H:heap}\n        : env -> theta -> mode -> expression -> type -> Prop :=\n  | TyLit : forall env Q m n t,\n      @well_typed_lit D Q H empty_scope n t ->\n      well_typed env Q m (ELit n t) t\n  | TyVar : forall env Q m x t,\n      Env.MapsTo x t env ->\n      well_typed env Q m (EVar x) t\n\n  | TyCall : forall env Q s m m' es x tvl e t, \n        F env x = Some (tvl,t,e,m') ->\n        get_dept_map tvl es = Some s ->\n        (m' = Unchecked -> m = Unchecked) ->\n        @well_typed_args D Q H env s es tvl ->\n           well_typed env Q m (ECall x es) (subst_type s t)\n\n  | TyStrlen : forall env Q m x h l t, \n      Env.MapsTo x (TPtr m (TNTArray h l t)) env ->\n      well_typed env Q m (EStrlen x) TNat\n\n  | TyLetStrlen : forall env Q m x y e l h t ta, \n      ~ Env.In x env ->\n      Env.MapsTo y (TPtr m (TNTArray l h ta)) env ->\n      well_typed (Env.add x TNat (Env.add y (TPtr m (TNTArray l (Var x 0) ta)) env)) (Theta.add x GeZero Q) m e t ->\n      ~ In x (get_tvars t) ->\n      well_typed env Q m (ELet x (EStrlen y) e) t\n\n  | TyLetNat : forall env Q m x e1 e2 t b,\n      ~ Env.In x env ->\n      well_typed env Q m e1 TNat ->\n      well_typed (Env.add x TNat env) Q m e2 t ->\n      In x (get_tvars t) -> get_good_dept e1 = Some b ->\n      well_typed env Q m (ELet x e1 e2) (subst_type [(x,b)] t)\n\n  | TyLet : forall env Q m x e1 t1 e2 t,\n      ~ Env.In x env ->\n      well_typed env Q m e1 t1 ->\n      well_typed (Env.add x t1 env) Q m e2 t ->\n      ~ In x (get_tvars t) ->\n      well_typed env Q m (ELet x e1 e2) t\n\n  | TyRetTNat : forall env Q m x na e t,\n      Env.In x env ->\n      In x (get_tvars t) ->\n      well_typed env Q m e t ->\n      well_typed env Q m (ERet x (na,TNat) e) (subst_type [(x,(Num na))] t)\n\n  | TyRet : forall env Q m x na ta e t,\n      Env.In x env ->\n      well_typed env Q m e t ->\n      ~ In x (get_tvars t) ->\n      well_typed env Q m (ERet x (na,ta) e) t\n\n  | TyPlus : forall env Q m e1 e2,\n      well_typed env Q m e1 (TNat) ->\n      well_typed env Q m e2 (TNat) ->\n      well_typed env Q m (EPlus e1 e2) TNat\n  | TyFieldAddr : forall env Q m e m' T fs i fi ti,\n      well_typed env Q m e (TPtr m' (TStruct T)) ->\n      StructDef.MapsTo T fs D ->\n      Fields.MapsTo fi ti fs ->\n      List.nth_error (Fields.this fs) i = Some (fi, ti) ->\n      well_typed env Q m (EFieldAddr e fi) (TPtr m' ti)\n  | TyMalloc : forall env Q m w,\n      well_type_bound_in env w ->\n      well_typed env Q m (EMalloc w) (TPtr Checked w)\n  | TyUnchecked : forall env Q m e t,\n      well_typed env Q Unchecked e t ->\n      well_typed env Q m (EUnchecked e) t\n  | TyCast1 : forall env Q m t e t',\n      well_type_bound_in env t ->\n      (m = Checked -> forall w, t <> TPtr Checked w) ->\n      well_typed env Q m e t' ->\n      well_typed env Q m (ECast t e) t\n  | TyCast2 : forall env Q m t e t',\n      well_type_bound_in env t ->\n      well_typed env Q m e t' -> \n      subtype_stack D Q S t' (TPtr Checked t) ->\n      well_typed env Q m (ECast (TPtr Checked t) e) (TPtr Checked t)\n\n  | TyDynCast1 : forall env Q m e x y u v t t',\n      well_type_bound_in env (TPtr Checked (TArray x y t)) ->\n      well_typed env Q m e (TPtr Checked (TArray u v t')) ->\n      type_eq S t t' ->\n      well_typed env Q m (EDynCast (TPtr Checked (TArray x y t)) e) (TPtr Checked (TArray x y t))\n  | TyDynCast2 : forall env Q m e x y t t',\n      ~ is_array_ptr (TPtr Checked t') ->\n      type_eq S t t' ->\n      well_type_bound_in env (TPtr Checked (TArray x y t)) ->\n      well_typed env Q m e (TPtr Checked t') ->\n      well_typed env Q m (EDynCast (TPtr Checked (TArray x y t)) e) (TPtr Checked (TArray (Num 0) (Num 1) t))\n  | TyDynCast3 : forall env Q m e x y u v t t',\n      well_type_bound_in env (TPtr Checked (TNTArray x y t)) ->\n      type_eq S t t' ->\n      well_typed env Q m e (TPtr Checked (TNTArray u v t')) ->\n      well_typed env Q m (EDynCast (TPtr Checked (TNTArray x y t)) e) (TPtr Checked (TNTArray x y t))\n  | TyDeref : forall env Q m e m' t l h t' t'',\n      well_typed env Q m e t ->\n      subtype D Q t (TPtr m' t'') ->\n      ((word_type t'' /\\ t'' = t') \n       \\/ (t'' = TArray l h t' /\\ word_type t' /\\ type_wf D t')\n       \\/ (t'' = TNTArray l h t' /\\ word_type t' /\\ type_wf D t')) ->\n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env Q m (EDeref e) t'\n  | TyIndex1 : forall env Q m e1 m' l h e2 t,\n      word_type t -> type_wf D t ->\n      well_typed env Q m e1 (TPtr m' (TArray l h t)) -> \n      well_typed env Q m e2 (TNat) ->\n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env Q m (EDeref (EPlus e1 e2)) t\n  | TyIndex2 : forall env Q m e1 m' l h e2 t,\n      word_type t -> type_wf D t ->\n      well_typed env Q m e1 (TPtr m' (TNTArray l h t)) ->\n      well_typed env Q m e2 (TNat) ->\n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env Q m (EDeref (EPlus e1 e2)) t\n  | TyAssign1 : forall env Q m e1 e2 m' t t1,\n      subtype_stack D Q S t1 t -> word_type t ->\n      well_typed env Q m e1 (TPtr m' t) ->\n      well_typed env Q m e2 t1 ->\n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env Q m (EAssign e1 e2) t\n  | TyAssign2 : forall env Q m e1 e2 m' l h t t',\n      word_type t -> type_wf D t -> subtype_stack D Q S t' t ->\n      well_typed env Q m e1 (TPtr m' (TArray l h t)) ->\n      well_typed env Q m e2 t' ->\n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env Q m (EAssign e1 e2) t\n  | TyAssign3 : forall env Q m e1 e2 m' l h t t',\n      word_type t -> type_wf D t -> \n     subtype_stack D Q S t' t ->\n      well_typed env Q m e1 (TPtr m' (TNTArray l h t)) ->\n      well_typed env Q m e2 t' ->\n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env Q m (EAssign e1 e2) t\n  | TyIndexAssign1 : forall env Q m e1 e2 e3 m' l h t t',\n      word_type t' -> type_wf D t' -> \n      subtype_stack D Q S t' t ->\n      well_typed env Q m e1 (TPtr m' (TArray l h t)) ->\n      well_typed env Q m e2 (TNat) ->\n      well_typed env Q m e3 t' ->\n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env Q m (EAssign (EPlus e1 e2) e3) t\n  | TyIndexAssign2 : forall env Q m e1 e2 e3 m' l h t t',\n      word_type t' -> type_wf D t' -> \n      subtype_stack D Q S t' t ->\n      well_typed env Q m e1 (TPtr m' (TNTArray l h t)) ->\n      well_typed env Q m e2 (TNat) ->\n      well_typed env Q m e3 t' ->\n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env Q m (EAssign (EPlus e1 e2) e3) t\n  | TyIfDef : forall env Q m m' x t1 e1 e2 t2 t3 t4,\n      Env.MapsTo x (TPtr m' t1) env ->\n      (exists l h t', (word_type t1 /\\ t1 = t')\n         \\/ (t1 = TArray l h t' /\\ word_type t' /\\ type_wf D t')\n       \\/ (t1 = TNTArray l h t' /\\ word_type t' /\\ type_wf D t')) ->\n      well_typed env Q m e1 t2 -> well_typed env Q m e2 t3 ->\n      join_type D Q S t2 t3 t4 -> \n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env Q m (EIfDef x e1 e2) t4\n  | TyIfDefNT : forall env Q m m' x l t e1 e2 t2 t3 t4,\n      Env.MapsTo x (TPtr m' (TNTArray l (Num 0) t)) env ->\n      well_typed (Env.add x (TPtr m' (TNTArray l (Num 1) t)) env) Q m e1 t2 -> well_typed env Q m e2 t3 ->\n      join_type D Q S t2 t3 t4 -> \n      (m' = Unchecked -> m = Unchecked) ->\n      well_typed env Q m (EIfDef x e1 e2) t4\n  | TyIf : forall env Q m e1 e2 e3 t2 t3 t4,\n      well_typed env Q m e1 TNat ->\n      well_typed env Q m e2 t2 ->\n      well_typed env Q m e3 t3 ->\n      join_type D Q S t2 t3 t4 -> \n      well_typed env Q m (EIf e1 e2 e3) t4. \n\nDefinition fun_wf (D : structdef) (F:FEnv) :=\n     forall H env env' S f tvl t e m, F env f = Some (tvl,t,e,m) -> \n          gen_arg_env env tvl env' ->\n          (forall x t', In (x,t') tvl -> word_type t' /\\ type_wf D t' /\\ well_bound_vars_type tvl t') /\\\n          (forall a, In a tvl -> ~ Env.In (fst a) env) /\\\n          (forall n n' a b, n <> n' -> nth_error tvl n = Some a -> nth_error tvl n' = Some b -> fst a <> fst b) /\\\n          word_type t /\\ type_wf D t /\\ well_bound_vars_type tvl t /\\ expr_wf D fenv e\n          /\\ @well_typed D F S H env' empty_theta m e t.\n\nAxiom alpha_same : forall D Q Q' S S' H H' env env' e e' t t' m, \n  @reduce D (fenv env) S H e m S' H' (RExpr e') ->\n  @well_typed D fenv S H env Q m e t ->\n  @well_typed D fenv S' H' env' Q' m e' t' -> \n  fenv env = fenv env'.\n\nDefinition sub_domain (env: env) (S:stack) := forall x, Env.In x env -> Stack.In x S.\n\n\nDefinition heap_wt_all (D : structdef) (Q:theta) (H:heap) := forall x n t, Heap.MapsTo x (n,t) H\n            -> word_type t /\\ type_wf D t /\\ simple_type t /\\ well_typed_lit D Q H empty_scope n t.\n\nDefinition stack_consistent_grow (S S' : stack) (env : env) := \n       forall x v t, Env.In x env -> sub_domain env S -> Stack.MapsTo x (v,t) S -> Stack.MapsTo x (v,t) S'.\n\nDefinition stack_wf D Q env s :=\n    (forall x t,\n         Env.MapsTo x t env ->\n         exists v t' t'',\n           cast_type_bound s t t' /\\\n           subtype D Q t'' t' /\\\n            Stack.MapsTo x (v, t'') s).\n\nDefinition stack_heap_consistent D Q H S :=\n    forall x n t, Stack.MapsTo x (n,t) S -> well_typed_lit D Q H empty_scope n t.\n\nLocal Close Scope Z_scope.\n\nLocal Open Scope nat_scope.\n\nHint Constructors well_typed.\n\n(*Hint Constructors ty_ssa.*)\n\n\nLemma ptr_subtype_equiv : forall D Q m w t,\nsubtype D Q w (TPtr m t) ->\nexists t', w = (TPtr m t').\nProof.\n  intros. remember (TPtr m t) as p. generalize dependent t. induction H.\n  - intros. exists t0. rewrite Heqp. reflexivity.\n  - intros. inv Heqp. exists t. easy.\n  - intros. inv Heqp. exists (TArray l h t0). easy.\n  - intros. inv Heqp. exists (TNTArray l h t0). easy.\n  - intros. inv Heqp. exists (TArray l h t). easy.\n  - intros. inv Heqp. exists (TNTArray l h t). easy.\n  - intros. inv Heqp. exists (TNTArray l h t). easy.\n  - intros. exists (TStruct T).\n    assert (m0 = m). {\n      inv Heqp. reflexivity. \n    }\n    rewrite H1. reflexivity.\n  - intros. inv Heqp. exists (TStruct T).\n    reflexivity.\nQed.\n\n(* this might be an issue if we want to make checked pointers\na subtype of unchecked pointers. This will need to\nbe changed to generalize m*)\nLemma ptr_subtype_equiv' : forall D Q m w t,\nsubtype D Q (TPtr m t) w ->\nexists t', w = (TPtr m t').\nProof.\n intros. remember (TPtr m t) as p. generalize dependent t. induction H.\n  - intros. exists t0. rewrite Heqp. reflexivity.\n  - intros. inv Heqp. exists (TArray l h t0). easy.\n  - intros. inv Heqp. exists t. easy.\n  - intros. inv Heqp. exists t. easy.\n  - intros. exists (TArray l' h' t).\n    assert (m0 = m). {\n      inv Heqp. reflexivity. \n    }\n    rewrite H1. reflexivity.\n  - intros. inv Heqp. exists (TArray l' h' t). easy.\n  - intros. exists (TNTArray l' h' t).\n    assert (m0 = m). {\n      inv Heqp. reflexivity. \n    }\n    rewrite H1. reflexivity.\n  - intros. exists TNat.\n    assert (m0 = m). {\n      inv Heqp. reflexivity. \n    }\n    rewrite H1. reflexivity.\n  - intros. exists (TArray l h TNat).\n    assert (m0 = m). {\n      inv Heqp. reflexivity. \n    }\n    rewrite H3. reflexivity.\nQed.\n\nLemma nat_subtype : forall D Q t,\nsubtype D Q TNat t ->\nt = TNat.\nProof.\n  intros. remember TNat as t'. induction H; eauto.\n  - exfalso. inv Heqt'.\n  - exfalso. inv Heqt'.\n  - exfalso. inv Heqt'.\n  - exfalso. inv Heqt'.\n  - exfalso. inv Heqt'.\n  - exfalso. inv Heqt'.\n  - exfalso. inv Heqt'.\n  - exfalso. inv Heqt'.\nQed.\n\n(** ** Metatheory *)\n\n(** *** Automation *)\n\n(* TODO: write a function decompose : expr -> (context * expr) *)\n\n\nLtac clean :=\n  subst;\n  repeat (match goal with\n          | [ P : ?T, PQ : ?T -> _ |- _ ] => specialize (PQ P); clear P\n          | [ H : ?T = ?T -> _ |- _ ] => specialize (H eq_refl)\n          end).\n\nDefinition heap_consistent { D : structdef } {Q:theta} (H' : heap) (H : heap) : Prop :=\n  forall n t,\n    @well_typed_lit D Q H empty_scope n t->\n    @well_typed_lit D Q H' empty_scope n t.\n\nHint Unfold heap_consistent.\n\n\n(** *** Lemmas *)\n\n(* ... for Progress *)\n\nCreate HintDb Progress.\n\nLemma step_implies_reduces : forall D F H s e H' s' r,\n    @step D F s H e s' H' r ->\n    reduces D F s H e.\nProof.\n  intros.\n  assert (e = in_hole e CHole); try reflexivity.\n  rewrite H1.\n  destruct r; eauto 20.\nQed.\n\nHint Resolve step_implies_reduces : Progress.\n\nLemma reduces_congruence : forall D F H s e0 e,\n    (exists E, in_hole e0 E = e) ->\n    reduces D F s H e0 ->\n    reduces D F s H e.\nProof.\n  intros.\n  destruct H0 as [ E Hhole ].\n  destruct H1 as [H' [ m' [ s' [r  HRed ]] ] ].\n  inv HRed.\n  rewrite compose_correct; eauto 20.\n  rewrite compose_correct; eauto 20.\n  rewrite compose_correct; eauto 20.\nQed.\n\nHint Resolve reduces_congruence : Progress.\n\nLemma unchecked_congruence : forall e0 e,\n    (exists e1 E, e0 = in_hole e1 E /\\ mode_of(E) = Unchecked) ->\n    (exists E, in_hole e0 E = e) ->\n    exists e' E, e = in_hole e' E /\\ mode_of(E) = Unchecked.\nProof.\n  intros.\n  destruct H as [ e1 [ E1 [ He0 HE1U ] ] ].\n  destruct H0 as [ E He ].\n  exists e1.\n  exists (compose E E1).\n  split.\n  - subst. rewrite compose_correct. reflexivity.\n  - apply compose_unchecked. assumption.\nQed.\n\nHint Resolve unchecked_congruence : Progress.\n\n\nOpen Scope Z.\nLemma wf_implies_allocate_meta :\n  forall (D : structdef) (w : type),\n    (forall l h t, w = TArray (Num l) (Num h) t -> l = 0 /\\ h > 0) ->\n    (forall l h t, w = TNTArray (Num l) (Num h) t -> l = 0 /\\ h > 0) ->\n    simple_type w ->\n    type_wf D w -> exists b allocs, allocate_meta D w = Some (b, allocs).\nProof.\n  intros D w HL1 HL2 HS HT.\n  destruct w; simpl in *; eauto.\n  - inv HT. destruct H0.\n    apply StructDef.find_1 in H.\n    rewrite -> H.\n    eauto.\n  - inv HS. eauto.\n  - inv HS. eauto.\nQed.\n\nLemma wf_implies_allocate :\n  forall (D : structdef) (w : type) (H : heap),\n    (forall l h t, w = TArray (Num l) (Num h) t -> l = 0 /\\ h > 0) ->\n    (forall l h t, w = TNTArray (Num l) (Num h) t -> l = 0 /\\ h > 0) ->\n    simple_type w ->\n    type_wf D w -> exists n H', allocate D H w = Some (n, H').\nProof.\n  intros D w H HL1 HL2 HS HT.\n  eapply wf_implies_allocate_meta in HT; eauto.\n  destruct HT as [l [ts HT]]. \n  unfold allocate. unfold allocate_meta in *.\n  rewrite HT.\n  edestruct (fold_left\n               (fun (acc : Z * heap) (t : type) =>\n                  let (sizeAcc, heapAcc) := acc in\n                  (sizeAcc + 1, Heap.add (sizeAcc + 1) (0, t) heapAcc)) ts\n               ((Z.of_nat (Heap.cardinal H)), H)) as (z, h).\n\n  destruct w eqn:Hw; inv HT; simpl in *; eauto.\n\n  - destruct (StructDef.find s D) eqn:HFind; inv H1; eauto.\n  - inv HS.\n    edestruct HL1; eauto. \n    destruct l. subst; eauto.\n    rewrite H0 in H1.\n    assert (0 < Z.pos p).\n    easy. inversion H1.\n    assert (Z.neg p < 0).\n    easy. rewrite H0 in H1. inversion H1.\n  - inv HS.\n    edestruct HL2; eauto. \n    destruct l. subst; eauto.\n    rewrite H0 in H1.\n    assert (0 < Z.pos p).\n    easy. inversion H1.\n    assert (Z.neg p < 0).\n    easy. rewrite H0 in H1. inversion H1.\nQed.\n\n\nDefinition unchecked (m : mode) (e : expression) : Prop :=\n  m = Unchecked \\/ exists e' E, e = in_hole e' E /\\ mode_of(E) = Unchecked.\n\nHint Unfold unchecked.\n\nLtac solve_empty_scope :=\n  match goal with\n  | [ H : set_In _ empty_scope |- _ ] => inversion H\n  | _ => idtac \"No empty scope found\"\n  end.\n\n\nRequire Import Coq.FSets.FMapList.\nRequire Import Coq.FSets.FMapFacts.\n\nModule FieldFacts := WFacts_fun Fields.E Fields.\nModule StructDefFacts := WFacts_fun StructDef.E StructDef.\nModule HeapFacts := WFacts_fun Heap.E Heap.\n\n(* This really should be part of the library, or at least easily provable... *)\nModule HeapProp := WProperties_fun Heap.E Heap.\nLemma cardinal_plus_one :\n  forall (H : heap) n v, ~ Heap.In n H ->\n                         (Z.of_nat(Heap.cardinal (Heap.add n v H)) = Z.of_nat(Heap.cardinal H) + 1).\nProof.\n  intros H n v NotIn.\n  pose proof HeapProp.cardinal_2 as Fact.\n  specialize (Fact _ H (Heap.add n v H) n v NotIn).\n  assert (Hyp: HeapProp.Add n v H (Heap.add n v H)).\n  {\n    intros y.\n    auto.\n  } \n  specialize (Fact Hyp).\n  lia.\nQed.\n\n(* This should be part of the stupid map library. *)\n(* Changed to Z to push final proof DP*)\nLemma heap_add_in_cardinal : forall n v H,\n  Heap.In n H -> \n  Heap.cardinal (elt:=Z * type) (Heap.add n v H) =\n  Heap.cardinal (elt:=Z * type) H.\nProof.\n  intros.\n  remember (Heap.cardinal (elt:=Z * type) H) as m.\n  destruct m.\n  symmetry in Heqm.\n  apply HeapProp.cardinal_Empty in Heqm.\nAdmitted.\n\nLemma replicate_length : forall (n : nat) (T : type),\n(length (replicate n T)) = n.\nProof.\n  intros n T. induction n.\n    -simpl. reflexivity.\n    -simpl. rewrite IHn. reflexivity.\nQed.\n\nLemma replicate_length_nth {A} : forall (n k : nat) (w x : A),\n    nth_error (replicate n w) k = Some x -> (k < n)%nat.\nProof.\n  intros n; induction n; intros; simpl in *; auto.\n  - inv H.\n    destruct k; inv H1.\n  - destruct k.\n    + lia.\n    + simpl in *.\n      apply IHn in H.\n      lia.\nQed.\n\n(* Progress:\n     If [e] is well-formed with respect to [D] and\n        [e] has type [t] under heap [H] in mode [m]\n     Then\n        [e] is a value, [e] reduces, or [e] is stuck in unchecked code *)\nLemma pos_succ : forall x, exists n, (Pos.to_nat x) = S n.\nProof.\n   intros x. destruct (Pos.to_nat x) eqn:N.\n    +zify. lia.\n    +exists n. reflexivity.\nQed.\n\nLtac remove_options :=\n  match goal with\n  | [ H: Some ?X = Some ?Y |- _ ] => inversion H; subst X; clear H\n  end.\n\n(*No longer provable since we can allocate\nbounds that are less than 0 now.\nLemma allocate_bounds : forall D l h t b ts,\nSome(b, ts) = allocate_meta D (TArray l h t) ->\nl = 0 /\\ h > 0.\nProof.\nintros.\ndestruct l.\n  +destruct h.\n    *simpl in H. inv H.\n    *zify. omega.\n    *simpl in H. inv H.\n  +simpl in H. inv H.\n  +simpl in H. inv H.\nQed.\n*)\n\nLemma fields_aux : forall fs,\nlength (map snd (Fields.elements (elt:=type) fs)) = length (Fields.elements (elt:=type) fs).\nProof.\n  intros. eapply map_length.\nQed.\n\nLemma obvious_list_aux : forall (A : Type) (l : list A),\n(length l) = 0%nat -> \nl = nil.\nProof.\n  intros. destruct l.\n  - reflexivity.\n  - inv H.\nQed.\n\n(*These are obvious*)\nLemma fields_implies_length : forall fs t,\nSome t = Fields.find (elt:=type) 0%nat fs ->\n((length (Fields.elements (elt:=type) fs) > 0))%nat.\nProof.\n intros.\n assert (Fields.find (elt:=type) 0%nat fs = Some t) by easy.\n apply Fields.find_2 in H0.\n apply Fields.elements_1 in H0.\n destruct ((Fields.elements (elt:=type) fs)).\n inv H0. simpl. lia.\nQed.\n\nLemma find_implies_mapsto : forall s D f,\nStructDef.find (elt:=fields) s D = Some f ->\nStructDef.MapsTo s f D.\nProof.\n  intros. \n  eapply StructDef.find_2. assumption.\nQed.\n\n\nLemma struct_subtype_non_empty : forall m T fs D Q,\nsubtype D Q (TPtr m (TStruct T)) (TPtr m TNat) ->\n(StructDef.MapsTo T fs D) ->\nZ.of_nat(length (map snd (Fields.elements (elt:=type) fs))) > 0.\nProof.\n  intros. remember (TPtr m (TStruct T)) as p1.\n  remember (TPtr m TNat) as p2. induction H.\n  - exfalso. rewrite Heqp1 in Heqp2. inv Heqp2.\n  - exfalso. inv Heqp2.\n  - exfalso. inv Heqp1.\n  - exfalso. inv Heqp1.\n  - exfalso. inv Heqp2.\n  - inv Heqp1.\n  - inv Heqp1.\n  - inv Heqp1. assert (fs = fs0) by (eapply StructDefFacts.MapsTo_fun; eauto). \n    eapply fields_implies_length in H1. rewrite H2.\n    zify. eauto. rewrite map_length. assumption.\n  - inv Heqp2. \nQed.\n\nLemma struct_subtype_non_empty_1 : forall m T fs D Q,\nsubtype D Q (TPtr m (TStruct T)) (TPtr m (TArray (Num 0) (Num 1) TNat)) ->\n(StructDef.MapsTo T fs D) ->\nZ.of_nat(length (map snd (Fields.elements (elt:=type) fs))) > 0.\nProof.\n  intros. remember (TPtr m (TStruct T)) as p1.\n  remember (TPtr m (TArray (Num 0) (Num 1) TNat)) as p2. induction H.\n  - exfalso. rewrite Heqp1 in Heqp2. inv Heqp2.\n  - exfalso. inv Heqp2. inv Heqp1.\n  - exfalso. inv Heqp1.\n  - exfalso. inv Heqp1.\n  - exfalso. inv Heqp1.\n  - inv Heqp1.\n  - inv Heqp2. \n  - inv Heqp1. inv Heqp2. \n  - inv Heqp1. inv Heqp2. \n    assert (fs = fs0) by (eapply StructDefFacts.MapsTo_fun; eauto). \n    eapply fields_implies_length in H1. rewrite H4.\n    zify. eauto. rewrite map_length. assumption.\nQed.\n\nLemma struct_subtype_non_empty_2 : forall m T fs D Q,\nsubtype D Q (TPtr m (TStruct T)) (TPtr m (TNTArray (Num 0) (Num 1) TNat)) ->\n(StructDef.MapsTo T fs D) ->\nZ.of_nat(length (map snd (Fields.elements (elt:=type) fs))) > 0.\nProof.\n  intros. remember (TPtr m (TStruct T)) as p1.\n  remember (TPtr m (TNTArray (Num 0) (Num 1) TNat)) as p2. induction H.\n  - exfalso. rewrite Heqp1 in Heqp2. inv Heqp2.\n  - exfalso. inv Heqp2.\n  - exfalso. inv Heqp2. inv Heqp1.\n  - exfalso. inv Heqp1.\n  - exfalso. inv Heqp1.\n  - inv Heqp1.\n  - inv Heqp1. \n  - inv Heqp2. \n  - inv Heqp1. inv Heqp2. \nQed.\n\n(*\nDefinition env_denv_prop (env: env) (S:stack) (denv:dyn_env) :=\n    forall x t t', Env.MapsTo x t env -> cast_type_bound S t t' -> Stack.MapsTo x t' denv.\n*)\nLemma gen_cast_bound_same :\n   forall env s b, well_bound_in env b -> sub_domain env s -> (exists b', cast_bound s b = Some b').\nProof.\n  intros. induction b.\n  exists (Num z). unfold cast_bound. reflexivity.\n  inv H. unfold sub_domain in *.\n  assert (Env.In v env0).\n  unfold Env.In,Env.Raw.PX.In.\n  exists TNat. easy.\n  apply H0 in H. \n  unfold cast_bound.\n  unfold Stack.In,Stack.Raw.PX.In in *.\n  destruct H. apply Stack.find_1 in H.\n  destruct (Stack.find v s).\n  injection H as eq1. destruct p.\n  exists (Num (z + z0)). reflexivity.\n  inv H.\nQed.\n\nLemma gen_cast_type_bound_same :\n   forall env s t, well_type_bound_in env t -> sub_domain env s\n           -> (exists t', cast_type_bound s t t').\nProof.\n  intros. induction t.\n  exists TNat. apply cast_type_bound_nat.\n  inv H. apply IHt in H3. destruct H3.\n  exists (TPtr m x). apply cast_type_bound_ptr. assumption.\n  exists (TStruct s0). apply cast_type_bound_struct.\n  inv H. apply IHt in H7. destruct H7.\n  apply (gen_cast_bound_same env0 s) in H5.\n  apply (gen_cast_bound_same env0 s) in H6.\n  destruct H5. destruct H6.\n  exists (TArray x0 x1 x).\n  apply cast_type_bound_array.\n  1 - 5: assumption.\n  inv H. apply IHt in H7. destruct H7.\n  apply (gen_cast_bound_same env0 s) in H5.\n  apply (gen_cast_bound_same env0 s) in H6.\n  destruct H5. destruct H6.\n  exists (TNTArray x0 x1 x).\n  apply cast_type_bound_ntarray.\n  1 - 5: assumption.\nQed.\n\n\nLemma cast_word_type : forall s t t', cast_type_bound s t t' -> word_type t -> word_type t'.\nProof.\n intros. inv H0. inv H. constructor.\n inv H. constructor.\nQed.\n\nLemma cast_type_wf : forall D s t t', cast_type_bound s t t' -> type_wf D t -> type_wf D t'.\nProof.\n intros. generalize dependent t'. induction t.\n intros. inv H. constructor.\n intros. inv H. constructor. apply IHt. inv H0. assumption.\n assumption.\n intros. inv H. constructor.\n inv H0. destruct H1. exists x. assumption.\n intros. inv H.\n constructor. inv H0. eapply cast_word_type. apply H7. assumption.\n apply IHt. inv H0. assumption. assumption.\n intros. inv H.\n constructor. inv H0. eapply cast_word_type. apply H7. assumption.\n apply IHt. inv H0. assumption. assumption.\nQed.\n\nLemma cast_type_bound_same : forall s t t' t'',\n              cast_type_bound s t t' -> cast_type_bound s t t'' -> t' = t''.\nProof.\n intros s t.\n induction t.\n intros. inv H0. inv H. reflexivity.\n intros.\n inv H. inv H0.\n assert (t' = t'0).\n apply IHt. assumption. assumption. rewrite H. reflexivity.\n intros. inv H. inv H0. reflexivity.\n intros. inv H. inv H0.\n unfold cast_bound in *.\n destruct b. destruct b0. inv H4. inv H6. inv H3. inv H8.\n assert (t' = t'0).\n apply IHt. assumption. assumption. rewrite H. reflexivity.\n destruct (Stack.find (elt:=Z * type) v s).\n destruct p.\n inv H4. inv H6. inv H3. inv H8.\n assert (t' = t'0).\n apply IHt. assumption. assumption. rewrite H. reflexivity.\n inv H6.\n destruct (Stack.find (elt:=Z * type) v s). destruct b0.\n destruct p.\n inv H4. inv H6. inv H3. inv H8.\n assert (t' = t'0).\n apply IHt. assumption. assumption. rewrite H. reflexivity.\n destruct (Stack.find (elt:=Z * type) v0 s). destruct p. destruct p0.\n inv H4. inv H6. inv H3. inv H8.\n assert (t' = t'0).\n apply IHt. assumption. assumption. rewrite H. reflexivity.\n inv H6. inv H3. \n intros. inv H. inv H0.\n unfold cast_bound in *.\n destruct b. destruct b0. inv H4. inv H6. inv H3. inv H8.\n assert (t' = t'0).\n apply IHt. assumption. assumption. rewrite H. reflexivity.\n destruct (Stack.find (elt:=Z * type) v s).\n destruct p.\n inv H4. inv H6. inv H3. inv H8.\n assert (t' = t'0).\n apply IHt. assumption. assumption. rewrite H. reflexivity.\n inv H6.\n destruct (Stack.find (elt:=Z * type) v s). destruct b0.\n destruct p.\n inv H4. inv H6. inv H3. inv H8.\n assert (t' = t'0).\n apply IHt. assumption. assumption. rewrite H. reflexivity.\n destruct (Stack.find (elt:=Z * type) v0 s). destruct p. destruct p0.\n inv H4. inv H6. inv H3. inv H8.\n assert (t' = t'0).\n apply IHt. assumption. assumption. rewrite H. reflexivity.\n inv H6. inv H3. \nQed.\n\nLemma simple_type_means_cast_same : forall t s, simple_type t -> cast_type_bound s t t.\nProof.\n  induction t;intros; simpl; try constructor.\n  inv H. apply IHt. easy.\n  inv H. easy. inv H. easy. apply IHt. inv H. easy.\n  inv H. easy. inv H. easy. apply IHt. inv H. easy.\nQed. \n\nLemma simple_type_means_eval_same : forall t s, simple_type t -> eval_type_bound s t = Some t.\nProof.\n  induction t;intros; simpl; try constructor.\n  destruct t; try easy.\n  inv H. inv H1.\n  unfold eval_bound. easy.\n  inv H. inv H1.\n  unfold eval_bound. easy.\nQed. \n\nLemma cast_type_eq : forall s t t1 t', \n        cast_type_bound s t t' -> type_eq s t t1 -> cast_type_bound s t1 t'.\nProof.\n intros. inv H0. easy.\n assert (t' = t1).\n eapply cast_type_bound_same. apply H. easy. subst.\n apply simple_type_means_cast_same. easy.\n assert (t1 = t').\n specialize (simple_type_means_cast_same t1 s H1) as eq1.\n eapply cast_type_bound_same. apply H2. easy. subst.\n apply simple_type_means_cast_same. easy.\nQed.\n\nLemma sub_domain_grow : forall env S x v t, sub_domain env S \n                 -> sub_domain (Env.add x t env) (Stack.add x v S).\nProof.\n  intros.\n  unfold sub_domain in *.\n  intros.\n  unfold Env.In,Env.Raw.PX.In in H0.\n  destruct H0.\n  unfold Stack.In,Stack.Raw.PX.In.\n  destruct (Nat.eq_dec x x0).\n  subst.\n  exists v.\n  apply Stack.add_1. easy.\n  apply Env.add_3 in H0.\n  assert (Env.In x0 env0).\n  unfold Env.In,Env.Raw.PX.In.\n  exists x1. easy.\n  apply H in H1.\n  unfold Stack.In,Stack.Raw.PX.In in H1.\n  destruct H1.\n  exists x2.\n  apply Stack.add_2.\n  lia. assumption. lia.\nQed.\n\n(* Some lemmas related to cast/well_bound_in *)\nLemma not_in_empty : forall x, Env.In x empty_env -> False.\nProof.\n intros.\n  unfold empty_env in H.\n specialize (@Env.empty_1 type) as H1.\n unfold Env.In,Env.Raw.PX.In in H.\n destruct H.\n unfold Env.Empty,Env.Raw.Empty in H1.\n inv H.\nQed.\n\nLemma simple_type_well_bound : forall (env: env) (w:type),\n                simple_type w -> well_type_bound_in env w.\nProof.\n   intros. induction w.\n   apply well_type_bound_in_nat.\n   apply well_type_bound_in_ptr.\n   apply IHw. inv H. assumption.\n   apply well_type_bound_in_struct.\n   inv H.\n   apply well_type_bound_in_array.\n   apply well_bound_in_num.\n   apply well_bound_in_num.\n   apply IHw. assumption.\n   inv H.\n   apply well_type_bound_in_ntarray.\n   apply well_bound_in_num.\n   apply well_bound_in_num.\n   apply IHw. assumption.\nQed.\n\n\nLemma well_bound_means_no_var :\n     forall b, well_bound_in empty_env b -> (exists n, b = (Num n)).\nProof.\n intros. remember empty_env as env.\n induction H. eauto.\n subst. \n unfold empty_env in H.\n specialize (@Env.empty_1 type) as H1.\n unfold Env.In,Env.Raw.PX.In in H.\n apply EnvFacts.empty_mapsto_iff in H. inv H.\nQed.\n\n\n\nLemma well_typed_means_simple : forall (w : type),\n          well_type_bound_in empty_env w -> simple_type w.\nProof.\n intros. remember empty_env as env0.\n induction H.\n apply SPTNat.\n apply SPTPtr.\n apply IHwell_type_bound_in.\n subst. easy.\n constructor.\n subst. inv H0.\n apply well_bound_means_no_var in H; try easy.\n destruct H. subst.\n constructor. apply IHwell_type_bound_in. easy. easy.\n subst. inv H0.\n apply well_bound_means_no_var in H; try easy.\n destruct H. subst.\n constructor. apply IHwell_type_bound_in. easy. easy.\nQed.\n\n\nLemma empty_env_means_cast_bound_same :\n   forall s b, well_bound_in empty_env b  -> cast_bound s b = Some b.\nProof.\n  intros. unfold cast_bound. inv H.\n  easy. apply EnvFacts.empty_mapsto_iff in H0. inv H0.\nQed.\n\n\nLemma empty_env_means_cast_type_bound_same :\n   forall s t, well_type_bound_in empty_env t -> cast_type_bound s t t.\nProof.\n intros. \n remember empty_env as env.\n induction H. constructor.\n constructor. apply IHwell_type_bound_in. easy.\n constructor.\n constructor. subst.\n apply empty_env_means_cast_bound_same. easy.\n subst.\n apply empty_env_means_cast_bound_same. easy.\n apply IHwell_type_bound_in; easy.\n constructor. subst.\n apply empty_env_means_cast_bound_same. easy.\n subst.\n apply empty_env_means_cast_bound_same. easy.\n apply IHwell_type_bound_in; easy.\nQed.\n\n(*\nLemma lit_empty_means_cast_type_bound_same :\n  forall D F Q S H m n t t1, @well_typed D F S H empty_env Q m (ELit n t) t1 ->  cast_type_bound S t t.\nProof.\n intros. remember empty_env as env.\n inv H0.\n apply simple_type_means_cast_same.\n easy.\nQed.\n*)\n\nLemma lit_nat_type : forall D F H Q S env m n t, \n       @well_typed D F S H env Q m (ELit n t) TNat -> t = TNat.\nProof.\n intros. remember (ELit n t) as e. remember TNat as t1.\n induction H0; subst; inv Heqe.\n reflexivity.\nQed.\n\n\n(* Progress proof for args. *)\nLemma well_typed_args_same_length : forall D Q H env s es tvl,\n    @well_typed_args D Q H env s es tvl -> length es = length tvl.\nProof.\n  intros. induction H0. easy.\n  simpl. rewrite IHwell_typed_args. easy.\nQed.\n\nDefinition bound_in_stack (S: stack) (b:bound) :=\n       match b with Num n => True\n                | Var x n => Stack.In x S\n       end.\n\nInductive stack_bound_in : stack -> type -> Prop :=\n   | stack_bound_in_nat : forall env, stack_bound_in env TNat\n   | stack_bound_in_ptr : forall m t env, stack_bound_in env t -> stack_bound_in env (TPtr m t)\n   | stack_bound_in_struct : forall env T, stack_bound_in env (TStruct T)\n   | stack_bound_in_array : forall env l h t, bound_in_stack env l -> bound_in_stack env h -> \n                                      stack_bound_in env t -> stack_bound_in env (TArray l h t)\n   | stack_bound_in_ntarray : forall env l h t, bound_in_stack env l -> bound_in_stack env h -> \n                                      stack_bound_in env t -> stack_bound_in env (TNTArray l h t).\n\nFixpoint bounds_in_stack (S:stack) (l : list (var * bound)) :=\n   match l with [] => True\n            | (x,v)::xl => (bound_in_stack S v /\\ bounds_in_stack S xl)\n   end.\n\nLemma stack_in_cast_bound : forall s t, bound_in_stack s t\n              -> (exists t', cast_bound s t = Some t').\nProof.\n  intros. unfold bound_in_stack in H.\n  destruct t. exists (Num z). easy.\n  unfold Stack.In,Stack.Raw.PX.In in H.\n  destruct H. destruct x.\n  exists (Num (z+z0)).\n  unfold cast_bound.\n  apply Stack.find_1 in H. rewrite H. easy.\nQed.\n\nLemma stack_in_cast_type : forall s t, stack_bound_in s t\n              -> (exists t', cast_type_bound s t t').\nProof.\n  intros. induction H.\n  exists TNat. constructor.\n  destruct IHstack_bound_in.\n  exists (TPtr m x). constructor. easy.\n  exists (TStruct T). constructor.\n  destruct IHstack_bound_in.\n  apply stack_in_cast_bound in H0.\n  apply stack_in_cast_bound in H.\n  destruct H. destruct H0.\n  exists (TArray x0 x1 x).\n  constructor. 1-3: easy.\n  destruct IHstack_bound_in.\n  apply stack_in_cast_bound in H0.\n  apply stack_in_cast_bound in H.\n  destruct H. destruct H0.\n  exists (TNTArray x0 x1 x).\n  constructor. 1-3: easy.\nQed.\n\nLemma well_bound_stack_bound_in : forall env S t,\n  well_bound_in env t -> sub_domain env S -> bound_in_stack S t.\nProof.\n  intros. induction H.\n  constructor.\n  unfold bound_in_stack.\n  unfold sub_domain in H0.\n  unfold Env.In,Env.Raw.PX.In in H0.\n  specialize (H0 x).\n  apply H0. exists TNat. easy.\nQed.\n\nLemma well_type_stack_bound_in : forall env S t,\n  well_type_bound_in env t -> sub_domain env S -> stack_bound_in S t.\nProof.\n  intros. induction H.\n  constructor. constructor. apply IHwell_type_bound_in. easy.\n  constructor. constructor.\n  apply (well_bound_stack_bound_in env0); try easy.\n  apply (well_bound_stack_bound_in env0); try easy.\n  apply IHwell_type_bound_in. easy.\n  constructor.\n  apply (well_bound_stack_bound_in env0); try easy.\n  apply (well_bound_stack_bound_in env0); try easy.\n  apply IHwell_type_bound_in. easy.\nQed.\n\nLemma stack_bound_in_bounds : forall AS S b, bounds_in_stack S AS ->\n    bound_in_stack S b -> bound_in_stack S (subst_bounds b AS).\nProof.\n  induction AS; intros; simpl. easy.\n  destruct a.\n  apply IHAS. simpl in H. destruct H. easy.\n  simpl in H. destruct H.\n  unfold subst_bound. destruct b. easy.\n  destruct (var_eq_dec v0 v).\n  destruct b0. constructor.\n  unfold bound_in_stack.\n  inv H. unfold Stack.In,Stack.Raw.PX.In.\n  exists x. easy.\n  easy.\nQed.\n\nLemma stack_bound_in_subst_type : forall S AS t, bounds_in_stack S AS -> \n         stack_bound_in S t -> stack_bound_in S (subst_type AS t).\nProof.\n  intros. induction H0; simpl.\n  constructor. constructor. apply IHstack_bound_in. easy. constructor.\n  constructor.\n  apply stack_bound_in_bounds; try easy.\n  apply stack_bound_in_bounds; try easy.\n  apply IHstack_bound_in. easy.\n  constructor.\n  apply stack_bound_in_bounds; try easy.\n  apply stack_bound_in_bounds; try easy.\n  apply IHstack_bound_in. easy.\nQed.\n\nLemma eval_arg_exists : forall S env e t,\n         well_type_bound_in env t -> sub_domain env S ->\n         ((exists n t, e = ELit n t) \\/ (exists y, e = EVar y /\\ Env.In y env))\n          -> (exists n' t', eval_arg S e t (ELit n' t')).\nProof.\n intros. destruct H1. destruct H1. destruct H1. subst.\n assert (exists t', cast_type_bound S t t').\n apply stack_in_cast_type.\n apply (well_type_stack_bound_in env0); try easy.\n destruct H1.\n exists x. exists x1. constructor. easy.\n destruct H1. destruct H1. subst.\n assert (exists t', cast_type_bound S t t').\n apply stack_in_cast_type.\n apply (well_type_stack_bound_in env0); try easy.\n destruct H1.\n unfold sub_domain in H0. apply H0 in H2.\n destruct H2. destruct x1.\n exists z. exists x0.\n apply eval_var with (t' := t0).\n easy. easy. \nQed.\n\nLemma typed_args_values :\n    forall tvl es D Q S H env AS, \n        sub_domain env S ->\n        bounds_in_stack S AS ->\n        @well_typed_args D Q H env AS es tvl ->\n          (exists S', @eval_el AS S tvl es S').\nProof.\n  intros. induction H2.\n  exists S. constructor. \n  specialize (IHwell_typed_args H0 H1).\n  destruct IHwell_typed_args.\n  specialize (eval_arg_exists S env0 e (subst_type s t)) as X1.\n  inv H2.\n  apply simple_type_well_bound with (env := env0) in H5.\n  specialize (X1 H5 H0).\n  assert ((exists (n0 : Z) (t : type), ELit n t' = ELit n0 t) \\/\n     (exists y : var,\n        ELit n t' = EVar y /\\ Env.In (elt:=type) y env0)).\n  left. exists n. exists t'. easy.\n  apply X1 in H2. destruct H2. destruct H2.\n  exists ((Stack.add v (x0,x1) x)).\n  apply eval_el_many_2; try easy.\n  assert ((exists (n : Z) (t : type), EVar x0 = ELit n t) \\/\n     (exists y : var,\n        EVar x0 = EVar y /\\ Env.In (elt:=type) y env0)).\n  right.\n  exists x0. split. easy. exists t'. easy.\n  specialize (X1 H6 H0 H2).\n  inv H2. destruct H8. destruct H2. inv H2.\n  destruct H8. destruct H2. inv H2.\n  destruct X1. destruct H2.\n  exists ((Stack.add v (x0,x2) x)).\n  apply eval_el_many_2; try easy.\nQed.\n\nInductive well_arg_env_in : env -> expression -> Prop :=\n   | well_arg_env_lit : forall s v t, well_arg_env_in s (ELit v t)\n   | well_arg_env_var : forall s x, Env.In x s -> well_arg_env_in s (EVar x).\n\nInductive well_args_env_in : env -> list expression -> Prop :=\n   | well_args_empty : forall s, well_args_env_in s []\n   | well_args_many : forall s e es, well_arg_env_in s e -> well_args_env_in s es -> well_args_env_in s (e::es).\n\nLemma well_type_args_trans : forall D Q H env AS es tvl, @well_typed_args D Q H env AS es tvl -> well_args_env_in env es.\nProof.\n  intros. induction H0. constructor.\n  constructor.\n  inv H0. constructor.\n  constructor.\n  exists t'. easy. easy.\nQed.\n\nDefinition bounds_in_stack_inv (l : list (var * bound)) (S:stack) := forall x y n, In (x,Var y n) l -> Stack.In y S.\n\nLemma get_dept_map_bounds_in_stack_inv : forall tvl es env S AS, well_args_env_in env es\n             -> sub_domain env S -> get_dept_map tvl es = Some AS -> bounds_in_stack_inv AS S.\nProof.\n  induction tvl. intros. simpl in *. inv H1. unfold bounds_in_stack. easy.\n  intros.\n  simpl in *. destruct a. destruct t.\n  destruct es. inv H1.\n  inv H. inv H5.\n  unfold get_good_dept in *.\n  destruct (get_dept_map tvl es) eqn:eq1. inv H1.\n  specialize (IHtvl es env0 S l H6 H0 eq1).\n  unfold bounds_in_stack_inv in *.\n  intros. simpl in H. destruct H. inv H. apply IHtvl with (x := x) (y := y) (n:=n). easy.\n  inv H1.\n  unfold get_good_dept in *.\n  destruct (get_dept_map tvl es) eqn:eq1. inv H1.\n  specialize (IHtvl es env0 S l H6 H0 eq1).\n  unfold bounds_in_stack_inv in *.\n  intros. simpl in H1. destruct H1. inv H1.\n  unfold sub_domain in H0.\n  apply H0. easy.\n  apply IHtvl with (x := x0) (y := y) (n:=n). easy.\n  inv H1.\n  destruct es. inv H1.\n  inv H.\n  apply IHtvl with (es := es) (env:=env0); try easy.\n  destruct es. inv H1.\n  inv H.\n  apply IHtvl with (es := es) (env:=env0); try easy.\n  destruct es. inv H1.\n  inv H.\n  apply IHtvl with (es := es) (env:=env0); try easy.\n  destruct es. inv H1.\n  inv H.\n  apply IHtvl with (es := es) (env:=env0); try easy.\nQed.\n\nLemma bound_in_stack_correct : forall S AS, bounds_in_stack_inv AS S -> bounds_in_stack S AS.\nProof.\n  intros. induction AS. simpl in *. easy.\n  simpl in *. destruct a eqn:eq1.\n  split.\n  unfold bounds_in_stack_inv in H.\n  destruct b. unfold bound_in_stack. easy.\n  unfold bound_in_stack. apply H with (x := v) (n := z).\n  simpl. left. easy.\n  apply IHAS.\n  unfold bounds_in_stack_inv in *.\n  intros.\n  apply H with (x := x) (n:=n). simpl. right. easy.\nQed.\n\nLemma get_dept_map_bounds_in_stack : forall tvl es env S AS, well_args_env_in env es\n             -> sub_domain env S -> get_dept_map tvl es = Some AS -> bounds_in_stack S AS.\nProof.\n  intros.\n  apply bound_in_stack_correct.\n  apply get_dept_map_bounds_in_stack_inv with (tvl := tvl) (env := env0) (es := es); try easy.\nQed.\n\n(*\nDefinition sub_stack_nat (arg_env: arg_stack) (S:stack) (arg_s:stack) :=\n       (forall x v, (Stack.MapsTo x (NumVal v) arg_env -> Stack.MapsTo x (v,TNat) arg_s)) /\\\n       (forall x v t v', (Stack.MapsTo x (VarVal v) arg_env -> Stack.MapsTo v (v',t) S -> Stack.MapsTo x (v',TNat) arg_s)).\n\nLemma subtype_stack_nat : forall D S t, subtype_stack D S TNat t -> t = TNat.\nProof.\n  intros. inv H. inv H0. easy. inv H2. inv H1. easy. inv H1. inv H2. easy.\nQed.\n\nDefinition sub_list_arg_s (l : list var) (arg_s:stack) := forall x, In x l -> Stack.In x arg_s.\n\nLemma well_bound_vars_cast : forall b l s, sub_list_arg_s l s -> no_ebound b\n          -> well_bound_vars l b -> (exists b', cast_bound s b = Some (Num b')).\nProof.\n intros. induction b; simpl.\n exists z. easy.\n destruct (Stack.find (elt:=Z * type) v s) eqn:eq1.\n destruct p.\n exists ((z + z0)). easy.\n unfold sub_list_arg_s in *.\n inv H1. apply H in H4.\n unfold Stack.In,Stack.Raw.PX.In in *.\n destruct H4. apply Stack.find_1 in H1.\n rewrite H1 in eq1. inv eq1.\n inv H0.\nQed.\n\nLemma well_type_bound_vars_cast : forall t l s, sub_list_arg_s l s -> well_bound_vars_type l t ->\n               no_etype t -> (exists t', cast_type_bound s t t' /\\ simple_type t').\nProof.\n  induction t; intros; simpl.\n  exists TNat. split. constructor. constructor.\n  inv H0. apply IHt with (s := s) in H4. destruct H4.\n  exists (TPtr m x). split.  constructor. easy. constructor. easy. easy. inv H1. easy.\n  exists (TStruct s). constructor. constructor. constructor.\n  inv H0. inv H1.\n  apply IHt with (s := s) in H8; try easy. destruct H8.\n  apply well_bound_vars_cast with (s := s) in H6; try easy.\n  apply well_bound_vars_cast with (s := s) in H7; try easy.\n  destruct H6. destruct H7.\n  exists (TArray (Num x0) (Num x1) x). split. constructor. easy. easy. easy.\n  constructor. easy.\n  inv H0. inv H1.\n  apply IHt with (s := s) in H8; try easy. destruct H8.\n  apply well_bound_vars_cast with (s := s) in H6; try easy.\n  apply well_bound_vars_cast with (s := s) in H7; try easy.\n  destruct H6. destruct H7.\n  exists (TNTArray (Num x0) (Num x1) x). split. constructor. easy. easy. easy.\n  constructor. easy.\n  inv H1.\nQed.\n\n\n\n\n\nLemma subtype_no_etype : forall t D t', subtype D t t' -> no_etype t -> no_etype t'.\nProof.\n  intros. induction H; try easy.\n  inv H0. constructor. constructor. easy.\n  inv H1. constructor. inv H2. constructor.\n  inv H0. inv H4. constructor. easy.\n  inv H0. inv H4. constructor. easy.\n  inv H0. constructor. inv H3. constructor. easy.\n  inv H. constructor. constructor.\n  inv H1. constructor. constructor.\n  inv H0. constructor. inv H3. constructor. easy.\n  inv H. constructor. constructor.\n  inv H1. constructor. constructor.\n  inv H0. constructor. inv H3. constructor. easy.\n  inv H. constructor. constructor.\n  inv H1. constructor. constructor.\n  constructor. constructor.\n  constructor. constructor. constructor.\n  inv H2. constructor. inv H3. constructor.\nQed.\n\nLemma cast_bound_no_ebound : forall s b b', cast_bound s b = Some b' -> no_ebound b' -> no_ebound b.\nProof.\n  intros. induction b; simpl. easy. easy.\n  inv H. inv H0.\nQed.\n\nLemma cast_type_no_etype : forall s t t', cast_type_bound s t t' -> no_etype t' -> no_etype t.\nProof.\n  intros. induction H;simpl. easy.\n  inv H0. constructor. apply IHcast_type_bound. easy.\n  inv H0. constructor. apply IHcast_type_bound. easy.\n  apply cast_bound_no_ebound with (s := s) (b' := l'); try easy.\n  apply cast_bound_no_ebound with (s := s) (b' := h'); try easy.\n  inv H0. constructor. apply IHcast_type_bound. easy.\n  apply cast_bound_no_ebound with (s := s) (b' := l'); try easy.\n  apply cast_bound_no_ebound with (s := s) (b' := h'); try easy.\n  easy. inv H0.\nQed.\n\nLemma subtype_no_etype_r : forall t D t', subtype D t t' -> no_etype t' -> no_etype t.\nProof.\n  intros. induction H; try easy.\n  inv H0. inv H4. constructor. easy.\n  inv H1. constructor. inv H2. constructor. inv H0. easy.\n  constructor. constructor.\n  inv H0. constructor. constructor. easy.\n  inv H1. constructor. inv H2. constructor.\n  inv H0. inv H3. constructor. constructor. easy.\n  inv H. constructor. constructor. inv H1. constructor. constructor.\n  inv H0. inv H3. constructor. constructor. easy.\n  inv H. constructor. constructor. inv H1. constructor. constructor.\n  inv H0. inv H3. constructor. constructor. easy.\n  inv H. constructor. constructor. inv H1. constructor. constructor.\n  constructor. constructor.\n  constructor. constructor.\nQed.\n\nLemma cast_bound_no_ebound_r : forall s b b', cast_bound s b = Some b' -> no_ebound b -> no_ebound b'.\nProof.\n  intros. induction b; simpl. inv H. constructor. inv H. \n  destruct (Stack.find (elt:=Z * type) v s) eqn:eq1. destruct p. inv H2. constructor. inv H2.\n  inv H0.\nQed.\n\nLemma cast_type_no_etype_r : forall s t t', cast_type_bound s t t' -> no_etype t -> no_etype t'.\nProof.\n  intros. induction H;simpl. easy.\n  inv H0. constructor. apply IHcast_type_bound. easy.\n  inv H0. constructor. apply IHcast_type_bound. easy.\n  apply cast_bound_no_ebound_r with (s := s) (b := l); try easy.\n  apply cast_bound_no_ebound_r with (s := s) (b := h); try easy.\n  inv H0. constructor. apply IHcast_type_bound. easy.\n  apply cast_bound_no_ebound_r with (s := s) (b := l); try easy.\n  apply cast_bound_no_ebound_r with (s := s) (b := h); try easy.\n  easy. inv H0.\nQed.\n\nLemma subtype_stack_no_etype : forall t D s t', subtype_stack D s t t' -> no_etype t -> no_etype t'.\nProof.\n  intros. inv H.\n  apply subtype_no_etype with (t := t) (D:=D). easy. easy.\n  specialize (subtype_no_etype t D t2' H3 H0) as eq1.\n  apply cast_type_no_etype with (s := s) (t' := t2'); try easy.\n  specialize (cast_type_no_etype_r s t t1' H2 H0) as eq1. \n  specialize (subtype_no_etype t1' D t' H3 eq1) as eq2.\n  easy.\nQed.\n\nDefinition bound_env (e:env) := forall x t, Env.MapsTo x t e -> ext_type_in [] t.\n\nLemma no_ebound_ext_bound : forall b, no_ebound b -> ext_bound_in [] b.\nProof.\n  intros. induction b. constructor. constructor. inv H.\nQed.\n\nLemma no_ebound_ext_bound_anti : forall b, ext_bound_in [] b -> no_ebound b.\nProof.\n  intros. induction b. constructor. constructor. inv H. simpl in H2. inv H2.\nQed.\n\nLemma no_etype_ext_type : forall t, no_etype t -> ext_type_in [] t.\nProof.\n  intros. induction H; try constructor. easy.\n  apply no_ebound_ext_bound. easy.\n  apply no_ebound_ext_bound. easy.\n  easy.\n  apply no_ebound_ext_bound. easy.\n  apply no_ebound_ext_bound. easy.\n  easy.\nQed.\n\nLemma gen_env_ext_type : forall tvl D env env', gen_env env tvl env' ->\n        (forall x t', In (x,t') tvl -> word_type t' /\\ type_wf D t' /\\ no_etype t') -> bound_env env -> bound_env env'.\nProof.\n  induction tvl; intros; simpl.\n  inv H. easy.\n  unfold bound_env in *. intros.\n  inv H.\n  assert ((forall (x : var) (t' : type),\n         In (x, t') tvl ->\n         word_type t' /\\ type_wf D t' /\\ no_etype t')).\n  intros.\n  specialize (H0 x1 t').\n  assert (In (x1, t') ((x0, t0) :: tvl)).\n  simpl. right. easy. apply H0 in H3. easy.\n  specialize (IHtvl D env0 env'0 H7 H H1).\n  destruct (Nat.eq_dec x x0). subst.\n  apply Env.mapsto_add1 in H2. subst.\n  apply no_etype_ext_type.\n  specialize (H0 x0 t0).\n  assert (In (x0, t0) ((x0, t0) :: tvl)). simpl. left. easy.\n  apply H0 in H2. easy.\n  apply Env.add_3 in H2. apply IHtvl with (x := x). easy. lia.\nQed.\n\nLemma vars_to_ext_bound : forall t t' l, (forall x, In x (get_tvars t) -> In x l)\n              -> vars_to_ext l t t' -> ext_type_in [] t'.\nProof.\n  induction t; intros; simpl.\n  inv H0. constructor.\n  inv H2. inv H1. constructor. constructor.\n  inv H3.\nAdmitted.\n\nLemma to_ext_ext_type : forall t x t', to_ext_type x t t' -> ext_type_in [] t -> ext_type_in [x] t'.\nProof.\n  induction t; intros;simpl. inv H. constructor.\n  inv H. inv H0. constructor. apply IHt. easy. easy.\n  inv H. constructor.\n  inv H.\nAdmitted.\n\nLemma simple_type_ext_type : forall t, simple_type t -> ext_type_in [] t.\nProof.\n  intros. induction H. constructor. constructor. apply IHsimple_type.\n  constructor. constructor. constructor. constructor. easy.\n  constructor.  constructor.  constructor. easy.\nQed.\n\nLemma ext_type_well_bound : forall e D F st env m t, expr_wf D F e -> fun_wf D F -> structdef_wf D ->\n          bound_env env -> @well_typed D F st env m e t -> ext_type_in [] t.\nProof.\n  intros. induction H3; simpl.\n  inv H. apply no_etype_ext_type. easy.\n  inv H. unfold bound_env in H2. apply H2 with (x := x). easy.\n  apply vars_to_ext_bound with (t := t) (l := get_tvars t).\n  intros. easy. easy. constructor.\n  constructor.\n  apply to_ext_ext_type with (t := t). easy.\n  apply IHwell_typed2. inv H. easy.\n  unfold bound_env in *. intros.\n  destruct (Nat.eq_dec x0 x). subst.\n  apply Env.mapsto_add1 in H5. subst. constructor.\n  apply Env.add_3 in H5. apply H2 with (x := x0). easy. lia.\n  inv H.\n  apply IHwell_typed2. easy.\n  unfold bound_env in *. intros.\n  destruct (Nat.eq_dec x0 x). subst.\n  apply Env.mapsto_add1 in H. subst. apply IHwell_typed1. easy. easy.\n  apply Env.add_3 in H. apply H2 with (x := x0). easy. lia.\n  inv H.\n  apply IHwell_typed; try easy.\n  constructor.\n  unfold structdef_wf in H1.\n  specialize (H1 T fs). apply H1 in H4. unfold fields_wf in H4.\n  apply H4 in H5. destruct H5 as [X1 [X2 X3]].\n  constructor.\n  apply simple_type_ext_type. easy. inv H.\n  constructor. apply no_etype_ext_type. easy.\n  apply IHwell_typed.  inv H. easy. easy.\n  inv H. apply no_etype_ext_type. easy.\n  inv H. apply no_etype_ext_type. easy.\n  inv H. apply no_etype_ext_type. easy.\n  inv H. apply no_etype_ext_type. inv H11. inv H7. constructor. constructor. easy.\n  constructor. constructor.\n  inv H. apply no_etype_ext_type. inv H10. inv H6. constructor. constructor. easy.\n  easy. easy.\n  inv H.\n  apply IHwell_typed in H8.\nAdmitted.\n\n\nLemma subtype_word_type : forall D m t1 t2, word_type t1 -> \n        subtype D (TPtr m t1) (TPtr m t2) -> t2 = t1 \\/ (exists l h, nat_leq (Num 0) l\n                                   /\\ nat_leq h (Num 1) /\\ t2 = TArray l h t1).\nProof.\n  intros. \n  inv H0. left. easy.\n  right. exists l. exists h. easy.\n  inv H. inv H. inv H. inv H. inv H.\n  inv H. inv H.\nQed.\n\n\n*)\n\nLemma replicate_gt_eq : forall x t, 0 < x -> Z.of_nat (length (Zreplicate (x) t)) = x.\nProof.\n  intros.\n  unfold Zreplicate.\n  destruct x eqn:eq1. lia.\n  simpl. \n  rewrite replicate_length. lia.\n  lia.\nQed.\n\nLemma gen_rets_exist: forall tvl (S S':stack) AS es e, length es = length tvl ->\n         eval_el AS S tvl es S' -> (exists e', gen_rets AS S tvl es e e').\nProof.\n  induction tvl. intros.\n  simpl in *.\n  destruct es. exists e.\n  constructor. simpl in *. inv H.\n  intros.\n  destruct es. inv H. inv H0.\n  assert (length es = length tvl). inv H. easy.\n  apply IHtvl with (AS:= AS) (S := S) (S' := s') (e := e) in H0; try easy.\n  destruct H0. \n  exists (ERet x (n,t') x0).\n  constructor. easy. easy.\nQed.\n\nLemma subtype_well_type : forall D Q H env t t' n,\nsimple_type t -> \nsimple_type t' -> type_wf D t' ->\n@well_typed_lit D Q H env n t ->\nsubtype D Q t t' ->\n@well_typed_lit D Q H env n t'.\nProof.\n  intros. induction H3. \n  - inv H4. eauto.\n  - assert (exists t, t' = (TPtr Unchecked t)) by (inv H4; eauto).\n    destruct H3. rewrite H3. eauto.\n  - eauto.\n  - specialize (subtype_trans D Q t t' Checked w) as eq1.\n\n    assert (exists t0, t' = (TPtr Checked t0)) by (inv H4; eauto).\n    destruct H6. rewrite H6 in *.\n    eapply TyLitRec; eauto.\n  - assert (exists t0, t' = (TPtr Checked t0)) by (inv H4; eauto).\n    destruct H9. subst.\n    assert (subtype D Q (TPtr Checked w) (TPtr Checked x)).\n    apply subtype_trans with (m := Checked) (w := t); try easy.\n    eapply TyLitC;eauto.\n    unfold nt_array_prop in *.\n    destruct t. inv H4; try easy.\n    inv H4; try easy.\n    inv H4; try easy.\n    inv H4; try easy.\n    destruct x; try easy.\n    inv H4; try easy.\n    destruct x; try easy.\n    inv H0. inv H1. inv H4. inv H10. inv H12. inv H16. easy.\nQed.\n\n(*\nLemma well_typed_lit_reduce : forall t D Q H s n1 tv n, \n    @get_root D (TPtr Checked t) tv ->\n    well_typed_lit D Q H (set_add eq_dec_nt (n1, TPtr Checked t) s) n tv ->\n    well_typed_lit D Q H s n tv.\nProof.\n  induction t;intros;simpl. inv H0.\n  constructor.\n  inv H1. constructor. constructor.\n  apply set_add_elim in H6. destruct H6.\n  inv H1. inv H0. inv H7. admit. admit. inv H7. admit. admit. admit.\n  admit. inv H7. admit. admit. admit. admit. admit.\n  apply TyLitRec with (t := t0); try easy.\n  inv H0. destruct m.\nQed.\n*)\n\nLemma stack_wf_sub : forall D Q env S, stack_wf D Q env S -> sub_domain env S.\nProof.\n  intros. unfold stack_wf,sub_domain in *.\n  intros. destruct H0. apply H in H0.\n  destruct H0. destruct H0. destruct H0.\n  exists (x1,x3). easy.\nQed.\n\n(* Define the property of a stack. *)\nDefinition stack_wt D (S:stack) := \n    forall x v t, Stack.MapsTo x (v,t) S -> word_type t /\\ type_wf D t /\\ simple_type t.\n\nDefinition env_wt D (env : env) :=\n    forall x t, Env.MapsTo x t env -> word_type t /\\ type_wf D t /\\ well_type_bound_in env t.\n\nDefinition theta_wt (Q:theta) (env:env) (S:stack) :=\n     (forall x, Theta.In x Q -> Env.In x env)\n  /\\ (forall x n ta, Theta.MapsTo x GeZero Q -> Stack.MapsTo x (n,ta) S -> 0 <= n).\n\nLemma cast_bound_num : forall s b b1, cast_bound s b = Some b1 -> (exists n, b1 = Num n).\nProof.\n  intros. unfold cast_bound in *.\n  destruct b. exists z. inv H. easy.\n  destruct (Stack.find (elt:=Z * type) v s). destruct p.\n  inv H.  exists (z+z0). easy.\n  inv H.\nQed.\n\n\nLemma cast_means_simple_type : forall s t t', cast_type_bound s t t' -> simple_type t'.\nProof.\n  intros. induction H. \n  apply SPTNat. apply SPTPtr. assumption.\n  unfold cast_bound in *.\n  destruct l. destruct h.\n  injection H as eq1. injection H0 as eq2.\n  subst. \n  apply SPTArray. assumption.\n  destruct (Stack.find (elt:=Z * type) v s).\n  destruct p.\n  injection H0 as eq1. injection H as eq2. subst.\n  apply SPTArray. assumption.\n  inv H0.\n  destruct (Stack.find (elt:=Z * type) v s). destruct p.\n  destruct h.\n  inv H. inv H0.\n  apply SPTArray. assumption.\n  destruct (Stack.find (elt:=Z * type) v0 s). destruct p.\n  inv H. inv H0.\n  apply SPTArray. assumption.\n  inv H0. inv H.\n  unfold cast_bound in *.\n  destruct l. destruct h.\n  injection H as eq1. injection H0 as eq2.\n  subst. \n  apply SPTNTArray. assumption.\n  destruct (Stack.find (elt:=Z * type) v s).\n  destruct p.\n  inv H. inv H0.\n  apply SPTNTArray. assumption.\n  inv H0.\n  destruct (Stack.find (elt:=Z * type) v s). destruct p.\n  destruct h.\n  inv H. inv H0.\n  apply SPTNTArray. assumption.\n  destruct (Stack.find (elt:=Z * type) v0 s). destruct p.\n  inv H. inv H0.\n  apply SPTNTArray. assumption.\n  inv H0. inv H.\n  apply SPTStruct.\nQed.\n\n(* The Type Progress Theorem *)\nLemma progress : forall D Q H s env m e t,\n    structdef_wf D ->\n    heap_wf D H ->\n    fun_wf D fenv ->\n    expr_wf D fenv e ->\n    stack_wt D s ->\n    env_wt D env ->\n    theta_wt Q env s ->\n    stack_wf D Q env s ->\n    stack_heap_consistent D Q H s ->\n    @well_typed D fenv s H env Q m e t ->\n    value D e \\/\n    reduces D (fenv env) s H e \\/\n    unchecked m e.\nProof with eauto 20 with Progress.\n  intros D Q H st env m e t HDwf HHwf Hfun Hewf HSwt Henv HQt HSwf HSHwf Hwt.\n  induction Hwt as [\n                     env Q m n t HTyLit                                         | (* Literals *)\n                     env Q m x t Wb                                             | (* Variables *)\n                     env Q AS m m' es x tvl e t HMap HGen HMode HArg            | (* Call *)\n                     env Q m x h l t Wb                                         | (* Strlen *)\n                     env Q m x y e l h t ta Alpha Wb HTy IH Hx                  | (* LetStrlen *)\n                     env Q m x e1 e2 t b Alpha HTy1 IH1 HTy2 IH2 Hx Hdept       | (* Let-Nat-Expr *)\n                     env Q m x e1 t1 e2 t Alpha HTy1 IH1 HTy2 IH2 Hx            | (* Let-Expr *)\n                     env Q m x na e t HIn Hx HTy1 IH1                           | (* RetNat *)\n                     env Q m x na ta e t HIn HTy1 IH1 Hx                        | (* Ret *)\n                     env Q m e1 e2 HTy1 IH1 HTy2 IH2                            | (* Addition *)\n                     env Q m e m' T fs i fi ti HTy IH HWf1 HWf2                 | (* Field Addr *)\n                     env Q m w Wb                                               | (* Malloc *)\n                     env Q m e t HTy IH                                         | (* Unchecked *)\n                     env Q m t e t' Wb HChkPtr HTy IH                           | (* Cast - nat *)\n                     env Q m t e t' Wb HTy IH HSub                              | (* Cast - subtype *)\n                     env Q m e x y u v t t' Wb HTy IH Teq                       | (* DynCast - ptr array *)\n                     env Q m e x y t t' HNot Teq Wb HTy IH                      | (* DynCast - ptr array from ptr *)\n                     env Q m e x y u v t t' Wb Teq HTy IH                       | (* DynCast - ptr nt-array *)\n                     env Q m e m' t l h t' t'' HTy IH HSub HPtrType HMode       | (* Deref *)\n                     env Q m e1 m' l h e2 t WT Twf HTy1 IH1 HTy2 IH2 HMode                      | (* Index for array pointers *)\n                     env Q m e1 m' l h e2 t WT Twf HTy1 IH1 HTy2 IH2 HMode                      | (* Index for ntarray pointers *)\n                     env Q m e1 e2 m' t t1 HSub WT HTy1 IH1 HTy2 IH2 HMode                      | (* Assign normal *)\n                     env Q m e1 e2 m' l h t t' WT Twf HSub HTy1 IH1 HTy2 IH2 HMode              | (* Assign array *)\n                     env Q m e1 e2 m' l h t t' WT Twf HSub HTy1 IH1 HTy2 IH2 HMode              | (* Assign nt-array *)\n\n                     env Q m e1 e2 e3 m' l h t t' WT Twf TSub HTy1 IH1 HTy2 IH2 HTy3 IH3 HMode      |  (* IndAssign for array pointers *)\n                     env Q m e1 e2 e3 m' l h t t' WT Twf TSub HTy1 IH1 HTy2 IH2 HTy3 IH3 HMode      |  (* IndAssign for ntarray pointers *)\n                     env Q m m' x t1 e1 e2 t2 t3 t4 HEnv HPtr HTy1 IH1 HTy2 IH2 HJoin HMode         | (*  IfDef *)\n                     env Q m m' x l t e1 e2 t2 t3 t4 HEnv HTy1 IH1 HTy2 IH2 HJoin HMode             | (* IfDefNT *)\n                     env Q m e1 e2 e3 t2 t3 t4 HTy1 IH1 HTy2 IH2 HTy3 IH3 HJoin (* If *)\n                 ]; clean.\n  (* Case: TyLit *)\n  - (* Holds trivially, since literals are values *)\n    left...\n    inv Hewf. apply VLit. 1-3:assumption.\n  (* Case: TyVar *)\n  - (* Impossible, since environment is empty *)\n    right. left. \n    apply HSwf in Wb as eq1.\n    destruct eq1 as [va [ta [tb [X1 [X2 X3]]]]].\n    eapply step_implies_reduces.\n    Check SVar.\n    apply (SVar D (fenv env) st H x va tb); try easy.\n\n  - (* Call Case *)\n    right. left. inv Hewf.\n    specialize (well_typed_args_same_length D Q H env AS es tvl HArg) as X1.\n    assert (sub_domain env st). apply stack_wf_sub in HSwf; try easy.\n    specialize (typed_args_values tvl es D Q st H env AS H0) as X3.\n    assert (bounds_in_stack st AS).\n    apply get_dept_map_bounds_in_stack with (tvl := tvl) (es := es) (env := env); try easy.\n    apply (well_type_args_trans D Q H env AS es tvl); try easy.\n    specialize (X3 H1 HArg). destruct X3.\n    specialize (gen_rets_exist tvl st x0 AS es e X1 H4) as X2.\n    destruct X2.\n    eapply step_implies_reduces.\n    Check SCall.\n    apply (SCall D (fenv env) AS st x0 H x es t tvl e x1 m'); try easy.\n  -   (* Case: TyStrlen *)\n    destruct m.\n    right. left.\n    apply HSwf in Wb as eq1.\n    destruct eq1 as [va [ta [tb [X1 [X2 X3]]]]].\n    inv X1. inv H3.\n    inv X2.\n    apply cast_bound_num in H4 as eq2.\n    destruct eq2. subst.\n    apply cast_bound_num in H6 as eq2.\n    destruct eq2. subst.\n\n    destruct (Z_gt_dec x0 0).\n\n    (* if l > 0 we have a bounds error*)\n    {\n       eapply step_implies_reduces. \n       eapply (StrlenLowOOB);eauto.\n    }\n\n    destruct (Z_le_dec x1 0).\n\n    (* if h <= 0 we have a bounds error*)\n    {\n       eapply step_implies_reduces. \n       eapply (StrlenHighOOB) with (h := x1);eauto.\n    }\n\n    destruct (Z_le_dec va 0).\n\n    (* if h <= 0 we have a bounds error*)\n    {\n       eapply step_implies_reduces. \n       eapply (StrlenNull);eauto.\n    }\n    \n    apply HSHwf in X3 as eq1.\n    inv eq1. lia.\n    solve_empty_scope.\n    unfold nt_array_prop in H5.\n    destruct H5 as [n' [t' [Y1 [Y2 Y3]]]].\n    eapply step_implies_reduces. \n    eapply (Strlen);eauto. lia.\n    inv H2. inv H2.\n\n    apply cast_bound_num in H4 as eq2.\n    destruct eq2. subst.\n    apply cast_bound_num in H6 as eq2.\n    destruct eq2. subst.\n\n\n    apply HSwt in X3 as eq1.\n    destruct eq1 as [Y4 [Y5 Y6]].\n    inv Y6. inv H1.\n    inv H3. inv H9.\n\n    destruct (Z_gt_dec l1 0).\n\n    (* if l > 0 we have a bounds error*)\n    {\n       eapply step_implies_reduces. \n       eapply (StrlenLowOOB);eauto.\n    }\n\n    destruct (Z_le_dec h1 0).\n\n    (* if h <= 0 we have a bounds error*)\n    {\n       eapply step_implies_reduces. \n       eapply (StrlenHighOOB) with (h := h1);eauto.\n    }\n\n    destruct (Z_le_dec va 0).\n\n    (* if h <= 0 we have a bounds error*)\n    {\n       eapply step_implies_reduces. \n       eapply (StrlenNull);eauto.\n    }\n\n\n    apply HSHwf in X3 as eq1.\n    inv eq1. lia.\n    solve_empty_scope.\n    unfold nt_array_prop in H10.\n    destruct H10 as [n' [t' [Y1 [Y2 Y3]]]].\n    eapply step_implies_reduces. \n    eapply (Strlen);eauto. lia.\n    right. right.\n    unfold unchecked. left. easy.\n\n  -   (* Case: TyLetStrlen *)\n    destruct m.\n    right. left.\n    apply HSwf in Wb as eq1.\n    destruct eq1 as [va [tc [td [X1 [X2 X3]]]]].\n    inv X1. inv H3.\n\n    apply cast_bound_num in H4 as eq2.\n    destruct eq2. subst.\n    apply cast_bound_num in H6 as eq2.\n    destruct eq2. subst.\n\n    inv X2.\n\n    destruct (Z_gt_dec x0 0).\n\n    (* if l > 0 we have a bounds error*)\n    {\n       ctx (ELet x (EStrlen y) e) (in_hole (EStrlen y) (CLet x CHole e))...  \n    }\n\n    destruct (Z_le_dec x1 0).\n\n    (* if h <= 0 we have a bounds error*)\n    {\n       ctx (ELet x (EStrlen y) e) (in_hole (EStrlen y) (CLet x CHole e))...  \n    }\n\n    destruct (Z_le_dec va 0).\n\n    (* if h <= 0 we have a bounds error*)\n    {\n       ctx (ELet x (EStrlen y) e) (in_hole (EStrlen y) (CLet x CHole e))...  \n    }\n\n    \n    \n    apply HSHwf in X3 as eq1.\n    inv eq1. lia.\n    solve_empty_scope.\n    unfold nt_array_prop in H5.\n    destruct H5 as [n' [t' [Y1 [Y2 Y3]]]].\n    ctx (ELet x (EStrlen y) e) (in_hole (EStrlen y) (CLet x CHole e)).\n    rewrite HCtx.\n    unfold reduces.\n    exists Checked. exists (change_strlen_stack st y Checked t'0 x0 va n' x1). exists H.\n    exists (RExpr ((in_hole (ELit n' TNat) (CLet x CHole e)))).\n    eapply RSExp; eauto.\n    apply (Strlen) with (t1 := t');eauto. lia.\n    inv H2. inv H2.\n\n    apply cast_bound_num in H4 as eq2.\n    destruct eq2. subst.\n    apply cast_bound_num in H6 as eq2.\n    destruct eq2. subst.\n\n\n    apply HSwt in X3 as eq1.\n    destruct eq1 as [Y4 [Y5 Y6]].\n    inv Y6. inv H1.\n    inv H3. inv H9.\n\n    destruct (Z_gt_dec l1 0).\n\n    (* if l > 0 we have a bounds error*)\n    {\n       ctx (ELet x (EStrlen y) e) (in_hole (EStrlen y) (CLet x CHole e))...  \n    }\n\n    destruct (Z_le_dec h1 0).\n\n    (* if h <= 0 we have a bounds error*)\n    {\n       ctx (ELet x (EStrlen y) e) (in_hole (EStrlen y) (CLet x CHole e))...  \n    }\n\n    destruct (Z_le_dec va 0).\n\n    (* if h <= 0 we have a bounds error*)\n    {\n       ctx (ELet x (EStrlen y) e) (in_hole (EStrlen y) (CLet x CHole e))...  \n    }\n\n\n    apply HSHwf in X3 as eq1.\n    inv eq1. lia.\n    solve_empty_scope.\n    unfold nt_array_prop in H11.\n    destruct H11 as [n' [t' [Y1 [Y2 Y3]]]].\n    ctx (ELet x (EStrlen y) e) (in_hole (EStrlen y) (CLet x CHole e)).\n    rewrite HCtx.\n    unfold reduces.\n    exists Checked. exists (change_strlen_stack st y Checked t'0 l1 va n' h1). exists H.\n    exists (RExpr ((in_hole (ELit n' TNat) (CLet x CHole e)))).\n    eapply RSExp; eauto.\n    apply (Strlen) with (t1 := t');eauto. lia.\n    inv H5.\n\n    right. right.\n    unfold unchecked. left. easy.\n\n  (* Case: TyLetNat *)\n  - (* `ELet x e1 e2` is not a value *)\n    right.\n    (* Invoke the IH on `e1` *)\n    inv Hewf.\n    apply (IH1) in H2; try easy.\n    destruct H2 as [ HVal1 | [ HRed1 | HUnchk1 ] ].\n    (* Case: `e1` is a value *)\n    + (* We can take a step according to SLet *)\n      left.  \n      inv HVal1...\n      apply (step_implies_reduces D (fenv env) H st \n              (ELet x (ELit n t0) e2) H (Stack.add x (n, t0) st) (RExpr(ERet x (n,t0) e2))).\n      apply SLet.\n      apply simple_type_means_cast_same. easy.\n    (* Case: `e1` reduces *)\n    + (* We can take a step by reducing `e1` *)\n      left.\n      ctx (ELet x e1 e2) (in_hole e1 (CLet x CHole e2))...\n    (* Case: `e1` is unchecked *)\n    + (* `ELet x e1 e2` must be unchecked, since `e1` is *)\n      right.\n      ctx (ELet x e1 e2) (in_hole e1 (CLet x CHole e2)).\n      destruct HUnchk1...\n  (* Case: TyLet *)\n  - (* `ELet x e1 e2` is not a value *)\n    right.\n    (* Invoke the IH on `e1` *)\n    inv Hewf.\n    apply (IH1) in H2; try easy.\n    destruct H2 as [ HVal1 | [ HRed1 | HUnchk1 ] ].\n    (* Case: `e1` is a value *)\n    + (* We can take a step according to SLet *)\n      left.  \n      inv HVal1...\n      apply (step_implies_reduces D (fenv env) H st \n              (ELet x (ELit n t0) e2) H (Stack.add x (n, t0) st) (RExpr(ERet x (n,t0) e2))).\n      apply SLet.\n      apply simple_type_means_cast_same.\n      easy.\n    (* Case: `e1` reduces *)\n    + (* We can take a step by reducing `e1` *)\n      left.\n      ctx (ELet x e1 e2) (in_hole e1 (CLet x CHole e2))...\n    (* Case: `e1` is unchecked *)\n    + (* `ELet x e1 e2` must be unchecked, since `e1` is *)\n      right.\n      ctx (ELet x e1 e2) (in_hole e1 (CLet x CHole e2)).\n      destruct HUnchk1...\n  (* Case: TyRet *)\n  - (* `ELet x e1 e2` is not a value *)\n    right.\n    (* Invoke the IH on `e1` *)\n    inv Hewf.\n    apply (IH1) in H4; try easy.\n    destruct H4 as [ HVal1 | [ HRed1 | HUnchk1 ] ].\n    (* Case: `e1` is a value *)\n    + (* We can take a step according to SLet *)\n      left.  \n      inv HVal1...\n    (* Case: `e1` reduces *)\n    + (* We can take a step by reducing `e1` *)\n      left.\n      ctx (ERet x (na, TNat) e) (in_hole e (CRet x (na, TNat) CHole))...\n    (* Case: `e1` is unchecked *)\n    + (* `ELet x e1 e2` must be unchecked, since `e1` is *)\n      right.\n      ctx (ERet x (na, TNat) e) (in_hole e (CRet x (na, TNat) CHole))...\n      destruct HUnchk1...\n  - (* `ELet x e1 e2` is not a value *)\n    right.\n    (* Invoke the IH on `e1` *)\n    inv Hewf.\n    apply (IH1) in H4; try easy.\n    destruct H4 as [ HVal1 | [ HRed1 | HUnchk1 ] ].\n    (* Case: `e1` is a value *)\n    + (* We can take a step according to SLet *)\n      left.  \n      inv HVal1...\n    (* Case: `e1` reduces *)\n    + (* We can take a step by reducing `e1` *)\n      left.\n      ctx (ERet x (na, ta) e) (in_hole e (CRet x (na, ta) CHole))...\n    (* Case: `e1` is unchecked *)\n    + (* `ELet x e1 e2` must be unchecked, since `e1` is *)\n      right.\n      ctx (ERet x (na, ta) e) (in_hole e (CRet x (na, ta) CHole))...\n      destruct HUnchk1...\n  (* Case: TyPlus *)\n  - (* `EPlus e1 e2` isn't a value *)\n    right.\n    inv Hewf.\n    apply (IH1) in H2; try easy.\n    (* Invoke the IH on `e1` *)\n    destruct H2 as [ HVal1 | [ HRed1 | HUnchk1 ] ].\n    (* Case: `e1` is a value *)\n    + (* We don't know if we can take a step yet, since `e2` might be unchecked. *)\n      inv HVal1 as [ n1 t1 ].\n      (* Invoke the IH on `e2` *)\n      apply (IH2) in H3; try easy.\n      destruct H3 as [ HVal2 | [ HRed2 | HUnchk2 ] ].\n      (* Case: `e2` is a value *)\n      * (* We can step according to SPlus *)\n        left.\n        inv HVal2 as [ n2 t2 ]...\n        eapply (step_implies_reduces D (fenv env) H st (EPlus (ELit n1 t1) (ELit n2 t2)) H st (RExpr (ELit (n1 + n2) t1))).\n        apply lit_nat_type in HTy2. subst.\n        apply (@SPlus D (fenv env) st H t1 n1 n2).\n        apply lit_nat_type in HTy1. subst.\n        unfold is_array_ptr. easy.\n      (* Case: `e2` reduces *)\n      * (* We can take a step by reducing `e2` *)\n        left.\n        ctx (EPlus (ELit n1 t1) e2) (in_hole e2 (CPlusR n1 t1 CHole))...\n      (* Case: `e2` is unchecked *)\n      * (* `EPlus (n1 t1) e2` must be unchecked, since `e2` is *)\n        right.\n        ctx (EPlus (ELit n1 t1) e2) (in_hole e2 (CPlusR n1 t1 CHole)).\n        destruct HUnchk2...\n    (* Case: `e1` reduces *)\n    + (* We can take a step by reducing `e1` *)\n      left.\n      ctx (EPlus e1 e2) (in_hole e1 (CPlusL CHole e2))...\n    (* Case: `e1` is unchecked *)\n    + (* `EPlus e1 e2` must be unchecked, since `e1` is *)\n      right.\n      ctx (EPlus e1 e2) (in_hole e1 (CPlusL CHole e2)).\n      destruct HUnchk1...\n  (* Case: TyFieldAddr *)\n  - (* `EFieldAddr e fi` isn't a value *)\n    right.\n    inv Hewf.\n    apply (IH) in H2; try easy.\n    (* Invoke the IH on `e` *)\n    destruct H2 as [ HVal | [ HRed | HUnchk ] ].\n    (* Case: `e` is a value *)\n    + (* So we can take a step... but how? *)\n      left.\n      inv HVal.\n      inv HTy.\n      {\n        (* We proceed by case analysis on `m'` -- the mode of the pointer *)\n        destruct m'.\n        (* Case: m' = Checked *)\n        * (* We now proceed by case analysis on 'n > 0' *)\n          destruct (Z_gt_dec n 0).\n          (* Case: n > 0 *)\n          { (* We can step according to SFieldAddrChecked  *)\n            assert (HWf3 := HDwf T fs HWf1). (* TODO(ins): turn these into lemmas, and stick into Progress db *)\n            assert (HWf4 := HWf3 fi ti HWf2).\n            destruct HWf4... }\n          (* Case: n <= 0 *)\n          { (* We can step according to SFieldAddrNull *)\n             subst...   }\n        (* Case: m' = Unchecked *)\n        * (* We can step according to SFieldAddr *)\n          eapply step_implies_reduces; eapply SFieldAddr; eauto.\n          { (* LEO: This should probably be abstracted into a lemma *)\n            apply HDwf in HWf1.\n            apply HWf1 in HWf2.\n            destruct HWf2...\n          }\n      }\n\n        \n    (* Case: `e` reduces *)\n    + (* We can take a step by reducing `e` *)\n      left.\n      ctx (EFieldAddr e fi) (in_hole e (CFieldAddr CHole fi))...\n    (* Case: `e` is unchecked *)\n    + (* `EFieldAddr e fi` must be unchecked, since `e` is *)\n      right.\n      ctx (EFieldAddr e fi) (in_hole e (CFieldAddr CHole fi)).\n      destruct HUnchk...\n  (* Case: TyMalloc *)\n  - (* `EMalloc w` isn't a value *)\n    right.\n    left.\n    inv Hewf.\n    apply gen_cast_type_bound_same with (s := st) in Wb as eq1.\n    2: { apply stack_wf_sub in HSwf; easy. }\n    destruct eq1 as [w' eq1]. destruct w'.\n    apply cast_means_simple_type in eq1 as eq2.\n    inv eq1.\n    * assert ((forall (l h : Z) (t : type),\n       TNat = TArray (Num l) (Num h) t -> l = 0 /\\ h > 0)).\n      intros. inv H0.\n      assert (((forall (l h : Z) (t : type),\n       TNat = TNTArray (Num l) (Num h) t -> l = 0 /\\ h > 0))).\n       intros. inv H2.\n       destruct ((wf_implies_allocate D TNat H H0 H2 eq2 H1)) as [ n [ H' HAlloc]].\n       apply (step_implies_reduces D (fenv env) H st (EMalloc TNat) H' st (RExpr (ELit n (TPtr Checked TNat)))).\n       apply SMalloc. constructor.\n       easy. easy.\n   * assert ((forall (l h : Z) (t : type),\n       (TPtr m0 w') = TArray (Num l) (Num h) t -> l = 0 /\\ h > 0)).\n      intros. inv H0.\n      assert (((forall (l h : Z) (t : type),\n       (TPtr m0 w') = TNTArray (Num l) (Num h) t -> l = 0 /\\ h > 0))).\n      intros. inv H2.\n      apply cast_means_simple_type in eq1 as eq2.\n      apply cast_type_wf with (D := D) in eq1 as eq3; try easy.\n       destruct ((wf_implies_allocate D (TPtr m0 w') H H0 H2 eq2 eq3)) as [ n [ H' HAlloc]].\n       apply (step_implies_reduces D (fenv env) H st (EMalloc w) H' st (RExpr (ELit n (TPtr Checked (TPtr m0 w'))))).\n       apply SMalloc. easy.\n       unfold malloc_bound. easy.\n       easy.\n   * assert ((forall (l h : Z) (t : type),\n       (TStruct s) = TArray (Num l) (Num h) t -> l = 0 /\\ h > 0)).\n      intros. inv H0.\n      assert (((forall (l h : Z) (t : type),\n       (TStruct s) = TNTArray (Num l) (Num h) t -> l = 0 /\\ h > 0))).\n      intros. inv H2.\n      apply cast_means_simple_type in eq1 as eq2.\n      apply cast_type_wf with (D := D) in eq1 as eq3; try easy.\n       destruct ((wf_implies_allocate D (TStruct s) H H0 H2 eq2 eq3)) as [ n [ H' HAlloc]].\n       apply (step_implies_reduces D (fenv env) H st (EMalloc w) H' st (RExpr (ELit n (TPtr Checked (TStruct s))))).\n       apply SMalloc. easy. easy.\n       assumption.\n   * apply cast_means_simple_type in eq1 as eq2.\n     apply cast_type_wf with (D := D) in eq1 as eq3; try easy.\n     inv eq2.\n     destruct (Z.eq_dec l 0).\n     destruct (0 <? h) eqn:eq2.\n     apply Z.ltb_lt in eq2.\n     assert ((forall (l' h' : Z) (t : type),\n       (TArray (Num l) (Num h) w') = TArray (Num l') (Num h') t -> l' = 0 /\\ h' > 0)).\n      intros. split. injection H0.\n      intros. subst. reflexivity.\n      injection H0. intros. subst.  lia.\n      assert ((forall (l' h' : Z) (t : type),\n       (TArray (Num l) (Num h) w') = TNTArray (Num l') (Num h') t -> l' = 0 /\\ h' > 0)).\n       intros. inv H3.\n       apply cast_means_simple_type in eq1 as eq4.\n       destruct ((wf_implies_allocate D (TArray (Num l) (Num h) w') H H0 H3 eq4 eq3)) as [ n [ H' HAlloc]].\n       apply (step_implies_reduces D (fenv env) H st (EMalloc w)\n                             H' st (RExpr (ELit n (TPtr Checked (TArray (Num l) (Num h) w'))))).\n       apply SMalloc. easy.\n       unfold malloc_bound. split. easy. lia. easy.\n       assert (h <= 0).\n       specialize (Z.ltb_lt 0 h) as eq4.\n       apply not_iff_compat in eq4.\n       assert((0 <? h) <> true).\n       apply not_true_iff_false. assumption.\n       apply eq4 in H0. lia.\n       apply (step_implies_reduces D (fenv env) H st (EMalloc w) H st RBounds).\n       apply (SMallocHighOOB D (fenv env) st H w (TArray (Num l) (Num h) w') h).\n       assumption. easy. easy.\n       apply (step_implies_reduces D (fenv env) H st (EMalloc w) H st RBounds).\n       apply (SMallocLowOOB D (fenv env) st H w (TArray (Num l) (Num h) w') l); try easy.\n   * apply cast_means_simple_type in eq1 as eq2.\n     apply cast_type_wf with (D := D) in eq1 as eq3; try easy.\n     inv eq2.\n     destruct (Z.eq_dec l 0).\n     destruct (0 <? h) eqn:eq2.\n     apply Z.ltb_lt in eq2.\n     assert ((forall (l' h' : Z) (t : type),\n       (TNTArray (Num l) (Num h) w') = TArray (Num l') (Num h') t -> l' = 0 /\\ h' > 0)).\n       intros. inv H0.\n      assert ((forall (l' h' : Z) (t : type),\n       (TNTArray (Num l) (Num h) w') = TNTArray (Num l') (Num h') t -> l' = 0 /\\ h' > 0)).\n      intros. split. injection H3.\n      intros. subst. reflexivity.\n      injection H3. intros. subst.  lia.\n      apply cast_means_simple_type in eq1 as eq4.\n       destruct ((wf_implies_allocate D (TNTArray (Num l) (Num h) w') H H0 H3 eq4 eq3)) as [ n [ H' HAlloc]].\n       apply (step_implies_reduces D (fenv env) H st (EMalloc w)\n                             H' st (RExpr (ELit n (TPtr Checked (TNTArray (Num l) (Num h) w'))))).\n       apply SMalloc; try easy.\n       unfold malloc_bound.  split. easy. lia.\n       assert (h <= 0).\n       specialize (Z.ltb_lt 0 h) as eq4.\n       apply not_iff_compat in eq4.\n       assert((0 <? h) <> true).\n       apply not_true_iff_false. assumption.\n       apply eq4 in H0. lia.\n       apply (step_implies_reduces D (fenv env) H st (EMalloc w) H st RBounds).\n       apply (SMallocHighOOB D (fenv env) st H w (TNTArray (Num l) (Num h) w') h); try easy.\n       apply (step_implies_reduces D (fenv env) H st (EMalloc w) H st RBounds).\n       apply (SMallocLowOOB D (fenv env) st H w (TNTArray (Num l) (Num h) w') l); try easy.\n  (* Case: TyUnchecked *)\n  - (* `EUnchecked e` isn't a value *)\n    right.\n    inv Hewf.\n    apply (IH) in H1; try easy.\n    (* Invoke the IH on `e` *)\n    destruct H1 as [ HVal | [ HRed | HUnchk ] ].\n    (* Case: `e` is a value *)\n    + (* We can step according to SUnchecked *)\n      left.\n      inv HVal...\n    (* Case: `e` reduces *)\n    + (* We can take a step by reducing `e` *)\n      left.\n      ctx (EUnchecked e) (in_hole e (CUnchecked CHole))...\n    (* Case: `e` is unchecked *)\n    + (* `EUnchecked e` is obviously unchecked *)\n      right.\n      ctx (EUnchecked e) (in_hole e (CUnchecked CHole))...\n  (* Case: TyCast1 *)\n  - (* `ECast t e` isn't a value when t is a nat type or is unchecked mode. *)\n    right.\n    inv Hewf. apply (IH) in H4; try easy.\n    (* Invoke the IH on `e` *)\n    destruct H4 as [ HVal | [ HRed | HUnchk ] ].\n    (* Case: `e` is a value *)\n    + (* We can step according to SCast *)\n      destruct m. left.\n      inv HVal.\n      apply gen_cast_type_bound_same with (s := st) in Wb as eq1.\n      destruct eq1. apply cast_means_simple_type in H5 as eq1.\n      apply (step_implies_reduces D (fenv env) H st (ECast t (ELit n t0)) H st (RExpr (ELit n x))).\n      apply SCast. easy.\n      apply stack_wf_sub in HSwf; try easy.\n      right. unfold unchecked. left.\n      reflexivity.\n    (* Case: `e` reduces *)\n    + (* `ECast t e` can take a step by reducing `e` *)\n      left.\n      ctx (ECast t e) (in_hole e (CCast t CHole))...\n    (* Case: `e` is unchecked *)\n    + (* `ECast t e` must be unchecked, since `e` is *)\n      right.\n      ctx (ECast t e) (in_hole e (CCast t CHole)).\n      destruct HUnchk...\n  - (* `ECast (TPtr Checked t) e` isn't a value when t is a nat type or is unchecked mode. *)\n    right.\n    inv Hewf. apply (IH) in H4; try easy.\n    (* Invoke the IH on `e` *)\n    destruct H4 as [ HVal | [ HRed | HUnchk ] ].\n    (* Case: `e` is a value *)\n    + (* We can step according to SCast *)\n      destruct m.\n      left.\n      inv HVal.\n      apply gen_cast_type_bound_same with (s := st) in Wb as eq1.\n      destruct eq1.\n      apply (step_implies_reduces D (fenv env) H st (ECast (TPtr Checked t) (ELit n t0)) H st (RExpr (ELit n (TPtr Checked x)))).\n      apply SCast. constructor. easy.\n      apply stack_wf_sub in HSwf; try easy.\n      right. unfold unchecked. left.\n      reflexivity.\n    (* Case: `e` reduces *)\n    + (* `ECast t e` can take a step by reducing `e` *)\n      left.\n      ctx (ECast (TPtr Checked t) e) (in_hole e (CCast (TPtr Checked t) CHole))...\n    (* Case: `e` is unchecked *)\n    + (* `ECast t e` must be unchecked, since `e` is *)\n      right.\n      ctx (ECast (TPtr Checked t) e) (in_hole e (CCast (TPtr Checked t) CHole)).\n      destruct HUnchk...\n  - (* `EDynCast t e` isn't a value when t is an array pointer. *)\n    right.\n    inv Hewf.\n    apply (IH) in H4; try easy.\n    (* Invoke the IH on `e` *)\n    destruct H4 as [ HVal | [ HRed | HUnchk ] ].\n    (* Case: `e` is a value *)\n    + (* We can step according to SCast *)\n      left.\n      inv HVal.\n      inv HTy.\n      apply gen_cast_type_bound_same with (s := st) in Wb as eq2.\n      destruct eq2.\n      inv H5. inv H9.\n      apply cast_bound_num in H8 as eq2. destruct eq2 as [l eq2]. subst.\n      apply cast_bound_num in H12 as eq2. destruct eq2 as [h eq2]. subst.\n      inv H4. inv H6.\n      destruct (Z_le_dec l0 l).\n      destruct (Z_lt_dec l h).\n      destruct (Z_le_dec h h0).\n      apply (step_implies_reduces D (fenv env) H st (EDynCast (TPtr Checked (TArray x y t))\n           (ELit n (TPtr Checked (TArray (Num l0) (Num h0) t')))) H st (RExpr (ELit n (TPtr Checked (TArray (Num l) (Num h) t'1))))).\n      eapply (SCastArray);eauto. constructor. constructor; try easy.\n      eapply step_implies_reduces;eauto.\n      eapply SCastArrayHighOOB1;eauto.\n      constructor. constructor. apply H8. apply H12. apply H13. lia.\n      eapply step_implies_reduces;eauto.\n      eapply SCastArrayLowOOB2 with (h := h);eauto.\n      constructor. constructor. apply H8. apply H12. apply H13. lia.\n      eapply step_implies_reduces;eauto.\n      eapply SCastArrayLowOOB1;eauto.\n      constructor. constructor. apply H8. apply H12. apply H13. lia.\n      apply stack_wf_sub in HSwf; try easy.\n    (* Case: `e` reduces *)\n    + (* `ECast t e` can take a step by reducing `e` *)\n      left.\n      ctx (EDynCast (TPtr Checked (TArray x y t)) e) (in_hole e (CDynCast (TPtr Checked (TArray x y t)) CHole))...\n    (* Case: `e` is unchecked *)\n    + (* `ECast t e` must be unchecked, since `e` is *)\n      right.\n      ctx (EDynCast (TPtr Checked (TArray x y t)) e) (in_hole e (CDynCast (TPtr Checked (TArray x y t)) CHole)).\n      destruct HUnchk...\n  - (* `EDynCast t e` isn't a value when t is an pointer. *)\n    right.\n    inv Hewf.\n    apply (IH) in H4; try easy.\n    (* Invoke the IH on `e` *)\n    destruct H4 as [ HVal | [ HRed | HUnchk ] ].\n    (* Case: `e` is a value *)\n    + (* We can step according to SCast *)\n      left.\n      inv HVal.\n      inv HTy.\n      apply gen_cast_type_bound_same with (s := st) in Wb as eq2.\n      destruct eq2.\n      inv H5. inv H9.\n      apply cast_bound_num in H8 as eq2. destruct eq2 as [l eq2]. subst.\n      apply cast_bound_num in H12 as eq2. destruct eq2 as [h eq2]. subst.\n      eapply step_implies_reduces;eauto.\n      apply stack_wf_sub in HSwf; try easy.\n    (* Case: `e` reduces *)\n    + (* `ECast t e` can take a step by reducing `e` *)\n      left.\n      ctx (EDynCast (TPtr Checked (TArray x y t)) e) (in_hole e (CDynCast (TPtr Checked (TArray x y t)) CHole))...\n    (* Case: `e` is unchecked *)\n    + (* `ECast t e` must be unchecked, since `e` is *)\n      right.\n      ctx (EDynCast (TPtr Checked (TArray x y t)) e) (in_hole e (CDynCast (TPtr Checked (TArray x y t)) CHole)).\n      destruct HUnchk...\n  - (* `ECast t e` isn't a value when t is an nt-array pointer. *)\n    right.\n    inv Hewf. \n    apply (IH) in H4; try easy.\n    (* Invoke the IH on `e` *)\n    destruct H4 as [ HVal | [ HRed | HUnchk ] ].\n    (* Case: `e` is a value *)\n    + (* We can step according to SCast *)\n      left.\n      inv HVal.\n      inv HTy.\n      apply gen_cast_type_bound_same with (s := st) in Wb as eq2.\n      destruct eq2.\n      inv H5. inv H9.\n      apply cast_bound_num in H8 as eq2. destruct eq2 as [l eq2]. subst.\n      apply cast_bound_num in H12 as eq2. destruct eq2 as [h eq2]. subst.\n      inv H4. inv H6.\n      destruct (Z_le_dec l0 l).\n      destruct (Z_lt_dec l h).\n      destruct (Z_le_dec h h0).\n      apply (step_implies_reduces D (fenv env) H st (EDynCast (TPtr Checked (TNTArray x y t))\n           (ELit n (TPtr Checked (TNTArray (Num l0) (Num h0) t')))) H st (RExpr (ELit n (TPtr Checked (TNTArray (Num l) (Num h) t'1))))).\n      eapply (SCastNTArray);eauto. constructor. constructor; try easy.\n      eapply step_implies_reduces;eauto.\n      eapply SCastNTArrayHighOOB1;eauto.\n      constructor. constructor. apply H8. apply H12. apply H13. lia.\n      eapply step_implies_reduces;eauto.\n      eapply SCastNTArrayLowOOB2 with (h := h);eauto.\n      constructor. constructor. apply H8. apply H12. apply H13. lia.\n      eapply step_implies_reduces;eauto.\n      eapply SCastNTArrayLowOOB1;eauto.\n      constructor. constructor. apply H8. apply H12. apply H13. lia.\n      apply stack_wf_sub in HSwf; try easy.\n    (* Case: `e` reduces *)\n    + (* `ECast t e` can take a step by reducing `e` *)\n      left.\n      ctx (EDynCast (TPtr Checked (TNTArray x y t)) e) (in_hole e (CDynCast (TPtr Checked (TNTArray x y t)) CHole))...\n    (* Case: `e` is unchecked *)\n    + (* `ECast t e` must be unchecked, since `e` is *)\n      right.\n      ctx (EDynCast (TPtr Checked (TNTArray x y t)) e) (in_hole e (CDynCast (TPtr Checked (TNTArray x y t)) CHole)).\n      destruct HUnchk...\n\n  (* Case: TyDeref *)\n  - (* `EDeref e` isn't a value *)\n    right.\n\n    (* If m' is unchecked, then the typing mode `m` is unchecked *)\n    destruct m'; [> | right; eauto 20 with Progress].\n    clear HMode.\n\n    (* TODO(ins): find a way to automate everything after case analysis... *)\n    inv Hewf.\n    apply (IH) in H1; try easy.\n    (* Invoke the IH on `e` *)\n    destruct H1 as [ HVal | [ HRed | HUnchk ] ].\n    (* Case: `e` is a value *)\n     (* We can take a step... but how? *)\n\n     + inv HVal.\n      inv HTy.\n      (* We proceed by case analysis on `w`, the type of the pointer *)\n      destruct HPtrType.\n      (* Case: `w` is a word pointer *)\n      * (* We now proceed by case analysis on 'n > 0' *)\n        destruct (Z_gt_dec n 0) as [ Hn0eq0 | Hn0neq0 ].\n        (* Case: n > 0 *)\n        { (*Since w is subtype of a ptr it is also a ptr*)\n          assert (H4 : exists t1, t = (TPtr Checked t1)).\n          { eapply ptr_subtype_equiv. eauto.\n          } destruct H4. rewrite H4 in *.\n          clear H4.\n          (* We now proceed by case analysis on '|- n0 : ptr_C w' *)\n          inv H3.\n          assert (HSim := H2).\n          inv H9.\n          (* Case: TyLitZero *)\n          {\n           (* Impossible, since n > 0 *)\n           exfalso. lia.\n            (*subst. inv H2. inv H3.*)\n          }\n          (* Case: TyLitRec *)\n          { (* Impossible, since scope is empty *)\n            solve_empty_scope. }\n          (* Case: TyLitC *)\n          { (* We can step according to SDeref *)\n            destruct H12 with (k := 0) as [ n' [ t1' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n            unfold allocate_meta in *.\n            specialize (subtype_trans D Q (TPtr Checked w) (TPtr Checked t') Checked x H6 HSub) as X1.\n            inv H4.\n            inv X1. inv H7. simpl. lia. \n            inv H11. inv H13.  inv H7. rewrite replicate_gt_eq. lia. lia.\n            inv H7. simpl. lia.\n            inv H11. inv H13.  inv H7. rewrite replicate_gt_eq. lia. lia.\n            inv H7. simpl. lia.\n            apply StructDef.find_1 in H9. rewrite H9 in H7. inv H7.\n            split. lia.\n            assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) fs))) > 0). \n            {\n              eapply struct_subtype_non_empty; eauto.\n              apply (SubTyStructArrayField_1 D Q T fs m).\n              apply StructDef.find_2. assumption.\n              assumption.\n              apply StructDef.find_2.  easy.\n            } lia.\n            inv X1. inv H7. simpl. lia.\n            inv H11. inv H13.  inv H7. rewrite replicate_gt_eq. lia. lia.\n            inv H7. simpl. lia.\n            inv H11. inv H13.  inv H7. rewrite replicate_gt_eq. lia. lia.\n            inv H7. simpl. lia.\n            rewrite Z.add_0_r in Hheap;\n            inv Ht'tk.\n            left.\n            assert (exists tv, @get_root D (TPtr Checked x) tv).\n            inv HSub.\n            exists t'. constructor. easy.\n            exists x. constructor. easy.\n            exists t'. apply get_root_array.\n            exists t'. apply get_root_ntarray.\n            inv H4. inv H4. inv H4.\n            exists TNat. apply get_root_struct with (f := fs); try easy.\n            inv H4.\n            destruct H7. destruct H3.\n            eapply step_implies_reduces.\n            eapply SDeref; eauto.\n            - apply simple_type_means_cast_same. easy.\n            - intros. inv H7. inv H4. inv HSub.\n              inv H15. inv H16. split. lia. easy.\n              inv HSub. inv H15. inv H16. lia.\n            - intros. inv H7. inv H4. inv HSub.\n              inv H15. inv H16. split. lia. easy.\n              inv HSub. inv H15. inv H16. lia.\n          }\n        }\n        (* Case: n <= 0 *)\n        { (* We can step according to SDerefNull *)\n          left. eapply step_implies_reduces.\n         \n          assert (exists w0, t = TPtr Checked w0).\n          {\n            inv H0. inv HSub.\n            exists w. destruct m0.\n            reflexivity. inv HSub.\n          }\n          destruct H4. subst.\n          eapply SDerefNull; eauto. \n        }\n\n      (* Case: `w` is an array pointer *)\n      * destruct H3.\n        destruct H3 as [Ht H3].\n        subst.\n\n\n        assert (HArr : (exists l0 h0, t = (TPtr Checked (TArray l0 h0 t')))\n                     \\/ (exists l0 h0, t = (TPtr Checked (TNTArray l0 h0 t')))\n                        \\/ (t = TPtr Checked t')\n                           \\/ (exists T, (t = TPtr Checked (TStruct T)))).\n        {\n          inv HSub.\n          left. exists l; exists h; reflexivity.\n          right. right. left. easy. inv H6.\n          inv H6.\n          left. exists l0; exists h0; reflexivity.\n          right. left. exists l0; exists h0; reflexivity.\n          right. right. right. exists T. easy.\n        }\n\n        destruct HArr.\n        destruct H4 as [l1 [h1 HArr]].\n        subst.\n        (* We now perform case analysis on 'n > 0' *)\n        destruct (Z_gt_dec n 0) as [ Hn0eq0 | Hn0neq0 ].\n        (* Case: n > 0 *)\n        { (* We now proceed by case analysis on '|- n0 : ptr_C (array n t)' *)\n          assert (simple_type ((TPtr Checked (TArray l1 h1 t')))) as Y1.\n          easy.\n          match goal with\n          | [ H : well_typed_lit _ _ _ _ _ _ |- _ ] => inv H\n          end.\n          (* Case: TyLitZero *)\n          { (* Impossible, since n0 <> 0 *)\n            exfalso. inv Hn0eq0.\n          } \n          (* Case: TyLitRec *)\n          { (* Impossible, since scope is empty *)\n            solve_empty_scope.\n          } \n          (* Case: TyLitC *)\n          { (* We proceed by case analysis on 'h > 0' -- the size of the array *)\n            destruct H3 as [Hyp2 Hyp3]; subst.\n            inv Y1. inv H4.\n            (* should this also be on ' h > 0' instead? DP*)\n            destruct (Z_gt_dec h0 0) as [ Hneq0 | Hnneq0 ].\n            (* Case: h > 0 *)\n            { left. (* We can step according to SDeref *)\n              (* LEO: This looks exactly like the previous one. Abstract ? *)\n              inv H6. inv H7.\n              specialize (simple_type_means_cast_same t' st H9) as eq1.\n              destruct (Z_gt_dec l0 0).\n\n              (* if l > 0 we have a bounds error*)\n              {\n                eapply step_implies_reduces. \n                eapply (SDerefLowOOB);eauto. easy.\n                unfold get_low_ptr. easy.\n              }\n              \n              (* if l <= 0 we can step according to SDeref. *)\n\n              assert (Hhl : h0 - l0 > 0). {\n                destruct h0. inv Hneq0. lia. inv Hneq0.\n              }\n              destruct (h0 - l0) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n              simpl in *.\n              rewrite replicate_length in *.\n              assert (HL: l0 + Z.of_nat (Pos.to_nat p) = h0) by (zify; lia).\n              rewrite HL in *; try lia.\n\n              destruct H12 with (k := 0) as [ n' [ t'' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n              { (split;  lia). }\n\n              rewrite Z.add_0_r in Hheap.\n              simpl in *.\n\n              assert (Hp': Z.of_nat (Pos.to_nat p) = Z.pos p) by lia.\n              rewrite Hp' in *; clear Hp'.\n              assert (Hp': Pos.to_nat p = Z.to_nat (Z.pos p)) by (simpl; reflexivity).\n              rewrite Hp' in *; clear Hp'. \n\n              assert (t' = t'').\n              {\n                eapply replicate_nth; eauto.\n              }\n              subst t''.\n              eapply step_implies_reduces.\n              eapply (SDeref); eauto.\n              apply simple_type_means_cast_same. constructor. constructor.  easy.\n              intros l' h' t'' HT.\n              inv HT.\n              split; zify; lia.\n              intros. inv H3.\n              apply get_root_array.\n\n              inv H15. inv H16.\n\n              destruct (Z_gt_dec l0 0).\n\n              (* if l > 0 we have a bounds error*)\n              {\n                eapply step_implies_reduces. \n                eapply (SDerefLowOOB);eauto. easy.\n                unfold get_low_ptr. easy.\n              }\n\n              assert (l0 = 0) by lia.\n              assert (h0 = 1) by lia.\n              subst.\n\n              (* if l <= 0 we can step according to SDeref. *)\n              inv H13. inv H7.\n              specialize (H12 0). simpl in *.\n              assert (0 <= 0 < 1) by lia.\n              apply H12 in H3. destruct H3 as [n' [t' [X1 [X2 X3]]]].\n              inv X1.\n              eapply step_implies_reduces.\n              eapply (SDeref); eauto.\n              apply simple_type_means_cast_same. constructor. constructor.  easy.\n              rewrite Z.add_0_r in X2. apply X2.\n              intros. inv H3. lia.\n              intros. inv H3.\n              apply get_root_array.\n\n              inv H7.\n              specialize (H12 0). simpl in *.\n              assert (0 <= 0 < 1) by lia.\n              apply H12 in H3. destruct H3 as [n' [t' [X1 [X2 X3]]]].\n              inv X1.\n              eapply step_implies_reduces.\n              eapply (SDeref); eauto.\n              apply simple_type_means_cast_same. constructor. constructor.  easy.\n              rewrite Z.add_0_r in X2. apply X2.\n              intros. inv H3. lia.\n              intros. inv H3.\n              apply get_root_array.\n              inv H11. inv H11.\n              inv H11. inv H15.\n\n              destruct (Z_gt_dec l0 0).\n\n              (* if l > 0 we have a bounds error*)\n              {\n                eapply step_implies_reduces. \n                eapply (SDerefLowOOB);eauto. easy.\n                unfold get_low_ptr. easy.\n              }\n\n              (* if l <= 0 we can step according to SDeref. *)\n              inv H7.\n              assert (l2 <= 0) by lia.\n              rewrite replicate_gt_eq in *.\n\n              assert (Hhl : h2 - l2 > 0). {\n                destruct h0. inv Hneq0. lia. inv Hneq0.\n              }\n\n              destruct H12 with (k := 0) as [ n' [ t'' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n              lia.\n              rewrite Z.add_0_r in Hheap.\n              simpl in *.\n              unfold Zreplicate in Ht'tk.\n\n              destruct (h2 - l2) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n              simpl in *.\n\n              assert (Hp': Pos.to_nat p = Z.to_nat (Z.pos p)) by (simpl; reflexivity).\n              rewrite Hp' in *; clear Hp'. \n\n              assert (t' = t'').\n              {\n                eapply replicate_nth; eauto.\n              }\n              subst t''.\n              eapply step_implies_reduces.\n              eapply (SDeref); eauto.\n              apply simple_type_means_cast_same. constructor. constructor.  easy.\n              intros l' h' t'' HT.\n              inv HT.\n              split; zify; lia.\n              intros. inv H7.\n              apply get_root_array.\n              lia.\n              inv H5.\n              \n              inv H11. inv H15. \n              destruct (Z_gt_dec l0 0).\n\n              (* if l > 0 we have a bounds error*)\n              {\n                eapply step_implies_reduces. \n                eapply (SDerefLowOOB);eauto. easy.\n                unfold get_low_ptr. easy.\n              }\n\n              (* if l <= 0 we can step according to SDeref. *)\n              inv H7.\n              assert (l2 <= 0) by lia.\n              rewrite replicate_gt_eq in *.\n\n              assert (Hhl : h2 - l2 > 0). {\n                destruct h0. inv Hneq0. lia. inv Hneq0.\n              }\n\n              destruct H12 with (k := 0) as [ n' [ t'' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n              lia.\n              rewrite Z.add_0_r in Hheap.\n              simpl in *.\n              unfold Zreplicate in Ht'tk.\n\n              destruct (h2 - l2 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n              simpl in *.\n\n              assert (Hp': Pos.to_nat p = Z.to_nat (Z.pos p)) by (simpl; reflexivity).\n              rewrite Hp' in *; clear Hp'. \n\n              assert (t' = t'').\n              {\n                eapply replicate_nth; eauto.\n              }\n              subst t''.\n              eapply step_implies_reduces.\n              eapply (SDeref); eauto.\n              apply simple_type_means_cast_same. constructor. constructor.  easy.\n              intros l' h' t'' HT.\n              inv HT.\n              split; zify; lia.\n              intros. inv H7.\n              apply get_root_array.\n              lia.\n              inv H5.\n              \n              inv H16. inv H17.\n              destruct (Z_gt_dec l0 0).\n\n              (* if l > 0 we have a bounds error*)\n              {\n                eapply step_implies_reduces. \n                eapply (SDerefLowOOB);eauto. easy.\n                unfold get_low_ptr. easy.\n              }\n\n              assert (l0 = 0) by lia.\n              assert (h0 = 1) by lia.\n              subst.\n\n              destruct H12 with (k := 0) as [ n' [ t1' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n              unfold allocate_meta in *. inv H7. \n              destruct (StructDef.find T D) eqn:HFind.\n               assert (Hmap : StructDef.MapsTo T f D). \n               {\n                 eapply find_implies_mapsto. assumption.\n                }\n               assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) f))) > 0). \n              {\n                 eapply struct_subtype_non_empty; eauto.\n                 apply (SubTyStructArrayField_1 D Q T fs m).\n                 assumption.\n                 assumption.\n              }\n              inv H4; zify; try lia.\n              inv H4.\n\n              rewrite Z.add_0_r in Hheap;\n              inv Ht'tk.\n              eapply step_implies_reduces.\n              eapply SDeref; eauto.\n              - apply simple_type_means_cast_same. easy.\n              - intros. inv H3. lia.\n              - intros. inv H3.\n              - apply get_root_array.\n\n            }\n            (* Case: h <= 0 *)\n            { (* We can step according to SDerefOOB *)\n              subst. left. eapply step_implies_reduces. \n              eapply (SDerefHighOOB);eauto. easy.\n              unfold get_high_ptr. reflexivity.\n            }\n          }\n        } \n        (* Case: n <= 0 *)\n        { (* We can step according to SDerefNull *)\n          subst... }\n\n        (* when subtype is nt-array ptr. *)\n        destruct H4.\n        destruct H4 as [l1 [h1 HArr]].\n        subst.\n        (* We now perform case analysis on 'n > 0' *)\n        destruct (Z_gt_dec n 0) as [ Hn0eq0 | Hn0neq0 ].\n        (* Case: n > 0 *)\n        { (* We now proceed by case analysis on '|- n0 : ptr_C (array n t)' *)\n          assert (simple_type ((TPtr Checked (TNTArray l1 h1 t')))) as Y1.\n          easy.\n          match goal with\n          | [ H : well_typed_lit _ _ _ _ _ _ |- _ ] => inv H\n          end.\n          (* Case: TyLitZero *)\n          { (* Impossible, since n0 <> 0 *)\n            exfalso. inv Hn0eq0.\n          } \n          (* Case: TyLitRec *)\n          { (* Impossible, since scope is empty *)\n            solve_empty_scope.\n          } \n          (* Case: TyLitC *)\n          { (* We proceed by case analysis on 'h > 0' -- the size of the array *)\n            destruct H3 as [Hyp2 Hyp3]; subst.\n            inv Y1. inv H4. \n            (* should this also be on ' h > 0' instead? DP*)\n            destruct (Z_gt_dec h0 0) as [ Hneq0 | Hnneq0 ].\n            (* Case: h > 0 *)\n            { left. (* We can step according to SDeref *)\n              (* LEO: This looks exactly like the previous one. Abstract ? *)\n              inv H6. inv H7.\n              specialize (simple_type_means_cast_same t' st H9) as eq1.\n              destruct (Z_gt_dec l0 0).\n\n              (* if l > 0 we have a bounds error*)\n              {\n                eapply step_implies_reduces. \n                eapply (SDerefLowOOB);eauto. easy.\n                unfold get_low_ptr. easy.\n              }\n              \n              (* if l <= 0 we can step according to SDeref. *)\n\n              assert (Hhl : h0 - l0 +1 > 0). {\n                destruct h0. inv Hneq0. lia. inv Hneq0.\n              }\n              destruct (h0 - l0 +1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n              simpl in *.\n              rewrite replicate_length in *.\n\n              destruct H12 with (k := 0) as [ n' [ t'' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n              { (split;  lia). }\n\n              rewrite Z.add_0_r in Hheap.\n              simpl in *.\n\n              assert (Hp': Z.of_nat (Pos.to_nat p) = Z.pos p) by lia.\n              rewrite Hp' in *; clear Hp'.\n              assert (Hp': Pos.to_nat p = Z.to_nat (Z.pos p)) by (simpl; reflexivity).\n              rewrite Hp' in *; clear Hp'. \n\n              assert (t' = t'').\n              {\n                eapply replicate_nth; eauto.\n              }\n              subst t''.\n              eapply step_implies_reduces.\n              eapply (SDeref); eauto.\n              apply simple_type_means_cast_same. constructor. constructor.  easy.\n              intros l' h' t'' HT. inv HT.\n              intros.\n              inv H3.\n              split; zify; lia.\n              apply get_root_ntarray.\n              inv H11. inv H11.\n\n              inv H11. inv H15.\n\n              destruct (Z_gt_dec l0 0).\n\n              (* if l > 0 we have a bounds error*)\n              {\n                eapply step_implies_reduces. \n                eapply (SDerefLowOOB);eauto. easy.\n                unfold get_low_ptr. easy.\n              }\n\n              (* if l <= 0 we can step according to SDeref. *)\n              inv H7.\n              assert (l2 <= 0) by lia.\n              rewrite replicate_gt_eq in *.\n\n              assert (Hhl : h2 - l2 + 1 > 0). {\n                destruct h0. inv Hneq0. lia. inv Hneq0.\n              }\n\n              destruct H12 with (k := 0) as [ n' [ t'' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n              lia.\n              rewrite Z.add_0_r in Hheap.\n              simpl in *.\n              unfold Zreplicate in Ht'tk.\n\n              destruct (h2 - l2 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n              simpl in *.\n\n              assert (Hp': Pos.to_nat p = Z.to_nat (Z.pos p)) by (simpl; reflexivity).\n              rewrite Hp' in *; clear Hp'. \n\n              assert (t' = t'').\n              {\n                eapply replicate_nth; eauto.\n              }\n              subst t''.\n              eapply step_implies_reduces.\n              eapply (SDeref); eauto.\n              apply simple_type_means_cast_same. constructor. constructor.  easy.\n              intros l' h' t'' HT. inv HT.\n              intros. inv H7.\n              split; zify; lia.\n              apply get_root_ntarray.\n              lia.\n              inv H5.\n            }\n            (* Case: h <= 0 *)\n            { (* We can step according to SDerefOOB *)\n              subst. left. eapply step_implies_reduces. \n              eapply (SDerefHighOOB); eauto. easy.\n              unfold get_high_ptr. reflexivity.\n            }\n\n          }\n        } \n        (* Case: n <= 0 *)\n        { (* We can step according to SDerefNull *)\n          subst... }\n\n        destruct H4.\n        destruct H3 as [Ht H3].\n        subst.\n\n        destruct (Z_gt_dec n 0) as [ Hn0eq0 | Hn0neq0 ].\n        (* Case: n > 0 *)\n        { (*Since w is subtype of a ptr it is also a ptr*)\n          (* We now proceed by case analysis on '|- n0 : ptr_C w' *)\n          assert (simple_type (TPtr Checked t')) as Hsim. easy.\n          inv H9.\n          (* Case: TyLitZero *)\n          {\n           (* Impossible, since n > 0 *)\n           exfalso. lia.\n            (*subst. inv H2. inv H3.*)\n          }\n          (* Case: TyLitRec *)\n          { (* Impossible, since scope is empty *)\n            solve_empty_scope. }\n          (* Case: TyLitC *)\n          { (* We can step according to SDeref *)\n            inv H6. \n\n            destruct H12 with (k := 0) as [ n' [ t1' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n            unfold allocate_meta in *. destruct t'.\n            inv H7. simpl. lia. inv H7. simpl. lia.\n            inv Ht. inv Ht. inv Ht.\n\n            rewrite Z.add_0_r in Hheap;\n            inv Ht'tk.\n            left.\n            eapply step_implies_reduces with (s' := st) (H' := H) (r := RExpr (ELit n' t')).\n            eapply SDeref; eauto.\n            apply simple_type_means_cast_same; try easy.\n            intros. inv H4. inv Ht.\n            intros. inv H4. inv Ht.\n            apply get_root_word. easy.\n\n            inv H13. inv H14.\n\n            destruct (Z_gt_dec h1 0).\n\n            (* if l > 0 we have a bounds error*)\n            {\n                left.\n                eapply step_implies_reduces. \n                eapply (SDerefLowOOB);eauto. easy.\n                unfold get_low_ptr. easy.\n            }\n\n            destruct (Z_ge_dec 0 l0).\n\n            (* if h <= 0 we have a bounds error*)\n            {\n                left.\n                eapply step_implies_reduces. \n                eapply (SDerefHighOOB);eauto. easy.\n                unfold get_high_ptr. easy.\n            }\n\n            assert (h1 = 0) by lia.\n            assert (l0 = 1) by lia. subst.\n              (* if l <= 0 we can step according to SDeref. *)\n              inv H11. inv H7.\n              left.\n              specialize (H12 0). simpl in *.\n              assert (0 <= 0 < 1) by lia.\n              apply H12 in H4. destruct H4 as [n' [t' [X1 [X2 X3]]]].\n              inv X1.\n              eapply step_implies_reduces with (s' := st) (H' := H) (r := RExpr (ELit n' TNat)).\n              eapply (SDeref); eauto.\n              apply simple_type_means_cast_same. easy. \n              rewrite Z.add_0_r in X2. apply X2.\n              intros. inv H4. lia.\n              intros. inv H4.\n              apply get_root_array.\n\n              inv H7. left.\n              specialize (H12 0). simpl in *.\n              assert (0 <= 0 < 1) by lia.\n              apply H12 in H4. destruct H4 as [n' [t' [X1 [X2 X3]]]].\n              inv X1.\n              eapply step_implies_reduces with (s' := st) (H' := H) (r := RExpr (ELit n' (TPtr m0 w0))).\n              eapply (SDeref); eauto.\n              apply simple_type_means_cast_same. easy.\n              rewrite Z.add_0_r in X2. apply X2.\n              intros. inv H4. lia.\n              intros. inv H4.\n              apply get_root_array.\n              inv Hsim. inv H10.\n              inv H7. \n              inv H13. inv H14.\n\n              inv H6. left.\n              assert (Hhl : (h1 - l1) > 0) by lia.\n\n              destruct (h1 - l1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n              simpl in *.\n              rewrite replicate_length in *.\n              assert (HL: l1 + Z.of_nat (Pos.to_nat p) = h1) by (zify; lia).\n              rewrite HL in *; try lia.\n\n              destruct H12 with (k := 0) as [ n' [ t'' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n              { (split;  lia). }\n\n              rewrite Z.add_0_r in Hheap.\n              simpl in *.\n\n              assert (Hp': Z.of_nat (Pos.to_nat p) = Z.pos p) by lia.\n              rewrite Hp' in *; clear Hp'.\n              assert (Hp': Pos.to_nat p = Z.to_nat (Z.pos p)) by (simpl; reflexivity).\n              rewrite Hp' in *; clear Hp'. \n\n              assert (t' = t'').\n              {\n                eapply replicate_nth; eauto.\n              }\n              subst t''.\n              apply (simple_type_means_cast_same) with (s := st) in H5 as eq1.\n              eapply step_implies_reduces with (s' := st) (H' := H) (r := RExpr (ELit n' t')).\n              eapply (SDeref D); eauto.\n              apply simple_type_means_cast_same. easy.\n              intros. inv H4. inv H11.\n              intros. inv H4. inv H11.\n              apply get_root_word. easy.\n\n              inv H5.\n              inv H13. inv H14.\n              inv H7. left.\n              assert (Hhl : (h1 - l1 + 1) > 0) by lia.\n\n              destruct (h1 - l1  + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n              simpl in *.\n              rewrite replicate_length in *.\n              assert (HL: l1 + Z.of_nat (Pos.to_nat p) = h1+1) by (zify; lia).\n              rewrite HL in *; try lia.\n\n              destruct H12 with (k := 0) as [ n' [ t'' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n              { (split;  lia). }\n\n              rewrite Z.add_0_r in Hheap.\n              simpl in *.\n\n              assert (Hp': Z.of_nat (Pos.to_nat p) = Z.pos p) by lia.\n              rewrite Hp' in *; clear Hp'.\n              assert (Hp': Pos.to_nat p = Z.to_nat (Z.pos p)) by (simpl; reflexivity).\n              rewrite Hp' in *; clear Hp'. \n\n              assert (t' = t'').\n              {\n                eapply replicate_nth; eauto.\n              }\n              subst t''.\n\n              eapply step_implies_reduces.\n              eapply (SDeref); eauto.\n              apply simple_type_means_cast_same. constructor. inv H2. easy.\n              intros. inv H4. inv H11.\n              intros. inv H4. inv H11.\n              apply get_root_word. easy.\n              inv H5. inv H5. inv Ht. inv Ht. inv Ht.\n\n              inv H7.\n              destruct H12 with (k := 0) as [ n' [ t1' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n              unfold allocate_meta in *. \n              destruct (StructDef.find T D) eqn:HFind.\n               assert (Hmap : StructDef.MapsTo T f D). \n               {\n                 eapply find_implies_mapsto. assumption.\n                }\n               assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) f))) > 0). \n              {\n                 eapply struct_subtype_non_empty; eauto.\n                 apply (SubTyStructArrayField_1 D Q T fs m).\n                 assumption.\n                 assumption.\n              }\n              inv H6; zify; try lia.\n              inv H6.\n\n              rewrite Z.add_0_r in Hheap;\n              inv Ht'tk. left.\n              eapply step_implies_reduces.\n              eapply SDeref; eauto.\n              apply simple_type_means_cast_same. easy.\n              intros. inv H4.\n              intros. inv H4.\n              apply get_root_word. easy.\n\n              inv H14. inv H15. inv Ht. inv H2. inv H10.\n\n          }\n        }\n\n        (* Case: n <= 0 *)\n        { (* We can step according to SDerefNull *)\n          left. eapply step_implies_reduces.\n         \n          eapply SDerefNull; eauto. \n        }\n\n       (* when subtype is a TStruct pointer. *)\n        destruct H4.\n        destruct H3 as [Ht H3].\n        subst.\n        inv HSub. inv Ht.        \n\n        destruct (Z_gt_dec n 0) as [ Hn0eq0 | Hn0neq0 ].\n        (* Case: n > 0 *)\n        { (*Since w is subtype of a ptr it is also a ptr*)\n          (* We now proceed by case analysis on '|- n0 : ptr_C w' *)\n          assert (simple_type (TPtr Checked (TStruct x))) as Hsim.\n          constructor. constructor. inv H9.\n          (* Case: TyLitZero *)\n          {\n           (* Impossible, since n > 0 *)\n           exfalso. lia.\n            (*subst. inv H2. inv H3.*)\n          }\n          (* Case: TyLitRec *)\n          { (* Impossible, since scope is empty *)\n            solve_empty_scope. }\n          (* Case: TyLitC *)\n          { (* We can step according to SDeref *)\n            inv H6. \n            destruct H16 with (k := 0) as [ n' [ t1' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n            unfold allocate_meta in *. inv H7. \n            destruct (StructDef.find x D) eqn:HFind.\n            assert (Hmap : StructDef.MapsTo x f D). \n            {\n             eapply find_implies_mapsto. assumption.\n            }\n            assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) f))) > 0). \n            {\n              eapply struct_subtype_non_empty; eauto.\n              apply (SubTyStructArrayField_1 D Q x fs m).\n              assumption.\n              assumption.\n            }\n            inv H6; zify; try lia.\n            inv H6.\n\n            unfold allocate_meta in *. inv H7.\n            destruct (StructDef.find x D) eqn:HFind.\n            assert (Hmap : StructDef.MapsTo x f D). \n            {\n             eapply find_implies_mapsto. assumption.\n            }\n            assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) f))) > 0). \n            {\n              eapply struct_subtype_non_empty; eauto.\n              apply (SubTyStructArrayField_1 D Q x fs m).\n              assumption.\n              assumption.\n            }\n\n            rewrite Z.add_0_r in Hheap;\n            inv Ht'tk. inv H6.\n            left.\n            eapply step_implies_reduces.\n            eapply SDeref; eauto.\n            apply simple_type_means_cast_same. easy.\n            intros. inv H6.\n            intros. inv H6.\n            apply get_root_struct with (f0 := f); try easy. \n            apply StructDef.find_1 in H10.\n            rewrite H10 in *. inv HFind. easy. inv H6. inv H15. inv H15.\n          }\n        }\n        (* Case: n <= 0 *)\n        { (* We can step according to SDerefNull *)\n          left. eapply step_implies_reduces.\n         \n          eapply SDerefNull; eauto. \n        }\n\n        (* when t'' is a TNTArray. *)\n        destruct H3 as [Ht H3]. subst.\n        assert (HArr : (exists l0 h0, t = (TPtr Checked (TNTArray l0 h0 t')))).\n        {\n          inv HSub.\n          exists l; exists h; easy.\n          inv H6. inv H6.\n          exists l0; exists h0; reflexivity.\n        }\n\n        destruct HArr as [l1 [h1 HArr]].\n        rewrite HArr in *. clear HArr.\n        (* We now perform case analysis on 'n > 0' *)\n        destruct (Z_gt_dec n 0) as [ Hn0eq0 | Hn0neq0 ].\n        (* Case: n > 0 *)\n        { (* We now proceed by case analysis on '|- n0 : ptr_C (array n t)' *)\n          assert (simple_type ((TPtr Checked (TNTArray l1 h1 t')))) as Y1.\n          easy.\n          match goal with\n          | [ H : well_typed_lit _ _ _ _ _ _ |- _ ] => inv H\n          end.\n          (* Case: TyLitZero *)\n          { (* Impossible, since n0 <> 0 *)\n            exfalso. inv Hn0eq0.\n          } \n          (* Case: TyLitRec *)\n          { (* Impossible, since scope is empty *)\n            solve_empty_scope.\n          } \n          (* Case: TyLitC *)\n          { (* We proceed by case analysis on 'h > 0' -- the size of the array *)\n            destruct H3 as [Hyp2 Hyp3]; subst.\n            inv Y1. inv H4.\n            (* should this also be on ' h > 0' instead? DP*)\n            destruct (Z_gt_dec h0 0) as [ Hneq0 | Hnneq0 ].\n            (* Case: h > 0 *)\n            { left. (* We can step according to SDeref *)\n              (* LEO: This looks exactly like the previous one. Abstract ? *)\n              destruct (Z_gt_dec l0 0).\n\n              (* if l > 0 we have a bounds error*)\n              {\n                eapply step_implies_reduces. \n                eapply (SDerefLowOOB);eauto. easy.\n                unfold get_low_ptr.\n                reflexivity.\n              }\n              \n              (* if l <= 0 we can step according to SDeref. *)\n              inv H6. inv H7.\n              assert (Hhl : (h0 - l0 + 1) > 0). {\n                destruct h0. inv Hneq0. lia. inv Hneq0.\n              }\n\n              destruct (h0 - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n              simpl in *.\n              rewrite replicate_length in *.\n              assert (HL: l0 + Z.of_nat (Pos.to_nat p) = h0+1) by (zify; lia).\n              rewrite HL in *; try lia.\n\n              destruct H12 with (k := 0) as [ n' [ t'' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n              { (split;  lia). }\n\n              rewrite Z.add_0_r in Hheap.\n              simpl in *.\n\n              assert (Hp': Z.of_nat (Pos.to_nat p) = Z.pos p) by lia.\n              rewrite Hp' in *; clear Hp'.\n              assert (Hp': Pos.to_nat p = Z.to_nat (Z.pos p)) by (simpl; reflexivity).\n              rewrite Hp' in *; clear Hp'. \n\n              assert (t' = t'').\n              {\n                eapply replicate_nth; eauto.\n              }\n              subst t''.\n              apply (simple_type_means_cast_same) with (s := st) in H5 as eq1.\n              eapply step_implies_reduces.\n              eapply (SDeref); eauto.\n              apply simple_type_means_cast_same. constructor. constructor. easy. \n              intros. inv H3.\n              intros l' h' t'' HT.\n              injection HT. intros. subst.\n              split; zify; lia.\n              apply get_root_ntarray.\n              inv H11. inv H11.\n\n              inv H11. inv H15. inv H7.\n              assert (Hhl : (h2 - l2 + 1) > 0). {\n                destruct h0. inv Hneq0. lia. inv Hneq0.\n              }\n\n              destruct (h2 - l2 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n              simpl in *.\n              rewrite replicate_length in *.\n\n              destruct H12 with (k := 0) as [ n' [ t'' [ Ht'tk [ Hheap Hwtn' ] ] ] ].\n              { (split;  lia). }\n\n              rewrite Z.add_0_r in Hheap.\n              simpl in *.\n\n              assert (Hp': Z.of_nat (Pos.to_nat p) = Z.pos p) by lia.\n              rewrite Hp' in *; clear Hp'.\n              assert (Hp': Pos.to_nat p = Z.to_nat (Z.pos p)) by (simpl; reflexivity).\n              rewrite Hp' in *; clear Hp'. \n\n              assert (t' = t'').\n              {\n                eapply replicate_nth; eauto.\n              }\n              subst t''.\n              apply (simple_type_means_cast_same) with (s := st) in H5 as eq1.\n              eapply step_implies_reduces.\n              eapply (SDeref ); eauto.\n              apply simple_type_means_cast_same. constructor. constructor. easy. \n              intros. inv H3.\n              intros l' h' t'' HT.\n              injection HT. intros. subst.\n              split; zify; lia.\n              apply get_root_ntarray.\n              inv H5.\n            }\n            (* Case: h <= 0 *)\n            { (* We can step according to SDerefOOB *)\n              subst. left. eapply step_implies_reduces. \n              eapply (SDerefHighOOB ); eauto. easy.\n              unfold get_high_ptr. reflexivity.\n            } \n          }\n        } \n        (* Case: n <= 0 *)\n        { (* We can step according to SDerefNull *)\n          subst... }\n\n\n\n     + left. ctx (EDeref e) (in_hole e (CDeref CHole))...\n     + right.\n       ctx (EDeref e) (in_hole e (CDeref CHole)).\n       destruct HUnchk...\n\n  - (* Index for array type. *)\n    right.\n    destruct m'; [> | right; eauto 20 with Progress].\n    clear HMode.\n    (* Leo: This is becoming hacky *)\n    inv Hewf. inv H1.\n    (*\n    assert (exists l0 h0, t = (TPtr Checked (TArray l0 h0 t'))).\n    {\n      inv HSubType. exists l; exists h; eauto.\n      exists l0; exists h0; eauto.\n    }\n    destruct H0 as [l0 [h0 H0]].\n    rewrite H0 in *.\n    clear HSubType H0 l h.\n    remember l0 as l. remember h0 as h.\n    clear Heql Heqh l0 h0 t.\n    remember t' as t. clear Heqt t'.\n    *)\n    apply IH1 in H3;try easy.\n    apply IH2 in H4;try easy.\n    destruct H3 as [ HVal1 | [ HRed1 | HUnchk1 ] ]; eauto.\n    + inv HVal1 as [ n1 t1 ].\n      destruct H4 as [ HVal2 | [ HRed2 | HUnchk2 ] ]; eauto.\n      * left.\n        inv HVal2.\n        ctx (EDeref (EPlus (ELit n1 t1) (ELit n t0))) (in_hole (EPlus (ELit n1 t1) (ELit n t0)) (CDeref CHole)).\n        inv HTy1.\n        inv H2. inv H7.\n        exists Checked.\n        exists st.\n        exists H.\n        { destruct (Z_gt_dec n1 0).\n          - (* n1 > 0 *)\n            exists (RExpr (EDeref (ELit (n1 + n) (TPtr Checked (TArray (Num (l0 - n)) (Num (h0 - n)) t))))).\n            ctx (EDeref (ELit (n1 + n) (TPtr Checked (TArray (Num (l0 - n)) (Num (h0 - n)) t))))\n                (in_hole (ELit (n1 + n) (TPtr Checked (TArray (Num (l0 - n)) (Num (h0 - n)) t))) (CDeref CHole)).\n            rewrite HCtx.\n            rewrite HCtx0.\n            inv HTy2.\n            eapply RSExp; eauto.\n            assert ((TPtr Checked (TArray (Num (l0 - n)) (Num (h0 - n)) t)) \n             = sub_type_bound (TPtr Checked (TArray (Num l0) (Num h0) t)) n).\n            unfold sub_type_bound,sub_bound. reflexivity.\n            rewrite H2.\n            apply SPlusChecked. assumption.\n            unfold is_array_ptr. easy.\n          - (* n1 <= 0 *)\n            exists RNull.\n            subst. \n            rewrite HCtx. \n            inv HTy2.\n            eapply RSHaltNull; eauto.\n            apply SPlusNull. lia.\n            unfold is_array_ptr. easy.\n        }\n      * left.\n        ctx (EDeref (EPlus (ELit n1 t1) e2)) (in_hole e2 (CDeref (CPlusR n1 t1 CHole)))...\n      * right.\n        ctx (EDeref (EPlus (ELit n1 t1) e2)) (in_hole e2 (CDeref (CPlusR n1 t1 CHole))).\n        destruct HUnchk2...\n    + left.\n      ctx (EDeref (EPlus e1 e2)) (in_hole e1 (CDeref (CPlusL CHole e2)))...\n    + right.\n      ctx (EDeref (EPlus e1 e2)) (in_hole e1 (CDeref (CPlusL CHole e2))).\n      destruct HUnchk1...\n\n  - (* Index for ntarray type. *)\n    right.\n    destruct m'; [> | right; eauto 20 with Progress].\n    clear HMode.\n    (* Leo: This is becoming hacky *)\n    inv Hewf.\n    inv H1.\n    (*\n    assert (exists l0 h0, t = (TPtr Checked (TArray l0 h0 t'))).\n    {\n      inv HSubType. exists l; exists h; eauto.\n      exists l0; exists h0; eauto.\n    }\n    destruct H0 as [l0 [h0 H0]].\n    rewrite H0 in *.\n    clear HSubType H0 l h.\n    remember l0 as l. remember h0 as h.\n    clear Heql Heqh l0 h0 t.\n    remember t' as t. clear Heqt t'.\n    *)\n    apply (IH1) in H3; try easy.\n    apply (IH2) in H4; try easy.\n    destruct H3 as [ HVal1 | [ HRed1 | HUnchk1 ] ]; eauto.\n    + inv HVal1 as [ n1 t1 ].\n      destruct H4 as [ HVal2 | [ HRed2 | HUnchk2 ] ]; eauto.\n      * left.\n        inv HVal2.\n        ctx (EDeref (EPlus (ELit n1 t1) (ELit n t0))) (in_hole (EPlus (ELit n1 t1) (ELit n t0)) (CDeref CHole)).\n        inv HTy1.\n        inv H2. inv H7.\n        exists Checked.\n        exists st.\n        exists H.\n        { destruct (Z_gt_dec n1 0).\n          - (* n1 > 0 *)\n            exists (RExpr (EDeref (ELit (n1 + n) (TPtr Checked (TNTArray (Num (l0 - n)) (Num (h0 - n)) t))))).\n            ctx (EDeref (ELit (n1 + n) (TPtr Checked (TNTArray (Num (l0 - n)) (Num (h0 - n)) t))))\n                (in_hole (ELit (n1 + n) (TPtr Checked (TNTArray (Num (l0 - n)) (Num (h0 - n)) t))) (CDeref CHole)).\n            rewrite HCtx.\n            rewrite HCtx0.\n            inv HTy2.\n            eapply RSExp; eauto.\n            assert ((TPtr Checked (TNTArray (Num (l0 - n)) (Num (h0 - n)) t)) \n             = sub_type_bound (TPtr Checked (TNTArray (Num l0) (Num h0) t)) n).\n            unfold sub_type_bound,sub_bound. reflexivity.\n            rewrite H2.\n            apply SPlusChecked. assumption.\n            unfold is_array_ptr. easy.\n          - (* n1 <= 0 *)\n            exists RNull.\n            subst. \n            rewrite HCtx. \n            inv HTy2.\n            eapply RSHaltNull; eauto.\n            apply SPlusNull. lia.\n            unfold is_array_ptr. easy.\n        }\n      * left.\n        ctx (EDeref (EPlus (ELit n1 t1) e2)) (in_hole e2 (CDeref (CPlusR n1 t1 CHole)))...\n      * right.\n        ctx (EDeref (EPlus (ELit n1 t1) e2)) (in_hole e2 (CDeref (CPlusR n1 t1 CHole))).\n        destruct HUnchk2...\n    + left.\n      ctx (EDeref (EPlus e1 e2)) (in_hole e1 (CDeref (CPlusL CHole e2)))...\n    + right.\n      ctx (EDeref (EPlus e1 e2)) (in_hole e1 (CDeref (CPlusL CHole e2))).\n      destruct HUnchk1...\n\n  - (* Assign1 rule. This isn't a value, so it must reduce *)\n    right.\n\n    (* If m' is unchecked, then we are typing mode is unchecked *)\n    destruct m'; [> | right; eauto 20 with Progress].\n    clear HMode.\n\n    (* Invoke IH on e1 *)\n    inv Hewf.\n    apply (IH1) in H2; try easy.\n    destruct H2 as [ HVal1 | [ HRed1 | [| HUnchk1 ] ] ]; idtac...\n    + (* Case: e1 is a value *)\n      inv HVal1 as [ n1' t1' WTt1' Ht1' ].\n      (* Invoke IH on e2 *)\n      apply (IH2) in H3; try easy.\n      inv H3 as [ HVal2 | [ HRed2 | [| HUnchk2 ] ] ]; idtac...\n      * (* Case: e2 is a value, so we can take a step *)\n        inv HVal2 as [n2' t2' Wtt2' Ht2' ].\n        {\n            inv HTy1; eauto.\n            match goal with\n            | [ H : well_typed_lit _ _ _ _ _ _ |- _ ] => inv H\n            end... \n            + left.\n              eapply step_implies_reduces.\n              eapply SAssignNull; eauto. lia.\n              apply simple_type_means_eval_same. assumption.\n            + solve_empty_scope.\n            + left.\n              inv HTy2. inv H4.\n              unfold allocate_meta in H5.\n              destruct t; inv H5; simpl in *. \n              ++   destruct (H10 0) as [x [xT [HNth [HMap HWT]]]]; simpl in*;\n                try (zify; lia);\n                try rewrite Z.add_0_r in *;\n                eauto; \n              try (eapply step_implies_reduces;\n                   eapply SAssign; eauto);\n              try (eexists; eauto);\n              intros; try congruence...\n              apply simple_type_means_cast_same. easy. inv H2. inv H2. inv H2. inv H2.\n              apply get_root_word. constructor.\n              ++ destruct (H10 0) as [x [xT [HNth [HMap HWT]]]]; simpl in*;\n                try (zify; lia);\n                try rewrite Z.add_0_r in *;\n                eauto; \n              try (eapply step_implies_reduces;\n                   eapply SAssign; eauto);\n              try (eexists; eauto);\n              intros; try congruence...\n              apply simple_type_means_cast_same. easy. inv H2. inv H2. inv H2. inv H2. \n              apply get_root_word. constructor.\n              ++ inv WT.\n              ++ inv WT.\n              ++ inv WT.\n              ++ inv WT.\n              ++ inv H11. inv H12. inv H5.\n                 destruct (H10 0) as [x [xT [HNth [HMap HWT]]]]; simpl in*;\n                try (zify; lia);\n                try rewrite Z.add_0_r in *;\n                eauto; \n              try (eapply step_implies_reduces;\n                   eapply SAssign; eauto);\n              try (eexists; eauto);\n              intros; try congruence...\n              rewrite replicate_gt_eq. lia. lia.\n              inv H3.\n              apply simple_type_means_cast_same. constructor. easy.\n              1-4:inv H2; inv WT.\n              apply get_root_word. easy. inv H3. \n              ++ inv H11. inv H12. inv H5.\n                 destruct (H10 0) as [x [xT [HNth [HMap HWT]]]]; simpl in*;\n                try (zify; lia);\n                try rewrite Z.add_0_r in *;\n                eauto; \n              try (eapply step_implies_reduces;\n                   eapply SAssign; eauto);\n              try (eexists; eauto);\n              intros; try congruence...\n              rewrite replicate_gt_eq. lia. lia.\n              inv H3.\n              apply simple_type_means_cast_same. constructor. easy.\n              1-4:inv H2; inv WT.\n              apply get_root_word. easy. inv H3. \n              ++ inv WT.\n              ++ inv WT.\n              ++ inv WT.\n              ++ inv H5. apply StructDef.find_1 in H9 as eq1.  rewrite eq1 in *.\n                 inv H4.\n              assert (forall t, subtype_stack D Q st t TNat -> t = TNat).\n              {\n                intros. inv H2. inv H4. easy. inv H5. inv H7. easy. inv H7. inv H5. easy.\n              }\n              apply H2 in HSub. clear H2. subst.\n               assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) fs))) > 0). \n              {\n                 eapply struct_subtype_non_empty; eauto.\n                 apply (SubTyStructArrayField_1 D Q T fs m).\n                 assumption.\n                 assumption.\n              }\n                 destruct (H10 0) as [x [xT [HNth [HMap HWT]]]]; simpl in*;\n                try (zify; lia);\n                try rewrite Z.add_0_r in *;\n                eauto; \n              try (eapply step_implies_reduces;\n                   eapply SAssign; eauto);\n              try (eexists; eauto);\n              intros; try congruence...\n              apply simple_type_means_cast_same. constructor. constructor.\n              1-4:inv H4. \n              apply get_root_word. easy.\n              ++ inv WT.\n         }\n      * unfold reduces in HRed2. destruct HRed2 as [ H' [ ? [ ? [ r HRed2 ] ] ] ].\n        inv HRed2; ctx (EAssign (ELit n1' t1') (in_hole e E)) (in_hole e (CAssignR n1' t1' E))...\n      * destruct HUnchk2 as [ e' [ E [ ] ] ]; subst.\n        ctx (EAssign (ELit n1' t1') (in_hole e' E)) (in_hole e' (CAssignR n1' t1' E))...\n    + (* Case: e1 reduces *)\n      destruct HRed1 as [ H' [ ? [? [ r HRed1 ] ] ] ].\n      inv HRed1; ctx (EAssign (in_hole e E) e2) (in_hole e (CAssignL E e2))...\n    + destruct HUnchk1 as [ e' [ E [ ] ] ]; subst.\n      ctx (EAssign (in_hole e' E) e2) (in_hole e' (CAssignL E e2))...\n  - (* Assign2 rule for array. *)\n    right.\n\n    (* If m' is unchecked, then we are typing mode is unchecked *)\n    destruct m'; [> | right; eauto 20 with Progress].\n    clear HMode.\n\n    (* Invoke IH on e1 *)\n    inv Hewf.\n    apply (IH1) in H2; try easy.\n    destruct H2 as [ HVal1 | [ HRed1 | [| HUnchk1 ] ] ]; idtac...\n    + (* Case: e1 is a value *)\n      inv HVal1 as [ n1' t1' WTt1' Ht1' ].\n      (* Invoke IH on e2 *)\n      apply (IH2) in H3; try easy.\n      inv H3 as [ HVal2 | [ HRed2 | [| HUnchk2 ] ] ]; idtac...\n      * (* Case: e2 is a value, so we can take a step *)\n        inv HVal2 as [n2' t2' Wtt2' Ht2' ].\n        {\n            inv HTy1; eauto.\n            assert (Hsim := H0). inv H0. inv H3.\n            match goal with\n            | [ H : well_typed_lit _ _ _ _ _ _ |- _ ] => inv H\n            end...\n            + left.\n\n              destruct (Z_gt_dec h0 0).\n              * (* h > 0 - Assign  *)\n                destruct (Z_gt_dec l0 0).\n                { (* l > 0 *)\n                eapply step_implies_reduces.\n                eapply SAssignLowOOB; eauto... inv HTy2.\n                unfold eval_type_bound,eval_bound. reflexivity.\n                unfold get_low_ptr. easy.\n                }\n                { (* l <= 0 *)\n                  eapply step_implies_reduces.\n                  eapply SAssignNull; eauto. lia.\n                  unfold eval_type_bound,eval_bound. eauto. \n                }\n              * (* h <= 0 *)\n                eapply step_implies_reduces.\n                eapply SAssignHighOOB; eauto... \n                unfold eval_type_bound, eval_bound. reflexivity.\n                unfold get_high_ptr. easy.\n            + solve_empty_scope.\n            + left.\n\n              destruct (Z_gt_dec n1' 0).\n                ++ destruct (Z_gt_dec h0 0).\n                    * (* h > 0 - Assign  *)\n                      destruct (Z_gt_dec l0 0).\n                      { (* l > 0 *)\n                      eapply step_implies_reduces.\n                      eapply SAssignLowOOB; eauto... \n                      unfold eval_type_bound, eval_bound. reflexivity.\n                      unfold get_low_ptr. easy. }\n                      { (* l <= 0 *)\n                        inv H4. inv H5.\n                        destruct (H10 0).\n                        rewrite replicate_gt_eq. lia. lia.\n                        destruct H0 as [ta [X1 [X2 X3]]].\n                        eapply step_implies_reduces.\n                        eapply (SAssign); eauto.\n                        rewrite Z.add_0_r in X2. apply X2.\n                        apply (simple_type_means_cast_same (TArray (Num l0) (Num h0) t) st) in H3.\n                        constructor. apply H3.\n                        intros. inv H0. split. lia. lia.\n                        intros. inv H0.\n                        apply get_root_array.\n                        inv H13. inv H14.\n                        inv WT. inv H5.\n                        destruct (H10 0). simpl in *. lia.\n                        destruct H0 as [ta [X1 [X2 X3]]].\n                        eapply step_implies_reduces.\n                        eapply (SAssign); eauto.\n                        rewrite Z.add_0_r in X2. apply X2.\n                        apply (simple_type_means_cast_same (TPtr Checked (TArray (Num l0) (Num h0) TNat)) st) in Hsim.\n                        apply Hsim.\n                        intros. inv H0. split. lia. lia.\n                        intros. inv H0.\n                        apply get_root_array.\n                        inv H5.\n                        destruct (H10 0). simpl in *. lia.\n                        destruct H0 as [ta [X1 [X2 X3]]].\n                        eapply step_implies_reduces.\n                        eapply (SAssign); eauto.\n                        rewrite Z.add_0_r in X2. apply X2.\n                        apply (simple_type_means_cast_same\n                                   (TPtr Checked (TArray (Num l0) (Num h0) (TPtr m0 w))) st) in Hsim.\n                        apply Hsim.\n                        intros. inv H0. split. lia. lia.\n                        intros. inv H0.\n                        apply get_root_array.\n                        inv H9. inv H9. inv H9. inv H13.\n                        inv H5.\n                        destruct (H10 0).\n                        rewrite replicate_gt_eq. lia. lia.\n                        destruct H0 as [ta [X1 [X2 X3]]].\n                        eapply step_implies_reduces.\n                        eapply (SAssign); eauto.\n                        rewrite Z.add_0_r in X2. apply X2.\n                        apply (simple_type_means_cast_same (TPtr Checked (TArray (Num l0) (Num h0) t)) st) in Hsim.\n                        apply Hsim.\n                        intros. inv H0. split. lia. lia.\n                        intros. inv H0.\n                        apply get_root_array.\n                        inv H3. inv H9. inv H13. inv H5.\n                        destruct (H10 0).\n                        rewrite replicate_gt_eq. lia. lia.\n                        destruct H0 as [ta [X1 [X2 X3]]].\n                        eapply step_implies_reduces.\n                        eapply (SAssign); eauto.\n                        rewrite Z.add_0_r in X2. apply X2.\n                        apply (simple_type_means_cast_same (TPtr Checked (TArray (Num l0) (Num h0) t)) st) in Hsim.\n                        apply Hsim.\n                        intros. inv H0. split. lia. lia.\n                        intros. inv H0.\n                        apply get_root_array.\n                        inv H3. inv H14. inv H15.\n                        inv H5.\n                        apply StructDef.find_1 in H12. rewrite H12 in *.\n                        inv H4.\n                        destruct (H10 0).\n                        assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) fs))) > 0). \n                       {\n                             eapply struct_subtype_non_empty; eauto.\n                              apply (SubTyStructArrayField_1 D Q T fs m).\n                             apply StructDef.find_2. easy. easy.\n                             apply StructDef.find_2. easy. \n                       } lia.\n                        destruct H0 as [ta [X1 [X2 X3]]].\n                        eapply step_implies_reduces.\n                        eapply (SAssign); eauto.\n                        rewrite Z.add_0_r in X2. apply X2.\n                        apply (simple_type_means_cast_same\n                                   (TPtr Checked (TArray (Num l0) (Num h0) TNat)) st) in Hsim.\n                        apply Hsim.\n                        intros. inv H0. split. lia. lia.\n                        intros. inv H0.\n                        apply get_root_array.\n                      }\n                    * (* h <= 0 *)\n                      eapply step_implies_reduces.\n                      eapply SAssignHighOOB; eauto...\n                      unfold eval_type_bound,eval_bound. reflexivity. \n                      unfold get_high_ptr. easy.\n              ++ destruct (Z_gt_dec h0 0).\n                 * (* h > 0 - Assign  *)\n                   destruct (Z_gt_dec l0 0).\n                   { (* l > 0 *)\n                   eapply step_implies_reduces.\n                   eapply SAssignLowOOB; eauto...\n                   unfold eval_type_bound,eval_bound. reflexivity. \n                   unfold get_low_ptr. easy. }\n                   { (* l <= 0 *)\n                     eapply step_implies_reduces.   \n                     eapply SAssignNull; eauto.\n                     unfold eval_type_bound,eval_bound. eauto.\n                   }\n                 * (* h <= 0 *)\n                   eapply step_implies_reduces.\n                   eapply SAssignHighOOB; eauto... inv HTy2.\n                   unfold eval_type_bound,eval_bound. reflexivity.\n                   unfold get_high_ptr. easy.\n         }\n      * unfold reduces in HRed2. destruct HRed2 as [ H' [ ? [ ? [ r HRed2 ] ] ] ].\n        inv HRed2; ctx (EAssign (ELit n1' t1') (in_hole e E)) (in_hole e (CAssignR n1' t1' E))...\n      * destruct HUnchk2 as [ e' [ E [ ] ] ]; subst.\n        ctx (EAssign (ELit n1' t1') (in_hole e' E)) (in_hole e' (CAssignR n1' t1' E))...\n    + (* Case: e1 reduces *)\n      destruct HRed1 as [ H' [ ? [? [ r HRed1 ] ] ] ].\n      inv HRed1; ctx (EAssign (in_hole e E) e2) (in_hole e (CAssignL E e2))...\n    + destruct HUnchk1 as [ e' [ E [ ] ] ]; subst.\n      ctx (EAssign (in_hole e' E) e2) (in_hole e' (CAssignL E e2))...\n\n  - (* Assign3 rule for nt-array. *)\n    right.\n\n    (* If m' is unchecked, then we are typing mode is unchecked *)\n    destruct m'; [> | right; eauto 20 with Progress].\n    clear HMode.\n\n    (* Invoke IH on e1 *)\n    inv Hewf.\n    apply (IH1) in H2; try easy.\n    destruct H2 as [ HVal1 | [ HRed1 | [| HUnchk1 ] ] ]; idtac...\n    + (* Case: e1 is a value *)\n      inv HVal1 as [ n1' t1' WTt1' Ht1' ].\n      (* Invoke IH on e2 *)\n      apply (IH2) in H3; try easy.\n      inv H3 as [ HVal2 | [ HRed2 | [| HUnchk2 ] ] ]; idtac...\n      * (* Case: e2 is a value, so we can take a step *)\n        inv HVal2 as [n2' t2' Wtt2' Ht2' ].\n        {\n            inv HTy1; eauto.\n            assert (Hsim := H0). inv H0. inv H3.\n            match goal with\n            | [ H : well_typed_lit _ _ _ _ _ _ |- _ ] => inv H\n            end...\n            + left.\n\n              destruct (Z_gt_dec h0 0).\n              * (* h > 0 - Assign  *)\n                destruct (Z_gt_dec l0 0).\n                { (* l > 0 *)\n                eapply step_implies_reduces.\n                eapply SAssignLowOOB; eauto...\n                unfold eval_type_bound,eval_bound. reflexivity. \n                unfold get_low_ptr. easy. }\n                { (* l <= 0 *)\n                  eapply step_implies_reduces.\n                  eapply SAssignNull; eauto. lia.\n                  unfold eval_type_bound,eval_bound. eauto. \n                }\n              * (* h <= 0 *)\n                eapply step_implies_reduces.\n                eapply SAssignHighOOB; eauto...                \n                unfold eval_type_bound,eval_bound. reflexivity. \n                unfold get_high_ptr. easy. \n            + solve_empty_scope.\n            + left.\n\n              destruct (Z_gt_dec n1' 0).\n                ++ destruct (Z_gt_dec h0 0).\n                    * (* h > 0 - Assign  *)\n                      destruct (Z_gt_dec l0 0).\n                      { (* l > 0 *)\n                      eapply step_implies_reduces.\n                      eapply SAssignLowOOB; eauto...                \n                      unfold eval_type_bound,eval_bound. reflexivity. \n                      unfold get_low_ptr. easy. }\n                      { (* l <= 0 *)\n                        inv H4. inv H5.\n                        destruct (H10 0).\n                        rewrite replicate_gt_eq. lia. lia.\n                        destruct H0 as [ta [X1 [X2 X3]]].\n                        eapply step_implies_reduces.\n                        eapply (SAssign); eauto.\n                        rewrite Z.add_0_r in X2. apply X2.\n                        apply (simple_type_means_cast_same (TNTArray (Num l0) (Num h0) t) st) in H3.\n                        constructor. apply H3.\n                        intros. inv H0.\n                        intros. inv H0. split. lia. lia.\n                        apply get_root_ntarray.\n                        inv H9. inv H9. inv H9. inv H13.\n                        inv H5.\n                        destruct (H10 0).\n                        rewrite replicate_gt_eq. lia. lia.\n                        destruct H0 as [ta [X1 [X2 X3]]].\n                        eapply step_implies_reduces.\n                        eapply (SAssign); eauto.\n                        rewrite Z.add_0_r in X2. apply X2.\n                        apply (simple_type_means_cast_same (TPtr Checked (TNTArray (Num l0) (Num h0) t)) st) in Hsim.\n                        apply Hsim.\n                        intros. inv H0.\n                        intros. inv H0. split. lia. lia.\n                        apply get_root_ntarray.\n                        inv H3.\n                      }\n                    * (* h <= 0 *)\n                      eapply step_implies_reduces.\n                      eapply SAssignHighOOB; eauto...\n                      unfold eval_type_bound,eval_bound. reflexivity.\n                      unfold get_high_ptr. easy.\n              ++ destruct (Z_gt_dec h0 0).\n                 * (* h > 0 - Assign  *)\n                   destruct (Z_gt_dec l0 0).\n                   { (* l > 0 *)\n                   eapply step_implies_reduces.\n                   eapply SAssignLowOOB; eauto...\n                   unfold eval_type_bound,eval_bound. reflexivity.\n                   unfold get_low_ptr. easy.\n                   }\n                   { (* l <= 0 *)\n                     eapply step_implies_reduces.   \n                     eapply SAssignNull; eauto.\n                     unfold eval_type_bound,eval_bound. eauto.\n                   }\n                 * (* h <= 0 *)\n                   eapply step_implies_reduces.\n                   eapply SAssignHighOOB; eauto...\n                   unfold eval_type_bound,eval_bound. reflexivity.\n                   unfold get_high_ptr. easy.\n         }\n      * unfold reduces in HRed2. destruct HRed2 as [ H' [ ? [ ? [ r HRed2 ] ] ] ].\n        inv HRed2; ctx (EAssign (ELit n1' t1') (in_hole e E)) (in_hole e (CAssignR n1' t1' E))...\n      * destruct HUnchk2 as [ e' [ E [ ] ] ]; subst.\n        ctx (EAssign (ELit n1' t1') (in_hole e' E)) (in_hole e' (CAssignR n1' t1' E))...\n    + (* Case: e1 reduces *)\n      destruct HRed1 as [ H' [ ? [? [ r HRed1 ] ] ] ].\n      inv HRed1; ctx (EAssign (in_hole e E) e2) (in_hole e (CAssignL E e2))...\n    + destruct HUnchk1 as [ e' [ E [ ] ] ]; subst.\n      ctx (EAssign (in_hole e' E) e2) (in_hole e' (CAssignL E e2))...\n\n  (* T-IndAssign for array pointer. *)\n  - (* This isn't a value, so it must reduce *)\n    right.\n\n    (* If m' is unchecked, then we are typing mode is unchecked *)\n    destruct m'; [> | right; eauto 20 with Progress].\n    clear HMode.\n    inv Hewf.\n    inv H2.\n    (*\n    assert (exists l0 h0, t = (TPtr Checked (TArray l0 h0 t'))).\n    {\n      inv HSubType. exists l; exists h; eauto.\n      exists l0; exists h0; eauto.\n    }\n    destruct H0 as [l0 [h0 H0]].\n    rewrite H0 in *.\n    clear HSubType H0 l h.\n    remember l0 as l. remember h0 as h.\n    clear Heql Heqh l0 h0 t.\n    remember t' as t. clear Heqt t'.\n    *)\n    (* Invoke IH on e1 *)\n    apply (IH1) in H4; try easy.\n    destruct H4 as [ HVal1 | [ HRed1 | [| HUnchk1 ] ] ]; idtac...\n    + (* Case: e1 is a value *)\n      inv HVal1.\n      (* Invoke IH on e2 *)\n      apply (IH2) in H5; try easy.\n      destruct H5 as [ HVal2 | [ HRed2 | [| HUnchk2 ] ] ]; idtac...\n      * inv HVal2.\n        ctx (EAssign (EPlus (ELit n t0) (ELit n0 t1)) e3) \n                  (in_hole (EPlus (ELit n t0) (ELit n0 t1)) (CAssignL CHole e3)).\n        inv HTy1.\n        inv HTy2.\n        assert (Hsim := H2).\n        inv Hsim. inv H8.\n        assert (simple_type TNat). constructor.\n        {\n          apply (IH3) in H3; try easy.\n          inv H2; inv H7; (eauto 20 with Progress); \n            try solve_empty_scope.\n          - destruct H3 as [ HVal3 | [ HRed3 | [| HUnchk3]]]; idtac...\n            + inv HVal3.\n              inv HTy3.\n              left; eauto...\n              destruct (Z_gt_dec n 0); subst; rewrite HCtx; do 4 eexists.\n              * eapply RSExp... eapply SPlusChecked. easy.\n                unfold is_array_ptr. easy.\n              * eapply RSHaltNull... eapply SPlusNull. lia.\n                unfold is_array_ptr. easy.\n            + destruct HRed3 as [H' [? [r HRed3]]].\n              destruct (Z_gt_dec n 0).\n              rewrite HCtx; left; do 4 eexists.\n              eapply RSExp... eapply SPlusChecked. easy.\n                unfold is_array_ptr. easy.\n              rewrite HCtx; left; do 4 eexists.\n              eapply RSHaltNull... eapply SPlusNull. lia.\n                unfold is_array_ptr. easy.\n            + destruct HUnchk3 as [ e' [ E [ He2 HEUnchk ]]]; subst.\n              destruct (Z_gt_dec n 0).\n              rewrite HCtx; left; do 4 eexists.\n              eapply RSExp... eapply SPlusChecked. easy.\n                unfold is_array_ptr. easy.\n              rewrite HCtx; left; do 4 eexists.\n              eapply RSHaltNull... eapply SPlusNull. lia.\n                unfold is_array_ptr. easy.\n        }\n      * destruct HRed2 as [ H' [ ? [? [ r HRed2 ] ] ] ].\n        inv HRed2; ctx (EAssign (EPlus (ELit n t0) (in_hole e E)) e3) (in_hole e (CAssignL (CPlusR n t0 E) e3))...\n      * destruct HUnchk2 as [ e' [ E [ He2 HEUnchk ] ] ]; subst.\n        ctx (EAssign (EPlus (ELit n t0) (in_hole e' E)) e3) (in_hole e' (CAssignL (CPlusR n t0 E) e3))...\n    + destruct HRed1 as [ H' [? [ ? [ r HRed1 ] ] ] ].\n      inv HRed1; ctx (EAssign (EPlus (in_hole e E) e2) e3) (in_hole e (CAssignL (CPlusL E e2) e3))...\n    + destruct HUnchk1 as [ e' [ E [ He1 HEUnchk ] ] ]; subst.\n      ctx (EAssign (EPlus (in_hole e' E) e2) e3) (in_hole e' (CAssignL (CPlusL E e2) e3))...\n  (* T-IndAssign for ntarray pointer. *)\n  - (* This isn't a value, so it must reduce *)\n    right.\n\n    (* If m' is unchecked, then we are typing mode is unchecked *)\n    destruct m'; [> | right; eauto 20 with Progress].\n    clear HMode.\n    inv Hewf. inv H2.\n    (*\n    assert (exists l0 h0, t = (TPtr Checked (TArray l0 h0 t'))).\n    {\n      inv HSubType. exists l; exists h; eauto.\n      exists l0; exists h0; eauto.\n    }\n    destruct H0 as [l0 [h0 H0]].\n    rewrite H0 in *.\n    clear HSubType H0 l h.\n    remember l0 as l. remember h0 as h.\n    clear Heql Heqh l0 h0 t.\n    remember t' as t. clear Heqt t'.\n    *)\n    (* Invoke IH on e1 *)\n    apply (IH1) in H4; try easy.\n    destruct H4 as [ HVal1 | [ HRed1 | [| HUnchk1 ] ] ]; idtac...\n    + (* Case: e1 is a value *)\n      inv HVal1.\n      (* Invoke IH on e2 *)\n      apply (IH2) in H5; try easy.\n      destruct H5 as [ HVal2 | [ HRed2 | [| HUnchk2 ] ] ]; idtac...\n      * inv HVal2.\n        ctx (EAssign (EPlus (ELit n t0) (ELit n0 t1)) e3) \n                  (in_hole (EPlus (ELit n t0) (ELit n0 t1)) (CAssignL CHole e3)).\n        inv HTy1.\n        inv HTy2.\n        assert (Hsim := H2).\n        inv Hsim. inv H8.\n        assert (simple_type TNat). constructor.\n        {\n          apply (IH3) in H3; try easy.\n          inv H2; inv H7; (eauto 20 with Progress); \n            try solve_empty_scope.\n          - destruct H3 as [ HVal3 | [ HRed3 | [| HUnchk3]]]; idtac...\n            + inv HVal3.\n              inv HTy3.\n              left; eauto...\n              destruct (Z_gt_dec n 0); subst; rewrite HCtx; do 4 eexists.\n              * eapply RSExp... eapply SPlusChecked. easy.\n                unfold is_array_ptr. easy.\n              * eapply RSHaltNull... eapply SPlusNull. lia.\n                unfold is_array_ptr. easy.\n            + destruct HRed3 as [H' [? [r HRed3]]].\n              destruct (Z_gt_dec n 0).\n              rewrite HCtx; left; do 4 eexists.\n              eapply RSExp... eapply SPlusChecked. easy.\n                unfold is_array_ptr. easy.\n              rewrite HCtx; left; do 4 eexists.\n              eapply RSHaltNull... eapply SPlusNull. lia.\n                unfold is_array_ptr. easy.\n            + destruct HUnchk3 as [ e' [ E [ He2 HEUnchk ]]]; subst.\n              destruct (Z_gt_dec n 0).\n              rewrite HCtx; left; do 4 eexists.\n              eapply RSExp... eapply SPlusChecked. easy.\n                unfold is_array_ptr. easy.\n              rewrite HCtx; left; do 4 eexists.\n              eapply RSHaltNull... eapply SPlusNull. lia.\n                unfold is_array_ptr. easy.\n        }\n      * destruct HRed2 as [ H' [ ? [? [ r HRed2 ] ] ] ].\n        inv HRed2; ctx (EAssign (EPlus (ELit n t0) (in_hole e E)) e3) (in_hole e (CAssignL (CPlusR n t0 E) e3))...\n      * destruct HUnchk2 as [ e' [ E [ He2 HEUnchk ] ] ]; subst.\n        ctx (EAssign (EPlus (ELit n t0) (in_hole e' E)) e3) (in_hole e' (CAssignL (CPlusR n t0 E) e3))...\n    + destruct HRed1 as [ H' [? [ ? [ r HRed1 ] ] ] ].\n      inv HRed1; ctx (EAssign (EPlus (in_hole e E) e2) e3) (in_hole e (CAssignL (CPlusL E e2) e3))...\n    + destruct HUnchk1 as [ e' [ E [ He1 HEUnchk ] ] ]; subst.\n      ctx (EAssign (EPlus (in_hole e' E) e2) e3) (in_hole e' (CAssignL (CPlusL E e2) e3))...\n\n\n   -   (* IfDef. *)\n    right.\n\n    (* If m' is unchecked, then the typing mode `m` is unchecked *)\n    destruct m'; [> | right; eauto 20 with Progress].\n    clear HMode.\n\n    (* TODO(ins): find a way to automate everything after case analysis... *)\n    inv Hewf.\n    apply HSwf in HEnv as eq1.\n    destruct eq1 as [va [ta [tb [X1 [X2 X3]]]]].\n    apply HSwt in X3 as eq2. destruct eq2 as [X4 [X5 X6]].\n    apply HSHwf in X3 as eq3.\n    destruct HPtr as [l [h [tc HPt]]].\n    destruct HPt. destruct H0. subst.\n    inv X1. rename H6 into eq4.\n    apply cast_word_type in eq4 as eq5.\n    inv X2.\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 (TPtr Checked t'))) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail;eauto.\n    unfold is_rexpr. easy.\n    solve_empty_scope. inv H5.\n    inv H3. inv H6.\n    simpl in *.\n    assert (0 <= 0 <1) by lia.\n    destruct (H10 0 H1) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked TNat))) st H (RExpr (ELit nd TNat))).\n    eapply SDeref;eauto. constructor. constructor.\n    intros.  inv H3. intros. inv H3. apply get_root_word. constructor.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H6.\n    simpl in *.\n    assert (0 <= 0 <1) by lia.\n    destruct (H10 0 H3) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TPtr m0 w)))) st H (RExpr (ELit nd (TPtr m0 w)))).\n    eapply SDeref;eauto. constructor. constructor. apply simple_type_means_cast_same. easy.\n    intros.  inv H5. intros. inv H5. apply get_root_word. constructor.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    1-4:inv eq5.\n\n    inv H3. inv H12. inv H13. inv H6.\n    rewrite replicate_gt_eq in H10; try lia.\n    assert (l1 <= 0 < l1 + (h1 - l1)) by lia.\n    destruct (H10 0 H1) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked t'))) st H (RExpr (ELit nd t'))).\n    eapply SDeref;eauto. constructor. apply simple_type_means_cast_same. easy.\n    intros.  inv H3. inv H11. intros. inv H3. inv eq5. apply get_root_word. easy.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. inv H11. easy. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. inv H11. easy. easy.\n    inv H3. inv H12. inv H13. inv H6.\n    rewrite replicate_gt_eq in H10; try lia.\n    assert (l1 <= 0 < l1 + (h1 - l1 + 1)) by lia.\n    destruct (H10 0 H1) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked t'))) st H (RExpr (ELit nd t'))).\n    eapply SDeref;eauto. constructor. apply simple_type_means_cast_same. easy.\n    intros.  inv H3. inv H11. intros. inv H3. inv eq5. apply get_root_word. easy.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. inv H11. easy. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. inv H11. easy. easy.\n    inv eq5. inv eq5. inv eq5. \n    inv H6.\n    apply StructDef.find_1 in H11. rewrite H11 in *. inv H5.\n    assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) fs))) > 0). \n    {\n       eapply struct_subtype_non_empty; eauto.\n       apply (SubTyStructArrayField_1 D Q T fs m).\n       apply StructDef.find_2. assumption.\n       assumption.\n       apply StructDef.find_2.  easy.\n    }\n    assert (0 <= 0 < 0 +\n     Z.of_nat (length (map snd (Fields.elements (elt:=type) fs)))).\n    lia.\n    destruct (H10 0 H5) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked TNat))) st H (RExpr (ELit nd TNat))).\n    eapply SDeref;eauto. constructor. constructor.\n    intros.  inv H6. intros. inv H6. apply get_root_word. constructor.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv eq5. inv eq5.\n  \n    inv X6. inv H3.\n    inv H7. inv H8.\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 (TPtr Checked (TArray (Num l1) (Num h1) t')))) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail with (r := RNull);eauto.\n    solve_empty_scope.\n    inv H8. inv H10.\n    simpl in *.\n    rewrite replicate_gt_eq in H14; try lia.\n    assert (l1 <= 0 < l1 + (h1 - l1)) by lia.\n    destruct (H14 0 H1) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TArray (Num l1) (Num h1) t')))) st H (RExpr (ELit nd t'))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy. apply simple_type_means_cast_same. easy.\n    intros.  inv H8. lia. intros. inv H8. apply get_root_array. \n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H16. inv H10. simpl in *.\n    assert (0 <= 0 <1) by lia.\n    destruct (H14 0 H1) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H \n           (EDeref (ELit va (TPtr Checked (TArray (Num l1) (Num h1) TNat)))) st H (RExpr (ELit nd TNat))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy. constructor.\n    intros.  inv H8. lia. intros. inv H8. apply get_root_array. constructor.\n    destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H10. simpl in *.\n    assert (0 <= 0 <1) by lia.\n    destruct (H14 0 H1) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H \n           (EDeref (ELit va (TPtr Checked (TArray (Num l1) (Num h1) (TPtr m0 w))))) st H (RExpr (ELit nd (TPtr m0 w)))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same. easy.\n    intros.  inv H8. lia. intros. inv H8. apply get_root_array. constructor.\n    destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n\n    inv H15. inv H15. inv H3. inv H15. inv H18. inv H10.\n    simpl in *.\n    rewrite replicate_gt_eq in H14; try lia.\n    assert (l2 <= 0 < l2 + (h2 - l2)) by lia.\n    destruct (H14 0 H1) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TArray (Num l1) (Num h1) t')))) st H (RExpr (ELit nd t'))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same. easy.\n    intros.  inv H3. lia. intros. inv H3. apply get_root_array. \n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H3. inv H15. inv H18. inv H10.\n    simpl in *.\n    rewrite replicate_gt_eq in H14; try lia.\n    assert (l2 <= 0 < l2 + (h2 - l2 + 1)) by lia.\n    destruct (H14 0 H1) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TArray (Num l1) (Num h1) t')))) st H (RExpr (ELit nd t'))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same. easy.\n    intros.  inv H3. lia. intros. inv H3. apply get_root_array. \n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H10. inv H19. inv H20.\n    apply StructDef.find_1 in H17. rewrite H17 in *. inv H8.\n    assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) fs))) > 0). \n    {\n       eapply struct_subtype_non_empty; eauto.\n       apply (SubTyStructArrayField_1 D Q T fs m).\n       apply StructDef.find_2. assumption.\n       assumption.\n       apply StructDef.find_2.  easy.\n    }\n    assert (0 <= 0 < 0 +\n     Z.of_nat (length (map snd (Fields.elements (elt:=type) fs)))).\n    lia.\n    destruct (H14 0 H8) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TArray (Num l1) (Num h1) TNat)))) st H (RExpr (ELit nd TNat))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy. constructor.\n    intros.  inv H10. lia. intros. inv H10. apply get_root_array. constructor.\n    destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n\n    inv X6. inv H3. inv H7. inv H8.\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 (TPtr Checked (TNTArray (Num l1) (Num h1) t')))) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail;eauto.\n    unfold is_rexpr. easy.\n    solve_empty_scope.\n    inv H8. inv H10.\n    simpl in *.\n    rewrite replicate_gt_eq in H14; try lia.\n    assert (l1 <= 0 < l1 + (h1 - l1  + 1)) by lia.\n    destruct (H14 0 H1) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TNTArray (Num l1) (Num h1) t')))) st H (RExpr (ELit nd t'))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same. easy.\n    intros.  inv H8. intros. inv H8. lia. apply get_root_ntarray. \n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. destruct h1; easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. destruct h1; easy.\n    inv H15. inv H15. inv H3. inv H15. inv H18. inv H10.\n    simpl in *.\n    rewrite replicate_gt_eq in H14; try lia.\n    assert (l2 <= 0 < l2 + (h2 - l2 + 1)) by lia.\n    destruct (H14 0 H1) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TNTArray (Num l1) (Num h1) t')))) st H (RExpr (ELit nd t'))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same. easy.\n    intros.  inv H3. intros. inv H3. lia. apply get_root_ntarray. \n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. destruct h1; easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. destruct h1; easy.\n    1-3:inv eq5.\n\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 (TPtr Checked (TStruct T)))) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail;eauto.\n    unfold is_rexpr. easy.\n    solve_empty_scope.\n    inv H5.\n    inv H8.\n    apply StructDef.find_1 in H6. rewrite H6 in *. inv H5.\n    assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) fs))) > 0). \n    {\n       eapply struct_subtype_non_empty; eauto.\n       apply (SubTyStructArrayField_1 D Q T fs m).\n       apply StructDef.find_2. assumption.\n       assumption.\n       apply StructDef.find_2.  easy.\n    }\n    assert (0 <= 0 < 0 +\n     Z.of_nat (length (map snd (Fields.elements (elt:=type) fs)))).\n    lia.\n    destruct (H12 0 H5) as [nd [td [Y1 [Y2 Y3]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TStruct T)))) st H (RExpr (ELit nd TNat))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy. apply get_root_struct with (f := fs); try easy.\n    apply StructDef.find_2 in H6. easy.\n    left. destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H13. inv H13. inv eq5. easy.\n\n    destruct H0.\n    destruct H0 as [Y1 [Y2 Y3]];subst.\n    inv X1. inv H5.\n    apply cast_bound_num in H6 as eq2. destruct eq2 as [l1 eq4]; subst.\n    apply cast_bound_num in H8 as eq2. destruct eq2 as [h1 eq4]; subst.\n    apply cast_word_type in H9 as eq4; try easy.\n    inv X2.\n    \n   destruct (Z_gt_dec l1 0).\n\n   (* if l > 0 we have a bounds error*)\n   {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply SDerefLowOOB;eauto. easy.\n      unfold get_low_ptr. easy.\n   }\n\n   destruct (Z_le_dec h1 0).\n\n   (* if h < 0 we have a bounds error*)\n    {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply (SDerefHighOOB) with (h := h1);eauto. easy.\n      unfold get_high_ptr. easy.\n    }\n\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 (TPtr Checked (TArray (Num l1) (Num h1) t'0)))) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail with (r := RNull);eauto.\n    solve_empty_scope.\n    inv H3. inv H5.\n    simpl in *.\n    rewrite replicate_gt_eq in H12; try lia.\n    assert (l1 <= 0 < l1 + (h1 - l1)) by lia.\n    destruct (H12 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TArray (Num l1) (Num h1) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy. apply simple_type_means_cast_same.\n    inv H1. easy.\n    intros.  inv H3. lia. intros. inv H3. apply get_root_array. \n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H16. inv H17. inv H14. inv H5. simpl in *.\n    assert (0 <= 0 <1) by lia.\n    destruct (H12 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H \n           (EDeref (ELit va (TPtr Checked (TArray (Num l1) (Num h1) TNat)))) st H (RExpr (ELit nd TNat))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy. constructor.\n    intros.  inv H3. lia. intros. inv H3. apply get_root_array. constructor.\n    destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H5. simpl in *.\n    assert (0 <= 0 <1) by lia.\n    destruct (H12 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H \n           (EDeref (ELit va (TPtr Checked (TArray (Num l1) (Num h1) (TPtr m0 w))))) st H (RExpr (ELit nd (TPtr m0 w)))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same. easy.\n    intros.  inv H3. lia. intros. inv H3. apply get_root_array. constructor.\n    destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H13. inv H13. inv H1. inv H13. inv H16.\n    inv H5.\n    simpl in *.\n    rewrite replicate_gt_eq in H12; try lia.\n    assert (l2 <= 0 < l2 + (h2 - l2)) by lia.\n    destruct (H12 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TArray (Num l1) (Num h1) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy. apply simple_type_means_cast_same. easy.\n    intros.  inv H1. lia. intros. inv H1. apply get_root_array. \n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H1. inv H13. inv H16. inv H5.\n    simpl in *.\n    rewrite replicate_gt_eq in H12; try lia.\n    assert (l2 <= 0 < l2 + (h2 - l2 + 1)) by lia.\n    destruct (H12 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TArray (Num l1) (Num h1) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy. apply simple_type_means_cast_same. easy.\n    intros.  inv H1. lia. intros. inv H1. apply get_root_array. \n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H17. inv H18. inv H5.\n    apply StructDef.find_1 in H15. rewrite H15 in *. inv H3.\n    assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) fs))) > 0). \n    {\n       eapply struct_subtype_non_empty; eauto.\n       apply (SubTyStructArrayField_1 D Q T fs m).\n       apply StructDef.find_2. assumption.\n       assumption.\n       apply StructDef.find_2.  easy.\n    }\n    assert (0 <= 0 < 0 +\n     Z.of_nat (length (map snd (Fields.elements (elt:=type) fs)))).\n    lia.\n    destruct (H12 0 H3) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TArray (Num l1) (Num h1) TNat)))) st H (RExpr (ELit nd TNat))).\n    eapply SDeref;eauto. constructor. constructor. constructor. easy. constructor.\n    intros. inv H5. lia. intros. inv H5. apply get_root_array.\n    left. destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 (TPtr Checked ( t'0)))) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail with (r := RNull);eauto.\n    solve_empty_scope.\n    inv H3. inv eq4. inv H5.\n    simpl in *.\n    assert (0 <= 0 < 1) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked TNat))) st H (RExpr (ELit nd TNat))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply get_root_word. constructor.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H5. simpl in *.\n    assert (0 <= 0 <1) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H \n           (EDeref (ELit va (TPtr Checked (TPtr m0 w)))) st H (RExpr (ELit nd (TPtr m0 w)))).\n    eapply SDeref;eauto. constructor. \n    apply simple_type_means_cast_same; try easy.\n    intros.  inv H3. intros. inv H3. apply get_root_word. constructor.\n    left.\n    destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv eq4.\n    inv H17. inv H18. inv H5. \n    rewrite replicate_gt_eq in H15; try lia.\n    assert (l2 <= 0 < l2 + (h2 - l2)) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked t'0))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor.\n    inv H1. apply simple_type_means_cast_same; try easy.\n    intros. inv H5. inv H16.\n    intros. inv H5. inv H16.\n    apply get_root_word. easy.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    inv H16; easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    inv H16; easy.\n    inv H1. inv H1. inv H5. inv H17. inv H18.\n    rewrite replicate_gt_eq in H15; try lia.\n    assert (l2 <= 0 < l2 + (h2 - l2 + 1)) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked t'0))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H1. inv H16.\n    intros. inv H1. inv H16.\n    apply get_root_word. easy.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    inv H16; easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    inv H16; easy.\n    inv eq4. inv eq4. inv eq4.\n    inv H5.\n    apply StructDef.find_1 in H16. rewrite H16 in *. inv H3.\n    assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) fs))) > 0). \n    {\n       eapply struct_subtype_non_empty; eauto.\n       apply (SubTyStructArrayField_1 D Q T fs m).\n       apply StructDef.find_2. assumption.\n       assumption.\n       apply StructDef.find_2.  easy.\n    }\n    assert (0 <= 0 < 0 +\n     Z.of_nat (length (map snd (Fields.elements (elt:=type) fs)))).\n    lia.\n    destruct (H15 0 H3) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked TNat))) st H (RExpr (ELit nd TNat))).\n    eapply SDeref;eauto. constructor. constructor.\n    intros. inv H5. intros. inv H5. apply get_root_word. constructor.\n    left. destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv eq4. inv H3. inv H3.\n\n    inv X6. inv H1. inv H5. inv H11.\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 ( (TPtr Checked (TArray (Num l2) (Num h2) t'0))))) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail with (r := RNull);eauto.\n    solve_empty_scope.\n    inv H10. inv H11.\n   destruct (Z_gt_dec l2 0).\n\n   (* if l > 0 we have a bounds error*)\n   {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply SDerefLowOOB;eauto. easy.\n      unfold get_low_ptr. easy.\n   }\n\n   destruct (Z_le_dec h2 0).\n\n   (* if h < 0 we have a bounds error*)\n    {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply (SDerefHighOOB) with (h := h2);eauto. easy.\n      unfold get_high_ptr. easy.\n    }\n\n    simpl in *.\n    rewrite replicate_gt_eq in H15; try lia.\n    assert (l2 <= 0 < l2 + (h2 - l2)) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TArray (Num l2) (Num h2) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H10. lia. intros. inv H10.\n    apply get_root_array.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n\n   destruct (Z_gt_dec l2 0).\n   {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply SDerefLowOOB;eauto. easy.\n      unfold get_low_ptr. easy.\n   }\n\n   destruct (Z_le_dec h2 0).\n\n   (* if h < 0 we have a bounds error*)\n    {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply (SDerefHighOOB) with (h := h2);eauto. easy.\n      unfold get_high_ptr. easy.\n    }\n\n    inv eq4. inv H11.\n    simpl in *.\n    assert (0 <= 0 <1) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H \n           (EDeref (ELit va (TPtr Checked (TArray (Num l2) (Num h2) TNat)))) st H (RExpr (ELit nd TNat))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy. constructor. \n    intros.  inv H10. lia. intros. inv H10.\n    apply get_root_array.\n    left.\n    destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H11.\n    simpl in *.\n    assert (0 <= 0 <1) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H \n           (EDeref (ELit va (TPtr Checked (TArray (Num l2) (Num h2) (TPtr m0 w))))) st H (RExpr (ELit nd (TPtr m0 w)))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same; try easy.\n    intros.  inv H10. lia. intros. inv H10.\n    apply get_root_array.\n    left.\n    destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H16. inv H16. inv H1. inv H16. inv H19.\n\n   destruct (Z_gt_dec l2 0).\n   {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply SDerefLowOOB;eauto. easy.\n      unfold get_low_ptr. easy.\n   }\n\n   destruct (Z_le_dec h2 0).\n\n   (* if h < 0 we have a bounds error*)\n    {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply (SDerefHighOOB) with (h := h2);eauto. easy.\n      unfold get_high_ptr. easy.\n    }\n\n    inv H11.\n    rewrite replicate_gt_eq in H15; try lia.\n    assert (l3 <= 0 < l3 + (h3 - l3)) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TArray (Num l2) (Num h2) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H1. lia.\n    intros. inv H1.\n    apply get_root_array.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    easy.\n\n    inv H1. inv H16. inv H19.\n\n   destruct (Z_gt_dec l2 0).\n   {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply SDerefLowOOB;eauto. easy.\n      unfold get_low_ptr. easy.\n   }\n\n   destruct (Z_le_dec h2 0).\n\n   (* if h < 0 we have a bounds error*)\n    {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply (SDerefHighOOB) with (h := h2);eauto. easy.\n      unfold get_high_ptr. easy.\n    }\n\n    inv H11.\n    rewrite replicate_gt_eq in H15; try lia.\n    assert (l3 <= 0 < l3 + (h3 - l3+1)) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TArray (Num l2) (Num h2) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H1. lia.\n    intros. inv H1.\n    apply get_root_array.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    easy.\n    inv H20. inv H21.\n\n   destruct (Z_gt_dec l2 0).\n   {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply SDerefLowOOB;eauto. easy.\n      unfold get_low_ptr. easy.\n   }\n\n   destruct (Z_le_dec h2 0).\n\n   (* if h < 0 we have a bounds error*)\n    {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply (SDerefHighOOB) with (h := h2);eauto. easy.\n      unfold get_high_ptr. easy.\n    }\n    inv H11.\n    apply StructDef.find_1 in H18. rewrite H18 in *. inv H10.\n    assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) fs))) > 0). \n    {\n       eapply struct_subtype_non_empty; eauto.\n       apply (SubTyStructArrayField_1 D Q T fs m).\n       apply StructDef.find_2. assumption.\n       assumption.\n       apply StructDef.find_2.  easy.\n    }\n    assert (0 <= 0 < 0 +\n     Z.of_nat (length (map snd (Fields.elements (elt:=type) fs)))).\n    lia.\n    destruct (H15 0 H10) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TArray (Num l2) (Num h2) TNat)) )) st H (RExpr (ELit nd TNat))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy. constructor.\n    intros. inv H11. lia. intros. inv H11. apply get_root_array. \n    left. destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv X6.  inv H1. inv H5. inv H11.\n\n   destruct (Z_gt_dec l2 0).\n   {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply SDerefLowOOB;eauto. easy.\n      unfold get_low_ptr. easy.\n   }\n\n   destruct (Z_le_dec h2 0).\n\n   (* if h < 0 we have a bounds error*)\n    {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply (SDerefHighOOB) with (h := h2);eauto. easy.\n      unfold get_high_ptr. easy.\n    }\n\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 (TPtr Checked (TNTArray (Num l2) (Num h2) t'0)))) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail with (r := RNull);eauto.\n    solve_empty_scope.\n    inv H10. inv H11.\n    simpl in *.\n    rewrite replicate_gt_eq in H15; try lia.\n    assert (l2 <= 0 < l2 + (h2 - l2+1)) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TNTArray (Num l2) (Num h2) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H10.\n    intros. inv H10. lia.\n    apply get_root_ntarray.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    destruct h2. lia. easy. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    destruct h2. lia. easy. easy.\n    inv H16. inv H16.\n    inv H16. inv H19.\n    inv H11.\n    rewrite replicate_gt_eq in H15; try lia.\n    assert (l3 <= 0 < l3 + (h3 - l3 + 1)) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TNTArray (Num l2) (Num h2) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor.\n    inv H1. constructor. easy. easy.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H11.\n    intros. inv H11. lia.\n    apply get_root_ntarray.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    destruct h2. lia. easy. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    destruct h2. lia. easy. easy.\n    inv H1.\n    \n    inv H12. inv H13.\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 ( TPtr Checked (TStruct T)))) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail with (r := RNull);eauto.\n    solve_empty_scope.\n    inv H7. inv H12.\n    apply StructDef.find_1 in H10. rewrite H10 in *. inv H7.\n    assert ( Z.of_nat (length (map snd (Fields.elements (elt:=type) fs))) > 0). \n    {\n       eapply struct_subtype_non_empty; eauto.\n       apply (SubTyStructArrayField_1 D Q T fs m).\n       apply StructDef.find_2. assumption.\n       assumption.\n       apply StructDef.find_2.  easy.\n    }\n    assert (0 <= 0 < 0 +\n     Z.of_nat (length (map snd (Fields.elements (elt:=type) fs)))).\n    lia.\n    destruct (H16 0 H7) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TStruct T)))) st H (RExpr (ELit nd TNat))).\n    eapply SDeref;eauto. constructor. constructor.\n    intros. inv H12. intros. inv H12. apply get_root_struct with (f := fs).\n    apply StructDef.find_2 in H10. easy. easy.\n    left. destruct nd.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H17. inv H17.\n\n    destruct H0 as [Y1 [Y2 Y3]]; subst.\n    inv X1. inv H5.\n    apply cast_bound_num in H6 as eq2. destruct eq2 as [l0 eq2]; subst.\n    apply cast_bound_num in H8 as eq2. destruct eq2 as [h0 eq2]; subst.\n    apply cast_word_type in H9 as eq2.\n    inv X2.\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 (TPtr Checked (TNTArray (Num l0) (Num h0) t'0)) )) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail with (r := RNull);eauto.\n    solve_empty_scope.\n\n   destruct (Z_gt_dec l0 0).\n   {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply SDerefLowOOB;eauto. easy.\n      unfold get_low_ptr. easy.\n   }\n\n   destruct (Z_le_dec h0 0).\n\n   (* if h < 0 we have a bounds error*)\n    {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply (SDerefHighOOB) with (h := h0);eauto. easy.\n      unfold get_high_ptr. easy.\n    }\n\n    inv H3.\n    inv H5.\n    simpl in *.\n    rewrite replicate_gt_eq in H12; try lia.\n    assert (l0 <= 0 < l0 + (h0 - l0+1)) by lia.\n    destruct (H12 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TNTArray (Num l0) (Num h0) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H3.\n    intros. inv H3. lia.\n    apply get_root_ntarray.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    destruct h0. lia. easy. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    destruct h0. lia. easy. easy.\n    inv H13. inv H13. inv H13. inv H16.\n    inv H5.\n    simpl in *.\n    rewrite replicate_gt_eq in H12; try lia.\n    assert (l2 <= 0 < l2 + (h2 - l2+1)) by lia.\n    destruct (H12 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TNTArray (Num l0) (Num h0) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy. inv H1.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H5.\n    intros. inv H5. lia.\n    apply get_root_ntarray.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    destruct h0. lia. easy. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    destruct h0. lia. easy. easy.\n    inv H1. inv H3. inv H3.\n    inv X6. inv H1. inv H5. inv H11.\n\n   destruct (Z_gt_dec l2 0).\n   {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply SDerefLowOOB;eauto. easy.\n      unfold get_low_ptr. easy.\n   }\n\n   destruct (Z_le_dec h2 0).\n\n   (* if h < 0 we have a bounds error*)\n    {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply (SDerefHighOOB) with (h := h2);eauto. easy.\n      unfold get_high_ptr. easy.\n    }\n\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 (TPtr Checked (TNTArray (Num l2) (Num h2) t'0)))) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail with (r := RNull);eauto.\n    solve_empty_scope.\n    inv H10. inv H11. \n    rewrite replicate_gt_eq in H15; try lia.\n    assert (l2 <= 0 < l2 + (h2 - l2+1)) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TNTArray (Num l2) (Num h2) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H10.\n    intros. inv H10. lia.\n    apply get_root_ntarray.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    destruct h2. lia. easy. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    destruct h2. lia. easy. easy.\n    inv H16. inv H16. inv H1. inv H16. inv H19.\n    inv H11.\n    simpl in *.\n    rewrite replicate_gt_eq in H15; try lia.\n    assert (l3 <= 0 < l3 + (h3 - l3+1)) by lia.\n    destruct (H15 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TNTArray (Num l2) (Num h2) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H1.\n    intros. inv H1. lia.\n    apply get_root_ntarray.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    destruct h2. lia. easy. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3.\n    destruct h2. lia. easy. easy. easy.\n\n   - (* Ty-If-NT *)\n    right.\n\n    (* If m' is unchecked, then the typing mode `m` is unchecked *)\n    destruct m'; [> | right; eauto 20 with Progress].\n    clear HMode.\n\n    (* TODO(ins): find a way to automate everything after case analysis... *)\n    inv Hewf.\n    apply HSwf in HEnv as eq1.\n    destruct eq1 as [va [ta [tb [X1 [X2 X3]]]]].\n    apply HSwt in X3 as eq2. destruct eq2 as [X4 [X5 X6]].\n    apply HSHwf in X3 as eq3.\n\n    inv X1. inv H5.\n    apply Henv in HEnv. destruct HEnv as [X7 [X8 X9]].\n    inv X8. inv H1.\n    apply cast_word_type in H9 as eq5; try easy.\n    apply cast_bound_num in H6 as eq4. destruct eq4 as [l0 eq4]; subst.\n    unfold cast_bound in H8. inv H8.\n    inv X2.\n\n   destruct (Z_gt_dec l0 0).\n   {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply SDerefLowOOB;eauto. easy.\n      unfold get_low_ptr. easy.\n   }\n\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 (TPtr Checked (TNTArray (Num l0) (Num 0) t'0)))) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail;eauto.\n    unfold is_rexpr. easy.\n    solve_empty_scope.\n    inv H3. inv H7.\n    simpl in *.\n    rewrite replicate_gt_eq in H13; try lia.\n    assert (l0 <= 0 < l0 + (- l0+1)) by lia.\n    destruct (H13 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TNTArray (Num l0) (Num 0) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H3.\n    intros. inv H3. lia.\n    apply get_root_ntarray.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H14. inv H14.\n    inv H1.\n    inv H7. inv H14. inv H17.\n    simpl in *.\n    rewrite replicate_gt_eq in H13; try lia.\n    assert (l2 <= 0 < l2 + (h0- l2+1)) by lia.\n    destruct (H13 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TNTArray (Num l0) (Num 0) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H1.\n    intros. inv H1. lia.\n    apply get_root_ntarray.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    inv H3. inv H3.\n    inv X6. inv H1. inv H7. inv H12.\n\n   destruct (Z_gt_dec l2 0).\n   {\n      left.\n      eapply step_implies_reduces. \n      eapply (SIfDefFail) with (r := RBounds);eauto.\n      eapply SDerefLowOOB with (l := l2);eauto. easy.\n      unfold get_low_ptr. easy.\n   }\n\n    inv eq3.\n    assert (step D (fenv env) st H (EDeref (ELit 0 (TPtr Checked (TNTArray (Num l2) (Num h0) t'0)))) st H RNull).\n    eapply SDerefNull;eauto. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFail;eauto.\n    unfold is_rexpr. easy.\n    solve_empty_scope.\n    inv H11. inv H12.\n    simpl in *.\n    rewrite replicate_gt_eq in H16; try lia.\n    assert (l2 <= 0 < l2 + (h0 - l2+1)) by lia.\n    destruct (H16 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TNTArray (Num l2) (Num h0) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor. inv H1. constructor. easy. easy.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H11.\n    intros. inv H11. lia.\n    apply get_root_ntarray.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    destruct h0.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    lia.\n    left. destruct h0.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    lia.\n    inv H17. inv H17.\n    inv H1.\n    inv H12. inv H17. inv H20.\n    simpl in *.\n    rewrite replicate_gt_eq in H16; try lia.\n    assert (l3 <= 0 < l3 + (h1- l3+1)) by lia.\n    destruct (H16 0 H0) as [nd [td [Y4 [Y5 Y6]]]].\n    rewrite Z.add_0_r in *.\n    assert (step D (fenv env) st H (EDeref (ELit va (TPtr Checked (TNTArray (Num l2) (Num h0) t'0)))) st H (RExpr (ELit nd t'0))).\n    eapply SDeref;eauto. constructor. constructor. easy. easy.\n    apply simple_type_means_cast_same; try easy.\n    intros. inv H1.\n    intros. inv H1. lia.\n    apply get_root_ntarray.\n    destruct nd.\n    left.\n    eapply step_implies_reduces.\n    eapply SIfDefFalse;eauto.\n    left. destruct h0.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    lia.\n    left. destruct h0.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    eapply step_implies_reduces.\n    eapply SIfDefTrueNotNTHit;eauto. lia.\n    unfold NTHit.\n    apply Stack.find_1 in X3. rewrite X3. easy.\n    lia.\n\n   - right.\n    inv Hewf.\n    apply (IH1) in H3; try easy.\n    (* Invoke the IH on `e1` *)\n    destruct H3 as [ HVal1 | [ HRed1 | HUnchk1 ] ].\n    (* Case: `e1` is a value *)\n    + (* We don't know if we can take a step yet, since `e2` might be unchecked. *)\n      inv HVal1 as [ n1 t1 ].\n      (* Invoke the IH on `e2` *)\n       left.\n       destruct n1 eqn:eq1.\n       eapply (step_implies_reduces D).\n       eapply SIfFalse;eauto.\n       eapply (step_implies_reduces D).\n       eapply SIfTrue;eauto. lia.\n       eapply (step_implies_reduces D).\n       eapply SIfTrue;eauto. lia.\n    (* Case: `e1` reduces *)\n    + (* We can take a step by reducing `e1` *)\n      left.\n      ctx (EIf e1 e2 e3) (in_hole e1 (CIf CHole e2 e3))...\n    (* Case: `e1` is unchecked *)\n    + (* `EPlus e1 e2` must be unchecked, since `e1` is *)\n      right.\n      ctx (EIf e1 e2 e3) (in_hole e1 (CIf CHole e2 e3)).\n      destruct HUnchk1...\nQed.\n\n\n\n(*\nLemma stack_simple_aux : forall D S x, stack_wf D (add_nt_one S x) -> stack_wf D S.\nProof.\n  unfold stack_simple in *.\n  unfold add_nt_one.\n  intros. \n  destruct (Stack.find (elt:=Z * type) x S) eqn:eq1.\n  destruct p. destruct t0.\n  apply (H x0 v t). assumption.\n  destruct t0.\n  apply (H x0 v t). assumption.\n  apply (H x0 v t). assumption.\n  apply (H x0 v t). assumption.\n  apply (H x0 v t). assumption.\n  destruct b0.\n  destruct (Nat.eq_dec x0 x).\n  specialize (H x z (TPtr m (TNTArray b (Num (z0 + 1)) t0))).\n  assert (Stack.MapsTo x\n      (z, TPtr m (TNTArray b (Num (z0 + 1)) t0))\n      (Stack.add x\n         (z, TPtr m (TNTArray b (Num (z0 + 1)) t0)) S)).\n  apply Stack.add_1. reflexivity.\n  apply H in H1.\n  apply Stack.find_2 in eq1.\n  subst.\n  apply (Stack.mapsto_always_same (Z * type) x (z, TPtr m (TNTArray b (Num z0) t0)) (v, t)) in eq1.\n  inv eq1.\n  inv H1. inv H3.\n  apply SPTPtr.\n  apply SPTNTArray. assumption. assumption.\n  specialize (H x0 v t).\n  assert (Stack.MapsTo x0 (v, t)\n      (Stack.add x\n         (z, TPtr m (TNTArray b (Num (z0 + 1)) t0)) S)).\n  apply Stack.add_2. lia. assumption.\n  apply H in H1.\n  assumption.\n  apply H with (x:= x0) (v:=v).  easy.\n  apply H with (x:= x0) (v:=v).  easy.\n  apply H with (x:= x0) (v:=v).  easy.\n  apply H with (x:= x0) (v:=v).  easy.\n  apply H with (x:= x0) (v:=v).  easy.\nQed.\n*)\n\n\nLemma stack_simple_eval_arg : forall s e n t t',\n              eval_arg s e t (ELit n t') -> simple_type t'.\nProof.\n  intros. inv H.\n  apply cast_means_simple_type with (s := s) (t := t). easy.\n  apply cast_means_simple_type with (s := s) (t := t). easy.\nQed.\n\nLemma subst_type_word_type : forall AS t, word_type t -> word_type (subst_type AS t).\nProof.\n intros. induction t. simpl. easy.\n simpl. constructor. simpl. easy.\n inv H.\n inv H.\nQed.\n\nLemma subst_type_type_wf : forall D AS t, type_wf D t -> type_wf D (subst_type AS t).\nProof.\n intros. induction t. simpl. easy.\n simpl. constructor. apply IHt. inv H. easy.\n simpl.  easy.\n simpl. constructor. inv H. apply subst_type_word_type. easy.\n apply IHt. inv H. easy.\n simpl. constructor. inv H. apply subst_type_word_type. easy.\n apply IHt. inv H. easy.\nQed.\n\nLemma stack_simple_eval_el : forall D AS s tvl el s',\n              stack_wt D s -> (forall x t, In (x,t) tvl -> word_type t /\\ type_wf D t) ->\n               eval_el AS s tvl el s' -> stack_wt D s'.\nProof.\n  intros. induction H1. easy.\n  apply stack_simple_eval_arg in H1 as eq1.\n  assert (stack_wt D s').\n  apply IHeval_el; try easy.\n  intros.\n  specialize (H0 x0 t0).\n  apply H0. simpl. right. easy.\n  unfold stack_wt.\n  intros.\n  destruct (Nat.eq_dec x0 x).\n  subst.\n  apply Stack.mapsto_add1 in H4. inv H4.\n  inv H1.\n  specialize (H0 x t).\n  assert (In (x, t) ((x, t) :: tvl)). simpl.  left. easy.\n  apply H0 in H1.\n  split.\n  apply cast_word_type with (s := s) (t := subst_type AS t). easy.\n  apply subst_type_word_type. easy.\n  split.\n  apply cast_type_wf with (s := s) (t := subst_type AS t). easy.\n  apply subst_type_type_wf. easy. easy.\n  specialize (H0 x t).\n  assert (In (x, t) ((x, t) :: tvl)). simpl.  left. easy.\n  apply H0 in H1.\n  split.\n  apply cast_word_type with (s := s) (t := subst_type AS t). easy.\n  apply subst_type_word_type. easy.\n  split.\n  apply cast_type_wf with (s := s) (t := subst_type AS t). easy.\n  apply subst_type_type_wf. easy. easy.\n  apply Stack.add_3 in H4.\n  apply H3 in H4. easy. lia.\nQed.\n\nLemma gen_arg_env_good : forall tvl enva, exists env, gen_arg_env enva tvl env.\nProof.\n intros.\n induction tvl. exists enva. subst. constructor.\n destruct IHtvl.\n destruct a.\n exists (Env.add v t x).\n constructor. easy.\nQed.\n\nLemma sub_domain_grows : forall tvl es env env' s s' AS,\n      gen_arg_env env tvl env' -> eval_el AS s tvl es s'\n    -> sub_domain env s -> sub_domain env' s'.\nProof.\n  induction tvl. intros.\n  inv H. inv H0. easy.\n  intros. inv H. inv H0.\n  apply sub_domain_grow.\n  apply IHtvl with (es := es0) (s := s) (env0 := env0) (AS := AS); try easy.\nQed.\n\n\nLemma stack_simple_prop : forall D env S H S' H' e e',\n         sub_domain env S ->\n         fun_wf D fenv -> expr_wf D fenv e -> stack_wt D S ->\n            step D (fenv env) S H e S' H' (RExpr e') -> stack_wt D S'.\nProof.\n  intros.\n  induction H4; try easy.\n  unfold stack_wt in *.\n  intros.\n  unfold change_strlen_stack in *.\n  destruct (n' <=? h).\n  apply (H3 x0 v t0). assumption.\n  destruct (Nat.eq_dec x x0). subst.\n  apply Stack.mapsto_add1 in H10. inv H10.\n  apply H3 in H7. inv H7. constructor.\n  inv H10. constructor.\n  inv H10. inv H11. split.\n  constructor. inv H7. constructor. inv H12. easy. inv H12. easy.\n  inv H10. constructor. inv H12. constructor. easy.\n  apply Stack.add_3 in H10.\n  apply H3 in H10. easy. easy.\n  apply stack_simple_eval_el with (D := D) in H6. easy. easy.\n  intros.\n  unfold fun_wf in *.\n  specialize (gen_arg_env_good tvl env0) as X1.\n  destruct X1.\n  specialize (H1 H env0 x1 s' x tvl t e m H4 H9).\n  specialize (sub_domain_grows tvl el env0 x1 s s' AS H9 H6 H0) as eq1.\n  destruct H1.\n  destruct (H1 x0 t0 H8). easy.\n  unfold stack_wt. intros.\n  destruct (Nat.eq_dec x x0). subst.\n  apply Stack.mapsto_add1 in H5. inv H5.\n  inv H2. inv H7.\n  split.\n  apply cast_word_type with (s := s) (t := t); try easy.\n  split.\n  apply cast_type_wf with (s := s) (t := t); try easy.\n  apply cast_means_simple_type with (s := s) (t := t). easy.\n  apply Stack.add_3 in H5.\n  apply H3 in H5. easy. easy.\n  unfold stack_wt in *.\n  intros.\n  apply Stack.remove_3 in H4.\n  apply H3 in H4. easy.\n  unfold stack_wt.\n  intros. unfold add_nt_one in *.\n  destruct (Stack.find (elt:=Z * type) x s) eqn:eq1. destruct p.\n  destruct t2. inv H2.\n  apply H3 in H8. easy.\n  destruct t2.\n  apply H3 in H8. easy.\n  apply H3 in H8. easy.\n  apply H3 in H8. easy.\n  apply H3 in H8. easy.\n  destruct b0.\n  apply Stack.find_2 in eq1.\n  destruct (Nat.eq_dec x x0). subst.\n  apply Stack.mapsto_add1 in H8. inv H8.\n  apply H3 in eq1.\n  destruct eq1 as [X1 [X2 X3]].\n  split. constructor.\n  split. constructor. inv X2. inv H9. constructor. easy. easy.\n  constructor. inv X3. inv H9. constructor. easy.\n  apply Stack.add_3 in H8.\n  apply H3 in H8. easy. easy.\n  apply H3 in H8. easy.\n  apply H3 in H8. easy.\n  apply H3 in H8. easy.\n  apply H3 in H8. easy.\n  apply H3 in H8. easy.\nQed.\n\nLemma subtype_type_wf : forall D Q t t', subtype D Q t t' -> type_wf D t -> type_wf D t'.\nProof.\n  intros.\n  inv H. assumption.\n  inv H0. constructor.\n  constructor. assumption. assumption.\n  inv H0.\n  constructor.\n  inv H4.\n  assumption.\n  constructor.\n  inv H0.\n  inv H4. assumption.\n  inv H0. inv H3. constructor. constructor. assumption. assumption.\n  inv H0. inv H3. constructor. constructor. assumption. assumption.\n  inv H0. inv H3. constructor. constructor. assumption. assumption.\n  constructor. constructor.\n  constructor. constructor.\n  constructor. constructor.\nQed.\n\n(*\nLemma simple_type_var_fresh : forall x t, simple_type t -> var_fresh_type x t.\nProof.\n  intros. \n  induction t.\n  constructor.\n  constructor.\n  apply IHt. inv H. assumption.\n  constructor.\n  inv H. constructor. constructor. constructor.\n  apply IHt. assumption.\n  inv H. constructor. constructor. constructor.\n  apply IHt. assumption.\nQed.\n\nLemma step_exp_fresh : forall D F cx S H e cx' S' H' e',\n        stack_simple S ->\n        step D F cx S H e cx' S' H' (RExpr e') -> var_fresh cx e -> var_fresh cx' e'.\nProof.\nintros.\nremember (RExpr e') as ea.\ninduction H1; eauto.\ninv Heqea.\nconstructor.\napply Stack.find_2 in H1.\napply H0 in H1.\napply simple_type_var_fresh. assumption.\ninv Heqea. constructor. constructor.\ninv Heqea.\nQed.\n*)\n\nLemma nth_error_map_snd : forall (l : list (Z*type)) t i,\n                nth_error (map snd l) i = Some t -> (exists x, nth_error l i = Some (x,t)).\nProof.\n  intros. generalize dependent i.\n  induction l.\n  intros.\n  destruct i eqn:eq1.\n  simpl in *. inv H.\n  inv H.\n  intros.\n  destruct i.\n  simpl.\n  simpl in H.\n  destruct a.\n  exists z. inv H. easy.\n  simpl in H.\n  apply IHl in H.\n  simpl.\n  easy.\nQed.\n\nCheck InA.\n\nCheck Fields.elements_1.\n\nLemma weakening_bound : forall env x b t' t, Env.MapsTo x t env -> t <> TNat ->\n     well_bound_in env b -> well_bound_in (Env.add x t' env) b.\nProof.\n  intros. induction H1.\n  apply well_bound_in_num.\n  apply well_bound_in_var.\n  unfold Env.In in *.\n  unfold Env.Raw.PX.In in *.\n  assert (x = x0 \\/ x <> x0).\n  lia.\n  destruct H2. subst.\n  apply Env.mapsto_always_same with (v1 := t) in H1; try easy.\n  apply Env.add_2. assumption.\n  assumption.\nQed.\n\nLemma weakening_type_bound : forall env x t t' ta,  Env.MapsTo x ta env -> ta <> TNat ->\n         well_type_bound_in env t -> well_type_bound_in (Env.add x t' env) t.\nProof.\n  intros.\n  induction H1.\n  apply well_type_bound_in_nat.\n  apply well_type_bound_in_ptr.\n  apply IHwell_type_bound_in. easy.\n  apply well_type_bound_in_struct.\n  apply well_type_bound_in_array.\n  apply weakening_bound with (t := ta); try easy. \n  apply weakening_bound with (t := ta); try easy. \n  apply IHwell_type_bound_in. easy.\n  apply well_type_bound_in_ntarray.\n  apply weakening_bound with (t := ta); try easy. \n  apply weakening_bound with (t := ta); try easy. \n  apply IHwell_type_bound_in. easy.\nQed.\n\n(* ... for Preservation *)\n(*\nLemma weakening_bound : forall env x b t',\n     well_bound_in env b -> well_bound_in (Env.add x t' env) b.\nProof.\n  intros. induction H.\n  apply well_bound_in_num.\n  apply well_bound_in_var.\n  unfold Env.In in *.\n  unfold Env.Raw.PX.In in *.\n  assert (x = x0 \\/ x <> x0).\n  lia.\n  destruct H0.\n  apply Env.add_1. assumption.\n  destruct H.\n  exists x1.\n  apply Env.add_2. assumption.\n  assumption.\nQed.\n\nLemma weakening_type_bound : forall env x t t', \n         well_type_bound_in env t -> well_type_bound_in (Env.add x t' env) t.\nProof.\n  intros.\n  induction H.\n  apply well_type_bound_in_nat.\n  apply well_type_bound_in_ptr.\n  assumption.\n  apply well_type_bound_in_struct.\n  apply well_type_bound_in_array.\n  apply weakening_bound. assumption.\n  apply weakening_bound. assumption.\n  assumption.\n  apply well_type_bound_in_ntarray.\n  apply weakening_bound. assumption.\n  apply weakening_bound. assumption.\n  assumption.\nQed.\n\n\nLemma weakening : forall D F S H env m n t,\n    @well_typed D F S H env m (ELit n t) t ->\n    forall x t', @well_typed D F S H (Env.add x t' env) m (ELit n t) t.\nProof.\n  intros D F S H env m e t HWT.\n  inv HWT.\n  inv H6; eauto.\n  intros. apply TyLit.\n  apply weakening_type_bound. assumption.\n  apply (@WTStack D S H empty_scope e t t').\n  assumption.\n  apply H1.\nQed.\n*)\n\nLemma env_maps_add :\n  forall env x (t1 t2 : type),\n    Env.MapsTo x t1 (Env.add x t2 env) ->\n    t1 = t2.\nProof.\n  intros env x t1 t2 H.\n  assert (Env.E.eq x x); try reflexivity.\n  apply Env.add_1 with (elt := type) (m := env) (e := t2) in H0.\n  remember (Env.add x t2 env) as env'.\n  apply Env.find_1 in H.\n  apply Env.find_1 in H0.\n  rewrite H in H0.\n  inv H0.\n  reflexivity.\nQed.\n\n\n(* This theorem will be useful for substitution.\n\n   In particular, we can automate a lot of reasoning about environments by:\n   (1) proving that equivalent environments preserve typing (this lemma)\n   (2) registering environment equivalence in the Setoid framework (this makes proofs in (3) easier)\n   (3) proving a number of lemmas about which environments are equivalent (such as shadowing above)\n   (4) registering these lemmas in the proof automation (e.g. Hint Resolve env_shadow)\n\n   Then when we have a typing context that looks like:\n\n   H : (Env.add x0 t0 (Env.add x0 t1 env)) |- e : t\n   ================================================\n   (Env.add x0 t0 env) |- e : t\n\n   we can solve it simply by eauto.\n\n   during proof search, eauto should invoke equiv_env_wt which will leave a goal of\n   (Env.add x0 t0 (Env.add x0 t1 env)) == (Env.add x0 t0) and then subsequently apply the\n   shadowing lemma.\n *)\n\nLemma env_find_add1 : forall x (t : type) env,\n    Env.find x (Env.add x t env) = Some t.\nProof.\n  intros.\n  apply Env.find_1.\n  apply Env.add_1.\n  reflexivity.\nQed.\n\nLemma env_find1 : forall x env,\n    Env.find x env = None -> (forall (t : type), ~ Env.MapsTo x t env).\nProof.\n  intros.\n  unfold not.\n  intros.\n  apply Env.find_1 in H0.\n  rewrite -> H0 in H.\n  inv H.\nQed.\n\nLemma env_find2 : forall x env,\n    (forall (t : type), ~ Env.MapsTo x t env) -> Env.find x env = None.\nProof.\n  intros.\n  destruct (Env.find (elt := type) x env0) eqn:Hd.\n  - exfalso. eapply H.\n    apply Env.find_2 in Hd.\n    apply Hd.\n  - reflexivity.\nQed.\n\nLemma env_find_add2 : forall x y (t : type) env,\n    x <> y ->\n    Env.find x (Env.add y t env) = Env.find x env.\nProof.\n  intros.\n  destruct (Env.find (elt:=type) x env0) eqn:H1.\n  apply Env.find_1.\n  apply Env.add_2.\n  auto.\n  apply Env.find_2.\n  assumption.\n  apply env_find2.\n  unfold not.\n  intros.\n  eapply Env.add_3 in H0.\n  apply Env.find_1 in H0.\n  rewrite -> H1 in H0.\n  inversion H0.\n  auto.\nQed.\n\nLemma equiv_env_add : forall x t env1 env2,\n    Env.Equal (elt:=type) env1 env2 ->\n    Env.Equal (elt:=type) (Env.add x t env1) (Env.add x t env2).\nProof.\n  intros.\n  unfold Env.Equal.\n  intros.\n  destruct (Env.E.eq_dec x y).\n  rewrite e.\n  rewrite env_find_add1.\n  rewrite env_find_add1.\n  auto.\n  auto.\n  auto.\n  rewrite env_find_add2.\n  rewrite env_find_add2.\n  unfold Env.Equal in H.\n  apply H.\n  auto.\n  auto.\nQed.\n(* LEO: All of these proofs are horribly brittle :) *)\n\nLemma equiv_env_well_bound : forall b env1 env2,\n    Env.Equal env1 env2 -> well_bound_in env1 b -> well_bound_in env2 b.\nProof.\n  intros. induction H0;eauto.\n  apply well_bound_in_num.\n  apply well_bound_in_var.\n  unfold Env.In in *. unfold Env.Raw.PX.In in *.\n  specialize (@Env.mapsto_equal type x TNat env0 env2 H0 H) as eq1.\n  eauto.\nQed.\n\nLemma equiv_env_well_bound_type : forall t env1 env2,\n    Env.Equal env1 env2 -> well_type_bound_in env1 t -> well_type_bound_in env2 t.\nProof.\n  intros. induction H0;eauto.\n  apply well_type_bound_in_nat.\n  apply well_type_bound_in_ptr.\n  apply IHwell_type_bound_in.\n  assumption.\n  apply well_type_bound_in_struct.\n  apply well_type_bound_in_array.\n  apply (equiv_env_well_bound l env0 env2). 1 - 2: assumption.\n  apply (equiv_env_well_bound h env0 env2). 1 - 2: assumption.\n  apply IHwell_type_bound_in. assumption.\n  apply well_type_bound_in_ntarray.\n  apply (equiv_env_well_bound l env0 env2). 1 - 2: assumption.\n  apply (equiv_env_well_bound h env0 env2). 1 - 2: assumption.\n  apply IHwell_type_bound_in. assumption.\nQed.\n\nLemma equiv_env_warg: forall D Q H env1 env2 e t,\n    Env.Equal env1 env2 -> \n     well_typed_arg D Q H env1 e t -> \n     well_typed_arg D Q H env2 e t.\nProof.\n  intros. generalize dependent env2.\n  induction H1; eauto 20.\n  intros. eapply ArgLit. easy. easy. easy.\n  intros. apply ArgVar with (t' := t').\n  apply Env.mapsto_equal with (s1 := env1); try easy.\n  eapply equiv_env_well_bound_type. apply H3. apply H1. easy.\nQed.\n\n\nLemma equiv_env_wargs: forall D Q H AS env1 env2 es tvl,\n    Env.Equal env1 env2 -> \n     @well_typed_args D Q H env1 AS es tvl -> \n     @well_typed_args D Q H env2 AS es tvl.\nProof.\n  intros. generalize dependent env2.\n  induction H1; eauto 20.\n  intros. apply args_empty.\n  intros. eapply args_many.\n  eapply equiv_env_warg. apply H2. assumption.\n  apply IHwell_typed_args. easy.\nQed.\n\n(*\nLemma equiv_env_wt : forall D F S H Q env1 env2 m e t,\n    Env.Equal env1 env2 ->\n    @well_typed D F S H env1 Q m e t ->\n    @well_typed D F S H env2 Q m e t.\nProof.\n  intros.\n  generalize dependent env2.\n  induction H1; eauto 20.\n  - intros.\n    apply TyVar.\n    apply Env.mapsto_equal with (s1 := env0); try easy.\n  - intros. \n    eapply TyCall.\n    apply H0. easy.\n    eapply equiv_env_wargs. apply H3.\n    assumption.\n  - intros. \n    apply (TyStrlen env2 Q m x h l t).\n    apply Env.mapsto_equal with (s1 := env0); try easy.\n  - intros.\n    apply (TyLetStrlen env2 Q m x y e l h t).\n    apply Env.mapsto_equal with (s1 := env0); try easy.\n  - intros.\n    eapply TyLet.\n    apply IHwell_typed1.\n    assumption.\n    apply IHwell_typed2.\n    apply equiv_env_add.\n    auto.\n  - intros.\n    eapply TyMalloc.\n    apply (equiv_env_well_bound_type w env0 env2). 1 - 2 : assumption.\n  - intros.\n    eapply TyCast1; eauto.\n    apply (equiv_env_well_bound_type t env0 env2). 1 - 2 : assumption.\n  - intros.\n    eapply TyCast2; eauto.\n    apply (equiv_env_well_bound_type t env0 env2). 1 - 2 : assumption.\n  - intros.\n    eapply TyDynCast1; eauto.\n    apply (equiv_env_well_bound_type (TPtr Checked (TArray x y t)) env0 env2). 1 - 2 : assumption.\n  - intros.\n    eapply TyDynCast2; eauto.\n    apply (equiv_env_well_bound_type (TPtr Checked (TArray x y t)) env0 env2). 1 - 2 : assumption.\n  - intros.\n    eapply TyDynCast3; eauto.\n    apply (equiv_env_well_bound_type (TPtr Checked (TNTArray x y t)) env0 env2). 1 - 2 : assumption.\n  - intros.\n    eapply TyIf; eauto.\n    apply Env.find_2.\n    apply Env.find_1 in H0.\n    unfold Env.Equal in H5.\n    rewrite <- H5. assumption.\nQed.\n*)\nLemma env_shadow : forall env x (t1 t2 : type),\n    Env.Equal (Env.add x t2 (Env.add x t1 env)) (Env.add x t2 env).\nProof.\n  intros env x t1 t2 y.\n  destruct (Nat.eq_dec x y) eqn:Eq; subst; eauto.\n  - do 2 rewrite env_find_add1; auto.\n  - repeat (rewrite env_find_add2; eauto).\nQed.\n\nLemma env_shadow_eq : forall env0 env1 x (t1 t2 : type),\n    Env.Equal env0 (Env.add x t2 env1) ->\n    Env.Equal (Env.add x t1 env0) (Env.add x t1 env1).\nProof.\n  intros env0 env1 x t1 t2 H y.\n  destruct (Nat.eq_dec x y) eqn:Eq; subst; eauto.\n  - repeat (rewrite env_find_add1; eauto).\n  - rewrite env_find_add2; eauto.\n    specialize (H y).\n    rewrite env_find_add2 in H; eauto.\n    rewrite env_find_add2; eauto.\nQed.\n\nLemma env_neq_commute : forall x1 x2 (t1 t2 : type) env,\n    ~ Env.E.eq x1 x2 ->\n    Env.Equal (Env.add x1 t1 (Env.add x2 t2 env)) (Env.add x2 t2 (Env.add x1 t1 env)).\nProof.\n  intros x1 x2 t1 t2 env Eq x.\n  destruct (Nat.eq_dec x x1) eqn:Eq1; destruct (Nat.eq_dec x x2) eqn:Eq2; subst; eauto;\n  repeat (try rewrite env_find_add1; auto; try rewrite env_find_add2; auto).    \nQed.\n\nLemma env_neq_commute_eq : forall x1 x2 (t1 t2 : type) env env',\n    ~ Env.E.eq x1 x2 -> Env.Equal env' (Env.add x2 t2 env) ->\n    Env.Equal (Env.add x1 t1 env') (Env.add x2 t2 (Env.add x1 t1 env)).\nProof.\n  intros x1 x2 t1 t2 env env' NEq Eq x.\n  destruct (Nat.eq_dec x x1) eqn:Eq1; destruct (Nat.eq_dec x x2) eqn:Eq2; subst; eauto.\n  - unfold Env.E.eq in *; exfalso; eapply NEq; eauto.\n  - repeat (try rewrite env_find_add1 in *; auto; try rewrite env_find_add2 in *; auto).\n  - specialize (Eq x2); repeat (try rewrite env_find_add1 in *; auto; try rewrite env_find_add2 in *; auto).\n  - specialize (Eq x); repeat (try rewrite env_find_add1 in *; auto; try rewrite env_find_add2 in *; auto).\nQed.\n\nCreate HintDb Preservation.\n\n\n(*\nInductive stack_wf D Q H : env -> stack -> Prop :=\n  | WFS_Stack : forall env s,\n     (forall x t,\n         Env.MapsTo x t env ->\n         exists v t' t'',\n           cast_type_bound s t t' /\\\n           subtype D Q t'' t' /\\\n            Stack.MapsTo x (v, t'') s /\\\n            @well_typed_lit D H empty_scope v t'')\n   /\\ (forall x v t,\n             Stack.MapsTo x (v, t) s -> \n                   @well_typed_lit D H empty_scope v t    \n          -> exists t' t'',\n                @Env.MapsTo type x t' env /\\ cast_type_bound s t' t''\n                   /\\ subtype D Q t t'')\n ->\n     stack_wf D Q H env s.\n*)\nLemma values_are_nf : forall D F H s e,\n    value D e ->\n    ~ exists  m s' H' r, @reduce D F s H e m s' H' r.\nProof.\n  intros D F H s e Hv contra.\n  inv Hv.\n  destruct contra as [m [ s' [ H' [ r contra ] ] ] ].\n  inv contra; destruct E; inversion H4; simpl in *; subst; try congruence.\n  inv H5. inv H5. inv H5.\nQed.\n\nLemma lit_are_nf : forall D F H s n t,\n    ~ exists H'  s' m r, @reduce D F s H (ELit n t) m s' H' r.\nProof.\n  intros D F s H n t contra.\n  destruct contra as [H' [ s' [ m [ r contra ] ] ] ].\n  inv contra; destruct E; inversion H2; simpl in *; subst; try congruence.\nQed.\n\n\nLemma subtype_ptr : forall D Q m t t', subtype D Q (TPtr m t) t' -> exists ta, t' = TPtr m ta.\nProof.\n  intros. inv H. exists t. easy.\n  exists (TArray l h t). easy.\n  exists t0. easy.\n  exists t0. easy.\n  exists (TArray l' h' t0). easy.\n  exists (TArray l' h' t0). easy.\n  exists (TNTArray l' h' t0). easy.\n  exists TNat. easy.\n  exists (TArray l h TNat). easy.\nQed.\n\nLemma cast_ptr_left : forall s t1 m t2, cast_type_bound s t1 (TPtr m t2) -> exists ta, t1 = (TPtr m ta).\nProof.\n  intros. inv H. exists t. easy.\nQed.\n\nLemma gen_arg_env_has_old : forall tvl env env0, gen_arg_env env tvl env0\n          -> (forall x, Env.In x env -> Env.In x env0).\nProof.\n  induction tvl.\n  intros;simpl.\n  inv H. easy.\n  intros;simpl. inv H.\n  apply IHtvl with (x := x) in H5.\n  destruct H5.\n  destruct (Nat.eq_dec x x0).\n  subst.\n  exists t.\n  apply Env.add_1. easy.\n  exists x1.\n  apply Env.add_2. lia.\n  easy.\n  easy.\nQed.\n\nLemma gen_arg_env_has_all : forall tvl env env0, gen_arg_env env tvl env0\n          -> (forall x t, Env.MapsTo x t env0 -> Env.MapsTo x t env \\/ In (x,t) tvl).\nProof.\n  intros. induction H. left. easy.\n  destruct (Nat.eq_dec x x0). subst.\n  apply Env.mapsto_add1 in H0. subst.\n  right. simpl. left. easy.\n  apply Env.add_3 in H0.\n  apply IHgen_arg_env in H0. destruct H0. left. easy.\n  right. simpl. right. easy. lia.\nQed.\n\nLemma stack_consist_trans : forall S S' env tvl es AS,\n    sub_domain env S ->\n    (forall a, In a tvl -> ~ Env.In (fst a) env) ->\n    length tvl = length es ->\n    eval_el AS S tvl es S' -> stack_consistent_grow S S' env.\nProof.\n  intros. induction H2.\n  unfold stack_consistent_grow.\n  intros. easy.\n  unfold stack_consistent_grow.\n  intros.\n  assert ((forall a : Env.key * type,\n             In a tvl -> ~ Env.In (elt:=type) (fst a) env0)).\n  intros.\n  apply H0. simpl. right. easy.\n  assert (length tvl = length es). simpl in *.\n  inv H1. easy.\n  specialize (IHeval_el H5 H7 H8).\n  unfold stack_consistent_grow in *.\n  specialize (IHeval_el x0 v t0 H4 H5 H6).\n  destruct (Nat.eq_dec x0 x). subst.\n  assert (In (x,t) ((x, t) :: tvl)). simpl. left. easy.\n  apply H0 in H9.\n  simpl in *. contradiction.\n  apply Stack.add_2. lia. easy.\nQed.\n\nLemma well_typed_arg_same_length : forall D Q H env AS es tvl,\n         @well_typed_args D Q H env AS es tvl -> length es = length tvl.\nProof.\n  intros. induction H0. easy.\n  simpl. rewrite IHwell_typed_args. easy.\nQed.\n\nLemma gen_arg_env_grow_1 : forall tvl env env', gen_arg_env env tvl env' -> \n      (forall a, In a tvl -> ~ Env.In (fst a) env) ->\n      (forall x t, Env.MapsTo x t env -> Env.MapsTo x t env').\nProof.\n  induction tvl; intros;simpl.\n  inv H. easy.\n  inv H.\n  specialize (IHtvl env0 env'0 H6).\n  assert ((forall a : var * type,\n         In a tvl -> ~ Env.In (elt:=type) (fst a) env0)).\n  intros.\n  apply H0. simpl. right. easy.\n  specialize (IHtvl H).\n  apply IHtvl in H1 as eq1.\n  destruct (Nat.eq_dec x x0).\n  subst.\n  specialize (H0 (x0,t0)).\n  assert (In (x0, t0) ((x0, t0) :: tvl)).\n  simpl. left. easy.\n  apply H0 in H2.\n  simpl in *.\n  assert (Env.In (elt:=type) x0 env0).\n  exists t. easy. contradiction.\n  apply Env.add_2. lia.\n  easy.\nQed.\n\nLemma gen_arg_env_grow_2 : forall tvl env env', gen_arg_env env tvl env' -> \n      (forall a, In a tvl -> ~ Env.In (fst a) env) ->\n      (forall x t, Env.MapsTo x t env' -> Env.MapsTo x t env \\/ In (x,t) tvl).\nProof.\n  induction tvl; intros;simpl.\n  inv H. left. easy.\n  inv H.\n  destruct (Nat.eq_dec x x0). subst.\n  apply Env.mapsto_add1 in H1. subst.\n  right. left. easy.\n  apply Env.add_3 in H1; try lia.\n  assert ((forall a : var * type,\n         In a tvl -> ~ Env.In (elt:=type) (fst a) env0)).\n  intros.\n  apply H0. simpl. right. easy.\n  specialize (IHtvl env0 env'0 H6 H x t H1).\n  destruct IHtvl. left. easy.\n  right. right. easy.\nQed.\n\nLemma stack_grow_cast_same : forall env S S' b b', well_bound_in env b ->\n        sub_domain env S -> stack_consistent_grow S S' env ->\n              cast_bound S b = Some b' -> cast_bound S' b = Some b'.\nProof.\n  intros. unfold cast_bound in *.\n  destruct b. assumption.\n  destruct (Stack.find (elt:=Z * type) v S) eqn:eq1. destruct p.\n  unfold stack_consistent_grow in *.\n  apply Stack.find_2 in eq1. inv H.\n  apply H1 in eq1; try easy.\n  destruct (Stack.find (elt:=Z * type) v S') eqn:eq2.\n  destruct p.\n  apply Stack.find_2 in eq2.\n  apply (@Stack.mapsto_always_same (Z * type) v (z0,t)) in eq2; try easy.\n  inv eq2. easy.\n  apply Stack.find_1 in eq1.\n  rewrite eq1 in eq2. easy.\n  exists TNat. easy. inv H2.\nQed.\n\nLemma stack_grow_cast_type_same : forall env S S' t t', well_type_bound_in env t ->\n        sub_domain env S -> stack_consistent_grow S S' env ->\n              cast_type_bound S t t' -> cast_type_bound S' t t'.\nProof.\n  intros.\n  induction H2. constructor.\n  constructor.\n  apply IHcast_type_bound. inv H. easy.\n  inv H.\n  constructor.\n  apply (stack_grow_cast_same env0 S); try easy.\n  apply (stack_grow_cast_same env0 S); try easy.\n  apply IHcast_type_bound. easy.\n  inv H.\n  constructor.\n  apply (stack_grow_cast_same env0 S); try easy.\n  apply (stack_grow_cast_same env0 S); try easy.\n  apply IHcast_type_bound. easy.\n  apply cast_type_bound_struct.\nQed.\n\nLemma nth_error_empty_none {A:Type}: forall n, @nth_error A [] n = None.\nProof.\n  induction n; intros;simpl.\n  easy. easy.\nQed.\n\nLemma cast_subtype_same : forall t1 D Q S t1' t2 t2', subtype D Q t1 t2 -> \n    cast_type_bound S t1 t1' -> cast_type_bound S t2 t2' ->\n    (forall x n ta, Theta.MapsTo x GeZero Q -> Stack.MapsTo x (n,ta) S -> 0 <= n) ->\n    subtype D Q t1' t2'.\nProof.\n  induction t1; intros;simpl.\n  inv H0. inv H. inv H1. constructor.\n  inv H0.\n  inv H. inv H1.\n  specialize (cast_type_bound_same S t1 t' t'0 H6 H4) as eq3. subst.\n  constructor. inv H5. inv H8.\n  inv H1. inv H8. unfold cast_bound in *. inv H7. inv H10.\n  specialize (cast_type_bound_same S t1 t' t'1 H6 H11) as eq3. subst.\n  apply SubTyBot.\n  apply cast_word_type in H6; try easy. constructor. easy. constructor. easy.\n  inv H8. inv H1. inv H9. unfold cast_bound in *.\n  destruct (Stack.find (elt:=Z * type) x S) eqn:eq1. destruct p. inv H8. inv H11.\n  specialize (cast_type_bound_same S t1 t' t'1 H6 H12) as eq3. subst.\n  apply SubTyBot.\n  apply cast_word_type in H6; try easy. constructor.\n  apply Stack.find_2 in eq1.\n  apply H2 in eq1; try easy. lia. constructor. easy.\n  inv H8.\nAdmitted.\n\nDefinition bound_eval (S:stack) (b:bound) :=\n  match b with Num n => Some n\n           | Var x n => match Stack.find x S with Some (m,t) => Some (m + n)\n                                               | None => None\n                        end\n  end.\n\n\nLemma well_bound_var_in_as : forall AS x z env, \n     ~ Env.In x env ->\n      well_bound_in env (subst_bounds (Var x z) AS) ->\n     (exists b, In (x,b) AS).\nProof.\n  induction AS; intros; simpl in *.\n  inv H0. assert (Env.In x env0).\n  exists TNat. easy. contradiction.\n  destruct a.\n  destruct (var_eq_dec x v). subst.\n  exists b. left. easy.\n  specialize (IHAS x z env0 H H0). destruct IHAS. \n  exists x0. right. easy.\nQed.\n\n\nLemma cast_bound_in_env_same : forall AS S env0 v z, \n    sub_domain env0 S ->\n            (forall a, In a AS -> ~ Env.In (fst a) env0) -> Env.In v env0 ->\n              cast_bound S (subst_bounds (Var v z) AS) = cast_bound S (Var v z).\nProof.\n  induction AS; intros;simpl.\n  unfold sub_domain in *.\n  specialize (H v H1). destruct H.\n  apply Stack.find_1 in H. rewrite H. easy.\n  destruct a.\n  destruct (var_eq_dec v k). subst.\n  assert (In (k,b) ((k, b) :: AS)).\n  simpl. left. easy.\n  apply H0 in H2. simpl in *. contradiction.\n  assert ((forall a : Env.key * bound,\n        In a AS -> ~ Env.In (elt:=type) (fst a) env0)).\n  intros. apply H0. simpl. right. easy.\n  rewrite IHAS with (env0 := env0); try easy.\nQed.\n\nLemma nth_no_appear {A B:Type} : forall x v AS,\n     (forall n n' (a b: A * B), n <> n' -> nth_error ((x,v)::AS) n = Some a -> nth_error ((x,v)::AS) n' = Some b -> fst a <> fst b) ->\n     (forall y w, In (y,w) AS -> x <> y).\nProof.\n  intros.\n  apply In_nth_error in H0. destruct H0.\n  specialize (H Nat.zero (S x0) (x,v) (y,w)).\n  assert (Nat.zero <> S x0).\n  intros R. easy.\n  apply H in H1; try easy.\nQed.\n\nLemma subst_type_no_effect: forall AS v z,\n     (forall a, In a AS -> fst a <> v) -> subst_bounds (Var v z) AS = Var v z.\nProof.\n  induction AS;intros;simpl.\n  easy.\n  destruct a.\n  specialize (H (v0,b)) as eq1.\n  assert (In (v0, b) ((v0, b) :: AS)). simpl. left. easy.\n  apply eq1 in H0.\n  destruct (var_eq_dec v v0). subst. easy.\n  assert (forall a : var * bound, In a (AS) -> fst a <> v).\n  intros. apply H. simpl. right. easy.\n  apply IHAS with (z := z) in H1. easy.\nQed.\n\nLemma subst_bounds_only_one: forall AS env v b z, In (v,b) AS -> \n    (forall a, In a AS -> ~ Env.In (fst a) env) ->\n     (forall x b, In (x,b) AS -> (match b with Num v => True | Var y v => @Env.In (type) y env end)) ->\n    (forall n n' a b, n <> n' -> nth_error AS n = Some a -> nth_error AS n' = Some b -> fst a <> fst b) ->\n       subst_bounds (Var v z) AS = subst_bound (Var v z) v b.\nProof.\n  induction AS;intros.\n  easy. simpl.\n  destruct a. simpl in H. destruct H. inv H.\n  destruct (var_eq_dec v v).\n  destruct b.\n   assert (forall AS z, subst_bounds (Num z) AS = Num z).\n   {\n    intros. induction AS0. simpl. easy.\n    simpl. destruct a. easy.\n   }\n  rewrite H. easy.\n  assert (forall a, In a ((v, Var v0 z0) :: AS) -> fst a <> v0).\n  {\n    intros. simpl in *. intros R. destruct H. destruct a. inv H.\n    simpl in *.\n    specialize (H0 (k,Var k z0)).\n    specialize (H1 k (Var k z0)).\n    assert ((k, Var k z0) = (k, Var k z0) \\/ In (k, Var k z0) AS).\n    left. easy. apply H0 in H as eq1. apply H1 in H. simpl in *. contradiction.\n    specialize (H0 a).\n    assert ((v, Var v0 z0) = a \\/ In a AS). right. easy.\n    apply H0 in H3.\n    specialize (H1 v (Var v0 z0)).\n    assert ((v, Var v0 z0) = (v, Var v0 z0) \\/ In (v, Var v0 z0) AS). left. easy.\n    apply H1 in H4. destruct a. simpl in *. subst. contradiction.\n  }\n  rewrite subst_type_no_effect; try easy.\n  intros. apply H. simpl. right. easy. easy.\n  destruct (var_eq_dec v k). subst.\n  specialize (nth_no_appear k b0 AS H2) as eq1.\n  apply eq1 in H. easy.\n  specialize (IHAS env0 v b z H).\n  assert ((forall a : Env.key * bound,\n        In a AS -> ~ Env.In (elt:=type) (fst a) env0)).\n  intros. apply H0. simpl. right. easy.\n  assert ((forall (x : Env.key) (b : bound),\n        In (x, b) AS ->\n        match b with\n        | Num _ => True\n        | Var y _ => Env.In (elt:=type) y env0\n        end)).\n  intros. apply (H1 x). simpl. right. easy. \n  assert ((forall (n n' : nat) (a b : Env.key * bound),\n        n <> n' ->\n        nth_error AS n = Some a ->\n        nth_error AS n' = Some b -> fst a <> fst b)).\n  intros.\n  specialize (H2 (S n0) (S n')).\n  simpl in *.\n  apply H2. lia. easy. easy.\n  specialize (IHAS H3 H4 H5).\n  rewrite IHAS.\n  unfold subst_bound.\n  easy.\nQed.\n\n\nLemma cast_as_same_bound : forall b S S' env AS b',\n    sub_domain env S -> stack_consistent_grow S S' env ->\n    well_bound_in env (subst_bounds b AS) ->\n    (forall a, In a AS -> ~ Env.In (fst a) env) ->\n     (forall x b, In (x,b) AS -> (match b with Num v => True | Var y v => Env.In y env end)) ->\n     (forall a, In a AS -> Stack.In (fst a) S') ->\n     (forall x b na ta, In (x,b) AS -> Stack.MapsTo x (na,ta) S' -> bound_eval S b = Some na) ->\n    (forall n n' a b, n <> n' -> nth_error AS n = Some a -> nth_error AS n' = Some b -> fst a <> fst b) ->\n      cast_bound S (subst_bounds b AS) = Some b' -> cast_bound S' b = Some b'.\nProof.\n  intros. simpl in *. destruct b.\n   assert (forall AS, subst_bounds (Num z) AS = Num z).\n   {\n    intros. induction AS0. simpl. easy.\n    simpl. destruct a. easy.\n   }\n   rewrite H8 in H7. easy.\n   specialize (Classical_Prop.classic (Env.In v env0)) as eq1.\n   destruct eq1.\n   rewrite cast_bound_in_env_same with (env0 := env0) in H7.\n   unfold stack_consistent_grow in *.\n   rewrite <- H7.\n   unfold cast_bound.\n   destruct (Stack.find (elt:=Z * type) v S) eqn:eq1. destruct p.\n   apply Stack.find_2 in eq1.\n   apply H0 in eq1; try easy.\n   apply Stack.find_1 in eq1. rewrite eq1. easy.\n   unfold sub_domain in *.\n   apply H in H8.\n   destruct H8. apply Stack.find_1 in H8. rewrite eq1 in H8. easy.\n   easy. easy. easy.\n   specialize (well_bound_var_in_as AS v z env0 H8 H1) as eq1.\n   destruct eq1.\n   rewrite <- H7.\n   apply H4 in H9 as eq2.\n   destruct eq2. simpl in *. destruct x0.\n   apply H5 with (b := x) in H10 as eq3; try easy.\n   unfold bound_eval in eq3.\n   apply Stack.find_1 in H10.\n   rewrite H10.\n   rewrite subst_bounds_only_one with (env := env0) (b := x); try easy.\n   unfold subst_bound.\n   destruct (var_eq_dec v v).\n   destruct x. inv eq3. easy.\n   unfold cast_bound.\n   destruct (Stack.find (elt:=Z * type) v0 S) eqn:eq1. destruct p. inv eq3.\n   assert ((z + (z2 + z1)) = (z + z1 + z2)) by lia.\n   rewrite H11. easy. inv eq3. easy.\nQed.\n\nLemma cast_as_same : forall t S S' env AS t',\n    sub_domain env S -> stack_consistent_grow S S' env ->\n     well_type_bound_in env (subst_type AS t) -> \n    (forall a, In a AS -> ~ Env.In (fst a) env) ->\n     (forall x b, In (x,b) AS -> (match b with Num v => True | Var y v => Env.In y env end)) ->\n     (forall a, In a AS -> Stack.In (fst a) S') ->\n     (forall x b na ta, In (x,b) AS -> Stack.MapsTo x (na,ta) S' -> bound_eval S b = Some na) ->\n    (forall n n' a b, n <> n' -> nth_error AS n = Some a -> nth_error AS n' = Some b -> fst a <> fst b) ->\n     cast_type_bound S (subst_type AS t) t' ->\n     cast_type_bound S' t t'.\nProof.\n   induction t; intros; simpl.\n   assert (forall AS, subst_type AS TNat = TNat).\n   {\n    intros. induction AS0. simpl. easy.\n    simpl. easy.\n   }\n   rewrite H8 in H7. inv H7. constructor.\n   simpl in *. \n   inv H7. constructor. apply IHt with (S := S) (env := env0) (AS := AS); try easy.\n   inv H1. easy.\n   assert (forall AS, subst_type AS (TStruct s)  = (TStruct s) ).\n   {\n    intros. induction AS0. simpl. easy.\n    simpl. easy.\n   }\n   rewrite H8 in H7. inv H7. constructor.\n   simpl in *. inv H1. inv H7.\n   constructor.\n   rewrite cast_as_same_bound with (S := S) (env := env0) (AS := AS) (b' := l'); try easy.\n   rewrite cast_as_same_bound with (S := S) (env := env0) (AS := AS) (b' := h'); try easy.\n   apply IHt with (S := S) (AS := AS) (env := env0); try easy.\n   simpl in *. inv H1. inv H7.\n   constructor.\n   rewrite cast_as_same_bound with (S := S) (env := env0) (AS := AS) (b' := l'); try easy.\n   rewrite cast_as_same_bound with (S := S) (env := env0) (AS := AS) (b' := h'); try easy.\n   apply IHt with (S := S) (AS := AS) (env := env0); try easy.\nQed.\n\n\nLemma stack_wf_out : forall tvl es D Q H env AS S S',\n     sub_domain env S -> stack_wt D S -> stack_wf D Q env S ->\n     env_wt D env -> stack_heap_consistent D Q H S ->\n     (forall a, In a tvl -> ~ Env.In (fst a) env) ->\n     (forall x n t ta, Env.MapsTo x t env -> Stack.MapsTo x (n,ta) S ->\n           (exists t', cast_type_bound S t t' /\\ subtype D Q ta t')) ->\n     (forall x n ta, Theta.MapsTo x GeZero Q -> Stack.MapsTo x (n,ta) S -> 0 <= n) ->\n     (forall n n' a b, n <> n' -> nth_error tvl n = Some a -> nth_error tvl n' = Some b -> fst a <> fst b) ->\n     (forall e, In e es -> (exists n t, e = ELit n t\n                 /\\ word_type t /\\ type_wf D t /\\ simple_type t) \\/ (exists y, e = EVar y)) ->\n     @well_typed_args D Q H env AS es tvl ->\n     eval_el AS S tvl es S' ->\n       (forall x t, In (x,t) tvl ->\n         exists v t',\n           cast_type_bound S (subst_type AS t) t' /\\\n            Stack.MapsTo x (v,t') S' /\\\n            @well_typed_lit D Q H empty_scope v t').\nProof.\n  intros.\n  induction H11. inv H10. intros.\n  inv H12.\n  intros. inv H10.\n  assert ((forall a : Env.key * type,\n             In a tvl ->\n             ~ Env.In (elt:=type) (fst a) env0)).\n  intros. apply H5. simpl. right. easy.\n  assert ((forall (n n' : nat) (a b : Env.key * type),\n             n <> n' ->\n             nth_error tvl n = Some a ->\n             nth_error tvl n' = Some b -> fst a <> fst b)).\n  intros.\n  specialize (H8 (S n0) (S n') a b).\n  simpl in H8. apply H8; try easy. lia.\n  assert ((forall e : expression,\n             In e es ->\n             (exists (n : Z) (t : type),\n                e = ELit n t /\\ word_type t /\\ type_wf D t /\\ simple_type t) \\/\n             (exists y : var, e = EVar y))).\n  intros. apply H9. simpl. right. easy.\n  specialize (IHeval_el H0 H1 H2 H4 H10 H6 H7 H14 H15 H22). clear H14. clear H15.\n  simpl in H12. destruct H12. inv H12.\n  inv H19. inv H11.\n  exists n.\n  apply simple_type_means_cast_same with (s := s) in H12 as eq1.\n  exists (subst_type AS t).\n  split. easy. \n  split.\n  apply (cast_type_bound_same s (subst_type AS t) (subst_type AS t) t' eq1) in H20.\n  rewrite H20. apply Stack.add_1. easy.\n  apply subtype_well_type with (t := t'0); try easy.\n  assert (In (ELit n t'0) (ELit n t'0 :: es)). simpl. left. easy.\n  apply H9 in H11. destruct H11. destruct H11 as [na [ta [X1 [X2 [X3 X4]]]]].\n  inv X1. easy.\n  destruct H11. inv H11.\n  apply subtype_type_wf in H15. easy.\n  assert (In (ELit n t'0) (ELit n t'0 :: es)). simpl. left. easy.\n  apply H9 in H11. destruct H11. destruct H11 as [na [ta [X1 [X2 [X3 X4]]]]].\n  inv X1. easy.\n  destruct H11. inv H11.\n  inv H11.\n  assert (well_type_bound_in env0 t'0).\n  apply H3 with (x := x0); easy.\n  specialize (gen_cast_type_bound_same env0 s t'0 H11 H0) as eq1.\n  destruct eq1.\n  apply cast_means_simple_type in H16 as eq1.\n  apply cast_means_simple_type in H23 as eq2.\n  specialize (H6 x0 n t'0 t'1 H12 H21) as eq3.\n  destruct eq3. destruct H17.\n  specialize (cast_type_bound_same s t'0 x1 x2 H16 H17) as eq3. subst.\n  unfold stack_wt in H1.\n  specialize (cast_subtype_same t'0 D Q s x2 (subst_type AS t) t' H15 H16 H23 H7) as eq3.\n  assert (word_type x2).\n  apply cast_word_type in H16; try easy.\n  specialize (H3 x0 t'0 H12). easy.\n  inv H19. inv eq3. inv H18. inv H23. inv H16.\n  exists n. exists TNat.\n  split. easy.\n  split. apply Stack.add_1. easy.  apply TyLitInt.\n  specialize (subtype_trans D Q t'1 t' m w H18 eq3) as eq4.\n  exists n. exists t'. split. easy.\n  split. apply Stack.add_1. easy.\n  unfold stack_wf in *.\n  specialize (H2 x0 t'0 H12).\n  destruct H2 as [v [ta [tb [X1 [X2 X3]]]]].\n  apply Stack.mapsto_always_same with (v1 := (n, t'1)) in X3 as eq6; try easy. inv eq6.\n  apply H1 in X3 as X4. destruct X4 as [X3a [X3b X3c]].\n  apply subtype_well_type with (t := tb); try easy.\n  apply subtype_type_wf with (Q := Q) (t' := t')  in X3b. easy. easy.\n  unfold stack_heap_consistent in *.\n  apply H4 with (x := x0); try easy.\n  simpl in *.\n  specialize (IHeval_el H12).\n  destruct IHeval_el as [v [ta [X1 [X2 X3]]]].\n  exists v. exists ta.\n  split. easy. split.\n  apply nth_no_appear with (y := x) (w := t) in H8.\n  apply Stack.add_2. easy. easy.\n  easy. easy.\nQed.\n\n\nLemma well_type_args_well_bound : forall D Q H env AS es tvl,\n   @well_typed_args D Q H env AS es tvl -> \n   (forall x t, In (x,t) tvl -> well_type_bound_in env (subst_type AS t)).\nProof.\n  intros. induction H0.\n  simpl in *. easy. simpl in *.\n  destruct H1.\n  inv H1. inv H0.\n  apply simple_type_well_bound with (env := env0) in H1. easy.\n  easy.\n  apply IHwell_typed_args. easy.\nQed.\n\nLemma as_well_bound : forall AS D Q H env tvl es,\n   @well_typed_args D Q H env AS es tvl -> \n     get_dept_map tvl es = Some AS -> \n    (forall x b, In (x,b) AS -> (match b with Num v => True | Var y v => Env.In y env end)).\nProof.\nAdmitted.\n\nLemma as_not_in_env : forall AS tvl es env,\n     get_dept_map tvl es = Some AS -> length tvl = length es -> \n    (forall a, In a tvl -> ~ @Env.In type (fst a) env) -> (forall a, In a AS -> ~ @Env.In type (fst a) env).\nProof.\nAdmitted.\n\nLemma as_stack_in : forall AS tvl es S S',\n     get_dept_map tvl es = Some AS -> eval_el AS S tvl es S' ->\n    (forall a, In a AS -> Stack.In (fst a) S').\nProof.\nAdmitted.\n\nLemma as_stack_in_2 : forall AS tvl es S S',\n     get_dept_map tvl es = Some AS -> eval_el AS S tvl es S' ->\n    (forall a, In a AS -> Stack.In (fst a) S') -> \n(forall x b na ta, In (x,b) AS -> Stack.MapsTo x (na,ta) S' -> bound_eval S b = Some na).\nProof.\nAdmitted.\n\nLemma as_diff : forall AS tvl es,\n     get_dept_map tvl es = Some AS -> length tvl = length es ->\n   (forall n n' a b, n <> n' -> nth_error tvl n = Some a -> nth_error tvl n' = Some b -> fst a <> fst b) ->\n   (forall n n' a b, n <> n' -> nth_error AS n = Some a -> nth_error AS n' = Some b -> fst a <> fst b).\nProof.\nAdmitted.\n\n\nLemma stack_wf_core : forall D Q env S, stack_wf D Q env S ->\n    (forall x n t ta, Env.MapsTo x t env -> Stack.MapsTo x (n,ta) S ->\n           (exists t', cast_type_bound S t t' /\\ subtype D Q ta t')).\nProof.\n  intros.\n  unfold stack_wf in *.\n  specialize (H x t H0).\n  destruct H as [v [t' [t'' [X1 [X2 X3]]]]].\n  exists t'. split. easy.\n  apply Stack.mapsto_always_same with (v1 := (v,t'')) in H1; try easy. inv H1.\n  easy.\nQed.\n\nLemma stack_tvl_has : forall tvl AS S es S', eval_el AS S tvl es S'\n        -> (forall x t, In (x,t) tvl -> exists n ta, Stack.MapsTo x (n,ta) S').\nProof.\n  intros. induction H.\n  simpl in *. easy.\n  simpl in H0. destruct H0.\n  inv H0. exists n. exists t'. apply Stack.add_1. easy.\n  destruct (Nat.eq_dec x x0). subst.\n  exists n. exists t'. apply Stack.add_1. easy.\n  apply IHeval_el in H0.\n  destruct H0. destruct H0.\n  exists x1. exists x2.\n  apply Stack.add_2. lia. easy.\nQed.\n\n\nLemma stack_wf_trans :\n   forall D Q H env env' S S' AS tvl es,\n   stack_wt D S -> sub_domain env S -> stack_wf D Q env S -> stack_heap_consistent D Q H S -> env_wt D env ->\n     (forall a, In a tvl -> ~ Env.In (fst a) env) ->\n     (forall n n' a b, n <> n' -> nth_error tvl n = Some a -> nth_error tvl n' = Some b -> fst a <> fst b) ->\n     (forall x t, Env.MapsTo x t env' -> Env.MapsTo x t env \\/ In (x,t) tvl) ->\n     (forall x n ta, Theta.MapsTo x GeZero Q -> Stack.MapsTo x (n,ta) S -> 0 <= n) ->\n     (forall e, In e es -> (exists n t, e = ELit n t\n                 /\\ word_type t /\\ type_wf D t /\\ simple_type t) \\/ (exists y, e = EVar y)) ->\n     @well_typed_args D Q H env AS es tvl ->\n     get_dept_map tvl es = Some AS ->\n     eval_el AS S tvl es S' ->\n      stack_wf D Q env' S'.\nProof.\n  intros.\n  assert (length tvl = length es) as eq1.\n  rewrite (well_typed_args_same_length D Q H env0 AS es tvl); try easy.\n  specialize (stack_consist_trans S S' env0 tvl es AS H1 H5 eq1 H12) as eq2.\n  specialize (stack_wf_core D Q env0 S H2) as eq3.\n  specialize (stack_wf_out tvl es D Q H env0 AS S S' H1 H0 H2 H4 H3 H5 eq3 H8 H6 H9 H10 H12) as eq4.\n  unfold stack_wf in *.\n  intros.\n  apply H7 in H13.\n  destruct H13. apply H2 in H13 as eq5. destruct eq5 as [v [ta [tb [X1 [X2 X3]]]]].\n  exists v. exists ta. exists tb.\n  split. apply stack_grow_cast_type_same with (env := env0) (S := S); try easy.\n  unfold env_wt in *.\n  apply H4 in H13. easy. split. easy.\n  unfold stack_consistent_grow in *.\n  apply eq2; try easy. exists t. easy.\n  apply eq4 in H13 as eq5.\n  destruct eq5 as [v [ta [X1 [X2 X3]]]].\n  exists v. exists ta. exists ta.\n  split.\n  apply cast_as_same with (S := S) (AS := AS) (env := env0); try easy.\n  apply (well_type_args_well_bound D Q H env0 AS es tvl) with (x := x); try easy.\n  intros.\n  apply (as_not_in_env AS tvl es env0); try easy.\n  intros.\n  apply (as_well_bound AS D Q H env0 tvl es) with (x := x0); try easy.\n  intros. \n  apply (as_stack_in AS tvl es S S'); try easy.\n  intros.\n  apply (as_stack_in_2 AS tvl es S S') with (x := x0) (ta := ta0); try easy.\n  apply (as_stack_in AS tvl es S S'); try easy.\n  intros. \n  apply (as_diff AS tvl es) with (n := n) (n' := n'); try easy.\n  split. constructor. easy.\nQed.\n\nLemma subtype_word_type : forall D Q t t', subtype D Q t t' -> word_type t -> word_type t'.\nProof.\n  intros.\n  inv H. assumption.\n  1-8:constructor.\nQed.\n\nLemma stack_heap_consistent_trans : forall tvl es D Q H env AS S S',\n     sub_domain env S -> stack_wt D S -> stack_wf D Q env S ->\n     env_wt D env -> stack_heap_consistent D Q H S ->\n     (forall a, In a tvl -> ~ Env.In (fst a) env) ->\n     (forall x n t ta, Env.MapsTo x t env -> Stack.MapsTo x (n,ta) S ->\n           (exists t', cast_type_bound S t t' /\\ subtype D Q ta t')) ->\n     (forall x n ta, Theta.MapsTo x GeZero Q -> Stack.MapsTo x (n,ta) S -> 0 <= n) ->\n     (forall n n' a b, n <> n' -> nth_error tvl n = Some a -> nth_error tvl n' = Some b -> fst a <> fst b) ->\n     (forall e, In e es -> (exists n t, e = ELit n t\n                 /\\ word_type t /\\ type_wf D t /\\ simple_type t) \\/ (exists y, e = EVar y)) ->\n     @well_typed_args D Q H env AS es tvl ->\n     eval_el AS S tvl es S' ->  stack_heap_consistent D Q H S'.\nProof.\n  intros.\n  induction H11. inv H10. easy.\n  unfold stack_heap_consistent in *.\n  intros. inv H10.\n  assert ((forall a : Env.key * type,\n             In a tvl ->\n             ~ Env.In (elt:=type) (fst a) env0)).\n  intros. apply H5. simpl. right. easy.\n  assert ((forall (n n' : nat) (a b : Env.key * type),\n             n <> n' ->\n             nth_error tvl n = Some a ->\n             nth_error tvl n' = Some b -> fst a <> fst b)).\n  intros.\n  specialize (H8 (S n1) (S n') a b).\n  simpl in H8. apply H8; try easy. lia.\n  assert ((forall e : expression,\n             In e es ->\n             (exists (n : Z) (t : type),\n                e = ELit n t /\\ word_type t /\\ type_wf D t /\\ simple_type t) \\/\n             (exists y : var, e = EVar y))).\n  intros. apply H9. simpl. right. easy.\n  specialize (IHeval_el H0 H1 H2 H4 H10 H6 H7 H14 H15 H22). clear H14. clear H15.\n  inv H11.\n  inv H19.\n  destruct (Nat.eq_dec x0 x). subst.\n  apply Stack.mapsto_add1 in H13. inv H13.\n  apply simple_type_means_cast_same with (s := s) in H15 as eq1.\n  apply cast_type_bound_same with (t' := (subst_type AS t)) in H18; try easy.\n  rewrite <- H18.\n  apply subtype_well_type with (t := t'0); try easy.\n  assert (In (ELit n t'0) (ELit n t'0 :: es)).\n  simpl. left. easy. apply H9 in H11.\n  destruct H11. destruct H11. destruct H11. destruct H11. inv H11. easy.\n  destruct H11. inv H11.\n  apply subtype_type_wf with (Q := Q) (t := t'0); try easy.\n  assert (In (ELit n t'0) (ELit n t'0 :: es)).\n  simpl. left. easy. apply H9 in H11.\n  destruct H11. destruct H11. destruct H11. destruct H11. inv H11. easy.\n  destruct H11. inv H11.\n  apply Stack.add_3 in H13.\n  apply IHeval_el in H13. easy. lia.\n  inv H19.\n  apply H4 in H20 as eq1.\n  destruct (Nat.eq_dec x0 x). subst.\n  apply Stack.mapsto_add1 in H13. inv H13.\n  unfold stack_wf in H2.\n  apply H2 in H14 as eq2.\n  destruct eq2 as [va [ta [tb [X1 [X2 X3]]]]].\n  apply Stack.mapsto_always_same with (v1 := (n,t'0)) in X3; try easy. inv X3.\n  assert (subtype D Q ta t').\n  apply cast_subtype_same with (S := s) (t1 := t'1) (t2 := (subst_type AS t)); try easy.\n  assert (subtype D Q tb t').\n  apply H1 in H20.\n  assert (word_type ta).\n  apply (subtype_word_type D Q tb); try easy.\n  inv H13. inv H11. inv X2. constructor.\n  apply subtype_trans with (m := m) (w := w); try easy.\n  apply subtype_well_type with (t := tb); try easy.\n  apply H1 in H20. easy.\n  apply cast_means_simple_type in H21. easy.\n  apply subtype_type_wf with (Q := Q) (t := tb); try easy.\n  apply H1 in H20. easy.\n  apply Stack.add_3 in H13.\n  apply IHeval_el in H13. easy. lia.\nQed.\n\nLemma theta_grow_type : forall D F S H env Q m e t,\n  @well_typed D F S H env empty_theta m e t\n   -> @well_typed D F S H env Q m e t.\nProof.\n  intros. remember empty_theta as Q'. induction H0;subst;eauto.\n  constructor.\nAdmitted.\n\nCheck List.find.\n\nDefinition tmem (l : list var) (x:var) := \n   match find (fun y => Nat.eqb x y) l with Some x => true | _ => false end.\n\nDefinition gen_rets_type (S:stack) (x:var) (ta:type) (e:expression) (t:type) :=\n   match ta with TNat => \n     match e with ELit v t' => if tmem (get_tvars t) x then Some (subst_type [(x,Num v)] t) else Some t\n                | EVar y => match Stack.find y S with None => None\n                                  | Some (v,t') => \n                                 if tmem (get_tvars t) x then Some (subst_type [(x,Num v)] t) else Some t\n                            end\n                | _ => None\n     end\n             | _ => Some t\n   end.\n\nInductive gen_rets_types (S:stack) : list (var * type) -> (list expression) -> type -> type -> Prop :=\n   | rets_type_empty : forall t, gen_rets_types S [] [] t t\n   | rets_type_many : forall x ta tvl e es t t' t'', gen_rets_types S tvl es t t' -> \n                gen_rets_type S x ta e t' = Some t'' ->\n                gen_rets_types S ((x,ta)::tvl) (e::es) t t''.\n\nLemma tmem_in : forall l x, tmem l x = true <-> In x l.\nProof.\n  intros. split. unfold tmem. intros.\n  destruct (find (fun y : nat => (x =? y)%nat) l) eqn:eq1.\n  apply find_some in eq1. destruct eq1.\n  apply Nat.eqb_eq in H1. subst. easy.\n  apply find_none with (x := x) in eq1.\n  apply Nat.eqb_neq in eq1. easy. easy.\n  intros. unfold tmem.\n  destruct (find (fun y : nat => (x =? y)%nat) l) eqn:eq1.\n  apply find_some in eq1. destruct eq1.\n  apply Nat.eqb_eq in H1. subst. easy.\n  apply find_none with (x := x) in eq1.\n  apply Nat.eqb_neq in eq1. easy. easy.\nQed.\n\nLemma well_typed_type_nat : forall D F S H env Q m e t, \n         @well_typed D F S H env Q m e t -> expr_wf D F e -> (forall x, In x (get_tvars t) -> Env.MapsTo x TNat env).\nProof.\nAdmitted.\n\nLemma expr_wf_gen_rets : forall tvl es D F S AS e e',\n     stack_wt D S -> \n     expr_wf D F e -> gen_rets AS S tvl es e e' ->\n    (forall x t', In (x,t') tvl -> word_type t' /\\ type_wf D t') ->\n     expr_wf D F e'.\nProof.\n  intros. induction H1. easy.\n  specialize (H2 x t) as eq1.\n  assert (In (x, t) ((x, t) :: xl)). simpl in *. left. easy.\n  apply eq1 in H4. destruct H4.\n  constructor.\n  simpl. inv H3.\n  split.\n  apply cast_word_type in H10; try easy.\n  apply subst_type_word_type. easy.\n  split.\n  apply cast_type_wf with (D:= D) in H10; try easy.\n  apply subst_type_type_wf. easy.\n  apply cast_means_simple_type in H10. easy.\n  split.\n  apply cast_word_type in H12; try easy.\n  apply subst_type_word_type. easy.\n  split.\n  apply cast_type_wf with (D:= D) in H12; try easy.\n  apply subst_type_type_wf. easy.\n  apply cast_means_simple_type in H12. easy.\n  apply IHgen_rets; try easy. intros.\n  specialize (H2 x0 t'0).\n  assert (In (x0, t'0) ((x, t) :: xl)). simpl. right. easy.\n  apply H2 in H7. easy.\nQed.\n\nLemma well_typed_gen_rets : forall tvl es D F S S' H AS env Q m e t e' t',\n       expr_wf D F e' ->\n       @well_typed D F S' H env Q m e t -> \n       gen_rets AS S tvl es e e' ->\n       gen_rets_types S tvl es t t' ->\n       (forall x t, In (x,t) tvl -> Env.MapsTo x t env) ->\n       stack_heap_consistent D Q H S ->\n       @well_typed D F S' H env Q m e' t'.\nProof.\n  intros. generalize dependent t'.\n  induction H2; intros. inv H3. easy.\n  inv H6.\n  apply IHgen_rets in H14 ; try easy.\n  unfold gen_rets_type in *.\n  assert (t0 = TNat \\/ t0 <> TNat).\n  destruct t0. left. easy. 1-4:right; easy.\n  destruct H6. subst.\n   assert (forall AS, subst_type AS TNat = TNat).\n   {\n    intros. induction AS0. simpl. easy.\n    simpl. easy.\n   }\n  rewrite H6 in H3. inv H3. inv H11.\n  destruct (tmem (get_tvars t'1) x) eqn:eq1.\n  apply tmem_in in eq1. inv H15.\n  apply TyRetTNat.\n  specialize (H4 x TNat). simpl in *. exists TNat. apply H4. left. easy. easy. easy.\n  assert (~ In x (get_tvars t'1)).\n  intros R. apply tmem_in in R.\n  rewrite eq1 in R. easy.\n  inv H15. apply TyRet.\n  specialize (H4 x TNat). simpl in *. exists TNat. apply H4. left. easy. easy. easy.\n  inv H13.\n  apply Stack.find_1 in H12. rewrite H12 in *.\n  destruct (tmem (get_tvars t'1) x) eqn:eq1.\n  apply tmem_in in eq1. inv H15.\n  apply TyRetTNat.\n  specialize (H4 x TNat). simpl in *. exists TNat. apply H4. left. easy. easy. easy.\n  assert (~ In x (get_tvars t'1)).\n  intros R. apply tmem_in in R.\n  rewrite eq1 in R. easy.\n  inv H15. apply TyRet.\n  specialize (H4 x TNat). simpl in *. exists TNat. apply H4. left. easy. easy. easy.\n  assert (match t0 with\n      | TNat =>\n          match e1 with\n          | ELit v _ =>\n              if tmem (get_tvars t'1) x\n              then Some (subst_type [(x, Num v)] t'1)\n              else Some t'1\n          | EVar y =>\n              match Stack.find (elt:=Z * type) y S with\n              | Some (v, _) =>\n                  if tmem (get_tvars t'1) x\n                  then Some (subst_type [(x, Num v)] t'1)\n                  else Some t'1\n              | None => None\n              end\n          | _ => None\n          end\n      | _ => Some t'1\n      end = Some t'1).\n  destruct t0; try easy. rewrite H7 in *. clear H7.\n  inv H15.\n  inv H0.\n  specialize (well_typed_type_nat D F S' H env0 Q m e' t'0 H14 H11) as eq1.\n  apply TyRet.\n  specialize (H4 x t0) as eq2.\n  simpl in *. exists t0. apply eq2; try easy. left. easy.\n  easy.\n  intros R.\n  apply eq1 in R.\n  specialize (H4 x t0) as eq2.\n  simpl in *. \n  assert ((x, t0) = (x, t0) \\/ In (x, t0) xl). left. easy.\n  apply eq2 in H0.\n  apply Env.mapsto_always_same with (v1 := TNat) in H0; try easy.\n  rewrite <- H0 in *. contradiction.\n  inv H0. easy.\n  intros. apply H4. simpl. right. easy.\nQed.\n\nLemma gen_arg_env_same : forall env tvl enva, gen_arg_env env tvl enva\n      -> (forall n n' a b, n <> n' -> nth_error tvl n = Some a -> nth_error tvl n' = Some b -> fst a <> fst b)\n       -> (forall x t, In (x,t) tvl -> Env.MapsTo x t enva).\nProof.\n intros. induction H.\n simpl in *. easy.\n specialize (nth_no_appear x0 t0 tvl H0) as eq1.\n simpl in *. destruct H1. inv H1.\n apply Env.add_1. easy.\n apply Env.add_2.\n apply eq1 in H1. easy.\n apply IHgen_arg_env; try easy.\n intros.\n specialize (H0 (S n) (S n') a b).\n apply H0. lia. simpl. easy. easy.\nQed.\n\nLemma get_dept_in_as : forall tvl es AS, \n   get_dept_map tvl es = Some AS -> (forall x, In (x,TNat) tvl -> (exists v, In (x,v) AS)).\nProof.\n  induction tvl; intros;simpl in *. easy.\n  destruct H0. subst.\n  destruct es. inv H.\n  destruct (get_good_dept e) eqn:eq1.\n  destruct (get_dept_map tvl es) eqn:eq2. inv H.\n  exists b. simpl. left. easy.\n  inv H. inv H.\n  destruct a. destruct t. destruct es. inv H.\n  destruct (get_good_dept e) eqn:eq1.\n  destruct (get_dept_map tvl es) eqn:eq2. inv H.\n  specialize (IHtvl es l eq2 x H0).\n  destruct IHtvl. exists x0. simpl. right. easy.\n  inv H. inv H. destruct es. inv H.\n  specialize (IHtvl es AS H x H0). destruct IHtvl. exists x0. easy.\n  destruct es. inv H.\n  specialize (IHtvl es AS H x H0). destruct IHtvl. exists x0. easy.\n  destruct es. inv H.\n  specialize (IHtvl es AS H x H0). destruct IHtvl. exists x0. easy.\n  destruct es. inv H.\n  specialize (IHtvl es AS H x H0). destruct IHtvl. exists x0. easy.\nQed.\n\n\nLemma gen_rets_as_cast_same:\n   forall tvl D Q H env es AS S t t', get_dept_map tvl es = Some AS ->\n   stack_wf D Q env S ->\n   gen_rets_types S tvl es t t' -> \n   well_bound_vars_type tvl t ->\n   @well_typed_args D Q H env AS es tvl ->\n   cast_type_bound S (subst_type AS t) t'.\nProof.\nAdmitted.\n\nLemma gen_rets_type_exists:\n   forall tvl D Q H env es AS S t, \n   sub_domain env S -> \n   get_dept_map tvl es = Some AS ->\n   @well_typed_args D Q H env AS es tvl ->\n   (exists t', gen_rets_types S tvl es t t').\nProof.\nAdmitted.\n\n\nLemma call_t_in_env : forall tvl D Q H env es AS t,\n   well_bound_vars_type tvl t ->\n   get_dept_map tvl es = Some AS ->\n   @well_typed_args D Q H env AS es tvl ->\n   well_type_bound_in env (subst_type AS t).\nProof.\nAdmitted.\n\nLemma stack_grow_well_typed:\n   forall D F S S' H env Q m e t,\n     stack_consistent_grow S S' env -> @well_typed D F S H env Q m e t\n     -> @well_typed D F S' H env Q m e t.\nProof.\nAdmitted.\n\nLemma well_typed_exchange_strlen :\n    forall D env Q S H l x y n n' e m t t0 ta l0 h0, stack_wt D S -> stack_wf D Q env S\n      -> stack_heap_consistent D Q H S -> theta_wt Q env S \n      -> heap_wf D H -> heap_wt_all D Q H ->\n      env_wt D env -> ~ Env.In (elt:=type) x env ->\n     ~ In x (get_tvars t) -> 0 <= n' -> \n      @well_typed D (fenv) S H\n        (Env.add x TNat\n           (Env.add y (TPtr Checked (TNTArray l (Var x 0) ta)) env))\n        (Theta.add x GeZero Q) Checked e t\n    ->\n   @well_typed D (fenv) (change_strlen_stack S y m t0 l0 n n' h0) H\n     (Env.add x TNat (Env.add y (TPtr Checked (TNTArray l (Num n') ta)) env)) Q\n      Checked e t.\nProof.\n  intros.\nAdmitted.\n\nLemma well_bound_grow_env :\n    forall env enva b, (forall x t, Env.MapsTo x t env -> Env.MapsTo x t enva) -> \n     well_bound_in env b -> well_bound_in enva b.\nProof.\n   intros. induction b.\n   apply well_bound_in_num.\n   apply well_bound_in_var. inv H0.\n   apply H. easy.\nQed.\n\nLemma well_type_bound_grow_env :\n        forall env enva t, (forall x t, Env.MapsTo x t env -> Env.MapsTo x t enva) -> \n         well_type_bound_in env t -> well_type_bound_in enva t.\nProof.\n   intros. induction t.\n   apply well_type_bound_in_nat.\n   apply well_type_bound_in_ptr.\n   apply IHt. inv H0. assumption.\n   apply well_type_bound_in_struct.\n   apply well_type_bound_in_array.\n   apply well_bound_grow_env with (env := env0); try easy. inv H0. assumption.\n   apply well_bound_grow_env with (env := env0); try easy. inv H0. assumption.\n   inv H0. apply IHt. assumption.\n   apply well_type_bound_in_ntarray.\n   apply well_bound_grow_env with (env := env0); try easy. inv H0. assumption.\n   apply well_bound_grow_env with (env := env0); try easy. inv H0. assumption.\n   inv H0. apply IHt. assumption.\nQed.\n\nModule StackFacts := FMapFacts.Facts (Stack).\n\nLemma cast_bound_not_nat :\n   forall env S b b' x n ta m tb, sub_domain env S -> well_bound_in env b ->\n     Env.MapsTo x (TPtr m tb) env ->\n     cast_bound S b = Some b' -> \n     cast_bound (Stack.add x (n,ta) S) b = Some b'.\nProof.\n  intros. unfold cast_bound in *. destruct b. easy.\n  inv H0.\n  destruct (Stack.find (elt:=Z * type) v (Stack.add x (n, ta) S) ) eqn:eq1. destruct p.\n  apply Stack.find_2 in eq1.\n  destruct (Stack.find (elt:=Z * type) v S) eqn:eq2.\n  apply Stack.find_2 in eq2. destruct p.\n  destruct (Nat.eq_dec x v). subst.\n  apply Env.mapsto_always_same with (v1 := TNat) in H1; try easy.\n  apply Stack.add_3 in eq1; try easy.\n  apply Stack.mapsto_always_same with (v1 := (z1, t0)) in eq1; try easy. inv eq1. easy.\n  destruct (Nat.eq_dec x v). subst.\n  apply Env.mapsto_always_same with (v1 := TNat) in H1; try easy.\n  apply Stack.add_3 in eq1.\n  apply Stack.find_1 in eq1. rewrite eq1 in eq2. inv eq2.\n  easy.\n  destruct (Stack.find (elt:=Z * type) v S) eqn:eq2.\n  apply Stack.find_2 in eq2.\n  destruct (Nat.eq_dec x v). subst.\n  apply Env.mapsto_always_same with (v1 := TNat) in H1; try easy.\n  apply StackFacts.not_find_in_iff in eq1.\n  assert (Stack.In (elt:=Z * type) v (Stack.add x (n, ta) S)).\n  exists p.\n  apply Stack.add_2. easy. easy. contradiction. easy.\nQed.\n\nLemma cast_type_bound_not_nat :\n   forall env S t t' x n ta m tb, sub_domain env S -> well_type_bound_in env t ->\n     Env.MapsTo x (TPtr m tb) env ->\n     cast_type_bound S t t' -> \n     cast_type_bound (Stack.add x (n,ta) S) t t'.\nProof.\n  intros. induction H2. constructor.\n  constructor. apply IHcast_type_bound. inv H0. easy.\n  constructor. apply cast_bound_not_nat with (env := env0) (m := m) (tb := tb); try easy.\n  inv H0. easy.\n  apply cast_bound_not_nat with (env := env0) (m := m) (tb := tb); try easy.\n  inv H0. easy.\n  apply IHcast_type_bound. inv H0. easy.\n  constructor. apply cast_bound_not_nat with (env := env0) (m := m) (tb := tb); try easy.\n  inv H0. easy.\n  apply cast_bound_not_nat with (env := env0) (m := m) (tb := tb); try easy.\n  inv H0. easy.\n  apply IHcast_type_bound. inv H0. easy.\n  constructor.\nQed.\n\nLemma replicate_nth_anti {A:Type} : forall (n k : nat) (x : A),\n    (k < n)%nat -> nth_error (replicate n x) k = Some x.\n  Proof.\n    induction n; intros k w H.\n    - lia.\n    - simpl. destruct k. simpl. easy.\n      assert (k < n)%nat by lia.\n      apply IHn with (x := w) in H0. simpl. easy. \nQed.\n\nLemma alloc_correct : forall w D Q H ptr H',\n    simple_type w ->\n    allocate D H w = Some (ptr, H') ->\n    structdef_wf D ->\n    heap_wf D H ->\n    @heap_consistent D Q H' H /\\\n    well_typed_lit D Q H empty_scope ptr (TPtr Checked w) /\\\n    heap_wf D H'.\nProof.\n  intros. \nAdmitted.\n\nLemma env_wt_trans : forall D tvl env enva, gen_arg_env env tvl enva -> \n    (forall x t', In (x,t') tvl -> word_type t' /\\ type_wf D t' /\\ well_bound_vars_type tvl t') ->\n      env_wt D env -> env_wt D enva.\nProof.\nAdmitted.\n\nLemma theta_wt_call_trans : forall AS tvl es Q S S' env env',\n      (forall a, In a tvl -> ~ Env.In (fst a) env) ->\n      (forall n n' a b, n <> n' -> nth_error tvl n = Some a -> nth_error tvl n' = Some b -> fst a <> fst b) ->\n      gen_arg_env env tvl env' -> sub_domain env S -> eval_el AS S tvl es S' ->\n      theta_wt Q env S -> theta_wt Q env' S'.\nProof.\nAdmitted.\n\n(* Type Preservation Theorem. *)\nLemma preservation : forall e D S H env Q t S' H' e',\n    @structdef_wf D ->\n    heap_wf D H ->\n    heap_wt_all D Q H ->\n    fun_wf D fenv ->\n    expr_wf D fenv e ->\n    stack_wt D S ->\n    env_wt D env ->\n    theta_wt Q env S ->\n    stack_wf D Q env S ->\n    stack_heap_consistent D Q H S ->\n    @well_typed D fenv S H env Q Checked e t ->\n    @reduce D (fenv env) S H e Checked S' H' (RExpr e') ->\n    exists env' Q', env_wt D env' /\\ theta_wt Q' env' S' /\\\n           stack_wf D Q' env' S' \n        /\\ stack_heap_consistent D Q' H' S' /\\\n      @heap_consistent D Q H' H \n   /\\ (exists t'', (@well_typed D fenv S' H' env' Q' Checked e' t'' /\\\n            (exists tx ty, cast_type_bound S' t tx /\\ cast_type_bound S' t'' ty /\\ subtype D Q' ty tx))).\nProof with eauto 20 with Preservation.\n  induction e; intros D s H env Q ta s' H' e'\n     HDwf HHwf HHWt HFun HEwf Hswt Henvt HQt HSwf HSHwf Hwt Hreduces; subst.\n  - inv Hwt. exfalso. eapply lit_are_nf...\n  (* T-Var *)\n  - inv Hwt. inv Hreduces.\n    destruct E; inversion H1; simpl in *; subst. inv H6. exists env. exists Q.\n    split. easy. split. easy. split. easy. \n    split. easy.\n    split. unfold heap_consistent. eauto.\n    unfold stack_wf in HSwf.\n    unfold stack_heap_consistent in *.\n    specialize (HSwf v ta H4) as eq2.\n    destruct eq2 as [ vx [ t' [t'' [X1 [X2 X3]]]]].\n    specialize (Stack.mapsto_always_same (Z*type) v (vx, t'') (v0, t) s' X3 H11) as eq1.\n    inv eq1.\n    exists t. split. constructor. apply HSHwf with (x := v); try easy.\n    exists t'. exists t. split. easy.\n    split. apply simple_type_means_cast_same.\n    unfold stack_wt in *.\n    specialize (Hswt v v0 t H11). easy. easy.\n\n  (*T-Strlen*)\n  - inv Hwt. inv Hreduces.\n    destruct E; inversion H1; simpl in *; subst. inv H6. exists env. exists Q.\n    split. easy.\n    split.\n    unfold theta_wt in *.\n    destruct HQt. split. apply H. intros.\n    unfold change_strlen_stack in *.\n    destruct (n' <=? h0) eqn:eq1.\n    apply H1 with (x := x) (ta := ta); try easy.\n    destruct (Nat.eq_dec x v). subst.\n    apply Stack.mapsto_add1 in H3. inv H3.\n    apply H1 in H9. easy. easy.\n    apply Stack.add_3 in H3. apply H1 with (x := x) (ta := ta); try easy. lia.\n    split.\n    assert (sub_domain env s) as G1. apply stack_wf_sub in HSwf; try easy.\n    unfold stack_wf in *. intros.\n    unfold change_strlen_stack. \n    destruct (Nat.eq_dec v x). subst.\n    unfold stack_wt in *.\n    apply Hswt in H9 as eq1. destruct eq1 as [X1 [X2 X3]].\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1.\n    specialize (HSwf x t2 H). easy.\n    apply Z.leb_nle in eq1.\n    specialize (HSwf x (TPtr Checked (TNTArray h l t)) H4).\n    destruct HSwf as [va [ta [tb [Y1 [Y2 Y3]]]]].\n    apply Stack.mapsto_always_same with (v1 := (va,tb)) in H9; try easy.\n    inv H9.\n    apply Env.mapsto_always_same with (v1 := t2) in H4; try easy. subst.\n    exists n. exists ta. exists (TPtr m (TNTArray (Num l0) (Num n') t0)).\n    assert (subtype D Q (TPtr m (TNTArray (Num l0) (Num n') t0)) (TPtr m (TNTArray (Num l0) (Num h0) t0))).\n    apply SubTyNtSubsume.\n    constructor. easy. constructor. lia.\n    split. apply Henvt in H as eq2. destruct eq2 as [Y5 [Y6 Y7]].\n    apply cast_type_bound_not_nat with (env := env) (m := Checked) (tb := ((TNTArray h l t))); try easy.\n    split.\n    apply subtype_trans with (m := m) (w := (TNTArray (Num l0) (Num h0) t0)); try easy.\n    apply Stack.add_1. easy.\n    specialize (HSwf x t2 H).\n    destruct HSwf as [va [ta [tb [X1 [X2 X3]]]]].\n    exists va.  exists ta. exists tb.\n    split.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1. easy.\n    apply Z.leb_nle in eq1.\n    apply cast_type_bound_not_nat with (env := env) (m := Checked) (tb := ((TNTArray h l t))); try easy.\n    apply Henvt in H as eq2. destruct eq2 as [Y5 [Y6 Y7]]. easy.\n    split. easy.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1. easy.\n    apply Z.leb_nle in eq1.\n    apply Stack.add_2. lia. easy.\n    split.\n    unfold stack_heap_consistent in *.\n    intros.\n    unfold change_strlen_stack in H.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1.\n    apply HSHwf with (x := x); try easy.\n    apply Z.leb_nle in eq1.\n    destruct (Nat.eq_dec v x). subst.\n    apply Stack.mapsto_add1 in H. inv H.\n    apply HSHwf in H9 as eq3. inv eq3. constructor. constructor.\n    solve_empty_scope.\n    unfold scope_set_add in *. inv H3. inv H2. inv H6.\n    apply TyLitC with (w := ((TNTArray (Num l0) (Num n') t0)))\n     (b := l0) (ts := (Zreplicate (n' - l0 + 1) t0)); eauto.\n    constructor. easy. apply SubTyRefl.\n    intros.\n    unfold scope_set_add.\n    rewrite replicate_gt_eq in H; try lia.\n    assert (l0 + (n' - l0 + 1) = n' + 1) by lia.\n    rewrite H2 in *. clear H2.\n    destruct (Z.eq_dec n' 0). subst.\n    rewrite replicate_gt_eq in H15; try lia.\n    specialize (H13 n) as eq2.\n    assert (n <= n < n + n') by lia.\n    apply eq2 in H2. clear eq2.\n    specialize (H15 0) as eq2.\n    assert (l0 <= 0 < l0 + Z.of_nat (length (Zreplicate (h0 - l0 + 1) t0))).\n    rewrite replicate_gt_eq; try lia.\n    apply eq2 in H3. clear eq2.\n    destruct H3 as [na [ta [X1 [X2 X3]]]].\n    destruct H2 as [nb [X4 X5]].\n    rewrite Z.add_0_r in X2.\n    apply Heap.mapsto_always_same with (v1 := (nb,t1)) in X2; try easy. inv X2.\n    symmetry in X1.\n    destruct (h0 - l0 + 1) as [| p1 | ?] eqn:Hp1; zify; [lia | |lia].\n    unfold Zreplicate in X1.\n    apply replicate_nth in X1. subst.\n    destruct (Z_ge_dec h0 k).\n    specialize (H15 k).\n    assert (l0 <= k < l0 + Z.of_nat (length (Zreplicate (Z.pos p1) ta))).\n    rewrite replicate_gt_eq; try lia.\n    apply H15 in H2. destruct H2 as [nc [tc [Y1 [Y2 Y3]]]].\n    exists nc. exists tc.\n    split. unfold Zreplicate in *.\n    symmetry in Y1.\n    apply replicate_nth in Y1. subst.\n    destruct (n' - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n    rewrite replicate_nth_anti. easy. lia. easy.\n    destruct (Z.eq_dec n' k). subst.\n    exists 0. exists ta.\n    destruct (k - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n    unfold Zreplicate. split.\n    rewrite replicate_nth_anti. easy. lia. split. easy.\n    constructor.\n    specialize (H13 (n+k)).\n    assert (n <= n + k < n + n') by lia.\n    apply H13 in H2.\n    destruct H2 as [nb [Y1 Y2]].\n    apply HHWt in Y1 as eq2.\n    exists nb. exists ta.\n    destruct (n' - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n    split. unfold Zreplicate.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    inv H12. inv H12. inv H2. inv H19. inv H12.\n    destruct (Z_ge_dec h2 n').\n    apply subtype_well_type with (t := (TPtr Checked (TNTArray (Num l2) (Num h2) t0))); try easy.\n    constructor. constructor. easy.\n    constructor. apply Hswt in H9. constructor.\n    destruct H9. destruct H2. inv H2. inv H17. easy.\n    apply Hswt in H9. \n    destruct H9 as [Y1 [Y2 Y3]]. inv Y2. inv H2. constructor. constructor. easy. easy.\n    apply TyLitC with (w := (TNTArray (Num l2) \n           (Num h2) t0)) (b := l2) (ts := Zreplicate (h2 - l2 + 1) t0); try easy.\n    constructor. easy.\n    constructor. intros.\n    unfold scope_set_add.\n    inv H6.\n    specialize (H15 k H). easy.\n    apply SubTyNtSubsume. constructor. lia. constructor. lia.\n    inv H6.\n    apply TyLitC with (w := ((TNTArray (Num l0) (Num n') t0)))\n     (b := l0) (ts := (Zreplicate (n' - l0 + 1) t0)); eauto.\n    constructor. easy. apply SubTyRefl.\n    intros.\n    unfold scope_set_add.\n    destruct (n' - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n    rewrite replicate_gt_eq in H; try easy.\n    rewrite <- Hp in *. assert (l0 + (n' - l0 + 1) = n' + 1) by lia.\n    rewrite H2 in *. clear H2.\n    destruct (Z.eq_dec n' 0). subst. lia.\n    specialize (H13 n) as eq2.\n    assert (n <= n < n + n') by lia.\n    apply eq2 in H2. clear eq2.\n    specialize (H15 0) as eq2.\n    assert (l2 <= 0 < l2 + Z.of_nat (length (Zreplicate (h2 - l2 + 1) t0))).\n    rewrite replicate_gt_eq; try lia.\n    apply eq2 in H6. clear eq2.\n    destruct H6 as [na [ta [X1 [X2 X3]]]].\n    destruct H2 as [nb [X4 X5]].\n    rewrite Z.add_0_r in X2.\n    apply Heap.mapsto_always_same with (v1 := (nb,t1)) in X2; try easy. inv X2.\n    symmetry in X1.\n    destruct (h2 - l2 + 1) as [| p1 | ?] eqn:Hp1; zify; [lia | |lia].\n    unfold Zreplicate in X1.\n    apply replicate_nth in X1. subst.\n    destruct (Z_ge_dec h2 k).\n    specialize (H15 k).\n    assert (l2 <= k < l2 + Z.of_nat (length (Zreplicate (Z.pos p1) ta))).\n    rewrite replicate_gt_eq; try lia.\n    apply H15 in H2. destruct H2 as [nc [tc [Y1 [Y2 Y3]]]].\n    exists nc. exists tc.\n    rewrite Hp.\n    split. unfold Zreplicate in *.\n    symmetry in Y1.\n    apply replicate_nth in Y1. subst.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    destruct (Z.eq_dec n' k). subst.\n    exists 0. exists ta.\n    unfold Zreplicate.\n    destruct (k - l0 + 1) as [| p2 | ?] eqn:Hp2; zify; [lia | |lia].\n    rewrite replicate_nth_anti. easy. lia.\n    specialize (H13 (n+k)).\n    assert (n <= n + k < n + n') by lia.\n    apply H13 in H2.\n    destruct H2 as [nb [Y1 Y2]].\n    apply HHWt in Y1 as eq2.\n    exists nb. exists ta.\n    split. unfold Zreplicate. rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    apply Stack.add_3 in H. apply HSHwf in H. easy. lia.\n    split. easy. exists TNat. split. constructor. constructor.\n    exists TNat. exists TNat. split. constructor. split. constructor. constructor.\n\n  (*T-Call*)\n  - inv Hwt. inv Hreduces.\n    destruct E; inversion H1; simpl in *; subst. inv H8.\n    rewrite H10 in H2. inv H2.\n    specialize (gen_arg_env_good tvl env) as X1.\n    destruct X1 as [enva X1]. rewrite H3 in H14. inv H14.\n    assert (sub_domain env s) as HSubDom.\n    apply stack_wf_sub in HSwf. easy.\n    specialize (sub_domain_grows tvl l env enva s s' AS X1 H17 HSubDom) as X2.\n    exists enva. exists Q.\n    split. \n    unfold fun_wf in *.\n    apply HFun with (H := H') (S := s) (env' := enva) in H10 ; try easy.\n    destruct H10.\n    specialize (env_wt_trans D tvl env enva X1 H Henvt) as eq2. easy.\n    split.\n\n    unfold fun_wf in *.\n    apply HFun with (H := H') (S := s) (env' := enva) in H10 ; try easy.\n    destruct H10 as [Y1 [Y2 [Y3 [Y4 Y5]]]].\n    specialize (theta_wt_call_trans AS tvl l Q s s' env \n             enva Y2 Y3 X1 HSubDom H17 HQt) as eq2. easy.\n    split. \n    apply (stack_wf_trans D Q H' env enva s s' AS tvl l); try easy.\n    unfold fun_wf in *.\n    destruct (HFun H' env enva s' f tvl t e m' H10 X1) as [Y1 [Y2 Y3]]. easy.\n    destruct (HFun H' env enva s' f tvl t e m' H10 X1) as [Y1 [Y2 Y3]]. easy.\n    intros.\n    specialize (gen_arg_env_has_all tvl env enva X1 x t0 H) as eq1. easy.\n    unfold theta_wt in *. destruct HQt. easy.\n    inv HEwf. easy.\n    split.\n    apply (stack_heap_consistent_trans tvl l D Q H' env AS s s'); try easy.\n    unfold fun_wf in *.\n    destruct (HFun H' env enva s' f tvl t e m' H10 X1) as [Y1 [Y2 Y3]]. easy.\n    unfold stack_wf in *. intros. specialize (HSwf x t0 H).\n    destruct HSwf as [va [tc [td [Y1 [Y2 Y3]]]]].\n    apply Stack.mapsto_always_same with (v1 := (n,ta)) in Y3; try easy. inv Y3.\n    exists tc. easy.\n    unfold theta_wt in *. destruct HQt. easy.\n    destruct (HFun H' env enva s' f tvl t e m' H10 X1) as [Y1 [Y2 Y3]]. easy.\n    inv HEwf. easy.\n    split.\n    easy.\n    destruct (HFun H' env enva s' f tvl t e m' H10 X1) as [Y1 [Y2 [Y3 [Y4 [Y5 [Y6 [Y7 Y8]]]]]]].\n    destruct m'. 2: { assert (Unchecked = Unchecked) by easy. apply H7 in H. easy. } \n    specialize (gen_rets_type_exists tvl D Q H' env l AS s t HSubDom H3 H9) as eq1.\n    destruct eq1.\n    specialize (gen_rets_as_cast_same tvl D Q H' env l AS s t x H3 HSwf H Y6 H9) as eq1.\n    apply theta_grow_type with (Q := Q) in Y8.\n    assert (forall x t', In (x,t') tvl -> word_type t' /\\ type_wf D t').\n    intros. apply Y1 in H1. easy.\n    specialize (expr_wf_gen_rets tvl l D fenv s AS e e' Hswt Y7 H18 H1) as eq2.\n    specialize (gen_arg_env_same env tvl enva X1 Y3) as eq3.\n    specialize (well_typed_gen_rets tvl l D (fenv) s s' H' AS enva\n               Q Checked e t e' x eq2 Y8 H18 H eq3 HSHwf) as eq4.\n    specialize (call_t_in_env tvl D Q H' env l AS t Y6 H3 H9) as eq5.\n    assert (length tvl = length l) as eq6.\n    rewrite (well_typed_args_same_length D Q H' env AS l tvl); try easy.\n    specialize (stack_consist_trans s s' env tvl l AS HSubDom Y2 eq6 H17) as eq7.\n    inv Y4. exists TNat. split.\n    apply TyCast1 with (t' := x); try easy. constructor.\n   assert (forall AS, subst_type AS TNat = TNat).\n   {\n    intros. induction AS0. simpl. easy.\n    simpl. easy.\n   }\n   rewrite H2. exists TNat. exists TNat. split;constructor. constructor. constructor.\n   destruct m. simpl.\n   exists (TPtr Checked (subst_type AS w)). split. \n   apply TyCast2 with (t' := x); try easy.\n   apply well_type_bound_grow_env with (env := env).\n   apply gen_arg_env_grow_1 with (tvl := tvl); try easy.\n   inv eq5. easy.\n   simpl in eq1.\n   apply subtype_left with (t2' := x).\n   apply cast_means_simple_type in eq1. easy.\n   apply stack_grow_cast_type_same with (env := env) (S := s); try easy.\n   constructor. exists x. exists x.\n   split.  apply stack_grow_cast_type_same with (env := env) (S := s); try easy.\n   split.    apply stack_grow_cast_type_same with (env := env) (S := s); try easy.\n   constructor.\n   exists (subst_type AS (TPtr Unchecked w)).\n   split.\n    apply TyCast1 with (t' := x); try easy.\n   apply well_type_bound_grow_env with (env := env).\n   apply gen_arg_env_grow_1 with (tvl := tvl); try easy.\n   easy.\n   exists x. exists x.\n   split.  apply stack_grow_cast_type_same with (env := env) (S := s); try easy.\n   split.    apply stack_grow_cast_type_same with (env := env) (S := s); try easy.\n   constructor.\n\n  (*T-Ret*)\n  - inv Hwt. inv Hreduces.\n    destruct E; inversion H1; simpl in *; subst. \n    inv H5. exists (Env.remove v env). exists (Theta.remove v Q).\n    split.\n    unfold env_wt in *. intros.\n    easy. split. easy. split.\n    unfold sub_domain in *. intros.\n    destruct (Nat.eq_dec x v). subst.\n    exists (a,ta). apply Stack.add_1. easy.\n    destruct H. apply Env.add_3 in H; try lia. \n    assert (Env.In x env). exists x0. easy.\n    apply HSubDom in H1. destruct H1. exists x1.\n    apply Stack.add_2;try lia. easy.\n    split. \n    unfold stack_wf in *. intros.\n    destruct (Nat.eq_dec x v). subst.\n    apply Env.mapsto_add1 in H. subst.\n    inv HEwf. inv H5. destruct H1.\n    exists a. exists ta. exists ta.\n    split. apply simple_type_means_cast_same;try easy.\n    split; try constructor. apply Stack.add_1. easy.\n    apply Env.add_3 in H; try lia.\n    apply HSwf in H. easy.\n    exists (a,ta). apply Stack.add_1. easy.\n    destruct H. apply Env.add_3 in H; try lia. \n    assert (Env.In x env). exists x0. easy.\n    apply HSubDom in H1. destruct H1. exists x1.\n    apply Stack.add_2;try lia. easy.\n\n    unfold sub_domain in *.\n    intros. destruct (n' <=? h0).\n    apply HSubDom. easy.\n    destruct (Nat.eq_dec x0 x). subst.\n    exists (n, TPtr m (TNTArray (Num l0) (Num n') t0)).\n    apply Stack.add_1. easy.\n    apply HSubDom in H.\n    destruct H.\n    exists x1.\n    apply Stack.add_2. lia. easy.\n    split.\n    unfold stack_wf in *. intros.\n    unfold change_strlen_stack. \n    destruct (Nat.eq_dec x0 x). subst.\n    unfold stack_wt in *.\n    apply Hswt in H8 as eq1. destruct eq1 as [X1 [X2 X3]].\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1.\n    specialize (HSwf x t2 H). easy.\n    apply Z.leb_nle in eq1.\n    specialize (HSwf x (TPtr Checked (TNTArray h l t)) Wb).\n    destruct HSwf as [va [ta [tb [Y1 [Y2 Y3]]]]].\n    apply Stack.mapsto_always_same with (v1 := (va,tb)) in H8; try easy.\n    inv H8.\n    apply Env.mapsto_always_same with (v1 := t2) in Wb; try easy. subst.\n    exists n. exists ta. exists (TPtr m (TNTArray (Num l0) (Num n') t0)).\n    assert (subtype D Q (TPtr m (TNTArray (Num l0) (Num n') t0)) (TPtr m (TNTArray (Num l0) (Num h0) t0))).\n    apply SubTyNtSubsume.\n    constructor. easy. constructor. lia.\n    split. apply Henvt in H as eq2. destruct eq2 as [Y5 [Y6 Y7]].\n    apply cast_type_bound_not_nat with (env := env) (m := Checked) (tb := ((TNTArray h l t))); try easy.\n    split.\n    apply subtype_trans with (m := m) (w := (TNTArray (Num l0) (Num h0) t0)); try easy.\n    apply Stack.add_1. easy.\n    specialize (HSwf x0 t2 H).\n    destruct HSwf as [va [ta [tb [X1 [X2 X3]]]]].\n    exists va.  exists ta. exists tb.\n    split.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1. easy.\n    apply Z.leb_nle in eq1.\n    apply cast_type_bound_not_nat with (env := env) (m := Checked) (tb := ((TNTArray h l t))); try easy.\n    apply Henvt in H as eq2. destruct eq2 as [Y5 [Y6 Y7]]. easy.\n    split. easy.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1. easy.\n    apply Z.leb_nle in eq1.\n    apply Stack.add_2. lia. easy.\n    split.\n    unfold stack_heap_consistent in *.\n    intros.\n    unfold change_strlen_stack in H.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1.\n    apply HSHwf with (x := x0); try easy.\n    apply Z.leb_nle in eq1.\n    destruct (Nat.eq_dec x0 x). subst.\n    apply Stack.mapsto_add1 in H. inv H.\n    apply HSHwf in H8 as eq3. inv eq3. constructor. constructor.\n    solve_empty_scope.\n    unfold allocate_meta in *. \n    unfold scope_set_add in *. inv H3. inv H2. inv H11.\n    apply TyLitC with (w := ((TNTArray (Num l0) (Num n') t0)))\n     (b := l0) (ts := (Zreplicate (n' - l0 + 1) t0)); eauto.\n    constructor. easy. apply SubTyRefl.\n    intros.\n    unfold scope_set_add.\n    destruct (n' - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n    rewrite replicate_gt_eq in H; try easy.\n    rewrite <- Hp in *. assert (l0 + (n' - l0 + 1) = n' + 1) by lia.\n    rewrite H2 in *. clear H2.\n    specialize (H12 n) as eq2.\n    assert (n <= n < n + n' + 1) by lia.\n    apply eq2 in H2. clear eq2.\n    specialize (H13 0) as eq2.\n    assert (l0 <= 0 < l0 + Z.of_nat (length (Zreplicate (h0 - l0 + 1) t0))).\n    rewrite replicate_gt_eq; try lia.\n    apply eq2 in H3. clear eq2.\n    destruct H3 as [na [ta [X1 [X2 X3]]]].\n    destruct H2 as [nb [X4 X5]].\n    rewrite Z.add_0_r in X2.\n    apply Heap.mapsto_always_same with (v1 := (nb,t1)) in X2; try easy. inv X2.\n    symmetry in X1.\n    destruct (h0 - l0 + 1) as [| p1 | ?] eqn:Hp1; zify; [lia | |lia].\n    unfold Zreplicate in X1.\n    apply replicate_nth in X1. subst.\n    destruct (Z_ge_dec h0 k).\n    specialize (H13 k).\n    assert (l0 <= k < l0 + Z.of_nat (length (Zreplicate (Z.pos p1) ta))).\n    rewrite replicate_gt_eq; try lia.\n    apply H13 in H2. destruct H2 as [nc [tc [Y1 [Y2 Y3]]]].\n    exists nc. exists tc.\n    split. unfold Zreplicate in *.\n    symmetry in Y1.\n    apply replicate_nth in Y1. subst.\n    rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    specialize (H12 (n+k)).\n    assert (n <= n + k < n + n' + 1) by lia.\n    apply H12 in H2.\n    destruct H2 as [nb [Y1 Y2]].\n    apply HHWt in Y1 as eq2.\n    exists nb. exists ta.\n    split. unfold Zreplicate. rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    inv H10. inv H10. inv H2. inv H17. inv H10.\n    destruct (Z_ge_dec h2 n').\n    apply subtype_well_type with (t := (TPtr Checked (TNTArray (Num l2) (Num h2) t0))); try easy.\n    constructor. constructor. easy.\n    constructor. apply Hswt in H8. constructor.\n    destruct H8. destruct H2. inv H2. inv H14. easy.\n    destruct H8 as [Y1 [Y2 Y3]]. inv Y2. inv H2. easy.\n    apply TyLitC with (w := (TNTArray (Num l2) \n           (Num h2) t0)) (b := l2) (ts := Zreplicate (h2 - l2 + 1) t0); try easy.\n    constructor. easy.\n    constructor. intros.\n    unfold scope_set_add.\n    inv H11.\n    specialize (H13 k H). easy.\n    apply SubTyNtSubsume. constructor. lia. constructor. lia.\n    inv H11.\n    apply TyLitC with (w := ((TNTArray (Num l0) (Num n') t0)))\n     (b := l0) (ts := (Zreplicate (n' - l0 + 1) t0)); eauto.\n    constructor. easy. apply SubTyRefl.\n    intros.\n    unfold scope_set_add.\n    destruct (n' - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n    rewrite replicate_gt_eq in H; try easy.\n    rewrite <- Hp in *. assert (l0 + (n' - l0 + 1) = n' + 1) by lia.\n    rewrite H2 in *. clear H2.\n    specialize (H12 n) as eq2.\n    assert (n <= n < n + n' + 1) by lia.\n    apply eq2 in H2. clear eq2.\n    specialize (H13 0) as eq2.\n    assert (l2 <= 0 < l2 + Z.of_nat (length (Zreplicate (h2 - l2 + 1) t0))).\n    rewrite replicate_gt_eq; try lia.\n    apply eq2 in H10. clear eq2.\n    destruct H10 as [na [ta [X1 [X2 X3]]]].\n    destruct H2 as [nb [X4 X5]].\n    rewrite Z.add_0_r in X2.\n    apply Heap.mapsto_always_same with (v1 := (nb,t1)) in X2; try easy. inv X2.\n    symmetry in X1.\n    destruct (h2 - l2 + 1) as [| p1 | ?] eqn:Hp1; zify; [lia | |lia].\n    unfold Zreplicate in X1.\n    apply replicate_nth in X1. subst.\n    destruct (Z_ge_dec h2 k).\n    specialize (H13 k).\n    assert (l2 <= k < l2 + Z.of_nat (length (Zreplicate (Z.pos p1) ta))).\n    rewrite replicate_gt_eq; try lia.\n    apply H13 in H2. destruct H2 as [nc [tc [Y1 [Y2 Y3]]]].\n    exists nc. exists tc.\n    rewrite Hp.\n    split. unfold Zreplicate in *.\n    symmetry in Y1.\n    apply replicate_nth in Y1. subst.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    specialize (H12 (n+k)).\n    assert (n <= n + k < n + n' + 1) by lia.\n    apply H12 in H2.\n    destruct H2 as [nb [Y1 Y2]].\n    apply HHWt in Y1 as eq2.\n    exists nb. exists ta.\n    split. unfold Zreplicate. rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    apply Stack.add_3 in H. apply HSHwf in H. easy. lia.\n    split. easy.\n\n  (*T-LetStrlen*)\n  - inv Hwt. inv Hreduces.\n    destruct E; inversion H1; simpl in *; subst. inv H5. \n    assert (forall E' e', in_hole e' E' = EStrlen y -> E' = CHole).\n    { induction E';intros;simpl in *;eauto.\n      1-12:inv H0.\n    }\n    apply H0 in H3 as eq1. subst. rewrite hole_is_id in *. subst.\n    inv H5.\n    simpl in *. \n    exists (Env.add y (TPtr Checked (TNTArray l (Num n') ta)) env). exists Q.\n    split.\n    unfold change_strlen_stack.\n    unfold sub_domain in *.\n    intros. destruct (n' <=? h0).\n    apply HSubDom.\n    destruct (Nat.eq_dec x0 y). subst.\n    exists (TPtr Checked (TNTArray l h ta)). easy.\n    destruct H. apply Env.add_3 in H. exists x1. easy. lia.\n    destruct (Nat.eq_dec x0 y). subst.\n    exists (n, TPtr m (TNTArray (Num l0) (Num n') t0)).\n    apply Stack.add_1. easy.\n    destruct H. apply Env.add_3 in H.\n    assert (Env.In x0 env). exists x1. easy.\n    apply (HSubDom) in H2.\n    destruct H2.\n    exists x2.\n    apply Stack.add_2. lia. easy. lia.\n    split.\n    unfold stack_wf in *. intros.\n    unfold change_strlen_stack. \n    destruct (Nat.eq_dec x0 y). subst.\n    unfold stack_wt in *.\n    apply Hswt in H10 as eq1. destruct eq1 as [X1 [X2 X3]].\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1.\n    apply Env.mapsto_add1 in H as eq2. subst.\n    specialize (HSwf y (TPtr Checked (TNTArray l h ta)) Wb).\n    destruct HSwf as [va [ta' [tb [Y1 [Y2 Y3]]]]].\n    inv Y1. inv H5.\n    apply Stack.mapsto_always_same with (v1 := (va,tb)) in H10; try easy.\n    inv H10. inv Y2.\n    exists n. exists (TPtr Checked (TNTArray (Num l0) (Num n') t'0)).\n    exists (TPtr Checked (TNTArray (Num l0) (Num h0) t'0)).\n    split. constructor. constructor.\n    easy. easy. easy. split. apply SubTyNtSubsume. constructor. easy. constructor. easy. easy.\n    inv X2. inv H3. inv H10. inv H4.\n    exists n. exists (TPtr Checked (TNTArray (Num h1) (Num n') t'0)).\n    exists (TPtr Checked (TNTArray (Num l0) (Num h0) t'0)).\n    split. constructor. constructor.\n    easy. easy. easy. split. apply SubTyNtSubsume. constructor. easy. constructor. easy. easy.\n    unfold cast_bound in H11. destruct l. inv H11. destruct (Stack.find (elt:=Z * type) v s).\n    destruct p. inv H11. inv H11.\n    apply Z.leb_nle in eq1.\n    specialize (HSwf y (TPtr Checked (TNTArray l h ta)) Wb).\n    destruct HSwf as [va [ta' [tb [Y1 [Y2 Y3]]]]].\n    apply Stack.mapsto_always_same with (v1 := (va,tb)) in H10; try easy.\n    inv H10.\n    apply Env.mapsto_add1 in H as eq2. subst. inv Y2.\n    exists n. exists  (TPtr m (TNTArray (Num l0) (Num n') t0)). exists (TPtr m (TNTArray (Num l0) (Num n') t0)).\n    assert (subtype D Q (TPtr m (TNTArray (Num l0) (Num n') t0)) (TPtr m (TNTArray (Num l0) (Num n') t0))).\n    constructor. split.\n    apply cast_type_bound_not_nat with (env := (Env.add y (TPtr Checked (TNTArray l (Num n') ta)) env)) \n     (m := Checked) (tb := (TNTArray l (Num n') ta)); try easy.\n    unfold sub_domain. intros. destruct H3.\n    destruct (Nat.eq_dec x0 y). subst. \n    exists ((n, TPtr m (TNTArray (Num l0) (Num h0) t0)) ). easy.\n    apply Env.add_3 in H3. apply HSubDom. exists x1. easy. lia.\n    apply weakening_type_bound with (ta := (TPtr Checked (TNTArray l h ta))); try easy.\n    apply Henvt in Wb as eq2. destruct eq2 as [Y5 [Y6 Y7]].\n    inv Y7. inv H5. constructor. constructor. easy. constructor. easy.\n    inv Y1. inv H4. constructor. constructor; try easy.\n    split. constructor. apply Stack.add_1. easy. inv H4.\n    inv Y1. inv H3. inv H11. inv Y1. inv H3. inv H11. inv H12.\n    inv Y1. inv H4.\n    exists n. exists  (TPtr Checked (TNTArray (Num h1) (Num n') t0)).\n    exists (TPtr Checked (TNTArray (Num l0) (Num n') t0)).\n    split.\n    apply cast_type_bound_not_nat with (env := (Env.add y (TPtr Checked (TNTArray (Num l0) (Num n') ta)) env)) \n     (m := Checked) (tb := (TNTArray (Num l0) (Num n') ta)); try easy.\n    unfold sub_domain. intros. destruct H2.\n    destruct (Nat.eq_dec x0 y). subst. \n    exists ((n, TPtr Checked (TNTArray (Num l0) (Num h0) t0)) ). easy.\n    apply Env.add_3 in H2. apply HSubDom. exists x1. easy. lia.\n    apply weakening_type_bound with (ta := (TPtr Checked (TNTArray l h ta))); try easy.\n    apply Henvt in Wb as eq2. destruct eq2 as [Y5 [Y6 Y7]].\n    inv Y7. inv H10. constructor. constructor. easy. constructor. easy.\n    apply Env.add_1. easy.\n    constructor. constructor; try easy.\n    split. constructor. constructor. easy. constructor. easy.\n    apply Stack.add_1. easy.\n    inv Y1. inv H5.\n    destruct l. inv H15. unfold cast_bound in H15.\n    destruct (Stack.find (elt:=Z * type) v s). destruct p. inv H15. inv H15.\n    apply Env.add_3 in H; try lia. apply HSwf in H as eq1.\n    destruct eq1 as [va [ta' [tb [Y5 [Y6 Y7]]]]].\n    exists va. exists ta'. exists tb.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1.\n    easy.\n    apply Z.leb_nle in eq1.\n    split. \n    apply cast_type_bound_not_nat with (env := env) \n     (m := Checked) (tb := (TNTArray l h ta)); try easy.\n    apply Henvt in H. easy.\n    split. easy.\n    apply Stack.add_2. lia. easy.\n    split.\n    unfold stack_heap_consistent in *.\n    intros.\n    unfold change_strlen_stack in H.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1.\n    apply HSHwf with (x := x0); try easy.\n    apply Z.leb_nle in eq1.\n    destruct (Nat.eq_dec x0 y). subst.\n    apply Stack.mapsto_add1 in H. inv H.\n    apply HSHwf in H10 as eq3. inv eq3. constructor. constructor.\n    solve_empty_scope.\n    unfold allocate_meta in *. \n    unfold scope_set_add in *. inv H4. inv H3. inv H12.\n    apply TyLitC with (w := ((TNTArray (Num l0) (Num n') t0)))\n     (b := l0) (ts := (Zreplicate (n' - l0 + 1) t0)); eauto.\n    constructor. easy. apply SubTyRefl.\n    intros.\n    unfold scope_set_add.\n    destruct (n' - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n    rewrite replicate_gt_eq in H; try easy.\n    rewrite <- Hp in *. assert (l0 + (n' - l0 + 1) = n' + 1) by lia.\n    rewrite H3 in *. clear H3.\n    specialize (H13 n) as eq2.\n    assert (n <= n < n + n' + 1) by lia.\n    apply eq2 in H3. clear eq2.\n    specialize (H14 0) as eq2.\n    assert (l0 <= 0 < l0 + Z.of_nat (length (Zreplicate (h0 - l0 + 1) t0))).\n    rewrite replicate_gt_eq; try lia.\n    apply eq2 in H4. clear eq2.\n    destruct H4 as [na [ta' [X1 [X2 X3]]]].\n    destruct H3 as [nb [X4 X5]].\n    rewrite Z.add_0_r in X2.\n    apply Heap.mapsto_always_same with (v1 := (nb,t1)) in X2; try easy. inv X2.\n    symmetry in X1.\n    destruct (h0 - l0 + 1) as [| p1 | ?] eqn:Hp1; zify; [lia | |lia].\n    unfold Zreplicate in X1.\n    apply replicate_nth in X1. subst.\n    destruct (Z_ge_dec h0 k).\n    specialize (H14 k).\n    assert (l0 <= k < l0 + Z.of_nat (length (Zreplicate (Z.pos p1) ta'))).\n    rewrite replicate_gt_eq; try lia.\n    apply H14 in H3. destruct H3 as [nc [tc [Y1 [Y2 Y3]]]].\n    exists nc. exists tc.\n    split. unfold Zreplicate in *.\n    symmetry in Y1.\n    apply replicate_nth in Y1. subst.\n    rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    specialize (H13 (n+k)).\n    assert (n <= n + k < n + n' + 1) by lia.\n    apply H13 in H3.\n    destruct H3 as [nb [Y1 Y2]].\n    apply HHWt in Y1 as eq2.\n    exists nb. exists ta'.\n    split. unfold Zreplicate. rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    inv H11. inv H11. inv H3. inv H18. inv H11.\n    destruct (Z_ge_dec h2 n').\n    apply subtype_well_type with (t := (TPtr Checked (TNTArray (Num l2) (Num h2) t0))); try easy.\n    constructor. constructor. easy.\n    constructor. apply Hswt in H10. constructor.\n    destruct H10. destruct H3. inv H3. inv H15. easy.\n    destruct H10 as [Y1 [Y2 Y3]]. inv Y2. inv H3. easy.\n    apply TyLitC with (w := (TNTArray (Num l2) \n           (Num h2) t0)) (b := l2) (ts := Zreplicate (h2 - l2 + 1) t0); try easy.\n    constructor. easy.\n    constructor. intros.\n    unfold scope_set_add.\n    inv H12.\n    specialize (H14 k H). easy.\n    apply SubTyNtSubsume. constructor. lia. constructor. lia.\n    inv H12.\n    apply TyLitC with (w := ((TNTArray (Num l0) (Num n') t0)))\n     (b := l0) (ts := (Zreplicate (n' - l0 + 1) t0)); eauto.\n    constructor. easy. apply SubTyRefl.\n    intros.\n    unfold scope_set_add.\n    destruct (n' - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n    rewrite replicate_gt_eq in H; try easy.\n    rewrite <- Hp in *. assert (l0 + (n' - l0 + 1) = n' + 1) by lia.\n    rewrite H3 in *. clear H3.\n    specialize (H13 n) as eq2.\n    assert (n <= n < n + n' + 1) by lia.\n    apply eq2 in H3. clear eq2.\n    specialize (H14 0) as eq2.\n    assert (l2 <= 0 < l2 + Z.of_nat (length (Zreplicate (h2 - l2 + 1) t0))).\n    rewrite replicate_gt_eq; try lia.\n    apply eq2 in H11. clear eq2.\n    destruct H11 as [na [ta' [X1 [X2 X3]]]].\n    destruct H3 as [nb [X4 X5]].\n    rewrite Z.add_0_r in X2.\n    apply Heap.mapsto_always_same with (v1 := (nb,t1)) in X2; try easy. inv X2.\n    symmetry in X1.\n    destruct (h2 - l2 + 1) as [| p1 | ?] eqn:Hp1; zify; [lia | |lia].\n    unfold Zreplicate in X1.\n    apply replicate_nth in X1. subst.\n    destruct (Z_ge_dec h2 k).\n    specialize (H14 k).\n    assert (l2 <= k < l2 + Z.of_nat (length (Zreplicate (Z.pos p1) ta'))).\n    rewrite replicate_gt_eq; try lia.\n    apply H14 in H3. destruct H3 as [nc [tc [Y1 [Y2 Y3]]]].\n    exists nc. exists tc.\n    rewrite Hp.\n    split. unfold Zreplicate in *.\n    symmetry in Y1.\n    apply replicate_nth in Y1. subst.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    specialize (H13 (n+k)).\n    assert (n <= n + k < n + n' + 1) by lia.\n    apply H13 in H3.\n    destruct H3 as [nb [Y1 Y2]].\n    apply HHWt in Y1 as eq2.\n    exists nb. exists ta'.\n    split. unfold Zreplicate. rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    apply Stack.add_3 in H. apply HSHwf in H. easy. lia.\n    split. easy.\n    left. apply TyLet with (t2 := TNat); try easy.\n    intros R. destruct R. apply Env.add_3 in H.\n    assert (Env.In (elt:=type) x env). exists x0. easy. contradiction.\n    intros R. subst.\n    assert (Env.In (elt:=type) x env). exists (TPtr Checked (TNTArray l h ta)).\n    easy. contradiction.\n    apply TyLit. constructor.\n    apply well_typed_exchange_strlen; try easy.\n\n  (*T-Strlen*)\n  - inv Hreduces.\n    destruct E; inversion H1; simpl in *; subst. inv H5. exists env. exists Q.\n    split.\n    unfold change_strlen_stack.\n    unfold sub_domain in *.\n    intros. destruct (n' <=? h0).\n    apply HSubDom. easy.\n    destruct (Nat.eq_dec x0 x). subst.\n    exists (n, TPtr m (TNTArray (Num l0) (Num n') t0)).\n    apply Stack.add_1. easy.\n    apply HSubDom in H.\n    destruct H.\n    exists x1.\n    apply Stack.add_2. lia. easy.\n    split.\n    unfold stack_wf in *. intros.\n    unfold change_strlen_stack. \n    destruct (Nat.eq_dec x0 x). subst.\n    unfold stack_wt in *.\n    apply Hswt in H8 as eq1. destruct eq1 as [X1 [X2 X3]].\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1.\n    specialize (HSwf x t2 H). easy.\n    apply Z.leb_nle in eq1.\n    specialize (HSwf x (TPtr Checked (TNTArray h l t)) Wb).\n    destruct HSwf as [va [ta [tb [Y1 [Y2 Y3]]]]].\n    apply Stack.mapsto_always_same with (v1 := (va,tb)) in H8; try easy.\n    inv H8.\n    apply Env.mapsto_always_same with (v1 := t2) in Wb; try easy. subst.\n    exists n. exists ta. exists (TPtr m (TNTArray (Num l0) (Num n') t0)).\n    assert (subtype D Q (TPtr m (TNTArray (Num l0) (Num n') t0)) (TPtr m (TNTArray (Num l0) (Num h0) t0))).\n    apply SubTyNtSubsume.\n    constructor. easy. constructor. lia.\n    split. apply Henvt in H as eq2. destruct eq2 as [Y5 [Y6 Y7]].\n    apply cast_type_bound_not_nat with (env := env) (m := Checked) (tb := ((TNTArray h l t))); try easy.\n    split.\n    apply subtype_trans with (m := m) (w := (TNTArray (Num l0) (Num h0) t0)); try easy.\n    apply Stack.add_1. easy.\n    specialize (HSwf x0 t2 H).\n    destruct HSwf as [va [ta [tb [X1 [X2 X3]]]]].\n    exists va.  exists ta. exists tb.\n    split.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1. easy.\n    apply Z.leb_nle in eq1.\n    apply cast_type_bound_not_nat with (env := env) (m := Checked) (tb := ((TNTArray h l t))); try easy.\n    apply Henvt in H as eq2. destruct eq2 as [Y5 [Y6 Y7]]. easy.\n    split. easy.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1. easy.\n    apply Z.leb_nle in eq1.\n    apply Stack.add_2. lia. easy.\n    split.\n    unfold stack_heap_consistent in *.\n    intros.\n    unfold change_strlen_stack in H.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1.\n    apply HSHwf with (x := x0); try easy.\n    apply Z.leb_nle in eq1.\n    destruct (Nat.eq_dec x0 x). subst.\n    apply Stack.mapsto_add1 in H. inv H.\n    apply HSHwf in H8 as eq3. inv eq3. constructor. constructor.\n    solve_empty_scope.\n    unfold allocate_meta in *. \n    unfold scope_set_add in *. inv H3. inv H2. inv H11.\n    apply TyLitC with (w := ((TNTArray (Num l0) (Num n') t0)))\n     (b := l0) (ts := (Zreplicate (n' - l0 + 1) t0)); eauto.\n    constructor. easy. apply SubTyRefl.\n    intros.\n    unfold scope_set_add.\n    destruct (n' - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n    rewrite replicate_gt_eq in H; try easy.\n    rewrite <- Hp in *. assert (l0 + (n' - l0 + 1) = n' + 1) by lia.\n    rewrite H2 in *. clear H2.\n    specialize (H12 n) as eq2.\n    assert (n <= n < n + n' + 1) by lia.\n    apply eq2 in H2. clear eq2.\n    specialize (H13 0) as eq2.\n    assert (l0 <= 0 < l0 + Z.of_nat (length (Zreplicate (h0 - l0 + 1) t0))).\n    rewrite replicate_gt_eq; try lia.\n    apply eq2 in H3. clear eq2.\n    destruct H3 as [na [ta [X1 [X2 X3]]]].\n    destruct H2 as [nb [X4 X5]].\n    rewrite Z.add_0_r in X2.\n    apply Heap.mapsto_always_same with (v1 := (nb,t1)) in X2; try easy. inv X2.\n    symmetry in X1.\n    destruct (h0 - l0 + 1) as [| p1 | ?] eqn:Hp1; zify; [lia | |lia].\n    unfold Zreplicate in X1.\n    apply replicate_nth in X1. subst.\n    destruct (Z_ge_dec h0 k).\n    specialize (H13 k).\n    assert (l0 <= k < l0 + Z.of_nat (length (Zreplicate (Z.pos p1) ta))).\n    rewrite replicate_gt_eq; try lia.\n    apply H13 in H2. destruct H2 as [nc [tc [Y1 [Y2 Y3]]]].\n    exists nc. exists tc.\n    split. unfold Zreplicate in *.\n    symmetry in Y1.\n    apply replicate_nth in Y1. subst.\n    rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    specialize (H12 (n+k)).\n    assert (n <= n + k < n + n' + 1) by lia.\n    apply H12 in H2.\n    destruct H2 as [nb [Y1 Y2]].\n    apply HHWt in Y1 as eq2.\n    exists nb. exists ta.\n    split. unfold Zreplicate. rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    inv H10. inv H10. inv H2. inv H17. inv H10.\n    destruct (Z_ge_dec h2 n').\n    apply subtype_well_type with (t := (TPtr Checked (TNTArray (Num l2) (Num h2) t0))); try easy.\n    constructor. constructor. easy.\n    constructor. apply Hswt in H8. constructor.\n    destruct H8. destruct H2. inv H2. inv H14. easy.\n    destruct H8 as [Y1 [Y2 Y3]]. inv Y2. inv H2. easy.\n    apply TyLitC with (w := (TNTArray (Num l2) \n           (Num h2) t0)) (b := l2) (ts := Zreplicate (h2 - l2 + 1) t0); try easy.\n    constructor. easy.\n    constructor. intros.\n    unfold scope_set_add.\n    inv H11.\n    specialize (H13 k H). easy.\n    apply SubTyNtSubsume. constructor. lia. constructor. lia.\n    inv H11.\n    apply TyLitC with (w := ((TNTArray (Num l0) (Num n') t0)))\n     (b := l0) (ts := (Zreplicate (n' - l0 + 1) t0)); eauto.\n    constructor. easy. apply SubTyRefl.\n    intros.\n    unfold scope_set_add.\n    destruct (n' - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n    rewrite replicate_gt_eq in H; try easy.\n    rewrite <- Hp in *. assert (l0 + (n' - l0 + 1) = n' + 1) by lia.\n    rewrite H2 in *. clear H2.\n    specialize (H12 n) as eq2.\n    assert (n <= n < n + n' + 1) by lia.\n    apply eq2 in H2. clear eq2.\n    specialize (H13 0) as eq2.\n    assert (l2 <= 0 < l2 + Z.of_nat (length (Zreplicate (h2 - l2 + 1) t0))).\n    rewrite replicate_gt_eq; try lia.\n    apply eq2 in H10. clear eq2.\n    destruct H10 as [na [ta [X1 [X2 X3]]]].\n    destruct H2 as [nb [X4 X5]].\n    rewrite Z.add_0_r in X2.\n    apply Heap.mapsto_always_same with (v1 := (nb,t1)) in X2; try easy. inv X2.\n    symmetry in X1.\n    destruct (h2 - l2 + 1) as [| p1 | ?] eqn:Hp1; zify; [lia | |lia].\n    unfold Zreplicate in X1.\n    apply replicate_nth in X1. subst.\n    destruct (Z_ge_dec h2 k).\n    specialize (H13 k).\n    assert (l2 <= k < l2 + Z.of_nat (length (Zreplicate (Z.pos p1) ta))).\n    rewrite replicate_gt_eq; try lia.\n    apply H13 in H2. destruct H2 as [nc [tc [Y1 [Y2 Y3]]]].\n    exists nc. exists tc.\n    rewrite Hp.\n    split. unfold Zreplicate in *.\n    symmetry in Y1.\n    apply replicate_nth in Y1. subst.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    specialize (H12 (n+k)).\n    assert (n <= n + k < n + n' + 1) by lia.\n    apply H12 in H2.\n    destruct H2 as [nb [Y1 Y2]].\n    apply HHWt in Y1 as eq2.\n    exists nb. exists ta.\n    split. unfold Zreplicate. rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    apply Stack.add_3 in H. apply HSHwf in H. easy. lia.\n    split. easy.\n    left. constructor. constructor.\n  (*T-LetStrlen*)\n  - inv Hreduces.\n    destruct E; inversion H1; simpl in *; subst. inv H5. \n    assert (forall E' e', in_hole e' E' = EStrlen y -> E' = CHole).\n    { induction E';intros;simpl in *;eauto.\n      1-12:inv H0.\n    }\n    apply H0 in H3 as eq1. subst. rewrite hole_is_id in *. subst.\n    inv H5.\n    simpl in *. \n    exists (Env.add y (TPtr Checked (TNTArray l (Num n') ta)) env). exists Q.\n    split.\n    unfold change_strlen_stack.\n    unfold sub_domain in *.\n    intros. destruct (n' <=? h0).\n    apply HSubDom.\n    destruct (Nat.eq_dec x0 y). subst.\n    exists (TPtr Checked (TNTArray l h ta)). easy.\n    destruct H. apply Env.add_3 in H. exists x1. easy. lia.\n    destruct (Nat.eq_dec x0 y). subst.\n    exists (n, TPtr m (TNTArray (Num l0) (Num n') t0)).\n    apply Stack.add_1. easy.\n    destruct H. apply Env.add_3 in H.\n    assert (Env.In x0 env). exists x1. easy.\n    apply (HSubDom) in H2.\n    destruct H2.\n    exists x2.\n    apply Stack.add_2. lia. easy. lia.\n    split.\n    unfold stack_wf in *. intros.\n    unfold change_strlen_stack. \n    destruct (Nat.eq_dec x0 y). subst.\n    unfold stack_wt in *.\n    apply Hswt in H10 as eq1. destruct eq1 as [X1 [X2 X3]].\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1.\n    apply Env.mapsto_add1 in H as eq2. subst.\n    specialize (HSwf y (TPtr Checked (TNTArray l h ta)) Wb).\n    destruct HSwf as [va [ta' [tb [Y1 [Y2 Y3]]]]].\n    inv Y1. inv H5.\n    apply Stack.mapsto_always_same with (v1 := (va,tb)) in H10; try easy.\n    inv H10. inv Y2.\n    exists n. exists (TPtr Checked (TNTArray (Num l0) (Num n') t'0)).\n    exists (TPtr Checked (TNTArray (Num l0) (Num h0) t'0)).\n    split. constructor. constructor.\n    easy. easy. easy. split. apply SubTyNtSubsume. constructor. easy. constructor. easy. easy.\n    inv X2. inv H3. inv H10. inv H4.\n    exists n. exists (TPtr Checked (TNTArray (Num h1) (Num n') t'0)).\n    exists (TPtr Checked (TNTArray (Num l0) (Num h0) t'0)).\n    split. constructor. constructor.\n    easy. easy. easy. split. apply SubTyNtSubsume. constructor. easy. constructor. easy. easy.\n    unfold cast_bound in H11. destruct l. inv H11. destruct (Stack.find (elt:=Z * type) v s).\n    destruct p. inv H11. inv H11.\n    apply Z.leb_nle in eq1.\n    specialize (HSwf y (TPtr Checked (TNTArray l h ta)) Wb).\n    destruct HSwf as [va [ta' [tb [Y1 [Y2 Y3]]]]].\n    apply Stack.mapsto_always_same with (v1 := (va,tb)) in H10; try easy.\n    inv H10.\n    apply Env.mapsto_add1 in H as eq2. subst. inv Y2.\n    exists n. exists  (TPtr m (TNTArray (Num l0) (Num n') t0)). exists (TPtr m (TNTArray (Num l0) (Num n') t0)).\n    assert (subtype D Q (TPtr m (TNTArray (Num l0) (Num n') t0)) (TPtr m (TNTArray (Num l0) (Num n') t0))).\n    constructor. split.\n    apply cast_type_bound_not_nat with (env := (Env.add y (TPtr Checked (TNTArray l (Num n') ta)) env)) \n     (m := Checked) (tb := (TNTArray l (Num n') ta)); try easy.\n    unfold sub_domain. intros. destruct H3.\n    destruct (Nat.eq_dec x0 y). subst. \n    exists ((n, TPtr m (TNTArray (Num l0) (Num h0) t0)) ). easy.\n    apply Env.add_3 in H3. apply HSubDom. exists x1. easy. lia.\n    apply weakening_type_bound with (ta := (TPtr Checked (TNTArray l h ta))); try easy.\n    apply Henvt in Wb as eq2. destruct eq2 as [Y5 [Y6 Y7]].\n    inv Y7. inv H5. constructor. constructor. easy. constructor. easy.\n    inv Y1. inv H4. constructor. constructor; try easy.\n    split. constructor. apply Stack.add_1. easy. inv H4.\n    inv Y1. inv H3. inv H11. inv Y1. inv H3. inv H11. inv H12.\n    inv Y1. inv H4.\n    exists n. exists  (TPtr Checked (TNTArray (Num h1) (Num n') t0)).\n    exists (TPtr Checked (TNTArray (Num l0) (Num n') t0)).\n    split.\n    apply cast_type_bound_not_nat with (env := (Env.add y (TPtr Checked (TNTArray (Num l0) (Num n') ta)) env)) \n     (m := Checked) (tb := (TNTArray (Num l0) (Num n') ta)); try easy.\n    unfold sub_domain. intros. destruct H2.\n    destruct (Nat.eq_dec x0 y). subst. \n    exists ((n, TPtr Checked (TNTArray (Num l0) (Num h0) t0)) ). easy.\n    apply Env.add_3 in H2. apply HSubDom. exists x1. easy. lia.\n    apply weakening_type_bound with (ta := (TPtr Checked (TNTArray l h ta))); try easy.\n    apply Henvt in Wb as eq2. destruct eq2 as [Y5 [Y6 Y7]].\n    inv Y7. inv H10. constructor. constructor. easy. constructor. easy.\n    apply Env.add_1. easy.\n    constructor. constructor; try easy.\n    split. constructor. constructor. easy. constructor. easy.\n    apply Stack.add_1. easy.\n    inv Y1. inv H5.\n    destruct l. inv H15. unfold cast_bound in H15.\n    destruct (Stack.find (elt:=Z * type) v s). destruct p. inv H15. inv H15.\n    apply Env.add_3 in H; try lia. apply HSwf in H as eq1.\n    destruct eq1 as [va [ta' [tb [Y5 [Y6 Y7]]]]].\n    exists va. exists ta'. exists tb.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1.\n    easy.\n    apply Z.leb_nle in eq1.\n    split. \n    apply cast_type_bound_not_nat with (env := env) \n     (m := Checked) (tb := (TNTArray l h ta)); try easy.\n    apply Henvt in H. easy.\n    split. easy.\n    apply Stack.add_2. lia. easy.\n    split.\n    unfold stack_heap_consistent in *.\n    intros.\n    unfold change_strlen_stack in H.\n    destruct (n' <=? h0) eqn:eq1. apply Z.leb_le in eq1.\n    apply HSHwf with (x := x0); try easy.\n    apply Z.leb_nle in eq1.\n    destruct (Nat.eq_dec x0 y). subst.\n    apply Stack.mapsto_add1 in H. inv H.\n    apply HSHwf in H10 as eq3. inv eq3. constructor. constructor.\n    solve_empty_scope.\n    unfold allocate_meta in *. \n    unfold scope_set_add in *. inv H4. inv H3. inv H12.\n    apply TyLitC with (w := ((TNTArray (Num l0) (Num n') t0)))\n     (b := l0) (ts := (Zreplicate (n' - l0 + 1) t0)); eauto.\n    constructor. easy. apply SubTyRefl.\n    intros.\n    unfold scope_set_add.\n    destruct (n' - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n    rewrite replicate_gt_eq in H; try easy.\n    rewrite <- Hp in *. assert (l0 + (n' - l0 + 1) = n' + 1) by lia.\n    rewrite H3 in *. clear H3.\n    specialize (H13 n) as eq2.\n    assert (n <= n < n + n' + 1) by lia.\n    apply eq2 in H3. clear eq2.\n    specialize (H14 0) as eq2.\n    assert (l0 <= 0 < l0 + Z.of_nat (length (Zreplicate (h0 - l0 + 1) t0))).\n    rewrite replicate_gt_eq; try lia.\n    apply eq2 in H4. clear eq2.\n    destruct H4 as [na [ta' [X1 [X2 X3]]]].\n    destruct H3 as [nb [X4 X5]].\n    rewrite Z.add_0_r in X2.\n    apply Heap.mapsto_always_same with (v1 := (nb,t1)) in X2; try easy. inv X2.\n    symmetry in X1.\n    destruct (h0 - l0 + 1) as [| p1 | ?] eqn:Hp1; zify; [lia | |lia].\n    unfold Zreplicate in X1.\n    apply replicate_nth in X1. subst.\n    destruct (Z_ge_dec h0 k).\n    specialize (H14 k).\n    assert (l0 <= k < l0 + Z.of_nat (length (Zreplicate (Z.pos p1) ta'))).\n    rewrite replicate_gt_eq; try lia.\n    apply H14 in H3. destruct H3 as [nc [tc [Y1 [Y2 Y3]]]].\n    exists nc. exists tc.\n    split. unfold Zreplicate in *.\n    symmetry in Y1.\n    apply replicate_nth in Y1. subst.\n    rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    specialize (H13 (n+k)).\n    assert (n <= n + k < n + n' + 1) by lia.\n    apply H13 in H3.\n    destruct H3 as [nb [Y1 Y2]].\n    apply HHWt in Y1 as eq2.\n    exists nb. exists ta'.\n    split. unfold Zreplicate. rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    inv H11. inv H11. inv H3. inv H18. inv H11.\n    destruct (Z_ge_dec h2 n').\n    apply subtype_well_type with (t := (TPtr Checked (TNTArray (Num l2) (Num h2) t0))); try easy.\n    constructor. constructor. easy.\n    constructor. apply Hswt in H10. constructor.\n    destruct H10. destruct H3. inv H3. inv H15. easy.\n    destruct H10 as [Y1 [Y2 Y3]]. inv Y2. inv H3. easy.\n    apply TyLitC with (w := (TNTArray (Num l2) \n           (Num h2) t0)) (b := l2) (ts := Zreplicate (h2 - l2 + 1) t0); try easy.\n    constructor. easy.\n    constructor. intros.\n    unfold scope_set_add.\n    inv H12.\n    specialize (H14 k H). easy.\n    apply SubTyNtSubsume. constructor. lia. constructor. lia.\n    inv H12.\n    apply TyLitC with (w := ((TNTArray (Num l0) (Num n') t0)))\n     (b := l0) (ts := (Zreplicate (n' - l0 + 1) t0)); eauto.\n    constructor. easy. apply SubTyRefl.\n    intros.\n    unfold scope_set_add.\n    destruct (n' - l0 + 1) as [| p | ?] eqn:Hp; zify; [lia | |lia].\n    rewrite replicate_gt_eq in H; try easy.\n    rewrite <- Hp in *. assert (l0 + (n' - l0 + 1) = n' + 1) by lia.\n    rewrite H3 in *. clear H3.\n    specialize (H13 n) as eq2.\n    assert (n <= n < n + n' + 1) by lia.\n    apply eq2 in H3. clear eq2.\n    specialize (H14 0) as eq2.\n    assert (l2 <= 0 < l2 + Z.of_nat (length (Zreplicate (h2 - l2 + 1) t0))).\n    rewrite replicate_gt_eq; try lia.\n    apply eq2 in H11. clear eq2.\n    destruct H11 as [na [ta' [X1 [X2 X3]]]].\n    destruct H3 as [nb [X4 X5]].\n    rewrite Z.add_0_r in X2.\n    apply Heap.mapsto_always_same with (v1 := (nb,t1)) in X2; try easy. inv X2.\n    symmetry in X1.\n    destruct (h2 - l2 + 1) as [| p1 | ?] eqn:Hp1; zify; [lia | |lia].\n    unfold Zreplicate in X1.\n    apply replicate_nth in X1. subst.\n    destruct (Z_ge_dec h2 k).\n    specialize (H14 k).\n    assert (l2 <= k < l2 + Z.of_nat (length (Zreplicate (Z.pos p1) ta'))).\n    rewrite replicate_gt_eq; try lia.\n    apply H14 in H3. destruct H3 as [nc [tc [Y1 [Y2 Y3]]]].\n    exists nc. exists tc.\n    rewrite Hp.\n    split. unfold Zreplicate in *.\n    symmetry in Y1.\n    apply replicate_nth in Y1. subst.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    specialize (H13 (n+k)).\n    assert (n <= n + k < n + n' + 1) by lia.\n    apply H13 in H3.\n    destruct H3 as [nb [Y1 Y2]].\n    apply HHWt in Y1 as eq2.\n    exists nb. exists ta'.\n    split. unfold Zreplicate. rewrite Hp.\n    rewrite replicate_nth_anti. easy. lia. easy.\n    apply Stack.add_3 in H. apply HSHwf in H. easy. lia.\n    split. easy.\n    left. apply TyLet with (t2 := TNat); try easy.\n    intros R. destruct R. apply Env.add_3 in H.\n    assert (Env.In (elt:=type) x env). exists x0. easy. contradiction.\n    intros R. subst.\n    assert (Env.In (elt:=type) x env). exists (TPtr Checked (TNTArray l h ta)).\n    easy. contradiction.\n    apply TyLit. constructor.\n    apply well_typed_exchange_strlen; try easy.\n  (* T-Let *)\n\n  - inv Hreduces.\n    destruct E; inversion H1; simpl in *; subst.\n    + clear H0. clear H9. rename e'0 into e'.\n      Set Printing All.\n      specialize (stack_grow_prop D F s H s' H' (ELet x e1 e2) e' HSSA H5) as eq1.\n      specialize (stack_simple_prop D F s H s' H' (ELet x e1 e2) e' SSimple H5) as eq2.\n      inv H5. exists (Env.add x t0 env). inv HEwf.\n      assert (Ht : t0 = t1). {\n        inv HTy1. reflexivity.\n      } rewrite Ht in *. clear Ht.\n      split. econstructor.\n      inv HSSA.\n      destruct H. destruct H0.\n      inv H0.\n      unfold sub_domain in HSubDom.\n      intros R. apply HSubDom in R.\n      apply H in R. contradiction.\n      split. unfold sub_domain in *.\n      intros. \n      destruct (Nat.eq_dec x0 x). subst.\n      unfold Stack.In,Stack.Raw.PX.In.\n      exists (n, t').\n      apply Stack.add_1. reflexivity.\n      assert (Stack.In (elt:=Z * type) x0 s -> Stack.In (elt:=Z * type) x0 (Stack.add x (n, t') s)).\n      intros. \n      unfold Stack.In,Stack.Raw.PX.In in *.\n      destruct H0. exists x1.\n      apply Stack.add_2. lia. assumption.\n      apply H0. apply HSubDom.\n      unfold Env.In,Env.Raw.PX.In in *.\n      destruct H.\n      apply Env.add_3 in H.\n      exists x1. assumption. lia.\n      split. apply (new_sub D F).\n      assumption. assumption.\n      assumption. assumption.\n      assumption.\n      split. unfold heap_consistent. eauto.\n      left. apply (stack_grow_well_typed D F s).\n      assumption.\n      assumption.\n    + clear H1.\n      assert (~ Stack.In x s) as eqa.\n      inv HSSA. destruct H0. destruct H1.\n      inv H1.\n      intros R. apply H0 in R. contradiction.\n      apply ty_ssa_stack_small_let in HSSA.\n      specialize (ty_ssa_stack_in_hole s e E HSSA) as eq3.\n      specialize (stack_grow_prop D F s H s' H' e e'0 eq3 H5) as eq1.\n      edestruct IH1...\n      inv HEwf;eauto.\n      exists x0. destruct H0 as [He [Hdom [Hs' [Hh Hwt]]]]. split. eauto. split.\n      eauto. split. eauto. split. eauto.\n      destruct Hwt.\n      left. econstructor. apply H0.\n      inv He. apply (stack_grow_well_typed D F s).\n      assumption. \n      apply (heapWF D F s H).\n      assumption. assumption.\n      destruct (Nat.eq_dec x  x1).\n      subst.\n      eapply equiv_env_wt.\n      assert (Env.Equal (Env.add x1 t1 (Env.add x1 t0 env)) (Env.add x1 t1 env)).\n      apply env_shadow. apply env_sym in H2.\n      apply H2.\n      apply (stack_grow_well_typed D F s s') in HTy2.\n      apply (heapWF D F s' H). assumption.\n      assumption. assumption.\n      apply (equiv_env_wt D F s' H' \n               (Env.add x1 t0 (Env.add x t1 env)) (Env.add x t1 (Env.add x1 t0 env))).\n      apply env_neq_commute_eq.\n      unfold Env.E.eq. lia. easy.\n      apply well_typed_grow.\n      intros R. \n      unfold Env.In,Env.Raw.PX.In in *.\n      destruct R.\n      apply Env.add_3 in H2.\n      destruct H1.\n      exists x0. assumption. assumption.\n      apply (stack_grow_well_typed D F s s') in HTy2.\n      apply (heapWF D F s' H). assumption.\n      assumption. assumption.\n      destruct H0.\n      destruct H0.\n      destruct H0. destruct H1.\n      assert (@well_typed D F s' H' (Env.add x t1 env) Checked e2 t).\n      apply (stack_grow_well_typed D F s s') in HTy2.\n      apply (heapWF D F s' H). assumption. assumption. assumption.\n      specialize (@well_typed_subtype D F s' H' env\n                    Checked e2 t x t1 x1 x2 H3 H0 H1) as eqb.\n      destruct eqb. left. econstructor.\n      apply H2. inv He. \n      apply well_typed_grow.\n      destruct (Nat.eq_dec x  x3).\n      subst.\n      eapply equiv_env_wt.\n      assert (Env.Equal (Env.add x3 x2 (Env.add x3 t0 env)) (Env.add x3 x2 env)).\n      apply env_shadow. apply env_sym in H7.\n      apply H7. assumption.\n      apply (equiv_env_wt D s' H' \n               (Env.add x3 t0 (Env.add x x2 env)) (Env.add x x2 (Env.add x3 t0 env))).\n      apply env_neq_commute_eq.\n      unfold Env.E.eq. lia. easy.\n      apply well_typed_grow.\n      intros R. \n      unfold Env.In,Env.Raw.PX.In in *.\n      destruct R.\n      apply Env.add_3 in H7.\n      destruct H6.\n      exists x0. assumption. assumption. assumption.\n      destruct H4.\n      destruct H4.\n      destruct H4.\n      destruct H6.\n      right. exists x3. exists x4.\n      split. eauto. split. eauto.\n      econstructor. apply H2.\n      inv He. assumption.\n      destruct (Nat.eq_dec x  x5).\n      subst.\n      eapply equiv_env_wt.\n      assert (Env.Equal (Env.add x5 x2 (Env.add x5 t0 env)) (Env.add x5 x2 env)).\n      apply env_shadow. apply env_sym in H10.\n      apply H10. assumption.\n      apply (equiv_env_wt D s' H' \n               (Env.add x5 t0 (Env.add x x2 env)) (Env.add x x2 (Env.add x5 t0 env))).\n      apply env_neq_commute_eq.\n      unfold Env.E.eq. lia. easy.\n      apply well_typed_grow.\n      intros R. \n      unfold Env.In,Env.Raw.PX.In in *.\n      destruct R.\n      apply Env.add_3 in H10.\n      destruct H8.\n      exists x0. assumption. assumption. assumption.\n  (* T-FieldAddr *)\n  - inv Hreduces.\n    destruct E; inversion H2; simpl in *; subst. exists env. \n    + clear H0. clear H10. inv H6.\n      * inv HTy.\n        (* Gotta prove some equalities *)\n        assert (fs = fs0).\n        { apply StructDef.find_1 in HWf1.\n          match goal with\n          | [ H : StructDef.MapsTo _ _ _ |- _ ] =>\n            apply StructDef.find_1 in H; rewrite HWf1 in H; inv H\n          end; auto.\n        } \n        subst.\n        assert (fields_wf D fs0) by eauto.\n\n        (* assert (i = i0).\n        { edestruct H; eauto. destruct H0. eapply H0. apply HWf2. apply H9. } *)\n        subst.\n        assert (ti = ti0).\n        { apply Fields.find_1 in HWf2.\n          apply Fields.find_1 in H9.\n          rewrite HWf2 in H9.\n          inv H9.\n          reflexivity. }\n        subst.\n        rename fs0 into fs.\n        clear i.\n        rename i0 into i. \n        rename ti0 into ti. \n\n        (* The fact that n^(ptr C struct T) is well-typed is all we need *)\n        split; eauto.\n        inv HHwf.\n        constructor. eapply preservation_fieldaddr; eauto. omega.\n      * inv HTy.\n        (* Gotta prove some equalities *)\n        assert (fs = fs0).\n        { apply StructDef.find_1 in HWf1.\n          apply StructDef.find_1 in H7.\n          rewrite HWf1 in H7.\n          inv H7.\n          reflexivity. }\n        subst. \n        assert (fields_wf D fs0) by eauto.\n        assert (ti = ti0).\n        { eauto using FieldFacts.MapsTo_fun. }\n        clear i.\n        rename fs0 into fs.\n        rename i0 into i.\n        subst; rename ti0 into ti.\n        (* Since it is an unchecked pointer, well-typedness is easy *)\n        idtac...\n    + clear H2. rename e0 into e1_redex. rename e'0 into e1_redex'.\n      edestruct IH; eauto.\n      inv HHwf; eauto.\n  (* T-Plus *)\n  - inv Hreduces.\n    destruct E; inversion H1; simpl in *; subst.\n    + clear H0. clear H7. rename e'0 into e'. inv H4.\n      * inversion HTy1.\n      * inv HTy1...\n    + clear H1. rename e into e1_redex. rename e'0 into e1_redex'. edestruct IH1; idtac...\n      inv HHwf; eauto.\n    + clear H1. rename e into e2_redex. rename e'0 into e2_redex'. edestruct IH2; idtac...\n      inv HHwf; eauto.\n  (* T-Malloc *)\n  - inv Hreduces.\n    destruct E; inversion H2; simpl in *; subst.\n    clear H0. clear H8.\n    inv H5.\n    split; eapply alloc_correct; eauto.\n  (* T-Unchecked *)\n  - inv Hreduces.\n    destruct E; inversion H1; simpl in *; subst.\n    + clear H0. clear H7. inv H4. inv HTy...\n    + inversion H7; inversion H0.\n  (* T-Cast *)\n  - inv Hreduces.\n    destruct E; inversion H1; simpl in *; subst.\n    + clear H0. clear H7. inv H4. inv HTy.\n      inv HHwf.\n      inv H1.\n      * idtac...\n      * destruct m.\n        { specialize (HChkPtr eq_refl w). exfalso. apply HChkPtr. reflexivity. }\n        { idtac... }\n    + clear H1. rename e0 into e1_redex. rename e'0 into e1_redex'. edestruct IH; idtac...\n      inv HHwf; eauto.\n  (* T-Deref *) \n  - destruct m'; try (specialize (HMode eq_refl); inversion HMode).\n    clear HMode.\n    inv HHwf.\n    specialize (IH H1 eq_refl).\n    inv Hreduces.\n    destruct E eqn:He; inversion H2; simpl in *; try congruence.\n    + \n      subst.\n      clear IH.\n      inv H5.\n      split; eauto.\n      destruct HPtrType as [[Hw Eq] | Hw]; subst.\n      *   inv HSubType.  \n         ** { inv HTy.\n            remember H7 as Backup; clear HeqBackup.\n            inv H7.\n           - exfalso.\n            eapply heap_wf_maps_nonzero; eauto.\n           - inv H2.\n            \n           - inv Hw; simpl in*; subst; simpl in *.\n            + inv H0; simpl in *.\n              destruct (H5 0) as [N [T' [HT' [HM' HWT']]]]; [inv H2; simpl; omega | ].\n             \n              inv HT'.\n              rewrite Z.add_0_r in HM'.\n              assert (Hyp: (N, TNat) = (n1, t1)). {\n              eapply HeapFacts.MapsTo_fun. inv H2. inv H0.\n              exact HM'. exact H9. }\n              inv Hyp; subst; eauto.\n            + inv H0; simpl in *.\n              destruct (H5 0) as [N [T' [HT' [HM' HWT']]]]; [inv H2; simpl; omega | ].\n              inv HT'.\n              rewrite Z.add_0_r in HM'.\n              assert (Hyp: (N, TPtr m w) = (n1, t1)). {\n                eapply HeapFacts.MapsTo_fun. inv H2.\n                inv H0. exact HM'. exact H9. }\n              inv Hyp; subst; eauto.\n              apply TyLit.\n\n              assert (Hyp: set_remove_all (n, TPtr Checked (TPtr m w))\n                                     ((n,TPtr Checked (TPtr m w))::nil) = empty_scope).\n              { \n                destruct (eq_dec_nt (n, TPtr Checked (TPtr m w)) (n, TPtr Checked (TPtr m w))) eqn:EQ; try congruence.\n                unfold set_remove_all.\n                rewrite EQ.\n                auto.\n              }\n\n              rewrite <- Hyp.\n              apply scope_strengthening. inv H2. inv H0.\n              exact HWT'. exact HEwf. exact Backup.\n            }\n           ** { inv HTy.\n              remember H10 as Backup; clear HeqBackup.\n              inv H10.\n              - exfalso.\n                eapply heap_wf_maps_nonzero; eauto.\n              - inv H2.\n            \n              - inv Hw; simpl in*; subst; simpl in *.\n            \n              }\n          ** { inv HTy.\n               remember H12 as Backup; clear HeqBackup.\n               inv H12.\n               - exfalso.\n                 eapply heap_wf_maps_nonzero; eauto.\n               - inv H2.\n            \n               - inv Hw; simpl in*; subst; simpl in *.\n                 + inv H0; simpl in *.\n                   destruct (H10 0) as [N [T' [HT' [HM' HWT']]]]; [inv H2; simpl; eauto | ].\n                   destruct (StructDef.find (elt:=fields) T D) eqn:H.\n                   inv H0. rewrite map_length. \n                   assert (StructDef.MapsTo T f D) by (eapply find_implies_mapsto; eauto).\n                   assert (f = fs) by (eapply StructDefFacts.MapsTo_fun; eauto). rewrite <- H2 in *.\n                   assert (((length (Fields.elements (elt:=type) f)) > 0)%nat) by (eapply fields_implies_length; eauto).\n                   omega. inv H. inv H0.\n                   inv HT'.\n                   rewrite Z.add_0_r in HM'.\n                   assert (Hb : b = 0). \n                   {\n                     destruct (StructDef.find (elt:=fields) T D);\n                      inv H2. reflexivity.\n                   } rewrite Hb in *.\n                   simpl in H0. \n                   assert (Hts : StructDef.find (elt:=fields) T D = Some fs) by (eapply StructDef.find_1; eauto).\n                   rewrite Hts in H2. inv H2.\n                   assert (Some TNat = match map snd (Fields.elements (elt := type) fs)\n                    with \n                    | nil => None\n                    | x:: _ => Some x\n                          end) by (eapply element_implies_element; eauto).\n                    rewrite <- H in H0. inv H0. \n                    assert (Hyp: (N, TNat) = (n1, t1)). {\n                    eapply HeapFacts.MapsTo_fun.\n                    exact HM'. exact H9. }\n                    inv Hyp; subst; eauto.\n                }\n      *   assert (exists t1, w = (TPtr Checked t1)) by (inv HSubType; eauto).\n          destruct H. rewrite H in *. clear H.\n        { inv HTy.\n          clear H8.\n          clear H0.\n          clear H1.\n          remember H7 as Backup; clear HeqBackup.\n          inv H7.\n          - exfalso. \n            eapply heap_wf_maps_nonzero; eauto.\n          - inversion H0.\n          - destruct Hw as [? [? ?]]; subst.\n            inv H0; simpl in *.\n            inv HSubType.\n            -- unfold allocate_meta in H4.\n               destruct (H11 l h t). reflexivity.\n               assert (Hpos : exists p, (h - l) = Z.pos p).\n                {\n                   destruct h; destruct l; inv H.\n                   + exists p. simpl; reflexivity.\n                   + exfalso. eapply H0. simpl. reflexivity.\n                   + assert (Z.pos p - Z.neg p0 > 0) by (zify; omega).\n                     assert (exists p2, Z.pos p - Z.neg p0 = Z.pos p2).\n                     {\n                      destruct (Z.pos p - Z.neg p0); inv H. exists p1. reflexivity.\n                     } destruct H5. exists x. assumption.\n                }\n                destruct Hpos. rewrite H5 in *. simpl in H4. \n                inv H4; simpl in *. \n                assert (exists p, h = Z.pos p).\n                {\n                  destruct h; inv H. exists p; reflexivity.\n                }\n                destruct H4. destruct l.\n                * assert (Hpos : exists n, Pos.to_nat x = S n) by apply pos_succ.\n                  destruct Hpos.\n                  destruct (H3 0) as [N [T' [HT' [HM' HWT']]]]; [ simpl; rewrite H7; simpl; zify; omega  | ].\n                  rewrite H7 in HT'.  simpl in HT'. inv HT'.  rewrite Z.add_0_r in HM'.\n                  maps_to_fun.\n                  constructor.\n                  assert (Hyp: set_remove_all (n, TPtr Checked (TArray 0 (Z.pos x0) t))\n                                        ((n,TPtr Checked (TArray 0 (Z.pos x0) t))::nil) = empty_scope).\n                    { \n                      destruct (eq_dec_nt (n, TPtr Checked (TArray 0 (Z.pos x0) t))\n                                    (n, TPtr Checked (TArray 0 (Z.pos x0) t))) eqn:EQ; try congruence.\n                      unfold set_remove_all.\n                      rewrite EQ.\n                      auto.\n                    }\n                  rewrite <- Hyp.\n                  apply scope_strengthening; eauto.\n                * exfalso; eapply H0; eauto.\n                * assert (Hpos : exists n, Pos.to_nat x = S n) by apply pos_succ.\n                  destruct Hpos. rewrite H4 in *.  clear H4 H0 H.\n                  destruct (H3 0) as [N [T' [HT' [HM' HWT']]]]; [ rewrite H7; rewrite replicate_length; zify; omega | ].\n                  rewrite H7 in HT'.\n                  rewrite Z.add_0_r in HM'.\n                  symmetry in HT'.\n                   assert (t = T').\n                   { \n                     eapply replicate_nth; eauto.\n                   } \n                   subst T'.\n                  maps_to_fun.\n                   econstructor.\n                   assert (Hyp: set_remove_all (n, TPtr Checked (TArray (Z.neg p) (Z.pos x0) t))\n                                        ((n,TPtr Checked (TArray (Z.neg p) (Z.pos x0) t))::nil) = empty_scope).\n                        { \n                          destruct (eq_dec_nt (n, TPtr Checked (TArray (Z.neg p) (Z.pos x0) t))\n                                        (n, TPtr Checked (TArray (Z.neg p) (Z.pos x0) t))) eqn:EQ; try congruence.\n                          unfold set_remove_all.\n                          rewrite EQ.\n                          auto.\n                        }\n\n                      rewrite <- Hyp.\n                      apply scope_strengthening; eauto.\n            -- unfold allocate_meta in H4.\n               destruct (H11 l0 h0 t). reflexivity.\n               clear H0.\n               assert (Hpos : exists p, (h0 - l0) = Z.pos p).\n                {\n                   destruct h0; destruct l0; inv H.\n                   + exists p. simpl; reflexivity.\n                   + exfalso. eapply H5. simpl. reflexivity.\n                   + assert (Z.pos p - Z.neg p0 > 0) by (zify; omega).\n                     assert (exists p2, Z.pos p - Z.neg p0 = Z.pos p2).\n                     {\n                      destruct (Z.pos p - Z.neg p0); inv H. exists p1. reflexivity.\n                     } destruct H0. exists x. assumption.\n                }\n                destruct Hpos. rewrite H0 in *. simpl in H4. \n                inv H4; simpl in *. \n                assert (exists p, h0 = Z.pos p).\n                {\n                  destruct h0; inv H. exists p; reflexivity.\n                }\n                destruct H4. destruct l0.\n                * assert (Hpos : exists n, Pos.to_nat x = S n) by apply pos_succ.\n                  destruct Hpos.\n                  destruct (H3 0) as [N [T' [HT' [HM' HWT']]]]; [ simpl; rewrite H7; simpl; zify; omega  | ].\n                  rewrite H7 in HT'.  simpl in HT'. inv HT'.  rewrite Z.add_0_r in HM'.\n                  maps_to_fun.\n                  constructor.\n                  assert (Hyp: set_remove_all (n, TPtr Checked (TArray 0 (Z.pos x0) t))\n                                        ((n,TPtr Checked (TArray 0 (Z.pos x0) t))::nil) = empty_scope).\n                    { \n                      destruct (eq_dec_nt (n, TPtr Checked (TArray 0 (Z.pos x0) t))\n                                    (n, TPtr Checked (TArray 0 (Z.pos x0) t))) eqn:EQ; try congruence.\n                      unfold set_remove_all.\n                      rewrite EQ.\n                      auto.\n                    }\n                  rewrite <- Hyp.\n                  apply scope_strengthening; eauto.\n                * exfalso; eapply H5; eauto.\n                * assert (Hpos : exists n, Pos.to_nat x = S n) by apply pos_succ.\n                  destruct Hpos. rewrite H4 in *.\n                  destruct (H3 0) as [N [T' [HT' [HM' HWT']]]]; [ rewrite H7; rewrite replicate_length; zify; omega | ].\n                  rewrite H7 in HT'.\n                  rewrite Z.add_0_r in HM'.\n                  symmetry in HT'.\n                   assert (t = T').\n                   { \n                     eapply replicate_nth; eauto.\n                   } \n                   subst T'.\n                  maps_to_fun.\n                   econstructor.\n                   assert (Hyp: set_remove_all (n, TPtr Checked (TArray (Z.neg p) (Z.pos x0) t))\n                                        ((n,TPtr Checked (TArray (Z.neg p) (Z.pos x0) t))::nil) = empty_scope).\n                        { \n                          destruct (eq_dec_nt (n, TPtr Checked (TArray (Z.neg p) (Z.pos x0) t))\n                                        (n, TPtr Checked (TArray (Z.neg p) (Z.pos x0) t))) eqn:EQ; try congruence.\n                          unfold set_remove_all.\n                          rewrite EQ.\n                          auto.\n                        }\n\n                      rewrite <- Hyp.\n                      apply scope_strengthening; eauto.\n          }\n\n    + subst.\n      destruct (IH (in_hole e'0 c) H') as [HC HWT]; eauto. \n  - inv HHwf.\n\n    assert (exists l0 h0, t = (TPtr m' (TArray l0 h0 t'))).\n    {\n      inv HSubType. exists l. exists h. reflexivity.\n      exists l0. exists h0. reflexivity. \n    }\n\n    destruct H0 as [l0 [h0 Hb]].\n    rewrite Hb in *. clear Hb HSubType.\n    (* TODO: Move outside, cleanup *)\n    Ltac invert_expr_wf e :=\n      match goal with\n      | [ H : expr_wf _ e |- _ ] => inv H\n      end.\n\n    invert_expr_wf (EPlus e1 e2).\n    inv Hreduces.\n\n    Ltac invert_ctx_and_hole :=\n      match goal with\n      | [H : in_hole _ ?C = _ |- _] => destruct C; inversion H; simpl in *; subst; clear H\n      end.\n\n    invert_ctx_and_hole.\n\n    + inv H6. (*TODO: auto *)\n    + invert_ctx_and_hole.\n      * { (* Plus step *)\n          match goal with\n          | [ H : step _ _ _ _ _ |- _ ] => inv H\n          end; split; eauto...\n          - inv HTy1.\n            eapply TyDeref; eauto.\n            constructor.\n\n            Ltac cleanup :=\n              repeat (match goal with\n                      | [H : ?X =  ?X |- _ ] => clear H\n                      | [H : ?X -> ?X |- _ ] => clear H\n                      end).\n            cleanup.\n            \n            match goal with\n            | [ H : well_typed_lit _ _ _ _ _ |- _ ] =>\n              remember H as Backup; clear HeqBackup; inv H; eauto; try omega\n            end.\n\n            unfold allocate_meta in *.\n\n            inversion H0; subst b; subst ts; clear H0.\n            \n            eapply TyLitC; unfold allocate_meta in *; eauto.\n\n            intros k Hk.\n            \n            assert (Hyp: h0 - n2 - (l0 - n2) = h0 - l0) by omega.\n            rewrite Hyp in * ; clear Hyp.\n            \n            destruct (H6 (n2 + k)) as [n' [t'' [HNth [HMap HWT]]]]; [inv H0; omega | ].\n\n            exists n'. exists t''.\n\n            rewrite Z.add_assoc in HMap.\n            inv H0.\n            split; [ | split]; auto.\n            + destruct (h0 - l0) eqn:HHL; simpl in *.\n              * rewrite Z.add_0_r in Hk.\n                destruct (Z.to_nat (n2 + k - l0)); inv HNth.\n              * assert (HR: k - (l0 - n2) = n2 + k - l0) by (zify; omega).\n                rewrite HR.\n                auto.\n              * destruct (Z.to_nat (n2 + k - l0)); inv HNth.\n            + apply scope_weakening_cons.\n\n              eapply scope_strengthening in HWT; eauto.\n              assert (HAdd : set_add eq_dec_nt (n1, TPtr Checked (TArray l0 h0 t'))\n                                     empty_scope =\n                             (n1, TPtr Checked (TArray l0 h0 t')) :: nil) by auto.\n              rewrite HAdd in HWT.\n              clear HAdd.\n\n              assert (HEmpty : empty_scope =\n                               set_remove_all (n1, TPtr Checked (TArray l0 h0 t')) \n                                             ((n1, TPtr Checked (TArray l0 h0 t')) :: nil)).\n              {\n                unfold set_remove_all.\n                destruct (eq_dec_nt (n1, TPtr Checked (TArray l0 h0 t'))\n                                    (n1, TPtr Checked (TArray l0 h0 t'))); auto.\n                congruence.\n              }\n              rewrite <- HEmpty in HWT.\n              auto.\n            + eapply SubTyRefl.\n          - inv HTy1.\n            destruct m'.\n            + exfalso; eapply H10; eauto.\n            + specialize (HMode eq_refl). inv HMode.\n        }\n      * clear l h t. \n        specialize (IH1 H3 eq_refl).\n        specialize (IH1 (in_hole e'0 E) H').\n        destruct IH1 as [HC HWT]; eauto.\n        split; eauto. eapply TyIndex; eauto.\n        eapply SubTyRefl. eauto...\n      * specialize (IH2 H4 eq_refl (in_hole e'0 E) H').\n        destruct IH2 as [HC HWT]; eauto.\n        split; eauto. eapply TyIndex; eauto...\n        eapply SubTyRefl.\n  (* T-Assign *)\n  - inv Hreduces.\n    inv HHwf.\n    destruct E; inversion H4; simpl in *; subst.\n    + clear H10 H3.\n      inv H7.\n      inv Hwt2.\n      inv Hwt1.\n      destruct H1 as [[HW Eq] | Eq]; subst.\n      * {\n          destruct m'; [| specialize (H2 eq_refl); inv H2].\n          inv H0.\n          **\n            eapply well_typed_heap_in in H11; eauto.\n            destruct H11 as [N HMap].\n            split.\n            - apply HeapUpd with (n := N); eauto...\n              eapply PtrUpd; eauto.\n            - constructor.\n              eapply PtrUpd; eauto. \n          **\n            eapply well_typed_heap_in in H11; eauto.\n            destruct H11 as [N HMap].\n            split.\n            - apply HeapUpd with (n := N); eauto...\n              eapply PtrUpd; eauto.\n            - constructor.\n              eapply PtrUpd; eauto. \n            - eapply subtype_well_type;\n              eauto. eapply SubTySubsume; eauto.\n          **\n            eapply well_typed_heap_in in H11. eauto.\n            destruct H11 as [N HMap].\n            split; eauto.\n            - apply HeapUpd with (n := N); eauto...\n            - eauto.\n            - eauto.\n            - eapply subtype_well_type;\n              eauto. eapply SubTyStructArrayField; eauto.\n        } \n      * destruct Eq as [? [? ?]]; subst.\n        inv H0. \n        ** \n          { destruct m'; [| specialize (H2 eq_refl); inv H2].\n            eapply (well_typed_heap_in_array n D H l h) in H11; eauto.\n            destruct H11 as [N HMap].\n            split.\n            - apply HeapUpd with (n := N); eauto...\n              eapply PtrUpd; eauto.\n            - constructor.\n              eapply PtrUpd; eauto.\n            - eapply (H13 l h). eauto.\n            - eapply H13. eauto.\n          }\n        ** \n          { clear H7. clear l h.\n            destruct m'; [| specialize (H2 eq_refl); inv H2].\n            eapply (well_typed_heap_in_array n D H l0 h0) in H11; eauto.\n            destruct H11 as [N HMap].\n            split.\n            - apply HeapUpd with (n := N); eauto...\n              eapply PtrUpd; eauto.\n            - constructor.\n              eapply PtrUpd; eauto.\n            - eapply (H13 l0 h0). eauto.\n            - eapply H13. eauto.\n          }\n    + destruct (IHHwt1 H6 eq_refl (in_hole e'0 E) H') as [HC HWT]; eauto.\n      split; eauto...\n    + destruct (IHHwt2 H8 eq_refl (in_hole e'0 E) H') as [HC HWT]; eauto.\n      split; eauto... \n  - inv Hreduces.\n    inv HHwf.\n    inv H7.\n    destruct E; inv H5; subst; simpl in*; subst; eauto.\n    + inv H8.\n    + assert (exists l0 h0, t = (TPtr m' (TArray l0 h0 t'))).\n      {\n        inv H2. exists l. exists h. reflexivity.\n        exists l0. exists h0. reflexivity. \n      }\n      destruct H4 as [l0 [h0 H4]].\n      rewrite H4 in *. clear H4 H2.\n      destruct E; inversion H6; simpl in *; subst.\n      * { (* Plus step *)\n          inv H8; split; eauto...\n          - inv Hwt1.\n            eapply TyAssign; eauto.\n            constructor.\n            cleanup.\n            \n            match goal with\n            | [ H : well_typed_lit _ _ _ _ _ |- _ ] =>\n              remember H as Backup; clear HeqBackup; inv H; eauto; try omega\n            end.\n\n            unfold allocate_meta in *.\n\n            inversion H2; subst b; subst ts; clear H0.\n            \n            eapply TyLitC; unfold allocate_meta in *; eauto.\n\n            intros k Hk.\n            \n            assert (Hyp: h0 - n2 - (l0 - n2) = h0 - l0) by omega.\n            rewrite Hyp in * ; clear Hyp.\n            inv H2.\n            destruct (H5 (n2 + k)) as [n' [t0 [HNth [HMap HWT]]]]; [omega | ].\n\n            exists n'. exists t0.\n\n            rewrite Z.add_assoc in HMap.\n\n            split; [ | split]; eauto.\n            + destruct (h0 - l0) eqn:HHL; simpl in *.\n              * rewrite Z.add_0_r in Hk.\n                destruct (Z.to_nat (n2 + k - l0)); inv HNth.\n              * assert (HR: k - (l0 - n2) = n2 + k - l0) by (zify; omega).\n                rewrite HR.\n                auto.\n              * destruct (Z.to_nat (n2 + k - l0)); inv HNth.\n            + apply scope_weakening_cons.\n\n              eapply scope_strengthening in HWT; eauto.\n              assert (HAdd : set_add eq_dec_nt (n1, TPtr Checked (TArray l0 h0 t'))\n                                     empty_scope =\n                             (n1, TPtr Checked (TArray l0 h0 t')) :: nil) by auto.\n              rewrite HAdd in HWT.\n              clear HAdd.\n\n              assert (HEmpty : empty_scope =\n                               set_remove_all (n1, TPtr Checked (TArray l0 h0 t')) \n                                             ((n1, TPtr Checked (TArray l0 h0 t')) :: nil)).\n              {\n                unfold set_remove_all.\n                destruct (eq_dec_nt (n1, TPtr Checked (TArray l0 h0 t'))\n                                    (n1, TPtr Checked (TArray l0 h0 t'))); auto.\n                congruence.\n              }\n              rewrite <- HEmpty in HWT.\n              auto.\n            + eapply SubTyRefl; eauto.\n          - inv Hwt1.\n            destruct m'.\n            + exfalso; eapply H14; eauto.\n            + specialize (H3 eq_refl). exfalso; inv H3.\n              \n         }\n      * destruct (IHHwt1 H10 eq_refl (in_hole e'0 E) H') as [HC HWT]; eauto.\n        split. eauto. eapply TyIndexAssign; eauto.\n        eapply SubTyRefl. eauto... eauto... \n      * destruct (IHHwt2 H12 eq_refl (in_hole e'0 E) H') as [HC HWT]; eauto.\n        split; eauto. eapply TyIndexAssign; eauto... eapply SubTyRefl.\n  Qed.\n\n(* ... for Blame *)\n\nCreate HintDb Blame.\n\nPrint heap_add_in_cardinal.\n\nLemma heap_wf_step : forall D F S H e S' H' e',\n    @structdef_wf D ->\n    heap_wf D H ->\n    @step D F S H e S' H' (RExpr e') ->\n    heap_wf D H'.\nProof.\n  intros D F S H e S' H' e' HD HHwf HS.\n  induction HS; eauto.\n  - assert (Heap.cardinal H' = Heap.cardinal H).\n      { rewrite H5. apply heap_add_in_cardinal. exists (na,ta). eauto. }\n    intro addr; split; intro Hyp.\n    + rewrite H5.\n      rewrite H6 in Hyp.\n      destruct (HHwf addr) as [HAddr HIn].\n      destruct (HAddr Hyp) as [v Hx].\n      destruct (Z.eq_dec addr n).\n      * subst.\n        exists (n1, ta). apply Heap.add_1. easy.\n      * exists v.\n        eapply Heap.add_2; eauto.\n    + rewrite H5 in Hyp.\n      destruct Hyp as [v Hv].\n      destruct (Z.eq_dec addr n).\n      * subst.\n        rewrite H6.\n        apply HHwf; auto.\n        exists (na,ta);easy.\n      * rewrite H6.\n        apply HHwf.\n        exists v.\n        apply Heap.add_3 in Hv; auto.\n  - apply alloc_correct with (Q := empty_theta) in H2; try easy.\n    apply cast_means_simple_type in H0. easy.\nQed.\n\nLemma heap_wt_step : forall D F Q S H e S' Q' H' e',\n    heap_wt_all D Q H ->\n    @step D F S H e S' H' (RExpr e') ->\n    heap_wt_all D Q' H'.\nProof.\nAdmitted.\n\n(*\nLemma expr_wf_subst :\n  forall D n t x e,\n    expr_wf D (ELit n t) ->\n    expr_wf D e ->\n    expr_wf D (subst x (ELit n t) e).\nProof.\n  intros D n t x e Hwf H.\n  inv Hwf.\n  induction H; simpl; eauto;\n    repeat (constructor; eauto).\n  - destruct (var_eq_dec x x0); repeat (constructor; eauto).\n  - destruct (var_eq_dec x x0); repeat (constructor; eauto).\nQed.\n*)\n\nLemma expr_wf_step : forall env D S H e S' H' e',\n    @expr_wf D fenv e -> stack_wt D S ->\n    @step D (fenv env) S H e S' H' (RExpr e') ->\n    @expr_wf D fenv e'.\nProof.\n  intros env D S H e S' H' e' Hwf Hswt HS.\n  inv HS; inv Hwf; eauto; try solve [repeat (constructor; eauto)].\n  apply Hswt in H7. constructor; try easy.\nAdmitted.\n\nLemma expr_wf_reduce : forall env D S H m e S' H' e',\n    @expr_wf D fenv e -> stack_wt D S ->\n    @reduce D (fenv env) S H e m S' H' (RExpr e') ->\n    @expr_wf D fenv e'.\nProof.\n  intros env D S H m e S' H' e' Hwf Hswt HR.\n  inv HR; auto.\n  induction E; subst; simpl in *; eauto;\n  try solve [inv Hwf; constructor; eauto].\n  - eapply expr_wf_step in H2; eauto.\nQed.  \n\nDefinition normal { D : structdef } {F:funid -> option (list (var * type) * type * expression * mode)}\n          (S:stack) (H : heap) (e : expression) : Prop :=\n  ~ exists m' S' H' r, @reduce D F S H e m' S' H' r.\n\nDefinition stuck { D : structdef } {F:funid -> option (list (var * type) * type * expression * mode)}\n        (S:stack) (H : heap) (r : result) : Prop :=\n  match r with\n  | RBounds => False\n  | RNull => False\n  | RExpr e => @normal D F S H e /\\ ~ value D e\n  end.\n\nInductive eval { D : structdef } {F:funid -> option (list (var * type) * type * expression * mode)} :\n    nat -> stack -> heap -> expression -> mode -> stack -> heap -> result -> Prop :=\n  | eval_refl   : forall n S H e m, eval n S H e m S H (RExpr e)\n  | eval_transC : forall n s H s' H' s'' H'' e e' r,\n      @reduce D F s H e Checked s' H' (RExpr e') ->\n      eval n s' H' e' Checked s'' H'' r ->\n      eval (S n) s H e Checked s'' H'' r\n  | eval_transU : forall n s H s' H' s'' H'' m' e e' r,\n      @reduce D F s H e Unchecked s' H' (RExpr e') ->\n      eval n s' H' e' m' s'' H'' r ->\n      eval (S n) s H e Unchecked s'' H'' r.\n\n\nLemma expr_wf_in_hole : forall E D e, expr_wf D fenv (in_hole e E) -> expr_wf D fenv e.\nProof.\n induction E; intros;simpl in *; try easy.\n inv H. apply IHE in H2. easy.\n inv H. apply IHE in H2. easy.\n inv H. apply IHE in H3. easy.\n inv H. apply IHE in H1. easy.\n inv H. apply IHE in H4. easy.\n inv H. apply IHE in H4. easy.\n inv H. apply IHE in H1. easy.\n inv H. apply IHE in H2. easy.\n inv H. apply IHE in H3. easy.\n inv H. apply IHE in H4. easy.\n inv H. apply IHE in H3. easy.\n inv H. apply IHE in H1. easy.\nQed.\n\n(* The Blame Theorem. *)\nTheorem blame : forall n D Q S H env e t m S' H' r,\n    @structdef_wf D ->\n    heap_wf D H ->\n    heap_wt_all D Q H ->\n    fun_wf D fenv ->\n    @expr_wf D fenv e ->\n    stack_wt D S ->\n    env_wt D env ->\n    theta_wt Q env S ->\n    stack_wf D Q env S ->\n    stack_heap_consistent D Q H S ->\n    @well_typed D fenv S H env Q Checked e t ->\n    @eval D (fenv env) n S H e m S' H' r ->\n    @stuck D (fenv env) S' H' r ->\n    m = Unchecked \\/ (exists E e0, r = RExpr (in_hole e0 E) /\\ mode_of E = Unchecked).\nProof.\n  induction n;\n  intros D Q S H env e t m S' H' r HDwf HHwf HHwt Hfun Hewf HSwt HEnv HQt HSwf HSHwf Hwt Heval Hstuck.\n  inv Heval. destruct m.\n  unfold stuck,normal in Hstuck.\n  destruct Hstuck.\n  specialize (progress D Q H' S' env Checked e t\n    HDwf HHwf Hfun Hewf HSwt HEnv HQt HSwf HSHwf Hwt) as eq1.\n  destruct eq1. easy.\n  destruct H1. unfold reduces in *. easy.\n  unfold unchecked in *. destruct H1. left. easy.\n  right. destruct H1 as [ea [Ea [X1 X2]]].\n  exists Ea. exists ea. split. rewrite X1. easy. easy.\n  left. easy.\n  inv Heval. destruct m.\n  unfold stuck,normal in Hstuck.\n  destruct Hstuck.\n  specialize (progress D Q H' S' env Checked e t\n    HDwf HHwf Hfun Hewf HSwt HEnv HQt HSwf HSHwf Hwt) as eq1.\n  destruct eq1. easy.\n  destruct H1. unfold reduces in *. easy.\n  unfold unchecked in *. destruct H1. left. easy.\n  right. destruct H1 as [ea [Ea [X1 X2]]].\n  exists Ea. exists ea. split. rewrite X1. easy. easy.\n  left. easy.\n  specialize (preservation e D S H env Q t s' H'0 e'\n     HDwf HHwf HHwt Hfun Hewf HSwt HEnv HQt HSwf HSHwf Hwt H2) as eq1.\n  destruct eq1 as [env' [Q' [HEnv' [HQt' [HSwf' [HSHwf' [HC [ta [Hwt' [tb [tc [X1 [X2 X3]]]]]]]]]]]]].\n  assert (fenv env' = fenv env).\n  rewrite (alpha_same D Q Q' S s' H H'0 env env' e e' t ta Checked); try easy.\n  apply (IHn D Q' s' H'0 env' e' ta Checked S' H' r); try easy.\n  inv H2.\n  eapply heap_wf_step; eauto.\n  inv H2.\n  eapply heap_wt_step;eauto.\n  eapply expr_wf_reduce;eauto.\n  inv H2.\n  eapply stack_simple_prop with (e := e0); eauto.\n  apply stack_wf_sub in HSwf. apply HSwf.\n  apply expr_wf_in_hole in Hewf. easy.\n  rewrite H0. easy.\n  rewrite H0. easy.\n  left. easy.\nQed.\n\n", "meta": {"author": "plum-umd", "repo": "checkedc", "sha": "9b03a0d490018936211da23796d7b6ec3539bc6f", "save_path": "github-repos/coq/plum-umd-checkedc", "path": "github-repos/coq/plum-umd-checkedc/checkedc-9b03a0d490018936211da23796d7b6ec3539bc6f/coq/CheckedC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23252493517189746}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        Coq.ZArith.ZArith\n        Coq.Lists.List\n        Coq.Strings.String\n        Coq.Arith.Mult.\n\nRequire Import\n        Fiat.Common\n        Fiat.Common.DecideableEnsembles\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Stores.Cache\n        Fiat.Narcissus.Formats.DomainNameOpt.\n\nRequire Import Bedrock.Word.\n\nSection DomainNameCache.\n\n  Open Scope list.\n\n  Definition association_list K V := list (K * V).\n\n  Fixpoint association_list_find_first {K V}\n           {K_eq : Query_eq K}\n           (l : association_list K V)\n           (k : K) : option V :=\n    match l with\n    | (k', v) :: l' => if A_eq_dec k k' then Some v else association_list_find_first l' k\n    | _ => None\n    end.\n\n  Fixpoint association_list_find_all {K V}\n           {K_eq : Query_eq K}\n           (l : association_list K V)\n           (k : K) : list V :=\n    match l with\n    | (k', v) :: l' => if A_eq_dec k k' then v :: association_list_find_all l' k\n                       else association_list_find_all l' k\n    | _ => nil\n    end.\n\n  Definition association_list_add {K V}\n           {K_eq : DecideableEnsembles.Query_eq K}\n           (l : association_list K V)\n           (k : K) (v : V) : list (K * V)  :=\n    (k, v) :: l.\n\n  Global Instance dns_list_cache : Cache :=\n    {| CacheFormat := option (word 17) * association_list string pointerT;\n       CacheDecode := option (word 17) * association_list pointerT string;\n       Equiv ce cd := fst ce = fst cd\n                      /\\ (snd ce) = (map (fun ps => match ps with (p, s) => (s, p) end) (snd cd))\n                      /\\ NoDup (map fst (snd cd))\n    |}%type.\n\n  Definition list_CacheFormat_empty : CacheFormat := (Some (wzero _), nil).\n  Definition list_CacheDecode_empty : CacheDecode := (Some (wzero _), nil).\n\n  Lemma list_cache_empty_Equiv : Equiv list_CacheFormat_empty list_CacheDecode_empty.\n  Proof.\n    simpl; intuition; simpl; econstructor.\n  Qed.\n\n  Local Opaque pow2.\n  Arguments natToWord : simpl never.\n  Arguments wordToNat : simpl never.\n\n  (* pointerT2Nat (Nat2pointerT (NPeano.div (wordToNat w) 8)) *)\n\n  Global Instance cacheAddNat : CacheAdd _ nat.\n  Proof.\n    refine {| addE ce n := (Ifopt (fst ce) as m Then\n                                                let n' := (wordToNat m) + n in\n                                                if Compare_dec.lt_dec n' (pow2 17)\n                                                then Some (natToWord _ n')\n                                                else None\n                                                       Else None, snd ce);\n              addD cd n := (Ifopt (fst cd) as m Then\n                                                let n' := (wordToNat m) + n in\n                                                if Compare_dec.lt_dec n' (pow2 17)\n                                                then Some (natToWord _ n')\n                                                else None\n                                                       Else None, snd cd) |}.\n    simpl; intuition eauto; destruct a; destruct a0;\n      simpl in *; eauto; try congruence.\n    injections.\n    find_if_inside; eauto.\n  Defined.\n\n  Global Instance Query_eq_string : Query_eq string :=\n    {| A_eq_dec := string_dec |}.\n\n  Global Instance : Query_eq pointerT :=\n    {| A_eq_dec := pointerT_eq_dec |}.\n\n  Global Instance cachePeekDNPointer : CachePeek _ (option pointerT).\n  Proof.\n    refine {| peekE ce := Ifopt (fst ce) as m Then Some (Nat2pointerT (wordToNat (wtl (wtl (wtl m))))) Else None;\n              peekD cd := Ifopt (fst cd) as m Then Some\n                                              (Nat2pointerT (wordToNat (wtl (wtl (wtl m)))))\n                                              Else None |}.\n    abstract (simpl; intros; intuition; rewrite H0; auto).\n  Defined.\n\n  Lemma cacheGetDNPointer_pf\n    : forall (ce : CacheFormat) (cd : CacheDecode)\n             (p : string) (q : pointerT),\n      Equiv ce cd ->\n      (association_list_find_first (snd cd) q = Some p <-> List.In q (association_list_find_all (snd ce) p)).\n  Proof.\n    intros [? ?] [? ?] ? ?; simpl; intuition eauto; subst.\n    - subst; induction a0; simpl in *; try congruence.\n      destruct a; simpl in *; find_if_inside; subst.\n      + inversion H2; subst; intros.\n        find_if_inside; subst; simpl; eauto.\n      + inversion H2; subst; intros.\n        find_if_inside; subst; simpl; eauto; congruence.\n    - subst; induction a0; simpl in *; intuition.\n      destruct a; simpl in *; find_if_inside.\n      + inversion H2; subst; intros.\n        find_if_inside; subst; simpl; eauto; try congruence.\n        apply IHa0 in H1; eauto.\n        exfalso; apply H3; revert H1; clear.\n        induction a0; simpl; intros; try congruence.\n        destruct a; find_if_inside; injections; auto.\n      + inversion H2; subst; intros.\n        find_if_inside; subst; simpl; eauto; try congruence.\n        simpl in H1; intuition eauto; subst.\n        congruence.\n  Qed.\n\n  Global Instance cacheGetDNPointer : CacheGet dns_list_cache string pointerT :=\n    {| getE ce p := @association_list_find_all string _ _ (snd ce) p;\n       getD ce p := association_list_find_first (snd ce) p;\n       get_correct := cacheGetDNPointer_pf |}.\n\n  Lemma cacheAddDNPointer_pf\n    : forall (ce : CacheFormat) (cd : CacheDecode) (t : string * pointerT),\n      Equiv ce cd ->\n      add_ptr_OK t ce cd ->\n      Equiv (fst ce, association_list_add (snd ce) (fst t) (snd t))\n            (fst cd, association_list_add (snd cd) (snd t) (fst t)).\n  Proof.\n    simpl; intuition eauto; simpl in *; subst; eauto;\n      unfold add_ptr_OK in *.\n    destruct t; simpl in *; simpl association_list_add; try econstructor; eauto.\n    clear H3; induction b0; simpl.\n    - intuition.\n    - simpl in H0; destruct a; find_if_inside;\n          try discriminate.\n        intuition.\n  Qed.\n\n  Global Instance cacheAddDNPointer\n    : CacheAdd_Guarded _ add_ptr_OK :=\n    {| addE_G ce sp := (fst ce, association_list_add (snd ce) (fst sp) (snd sp));\n       addD_G cd sp := (fst cd, association_list_add (snd cd) (snd sp) (fst sp));\n       add_correct_G := cacheAddDNPointer_pf\n    |}.\n\n  Lemma IndependentCaches :\n    forall env p (b : nat),\n      getD (addD env b) p = getD env p.\n  Proof.\n    simpl; intros; eauto.\n  Qed.\n\n  Lemma IndependentCaches' :\n    forall env p (b : nat),\n      getE (addE env b) p = getE env p.\n  Proof.\n    simpl; intros; eauto.\n  Qed.\n\n  Lemma IndependentCaches''' :\n    forall env b,\n      peekE (addE_G env b) = peekE env.\n  Proof.\n    simpl; intros; eauto.\n  Qed.\n\n  Lemma getDistinct :\n    forall env l p p',\n      p <> p'\n      -> getD (addD_G env (l, p)) p' = getD env p'.\n  Proof.\n    simpl; intros; eauto.\n    find_if_inside; try congruence.\n  Qed.\n\n  Lemma getDistinct' :\n    forall env l p p' l',\n      List.In p (getE (addE_G env (l', p')) l)\n      -> p = p' \\/ List.In p (getE env l).\n  Proof.\n    simpl in *; intros; intuition eauto.\n    find_if_inside; simpl in *; intuition eauto.\n  Qed.\n\n  Arguments NPeano.div : simpl never.\n\n  Lemma mult_pow2 :\n    forall m n,\n      pow2 m * pow2 n = pow2 (m + n).\n  Proof.\n    Local Transparent pow2.\n    induction m; simpl; intros.\n    - omega.\n    - rewrite <- IHm.\n      rewrite <- !plus_n_O.\n      rewrite Mult.mult_plus_distr_r; omega.\n  Qed.\n\n  Corollary mult_pow2_8 : forall n,\n      8 * (pow2 n) = pow2 (3 + n).\n  Proof.\n    intros; rewrite <- mult_pow2.\n    reflexivity.\n  Qed.\n\n  Local Opaque pow2.\n\n  Lemma pow2_div\n    : forall m n,\n      lt (m + n * 8) (pow2 17)\n      -> lt (NPeano.div m 8) (pow2 14).\n  Proof.\n    intros.\n    eapply (NPeano.Nat.mul_lt_mono_pos_l 8); try omega.\n    rewrite mult_pow2_8.\n    eapply le_lt_trans.\n    apply NPeano.Nat.mul_div_le; try omega.\n    simpl.\n    omega.\n  Qed.\n\n  Lemma addPeekNone :\n    forall env n,\n      peekD env = None\n      -> peekD (addD env n) = None.\n  Proof.\n    simpl; intros.\n    destruct (fst env); simpl in *; congruence.\n  Qed.\n\n  Lemma wtl_div\n    : forall n (w : word (S (S (S n)))),\n      wordToNat (wtl (wtl (wtl w))) = NPeano.div (wordToNat w) 8.\n  Proof.\n    intros.\n    pose proof (shatter_word_S w); destruct_ex; subst.\n    pose proof (shatter_word_S x0); destruct_ex; subst.\n    pose proof (shatter_word_S x2); destruct_ex; subst.\n    simpl wtl.\n    rewrite <- (NPeano.Nat.div_div _ 2 4) by omega.\n    rewrite <- (NPeano.Nat.div_div _ 2 2) by omega.\n    rewrite <- !NPeano.Nat.div2_div.\n    rewrite !div2_WS.\n    reflexivity.\n  Qed.\n\n  Lemma mult_lt_compat_l'\n    : forall (m n p : nat),\n      lt 0 p\n      -> lt (p * n)  (p * m)\n      -> lt n m.\n  Proof.\n    induction m; simpl; intros; try omega.\n    rewrite (mult_comm p 0) in H0; simpl in *; try omega.\n    destruct p; try (exfalso; auto with arith; omega).\n    inversion H0.\n    rewrite (mult_comm p (S m)) in H0.\n    simpl in H0.\n    destruct n; try omega.\n    rewrite (mult_comm p (S n)) in H0; simpl in H0.\n    apply plus_lt_reg_l in H0.\n    rewrite <- NPeano.Nat.succ_lt_mono.\n    eapply (IHm n p); try eassumption; try omega.\n    rewrite mult_comm.\n    rewrite (mult_comm p m); auto.\n  Qed.\n\n  Lemma mult_lt_compat_l''\n    : forall (p m k n : nat),\n      lt 0 p\n      -> lt n m\n      -> lt k p\n      -> lt ((p * n) + k) (p * m).\n  Proof.\n    induction p; intros; try omega.\n    simpl.\n    inversion H; subst; simpl.\n    inversion H1; subst; omega.\n    destruct k; simpl.\n    - rewrite <- plus_n_O.\n      eapply (mult_lt_compat_l n m (S p)); auto.\n    - assert (lt (p * n + k) (p * m)) by\n          (apply IHp; try omega).\n      omega.\n  Qed.\n\n  Lemma addPeekNone' :\n    forall env n m,\n      peekD env = Some m\n      -> ~ lt (n + (pointerT2Nat m)) (pow2 14)\n      -> peekD (addD env (n * 8)) = None.\n  Proof.\n    simpl; intros; subst.\n    destruct (fst env); simpl in *; try discriminate.\n    injections.\n    find_if_inside; try reflexivity.\n    unfold If_Opt_Then_Else.\n    rewrite !wtl_div in *.\n    exfalso; apply H0.\n    rewrite pointerT2Nat_Nat2pointerT in *;\n      try (eapply pow2_div; eassumption).\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    destruct n; try omega.\n    exfalso; apply H0.\n    simpl.\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    - eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      simpl in l.\n      rewrite mult_pow2_8; simpl; omega.\n    - rewrite mult_plus_distr_l.\n      assert (8 <> 0) by omega.\n      pose proof (NPeano.Nat.mul_div_le (wordToNat w) 8 H).\n      apply le_lt_trans with (8 * S n + (wordToNat w)).\n      omega.\n      rewrite mult_pow2_8; simpl; omega.\n  Qed.\n\n  Lemma addPeekSome :\n    forall env n m,\n      peekD env = Some m\n      -> lt (n + (pointerT2Nat m)) (pow2 14)\n      -> exists p',\n          peekD (addD env (n * 8)) = Some p'\n          /\\ pointerT2Nat p' = n + (pointerT2Nat m).\n  Proof.\n    simpl; intros; subst.\n    destruct (fst env); simpl in *; try discriminate.\n    injections.\n    find_if_inside.\n    - rewrite !wtl_div in *.\n      rewrite pointerT2Nat_Nat2pointerT in *;\n        try (eapply pow2_div; eassumption).\n      unfold If_Opt_Then_Else.\n      eexists; split; try reflexivity.\n      rewrite wtl_div.\n      rewrite wordToNat_natToWord_idempotent.\n      rewrite pointerT2Nat_Nat2pointerT in *; try omega.\n      rewrite NPeano.Nat.div_add; try omega.\n      rewrite NPeano.Nat.div_add; try omega.\n      apply Nomega.Nlt_in.\n      rewrite Nnat.Nat2N.id, Npow2_nat; auto.\n    - exfalso; apply n0.\n      rewrite !wtl_div in *.\n      rewrite pointerT2Nat_Nat2pointerT in *.\n      rewrite (NPeano.div_mod (wordToNat w) 8); try omega.\n      pose proof (mult_pow2_8 14) as H'; simpl plus in H'; rewrite <- H'.\n      replace (8 * NPeano.div (wordToNat w) 8 + NPeano.modulo (wordToNat w) 8 + n * 8)\n      with (8 * (NPeano.div (wordToNat w) 8 + n) + NPeano.modulo (wordToNat w) 8)\n        by omega.\n      eapply mult_lt_compat_l''; try omega.\n      apply NPeano.Nat.mod_upper_bound; omega.\n      eapply (mult_lt_compat_l' _ _ 8); try omega.\n      eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      rewrite mult_pow2_8; simpl.\n      apply wordToNat_bound.\n  Qed.\n\n  Lemma addZeroPeek :\n    forall xenv,\n      peekD xenv = peekD (addD xenv 0).\n  Proof.\n    simpl; intros.\n    destruct (fst xenv); simpl; eauto.\n    find_if_inside; unfold If_Opt_Then_Else.\n    rewrite <- plus_n_O, natToWord_wordToNat; auto.\n    exfalso; apply n.\n    rewrite <- plus_n_O.\n    apply wordToNat_bound.\n  Qed.\n\n  Local Opaque wordToNat.\n  Local Opaque natToWord.\n\n  Lemma boundPeekSome :\n    forall env n m m',\n      peekD env = Some m\n      -> peekD (addD env (n * 8)) = Some m'\n      -> lt (n + (pointerT2Nat m)) (pow2 14).\n  Proof.\n    simpl; intros; subst.\n    destruct (fst env); simpl in *; try discriminate.\n    injections.\n    find_if_inside; unfold If_Opt_Then_Else in *; try congruence.\n    injections.\n    rewrite !wtl_div in *.\n    rewrite pointerT2Nat_Nat2pointerT in *;\n      try (eapply pow2_div; eassumption).\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    - rewrite mult_plus_distr_l.\n      assert (8 <> 0) by omega.\n      pose proof (NPeano.Nat.mul_div_le (wordToNat w) 8 H).\n      apply le_lt_trans with (8 * n + (wordToNat w)).\n      omega.\n      rewrite mult_pow2_8.\n      simpl plus at -1.\n      omega.\n  Qed.\n\n  Lemma addPeekESome :\n    forall env n m,\n      peekE env = Some m\n      -> lt (n + (pointerT2Nat m)) (pow2 14)%nat\n      -> exists p',\n          peekE (addE env (n * 8)) = Some p'\n          /\\ pointerT2Nat p' = n + (pointerT2Nat m).\n  Proof.\n    simpl; intros; subst.\n    destruct (fst env); simpl in *; try discriminate.\n    injections.\n    find_if_inside.\n    - rewrite !wtl_div in *.\n      rewrite pointerT2Nat_Nat2pointerT in *;\n        try (eapply pow2_div; eassumption).\n      unfold If_Opt_Then_Else.\n      eexists; split; try reflexivity.\n      rewrite wtl_div.\n      rewrite wordToNat_natToWord_idempotent.\n      rewrite pointerT2Nat_Nat2pointerT in *; try omega.\n      rewrite NPeano.Nat.div_add; try omega.\n      rewrite NPeano.Nat.div_add; try omega.\n      apply Nomega.Nlt_in.\n      rewrite Nnat.Nat2N.id, Npow2_nat; auto.\n    - exfalso; apply n0.\n      rewrite !wtl_div in *.\n      rewrite pointerT2Nat_Nat2pointerT in *.\n      rewrite (NPeano.div_mod (wordToNat w) 8); try omega.\n      pose proof (mult_pow2_8 14) as H'; simpl plus in H'; rewrite <- H'.\n      replace (8 * NPeano.div (wordToNat w) 8 + NPeano.modulo (wordToNat w) 8 + n * 8)\n      with (8 * (NPeano.div (wordToNat w) 8 + n) + NPeano.modulo (wordToNat w) 8)\n        by omega.\n      eapply mult_lt_compat_l''; try omega.\n      apply NPeano.Nat.mod_upper_bound; omega.\n      eapply (mult_lt_compat_l' _ _ 8); try omega.\n      eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      rewrite mult_pow2_8; simpl.\n      apply wordToNat_bound.\n  Qed.\n\n  Lemma boundPeekESome :\n    forall env n m m',\n      peekE env = Some m\n      -> peekE (addE env (n * 8)) = Some m'\n      -> lt (n + (pointerT2Nat m)) (pow2 14).\n  Proof.\n    simpl; intros; subst.\n    destruct (fst env); simpl in *; try discriminate.\n    injections.\n    find_if_inside; unfold If_Opt_Then_Else in *; try congruence.\n    injections.\n    rewrite !wtl_div in *.\n    rewrite pointerT2Nat_Nat2pointerT in *;\n      try (eapply pow2_div; eassumption).\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    - rewrite mult_plus_distr_l.\n      assert (8 <> 0) by omega.\n      pose proof (NPeano.Nat.mul_div_le (wordToNat w) 8 H).\n      apply le_lt_trans with (8 * n + (wordToNat w)).\n      omega.\n      rewrite mult_pow2_8.\n      simpl plus at -1.\n      omega.\n  Qed.\n\n  Lemma addPeekENone :\n    forall env n,\n      peekE env = None\n      -> peekE (addE env n) = None.\n  Proof.\n    simpl; intros.\n    destruct (fst env); simpl in *; congruence.\n  Qed.\n\n  Lemma addPeekENone' :\n    forall env n m,\n      peekE env = Some m\n      -> ~ lt (n + (pointerT2Nat m)) (pow2 14)%nat\n      -> peekE (addE env (n * 8)) = None.\n  Proof.\n    simpl; intros; subst.\n    destruct (fst env); simpl in *; try discriminate.\n    injections.\n    find_if_inside; try reflexivity.\n    unfold If_Opt_Then_Else.\n    rewrite !wtl_div in *.\n    exfalso; apply H0.\n    rewrite pointerT2Nat_Nat2pointerT in *;\n      try (eapply pow2_div; eassumption).\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    destruct n; try omega.\n    exfalso; apply H0.\n    simpl.\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    - eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      simpl in l.\n      rewrite mult_pow2_8; simpl; omega.\n    - rewrite mult_plus_distr_l.\n      assert (8 <> 0) by omega.\n      pose proof (NPeano.Nat.mul_div_le (wordToNat w) 8 H).\n      apply le_lt_trans with (8 * S n + (wordToNat w)).\n      omega.\n      rewrite mult_pow2_8; simpl; omega.\n  Qed.\n\n  Lemma addZeroPeekE :\n    forall xenv,\n      peekE xenv = peekE (addE xenv 0).\n  Proof.\n    simpl; intros.\n    destruct (fst xenv); simpl; eauto.\n    find_if_inside; unfold If_Opt_Then_Else.\n    rewrite <- plus_n_O, natToWord_wordToNat; auto.\n    exfalso; apply n.\n    rewrite <- plus_n_O.\n    apply wordToNat_bound.\n  Qed.\n\n  Import Vectors.Vector.VectorNotations.\n\n  Definition GoodCache (env : CacheDecode) :=\n    forall domain p,\n      getD env p = Some domain\n      -> ValidDomainName domain\n         /\\ (String.length domain > 0)%nat\n         /\\ (getD env p = Some domain\n             -> forall p' : pointerT, peekD env = Some p' -> lt (pointerT2Nat p) (pointerT2Nat p')).\n\n  Lemma cacheIndependent_add\n    : forall (b : nat) (cd : CacheDecode),\n      GoodCache cd -> GoodCache (addD cd b).\n  Proof.\n    unfold GoodCache; intros.\n    rewrite IndependentCaches in *;\n      eapply H in H0; intuition eauto.\n    simpl in *.\n    destruct (fst cd); simpl in *; try discriminate.\n    find_if_inside; simpl in *; try discriminate.\n    injections.\n    pose proof (H4 _ (eq_refl _)).\n    eapply lt_le_trans; eauto.\n    assert (wordToNat w / 8 < pow2 14)%nat. {\n      eapply (mult_lt_compat_l' _ _ 8); try omega.\n      eapply le_lt_trans.\n      apply NPeano.Nat.mul_div_le; omega.\n      rewrite mult_pow2_8; simpl; omega.\n    }\n    rewrite !pointerT2Nat_Nat2pointerT in *;\n      rewrite !wtl_div in *; auto.\n    rewrite wordToNat_natToWord_idempotent.\n    apply NPeano.Nat.div_le_mono; omega.\n    apply Nomega.Nlt_in.\n    rewrite Nnat.Nat2N.id, Npow2_nat; auto.\n    eapply (mult_lt_compat_l' _ _ 8); try omega.\n    eapply le_lt_trans.\n    apply NPeano.Nat.mul_div_le; omega.\n    rewrite wordToNat_natToWord_idempotent.\n    rewrite mult_pow2_8; simpl; omega.\n    apply Nomega.Nlt_in.\n    rewrite Nnat.Nat2N.id, Npow2_nat; auto.\n  Qed.\n\n  Lemma cacheIndependent_add_2\n    : forall cd p (b : nat) domain,\n      GoodCache cd\n      -> getD (addD cd b) p = Some domain\n      -> forall pre label post : string,\n          domain = (pre ++ label ++ post)%string ->\n          ValidLabel label -> (String.length label <= 63)%nat.\n  Proof.\n    unfold GoodCache; intros.\n    rewrite IndependentCaches in *; eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_3\n    : forall cd p (b : nat) domain,\n      GoodCache cd\n      -> getD (addD cd b) p = Some domain\n      -> ValidDomainName domain.\n  Proof.\n    unfold GoodCache; intros.\n    rewrite IndependentCaches in *; eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_4\n    : forall cd p (b : nat) domain,\n      GoodCache cd\n      -> getD (addD cd b) p = Some domain\n      -> gt (String.length domain) 0.\n  Proof.\n    unfold GoodCache; intros.\n    rewrite IndependentCaches in *; eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_5\n    : forall cd p domain,\n      GoodCache cd\n      -> getD cd p = Some domain\n      -> ValidDomainName domain.\n  Proof.\n    unfold GoodCache; intros.\n    eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_6\n    : forall cd p domain,\n      GoodCache cd\n      -> getD cd p = Some domain\n      -> gt (String.length domain) 0.\n  Proof.\n    unfold GoodCache; intros.\n    eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_7\n    : forall cd p domain,\n      GoodCache cd\n      -> getD cd p = Some domain\n      -> forall pre label post : string,\n          domain = (pre ++ label ++ post)%string ->\n          ValidLabel label -> (String.length label <= 63)%nat.\n  Proof.\n    unfold GoodCache; intros.\n    eapply H; eauto.\n  Qed.\n\n  Lemma ptr_eq_dec :\n    forall (p p' : pointerT),\n      {p = p'} + {p <> p'}.\n  Proof.\n    decide equality.\n    apply weq.\n    destruct a; destruct s; simpl in *.\n    destruct (weq x x0); subst.\n    left; apply ptr_eq; reflexivity.\n    right; unfold not; intros; apply n.\n    congruence.\n  Qed.\n\n  Lemma cacheIndependent_add_8\n    : forall cd p p0 domain domain',\n      GoodCache cd\n      -> ValidDomainName domain' /\\ (String.length domain' > 0)%nat\n      -> getD (addD_G cd (domain', p0)) p = Some domain\n      -> forall pre label post : string,\n          domain = (pre ++ label ++ post)%string ->\n          ValidLabel label -> (String.length label <= 63)%nat.\n  Proof.\n    unfold GoodCache; simpl; intros.\n    destruct (pointerT_eq_dec p p0); subst.\n    - injections; intuition.\n      eapply H1; eauto.\n    - eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_9\n    : forall cd p p0 domain domain',\n      GoodCache cd\n      -> ValidDomainName domain' /\\ (String.length domain' > 0)%nat\n      -> getD (addD_G cd (domain', p0)) p = Some domain\n      -> ValidDomainName domain.\n  Proof.\n    unfold GoodCache; simpl; intros.\n    destruct (pointerT_eq_dec p p0); subst.\n    - injections; intuition.\n    - eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_10\n    : forall cd p p0 domain domain',\n      GoodCache cd\n      -> ValidDomainName domain' /\\ (String.length domain' > 0)%nat\n      -> getD (addD_G cd (domain', p0)) p = Some domain\n      -> gt (String.length domain) 0.\n  Proof.\n    unfold GoodCache; simpl; intros.\n    destruct (pointerT_eq_dec p p0); subst.\n    - injections; intuition.\n    - eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_11\n    : forall (b : nat)\n             (cd : CacheDecode)\n             (domain : string)\n             (p : pointerT),\n      GoodCache cd\n      -> getD (addD cd b) p = Some domain ->\n      forall p' : pointerT, peekD (addD cd b) = Some p' -> lt (pointerT2Nat p) (pointerT2Nat p').\n  Proof.\n    intros.\n    eapply (cacheIndependent_add b) in H.\n    eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_12\n    : forall (p : pointerT) (cd : CacheDecode) (domain : string),\n      GoodCache cd ->\n      getD cd p = Some domain\n      -> forall p' : pointerT,\n          peekD cd = Some p'\n          -> lt (pointerT2Nat p) (pointerT2Nat p').\n  Proof.\n    unfold GoodCache; simpl; intros; intuition eauto.\n    eapply H; eauto.\n  Qed.\n\n  Lemma cacheIndependent_add_13\n    : forall  (env : CacheDecode)\n              (p : pointerT)\n              (domain : string)\n              (H : GoodCache env)\n              (H0 : ValidDomainName domain /\\ (String.length domain > 0)%nat)\n              (H1 : getD env p = None)\n              (H2 : forall p' : pointerT, peekD env = Some p' -> lt (pointerT2Nat p) (pointerT2Nat p'))\n              (domain0 : string)\n              (p0 : pointerT)\n              (H3 : getD (addD_G env (domain, p)) p0 = Some domain0)\n              (p' : pointerT),\n      peekD (addD_G env (domain, p)) = Some p'\n      -> lt (pointerT2Nat p0) (pointerT2Nat p').\n  Proof.\n    simpl; intros.\n    destruct (fst env) eqn: ?; simpl in *; try discriminate.\n    find_if_inside; subst.\n    - injections.\n      apply (H2 _ (eq_refl _)).\n    - injections.\n      pose proof (H2 _ (eq_refl _)).\n      unfold GoodCache in *; intuition.\n      eapply H; simpl.\n      eassumption.\n      eassumption.\n      rewrite Heqo; simpl; reflexivity.\n  Qed.\n\n  Lemma addD_addD_plus :\n    forall (cd : CacheDecode) (n m : nat), addD (addD cd n) m = addD cd (n + m).\n  Proof.\n    simpl; intros.\n    destruct (fst cd); simpl; eauto.\n    repeat (find_if_inside; simpl); eauto.\n    f_equal; f_equal.\n    rewrite !natToWord_plus.\n    rewrite !natToWord_wordToNat.\n    rewrite wplus_assoc; reflexivity.\n    rewrite !natToWord_plus in l0.\n    rewrite !natToWord_wordToNat in l0.\n    exfalso.\n    apply n0.\n    rewrite <- (natToWord_wordToNat w) in l0.\n    rewrite <- natToWord_plus in l0.\n    rewrite wordToNat_natToWord_idempotent in l0.\n    omega.\n    apply Nomega.Nlt_in; rewrite Nnat.Nat2N.id, Npow2_nat; assumption.\n    exfalso.\n    apply n0.\n    rewrite <- (natToWord_wordToNat w).\n    rewrite !natToWord_plus.\n    rewrite !wordToNat_natToWord_idempotent.\n    rewrite <- natToWord_plus.\n    rewrite !wordToNat_natToWord_idempotent.\n    omega.\n    apply Nomega.Nlt_in; rewrite Nnat.Nat2N.id, Npow2_nat; assumption.\n    apply Nomega.Nlt_in; rewrite Nnat.Nat2N.id, Npow2_nat; omega.\n    omega.\n  Qed.\n\n  Lemma addE_addE_plus :\n    forall (cd : CacheFormat) (n m : nat), addE (addE cd n) m = addE cd (n + m).\n  Proof.\n    simpl; intros.\n    destruct (fst cd); simpl; eauto.\n    repeat (find_if_inside; simpl); eauto.\n    f_equal; f_equal.\n    rewrite !natToWord_plus.\n    rewrite !natToWord_wordToNat.\n    rewrite wplus_assoc; reflexivity.\n    rewrite !natToWord_plus in l0.\n    rewrite !natToWord_wordToNat in l0.\n    exfalso.\n    apply n0.\n    rewrite <- (natToWord_wordToNat w) in l0.\n    rewrite <- natToWord_plus in l0.\n    rewrite wordToNat_natToWord_idempotent in l0.\n    omega.\n    apply Nomega.Nlt_in; rewrite Nnat.Nat2N.id, Npow2_nat; assumption.\n    exfalso.\n    apply n0.\n    rewrite <- (natToWord_wordToNat w).\n    rewrite !natToWord_plus.\n    rewrite !wordToNat_natToWord_idempotent.\n    rewrite <- natToWord_plus.\n    rewrite !wordToNat_natToWord_idempotent.\n    omega.\n    apply Nomega.Nlt_in; rewrite Nnat.Nat2N.id, Npow2_nat; assumption.\n    apply Nomega.Nlt_in; rewrite Nnat.Nat2N.id, Npow2_nat; omega.\n    omega.\n  Qed.\n\nEnd DomainNameCache.\n\nLtac solve_GoodCache_inv _ :=\n  lazymatch goal with\n    |- cache_inv_Property ?Z _ =>\n    unify Z GoodCache;\n    unfold cache_inv_Property; repeat split;\n    eauto using cacheIndependent_add, cacheIndependent_add_2, cacheIndependent_add_4, cacheIndependent_add_6, cacheIndependent_add_7, cacheIndependent_add_8, cacheIndependent_add_10, cacheIndependent_add_11, cacheIndependent_add_12, cacheIndependent_add_13;\n    try match goal with\n          H : _ = _ |- _ =>\n          try solve [ eapply cacheIndependent_add_3 in H; intuition eauto ];\n          try solve [ eapply cacheIndependent_add_9 in H; intuition eauto ];\n          try solve [ eapply cacheIndependent_add_5 in H; intuition eauto ]\n        end;\n    try solve [instantiate (1 := fun _ => True); exact I]\n  end.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Narcissus/Stores/DomainNameStore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23252493517189743}}
{"text": "(* Default settings (from HsToCoq.Coq.Preamble) *)\n\nGeneralizable All Variables.\n\nUnset Implicit Arguments.\nSet Maximal Implicit Insertion.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Coq.Program.Tactics.\nRequire Coq.Program.Wf.\n\n(* Preamble *)\n\nRequire String BitTerminationProofs.\nImport String.StringSyntax.\n\n(* Converted imports: *)\n\nRequire Coq.Init.Peano.\nRequire Coq.NArith.BinNat.\nRequire Coq.Numbers.BinNums.\nRequire Data.Bits.\nRequire Data.Foldable.\nRequire Data.Maybe.\nRequire Data.Tuple.\nRequire GHC.Base.\nRequire GHC.Err.\nRequire GHC.Num.\nRequire GHC.Wf.\nRequire Utils.Containers.Internal.BitUtil.\nImport Data.Bits.Notations.\nImport GHC.Base.Notations.\nImport GHC.Num.Notations.\n\n(* Converted type declarations: *)\n\nDefinition Prefix :=\n  Coq.Numbers.BinNums.N.\n\nDefinition Nat :=\n  Coq.Numbers.BinNums.N.\n\nDefinition Mask :=\n  Coq.Numbers.BinNums.N.\n\nDefinition Key :=\n  Coq.Numbers.BinNums.N%type.\n\nDefinition BitMap :=\n  Coq.Numbers.BinNums.N.\n\nInductive IntSet : Type\n  := | Bin : Prefix -> Mask -> IntSet -> IntSet -> IntSet\n  |  Tip : Prefix -> BitMap -> IntSet\n  |  Nil : IntSet.\n\nInductive Stack : Type\n  := | Push : Prefix -> IntSet -> Stack -> Stack\n  |  Nada : Stack.\n\nInstance Default__IntSet : GHC.Err.Default IntSet :=\n  GHC.Err.Build_Default _ Nil.\n\nInstance Default__Stack : GHC.Err.Default Stack := GHC.Err.Build_Default _ Nada.\n\n(* Midamble *)\n\n(** Additional definitions for termination proof *)\n\nFixpoint size_nat (t : IntSet) : nat :=\n  match t with\n  | Bin _ _ l r => S (size_nat l + size_nat r)%nat\n  | Tip _ bm => 0\n  | Nil => 0\n  end.\n\nRequire Omega.\nLtac termination_by_omega :=\n  Coq.Program.Tactics.program_simpl;\n  simpl;Omega.omega.\n\n\nRequire Import Coq.NArith.NArith.\n(* Z.ones 6 = 64-1 *)\n(* Definition suffixBitMask := Coq.NArith.BinNat.N.ones 6%N. *)\n\n(* Converted value declarations: *)\n\nDefinition branchMask : Prefix -> Prefix -> Mask :=\n  fun p1 p2 =>\n    Coq.NArith.BinNat.N.pow 2 (Coq.NArith.BinNat.N.log2 (Coq.NArith.BinNat.N.lxor p1\n                                                                                  p2)).\n\nDefinition maskW : Nat -> Nat -> Prefix :=\n  fun i m => Coq.NArith.BinNat.N.ldiff i (2 * m - 1 % N).\n\nDefinition mask : Coq.Numbers.BinNums.N -> Mask -> Prefix :=\n  fun i m => maskW (i) (m).\n\nDefinition zero : Coq.Numbers.BinNums.N -> Mask -> bool :=\n  fun i m => ((i) Data.Bits..&.(**) (m)) GHC.Base.== #0.\n\nDefinition link : Prefix -> IntSet -> Prefix -> IntSet -> IntSet :=\n  fun p1 t1 p2 t2 =>\n    let m := branchMask p1 p2 in\n    let p := mask p1 m in if zero p1 m : bool then Bin p m t1 t2 else Bin p m t2 t1.\n\nDefinition nomatch : Coq.Numbers.BinNums.N -> Prefix -> Mask -> bool :=\n  fun i p m => (mask i m) GHC.Base./= p.\n\nFixpoint insertBM (arg_0__ : Prefix) (arg_1__ : BitMap) (arg_2__ : IntSet)\n           : IntSet\n           := match arg_0__, arg_1__, arg_2__ with\n              | kx, bm, (Bin p m l r as t) =>\n                  if nomatch kx p m : bool then link kx (Tip kx bm) p t else\n                  if zero kx m : bool then Bin p m (insertBM kx bm l) r else\n                  Bin p m l (insertBM kx bm r)\n              | kx, bm, (Tip kx' bm' as t) =>\n                  if kx' GHC.Base.== kx : bool then Tip kx' (bm Data.Bits..|.(**) bm') else\n                  link kx (Tip kx bm) kx' t\n              | kx, bm, Nil => Tip kx bm\n              end.\n\nDefinition shorter : Mask -> Mask -> bool :=\n  fun m1 m2 => (m1) GHC.Base.> (m2).\n\nProgram Fixpoint union (arg_0__ arg_1__ : IntSet) {measure (size_nat arg_0__ +\n                        size_nat arg_1__)} : IntSet\n                   := match arg_0__, arg_1__ with\n                      | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n                          let union2 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then link p1 t1 p2 t2 else\n                            if Bool.Sumbool.sumbool_of_bool (zero p1 m2)\n                            then Bin p2 m2 (union t1 l2) r2 else\n                            Bin p2 m2 l2 (union t1 r2) in\n                          let union1 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then link p1 t1 p2 t2 else\n                            if Bool.Sumbool.sumbool_of_bool (zero p2 m1)\n                            then Bin p1 m1 (union l1 t2) r1 else\n                            Bin p1 m1 l1 (union r1 t2) in\n                          if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then union1 else\n                          if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then union2 else\n                          if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n                          then Bin p1 m1 (union l1 l2) (union r1 r2) else\n                          link p1 t1 p2 t2\n                      | (Bin _ _ _ _ as t), Tip kx bm => insertBM kx bm t\n                      | (Bin _ _ _ _ as t), Nil => t\n                      | Tip kx bm, t => insertBM kx bm t\n                      | Nil, t => t\n                      end.\nSolve Obligations with (termination_by_omega).\n\nLocal Definition Semigroup__IntSet_op_zlzlzgzg__ : IntSet -> IntSet -> IntSet :=\n  union.\n\nProgram Instance Semigroup__IntSet : GHC.Base.Semigroup IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zlzlzgzg____ := Semigroup__IntSet_op_zlzlzgzg__ |}.\n\nLocal Definition Monoid__IntSet_mappend : IntSet -> IntSet -> IntSet :=\n  _GHC.Base.<<>>_.\n\nDefinition empty : IntSet :=\n  Nil.\n\nDefinition unions {f} `{Data.Foldable.Foldable f} : f IntSet -> IntSet :=\n  fun xs => Data.Foldable.foldl' union empty xs.\n\nLocal Definition Monoid__IntSet_mconcat : list IntSet -> IntSet :=\n  unions.\n\nLocal Definition Monoid__IntSet_mempty : IntSet :=\n  empty.\n\nProgram Instance Monoid__IntSet : GHC.Base.Monoid IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.mappend__ := Monoid__IntSet_mappend ;\n           GHC.Base.mconcat__ := Monoid__IntSet_mconcat ;\n           GHC.Base.mempty__ := Monoid__IntSet_mempty |}.\n\n(* Skipping all instances of class `Data.Data.Data', including\n   `Data.IntSet.Internal.Data__IntSet' *)\n\n(* Skipping all instances of class `GHC.Exts.IsList', including\n   `Data.IntSet.Internal.IsList__IntSet' *)\n\nFixpoint equal (arg_0__ arg_1__ : IntSet) : bool\n           := match arg_0__, arg_1__ with\n              | Bin p1 m1 l1 r1, Bin p2 m2 l2 r2 =>\n                  andb (m1 GHC.Base.== m2) (andb (p1 GHC.Base.== p2) (andb (equal l1 l2) (equal r1\n                                                                            r2)))\n              | Tip kx1 bm1, Tip kx2 bm2 => andb (kx1 GHC.Base.== kx2) (bm1 GHC.Base.== bm2)\n              | Nil, Nil => true\n              | _, _ => false\n              end.\n\nLocal Definition Eq___IntSet_op_zeze__ : IntSet -> IntSet -> bool :=\n  fun t1 t2 => equal t1 t2.\n\nFixpoint nequal (arg_0__ arg_1__ : IntSet) : bool\n           := match arg_0__, arg_1__ with\n              | Bin p1 m1 l1 r1, Bin p2 m2 l2 r2 =>\n                  orb (m1 GHC.Base./= m2) (orb (p1 GHC.Base./= p2) (orb (nequal l1 l2) (nequal r1\n                                                                         r2)))\n              | Tip kx1 bm1, Tip kx2 bm2 => orb (kx1 GHC.Base./= kx2) (bm1 GHC.Base./= bm2)\n              | Nil, Nil => false\n              | _, _ => true\n              end.\n\nLocal Definition Eq___IntSet_op_zsze__ : IntSet -> IntSet -> bool :=\n  fun t1 t2 => nequal t1 t2.\n\nProgram Instance Eq___IntSet : GHC.Base.Eq_ IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zeze____ := Eq___IntSet_op_zeze__ ;\n           GHC.Base.op_zsze____ := Eq___IntSet_op_zsze__ |}.\n\nDefinition indexOfTheOnlyBit :=\n  fun x => Coq.NArith.BinNat.N.log2 x.\n\nDefinition revNat : Nat -> Nat :=\n  fun x1 =>\n    let 'x2 := ((Utils.Containers.Internal.BitUtil.shiftRL x1 #1) Data.Bits..&.(**)\n                  #6148914691236517205) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x1 Data.Bits..&.(**)\n                                                             #6148914691236517205) #1) in\n    let 'x3 := ((Utils.Containers.Internal.BitUtil.shiftRL x2 #2) Data.Bits..&.(**)\n                  #3689348814741910323) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x2 Data.Bits..&.(**)\n                                                             #3689348814741910323) #2) in\n    let 'x4 := ((Utils.Containers.Internal.BitUtil.shiftRL x3 #4) Data.Bits..&.(**)\n                  #1085102592571150095) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x3 Data.Bits..&.(**)\n                                                             #1085102592571150095) #4) in\n    let 'x5 := ((Utils.Containers.Internal.BitUtil.shiftRL x4 #8) Data.Bits..&.(**)\n                  #71777214294589695) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x4 Data.Bits..&.(**)\n                                                             #71777214294589695) #8) in\n    let 'x6 := ((Utils.Containers.Internal.BitUtil.shiftRL x5 #16) Data.Bits..&.(**)\n                  #281470681808895) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x5 Data.Bits..&.(**)\n                                                             #281470681808895) #16) in\n    (Utils.Containers.Internal.BitUtil.shiftRL x6 #32) Data.Bits..|.(**)\n    (Utils.Containers.Internal.BitUtil.shiftLL x6 #32).\n\nDefinition revNatSafe n :=\n  Coq.NArith.BinNat.N.modulo (revNat n) (Coq.NArith.BinNat.N.pow 2 64).\n\nProgram Definition foldrBits {a}\n           : Coq.Numbers.BinNums.N ->\n             (Coq.Numbers.BinNums.N -> a -> a) -> a -> Nat -> a :=\n          fun prefix f z bitmap =>\n            let go :=\n              GHC.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                               Coq.NArith.BinNat.N.to_nat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                               match arg_0__, arg_1__ with\n                               | num_2__, acc =>\n                                   if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                                   match arg_0__, arg_1__ with\n                                   | bm, acc =>\n                                       let bitmask := Utils.Containers.Internal.BitUtil.lowestBitMask bm in\n                                       let bi := indexOfTheOnlyBit bitmask in\n                                       go (Data.Bits.xor bm bitmask) ((f ((prefix GHC.Num.+ (#64 GHC.Num.- #1))\n                                                                          GHC.Num.-\n                                                                          bi)) acc)\n                                   end\n                               end) in\n            go (revNatSafe bitmap) z.\nSolve Obligations with (BitTerminationProofs.termination_foldl).\n\nDefinition foldr {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | z', Nil => z'\n                 | z', Tip kx bm => foldrBits kx f z' bm\n                 | z', Bin _ _ l r => go (go z' r) l\n                 end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z l) r else go (go z r) l\n      | _ => go z t\n      end.\n\nDefinition toAscList : IntSet -> list Key :=\n  foldr cons nil.\n\nLocal Definition Ord__IntSet_compare : IntSet -> IntSet -> comparison :=\n  fun s1 s2 => GHC.Base.compare (toAscList s1) (toAscList s2).\n\nLocal Definition Ord__IntSet_op_zl__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base.== Lt.\n\nLocal Definition Ord__IntSet_op_zlze__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base./= Gt.\n\nLocal Definition Ord__IntSet_op_zg__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base.== Gt.\n\nLocal Definition Ord__IntSet_op_zgze__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base./= Lt.\n\nLocal Definition Ord__IntSet_max : IntSet -> IntSet -> IntSet :=\n  fun x y => if Ord__IntSet_op_zlze__ x y : bool then y else x.\n\nLocal Definition Ord__IntSet_min : IntSet -> IntSet -> IntSet :=\n  fun x y => if Ord__IntSet_op_zlze__ x y : bool then x else y.\n\nProgram Instance Ord__IntSet : GHC.Base.Ord IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zl____ := Ord__IntSet_op_zl__ ;\n           GHC.Base.op_zlze____ := Ord__IntSet_op_zlze__ ;\n           GHC.Base.op_zg____ := Ord__IntSet_op_zg__ ;\n           GHC.Base.op_zgze____ := Ord__IntSet_op_zgze__ ;\n           GHC.Base.compare__ := Ord__IntSet_compare ;\n           GHC.Base.max__ := Ord__IntSet_max ;\n           GHC.Base.min__ := Ord__IntSet_min |}.\n\n(* Skipping all instances of class `GHC.Show.Show', including\n   `Data.IntSet.Internal.Show__IntSet' *)\n\n(* Skipping all instances of class `GHC.Read.Read', including\n   `Data.IntSet.Internal.Read__IntSet' *)\n\n(* Skipping all instances of class `Control.DeepSeq.NFData', including\n   `Data.IntSet.Internal.NFData__IntSet' *)\n\n(* Skipping definition `Data.IntSet.Internal.natFromInt' *)\n\n(* Skipping definition `Data.IntSet.Internal.intFromNat' *)\n\nDefinition bin : Prefix -> Mask -> IntSet -> IntSet -> IntSet :=\n  fun arg_0__ arg_1__ arg_2__ arg_3__ =>\n    match arg_0__, arg_1__, arg_2__, arg_3__ with\n    | _, _, l, Nil => l\n    | _, _, Nil, r => r\n    | p, m, l, r => Bin p m l r\n    end.\n\nDefinition tip : Prefix -> BitMap -> IntSet :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | _, num_2__ =>\n        if num_2__ GHC.Base.== #0 : bool then Nil else\n        match arg_0__, arg_1__ with\n        | kx, bm => Tip kx bm\n        end\n    end.\n\nFixpoint deleteBM (arg_0__ : Prefix) (arg_1__ : BitMap) (arg_2__ : IntSet)\n           : IntSet\n           := match arg_0__, arg_1__, arg_2__ with\n              | kx, bm, (Bin p m l r as t) =>\n                  if nomatch kx p m : bool then t else\n                  if zero kx m : bool then bin p m (deleteBM kx bm l) r else\n                  bin p m l (deleteBM kx bm r)\n              | kx, bm, (Tip kx' bm' as t) =>\n                  if kx' GHC.Base.== kx : bool\n                  then tip kx (Data.Bits.xor bm' (bm' Data.Bits..&.(**) bm)) else\n                  t\n              | _, _, Nil => Nil\n              end.\n\nProgram Fixpoint difference (arg_0__ arg_1__ : IntSet) {measure (size_nat\n                             arg_0__ +\n                             size_nat arg_1__)} : IntSet\n                   := match arg_0__, arg_1__ with\n                      | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n                          let difference2 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then t1 else\n                            if Bool.Sumbool.sumbool_of_bool (zero p1 m2) then difference t1 l2 else\n                            difference t1 r2 in\n                          let difference1 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then t1 else\n                            if Bool.Sumbool.sumbool_of_bool (zero p2 m1)\n                            then bin p1 m1 (difference l1 t2) r1 else\n                            bin p1 m1 l1 (difference r1 t2) in\n                          if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then difference1 else\n                          if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then difference2 else\n                          if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n                          then bin p1 m1 (difference l1 l2) (difference r1 r2) else\n                          t1\n                      | (Bin _ _ _ _ as t), Tip kx bm => deleteBM kx bm t\n                      | (Bin _ _ _ _ as t), Nil => t\n                      | (Tip kx bm as t1), t2 =>\n                          let fix differenceTip arg_12__\n                                    := match arg_12__ with\n                                       | Bin p2 m2 l2 r2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx p2 m2) then t1 else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx m2) then differenceTip l2 else\n                                           differenceTip r2\n                                       | Tip kx2 bm2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx GHC.Base.== kx2)\n                                           then tip kx (Data.Bits.xor bm (bm Data.Bits..&.(**) bm2)) else\n                                           t1\n                                       | Nil => t1\n                                       end in\n                          differenceTip t2\n                      | Nil, _ => Nil\n                      end.\nSolve Obligations with (termination_by_omega).\n\nDefinition op_zrzr__ : IntSet -> IntSet -> IntSet :=\n  fun m1 m2 => difference m1 m2.\n\nNotation \"'_\\\\_'\" := (op_zrzr__).\n\nInfix \"\\\\\" := (_\\\\_) (at level 99).\n\n(* Skipping definition `Data.IntSet.Internal.fromListConstr' *)\n\n(* Skipping definition `Data.IntSet.Internal.intSetDataType' *)\n\nDefinition null : IntSet -> bool :=\n  fun arg_0__ => match arg_0__ with | Nil => true | _ => false end.\n\nDefinition size : IntSet -> Coq.Numbers.BinNums.N :=\n  let fix go arg_0__ arg_1__\n            := match arg_0__, arg_1__ with\n               | acc, Bin _ _ l r => go (go acc l) r\n               | acc, Tip _ bm =>\n                   acc GHC.Num.+ Utils.Containers.Internal.BitUtil.bitcount #0 bm\n               | acc, Nil => acc\n               end in\n  go #0.\n\nDefinition bitmapOfSuffix : Coq.Numbers.BinNums.N -> BitMap :=\n  fun s => Utils.Containers.Internal.BitUtil.shiftLL #1 s.\n\nDefinition suffixBitMask :=\n  Coq.NArith.BinNat.N.ones 6.\n\nDefinition suffixOf : Coq.Numbers.BinNums.N -> Coq.Numbers.BinNums.N :=\n  fun x => x Data.Bits..&.(**) suffixBitMask.\n\nDefinition bitmapOf : Coq.Numbers.BinNums.N -> BitMap :=\n  fun x => bitmapOfSuffix (suffixOf x).\n\nDefinition prefixOf : Coq.Numbers.BinNums.N -> Prefix :=\n  fun x => Coq.NArith.BinNat.N.ldiff x suffixBitMask.\n\nDefinition member : Key -> IntSet -> bool :=\n  fun x =>\n    let fix go arg_0__\n              := match arg_0__ with\n                 | Bin p m l r =>\n                     if nomatch x p m : bool then false else\n                     if zero x m : bool then go l else\n                     go r\n                 | Tip y bm =>\n                     andb (prefixOf x GHC.Base.== y) ((bitmapOf x Data.Bits..&.(**) bm) GHC.Base./=\n                           #0)\n                 | Nil => false\n                 end in\n    go.\n\nDefinition notMember : Key -> IntSet -> bool :=\n  fun k => negb GHC.Base.∘ member k.\n\nDefinition highestBitSet : Nat -> Coq.Numbers.BinNums.N :=\n  fun x => indexOfTheOnlyBit (Utils.Containers.Internal.BitUtil.highestBitMask x).\n\nFixpoint unsafeFindMax (arg_0__ : IntSet) : option Key\n           := match arg_0__ with\n              | Nil => None\n              | Tip kx bm => Some (kx GHC.Num.+ highestBitSet bm)\n              | Bin _ _ _ r => unsafeFindMax r\n              end.\n\nDefinition lookupLT : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | def, Bin p m l r =>\n                     if nomatch x p m : bool\n                     then if x GHC.Base.< p : bool\n                          then unsafeFindMax def\n                          else unsafeFindMax r else\n                     if zero x m : bool then go def l else\n                     go l r\n                 | def, Tip kx bm =>\n                     let maskLT := (bitmapOf x GHC.Num.- #1) Data.Bits..&.(**) bm in\n                     if prefixOf x GHC.Base.> kx : bool\n                     then Some (kx GHC.Num.+ highestBitSet bm) else\n                     if andb (prefixOf x GHC.Base.== kx) (maskLT GHC.Base./= #0) : bool\n                     then Some (kx GHC.Num.+ highestBitSet maskLT) else\n                     unsafeFindMax def\n                 | def, Nil => unsafeFindMax def\n                 end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go r l\n             else go Nil r else\n        j_12__\n    | _ => j_12__\n    end.\n\n(* Skipping definition `Utils.Containers.Internal.BitUtil.lowestBitMask' *)\n\nDefinition lowestBitSet : Nat -> Coq.Numbers.BinNums.N :=\n  fun x => indexOfTheOnlyBit (Utils.Containers.Internal.BitUtil.lowestBitMask x).\n\nFixpoint unsafeFindMin (arg_0__ : IntSet) : option Key\n           := match arg_0__ with\n              | Nil => None\n              | Tip kx bm => Some (kx GHC.Num.+ lowestBitSet bm)\n              | Bin _ _ l _ => unsafeFindMin l\n              end.\n\nDefinition lookupGT : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | def, Bin p m l r =>\n                     if nomatch x p m : bool\n                     then if x GHC.Base.< p : bool\n                          then unsafeFindMin l\n                          else unsafeFindMin def else\n                     if zero x m : bool then go r l else\n                     go def r\n                 | def, Tip kx bm =>\n                     let maskGT :=\n                       (Coq.NArith.BinNat.N.ldiff (Coq.NArith.BinNat.N.ones (64 % N))\n                                                  (Coq.NArith.BinNat.N.pred (Utils.Containers.Internal.BitUtil.shiftLL\n                                                                             (bitmapOf x) #1))) Data.Bits..&.(**)\n                       bm in\n                     if prefixOf x GHC.Base.< kx : bool then Some (kx GHC.Num.+ lowestBitSet bm) else\n                     if andb (prefixOf x GHC.Base.== kx) (maskGT GHC.Base./= #0) : bool\n                     then Some (kx GHC.Num.+ lowestBitSet maskGT) else\n                     unsafeFindMin def\n                 | def, Nil => unsafeFindMin def\n                 end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go Nil l\n             else go l r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition lookupLE : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | def, Bin p m l r =>\n                     if nomatch x p m : bool\n                     then if x GHC.Base.< p : bool\n                          then unsafeFindMax def\n                          else unsafeFindMax r else\n                     if zero x m : bool then go def l else\n                     go l r\n                 | def, Tip kx bm =>\n                     let maskLE :=\n                       ((Utils.Containers.Internal.BitUtil.shiftLL (bitmapOf x) #1) GHC.Num.- #1)\n                       Data.Bits..&.(**)\n                       bm in\n                     if prefixOf x GHC.Base.> kx : bool\n                     then Some (kx GHC.Num.+ highestBitSet bm) else\n                     if andb (prefixOf x GHC.Base.== kx) (maskLE GHC.Base./= #0) : bool\n                     then Some (kx GHC.Num.+ highestBitSet maskLE) else\n                     unsafeFindMax def\n                 | def, Nil => unsafeFindMax def\n                 end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go r l\n             else go Nil r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition lookupGE : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | def, Bin p m l r =>\n                     if nomatch x p m : bool\n                     then if x GHC.Base.< p : bool\n                          then unsafeFindMin l\n                          else unsafeFindMin def else\n                     if zero x m : bool then go r l else\n                     go def r\n                 | def, Tip kx bm =>\n                     let maskGE :=\n                       (Coq.NArith.BinNat.N.ldiff (Coq.NArith.BinNat.N.ones (64 % N))\n                                                  (Coq.NArith.BinNat.N.pred (bitmapOf x))) Data.Bits..&.(**)\n                       bm in\n                     if prefixOf x GHC.Base.< kx : bool then Some (kx GHC.Num.+ lowestBitSet bm) else\n                     if andb (prefixOf x GHC.Base.== kx) (maskGE GHC.Base./= #0) : bool\n                     then Some (kx GHC.Num.+ lowestBitSet maskGE) else\n                     unsafeFindMin def\n                 | def, Nil => unsafeFindMin def\n                 end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go Nil l\n             else go l r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition singleton : Key -> IntSet :=\n  fun x => Tip (prefixOf x) (bitmapOf x).\n\nDefinition insert : Key -> IntSet -> IntSet :=\n  fun x => insertBM (prefixOf x) (bitmapOf x).\n\nDefinition delete : Key -> IntSet -> IntSet :=\n  fun x => deleteBM (prefixOf x) (bitmapOf x).\n\nProgram Fixpoint intersection (arg_0__ arg_1__ : IntSet) {measure (size_nat\n                               arg_0__ +\n                               size_nat arg_1__)} : IntSet\n                   := match arg_0__, arg_1__ with\n                      | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n                          let intersection2 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then Nil else\n                            if Bool.Sumbool.sumbool_of_bool (zero p1 m2) then intersection t1 l2 else\n                            intersection t1 r2 in\n                          let intersection1 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then Nil else\n                            if Bool.Sumbool.sumbool_of_bool (zero p2 m1) then intersection l1 t2 else\n                            intersection r1 t2 in\n                          if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then intersection1 else\n                          if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then intersection2 else\n                          if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n                          then bin p1 m1 (intersection l1 l2) (intersection r1 r2) else\n                          Nil\n                      | (Bin _ _ _ _ as t1), Tip kx2 bm2 =>\n                          let fix intersectBM arg_11__\n                                    := match arg_11__ with\n                                       | Bin p1 m1 l1 r1 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx2 p1 m1) then Nil else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx2 m1) then intersectBM l1 else\n                                           intersectBM r1\n                                       | Tip kx1 bm1 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                                           then tip kx1 (bm1 Data.Bits..&.(**) bm2) else\n                                           Nil\n                                       | Nil => Nil\n                                       end in\n                          intersectBM t1\n                      | Bin _ _ _ _, Nil => Nil\n                      | Tip kx1 bm1, t2 =>\n                          let fix intersectBM arg_18__\n                                    := match arg_18__ with\n                                       | Bin p2 m2 l2 r2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx1 p2 m2) then Nil else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx1 m2) then intersectBM l2 else\n                                           intersectBM r2\n                                       | Tip kx2 bm2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                                           then tip kx1 (bm1 Data.Bits..&.(**) bm2) else\n                                           Nil\n                                       | Nil => Nil\n                                       end in\n                          intersectBM t2\n                      | Nil, _ => Nil\n                      end.\nSolve Obligations with (termination_by_omega).\n\nFixpoint subsetCmp (arg_0__ arg_1__ : IntSet) : comparison\n           := match arg_0__, arg_1__ with\n              | (Bin p1 m1 l1 r1 as t1), Bin p2 m2 l2 r2 =>\n                  let subsetCmpEq :=\n                    match pair (subsetCmp l1 l2) (subsetCmp r1 r2) with\n                    | pair Gt _ => Gt\n                    | pair _ Gt => Gt\n                    | pair Eq Eq => Eq\n                    | _ => Lt\n                    end in\n                  let subsetCmpLt :=\n                    if nomatch p1 p2 m2 : bool then Gt else\n                    if zero p1 m2 : bool then subsetCmp t1 l2 else\n                    subsetCmp t1 r2 in\n                  if shorter m1 m2 : bool then Gt else\n                  if shorter m2 m1 : bool\n                  then match subsetCmpLt with\n                       | Gt => Gt\n                       | _ => Lt\n                       end else\n                  if p1 GHC.Base.== p2 : bool then subsetCmpEq else\n                  Gt\n              | _, _ =>\n                  match arg_0__, arg_1__ with\n                  | Bin _ _ _ _, _ => Gt\n                  | Tip kx1 bm1, Tip kx2 bm2 =>\n                      if kx1 GHC.Base./= kx2 : bool then Gt else\n                      if bm1 GHC.Base.== bm2 : bool then Eq else\n                      if Data.Bits.xor bm1 (bm1 Data.Bits..&.(**) bm2) GHC.Base.== #0 : bool\n                      then Lt else\n                      Gt\n                  | (Tip kx _ as t1), Bin p m l r =>\n                      if nomatch kx p m : bool then Gt else\n                      if zero kx m : bool then match subsetCmp t1 l with | Gt => Gt | _ => Lt end else\n                      match subsetCmp t1 r with\n                      | Gt => Gt\n                      | _ => Lt\n                      end\n                  | Tip _ _, Nil => Gt\n                  | Nil, Nil => Eq\n                  | Nil, _ => Lt\n                  end\n              end.\n\nDefinition isProperSubsetOf : IntSet -> IntSet -> bool :=\n  fun t1 t2 => match subsetCmp t1 t2 with | Lt => true | _ => false end.\n\nDefinition match_ : Coq.Numbers.BinNums.N -> Prefix -> Mask -> bool :=\n  fun i p m => (mask i m) GHC.Base.== p.\n\nFixpoint isSubsetOf (arg_0__ arg_1__ : IntSet) : bool\n           := match arg_0__, arg_1__ with\n              | (Bin p1 m1 l1 r1 as t1), Bin p2 m2 l2 r2 =>\n                  if shorter m1 m2 : bool then false else\n                  if shorter m2 m1 : bool\n                  then andb (match_ p1 p2 m2) (if zero p1 m2 : bool\n                             then isSubsetOf t1 l2\n                             else isSubsetOf t1 r2) else\n                  andb (p1 GHC.Base.== p2) (andb (isSubsetOf l1 l2) (isSubsetOf r1 r2))\n              | _, _ =>\n                  match arg_0__, arg_1__ with\n                  | Bin _ _ _ _, _ => false\n                  | Tip kx1 bm1, Tip kx2 bm2 =>\n                      andb (kx1 GHC.Base.== kx2) (Data.Bits.xor bm1 (bm1 Data.Bits..&.(**) bm2)\n                            GHC.Base.==\n                            #0)\n                  | (Tip kx _ as t1), Bin p m l r =>\n                      if nomatch kx p m : bool then false else\n                      if zero kx m : bool then isSubsetOf t1 l else\n                      isSubsetOf t1 r\n                  | Tip _ _, Nil => false\n                  | Nil, _ => true\n                  end\n              end.\n\nProgram Fixpoint disjoint (arg_0__ arg_1__ : IntSet) {measure (size_nat arg_0__\n                           +\n                           size_nat arg_1__)} : bool\n                   := match arg_0__, arg_1__ with\n                      | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n                          let disjoint2 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then true else\n                            if Bool.Sumbool.sumbool_of_bool (zero p1 m2) then disjoint t1 l2 else\n                            disjoint t1 r2 in\n                          let disjoint1 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then true else\n                            if Bool.Sumbool.sumbool_of_bool (zero p2 m1) then disjoint l1 t2 else\n                            disjoint r1 t2 in\n                          if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then disjoint1 else\n                          if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then disjoint2 else\n                          if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n                          then andb (disjoint l1 l2) (disjoint r1 r2) else\n                          true\n                      | (Bin _ _ _ _ as t1), Tip kx2 bm2 =>\n                          let fix disjointBM arg_11__\n                                    := match arg_11__ with\n                                       | Bin p1 m1 l1 r1 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx2 p1 m1) then true else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx2 m1) then disjointBM l1 else\n                                           disjointBM r1\n                                       | Tip kx1 bm1 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                                           then (bm1 Data.Bits..&.(**) bm2) GHC.Base.== #0 else\n                                           true\n                                       | Nil => true\n                                       end in\n                          disjointBM t1\n                      | Bin _ _ _ _, Nil => true\n                      | Tip kx1 bm1, t2 =>\n                          let fix disjointBM arg_18__\n                                    := match arg_18__ with\n                                       | Bin p2 m2 l2 r2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx1 p2 m2) then true else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx1 m2) then disjointBM l2 else\n                                           disjointBM r2\n                                       | Tip kx2 bm2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                                           then (bm1 Data.Bits..&.(**) bm2) GHC.Base.== #0 else\n                                           true\n                                       | Nil => true\n                                       end in\n                          disjointBM t2\n                      | Nil, _ => true\n                      end.\nSolve Obligations with (termination_by_omega).\n\nProgram Definition foldl'Bits {a}\n           : Coq.Numbers.BinNums.N ->\n             (a -> Coq.Numbers.BinNums.N -> a) -> a -> Nat -> a :=\n          fun prefix f z bitmap =>\n            let go :=\n              GHC.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                               Coq.NArith.BinNat.N.to_nat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                               match arg_0__, arg_1__ with\n                               | num_2__, acc =>\n                                   if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                                   match arg_0__, arg_1__ with\n                                   | bm, acc =>\n                                       let bitmask := Utils.Containers.Internal.BitUtil.lowestBitMask bm in\n                                       let bi := indexOfTheOnlyBit bitmask in\n                                       go (Data.Bits.xor bm bitmask) (f acc (prefix GHC.Num.+ bi))\n                                   end\n                               end) in\n            go bitmap z.\nSolve Obligations with (BitTerminationProofs.termination_foldl).\n\nFixpoint filter (predicate : (Key -> bool)) (t : IntSet) : IntSet\n           := let bitPred :=\n                fun kx bm bi =>\n                  if predicate (kx GHC.Num.+ bi) : bool\n                  then bm Data.Bits..|.(**) bitmapOfSuffix bi else\n                  bm in\n              match t with\n              | Bin p m l r => bin p m (filter predicate l) (filter predicate r)\n              | Tip kx bm => tip kx (foldl'Bits #0 (bitPred kx) #0 bm)\n              | Nil => Nil\n              end.\n\nDefinition partition : (Key -> bool) -> IntSet -> (IntSet * IntSet)%type :=\n  fun predicate0 t0 =>\n    let fix go predicate t\n              := let bitPred :=\n                   fun kx bm bi =>\n                     if predicate (kx GHC.Num.+ bi) : bool\n                     then bm Data.Bits..|.(**) bitmapOfSuffix bi else\n                     bm in\n                 match t with\n                 | Bin p m l r =>\n                     let 'pair r1 r2 := go predicate r in\n                     let 'pair l1 l2 := go predicate l in\n                     pair (bin p m l1 r1) (bin p m l2 r2)\n                 | Tip kx bm =>\n                     let bm1 := foldl'Bits #0 (bitPred kx) #0 bm in\n                     pair (tip kx bm1) (tip kx (Data.Bits.xor bm bm1))\n                 | Nil => (pair Nil Nil)\n                 end in\n    id (go predicate0 t0).\n\nDefinition split : Key -> IntSet -> (IntSet * IntSet)%type :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | x', (Bin p m l r as t') =>\n                     if match_ x' p m : bool\n                     then if zero x' m : bool\n                          then let 'pair lt gt := go x' l in\n                               pair lt (union gt r)\n                          else let 'pair lt gt := go x' r in\n                               pair (union lt l) gt else\n                     if x' GHC.Base.< p : bool\n                     then (pair Nil t')\n                     else (pair t' Nil)\n                 | x', (Tip kx' bm as t') =>\n                     let lowerBitmap := bitmapOf x' GHC.Num.- #1 in\n                     let higherBitmap :=\n                       Coq.NArith.BinNat.N.ldiff (Coq.NArith.BinNat.N.ones (64 % N)) (lowerBitmap\n                                                  GHC.Num.+\n                                                  bitmapOf x') in\n                     if kx' GHC.Base.> x' : bool then (pair Nil t') else\n                     if kx' GHC.Base.< prefixOf x' : bool then (pair t' Nil) else\n                     pair (tip kx' (bm Data.Bits..&.(**) lowerBitmap)) (tip kx' (bm Data.Bits..&.(**)\n                                                                                 higherBitmap))\n                 | _, Nil => (pair Nil Nil)\n                 end in\n    let j_21__ := let 'pair lt gt := go x t in pair lt gt in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then let 'pair lt gt := go x l in\n                  let lt' := union lt r in pair lt' gt\n             else let 'pair lt gt := go x r in\n                  let gt' := union gt l in pair lt gt' else\n        j_21__\n    | _ => j_21__\n    end.\n\nDefinition splitMember : Key -> IntSet -> (IntSet * bool * IntSet)%type :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | x', (Bin p m l r as t') =>\n                     if match_ x' p m : bool\n                     then if zero x' m : bool\n                          then let 'pair (pair lt fnd) gt := go x' l in\n                               pair (pair lt fnd) (union gt r)\n                          else let 'pair (pair lt fnd) gt := go x' r in\n                               pair (pair (union lt l) fnd) gt else\n                     if x' GHC.Base.< p : bool\n                     then pair (pair Nil false) t'\n                     else pair (pair t' false) Nil\n                 | x', (Tip kx' bm as t') =>\n                     let bitmapOfx' := bitmapOf x' in\n                     let lowerBitmap := bitmapOfx' GHC.Num.- #1 in\n                     let higherBitmap :=\n                       Coq.NArith.BinNat.N.ldiff (Coq.NArith.BinNat.N.ones (64 % N)) (lowerBitmap\n                                                  GHC.Num.+\n                                                  bitmapOfx') in\n                     if kx' GHC.Base.> x' : bool then pair (pair Nil false) t' else\n                     if kx' GHC.Base.< prefixOf x' : bool then pair (pair t' false) Nil else\n                     let gt := tip kx' (bm Data.Bits..&.(**) higherBitmap) in\n                     let found := (bm Data.Bits..&.(**) bitmapOfx') GHC.Base./= #0 in\n                     let lt := tip kx' (bm Data.Bits..&.(**) lowerBitmap) in pair (pair lt found) gt\n                 | _, Nil => pair (pair Nil false) Nil\n                 end in\n    let j_22__ := go x t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then let 'pair (pair lt fnd) gt := go x l in\n                  let lt' := union lt r in pair (pair lt' fnd) gt\n             else let 'pair (pair lt fnd) gt := go x r in\n                  let gt' := union gt l in pair (pair lt fnd) gt' else\n        j_22__\n    | _ => j_22__\n    end.\n\nDefinition maxView : IntSet -> option (Key * IntSet)%type :=\n  fun t =>\n    let fix go arg_0__\n              := match arg_0__ with\n                 | Bin p m l r => let 'pair result r' := go r in pair result (bin p m l r')\n                 | Tip kx bm =>\n                     let 'bi := highestBitSet bm in\n                     pair (kx GHC.Num.+ bi) (tip kx (Data.Bits.xor bm (bm Data.Bits..&.(**)\n                                                                    bitmapOfSuffix bi)))\n                 | Nil => pair (0 % N) Nil\n                 end in\n    let j_12__ := Some (go t) in\n    match t with\n    | Nil => None\n    | Bin p m l r =>\n        if m GHC.Base.< #0 : bool\n        then let 'pair result l' := go l in\n             Some (pair result (bin p m l' r)) else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition minView : IntSet -> option (Key * IntSet)%type :=\n  fun t =>\n    let fix go arg_0__\n              := match arg_0__ with\n                 | Bin p m l r => let 'pair result l' := go l in pair result (bin p m l' r)\n                 | Tip kx bm =>\n                     let 'bi := lowestBitSet bm in\n                     pair (kx GHC.Num.+ bi) (tip kx (Data.Bits.xor bm (bm Data.Bits..&.(**)\n                                                                    bitmapOfSuffix bi)))\n                 | Nil => pair (0 % N) Nil\n                 end in\n    let j_12__ := Some (go t) in\n    match t with\n    | Nil => None\n    | Bin p m l r =>\n        if m GHC.Base.< #0 : bool\n        then let 'pair result r' := go r in\n             Some (pair result (bin p m l r')) else\n        j_12__\n    | _ => j_12__\n    end.\n\n(* Skipping definition `Data.IntSet.Internal.deleteFindMin' *)\n\n(* Skipping definition `Data.IntSet.Internal.deleteFindMax' *)\n\n(* Skipping definition `Data.IntSet.Internal.findMin' *)\n\n(* Skipping definition `Data.IntSet.Internal.findMax' *)\n\nDefinition deleteMin : IntSet -> IntSet :=\n  Data.Maybe.maybe Nil Data.Tuple.snd GHC.Base.∘ minView.\n\nDefinition deleteMax : IntSet -> IntSet :=\n  Data.Maybe.maybe Nil Data.Tuple.snd GHC.Base.∘ maxView.\n\nDefinition fromList : list Key -> IntSet :=\n  fun xs => let ins := fun t x => insert x t in Data.Foldable.foldl' ins empty xs.\n\nDefinition toList : IntSet -> list Key :=\n  toAscList.\n\nDefinition map : (Key -> Key) -> IntSet -> IntSet :=\n  fun f => fromList GHC.Base.∘ (GHC.Base.map f GHC.Base.∘ toList).\n\nDefinition fold {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  foldr.\n\nProgram Definition foldr'Bits {a}\n           : Coq.Numbers.BinNums.N ->\n             (Coq.Numbers.BinNums.N -> a -> a) -> a -> Nat -> a :=\n          fun prefix f z bitmap =>\n            let go :=\n              GHC.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                               Coq.NArith.BinNat.N.to_nat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                               match arg_0__, arg_1__ with\n                               | num_2__, acc =>\n                                   if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                                   match arg_0__, arg_1__ with\n                                   | bm, acc =>\n                                       let bitmask := Utils.Containers.Internal.BitUtil.lowestBitMask bm in\n                                       let bi := indexOfTheOnlyBit bitmask in\n                                       go (Data.Bits.xor bm bitmask) ((f ((prefix GHC.Num.+ (#64 GHC.Num.- #1))\n                                                                          GHC.Num.-\n                                                                          bi)) acc)\n                                   end\n                               end) in\n            go (revNatSafe bitmap) z.\nSolve Obligations with (BitTerminationProofs.termination_foldl).\n\nDefinition foldr' {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | z', Nil => z'\n                 | z', Tip kx bm => foldr'Bits kx f z' bm\n                 | z', Bin _ _ l r => go (go z' r) l\n                 end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z l) r else go (go z r) l\n      | _ => go z t\n      end.\n\nProgram Definition foldlBits {a}\n           : Coq.Numbers.BinNums.N ->\n             (a -> Coq.Numbers.BinNums.N -> a) -> a -> Nat -> a :=\n          fun prefix f z bitmap =>\n            let go :=\n              GHC.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                               Coq.NArith.BinNat.N.to_nat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                               match arg_0__, arg_1__ with\n                               | num_2__, acc =>\n                                   if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                                   match arg_0__, arg_1__ with\n                                   | bm, acc =>\n                                       let bitmask := Utils.Containers.Internal.BitUtil.lowestBitMask bm in\n                                       let bi := indexOfTheOnlyBit bitmask in\n                                       go (Data.Bits.xor bm bitmask) (f acc (prefix GHC.Num.+ bi))\n                                   end\n                               end) in\n            go bitmap z.\nSolve Obligations with (BitTerminationProofs.termination_foldl).\n\nDefinition foldl {a} : (a -> Key -> a) -> a -> IntSet -> a :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | z', Nil => z'\n                 | z', Tip kx bm => foldlBits kx f z' bm\n                 | z', Bin _ _ l r => go (go z' l) r\n                 end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z r) l else go (go z l) r\n      | _ => go z t\n      end.\n\nDefinition foldl' {a} : (a -> Key -> a) -> a -> IntSet -> a :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | z', Nil => z'\n                 | z', Tip kx bm => foldl'Bits kx f z' bm\n                 | z', Bin _ _ l r => go (go z' l) r\n                 end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z r) l else go (go z l) r\n      | _ => go z t\n      end.\n\nDefinition elems : IntSet -> list Key :=\n  toAscList.\n\nDefinition toDescList : IntSet -> list Key :=\n  foldl (GHC.Base.flip cons) nil.\n\nDefinition foldrFB {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  foldr.\n\nDefinition foldlFB {a} : (a -> Key -> a) -> a -> IntSet -> a :=\n  foldl.\n\n(* Skipping definition `Data.IntSet.Internal.fromAscList' *)\n\n(* Skipping definition `Data.IntSet.Internal.fromDistinctAscList' *)\n\n(* Skipping definition `Data.IntSet.Internal.showTree' *)\n\n(* Skipping definition `Data.IntSet.Internal.showTreeWith' *)\n\n(* Skipping definition `Data.IntSet.Internal.showsTree' *)\n\n(* Skipping definition `Data.IntSet.Internal.showsTreeHang' *)\n\n(* Skipping definition `Data.IntSet.Internal.showBin' *)\n\n(* Skipping definition `Data.IntSet.Internal.showWide' *)\n\n(* Skipping definition `Data.IntSet.Internal.showsBars' *)\n\n(* Skipping definition `Data.IntSet.Internal.showsBitMap' *)\n\n(* Skipping definition `Data.IntSet.Internal.showBitMap' *)\n\n(* Skipping definition `Data.IntSet.Internal.node' *)\n\n(* Skipping definition `Data.IntSet.Internal.withBar' *)\n\n(* Skipping definition `Data.IntSet.Internal.withEmpty' *)\n\n(* Skipping definition `Data.IntSet.Internal.prefixBitMask' *)\n\nDefinition splitRoot : IntSet -> list IntSet :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Nil => nil\n    | (Tip _ _ as x) => cons x nil\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool then cons r (cons l nil) else\n        cons l (cons r nil)\n    end.\n\nModule Notations.\nNotation \"'_Data.IntSet.Internal.\\\\_'\" := (op_zrzr__).\nInfix \"Data.IntSet.Internal.\\\\\" := (_\\\\_) (at level 99).\nEnd Notations.\n\n(* External variables:\n     Bool.Sumbool.sumbool_of_bool Eq Gt Lt N None Some andb bool comparison cons\n     false id list negb nil op_zm__ op_zp__ op_zt__ op_zv__ option orb pair size_nat\n     true Coq.Init.Peano.lt Coq.NArith.BinNat.N.ldiff Coq.NArith.BinNat.N.log2\n     Coq.NArith.BinNat.N.lxor Coq.NArith.BinNat.N.modulo Coq.NArith.BinNat.N.ones\n     Coq.NArith.BinNat.N.pow Coq.NArith.BinNat.N.pred Coq.NArith.BinNat.N.to_nat\n     Coq.Numbers.BinNums.N Data.Bits.op_zizazi__ Data.Bits.op_zizbzi__ Data.Bits.xor\n     Data.Foldable.Foldable Data.Foldable.foldl' Data.Maybe.maybe Data.Tuple.snd\n     GHC.Base.Eq_ GHC.Base.Monoid GHC.Base.Ord GHC.Base.Semigroup GHC.Base.compare\n     GHC.Base.compare__ GHC.Base.flip GHC.Base.map GHC.Base.mappend__ GHC.Base.max__\n     GHC.Base.mconcat__ GHC.Base.mempty__ GHC.Base.min__ GHC.Base.op_z2218U__\n     GHC.Base.op_zeze__ GHC.Base.op_zeze____ GHC.Base.op_zg__ GHC.Base.op_zg____\n     GHC.Base.op_zgze__ GHC.Base.op_zgze____ GHC.Base.op_zl__ GHC.Base.op_zl____\n     GHC.Base.op_zlze____ GHC.Base.op_zlzlzgzg__ GHC.Base.op_zlzlzgzg____\n     GHC.Base.op_zsze__ GHC.Base.op_zsze____ GHC.Err.Build_Default GHC.Err.Default\n     GHC.Num.fromInteger GHC.Num.op_zm__ GHC.Num.op_zp__ GHC.Wf.wfFix2\n     Utils.Containers.Internal.BitUtil.bitcount\n     Utils.Containers.Internal.BitUtil.highestBitMask\n     Utils.Containers.Internal.BitUtil.lowestBitMask\n     Utils.Containers.Internal.BitUtil.shiftLL\n     Utils.Containers.Internal.BitUtil.shiftRL\n*)\n", "meta": {"author": "antalsz", "repo": "hs-to-coq", "sha": "cd62a35fff22cb6022a8935581746df658264f0f", "save_path": "github-repos/coq/antalsz-hs-to-coq", "path": "github-repos/coq/antalsz-hs-to-coq/hs-to-coq-cd62a35fff22cb6022a8935581746df658264f0f/examples/containers/lib/Data/IntSet/Internal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.2324607027293894}}
{"text": "Require Import VST.floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\n\nRequire Import sha.general_lemmas.\nRequire Import hmacdrbg.hmac_drbg.\nRequire Import hmacdrbg.entropy.\nRequire Import hmacdrbg.spec_hmac_drbg.\nRequire Import hmacdrbg.HMAC_DRBG_common_lemmas.\n\nRequire Import sha.HMAC256_functional_prog.\nRequire Import hmacdrbg.entropy_lemmas.\nRequire Import VST.floyd.library.\n\nRequire Import hmacdrbg.HMAC256_DRBG_bridge_to_FCF.\n\nDefinition WF (I:hmac256drbgabs):=\n         Zlength (hmac256drbgabs_value I) = 32 /\\ \n         0 < hmac256drbgabs_entropy_len I <= 384 /\\\n         RI_range (hmac256drbgabs_reseed_interval I) /\\\n         0 <= hmac256drbgabs_reseed_counter I < Int.max_signed /\\\n         Forall isbyteZ (hmac256drbgabs_value I).\n\nDefinition REP kv (Info:md_info_state) (A:hmac256drbgabs) (v: val): mpred :=\n  EX a:hmac256drbgstate, \n       (!! WF A) &&\n          data_at Tsh t_struct_hmac256drbg_context_st a v\n          * hmac256drbg_relate A a\n          * data_at Tsh t_struct_mbedtls_md_info Info (hmac256drbgstate_md_info_pointer a)\n          * spec_sha.K_vector kv.\n\nDefinition AREP kv (A:hmac256drbgabs) (v: val): mpred :=\n  EX Info:md_info_state, REP kv Info A v. \n\nDefinition seedREP dp rc pr ri kv (Info:md_info_state) (info:val) (v: val): mpred :=\n  EX a:hmac256drbgstate, \n          data_at Tsh t_struct_hmac256drbg_context_st a v\n          * preseed_relate dp rc pr ri a\n          * data_at Tsh t_struct_mbedtls_md_info Info info\n          * spec_sha.K_vector kv.\n\nDefinition seedbufREP kv (Info:md_info_state) (info:val) (A:hmac256drbgabs) (v: val): mpred :=\n  EX a:hmac256drbgstate,\n     !! (0 < hmac256drbgabs_entropy_len A <= 384 /\\\n         RI_range (hmac256drbgabs_reseed_interval A) /\\\n         0 <= hmac256drbgabs_reseed_counter A < Int.max_signed)\n     && data_at Tsh t_struct_hmac256drbg_context_st a v\n          * hmac256drbg_relate A a\n          * data_at Tsh t_struct_mbedtls_md_info Info info\n          * spec_sha.K_vector kv.\n\n(*TODO: init, free*)\n\n(*based on hmac_drbg_seed_inst256_spec*)\nDefinition drbg_seed_inst256_spec_abs :=\n  DECLARE _mbedtls_hmac_drbg_seed\n   WITH dp:_, ctx: val, info:val, len: Z, data:val, Data: list Z,\n        kv: val, Info: md_info_state, s:ENTROPY.stream, rc:Z, pr_flag:bool, ri:Z,\n        handle_ss: DRBG_functions.DRBG_state_handle * ENTROPY.stream\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _md_info OF tptr (Tstruct _mbedtls_md_info_t noattr),\n         _custom OF tptr tuchar, _len OF tuint ]\n       PROP (len = Zlength Data /\\ 0 <= len <=256 /\\ Forall isbyteZ Data /\\\n             instantiate_function_256 s pr_flag (contents_with_add data (Zlength Data) Data)\n               = ENTROPY.success (fst handle_ss) (snd handle_ss))\n       LOCAL (temp _ctx ctx; temp _md_info info;\n              temp _len (Vint (Int.repr len)); temp _custom data; gvar sha._K256 kv)\n       SEP (seedREP dp rc pr_flag ri kv Info info ctx; Stream s;\n            da_emp Tsh (tarray tuchar (Zlength Data)) (map Vint (map Int.repr Data)) data)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp (Vint ret_value))\n       SEP (da_emp Tsh (tarray tuchar (Zlength Data)) (map Vint (map Int.repr Data)) data;\n            if Int.eq ret_value (Int.repr (-20864))\n            then seedREP dp rc pr_flag ri kv Info info ctx * Stream s                 \n            else !!(ret_value = Int.zero) &&                  \n                 EX p:val, malloc_token Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n                 match fst handle_ss with ((((newV, newK), newRC), newEL), newPR) =>\n                    AREP kv (HMAC256DRBGabs newK newV newRC 32 newPR 10000) ctx *\n                    Stream (snd handle_ss) * EX mds:mdstate, md_empty mds   \n                 end).\n\nDefinition drbg_seed_buf_abs_spec :=\n  DECLARE _mbedtls_hmac_drbg_seed_buf\n   WITH ctx: val, info:val, d_len: Z, data:val, Data: list Z,\n        I: hmac256drbgabs, Info:md_info_state,\n        kv: val \n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _md_info OF (tptr (Tstruct _mbedtls_md_info_t noattr)),\n         _data OF tptr tuchar, _data_len OF tuint ]\n       PROP (d_len = Zlength Data \\/ d_len=0;\n             0 <= d_len <= Int.max_unsigned; Forall isbyteZ Data)\n       LOCAL (temp _ctx ctx; temp _md_info info;\n              temp _data_len (Vint (Int.repr d_len)); temp _data data; gvar sha._K256 kv)\n       SEP (seedbufREP kv Info info I ctx;\n            da_emp Tsh (tarray tuchar (Zlength Data)) (map Vint (map Int.repr Data)) data)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp ret_value)\n       SEP (da_emp Tsh (tarray tuchar (Zlength Data)) (map Vint (map Int.repr Data)) data *\n            if Val.eq ret_value (Vint (Int.repr (-20864)))\n            then seedbufREP kv Info info I ctx\n            else match I with HMAC256DRBGabs key V RC EL PR RI =>\n                 EX KEY:list Z, EX VAL:list Z, EX p:val, EX mds:mdstate,\n                 !!(hmacdrbg.HMAC256_DRBG_functional_prog.HMAC256_DRBG_update (contents_with_add data d_len Data) V (list_repeat 32 1) = (KEY, VAL))\n                 && md_full key mds * malloc_token Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n                 REP kv Info (HMAC256DRBGabs KEY VAL RC EL PR RI) ctx end).\n\nDefinition drbg_setPredictionResistance_spec_abs :=\n  DECLARE _mbedtls_hmac_drbg_set_prediction_resistance \n   WITH ctx:val, A:_, r:bool, kv:_\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _resistance OF tint ]\n       PROP ( )\n       LOCAL (temp _ctx ctx; temp _resistance (Val.of_bool r))\n       SEP (AREP kv A ctx)\n    POST [ tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (AREP kv (setPR_ABS r A) ctx).\n\n\nDefinition drbg_setEntropyLen_spec_abs :=\n  DECLARE _mbedtls_hmac_drbg_set_entropy_len\n   WITH ctx:val, A:_, l:_, kv:_\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _len OF tuint ]\n       PROP ( 0 < l <= 384 )\n       LOCAL (temp _ctx ctx; temp _len (Vint (Int.repr l)))\n       SEP (AREP kv A ctx)\n    POST [ tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (AREP kv (setEL_ABS l A) ctx).\n\nDefinition drbg_setReseedInterval_spec_abs :=\n  DECLARE _mbedtls_hmac_drbg_set_reseed_interval\n   WITH ctx:val, A:_, ri:_, kv:_\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _interval OF tint ]\n       PROP (RI_range ri )\n       LOCAL (temp _ctx ctx; temp _interval (Vint (Int.repr ri)))\n       SEP (AREP kv A ctx)\n    POST [ tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (AREP kv (setRI_ABS ri A) ctx).\n\nDefinition drbg_update_abs_spec :=\n  DECLARE _mbedtls_hmac_drbg_update\n   WITH contents: list Z,\n        additional: val, add_len: Z,\n        ctx: val, I: hmac256drbgabs,\n        kv: val\n     PRE [ _ctx OF (tptr t_struct_hmac256drbg_context_st),\n           _additional OF (tptr tuchar), _add_len OF tuint ]\n       PROP (0 <= add_len <= Int.max_unsigned;\n             add_len = Zlength contents \\/ add_len = 0;\n             Forall isbyteZ contents)\n       LOCAL (temp _ctx ctx;\n              temp _additional additional;\n              temp _add_len (Vint (Int.repr add_len));\n              gvar sha._K256 kv)\n       SEP (AREP kv I ctx;\n            da_emp Tsh (tarray tuchar (Zlength contents)) (map Vint (map Int.repr contents)) additional)\n    POST [ tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (AREP kv (hmac256drbgabs_hmac_drbg_update I (contents_with_add additional add_len contents)) ctx;\n            da_emp Tsh (tarray tuchar (Zlength contents)) (map Vint (map Int.repr contents)) additional).\n\nDefinition drbg_reseed_spec_abs :=\n  DECLARE _mbedtls_hmac_drbg_reseed\n   WITH contents: list Z,\n        additional: val, add_len: Z,\n        ctx: val, I: hmac256drbgabs,\n        kv: val, s: ENTROPY.stream\n    PRE [ _ctx OF (tptr t_struct_hmac256drbg_context_st), _additional OF (tptr tuchar), _len OF tuint ]\n       PROP (0 <= add_len <= Int.max_unsigned;\n             add_len = Zlength contents;\n             0 < hmac256drbgabs_entropy_len I + Zlength (contents_with_add additional add_len contents) < Int.modulus;         \n             Forall isbyteZ contents)\n       LOCAL (temp _ctx ctx; temp _additional additional; temp _len (Vint (Int.repr add_len)); gvar sha._K256 kv)\n       SEP ( da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional;\n              AREP kv I ctx; Stream s)\n    POST [ tint ]\n       EX rv:_,\n       PROP ()\n       LOCAL (temp ret_temp rv)\n       SEP (if ((zlt 256 add_len) || (zlt 384 (hmac256drbgabs_entropy_len I + add_len)))%bool\n  then (!!(rv = Vint (Int.neg (Int.repr 5))) &&\n       (da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional *\n         AREP kv I ctx * Stream s))\n  else (let F := mbedtls_HMAC256_DRBG_reseed_function s I (contents_with_add additional add_len contents)\n        in !!(return_value_relate_result F rv)\n           && AREP kv ((*match F with ENTROPY.error _ _ => I | \n                  ENTROPY.success (V, K, rc, _, pr) _ => HMAC256DRBGabs K V rc (hmac256drbgabs_entropy_len I) pr\n                                (hmac256drbgabs_reseed_interval I) end*)\n                     (hmac256drbgabs_reseed I s (contents_with_add additional add_len contents))) ctx *\n              da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional *\n              Stream (get_stream_result F))).\n\nDefinition generate_absPOST ret_value contents additional add_len output out_len ctx I kv s :=\nif out_len >? 1024\nthen (!!(ret_value = Vint (Int.neg (Int.repr 3))) &&\n       (data_at_ Tsh (tarray tuchar out_len) output *\n         da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional *\n         AREP kv I ctx * Stream s))\nelse\n  if (add_len >? 256)\n  then (!!(ret_value = Vint (Int.neg (Int.repr 5))) &&\n       (data_at_ Tsh (tarray tuchar out_len) output *\n         da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional *\n         AREP kv I ctx * Stream s))\n  else let F := (mbedtls_HMAC256_DRBG_generate_function s I out_len (contents_with_add additional add_len contents))\n       in (!!(return_value_relate_result F ret_value)) &&\n          (match F with\n            | ENTROPY.error _ _ => (data_at_ Tsh (tarray tuchar out_len) output)\n            | ENTROPY.success (bytes, _) _ => (data_at Tsh (tarray tuchar out_len) (map Vint (map Int.repr bytes)) output)\n          end *\n          da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional *\n          Stream (get_stream_result F) *\n          AREP kv (hmac256drbgabs_generate I s out_len (contents_with_add additional add_len contents)) ctx).\n\nDefinition hmac_drbg_generate_abs_spec :=\n  DECLARE _mbedtls_hmac_drbg_random_with_add\n   WITH contents: list Z,\n        additional: val, add_len: Z,\n        output: val, out_len: Z,\n        ctx: val, \n        I: hmac256drbgabs,\n        kv: val, s: ENTROPY.stream\n    PRE [ _p_rng OF (tptr tvoid), _output OF (tptr tuchar), _out_len OF tuint, \n          _additional OF (tptr tuchar), _add_len OF tuint ]\n       PROP (0 <= add_len <= Int.max_unsigned;\n             0 <= out_len <= Int.max_unsigned;\n             add_len = Zlength contents;\n             hmac256drbgabs_entropy_len I + Zlength contents <= 384;\n             Forall isbyteZ contents)\n       LOCAL (temp _p_rng ctx; temp _output output; temp _out_len (Vint (Int.repr out_len)); \n              temp _additional additional; temp _add_len (Vint (Int.repr add_len)); gvar sha._K256 kv)\n       SEP (data_at_ Tsh (tarray tuchar out_len) output;\n            da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional;\n            AREP kv I ctx; Stream s)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp ret_value)\n       SEP (generate_absPOST ret_value contents additional add_len output out_len ctx I kv s).\n\nDefinition drbg_random_abs_spec :=\n  DECLARE _mbedtls_hmac_drbg_random\n   WITH output: val, n: Z, ctx: val, \n        I: hmac256drbgabs, kv: val, \n        s: ENTROPY.stream, bytes:_, F:_, ss:_\n    PRE [_p_rng OF tptr tvoid, _output OF tptr tuchar, _out_len OF tuint ]\n       PROP (0 <= n <= 1024;\n         mbedtls_generate s I n = Some(bytes, ss, F))\n       LOCAL (temp _p_rng ctx; temp _output output;\n              temp _out_len (Vint (Int.repr n)); gvar sha._K256 kv)\n       SEP (data_at_ Tsh (tarray tuchar n) output;\n            AREP kv I ctx; Stream s)\n    POST [ tint ] \n       PROP () \n       LOCAL (temp ret_temp (Vint Int.zero))\n       SEP (data_at Tsh (tarray tuchar n) (map Vint (map Int.repr bytes)) output;\n            AREP kv F ctx; Stream ss).\n\nDefinition drbg_random_abs_spec1 :=\n  DECLARE _mbedtls_hmac_drbg_random\n   WITH output: val, n: Z, ctx: val, \n        I: hmac256drbgabs, kv: val, \n        s: ENTROPY.stream, bytes:_, J:_, ss:_\n    PRE [_p_rng OF tptr tvoid, _output OF tptr tuchar, _out_len OF tuint ]\n       PROP (0 <= n <= 1024;\n         mbedtls_HMAC256_DRBG_generate_function s I n [] = ENTROPY.success (bytes, J) ss)\n       LOCAL (temp _p_rng ctx; temp _output output;\n              temp _out_len (Vint (Int.repr n)); gvar sha._K256 kv)\n       SEP (data_at_ Tsh (tarray tuchar n) output;\n            AREP kv I ctx; Stream s)\n    POST [ tint ] EX F: hmac256drbgabs,  \n       PROP (F = match J with ((((VV, KK), RC), _), PR) =>\n                   HMAC256DRBGabs KK VV RC (hmac256drbgabs_entropy_len I) PR \n                                 (hmac256drbgabs_reseed_interval I)\n                      end) \n       LOCAL (temp ret_temp (Vint Int.zero))\n       SEP (data_at Tsh (tarray tuchar n) (map Vint (map Int.repr bytes)) output;\n            AREP kv F ctx; Stream ss).\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/hmacdrbg/drbg_protocol_specs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.232460697241573}}
{"text": "Require Import Bool.\nRequire Import Sorting.Permutation.\nRequire Import Omega.\nRequire Import sflib.\nRequire Import Lia.\n\nRequire Import Common.\nRequire Import Value.\nRequire Import Lang.\nRequire Import Memory.\nRequire Import State.\nRequire Import LoadStore.\nRequire Import SmallStep.\nRequire Import SmallStepAux.\nRequire Import SmallStepWf.\nRequire Import Refinement.\nRequire Import SmallStepRefinement.\nRequire Import Reordering.\nRequire Import GVN1.\n\nModule Ir.\n\nModule GVN3.\n\n\n(* 3nd condition of replacing p with q:\n   If p and q are both computed by the gep inbounds with same\n   base pointer, it is valid to replace p with q. *)\nDefinition eqprop_valid3 (m:Ir.Memory.t) (p q:Ir.val) :=\n  exists p0 idx1 idx2 ty1 ty2,\n    p = Ir.SmallStep.gep p0 idx1 ty1 m true /\\\n    q = Ir.SmallStep.gep p0 idx2 ty2 m true.\n\n\n\n(*********************************************************\n Important property of eqprop_valid3:\n  If eqprop_valid3 p q holds, and `icmp eq p, q` evaluates\n    to true, then p and q are exactly the same pointer.\n *********************************************************)\n\nLemma twos_compl_twos_compl_add_PTRSZ:\n  forall n x,\n    Ir.SmallStep.twos_compl (Ir.SmallStep.twos_compl_add n x Ir.PTRSZ) Ir.PTRSZ =\n    Ir.SmallStep.twos_compl_add n x Ir.PTRSZ.\nProof.\n  intros.\n  rewrite Ir.PTRSZ_def.\n  unfold Ir.SmallStep.twos_compl_add.\n  unfold Ir.SmallStep.twos_compl.\n  rewrite Nat.mod_mod. reflexivity.\n  apply shiftl_2_nonzero.\nQed.\n\nTheorem gep_never_returns_num:\n  forall v p idx ty m inb\n    (HGEP1:Ir.SmallStep.gep p idx ty m inb = v),\n    ~exists n, v = Ir.num n.\nProof.\n  intros.\n  unfold Ir.SmallStep.gep in HGEP1.\n  intros HH.\n  inv HH.\n  des_ifs.\nQed.\n\n(* I had to split the big theorem into lemmas due to\n   Coq bug - Coq does not terminate processing of 'Qed.', due to unknown reason :( *)\nLemma eqprop_valid3_after_icmpeq_true_log:\n  forall md st st' r ptrty op1 op2 p1 p2 e l0 o0 idx1 ty1 idx2 ty2\n    (HWF:Ir.Config.wf md st)\n    (HINST:Some (Ir.Inst.iicmp_eq r ptrty op1 op2) = Ir.Config.cur_inst md st)\n    (HOP1:Some (Ir.ptr p1) = Ir.Config.get_val st op1)\n    (HOP2:Some (Ir.ptr p2) = Ir.Config.get_val st op2)\n    (* geps *)\n    (HGEP1:(Ir.ptr p1) = Ir.SmallStep.gep (Ir.plog l0 o0) idx1 ty1 (Ir.Config.m st) true)\n    (HGEP2:(Ir.ptr p2) = Ir.SmallStep.gep (Ir.plog l0 o0) idx2 ty2 (Ir.Config.m st) true)\n    (* have a small step *)\n    (HSTEP:Ir.SmallStep.sstep md st (Ir.SmallStep.sr_success e st'))\n    (* p1 == p2 is true *)\n    (HTRUE:Some (Ir.num 1) = Ir.Config.get_val st' (Ir.opreg r)),\n\n    p1 = p2.\nProof.\n  intros.\n\n  assert (HS:Ir.Config.s st <> []).\n  {\n    unfold Ir.Config.cur_inst in HINST.\n    unfold Ir.Config.cur_fdef_pc in HINST.\n    des_ifs.\n  }\n\n  inv HSTEP.\n  { inv HISTEP; try congruence.\n    { unfold Ir.SmallStep.inst_det_step in HNEXT.\n      rewrite <- HINST in HNEXT.\n      rewrite <- HOP1, <- HOP2 in HNEXT.\n      unfold Ir.SmallStep.icmp_eq_ptr in HNEXT.\n      unfold Ir.SmallStep.gep in *.\n      des_ifs.\n      {\n        rewrite Ir.SmallStep.get_val_update_reg_and_incrpc in HTRUE.\n        unfold Ir.Config.get_val in HTRUE.\n        rewrite Ir.Config.get_rval_update_rval_id in HTRUE.\n        inv HTRUE.\n        des_ifs.\n        rewrite Nat.eqb_eq in Heq3. congruence. assumption.\n      }\n      {\n        rewrite Ir.SmallStep.get_val_update_reg_and_incrpc in HTRUE.\n        unfold Ir.Config.get_val in HTRUE.\n        rewrite Ir.Config.get_rval_update_rval_id in HTRUE.\n        inv HTRUE.\n        des_ifs.\n      }\n    }\n    { rewrite <- HINST in HCUR.\n      inv HCUR.\n      rewrite <- HOP1 in HOP0. inv HOP0.\n      rewrite <- HOP2 in HOP3. inv HOP3.\n      unfold Ir.SmallStep.gep in *.\n      unfold Ir.SmallStep.icmp_eq_ptr_nondet_cond in *.\n      des_ifs; rewrite Nat.eqb_refl in HNONDET; inv HNONDET.\n    }\n  }\n  { apply Ir.Config.cur_inst_not_cur_terminator in HINST.\n    unfold Ir.SmallStep.t_step in HTSTEP. rewrite <- HINST in HTSTEP.\n    congruence.\n  }\nQed.\n\n(* due to Coq bug, I made a separated lemmax *)\nLemma gep_helper_small:\n  forall n l o x1 x3 st p0 n'1\n(HVAL2 : Ir.SmallStep.gep (Ir.pphy n l o) x1 x3 (Ir.Config.m st) true =\n          Ir.ptr p0)\n(Heqn'1: n'1 =\n           Ir.SmallStep.twos_compl_add n (x1 * Ir.ty_bytesz x3)\n             Ir.PTRSZ),\n  p0 = Ir.pphy n'1 (n::n'1::l) o.\nProof.\n  intros. unfold Ir.SmallStep.gep in HVAL2. des_ifs.\nQed.\n\nLemma gep_helper:\n  forall n l o x1 x3 x0 x2 st p0 p st' r e md\n(HVAL2 : Ir.SmallStep.gep (Ir.pphy n l o) x1 x3 (Ir.Config.m st) true =\n          Ir.ptr p0)\n(HVAL1 : Ir.SmallStep.gep (Ir.pphy n l o) x0 x2 (Ir.Config.m st) true =\n          Ir.ptr p)\n(HTRUE : Some (Ir.num 1) = Ir.Config.get_val st' (Ir.opreg r))\n(HNEXT : Some (Ir.SmallStep.sr_success e st') =\n          match Ir.SmallStep.icmp_eq_ptr p p0 (Ir.Config.m st) with\n          | Some b =>\n              Some\n                (Ir.SmallStep.sr_success Behaviors.Ir.e_none\n                   (Ir.SmallStep.update_reg_and_incrpc md st r\n                      (Ir.SmallStep.to_num b)))\n          | None => None\n          end)\n(HS : Ir.Config.s st <> []),\n    Ir.ptr p = Ir.ptr p0.\nProof.\n  intros.\n  eapply gep_helper_small in HVAL2; try reflexivity.\n  eapply gep_helper_small in HVAL1; try reflexivity.\n  rewrite HVAL1, HVAL2 in HNEXT.\n  unfold Ir.SmallStep.icmp_eq_ptr in HNEXT.\n  unfold Ir.SmallStep.p2N in HNEXT.\n  rewrite Nat.min_id in HNEXT.\n  rewrite twos_compl_twos_compl_add_PTRSZ in HNEXT.\n  inversion HNEXT.\n  rewrite H1 in HTRUE.\n  rewrite Ir.SmallStep.get_val_update_reg_and_incrpc in HTRUE.\n  unfold Ir.Config.get_val in HTRUE.\n  rewrite Ir.Config.get_rval_update_rval_id in HTRUE.\n  inversion HTRUE.\n  destruct (Ir.SmallStep.twos_compl_add n (x0 * Ir.ty_bytesz x2) Ir.PTRSZ =?\n         Ir.SmallStep.twos_compl_add n (x1 * Ir.ty_bytesz x3) Ir.PTRSZ)\n           eqn:Heq; try congruence.\n  rewrite Nat.eqb_eq in Heq. rewrite HVAL1, HVAL2, Heq.\n  reflexivity.\n  assumption.\nQed. (* This is really strange.. Why Qed never ends? *)\n\n\nTheorem eqprop_valid3_after_icmpeq_true:\n  forall md st st' r ptrty op1 op2 v1 v2 e\n    (HWF:Ir.Config.wf md st)\n    (HINST:Some (Ir.Inst.iicmp_eq r ptrty op1 op2) = Ir.Config.cur_inst md st)\n    (HOP1:Some v1 = Ir.Config.get_val st op1)\n    (HOP2:Some v2 = Ir.Config.get_val st op2)\n    (* eqprop_valid3 holds *)\n    (HEQPROP:eqprop_valid3 (Ir.Config.m st) v1 v2)\n    (* have a small step *)\n    (HSTEP:Ir.SmallStep.sstep md st (Ir.SmallStep.sr_success e st'))\n    (* p1 == p2 is true *)\n    (HTRUE:Some (Ir.num 1) = Ir.Config.get_val st' (Ir.opreg r)),\n\n    v1 = v2.\nProof.\n  intros.\n  assert (HS:Ir.Config.s st <> []).\n  {\n    unfold Ir.Config.cur_inst in HINST.\n    unfold Ir.Config.cur_fdef_pc in HINST.\n    des_ifs.\n  }\n\n  inv HSTEP.\n  { inv HISTEP; try congruence.\n    { inv HEQPROP.\n      inv H. inv H0. inv H. inv H0. inv H.\n      destruct x.\n      { destruct (Ir.SmallStep.gep (Ir.plog b n) x0 x2 (Ir.Config.m st) true) eqn:HVAL1;\n          destruct (Ir.SmallStep.gep (Ir.plog b n) x1 x3 (Ir.Config.m st) true) eqn:HVAL2;\n        try (apply gep_never_returns_num in HVAL1;\n             exfalso; apply HVAL1; eexists; reflexivity);\n        try (apply gep_never_returns_num in HVAL2;\n             exfalso; apply HVAL2; eexists; reflexivity).\n        { exploit eqprop_valid3_after_icmpeq_true_log.\n          { eassumption. }\n          { eassumption. }\n          { eassumption. }\n          { eassumption. }\n          { rewrite HVAL1. reflexivity. }\n          { rewrite HVAL2. reflexivity. }\n          { eapply Ir.SmallStep.ss_inst.\n            eapply Ir.SmallStep.s_det.\n            eassumption. }\n          { eassumption. }\n          intros HH. congruence.\n        }\n        { unfold Ir.SmallStep.inst_det_step in HNEXT.\n          rewrite <- HINST in HNEXT.\n          rewrite <- HOP2 in HNEXT. des_ifs.\n          rewrite Ir.SmallStep.get_val_update_reg_and_incrpc in HTRUE.\n          unfold Ir.Config.get_val in HTRUE.\n          rewrite Ir.Config.get_rval_update_rval_id in HTRUE.\n          inv HTRUE. assumption.\n        }\n        { unfold Ir.SmallStep.inst_det_step in HNEXT.\n          rewrite <- HINST in HNEXT.\n          rewrite <- HOP1 in HNEXT. des_ifs.\n          rewrite Ir.SmallStep.get_val_update_reg_and_incrpc in HTRUE.\n          unfold Ir.Config.get_val in HTRUE.\n          rewrite Ir.Config.get_rval_update_rval_id in HTRUE.\n          inv HTRUE. assumption.\n        }\n        { unfold Ir.SmallStep.inst_det_step in HNEXT.\n          rewrite <- HINST in HNEXT.\n          rewrite <- HOP2 in HNEXT. des_ifs.\n        }\n      }\n      { (* phy. *)\n        unfold Ir.SmallStep.inst_det_step in HNEXT.\n        rewrite <- HINST in HNEXT.\n        rewrite <- HOP1, <- HOP2 in HNEXT.\n\n        destruct (Ir.SmallStep.gep (Ir.pphy n l o) x0 x2 (Ir.Config.m st) true) eqn:HVAL1;\n          destruct (Ir.SmallStep.gep (Ir.pphy n l o) x1 x3 (Ir.Config.m st) true) eqn:HVAL2;\n        try (apply gep_never_returns_num in HVAL1;\n             exfalso; apply HVAL1; eexists; reflexivity);\n        try (apply gep_never_returns_num in HVAL2;\n             exfalso; apply HVAL2; eexists; reflexivity).\n        { eapply gep_helper; try eassumption. }\n        { inv HNEXT.\n          rewrite Ir.SmallStep.get_val_update_reg_and_incrpc in HTRUE.\n          unfold Ir.Config.get_val in HTRUE.\n          rewrite Ir.Config.get_rval_update_rval_id in HTRUE.\n          inv HTRUE. assumption. }\n        { inv HNEXT.\n          rewrite Ir.SmallStep.get_val_update_reg_and_incrpc in HTRUE.\n          unfold Ir.Config.get_val in HTRUE.\n          rewrite Ir.Config.get_rval_update_rval_id in HTRUE.\n          inv HTRUE. assumption. }\n        { reflexivity. }\n      }\n    }\n    { (* well, cannot be nondet... *)\n      rewrite <- HINST in HCUR. inv HCUR.\n      rewrite <- HOP1 in HOP0. inv HOP0.\n      rewrite <- HOP2 in HOP3. inv HOP3.\n      inv HEQPROP.\n      inv H. inv H0. inv H. inv H0. destruct H.\n      destruct x.\n      { assert (HOFS1:exists ofs1, p1 = (Ir.plog b ofs1)).\n        { unfold Ir.SmallStep.gep in H.\n          unfold Ir.SmallStep.gep in H0.\n          unfold Ir.SmallStep.icmp_eq_ptr_nondet_cond in HNONDET.\n          des_ifs; eexists; reflexivity. }\n        assert (HOFS2:exists ofs2, p2 = (Ir.plog b ofs2)).\n        { unfold Ir.SmallStep.gep in H.\n          unfold Ir.SmallStep.gep in H0.\n          unfold Ir.SmallStep.icmp_eq_ptr_nondet_cond in HNONDET.\n          des_ifs; eexists; reflexivity. }\n        inv HOFS1. inv HOFS2.\n        unfold Ir.SmallStep.icmp_eq_ptr_nondet_cond in HNONDET.\n        des_ifs;\n          rewrite Nat.eqb_refl in HNONDET; inv HNONDET.\n      }\n      { assert (HOFS1:exists a1 b1 c1, p1 = (Ir.pphy a1 b1 c1)).\n        { unfold Ir.SmallStep.gep in H.\n          unfold Ir.SmallStep.gep in H0.\n          unfold Ir.SmallStep.icmp_eq_ptr_nondet_cond in HNONDET.\n          des_ifs; eexists; reflexivity. }\n        assert (HOFS2:exists a2 b2 c2, p2 = (Ir.pphy a2 b2 c2)).\n        { unfold Ir.SmallStep.gep in H.\n          unfold Ir.SmallStep.gep in H0.\n          unfold Ir.SmallStep.icmp_eq_ptr_nondet_cond in HNONDET.\n          des_ifs; eexists; reflexivity. }\n        inv HOFS1. inv H1. inv H2.\n        inv HOFS2. inv H1. inv H2.\n        unfold Ir.SmallStep.icmp_eq_ptr_nondet_cond in HNONDET.\n        des_ifs.\n      }\n    }\n  }\n  { (* terminator! *)\n    apply Ir.Config.cur_inst_not_cur_terminator in HINST.\n    unfold Ir.SmallStep.t_step in HTSTEP.\n    rewrite <- HINST in HTSTEP.\n    congruence.\n  }\nQed.\n\n(*********************************************************\n    Okay, from theorem `eqprop_valid3_after_icmpeq_true`,\n    we can say that two pointers have same value after\n    `p == q` check.\n    It is trivial to have same execution when same value\n    is given, hence not proved.\n *********************************************************)\n\nEnd GVN3.\n\nEnd Ir.", "meta": {"author": "aqjune", "repo": "twinsem", "sha": "c9cc45994bbc7545d32cad0a918492666e6bb69f", "save_path": "github-repos/coq/aqjune-twinsem", "path": "github-repos/coq/aqjune-twinsem/twinsem-c9cc45994bbc7545d32cad0a918492666e6bb69f/GVN3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.232460697241573}}
{"text": "(* Default settings (from HsToCoq.Coq.Preamble) *)\n\nGeneralizable All Variables.\n\nUnset Implicit Arguments.\nSet Maximal Implicit Insertion.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Coq.Program.Tactics.\nRequire Coq.Program.Wf.\n\n(* Preamble *)\n\nRequire String BitTerminationProofs.\nImport String.StringSyntax.\n\n(* Converted imports: *)\n\nRequire Coq.Init.Peano.\nRequire Data.Bits.\nRequire Data.Foldable.\nRequire Data.Maybe.\nRequire Data.Tuple.\nRequire GHC.Base.\nRequire GHC.Err.\nRequire GHC.Num.\nRequire GHC.Wf.\nRequire IntWord.\nImport Data.Bits.Notations.\nImport GHC.Base.Notations.\nImport GHC.Num.Notations.\n\n(* Converted type declarations: *)\n\nDefinition Prefix :=\n  IntWord.Int%type.\n\nDefinition Nat :=\n  IntWord.Word%type.\n\nDefinition Mask :=\n  IntWord.Int%type.\n\nDefinition Key :=\n  IntWord.Int%type.\n\nDefinition BitMap :=\n  IntWord.Word%type.\n\nInductive IntSet : Type\n  := | Bin : Prefix -> Mask -> IntSet -> IntSet -> IntSet\n  |  Tip : Prefix -> BitMap -> IntSet\n  |  Nil : IntSet.\n\nInductive Stack : Type\n  := | Push : Prefix -> IntSet -> Stack -> Stack\n  |  Nada : Stack.\n\nInstance Default__IntSet : GHC.Err.Default IntSet :=\n  GHC.Err.Build_Default _ Nil.\n\nInstance Default__Stack : GHC.Err.Default Stack := GHC.Err.Build_Default _ Nada.\n\n(* Midamble *)\n\n(** Additional definitions for termination proof *)\n\nFixpoint size_nat (t : IntSet) : nat :=\n  match t with\n  | Bin _ _ l r => S (size_nat l + size_nat r)%nat\n  | Tip _ bm => 0\n  | Nil => 0\n  end.\n\nRequire Omega.\nLtac termination_by_omega :=\n  Coq.Program.Tactics.program_simpl;\n  simpl;Omega.omega.\n\n(* Converted value declarations: *)\n\nDefinition intFromNat :=\n  IntWord.intFromWord.\n\nDefinition natFromInt :=\n  IntWord.wordFromInt.\n\nDefinition branchMask : Prefix -> Prefix -> Mask :=\n  fun p1 p2 =>\n    intFromNat (IntWord.highestBitMask (Data.Bits.xor (natFromInt p1) (natFromInt\n                                                       p2))).\n\nDefinition maskW : Nat -> Nat -> Prefix :=\n  fun i m =>\n    intFromNat (i Data.Bits..&.(**)\n                (Data.Bits.xor (Data.Bits.complement (m GHC.Num.- #1)) m)).\n\nDefinition mask : IntWord.Int -> Mask -> Prefix :=\n  fun i m => maskW (natFromInt i) (natFromInt m).\n\nDefinition zero : IntWord.Int -> Mask -> bool :=\n  fun i m => ((natFromInt i) Data.Bits..&.(**) (natFromInt m)) GHC.Base.== #0.\n\nDefinition link : Prefix -> IntSet -> Prefix -> IntSet -> IntSet :=\n  fun p1 t1 p2 t2 =>\n    let m := branchMask p1 p2 in\n    let p := mask p1 m in if zero p1 m : bool then Bin p m t1 t2 else Bin p m t2 t1.\n\nDefinition nomatch : IntWord.Int -> Prefix -> Mask -> bool :=\n  fun i p m => (mask i m) GHC.Base./= p.\n\nFixpoint insertBM (arg_0__ : Prefix) (arg_1__ : BitMap) (arg_2__ : IntSet)\n           : IntSet\n           := match arg_0__, arg_1__, arg_2__ with\n              | kx, bm, (Bin p m l r as t) =>\n                  if nomatch kx p m : bool then link kx (Tip kx bm) p t else\n                  if zero kx m : bool then Bin p m (insertBM kx bm l) r else\n                  Bin p m l (insertBM kx bm r)\n              | kx, bm, (Tip kx' bm' as t) =>\n                  if kx' GHC.Base.== kx : bool then Tip kx' (bm Data.Bits..|.(**) bm') else\n                  link kx (Tip kx bm) kx' t\n              | kx, bm, Nil => Tip kx bm\n              end.\n\nDefinition shorter : Mask -> Mask -> bool :=\n  fun m1 m2 => (natFromInt m1) GHC.Base.> (natFromInt m2).\n\nProgram Fixpoint union (arg_0__ arg_1__ : IntSet) {measure (size_nat arg_0__ +\n                        size_nat arg_1__)} : IntSet\n                   := match arg_0__, arg_1__ with\n                      | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n                          let union2 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then link p1 t1 p2 t2 else\n                            if Bool.Sumbool.sumbool_of_bool (zero p1 m2)\n                            then Bin p2 m2 (union t1 l2) r2 else\n                            Bin p2 m2 l2 (union t1 r2) in\n                          let union1 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then link p1 t1 p2 t2 else\n                            if Bool.Sumbool.sumbool_of_bool (zero p2 m1)\n                            then Bin p1 m1 (union l1 t2) r1 else\n                            Bin p1 m1 l1 (union r1 t2) in\n                          if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then union1 else\n                          if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then union2 else\n                          if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n                          then Bin p1 m1 (union l1 l2) (union r1 r2) else\n                          link p1 t1 p2 t2\n                      | (Bin _ _ _ _ as t), Tip kx bm => insertBM kx bm t\n                      | (Bin _ _ _ _ as t), Nil => t\n                      | Tip kx bm, t => insertBM kx bm t\n                      | Nil, t => t\n                      end.\nSolve Obligations with (termination_by_omega).\n\nLocal Definition Semigroup__IntSet_op_zlzlzgzg__ : IntSet -> IntSet -> IntSet :=\n  union.\n\nProgram Instance Semigroup__IntSet : GHC.Base.Semigroup IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zlzlzgzg____ := Semigroup__IntSet_op_zlzlzgzg__ |}.\n\nLocal Definition Monoid__IntSet_mappend : IntSet -> IntSet -> IntSet :=\n  _GHC.Base.<<>>_.\n\nDefinition empty : IntSet :=\n  Nil.\n\nDefinition unions {f} `{Data.Foldable.Foldable f} : f IntSet -> IntSet :=\n  fun xs => Data.Foldable.foldl' union empty xs.\n\nLocal Definition Monoid__IntSet_mconcat : list IntSet -> IntSet :=\n  unions.\n\nLocal Definition Monoid__IntSet_mempty : IntSet :=\n  empty.\n\nProgram Instance Monoid__IntSet : GHC.Base.Monoid IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.mappend__ := Monoid__IntSet_mappend ;\n           GHC.Base.mconcat__ := Monoid__IntSet_mconcat ;\n           GHC.Base.mempty__ := Monoid__IntSet_mempty |}.\n\n(* Skipping all instances of class `Data.Data.Data', including\n   `Data.IntSet.InternalWord.Data__IntSet' *)\n\n(* Skipping all instances of class `GHC.Exts.IsList', including\n   `Data.IntSet.InternalWord.IsList__IntSet' *)\n\nFixpoint equal (arg_0__ arg_1__ : IntSet) : bool\n           := match arg_0__, arg_1__ with\n              | Bin p1 m1 l1 r1, Bin p2 m2 l2 r2 =>\n                  andb (m1 GHC.Base.== m2) (andb (p1 GHC.Base.== p2) (andb (equal l1 l2) (equal r1\n                                                                            r2)))\n              | Tip kx1 bm1, Tip kx2 bm2 => andb (kx1 GHC.Base.== kx2) (bm1 GHC.Base.== bm2)\n              | Nil, Nil => true\n              | _, _ => false\n              end.\n\nLocal Definition Eq___IntSet_op_zeze__ : IntSet -> IntSet -> bool :=\n  fun t1 t2 => equal t1 t2.\n\nFixpoint nequal (arg_0__ arg_1__ : IntSet) : bool\n           := match arg_0__, arg_1__ with\n              | Bin p1 m1 l1 r1, Bin p2 m2 l2 r2 =>\n                  orb (m1 GHC.Base./= m2) (orb (p1 GHC.Base./= p2) (orb (nequal l1 l2) (nequal r1\n                                                                         r2)))\n              | Tip kx1 bm1, Tip kx2 bm2 => orb (kx1 GHC.Base./= kx2) (bm1 GHC.Base./= bm2)\n              | Nil, Nil => false\n              | _, _ => true\n              end.\n\nLocal Definition Eq___IntSet_op_zsze__ : IntSet -> IntSet -> bool :=\n  fun t1 t2 => nequal t1 t2.\n\nProgram Instance Eq___IntSet : GHC.Base.Eq_ IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zeze____ := Eq___IntSet_op_zeze__ ;\n           GHC.Base.op_zsze____ := Eq___IntSet_op_zsze__ |}.\n\nDefinition indexOfTheOnlyBit :=\n  IntWord.indexOfTheOnlyBit.\n\nDefinition lowestBitMask : Nat -> Nat :=\n  fun x => x Data.Bits..&.(**) GHC.Num.negate x.\n\nDefinition revNat : Nat -> Nat :=\n  fun x1 =>\n    let 'x2 := ((IntWord.shiftRWord x1 #1) Data.Bits..&.(**) #6148914691236517205)\n                 Data.Bits..|.(**)\n                 (IntWord.shiftLWord (x1 Data.Bits..&.(**) #6148914691236517205) #1) in\n    let 'x3 := ((IntWord.shiftRWord x2 #2) Data.Bits..&.(**) #3689348814741910323)\n                 Data.Bits..|.(**)\n                 (IntWord.shiftLWord (x2 Data.Bits..&.(**) #3689348814741910323) #2) in\n    let 'x4 := ((IntWord.shiftRWord x3 #4) Data.Bits..&.(**) #1085102592571150095)\n                 Data.Bits..|.(**)\n                 (IntWord.shiftLWord (x3 Data.Bits..&.(**) #1085102592571150095) #4) in\n    let 'x5 := ((IntWord.shiftRWord x4 #8) Data.Bits..&.(**) #71777214294589695)\n                 Data.Bits..|.(**)\n                 (IntWord.shiftLWord (x4 Data.Bits..&.(**) #71777214294589695) #8) in\n    let 'x6 := ((IntWord.shiftRWord x5 #16) Data.Bits..&.(**) #281470681808895)\n                 Data.Bits..|.(**)\n                 (IntWord.shiftLWord (x5 Data.Bits..&.(**) #281470681808895) #16) in\n    (IntWord.shiftRWord x6 #32) Data.Bits..|.(**) (IntWord.shiftLWord x6 #32).\n\nProgram Definition foldrBits {a}\n           : IntWord.Int -> (IntWord.Int -> a -> a) -> a -> Nat -> a :=\n          fun prefix f z bitmap =>\n            let go :=\n              GHC.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                               IntWord.wordTonat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                               match arg_0__, arg_1__ with\n                               | num_2__, acc =>\n                                   if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                                   match arg_0__, arg_1__ with\n                                   | bm, acc =>\n                                       let bitmask := lowestBitMask bm in\n                                       let bi := indexOfTheOnlyBit bitmask in\n                                       go (Data.Bits.xor bm bitmask) ((f ((prefix GHC.Num.+ (#64 GHC.Num.- #1))\n                                                                          GHC.Num.-\n                                                                          bi)) acc)\n                                   end\n                               end) in\n            go (revNat bitmap) z.\nAdmit Obligations.\n\nDefinition foldr {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | z', Nil => z'\n                 | z', Tip kx bm => foldrBits kx f z' bm\n                 | z', Bin _ _ l r => go (go z' r) l\n                 end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z l) r else go (go z r) l\n      | _ => go z t\n      end.\n\nDefinition toAscList : IntSet -> list Key :=\n  foldr cons nil.\n\nLocal Definition Ord__IntSet_compare : IntSet -> IntSet -> comparison :=\n  fun s1 s2 => GHC.Base.compare (toAscList s1) (toAscList s2).\n\nLocal Definition Ord__IntSet_op_zl__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base.== Lt.\n\nLocal Definition Ord__IntSet_op_zlze__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base./= Gt.\n\nLocal Definition Ord__IntSet_op_zg__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base.== Gt.\n\nLocal Definition Ord__IntSet_op_zgze__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base./= Lt.\n\nLocal Definition Ord__IntSet_max : IntSet -> IntSet -> IntSet :=\n  fun x y => if Ord__IntSet_op_zlze__ x y : bool then y else x.\n\nLocal Definition Ord__IntSet_min : IntSet -> IntSet -> IntSet :=\n  fun x y => if Ord__IntSet_op_zlze__ x y : bool then x else y.\n\nProgram Instance Ord__IntSet : GHC.Base.Ord IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zl____ := Ord__IntSet_op_zl__ ;\n           GHC.Base.op_zlze____ := Ord__IntSet_op_zlze__ ;\n           GHC.Base.op_zg____ := Ord__IntSet_op_zg__ ;\n           GHC.Base.op_zgze____ := Ord__IntSet_op_zgze__ ;\n           GHC.Base.compare__ := Ord__IntSet_compare ;\n           GHC.Base.max__ := Ord__IntSet_max ;\n           GHC.Base.min__ := Ord__IntSet_min |}.\n\n(* Skipping all instances of class `GHC.Show.Show', including\n   `Data.IntSet.InternalWord.Show__IntSet' *)\n\n(* Skipping all instances of class `GHC.Read.Read', including\n   `Data.IntSet.InternalWord.Read__IntSet' *)\n\n(* Skipping all instances of class `Control.DeepSeq.NFData', including\n   `Data.IntSet.InternalWord.NFData__IntSet' *)\n\nDefinition bin : Prefix -> Mask -> IntSet -> IntSet -> IntSet :=\n  fun arg_0__ arg_1__ arg_2__ arg_3__ =>\n    match arg_0__, arg_1__, arg_2__, arg_3__ with\n    | _, _, l, Nil => l\n    | _, _, Nil, r => r\n    | p, m, l, r => Bin p m l r\n    end.\n\nDefinition tip : Prefix -> BitMap -> IntSet :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | _, num_2__ =>\n        if num_2__ GHC.Base.== #0 : bool then Nil else\n        match arg_0__, arg_1__ with\n        | kx, bm => Tip kx bm\n        end\n    end.\n\nFixpoint deleteBM (arg_0__ : Prefix) (arg_1__ : BitMap) (arg_2__ : IntSet)\n           : IntSet\n           := match arg_0__, arg_1__, arg_2__ with\n              | kx, bm, (Bin p m l r as t) =>\n                  if nomatch kx p m : bool then t else\n                  if zero kx m : bool then bin p m (deleteBM kx bm l) r else\n                  bin p m l (deleteBM kx bm r)\n              | kx, bm, (Tip kx' bm' as t) =>\n                  if kx' GHC.Base.== kx : bool\n                  then tip kx (bm' Data.Bits..&.(**) Data.Bits.complement bm) else\n                  t\n              | _, _, Nil => Nil\n              end.\n\nProgram Fixpoint difference (arg_0__ arg_1__ : IntSet) {measure (size_nat\n                             arg_0__ +\n                             size_nat arg_1__)} : IntSet\n                   := match arg_0__, arg_1__ with\n                      | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n                          let difference2 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then t1 else\n                            if Bool.Sumbool.sumbool_of_bool (zero p1 m2) then difference t1 l2 else\n                            difference t1 r2 in\n                          let difference1 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then t1 else\n                            if Bool.Sumbool.sumbool_of_bool (zero p2 m1)\n                            then bin p1 m1 (difference l1 t2) r1 else\n                            bin p1 m1 l1 (difference r1 t2) in\n                          if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then difference1 else\n                          if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then difference2 else\n                          if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n                          then bin p1 m1 (difference l1 l2) (difference r1 r2) else\n                          t1\n                      | (Bin _ _ _ _ as t), Tip kx bm => deleteBM kx bm t\n                      | (Bin _ _ _ _ as t), Nil => t\n                      | (Tip kx bm as t1), t2 =>\n                          let fix differenceTip arg_12__\n                                    := match arg_12__ with\n                                       | Bin p2 m2 l2 r2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx p2 m2) then t1 else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx m2) then differenceTip l2 else\n                                           differenceTip r2\n                                       | Tip kx2 bm2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx GHC.Base.== kx2)\n                                           then tip kx (bm Data.Bits..&.(**) Data.Bits.complement bm2) else\n                                           t1\n                                       | Nil => t1\n                                       end in\n                          differenceTip t2\n                      | Nil, _ => Nil\n                      end.\nSolve Obligations with (termination_by_omega).\n\nDefinition op_zrzr__ : IntSet -> IntSet -> IntSet :=\n  fun m1 m2 => difference m1 m2.\n\nNotation \"'_\\\\_'\" := (op_zrzr__).\n\nInfix \"\\\\\" := (_\\\\_) (at level 99).\n\n(* Skipping definition `Data.IntSet.InternalWord.fromListConstr' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.intSetDataType' *)\n\nDefinition null : IntSet -> bool :=\n  fun arg_0__ => match arg_0__ with | Nil => true | _ => false end.\n\nDefinition size : IntSet -> IntWord.Int :=\n  let fix go arg_0__ arg_1__\n            := match arg_0__, arg_1__ with\n               | acc, Bin _ _ l r => go (go acc l) r\n               | acc, Tip _ bm => acc GHC.Num.+ IntWord.bitcount #0 bm\n               | acc, Nil => acc\n               end in\n  go #0.\n\nDefinition bitmapOfSuffix : IntWord.Int -> BitMap :=\n  fun s => IntWord.shiftLWord #1 s.\n\nDefinition suffixBitMask : IntWord.Int :=\n  #63.\n\nDefinition suffixOf : IntWord.Int -> IntWord.Int :=\n  fun x => x Data.Bits..&.(**) suffixBitMask.\n\nDefinition bitmapOf : IntWord.Int -> BitMap :=\n  fun x => bitmapOfSuffix (suffixOf x).\n\nDefinition prefixBitMask : IntWord.Int :=\n  Data.Bits.complement suffixBitMask.\n\nDefinition prefixOf : IntWord.Int -> Prefix :=\n  fun x => x Data.Bits..&.(**) prefixBitMask.\n\nDefinition member : Key -> IntSet -> bool :=\n  fun x =>\n    let fix go arg_0__\n              := match arg_0__ with\n                 | Bin p m l r =>\n                     if nomatch x p m : bool then false else\n                     if zero x m : bool then go l else\n                     go r\n                 | Tip y bm =>\n                     andb (prefixOf x GHC.Base.== y) ((bitmapOf x Data.Bits..&.(**) bm) GHC.Base./=\n                           #0)\n                 | Nil => false\n                 end in\n    go.\n\nDefinition notMember : Key -> IntSet -> bool :=\n  fun k => negb GHC.Base.∘ member k.\n\nDefinition highestBitSet : Nat -> IntWord.Int :=\n  fun x => indexOfTheOnlyBit (IntWord.highestBitMask x).\n\nFixpoint unsafeFindMax (arg_0__ : IntSet) : option Key\n           := match arg_0__ with\n              | Nil => None\n              | Tip kx bm => Some (kx GHC.Num.+ highestBitSet bm)\n              | Bin _ _ _ r => unsafeFindMax r\n              end.\n\nDefinition lookupLT : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | def, Bin p m l r =>\n                     if nomatch x p m : bool\n                     then if x GHC.Base.< p : bool\n                          then unsafeFindMax def\n                          else unsafeFindMax r else\n                     if zero x m : bool then go def l else\n                     go l r\n                 | def, Tip kx bm =>\n                     let maskLT := (bitmapOf x GHC.Num.- #1) Data.Bits..&.(**) bm in\n                     if prefixOf x GHC.Base.> kx : bool\n                     then Some (kx GHC.Num.+ highestBitSet bm) else\n                     if andb (prefixOf x GHC.Base.== kx) (maskLT GHC.Base./= #0) : bool\n                     then Some (kx GHC.Num.+ highestBitSet maskLT) else\n                     unsafeFindMax def\n                 | def, Nil => unsafeFindMax def\n                 end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go r l\n             else go Nil r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition lowestBitSet : Nat -> IntWord.Int :=\n  fun x => indexOfTheOnlyBit (lowestBitMask x).\n\nFixpoint unsafeFindMin (arg_0__ : IntSet) : option Key\n           := match arg_0__ with\n              | Nil => None\n              | Tip kx bm => Some (kx GHC.Num.+ lowestBitSet bm)\n              | Bin _ _ l _ => unsafeFindMin l\n              end.\n\nDefinition lookupGT : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | def, Bin p m l r =>\n                     if nomatch x p m : bool\n                     then if x GHC.Base.< p : bool\n                          then unsafeFindMin l\n                          else unsafeFindMin def else\n                     if zero x m : bool then go r l else\n                     go def r\n                 | def, Tip kx bm =>\n                     let maskGT :=\n                       (GHC.Num.negate (IntWord.shiftLWord (bitmapOf x) #1)) Data.Bits..&.(**) bm in\n                     if prefixOf x GHC.Base.< kx : bool then Some (kx GHC.Num.+ lowestBitSet bm) else\n                     if andb (prefixOf x GHC.Base.== kx) (maskGT GHC.Base./= #0) : bool\n                     then Some (kx GHC.Num.+ lowestBitSet maskGT) else\n                     unsafeFindMin def\n                 | def, Nil => unsafeFindMin def\n                 end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go Nil l\n             else go l r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition lookupLE : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | def, Bin p m l r =>\n                     if nomatch x p m : bool\n                     then if x GHC.Base.< p : bool\n                          then unsafeFindMax def\n                          else unsafeFindMax r else\n                     if zero x m : bool then go def l else\n                     go l r\n                 | def, Tip kx bm =>\n                     let maskLE :=\n                       ((IntWord.shiftLWord (bitmapOf x) #1) GHC.Num.- #1) Data.Bits..&.(**) bm in\n                     if prefixOf x GHC.Base.> kx : bool\n                     then Some (kx GHC.Num.+ highestBitSet bm) else\n                     if andb (prefixOf x GHC.Base.== kx) (maskLE GHC.Base./= #0) : bool\n                     then Some (kx GHC.Num.+ highestBitSet maskLE) else\n                     unsafeFindMax def\n                 | def, Nil => unsafeFindMax def\n                 end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go r l\n             else go Nil r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition lookupGE : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | def, Bin p m l r =>\n                     if nomatch x p m : bool\n                     then if x GHC.Base.< p : bool\n                          then unsafeFindMin l\n                          else unsafeFindMin def else\n                     if zero x m : bool then go r l else\n                     go def r\n                 | def, Tip kx bm =>\n                     let maskGE := (GHC.Num.negate (bitmapOf x)) Data.Bits..&.(**) bm in\n                     if prefixOf x GHC.Base.< kx : bool then Some (kx GHC.Num.+ lowestBitSet bm) else\n                     if andb (prefixOf x GHC.Base.== kx) (maskGE GHC.Base./= #0) : bool\n                     then Some (kx GHC.Num.+ lowestBitSet maskGE) else\n                     unsafeFindMin def\n                 | def, Nil => unsafeFindMin def\n                 end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go Nil l\n             else go l r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition singleton : Key -> IntSet :=\n  fun x => Tip (prefixOf x) (bitmapOf x).\n\nDefinition insert : Key -> IntSet -> IntSet :=\n  fun x => insertBM (prefixOf x) (bitmapOf x).\n\nDefinition delete : Key -> IntSet -> IntSet :=\n  fun x => deleteBM (prefixOf x) (bitmapOf x).\n\nProgram Fixpoint intersection (arg_0__ arg_1__ : IntSet) {measure (size_nat\n                               arg_0__ +\n                               size_nat arg_1__)} : IntSet\n                   := match arg_0__, arg_1__ with\n                      | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n                          let intersection2 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then Nil else\n                            if Bool.Sumbool.sumbool_of_bool (zero p1 m2) then intersection t1 l2 else\n                            intersection t1 r2 in\n                          let intersection1 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then Nil else\n                            if Bool.Sumbool.sumbool_of_bool (zero p2 m1) then intersection l1 t2 else\n                            intersection r1 t2 in\n                          if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then intersection1 else\n                          if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then intersection2 else\n                          if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n                          then bin p1 m1 (intersection l1 l2) (intersection r1 r2) else\n                          Nil\n                      | (Bin _ _ _ _ as t1), Tip kx2 bm2 =>\n                          let fix intersectBM arg_11__\n                                    := match arg_11__ with\n                                       | Bin p1 m1 l1 r1 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx2 p1 m1) then Nil else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx2 m1) then intersectBM l1 else\n                                           intersectBM r1\n                                       | Tip kx1 bm1 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                                           then tip kx1 (bm1 Data.Bits..&.(**) bm2) else\n                                           Nil\n                                       | Nil => Nil\n                                       end in\n                          intersectBM t1\n                      | Bin _ _ _ _, Nil => Nil\n                      | Tip kx1 bm1, t2 =>\n                          let fix intersectBM arg_18__\n                                    := match arg_18__ with\n                                       | Bin p2 m2 l2 r2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx1 p2 m2) then Nil else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx1 m2) then intersectBM l2 else\n                                           intersectBM r2\n                                       | Tip kx2 bm2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                                           then tip kx1 (bm1 Data.Bits..&.(**) bm2) else\n                                           Nil\n                                       | Nil => Nil\n                                       end in\n                          intersectBM t2\n                      | Nil, _ => Nil\n                      end.\nSolve Obligations with (termination_by_omega).\n\nFixpoint subsetCmp (arg_0__ arg_1__ : IntSet) : comparison\n           := match arg_0__, arg_1__ with\n              | (Bin p1 m1 l1 r1 as t1), Bin p2 m2 l2 r2 =>\n                  let subsetCmpEq :=\n                    match pair (subsetCmp l1 l2) (subsetCmp r1 r2) with\n                    | pair Gt _ => Gt\n                    | pair _ Gt => Gt\n                    | pair Eq Eq => Eq\n                    | _ => Lt\n                    end in\n                  let subsetCmpLt :=\n                    if nomatch p1 p2 m2 : bool then Gt else\n                    if zero p1 m2 : bool then subsetCmp t1 l2 else\n                    subsetCmp t1 r2 in\n                  if shorter m1 m2 : bool then Gt else\n                  if shorter m2 m1 : bool\n                  then match subsetCmpLt with\n                       | Gt => Gt\n                       | _ => Lt\n                       end else\n                  if p1 GHC.Base.== p2 : bool then subsetCmpEq else\n                  Gt\n              | _, _ =>\n                  match arg_0__, arg_1__ with\n                  | Bin _ _ _ _, _ => Gt\n                  | Tip kx1 bm1, Tip kx2 bm2 =>\n                      if kx1 GHC.Base./= kx2 : bool then Gt else\n                      if bm1 GHC.Base.== bm2 : bool then Eq else\n                      if (bm1 Data.Bits..&.(**) Data.Bits.complement bm2) GHC.Base.== #0 : bool\n                      then Lt else\n                      Gt\n                  | (Tip kx _ as t1), Bin p m l r =>\n                      if nomatch kx p m : bool then Gt else\n                      if zero kx m : bool then match subsetCmp t1 l with | Gt => Gt | _ => Lt end else\n                      match subsetCmp t1 r with\n                      | Gt => Gt\n                      | _ => Lt\n                      end\n                  | Tip _ _, Nil => Gt\n                  | Nil, Nil => Eq\n                  | Nil, _ => Lt\n                  end\n              end.\n\nDefinition isProperSubsetOf : IntSet -> IntSet -> bool :=\n  fun t1 t2 => match subsetCmp t1 t2 with | Lt => true | _ => false end.\n\nDefinition match_ : IntWord.Int -> Prefix -> Mask -> bool :=\n  fun i p m => (mask i m) GHC.Base.== p.\n\nFixpoint isSubsetOf (arg_0__ arg_1__ : IntSet) : bool\n           := match arg_0__, arg_1__ with\n              | (Bin p1 m1 l1 r1 as t1), Bin p2 m2 l2 r2 =>\n                  if shorter m1 m2 : bool then false else\n                  if shorter m2 m1 : bool\n                  then andb (match_ p1 p2 m2) (if zero p1 m2 : bool\n                             then isSubsetOf t1 l2\n                             else isSubsetOf t1 r2) else\n                  andb (p1 GHC.Base.== p2) (andb (isSubsetOf l1 l2) (isSubsetOf r1 r2))\n              | _, _ =>\n                  match arg_0__, arg_1__ with\n                  | Bin _ _ _ _, _ => false\n                  | Tip kx1 bm1, Tip kx2 bm2 =>\n                      andb (kx1 GHC.Base.== kx2) ((bm1 Data.Bits..&.(**) Data.Bits.complement bm2)\n                            GHC.Base.==\n                            #0)\n                  | (Tip kx _ as t1), Bin p m l r =>\n                      if nomatch kx p m : bool then false else\n                      if zero kx m : bool then isSubsetOf t1 l else\n                      isSubsetOf t1 r\n                  | Tip _ _, Nil => false\n                  | Nil, _ => true\n                  end\n              end.\n\nProgram Fixpoint disjoint (arg_0__ arg_1__ : IntSet) {measure (size_nat arg_0__\n                           +\n                           size_nat arg_1__)} : bool\n                   := match arg_0__, arg_1__ with\n                      | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n                          let disjoint2 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then true else\n                            if Bool.Sumbool.sumbool_of_bool (zero p1 m2) then disjoint t1 l2 else\n                            disjoint t1 r2 in\n                          let disjoint1 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then true else\n                            if Bool.Sumbool.sumbool_of_bool (zero p2 m1) then disjoint l1 t2 else\n                            disjoint r1 t2 in\n                          if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then disjoint1 else\n                          if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then disjoint2 else\n                          if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n                          then andb (disjoint l1 l2) (disjoint r1 r2) else\n                          true\n                      | (Bin _ _ _ _ as t1), Tip kx2 bm2 =>\n                          let fix disjointBM arg_11__\n                                    := match arg_11__ with\n                                       | Bin p1 m1 l1 r1 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx2 p1 m1) then true else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx2 m1) then disjointBM l1 else\n                                           disjointBM r1\n                                       | Tip kx1 bm1 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                                           then (bm1 Data.Bits..&.(**) bm2) GHC.Base.== #0 else\n                                           true\n                                       | Nil => true\n                                       end in\n                          disjointBM t1\n                      | Bin _ _ _ _, Nil => true\n                      | Tip kx1 bm1, t2 =>\n                          let fix disjointBM arg_18__\n                                    := match arg_18__ with\n                                       | Bin p2 m2 l2 r2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx1 p2 m2) then true else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx1 m2) then disjointBM l2 else\n                                           disjointBM r2\n                                       | Tip kx2 bm2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                                           then (bm1 Data.Bits..&.(**) bm2) GHC.Base.== #0 else\n                                           true\n                                       | Nil => true\n                                       end in\n                          disjointBM t2\n                      | Nil, _ => true\n                      end.\nSolve Obligations with (termination_by_omega).\n\nProgram Definition foldl'Bits {a}\n           : IntWord.Int -> (a -> IntWord.Int -> a) -> a -> Nat -> a :=\n          fun prefix f z bitmap =>\n            let go :=\n              GHC.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                               IntWord.wordTonat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                               match arg_0__, arg_1__ with\n                               | num_2__, acc =>\n                                   if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                                   match arg_0__, arg_1__ with\n                                   | bm, acc =>\n                                       let bitmask := lowestBitMask bm in\n                                       let bi := indexOfTheOnlyBit bitmask in\n                                       go (Data.Bits.xor bm bitmask) (f acc (prefix GHC.Num.+ bi))\n                                   end\n                               end) in\n            go bitmap z.\nAdmit Obligations.\n\nFixpoint filter (predicate : (Key -> bool)) (t : IntSet) : IntSet\n           := let bitPred :=\n                fun kx bm bi =>\n                  if predicate (kx GHC.Num.+ bi) : bool\n                  then bm Data.Bits..|.(**) bitmapOfSuffix bi else\n                  bm in\n              match t with\n              | Bin p m l r => bin p m (filter predicate l) (filter predicate r)\n              | Tip kx bm => tip kx (foldl'Bits #0 (bitPred kx) #0 bm)\n              | Nil => Nil\n              end.\n\nDefinition partition : (Key -> bool) -> IntSet -> (IntSet * IntSet)%type :=\n  fun predicate0 t0 =>\n    let fix go predicate t\n              := let bitPred :=\n                   fun kx bm bi =>\n                     if predicate (kx GHC.Num.+ bi) : bool\n                     then bm Data.Bits..|.(**) bitmapOfSuffix bi else\n                     bm in\n                 match t with\n                 | Bin p m l r =>\n                     let 'pair r1 r2 := go predicate r in\n                     let 'pair l1 l2 := go predicate l in\n                     pair (bin p m l1 r1) (bin p m l2 r2)\n                 | Tip kx bm =>\n                     let bm1 := foldl'Bits #0 (bitPred kx) #0 bm in\n                     pair (tip kx bm1) (tip kx (Data.Bits.xor bm bm1))\n                 | Nil => (pair Nil Nil)\n                 end in\n    id (go predicate0 t0).\n\nDefinition split : Key -> IntSet -> (IntSet * IntSet)%type :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | x', (Bin p m l r as t') =>\n                     if match_ x' p m : bool\n                     then if zero x' m : bool\n                          then let 'pair lt gt := go x' l in\n                               pair lt (union gt r)\n                          else let 'pair lt gt := go x' r in\n                               pair (union lt l) gt else\n                     if x' GHC.Base.< p : bool\n                     then (pair Nil t')\n                     else (pair t' Nil)\n                 | x', (Tip kx' bm as t') =>\n                     let lowerBitmap := bitmapOf x' GHC.Num.- #1 in\n                     let higherBitmap := Data.Bits.complement (lowerBitmap GHC.Num.+ bitmapOf x') in\n                     if kx' GHC.Base.> x' : bool then (pair Nil t') else\n                     if kx' GHC.Base.< prefixOf x' : bool then (pair t' Nil) else\n                     pair (tip kx' (bm Data.Bits..&.(**) lowerBitmap)) (tip kx' (bm Data.Bits..&.(**)\n                                                                                 higherBitmap))\n                 | _, Nil => (pair Nil Nil)\n                 end in\n    let j_21__ := let 'pair lt gt := go x t in pair lt gt in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then let 'pair lt gt := go x l in\n                  let lt' := union lt r in pair lt' gt\n             else let 'pair lt gt := go x r in\n                  let gt' := union gt l in pair lt gt' else\n        j_21__\n    | _ => j_21__\n    end.\n\nDefinition splitMember : Key -> IntSet -> (IntSet * bool * IntSet)%type :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | x', (Bin p m l r as t') =>\n                     if match_ x' p m : bool\n                     then if zero x' m : bool\n                          then let 'pair (pair lt fnd) gt := go x' l in\n                               pair (pair lt fnd) (union gt r)\n                          else let 'pair (pair lt fnd) gt := go x' r in\n                               pair (pair (union lt l) fnd) gt else\n                     if x' GHC.Base.< p : bool\n                     then pair (pair Nil false) t'\n                     else pair (pair t' false) Nil\n                 | x', (Tip kx' bm as t') =>\n                     let bitmapOfx' := bitmapOf x' in\n                     let lowerBitmap := bitmapOfx' GHC.Num.- #1 in\n                     let higherBitmap := Data.Bits.complement (lowerBitmap GHC.Num.+ bitmapOfx') in\n                     if kx' GHC.Base.> x' : bool then pair (pair Nil false) t' else\n                     if kx' GHC.Base.< prefixOf x' : bool then pair (pair t' false) Nil else\n                     let gt := tip kx' (bm Data.Bits..&.(**) higherBitmap) in\n                     let found := (bm Data.Bits..&.(**) bitmapOfx') GHC.Base./= #0 in\n                     let lt := tip kx' (bm Data.Bits..&.(**) lowerBitmap) in pair (pair lt found) gt\n                 | _, Nil => pair (pair Nil false) Nil\n                 end in\n    let j_22__ := go x t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then let 'pair (pair lt fnd) gt := go x l in\n                  let lt' := union lt r in pair (pair lt' fnd) gt\n             else let 'pair (pair lt fnd) gt := go x r in\n                  let gt' := union gt l in pair (pair lt fnd) gt' else\n        j_22__\n    | _ => j_22__\n    end.\n\nDefinition maxView : IntSet -> option (Key * IntSet)%type :=\n  fun t =>\n    let fix go arg_0__\n              := match arg_0__ with\n                 | Bin p m l r => let 'pair result r' := go r in pair result (bin p m l r')\n                 | Tip kx bm =>\n                     let 'bi := highestBitSet bm in\n                     pair (kx GHC.Num.+ bi) (tip kx (bm Data.Bits..&.(**)\n                                                     Data.Bits.complement (bitmapOfSuffix bi)))\n                 | Nil => GHC.Err.error (GHC.Base.hs_string__ \"maxView Nil\")\n                 end in\n    let j_12__ := Some (go t) in\n    match t with\n    | Nil => None\n    | Bin p m l r =>\n        if m GHC.Base.< #0 : bool\n        then let 'pair result l' := go l in\n             Some (pair result (bin p m l' r)) else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition minView : IntSet -> option (Key * IntSet)%type :=\n  fun t =>\n    let fix go arg_0__\n              := match arg_0__ with\n                 | Bin p m l r => let 'pair result l' := go l in pair result (bin p m l' r)\n                 | Tip kx bm =>\n                     let 'bi := lowestBitSet bm in\n                     pair (kx GHC.Num.+ bi) (tip kx (bm Data.Bits..&.(**)\n                                                     Data.Bits.complement (bitmapOfSuffix bi)))\n                 | Nil => GHC.Err.error (GHC.Base.hs_string__ \"minView Nil\")\n                 end in\n    let j_12__ := Some (go t) in\n    match t with\n    | Nil => None\n    | Bin p m l r =>\n        if m GHC.Base.< #0 : bool\n        then let 'pair result r' := go r in\n             Some (pair result (bin p m l r')) else\n        j_12__\n    | _ => j_12__\n    end.\n\n(* Skipping definition `Data.IntSet.InternalWord.deleteFindMin' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.deleteFindMax' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.findMin' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.findMax' *)\n\nDefinition deleteMin : IntSet -> IntSet :=\n  Data.Maybe.maybe Nil Data.Tuple.snd GHC.Base.∘ minView.\n\nDefinition deleteMax : IntSet -> IntSet :=\n  Data.Maybe.maybe Nil Data.Tuple.snd GHC.Base.∘ maxView.\n\nDefinition fromList : list Key -> IntSet :=\n  fun xs => let ins := fun t x => insert x t in Data.Foldable.foldl' ins empty xs.\n\nDefinition toList : IntSet -> list Key :=\n  toAscList.\n\nDefinition map : (Key -> Key) -> IntSet -> IntSet :=\n  fun f => fromList GHC.Base.∘ (GHC.Base.map f GHC.Base.∘ toList).\n\nDefinition fold {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  foldr.\n\nProgram Definition foldr'Bits {a}\n           : IntWord.Int -> (IntWord.Int -> a -> a) -> a -> Nat -> a :=\n          fun prefix f z bitmap =>\n            let go :=\n              GHC.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                               IntWord.wordTonat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                               match arg_0__, arg_1__ with\n                               | num_2__, acc =>\n                                   if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                                   match arg_0__, arg_1__ with\n                                   | bm, acc =>\n                                       let bitmask := lowestBitMask bm in\n                                       let bi := indexOfTheOnlyBit bitmask in\n                                       go (Data.Bits.xor bm bitmask) ((f ((prefix GHC.Num.+ (#64 GHC.Num.- #1))\n                                                                          GHC.Num.-\n                                                                          bi)) acc)\n                                   end\n                               end) in\n            go (revNat bitmap) z.\nAdmit Obligations.\n\nDefinition foldr' {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | z', Nil => z'\n                 | z', Tip kx bm => foldr'Bits kx f z' bm\n                 | z', Bin _ _ l r => go (go z' r) l\n                 end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z l) r else go (go z r) l\n      | _ => go z t\n      end.\n\nProgram Definition foldlBits {a}\n           : IntWord.Int -> (a -> IntWord.Int -> a) -> a -> Nat -> a :=\n          fun prefix f z bitmap =>\n            let go :=\n              GHC.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                               IntWord.wordTonat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                               match arg_0__, arg_1__ with\n                               | num_2__, acc =>\n                                   if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                                   match arg_0__, arg_1__ with\n                                   | bm, acc =>\n                                       let bitmask := lowestBitMask bm in\n                                       let bi := indexOfTheOnlyBit bitmask in\n                                       go (Data.Bits.xor bm bitmask) (f acc (prefix GHC.Num.+ bi))\n                                   end\n                               end) in\n            go bitmap z.\nAdmit Obligations.\n\nDefinition foldl {a} : (a -> Key -> a) -> a -> IntSet -> a :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | z', Nil => z'\n                 | z', Tip kx bm => foldlBits kx f z' bm\n                 | z', Bin _ _ l r => go (go z' l) r\n                 end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z r) l else go (go z l) r\n      | _ => go z t\n      end.\n\nDefinition foldl' {a} : (a -> Key -> a) -> a -> IntSet -> a :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | z', Nil => z'\n                 | z', Tip kx bm => foldl'Bits kx f z' bm\n                 | z', Bin _ _ l r => go (go z' l) r\n                 end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z r) l else go (go z l) r\n      | _ => go z t\n      end.\n\nDefinition elems : IntSet -> list Key :=\n  toAscList.\n\nDefinition toDescList : IntSet -> list Key :=\n  foldl (GHC.Base.flip cons) nil.\n\nDefinition foldrFB {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  foldr.\n\nDefinition foldlFB {a} : (a -> Key -> a) -> a -> IntSet -> a :=\n  foldl.\n\n(* Skipping definition `Data.IntSet.InternalWord.fromAscList' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.fromDistinctAscList' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.showTree' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.showTreeWith' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.showsTree' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.showsTreeHang' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.showBin' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.showWide' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.showsBars' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.showsBitMap' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.showBitMap' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.node' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.withBar' *)\n\n(* Skipping definition `Data.IntSet.InternalWord.withEmpty' *)\n\nDefinition splitRoot : IntSet -> list IntSet :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Nil => nil\n    | (Tip _ _ as x) => cons x nil\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool then cons r (cons l nil) else\n        cons l (cons r nil)\n    end.\n\nModule Notations.\nNotation \"'_Data.IntSet.InternalWord.\\\\_'\" := (op_zrzr__).\nInfix \"Data.IntSet.InternalWord.\\\\\" := (_\\\\_) (at level 99).\nEnd Notations.\n\n(* External variables:\n     Bool.Sumbool.sumbool_of_bool Eq Gt Lt None Some andb bool comparison cons false\n     id list negb nil op_zp__ op_zt__ option orb pair size_nat true Coq.Init.Peano.lt\n     Data.Bits.complement Data.Bits.op_zizazi__ Data.Bits.op_zizbzi__ Data.Bits.xor\n     Data.Foldable.Foldable Data.Foldable.foldl' Data.Maybe.maybe Data.Tuple.snd\n     GHC.Base.Eq_ GHC.Base.Monoid GHC.Base.Ord GHC.Base.Semigroup GHC.Base.compare\n     GHC.Base.compare__ GHC.Base.flip GHC.Base.map GHC.Base.mappend__ GHC.Base.max__\n     GHC.Base.mconcat__ GHC.Base.mempty__ GHC.Base.min__ GHC.Base.op_z2218U__\n     GHC.Base.op_zeze__ GHC.Base.op_zeze____ GHC.Base.op_zg__ GHC.Base.op_zg____\n     GHC.Base.op_zgze__ GHC.Base.op_zgze____ GHC.Base.op_zl__ GHC.Base.op_zl____\n     GHC.Base.op_zlze____ GHC.Base.op_zlzlzgzg__ GHC.Base.op_zlzlzgzg____\n     GHC.Base.op_zsze__ GHC.Base.op_zsze____ GHC.Err.Build_Default GHC.Err.Default\n     GHC.Err.error GHC.Num.fromInteger GHC.Num.negate GHC.Num.op_zm__ GHC.Num.op_zp__\n     GHC.Wf.wfFix2 IntWord.Int IntWord.Word IntWord.bitcount IntWord.highestBitMask\n     IntWord.indexOfTheOnlyBit IntWord.intFromWord IntWord.shiftLWord\n     IntWord.shiftRWord IntWord.wordFromInt IntWord.wordTonat\n*)\n", "meta": {"author": "antalsz", "repo": "hs-to-coq", "sha": "cd62a35fff22cb6022a8935581746df658264f0f", "save_path": "github-repos/coq/antalsz-hs-to-coq", "path": "github-repos/coq/antalsz-hs-to-coq/hs-to-coq-cd62a35fff22cb6022a8935581746df658264f0f/examples/containers/lib/Data/IntSet/InternalWord.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.23246069724157295}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import ssreflect ssrbool.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config Universes.\nFrom MetaCoq.PCUIC Require Import PCUICTyping PCUICAst PCUICAstUtils PCUICTactics\n     PCUICLiftSubst PCUICInductives PCUICGeneration PCUICSpine\n     PCUICGlobalEnv PCUICWeakeningEnvConv PCUICWeakeningEnvTyp\n     PCUICSubstitution PCUICUnivSubst PCUICUnivSubstitutionConv\n     PCUICUnivSubstitutionTyp PCUICClosedTyp\n     PCUICConversion PCUICCumulativity PCUICConfluence PCUICContexts\n     PCUICSR PCUICInversion PCUICValidity PCUICSafeLemmata PCUICContextConversion\n     PCUICContextConversionTyp PCUICEquality PCUICReduction PCUICOnFreeVars\n     PCUICWellScopedCumulativity\n     PCUICInductiveInversion.\n\nRequire Import Equations.Type.Relation Equations.Type.Relation_Properties.\nRequire Equations.Prop.DepElim.\nFrom Equations Require Import Equations.\nRequire Import ssreflect.\n\nImplicit Types (Σ : global_env_ext).\n\nSection no_prop_leq_type.\n\nContext `{cf : checker_flags}.\nVariable Hcf : prop_sub_type = false.\nVariable Hcf' : check_univs.\n\nLemma cumul_sort_confluence {Σ} {wfΣ : wf Σ} {Γ A u v} :\n  Σ ;;; Γ ⊢ A ≤ tSort u ->\n  Σ ;;; Γ ⊢ A ≤ tSort v ->\n  ∑ v', (Σ ;;; Γ ⊢ A = tSort v') *\n        (leq_universe (global_ext_constraints Σ) v' u /\\\n          leq_universe (global_ext_constraints Σ) v' v).\nProof using Type.\n  move=> H H'.\n  eapply ws_cumul_pb_Sort_r_inv in H as [u'u ?].\n  eapply ws_cumul_pb_Sort_r_inv in H' as [vu ?].\n  destruct p, p0.\n  destruct (closed_red_confluence c c1) as [x [r1 r2]].\n  eapply invert_red_sort in r1.\n  eapply invert_red_sort in r2. subst. noconf r2.\n  exists u'u. split; auto. now apply red_conv.\nQed.\n\nLemma cumul_ind_confluence {Σ : global_env_ext} {wfΣ : wf Σ} {Γ A ind u v l l'} :\n  Σ ;;; Γ ⊢ A ≤ mkApps (tInd ind u) l  ->\n  Σ ;;; Γ ⊢ A ≤ mkApps (tInd ind v) l' ->\n  ∑ v' l'',\n    [× Σ ;;; Γ ⊢ A ⇝ (mkApps (tInd ind v') l''),\n       ws_cumul_pb_terms Σ Γ l l'',\n       ws_cumul_pb_terms Σ Γ l' l'',\n       R_global_instance Σ (eq_universe Σ) (leq_universe Σ) (IndRef ind) #|l| v' u &\n       R_global_instance Σ (eq_universe Σ) (leq_universe Σ) (IndRef ind) #|l'| v' v].\nProof using Type.\n  move=> H H'.\n  eapply ws_cumul_pb_Ind_r_inv in H as [u'u [l'u [redl ru ?]]].\n  eapply ws_cumul_pb_Ind_r_inv in H' as [vu [l''u [redr ru' ?]]].\n  destruct (closed_red_confluence redl redr) as [nf [redl' redr']].\n  eapply invert_red_mkApps_tInd in redl'  as [args' [eqnf clΓ conv]].\n  eapply invert_red_mkApps_tInd in redr'  as [args'' [eqnf' _ conv']].\n  rewrite eqnf in eqnf'. solve_discr. subst nf.\n  all:auto. exists u'u, args'; split; auto.\n  - transitivity (mkApps (tInd ind u'u) l'u).\n    auto. eapply closed_red_mkApps => //.\n  - eapply red_terms_ws_cumul_pb_terms in conv.\n    transitivity l'u => //. now symmetry.\n  - eapply red_terms_ws_cumul_pb_terms in conv'.\n    transitivity l''u => //. now symmetry.\nQed.\n\nLemma ws_cumul_pb_LetIn_l_inv_alt {Σ Γ C na d ty b} {wfΣ : wf Σ.1} :\n  wf_local Σ (Γ ,, vdef na d ty) ->\n  Σ ;;; Γ ⊢ tLetIn na d ty b = C ->\n  Σ ;;; Γ,, vdef na d ty ⊢ b = lift0 1 C.\nProof using Type.\n  intros wf Hlet.\n  epose proof (red_expand_let wf).\n  etransitivity. eapply red_conv, X.\n  eapply ws_cumul_pb_is_open_term_left in Hlet.\n  { rewrite on_fvs_letin in Hlet. now move/and3P: Hlet => []. }\n  eapply (@weakening_ws_cumul_pb _ _ _ _ Γ [] [vdef _ _ _]); auto.\n  now eapply ws_cumul_pb_LetIn_l_inv in Hlet.\n  now eapply wf_local_closed_context.\nQed.\n\nLemma is_prop_bottom {Σ Γ T s s'} :\n  wf_ext Σ ->\n  Σ ;;; Γ ⊢ T ≤ tSort s ->\n  Σ ;;; Γ ⊢ T ≤ tSort s' ->\n  Universe.is_prop s -> Universe.is_prop s'.\nProof using Hcf Hcf'.\n  intros wfΣ hs hs'.\n  destruct (cumul_sort_confluence hs hs') as [x' [conv [leq leq']]].\n  intros isp.\n  eapply leq_universe_prop_r in leq; eauto.\n  unshelve eapply (leq_universe_prop_no_prop_sub_type _ _ _ _ _ _ leq'); eauto.\nQed.\n\nLemma is_sprop_bottom {Σ Γ T s s'} :\n  wf_ext Σ ->\n  Σ ;;; Γ ⊢ T ≤ tSort s ->\n  Σ ;;; Γ ⊢ T ≤ tSort s' ->\n  Universe.is_sprop s -> Universe.is_sprop s'.\nProof using Hcf'.\n  intros wfΣ hs hs'.\n  destruct (cumul_sort_confluence hs hs') as [x' [conv [leq leq']]].\n  intros isp.\n  eapply leq_universe_sprop_r in leq; eauto.\n  unshelve eapply (leq_universe_sprop_l _ _ _ _ _ leq'); eauto.\nQed.\n\nLemma prop_sort_eq {Σ Γ u u'} : Universe.is_prop u -> Universe.is_prop u' ->\n  is_closed_context Γ ->\n  Σ ;;; Γ ⊢ tSort u = tSort u'.\nProof using Type.\n  destruct u, u';\n  move=> //_ //_.\n  constructor => //. constructor.\n  red. red. constructor.\nQed.\n\nLemma sprop_sort_eq {Σ Γ u u'} : Universe.is_sprop u -> Universe.is_sprop u' ->\n  is_closed_context Γ ->\n  Σ ;;; Γ ⊢ tSort u = tSort u'.\nProof using Type.\n  destruct u, u';\n  move=> //_ //_.\n  constructor => //. constructor.\n  do 2 red. constructor.\nQed.\n\nLemma conv_sort_inv {Σ : global_env_ext} {wfΣ : wf Σ} Γ s s' :\n  Σ ;;; Γ ⊢ tSort s = tSort s' ->\n  eq_universe (global_ext_constraints Σ) s s'.\nProof using Type.\n  intros H.\n  eapply ws_cumul_pb_alt_closed in H as [v [v' [redv redv' eqvv']]].\n  eapply invert_red_sort in redv.\n  eapply invert_red_sort in redv'. subst.\n  now depelim eqvv'.\nQed.\n\nLemma is_prop_superE {Σ l} : wf_ext Σ -> Universe.is_prop (Universe.super l) -> False.\nProof using Hcf'.\n  intros wfΣ.\n  eapply is_prop_gt; eauto.\n  eapply leq_universe_refl.\nQed.\n\nLemma is_sprop_superE {Σ l} : wf_ext Σ -> Universe.is_sprop (Universe.super l) -> False.\nProof using Type.\n  intros wfΣ. destruct l => //.\nQed.\n\nLemma is_prop_prod {s s'} : Universe.is_prop s' -> Universe.is_prop (Universe.sort_of_product s s').\nProof using Type.\n  intros isp.\n  unfold Universe.sort_of_product. rewrite isp. auto.\nQed.\n\nLemma is_sprop_prod {s s'} : Universe.is_sprop s' -> Universe.is_sprop (Universe.sort_of_product s s').\nProof using Type.\n  intros isp.\n  unfold Universe.sort_of_product. rewrite isp orb_true_r. auto.\nQed.\n\nDefinition eq_univ_prop (u v : Universe.t) :=\n  (Universe.is_prop u <-> Universe.is_prop v) /\\\n  (Universe.is_sprop u <-> Universe.is_sprop v).\n\nDefinition eq_term_prop (Σ : global_env) napp :=\n  PCUICEquality.eq_term_upto_univ_napp Σ eq_univ_prop eq_univ_prop napp.\n\nReserved Notation \" Σ ;;; Γ |- t ~~ u \" (at level 50, Γ, t, u at next level).\n\nInductive cumul_prop `{checker_flags} (Σ : global_env_ext) (Γ : context) : term -> term -> Type :=\n  | cumul_refl t u :\n    is_closed_context Γ ->\n    is_open_term Γ t ->\n    is_open_term Γ u ->\n    eq_term_prop Σ.1 0 t u -> Σ ;;; Γ |- t ~~ u\n  | cumul_red_l t u v :\n    is_closed_context Γ ->\n    is_open_term Γ t ->\n    is_open_term Γ u ->\n    is_open_term Γ v ->\n    red1 Σ.1 Γ t v -> Σ ;;; Γ |- v ~~ u -> Σ ;;; Γ |- t ~~ u\n  | cumul_red_r t u v :\n    is_closed_context Γ ->\n    is_open_term Γ t ->\n    is_open_term Γ u ->\n    is_open_term Γ v ->\n    Σ ;;; Γ |- t ~~ v -> red1 Σ.1 Γ u v -> Σ ;;; Γ |- t ~~ u\n\nwhere \" Σ ;;; Γ |- t ~~ u \" := (cumul_prop Σ Γ t u) : type_scope.\n\nLemma eq_term_prop_impl Σ Re Rle t u :\n  wf_ext Σ ->\n  forall n,\n  PCUICEquality.eq_term_upto_univ_napp Σ.1 Re Rle n t u ->\n  subrelation Re eq_univ_prop ->\n  subrelation Rle eq_univ_prop ->\n  eq_term_prop Σ n t u.\nProof using Type.\n  intros wfΣ n eq.\n  intros.\n  eapply PCUICEquality.eq_term_upto_univ_impl in eq. eauto.\n  all:auto.\nQed.\n\nLemma leq_universe_prop_spec Σ u1 u2 :\n  check_univs ->\n  wf_ext Σ ->\n  leq_universe Σ u1 u2 ->\n  match u1, u2 with\n  | Universe.lProp, Universe.lProp => True\n  | Universe.lSProp, Universe.lSProp => True\n  | Universe.lProp, Universe.lSProp => False\n  | Universe.lSProp, Universe.lProp => False\n  | Universe.lProp, Universe.lType _ => prop_sub_type\n  | Universe.lSProp, Universe.lType _ => False\n  | Universe.lType l, Universe.lType l' => True\n  | Universe.lType _, _ => False\n  end.\nProof using Type.\n  intros cu wf leq.\n  apply wf_ext_consistent in wf.\n  apply (leq_universe_props _ _ _ cu wf leq).\nQed.\n\nLemma subrelation_eq_universe_eq_prop Σ :\n  wf_ext Σ ->\n  subrelation (eq_universe Σ) eq_univ_prop.\nProof using Hcf Hcf'.\n  intros wfΣ x y eq'. red.\n  split; intros.\n  eapply eq_universe_leq_universe in eq'.\n  eapply leq_universe_prop_spec in eq'; auto.\n  destruct x, y; simpl in *; auto; cong.\n  eapply eq_universe_leq_universe in eq'.\n  eapply leq_universe_prop_spec in eq'; auto.\n  destruct x, y; simpl in *; auto; cong.\nQed.\n\nLemma subrelation_leq_universe_eq_prop Σ :\n  wf_ext Σ ->\n  subrelation (leq_universe Σ) eq_univ_prop.\nProof using Hcf Hcf'.\n  intros wfΣ x y eq'. red.\n  split; intros;\n  eapply leq_universe_prop_spec in eq'; auto;\n  destruct x, y; simpl in *; auto; cong.\nQed.\n\nLemma eq_term_eq_term_prop_impl Σ t u :\n  wf_ext Σ ->\n  forall n,\n  PCUICEquality.eq_term_upto_univ_napp Σ.1 (eq_universe Σ) (eq_universe Σ) n t u ->\n  eq_term_prop Σ n t u.\nProof using Hcf Hcf'.\n  intros wfΣ n eq. eapply eq_term_prop_impl; eauto.\n  now apply subrelation_eq_universe_eq_prop.\n  now apply subrelation_eq_universe_eq_prop.\nQed.\n\nLemma leq_term_eq_term_prop_impl Σ t u :\n  wf_ext Σ ->\n  forall n,\n  PCUICEquality.eq_term_upto_univ_napp Σ.1 (eq_universe Σ) (leq_universe Σ) n t u ->\n  eq_term_prop Σ n t u.\nProof using Hcf Hcf'.\n  intros wfΣ n eq. eapply eq_term_prop_impl; eauto.\n  now apply subrelation_eq_universe_eq_prop.\n  now apply subrelation_leq_universe_eq_prop.\nQed.\n\nLemma cumul_cumul_prop Σ Γ A B :\n  wf_ext Σ ->\n  Σ ;;; Γ ⊢ A ≤ B ->\n  Σ ;;; Γ |- A ~~ B.\nProof using Hcf Hcf'.\n  intros wfΣ. induction 1.\n  - constructor => //. now apply leq_term_eq_term_prop_impl in c.\n  - econstructor 2; eauto.\n  - econstructor 3; eauto.\nQed.\n\nLemma conv_cumul_prop Σ Γ A B :\n  wf_ext Σ ->\n  Σ ;;; Γ ⊢ A = B ->\n  Σ ;;; Γ |- A ~~ B.\nProof using Hcf Hcf'.\n  intros wfΣ. induction 1.\n  - constructor => //. now apply eq_term_eq_term_prop_impl in c.\n  - econstructor 2; eauto.\n  - econstructor 3; eauto.\nQed.\n\nLemma cumul_prop_alt {Σ : global_env_ext} {Γ T U} {wfΣ : wf Σ} :\n  Σ ;;; Γ |- T ~~ U <~>\n  ∑ nf nf', [× Σ ;;; Γ ⊢ T ⇝ nf, Σ ;;; Γ ⊢ U ⇝ nf' & eq_term_prop Σ 0 nf nf'].\nProof using Type.\n  split.\n  - induction 1.\n    exists t, u. intuition pcuic.\n    destruct IHX as [nf [nf' [redl redr eq]]].\n    exists nf, nf'; split; pcuic.\n    eapply into_closed_red; eauto.\n    transitivity v; auto. apply redl.\n    destruct IHX as [nf [nf' [redl redr eq]]].\n    exists nf, nf'; split; pcuic.\n    transitivity v; auto.\n    apply into_closed_red; auto.\n  - intros [nf [nf' [redv redv' eq]]].\n    assert (clnf := closed_red_open_right redv).\n    assert (clnf' := closed_red_open_right redv').\n    destruct redv as [clsrc clT redv]. destruct redv' as [clsrc' clU redv'].\n    apply clos_rt_rt1n in redv.\n    apply clos_rt_rt1n in redv'.\n    induction redv.\n    * induction redv'.\n    ** constructor; auto.\n    ** epose proof (red1_is_open_term _ _ r clsrc clU).\n       econstructor 3; eauto.\n    * epose proof (red1_is_open_term _ _ r clsrc clT).\n      econstructor 2; eauto.\nQed.\n\nLemma cumul_prop_props {Σ Γ u u'} {wfΣ : wf Σ}:\n  Universe.is_prop u ->\n  Σ ;;; Γ |- tSort u ~~ tSort u' ->\n  Universe.is_prop u'.\nProof using Type.\n  intros isp equiv.\n  eapply cumul_prop_alt in equiv as [nf [nf' [redl redr eq]]].\n  eapply invert_red_sort in redl. apply invert_red_sort in redr.\n  subst.\n  depelim eq. red in e. intuition auto.\nQed.\n\nLemma cumul_sprop_props {Σ Γ u u'} {wfΣ : wf Σ} :\n  Universe.is_sprop u ->\n  Σ ;;; Γ |- tSort u ~~ tSort u' ->\n  Universe.is_sprop u'.\nProof using Type.\n  intros isp equiv.\n  eapply cumul_prop_alt in equiv as [nf [nf' [redl redr eq]]].\n  eapply invert_red_sort in redl. apply invert_red_sort in redr.\n  subst.\n  depelim eq. red in e. intuition auto.\nQed.\n\nInstance refl_eq_univ_prop : RelationClasses.Reflexive eq_univ_prop.\nProof using Type.\n  intros x. red. intuition.\nQed.\n\nInstance sym_eq_univ_prop : RelationClasses.Symmetric eq_univ_prop.\nProof using Type.\n  intros x y; unfold eq_univ_prop; intuition.\nQed.\n\nInstance trans_eq_univ_prop : RelationClasses.Transitive eq_univ_prop.\nProof using Type.\n  intros x y; unfold eq_univ_prop; intuition.\nQed.\n\nLemma LevelExprSet_For_all (P : LevelExpr.t -> Prop) (u : LevelAlgExpr.t) :\n  LevelExprSet.For_all P u <->\n  Forall P (LevelExprSet.elements u).\nProof using Type.\n  rewrite NonEmptySetFacts.LevelExprSet_For_all_exprs.\n  pose proof (NonEmptySetFacts.to_nonempty_list_spec u).\n  destruct (NonEmptySetFacts.to_nonempty_list u). rewrite -H. simpl.\n  split. constructor; intuition.\n  intros H'; inv H'; intuition.\nQed.\n\nLemma univ_expr_set_in_elements e s :\n  LevelExprSet.In e s <-> In e (LevelExprSet.elements s).\nProof using Type.\n  rewrite -LevelExprSet.elements_spec1. generalize (LevelExprSet.elements s).\n  now eapply InA_In_eq.\nQed.\n\nLemma univ_epxrs_elements_map g s :\n  forall e, In e (LevelExprSet.elements (NonEmptySetFacts.map g s)) <->\n      In e (map g (LevelExprSet.elements s)).\nProof using Type.\n  intros e.\n  unfold NonEmptySetFacts.map.\n  pose proof (NonEmptySetFacts.to_nonempty_list_spec s).\n  destruct (NonEmptySetFacts.to_nonempty_list s) as [e' l] eqn:eq.\n  rewrite -univ_expr_set_in_elements NonEmptySetFacts.add_list_spec.\n  rewrite -H. simpl. rewrite LevelExprSet.singleton_spec.\n  intuition auto.\nQed.\n\nLemma Forall_elements_in P s : Forall P (LevelExprSet.elements s) <->\n  (forall x, LevelExprSet.In x s -> P x).\nProof using Type.\n  setoid_rewrite univ_expr_set_in_elements.\n  generalize (LevelExprSet.elements s).\n  intros.\n  split; intros.\n  induction H; depelim H0; subst => //; auto.\n  induction l; constructor; auto.\n  apply H. repeat constructor.\n  apply IHl. intros x inxl. apply H. right; auto.\nQed.\n\nLemma univ_exprs_map_all P g s :\n  Forall P (LevelExprSet.elements (NonEmptySetFacts.map g s)) <->\n  Forall (fun x => P (g x)) (LevelExprSet.elements s).\nProof using Type.\n  rewrite !Forall_elements_in.\n  setoid_rewrite NonEmptySetFacts.map_spec.\n  intuition auto.\n  eapply H. now exists x.\n  destruct H0 as [e' [ins ->]]. apply H; auto.\nQed.\n\nLemma expr_set_forall_map f g s :\n  LevelExprSet.for_all f (NonEmptySetFacts.map g s) <->\n  LevelExprSet.for_all (fun e => f (g e)) s.\nProof using Type.\n  rewrite /is_true !LevelExprSet.for_all_spec !LevelExprSet_For_all.\n  apply univ_exprs_map_all.\nQed.\n\nLemma univ_is_prop_make x : Universe.is_prop (Universe.make x) = false.\nProof using Type.\n  destruct x; simpl; auto.\nQed.\n\n(* Lemma is_prop_subst_level_expr u1 u2 s :\n  Forall2 (fun x y : Level.t => eq_univ_prop (Universe.make x) (Universe.make y)) u1 u2  ->\n  LevelExpr.is_prop (subst_instance_level_expr u1 s) = LevelExpr.is_prop (subst_instance_level_expr u2 s).\nProof.\n  intros hu. destruct s; simpl; auto.\n  destruct e as [[] ?]; simpl; auto.\n  destruct (nth_error u1 n) eqn:E.\n  eapply Forall2_nth_error_Some_l in hu; eauto.\n  destruct hu as [t' [-> eq]].\n  red in eq. rewrite !univ_is_prop_make in eq.\n  eapply eq_iff_eq_true in eq.\n  destruct t, t'; simpl in eq => //.\n  eapply Forall2_nth_error_None_l in hu; eauto.\n  now rewrite hu.\nQed. *)\n\nInstance substuniv_eq_univ_prop : SubstUnivPreserving eq_univ_prop.\nProof using Type.\n  intros s u1 u2 hu.\n  red in hu.\n  eapply Forall2_map_inv in hu.\n  rewrite /subst_instance_univ.\n  destruct s; red; simpl; auto; try intuition reflexivity.\nQed.\n\nLemma cumul_prop_sym Σ Γ T U :\n  wf Σ.1 ->\n  Σ ;;; Γ |- T ~~ U ->\n  Σ ;;; Γ |- U ~~ T.\nProof using Type.\n  intros wfΣ Hl.\n  eapply cumul_prop_alt in Hl as [t' [u' [tt' uu' eq]]].\n  eapply cumul_prop_alt.\n  exists u', t'; split; auto.\n  now symmetry.\nQed.\n\nLemma cumul_prop_trans Σ Γ T U V :\n  wf Σ ->\n  Σ ;;; Γ |- T ~~ U ->\n  Σ ;;; Γ |- U ~~ V ->\n  Σ ;;; Γ |- T ~~ V.\nProof using Type.\n  intros wfΣ Hl Hr.\n  eapply cumul_prop_alt in Hl as [t' [u' [tt' uu' eq]]].\n  eapply cumul_prop_alt in Hr as [u'' [v' [uu'' vv' eq']]].\n  eapply cumul_prop_alt.\n  destruct (closed_red_confluence uu' uu'') as [u'nf [ul ur]].\n  destruct ul as [? ? ul]. destruct ur as [? ? ur].\n  eapply red_eq_term_upto_univ_r in ul as [tnf [redtnf ?]]; tea; tc.\n  eapply red_eq_term_upto_univ_l in ur as [unf [redunf ?]]; tea; tc.\n  exists tnf, unf.\n  split; auto.\n  - transitivity t' => //. eapply into_closed_red; auto. fvs.\n  - transitivity v' => //. eapply into_closed_red; auto; fvs.\n  - now transitivity u'nf.\nQed.\n\nGlobal Instance cumul_prop_transitive Σ Γ : wf Σ -> CRelationClasses.Transitive (cumul_prop Σ Γ).\nProof using Type. intros. red. intros. now eapply cumul_prop_trans. Qed.\n\nLemma cumul_prop_cum_l {Σ Γ A T B} {wfΣ : wf_ext Σ} :\n  Σ ;;; Γ |- A ~~ T ->\n  Σ ;;; Γ ⊢ A ≤ B ->\n  Σ ;;; Γ |- B ~~ T.\nProof using Hcf Hcf'.\n  intros HT cum.\n  eapply cumul_cumul_prop in cum; auto.\n  eapply CRelationClasses.transitivity ; eauto.\n  eapply cumul_prop_sym; eauto.\nQed.\n\nLemma cumul_prop_cum_r {Σ Γ A T B} {wfΣ : wf_ext Σ} :\n  Σ ;;; Γ |- A ~~ T ->\n  Σ ;;; Γ ⊢ B ≤ A ->\n  Σ ;;; Γ |- B ~~ T.\nProof using Hcf Hcf'.\n  intros HT cum.\n  eapply cumul_cumul_prop in cum; auto.\n  eapply CRelationClasses.transitivity ; eauto.\nQed.\n\nLemma cumul_prop_conv_l {Σ Γ A T B} {wfΣ : wf_ext Σ} :\n  Σ ;;; Γ |- A ~~ T ->\n  Σ ;;; Γ ⊢ A = B ->\n  Σ ;;; Γ |- B ~~ T.\nProof using Hcf Hcf'.\n  intros HT cum.\n  eapply conv_cumul_prop in cum; auto.\n  eapply CRelationClasses.transitivity ; eauto.\n  eapply cumul_prop_sym; eauto.\nQed.\n\nLemma cumul_prop_conv_r {Σ Γ A T B} {wfΣ : wf_ext Σ} :\n  Σ ;;; Γ |- A ~~ T ->\n  Σ ;;; Γ ⊢ B = A ->\n  Σ ;;; Γ |- B ~~ T.\nProof using Hcf Hcf'.\n  intros HT cum.\n  eapply conv_cumul_prop in cum; auto.\n  eapply CRelationClasses.transitivity ; eauto.\nQed.\n\nDefinition conv_decls_prop (Σ : global_env_ext) (Γ Γ' : context) (c d : context_decl) :=\n  match decl_body c, decl_body d with\n  | None, None => True\n  | Some b, Some b' => b = b'\n  | _, _ => False\n  end.\n\nNotation conv_ctx_prop Σ := (All2_fold (conv_decls_prop Σ)).\n\nLemma conv_ctx_prop_refl Σ Γ :\n  conv_ctx_prop Σ Γ Γ.\nProof using Type.\n  induction Γ as [|[na [b|] ty]]; constructor; eauto => //.\nQed.\n\nLemma conv_ctx_prop_app Σ Γ Γ' Δ :\n  conv_ctx_prop Σ Γ Γ' ->\n  conv_ctx_prop Σ (Γ ,,, Δ) (Γ' ,,, Δ).\nProof using Type.\n  induction Δ; simpl; auto.\n  destruct a as [na  [b|] ty]; intros; constructor => //.\n  now eapply IHΔ.\n  now eapply IHΔ.\nQed.\n\nLemma red1_upto_conv_ctx_prop Σ Γ Γ' t t' :\n  red1 Σ.1 Γ t t' ->\n  conv_ctx_prop Σ Γ Γ' ->\n  red1 Σ.1 Γ' t t'.\nProof using Type.\n  intros Hred; induction Hred using red1_ind_all in Γ' |- *;\n    try solve [econstructor; eauto; try solve [solve_all]].\n  - econstructor. destruct (nth_error Γ i) eqn:eq; simpl in H => //.\n    noconf H; simpl in H; noconf H.\n    eapply All2_fold_nth in X; eauto.\n    destruct X as [d' [Hnth [ctxrel cp]]].\n    red in cp. rewrite H in cp. rewrite Hnth /=.\n    destruct (decl_body d'); subst => //.\n  - econstructor. eapply IHHred. constructor; simpl; auto => //.\n  - econstructor. eapply IHHred. constructor; simpl => //.\n  - intros h. constructor.\n    eapply IHHred. now apply conv_ctx_prop_app.\n  - intros h; constructor.\n    eapply OnOne2_impl; tea => /= br br'.\n    intros [red IH].\n    split=> //. now eapply red, conv_ctx_prop_app.\n  - intros. constructor; eapply IHHred; constructor; simpl; auto => //.\n  - intros. eapply fix_red_body. solve_all.\n    eapply b0. now eapply conv_ctx_prop_app.\n  - intros. eapply cofix_red_body. solve_all.\n    eapply b0. now eapply conv_ctx_prop_app.\nQed.\n\nLemma closed_red1_upto_conv_ctx_prop Σ Γ Γ' t t' :\n  is_closed_context Γ' ->\n  Σ ;;; Γ ⊢ t ⇝1 t' ->\n  conv_ctx_prop Σ Γ Γ' ->\n  Σ ;;; Γ' ⊢ t ⇝1 t'.\nProof using Type.\n  intros clΓ' [] conv.\n  eapply red1_upto_conv_ctx_prop in clrel_rel; eauto.\n  split; auto.\n  now rewrite -(All2_fold_length conv).\nQed.\n\nLemma red_upto_conv_ctx_prop Σ Γ Γ' t t' :\n  red Σ.1 Γ t t' ->\n  conv_ctx_prop Σ Γ Γ' ->\n  red Σ.1 Γ' t t'.\nProof using Type.\n  intros Hred. intros convctx.\n  induction Hred; eauto.\n  constructor. now eapply red1_upto_conv_ctx_prop.\n  eapply rt_trans; eauto.\nQed.\n\nLemma closed_red_upto_conv_ctx_prop Σ Γ Γ' t t' :\n  is_closed_context Γ' ->\n  Σ ;;; Γ ⊢ t ⇝ t' ->\n  conv_ctx_prop Σ Γ Γ' ->\n  Σ ;;; Γ' ⊢ t ⇝ t'.\nProof using Type.\n  intros clΓ' [] conv.\n  eapply red_upto_conv_ctx_prop in clrel_rel; eauto.\n  split; auto.\n  now rewrite -(All2_fold_length conv).\nQed.\n\nLemma cumul_prop_prod_inv {Σ Γ na A B na' A' B'} {wfΣ : wf Σ} :\n  Σ ;;; Γ |- tProd na A B ~~ tProd na' A' B' ->\n  Σ ;;; Γ ,, vass na A |- B ~~ B'.\nProof using Type.\n  intros H; eapply cumul_prop_alt in H as [nf [nf' [redv redv' eq]]].\n  eapply invert_red_prod in redv as (? & ? & [? ? ?]).\n  eapply invert_red_prod in redv' as (? & ? & [? ? ?]).\n  subst. all:auto.\n  eapply cumul_prop_alt.\n  exists x0, x2. split; auto.\n  eapply closed_red_upto_conv_ctx_prop; eauto. fvs.\n  constructor; auto => //. apply conv_ctx_prop_refl.\n  depelim eq. apply eq2.\nQed.\n\nLemma substitution_untyped_cumul_prop {Σ Γ Δ Γ' s M N} {wfΣ : wf Σ} :\n  forallb (is_open_term Γ) s ->\n  untyped_subslet Γ s Δ ->\n  Σ ;;; (Γ ,,, Δ ,,, Γ') |- M ~~ N ->\n  Σ ;;; (Γ ,,, subst_context s 0 Γ') |- (subst s #|Γ'| M) ~~ (subst s #|Γ'| N).\nProof using Type.\n  intros cls subs Hcum.\n  eapply cumul_prop_alt in Hcum as [nf [nf' [redl redr eq']]].\n  eapply closed_red_untyped_substitution in redl; eauto.\n  eapply closed_red_untyped_substitution in redr; eauto.\n  eapply cumul_prop_alt.\n  eexists _, _; split; eauto.\n  eapply PCUICEquality.eq_term_upto_univ_substs => //.\n  eapply All2_refl.\n  intros x. eapply PCUICEquality.eq_term_upto_univ_refl; typeclasses eauto.\nQed.\n\nLemma substitution_cumul_prop {Σ Γ Δ Γ' s M N} {wfΣ : wf Σ} :\n  subslet Σ Γ s Δ ->\n  Σ ;;; (Γ ,,, Δ ,,, Γ') |- M ~~ N ->\n  Σ ;;; (Γ ,,, subst_context s 0 Γ') |- (subst s #|Γ'| M) ~~ (subst s #|Γ'| N).\nProof using Type.\n  intros subs Hcum.\n  eapply substitution_untyped_cumul_prop; tea.\n  now eapply subslet_open in subs.\n  now eapply subslet_untyped_subslet.\nQed.\n\nLemma substitution_untyped_cumul_prop_equiv {Σ Γ Δ Γ' s s' M} {wfΣ : wf Σ} :\n  is_closed_context (Γ ,,, Δ ,,, Γ') ->\n  forallb (is_open_term Γ) s ->\n  forallb (is_open_term Γ) s' ->\n  is_open_term (Γ ,,, Δ ,,, Γ') M ->\n  #|s| = #|Δ| -> #|s'| = #|Δ| ->\n  All2 (eq_term_prop Σ.1 0) s s' ->\n  Σ ;;; (Γ ,,, subst_context s 0 Γ') |- (subst s #|Γ'| M) ~~ (subst s' #|Γ'| M).\nProof using Type.\n  intros clctx cls cls' clM lens_ lens' Heq.\n  constructor.\n  { eapply is_closed_subst_context; tea. }\n  { eapply is_open_term_subst; tea. }\n  { relativize #|Γ ,,, _|. eapply is_open_term_subst; tea. len. }\n  eapply PCUICEquality.eq_term_upto_univ_substs => //.\n  reflexivity.\nQed.\n\nLemma cumul_prop_args {Σ Γ args args'} {wfΣ : wf_ext Σ} :\n  All2 (cumul_prop Σ Γ) args args' ->\n  ∑ nf nf', [× All2 (closed_red Σ Γ) args nf, All2 (closed_red Σ Γ) args' nf' &\n    All2 (eq_term_prop Σ 0) nf nf'].\nProof using Type.\n  intros a.\n  induction a. exists [], []; intuition auto.\n  destruct IHa as (nfa & nfa' & [redl redr eq]).\n  eapply cumul_prop_alt in r as (nf & nf' & [redl' redr' eq'']).\n  exists (nf :: nfa), (nf' :: nfa'); intuition auto.\nQed.\n\nLemma is_closed_context_snoc_inv Γ d : is_closed_context (d :: Γ) ->\n  is_closed_context Γ /\\ closed_decl #|Γ| d.\nProof using Type.\n  rewrite on_free_vars_ctx_snoc.\n  move/andP => []; split; auto.\n  unfold ws_decl in b. destruct d as [na [bod|] ty]; cbn in *; auto.\n  move/andP: b => /= [] clb clt.\n  unfold closed_decl. cbn.\n  now rewrite !closedP_on_free_vars clb clt.\n  now rewrite closedP_on_free_vars.\nQed.\n\nLemma red_conv_prop {Σ Γ T U} {wfΣ : wf_ext Σ} :\n  Σ ;;; Γ ⊢ T ⇝ U ->\n  Σ ;;; Γ |- T ~~ U.\nProof using Hcf Hcf'.\n  move/(red_ws_cumul_pb (pb:=Conv)).\n  now apply conv_cumul_prop.\nQed.\n\nLemma substitution_red_terms_conv_prop {Σ Γ Δ Γ' s s' M} {wfΣ : wf_ext Σ} :\n  is_closed_context (Γ ,,, Δ ,,, Γ') ->\n  is_open_term (Γ ,,, Δ ,,, Γ') M ->\n  untyped_subslet Γ s Δ ->\n  red_terms Σ Γ s s' ->\n  Σ ;;; (Γ ,,, subst_context s 0 Γ') |- (subst s #|Γ'| M) ~~ (subst s' #|Γ'| M).\nProof using Hcf Hcf'.\n  intros.\n  apply red_conv_prop.\n  eapply closed_red_red_subst; tea.\nQed.\n\nLemma context_conversion_cumul_prop {Σ Γ Δ M N} {wfΣ : wf_ext Σ} :\n  Σ ;;; Γ |- M ~~ N ->\n  Σ ⊢ Γ = Δ ->\n  Σ ;;; Δ |- M ~~ N.\nProof using Hcf Hcf'.\n  induction 1; intros.\n  - constructor => //. eauto with fvs. now rewrite -(All2_fold_length X).\n    now rewrite -(All2_fold_length X).\n  - specialize (IHX X0). transitivity v => //.\n    eapply red1_red in r.\n    assert (Σ ;;; Γ ⊢ t ⇝ v) by (now apply into_closed_red).\n    symmetry in X0.\n    eapply conv_red_conv in X1. 2:exact X0.\n    3:{ eapply ws_cumul_pb_refl. fvs. now rewrite (All2_fold_length X0). }\n    2:{ eapply closed_red_refl. fvs. now rewrite (All2_fold_length X0). }\n    symmetry in X1. now eapply conv_cumul_prop.\n  - specialize (IHX X0). transitivity v => //.\n    eapply red1_red in r.\n    assert (Σ ;;; Γ ⊢ u ⇝ v) by (now apply into_closed_red).\n    symmetry in X0.\n    eapply conv_red_conv in X1. 2:exact X0.\n    3:{ eapply ws_cumul_pb_refl. fvs. now rewrite (All2_fold_length X0). }\n    2:{ eapply closed_red_refl. fvs. now rewrite (All2_fold_length X0). }\n    symmetry in X1. now eapply conv_cumul_prop.\nQed.\n\n(** Note: a more general version involving substitution in an extended context Γ ,,, Δ would be\n  harder as it requires a more involved proof about reduction being \"preserved\" when converting contexts using\n  cumul_prop rather than standard conversion.\n*)\nLemma substitution_untyped_cumul_prop_cumul {Σ Γ Δ Δ' s s' M} {wfΣ : wf_ext Σ} :\n  is_closed_context (Γ ,,, Δ) ->\n  is_closed_context (Γ ,,, Δ') ->\n  is_open_term (Γ ,,, Δ) M ->\n  untyped_subslet Γ s Δ ->\n  untyped_subslet Γ s' Δ' ->\n  All2 (cumul_prop Σ Γ) s s' ->\n  Σ ;;; Γ |- subst0 s M ~~ subst0 s' M.\nProof using Hcf Hcf'.\n  intros clctx clctx' clM subs subs' Heq.\n  assert (lens' := All2_length Heq).\n  destruct (cumul_prop_args Heq) as (nf & nf' & [redl redr eq]) => //.\n  transitivity (subst0 nf M).\n  * eapply (substitution_red_terms_conv_prop (Γ':=[])). 3:tea. all:tea.\n  * transitivity (subst0 nf' M).\n    constructor.\n    - rewrite on_free_vars_ctx_app in clctx. now move/andP: clctx.\n    - eapply (is_open_term_subst (Γ' := [])). apply clctx.\n      eapply closed_red_terms_open_right in redl. solve_all.\n      now rewrite -(All2_length redl) -(untyped_subslet_length subs). apply clM.\n    - eapply (is_open_term_subst (Γ' := [])). apply clctx.\n      eapply closed_red_terms_open_right in redr. solve_all.\n      now rewrite -(All2_length redr) -(untyped_subslet_length subs). apply clM.\n    - eapply PCUICEquality.eq_term_upto_univ_substs => //. reflexivity.\n    - eapply cumul_prop_sym; auto.\n      eapply (substitution_red_terms_conv_prop (Γ':=[])). 3:tea. all:tea.\n      len. len in clM. now rewrite -(untyped_subslet_length subs') -lens' (untyped_subslet_length subs).\nQed.\n\nLemma substitution1_untyped_cumul_prop {Σ Γ na t u M N} {wfΣ : wf Σ.1} :\n  is_open_term Γ u ->\n  Σ ;;; (Γ ,, vass na t) |- M ~~ N ->\n  Σ ;;; Γ |- M {0 := u} ~~ N {0 := u}.\nProof using Type.\n  intros clu Hcum.\n  eapply (substitution_untyped_cumul_prop (Δ := [_]) (Γ' := [])) in Hcum; cbn; eauto.\n  cbn; rewrite clu //.\n  repeat constructor.\nQed.\n\nLemma is_prop_subst_instance_level u l\n  : Universe.is_prop (Universe.make (subst_instance_level u l)) = Universe.is_prop (Universe.make l).\nProof using Type.\n  destruct l; simpl; auto.\nQed.\n\nLemma R_opt_variance_impl Re Rle v x y :\n  subrelation Re Rle ->\n  R_universe_instance Re x y ->\n  R_opt_variance Re Rle v x y.\nProof using Type.\n  intros sub.\n  destruct v; simpl; auto.\n  intros H. eapply Forall2_map_inv in H.\n  induction H in l |- *; simpl; auto.\n  destruct l. auto.\n  split. destruct t; simpl; auto.\n  eauto.\nQed.\n\nLemma cumul_prop_subst_instance_instance Σ univs u u' (i : Instance.t) :\n  wf Σ.1 ->\n  consistent_instance_ext Σ univs u ->\n  consistent_instance_ext Σ univs u' ->\n  R_universe_instance eq_univ_prop (subst_instance u i)\n    (subst_instance u' i).\nProof using Type.\n  intros wfΣ cu cu'. red.\n  eapply All2_Forall2, All2_map.\n  unfold subst_instance.\n  eapply All2_map. eapply All2_refl.\n  intros x. red.\n  rewrite !is_prop_subst_instance_level /=. split; reflexivity.\nQed.\n\nLemma cumul_prop_subst_instance {Σ Γ univs u u' T} {wfΣ : wf Σ} :\n  is_closed_context Γ ->\n  is_open_term Γ T ->\n  consistent_instance_ext Σ univs u ->\n  consistent_instance_ext Σ univs u' ->\n  Σ ;;; Γ |- subst_instance u T ~~ subst_instance u' T.\nProof using Type.\n  intros clΓ clT cu cu'.\n  eapply cumul_prop_alt.\n  enough (∑ nf nf' : term,\n    [× red Σ Γ T@[u] nf, red Σ Γ T@[u'] nf' & eq_term_prop Σ 0 nf nf']).\n  { destruct X as [nf [nf' [r r' e]]]. exists nf, nf'. split; try constructor; auto; fvs. }\n  eexists _, _; split; intuition auto. clear clΓ clT.\n  induction T using PCUICInduction.term_forall_list_ind; cbn; intros;\n    try solve [constructor; eauto; solve_all].\n  - cbn. constructor.\n    destruct s; split; reflexivity.\n  - constructor. eapply PCUICEquality.eq_term_upto_univ_impl in IHT1; eauto.\n    all:try typeclasses eauto.\n    apply IHT2.\n  - constructor. now eapply cumul_prop_subst_instance_instance.\n  - constructor. red. apply R_opt_variance_impl. intros x y; auto.\n    now eapply cumul_prop_subst_instance_instance.\n  - constructor. red. apply R_opt_variance_impl. intros x y; auto.\n    now eapply cumul_prop_subst_instance_instance.\n  - cbn. constructor. splits; simpl; solve_all.\n    eapply cumul_prop_subst_instance_instance; tea. reflexivity.\n    apply IHT.\n    eapply All2_map.\n    eapply All_All2; tea. cbn.\n    intuition auto. rewrite /id. reflexivity.\nQed.\n\nLemma R_eq_univ_prop_consistent_instances Σ univs u u' :\n  wf Σ.1 ->\n  consistent_instance_ext Σ univs u ->\n  consistent_instance_ext Σ univs u' ->\n  R_universe_instance eq_univ_prop u u'.\nProof using Type.\n  intros wfΣ cu cu'.\n  destruct univs; simpl in *.\n  - destruct u, u' => /= //. red.\n    simpl. constructor.\n  - intuition.\n    eapply Forall2_map.\n    eapply All2_Forall2.\n    solve_all.\n    eapply All2_impl.\n    eapply All_All_All2; eauto. lia.\n    simpl; intros.\n    intuition.\nQed.\n\nLemma untyped_subslet_inds Γ ind u u' mdecl :\n  untyped_subslet Γ (inds (inductive_mind ind) u (ind_bodies mdecl))\n    (subst_instance u' (arities_context (ind_bodies mdecl))).\nProof using Type.\n  generalize (le_n #|ind_bodies mdecl|).\n  generalize (ind_bodies mdecl) at 1 3 4.\n  unfold inds.\n  induction l using rev_ind; simpl; first constructor.\n  simpl. rewrite app_length /= => Hlen.\n  unfold arities_context.\n  simpl. rewrite /arities_context rev_map_spec /=.\n  rewrite map_app /= rev_app_distr /=.\n  rewrite /= Nat.add_1_r /=.\n  constructor.\n  rewrite -rev_map_spec. apply IHl. lia.\nQed.\n\nHint Resolve conv_ctx_prop_refl : core.\n\nLemma cumul_prop_tProd {Σ : global_env_ext} {Γ na t ty na' t' ty'} {wfΣ : wf_ext Σ} :\n  eq_binder_annot na na' ->\n  eq_term Σ.1 Σ t t' ->\n  Σ ;;; Γ ,, vass na t |- ty ~~ ty' ->\n  Σ ;;; Γ |- tProd na t ty ~~ tProd na' t' ty'.\nProof using Hcf Hcf'.\n  intros eqann eq cum.\n  eapply cumul_prop_alt in cum as (nf & nf' & [redl redr eq']).\n  eapply cumul_prop_alt. eexists (tProd na t nf), (tProd na' t' nf'); split; eauto.\n  - eapply closed_red_prod_codom; auto.\n  - eapply clrel_ctx in redl.\n    move: redl; rewrite on_free_vars_ctx_snoc /= => /andP[]; rewrite /on_free_vars_decl /test_decl /= => onΓ ont.\n    have clt' : is_open_term Γ t'.\n    eapply PCUICConfluence.eq_term_upto_univ_napp_on_free_vars in eq; tea.\n    eapply closed_red_prod; auto.\n    now eapply closed_red_refl.\n    eapply closed_red_upto_conv_ctx_prop; eauto.\n    now rewrite on_free_vars_ctx_snoc /= onΓ.\n    repeat (constructor; auto).\n  - repeat (constructor; auto).\n    eapply eq_term_eq_term_prop_impl; auto.\nQed.\n\nLemma cumul_prop_tLetIn (Σ : global_env_ext) {Γ na t d ty na' t' d' ty'} {wfΣ : wf_ext Σ} :\n  eq_binder_annot na na' ->\n  eq_term Σ.1 Σ t t' ->\n  eq_term Σ.1 Σ d d' ->\n  Σ ;;; Γ ,, vdef na d t |- ty ~~ ty' ->\n  Σ ;;; Γ |- tLetIn na d t ty ~~ tLetIn na' d' t' ty'.\nProof using Hcf Hcf'.\n  intros eqann eq eq' cum.\n  eapply cumul_prop_alt in cum as (nf & nf' & [redl redr eq'']).\n  eapply cumul_prop_alt.\n  assert(eq_context_upto Σ (eq_universe Σ) (eq_universe Σ) (Γ ,, vdef na d t) (Γ ,, vdef na' d' t')).\n  { repeat constructor; pcuic. eapply eq_context_upto_refl; typeclasses eauto. }\n  eapply (closed_red_eq_context_upto_l (pb:=Conv)) in redr; eauto.\n  2:{ eapply clrel_ctx in redl. rewrite !on_free_vars_ctx_snoc in redl |- *.\n      move/andP: redl => [] -> /= /andP[] cld clt.\n      eapply PCUICConfluence.eq_term_upto_univ_napp_on_free_vars in cld; tea.\n      eapply PCUICConfluence.eq_term_upto_univ_napp_on_free_vars in clt; tea.\n      rewrite /on_free_vars_decl /test_decl /=.\n      now rewrite cld clt. }\n  destruct redr as [v' [redv' eq''']].\n  eexists (tLetIn na d t nf), (tLetIn na' d' t' v'); split.\n  - now eapply closed_red_letin_body.\n  - now eapply closed_red_letin_body.\n  - constructor; eauto using eq_term_eq_term_prop_impl.\n    apply eq_term_eq_term_prop_impl; auto.\n    apply eq_term_eq_term_prop_impl; auto.\n    transitivity nf'. auto. now eapply eq_term_eq_term_prop_impl.\nQed.\n\nLemma cumul_prop_mkApps {Σ Γ f args f' args'} {wfΣ : wf_ext Σ} :\n  is_closed_context Γ ->\n  is_open_term Γ f ->\n  is_open_term Γ f' ->\n  eq_term Σ.1 Σ f f' ->\n  All2 (cumul_prop Σ Γ) args args' ->\n  Σ ;;; Γ |- mkApps f args ~~ mkApps f' args'.\nProof using Hcf Hcf'.\n  intros clΓ clf clf' eq eq'.\n  eapply cumul_prop_alt.\n  eapply cumul_prop_args in eq' as (nf & nf' & [redl redr eq']).\n  exists (mkApps f nf), (mkApps f' nf'); split.\n  - eapply closed_red_mkApps; auto.\n  - eapply closed_red_mkApps; auto.\n  - eapply eq_term_upto_univ_mkApps.\n    eapply eq_term_upto_univ_impl.\n    5:eapply eq. all:auto. 4:lia.\n    all:now eapply subrelation_eq_universe_eq_prop.\nQed.\n\nHint Resolve closed_red_open_right : fvs.\n\nLemma red_cumul_prop {Σ Γ} {wfΣ : wf Σ} :\n  CRelationClasses.subrelation (closed_red Σ Γ) (cumul_prop Σ Γ).\nProof using Type.\n  intros x y r. eapply cumul_prop_alt. exists y, y.\n  split; fvs. eapply closed_red_refl; fvs. apply eq_term_upto_univ_refl; typeclasses eauto.\nQed.\n\nLemma eq_term_prop_mkApps_inv {Σ ind u args ind' u' args'} {wfΣ : wf_ext Σ} :\n  forall n, eq_term_prop Σ n (mkApps (tInd ind u) args) (mkApps (tInd ind' u') args') ->\n  All2 (eq_term_prop Σ 0) args args'.\nProof using Type.\n  revert args'.\n  induction args using rev_ind; intros args' n; simpl.\n  intros H; destruct args' using rev_case.\n  constructor.\n  depelim H. solve_discr. eapply app_eq_nil in H1 as [_ H]. congruence.\n  intros H.\n  destruct args' using rev_case. depelim H. solve_discr.\n  apply app_eq_nil in H1 as [_ H]; discriminate.\n  rewrite !mkApps_app /= in H. depelim H.\n  eapply All2_app => //.\n  eapply IHargs; eauto. repeat constructor.\n  red. apply H0.\nQed.\n\nLemma cumul_prop_mkApps_Ind_inv {Σ Γ ind u args ind' u' args'} {wfΣ : wf_ext Σ} :\n  Σ ;;; Γ |- mkApps (tInd ind u) args ~~ mkApps (tInd ind' u') args' ->\n  All2 (cumul_prop Σ Γ) args args'.\nProof using Type.\n  intros eq.\n  eapply cumul_prop_alt in eq as (nf & nf' & [redl redr eq']).\n  eapply invert_red_mkApps_tInd in redl as [args'' [-> clΓ eqargs]].\n  eapply invert_red_mkApps_tInd in redr as [args''' [-> _ eqargs']].\n  eapply All2_trans. typeclasses eauto.\n  eapply All2_impl; eauto. eapply red_cumul_prop.\n  eapply All2_trans. typeclasses eauto.\n  2:{ eapply All2_symP. intros x y H; now eapply cumul_prop_sym.\n      eapply All2_impl; eauto. eapply red_cumul_prop. }\n  eapply eq_term_prop_mkApps_inv in eq' => //.\n  eapply closed_red_terms_open_right in eqargs.\n  eapply closed_red_terms_open_right in eqargs'.\n  solve_all. constructor; auto.\nQed.\n\nGlobal Instance cumul_prop_sym' Σ Γ : wf Σ.1 -> CRelationClasses.Symmetric (cumul_prop Σ Γ).\nProof using Type.\n  now intros wf x y; eapply cumul_prop_sym.\nQed.\n\nNotation eq_term_napp Σ n x y :=\n  (eq_term_upto_univ_napp Σ (eq_universe Σ) (eq_universe Σ) n x y).\n\nNotation leq_term_napp Σ n x y :=\n    (eq_term_upto_univ_napp Σ (eq_universe Σ) (leq_universe Σ) n x y).\n\nLemma eq_term_upto_univ_napp_leq {Σ : global_env_ext} {n x y} :\n  eq_term_napp Σ n x y ->\n  leq_term_napp Σ n x y.\nProof using Type.\n  eapply eq_term_upto_univ_impl; auto; typeclasses eauto.\nQed.\n\nLemma cumul_prop_is_open {Σ Γ T U} :\n  Σ ;;; Γ |- T ~~ U ->\n  [× is_closed_context Γ, is_open_term Γ T & is_open_term Γ U].\nProof using Type.\n  induction 1; split; auto.\nQed.\n\nLemma is_closed_context_weaken {Γ Δ} :\n  is_closed_context Γ ->\n  is_closed_context Δ ->\n  is_closed_context (Γ ,,, Δ).\nProof using Type.\n  rewrite on_free_vars_ctx_app => -> /=.\n  eapply on_free_vars_ctx_impl. discriminate.\nQed.\n\nLemma eq_context_upto_map2_set_binder_name Σ eqterm leterm eq le pctx pctx' Γ Δ :\n  eq_context_gen eqterm leterm pctx pctx' ->\n  eq_context_upto Σ eq le Γ Δ ->\n  eq_context_upto Σ eq le\n    (map2 set_binder_name (forget_types pctx) Γ)\n    (map2 set_binder_name (forget_types pctx') Δ).\nProof using Type.\nintros eqp.\ninduction 1 in pctx, pctx', eqp |- *.\n- induction eqp; cbn; constructor.\n- depelim eqp. simpl. constructor.\n  simpl. constructor; auto.\n  destruct c, p; constructor; auto.\nQed.\n\n(** Well-typed terms in the leq_term relation live in the same sort hierarchy. *)\nLemma typing_leq_term_prop (Σ : global_env_ext) Γ t t' T T' :\n  wf Σ.1 ->\n  Σ ;;; Γ |- t : T ->\n  on_udecl Σ.1 Σ.2 ->\n  Σ ;;; Γ |- t' : T' ->\n  forall n, leq_term_napp Σ n t' t ->\n  Σ ;;; Γ |- T ~~ T'.\nProof using Hcf Hcf'.\n  intros wfΣ Ht.\n  revert Σ wfΣ Γ t T Ht t' T'.\n  eapply (typing_ind_env\n  (fun Σ Γ t T =>\n  forall t' T' : term,\n  on_udecl Σ.1 Σ.2 ->\n  Σ;;; Γ |- t' : T' ->\n  forall n, leq_term_napp Σ n t' t ->\n  Σ ;;; Γ |- T ~~ T')%type\n  (fun Σ Γ => wf_local Σ Γ)); auto;intros Σ wfΣ Γ wfΓ; intros.\n\n  1-13:match goal with\n  [ H : leq_term_napp _ _ _ _ |- _ ] => depelim H\n  end; assert (wf_ext Σ) by (split; assumption).\n\n  15:{ assert (wf_ext Σ) by (split; assumption). specialize (X1 _ _ H X5 _ X6).\n       eapply cumul_prop_cum_l; tea.\n       eapply cumulSpec_cumulAlgo_curry in X4; tea; fvs. }\n\n  6:{ eapply inversion_App in X6 as (na' & A' & B' & hf & ha & cum); auto.\n      specialize (X3 _ _ H hf _ X7_1).\n      specialize (X5 _ _ H ha _ (eq_term_upto_univ_napp_leq X7_2)).\n      eapply cumul_cumul_prop in cum; auto.\n      transitivity (B' {0 := u0}) => //.\n      eapply cumul_prop_prod_inv in X3 => //.\n      transitivity (B' {0 := u}).\n      eapply substitution1_untyped_cumul_prop in X3. eapply X3.\n      now eapply subject_is_open_term.\n      destruct (cumul_prop_is_open cum).\n      constructor; auto. eapply on_free_vars_subst => /= //.\n      eapply subject_is_open_term in X4. now rewrite X4.\n      rewrite shiftnP_add. now eapply cumul_prop_is_open in X3 as [].\n      eapply eq_term_eq_term_prop_impl => //.\n      eapply PCUICEquality.eq_term_upto_univ_substs.\n      all:try typeclasses eauto.\n      eapply PCUICEquality.eq_term_upto_univ_refl. all:try typeclasses eauto.\n      constructor. 2:constructor. now symmetry. }\n\n  - eapply inversion_Rel in X0 as [decl' [wfΓ' [Hnth Hcum]]]; auto.\n    rewrite Hnth in H; noconf H. now eapply cumul_cumul_prop in Hcum.\n\n  - eapply inversion_Sort in X0 as [wf [wfs Hs]]; auto.\n    apply subrelation_leq_universe_eq_prop in x => //.\n    apply cumul_cumul_prop in Hs => //.\n    eapply cumul_prop_trans; eauto.\n    destruct (cumul_prop_is_open Hs) as [].\n    constructor => //. constructor. symmetry.\n    split; split; intros H'. 1,2:now eapply is_prop_superE in H'.\n    1,2:now eapply is_sprop_superE in H'.\n\n  - eapply inversion_Prod in X4 as [s1' [s2' [Ha [Hb Hs]]]]; auto.\n    specialize (X1 _ _ H Ha).\n    specialize (X1 _ (eq_term_upto_univ_napp_leq X5_1)).\n    eapply context_conversion in Hb.\n    3:{ constructor. apply conv_ctx_refl. constructor. eassumption.\n      constructor. eauto. }\n    2:{ constructor; eauto. now exists s1. }\n    specialize (X3 _ _ H Hb _ X5_2).\n    eapply cumul_cumul_prop in Hs => //.\n    eapply cumul_prop_trans; eauto.\n    constructor; fvs. constructor.\n    split.\n    * split; intros Hs'; apply is_prop_sort_prod in Hs'; eapply is_prop_prod; eapply cumul_prop_props; eauto.\n      now eapply cumul_prop_sym; eauto.\n    * split; intros Hs'; apply is_sprop_sort_prod in Hs'; eapply is_sprop_prod; eapply cumul_sprop_props; eauto.\n      now eapply cumul_prop_sym; eauto.\n\n  - eapply inversion_Lambda in X4 as (s & B & dom & bod & cum).\n    specialize (X1 _ _ H dom _ (eq_term_upto_univ_napp_leq X5_1)).\n    specialize (X3 t0 B H).\n    assert(conv_context cumulAlgo_gen Σ (Γ ,, vass na ty) (Γ ,, vass n t)).\n    { repeat constructor; pcuic. }\n    forward X3 by eapply context_conversion; eauto; pcuic.\n    specialize (X3 _ X5_2). eapply cumul_cumul_prop in cum; eauto.\n    eapply cumul_prop_trans; eauto.\n    eapply cumul_prop_tProd; eauto. now symmetry. now symmetry. auto.\n\n  - eapply inversion_LetIn in X6 as (s1' & A & dom & bod & codom & cum); auto.\n    specialize (X1 _ _ H dom _ (eq_term_upto_univ_napp_leq X7_2)).\n    specialize (X3 _ _ H bod _  (eq_term_upto_univ_napp_leq X7_1)).\n    assert(conv_context cumulAlgo_gen Σ (Γ ,, vdef na t ty) (Γ ,, vdef n b b_ty)).\n    { repeat constructor; pcuic. }\n    specialize (X5 u A H).\n    forward X5 by eapply context_conversion; eauto; pcuic.\n    specialize (X5 _ X7_3).\n    eapply cumul_cumul_prop in cum; eauto.\n    eapply cumul_prop_trans; eauto.\n    eapply cumul_prop_tLetIn; auto; now symmetry.\n\n  - eapply inversion_Const in X1 as [decl' [wf [declc [cu cum]]]]; auto.\n    eapply cumul_cumul_prop in cum; eauto.\n    eapply cumul_prop_trans; eauto.\n    unshelve eapply declared_constant_to_gen in H, declc; eauto.\n    pose proof (declared_constant_inj _ _ H declc); subst decl'.\n    eapply cumul_prop_subst_instance; eauto. fvs.\n    destruct (cumul_prop_is_open cum) as [].\n    now rewrite on_free_vars_subst_instance in i0.\n\n  - eapply inversion_Ind in X1 as [decl' [idecl' [wf [declc [cu cum]]]]]; auto.\n    unshelve eapply declared_inductive_to_gen in isdecl, declc; eauto.\n    pose proof (declared_inductive_inj isdecl declc) as [-> ->].\n    eapply cumul_cumul_prop in cum; eauto.\n    eapply cumul_prop_trans; eauto.\n    eapply cumul_prop_subst_instance; tea. fvs.\n    destruct (cumul_prop_is_open cum) as [].\n    now rewrite on_free_vars_subst_instance in i0.\n\n  - eapply inversion_Construct in X1 as [decl' [idecl' [cdecl' [wf [declc [cu cum]]]]]]; auto.\n    unshelve eapply declared_constructor_to_gen in declc; eauto.\n    unshelve epose proof (isdecl' := declared_constructor_to_gen isdecl); eauto.\n    pose proof (declared_constructor_inj isdecl' declc) as [-> [-> ->]].\n    eapply cumul_cumul_prop in cum; eauto.\n    eapply cumul_prop_trans; eauto.\n    unfold type_of_constructor.\n    have clars : is_closed_context (arities_context (ind_bodies mdecl))@[u].\n    { eapply wf_local_closed_context. eapply (wf_arities_context_inst isdecl H). }\n    have clty : is_open_term (Γ,,, arities_context (ind_bodies mdecl)) (cstr_type cdecl').\n    { eapply closedn_on_free_vars, closed_upwards.\n      eapply PCUICClosedTyp.declared_constructor_closed_gen_type; tea. len. }\n    rewrite on_free_vars_ctx_subst_instance in clars.\n    etransitivity.\n    eapply (@substitution_untyped_cumul_prop_equiv _ Γ (subst_instance u (arities_context mdecl.(ind_bodies))) []); auto.\n    * simpl.\n      apply is_closed_context_weaken. fvs.\n      now rewrite on_free_vars_ctx_subst_instance.\n    * eapply on_free_vars_terms_inds.\n    * eapply on_free_vars_terms_inds.\n    * simpl.\n      rewrite on_free_vars_subst_instance /=.\n      len. len in clty.\n    * len.\n    * len.\n    * generalize (ind_bodies mdecl).\n      induction l; simpl; constructor; auto.\n      constructor. simpl. eapply R_opt_variance_impl. now intros x.\n      eapply R_eq_univ_prop_consistent_instances; eauto.\n    * simpl.\n      eapply (@substitution_untyped_cumul_prop _ Γ (subst_instance u0 (arities_context mdecl.(ind_bodies))) []) => //.\n      eapply on_free_vars_terms_inds.\n      eapply untyped_subslet_inds. simpl.\n      eapply cumul_prop_subst_instance => //; eauto.\n      eapply is_closed_context_weaken; fvs.\n      len in clty; len.\n\n  - eapply inversion_Case in X9 as (mdecl' & idecl' & isdecl' & indices' & data & cum); auto.\n    eapply cumul_cumul_prop in cum; eauto.\n    eapply cumul_prop_trans; eauto. simpl.\n    clear X8.\n    unshelve eapply declared_inductive_to_gen in isdecl, isdecl'; eauto.\n    destruct (declared_inductive_inj isdecl isdecl'). subst.\n    destruct data.\n    specialize (X7 _ _ H5 scrut_ty _ (eq_term_upto_univ_napp_leq X10)).\n    eapply cumul_prop_sym => //.\n    destruct e as [eqpars [eqinst [eqpctx eqpret]]].\n    rewrite /ptm.\n    eapply cumul_prop_mkApps => //. fvs.\n    { eapply cumul_prop_is_open in cum as [].\n      rewrite on_free_vars_mkApps in i0.\n      move/andP: i0 => [] //. }\n    { now eapply type_it_mkLambda_or_LetIn, subject_is_open_term in pret. }\n    { eapply PCUICEquality.eq_term_upto_univ_it_mkLambda_or_LetIn => //. tc.\n      rewrite /predctx.\n      rewrite /case_predicate_context /case_predicate_context_gen.\n      rewrite /pre_case_predicate_context_gen /inst_case_context.\n      eapply eq_context_upto_map2_set_binder_name; tea.\n      eapply eq_context_upto_subst_context; tea. tc.\n      eapply eq_context_upto_univ_subst_instance; try tc. tas.\n      now eapply All2_rev. }\n    eapply All2_app. 2:(repeat constructor; auto using eq_term_eq_term_prop_impl).\n    eapply cumul_prop_mkApps_Ind_inv in X7 => //.\n    eapply All2_app_inv_l in X7 as (?&?&?&?&?).\n    eapply All2_symP => //. typeclasses eauto.\n    eapply app_inj in e as [eql ->] => //.\n    move: (All2_length eqpars).\n    move: (All2_length a0). lia. fvs. now eapply subject_is_open_term in scrut_ty.\n    now apply subject_is_open_term in X6.\n\n  - eapply inversion_Proj in X3 as (u' & mdecl' & idecl' & cdecl' & pdecl' & args' & inv); auto.\n    intuition auto.\n    specialize (X2 _ _  H0 a0 _ (eq_term_upto_univ_napp_leq X4)).\n    eapply eq_term_upto_univ_napp_leq in X4.\n    eapply cumul_cumul_prop in b; eauto.\n    eapply cumul_prop_trans; eauto.\n    eapply cumul_prop_mkApps_Ind_inv in X2 => //.\n    unshelve epose proof (a' := declared_projection_to_gen a); eauto.\n    unshelve epose proof (isdecl' := declared_projection_to_gen isdecl); eauto.\n    destruct (declared_projection_inj a' isdecl') as [<- [<- [<- <-]]].\n    destruct (isType_mkApps_Ind_inv _ isdecl X0 (validity X1)) as [ps [argss [_ cu]]]; eauto.\n    destruct (isType_mkApps_Ind_inv _ isdecl X0 (validity a0)) as [? [? [_ cu']]]; eauto.\n    epose proof (wf_projection_context _ _ isdecl c1).\n    epose proof (wf_projection_context _ _ isdecl c2).\n    transitivity (subst0 (c0 :: List.rev args') (subst_instance u pdecl'.(proj_type))).\n    eapply (@substitution_untyped_cumul_prop_cumul Σ Γ (projection_context p.(proj_ind) mdecl' idecl' u)) => //.\n    * cbn -[projection_context on_free_vars_ctx].\n      eapply is_closed_context_weaken; tas. fvs. now eapply wf_local_closed_context in X3.\n    * cbn -[projection_context on_free_vars_ctx].\n      eapply is_closed_context_weaken; tas. fvs. now eapply wf_local_closed_context in X6.\n    * epose proof (declared_projection_closed a).\n      len. rewrite on_free_vars_subst_instance. simpl; len.\n      rewrite (declared_minductive_ind_npars a) in H1.\n      rewrite closedn_on_free_vars //. eapply closed_upwards; tea. lia.\n    * epose proof (projection_subslet Σ _ _ _ _ _ _ _ _ _ isdecl wfΣ X1 (validity X1)).\n      now eapply subslet_untyped_subslet.\n    * epose proof (projection_subslet Σ _ _ _ _ _ _ _ _ _ a wfΣ a0 (validity a0)).\n      now eapply subslet_untyped_subslet.\n    * constructor => //. symmetry; constructor => //; fvs.\n      { now eapply leq_term_eq_term_prop_impl. }\n      { now eapply All2_rev. }\n    * eapply (@substitution_cumul_prop Σ Γ (projection_context p.(proj_ind) mdecl' idecl' u') []) => //.\n      { apply (projection_subslet Σ _ _ _ _ _ _ _ _ _ a wfΣ a0 (validity a0)). }\n      eapply cumul_prop_subst_instance; eauto.\n      cbn -[projection_context on_free_vars_ctx]; eapply is_closed_context_weaken => //; fvs.\n      epose proof (declared_projection_closed a).\n      simpl; len.\n      rewrite (declared_minductive_ind_npars a) in H1.\n      rewrite closedn_on_free_vars //. eapply closed_upwards; tea. lia.\n\n  - eapply inversion_Fix in X2 as (decl' & fixguard' & Hnth & types' & bodies & wffix & cum); auto.\n    eapply cumul_cumul_prop in cum; eauto.\n    eapply cumul_prop_trans; eauto.\n    eapply All2_nth_error in a; eauto.\n    destruct a as [[[a _] _] _].\n    constructor; [fvs|..].\n    { eapply nth_error_all in X0 as [? [dty ?]]; tea.\n      now apply subject_is_open_term in dty. }\n    { now eapply cumul_prop_is_open in cum as []. }\n    eapply eq_term_eq_term_prop_impl; eauto.\n    now symmetry in a.\n\n  - eapply inversion_CoFix in X2 as (decl' & fixguard' & Hnth & types' & bodies & wfcofix & cum); auto.\n    eapply cumul_cumul_prop in cum; eauto.\n    eapply cumul_prop_trans; eauto.\n    eapply All2_nth_error in a; eauto.\n    destruct a as [[[a _] _] _].\n    constructor; [fvs|..].\n    { eapply nth_error_all in X0 as [? [dty ?]]; tea.\n      now apply subject_is_open_term in dty. }\n    { now eapply cumul_prop_is_open in cum as []. }\n    eapply eq_term_eq_term_prop_impl; eauto.\n    now symmetry in a.\n\n  - depelim X2.\n    eapply inversion_Prim in X1 as [prim_ty' [cdecl' []]]; tea.\n    rewrite H in e. noconf e. eapply cumul_cumul_prop; eauto. pcuic.\nQed.\n\nEnd no_prop_leq_type.\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/pcuic/theories/PCUICCumulProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.23241174823774932}}
{"text": "Require Import InverseTraceRelations.\n\nRequire Import Raft.\nRequire Import CommonTheorems.\nRequire Import TraceUtil.\nRequire Import OutputImpliesAppliedInterface.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import SpecLemmas.\n\nRequire Import AppliedImpliesInputInterface.\n\nSection AppliedImpliesInputProof.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {oiai : output_implies_applied_interface}.\n\n  Lemma in_input_trace_or_app :\n    forall c id i tr1 tr2,\n      in_input_trace c id i tr1 \\/ in_input_trace c id i tr2 ->\n      in_input_trace c id i (tr1 ++ tr2).\n  Proof using. \n    unfold in_input_trace.\n    intuition; break_exists_exists; intuition.\n  Qed.\n\n  Section inner.\n    Variables client id : nat.\n    Variable i : input.\n\n    Lemma applied_implies_input_update_split :\n      forall client id i net h d ps,\n        applied_implies_input_state client id i (mkNetwork ps (update (nwState net) h d)) ->\n        exists e,\n          correct_entry client id i e /\\\n          (In e (log d) \\/\n           (exists h, In e (log (nwState net h))) \\/\n           (exists p es, In p ps /\\ mEntries (pBody p) = Some es /\\ In e es)).\n    Proof using. \n      unfold applied_implies_input_state.\n      intros.\n      break_exists_exists.\n      intuition.\n      break_exists.\n      simpl in *.\n      destruct (name_eq_dec h x0); rewrite_update; eauto.\n    Qed.\n\n    Lemma aiis_intro_state :\n      forall client id i net e h,\n        In e (log (nwState net h)) ->\n        correct_entry client id i e ->\n        applied_implies_input_state client id i net.\n    Proof using. \n      unfold applied_implies_input_state.\n      eauto 10.\n    Qed.\n\n    Lemma aiis_intro_packet :\n      forall client id i net e p es,\n        mEntries (pBody p) = Some es ->\n        In p (nwPackets net) ->\n        correct_entry client id i e ->\n        In e es ->\n        applied_implies_input_state client id i net.\n    Proof using. \n      unfold applied_implies_input_state.\n      eauto 10.\n    Qed.\n\n    Lemma doGenericServer_log :\n      forall h st os st' ps,\n        doGenericServer h st = (os, st', ps) ->\n        log st' = log st.\n    Proof using. \n      intros. unfold doGenericServer in *.\n      repeat break_match; find_inversion;\n      use_applyEntries_spec; simpl in *;\n      subst; auto.\n    Qed.\n\n    Theorem handleTimeout_log :\n      forall h st out st' ps,\n        handleTimeout h st = (out, st', ps) ->\n        log st' = log st.\n    Proof using. \n      intros. unfold handleTimeout, tryToBecomeLeader in *.\n      break_match; find_inversion; subst; auto.\n    Qed.\n\n    Theorem handleClientRequest_no_messages :\n      forall h st client id c out st' ps p,\n        handleClientRequest h st client id c = (out, st', ps) ->\n        In p ps -> False.\n    Proof using. \n      unfold handleClientRequest.\n      intros.\n      break_match; find_inversion; simpl in *; intuition.\n    Qed.\n\n    Lemma mEntries_some_is_applied_entries :\n      forall m es,\n        mEntries m = Some es ->\n        is_append_entries m.\n    Proof using. \n      unfold mEntries.\n      intros.\n      break_match; try discriminate.\n      find_inversion.\n      eauto 10.\n    Qed.\n\n    Lemma doGenericServer_packets :\n      forall h st os st' ps p,\n        doGenericServer h st = (os, st', ps) ->\n        In p ps -> False.\n    Proof using. \n      intros. unfold doGenericServer in *.\n      repeat break_match; find_inversion; subst; auto.\n    Qed.\n\n    Lemma doLeader_messages :\n      forall d h os d' ms m es e,\n        doLeader d h = (os, d', ms) ->\n        In m ms ->\n        mEntries (snd m) = Some es ->\n        In e es ->\n        In e (log d).\n    Proof using. \n      unfold doLeader.\n      intros.\n      repeat break_match; repeat find_inversion; simpl in *; intuition.\n      do_in_map. subst. simpl in *. find_inversion.\n      eauto using findGtIndex_in.\n    Qed.\n\n    Lemma handleInputs_aais :\n      forall client id h inp i net os d' ms e o,\n        ~ applied_implies_input_state client id i net ->\n        handleInput h inp (nwState net h) = (os, d', ms) ->\n        correct_entry client id i e ->\n        In e (log d') ->\n        in_input_trace client id i [(h, inl inp); o].\n    Proof using. \n      intros.\n      destruct inp; simpl in *.\n      - find_erewrite_lem handleTimeout_log.\n        exfalso. eauto using aiis_intro_state.\n      - destruct (log d') using (handleClientRequest_log_ind ltac:(eauto)).\n        + exfalso. eauto using aiis_intro_state.\n        + simpl in *.\n          break_or_hyp.\n          * subst. unfold in_input_trace. unfold correct_entry in *.\n            break_and. subst. simpl. eauto.\n          * exfalso. eauto using aiis_intro_state.\n    Qed.\n\n    Lemma mEntries_intro :\n      forall m t n l t' es l',\n        m = AppendEntries t n l t' es l' ->\n        mEntries m = Some es.\n    Proof using. \n      unfold mEntries. intros. subst. auto.\n    Qed.\n\n    Lemma handleMessage_aais :\n      forall client id i net p d' ms e,\n        ~ applied_implies_input_state client id i net ->\n        In p (nwPackets net) ->\n        handleMessage (pSrc p) (pDst p) (pBody p) (nwState net (pDst p)) = (d', ms) ->\n        correct_entry client id i e ->\n        In e (log d') ->\n        False.\n    Proof using. \n      intros.\n      destruct (pBody p) eqn:?; simpl in *; repeat break_let; repeat find_inversion.\n      - find_erewrite_lem handleRequestVote_same_log. eauto using aiis_intro_state.\n      - find_erewrite_lem handleRequestVoteReply_same_log. eauto using aiis_intro_state.\n      - find_apply_lem_hyp handleAppendEntries_log. intuition; find_rewrite.\n        + eauto using aiis_intro_state.\n        + subst. eauto using mEntries_intro, aiis_intro_packet.\n        + do_in_app. intuition.\n          * eauto using mEntries_intro, aiis_intro_packet.\n          * find_apply_lem_hyp removeAfterIndex_in.\n            eauto using aiis_intro_state.\n      - find_erewrite_lem handleAppendEntriesReply_same_log. eauto using aiis_intro_state.\n    Qed.\n\n    Lemma handleRequestVote_doesn't_send_AE :\n      forall h st t n lli llt d m,\n        handleRequestVote h st t n lli llt = (d, m) ->\n        ~ is_append_entries m.\n    Proof using. \n      intros.\n      unfold handleRequestVote in *.\n      repeat (break_match; repeat (find_inversion; simpl in *));\n        intro; break_exists; discriminate.\n    Qed.\n\n    Lemma handleAppendEntriesReply_doesn't_send_AE :\n      forall n st src t es b st' l,\n        handleAppendEntriesReply n st src t es b = (st', l) ->\n        forall x,\n          In x l ->\n          ~ is_append_entries (snd x).\n    Proof using. \n      intros.\n      unfold handleAppendEntriesReply in *.\n      repeat (break_match; repeat (find_inversion; simpl in *)); intuition.\n    Qed.\n\n    Lemma handleAppendEntries_doesn't_send_AE :\n      forall n st t i l t' l' l'' st' m,\n        handleAppendEntries n st t i l t' l' l'' = (st', m) ->\n        ~ is_append_entries m.\n    Proof using. \n      unfold handleAppendEntries.\n      intros.\n      repeat break_match; find_inversion; intro; break_exists; discriminate.\n    Qed.\n\n    Lemma handleMessage_sends_log :\n      forall client id i net p d' ms m es e,\n        In p (nwPackets net) ->\n        handleMessage (pSrc p) (pDst p) (pBody p) (nwState net (pDst p)) = (d', ms) ->\n        correct_entry client id i e ->\n        In m ms ->\n        mEntries (snd m) = Some es ->\n        In e es ->\n        In e (log (nwState net (pDst p))).\n    Proof using. \n      intros.\n      destruct (pBody p) eqn:?; simpl in *; repeat break_let; repeat find_inversion;\n      simpl in *; intuition; subst; simpl in *.\n      - exfalso. eapply handleRequestVote_doesn't_send_AE; eauto using mEntries_some_is_applied_entries.\n      - exfalso. eapply handleAppendEntries_doesn't_send_AE; eauto using mEntries_some_is_applied_entries.\n      - exfalso.\n        eapply handleAppendEntriesReply_doesn't_send_AE;\n          eauto using mEntries_some_is_applied_entries.\n    Qed.\n\n    Lemma applied_implies_input_in_input_trace :\n      forall net failed net' failed' tr,\n        raft_intermediate_reachable net ->\n        @step_f _ _ failure_params (failed, net) (failed', net') tr ->\n        ~ applied_implies_input_state client id i net ->\n        applied_implies_input_state client id i net' ->\n        in_input_trace client id i tr.\n    Proof using. \n      intros.\n      match goal with\n        | [ H : context [step_f _ _ _ ] |- _ ] => invcs H\n      end.\n      - unfold RaftNetHandler in *. repeat break_let. subst. find_inversion.\n        find_apply_lem_hyp applied_implies_input_update_split.\n        break_exists. intuition; break_exists.\n        + find_erewrite_lem doGenericServer_log.\n          find_erewrite_lem doLeader_same_log.\n          exfalso. eauto using aiis_intro_state, handleMessage_aais.\n        + exfalso. eauto using aiis_intro_state.\n        + intuition. do_in_app. intuition.\n          * do_in_map. subst. simpl in *.\n            { repeat (do_in_app; intuition).\n              - exfalso. eauto using aiis_intro_state, handleMessage_sends_log.\n              - find_eapply_lem_hyp doLeader_messages; eauto.\n                exfalso. eauto using aiis_intro_state, handleMessage_aais.\n              - exfalso. eauto using doGenericServer_packets.\n            }\n          * exfalso. eauto using aiis_intro_packet.\n      - unfold RaftInputHandler in *. repeat break_let. subst. find_inversion.\n        find_apply_lem_hyp applied_implies_input_update_split.\n        break_exists. intuition; break_exists.\n        + find_erewrite_lem doGenericServer_log.\n          find_erewrite_lem doLeader_same_log.\n          eauto using handleInputs_aais.\n        + exfalso. eauto using aiis_intro_state.\n        + intuition. do_in_app. intuition.\n          * do_in_map. subst. simpl in *.\n            { repeat (do_in_app; intuition).\n              - destruct inp; simpl in *.\n                + exfalso. eapply handleTimeout_not_is_append_entries; eauto.\n                  eauto using mEntries_some_is_applied_entries.\n                + exfalso. eauto using handleClientRequest_no_messages.\n              - find_eapply_lem_hyp doLeader_messages; eauto.\n                eauto using handleInputs_aais.\n              - exfalso. eauto using doGenericServer_packets.\n            }\n          * exfalso. eauto using aiis_intro_packet.\n      - unfold applied_implies_input_state in H2.\n        break_exists. intuition; break_exists; simpl in *.\n        + exfalso; eauto  using aiis_intro_state.\n        + break_and. simpl in *.\n          exfalso. eauto using aiis_intro_packet.\n      - unfold applied_implies_input_state in H2.\n        break_exists. intuition; break_exists; simpl in *.\n        + exfalso; eauto  using aiis_intro_state.\n        + intuition.\n          * subst. exfalso. eauto using aiis_intro_packet.\n          * exfalso. apply H1. eapply aiis_intro_packet; eauto.\n            congruence.\n      - congruence.\n      - unfold applied_implies_input_state in H2.\n        break_exists. intuition; break_exists; simpl in *.\n        + break_if.\n          * subst. unfold reboot in *. simpl in *.\n            exfalso. eauto using aiis_intro_state.\n          * exfalso. eauto using aiis_intro_state.\n        + intuition.\n          exfalso. eauto using aiis_intro_packet.\n    Qed.\n\n    Definition aiis_host (net : network) : Prop :=\n      exists h e,\n        correct_entry client id i e /\\\n        In e (log (nwState net h)).\n\n    Lemma name_dec :\n      forall (P : name -> Prop)\n             (P_dec : forall x, {P x} + {~P x}),\n        {exists x, P x} + {~ exists x, P x}.\n    Proof.\n      intros.\n      destruct (find (fun x => if P_dec x then true else false) nodes) eqn:?.\n      - find_apply_lem_hyp find_some. intuition. break_if; try discriminate.\n        eauto.\n      - right. intro. break_exists.\n        eapply find_none with (x := x) in Heqo; auto using all_names_nodes.\n        break_if; congruence.\n    Defined.\n\n    Definition correct_entry_dec (e : entry) :\n      {correct_entry client id i e} +\n      {~ correct_entry client id i e}.\n      unfold correct_entry.\n      destruct (eq_nat_dec (eClient e) client),\n               (eq_nat_dec (eId e) id),\n               (input_eq_dec (eInput e) i); intuition.\n    Defined.\n\n    Definition exists_dec :\n      forall A (P : A -> Prop)\n             (P_dec : forall x, {P x} + {~ P x}) l,\n        {exists x, P x /\\ In x l} +\n        {~ exists x, P x /\\ In x l}.\n      intros.\n      destruct (find (fun e => if P_dec e then true else false) l) eqn:?.\n      - find_apply_lem_hyp find_some. intuition. break_if; try discriminate. eauto.\n      - right. intro. break_exists. intuition.\n        eapply find_none with (x := x) in Heqo; eauto.\n        break_if; congruence.\n    Defined.\n\n    Definition aiis_host_dec (net : network) :\n      {aiis_host net} + {~aiis_host net}.\n      unfold aiis_host.\n      simpl.\n      apply name_dec.\n      intros.\n      apply exists_dec.\n      apply correct_entry_dec.\n    Defined.\n\n    Definition aiis_packet (net : network) : Prop :=\n      exists p,\n        (exists es,\n           (exists e,\n              correct_entry client id i e /\\\n              In e es) /\\\n           mEntries (pBody p) = Some es) /\\\n        In p (nwPackets net).\n\n    Definition aiis_packet_dec (net : network) : {aiis_packet net} + {~aiis_packet net}.\n      unfold aiis_packet.\n      apply exists_dec.\n      intros.\n      destruct (pBody x);\n        try solve [right; intro; break_exists; intuition; discriminate].\n      simpl.\n      destruct (exists_dec _ _ correct_entry_dec l0); eauto.\n      right. intro. break_exists. break_and. find_inversion. auto.\n    Defined.\n\n    Definition applied_implies_input_state_dec (net : network) :\n      {applied_implies_input_state client id i net} +\n      {~ applied_implies_input_state client id i net}.\n      unfold applied_implies_input_state.\n      destruct (aiis_host_dec net).\n      - unfold aiis_host in *.\n        left. repeat (break_exists; intuition). eauto 10.\n      - destruct (aiis_packet_dec net).\n        + unfold aiis_packet in *.\n          left. repeat (break_exists; intuition). eauto 10.\n        + unfold aiis_host, aiis_packet in *.\n          right. intro. repeat (break_exists; intuition); eauto 10.\n    Defined.\n\n    Instance ITR : InverseTraceRelation step_f :=\n      { init := step_f_init;\n        R := fun s => applied_implies_input_state client id i (snd s);\n        T := in_input_trace client id i\n      }.\n    - intros. apply applied_implies_input_state_dec.\n    - intros.\n      unfold in_input_trace in *. break_exists_exists.\n      intuition.\n    - unfold applied_implies_input_state. intro. break_exists. break_and.\n      intuition; break_exists; intuition.\n    - intros. simpl in *.\n      apply in_input_trace_or_app. right.\n      destruct s, s'. simpl in *.\n      eapply applied_implies_input_in_input_trace; eauto.\n      eapply step_f_star_raft_intermediate_reachable; eauto.\n    Defined.\n  End inner.\n\n  Lemma applied_implies_input :\n    forall client id failed net tr e,\n      @step_f_star _ _ failure_params step_f_init (failed, net) tr ->\n      eClient e = client ->\n      eId e = id ->\n      applied_implies_input_state client id (eInput e) net ->\n      in_input_trace client id (eInput e) tr.\n  Proof using. \n    intros.\n    pose proof @inverse_trace_relations_work _ _ step_f (ITR client id (eInput e)) (failed, net) tr.\n    unfold step_f_star in *. simpl in *.\n    auto.\n  Qed.\n\n  Instance aiii : applied_implies_input_interface.\n  Proof.\n    split.\n    exact applied_implies_input.\n  Qed.\nEnd AppliedImpliesInputProof.", "meta": {"author": "ahmet-celik", "repo": "pverdi", "sha": "dc88c4a5fd7d90b5bb48e583bd8286097f983f81", "save_path": "github-repos/coq/ahmet-celik-pverdi", "path": "github-repos/coq/ahmet-celik-pverdi/pverdi-dc88c4a5fd7d90b5bb48e583bd8286097f983f81/raft-proofs/AppliedImpliesInputProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23241173663748405}}
{"text": "Require Import RelationClasses.\n\nFrom Paco Require Import paco.\nFrom sflib Require Import sflib.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Loc.\nRequire Import Time.\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\nRequire Import Behavior.\nRequire Import Cover.\nRequire Import Pred.\nRequire Import Trace.\nRequire Import JoinedView.\n\nRequire Import MemoryProps.\nRequire Import OrderedTimes.\n\nRequire Import PFStep.\nRequire Import LocalPFThread.\n\nSet Implicit Arguments.\n\n\n\n\n\n\n\nSection SIM.\n\n  Variable L: Loc.t -> bool.\n  Variable times: Loc.t -> Time.t -> Prop.\n  Hypothesis WO: forall loc, well_ordered (times loc).\n\n  (* sim promises *)\n\n  Inductive sim_promise_content\n            (F: Prop)\n            (extra: Time.t -> Prop)\n            (loc: Loc.t) (ts: Time.t)\n    :\n      option (Time.t * Message.t) -> option (Time.t * Message.t) -> Prop :=\n  | sim_promise_content_none\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (NLOC: L loc)\n    :\n      sim_promise_content F extra loc ts None None\n  | sim_promise_content_normal\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (* (NLOC: ~ L loc) *)\n      cnt\n    :\n      sim_promise_content F extra loc ts cnt cnt\n  | sim_promise_content_reserve\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (LOC: L loc)\n      from_src from_tgt\n    :\n      sim_promise_content F extra loc ts\n                          (Some (from_src, Message.reserve))\n                          (Some (from_tgt, Message.reserve))\n  | sim_promise_content_forget\n      (PROM: F)\n      (NEXTRA: forall t, ~ extra t)\n      (LOC: L loc)\n      from_src from_tgt val released\n    :\n      sim_promise_content F extra loc ts\n                          (Some (from_src, Message.reserve))\n                          (Some (from_tgt, Message.concrete val released))\n  | sim_promise_content_extra\n      from\n      (NPROM: ~ F)\n      (LOC: L loc)\n      (EXTRA: extra from)\n    :\n      sim_promise_content F extra loc ts (Some (from, Message.reserve)) None\n  .\n  Hint Constructors sim_promise_content.\n\n  Record sim_promise\n         (self: Loc.t -> Time.t -> Prop)\n         (extra: Loc.t -> Time.t -> Time.t -> Prop)\n         (prom_src prom_tgt: Memory.t): Prop :=\n    {\n      sim_promise_contents:\n        forall loc ts,\n          sim_promise_content (self loc ts) (extra loc ts)\n                              loc ts\n                              (Memory.get loc ts prom_src)\n                              (Memory.get loc ts prom_tgt);\n      sim_promise_wf:\n        forall loc from ts (EXTRA: extra loc ts from),\n          (<<FORGET: self loc from>>) /\\\n          (<<LB: lb_time (times loc) from ts>>) /\\\n          (<<TS: Time.lt from ts>>);\n      sim_promise_extra:\n        forall loc ts (SELF: self loc ts),\n        exists to,\n          (<<GET: Memory.get loc to prom_src = Some (ts, Message.reserve)>>) /\\\n          (<<TS: Time.lt ts to>>);\n    }.\n\n  Lemma promises_forget_extra_exclusive F extra mem_src mem_tgt loc from to ts\n        (PROMISES: sim_promise F extra mem_src mem_tgt)\n        (FORGET: F loc ts)\n        (EXTRA: extra loc to from)\n    :\n      ts <> to.\n  Proof.\n    ii. subst.\n    set (PROM:=(sim_promise_contents PROMISES) loc to). inv PROM; ss.\n    eapply NEXTRA; eauto.\n  Qed.\n\n  Lemma sim_promise_src_none F extra prom_src prom_tgt\n        (PROMISE: sim_promise F extra prom_src prom_tgt)\n        loc to\n        (GETSRC: Memory.get loc to prom_src = None)\n    :\n      (<<GETTGT: Memory.get loc to prom_tgt = None>>) /\\\n      (<<NPROM: ~ F loc to >>) /\\\n      (<<NEXTRA: forall t, ~ extra loc to t>>).\n  Proof.\n    set (PROM:=(sim_promise_contents PROMISE) loc to).\n    rewrite GETSRC in PROM. inv PROM.\n    - splits; auto.\n    - splits; auto.\n  Qed.\n\n  Lemma sim_promise_bot self extra prom_src prom_tgt\n        (SIM: sim_promise self extra prom_src prom_tgt)\n        (BOT: prom_tgt = Memory.bot)\n    :\n      prom_src = Memory.bot.\n  Proof.\n    eapply Memory.ext. i. erewrite Memory.bot_get.\n    set (CNT:=(sim_promise_contents SIM) loc ts). subst.\n    erewrite Memory.bot_get in CNT. inv CNT; ss.\n    eapply sim_promise_wf in EXTRA; eauto. des.\n    set (CNT:=(sim_promise_contents SIM) loc from).\n    erewrite Memory.bot_get in CNT. inv CNT; ss.\n  Qed.\n\n\n\n  (* sim promises strong *)\n\n  Inductive sim_promise_content_strong\n            (F: Prop)\n            (extra: Time.t -> Prop)\n            (extra_all: Time.t -> Time.t -> Prop)\n            (loc: Loc.t) (ts: Time.t)\n    :\n      option (Time.t * Message.t) -> option (Time.t * Message.t) -> Prop :=\n  | sim_promise_content_strong_none\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (NLOC: L loc)\n    :\n      sim_promise_content_strong F extra extra_all loc ts None None\n  | sim_promise_content_strong_normal\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (* (NLOC: ~ L loc) *)\n      cnt\n    :\n      sim_promise_content_strong F extra extra_all loc ts cnt cnt\n  | sim_promise_content_strong_reserve\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (LOC: L loc)\n      from_src from_tgt\n      (EXTRA: from_tgt = from_src \\/ extra_all from_src from_tgt)\n    :\n      sim_promise_content_strong F extra extra_all loc ts\n                          (Some (from_src, Message.reserve))\n                          (Some (from_tgt, Message.reserve))\n  | sim_promise_content_strong_forget\n      (PROM: F)\n      (NEXTRA: forall t, ~ extra t)\n      (LOC: L loc)\n      from_src from_tgt val released\n      (EXTRA: from_tgt = from_src \\/ extra_all from_src from_tgt)\n    :\n      sim_promise_content_strong F extra extra_all loc ts\n                          (Some (from_src, Message.reserve))\n                          (Some (from_tgt, Message.concrete val released))\n  | sim_promise_content_strong_extra\n      from\n      (NPROM: ~ F)\n      (LOC: L loc)\n      (EXTRA: extra from)\n    :\n      sim_promise_content_strong F extra extra_all loc ts (Some (from, Message.reserve)) None\n  .\n  Hint Constructors sim_promise_content_strong.\n\n  Lemma sim_promise_content_strong_sim_promise_content\n        loc ts F extra get0 get1 extra_all\n        (SIM: sim_promise_content_strong F extra extra_all loc ts  get0 get1)\n    :\n      sim_promise_content F extra loc ts get0 get1.\n  Proof.\n    inv SIM; econs; eauto.\n  Qed.\n\n  Record sim_promise_strong\n         (self: Loc.t -> Time.t -> Prop)\n         (extra: Loc.t -> Time.t -> Time.t -> Prop)\n         (extra_all: Loc.t -> Time.t -> Time.t -> Prop)\n         (prom_src prom_tgt: Memory.t): Prop :=\n    {\n      sim_promise_strong_contents:\n        forall loc ts,\n          sim_promise_content_strong (self loc ts) (extra loc ts) (extra_all loc)\n                                     loc ts\n                                     (Memory.get loc ts prom_src)\n                                     (Memory.get loc ts prom_tgt);\n      sim_promise_strong_wf:\n        forall loc from ts (EXTRA: extra loc ts from),\n          (<<FORGET: self loc from>>) /\\\n          (<<LB: lb_time (times loc) from ts>>) /\\\n          (<<TS: Time.lt from ts>>);\n      sim_promise_strong_extra:\n        forall loc ts (SELF: self loc ts),\n        exists to,\n          (<<GET: Memory.get loc to prom_src = Some (ts, Message.reserve)>>) /\\\n          (<<TS: Time.lt ts to>>);\n    }.\n\n  Lemma sim_promise_strong_sim_promise\n        self extra extra_all prom_src prom_tgt\n        (SIM: sim_promise_strong self extra extra_all prom_src prom_tgt)\n    :\n      sim_promise self extra prom_src prom_tgt.\n  Proof.\n    econs.\n    - ii. eapply sim_promise_content_strong_sim_promise_content; eauto.\n      eapply SIM; eauto.\n    - apply SIM.\n    - apply SIM.\n  Qed.\n\n  Record sim_promise_list\n         (self: Loc.t -> Time.t -> Prop)\n         (extra: Loc.t -> Time.t -> Time.t -> Prop)\n         (extra_all: Loc.t -> Time.t -> Time.t -> Prop)\n         (prom_src prom_tgt: Memory.t)\n         (l: list (Loc.t * Time.t)): Prop :=\n    {\n      sim_promise_list_contents:\n        forall loc ts,\n          (<<NORMAL: sim_promise_content_strong (self loc ts) (extra loc ts) (extra_all loc) loc ts\n                                                (Memory.get loc ts prom_src)\n                                                (Memory.get loc ts prom_tgt)>>) \\/\n          ((<<LIN: List.In (loc, ts) l>>) /\\\n           (<<WEAK: sim_promise_content (self loc ts) (extra loc ts) loc ts\n                                        (Memory.get loc ts prom_src)\n                                        (Memory.get loc ts prom_tgt)>>));\n      sim_promise_list_wf:\n        forall loc from ts (EXTRA: extra loc ts from),\n          (<<FORGET: self loc from>>) /\\\n          (<<LB: lb_time (times loc) from ts>>) /\\\n          (<<TS: Time.lt from ts>>);\n      sim_promise_list_extra:\n        forall loc ts (SELF: self loc ts),\n        exists to,\n          (<<GET: Memory.get loc to prom_src = Some (ts, Message.reserve)>>) /\\\n          (<<TS: Time.lt ts to>>);\n    }.\n\n  Lemma sim_promise_list_nil self extra extra_all prom_src prom_tgt\n        (SIM: sim_promise_list self extra extra_all prom_src prom_tgt [])\n    :\n      sim_promise_strong self extra extra_all prom_src prom_tgt.\n  Proof.\n    econs.\n    - ii. hexploit (sim_promise_list_contents SIM); eauto. i. des; eauto. ss.\n    - apply SIM.\n    - apply SIM.\n  Qed.\n\n  Lemma sim_promise_weak_list_exists self extra extra_all prom_src prom_tgt\n        (SIM: sim_promise self extra prom_src prom_tgt)\n        (FIN: Memory.finite prom_src)\n    :\n      exists l,\n        (<<SIM: sim_promise_list self extra extra_all prom_src prom_tgt l>>).\n  Proof.\n    unfold Memory.finite in *. des.\n    hexploit (@list_filter_exists\n                (Loc.t * Time.t)\n                (fun locts =>\n                   let (loc, ts) := locts in\n                   ~ sim_promise_content_strong (self loc ts) (extra loc ts) (extra_all loc) loc ts\n                     (Memory.get loc ts prom_src)\n                     (Memory.get loc ts prom_tgt))\n                dom).\n    i. des. exists l'. econs; [|apply SIM|apply SIM].\n    ii. set (PROM:= (sim_promise_contents SIM) loc ts).\n    destruct (classic (List.In (loc,ts) l')).\n    - right. splits; auto.\n    - left. red. inv PROM; try by (econs; eauto).\n      + apply NNPP. ii. exploit FIN; eauto. i.\n        hexploit (proj1 (@COMPLETE (loc, ts))); auto.\n        splits; auto. ii. rewrite H1 in *. rewrite H2 in *. auto.\n      + apply NNPP. ii. exploit FIN; eauto. i.\n        hexploit (proj1 (@COMPLETE (loc, ts))); auto.\n        splits; auto. ii. rewrite H1 in *. rewrite H2 in *. auto.\n  Qed.\n\n  Lemma sim_promise_weak_strengthen others self extra_others extra_self\n        prom_src prom_tgt mem_src mem_tgt\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (MLETGT: Memory.le prom_tgt mem_tgt)\n        (MLESRC: Memory.le prom_src mem_src)\n        (FIN: Memory.finite prom_src)\n        (BOTNONESRC: Memory.bot_none prom_src)\n        (PROM: sim_promise self extra_self prom_src prom_tgt)\n        (MEMWF: memory_times_wf times mem_tgt)\n    :\n      exists prom_src' mem_src',\n        (<<FUTURE: reserve_future_memory prom_src mem_src prom_src' mem_src'>>) /\\\n        (<<MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src' mem_tgt>>) /\\\n        (<<PROM: sim_promise_strong\n                   self extra_self (extra_others \\\\3// extra_self)\n                   prom_src' prom_tgt>>).\n  Proof.\n    exploit sim_promise_weak_list_exists; eauto. i. des.\n    clear PROM. ginduction l.\n    { i. exists prom_src, mem_src. splits; auto.\n      { econs; eauto. }\n      { eapply sim_promise_list_nil; eauto. }\n    }\n    i. destruct a as [loc ts].\n\n    cut (sim_promise_content_strong (self loc ts) (extra_self loc ts)\n                                    ((extra_others \\\\3// extra_self) loc)\n                                    loc ts\n                                    (Memory.get loc ts prom_src)\n                                    (Memory.get loc ts prom_tgt) \\/\n         exists prom_src' mem_src',\n           (<<FUTURE: reserve_future_memory prom_src mem_src prom_src' mem_src'>>) /\\\n           (<<MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src' mem_tgt>>) /\\\n           (<<PROM: sim_promise_list\n                      self extra_self (extra_others \\\\3// extra_self)\n                      prom_src' prom_tgt l>>)).\n    { intros H. match goal with\n                | [H:?A \\/ ?B |- _ ] => cut B\n                end.\n      { clear H. i. des. exploit IHl.\n        { eauto. }\n        { eapply MEM0. }\n        { eauto. }\n        { eapply reserve_future_memory_le; eauto. }\n        { eapply reserve_future_memory_finite; eauto. }\n        { eapply reserve_future_memory_bot_none; try apply BOTNONESRC; eauto. }\n        { eauto. }\n        { eauto. }\n        i. des. exists prom_src'0, mem_src'0. splits; eauto.\n        eapply reserve_future_memory_trans; eauto. }\n      { des; eauto. exists prom_src, mem_src. splits; auto.\n        { econs; eauto. }\n        econs; [|apply SIM|apply SIM]. ii.\n        set (PROM:=(sim_promise_list_contents SIM) loc0 ts0).\n        ss. des; clarify; auto. }\n    }\n\n    set (SIM0:= (sim_promise_list_contents SIM) loc ts). des; auto.\n    inv WEAK.\n    { left. econs 1; eauto. }\n    { left. econs 2; eauto. }\n    { clear LIN. symmetry in H. symmetry in H0.\n      rename H into PROMTGT. rename H0 into PROMSRC.\n      dup PROMSRC. dup PROMTGT. apply MLESRC in PROMSRC0. apply MLETGT in PROMTGT0.\n      rename PROMSRC0 into MEMSRC. rename PROMTGT0 into MEMTGT.\n      set (MEM0:=(sim_memory_contents MEM) loc ts).\n      rewrite MEMSRC in MEM0. rewrite MEMTGT in MEM0. inv MEM0; ss.\n      destruct (classic (self loc from_src)) as [SELF|NSELF].\n      { left. exploit sim_memory_from_forget; eauto. ss. right. auto. }\n\n      hexploit (@Memory.remove_exists prom_src); eauto.\n      intros [prom_src' REMOVEPROM].\n      hexploit (@Memory.remove_exists_le prom_src mem_src); eauto.\n      intros [mem_src' REMOVEMEM].\n      assert (REMOVE: Memory.promise prom_src mem_src loc from_src ts Message.reserve prom_src' mem_src' Memory.op_kind_cancel).\n      { econs; eauto. }\n      destruct (classic (exists from_src', (extra_others \\\\3// extra_self) loc from_src' from_tgt))\n        as [[from_src' EXTRA]|].\n      { guardH EXTRA.\n        hexploit (@Memory.add_exists mem_src' loc from_src' ts Message.reserve).\n        { ii. erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o.\n          hexploit sim_memory_disjoint.\n          { eauto. }\n          { eauto. }\n          { apply MEMTGT. }\n          { eapply GET2. }\n          { instantiate (1:=x). inv LHS. econs; ss.\n            transitivity from_src'; auto.\n            eapply (sim_memory_wf MEM) in EXTRA. des; auto. }\n          { eauto. }\n          i. destruct H as [EQ|[EQ [FORGET [EXTRA0 TS]]]].\n          { des; subst. destruct o; ss. }\n          { guardH FORGET. guardH EXTRA0.\n            hexploit sim_memory_extra_inj.\n            { eapply MEM. }\n            { eapply EXTRA0. }\n            { eapply EXTRA. }\n            i. subst. inv LHS. inv RHS. ss. timetac. }\n        }\n        { eapply (sim_memory_wf MEM) in EXTRA. destruct EXTRA as [_ EXTRA]. des.\n          eapply LB0.\n          { eapply MEMWF in MEMTGT. des; auto. }\n          { apply memory_get_ts_strong in MEMTGT. des; auto.\n            subst. erewrite BOTNONESRC in PROMSRC. clarify. }\n        }\n        { econs; eauto. }\n        intros [mem_src'' ADDMEM].\n        hexploit (@Memory.add_exists_le prom_src' mem_src'); eauto.\n        { eapply promise_memory_le; eauto. }\n        intros [prom_src'' ADDPROM].\n        assert (ADD: Memory.promise prom_src' mem_src' loc from_src' ts Message.reserve prom_src'' mem_src'' Memory.op_kind_add).\n        { econs; eauto. i. clarify. }\n        right. exists prom_src'', mem_src''. splits; eauto.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { econs; [|apply MEM]. i.\n          erewrite (@Memory.add_o mem_src''); eauto.\n          erewrite (@Memory.remove_o mem_src'); eauto. des_ifs.\n          { ss. des; subst. rewrite MEMTGT. econs; eauto.\n            { left. eapply sim_memory_wf; eauto. ss. eauto. }\n            { i. apply (sim_memory_wf MEM). ss. }\n            { i. ss. }\n          }\n          { apply MEM. }\n        }\n        { econs; [|apply SIM|].\n          { i. erewrite (@Memory.add_o prom_src''); eauto.\n            erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n            { ss. des; subst. left. rewrite PROMTGT. econs; eauto. }\n            { guardH o. set (PROM:=(sim_promise_list_contents SIM) loc0 ts0).\n              des; auto. right. splits; eauto. ss. des; auto.\n              clarify. unguard. des; ss. }\n          }\n          { i. set (PROM:=(sim_promise_list_extra SIM) loc0 ts0 SELF).\n            des. exists to.\n            erewrite Memory.add_o; eauto. erewrite Memory.remove_o; eauto. des_ifs.\n            ss. des; subst. clarify. }\n        }\n      }\n\n      { hexploit (@Memory.add_exists mem_src' loc from_tgt ts Message.reserve).\n        { ii. erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o.\n          hexploit sim_memory_disjoint.\n          { eauto. }\n          { eauto. }\n          { eapply MEMTGT. }\n          { eapply GET2. }\n          { instantiate (1:=x). eauto. }\n          { eauto. }\n          i. destruct H0 as [EQ|[EQ [FORGET [EXTRA TS]]]].\n          { des; subst. destruct o; ss. }\n          { guardH FORGET. guardH EXTRA.\n            eapply H. esplits; eauto. }\n        }\n        { apply memory_get_ts_strong in MEMTGT. des; auto. subst.\n          erewrite BOTNONESRC in PROMSRC. clarify. }\n        { econs. }\n        intros [mem_src'' ADDMEM].\n        hexploit (@Memory.add_exists_le prom_src' mem_src'); eauto.\n        { eapply promise_memory_le; eauto. }\n        intros [prom_src'' ADDPROM].\n        assert (ADD: Memory.promise prom_src' mem_src' loc from_tgt ts Message.reserve prom_src'' mem_src'' Memory.op_kind_add).\n        { econs; eauto. i. clarify. }\n        right. exists prom_src'', mem_src''. splits; eauto.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { econs; [|apply MEM]. i.\n          erewrite (@Memory.add_o mem_src''); eauto.\n          erewrite (@Memory.remove_o mem_src'); eauto. des_ifs.\n          { ss. des; subst. rewrite MEMTGT. econs; eauto.\n            { refl. }\n            { i. apply eq_lb_time. }\n          }\n          { apply MEM. }\n        }\n        { econs; [|apply SIM|].\n          { i. erewrite (@Memory.add_o prom_src''); eauto.\n            erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n            { ss. des; subst. left. rewrite PROMTGT. eauto. }\n            { guardH o. set (PROM:=(sim_promise_list_contents SIM) loc0 ts0).\n              des; auto. right. splits; eauto. ss. des; auto.\n              clarify. unguard. des; ss. }\n          }\n          { i. set (PROM:=(sim_promise_list_extra SIM) loc0 ts0 SELF).\n            des. exists to.\n            erewrite Memory.add_o; eauto. erewrite Memory.remove_o; eauto. des_ifs.\n            ss. des; subst. clarify. }\n        }\n      }\n    }\n\n    { clear LIN. symmetry in H. symmetry in H0.\n      rename H into PROMTGT. rename H0 into PROMSRC.\n      dup PROMSRC. dup PROMTGT. apply MLESRC in PROMSRC0. apply MLETGT in PROMTGT0.\n      rename PROMSRC0 into MEMSRC. rename PROMTGT0 into MEMTGT.\n      set (MEM0:=(sim_memory_contents MEM) loc ts).\n      rewrite MEMSRC in MEM0. rewrite MEMTGT in MEM0. inv MEM0; ss. guardH PROM0.\n      destruct (classic (self loc from_src)) as [SELF|NSELF].\n      { left. exploit sim_memory_from_forget; eauto. ss. right. auto. }\n\n      hexploit (@Memory.remove_exists prom_src); eauto.\n      intros [prom_src' REMOVEPROM].\n      hexploit (@Memory.remove_exists_le prom_src mem_src); eauto.\n      intros [mem_src' REMOVEMEM].\n      assert (REMOVE: Memory.promise prom_src mem_src loc from_src ts Message.reserve prom_src' mem_src' Memory.op_kind_cancel).\n      { econs; eauto. }\n      destruct (classic (exists from_src', (extra_others \\\\3// extra_self) loc from_src' from_tgt))\n        as [[from_src' EXTRA]|].\n      { guardH EXTRA.\n        hexploit (@Memory.add_exists mem_src' loc from_src' ts Message.reserve).\n        { ii. erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o.\n          hexploit sim_memory_disjoint.\n          { eauto. }\n          { eauto. }\n          { eapply MEMTGT. }\n          { eapply GET2. }\n          { instantiate (1:=x). inv LHS. econs; ss.\n            transitivity from_src'; auto.\n            eapply (sim_memory_wf MEM) in EXTRA. des; auto. }\n          { eauto. }\n          i. destruct H as [EQ|[EQ [FORGET [EXTRA0 TS]]]].\n          { des; subst. destruct o; ss. }\n          { guardH FORGET. guardH EXTRA0.\n            hexploit sim_memory_extra_inj.\n            { eapply MEM. }\n            { eapply EXTRA0. }\n            { eapply EXTRA. }\n            i. subst. inv LHS. inv RHS. ss. timetac. }\n        }\n        { eapply (sim_memory_wf MEM) in EXTRA. destruct EXTRA as [_ EXTRA]. des.\n          eapply LB0.\n          { eapply MEMWF in MEMTGT. des; auto. }\n          { apply memory_get_ts_strong in MEMTGT. des; auto.\n            subst. erewrite BOTNONESRC in PROMSRC. clarify. }\n        }\n        { econs; eauto. }\n        intros [mem_src'' ADDMEM].\n        hexploit (@Memory.add_exists_le prom_src' mem_src'); eauto.\n        { eapply promise_memory_le; eauto. }\n        intros [prom_src'' ADDPROM].\n        assert (ADD: Memory.promise prom_src' mem_src' loc from_src' ts Message.reserve prom_src'' mem_src'' Memory.op_kind_add).\n        { econs; eauto. i. clarify. }\n        right. exists prom_src'', mem_src''. splits; eauto.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { econs; [|apply MEM]. i.\n          erewrite (@Memory.add_o mem_src''); eauto.\n          erewrite (@Memory.remove_o mem_src'); eauto. des_ifs.\n          { ss. des; subst. rewrite MEMTGT.\n            econs; eauto.\n            { left. eapply sim_memory_wf; eauto. ss. eauto. }\n            { i. apply (sim_memory_wf MEM). ss. }\n          }\n          { apply MEM. }\n        }\n        { econs; [|apply SIM|].\n          { i. erewrite (@Memory.add_o prom_src''); eauto.\n            erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n            { ss. des; subst. left. rewrite PROMTGT. econs; eauto. }\n            { guardH o. set (PROM1:=(sim_promise_list_contents SIM) loc0 ts0).\n              des; auto. right. splits; eauto. ss. des; auto.\n              clarify. unguard. des; ss. }\n          }\n          { i. set (PROM1:=(sim_promise_list_extra SIM) loc0 ts0 SELF).\n            des. exists to.\n            erewrite Memory.add_o; eauto. erewrite Memory.remove_o; eauto. des_ifs.\n            ss. des; subst. clarify. }\n        }\n      }\n\n      { hexploit (@Memory.add_exists mem_src' loc from_tgt ts Message.reserve).\n        { ii. erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o.\n          hexploit sim_memory_disjoint.\n          { eauto. }\n          { eauto. }\n          { eapply MEMTGT. }\n          { eapply GET2. }\n          { instantiate (1:=x). eauto. }\n          { eauto. }\n          i. destruct H0 as [EQ|[EQ [FORGET [EXTRA TS]]]].\n          { des; subst. destruct o; ss. }\n          { guardH FORGET. guardH EXTRA.\n            eapply H. esplits; eauto. }\n        }\n        { apply memory_get_ts_strong in MEMTGT. des; auto. subst.\n          erewrite BOTNONESRC in PROMSRC. clarify. }\n        { econs. }\n        intros [mem_src'' ADDMEM].\n        hexploit (@Memory.add_exists_le prom_src' mem_src'); eauto.\n        { eapply promise_memory_le; eauto. }\n        intros [prom_src'' ADDPROM].\n        assert (ADD: Memory.promise prom_src' mem_src' loc from_tgt ts Message.reserve prom_src'' mem_src'' Memory.op_kind_add).\n        { econs; eauto. i. clarify. }\n        right. exists prom_src'', mem_src''. splits; eauto.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { econs; [|apply MEM]. i.\n          erewrite (@Memory.add_o mem_src''); eauto.\n          erewrite (@Memory.remove_o mem_src'); eauto. des_ifs.\n          { ss. des; subst. rewrite MEMTGT.\n            econs; eauto.\n            { refl. }\n            { apply eq_lb_time. }\n          }\n          { apply MEM. }\n        }\n        { econs; [|apply SIM|].\n          { i. erewrite (@Memory.add_o prom_src''); eauto.\n            erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n            { ss. des; subst. left. rewrite PROMTGT. eauto. }\n            { guardH o. set (PROM1:=(sim_promise_list_contents SIM) loc0 ts0).\n              des; auto. right. splits; eauto. ss. des; auto.\n              clarify. unguard. des; ss. }\n          }\n          { i. set (PROM1:=(sim_promise_list_extra SIM) loc0 ts0 SELF).\n            des. exists to.\n            erewrite Memory.add_o; eauto. erewrite Memory.remove_o; eauto. des_ifs.\n            ss. des; subst. clarify. }\n        }\n      }\n    }\n    { left. econs 5; eauto. }\n  Qed.\n\n\n\n  (* sim local *)\n\n  Inductive sim_local\n            (self: Loc.t -> Time.t -> Prop)\n            (extra: Loc.t -> Time.t -> Time.t -> Prop)\n    :\n      forall (lc_src lc_tgt: Local.t), Prop :=\n  | sim_local_intro\n      tvw prom_src prom_tgt\n      (PROMS: sim_promise self extra prom_src prom_tgt)\n    :\n      sim_local self extra (Local.mk tvw prom_src) (Local.mk tvw prom_tgt)\n  .\n  Hint Constructors sim_local.\n\n  Lemma sim_local_tview_le self extra lc_src lc_tgt\n        (LOCAL: sim_local self extra lc_src lc_tgt)\n    :\n      TView.le (Local.tview lc_src) (Local.tview lc_tgt).\n  Proof.\n    inv LOCAL. ss. refl.\n  Qed.\n\n  Inductive sim_statelocal\n            (self: Loc.t -> Time.t -> Prop)\n            (extra: Loc.t -> Time.t -> Time.t -> Prop)\n    :\n      sigT (@Language.state ProgramEvent.t) * Local.t -> sigT (@Language.state ProgramEvent.t) * Local.t -> Prop :=\n  | forget_statelocal_intro\n      st lc_src lc_tgt\n      (LOCAL: sim_local self extra lc_src lc_tgt)\n    :\n      sim_statelocal self extra (st, lc_src) (st, lc_tgt)\n  .\n\n\n  Lemma sim_read_step self others extra_self extra_others lc_src lc_tgt mem_src mem_tgt loc to val released ord\n        lc_tgt'\n        (STEPTGT: Local.read_step lc_tgt mem_tgt loc to val released ord lc_tgt')\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\3/ extra_self) mem_src mem_tgt)\n        (LOCAL: sim_local self extra_self lc_src lc_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n        (NOREAD: ~ others loc to)\n    :\n      exists lc_src',\n        (<<STEPSRC: Local.read_step lc_src mem_src loc to val released ord lc_src'>>) /\\\n        (<<SIM: sim_local self extra_self lc_src' lc_tgt'>>) /\\\n        (<<GETSRC: exists from, Memory.get loc to mem_src = Some (from, Message.concrete val released)>>) /\\\n        (<<GETTGT: exists from, Memory.get loc to mem_tgt = Some (from, Message.concrete val released)>>) /\\\n        (<<RELEASEDMSRC: Memory.closed_opt_view released mem_src>>) /\\\n        (<<RELEASEDMTGT: Memory.closed_opt_view released mem_tgt>>) /\\\n        (<<RELEASEDMWF: View.opt_wf released>>)\n        /\\\n        (<<NOREAD: ~ (others \\\\2// self) loc to>>)\n  .\n  Proof.\n    inv LOCAL. inv STEPTGT.\n    set (MEM0:= (sim_memory_contents MEM) loc to). rewrite GET in *. inv MEM0; ss.\n    { inv MEMSRC. hexploit CLOSED.\n      { symmetry. eapply H0. } i. des. inv MSG_CLOSED. inv MSG_WF.\n      inv MEMTGT. hexploit CLOSED1.\n      { eapply GET. } i. des. inv MSG_CLOSED. inv MSG_WF.\n      esplits; eauto. }\n    { exfalso. destruct PROM; auto.\n      set (PROM:= (sim_promise_contents PROMS) loc to). inv PROM; ss.\n      symmetry in H3. eapply CONSISTENT in H3. ss.\n      eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt; [apply H3|].\n      unfold TimeMap.join, View.singleton_ur_if, View.singleton_ur, View.singleton_rw, TimeMap.singleton.\n      etrans; [|eapply Time.join_l]. etrans; [|eapply Time.join_r].\n      des_ifs; ss; setoid_rewrite LocFun.add_spec_eq; refl.\n    }\n  Qed.\n\n  Lemma sim_fence_step self extra lc_src lc_tgt sc ordr ordw\n        sc' lc_tgt'\n        (STEPTGT: Local.fence_step lc_tgt sc ordr ordw lc_tgt' sc')\n        (LOCAL: sim_local self extra lc_src lc_tgt)\n    :\n      exists lc_src',\n        (<<STEPSRC: Local.fence_step lc_src sc ordr ordw lc_src' sc'>>) /\\\n        (<<SIM: sim_local self extra lc_src' lc_tgt'>>)\n  .\n  Proof.\n    inv LOCAL. inv STEPTGT. esplits.\n    - econs; ss; eauto.\n      + ii.\n        set (PROM:= (sim_promise_contents PROMS) loc t).\n        rewrite GET in *. inv PROM; ss.\n        exploit RELEASE; eauto.\n      + i. eapply sim_promise_bot; eauto.\n    - econs; ss; eauto.\n  Qed.\n\n  Lemma sim_promise_consistent self extra lc_src lc_tgt\n        (CONSISTENT: Local.promise_consistent lc_tgt)\n        (SIM: sim_local self extra lc_src lc_tgt)\n    :\n      Local.promise_consistent lc_src.\n  Proof.\n    inv SIM. ii. ss.\n    set (PROM:= (sim_promise_contents PROMS) loc ts).\n    rewrite PROMISE in *. inv PROM. eauto.\n  Qed.\n\n  Lemma sim_failure_step self extra lc_src lc_tgt\n        (STEPTGT: Local.failure_step lc_tgt)\n        (SIM: sim_local self extra lc_src lc_tgt)\n    :\n      Local.failure_step lc_src.\n  Proof.\n    inv STEPTGT. econs.\n    eapply sim_promise_consistent; eauto.\n  Qed.\n\n  Lemma sim_promise_normal others self extra_others extra_self\n        mem_src mem_tgt prom_src prom_tgt\n        loc from to msg prom_tgt' mem_tgt' kind\n        (NLOC: ~ L loc)\n        (STEPTGT: Memory.promise prom_tgt mem_tgt loc from to msg prom_tgt' mem_tgt' kind)\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (WFSRC: Memory.le prom_src mem_src)\n        (WFTGT: Memory.le prom_tgt mem_tgt)\n        (PROMISE: sim_promise self extra_self prom_src prom_tgt)\n        (SEMI: semi_closed_message msg mem_src loc to)\n    :\n      exists prom_src' mem_src',\n        (<<STEPSRC: Memory.promise prom_src mem_src loc from to msg prom_src' mem_src' kind>>) /\\\n        (<<MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src' mem_tgt'>>) /\\\n        (<<PROMISE: sim_promise self extra_self prom_src' prom_tgt'>>) /\\\n        (<<CLOSED: Memory.closed_message msg mem_src'>>)\n  .\n  Proof.\n    generalize (sim_memory_others_self_wf MEM). intros PROMSWF.\n    generalize (sim_memory_extra_others_self_wf MEM). intros EXTRAWF.\n    inv STEPTGT.\n\n    (* add case *)\n    - exploit add_succeed_wf; try apply MEM0. i. des.\n      hexploit (@Memory.add_exists mem_src loc from to msg); ss.\n      { i. set (MEM1:= (sim_memory_contents MEM) loc to2).\n        rewrite GET2 in *. inv MEM1; cycle 1.\n        { exfalso. apply NLOC. des; eauto. }\n        { exfalso. apply NLOC. des; eauto. }\n        ii. eapply DISJOINT; eauto.\n        inv RHS. econs; ss. eapply TimeFacts.le_lt_lt; eauto. }\n      intros [mem_src' ADDMEMSRC].\n      exploit Memory.add_exists_le; try apply ADDMEMSRC; eauto.\n      intros [prom_src' ADDPROMSRC].\n\n      assert (PROMISESRC: Memory.promise prom_src mem_src loc from to msg prom_src' mem_src' Memory.op_kind_add).\n      { econs; eauto. i. subst.\n        set (MEM1:= (sim_memory_contents MEM) loc to'). rewrite GET in MEM1. inv MEM1; ss.\n        eapply ATTACH; eauto. erewrite NLOC0; eauto. }\n\n      assert (CLOSEDMSG: Memory.closed_message msg mem_src').\n      { destruct msg; auto.\n        eapply semi_closed_message_add; eauto. }\n\n      exists prom_src', mem_src'. splits; auto.\n      + econs.\n        { ii. set (MEM1:= (sim_memory_contents MEM) loc0 ts).\n          erewrite (@Memory.add_o mem_src'); eauto.\n          erewrite (@Memory.add_o mem_tgt'); eauto.\n          des_ifs; try by (ss; des; clarify).\n          * econs; eauto.\n            { ii. ss. des; clarify; eauto. }\n            { ii. ss. des; clarify; eauto. }\n            { refl. }\n            { i. ss. }\n        }\n        { eapply (sim_memory_wf MEM); eauto. }\n      + econs.\n        { ii. set (PROM:= (sim_promise_contents PROMISE) loc0 ts).\n          erewrite (@Memory.add_o prom_src'); eauto.\n          erewrite (@Memory.add_o prom_tgt'); eauto. des_ifs.\n          ss. des; clarify. econs; eauto.\n          { ii. eapply NLOC. eapply PROMSWF; ss. right. eauto. }\n          { ii. eapply NLOC. eapply EXTRAWF; ss. right. eauto. }\n        }\n        { apply PROMISE. }\n        { i. hexploit (sim_promise_extra PROMISE); eauto. i. des.\n          esplits; eauto. erewrite (@Memory.add_o prom_src'); eauto.\n          des_ifs. ss. des; clarify.\n          exfalso. eapply NLOC. eapply PROMSWF; eauto. right. eauto. }\n\n    (* split case *)\n    - exploit split_succeed_wf; try apply PROMISES. i. des. clarify.\n      set (PROMISE0:= (sim_promise_contents PROMISE) loc ts3). rewrite GET2 in *.\n      inv PROMISE0; ss.\n      hexploit (@Memory.split_exists prom_src loc from to ts3 (Message.concrete val'0 released'0)); ss.\n      { eauto. }\n      intros [prom_src' SPLITPROMSRC].\n      exploit Memory.split_exists_le; try apply SPLITPROMSRC; eauto.\n      intros [mem_src' SPLITMEMSRC].\n\n      assert (PROMISESRC: Memory.promise prom_src mem_src loc from to (Message.concrete val'0 released'0) prom_src' mem_src' (Memory.op_kind_split ts3 (Message.concrete val' released'))).\n      { econs; eauto. }\n\n      assert (CLOSEDMSG: Memory.closed_message (Message.concrete val'0 released'0) mem_src').\n      { eapply semi_closed_message_split; eauto. }\n\n      exists prom_src', mem_src'. splits; auto.\n      + econs.\n        { ii. set (MEM1:=(sim_memory_contents MEM) loc0 ts).\n          erewrite (@Memory.split_o mem_src'); eauto.\n          erewrite (@Memory.split_o mem_tgt'); eauto.\n          des_ifs; try by (ss; des; clarify).\n          { ss. des; clarify. econs; eauto.\n            * refl.\n            * i. ss. }\n          { guardH o. ss. des; clarify. econs; eauto.\n            * refl.\n            * i. ss. }\n        }\n        { apply (sim_memory_wf MEM); eauto. }\n      + econs.\n        { ii. set (PROM:= (sim_promise_contents PROMISE) loc0 ts).\n          erewrite (@Memory.split_o prom_src'); eauto.\n          erewrite (@Memory.split_o prom_tgt'); eauto. des_ifs.\n          * ss. des; clarify. econs; eauto.\n            { ii. eapply NLOC. eapply PROMSWF. right. eauto. }\n            { ii. eapply NLOC. eapply EXTRAWF. right. eauto. }\n          * guardH o. ss. des; clarify. econs; eauto. }\n        { apply PROMISE. }\n        { i. hexploit (sim_promise_extra PROMISE); eauto. i. des.\n          esplits; eauto. erewrite (@Memory.split_o prom_src'); eauto. des_ifs.\n          - ss. des; clarify. exfalso. eapply NLOC. eapply PROMSWF; eauto. right. eauto.\n          - ss. des; clarify. }\n\n    (* lower case *)\n    - exploit lower_succeed_wf; try apply PROMISES. i. des. clarify.\n      set (PROMISE0:= (sim_promise_contents PROMISE) loc to). rewrite GET in *. inv PROMISE0; ss.\n\n      hexploit (@Memory.lower_exists prom_src loc from to (Message.concrete val released) msg); ss.\n\n      intros [prom_src' LOWERPROMSRC].\n      exploit Memory.lower_exists_le; try apply LOWERPROMSRC; eauto.\n      intros [mem_src' LOWERMEMSRC].\n\n      assert (PROMISESRC: Memory.promise prom_src mem_src loc from to msg prom_src' mem_src' (Memory.op_kind_lower (Message.concrete val released))).\n      { econs; eauto. }\n\n      assert (CLOSEDMSG: Memory.closed_message msg mem_src').\n      { destruct msg; auto.\n        eapply semi_closed_message_lower; eauto. }\n\n      exists prom_src', mem_src'. splits; auto.\n      + econs.\n        { ii. set (MEM1:=(sim_memory_contents MEM) loc0 ts).\n          erewrite (@Memory.lower_o mem_src'); eauto.\n          erewrite (@Memory.lower_o mem_tgt'); eauto. des_ifs.\n          ss. des; clarify. econs; eauto.\n          * refl.\n          * i. ss. }\n        { apply (sim_memory_wf MEM); eauto. }\n      + econs.\n        { ii. set (PROM:= (sim_promise_contents PROMISE) loc0 ts).\n          erewrite (@Memory.lower_o prom_src'); eauto.\n          erewrite (@Memory.lower_o prom_tgt'); eauto. des_ifs.\n          ss. des; clarify. econs; eauto. }\n        { apply PROMISE. }\n        { i. hexploit (sim_promise_extra PROMISE); eauto. i. des.\n          esplits; eauto. erewrite (@Memory.lower_o prom_src'); eauto. des_ifs.\n          ss. des; clarify. }\n\n    (* cancel case *)\n    - exploit Memory.remove_get0; try apply PROMISES. i. des.\n      set (PROMISE0 := (sim_promise_contents PROMISE) loc to). rewrite GET in *.\n      inv PROMISE0; ss.\n\n      hexploit (@Memory.remove_exists prom_src loc from to Message.reserve); ss.\n      intros [prom_src' REMOVEPROMSRC].\n      exploit Memory.remove_exists_le; try apply REMOVEPROMSRC; eauto.\n      intros [mem_src' REMOVEMEMSRC].\n\n      assert (PROMISESRC: Memory.promise prom_src mem_src loc from to Message.reserve prom_src' mem_src' Memory.op_kind_cancel).\n      { econs; eauto. }\n\n      exists prom_src', mem_src'.\n      splits; auto.\n      + econs.\n        { ii. set (MEM1:=(sim_memory_contents MEM) loc0 ts).\n          erewrite (@Memory.remove_o mem_src'); eauto.\n          erewrite (@Memory.remove_o mem_tgt'); eauto.\n          des_ifs; try by (des; ss; clarify).\n          * ss. des; clarify. econs; eauto. }\n        { apply MEM. }\n      + econs.\n        { ii. set (PROM:= (sim_promise_contents PROMISE) loc0 ts).\n          erewrite (@Memory.remove_o prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_tgt'); eauto. des_ifs.\n          ss. des; clarify. econs 2; eauto. }\n        { apply PROMISE. }\n        { i. hexploit (sim_promise_extra PROMISE); eauto. i. des.\n          esplits; eauto. erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n          ss. des; clarify. exfalso. eapply NLOC. eapply PROMSWF; eauto. right. eauto. }\n  Qed.\n\n  Lemma sim_write_step_normal\n        others self extra_others extra_self lc_src lc_tgt sc mem_src mem_tgt\n        lc_tgt' sc' mem_tgt' loc from to val ord releasedm released kind\n        (NLOC: ~ L loc)\n        (STEPTGT: Local.write_step lc_tgt sc mem_tgt loc from to val releasedm released ord lc_tgt' sc' mem_tgt' kind)\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LOCALSRC: Local.wf lc_src mem_src)\n        (LOCALTGT: Local.wf lc_tgt mem_tgt)\n        (SIM: sim_local self extra_self lc_src lc_tgt)\n\n        (RELEASEDMCLOSED: Memory.closed_opt_view releasedm mem_src)\n        (RELEASEDMWF: View.opt_wf releasedm)\n    :\n      exists lc_src' mem_src',\n        (<<STEPSRC: Local.write_step lc_src sc mem_src loc from to val releasedm released ord lc_src' sc' mem_src' kind>>) /\\\n        (<<MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src' mem_tgt'>>) /\\\n        (<<SIM: sim_local self extra_self lc_src' lc_tgt'>>)\n  .\n  Proof.\n    inv STEPTGT. inv WRITE. inv SIM. inv LOCALSRC. inv LOCALTGT.\n\n    hexploit sim_promise_normal; eauto.\n    { ss. econs. unfold TView.write_released. des_ifs; econs.\n      eapply semi_closed_view_join.\n      - inv MEMSRC. eapply unwrap_closed_opt_view; auto.\n        eapply closed_opt_view_semi_closed. auto.\n      - ss. setoid_rewrite LocFun.add_spec_eq. des_ifs.\n        + eapply semi_closed_view_join.\n          * eapply closed_view_semi_closed. inv TVIEW_CLOSED. auto.\n          * inv MEMSRC. eapply semi_closed_view_singleton. auto.\n        + eapply semi_closed_view_join.\n          * eapply closed_view_semi_closed. inv TVIEW_CLOSED. auto.\n          * inv MEMSRC. eapply semi_closed_view_singleton. auto.\n    }\n    i. des. ss.\n\n    hexploit (@Memory.remove_exists\n                prom_src' loc from to\n                (Message.concrete val (TView.write_released tvw sc loc to releasedm ord))).\n    { set (PROM:= (sim_promise_contents PROMISE0) loc to).\n      eapply Memory.remove_get0 in REMOVE. des.\n      rewrite GET in *. inv PROM; ss. }\n    intros [prom_src'' REMOVESRC].\n\n    assert (NSELF: forall ts, ~ self loc ts).\n    { ii. set (PROM:= (sim_promise_contents PROMISE0) loc to). inv PROM; ss.\n      eapply NLOC. eapply sim_memory_others_self_wf; eauto. ss. right. eauto. }\n\n    esplits; eauto.\n\n    - econs; ss.\n      + econs; eauto.\n      + ii. set (PROM:=(sim_promise_contents PROMS) loc t).\n        rewrite GET in *. inv PROM; ss.\n        exploit RELEASE; eauto.\n\n    - econs; auto. econs.\n      { ii. set (PROM:=(sim_promise_contents PROMISE0) loc0 ts).\n        erewrite (@Memory.remove_o prom_src''); eauto.\n        erewrite (@Memory.remove_o promises2); eauto. des_ifs.\n        ss. des; subst. econs 2; eauto.\n        ii. exploit sim_memory_extra_others_self_wf.\n        { eapply MEM0. }\n        { right. eauto. }\n        { ii. ss. }\n      }\n      { apply PROMISE0. }\n      { i. set (PROM:=(sim_promise_extra PROMISE0) loc0 ts SELF). des.\n        esplits; eauto. erewrite (@Memory.remove_o prom_src''); eauto.\n        des_ifs. ss. des; clarify. exfalso. eapply NSELF; eauto. }\n  Qed.\n\n  Lemma sim_promise_step_normal others self extra_others extra_self\n        mem_src mem_tgt mem_tgt' lc_src lc_tgt lc_tgt' loc from to msg kind\n        (NLOC: ~ L loc)\n        (STEPTGT: Local.promise_step lc_tgt mem_tgt loc from to msg lc_tgt' mem_tgt' kind)\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (LOCAL: sim_local self extra_self lc_src lc_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LCSRC: Local.wf lc_src mem_src)\n        (LCTGT: Local.wf lc_tgt mem_tgt)\n        (SEMI: semi_closed_message msg mem_src loc to)\n    :\n      exists lc_src' mem_src',\n        (<<STEPSRC: Local.promise_step lc_src mem_src loc from to msg lc_src' mem_src' kind>>) /\\\n        (<<MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src' mem_tgt'>>) /\\\n        (<<LOCAL: sim_local self extra_self lc_src' lc_tgt'>>)\n  .\n  Proof.\n    inv LOCAL. inv LCSRC. inv LCTGT. inv STEPTGT. ss.\n    hexploit sim_promise_normal; eauto. i. des.\n    exists (Local.mk tvw prom_src'), mem_src'. splits; eauto.\n  Qed.\n\n  Lemma sim_promise_forget others (self: Loc.t -> Time.t -> Prop) extra_others extra_self\n        mem_src mem_tgt prom_src prom_tgt\n        loc from to msg_tgt prom_tgt' mem_tgt' kind_tgt\n        (LOC: L loc)\n        (STEPTGT: Memory.promise prom_tgt mem_tgt loc from to msg_tgt prom_tgt' mem_tgt' kind_tgt)\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (MLESRC: Memory.le prom_src mem_src)\n        (MLETGT: Memory.le prom_tgt mem_tgt)\n        (PROMISE: sim_promise self extra_self prom_src prom_tgt)\n        (MEMWF: memory_times_wf times mem_tgt')\n        (SEMI: semi_closed_message msg_tgt mem_src loc to)\n    :\n      (exists prom_src' mem_src' self' extra_self',\n          (<<STEPSRC: reserve_future_memory prom_src mem_src prom_src' mem_src'>>) /\\\n          (<<MEM: sim_memory L times (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src' mem_tgt'>>) /\\\n          (<<PROMISE: sim_promise self' extra_self' prom_src' prom_tgt'>>) /\\\n          (<<SELF: __guard__(self' loc to \\/ msg_tgt = Message.reserve)>>)) \\/\n      (exists prom_src' mem_src',\n          (<<STEPSRC: Memory.promise prom_src mem_src loc from to msg_tgt prom_src' mem_src' kind_tgt>>) /\\\n          (<<MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src' mem_tgt'>>) /\\\n          (<<PROMISE: sim_promise self extra_self prom_src' prom_tgt'>>) /\\\n          (<<CLOSED: Memory.closed_message msg_tgt mem_src'>>) /\\\n          (<<SELF: ~ self loc to>>))\n  .\n  Proof.\n    inv STEPTGT.\n\n    - left. exploit add_succeed_wf; try apply MEM0. i. des.\n      assert (exists from_src,\n                 (<<FROM: Time.le from from_src>>) /\\\n                 (<<TO: Time.lt from_src to>>) /\\\n                 (<<LB: lb_time (times loc) from from_src>>) /\\\n                 (<<EMPTY: forall to2 from2 msg2\n                                  (GET: Memory.get loc to2 mem_src = Some (from2, msg2)),\n                     Interval.disjoint (from_src, to) (from2, to2)>>)).\n      { destruct (classic (exists from_src,\n                              (extra_others \\\\3// extra_self) loc from_src from)).\n        { des. hexploit ((sim_memory_wf MEM) loc from from_src); eauto. i. des.\n          exists from_src. splits; eauto.\n          { left. eauto. }\n          { eapply Memory.add_get0 in MEM0. des.\n            eapply MEMWF in GET0. des.\n            eapply LB in TO. auto. }\n          i. hexploit sim_memory_get_larger; eauto. i. des.\n          { ii. eapply DISJOINT; eauto.\n            { instantiate (1:=x). inv LHS. econs; ss.\n              transitivity from_src; eauto. }\n            { inv RHS. econs; ss. eapply TimeFacts.le_lt_lt; eauto. }\n          }\n          { hexploit ((sim_memory_wf MEM) loc from2 to2); eauto. i. des.\n            ii. inv LHS. inv RHS. ss.\n            set (MEM1:=(sim_memory_contents MEM) loc from_src).\n            inv MEM1; try by (exfalso; eapply NEXTRA; eauto); ss.\n            set (MEM2:=(sim_memory_contents MEM) loc to2).\n            inv MEM2; try by (exfalso; eapply NEXTRA; eauto); ss.\n            symmetry in H1. symmetry in H3. hexploit memory_get_disjoint_strong.\n            { eapply H3. }\n            { eapply H1. }\n            i. des; clarify.\n            { timetac. }\n            { eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n              { eapply TS3. } etrans.\n              { left. eapply FROM. }\n              { eauto. }\n            }\n            { set (MEM3:=(sim_memory_contents MEM) loc from2). inv MEM3; ss.\n              symmetry in H6. eapply DISJOINT.\n              { eapply H6. }\n              { instantiate (1:=from2). econs; ss.\n                { eapply TimeFacts.lt_le_lt; eauto. }\n                { transitivity x; auto. left. auto. }\n              }\n              { econs; ss.\n                { apply memory_get_ts_strong in H6. des; auto.\n                  subst. inv MEMSRC. rewrite INHABITED in H5. clarify. }\n                { refl. }\n              }\n            }\n          }\n        }\n        { exists from. splits; auto.\n          { refl. }\n          { apply eq_lb_time. }\n          { i. hexploit sim_memory_get_larger; eauto. i. des.\n            { ii. eapply DISJOINT; eauto.\n              inv RHS. econs; ss. eapply TimeFacts.le_lt_lt; eauto. }\n            { hexploit ((sim_memory_wf MEM) loc from2 to2); eauto. i. des.\n              ii. inv LHS. inv RHS. ss.\n              set (MEM1:=(sim_memory_contents MEM) loc from2).\n              inv MEM1; try by (exfalso; eapply NPROM; eauto); ss.\n              symmetry in H2. hexploit memory_get_disjoint_strong.\n              { eapply Memory.add_get0. eapply MEM0. }\n              { eapply Memory.add_get1; eauto. }\n              i. des; subst.\n              { eapply Memory.add_get0 in MEM0. des. clarify. }\n              { eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n                { eapply TS2. } etrans.\n                { left. eapply FROM0. }\n                { eauto. }\n              }\n              { destruct TS1; cycle 1.\n                { inv H0. eapply H. eauto. }\n                { exploit LB.\n                  { instantiate (1:=from).\n                    eapply Memory.add_get0 in MEM0. des.\n                    eapply MEMWF in GET1. des. auto. }\n                  { auto. }\n                  { i. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n                    { eapply FROM. } etrans.\n                    { eapply TO0. }\n                    { left. auto. }\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n\n      des. hexploit (@Memory.add_exists mem_src loc from_src to Message.reserve); eauto.\n      { econs. }\n      intros [mem_src0 ADDMEM0].\n      hexploit (@Memory.add_exists_le prom_src mem_src loc from_src to Message.reserve); eauto.\n      intros [prom_src0 ADDPROM0].\n      assert (PROMISE0: Memory.promise prom_src mem_src loc from_src to Message.reserve prom_src0 mem_src0 Memory.op_kind_add).\n      { econs; eauto. i. clarify. }\n\n      assert (GETMEMNONE: Memory.get loc to mem_src = None).\n      { eapply Memory.add_get0; eauto. }\n      assert (GETPROMNONE: Memory.get loc to prom_src = None).\n      { destruct (Memory.get loc to prom_src) eqn:EQ; auto.\n        destruct p. apply MLESRC in EQ. clarify. }\n      hexploit sim_memory_src_none.\n      { eauto. }\n      { eapply GETMEMNONE. } i. des.\n      hexploit sim_promise_src_none.\n      { eauto. }\n      { eapply GETPROMNONE. } i. des.\n\n      destruct msg_tgt as [val released|].\n      { hexploit (@lb_time_exists (times loc) (@WO loc) to). i. des.\n        hexploit (@Memory.add_exists mem_src0 loc to ts' Message.reserve); eauto.\n        { i. erewrite Memory.add_o in GET2; eauto. des_ifs.\n          { ss. des; subst. ii. inv LHS. inv RHS. ss. timetac. }\n          des; ss. hexploit sim_memory_get_larger; eauto. i. des.\n          { ii. inv LHS. inv RHS. ss.\n            dup GETTGT1. eapply Memory.add_get1 in GETTGT1; eauto.\n            hexploit memory_get_disjoint_strong.\n            { eapply GETTGT1. }\n            { eapply Memory.add_get0; eauto. }\n            i. des; clarify.\n            { eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n              { eapply TS3. } etrans.\n              { left. eapply FROM0. }\n              { eauto. }\n            }\n            { destruct TS2.\n              { exploit LB0.\n                { instantiate (1:=from_tgt).\n                  eapply MEMWF in GETTGT1. des. auto. }\n                { auto. }\n                { i. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n                  { eapply x0. } etrans.\n                  { eapply TS1. } etrans.\n                  { left. eapply FROM1. }\n                  { eauto. }\n                }\n              }\n              { inv H. eapply ATTACH; eauto. }\n            }\n          }\n          { hexploit ((sim_memory_wf MEM) loc from2 to2); eauto. i. des.\n            set (MEM1:=(sim_memory_contents MEM) loc from2).\n            inv MEM1; ss.\n            symmetry in H. hexploit memory_get_disjoint_strong.\n            { eapply Memory.add_get1 in H; [|eauto]. eapply H. }\n            { eapply Memory.add_get0; eauto. }\n            i. des; clarify.\n            { ii. inv LHS. inv RHS. ss. exploit LB1.\n              { instantiate (1:=to).\n                apply Memory.add_get0 in MEM0. des.\n                apply MEMWF in GET0. des. auto. }\n              { auto. }\n              { i. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n                { eapply FROM1. } etrans.\n                { eapply TO2. }\n                { left. eauto. }\n              }\n            }\n            { eapply interval_le_disjoint.\n              left. eapply LB0; auto.\n              eapply Memory.add_get1 in H; eauto.\n              eapply MEMWF in H. des. auto. }\n          }\n        }\n        { econs. }\n        intros [mem_src1 ADDMEM1].\n        hexploit (@Memory.add_exists_le prom_src0 mem_src0 loc to ts' Message.reserve); eauto.\n        { eapply promise_memory_le; cycle 1; eauto. }\n        intros [prom_src1 ADDPROM1].\n        assert (PROMISE1: Memory.promise prom_src0 mem_src0 loc to ts' Message.reserve prom_src1 mem_src1 Memory.op_kind_add).\n        { econs; eauto. i. clarify. }\n\n        assert (GETMEMNONE0: Memory.get loc ts' mem_src = None).\n        { destruct (Memory.get loc ts' mem_src) eqn:EQ; auto.\n          destruct p. eapply Memory.add_get1 in EQ; eauto.\n          eapply Memory.add_get0 in ADDMEM1. des. clarify. }\n        assert (GETPROMNONE0: Memory.get loc ts' prom_src = None).\n        { destruct (Memory.get loc ts' prom_src) eqn:EQ; auto.\n          destruct p. eapply MLESRC in EQ. clarify. }\n        hexploit sim_memory_src_none.\n        { eauto. }\n        { eapply GETMEMNONE0. } i. des.\n        hexploit sim_promise_src_none.\n        { eauto. }\n        { eapply GETPROMNONE0. } i. des.\n\n        exists prom_src1, mem_src1,\n        (fun loc' ts' => if loc_ts_eq_dec (loc', ts') (loc, to)\n                         then True else self loc' ts'),\n        (fun l t => if (loc_ts_eq_dec (l, t) (loc, ts'))\n                    then (eq to)\n                    else extra_self l t). splits; eauto.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { econs.\n          { i. erewrite (@Memory.add_o mem_src1); eauto.\n            erewrite (@Memory.add_o mem_src0); eauto.\n            erewrite (@Memory.add_o mem_tgt'); eauto. des_ifs.\n            { ss. des; clarify. timetac. }\n            { ss. des; clarify. econs 3; eauto. right. auto. }\n            { ss. des; clarify. erewrite GETTGT1.\n              econs 4; eauto. right. auto. }\n            { eapply (sim_memory_contents MEM). }\n          }\n          { i. des_ifs; eauto.\n            { ss. des; clarify. splits; auto.\n              { right. auto. }\n              { i. destruct EXTRA0; auto.\n                exfalso. eapply NEXTRA1. left. eauto. }\n            }\n            { apply (sim_memory_wf MEM) in EXTRA. ss. des; clarify. }\n            { ss. des; clarify. destruct EXTRA as [EXTRA|EQ]; subst; ss.\n              hexploit ((sim_memory_wf MEM) loc from0 ts').\n              { left. auto. }\n              i. des. splits; auto.\n              i. destruct EXTRA0 as [EXTRA0|EQ].\n              { exfalso. eapply NEXTRA1. left. eauto. }\n              { subst. exfalso. eapply NEXTRA1. left. eauto. }\n            }\n            { eapply (sim_memory_wf MEM). auto. }\n          }\n        }\n        { econs.\n          { i. erewrite (@Memory.add_o prom_src1); eauto.\n            erewrite (@Memory.add_o prom_src0); eauto.\n            erewrite (@Memory.add_o prom_tgt'); eauto. des_ifs.\n            { ss. des; clarify. timetac. }\n            { ss. des; clarify. econs 4; eauto. }\n            { ss. des; clarify. erewrite GETTGT2. econs 5; eauto. }\n            { eapply (sim_promise_contents PROMISE). }\n          }\n          { i. des_ifs.\n            { ss. des; clarify. }\n            { ss. des; clarify.\n              hexploit ((sim_promise_wf PROMISE) loc to ts); auto.\n              i. des. splits; auto. }\n            { ss. des; clarify. }\n            { eapply (sim_promise_wf PROMISE); auto. }\n          }\n          { i. des_ifs.\n            { ss. des; clarify. exists ts'. splits; auto.\n              eapply Memory.add_get0; eauto. }\n            { guardH o. eapply (sim_promise_extra PROMISE) in SELF. des.\n              exists to0. splits; eauto.\n              eapply Memory.add_get1; eauto. eapply Memory.add_get1; eauto. }\n          }\n        }\n        { left. des_ifs. ss. des; clarify. }\n      }\n\n      exists prom_src0, mem_src0, self, extra_self. splits; eauto.\n      { econs; eauto. econs; eauto. }\n      { econs.\n        { i. erewrite (@Memory.add_o mem_src0); eauto.\n          erewrite (@Memory.add_o mem_tgt'); eauto. des_ifs.\n          { ss. des; clarify. econs 2; eauto. i. ss. }\n          { eapply (sim_memory_contents MEM). }\n        }\n        { eapply (sim_memory_wf MEM). }\n      }\n      { econs.\n        { i. erewrite (@Memory.add_o prom_src0); eauto.\n          erewrite (@Memory.add_o prom_tgt'); eauto. des_ifs.\n          { ss. des; clarify. econs 3; eauto. }\n          { eapply (sim_promise_contents PROMISE). }\n        }\n        { eapply (sim_promise_wf PROMISE). }\n        { i. eapply (sim_promise_extra PROMISE) in SELF. des.\n          exists to0. splits; eauto. eapply Memory.add_get1; eauto.  }\n      }\n      { right. auto. }\n\n    - des. subst.\n      exploit split_succeed_wf; try apply PROMISES. i. des.\n      dup GET2. apply MLETGT in GET0.\n      set (PROM:=(sim_promise_contents PROMISE) loc ts3).\n      rewrite GET2 in PROM.\n\n      set (MEM1:=(sim_memory_contents MEM) loc ts3). rewrite GET0 in MEM1.\n      destruct (classic (self loc ts3)) as [SELF|NSELF].\n      2: {\n        right. inv PROM; ss.\n        hexploit (@Memory.split_exists prom_src loc from to ts3 (Message.concrete val'0 released'0)); ss.\n        { eauto. }\n        intros [prom_src' SPLITPROMSRC].\n        exploit Memory.split_exists_le; try apply SPLITPROMSRC; eauto.\n        intros [mem_src' SPLITMEMSRC].\n\n        assert (PROMISESRC: Memory.promise prom_src mem_src loc from to (Message.concrete val'0 released'0) prom_src' mem_src' (Memory.op_kind_split ts3 (Message.concrete val' released'))).\n        { econs; eauto. }\n\n        assert (CLOSEDMSG: Memory.closed_message (Message.concrete val'0 released'0) mem_src').\n        { eapply semi_closed_message_split; eauto. }\n\n        assert (PROMSWF0: ~ (others loc to \\/ self loc to)).\n        { set (MEM2:=(sim_memory_contents MEM) loc to). inv MEM2; clarify.\n          eapply Memory.split_get0 in SPLITMEMSRC. des. rewrite GET in *. clarify. }\n\n        assert (EXTRAWF0: forall t : Time.t, ~ __guard__ (extra_others loc to t \\/ extra_self loc to t)).\n        { ii. set (MEM2:=(sim_memory_contents MEM) loc to). inv MEM2; clarify.\n          - eapply NEXTRA0; eauto.\n          - eapply NEXTRA0; eauto.\n          - eapply Memory.split_get0 in SPLITMEMSRC. des. rewrite GET in *. clarify. }\n\n        assert (PROMSWF1: ~ (others loc ts3 \\/ self loc ts3)).\n        { set (MEM2:=(sim_memory_contents MEM) loc ts3). inv MEM2; clarify.\n          eapply Memory.split_get0 in SPLITMEMSRC. des. rewrite GET1 in *. clarify. }\n\n        assert (EXTRAWF1: forall t : Time.t, ~ __guard__ (extra_others loc ts3 t \\/ extra_self loc ts3 t)).\n        { ii. set (MEM2:=(sim_memory_contents MEM) loc ts3). inv MEM2; clarify.\n          - eapply NEXTRA0; eauto.\n          - eapply NEXTRA0; eauto.\n          - eapply Memory.split_get0 in SPLITMEMSRC. des. rewrite GET1 in *. clarify. }\n\n        exists prom_src', mem_src'. splits; auto.\n        + econs.\n          { ii. set (MEM2:=(sim_memory_contents MEM) loc0 ts).\n            erewrite (@Memory.split_o mem_src'); eauto.\n            erewrite (@Memory.split_o mem_tgt'); eauto.\n            des_ifs; try by (ss; des; clarify).\n            { ss. des; clarify. econs; eauto.\n              * refl.\n              * i. ss. }\n            { guardH o. ss. des; clarify. econs; eauto.\n              * refl.\n              * i. ss. }\n          }\n          { apply (sim_memory_wf MEM); eauto. }\n        + econs.\n          { ii. set (PROM:= (sim_promise_contents PROMISE) loc0 ts).\n            erewrite (@Memory.split_o prom_src'); eauto.\n            erewrite (@Memory.split_o prom_tgt'); eauto. des_ifs.\n            * ss. des; clarify. econs; eauto.\n              ii. eapply EXTRAWF0; eauto. right. eauto.\n            * guardH o. ss. des; clarify. econs; eauto. }\n          { apply PROMISE. }\n          { i. hexploit (sim_promise_extra PROMISE); eauto. i. des.\n            esplits; eauto. erewrite (@Memory.split_o prom_src'); eauto. des_ifs.\n            - ss. des; clarify. exfalso.\n              eapply Memory.split_get0 in SPLITPROMSRC. des. clarify.\n            - ss. des; clarify. }\n      }\n\n      left.\n      assert (exists from_src,\n                 (<<GETSRC: Memory.get loc ts3 prom_src = Some (from_src, Message.reserve)>>) /\\\n                 (<<LB: lb_time (times loc) from from_src>>) /\\\n                 (<<FROM: Time.le from from_src>>)).\n      { inv PROM; ss.\n        { symmetry in H0. apply MLESRC in H0.\n          rewrite H0 in *. inv MEM1. esplits; eauto. }\n      } des.\n      assert (TS0: Time.lt from_src to).\n      { eapply LB; auto.\n        apply Memory.split_get0 in MEM0. des.\n        eapply MEMWF in GET4. des. auto. }\n\n      assert (NEXTRATO: forall t, ~ (extra_others loc to t \\/ extra_self loc to t)).\n      { set (MEM2:=(sim_memory_contents MEM) loc to).\n        inv MEM2; ss. guardH EXTRA. exfalso.\n        hexploit memory_get_disjoint_strong.\n        { symmetry. apply H0. }\n        { apply MLESRC. apply GETSRC. }\n        i. des; subst.\n        { timetac. }\n        { timetac. }\n        { eapply Time.lt_strorder. transitivity to; eauto. }\n      }\n\n      hexploit (@Memory.remove_exists prom_src loc from_src ts3 Message.reserve).\n      { eauto. }\n      intros [prom_src0 REMOVEPROM].\n      hexploit (@Memory.remove_exists_le prom_src mem_src loc from_src ts3 Message.reserve); eauto.\n      intros [mem_src0 REMOVEMEM].\n      assert (PROMISE0: Memory.promise prom_src mem_src loc from_src ts3 Message.reserve prom_src0 mem_src0 Memory.op_kind_cancel).\n      { econs; eauto. }\n\n      hexploit (@Memory.add_exists mem_src0 loc from_src to Message.reserve); auto.\n      { i. erewrite Memory.remove_o in GET1; eauto. des_ifs. guardH o.\n        hexploit Memory.get_disjoint.\n        { eapply GET1. }\n        { eapply MLESRC. eapply GETSRC. }\n        i. des; clarify.\n        { ss. destruct o; ss. }\n        { ii. eapply H; eauto. inv LHS. econs; ss.\n          etrans; eauto. left. auto. }\n      }\n      { econs. }\n      intros [mem_src1 ADDMEM1].\n      hexploit (@Memory.add_exists_le prom_src0 mem_src0 loc from_src to Message.reserve); eauto.\n      { eapply promise_memory_le; try apply PROMISE0; eauto. }\n      intros [prom_src1 ADDPROM1].\n      assert (PROMISE1: Memory.promise prom_src0 mem_src0 loc from_src to Message.reserve prom_src1 mem_src1 Memory.op_kind_add).\n      { econs; eauto. i. clarify. }\n      hexploit (@Memory.add_exists mem_src1 loc to ts3 Message.reserve); auto.\n      { i. erewrite Memory.add_o in GET1; eauto. des_ifs.\n        { ss. des; subst. ii. inv LHS. inv RHS. ss. timetac. }\n        { erewrite Memory.remove_o in GET1; eauto. des_ifs. guardH o.\n          hexploit Memory.get_disjoint.\n          { eapply GET1. }\n          { eapply MLESRC. eapply GETSRC. }\n          i. des; clarify.\n          ii. eapply H; eauto. inv LHS. econs; ss.\n          etrans; eauto. }\n      }\n      { econs. }\n      intros [mem_src2 ADDMEM2].\n      hexploit (@Memory.add_exists_le prom_src1 mem_src1 loc to ts3 Message.reserve); eauto.\n      { eapply promise_memory_le; try apply PROMISE1; eauto.\n        eapply promise_memory_le; try apply PROMISE0; eauto. }\n      intros [prom_src2 ADDPROM2].\n      assert (PROMISE2: Memory.promise prom_src1 mem_src1 loc to ts3 Message.reserve prom_src2 mem_src2 Memory.op_kind_add).\n      { econs; eauto. i. clarify. }\n\n      exists prom_src2, mem_src2,\n      (fun loc' ts' => if loc_ts_eq_dec (loc', ts') (loc, to)\n                       then True else self loc' ts'), extra_self. splits; auto.\n      { econs; eauto. econs; eauto. econs; eauto. econs; eauto. }\n      { econs.\n        { i. erewrite (@Memory.split_o mem_tgt'); eauto.\n          erewrite (@Memory.add_o mem_src2); eauto.\n          erewrite (@Memory.add_o mem_src1); eauto.\n          erewrite (@Memory.remove_o mem_src0); eauto. des_ifs.\n          { ss. des; subst. exfalso. eapply Time.lt_strorder; eauto. }\n          { ss. des; clarify. econs 3; auto. right. auto. }\n          { ss. des; clarify. inv PROM; ss.\n            { dup H0. symmetry in H0. apply MLESRC in H0.\n              rewrite H0 in *. inv MEM1.\n              econs 3; eauto.\n              { refl. }\n              { i. apply eq_lb_time. }\n            }\n          }\n          { eapply ((sim_memory_contents MEM)). }\n        }\n        { i. dup EXTRA.\n          apply ((sim_memory_wf MEM)) in EXTRA0. des_ifs.\n          destruct a. ss. subst. splits; try apply EXTRA0; auto. right. auto. }\n      }\n      { econs.\n        { i. erewrite (@Memory.split_o prom_tgt'); eauto.\n          erewrite (@Memory.add_o prom_src2); eauto.\n          erewrite (@Memory.add_o prom_src1); eauto.\n          erewrite (@Memory.remove_o prom_src0); eauto. des_ifs.\n          { ss. des; subst. exfalso. eapply Time.lt_strorder; eauto. }\n          { ss. des; clarify. econs 4; auto.\n            ii. eapply NEXTRATO. eauto. }\n          { ss. des; clarify. inv PROM; ss.\n            { econs 4; eauto. }\n          }\n          { eapply ((sim_promise_contents PROMISE)). }\n        }\n        { i. dup EXTRA.\n          apply ((sim_promise_wf PROMISE)) in EXTRA0. des_ifs.\n          destruct a. ss. subst. splits; try apply EXTRA0; auto. }\n        { i. des_ifs.\n          { ss. des. subst.\n            eapply Memory.add_get0 in ADDPROM2. des. esplits; eauto. }\n          { clear SELF. guardH o. apply (sim_promise_extra PROMISE) in SELF0. des.\n            destruct (loc_ts_eq_dec (loc0, to0) (loc, ts3)).\n            { ss. des; subst. clarify.\n              eapply Memory.add_get0 in ADDPROM1. des.\n              eapply Memory.add_get1 in GET3; eauto. }\n            destruct (loc_ts_eq_dec (loc0, to0) (loc, to)).\n            { ss. des; clarify. exfalso.\n              hexploit memory_get_disjoint_strong.\n              { eapply GET. }\n              { eapply GETSRC. }\n              i. des; clarify.\n              { timetac. }\n              { eapply Time.lt_strorder; eauto. }\n            }\n            { guardH o0. guardH o1. exists to0. splits; auto.\n              erewrite (@Memory.add_o prom_src2); eauto.\n              erewrite (@Memory.add_o prom_src1); eauto.\n              erewrite (@Memory.remove_o prom_src0); eauto. des_ifs.\n              { ss. des; subst. destruct o0; ss. }\n              { ss. destruct a; subst. destruct o1; ss. }\n            }\n          }\n        }\n      }\n      { left. des_ifs. ss. des; clarify. }\n\n    - des. subst.\n      exploit lower_succeed_wf; try apply PROMISES. i. des. inv MSG_LE.\n      rename GET into GETPROMTGT.\n      dup GETPROMTGT. apply MLETGT in GETPROMTGT0. rename GETPROMTGT0 into GETMEMTGT.\n      set (PROM:=(sim_promise_contents PROMISE) loc to).\n      rewrite GETPROMTGT in PROM. inv PROM; ss.\n\n      { right.\n        hexploit (@Memory.lower_exists prom_src loc from to (Message.concrete val released) (Message.concrete val released0)); ss; eauto.\n        intros [prom_src' LOWERPROMSRC].\n        exploit Memory.lower_exists_le; try apply LOWERPROMSRC; eauto.\n        intros [mem_src' LOWERMEMSRC].\n\n        assert (PROMISESRC: Memory.promise prom_src mem_src loc from to (Message.concrete val released0) prom_src' mem_src' (Memory.op_kind_lower (Message.concrete val released))).\n        { econs; eauto. }\n\n        assert (CLOSEDMSG: Memory.closed_message (Message.concrete val released0) mem_src').\n        { eapply semi_closed_message_lower; eauto. }\n\n        assert (PROMSWF0: ~ (others loc to \\/ self loc to)).\n        { set (MEM2:=(sim_memory_contents MEM) loc to). inv MEM2; clarify.\n          eapply Memory.lower_get0 in LOWERMEMSRC. des. rewrite GET in *. clarify. }\n\n        assert (EXTRAWF0: forall t : Time.t, ~ __guard__ (extra_others loc to t \\/ extra_self loc to t)).\n        { ii. set (MEM2:=(sim_memory_contents MEM) loc to). inv MEM2; clarify.\n          - eapply NEXTRA0; eauto.\n          - eapply NEXTRA0; eauto.\n          - eapply Memory.lower_get0 in LOWERMEMSRC. des. rewrite GET in *. clarify. }\n\n        exists prom_src', mem_src'. splits; auto.\n        + econs.\n          { ii. set (MEM1:=(sim_memory_contents MEM) loc0 ts).\n            erewrite (@Memory.lower_o mem_src'); eauto.\n            erewrite (@Memory.lower_o mem_tgt'); eauto. des_ifs.\n            ss. des; clarify. econs; eauto.\n            * refl.\n            * i. ss. }\n          { apply (sim_memory_wf MEM); eauto. }\n        + econs.\n          { ii. set (PROM:= (sim_promise_contents PROMISE) loc0 ts).\n            erewrite (@Memory.lower_o prom_src'); eauto.\n            erewrite (@Memory.lower_o prom_tgt'); eauto. des_ifs.\n            ss. des; clarify. econs; eauto. }\n          { apply PROMISE. }\n          { i. hexploit (sim_promise_extra PROMISE); eauto. i. des.\n            esplits; eauto. erewrite (@Memory.lower_o prom_src'); eauto. des_ifs.\n            ss. des; clarify. }\n      }\n\n      left. symmetry in H0. dup H0. apply MLESRC in H0.\n      rename H0 into GETMEMSRC. rename H1 into GETPROMSRC.\n      set (MEM1:=(sim_memory_contents MEM) loc to).\n      rewrite GETMEMSRC in MEM1. rewrite GETMEMTGT in MEM1. inv MEM1. clear PROM.\n\n      exists prom_src, mem_src, self, extra_self. splits; auto.\n      { econs. }\n      { econs.\n        { i. erewrite (@Memory.lower_o mem_tgt'); eauto. des_ifs.\n          { ss. des; subst. rewrite GETMEMSRC. econs; eauto. right. auto. }\n          { eapply (sim_memory_contents MEM). }\n        }\n        { apply (sim_memory_wf MEM). }\n      }\n      { econs.\n        { i. erewrite (@Memory.lower_o prom_tgt'); eauto. des_ifs.\n          { ss. des; subst. rewrite GETPROMSRC. econs; eauto. }\n          { eapply (sim_promise_contents PROMISE). }\n        }\n        { apply (sim_promise_wf PROMISE). }\n        { apply (sim_promise_extra PROMISE). }\n      }\n      { left. auto. }\n\n    - exploit Memory.remove_get0; try apply PROMISES. i. des.\n      rename GET into GETPROMTGT.\n      dup GETPROMTGT. apply MLETGT in GETPROMTGT0. rename GETPROMTGT0 into GETMEMTGT.\n      set (PROM:=(sim_promise_contents PROMISE) loc to).\n      rewrite GETPROMTGT in PROM.\n\n      assert (INV: exists from_src, <<NPROM: ~ self loc to>> /\\ <<NEXTRA: forall t, ~ extra_self loc to t>> /\\ <<H0: Some (from_src, Message.reserve) = Memory.get loc to prom_src>>).\n      { inv PROM; eauto. } des. clear PROM. left.\n\n      symmetry in H0. dup H0. apply MLESRC in H0.\n      rename H0 into GETMEMSRC. rename H1 into GETPROMSRC.\n      set (MEM1:=(sim_memory_contents MEM) loc to).\n      rewrite GETMEMSRC in MEM1. rewrite GETMEMTGT in MEM1. inv MEM1.\n\n      hexploit (@Memory.remove_exists prom_src loc from_src to Message.reserve).\n      { eauto. }\n      intros [prom_src0 REMOVEPROM].\n      hexploit (@Memory.remove_exists_le prom_src mem_src loc from_src to Message.reserve); eauto.\n      intros [mem_src0 REMOVEMEM].\n      assert (PROMISE0: Memory.promise prom_src mem_src loc from_src to Message.reserve prom_src0 mem_src0 Memory.op_kind_cancel).\n      { econs; eauto. }\n\n      destruct (classic (self loc from_src)) as [SELF|NSELF].\n      { exploit sim_memory_from_forget; eauto.\n        { ss. right. auto. } i. subst.\n        assert (TS: Time.lt from to).\n        { apply memory_get_ts_strong in GETPROMSRC. des; auto.\n          subst. clarify. }\n        assert (exists ts', (<<LB: lb_time (times loc) from ts'>>) /\\\n                            (<<TS0: Time.lt from ts'>>) /\\\n                            (<<TS1: Time.lt ts' to>>)).\n        { hexploit (@lb_time_exists (times loc) (@WO loc) from). i. des.\n          destruct (Time.le_lt_dec ts' (Time.middle from to)).\n          { exists ts'. splits; auto.\n            eapply TimeFacts.le_lt_lt; eauto. eapply Time.middle_spec; eauto. }\n          { exists (Time.middle from to). splits; auto.\n            { eapply lb_time_lower; eauto. left. auto. }\n            { eapply Time.middle_spec; eauto. }\n            { eapply Time.middle_spec; eauto. }\n          }\n        } des.\n        hexploit (@Memory.add_exists mem_src0 loc from ts' Message.reserve); eauto.\n        { ii. erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o.\n          hexploit Memory.get_disjoint.\n          { eapply GET2. }\n          { eapply GETMEMSRC. }\n          i. des.\n          { subst. destruct o; ss. }\n          { eapply H.\n            { eapply RHS. }\n            { inv LHS. econs; ss. etrans; eauto. left. auto. }\n          }\n        }\n        { econs. }\n        intros [mem_src1 ADDMEM].\n        hexploit (@Memory.add_exists_le prom_src0 mem_src0 loc from ts' Message.reserve); eauto.\n        { eapply promise_memory_le; try apply PROMISE0; eauto. }\n        intros [prom_src1 ADDPROM].\n        assert (PROMISE1: Memory.promise prom_src0 mem_src0 loc from ts' Message.reserve prom_src1 mem_src1 Memory.op_kind_add).\n        { econs; eauto. i. clarify. }\n\n        assert (GETMEMNONE: Memory.get loc ts' mem_src = None).\n        { destruct (Memory.get loc ts' mem_src) eqn:GET; auto. destruct p.\n          hexploit memory_get_disjoint_strong.\n          { eapply GET. }\n          { eapply GETMEMSRC. } i. des; subst.\n          { timetac. }\n          { timetac. }\n          { exfalso. eapply Time.lt_strorder.\n            transitivity ts'; eauto. }\n        }\n        assert (GETPROMNONE: Memory.get loc ts' prom_src = None).\n        { destruct (Memory.get loc ts' prom_src) eqn:EQ; auto.\n          destruct p. apply MLESRC in EQ. clarify. }\n        hexploit sim_memory_src_none.\n        { eauto. }\n        { eapply GETMEMNONE. } i. des.\n        hexploit sim_promise_src_none.\n        { eauto. }\n        { eapply GETPROMNONE. } i. des.\n\n        exists prom_src1, mem_src1, self,\n        (fun l t => if (loc_ts_eq_dec (l, t) (loc, ts'))\n                    then (eq from)\n                    else extra_self l t). splits; eauto.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { econs.\n          { i. erewrite (@Memory.remove_o mem_tgt'); eauto.\n            erewrite (@Memory.add_o mem_src1); eauto.\n            erewrite (@Memory.remove_o mem_src0); eauto. des_ifs.\n            { ss. des; clarify. }\n            { ss. des; clarify. rewrite GETTGT. econs 4; eauto. right. auto. }\n            { ss. des; clarify. econs 1; eauto. }\n            { eapply (sim_memory_contents MEM). }\n          }\n          { i. des_ifs.\n            { ss. des; clarify. destruct EXTRA as [EXTRA|EQ].\n              { hexploit ((sim_memory_wf MEM) loc from0 ts'); eauto.\n                { left. auto. }\n                i. des. splits; auto. i. des_ifs; eauto.\n                ss. des; clarify. destruct EXTRA0.\n                { exfalso. eapply NEXTRA1. left. eauto. }\n                { subst. exfalso. eapply NEXTRA1. left. eauto. }\n              }\n              { subst. splits; auto.\n                { right. auto. }\n                { i. des_ifs. ss. des; clarify.\n                  destruct EXTRA as [EXTRA|EQ]; auto.\n                  exfalso. eapply NEXTRA1. left. eauto. }\n              }\n            }\n            { hexploit ((sim_memory_wf MEM) loc0 from0 ts); eauto. }\n          }\n        }\n        { econs.\n          { i. erewrite (@Memory.remove_o prom_tgt'); eauto.\n            erewrite (@Memory.add_o prom_src1); eauto.\n            erewrite (@Memory.remove_o prom_src0); eauto. des_ifs.\n            { ss. des; clarify. }\n            { ss. des; clarify. rewrite GETTGT0. econs 5; eauto. }\n            { ss. des; clarify. eauto. }\n            { eapply (sim_promise_contents PROMISE). }\n          }\n          { i. des_ifs.\n            { ss. des; clarify. }\n            { eapply (sim_promise_wf PROMISE); eauto. }\n          }\n          { i. hexploit ((sim_promise_extra PROMISE) loc0 ts); eauto. i. des.\n            destruct (loc_ts_eq_dec (loc0, ts) (loc, from)).\n            { ss. des. clarify. exists ts'. splits; auto.\n              eapply Memory.add_get0; eauto. }\n            { exists to0. splits; auto.\n              erewrite Memory.add_o; eauto. erewrite Memory.remove_o; eauto.\n              des_ifs.\n              { ss. des; clarify. }\n              { ss. des; clarify. }\n            }\n          }\n        }\n        { right. auto. }\n      }\n      { exists prom_src0, mem_src0, self, extra_self. splits; eauto.\n        { econs; eauto. econs; eauto. }\n        { econs.\n          { i. erewrite (@Memory.remove_o mem_tgt'); eauto.\n            erewrite (@Memory.remove_o mem_src0); eauto. des_ifs.\n            { ss. des; subst. econs 1; eauto. }\n            { eapply (sim_memory_contents MEM). }\n          }\n          { apply (sim_memory_wf MEM). }\n        }\n        { econs.\n          { i. erewrite (@Memory.remove_o prom_tgt'); eauto.\n            erewrite (@Memory.remove_o prom_src0); eauto. des_ifs.\n            { ss. des; subst. eauto. }\n            { eapply (sim_promise_contents PROMISE). }\n          }\n          { apply (sim_promise_wf PROMISE). }\n          { i. dup SELF. apply (sim_promise_extra PROMISE) in SELF. des.\n            destruct (loc_ts_eq_dec (loc0, to0) (loc, to)).\n            { ss. des; clarify. }\n            { exists to0. splits; auto. erewrite Memory.remove_o; eauto. des_ifs.\n              ss. des; clarify. }\n          }\n        }\n        { right. auto. }\n      }\n  Qed.\n\n\n  Lemma sim_fulfill_forget from_src' others (self: Loc.t -> Time.t -> Prop) extra_others extra_self\n        prom_src prom_tgt mem_src mem_tgt prom_tgt'\n        loc from_tgt to val released\n        (LOC: L loc)\n        (SELF: self loc to)\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (MLETGT: Memory.le prom_tgt mem_tgt)\n        (MLESRC: Memory.le prom_src mem_src)\n        (FIN: Memory.finite prom_src)\n        (BOTNONESRC: Memory.bot_none prom_src)\n        (BOTNONETGT: Memory.bot_none prom_tgt)\n        (PROMISE: sim_promise self extra_self prom_src prom_tgt)\n        (REMOVE: Memory.remove prom_tgt loc from_tgt to (Message.concrete val released) prom_tgt')\n        (CLOSED: Memory.closed mem_tgt)\n\n        (FROMSRC0: Time.le from_tgt from_src')\n        (FROMSRC1: forall from_src msg\n                          (GET: Memory.get loc to mem_src = Some (from_src, msg)),\n            Time.le from_src' from_src)\n        (EMPTY: forall from_src msg\n                          (GET: Memory.get loc to mem_src = Some (from_src, msg))\n                          ts (ITV: Interval.mem (from_src', from_src) ts),\n            Memory.get loc ts mem_src = None)\n        (MEMWF: memory_times_wf times mem_tgt)\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src prom_src loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src prom_src loc' ts' from' Message.reserve>>))\n\n        (CONSISTENT: forall to' from' val' released'\n                            (GETTGT: Memory.get loc to' prom_tgt' = Some (from', Message.concrete val' released')),\n            Time.lt to to')\n    :\n      exists prom_src0 mem_src0 mem_src1 prom_src2 mem_src2 self' extra_self',\n        (<<FUTURE0: reserve_future_memory prom_src mem_src prom_src0 mem_src0>>) /\\\n        (<<WRITE: Memory.write prom_src0 mem_src0 loc from_src' to val released prom_src0 mem_src1 Memory.op_kind_add>>) /\\\n        (<<FROM: Time.le from_tgt from_src'>>) /\\\n        (<<FUTURE1: reserve_future_memory prom_src0 mem_src1 prom_src2 mem_src2>>) /\\\n        (<<MEM: sim_memory L times (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src2 mem_tgt>>) /\\\n        (<<PROMISE: sim_promise\n                      self' extra_self'\n                      prom_src2 prom_tgt'>>).\n  Proof.\n    hexploit Memory.remove_get0; try apply REMOVE. i. des.\n    rename GET into GETPROMTGT. dup GETPROMTGT.\n    apply MLETGT in GETPROMTGT0. rename GETPROMTGT0 into GETMEMTGT.\n\n    set (PROM := (sim_promise_contents PROMISE) loc to).\n    rewrite GETPROMTGT in PROM. inv PROM; ss.\n\n    symmetry in H0. rename H0 into GETPROMSRC.\n    dup GETPROMSRC. apply MLESRC in GETPROMSRC0. rename GETPROMSRC0 into GETMEMSRC.\n\n    set (MEM0 := (sim_memory_contents MEM) loc to).\n    rewrite GETMEMSRC in *. rewrite GETMEMTGT in *.\n    inv MEM0; try by (exfalso; apply NPROM; right; auto).\n\n    specialize (FROMSRC1 _ _ eq_refl).\n    specialize (EMPTY _ _ eq_refl).\n    assert (LB': lb_time (times loc) from_tgt from_src').\n    { eapply lb_time_lower; eauto. }\n\n    assert (NOTHER: ~ others loc to).\n    { intros OTHER. eapply EXCLUSIVE in OTHER. des. inv UNCH. clarify. }\n\n    hexploit ((sim_promise_extra PROMISE)); eauto. i. des.\n\n    hexploit (@Memory.remove_exists prom_src loc to to0 Message.reserve).\n    { eauto. }\n    intros [prom_src' REMOVEPROM0].\n    hexploit (@Memory.remove_exists_le prom_src mem_src loc to to0 Message.reserve); eauto.\n    intros [mem_src' REMOVEMEM0].\n    assert (PROMISE0: Memory.promise prom_src mem_src loc to to0 Message.reserve prom_src' mem_src' Memory.op_kind_cancel).\n    { econs; eauto. }\n\n    hexploit (@Memory.remove_exists prom_src' loc from_src to Message.reserve).\n    { erewrite Memory.remove_o; eauto. des_ifs.\n      ss. des; subst. timetac. }\n    intros [prom_src0 REMOVEPROM1].\n    hexploit (@Memory.remove_exists_le prom_src' mem_src' loc from_src to Message.reserve); eauto.\n    { eapply promise_memory_le; cycle 1; eauto. }\n    intros [mem_src0 REMOVEMEM1].\n    assert (PROMISE1: Memory.promise prom_src' mem_src' loc from_src to Message.reserve prom_src0 mem_src0 Memory.op_kind_cancel).\n    { econs; eauto. }\n\n    dup GETMEMTGT. eapply CLOSED in GETMEMTGT0. des.\n\n    hexploit (@Memory.add_exists mem_src0 loc from_src' to (Message.concrete val released)); eauto.\n    { ii. inv LHS. inv RHS. ss.\n      erewrite Memory.remove_o in GET2; eauto.\n      erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o. guardH o0.\n      destruct (Time.le_lt_dec x from_src).\n      { hexploit memory_get_disjoint_strong.\n        { eapply GET2. }\n        { eapply GETMEMSRC. }\n        i. des.\n        { subst. ss. destruct o; ss. }\n        { erewrite EMPTY in GET2; clarify. econs; ss.\n          eapply (@TimeFacts.lt_le_lt _ x); eauto.\n        }\n        { eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply FROM1. } etrans.\n          { eapply TO. }\n          { eauto. }\n        }\n      }\n      { hexploit Memory.get_disjoint.\n        { eapply GET2. }\n        { eapply GETMEMSRC. }\n        i. des; subst; ss.\n        { destruct o; ss. }\n        { eapply H; econs; eauto. }\n      }\n    }\n    { eapply (@TimeFacts.le_lt_lt _ from_src); eauto.\n      apply memory_get_ts_strong in GETMEMSRC. des; auto.\n      subst. erewrite BOTNONESRC in GETPROMSRC. clarify. }\n    intros [mem_src1 ADDMEM0].\n    hexploit (@Memory.add_exists_le prom_src0 mem_src0 loc from_src' to (Message.concrete val released)); eauto.\n    { eapply promise_memory_le; cycle 1; eauto.\n      eapply promise_memory_le; cycle 1; eauto. }\n    intros [prom_src1 ADDPROM0].\n    assert (PROMISE2: Memory.promise prom_src0 mem_src0 loc from_src' to (Message.concrete val released) prom_src1 mem_src1 Memory.op_kind_add).\n    { econs; eauto. i.\n      erewrite Memory.remove_o in GET1; eauto.\n      erewrite Memory.remove_o in GET1; eauto. des_ifs. guardH o. guardH o0.\n      hexploit memory_get_from_inj.\n      { eapply GET1. }\n      { eapply MLESRC. eapply GET. }\n      i. des; subst.\n      { destruct o0; ss. }\n      { erewrite BOTNONETGT in GETPROMTGT. clarify. }\n      { erewrite BOTNONETGT in GETPROMTGT. clarify. }\n    }\n\n    hexploit (@Memory.remove_exists prom_src1 loc from_src' to (Message.concrete val released)); eauto.\n    { eapply Memory.add_get0; eauto. }\n    intros [prom_src2 REMOVEPROM2].\n    hexploit (@MemoryFacts.add_remove_eq prom_src0 prom_src1 prom_src2); eauto.\n    i. subst.\n\n    assert (NOTHEREXTRA: forall from', ~ extra_others loc to0 from').\n    { intros from' OTHER. eapply EXCLUSIVEEXTRA in OTHER. des. inv OTHER. clarify. }\n\n    assert (WRITE: Memory.write prom_src0 mem_src0 loc from_src' to val released prom_src0 mem_src1 Memory.op_kind_add); eauto.\n\n    destruct (classic (exists to', <<EXTRA: extra_self loc to0 to'>>)) as [?|MINE].\n    { des. set (PROM1 := (sim_promise_contents PROMISE) loc to0).\n      inv PROM1; try by (exfalso; eapply NEXTRA1; eauto); ss.\n      rewrite GET in *. clarify.\n      assert (to' = to).\n      { hexploit (sim_memory_wf MEM).\n        { right. eapply EXTRA0. }\n        i. des. eapply UNIQUE. right. auto. } subst.\n      set (MEM1 := (sim_memory_contents MEM) loc to0).\n      inv MEM1; try by (exfalso; eapply NEXTRA1; right; eauto); ss.\n      dup GET. apply MLESRC in GET. rewrite GET in *. clarify.\n\n      exists prom_src0, mem_src0, mem_src1, prom_src0, mem_src1,\n      (fun loc' ts' => if loc_ts_eq_dec (loc', ts') (loc, to)\n                       then False else self loc' ts'),\n      (fun loc' ts' => if loc_ts_eq_dec (loc', ts') (loc, to0)\n                       then (fun _ => False) else extra_self loc' ts').\n      splits; eauto.\n      { econs; eauto. econs; eauto. econs; eauto. }\n      { econs. }\n      { econs.\n        { i. erewrite (@Memory.add_o mem_src1); eauto.\n          erewrite (@Memory.remove_o mem_src0); eauto.\n          erewrite (@Memory.remove_o mem_src'); eauto. des_ifs.\n          { ss. des; clarify. }\n          { ss. des; clarify. rewrite GETMEMTGT. econs 2; eauto.\n            { intros []; ss. }\n            { i. ss. }\n          }\n          { ss. des; clarify. rewrite <- H2. econs; eauto.\n            intros ? []; ss. eapply NOTHEREXTRA; eauto. }\n          { eapply (sim_memory_contents MEM). }\n        }\n        { i. des_ifs.\n          { ss. des; clarify.\n            destruct EXTRA2; ss. exfalso. eapply NOTHEREXTRA; eauto. }\n          { ss. des; clarify. exfalso. eapply o.\n            eapply sim_memory_extra_inj; eauto.\n            { eapply EXTRA2. }\n            { right. eauto. }\n          }\n          { ss. des; clarify.\n            destruct EXTRA2; ss. exfalso. eapply NOTHEREXTRA; eauto. }\n          { eapply (sim_memory_wf MEM). auto. }\n        }\n      }\n      { econs.\n        { i. erewrite (@Memory.remove_o prom_src0 prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_tgt'); eauto. des_ifs.\n          { ss. des; clarify. }\n          { ss. des; clarify. econs; eauto. }\n          { ss. des; clarify. rewrite <- H. econs; eauto. }\n          { apply (sim_promise_contents PROMISE). }\n        }\n        { i. des_ifs.\n          { ss. des; clarify. exfalso. eapply o.\n            eapply sim_memory_extra_inj; eauto.\n            { right. eapply EXTRA2. }\n            { right. eauto. }\n          }\n          { eapply (sim_promise_wf PROMISE); eauto. }\n        }\n        { i. des_ifs. guardH o. dup SELF0.\n          eapply (sim_promise_extra PROMISE) in SELF1. des.\n          exists to1. splits; auto.\n          erewrite (@Memory.remove_o prom_src0 prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n          { ss. des; clarify. exfalso.\n            set (PROM1:=(sim_promise_contents PROMISE) loc from_src).\n            inv PROM1; ss.\n            symmetry in H3. eapply Memory.remove_get1 in H3; eauto.\n            des; subst.\n            { timetac. }\n            { eapply CONSISTENT in GET3. eapply Time.lt_strorder.\n              transitivity from_src; eauto. }\n          }\n          { ss. des; clarify. destruct o; ss. }\n        }\n      }\n    }\n\n    { dup GET. eapply MLESRC in GET1.\n      assert (NOEXTRA: forall ts', ~ (extra_others \\\\3// extra_self) loc ts' to).\n      { ii. set (MEM1:=(sim_memory_contents MEM) loc ts').\n        inv MEM1; ss; try by (exfalso; eapply NEXTRA1; eauto).\n        hexploit ((sim_memory_wf MEM) loc from ts'); eauto. i. des.\n        eapply UNIQUE in H. subst.\n        hexploit memory_get_from_inj.\n        { symmetry. eapply H1. }\n        { eapply GET1. }\n        i. des.\n        { subst. destruct EXTRA.\n          { eapply EXCLUSIVEEXTRA in H. inv H. clarify. }\n          { eapply MINE; eauto. }\n        }\n        { subst. rewrite BOTNONESRC in GETPROMSRC. clarify. }\n        { subst. rewrite BOTNONESRC in GETPROMSRC. clarify. }\n      }\n\n      hexploit (@Memory.add_exists mem_src1 loc to to0 Message.reserve); eauto.\n      { i. erewrite Memory.add_o in GET2; eauto.\n        erewrite Memory.remove_o in GET2; eauto.\n        erewrite Memory.remove_o in GET2; eauto. des_ifs.\n        { ss. des; clarify. symmetry.\n          eapply Interval.disjoint_imm. }\n        { guardH o. guardH o0. hexploit Memory.get_disjoint.\n          { eapply MLESRC. eapply GET. }\n          { eapply GET2. }\n          i. des; auto. subst. destruct o0; ss. }\n      }\n      { econs. }\n      intros [mem_src2 ADDMEM1].\n      hexploit (@Memory.add_exists_le prom_src0 mem_src1 loc to to0 Message.reserve); eauto.\n      { eapply write_memory_le; cycle 1; eauto.\n        eapply promise_memory_le; cycle 1; eauto.\n        eapply promise_memory_le; cycle 1; eauto. }\n      intros [prom_src2 ADDPROM1].\n\n      assert (PROMISE3: Memory.promise prom_src0 mem_src1 loc to to0 Message.reserve prom_src2 mem_src2 Memory.op_kind_add).\n      { econs; eauto. i. clarify. }\n\n      exists prom_src0, mem_src0, mem_src1, prom_src2, mem_src2,\n      (fun loc' ts' => if loc_ts_eq_dec (loc', ts') (loc, to)\n                       then False else self loc' ts'), extra_self.\n      splits; eauto.\n      { econs; eauto. econs; eauto. econs; eauto. }\n      { econs; eauto. econs; eauto. }\n      { econs.\n        { i. erewrite (@Memory.add_o mem_src2); eauto.\n          erewrite (@Memory.add_o mem_src1); eauto.\n          erewrite (@Memory.remove_o mem_src0); eauto.\n          erewrite (@Memory.remove_o mem_src'); eauto. des_ifs.\n          { ss. des; clarify. timetac. }\n          { ss. des; clarify. rewrite GETMEMTGT. econs 2; eauto.\n            { intros []; ss. }\n            { i. ss. }\n          }\n          { ss. des; clarify. rewrite <- GET1.\n            eapply (sim_memory_contents MEM). }\n          { eapply (sim_memory_contents MEM). }\n        }\n        { i. des_ifs.\n          { ss. des; clarify. exfalso. eapply NOEXTRA; eauto. }\n          { eapply (sim_memory_wf MEM). auto. }\n        }\n      }\n      { econs.\n        { i. erewrite (@Memory.add_o prom_src2); eauto.\n          erewrite (@Memory.remove_o prom_src0 prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_tgt'); eauto. des_ifs.\n          { ss. des; clarify. timetac. }\n          { ss. des; clarify. econs; eauto. }\n          { ss. des; clarify. rewrite <- GET.\n            apply (sim_promise_contents PROMISE). }\n          { apply (sim_promise_contents PROMISE). }\n        }\n        { i. des_ifs.\n          { ss. des; clarify. exfalso.\n            eapply NOEXTRA. right. eauto. }\n          { eapply (sim_promise_wf PROMISE); eauto. }\n        }\n        { i. des_ifs. guardH o. dup SELF0.\n          eapply (sim_promise_extra PROMISE) in SELF1. des.\n          exists to1. splits; auto.\n          erewrite (@Memory.add_o prom_src2); eauto.\n          erewrite (@Memory.remove_o prom_src0 prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n          { ss. des; clarify. }\n          { ss. des; clarify. exfalso.\n            set (PROM1:=(sim_promise_contents PROMISE) loc from_src).\n            inv PROM1; ss.\n            symmetry in H. eapply Memory.remove_get1 in H; eauto.\n            des; subst.\n            { timetac. }\n            { eapply CONSISTENT in GET3. eapply Time.lt_strorder.\n              transitivity from_src; eauto. }\n          }\n        }\n      }\n    }\n  Qed.\n\n\n  Lemma sim_fulfill_forget_write others (self: Loc.t -> Time.t -> Prop) extra_others extra_self\n        prom_src prom_tgt mem_src mem_tgt prom_tgt'\n        loc from_tgt to val released\n        (LOC: L loc)\n        (SELF: self loc to)\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (MLETGT: Memory.le prom_tgt mem_tgt)\n        (MLESRC: Memory.le prom_src mem_src)\n        (FIN: Memory.finite prom_src)\n        (BOTNONESRC: Memory.bot_none prom_src)\n        (BOTNONETGT: Memory.bot_none prom_tgt)\n        (PROMISE: sim_promise self extra_self prom_src prom_tgt)\n        (REMOVE: Memory.remove prom_tgt loc from_tgt to (Message.concrete val released) prom_tgt')\n        (CLOSED: Memory.closed mem_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt)\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src prom_src loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src prom_src loc' ts' from' Message.reserve>>))\n\n        (CONSISTENT: forall to' from' val' released'\n                            (GETTGT: Memory.get loc to' prom_tgt' = Some (from', Message.concrete val' released')),\n            Time.lt to to')\n    :\n      exists from_src prom_src0 mem_src0 mem_src1 prom_src2 mem_src2 self' extra_self',\n        (<<FUTURE0: reserve_future_memory prom_src mem_src prom_src0 mem_src0>>) /\\\n        (<<WRITE: Memory.write prom_src0 mem_src0 loc from_src to val released prom_src0 mem_src1 Memory.op_kind_add>>) /\\\n        (<<FROM: Time.le from_tgt from_src>>) /\\\n        (<<FUTURE1: reserve_future_memory prom_src0 mem_src1 prom_src2 mem_src2>>) /\\\n        (<<MEM: sim_memory L times (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src2 mem_tgt>>) /\\\n        (<<PROMISE: sim_promise\n                      self' extra_self'\n                      prom_src2 prom_tgt'>>).\n  Proof.\n    hexploit Memory.remove_get0; try apply REMOVE. i. des.\n    rename GET into GETPROMTGT. dup GETPROMTGT.\n    apply MLETGT in GETPROMTGT0. rename GETPROMTGT0 into GETMEMTGT.\n\n    set (PROM := (sim_promise_contents PROMISE) loc to).\n    rewrite GETPROMTGT in PROM. inv PROM; ss.\n    symmetry in H0. rename H0 into GETPROMSRC.\n    dup GETPROMSRC. apply MLESRC in GETPROMSRC0. rename GETPROMSRC0 into GETMEMSRC.\n\n    set (MEM0 := (sim_memory_contents MEM) loc to).\n    rewrite GETMEMSRC in *. rewrite GETMEMTGT in *.\n    inv MEM0; try by (exfalso; apply NPROM; right; auto).\n\n    exists from_src. eapply sim_fulfill_forget; eauto.\n    { i. clarify. refl. }\n    { i. clarify. inv ITV. ss. timetac. }\n  Qed.\n\n  Lemma sim_fulfill_forget_update others (self: Loc.t -> Time.t -> Prop) extra_others extra_self\n        prom_src prom_tgt mem_src mem_tgt prom_tgt'\n        loc from_tgt to val released\n        (LOC: L loc)\n        (SELF: self loc to)\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (MLETGT: Memory.le prom_tgt mem_tgt)\n        (MLESRC: Memory.le prom_src mem_src)\n        (FIN: Memory.finite prom_src)\n        (BOTNONESRC: Memory.bot_none prom_src)\n        (BOTNONETGT: Memory.bot_none prom_tgt)\n        (PROMISE: sim_promise self extra_self prom_src prom_tgt)\n        (REMOVE: Memory.remove prom_tgt loc from_tgt to (Message.concrete val released) prom_tgt')\n        (CLOSED: Memory.closed mem_tgt)\n        (NOREAD: ~ others loc from_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt)\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src prom_src loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src prom_src loc' ts' from' Message.reserve>>))\n\n        (CONSISTENT: forall to' from' val' released'\n                            (GETTGT: Memory.get loc to' prom_tgt' = Some (from', Message.concrete val' released')),\n            Time.lt to to')\n    :\n      exists prom_src0 mem_src0 mem_src1 prom_src2 mem_src2 self' extra_self',\n        (<<FUTURE0: reserve_future_memory prom_src mem_src prom_src0 mem_src0>>) /\\\n        (<<WRITE: Memory.write prom_src0 mem_src0 loc from_tgt to val released prom_src0 mem_src1 Memory.op_kind_add>>) /\\\n        (<<FROM: Time.le from_tgt from_tgt>>) /\\\n        (<<FUTURE1: reserve_future_memory prom_src0 mem_src1 prom_src2 mem_src2>>) /\\\n        (<<MEM: sim_memory L times (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src2 mem_tgt>>) /\\\n        (<<PROMISE: sim_promise\n                      self' extra_self'\n                      prom_src2 prom_tgt'>>).\n  Proof.\n    hexploit Memory.remove_get0; try apply REMOVE. i. des.\n    rename GET into GETPROMTGT. dup GETPROMTGT.\n    apply MLETGT in GETPROMTGT0. rename GETPROMTGT0 into GETMEMTGT.\n\n    set (PROM := (sim_promise_contents PROMISE) loc to).\n    rewrite GETPROMTGT in PROM. inv PROM; ss.\n    symmetry in H0. rename H0 into GETPROMSRC.\n    dup GETPROMSRC. apply MLESRC in GETPROMSRC0. rename GETPROMSRC0 into GETMEMSRC.\n\n    set (MEM0 := (sim_memory_contents MEM) loc to).\n    rewrite GETMEMSRC in *. rewrite GETMEMTGT in *.\n    inv MEM0; try by (exfalso; apply NPROM; right; auto).\n\n    eapply sim_fulfill_forget; eauto.\n    { refl. }\n    { i. clarify. }\n    { i. clarify.\n      destruct (Memory.get loc ts mem_src) eqn:EQ; auto. destruct p.\n      eapply sim_memory_get_larger in EQ; eauto. des.\n      { inv ITV. ss. hexploit Memory.get_disjoint.\n        { eapply GETTGT. }\n        { eapply GETMEMTGT. }\n        i. des; clarify.\n        { apply memory_get_ts_strong in GET. des.\n          { subst. erewrite BOTNONESRC in GETPROMSRC. clarify. }\n          { timetac. }\n        }\n        { exfalso. eapply (H ts); econs; ss.\n          { apply memory_get_ts_strong in GETTGT. des; auto.\n            subst. exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n            { eapply FROM0. }\n            { eapply Time.bot_spec. }\n          }\n          { refl. }\n          { etrans; eauto. eapply memory_get_ts_le; eauto. }\n        }\n      }\n      { exfalso. set (MEM1:=(sim_memory_contents MEM) loc t). inv MEM1; ss.\n        hexploit ((sim_memory_wf MEM) loc t ts); eauto. i. des. inv ITV; ss.\n        hexploit memory_get_disjoint_strong.\n        { symmetry. eapply H. }\n        { eapply GETMEMTGT. }\n        i. des; clarify.\n        { rewrite GET in *. clarify.\n          eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply TS. } etrans.\n          { eapply TO. }\n          { eapply memory_get_ts_le; eauto. }\n        }\n        { exploit LB1.\n          { instantiate (1:=from_tgt).\n            apply MEMWF in GETMEMTGT. des. auto. }\n          { destruct TS0; auto. inv H1. exfalso. destruct PROM1; eauto.\n            set (PROM1:=(sim_promise_contents PROMISE) loc from_tgt). inv PROM1; ss.\n            symmetry in H4. eapply Memory.remove_get1 in H4; eauto. des.\n            { subst. timetac. }\n            { eapply CONSISTENT in GET2. eapply Time.lt_strorder.\n              etrans; [eapply GET2|]; eauto. }\n          }\n          { i. eapply Time.lt_strorder. etrans.\n            { eapply FROM1. } eauto.\n          }\n        }\n        { eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply TS1. } etrans.\n          { left. eapply TS. } etrans.\n          { eapply TO. }\n          { eapply memory_get_ts_le; eauto. }\n        }\n      }\n    }\n  Qed.\n\n\n  Lemma sim_promise_step_forget others (self: Loc.t -> Time.t -> Prop) extra_others extra_self\n        mem_src mem_tgt mem_tgt' lc_src lc_tgt lc_tgt' loc from to msg kind\n        (LOC: L loc)\n        (STEPTGT: Local.promise_step lc_tgt mem_tgt loc from to msg lc_tgt' mem_tgt' kind)\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (LOCAL: sim_local self extra_self lc_src lc_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LCSRC: Local.wf lc_src mem_src)\n        (LCTGT: Local.wf lc_tgt mem_tgt)\n\n        (CLOSED: Memory.closed mem_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (SEMI: semi_closed_message msg mem_src loc to)\n    :\n      (exists self' extra_self' prom_src' mem_src',\n        (<<FUTURE: reserve_future_memory (Local.promises lc_src) mem_src prom_src' mem_src'>>) /\\\n        (<<MEM: sim_memory L times (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src' mem_tgt'>>) /\\\n        (<<SIM: sim_local self' extra_self' (Local.mk (Local.tview lc_src) prom_src') lc_tgt'>>) /\\\n        (<<SELF: __guard__(self' loc to \\/ msg = Message.reserve)>>)) \\/\n      (exists lc_src' mem_src',\n        (<<STEPSRC: Local.promise_step lc_src mem_src loc from to msg lc_src' mem_src' kind>>) /\\\n        (<<MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src' mem_tgt'>>) /\\\n        (<<LOCAL: sim_local self extra_self lc_src' lc_tgt'>>) /\\\n        (<<SELF: ~ self loc to>>))\n  .\n  Proof.\n    inv STEPTGT. inv LCSRC. inv LCTGT. inv LOCAL.\n    hexploit sim_promise_forget; ss; eauto. i. des.\n    - left. esplits; eauto.\n    - right. esplits; eauto.\n  Qed.\n\n  Lemma sim_write_step_forget others self extra_others extra_self\n        mem_src mem_tgt mem_tgt' lc_src lc_tgt lc_tgt' loc from to kind_tgt sc sc' val released ord\n        (LOC: L loc)\n        (STEPTGT: Local.write_step lc_tgt sc mem_tgt loc from to val None released ord lc_tgt' sc' mem_tgt' kind_tgt)\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (LOCAL: sim_local self extra_self lc_src lc_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LCSRC: Local.wf lc_src mem_src)\n        (LCTGT: Local.wf lc_tgt mem_tgt)\n\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n\n        (CLOSED: Memory.closed mem_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n    :\n      exists self' extra_self' from' lc_src' prom_src0 mem_src0 mem_src1 prom_src' mem_src' kind_src,\n        (<<FUTURE0: reserve_future_memory (Local.promises lc_src) mem_src prom_src0 mem_src0>>) /\\\n        (<<WRITE: Local.write_step (Local.mk (Local.tview lc_src) prom_src0) sc mem_src0 loc from' to val None released ord lc_src' sc' mem_src1 kind_src>>) /\\\n        (<<FROM: Time.le from from'>>) /\\\n        (<<FUTURE1: reserve_future_memory (Local.promises lc_src') mem_src1 prom_src' mem_src'>>) /\\\n\n        (<<MEM: sim_memory L times (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src' mem_tgt'>>) /\\\n        (<<SIM: sim_local self' extra_self' (Local.mk (Local.tview lc_src') prom_src') lc_tgt'>>)\n  .\n  Proof.\n    inv STEPTGT. inv LCSRC. inv LCTGT. inv LOCAL. inv WRITE. ss.\n    hexploit Memory.promise_future; try apply PROMISE; eauto.\n    { econs. inv PROMISE; try by (eapply TViewFacts.op_closed_released; eauto). } i. des.\n\n    hexploit sim_promise_forget; ss; eauto.\n    { ss. econs. unfold TView.write_released. des_ifs; econs.\n      eapply semi_closed_view_join.\n      - inv MEMSRC. eapply unwrap_closed_opt_view; auto.\n        eapply closed_opt_view_semi_closed. auto.\n      - ss. setoid_rewrite LocFun.add_spec_eq. des_ifs.\n        + eapply semi_closed_view_join.\n          * eapply closed_view_semi_closed. inv TVIEW_CLOSED. auto.\n          * inv MEMSRC. eapply semi_closed_view_singleton. auto.\n        + eapply semi_closed_view_join.\n          * eapply closed_view_semi_closed. inv TVIEW_CLOSED. auto.\n          * inv MEMSRC. eapply semi_closed_view_singleton. auto.\n    }\n    i. des.\n    { destruct SELF as [SELF|]; ss.\n      hexploit reserve_future_memory_future; try apply STEPSRC; eauto.\n      i. des. inv LOCAL. ss.\n\n      hexploit sim_fulfill_forget_write; try apply SELF; try apply PROMISE0; eauto.\n      { i. eapply EXCLUSIVE in OTHER. des.\n        eapply reserve_future_memory_unchangable in UNCH; eauto. }\n      { i. eapply EXCLUSIVEEXTRA in OTHER. des.\n        eapply reserve_future_memory_unchangable in OTHER; eauto. }\n      { i. eapply CONSISTENT in GETTGT. ss.\n        eapply TimeFacts.le_lt_lt; [|eapply GETTGT].\n        unfold TimeMap.join, TimeMap.singleton. etrans; [|eapply Time.join_r].\n        setoid_rewrite LocFun.add_spec_eq. refl. }\n\n      i. des.\n      eexists self'0, extra_self'0, from_src, (Local.mk _ prom_src0), prom_src0, mem_src0, mem_src1, prom_src2, mem_src2, Memory.op_kind_add.\n      splits; eauto.\n      { eapply reserve_future_memory_trans; eauto. }\n      { econs; eauto; ss. ii. des_ifs.\n        eapply reserve_future_concrete_same_promise2 in GET; eauto.\n        eapply reserve_future_concrete_same_promise2 in GET; eauto.\n        set (PROM:= (sim_promise_contents PROMS) loc t).\n        rewrite GET in *. inv PROM; ss. exploit RELEASE; eauto.\n      }\n      { econs; eauto. }\n    }\n    { hexploit (@Memory.remove_exists\n                  prom_src' loc from to\n                  (Message.concrete val (TView.write_released tvw sc loc to None ord))).\n      { set (PROM:= (sim_promise_contents PROMISE0) loc to).\n        eapply Memory.remove_get0 in REMOVE. des.\n        rewrite GET in *. inv PROM; ss. }\n      intros [prom_src'' REMOVESRC]. esplits.\n      - econs 1.\n      - econs; ss.\n        + econs; eauto.\n        + ii. set (PROM:=(sim_promise_contents PROMS) loc t).\n          rewrite GET in *. inv PROM; ss.\n          exploit RELEASE; eauto.\n      - refl.\n      - econs 1.\n      - eauto.\n      - econs; auto. econs.\n        { ii. set (PROM:=(sim_promise_contents PROMISE0) loc0 ts).\n          erewrite (@Memory.remove_o prom_src''); eauto.\n          erewrite (@Memory.remove_o promises2); eauto. des_ifs.\n          ss. des; subst. econs 2; eauto.\n          ii. inv PROM; clarify; try by (eapply NEXTRA; eauto).\n          eapply Memory.remove_get0 in REMOVESRC. des. rewrite GET in *. clarify.\n        }\n        { apply PROMISE0. }\n        { i. set (PROM:=(sim_promise_extra PROMISE0) loc0 ts SELF0). des.\n          esplits; eauto. erewrite (@Memory.remove_o prom_src''); eauto.\n          des_ifs. ss. des; clarify. exfalso.\n          eapply Memory.remove_get0 in REMOVESRC. des. clarify. }\n    }\n  Qed.\n\n  Lemma sim_update_step_forget others self extra_others extra_self\n        mem_src mem_tgt mem_tgt' lc_src lc_tgt lc_tgt' loc from to kind_tgt sc sc' val releasedm released ord\n        (LOC: L loc)\n        (STEPTGT: Local.write_step lc_tgt sc mem_tgt loc from to val releasedm released ord lc_tgt' sc' mem_tgt' kind_tgt)\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (LOCAL: sim_local self extra_self lc_src lc_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LCSRC: Local.wf lc_src mem_src)\n        (LCTGT: Local.wf lc_tgt mem_tgt)\n\n        (NOREAD: ~ (others \\\\2// self) loc from)\n\n        (RELEASEDMCLOSED: Memory.closed_opt_view releasedm mem_tgt)\n        (RELEASEDMCLOSEDSRC: Memory.closed_opt_view releasedm mem_src)\n        (RELEASEDMWF: View.opt_wf releasedm)\n\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n\n        (CLOSED: Memory.closed mem_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n    :\n      exists self' extra_self' lc_src' prom_src0 mem_src0 mem_src1 prom_src' mem_src' kind_src,\n        (<<FUTURE0: reserve_future_memory (Local.promises lc_src) mem_src prom_src0 mem_src0>>) /\\\n        (<<WRITE: Local.write_step (Local.mk (Local.tview lc_src) prom_src0) sc mem_src0 loc from to val releasedm released ord lc_src' sc' mem_src1 kind_src>>) /\\\n        (<<FUTURE1: reserve_future_memory (Local.promises lc_src') mem_src1 prom_src' mem_src'>>) /\\\n\n        (<<MEM: sim_memory L times (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src' mem_tgt'>>) /\\\n        (<<SIM: sim_local self' extra_self' (Local.mk (Local.tview lc_src') prom_src') lc_tgt'>>)\n  .\n  Proof.\n    inv STEPTGT. inv LCSRC. inv LCTGT. inv LOCAL. inv WRITE. ss.\n    hexploit Memory.promise_future; try apply PROMISE; eauto.\n    { econs. inv PROMISE; try by (eapply TViewFacts.op_closed_released; eauto). } i. des.\n\n    hexploit sim_promise_forget; ss; eauto.\n    { ss. econs. unfold TView.write_released. des_ifs; econs.\n      eapply semi_closed_view_join.\n      - inv MEMSRC. eapply unwrap_closed_opt_view; auto.\n        eapply closed_opt_view_semi_closed. auto.\n      - ss. setoid_rewrite LocFun.add_spec_eq. des_ifs.\n        + eapply semi_closed_view_join.\n          * eapply closed_view_semi_closed. inv TVIEW_CLOSED. auto.\n          * inv MEMSRC. eapply semi_closed_view_singleton. auto.\n        + eapply semi_closed_view_join.\n          * eapply closed_view_semi_closed. inv TVIEW_CLOSED. auto.\n          * inv MEMSRC. eapply semi_closed_view_singleton. auto.\n    }\n    i. des.\n    { destruct SELF as [SELF|]; ss.\n      hexploit reserve_future_memory_future; try apply STEPSRC; eauto.\n      i. des. inv LOCAL. ss.\n\n      hexploit sim_fulfill_forget_update; try apply SELF; try apply PROMISE0; eauto.\n      { ii. eapply NOREAD. left. eauto. }\n      { i. eapply EXCLUSIVE in OTHER. des.\n        eapply reserve_future_memory_unchangable in UNCH; eauto. }\n      { i. eapply EXCLUSIVEEXTRA in OTHER. des.\n        eapply reserve_future_memory_unchangable in OTHER; eauto. }\n      { i. eapply CONSISTENT in GETTGT. ss.\n        eapply TimeFacts.le_lt_lt; [|eapply GETTGT].\n        unfold TimeMap.join, TimeMap.singleton. etrans; [|eapply Time.join_r].\n        setoid_rewrite LocFun.add_spec_eq. refl. }\n\n      i. des.\n      eexists self'0, extra_self'0, (Local.mk _ prom_src0), prom_src0, mem_src0, mem_src1, prom_src2, mem_src2, Memory.op_kind_add.\n      splits; eauto.\n      { eapply reserve_future_memory_trans; eauto. }\n      { econs; eauto; ss. ii. des_ifs.\n        eapply reserve_future_concrete_same_promise2 in GET; eauto.\n        eapply reserve_future_concrete_same_promise2 in GET; eauto.\n        set (PROM:= (sim_promise_contents PROMS) loc t).\n        rewrite GET in *. inv PROM; ss. exploit RELEASE; eauto.\n      }\n      { econs; eauto. }\n    }\n    { hexploit (@Memory.remove_exists\n                  prom_src' loc from to\n                  (Message.concrete val (TView.write_released tvw sc loc to releasedm ord))).\n      { set (PROM:= (sim_promise_contents PROMISE0) loc to).\n        eapply Memory.remove_get0 in REMOVE. des.\n        rewrite GET in *. inv PROM; ss. }\n      intros [prom_src'' REMOVESRC]. esplits.\n      - econs 1.\n      - econs; ss.\n        + econs; eauto.\n        + ii. set (PROM:=(sim_promise_contents PROMS) loc t).\n          rewrite GET in *. inv PROM; ss.\n          exploit RELEASE; eauto.\n      - econs 1.\n      - eauto.\n      - econs; auto. econs.\n        { ii. set (PROM:=(sim_promise_contents PROMISE0) loc0 ts).\n          erewrite (@Memory.remove_o prom_src''); eauto.\n          erewrite (@Memory.remove_o promises2); eauto. des_ifs.\n          ss. des; subst. econs 2; eauto.\n          ii. inv PROM; clarify; try by (eapply NEXTRA; eauto).\n          eapply Memory.remove_get0 in REMOVESRC. des. rewrite GET in *. clarify.\n        }\n        { apply PROMISE0. }\n        { i. set (PROM:=(sim_promise_extra PROMISE0) loc0 ts SELF0). des.\n          esplits; eauto. erewrite (@Memory.remove_o prom_src''); eauto.\n          des_ifs. ss. des; clarify. exfalso.\n          eapply Memory.remove_get0 in REMOVESRC. des. clarify. }\n    }\n  Qed.\n\n  Lemma reserving_trace_silent tr\n        (RESERVING: reserving_trace tr)\n    :\n      List.Forall (fun lce => ThreadEvent.get_machine_event (snd lce) = MachineEvent.silent) tr.\n  Proof.\n    induction RESERVING; eauto. econs; eauto.\n    unfold ThreadEvent.is_reservation_event in *. des_ifs.\n  Qed.\n\n  Lemma sim_thread_step_silent' others self extra_others extra_self\n        lang st lc_src lc_tgt sc mem_src mem_tgt pf e_tgt\n        st' lc_tgt' sc' mem_tgt' views views'\n        (STEPTGT: @JThread.step lang pf e_tgt (Thread.mk _ st lc_tgt sc mem_tgt) (Thread.mk _ st' lc_tgt' sc' mem_tgt') views views')\n        (NOREAD: no_read_msgs others e_tgt)\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LOCALSRC: Local.wf lc_src mem_src)\n        (LOCALTGT: Local.wf lc_tgt mem_tgt)\n        (SIM: sim_local self extra_self lc_src lc_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views loc ts))\n\n        (EVENT: ThreadEvent.get_machine_event e_tgt = MachineEvent.silent)\n    :\n      exists tr self' extra_self' lc_src' mem_src',\n        (<<STEPSRC: Trace.steps tr (Thread.mk _ st lc_src sc mem_src) (Thread.mk _ st' lc_src' sc' mem_src')>>) /\\\n        (<<MEM: sim_memory L times (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src' mem_tgt'>>) /\\\n        (<<SIM: sim_local self' extra_self' lc_src' lc_tgt'>>) /\\\n        (<<SILENT: List.Forall (fun lce => ThreadEvent.get_machine_event (snd lce) = MachineEvent.silent) tr>>)\n  .\n  Proof.\n    inv STEPTGT. inv STEP; ss.\n    - dup STEP0. inv STEP0.\n      assert (SEMICLOSED: semi_closed_message msg mem_src loc to).\n      { destruct msg; econs. hexploit PROMISE; eauto.\n        i. inv H; econs.\n        destruct (classic (views' loc to = views loc to)).\n        - rewrite H in *.\n          inv MEMSRC. eapply joined_view_semi_closed in JOINED0; eauto.\n        - exploit VIEWSLE; eauto. i. des. ss.\n          inv MEMSRC. eapply joined_view_semi_closed; cycle 1; eauto.\n          rewrite VIEW. econs.\n          + eapply semi_closed_view_join.\n            * eapply closed_view_semi_closed.\n              inv LOCALSRC. inv LOCAL. inv SIM. eapply TVIEW_CLOSED.\n            * eapply semi_closed_view_singleton; eauto.\n          + eapply List.Forall_forall.\n            i. eapply all_join_views_in_iff in H0. des. subst.\n            eapply List.Forall_forall in IN; eauto. ss.\n            erewrite View.join_comm. eapply join_singleton_semi_closed_view; eauto.\n            eapply memory_get_ts_le in GET. auto.\n      }\n\n      destruct (classic (L loc)).\n      + hexploit sim_promise_step_forget; eauto. i. des.\n        { destruct lc_src. ss. exploit reserve_future_memory_steps; eauto. i. des.\n          eexists _, self', extra_self', (Local.mk _ _), mem_src'. splits; eauto.\n          eapply reserving_trace_silent; eauto. }\n        { esplits; [|eauto|eauto|].\n          - econs; eauto. econs 1. econs; eauto.\n          - econs; eauto.\n        }\n      + hexploit sim_promise_step_normal; eauto.\n        i. des.\n        eexists [(_, ThreadEvent.promise loc from to msg kind)],\n        self, extra_self, lc_src', mem_src'.\n        splits; ss.\n        * econs 2; [|econs 1|ss]. econs 1. econs; eauto.\n        * econs; ss.\n    - inv STEP0. inv LOCAL.\n      + eexists [(_, ThreadEvent.silent)], self, extra_self, lc_src, mem_src. splits; ss.\n        * econs 2; [|econs 1|ss]. econs 2. econs; eauto.\n        * econs; ss.\n      + exploit sim_read_step; eauto. i. des.\n        eexists [(_, ThreadEvent.read loc ts val released ord)],\n        self, extra_self, lc_src', mem_src. splits; ss.\n        * econs 2; [|econs 1|ss]. econs 2. econs; eauto.\n        * econs; ss.\n      + destruct (classic (L loc)).\n        * exploit sim_write_step_forget; eauto. i. des.\n          destruct lc_src, lc_src'. ss.\n          eapply reserve_future_memory_steps in FUTURE0. des.\n          eapply reserve_future_memory_steps in FUTURE1. des.\n          esplits; [|eauto|eauto|].\n          { eapply Trace.steps_app.\n            { eapply STEPS. }\n            eapply Trace.steps_app.\n            { econs 2; [|econs 1|ss]. econs 2. econs; cycle 1.\n              - econs 3. eauto.\n              - ss. eauto. }\n            eauto.\n          }\n          { eapply Forall_app.\n            - eapply reserving_trace_silent; eauto.\n            - eapply Forall_app.\n              + econs; eauto.\n              + eapply reserving_trace_silent; eauto.\n          }\n        * hexploit sim_write_step_normal; eauto. i. des.\n          eexists [(_, ThreadEvent.write loc from to val _ ord)],\n          self, extra_self, lc_src', mem_src'.\n          splits; ss.\n          { econs 2; [|econs 1|ss]. econs 2. econs; eauto. }\n          { econs; ss. }\n      + exploit sim_read_step; eauto.\n        { eapply PromiseConsistent.write_step_promise_consistent; eauto. } i. des.\n        exploit Local.read_step_future; try apply LOCAL1; eauto. i. des.\n        exploit Local.read_step_future; try apply STEPSRC; eauto. i. des.\n        dup STEPSRC. inv STEPSRC. ss.\n        destruct (classic (L loc)).\n        * hexploit sim_update_step_forget; eauto. i. des. ss.\n          destruct lc_src, lc_src'.\n          eapply reserve_future_read_commute in STEPSRC0; eauto.\n          eapply reserve_future_memory_steps in FUTURE0. des.\n          eapply reserve_future_memory_steps in FUTURE1. des.\n          esplits; [|eauto|eauto|].\n          { eapply Trace.steps_app.\n            { eapply STEPS. }\n            eapply Trace.steps_app.\n            { econs 2; [|econs 1|ss]. econs 2. econs; cycle 1.\n              - econs 4; eauto.\n              - ss. eauto. }\n            eauto.\n          }\n          { eapply Forall_app.\n            - eapply reserving_trace_silent; eauto.\n            - eapply Forall_app.\n              + econs; eauto.\n              + eapply reserving_trace_silent; eauto.\n          }\n        * hexploit sim_write_step_normal; eauto. i. des.\n          eexists [(_, ThreadEvent.update loc tsr tsw valr valw releasedr releasedw ordr ordw)],\n          self, extra_self, lc_src', mem_src'. splits; ss.\n          { econs 2; [|econs 1|ss]. econs 2. econs; eauto. }\n          { econs; ss. }\n      + exploit sim_fence_step; eauto. i. des.\n        eexists [(_, ThreadEvent.fence ordr ordw)],\n        self, extra_self, lc_src', mem_src. splits; ss.\n        * econs 2; [|econs 1|ss]. econs 2. econs; eauto.\n        * econs; ss.\n      + ss.\n      + ss.\n  Qed.\n\n  Inductive sim_local_strong\n            (self: Loc.t -> Time.t -> Prop)\n            (extra extra_all: Loc.t -> Time.t -> Time.t -> Prop)\n    :\n      forall (lc_src lc_tgt: Local.t), Prop :=\n  | sim_local_strong_intro\n      tvw prom_src prom_tgt\n      (PROMS: sim_promise_strong self extra extra_all prom_src prom_tgt)\n    :\n      sim_local_strong self extra extra_all (Local.mk tvw prom_src) (Local.mk tvw prom_tgt)\n  .\n  Hint Constructors sim_local_strong.\n\n  Lemma sim_local_strong_sim_local\n        self extra extra_all lc_src lc_tgt\n        (SIM: sim_local_strong self extra extra_all lc_src lc_tgt)\n    :\n      sim_local self extra lc_src lc_tgt.\n  Proof.\n    inv SIM. econs; eauto. eapply sim_promise_strong_sim_promise; eauto.\n  Qed.\n\n  Lemma sim_thread_step_silent others self extra_others extra_self\n        lang st lc_src lc_tgt sc mem_src mem_tgt pf e_tgt\n        st' lc_tgt' sc' mem_tgt' views views'\n        (STEPTGT: @JThread.step lang pf e_tgt (Thread.mk _ st lc_tgt sc mem_tgt) (Thread.mk _ st' lc_tgt' sc' mem_tgt') views views')\n        (NOREAD: no_read_msgs others e_tgt)\n        (MEM: sim_memory L times (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LOCALSRC: Local.wf lc_src mem_src)\n        (LOCALTGT: Local.wf lc_tgt mem_tgt)\n        (SIM: sim_local self extra_self lc_src lc_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views loc ts))\n\n        (EVENT: ThreadEvent.get_machine_event e_tgt = MachineEvent.silent)\n    :\n      exists tr self' extra_self' lc_src' mem_src',\n        (<<STEPSRC: Trace.steps tr (Thread.mk _ st lc_src sc mem_src) (Thread.mk _ st' lc_src' sc' mem_src')>>) /\\\n        (<<MEM: sim_memory L times (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src' mem_tgt'>>) /\\\n        (<<SIM: sim_local_strong self' extra_self' (extra_others \\\\3// extra_self') lc_src' lc_tgt'>>) /\\\n        (<<JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src' loc ts) (views' loc ts)>>) /\\\n        (<<SILENT: List.Forall (fun lce => ThreadEvent.get_machine_event (snd lce) = MachineEvent.silent) tr>>)\n  .\n  Proof.\n    hexploit sim_thread_step_silent'; eauto. i. des.\n    exploit Thread.step_future.\n    { inv STEPTGT. eauto. } all: ss. i. des.\n    exploit Trace.steps_future; eauto. i. des. ss.\n    exploit sim_promise_weak_strengthen; eauto.\n    { eapply WF2. }\n    { eapply WF0. }\n    { eapply WF0. }\n    { eapply WF0. }\n    { inv SIM0. ss. }\n    i. des. destruct lc_src'. ss.\n    exploit reserve_future_memory_steps; eauto. i. des.\n    exists (tr++tr0). esplits; eauto.\n    { eapply Trace.steps_trans; eauto. }\n    { inv SIM0. econs; eauto. }\n    assert (JOINED0: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src' loc ts) (views' loc ts)).\n    { inv STEPTGT. ss.\n      i. destruct (classic (views' loc ts = views loc ts)).\n      { rewrite H.\n        eapply List.Forall_impl; eauto.\n        i. ss. eapply semi_closed_view_future; eauto. eapply Memory.future_future_weak; eauto. }\n      { hexploit VIEWSLE; eauto. i. des.\n        set (MEM2:=(sim_memory_contents MEM0) loc ts). rewrite GET in MEM2. inv MEM2; ss.\n        { rewrite VIEW. econs.\n          - eapply closed_view_semi_closed. eapply Memory.join_closed_view.\n            + inv WF0. inv SIM0. ss. eapply TVIEW_CLOSED.\n            + inv CLOSED0. eapply Memory.singleton_ur_closed_view; eauto.\n          - apply List.Forall_forall.\n            i. eapply all_join_views_in_iff in H0. des. subst.\n            eapply List.Forall_forall in IN; eauto. ss.\n            eapply semi_closed_view_future in IN.\n            2: { eapply Memory.future_future_weak; eauto. }\n            erewrite View.join_comm. eapply join_singleton_semi_closed_view; eauto.\n            eapply memory_get_ts_le in GET. ss.\n        }\n        { rewrite VIEW. econs.\n          - erewrite View.join_comm. eapply join_singleton_semi_closed_view.\n            + instantiate (1:=Time.bot). eapply closed_view_semi_closed.\n              inv WF0. inv SIM0. ss. eapply TVIEW_CLOSED.\n            + eapply Time.bot_spec.\n          - apply List.Forall_forall.\n            i. eapply all_join_views_in_iff in H0. des. subst.\n            eapply List.Forall_forall in IN; eauto. ss.\n            eapply semi_closed_view_future in IN.\n            2: { eapply Memory.future_future_weak; eauto. }\n            erewrite View.join_comm. eapply join_singleton_semi_closed_view; eauto.\n            eapply memory_get_ts_le in GET. ss.\n        }\n      }\n    }\n    { i. eapply List.Forall_impl; eauto.\n      i. ss. eapply semi_closed_view_future in H; eauto.\n      eapply Memory.future_future_weak; eauto.\n      eapply reserve_future_future; eauto. }\n    { eapply Forall_app; eauto.\n      eapply reserving_trace_silent; eauto. }\n  Qed.\n\n  Lemma sim_fence_step_strong self extra extra_all lc_src lc_tgt sc ordr ordw\n        sc' lc_tgt'\n        (STEPTGT: Local.fence_step lc_tgt sc ordr ordw lc_tgt' sc')\n        (LOCAL: sim_local_strong self extra extra_all lc_src lc_tgt)\n    :\n      exists lc_src',\n        (<<STEPSRC: Local.fence_step lc_src sc ordr ordw lc_src' sc'>>) /\\\n        (<<SIM: sim_local_strong self extra extra_all lc_src' lc_tgt'>>)\n  .\n  Proof.\n    inv LOCAL. inv STEPTGT. esplits.\n    - econs; ss; eauto.\n      + ii. set (PROM:= (sim_promise_strong_contents PROMS) loc t).\n        rewrite GET in *. inv PROM; ss.\n        exploit RELEASE; eauto.\n      + i. eapply sim_promise_strong_sim_promise in PROMS.\n        eapply sim_promise_bot in PROMS; eauto.\n    - econs; ss; eauto.\n  Qed.\n\nEnd SIM.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/ldrfpf/LocalPFThreadTime.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.3276682876897044, "lm_q1q2_score": 0.23232308550659897}}
{"text": "Require Import RamifyCoq.CertiGC.gc_spec.\n\nLtac hif_tac H :=\n  match type of H with context [if ?a then _ else _] => destruct a eqn: ?H end.\n\nLemma body_Is_block: semax_body Vprog Gprog f_Is_block Is_block_spec.\nProof.\n  start_function.\n  assert (eqb_type\n            (Tpointer Tvoid {| attr_volatile := false; attr_alignas := Some 2%N |})\n            int_or_ptr_type = true) by\n      (rewrite eqb_type_spec; unfold int_or_ptr_type; f_equal). forward_call x.\n  forward. hif_tac H1. 2: inversion H0. destruct x; simpl in *; entailer!.\nQed.\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/CertiGC/verif_Is_block.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23222279986964123}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\n\nFrom Ltac2 Require Import Ltac2.\n\nRequire Import Equations.Prop.Equations.\n\nFrom Coq Require Import String Ensembles Setoid Btauto.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Logic.Classical_Prop.\nFrom Coq.Logic Require Import FunctionalExtensionality Eqdep_dec.\nFrom Coq.Classes Require Import Morphisms_Prop.\nFrom Coq.Unicode Require Import Utf8.\nFrom Coq.micromega Require Import Lia.\n\nFrom stdpp Require Import base fin_sets sets propset proof_irrel option list coGset finite infinite gmap.\n\nFrom MatchingLogic Require Import\n  Logic\n  DerivedOperators_Syntax\n  ProofMode.MLPM\n.\nFrom MatchingLogic.Theories Require Import Definedness_Syntax Definedness_ProofSystem.\nFrom MatchingLogic.Utils Require Import stdpp_ext.\nImport extralibrary.\n\nImport MatchingLogic.Logic.Notations.\nImport MatchingLogic.DerivedOperators_Syntax.Notations.\nImport MatchingLogic.Syntax.BoundVarSugar.\n\nSet Default Proof Mode \"Classic\".\n\nImport Notations.\n\nOpen Scope ml_scope.\nOpen Scope string_scope.\nOpen Scope list_scope.\n\n(* TODO: These 3 lemmas are used only here as is, but maybe it should be somewhere else? *)\nLocal Lemma impl_ctx_impl {Σ : Signature} Γ ctx ϕ ψ i :\n  well_formed ϕ ->\n  well_formed ψ ->\n  well_formed (pcPattern ctx) ->\n  ProofInfoLe AnyReasoning i ->\n  Γ ⊢i ϕ ---> ψ using i ->\n  (is_positive_context ctx ->\n  Γ ⊢i (emplace ctx ϕ) ---> (emplace ctx ψ) using i)\n  *\n  (is_negative_context ctx ->\n  Γ ⊢i (emplace ctx ψ) ---> (emplace ctx ϕ) using i).\nProof.\n  intros wfϕ wfψ wfc pile H.\n\n  remember (size' (pcPattern ctx)) as sz.\n  assert (Hsz: size' (pcPattern ctx) <= sz) by lia.\n  clear Heqsz.\n\n  unfold emplace.\n\n  destruct ctx as [cvar cpatt].\n  simpl in *.\n\n  generalize dependent cpatt.\n\n  induction sz.\n  {\n    destruct cpatt; simpl in *; lia.\n  }\n\n  intros cpatt wfc Hsz.\n\n  split.\n  {\n    intro Hp.\n    destruct cpatt; simpl in *.\n\n    (* trivial cases *)\n    2,5,7: aapply A_impl_A;[eapply pile_trans;[|apply pile];try_solve_pile;try_solve_pile|wf_auto2].\n    (* not well formed cases*)\n    2,3: cbv in wfc; discriminate wfc.\n\n    + destruct decide.\n      { assumption. }\n      { gapply A_impl_A. eapply pile_trans;[|apply pile]; try_solve_pile. wf_auto2. }\n\n    + pose proof (IH1 := IHsz cpatt1).\n      feed specialize IH1.\n      { wf_auto2. }\n      { lia. }\n      destruct IH1 as [IH1 _]. feed specialize IH1.\n      {\n        clear -Hp. unfold is_positive_context in *. simpl in *.\n        unfold evar_has_negative_occurrence in Hp.\n        simpl in Hp. fold evar_has_negative_occurrence in Hp.\n        rewrite negb_or in Hp. destruct_and! Hp.\n        assumption.\n      }\n      pose proof (IH2 := IHsz cpatt2).\n      feed specialize IH2.\n      { wf_auto2. }\n      { lia. }\n      destruct IH2 as [IH2 _]. feed specialize IH2.\n      {\n        clear -Hp. unfold is_positive_context in *. simpl in *.\n        unfold evar_has_negative_occurrence in Hp.\n        simpl in Hp. fold evar_has_negative_occurrence in Hp.\n        rewrite negb_or in Hp. destruct_and! Hp.\n        assumption.\n      }\n\n      eapply syllogism_meta.\n      4: {\n        unshelve(eapply Framing_left;[| |apply IH1]).\n        { wf_auto2. }\n        { try_solve_pile. }\n      }\n      { wf_auto2. }\n      { wf_auto2. }\n      { wf_auto2. }\n      \n      unshelve(eapply Framing_right).\n      { wf_auto2. }\n      { eapply pile_trans;[|apply pile]. apply pile_any. }\n      apply IH2.\n\n    + unfold is_positive_context in Hp. simpl in Hp.\n      unfold evar_has_negative_occurrence in Hp. simpl in Hp.\n      fold evar_has_positive_occurrence evar_has_negative_occurrence in Hp.\n      rewrite negb_orb in Hp.\n      destruct_and! Hp.\n\n      pose proof (IH := IHsz (cpatt2)).\n      feed specialize IH.\n      { wf_auto2. }\n      { lia. }\n      destruct IH as [IH _]. feed specialize IH.\n      {\n        unfold is_positive_context. simpl. assumption.\n      }\n\n      toMLGoal.\n      { wf_auto2. }\n      mlAdd IH as \"IH\". clear IH.\n      mlIntro \"H\".\n      mlIntro \"Hc\".\n      mlApply \"IH\". mlClear \"IH\".\n      mlApply \"H\". mlClear \"H\".\n      fromMLGoal.\n\n      pose proof (IH := IHsz cpatt1).\n      feed specialize IH.\n      { wf_auto2. }\n      { lia. }\n      destruct IH as [_ IH]. feed specialize IH.\n      { unfold is_negative_context. simpl. assumption. }\n      assumption.\n\n    + remember (evar_fresh_s ({[cvar]} ∪ free_evars cpatt ∪ free_evars ψ ∪ free_evars ϕ)) as x.\n      pose proof (IH := IHsz (evar_open x 0 cpatt)).\n      feed specialize IH.\n      { wf_auto2. }\n      { rewrite evar_open_size'. lia. }\n      destruct IH as [IH _]. feed specialize IH.\n      {\n        clear -Hp Heqx. unfold is_positive_context in *. simpl in *.\n        unfold evar_has_negative_occurrence in Hp.\n        simpl in Hp. fold evar_has_negative_occurrence in Hp.\n        rewrite <- neg_occurrence_bevar_subst.\n        + assumption.\n        + subst. solve_fresh_neq.\n      }\n      rewrite <- evar_quantify_evar_open with (n := 0) (phi := cpatt^[[evar:cvar↦ϕ]]) (x := x).\n      rewrite <- evar_quantify_evar_open with (n := 0) (phi := cpatt^[[evar:cvar↦ψ]]) (x := x).\n      apply ex_quan_monotone.\n      { eapply pile_trans;[|apply pile]. try_solve_pile. }\n      unfold evar_open.\n      unfold evar_open in IH.\n\n      rewrite free_evar_subst_free_evar_subst.\n      { wf_auto2. }\n      { subst x. simpl.\n        rewrite not_elem_of_singleton.\n        solve_fresh_neq.\n      }\n\n      rewrite free_evar_subst_free_evar_subst.\n      { wf_auto2. }\n      {\n        rewrite not_elem_of_singleton.\n        solve_fresh_neq.\n      }\n\n      assumption.\n\n      {\n        subst x; clear.\n        eapply evar_is_fresh_in_richer'.\n        2: { apply set_evar_fresh_is_fresh'. }\n        pose proof (Hfree := free_evars_free_evar_subst cpatt ψ cvar).\n        set_solver.\n      }\n      { wf_auto2. }\n      {\n        subst x. \n        eapply evar_is_fresh_in_richer'.\n        2: { apply set_evar_fresh_is_fresh'. }\n        pose proof (Hfree := free_evars_free_evar_subst cpatt ϕ cvar).\n        clear -Hfree.\n        set_solver.\n      }\n      { wf_auto2. }\n\n    + remember (svar_fresh_s (free_svars cpatt ∪ free_svars ψ ∪ free_svars ϕ ∪ free_svars cpatt^[[evar:cvar↦ϕ]] ∪ free_svars cpatt^[[evar:cvar↦ψ]])) as X.\n      pose proof (IH := IHsz (svar_open X 0 cpatt)).\n      feed specialize IH.\n      { wf_auto2. }\n      { rewrite svar_open_size'. lia. }\n      destruct IH as [IH _]. feed specialize IH.\n      {\n        clear -Hp. unfold is_positive_context in *. simpl in *.\n        cbn in Hp.\n        rewrite <- neg_occurrence_bsvar_subst.\n        assumption.\n      }\n      rewrite <- svar_quantify_svar_open with (n := 0) (phi := cpatt^[[evar:cvar↦ϕ]]) (X := X).\n      rewrite <- svar_quantify_svar_open with (n := 0) (phi := cpatt^[[evar:cvar↦ψ]]) (X := X).\n      apply mu_monotone.\n      { eapply pile_trans;[|apply pile]. try_solve_pile. }\n      {\n        unfold is_positive_context in Hp. simpl in Hp. \n        unfold well_formed in wfc. simpl in wfc.\n        destruct_and! wfc.\n        pose proof (Hneg := free_evar_subst_preserves_no_negative_occurrence cvar cpatt ϕ 0).\n        feed specialize Hneg.\n        { wf_auto2. }\n        { assumption. }\n        cbn in Hp.\n        apply positive_negative_occurrence_db_named.\n        { assumption. }\n        apply fresh_svar_no_neg.\n        subst.\n        clear.\n        eapply svar_is_fresh_in_richer'.\n        2: apply set_svar_fresh_is_fresh'.\n        set_solver.\n      }\n      {\n        unfold is_positive_context in Hp. simpl in Hp. \n        unfold well_formed in wfc. simpl in wfc.\n        destruct_and! wfc.\n        pose proof (Hneg := free_evar_subst_preserves_no_negative_occurrence cvar cpatt ψ 0).\n        feed specialize Hneg.\n        { wf_auto2. }\n        { assumption. }\n        cbn in Hp.\n        apply positive_negative_occurrence_db_named.\n        { assumption. }\n        apply fresh_svar_no_neg.\n        subst.\n        clear.\n        eapply svar_is_fresh_in_richer'.\n        2: apply set_svar_fresh_is_fresh'.\n        set_solver.\n      }\n      unfold svar_open.\n      unfold svar_open in IH.\n      rewrite <- free_evar_subst_bsvar_subst.\n      rewrite <- free_evar_subst_bsvar_subst.\n      apply IH.\n      { wf_auto2. }\n      { unfold evar_is_fresh_in. set_solver. }\n      { wf_auto2. }\n      { unfold evar_is_fresh_in. set_solver. }\n      {\n        clear -HeqX.\n        intro Hcontra.\n        pose proof (Hfree := free_svars_free_evar_subst cpatt cvar ψ).\n        assert (X ∉ free_svars cpatt /\\ X ∉ free_svars ψ).\n        {\n          subst.\n          split.\n          {\n            eapply svar_is_fresh_in_richer'.\n            2: apply set_svar_fresh_is_fresh'.\n            clear.\n            set_solver.\n          }\n          {\n            eapply svar_is_fresh_in_richer'.\n            2: apply set_svar_fresh_is_fresh'.\n            clear.\n            set_solver.\n          }\n        }\n        set_solver.\n      }\n      { wf_auto2. }\n      {\n        subst X.\n        eapply svar_is_fresh_in_richer'.\n        2: apply set_svar_fresh_is_fresh'.\n        clear.\n        set_solver.\n      }\n      { wf_auto2. }\n  }\n  {\n    intro Hp.\n    destruct cpatt; simpl in *.\n\n    (* trivial cases *)\n    2,5,7: aapply A_impl_A;[eapply pile_trans;[|apply pile];try_solve_pile;try_solve_pile|wf_auto2].\n    (* not well formed cases*)\n    2,3: cbv in wfc; discriminate wfc.\n\n    + destruct decide.\n      {\n        subst.\n        unfold is_negative_context in Hp. cbn in Hp.\n        destruct decide in Hp; simpl in Hp; congruence.\n      }\n      { gapply A_impl_A. eapply pile_trans;[|apply pile]; try_solve_pile. wf_auto2. }\n\n    + pose proof (IH1 := IHsz cpatt1).\n      feed specialize IH1.\n      { wf_auto2. }\n      { lia. }\n      destruct IH1 as [_ IH1]. feed specialize IH1.\n      {\n        clear -Hp. unfold is_negative_context in *. simpl in *.\n        cbn in Hp.\n        rewrite negb_or in Hp. destruct_and! Hp.\n        assumption.\n      }\n      pose proof (IH2 := IHsz cpatt2).\n      feed specialize IH2.\n      { wf_auto2. }\n      { lia. }\n      destruct IH2 as [_ IH2]. feed specialize IH2.\n      {\n        clear -Hp. unfold is_negative_context in *. simpl in *.\n        cbn in Hp.\n        rewrite negb_or in Hp. destruct_and! Hp.\n        assumption.\n      }\n\n      eapply syllogism_meta.\n      4: {\n        unshelve(eapply Framing_left;[| |apply IH1]).\n        { wf_auto2. }\n        { eapply pile_trans;[|apply pile]. apply pile_any. }\n      }\n      { wf_auto2. }\n      { wf_auto2. }\n      { wf_auto2. }\n      \n      unshelve(eapply Framing_right).\n      { wf_auto2. }\n      { eapply pile_trans;[|apply pile]. apply pile_any. }\n      apply IH2.\n\n    + unfold is_negative_context in Hp. simpl in Hp.\n      unfold evar_has_positive_occurrence in Hp. simpl in Hp.\n      fold evar_has_positive_occurrence evar_has_negative_occurrence in Hp.\n      rewrite negb_orb in Hp.\n      destruct_and! Hp.\n\n      pose proof (IH := IHsz (cpatt2)).\n      feed specialize IH.\n      { wf_auto2. }\n      { lia. }\n      destruct IH as [_ IH]. feed specialize IH.\n      {\n        unfold is_negative_context. simpl. assumption.\n      }\n\n      toMLGoal.\n      { wf_auto2. }\n      mlAdd IH as \"IH\". clear IH.\n      mlIntro \"H\".\n      mlIntro \"Hc\".\n      mlApply \"IH\". mlClear \"IH\".\n      mlApply \"H\". mlClear \"H\".\n      fromMLGoal.\n\n      pose proof (IH := IHsz cpatt1).\n      feed specialize IH.\n      { wf_auto2. }\n      { lia. }\n      destruct IH as [IH _]. feed specialize IH.\n      { unfold is_positive_context. simpl. assumption. }\n      assumption.\n\n    + remember (evar_fresh_s ({[cvar]} ∪ free_evars cpatt ∪ free_evars ψ ∪ free_evars ϕ)) as x.\n      pose proof (IH := IHsz (evar_open x 0 cpatt)).\n      feed specialize IH.\n      { wf_auto2. }\n      { rewrite evar_open_size'. lia. }\n      destruct IH as [_ IH]. feed specialize IH.\n      {\n        clear -Hp Heqx. unfold is_negative_context in *. simpl in *.\n        cbn in Hp.\n        rewrite <- pos_occurrence_bevar_subst.\n        + assumption.\n        + subst. solve_fresh_neq.\n      }\n      rewrite <- evar_quantify_evar_open with (n := 0) (phi := cpatt^[[evar:cvar↦ϕ]]) (x := x).\n      rewrite <- evar_quantify_evar_open with (n := 0) (phi := cpatt^[[evar:cvar↦ψ]]) (x := x).\n      apply ex_quan_monotone.\n      { eapply pile_trans;[|apply pile]. try_solve_pile. }\n      unfold evar_open.\n      unfold evar_open in IH.\n\n      rewrite free_evar_subst_free_evar_subst.\n      { wf_auto2. }\n      {\n        rewrite not_elem_of_singleton.\n        solve_fresh_neq.\n      }\n\n      rewrite free_evar_subst_free_evar_subst.\n      { wf_auto2. }\n      {\n        rewrite not_elem_of_singleton.\n        solve_fresh_neq.\n      }\n\n      assumption.\n\n      {\n        subst x; clear.\n        eapply evar_is_fresh_in_richer'.\n        2: { apply set_evar_fresh_is_fresh'. }\n        pose proof (Hfree := free_evars_free_evar_subst cpatt ψ cvar).\n        set_solver.\n      }\n      { wf_auto2. }\n      {\n        subst x. \n        eapply evar_is_fresh_in_richer'.\n        2: { apply set_evar_fresh_is_fresh'. }\n        pose proof (Hfree := free_evars_free_evar_subst cpatt ϕ cvar).\n        clear -Hfree.\n        set_solver.\n      }\n      { wf_auto2. }\n\n    + remember (svar_fresh_s (free_svars cpatt ∪ free_svars ψ ∪ free_svars ϕ ∪ free_svars cpatt^[[evar:cvar↦ϕ]] ∪ free_svars cpatt^[[evar:cvar↦ψ]])) as X.\n      pose proof (IH := IHsz (svar_open X 0 cpatt)).\n      feed specialize IH.\n      { wf_auto2. }\n      { rewrite svar_open_size'. lia. }\n      destruct IH as [_ IH]. feed specialize IH.\n      {\n        clear -Hp. unfold is_negative_context in *. simpl in *.\n        cbn in Hp.\n        rewrite <- pos_occurrence_bsvar_subst.\n        assumption.\n      }\n      rewrite <- svar_quantify_svar_open with (n := 0) (phi := cpatt^[[evar:cvar↦ϕ]]) (X := X).\n      rewrite <- svar_quantify_svar_open with (n := 0) (phi := cpatt^[[evar:cvar↦ψ]]) (X := X).\n      apply mu_monotone.\n      { eapply pile_trans;[|apply pile]. try_solve_pile. }\n      {\n        unfold is_negative_context in Hp. simpl in Hp. \n        unfold well_formed in wfc. simpl in wfc.\n        destruct_and! wfc.\n        pose proof (Hneg := free_evar_subst_preserves_no_negative_occurrence cvar cpatt ψ 0).\n        feed specialize Hneg.\n        { wf_auto2. }\n        { assumption. }\n        cbn in Hp.\n        apply positive_negative_occurrence_db_named.\n        { assumption. }\n        apply fresh_svar_no_neg.\n        subst.\n        clear.\n        eapply svar_is_fresh_in_richer'.\n        2: apply set_svar_fresh_is_fresh'.\n        set_solver.\n      }\n      {\n        unfold is_negative_context in Hp. simpl in Hp. \n        unfold well_formed in wfc. simpl in wfc.\n        destruct_and! wfc.\n        pose proof (Hneg := free_evar_subst_preserves_no_negative_occurrence cvar cpatt ϕ 0).\n        feed specialize Hneg.\n        { wf_auto2. }\n        { assumption. }\n        cbn in Hp.\n        apply positive_negative_occurrence_db_named.\n        { assumption. }\n        apply fresh_svar_no_neg.\n        subst.\n        clear.\n        eapply svar_is_fresh_in_richer'.\n        2: apply set_svar_fresh_is_fresh'.\n        set_solver.\n      }\n      unfold svar_open.\n      unfold svar_open in IH.\n      rewrite <- free_evar_subst_bsvar_subst.\n      rewrite <- free_evar_subst_bsvar_subst.\n      apply IH.\n      { wf_auto2. }\n      { unfold evar_is_fresh_in. set_solver. }\n      { wf_auto2. }\n      { unfold evar_is_fresh_in. set_solver. }\n      {\n        clear -HeqX.\n        intro Hcontra.\n        pose proof (Hfree := free_svars_free_evar_subst cpatt cvar ψ).\n        assert (X ∉ free_svars cpatt /\\ X ∉ free_svars ψ).\n        {\n          subst.\n          split.\n          {\n            eapply svar_is_fresh_in_richer'.\n            2: apply set_svar_fresh_is_fresh'.\n            clear.\n            set_solver.\n          }\n          {\n            eapply svar_is_fresh_in_richer'.\n            2: apply set_svar_fresh_is_fresh'.\n            clear.\n            set_solver.\n          }\n        }\n        set_solver.\n      }\n      { wf_auto2. }\n      {\n        subst X.\n        eapply svar_is_fresh_in_richer'.\n        2: apply set_svar_fresh_is_fresh'.\n        clear.\n        set_solver.\n      }\n      { wf_auto2. }\n  }\nDefined.\n\nLemma impl_ctx_impl_pos {Σ : Signature} Γ ctx ϕ ψ i :\n  well_formed ϕ ->\n  well_formed ψ ->\n  well_formed (pcPattern ctx) ->\n  is_positive_context ctx ->\n  ProofInfoLe AnyReasoning i ->\n  Γ ⊢i ϕ ---> ψ using i ->\n  Γ ⊢i (emplace ctx ϕ) ---> (emplace ctx ψ) using i.\nProof.\n  intros wfϕ wfψ wfc Hp pile H.\n  pose proof (impl := impl_ctx_impl Γ ctx ϕ ψ i wfϕ wfψ wfc pile H).\n  destruct impl as [impl _].\n  apply impl in Hp.\n  assumption.\nDefined.\n\nLemma impl_ctx_impl_neg {Σ : Signature} Γ ctx ϕ ψ i :\n  well_formed ϕ ->\n  well_formed ψ ->\n  well_formed (pcPattern ctx) ->\n  is_negative_context ctx ->\n  ProofInfoLe AnyReasoning i ->\n  Γ ⊢i ϕ ---> ψ using i ->\n  Γ ⊢i (emplace ctx ψ) ---> (emplace ctx ϕ) using i.\nProof.\n  intros wfϕ wfψ wfc Hn pile H.\n  pose proof (impl := impl_ctx_impl Γ ctx ϕ ψ i wfϕ wfψ wfc pile H).\n  destruct impl as [_ impl].\n  apply impl in Hn.\n  assumption.\nDefined.\n\n(* Lemma 88 in in the matching mu logic paper.*)\nLemma pred_and_ctx_and {Σ : Signature} {syntax : Syntax} Γ ctx ϕ ψ:\n  Definedness_Syntax.theory ⊆ Γ ->\n  well_formed ϕ ->\n  well_formed ψ ->\n  well_formed (pcPattern ctx) ->\n  mu_in_evar_path (pcEvar ctx) (pcPattern ctx) 0 = false ->\n  Γ ⊢ is_predicate_pattern ψ ->\n  Γ ⊢ ψ and (emplace ctx ϕ) <---> ψ and (emplace ctx (ψ and ϕ)).\nProof.\n  intros HΓ wfm wfψ wfc Hmf Hp.\n\n  remember (size' (pcPattern ctx)) as sz.\n  assert (Hsz: size' (pcPattern ctx) <= sz) by lia.\n  clear Heqsz.\n\n  unfold emplace.\n\n  destruct ctx as [cvar cpatt].\n  simpl in *.\n\n  generalize dependent cpatt.\n\n  induction sz.\n  {\n    destruct cpatt; simpl in *; lia.\n  }\n\n  intros cpatt wfc Hmf Hsz.\n  destruct cpatt. all: simpl in *.\n\n  (* trivial cases *)\n  2,5,7: useBasicReasoning; apply pf_iff_equiv_refl; wf_auto2.\n  (* not well formed cases*)\n  2,3: cbv in wfc; discriminate wfc.\n\n  + destruct decide.\n    {\n      apply pf_iff_split; wf_auto2.\n      toMLGoal. wf_auto2. mlIntro. mlDestructAnd \"0\". mlSplitAnd.\n      { mlExact \"1\". }\n      {\n        mlSplitAnd.\n        * mlExact \"1\".\n        * mlExact \"2\".\n      }\n      toMLGoal. wf_auto2. mlIntro. mlDestructAnd \"0\". mlDestructAnd \"2\". mlSplitAnd.\n      * mlExact \"1\".\n      * mlExact \"3\".\n    }\n    { apply pf_iff_split;[wf_auto2|wf_auto2|aapply A_impl_A|aapply A_impl_A];wf_auto2; set_solver. }\n  + pose proof (IH1 := IHsz cpatt1).\n    feed specialize IH1.\n    { wf_auto2. }\n    {\n      unfold mu_in_evar_path in *.\n      simpl in Hmf.\n      case_match. \n      2: { lia. }\n      rewrite negb_false_iff.\n      eapply (introT (Nat.eqb_spec 0 _)).\n      lia.\n    }\n    {\n      lia.\n    }\n    pose proof (IH2 := IHsz cpatt2).\n    feed specialize IH2.\n    { wf_auto2. }\n    {\n      unfold mu_in_evar_path in *.\n      simpl in Hmf.\n      case_match. \n      2: { lia. }\n      rewrite negb_false_iff.\n      eapply (introT (Nat.eqb_spec 0 _)).\n      lia.\n    }\n    { lia. }\n\n    toMLGoal.\n    { wf_auto2. }\n    pose proof (Htmp := predicate_propagate_right_2 Γ\n      (cpatt2^[[evar:cvar↦ϕ]])\n      ψ\n      (cpatt1^[[evar:cvar↦ϕ]])\n      HΓ\n      ltac:(wf_auto2)\n      ltac:(wf_auto2)\n      ltac:(wf_auto2)\n      Hp\n    ).\n    mlRewrite Htmp at 1.\n    clear Htmp.\n    mlRewrite IH2 at 1.\n    pose proof (Htmp := predicate_propagate_right_2 Γ\n      (cpatt2^[[evar:cvar↦ψ and ϕ]])\n      ψ\n      (cpatt1^[[evar:cvar↦ϕ]])\n      HΓ\n      ltac:(wf_auto2)\n      ltac:(wf_auto2)\n      ltac:(wf_auto2)\n      Hp\n    ).\n    mlRewrite <- Htmp at 1.\n    clear Htmp.\n    pose proof (Htmp := predicate_propagate_left_2 Γ\n      (cpatt2^[[evar:cvar↦ψ and ϕ]])\n      ψ\n      (cpatt1^[[evar:cvar↦ϕ]])\n      HΓ\n      ltac:(wf_auto2)\n      ltac:(wf_auto2)\n      ltac:(wf_auto2)\n      Hp\n    ).\n    mlRewrite Htmp at 1.\n    clear Htmp.\n    mlRewrite IH1 at 1.\n    pose proof (Htmp := predicate_propagate_left_2 Γ\n      (cpatt2^[[evar:cvar↦ψ and ϕ]])\n      ψ\n      (cpatt1^[[evar:cvar↦ψ and ϕ]])\n      HΓ\n      ltac:(wf_auto2)\n      ltac:(wf_auto2)\n      ltac:(wf_auto2)\n      Hp\n    ).\n    mlRewrite <- Htmp at 1.\n    fromMLGoal.\n    useBasicReasoning.\n    apply pf_iff_equiv_refl.\n    wf_auto2.\n  + pose proof (IH1 := IHsz cpatt1).\n    feed specialize IH1.\n    { wf_auto2. }\n    {\n      unfold mu_in_evar_path in *.\n      simpl in Hmf.\n      case_match. \n      2: { lia. }\n      rewrite negb_false_iff.\n      eapply (introT (Nat.eqb_spec 0 _)).\n      lia.\n    }\n    { lia. }\n    pose proof (IH2 := IHsz cpatt2).\n    feed specialize IH2.\n    { wf_auto2. }\n    {\n      unfold mu_in_evar_path in *.\n      simpl in Hmf.\n      case_match. \n      2: { lia. }\n      rewrite negb_false_iff.\n      eapply (introT (Nat.eqb_spec 0 _)).\n      lia.\n    }\n    { lia. }\n    toMLGoal.\n    { wf_auto2. }\n    mlSplitAnd.\n    {\n      mlIntro \"H1\".\n      mlDestructAnd \"H1\" as \"Hψ\" \"Himp\".\n      mlSplitAnd.\n      { mlExact \"Hψ\". }\n      mlAdd IH2 as \"IH2\".\n      mlDestructAnd \"IH2\" as \"IH21\" \"IH22\".\n      mlIntro \"H\".\n      mlAssert (\"Htmp\": ((ψ and cpatt2^[[evar:cvar↦ψ and ϕ]]) ---> cpatt2^[[evar:cvar↦ψ and ϕ]])).\n      { wf_auto2. }\n      {\n        mlIntro \"H0\".\n        mlDestructAnd \"H0\" as \"H00\" \"H01\".\n        mlExact \"H01\".\n      }\n      mlApply \"Htmp\".\n      mlClear \"Htmp\".\n      mlAdd IH1 as \"IH1\".\n      mlDestructAnd \"IH1\" as \"IH11\" \"IH12\".\n      mlApply \"IH21\".\n      mlSplitAnd. mlExact \"Hψ\".\n      mlApply \"Himp\".\n      mlClear \"Himp\".\n      mlAssert (\"Htmp\": ((ψ and cpatt1^[[evar:cvar↦ϕ]]) ---> cpatt1^[[evar:cvar↦ϕ]])).\n      { wf_auto2. }\n      {\n        mlIntro \"H0\".\n        mlDestructAnd \"H0\" as \"H00\" \"H01\".\n        mlExact \"H01\".\n      }\n      mlApply \"Htmp\".\n      mlClear \"Htmp\".\n      mlApply \"IH12\".\n      mlSplitAnd.\n      { mlExact \"Hψ\". }\n      { mlExact \"H\". }\n    }\n    {\n      mlAdd IH1 as \"IH1\".\n      mlAdd IH2 as \"IH2\".\n      mlDestructAnd \"IH1\" as \"IH11\" \"IH12\".\n      mlDestructAnd \"IH2\" as \"IH21\" \"IH22\".\n      mlIntro \"H1\".\n      mlDestructAnd \"H1\" as \"Hψ\" \"H2\".\n      mlSplitAnd. mlExact \"Hψ\".\n      mlIntro \"H3\".\n      mlAssert (\"IH11'\": (ψ and cpatt1^[[evar:cvar↦ψ and ϕ]])).\n      { wf_auto2. }\n      {\n        mlApply \"IH11\".\n        mlSplitAnd.\n        { mlExact \"Hψ\". }\n        { mlExact \"H3\". }\n      }\n      mlClear \"IH11\".\n      mlAssert (\"H4\": (ψ and cpatt2^[[evar:cvar↦ψ and ϕ]])).\n      { wf_auto2. }\n      {\n        mlDestructAnd \"IH11'\" as \"IH11'1\" \"IH11'2\".\n        mlSplitAnd. mlExact \"Hψ\".\n        mlApply \"H2\".\n        mlExact \"IH11'2\".\n      }\n      mlAssert (\"IH22'\": (ψ and cpatt2^[[evar:cvar↦ϕ]])).\n      { wf_auto2. }\n      {\n        mlApply \"IH22\".\n        mlExact \"H4\".\n      }\n      mlClear \"IH22\".\n      mlDestructAnd \"IH22'\" as \"IH22'1\" \"IH22'2\".\n      mlExact \"IH22'2\".\n    }\n  + \n    toMLGoal.\n    { wf_auto2. }\n    mlApplyMeta extract_common_from_equivalence_1.\n    mlIntro \"Hψ\".\n    remember (evar_fresh_s (free_evars (cpatt ---> ϕ ---> ψ) ∪ {[cvar]})) as x0.\n    specialize (IHsz (cpatt^{evar:0↦x0})).\n    feed specialize IHsz.\n    {\n      wf_auto2.\n    }\n    {\n      unfold mu_in_evar_path in *.\n      simpl in Hmf.\n      case_match. \n      2: { lia. }\n      rewrite negb_false_iff.\n      eapply (introT (Nat.eqb_spec 0 _)).\n      rewrite evar_open_mu_depth.\n      { solve_fresh_neq. }\n      symmetry in H.\n      exact H.\n    }\n    {\n      rewrite evar_open_size'. lia.\n    }\n    mlSplitAnd; mlIntro \"H\".\n    {\n      mlDestructEx \"H\" as x0.\n      {\n        cbn. rewrite union_empty_r_L.\n        eapply evar_is_fresh_in_richer'.\n        2: { apply set_evar_fresh_is_fresh'. }\n        clear. cbn. set_solver.\n      }\n      {\n        cbn.\n        eapply evar_is_fresh_in_richer'.\n        2: { apply set_evar_fresh_is_fresh'. }\n        clear. cbn.\n        eapply transitivity. apply free_evars_free_evar_subst.\n        set_solver.\n      }\n      {\n        cbn.\n        eapply evar_is_fresh_in_richer'.\n        2: { apply set_evar_fresh_is_fresh'. }\n        clear. cbn.\n        eapply transitivity. apply free_evars_free_evar_subst.\n        set_solver.\n      }\n      mlExists x0. mlSimpl.\n      rewrite evar_open_free_evar_subst_swap.\n      { solve_fresh_neq. }\n      { wf_auto2. }\n      rewrite evar_open_free_evar_subst_swap.\n      { solve_fresh_neq. }\n      { wf_auto2. }\n\n      mlAssert (\"Hand\": (ψ and (cpatt^{evar:0↦x0}^[[evar:cvar↦ϕ]]))).\n      { wf_auto2. }\n      { mlSplitAnd; mlAssumption. }\n      mlClear \"Hψ\". mlClear \"H\".\n      mlRevertLast.\n      mlRewrite IHsz at 1.\n      mlIntro \"H\".\n      mlDestructAnd \"H\" as \"H1\" \"H2\".\n      mlExact \"H2\".\n    }\n    {\n      mlDestructEx \"H\" as x0.\n      {\n        cbn. rewrite union_empty_r_L.\n        eapply evar_is_fresh_in_richer'.\n        2: { apply set_evar_fresh_is_fresh'. }\n        clear. cbn. set_solver.\n      }\n      {\n        cbn.\n        eapply evar_is_fresh_in_richer'.\n        2: { apply set_evar_fresh_is_fresh'. }\n        clear. cbn.\n        eapply transitivity. apply free_evars_free_evar_subst.\n        set_solver.\n      }\n      {\n        cbn.\n        eapply evar_is_fresh_in_richer'.\n        2: { apply set_evar_fresh_is_fresh'. }\n        clear. cbn.\n        eapply transitivity. apply free_evars_free_evar_subst.\n        set_solver.\n      }\n      mlExists x0. mlSimpl.\n      rewrite evar_open_free_evar_subst_swap.\n      { solve_fresh_neq. }\n      { wf_auto2. }\n      rewrite evar_open_free_evar_subst_swap.\n      { solve_fresh_neq. }\n      { wf_auto2. }\n\n      mlAssert (\"Hand\": (ψ and (cpatt^{evar:0↦x0}^[[evar:cvar↦ψ and ϕ]]))).\n      { wf_auto2. }\n      { mlSplitAnd; mlAssumption. }\n      mlClear \"Hψ\". mlClear \"H\".\n      mlRevertLast.\n      mlRewrite <- IHsz at 1.\n      mlIntro \"H\".\n      mlDestructAnd \"H\" as \"H1\" \"H2\".\n      mlExact \"H2\".\n    }\n    \n  + \n    destruct (decide (cvar ∈ free_evars cpatt)).\n    {\n      unfold mu_in_evar_path in Hmf.\n      cbn in Hmf.\n      case_match.\n      2: { lia. }\n      rewrite maximal_mu_depth_to_S in H.\n      assumption.\n      inversion H.\n    }\n    {\n      rewrite free_evar_subst_no_occurrence.\n      { assumption. }\n      rewrite free_evar_subst_no_occurrence.\n      { assumption. }\n      useBasicReasoning.\n      apply pf_iff_equiv_refl.\n      wf_auto2.\n    }\nDefined.\n\n(* Lemma 89 *)\nLemma mu_and_predicate_propagation {Σ : Signature} {syntax : Syntax} Γ ϕ ψ X :\n  Definedness_Syntax.theory ⊆ Γ ->\n  well_formed (mu, ϕ) ->\n  well_formed ψ ->\n  (* \"Let X be a set variable that does not occur under any µ-binder in ϕ\" *)\n  (forall x, evar_is_fresh_in x ϕ ->\n    mu_in_evar_path x ϕ^[svar:0↦patt_free_evar x] 0 = false\n  ) ->\n  svar_is_fresh_in X ϕ ->\n  svar_is_fresh_in X ψ ->\n  Γ ⊢ is_predicate_pattern ψ ->\n  Γ ⊢ (mu, (ψ and ϕ)) <---> (ψ and (mu, ϕ)).\nProof.\n  intros HΓ wfm wfψ Hϕnomu fϕ fψ Hp.\n\n  assert (well_formed (mu , ψ and ϕ)).\n  {\n    clear -wfm wfψ.\n    unfold well_formed,well_formed_closed in *.\n    cbn in *. fold no_negative_occurrence_db_b.\n    destruct_and!.\n    split_and!; try reflexivity; try assumption.\n    {\n      apply wfc_impl_no_neg_occ.\n      assumption.\n    }\n    {\n      wf_auto2.\n    }\n  }\n\n  assert (svar_has_negative_occurrence X ψ^{svar:0↦X} = false).\n  {\n    clear -wfm wfψ fψ.\n    unfold well_formed,well_formed_closed in *.\n    cbn in *. fold no_negative_occurrence_db_b svar_has_negative_occurrence.\n    repeat rewrite orb_false_iff.\n    destruct_and!.\n    apply positive_negative_occurrence_db_named.\n    { apply wfc_impl_no_neg_occ. assumption. }\n    apply fresh_svar_no_neg.\n    apply fψ.\n  }\n\n  assert (svar_has_negative_occurrence X ψ^[svar:0↦patt_free_svar X] = false).\n  {\n    clear -wfm wfψ fψ.\n    unfold well_formed,well_formed_closed in *.\n    cbn in *. fold no_negative_occurrence_db_b svar_has_negative_occurrence.\n    destruct_and!.\n    apply svar_hno_bsvar_subst.\n    3: { apply fresh_svar_no_neg. exact fψ. }\n    {\n      cbn. congruence.\n    }\n    {\n      cbn. rewrite decide_eq_same. intros _.\n      apply wfc_impl_no_neg_occ. assumption.\n    }\n  }\n\n  assert (svar_has_negative_occurrence X ϕ^{svar:0↦X} = false).\n  {\n    wf_auto2.\n  }\n\n\n  apply pf_iff_split.\n  { assumption. }\n  { wf_auto2. }\n  \n  (* Makes set_solver work later in the proof. *)\n  unfold svar_is_fresh_in in fϕ, fψ.\n  {\n    toMLGoal.\n    {\n      wf_auto2.\n    }\n    mlIntro \"H\".\n    mlSplitAnd; fromMLGoal.\n    {\n      apply Knaster_tarski.\n      { try_solve_pile. }\n      { wf_auto2. }\n      unfold instantiate.\n      mlSimpl.\n      rewrite -> well_formed_bsvar_subst with (k := 0).\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro.\n      mlDestructAnd \"0\".\n      mlExact \"1\".\n      { lia. }\n      { wf_auto2. }\n    }\n    {\n      rewrite <- svar_quantify_svar_open with (n := 0) (phi := (ψ and ϕ)) (X := X).\n      rewrite <- svar_quantify_svar_open with (n := 0) (phi := ϕ) (X := X) at 2.\n      apply mu_monotone.\n      { try_solve_pile. }\n      {\n        unfold well_formed,well_formed_closed in *.\n        cbn in *. fold no_negative_occurrence_db_b svar_has_negative_occurrence.\n        repeat rewrite orb_false_iff.\n        repeat split; try reflexivity; try assumption.\n      }\n      { wf_auto2. }\n      {\n        unfold svar_open.\n        mlSimpl.\n        gapply pf_conj_elim_r.\n        { try_solve_pile. }\n        { wf_auto2. }\n        { wf_auto2. }\n      }\n      { assumption. }\n      { wf_auto2. }\n      { set_solver. }\n      { wf_auto2. }\n    }\n  }\n  \n  {\n    toMLGoal.\n    { wf_auto2. }\n    mlRewrite (useBasicReasoning AnyReasoning (@patt_and_comm Σ Γ ψ (mu , ϕ) wfψ wfm)) at 1.\n    fromMLGoal.\n    apply lhs_from_and.\n    { wf_auto2. }\n    { wf_auto2. }\n    { wf_auto2. }\n\n    apply Knaster_tarski.\n    { try_solve_pile. }\n    { wf_auto2. }\n\n    apply lhs_to_and.\n    { wf_auto2.\n      fold no_negative_occurrence_db_b.\n      apply wfc_impl_no_neg_occ. wf_auto2.\n    }\n    { wf_auto2. }\n    { wf_auto2. }\n    \n    toMLGoal.\n    { wf_auto2. fold no_negative_occurrence_db_b. apply wfc_impl_no_neg_occ. wf_auto2. }\n    assert (Htmp : is_true (well_formed (mu , ϕ) ^ [ψ ---> (mu , ψ and ϕ)])).\n    {\n      wf_auto2. fold no_negative_occurrence_db_b. apply wfc_impl_no_neg_occ. wf_auto2.\n    }\n    mlRewrite (useBasicReasoning AnyReasoning (@patt_and_comm Σ Γ ((mu , ϕ) ^ [ψ ---> (mu , ψ and ϕ)]) ψ Htmp wfψ)) at 1.\n    \n    mlIntro \"H\".\n    mlApplyMeta Pre_fixp.\n    unfold instantiate.\n    mlSimpl.\n    fromMLGoal.\n    rewrite -> well_formed_bsvar_subst with (φ := ψ) (k := 0).\n    2: auto.\n    2: wf_auto2.\n\n    remember (evar_fresh_s (free_evars ϕ)) as x.\n    pose proof (HH := pred_and_ctx_and Γ\n      {|\n        pcEvar := x;\n        pcPattern := ϕ^[svar:0↦patt_free_evar x];\n      |}\n      (ψ ---> (mu , ψ and ϕ)) ψ HΓ).\n    unfold emplace in HH. simpl in HH.\n    feed specialize HH.\n    { wf_auto2. }\n    { wf_auto2. }\n    { wf_auto2. }\n    {\n      apply Hϕnomu.\n      subst x. clear.\n      apply set_evar_fresh_is_fresh.\n    }\n    { assumption. }\n\n    assert (no_negative_occurrence_db_b 0 ψ = true).\n    {\n      apply wfc_impl_no_neg_occ. wf_auto2.\n    }\n\n    toMLGoal.\n    { wf_auto2. }\n    rewrite subst_svar_evar_svar in HH.\n    { subst x. solve_fresh. }\n    rewrite subst_svar_evar_svar in HH.\n    { subst x. solve_fresh. }\n    clear Htmp.\n    unshelve(epose proof (Htmp := @liftProofInfoLe _ _ _ _ AnyReasoning _ HH)).\n    { try_solve_pile. }\n    mlRewrite Htmp at 1.\n\n    clear Heqx x H Htmp.\n\n    remember (evar_fresh_s (free_evars ϕ)) as x.\n    pose proof (HH' := impl_ctx_impl_pos Γ\n      {|\n        pcEvar := x;\n        pcPattern := ϕ^[svar:0↦patt_free_evar x];\n      |}\n      (ψ and (ψ ---> (mu , ψ and ϕ)))\n      (mu , ψ and ϕ)\n      AnyReasoning\n      ).\n    unfold emplace in HH'. simpl in HH'.\n    feed specialize HH'.\n    { wf_auto2. }\n    { wf_auto2. }\n    { wf_auto2. }\n    { unfold is_positive_context. cbn.\n      unfold well_formed in wfm.\n      cbn in wfm.\n      destruct_and! wfm.\n      apply no_neg_svar_subst.\n      {  clear -H2 Heqx. subst. eapply evar_is_fresh_in_richer'. 2: apply set_evar_fresh_is_fresh. set_solver. }\n      { assumption. }\n    }\n    { try_solve_pile. }\n    toMLGoal.\n    { wf_auto2. }\n    { mlIntro \"H\". mlDestructAnd \"H\". mlApply \"1\". mlExact \"0\". }\n\n    rewrite subst_svar_evar_svar in HH'.\n    {\n      subst x. solve_fresh.\n    }\n    \n    rewrite subst_svar_evar_svar in HH'.\n    {\n      subst x. solve_fresh.\n    }\n\n    mlIntro \"H\".\n    mlDestructAnd \"H\" as \"H0\" \"H1\".\n    mlSplitAnd.\n    + mlExact \"H0\".\n    + mlApplyMeta HH'. mlExact \"H1\".\n  }\nDefined.\n\nLemma fresh_impl_no_mu_in_evar_path {Σ : Signature} x phi k:\n  evar_is_fresh_in x phi ->\n  mu_in_evar_path x phi k = false.\nProof.\n  move: k x.\n  induction phi; intros k x' Hx'; unfold mu_in_evar_path in *;\n    cbn in *; try reflexivity.\n  {\n    destruct (decide (x = x')); try reflexivity.\n    unfold evar_is_fresh_in in Hx'. cbn in Hx'.\n    exfalso. set_solver.\n  }\n  {\n    unfold evar_is_fresh_in in *.\n    cbn in Hx'.\n    specialize (IHphi1 k x' ltac:(set_solver)).\n    specialize (IHphi2 k x' ltac:(set_solver)).\n    repeat case_match; try reflexivity; cbn in *; lia.\n  }\n  {\n    unfold evar_is_fresh_in in *.\n    cbn in Hx'.\n    specialize (IHphi1 k x' ltac:(set_solver)).\n    specialize (IHphi2 k x' ltac:(set_solver)).\n    repeat case_match; try reflexivity; cbn in *; lia.\n  }\n  {\n    unfold evar_is_fresh_in in *.\n    cbn in Hx'.\n    specialize (IHphi k x' ltac:(set_solver)).\n    exact IHphi.\n  }\n  {\n    unfold evar_is_fresh_in in *.\n    cbn in Hx'.\n    specialize (IHphi (S k) x' ltac:(set_solver)).\n    exact IHphi.\n  }\nQed.\n\nLemma hbvum_impl_mmdt0 {Σ : Signature} phi dbi x y k:\n  evar_is_fresh_in x phi ->\n  evar_is_fresh_in y phi ->\n  well_formed_closed_mu_aux phi (S dbi) ->\n  maximal_mu_depth_to k y phi^[svar:dbi↦patt_free_evar y] = 0 ->\n  maximal_mu_depth_to k x phi^[svar:dbi↦patt_free_evar x] = 0\n.\nProof.\n  move: x y dbi k.\n  induction phi; intros x' y dbi k Hfrx' Hfry Hwf H; cbn in *; try reflexivity.\n  {\n    unfold evar_is_fresh_in in *. cbn in *.\n    repeat case_match; subst; try reflexivity.\n    set_solver. \n  }\n  {\n    repeat case_match; cbn in *; try reflexivity;\n    rewrite decide_eq_same; try reflexivity; subst;\n    case_match; subst; cbn in *; try reflexivity; contradiction.\n  }\n  {\n    unfold evar_is_fresh_in in *. cbn in *.\n    rewrite -> IHphi1 with (y := y).\n    5: lia.\n    4: wf_auto2.\n    3: set_solver.\n    2: set_solver.\n    cbn. apply IHphi2 with (y := y).\n    { set_solver. }\n    { set_solver. }\n    { wf_auto2. }\n    { lia. }\n  }\n  {\n    unfold evar_is_fresh_in in *. cbn in *.\n    rewrite -> IHphi1 with (y := y).\n    5: lia.\n    4: wf_auto2.\n    3: set_solver.\n    2: set_solver.\n    cbn. apply IHphi2 with (y := y).\n    { set_solver. }\n    { set_solver. }\n    { wf_auto2. }\n    { lia. }\n  }\n  {\n    eauto with nocore.\n  }\n  {\n    eauto with nocore.\n  }\nQed.\n\nTheorem deduction_theorem {Σ : Signature} {syntax : Syntax} Γ ϕ ψ\n  (gpi : ProofInfo)\n  (pf : Γ ∪ {[ ψ ]} ⊢i ϕ using gpi) :\n  well_formed ϕ ->\n  well_formed ψ ->\n  theory ⊆ Γ ->\n  pi_generalized_evars gpi ## (gset_to_coGset (free_evars ψ)) ->\n  pi_substituted_svars gpi ## (gset_to_coGset (free_svars ψ)) ->\n  pi_uses_advanced_kt gpi = false ->\n  Γ ⊢i ⌊ ψ ⌋ ---> ϕ\n  using AnyReasoning.\nProof.\n  intros wfϕ wfψ HΓ HnoExGen HnoSvarSubst Hnoakt.\n  destruct pf as [pf Hpf]. simpl.\n  induction pf.\n  - (* hypothesis *)\n    rename axiom into axiom0.\n    (* We could use [apply elem_of_union in e; destruct e], but that would be analyzing Prop\n        when building Set, which is prohibited. *)\n    destruct (decide (axiom0 = ψ)).\n    + subst.\n      eapply useGenericReasoning.\n      2: {\n        apply total_phi_impl_phi; try assumption.\n        instantiate (1 := fresh_evar ψ). solve_fresh.\n      }\n      {\n        try_solve_pile.\n      }\n\n    + assert (axiom0 ∈ Γ).\n      { clear -e n. set_solver. }\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlClear \"0\". fromMLGoal.\n      eapply useGenericReasoning.\n      2: apply (BasicProofSystemLemmas.hypothesis Γ axiom0 i H).\n      try_solve_pile.\n  - (* P1 *)\n    toMLGoal.\n    { wf_auto2. }\n    do 3 mlIntro. mlExactn 1.\n  - (* P2 *)\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlClear \"0\". fromMLGoal.\n    useBasicReasoning.\n    apply P2; assumption.\n  - (* P3 *)\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlClear \"0\". fromMLGoal.\n    useBasicReasoning.\n    apply P3; assumption.\n  - (* Modus Ponens *)\n    assert (well_formed phi2).\n    { unfold well_formed, well_formed_closed in *. simpl in *.\n      destruct_and!. split_and!; auto.\n    }\n    assert (well_formed phi1).\n    {\n      clear -pf1. apply proved_impl_wf in pf1. exact pf1.\n    }\n\n    remember_constraint as i'.\n\n    destruct Hpf as [Hpf2 Hpf3 Hpf4].\n    simpl in Hpf2, Hpf3, Hpf4.\n    feed specialize IHpf1.\n    {\n      constructor; simpl.\n      { set_solver. }\n      { set_solver. }\n      { unfold implb in *.\n        destruct (uses_kt pf1) eqn:Hktpf1;[|reflexivity]. simpl in *.\n        exact Hpf4.\n      }\n      {\n        cbn in *.\n        unfold is_true.\n        rewrite implb_true_iff.\n        intro Hakt1.\n        rewrite Hakt1 in pwi_pf_kta. simpl in pwi_pf_kta.\n        unfold is_true in pwi_pf_kta.\n        rewrite andb_true_iff in pwi_pf_kta.\n        destruct pwi_pf_kta as [HH1 HH2].\n        rewrite HH1.\n        simpl.\n        apply kt_unreasonably_implies_somehow.\n        exact Hakt1.\n      }\n    }\n    { assumption. }\n    feed specialize IHpf2.\n    {\n      constructor; simpl.\n      { set_solver. }\n      { set_solver. }\n      { unfold implb in *.\n        destruct (uses_kt pf2) eqn:Hktpf2;[|reflexivity].\n        rewrite orb_comm in Hpf4. simpl in *.\n        exact Hpf4.\n      }\n      {\n        cbn in *.\n        unfold is_true.\n        rewrite implb_true_iff.\n        intro Hakt1.\n        rewrite Hakt1 in pwi_pf_kta. rewrite orb_true_r in pwi_pf_kta.\n        simpl in pwi_pf_kta.\n        unfold is_true in pwi_pf_kta.\n        rewrite andb_true_iff in pwi_pf_kta.\n        destruct pwi_pf_kta as [HH1 HH2].\n        rewrite HH1.\n        simpl.\n        apply kt_unreasonably_implies_somehow.\n        exact Hakt1.\n      }\n    }\n    { wf_auto2. }\n\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro.\n    mlAdd IHpf2.\n    mlAssert ((phi1 ---> phi2)).\n    { wf_auto2. }\n    { mlApply \"1\". mlExactn 1. }\n    mlApply \"2\".\n    mlAdd IHpf1.\n    mlApply \"3\".\n    mlExactn 2.\n  - (* Existential Quantifier *)\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlClear \"0\". fromMLGoal.\n    useBasicReasoning.\n    apply Ex_quan. wf_auto2.\n  - (* Existential Generalization *)\n    destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n    simpl in Hpf2, Hpf3, Hpf4.\n    (*\n    simpl in HnoExGen.\n    case_match;[congruence|]. *)\n    feed specialize IHpf.\n    {\n      constructor; simpl.\n      { clear -Hpf2. set_solver. }\n      { clear -Hpf3. set_solver. }\n      { apply Hpf4. }\n      { apply Hpf5. }\n    }\n    { clear Hpf5; wf_auto2. }\n\n    apply reorder_meta in IHpf.\n    2-4:  clear Hpf5; wf_auto2.\n    apply Ex_gen with (x := x) in IHpf.\n    3: { simpl. set_solver. }\n    2: { try_solve_pile. }\n    apply reorder_meta in IHpf.\n    2-4: clear Hpf5; wf_auto2.\n    exact IHpf.\n    \n  - (* Propagation of ⊥, left *)\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlClear \"0\". fromMLGoal.\n    useBasicReasoning.\n    apply Prop_bott_left; assumption.\n  - (* Propagation of ⊥, right *)\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlClear \"0\"; auto. fromMLGoal.\n    useBasicReasoning.\n    apply Prop_bott_right; assumption.\n  - (* Propagation of 'or', left *)\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlClear \"0\"; auto. fromMLGoal.\n    useBasicReasoning.\n    apply Prop_disj_left; assumption.\n  - (* Propagation of 'or', right *)\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlClear \"0\"; auto. fromMLGoal.\n    useBasicReasoning.\n    apply Prop_disj_right; assumption.\n  - (* Propagation of 'exists', left *)\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlClear \"0\"; auto. fromMLGoal.\n    useBasicReasoning.\n    apply Prop_ex_left; assumption.\n  - (* Propagation of 'exists', right *)\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlClear \"0\"; auto. fromMLGoal.\n    useBasicReasoning.\n    apply Prop_ex_right; assumption.\n  - (* Framing left *)\n    assert (well_formed (phi1)).\n    { unfold well_formed,well_formed_closed in *. simpl in *.\n      destruct_and!. split_and!; auto. }\n\n    assert (well_formed (phi2)).\n    { unfold well_formed,well_formed_closed in *. simpl in *.\n      destruct_and!. split_and!; auto. }\n\n    assert (well_formed (psi)).\n    { unfold well_formed,well_formed_closed in *. simpl in *.\n      destruct_and!. split_and!; auto. }\n    \n    assert (well_formed (phi1 ---> phi2)).\n    { unfold well_formed,well_formed_closed in *. simpl in *.\n      destruct_and!. split_and!; auto. }\n    destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n    simpl in Hpf2,Hpf3,Hpf4.\n    feed specialize IHpf.\n    {\n      constructor; simpl.\n      { set_solver. }\n      { set_solver. }\n      { apply Hpf4. }\n      { apply Hpf5. }\n    }\n    { wf_auto2. }\n    clear Hpf5.\n    remember_constraint as i'.\n\n    (*\n    apply useGenericReasoning with (i0 := i') in IHpf.\n    2: {\n      subst i'.\n      apply pile_evs_svs_kt.\n      { clear. set_solver. }\n      { apply reflexivity. }\n      { reflexivity. }\n    }\n    *)\n    assert (S2: Γ ⊢i phi1 ---> (phi2 or ⌈ ! ψ ⌉) using i').\n    { toMLGoal.\n      {  wf_auto2. }\n      mlAdd IHpf. mlIntro.\n      mlAdd (useBasicReasoning i' (A_or_notA Γ (⌈ ! ψ ⌉) ltac:(wf_auto2))).\n      mlDestructOr \"0\".\n      - mlRight. mlExact \"3\".\n      - mlLeft.\n        mlApply \"4\". mlExact \"1\".\n    }\n\n    assert (S3: Γ ⊢i (⌈ ! ψ ⌉ $ psi) ---> ⌈ ! ψ ⌉ using i').\n    {\n      replace (⌈ ! ψ ⌉ $ psi)\n        with (subst_ctx (ctx_app_l AC_patt_defined psi ltac:(assumption)) (! ψ))\n        by reflexivity.\n      subst i'.\n      gapply in_context_impl_defined; auto.\n      instantiate (1 := fresh_evar (ψ ---> psi)).\n      try_solve_pile.\n      solve_fresh.\n    }\n\n    assert (S4: Γ ⊢i (phi1 $ psi) ---> ((phi2 or ⌈ ! ψ ⌉) $ psi) using i').\n    { \n      unshelve (eapply Framing_left).\n      { wf_auto2. } 2: exact S2.\n      subst i'. clear. try_solve_pile.\n    }\n\n    assert (S5: Γ ⊢i (phi1 $ psi) ---> ((phi2 $ psi) or (⌈ ! ψ ⌉ $ psi)) using i').\n    {\n      pose proof (Htmp := prf_prop_or_iff Γ (ctx_app_l box psi ltac:(assumption)) phi2 (⌈! ψ ⌉)).\n      feed specialize Htmp.\n      { wf_auto2. }\n      { wf_auto2. }\n      simpl in Htmp.\n      apply pf_iff_proj1 in Htmp.\n      3: wf_auto2.\n      2: wf_auto2.\n      subst i'.\n      eapply syllogism_meta.\n      5: {\n        gapply Htmp.\n        clear. try_solve_pile.\n      }\n      4: assumption.\n      all: wf_auto2.\n    }\n\n    assert (S6: Γ ⊢i ((phi2 $ psi) or (⌈ ! ψ ⌉ $ psi)) ---> ((phi2 $ psi) or (⌈ ! ψ ⌉)) using i').\n    {\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlAdd S3.\n      (* TODO we need a tactic for adding  something with stronger constraint. *)\n      mlAdd (useBasicReasoning i' (A_or_notA Γ (phi2 $ psi) ltac:(auto))).\n      mlDestructOr \"2\".\n      - mlLeft. mlExact \"3\".\n      - mlRight. mlApply \"1\". mlApply \"0\". mlExactn 0.\n    }\n\n    assert (S7: Γ ⊢i (phi1 $ psi) ---> ((phi2 $ psi)  or ⌈ ! ψ ⌉) using i').\n    {\n      toMLGoal.\n      { wf_auto2. }\n      mlAdd S5. mlAdd S6. mlIntro.\n      mlAssert (((phi2 $ psi) or (⌈ ! ψ ⌉ $ psi))).\n      { wf_auto2. }\n      { mlApply \"0\". mlExactn 2. }\n      mlDestructOr \"3\".\n      - mlLeft. mlExactn 3.\n      - mlApply \"1\". mlRight. mlExactn 3.\n    }\n\n    toMLGoal.\n    { wf_auto2. }\n    do 2 mlIntro. mlAdd S7.\n    mlAssert ((phi2 $ psi or ⌈ ! ψ ⌉)).\n    { wf_auto2. }\n    { mlApply \"2\". mlExactn 2. }\n    mlDestructOr \"3\".\n    + mlExactn 3.\n    + mlAssert ((phi2 $ psi or ⌈ ! ψ ⌉)).\n      { wf_auto2. }\n      { mlApply \"2\". mlExactn 2. }\n      mlAdd (useBasicReasoning i' (A_or_notA Γ (phi2 $ psi) ltac:(auto))).\n      mlDestructOr \"4\".\n      * mlExactn 0.\n      * mlAdd (useBasicReasoning i' (bot_elim Γ (phi2 $ psi) ltac:(auto))).\n        mlApply \"4\".\n        mlApply \"0\".\n        mlExactn 5.\n  - (* Framing right *)\n    assert (well_formed (phi1)).\n    { unfold well_formed,well_formed_closed in *. simpl in *.\n      destruct_and!. split_and!; auto. }\n\n    assert (well_formed (phi2)).\n    { unfold well_formed,well_formed_closed in *. simpl in *.\n      destruct_and!. split_and!; auto. }\n\n    assert (well_formed (psi)).\n    { unfold well_formed,well_formed_closed in *. simpl in *.\n      destruct_and!. split_and!; auto. }\n\n    assert (well_formed (phi1 ---> phi2)).\n    { unfold well_formed,well_formed_closed in *. simpl in *.\n      destruct_and!. split_and!; auto. }\n    simpl in HnoExGen. simpl in HnoSvarSubst.\n\n    destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n    simpl in Hpf2,Hpf3,Hpf4.\n    feed specialize IHpf.\n    {\n      constructor; simpl.\n      { set_solver. }\n      { set_solver. }\n      { apply Hpf4. }\n      { apply Hpf5. }\n    }\n    { clear Hpf5; wf_auto2. }\n\n    clear Hpf5.\n\n    remember_constraint as i'.\n\n    (*\n    apply useGenericReasoning with (i := i') in IHpf.\n    2: {\n      subst i'.\n      apply pile_evs_svs_kt.\n      { clear. set_solver. }\n      { apply reflexivity. }\n      { reflexivity. }\n    }\n    *)\n    assert (S2: Γ ⊢i phi1 ---> (phi2 or ⌈ ! ψ ⌉) using i').\n    { toMLGoal.\n      { wf_auto2. }\n      mlAdd IHpf. mlIntro.\n      mlAdd (useBasicReasoning i' (A_or_notA Γ (⌈ ! ψ ⌉) ltac:(wf_auto2))).\n      mlDestructOr \"2\".\n      - mlRight. mlExactn 0.\n      - mlLeft.\n        mlAssert((phi1 ---> phi2)).\n        { wf_auto2. }\n        { mlApply \"0\". mlExactn 0. }\n        mlApply \"2\". mlExactn 2.\n    }\n\n    assert (S3: Γ ⊢i (psi $ ⌈ ! ψ ⌉) ---> ⌈ ! ψ ⌉ using i').\n    {\n      replace (psi $ ⌈ ! ψ ⌉)\n        with (subst_ctx (ctx_app_r psi AC_patt_defined ltac:(assumption)) (! ψ))\n        by reflexivity.\n        subst i'.\n        gapply in_context_impl_defined; auto.\n        instantiate (1 := fresh_evar (ψ ---> psi)).\n        try_solve_pile. solve_fresh.\n    }\n\n    assert (S4: Γ ⊢i (psi $ phi1) ---> (psi $ (phi2 or ⌈ ! ψ ⌉)) using i').\n    { \n      (* TODO: have a variant of apply which automatically solves all wf constraints.\n        Like: unshelve (eapply H); try_wfauto\n      *)\n      unshelve (eapply Framing_right).\n      { wf_auto2. }\n      2: exact S2.\n      subst i'. try_solve_pile.\n    }\n\n    assert (S5: Γ ⊢i (psi $ phi1) ---> ((psi $ phi2) or (psi $ ⌈ ! ψ ⌉)) using i').\n    {\n      pose proof (Htmp := prf_prop_or_iff Γ (ctx_app_r psi box ltac:(assumption)) phi2 (⌈! ψ ⌉)).\n      feed specialize Htmp.\n      { wf_auto2. }\n      { wf_auto2. }\n      simpl in Htmp.\n      apply pf_iff_proj1 in Htmp.\n      2,3: wf_auto2.\n      subst i'.\n      eapply syllogism_meta.\n      5: gapply Htmp; try_solve_pile.\n      4: assumption.\n      all: wf_auto2.\n    }\n\n    assert (S6: Γ ⊢i ((psi $ phi2) or (psi $ ⌈ ! ψ ⌉)) ---> ((psi $ phi2) or (⌈ ! ψ ⌉)) using i').\n    {\n      toMLGoal.\n      { wf_auto2. }\n      mlIntro. mlAdd S3.\n      mlAdd (useBasicReasoning i' (A_or_notA Γ (psi $ phi2) ltac:(auto))).\n      mlDestructOr \"2\".\n      - mlLeft. mlExactn 0.\n      - mlRight. mlApply \"1\". mlApply \"0\". mlExactn 0.\n    }\n\n    assert (S7: Γ ⊢i (psi $ phi1) ---> ((psi $ phi2)  or ⌈ ! ψ ⌉) using i').\n    {\n      toMLGoal.\n      { wf_auto2. }\n      mlAdd S5. mlAdd S6. mlIntro.\n      mlAssert (((psi $ phi2) or (psi $ ⌈ ! ψ ⌉))).\n      { wf_auto2. }\n      { mlApply \"0\". mlExactn 2. }\n      mlDestructOr \"3\".\n      - mlLeft. mlExactn 3.\n      - mlApply \"1\". mlRight. mlExactn 3.\n    }\n\n    toMLGoal.\n    { wf_auto2. }\n    do 2 mlIntro. mlAdd S7.\n    mlAssert ((psi $ phi2 or ⌈ ! ψ ⌉)).\n    { wf_auto2. }\n    { mlApply \"2\". mlExactn 2. }\n    mlDestructOr \"3\".\n    + mlExactn 3.\n    + mlAssert ((psi $ phi2 or ⌈ ! ψ ⌉)).\n      { wf_auto2. }\n      { mlApply \"2\". mlExactn 2. }\n      mlAdd (useBasicReasoning i' (A_or_notA Γ (psi $ phi2) ltac:(auto))).\n      mlDestructOr \"4\".\n      * mlExactn 0.\n      * mlAdd (useBasicReasoning i' (bot_elim Γ (psi $ phi2) ltac:(auto))).\n        mlApply \"4\".\n        mlApply \"0\".\n        mlExactn 5.\n  - (* Set variable substitution *)\n    simpl in HnoExGen. simpl in HnoSvarSubst. simpl in IHpf.\n    destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n    simpl in Hpf2, Hpf3, Hpf4.\n    feed specialize IHpf.\n    {\n      constructor; simpl.\n      { exact Hpf2. }\n      { clear -Hpf3. set_solver. }\n      { exact Hpf4. }\n      { exact Hpf5. }\n    }\n    {\n      wf_auto2.\n    }\n    clear Hpf5.\n    remember_constraint as i'.\n\n    replace (⌊ ψ ⌋ ---> phi^[[svar: X ↦ psi]])\n      with ((⌊ ψ ⌋ ---> phi)^[[svar: X ↦ psi]]).\n    2: {  simpl.\n        rewrite [ψ^[[svar: X ↦ psi]]]free_svar_subst_fresh.\n        {\n          clear -HnoSvarSubst Hpf3. unfold svar_is_fresh_in. set_solver.\n        }\n        reflexivity.\n    }\n    apply Svar_subst.\n    3: {\n      apply IHpf.\n    }\n    {\n      subst i'. try_solve_pile.\n    }\n    { wf_auto2. }\n\n  - (* Prefixpoint *)\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlClear \"0\". fromMLGoal.\n    apply useBasicReasoning.\n    apply Pre_fixp. wf_auto2.\n  - (* Knaster-Tarski *)\n    destruct Hpf as [Hpf2 Hpf3 Hpf4 Hpf5].\n    apply lhs_to_and.\n    1-3: clear Hpf2 Hpf3 Hpf4 Hpf5; wf_auto2.\n    remember_constraint as pi.\n    feed specialize IHpf.\n    {\n      cbn. constructor; try assumption.\n      {\n        clear -Hpf4.\n        destruct (uses_kt pf) eqn:H; rewrite H; simpl.\n        2: reflexivity.\n        simpl in Hpf4.\n        assumption.\n      }\n      {\n        unfold is_true.\n        rewrite implb_true_iff. intros HH.\n        cbn in *.\n        unfold is_true in Hpf5.\n        rewrite HH in Hpf5. rewrite orb_true_r in Hpf5. simpl in Hpf5.\n        rewrite Hnoakt in Hpf5. inversion Hpf5.\n      }\n    }\n    { clear Hpf2 Hpf3 Hpf4 Hpf5.\n      wf_auto2.\n    }\n\n    cbn in *.\n    unfold is_true in Hpf5.\n    rewrite andb_true_r in Hpf5.\n    rewrite Hnoakt in Hpf5.\n    rewrite implb_false_r in Hpf5.\n    destruct (decide (has_bound_variable_under_mu phi = true)) as [Ht|Hf].\n    {\n      rewrite Ht in Hpf5. simpl in Hpf5. inversion Hpf5.\n    }\n    apply not_true_is_false in Hf.\n    remember (svar_fresh_s (free_svars ⌊ ψ ⌋ ∪ free_svars phi)) as X.\n    epose proof (Htmp := @mu_and_predicate_propagation _ _ Γ phi ⌊ ψ ⌋ X _ _ _).\n    feed specialize Htmp.\n    { \n      unfold has_bound_variable_under_mu in Hf.\n      unfold mu_in_evar_path in Hf.\n      rewrite negb_false_iff in Hf.\n      rewrite Nat.eqb_eq in Hf.\n      symmetry in Hf.\n      intros.\n      unfold mu_in_evar_path.\n      erewrite hbvum_impl_mmdt0.\n      { reflexivity. }\n      { assumption. }\n      3: { apply Hf. }\n      { apply set_evar_fresh_is_fresh. }\n      { wf_auto2. }\n    }\n    {\n      subst X. clear.\n      eapply svar_is_fresh_in_richer'.\n      2: apply set_svar_fresh_is_fresh'.\n      { set_solver. }\n    }\n    {\n      subst X. clear.\n      eapply svar_is_fresh_in_richer'.\n      2: apply set_svar_fresh_is_fresh'.\n      { set_solver. }\n    }\n    {\n      gapply floor_is_predicate.\n      { try_solve_pile. }\n      { exact HΓ. }\n      { wf_auto2. }\n    }\n    toMLGoal.\n    { clear Hpf2 Hpf3 Hpf4; wf_auto2. }\n    mlIntro.\n    apply pf_iff_proj2 in Htmp.\n    mlApplyMeta Htmp in \"0\". clear Htmp.\n    fromMLGoal.\n    apply Knaster_tarski.\n    { subst pi. try_solve_pile. }\n    1,4,5:clear Hpf2 Hpf3 Hpf4 Hpf5; wf_auto2.\n    {\n      fold no_negative_occurrence_db_b.\n      apply wfc_impl_no_neg_occ.\n      wf_auto2.\n    }\n    {\n      fold no_negative_occurrence_db_b.\n      apply wfc_impl_no_neg_occ.\n      wf_auto2.\n    }\n    2: { try_solve_pile. }\n\n    unfold instantiate.\n    mlSimpl.\n    apply lhs_from_and.\n\n    1-3:clear Hpf2 Hpf3 Hpf4; wf_auto2. \n    \n    rewrite -> well_formed_bsvar_subst with (k := 0).\n    3: wf_auto2.\n    2: lia.\n    simpl in IHpf.\n    apply IHpf.\n\n  - (* Existence *)\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlClear \"0\". fromMLGoal.\n    apply useBasicReasoning.\n    apply Existence.\n  - (* Singleton *)\n    toMLGoal.\n    { wf_auto2. }\n    mlIntro. mlClear \"0\". fromMLGoal.\n    apply useBasicReasoning.\n    apply Singleton_ctx. wf_auto2.\n    Unshelve.\n    2,3: wf_auto2.\n    1: exact HΓ.\nDefined.\n\nLemma MLGoal_deduct'\n  {Σ : Signature}\n  {syntax : Syntax}\n  (Γ : Theory)\n  (l : hypotheses)\n  name\n  (ψ g : Pattern)\n  (C : PatternCtx)\n  (i : ProofInfo)\n  :\n  theory ⊆ Γ ->\n  pi_generalized_evars i ## gset_to_coGset (free_evars ψ) ->\n  pi_substituted_svars i ## gset_to_coGset (free_svars ψ) ->\n  pi_uses_advanced_kt i = false ->\n  mkMLGoal Σ (Γ ∪ {[ψ]}) l g i ->\n  mkMLGoal Σ Γ ((mkNH _ name ⌊ ψ ⌋) :: l) g AnyReasoning .\nProof.\n  intros HΓ Hge Hse Hakt H.\n  intros wf1 wf2. cbn in *.\n  feed specialize H.\n  { wf_auto2. }\n  { cbn in wf2. cbn. destruct_and!. assumption. }\n  cbn in *.\n  eapply deduction_theorem.\n  { apply H. }\n  { wf_auto2. }\n  { wf_auto2. }\n  { exact HΓ. }\n  { assumption. }\n  { assumption. }\n  { assumption. }\nDefined.\n\nLemma MLGoal_deduct\n  {Σ : Signature}\n  {syntax : Syntax}\n  (Γ : Theory)\n  (l₁ l₂ : hypotheses)\n  name\n  (ψ g : Pattern)\n  :\n  theory ⊆ Γ ->\n  mkMLGoal Σ (Γ ∪ {[ψ]}) (l₁ ++ l₂) g\n    ((ExGen := ⊤ ∖ gset_to_coGset (free_evars ψ), SVSubst := ⊤ ∖ gset_to_coGset (free_svars ψ), KT := true, AKT := false)) ->\n  mkMLGoal Σ Γ (l₁ ++ (mkNH _ name ⌊ ψ ⌋) :: l₂) g AnyReasoning .\nProof.\n  intros HΓ H.\n  intros wf1 wf2. cbn in *.\n\n  rewrite map_app in wf2. cbn in wf2.\n  rewrite map_app in wf2. cbn in wf2.\n  rewrite foldr_app in wf2. cbn in wf2.\n  rewrite foldr_andb_true_iff in wf2.\n\n  assert (well_formed ψ).\n  {\n    wf_auto2.\n  }\n  assert (wf (map nh_patt l₁)).\n  {\n    destruct_and!. assumption.\n  }\n  assert (wf (map nh_patt l₂)).\n  {\n    destruct_and!. assumption.\n  }\n  \n  feed specialize H.\n  { wf_auto2. }\n  { cbn in wf2. cbn.\n    rewrite map_app. cbn.\n    rewrite map_app. cbn.\n    rewrite foldr_app. cbn.\n    rewrite foldr_andb_true_iff.\n    destruct_and!.\n    split_and!;assumption.\n  }\n  cbn in *.\n  rewrite map_app.\n  apply reorder_middle_to_head_meta.\n  { wf_auto2. }\n  { wf_auto2. }\n  { wf_auto2. }\n  { wf_auto2. }\n  cbn.\n  eapply deduction_theorem.\n  { \n    rewrite map_app in H.\n    apply H.\n  }\n  { wf_auto2. }\n  { wf_auto2. }\n  { exact HΓ. }\n  { cbn. rewrite union_empty_l_L.\n    unfold disjoint.\n    unfold set_disjoint_instance.\n    intros x Hx HContra.\n    rewrite elem_of_gset_to_coGset in HContra.\n    cbn in Hx.\n    clear -Hx HContra.\n    contradiction.\n  }\n  { cbn. rewrite union_empty_l_L.\n    unfold disjoint.\n    unfold set_disjoint_instance.\n    intros x Hx HContra.\n    rewrite elem_of_gset_to_coGset in HContra.\n    cbn in Hx.\n    clear -Hx HContra.\n    contradiction.\n  }\n  {\n    reflexivity.\n  }\nDefined.\n\n\nTactic Notation \"mlDeduct\" constr(name) :=\n  _ensureProofMode;\n  _mlReshapeHypsByName name;\n  apply MLGoal_deduct;\n  [try assumption|_mlReshapeHypsBack]\n.\n\n#[local]\nExample ex_deduct\n  {Σ : Signature} {syntax : Syntax} (Γ : Theory) (ϕ₁ ϕ₂ ϕ₃ : Pattern)\n  : \n  well_formed ϕ₁ ->\n  well_formed ϕ₂ ->\n  well_formed ϕ₃ ->\n  theory ⊆ Γ ->\n  Γ ⊢ ϕ₁ ---> ⌊ ϕ₂ ⌋ ---> ϕ₃ ---> ϕ₂\n.\nProof.\n  intros wf1 wf2 wf3 HΓ.\n  mlIntro \"H1\".\n  mlIntro \"H2\".\n  mlIntro \"H3\".\n  mlDeduct \"H2\".\n  useBasicReasoning.\n  mlClear \"H1\".\n  mlClear \"H3\".\n  fromMLGoal.\n  apply hypothesis.\n  { wf_auto2. }\n  { set_solver. }\nDefined.\n\nClose Scope ml_scope.\nClose Scope string_scope.\nClose Scope list_scope.", "meta": {"author": "harp-project", "repo": "AML-Formalization", "sha": "ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d", "save_path": "github-repos/coq/harp-project-AML-Formalization", "path": "github-repos/coq/harp-project-AML-Formalization/AML-Formalization-ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d/matching-logic/src/Theories/DeductionTheorem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23222279986964123}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n  Copyright 2018 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Export PBFTreceived_prepare_like.\nRequire Export PBFTknows_prepared.\n\n\nSection PBFT_A_1_4.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { pbft_context : PBFTcontext      }.\n  Context { pbft_auth    : PBFTauth         }.\n  Context { pbft_keys    : PBFTinitial_keys }.\n  Context { pbft_hash    : PBFThash         }.\n\n\n  Definition node0 : Rep := bij_inv node_bij nat_n_2Fp1_0.\n\n  Definition nat2node (n : nat) : node_type.\n  Proof.\n    destruct node_bij as [f a b].\n    destruct (lt_dec n num_nodes) as [d|d].\n    - exact (f (mk_nat_n d)). (* here we now that n < num_replicas so we can use our bijection *)\n    - exact node0. (* here num_replicas <= n, so we return a default value: replica0 *)\n  Defined.\n\n  Lemma A_1_4 :\n    forall (eo : EventOrdering)\n           (e1  : Event)\n           (e2  : Event)\n           (i   : Rep)\n           (j   : Rep)\n           (n   : SeqNum)\n           (v   : View)\n           (d1  : PBFTdigest)\n           (d2  : PBFTdigest)\n           (st1 : PBFTstate)\n           (st2 : PBFTstate),\n      AXIOM_authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> AXIOM_PBFTcorrect_keys eo\n      -> AXIOM_exists_at_most_f_faulty [e1, e2] F\n      -> loc e1 = PBFTreplica i                               (* e1 happened at location i *)\n      -> loc e2 = PBFTreplica j                               (* e2 happened at location j *)\n      -> state_sm_on_event (PBFTreplicaSM i) e1 = Some st1 (* state of i at e1 *)\n      -> state_sm_on_event (PBFTreplicaSM j) e2 = Some st2 (* state of j at e2 *)\n      -> prepared (request_data v n d1) st1 = true            (* the entry for <v,n,d1> is prepared at e1 *)\n      -> prepared (request_data v n d2) st2 = true            (* the entry for <v,n,d2> is prepared at e2 *)\n      -> d1 = d2.\n  Proof.\n    introv sendbyz corkeys fbyz eqloc1 eqloc2 eqst1 eqst2; introv prep1 prep2.\n\n    destruct (PBFTdigestdeq d1 d2) as [d|d]; auto.\n    assert False; tcsp.\n\n    assert (well_formed_log (log st1)) as wf1 by eauto 2 with pbft.\n    assert (well_formed_log (log st2)) as wf2 by eauto 2 with pbft.\n\n    eapply prepared_as_pbft_knows_rd in prep1;[| |eauto|];auto;[].\n    eapply prepared_as_pbft_knows_rd in prep2;[| |eauto|];auto;[].\n\n    pose proof (knows_in_intersection\n                  e1 e2\n                  (2 * F + 1)\n                  (request_data v n d1)\n                  (request_data v n d2)\n                  one_pre_prepare\n                  [e1,e2]\n                  F) as q.\n    repeat (autodimp q hyp); simpl; eauto 3 with pbft;\n      try (complete (unfold num_replicas; try omega));[].\n    destruct q as [e1' [e2' [pl1 [pl2 q]]]]; repnd.\n\n    pose proof (two_know_own_prepare_like eo e1' e2' pl1 pl2) as z.\n    repeat (autodimp z hyp); eauto 2 with pbft; try congruence;[].\n    eapply implies_prepare_like_have_same_digests in z;[|eauto|eauto]; tcsp.\n  Qed.\n\nEnd PBFT_A_1_4.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/PBFT/PBFT_A_1_4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2322206803411528}}
{"text": "Require Import VST.progs.conclib.\nRequire Import VST.progs.ghost.\n(*Require Import VST.progs.list_dt. Import LsegSpecial.*)\nRequire Import VST.floyd.library.\nRequire Import VST.progs.lock_coupling.\nRequire Import Sorting.\n\nRequire Export VST.floyd.Funspec_old_Notation.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition acquire_spec := DECLARE _acquire acquire_spec.\nDefinition release_spec := DECLARE _release release_spec.\nDefinition makelock_spec := DECLARE _makelock (makelock_spec _).\nDefinition freelock_spec := DECLARE _freelock (freelock_spec _).\n\nDefinition surely_malloc_spec :=\n DECLARE _surely_malloc\n   WITH n:Z\n   PRE [ _n OF tuint ]\n       PROP (0 <= n <= Int.max_unsigned)\n       LOCAL (temp _n (Vint (Int.repr n)))\n       SEP ()\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (malloc_token Tsh n p * memory_block Tsh n p).\n\nDefinition tnode := Tstruct _node noattr.\n\nModule ZOrder <: Orders.TotalLeBool.\n  Definition t := Z.\n  Definition leb x y := Z.leb x y.\n  Theorem leb_total : forall x y, leb x y = true \\/ leb y x = true.\n  Proof. intros; destruct (Zle_bool_total x y); auto. Qed.\nEnd ZOrder.\n\nModule Import ZSort := Sort ZOrder.\n\nLemma StronglySorted_imp : forall (R R' : Z -> Z -> Prop) l (HR' : forall x y, R x y -> R' x y)\n  (HR : StronglySorted R l), StronglySorted R' l.\nProof.\n  intros; induction HR; constructor; auto.\n  eapply Forall_impl, H; auto.\nQed.\n\nNotation sorted := (StronglySorted Z.le).\n\nLemma sort_sorted : forall l, sorted (sort l).\nProof.\n  intro; eapply StronglySorted_imp, StronglySorted_sort.\n  - intros.\n    rewrite <- Z.leb_le; auto.\n  - intros ???; apply Zle_bool_trans.\nQed.\n\nInductive set_op := Add (e : Z) | Remove (e : Z).\n\nFixpoint apply_hist S h :=\n  match h with\n  | [] => S\n  | Add e :: h' => if in_dec Z_eq_dec e S then apply_hist S h' else apply_hist (sort (e :: S)) h'\n  | Remove e :: h' => apply_hist (remove Z_eq_dec e S) h'\n  end.\n\nLemma apply_hist_app : forall h1 S h2, apply_hist S (h1 ++ h2) = apply_hist (apply_hist S h1) h2.\nProof.\n  induction h1; auto; simpl; intros.\n  destruct a; auto.\n  destruct (in_dec _ _ _); auto.\nQed.\n\n(* up *)\nLemma In_remove : forall A (a : A) dec l, incl (remove dec a l) l.\nProof.\n  induction l; simpl; auto.\n  destruct (dec a a0).\n  - apply incl_tl; auto.\n  - apply incl_same_head; auto.\nQed.\n\nLemma remove_sorted : forall a l, sorted l -> sorted (remove Z_eq_dec a l).\nProof.\n  induction l; auto; simpl; intro.\n  inv H.\n  destruct (Z.eq_dec a a0); auto.\n  constructor; auto.\n  rewrite Forall_forall in *; intros ? Hin.\n  apply In_remove in Hin; auto.\nQed.\n\nLemma apply_hist_sorted : forall h S, sorted S -> sorted (apply_hist S h).\nProof.\n  induction h; auto; simpl; intros.\n  destruct a.\n  - destruct (in_dec _ _ _); auto.\n    apply IHh, sort_sorted.\n  - apply IHh, remove_sorted; auto.\nQed.\n\nDefinition hist := hist_part set_op.\n\n(*Definition q_lock_pred' (t : type) P p (vals : list (val * reptype t)) head (addc remc : val) lock gsh h :=\n  !!(Zlength vals <= MAX /\\ 0 <= head < MAX /\\ consistent h [] vals) &&\n  (data_at Tsh tqueue (rotate (complete MAX (map fst vals)) head MAX, (vint (Zlength vals),\n                      (vint head, (vint ((head + Zlength vals) mod MAX), (addc, remc))))) p *\n   cond_var Tsh addc * cond_var Tsh remc * malloc_token Tsh (sizeof tqueue_t) p *\n   malloc_token Tsh (sizeof tcond) addc * malloc_token Tsh (sizeof tcond) remc *\n   malloc_token Tsh (sizeof tlock) lock * ghost gsh (Tsh, h) p *\n   fold_right sepcon emp (map (fun x => let '(p, v) := x in \n     !!(P v) && (data_at Tsh t v p * malloc_token Tsh (sizeof t) p)) vals)).\n\nDefinition q_lock_pred A P p lock gsh := EX vals : list (val * reptype A), EX head : Z,\n  EX addc : val, EX remc : val, EX h : hist _, q_lock_pred' A P p vals head addc remc lock gsh h.*)\n\nDefinition node_lock_inv e p := EX n : val, EX l : val,(*EX h : list set_op,*)\n  field_at Tsh tnode [StructField _val] (vint e) p *\n  field_at Tsh tnode [StructField _next] n p * field_at Tsh tnode [StructField _lock] l n *\n  node_lock_inv.\n\nDefinition node_pred sh e p := EX l : val,\n  !!((*sepalg.join gsh1 gsh2 Tsh /\\*) repable_signed e /\\ field_compatible tnode [] p) &&\n  (field_at sh tnode [StructField _lock] l p *\n   lock_inv sh l (node_lock_inv e p) (* * ghost gsh1 (lsh, h) p*)).\n\nDefinition new_node_spec :=\n DECLARE _new_node\n  WITH e : Z\n  PRE [ _e OF tint ]\n   PROP (repable_signed e)\n   LOCAL (temp _e (vint e))\n   SEP ()\n  POST [ tptr tnode ]\n   EX p : val,\n   PROP ()\n   LOCAL (temp ret_temp p)\n   SEP (node_pred Tsh e p).\n\nDefinition del_node_spec :=\n DECLARE _new_node\n  WITH e : Z, p : val\n  PRE [ _n OF tptr tnode ]\n   PROP ()\n   LOCAL (temp _n p)\n   SEP (node_pred Tsh e p)\n  POST [ tvoid ]\n   PROP ()\n   LOCAL ()\n   SEP ().\n\nDefinition tnode_pair := Tstruct _node_pair noattr.\n\nDefinition list_inv sh H h := node_pred sh Int.min_signed H * ghost_hist h H.\n\nDefinition locate_spec :=\n DECLARE _locate\n  WITH e : Z, sh : share, H : val, h : hist\n  PRE [ _e OF tint ]\n   PROP (repable_signed e)\n   LOCAL (temp _e (vint e); gvar _head H)\n   SEP (list_inv sh H h)\n  POST [ tptr tnode_pair ]\n   EX h' : hist, EX p : val, EX n1 : val, EX n2 : val, EX e1 : Z, EX e2 : Z, EX sh : share,\n   PROP (incl h h'; e1 < e <= e2)\n   LOCAL ()\n   SEP (list_inv H h'; data_at Tsh tnode_pair (n1, n2) p; node_pred sh e1 n1;\n        field_at Tsh tnode [StructField _val] (vint e1) n1; field_at Tsh tnode [StructField _next] n2 n1;\n        node_pred sh e2 n2; node_lock_inv e2 n2).\n\nDefinition add_spec :=\n DECLARE _add\n  WITH e : Z, H : val, h : hist\n  PRE [ _e OF tint ]\n   PROP (repable_signed e)\n   LOCAL (temp _e (vint e); gvar _head H)\n   SEP (list_inv H h)\n  POST [ tint ]\n   EX h' : hist, EX S : list Z, EX t' : nat,\n   PROP (incl h h'; apply_hist [] h' = S)\n   LOCAL (temp ret_temp (if in_dec Z_eq_dec e S then 0 else 1))\n   SEP (list_inv H (h' ++ [(t', Add e)]).\n\nDefinition remove_spec :=\n DECLARE _remove\n  WITH e : Z, H : val, h : hist\n  PRE [ _e OF tint ]\n   PROP (repable_signed e)\n   LOCAL (temp _e (vint e); gvar _head H)\n   SEP (list_inv H h)\n  POST [ tint ]\n   EX h' : hist, EX S : list Z, EX t' : nat,\n   PROP (incl h h'; apply_hist [] h' = S)\n   LOCAL (temp ret_temp (if in_dec Z_eq_dec e S then 1 else 0))\n   SEP (list_inv H (h' ++ [(t', Remove e)]).\n\nDefinition main_spec :=\n DECLARE _main\n  WITH u : unit\n  PRE  [] main_pre prog tt nil u\n  POST [ tint ] main_post prog nil u.\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [acquire_spec; release_spec; makelock_spec;\n  freelock_spec; surely_malloc_spec; new_node_spec; del_node_spec; locate_spec; add_spec; remove_spec; main_spec]).\n\nLemma body_surely_malloc: semax_body Vprog Gprog f_surely_malloc surely_malloc_spec.\nProof.\n  start_function. \n  forward_call (* p = malloc(n); *)\n     n.\n  Intros p.\n  forward_if\n  (PROP ( )\n   LOCAL (temp _p p)\n   SEP (malloc_token Tsh n p * memory_block Tsh n p)).\n*\n  if_tac.\n    subst p. entailer!.\n    entailer!.\n*\n    forward_call tt.\n    contradiction.\n*\n    if_tac.\n    + forward. subst p. inv H0.\n    + Intros. forward. entailer!.\n*\n  forward. Exists p; entailer!.\nQed.\n\nLemma ctr_inv_precise : forall p,\n  precise (cptr_lock_inv p).\nProof.\n  intro; eapply derives_precise, data_at__precise with (sh := Ews)(t := tint); auto.\n  intros ? (? & H); apply data_at_data_at_ in H; eauto.\nQed.\n#[export] Hint Resolve ctr_inv_precise.\n\nLemma ctr_inv_positive : forall ctr,\n  positive_mpred (cptr_lock_inv ctr).\nProof.\n  intro; apply ex_positive; auto.\nQed.\n#[export] Hint Resolve ctr_inv_positive.\n\nLemma body_incr: semax_body Vprog Gprog f_incr incr_spec.\nProof.\n  start_function.\n  forward.\n  forward_call (lock, sh, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  unfold cptr_lock_inv at 2; simpl.\n  Intro z.\n  forward.\n  forward.\n  rewrite field_at_isptr; Intros.\n  forward_call (lock, sh, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { lock_props.\n    unfold cptr_lock_inv; Exists (z + 1); entailer!. }\n  forward.\nQed.\n\nLemma body_read : semax_body Vprog Gprog f_read read_spec.\nProof.\n  start_function.\n  forward_call (lock, sh, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  unfold cptr_lock_inv at 2; simpl.\n  Intro z.\n  forward.\n  rewrite data_at_isptr; Intros.\n  forward_call (lock, sh, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { lock_props.\n    unfold cptr_lock_inv; Exists z; entailer!. }\n  forward.\n  Exists z; entailer!.\nQed.\n\nLemma body_thread_func : semax_body Vprog Gprog f_thread_func thread_func_spec.\nProof.\n  start_function.\n  Intros.\n  forward.\n  forward_call (ctr, sh, lock).\n  forward_call (lockt, sh, lock_inv sh lock (cptr_lock_inv ctr), thread_lock_inv sh ctr lock lockt).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { unfold thread_lock_inv; lock_props.\n    rewrite selflock_eq at 2; cancel.\n    eapply derives_trans; [apply lock_inv_later | cancel]. }\n  forward.\nQed.\n\nLemma lock_struct : forall p, data_at_ Ews (Tstruct _lock_t noattr) p |-- data_at_ Ews tlock p.\nProof.\n  intros.\n  unfold data_at_, field_at_; unfold_field_at 1%nat.\n  unfold field_at; simpl.\n  rewrite field_compatible_cons; simpl; entailer.\n  (* temporarily broken *)\nAdmitted.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\n  name ctr _ctr; name lockt _thread_lock; name lock _ctr_lock.\n  start_function.\n  forward.\n  forward.\n  forward.\n  forward_call (lock, Ews, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { rewrite (sepcon_comm _ (fold_right_sepcon _)); apply sepcon_derives; [cancel | apply lock_struct]. }\n  rewrite field_at_isptr; Intros.\n  forward_call (lock, Ews, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { lock_props.\n    unfold cptr_lock_inv; Exists 0; cancel. }\n  (* need to split off shares for the locks here *)\n  destruct split_Ews as (sh1 & sh2 & ? & ? & Hsh).\n  forward_call (lockt, Ews, thread_lock_inv sh1 ctr lock lockt).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { rewrite (sepcon_comm _ (fold_right_sepcon _)); apply sepcon_derives; [cancel | apply lock_struct]. }\n  get_global_function'' _thread_func.\n  apply extract_exists_pre; intros f_.\n  forward_spawn (val * share * val * val)%type (f_, Vint (Int.repr 0), (ctr, sh1, lock, lockt),\n    fun (x : (val * share * val * val)) (_ : val) => let '(ctr, sh, lock, lockt) := x in\n         !!readable_share sh && emp * lock_inv sh lock (cptr_lock_inv ctr) *\n         lock_inv sh lockt (thread_lock_inv sh ctr lock lockt)).\n  { simpl spawn_pre; entailer!.\n    Exists _args (fun x : val * share * val * val => let '(ctr, sh, lock, lockt) := x in\n      [(_ctr, ctr); (_ctr_lock, lock); (_thread_lock, lockt)]); entailer.\n    rewrite !sepcon_assoc; apply sepcon_derives.\n    { apply derives_refl'. f_equal.\n      unfold NDmk_funspec.\n      apply mk_funspec_congr; auto.\n      apply eq_JMeq.\n      extensionality x x0.\n      destruct x0 as (?, (((?, ?), ?), ?)); simpl.\n      rewrite <- !sepcon_assoc; reflexivity.  }\n    erewrite <- lock_inv_share_join; try apply Hsh; auto.\n    erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto.\n    entailer!. }\n  forward_call (ctr, sh2, lock).\n  forward_call (lockt, sh2, thread_lock_inv sh1 ctr lock lockt).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  forward_call (ctr, sh2, lock).\n  Intro z.\n  forward_call (lock, sh2, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  forward_call (lockt, Ews, sh1, |>lock_inv sh1 lock (cptr_lock_inv ctr), |>thread_lock_inv sh1 ctr lock lockt).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { unfold thread_lock_inv; lock_props.\n    - apply later_positive; auto.\n    - unfold rec_inv.\n      rewrite selflock_eq at 1.\n      rewrite later_sepcon; f_equal.\n      apply lock_inv_later_eq.\n    - rewrite selflock_eq at 2.\n      erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto; cancel.\n      rewrite sepcon_comm, <- !sepcon_assoc, sepcon_comm.\n      apply sepcon_derives; [apply lock_inv_later | cancel]. }\n  forward_call (lock, Ews, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { lock_props.\n    erewrite sepcon_assoc, lock_inv_share_join; eauto; cancel. }\n  forward.\nQed.\n\nDefinition extlink := ext_link_prog prog.\nDefinition Espec := add_funspecs (Concurrent_Espec unit _ extlink) extlink Gprog.\nExisting Instance Espec.\n\nLemma prog_correct:\n  semax_prog prog tt Vprog Gprog.\nProof.\nprove_semax_prog.\nrepeat (apply semax_func_cons_ext_vacuous; [reflexivity | reflexivity | ]).\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons body_incr.\nsemax_func_cons body_read.\nsemax_func_cons body_thread_func.\nsemax_func_cons body_main.\nQed.\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/progs/verif_lock_coupling.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.23222067501341784}}
{"text": "(* This file is an automatic translation, the licence of the source can be found here: *)\n(* https://github.com/herd/herdtools7/blob/master/LICENSE.txt *)\n(* Translation of model TSO *)\nFrom Coq Require Import Relations Ensembles String.\nFrom RelationAlgebra Require Import lattice prop monoid rel kat.\nFrom Catincoq.lib Require Import Cat proprel.\nSection Model.\nVariable c : candidate.\nDefinition events := events c.\nDefinition R := R c.\nDefinition W := W c.\nDefinition IW := IW c.\nDefinition FW := FW c.\nDefinition B := B c.\nDefinition RMW := RMW c.\nDefinition F := F c.\nDefinition rf := rf c.\nDefinition po := po c.\nDefinition int := int c.\nDefinition ext := ext c.\nDefinition loc := loc c.\nDefinition addr := addr c.\nDefinition data := data c.\nDefinition ctrl := ctrl c.\nDefinition amo := amo c.\nDefinition rmw := rmw c.\nDefinition unknown_set := unknown_set c.\nDefinition unknown_relation := unknown_relation c.\nDefinition M := R ⊔ W.\nDefinition emptyset : set events := empty.\nDefinition classes_loc : set events -> Ensemble (Ensemble events) := partition loc.\nDefinition tag2events := unknown_relation \"tag2events\".\nDefinition emptyset_0 : set events := domain 0.\nDefinition partition := classes_loc.\nDefinition tag2instrs := tag2events.\nDefinition po_loc := po ⊓ loc.\nDefinition rfe := rf ⊓ ext.\nDefinition rfi := rf ⊓ int.\nDefinition co0 := loc ⊓ ([IW] ⋅ top ⋅ [(W ⊓ !IW)] ⊔ [(W ⊓ !FW)] ⋅ top ⋅ [FW]).\nDefinition toid (s : set events) : relation events := [s].\nDefinition fencerel (B : set events) := (po ⊓ [top] ⋅ top ⋅ [B]) ⋅ po.\nDefinition ctrlcfence (CFENCE : set events) := (ctrl ⊓ [top] ⋅ top ⋅ [CFENCE]) ⋅ po.\nDefinition imply (A : relation events) (B : relation events) := !A ⊔ B.\nDefinition nodetour (R1 : relation events) (R2 : relation events) (R3 : relation events) := R1 ⊓ !(R2 ⋅ R3).\nDefinition singlestep (R : relation events) := nodetour R R R.\n(* Definition of map already included in the prelude *)\nDefinition LKW := (*failed: try LKW with emptyset_0*) emptyset_0.\nDefinition mfence : relation events := (*failed: try fencerel MFENCE with 0*) 0.\nDefinition lfence : relation events := (*failed: try fencerel LFENCE with 0*) 0.\nDefinition sfence : relation events := (*failed: try fencerel SFENCE with 0*) 0.\nDefinition A := ((*failed: try X with emptyset_0*) emptyset_0) ⊔ ((*failed: try A with emptyset_0*) emptyset_0).\nDefinition P := M ⊓ !A.\nDefinition WW r := r ⊓ [W] ⋅ top ⋅ [W].\nDefinition WR r := r ⊓ [W] ⋅ top ⋅ [R].\nDefinition RW r := r ⊓ [R] ⋅ top ⋅ [W].\nDefinition RR r := r ⊓ [R] ⋅ top ⋅ [R].\nDefinition RM r := r ⊓ [R] ⋅ top ⋅ [M].\nDefinition MR r := r ⊓ [M] ⋅ top ⋅ [R].\nDefinition WM r := r ⊓ [W] ⋅ top ⋅ [M].\nDefinition MW r := r ⊓ [M] ⋅ top ⋅ [W].\nDefinition MM r := r ⊓ [M] ⋅ top ⋅ [M].\nDefinition AA r := r ⊓ [A] ⋅ top ⋅ [A].\nDefinition AP r := r ⊓ [A] ⋅ top ⋅ [P].\nDefinition PA r := r ⊓ [P] ⋅ top ⋅ [A].\nDefinition PP r := r ⊓ [P] ⋅ top ⋅ [P].\nDefinition AM r := r ⊓ [A] ⋅ top ⋅ [M].\nDefinition MA r := r ⊓ [M] ⋅ top ⋅ [A].\nDefinition noid r : relation events := r ⊓ !id.\nDefinition atom := [A].\n(* Definition of co_locs already included in the prelude *)\n(* Definition of cross already included in the prelude *)\nDefinition generate_orders s pco := cross (co_locs pco (partition s)).\nDefinition generate_cos pco := generate_orders W pco.\nDefinition cobase := co0.\nVariable co : relation events.\nDefinition coi := co ⊓ int.\nDefinition coe := co ⊓ !coi.\nDefinition fr := rf° ⋅ co ⊓ !id.\nDefinition fri := fr ⊓ int.\nDefinition fre := fr ⊓ !fri.\nDefinition com := rf ⊔ (fr ⊔ co).\nDefinition test := acyclic (po_loc ⊔ com).\nDefinition test_0 := is_empty (rmw ⊓ fre ⋅ coe).\nDefinition po_ghb := WW po ⊔ RM po.\nDefinition mfence_0 : relation events := (*failed: try fencerel MFENCE with 0*) 0.\nDefinition lfence_0 : relation events := (*failed: try fencerel LFENCE with 0*) 0.\nDefinition sfence_0 : relation events := (*failed: try fencerel SFENCE with 0*) 0.\nDefinition poWR := WR po.\nDefinition i1 := MA poWR.\nDefinition i2 := AM poWR.\nDefinition implied := i1 ⊔ i2.\nDefinition ghb := mfence_0 ⊔ (implied ⊔ (po_ghb ⊔ (rfe ⊔ (fr ⊔ co)))).\nDefinition tso := acyclic ghb.\nDefinition witness_conditions := generate_cos cobase co.\nDefinition model_conditions := test /\\ (test_0 /\\ tso).\nEnd Model.\n\nHint Unfold events R W IW FW B RMW F rf po int ext loc addr data ctrl amo rmw unknown_set unknown_relation M emptyset classes_loc tag2events emptyset_0 partition tag2instrs po_loc rfe rfi co0 toid fencerel ctrlcfence imply nodetour singlestep LKW mfence lfence sfence A P WW WR RW RR RM MR WM MW MM AA AP PA PP AM MA noid atom generate_orders generate_cos cobase coi coe fr fri fre com test test_0 po_ghb mfence_0 lfence_0 sfence_0 poWR i1 i2 implied ghb tso witness_conditions model_conditions : cat.\n\nDefinition valid (c : candidate) :=\n  exists co : relation (events c),\n    witness_conditions c co /\\\n    model_conditions c co.\n\n(* End of translation of model TSO *)\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/models/x86tso.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.232201706619121}}
{"text": "From hahn Require Import Hahn.\nRequire Import PromisingLib.\nFrom Promising Require Import Event Cell Memory Configuration Thread.\nFrom imm Require Import Prog.\nFrom imm Require Import ProgToExecution.\nFrom imm Require Import Events.\nRequire Import Event_imm_promise.\nRequire Import PromiseLTS.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nDefinition init_threads (prog : Prog.t) : Threads.syntax :=\n  IdentMap.mapi (fun tid (linstr : list Instr.t) => existT _ (thread_lts tid) linstr) prog.\n\nDefinition conf_step (PC PC' : Configuration.t) :=\n  exists pe tid, Configuration.step pe tid PC PC'.\n\nDefinition final_memory_state (memory : Memory.t) (loc : location) : option value :=\n  match Memory.get loc (Memory.max_ts loc memory) memory with\n  | Some (_, msg) => Some msg.(Message.val)\n  | None => None\n  end.\n\nDefinition conf_init (prog : Prog.t) := Configuration.init (init_threads prog).\n\nDefinition promise_allows (prog : Prog.t) (final_memory : location -> value) :=\n  exists PC,\n    ⟪STEPS   : conf_step＊ (conf_init prog) PC⟫ /\\\n    ⟪FINAL   : Configuration.is_terminal PC⟫ /\\\n    ⟪OUTCOME : forall loc, final_memory_state PC.(Configuration.memory) loc =\n                           Some (final_memory loc)⟫.\n", "meta": {"author": "weakmemory", "repo": "promising1ToImm", "sha": "f27e87f0c2d037b30f0bc13763af39a11bb949a1", "save_path": "github-repos/coq/weakmemory-promising1ToImm", "path": "github-repos/coq/weakmemory-promising1ToImm/promising1ToImm-f27e87f0c2d037b30f0bc13763af39a11bb949a1/src/PromiseOutcome.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.23220170154540917}}
{"text": "(* En este archivo se demuestra la corrección de la acción startService *)\nRequire Export Exec.\nRequire Import Implementacion.\nRequire Export AuxFunsCorrect.\nRequire Export ListAuxFuns.\nRequire Import Classical.\nRequire Import Estado.\nRequire Import DefBasicas.\nRequire Import Semantica.\nRequire Import Operaciones.\nRequire Import ErrorManagement.\nRequire Import Maps.\nRequire Import Tacticas.\n\nSection StartService.\n\nLemma startServiceCorrect : forall (s:System) (i:Intent) (ic:iCmp) (sValid: validstate s),\n    (pre (startService i ic) s) -> post_startService i ic s (startService_post i ic s).\nProof.\n    intros.\n    unfold post_startService.\n    simpl in H.\n    unfold pre_startService in H;simpl in H.\n    destruct_conj H.\n    unfold addIntent.\n    unfold onlyIntentsChanged.\n    unfold startService_post.\n    simpl.\n    split; intros.\n    split; intros.\n    right;auto.\n    split;intros.\n    destruct H2.\n    right.\n    inversion H2.\n    split;auto.\n    unfold createIntent in *.\n    simpl.\n    repeat (split;auto).\n    left;auto.\n    left.\n    assert (i=createIntent i None).\n    case_eq i;intros.\n    unfold createIntent.\n    simpl.\n    rewrite<- H.\n    rewrite H2.\n    simpl.\n    auto.\n    rewrite<- H2.\n    auto.\n    \n    repeat (split;auto).\nQed.\n\nLemma notPreStartServiceThenError : forall (s:System) (i:Intent) (ic:iCmp), ~(pre (startService i ic) s) -> validstate s -> exists ec : ErrorCode, response (step s (startService i ic)) = error ec /\\ ErrorMsg s (startService i ic) ec /\\ s = system (step s (startService i ic)).\nProof.\n    intros.\n    simpl.\n    simpl in H.\n    unfold pre_startService in H.\n    unfold startService_safe.\n    unfold startService_pre.\n    case_eq (negb (intTypeEqBool (intType i) intService));intros.\n    exists incorrect_intent_type.\n    split;auto.\n    split;auto.\n    rewrite negb_true_iff in H1.\n    invertBool H1.\n    intro;apply H1.\n    rewrite H2.\n    destruct intTypeEqBool;auto.\n    case_eq (isSomethingBool Perm (brperm i));intros.\n    exists faulty_intent.\n    split;auto.\n    split;auto.\n    unfold isSomethingBool in H2.\n    intro.\n    destruct (brperm i).\n    discriminate H3.\n    discriminate H2.\n    case_eq (negb (isiCmpRunningBool ic s));intros.\n    exists instance_not_running.\n    split;auto.\n    split;auto.\n    rewrite negb_true_iff in H3.\n    invertBool H3.\n    intro;apply H3.\n    apply isiCmpRunningCorrect;auto.\n    case_eq ( existsb (fun pair : iCmp * Intent => if idInt_eq (idI i) (idI (snd pair)) then true else false) (sentIntents (state s)));intros.\n    exists intent_already_sent.\n    split;auto.\n    split;auto.\n    rewrite existsb_exists in H4.\n    destruct H4.\n    exists (snd x), (fst x).\n    destruct H4.\n    split.\n    destruct x.\n    simpl.\n    auto.\n    destruct idInt_eq in H5.\n    rewrite e;auto.\n    discriminate H5.\n    destruct H.\n    split.\n    rewrite negb_false_iff in H1.\n    unfold intTypeEqBool in H1.\n    destruct (intType i);auto;discriminate H1.\n    split.\n    unfold isSomethingBool in H2.\n    destruct (brperm i);auto;discriminate H2.\n    split.\n    rewrite negb_false_iff in H3.\n    apply isiCmpRunningCorrect;auto.\n    invertBool H4.\n    intro;apply H4.\n    rewrite existsb_exists.\n    destruct H.\n    destruct H.\n    destruct H.\n    exists (x0,x).\n    split;auto.\n    simpl.\n    destruct idInt_eq;auto.\nQed.\n\nLemma startServiceIsSound : forall (s:System) (i:Intent) (ic:iCmp) (sValid: validstate s),\n        exec s (startService i ic) (system (step s (startService i ic))) (response (step s (startService i ic))).\nProof.\n    intros.\n    unfold exec.\n    split.\n    auto.\n    elim (classic (pre (startService i ic) s));intro.\n    left.\n    simpl.\n    assert(startService_pre i ic s = None).\n    unfold startService_pre.\n    destruct H.\n    rewrite H.\n    unfold intTypeEqBool.\n    assert (negb true=false).\n    rewrite negb_false_iff.\n    auto.\n    rewrite H1.\n    \n    destruct_conj H0.\n    rewrite H2.\n    unfold isSomethingBool.\n    assert (negb (isiCmpRunningBool ic s)=false).\n    rewrite negb_false_iff.\n    apply isiCmpRunningCorrect; auto.\n    rewrite H3.\n    \n    assert (existsb (fun pair : iCmp * Intent => if idInt_eq (idI i) (idI (snd pair)) then true else false) (sentIntents (state s))=false).\n    rewrite <-not_true_iff_false.\n    unfold not;intros.\n    rewrite existsb_exists in H5.\n    destruct H5.\n    destruct H5.\n    apply H4.\n    exists (snd x).\n    destruct idInt_eq in H6.\n    exists (fst x).\n    case_eq x;intros.\n    simpl.\n    rewrite<- H7.\n    rewrite H7 in e.\n    simpl in e.\n    split;auto.\n    discriminate H6.\n    rewrite H5.\n    auto.\n    unfold startService_safe;simpl.\n    rewrite H0;simpl.\n    split;auto.\n    split;auto.\n    apply startServiceCorrect;auto.\n    right.\n    apply notPreStartServiceThenError;auto.\nQed.\nEnd StartService.\n", "meta": {"author": "g-deluca", "repo": "android-coq-model", "sha": "fd89432c39c043e1ca9d3d90e5702fd8cf536167", "save_path": "github-repos/coq/g-deluca-android-coq-model", "path": "github-repos/coq/g-deluca-android-coq-model/android-coq-model-fd89432c39c043e1ca9d3d90e5702fd8cf536167/src/StartServiceIsSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.23220169647169722}}
{"text": "From aneris_examples.consensus Require Import paxos_prelude.\nImport RecordSetNotations.\n\nSection paxos_proposer.\n  Context `{!anerisG (Paxos_model params) Σ}.\n  Context `{!paxosG Σ params}.\n\n  Lemma recv_promises_spec p h (n : nat) (b : Ballot) :\n    p ∈ Proposers →\n    {{{ inv paxosN paxos_inv ∗ p ⤇ proposer_si ∗\n        h ↪[ip_of_address p] (udp_socket (Some p) true) }}}\n      recv_promises int_serializer #(LitSocket h) #n #b\n      @[ip_of_address p]\n    {{{ vp (promises : gset (option (Ballot * Value))) (senders : gset Acceptor),\n        RET vp;\n        h ↪[ip_of_address p] (udp_socket (Some p) true) ∗\n        ⌜is_set promises vp⌝ ∗\n        ⌜size senders = n⌝ ∗\n        (∀ a, ⌜a ∈ senders⌝ -∗\n               ∃ mv, ⌜mv ∈ promises⌝ ∗ msgs_elem_of (msg1b a b mv)) ∗\n        (* TODO: better spec/implementation? - this is a bit silly *)\n        (∀ mv, ⌜mv ∈ promises⌝ →\n               ∃ a, ⌜a ∈ senders⌝ ∗ msgs_elem_of (msg1b a b mv)) }}}.\n  Proof.\n    iIntros (? Φ) \"(#Hinv & #Hp_si & Hh) HΦ\". rewrite /recv_promises.\n    wp_pures.\n    wp_apply (wp_set_empty (option (Ballot * Value))); [done|].\n    iIntros (vp Hvp). wp_alloc lp as \"Hlp\".\n    wp_pures.\n    wp_apply (wp_set_empty Acceptor); [done|].\n    iIntros (vs Hvs). wp_alloc ls as \"Hls\".\n    do 4 wp_pure _.\n    (* loop invariant *)\n    iAssert (\n        ∃ (promises : gset (option (Ballot * Value))) (senders : gset Acceptor) vp vs,\n          lp ↦[ip_of_address p] vp ∗ ls ↦[ip_of_address p] vs ∗\n             ⌜is_set promises vp⌝ ∗ ⌜is_set senders vs⌝ ∗\n             (∀ a, ⌜a ∈ senders⌝ -∗\n                    ∃ mv, ⌜mv ∈ promises⌝ ∗ msgs_elem_of (msg1b a b mv)) ∗\n             (∀ mv, ⌜mv ∈ promises⌝ →\n               ∃ a, ⌜a ∈ senders⌝ ∗ msgs_elem_of (msg1b a b mv)))%I\n      with \"[Hlp Hls]\" as \"Hloop\".\n    { iExists ∅, ∅, _, _. iFrame \"∗%\". iSplit; iIntros (? []%elem_of_empty). }\n    clear Hvp Hvs vs vp. wp_pure _.\n    iLöb as \"IH\".\n    iDestruct \"Hloop\" as (promises senders vp vs) \"(Hlp & Hls & %Hvp & %Hvs & Hincl & Hacc)\".\n    wp_pures.\n    wp_load.\n    wp_apply wp_set_cardinal; [done|]; iIntros \"_\".\n    wp_op. case_bool_decide as Heq; wp_pures.\n    { wp_load. iApply \"HΦ\". iFrame. apply Nat2Z.inj in Heq. by iFrame \"%\". }\n    wp_bind (ReceiveFrom _).\n    iInv (paxosN) as (δ) \"(>Hfrag & >Hmauth & >Hbal & >Hval & Hmcoh & >HbI)\"\n                         \"Hclose\".\n    iDestruct \"Hmcoh\" as \">Hmcoh\".\n    iDestruct \"Hmcoh\" as (F Ts) \"(Has & Hps & -> & %HM)\".\n    iDestruct (big_sepS_delete _ _ p with \"Hps\") as \"[[% Hp] Hps]\"; [done|].\n    wp_apply (aneris_wp_pers_receivefrom with \"[$Hh $Hp $Hp_si]\"); [done..|].\n    iIntros (m) \"(Hh & Hp & Hm)\".\n    iMod (\"Hclose\" with \"[-Hh Hm Hlp Hls Hincl Hacc HΦ]\") as \"_\".\n    { iModIntro. iExists _. iFrame.\n      iExists _, _. iFrame (HM) \"Has\".\n      iSplit; [|done].\n      iDestruct (big_sepS_insert _ _ p with \"[Hp $Hps]\")\n        as \"Hps\"; [set_solver|eauto|].\n      rewrite -union_difference_singleton_L //. }\n    rewrite /proposer_si.\n    iDestruct \"Hm\" as (?? mval Hser) \"(-> & Hm)\".\n    iModIntro. wp_apply wp_unSOME; [done|]; iIntros \"_\".\n    wp_pures.\n    wp_apply (s_deser_spec proposer_serialization); [done|]; iIntros \"_\".\n    wp_pures.\n    case_bool_decide; wp_if; last first.\n    { wp_seq. wp_apply (\"IH\" with \"Hh HΦ [Hlp Hls Hincl Hacc]\").\n      iExists _, _, _, _. auto with iFrame. }\n    simplify_eq.\n    wp_load.\n    wp_apply (wp_set_add $! Hvs). iIntros (vs' ?).\n    wp_store. wp_load.\n    wp_apply (wp_set_add $! Hvp).\n    iIntros (vp' Hvp'). wp_store.\n    wp_apply (\"IH\" with \"Hh HΦ\").\n    iExists (_ ∪ _), (_ ∪ _), _, _. iFrame \"Hlp Hls\".\n    do 2 (iSplit; [done|]).\n    iSplit; last first.\n    { iIntros (mv). rewrite elem_of_union elem_of_singleton. iIntros ([-> | Hin]).\n      - iExists _. iFrame. iPureIntro; set_solver.\n      - iDestruct (\"Hacc\" $! mv Hin) as (a') \"[% ?]\".\n        iExists a'. iFrame. iPureIntro; set_solver. }\n    iIntros (a').\n    rewrite elem_of_union elem_of_singleton.\n    iIntros ([-> | ?]); last first.\n    { iDestruct (\"Hincl\" $! a' with \"[//]\") as (mv') \"[% H]\".\n      iExists mv'. iFrame. iPureIntro; set_solver. }\n    iExists _. iFrame. iPureIntro; set_solver.\n  Qed.\n\n  Lemma find_max_promise_spec (lp : val)\n        (promises : gset (option (Ballot * Value))) ip :\n    is_set promises lp →\n    {{{ True }}}\n      find_max_promise lp @[ip]\n    {{{ v, RET v;\n        (⌜v = NONEV⌝ ∗ ⌜set_Forall (λ p, p = None) promises⌝) ∨\n        (∃ (b : Ballot) (val : Value),\n            ⌜Some (b, val) ∈ promises⌝ ∗\n            ⌜v = SOMEV ($b, $val)⌝ ∗\n            ⌜set_Forall (λ p, if p is Some (b', v')\n                              then b ≥ b' else True) promises⌝) }}}.\n  Proof.\n    iIntros (? Φ) \"_ HΦ\". rewrite /find_max_promise.\n    wp_pures.\n    wp_apply (wp_set_foldl (A := option (Ballot * Value))\n                (λ X v, (⌜v = NONEV⌝ ∗ ⌜set_Forall (λ p, p = None) X⌝) ∨\n                        (∃ (b : Ballot) (val : Value),\n                            ⌜Some (b, val) ∈ X⌝ ∗\n                            ⌜v = SOMEV ($b, $val)⌝ ∗\n                            ⌜set_Forall (λ p, if p is Some (b', v')\n                                              then b ≥ b' else True) X⌝))%I\n                (λ _, True%I) (λ _, True%I)).\n    { iIntros ([[b v]|] acc X) \"!#\";\n        iIntros (Ψ) \"[[[-> %Hall] | (% & % & %Hin & -> & %Hall)] _] HΨ\".\n      - wp_pures. iApply \"HΨ\". iSplit; [|done]. iRight.\n        iExists b, v. iPureIntro.\n        split; [by apply elem_of_union_r, elem_of_singleton|].\n        split; [done|].\n        apply set_Forall_union.\n        { apply (set_Forall_impl _ _ _ Hall). by intros ? ->. }\n        apply set_Forall_singleton. lia.\n      - wp_pures. case_bool_decide; wp_if.\n        + iApply \"HΨ\". iPureIntro.\n          split; [|done]. right.\n          do 2 eexists.\n          split; [apply elem_of_union_l, Hin|].\n          split; [done|].\n          apply set_Forall_union; [done|].\n          apply set_Forall_singleton. lia.\n        + iApply \"HΨ\". iPureIntro.\n          split; [|done]. right.\n          do 2 eexists.\n          split; [by apply elem_of_union_r, elem_of_singleton|].\n          split; [done|].\n          apply set_Forall_union; [|apply set_Forall_singleton; lia].\n          apply (set_Forall_impl _ _ _ Hall).\n          intros [[]|]; [|done]. lia.\n      - wp_pures. iApply \"HΨ\". iPureIntro.\n        split; [|done]. left.\n        split; [done|].\n        apply set_Forall_union; [done|].\n        by apply set_Forall_singleton.\n      - wp_pures. iApply \"HΨ\". iPureIntro.\n        split; [|done]. right.\n        do 2 eexists.\n        split; [by apply elem_of_union_l, Hin|].\n        split; [done|].\n        apply set_Forall_union; [done|].\n        by apply set_Forall_singleton. }\n    { iFrame \"%\". rewrite big_opS_unit; eauto. }\n    iIntros (?) \"[H _]\". by iApply \"HΦ\".\n  Qed.\n\n  (* Definition bal (n : nat) (p : nat) := n * ProposersN + p. *)\n\n  Lemma proposer_spec av h b (p : Proposer) (z : Value) :\n    is_set Acceptors av →\n    inv paxosN paxos_inv -∗\n    ([∗ set] a ∈ Acceptors, a ⤇ acceptor_si) -∗\n    (`p) ⤇ proposer_si -∗\n    h ↪[ip_of_address (`p)] (udp_socket (Some (`p)) true) -∗\n    pending b -∗\n    WP proposer int_serializer av #(LitSocket h) #b #`z @[ip_of_address (`p)]\n    {{ _, ∃ v, msgs_elem_of (msg2a b v) ∗\n               h ↪[ip_of_address (`p)] (udp_socket (Some (`p)) true) }}.\n  Proof.\n    iIntros (?) \"#Hinv #HA_sis #Hp_si Hh Hb\".\n    rewrite /proposer.\n    wp_pures.\n    wp_apply (s_ser_spec (acceptor_serialization)).\n    { iPureIntro. apply serializable. }\n    iIntros (s) \"%Hser\".\n    (* send a phase 1a message to all acceptors, taking a step in the model for\n       each message. *)\n    wp_apply (wp_pers_sendto_all_take_step\n                True%I\n                (λ _, msgs_elem_of (msg1a _))\n                (λ _, True)%I\n                with \"[] [$Hh //]\"); [done|done|eassumption| |].\n    { iIntros \"!#\" (a ?) \"(_ & _ & %Ha)\".\n      set (m := {| m_sender := `p; m_destination := a;\n                   m_protocol := _; m_body := s |}).\n      iInv (paxosN) as (δ) \">(Hfrag & Hmauth & Hbal & Hval & Hmcoh & HbI)\" \"Hclose\".\n      iMod (msgs_update (msg1a b) with \"Hmauth\") as \"[Hmauth #Hm]\".\n      iModIntro.\n      iDestruct \"Hmcoh\" as (F Ts) \"(Has & Hps & -> & %HM)\".\n      iDestruct (big_sepS_delete _ _ (`p) with \"Hps\") as \"[[% Hp] Hps]\"; [auto|].\n      iDestruct (big_sepS_elem_of _ _ a with \"HA_sis\") as \"#Ha_si\"; [done|].\n      iExists _, _, _, _, δ, (δ <| msgs ::= λ ms, ms ∪ {[msg1a _]} |>).\n      iFrame \"#∗\".\n      iSplit.\n      { iPureIntro. right. constructor. }\n      iSplitR.\n      { iExists p. iSplit; [done|]. iLeft. iExists _. iFrame \"% #\". }\n      iIntros \"(Hp & Hfrag)\".\n      iMod (\"Hclose\" with \"[-]\"); [|done].\n      iModIntro. iExists _. iFrame.\n      iSplitR \"HbI\"; last first.\n      { iApply (ballot_inv_send_not2a with \"HbI\"). naive_solver. }\n      iExists (<[(`p) := {[m]} ∪ F (`p)]>F), _; simpl.\n      rewrite send_msg_notin; [|auto].\n      iFrame.\n      iDestruct (send_msg_combine with \"Hp Hps\") as \"$\"; [auto|].\n      iSplit; [done|].\n      iPureIntro.\n      apply messages_agree_add; [| |done].\n      { apply elem_of_union; auto. }\n      simpl. destruct_is_ser Hser.\n      by exists p, (a ↾ Ha). }\n    iIntros \"(_ & Hh & _ & Helem)\". wp_pures.\n    wp_apply (wp_set_cardinal with \"[//]\"); iIntros \"_\".\n    wp_pures.\n    replace #(_ + 1) with #(size Acceptors / 2 + 1)%nat; last first.\n    { do 2 f_equal. lia. }\n    wp_apply (recv_promises_spec with \"[$Hinv $Hp_si $Hh]\"); [auto|].\n    iIntros (vp promises senders) \"(Hh & %Hvp & %Hsize & #Hmsgs & #Hacc)\".\n    wp_pures.\n    (* find the maximum phase 1b message from the majority, if any *)\n    wp_apply (find_max_promise_spec _ promises with \"[//]\"); [done|].\n    iIntros (?) \"[(-> & %Hpromises) | (%b0 & %z' & %Hin &-> & %Hall)]\".\n    - (* no value was proposed by the majority *)\n      wp_pures.\n      iMod (pend_update_shot b z with \"Hb\") as \"#Hshot\".\n      wp_apply (s_ser_spec (acceptor_serialization)).\n      { iPureIntro. apply serializable. }\n      iIntros (s' Hser').\n      (* send phase 2a decision to all acceptors *)\n      wp_apply (wp_pers_sendto_all_take_step\n                  True%I (λ _, msgs_elem_of (msg2a b z)) (λ _, True)%I\n                  with \"[Hmsgs] [$Hh]\"); [done|done|eassumption| |].\n      { iIntros \"!#\" (a _) \"(_ & _ & %Ha)\".\n        iInv (paxosN) as (δ) \">(Hfrag & Hmauth & Hbal & Hval & Hmcoh & HbI)\" \"Hclose\".\n        iAssert (⌜∀ a, a ∈ senders →\n                       ∃ mv, mv ∈ promises ∧ msg1b a b mv ∈ δ.(msgs)⌝)%I\n          as \"%Hsenders\".\n        { iIntros (a' Ha').\n          iDestruct (\"Hmsgs\" $! a' Ha') as (mv) \"[% Hm]\".\n          iDestruct (msgs_elem_of_in with \"Hmauth Hm\") as %?. eauto. }\n        iMod (msgs_update (msg2a b z) with \"Hmauth\") as \"[Hmauth #Hm]\".\n        iModIntro.\n        iDestruct \"Hmcoh\" as (F Ts) \"(Has & Hps & -> & %HM)\".\n        iDestruct (big_sepS_delete _ _ (`p) with \"Hps\") as \"[[% Hp] Hps]\"; [auto|].\n        iDestruct (big_sepS_elem_of _ _ a with \"HA_sis\") as \"#Ha_si\"; [done|].\n        set (m := {| m_sender := `p; m_destination := a;\n                     m_protocol := _; m_body := s' |}).\n        (* this viewshift is used for all acceptors; here we destruct on whether\n           we're considering the first (the 2a message has not been recorded in\n           the model) or not. *)\n        destruct (decide (msg2a b z ∈ δ.(msgs))).\n        + iExists _, _, _, _, δ, δ.\n          iFrame \"Hfrag Hp Ha_si\".\n          iSplit; [auto|].\n          iSplitR.\n          { iExists p. iSplit; [done|]. iRight. iExists _, z. by iFrame \"Hm\". }\n          iIntros \"(Hp & Hfrag)\".\n          iMod (\"Hclose\" with \"[-]\") as \"_\"; [|auto].\n          iModIntro. iExists _. simpl.\n          assert ((msgs δ ∪ {[msg2a b z]}) = msgs δ) as -> by set_solver.\n          iFrame.\n          iExists (<[(`p) := {[m]} ∪ F (`p)]>F), _; iFrame.\n          rewrite send_msg_notin; [|auto]. iFrame.\n          iDestruct (send_msg_combine with \"Hp Hps\") as \"$\"; [auto|].\n          iSplit; [done|]. iPureIntro.\n          eapply messages_agree_duplicate; [done| |done].\n          destruct_is_ser Hser'. by exists p, (a ↾ Ha).\n        + iExists _, _, _, _, δ, (δ <| msgs ::= λ ms, ms ∪ {[msg2a _ z]} |>).\n          iAssert (⌜¬ (∃ z', msg2a b z' ∈ msgs δ)⌝)%I as \"%\".\n          { iIntros ([? Hz']).\n            iSpecialize (\"HbI\" $! _ _ Hz').\n            by iDestruct (shot_agree with \"Hshot HbI\") as %->. }\n          iDestruct (frag_st_rtc with \"Hfrag\") as %Hrtc.\n          iFrame \"Hfrag Hp Ha_si\".\n          iSplit.\n          { iPureIntro. right.\n            eapply (phase2a _ _ _ senders).\n            * done.\n            * apply majority_show_quorum. rewrite Hsize. lia.\n            * split.\n              - intros a' Ha'.\n                destruct (Hsenders a' Ha') as (mv &?&?).\n                exists (msg1b a' b mv).\n                rewrite !elem_of_PropSet. split; eauto.\n              - left.\n                rewrite set_equiv=> m'.\n                rewrite !elem_of_PropSet.\n                split; [|done].\n                intros ([Hin1 (? &?&?& Ha')] & a' & [? ?]); simplify_eq.\n                destruct (Hsenders a' Ha') as (? & Hprom & Hin2).\n                (* N.B.: here we are explicitlty using a pure property of the\n                   model to obtain the contradiction! *)\n                specialize (msg1b_agree _ _ _ _ _ Hrtc Hin1 Hin2).\n                rewrite (Hpromises _ Hprom).\n                done. }\n          iSplit.\n          { iExists p. iSplit; [done|]. iRight. iExists _, z. by iFrame \"Hm\". }\n          iIntros \"[Hp Hfrag]\".\n          iMod (\"Hclose\" with \"[-]\") as \"_\"; [|auto].\n          iModIntro. iExists _. iFrame \"Hfrag Hmauth Hbal Hval\".\n          iSplitR \"HbI\"; last first.\n          { iIntros (??).\n            rewrite elem_of_union elem_of_singleton.\n            iIntros ([?|?]); by [iApply \"HbI\"|simplify_eq]. }\n          iExists (<[(`p) := {[m]} ∪ F (`p)]>F), _. simpl.\n          rewrite send_msg_notin; [|auto]. iFrame.\n          iDestruct (send_msg_combine with \"Hp Hps\") as \"$\"; [auto|].\n          iSplit; [done|].\n          iPureIntro.\n          apply messages_agree_add; [| |done].\n          { apply elem_of_union; auto. }\n          destruct_is_ser Hser'. by exists p, (a ↾ Ha). }\n      iIntros \"(_ & Hh & _ & H2a)\".\n      iExists _. iFrame.\n      destruct Acceptors_choose as [a ?].\n      by iApply (big_sepS_elem_of _ _ a with \"H2a\").\n    - (* a value has already been proposed *)\n      wp_pures.\n      wp_apply (s_ser_spec (acceptor_serialization)).\n      { iPureIntro. apply serializable. }\n      iIntros (s' Hser').\n      iMod (pend_update_shot b z' with \"Hb\") as \"#Hshot\".\n      wp_apply (wp_pers_sendto_all_take_step\n                  True%I (λ _, msgs_elem_of (msg2a b z')) (λ _, True)%I\n                  with \"[Hmsgs] [$Hh]\"); [done|done|eassumption| |].\n      { iIntros \"!#\" (a _) \"(_ & _ & %Ha)\".\n        iInv (paxosN) as (δ) \">(Hfrag & Hmauth & Hbal & Hval & Hmcoh & HbI)\"\n                                 \"Hclose\".\n        iAssert (⌜∀ a, a ∈ senders →\n                       ∃ mv, mv ∈ promises ∧ msg1b a b mv ∈ δ.(msgs)⌝)%I as \"%Hsenders\".\n        { iIntros (a' Ha').\n          iDestruct (\"Hmsgs\" $! a' Ha') as (mv) \"[% Hm']\".\n          iDestruct (msgs_elem_of_in with \"Hmauth Hm'\") as %?. eauto. }\n        iAssert (⌜∀ mv, mv ∈ promises →\n                        ∃ a, a ∈ senders ∧ msg1b a b mv ∈ δ.(msgs)⌝)%I as \"%Hpromises\".\n        { iIntros (mv Hmv).\n          iDestruct (\"Hacc\" $! mv Hmv) as (a') \"[% Hm']\".\n          iDestruct (msgs_elem_of_in with \"Hmauth Hm'\") as %?. eauto. }\n        iMod (msgs_update (msg2a b z') with \"Hmauth\") as \"[Hmauth #Hm]\".\n        iModIntro.\n        iDestruct \"Hmcoh\" as (F Ts) \"(Has & Hps & -> & %HM)\".\n        iDestruct (big_sepS_delete _ _ (`p) with \"Hps\") as \"[[% Hp] Hps]\"; [auto|].\n        iDestruct (big_sepS_elem_of _ _ a with \"HA_sis\") as \"#Ha_si\"; [done|].\n        set (m := {| m_sender := `p; m_destination := a; m_protocol := _; m_body := s' |}).\n        destruct (decide ((msg2a b z') ∈ δ.(msgs))).\n        + iExists _, _, _, _, δ, δ.\n          iFrame \"Hfrag Hp Ha_si\".\n          iSplit; [auto|].\n          iSplit.\n          { iExists p. iSplit; [done|]. iRight. iExists _, _. by iFrame \"Hm\". }\n          iIntros \"[Hp Hfrag]\".\n          iMod (\"Hclose\" with \"[-]\") as \"_\"; [|auto].\n          iModIntro. iExists _. simpl.\n          assert ((msgs δ ∪ {[msg2a b z']}) = msgs δ) as -> by set_solver.\n          iFrame. iExists (<[(`p) := {[m]} ∪ F (`p)]>F), _.\n          rewrite send_msg_notin; [|auto]. iFrame.\n          iDestruct (send_msg_combine with \"Hp Hps\") as \"$\"; [auto|].\n          iSplit; [done|]. iPureIntro.\n          eapply messages_agree_duplicate; [done| |done].\n          destruct_is_ser Hser'. by exists p, (a ↾ Ha).\n        + iExists _, _, _, _, δ, (δ <| msgs ::= λ ms, ms ∪ {[msg2a b z']} |>).\n          iAssert (⌜¬ (∃ z', msg2a b z' ∈ msgs δ)⌝)%I as \"%\".\n          { iIntros ([? Hz']).\n            iSpecialize (\"HbI\" $! _ _ Hz').\n            by iDestruct (shot_agree with \"Hshot HbI\") as %->. }\n          iDestruct (frag_st_rtc with \"Hfrag\") as %Hrtc.\n          iFrame \"Hfrag Hp Ha_si\".\n          iSplit.\n          { iPureIntro. right.\n            eapply (phase2a _ z' _ senders).\n            * done.\n            * apply majority_show_quorum. rewrite Hsize. lia.\n            * split.\n              - intros a' Ha'.\n                destruct (Hsenders a' Ha') as (mv &?&?).\n                exists (msg1b a' b mv).\n                rewrite !elem_of_PropSet. split; eauto.\n              - right.\n                destruct (Hpromises _ Hin) as (a' & Ha' & Hm).\n                eexists _; exists a', b0.\n                repeat split; eauto.\n                intros m' ((Hin1 &?&?&?& Hin') & ? & ([]&?)); simplify_eq.\n                do 3 eexists. split; [done|].\n                destruct (Hsenders _ Hin') as (mv & Hmv & Hin2).\n                specialize (Hall _ Hmv).\n                (* N.B.: here we are explicitlty using a pure property of the\n                   model to finish the proof!  *)\n                specialize (msg1b_agree _ _ _ _ _ Hrtc Hin1 Hin2) as ?.\n                simplify_eq. done. }\n          iSplitR.\n          { iExists p. iSplit; [done|]. iRight. iExists _, z'. by iFrame \"Hm\". }\n          iIntros \"[Hp Hfrag]\".\n          iMod (\"Hclose\" with \"[-]\") as \"_\"; [|auto].\n          iModIntro. iExists _. iFrame.\n          iSplitR \"HbI\"; last first.\n          { iIntros (??).\n            rewrite elem_of_union elem_of_singleton.\n            iIntros ([?|?]); by [iApply \"HbI\"|simplify_eq]. }\n          iExists (<[(`p) := {[m]} ∪ F (`p)]>F), _; simpl.\n          rewrite send_msg_notin; [|auto]. iFrame.\n          iDestruct (send_msg_combine with \"Hp Hps\") as \"$\"; [auto|].\n          iSplit; [done|].\n          iPureIntro.\n          apply messages_agree_add; [| |done].\n          { apply elem_of_union; auto. }\n          destruct_is_ser Hser'. by exists p, (a ↾ Ha). }\n      iIntros \"(_ & Hh & _ & H2a)\".\n      iExists _. iFrame.\n      destruct Acceptors_choose as [a ?].\n      by iApply (big_sepS_elem_of _ _ a with \"H2a\").\n  Qed.\n\n  Lemma proposer'_spec av i (p : Proposer) (z : Value) A :\n    i < size Proposers →             \n    `p ∈ A →\n    is_set Acceptors av →\n    inv paxosN paxos_inv -∗\n    ([∗ set] a ∈ Acceptors, a ⤇ acceptor_si) -∗\n    fixed A -∗\n    free_ports (ip_of_address (`p)) {[port_of_address (`p)]} -∗\n    (`p) ⤇ proposer_si -∗\n    pending_class i 0 -∗\n    WP proposer' int_serializer av #(`p) #i #(size Proposers) #`z\n       @[ip_of_address (`p)] {{ _, True }}.\n  Proof.\n    iIntros (???) \"#Hinv #Has #Hfixed Hport #Hp Hi\". rewrite /proposer'.\n    wp_pures.\n    wp_socket sh as \"Hskt\".\n    wp_pures.\n    wp_socketbind_static.\n    wp_alloc l as \"Hl\".\n    do 4 wp_pure _.\n    (* loop invariant *)\n    iAssert (∃ c, pending_class i c ∗ l ↦[ip_of_address (`p)] #c)%I\n      with \"[Hi Hl]\" as \"Hloop\".\n    { iExists 0. replace (#0%nat) with (#0) by f_equal. iFrame. }\n    wp_pure _.\n    iLöb as \"IH\".\n    iDestruct \"Hloop\" as (b) \"(Hi & Hl)\".\n    wp_pures.\n    wp_load.\n    wp_pures.\n    iDestruct (pending_pend_split with \"Hi\") as \"[Hi Hpend]\"; [done|].                             \n    replace (#(b * size Proposers + i)) with (#(b * size Proposers + i)%nat)\n      by (do 2 f_equal; lia).\n    wp_bind (proposer _ _ _ _ _)%E.\n    wp_apply aneris_wp_wand_r. iSplitL \"Hpend Hskt\".\n    { by wp_apply (proposer_spec with \"Hinv Has Hp Hskt Hpend\"). }\n    iIntros (?) \"(% & #? & Hskt)\".\n    wp_seq. wp_load. wp_op.\n    wp_store.\n    iApply (\"IH\" with \"Hskt [-]\").\n    iExists _. iFrame.\n    replace (#(b + 1)%nat) with (#(b + 1)) by (do 2 f_equal; lia).\n    done.\n  Qed.\n\nEnd paxos_proposer.\n", "meta": {"author": "fresheed", "repo": "trillium-experiments", "sha": "a9c38a9e9566fb8057ae97ecb8d1a0c09c799aef", "save_path": "github-repos/coq/fresheed-trillium-experiments", "path": "github-repos/coq/fresheed-trillium-experiments/trillium-experiments-a9c38a9e9566fb8057ae97ecb8d1a0c09c799aef/theories/consensus/paxos_proposer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2321550700079415}}
{"text": "Require Import\n  Pact.Lib\n  Pact.Value\n  Hask.Control.Monad.Trans.State\n  Pact.Data.Either.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSet Equations With UIP.\n\nGeneralizable All Variables.\nSet Primitive Projections.\n\n(*************************************************************************\n * Capability values\n *)\n\nRecord CapSig : Set := {\n  paramTy : ValueTy;\n  valueTy : ValueTy;\n}.\n\nDerive NoConfusion NoConfusionHom Subterm EqDec for CapSig.\n\n(* jww (2022-07-21): Capabilities need to match also on the module name *)\nInductive Cap (s : CapSig) : Type :=\n  | Token (name : string) :\n    reflectTy (paramTy s) → reflectTy (valueTy s) → Cap s.\n\nDerive NoConfusion NoConfusionHom Subterm for Cap.\n\n#[export]\nProgram Instance Cap_EqDec {s} : EqDec (Cap s).\nNext Obligation.\n  destruct x as [n1 p1 v1], y as [n2 p2 v2].\n  destruct (string_EqDec n1 n2); [subst|sauto].\n  destruct (reflectTy_EqDec p1 p2); [subst|sauto].\n  destruct (reflectTy_EqDec v1 v2); sauto.\nDefined.\n\nArguments Token {s} name arg val.\n\nDefinition nameOf `(c : Cap s) : string :=\n  match c with Token n _ _ => n end.\n\nDefinition paramOf `(c : Cap s) : reflectTy (paramTy s) :=\n  match c with Token _ p _ => p end.\n\nDefinition valueOf `(c : Cap s) : reflectTy (valueTy s) :=\n  match c with Token _ _ v => v end.\n\nInductive ACap : Type :=\n  | AToken (s : CapSig) : Cap s → ACap.\n\nDerive NoConfusion NoConfusionHom Subterm for ACap.\n\n#[export]\nProgram Instance ACap_EqDec : EqDec ACap.\nNext Obligation.\n  destruct x, y.\n  destruct (CapSig_EqDec s s0); [subst|right; congruence].\n  apply dec_eq_f1.\n  - apply Cap_EqDec.\n  - now intros ? ? H; inv H.\nDefined.\n\nInductive CapError : Set :=\n  | CapErr_CapabilityNotAvailable\n  | CapErr_NoResourceAvailable\n  | CapErr_CannotInstallInDefcap\n  | CapErr_CannotWithInDefcap\n  | CapErr_CannotWithOutsideDefcapModule\n  | CapErr_CannotComposeOutsideDefcap\n  | CapErr_CannotComposeOutsideDefcapModule.\n\nDerive NoConfusion NoConfusionHom Subterm EqDec for CapError.\n", "meta": {"author": "kadena-io", "repo": "pact-model", "sha": "2a6ab4b3b53d7e53857aa0148f57ed86ffe9e3f4", "save_path": "github-repos/coq/kadena-io-pact-model", "path": "github-repos/coq/kadena-io-pact-model/pact-model-2a6ab4b3b53d7e53857aa0148f57ed86ffe9e3f4/src/Lang/CapabilityType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23215507000794144}}
{"text": "Require Export MMLL.Misc.UtilsTactics.\nRequire Export MMLL.OL.CutCoherence.LNSi.LJBipoles.\nRequire Export MMLL.SL.FLLReasoning.\nRequire Export MMLL.SL.InvPositivePhase.\n         \nExport ListNotations.\nExport LLNotations.\n\nSet Implicit Arguments.\n\nSection LJInv.\n\nContext {SI: Signature}.\nContext {Unb: UnbSignature}.\nContext {UnbD: UnbNoDSignature}.\n\n  Theorem InvTT:  forall n a B M, \n   IsPositiveAtomFormulaL M ->\n   IsPositiveAtomFormulaL (second B) ->\n    seqN (LJ a) n ((a,d| t_cons TT|)::B) M (UP []) -> seq (LJ a) B M (UP []).\n    Proof with sauto;OLSolve.\n      induction n using strongind;intros.\n      inversion H1...\n      inversion H2...\n       apply RemoveNotPos1 in H5...\n       intro Hc. inversion Hc;inversion H4...\n       inversion H7...\n       contradict H6.\n       constructor.\n       apply InUNotPos in H3...\n       rewrite allU in H4...\n       2:{ solveSignature1. }\n       inversion H4...\n       + inversion H3...\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             inversion H10...\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor [u| t_cons TT | ] x0.\n             simpl... \n             simpl in H12.\n             checkPermutationCases H12.\n             inversion H10...\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor (@nil oo) M.\n             LLrew2 H8. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H6...\n             inversion H10...\n             solveF.\n             inversion H10...\n             solveF.\n           - apply BipoleReasoning in H6...\n             inversion H10...\n             solveF.\n             inversion H10...\n             solveF.\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             inversion H10...\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor [d| t_cons FF| ] x0.\n             simpl... \n             simpl in H12.\n             checkPermutationCases H12.\n             inversion H10...\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor (@nil oo) M.\n             LLrew2 H8. \n             init2 x0 x2.\n             simpl...\n       + inversion H3...\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             apply FocusingWith in H10...\n             apply H in H10, H12...\n             TFocus (BinBipole AND_BODY Right F0 G).\n             LLTensor [u| t_bin AND F0 G| ] x0.\n             simpl...\n             simpl in H12.\n             checkPermutationCases H12.\n             apply FocusingWith in H10...\n             apply H in H13, H14...\n             TFocus (BinBipole AND_BODY Right F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H8. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             apply FocusingPlus in H10...\n             1-2: apply H in H9...\n             1-2:TFocus (BinBipole AND_BODY Left F0 G).\n             1-2:LLTensor [d| t_bin AND F0 G| ] x0.\n             1-2:simpl...\n             simpl in H12.\n             checkPermutationCases H12.\n             apply FocusingPlus in H10...\n             1-2: apply H in H12...\n             1-2:TFocus (BinBipole AND_BODY Left F0 G).\n             1-2:LLTensor (@nil oo) M.\n             1,3: LLrew2 H8.\n             1,2: init2 x0 x2.\n             1,2: simpl...\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             apply FocusingPlus in H10...\n             1-2: apply H in H9...\n             1-2:TFocus (BinBipole OR_BODY Right F0 G).\n             1-2:LLTensor [u| t_bin OR F0 G| ] x0.\n             1-2:simpl...\n             simpl in H12.\n             checkPermutationCases H12.\n             apply FocusingPlus in H10...\n             1-2: apply H in H12...\n             1-2:TFocus (BinBipole OR_BODY Right F0 G).\n             1-2:LLTensor (@nil oo) M.\n             1,3: LLrew2 H8.\n             1,2: init2 x0 x2.\n             1,2: simpl...\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             apply FocusingWith in H10...\n             apply H in H10, H12...\n             TFocus (BinBipole OR_BODY Left F0 G).\n             LLTensor [d| t_bin OR F0 G| ] x0.\n             simpl...\n             simpl in H12.\n             checkPermutationCases H12.\n             apply FocusingWith in H10...\n             apply H in H13, H14...\n             TFocus (BinBipole OR_BODY Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H8. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H6...\n             simpl in H13.\n             apply FocusingBangPar in H12...\n             checkPermutationCases H11.\n             LLrew1 H10 H18.\n             apply H in H18...\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n             LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n             simpl... createWorld. solveSignature1.\n             apply GenK4RelUT' with (C4:= x) \n                        (CK:=[])\n                        (CN:=x3);solveSignature1...\n             rewrite H10 in H14. solveSE.\n             rewrite H10 in H15. solveSE.\n             rewrite H10 in H16. solveLT.\n             simpl...\n             symmetry in H11.\n             srewrite H11 in H1.\n             rewrite map_app in H1. OLSolve.\n            TFocus (BinBipole (IMP_BODY a) Right F0 G).\n             LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n             simpl... createWorld. solveSignature1.\n             apply GenK4RelUT' with (C4:= x2) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n             simpl...\n             LLPar. do 2 LLStore.\n             HProof.\n             \n             simpl in H14.\n             checkPermutationCases H14.\n             apply FocusingBangPar in H12...\n             checkPermutationCases H14.\n             LLrew1 H12 H20.\n             apply H in H20...\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n             LLTensor.\n             LLrew2 H10. \n             init2 x0 x2.\n             simpl... createWorld. solveSignature1.\n             apply GenK4RelUT' with (C4:= x) \n                        (CK:=[])\n                        (CN:=x5);solveSignature1...\n             rewrite H12 in H16. solveSE.\n             rewrite H12 in H17. solveSE.\n             rewrite H12 in H18. solveLT.\n             simpl...\n             symmetry in H14.\n             srewrite H14 in H1.\n             rewrite map_app in H1. OLSolve.\n            TFocus (BinBipole (IMP_BODY a) Right F0 G).\n             LLTensor.\n             LLrew2 H10. \n             init2 x0 x2.\n             simpl... createWorld. solveSignature1.\n             apply GenK4RelUT' with (C4:= x4) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n             simpl...\n             LLPar. do 2 LLStore.\n             HProof.\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             apply FocusingTensor in H10...\n             apply H in H9, H13...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor [d| t_bin IMP F0 G| ] x0.\n             simpl...\n             LLTensor x2 x3.\n             1-2: rewrite H10 in H11.\n             1-2: rewrite H11 in H0.\n             1-2: inversion H0...\n             \n             simpl in H12.\n             checkPermutationCases H12.\n             apply FocusingTensor in H10...\n             apply H in H12, H15...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H8. \n             init2 x0 x2.\n             LLTensor x4 x5.\n       + apply FocusingInitRuleU in H6...\n           - TFocus (RINIT OO).\n              LLTensor [u| OO |] [d| OO |].\n           - checkPermutationCases H9. \n             TFocus (CteBipole TT_BODY Right).\n             apply ooth_consC.\n             constructor...\n             inversion H6.\n             LLTensor [u| t_cons TT |] (@nil oo).\n             simpl...\n             TFocus (RINIT OO).\n             LLTensor [u| OO |] (@nil oo).\n             LLrew2 H7. \n             init2 x x1.\n           - checkPermutationCases H9. \n             TFocus (RINIT OO).\n             LLTensor  (@nil oo) [d| OO |].\n             LLrew2 H7. \n             init2 x x1.\n           - checkPermutationCases H9. \n             checkPermutationCases H7.\n             TFocus (CteBipole TT_BODY Right).\n             apply ooth_consC.\n             constructor...\n             inversion H6.\n             LLTensor.\n             LLrew2 H9. \n             init2 x0 x3.\n             simpl...\n             TFocus (RINIT OO).\n             LLTensor. \n             init2 x0 x3.\n             init2 x x4.\n       +   apply BipoleReasoning in H6...\n             apply FocusingQuest in H9...\n             LLSwapC H8. \n             apply H in H8...\n             TFocus (POS OO a).\n             LLTensor [d| OO| ] x0.\n             simpl in H11.\n             checkPermutationCases H11.\n             apply FocusingQuest in H9...\n             \n             apply contractionN with (F:=(a, d| t_cons TT_BODY.(cte) |)) in H9...\n             apply H in H9...\n             solveSignature1.\n             simpl...\n             apply FocusingQuest in H9...\n             LLSwapC H11.\n             apply H in H11...\n             TFocus (POS OO a).\n             LLTensor (@nil oo) M.\n             LLrew2 H7. \n             init2 x0 x2.\n       +   apply BipoleReasoning in H6...\n             apply FocusingQuest in H9...\n             LLSwapC H8. \n             apply H in H8...\n             TFocus (NEG OO loc).\n             LLTensor [u| OO| ] x0.\n             simpl in H11.\n             checkPermutationCases H11.\n             apply FocusingQuest in H9...\n             LLSwapC H11.\n             apply H in H11...\n             TFocus (NEG OO loc).\n             LLTensor (@nil oo) M.\n             LLrew2 H7. \n             init2 x0 x2.\n Qed.            \n \n  Theorem InvFF:  forall n a B M, \n   IsPositiveAtomFormulaL M ->\n   IsPositiveAtomFormulaL (second B) ->\n    seqN (LJ a) n ((loc,u| t_cons FF|)::B) M (UP []) -> seq (LJ a) B M (UP []).\n    Proof with sauto;OLSolve.\n      induction n using strongind;intros.\n      inversion H1...\n      inversion H2...\n       apply RemoveNotPos1 in H5...\n       intro Hc. inversion Hc;inversion H4...\n       inversion H7...\n       contradict H6.\n       constructor.\n       apply InUNotPos in H3...\n       rewrite allU in H4...\n       2:{ solveSignature1. }\n       inversion H4...\n       + inversion H3...\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             inversion H10...\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor [u| t_cons TT | ] x0.\n             simpl... \n             simpl in H12.\n             checkPermutationCases H12.\n             inversion H10...\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor (@nil oo) M.\n             LLrew2 H8. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H6...\n             inversion H10...\n             solveF.\n             inversion H10...\n             solveF.\n           - apply BipoleReasoning in H6...\n             inversion H10...\n             solveF.\n             inversion H10...\n             solveF.\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             inversion H10...\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor [d| t_cons FF| ] x0.\n             simpl... \n             simpl in H12.\n             checkPermutationCases H12.\n             inversion H10...\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor (@nil oo) M.\n             LLrew2 H8. \n             init2 x0 x2.\n             simpl...\n       + inversion H3...\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             apply FocusingWith in H10...\n             apply H in H10, H12...\n             TFocus (BinBipole AND_BODY Right F0 G).\n             LLTensor [u| t_bin AND F0 G| ] x0.\n             simpl...\n             simpl in H12.\n             checkPermutationCases H12.\n             apply FocusingWith in H10...\n             apply H in H13, H14...\n             TFocus (BinBipole AND_BODY Right F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H8. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             apply FocusingPlus in H10...\n             1-2: apply H in H9...\n             1-2:TFocus (BinBipole AND_BODY Left F0 G).\n             1-2:LLTensor [d| t_bin AND F0 G| ] x0.\n             1-2:simpl...\n             simpl in H12.\n             checkPermutationCases H12.\n             apply FocusingPlus in H10...\n             1-2: apply H in H12...\n             1-2:TFocus (BinBipole AND_BODY Left F0 G).\n             1-2:LLTensor (@nil oo) M.\n             1,3: LLrew2 H8.\n             1,2: init2 x0 x2.\n             1,2: simpl...\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             apply FocusingPlus in H10...\n             1-2: apply H in H9...\n             1-2:TFocus (BinBipole OR_BODY Right F0 G).\n             1-2:LLTensor [u| t_bin OR F0 G| ] x0.\n             1-2:simpl...\n             simpl in H12.\n             checkPermutationCases H12.\n             apply FocusingPlus in H10...\n             1-2: apply H in H12...\n             1-2:TFocus (BinBipole OR_BODY Right F0 G).\n             1-2:LLTensor (@nil oo) M.\n             1,3: LLrew2 H8.\n             1,2: init2 x0 x2.\n             1,2: simpl...\n           - apply BipoleReasoning in H6...\n             simpl in H11.\n             apply FocusingWith in H10...\n             apply H in H10, H12...\n             TFocus (BinBipole OR_BODY Left F0 G).\n             LLTensor [d| t_bin OR F0 G| ] x0.\n             simpl...\n             simpl in H12.\n             checkPermutationCases H12.\n             apply FocusingWith in H10...\n             apply H in H13, H14...\n             TFocus (BinBipole OR_BODY Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H8. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H6...\n             simpl in H13.\n             apply FocusingBangPar in H12...\n             checkPermutationCases H11.\n             rewrite H10 in H14.\n             inversion H14... solveSignature1.\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n             LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n             simpl... createWorld; solveSignature1.\n             apply GenK4RelUT' with (C4:= x2) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n             apply seqNtoSeq in H18.\n             simpl...\n             \n             checkPermutationCases H14.\n             apply FocusingBangPar in H12...\n             checkPermutationCases H14.\n             rewrite H12 in H16.\n             inversion H16... solveSignature1.\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n             LLTensor.\n             LLrew2 H10. \n             init2 x0 x2.\n             simpl... createWorld; solveSignature1.\n             apply GenK4RelUT' with (C4:= x4) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n             apply seqNtoSeq in H20.\n             simpl...\n            - apply BipoleReasoning in H6...\n             simpl in H11.\n             apply FocusingTensor in H10...\n             apply H in H9, H13...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor [d| t_bin IMP F0 G| ] x0.\n             simpl...\n             LLTensor x2 x3.\n             1-2: rewrite H10 in H11.\n             1-2: rewrite H11 in H0.\n             1-2: inversion H0...\n             \n             simpl in H12.\n             checkPermutationCases H12.\n             apply FocusingTensor in H10...\n             apply H in H12, H15...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H8. \n             init2 x0 x2.\n             LLTensor x4 x5.\n       + apply FocusingInitRuleU in H6...\n           - TFocus (RINIT OO).\n              LLTensor [u| OO |] [d| OO |].\n           - checkPermutationCases H9. \n             TFocus (RINIT OO).\n             LLTensor  [u| OO |]  (@nil oo).\n             LLrew2 H7. \n             init2 x x1.\n           - checkPermutationCases H9. \n             TFocus (CteBipole FF_BODY Left).\n             apply ooth_consC.\n             constructor...\n             inversion H6.\n             LLTensor [d| t_cons FF |] (@nil oo) .\n             simpl...\n             TFocus (RINIT OO).\n             LLTensor (@nil oo)  [d| OO |] .\n             LLrew2 H7. \n             init2 x x1.\n           - checkPermutationCases H9. \n             checkPermutationCases H7.\n             TFocus (CteBipole FF_BODY Left).\n             apply ooth_consC.\n             constructor...\n             inversion H6.\n             LLTensor.\n             LLrew2 H7. \n             init2 x x0.\n             simpl...\n             checkPermutationCases H7.\n             TFocus (RINIT OO).\n             LLTensor. \n             init2 x0 x3.\n             init2 x x4.\n       +   apply BipoleReasoning in H6...\n             apply FocusingQuest in H9...\n             LLSwapC H8. \n             apply H in H8...\n             TFocus (POS OO a).\n             LLTensor [d| OO| ] x0.\n             simpl in H11.\n             checkPermutationCases H11.\n             apply FocusingQuest in H9...\n             \n             LLSwapC H11.\n             apply H in H11...\n             TFocus (POS OO a).\n             LLTensor (@nil oo) M.\n             LLrew2 H7. \n             init2 x0 x2.\n       +   apply BipoleReasoning in H6...\n             apply FocusingQuest in H9...\n             LLSwapC H8. \n             apply H in H8...\n             TFocus (NEG OO loc).\n             LLTensor [u| OO| ] x0.\n             simpl in H11.\n             checkPermutationCases H11.\n             apply FocusingQuest in H9...\n              apply contractionN in H9...\n             apply H in H9...\n             solveSignature1.\n            \n             apply FocusingQuest in H9...\n             LLSwapC H11.\n             apply H in H11...\n             TFocus (NEG OO loc).\n             LLTensor (@nil oo) M.\n             LLrew2 H7. \n             init2 x0 x2.\n Qed.            \n \n \n  Theorem InvIMPR:  forall n a P Q B M, \n   IsPositiveAtomFormulaL M ->\n   IsPositiveAtomFormulaL (second B) ->\n   mt a = true ->\n   m4 a = true ->\n    seqN (LJ a) n ((loc,u| t_bin IMP P Q|) :: (a,d| P| )::  (loc,u| Q| )::B) M (UP []) -> seq (LJ a) ((a,d| P| ):: (loc,u| Q| ):: B) M (UP []).\n    Proof with sauto;OLSolve.\n      induction n using strongind;intros *;\n      intros isFM isFB Hta H4a HF.\n      inversion HF...\n      inversion HF...\n      apply RemoveNotPos1 in H2...\n       intro Hc. inversion Hc;inversion H1...\n       inversion H4...\n       contradict H3.\n       constructor.\n       inversion H0...\n       contradict H3.\n       constructor.\n       inversion H6...\n       contradict H3.\n       constructor.\n       \n       apply InUNotPos in H7...\n       rewrite allU in H1...\n       2:{ solveSignature1. }\n       inversion H1...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor [u| t_cons TT | ] x0.\n             simpl... \n             simpl in H9.\n             checkPermutationCases H9.\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor [d| t_cons FF | ] x0.\n             simpl... \n             checkPermutationCases H9.\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole AND_BODY Right F0 G).\n              LLTensor [u| t_bin AND F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.  \n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole AND_BODY Right F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2: LLTensor [d| t_bin AND F0 G| ] x0.\n            1,2: simpl...\n            simpl in H9.\n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2: LLTensor [u| t_bin OR F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole OR_BODY Left F0 G).\n              LLTensor [d| t_bin OR F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.  \n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole OR_BODY Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            { apply FocusingBangPar in H7...\n               checkPermutationCases H5.\n               rewrite H4 in H9.\n               inversion H9...\n               solveSignature1. \n               checkPermutationCases H5.\n               checkPermutationCases H7.\n               rewrite H7 in H5.\n               rewrite H5 in H9.\n               inversion H9...\n               inversion H15...\n               solveSignature1. \n               LLSwap.\n               apply weakening;solveSignature1...\n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x2) \n                        (CK:=[])\n                        (CN:=x4);solveSignature1...\n                        rewrite <- H8...\n                        rewrite H5...\n              apply seqNtoSeq in H13.           \n              simpl... \n              checkPermutationCases H7.\n               rewrite H7 in H9.\n               inversion H9...\n               solveSignature1. \n               LLSwap.\n               apply weakening;solveSignature1...\n               apply weakening;solveSignature1...\n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x2) \n                        (CK:=[])\n                        (CN:=x4);solveSignature1...\n              apply seqNtoSeq in H13.           \n              simpl... }\n             { \n               checkPermutationCases H9.\n               +\n               clear H8.\n                apply FocusingBangPar in H7...\n               checkPermutationCases H7.\n               rewrite H4 in H9.\n               inversion H9...\n               solveSignature1. \n               checkPermutationCases H7.\n               checkPermutationCases H8.\n               rewrite H8 in H7.\n               rewrite H7 in H9.\n               inversion H9...\n               inversion H16...\n               solveSignature1. \n               apply AbsorptionC';solveSignature1...\n               LLSwap.\n               apply AbsorptionL';solveSignature1...\n               rewrite <- H12.\n               LLPerm  (x4++(a, d| P |) :: x1).\n               apply weakeningGen...\n               rewrite <- H7.\n               HProof.\n               checkPermutationCases H8.\n               rewrite H8 in H9.\n               inversion H9...\n               solveSignature1. \n               apply AbsorptionL';solveSignature1...\n               apply AbsorptionL';solveSignature1...\n               rewrite <- H12.\n               LLPerm  (x4++x2).\n               apply weakeningGen...\n               HProof.\n               + \n               clear H8.\n                apply FocusingBangPar in H7...\n               checkPermutationCases H8.\n               rewrite H7 in H10.\n               inversion H10...\n               solveSignature1. \n               checkPermutationCases H8.\n               checkPermutationCases H9.\n               rewrite H9 in H8.\n               rewrite H8 in H10.\n               inversion H10...\n               inversion H17...\n               solveSignature1.\n              TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor.\n               simpl...  init2 x0 x2.\n                LLSwap.\n               apply weakening;solveSignature1...\n              \n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x4) \n                        (CK:=[])\n                        (CN:=x6);solveSignature1...\n                rewrite <- H13...\n                rewrite H8...        \n              apply seqNtoSeq in H14.           \n              simpl... \n              \n               checkPermutationCases H9.\n               rewrite H9 in H10.\n               inversion H10...\n               solveSignature1.\n              TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor.\n               simpl...  init2 x0 x2.\n               apply weakening;solveSignature1...\n              apply weakening;solveSignature1...\n              \n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x4) \n                        (CK:=[])\n                        (CN:=x6);solveSignature1...\n              apply seqNtoSeq in H14.           \n              simpl... \n              \n              }\n             - apply BipoleReasoning in H3...\n             apply FocusingTensor in H7...\n             apply H in H6, H10...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor [d| t_bin IMP F0 G| ] x0.\n             simpl...\n             LLTensor x2 x3.\n             1-2: rewrite H7 in H8.\n             1-2: rewrite H8 in isFM.\n             1-2: inversion isFM...\n             \n             checkPermutationCases H9.\n             apply FocusingTensor in H7...\n             apply H in H9, H12...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             LLTensor x4 x5. \n       + apply FocusingInitRuleU in H3... \n           - TFocus (RINIT OO).\n              LLTensor [u| OO |] [d| OO |].\n           - checkPermutationCases H6.\n              TFocus (RINIT OO).\n              LLTensor [u| OO |] (@nil oo).\n              init2 x x1.\n           - checkPermutationCases H6.\n             TFocus (BinBipole (IMP_BODY a) Left P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor [d| t_bin IMP P Q |] (@nil oo)  .\n             simpl...\n              LLTensor; LLRelease;LLStore.\n             TFocus (RINIT P).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor [ u| P |] (@nil oo).\n             solveLL.\n             TFocus (RINIT Q).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor (@nil oo) [ d| Q |] .\n             apply weakening;solveSignature1.\n             solveLL.\n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor (@nil oo)  [ d| OO |].\n             apply weakening;solveSignature1.\n             solveLL.\n            - checkPermutationCases H6.\n             checkPermutationCases H4.\n             TFocus (BinBipole (IMP_BODY a) Left P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor.\n             init2 x x0.\n             rewrite H4...\n              LLTensor; LLRelease;LLStore.\n             TFocus (RINIT P).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor [ u| P |] (@nil oo).\n             solveLL.\n             TFocus (RINIT Q).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor (@nil oo) [ d| Q |] .\n             apply weakening;solveSignature1.\n             solveLL.\n            \n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor.\n              LLrew2 H6. \n             init2 x0 x3.\n              LLrew2 H4. \n             init2 x x4.\n       +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((loc, u| t_bin IMP P Q |)\n           :: (a, d| P |) :: (loc, u| Q |) :: (a, d| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor [d| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             \n             assert(Hyp: seqN (LJ a) x3\n       ((loc, u| t_bin IMP P Q |)\n           :: (a, d| P |) :: (loc, u| Q |) :: (a, d| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n       +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((loc, u| t_bin IMP P Q |)\n           :: (a, d| P |) :: (loc, u| Q |) :: (loc, u| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor [u| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             apply contractionN in H6;solveSignature1...\n             apply H in H6...\n             \n             apply FocusingQuest in H6...\n             \n             assert(Hyp: seqN (LJ a) x3\n       ((loc, u| t_bin IMP P Q |)\n           :: (a, d| P |) :: (loc, u| Q |) :: (loc, u| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n Qed.            \n\nTheorem InvIMPL:  forall n a P Q B M, \n   IsPositiveAtomFormulaL M ->\n   IsPositiveAtomFormulaL (second B) ->\n   mt a = true ->\n   m4 a = true ->\n    seqN (LJ a) n ((a,d| t_bin IMP P Q|) :: (a,d| Q| )::B) M (UP []) -> seq (LJ a) ( (a,d| Q| ):: B) M (UP []).\n      Proof with sauto;OLSolve.\n      induction n using strongind;intros *;\n      intros isFM isFB Hta H4a HF.\n      inversion HF...\n      inversion HF...\n      apply RemoveNotPos1 in H2...\n       intro Hc. inversion Hc;inversion H1...\n       inversion H4...\n       contradict H3.\n       constructor.\n       inversion H0...\n       contradict H3.\n       constructor.\n       \n       apply InUNotPos in H6...\n       rewrite allU in H1...\n       2:{ solveSignature1. }\n       inversion H1...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor [u| t_cons TT | ] x0.\n             simpl... \n             simpl in H9.\n             checkPermutationCases H9.\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor [d| t_cons FF | ] x0.\n             simpl... \n             checkPermutationCases H9.\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole AND_BODY Right F0 G).\n              LLTensor [u| t_bin AND F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.\n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole AND_BODY Right F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2: LLTensor [d| t_bin AND F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2: LLTensor [u| t_bin OR F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole OR_BODY Left F0 G).\n              LLTensor [d| t_bin OR F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.\n             \n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole OR_BODY Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            { apply FocusingBangPar in H7...\n               checkPermutationCases H5.\n               checkPermutationCases H5.\n               rewrite H5 in H4.\n               LLrew1 H4 H13.\n               apply H in H13...\n            TFocus (BinBipole (IMP_BODY a) Right F0 G).\n            LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n            simpl... createWorld; solveSignature1.\n             rewrite <- H5 in H4.\n             apply GenK4RelUT' with (C4:= x) \n                        (CK:=[])\n                        (CN:=x3);solveSignature1...\n             \n             rewrite H4 in H9. solveSE.\n             rewrite H4 in H10. solveSE.\n             rewrite H4 in H11. solveLT.\n             rewrite <- H7...\n             rewrite H5...\n             rewrite <- H5 in H13. \n             simpl...\n             symmetry in H7.\n             srewrite H7 in isFB.\n             rewrite map_app in isFB. OLSolve. \n             \n             assert(Hyp : seqN (LJ a) x1\n        ((a, d| t_bin IMP P Q |) :: (a, d| Q |) :: x)\n        [u| G |; d| F0 |] (UP [])).\n        eapply weakeningN with (F:=(a, d| Q |)) in H13;solveSignature1.\n           \n            LLExact H13. rewrite H4...\n            apply H in Hyp...\n            TFocus (BinBipole (IMP_BODY a) Right F0 G).\n            LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n            simpl... createWorld; solveSignature1.\n             apply GenK4RelUT' with (C4:= (a, d| Q |) :: x) \n                        (CK:=[])\n                        (CN:=x0);solveSignature1...\n                        \n             rewrite H4 in H9.\n             apply Forall_cons...\n             inversion H9... \n             \n             rewrite H4 in H10.\n             apply Forall_cons...\n             inversion H10... \n             \n             rewrite H4 in H11.\n             apply Forall_cons...\n             reflexivity.\n             inversion H11... \n             rewrite <- H7...\n             simpl...\n             symmetry in H7.\n             srewrite H7 in isFB.\n             rewrite map_app in isFB. OLSolve. \n             checkPermutationCases H5.\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x2) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n               rewrite <- H7...         \n               rewrite H5...\n              apply seqNtoSeq in H13.           \n               simpl...\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x2) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n               rewrite <- H7...         \n               rewrite H5...\n              apply seqNtoSeq in H13.           \n               simpl... }\n             \n             simpl in H9.\n             checkPermutationCases H9.\n             apply FocusingBangPar in H7...\n             checkPermutationCases H9.\n            checkPermutationCases H9.\n               rewrite H9 in H7.\n               LLrew1 H7 H15.\n               apply H in H15...\n            TFocus (BinBipole (IMP_BODY a) Right F0 G).\n            LLTensor. \n            simpl... init2 x0 x2.\n            simpl... createWorld; solveSignature1.\n             rewrite <- H9 in H7.\n             apply GenK4RelUT' with (C4:= x) \n                        (CK:=[])\n                        (CN:=x5);solveSignature1...\n             \n             rewrite H7 in H11. solveSE.\n             rewrite H7 in H12. solveSE.\n             rewrite H7 in H13. solveLT.\n             rewrite <- H10...\n             rewrite H9...\n             rewrite <- H9 in H15. \n             simpl...\n             symmetry in H10.\n             srewrite H10 in isFB.\n             rewrite map_app in isFB. OLSolve. \n             \n             assert(Hyp : seqN (LJ a) x3\n        ((a, d| t_bin IMP P Q |) :: (a, d| Q |) :: x)\n        [u| G |; d| F0 |] (UP [])).\n        eapply weakeningN with (F:=(a, d| Q |)) in H15;solveSignature1.\n           \n            LLExact H15. rewrite H7...\n            apply H in Hyp...\n            TFocus (BinBipole (IMP_BODY a) Right F0 G).\n            LLTensor.\n            simpl... init2 x0 x2.\n            simpl... createWorld; solveSignature1.\n             apply GenK4RelUT' with (C4:= (a, d| Q |) :: x) \n                        (CK:=[])\n                        (CN:=x6);solveSignature1...\n                        \n             rewrite H7 in H11.\n             apply Forall_cons...\n             inversion H11... \n             \n             rewrite H7 in H12.\n             apply Forall_cons...\n             inversion H12... \n             \n             rewrite H7 in H13.\n             apply Forall_cons...\n             reflexivity.\n             inversion H13... \n             rewrite <- H10...\n             simpl...\n             symmetry in H10.\n             srewrite H10 in isFB.\n             rewrite map_app in isFB. OLSolve. \n             checkPermutationCases H9.\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor. \n               simpl... init2 x0 x2.\n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x4) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n               rewrite <- H10...         \n               rewrite H9...\n              apply seqNtoSeq in H15.           \n               simpl...\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor.\n               simpl... init2 x0 x2.\n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x4) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n               rewrite <- H10...         \n               rewrite H9...\n              apply seqNtoSeq in H15.           \n               simpl...\n            - apply BipoleReasoning in H3...\n             apply FocusingTensor in H7...\n             apply H in H6, H10...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor [d| t_bin IMP F0 G| ] x0.\n             simpl...\n             LLTensor x2 x3.\n             1-2: rewrite H7 in H8.\n             1-2: rewrite H8 in isFM.\n             1-2: inversion isFM...\n             \n             checkPermutationCases H9.\n            \n             { \n             clear H8.\n             apply FocusingTensor in H7...\n             apply H in H7, H10...\n             rewrite H8.\n             assert(isFx2:  IsPositiveAtomFormulaL x2).\n             OLSolve.\n             specialize (posDestruct' isFx2) as HC...\n             refine (LinearToClassic2 _ _ _ (LJHasPos a)  (LJHasNeg a) _ H3 _ )... \n             apply weakeningGen...\n     apply weakeningGen...\n            apply AbsorptionC'...\n            solveSignature1.\n             }\n             apply FocusingTensor in H7...\n             apply H in H9, H12...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             LLTensor x4 x5.\n       + apply FocusingInitRuleU in H3... \n           - TFocus (RINIT OO).\n              LLTensor [u| OO |] [d| OO |].\n          - checkPermutationCases H6.\n             TFocus (BinBipole (IMP_BODY a) Right P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor [u| t_bin IMP P Q |] (@nil oo).\n             simpl... createWorld;solveSignature1.\n             copyK4 a (d|Q |) B.\n             reflexivity.\n             finishExp.  rewrite plustpropT...\n             LLPar. do 2 LLStore.\n             TFocus (POS P a).\n             apply ooth_posC... inversion H3.\n             LLTensor [d| P |] [u| Q |].\n             simpl... solveLL. \n             apply weakening;solveSignature1...\n             TFocus (RINIT Q).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor [ u| Q |]  (@nil oo) .\n             solveLL.\n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor [ u| OO |]  (@nil oo)  .\n             solveLL.\n             TFocus (RINIT OO).\n             LLTensor [u| OO |]  (@nil oo)  .\n             apply weakening;solveSignature1.\n             solveLL.\n               \n           - checkPermutationCases H6.\n              checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor  (@nil oo)  [d| OO |] .\n             apply weakening;solveSignature1.\n             LLrew2 H6. \n             init2 x x2.\n           - checkPermutationCases H6.\n             checkPermutationCases H4.\n             checkPermutationCases H6.\n             \n             TFocus (BinBipole (IMP_BODY a) Right P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor.\n             apply weakening;solveSignature1.\n              LLrew2 H6. \n             init2 x0 x.\n             simpl...\n             createWorld;solveSignature1.\n             copyK4 a (d|Q |) B.\n             reflexivity.\n             finishExp.  rewrite plustpropT...\n              LLPar. do 2 LLStore.\n              TFocus (POS P a).\n             apply ooth_posC... inversion H3.\n             LLTensor [d| P |] [u| Q |].\n             simpl... solveLL. \n             apply weakening;solveSignature1...\n             TFocus (RINIT Q).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor [ u| Q |]  (@nil oo) .\n             solveLL.\n             checkPermutationCases H6.\n               checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor. \n             apply weakening;solveSignature1.\n             solveLL.\n             solveLL.\n             apply weakening;solveSignature1.\n             TFocus (RINIT OO).\n             LLTensor. \n             solveLL. solveLL.\n           +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((a, d| t_bin IMP P Q |)\n           :: (a, d| Q |) :: (a, d| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor [d| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             \n             eapply contractionN in H6...\n             apply H in H6...\n             solveSignature1.\n                 apply FocusingQuest in H6...\n         \n             \n             assert(Hyp: seqN (LJ a) x3\n       ((a, d| t_bin IMP P Q |)\n           :: (a, d| Q |) ::  (a, d| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n       +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((a, d| t_bin IMP P Q |)\n           :: (a, d| Q |) ::  (loc, u| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor [u| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             \n             assert(Hyp: seqN (LJ a) x3\n       ((a, d| t_bin IMP P Q |)\n           :: (a, d| Q |) ::  (loc, u| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n Qed.\n \n Theorem InvANDL:  forall n a P Q B M, \n   IsPositiveAtomFormulaL M ->\n   IsPositiveAtomFormulaL (second B) ->\n   mt a = true ->\n   m4 a = true ->\n    seqN (LJ a) n ((a,d| t_bin AND P Q|) :: (a,d| P| )::(a,d| Q|) :: B) M (UP []) -> seq (LJ a) ((a,d| P| )::(a,d| Q|) :: B) M (UP []).\n    Proof with sauto;OLSolve.\n      induction n using strongind;intros *;\n      intros isFM isFB Hta H4a HF.\n      inversion HF...\n      inversion HF...\n      apply RemoveNotPos1 in H2...\n       intro Hc. inversion Hc;inversion H1...\n       inversion H4...\n       contradict H3.\n       constructor.\n       inversion H0...\n       contradict H3.\n       constructor.\n       inversion H6...\n       contradict H3.\n       constructor.\n       apply InUNotPos in H7...\n       rewrite allU in H1...\n       2:{ solveSignature1. }\n       inversion H1...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor [u| t_cons TT | ] x0.\n             simpl... \n             simpl in H9.\n             checkPermutationCases H9.\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor [d| t_cons FF | ] x0.\n             simpl... \n             checkPermutationCases H9.\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole AND_BODY Right F0 G).\n              LLTensor [u| t_bin AND F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.  \n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole AND_BODY Right F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2: LLTensor [d| t_bin AND F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H7...\n            apply AbsorptionC'...\n            solveSignature1.\n            LLSwap.\n            apply AbsorptionC'...\n            solveSignature1.\n            LLSwap;auto.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2: LLTensor [u| t_bin OR F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole OR_BODY Left F0 G).\n              LLTensor [d| t_bin OR F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.  \n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole OR_BODY Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            { apply FocusingBangPar in H7...\n               checkPermutationCases H5.\n               2:{ \n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x2) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n              apply seqNtoSeq in H13.           \n              simpl... }\n             \n             checkPermutationCases H5.\n             checkPermutationCases H7.\n             rewrite H7 in H5.\n             rewrite H5 in H4.\n             LLrew1 H4 H13.\n             apply H in H13...\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n             LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n             simpl... createWorld; solveSignature1.\n             apply GenK4RelUT' with (C4:= (a, d| P |) :: (a, d| Q |) ::x4) \n                        (CK:=[])\n                        (CN:=x3);solveSignature1...\n             \n             rewrite H4 in H9. solveSE. \n             rewrite H4 in H10. solveSE.\n             rewrite H4 in H11. solveLT. \n             rewrite <- H8...\n             \n             2:{\n             symmetry in H8.\n             srewrite H8 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...\n             \n             rewrite H5 in H4.\n             LLrew1 H4 H13.\n             \n             assert(Hyp : seqN (LJ a) x1\n        ((a, d| t_bin AND P Q |) :: (a, d| P |) ::  (a, d| Q |) :: x0)\n        [u| G |; d| F0 |] (UP [])).\n        eapply weakeningN with (F:=(a, d| Q |)) in H13;solveSignature1.\n           \n            LLExact H13.\n            apply H in Hyp...\n            TFocus (BinBipole (IMP_BODY a) Right F0 G).\n            LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n            simpl... createWorld; solveSignature1.\n             apply GenK4RelUT' with (C4:= (a, d| P |) :: (a, d| Q |) ::x0) \n                        (CK:=[])\n                        (CN:=x4);solveSignature1...\n                        \n             rewrite H4 in H9.\n             apply Forall_cons...\n             apply Forall_cons... \n             inversion H9... \n             inversion H15... \n             \n             rewrite H4 in H10.\n             apply Forall_cons...\n             apply Forall_cons... \n             inversion H10... \n             inversion H15... \n             \n             rewrite H4 in H11.\n             apply Forall_cons...\n             reflexivity.\n             apply Forall_cons...\n             reflexivity. \n             inversion H11... \n             inversion H15...\n              \n             rewrite <- H8...\n             \n             2:{\n             symmetry in H8.\n             srewrite H8 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...\n             \n             checkPermutationCases H7.\n             \n             rewrite H7 in H4.\n             LLrew1 H4 H13.\n             assert(Hyp : seqN (LJ a) x1\n        ((a, d| t_bin AND P Q |) :: (a, d| P |) ::  (a, d| Q |) :: x4)\n        [u| G |; d| F0 |] (UP [])).\n            apply weakeningN with (F:=  (a, d| P |)) in H13;solveSignature1...\n             LLExact H13.\n             apply H in Hyp...\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n             LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n             simpl... createWorld; solveSignature1.\n             apply GenK4RelUT' with (C4:= (a, d| P |) :: (a, d| Q |) ::x4) \n                        (CK:=[])\n                        (CN:=x0);solveSignature1...\n             \n             rewrite H4 in H9.\n             apply Forall_cons...\n             apply Forall_cons... \n             inversion H9... \n             inversion H15... \n             \n             rewrite H4 in H10.\n             apply Forall_cons...\n             apply Forall_cons... \n             inversion H10... \n             inversion H15... \n             \n             rewrite H4 in H11.\n             apply Forall_cons...\n             reflexivity.\n             apply Forall_cons...\n             reflexivity. \n             inversion H11... \n             inversion H15...\n              \n             rewrite <- H8...\n             \n             2:{\n             symmetry in H8.\n             srewrite H8 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...\n             \n             LLrew1 H4 H13.\n             assert(Hyp : seqN (LJ a) x1\n        ((a, d| t_bin AND P Q |) :: (a, d| P |) ::  (a, d| Q |) :: x)\n        [u| G |; d| F0 |] (UP [])).\n             apply weakeningN with (F:=(a, d| Q |)) in H13;solveSignature1.\n        apply weakeningN with (F:=(a, d| P |)) in H13;solveSignature1.\n        LLExact H13.\n        apply H in Hyp...\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n             LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n             simpl... createWorld; solveSignature1.\n             apply GenK4RelUT' with (C4:= (a, d| P |) :: (a, d| Q |) ::x) \n                        (CK:=[])\n                        (CN:=x4);solveSignature1...\n                        \n             rewrite H4 in H9.\n             apply Forall_cons...\n             apply Forall_cons... \n             inversion H9... \n             \n             rewrite H4 in H10.\n             apply Forall_cons...\n             apply Forall_cons... \n             inversion H10... \n             \n             rewrite H4 in H11.\n             apply Forall_cons...\n             reflexivity.\n             apply Forall_cons...\n             reflexivity. \n             inversion H11... \n              \n             rewrite <- H8...\n             \n             2:{\n             symmetry in H8.\n             srewrite H8 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl... }\n            { checkPermutationCases H9.\n               checkPermutationCases H4.\n               checkPermutationCases H9.\n            \n               apply FocusingBangPar in H7...\n              checkPermutationCases H11.\n               \n            \n               2:{ \n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor.\n               apply weakening;solveSignature1.\n               apply weakening;solveSignature1.\n               LLrew2 H10.\n               init2 x0 x4. \n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x6) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n              apply seqNtoSeq in H17.           \n              simpl... }\n             \n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor.\n               apply weakening;solveSignature1.\n               apply weakening;solveSignature1.\n               LLrew2 H10.\n               init2 x0 x4. \n               simpl... createWorld;solveSignature1.\n               \n             checkPermutationCases H11.\n             checkPermutationCases H12.\n             rewrite H12 in H11.\n             rewrite H11 in H7.\n             LLrew1 H7 H17.\n             apply H in H17...\n             apply GenK4RelUT' with (C4:= (a, d| P |) :: (a, d| Q |) ::x9) \n                        (CK:=[])\n                        (CN:=x7);solveSignature1...\n             \n             rewrite H7 in H13. solveSE. \n             rewrite H7 in H14. solveSE.\n             rewrite H7 in H15. solveLT. \n             rewrite <- H16...\n             \n             2:{\n             symmetry in H16.\n             srewrite H16 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...\n             \n             rewrite H11 in H7.\n             LLrew1 H7 H17.\n             \n             assert(Hyp : seqN (LJ a) x5\n        ((a, d| t_bin AND P Q |) :: (a, d| P |) ::  (a, d| Q |) :: x8)\n        [u| G |; d| F0 |] (UP [])).\n        eapply weakeningN with (F:=(a, d| Q |)) in H17;solveSignature1.\n           \n            LLExact H17.\n            apply H in Hyp...\n             apply GenK4RelUT' with (C4:= (a, d| P |) :: (a, d| Q |) ::x8) \n                        (CK:=[])\n                        (CN:=x9);solveSignature1...\n             \n             rewrite H7 in H13.\n             apply Forall_cons...\n             apply Forall_cons... \n             inversion H13... \n             inversion H20... \n             \n             rewrite H7 in H14.\n             apply Forall_cons...\n             apply Forall_cons... \n             inversion H14... \n             inversion H20... \n             \n             rewrite H7 in H15.\n             apply Forall_cons...\n             reflexivity.\n             apply Forall_cons...\n             reflexivity. \n             inversion H15... \n             inversion H20...\n              \n             rewrite <- H16...\n             \n             2:{\n             symmetry in H16.\n             srewrite H16 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...\n             \n             checkPermutationCases H12.\n             rewrite H12 in H7.\n             LLrew1 H7 H17.\n             \n             assert(Hyp : seqN (LJ a) x5\n        ((a, d| t_bin AND P Q |) :: (a, d| P |) ::  (a, d| Q |) :: x9)\n        [u| G |; d| F0 |] (UP [])).\n        eapply weakeningN with (F:=(a, d| P |)) in H17;solveSignature1.\n           \n            LLExact H17.\n            apply H in Hyp...\n             apply GenK4RelUT' with (C4:= (a, d| P |) :: (a, d| Q |) ::x9) \n                        (CK:=[])\n                        (CN:=x8);solveSignature1...\n             \n             rewrite H7 in H13.\n             apply Forall_cons...\n             apply Forall_cons... \n             inversion H13... \n             inversion H20... \n             \n             rewrite H7 in H14.\n             apply Forall_cons...\n             apply Forall_cons... \n             inversion H14... \n             inversion H20... \n             \n             rewrite H7 in H15.\n             apply Forall_cons...\n             reflexivity.\n             apply Forall_cons...\n             reflexivity. \n             inversion H15... \n             inversion H20...\n              \n             rewrite <- H16...\n             \n             2:{\n             symmetry in H16.\n             srewrite H16 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...\n             \n         \n             LLrew1 H7 H17.\n             assert(Hyp : seqN (LJ a) x5\n        ((a, d| t_bin AND P Q |) :: (a, d| P |) ::  (a, d| Q |) :: x)\n        [u| G |; d| F0 |] (UP [])).\n             apply weakeningN with (F:=(a, d| Q |)) in H17;solveSignature1.\n        apply weakeningN with (F:=(a, d| P |)) in H17;solveSignature1.\n        LLExact H17.\n        apply H in Hyp...\n        apply GenK4RelUT' with (C4:= (a, d| P |) :: (a, d| Q |) ::x) \n                        (CK:=[])\n                        (CN:=x9);solveSignature1...\n             rewrite H7 in H13.\n             apply Forall_cons...\n             apply Forall_cons... \n             inversion H13... \n             \n             rewrite H7 in H14.\n             apply Forall_cons...\n             apply Forall_cons... \n             inversion H14... \n             \n             rewrite H7 in H15.\n             apply Forall_cons...\n             reflexivity.\n             apply Forall_cons...\n             reflexivity. \n             inversion H15... \n              \n             rewrite <- H16...\n             \n             2:{\n             symmetry in H16.\n             srewrite H16 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl... }\n           - apply BipoleReasoning in H3...\n             apply FocusingTensor in H7...\n             apply H in H6, H10...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor [d| t_bin IMP F0 G| ] x0.\n             simpl...\n             LLTensor x2 x3.\n             1-2: rewrite H7 in H8.\n             1-2: rewrite H8 in isFM.\n             1-2: inversion isFM...\n             \n             checkPermutationCases H9.\n             apply FocusingTensor in H7...\n             apply H in H9, H12...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             LLTensor x4 x5.\n       + apply FocusingInitRuleU in H3... \n           - TFocus (RINIT OO).\n              LLTensor [u| OO |] [d| OO |].\n           - checkPermutationCases H6.\n             TFocus (BinBipole AND_BODY Right P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor [u| t_bin AND P Q |] (@nil oo).\n             simpl... LLRelease. LLWith;LLStore.\n             TFocus (RINIT P).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor [ u| P |] (@nil oo).\n             solveLL.\n             TFocus (RINIT Q).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor [ u| Q |] (@nil oo).\n             apply weakening;solveSignature1.\n             solveLL.\n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor [ u| OO |] (@nil oo).\n             solveLL.\n             checkPermutationCases H6.\n             TFocus (RINIT OO).\n             LLTensor [ u| OO |] (@nil oo).\n             apply weakening;solveSignature1.\n             solveLL.\n             TFocus (RINIT OO).\n             LLTensor [ u| OO |] (@nil oo).\n             apply weakening;solveSignature1.\n              apply weakening;solveSignature1.\n             solveLL.\n           - checkPermutationCases H6.\n             checkPermutationCases H4.\n             checkPermutationCases H6.\n             TFocus (RINIT OO).\n             LLTensor (@nil oo) [ d| OO |] .\n             apply weakening;solveSignature1.\n              apply weakening;solveSignature1.\n             solveLL.\n           - checkPermutationCases H6.\n             checkPermutationCases H6.\n             checkPermutationCases H9.\n             checkPermutationCases H4.\n             TFocus (BinBipole AND_BODY Right P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor.\n             apply weakening;solveSignature1.\n             apply weakening;solveSignature1.\n              LLrew2 H10. \n             init2 x0 x5.\n             simpl... LLRelease. LLWith;LLStore.\n             TFocus (RINIT P).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor [ u| P |] (@nil oo).\n             solveLL.\n             TFocus (RINIT Q).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor [ u| Q |] (@nil oo).\n             apply weakening;solveSignature1.\n             solveLL.\n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor.\n             apply weakening;solveSignature1.\n             apply weakening;solveSignature1.\n              LLrew2 H10. \n             init2 x0 x5.\n             \n             solveLL.\n             checkPermutationCases H12.\n             TFocus (RINIT OO).\n             LLTensor.\n             apply weakening;solveSignature1.\n             apply weakening;solveSignature1.\n              LLrew2 H10. \n             init2 x0 x5.\n             apply weakening;solveSignature1.\n             solveLL.\n             TFocus (RINIT OO).\n             LLTensor. \n             apply weakening;solveSignature1.\n             apply weakening;solveSignature1.\n              LLrew2 H10. \n              init2 x0 x5.\n             apply weakening;solveSignature1.\n             apply weakening;solveSignature1.\n              LLrew2 H13. \n             init2 x x8.\n       +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((a, d| t_bin AND P Q |)\n           :: (a, d| P |) :: (a, d| Q |) :: (a, d| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor [d| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             \n             eapply contractionN in H6...\n             apply H in H6...\n             solveSignature1.\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x3\n       ((a, d| t_bin AND P Q |)\n           :: (a, d| P |) :: (a, d| Q |) :: (a, d| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n       +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((a, d| t_bin AND P Q |)\n           :: (a, d| P |) :: (a, d| Q |) :: (loc, u| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor [u| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             checkPermutationCases H4.\n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             \n             assert(Hyp: seqN (LJ a) x5\n       ((a, d| t_bin AND P Q |)\n           :: (a, d| P |) :: (a, d| Q |) :: (loc, u| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H10.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor (@nil oo) M . \n             apply weakening;solveSignature1...\n              apply weakening;solveSignature1...\n             LLrew2 H9. \n             init2 x0 x4.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n Qed.            \n\n Theorem InvORR:  forall n a P Q B M, \n   IsPositiveAtomFormulaL M ->\n   IsPositiveAtomFormulaL (second B) ->\n    seqN (LJ a) n ((loc,u| t_bin OR P Q|) :: (loc,u| P| )::(loc,u| Q|) :: B) M (UP []) -> seq (LJ a) ((loc,u| P| )::(loc,u| Q|) :: B) M (UP []).\n    Proof with sauto;OLSolve.\n      induction n using strongind;intros *;\n      intros isFM isFB HF.\n      inversion HF...\n      inversion HF...\n      apply RemoveNotPos1 in H2...\n       intro Hc. inversion Hc;inversion H1...\n       inversion H4...\n       contradict H3.\n       constructor.\n       inversion H0...\n       contradict H3.\n       constructor.\n       inversion H6...\n       contradict H3.\n       constructor.\n       apply InUNotPos in H7...\n       rewrite allU in H1...\n       2:{ solveSignature1. }\n       inversion H1...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor [u| t_cons TT | ] x0.\n             simpl... \n             simpl in H9.\n             checkPermutationCases H9.\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor [d| t_cons FF | ] x0.\n             simpl... \n             checkPermutationCases H9.\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole AND_BODY Right F0 G).\n              LLTensor [u| t_bin AND F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.  \n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole AND_BODY Right F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2: LLTensor [d| t_bin AND F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2: LLTensor [u| t_bin OR F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H7...\n            apply AbsorptionC'...\n            solveSignature1.\n            LLSwap.\n            apply AbsorptionC'...\n            solveSignature1.\n            LLSwap;auto.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole OR_BODY Left F0 G).\n              LLTensor [d| t_bin OR F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.  \n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole OR_BODY Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            { apply FocusingBangPar in H9...\n               checkPermutationCases H8.\n               rewrite H7 in H11.\n               inversion H11...\n               solveSignature1.\n               \n               checkPermutationCases H8.\n               rewrite H8 in H11.\n               inversion H11...\n               solveSignature1.\n               \n               checkPermutationCases H9.\n               rewrite H9 in H11.\n               inversion H11...\n               solveSignature1.\n               \n               apply weakening;solveSignature1.\n               apply weakening;solveSignature1.\n               \n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x2) \n                        (CK:=[])\n                        (CN:=x4);solveSignature1...\n              apply seqNtoSeq in H15.           \n              simpl... }\n             \n              apply FocusingBangPar in H9...\n               checkPermutationCases H9.\n               rewrite H7 in H12.\n               inversion H12...\n               solveSignature1.\n              checkPermutationCases H9.\n               rewrite H9 in H12.\n               inversion H12...\n               solveSignature1.\n              checkPermutationCases H10.\n               rewrite H10 in H12.\n               inversion H12...\n               solveSignature1.\n              \n               checkPermutationCases H11.\n               \n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor. \n               LLrew2 H11. \n                init2 x0 x7.\n               apply weakening;solveSignature1.\n               apply weakening;solveSignature1.\n             \n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x3) \n                        (CK:=[])\n                        (CN:=x6);solveSignature1...\n              apply seqNtoSeq in H16.           \n              simpl...\n           - apply BipoleReasoning in H3...\n             apply FocusingTensor in H7...\n             apply H in H6, H10...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor [d| t_bin IMP F0 G| ] x0.\n             simpl...\n             LLTensor x2 x3.\n             1-2: rewrite H7 in H8.\n             1-2: rewrite H8 in isFM.\n             1-2: inversion isFM...\n             \n             checkPermutationCases H9.\n             apply FocusingTensor in H7...\n             apply H in H9, H12...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             LLTensor x4 x5.\n       + apply FocusingInitRuleU in H3... \n           - TFocus (RINIT OO).\n              LLTensor [u| OO |] [d| OO |].\n           - checkPermutationCases H6.\n              checkPermutationCases H4.\n              checkPermutationCases H6.\n             TFocus (RINIT OO).\n             LLTensor [ u| OO |] (@nil oo).\n             apply weakening;solveSignature1.\n             apply weakening;solveSignature1. \n             LLrew2 H8. \n             init2 x x3.\n           - checkPermutationCases H6.\n             TFocus (BinBipole OR_BODY Left P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor [d| t_bin OR P Q |] (@nil oo).\n             simpl... LLRelease. LLWith;LLStore.\n             TFocus (RINIT P).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor  (@nil oo) [ d| P |].\n             solveLL.\n             TFocus (RINIT Q).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor  (@nil oo) [ d| Q |].\n             apply weakening;solveSignature1.\n             solveLL.\n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor ( @nil oo)[ d| OO |] .\n             solveLL.\n             checkPermutationCases H6.\n             TFocus (RINIT OO).\n             LLTensor (@nil oo) [ d| OO |] .\n             apply weakening;solveSignature1.\n             solveLL.\n             TFocus (RINIT OO).\n             LLTensor (@nil oo) [d| OO |] .\n             apply weakening;solveSignature1.\n              apply weakening;solveSignature1.\n             solveLL.\n           - checkPermutationCases H6.\n             checkPermutationCases H4.\n             checkPermutationCases H4.\n             checkPermutationCases H8.\n             \n             TFocus (BinBipole OR_BODY Left P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor.\n             apply weakening;solveSignature1.\n             apply weakening;solveSignature1.\n              LLrew2 H10. \n             init2 x x4.\n             simpl... LLRelease. LLWith;LLStore.\n             TFocus (RINIT P).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor (@nil oo) [ d| P |] .\n             solveLL.\n             TFocus (RINIT Q).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor (@nil oo) [ d| Q |].\n             apply weakening;solveSignature1.\n             solveLL.\n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor.\n              LLrew2 H6. \n             init2 x0 x3.\n              LLrew2 H4. \n             init2 x x4.\n           +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((loc, u| t_bin OR P Q |)\n           :: (loc, u| P |) :: (loc, u| Q |) :: (a, d| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor [d| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             \n             \n             assert(Hyp: seqN (LJ a) x3\n       ((loc, u| t_bin OR P Q |)\n           :: (loc, u| P |) :: (loc, u| Q |) :: (a, d| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n       +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((loc, u| t_bin OR P Q |)\n           :: (loc, u| P |) :: (loc, u| Q |) :: (loc, u| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor [u| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             eapply contractionN in H6...\n             apply H in H6...\n             solveSignature1.\n             \n             apply FocusingQuest in H6...\n             \n             assert(Hyp: seqN (LJ a) x3\n       ((loc, u| t_bin OR P Q |)\n           :: (loc, u| P |) :: (loc, u| Q |) :: (loc, u| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n Qed.  \n\n Theorem InvORL1:  forall n a P Q B M, \n   IsPositiveAtomFormulaL M ->\n   IsPositiveAtomFormulaL (second B) ->\n   mt a = true ->\n   m4 a =  true ->\n    seqN (LJ a) n ((a,d| t_bin OR P Q|) :: (a,d| P| )::B) M (UP []) -> seq (LJ a) ((a,d| P| )::B) M (UP []).\n    Proof with sauto;OLSolve.\n      induction n using strongind;intros *;\n      intros isFM isFB Hta H4a HF.\n      inversion HF...\n      inversion HF...\n      apply RemoveNotPos1 in H2...\n       intro Hc. inversion Hc;inversion H1...\n       inversion H4...\n       contradict H3.\n       constructor.\n       inversion H0...\n       contradict H3.\n       constructor.\n       apply InUNotPos in H6...\n       rewrite allU in H1...\n       2:{ solveSignature1. }\n       inversion H1...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor [u| t_cons TT | ] x0.\n             simpl... \n             simpl in H9.\n             checkPermutationCases H9.\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor [d| t_cons FF | ] x0.\n             simpl... \n             checkPermutationCases H9.\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole AND_BODY Right F0 G).\n              LLTensor [u| t_bin AND F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.\n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole AND_BODY Right F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2: LLTensor [d| t_bin AND F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2: LLTensor [u| t_bin OR F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole OR_BODY Left F0 G).\n              LLTensor [d| t_bin OR F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.\n              {\n             apply FocusingWith in H7...\n             apply H in H9, H10...\n            apply AbsorptionC'...\n            solveSignature1. }\n             \n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole OR_BODY Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            { apply FocusingBangPar in H7...\n               checkPermutationCases H5.\n               2:{ \n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x2) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n              apply seqNtoSeq in H13.           \n              simpl... }\n             \n             checkPermutationCases H5.\n             rewrite H5 in H4.\n             LLrew1 H4 H13.\n             apply H in H13...\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n             LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n             simpl... createWorld; solveSignature1.\n             apply GenK4RelUT' with (C4:= (a, d| P |) ::x0) \n                        (CK:=[])\n                        (CN:=x3);solveSignature1...\n             \n             rewrite H4 in H9. solveSE. \n             rewrite H4 in H10. solveSE.\n             rewrite H4 in H11. solveLT. \n             rewrite <- H7...\n             \n             2:{\n             symmetry in H7.\n             srewrite H7 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...\n             \n             LLrew1 H4 H13.\n             \n             assert(Hyp : seqN (LJ a) x1\n        ((a, d| t_bin OR P Q |) :: (a, d| P |) :: x)\n        [u| G |; d| F0 |] (UP [])).\n        eapply weakeningN with (F:=(a, d| P |)) in H13;solveSignature1.\n           \n            LLExact H13.\n            apply H in Hyp...\n            TFocus (BinBipole (IMP_BODY a) Right F0 G).\n            LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n            simpl... createWorld; solveSignature1.\n             apply GenK4RelUT' with (C4:= (a, d| P |) :: x) \n                        (CK:=[])\n                        (CN:=x0);solveSignature1...\n                        \n             rewrite H4 in H9.\n             apply Forall_cons...\n             inversion H9... \n             \n             rewrite H4 in H10.\n             apply Forall_cons...\n             inversion H10... \n             \n             rewrite H4 in H11.\n             apply Forall_cons...\n             reflexivity.\n             inversion H11... \n              \n             rewrite <- H7...\n             \n             2:{\n             symmetry in H7.\n             srewrite H7 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...  }\n             \n             checkPermutationCases H9.\n             apply FocusingBangPar in H7...\n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor.\n               LLrew2 H4.\n               init2 x0 x2. \n               simpl... createWorld;solveSignature1.\n               \n             checkPermutationCases H9.\n             checkPermutationCases H9.\n             rewrite H9 in H7.\n             LLrew1 H7 H15.\n             apply H in H15...\n             apply GenK4RelUT' with (C4:= (a, d| P |)::x6) \n                        (CK:=[])\n                        (CN:=x5);solveSignature1...\n             \n             rewrite H7 in H11. solveSE. \n             rewrite H7 in H12. solveSE.\n             rewrite H7 in H13. solveLT. \n             rewrite <- H10...\n             \n             2:{\n             symmetry in H10.\n             srewrite H10 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...\n             \n             LLrew1 H7 H15.\n             \n             assert(Hyp : seqN (LJ a) x3\n        ((a, d| t_bin OR P Q |) :: (a, d| P |) ::  x)\n        [u| G |; d| F0 |] (UP [])).\n        eapply weakeningN with (F:=(a, d| P |)) in H15;solveSignature1.\n           \n            LLExact H15.\n            apply H in Hyp...\n             apply GenK4RelUT' with (C4:= (a, d| P |) ::x) \n                        (CK:=[])\n                        (CN:=x6);solveSignature1...\n             \n             rewrite H7 in H11.\n             apply Forall_cons...\n             inversion H11... \n             \n             rewrite H7 in H12.\n             apply Forall_cons...\n             inversion H12... \n             \n             rewrite H7 in H13.\n             apply Forall_cons...\n             reflexivity.\n             inversion H13... \n              \n             rewrite <- H10...\n             \n             2:{\n             symmetry in H10.\n             srewrite H10 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...\n             \n             checkPermutationCases H9.\n             LLrew1 H9 H15.\n             \n             apply GenK4RelUT' with (C4:= (a, d| P |) :: x6) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n             \n                rewrite H9 in H11. solveSE. \n             rewrite H9 in H12. solveSE.\n             rewrite H9 in H13. solveLT. \n             rewrite <- H10...\n             apply seqNtoSeq in H15.\n             simpl...\n             apply GenK4RelUT' with (C4:= x4) \n                        (CK:=[])\n                        (CN:= (a, d| P |) :: x6);solveSignature1...\n             rewrite <- H10...\n             apply seqNtoSeq in H15.\n             simpl...\n            - apply BipoleReasoning in H3...\n             apply FocusingTensor in H7...\n             apply H in H6, H10...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor [d| t_bin IMP F0 G| ] x0.\n             simpl...\n             LLTensor x2 x3.\n             1-2: rewrite H7 in H8.\n             1-2: rewrite H8 in isFM.\n             1-2: inversion isFM...\n             \n             checkPermutationCases H9.\n             apply FocusingTensor in H7...\n             apply H in H9, H12...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             LLTensor x4 x5.\n       + apply FocusingInitRuleU in H3... \n           - TFocus (RINIT OO).\n              LLTensor [u| OO |] [d| OO |].\n          - checkPermutationCases H6.\n             TFocus (BinBipole OR_BODY Right P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor [u| t_bin OR P Q |] (@nil oo).\n             simpl... LLPlusL. LLRelease. LLStore.\n             TFocus (RINIT P).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor [ u| P |]  (@nil oo) .\n             solveLL.\n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor [ u| OO |]  (@nil oo)  .\n             solveLL.\n             TFocus (RINIT OO).\n             LLTensor [u| OO |]  (@nil oo)  .\n             apply weakening;solveSignature1.\n             solveLL.\n               \n           - checkPermutationCases H6.\n              checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor  (@nil oo)  [d| OO |] .\n             apply weakening;solveSignature1.\n             LLrew2 H6. \n             init2 x x2.\n           - checkPermutationCases H6.\n             checkPermutationCases H4.\n             checkPermutationCases H6.\n             \n             TFocus (BinBipole OR_BODY Right P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor.\n             apply weakening;solveSignature1.\n              LLrew2 H6. \n             init2 x0 x.\n             simpl... LLPlusL. LLRelease. LLStore.\n             TFocus (RINIT P).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor [u| P |]  (@nil oo)  .\n             solveLL.\n             TFocus (RINIT OO).\n             LLTensor.\n              LLrew2 H6. \n             init2 x0 x3.\n              LLrew2 H4. \n             init2 x x4.\n           +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((a, d| t_bin OR P Q |)\n           :: (a, d| P |) :: (a, d| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor [d| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             \n             eapply contractionN in H6...\n             apply H in H6...\n             solveSignature1.\n                 apply FocusingQuest in H6...\n         \n             \n             assert(Hyp: seqN (LJ a) x3\n       ((a, d| t_bin OR P Q |)\n           :: (a, d| P |) ::  (a, d| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n       +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((a, d| t_bin OR P Q |)\n           :: (a, d| P |) ::  (loc, u| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor [u| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             \n             assert(Hyp: seqN (LJ a) x3\n       ((a, d| t_bin OR P Q |)\n           :: (a, d| P |) ::  (loc, u| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n Qed.\n \n Theorem InvORL2:  forall n a P Q B M, \n   IsPositiveAtomFormulaL M ->\n   IsPositiveAtomFormulaL (second B) ->\n   mt a = true ->\n   m4 a =  true ->\n    seqN (LJ a) n ((a,d| t_bin OR P Q|) :: (a,d| Q| )::B) M (UP []) -> seq (LJ a) ((a,d| Q| )::B) M (UP []).\n    Proof with sauto;OLSolve.\n      induction n using strongind;intros *;\n      intros isFM isFB Hta H4a HF.\n      inversion HF...\n      inversion HF...\n      apply RemoveNotPos1 in H2...\n       intro Hc. inversion Hc;inversion H1...\n       inversion H4...\n       contradict H3.\n       constructor.\n       inversion H0...\n       contradict H3.\n       constructor.\n       apply InUNotPos in H6...\n       rewrite allU in H1...\n       2:{ solveSignature1. }\n       inversion H1...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor [u| t_cons TT | ] x0.\n             simpl... \n             simpl in H9.\n             checkPermutationCases H9.\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor [d| t_cons FF | ] x0.\n             simpl... \n             checkPermutationCases H9.\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole AND_BODY Right F0 G).\n              LLTensor [u| t_bin AND F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.\n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole AND_BODY Right F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2: LLTensor [d| t_bin AND F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2: LLTensor [u| t_bin OR F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole OR_BODY Left F0 G).\n              LLTensor [d| t_bin OR F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.\n              {\n             apply FocusingWith in H7...\n             apply H in H9, H10...\n            apply AbsorptionC'...\n            solveSignature1. }\n             \n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole OR_BODY Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            { apply FocusingBangPar in H7...\n               checkPermutationCases H5.\n               2:{ \n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x2) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n              apply seqNtoSeq in H13.           \n              simpl... }\n             \n             checkPermutationCases H5.\n             rewrite H5 in H4.\n             LLrew1 H4 H13.\n             apply H in H13...\n             TFocus (BinBipole (IMP_BODY a) Right F0 G).\n             LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n             simpl... createWorld; solveSignature1.\n             apply GenK4RelUT' with (C4:= (a, d| Q |) ::x0) \n                        (CK:=[])\n                        (CN:=x3);solveSignature1...\n             \n             rewrite H4 in H9. solveSE. \n             rewrite H4 in H10. solveSE.\n             rewrite H4 in H11. solveLT. \n             rewrite <- H7...\n             \n             2:{\n             symmetry in H7.\n             srewrite H7 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...\n             \n             LLrew1 H4 H13.\n             \n             assert(Hyp : seqN (LJ a) x1\n        ((a, d| t_bin OR P Q |) :: (a, d| Q |) :: x)\n        [u| G |; d| F0 |] (UP [])).\n        eapply weakeningN with (F:=(a, d| Q |)) in H13;solveSignature1.\n           \n            LLExact H13.\n            apply H in Hyp...\n            TFocus (BinBipole (IMP_BODY a) Right F0 G).\n            LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n            simpl... createWorld; solveSignature1.\n             apply GenK4RelUT' with (C4:= (a, d| Q |) :: x) \n                        (CK:=[])\n                        (CN:=x0);solveSignature1...\n                        \n             rewrite H4 in H9.\n             apply Forall_cons...\n             inversion H9... \n             \n             rewrite H4 in H10.\n             apply Forall_cons...\n             inversion H10... \n             \n             rewrite H4 in H11.\n             apply Forall_cons...\n             reflexivity.\n             inversion H11... \n              \n             rewrite <- H7...\n             \n             2:{\n             symmetry in H7.\n             srewrite H7 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...  }\n             \n             checkPermutationCases H9.\n             apply FocusingBangPar in H7...\n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor.\n               LLrew2 H4.\n               init2 x0 x2. \n               simpl... createWorld;solveSignature1.\n               \n             checkPermutationCases H9.\n             checkPermutationCases H9.\n             rewrite H9 in H7.\n             LLrew1 H7 H15.\n             apply H in H15...\n             apply GenK4RelUT' with (C4:= (a, d| Q |)::x6) \n                        (CK:=[])\n                        (CN:=x5);solveSignature1...\n             \n             rewrite H7 in H11. solveSE. \n             rewrite H7 in H12. solveSE.\n             rewrite H7 in H13. solveLT. \n             rewrite <- H10...\n             \n             2:{\n             symmetry in H10.\n             srewrite H10 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...\n             \n             LLrew1 H7 H15.\n             \n             assert(Hyp : seqN (LJ a) x3\n        ((a, d| t_bin OR P Q |) :: (a, d| Q |) ::  x)\n        [u| G |; d| F0 |] (UP [])).\n        eapply weakeningN with (F:=(a, d| Q |)) in H15;solveSignature1.\n           \n            LLExact H15.\n            apply H in Hyp...\n             apply GenK4RelUT' with (C4:= (a, d| Q |) ::x) \n                        (CK:=[])\n                        (CN:=x6);solveSignature1...\n             \n             rewrite H7 in H11.\n             apply Forall_cons...\n             inversion H11... \n             \n             rewrite H7 in H12.\n             apply Forall_cons...\n             inversion H12... \n             \n             rewrite H7 in H13.\n             apply Forall_cons...\n             reflexivity.\n             inversion H13... \n              \n             rewrite <- H10...\n             \n             2:{\n             symmetry in H10.\n             srewrite H10 in isFB.\n             rewrite map_app in isFB. OLSolve. }\n             simpl...\n             \n             checkPermutationCases H9.\n             LLrew1 H9 H15.\n             \n             apply GenK4RelUT' with (C4:= (a, d| Q |) :: x6) \n                        (CK:=[])\n                        (CN:=x);solveSignature1...\n             \n                rewrite H9 in H11. solveSE. \n             rewrite H9 in H12. solveSE.\n             rewrite H9 in H13. solveLT. \n             rewrite <- H10...\n             apply seqNtoSeq in H15.\n             simpl...\n             apply GenK4RelUT' with (C4:= x4) \n                        (CK:=[])\n                        (CN:= (a, d| Q |) :: x6);solveSignature1...\n             rewrite <- H10...\n             apply seqNtoSeq in H15.\n             simpl...\n            - apply BipoleReasoning in H3...\n             apply FocusingTensor in H7...\n             apply H in H6, H10...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor [d| t_bin IMP F0 G| ] x0.\n             simpl...\n             LLTensor x2 x3.\n             1-2: rewrite H7 in H8.\n             1-2: rewrite H8 in isFM.\n             1-2: inversion isFM...\n             \n             checkPermutationCases H9.\n             apply FocusingTensor in H7...\n             apply H in H9, H12...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             LLTensor x4 x5.\n       + apply FocusingInitRuleU in H3... \n           - TFocus (RINIT OO).\n              LLTensor [u| OO |] [d| OO |].\n          - checkPermutationCases H6.\n             TFocus (BinBipole OR_BODY Right P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor [u| t_bin OR P Q |] (@nil oo).\n             simpl... LLPlusR. LLRelease. LLStore.\n             TFocus (RINIT Q).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor [ u| Q |]  (@nil oo) .\n             solveLL.\n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor [ u| OO |]  (@nil oo)  .\n             solveLL.\n             TFocus (RINIT OO).\n             LLTensor [u| OO |]  (@nil oo)  .\n             apply weakening;solveSignature1.\n             solveLL.\n               \n           - checkPermutationCases H6.\n              checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor  (@nil oo)  [d| OO |] .\n             apply weakening;solveSignature1.\n             LLrew2 H6. \n             init2 x x2.\n           - checkPermutationCases H6.\n             checkPermutationCases H4.\n             checkPermutationCases H6.\n             \n             TFocus (BinBipole OR_BODY Right P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor.\n             apply weakening;solveSignature1.\n              LLrew2 H6. \n             init2 x0 x.\n             simpl... LLPlusR. LLRelease. LLStore.\n             TFocus (RINIT Q).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor [u| Q |]  (@nil oo)  .\n             solveLL.\n             TFocus (RINIT OO).\n             LLTensor.\n              LLrew2 H6. \n             init2 x0 x3.\n              LLrew2 H4. \n             init2 x x4.\n           +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((a, d| t_bin OR P Q |)\n           :: (a, d| Q |) :: (a, d| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor [d| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             \n             eapply contractionN in H6...\n             apply H in H6...\n             solveSignature1.\n                 apply FocusingQuest in H6...\n         \n             \n             assert(Hyp: seqN (LJ a) x3\n       ((a, d| t_bin OR P Q |)\n           :: (a, d| Q |) ::  (a, d| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n       +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((a, d| t_bin OR P Q |)\n           :: (a, d| Q |) ::  (loc, u| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor [u| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             \n             assert(Hyp: seqN (LJ a) x3\n       ((a, d| t_bin OR P Q |)\n           :: (a, d| Q |) ::  (loc, u| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n Qed. \n\n Theorem InvANDR1:  forall n a P Q B M, \n   IsPositiveAtomFormulaL M ->\n   IsPositiveAtomFormulaL (second B) ->\n    seqN (LJ a) n ((loc,u| t_bin AND P Q|) :: (loc,u| P| )::B) M (UP []) -> seq (LJ a) ((loc,u| P| )::B) M (UP []).\n    Proof with sauto;OLSolve.\n      induction n using strongind;intros *;\n      intros isFM isFB HF.\n      inversion HF...\n      inversion HF...\n      apply RemoveNotPos1 in H2...\n       intro Hc. inversion Hc;inversion H1...\n       inversion H4...\n       contradict H3.\n       constructor.\n       inversion H0...\n       contradict H3.\n       constructor.\n       apply InUNotPos in H6...\n       rewrite allU in H1...\n       2:{ solveSignature1. }\n       inversion H1...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor [u| t_cons TT | ] x0.\n             simpl... \n             simpl in H9.\n             checkPermutationCases H9.\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor [d| t_cons FF | ] x0.\n             simpl... \n             checkPermutationCases H9.\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole AND_BODY Right F0 G).\n              LLTensor [u| t_bin AND F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.\n            {\n             apply FocusingWith in H7...\n             apply H in H9, H10...\n            apply AbsorptionC'...\n            solveSignature1. }\n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole AND_BODY Right F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2: LLTensor [d| t_bin AND F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2: LLTensor [u| t_bin OR F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole OR_BODY Left F0 G).\n              LLTensor [d| t_bin OR F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.  \n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole OR_BODY Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            { apply FocusingBangPar in H9...\n               checkPermutationCases H8.\n               rewrite H7 in H11.\n               inversion H11...\n               solveSignature1.\n               \n               checkPermutationCases H8.\n               rewrite H8 in H11.\n               inversion H11...\n               solveSignature1.\n               \n               apply weakening;solveSignature1.\n               \n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x2) \n                        (CK:=[])\n                        (CN:=x0);solveSignature1...\n              apply seqNtoSeq in H15.           \n              simpl... }\n             \n              apply FocusingBangPar in H9...\n               checkPermutationCases H9.\n               rewrite H7 in H12.\n               inversion H12...\n               solveSignature1.\n              checkPermutationCases H9.\n               rewrite H9 in H12.\n               inversion H12...\n               solveSignature1.\n               checkPermutationCases H11.\n               \n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor. \n               LLrew2 H11. \n                init2 x0 x6.\n               apply weakening;solveSignature1.\n             \n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x3) \n                        (CK:=[])\n                        (CN:=x5);solveSignature1...\n              apply seqNtoSeq in H16.           \n              simpl...\n           - apply BipoleReasoning in H3...\n             apply FocusingTensor in H7...\n             apply H in H6, H10...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor [d| t_bin IMP F0 G| ] x0.\n             simpl...\n             LLTensor x2 x3.\n             1-2: rewrite H7 in H8.\n             1-2: rewrite H8 in isFM.\n             1-2: inversion isFM...\n             \n             checkPermutationCases H9.\n             apply FocusingTensor in H7...\n             apply H in H9, H12...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             LLTensor x4 x5.\n       + apply FocusingInitRuleU in H3... \n           - TFocus (RINIT OO).\n              LLTensor [u| OO |] [d| OO |].\n           - checkPermutationCases H6.\n              checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor [ u| OO |] (@nil oo).\n             apply weakening;solveSignature1.\n             LLrew2 H6. \n             init2 x x2.\n           - checkPermutationCases H6.\n             TFocus (BinBipole AND_BODY Left P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor [d| t_bin AND P Q |] (@nil oo).\n             simpl... LLPlusL. LLRelease. LLStore.\n             TFocus (RINIT P).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor  (@nil oo) [ d| P |].\n             solveLL.\n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor ( @nil oo)[ d| OO |] .\n             solveLL.\n             TFocus (RINIT OO).\n             LLTensor (@nil oo) [ d| OO |] .\n             apply weakening;solveSignature1.\n             solveLL.\n           - checkPermutationCases H6.\n             checkPermutationCases H4.\n             checkPermutationCases H4.\n             \n             TFocus (BinBipole AND_BODY Left P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor.\n             apply weakening;solveSignature1.\n              LLrew2 H8. \n             init2 x x3.\n             simpl... LLPlusL. LLRelease. LLStore.\n             TFocus (RINIT P).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor (@nil oo) [ d| P |] .\n             solveLL.\n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor.\n              LLrew2 H6. \n             init2 x0 x3.\n              LLrew2 H4. \n             init2 x x4.\n           +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((loc, u| t_bin AND P Q |)\n           :: (loc, u| P |) :: (a, d| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor [d| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             \n             \n             assert(Hyp: seqN (LJ a) x3\n       ((loc, u| t_bin AND P Q |)\n           :: (loc, u| P |) ::  (a, d| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n       +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((loc, u| t_bin AND P Q |)\n           :: (loc, u| P |) ::  (loc, u| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor [u| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             eapply contractionN in H6...\n             apply H in H6...\n             solveSignature1.\n             \n             apply FocusingQuest in H6...\n             \n             assert(Hyp: seqN (LJ a) x3\n       ((loc, u| t_bin AND P Q |)\n           :: (loc, u| P |) ::  (loc, u| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n Qed.\n \n Theorem InvANDR2:  forall n a P Q B M, \n   IsPositiveAtomFormulaL M ->\n   IsPositiveAtomFormulaL (second B) ->\n    seqN (LJ a) n ((loc,u| t_bin AND P Q|) :: (loc,u| Q| )::B) M (UP []) -> seq (LJ a) ((loc,u| Q| )::B) M (UP []).\n    Proof with sauto;OLSolve.\n      induction n using strongind;intros *;\n      intros isFM isFB HF.\n      inversion HF...\n      inversion HF...\n      apply RemoveNotPos1 in H2...\n       intro Hc. inversion Hc;inversion H1...\n       inversion H4...\n       contradict H3.\n       constructor.\n       inversion H0...\n       contradict H3.\n       constructor.\n       apply InUNotPos in H6...\n       rewrite allU in H1...\n       2:{ solveSignature1. }\n       inversion H1...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor [u| t_cons TT | ] x0.\n             simpl... \n             simpl in H9.\n             checkPermutationCases H9.\n             TFocus (CteBipole TT_BODY Right).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             inversion H7...\n             solveF.\n             inversion H7...\n             solveF.\n           - apply BipoleReasoning in H3...\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor [d| t_cons FF | ] x0.\n             simpl... \n             checkPermutationCases H9.\n             TFocus (CteBipole FF_BODY Left).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n       + inversion H0...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole AND_BODY Right F0 G).\n              LLTensor [u| t_bin AND F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.\n            {\n             apply FocusingWith in H7...\n             apply H in H9, H10...\n            apply AbsorptionC'...\n            solveSignature1. }\n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole AND_BODY Right F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2: LLTensor [d| t_bin AND F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole AND_BODY Left F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n          - apply BipoleReasoning in H3...\n            apply FocusingPlus in H7...\n            1,2: apply H in H6...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2: LLTensor [u| t_bin OR F0 G| ] x0.\n            1,2: simpl...\n            \n            checkPermutationCases H9.\n            apply FocusingPlus in H7...\n            1,2: apply H in H9...\n            1,2: TFocus (BinBipole OR_BODY Right F0 G).\n            1,2:LLTensor (@nil oo) M.\n            1,3: LLrew2 H5. \n            1,2: init2 x0 x2.\n            1,2: simpl...\n           - apply BipoleReasoning in H3...\n              apply FocusingWith in H7...\n              apply H in H7, H9...\n              TFocus (BinBipole OR_BODY Left F0 G).\n              LLTensor [d| t_bin OR F0 G| ] x0. \n             simpl...\n             checkPermutationCases H9.  \n             apply FocusingWith in H7...\n             apply H in H10, H11...\n             TFocus (BinBipole OR_BODY Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             simpl...\n          - apply BipoleReasoning in H3...\n            { apply FocusingBangPar in H9...\n               checkPermutationCases H8.\n               rewrite H7 in H11.\n               inversion H11...\n               solveSignature1.\n               \n               checkPermutationCases H8.\n               rewrite H8 in H11.\n               inversion H11...\n               solveSignature1.\n               \n               apply weakening;solveSignature1.\n               \n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor [u| t_bin IMP F0 G| ] (@nil oo).\n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x2) \n                        (CK:=[])\n                        (CN:=x0);solveSignature1...\n              apply seqNtoSeq in H15.           \n              simpl... }\n             \n              apply FocusingBangPar in H9...\n               checkPermutationCases H9.\n               rewrite H7 in H12.\n               inversion H12...\n               solveSignature1.\n              checkPermutationCases H9.\n               rewrite H9 in H12.\n               inversion H12...\n               solveSignature1.\n               checkPermutationCases H11.\n               \n               TFocus (BinBipole (IMP_BODY a) Right F0 G).\n               LLTensor. \n               LLrew2 H11. \n                init2 x0 x6.\n               apply weakening;solveSignature1.\n             \n               simpl... createWorld;solveSignature1.\n               apply GenK4RelUT' with (C4:=x3) \n                        (CK:=[])\n                        (CN:=x5);solveSignature1...\n              apply seqNtoSeq in H16.           \n              simpl...\n           - apply BipoleReasoning in H3...\n             apply FocusingTensor in H7...\n             apply H in H6, H10...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor [d| t_bin IMP F0 G| ] x0.\n             simpl...\n             LLTensor x2 x3.\n             1-2: rewrite H7 in H8.\n             1-2: rewrite H8 in isFM.\n             1-2: inversion isFM...\n             \n             checkPermutationCases H9.\n             apply FocusingTensor in H7...\n             apply H in H9, H12...\n             TFocus (BinBipole (IMP_BODY a) Left F0 G).\n             LLTensor (@nil oo) M.\n             LLrew2 H5. \n             init2 x0 x2.\n             LLTensor x4 x5.\n       + apply FocusingInitRuleU in H3... \n           - TFocus (RINIT OO).\n              LLTensor [u| OO |] [d| OO |].\n           - checkPermutationCases H6.\n              checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor [ u| OO |] (@nil oo).\n             apply weakening;solveSignature1.\n             LLrew2 H6. \n             init2 x x2.\n           - checkPermutationCases H6.\n             TFocus (BinBipole AND_BODY Left P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor [d| t_bin AND P Q |] (@nil oo).\n             simpl... LLPlusR. LLRelease. LLStore.\n             TFocus (RINIT Q).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor  (@nil oo) [ d| Q |].\n             solveLL.\n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor ( @nil oo)[ d| OO |] .\n             solveLL.\n             TFocus (RINIT OO).\n             LLTensor (@nil oo) [ d| OO |] .\n             apply weakening;solveSignature1.\n             solveLL.\n           - checkPermutationCases H6.\n             checkPermutationCases H4.\n             checkPermutationCases H4.\n             \n             TFocus (BinBipole AND_BODY Left P Q).\n             apply ooth_rulesC.\n             constructor...\n             inversion H3.\n             LLTensor.\n             apply weakening;solveSignature1.\n              LLrew2 H8. \n             init2 x x3.\n             simpl... LLPlusR. LLRelease. LLStore.\n             TFocus (RINIT Q).\n             apply ooth_initC...\n             inversion H3.\n             LLTensor (@nil oo) [ d| Q |] .\n             solveLL.\n             checkPermutationCases H4.\n             TFocus (RINIT OO).\n             LLTensor.\n              LLrew2 H6. \n             init2 x0 x3.\n              LLrew2 H4. \n             init2 x x4.\n           +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((loc, u| t_bin AND P Q |)\n           :: (loc, u| Q |) :: (a, d| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor [d| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             \n             \n             assert(Hyp: seqN (LJ a) x3\n       ((loc, u| t_bin AND P Q |)\n           :: (loc, u| Q |) ::  (a, d| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (POS OO a).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n       +   apply BipoleReasoning in H3...\n             apply FocusingQuest in H6...\n             assert(Hyp: seqN (LJ a) x1\n       ((loc, u| t_bin AND P Q |)\n           :: (loc, u| Q |) ::  (loc, u| OO |)\n        :: B) x0 \n       (UP [])).\n             LLExact H5.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor [u| OO| ] x0.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n             \n             checkPermutationCases H8.\n             apply FocusingQuest in H6...\n             eapply contractionN in H6...\n             apply H in H6...\n             solveSignature1.\n             \n             apply FocusingQuest in H6...\n             \n             assert(Hyp: seqN (LJ a) x3\n       ((loc, u| t_bin AND P Q |)\n           :: (loc, u| Q |) ::  (loc, u| OO |)\n        :: B) M \n       (UP [])).\n             LLExact H8.\n             apply H in Hyp...\n             TFocus (NEG OO loc).\n             LLTensor (@nil oo) M . \n             LLrew2 H4. \n             init2 x0 x2.\n             LLRelease. LLStoreC.\n             LLExact Hyp.\n Qed.\n \n \nTheorem InversionTT\n     : forall (n m: nat) (a : subexp)\n         (B : list (subexp * oo)) (M : list oo),\n       IsPositiveAtomFormulaL M ->\n       IsPositiveAtomFormulaL (second B) ->\n       seqN (LJ a) m ((a, d| t_cons TT |) :: B) M (UP []) ->\n       seq (LJC a n) B M (UP []).\n Proof with auto.\n   intros. \n   apply InvTT in H1...\n   refine (WeakTheory _ _ H1)...\n   apply TheoryEmb1.\n Qed.   \n\nTheorem InversionFF\n     : forall (n m: nat) (a : subexp)\n         (B : list (subexp * oo)) (M : list oo),\n       IsPositiveAtomFormulaL M ->\n       IsPositiveAtomFormulaL (second B) ->\n       seqN (LJ a) m ((loc, u| t_cons FF |) :: B) M (UP []) ->\n       seq (LJC a n) B M (UP []).\n Proof with auto.\n   intros. \n   apply InvFF in H1...\n   refine (WeakTheory _ _ H1)...\n   apply TheoryEmb1.\n Qed.\n \n Theorem InversionANDL\n     : forall (n m: nat) (a : subexp) (P Q : uexp)\n         (B : list (subexp * oo)) (M : list oo),\n       IsPositiveAtomFormulaL M ->\n       IsPositiveAtomFormulaL (second B) ->\n       mt a = true ->\n       m4 a = true ->\n       seqN (LJ a) m\n         ((a, d| t_bin AND P Q |) :: B) M \n         (UP []) ->\n       seq (LJC a n) ((a, d| P |) :: (a, d| Q |) :: B) M\n         (UP []).\n Proof with auto.\n   intros.\n   eapply WeakTheory with (th:=(LJ a)). \n   apply TheoryEmb1.\n   eapply InvANDL with (n:=m)...\n   LLSwap.\n   apply weakeningN;solveSignature1.\n   LLSwap.\n   apply weakeningN;solveSignature1...\n  Qed.\n\n  Theorem InversionORR\n     : forall (n m: nat) (a : subexp) (P Q : uexp)\n         (B : list (subexp * oo)) (M : list oo),\n       IsPositiveAtomFormulaL M ->\n       IsPositiveAtomFormulaL (second B) ->\n       seqN (LJ a) m\n         ((loc, u| t_bin OR P Q |) :: B) M \n         (UP []) ->\n       seq (LJC a n) ((loc, u| P |) :: (loc, u| Q |) :: B) M\n         (UP []).\n Proof with auto.\n   intros.\n   eapply WeakTheory with (th:=(LJ a)). \n   apply TheoryEmb1.\n   eapply InvORR with (n:=m)...\n   LLSwap.\n   apply weakeningN;solveSignature1.\n   LLSwap.\n   apply weakeningN;solveSignature1...\n  Qed.\n  \n Theorem InversionANDR1\n     : forall (n m: nat) (a : subexp) (P Q : uexp)\n         (B : list (subexp * oo)) (M : list oo),\n       IsPositiveAtomFormulaL M ->\n       IsPositiveAtomFormulaL (second B) ->\n       seqN (LJ a) m\n         ((loc, u| t_bin AND P Q |) :: B) M\n         (UP []) ->\n       seq (LJC a n) ((loc, u| P |) :: B) M (UP []).\n  Proof with auto.\n   intros.\n   eapply WeakTheory with (th:=(LJ a)). \n   apply TheoryEmb1.\n   eapply InvANDR1 with (Q:=Q) (n:=m)...\n   LLSwap.\n   apply weakeningN;solveSignature1...\n  Qed.        \n\n Theorem InversionANDR2\n     : forall (n m: nat) (a : subexp) (P Q : uexp)\n         (B : list (subexp * oo)) (M : list oo),\n       IsPositiveAtomFormulaL M ->\n       IsPositiveAtomFormulaL (second B) ->\n       seqN (LJ a) m\n         ((loc, u| t_bin AND P Q |) :: B) M\n         (UP []) ->\n       seq (LJC a n) ((loc, u| Q |) :: B) M (UP []).\n  Proof with auto.\n   intros.\n   eapply WeakTheory with (th:=(LJ a)). \n   apply TheoryEmb1.\n   eapply InvANDR2 with (P:=P) (n:=m)...\n   LLSwap.\n   apply weakeningN;solveSignature1...\n  Qed.        \n \n  Theorem InversionORL1\n     : forall (n m: nat) (a : subexp) (P Q : uexp)\n         (B : list (subexp * oo)) (M : list oo),\n       IsPositiveAtomFormulaL M ->\n       IsPositiveAtomFormulaL (second B) ->\n       mt a = true ->\n       m4 a = true ->\n       seqN (LJ a) m\n         ((a, d| t_bin OR P Q |) :: B) M\n         (UP []) ->\n       seq (LJC a n) ((a, d| P |) :: B) M (UP []).\n  Proof with auto.\n   intros.\n   eapply WeakTheory with (th:=(LJ a)). \n   apply TheoryEmb1.\n   eapply InvORL1 with (Q:=Q) (n:=m)...\n   LLSwap.\n   apply weakeningN;solveSignature1...\n  Qed.        \n\n  Theorem InversionORL2\n     : forall (n m: nat) (a : subexp) (P Q : uexp)\n         (B : list (subexp * oo)) (M : list oo),\n       IsPositiveAtomFormulaL M ->\n       IsPositiveAtomFormulaL (second B) ->\n       mt a = true ->\n       m4 a = true ->\n       seqN (LJ a) m\n         ((a, d| t_bin OR P Q |) :: B) M\n         (UP []) ->\n       seq (LJC a n) ((a, d| Q |) :: B) M (UP []).\n  Proof with auto.\n   intros.\n   eapply WeakTheory with (th:=(LJ a)). \n   apply TheoryEmb1.\n   eapply InvORL2 with (P:=P) (n:=m)...\n   LLSwap.\n   apply weakeningN;solveSignature1...\n  Qed.\n   \n  Theorem InversionIMPL\n     : forall (n m: nat) (a : subexp) (P Q : uexp)\n         (B : list (subexp * oo)) (M : list oo),\n       IsPositiveAtomFormulaL M ->\n       IsPositiveAtomFormulaL (second B) ->\n       mt a = true ->\n       m4 a = true ->\n       seqN (LJ a) m\n         ((a, d| t_bin IMP P Q |) :: B) M\n         (UP []) -> \n         seq (LJC a n) ((a, d| Q |) :: B) M (UP []).\n  Proof with auto.\n   intros.\n   eapply WeakTheory with (th:=(LJ a)). \n   apply TheoryEmb1.\n   eapply InvIMPL with (P:=P) (n:=m)...\n      LLSwap.\n   apply weakeningN;solveSignature1...\n  Qed.\n           \n  Theorem InversionIMPR\n          : forall (n m: nat) (a : subexp) (P Q : uexp)\n         (B : list (subexp * oo)) (M : list oo),\n       IsPositiveAtomFormulaL M ->\n       IsPositiveAtomFormulaL (second B) ->\n       mt a = true ->\n       m4 a = true ->\n       seqN (LJ a) m\n         ((loc, u| t_bin IMP P Q |) :: B) M \n         (UP []) ->\n       seq (LJC a n) ((a, d| P |) :: (loc, u| Q |) :: B) M\n         (UP []).\nProof with auto.\n   intros.\n   eapply WeakTheory with (th:=(LJ a)). \n   apply TheoryEmb1.\n   eapply InvIMPR with (n:=m)...\n   LLSwap.\n   apply weakeningN;solveSignature1... \nLLSwap.\n   apply weakeningN;solveSignature1...\n\n  Qed.\n       \nEnd LJInv.", "meta": {"author": "meta-logic", "repo": "MMLL", "sha": "dc4cb8cc9056efb264be3a97e9bfd4c2cf32838e", "save_path": "github-repos/coq/meta-logic-MMLL", "path": "github-repos/coq/meta-logic-MMLL/MMLL-dc4cb8cc9056efb264be3a97e9bfd4c2cf32838e/OL/CutCoherence/LNSi/LJInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23215507000794144}}
{"text": "(* Copyright (c) 2012-2015, Robbert Krebbers. *)\n(* This file is distributed under the terms of the BSD license. *)\n(** This file defines an axiomatic semantics (in the form of shallow embedding\nof a separation logic) for our language. This axiomatic semantics has two\njudgments: one for statements and one for expressions. Statement judgment are\nsextuples of the shape [Γ\\ δ\\ R\\ J\\ T ⊨ₛ {{ P }} s {{ Q }}] where:\n\n- [s] is a statement, and [P] and [Q] are assertions called the pre- and\n  postcondition of [s], respectively.\n- [R] is a function that gives the returning condition for a return value.\n  That means, [R v] has to hold to execute a [return e] where execution of [e]\n  yields the value [v].\n- [J] is a function that gives the jumping condition for each goto. That means,\n  [J l] has to hold to execute a [goto l].\n- [T] is a function that gives the jumping condition for each throw.\n\nThe assertions [P], [Q], [R], [J] and [T] correspond to the four directions [↘],\n[↗], [⇈], [↷] and [↑] in which traversal through a statement can be performed.\nWe therefore treat the sextuple as a triple [Γ\\ Pd ⊨ₚ s] where [Pd] is a\nfunction from directions to assertions such that [Pd ↘ = P], [Pd ↗ = Q],\n[Pd (⇈ v) = R v], [P (↷ l) = J l], and [P (↑ n) = T n] *)\n\n(** Expression judgments are quintuples [Γ\\ δ\\ A ⊨ₑ {{ P }} e {{ Q }}]. As\nusual, [P] and [Q] are the pre- and postcondition of [e]. However, whereas the\nprecondition is just an assertion, the postcondition is a function from values\nto assertions. It ensures that if execution of [e] yields a value [v], then\n[Q v] holds. The environment [A] can be used to \"frame\" writable memory that is\nbeing shared by all function calls. *)\nRequire Export assertions.\nRequire Import axiomatic_graph.\nLocal Open Scope nat_scope.\nLocal Obligation Tactic := idtac.\n\nLtac simplify_mem_disjoint_hyps :=\n  simplify_sep_disjoint_hyps;\n  repeat match goal with\n  | H : ✓{_} (_ ∪ _) |- _ =>\n     rewrite cmap_union_valid in H by auto; destruct H\n  end.\nLtac solve_mem_disjoint :=\n  repeat match goal with\n  | H : ✓{_} _ |- _ => apply cmap_valid_sep_valid in H\n  end; solve_sep_disjoint.\nLocal Hint Extern 1 (_ ## _) => solve_mem_disjoint: core.\nLocal Hint Extern 1 (## _) => solve_mem_disjoint: core.\nLocal Hint Extern 1 (sep_valid _) => solve_mem_disjoint: core.\nLocal Hint Extern 1 (_ ⊆ _) => etransitivity; [eassumption|]: core.\nLocal Hint Extern 1 (_ ≤ _) => lia: core.\n\n(** ** Directed assertions *)\n(** The statement judgment will be of the shape [Γ\\ δ\\ Pd ⊨ₚ s] where [Pd] is\na function from directions to assertions taking the pre- and post, returning,\nand jumping condition together. We generalize this idea slightly, and define\nthe type [directed A] as functions [direction → A]. *)\nDefinition directed_pack {K A} (P : A) (Q : A) (R : val K → A)\n    (J : labelname → A) (T : nat → A) (C : option Z → A) : direction K → A :=\n  direction_rect _ (λ _, A) P Q R J T C.\n\n(** This hideous definition of [fmap] makes [f <$> directed_pack P Q R J]\nconvertable with [directed_pack (f P) (f Q) (f ∘ R) (f ∘ J)]. *)\n#[global] Instance directed_fmap {K} : FMap (direction K →.) := λ A B f Pd d,\n  match d with\n  | ↘ => f (Pd ↘)\n  | ↗ => f (Pd ↗)\n  | ⇈ v => f (Pd (⇈ v))\n  | ↷ l => f (Pd (↷ l))\n  | ↑ n => f (Pd (↑ n))\n  | ↓ mx => f (Pd (↓ mx))\n  end.\n\nNotation dassert K := (direction K → assert K).\nNotation dassert_pack P Q R J T C :=\n  (@directed_pack _ (assert _) P%A Q%A R%A J%A T%A C%A).\nDefinition dassert_pack_top `{Env K}\n    (P : assert K) (R : val K → assert K) : dassert K :=\n  dassert_pack P (R voidV) R (λ _, False%A) (λ _, False%A) (λ _, False%A).\n\n(** ** The Hoare judgment for statements *)\n(** Now the interpretation of the statement Hoare judgment is just taking all\nof the previously defined notions together. We require both the program and\nthe memory to contain no locks at the start. Also, we require all locks to be\nreleased in the end, as each statement that contains an expression always has\na sequence point in the end. *)\nInductive ax_stmt_post' `{Env K} (Pd : dassert K) (s : stmt K) (cmτ : rettype K)\n    (Γ : env K) (Δ : memenv K) (δ : funenv K)\n    (ρ : stack K) (n : nat) : focus K → mem K → Prop :=\n  mk_ax_stmt_post d m :\n    direction_out d s → (Γ,Δ) ⊢ d : cmτ →\n    mem_locks m = ∅ →\n    assert_holds (Pd d) Γ Δ δ ρ n (cmap_erase m) →\n    ax_stmt_post' Pd s cmτ Γ Δ δ ρ n (Stmt d s) m.\nProgram Definition ax_stmt_post `{EnvSpec K} (Pd : dassert K)\n    (s : stmt K) (cmτ : rettype K) : ax_assert K := {|\n  ax_assert_holds := ax_stmt_post' Pd s cmτ\n|}.\nNext Obligation.\n  intros ??? Pd s cmτ Γ1 Γ2 Δ1 Δ2 δ1 δ2 ρ n n' φ m ????;\n    destruct 1 as [d m' ????]; constructor;\n    eauto using direction_typed_weaken, assert_weaken, cmap_erase_valid.\nQed.\nNext Obligation.\n  intros ??? Pd s cmτ Γ Δ δ n ρ φ m m' [d m'' ????] [? p]; inv_rcstep; set_solver.\nQed.\nDefinition ax_stmt_packed `{EnvSpec K} (Γ : env K) (δ : funenv K)\n    (Pd : dassert K) (s : stmt K) : Prop := ∀ Γ' Δ δ' n ρ d m cmτ,\n  ✓ Γ' → Γ ⊆ Γ' → δ ⊆ δ' →\n  ✓{Γ',Δ} δ' →\n  ✓{Γ',Δ} m →\n  mem_locks m = ∅ →\n  direction_in d s →\n  (Γ',Δ,ρ.*2) ⊢ s : cmτ →\n  ✓{Δ}* ρ →\n  assert_holds (Pd d) Γ' Δ δ' ρ n (cmap_erase m) →\n  ax_graph ax_disjoint_cond (ax_stmt_post Pd s cmτ) Γ' δ' Δ ρ n [] (Stmt d s) m.\n#[global] Instance: Params (@ax_stmt_packed) 5 := {}.\nNotation \"Γ \\ δ \\ P ⊨ₚ s\" :=\n  (ax_stmt_packed Γ δ P%A s)\n  (at level 74, δ at next level, P at next level, s at next level,\n   format \"Γ \\  δ \\  P  ⊨ₚ  '[' s ']'\") : C_scope.\n\nDefinition ax_stmt `{EnvSpec K} (Γ : env K) (δ : funenv K) R J T C P s Q :=\n  Γ\\ δ\\ dassert_pack P Q R J T C ⊨ₚ s.\nDefinition ax_stmt_top `{EnvSpec K} (Γ : env K) (δ : funenv K) P s Q :=\n  Γ\\ δ\\ dassert_pack_top P Q ⊨ₚ s.\n#[global] Instance: Params (@ax_stmt) 5 := {}.\n#[global] Instance: Params (@ax_stmt_top) 5 := {}.\nNotation \"Γ \\ δ \\ R \\ J \\ T \\ C ⊨ₛ {{ P } } s {{ Q } }\" :=\n  (ax_stmt Γ δ R%A J%A T%A C%A P%A s Q%A)\n  (at level 74, δ at next level, R at next level,\n   J at next level, T at next level, C at next level,\n   format \"Γ \\  δ \\  R \\  J \\  T \\  C  ⊨ₛ  '[' {{  P  } } '/'  s  '/' {{  Q  } } ']'\") : C_scope.\nNotation \"Γ \\ δ ⊨ₛ {{ P } } s {{ Q } }\" :=\n  (ax_stmt_top Γ δ P%A s%S Q%A)\n  (at level 74, δ at next level,\n   format \"Γ \\  δ  ⊨ₛ  '[' {{  P  } } '/'  s  '/' {{  Q  } } ']'\") : C_scope.\n\n(** ** The Hoare judgment for expressions *)\n(** The interpretation of the expression judgment is defined similarly as the\ninterpretation of the judgment for statements. At the start, we require both\nthe expression and the memory to be lock free. In the end, the locks in the\nmemory should exactly match the annotated locations in the final expression\nthat remain to be unlocked. The latter is important, as an unlock operation at\na sequence point thereby corresponds to unlocking everything. *)\nInductive ax_expr_frame (K : iType) : iType :=\n  InExpr (mf mA : mem K) | InFun (mf : mem K).\nArguments InExpr {_} _ _.\nArguments InFun {_} _.\n\nInductive ax_expr_cond_frame `{Env K}\n     (ρ : stack K) (A : assert K) (Γ : env K)\n     (Δ : memenv K) (δ : funenv K) (k : ctx K)\n     (n : nat) (φ : focus K) (m m' : mem K) : ax_expr_frame K → Prop :=\n  | ax_frame_in_expr mA mf :\n     m' = m ∪ mf ∪ mA → ✓{Γ,Δ} mf → ✓{Γ,Δ} mA →\n     ## [m; mf; mA] → k = [] → cmap_erased mA → mem_locks mA = ∅ →\n     assert_holds A Γ Δ δ ρ n mA →\n     ax_expr_cond_frame ρ A Γ Δ δ k n φ m m' (InExpr mf mA)\n  | ax_frame_in_fun mf :\n     m' = m ∪ mf → ✓{Γ,Δ} mf →\n     ## [m; mf] → k ≠ [] →\n     ax_expr_cond_frame ρ A Γ Δ δ k n φ m m' (InFun mf).\nInductive ax_expr_cond_unframe `{Env K}\n     (ρ : stack K) (A : assert K) (Γ : env K)\n     (Δ : memenv K) (δ : funenv K) (k : ctx K)\n     (n : nat) (φ : focus K) (m m' : mem K) : ax_expr_frame K → Prop :=\n  | ax_unframe_expr_to_expr mA mf :\n     m' = m ∪ mf ∪ mA → ## [m; mf; mA] → k = [] →\n     ax_expr_cond_unframe ρ A Γ Δ δ k n φ m m' (InExpr mf mA)\n  | ax_unframe_fun_to_expr mA mf :\n     m' = m ∪ mf ∪ mA → ## [m; mf; mA] → k = [] →\n     cmap_erased mA → mem_locks mA = ∅ →\n     assert_holds A Γ Δ δ ρ n mA → \n     ax_expr_cond_unframe ρ A Γ Δ δ k n φ m m' (InFun mf)\n  | ax_unframe_expr_to_fun m'' mA mf :\n     m = m'' ∪ mA → m' = m'' ∪ mf ∪ mA → ## [m''; mf; mA] → k ≠ [] →\n     ax_expr_cond_unframe ρ A Γ Δ δ k n φ m m' (InExpr mf mA)\n  | ax_unframe_fun_to_fun mf :\n     m' = m ∪ mf → ## [m; mf] → k ≠ [] →\n     ax_expr_cond_unframe ρ A Γ Δ δ k n φ m m' (InFun mf).\nProgram Definition ax_expr_cond `{EnvSpec K} (ρ : stack K)\n    (A : assert K) : ax_frame_cond K (ax_expr_frame K) := {|\n  frame := ax_expr_cond_frame ρ A;\n  unframe := ax_expr_cond_unframe ρ A\n|}.\nNext Obligation.\n  intros ??? ρ A Γ Δ δ k n φ m m' ??;\n    destruct 1; subst; auto using cmap_union_valid_2.\nQed.\nNext Obligation.\n  intros ??? ρ A Γ Δ δ k n φ m m' ??; destruct 1; subst;\n    rewrite ?cmap_union_valid; intuition.\nQed.\n\nDefinition ax_expr_invariant `{Env K} (A : assert K)\n    (Γ : env K) (Δ : memenv K) (δ : funenv K)\n    (ρ : stack K) (n : nat) (m : mem K) := ∃ mA,\n  ## [mA; m] ∧ ✓{Γ,Δ} mA ∧ cmap_erased mA ∧ mem_locks mA = ∅ ∧\n  assert_holds A Γ Δ δ ρ n mA.\nInductive ax_expr_post' `{Env K} (Q : lrval K → assert K)\n    (τlr : lrtype K) (Γ : env K) (Δ : memenv K)\n    (δ : funenv K) (ρ : stack K) (n : nat) : focus K → mem K → Prop :=\n  mk_ax_expr_post ν Ω m :\n    (Γ,Δ) ⊢ ν : τlr →\n    mem_locks m = Ω →\n    assert_holds (Q ν) Γ Δ δ ρ n (cmap_erase m) →\n    ax_expr_post' Q τlr Γ Δ δ ρ n (Expr (%#{Ω} ν)) m.\nProgram Definition ax_expr_post `{EnvSpec K}\n    (Q : lrval K → assert K) (τlr : lrtype K) : ax_assert K := {|\n  ax_assert_holds := ax_expr_post' Q τlr\n|}.\nNext Obligation.\n  intros ??? Q τlr Γ1 Γ2 Δ1 Δ2 δ1 δ2 ρ n φ m ?????; destruct 1; constructor;\n    eauto using assert_weaken, cmap_erase_valid, lrval_typed_weaken.\nQed.\nNext Obligation.\n  intros ??? Q τlr Γ Δ δ ρ n φ m m' [d m'' ???] [? p]; inv_rcstep.\nQed.\nDefinition ax_expr `{EnvSpec K} (Γ : env K) (δ : funenv K) (A P : assert K)\n    (e : expr K) (Q : lrval K → assert K) : Prop := ∀ Γ' Δ δ' n ρ m τlr,\n  ✓ Γ' → Γ ⊆ Γ' → δ ⊆ δ' →\n  ✓{Γ',Δ} δ' →\n  ✓{Γ',Δ} m →\n  mem_locks m = ∅ →\n  (Γ',Δ,ρ.*2) ⊢ e : τlr →\n  locks e = ∅ →\n  ✓{Δ}* ρ →\n  ax_expr_invariant A Γ' Δ δ' ρ n m →\n  assert_holds P Γ' Δ δ' ρ n (cmap_erase m) →\n  ax_graph (ax_expr_cond ρ A) (ax_expr_post Q τlr) Γ' δ' Δ ρ n [] (Expr e) m.\n#[global] Instance: Params (@ax_expr) 5 := {}.\nNotation \"Γ \\ δ \\ A ⊨ₑ {{ P } } e {{ Q } }\" :=\n  (ax_expr Γ δ A%A P%A e Q%A)\n  (at level 74, δ at next level, A at next level,\n  format \"Γ \\  δ \\  A  ⊨ₑ  '[' {{  P  } } '/'  e  '/' {{  Q  } } ']'\") : C_scope.\n\n(** ** Function specifications *)\nInductive fassert (K : Type) `{Env K} := FAssert {\n  fcommon : Type;\n  fpre : fcommon → list (val K) → assert K;\n  fpost : fcommon → list (val K) → val K → assert K;\n  fpre_stack_indep c vs : StackIndep (fpre c vs);\n  fpost_stack_indep c vs v : StackIndep (fpost c vs v)\n}.\nArguments fcommon {_ _} _.\nArguments fpre {_ _} _ _ _.\nArguments fpost {_ _} _ _ _ _.\n#[global] Existing Instance fpre_stack_indep.\n#[global] Existing Instance fpost_stack_indep.\n\nInductive ax_fun_post' `{Env K}\n    (f : funname) (τ : type K) (P : val K → assert K)\n    (Γ : env K) (Δ : memenv K) (δ : funenv K)\n    (ρ : stack K) (n : nat) : focus K → mem K → Prop :=\n  mk_ax_fun_post v m :\n    (Γ,Δ) ⊢ v : τ →\n    mem_locks m = ∅ →\n    assert_holds (P v) Γ Δ δ ρ n (cmap_erase m) →\n    ax_fun_post' f τ P Γ Δ δ ρ n (Return f v) m.\nProgram Definition ax_fun_post `{EnvSpec K} (f : funname) (τ : type K)\n    (P : val K → assert K) : ax_assert K := {|\n  ax_assert_holds := ax_fun_post' f τ P \n|}.\nNext Obligation.\n  intros ??? f τ Pf Γ1 Γ2 Δ1 Δ2 δ1 δ2 ρ n n' φ ?????; destruct 1 as [v m];\n    constructor; eauto using assert_weaken, cmap_erase_valid, val_typed_weaken.\nQed.\nNext Obligation.\n  intros ??? f τ Pf Γ Δ δ n ρ φ m m' [v m'' ??] [? p]; inv_rcstep.\nQed.\nProgram Definition assert_fun `{EnvSpec K} (f : funname)\n    (Pf : fassert K) (τs : list (type K)) (τ : type K) : assert K := {|\n  assert_holds Γ Δ δ ρ n m :=\n    m = ∅ ∧\n    Γ !! f = Some (τs,τ) ∧\n    ∀ Γ' Δ' δ' n' c vs m',\n      Γ ⊆ Γ' → ✓ Γ' → Δ ⇒ₘ Δ' → δ ⊆ δ' → n' ≤ n →\n      ✓{Γ',Δ'} δ' →\n      ✓{Γ',Δ'} m' →\n      mem_locks m' = ∅ →\n      (Γ',Δ') ⊢* vs :* τs →\n      assert_holds (fpre Pf c vs) Γ' Δ' δ' [] n' (cmap_erase m') →\n      ax_graph ax_disjoint_cond\n        (ax_fun_post f τ (fpost Pf c vs)) Γ' δ' Δ' [] n' [] (Call f vs) m'\n|}.\nNext Obligation. naive_solver eauto using lookup_fun_weaken. Qed.\n\nSection axiomatic.\nContext `{EnvSpec K}.\nImplicit Types Γ : env K.\nImplicit Types Δ : memenv K.\nImplicit Types δ : funenv K.\nImplicit Types m : mem K.\nImplicit Types e : expr K.\nImplicit Types s : stmt K.\n\nHint Immediate cmap_valid_memenv_valid: core.\nHint Resolve cmap_empty_valid cmap_erased_empty mem_locks_empty: core.\nHint Resolve cmap_union_valid_2 cmap_erase_valid: core.\n\n#[global] Instance directed_pack_proper `{!@Equivalence A R} :\n  Proper (R ==> R ==> pointwise_relation _ R ==> pointwise_relation _ R ==>\n    pointwise_relation _ R ==> pointwise_relation _ R ==>\n    pointwise_relation _ R) (@directed_pack K A).\nProof. intros ?????????????????? []; simplify_equality'; auto. Qed.\nLemma directed_fmap_spec {A B} (f : A → B) (P : direction K → A) d :\n  (@fmap _ (@directed_fmap K) _ _ f P) d = f (P d).\nProof. by destruct d. Qed.\n#[global] Instance ax_stmt_packed_proper Γ δ : Proper\n  (pointwise_relation _ (≡{Γ,δ}) ==> (=) ==> iff) (ax_stmt_packed Γ δ).\nProof.\n  cut (Proper (pointwise_relation _ (≡{Γ,δ}) ==> (=) ==> impl)\n              (ax_stmt_packed Γ δ)).\n  { intros help. by split; apply help. }\n  intros Pd Qd HPQ ?? -> Hax ??????????????????.\n  eapply ax_weaken with ax_disjoint_cond (ax_stmt_post Pd _ _) n; eauto.\n  { eapply Hax, HPQ; eauto. }\n  destruct 2; constructor; auto.\n  eapply HPQ; eauto using indexes_valid_weaken, funenv_valid_weaken.\nQed.\nLemma ax_stmt_top_unfold Γ δ P (Q : val _ → assert _) s :\n  Γ\\ δ ⊨ₛ {{ P }} s {{ Q }} ↔\n  Γ\\ δ\\ Q\\ (λ _, False)\\ (λ _, False)\\ (λ _, False) ⊨ₛ {{ P }} s {{ Q voidV }}.\nProof. done. Qed.\n#[global] Instance ax_stmt_proper Γ δ :\n  Proper (pointwise_relation _ (≡{Γ,δ}) ==> pointwise_relation _ (≡{Γ,δ}) ==>\n     pointwise_relation _ (≡{Γ,δ}) ==> pointwise_relation _ (≡{Γ,δ}) ==>\n     (≡{Γ,δ}) ==> (=) ==> (≡{Γ,δ}) ==> iff) (ax_stmt Γ δ).\nProof.\n  intros ?? HR ?? HJ ?? HT ?? HC ?? HP ?? -> ?? HQ.\n  unfold ax_stmt. by rewrite HR, HJ, HT, HC, HP, HQ.\nQed.\n#[global] Instance ax_stmt_top_proper Γ δ :\n  Proper ((≡{Γ,δ}) ==> (=) ==> pointwise_relation _ (≡{Γ,δ}) ==> iff)\n         (ax_stmt_top Γ δ).\nProof.\n  intros ?? HP ?? -> ?? HQ.\n  unfold ax_stmt_top, dassert_pack_top. by rewrite HP, HQ.\nQed.\n\nLemma ax_expr_invariant_emp Γ Δ δ ρ n m :\n  ✓{Γ,Δ} m → ax_expr_invariant emp Γ Δ δ ρ n m.\nProof. by eexists ∅; split_and ?; eauto. Qed.\nHint Resolve ax_expr_invariant_emp: core.\nLemma ax_expr_invariant_weaken Γ Δ δ A ρ n1 n2 m1 m2 :\n  ✓ Γ → ✓{Δ}* ρ →\n  ax_expr_invariant A Γ Δ δ ρ n1 m2 → m1 ⊆ m2 → n2 ≤ n1 →\n  ax_expr_invariant A Γ Δ δ ρ n2 m1.\nProof.\n  intros ?? (mA&?&?&?&?&?) Hm12.\n  exists mA; split_and ?; eauto using assert_weaken.\n  by rewrite <-(sep_subseteq_disjoint_le m1) by eauto.\nQed.\nLemma ax_disjoint_expr_compose_diagram Γ ρ A Ek :\n  ax_compose_diagram ax_disjoint_cond (ax_expr_cond ρ A) Γ [Ek].\nProof.\n  intros Δ δ k n φ a m m' ??; simpl.\n  destruct 1; subst; [discriminate_list_equality|].\n  exists mf; split_and ?; auto; intros Δ' k' φ' m2 m2' ?? [-> ?].\n  constructor; trivial; intro; discriminate_list_equality.\nQed.\nLemma ax_expr_disjoint_compose_diagram Γ ρ k :\n  ax_compose_diagram (ax_expr_cond ρ emp%A) ax_disjoint_cond Γ k.\nProof.\n  intros Δ δ k' φ n m m' mf ?? (->&?&?); simpl.\n  destruct (decide (k' = [])) as [->|].\n  * exists (InExpr mf ∅). split.\n    { by constructor; rewrite ?sep_right_id by auto;\n        eauto using mem_locks_empty, cmap_empty_valid, cmap_erased_empty. }\n    intros Δ' k'' φ' m2 m2' ??; inversion 1; subst;\n      rewrite ?sep_right_id by auto; auto.\n  * exists (InFun mf); split; [by constructor|].\n    intros Δ' k'' φ' m2 m2' ??; inversion 1 as [|mA mf' ????? [??]| | ]; subst;\n      rewrite ?sep_right_id by auto; auto.\nQed.\nLemma ax_expr_cond_frame_diagram_simple Γ ρ B mf :\n  ax_frame_diagram (ax_expr_cond ρ B) (ax_expr_cond ρ B) Γ mf.\nProof.\n  intros Δ δ k φ n m m' ??; destruct 4 as [mA mf'|mf']; subst.\n  * simplify_mem_disjoint_hyps; exists (InExpr (mf ∪ mf') mA); split.\n    { constructor; auto. by rewrite sep_associative by auto. }\n    intros Δ' k' φ' m2 m2'.\n    inversion 1 as [| |m''|]; intros; simplify_mem_disjoint_hyps; subst.\n    + split; auto. apply ax_unframe_expr_to_expr; auto.\n      by rewrite sep_associative by auto.\n    + split; auto. apply ax_unframe_expr_to_fun with (m'' ∪ mf); auto.\n      - by rewrite <-!sep_associative, (sep_commutative mA) by auto.\n      - by rewrite sep_associative by auto.\n  * simplify_mem_disjoint_hyps; exists (InFun (mf ∪ mf')); split.\n    { constructor; auto. by rewrite sep_associative by auto. }\n    intros Δ' k' φ' m2 m2'.\n    inversion 1 as [|mA| |]; intros; simplify_mem_disjoint_hyps; subst.\n    + split; auto. apply ax_unframe_fun_to_expr with mA; auto.\n      by rewrite sep_associative by auto.\n    + split; auto. apply ax_unframe_fun_to_fun; auto.\n      by rewrite sep_associative by auto.\nQed.\n#[global] Instance ax_expr_proper Γ δ :\n  Proper ((≡{Γ,δ}) ==> (≡{Γ,δ}) ==> (=) ==>\n          pointwise_relation _ (≡{Γ,δ}) ==> iff) (ax_expr Γ δ).\nProof.\n  cut (Proper ((≡{Γ,δ}) ==> (≡{Γ,δ}) ==> (=) ==>\n    pointwise_relation _ (≡{Γ,δ}) ==> impl) (ax_expr Γ δ)).\n  { intros help. by split; apply help. }\n  intros A1 A2 HA P1 P2 HP ?? -> Q1 Q2 HQ Hax ???????????????? (?&?&?&?&?&?) ?.\n  eapply ax_weaken with (ax_expr_cond ρ A1) (ax_expr_post Q1 τlr) n; eauto.\n  * apply Hax, HP; eauto.\n    econstructor; split_and ?; eauto. apply HA; eauto.\n  * destruct 2; constructor; auto.\n    apply HA; eauto using indexes_valid_weaken, funenv_valid_weaken.\n  * destruct 2; subst; simplify_mem_disjoint_hyps; econstructor; first\n     [by eauto|apply HA;eauto using indexes_valid_weaken, funenv_valid_weaken].\n  * destruct 2; constructor; auto.\n    apply HQ; eauto using indexes_valid_weaken, funenv_valid_weaken.\nQed.\nEnd axiomatic.\n", "meta": {"author": "robbertkrebbers", "repo": "ch2o", "sha": "1afb3f615db053b741341e9bfd1d5c65bddea641", "save_path": "github-repos/coq/robbertkrebbers-ch2o", "path": "github-repos/coq/robbertkrebbers-ch2o/ch2o-1afb3f615db053b741341e9bfd1d5c65bddea641/axiomatic/axiomatic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23215507000794144}}
{"text": "From RecordUpdate Require Import RecordSet.\nImport RecordSetNotations.\n\nFrom Perennial.algebra Require Import liftable auth_map.\nFrom Perennial.Helpers Require Import Transitions.\nFrom Perennial.program_proof Require Import disk_prelude.\nFrom Perennial.Helpers Require Import NamedProps Map List range_set.\nFrom Perennial.algebra Require Import log_heap.\nFrom Perennial.program_logic Require Import spec_assert.\n\nFrom Goose.github_com.mit_pdos.go_nfsd Require Import simple.\nFrom Perennial.program_proof Require Import obj.obj_proof marshal_proof addr_proof crash_lockmap_proof addr.addr_proof buf.buf_proof.\nFrom Perennial.program_proof Require Import jrnl.sep_jrnl_proof jrnl.sep_jrnl_recovery_proof.\nFrom Perennial.program_proof Require Import disk_prelude.\nFrom Perennial.program_proof Require Import disk_lib.\nFrom Perennial.goose_lang.lib Require Import slice.typed_slice into_val.\nFrom Perennial.program_proof.simple Require Import spec invariant common.\nFrom Perennial.goose_lang Require Import crash_modality.\n\nSection stable.\nContext `{!heapGS Σ}.\nContext `{!simpleG Σ}.\n\nGlobal Instance is_inode_stable_set_stable γsrc γ':\n    IntoCrash ([∗ set] a ∈ covered_inodes, is_inode_stable γsrc γ' a)\n              (λ _, ([∗ set] a ∈ covered_inodes, is_inode_stable γsrc γ' a))%I.\nProof. rewrite /IntoCrash. iApply post_crash_nodep. Qed.\n\nGlobal Instance is_txn_durable_stable γ dinit logm:\n    IntoCrash (is_txn_durable γ dinit logm) (λ _, is_txn_durable γ dinit logm).\nProof.\n  rewrite /IntoCrash. iNamed 1.\n  iDestruct (post_crash_nodep with \"Hlogm\") as \"Hlogm\".\n  iDestruct (post_crash_nodep with \"Hasync_ctx\") as \"Hasync_ctx\".\n  iCrash. rewrite /is_txn_durable. iFrame.\nQed.\n\nLemma is_source_into_crash P P' γsrc:\n  (∀ σ, P σ -∗ post_crash (λ hG, P' hG σ)) -∗\n  is_source P γsrc -∗ post_crash (λ hG, is_source (P' hG) γsrc).\nProof.\n  iIntros \"HPwand Hsrc\".\n  iNamed \"Hsrc\".\n  iDestruct (post_crash_nodep with \"Hnooverflow\") as \"-#Hnooverflow'\".\n  iDestruct (post_crash_nodep with \"Hsrcheap\") as \"Hsrcheap\".\n  iDestruct (\"HPwand\" with \"[$]\") as \"HP\".\n  iCrash. iExists _. iFrame. eauto.\nQed.\n\nEnd stable.\n\nSection goose_lang.\nContext `{!heapGS Σ}.\nContext `{!simpleG Σ}.\nImplicit Types (stk:stuckness) (E: coPset).\n\nContext (P1 : SimpleNFS.State → iProp Σ).\nContext (P2 : SimpleNFS.State → iProp Σ).\n\nDefinition fs_kinds sz : gmap u64 bufDataKind :=\n  {[U64 513 := KindInode]} ∪\n  gset_to_gmap KindBlock (rangeSet 514 (sz - 514)).\n\nDefinition fs_dinit sz : gmap Z Block :=\n  gset_to_gmap block0 (list_to_set $ seqZ 513 (sz-513)).\n\nLemma dom_fs_dinit:\n  ∀ sz : Z,\n    513 + 1 + (32 - 2) ≤ sz\n    → dom (fs_dinit sz) = list_to_set (seqZ 513 (sz - 513)).\nProof.\n  intros sz Hsz.\n  rewrite /fs_dinit.\n  rewrite dom_gset_to_gmap.\n  auto with f_equal lia.\nQed.\n\nLemma dom_fs_kinds:\n  ∀ sz : Z,\n    513 + 1 + (32 - 2) ≤ sz\n    → dom (fs_kinds sz) = list_to_set (U64 <$> seqZ 513 (sz - 513)).\nProof.\n  intros sz Hsz.\n  rewrite /fs_kinds.\n  rewrite dom_union_L dom_singleton_L.\n  rewrite dom_gset_to_gmap.\n  rewrite /rangeSet.\n  replace (seqZ 513 (sz - 513)) with ([513] ++ seqZ 514 (sz - 514)); auto.\n  change ([513]) with (seqZ 513 1).\n  rewrite <- seqZ_app by lia.\n  auto with f_equal lia.\nQed.\n\nLemma gmap_uncurry_union K1 K2 `{Countable K1} `{Countable K2} A\n      (m1 m2: gmap K1 (gmap K2 A)) :\n  m1 ##ₘ m2 →\n  gmap_uncurry (m1 ∪ m2) = gmap_uncurry m1 ∪ gmap_uncurry m2.\nProof.\n  intros.\n  apply map_eq; intros.\n  rewrite lookup_union.\n  destruct i as [i1 i2].\n  rewrite !lookup_gmap_uncurry.\n  rewrite lookup_union.\n  destruct (m1 !! i1) eqn:?;\n           destruct (m2 !! i1) eqn:?;\n           simpl;\n    auto.\n  - apply map_disjoint_dom in H1.\n    apply elem_of_dom_2 in Heqo.\n    apply elem_of_dom_2 in Heqo0.\n    set_solver.\n  - destruct (g !! i2); simpl; auto.\n  - rewrite /union_with /=.\n    destruct (g !! i2); simpl; auto.\nQed.\n\nLemma gmap_uncurry_insert K1 K2 `{Countable K1} `{Countable K2} A\n      k (m11: gmap K2 A) (m2: gmap K1 (gmap K2 A)) :\n  m2 !! k = None →\n  gmap_uncurry (<[k := m11]> m2) = map_fold (λ i2 x, <[(k,i2):=x]>) (gmap_uncurry m2) m11.\nProof.\n  rewrite /gmap_uncurry => Hlookup.\n  simpl.\n\n  rewrite map_fold_insert_L //; last first.\n  intros.\nAbort.\n\nLemma zero_disk_to_inodes γ sz :\n  (513 + 1 + (32-2) ≤ sz < 2^49) →\n  ([∗ map] a ↦ o ∈ kind_heap0 (fs_kinds sz), durable_mapsto_own γ a o) -∗\n  ([∗ set] inum ∈ covered_inodes, is_inode_enc inum (U64 0) (U64 0) (durable_mapsto_own γ)) ∗\n  ([∗ list] _ ↦ a ∈ seqZ 513 (32-2), durable_mapsto_own γ (blk2addr (U64 a)) (existT _ (bufBlock block0)))\n.\nProof.\n  iIntros (Hsz) \"Hobjs\".\n  rewrite /fs_kinds.\n  rewrite /kind_heap0.\n\n  rewrite map_fmap_union.\n  rewrite gmap_uncurry_union.\n  2: {\n    admit.\n  }\n  rewrite map_fmap_singleton.\n  rewrite fmap_gset_to_gmap.\n  rewrite big_sepM_union.\n  2: {\n    admit.\n  }\n  iDestruct \"Hobjs\" as \"[Hinodes Hblocks]\".\n  rewrite /covered_inodes.\n  iSplitL \"Hinodes\".\n  - rewrite /is_inode_enc.\n    admit.\n  - admit.\nAbort.\n\n(* amazingly not in Coq 8.12 *)\nLemma repeat_app {A} n1 n2 (x:A) :\n  repeat x (n1+n2)%nat = repeat x n1 ++ repeat x n2.\nProof. induction n1; simpl; congruence. Qed.\n\n(* sz is the actual size of the disk *)\nLemma wpc_Mkfs d sz :\n  (513 + 1 + (32-2) ≤ sz < 2^49) →\n  {{{ 0 d↦∗ repeat block0 (Z.to_nat sz) ∗ P1 (gset_to_gmap [] (rangeSet 2 (NumInodes-2)))  }}}\n    Mkfs (disk_val d) @ ⊤\n  {{{ γtxn γsrc (txn:loc), RET #txn;\n      let logm0 := Build_async (kind_heap0 (fs_kinds sz)) [] in\n      is_txn_durable γtxn (fs_dinit sz) logm0 ∗\n      is_source P1 γsrc\n    }}}\n   {{{ True }}}.\nProof.\n  intros Hsz.\n  iIntros (Φ Φc) \"Hd HΦ\".\n  replace (Z.to_nat sz) with (513 + (Z.to_nat sz - 513))%nat by lia.\n  rewrite repeat_app disk_array_app.\n  iDestruct \"Hd\" as \"[Hlog Hd]\".\n  rewrite repeat_length.\n  change (0 + 513%nat) with 513.\n  replace (Z.to_nat sz - 513)%nat with (Z.to_nat $ sz - 513) by lia.\n  iMod (is_txn_durable_init (fs_dinit sz) (fs_kinds sz) _\n          with \"[$Hlog $Hd]\") as (γ Hkinds) \"(Htxn & #Hlb & Hmapstos)\".\n  { rewrite -> Z2Nat.id by word.\n    apply dom_fs_dinit; lia. }\n  { rewrite -> Z2Nat.id by word.\n    apply dom_fs_kinds; lia. }\n  { rewrite /block_bytes.\n    rewrite -> !Z2Nat.id by word.\n    lia. }\n  rewrite /Mkfs.\n  wpc_pures.\n  { crash_case; auto. }\n  iCache (Φc)%I with \"HΦ\".\n  { crash_case; auto. }\n  wpc_apply (wpc_MkLog (nroot.@\"simple\") with \"[$Htxn]\").\n  { solve_ndisj. }\n  { solve_ndisj. }\n  iSplit.\n  { iLeft in \"HΦ\".\n    iIntros \"H\".\n    iApply \"HΦ\"; auto. }\n  iNext.\n  iIntros (γ' txn_l) \"Hpost\".\n  iDestruct \"Hpost\" as \"(#Htxn & #Htxn_system & Hcfupd & Hcinv)\".\n  wpc_pures.\n  wpc_frame \"HΦ\".\n  wp_apply (wp_Op__Begin with \"[$Htxn $Htxn_system]\").\n  iIntros (γtxn l).\n  iIntros \"Hjrnl\".\n  wp_pures.\n  (* the interesting part, reasoning about [inodeInit]; will need to break apart\n     Hmapstos and turn it into a bunch of inodes in order to lift them *)\nAbort.\n\nLemma is_source_later_upd P P' γsrc:\n  (∀ σ, ▷ P σ -∗ |C={⊤ ∖ ↑N}=> ▷ P σ ∗ ▷ P' σ) -∗\n   ▷ is_source P γsrc -∗\n   |C={⊤}=> ▷ is_source P' γsrc.\nProof.\n  iIntros \"Hwand H\". iDestruct \"H\" as (?) \"(>?&>%&>#?&?)\".\n  iSpecialize (\"Hwand\" with \"[$]\").\n  iMod (cfupd_weaken_mask with \"Hwand\") as \"(HP1&HP2)\"; auto.\n  iModIntro.\n  iNext. iExists _. iFrame \"# ∗ %\".\nQed.\n\nLemma crash_upd_src γsrc γ' src:\n  dom src = covered_inodes →\n  (\"Hlmcrash\" ∷ ([∗ set] y ∈ covered_inodes, is_inode_stable γsrc γ' y) ∗\n  \"Hsrcheap\" ∷ map_ctx γsrc 1 src) ==∗\n  ∃ γsrc',\n  map_ctx γsrc 1 src ∗\n  map_ctx γsrc' 1 src ∗\n  [∗ set] y ∈ covered_inodes, is_inode_stable γsrc' γ' y.\nProof.\n  iIntros (Hdom) \"H\". iNamed \"H\".\n  iMod (map_init ∅) as (γsrc') \"H\".\n  iMod (map_alloc_many src with \"H\") as \"(Hctx&Hmapsto)\".\n  { intros. rewrite lookup_empty //=. }\n  rewrite right_id_L.\n  iModIntro. iExists γsrc'.\n  rewrite -Hdom -?big_sepM_dom.\n  iFrame \"Hctx\".\n  iCombine \"Hmapsto Hlmcrash\" as \"H\".\n  rewrite -big_sepM_sep.\n  iApply (big_sepM_mono_with_inv with \"Hsrcheap H\").\n  iIntros (k v Hlookup) \"(Hctx&src&Hstable)\".\n  iNamed \"Hstable\".\n  iDestruct (map_valid with \"[$] [$]\") as %Heq.\n  subst. iFrame. iExists _. iFrame. rewrite /named. iExactEq \"src\". f_equal. congruence.\nQed.\n\nDefinition fs_cfupd_cancel dinit P :=\n  ((|C={⊤}=>\n    ∃ γ γsrc logm',\n    is_txn_durable γ dinit logm' ∗\n    ▷ is_source P γsrc ∗\n    [∗ set] a ∈ covered_inodes, is_inode_stable γsrc γ a))%I.\n\nTheorem wpc_Recover γ γsrc d dinit logm :\n  {{{\n    (∀ σ, ▷ P1 σ -∗ |C={⊤ ∖ ↑N}=> ▷ P1 σ ∗ ▷ P2 σ) ∗\n    is_txn_durable γ dinit logm ∗\n    ▷ is_source P1 γsrc ∗\n    [∗ set] a ∈ covered_inodes, is_inode_stable γsrc γ a\n  }}}\n    Recover (disk_val d) @ ⊤\n  {{{ nfs, RET #nfs;\n      init_cancel (∃ γsimp, is_fs P1 γsimp nfs dinit) (fs_cfupd_cancel dinit P2)}}}\n  {{{\n    ∃ γ' γsrc' logm',\n    is_txn_durable γ' dinit logm' ∗\n    ▷ is_source P2 γsrc' ∗\n    [∗ set] a ∈ covered_inodes, is_inode_stable γsrc' γ' a\n  }}}.\nProof using All.\n  iIntros (Φ Φc) \"(Hshift & Htxndurable & Hsrc & Hstable) HΦ\".\n  rewrite /Recover.\n  iApply wpc_cfupd.\n  wpc_pures.\n  { iDestruct \"HΦ\" as \"[HΦc _]\".\n    iMod (is_source_later_upd P1 P2 with \"Hshift Hsrc\") as \"Hsrc\".\n    iModIntro. iApply \"HΦc\".\n    iExists _, _, _. iFrame. }\n\n  wpc_apply (wpc_MkLog Njrnl with \"Htxndurable\").\n  { solve_ndisj. }\n  { solve_ndisj. }\n\n\n  iSplit.\n  { iDestruct \"HΦ\" as \"[HΦc _]\". iIntros \"H\".\n    iDestruct \"H\" as (γ' logm') \"Htxndurable\".\n    iDestruct \"Htxndurable\" as \"(Hdurable&[%Heq|#Hexch])\".\n    { subst.\n      iMod (is_source_later_upd P1 P2 with \"[$] Hsrc\") as \"Hsrc\".\n      iModIntro. iApply \"HΦc\". iExists _, _, _.\n      iFrame. }\n    iMod (is_source_later_upd P1 P2 with \"[$] Hsrc\") as \"Hsrc\".\n    iIntros \"#HC\".\n    iAssert (|={⊤}=> [∗ set] a ∈ covered_inodes, is_inode_stable γsrc γ' a)%I with \"[Hstable]\" as \">Hcrash\".\n    {\n      iApply big_sepS_fupd.\n      iApply (big_sepS_wand with \"Hstable\").\n      iApply big_sepS_intro. iModIntro. iIntros (? Hin) \"H\".\n      iMod (is_inode_stable_crash with \"[$] [$] [$]\"); eauto.\n    }\n    iModIntro.\n    iApply \"HΦc\".\n    iExists _, _, _. iFrame.\n\n  }\n\n  iModIntro.\n  iIntros (γ' l) \"(#Histxn & #Htxnsys & Hcfupdcancel & #Htxncrash)\".\n  iCache (|C={⊤}=> Φc)%I with \"Hshift Hsrc Hstable Hcfupdcancel HΦ\".\n  { iDestruct \"HΦ\" as \"[HΦc _]\". iIntros \"#HC\".\n    iAssert (|={⊤}=> [∗ set] a ∈ covered_inodes, is_inode_stable γsrc γ' a)%I with \"[Hstable]\" as \">Hcrash\".\n    {\n      iApply big_sepS_fupd.\n      iApply (big_sepS_wand with \"Hstable\").\n      iApply big_sepS_intro. iModIntro. iIntros (? Hin) \"H\".\n      iMod (is_inode_stable_crash with \"[$] [$] [$]\"); eauto.\n    }\n    rewrite /txn_cfupd_cancel.\n    iMod (is_source_later_upd P1 P2 with \"[$] Hsrc [$]\") as \"Hsrc\".\n    rewrite own_discrete_elim.\n    iMod (\"Hcfupdcancel\" with \"[$]\") as \">Hcfupdcancel\".\n    iModIntro.\n    iApply \"HΦc\".\n    iDestruct \"Hcfupdcancel\" as (?) \"H\".\n    iExists _, _, _. iFrame.\n  }\n\n  wpc_frame.\n  wp_pures.\n  (*\n\n  wpc_pures.\n  { iDestruct \"HΦ\" as \"[HΦc _]\". iIntros \"#HC\".\n    iAssert (|={⊤}=> [∗ set] a ∈ covered_inodes, is_inode_stable γsrc γ' a)%I with \"[Hstable]\" as \">Hcrash\".\n    {\n      iApply big_sepS_fupd.\n      iApply (big_sepS_wand with \"Hstable\").\n      iApply big_sepS_intro. iModIntro. iIntros (? Hin) \"H\".\n      unshelve (iMod (is_inode_stable_crash with \"[$] [$] [$]\"); eauto).\n      { exact O. (* This will go away when we remove the useless k parameter *)  }\n    }\n    rewrite /txn_cfupd_cancel.\n    iMod (is_source_later_upd P1 P2 with \"[$] Hsrc [$]\") as \"Hsrc\".\n    rewrite own_discrete_elim.\n    iMod (\"Hcfupdcancel\" with \"[$]\") as \">Hcfupdcancel\".\n    iModIntro.\n    iApply \"HΦc\".\n    iDestruct \"Hcfupdcancel\" as (?) \"H\".\n    iExists _, _, _. iFrame.\n  }\n   *)\n\n  wp_apply (wp_MkLockMap).\n  iIntros (lm) \"Hfree\".\n\n  (*\n  iMod (inv_alloc N with \"Hsrc\") as \"#Hsrc\".\n   *)\n\n  (*\n  iApply wp_wpc_frame'.\n  iSplitL \"Hlmcrash Hcfupdcancel HΦ Hsrc Hshift\".\n  {\n    iAssert (fs_cfupd_cancel dinit P2)%I with \"[-HΦ]\" as \"Hcancel\".\n    { iModIntro.\n      rewrite -big_sepS_later.\n      iMod \"Hlmcrash\" as \">Hlmcrash\". iMod \"Hcfupdcancel\" as \">Hcfupdcancel\".\n      iIntros \"#HC\".\n      iInv \"Hsrc\" as \"Hopen\" \"Hclose\".\n      iDestruct \"Hopen\" as (?) \"(>Hsrcheap&>%Hdom&>#Hnooverflow&HP)\".\n      iMod (crash_upd_src with \"[$]\") as (γsrc') \"(Hsrcheap&Hsrcheap'&Hlmcrash)\".\n      { eauto. }\n      iMod (\"Hshift\" with \"HP HC\") as \"(HP1&HP2)\".\n      iMod (\"Hclose\" with \"[HP1 Hsrcheap]\") as \"_\".\n      { iNext. iExists _. iFrame \"# ∗ %\". }\n      iDestruct \"Hcfupdcancel\" as (?) \"?\".\n      iExists γ', γsrc', _. iFrame.\n      iModIntro. iNext. iExists _. iFrame \"# ∗ %\".\n    }\n    iSplit.\n    { iDestruct \"HΦ\" as \"[HΦc _]\". iModIntro. iMod (\"Hcancel\"). iModIntro. by iApply \"HΦc\". }\n    { iNamedAccu. }\n  }\n\n   *)\n  wp_apply wp_allocStruct; first val_ty.\n  iIntros (nfs) \"Hnfs\".\n\n  iDestruct (struct_fields_split with \"Hnfs\") as \"Hnfs\". iNamed \"Hnfs\".\n  iMod (readonly_alloc_1 with \"t\") as \"#Ht\".\n  iMod (readonly_alloc_1 with \"l\") as \"#Hl\".\n\n  (*\n  iAssert (is_fs P1 (Build_simple_names γ γ' γsrc ghs) nfs dinit) with \"[]\" as \"Hfs\".\n  { iExists _, _. iFrame \"Ht Hl Histxn Htxnsys Htxncrash Hlm Hsrc\". }\n   *)\n  wp_pures. iModIntro. iNamed 1.\n  iRight in \"HΦ\". iApply \"HΦ\".\n  iApply fupd_init_cancel.\n  iMod (inv_alloc N with \"Hsrc\") as \"#Hsrc\".\n  rewrite /txn_cfupd_cancel.\n  iDestruct (alloc_lockMap_init_cancel covered_inodes lm\n                                       (is_inode_stable γsrc γ)\n                                       (λ a, C -∗ |={⊤}=> is_inode_stable γsrc γ' a)%I\n               with \"[Hstable] [$]\") as \"Hcancel\".\n  {\n    iApply (big_sepS_wand with \"Hstable\").\n    iApply big_sepS_intro. iModIntro. iIntros (? Hin) \"H\".\n    iFrame. iModIntro. iIntros \"Hstable\".\n    iMod (is_inode_stable_crash with \"[$] [$]\"); eauto.\n  }\n  iApply (init_cancel_wand with \"Hcancel [] [Hcfupdcancel Hshift]\").\n  {\n    iDestruct 1 as (ghs) \"Hlm\".\n    iExists (Build_simple_names γ γ' γsrc ghs).\n    { iExists _, _. iFrame \"Ht Hl Histxn Htxnsys Htxncrash Hsrc\". eauto. }\n  }\n\n  iIntros \"H\".\n  rewrite /fs_cfupd_cancel.\n  iAssert (|C={⊤}=> [∗ set] a ∈ covered_inodes, is_inode_stable γsrc γ' a)%I\n    with \"[H]\" as \">H\".\n  { iIntros \"#HC\". iApply big_sepS_fupd.\n    iApply (big_sepS_wand with \"H\"). iApply big_sepS_intro.\n    iModIntro. iIntros (??) \"H\". iMod (\"H\" with \"[$]\") as \"$\". eauto. }\n  iEval (rewrite own_discrete_elim) in \"Hcfupdcancel\".\n  iMod (\"Hcfupdcancel\") as \"Hcfupdcancel\".\n  iIntros \"HC\". iDestruct \"Hcfupdcancel\" as \">Hcfupdcancel\".\n  iInv \"Hsrc\" as \"Hopen\" \"Hclose\".\n  iDestruct \"Hopen\" as (?) \"(>Hsrcheap&>%Hdom&>#Hnooverflow&HP)\".\n  iMod (crash_upd_src with \"[$]\") as (γsrc') \"(Hsrcheap&Hsrcheap'&Hlmcrash)\".\n  { eauto. }\n  iMod (\"Hshift\" with \"HP HC\") as \"(HP1&HP2)\".\n  iMod (\"Hclose\" with \"[HP1 Hsrcheap]\") as \"_\".\n  { iNext. iExists _. iFrame \"# ∗ %\". }\n  iDestruct \"Hcfupdcancel\" as (?) \"?\".\n  iExists γ', γsrc', _. iFrame.\n  iModIntro. iNext. iExists _. iFrame \"# ∗ %\".\nQed.\n\nEnd goose_lang.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/simple/recovery.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23215506384291743}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp\nRequire Import path.\nRequire Import Eqdep.\nRequire Import Relation_Operators.\nFrom fcsl\nRequire Import axioms pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL\nRequire Import Freshness State EqTypeX Protocols Worlds NetworkSem Rely.\nFrom DiSeL\nRequire Import Actions Injection Process Always HoareTriples InferenceRules.\nFrom DiSeL\nRequire Import InductiveInv StatePredicates.\nFrom DiSeL\nRequire Import CalculatorProtocol.\n\nSection CalculatorInductiveInv.\n\nVariable l : Label.\n\nVariable f : input -> option nat.\nVariable prec : input -> bool.\nHypothesis prec_valid :\n  forall i, prec i -> exists v, f i = Some v.\n\nVariable cs: seq nid.\nVariable cls : seq nid.\n(* All nodes *)\nNotation nodes := (cs ++ cls).\n(* All nodes are unique *)\nHypothesis Huniq : uniq nodes.\n\n(* Protocol and its transitions *)\nNotation cal := (CalculatorProtocol f prec cs cls l).\nNotation sts := (snd_trans cal).\nNotation rts := (rcv_trans cal).\n\nDefinition reqs := cstate.\nNotation coh := (coh cal).\n\nNotation loc n d := (getLocal n d).\n\nLemma nodes_falso z : z \\in cs -> z \\in cls -> False.\nProof.\nmove=>H1 H2.\nmove: (Huniq); rewrite cat_uniq=>/andP[_]/andP[/negP H]_.\nby apply: H; apply/hasP; exists z.\nQed.\n\nDefinition CalcInv d :=\n  forall (C: coh d) n to v args i s',\n    n \\in cls -> to \\in cs -> \n    dsoup d = i \\\\-> (Msg (TMsg resp (v::args)) to n true) \\+ s' ->\n    f args = Some v.\n\nNotation cal' := (CalculatorProtocol f prec cs cls l).\nNotation coh' := (coh cal).\nNotation Sinv := (@S_inv cal (fun d _ => CalcInv d)).\nNotation Rinv := (@R_inv cal (fun d _ => CalcInv d)).\nNotation PI := pf_irr.\n\nProgram Definition s1: Sinv (server_send_trans f prec cs cls).\nProof.\nmove=>this to d msg S b.\nmove=>/= Hi E G C' n to' v' args' i s1 N1 N2/= Es.\ncase: (S)=>_[_][C]/hasP[[[me cc]args]]_.\ncase/andP=>/eqP Z1/andP[/eqP Y]/eqP Z2. \nmove: (cohVs C')=>V; rewrite joinC/= in Es V.\nmove: (cancel2 V Es)=>/=; case: ifP.\n- move=>_; case. case=>Z3 Z4 Z5 Z6; subst s1 to to' msg.\n  by simpl in Y; case: Z2=>->.\nmove=>_[E1]/=E2 E3; subst to. clear Es V.\nby apply: (Hi C n to' v' args' i _ _ _ E2).\nQed.\n\n\nProgram Definition s2: Sinv (client_send_trans prec cs cls).\nProof.\nmove=>this to d msg S b.\nmove=>/= Hi E G C' n to' v' args' i s1 N1 N2/= Es.\nmove: (cohVs C')=>V; rewrite joinC/= in Es V.\nmove: (cancel2 V Es)=>/=; case: ifP; last first.\n- move=>_[E1]/=E2 E3; clear Es V.\n  by case: (S)=>_[_]C _; apply: (Hi C n to' v' args' i _ _ _ E2).\nmove/eqP=>Z; subst i; by case; discriminate.\nQed.\n\nProgram Definition r1: Rinv (server_recv_trans prec cs cls).\nProof.\nmove=>d from this i C m pf Hi F D Hw Et _.\nmove=> C' n to v args i' s1 N1 N2/=Es.\nsuff Es' : exists s', dsoup d =\n       i' \\\\-> {| content := {| tag := resp; tms_cont := v :: args |};\n                  from := to;  to := n;\n                  active := true |} \\+ s'.\nby case: Es'=>s' Es'; apply: (Hi C n to v args i' _ N1 N2 Es').\ncase B: (i \\in dom (dsoup d)); last first.\nby move: dom_find B Es; rewrite /consume_msg; case=>//->_->; exists s1.\nmove/um_eta: B=>[vm][_]S1.\nmove: (cohVs C)=>V; rewrite S1 in V.\nrewrite S1 joinC consumeUn ?eqxx joinC// in Es. \nsuff V': valid (i \\\\-> mark_msg vm \\+\n                free (cT:=union_mapUMC mid (msg TaggedMessage)) i (dsoup d)).\n- move: (cancel2 V' Es); case: ifP=>B.\n  - move/eqP:B=>B{S1 V V' Es}; subst i'.\n    by case: vm=>????/=; rewrite /mark_msg/=; case; discriminate.\n  by case=>_ X2 _; rewrite X2 joinCA in S1; rewrite S1; eexists _. \nmove: (consume_valid i V).\nrewrite /consume_msg/= findUnL// ?domPt inE/= eqxx findPt/=. \nby rewrite updUnL/= domPt/=!inE eqxx !updPt/=.\nQed.\n\nProgram Definition r2: Rinv (client_recv_trans prec cs cls).\nProof.\nmove=>d from this i C m pf Hi F D Hw Et _.\nmove=> C' n to v args i' s1 N1 N2/=Es.\nsuff Es' : exists s', dsoup d =\n       i' \\\\-> {| content := {| tag := resp; tms_cont := v :: args |};\n                  from := to;  to := n;\n                  active := true |} \\+ s'.\nby case: Es'=>s' Es'; apply: (Hi C n to v args i' _ N1 N2 Es').\ncase B: (i \\in dom (dsoup d)); last first.\nby move: dom_find B Es; rewrite /consume_msg; case=>//->_->; exists s1.\nmove/um_eta: B=>[vm][_]S1.\nmove: (cohVs C)=>V; rewrite S1 in V.\nrewrite S1 joinC consumeUn ?eqxx joinC// in Es. \nsuff V': valid (i \\\\-> mark_msg vm \\+\n                free (cT:=union_mapUMC mid (msg TaggedMessage)) i (dsoup d)).\n- move: (cancel2 V' Es); case: ifP=>B.\n  - move/eqP:B=>B{S1 V V' Es}; subst i'.\n    by case: vm=>????/=; rewrite /mark_msg/=; case; discriminate.\n  by case=>_ X2 _; rewrite X2 joinCA in S1; rewrite S1; eexists _. \nmove: (consume_valid i V).\nrewrite /consume_msg/= findUnL// ?domPt inE/= eqxx findPt/=. \nby rewrite updUnL/= domPt/=!inE eqxx !updPt/=.\nQed.\n\nDefinition sts' := [:: SI s1; SI s2].\nDefinition rts' := [:: RI r1; RI r2].\n\nProgram Definition ii := @ProtocolWithInvariant.II _ _ sts' rts' _ _.\n\nDefinition cal_with_inv := ProtocolWithIndInv ii.\n\n(**************************************************)\n(*\nOverall Implementation effort:\n\n1 person-day\n\n*)\n(**************************************************)\n\n        \n\nEnd CalculatorInductiveInv.\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/disel/Examples/Calculator/CalculatorInvariant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23215506384291743}}
{"text": "Set Implicit Arguments.\n\nRequire Import RandomQC.\nRequire Import Coq.Strings.String.\n\nRequire Import StringOT.\nRequire Import FSets.FMapAVL.\n\nModule Map := FMapAVL.Make(StringOT).\n\nRecord State := MkState\n  { maxSuccessTests   : nat\n  ; maxDiscardedTests : nat\n  ; maxShrinkNo       : nat\n  ; computeSize       : nat -> nat -> nat\n\n  ; numSuccessTests   : nat\n  ; numDiscardedTests : nat\n\n  ; labels            : Map.t nat\n\n  ; expectedFailure   : bool\n  ; randomSeed        : RandomSeed\n\n  ; numSuccessShrinks : nat\n  ; numTryShrinks     : nat\n  ; stDoAnalysis      : bool\n  }.\n\nDefinition updTryShrinks (st : State) (f : nat -> nat) : State :=\n  match st with\n    | MkState mst mdt ms cs nst ndt ls e r nss nts ana =>\n      MkState mst mdt ms cs nst ndt ls e r nss (f nts) ana\n  end.\n\nDefinition updSuccessShrinks (st : State) (f : nat -> nat) : State :=\n  match st with\n    | MkState mst mdt ms cs nst ndt ls e r nss nts ana =>\n      MkState mst mdt ms cs nst ndt ls e r (f nss) nts ana\n  end.\n\nDefinition updSuccTests st f :=\n  match st with\n    | MkState mst mdt ms cs nst     ndt ls e r nss nts ana =>\n      MkState mst mdt ms cs (f nst) ndt ls e r nss nts ana\n  end.\n\nDefinition updDiscTests st f :=\n  match st with\n    | MkState mst mdt ms cs nst ndt     ls e r nss nts ana =>\n      MkState mst mdt ms cs nst (f ndt) ls e r nss nts ana\n  end.\n", "meta": {"author": "QuickChick", "repo": "QuickChick", "sha": "ca56cc21ecc76bc0e1443e917ce26c010980ae2f", "save_path": "github-repos/coq/QuickChick-QuickChick", "path": "github-repos/coq/QuickChick-QuickChick/QuickChick-ca56cc21ecc76bc0e1443e917ce26c010980ae2f/src/State.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2321394484026449}}
{"text": "(** * Data types for the crowdfunding contract *)\n\nRequire Import String ZArith Basics.\nFrom ConCert.Embedding Require Import Ast Notations PCUICTranslate Utils.\nFrom ConCert.Embedding.Examples Require Import Prelude SimpleBlockchain.\nRequire Import List PeanoNat ssrbool.\n\nImport ListNotations.\nFrom MetaCoq.Template Require Import All.\n\nImport MonadNotation.\nImport BaseTypes.\nOpen Scope list.\n\n\nImport AcornBlockchain.\n\n(** Note that we define the deep embedding (abstract syntax trees) of the data structures and programs using notations. These notations are defined in  [Ast.v] and make use of the \"custom entries\" feature. *)\n\n(** Brackets like [[\\ \\]] delimit the scope of data type definitions and like [[| |]] the scope of programs *)\n\n(** Generating names for the data structures  *)\nRun TemplateProgram\n      (mkNames [\"State\" ; \"mkState\"; \"balance\" ; \"donations\" ; \"owner\"; \"deadline\"; \"goal\"; \"done\";\n                \"Res\" ; \"Error\";\n                \"Msg\"; \"Donate\"; \"GetFunds\"; \"Claim\";\n                \"Action\"; \"Transfer\"; \"Empty\" ] \"_coq\").\n\nImport ListNotations.\n\n(** ** Definitions of data structures for the contract *)\n\n(** The internal state of the contract *)\nDefinition state_syn : global_dec :=\n  [\\ record State :=\n     mkState { balance : Money ;\n       donations : Map;\n       owner : Address;\n       deadline : Nat;\n       done : Bool;\n       goal : Money } \\].\n\n(** We can print actual AST by switching off the notations *)\n\nUnset Printing Notations.\n\nPrint state_syn.\n(* state_syn =\n    gdInd State O\n      (cons\n         (rec_constr State\n            (cons (pair (nNamed balance) (tyInd Money))\n               (cons (pair (nNamed donations) (tyInd Map))\n                  (cons (pair (nNamed owner) (tyInd Money))\n                     (cons (pair (nNamed deadline) (tyInd Nat))\n                        (cons (pair (nNamed goal) (tyInd Money)) nil)))))) nil) true\n         : global_dec *)\n\nSet Printing Notations.\n\n(** Unquoting the definition of a record *)\nSet Nonrecursive Elimination Schemes.\nMake Inductive (global_to_tc state_syn).\n\n(** As a result, we get a new Coq record [State_coq] *)\nPrint State_coq.\n\nDefinition msg_syn :=\n  [\\ data Msg =\n       Donate [_]\n     | GetFunds [_]\n     | Claim [_] \\].\n\nMake Inductive (global_to_tc msg_syn).\n\n(** Custom notations for patterns, projections and constructors *)\nModule Notations.\n\n  Notation \"'ctx_from' a\" := [| {eConst \"Ctx_from\"} {a} |]\n                             (in custom expr at level 0).\n  Notation \"'ctx_contract_address' a\" :=\n    [| {eConst \"Ctx_contract_address\"} {a} |]\n      (in custom expr at level 0).\n  Notation \"'amount' a\" := [| {eConst \"Ctx_amount\"} {a} |]\n                             (in custom expr at level 0).\n\n\n  (** Projections *)\n  Notation \"'balance' a\" :=\n    [| {eConst balance} {a} |]\n      (in custom expr at level 0).\n  Notation \"'donations' a\" :=\n    [| {eConst donations} {a} |]\n      (in custom expr at level 0).\n  Notation \"'owner' a\" :=\n    [| {eConst owner} {a} |]\n      (in custom expr at level 0).\n  Notation \"'deadline' a\" :=\n    [| {eConst deadline} {a} |]\n      (in custom expr at level 0).\n  Notation \"'goal' a\" :=\n    [| {eConst goal} {a} |]\n      (in custom expr at level 0).\n  Notation \"'done' a\" :=\n    [| {eConst done} {a} |]\n      (in custom expr at level 0).\n\n\n  Notation \"'Nil'\" := [| {eConstr \"list\" \"nil\"} {eTy (tyInd SActionBody)} |]\n                      (in custom expr at level 0).\n\n  Notation \" x ::: xs\" := [| {eConstr \"list\" \"cons\"} {eTy (tyInd SActionBody)} {x} {xs} |]\n                            ( in custom expr at level 0).\n\n  Notation \"[ x ]\" := [| {eConstr \"list\" \"cons\"} {eTy (tyInd SActionBody)} {x} Nil |]\n                        ( in custom expr at level 0,\n                          x custom expr at level 1).\n  (** Constructors. [Res] is an abbreviation for [Some (st, [action]) : option (State * list ActionBody)] *)\n\n\n\n  Definition actions_ty := [! \"list\" \"SimpleActionBody\" !].\n\n  Notation \"'Result'\" := [!\"prod\" State (\"list\" \"SimpleActionBody\") !]\n                           (in custom type at level 2).\n\n\n  Definition mk_res a b := [| {eConstr \"option\" \"Some\"}\n                                {eTy [! Result !]}\n                                 ({eConstr \"prod\" \"pair\"} {eTy (tyInd State)}\n                                 {eTy actions_ty} {a} {b}) |].\n  Notation \"'Res' a b\" := (mk_res a b)\n      (in custom expr at level 2,\n          a custom expr at level 4,\n          b custom expr at level 4).\n\n  Notation \"'mkState' a b\" :=\n    [| {eConstr State \"mkState_coq\"} {a} {b} |]\n      (in custom expr at level 0,\n          a custom expr at level 1,\n          b custom expr at level 1).\n\n  Notation \"'Transfer' a b\" :=\n    [| {eConstr SActionBody \"Act_transfer\"} {b} {a} |]\n      (in custom expr at level 0,\n          a custom expr at level 1,\n          b custom expr at level 1).\n\n  Notation \"'Empty'\" := (eConstr Action Empty)\n                      (in custom expr at level 0).\n\n  (** New global context with the constants defined above (in addition to the ones defined in the Oak's \"StdLib\") *)\n\n  Definition Σ' :=\n    Prelude.Σ ++ [ Prelude.AcornMaybe;\n           state_syn;\n           msg_syn;\n           addr_map_acorn;\n           AcornBlockchain.SimpleChainAcorn;\n           AcornBlockchain.SimpleContractCallContextAcorn;\n           AcornBlockchain.SimpleActionBodyAcorn;\n           gdInd \"Z\" 0 [(\"Z0\", []); (\"Zpos\", [(None,tyInd \"positive\")]);\n                          (\"Zneg\", [(None,tyInd \"positive\")])] false].\n\n\n  Notation \"0 'z'\" := (eConstr \"Z\" \"Z0\") (in custom expr at level 0).\n  End Notations.\n\n\nImport Prelude.\n(** Generating string constants for variable names *)\n\nRun TemplateProgram (mkNames [\"c\";\"s\";\"e\";\"m\";\"v\";\"dl\"; \"g\"; \"chain\";\n                              \"tx_amount\"; \"bal\"; \"sender\"; \"own\"; \"isdone\" ;\n                              \"accs\"; \"now\";\n                               \"newstate\"; \"newmap\"; \"cond\"] \"\").\n(** A shortcut for [if .. then .. else ..]  *)\nNotation \"'if' cond 'then' b1 'else' b2 : ty\" :=\n  (eCase (Bool,[]) ty cond\n         [(pConstr true_name [],b1);(pConstr false_name [],b2)])\n    (in custom expr at level 4,\n        cond custom expr at level 4,\n        ty custom type at level 4,\n        b1 custom expr at level 4,\n        b2 custom expr at level 4).\n\nNotation SCtx := \"SimpleContractCallContext\".\n", "meta": {"author": "malthelange", "repo": "CLVM", "sha": "e80aef02c3112b5b62db79bc2b233020367b0bde", "save_path": "github-repos/coq/malthelange-CLVM", "path": "github-repos/coq/malthelange-CLVM/CLVM-e80aef02c3112b5b62db79bc2b233020367b0bde/embedding/examples/crowdfunding/CrowdfundingData.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2321394484026449}}
{"text": "(** Heavily annotated for a tutorial introduction. *)\n\n(** First, import the entire Floyd proof automation system, which includes\n ** the VeriC program logic and the MSL theory of separation logic**)\nRequire Import VST.floyd.proofauto.\n\n(** Import the [reverse.v] file, which is produced by CompCert's clightgen\n ** from reverse.c.   The file reverse.v defines abbreviations for identifiers\n ** (variable names, etc.) of the C program, such as _head, _reverse.\n ** It also defines \"prog\", which is the entire abstract syntax tree\n ** of the C program *)\nRequire Import VST.progs.reverse.\n\n(* The C programming language has a special namespace for struct\n** and union identifiers, e.g., \"struct foo {...}\".  Some type-based operators\n** in the program logic need access to an interpretation of this namespace,\n** i.e., the meaning of each struct-identifier such as \"foo\".  The next\n** line (which looks identical for any program) builds this\n** interpretation, called \"CompSpecs\" *)\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\n\n(** Calculate the \"types-of-global-variables\" specification\n ** directly from the program *)\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n(** A convenience definition *)\nDefinition t_struct_list := Tstruct _list noattr.\n\n(** Inductive definition of linked lists *)\nFixpoint listrep (sigma: list val) (x: val) : mpred :=\n match sigma with\n | h::hs => \n    EX y:val, \n      data_at Tsh t_struct_list (h,y) x  *  listrep hs y\n | nil => \n    !! (x = nullval) && emp\n end.\n\nArguments listrep sigma x : simpl never.\n\n(** Whenever you define a new spatial operator, such as\n ** [listrep] here, it's useful to populate two hint databases.\n ** The [saturate_local] hint is a lemma that extracts\n ** pure propositional facts from a spatial fact.\n ** The [valid_pointer] hint is a lemma that extracts a\n ** valid-pointer fact from a spatial lemma.\n **)\n\nLemma listrep_local_facts:\n  forall sigma p,\n   listrep sigma p |--\n   !! (is_pointer_or_null p /\\ (p=nullval <-> sigma=nil)).\nProof.\nintros.\nrevert p; induction sigma; \n  unfold listrep; fold listrep; intros; normalize.\napply prop_right; split; simpl; auto. intuition.\nentailer!.\nsplit; intro. subst p. destruct H; contradiction. inv H2.\nQed.\n\nHint Resolve listrep_local_facts : saturate_local.\n\nLemma listrep_valid_pointer:\n  forall sigma p,\n   listrep sigma p |-- valid_pointer p.\nProof.\n destruct sigma; unfold listrep; fold listrep;\n intros; normalize.\n auto with valid_pointer.\n apply sepcon_valid_pointer1.\n apply data_at_valid_ptr; auto.\n simpl;  computable.\nQed.\n\nHint Resolve listrep_valid_pointer : valid_pointer.\n\n(** Specification of the [reverse] function.  It characterizes\n ** the precondition required for calling the function,\n ** and the postcondition guaranteed by the function.\n **)\nDefinition reverse_spec :=\n DECLARE _reverse\n  WITH sigma : list val, p: val\n  PRE  [ _p OF (tptr t_struct_list) ]\n     PROP ()\n     LOCAL (temp _p p)\n     SEP (listrep sigma p)\n  POST [ (tptr t_struct_list) ]\n    EX q:val,\n     PROP () LOCAL (temp ret_temp q)\n     SEP (listrep(rev sigma) q).\n\n(** The global function spec, characterizing the\n ** preconditions/postconditions of all the functions\n ** that your proved-correct program will call. \n ** Normally you include all the functions here, but\n ** in this tutorial example we include only one. *)\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ reverse_spec ]).\n\n(** For each function definition in the C program, prove that the\n ** function-body (in this case, f_reverse) satisfies its specification\n ** (in this case, reverse_spec).\n **)\nLemma body_reverse: semax_body Vprog Gprog\n                                    f_reverse reverse_spec.\nProof.\n(** The start_function tactic \"opens up\" a semax_body\n ** proof goal into a Hoare triple. *)\nstart_function.\n(** For each assignment statement, \"symbolically execute\" it\n ** using the forward tactic *)\nforward.  (* w = NULL; *)\nforward.  (* v = p; *)\n(** To prove a while-loop, you must supply a loop invariant,\n ** in this case (EX s1  PROP(...)LOCAL(...)(SEP(...)).  *)\nforward_while\n   (EX s1: list val, EX s2 : list val, \n    EX w: val, EX v: val,\n     PROP (sigma = rev s1 ++ s2)\n     LOCAL (temp _w w; temp _v v)\n     SEP (listrep s1 w; listrep s2 v)).\n(** The forward_while tactic leaves four subgoals,\n ** which we mark with * (the Coq \"bullet\") *)\n* (* Prove that precondition implies loop invariant *)\nExists (@nil val) sigma nullval p.\nentailer!.\nunfold listrep.\nentailer!.\n* (* Prove that loop invariant implies typechecking of loop condition *)\nentailer!.\n* (* Prove that loop body preserves invariant *)\ndestruct s2 as [ | h r].\n - unfold listrep at 2. \n   Intros. subst. contradiction.\n - unfold listrep at 2; fold listrep.\n   Intros y.\n   forward. (* t = v->tail *)\n   forward. (* v->tail = w; *)\n   forward. (* w = v; *)\n   forward. (* v = t; *)\n   (* At end of loop body; reestablish invariant *)\n   entailer!.\n   Exists (h::s1,r,v,y).\n   entailer!.\n   + simpl. rewrite app_ass. auto.\n   + unfold listrep at 3; fold listrep.\n     Exists w. entailer!.\n* (* after the loop *)\nforward.  (* return w; *)\nExists w; entailer!.\nrewrite (proj1 H1) by auto.\nunfold listrep at 2; fold listrep.\nentailer!.\nrewrite <- app_nil_end, rev_involutive.\nauto.\nQed.\n\n(** See the file [progs/verif_reverse.v] for an alternate\n ** proof of this function, using a general theory of\n ** list segments.  That file also has proofs of the\n ** sumlist function, the main function, and the\n ** [semax_func] theorem that ties all the functions together\n **)\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/progs/verif_reverse2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.23213944840264486}}
{"text": "Require Import Raft.\nRequire Import CommonDefinitions.\nRequire Import TraceUtil.\n\nSection AppliedImpliesInputInterface.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Section inner.\n    Variables client id : nat.\n    Variable i : input.\n\n    Definition correct_entry (e : entry) : Prop :=\n      eClient e = client /\\\n      eId e = id /\\\n      eInput e = i.\n\n    Definition applied_implies_input_state (net : network) : Prop :=\n      exists e,\n        correct_entry e /\\\n        ((exists h, In e (log (nwState net h))) \\/\n         (exists p entries, In p (nwPackets net) /\\\n                            mEntries (pBody p) = Some entries /\\\n                            In e entries)).\n\n  End inner.\n\n  Class applied_implies_input_interface : Prop :=\n    {\n      applied_implies_input :\n        forall client id failed net tr e,\n          step_f_star step_f_init (failed, net) tr ->\n          eClient e = client ->\n          eId e = id ->\n          applied_implies_input_state client id (eInput e) net ->\n          in_input_trace client id (eInput e) tr\n    }.\nEnd AppliedImpliesInputInterface.", "meta": {"author": "ahmet-celik", "repo": "pverdi", "sha": "dc88c4a5fd7d90b5bb48e583bd8286097f983f81", "save_path": "github-repos/coq/ahmet-celik-pverdi", "path": "github-repos/coq/ahmet-celik-pverdi/pverdi-dc88c4a5fd7d90b5bb48e583bd8286097f983f81/raft/AppliedImpliesInputInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23212002397699097}}
{"text": "(**\n\nThis file describes the syntax of an imperative lambda calculus with \npointers, structs and arrays.\n\nAuthor: Ramon Fernandez I Mir and Arthur Charguéraud.\n\nLicense: MIT.\n\n*)\n\n\nSet Implicit Arguments.\nRequire Export Bind TLCbuffer.\nRequire Export LibString LibCore LibLogic LibReflect\n  LibOption LibRelation LibLogic LibOperation LibEpsilon\n  LibMonoid LibSet LibContainer LibListZ LibMap.\n\nOpen Scope set_scope.\nOpen Scope container_scope.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Representation of locations and fields *)\n\n(** [loc] describes base pointers to an allocated block. *)\n\nDefinition loc := int.\nDefinition null : loc := 0%Z.\n\n(** A struct is a map from [field]s. *)\n\nDefinition field := var.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Representation of low-level memory constructs  *)\n\n(** We need [size]s for low-level memory accesses and also for arrays.  *)\n\nDefinition size := int.\n\n(** Low-level pointers use [offset]s. *)\n\nDefinition offset := int.\n\n(** A [word] is the basic memory unit. *)\n\nInductive word : Type :=\n  | word_undef : word\n  | word_int : int -> word.\n\nDefinition words := list word.\n\n(** Bijection between high-level and low-level memory locations. *)\n\nDefinition alpha := map loc loc.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Grammar of types *)\n\nDefinition typvar := var.\n\nInductive typ : Type :=\n  | typ_unit : typ\n  | typ_int : typ\n  | typ_double : typ\n  | typ_bool : typ\n  | typ_ptr : typ -> typ\n  | typ_array : typ -> option size -> typ\n  | typ_struct : map field typ -> typ\n  | typ_fun : list typ -> typ -> typ\n  | typ_var : typvar -> typ.\n\n(** Type of the state *)\n\nDefinition phi := map loc typ.\nDefinition empty_phi : phi := empty.\n\n(** Type of a stack *)\n\nDefinition gamma := Ctx.ctx typ.\nDefinition empty_gamma : gamma := nil.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Contexts *)\n\n(** Type definitions context *)\n\nDefinition typdefctx := map typvar typ.\n\n(** Contex holding low-level information about structs and their fields. *)\n\nDefinition ll_typdefctx_typvar_sizes := map typvar size.\nDefinition ll_typdefctx_fields_offsets := map typvar (map field offset).\nDefinition ll_typdefctx_fields_order := map typvar (list field).\n\nRecord ll_typdefctx := make_ll_typdefctx {\n  typvar_sizes : ll_typdefctx_typvar_sizes;\n  fields_offsets : ll_typdefctx_fields_offsets;\n  fields_order : ll_typdefctx_fields_order }.\n\nNotation \"'make_ll_typdefctx''\" := make_ll_typdefctx.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Syntax of the source language *)\n\n(** High-level pointers are represented using [accesses]. *)\n\nInductive access : Type :=\n  | access_array : typ -> int -> access\n  | access_field : typ -> field -> access.\n\nDefinition accesses := list access.\n\n(** Values. *)\n\nInductive val : Type :=\n  | val_error : val\n  | val_unit : val\n  | val_uninitialized : val\n  | val_bool : bool -> val\n  | val_int : int -> val\n  | val_double : int -> val\n  | val_abstract_ptr : loc -> accesses -> val\n  | val_concrete_ptr : loc -> offset -> val\n  | val_array : typ -> list val -> val\n  | val_struct : typ -> map field val -> val\n  | val_words : list word -> val.\n\n(** Binary operations. *)\n\nInductive binop : Type :=\n  | binop_eq : binop\n  | binop_sub : binop\n  | binop_add : binop\n  | binop_mul : binop\n  | binop_div : binop\n  | binop_mod : binop\n  | binop_ptr_add : binop.\n\n(** Primitive functions. *)\n\nInductive prim : Type :=\n  | prim_binop : binop -> prim\n  | prim_get : typ -> prim\n  | prim_set : typ -> prim\n  | prim_new : typ -> prim\n  | prim_new_array : typ -> prim\n  | prim_struct_access : typ -> field -> prim\n  | prim_array_access : typ -> prim\n  | prim_struct_get : typ -> field -> prim\n  | prim_array_get : typ -> prim\n  | prim_ll_get : typ -> prim\n  | prim_ll_set : typ -> prim\n  | prim_ll_new : typ -> prim\n  | prim_ll_access : typ -> prim.\n\n(** Terms. *)\n\nInductive trm : Type :=\n  | trm_var : var -> trm\n  | trm_val : val -> trm\n  | trm_if : trm -> trm -> trm -> trm\n  | trm_let : bind -> trm -> trm -> trm\n  | trm_app : prim -> list trm -> trm\n  | trm_while : trm -> trm -> trm\n  | trm_for : var -> val -> val -> trm -> trm.\n\n(** Sequence is a special case of let bindings *)\n\nNotation trm_seq := (trm_let bind_anon).\n\n\n(* ---------------------------------------------------------------------- *)\n(** State and stack *)\n\n(** Representation of the state *)\n\nDefinition state := map loc val.\nDefinition empty_state : state := empty.\n\n(** Representation of the stack *)\n\nDefinition stack := Ctx.ctx val.\nDefinition empty_stack : stack := nil.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Inhabited words, values, types and terms *)\n\nGlobal Instance Inhab_word : Inhab word.\nProof using. apply (Inhab_of_val word_undef). Qed.\n\nGlobal Instance Inhab_val : Inhab val.\nProof using. apply (Inhab_of_val val_unit). Qed.\n\nGlobal Instance Inhab_trm : Inhab trm.\nProof using. apply (Inhab_of_val (trm_val val_unit)). Qed.\n\nGlobal Instance Inhab_typ : Inhab typ.\nProof using. apply (Inhab_of_val typ_unit). Qed.\n\nHint Extern 1 (Inhab word) => apply Inhab_word.\n\nHint Extern 1 (Inhab val) => apply Inhab_val.\n\nHint Extern 1 (Inhab trm) => apply Inhab_trm.\n\nHint Extern 1 (Inhab typ) => apply Inhab_typ.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Coercions *)\n\nCoercion prim_binop : binop >-> prim.\nCoercion trm_val : val >-> trm.\nCoercion trm_var : var >-> trm.\nCoercion trm_app : prim >-> Funclass.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Implicit types *)\n\nImplicit Types t : trm.\nImplicit Types v : val.\nImplicit Types l : loc.\nImplicit Types b : bool.\nImplicit Types x : var.\nImplicit Types z : bind.\nImplicit Types vs : list val.\nImplicit Types ts : list trm.\n\n\n(* ---------------------------------------------------------------------- *)\n(** Auxiliary predicates for the semantics and transformations *)\n\n(** Predicates for values *)\n\nDefinition is_basic (v:val) :=\n  match v with\n  | val_error => True\n  | val_unit => True\n  | val_uninitialized => True\n  | val_bool _ => True\n  | val_int _ => True\n  | val_double _ => True\n  | val_abstract_ptr _ _ => True\n  | val_concrete_ptr _ _ => True\n  | _ => False\n  end.\n\nDefinition is_error (v:val) :=\n  match v with\n  | val_error => True\n  | _ => False\n  end.\n\nDefinition is_bool (v:val) :=\n  match v with\n  | val_bool _ => True\n  | _ => False\n  end.\n\nDefinition is_ptr (v:val) :=\n  match v with\n  | val_abstract_ptr _ _ => True\n  | _ => False\n  end.\n\nDefinition is_int (v:val) :=\n  match v with\n  | val_int _ => True\n  | _ => False\n  end.\n\nDefinition is_struct (v:val) :=\n  match v with\n  | val_struct _ _ => True\n  | _ => False\n  end.\n\nDefinition is_array (v:val) :=\n  match v with\n  | val_array _ _ => True\n  | _ => False\n  end.\n\n(** Predicates on primitive functions. *)\n\nDefinition is_struct_op (op:prim) :=\n  match op with\n  | prim_struct_access _ _ => True\n  | prim_struct_get _ _ => True\n  | _ => False\n  end.\n\nDefinition is_array_op (op:prim) :=\n  match op with\n  | prim_array_access _ => True\n  | prim_array_get _ => True\n  | _ => False\n  end.\n\n(** Predicates on terms. *)\n\nDefinition is_val (t:trm) :=\n  match t with\n  | trm_val _ => True\n  | _ => False\n  end.\n\n(** Special predicate: Checking if a value can be get from memory, i.e.\n    checking if it contains any [val_uninitialized] somewhere. *)\n\nInductive is_uninitialized : val -> Prop :=\n  | is_uninitialized_val_uninitialized :\n      is_uninitialized val_uninitialized\n  | is_uninitialized_array : forall T a,\n      (exists i, index a i /\\ is_uninitialized a[i]) ->\n      is_uninitialized (val_array T a)\n  | is_uninitialized_struct : forall T s,\n      (exists f, f \\indom s /\\ is_uninitialized s[f]) ->\n      is_uninitialized (val_struct T s).\n\n(** Same as above but for the low-level equivalent of undefined, \n    which is called [word_undef]. *)\n\nDefinition is_undef (v:val) :=\n  match v with\n  | val_words ws => exists i, index ws i /\\ ws[i] = word_undef\n  | _ => False\n  end.\n", "meta": {"author": "ramonfmir", "repo": "verified_transfo", "sha": "2afbe24651f5af8e4fa545ff1afb454be3ce7f9e", "save_path": "github-repos/coq/ramonfmir-verified_transfo", "path": "github-repos/coq/ramonfmir-verified_transfo/verified_transfo-2afbe24651f5af8e4fa545ff1afb454be3ce7f9e/src/Language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23212001802571686}}
{"text": "Require Import LiveVerif.LiveVerifLib.\nRequire Import coqutil.Tactics.syntactic_unify.\nRequire Import Lia.\n\nLoad LiveVerif.\n\n(* TODO support functions that don't access any memory *)\nDefinition dummy: mem -> Prop := emp True.\n\nRecord node := {\n  data: word;\n  next: word;\n}.\nDefinition node_t(r: node): word -> mem -> Prop := .**/\ntypedef struct __attribute__ ((__packed__)) {\n  uintptr_t data;\n  uintptr_t next;\n} node_t;\n/**.\n\n#[export] Instance spec_of_malloc: fnspec :=                         .**/\nuintptr_t malloc(uintptr_t size)                                     /**#\n  ghost_args := (R: mem -> Prop);\n  requires t m := sep dummy R m;\n  ensures t' m' retPtr := t' = t /\\ exists anyData,\n       <{ * dummy\n          * array uintptr \\[size] anyData retPtr\n          * R }> m'                                                   #**/ /**.\nParameter malloc : function_with_callees.\nParameter malloc_ok : program_logic_goal_for \"malloc\" malloc.\n\n\n#[export] Instance spec_of_malloc_node: fnspec :=                    .**/\nuintptr_t malloc_node(uintptr_t anything)                                 /**#\n  ghost_args := (R: mem -> Prop);\n  requires t m := sep dummy R m;\n  (* ensures t' m' retPtr := t' = t /\\\n                          <{ * ex1 (fun x => node x retPtr)\n                             * R }> m                               #**/ /**. *)\n  ensures t' m' retPtr := t' = t /\\ exists x,\n                          <{ * dummy\n                             * node_t x retPtr\n                             * R }> m'                               #**/ /**.\nDerive malloc_node SuchThat (fun_correct! malloc_node) As malloc_node_ok. .**/\n{ /**. .**/\n  uintptr_t r = malloc(2);   /**.\n  assert (len anyData = 2) as Hlen by hwlia.\n\n  destruct anyData; [discriminate Hlen | idtac].\n  destruct anyData; [discriminate Hlen | idtac].\n  destruct anyData; [idtac | simpl in Hlen; lia].\n\n  .**/ return r; /**.\n.**/ } /**.\n\n  unfold node_t.\n  unfold sepapps.\n  simpl.\n  unfold sepapp.\n  (* TODO: automated memory cast *)\n  instantiate (1 := {| data := r0; next := r1 |}).\n  unfold array.\n  simpl.\n  eapply iff1ToEq. cancel.\n  unfold seps. unfold iff1. unfold emp. intuition.\nQed.\n\n\nFixpoint sll (L : list word) (p : word): mem -> Prop :=\n  match L with\n  | nil => emp (p = /[0])\n  | x::L' => ex1 (fun (q:word) =>\n      <{ * uintptr x p\n         * uintptr q (p ^+ /[4])\n         * sll L' q }>)\n  end.\n\nLemma purify_sll:\n  forall L p,\n    purify (sll L p) (True).\nProof.\n  unfold purify. auto.\nQed.\nHint Resolve purify_sll : purify.\n\n#[export] Instance spec_of_sll_prepend: fnspec := .**/\n\nuintptr_t sll_prepend(uintptr_t p, uintptr_t val) /**#\n  ghost_args := (L : list word) (R: mem -> Prop);\n  requires t m := <{ * dummy\n                     * sll L p\n                     * R }> m;\n  ensures t' m' res := t' = t /\\\n       <{ * dummy\n          * sll (val::L) res\n          * R }> m' #**/ /**.\nDerive sll_prepend SuchThat (fun_correct! sll_prepend) As sll_prepend_ok. .**/\n{ /**.\n  (* TODO: a lot of dummys *)\n  (* TODO: should support empty arguments *)\n  .**/ uintptr_t r = malloc_node(-123); /**.\n  (* set r.data = val *)\n  .**/ store(r, val); /**.\n  .**/ store(r+4, p); /**.\n  .**/ return r; /**.\n  (* TODO: all of this should probably be automated *)\n  replace ((m4 \\*/ (m2 \\*/ m3)) \\*/ m) with (m \\*/ m2 \\*/ m3 \\*/ m4) in D by admit.\n  assert (exists (mm2:mem), m \\*/ m2 = mm2) as Hex by admit.\n  destruct Hex as [mm2 Hex]. rewrite Hex in D. clear Hex.\n  assert (mm2 |= sll (val :: L) r) by admit.\n.**/ } /**.\nAbort.\n\nEnd LiveVerif. Comments .**/ //.\n", "meta": {"author": "mit-plv", "repo": "bedrock2", "sha": "7f2d764ed79f394fe715505a04301d0fb502407f", "save_path": "github-repos/coq/mit-plv-bedrock2", "path": "github-repos/coq/mit-plv-bedrock2/bedrock2-7f2d764ed79f394fe715505a04301d0fb502407f/LiveVerif/src/LiveVerifExamples/linked_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23212001802571686}}
{"text": "Require Import Cosa.Lib.Header.\nRequire compcert.common.Memdata.\nRequire Import Cosa.Interaction.Interaction.\nRequire Import Cosa.Interaction.InteractionLib.\nRequire Import Cosa.Abstract.Lang.\nRequire Import Cosa.Abstract.Valuation.\nRequire Import Cosa.Shape.Graph.\nRequire Import Cosa.Shape.Summary.\nImport List.ListNotations.\nImport Coq.Classes.EquivDec.\n\n(** In this file we define the concrete instances of inductive shapes\n    we are interested in. *)\n\nSection Schemata.\n\n  Context {name:Type} (γ_name:name -> node -> ℘ Graph.conc).\n  Hypothesis valuation_not_fixed_summary : forall α sm f,\n    central (belongs_to_summary α sm)\n            (fun ν => (ν,f) ∈ γ_name sm α).\n\n  (** In this section we define generic combinators to build inductive\n      summaries. *)\n\n  (** [fnf n] is the type of functions taking [n] argument nodes and\n      returning a rule. *)\n  Fixpoint fnf (n:nat) : Type :=\n    match n with\n    | 0 => rule name\n    | S n => Graph.node -> fnf n\n    end\n  .\n\n  (** [rule_with_new n] is the type of interaction structures\n      requiring [n] new nodes and producing a rule. *)\n  Fixpoint rule_with_new {n:nat} : fnf n -> Interaction (℘ node) (rule name) :=\n    match n with\n    | 0 => fun r => just r\n    | S n => fun r => bind with_new (fun α => rule_with_new (r α))\n    end\n  .\n\n  (** A correction property for [rule_with_new n]: the nodes allowed\n      in the generated rule must only contain nodes in a given set and\n      the [n] new nodes. *)\n  Fixpoint rule_correct {n:nat} : fnf n -> ℘ node -> Prop :=\n    match n with\n    | 0 => fun r P => sub (Γ:=[node]) (belongs_to_graph (fst r)) P /\\\n                      sub (Γ:=[node]) (belongs_to_expr (snd r)) P\n    | S n => fun r P => forall α, rule_correct (r α) (P ∪ singleton α)\n    end\n  .\n\n  (* arnaud: déplacer dans extra? *)\n  Lemma exists_sigTr (A:Type) (F:A->Type) (P:forall x:A, F x -> Prop) :\n    (exists u:{x:A & F x}, (P (projT1 u) (projT2 u))) <->\n    (exists (x:A) (y:F x), P x y).\n  Proof.\n    split.\n    - intros [ [ x y ] h ]; simpl in *.\n      decompose_concl; eauto.\n    - intros [ x [ y h ]].\n      eexists (existT _ x y); simpl.\n      easy.\n  Qed.\n\n  (* arnaud: déplacer dans extra? *)\n  Lemma exists_sigT (A:Type) (F:A->Type) (P:{ x:A & F x} -> Prop) :\n    (exists u, P u) <->\n    (exists (x:A) (y:F x), P (existT _ x y)).\n  Proof.\n    split.\n    - intros [ [ x y ] h ]; simpl in *.\n      decompose_concl; eauto.\n    - intros [ x [ y h ]].\n      eexists (existT _ x y); simpl.\n      easy.\n  Qed.\n\n  (* arnaud: déplacer dans extra? *)\n  Lemma exists_sig (A:Type) (F:A->Prop) (P:{ x:A | F x} -> Prop) :\n    (exists u, P u) <->\n    (exists (x:A) (y:F x), P (exist _ x y)).\n  Proof.\n    split.\n    - intros [ [ x y ] h ]; simpl in *.\n      decompose_concl; eauto.\n    - intros [ x [ y h ]].\n      eexists (existT _ x y); simpl.\n      easy.\n  Qed.\n\n  Lemma γ_unfolding_with_new (u:node->unfolding name) (P:℘ node) α :\n    γ_unfolding_with γ_name P (fun α => (bind with_new (fun β => u β α))) α =\n    Join (fun β => meet (Γ:=[_]) (fun _ => β ∉ P)\n                                 (γ_unfolding_with γ_name (fun δ=>δ∈P\\/δ=β) (u β) α)).\n  Proof.\n    double_sub; intros s.\n    - unfold γ_unfolding_with; simpl.\n      intros [ [ [ β hβ ] h₂ ] [ [ [] r] h₃ ]]; simpl in *.\n      decompose_concl; eauto.\n    - unfold γ_unfolding_with; simpl.\n      intros [ β [ h₁ [ c [ r h₂ ]]]].\n      rewrite ?exists_sigT,?exists_sig; simpl.\n      eexists; split.\n      { eauto. }\n      exists (fun _ => c).\n      rewrite ?exists_sigT,?exists_sig; simpl.\n      decompose_concl; eauto.\n      easy.\n  Qed.\n\n  (** The properties of [Summary.env] are verified by unfoldings of\n      the form [rule_with_new n r] *)\n\n  Obligation Tactic := idtac.\n  Definition swap_set (α β :node) (P:℘ node) : ℘ node :=\n    fun δ =>\n      if      δ == α then P β\n      else if δ == β then P α\n           else           P δ\n  .\n\n  Program Fixpoint swap_com_rec {n:nat} : forall {r:fnf n} {P:℘ node} (α β:node), (rule_with_new r).(Com) P -> (rule_with_new r).(Com) (swap_set α β P) :=\n    match n with\n    | 0 => fun _ _ _ _ _ => tt\n    | S n => fun r P α β c =>\n               if proj1_sig (projT1 c) == α then\n                 existT _ (exist _ β _) _\n               else\n                 _\n    end.\n  Next Obligation.\n    intros * <-; simpl in *.\n    intros r P α β [ [ δ hδ] c] <- ; simpl in *.\n    unfold swap_set.\n    rewrite if_eq_refl.\n    destruct (β==δ) as [ <- | _ ]; assumption.\n  Qed.\n  Next Obligation.\n    intros ? n <- r P α β [ [δ hδ] c ] <- ; simpl in *; intros _.\n    \n\n  Program Fixpoint swap_com {n:nat} : forall {r:fnf n} {P:℘ node} (α β:node), (rule_with_new r).(Com) P -> α ∉ P -> β ∉ P -> (rule_with_new r).(Com) P:=\n    match n with\n    | 0 => fun _ _ _ _ _ _ _ => tt\n    | S n => fun r P α β c hα hβ =>\n               if proj1_sig (projT1 c) == α then\n                 existT _ (exist _ β hβ) _\n               else\n                 _\n    end.\n  Next Obligation.\n    intros * <-; simpl in *.\n    intros r P α β [ [ δ hδ ] c ] hα hβ e; simpl in *.\n    Print sig.\n    \n\n  Lemma vnf_rule_with_new (n:nat) (r:fnf (S n)) (P:℘ node) (α:node) :\n    α ∈ P ->\n    (rule_correct (r α) P) ->\n    forall f,\n      central P\n              (fun ν => (ν,f) ∈ γ_unfolding_with γ_name P (fun α => rule_with_new (r α)) α).\n  Proof.\n    revert r P α.\n    induction n as [ | n hn ]; intros r P α.\n    - admit.\n    - intros h₁ h₂ f; simpl in h₂.\n      intros β δ hβ hδ ν h₃; unfold γ_unfolding_with in h₃ |- *; simpl in h₃ |- *.\n      destruct h₃ as [ [ [ γ hγ] c] h₃ ]; simpl in c,h₃.\n      destruct h₃ as [ [ [] r'] h₃ ]; simpl in h₃.\n      rewrite ?exists_sigT,?exists_sig; simpl.\n      destruct (β==γ) as [ <- | nβγ ].\n      + destruct (β==δ) as [ -> | nβδ ].\n        * assert (swap δ δ ν = ν) as e; [|rewrite e;clear e].\n          { extensionality x.\n            apply swap_self_id. }\n          exists δ; exists hδ; exists c.\n          rewrite ?exists_sigT,?exists_sig; simpl.\n          decompose_concl; eauto.\n        * \n  Admitted.\n\n\nEnd Schemata.\n\n(** spiwack: There are few inductive at the time, until we are able to generate them. *)\n\nInductive name :=\n| List\n| ListSegment (β:Graph.node)\n.\n\nLocal Notation \"α ≡ β\" := (Lang.Abinop (Cminor.Ocmpu Integers.Ceq) α β) (at level 70).\nLocal Notation \"α ≠ β\" := (Lang.Aunop Cminor.Onegint (α≡β)) (at level 70).\nLocal Notation \"0\" := (Lang.Aconst (Cminor.Ointconst Int.zero)).\nLocal Notation \"1\" := (Lang.Aconst (Cminor.Ointconst Int.one)).\n\nDefinition add_chunk (offs:int) (chunk:AST.memory_chunk) : int :=\n  Int.add offs (Int.repr (Memdata.size_chunk chunk))\n.\n\nDefinition def (i:name) (α:node) : Interaction (℘ node) (Summary.rule name) :=\n  match i with\n  | List =>\n    Interaction.pi (Finite.access [\n        just (Graph.NodeTree.empty _, (Avar α) ≡ 0) (** empty list *);\n        bind with_new (fun β => (** head *)\n        bind with_new (fun δ => (** tail *)\n            just (NodeTree.set α (Point_to\n                    [(Int.zero,{|destination:=(β,Int.zero);size:=AST.Mint32|});\n                     (add_chunk (Int.zero) AST.Mint32,{|destination:=(δ,Int.zero);size:=AST.Mint32|})]\n                   )\n                  (NodeTree.set δ (Summarized List)\n                  (NodeTree.empty _)) ,\n                  (Avar α) ≠ 0)))\n      ])\n  | ListSegment β =>\n    Interaction.pi (Finite.access [\n        just (Graph.NodeTree.empty _, (Avar α) ≡ (Avar β)) (** empty segment *);\n        bind with_new (fun γ => (** head *)\n        bind with_new (fun δ => (** tail *)\n            just (NodeTree.set α (Point_to\n                    [(Int.zero,{|destination:=(γ,Int.zero);size:=AST.Mint32|});\n                     (add_chunk (Int.zero) AST.Mint32,{|destination:=(δ,Int.zero);size:=AST.Mint32|})]\n                   )\n                  (NodeTree.set δ (Summarized (ListSegment β))\n                  (NodeTree.empty _)) ,\n                  (Avar α) ≠ 0)))\n      ])\n  end\n.\n\n(** Segments can be unfolded from the back node. *)\nDefinition list_segment_backward_unfolding (β α:node) :\n   Interaction (℘ node) (Summary.rule name) :=\n  Interaction.pi (Finite.access [\n      just ( (** backward unfolding can yield identity. *)\n        NodeTree.set α (Summarized (ListSegment β))\n       (NodeTree.empty _),1 );\n\n      bind with_new (fun γ => (** value *)\n      bind with_new (fun δ => (** new end point *)\n        just (NodeTree.set α (Summarized (ListSegment δ))\n             (NodeTree.set δ (Point_to\n                  [(Int.zero,{|destination:=(γ,Int.zero);size:=AST.Mint32|});\n                     (add_chunk (Int.zero) AST.Mint32,{|destination:=(β,Int.zero);size:=AST.Mint32|})]\n                   )\n             (NodeTree.empty _)) ,\n             (Avar δ) ≠ 0)))\n      ])\n.\n\nDefinition d : Summary.def :=\n  existT _ name def\n.\n\nInductive fb := Forward | Backward.\n\nDefinition list_unfoldings (i:name) : { U:Type & U -> unfolding name }:=\n  match i with\n  | List => existT _ (unit:Type) (fun _ => def List)\n  | ListSegment β => existT (fun U => U -> unfolding name) (fb:Type)\n                                 (fun d => match d with\n                                           | Forward => def (ListSegment β)\n                                           | Backward => list_segment_backward_unfolding β\n                                           end)\n  end\n.\n\n(* arnaud: WIP *)\nProgram Definition env : Summary.env := {|\n  defs := d ;\n  unfoldings := list_unfoldings\n|}.\nNext Obligation. (** [defs_local] *)\n  unfold valuation_not_fixed_def, Valuation.central.\n  (** Reformulate the goal into a form where [lfp_ind] can be applied *)\n  cut (sub (Γ:=[names_of d;node;conc])\n             (γ d)\n             (fun i α s =>\n                forall β δ,\n                  ~ belongs_to_summary α i β ->\n                  ~ belongs_to_summary α i δ ->\n                  γ d i α (Valuation.swap β δ (fst s), (snd s)))).\n  { simpl; intros h; intros i α f β δ h₁ h₂ ν.\n    specialize (h i α (ν,f)); eauto. }\n  (** by induction *)\n  apply lfp_ind.\n  { typeclasses eauto. }\n  simpl; intros R h₁ h₂ i α [ν f] h₃ β δ hβ hδ; simpl.\n  change (lfp (F_γ d)) with (γ d) in h₁.\n  destruct i as [|γ].\n  - (** [List] *)\n    unfold F_γ,γ_unfolding in h₃.\n    rewrite <- γ_fixed_point.\n    unfold F_γ,γ_unfolding.\n    destruct h₃ as [ P [ εs [ r h₃]]]. exists P.\n    destruct h₃ as [ h₃₁ h₃₂ ].\n    destruct r as [ [ [[]|] | ] r_plus ].\n    * (** ν is of the form cons *)\n      simpl in * |-.\n      destruct r_plus as [ [] [ [] [] ]].\n      destruct (εs (Some None)) as [ [ε hε] ζ₀ ]; simpl in * |-; clear εs.\n      destruct (ζ₀ tt) as [ [ζ hζ] id_unit ]; simpl in * |-; clear ζ₀.\n      \n    * (** ν is of the form nil *)\n  - (** [ListSegment β] *)", "meta": {"author": "aspiwack", "repo": "cosa", "sha": "2d808236e71f2289033dff6b74a3f57311df9a14", "save_path": "github-repos/coq/aspiwack-cosa", "path": "github-repos/coq/aspiwack-cosa/cosa-2d808236e71f2289033dff6b74a3f57311df9a14/Analysis/Inductives.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23212001802571686}}
{"text": "Require Import VST.concurrency.conclib.\nRequire Import VST.floyd.proofauto.\nRequire Import VST.atomics.general_locks.\nRequire Import Coq.Sets.Ensembles.\nRequire Import bst.puretree.\nRequire Import bst.bst_template_coupling.\nRequire Import bst.coupling_lib.\nRequire Import bst.coupling_traverse.\nRequire Import VST.floyd.library.\nImport FashNotation.\n\n(* Specification of lookup function *)\nProgram Definition lookup_spec :=\n  DECLARE _lookup\n  ATOMIC TYPE (rmaps.ConstType (val * share * lock_handle * Z * globals * gname * gname))\n         OBJ M INVS ∅\n  WITH b, sh, lock, x, gv, g, g_root\n  PRE [tptr (tptr t_struct_tree_t), tint]\n    PROP (writable_share sh;\n    and (Z.le Int.min_signed x)(Z.le x Int.max_signed))\n    PARAMS (b; Vint (Int.repr x)) GLOBALS (gv)\n    SEP  (mem_mgr gv; nodebox_rep g g_root sh lock b) |\n  (tree_rep g g_root M)\n  POST [tptr Tvoid]\n    EX ret: val,\n    PROP ()\n    LOCAL (temp ret_temp ret)\n    SEP (mem_mgr gv; nodebox_rep g g_root sh lock b) |\n        (!! (ret = match M !! x with Some v => v | None => nullval end) && tree_rep g g_root M).\n\nDefinition Gprog : funspecs :=\n    ltac:(with_library prog [acquire_spec; release_spec; makelock_spec;\n     surely_malloc_spec; traverse_spec; findnext_spec; lookup_spec]).\n\n(* Proving lookup function satisfies spec *)\nLemma body_lookup: semax_body Vprog Gprog f_lookup lookup_spec.\nProof.\n  start_function.\n  unfold nodebox_rep, ltree.\n  Intros np.\n  forward_call (t_struct_pn, gv).\n  Intros nb.\n  forward.\n  forward.\n  forward.\n  forward.\n  set (AS := atomic_shift _ _ _ _ _).\n  (* acquire(pn->n->lock); *)\n  forward_call acquire_inv_simple (sh, lock, node_lock_inv (Share.split gsh1).1 g np g_root lock).\n  {\n    set Q1:= fun (b : (bool * ( val * (val * (lock_handle * (share * (gname * node_info))))))%type) =>\n              if b.1 then AS else AS.\n    (* traverse(pn, x, nullval) *)\n    (* we assign value to nullval*)\n    forward_call (nb, np, sh, lock, x, nullval, gv, g, g_root, Q1).\n    {\n      unfold pn_rep_1, node_lock_inv'.\n      Exists (default_val t_struct_pn).1.\n      unfold node_lock_inv.\n      sep_apply self_part_eq.\n      assert (lsh2 <> Share.bot).\n      { apply readable_not_bot. apply readable_lsh2. }\n      auto.\n      entailer !.\n      rewrite -> 2sepcon_assoc. rewrite sepcon_comm.\n      rewrite -> sepcon_assoc; apply sepcon_derives; [|cancel].\n      unfold atomic_shift; iIntros \"AU\"; iAuIntro; unfold atomic_acc; simpl.\n      iMod \"AU\" as (m) \"[Hm HClose]\".\n      iModIntro.\n      iExists m.\n      iFrame \"Hm\".\n      iSplit; iFrame.\n      { by iApply bi.and_elim_l. }\n      {\n        iDestruct \"HClose\" as \"[HClose _]\".\n        iIntros (pt) \"[H _]\".\n        iMod (\"HClose\" with \"H\") as \"H\".\n        iModIntro.\n        unfold Q1.\n        destruct (decide (pt.1 = true)). { rewrite e; iFrame. }\n        { apply not_true_is_false in n; rewrite n; iFrame. }\n      }\n    }\n    Intros pt.\n    destruct pt as (fl & (p1 & (tp & (lock_in & (gsh & (g_in & r)))))).\n    simpl in H1, H2.\n    destruct fl.\n    simpl.\n    change emp with seplog.emp.\n    - destruct H2.\n      forward_if (\n          PROP ( )\n            LOCAL (temp _v nullval; temp _t'2 Vtrue; temp _t'8 (ptr_of lock);\n                   temp _t'7 np; temp _t'9 np; temp _pn__2 nb; gvars gv; temp _t b; temp _x (vint x))\n            SEP (Q1 (true, (p1, (tp, (lock_in, (gsh, (g_in, r)))))); mem_mgr gv; emp;\n                 node_lock_inv_new gsh g p1 g_in lock_in tp r;\n                 data_at Ews t_struct_pn (p1, p1) nb;\n                 my_half g_root (Share.split gsh1).2 (Neg_Infinity, Pos_Infinity, None);\n                 data_at sh (tptr t_struct_tree_t) np b;\n                 field_at sh t_struct_tree_t (DOT _lock) (ptr_of lock) np;\n                 lock_inv sh lock\n                   (selflock (node_lock_inv_pred (Share.split gsh1).1 g np g_root (ptr_of lock))\n                      gsh2 lock);\n                 malloc_token Ews t_struct_pn nb)).\n      + pose proof (Int.one_not_zero); easy.\n      + Intros.\n        forward.\n        unfold node_lock_inv_new.\n        entailer !.\n      + rewrite H3.\n        unfold node_lock_inv_new, tree_rep_R.\n        rewrite -> if_true by auto.\n        unfold Q1.\n        simpl.\n        Intros.\n        gather_SEP AS (my_half g_in _ _) (in_tree g _).\n        viewshift_SEP 0 (EX y, Q y * (!! (y = nullval) && (in_tree g g_in * my_half g_in gsh r))).\n        {\n          go_lower.\n          apply sync_commit_same.\n          intro t.\n          unfold tree_rep at 1.\n          Intros tg.\n          sep_apply node_exist_in_tree; Intros.\n          sep_apply (ghost_tree_rep_public_half_ramif _ _ (Neg_Infinity, Pos_Infinity) _ H9).\n          Intros r0.\n          eapply derives_trans; [|apply ghost_seplog.bupd_intro].\n          Exists r0.\n          unfold public_half'; cancel.\n          apply imp_andp_adjoint.\n          Intros.\n          apply node_info_incl' in H11 as [].\n          eapply derives_trans; [|apply ghost_seplog.bupd_intro].\n          rewrite <- wand_sepcon_adjoint.\n          eapply derives_trans; [|apply ghost_seplog.bupd_intro].\n          simpl.\n          simpl in H12.\n          Exists nullval; simpl; entailer!.\n          - destruct r as [range r2], r0 as [rg ?]; simpl in *; subst.\n            rewrite -> range_info_not_in_gmap\n              with (rn := rg)(r_root := (Neg_Infinity, Pos_Infinity)); auto.\n            eapply key_in_range_incl; eauto.\n          - unfold tree_rep. Exists tg. entailer!. iIntros \"[[? H] ?]\".\n            iApply \"H\". iFrame. \n        }\n        Intros y.\n        subst y.\n        (*  (_release2(_t'4); *)\n        change emp with seplog.emp.\n        forward.\n        forward.\n        forward_call release_self (gsh2, lock_in,\n                    node_lock_inv_pred gsh g p1 g_in (ptr_of lock_in)).\n        {\n          unfold node_lock_inv_pred at 3, sync_inv.\n          Exists r.\n          rewrite node_rep_def.\n          unfold node_lock_inv, tree_rep_R.\n          Exists nullval.\n          rewrite -> if_true by auto.\n          entailer !.\n        }\n        forward_call (t_struct_pn, nb, gv).\n        { assert_PROP (nb <> nullval) by entailer !. rewrite if_false; auto. cancel. }\n        forward.\n        unfold nodebox_rep, ltree.\n        Exists nullval np.\n        entailer !.\n    - (* v = pn->p->t->value; *)\n      unfold Q1.\n      destruct H2 as ( ?  & v2 & g21 & g22 & ?).\n      simpl.\n      forward_if (\n            PROP ( )\n                 LOCAL (temp _v v2; temp _t'2 Vfalse; temp _t'8 (ptr_of lock); temp _t'7 np;\n                        temp _t'9 np; temp _pn__2 nb; gvars gv; temp _t b; temp _x (vint x))\n                 SEP (Q1 (false, (p1, (tp, (lock_in, (gsh, (g_in, r))))));\n                    mem_mgr gv; seplog.emp;\n                    field_at Ews t_struct_tree_t (DOT _t) tp p1 *\n                      malloc_token Ews t_struct_tree_t p1 * in_tree g g_in *\n                      (EX (ga gb : gname) (x1 : Z) (v0 pa pb : val) (locka lockb : lock_handle),\n                        !! (r.2 = Some (Some (x1, v0, ga, gb))\n                            ∧ (Int.min_signed ≤ x1 ≤ Int.max_signed)%Z\n                            ∧ is_pointer_or_null pa\n                            ∧ is_pointer_or_null pb ∧ tc_val (tptr Tvoid) v0 ∧\n                              key_in_range x1 r.1 = true) &&\n                          data_at Ews t_struct_tree (vint x1, (v0, (pa, pb))) tp *\n                          malloc_token Ews t_struct_tree tp *\n                          |> ltree g ga lsh1 gsh1 gsh1 pa locka *\n                          |> ltree g gb lsh1 gsh1 gsh1 pb lockb) *\n                      my_half g_in gsh r *\n                      field_at lsh2 t_struct_tree_t (DOT _lock) (ptr_of lock_in) p1 *\n                      |> lock_inv gsh2 lock_in (node_lock_inv gsh g p1 g_in lock_in);\n                    data_at Ews t_struct_pn (p1, p1) nb;\n                    my_half g_root (Share.split gsh1).2 (Neg_Infinity, Pos_Infinity, None);\n                    data_at sh (tptr t_struct_tree_t) np b;\n                    field_at sh t_struct_tree_t (DOT _lock) (ptr_of lock) np;\n                    lock_inv sh lock (node_lock_inv (Share.split gsh1).1 g np g_root lock);\n                    malloc_token Ews t_struct_pn nb)); unfold node_lock_inv_new, tree_rep_R.\n      + rewrite -> if_false; auto.\n        Intros g1 g2 x1 v p1' p2' l1 l2.\n        change emp with seplog.emp.\n        forward.\n        forward.\n        forward.\n        Exists g1 g2 x1 v p1' p2' l1 l2.\n        unfold Q1.\n        entailer !. auto.\n      + pose proof Int.one_not_zero; contradiction.\n      + Intros g1 g2 x1 v p1' p2' l1 l2.\n        change emp with seplog.emp.\n        forward.\n        forward.\n        simpl in H1, H3, H4, H5, H6, H7.\n        rewrite H4 in H3.\n        injection H3.\n        intros. subst x1. subst v2. subst g21. subst g22.\n        unfold Q1.\n        simpl.\n        gather_SEP AS (my_half g_in _ _) (in_tree g _).\n        viewshift_SEP 0 ( EX y, Q y * (!!(y = v) && (in_tree g g_in * my_half g_in gsh r))).\n        {\n          go_lower.\n          apply sync_commit_same.\n          intro t.\n          unfold tree_rep at 1.\n          Intros tg.\n          sep_apply node_exist_in_tree; Intros.\n          sep_apply (ghost_tree_rep_public_half_ramif _ _ (Neg_Infinity, Pos_Infinity) _ H14).\n          Intros r0.\n          eapply derives_trans; [|apply ghost_seplog.bupd_intro].\n          Exists r0.\n          unfold public_half'; cancel.\n          apply imp_andp_adjoint.\n          Intros.\n          apply node_info_incl' in H16 as [].\n          eapply derives_trans; [|apply ghost_seplog.bupd_intro].\n          rewrite <- wand_sepcon_adjoint.\n          eapply derives_trans; [|apply ghost_seplog.bupd_intro].\n          Exists v; entailer!.\n          simpl. entailer !.\n          - destruct r as [range r2], r0 as [range0 r0]. simpl in *; subst.\n            erewrite range_info_in_gmap; eauto.\n          - iIntros \"[[[? H] ?] ?]\".\n            unfold tree_rep. iExists tg. iFrame; iSplit; auto.\n            iApply \"H\"; iFrame.\n        }\n        Intros y.\n        subst y.\n        Intros.\n        forward_call release_self (gsh2, lock_in,\n                    node_lock_inv_pred gsh g p1 g_in (ptr_of lock_in)).\n        {\n          unfold node_lock_inv, node_lock_inv_pred at 4, sync_inv.\n          Exists r.\n          rewrite node_rep_def.\n          Exists tp.\n          unfold tree_rep_R, ltree.\n          rewrite -> if_false by auto.\n          Exists g1 g2 x v p1' p2' l1 l2.\n          entailer !.\n          rewrite <- later_sepcon;\n            eapply derives_trans;\n            [|apply sepcon_derives, derives_refl; apply now_later].\n          cancel.\n        }\n        forward_call (t_struct_pn, nb, gv).\n        { assert_PROP (nb <> nullval) by entailer !. rewrite if_false; auto. cancel. }\n        forward.\n        unfold nodebox_rep, ltree.\n        Exists v np.\n        entailer !.\n  }\nQed.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "DeepSpecDB", "sha": "a67d933b4288498bd04c70748b7fa28f676983c3", "save_path": "github-repos/coq/PrincetonUniversity-DeepSpecDB", "path": "github-repos/coq/PrincetonUniversity-DeepSpecDB/DeepSpecDB-a67d933b4288498bd04c70748b7fa28f676983c3/concurrency/templates/coupling_lookup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23212001802571686}}
{"text": "Require Import List.\nImport ListNotations.\n\nRequire Export Meta.\nRequire Export Shared.\n\n(*\n======\nTypes\n======\n*)\n\nInductive ty : Type :=\n  | TClass : class_id -> ty\n  | TInterface : interface_id -> ty\n  | TUnit : ty.\n\n(*\n============\nExpressions\n============\n*)\n\nInductive val : Type :=\n  | VNull : val\n  | VLoc  : loc -> val.\n\nInductive var : Type :=\n  | SV : svar -> var\n  | DV : dvar -> var.\n\nInductive expr : Type :=\n  | EVal : val -> expr\n  | EVar : var -> expr\n  | ENew : class_id -> expr\n  | ECall : var -> method_id -> expr -> expr\n  | ESelect : var -> field_id -> expr\n  | EUpdate : var -> field_id -> expr -> expr\n  | ELet : svar -> expr -> expr -> expr\n  | ECast : ty -> expr -> expr\n  | EPar : expr -> expr -> expr -> expr\n  | ELock : var -> expr -> expr\n  | ELocked : lock -> expr -> expr\n  | EAssert : var -> var -> expr\n.\n\nTactic Notation \"expr_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"EVal\"\n  | Case_aux c \"EVar\"\n  | Case_aux c \"ENew\"\n  | Case_aux c \"ECall\"\n  | Case_aux c \"ESelect\"\n  | Case_aux c \"EUpdate\"\n  | Case_aux c \"ELet\"\n  | Case_aux c \"ECast\"\n  | Case_aux c \"EPar\"\n  | Case_aux c \"ELock\"\n  | Case_aux c \"ELocked\"\n  | Case_aux c \"EAssert\"\n].\n\nDefinition econtext := expr -> expr.\n\nDefinition ctx_call (x : _) (m : _) : econtext := (fun e => ECall x m e).\nHint Unfold ctx_call.\nDefinition ctx_update (x : _) (f : _) : econtext := (fun e => EUpdate x f e).\nHint Unfold ctx_update.\nDefinition ctx_let (x : _) (body : _) : econtext := (fun e => ELet x e body).\nHint Unfold ctx_let.\nDefinition ctx_cast (t : _) : econtext := (fun e => ECast t e).\nHint Unfold ctx_cast.\nDefinition ctx_locked (L : _) : econtext := (fun e => ELocked L e).\nHint Unfold ctx_locked.\n\nInductive is_econtext : econtext -> Prop :=\n  | EC_Call :\n      forall x m,\n        is_econtext (ctx_call x m)\n  | EC_Update :\n      forall x f,\n        is_econtext (ctx_update x f)\n  | EC_Let :\n      forall x body,\n        is_econtext (ctx_let x body)\n  | EC_Cast :\n      forall t,\n        is_econtext (ctx_cast t)\n  | EC_Locked :\n      forall L,\n        is_econtext (ctx_locked L).\n\nDefinition isVal (e : expr) : Prop :=\n  match e with\n    | EVal _ => True\n    | _ => False\n  end.\n\nInductive exprStatic : expr -> Prop :=\n  | StaticVar : forall x, exprStatic (EVar (SV x))\n  | StaticNull : exprStatic (EVal VNull)\n  | StaticNew : forall c, exprStatic (ENew c)\n  | StaticCall : forall x m arg, exprStatic arg -> exprStatic (ECall (SV x) m arg)\n  | StaticSelect : forall x f, exprStatic (ESelect (SV x) f)\n  | StaticUpdate : forall x f e, exprStatic e -> exprStatic (EUpdate (SV x) f e)\n  | StaticLet : forall x e body, exprStatic e -> exprStatic body -> exprStatic (ELet x e body)\n  | StaticPar : forall e1 e2 e3, exprStatic e1 -> exprStatic e2 -> exprStatic e3 -> exprStatic (EPar e1 e2 e3)\n  | StaticCast : forall t e, exprStatic e -> exprStatic (ECast t e)\n  | StaticLock : forall x e, exprStatic e -> exprStatic (ELock (SV x) e)\n  | StaticAssert : forall x y, exprStatic (EAssert (SV x) (SV y))\n.\n\nFixpoint freeVars (e : expr) : list svar :=\n  match e with\n    | EVar (SV x) => [x]\n    | ECall (SV x) _ arg => x :: (freeVars arg)\n    | ECall (DV _) _ arg => (freeVars arg)\n    | ESelect (SV x) _ => [x]\n    | EUpdate (SV x) _ rhs => x :: (freeVars rhs)\n    | EUpdate (DV _) _ rhs => freeVars rhs\n    | ELet x e body =>\n      (freeVars e) ++\n      (List.remove id_eq_dec x (freeVars body))\n    | EPar e1 e2 e3 => (freeVars e1) ++ (freeVars e2) ++ (freeVars e3)\n    | ECast t e => freeVars e\n    | ELock (SV x) e => x :: (freeVars e)\n    | ELock (DV _) e => freeVars e\n    | ELocked _ e => freeVars e\n    | EAssert (SV x) (SV y) => [x; y]\n    | EAssert (DV _) (SV y) => [y]\n    | EAssert (SV x) (DV _) => [x]\n    | EAssert (DV _) (DV _) => []\n    | _ => nil\n  end.\n\nDefinition subst_var (x : svar) (y : dvar) (z : var) : var :=\n  match z with\n    | (SV z) => if id_eq_dec x z then DV y else SV z\n    | (DV z) => (DV z)\n  end.\n\nHint Unfold subst_var.\n\nFixpoint subst (x : svar) (y : dvar) (e : expr) : expr :=\n  match e with\n    | EVar z => EVar (subst_var x y z)\n    | ELet z e' body =>\n        ELet z (subst x y e')\n             (if id_eq_dec x z then\n                body\n              else\n                (subst x y body))\n    | ECall z m arg =>\n        ECall (subst_var x y z)\n              m (subst x y arg)\n    | ESelect z f => ESelect (subst_var x y z) f\n    | EUpdate z f rhs =>\n        EUpdate (subst_var x y z)\n                f (subst x y rhs)\n    | EPar e1 e2 e3 =>\n        EPar (subst x y e1)\n             (subst x y e2)\n             (subst x y e3)\n    | ECast t e =>\n        ECast t (subst x y e)\n    | ELock z e =>\n        ELock (subst_var x y z) (subst x y e)\n    | ELocked L e =>\n        ELocked L (subst x y e)\n    | EAssert z1 z2 =>\n        EAssert (subst_var x y z1) (subst_var x y z2)\n    | _ => e\n  end.\n\nFixpoint locks (e : expr) : list lock :=\n  match e with\n    | ECall _ _ arg => locks arg\n    | EUpdate _ _ rhs => locks rhs\n    | ELet _ e body => locks e ++ locks body\n    | ECast _ e => locks e\n    | EPar e1 e2 e3 => locks e1 ++ locks e2 ++ locks e3\n    | ELock _ e => locks e\n    | ELocked L e => L :: locks e\n    | _ => nil\n  end.\n\nDefinition no_locks (e : expr) : Prop :=\n  locks e = nil.\n\n(*\n==============\nConfiguration\n==============\n*)\n\n(*\n------\nStack\n------\n*)\n\nDefinition dvar_map := partial_map dvar val.\n\n(*\n------\nLocks\n------\n*)\n\nInductive lock_status : Type :=\n  | LLocked : lock_status\n  | LUnlocked : lock_status.\n\n(*\n-----\nHeap\n-----\n*)\n\nDefinition dyn_fields := partial_map field_id val.\n\nDefinition object := (class_id * dyn_fields * lock_status)%type.\n\nDefinition heap := list object.\n\nDefinition heapExtend (H : heap) (obj : object) := snoc H obj.\n\nDefinition heapLookup (H : heap) (l : loc) :=\n  nth_error H l.\n\nFixpoint heapUpdate (H : heap) (l : loc) (obj : object) :=\n  match H with\n  | nil => nil\n  | obj' :: H' =>\n    match l with\n    | O    => obj :: H'\n    | S l' => obj' :: (heapUpdate H' l' obj)\n    end\n  end.\n\n(*\n--------\nThreads\n--------\n*)\n\nInductive threads :=\n  | T_EXN    : list lock -> threads\n  | T_Thread : list lock -> expr -> threads\n  | T_Async  : threads -> threads -> expr -> threads.\n\nDefinition threads_done (thr : threads) :=\n  match thr with\n    | T_Thread _ (EVal _) => True\n    | _ => False\n  end.\n\nDefinition threads_exn (thr : threads) :=\n  match thr with\n    | T_EXN _ => True\n    | _ => False\n  end.\n\nFixpoint heldLocks (T : threads) :=\n  match T with\n    | T_EXN Ls => Ls\n    | T_Thread Ls _ => Ls\n    | T_Async T1 T2 _ => heldLocks T1 ++ heldLocks T2\n  end.\n\nFixpoint leftmost_locks (T : threads) : list lock :=\n  match T with\n    | T_EXN Ls => Ls\n    | T_Thread Ls _ => Ls\n    | T_Async T1 _ _ => leftmost_locks T1\n  end.\n\nFixpoint t_locks (T : threads) :=\n  match T with\n    | T_EXN _ => nil\n    | T_Thread _ e => locks e\n    | T_Async T1 T2 e => t_locks T1 ++ t_locks T2 ++ locks e\n  end.\n\n(*\n--------------\nConfiguration\n--------------\n*)\n\nDefinition configuration := (heap * dvar_map * nat * threads)%type.\n\nDefinition cfg_done (cfg : configuration) : Prop :=\n  match cfg with\n    | (_, _, _, thr) => threads_done thr\n  end.\n\nDefinition cfg_exn (cfg : configuration) : Prop :=\n  match cfg with\n    | (_, _, _, thr) => threads_exn thr\n  end.\n\n(*\n========\nProgram\n========\n*)\n\nInductive fieldDecl : Type :=\n  | Field : field_id -> ty -> fieldDecl.\n\nInductive methodDecl : Type :=\n  | Method : method_id -> (svar * ty) -> ty -> expr -> methodDecl.\n\nInductive classDecl : Type :=\n  | Cls : class_id -> interface_id -> list fieldDecl -> list methodDecl -> classDecl.\n\nInductive methodSig : Type :=\n  | MethodSig : method_id -> (svar * ty) -> ty -> methodSig.\n\nInductive interfaceDecl : Type :=\n  | Interface : interface_id -> list methodSig -> interfaceDecl\n  | ExtInterface : interface_id -> interface_id -> interface_id -> interfaceDecl.\n\nDefinition program := (list classDecl * list interfaceDecl * expr)%type.\n\nDefinition classLookup(P : program)(c : class_id) : option classDecl :=\n  match P with\n    | (cs, _, _) =>\n      let c_eq c cls := match cls with\n                          | Cls c' _ _ _ => beq_nat c c'\n                        end\n      in\n      find (c_eq c) cs\n  end.\n\nDefinition interfaceLookup(P : program)(i : interface_id) : option interfaceDecl :=\n  match P with\n    | (_, ids, _) =>\n      let i_eq i intr := match intr with\n                          | Interface i' _ => beq_nat i i'\n                          | ExtInterface i' _ _ => beq_nat i i'\n                        end\n      in\n      find (i_eq i) ids\n  end.\n\nDefinition fieldLookup(fs : list fieldDecl)(f : field_id) :=\n  let f_eq f fld := match fld with\n                     | Field f' _ => beq_nat f f'\n                    end\n  in\n  find (f_eq f) fs.\n\nDefinition fields(P : program)(t : ty) :=\n  match t with\n    | TClass c => match classLookup P c with\n                    | Some (Cls _ _ fs _) => Some fs\n                    | None => None\n                  end\n    | _ => None\n  end.\n\nDefinition methodLookup(ms : list methodDecl)(m : method_id) :=\n  let m_eq m mtd := match mtd with\n                      | Method m' _ _ _ => beq_nat m m'\n                    end\n  in\n  find (m_eq m) ms.\n\nDefinition methods(P : program)(t : ty) :=\n  match t with\n    | TClass c => match classLookup P c with\n                    | Some (Cls _ _ _ ms) => Some ms\n                    | None => None\n                  end\n    | _ => None\n  end.\n\nDefinition methodSigLookup(ms : list methodSig)(m : method_id) :=\n  let m_eq m mtd := match mtd with\n                      | MethodSig m' _ _ => beq_nat m m'\n                    end\n  in\n  find (m_eq m) ms.\n\nDefinition extractSigs(ms : list methodDecl) :=\n  let extract := fun mtd => match mtd with\n                              | Method m param t e => MethodSig m param t\n                            end\n  in\n  map extract ms.\n\nInductive methodSigs(P : program) : ty -> list methodSig -> Prop :=\n  | MSigs_Class :\n      forall c i fs ms,\n        classLookup P c = Some (Cls c i fs ms) ->\n        methodSigs P (TClass c) (extractSigs ms)\n  | MSigs_Interface :\n      forall i msigs,\n        interfaceLookup P i = Some (Interface i msigs) ->\n        methodSigs P (TInterface i) msigs\n  | MSigs_ExtInterface :\n      forall i i1 i2 msigs1 msigs2,\n        interfaceLookup P i = Some (ExtInterface i i1 i2) ->\n        methodSigs P (TInterface i1) msigs1 ->\n        methodSigs P (TInterface i2) msigs2 ->\n        methodSigs P (TInterface i) (msigs1 ++ msigs2)\n  | MSigs_Unit :\n      methodSigs P TUnit [].\n\n\nFixpoint declsToFields (l : list fieldDecl) :=\n  match l with\n    | nil => empty\n    | fd :: fs =>\n      match fd with\n        | Field f _ =>\n          extend (declsToFields fs) f VNull\n      end\n  end.", "meta": {"author": "EliasC", "repo": "oolong", "sha": "f449d42f70da1c404883860296ec4f2c5ed088b7", "save_path": "github-repos/coq/EliasC-oolong", "path": "github-repos/coq/EliasC-oolong/oolong-f449d42f70da1c404883860296ec4f2c5ed088b7/coq/assert/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23194161390836882}}
{"text": "(* -*- mode: coq -*- *)\n(* Time-stamp: <2014/8/23 21:0:44> *)\n(*\n  substitute.v \n  - mathink : Author\n *)\n\n(* Program libraries for [Program] *)\n(* Map Skelton *)\nRequire Import\nSsreflect.ssreflect\nSsreflect.ssrfun\nSsreflect.ssrbool\nSsreflect.eqtype.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nRequire Import MSL.lambda.\n\nDelimit Scope map with map_scope.\nOpen Scope map_scope.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* Notations for Maybe *)\nDefinition bind {X Y: Type}(f: X -> option Y)(m: option X): option Y :=\n  if m is Some x then f x else None.\nNotation emb := Some.\nNotation \"m >>= f\" := (bind f m) (at level 65, left associativity).\nNotation \"m >> p\" := (bind (fun _ => p) m) (at level 65, left associativity).\nNotation \"x <- m ; p\" := (m >>= fun x => p) (at level 60, right associativity).\nNotation \"(: x , y :) <- m ; p\" := (m >>= fun tup:_*_ => let: (x,y) := tup in p) (at level 60, right associativity).\nNotation \"'do' m\" := m (at level 100, right associativity).\nNotation \"'mlet' x := m ; p\" := (x <- emb m ; p) (at level 60, right associativity).\n\nSection HoleFilling.\n  Open Scope map_scope.\n  Context {T: eqType}.\n\n  Notation \"[=]\" := (box T).\n  Let sexp := sexp T.\n  Let lambda := lambda T.\n\n  Arguments asL {T}(s H): rename.\n\n  Check (fun s (b: is_true (wfb 0 s)) =>(elimT (wfbP 0 s) b)).\n  Notation \"[ 'L' s | b ]\" :=\n    (Lam (introT (isLbP s) (elimT (isLbP s) b)))\n  (at level 0, format \"[ 'L' s | b ]\"): map_scope.\n  Notation \"'L.' s\" := (asL s _)\n  (at level 0, format \"'L.' s\"): map_scope.\n  Notation \"[ 'S' M ]\" := (body M)\n  (at level 0, format \"[ 'S' M ]\"): map_scope.\n  Notation \"'S.' M\" := (body M)\n  (at level 0, format \"'S.' M\"): map_scope.\n  Definition asL (s: sexp): 0#s -> lambda :=\n    fun H => Lam (introT (isLbP s) (wf_sexp_is_lambda H)).\n\n  Fixpoint HF_aux (P: lambda)(m: map)(s: sexp){struct s}: option sexp :=\n    match m, s with\n      | 1, box => Some S.P\n      | 0, box => Some [=]\n      | 0, free x => Some (free x)\n      | 1, free x => None\n      | 0, M@N =>\n       match HF_aux P 0 M, HF_aux P 0 N with\n         | Some MmP, Some NnP  => Some (MmP@NnP)\n         | _, _  => None end\n      | minl m, M@N =>\n       match HF_aux P m M, HF_aux P 0 N with\n         | Some MmP, Some NnP  => Some (MmP@NnP)\n         | _, _  => None end\n      | minr n, M@N =>\n       match HF_aux P 0 M, HF_aux P n N with\n         | Some MmP, Some NnP  => Some (MmP@NnP)\n         | _, _  => None end\n      | mcons m n, M@N =>\n       match HF_aux P m M, HF_aux P n N with\n         | Some MmP, Some NnP  => Some (MmP@NnP)\n         | _, _  => None end\n      | m, n\\N =>\n        if wfb n N && orthb n m then\n          if HF_aux P m N is Some NmP then Some (n\\NmP) else None\n        else None\n      |  _,_  => None\n    end.\n\n  Functional Scheme HF_aux_ind := Induction for HF_aux Sort Prop.\n\n  Lemma HF_0 M (P: lambda): 0#M -> emb M = HF_aux P 0 M.\n  Proof.\n    elim: M => [x||M1 IH1 M2 IH2|m M IH] Hwf //=.\n    - rewrite -mapp_00_0 in Hwf; inversion Hwf; subst.\n      rewrite H; rewrite -mapp_00_0 in H.\n      by move: H H2 H3 => /eqP; rewrite mapp_injective;\n        move=> /andP [/eqP -> /eqP ->] H1 H2;\n          rewrite -(IH1 H1) -(IH2 H2). 2!emb_bind //=.\n    - rewrite orthb_symm //= andbT.\n      inversion Hwf; subst.\n      by move: H3 => /wfbP ->; rewrite -(IH H1).\n  Qed.\n      \n(*   Lemma orth_wf_HF_wf m1 m2 t t1 P: *)\n(*     m1!m2 -> m1#t -> emb t1 = HF_aux P m1 t -> m2#t1. *)\n(*   Proof. *)\n(*     move: m2 t1. *)\n(*     pattern (HF_aux P m1 t); apply HF_aux_ind => // m0 s0. *)\n(*     - move=> _{m0} x _{s0} m s Hor Hwf [] -> //=. *)\n(*       inversion Hor. *)\n(*     elim/HF_aux_ind: P t /(HF_aux P m1 t). *)\n(* Check HF_aux_ind. *)\n(*     elim=> [m|n|m n m' n' Ho IH Ho' IH'] Hwf Heq /=. *)\n(*     - elim: t m Hwf Heq => [x||s1 IHs1 s2 IHs2|m s1 IH] /=. *)\n(*       + move=> m Hwfm; inversion Hwfm; subst. *)\n(*         by move=> Heq; apply emb_mono in Heq; subst. *)\n(*       + move=> m Hwfm; inversion Hwfm; subst. *)\n(*         * by move=> Heq; apply emb_mono in Heq; subst. *)\n(*         * move=> Heq; apply emb_mono in Heq; subst. *)\n(*           apply lambda_is_wf. *)\n(*       + move=> m Hwfm; inversion Hwfm; subst. *)\n(*         destruct m0, n; simpl in *. *)\n(*         * rewrite -(HF_0 _ H2) -(HF_0 _ H3) 2!emb_bind; *)\n(*           by move=> Heq; apply emb_mono in Heq; move: Heq => ->. *)\n(*         * rewrite -(HF_0 _ H2) emb_bind. *)\n\n  Lemma HF_aux_wf s m P:\n    m#s -> exists t: sexp, emb t = HF_aux P m s/\\isLb t.\n  Proof.\n    elim=> [y|||m1 m2 s1 s2 H1 IH1 H2 IH2|m1 m2 t H1 IH1 H2 IH2 Horth] .\n    - exists (free y); repeat split; constructor.\n    - by exists [=]; repeat split; constructor.\n    - by exists (S.P); repeat split; try constructor; destruct P.\n    - move: IH1 IH2 => [t1 [Heq1 HL1]] [t2 [Heq2 HL2]].\n      exists (t1@t2).\n      destruct m1, m2; simpl in *;\n      (rewrite -Heq1 -Heq2;\n       repeat split; try done; last by apply /andP; split).\n    - move: IH1 IH2 => [t1 [Heq1 HL1]] [t2 [Heq2 HL2]].\n      exists (m2\\t1); split.\n      + simpl HF_aux.\n        rewrite -Heq1 /=.\n        case: (m2!P m1) => [Hor|Hnor]; rewrite ?andbT ?andbF.\n        * case: (m2#P t) => [Hwf|Hnwf]; rewrite ?andbT.\n          clear Heq1 H1 Horth Hor.\n          destruct m1; try done.\n          destruct m0; try done.\n        * destruct m1; try done.\n      + apply orth_symm in Horth; contradiction.\n    - apply/isLbP; apply labs; first by apply/isLbP.\n  (* have: m1!m2 -> m1#t -> emb t1 = HF_aux t m1 P -> m2#t1 *)\n      Abort.\n  Qed.\n\n  Notation \"[ M '_' m { P } ]\" := (HF_ M m P).\n\n\n  Program Fixpoint HoleFill (s: sexp)(m: map)(s: lambda): F lambda :=\n    match M , m return F lambda with\n      | Lam (free x) _, 0 => emb L.(free x)\n      | Lam box _, 1 => emb P\n      | Lam box _, 0 => emb L.[]\n      | Lam (M@N) H, 0 =>\n        do mlet m := 0;\n           mlet n := 0;\n           MmP <- HoleFill L.M m P;\n           NnP <- HoleFill L.N n P;\n           emb L.(S.MmP @ S.NnP)\n      | _, _ => failure lambda\n    end; try by constructor.\n    Proof.\n      - rewrite -mapp_00_0; apply wf_mapp_app; apply lambda_is_wf.\n      - move: H => /isLbP.\n        destruct term.\napply lambda_is_wf.\n\n      | M@N, minl m =>\n        do mlet n := 0;\n           MmP <- HoleFill L.M m P;\n           NnP <- HoleFill L.N n P;\n           emb L.(S.MmP @ S.NnP)\n      | M@N, minr n =>\n        do mlet m := 0;\n           MmP <- HoleFill M m P;\n           NnP <- HoleFill N n P;\n           emb (MmP@NnP)\n       | M@N, mcons m n =>\n         do MmP <- HoleFill M m P;\n            NnP <- HoleFill N n P;\n            emb (MmP@NnP)\n       | n\\N, m =>\n         do NmP <- HoleFill N m P;\n            emb (n\\NmP)\n      | _, _ => failure lambda\n    end).\n          | _,_ => failure sexP\n        end.\n\n      Notation \"[ M '_' m { P } ]\" := (HoleFill M m P).\n\n      (*      Lemma wf_wf m x: 0#x -> m#x.\n      Proof.\n        move=> H0x; move: x H0x m.\n        elim=> [y||s IHs t IHt|m s IHs] Hwf m'; try constructor. *)\n\n      (* Lemma HoleFill_wf m M N: *)\n      (*   (exists x, emb x = HoleFill M m N) -> m#M. *)\n\n      Lemma HoleFill_wf m M N:\n        m#M -> 0#N -> exists x, 0#x /\\ emb x = HoleFill M m N.\n      Proof.\n        move=> HmM H0N.\n        elim: HmM =>  //= [x||\n                          | m1 m2 s t H1 IH1 H2 IH2\n                          | m1 m2 s H1 IH1 H2 IH2] /=.\n        - exists (free x); split; try by constructor.\n        - exists box; split; try by constructor.\n        - exists N; split; done.\n          move: IH1 IH2 => [x1 [Hx1 Heq1]] [x2 [Hx2 Heq2]] /=.\n          exists (x1@x2); split;\n          first (rewrite -mapp_00_0; apply wf_mapp_app; done).\n          case: m1 H1 Heq1 => /=.\n          + case: m2 H2 Heq2 => /=.\n            * move=> _ Heq1 _ Heq2.\n                by rewrite emb_bind emb_bind\n                   -Heq1 -Heq2 emb_bind emb_bind.\n            * move=> m' _ Heq1 _ Heq2.\n                by rewrite emb_bind -Heq1 -Heq2 emb_bind emb_bind.\n          + case: m2 H2 Heq2 => /=.\n            * move=> _ Heq1 n' _ Heq2.\n                by rewrite emb_bind -Heq1 -Heq2 emb_bind emb_bind.\n            * move=> m' _ Heq1 n' _ Heq2.\n                by rewrite -Heq1 -Heq2 emb_bind emb_bind.\n        - move: IH1 IH2 => [x1 [Hx1 Heq1]] [x2 [Hx2 Heq2]] Horth.\n          rewrite -Heq1 emb_bind.\n          exists (m2\\x1); split; last done.\n          apply wf_abs; first done; try by constructor.\n          (*   Heq2 : emb x2 = [s _ m2 {N}] means m2#x1 *)\n\n      Fixpoint mapf (x: T)(s: sexp): map :=\n        match s with\n          | free y => if x == y then 1 else 0\n          | box => 0\n          | M@N => mapf x M*mapf x N\n          | m\\M => mapf x M\n        end.\n\n      Fixpoint skelf (x: T)(s: sexp): sexp :=\n        match s with\n          | free y => if x == y then box else free y\n          | box => box\n          | M@N => skelf x M@skelf x N\n          | m\\M => m\\skelf x M\n        end.\n\n      Definition lam (x: T)(M: sexp) := mapf x M\\skelf x M.\n\n      Lemma mapp_0 m n: m*n = 0 -> m = 0 /\\ n = 0.\n      Proof.\n        case: m => [|m] /=; case: n => [| n] /=; try done.\n      Qed.\n\n      Lemma wf_skelf m x s: m#s -> m#skelf x s.\n      Proof.\n        elim=> [y|||m1 m2 s1 s2 H1 IH1 H2 IH2|m1 m2 t H1 IH1 H2 IH2 H] /=;\n          try by constructor.\n        - case: (x == y) => /=; try by constructor.\n      Qed.\n\n\n(*      Lemma orth_mapf m x s: 0#s -> 0!m -> (mapf x s)!m.\n        elim: s => [y||s IHs t IHt|n s IHs] /= Hwf Horth;\n                  try by constructor.\n        - case: (x == y) => /=; try by constructor.\n          simpl.\n        move=> Horth; move: Horth x s.\n        elim=> [m'|n'|m1 n1 m2 n2 H1 IH1 H2 IH2] x s; try by constructor.\n      Lemma orth_mapf m x s: 0!m -> mapf x s!m.\n      Proof.\n        move=> Horth; move: Horth x s.\n        elim=> [_|n|m1 n1 m2 n2 H1 IH1 H2 IH2]; try by constructor.\n        - case: (x == y) => /=; try by constructor.\n      Qed.\n       *)\n\n      (*\n      Lemma map_skeleton_aux:\n        forall x m M,\n          m#M ->\n          m*mapf x M # skelf x M -> mapf x M # m\\skelf x M.\n      Proof.\n        move=> x m M Hwf.\n        elim: Hwf => [y||\n                     |m1 m2 s1 s2 H1 IH1 H2 IH2\n                     |m1 m2 s H1 IH1 H2 IH2 Horth] /=;\n          try by constructor.\n        - case: (x == y) => /=; try by constructor.\n          + move=> H; inversion H.\n          + move=> H; inversion H.\n            apply wf_abs; try by constructor.\n        - move=> H; apply wf_abs; try by constructor.\n        - move=> H; apply wf_abs; try by constructor.\n        - move=> H; inversion H; subst.\n          move: H3 => /eqP; rewrite mapp_injective;\n            move=> -/andP [-/eqP Heq1 -/eqP Heq2]; subst.\n          apply wf_abs; try done.\n          apply wf_mapp_app; try done.\n          + apply wf_mapp_app; try done.\n\n\n        move=> x m M; simpl; auto.\n      Qed.\n       *)\n\n      Definition substitute (M: sexp)(x: T)(p: sexp) :=\n        HoleFill (skelf x M) (mapf x M) p.\n\n      Lemma substitute_app M N x P:\n        substitute (M@N) x P = do MxP <- substitute M x P;\n                                  NxP <- substitute N x P;\n                                  emb (MxP@NxP).\n      Proof.\n        rewrite /substitute //=.\n        case: (mapf x M) => //=.\n        - case: (mapf x N) => //=.\n          + by rewrite emb_bind emb_bind.\n          + by move=> m; rewrite emb_bind.\n        - move=> m.\n          case: (mapf x N) => //=.\n          + by rewrite emb_bind.\n      Qed.\n\n      Lemma substitute_abs m M x P:\n        substitute (m\\M) x P = do MxP <- substitute M x P;\n                                  emb (m\\MxP).\n      Proof.\n        rewrite /substitute //=.\n      Qed.\n\n\n      Lemma fresh_on_skelf x P:\n        fresh_on x P -> skelf x P = P.\n      Proof.\n        elim: P => //= [y|s IHs t IHt| m s IHs] /=.\n        - apply ifN_eq.\n        - by move=> /andP [Hs Ht]; rewrite (IHs Hs) (IHt Ht).\n        - by move=> H; rewrite (IHs H).\n      Qed.\n\n      Lemma fresh_on_mapf x P:\n        fresh_on x P -> mapf x P = 0.\n      Proof.\n        elim: P => //= [y|s IHs t IHt] /=.\n        - apply ifN_eq.\n        - by move=> /andP [Hs Ht]; rewrite (IHs Hs) (IHt Ht).\n      Qed.\n\n      Lemma HF_0 P M: emb P = HoleFill P 0 M.\n      Proof.\n        { elim: P => [x||s IHs t IHt|m s IHs] //=.\n          - rewrite emb_bind emb_bind //= -IHs -IHt.\n            rewrite emb_bind emb_bind //=.\n          - by rewrite -IHs emb_bind. }\n      Qed.\n\n      Lemma substitute_lemma x y P M N:\n        x <> y -> fresh_on x P ->\n        (do MxN <- substitute M x N;\n            substitute MxN y P)\n        =\n        (do MyP <- substitute M y P;\n            NyP <- substitute N y P;\n            substitute MyP x NyP).\n      Proof.\n        move=> Hneq Hfresh.\n        rewrite /substitute; induction M; move=> //=.\n        - case Hxx0: (x == x0) => //=.\n          + rewrite emb_bind //=.\n            case Hyy0: (y == x0) => //=.\n            * move: Hxx0 Hyy0 => /eqP Hxx0 /eqP Hyy0 //=; subst.\n                by elim Hneq.\n            * by rewrite emb_bind //= Hxx0 //= bind_emb.\n          + rewrite emb_bind //=.\n            case Hyy0: (y == x0) => //=.\n            * rewrite emb_bind //=.\n              rewrite (fresh_on_mapf Hfresh)\n                      (fresh_on_skelf Hfresh) //=.\n              { elim: N => [x1||s IHs t IHt| m s IHs] //=.\n                - case Hyx1: (y == x1) => //=.\n                  + rewrite emb_bind.\n                    apply: (HF_0 P P).\n                  + rewrite emb_bind.\n                    apply: (HF_0 P _).\n                - rewrite emb_bind.\n                  apply: (HF_0 P _).\n                - destruct (mapf y s); simpl.\n                  + destruct (mapf y t); simpl.\n                    * rewrite emb_bind emb_bind.\n                      by rewrite -(HF_0 _ P) -(HF_0 _ P)\n                        emb_bind emb_bind emb_bind -(HF_0 _ _).\n                    * rewrite emb_bind -(HF_0 _ _) emb_bind //=.\n                      rewrite bind_assoc IHt.\n                      apply bind_subst; try done.\n                      by move=> x1;\n                          rewrite emb_bind -(HF_0 _ _) -(HF_0 _ _).\n                  + destruct (mapf y t); simpl.\n                    * rewrite emb_bind bind_assoc IHs.\n                      apply bind_subst; try done.\n                      move=> x1.\n                      rewrite bind_assoc -(HF_0 _ _) IHt.\n                      apply bind_subst; try done.\n                      move=> x2.\n                      by rewrite emb_bind -(HF_0 _ _) -(HF_0 _ _).\n                    * rewrite bind_assoc IHs.\n                      apply bind_subst; try done.\n                      move=> x1.\n                      rewrite bind_assoc -(HF_0 _ _) IHt.\n                      apply bind_subst; try done.\n                      move=> x2.\n                      by rewrite emb_bind -(HF_0 _ _) -(HF_0 _ _).\n                - rewrite bind_assoc IHs.\n                  apply bind_subst; try done.\n                  move=> x1.\n                    by rewrite emb_bind -(HF_0 _ _) -(HF_0 _ _). }\n            * rewrite emb_bind //= Hxx0 /=.\n              ", "meta": {"author": "mathink", "repo": "mslambda", "sha": "0e9c9fb79193bc5e29c28aa024452770ed4eaa99", "save_path": "github-repos/coq/mathink-mslambda", "path": "github-repos/coq/mathink-mslambda/mslambda-0e9c9fb79193bc5e29c28aa024452770ed4eaa99/substitute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23194161390836876}}
{"text": "Require Import compcert.backend.Cminor.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Errors.\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Integers.\nRequire Import compcert.lib.Maps.\nRequire Import InetDiag.\nRequire Import InetDiagConf.\nImport ListNotations.\n\nOpen Local Scope error_monad_scope.\n\nDefinition reg_entry: ident := 1%positive.\n\nDefinition transl_load_field (f: field) : Cminor.expr :=\n  match f with\n  | (ty, offset) =>\n    let addr := Ebinop Oadd (Evar reg_entry) (Econst (Ointconst offset)) in\n    Eload ty addr\n  end.\n\nDefinition transl_jmp (loc: location) (nextlbl: nat) : Cminor.stmt :=\n  match loc with\n  | Reject => Sreturn (Some (Econst (Ointconst Int.zero)))\n  | Loc n => Sgoto (P_of_succ_nat (nextlbl - n - 1))\n  end.\n\nDefinition transl_cond (cond: InetDiag.condition) :=\n  let v := transl_load_field (cond_field cond) in\n  match cond with\n  | Sge p => Ebinop (Ocmpu Cge) v (Econst (Ointconst p))\n  | Sle p => Ebinop (Ocmpu Cle) v (Econst (Ointconst p))\n  | Dge p => Ebinop (Ocmpu Cge) v (Econst (Ointconst p))\n  | Dle p => Ebinop (Ocmpu Cle) v (Econst (Ointconst p))\n  end.\n\nDefinition transl_instr (instr: instruction) (nextlbl: nat) : Cminor.stmt :=\n  match instr with\n  | Nop => Sskip\n  | Jmp loc => transl_jmp loc nextlbl\n  | Cjmp cond loc => Sifthenelse (transl_cond cond) Sskip (transl_jmp loc nextlbl)\n  end.\n\nFixpoint transl_code (c: code) : res Cminor.stmt :=\n  match c with\n  | nil => OK (Sreturn (Some (Econst (Ointconst Int.one))))\n  | instr :: rest =>\n    let n := length rest in\n    do ts <- transl_code rest;\n    let hs := transl_instr instr (S n) in\n    OK (Sseq hs (Slabel (P_of_succ_nat n) ts))\n  end.\n\nDefinition transl_function (f: function) : res Cminor.function :=\n  do body <- transl_code f;\n  let params := [ reg_entry ] in\n  let vars := [] in\n  let stackspace := 0 in\n  OK (Cminor.mkfunction signature_main params vars stackspace body).\n\nDefinition transl_fundef (fd: fundef) : res Cminor.fundef :=\n  match fd with\n  | Internal f => do f' <- transl_function f; OK (Internal f')\n  | External f => Error (msg \"no external function allowed\")\n  end.\n\nDefinition transl_program (p: program) : res Cminor.program :=\n  transform_partial_program transl_fundef p.\n\nDefinition example1 :=\n  [ Cjmp (Sge (Int.repr 21)) Reject\n  ; Cjmp (Sge (Int.repr 1024)) (Loc 1)\n  ; Jmp Reject\n  ; Nop\n  ].\n", "meta": {"author": "utokyo-lzh", "repo": "Jitk", "sha": "7f7f6eb541c7e8a2613974fff5b4fc6fc0783182", "save_path": "github-repos/coq/utokyo-lzh-Jitk", "path": "github-repos/coq/utokyo-lzh-Jitk/Jitk-7f7f6eb541c7e8a2613974fff5b4fc6fc0783182/InetDiagJit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23184220331106556}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Rewriter.Language.Language.\nRequire Import Crypto.Language.API.\nRequire Import Rewriter.Language.Wf.\nRequire Import Crypto.Language.WfExtra.\nRequire Import Crypto.Rewriter.AllTacticsExtra.\nRequire Import Crypto.Rewriter.RulesProofs.\n\nModule Compilers.\n  Import Language.Compilers.\n  Import Language.API.Compilers.\n  Import Language.Wf.Compilers.\n  Import Language.WfExtra.Compilers.\n  Import Rewriter.AllTacticsExtra.Compilers.RewriteRules.GoalType.\n  Import Rewriter.AllTactics.Compilers.RewriteRules.Tactic.\n  Import Compilers.Classes.\n\n  Module Import RewriteRules.\n    Section __.\n      Context (which_bitwidths : list Z).\n\n      Definition VerifiedRewriterRelaxBitwidthAdcSbb : VerifiedRewriter_with_args false false true (relax_bitwidth_adc_sbb_rewrite_rules_proofs which_bitwidths).\n      Proof using All. make_rewriter. Defined.\n\n      Definition default_opts := Eval hnf in @default_opts VerifiedRewriterRelaxBitwidthAdcSbb.\n      Let optsT := Eval hnf in optsT VerifiedRewriterRelaxBitwidthAdcSbb.\n\n      Definition RewriteRelaxBitwidthAdcSbb (opts : optsT) {t : API.type} := Eval hnf in @Rewrite VerifiedRewriterRelaxBitwidthAdcSbb opts t.\n\n      Lemma Wf_RewriteRelaxBitwidthAdcSbb opts {t} e (Hwf : Wf e) : Wf (@RewriteRelaxBitwidthAdcSbb opts t e).\n      Proof. now apply VerifiedRewriterRelaxBitwidthAdcSbb. Qed.\n\n      Lemma Interp_RewriteRelaxBitwidthAdcSbb opts {t} e (Hwf : Wf e) : expr.Interp (@Compilers.ident_interp) (@RewriteRelaxBitwidthAdcSbb opts t e) == expr.Interp (@Compilers.ident_interp) e.\n      Proof. now apply VerifiedRewriterRelaxBitwidthAdcSbb. Qed.\n    End __.\n  End RewriteRules.\n\n  Module Export Hints.\n#[global]\n    Hint Resolve Wf_RewriteRelaxBitwidthAdcSbb : wf wf_extra.\n#[global]\n    Hint Opaque RewriteRelaxBitwidthAdcSbb : wf wf_extra interp interp_extra rewrite.\n#[global]\n    Hint Rewrite @Interp_RewriteRelaxBitwidthAdcSbb : interp interp_extra.\n  End Hints.\nEnd Compilers.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Rewriter/Passes/RelaxBitwidthAdcSbb.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.23184220331106553}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Import terms2.\n\n\nLemma deq_nvar_refl :\n  forall v, deq_nvar v v = left eq_refl.\nProof.\n  introv.\n  destruct (deq_nvar v v); sp.\n  generalize (@UIPReflDeq NVar deq_nvar v e); intro k.\n  rw k; auto.\nQed.\n\nLtac boolvar_step :=\n  match goal with\n    | [ |- context[beq_var ?v ?v] ] => rewrite <- beq_var_refl\n    | [ |- context[deq_nvar ?v ?v] ] => rewrite deq_nvar_refl\n    | [ |- context[deq_nvar ?v1 ?v2] ] =>\n      destruct (deq_nvar v1 v2);[try(subst v1)|];try(complete auto)\n    | [ |- context[memvar ?v ?s] ] =>\n        let name := fresh \"b\" in\n          remember (memvar v s) as name;\n        match goal with\n          | [ H : name = memvar v s |- _ ] =>\n              symmetry in H;\n              destruct name;\n              [ rewrite fold_assert in H;\n                  trw_h assert_memvar H;\n                  simpl in H\n              | trw_h not_of_assert H;\n                  trw_h assert_memvar H;\n                  simpl in H\n              ]\n        end\n    | [ |- context[beq_var ?v1 ?v2] ] =>\n        let name := fresh \"b\" in\n          remember (beq_var v1 v2) as name;\n        match goal with\n          | [ H : name = beq_var v1 v2 |- _ ] =>\n            destruct name;\n              [ apply beq_var_true in H; try subst\n              | apply beq_var_false in H\n              ]\n        end\n\n    | [ H : context[beq_var ?v ?v] |- _ ] => rewrite <- beq_var_refl in H\n    | [ H : context[deq_nvar ?v ?v] |- _ ] => rewrite deq_nvar_refl in H\n    | [ H : context[deq_nvar ?v1 ?v2] |- _ ] =>\n      destruct (deq_nvar v1 v2);[try(subst v1)|];try(complete auto)\n    | [ H : context[memvar ?v ?s] |- _ ] =>\n      let name := fresh \"b\" in\n      remember (memvar v s) as name;\n        match goal with\n          | [ J : name = memvar v s |- _ ] =>\n            symmetry in J;\n              destruct name;\n              [ rewrite fold_assert in J;\n                trw_h assert_memvar J;\n                simpl in J\n              | trw_h not_of_assert J;\n                trw_h assert_memvar J;\n                simpl in J\n              ]\n        end\n    | [ H : context[beq_var ?v1 ?v2] |- _ ] =>\n        let name := fresh \"b\" in\n        remember (beq_var v1 v2) as name;\n          match goal with\n            | [ J : name = beq_var v1 v2 |- _ ] =>\n              destruct name;\n                [ apply beq_var_true in J; try subst\n                | apply beq_var_false in J\n                ]\n          end\n\n    | [ |- context[if ?x then _ else _] ] =>\n      match type of x with\n        | {_} + {_} => destruct x\n      end\n    | [ |- context[if ?x then _ else _] ] =>\n      match type of x with\n        | sum _ _ => destruct x\n      end\n    | [ |- context[if ?x then _ else _] ] =>\n      match type of x with\n        | decidable _ => destruct x\n      end\n    | [ |- context[d2b ?x] ] =>\n      match type of x with\n        | decidable _ => destruct x\n      end\n\n    | [H : context[if ?x then _ else _] |- _ ] =>\n      match type of x with\n        | {_} + {_} => destruct x\n      end\n    | [H : context[if ?x then _ else _] |- _ ] =>\n      match type of x with\n        | sum _ _ => destruct x\n      end\n    | [H : context[if ?x then _ else _] |- _ ] =>\n      match type of x with\n        | decidable _ => destruct x\n      end\n    | [H : context[d2b ?x] |- _ ] =>\n      match type of x with\n        | decidable _ => destruct x\n      end\n\n    | [ |- context[deq_nat           ?x ?y] ] => destruct (deq_nat           x y)\n    | [ |- context[String.string_dec ?x ?y] ] => destruct (String.string_dec x y)\n    | [ |- context[opsign_dec        ?x ?y] ] => destruct (opsign_dec        x y)\n    | [ |- context[Z_noteq_dec       ?x ?y] ] => destruct (Z_noteq_dec       x y)\n    | [ |- context[parameter_dec     ?x ?y] ] => destruct (parameter_dec     x y)\n    | [ |- context[parameters_dec    ?x ?y] ] => destruct (parameters_dec    x y)\n\n    | [ H : context[deq_nat           ?x ?y] |- _ ] => destruct (deq_nat           x y)\n    | [ H : context[String.string_dec ?x ?y] |- _ ] => destruct (String.string_dec x y)\n    | [ H : context[opsign_dec        ?x ?y] |- _ ] => destruct (opsign_dec        x y)\n    | [ H : context[Z_noteq_dec       ?x ?y] |- _ ] => destruct (Z_noteq_dec       x y)\n    | [ H : context[parameter_dec     ?x ?y] |- _ ] => destruct (parameter_dec     x y)\n    | [ H : context[parameters_dec    ?x ?y] |- _ ] => destruct (parameters_dec    x y)\n\n    | [ H : context[if memberb _ _ _ then _ else _] |- _ ] => rewrite memberb_din in H\n    | [ |- context[if memberb _ _ _ then _ else _] ] => rewrite memberb_din\n  end.\n\nLtac boolvar := repeat boolvar_step.\n\n\nLemma fold_mk_prod {o} :\n  forall (a : @NTerm o) v b,\n    v = newvar b\n    -> mk_product a v b = mk_prod a b.\nProof.\n  introv e; subst; sp.\nQed.\n\nLemma fold_mk_fun {o} :\n  forall (a : @NTerm o) v b,\n    v = newvar b\n    -> mk_function a v b = mk_fun a b.\nProof.\n  introv e; subst; sp.\nQed.\n\nLemma fold_mk_ufun {o} :\n  forall (a : @NTerm o) v b,\n    v = newvar b\n    -> mk_isect a v b = mk_ufun a b.\nProof.\n  introv e; subst; sp.\nQed.\n\nLemma int_zero {o} :\n  @mk_integer o 0 = mk_zero.\nProof. sp. Qed.\n\nDefinition absolute_value {o} (t : @NTerm o) :=\n  mk_less t mk_zero (mk_minus t) t.\n\nLtac fold_terms_step :=\n  match goal with\n    | [ |- context[@oterm ?p (Can NAxiom) []] ] => fold (@mk_axiom p)\n    | [ |- context[@oterm ?p (Can NInt) []] ] => fold (@mk_int p)\n    | [ |- context[@oterm ?p (Can (NUTok ?a)) []] ] => fold (@mk_utoken p a)\n    | [ |- context[@oterm ?p (Can (NTok ?a)) []] ] => fold (@mk_token p a)\n    | [ |- context[@mk_approx ?p mk_axiom mk_axiom] ] => fold (@mk_true p)\n    | [ |- context[@mk_approx ?p mk_axiom mk_bot] ] => fold (@mk_false p)\n    | [ |- context[@mk_lam ?p nvarx (mk_var nvarx)] ] => fold (@mk_id p)\n    | [ |- context[@mk_fix ?p mk_id] ] => fold (@mk_bottom p)\n    | [ |- context[@mk_bottom ?p] ] => fold (@mk_bot p)\n    | [ |- context[@bterm ?p [] ?x] ] => fold (@nobnd p x)\n    | [ |- context[@vterm ?p ?v] ] => fold (@mk_var p v)\n    | [ |- context[@oterm ?p (Can (Nint ?z)) []] ] => fold (@mk_integer p z)\n    | [ |- context[@mk_integer ?p (Z.of_nat ?n)] ] => fold (@mk_nat p n)\n    | [ |- context[@mk_nat ?p 0] ] => fold (@mk_zero p)\n    | [ |- context[@oterm ?p (Can (Nseq ?f)) []] ] => fold (@mk_nseq p f)\n    | [ |- context[oterm (Can NLambda) [bterm [?v] ?t]] ] => fold (mk_lam v t)\n    | [ |- context[oterm (Can NApprox) [nobnd ?a, nobnd ?b]] ] => fold (mk_approx a b)\n    | [ |- context[oterm (Can NEquality) [nobnd ?a, nobnd ?b, nobnd ?c]] ] => fold (mk_equality a b c)\n    | [ |- context[oterm (Can NFunction) [nobnd ?a, bterm [?v] ?b]] ] => fold (mk_function a v b)\n    | [ |- context[oterm (Can NProduct) [nobnd ?a, bterm [?v] ?b]] ] => fold (mk_product a v b)\n    | [ |- context[oterm (Can NUnion) [nobnd ?x, nobnd ?y]] ] => fold (mk_union x y)\n    | [ |- context[oterm (Can NTExc) [nobnd ?x, nobnd ?y]] ] => fold (mk_texc x y)\n    | [ |- context[oterm (NCan NApply) [nobnd ?x, nobnd ?y]] ] => fold (mk_apply x y)\n    | [ |- context[oterm (NCan NEApply) [nobnd ?x, nobnd ?y]] ] => fold (mk_eapply x y)\n    | [ |- context[oterm (NCan (NApseq ?f)) [nobnd ?x] ] ] => fold (mk_apseq f x)\n    | [ |- context[oterm (NCan NDecide) [nobnd ?d, bterm [?x] ?f, bterm [?y] ?g]] ] => fold (mk_decide d x f y g)\n    | [ |- context[oterm (NCan NSpread) [nobnd ?p, bterm [?x,?y] ?f]] ] => fold (mk_spread p x y f)\n    | [ |- context[oterm (NCan NTryCatch) [nobnd ?a, nobnd ?b, bterm [?v] ?c]] ] => fold (mk_try a b v c)\n    | [ |- context[oterm (NCan NFix) [nobnd ?x]] ] => unfold nobnd; fold (mk_fix x); try (fold nobnd)\n    | [ |- context[oterm (NCan NCbv) [nobnd ?a, bterm [?v] ?b]] ] => fold (mk_cbv a v b)\n    | [ |- context[oterm (NCan NFresh) [bterm [?v] ?b]] ] => fold (mk_fresh v b)\n    | [ |- context[oterm (NCan (NCompOp CompOpLess)) [nobnd ?a, nobnd ?b, nobnd ?c, nobnd ?d]] ] => fold (mk_less a b c d)\n    | [ |- context[oterm Exc [nobnd ?a, nobnd ?x]] ] => fold (mk_exception a x)\n    | [ |- context[oterm (Can NIsect) [nobnd ?a, bterm [?v] ?b] ] ] => fold (mk_isect a v b)\n    | [ |- context[oterm (Can NSet) [nobnd ?a, bterm [?v] ?b] ] ] => fold (mk_set a v b)\n    | [ |- context[oterm (NCan NMinus) [nobnd ?a] ] ] => fold (mk_minus a)\n    | [ |- context[mk_equality ?t ?t ?T] ] => fold (mk_member t T)\n    | [ |- context[mk_less ?t mk_zero (mk_minus ?t) ?t] ] => fold (absolute_value t)\n    | [ |- context[mk_less ?a ?b mk_true mk_false] ] => fold (mk_less_than a b)\n    | [ |- context[@mk_integer ?o 0] ] => rewrite (@int_zero o)\n    | [ |- context[@mk_false ?o] ] => fold (@mk_void o)\n    | [ |- context[mk_fun ?a mk_void] ] => fold (mk_not a)\n    | [ |- context[mk_not (mk_less_than ?b ?a)] ] => fold (mk_le a b)\n\n    | [ H : ?v = newvar ?b |- context[mk_product ?a ?v ?b] ] => rewrite (fold_mk_prod a v b H)\n    | [ H : ?v = newvar ?b |- context[mk_function ?a ?v ?b] ] => rewrite (fold_mk_fun a v b H); auto\n    | [ H : ?v = newvar ?b |- context[mk_isect ?a ?v ?b] ] => rewrite (fold_mk_ufun a v b H); auto\n\n    | [ H : context[@oterm ?p (Can NAxiom) []] |- _ ] => fold (@mk_axiom p) in H\n    | [ H : context[@oterm ?p (Can NInt) []] |- _ ] => fold (@mk_int p) in H\n    | [ H : context[@oterm ?p (Can (NUTok ?a)) []] |- _ ] => fold (@mk_utoken p a) in H\n    | [ H : context[@oterm ?p (Can (NTok ?a)) []] |- _ ] => fold (@mk_token p a) in H\n    | [ H : context[@mk_approx ?p mk_axiom mk_axiom] |- _ ] => fold (@mk_true p) in H\n    | [ H : context[@mk_approx ?p mk_axiom mk_bot] |- _ ] => fold (@mk_false p) in H\n    | [ H : context[@mk_lam ?p nvarx (mk_var nvarx)] |- _ ] => fold (@mk_id p) in H\n    | [ H : context[@mk_fix ?p mk_id] |- _ ] => fold (@mk_bottom p) in H\n    | [ H : context[@mk_bottom ?p] |- _ ] => fold (@mk_bot p) in H\n    | [ H : context[@bterm ?p [] ?x] |- _ ] => fold (@nobnd p x) in H\n    | [ H : context[@vterm ?p ?v] |- _ ] => fold (@mk_var p v) in H\n    | [ H : context[@oterm ?p (Can (Nint ?z)) []] |- _ ] => fold (@mk_integer p z) in H\n    | [ H : context[@mk_integer ?p (Z.of_nat ?n)] |- _ ] => fold (@mk_nat p n) in H\n    | [ H : context[@mk_nat ?p 0] |- _ ] => fold (@mk_zero p) in H\n    | [ H : context[@oterm ?p (Can (Nseq ?f)) []] |- _ ] => fold (@mk_nseq p f) in H\n    | [ H : context[oterm (Can NLambda) [bterm [?v] ?t]] |- _ ] => fold (mk_lam v t) in H\n    | [ H : context[oterm (Can NApprox) [nobnd ?a, nobnd ?b]] |- _ ] => fold (mk_approx a b) in H\n    | [ H : context[oterm (Can NEquality) [nobnd ?a, nobnd ?b, nobnd ?c]] |- _ ] => fold (mk_equality a b c) in H\n    | [ H : context[oterm (Can NFunction) [nobnd ?a, bterm [?v] ?b]] |- _ ] => fold (mk_function a v b) in H\n    | [ H : context[oterm (Can NProduct) [nobnd ?a, bterm [?v] ?b]] |- _ ] => fold (mk_product a v b) in H\n    | [ H : context[oterm (Can NUnion) [nobnd ?x, nobnd ?y]] |- _ ] => fold (mk_union x y) in H\n    | [ H : context[oterm (Can NTExc) [nobnd ?x, nobnd ?y]] |- _ ] => fold (mk_texc x y) in H\n    | [ H : context[oterm (NCan NApply) [nobnd ?x, nobnd ?y]] |- _ ] => fold (mk_apply x y) in H\n    | [ H : context[oterm (NCan NEApply) [nobnd ?x, nobnd ?y]] |- _ ] => fold (mk_eapply x y) in H\n    | [ H : context[oterm (NCan (NApseq ?f)) [nobnd ?x] ] |- _ ] => fold (mk_apseq f x) in H\n    | [ H : context[oterm (NCan NDecide) [nobnd ?d, bterm [?x] ?f, bterm [?y] ?g]] |- _ ] => fold (mk_decide d x f y g) in H\n    | [ H : context[oterm (NCan NSpread) [nobnd ?p, bterm [?x,?y] ?f]] |- _ ] => fold (mk_spread p x y f) in H\n    | [ H : context[oterm (NCan NTryCatch) [nobnd ?a, nobnd ?b, bterm [?v] ?c]] |- _ ] => fold (mk_try a b v c) in H\n    | [ H : context[oterm (NCan NFix) [nobnd ?x]] |- _ ] => unfold nobnd in H; fold (mk_fix x) in H; try (fold nobnd in H)\n    | [ H : context[oterm (NCan NCbv) [nobnd ?a, bterm [?v] ?b]] |- _ ] => fold (mk_cbv a v b) in H\n    | [ H : context[oterm (NCan NFresh) [bterm [?v] ?b]] |- _ ] => fold (mk_fresh v b) in H\n    | [ H : context[oterm (NCan (NCompOp CompOpLess)) [nobnd ?a, nobnd ?b, nobnd ?c, nobnd ?d]] |- _ ] => fold (mk_less a b c d) in H\n    | [ H : context[oterm Exc [nobnd ?a, nobnd ?x]] |- _ ] => fold (mk_exception a x) in H\n    | [ H : context[oterm (Can NIsect) [nobnd ?a, bterm [?v] ?b] ] |- _ ] => fold (mk_isect a v b) in H\n    | [ H : context[oterm (Can NSet) [nobnd ?a, bterm [?v] ?b] ] |- _ ] => fold (mk_set a v b) in H\n    | [ H : context[oterm (NCan NMinus) [nobnd ?a] ] |- _ ] => fold (mk_minus a) in H\n    | [ H : context[mk_equality ?t ?t ?T] |- _ ] => fold (mk_member t T) in H\n    | [ H : context[mk_less ?t mk_zero (mk_minus ?t) ?t] |- _ ] => fold (absolute_value t) in H\n    | [ H : context[mk_less ?a ?b mk_true mk_false] |- _ ] => fold (mk_less_than a b) in H\n    | [ H : context[@mk_integer ?o 0] |- _ ] => rewrite (@int_zero o) in H\n    | [ H : context[@mk_false ?o] |- _ ] => fold (@mk_void o) in H\n    | [ H : context[mk_fun ?a mk_void] |- _ ] => fold (mk_not a) in H\n    | [ H : context[mk_not (mk_less_than ?b ?a)] |- _ ] => fold (mk_le a b) in H\n\n    | [ H : ?v = newvar ?b, J : context[mk_product ?a ?v ?b] |- _ ] => rewrite (fold_mk_prod a v b H) in J; auto\n    | [ H : ?v = newvar ?b, J : context[mk_function ?a ?v ?b] |- _ ] => rewrite (fold_mk_fun a v b H) in J; auto\n    | [ H : ?v = newvar ?b, J : context[mk_isect ?a ?v ?b] |- _ ] => rewrite (fold_mk_ufun a v b H) in J; auto\n\n  end.\n\nLtac fold_terms := repeat fold_terms_step.\n", "meta": {"author": "coq-contribs", "repo": "intuitionistic-nuprl", "sha": "6279ed83244dc4aec2e23ffb4c87e3f10a50326d", "save_path": "github-repos/coq/coq-contribs-intuitionistic-nuprl", "path": "github-repos/coq/coq-contribs-intuitionistic-nuprl/intuitionistic-nuprl-6279ed83244dc4aec2e23ffb4c87e3f10a50326d/terms_tacs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2318422033110655}}
{"text": "From iris.algebra Require Import agree auth gmap.\nFrom iris.proofmode Require Import proofmode.\nRequire Import Eqdep_dec List.\nFrom cap_machine Require Import macros_helpers addr_reg_sample macros_new.\nFrom cap_machine Require Import rules logrel contiguous fundamental.\nFrom cap_machine Require Import arch_sealing interval_arch malloc interval_closure_arch.\nFrom cap_machine Require Import solve_pure proofmode map_simpl register_tactics.\n\nSection interval_client.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ} {sealg: sealStoreG Σ}\n          {nainv: logrel_na_invs Σ}\n          `{MP: MachineParameters}.\n\n  (* r_t1 : interval input *)\n  (* r_env : capability containing the three entry points: makeint, imin, imax *)\n  (* pc_b : environment table containing the assert subroutine *)\n  Definition check_interval f_a :=\n    encodeInstrsW [ Mov r_temp1 r_t1;\n                  Mov r_temp2 r_env;\n                  Mov r_temp3 r_t0;\n                  (* load imin subroutine *)\n                  Lea r_env 1;\n                  Load r_t2 r_env;\n                  (* jmp to imin *)\n                  Mov r_t0 PC;\n                  Lea r_t0 3;\n                  Jmp r_t2;\n                  (* copy the result *)\n                  Mov r_temp4 r_t1;\n                  (* load imax subroutine *)\n                  Lea r_temp2 2;\n                  Load r_t2 r_temp2;\n                  (* jmp to imax *)\n                  Mov r_t1 r_temp1;\n                  Mov r_t0 PC;\n                  Lea r_t0 3;\n                  Jmp r_t2;\n                  (* compare the two results *)\n                  Lt r_t4 r_t1 r_temp4; (* if r_t1 is 1 then z2 < z1, and the assert should fail *)\n                  Mov r_t5 0]\n                  ++ assert_instrs f_a ++ (* assert (r_t4 = r_t5) *)\n                  (* register cleanup*)\n    encodeInstrsW [ Mov r_temp1 0;\n                  Mov r_temp2 0;\n                  Mov r_t0 r_temp3;\n                  Mov r_temp3 0;\n                  Mov r_t20 0;\n                  Mov r_t1 0;\n                  Mov r_t2 0;\n                  Jmp r_t0 ].\n\n  (* the interval library environment must contain:\n   (1) the activation code for makeint, imax, imin\n   (2) a linking table with the assert subroutine *)\n\n  (* the subroutines for makeint imax and imin will be\n     in separate invariants. So will the relevant parts of its environment table *)\n\n  Definition interval_env d1 d4 benv0 eenv p b e a f_m b1 e1 b2 e2 b3 e3: iProp Σ :=\n    (∃ d2 d3, ⌜(d1 + 1 = Some d2 ∧ d2 + 1 = Some d3 ∧ d3 + 1 = Some d4)%a⌝\n          ∗ d1 ↦ₐ WCap E b1 e1 b1\n          ∗ d2 ↦ₐ WCap E b2 e2 b2\n          ∗ d3 ↦ₐ WCap E b3 e3 b3 ∗\n          let wvar := WCap RWX benv0 eenv benv0 in\n          let wcode1 := WCap p b e a in\n          let wcode2 := WCap p b e (a ^+ length (makeint f_m))%a in\n          let wcode3 := WCap p b e (a ^+ length (makeint f_m) ^+ length (imin))%a in\n          ⌜(b1 + 8)%a = Some e1 ∧ (b2 + 8)%a = Some e2 ∧ (b3 + 8)%a = Some e3⌝\n          ∗ ⌜ExecPCPerm p ∧ SubBounds b e a (a ^+ length (makeint f_m) ^+ length imin\n                                               ^+ length imax)%a⌝\n          ∗ [[b1,e1]]↦ₐ[[activation_instrs wcode1 wvar]]\n          ∗ [[b2,e2]]↦ₐ[[activation_instrs wcode2 wvar]]\n          ∗ [[b3,e3]]↦ₐ[[activation_instrs wcode3 wvar]]\n    )%I.\n\n\n\n  Local Existing Instance interp_weakening.if_persistent.\n  Lemma check_interval_spec pc_p pc_b pc_e (* PC *)\n        wret (* return cap *)\n        iw (* input interval. If they are sealed intervals, the program crashes *)\n        d1 d4 (* dynamically allocated interval environment *)\n        a_first (* special adresses *)\n        ι0 ι1 ι2 ι3 ι4 ι5 ι6 o (* invariant/gname names *)\n        f_a b_r e_r a_r a_r' b_a e_a a_flag assertN (* assert environment *)\n        rmap (* register map *)\n        benv0 eenv p_i b_i e_i a_i f_m_i b1 e1 b2 e2 b3 e3 (* interval library *)\n        ll ll' p_s b_s e_s a_s Φs(* nested seal environment *) :\n\n    (* PC assumptions *)\n    ExecPCPerm pc_p →\n\n    (* Program adresses assumptions *)\n    SubBounds pc_b pc_e a_first (a_first ^+ length (check_interval f_a))%a →\n\n    (* environment table: required by the seal and malloc spec *)\n    withinBounds b_r e_r a_r' = true →\n    (a_r + f_a)%a = Some a_r' →\n\n    dom rmap = all_registers_s ∖ {[ PC; r_t0; r_env; r_t1; r_t20]} →\n\n    (* The two invariants have different names *)\n    (up_close (B:=coPset)ι2 ⊆ ⊤ ∖ ↑ι1) ->\n    up_close (B:=coPset)ι0 ## ↑ι3 →\n    up_close (B:=coPset)ι6 ## ↑ι0 →\n    up_close (B:=coPset)ι6 ## ↑ι3 →\n    up_close (B:=coPset)ι0 ## ↑ι5 →\n    up_close (B:=coPset)ι6 ## ↑ι5 →\n    up_close (B:=coPset)ι4 ⊆ ⊤ ∖ ↑ι1 →\n    up_close (B:=coPset)ι1 ## ↑assertN →\n    up_close (B:=coPset)ι4 ## ↑assertN →\n\n    {{{ PC ↦ᵣ WCap pc_p pc_b pc_e a_first\n       ∗ r_t0 ↦ᵣ wret\n       ∗ r_env ↦ᵣ WCap RWX d1 d4 d1\n       ∗ r_t1 ↦ᵣ iw\n       (* proof that the provided value has been validly sealed *)\n       ∗ ▷ (if is_sealed_with_o iw o then valid_sealed iw o Φs else True)\n       ∗ (∃ w, r_t20 ↦ᵣ w)\n       ∗ ([∗ map] r_i↦w_i ∈ rmap, r_i ↦ᵣ w_i)\n       (* invariant for the seal (must be an isInterval seal) and the seal/unseal pair environment,\n          and the interval library environment *)\n       ∗ na_inv logrel_nais ι0 (seal_env benv0 eenv ll ll' p_s b_s e_s a_s)\n       ∗ seal_state ι6 ll o isInterval\n       ∗ na_inv logrel_nais ι2 (interval_env d1 d4 benv0 eenv p_i b_i e_i a_i f_m_i b1 e1 b2 e2 b3 e3)\n       (* code for imin and imax subroutines *)\n       ∗ na_inv logrel_nais ι3 (codefrag (a_i ^+ length (makeint f_m_i))%a imin)\n       ∗ na_inv logrel_nais ι5 (codefrag ((a_i ^+ length (makeint f_m_i)) ^+ length imin)%a imax)\n       (* token which states all non atomic invariants are closed *)\n       ∗ na_own logrel_nais ⊤\n       (* callback validity *)\n       ∗ interp wret\n       (* assert and environment table *)\n       ∗ na_inv logrel_nais ι4 (pc_b ↦ₐ WCap RO b_r e_r a_r ∗ a_r' ↦ₐ WCap E b_a e_a b_a)\n       ∗ na_inv logrel_nais assertN (assert_inv b_a a_flag e_a)\n       (* trusted code *)\n       ∗ na_inv logrel_nais ι1 (codefrag a_first (check_interval f_a))\n       (* the remaining registers are all valid *)\n       ∗ ([∗ map] _↦w_i ∈ rmap, interp w_i) }}}\n      Seq (Instr Executable)\n      {{{ v, RET v; ⌜v = HaltedV⌝ →\n                    ∃ r, full_map r ∧ registers_mapsto r\n                         ∗ na_own logrel_nais ⊤ }}}.\n  Proof.\n    iIntros (Hvpc Hbounds Hwb Ha_r' Hdom Hι0 Hι1 Hι2 Hι3 Hι4 Hι5 Hι6 ? ? Φ)\n            \"(HPC & Hr_t0 & Hr_env & Hr_t1 & #Hseal_valid & Hr_t20 & Hregs & #Hseal_env & #HsealLL & #Hinterval_env & #Himin & #Himax &\n              Hown & #Hwret_valid & #Htable & #Hassert & #Hcheck_interval & #Hregs_valid) HΦ\".\n    iMod (na_inv_acc with \"Hcheck_interval Hown\") as \"(>Hcode & Hown & Hcls)\";auto.\n    iMod (na_inv_acc with \"Hinterval_env Hown\") as \"(>Hint & Hown & Hcls')\";[auto..|].\n    iDestruct \"Hint\" as (d2 d3 (Hd2&Hd3&Hd4))\n                          \"(Hd1 & Hd2 & Hd3 & %Hcond & %Hi_pc & Hact1 & Hact2 & Hact3)\".\n    destruct Hcond as (He1 & He2 & He3).\n    destruct Hi_pc as (Hvpci & Hboundsi).\n\n    iExtractList \"Hregs\" [r_temp1;r_temp2;r_temp3;r_temp4;r_t2] as [\"Hr_temp1\";\"Hr_temp2\";\"Hr_temp3\";\"Hr_temp4\";\"Hr_t2\"].\n\n    rewrite /check_interval.\n    focus_block_0 \"Hcode\" as \"Hblock\" \"Hcont\".\n    iGo \"Hblock\". split;auto. solve_addr+Hd2 Hd3 Hd4.\n    iGo \"Hblock\".\n    unfocus_block \"Hblock\" \"Hcont\" as \"Hcode\".\n\n    iDestruct \"Hr_t20\" as (w5) \"Hr_t20\".\n    iApply closure_activation_spec;iFrameAutoSolve. iFrame \"Hact2\".\n    iNext. iIntros \"(HPC & Hr_t20 & Hr_env & Hact2)\".\n\n    rewrite updatePcPerm_cap_non_E;[|by inv Hvpci].\n    iMod (\"Hcls'\" with \"[$Hown Hact1 Hact2 Hact3 Hd1 Hd2 Hd3]\") as \"Hown\".\n    { iNext. iExists _,_. iFrame \"Hact1 Hact2 Hact3\". iFrame. auto. }\n    iMod (\"Hcls\" with \"[$Hown $Hcode]\") as \"Hown\".\n    iExtractList \"Hregs\" [r_t3;r_t4;r_t5] as [\"Hr_t3\";\"Hr_t4\";\"Hr_t5\"].\n    iApply imin_spec;iFrameAutoSolve;[..|iFrame \"HsealLL Hseal_env Himin Hown HΦ\"];[|eauto..|].\n    solve_addr+Hboundsi.\n    iSplitR; [iExact \"Hseal_valid\"|].\n    iSplitL \"Hr_t2\";[eauto|]. iSplitL \"Hr_t5\";[eauto|]. iSplitL \"Hr_t20\";[eauto|].\n    iSplitR.\n    { iNext. iIntros (Hcontr); inversion Hcontr. }\n    iNext. iIntros \"Hres\".\n    iDestruct \"Hres\" as (z1 z2 w)\n                          \"(%Heqiw & #His_int & HPC & Hr_t1 & Hr_t2\n                          & Hr_t5 & Hr_t20 & Hr_env & Hr_t0 & Hown)\".\n    subst iw.\n\n    iMod (na_inv_acc with \"Hcheck_interval Hown\") as \"(>Hcode & Hown & Hcls)\";auto.\n    iMod (na_inv_acc with \"Hinterval_env Hown\") as \"(>Hint & Hown & Hcls')\";[auto..|].\n    iDestruct \"Hint\" as (d2' d3' (Hd2'&Hd3'&Hd4'))\n                          \"(Hd1 & Hd2 & Hd3 & %Hcond & %Hi_pc & Hact1 & Hact2 & Hact3)\".\n    destruct Hcond as (He1' & He2' & He3').\n    destruct Hi_pc as (Hvpci' & Hboundsi').\n    simplify_eq.\n\n    focus_block_0 \"Hcode\" as \"Hblock\" \"Hcont\".\n    rewrite updatePcPerm_cap_non_E;[|by inv Hvpc].\n    iGo \"Hblock\". instantiate (1:=d3). solve_addr +Hd2 Hd3 Hd4.\n    iGo \"Hblock\". split;auto. solve_addr +Hd2 Hd3 Hd4.\n    iGo \"Hblock\". unfocus_block \"Hblock\" \"Hcont\" as \"Hcode\".\n\n    iApply closure_activation_spec;iFrameAutoSolve. iFrame \"Hact3\".\n    iNext. iIntros \"(HPC & Hr_t20 & Hr_env & Hact3)\".\n\n    rewrite updatePcPerm_cap_non_E;[|by inv Hvpci].\n    iMod (\"Hcls'\" with \"[$Hown Hact1 Hact2 Hact3 Hd1 Hd2 Hd3]\") as \"Hown\".\n    { iNext. iExists _,_. iFrame \"Hact1 Hact2 Hact3\". iFrame. auto. }\n    iMod (\"Hcls\" with \"[$Hown $Hcode]\") as \"Hown\".\n\n    iApply imax_spec;iFrameAutoSolve;[..|iFrame \"HsealLL Hseal_env Himax Hown\"];[|eauto..|].\n    solve_addr+Hboundsi.\n    iSplitR; [iExact \"Hseal_valid\"|].\n    iSplitL \"Hr_t2\";[eauto|]. iSplitL \"Hr_t5\";[eauto|]. iSplitL \"Hr_t20\";[eauto|].\n\n    iSplitR;[|iSplitR].\n    2: { iNext. iIntros (v). iIntros \"H\". iExact \"H\". }\n    iNext. iIntros (Hcontr);inversion Hcontr.\n\n    iNext. iIntros \"Hres\".\n    iDestruct \"Hres\" as (z0 z3 w')\n                          \"(%Heq & #His_int' & HPC & Hr_t1 & Hr_t2 & Hr_t5\n                           & Hr_t20 & Hr_env & Hr_t0 & Hown)\".\n    inv Heq.\n\n    (* (* we must now use the sealLL invariant to conclude that w = w' *) *)\n    (* iMod (na_inv_acc with \"HsealLL Hown\") as \"(Hseal_inv & Hown & Hcls)\";auto. *)\n    (* iDestruct \"Hseal_inv\" as (hd) \"(>Hll & Hhd)\". *)\n    (* iDestruct \"Hhd\" as (awvals) \"(HisList & >Hexact & #Hintervals)\". *)\n    (* iDestruct (know_pref with \"Hexact Hpref\") as %Hprefix. *)\n    (* iDestruct (know_pref with \"Hexact Hpref'\") as %Hprefix'. *)\n    (* iAssert (▷ ⌜NoDup awvals.*1⌝)%I as \"#>%HnoDup\". *)\n    (* { iNext. iApply isList_NoDup. iFrame. } *)\n    (* rewrite Hincr in Hincr'. inv Hincr'. *)\n    (* pose proof (elem_of_prefix_eq b01 w w' pbvals pbvals' awvals Hin Hin' Hprefix Hprefix' HnoDup) as <-. *)\n    (* iMod (\"Hcls\" with \"[$Hown Hll HisList Hexact]\") as \"Hown\". *)\n    (* { iNext. iExists _. iFrame. iExists _. iFrame. auto. } *)\n    (* next, we can use isInterval property to conclude that z1 = z0 and z2 = z3 *)\n    iDestruct (intervals_agree with \"His_int His_int'\") as %(Heq & Heq'). subst z0 z3.\n\n    (* we can now finish the program, knowing that z1 <= z2 *)\n    iMod (na_inv_acc with \"Hcheck_interval Hown\") as \"(>Hcode & Hown & Hcls)\";auto.\n    rewrite updatePcPerm_cap_non_E;[|by inv Hvpc].\n    focus_block_0 \"Hcode\" as \"Hblock\" \"Hcont\".\n    iGo \"Hblock\". unfocus_block \"Hblock\" \"Hcont\" as \"Hcode\".\n\n    iDestruct \"His_int'\" as (a1 a2 a3 _) \"(_&_&%Hle)\".\n    assert (z2 <? z1 = false)%Z as ->. lia.\n\n    focus_block 1 \"Hcode\" as a_mid Ha_mid \"Hblock\" \"Hcont\".\n    iMod (na_inv_acc with \"Htable Hown\") as \"(>(Hpc_b & Ha_r') & Hown & Hcls')\";auto.\n    iApply (assert_success with \"[- $Hassert $Hown]\");iFrameAutoSolve. solve_ndisj. by auto.\n    iNext. iIntros \"(HPC & Hr_t0 & Hr_t1 & Hr_t2 & Hr_t3 & Hr_t4 & Hr_t5 & Hblock & Hown & Hpc_b & Ha_r')\".\n    iMod (\"Hcls'\" with \"[$Hown $Hpc_b $Ha_r']\") as \"Hown\".\n    unfocus_block \"Hblock\" \"Hcont\" as \"Hcode\".\n\n    iDestruct (jmp_to_unknown _ with \"Hwret_valid\") as \"Hcallback_now\".\n\n    focus_block 2 \"Hcode\" as a_mid0 Ha_mid0 \"Hblock\" \"Hcont\".\n    iGo \"Hblock\".\n    unfocus_block \"Hblock\" \"Hcont\" as \"Hcode\".\n    iMod (\"Hcls\" with \"[$Hown $Hcode]\") as \"Hown\".\n    iInsertList \"Hregs\" [r_t5;r_t4;r_t3;r_t2;r_temp1;r_temp2;r_temp3;r_temp4;r_t1;r_t0;r_t20;r_env].\n\n    iApply (\"Hcallback_now\" with \"[] [$HPC Hregs $Hown]\");cycle 1.\n    { iApply big_sepM_sep. iFrame.\n      repeat (iApply big_sepM_insert_2; first by iApply fixpoint_interp1_eq).\n      iApply big_sepM_insert_2. iFrame \"#\".\n      repeat (iApply big_sepM_insert_2; first by iApply fixpoint_interp1_eq).\n      iFrame \"#\". }\n    iPureIntro. rewrite !dom_insert_L Hdom. rewrite !singleton_union_difference_L. set_solver+.\n  Qed.\n\nEnd interval_client.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/examples/interval_client_arch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.23180706062648135}}
{"text": "\nRequire Export CatSem.PROP_untyped.initial.\nRequire Export CatSem.CAT.SO.\n\nRequire Import Coq.Program.Equality.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Automatic Introduction.\nUnset Transparent Obligations.\n\n\nNotation \"[[ x ; .. ; y ]]\" := (cons x .. (cons y nil) ..).\n\nNotation \"[ T ]\" := (list T) (at level 5).\n\n(** ** Propositional arities and their representations\n\tgiven a signature [S], we define \n\t- half-equations \n\t- algebraic half-equations\n\t- (in)equations over [S] as pairs of half-equations\n\t- representations of (in)equations as a predicate on representations of [S]\n*)\n\n(** ** Modules with codomain [wPO] *)\n\n(** given a relative module [M:Set -> PO] over a relative monad [P] over Delta, \n       the data of [M] defines a [P]-module [M : Set -> wPO ] *)\n\nSection wPO_taut_mod.\n\nVariable P : RMonad Delta.\nVariable M : RModule P Ord.\n\nObligation Tactic := unfold Proper, respectful; mauto;\n        try apply (rmkl_eq M);\n        try rew (rmklmkl M);\n        try rew (rmkleta M); mauto.\n\nProgram Instance wOrd_RMod_struct : RModule_struct P wOrd M := {\n  rmkleisli a b f := rmkleisli (RModule_struct:= M) f }.\n\nDefinition wOrd_RMod : RModule P wOrd := Build_RModule wOrd_RMod_struct.\n\nEnd wPO_taut_mod.\n\n(*\nSection monadic_subst_as_mod_hom.\n\nVariable P : RMonad Delta.\n\n(*\nPrint RModule_Hom.\n\nDefinition bla:\n(forall c : TYPE,\n  (product (C:= RMOD P wPO) (wPO_RMod ((DER_RMOD_not PO P) P)) (wPO_RMod P)) c --->\n  (wPO_RMod P) c).\nsimpl.\nintro c.\napply (fun y => Rsubstar_not (snd y) (fst y)).\nDefined.\n\n(*\napply substar_not.\nintro c.\napply (substar \n*)\nPrint bla.\n*)\n\nLtac elim_option := match goal with [H : option _ |- _ ] => \n                     destruct H end.\n\nLtac t := mauto ; repeat (unfold Rsubstar_not ||\n         match goal with [H: prod _ _ |-_] => destruct H end ||\n         rew (rklkl P) || app (rkl_eq P) || elim_option ||  \n         rew (rkleta P) || rew (retakl P ) || \n         rew (rlift_rkleisli P) || rew (rkleisli_rlift P) || \n         unfold rlift || rew (rkleta_eq (FM:=P)) || mauto ).\n\n(*\nObligation Tactic := t.\nCheck Der_RMod_not.\nProgram Instance Rsubstar_mod_hom_struct : RModule_Hom_struct\n   (M := product (C:=RMOD P wPO) ((DER_RMOD_not _ _ (wPO_RMod P))) (wPO_RMod P)) \n   (N := wPO_RMod P) \n   (fun c y => Rsubstar_not (snd y) (fst y)).\nDefinition Rsubstar_mod_hom := Build_RModule_Hom Rsubstar_mod_hom_struct.\n*)\n\nEnd monadic_subst_as_mod_hom.\n*)\n\n(** ** S-Modules and Equations\n   given signature [S], we define equations and the predicate [satisfies_prop_sig]\n     on representations of [S]\n*)\n\nSection S_Mods_and_Eqs.\n\nVariable S : Signature.\n\n(** an S_Module over [S] should be a functor from representations of [S]\n      to the category whose objects are pairs of a monad P and a module over P.\n   we don't need the functor properties, and use dependent types instead of the cumbersome \n   category of pairs\n*)\n\n(*\nClass S_Module_s (Tau : forall R : REP S, RMOD R wOrd) := {\n   S_Mod_Hom : forall (R S : REP S) (f : R ---> S), \n      Tau R ---> PbRMod f (Tau S)  }.\n*)\n\nRecord S_Module := {\n  s_mod :> forall R : REP S, RMOD R wOrd ;\n  s_mod_hom :> forall (R T : REP S)(f : R ---> T),\n         s_mod R ---> PbRMod f (s_mod T)  }.\n\n(** a half-equation is a natural transformation of between S-Modules. \n    we need the naturality condition in the following *)\n\n(*Notation \"U @ f\" := (S_Mod_Hom (S_Module_s := U) f)(at level 4).*)\n\n\nNotation \"U @ f\" := (s_mod_hom U f)(at level 4). \n\nClass half_equation_struct (U V : S_Module) \n    (half_eq : forall R : REP S, (*s_mod*) U R ---> (*s_mod*) V R) := {\n  comm_eq_s : forall (R T : REP S)  (f : R ---> T), \n      U @ f ;; PbRMod_Hom _ (half_eq T) ==  half_eq R ;; V @ f }.\n\n\n\n(*\nClass half_equation_struct (U V : S_Module) \n    (half_eq : forall R : REP S, s_mod U R ---> s_mod V R) := {\n  comm_eq_s : forall (R S : REP S)  (f : R ---> S), \n     S_Mod_Hom (*S_Module_s := U*) f ;; PbRMod_Hom _ (half_eq S) == \n                half_eq R ;; S_Mod_Hom (S_Module_s := V) f }.\n*)\n\n(*\nClass half_equation_struct (U V : S_Module) \n    (half_eq : forall R : REP S, s_mod U R ---> s_mod V R) := {\n  comm_eq_s : forall (R S : REP S)  (f : R ---> S), \n     S_Mod_Hom (*S_Module_s := U*) f ;; PbRMod_Hom _ (half_eq S) == \n                half_eq R ;; S_Mod_Hom (S_Module_s := V) f }.\n*)\n\nRecord half_equation (U V : S_Module) := {\n  half_eq :> forall R : REP S, U R --->  V R ;\n  half_eq_s :> half_equation_struct half_eq }.\n\n\n\nSection S_Module_classic.\n\n(** ** Classic S-Modules and Equations \n\nwe are interested in classic S-Modules, i.e. of the form PROD_i P^{n(i)} *)\n\nVariable l : [nat].\n\n(** classic S-Modules on objects *)\n\nSection ob.\n\nVariable P : RMonad Delta.\nVariable M : RModule P Ord.\n\nObligation Tactic := mauto; repeat (t || unfold Proper, respectful || \n                             app pm_mkl_eq || rew pm_mkl_mkl || app pm_mkl_weta).\n\nProgram Instance S_Mod_classic_ob_s : RModule_struct P wOrd (fun V => prod_mod_po M V l) := {\n  rmkleisli a b f := pm_mkl f }.\n\nDefinition S_Mod_classic_ob : RMOD P wOrd := Build_RModule S_Mod_classic_ob_s.\n\nEnd ob.\n\nSection mor.\n\n(** classic S-Modules on morphisms *)\n\nVariables P Q : RMonad Delta.\nVariable f : RMonad_Hom P Q.\n\nObligation Tactic := repeat (mauto || rew prod_mod_c_kl || app pm_mkl_eq).\n\nProgram Instance S_Mod_classic_mor_s : RModule_Hom_struct \n       (M := S_Mod_classic_ob P) (N := PbRMod f (S_Mod_classic_ob Q)) \n       (@Prod_mor_c _ _ f l).\n\nDefinition S_Mod_classic_mor := Build_RModule_Hom S_Mod_classic_mor_s.\n\nEnd mor.\n\nDefinition S_Mod_classic := {|\n      s_mod := fun R => S_Mod_classic_ob R ;\n      s_mod_hom R T f := S_Mod_classic_mor f |}.\n(*\nInstance S_Mod_classic_s : S_Module_s (fun R => S_Mod_classic_ob R) := {\n  S_Mod_Hom R S f := S_Mod_classic_mor f }.\n*)\n(*Definition S_Mod_classic := Build_S_Module S_Mod_classic_s.*)\n\nEnd S_Module_classic.\n\n(** ** Example : substitution *)\n\nSection substitution.\n\n(** substitiution is an example of half-equation *)\n\n(** the carrier is - for the moment - defined by tactics. Buh! \n     we don't care, since it's just an example *)\n\nDefinition subst_carrier (P : REP S) :\n(forall c : TYPE, (S_Mod_classic_ob [[1; 0]] P) c ---> (S_Mod_classic_ob [[0]] P) c) .\nsimpl.\nintros.\nsimpl in *.\ninversion X.\nsimpl in *.\ninversion X1.\nsimpl in X2.\nconstructor.\nsimpl.\napply (Rsubstar_not X2 X0).\napply TTT.\nDefined.\n\n(*\nPrint subst_carrier.\n\nDefinition subst_carrier_exp (P : REP S) :\n(forall c : TYPE, (S_Mod_classic_ob [[1; 0]] P) c ---> (S_Mod_classic_ob [[0]] P) c) :=\n  fun c X => match X in (prod_mod_c _ _ l) return \n       (match l with \n        | TTT => False_rect _ _ _ \n        | CONSTR a b => match b with\n\n\nDefinition subst_carrier2 (P : REP S) :\n(forall c : TYPE, (S_Mod_classic_ob [[1; 0]] P) c ---> (S_Mod_classic_ob [[0]] P) c) .\nsimpl; intros.\npose (diag x := match x with cons a b => prod_mod_c (fun x => P x) x [[0]])\n  fun c X => match X in \n          prod_mod_c (fun x : Type => P x) _ l return \n\n*)\n\nProgram Instance sub_struct (P : REP S) : RModule_Hom_struct \n  (M:=S_Mod_classic_ob [[1;0]] P) (N:=S_Mod_classic_ob [[0]] P) (subst_carrier (P:=P)).\nNext Obligation.\nProof.\n  dependent destruction x.\n  dependent destruction x.\n  simpl in *.\n  apply CONSTR_eq; auto.\n  unfold Rsubstar_not.\n  rew (rklkl P).\n  rew (rklkl P).\n  apply (rkl_eq P).\n  simpl.\n  mauto. \n  destruct x0; simpl.\n  unfold rlift.\n  simpl.\n  rew (retakl P).\n  rew (rklkl P).\n  rew (rkleta_eq (FM:=P)).\n  intros.\n  rew (retakl P).\n  rew (retakl P).\nQed.\n\n\nDefinition subst_module_mor (P : REP S) := Build_RModule_Hom (sub_struct P).\n\n\nProgram Instance subst_half_s : half_equation_struct \n      (U:= (S_Mod_classic [[1 ; 0]])) (V:=S_Mod_classic [[0]]) subst_module_mor.\nNext Obligation.\nProof.\n  \n  dependent destruction x.\n  dependent destruction x.\n  dependent destruction x.\n  \n  simpl.\n  apply CONSTR_eq; auto.\n  unfold Rsubstar_not.\n  \n  rew (rmon_hom_rkl f).\n  app (rkl_eq T).\n  intros. \n  match goal with [H:option _ |- _]=>destruct H end;\n  simpl.\n  rew (rmon_hom_rweta f).\n  auto.\nQed.\n\nDefinition subst_half_eq := Build_half_equation subst_half_s.\n\nEnd substitution.\n\n(** end of example *)\n\n(** ** Algebraic stuff cont. \n\nan algebraic half-equation is a half-equation with algebraic codomain, and\n\tan arbitrary domain *)\n\n\n\nDefinition half_eq_classic (U : S_Module)(codl : [nat]) := \n      half_equation U (S_Mod_classic codl).\n\n(** an algebraic (in)equation is given by \n       - an arbitrary domain [domS]\n       - an algebraic codomain [S_Mod_alg codl]\n       - two half-equations [eq1 eq2 : domS -> S_Mod_alg codl] *)\n\nRecord ineq_classic := {\n  Dom : S_Module ;\n  Cod : [nat] ;\n  half_eq_l : half_eq_classic Dom Cod ;\n  half_eq_r : half_eq_classic Dom Cod }.\n\n\n\n(*\nDefinition satisfies_eq l l' (e : eq_alg l l') (P : REP S) : Prop.\nintros.\ndestruct e.\nsimpl in *.\ndestruct eq3.\ndestruct eq4.\nCheck S_Mod_alg. Print S_Module.\napply (forall c : TYPE,\n         forall x : s_mod_rep (S_Mod_alg l) P c, half_eq0 P _ x << half_eq1 _ _ x).\nDefined.\n\n*)\n\n(** ** Representation of (a set of) (in)equations \n\na representation [P] satisfies an equation [e] iff for any element in the domain [domS e P c],\n ([c] a set of variables) its two images under e1 and e2 are related\n*)\n\n(*\nDefinition satisfies_eq (e : eq_alg) (P : REP S) :=\n  forall c (x : s_mod_rep (domS e) P c), \n       (*half_eq*) (eq1 e) P _ x << (*half_eq*) (eq2 e)_ _ x.\n*)\n\nDefinition satisfies_ineq (e : ineq_classic) (P : REP S) :=\n  forall c (x : Dom e P c), \n        half_eq_l _ _ _ x <<  half_eq_r _ _ _ x.\n\n(** a set of (in)equations, indexed by a set A *)\n\nDefinition Inequations (A : Type) := A -> ineq_classic.\n\n\n(** [R] satisfies [T] iff it satisfies any equation of [T] *)\n\nDefinition satisfies_ineqs A (T : Inequations A) (R : REP S) :=\n      forall a, satisfies_ineq (T a) R.\n\n(** ** Subcategory of Rep(S) of representations satisfying equations *)\n\nSection subcat.\n\n(** given any set of (in)equations [T], we consider the following subcategory of \n    the category of representations:\n     - objects : representations that satisfy [T]\n     - morphisms : morphisms that satisfy [True], hence any \n*)\n\nVariable A : Type.\nVariable T : Inequations A.\n\n(** lemma stating that the properties are closed under composition and \n    identity *)\n\nProgram Instance Ineq_Rep : SubCat_compat (REP S)\n     (fun P => satisfies_ineqs T P) (fun a b f => True).\n\n(** hence we obtain a category, the category of representations of [(S, T)] *)\n\nDefinition INEQ_REP : Cat := SubCat Ineq_Rep.\n\n\n(** * Initiality in the subcategory \nWe proceed with the construction of its initial object *)\n\n(** ** Order induced by a set of equations\nfirst thing to do is to build the correct order on the set of terms:\n     - two terms [x] and [y] are related if their images under any \n        initial morphism towards a rep of [(S, T)] is\n     - this initial morphism is actually in the category of representations of \n     [S], hence we must inject [R] into the big category\n*)\n\nDefinition prop_rel_c X (x y : UTS S X) : Prop :=\n      forall R : INEQ_REP, init (FINJ _ R) x << init (FINJ _ R) y.\n\n(** this ordering is a preorder *)\n\nProgram Instance prop_rel_po X : PreOrder (@prop_rel_c X).\nNext Obligation.\nProof.\n  unfold Reflexive.\n  unfold prop_rel_c.\n  reflexivity.\nQed.\nNext Obligation.\nProof.\n  unfold Transitive.\n  unfold prop_rel_c.\n  simpl; intros.\n  transitivity (init (proj1_sig R) y); \n  auto.\nQed.\n\nDefinition prop_rel_po_s X := Build_PO_obj_struct (prop_rel_po X).\n\nDefinition prop_rel X := Build_PO_obj (prop_rel_po_s X).\n\n(** ** Substitution compatible with new order\nsubstitution as defined previously is compatible with this order *)\n\nProgram Instance subst_prop_rel_s X Y (f : X ---> UTS S Y) : \n   PO_mor_struct (a := prop_rel X) (b := prop_rel Y) (subst f).\nNext Obligation.\nProof.\n  unfold Proper, respectful.\n  unfold prop_rel_c.\n  simpl. intros.\n  assert (H':= init_kleisli (proj1_sig R)).\n  simpl in H'.\n  assert (H2 := H' X x _ (Sm_ind f)).\n  simpl in H2.\n  rewrite H2.\n  clear H2.\n  assert (H3 := H' X y _ (Sm_ind f)).\n  rew H3.\n  clear H3.\n  apply PO_mor_monotone.\n  auto.\nQed.\n\nDefinition subst_prop_rel X Y f := Build_PO_mor (subst_prop_rel_s X Y f).\n\n(** now this gives a new relative monad\n     - the set of terms is the same as [UTS_sm]\n     - the order on any set of terms is different\n*)\n\nObligation Tactic := cat; \n      repeat (unfold Proper, respectful || \n       rewrite subst_var || app subst_eq ||\n       rewrite subst_subst || cat).\n      \n(** ** Monad with previously defined terms but new order, induced by equations *)\n\nProgram Instance UTS_prop_rel_rmonad_s : RMonad_struct Delta prop_rel := {\n  rweta c := Sm_ind (@Var S c);\n  rkleisli := subst_prop_rel\n}.\n\nDefinition UTSP := Build_RMonad (UTS_prop_rel_rmonad_s).\n\n(** ** an experiment *)\nSection higher_order_monotonicity.\n\n(** see the content of this section in _variant *)\n\n(*\nVariables X Y : TYPE.\nVariables f g : X -> UTSP Y.\nHypothesis H : forall x, f x << g x.\nCheck H.\n\n\nLemma higher_order_mon X (t : UTSP X) Y (f g : X -> UTSP Y)\n           (H : forall x, f x << g x)\n         : subst_prop_rel f t << subst_prop_rel g t.\nProof.\n  simpl in *.\n  Check (prod_mod_c_rel (M:= prop_rel)).\n Check prop_rel.\n  Check prod_mod_c.\n  Check (@UTSind S\n           (fun X (t : UTSP  X) =>\n              forall Y (f g : X ---> UTS S Y),\n             (forall x : X, prop_rel_c (f x) (g x)) ->\n            prop_rel_c (subst f t) (subst g t))\n\n           (fun X l (v : UTS_list S X l) => \n              forall Y (f g : X ---> UTS S Y),\n                 (forall x : X, prop_rel_c (f x) (g x)) ->\n\n           Rel \n            prod_mod_c_rel (M:=prop_rel) (list_subst v f) (list_subst v g))).\n\n).\n\n\n\n       Rel (PO_obj_struct := prod_mod_po (SC_inj_ob R) V l) \n  (Prod_mor_c (init_mon (S:=S) (SC_inj_ob R)) x)\n  (Prod_mor_c (init_mon (S:=S) (SC_inj_ob R)) y) ) :\nprod_mod_c_rel (M:=prop_rel) x y.\n          (forall x : X, forall R, init (proj1_sig R) (f x) << init _ (g x))\n            -> forall t : UTSP X, subst_prop_rel f t << subst_prop_rel g t)).\n\n\n set (H:= (@UTSind S\n            (fun (X : Type) (T : UTS S X) =>\n             forall (Y : Type) (f g : X -> UTS S Y),\n         (forall x : X, forall R, init (proj1_sig R) (f x) << init _ (g x))\n            -> forall t : UTSP X, subst_prop_rel f t << subst_prop_rel g t))).\n\n\napp (@UTSlistind \n      (fun V x => forall W (f g : V ---> UTS W)\n              (H:f == g), x >== f = x >== g)\n      (fun V l (v : UTS_list V l) => \n               forall W (f g : V ---> UTS W)(H:f == g),\n           v >>== f = v >>== g) );\n\napp (@UTSind \n       (fun (a : Type) (v : UTS a) => \n            forall (b : Type)(f g : a ---> b),\n         (f == g) ->\n         rename (W:=b) f v = rename (W:=b) g v)\n       (fun V l (v : UTS_list V l) => \n            forall (b : TYPE)(f g : V ---> b),\n         (f == g) ->\n         v //-- f =  v //-- g))\n\n\n  unfold po_obj_struct in H.\n  unfold prop_rel in H.\n*)\nEnd higher_order_monotonicity.\n\n(** ** Important Lemma\nThis lemma corresponds to one direction of Lemma 36 *)\n(** it says : the relation defined by the set of equations\n       behaves well when doing products and derivations.\n this is why we restrict ourselves to algebraic codomains\n*)\n\n\n\nLemma lemma36 (l : [nat]) (V : Type)\n    (x y : prod_mod_c (fun x : Type => UTS S x) V l)\n    (H : prod_mod_c_rel (M:=prop_rel) x y) \n    (R : INEQ_REP):\nRel (PO_obj_struct := prod_mod_po (SC_inj_ob R) V l) \n  (Prod_mor_c (init_mon (SC_inj_ob R)) x)\n  (Prod_mor_c (init_mon (SC_inj_ob R)) y).\n\n(*\nLemma lemma36 (l : [nat]) (V : Type)\n    (x y : prod_mod_c (fun x : Type => UTS Sig x) V l)\n    (H : prod_mod_c_rel (M:=prop_rel) x y) \n    (R : subob (fun P : Representation Sig => satisfies_prop_sig (A:=A) T P)):\nRel (PO_obj_struct := prod_mod_po (SC_inj_ob R) V l) \n  (Prod_mor_c (init_mon (SC_inj_ob R)) x)\n  (Prod_mor_c (init_mon (SC_inj_ob R)) y).\n*)\n\nProof.\n  simpl.\n  induction l; simpl;\n  intros.\n  dependent destruction x.\n  dependent destruction y.\n  constructor.\n  dependent destruction x.\n  simpl.\n  dependent destruction y.\n  simpl.\n  constructor.\n  simpl.\n  Focus 2.\n  apply IHl.\n  dependent destruction H.\n  auto.\n  dependent destruction H.\n  unfold prop_rel in H. simpl in H.\n  unfold prop_rel_c in H.\n  apply (H R).\nQed.\n\n\n(** ** Representation in the new monad \nwe now pass to representations of [S] in our new shiny monad. the carrier is \n    the same as for the diagonal monad. we have to prove that it is compatible with\n    the new order on terms *)\n\nProgram Instance Build_prop_pos (i : sig_index S) V : PO_mor_struct\n  (a := prod_mod UTSP (sig i) V) (b := UTSP V)\n  (fun X => Build (i:=i) (UTSl_f_pm (V:=V) X)).\nNext Obligation.\nProof.\n  unfold Proper; red.\n  intros; simpl.\n  unfold prop_rel_c.\n  simpl.\n  intros.\n  assert (H2:= repr_hom_s (Representation_Hom_struct := init_representic (SC_inj_ob R))).\n  simpl in H2.\n  unfold commute in H2.\n  simpl in H2.\n  rewrite <- H2.\n  rewrite <- H2.\n  apply PO_mor_monotone.\n  apply lemma36.\n  auto.\nQed.\n\nDefinition Build_prop_po i V := Build_PO_mor (Build_prop_pos i V).\n\n(** these lemmas are the same as for the other monad *)\n(** perhaps we could reuse some code here, but that is not urgent *)\n\nLemma _lshift_lshift_eq2 (b : nat) (X W : TYPE) (f : PO_mor (sm_po X) (prop_rel W))\n   (x : X ** b):\n lshift_c (P:=UTSP) (l:=b) (V:=X) (W:=W) f x =\n    _lshift (S:=S) (l:=b) (V:=X) (W:=W) f x .\nProof.\n  induction b;\n  simpl; intros.\n  auto. \n  rewrite IHb.\n  apply _lshift_eq.\n  simpl.\n  intros.\n  destruct x0; simpl;\n  auto.\n  unfold inj.\n  rewrite subst_eq_rename.\n  auto.\nQed.\n\nLemma sts_list_subst2 l X (v : prod_mod (UTSP) l X) \n       W (f : Delta X ---> UTSP W):\n  UTSl_f_pm  (pm_mkl f v ) = list_subst (UTSl_f_pm v) f.\nProof.\n  induction v; simpl;\n  intros. auto.\n  apply constr_eq.\n  apply subst_eq.\n  intros.\n  rewrite _lshift_lshift_eq2.\n  auto.\n  auto.\nQed.\n\nHint Resolve sts_list_subst : fin.\nHint Rewrite sts_list_subst : fin.\n\n(** we need module morphisms for the representation *)\n\nProgram Instance Build_prop_s i : RModule_Hom_struct (Build_prop_po i).\nNext Obligation.\nProof.\n  rewrite sts_list_subst2.\n  auto.\nQed.\n\n(** [Build_prop i] represents the arity [i] *)\n\nDefinition Build_prop i := Build_RModule_Hom (Build_prop_s i).\n\n\n(**  UTSP has a structure as a representation of S *)\n\nCanonical Structure UTSPrepr : Repr S UTSP := Build_prop.\n\nCanonical Structure UTSProp : REP S := \n       Build_Representation (@UTSPrepr).\n\n(** ** Important Lemma, other direction\nother direction of Lemma 36\n    - also here some code savings possible\n    - this is actually not the variant we need: point is,\n      we have V (init) = V (init_prop) (cf. later) \n    - here is the version with V (init)\n*)\n\nLemma lemma36_2 (l : [nat]) (V : Type)\n    (x y : prod_mod_c (fun x : Type => UTS S x) V l)\n    (H : forall R : INEQ_REP,\n        Rel (PO_obj_struct := prod_mod_po (SC_inj_ob R) V l) \n  (Prod_mor_c (init_mon (S:=S) (SC_inj_ob R)) x)\n  (Prod_mor_c (init_mon (S:=S) (SC_inj_ob R)) y) ) :\nprod_mod_c_rel (M:=prop_rel) x y.\n\n(*\nLemma lemma36_2 (l : [nat]) (V : Type)\n    (x y : prod_mod_c (fun x : Type => UTS Sig x) V l)\n    (H : forall R : subob (fun P : Representation Sig => satisfies_prop_sig (A:=A) T P),\n        Rel (PO_obj_struct := prod_mod_po (SC_inj_ob R) V l) \n  (Prod_mor_c (init_mon (Sig:=Sig) (SC_inj_ob R)) x)\n  (Prod_mor_c (init_mon (Sig:=Sig) (SC_inj_ob R)) y) ) :\nprod_mod_c_rel (M:=prop_rel) x y.\n*)\n\nProof.\n  simpl.\n  induction l; simpl;\n  intros.\n  constructor.\n  dependent destruction x.\n  dependent destruction y.\n  simpl.\n  constructor.\n  simpl.\n  Focus 2.\n  apply IHl.\n  intros.\n  assert (h:= H R).\n  clear H.\n  dependent destruction h.\n  apply h.\n  unfold prop_rel_c.\n  intros.\n  assert (h:= H R).\n  dependent destruction h.\n  apply H0.\nQed.\n\n(** ** A morphism of representations \nwe produce a morphism of representations from [UTSP_sm] to \n     [UTSPREPR] \n     - this is in fact the identity morphism\n     - just the order becomes bigger\n*)\n(** we use this morphism to show that an equation is the same on \n  [UTSM_sm] (diagonal order) and [UTSP] (order induced by equations)\n*)\n\nProgram Instance Id_UTSM_UTSPs : \n   RMonad_Hom_struct (P:=UTSM S) (Q:=UTSP) \n   (fun c => Sm_ind (id (UTS S c))).\n\nDefinition Id_UTSM_sm_UTSP := Build_RMonad_Hom Id_UTSM_UTSPs.\n\nLemma id_UTSM_sm_UTSP l c (x : prod_mod_c (fun x => UTS S x) c l) : \n      Prod_mor_c Id_UTSM_sm_UTSP x = x.\nProof.\n  induction x; simpl; intros;\n  auto; apply CONSTR_eq; auto.\nQed.\n\nObligation Tactic := unfold commute; simpl; intros;\n     repeat (apply f_equal || apply id_UTSM_sm_UTSP || auto).\n\nProgram Instance debi2s : \n     Representation_Hom_struct (P:=UTSRepr S) (Q:=UTSProp) Id_UTSM_sm_UTSP.\n\nDefinition UTSM_sm_UTSP_rep_hom := Build_Representation_Hom debi2s.\n\nExisting Instance UTS_initial.\n\nLemma half_eq_const_on_carrier : forall c x, \n   init_rep UTSProp c x = x.\nProof.\n  simpl;\n  assert (H:=InitMorUnique (C:=REP S) UTSM_sm_UTSP_rep_hom);\n  simpl in H;\n  auto.\nQed.\n\n\n(*\n\n(** this lemma states that half-equations are constant on \n    representations whose underlying sets of terms are the same and the \n     order gets bigger *)\n(** when passing from [UTSM_sm] to [UTSP], the equations remain the same *)\n\nLemma debi3s a c x:\nforall h : half_eq_alg (domS (T a)) (codl (T a)),\n    (h (UTSRepr Sig)) c x = (h UTSPROPRepr) c x.\nProof.\n  simpl.\n  intros.\n  destruct h.\n  simpl in *.\n  destruct half_eq_s0.\n  simpl in *.\n  assert (H:= comm_eq_s0 _ _ (debi2) c x).\n  rewrite debi25 in H.\n  rewrite debi25 in H.\n  auto.\nQed.\n\n*)\n\n\n(** [UTSPROPRepr] satisfies (in)equations\nthe new nice representation [UTSPROPRepr] satisfies the equations of [T], contrary\n    to the old one, [UTSRepr] *)\n\n(** ** Weak Initiality\n     we will use the weak initial morphism in the proof that\n     UTSPROPRepr satisfies the equations\n\n*)\n\nSection weak_init.\n\nVariable R : INEQ_REP.\n\n(** the initial morphism is the same as before\n      - we need to show that it is monotone, which is by definition\n      - that it is a morphism of monads\n      - morphism of representations\n      - unicity\n*)\n\n\nProgram Instance init_prop_s V : PO_mor_struct\n    (a:=(UTSProp) V) (b:=(FINJ _ R) V) (init (FINJ _ R) (V:=V)).\nNext Obligation.\nProof.\n  unfold Proper, respectful;\n  intros. \n  simpl in *. \n  unfold prop_rel_c in H. \n  simpl in H.\n  apply H.\nQed.\n\nDefinition init_prop_po V := Build_PO_mor (init_prop_s V).\n\nObligation Tactic := cat; rewrite init_kleisli2; \n           app (rkl_eq (proj1_sig R)).\n\n(** monadicity *)\n\nProgram Instance init_prop_mon_s : RMonad_Hom_struct\n      (P:=UTSProp)(Q:=FINJ _ R) init_prop_po.\n\nDefinition init_prop_mon := Build_RMonad_Hom init_prop_mon_s.\n\n(** representativity asks for a lemma, same as for case without equations *)\n\nLemma prod_mor_eq_init_list2 (i : sig_index S) V\n       (x : prod_mod_c (fun V => UTS S V) V (sig i)) :\n  Prod_mor_c init_prop_mon x = init_list _ (UTSl_f_pm x).\nProof.\n  induction x;\n  simpl; auto.\n  unfold FINJ in IHx. simpl in *.\n  rewrite  IHx.\n  simpl. auto.\nQed.\n\nObligation Tactic := repeat (cat || unfold commute ||\n             rewrite prod_mor_eq_init_list2).\n\nProgram Instance init_prop_rep : Representation_Hom_struct \n       init_prop_mon.\n\nDefinition init_prop_re := Build_Representation_Hom init_prop_rep.\n\nEnd weak_init.\n\n\n(** ** V (init) = V (init_prop)\n*)\n\nLemma bb2b (R : INEQ_REP) a l (x : prod_mod_c (fun x : Type => UTS S x) a l):\n  Prod_mor_c (init_prop_mon R) x = Prod_mor_c (init_mon (SC_inj_ob R)) x.\nProof.\n  reflexivity.\nQed.\n\n(** ** Version of lemma36_2 using init_prop\n*)\n\nLemma lemma36_2a (l : [nat]) (V : Type)\n    (x y : prod_mod_c (fun x : Type => UTS S x) V l)\n    (H : forall R : INEQ_REP,\n        Rel (PO_obj_struct := prod_mod_po (SC_inj_ob R) V l) \n  (Prod_mor_c (init_prop_mon  (R)) x)\n  (Prod_mor_c (init_prop_mon  (R)) y) ) :\nprod_mod_c_rel (M:=prop_rel) x y.\nProof.\n  simpl; intros.\n  apply lemma36_2.\n  simpl; intros.\n  rewrite <- bb2b.\n  rewrite <- bb2b.\n  apply H.\nQed.\n\n(** ** [UTSPROPRepr satisfies equations\n      - we use  a1(x) < a2(x) in V(Sigma)(X) iff \n                  forall R, V(init_R) (a1(x)) < V(init_R) (a2(x))\n      - we rewrite V(init_R)(a1(x)) = a1 (U (init_R) x) \n      - and for a2 as well\n*)\n\nLemma UTSPRepr_sig_prop : satisfies_ineqs T UTSProp.\nProof.\n  unfold satisfies_ineqs, satisfies_ineq.\n  simpl; intros.\n  apply lemma36_2a.\n  intros. \n  assert (H4:=comm_eq_s (half_equation_struct := half_eq_l (T a))).\n  assert (H5:=H4 _ _ (init_prop_re R)).\n  \n  assert (H4':=comm_eq_s (half_equation_struct := half_eq_r (T a))).\n  assert (H5':=H4' _ _ (init_prop_re R)).\n  \n  clear H4 H4'.\n  simpl in *.\n\n  rewrite <- H5.\n  rewrite <- H5'.\n  \n  destruct R as [R v].\n  unfold satisfies_ineqs in v.\n  unfold satisfies_ineq in v.\n  simpl in *.\n  apply v.\nQed.\n\n(*\n  simpl in *.\n  assert (H6:=H5 c x).\n  simpl in *.\n  rewrite <- bbb.\n  Check Prod_mor_c.\n  Check ((eq1 (T a) UTSPROPRepr) c x).\n  assert (H: \n       Prod_mor_c1\n                             (init_prop_mon\n                                (exist\n                                   (fun a : Representation Sig =>\n                                    satisfies_prop_sig (A:=A) T a) x0 v))\n                             (((eq1 (T a)) UTSPROPRepr) c x) = \n  Prod_mor_c1 (init_mon (Sig:=Sig) x0) (((eq1 (T a)) UTSPROPRepr) c x)).\n  simpl. auto.\n  rerew  H.\n  clear H.\n  rewrite <- H6.\n  clear H5 H6.\n  \n  assert (H1: \n       Prod_mor_c1\n      (init_prop_mon\n         (exist (fun a : Representation Sig => satisfies_prop_sig (A:=A) T a)\n            x0 v)) (((eq2 (T a)) UTSPROPRepr) c x) = \n        Prod_mor_c1 (init_mon (Sig:=Sig) x0) (((eq2 (T a)) UTSPROPRepr) c x)).\n  simpl; auto.\n  rerew H1.\n  rewrite <- H5'.\n       \n  unfold satisfies_prop_sig in v.\n  unfold satisfies_eq in v.\n  simpl in v.\n  apply v.\nQed.\n*)\n\n(** ** yielding an object of the subcategory \n*)\n\nDefinition UTSPROP : INEQ_REP := \n exist (fun R : Representation S => satisfies_ineqs (*A:=A*) T R) UTSProp\n  UTSPRepr_sig_prop.\n\n(** ** Initiality in the subcategory *)\n\nSection init.\n\nVariable R : INEQ_REP.\n\n(** the initial morphism is the same as before\n      - we need to show that it is monotone, which is by definition\n      - that it is a morphism of monads\n      - morphism of representations\n      - unicity\n*)\n\n\n\n\n(** ** Weak Initial morphism in subcategory \n    was already defined *)\n\nDefinition init_prop : UTSPROP ---> R := exist _ (init_prop_re R) I.\n\nSection unique.\n\n(** ** Initiality in subcategory *)\n\nVariable f : UTSPROP ---> R.\n\nExisting Instance REP_struct.\n\n(** the proof uses initiality of init in the case without equations\n     - unicity is only concerned with data\n     - for data, the initial morphisms in the category of reps and in \n       the subcategory are the same\n*)\n\nLemma init_prop_unique : f == init_prop.\nProof.\n  simpl. intros.\n  destruct f.\n  simpl in *.\n  clear t.\n  clear f.\n  unfold SC_inj_ob in x1.\n  simpl in x1.\n  destruct R.\n  simpl in *.\n  clear R.\n  assert (H:= InitMorUnique (Initial := UTS_initial S) \n                         (UTSM_sm_UTSP_rep_hom ;; x1)).\n  simpl in H.\n  auto.\nQed.  \n\n\n(*\nLemma init_prop_unique : f == init_prop.\nProof.\n  simpl. intros.\n  destruct f.\n  simpl in *.\n  clear t.\n  clear f.\n  unfold SC_inj_ob in x1.\n  simpl in x1.\n  destruct R.\n  simpl in *.\n  clear R.\n  \n  apply (@UTSind Sig\n     (fun V v => x1 V v = init x2 v)\n     (fun V l v => Prod_mor x1 l V (pm_f_STSl v) = init_list _ v));\n  simpl; intros;\n  auto.\n  rew (rmon_hom_rweta x1).\n  rewrite <- (one_way u).\n  assert (H':=@repr_hom_s _ _ _ x1 x1).\n  unfold commute in H'.\n  simpl in H'.\n  rewrite <- H'.\n  \n  rewrite one_way.\n  rewrite H. auto.\n  rewrite H0. simpl.\n  rewrite H.\n  auto.\nQed.\n*)\n\nEnd unique.\n\nEnd init.\n\n(** ** Initiality verified by Coq *)\n\nProgram Instance INITIAL_INEQ_REP : Initial INEQ_REP := {\n  Init := UTSPROP ;\n  InitMor := init_prop ;\n  InitMorUnique := init_prop_unique\n}.\n\nEnd subcat.\nEnd S_Mods_and_Eqs.\n\n(* Print Assumptions INITIAL_INEQ_REP. *)", "meta": {"author": "JasonGross", "repo": "benediktahrens-coq-fossil", "sha": "834bc904a07549ac3f659e68d94a3f1c73c5b72a", "save_path": "github-repos/coq/JasonGross-benediktahrens-coq-fossil", "path": "github-repos/coq/JasonGross-benediktahrens-coq-fossil/benediktahrens-coq-fossil-834bc904a07549ac3f659e68d94a3f1c73c5b72a/PROP_untyped/prop_arities_initial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.23178467793877455}}
{"text": "From iris.proofmode Require Import coq_tactics reduction.\nFrom iris.proofmode Require Import tactics.\n\nFrom Perennial.goose_lang Require Import notation proofmode typing.\nFrom Perennial.goose_lang.lib Require Import typed_mem.\n\nImport uPred.\n\nSection goose_lang.\nContext `{ffi_sem: ffi_semantics} `{!ffi_interp ffi} `{!heapGS Σ}.\nContext {ext_ty: ext_types ext}.\n\nLemma tac_wp_store Δ Δ' Δ'' s E i K l v v' Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦ v)%I →\n  envs_simple_replace i false (Esnoc Enil i (l ↦ v')) Δ' = Some Δ'' →\n  envs_entails Δ'' (WP fill K (Val $ LitV LitUnit) @ s; E {{ Φ }}) →\n  envs_entails Δ (WP fill K (Store (LitV l) (Val v')) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_unseal=> ????.\n  rewrite -wp_bind. eapply wand_apply; first by eapply wp_store.\n  rewrite into_laterN_env_sound -later_sep envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply later_mono, sep_mono_r, wand_mono.\nQed.\n\nEnd goose_lang.\n\nTactic Notation \"wp_untyped_store\" :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_untyped_store: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_store _ _ _ _ _ _ K))\n      |fail 1 \"wp_untyped_store: cannot find 'Store' in\" e];\n    [tc_solve\n    |solve_mapsto ()\n    |pm_reflexivity\n    |first [wp_seq|wp_finish]]\n  | _ => fail \"wp_untyped_store: not a 'wp'\"\n  end.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/goose_lang/lib/wp_store.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.23178467793877452}}
{"text": "Require Import compcert.common.Memory.\nRequire Import compcert.common.Values.\nRequire Import VST.sepcomp.structured_injections.\n\nDefinition full_comp (j1 j2: meminj) :=\n  forall b0 b1 delta1, j1 b0 = Some (b1, delta1) -> exists b2 delta2, j2 b1 = Some (b2, delta2).\n\nDefinition full_ext (mu1 mu2: SM_Injection) :=\n  full_comp (extern_of mu1) (extern_of mu2).\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/sepcomp/full_composition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.23178467236331968}}
{"text": "Require Import Bool String List.\nRequire Import Lib.CommonTactics Lib.ilist Lib.Word.\nRequire Import Lib.Struct Lib.FMap Lib.StringEq Lib.Indexer.\nRequire Import Kami.Syntax Kami.Semantics Kami.RefinementFacts Kami.Renaming Kami.Wf.\nRequire Import Kami.Renaming Kami.Specialize Kami.Inline Kami.InlineFacts Kami.Decomposition.\nRequire Import Kami.Tactics Kami.Notations.\nRequire Import Ex.MemTypes Ex.SC Ex.NativeFifo Ex.MemAsync Ex.ProcFetchDecode Ex.ProcFDInl.\nRequire Import Eqdep ProofIrrelevance.\n\nSet Implicit Arguments.\n\nSection Invariants.\n  Variables addrSize iaddrSize instBytes dataBytes rfIdx: nat.\n\n  Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes)\n            (dec: AbsDec addrSize instBytes dataBytes rfIdx).\n\n  Variable (d2eElt: Kind).\n  Variable (d2ePack:\n              forall ty,\n                Expr ty (SyntaxKind (Bit 2)) -> (* opTy *)\n                Expr ty (SyntaxKind (Bit rfIdx)) -> (* dst *)\n                Expr ty (SyntaxKind (Bit addrSize)) -> (* addr *)\n                Expr ty (SyntaxKind (Array Bool dataBytes)) -> (* byteEn *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val1 *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val2 *)\n                Expr ty (SyntaxKind (Data instBytes)) -> (* rawInst *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* curPc *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* nextPc *)\n                Expr ty (SyntaxKind Bool) -> (* epoch *)\n                Expr ty (SyntaxKind d2eElt)).\n\n  Variable (f2dElt: Kind).\n  Variable (f2dPack:\n              forall ty,\n                Expr ty (SyntaxKind (Data instBytes)) -> (* rawInst *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* curPc *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* nextPc *)\n                Expr ty (SyntaxKind Bool) -> (* epoch *)\n                Expr ty (SyntaxKind f2dElt)).\n  Variables\n    (f2dRawInst: forall ty, fullType ty (SyntaxKind f2dElt) ->\n                            Expr ty (SyntaxKind (Data instBytes)))\n    (f2dCurPc: forall ty, fullType ty (SyntaxKind f2dElt) ->\n                          Expr ty (SyntaxKind (Pc addrSize)))\n    (f2dNextPc: forall ty, fullType ty (SyntaxKind f2dElt) ->\n                           Expr ty (SyntaxKind (Pc addrSize)))\n    (f2dEpoch: forall ty, fullType ty (SyntaxKind f2dElt) ->\n                          Expr ty (SyntaxKind Bool)).\n\n  Hypotheses (Hf2dRawInst: forall rawInst curPc nextPc epoch,\n                 evalExpr (f2dRawInst _ (evalExpr (f2dPack rawInst curPc nextPc epoch))) =\n                 evalExpr rawInst)\n             (Hf2dCurPc: forall rawInst curPc nextPc epoch,\n                 evalExpr (f2dCurPc _ (evalExpr (f2dPack rawInst curPc nextPc epoch))) =\n                 evalExpr curPc)\n             (Hf2dNextPc: forall rawInst curPc nextPc epoch,\n                 evalExpr (f2dNextPc _ (evalExpr (f2dPack rawInst curPc nextPc epoch))) =\n                 evalExpr nextPc)\n             (Hf2dEpoch: forall rawInst curPc nextPc epoch,\n                 evalExpr (f2dEpoch _ (evalExpr (f2dPack rawInst curPc nextPc epoch))) =\n                 evalExpr epoch).\n\n  Variables (pcInit : ConstT (Pc addrSize)).\n  \n  Definition fetchDecodeInl := projT1 (fetchDecodeInl\n                                         fetch dec\n                                         d2ePack f2dPack f2dRawInst f2dCurPc f2dNextPc f2dEpoch\n                                         pcInit).\n\n  Definition fetchDecode_inv_body\n             (pcv: fullType type (SyntaxKind (Pc addrSize)))\n             (pgmv: fullType type (SyntaxKind (Vector (Data instBytes) iaddrSize)))\n             (fepochv: fullType type (SyntaxKind Bool))\n             (f2dfullv: fullType type (SyntaxKind Bool))\n             (f2deltv: fullType type (SyntaxKind f2dElt)) :=\n    f2dfullv = true ->\n    let rawInst := evalExpr (f2dRawInst _ f2deltv) in\n    (rawInst = pgmv (evalExpr (toIAddr _ (evalExpr (f2dCurPc _ f2deltv)))) /\\\n     evalExpr (f2dNextPc _ f2deltv) = pcv /\\\n     evalExpr (f2dEpoch _ f2deltv) = fepochv).\n                                                      \n  Record fetchDecode_inv (o: RegsT) : Prop :=\n    { pcv : fullType type (SyntaxKind (Pc addrSize));\n      Hpcv : M.find \"pc\"%string o = Some (existT _ _ pcv);\n      pinitv : fullType type (SyntaxKind Bool);\n      Hpinitv : M.find \"pinit\"%string o = Some (existT _ _ pinitv);\n      pinitRqv : fullType type (SyntaxKind Bool);\n      HpinitRqv : M.find \"pinitRq\"%string o = Some (existT _ _ pinitRqv);\n      pinitRqOfsv : fullType type (SyntaxKind (Bit iaddrSize));\n      HpinitRqOfsv : M.find \"pinitRqOfs\"%string o = Some (existT _ _ pinitRqOfsv);\n      pinitRsOfsv : fullType type (SyntaxKind (Bit iaddrSize));\n      HpinitRsOfsv : M.find \"pinitRsOfs\"%string o = Some (existT _ _ pinitRsOfsv);\n      \n      pgmv : fullType type (SyntaxKind (Vector (Data instBytes) iaddrSize));\n      Hpgmv : M.find \"pgm\"%string o = Some (existT _ _ pgmv);\n      fepochv : fullType type (SyntaxKind Bool);\n      Hfepochv : M.find \"fEpoch\"%string o = Some (existT _ _ fepochv);\n\n      f2dfullv : fullType type (SyntaxKind Bool);\n      Hf2dfullv : M.find \"full.f2d\"%string o = Some (existT _ _ f2dfullv);\n      f2deltv : fullType type (SyntaxKind f2dElt);\n      Hf2deltv : M.find \"elt.f2d\"%string o = Some (existT _ _ f2deltv);\n\n      Hinv0 : pinitv = false -> f2dfullv = false;\n      Hinv1 : fetchDecode_inv_body pcv pgmv fepochv f2dfullv f2deltv\n    }.\n\n  #[local] Hint Unfold fetchDecode_inv_body : InvDefs.\n\n  Ltac fetchDecode_inv_old :=\n    repeat match goal with\n           | [H: fetchDecode_inv _ |- _] => destruct H\n           end;\n    kinv_red.\n\n  Ltac fetchDecode_inv_new :=\n    econstructor; (* let's prove that the invariant holds for the next state *)\n    try (findReify; (reflexivity || eassumption); fail);\n    kregmap_clear; (* for improving performance *)\n    kinv_red; (* unfolding invariant definitions *)\n    repeat (* cheaper than \"intuition\" *)\n      (match goal with\n       | [ |- _ /\\ _ ] => split\n       end);\n    try eassumption; intros; try reflexivity;\n    intuition kinv_simpl; intuition idtac.\n\n  Ltac f2d_abs_tac :=\n    try rewrite Hf2dRawInst in *;\n    try rewrite Hf2dCurPc in *;\n    try rewrite Hf2dNextPc in *;\n    try rewrite Hf2dEpoch in *.\n\n  Ltac fetchDecode_inv_tac := fetchDecode_inv_old; fetchDecode_inv_new; f2d_abs_tac.\n\n  Lemma fetchDecode_inv_ok':\n    forall init n ll,\n      init = initRegs (getRegInits fetchDecodeInl) ->\n      Multistep fetchDecodeInl init n ll ->\n      fetchDecode_inv n.\n  Proof. (* SKIP_PROOF_ON\n    induction 2.\n\n    - fetchDecode_inv_old.\n      unfold getRegInits, fetchDecodeInl, ProcFDInl.fetchDecodeInl, projT1.\n      fetchDecode_inv_new; simpl in *; kinv_simpl.\n\n    - kinvert.\n      + mred.\n      + mred.\n      + kinv_dest_custom fetchDecode_inv_tac.\n      + kinv_dest_custom fetchDecode_inv_tac.\n      + kinv_dest_custom fetchDecode_inv_tac.\n      + kinv_dest_custom fetchDecode_inv_tac.\n      + kinv_dest_custom fetchDecode_inv_tac.\n      + kinv_dest_custom fetchDecode_inv_tac; kinv_eq.\n      + kinv_dest_custom fetchDecode_inv_tac.\n      + kinv_dest_custom fetchDecode_inv_tac.\n      + kinv_dest_custom fetchDecode_inv_tac.\n        END_SKIP_PROOF_ON *) apply cheat.\n  Qed.\n\n  Lemma fetchDecode_inv_ok:\n    forall o,\n      reachable o fetchDecodeInl ->\n      fetchDecode_inv o.\n  Proof.\n    intros; inv H; inv H0.\n    eapply fetchDecode_inv_ok'; eauto.\n  Qed.\n\nEnd Invariants.\n\n#[global] Hint Unfold fetchDecode_inv_body : InvDefs.\n\n", "meta": {"author": "mit-plv", "repo": "kami", "sha": "cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0", "save_path": "github-repos/coq/mit-plv-kami", "path": "github-repos/coq/mit-plv-kami/kami-cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0/Kami/Ex/ProcFDInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23173994123009906}}
{"text": "Require Export FcEtt.tactics.\nRequire Export FcEtt.ett_inf.\n\nRequire Import FcEtt.utils.\nRequire Import FcEtt.imports.\nRequire Import FcEtt.notations.\n\nRequire Import FcEtt.ett_ind.\nRequire Import FcEtt.toplevel.\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Implicit Arguments.\n\nGeneralizable All Variables.\n\n(* --------------------------------------------------------------------------- *)\n(* --------------------------------------------------------------------------- *)\n(* --------------------------------------------------------------------------- *)\n\n(* TODO (tactics): integrate *)\nLtac solve_binds :=\n  match goal with\n    | [ b : binds ?v _ ?G\n      , H : forall v' _, binds v' _ ?G -> _ [<=] dom ?G ∧ _ [<=] dom ?G\n      |- _ ] =>\n      apply H in b; simpl in b; autofwd; (done || fsetdec)\n  end.\n\n\nImport AtomSetImpl.\n\nLemma in_singleton_subset : forall x (G : context), x `in` dom G -> singleton x [<=] dom G.\nProof.\n  unfold Subset.\n  intros.\n  apply singleton_1 in H0.\n  subst.\n  done.\nQed.\n\nHint Unfold AtomSetImpl.Subset.\nHint Resolve binds_In AtomSetImpl.singleton_1 in_singleton_subset.\n\nTheorem rctx_uniq : forall W a R, roleing W a R -> uniq W.\nProof. intros. induction H; eauto. pick fresh x.\n       simpl in *. eapply uniq_cons_1. eauto.\n       pick fresh c. simpl in *. eapply uniq_cons_1. eauto. Unshelve. exact.\nQed.\n\nTheorem rctx_fv_tm_co : forall W a R, roleing W a R ->\n        fv_tm_tm_tm a [<=] dom W /\\ fv_co_co_tm a [<=] empty.\nProof. intros. induction H; simpl in *; split; split_hyp; autounfold.\n       all: try (intros y h; apply empty_iff in h; contradiction).\n       all: try (intros y h; apply union_iff in h; inversion h as [h1 | h2];\n            eauto; fail).\n       all: try (intros; eapply AtomSetProperties.in_subset;\n                   [ eauto | rewrite union_empty_r; auto ]).\n       all: try (intros; eapply AtomSetProperties.in_subset;\n                   [ eauto | apply AtomSetProperties.union_subset_3;\n                      [ auto | apply AtomSetProperties.union_subset_3; auto ]]).\n       all: try (intros y h; pick fresh z;\n            match goal with\n             [ Q : forall _, _ -> _ /\\ _  |- _ ] =>\n             move: (Q z ltac:(auto)) => h'; split_hyp\n            end).\n       all: try (apply union_iff in h; inversion h).\n       all: try (eapply AtomSetProperties.in_subset; eauto; fail).\n       all: try (eapply add_3; [ eauto |\n            eapply AtomSetProperties.in_subset; [ eauto |\n            erewrite fv_tm_tm_tm_open_tm_wrt_tm_lower; eauto]]; fail).\n       all: try (eapply add_3; [ eauto |\n            eapply AtomSetProperties.in_subset; [ eauto |\n            erewrite fv_co_co_tm_open_tm_wrt_tm_lower; eauto]]; fail).\n       all: try (eapply AtomSetProperties.in_subset;\n            [ eauto | erewrite fv_tm_tm_tm_open_tm_wrt_co_lower; eauto]; fail).\n       all: try (eapply AtomSetProperties.in_subset;\n            [ eauto | erewrite fv_co_co_tm_open_tm_wrt_co_lower; eauto]; fail).\n       all: repeat (with (In _ (_ ∪ _)) do ltac:(fun h => apply union_iff in h; inv h)).\n       all: try by eapply AtomSetProperties.in_subset; eauto.\n       all: try by intros; fsetdec.\n       - intros.\n         with In do ltac:(fun h => apply singleton_iff in h; subst).\n         eapply binds_In; eauto.\nQed.\n\nLemma rctx_fv : forall W a R, roleing W a R -> fv_tm_tm_tm a [<=] dom W.\nProof. intros. eapply rctx_fv_tm_co; eauto.\nQed.\n\nLemma rctx_fv_co : forall W a R, roleing W a R -> fv_co_co_tm a [<=] empty.\nProof. intros. eapply rctx_fv_tm_co; eauto.\nQed.\n\nLemma pat_ctx_fv : forall W G D F A p B, PatternContexts W G D F A p B ->\n                                       dom W [<=] fv_tm_tm_tm p.\nProof. intros. induction H; simpl; fsetdec.\nQed.\n\n\nLemma axiom_body_fv_in_pattern : forall F p b A R Rs,\n      binds F (Ax p b A R Rs) toplevel -> fv_tm_tm_tm b [<=] fv_tm_tm_tm p.\nProof.\n  intros.\n  with binds do applyin toplevel_inversion.\n  autofwd.\n  with roleing do applyin rctx_fv.\n  with PatternContexts do applyin pat_ctx_fv.\n  by fsetdec.\nQed.\n\nLemma axiom_body_fv_co : forall F p b A R Rs,\n      binds F (Ax p b A R Rs) toplevel -> fv_co_co_tm b [<=] empty.\nProof.\n  intros.\n  with binds do applyin toplevel_inversion.\n  autofwd.\n  by with roleing do applyin rctx_fv_co.\nQed.\n\n\nTheorem context_fv_mutual :\n  (forall G (a : tm) A (H: Typing G a A),\n      fv_tm_tm_tm a [<=] dom G /\\ fv_co_co_tm a [<=] empty /\\\n      fv_tm_tm_tm A [<=] dom G /\\ fv_co_co_tm A [<=] empty)\n  /\\\n  (forall G phi  (H : PropWff G phi ),\n      fv_tm_tm_constraint phi [<=] dom G /\\ fv_co_co_constraint phi [<=] empty)\n  /\\\n  (forall G D p1 p2  (H : Iso G D p1 p2 ),\n      fv_tm_tm_constraint p1 [<=] dom G /\\ fv_co_co_constraint p1 [<=] empty /\\\n      fv_tm_tm_constraint p2 [<=] dom G /\\ fv_co_co_constraint p2 [<=] empty)\n  /\\\n  (forall G D A B T R (H : DefEq G D A B T R),\n      (fv_tm_tm_tm A [<=] dom G /\\ fv_co_co_tm A [<=] empty /\\\n      fv_tm_tm_tm B [<=] dom G /\\ fv_co_co_tm B [<=] empty /\\\n      fv_tm_tm_tm T [<=] dom G /\\ fv_co_co_tm T [<=] empty))\n\n  /\\\n  (forall G (H : Ctx G),\n      (forall x A,\n          binds x (Tm A)   G ->\n          fv_tm_tm_tm         A   [<=] dom G /\\ fv_co_co_tm         A   [<=] empty) /\\\n      (forall c phi,\n          binds c (Co phi) G ->\n          fv_tm_tm_constraint phi [<=] dom G /\\ fv_co_co_constraint phi [<=] empty)).\n\nProof.\n  (* TODO: this needs maintenance *)\n  eapply typing_wff_iso_defeq_mutual.\n  all: autounfold.\n\n  (* We can't just use `repeat split` because we don't want to split under foralls *)\n  all: intros; repeat match goal with |- _ ∧ _ => split end; split_hyp; simpl.\n  all: eauto 1.\n  (* split all asummptions about unions *)\n\n  (* Do the cases about the context at the end. *)\n  all: try (intros x0 A0 BI).\n  all: try solve [intros; autofv].\n  all: try (match goal with |- _ ∧ _ => split end).\n\n  all: try (intros y h1; inversion BI; [\n              match goal with\n                [ H5 : (_,_) = (_,_) |- _ ] =>\n                inversion H5; subst; clear H5; eauto end|\n              match goal with\n                [ H5 : List.In (?x0, ?s ?a) ?G,\n                  H : forall x A, binds x (?s A) ?G -> _ |- _ ] =>\n                destruct (H x0 _ H5); eauto end]).\n\n (* rest of the cases *)\n  all: intros y IN.\n\n  (* more splitting, assumption has a union type *)\n  all: try match goal with\n    [ H7 : ?y `in` union ?A ?B |- _ ] =>\n    apply F.union_iff in H7; destruct H7; eauto end.\n\n  all: try solve [ destruct (H _ _ b); eauto ].\n\n\n  all: try solve [apply H1; eauto; simpl; auto].\n  all: try solve [apply H2; eauto; simpl; auto].\n  all: try solve [apply H3; eauto; simpl; auto].\n  all: try solve [apply H0; eauto; simpl; auto].\n\n\n\n  all: try match goal with\n    [ H5 : forall x : atom, (x `in` ?L -> False) -> ( _ /\\ _ ) |- _ ] =>\n    pick fresh x; destruct (H5 x); eauto; split_hyp\n           end.\n\n  all: try match goal with\n    [ H4 : ?y `in` fv_tm_tm_tm ?B,\n      H5 : ∀ a : atom,\n       a `in` fv_tm_tm_tm (open_tm_wrt_tm ?B (a_Var_f ?x))\n            → a `in` dom (?x ~ ?s ++ ?G) |- _ ] =>\n    assert (h0: y `in` dom (x ~ s ++ G)) by\n    (eapply H5; eauto;\n    eapply fv_tm_tm_tm_open_tm_wrt_tm_lower; auto);\n      simpl in h0; apply F.add_neq_iff in h0; auto\n           end.\n\n  all: try match goal with\n    [ H4 : ?y `in` fv_tm_tm_tm ?B,\n      H5 : ∀ a : atom,\n       a `in` fv_tm_tm_tm (open_tm_wrt_co ?B (g_Var_f ?x))\n            → a `in` dom (?x ~ ?s ++ ?G) |- _ ] =>\n    assert (h0: y `in` dom (x ~ s ++ G)) by\n    (eapply H5; eauto;\n    eapply fv_tm_tm_tm_open_tm_wrt_co_lower; auto);\n    simpl in h0; apply F.add_neq_iff in h0; auto\n           end.\n\n  all: try (simpl in *; eapply fv_tm_tm_tm_open_tm_wrt_tm_upper in IN;\n    apply F.union_iff in IN; destruct IN; eauto).\n  all: try (simpl in *; eapply fv_co_co_tm_open_tm_wrt_tm_upper in IN;\n    apply F.union_iff in IN; destruct IN; eauto).\n  all: try (simpl in *; eapply fv_tm_tm_tm_open_tm_wrt_co_upper in IN;\n    apply F.union_iff in IN; destruct IN; eauto).\n  all: try (simpl in *; eapply fv_co_co_tm_open_tm_wrt_co_upper in IN;\n    apply F.union_iff in IN; destruct IN; eauto).\n\n  all: try (apply H0 in IN; apply notin_empty_1 in IN; contradiction).\n  all: try (apply H1 in IN; apply notin_empty_1 in IN; contradiction).\n\n  all: try match goal with\n    [ H7 : ?y `in` union ?A ?B |- _ ] =>\n    apply F.union_iff in H7; destruct H7; eauto end.\n\n  all: try (simpl in *; match goal with [ H : ?y `in` Metatheory.empty |- _ ] => apply notin_empty_1 in H; done end).\n\n  all: try solve [destruct phi1; simpl in *; eauto].\n\n  all: try solve [ simpl in *; eauto].\n\n  all: try solve [ assert (c = y) by auto; subst; eapply binds_In; eauto ].\n  all: try solve [ destruct (H0 _ _ b0); simpl in *; eauto].\n  \n  all: try match goal with\n    [ H4 : ?y `in` fv_co_co_tm ?B,\n      H5 : ∀ a : atom,\n       a `in` fv_co_co_tm (open_tm_wrt_tm ?B (a_Var_f ?x))\n            → a `in` empty |- _ ] =>\n    (eapply H5; eauto;\n    eapply fv_co_co_tm_open_tm_wrt_tm_lower; auto)\n      end.\n\n  all: try match goal with\n    [ H4 : ?y `in` fv_co_co_tm ?B,\n      H5 : ∀ a : atom,\n       a `in` fv_co_co_tm (open_tm_wrt_co ?B (g_Var_f ?x))\n            → a `in` empty |- _ ] =>\n    eapply H5; eauto;\n    eapply fv_co_co_tm_open_tm_wrt_co_lower; auto\n  end.\n\nQed.\n\n\nDefinition Typing_context_fv  := first context_fv_mutual.\nDefinition ProfWff_context_fv := second context_fv_mutual.\nDefinition Iso_context_fv     := third context_fv_mutual.\nDefinition DefEq_context_fv   := fourth context_fv_mutual.\n\nLtac show_fresh :=\n  match goal with \n  | [H: Typing _ ?T _ |- ?c `notin` _ ?T ] => \n    move: (Typing_context_fv H) => ?; autofwd; auto\n  | [H: Typing _ _ ?T |- ?c `notin` _ ?T ] => \n    move: (Typing_context_fv H) => ?; autofwd; auto\n\n  end.\n", "meta": {"author": "sweirich", "repo": "corespec-roles", "sha": "6fefeb38ed51592b6d1304e82b3f419a8e15a932", "save_path": "github-repos/coq/sweirich-corespec-roles", "path": "github-repos/coq/sweirich-corespec-roles/corespec-roles-6fefeb38ed51592b6d1304e82b3f419a8e15a932/src/FcEtt/ext_context_fv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.23171579230926337}}
{"text": "(* Lifts for packing *)\n\nFrom Coq Require Import Bool String List BinPos Compare_dec Lia Arith.\nRequire Import Equations.Prop.DepElim.\nFrom Equations Require Import Equations.\nFrom Translation\nRequire Import util Sorts SAst SLiftSubst Equality SCommon XTyping\n               ITyping ITypingLemmata ITypingAdmissible.\nImport ListNotations.\n\nSection Pack.\n\nContext `{Sort_notion : Sorts.notion}.\n\n(* In order to do things properly we need to extend the context heterogenously,\n   this is done by extending the context with packed triples\n   (x : A, y : B, e : heq A x B y).\n   We call Γm the mix of Γ1 and Γ2.\n   We also need to define correspond lifts.\n\n   If Γ, Γ1, Δ |- t : T then\n   Γ, Γm, Δ↑ |- llift #|Γm| #|Δ| t : llift #|Γm| #|Δ| T\n   If Γ, Γ2, Δ |- t : T then\n   Γ, Γm, Δ↑ |- rlift #|Γm| #|Δ| t : rlift #|Γm| #|Δ| T\n *)\n\nFixpoint llift γ δ (t:sterm)  : sterm :=\n  match t with\n  | sRel i =>\n    if i <? δ\n    then sRel i\n    else if i <? δ + γ\n         then sProjT1 (sRel i)\n         else sRel i\n  | sLambda na A B b =>\n    sLambda na (llift γ δ A) (llift γ (S δ) B) (llift γ (S δ) b)\n  | sApp u A B v =>\n    sApp (llift γ δ u) (llift γ δ A) (llift γ (S δ) B) (llift γ δ v)\n  | sProd na A B => sProd na (llift γ δ A) (llift γ (S δ) B)\n  | sSum na A B => sSum na (llift γ δ A) (llift γ (S δ) B)\n  | sPair A B u v =>\n    sPair (llift γ δ A) (llift γ (S δ) B) (llift γ δ u) (llift γ δ v)\n  | sPi1 A B p => sPi1 (llift γ δ A) (llift γ (S δ) B) (llift γ δ p)\n  | sPi2 A B p => sPi2 (llift γ δ A) (llift γ (S δ) B) (llift γ δ p)\n  | sEq A u v => sEq (llift γ δ A) (llift γ δ u) (llift γ δ v)\n  | sRefl A u => sRefl (llift γ δ A) (llift γ δ u)\n  | sJ A u P w v p =>\n    sJ (llift γ δ A)\n       (llift γ δ u)\n       (llift γ (S (S δ)) P)\n       (llift γ δ w)\n       (llift γ δ v)\n       (llift γ δ p)\n  | sTransport A B p t =>\n    sTransport (llift γ δ A) (llift γ δ B) (llift γ δ p) (llift γ δ t)\n  | sBeta t u => sBeta (llift γ (S δ) t) (llift γ δ u)\n  | sHeq A a B b =>\n    sHeq (llift γ δ A) (llift γ δ a) (llift γ δ B) (llift γ δ b)\n  | sHeqToEq p => sHeqToEq (llift γ δ p)\n  | sHeqRefl A a => sHeqRefl (llift γ δ A) (llift γ δ a)\n  | sHeqSym p => sHeqSym (llift γ δ p)\n  | sHeqTrans p q => sHeqTrans (llift γ δ p) (llift γ δ q)\n  | sHeqTransport p t => sHeqTransport (llift γ δ p) (llift γ δ t)\n  | sCongProd B1 B2 p q =>\n    sCongProd (llift γ (S δ) B1) (llift γ (S δ) B2)\n              (llift γ δ p) (llift γ (S δ) q)\n  | sCongLambda B1 B2 t1 t2 pA pB pt =>\n    sCongLambda (llift γ (S δ) B1) (llift γ (S δ) B2)\n                (llift γ (S δ) t1) (llift γ (S δ) t2)\n                (llift γ δ pA) (llift γ (S δ) pB) (llift γ (S δ) pt)\n  | sCongApp B1 B2 pu pA pB pv =>\n    sCongApp (llift γ (S δ) B1) (llift γ (S δ) B2)\n             (llift γ δ pu) (llift γ δ pA) (llift γ (S δ) pB) (llift γ δ pv)\n  | sCongSum B1 B2 p q =>\n    sCongSum (llift γ (S δ) B1) (llift γ (S δ) B2)\n             (llift γ δ p) (llift γ (S δ) q)\n  | sCongPair B1 B2 pA pB pu pv =>\n    sCongPair (llift γ (S δ) B1) (llift γ (S δ) B2)\n             (llift γ δ pA) (llift γ (S δ) pB)\n             (llift γ δ pu) (llift γ δ pv)\n  | sCongPi1 B1 B2 pA pB pp =>\n    sCongPi1 (llift γ (S δ) B1) (llift γ (S δ) B2)\n             (llift γ δ pA) (llift γ (S δ) pB) (llift γ δ pp)\n  | sCongPi2 B1 B2 pA pB pp =>\n    sCongPi2 (llift γ (S δ) B1) (llift γ (S δ) B2)\n             (llift γ δ pA) (llift γ (S δ) pB) (llift γ δ pp)\n  | sCongEq pA pu pv => sCongEq (llift γ δ pA) (llift γ δ pu) (llift γ δ pv)\n  | sCongRefl pA pu => sCongRefl (llift γ δ pA) (llift γ δ pu)\n  | sEqToHeq p => sEqToHeq (llift γ δ p)\n  | sHeqTypeEq A B p => sHeqTypeEq (llift γ δ A) (llift γ δ B) (llift γ δ p)\n  | sSort x => sSort x\n  | sPack A B => sPack (llift γ δ A) (llift γ δ B)\n  | sProjT1 x => sProjT1 (llift γ δ x)\n  | sProjT2 x => sProjT2 (llift γ δ x)\n  | sProjTe x => sProjTe (llift γ δ x)\n  | sAx id => sAx id\n  end.\n\nFixpoint rlift γ δ t : sterm :=\n  match t with\n  | sRel i =>\n    if i <? δ\n    then sRel i\n    else if i <? δ + γ\n         then sProjT2 (sRel i)\n         else sRel i\n  | sLambda na A B b =>\n    sLambda na (rlift γ δ A) (rlift γ (S δ) B) (rlift γ (S δ) b)\n  | sApp u A B v =>\n    sApp (rlift γ δ u) (rlift γ δ A) (rlift γ (S δ) B) (rlift γ δ v)\n  | sProd na A B => sProd na (rlift γ δ A) (rlift γ (S δ) B)\n  | sSum na A B => sSum na (rlift γ δ A) (rlift γ (S δ) B)\n  | sPair A B u v =>\n    sPair (rlift γ δ A) (rlift γ (S δ) B) (rlift γ δ u) (rlift γ δ v)\n  | sPi1 A B p => sPi1 (rlift γ δ A) (rlift γ (S δ) B) (rlift γ δ p)\n  | sPi2 A B p => sPi2 (rlift γ δ A) (rlift γ (S δ) B) (rlift γ δ p)\n  | sEq A u v => sEq (rlift γ δ A) (rlift γ δ u) (rlift γ δ v)\n  | sRefl A u => sRefl (rlift γ δ A) (rlift γ δ u)\n  | sJ A u P w v p =>\n    sJ (rlift γ δ A)\n       (rlift γ δ u)\n       (rlift γ (S (S δ)) P)\n       (rlift γ δ w)\n       (rlift γ δ v)\n       (rlift γ δ p)\n  | sTransport A B p t =>\n    sTransport (rlift γ δ A) (rlift γ δ B) (rlift γ δ p) (rlift γ δ t)\n  | sBeta t u => sBeta (rlift γ (S δ) t) (rlift γ δ u)\n  | sHeq A a B b =>\n    sHeq (rlift γ δ A) (rlift γ δ a) (rlift γ δ B) (rlift γ δ b)\n  | sHeqToEq p => sHeqToEq (rlift γ δ p)\n  | sHeqRefl A a => sHeqRefl (rlift γ δ A) (rlift γ δ a)\n  | sHeqSym p => sHeqSym (rlift γ δ p)\n  | sHeqTrans p q => sHeqTrans (rlift γ δ p) (rlift γ δ q)\n  | sHeqTransport p t => sHeqTransport (rlift γ δ p) (rlift γ δ t)\n  | sCongProd B1 B2 p q =>\n    sCongProd (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n              (rlift γ δ p) (rlift γ (S δ) q)\n  | sCongLambda B1 B2 t1 t2 pA pB pt =>\n    sCongLambda (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n                (rlift γ (S δ) t1) (rlift γ (S δ) t2)\n                (rlift γ δ pA) (rlift γ (S δ) pB) (rlift γ (S δ) pt)\n  | sCongSum B1 B2 p q =>\n    sCongSum (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n              (rlift γ δ p) (rlift γ (S δ) q)\n  | sCongPair B1 B2 pA pB pu pv =>\n    sCongPair (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n             (rlift γ δ pA) (rlift γ (S δ) pB)\n             (rlift γ δ pu) (rlift γ δ pv)\n  | sCongPi1 B1 B2 pA pB pp =>\n    sCongPi1 (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n             (rlift γ δ pA) (rlift γ (S δ) pB) (rlift γ δ pp)\n  | sCongPi2 B1 B2 pA pB pp =>\n    sCongPi2 (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n             (rlift γ δ pA) (rlift γ (S δ) pB) (rlift γ δ pp)\n  | sCongApp B1 B2 pu pA pB pv =>\n    sCongApp (rlift γ (S δ) B1) (rlift γ (S δ) B2)\n             (rlift γ δ pu) (rlift γ δ pA) (rlift γ (S δ) pB) (rlift γ δ pv)\n  | sCongEq pA pu pv => sCongEq (rlift γ δ pA) (rlift γ δ pu) (rlift γ δ pv)\n  | sCongRefl pA pu => sCongRefl (rlift γ δ pA) (rlift γ δ pu)\n  | sEqToHeq p => sEqToHeq (rlift γ δ p)\n  | sHeqTypeEq A B p => sHeqTypeEq (rlift γ δ A) (rlift γ δ B) (rlift γ δ p)\n  | sSort x => sSort x\n  | sPack A B => sPack (rlift γ δ A) (rlift γ δ B)\n  | sProjT1 x => sProjT1 (rlift γ δ x)\n  | sProjT2 x => sProjT2 (rlift γ δ x)\n  | sProjTe x => sProjTe (rlift γ δ x)\n  | sAx id => sAx id\n  end.\n\nEnd Pack.\n\nNotation llift0 γ t := (llift γ 0 t).\nNotation rlift0 γ t := (rlift γ 0 t).\n\nSection Mix.\n\nContext `{Sort_notion : Sorts.notion}.\n\nInductive ismix Σ Γ : forall (Γ1 Γ2 Γm : scontext), Type :=\n| mixnil : ismix Σ Γ [] [] []\n| mixsnoc Γ1 Γ2 Γm s A1 A2 :\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γ1 |-i A1 : sSort s ->\n    Σ ;;; Γ ,,, Γ2 |-i A2 : sSort s ->\n    ismix Σ Γ\n          (Γ1 ,, A1)\n          (Γ2 ,, A2)\n          (Γm ,, (sPack (llift0 #|Γm| A1) (rlift0 #|Γm| A2)))\n.\n\nFact mix_length1 :\n  forall {Σ Γ Γ1 Γ2 Γm},\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    #|Γm| = #|Γ1|.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hm.\n  dependent induction hm.\n  - cbn. reflexivity.\n  - cbn. f_equal. assumption.\nDefined.\n\nFact mix_length2 :\n  forall {Σ Γ Γ1 Γ2 Γm},\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    #|Γm| = #|Γ2|.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hm.\n  dependent induction hm.\n  - cbn. reflexivity.\n  - cbn. f_equal. assumption.\nDefined.\n\nLemma llift00 :\n  forall {t δ}, llift 0 δ t = t.\nProof.\n  intro t.\n  induction t ; intro δ.\n  all: try (cbn ; f_equal ; easy).\n  cbn. case_eq δ.\n  + intro h. cbn. f_equal.\n  + intros m h. case_eq (n <=? m).\n    * intro. reflexivity.\n    * intro nlm. cbn.\n      replace (m+0)%nat with m by mylia.\n      rewrite nlm. f_equal.\nDefined.\n\nLemma rlift00 :\n  forall {t δ}, rlift 0 δ t = t.\nProof.\n  intro t.\n  induction t ; intro δ.\n  all: try (cbn ; f_equal ; easy).\n  cbn. case_eq δ.\n  + intro h. cbn. f_equal.\n  + intros m h. case_eq (n <=? m).\n    * intro. reflexivity.\n    * intro nlm. cbn.\n      replace (m+0)%nat with m by mylia.\n      rewrite nlm. f_equal.\nDefined.\n\nLemma lift_llift :\n  forall {t i j k},\n    lift i k (llift j k t) = llift (i+j) k (lift i k t).\nProof.\n  intro t. induction t ; intros i j k.\n  all: try (cbn ; f_equal ; easy).\n  unfold llift at 1. case_eq (n <? k) ; intro e ; bprop e.\n  - unfold lift. case_eq (k <=? n) ; intro e1 ; bprop e1 ; try mylia.\n    unfold llift. rewrite e. reflexivity.\n  - case_eq (n <? k + j) ; intro e1 ; bprop e1.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift. case_eq (i + n <? k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + (i+j)) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift. case_eq (i + n <? k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + (i + j)) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_llift' :\n  forall {t i j k},\n    lift i k (llift j k t) = llift j (k+i) (lift i k t).\nProof.\n  intro t. induction t ; intros i j k.\n  all: try (cbn ; f_equal ;\n            try replace (S (S (k + i))) with ((S (S k)) + i)%nat by mylia ;\n            try replace (S (k + i)) with ((S k) + i)%nat by mylia ;\n            easy).\n  unfold llift at 1. case_eq (n <? k) ; intro e ; bprop e.\n  - unfold lift. case_eq (k <=? n) ; intro e1 ; bprop e1 ; try mylia.\n    unfold llift. case_eq (n <? k + i) ; intro e3 ; bprop e3 ; try mylia.\n    reflexivity.\n  - case_eq (n <? k + j) ; intro e1 ; bprop e1.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift.\n      case_eq (i + n <? k + i) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + i + j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift.\n      case_eq (i + n <? k + i) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + i + j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_llift3 :\n  forall {t i j k l},\n    l <= k ->\n    lift i l (llift j k t) = llift j (i+k) (lift i l t).\nProof.\n  intro t. induction t ; intros i j k l h.\n  all: try (cbn ; f_equal ;\n            try replace (S (S (i + k))) with (i + (S (S k)))%nat by mylia ;\n            try replace (S (i + k)) with (i + (S k))%nat by mylia ;\n            easy).\n  unfold llift at 1.\n  case_eq (n <? k) ; intro e ; bprop e.\n  - cbn. case_eq (l <=? n) ; intro e1 ; bprop e1.\n    + unfold llift. case_eq (i + n <? i + k) ; intro e3 ; bprop e3 ; try mylia.\n      reflexivity.\n    + unfold llift. case_eq (n <? i + k) ; intro e3 ; bprop e3 ; try mylia.\n      reflexivity.\n  - case_eq (n <? k + j) ; intro e1 ; bprop e1.\n    + cbn. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift.\n      case_eq (i + n <? i + k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? i + k + j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + cbn. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift. case_eq (i+n <? i+k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i+n <? i+k+j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_llift4 :\n  forall {t i j k l},\n    k < i ->\n    i <= k + j ->\n    lift i l (llift (j - (i - k)) l t) = llift j (k+l) (lift i l t).\nProof.\n  intro t. induction t ; intros i j k l h1 h2.\n  all: try (cbn ; f_equal ;\n            try replace (S (S (k + l))) with (k + (S (S l)))%nat by mylia ;\n            try replace (S (k + l)) with (k + (S l))%nat by mylia ;\n            easy).\n  unfold llift at 1.\n  case_eq (n <? l) ; intro e ; bprop e ; try mylia.\n  - unfold lift. case_eq (l <=? n) ; intro e1 ; bprop e1 ; try mylia.\n    unfold llift. case_eq (n <? k + l) ; intro e3 ; bprop e3 ; try mylia.\n    reflexivity.\n  - case_eq (n <? l + (j - (i - k))) ; intro e1 ; bprop e1 ; try mylia.\n    + unfold lift. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift. case_eq (i+n <? k+l) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i+n <? k+l+j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + unfold lift. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold llift. case_eq (i+n <? k+l) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i+n <? k+l+j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_llift5 :\n  forall {t i j k l},\n    j + k <= i + l ->\n    l <= k ->\n    llift j k (lift i l t) = lift i l t.\nProof.\n  intro t; induction t ; intros i j k l h1 h2; cbn ; f_equal;\n    try eapply IHt; try eapply IHt1; try eapply IHt2; try eapply IHt3;\n    try eapply IHt4; try eapply IHt5; try eapply IHt6; try eapply IHt7;\n    try mylia.\n  unfold lift. case_eq (l <=? n) ; intro e ; bprop e.\n  - unfold llift. case_eq (i+n <? k) ; intro e1 ; bprop e1 ; try mylia.\n    case_eq (i+n <? k+j) ; intro e3 ; bprop e3 ; try mylia.\n    reflexivity.\n  - unfold llift. case_eq (n <? k) ; intro e1 ; bprop e1 ; try mylia.\n    reflexivity.\nDefined.\n\nLemma lift_rlift :\n  forall {t i j k},\n    lift i k (rlift j k t) = rlift (i+j) k (lift i k t).\nProof.\n  intro t. induction t ; intros i j k.\n  all: try (cbn ; f_equal ; easy).\n  unfold rlift at 1. case_eq (n <? k) ; intro e ; bprop e.\n  - unfold lift. case_eq (k <=? n) ; intro e1 ; bprop e1 ; try mylia.\n    unfold rlift. rewrite e. reflexivity.\n  - case_eq (n <? k + j) ; intro e1 ; bprop e1.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift. case_eq (i + n <? k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + (i+j)) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift. case_eq (i + n <? k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + (i + j)) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_rlift' :\n  forall {t i j k},\n    lift i k (rlift j k t) = rlift j (k+i) (lift i k t).\nProof.\n  intro t. induction t ; intros i j k.\n  all: try (cbn ; f_equal ;\n            try replace (S (S (k + i))) with ((S (S k)) + i)%nat by mylia ;\n            try replace (S (k + i)) with ((S k) + i)%nat by mylia ;\n            easy).\n  unfold rlift at 1. case_eq (n <? k) ; intro e ; bprop e.\n  - unfold lift. case_eq (k <=? n) ; intro e1 ; bprop e1 ; try mylia.\n    unfold rlift. case_eq (n <? k + i) ; intro e3 ; bprop e3 ; try mylia.\n    reflexivity.\n  - case_eq (n <? k + j) ; intro e1 ; bprop e1.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift.\n      case_eq (i + n <? k + i) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + i + j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + unfold lift. case_eq (k <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift.\n      case_eq (i + n <? k + i) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? k + i + j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_rlift3 :\n  forall {t i j k l},\n    l <= k ->\n    lift i l (rlift j k t) = rlift j (i+k) (lift i l t).\nProof.\n  intro t. induction t ; intros i j k l h.\n  all: try (cbn ; f_equal ;\n            try replace (S (S (i + k))) with (i + (S (S k)))%nat by mylia ;\n            try replace (S (i + k)) with (i + (S k))%nat by mylia ;\n            easy).\n  unfold rlift at 1.\n  case_eq (n <? k) ; intro e ; bprop e.\n  - cbn. case_eq (l <=? n) ; intro e1 ; bprop e1.\n    + unfold rlift. case_eq (i + n <? i + k) ; intro e3 ; bprop e3 ; try mylia.\n      reflexivity.\n    + unfold rlift. case_eq (n <? i + k) ; intro e3 ; bprop e3 ; try mylia.\n      reflexivity.\n  - case_eq (n <? k + j) ; intro e1 ; bprop e1.\n    + cbn. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift.\n      case_eq (i + n <? i + k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i + n <? i + k + j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + cbn. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift. case_eq (i+n <? i+k) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i+n <? i+k+j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_rlift4 :\n  forall {t i j k l},\n    k < i ->\n    i <= k + j ->\n    lift i l (rlift (j - (i - k)) l t) = rlift j (k+l) (lift i l t).\nProof.\n  intro t. induction t ; intros i j k l h1 h2.\n  all: try (cbn ; f_equal ;\n            try replace (S (S (k + l))) with (k + (S (S l)))%nat by mylia ;\n            try replace (S (k + l)) with (k + (S l))%nat by mylia ;\n            easy).\n  unfold rlift at 1.\n  case_eq (n <? l) ; intro e ; bprop e ; try mylia.\n  - unfold lift. case_eq (l <=? n) ; intro e1 ; bprop e1 ; try mylia.\n    unfold rlift. case_eq (n <? k + l) ; intro e3 ; bprop e3 ; try mylia.\n    reflexivity.\n  - case_eq (n <? l + (j - (i - k))) ; intro e1 ; bprop e1 ; try mylia.\n    + unfold lift. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift. case_eq (i+n <? k+l) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i+n <? k+l+j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\n    + unfold lift. case_eq (l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      unfold rlift. case_eq (i+n <? k+l) ; intro e5 ; bprop e5 ; try mylia.\n      case_eq (i+n <? k+l+j) ; intro e7 ; bprop e7 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma lift_rlift5 :\n  forall {t i j k l},\n    j + k <= i + l ->\n    l <= k ->\n    rlift j k (lift i l t) = lift i l t.\nProof.\n  intro t; induction t ; intros i j k l h1 h2; cbn; f_equal;\n    try eapply IHt; try eapply IHt1; try eapply IHt2; try eapply IHt3;\n    try eapply IHt4; try eapply IHt5; try eapply IHt6; try eapply IHt7;\n    try mylia.\n  unfold lift. case_eq (l <=? n) ; intro e ; bprop e.\n  - unfold rlift. case_eq (i+n <? k) ; intro e1 ; bprop e1 ; try mylia.\n    case_eq (i+n <? k+j) ; intro e3 ; bprop e3 ; try mylia.\n    reflexivity.\n  - unfold rlift. case_eq (n <? k) ; intro e1 ; bprop e1 ; try mylia.\n    reflexivity.\nDefined.\n\nFixpoint llift_context n (Δ : scontext) : scontext :=\n  match Δ with\n  | nil => nil\n  | A :: Δ => (llift n #|Δ| A) :: (llift_context n Δ)\n  end.\n\nFact llift_context_length :\n  forall {n Δ}, #|llift_context n Δ| = #|Δ|.\nProof.\n  intros n Δ.\n  induction Δ.\n  - cbn. reflexivity.\n  - cbn. f_equal. assumption.\nDefined.\n\nFact llift_context0 :\n  forall {Γ}, llift_context 0 Γ = Γ.\nProof.\n  intro Γ. induction Γ.\n  - reflexivity.\n  - cbn. rewrite llift00. rewrite IHΓ. reflexivity.\nDefined.\n\nFixpoint rlift_context n (Δ : scontext) : scontext :=\n  match Δ with\n  | nil => nil\n  | A :: Δ => (rlift n #|Δ| A) :: (rlift_context n Δ)\n  end.\n\nFact rlift_context_length :\n  forall {n Δ}, #|rlift_context n Δ| = #|Δ|.\nProof.\n  intros n Δ.\n  induction Δ.\n  - cbn. reflexivity.\n  - cbn. f_equal. assumption.\nDefined.\n\nFact rlift_context0 :\n  forall {Γ}, rlift_context 0 Γ = Γ.\nProof.\n  intro Γ. induction Γ.\n  - reflexivity.\n  - cbn. rewrite rlift00. rewrite IHΓ. reflexivity.\nDefined.\n\n(* We introduce an alternate version of ismix that will be implied by ismix but\n   will be used as an intermediary for the proof.\n *)\nInductive ismix' Σ Γ : forall (Γ1 Γ2 Γm : scontext), Type :=\n| mixnil' : ismix' Σ Γ [] [] []\n| mixsnoc' Γ1 Γ2 Γm s A1 A2 :\n    ismix' Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm |-i llift0 #|Γm| A1 : sSort s ->\n    Σ ;;; Γ ,,, Γm |-i rlift0 #|Γm|A2 : sSort s ->\n    ismix' Σ Γ\n          (Γ1 ,, A1)\n          (Γ2 ,, A2)\n          (Γm ,, (sPack (llift0 #|Γm| A1) (rlift0 #|Γm| A2)))\n.\n\nLemma wf_mix {Σ Γ Γ1 Γ2 Γm} (h : wf Σ Γ) :\n  ismix' Σ Γ Γ1 Γ2 Γm ->\n  wf Σ (Γ ,,, Γm).\nProof.\n  intro hm. induction hm.\n  - cbn. assumption.\n  - cbn. econstructor.\n    + assumption.\n    + eapply type_Pack with (s0 := s) ; assumption.\nDefined.\n\nFact mix'_length1 :\n  forall {Σ Γ Γ1 Γ2 Γm},\n    ismix' Σ Γ Γ1 Γ2 Γm ->\n    #|Γm| = #|Γ1|.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hm.\n  dependent induction hm.\n  - cbn. reflexivity.\n  - cbn. f_equal. assumption.\nDefined.\n\nFact mix'_length2 :\n  forall {Σ Γ Γ1 Γ2 Γm},\n    ismix' Σ Γ Γ1 Γ2 Γm ->\n    #|Γm| = #|Γ2|.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hm.\n  dependent induction hm.\n  - cbn. reflexivity.\n  - cbn. f_equal. assumption.\nDefined.\n\nDefinition llift_subst :\n  forall (u t : sterm) (i j m : nat),\n    llift j (i+m) (u {m := t}) = (llift j (S i+m) u) {m := llift j i t}.\nProof.\n  induction u ; intros t i j m.\n  all: try (cbn ; f_equal;\n            try replace (S (S (S (j + m))))%nat with (j + (S (S (S m))))%nat by mylia ;\n            try replace (S (S (j + m)))%nat with (j + (S (S m)))%nat by mylia ;\n            try replace (S (j + m))%nat with (j + (S m))%nat by mylia ;\n            try replace (S (S (S (i + m))))%nat with (i + (S (S (S m))))%nat by mylia ;\n            try replace (S (S (i + m)))%nat with (i + (S (S m)))%nat by mylia ;\n            try replace (S (i + m))%nat with (i + (S m))%nat by mylia;\n            try  (rewrite IHu; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu1; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu2; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu3; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu4; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu5; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu6; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu7; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu8; cbn; repeat f_equal; mylia)).\n  case_eq (m ?= n) ; intro e ; bprop e.\n  - subst. case_eq (n <=? i + n) ; intro e1 ; bprop e1 ; try mylia.\n    cbn. rewrite e. rewrite lift_llift3 by mylia.\n    f_equal. mylia.\n  - case_eq (n <=? i + m) ; intro e1 ; bprop e1.\n    + unfold llift at 1.\n      case_eq (Init.Nat.pred n <? i + m) ; intro e3 ; bprop e3 ; try mylia.\n      cbn. rewrite e. reflexivity.\n    + case_eq (n <=? i+m+j) ; intro e3 ; bprop e3.\n      * unfold llift at 1.\n        case_eq (Init.Nat.pred n <? i + m) ; intro e5 ; bprop e5 ; try mylia.\n        case_eq (Init.Nat.pred n <? i+m+j) ; intro e7 ; bprop e7 ; try mylia.\n        cbn. rewrite e. reflexivity.\n      * unfold llift at 1.\n        case_eq (Init.Nat.pred n <? i + m) ; intro e5 ; bprop e5 ; try mylia.\n        case_eq (Init.Nat.pred n <? i+m+j) ; intro e7 ; bprop e7 ; try mylia.\n        cbn. rewrite e. reflexivity.\n  - case_eq (n <=? i+m) ; intro e1 ; bprop e1 ; try mylia.\n    unfold llift at 1.\n    case_eq (n <? i+m) ; intro e3 ; bprop e3 ; try mylia.\n    cbn. rewrite e. reflexivity.\nDefined.\n\nDefinition rlift_subst :\n  forall (u t : sterm) (i j m : nat),\n    rlift j (i+m) (u {m := t}) = (rlift j (S i+m) u) {m := rlift j i t}.\nProof.\n  induction u ; intros t i j m.\n  all: try (cbn ; f_equal;\n            try replace (S (S (S (j + m))))%nat with (j + (S (S (S m))))%nat by mylia ;\n            try replace (S (S (j + m)))%nat with (j + (S (S m)))%nat by mylia ;\n            try replace (S (j + m))%nat with (j + (S m))%nat by mylia ;\n            try replace (S (S (S (i + m))))%nat with (i + (S (S (S m))))%nat by mylia ;\n            try replace (S (S (i + m)))%nat with (i + (S (S m)))%nat by mylia ;\n            try replace (S (i + m))%nat with (i + (S m))%nat by mylia;\n            try  (rewrite IHu; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu1; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu2; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu3; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu4; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu5; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu6; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu7; cbn; repeat f_equal; mylia);\n            try  (rewrite IHu8; cbn; repeat f_equal; mylia)).\n  case_eq (m ?= n) ; intro e ; bprop e.\n  - subst. case_eq (n <=? i + n) ; intro e1 ; bprop e1 ; try mylia.\n    cbn. rewrite e. rewrite lift_rlift3 by mylia.\n    f_equal. mylia.\n  - case_eq (n <=? i + m) ; intro e1 ; bprop e1.\n    + unfold rlift at 1.\n      case_eq (Init.Nat.pred n <? i + m) ; intro e3 ; bprop e3 ; try mylia.\n      cbn. rewrite e. reflexivity.\n    + case_eq (n <=? i+m+j) ; intro e3 ; bprop e3.\n      * unfold rlift at 1.\n        case_eq (Init.Nat.pred n <? i + m) ; intro e5 ; bprop e5 ; try mylia.\n        case_eq (Init.Nat.pred n <? i+m+j) ; intro e7 ; bprop e7 ; try mylia.\n        cbn. rewrite e. reflexivity.\n      * unfold rlift at 1.\n        case_eq (Init.Nat.pred n <? i + m) ; intro e5 ; bprop e5 ; try mylia.\n        case_eq (Init.Nat.pred n <? i+m+j) ; intro e7 ; bprop e7 ; try mylia.\n        cbn. rewrite e. reflexivity.\n  - case_eq (n <=? i+m) ; intro e1 ; bprop e1 ; try mylia.\n    unfold rlift at 1.\n    case_eq (n <? i+m) ; intro e3 ; bprop e3 ; try mylia.\n    cbn. rewrite e. reflexivity.\nDefined.\n\n(* Should be somewhere else. *)\nLemma inversion_wf_cat :\n  forall {Σ Δ Γ},\n    wf Σ (Γ ,,, Δ) ->\n    wf Σ Γ.\nProof.\n  intros Σ Δ. induction Δ ; intros Γ h.\n  - assumption.\n  - dependent destruction h.\n    apply IHΔ. assumption.\nDefined.\n\nFact nil_eq_cat :\n  forall {Δ Γ},\n    [] = Γ ,,, Δ ->\n    ([] = Γ) * ([] = Δ).\nProof.\n  intro Δ ; destruct Δ ; intros Γ e.\n  - rewrite cat_nil in e. split ; easy.\n  - cbn in e. inversion e.\nDefined.\n\n(* llift/rlift and closedness *)\n\nFact closed_above_llift_id :\n  forall t n k l,\n    closed_above l t = true ->\n    k >= l ->\n    llift n k t = t.\nProof.\n  intro t. induction t ; intros m k l clo h.\n  all: try (cbn ; cbn in clo ; repeat destruct_andb ;\n            repeat erewrite_close_above_lift_id ;\n            reflexivity).\n  unfold closed in clo. unfold closed_above in clo.\n  bprop clo. unfold llift.\n  case_eq (n <? k) ; intro e ; bprop e ; try mylia.\n  reflexivity.\nDefined.\n\nFact closed_llift :\n  forall t n k,\n    closed t ->\n    llift n k t = t.\nProof.\n  intros t n k h.\n  unfold closed in h.\n  eapply closed_above_llift_id.\n  - eassumption.\n  - mylia.\nDefined.\n\nFact closed_above_rlift_id :\n  forall t n k l,\n    closed_above l t = true ->\n    k >= l ->\n    rlift n k t = t.\nProof.\n  intro t. induction t ; intros m k l clo h.\n  all: try (cbn ; cbn in clo ; repeat destruct_andb ;\n            repeat erewrite_close_above_lift_id ;\n            reflexivity).\n  unfold closed in clo. unfold closed_above in clo.\n  bprop clo. unfold rlift.\n  case_eq (n <? k) ; intro e ; bprop e ; try mylia.\n  reflexivity.\nDefined.\n\nFact closed_rlift :\n  forall t n k,\n    closed t ->\n    rlift n k t = t.\nProof.\n  intros t n k h.\n  unfold closed in h.\n  eapply closed_above_rlift_id.\n  - eassumption.\n  - mylia.\nDefined.\n\nLemma nl_llift :\n  forall {t u n k},\n    nl t = nl u ->\n    nl (llift n k t) = nl (llift n k u).\nProof.\n  intros t u n k.\n  case (nl_dec (nl t) (nl u)).\n  - intros e _.\n    revert u e n k.\n    induction t ;\n    intros u e m k ; destruct u ; cbn in e ; try discriminate e.\n    all:\n      try (cbn ; inversion e ;\n           repeat (erewrite_assumption by eassumption) ; reflexivity).\n  - intros h e. exfalso. apply h. apply e.\nDefined.\n\nLemma nl_rlift :\n  forall {t u n k},\n    nl t = nl u ->\n    nl (rlift n k t) = nl (rlift n k u).\nProof.\n  intros t u n k.\n  case (nl_dec (nl t) (nl u)).\n  - intros e _.\n    revert u e n k.\n    induction t ;\n    intros u e m k ; destruct u ; cbn in e ; try discriminate e.\n    all:\n      try (cbn ; inversion e ;\n           repeat (erewrite_assumption by eassumption) ; reflexivity).\n  - intros h e. exfalso. apply h. apply e.\nDefined.\n\nFact llift_ax_type :\n  forall {Σ},\n    type_glob Σ ->\n    forall {id ty},\n      lookup_glob Σ id = Some ty ->\n      forall n k, llift n k ty = ty.\nProof.\n  intros Σ hg id ty isd n k.\n  destruct (typed_ax_type hg isd).\n  eapply closed_llift.\n  eapply type_ctxempty_closed. eassumption.\nDefined.\n\nFact rlift_ax_type :\n  forall {Σ},\n    type_glob Σ ->\n    forall {id ty},\n      lookup_glob Σ id = Some ty ->\n      forall n k, rlift n k ty = ty.\nProof.\n  intros Σ hg id ty isd n k.\n  destruct (typed_ax_type hg isd).\n  eapply closed_rlift.\n  eapply type_ctxempty_closed. eassumption.\nDefined.\n\nLemma nth_error_llift_context :\n  forall Γ k n A,\n    nth_error Γ n = Some A ->\n    nth_error (llift_context k Γ) n = Some (llift k (#|Γ| - S n) A).\nProof.\n  intros Γ k n A e.\n  induction Γ in k, n, A, e |- *.\n  1:{ destruct n. all: discriminate. }\n  destruct n.\n  - cbn in e. inversion e. subst. clear e.\n    cbn. f_equal. f_equal. mylia.\n  - cbn. cbn in e. eapply IHΓ in e. rewrite e. reflexivity.\nDefined.\n\nLemma nth_error_rlift_context :\n  forall Γ k n A,\n    nth_error Γ n = Some A ->\n    nth_error (rlift_context k Γ) n = Some (rlift k (#|Γ| - S n) A).\nProof.\n  intros Γ k n A e.\n  induction Γ in k, n, A, e |- *.\n  1:{ destruct n. all: discriminate. }\n  destruct n.\n  - cbn in e. inversion e. subst. clear e.\n    cbn. f_equal. f_equal. mylia.\n  - cbn. cbn in e. eapply IHΓ in e. rewrite e. reflexivity.\nDefined.\n\nLemma nth_error_ismix'_left :\n  forall Σ Γ Γ1 Γ2 Γm n A,\n    ismix' Σ Γ Γ1 Γ2 Γm ->\n    nth_error Γ1 n = Some A ->\n    ∑ B,\n      nth_error Γ2 n = Some B /\\\n      nth_error Γm n =\n      Some (sPack (llift0 (#|Γm| - S n) A) (rlift0 (#|Γm| - S n) B)).\nProof.\n  intros Σ Γ Γ1 Γ2 Γm n A hm e.\n  induction hm in A, n, e |- *.\n  1:{ destruct n. all: discriminate. }\n  destruct n.\n  - cbn in e. inversion e. subst. clear e.\n    cbn. eexists. intuition eauto.\n    f_equal. f_equal. all: f_equal. all: mylia.\n  - cbn in e. eapply IHhm in e as [B [e2 em]].\n    cbn. eexists. intuition eauto.\nDefined.\n\nLemma nth_error_ismix'_right :\n  forall Σ Γ Γ1 Γ2 Γm n A,\n    ismix' Σ Γ Γ1 Γ2 Γm ->\n    nth_error Γ2 n = Some A ->\n    ∑ B,\n      nth_error Γ1 n = Some B /\\\n      nth_error Γm n =\n      Some (sPack (llift0 (#|Γm| - S n) B) (rlift0 (#|Γm| - S n) A)).\nProof.\n  intros Σ Γ Γ1 Γ2 Γm n A hm e.\n  induction hm in A, n, e |- *.\n  1:{ destruct n. all: discriminate. }\n  destruct n.\n  - cbn in e. inversion e. subst. clear e.\n    cbn. eexists. intuition eauto.\n    f_equal. f_equal. all: f_equal. all: mylia.\n  - cbn in e. eapply IHhm in e as [B [e2 em]].\n    cbn. eexists. intuition eauto.\nDefined.\n\nLtac lh h :=\n  lazymatch goal with\n  | [ type_llift' :\n        forall (Σ : sglobal_context) (Γ Γ1 Γ2 Γm Δ : scontext) (t A : sterm),\n          Σ;;; Γ ,,, Γ1 ,,, Δ |-i t : A ->\n          type_glob Σ ->\n          ismix' Σ Γ Γ1 Γ2 Γm ->\n          Σ;;; Γ ,,, Γm ,,, llift_context #|Γm| Δ\n          |-i llift #|Γm| #|Δ| t : llift #|Γm| #|Δ| A\n    |- _ ] =>\n    lazymatch type of h with\n    | _ ;;; ?Γ' ,,, ?Γ1' ,,, ?Δ' |-i _ : ?T' =>\n      eapply meta_conv ; [\n        eapply meta_ctx_conv ; [\n          eapply type_llift' with (Γ := Γ') (Γ1 := Γ1') (Δ := Δ') (A := T') ; [\n            exact h\n          | eassumption\n          | eassumption\n          ]\n        | .. ]\n      | .. ]\n    | _ ;;; (?Γ' ,,, ?Γ1' ,,, ?Δ'),, ?d' |-i _ : ?T' =>\n      eapply meta_conv ; [\n        eapply meta_ctx_conv ; [\n          eapply type_llift' with (Γ := Γ') (Γ1 := Γ1') (Δ := Δ',, d') (A := T') ; [\n            exact h\n          | eassumption\n          | eassumption\n          ]\n        | .. ]\n      | .. ]\n    | _ ;;; (?Γ' ,,, ?Γ1' ,,, ?Δ'),, ?d',, ?d'' |-i _ : ?T' =>\n      eapply meta_conv ; [\n        eapply meta_ctx_conv ; [\n          eapply type_llift' with (Γ := Γ') (Γ1 := Γ1') (Δ := (Δ',, d'),, d'') (A := T') ; [\n            exact h\n          | eassumption\n          | eassumption\n          ]\n        | .. ]\n      | .. ]\n    end ; try (cbn ; reflexivity)\n  | _ => fail \"Cannot retrieve type_llift'\"\n  end.\n\nLtac rh h :=\n  lazymatch goal with\n  | [ type_rlift' :\n        forall (Σ : sglobal_context) (Γ Γ1 Γ2 Γm Δ : scontext) (t A : sterm),\n          Σ;;; Γ ,,, Γ2 ,,, Δ |-i t : A ->\n          type_glob Σ ->\n          ismix' Σ Γ Γ1 Γ2 Γm ->\n          Σ;;; Γ ,,, Γm ,,, rlift_context #|Γm| Δ\n          |-i rlift #|Γm| #|Δ| t : rlift #|Γm| #|Δ| A\n    |- _ ] =>\n    lazymatch type of h with\n    | _ ;;; ?Γ' ,,, ?Γ2' ,,, ?Δ' |-i _ : ?T' =>\n      eapply meta_conv ; [\n        eapply meta_ctx_conv ; [\n          eapply type_rlift' with (Γ := Γ') (Γ2 := Γ2') (Δ := Δ') (A := T') ; [\n            exact h\n          | eassumption\n          | eassumption\n          ]\n        | .. ]\n      | .. ]\n    | _ ;;; (?Γ' ,,, ?Γ2' ,,, ?Δ'),, ?d' |-i _ : ?T' =>\n      eapply meta_conv ; [\n        eapply meta_ctx_conv ; [\n          eapply type_rlift' with (Γ := Γ') (Γ2 := Γ2') (Δ := Δ',, d') (A := T') ; [\n            exact h\n          | eassumption\n          | eassumption\n          ]\n        | .. ]\n      | .. ]\n    | _ ;;; (?Γ' ,,, ?Γ2' ,,, ?Δ'),, ?d',, ?d'' |-i _ : ?T' =>\n      eapply meta_conv ; [\n        eapply meta_ctx_conv ; [\n          eapply type_rlift' with (Γ := Γ') (Γ2 := Γ2') (Δ := (Δ',, d'),, d'') (A := T') ; [\n            exact h\n          | eassumption\n          | eassumption\n          ]\n        | .. ]\n      | .. ]\n    end ; try (cbn ; reflexivity)\n  | _ => fail \"Cannot retrieve type_rlift'\"\n  end.\n\nLtac emh :=\n  lazymatch goal with\n  | h : _ ;;; _ |-i ?t : _ |- _ ;;; _ |-i llift _ _ ?t : _ => lh h\n  | h : _ ;;; _ |-i ?t : _ |- _ ;;; _ |-i rlift _ _ ?t : _ => rh h\n  | _ => fail \"Not a case for emh\"\n  end.\n\nFixpoint type_llift' {Σ Γ Γ1 Γ2 Γm Δ t A}\n  (h : Σ ;;; Γ ,,, Γ1 ,,, Δ |-i t : A) {struct h} :\n  type_glob Σ ->\n  ismix' Σ Γ Γ1 Γ2 Γm ->\n  Σ ;;; Γ ,,, Γm ,,, llift_context #|Γm| Δ\n  |-i llift #|Γm| #|Δ| t : llift #|Γm| #|Δ| A\n\nwith type_rlift' {Σ Γ Γ1 Γ2 Γm Δ t A}\n  (h : Σ ;;; Γ ,,, Γ2 ,,, Δ |-i t : A) {struct h} :\n  type_glob Σ ->\n  ismix' Σ Γ Γ1 Γ2 Γm ->\n  Σ ;;; Γ ,,, Γm ,,, rlift_context #|Γm| Δ\n  |-i rlift #|Γm| #|Δ| t : rlift #|Γm| #|Δ| A\n\nwith wf_llift' {Σ Γ Γ1 Γ2 Γm Δ} (h : wf Σ (Γ ,,, Γ1 ,,, Δ)) {struct h} :\n  type_glob Σ ->\n  ismix' Σ Γ Γ1 Γ2 Γm ->\n  wf Σ (Γ ,,, Γm ,,, llift_context #|Γm| Δ)\n\nwith wf_rlift' {Σ Γ Γ1 Γ2 Γm Δ} (h : wf Σ (Γ ,,, Γ2 ,,, Δ)) {struct h} :\n  type_glob Σ ->\n  ismix' Σ Γ Γ1 Γ2 Γm ->\n  wf Σ (Γ ,,, Γm ,,, rlift_context #|Γm| Δ)\n.\nProof.\n  (* type_llift' *)\n  - { dependent destruction h ; intros hg hm.\n      - unfold llift at 1.\n        case_eq (n <? #|Δ|) ; intro e ; bprop e.\n        + eapply meta_conv.\n          * eapply type_Rel.\n            1: eapply wf_llift' ; eassumption.\n            unfold \",,,\". rewrite nth_error_app1.\n            2:{ rewrite llift_context_length. auto. }\n            eapply nth_error_llift_context.\n            unfold \",,,\" in H0. rewrite nth_error_app1 in H0 by auto.\n            eassumption.\n          * rewrite lift_llift3 by mylia.\n            f_equal. mylia.\n        + case_eq (n <? #|Δ| + #|Γm|) ; intro e1 ; bprop e1.\n          * unfold \",,,\" in H0. rewrite nth_error_app2 in H0 by auto.\n            apply mix'_length1 in hm as ?.\n            rewrite nth_error_app1 in H0 by mylia.\n            eapply nth_error_ismix'_left in H0 as [B [e' em]].\n            2: eassumption.\n            eapply type_ProjT1' ; try assumption.\n            eapply meta_conv.\n            -- eapply type_Rel.\n               1: eapply wf_llift' ; eassumption.\n               unfold \",,,\". rewrite nth_error_app2.\n               2:{ rewrite llift_context_length. auto. }\n               rewrite llift_context_length.\n               rewrite nth_error_app1 by mylia.\n               eassumption.\n            -- cbn. f_equal.\n               replace #|Δ| with (#|Δ| + 0)%nat at 2 by mylia.\n               rewrite <- lift_llift4 by mylia.\n               f_equal. f_equal. mylia.\n          * eapply meta_conv.\n            -- eapply type_Rel.\n               1: eapply wf_llift' ; eassumption.\n               unfold \",,,\". rewrite nth_error_app2.\n               2:{ rewrite llift_context_length. auto. }\n               rewrite llift_context_length.\n               rewrite nth_error_app2 by mylia.\n               unfold \",,,\" in H0. rewrite nth_error_app2 in H0 by auto.\n               apply  mix'_length1 in hm as e'.\n               rewrite nth_error_app2 in H0 by mylia.\n               rewrite e'. eassumption.\n            -- rewrite lift_llift5 by mylia. reflexivity.\n      - cbn. eapply type_Sort. eapply wf_llift' ; eassumption.\n      - cbn. eapply type_Prod ; emh.\n      - cbn. eapply type_Lambda ; emh.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite llift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_App ; emh.\n      - cbn. eapply type_Sum ; emh.\n      - cbn. eapply type_Pair ; emh.\n        replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite llift_subst.\n        cbn. replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        reflexivity.\n      - cbn. eapply type_Pi1 ; emh.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite llift_subst.\n        cbn. replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_Pi2 ; emh.\n      - cbn. eapply type_Eq ; emh.\n      - cbn. eapply type_Refl ; emh.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite llift_subst.\n        replace (S #|Δ| + 0)%nat with (#|Δ| + 1)%nat by mylia.\n        rewrite llift_subst.\n        cbn. replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        replace (S (#|Δ| + 1))%nat with (S (S #|Δ|)) by mylia.\n        eapply type_J ; emh.\n        + cbn. unfold ssnoc. cbn. f_equal. f_equal.\n          * replace (S #|Δ|) with (1 + #|Δ|)%nat by mylia.\n            rewrite lift_llift3 by mylia. reflexivity.\n          * replace (S #|Δ|) with (1 + #|Δ|)%nat by mylia.\n            rewrite lift_llift3 by mylia. reflexivity.\n        + replace (S (S #|Δ|)) with ((S #|Δ|) + 1)%nat by mylia.\n          rewrite <- llift_subst.\n          change (sRefl (llift #|Γm| #|Δ| A0) (llift #|Γm| #|Δ| u))\n            with (llift #|Γm| #|Δ| (sRefl A0 u)).\n          replace (#|Δ| + 1)%nat with (S #|Δ| + 0)%nat by mylia.\n          rewrite <- llift_subst. f_equal. mylia.\n      - cbn. eapply type_Transport ; emh.\n      - cbn.\n        replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite 2!llift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_Beta ; emh.\n      - cbn. eapply type_Heq ; emh.\n      - cbn. eapply type_HeqToEq ; emh.\n      - cbn. eapply type_HeqRefl ; emh.\n      - cbn. eapply type_HeqSym ; emh.\n      - cbn.\n        eapply @type_HeqTrans\n          with (B := llift #|Γm| #|Δ| B) (b := llift #|Γm| #|Δ| b) ; emh.\n      - cbn. eapply type_HeqTransport ; emh.\n      - cbn. eapply type_CongProd ; emh.\n        cbn. f_equal.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongLambda ; emh.\n        + cbn. f_equal.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n        + cbn. f_equal.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite 2!llift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_CongApp ; emh.\n        cbn. f_equal.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongSum ; emh.\n        cbn. f_equal.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongPair ; emh.\n        + cbn. f_equal.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n          * rewrite lift_llift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite llift_subst. cbn. reflexivity.\n        + cbn. f_equal.\n          * replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n            rewrite llift_subst. cbn.\n            replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n            reflexivity.\n          * replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n            rewrite llift_subst. cbn.\n            replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n            reflexivity.\n        + replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n          rewrite llift_subst. cbn.\n          replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n          reflexivity.\n        + replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n          rewrite llift_subst. cbn.\n          replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n          reflexivity.\n      - cbn. eapply type_CongPi1 ; emh.\n        cbn. f_equal.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite 2!llift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_CongPi2 ; emh.\n        cbn. f_equal.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n        + rewrite lift_llift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite llift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongEq ; emh.\n      - cbn. eapply type_CongRefl ; emh.\n      - cbn. eapply type_EqToHeq ; emh.\n      - cbn. eapply type_HeqTypeEq ; emh.\n      - cbn. eapply type_Pack ; emh.\n      - cbn. eapply @type_ProjT1 with (A2 := llift #|Γm| #|Δ| A2) ; emh.\n      - cbn. eapply @type_ProjT2 with (A1 := llift #|Γm| #|Δ| A1) ; emh.\n      - cbn. eapply type_ProjTe ; emh.\n      - cbn. erewrite llift_ax_type by eassumption.\n        eapply type_Ax.\n        + eapply wf_llift' ; eassumption.\n        + assumption.\n      - eapply type_rename.\n        + emh.\n        + eapply nl_llift. assumption.\n    }\n\n  (* type_rlift' *)\n  - { dependent destruction h ; intros hg hm.\n      - unfold rlift at 1.\n        case_eq (n <? #|Δ|) ; intro e ; bprop e.\n        + eapply meta_conv.\n          * eapply type_Rel.\n            1: eapply wf_rlift' ; eassumption.\n            unfold \",,,\". rewrite nth_error_app1.\n            2:{ rewrite rlift_context_length. auto. }\n            eapply nth_error_rlift_context.\n            unfold \",,,\" in H0. rewrite nth_error_app1 in H0 by auto.\n            eassumption.\n          * rewrite lift_rlift3 by mylia.\n            f_equal. mylia.\n        + case_eq (n <? #|Δ| + #|Γm|) ; intro e1 ; bprop e1.\n          * unfold \",,,\" in H0. rewrite nth_error_app2 in H0 by auto.\n            apply mix'_length2 in hm as ?.\n            rewrite nth_error_app1 in H0 by mylia.\n            eapply nth_error_ismix'_right in H0 as [B [e' em]].\n            2: eassumption.\n            eapply type_ProjT2' ; try assumption.\n            eapply meta_conv.\n            -- eapply type_Rel.\n               1: eapply wf_rlift' ; eassumption.\n               unfold \",,,\". rewrite nth_error_app2.\n               2:{ rewrite rlift_context_length. auto. }\n               rewrite rlift_context_length.\n               rewrite nth_error_app1 by mylia.\n               eassumption.\n            -- cbn. f_equal.\n               replace #|Δ| with (#|Δ| + 0)%nat at 2 by mylia.\n               rewrite <- lift_rlift4 by mylia.\n               f_equal. f_equal. mylia.\n          * eapply meta_conv.\n            -- eapply type_Rel.\n               1: eapply wf_rlift' ; eassumption.\n               unfold \",,,\". rewrite nth_error_app2.\n               2:{ rewrite rlift_context_length. auto. }\n               rewrite rlift_context_length.\n               rewrite nth_error_app2 by mylia.\n               unfold \",,,\" in H0. rewrite nth_error_app2 in H0 by auto.\n               apply  mix'_length2 in hm as e'.\n               rewrite nth_error_app2 in H0 by mylia.\n               rewrite e'. eassumption.\n            -- rewrite lift_rlift5 by mylia. reflexivity.\n      - cbn. eapply type_Sort. eapply wf_rlift' ; eassumption.\n      - cbn. eapply type_Prod ; emh.\n      - cbn. eapply type_Lambda ; emh.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite rlift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_App ; emh.\n      - cbn. eapply type_Sum ; emh.\n      - cbn. eapply type_Pair ; emh.\n        replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite rlift_subst.\n        cbn. replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        reflexivity.\n      - cbn. eapply type_Pi1 ; emh.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite rlift_subst.\n        cbn. replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_Pi2 ; emh.\n      - cbn. eapply type_Eq ; emh.\n      - cbn. eapply type_Refl ; emh.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite rlift_subst.\n        replace (S #|Δ| + 0)%nat with (#|Δ| + 1)%nat by mylia.\n        rewrite rlift_subst.\n        cbn. replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        replace (S (#|Δ| + 1))%nat with (S (S #|Δ|)) by mylia.\n        eapply type_J ; emh.\n        + cbn. unfold ssnoc. cbn. f_equal. f_equal.\n          * replace (S #|Δ|) with (1 + #|Δ|)%nat by mylia.\n            rewrite lift_rlift3 by mylia. reflexivity.\n          * replace (S #|Δ|) with (1 + #|Δ|)%nat by mylia.\n            rewrite lift_rlift3 by mylia. reflexivity.\n        + replace (S (S #|Δ|)) with ((S #|Δ|) + 1)%nat by mylia.\n          rewrite <- rlift_subst.\n          change (sRefl (rlift #|Γm| #|Δ| A0) (rlift #|Γm| #|Δ| u))\n            with (rlift #|Γm| #|Δ| (sRefl A0 u)).\n          replace (#|Δ| + 1)%nat with (S #|Δ| + 0)%nat by mylia.\n          rewrite <- rlift_subst. f_equal. mylia.\n      - cbn. eapply type_Transport ; emh.\n      - cbn.\n        replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite 2!rlift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_Beta ; emh.\n      - cbn. eapply type_Heq ; emh.\n      - cbn. eapply type_HeqToEq ; emh.\n      - cbn. eapply type_HeqRefl ; emh.\n      - cbn. eapply type_HeqSym ; emh.\n      - cbn.\n        eapply @type_HeqTrans\n          with (B := rlift #|Γm| #|Δ| B) (b := rlift #|Γm| #|Δ| b) ; emh.\n      - cbn. eapply type_HeqTransport ; emh.\n      - cbn. eapply type_CongProd ; emh.\n        cbn. f_equal.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongLambda ; emh.\n        + cbn. f_equal.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n        + cbn. f_equal.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite 2!rlift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_CongApp ; emh.\n        cbn. f_equal.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongSum ; emh.\n        cbn. f_equal.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongPair ; emh.\n        + cbn. f_equal.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n          * rewrite lift_rlift3 by mylia.\n            replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n            rewrite rlift_subst. cbn. reflexivity.\n        + cbn. f_equal.\n          * replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n            rewrite rlift_subst. cbn.\n            replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n            reflexivity.\n          * replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n            rewrite rlift_subst. cbn.\n            replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n            reflexivity.\n        + replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n          rewrite rlift_subst. cbn.\n          replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n          reflexivity.\n        + replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n          rewrite rlift_subst. cbn.\n          replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n          reflexivity.\n      - cbn. eapply type_CongPi1 ; emh.\n        cbn. f_equal.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n      - cbn. replace #|Δ| with (#|Δ| + 0)%nat by mylia.\n        rewrite 2!rlift_subst. cbn.\n        replace (#|Δ| + 0)%nat with #|Δ| by mylia.\n        eapply type_CongPi2 ; emh.\n        cbn. f_equal.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n        + rewrite lift_rlift3 by mylia.\n          replace (S #|Δ|) with ((S #|Δ|) + 0)%nat by mylia.\n          rewrite rlift_subst. cbn. reflexivity.\n      - cbn. eapply type_CongEq ; emh.\n      - cbn. eapply type_CongRefl ; emh.\n      - cbn. eapply type_EqToHeq ; emh.\n      - cbn. eapply type_HeqTypeEq ; emh.\n      - cbn. eapply type_Pack ; emh.\n      - cbn. eapply @type_ProjT1 with (A2 := rlift #|Γm| #|Δ| A2) ; emh.\n      - cbn. eapply @type_ProjT2 with (A1 := rlift #|Γm| #|Δ| A1) ; emh.\n      - cbn. eapply type_ProjTe ; emh.\n      - cbn. erewrite rlift_ax_type by eassumption.\n        eapply type_Ax.\n        + eapply wf_rlift' ; eassumption.\n        + assumption.\n      - eapply type_rename.\n        + emh.\n        + eapply nl_rlift. assumption.\n    }\n\n  (* wf_llift' *)\n  - { destruct Δ.\n      - cbn. rewrite cat_nil in h.\n        intros hg hm. eapply wf_mix.\n        + eapply inversion_wf_cat. eassumption.\n        + eassumption.\n      - cbn. intros hg hm. dependent destruction h.\n        econstructor.\n        + eapply wf_llift' ; eassumption.\n        + eapply type_llift' with (A := sSort s0) ; eassumption.\n    }\n\n  (* wf_rlift' *)\n  - { destruct Δ.\n      - cbn. rewrite cat_nil in h.\n        intros hg hm. eapply wf_mix.\n        + eapply inversion_wf_cat. eassumption.\n        + eassumption.\n      - cbn. intros hg hm. dependent destruction h.\n        econstructor.\n        + eapply wf_rlift' ; eassumption.\n        + eapply type_rlift' with (A := sSort s0) ; eassumption.\n    }\n\n  Unshelve.\n  all: pose (mix'_length1 hm) ;\n       pose (mix'_length2 hm) ;\n       cbn ; try rewrite !length_cat ;\n       try rewrite !llift_context_length ;\n       try rewrite !rlift_context_length ;\n       try rewrite !length_cat in isdecl ;\n       try mylia.\nDefined.\n\nLemma ismix_ismix' :\n  forall {Σ Γ Γ1 Γ2 Γm},\n    type_glob Σ ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    ismix' Σ Γ Γ1 Γ2 Γm.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hg h.\n  dependent induction h.\n  - constructor.\n  - econstructor.\n    + assumption.\n    + eapply @type_llift' with (A := sSort s) (Δ := []) ; eassumption.\n    + eapply @type_rlift' with (A := sSort s) (Δ := []) ; eassumption.\nDefined.\n\nCorollary type_llift :\n  forall {Σ Γ Γ1 Γ2 Γm Δ t A},\n    type_glob Σ ->\n    Σ ;;; Γ ,,, Γ1 ,,, Δ |-i t : A ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm ,,, llift_context #|Γm| Δ\n    |-i llift #|Γm| #|Δ| t : llift #|Γm| #|Δ| A.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm Δ t A hg ht hm.\n  eapply type_llift'.\n  - eassumption.\n  - assumption.\n  - eapply ismix_ismix' ; eassumption.\nDefined.\n\nCorollary wf_llift :\n  forall {Σ Γ Γ1 Γ2 Γm Δ},\n    type_glob Σ ->\n    wf Σ (Γ ,,, Γ1 ,,, Δ) ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    wf Σ (Γ ,,, Γm ,,, llift_context #|Γm| Δ).\nProof.\n  intros Σ Γ Γ1 Γ2 Γm Δ hg hw hm.\n  eapply wf_llift'.\n  - eassumption.\n  - assumption.\n  - eapply ismix_ismix' ; eassumption.\nDefined.\n\nCorollary type_rlift :\n  forall {Σ Γ Γ1 Γ2 Γm Δ t A},\n    type_glob Σ ->\n    Σ ;;; Γ ,,, Γ2 ,,, Δ |-i t : A ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm ,,, rlift_context #|Γm| Δ\n    |-i rlift #|Γm| #|Δ| t : rlift #|Γm| #|Δ| A.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm Δ t A hg ht hm.\n  eapply type_rlift'.\n  - eassumption.\n  - assumption.\n  - eapply ismix_ismix' ; eassumption.\nDefined.\n\nCorollary wf_rlift :\n  forall {Σ Γ Γ1 Γ2 Γm Δ},\n    type_glob Σ ->\n    wf Σ (Γ ,,, Γ2 ,,, Δ) ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    wf Σ (Γ ,,, Γm ,,, rlift_context #|Γm| Δ).\nProof.\n  intros Σ Γ Γ1 Γ2 Γm Δ hg hw hm.\n  eapply wf_rlift'.\n  - eassumption.\n  - assumption.\n  - eapply ismix_ismix' ; eassumption.\nDefined.\n\n(* Lemma to use ismix knowledge about sorting. *)\nLemma ismix_nth_sort :\n  forall {Σ Γ Γ1 Γ2 Γm},\n    type_glob Σ ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    forall n A1 A2,\n      nth_error Γ1 n = Some A1 ->\n      nth_error Γ2 n = Some A2 ->\n      ∑ s,\n        (Σ;;; Γ ,,, Γ1 |-i lift0 (S n) A1 : sSort s) *\n        (Σ;;; Γ ,,, Γ2 |-i lift0 (S n) A2 : sSort s).\nProof.\n  intros Σ Γ Γ1 Γ2 Γm hg hm n A1 A2 e1 e2.\n  induction hm in n, A1, A2, e1, e2 |- *.\n  1:{ destruct n. all: discriminate. }\n  destruct n.\n  - cbn in *. inversion e1. inversion e2. subst. clear e1 e2.\n    exists s. split.\n    all: eapply @typing_lift01 with (A := sSort s).\n    all: eassumption.\n  - cbn in *.\n    specialize IHhm with (1 := e1) (2 := e2).\n    destruct IHhm as [s' [h1 h2]].\n    exists s'. split.\n    + replace (S (S n)) with (1 + (S n))%nat by mylia.\n      rewrite <- liftP3 with (k := 0) by mylia.\n      eapply @typing_lift01 with (A := sSort s'). all: eassumption.\n    + replace (S (S n)) with (1 + (S n))%nat by mylia.\n      rewrite <- liftP3 with (k := 0) by mylia.\n      eapply @typing_lift01 with (A := sSort s'). all: eassumption.\nDefined.\n\n(* Simpler to use corollaries *)\n\nCorollary type_llift0 :\n  forall {Σ Γ Γ1 Γ2 Γm t A},\n    type_glob Σ ->\n    Σ ;;; Γ ,,, Γ1 |-i t : A ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm |-i llift0 #|Γm| t : llift0 #|Γm| A.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm t A hg ? ?.\n  eapply @type_llift with (Δ := nil) ; eassumption.\nDefined.\n\nCorollary type_llift1 :\n  forall {Σ Γ Γ1 Γ2 Γm t A B},\n    type_glob Σ ->\n    Σ ;;; (Γ ,,, Γ1) ,, B |-i t : A ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm ,, (llift0 #|Γm| B)\n    |-i llift #|Γm| 1 t : llift #|Γm| 1 A.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm t A B hg ht hm.\n  eapply @type_llift with (Δ := [ B ]).\n  - assumption.\n  - exact ht.\n  - eassumption.\nDefined.\n\nCorollary type_rlift0 :\n  forall {Σ Γ Γ1 Γ2 Γm t A},\n    type_glob Σ ->\n    Σ ;;; Γ ,,, Γ2 |-i t : A ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm |-i rlift0 #|Γm| t : rlift0 #|Γm| A.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm t A ? ? ?.\n  eapply @type_rlift with (Δ := nil) ; eassumption.\nDefined.\n\nCorollary type_rlift1 :\n  forall {Σ Γ Γ1 Γ2 Γm t A B},\n    type_glob Σ ->\n    Σ ;;; (Γ ,,, Γ2) ,, B |-i t : A ->\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    Σ ;;; Γ ,,, Γm ,, (rlift0 #|Γm| B)\n    |-i rlift #|Γm| 1 t : rlift #|Γm| 1 A.\nProof.\n  intros Σ Γ Γ1 Γ2 Γm t A B hg ht hm.\n  eapply @type_rlift with (Δ := [ B ]).\n  - assumption.\n  - exact ht.\n  - eassumption.\nDefined.\n\n(* More lemmata about exchange.\n   They should go above with the others.\n *)\n\nLemma llift_substProj :\n  forall {t γ l},\n    (lift 1 (S l) (llift γ (S l) t)) {l := sProjT1 (sRel 0)} = llift (S γ) l t.\nProof.\n  intro t. induction t ; intros γ l.\n  all: try (cbn ; f_equal ; easy).\n  unfold llift.\n  case_eq (n <? S l) ; intro e ; bprop e ; try mylia.\n  - case_eq (n <? l) ; intro e1 ; bprop e1 ; try mylia.\n    + unfold lift. case_eq (S l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      cbn. case_eq (l ?= n) ; intro e5 ; bprop e5 ; try mylia.\n      reflexivity.\n    + case_eq (n <? l + S γ) ; intro e3 ; bprop e3 ; try mylia.\n      unfold lift. case_eq (S l <=? n) ; intro e5 ; bprop e5 ; try mylia.\n      cbn. case_eq (l ?= n) ; intro e7 ; bprop e7 ; try mylia.\n      f_equal. f_equal. mylia.\n  - case_eq (n <? l) ; intro e1 ; bprop e1 ; try mylia.\n    case_eq (n <? S l + γ) ; intro e3 ; bprop e3 ; try mylia.\n    + case_eq (n <? l + S γ) ; intro e5 ; bprop e5 ; try mylia.\n      unfold lift. case_eq (S l <=? n) ; intro e7 ; bprop e7 ; try mylia.\n      cbn. case_eq (l ?= S n) ; intro e9 ; bprop e9 ; try mylia.\n      reflexivity.\n    + case_eq (n <? l + S γ) ; intro e5 ; bprop e5 ; try mylia.\n      unfold lift. case_eq (S l <=? n) ; intro e7 ; bprop e7 ; try mylia.\n      cbn. case_eq (l ?= S n) ; intro e9 ; bprop e9 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma rlift_substProj :\n  forall {t γ l},\n    (lift 1 (S l) (rlift γ (S l) t)) {l := sProjT2 (sRel 0)} = rlift (S γ) l t.\nProof.\n  intro t. induction t ; intros γ l.\n  all: try (cbn ; f_equal ; easy).\n  unfold rlift.\n  case_eq (n <? S l) ; intro e ; bprop e ; try mylia.\n  - case_eq (n <? l) ; intro e1 ; bprop e1 ; try mylia.\n    + unfold lift. case_eq (S l <=? n) ; intro e3 ; bprop e3 ; try mylia.\n      cbn. case_eq (l ?= n) ; intro e5 ; bprop e5 ; try mylia.\n      reflexivity.\n    + case_eq (n <? l + S γ) ; intro e3 ; bprop e3 ; try mylia.\n      unfold lift. case_eq (S l <=? n) ; intro e5 ; bprop e5 ; try mylia.\n      cbn. case_eq (l ?= n) ; intro e7 ; bprop e7 ; try mylia.\n      f_equal. f_equal. mylia.\n  - case_eq (n <? l) ; intro e1 ; bprop e1 ; try mylia.\n    case_eq (n <? S l + γ) ; intro e3 ; bprop e3 ; try mylia.\n    + case_eq (n <? l + S γ) ; intro e5 ; bprop e5 ; try mylia.\n      unfold lift. case_eq (S l <=? n) ; intro e7 ; bprop e7 ; try mylia.\n      cbn. case_eq (l ?= S n) ; intro e9 ; bprop e9 ; try mylia.\n      reflexivity.\n    + case_eq (n <? l + S γ) ; intro e5 ; bprop e5 ; try mylia.\n      unfold lift. case_eq (S l <=? n) ; intro e7 ; bprop e7 ; try mylia.\n      cbn. case_eq (l ?= S n) ; intro e9 ; bprop e9 ; try mylia.\n      reflexivity.\nDefined.\n\nLemma nth_error_mix :\n  forall Σ Γ Γ1 Γ2 Γm n A1 A2,\n    ismix Σ Γ Γ1 Γ2 Γm ->\n    nth_error Γ1 n = Some A1 ->\n    nth_error Γ2 n = Some A2 ->\n    nth_error Γm n =\n    Some (sPack (llift0 (#|Γm| - S n) A1) (rlift0 (#|Γm| - S n) A2)).\nProof.\n  intros Σ Γ Γ1 Γ2 Γm n A1 A2 hm e1 e2.\n  induction hm in n, A1, A2, e1, e2 |- *.\n  1:{ destruct n. all: discriminate. }\n  destruct n.\n  - cbn in *. inversion e1. inversion e2. subst. clear e1 e2.\n    f_equal. f_equal. all: f_equal. all: mylia.\n  - cbn in *. eapply IHhm. all: assumption.\nDefined.\n\nEnd Mix.", "meta": {"author": "TheoWinterhalter", "repo": "ett-to-wtt", "sha": "a19d7fe082fc5a597093c4ce56ce22158befb60c", "save_path": "github-repos/coq/TheoWinterhalter-ett-to-wtt", "path": "github-repos/coq/TheoWinterhalter-ett-to-wtt/ett-to-wtt-a19d7fe082fc5a597093c4ce56ce22158befb60c/theories/PackLifts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2317157923092633}}
{"text": "(* PREAMBLE *)\n\nFrom compcert.common     Require Memory.\nFrom compcert.lib        Require Coqlib.\n\nFrom trancert.properties Require Env.\nFrom trancert.lib        Require All.\n\nImport Csem Memory Mem Coqlib Tac properties.Env Maps.PTree lib.All ContinuationQuant.\n\n(** * High-level properties of [free] memory operation *)\n\n\n(** ** [free_list] *)\n\n(** When [free_list] accepts a concatenation of two lists, it can be broken into\ntwo [free_list]s with an intermediate memory state. *)\n\nTheorem free_list_app:\n  forall xs ys m1 m2 ,\n    free_list m1 (xs ++ ys) = Some m2 ->\n    exists m3, free_list m1 xs = Some m3 /\\ free_list m3 ys = Some m2.\nProof.\n  induction xs.\n  - by intros; simpl in *; eauto.\n  - intros; simpl in *; repeat option_cases.\n    subst; eauto.\nQed.\n\n(** This is the inverse of [free_list_app]. *)\n\nTheorem free_list_concat:\n  forall xs ys m1 m2 m3 ,\n    free_list m1 xs = Some m3 ->\n    free_list m3 ys = Some m2 ->\n    free_list m1 (xs ++ ys) = Some m2.\nProof.\n  elim.\n  - intros; simpl in *. by inv H.\n  - intros; simpl in *; repeat option_cases; subst. by eauto.\nQed.\n\n\n(** [free_list] does not change permissions for blocks outside the list.  *)\nTheorem free_list_preserves_perm:\n  forall b blocks m1 m2 ofs k p,\n    free_list m1 blocks = Some m2 ->\n    (forall l r, ~ In (b, l, r) blocks) ->\n    perm m1 b ofs k p  ->  \n    perm m2 b ofs k p  .\nProof.\n  induction blocks.\n  - intros until p. inversion 1; auto.\n  - intros m1 m2 ofs k p H Hblocks H1.\n    simpl in *.\n    repeat option_cases. subst.\n    eapply IHblocks in H; eauto.\n    + intros l r Hnot. eapply (Hblocks l r).\n        by eauto.\n    + eapply perm_free_1; eauto.\n      left.\n      intro Hb; subst.\n      by eapply Hblocks; auto.\nQed.\n\n\n(** A successful [free_list] means that all its address ranges were freeable. *)\nTheorem free_list_preserves_range_perm:\n  forall ls m1 m2 b lo hi,\n    free_list m1 ls = Some m2 ->\n    In (b, lo, hi) ls ->\n    range_perm m1 b lo hi Memtype.Cur Memtype.Freeable.\nProof.\n  unfold range_perm.\n  induction ls.\n  inversion 2.\n  intros m1 m2 b lo hi H [Hfst | Hnext];\n    simpl in *; repeat option_cases; subst.\n  - inv Hfst.\n    eapply free_range_perm; eauto.\n  - intros ofs H0.\n    eapply perm_free_3; eauto.\nQed.\n\n(** [free_list] does not change the maximal block index. *)\nTheorem free_list_nextblock:\n  forall ls m1 m2,\n    free_list m1 ls = Some m2 ->\n    nextblock m2 = nextblock m1.\nProof.\n  induction ls.\n  - intros; inv H; reflexivity.\n  - intros m1 m2 H. simpl in *. repeat option_cases.\n    subst. apply nextblock_free in Heq1.\n    rewrite <-Heq1.\n    by apply IHls.\nQed.\n\n(** For a list of unique ranges, if we can perform [free_list], then we can pick any of its elements and free it in the original memory state. *)\nTheorem free_after_free_list_correct:\n  forall hs m1 m2 a b c,\n    list_norepet (List.map (fun x => fst (fst x)) (hs ++ (a,b,c)::nil)) ->\n    free_list m1 (hs ++ (a,b,c)::nil) = Some m2 ->\n    exists m2', free m1 a b c = Some m2'.\nProof.\n  intros hs m1 m2 a b c H H0.\n  simpl in *.\n  edestruct range_perm_free; eauto.\n  eapply free_list_preserves_range_perm; eauto.\n  rewrite in_app.\n  simpl; auto.\nQed.\n\n(** *Local environment *)\n\n(** Local environment is always freeable; this is the property of CompCert C semantics. *)\n\n(** Performing a regular [free] on a local variable of the current environment\nwill not affect permissions of any local variable of a different function\ninstance.\n\nProperty [cont_envs_distinct_blocks] is required for this; it guarantees that all local variables of all functions are stored in different blocks.\n *)\n\nTheorem free_env_freeable:\n  forall (ge:Csem.genv) m1 m2 e  f k i id b t,\n    get i e = Some (b,t) ->\n    free m1 b 0%Z (Ctypes.sizeof ge t)= Some m2 ->\n    econt_envs_distinct_blocks e k ->\n    forall_envs_in_econt (fun _ _ => env_freeable ge m1) f id k ->\n    forall_envs_in_econt (fun _ _ => env_freeable ge m2) f id k .\nProof.\n  unfold forall_envs_in_econt.\n  intros ge m1 m2 e f k i id b t0 Hget Hfree Hdistinct Hcont.\n  generalize dependent f.\n  generalize dependent id.\n  induction k; intros; inv Hdistinct; inv Hcont; try solve [econstructor;  eauto 2].\n  (* One non-trivial case: Kcall *)\n  - econstructor; simpl in *; repeat clean; eauto.\n    unfold env_freeable, range_perm, envs_distinct_blocks in *.\n    intros; eapply perm_free_1; eauto.\n    left; apply not_eq_sym. by eauto.\nQed.\n\nTheorem free_list_env_freeable:\n  forall (ge:Csem.genv) m1 m2 e  f k id,\n    free_list m1 (blocks_of_env ge e) = Some m2 ->\n    econt_envs_distinct_blocks e k ->\n    forall_envs_in_econt (fun _ _ => env_freeable ge m1 ) f id k ->\n    forall_envs_in_econt (fun _ _ => env_freeable ge m2 ) f id k .\nProof.\n  unfold blocks_of_env, block_of_binding.\n  intros ge m1 m2 e f k id H0 H1 H2.\n  eapply cont_envs_distinct_blocks_equiv in H1.\n  unfold econt_envs_distinct_blocks' in *.\n\n  generalize dependent m1.\n  generalize dependent m2.\n  generalize dependent id.\n  move: (elements_complete e).\n  elim: (elements e).\n  - by inversion 2.\n  - simpl. move => [a1 [a2 a3]] l IH Hcomplete id m2 m1 H0 H2.\n    repeat option_cases. inv Heq.\n    eapply free_env_freeable in H2.\n    + eapply IH; eauto.\n    + eapply Hcomplete; eauto.\n    + assumption.\n    + by eapply cont_envs_distinct_blocks_equiv.\nQed.\n\n\n\nTheorem free_of_different_env:\n  forall (ge:Csem.genv) e ev m1 m2,\n    envs_distinct_blocks e ev ->\n    free_list m1 (blocks_of_env ge e) = Some m2 ->\n    env_freeable ge m1 ev ->\n    env_freeable ge m2 ev.\nProof.\n  unfold blocks_of_env.\n  move => ge e ev m1 m2 Hdistinct Hlist Hfreeable.\n  apply env_freeable_equiv.\n  apply env_freeable_equiv in Hfreeable.\n  eapply distinct_blocks_equiv in Hdistinct.\n  unfold env_freeable', envs_distinct_blocks' in *.\n  generalize dependent m1.\n  generalize dependent m2.\n  generalize dependent ev.\n  induction (elements e).\n  - by inversion 2.\n  - simpl.\n    move => ev Hdistinct m2 m1 Hlist Hfreeable i b t0 H.\n    simpl in *.\n    repeat option_cases.\n    subst. destruct a as (a1& a2& a3). inv Heq.\n    eapply IHl; eauto.\n    move => i0 b1 t2 Hinside2 ofs Hofs.\n    eapply perm_free_1; eauto.\n    + left; apply not_eq_sym. by eauto.\n    + eapply Hfreeable; eauto.\nQed.\n\n(** * Low-level [free] properties *)\n\n(** CompCert does not expose the internals of [free] and it also does not\ndefine enough properties to reason about allocations on the low level. These two\nlemmas provide information about how the allocated memory is constructed.\n *)\n\nTheorem free_mem_contents:\n  forall m b lo hi m',\n    free m b lo hi = Some m' ->\n    mem_contents m = mem_contents m'.\nProof.\n  intros m b lo hi m' H.\n\n  change free with (fun (m: mem) (b: Values.block) (lo hi: Z) =>\n                      if range_perm_dec m b lo hi Cur Freeable is left _\n                      then Some(unchecked_free m b lo hi)\n                      else None) in *.\n  simpl in *.\n  destruct (range_perm_dec _ _ _ _ _ _); [|discriminate].\n  inv H.\n  reflexivity.\nQed.\n", "meta": {"author": "sayon", "repo": "trancert", "sha": "eb5c94c75067782158522f61bdd7cc902bf74185", "save_path": "github-repos/coq/sayon-trancert", "path": "github-repos/coq/sayon-trancert/trancert-eb5c94c75067782158522f61bdd7cc902bf74185/properties/memory/Free.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23164923162526846}}
{"text": "From stdpp Require Import coPset namespaces.\nFrom iris.proofmode Require Import tactics.\nSet Default Proof Using \"Type\".\n\nSection accessor.\n(* Just playing around a bit with a telescope version\n   of accessors with just one binder list. *)\nDefinition accessor `{!BiFUpd PROP} {X : tele} (E1 E2 : coPset)\n           (α β γ : X → PROP) : PROP :=\n  (|={E1,E2}=> ∃.. x, α x ∗ (β x -∗ |={E2,E1}=> (γ x)))%I.\n\nNotation \"'ACC' @ E1 , E2 {{ ∃ x1 .. xn , α | β | γ } }\" :=\n  (accessor (X:=TeleS (fun x1 => .. (TeleS (fun xn => TeleO)) .. ))\n            E1 E2\n            (tele_app (TT:=TeleS (fun x1 => .. (TeleS (fun xn => TeleO)) .. )) $\n                      fun x1 => .. (fun xn => α%I) ..)\n            (tele_app (TT:=TeleS (fun x1 => .. (TeleS (fun xn => TeleO)) .. )) $\n                      fun x1 => .. (fun xn => β%I) ..)\n            (tele_app (TT:=TeleS (fun x1 => .. (TeleS (fun xn => TeleO)) .. )) $\n                      fun x1 => .. (fun xn => γ%I) ..))\n  (at level 20, α, β, γ at level 200, x1 binder, xn binder, only parsing).\n\n(* Working with abstract telescopes. *)\nSection tests.\nContext `{!BiFUpd PROP} {X : tele}.\nImplicit Types α β γ : X → PROP.\n\nLemma acc_mono E1 E2 α β γ1 γ2 :\n  (∀.. x, γ1 x -∗ γ2 x) -∗\n  accessor E1 E2 α β γ1 -∗ accessor E1 E2 α β γ2.\nProof.\n  iIntros \"Hγ12 >Hacc\". iDestruct \"Hacc\" as (x') \"[Hα Hclose]\". Show.\n  iModIntro. iExists x'. iFrame. iIntros \"Hβ\".\n  iMod (\"Hclose\" with \"Hβ\") as \"Hγ\". iApply \"Hγ12\". auto.\nQed.\nEnd tests.\n\nSection printing_tests.\nContext `{!BiFUpd PROP}.\n\n(* Working with concrete telescopes: Testing the reduction into normal quantifiers. *)\nLemma acc_elim_test_1 E1 E2 :\n  ACC @ E1, E2 {{ ∃ a b : nat, <affine> ⌜a = b⌝ | True | <affine> ⌜a ≠ b⌝ }}\n    ⊢@{PROP} |={E1}=> False.\nProof.\n  iIntros \">H\". Show.\n  iDestruct \"H\" as (a b) \"[% Hclose]\". iMod (\"Hclose\" with \"[//]\") as \"%\".\n  done.\nQed.\nEnd printing_tests.\nEnd accessor.\n\n(* Robbert's tests *)\nSection telescopes_and_tactics.\n\nDefinition test1 {PROP : sbi} {X : tele} (α : X → PROP) : PROP :=\n  (∃.. x, α x)%I.\n\nNotation \"'TEST1' {{ ∃ x1 .. xn , α } }\" :=\n  (test1 (X:=TeleS (fun x1 => .. (TeleS (fun xn => TeleO)) .. ))\n            (tele_app (TT:=TeleS (fun x1 => .. (TeleS (fun xn => TeleO)) .. )) $\n                      fun x1 => .. (fun xn => α%I) ..))\n  (at level 20, α at level 200, x1 binder, xn binder, only parsing).\n\nDefinition test2 {PROP : sbi} {X : tele} (α : X → PROP) : PROP :=\n  (▷ ∃.. x, α x)%I.\n\nNotation \"'TEST2' {{ ∃ x1 .. xn , α } }\" :=\n  (test2 (X:=TeleS (fun x1 => .. (TeleS (fun xn => TeleO)) .. ))\n            (tele_app (TT:=TeleS (fun x1 => .. (TeleS (fun xn => TeleO)) .. )) $\n                      fun x1 => .. (fun xn => α%I) ..))\n  (at level 20, α at level 200, x1 binder, xn binder, only parsing).\n\nDefinition test3 {PROP : sbi} {X : tele} (α : X → PROP) : PROP :=\n  (◇ ∃.. x, α x)%I.\n\nNotation \"'TEST3' {{ ∃ x1 .. xn , α } }\" :=\n  (test3 (X:=TeleS (fun x1 => .. (TeleS (fun xn => TeleO)) .. ))\n            (tele_app (TT:=TeleS (fun x1 => .. (TeleS (fun xn => TeleO)) .. )) $\n                      fun x1 => .. (fun xn => α%I) ..))\n  (at level 20, α at level 200, x1 binder, xn binder, only parsing).\n\nCheck \"test1_test\".\nLemma test1_test {PROP : sbi}  :\n  TEST1 {{ ∃ a b : nat, <affine> ⌜a = b⌝ }} ⊢@{PROP} ▷ False.\nProof.\n  iIntros \"H\". iDestruct \"H\" as (x) \"H\". Show.\nRestart.\n  iIntros \"H\". unfold test1. iDestruct \"H\" as (x) \"H\". Show.\nAbort.\n\nCheck \"test2_test\".\nLemma test2_test {PROP : sbi}  :\n  TEST2 {{ ∃ a b : nat, <affine> ⌜a = b⌝ }} ⊢@{PROP} ▷ False.\nProof.\n  iIntros \"H\". iModIntro. Show.\n  iDestruct \"H\" as (x) \"H\". Show.\nRestart.\n  iIntros \"H\". iDestruct \"H\" as (x) \"H\". Show.\nAbort.\n\nCheck \"test3_test\".\nLemma test3_test {PROP : sbi}  :\n  TEST3 {{ ∃ a b : nat, <affine> ⌜a = b⌝ }} ⊢@{PROP} ▷ False.\nProof.\n  iIntros \"H\". iMod \"H\".\n  iDestruct \"H\" as (x) \"H\".\n  Show.\nRestart.\n  iIntros \"H\". iDestruct \"H\" as (x) \"H\". Show.\nAbort.\n\nEnd telescopes_and_tactics.\n", "meta": {"author": "izgzhen", "repo": "iris-coq", "sha": "4a1eb8a3d20789af6265b9011939be8274da042c", "save_path": "github-repos/coq/izgzhen-iris-coq", "path": "github-repos/coq/izgzhen-iris-coq/iris-coq-4a1eb8a3d20789af6265b9011939be8274da042c/tests/telescopes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23164923162526846}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\n\nSet Implicit Arguments.\n\n\nVariant covered (loc:Loc.t) (ts:Time.t) (mem:Memory.t): Prop :=\n| covered_intro\n    from to msg\n    (GET: Memory.get loc to mem = Some (from, msg))\n    (ITV: Interval.mem (from, to) ts)\n.\n\nLemma covered_disjoint\n      mem1 mem2 loc from to\n      (COVER: forall loc ts, covered loc ts mem1 -> covered loc ts mem2)\n      (DISJOINT: forall to2 from2 msg2\n                   (GET2: Memory.get loc to2 mem2 = Some (from2, msg2)),\n          Interval.disjoint (from, to) (from2, to2)):\n  forall to2 from2 msg2\n    (GET2: Memory.get loc to2 mem1 = Some (from2, msg2)),\n    Interval.disjoint (from, to) (from2, to2).\nProof.\n  ii. exploit COVER; eauto.\n  { econs; eauto. }\n  intros x0. inv x0. eapply DISJOINT; eauto.\nQed.\n\nLemma get_disjoint_covered_disjoint\n      mem loc from to:\n  (forall t f m, Memory.get loc t mem = Some (f, m) -> Interval.disjoint (from, to) (f, t)) ->\n  (forall ts, covered loc ts mem -> ~ Interval.mem (from, to) ts).\nProof.\n  ii. inv H0. eapply H; eauto.\nQed.\n\nLemma covered_disjoint_get_disjoint\n      mem loc from to:\n  (forall ts, covered loc ts mem -> ~ Interval.mem (from, to) ts) ->\n  (forall t f m, Memory.get loc t mem = Some (f, m) -> Interval.disjoint (from, to) (f, t)).\nProof.\n  ii. eapply H; eauto. econs; eauto.\nQed.\n\nLemma add_covered\n      mem2 mem1 loc from to msg\n      l t\n      (ADD: Memory.add mem1 loc from to msg mem2):\n  covered l t mem2 <->\n  covered l t mem1 \\/ (l = loc /\\ Interval.mem (from, to) t).\nProof.\n  econs; i.\n  - inv H. revert GET. erewrite Memory.add_o; eauto. condtac; ss.\n    + des. subst. i. inv GET. auto.\n    + left. econs; eauto.\n  - des.\n    + inv H. econs; eauto.\n      erewrite Memory.add_o; eauto. condtac; ss; eauto.\n      des. subst. exploit Memory.add_get0; eauto. i. des. congr.\n    + subst. econs; eauto. erewrite Memory.add_o; eauto. condtac; ss.\n      des; congr.\nQed.\n\nLemma remove_covered\n      mem2 mem1 loc from to msg\n      l t\n      (REMOVE: Memory.remove mem1 loc from to msg mem2):\n  covered l t mem2 <->\n  covered l t mem1 /\\ (l <> loc \\/ ~ Interval.mem (from, to) t).\nProof.\n  split; i.\n  - inv H. revert GET. erewrite Memory.remove_o; eauto.\n    condtac; ss; eauto. i.\n    split; try by (econs; eauto).\n    destruct (Loc.eq_dec l loc); auto. subst.\n    des; ss. right. ii.\n    exploit Memory.remove_get0; eauto. i. des.\n    exploit Memory.get_disjoint; [exact GET|exact GET0|]. i. des; ss.\n    eapply x0; eauto.\n  - inv H. inv H0. guardH H1.\n    exploit Memory.remove_get1; try exact GET; eauto. i. des.\n    + subst. inv H1; ss.\n    + econs; eauto.\nQed.\n\nLemma cap_covered\n      mem cap\n      loc ts\n      (CLOSED: Memory.closed mem)\n      (CAP: Memory.cap mem cap)\n      (ITV: Interval.mem (Time.bot, Time.incr (Memory.max_ts loc mem)) ts):\n  covered loc ts cap.\nProof.\n  specialize (Memory.max_exists (fun to => Time.le to ts) loc mem). i. des.\n  { exfalso. eapply NONE; try apply CLOSED. apply Time.bot_spec. }\n  inv SAT; cycle 1.\n  { inv H. inv CAP. exploit SOUND; eauto. i.\n    econs; eauto. econs; s; try refl.\n    exploit Memory.get_ts; try exact GET. i. des; ss.\n    subst. inv ITV. timetac.\n  }\n  specialize (Memory.min_exists (Time.le ts) loc mem). i. des.\n  { exploit Memory.max_ts_spec; try apply CLOSED. i. des. clear MAX0.\n    hexploit NONE; try exact GET0. i.\n    inv CAP. exploit BACK; try exact GET0. i.\n    econs; try exact x0.\n    inv ITV. ss. econs; ss.\n    destruct (TimeFacts.le_lt_dec ts (Memory.max_ts loc mem)); ss.\n  }\n  destruct (TimeFacts.le_lt_dec ts from_min); cycle 1.\n  { inv CAP. exploit SOUND; try exact GET0. i.\n    econs; try exact x0. econs; ss.\n  }\n  inv CAP. exploit MIDDLE.\n  { econs; [exact GET|exact GET0|..].\n    - eapply TimeFacts.lt_le_lt; try exact H. etrans; eauto.\n      exploit Memory.get_ts; try exact GET0. i. des; timetac.\n    - i. destruct (Memory.get loc ts0 mem) as [[]|] eqn:GET'; ss.\n      destruct (TimeFacts.le_lt_dec ts0 ts).\n      + exploit MAX; try exact GET'; ss. i. timetac.\n      + exploit MIN; try exact GET'; timetac. i.\n        rewrite TS2 in x0.\n        exploit Memory.get_ts; try exact GET0. i. des; timetac.\n        exploit TimeFacts.lt_le_lt; try exact TS1; try exact TS2. i. timetac.\n  }\n  { timetac. }\n  i. econs; try exact x0. econs; ss.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/prop/Cover.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23151758995152957}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import Morphisms.\nFrom MetaCoq.Template Require Import config utils.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICCases PCUICInduction\n     PCUICLiftSubst PCUICUnivSubst PCUICSigmaCalculus PCUICClosed\n     PCUICOnFreeVars PCUICTyping PCUICReduction PCUICGlobalEnv PCUICWeakeningEnv\n     PCUICEquality.\n\nRequire Import ssreflect ssrbool.\nFrom Equations Require Import Equations.\n\nImplicit Types (cf : checker_flags) (Σ : global_env_ext).\n\nLemma type_local_ctx_All_local_env {cf} P Σ Γ Δ s :\n  All_local_env (lift_typing P Σ) Γ ->\n  type_local_ctx (lift_typing P) Σ Γ Δ s ->\n  All_local_env (lift_typing P Σ) (Γ ,,, Δ).\nProof.\n  induction Δ; simpl; auto.\n  destruct a as [na [b|] ty];\n  intros wfΓ wfctx; constructor; intuition auto.\n   exists s; auto.\nQed.\n\nLemma sorts_local_ctx_All_local_env {cf} P Σ Γ Δ s :\n  All_local_env (lift_typing P Σ) Γ ->\n  sorts_local_ctx (lift_typing P) Σ Γ Δ s ->\n  All_local_env (lift_typing P Σ) (Γ ,,, Δ).\nProof.\n  induction Δ in s |- *; simpl; eauto.\n  destruct a as [na [b|] ty];\n  intros wfΓ wfctx; constructor; intuition eauto.\n  destruct s => //. destruct wfctx; eauto.\n  destruct s => //. destruct wfctx. exists t; auto.\nQed.\n\nLemma type_local_ctx_Pclosed Σ Γ Δ s :\n  type_local_ctx (lift_typing Pclosed) Σ Γ Δ s ->\n  Alli (fun i d => closed_decl (#|Γ| + i) d) 0 (List.rev Δ).\nProof.\n  induction Δ; simpl; auto; try constructor.\n  destruct a as [? [] ?]; intuition auto.\n  - apply Alli_app_inv; auto. constructor. simpl.\n    rewrite List.rev_length. 2:constructor.\n    unfold closed_decl. unfold Pclosed in b0. simpl.\n    rewrite app_context_length in b0. now rewrite Nat.add_comm.\n  - apply Alli_app_inv; auto. constructor. simpl.\n    rewrite List.rev_length. 2:constructor.\n    unfold closed_decl. unfold Pclosed in b. simpl.\n    rewrite app_context_length in b. rewrite Nat.add_comm.\n    now rewrite andb_true_r in b.\nQed.\n\nLemma sorts_local_ctx_Pclosed Σ Γ Δ s :\n  sorts_local_ctx (lift_typing Pclosed) Σ Γ Δ s ->\n  Alli (fun i d => closed_decl (#|Γ| + i) d) 0 (List.rev Δ).\nProof.\n  induction Δ in s |- *; simpl; auto; try constructor.\n  destruct a as [? [] ?]; intuition auto.\n  - apply Alli_app_inv; eauto. constructor. simpl.\n    rewrite List.rev_length. 2:constructor.\n    unfold closed_decl. unfold Pclosed in b0. simpl.\n    rewrite app_context_length in b0. now rewrite Nat.add_comm.\n  - destruct s as [|u us]; auto. destruct X as [X b].\n    apply Alli_app_inv; eauto. constructor. simpl.\n    rewrite List.rev_length. 2:constructor.\n    unfold closed_decl. unfold Pclosed in b. simpl.\n    rewrite app_context_length in b. rewrite Nat.add_comm.\n    now rewrite andb_true_r in b.\nQed.\n\nLemma All_local_env_Pclosed Σ Γ :\n  All_local_env ( lift_typing Pclosed Σ) Γ ->\n  Alli (fun i d => closed_decl i d) 0 (List.rev Γ).\nProof.\n  induction Γ; simpl; auto; try constructor.\n  intros all; depelim all; intuition auto.\n  - apply Alli_app_inv; auto. constructor. simpl.\n    rewrite List.rev_length. 2:constructor.\n    unfold closed_decl. unfold Pclosed in l. simpl. red in l.\n    destruct l as [s H].\n    now rewrite andb_true_r in H.\n  - apply Alli_app_inv; auto. constructor. simpl.\n    rewrite List.rev_length. 2:constructor.\n    now simpl.\nQed.\n\nLemma weaken_env_prop_closed {cf} :\n  weaken_env_prop cumulSpec0 (lift_typing typing) (lift_typing (fun (_ : global_env_ext) (Γ : context) (t T : term) =>\n  closedn #|Γ| t && closedn #|Γ| T)).\nProof. repeat red. intros. destruct t; red in X0; eauto. Qed.\n\n\nLemma closedn_ctx_alpha {k ctx ctx'} :\n  eq_context_upto_names ctx ctx' ->\n  closedn_ctx k ctx = closedn_ctx k ctx'.\nProof.\n  induction 1 in k |- *; simpl; auto.\n  rewrite IHX. f_equal.\n  rewrite (All2_length X).\n  destruct r; cbn; now subst.\nQed.\n\nLemma closedn_All_local_env (ctx : list context_decl) :\n  All_local_env\n    (fun (Γ : context) (b : term) (t : typ_or_sort) =>\n      closedn #|Γ| b && typ_or_sort_default (closedn #|Γ|) t true) ctx ->\n    closedn_ctx 0 ctx.\nProof.\n  induction 1; auto; rewrite closedn_ctx_cons IHX /=; now move/andP: t0 => [].\nQed.\n\nLemma declared_minductive_closed_inds {cf} {Σ ind mdecl u} {wfΣ : wf Σ} :\n  declared_minductive Σ (inductive_mind ind) mdecl ->\n  forallb (closedn 0) (inds (inductive_mind ind) u (ind_bodies mdecl)).\nProof.\n  intros h.\n  red in h.\n  eapply lookup_on_global_env in h. 2: eauto.\n  destruct h as [Σ' [ext wfΣ' decl']].\n  red in decl'. destruct decl' as [h ? ? ?].\n  rewrite inds_spec. rewrite forallb_rev.\n  unfold mapi.\n  generalize 0 at 1. generalize 0. intros n m.\n  induction h in n, m |- *.\n  - reflexivity.\n  - simpl. eauto.\nQed.\n\nLemma closed_cstr_branch_context_gen {cf : checker_flags} {Σ} {wfΣ : wf Σ} {c mdecl cdecl} :\n  closed_inductive_decl mdecl ->\n  closed_constructor_body mdecl cdecl ->\n  closedn_ctx (context_assumptions mdecl.(ind_params)) (cstr_branch_context c mdecl cdecl).\nProof.\n  intros cl clc.\n  move/andP: cl => [] clpars _.\n  move/andP: clc => [] /andP [] clargs clinds cltype.\n  rewrite /cstr_branch_context /=.\n  eapply (closedn_ctx_expand_lets 0) => // /=.\n  eapply (closedn_ctx_subst 0). len. now rewrite Nat.add_comm.\n  eapply closed_inds.\nQed.\n\nLemma closedn_All_local_closed:\n  forall (cf : checker_flags) (Σ : global_env_ext) (Γ : context) (ctx : list context_decl)\n         (wfΓ' : wf_local Σ (Γ ,,, ctx)),\n    All_local_env_over typing\n    (fun (Σ0 : global_env_ext) (Γ0 : context) (_ : wf_local Σ0 Γ0) (t T : term) (_ : Σ0;;; Γ0 |- t : T) =>\n       closedn #|Γ0| t && closedn #|Γ0| T) Σ (Γ ,,, ctx) wfΓ' ->\n    closedn_ctx 0 Γ && closedn_ctx #|Γ| ctx.\nProof.\n  intros cf Σ Γ ctx wfΓ' al.\n  remember (Γ ,,, ctx) as Γ'. revert Γ' wfΓ' ctx HeqΓ' al.\n  induction Γ. simpl. intros. subst. unfold app_context in *. rewrite app_nil_r in wfΓ' al.\n  induction al; try constructor;\n  rewrite closedn_ctx_cons /=; cbn.\n  move/andP: Hs => [] /= -> _. now rewrite IHal.\n  now rewrite IHal /= /test_decl /=.\n  intros.\n  unfold app_context in *. subst Γ'.\n  specialize (IHΓ (ctx ++ a :: Γ) wfΓ' (ctx ++ [a])).\n  rewrite -app_assoc in IHΓ. specialize (IHΓ eq_refl al).\n  rewrite closedn_ctx_app /= Nat.add_1_r andb_assoc in IHΓ.\n  now rewrite closedn_ctx_cons /=.\nQed.\n\n", "meta": {"author": "SwampertX", "repo": "undergraduate-thesis", "sha": "b0c78984b94e56f1372a7195bd0babaab10fca8d", "save_path": "github-repos/coq/SwampertX-undergraduate-thesis", "path": "github-repos/coq/SwampertX-undergraduate-thesis/undergraduate-thesis-b0c78984b94e56f1372a7195bd0babaab10fca8d/final-report-new/code/v2/pcuic/theories/Conversion/PCUICClosedConv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23151758995152957}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Compile-time evaluation of initializers for global C variables. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import AST.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Ctypes.\nRequire Import Cop.\nRequire Import Csyntax.\n\nOpen Scope error_monad_scope.\n\n(** * Evaluation of compile-time constant expressions *)\n\n(** To evaluate constant expressions at compile-time, we use the same [value]\n  type and the same [sem_*] functions that are used in CompCert C's semantics\n  (module [Csem]).  However, we interpret pointer values symbolically:\n  [Vptr id ofs] represents the address of global variable [id]\n  plus byte offset [ofs]. *)\n\n(** [constval a] evaluates the constant expression [a].\n\nIf [a] is a r-value, the returned value denotes:\n- [Vint n], [Vfloat f]: the corresponding number\n- [Vptr id ofs]: address of global variable [id] plus byte offset [ofs]\n- [Vundef]: erroneous expression\n\nIf [a] is a l-value, the returned value denotes:\n- [Vptr id ofs]: global variable [id] plus byte offset [ofs]\n*)\n\nDefinition do_cast (v: val) (t1 t2: type) : res val :=\n  match sem_cast v t1 t2 with\n  | Some v' => OK v'\n  | None => Error(msg \"undefined cast\")\n  end.\n\nFixpoint constval (a: expr) : res val :=\n  match a with\n  | Eval v ty =>\n      match v with\n      | Vint _ | Vfloat _ | Vsingle _ | Vlong _ => OK v\n      | Vptr _ _ | Vundef => Error(msg \"illegal constant\")\n      end\n  | Evalof l ty =>\n      match access_mode ty with\n      | By_reference | By_copy => constval l\n      | _ => Error(msg \"dereferencing of an l-value\")\n      end\n  | Eaddrof l ty =>\n      constval l\n  | Eunop op r1 ty =>\n      do v1 <- constval r1;\n      match sem_unary_operation op v1 (typeof r1) with\n      | Some v => OK v\n      | None => Error(msg \"undefined unary operation\")\n      end\n  | Ebinop op r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match sem_binary_operation op v1 (typeof r1) v2 (typeof r2) Mem.empty with\n      | Some v => OK v\n      | None => Error(msg \"undefined binary operation\")\n      end\n  | Ecast r ty =>\n      do v1 <- constval r; do_cast v1 (typeof r) ty\n  | Esizeof ty1 ty =>\n      OK (Vint (Int.repr (sizeof ty1)))\n  | Ealignof ty1 ty =>\n      OK (Vint (Int.repr (alignof ty1)))\n  | Eseqand r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match bool_val v1 (typeof r1) with\n      | Some true => do_cast v2 (typeof r2) type_bool\n      | Some false => OK (Vint Int.zero)\n      | None => Error(msg \"undefined && operation\")\n      end\n  | Eseqor r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match bool_val v1 (typeof r1) with\n      | Some false => do_cast v2 (typeof r2) type_bool\n      | Some true => OK (Vint Int.one)\n      | None => Error(msg \"undefined || operation\")\n      end\n  | Econdition r1 r2 r3 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      do v3 <- constval r3;\n      match bool_val v1 (typeof r1) with\n      | Some true => do_cast v2 (typeof r2) ty\n      | Some false => do_cast v3 (typeof r3) ty\n      | None => Error(msg \"condition is undefined\")\n      end\n  | Ecomma r1 r2 ty =>\n      do v1 <- constval r1; constval r2\n  | Evar x ty =>\n      OK(Vptr x Int.zero)\n  | Ederef r ty =>\n      constval r\n  | Efield l f ty =>\n      match typeof l with\n      | Tstruct id fList _ =>\n          do delta <- field_offset f fList;\n          do v <- constval l;\n          OK (Val.add v (Vint (Int.repr delta)))\n      | Tunion id fList _ =>\n          constval l\n      | _ =>\n          Error(msg \"ill-typed field access\")\n      end\n  | Eparen r tycast ty =>\n      do v <- constval r; do_cast v (typeof r) tycast\n  | _ =>\n    Error(msg \"not a compile-time constant\")\n  end.\n\n(** * Translation of initializers *)\n\nInductive initializer :=\n  | Init_single (a: expr)\n  | Init_array (il: initializer_list)\n  | Init_struct (il: initializer_list)\n  | Init_union (f: ident) (i: initializer)\nwith initializer_list :=\n  | Init_nil\n  | Init_cons (i: initializer) (il: initializer_list).\n\n(** Translate an initializing expression [a] for a scalar variable\n  of type [ty].  Return the corresponding initialization datum. *)\n\nDefinition transl_init_single (ty: type) (a: expr) : res init_data :=\n  do v1 <- constval a;\n  do v2 <- do_cast v1 (typeof a) ty;\n  match v2, ty with\n  | Vint n, Tint (I8|IBool) sg _ => OK(Init_int8 n)\n  | Vint n, Tint I16 sg _ => OK(Init_int16 n)\n  | Vint n, Tint I32 sg _ => OK(Init_int32 n)\n  | Vint n, Tpointer _ _ => OK(Init_int32 n)\n  | Vint n, Tcomp_ptr _ _ => OK(Init_int32 n)\n  | Vlong n, Tlong _ _ => OK(Init_int64 n)\n  | Vsingle f, Tfloat F32 _ => OK(Init_float32 f)\n  | Vfloat f, Tfloat F64 _ => OK(Init_float64 f)\n  | Vptr id ofs, Tint I32 sg _ => OK(Init_addrof id ofs)\n  | Vptr id ofs, Tpointer _ _ => OK(Init_addrof id ofs)\n  | Vptr id ofs, Tcomp_ptr _ _ => OK(Init_addrof id ofs)\n  | Vundef, _ => Error(msg \"undefined operation in initializer\")\n  | _, _ => Error (msg \"type mismatch in initializer\")\n  end.\n\n(** Translate an initializer [i] for a variable of type [ty].\n  Return the corresponding list of initialization data. *)\n\nDefinition padding (frm to: Z) : list init_data :=\n  if zlt frm to then Init_space (to - frm) :: nil else nil.\n\nFixpoint transl_init (ty: type) (i: initializer)\n                     {struct i} : res (list init_data) :=\n  match i, ty with\n  | Init_single a, _ =>\n      do d <- transl_init_single ty a; OK (d :: nil)\n  | Init_array il, Tarray tyelt nelt _ =>\n      transl_init_array tyelt il (Zmax 0 nelt)\n  | Init_struct il, Tstruct id fl _ =>\n      transl_init_struct id ty fl il 0\n  | Init_union f i1, Tunion id fl _ =>\n      do ty1 <- field_type f fl;\n      do d <- transl_init ty1 i1;\n      OK (d ++ padding (sizeof ty1) (sizeof ty))\n  | _, _ =>\n      Error (msg \"wrong type for compound initializer\")\n  end\n\nwith transl_init_array (ty: type) (il: initializer_list) (sz: Z)\n                       {struct il} : res (list init_data) :=\n  match il with\n  | Init_nil =>\n      if zeq sz 0 then OK nil\n      else if zle 0 sz then OK (Init_space (sz * sizeof ty) :: nil)\n      else Error (msg \"wrong number of elements in array initializer\")\n  | Init_cons i1 il' =>\n      do d1 <- transl_init ty i1;\n      do d2 <- transl_init_array ty il' (sz - 1);\n      OK (d1 ++ d2)\n  end\n\nwith transl_init_struct (id: ident) (ty: type)\n                        (fl: fieldlist) (il: initializer_list) (pos: Z)\n                        {struct il} : res (list init_data) :=\n  match il, fl with\n  | Init_nil, Fnil =>\n      OK (padding pos (sizeof ty))\n  | Init_cons i1 il', Fcons _ ty1 fl' =>\n      let pos1 := align pos (alignof ty1) in\n      do d1 <- transl_init ty1 i1;\n      do d2 <- transl_init_struct id ty fl' il' (pos1 + sizeof ty1);\n      OK (padding pos pos1 ++ d1 ++ d2)\n  | _, _ =>\n      Error (msg \"wrong number of elements in struct initializer\")\n  end.\n\n\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/cfrontend/Initializers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23151758406849465}}
{"text": "(*\n * Copyright (c) 2017-present,\n * Programming Research Laboratory (ROPAS), Seoul National University, Korea\n * This software is distributed under the term of the BSD-3 clause license.\n *)\n(** Concrete key: pos.  *)\n\nSet Implicit Arguments.\n\nRequire Import Pos DLat.\n\nModule DPos <: KEY.\n  Include Pos_as_OT.\n  Definition eqb x y := if eq_dec x y then true else false.\n  Definition zb_eq : zb_equiv eq :=\n    {| zb_equiv_refl := eq_refl\n     ; zb_equiv_sym := eq_sym\n     ; zb_equiv_trans := eq_trans |}.\nEnd DPos.\n", "meta": {"author": "ropas", "repo": "zooberry", "sha": "17b1cb1a44c2a796d6b7d85c2026b142685d291b", "save_path": "github-repos/coq/ropas-zooberry", "path": "github-repos/coq/ropas-zooberry/zooberry-17b1cb1a44c2a796d6b7d85c2026b142685d291b/spec/Basic/DPos.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.23146209301246018}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*                   Proof of functional correctness                   *)\n(*          for the C functions implemented in the MPTBit layer        *)\n(*                                                                     *)\n(*                        Xiongnan (Newman) Wu                         *)\n(*                                                                     *)\n(*                          Yale University                            *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import TacticsForTesting.\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import MemoryX.\nRequire Import EventsX.\nRequire Import Globalenvs.\nRequire Import Locations.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Cop.\nRequire Import MPTInit.\nRequire Import ZArith.Zwf.\nRequire Import RealParams.\nRequire Import LoopProof.\nRequire Import VCGen.\nRequire Import liblayers.compcertx.Stencil.\nRequire Import liblayers.compcertx.MakeProgram.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import CompatClightSem.\nRequire Import PrimSemantics.\nRequire Import PTNewGenSpec.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import XOmega.\nRequire Import AbstractDataType.\nRequire Import MPTInitCSource.\n\n\nModule MPTINITCODE.\n\n  Section WithPrimitives.\n\n    Context `{real_params: RealParams}.\n    Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n    Context `{Hmwd: UseMemWithData memb}.\n\n    Let mem := mwd (cdata RData).\n\n    Context `{Hstencil: Stencil}.\n    Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n    Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n    \n\n\n    Section PTRESV2.\n\n      Let L: compatlayer (cdata RData) := container_alloc ↦ gensem alloc_spec\n           ⊕ pt_insert ↦ gensem ptInsert0_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section PTResv2Body.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        (** container_alloc *)\n\n        Variable balloc: block.\n\n        Hypothesis halloc1 : Genv.find_symbol ge container_alloc = Some balloc. \n        \n        Hypothesis halloc2 : Genv.find_funct_ptr ge balloc = Some (External (EF_external container_alloc (signature_of_type (Tcons tint Tnil) tint cc_default)) (Tcons tint Tnil) tint cc_default).\n\n        (** pt_insert2 *)\n\n        Variable bptinsert: block.\n\n        Hypothesis hpt_insert1 : Genv.find_symbol ge pt_insert = Some bptinsert. \n        \n        Hypothesis hpt_insert2 : Genv.find_funct_ptr ge bptinsert = Some (External (EF_external pt_insert (signature_of_type (Tcons tint (Tcons tint (Tcons tint (Tcons tint Tnil)))) tint cc_default)) (Tcons tint (Tcons tint (Tcons tint (Tcons tint Tnil)))) tint cc_default).\n\n        Lemma pt_resv2_body_correct: forall m d d' env le proc_index vaddr perm proc_index2 vaddr2 perm2 v,\n                                      env = PTree.empty _ ->\n                                      PTree.get tproc_index le = Some (Vint proc_index) ->\n                                      PTree.get tvaddr le = Some (Vint vaddr) ->\n                                      PTree.get tperm le = Some (Vint perm) ->\n                                      PTree.get tproc_index2 le = Some (Vint proc_index2) ->\n                                      PTree.get tvaddr2 le = Some (Vint vaddr2) ->\n                                      PTree.get tperm2 le = Some (Vint perm2) ->\n                                      ptResv2_spec (Int.unsigned proc_index) (Int.unsigned vaddr) (Int.unsigned perm) (Int.unsigned proc_index2) (Int.unsigned vaddr2) (Int.unsigned perm2) d = Some (d', Int.unsigned v) ->\n                                      high_level_invariant d ->\n                                      exists le',\n                                        exec_stmt ge env le ((m, d): mem) pt_resv2_body E0 le' (m, d') (Out_return (Some (Vint v, tint))).\n        Proof.\n          generalize max_unsigned_val; intro muval.\n          intros.\n          subst.\n          unfold pt_resv2_body.\n          inversion H7.\n          functional inversion H6; subst.\n          {\n            rewrite <- Int.unsigned_repr with 1048577 in H8; try omega.\n            apply unsigned_inj in H8.\n            rewrite <- H8.\n            functional inversion H9; subst.\n            {\n              destruct _x.\n              omega.\n            }\n            {\n              change 0 with (Int.unsigned Int.zero) in H9.\n              esplit.\n              repeat vcgen.\n            }\n          }\n          {\n            rewrite <- Int.unsigned_repr with 1048577 in H8; try omega.\n            apply unsigned_inj in H8.\n            rewrite <- H8.\n            functional inversion H9;subst.\n            {\n              destruct _x0.\n              destruct a0.\n              generalize (valid_nps H17); intro npsrange.\n              esplit.\n              repeat vcgen.\n            }\n            {\n              omega.\n            }\n          }\n          {\n            functional inversion H8; subst.\n            {\n              destruct _x1.\n              destruct a0.\n              generalize (valid_nps H17); intro npsrange.\n              functional inversion H10; functional inversion H28; subst; esplit; repeat vcgen.\n              destruct _x2.\n              destruct a1.\n              simpl in a0.\n              instantiate (1:= v0).\n              repeat vcgen.\n              discharge_cmp.\n              omega.\n              destruct _x2.\n              destruct a1.\n              simpl in a0.\n              omega.\n              repeat vcgen.\n              repeat vcgen.\n            }\n            {\n              omega.\n            }\n          }\n          Grab Existential Variables.\n          apply le.\n          apply le.\n          apply le.\n        Qed.\n\n      End PTResv2Body.\n\n      Theorem pt_resv2_code_correct:\n        spec_le (pt_resv2 ↦ ptResv2_spec_low) (〚pt_resv2 ↦ f_pt_resv2 〛L).\n      Proof.\n        set (L' := L) in *. unfold L in *.\n        fbigstep_pre L'.\n        fbigstep (pt_resv2_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd labd' (PTree.empty _) \n                                        (bind_parameter_temps' (fn_params f_pt_resv2)\n                                                               (Vint n::Vint vadr::Vint p0::Vint n'::Vint vadr'::Vint p'::nil)\n                                                               (create_undef_temps (fn_temps f_pt_resv2)))) H0. \n      Qed.\n\n    End PTRESV2.\n\n\n\n    Section PTNEW.\n\n      Let L: compatlayer (cdata RData) := container_split ↦ gensem container_split_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n\n      Section PTNewBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        (* parameters *)\n        Variables (id quota: int).\n\n        (** container_split *)\n\n        Variable bsplit: block.\n\n        Hypothesis hsplit1 : Genv.find_symbol ge container_split = Some bsplit.\n\n        Hypothesis hsplit2 : \n          Genv.find_funct_ptr ge bsplit = Some (External \n            (EF_external container_split (signature_of_type (Tcons tint (Tcons tint Tnil)) tint cc_default)) \n            (Tcons tint (Tcons tint Tnil)) tint cc_default).\n\n        Lemma pt_new_body_correct: \n          forall m d d' env le n,\n            env = PTree.empty _ ->\n            pt_new_spec (Int.unsigned id) (Int.unsigned quota) d = Some (d', Int.unsigned n) ->            \n            le ! tid = Some (Vint id) -> le ! tquota = Some (Vint quota) ->\n            exists le',\n              exec_stmt ge env le ((m, d): mem) pt_new_body E0 le' (m, d') (Out_return (Some (Vint n, tint))).\n        Proof.\n          generalize max_unsigned_val; intro muval.\n          intros.\n          unfold pt_new_body.\n          functional inversion H0.\n          unfold update_cusage, update_cchildren in *; rewrite ZMap.gss in *; simpl in *.          \n          exists (PTree.set tchild (Vint n) le).\n          repeat vcgen.\n          subst; apply PTree.gempty.\n          unfold container_split_spec, update_cusage, update_cchildren; subst child c i.\n          repeat (match goal with\n                  | [ H : ?a = _ |- context [if ?a then _ else _] ] => rewrite H\n                  | [ |- context [if ?a then _ else _] ] => destruct a; try omega\n                  end).\n          rewrite ZMap.gss; subst.\n          apply f_equal with (f:= Int.repr) in H4; rewrite Int.repr_unsigned in H4; subst.\n          repeat vcgen.\n        Qed.\n\n      End PTNewBody.\n\n      Theorem pt_new_code_correct:\n        spec_le (pt_new ↦ pt_new_spec_low) (〚pt_new ↦ f_pt_new 〛L).\n      Proof.\n        fbigstep_pre L.\n        fbigstep (pt_new_body_correct s (Genv.globalenv p) makeglobalenv id q b0 Hb0fs Hb0fp \n                                      m'0 labd labd' (PTree.empty _) \n                                      (bind_parameter_temps' (fn_params f_pt_new)\n                                         (Vint id :: Vint q :: nil)\n                                         (create_undef_temps (fn_temps f_pt_new)))) H0.\n      Qed.\n\n    End PTNEW.\n\n\n    Section PTRESV.\n\n      Let L: compatlayer (cdata RData) := container_alloc ↦ gensem alloc_spec\n           ⊕ pt_insert ↦ gensem ptInsert0_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section PTResvBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        (** container_alloc *)\n\n        Variable balloc: block.\n\n        Hypothesis halloc1 : Genv.find_symbol ge container_alloc = Some balloc. \n        \n        Hypothesis halloc2 : Genv.find_funct_ptr ge balloc = Some (External (EF_external container_alloc (signature_of_type (Tcons tint Tnil) tint cc_default)) (Tcons tint Tnil) tint cc_default).\n\n        (** pt_insert2 *)\n\n        Variable bptinsert: block.\n\n        Hypothesis hpt_insert1 : Genv.find_symbol ge pt_insert = Some bptinsert. \n        \n        Hypothesis hpt_insert2 : Genv.find_funct_ptr ge bptinsert = Some (External (EF_external pt_insert (signature_of_type (Tcons tint (Tcons tint (Tcons tint (Tcons tint Tnil)))) tint cc_default)) (Tcons tint (Tcons tint (Tcons tint (Tcons tint Tnil)))) tint cc_default).\n\n        Lemma pt_resv_body_correct: forall m d d' env le proc_index vaddr perm v,\n                                      env = PTree.empty _ ->\n                                      PTree.get tproc_index le = Some (Vint proc_index) ->\n                                      PTree.get tvaddr le = Some (Vint vaddr) ->\n                                      PTree.get tperm le = Some (Vint perm) ->\n                                      ptResv_spec (Int.unsigned proc_index)\n                                                    (Int.unsigned vaddr) (Int.unsigned perm) d = Some (d', Int.unsigned v) ->\n                                      high_level_invariant d ->\n                                      exists le',\n                                        exec_stmt ge env le ((m, d): mem) pt_resv_body E0 le' (m, d') (Out_return (Some (Vint v, tint))).\n        Proof.\n          generalize max_unsigned_val; intro muval.\n          intros.\n          subst.\n          unfold pt_resv_body.\n          inversion H4.\n          functional inversion H3; subst.\n          {\n            rewrite <- Int.unsigned_repr with 1048577 in H5; try omega.\n            apply unsigned_inj in H5.\n            rewrite <- H5.\n            functional inversion H6;subst.\n            {\n              destruct _x.\n              destruct a0.\n              generalize (valid_nps H12); intro npsrange.\n              esplit.\n              repeat vcgen.\n            }\n            {\n              change 0 with (Int.unsigned Int.zero) in H6.\n              esplit.\n              repeat vcgen.\n            }\n          }\n          {\n            functional inversion H5; subst.\n            {\n              destruct _x0.\n              destruct a0.\n              generalize (valid_nps H12); intro npsrange.\n              esplit.\n              repeat vcgen.\n            }\n            {\n              change 0 with (Int.unsigned Int.zero) in H5.\n              esplit.\n              repeat vcgen.\n            }\n          }\n          Grab Existential Variables.\n          apply le.\n          apply le.\n        Qed.\n\n      End PTResvBody.\n\n      Theorem pt_resv_code_correct:\n        spec_le (pt_resv ↦ ptResv_spec_low) (〚pt_resv ↦ f_pt_resv 〛L).\n      Proof.\n        set (L' := L) in *. unfold L in *.\n        fbigstep_pre L'.\n        fbigstep (pt_resv_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd labd' (PTree.empty _) \n                                        (bind_parameter_temps' (fn_params f_pt_resv)\n                                                               (Vint n::Vint vadr::Vint p0::nil)\n                                                               (create_undef_temps (fn_temps f_pt_resv)))) H0. \n      Qed.\n\n    End PTRESV.\n\n\n    Section PMAPINIT.\n\n      Let L: compatlayer (cdata RData) := pt_init ↦ gensem pt_init_spec.\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Local Open Scope Z_scope.\n\n      Section PMapInitBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        (** pt_init *)\n\n        Variable bptinit: block.\n\n        Hypothesis hpt_init1 : Genv.find_symbol ge pt_init = Some bptinit. \n        \n        Hypothesis hpt_init2 : Genv.find_funct_ptr ge bptinit = Some (External (EF_external pt_init (signature_of_type (Tcons tint Tnil) Tvoid cc_default)) (Tcons tint Tnil) Tvoid cc_default).\n\n        Lemma pmap_init_body_correct: \n          forall m d d' env le mbi_adr,\n            env = PTree.empty _ ->\n            PTree.get tmbi_adr le = Some (Vint mbi_adr) ->\n            pmap_init_spec (Int.unsigned mbi_adr) d = Some d' ->\n            exec_stmt ge env le ((m, d): mem) pmap_init_body E0 le (m, d') Out_normal.\n        Proof.\n          intros; unfold pmap_init_body.\n          functional inversion H1.\n          change le with (set_opttemp None Vundef le); repeat vcgen.\n          subst; apply PTree.gempty.\n          unfold pt_init_spec.\n          repeat (match goal with\n                  | [ H : ?a = _ |- context[if ?a then _ else _] ] => rewrite H\n                  end); auto.\n        Qed.\n\n      End PMapInitBody.\n\n      Theorem pmap_init_code_correct:\n        spec_le (pmap_init ↦ pmap_init_spec_low) (〚pmap_init ↦ f_pmap_init 〛L).\n      Proof.\n        fbigstep_pre L.\n        fbigstep (pmap_init_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp \n                                         m'0 labd labd' (PTree.empty _) \n                                         (bind_parameter_temps' (fn_params f_pmap_init)\n                                                                (Vint mbi_adr::nil)\n                                                                (create_undef_temps (fn_temps f_pmap_init)))) H0. \n      Qed.\n\n    End PMAPINIT.\n\n\n\n(*\n    Section PTFREE.\n\n      Let L: compatlayer (cdata RData) := set_bit ↦ gensem (fun a b d => set_pt_bit_spec d a b)\n           ⊕ pt_rmv ↦ gensem (fun a b d => ptRmv_spec d a b).\n\n      Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n\n      Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n      Section PTFreeBody.\n\n        Context `{Hwb: WritableBlockOps}.\n\n        Variable (sc: stencil).\n\n        Variables (ge: genv)\n                  (STENCIL_MATCHES: stencil_matches sc ge).\n\n        (** set_bit *)\n\n        Variable bsetbit: block.\n\n        Hypothesis hset_bit1 : Genv.find_symbol ge set_bit = Some bsetbit. \n        \n        Hypothesis hset_bit2 : Genv.find_funct_ptr ge bsetbit = Some (External (EF_external set_bit (signature_of_type (Tcons tint (Tcons tint Tnil)) Tvoid cc_default)) (Tcons tint (Tcons tint Tnil)) Tvoid cc_default).\n\n        (** pt_rmv *)\n\n        Variable bptrmv: block.\n\n        Hypothesis hpt_rmv1 : Genv.find_symbol ge pt_rmv = Some bptrmv. \n        \n        Hypothesis hpt_rmv2 : Genv.find_funct_ptr ge bptrmv = Some (External (EF_external pt_rmv (signature_of_type (Tcons tint (Tcons tint Tnil)) Tvoid cc_default)) (Tcons tint (Tcons tint Tnil)) Tvoid cc_default).\n\n        Definition pt_free_mk_rdata adt (i: Z) (proc_index: Z) := (mkRData (HP adt) (ti adt) (pe adt) (ikern adt) (ihost adt) (AT adt) (nps adt) (PT adt) (ZMap.set proc_index (Calculate_free_pt (Z.to_nat ((i - (kern_low * PgSize)) / PgSize)) (ZMap.get proc_index (ptpool adt))) (ptpool adt)) (ipt adt) (pb adt)).\n\n        Section pt_free_loop_proof.\n\n          Variable minit: memb.\n          Variable proc_index: int.\n          Variable adt: RData.\n          Hypothesis pe : pe adt = true.\n          Hypothesis ipt : ipt adt = true.\n          Hypothesis ikern: ikern adt = true.\n          Hypothesis ihost: ihost adt = true.\n          Hypothesis indexrange: 0 < Int.unsigned proc_index < num_proc.\n          Hypothesis hinv: high_level_invariant adt.\n\n          Lemma valid_PT_kern: forall m: mem, ipt adt = true -> pe adt = true -> PT adt = 0.\n          Proof.\n            intros.\n            remember adt as ad.\n            destruct ad.\n            destruct hinv.\n            rewrite Heqad in *.\n            apply valid_PT_kern; auto.\n          Qed.\n\n          Definition pt_free_loop_body_P (le: temp_env) (m: mem): Prop := \n            PTree.get ti le = Some (Vint (Int.repr adr_low)) /\\ \n            PTree.get tproc_index le = Some (Vint proc_index) /\\ \n            (forall i, adr_low <= Int.unsigned i < adr_high -> \n                       exists pdt, ZMap.get (PDX (Int.unsigned i))\n                                            (ZMap.get (Int.unsigned proc_index)\n                                                      (ptpool adt)) = PDTValid pdt) /\\\n            m = (minit, adt).\n\n          Definition pt_free_loop_body_Q (le : temp_env) (m: mem): Prop := \n            m = (minit, pt_free_mk_rdata adt (adr_high - PgSize) (Int.unsigned proc_index)).\n\n          Lemma pt_free_loop_correct_aux : LoopProofSimpleWhile.t pt_free_while_condition pt_free_while_body ge (PTree.empty _) (pt_free_loop_body_P) (pt_free_loop_body_Q).\n          Proof.\n            generalize max_unsigned_val; intro muval.\n            generalize adr_low_val; intro adrlowval.\n            generalize adr_high_val; intro adrhighval.\n            apply LoopProofSimpleWhile.make with\n            (W := Z)\n              (lt := fun z1 z2 => (0 <= z2 /\\ z1 < z2)%Z)\n              (I := fun le (m: mem) w => exists i,\n                                           PTree.get ti le = Some (Vint i) /\\\n                                           PTree.get tproc_index le = Some (Vint proc_index) /\\\n                                           ipt adt = true /\\\n                                           pe adt = true /\\\n                                           ihost adt = true /\\\n                                           (forall i, adr_low <= Int.unsigned i < adr_high -> \n                                                      exists pdt, ZMap.get (PDX (Int.unsigned i))\n                                                                           (ZMap.get (Int.unsigned proc_index)\n                                                                                     (ptpool adt)) = PDTValid pdt) /\\\n                                           (Int.unsigned i = adr_low /\\ m = (minit, adt) \\/ Int.unsigned i > adr_low /\\ m = (minit, pt_free_mk_rdata adt (Int.unsigned i - PgSize) (Int.unsigned proc_index))) /\\\n                                           adr_low <= Int.unsigned i <= adr_high /\\\n                                           (PgSize | Int.unsigned i) /\\\n                                           w = adr_high - Int.unsigned i \n              )\n            .\n            apply Zwf_well_founded.\n            intros.\n            unfold pt_free_loop_body_P in H.\n            destruct H as [tile tmpH].\n            destruct tmpH as [tprocindexle tmpH].\n            destruct tmpH as [pdtvalid msubst].\n            subst.\n            esplit. esplit. \n            repeat vcgen.\n            unfold Z.divide.\n            exists 262144.\n            omega.\n            intros.\n            destruct H as [i tmpH].\n            destruct tmpH as [tile tmpH].\n            destruct tmpH as [tprocindexle tmpH].\n            destruct tmpH as [nipt tmpH].\n            destruct tmpH as [npe tmpH].\n            destruct tmpH as [nihost tmpH].\n            destruct tmpH as [pdtvalid tmpH].\n            destruct tmpH as [mcase tmpH].\n            destruct tmpH as [irange tmpH].\n            destruct tmpH as [idiv nval].\n            subst.\n            unfold pt_free_while_condition.\n            unfold pt_free_while_body.\n            destruct irange as [ilow ihigh].\n            apply Zle_lt_or_eq in ihigh.\n            destruct m.\n            Caseeq ihigh.\n\n            (* i < adr_high *)\n            intro ihigh.\n\n            assert(icrange: adr_low <= Int.unsigned i < adr_high) by omega.\n            generalize (pdtvalid i icrange); intro pdtvalidi.\n            destruct pdtvalidi as [pdt pdtvalidi].\n            generalize (valid_PT_kern (m, adt) nipt npe); intro pt.\n\n            Caseeq mcase.\n\n            (* i = adr_low *)\n            intro tmpH.\n            destruct tmpH as [jval msubst].\n            rewrite jval.\n            injection msubst; intros; subst.\n\n            esplit. esplit.\n            repeat vcgen.\n            esplit. esplit.\n            repeat vcgen.\n            unfold ptRmv_spec.\n            rewrite ikern, pe, ihost, ipt, pdtvalidi.\n            unfold ptRmv_Arg.\n            repeat zdestruct.\n            exists (adr_high - adr_low - PgSize).\n            repeat vcgen.\n            esplit. \n            Opaque Z.sub PTree.set \"!\".\n            simpl.\n            Transparent Z.sub.\n            repeat vcgen.\n            right.\n            split.\n            omega.\n            assert(1073741824 <= Int.unsigned i + 4096 - 4096 < 4026531840) by omega.\n            f_equal.\n            unfold pt_free_mk_rdata.\n            rewrite jval in *.\n            simpl.\n            unfold Calculate_free_pt_at_i.\n            rewrite pdtvalidi.\n            rewrite ipt, ihost, ikern, pe.\n            reflexivity.\n            unfold Z.divide in *.\n            destruct idiv as [z idiv].\n            exists (z + 1).\n            omega.\n            \n            (* i > adr_low *)\n            intro tmpH.\n            destruct tmpH as [igt tmpH].\n            injection tmpH; intros; subst.\n\n            assert (exists pdt, ZMap.get (PDX (Int.unsigned i))\n                                         (Calculate_free_pt\n                                            (Z.to_nat ((Int.unsigned i - 4096 - 1073741824) / 4096))\n                                            (ZMap.get (Int.unsigned proc_index) (ptpool adt))) = PDTValid pdt).\n              set (ni:= Z.to_nat ((Int.unsigned i - 4096 - 1073741824) / 4096)).\n              induction ni.\n              (* ni = 0 *)\n              simpl.\n              unfold Calculate_free_pt_at_i.\n              assert(exists pdt : PTE,\n               ZMap.get (PDX 1073741824)\n                 (ZMap.get (Int.unsigned proc_index) (ptpool adt)) =\n               PDTValid pdt).\n                rewrite <- Int.unsigned_repr with (1073741824); try omega.\n                apply pdtvalid; auto.\n                rewrite Int.unsigned_repr with (1073741824); try omega.\n              destruct H.\n              rewrite H.\n              assert(icase: PDX (Int.unsigned i) = PDX 1073741824 \\/ PDX (Int.unsigned i) <> PDX 1073741824) by omega.\n              Caseeq icase.\n              (* PDX i0 = PDX i *)\n              intro ieqi.\n              rewrite ieqi.\n              rewrite ZMap.gss.\n              esplit.\n              reflexivity.\n              (* PDX i0 <> PDX i *)\n              intro ineqi.\n              rewrite ZMap.gso.\n              apply pdtvalid.\n              assumption.\n              assumption.\n              (* ni = S ni' *)\n              Opaque Z.of_nat.\n              simpl.\n              unfold Calculate_free_pt_at_i.\n              destruct (ZMap.get (PDX (Z.of_nat (S ni) * 4096 + 1073741824))\n           (Calculate_free_pt ni\n              (ZMap.get (Int.unsigned proc_index) (ptpool adt)))).\n              assert(icase: PDX (Int.unsigned i) = PDX (Z.of_nat (S ni) * 4096 + 1073741824) \\/ PDX (Int.unsigned i) <> PDX (Z.of_nat (S ni) * 4096 + 1073741824)) by omega.\n              Caseeq icase.\n              (* PDX i0 = PDX i *)\n              intro ieqi.\n              rewrite ieqi.\n              rewrite ZMap.gss.\n              esplit.\n              reflexivity.\n              (* PDX i0 <> PDX i *)\n              intro ineqi.\n              rewrite ZMap.gso.\n              assumption.\n              assumption.\n              assumption.\n            destruct H.\n\n            esplit. esplit.\n            split.\n            repeat vcgen.\n            split.\n            repeat vcgen.\n            split.\n            intro contra; discriminate contra.\n            intro.\n            esplit. esplit.\n            repeat vcgen.\n            unfold ptRmv_spec.\n            simpl.\n            rewrite ZMap.gss.\n            rewrite ikern, pe, ihost, ipt.\n            unfold ptRmv_Arg.\n            repeat zdestruct.\n            rewrite H.\n            reflexivity.\n\n            exists (adr_high - Int.unsigned i - PgSize).\n            repeat vcgen.\n            esplit. \n            repeat vcgen.\n            right.\n            split.\n            omega.\n            assert (irangenew: adr_low <= Int.unsigned i + 4096 - 4096 < adr_high) by omega.\n            f_equal.\n            unfold pt_free_mk_rdata.\n            rewrite ZMap.set2.\n            simpl.\n            assert(tmp: ((Int.unsigned i + 4096 - 4096 - 1073741824) / 4096) = (Int.unsigned i - 4096 - 1073741824) / 4096 + 1).\n            rewrite <- Z_div_plus_full.\n            assert (tmp1: Int.unsigned i + 4096 - 4096 - 1073741824 = Int.unsigned i - 1073741824) by omega.\n            assert (tmp2: Int.unsigned i - 4096 - 1073741824 + 1 * 4096 = Int.unsigned i - 1073741824) by omega.\n            rewrite tmp1, tmp2.\n            trivial.\n            omega.\n            rewrite tmp.\n            change ((Int.unsigned i - 4096 - 1073741824) / 4096 + 1) with (Z.succ ((Int.unsigned i - 4096 - 1073741824) / 4096)).\n            rewrite Z2Nat.inj_succ.\n            Opaque Z.of_nat.\n            simpl.\n            rewrite Nat2Z.inj_succ.\n            rewrite Z2Nat.id.\n            unfold Z.succ.\n            unfold Calculate_free_pt_at_i.\n            assert(tmp2: (((Int.unsigned i - 4096 - 1073741824) / 4096 + 1) *\n                          4096 + 1073741824) = Int.unsigned i).\n            rewrite <- Z_div_plus_full.\n            replace (Int.unsigned i - 4096 - 1073741824 + 1 * 4096) with (Int.unsigned i - 1073741824) by omega.\n            destruct idiv as [z idiv].\n            rewrite idiv.\n            replace 1073741824 with (262144 * 4096) by omega. \n            rewrite <- Z.mul_sub_distr_r.\n            rewrite Z_div_mult_full.\n            rewrite <- Z.mul_add_distr_r.\n            replace (z - 262144 + 262144) with z by omega.\n            trivial.\n            omega.\n            omega.\n            rewrite tmp2.\n            simpl in H.\n            rewrite H.\n            rewrite pe, ikern, ihost, ipt.\n            reflexivity.\n            repeat discharge_unsigned_range.\n            repeat discharge_unsigned_range.\n            repeat discharge_unsigned_range.\n            apply Z_div_pos; try omega.\n            destruct idiv as [z idiv].\n            rewrite idiv in *.\n            omega.\n            apply Z_div_pos; try omega.\n            destruct idiv as [z idiv].\n            rewrite idiv in *.\n            omega.\n            destruct idiv as [z idiv].\n            rewrite idiv in *.\n            omega.\n            destruct idiv as [z idiv].\n            rewrite idiv.\n            unfold Z.divide.\n            exists (z + 1).\n            omega.\n\n            (* j = adr_high *)\n            intro jeqadrhigh.\n            esplit. esplit.\n            repeat vcgen.\n            unfold pt_free_loop_body_Q.\n            Caseeq mcase.\n            intro tmpH.\n            destruct tmpH.\n            omega.\n            intro tmpH.\n            rewrite jeqadrhigh in tmpH.\n            destruct tmpH as [ihigh' tmpH].\n            assumption.\n          Qed.\n\n        End pt_free_loop_proof.\n\n          Lemma pt_free_loop_correct: forall m d d' le proc_index,    \n                                        pe d = true ->\n                                        ipt d = true ->\n                                        ikern d = true ->\n                                        ihost d = true ->\n                                        0 < Int.unsigned proc_index < num_proc ->\n                                        high_level_invariant d ->\n                                        PTree.get ti le = Some (Vint (Int.repr adr_low)) ->\n                                        PTree.get tproc_index le = Some (Vint proc_index) ->  \n                                        (forall i, adr_low <= Int.unsigned i < adr_high -> \n                                                   exists pdt, ZMap.get (PDX (Int.unsigned i))\n                                                                        (ZMap.get (Int.unsigned proc_index)\n                                                                                  (ptpool d)) = PDTValid pdt) ->\n                                        d' = pt_free_mk_rdata d (adr_high - PgSize) (Int.unsigned proc_index) ->\n                                        exists le', exec_stmt ge (PTree.empty _) le ((m, d): mem) (Swhile pt_free_while_condition pt_free_while_body) E0 le' (m, d') Out_normal.\n          Proof.\n            intros m d d' le proc_index pe ipt ikern ihost indexrange hinv tile tindexle pdtvalid d'val.\n            generalize (pt_free_loop_correct_aux m proc_index d pe ipt ikern ihost indexrange hinv).\n            intro LP.\n            refine (_ (LoopProofSimpleWhile.termination _ _ _ _ _ _ LP le (m, d) _)).\n            intro pre.\n            destruct pre as [le'' pre].\n            destruct pre as [m'' pre].\n            destruct pre as [pre1 pre2].\n            unfold pt_free_loop_body_Q in pre2.\n            subst.\n            esplit.\n            eassumption.\n            unfold pt_free_loop_body_P.\n            eauto.\n          Qed.\n\n        Lemma pt_free_body_correct: forall m d d' env le proc_index,\n                                      env = PTree.empty _ ->\n                                      PTree.get tproc_index le = Some (Vint proc_index) ->\n                                      pt_free_spec d (Int.unsigned proc_index) = Some d' ->\n                                      high_level_invariant d ->\n                                      exists le',\n                                        exec_stmt ge env le ((m, d): mem) pt_free_body E0 le' (m, d') Out_normal.\n        Proof.\n          generalize max_unsigned_val; intro muval.\n          intros.\n          subst.\n          unfold pt_free_body.\n          functional inversion H1.\n          subst.\n          \n          set (di:= {|\n                     HP := HP d;\n                     ti := ti d;\n                     pe := pe d;\n                     ikern := ikern d;\n                     ihost := ihost d;\n                     AT := AT d;\n                     nps := nps d;\n                     PT := PT d;\n                     ptpool := ptpool d;\n                     ipt := ipt d;\n                     pb := ZMap.set (Int.unsigned proc_index) PTFalse (pb d) |}).\n          exploit (pt_free_loop_correct m di (pt_free_mk_rdata di (4026531840 - 4096) (Int.unsigned proc_index)) (PTree.set ti (Vint (Int.repr adr_low)) (set_opttemp None Vundef le)) proc_index); repeat vcgen.\n          generalize set_bit_inv; intro.\n          inversion H.          \n          eapply semprops_high_level_invariant; auto.\n          instantiate  (2:= d).\n          repeat econstructor.\n          instantiate (2:= proc_index).\n          instantiate (1:= (Int.repr 0)).\n          unfold set_pt_bit_spec.\n          unfold di.\n          rewrite H3, H4, H5.\n          unfold ZtoPTBit.\n          repeat zdestruct.\n          assumption.\n          unfold di; simpl.\n          destruct H2.\n          rewrite H6 in valid_PT_common.\n          exploit (valid_PT_common refl_equal (Int.unsigned proc_index)).\n          omega.\n          intro.\n          destruct H2.\n          unfold PDT_usr in H10.\n          unfold PDT_valid in H10.\n          unfold PDX in *.\n          generalize (H10 (Int.unsigned i / 4096)); intro.\n          rewrite <- Zdiv_Zdiv in H11; try omega.\n          rewrite <- Zdiv_Zdiv; try omega.\n          rewrite Z_div_mult_full in H11; try omega.\n          apply H11.\n          generalize H; clear; intro.\n          xomega.\n          destruct H as [le' stmt].\n\n          esplit.\n          repeat vcgen.\n          unfold set_pt_bit_spec, di.\n          rewrite H3, H4, H5.\n          unfold ZtoPTBit.\n          repeat zdestruct.\n        Qed.\n\n      End PTFreeBody.\n\n      Theorem pt_free_code_correct:\n        spec_le (pt_free ↦ pt_free_spec_low) (〚pt_free ↦ f_pt_free 〛L).\n      Proof.\n        set (L' := L) in *. unfold L in *.\n        fbigstep_pre L'.\n        fbigstep (pt_free_body_correct s (Genv.globalenv p) makeglobalenv b0 Hb0fs Hb0fp b1 Hb1fs Hb1fp m'0 labd labd' (PTree.empty _) \n                                        (bind_parameter_temps' (fn_params f_pt_free)\n                                                               (Vint n::nil)\n                                                               (create_undef_temps (fn_temps f_pt_free)))) H0. \n      Qed.\n\n    End PTFREE.\n\n*)\n\n\n  End WithPrimitives.\n\nEnd MPTINITCODE.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/MPTInitCode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23146209301246015}}
{"text": "From Coq Require Import Logic.FinFun.\nFrom Coq Require Import Lists.List.\nFrom Coq Require Import micromega.Lia.\nFrom Coq Require Import ZArith.ZArith.\n\nFrom VST Require Import floyd.proofauto.\n\nFrom CertiGraph Require Import graph.graph_gen.\nFrom CertiGraph Require Import graph.graph_model.\nFrom CertiGraph Require Import lib.EquivDec_ext.\nFrom CertiGraph Require Import lib.List_ext.\n\nFrom CertiGC Require Import model.compatible.compatible.\nFrom CertiGC Require Import model.constants.\nFrom CertiGC Require Import model.heap.heap.\nFrom CertiGC Require Import model.heapgraph.block.block.\nFrom CertiGC Require Import model.heapgraph.block.ptr.\nFrom CertiGC Require Import model.heapgraph.block.cell.\nFrom CertiGC Require Import model.heapgraph.block.field.\nFrom CertiGC Require Import model.heapgraph.field_pairs.\nFrom CertiGC Require Import model.heapgraph.generation.generation.\nFrom CertiGC Require Import model.heapgraph.graph.\nFrom CertiGC Require Import model.heapgraph.has_block.\nFrom CertiGC Require Import model.heapgraph.has_field.\nFrom CertiGC Require Import model.heapgraph.mark.\nFrom CertiGC Require Import model.heapgraph.predicates.\nFrom CertiGC Require Import model.heapgraph.remset.remset.\nFrom CertiGC Require Import model.heapgraph.roots.\nFrom CertiGC Require Import model.op.do_generation.\nFrom CertiGC Require Import model.op.forward.\nFrom CertiGC Require Import model.op.reset.\nFrom CertiGC Require Import model.op.scan.\nFrom CertiGC Require Import model.thread_info.thread_info.\nFrom CertiGC Require Import model.util.\n\n\nDefinition new_gen_relation (gen: nat) (g1 g2: HeapGraph):\n    Prop\n := if heapgraph_has_gen_dec g1 gen\n    then g1 = g2\n    else exists gen_i: Generation, generation_block_count gen_i = O /\\ g2 = heapgraph_generations_append g1 gen_i\n.\n\nInductive garbage_collect_loop (f_info : fun_info)\n  : list nat -> roots_t -> HeapGraph -> roots_t -> HeapGraph -> Prop :=\n  gcl_nil: forall g roots, garbage_collect_loop f_info nil roots g roots g\n| gcl_cons: forall (g1 g2 g3 g4: HeapGraph) (i: nat) (il: list nat)\n                   (roots1 roots2 roots3: roots_t),\n    new_gen_relation (S i) g1 g2 ->\n    do_generation_relation i (S i) f_info roots1 roots2 g2 g3 ->\n    garbage_collect_loop f_info il roots2 g3 roots3 g4 ->\n    garbage_collect_loop f_info (i :: il) roots1 g1 roots3 g4.\n\nDefinition garbage_collect_relation (f_info: fun_info)\n           (roots1 roots2: roots_t) (g1 g2: HeapGraph): Prop :=\n  exists n, garbage_collect_loop f_info (nat_inc_list (S n)) roots1 g1 roots2 g2 /\\\n            heapgraph_generation_can_copy g2 n (S n).\n\nDefinition garbage_collect_condition (g: HeapGraph) (t_info : thread_info)\n           (roots : roots_t) (f_info : fun_info) : Prop :=\n  graph_unmarked g /\\ no_backward_edge g /\\ no_dangling_dst g /\\\n  roots_fi_compatible roots f_info /\\ ti_size_spec t_info.\n\nLocal Open Scope Z_scope.\n\nLemma gcc_add: forall g ti gi sp i (Hs: 0 <= i < MAX_SPACES) roots fi,\n    generation_block_count gi = O -> space_capacity sp = generation_size (Z.to_nat i) ->\n    garbage_collect_condition g ti roots fi ->\n    garbage_collect_condition (heapgraph_generations_append g gi)\n                              (ti_add_new_space ti sp i Hs) roots fi.\nProof.\n  intros. destruct H1 as [? [? [? [? ?]]]]. split; [|split; [|split; [|split]]].\n  - apply graph_unmarked_add; assumption.\n  - apply no_backward_edge_add; assumption.\n  - apply no_dangling_dst_add; assumption.\n  - assumption.\n  - apply ti_size_spec_add; assumption.\nQed.\n\n\nLemma gc_cond_implies_do_gen_cons: forall g t_info roots f_info i,\n    heapgraph_can_copy_except g i ->\n    heapgraph_has_gen g (S i) ->\n    graph_thread_info_compatible g t_info ->\n    garbage_collect_condition g t_info roots f_info ->\n    do_generation_condition g t_info roots f_info i (S i).\nProof.\n  intros.\n  destruct H2 as [? [? [? [? ?]]]].\n  assert (heapgraph_has_gen g i) by (unfold heapgraph_has_gen in H0 |-*; lia).\n  split; [|split; [|split; [|split; [|split; [|split; [|split]]]]]]; auto.\n  - unfold heapgraph_can_copy_except, heapgraph_generation_can_copy in H.\n    red.\n    unfold rest_gen_size.\n    specialize (H (S i) ltac:(lia) ltac:(lia) H0) ; simpl in H.\n    pose proof (generation__space__compatible__remembered (gt_gs_compatible _ _ H1 _ H0)) as HSi_remembered.\n    pose proof (generation__space__compatible__allocated (gt_gs_compatible _ _ H1 _ H0)) as HSi_allocated.\n    pose proof (generation__space__compatible__allocated (gt_gs_compatible _ _ H1 _ H7)) as Hallocated.\n    simpl in HSi_remembered, HSi_allocated, Hallocated.\n    fold (gen_size t_info (S i)).\n    pose proof (proj2 (space__order (nth_space t_info i))) as Horder.\n    fold (gen_size t_info i) in Horder.\n    unfold heapgraph_generation_size.\n    rewrite Hallocated. clear Hallocated.\n    transitivity (gen_size t_info i).\n    {\n      pose proof (space_remembered__lower_bound (nth_space t_info i)).\n      lia.\n    }\n    rewrite (ti_size_gen _ _ _ H1 H7 H6), (ti_size_gen _ _ _ H1 H0 H6).\n    unfold heapgraph_generation_size in H.\n    rewrite HSi_allocated in H ; clear HSi_allocated.\n    unfold heapgraph_remember_size in H.\n    rewrite HSi_remembered in H ; clear HSi_remembered.\n    assumption.\n  - now apply graph_unmarked_copy_compatible.\n  - unfold heapgraph_can_copy_except, heapgraph_generation_can_copy in H.\n    specialize (H (S i) ltac:(lia) ltac:(lia) ltac:(easy)).\n    replace\n      (Init.Nat.pred (S i))\n      with i\n      in H\n      by lia.\n    pose proof (ngs_0_lt i) as H8.\n    pose proof (ngs_0_lt (S i)) as H9.\n    rewrite (ti_size_gen _ _ _ H1 H0 H6).\n    replace\n      (heapgraph_generation_size g (S i))\n      with (space_allocated (nth_space t_info (S i)))\n      in H.\n    2: {\n      pose proof (gt_gs_compatible _ _ H1 _ H0) as H10.\n      apply generation__space__compatible__allocated in H10.\n      now simpl in H10.\n    }\n    replace\n      (heapgraph_remember_size g (S i))\n      with (space_remembered (nth_space t_info (S i)))\n      in H.\n    2: {\n      pose proof (gt_gs_compatible _ _ H1 _ H0) as H10.\n      apply generation__space__compatible__remembered in H10.\n      now simpl in H10.\n    }\n    pose proof (space_allocated__order (nth_space t_info (S i))) as H10.\n    lia.\n  - rewrite graph_heapgraph_generation_is_unmarked_iff in H2.\n    apply H2.\nQed.\n\nLemma do_gen_gcc: forall g1 t_info1 roots1 g2 t_info2 roots2 f_info i out,\n    super_compatible (g1, t_info1, roots1) f_info out ->\n    firstn_gen_clear g1 i -> heapgraph_has_gen g1 (S i) ->\n    thread_info_relation t_info1 t_info2 ->\n    garbage_collect_condition g1 t_info1 roots1 f_info ->\n    do_generation_relation i (S i) f_info roots1 roots2 g1 g2 ->\n    garbage_collect_condition g2 t_info2 roots2 f_info.\nProof.\n  intros. destruct H3 as [? [? [? [? ?]]]].\n  assert (heapgraph_generation_is_unmarked g1 (S i)) by (rewrite graph_heapgraph_generation_is_unmarked_iff in H3; apply H3).\n  assert (no_dangling_dst g2). {\n    eapply do_gen_no_dangling_dst; eauto.\n    - apply graph_unmarked_copy_compatible; assumption.\n    - apply (proj1 H7).\n    - destruct H as [_ [_ [[_ ?] _]]]. assumption. }\n  split; [|split; [|split; [|split]]]; auto.\n  - eapply do_gen_graph_unmarked; eauto.\n  - eapply do_gen_no_backward_edge; eauto.\n  - destruct H4 as [g3 [g4 [? _]]]. eapply frr_roots_fi_compatible; eauto.\n  - eapply ti_relation_size_spec; eauto.\nQed.\n\nLemma do_gen_stcte: forall g1 roots1 g2 roots2 f_info i,\n    heapgraph_can_copy_except g1 i -> heapgraph_has_gen g1 (S i) ->\n    do_generation_relation i (S i) f_info roots1 roots2 g1 g2 ->\n    heapgraph_can_copy_except g2 (S i).\nProof.\n  intros. unfold heapgraph_can_copy_except in *. intros.\n  destruct H1 as [g3 [g4 [? [? ?]]]]. destruct (Nat.eq_dec n i).\n  - subst. red. unfold heapgraph_generation_size, heapgraph_generation. simpl.\n    rewrite reset_heapgraph_generation_info_same. simpl. unfold heapgraph_block_size_prev.\n    simpl. destruct i. 1: contradiction. simpl. rewrite Z.sub_0_r.\n    pose proof (generation_size_le_S i).\n    now rewrite reset_graph_remember_size_zero.\n  - subst g2. apply reset_stct; auto. destruct H5 as [m [? ?]].\n    rewrite graph_has_gen_reset in H4.\n    assert (heapgraph_has_gen g3 (S i)) by (erewrite <- frr_graph_has_gen; eauto).\n    assert (heapgraph_has_gen g3 n) by (erewrite svwl_graph_has_gen; eauto).\n    eapply (svwl_stcg i (S i) _ g3); eauto.\n    assert (heapgraph_has_gen g1 n) by (erewrite frr_graph_has_gen; eauto).\n    eapply (frr_stcg i (S i) _ _ g1); eauto.\nQed.\n\nLemma gcl_add_tail: forall l g1 roots1 g2 roots2 g3 roots3 g4 f_info i,\n    garbage_collect_loop f_info l roots1 g1 roots2 g2 ->\n    new_gen_relation (S i) g2 g3 ->\n    do_generation_relation i (S i) f_info roots2 roots3 g3 g4 ->\n    garbage_collect_loop f_info (l +:: i) roots1 g1 roots3 g4.\nProof.\n  induction l; intros.\n  - simpl. inversion H. subst. eapply gcl_cons; eauto. constructor.\n  - inversion H. subst. clear H. simpl app. eapply gcl_cons; eauto.\nQed.", "meta": {"author": "CertiGraph", "repo": "CertiGC", "sha": "ec0183449d5e7dc66d33c9bc2dd5759de0ebd877", "save_path": "github-repos/coq/CertiGraph-CertiGC", "path": "github-repos/coq/CertiGraph-CertiGC/CertiGC-ec0183449d5e7dc66d33c9bc2dd5759de0ebd877/theories/CertiGC/model/op/garbage_collect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.23134704378100926}}
{"text": "Require Import Omega.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Time.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import FulfillStep.\nRequire Import MemoryReorder.\nRequire Import MemorySplit.\nRequire Import MemoryMerge.\n\nSet Implicit Arguments.\n\n\nDefinition VIEW_CMP := forall (loc:Loc.t) (ts:Time.t) (lhs rhs:option View.t), Prop.\n\nDefinition loctmeq: VIEW_CMP := fun _ _ (r1 r2: option View.t) => r1 = r2.\nHint Unfold loctmeq.\n\nDefinition mem_sub (cmp: VIEW_CMP) (m1 m2: Memory.t) : Prop :=\n  forall loc ts from val rel1\n    (IN: Memory.get loc ts m1 = Some (from, Message.mk val rel1)),\n  exists rel2,\n  <<IN: Memory.get loc ts m2 = Some (from, Message.mk val rel2)>> /\\\n  <<CMP: cmp loc ts rel1 rel2>>.\n\nDefinition mem_eqrel (cmp: VIEW_CMP) (m1 m2: Memory.t) : Prop :=\n  <<LR: mem_sub cmp m1 m2>> /\\\n  <<RL: mem_sub (fun l t x y => cmp l t y x) m2 m1>>.\nHint Unfold mem_eqrel.\n\nDefinition mem_eqlerel (m1 m2: Memory.t) : Prop :=\n  mem_eqrel (fun _ _ => View.opt_le) m1 m2.\nHint Unfold mem_eqlerel.\n\nProgram Instance mem_eqlerel_PreOrder: PreOrder mem_eqlerel.\nNext Obligation.\n  ii. econs; ii; esplits; eauto; refl.\nQed.\nNext Obligation.\n  ii. inv H. inv H0. des. econs; ii.\n  - exploit H1; eauto. i. des.\n    exploit H; eauto. i. des.\n    esplits; eauto. etrans; eauto.\n  - exploit H3; eauto. i. des.\n    exploit H2; eauto. i. des.\n    esplits; eauto. etrans; eauto.\nQed.\n\nLemma mem_eqlerel_get\n      m1 m2\n      l f t v r2\n      (LE: mem_eqlerel m1 m2)\n      (GET2: Memory.get l t m2 = Some (f, Message.mk v r2)):\n  exists r1,\n    <<GET1: Memory.get l t m1 = Some (f, Message.mk v r1)>> /\\\n    <<REL: View.opt_le r1 r2>>.\nProof. inv LE. des. exploit H0; eauto. Qed.\n\nLemma mem_eqrel_closed_timemap\n      cmp tm m1 m2\n      (EQMEM: mem_eqrel cmp m1 m2)\n      (CLOSED: Memory.closed_timemap tm m1):\n  Memory.closed_timemap tm m2.\nProof.\n  ii. specialize (CLOSED loc). des.\n  apply EQMEM in CLOSED. des.\n  esplits; eauto.\nQed.\n\nLemma mem_eqrel_closed_view\n      cmp cap m1 m2\n      (EQMEM: mem_eqrel cmp m1 m2)\n      (CLOSED: Memory.closed_view cap m1):\n  Memory.closed_view cap m2.\nProof.\n  inv CLOSED. econs; eapply mem_eqrel_closed_timemap; eauto.\nQed.\n\nLemma mem_eqrel_closed_opt_view\n      cmp cap m1 m2\n      (EQMEM: mem_eqrel cmp m1 m2)\n      (CLOSED: Memory.closed_opt_view cap m1):\n  Memory.closed_opt_view cap m2.\nProof.\n  inv CLOSED; econs. eapply mem_eqrel_closed_view; eauto.\nQed.\n\nLemma mem_eqrel_closed_tview\n      cmp tview m1 m2\n      (EQMEM: mem_eqrel cmp m1 m2)\n      (CLOSED: TView.closed tview m1):\n  TView.closed tview m2.\nProof.\n  inv CLOSED. econs; i; eapply mem_eqrel_closed_view; eauto.\nQed.\n\nLemma lower_mem_eqlerel\n      m1 loc from to val r1 r2 m2\n      (LOWER: Memory.lower m1 loc from to val r1 r2 m2):\n  mem_eqlerel m2 m1.\nProof.\n  econs; ii.\n  - revert IN. erewrite Memory.lower_o; eauto. condtac; ss.\n    + i. des. inv IN. exploit Memory.lower_get0; eauto. i. esplits; eauto.\n      inv LOWER. inv LOWER0. auto.\n    + i. esplits; eauto. refl.\n  - erewrite Memory.lower_o; eauto. condtac; ss.\n    + des. subst. revert IN. erewrite Memory.lower_get0; eauto. i. inv IN.\n      esplits; eauto. inv LOWER. inv LOWER0. auto.\n    + esplits; eauto. refl.\nQed.\n\nLemma mem_eqrel_memory_op\n      m1 m2 m1' m2' released1 released2 kind1 kind2\n      cmp\n      loc from to val\n      (EQMEM: mem_eqrel cmp m1 m2)\n      (OP1: Memory.op m1 loc from to val released1 m1' kind1)\n      (OP2: Memory.op m2 loc from to val released2 m2' kind2):\n  Memory.op_kind_match kind1 kind2.\nProof.\n  inv OP1; inv OP2; try by econs.\n  - exploit Memory.split_get0; eauto. i. des.\n    apply EQMEM in GET3. des.\n    inv ADD. inv ADD0. exfalso. eapply DISJOINT; eauto.\n    + apply Interval.mem_ub. auto.\n    + inv SPLIT. inv SPLIT0. econs; auto. left. auto.\n  - exploit Memory.lower_get0; eauto. i.\n    apply EQMEM in x0. des.\n    erewrite Memory.add_get0 in IN; eauto. congr.\n  - exploit Memory.split_get0; eauto. i. des.\n    apply EQMEM in GET3. des.\n    inv ADD. inv ADD0. exfalso. eapply DISJOINT; eauto.\n    + apply Interval.mem_ub. auto.\n    + inv SPLIT. inv SPLIT0. econs; auto. left. auto.\n  - exploit Memory.split_get0; try exact SPLIT; eauto. i. des.\n    apply EQMEM in GET3. des.\n    exploit Memory.split_get0; eauto. i. des.\n    exploit MemoryFacts.get_same_from; [exact IN|exact GET3|..].\n    { ii. subst. inv SPLIT. inv SPLIT1. inv TS23. }\n    { ii. subst. inv SPLIT0. inv SPLIT1. inv TS23. }\n    i. des. inv x1. econs; ss.\n  - exploit Memory.lower_get0; eauto. i.\n    apply EQMEM in x0. des.\n    exploit Memory.split_get0; eauto. i. des. congr.\n  - exploit Memory.lower_get0; eauto. i.\n    apply EQMEM in x0. des.\n    erewrite Memory.add_get0 in IN; eauto. congr.\n  - exploit Memory.lower_get0; eauto. i.\n    apply EQMEM in x0. des.\n    exploit Memory.split_get0; eauto. i. des. congr.\nQed.\n\nLemma mem_eqlerel_add\n      loc from to val released\n      m1 m2 m2'\n      (MEMLE: mem_eqlerel m1 m2)\n      (ADD2: Memory.add m2 loc from to val released m2'):\n  exists m1',\n    <<ADD1: Memory.add m1 loc from to val released m1'>> /\\\n    <<MEMLE': mem_eqlerel m1' m2'>>.\nProof.\n  exploit (@Memory.add_exists m1 loc from to);\n    try by inv ADD2; inv ADD; eauto.\n  { i. destruct msg2. eapply MEMLE in GET2. des.\n    inv ADD2. inv ADD. eapply DISJOINT. eauto.\n  }\n  i. des. esplits; eauto.\n  econs; splits; ii; revert IN.\n  - erewrite Memory.add_o; eauto. erewrite (@Memory.add_o m2'); eauto.\n    condtac; ss.\n    + i. des. inv IN. esplits; eauto. refl.\n    + i. eapply MEMLE. eauto.\n  - erewrite Memory.add_o; eauto. erewrite (@Memory.add_o mem2); eauto.\n    condtac; ss.\n    + i. des. inv IN. esplits; eauto. refl.\n    + i. eapply MEMLE. eauto.\nQed.\n\nLemma mem_eqlerel_split\n      loc ts1 ts2 ts3 val2 val3 released2 released3\n      m1 m2 m2' prm prm'\n      (MEMLE: mem_eqlerel m1 m2)\n      (PRM1: Memory.le prm m1)\n      (SPLIT2: Memory.split m2 loc ts1 ts2 ts3 val2 val3 released2 released3 m2')\n      (SPLITP2: Memory.split prm loc ts1 ts2 ts3 val2 val3 released2 released3 prm'):\n  exists m1',\n    <<SPLIT2: Memory.split m1 loc ts1 ts2 ts3 val2 val3 released2 released3 m1'>> /\\\n    <<MEMLE': mem_eqlerel m1' m2'>>.\nProof.\n  exploit Memory.split_get0; eauto. i. des. apply PRM1 in GET3.\n  exploit (@Memory.split_exists m1 loc ts1 ts2 ts3);\n    try by inv SPLIT2; inv SPLIT; eauto. i. des.\n  esplits; eauto.\n  econs; splits; ii; revert IN.\n  - erewrite Memory.split_o; eauto. erewrite (@Memory.split_o m2'); eauto.\n    repeat condtac; ss.\n    + i. des. inv IN. esplits; eauto. refl.\n    + guardH o. i. des. inv IN. esplits; eauto. refl.\n    + eapply MEMLE.\n  - erewrite Memory.split_o; eauto. erewrite (@Memory.split_o mem2); eauto.\n    repeat condtac; ss.\n    + i. des. inv IN. esplits; eauto. refl.\n    + guardH o. i. des. inv IN. esplits; eauto. refl.\n    + eapply MEMLE.\nQed.\n\nLemma mem_eqlerel_lower\n      loc from to val released1 released2\n      m1 m2 m2' prm prm'\n      (MEMLE: mem_eqlerel m1 m2)\n      (PRM1: Memory.le prm m1)\n      (LOWER2: Memory.lower m2 loc from to val released1 released2 m2')\n      (LOWERP2: Memory.lower prm loc from to val released1 released2 prm'):\n  exists m1',\n    <<LOWER1: Memory.lower m1 loc from to val released1 released2 m1'>> /\\\n    <<MEMLE': mem_eqlerel m1' m2'>>.\nProof.\n  exploit Memory.lower_get0; eauto. i. apply PRM1 in x0.\n  exploit (@Memory.lower_exists m1 loc from to val released1 released2);\n    try by inv LOWER2; inv LOWER; eauto; try by viewtac. i. des.\n  esplits; eauto.\n  econs; esplits; ii; revert IN.\n  - erewrite Memory.lower_o; eauto. erewrite (@Memory.lower_o m2'); eauto.\n    condtac; ss.\n    + i. des. inv IN. esplits; eauto. refl.\n    + eapply MEMLE.\n  - erewrite Memory.lower_o; eauto. erewrite (@Memory.lower_o mem2); eauto.\n    condtac; ss.\n    + i. des. inv IN. esplits; eauto. refl.\n    + eapply MEMLE.\nQed.\n\nLemma mem_eqlerel_promise\n      loc from to val released kind\n      m1 m2 m2' prm prm'\n      (MEMLE: mem_eqlerel m1 m2)\n      (PRM1: Memory.le prm m1)\n      (PROMISE2: Memory.promise prm m2 loc from to val released prm' m2' kind):\n  exists m1',\n    <<PROMISE1: Memory.promise prm m1 loc from to val released prm' m1' kind>> /\\\n    <<MEMLE': mem_eqlerel m1' m2'>>.\nProof.\n  inv PROMISE2.\n  - exploit mem_eqlerel_add; eauto. i. des.\n    esplits; eauto. econs; eauto.\n  - exploit mem_eqlerel_split; eauto. i. des.\n    esplits; eauto. econs; eauto.\n  - exploit mem_eqlerel_lower; eauto. i. des.\n    esplits; eauto. econs; eauto.\nQed.\n\nLemma mem_eqlerel_add_forward\n      loc from to val released1 released2\n      m1 m2 m2'\n      (MEMLE: mem_eqlerel m2 m1)\n      (ADD2: Memory.add m2 loc from to val released2 m2')\n      (RELLE: View.opt_le released2 released1)\n      (RELWF: View.opt_wf released1):\n  exists m1',\n    <<ADD1: Memory.add m1 loc from to val released1 m1'>> /\\\n    <<MEMLE': mem_eqlerel m2' m1'>>.\nProof.\n  exploit (@Memory.add_exists m1 loc from to); eauto;\n    try by inv ADD2; inv ADD; eauto.\n  { i. destruct msg2. eapply MEMLE in GET2. des.\n    inv ADD2. inv ADD. eapply DISJOINT. eauto.\n  }\n  i. des. esplits; eauto.\n  econs; splits; ii; revert IN.\n  - erewrite Memory.add_o; eauto. erewrite (@Memory.add_o mem2); eauto.\n    condtac; ss.\n    + i. des. inv IN. esplits; eauto.\n    + i. eapply MEMLE. eauto.\n  - erewrite Memory.add_o; eauto. erewrite (@Memory.add_o m2'); eauto.\n    condtac; ss.\n    + i. des. inv IN. esplits; eauto.\n    + i. eapply MEMLE. eauto.\nQed.\n\nLemma mem_eqlerel_split_forward\n      loc ts1 ts2 ts3 val2 val3 released2 released2' released3\n      m1 m2 m2'\n      (MEMLE: mem_eqlerel m2 m1)\n      (SPLIT2: Memory.split m2 loc ts1 ts2 ts3 val2 val3 released2 released3 m2')\n      (RELLE: View.opt_le released2 released2')\n      (RELWF: View.opt_wf released2'):\n  exists released3' m1',\n    <<SPLIT2: Memory.split m1 loc ts1 ts2 ts3 val2 val3 released2' released3' m1'>> /\\\n    <<MEMLE': mem_eqlerel m2' m1'>>.\nProof.\n  exploit Memory.split_get0; eauto. i. des.\n  apply MEMLE in GET3. i. des.\n  exploit (@Memory.split_exists m1 loc ts1 ts2 ts3); eauto;\n    try by inv SPLIT2; inv SPLIT; eauto. i. des.\n  esplits; eauto.\n  econs; splits; ii; revert IN0.\n  - erewrite Memory.split_o; eauto. erewrite (@Memory.split_o mem2); eauto.\n    repeat condtac; ss.\n    + i. des. inv IN0. esplits; eauto.\n    + guardH o. i. des. inv IN0. esplits; eauto.\n    + eapply MEMLE.\n  - erewrite Memory.split_o; eauto. erewrite (@Memory.split_o m2'); eauto.\n    repeat condtac; ss.\n    + i. des. inv IN0. esplits; eauto.\n    + guardH o. i. des. inv IN0. esplits; eauto.\n    + eapply MEMLE.\nQed.\n\nLemma mem_eqlerel_lower_forward\n      loc from to val released1 released2\n      m1 m2 m2'\n      (MEMLE: mem_eqlerel m2 m1)\n      (LOWER2: Memory.lower m2 loc from to val released1 released2 m2'):\n  exists released1' m1',\n    <<LOWER1: Memory.lower m1 loc from to val released1' released2 m1'>> /\\\n    <<MEMLE': mem_eqlerel m2' m1'>>.\nProof.\n  exploit Memory.lower_get0; eauto. i.\n  apply MEMLE in x0. des.\n  exploit (@Memory.lower_exists m1 loc from to val rel2 released2); eauto;\n    try by inv LOWER2; inv LOWER; eauto; try by viewtac.\n  { etrans; eauto. inv LOWER2. inv LOWER. auto. }\n  i. des.\n  esplits; eauto.\n  econs; esplits; ii; revert IN0.\n  - erewrite Memory.lower_o; eauto. erewrite (@Memory.lower_o mem2); eauto.\n    condtac; ss.\n    + i. des. inv IN0. esplits; eauto. refl.\n    + eapply MEMLE.\n  - erewrite Memory.lower_o; eauto. erewrite (@Memory.lower_o m2'); eauto.\n    condtac; ss.\n    + i. des. inv IN0. esplits; eauto. refl.\n    + eapply MEMLE.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-coq", "sha": "bff53239c51681ea653745cebf3b30ddd38f97ba", "save_path": "github-repos/coq/snu-sf-promising-coq", "path": "github-repos/coq/snu-sf-promising-coq/promising-coq-bff53239c51681ea653745cebf3b30ddd38f97ba/src/prop/MemoryRel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.23122255258455576}}
{"text": "(** * Nondeterminism *)\n\n(** Actually, bounded nondeterminism. *)\n\n(* begin hide *)\nSet Implicit Arguments.\nSet Contextual Implicit.\n\nFrom Coq Require Import\n     String List.\nImport ListNotations.\n\nFrom ITree Require Import\n     Basics.Basics\n     Core.ITreeDefinition\n     Indexed.Sum\n     Core.Subevent\n     Events.Exception.\n(* end hide *)\n\n(** Make nondeterministic choices. *)\nVariant nondetE : Type -> Type :=\n| Or : nondetE bool.\n\n(** Choose one of two computations. *)\nDefinition or {E F} `{nondetE +? F -< E} {R} (t1 t2 : itree E R)\n  : itree E R :=\n  vis Or (fun b : bool => if b then t1 else t2).\n\n(** Choose an element from a nonempty list (with the head and tail\n    as separate arguments), so it cannot fail. *)\nDefinition choose1 {E F} `{nondetE +? F -< E} {X}\n  : X -> list X -> itree E X\n  := fix choose1' x xs : itree E X :=\n       match xs with\n       | [] => Ret x\n       | x' :: xs => or (Ret x) (choose1' x' xs)\n       end.\n\n(** Pick any element in a list apart from the others. *)\nDefinition remove_from {X} : list X -> list (X * list X) :=\n  let fix remove_from_ pre xs :=\n      match xs with\n      | [] => []\n      | x :: xs' => (x, pre ++ xs') :: remove_from_ (pre ++ [x]) xs'\n      end in\n  remove_from_ [].\n\n(** ** Empty nondeterminism *)\n\n(** We can use [exceptE] events to model nullary branching. *)\n\n(** Exception thrown by [choose]. *)\nVariant no_choice : Set := NoChoice.\n\n(** Choose an element from a list.\n\n    This can fail if the list is empty, using the [exceptE no_choice] event.\n *)\n\nDefinition choose {E F G} `{nondetE +? F -< E} `{exceptE no_choice +? G -< E} {X}\n  : list X -> itree E X\n  := fix choose' xs : itree E X :=\n       match xs with\n       | [] => throw NoChoice\n       | x :: xs =>\n         or (Ret x) (choose' xs)\n       end.\n", "meta": {"author": "euisuny", "repo": "icfp22-layered-monadic-interpreters", "sha": "c3998f90613d1213585aaddf265fd463b77e4f8a", "save_path": "github-repos/coq/euisuny-icfp22-layered-monadic-interpreters", "path": "github-repos/coq/euisuny-icfp22-layered-monadic-interpreters/icfp22-layered-monadic-interpreters-c3998f90613d1213585aaddf265fd463b77e4f8a/src/theories/Events/Nondeterminism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2311806387407333}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of CFGV project.\n\n  CFGV is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  CFGV is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with CFGV.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/CFGVLFMTP2014/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\nRequire Export GVariables.\nSet Implicit Arguments.\n\n(** printing #  $\\times$ #×# *)\n(** printing &  $\\times$ #×# *)\n\n\n\n\n(** used in [bindingInfoCorrect] below.\n   Also, see [ValidIndicesDecidable] below*)\nDefinition ValidIndices {A B : Type}\n  (bindingInfo : list (nat * nat))\n  (rhsSyms : list (A + B)) : [univ] \n:= (\n      forall n m, \n      LIn (n,m) bindingInfo\n      -> (m < length rhsSyms) # (n < length rhsSyms)\n          # (true = liftNth isInl rhsSyms n)\n   )\n   #\n   (\n      forall n, \n        (true = liftNth isInl rhsSyms n)\n        -> LIn n (map (@fst _ _) bindingInfo)\n   )\n    #no_repeats bindingInfo.\n\n(** For concretely specified grammars,\n  one can just compute the following lemma to get the\n  proof of [ValidIndices]. See the tactic (Ltac)\n  [proveBindingInfoCorrect] below. *)\nLemma ValidIndicesDecidable:\n  forall {A B : Type}\n  (bindingInfo : list (nat * nat))\n  (rhsSyms : list (A + B)),\n  decidable (ValidIndices bindingInfo rhsSyms).\nProof.\n  intros.\n  unfold ValidIndices.\n  apply decidable_prod;[|apply decidable_prod].\n  - induction bindingInfo as [| (n,m) bindingInfo Hind];\n      [left; dands |]; cpx.\n    dorn Hind;[| right]; cpx.\n    remember (liftNth isInl rhsSyms n) as bl.\n    destruct (lt_dec m (length rhsSyms));\n    destruct (lt_dec n (length rhsSyms));\n    destruct bl; try rewrite <- Heqbl;\n    try(left; introv Hin; repeat(in_reasoning); cpx; fail);\n    [| | | | | | ];\n    right; introv Hin;\n    specialize (Hin _ _ (inl eq_refl));\n    try rewrite <- Heqbl in Hin;\n    dands; cpx.\n\n  - remember ((map (fst (B:=nat)) bindingInfo)) as bif.\n    clear dependent bindingInfo.\n    revert bif. unfold liftNth;\n    induction rhsSyms as [| rs rhsSyms Hind];\n      [left; intro n; destruct n;\n         simpl; cpx |].\n    intro bifCons.\n    remember (flat_map \n      (fun n=> match n with\n               |0 => []\n               | S m => [m] end) bifCons)\n      as bif.\n    specialize (Hind bif).\n    dorn Hind; [| right]; cpx.\n    + destruct rs as [sa| sb];[|left; destruct n;\n            allsimpl; cpx].\n      * destruct (in_deq _ deq_nat 0 bifCons); cpx;\n        [left; destruct n | right]; simpl;\n        subst bif; cpx;[].\n        \n        introv Heq.\n        apply Hind in Heq.\n        apply lin_flat_map in Heq.\n        exrepnd.\n        destruct x; cpx.\n        inverts Heq0; cpx; fail.\n\n      * introv Heq. subst bif.\n        specialize (Hind ( n)).\n        apply Hind in Heq. clear Hind.\n        apply lin_flat_map in Heq.\n        exrepnd. destruct x; cpx.\n        inverts Heq0; cpx.\n    + introv Hc. apply Hind. clear Hind. introv Heq.\n      subst bif. apply lin_flat_map.\n      specialize (Hc (S n)). simpl in Hc.\n      apply Hc in Heq.\n      exists (S n). dands; cpx.\n\n  - apply no_repeat_dec. apply deq_prod; exact deq_nat.\nDefined.\n\n\n\n  \n(* using some ideas from \n  http://gallium.inria.fr/~xleroy/publi/validated-parser.pdf\n\n  Coq sources are linked in sources in [9].\n\n  specifically, cparser/validator/Grammar.v\n\n*)\n\n(** CatchFileBetweenTagsCFGVStart *)\nRecord CFGV := {\n  Terminal : Type;   VarSym : Type; \n  TNonTerminal : Type;   PNonTerminal : Type;\n\n  PatProd : Type;  EmbedProd : Type;  TermProd : Type;\n\n  varSem : VarSym -> VarType;\n  vSubstType : VarSym -> TNonTerminal;\n  tSemType : Terminal -> Type;\n\n  ppLhsRhs: PatProd -> \n    (PNonTerminal * list (PNonTerminal \n                           + (Terminal + VarSym)));\n\n  epLhsRhs : EmbedProd -> (PNonTerminal * TNonTerminal);\n  \n  tpLhsRhs: TermProd -> \n    (TNonTerminal * list ((PNonTerminal + VarSym)\n                          +(Terminal+TNonTerminal)));\n  \n  bindingInfo : TermProd -> list (nat * nat);\n  bindingInfoCorrect: forall (p: TermProd),\n      ValidIndices (bindingInfo p) (snd (tpLhsRhs p));\n(** }. CatchFileBetweenTagsCFGVEnd *)\n\n  DeqVarSym : Deq VarSym;\n  deqT : Deq Terminal;\n  deqNT : Deq TNonTerminal;\n  deqPT : Deq PNonTerminal;\n  deqPr : Deq TermProd;\n  deqEm : Deq EmbedProd;\n  deqPPr : Deq PatProd;\n  deqTSem : forall (t: Terminal), Deq (tSemType t)\n\n}.\n\n\nDefinition vType {G: CFGV} (vc : VarSym G) : Type :=\n  (typ (varSem G vc)).\n\n(** A more intuitive way to denote symbols of a CFGV :\n    instead of inl inr.... *)\n\n(** CatchFileBetweenTagsGSymStart *)\nInductive GSym (G: CFGV) : Type :=\n| gsymT : Terminal G -> GSym G\n| gsymV : VarSym G -> GSym G\n| gsymTN : TNonTerminal G -> GSym G\n| gsymPN : PNonTerminal G -> GSym G.\n(** CatchFileBetweenTagsGSymEnd *)\n\n(** Make the [CFGV] argument implicit *) \nArguments gsymT {G} _.\nArguments gsymV {G} _.\nArguments gsymTN {G} _.\nArguments gsymPN {G} _.\n\nArguments bindingInfo {c} _.\n\nLemma deqGSym :  forall (G: CFGV),\n  Deq (GSym G).\nProof.\nintros.\nintros sa sb.\ndestruct sa as [sa|sa|sa|sa]; destruct sb as [sb|sb|sb|sb]; \ntry (right; introv Hc; inverts Hc; cpx; fail).\n- destruct (deqT G sa sb);[left; subst|right; introv HC; inverts HC]; cpx.\n- destruct (DeqVarSym G sa sb);[left; subst|right; introv HC; inverts HC]; cpx.\n- destruct (deqNT G sa sb);[left; subst|right; introv HC; inverts HC]; cpx.\n- destruct (deqPT G sa sb);[left; subst|right; introv HC; inverts HC]; cpx.\nDefined.\n\n\nHint Resolve deqT deqTSem DeqVarSym deqNT deqPT deqGSym deqPr deqEm deqPPr: Deq.\n\n\n\nDefinition  prhs_aux {G : CFGV} \n  (symSum :((PNonTerminal G + VarSym G) \n              +(Terminal G + TNonTerminal G))) : (GSym G) :=\nmatch symSum with\n| inl (inl p) => gsymPN p\n| inl (inr vc) => gsymV vc\n| inr (inl t) => gsymT t\n| inr (inr nt) => gsymTN nt\nend.\n\nDefinition tpRhsSym {G: CFGV} (p:TermProd G) : list (GSym G)\n:=map (prhs_aux) (snd (tpLhsRhs G p)).\n\nDefinition  ptrhs_aux {G : CFGV} \n  (symSum :((PNonTerminal G)+ (Terminal G + VarSym G))) \n      : (GSym G) :=\nmatch symSum with\n| (inl p) => gsymPN p\n| inr (inl t) => gsymT t\n| inr (inr v) => gsymV v\nend.\n\nDefinition gsymNotNT {G : CFGV} (s : GSym G) :=\nmatch s with\n| gsymT _ => True\n| gsymV _ => True\n| gsymTN _ => False\n| gsymPN _ => True\nend.\n\nLemma ptrhs_aux_nonNT : forall {G: CFGV} \n    (symSum :((PNonTerminal G)+ (Terminal G + VarSym G))) ,\n  gsymNotNT (ptrhs_aux symSum).\nProof.\n  intros.\n  dorn symSum;[|dorn symSum]; simpl; auto.\nQed.\n\nDefinition ppRhsSym {G: CFGV} (p:PatProd G) : list (GSym G)\n:=map (ptrhs_aux) (snd (ppLhsRhs G p)).\n\nDefinition tpLhs (G: CFGV) (p:TermProd G) : TNonTerminal G\n:= (fst (tpLhsRhs G p)).\n\nDefinition epLhs (G: CFGV) (p:EmbedProd G) : PNonTerminal G\n:= (fst (epLhsRhs G p)).\n\nDefinition epRhs (G: CFGV) (p:EmbedProd G) : TNonTerminal G\n:= (snd (epLhsRhs G p)).\n\nDefinition ppLhs (G: CFGV) (p:PatProd G) : PNonTerminal G\n:= (fst (ppLhsRhs G p)).\n\nDefinition gsymNotP {G : CFGV} (s : GSym G) :=\nmatch s with\n| gsymT _ => True\n| gsymV _ => True\n| gsymTN _ => True\n| gsymPN _ => False\nend.\n\n\nArguments DeqVarSym {c}  _ _.\n\n\nDefinition flatten {A : Type} (l : list (list A)) : list A:= \n  flat_map (fun x => x) l.\n\n\n(* how many times the nth symbol in rhs of production p is bound.\n    (not the most efficient algorithm) *)\nDefinition bindCount {G : CFGV} (p: TermProd G) (n : nat) :=\n  let lnat := (map (@fst _ _) (bindingInfo p))\n    in count_occ deq_nat lnat n.\n\n(* the following can be written better using [LIn]\nDefinition isBound {G : CFGV} (p: TermProd G) (n : nat) :=\n  negb (beq_nat (bindCount p n) 0).\n*)\n\n\n(* Now we (parially) \n    define the semantics of the language,\n    It is essentially a parse tree.\n    The full semantics also needs\n    to formalize variable binding semantics;\n    e.g. alpha equality and substitution.\n    \n    The parse tree s parametrized by the\n    head symbol.\n *)\n\n\nDefinition prhsIsBound {G : CFGV} (p: TermProd G) : list bool := \n (map isInl (snd (tpLhsRhs G p))).\n\nDefinition MixtureParam {G : CFGV} :=\n  list (bool * (GSym G)).\n\nDefinition MParamCorrectb {G : CFGV} (pp: @MixtureParam G)\n   : bool :=\nforallb  (fun p=> match p with \n                   | (false, gsymPN _) => false\n                   | _ => true\n                   end) \n          pp.\n\n\n(* augment rhs with indicators whether a pattern is bound somewhere*)\nDefinition tpRhsAugIsPat {G : CFGV} (p: TermProd G) \n    : MixtureParam := \n combine (prhsIsBound p) (tpRhsSym p).\n\n\n\n(* TODO: Show some examples. encode Coq in the standard inductive\n    way and then use this CFGV. Prove bijection.\n    Ignore bindings to begin with.\n*)\n\n\nDefinition bindingSourcesNth {G:CFGV} \n  (p: TermProd G) (k:nat) : list nat :=\nflat_map \n     (fun pp : (nat * nat) \n                => let (n,m) := pp in \n                    if (beq_nat k m) then [n] else [])\n     (bindingInfo p).\n\nDefinition ValidNthSrc (len : nat) (ln: list nat):=\n  no_repeats ln\n  # lForall (fun n =>  n < len) ln.\n\n\nLemma bsNthValid : forall {G:CFGV}\n(p: TermProd G) (k:nat),\nValidNthSrc (length (tpRhsSym p)) (bindingSourcesNth p k).\nProof.\n  intros. unfold ValidNthSrc.\n  unfold bindingSourcesNth, bindingInfo, tpRhsSym.\n  autorewrite with fast.\n  pose proof (bindingInfoCorrect G p) as XX.\n  destruct (tpLhsRhs G p) as [lhs ls].\n  destruct G; allsimpl; cpx.\n\n  allsimpl. remember ((bindingInfo0 p)) as bi. clear Heqbi.\n  allsimpl. clear  bindingInfoCorrect0.\n  repnud XX. clear XX1.\n  induction bi; dands; allsimpl;  cpx;\n  allrw no_repeats_cons;\n  exrepnd;\n\n  apply IHbi in XX1; exrepnd; cpx;\n  remember (beq_nat k a) as bn; destruct bn; cpx;\n  allrw no_repeats_cons; allsimpl; dands;  cpx.\n  - introv Hin. rw lin_flat_map in Hin.\n    exrepnd.\n    remember (beq_nat k x) as bkx; destruct bkx; allsimpl; cpx.\n    dorn Hin0; subst; cpx.\n    allapply beq_nat_eq.\n    subst. subst. cpx.\n  - pose proof (XX0 _ _ (inl eq_refl)).\n    repnd; cpx.\nQed.\n\nDefinition bndngPatIndices {G:CFGV} \n  (p: TermProd G) : list  (list nat) :=\nmap (bindingSourcesNth p) (seq 0 (length (tpRhsSym p))).\n\nDefinition validBsl (len:nat) (lln: list (list nat)) :=\nlforall (ValidNthSrc len) lln.\n\nLemma  bndngPatIndicesValid : forall\n{G:CFGV} (p: TermProd G),\nvalidBsl (length (tpRhsSym p)) (bndngPatIndices p).\nProof.\n  intros.\n  unfolds_base.\n  unfold bndngPatIndices.\n  introv Hin.\n  apply in_map_iff in Hin.\n  exrepnd.\n  subst.\n  apply bsNthValid.\nQed.\n\nLemma  bndngPatIndicesValid2 : forall\n{G:CFGV} (p: TermProd G),\nvalidBsl (length (snd (tpLhsRhs G p))) (bndngPatIndices p).\nProof.\n  intros.\n  pose proof (bndngPatIndicesValid p) as X.\n  unfold tpRhsSym in X.\n  autorewrite with fast in X.\n  trivial.\nQed.\n\nLemma DeqVtype : forall  {G:CFGV} (vc : VarSym G),\n     Deq (vType vc).\nProof.\n  intros. unfold vType.\n  match goal with\n  [ |- Deq (typ ?xx)] => destruct xx as [? vd]\n  end.\n  repnud vd. auto.\nDefined.\n\nHint Resolve DeqVtype : Deq.\n\nDefinition vFreshVar \n  {G : CFGV} \n  {vc : VarSym G}\n  (lvAvoid: list (vType vc))\n  (v: (vType vc)) : vType vc :=\n  ((fresh (varSem G vc)) lvAvoid [v]).\n\nDefinition GFreshVars \n  {G : CFGV} \n  {vc : VarSym G}\n  (lvAvoid: list (vType vc))\n  (lv: list (vType vc)) : list (vType vc)  :=\n  (FreshDistinctVars (varSem G vc) lv lvAvoid).\n\nLemma FreshDistVarsSpec: forall\n  {G : CFGV} {vc : VarSym G}\n  (lvAvoid: list (vType vc))\n  (lv: list (vType vc)),\n  let lvn := (GFreshVars  lvAvoid lv) in\n  no_repeats lvn # disjoint lvn lvAvoid # length lvn= length lv.\nProof.\n  intros.\n  subst lvn.\n  unfold GFreshVars.\n  pose proof( \n    FreshDistVarsSpec  lv lvAvoid).\n  allsimpl.\n  exrepnd; dands; cpx.\nQed.\n\n\nLemma vFreshVarSpec : forall \n  {G : CFGV} \n  {vc : VarSym G}\n  (lvAvoid: list (vType vc))\n  (v: (vType vc)),\n  ! LIn (vFreshVar lvAvoid v) lvAvoid.\nProof.\n  intros.\n  unfold vFreshVar.\n  revert v. revert lvAvoid.\n  unfold vType.\n  destruct  (varSem G vc) as [T vd Vf Vfc].\n  allsimpl.\n  exrepnd. allsimpl.\n  cpx.\nQed.\n\n(** also guaranteed to be different from the input *)\nDefinition vFreshDiff\n  {G : CFGV} \n  {vc : VarSym G}\n  (lvAvoid: list (vType vc))\n  (v: (vType vc)) :=\n  (fresh (varSem G vc)) (v::lvAvoid) [v].\n\nLemma vFreshDiffSpec : forall \n  {G : CFGV} \n  {vc : VarSym G}\n  (lvAvoid: list (vType vc))\n  (v: (vType vc)),\n  ! LIn (vFreshDiff (lvAvoid) v) (v::lvAvoid).\nProof.\n  intros.\n  apply vFreshVarSpec.\nQed.\n\nLemma length_pRhsAugIsPat : forall {G : CFGV}  (p : TermProd G),\n  length (tpRhsAugIsPat p) = length ((snd (tpLhsRhs G p))).\nProof.\n  intros. simpl.\n  unfold tpRhsAugIsPat, prhsIsBound , tpRhsSym.\n  rewrite combine_length.\n  autorewrite with fast.\n  rewrite min_eq; refl.\nQed.\n\nLemma GFreshDistRenWSpec: forall\n   {G:CFGV} (vc : VarSym G)\n  (lv :list (vType vc))\n  (lvAvoid :list (vType vc)),\n  {lvn : list (vType vc) $\n  no_repeats lvn # disjoint lvn lvAvoid \n  # length lvn= length lv}.\nProof.\n  intros. eapply FreshDistRenWSpec; eauto.\nDefined.\n\nLemma deqMixP : forall {G}, Deq (@MixtureParam G).\nProof.\n  unfold MixtureParam.\n  eauto with Deq.\nDefined.\n\nLemma deqSigVType : \n  forall {G}, (Deq (sigT (@vType G))).\nProof.\n  intros.\n  apply sigTDeq;\n  eauto with Deq.\nDefined.\n\nLemma deqSigTSemType : \n  forall {G}, (Deq (sigT (tSemType G))).\nProof.\n  intros.\n  apply sigTDeq;\n  eauto with Deq.\nDefined.\n\n\nDefinition decDisjointV {G} (vc : VarSym G)\n   (la lb : list (vType vc)) :\n    (disjoint la lb[+]!disjoint la lb)\n  := dec_disjoint (DeqVtype vc) la lb.\n\nLtac proveBindingInfoCorrect :=\n  let p:= fresh \"tprod\" in\n  let d:= fresh \"decVal\" in\n  let Heqd:= fresh \"Heq\" d in\n  intro p;\n  match goal with\n  [ |- ValidIndices ?binf ?rhsSyms ] =>\n    remember (ValidIndicesDecidable binf rhsSyms) as d eqn:Heqd;\n      destruct p; unfold ValidIndicesDecidable in Heqd; allsimpl;\n      destruct d; auto; inverts Heqd\n  end.\n\nLtac proveDeqInductiveNonrec :=\n  let x:= fresh \"xdl\" in\n  let y:= fresh \"axr\" in\n  let Hc:= fresh \"Hcontra\" in\n  intros x y ; destruct x; destruct y; \n    try (left; cpx; fail); (try right; introv Hc; inverts Hc ; cpx).\n(*\n*** Local Variables:\n*** coq-load-path: (\"../\")\n*** End:\n*)\n\n(*\nDefinition vFreshDistRenLL \n  {G : CFGV} (vc : VarSym G):=\n  FreshDistinctRenListList (snd (projT2 (vSemType G vc))).\n*)\n\n(* Lemma  : forall {G : CFGV},\n  Deq (VarSym G).\nProof.\n  intros.\n  destruct G.\n  simpl.\n  (* info_eauto with Deq. *)\n    apply Finite_Deq.\n    exact FinV0.\nDefined. *)\n\n(*\nwith Patterns {G : CFGV} :\n  list (GSym G) -> Type :=\n| pnil : Patterns []\n| pcons : forall  {h: GSym G}\n        {tl: list (GSym G) }\n        (ph: Pattern h )\n        (ptl: Patterns tl),\n          Patterns (h::tl)\n*)\n(* not necessary till we do parsing.\n  these implied decidability of equality.\n  We added those to make\n  depedent destruction to work.\n\n  FinV: Finite VarSym;\n  FinPt: Finite PNonTerminal;\n  FinT: Finite Terminal;\n  FinPr: Finite TermProd;\n  FinEmb: Finite EmbedProd;\n  FinNT: Finite TNonTerminal;\n  FinPat: Finite PatProd;\n*)\n(* The following legitimate definition is\n    rejected by Coq's too strict strict-positivity checker.\n[[\nRequire Import Tuples.\nInductive ParseTree (G : CFGV) : (GSymb G) -> Type :=\n| leaf : forall (t :Token G), ParseTree G (Token2Gsymb t)\n| tnode : forall (p: TermProd G),\n    tuple (map (ParseTree G) (prhs G p))\n    -> (ParseTree G  (gsymTN _ _ _ (tpLhs G p))).\n]]\n*)\n", "meta": {"author": "aa755", "repo": "CFGV", "sha": "440965e85e0d7107a8f0cfef5d14b895979716e5", "save_path": "github-repos/coq/aa755-CFGV", "path": "github-repos/coq/aa755-CFGV/CFGV-440965e85e0d7107a8f0cfef5d14b895979716e5/CFGV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2311168699410591}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Rewriter.Language.Language.\nRequire Import Crypto.Language.API.\nRequire Import Rewriter.Language.Wf.\nRequire Import Crypto.Language.WfExtra.\nRequire Import Crypto.Rewriter.AllTacticsExtra.\nRequire Import Crypto.Rewriter.RulesProofs.\n\nModule Compilers.\n  Import Language.Compilers.\n  Import Language.API.Compilers.\n  Import Language.Wf.Compilers.\n  Import Language.WfExtra.Compilers.\n  Import Rewriter.AllTacticsExtra.Compilers.RewriteRules.GoalType.\n  Import Rewriter.AllTactics.Compilers.RewriteRules.Tactic.\n  Import Compilers.Classes.\n\n  Module Import RewriteRules.\n    Section __.\n      Context (max_const_val : Z).\n\n      Definition VerifiedRewriterArith : VerifiedRewriter_with_args false false true (arith_rewrite_rules_proofs max_const_val).\n      Proof using All. make_rewriter. Defined.\n\n      Definition default_opts := Eval hnf in @default_opts VerifiedRewriterArith.\n      Let optsT := Eval hnf in optsT VerifiedRewriterArith.\n\n      Definition RewriteArith (opts : optsT) {t : API.type} := Eval hnf in @Rewrite VerifiedRewriterArith opts t.\n\n      Lemma Wf_RewriteArith opts {t} e (Hwf : Wf e) : Wf (@RewriteArith opts t e).\n      Proof. now apply VerifiedRewriterArith. Qed.\n\n      Lemma Interp_RewriteArith opts {t} e (Hwf : Wf e) : API.Interp (@RewriteArith opts t e) == API.Interp e.\n      Proof. now apply VerifiedRewriterArith. Qed.\n    End __.\n  End RewriteRules.\n\n  Module Export Hints.\n#[global]\n    Hint Resolve Wf_RewriteArith : wf wf_extra.\n#[global]\n    Hint Opaque RewriteArith : wf wf_extra interp interp_extra rewrite.\n#[global]\n    Hint Rewrite @Interp_RewriteArith : interp interp_extra.\n  End Hints.\nEnd Compilers.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Rewriter/Passes/Arith.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23111686390976063}}
{"text": "Require Import Omega.\nRequire Import Bool.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import PromiseConsistent.\nRequire Import Mapping.\n\nRequire Import PFStep.\n\nSet Implicit Arguments.\n\n\n\n\n(** L-SC machine **)\nModule SCLocal.\n  Section SCLocal.\n    Variable L: Loc.t -> bool.\n\n    Definition non_maximal (lc: Local.t) (mem: Memory.t) (loc: Loc.t): Prop :=\n      exists to from val released,\n        (<<GET: Memory.get loc to mem = Some (from, Message.concrete val released)>>) /\\\n        (<<TS: Time.lt ((TView.cur (Local.tview lc)).(View.rlx) loc) to>>)\n    .\n\n    Inductive read_step (lc1:Local.t) (mem1:Memory.t) (loc:Loc.t) (to:Time.t) (val:Const.t) (released:option View.t) (ord:Ordering.t) (lc2:Local.t): Prop :=\n    | read_step_intro\n        ord'\n        (ORD: ord' = if L loc then Ordering.join ord Ordering.acqrel else ord)\n        (STEP: Local.read_step lc1 mem1 loc to val released ord' lc2)\n        (MAXIMAL: forall (LOC: L loc)\n                         from' to' val' released'\n                         (GET: Memory.get loc to' mem1 = Some (from', Message.concrete val' released')),\n            Time.le to' to)\n    .\n    Hint Constructors read_step.\n\n    Inductive write_step (lc1:Local.t) (sc1:TimeMap.t) (mem1:Memory.t)\n              (loc:Loc.t) (from to:Time.t)\n              (val:Const.t) (releasedm released:option View.t) (ord:Ordering.t)\n              (lc2:Local.t) (sc2:TimeMap.t) (mem2:Memory.t) (kind:Memory.op_kind): Prop :=\n    | write_step_intro\n        ord'\n        (ORD: ord' = if L loc then Ordering.join ord Ordering.acqrel else ord)\n        (STEP: Local.write_step lc1 sc1 mem1 loc from to val releasedm released ord' lc2 sc2 mem2 kind)\n        (MAXIMAL: forall (LOC: L loc)\n                         from' to' val' released'\n                         (GET: Memory.get loc to' mem1 = Some (from', Message.concrete val' released')),\n            Time.lt to' to)\n    .\n    Hint Constructors write_step.\n\n    Inductive program_step:\n      forall (e:ThreadEvent.t) (lc1:Local.t) (sc1:TimeMap.t) (mem1:Memory.t) (lc2:Local.t) (sc2:TimeMap.t) (mem2:Memory.t), Prop :=\n    | step_silent\n        lc1 sc1 mem1:\n        program_step ThreadEvent.silent lc1 sc1 mem1 lc1 sc1 mem1\n    | step_read\n        lc1 sc1 mem1\n        loc ts val released ord lc2\n        (LOCAL: read_step lc1 mem1 loc ts val released ord lc2):\n        program_step (ThreadEvent.read loc ts val released ord) lc1 sc1 mem1 lc2 sc1 mem1\n    | step_write\n        lc1 sc1 mem1\n        loc from to val released ord lc2 sc2 mem2 kind\n        (LOCAL: write_step lc1 sc1 mem1 loc from to val None released ord lc2 sc2 mem2 kind):\n        program_step (ThreadEvent.write loc from to val released ord) lc1 sc1 mem1 lc2 sc2 mem2\n    | step_update\n        lc1 sc1 mem1\n        loc ordr ordw\n        tsr valr releasedr releasedw lc2\n        tsw valw lc3 sc3 mem3 kind\n        (LOCAL1: read_step lc1 mem1 loc tsr valr releasedr ordr lc2)\n        (LOCAL2: write_step lc2 sc1 mem1 loc tsr tsw valw releasedr releasedw ordw lc3 sc3 mem3 kind):\n        program_step (ThreadEvent.update loc tsr tsw valr valw releasedr releasedw ordr ordw)\n                     lc1 sc1 mem1 lc3 sc3 mem3\n    | step_fence\n        lc1 sc1 mem1\n        ordr ordw lc2 sc2\n        (LOCAL: Local.fence_step lc1 sc1 ordr ordw lc2 sc2):\n        program_step (ThreadEvent.fence ordr ordw) lc1 sc1 mem1 lc2 sc2 mem1\n    | step_syscall\n        lc1 sc1 mem1\n        e lc2 sc2\n        (LOCAL: Local.fence_step lc1 sc1 Ordering.seqcst Ordering.seqcst lc2 sc2):\n        program_step (ThreadEvent.syscall e) lc1 sc1 mem1 lc2 sc2 mem1\n    | step_failure\n        lc1 sc1 mem1\n        (LOCAL: Local.failure_step lc1):\n        program_step ThreadEvent.failure lc1 sc1 mem1 lc1 sc1 mem1\n    .\n    Hint Constructors program_step.\n\n\n    (* step_future *)\n\n    Lemma write_step_non_cancel\n          lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n          (STEP: write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind):\n      negb (Memory.op_kind_is_cancel kind).\n    Proof.\n      inv STEP. eapply Local.write_step_non_cancel; eauto.\n    Qed.\n\n    Lemma write_step_strong_relaxed\n          lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind\n          (STEP: write_step lc1 sc1 mem1 loc from to val releasedm released ord lc2 sc2 mem2 kind)\n          (ORD: Ordering.le Ordering.strong_relaxed ord):\n      negb (Memory.op_kind_is_lower kind).\n    Proof.\n      inv STEP. eapply Local.write_step_strong_relaxed; eauto.\n      etrans; eauto. des_ifs; try refl.\n      eapply Ordering.join_l.\n    Qed.\n\n    Lemma program_step_future\n          e lc1 sc1 mem1 lc2 sc2 mem2\n          (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n          (WF1: Local.wf lc1 mem1)\n          (SC1: Memory.closed_timemap sc1 mem1)\n          (CLOSED1: Memory.closed mem1):\n      <<WF2: Local.wf lc2 mem2>> /\\\n      <<SC2: Memory.closed_timemap sc2 mem2>> /\\\n      <<CLOSED2: Memory.closed mem2>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview lc1) (Local.tview lc2)>> /\\\n      <<SC_FUTURE: TimeMap.le sc1 sc2>> /\\\n      <<MEM_FUTURE: Memory.future mem1 mem2>>.\n    Proof.\n      inv STEP.\n      - esplits; eauto; try refl.\n      - inv LOCAL.\n        exploit Local.read_step_future; eauto. i. des.\n        esplits; eauto; try refl.\n      - inv LOCAL.\n        exploit Local.write_step_future; eauto; try by econs. i. des.\n        esplits; eauto; try refl.\n      - inv LOCAL1. inv LOCAL2.\n        exploit Local.read_step_future; eauto. i. des.\n        exploit Local.write_step_future; eauto; try by econs. i. des.\n        esplits; eauto. etrans; eauto.\n      - exploit Local.fence_step_future; eauto. i. des. esplits; eauto; try refl.\n      - exploit Local.fence_step_future; eauto. i. des. esplits; eauto; try refl.\n      - esplits; eauto; try refl.\n    Qed.\n\n    Lemma program_step_inhabited\n          e lc1 sc1 mem1 lc2 sc2 mem2\n          (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n          (INHABITED1: Memory.inhabited mem1):\n      <<INHABITED2: Memory.inhabited mem2>>.\n    Proof.\n      inv STEP; eauto.\n      - inv LOCAL. inv STEP. inv WRITE.\n        inv PROMISE; eauto using Memory.add_inhabited, Memory.split_inhabited, Memory.lower_inhabited, Memory.cancel_inhabited.\n      - inv LOCAL2. inv STEP. inv WRITE.\n        inv PROMISE; eauto using Memory.add_inhabited, Memory.split_inhabited, Memory.lower_inhabited, Memory.cancel_inhabited.\n    Qed.\n\n\n    (* step_disjoint *)\n\n    Lemma program_step_disjoint\n          e lc1 sc1 mem1 lc2 sc2 mem2 lc\n          (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n          (WF1: Local.wf lc1 mem1)\n          (SC1: Memory.closed_timemap sc1 mem1)\n          (CLOSED1: Memory.closed mem1)\n          (DISJOINT1: Local.disjoint lc1 lc)\n          (WF: Local.wf lc mem1):\n      <<DISJOINT2: Local.disjoint lc2 lc>> /\\\n      <<WF: Local.wf lc mem2>>.\n    Proof.\n      inv STEP.\n      - esplits; eauto.\n      - inv LOCAL. exploit Local.read_step_disjoint; eauto.\n      - inv LOCAL. exploit Local.write_step_disjoint; eauto.\n      - inv LOCAL1. inv LOCAL2.\n        exploit Local.read_step_future; eauto. i. des.\n        exploit Local.read_step_disjoint; eauto. i. des.\n        exploit Local.write_step_disjoint; eauto.\n      - exploit Local.fence_step_disjoint; eauto.\n      - exploit Local.fence_step_disjoint; eauto.\n      - esplits; eauto.\n    Qed.\n\n    Lemma program_step_promises_bot\n          e lc1 sc1 mem1 lc2 sc2 mem2\n          (STEP: program_step e lc1 sc1 mem1 lc2 sc2 mem2)\n          (PROMISES: (Local.promises lc1) = Memory.bot):\n      (Local.promises lc2) = Memory.bot.\n    Proof.\n      inv STEP; try inv LOCAL; ss; try inv STEP; ss.\n      - eapply Memory.write_promises_bot; eauto.\n      - inv LOCAL1. inv LOCAL2. inv STEP. inv STEP0.\n        eapply Memory.write_promises_bot; eauto.\n    Qed.\n  End SCLocal.\nEnd SCLocal.\n\n\nModule SCThread.\n  Section SCThread.\n    Variable lang: language.\n    Variable L: Loc.t -> bool.\n\n    Inductive program_step (e:ThreadEvent.t): forall (e1 e2:Thread.t lang), Prop :=\n    | program_step_intro\n        st1 lc1 sc1 mem1\n        st2 lc2 sc2 mem2\n        (STATE: (Language.step lang) (ThreadEvent.get_program_event e) st1 st2)\n        (LOCAL: SCLocal.program_step L e lc1 sc1 mem1 lc2 sc2 mem2):\n        program_step e (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2)\n    .\n    Hint Constructors program_step.\n\n    Inductive step: forall (pf:bool) (e:ThreadEvent.t) (e1 e2:Thread.t lang), Prop :=\n    | step_promise\n        pf e e1 e2\n        (STEP: Thread.promise_step pf e e1 e2)\n        (PF: PF.pf_event L e):\n        step pf e e1 e2\n    | step_program\n        e e1 e2\n        (STEP: program_step e e1 e2):\n        step true e e1 e2\n    .\n    Hint Constructors step.\n\n    Inductive step_allpf (e: ThreadEvent.t) (e1 e2: Thread.t lang): Prop :=\n    | step_nopf_intro\n        pf\n        (STEP: step pf e e1 e2)\n    .\n    Hint Constructors step_allpf.\n\n    Lemma allpf pf: step pf <3= step_allpf.\n    Proof.\n      i. econs. eauto.\n    Qed.\n\n    Definition pf_tau_step := tau (step true).\n    Hint Unfold pf_tau_step.\n\n    Definition tau_step := tau step_allpf.\n    Hint Unfold tau_step.\n\n    Definition all_step := union step_allpf.\n    Hint Unfold all_step.\n\n    Inductive opt_step: forall (e: ThreadEvent.t) (e1 e2: Thread.t lang), Prop :=\n    | step_none\n        e:\n        opt_step ThreadEvent.silent e e\n    | step_some\n        pf e e1 e2\n        (STEP: step pf e e1 e2):\n        opt_step e e1 e2\n    .\n    Hint Constructors opt_step.\n\n    Definition steps_failure (e1: Thread.t lang): Prop :=\n      exists e2 e3,\n        <<STEPS: rtc tau_step e1 e2>> /\\\n        <<FAILURE: step true ThreadEvent.failure e2 e3>>.\n    Hint Unfold steps_failure.\n\n    Definition consistent (e: Thread.t lang): Prop :=\n      forall mem1 sc1\n        (CAP: Memory.cap (Thread.memory e) mem1)\n        (SC_MAX: Memory.max_concrete_timemap mem1 sc1),\n        <<FAILURE: steps_failure (Thread.mk lang (Thread.state e) (Thread.local e) sc1 mem1)>> \\/\n        exists e2,\n          <<STEPS: rtc tau_step (Thread.mk lang (Thread.state e) (Thread.local e) sc1 mem1) e2>> /\\\n          <<PROMISES: (Local.promises (Thread.local e2)) = Memory.bot>>.\n\n\n    (* future *)\n\n    Lemma program_step_future\n          e e1 e2\n          (STEP: program_step e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      inv STEP. ss. eapply SCLocal.program_step_future; eauto.\n    Qed.\n\n    Lemma step_future\n          pf e e1 e2\n          (STEP: step pf e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      inv STEP.\n      - eapply Thread.promise_step_future; eauto.\n      - eapply program_step_future; eauto.\n    Qed.\n\n    Lemma rtc_all_step_future\n          e1 e2\n          (STEPS: rtc all_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      revert WF1 SC1 CLOSED1. induction STEPS; i.\n      - esplits; eauto; refl.\n      - inv H. inv USTEP. exploit step_future; eauto. i. des.\n        exploit IHSTEPS; eauto. i. des.\n        esplits; eauto; etrans; eauto.\n    Qed.\n\n    Lemma rtc_tau_step_future\n          e1 e2\n          (STEPS: rtc tau_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      eapply rtc_all_step_future; eauto.\n      eapply rtc_implies; try exact STEPS.\n      apply tau_union.\n    Qed.\n\n    Lemma opt_step_future\n          e e1 e2\n          (STEP: opt_step e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1)):\n      <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\\n      <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\\n      <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\\n      <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>.\n    Proof.\n      inv STEP.\n      - esplits; eauto; try refl.\n      - eapply step_future; eauto.\n    Qed.\n\n    (* disjoint *)\n\n    Lemma step_disjoint\n          pf e e1 e2 lc\n          (STEP: step pf e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (DISJOINT1: Local.disjoint (Thread.local e1) lc)\n          (WF: Local.wf lc (Thread.memory e1)):\n      <<DISJOINT2: Local.disjoint (Thread.local e2) lc>> /\\\n      <<WF: Local.wf lc (Thread.memory e2)>>.\n    Proof.\n      inv STEP.\n      - eapply Thread.promise_step_disjoint; eauto.\n      - inv STEP0. eapply SCLocal.program_step_disjoint; eauto.\n    Qed.\n\n    Lemma rtc_all_step_disjoint\n          e1 e2 lc\n          (STEPS: rtc all_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (DISJOINT1: Local.disjoint (Thread.local e1) lc)\n          (WF: Local.wf lc (Thread.memory e1)):\n      <<DISJOINT2: Local.disjoint (Thread.local e2) lc>> /\\\n      <<WF: Local.wf lc (Thread.memory e2)>>.\n    Proof.\n      revert WF1 SC1 CLOSED1 DISJOINT1 WF.\n      induction STEPS; i; eauto.\n      inv H. inv USTEP.\n      exploit step_future; eauto. i. des.\n      exploit step_disjoint; eauto. i. des.\n      eauto.\n    Qed.\n\n    Lemma rtc_tau_step_disjoint\n          e1 e2 lc\n          (STEPS: rtc tau_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (DISJOINT1: Local.disjoint (Thread.local e1) lc)\n          (WF: Local.wf lc (Thread.memory e1)):\n      <<DISJOINT2: Local.disjoint (Thread.local e2) lc>> /\\\n      <<WF: Local.wf lc (Thread.memory e2)>>.\n    Proof.\n      eapply rtc_all_step_disjoint; try exact DISJOINT1; eauto.\n      eapply rtc_implies; try exact STEPS.\n      apply tau_union.\n    Qed.\n\n\n    (* promise_consistent *)\n\n    Lemma step_promise_consistent\n          pf e e1 e2\n          (STEP: step pf e e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (CONS: Local.promise_consistent (Thread.local e2)):\n      Local.promise_consistent (Thread.local e1).\n    Proof.\n      inv STEP; ss.\n      - inv STEP0. s.\n        eapply promise_step_promise_consistent; eauto.\n      - inv STEP0. inv LOCAL; ss.\n        + inv LOCAL0. eapply read_step_promise_consistent; eauto.\n        + inv LOCAL0. eapply write_step_promise_consistent; eauto.\n        + inv LOCAL1. inv LOCAL2.\n          exploit Local.read_step_future; eauto. i. des.\n          eapply read_step_promise_consistent; eauto.\n          eapply write_step_promise_consistent; eauto.\n        + eapply fence_step_promise_consistent; eauto.\n        + eapply fence_step_promise_consistent; eauto.\n    Qed.\n\n    Lemma rtc_all_step_promise_consistent\n          e1 e2\n          (STEPS: rtc all_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (CONS: Local.promise_consistent (Thread.local e2)):\n      Local.promise_consistent (Thread.local e1).\n    Proof.\n      revert WF1 SC1 CLOSED1 CONS. induction STEPS; ss. i.\n      inv H. inv USTEP. exploit step_future; eauto. i. des.\n      eapply step_promise_consistent; eauto.\n    Qed.\n\n    Lemma rtc_tau_step_promise_consistent\n          e1 e2\n          (STEPS: rtc tau_step e1 e2)\n          (WF1: Local.wf (Thread.local e1) (Thread.memory e1))\n          (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1))\n          (CLOSED1: Memory.closed (Thread.memory e1))\n          (CONS: Local.promise_consistent (Thread.local e2)):\n      Local.promise_consistent (Thread.local e1).\n    Proof.\n      eapply rtc_all_step_promise_consistent; try exact CONS; eauto.\n      eapply rtc_implies; try exact STEPS.\n      apply tau_union.\n    Qed.\n\n  End SCThread.\nEnd SCThread.\n\n\nModule SCConfiguration.\n  Section SCConfiguration.\n    Variable L: Loc.t -> bool.\n\n    Inductive step: forall (e: ThreadEvent.t) (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n    | step_intro\n        e tid c1 lang st1 lc1 e2 e3 st4 lc4 sc4 memory4\n        (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))\n        (CANCELS: rtc (@Thread.cancel_step _) (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1)) e2)\n        (STEP: SCThread.opt_step L e e2 e3)\n        (RESERVES: rtc (@Thread.reserve_step _) e3 (Thread.mk _ st4 lc4 sc4 memory4))\n        (CONSISTENT: e <> ThreadEvent.failure ->\n                     SCThread.consistent L (Thread.mk _ st4 lc4 sc4 memory4)):\n        step e tid c1 (Configuration.mk (IdentMap.add tid (existT _ _ st4, lc4) (Configuration.threads c1)) sc4 memory4)\n    .\n    Hint Constructors step.\n\n    Inductive all_step (c1 c2: Configuration.t): Prop :=\n    | all_step_intro\n        e tid\n        (STEP: step e tid c1 c2)\n    .\n    Hint Constructors all_step.\n\n    Inductive machine_step: forall (e: MachineEvent.t) (tid: Ident.t) (c1 c2: Configuration.t), Prop :=\n    | machine_step_instro\n        e tid c1 c2\n        (STEP: step e tid c1 c2):\n        machine_step (ThreadEvent.get_machine_event e) tid c1 c2\n    .\n    Hint Constructors machine_step.\n\n    Lemma step_future\n          e tid c1 c2\n          (STEP: step e tid c1 c2)\n          (WF1: Configuration.wf c1):\n      (<<WF2: Configuration.wf c2>>) /\\\n      (<<SC_FUTURE: TimeMap.le (Configuration.sc c1) (Configuration.sc c2)>>) /\\\n      (<<MEM_FUTURE: Memory.future (Configuration.memory c1) (Configuration.memory c2)>>).\n    Proof.\n      inv WF1. inv WF. inv STEP; s. exploit THREADS; ss; eauto. i.\n      assert (STEPS: rtc\n                       (@SCThread.all_step _ L)\n                       (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1))\n                       (Thread.mk _ st4 lc4 sc4 memory4)).\n      { etrans.\n        { eapply rtc_implies; try apply CANCELS. i.\n          inv H. inv STEP; [|inv STEP1; inv LOCAL].\n          econs; eauto. econs; eauto. econs 1; eauto. ii. clarify. }\n        etrans.\n        { instantiate (1:=e3). inv STEP0; eauto.\n          econs; [|refl]; eauto. econs; eauto. econs; eauto. }\n        { eapply rtc_implies; try apply RESERVES. i.\n          inv H. inv STEP; [|inv STEP1; inv LOCAL].\n          econs; eauto. econs; eauto. econs 1; eauto. ii. clarify. }\n      }\n      exploit SCThread.rtc_all_step_future; eauto. s. i. des.\n      splits; eauto. econs; ss. econs.\n      + i. Configuration.simplify.\n        * exploit THREADS; try apply TH1; eauto. i. des.\n          exploit SCThread.rtc_all_step_disjoint; eauto. i. des.\n          symmetry. auto.\n        * exploit THREADS; try apply TH2; eauto. i. des.\n          exploit SCThread.rtc_all_step_disjoint; eauto. i. des.\n          auto.\n        * eapply DISJOINT; [|eauto|eauto]. auto.\n      + i. Configuration.simplify.\n        exploit THREADS; try apply TH; eauto. i.\n        exploit SCThread.rtc_all_step_disjoint; eauto. i. des.\n        auto.\n    Qed.\n\n    Lemma all_steps_future\n          c1 c2\n          (STEPS: rtc all_step c1 c2)\n          (WF1: Configuration.wf c1):\n      (<<WF2: Configuration.wf c2>>) /\\\n      (<<SC_FUTURE: TimeMap.le (Configuration.sc c1) (Configuration.sc c2)>>) /\\\n      (<<MEM_FUTURE: Memory.future (Configuration.memory c1) (Configuration.memory c2)>>).\n    Proof.\n      ginduction STEPS; eauto.\n      - i. esplits; eauto; try refl.\n      - i. inv H. exploit step_future; eauto. i. des.\n        exploit IHSTEPS; eauto. i. des. esplits; eauto. etrans; eauto.\n    Qed.\n  End SCConfiguration.\nEnd SCConfiguration.\n\n\nDefinition is_accessing (e:ProgramEvent.t): option Loc.t :=\n  match e with\n  | ProgramEvent.read loc _ _ => Some loc\n  | ProgramEvent.write loc _ _ => Some loc\n  | ProgramEvent.update loc _ _ _ _ => Some loc\n  | _ => None\n  end.\n\n\n(** L-SC race **)\nModule SCRace.\n  Section SCRace.\n    Variable L: Loc.t -> bool.\n\n    Definition race lang (th: Thread.t lang): Prop :=\n      exists e st' loc,\n        (<<STEP: Language.step _ e (Thread.state th) st'>>) /\\\n        (<<ACCESS: is_accessing e = (Some loc)>>) /\\\n        (<<LOC: L loc>>) /\\\n        (<<MAXIMAL: SCLocal.non_maximal (Thread.local th) (Thread.memory th) loc>>).\n\n    Lemma non_maximal_equiv lc loc mem\n          (LOCAL: Local.wf lc mem)\n      :\n        SCLocal.non_maximal lc mem loc <->\n        ~ Memory.max_concrete_ts mem loc ((TView.cur (Local.tview lc)).(View.rlx) loc).\n    Proof.\n      inv LOCAL. unfold SCLocal.non_maximal. split; i.\n      - des. ii. eapply H in GET. timetac.\n      - inv TVIEW_CLOSED. inv CUR. specialize (RLX loc). des.\n        eapply NNPP. ii. eapply H. econs; eauto.\n        i. destruct (Time.le_lt_dec to (View.rlx (TView.cur (Local.tview lc)) loc)); auto.\n        exfalso. eapply H0. esplits; eauto.\n    Qed.\n\n    Definition race_steps (c: Configuration.t) (tid: Ident.t): Prop :=\n      exists lang st1 lc1 e2,\n        (<<TID: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st1, lc1)>>) /\\\n        (<<THREAD_STEPS: rtc (SCThread.all_step L)\n                             (Thread.mk _ st1 lc1 (Configuration.sc c) (Configuration.memory c)) e2>>) /\\\n        (<<CONS: Local.promise_consistent (Thread.local e2)>>) /\\\n        (<<SCRACE: race e2>>).\n\n    Definition racefree (c: Configuration.t): Prop :=\n      forall tid c2\n             (STEPS: rtc (SCConfiguration.all_step L) c c2),\n        ~ race_steps c2 tid.\n\n    Definition racefree_syn (syn: Threads.syntax): Prop :=\n      racefree (Configuration.init syn).\n\n    Lemma step_racefree\n          e tid c1 c2\n          (RACEFREE: racefree c1)\n          (STEP: SCConfiguration.step L e tid c1 c2):\n      racefree c2.\n    Proof.\n      ii. eapply RACEFREE; cycle 1; eauto.\n      econs 2; eauto. econs; eauto.\n    Qed.\n  End SCRace.\nEnd SCRace.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/ldrfsc/SCStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7279754489059775, "lm_q2_score": 0.3174262785020255, "lm_q1q2_score": 0.23107853758706584}}
{"text": "Require Import Lia.\nRequire Import RelationClasses.\n\nFrom Paco Require Import paco.\nFrom sflib Require Import sflib.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nRequire Import Time.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\nRequire Import Behavior.\n\nRequire Import PF.\n\nSet Implicit Arguments.\n\nModule PFSingle.\n\n  Inductive step: forall (e:MachineEvent.t) (tid:Ident.t) (c1 c2: Configuration.t), Prop :=\n  | step_intro\n      e tid c1 lang st1 lc1 st3 lc3 sc3 memory3\n      (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))\n      (STEP: Thread.program_step e (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1)) (Thread.mk _ st3 lc3 sc3 memory3))\n      c2\n      (CONFIG: c2 = Configuration.mk (IdentMap.add tid (existT _ _ st3, lc3) (Configuration.threads c1)) sc3 memory3)\n    :\n      step (ThreadEvent.get_machine_event e) tid c1 c2\n  .\n\n  Inductive tau_step tid (c1 c2: Configuration.t): Prop :=\n  | tau_step_intro\n      (STEP: step MachineEvent.silent tid c1 c2)\n  .\n\n  Definition step_all (c0 c1: Configuration.t) :=\n    union (fun e => union (step e)) c0 c1.\n  #[export]\n  Hint Unfold step_all: core.\n\n  Lemma step_long_step\n    :\n      step <4= PFConfiguration.step.\n  Proof.\n    i. inv PR. econs; eauto.\n  Qed.\n\n  Lemma tau_steps_single_steps c tid lang st1 lc1 st2 lc2 sc2 mem2\n        (TID: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st1, lc1))\n        (STEPS: Relation_Operators.clos_refl_trans_n1 _ (tau (@Thread.program_step _)) (Thread.mk _ st1 lc1 (Configuration.sc c) (Configuration.memory c)) (Thread.mk _ st2 lc2 sc2 mem2))\n    :\n      exists ths',\n        (<<STEPS: Relation_Operators.clos_refl_trans_n1 _ (tau_step tid) c (Configuration.mk ths' sc2 mem2)>>) /\\\n        ((ths' = IdentMap.add tid (existT _ lang st2, lc2) (Configuration.threads c)) \\/\n         (ths' = (Configuration.threads c) /\\ st1 = st2 /\\ lc1 = lc2)).\n  Proof.\n    remember (Thread.mk _ st1 lc1 (Configuration.sc c) (Configuration.memory c)) as th1.\n    remember (Thread.mk _ st2 lc2 sc2 mem2) as th2. ginduction STEPS.\n    - i. clarify. destruct c. esplits.\n      + ss. econs 1.\n      + ss. right. auto.\n    - i. clarify. destruct y. inv H. exploit IHSTEPS; eauto. i. des; clarify.\n      + destruct c. ss. esplits.\n        * econs 2; eauto. econs; eauto. rewrite <- EVENT. econs; eauto.\n          ss. rewrite IdentMap.gss. ss.\n        * ss. left. eapply IdentMap.add_add_eq.\n      + destruct c. ss. esplits.\n        * econs 2; eauto. econs; eauto. rewrite <- EVENT. econs; eauto.\n        * ss. left. auto.\n  Qed.\n\n  Lemma step_sim c0 c1 e tid\n        (STEP: PFConfiguration.step e tid c0 c1)\n    :\n      exists c',\n        (<<STEPS: rtc (tau_step tid) c0 c'>>) /\\\n        (<<STEP: step e tid c' c1>>).\n  Proof.\n    inv STEP.\n    eapply Operators_Properties.clos_rt1n_rt in STEPS.\n    eapply Operators_Properties.clos_rt_rtn1 in STEPS.\n    destruct e2. exploit tau_steps_single_steps; eauto. i. des; clarify.\n    - eapply Operators_Properties.clos_rtn1_rt in STEPS0.\n      eapply Operators_Properties.clos_rt_rt1n in STEPS0.\n      esplits; eauto. econs.\n      + ss. rewrite IdentMap.gss. ss.\n      + ss. eauto.\n      + ss. f_equal. symmetry. eapply IdentMap.add_add_eq.\n    - eapply Operators_Properties.clos_rtn1_rt in STEPS0.\n      eapply Operators_Properties.clos_rt_rt1n in STEPS0.\n      esplits; eauto. econs; eauto.\n  Qed.\n\n  Lemma taus_step tid c0 c1 beh\n        (TAUS: rtc (tau_step tid) c0 c1)\n        (BEH: behaviors step c1 beh)\n    :\n      behaviors step c0 beh.\n  Proof.\n    ginduction TAUS; i; auto.\n    eapply IHTAUS in BEH. inv H. econs 4; eauto.\n  Qed.\n\n  Theorem long_step_equiv c\n    :\n      behaviors PFConfiguration.step c\n      <1=\n      behaviors step c.\n  Proof.\n    ii. ginduction PR.\n    - econs; ss.\n    - exploit step_sim; eauto. i. des.\n      eapply taus_step in STEPS; eauto. econs 2; eauto.\n    - exploit step_sim; eauto. i. des.\n      eapply taus_step in STEPS; eauto. econs 3; eauto.\n    - exploit step_sim; eauto. i. des.\n      eapply taus_step in STEPS; eauto. econs 4; eauto.\n  Qed.\n\n  Theorem long_step_equiv2 c\n    :\n      behaviors step c\n      <1=\n      behaviors PFConfiguration.step c.\n  Proof.\n    eapply le_step_behavior_improve; eauto.\n    eapply step_long_step.\n  Qed.\n\nEnd PFSingle.\n", "meta": {"author": "snu-sf", "repo": "promising2-coq", "sha": "52dd46538036a7a69c132e89dd3e7698b5e2f830", "save_path": "github-repos/coq/snu-sf-promising2-coq", "path": "github-repos/coq/snu-sf-promising2-coq/promising2-coq-52dd46538036a7a69c132e89dd3e7698b5e2f830/src/pf/PFSingle.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.231042894885315}}
{"text": "Require Import CertiGraph.CertiGC.gc_spec.\nRequire Import CertiGraph.msl_ext.ramification_lemmas.\n\nLocal Open Scope logic.\n\nLemma root_valid_int_or_ptr: forall g (roots: roots_t) root outlier,\n    In root roots ->\n    roots_compatible g outlier roots ->\n    graph_rep g * outlier_rep outlier |-- !! (valid_int_or_ptr (root2val g root)).\nProof.\n  intros. destruct H0. destruct root as [[? | ?] | ?].\n  - simpl root2val. unfold odd_Z2val. replace (2 * z + 1) with (z + z + 1) by lia.\n    apply prop_right, valid_int_or_ptr_ii1.\n  - sep_apply (roots_outlier_rep_single_rep _ _ _ H H0).\n    sep_apply (single_outlier_rep_valid_int_or_ptr g0). entailer!.\n  - red in H1. rewrite Forall_forall in H1.\n    rewrite (filter_sum_right_In_iff v roots) in H.\n    apply H1 in H. simpl. sep_apply (graph_rep_valid_int_or_ptr _ _ H). entailer!.\nQed.\n\nLemma weak_derives_strong: forall (P Q: mpred),\n    P |-- Q -> P |-- (weak_derives P Q && emp) * P.\nProof.\n  intros. cancel. apply andp_right. 2: cancel.\n  assert (HS: emp |-- TT) by entailer; sep_apply HS; clear HS.\n  apply derives_weak. assumption.\nQed.\n\nLemma sapi_ptr_val: forall p m n,\n    isptr p -> Int.min_signed <= n <= Int.max_signed ->\n    (force_val\n       (sem_add_ptr_int int_or_ptr_type Signed (offset_val (WORD_SIZE * m) p)\n                        (vint n))) = offset_val (WORD_SIZE * (m + n)) p.\nProof.\n  intros. rewrite sem_add_pi_ptr_special; [| easy | | easy].\n  - simpl. rewrite offset_offset_val. f_equal. rep_lia.\n  - rewrite isptr_offset_val. assumption.\nQed.\n\nLemma data_at_mfs_eq: forall g v i sh nv,\n    field_compatible int_or_ptr_type [] (offset_val (WORD_SIZE * i) nv) ->\n    0 <= i < Zlength (raw_fields (vlabel g v)) ->\n    data_at sh (tarray int_or_ptr_type i) (sublist 0 i (make_fields_vals g v)) nv *\n    field_at sh int_or_ptr_type [] (Znth i (make_fields_vals g v))\n             (offset_val (WORD_SIZE * i) nv) =\n    data_at sh (tarray int_or_ptr_type (i + 1))\n            (sublist 0 (i + 1) (make_fields_vals g v)) nv.\nProof.\n  intros. rewrite field_at_data_at. unfold field_address.\n  rewrite if_true by assumption. simpl nested_field_type.\n  simpl nested_field_offset. rewrite offset_offset_val.\n  replace (WORD_SIZE * i + 0) with (WORD_SIZE * i)%Z by lia.\n  rewrite <- (data_at_singleton_array_eq\n                sh int_or_ptr_type _ [Znth i (make_fields_vals g v)]) by reflexivity.\n  rewrite <- fields_eq_length in H0.\n  rewrite (data_at_tarray_value\n             sh (i + 1) i nv (sublist 0 (i + 1) (make_fields_vals g v))\n             (make_fields_vals g v) (sublist 0 i (make_fields_vals g v))\n             [Znth i (make_fields_vals g v)]).\n  - replace (i + 1 - i) with 1 by lia. reflexivity.\n  - lia.\n  - lia.\n  - autorewrite with sublist. reflexivity.\n  - reflexivity.\n  - rewrite sublist_one; [reflexivity | lia..].\nQed.\n\nLemma data_at__value_0_size: forall sh p,\n    data_at_ sh (tarray int_or_ptr_type 0) p |-- emp.\nProof. intros. rewrite data_at__eq. apply data_at_zero_array_inv; reflexivity. Qed.\n\nLemma data_at_minus1_address: forall sh v p,\n    data_at sh tuint v (offset_val (- WORD_SIZE) p) |--\n   !! (force_val (sem_add_ptr_int tuint Signed p (eval_unop Oneg tint (vint 1))) =\n       field_address tuint [] (offset_val (- WORD_SIZE) p)).\nProof.\n  intros. unfold eval_unop. simpl. rewrite WORD_SIZE_eq. entailer!.\n  unfold field_address. rewrite if_true by assumption. rewrite offset_offset_val.\n  simpl. reflexivity.\nQed.\n\nLemma body_forward: semax_body Vprog Gprog f_forward forward_spec.\nProof.\n  start_function.\n  destruct H as [? [? [? ?]]]. destruct H1 as [? [? [? [? ?]]]].\n  unfold limit_address, next_address, forward_p_address. destruct forward_p.\n  - unfold thread_info_rep. Intros.\n    assert (Zlength roots = Zlength (live_roots_indices f_info)) by\n        (rewrite <- (Zlength_map _ _ (flip Znth (ti_args t_info))), <- H4, Zlength_map; trivial).\n    pose proof (Znth_map _ (root2val g) _ H0). hnf in H0. rewrite H11 in H0.\n    rewrite H4, Znth_map in H12 by assumption. unfold flip in H12.\n    remember (Znth z roots) as root. rewrite <- H11 in H0.\n    pose proof (Znth_In _ _ H0).\n    rewrite <- Heqroot in H13. rewrite H11 in H0. unfold Inhabitant_val in H12.\n    assert (forall v, In (inr v) roots -> isptr (vertex_address g v)). { (**)\n      intros. destruct H5. unfold vertex_address. red in H15.\n      rewrite Forall_forall in H15.\n      rewrite (filter_sum_right_In_iff v roots) in H14. apply H15 in H14.\n      destruct H14. apply graph_has_gen_start_isptr in H14.\n      remember (gen_start g (vgeneration v)) as vv. destruct vv; try contradiction.\n      simpl. exact I. }\n    assert (is_pointer_or_integer (root2val g root)). {\n      destruct root as [[? | ?] | ?]; simpl; auto.\n      - destruct g0. simpl. exact I.\n      - specialize (H14 _ H13). apply isptr_is_pointer_or_integer. assumption. }\n    assert (0 <= Znth z (live_roots_indices f_info) < MAX_ARGS) by\n        (apply (fi_index_range f_info), Znth_In; assumption).\n    forward; rewrite H12. 1: entailer!.\n    assert_PROP (valid_int_or_ptr (root2val g root)). {\n      gather_SEP (graph_rep _) (outlier_rep _).\n      sep_apply (root_valid_int_or_ptr _ _ _ _ H13 H5). entailer!. }\n    forward_call (root2val g root).\n    remember (graph_rep g * heap_rest_rep (ti_heap t_info) * outlier_rep outlier)\n      as P. pose proof (graph_and_heap_rest_data_at_ _ _ _ H7 H).\n    unfold generation_data_at_ in H18. remember (gen_start g from) as fp.\n    remember (nth_sh g from) as fsh. remember (gen_size t_info from) as gn.\n    remember (WORD_SIZE * gn)%Z as fn.\n    assert (P |-- (weak_derives P (memory_block fsh fn fp * TT) && emp) * P). {\n      apply weak_derives_strong. subst. sep_apply H18.\n      rewrite data_at__memory_block.\n      rewrite sizeof_tarray_int_or_ptr; [Intros; cancel | unfold gen_size].\n      destruct (total_space_tight_range (nth_space t_info from)). assumption. }\n    destruct root as [[? | ?] | ?]; simpl root2val.\n    + unfold odd_Z2val. forward_if.\n      1: exfalso; apply H20'; reflexivity.\n      forward. Exists g t_info roots.\n      entailer!.\n      * simpl; split3; try rewrite <- Heqroot; [easy..|].\n        split3; [constructor | easy | apply tir_id].\n      * unfold thread_info_rep. entailer!.\n    + unfold GC_Pointer2val. destruct g0. forward_if.\n      2: exfalso; apply Int.one_not_zero in H20; assumption.\n      forward_call (Vptr b i).\n      gather_SEP (graph_rep _) (heap_rest_rep _) (outlier_rep _).\n      rewrite <- HeqP. destruct H5.\n      replace_SEP 0 ((weak_derives P (memory_block fsh fn fp * TT) && emp) * P) by\n          (entailer; assumption). clear H19. Intros. simpl root2val in *.\n      assert (P |-- (weak_derives P (valid_pointer (Vptr b i) * TT) && emp) * P). {\n        subst. cancel. apply andp_right. 2: cancel.\n        assert (HS: emp |-- TT) by entailer; sep_apply HS; clear HS.\n        apply derives_weak.\n        sep_apply (roots_outlier_rep_valid_pointer _ _ _ H13 H5).\n        simpl GC_Pointer2val. cancel. }\n      replace_SEP 1 ((weak_derives P (valid_pointer (Vptr b i) * TT) && emp) * P) by\n          (entailer; assumption). Intros. clear H19.\n      forward_call (fsh, fp, fn, (Vptr b i), P). Intros v. destruct v.\n      * rewrite HeqP. Intros.\n        gather_SEP (graph_rep g) (heap_rest_rep _).\n        sep_apply H18. rewrite Heqfn in v.\n        sep_apply (roots_outlier_rep_single_rep _ _ _ H13 H5). Intros.\n        gather_SEP (single_outlier_rep _) (data_at_ _ _ _).\n        change (Vptr b i) with (GC_Pointer2val (GCPtr b i)) in v.\n        pose proof (generation_share_writable (nth_gen g from)).\n        change (generation_sh (nth_gen g from)) with (nth_sh g from) in H19.\n        rewrite <- Heqfsh in H19. unfold generation_data_at_.\n        sep_apply (single_outlier_rep_memory_block_FF (GCPtr b i) fp gn fsh H19 v).\n        assert_PROP False by entailer!. contradiction.\n      * forward_if. 1: exfalso; apply H19'; reflexivity.\n        forward. Exists g t_info roots.\n        entailer!.\n        -- split3; [| |split3]; simpl; try rewrite <- Heqroot;\n             [easy.. | constructor | hnf; intuition | apply tir_id].\n        -- unfold thread_info_rep. entailer!.\n    + specialize (H14 _ H13). destruct (vertex_address g v) eqn:? ; try contradiction.\n      forward_if. 2: exfalso; apply Int.one_not_zero in H20; assumption.\n      clear H20 H20'. simpl in H15, H17. forward_call (Vptr b i).\n      rewrite <- Heqv0 in *.\n      gather_SEP (graph_rep _) (heap_rest_rep _) (outlier_rep _).\n      rewrite <- HeqP.\n      replace_SEP 0 ((weak_derives P (memory_block fsh fn fp * TT) && emp) * P) by\n          (entailer; assumption). clear H19. Intros. assert (graph_has_v g v). {\n        destruct H5. red in H19. rewrite Forall_forall in H19. apply H19.\n        rewrite <- filter_sum_right_In_iff. assumption. }\n      assert (P |-- (weak_derives P (valid_pointer (Vptr b i) * TT) && emp) * P). {\n        apply weak_derives_strong. subst. sep_apply (graph_rep_vertex_rep g v H19).\n        Intros shh. unfold vertex_rep, vertex_at. remember (make_fields_vals g v).\n        sep_apply (data_at_valid_ptr shh (tarray int_or_ptr_type (Zlength l)) l\n                                     (vertex_address g v)).\n        - apply readable_nonidentity, writable_readable_share. assumption.\n        - subst l. simpl. rewrite fields_eq_length.\n          rewrite Z.max_r; pose proof (raw_fields_range (vlabel g v)); lia.\n        - rewrite Heqv0. cancel.\n      }\n      replace_SEP 1 (weak_derives P (valid_pointer (Vptr b i) * TT) && emp * P)\n        by (entailer; assumption). clear H20. Intros. rewrite <- Heqv0 in *.\n      forward_call (fsh, fp, fn, (vertex_address g v), P). Intros vv. rewrite HeqP.\n      sep_apply (graph_and_heap_rest_v_in_range_iff _ _ _ _ H H7 H19). Intros.\n      rewrite <- Heqfp, <- Heqgn, <- Heqfn in H20. destruct vv.\n      * Intros. rewrite H20 in v0. clear H20. forward_if.\n        2: exfalso; inversion H20. freeze [1; 2; 3; 4; 5; 6] FR.\n        clear H20 H20'. localize [vertex_rep (nth_sh g (vgeneration v)) g v].\n        unfold vertex_rep, vertex_at. Intros. rewrite v0.\n        assert (readable_share (nth_sh g from)) by\n            (unfold nth_sh; apply writable_readable, generation_share_writable).\n        sep_apply (data_at_minus1_address (nth_sh g from) (Z2val (make_header g v))\n                                          (vertex_address g v)).\n        Intros. forward. clear H21.\n        gather_SEP (data_at _ tuint _ _) (data_at _ _ _ _).\n        replace_SEP 0 (vertex_rep (nth_sh g (vgeneration v)) g v) by\n            (unfold vertex_rep, vertex_at; entailer!).\n        unlocalize [graph_rep g]. 1: apply (graph_vertex_ramif_stable _ _ H19).\n        forward_if; rewrite make_header_int_rep_mark_iff in H21.\n        -- localize [vertex_rep (nth_sh g (vgeneration v)) g v].\n           rewrite v0. unfold vertex_rep, vertex_at. Intros.\n           unfold make_fields_vals at 2. rewrite H21.\n           assert (0 <= 0 < Zlength (make_fields_vals g v)). {\n             split. 1: lia. rewrite fields_eq_length.\n             apply (proj1 (raw_fields_range (vlabel g v))). }\n           assert (is_pointer_or_integer\n                     (vertex_address g (copied_vertex (vlabel g v)))). {\n             apply isptr_is_pointer_or_integer. unfold vertex_address.\n             rewrite isptr_offset_val.\n             apply graph_has_gen_start_isptr, H9; assumption. }\n           forward. rewrite Znth_0_cons.\n           gather_SEP (data_at _ tuint _ _) (data_at _ _ _ _).\n           replace_SEP 0 (vertex_rep (nth_sh g (vgeneration v)) g v). {\n             unfold vertex_rep, vertex_at. unfold make_fields_vals at 3.\n             rewrite H21. entailer!. }\n           unlocalize [graph_rep g]. 1: apply (graph_vertex_ramif_stable _ _ H19).\n           thaw FR. forward.\n           Exists g (upd_thread_info_arg\n                       t_info\n                       (Znth z (live_roots_indices f_info))\n                       (vertex_address g (copied_vertex (vlabel g v))) H16)\n                  (upd_bunch z f_info roots (inr (copied_vertex (vlabel g v)))).\n           unfold thread_info_rep. entailer!. 2: simpl; entailer!. simpl.\n           split; split; [|split; [|split] | |split]; auto.\n           ++ now apply upd_fun_thread_arg_compatible.\n           ++ specialize (H9 _ H19 H21). destruct H9 as [? _].\n              now apply upd_roots_compatible.\n           ++ rewrite <- Heqroot, H21.\n              now rewrite if_true by reflexivity.\n           ++ rewrite <- Heqroot. apply fr_v_in_forwarded; [reflexivity | assumption].\n           ++ easy.\n        -- forward. thaw FR. freeze [0; 1; 2; 3; 4; 5] FR.\n           apply not_true_is_false in H21. rewrite make_header_Wosize by assumption.\n           assert (0 <= Z.of_nat to < 12). {\n             clear -H H8. destruct H as [_ [_ ?]]. red in H8.\n             pose proof (spaces_size (ti_heap t_info)).\n             rewrite Zlength_correct in H0. rep_lia. } unfold heap_struct_rep.\n           destruct (gt_gs_compatible _ _ H _ H8) as [? [? ?]].\n           rewrite nth_space_Znth in *.\n           remember (Znth (Z.of_nat to) (spaces (ti_heap t_info))) as sp_to.\n           assert (isptr (space_start sp_to)) by (rewrite <- H23; apply start_isptr).\n           remember (map space_tri (spaces (ti_heap t_info))) as l.\n           assert (@Znth (val * (val * val)) (Vundef, (Vundef, Vundef))\n                         (Z.of_nat to) l = space_tri sp_to). {\n             subst l sp_to. rewrite Znth_map by (rewrite spaces_size; rep_lia).\n             reflexivity. }\n           forward; rewrite H27; unfold space_tri. 1: entailer!.\n           forward. simpl sem_binary_operation'.\n           rewrite sapi_ptr_val; [|assumption | rep_lia].\n           Opaque Znth. forward. Transparent Znth.\n           assert (Hr: Int.min_signed <= Zlength (raw_fields (vlabel g v)) <=\n                       Int.max_signed). {\n             pose proof (raw_fields_range (vlabel g v)). destruct H28. split.\n             1: rep_lia. transitivity (two_power_nat 22). 1: lia.\n             compute; intro s; inversion s. }\n           rewrite sapi_ptr_val by assumption. rewrite H27. unfold space_tri.\n           rewrite <- Z.add_assoc.\n           replace (1 + Zlength (raw_fields (vlabel g v))) with (vertex_size g v) by\n               (unfold vertex_size; lia). thaw FR. freeze [0; 2; 3; 4; 5; 6] FR.\n           assert (Hi : 0 <= Z.of_nat to < Zlength (spaces (ti_heap t_info))) by\n               (rewrite spaces_size; rep_lia).\n           assert (Hh: has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info)))\n                                 (vertex_size g v)). {\n             red. split. 1: pose proof (svs_gt_one g v); lia.\n             transitivity (unmarked_gen_size g (vgeneration v)).\n             - apply single_unmarked_le; assumption.\n             - red in H1. unfold rest_gen_size in H1. subst from.\n               rewrite nth_space_Znth in H1. assumption. }\n           assert (Hn: space_start (Znth (Z.of_nat to) (spaces (ti_heap t_info))) <>\n                       nullval). {\n             rewrite <- Heqsp_to. destruct (space_start sp_to); try contradiction.\n             intro Hn. inversion Hn. }\n           rewrite (heap_rest_rep_cut\n                      (ti_heap t_info) (Z.of_nat to) (vertex_size g v) Hi Hh Hn).\n           rewrite <- Heqsp_to. thaw FR.\n           gather_SEP (data_at _ thread_info_type _ _)\n                      (data_at _ heap_type _ _)\n                      (heap_rest_rep _).\n           replace_SEP 0 (thread_info_rep\n                            sh (cut_thread_info t_info _ _ Hi Hh) ti). {\n             entailer. unfold thread_info_rep. simpl ti_heap. simpl ti_heap_p. cancel.\n             simpl spaces. rewrite <- upd_Znth_map. unfold cut_space.\n             unfold space_tri at 3. simpl. unfold heap_struct_rep. cancel. }\n           sep_apply (graph_vertex_ramif_stable _ _ H19). Intros.\n           freeze [1; 2; 3; 4; 5] FR. rewrite v0.\n           remember (nth_sh g from) as shv.\n           assert (writable_share (space_sh sp_to)) by\n               (rewrite <- H24; apply generation_share_writable).\n           remember (space_sh sp_to) as sht.\n           rewrite (data_at__tarray_value _ _ 1). 2: unfold vertex_size; rep_lia.\n           Intros.\n           remember (offset_val (WORD_SIZE * used_space sp_to) (space_start sp_to)).\n           rewrite (data_at__int_or_ptr_tuint sht v1).\n           assert_PROP\n             (force_val (sem_add_ptr_int\n                           tuint Signed\n                           (offset_val (WORD_SIZE * (used_space sp_to + 1))\n                                       (space_start sp_to))\n                           (eval_unop Oneg tint (vint 1))) =\n              field_address tuint [] v1). {\n             subst v1. rewrite WORD_SIZE_eq. entailer!. simpl. rewrite neg_repr.\n             rewrite sem_add_pi_ptr_special'; auto. simpl. unfold field_address.\n             rewrite if_true by assumption. simpl. rewrite !offset_offset_val.\n             f_equal. lia. }\n           forward. sep_apply (field_at_data_at_cancel\n                                 sht tuint (Z2val (make_header g v)) v1). clear H29.\n           subst v1. rewrite offset_offset_val.\n           replace (vertex_size g v - 1) with (Zlength (raw_fields (vlabel g v)))\n             by (unfold vertex_size; lia).\n           replace (WORD_SIZE * used_space sp_to + WORD_SIZE * 1) with\n               (WORD_SIZE * (used_space sp_to + 1))%Z by rep_lia.\n           remember (offset_val (WORD_SIZE * (used_space sp_to + 1))\n                                (space_start sp_to)) as nv.\n           thaw FR. freeze [0; 1; 2; 3; 4; 5] FR. rename i into j.\n           remember (Zlength (raw_fields (vlabel g v))) as n.\n           assert (isptr nv) by (subst nv; rewrite isptr_offset_val; assumption).\n           remember (field_address thread_info_type\n                                   [ArraySubsc (Znth z (live_roots_indices f_info));\n                                    StructField _args] ti) as p_addr.\n           remember (field_address heap_type\n                                   [StructField _next; ArraySubsc (Z.of_nat to);\n                                    StructField _spaces] (ti_heap_p t_info)) as n_addr.\n           forward_for_simple_bound\n             n\n             (EX i: Z,\n              PROP ( )\n              LOCAL (temp _new nv;\n                     temp _sz (vint n);\n                     temp _v (vertex_address g v);\n                     temp _from_start fp;\n                     temp _from_limit (offset_val fn fp);\n                     temp _next n_addr;\n                     temp _p p_addr;\n                     temp _depth (vint depth))\n              SEP (vertex_rep shv g v;\n                   data_at sht (tarray int_or_ptr_type i)\n                           (sublist 0 i (make_fields_vals g v)) nv;\n                   data_at_ sht (tarray int_or_ptr_type (n - i))\n                            (offset_val (WORD_SIZE * i) nv); FRZL FR))%assert.\n           ++ rewrite sublist_nil. replace (n - 0) with n by lia.\n              replace (WORD_SIZE * 0)%Z with 0 by lia.\n              rewrite isptr_offset_val_zero by assumption.\n              rewrite data_at_zero_array_eq;\n                [|reflexivity | assumption | reflexivity]. entailer!.\n           ++ unfold vertex_rep, vertex_at. Intros.\n              rewrite fields_eq_length, <- Heqn. forward.\n              ** entailer!. pose proof (mfv_all_is_ptr_or_int _ _ H9 H10 H19).\n                 rewrite Forall_forall in H45. apply H45, Znth_In.\n                 rewrite fields_eq_length. assumption.\n              ** rewrite (data_at__tarray_value _ _ 1) by lia. Intros.\n                 rewrite data_at__singleton_array_eq.\n                 assert_PROP\n                   (field_compatible int_or_ptr_type []\n                                     (offset_val (WORD_SIZE * i) nv)) by\n                     (sep_apply (data_at__local_facts\n                                   sht int_or_ptr_type\n                                   (offset_val (WORD_SIZE * i) nv)); entailer!).\n                 assert_PROP\n                   (force_val (sem_add_ptr_int int_or_ptr_type\n                                               Signed nv (vint i)) =\n                    field_address int_or_ptr_type []\n                                  (offset_val (WORD_SIZE * i) nv)). {\n                   unfold field_address. rewrite if_true by assumption.\n                   clear. entailer!. }\n                 gather_SEP (data_at _ tuint _ _) (data_at _ _ _ _).\n                 replace_SEP 0 (vertex_rep shv g v) by\n                     (unfold vertex_rep, vertex_at;\n                      rewrite fields_eq_length; entailer!). forward.\n                 rewrite offset_offset_val.\n                 replace (n - i - 1) with (n - (i + 1)) by lia.\n                 replace (WORD_SIZE * i + WORD_SIZE * 1) with\n                     (WORD_SIZE * (i + 1))%Z by rep_lia.\n                 gather_SEP (data_at sht _ _ nv) (field_at _ _ _ _ _).\n                 rewrite data_at_mfs_eq. 2: assumption.\n                 2: subst n; assumption. entailer!.\n           ++ thaw FR. rewrite v0, <- Heqshv.\n              gather_SEP (vertex_rep _ _ _) (_ -* _).\n              replace_SEP 0 (graph_rep g) by (entailer!; apply wand_frame_elim).\n              rewrite sublist_all by (rewrite fields_eq_length; lia).\n              replace_SEP 2 emp. {\n                replace (n - n) with 0 by lia. clear. entailer.\n                apply data_at__value_0_size. }\n              assert (nv = vertex_address g (new_copied_v g to)). {\n                subst nv. unfold vertex_address. unfold new_copied_v. simpl. f_equal.\n                - unfold vertex_offset. simpl. rewrite H25. reflexivity.\n                - unfold gen_start. rewrite if_true by assumption.\n                  rewrite H23. reflexivity. }\n              gather_SEP (data_at sht _ _ _) (emp) (data_at sht tuint _ _).\n              replace_SEP\n                0 (vertex_at (nth_sh g to)\n                             (vertex_address g (new_copied_v g to))\n                             (make_header g v) (make_fields_vals g v)). {\n                normalize. rewrite <- H24.\n                change (generation_sh (nth_gen g to)) with (nth_sh g to).\n                rewrite <- fields_eq_length in Heqn.\n                replace (offset_val (WORD_SIZE * used_space sp_to) (space_start sp_to))\n                  with (offset_val (- WORD_SIZE) nv) by\n                    (rewrite Heqnv; rewrite offset_offset_val; f_equal; rep_lia).\n                rewrite <- H30. unfold vertex_at; entailer!. }\n              gather_SEP (vertex_at _ _ _ _) (graph_rep _).\n              rewrite (copied_v_derives_new_g g v to) by assumption.\n              freeze [1; 2; 3; 4] FR. remember (lgraph_add_copied_v g v to) as g'.\n              assert (vertex_address g' v = vertex_address g v) by\n                  (subst g'; apply lacv_vertex_address_old; assumption).\n              assert (vertex_address g' (new_copied_v g to) =\n                      vertex_address g (new_copied_v g to)) by\n                  (subst g'; apply lacv_vertex_address_new; assumption).\n              rewrite <- H31. rewrite <- H32 in H30.\n              assert (writable_share (nth_sh g' (vgeneration v))) by\n                  (unfold nth_sh; apply generation_share_writable).\n              assert (graph_has_v g' (new_copied_v g to)) by\n                  (subst g'; apply lacv_graph_has_v_new; assumption).\n              sep_apply (graph_rep_valid_int_or_ptr _ _ H34). Intros.\n              rewrite <- H30 in H35. assert (graph_has_v g' v) by\n                  (subst g'; apply lacv_graph_has_v_old; assumption).\n              remember (nth_sh g' (vgeneration v)) as sh'.\n              sep_apply (graph_vertex_lmc_ramif g' v (new_copied_v g to) H36).\n              rewrite <- Heqsh'. Intros. freeze [1; 2] FR1.\n              unfold vertex_rep, vertex_at. Intros.\n              sep_apply (data_at_minus1_address\n                           sh' (Z2val (make_header g' v)) (vertex_address g' v)).\n              Intros. forward. clear H37.\n              sep_apply (field_at_data_at_cancel\n                           sh' tuint (vint 0)\n                           (offset_val (- WORD_SIZE) (vertex_address g' v))).\n              forward_call (nv). remember (make_fields_vals g' v) as l'.\n              assert (0 < Zlength l'). {\n                subst l'. rewrite fields_eq_length.\n                apply (proj1 (raw_fields_range (vlabel g' v))). }\n              rewrite data_at_tarray_value_split_1 by assumption. Intros.\n              assert_PROP (force_val (sem_add_ptr_int int_or_ptr_type Signed\n                                                      (vertex_address g' v) (vint 0)) =\n                           field_address int_or_ptr_type [] (vertex_address g' v)). {\n                clear. entailer!. unfold field_address. rewrite if_true by assumption.\n                simpl. rewrite isptr_offset_val_zero. 1: reflexivity.\n                destruct H7. assumption. } forward. clear H38.\n              sep_apply (field_at_data_at_cancel\n                           sh' int_or_ptr_type nv (vertex_address g' v)).\n              gather_SEP\n                (data_at _ tuint (vint 0) _)\n                (data_at _ int_or_ptr_type nv _)\n                (data_at _ _ _ _).\n              rewrite H30. subst l'.\n              rewrite <- lmc_vertex_rep_eq.\n              thaw FR1.\n              gather_SEP (vertex_rep _ _ _) (_ -* _).\n              sep_apply\n                (wand_frame_elim\n                   (vertex_rep sh' (lgraph_mark_copied g' v (new_copied_v g to)) v)\n                   (graph_rep (lgraph_mark_copied g' v (new_copied_v g to)))).\n              rewrite <- (lmc_vertex_address g' v (new_copied_v g to)) in *. subst g'.\n              change (lgraph_mark_copied\n                        (lgraph_add_copied_v g v to) v (new_copied_v g to))\n                with (lgraph_copy_v g v to) in *.\n              remember (lgraph_copy_v g v to) as g'. rewrite <- H30 in *. thaw FR.\n              forward_call (nv). subst p_addr.\n              remember (cut_thread_info t_info (Z.of_nat to) (vertex_size g v) Hi Hh)\n                as t_info'. unfold thread_info_rep. Intros. forward.\n              remember (Znth z (live_roots_indices f_info)) as lz.\n              gather_SEP\n                (data_at sh thread_info_type _ ti)\n                (heap_struct_rep sh _ _)\n                (heap_rest_rep _ ).\n              replace_SEP 0 (thread_info_rep\n                               sh (update_thread_info_arg t_info' lz nv H16) ti). {\n                unfold thread_info_rep. simpl heap_head. simpl ti_heap_p.\n                simpl ti_args. simpl ti_heap. clear Heqt_info'. entailer!. }\n              remember (update_thread_info_arg t_info' lz nv H16) as t. subst t_info'.\n              rename t into t_info'. rewrite H30 in H32.\n              assert (forward_relation from to 0 (inl (inr v)) g g') by\n                  (subst g'; constructor; assumption).\n              assert (forward_condition g' t_info' from to). {\n                subst g' t_info' from. apply lcv_forward_condition; try assumption.\n                red. intuition. }\n              remember (upd_bunch z f_info roots (inr (new_copied_v g to))) as roots'.\n              assert (super_compatible (g', t_info', roots') f_info outlier). {\n                subst g' t_info' roots' lz. rewrite H30, H32.\n                apply lcv_super_compatible; try assumption. red. intuition. }\n              assert (thread_info_relation t_info t_info'). {\n                subst t_info'. split; [|split]; [reflexivity| |]; intros m.\n                - rewrite utiacti_gen_size. reflexivity.\n                - rewrite utiacti_space_start. reflexivity. }\n              forward_if.\n              ** destruct H41 as [? [? ?]]. replace fp with (gen_start g' from) by\n                     (subst fp g'; apply lcv_gen_start; assumption).\n                 replace (offset_val fn (gen_start g' from)) with\n                     (limit_address g' t_info' from) by\n                     (subst fn gn; rewrite H43; reflexivity).\n                 replace n_addr with (next_address t_info' to) by\n                     (subst n_addr; rewrite H41; reflexivity).\n                 forward_for_simple_bound\n                   n\n                   (EX i: Z, EX g3: LGraph, EX t_info3: thread_info,\n                    PROP (super_compatible (g3, t_info3, roots') f_info outlier;\n                          forward_loop\n                            from to (Z.to_nat (depth - 1))\n                            (sublist 0 i (vertex_pos_pairs g' (new_copied_v g to)))\n                            g' g3;\n                          forward_condition g3 t_info3 from to;\n                          thread_info_relation t_info' t_info3)\n                    LOCAL (temp _new nv;\n                           temp _sz (vint n);\n                           temp _from_start (gen_start g3 from);\n                           temp _from_limit (limit_address g3 t_info3 from);\n                           temp _next (next_address t_info3 to);\n                           temp _depth (vint depth))\n                    SEP (all_string_constants rsh gv;\n                         fun_info_rep rsh f_info fi;\n                         outlier_rep outlier;\n                         graph_rep g3;\n                         thread_info_rep sh t_info3 ti))%assert.\n                 --- Exists g' t_info'. autorewrite with sublist.\n                     assert (forward_loop from to (Z.to_nat (depth - 1)) [] g' g') by\n                         constructor. unfold thread_info_relation. entailer!.\n                 --- change (Tpointer tvoid {| attr_volatile := false;\n                                               attr_alignas := Some 2%N |})\n                       with (int_or_ptr_type). Intros.\n                     assert (graph_has_gen g' to) by\n                         (rewrite Heqg', <- lcv_graph_has_gen; assumption).\n                     assert (graph_has_v g' (new_copied_v g to)) by\n                         (rewrite Heqg'; apply lcv_graph_has_v_new; assumption).\n                     forward_call (rsh, sh, gv, fi, ti, g3, t_info3, f_info, roots',\n                                   outlier, from, to, depth - 1,\n                                   (@inr Z _ (new_copied_v g to, i))).\n                     +++ apply prop_right. simpl. rewrite sub_repr, H30.\n                         do 4 f_equal. rewrite sem_add_pi_ptr_special.\n                         *** simpl. f_equal. erewrite fl_vertex_address; eauto.\n                             subst g'. apply graph_has_v_in_closure. assumption.\n                         *** subst n. clear -H45 Hr. easy.\n                         *** rewrite <- H30. assumption.\n                         *** rep_lia.\n                     +++ do 3 (split; [assumption |]). split.\n                         *** simpl. split; [|split; [|split]]; auto.\n                             ---- destruct H39 as [_ [_ [? _]]].\n                                  apply (fl_graph_has_v _ _ _ _ _ _ H39 H47 _ H51).\n                             ---- erewrite <- fl_raw_fields; eauto. subst g'.\n                                  unfold lgraph_copy_v. subst n.\n                                  rewrite <- lmc_raw_fields, lacv_vlabel_new.\n                                  assumption.\n                             ---- erewrite <- fl_raw_mark; eauto. subst g' from.\n                                  rewrite lcv_vlabel_new; assumption.\n                         *** split; [assumption|]. split; [lia | assumption].\n                     +++ Intros vret. destruct vret as [[g4 t_info4] roots4].\n                         simpl fst in *. simpl snd in *. Exists g4 t_info4.\n                         simpl in H53. subst roots4.\n                         assert (gen_start g3 from = gen_start g4 from). {\n                           eapply fr_gen_start; eauto.\n                           erewrite <- fl_graph_has_gen; eauto. } rewrite H53.\n                         assert (limit_address g3 t_info3 from =\n                                 limit_address g4 t_info4 from). {\n                           unfold limit_address. f_equal. 2: assumption. f_equal.\n                           destruct H56 as [? [? _]]. rewrite H57. reflexivity. }\n                         rewrite H57.\n                         assert (next_address t_info3 to = next_address t_info4 to). {\n                           unfold next_address. f_equal. destruct H56. assumption. }\n                         rewrite H58. clear H53 H57 H58.\n                         assert (thread_info_relation t_info' t_info4) by\n                             (apply tir_trans with t_info3; assumption).\n                         assert (forward_loop\n                                   from to (Z.to_nat (depth - 1))\n                                   (sublist 0 (i + 1)\n                                            (vertex_pos_pairs g' (new_copied_v g to)))\n                                   g' g4). {\n                           eapply forward_loop_add_tail_vpp; eauto. subst n g' from.\n                           rewrite lcv_vlabel_new; assumption. }\n                         entailer!.\n                 --- Intros g3 t_info3.\n                     assert (thread_info_relation t_info t_info3) by\n                         (apply tir_trans with t_info';\n                          [split; [|split]|]; assumption).\n                     rewrite sublist_all in H46. clear Heqt.\n                     2: { rewrite Z.le_lteq. right. subst n g' from.\n                          rewrite vpp_Zlength, lcv_vlabel_new; auto. }\n                     Opaque super_compatible.\n                     Exists g3 t_info3 roots'. entailer!. simpl.\n                     rewrite <- Heqroot, H21, if_true by reflexivity. split; auto.\n                     replace (Z.to_nat depth) with (S (Z.to_nat (depth - 1))) by\n                         (rewrite <- Z2Nat.inj_succ; [f_equal|]; lia).\n                     constructor; easy.\n                     Transparent super_compatible.\n              ** assert (depth = 0) by lia. subst depth. clear H42.\n                 clear Heqnv. forward.\n                 remember (cut_thread_info\n                             t_info (Z.of_nat to) (vertex_size g v) Hi Hh).\n                 Exists (lgraph_copy_v g v to) (update_thread_info_arg t lz nv H16)\n                        (upd_bunch z f_info roots (inr (new_copied_v g to))).\n                 entailer!. simpl; rewrite <- Heqroot.\n                 rewrite if_true by reflexivity; rewrite H21; easy.\n      * forward_if. 1: exfalso; apply H21'; reflexivity.\n        rewrite H20 in n. forward.\n        Exists g t_info roots. entailer!; simpl.\n        -- rewrite <- Heqroot, if_false by assumption.\n           split3; [| |simpl root2forward; constructor]; try easy.\n           now constructor.\n        -- unfold thread_info_rep. entailer!.\n  (* p is Vtype * Z, ie located in graph *)\n  - destruct p as [v n]. destruct H0 as [? [? [? ?]]]. freeze [0; 1; 2; 4] FR.\n    localize [vertex_rep (nth_sh g (vgeneration v)) g v].\n    unfold vertex_rep, vertex_at. Intros.\n    assert_PROP (offset_val (WORD_SIZE * n) (vertex_address g v) =\n                 field_address (tarray int_or_ptr_type\n                                       (Zlength (make_fields_vals g v)))\n                               [ArraySubsc n] (vertex_address g v)). {\n      entailer!. unfold field_address. rewrite if_true; [simpl; f_equal|].\n      clear -H20 H11; rewrite <- fields_eq_length in H11.\n      unfold field_compatible in *; simpl in *; intuition.\n    }\n    assert (readable_share (nth_sh g (vgeneration v))) by\n      apply writable_readable, generation_share_writable.\n    assert (is_pointer_or_integer (Znth n (make_fields_vals g v))). {\n      pose proof (mfv_all_is_ptr_or_int g v H9 H10 H0). rewrite Forall_forall in H16.\n      apply H16, Znth_In. rewrite fields_eq_length. assumption. } forward.\n    gather_SEP (data_at _ tuint _ _) (data_at _ _ _ _).\n    replace_SEP 0 (vertex_rep (nth_sh g (vgeneration v)) g v).\n    1: unfold vertex_rep, vertex_at; entailer!.\n    unlocalize [graph_rep g]. 1: apply graph_vertex_ramif_stable; assumption. thaw FR.\n    unfold make_fields_vals.\n    rewrite H12, Znth_map; [|rewrite make_fields_eq_length; assumption].\n    assert_PROP (valid_int_or_ptr (field2val g (Znth n (make_fields g v)))). {\n      destruct (Znth n (make_fields g v)) eqn:?; [destruct s|].\n      - unfold field2val; unfold odd_Z2val.\n        replace (2 * z + 1) with (z + z + 1) by lia.\n        entailer!. apply valid_int_or_ptr_ii1.\n      - unfold field2val, outlier_rep.\n        apply in_gcptr_outlier with (gcptr:= g0) (outlier:=outlier) (n:=n) in H0;\n          try assumption.\n        apply (in_map single_outlier_rep outlier g0) in H0.\n        replace_SEP 3 (single_outlier_rep g0). {\n          clear -H0.\n          apply (list_in_map_inv single_outlier_rep) in H0; destruct H0 as [? [? ?]].\n          rewrite H.\n          apply (in_map single_outlier_rep) in H0.\n          destruct (log_normalize.fold_right_andp\n                     (map single_outlier_rep outlier)\n                     (single_outlier_rep x) H0).\n          rewrite H1. entailer!; now apply andp_left1.\n        }\n        sep_apply (single_outlier_rep_valid_int_or_ptr g0); entailer!.\n      - unfold field2val.\n        unfold no_dangling_dst in H10.\n        apply H10 with (e:=e) in H0.\n        1: sep_apply (graph_rep_valid_int_or_ptr g (dst g e) H0); entailer!.\n        unfold get_edges; rewrite <- filter_sum_right_In_iff, <- Heqf.\n        now apply Znth_In; rewrite make_fields_eq_length. }\n    forward_call (field2val g (Znth n (make_fields g v))).\n    remember (graph_rep g * heap_rest_rep (ti_heap t_info) * outlier_rep outlier) as P.\n    pose proof (graph_and_heap_rest_data_at_ _ _ _ H7 H).\n    unfold generation_data_at_ in H18. remember (gen_start g from) as fp.\n    remember (nth_sh g from) as fsh. remember (gen_size t_info from) as gn.\n    remember (WORD_SIZE * gn)%Z as fn.\n    assert (P |-- (weak_derives P (memory_block fsh fn fp * TT) && emp) * P). {\n      apply weak_derives_strong. subst. sep_apply H18.\n      rewrite data_at__memory_block.\n      rewrite sizeof_tarray_int_or_ptr; [Intros; cancel | unfold gen_size].\n      destruct (total_space_tight_range (nth_space t_info from)). assumption. }\n    destruct (Znth n (make_fields g v)) eqn:? ; [destruct s|].\n    (* Z + GC_Pointer + EType *)\n    + (* Z *)\n      unfold field2val, odd_Z2val. forward_if.\n      1: exfalso; apply H20'; reflexivity.\n      forward. Exists g t_info roots. entailer!. split.\n      * easy.\n      * unfold forward_condition, thread_info_relation.\n        simpl. rewrite Heqf, H12. simpl. constructor; [constructor|easy].\n    + (* GC_Pointer *)\n      destruct g0. unfold field2val, GC_Pointer2val. forward_if.\n      2: exfalso; apply Int.one_not_zero; assumption.\n      forward_call (Vptr b i). 1: exact I.\n      unfold thread_info_rep; Intros.\n      gather_SEP (graph_rep _) (heap_rest_rep _) (outlier_rep _).\n      rewrite <- HeqP. destruct H5.\n      replace_SEP 0 ((weak_derives P (memory_block fsh fn fp * TT) && emp) * P) by\n          (entailer; assumption). clear H19. Intros.\n      assert (P |-- (weak_derives P (valid_pointer (Vptr b i) * TT) && emp) * P). {\n        subst; cancel; apply andp_right; [|cancel].\n        assert (HS: emp |-- TT) by entailer; sep_apply HS; clear HS.\n        apply derives_weak. assert (In (GCPtr b i) outlier) by\n            (eapply in_gcptr_outlier; eauto).\n        sep_apply (outlier_rep_valid_pointer outlier (GCPtr b i) H19).\n        simpl GC_Pointer2val. cancel. }\n      replace_SEP 1 ((weak_derives P (valid_pointer (Vptr b i) * TT) && emp) * P) by\n          (entailer; assumption). Intros. clear H19.\n      forward_call (fsh, fp, fn, (Vptr b i), P).\n      Intros vret. destruct vret. (* is_from? *)\n      * (* yes *)\n        rewrite HeqP. Intros.\n        gather_SEP (graph_rep _) (heap_rest_rep _).\n        sep_apply H18. rewrite Heqfn in v0.\n        pose proof in_gcptr_outlier g (GCPtr b i) outlier n v H0 H6 H11 Heqf.\n        sep_apply (outlier_rep_single_rep outlier (GCPtr b i)).\n        Intros.\n        gather_SEP (data_at_ _ _ _) (single_outlier_rep _).\n        change (Vptr b i) with (GC_Pointer2val (GCPtr b i)) in v0.\n        pose proof (generation_share_writable (nth_gen g from)).\n        change (generation_sh (nth_gen g from)) with (nth_sh g from) in H22.\n        rewrite <- Heqfsh in H22. unfold generation_data_at_.\n        sep_apply (single_outlier_rep_memory_block_FF (GCPtr b i) fp gn fsh H22 v0).\n        assert_PROP False by entailer!. contradiction.\n      * (* no *)\n        forward_if. 1: exfalso; apply H19'; reflexivity.\n        forward. Exists g t_info roots. entailer!.\n        -- split3.\n           ++ unfold roots_compatible. easy.\n           ++ simpl. rewrite Heqf, H12. simpl. constructor.\n           ++ easy.\n        -- unfold thread_info_rep. entailer!.\n    + (* EType *)\n      unfold field2val. remember (dst g e) as v'.\n      assert (isptr (vertex_address g v')). { (**)\n        unfold vertex_address; unfold offset_val.\n        remember (vgeneration v') as n'.\n        assert (graph_has_v g v'). {\n          unfold no_dangling_dst in H10.\n          subst. clear -H0 H10 H11 e Heqf.\n          apply (H10 v H0).\n          unfold get_edges;\n          rewrite <- filter_sum_right_In_iff, <- Heqf; apply Znth_In.\n          now rewrite make_fields_eq_length.\n        }\n        destruct H20. rewrite <- Heqn' in H20.\n        pose proof (graph_has_gen_start_isptr g n' H20).\n        destruct (gen_start g n'); try contradiction; auto.       }\n      destruct (vertex_address g v') eqn:?; try contradiction.\n      forward_if. 2: exfalso; apply Int.one_not_zero in H21; assumption.\n      clear H21 H21'. forward_call (Vptr b i).\n      unfold thread_info_rep; Intros.\n      gather_SEP (graph_rep _) (heap_rest_rep _) (outlier_rep _).\n      rewrite <- HeqP.\n      replace_SEP 0\n                  ((weak_derives P (memory_block fsh fn fp * TT) && emp) * P) by\n          (entailer; assumption).\n      clear H19. Intros. assert (graph_has_v g v'). { (**)\n        rewrite Heqv'.\n        unfold no_dangling_dst in H10.\n        clear -H10 H0 e Heqf H11. apply (H10 v H0).\n        unfold get_edges.\n        rewrite <- filter_sum_right_In_iff.\n        rewrite <- Heqf.\n        apply Znth_In.\n        rewrite make_fields_eq_length; assumption.\n      }\n      assert (P |-- (weak_derives P (valid_pointer (Vptr b i) * TT) && emp) * P). {\n        apply weak_derives_strong. subst.\n        remember (dst g e) as v'.\n        sep_apply (graph_rep_vertex_rep g v' H19).\n        Intros shh. unfold vertex_rep, vertex_at. rewrite Heqv0.\n        sep_apply (data_at_valid_ptr\n                     shh (tarray int_or_ptr_type (Zlength (make_fields_vals g v')))\n                     (make_fields_vals g v') (Vptr b i)).\n        - apply readable_nonidentity, writable_readable_share; assumption.\n        - simpl. rewrite fields_eq_length.\n          pose proof (proj1 (raw_fields_range (vlabel g v'))). rewrite Z.max_r; lia.\n        - cancel.\n      }\n      replace_SEP 1 (weak_derives P (valid_pointer (Vptr b i) * TT) && emp * P)\n        by entailer!. clear H21. Intros.\n      forward_call (fsh, fp, fn, (Vptr b i), P).\n      (* is_from *)\n      Intros vv. rewrite HeqP.\n      sep_apply (graph_and_heap_rest_v_in_range_iff _ _ _ _ H H7 H19).\n      Intros. rewrite <- Heqfp, <- Heqgn, <- Heqfn, Heqv0 in H21. destruct vv.\n      * (* yes, is_from *)\n        rewrite H21 in v0. clear H21. forward_if.\n        2: exfalso; inversion H21.\n        freeze [1; 2; 3; 4; 5; 6] FR.\n        clear H21 H21'. localize [vertex_rep (nth_sh g (vgeneration v')) g v'].\n        unfold vertex_rep, vertex_at. Intros. rewrite v0.\n        assert (readable_share (nth_sh g from)) by\n            (unfold nth_sh; apply writable_readable, generation_share_writable).\n        rewrite <- Heqv0.\n        sep_apply (data_at_minus1_address\n                     (nth_sh g from) (Z2val (make_header g v')) (vertex_address g v')).\n        Intros. forward. clear H22.\n        gather_SEP (data_at _ tuint _ _) (data_at _ _ _ _).\n        replace_SEP 0 (vertex_rep (nth_sh g (vgeneration v')) g v') by\n            (unfold vertex_rep, vertex_at; entailer!).\n        unlocalize [graph_rep g]. 1: apply (graph_vertex_ramif_stable _ _ H19).\n        forward_if; rewrite make_header_int_rep_mark_iff in H22.\n        -- (* yes, already forwarded *)\n          localize [vertex_rep (nth_sh g (vgeneration v')) g v'].\n          change (Tpointer tvoid {| attr_volatile := false;\n                                    attr_alignas := Some 2%N |}) with int_or_ptr_type.\n          rewrite v0. unfold vertex_rep, vertex_at. Intros.\n          unfold make_fields_vals at 2. rewrite H22.\n          assert (0 <= 0 < Zlength (make_fields_vals g v')). {\n             split. 1: lia. rewrite fields_eq_length.\n             apply (proj1 (raw_fields_range (vlabel g v'))).\n          }\n          assert (is_pointer_or_integer\n                    (vertex_address g (copied_vertex (vlabel g v')))). {\n            apply isptr_is_pointer_or_integer. unfold vertex_address.\n            rewrite isptr_offset_val.\n            apply graph_has_gen_start_isptr, H9; assumption. }\n          forward. rewrite Znth_0_cons.\n          gather_SEP (data_at _ tuint _ _) (data_at _ _ _ _).\n          replace_SEP 0 (vertex_rep (nth_sh g (vgeneration v')) g v'). {\n            unfold vertex_rep, vertex_at. unfold make_fields_vals at 3.\n            rewrite H22. entailer!. }\n          unlocalize [graph_rep g]. 1: apply (graph_vertex_ramif_stable _ _ H19).\n          localize [vertex_rep (nth_sh g (vgeneration v)) g v].\n          unfold vertex_rep, vertex_at. Intros.\n          assert (writable_share (nth_sh g (vgeneration v))) by\n               (unfold nth_sh; apply generation_share_writable).\n          forward.\n          sep_apply (field_at_data_at_cancel\n                       (nth_sh g (vgeneration v))\n                       (tarray int_or_ptr_type (Zlength (make_fields_vals g v)))\n                       (upd_Znth n (make_fields_vals g v)\n                       (vertex_address g (copied_vertex (vlabel g v'))))\n                       (vertex_address g v)).\n          gather_SEP (data_at _ tuint _ _ ) (data_at _ _ _ _).\n          remember (copied_vertex (vlabel g v')).\n          remember (labeledgraph_gen_dst g e v1) as g'.\n          replace_SEP 0 (vertex_rep (nth_sh g' (vgeneration v)) g' v).\n          1: { unfold vertex_rep, vertex_at.\n               replace (nth_sh g' (vgeneration v)) with\n                   (nth_sh g (vgeneration v)) by (subst g'; reflexivity).\n               replace (Zlength (make_fields_vals g' v)) with\n                   (Zlength (make_fields_vals g v)) by\n                   (subst g'; repeat rewrite fields_eq_length;\n                    apply lgd_raw_fld_length_eq).\n               rewrite (lgd_mfv_change_in_one_spot g v e v1 n);\n                 [|rewrite make_fields_eq_length| | ]; try assumption.\n               entailer!. }\n          subst g'; subst v1.\n          unlocalize [graph_rep (labeledgraph_gen_dst g e\n                                                      (copied_vertex (vlabel g v')))].\n          1: apply (graph_vertex_lgd_ramif g v e (copied_vertex (vlabel g v')) n);\n            try (rewrite make_fields_eq_length); assumption.\n          Exists (labeledgraph_gen_dst g e (copied_vertex (vlabel g (dst g e))))\n                 t_info roots.\n          entailer!.\n          2: unfold thread_info_rep; thaw FR; entailer!.\n          pose proof (lgd_no_dangling_dst_copied_vert g e (dst g e) H9 H19 H22 H10).\n          split; [|split; [|split; [|split]]]; try reflexivity.\n          ++ now constructor.\n          ++ simpl forward_p2forward_t.\n             rewrite H12, Heqf. simpl. now constructor.\n          ++ now constructor.\n          ++ easy.\n        -- (* not yet forwarded *)\n          forward. thaw FR.  freeze [0; 1; 2; 3; 4; 5] FR.\n           apply not_true_is_false in H22. rewrite make_header_Wosize by assumption.\n           assert (0 <= Z.of_nat to < 12). {\n             clear -H H8. destruct H as [_ [_ ?]]. red in H8.\n             pose proof (spaces_size (ti_heap t_info)).\n             rewrite Zlength_correct in H0. rep_lia. } unfold heap_struct_rep.\n           destruct (gt_gs_compatible _ _ H _ H8) as [? [? ?]].\n           rewrite nth_space_Znth in *.\n           remember (Znth (Z.of_nat to) (spaces (ti_heap t_info))) as sp_to.\n           assert (isptr (space_start sp_to)) by (rewrite <- H24; apply start_isptr).\n           remember (map space_tri (spaces (ti_heap t_info))).\n           assert (@Znth (val * (val * val)) (Vundef, (Vundef, Vundef))\n                         (Z.of_nat to) l = space_tri sp_to). {\n             subst l sp_to. rewrite Znth_map by (rewrite spaces_size; rep_lia).\n             reflexivity. }\n           forward; rewrite H28; unfold space_tri. 1: entailer!.\n           forward. simpl sem_binary_operation'.\n           rewrite sapi_ptr_val; [| assumption | rep_lia].\n           Opaque Znth.  forward. Transparent Znth.\n           assert (Hr: Int.min_signed <= Zlength (raw_fields (vlabel g v')) <=\n                       Int.max_signed). {\n             pose proof (raw_fields_range (vlabel g v')). destruct H29. split.\n             - rep_lia.\n             - transitivity (two_power_nat 22). 1: lia.\n               compute; intro s; inversion s. }\n           rewrite sapi_ptr_val; [|easy|easy].\n           rewrite H28. unfold space_tri.\n           rewrite <- Z.add_assoc.\n           replace (1 + Zlength (raw_fields (vlabel g v'))) with (vertex_size g v') by\n               (unfold vertex_size; lia). thaw FR. freeze [0; 2; 3; 4; 5; 6] FR.\n           assert (Hi : 0 <= Z.of_nat to < Zlength (spaces (ti_heap t_info))) by\n               (rewrite spaces_size; rep_lia).\n           assert (Hh: has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info)))\n                                 (vertex_size g v')). {\n             red. split. 1: pose proof (svs_gt_one g v'); lia.\n             transitivity (unmarked_gen_size g (vgeneration v')).\n             - apply single_unmarked_le; assumption.\n             - red in H1. unfold rest_gen_size in H1. subst from.\n               rewrite nth_space_Znth in H1. assumption. }\n           assert (Hn: space_start (Znth (Z.of_nat to) (spaces (ti_heap t_info))) <>\n                       nullval). {\n             rewrite <- Heqsp_to. destruct (space_start sp_to); try contradiction.\n             intro Hn. inversion Hn. }\n           rewrite (heap_rest_rep_cut\n                      (ti_heap t_info) (Z.of_nat to) (vertex_size g v') Hi Hh Hn).\n           rewrite <- Heqsp_to. thaw FR.\n           gather_SEP (data_at _ _ _ ti) (data_at _ _ _ _) (heap_rest_rep _).\n           replace_SEP 0 (thread_info_rep\n                            sh (cut_thread_info t_info _ _ Hi Hh) ti). {\n             entailer. unfold thread_info_rep. simpl ti_heap. simpl ti_heap_p. cancel.\n             simpl spaces. rewrite <- upd_Znth_map. unfold cut_space.\n             unfold space_tri at 3. simpl. unfold heap_struct_rep. cancel. }\n           sep_apply (graph_vertex_ramif_stable _ _ H19). Intros.\n           freeze [1; 2; 3; 4; 5] FR. rewrite v0.\n           remember (nth_sh g from) as shv.\n           assert (writable_share (space_sh sp_to)) by\n               (rewrite <- H25; apply generation_share_writable).\n           remember (space_sh sp_to) as sht.\n           rewrite (data_at__tarray_value _ _ 1). 2: unfold vertex_size; rep_lia.\n           Intros.\n           remember (offset_val (WORD_SIZE * used_space sp_to) (space_start sp_to)).\n           rewrite (data_at__int_or_ptr_tuint sht v1).\n           assert_PROP\n             (force_val (sem_add_ptr_int\n                           tuint Signed\n                           (offset_val (WORD_SIZE * (used_space sp_to + 1))\n                                       (space_start sp_to))\n                           (eval_unop Oneg tint (vint 1))) =\n              field_address tuint [] v1). {\n             subst v1. rewrite WORD_SIZE_eq. entailer!. unfold field_address.\n             simpl. rewrite neg_repr. rewrite sem_add_pi_ptr_special'; auto.\n             rewrite if_true by assumption. simpl. rewrite !offset_offset_val.\n             f_equal. lia. }\n           forward. sep_apply (field_at_data_at_cancel\n                                 sht tuint (Z2val (make_header g v')) v1). clear H30.\n           subst v1. rewrite offset_offset_val.\n           replace (vertex_size g v' - 1) with (Zlength (raw_fields (vlabel g v')))\n             by (unfold vertex_size; lia).\n           replace (WORD_SIZE * used_space sp_to + WORD_SIZE * 1) with\n               (WORD_SIZE * (used_space sp_to + 1))%Z by rep_lia.\n           remember (offset_val (WORD_SIZE * (used_space sp_to + 1))\n                                (space_start sp_to)) as nv.\n           thaw FR. freeze [0; 1; 2; 3; 4; 5] FR. rename i into j. \n           remember (Zlength (raw_fields (vlabel g v'))) as n'.\n           assert (isptr nv) by (subst nv; rewrite isptr_offset_val; assumption).\n           remember (field_address heap_type\n                                   [StructField _next; ArraySubsc (Z.of_nat to);\n                                    StructField _spaces] (ti_heap_p t_info)) as n_addr.\n           forward_for_simple_bound\n             n'\n             (EX i: Z,\n              PROP ( )\n              LOCAL (temp _new nv;\n                     temp _sz (vint n');\n                     temp _v (vertex_address g v');\n                     temp _from_start fp;\n                     temp _from_limit (offset_val fn fp);\n                     temp _next n_addr;\n                     temp _p (offset_val (WORD_SIZE * n) (vertex_address g v));\n                     temp _depth (vint depth))\n              SEP (vertex_rep shv g v';\n                   data_at sht (tarray int_or_ptr_type i)\n                           (sublist 0 i (make_fields_vals g v')) nv;\n                   data_at_ sht (tarray int_or_ptr_type (n' - i))\n                            (offset_val (WORD_SIZE * i) nv); FRZL FR))%assert.\n           ++ rewrite sublist_nil. replace (n' - 0) with n' by lia.\n              replace (WORD_SIZE * 0)%Z with 0 by lia.\n              rewrite isptr_offset_val_zero by assumption.\n              rewrite data_at_zero_array_eq; [entailer! | easy..].\n           ++ unfold vertex_rep, vertex_at. Intros.\n              rewrite fields_eq_length, <- Heqn'. forward.\n              ** entailer!. pose proof (mfv_all_is_ptr_or_int _ _ H9 H10 H19).\n                 rewrite Forall_forall in H46. apply H46, Znth_In.\n                 rewrite fields_eq_length. assumption.\n              ** rewrite (data_at__tarray_value _ _ 1) by lia. Intros.\n                 rewrite data_at__singleton_array_eq.\n                 assert_PROP\n                   (field_compatible int_or_ptr_type []\n                                     (offset_val (WORD_SIZE * i) nv)) by\n                     (sep_apply (data_at__local_facts\n                                   sht int_or_ptr_type\n                                   (offset_val (WORD_SIZE * i) nv)); entailer!).\n                 assert_PROP\n                   (force_val (sem_add_ptr_int int_or_ptr_type\n                                               Signed nv (vint i)) =\n                    field_address int_or_ptr_type []\n                                  (offset_val (WORD_SIZE * i) nv)). {\n                   unfold field_address. rewrite if_true by assumption.\n                   clear. entailer!. }\n                 gather_SEP (data_at _ tuint _ _) (data_at _ (_ n') _ _).\n                 replace_SEP 0 (vertex_rep shv g v') by\n                     (unfold vertex_rep, vertex_at;\n                      rewrite fields_eq_length; entailer!). forward.\n                 rewrite offset_offset_val.\n                 replace (n' - i - 1) with (n' - (i + 1)) by lia.\n                 replace (WORD_SIZE * i + WORD_SIZE * 1) with\n                     (WORD_SIZE * (i + 1))%Z by rep_lia.\n                 gather_SEP (data_at _ _ _ nv) (field_at _ _ _ _ _).\n                 rewrite data_at_mfs_eq;\n                                   [entailer! | assumption | subst n'; assumption].\n           ++ thaw FR. rewrite v0, <- Heqshv.\n              gather_SEP (vertex_rep _ _ _) (_ -* _).\n              replace_SEP 0 (graph_rep g) by (entailer!; apply wand_frame_elim).\n              rewrite sublist_all by (rewrite fields_eq_length; lia).\n              replace_SEP 2 emp. {\n                replace (n' - n') with 0 by lia. clear. entailer.\n                apply data_at__value_0_size. }\n              assert (nv = vertex_address g (new_copied_v g to)). {\n                subst nv. unfold vertex_address. unfold new_copied_v. simpl. f_equal.\n                - unfold vertex_offset. simpl. rewrite H26. reflexivity.\n                - unfold gen_start. rewrite if_true by assumption.\n                  rewrite H24. reflexivity. }\n              gather_SEP (data_at sht _ _ nv) (emp) (data_at sht tuint _ _).\n              replace_SEP\n                0 (vertex_at (nth_sh g to)\n                             (vertex_address g (new_copied_v g to))\n                             (make_header g v') (make_fields_vals g v')). {\n                normalize. rewrite <- H25.\n                change (generation_sh (nth_gen g to)) with (nth_sh g to).\n                rewrite <- fields_eq_length in Heqn'.\n                replace (offset_val (WORD_SIZE * used_space sp_to) (space_start sp_to))\n                  with (offset_val (- WORD_SIZE) nv) by\n                    (rewrite Heqnv; rewrite offset_offset_val; f_equal; rep_lia).\n                rewrite <- H31. unfold vertex_at; entailer!. }\n              gather_SEP (vertex_at _ _ _ _) (graph_rep _).\n              rewrite (copied_v_derives_new_g g v' to) by assumption.\n              freeze [1; 2; 3; 4] FR. remember (lgraph_add_copied_v g v' to) as g'.\n              assert (vertex_address g' v' = vertex_address g v') by\n                  (subst g'; apply lacv_vertex_address_old; assumption).\n              assert (vertex_address g' (new_copied_v g to) =\n                      vertex_address g (new_copied_v g to)) by\n                  (subst g'; apply lacv_vertex_address_new; assumption).\n              rewrite <- H32. rewrite <- H33 in H31.\n              assert (writable_share (nth_sh g' (vgeneration v'))) by\n                  (unfold nth_sh; apply generation_share_writable).\n              assert (graph_has_v g' (new_copied_v g to)) by\n                  (subst g'; apply lacv_graph_has_v_new; assumption).\n              sep_apply (graph_rep_valid_int_or_ptr _ _ H35). Intros.\n              rewrite <- H31 in H36. assert (graph_has_v g' v') by\n                  (subst g'; apply lacv_graph_has_v_old; assumption).\n              remember (nth_sh g' (vgeneration v')) as sh'.\n              sep_apply (graph_vertex_lmc_ramif g' v' (new_copied_v g to) H37).\n              rewrite <- Heqsh'. Intros. freeze [1; 2] FR1.\n              unfold vertex_rep, vertex_at. Intros.\n              sep_apply (data_at_minus1_address\n                           sh' (Z2val (make_header g' v')) (vertex_address g' v')).\n              Intros. forward. clear H38.\n              sep_apply (field_at_data_at_cancel\n                           sh' tuint (vint 0)\n                           (offset_val (- WORD_SIZE) (vertex_address g' v'))).\n              forward_call (nv). remember (make_fields_vals g' v') as l'.\n              assert (0 < Zlength l'). {\n                subst l'. rewrite fields_eq_length.\n                apply (proj1 (raw_fields_range (vlabel g' v'))). }\n              rewrite data_at_tarray_value_split_1 by assumption. Intros.\n              assert_PROP (force_val (sem_add_ptr_int int_or_ptr_type Signed\n                                                      (vertex_address g' v') (vint 0))\n                           =\n                           field_address int_or_ptr_type [] (vertex_address g' v')). {\n                clear. entailer!. unfold field_address. rewrite if_true by assumption.\n                simpl. rewrite isptr_offset_val_zero. 1: reflexivity.\n                destruct H7. assumption. }\n              forward. clear H39.\n              sep_apply (field_at_data_at_cancel\n                           sh' int_or_ptr_type nv (vertex_address g' v')).\n              gather_SEP\n                (data_at _ tuint _ _)\n                (data_at _ int_or_ptr_type _ _)\n                (data_at _ (tarray _ _) _ _).\n              rewrite H31. subst l'.\n              rewrite <- lmc_vertex_rep_eq.\n              thaw FR1.\n              gather_SEP (vertex_rep _ _ _) (_ -* _).\n              sep_apply\n                (wand_frame_elim\n                   (vertex_rep sh' (lgraph_mark_copied g' v' (new_copied_v g to)) v')\n                   (graph_rep (lgraph_mark_copied g' v' (new_copied_v g to)))).\n              rewrite <- (lmc_vertex_address g' v' (new_copied_v g to)) in *. subst g'.\n              change (lgraph_mark_copied\n                        (lgraph_add_copied_v g v' to) v' (new_copied_v g to))\n                with (lgraph_copy_v g v' to) in *.\n              remember (lgraph_copy_v g v' to) as g'.\n\n              assert (vertex_address g' v' = vertex_address g v') by\n              (subst g'; apply lcv_vertex_address_old; assumption).\n              assert (vertex_address g' (new_copied_v g to) =\n                      vertex_address g (new_copied_v g to)) by\n                  (subst g'; apply lcv_vertex_address_new; assumption).\n              assert (writable_share (nth_sh g' (vgeneration v'))) by\n                  (unfold nth_sh; apply generation_share_writable).\n              assert (graph_has_v g' (new_copied_v g to)) by\n                  (subst g'; apply lcv_graph_has_v_new; assumption).\n              forward_call (nv).\n              rewrite <- H31 in *.\n              rewrite lacv_vertex_address;\n                [|apply graph_has_v_in_closure|]; try assumption.\n              rewrite <- H32.\n              rewrite <- (lcv_vertex_address g v' to v);\n                try rewrite <- (lcv_vertex_address g v' to v) in H14;\n                try apply graph_has_v_in_closure; try assumption.\n              rewrite (lcv_mfv_Zlen_eq g v v' to H8 H0) in H14. rewrite <- Heqg' in *.\n              remember (nth_sh g' (vgeneration v)) as shh.\n              remember (make_fields_vals g' v) as mfv.\n              remember (new_copied_v g to).\n              remember (labeledgraph_gen_dst g' e v1) as g1.\n              assert (0 <= n < Zlength (make_fields_vals g' v)) by\n                  (subst g'; rewrite fields_eq_length, <- lcv_raw_fields; assumption).\n              assert (Znth n (make_fields g' v) = inr e) by\n                  (subst g'; unfold make_fields in *;\n                   rewrite <- lcv_raw_fields; assumption).\n              assert (0 <= n < Zlength (make_fields g' v)) by\n                  (rewrite make_fields_eq_length;\n                   rewrite fields_eq_length in H43; assumption).\n              assert (graph_has_v g' v) by\n                  (subst g'; apply lcv_graph_has_v_old; assumption).\n              assert (v <> v') by\n                  (intro; subst v; clear -v0 H13; lia).\n              assert (raw_mark (vlabel g' v) = false) by\n                (subst g'; rewrite <- lcv_raw_mark; assumption).\n              assert (writable_share shh) by\n                  (rewrite Heqshh; unfold nth_sh; apply generation_share_writable).\n              localize [vertex_rep (nth_sh g' (vgeneration v)) g' v].\n              unfold vertex_rep, vertex_at. Intros.\n              rewrite Heqmfv in *; rewrite <- Heqshh.\n              forward.\n              rewrite H31.\n              sep_apply (field_at_data_at_cancel\n                           shh\n                           (tarray int_or_ptr_type (Zlength (make_fields_vals g' v)))\n                           (upd_Znth n (make_fields_vals g' v) (vertex_address g' v1))\n                           (vertex_address g' v)).\n              gather_SEP (data_at shh tuint _ _) (data_at shh _ _ _).\n              replace_SEP 0 (vertex_rep (nth_sh g1 (vgeneration v)) g1 v).\n              1: { unfold vertex_rep, vertex_at.\n                   replace (nth_sh g1 (vgeneration v)) with shh by\n                       (subst shh g1; reflexivity).\n                   replace (Zlength (make_fields_vals g1 v)) with\n                       (Zlength (make_fields_vals g' v)) by\n                       (subst g1; repeat rewrite fields_eq_length;\n                        apply lgd_raw_fld_length_eq).\n                   rewrite (lgd_mfv_change_in_one_spot g' v e v1 n);\n                     try assumption. entailer!. }\n              subst g1; subst v1.\n              unlocalize [graph_rep (labeledgraph_gen_dst g' e (new_copied_v g to))].\n              1: apply (graph_vertex_lgd_ramif g' v e (new_copied_v g to) n);\n                assumption.\n              remember (new_copied_v g to).\n              remember (labeledgraph_gen_dst g' e v1) as g1.\n              thaw FR.\n              remember (cut_thread_info t_info (Z.of_nat to) (vertex_size g v') Hi Hh)\n                as t_info'.\n              unfold thread_info_rep. Intros.\n              assert (0 <= 0 < Zlength (ti_args t_info')) by\n                  (rewrite arg_size; rep_lia).\n              gather_SEP\n                (data_at _ _ _ _)\n                (heap_struct_rep _ _ _)\n                (heap_rest_rep _).\n              replace_SEP 0 (thread_info_rep sh t_info' ti).\n              { unfold thread_info_rep. simpl heap_head. simpl ti_heap_p.\n                simpl ti_args. simpl ti_heap. entailer!. }\n              rewrite H31 in H33.\n                assert (forward_relation from to 0 (inr e) g g1) by\n                    (subst g1 g' v1 v'; constructor; assumption).\n                assert (In e (get_edges g v)). { (**)\n                  unfold get_edges.\n                  rewrite <- filter_sum_right_In_iff.\n                  rewrite <- Heqf.\n                  apply (Znth_In n (make_fields g v)).\n                  rewrite make_fields_eq_length. assumption.\n                }\n                assert (forward_condition g1 t_info' from to). {\n                  subst g1 g' t_info' from v'.\n                  apply lgd_forward_condition; try assumption.\n                  apply lcv_forward_condition_unchanged; try assumption.\n                  red. intuition. }\n                remember roots as roots'.\n                assert (super_compatible (g1, t_info', roots') f_info outlier). {\n\n                  subst g1 g' t_info' roots'.\n                  apply lgd_super_compatible, lcv_super_compatible_unchanged;\n                    try assumption.\n                  red; intuition. }\n              assert (thread_info_relation t_info t_info'). {\n                subst t_info'. split; [|split]; [reflexivity| |]; intros m.\n                - rewrite cti_gen_size. reflexivity.\n                - rewrite cti_space_start. reflexivity. }\n                forward_if.\n              ** destruct H55 as [? [? ?]]. replace fp with (gen_start g1 from) by\n                     (subst fp g1 g'; apply lcv_gen_start; assumption).\n                 replace (offset_val fn (gen_start g1 from)) with\n                     (limit_address g1 t_info' from) by\n                     (subst fn gn; rewrite H57; reflexivity).\n                 replace n_addr with (next_address t_info' to) by\n                     (subst n_addr; rewrite H55; reflexivity).\n                 forward_for_simple_bound\n                   n'\n                   (EX i: Z, EX g3: LGraph, EX t_info3: thread_info,\n                    PROP (super_compatible (g3, t_info3, roots') f_info outlier;\n                          forward_loop\n                            from to (Z.to_nat (depth - 1))\n                            (sublist 0 i (vertex_pos_pairs g1 (new_copied_v g to)))\n                            g1 g3;\n                          forward_condition g3 t_info3 from to;\n                          thread_info_relation t_info' t_info3)\n                    LOCAL (temp _new nv;\n                           temp _sz (vint n');\n                           temp _from_start (gen_start g3 from);\n                           temp _from_limit (limit_address g3 t_info3 from);\n                           temp _next (next_address t_info3 to);\n                           temp _depth (vint depth))\n                    SEP (all_string_constants rsh gv;\n                         fun_info_rep rsh f_info fi;\n                         outlier_rep outlier;\n                         graph_rep g3;\n                         thread_info_rep sh t_info3 ti))%assert.\n                 --- Exists g1 t_info'. autorewrite with sublist.\n                     assert (forward_loop from to (Z.to_nat (depth - 1)) [] g1 g1) by\n                         constructor. unfold thread_info_relation.\n                     destruct H54 as [? [? [? ?]]].\n                     entailer!. easy.\n                 --- change (Tpointer tvoid {| attr_volatile := false;\n                                               attr_alignas := Some 2%N |})\n                       with (int_or_ptr_type). Intros.\n                     assert (graph_has_gen g1 to) by\n                         (rewrite Heqg1, lgd_graph_has_gen; subst g';\n                          rewrite <- lcv_graph_has_gen; assumption).\n                     assert (graph_has_v g1 (new_copied_v g to)) by\n                       (subst g1; rewrite <- lgd_graph_has_v;\n                       rewrite Heqg'; apply lcv_graph_has_v_new; assumption).\n                     forward_call (rsh, sh, gv, fi, ti, g3, t_info3, f_info, roots',\n                                   outlier, from, to, depth - 1,\n                                   (@inr Z _ (new_copied_v g to, i))).\n                     +++ apply prop_right. simpl. rewrite sub_repr.\n                         do 4 f_equal. rewrite H31, sem_add_pi_ptr_special.\n                         *** simpl. f_equal.\n                             rewrite <- (lgd_vertex_address_eq g' e v1), <- Heqg1.\n                             subst v1. apply (fl_vertex_address _ _ _ _ _ _ H64 H61).\n                             apply graph_has_v_in_closure; assumption.\n                         *** subst n'. clear -H59 Hr. easy.\n                         *** rewrite <- H31. assumption.\n                         *** rep_lia.\n                     +++ do 3 (split; [assumption |]). split.\n                         *** simpl. split; [|split].\n                             ---- destruct H53 as [_ [_ [? _]]].\n                                  apply (fl_graph_has_v _ _ _ _ _ _ H64 H61 _ H65).\n                             ---- erewrite <- fl_raw_fields; eauto. subst g1.\n                                  unfold lgraph_copy_v. subst n'.\n                                  rewrite <- lgd_raw_fld_length_eq.\n                                  subst g'. rewrite lcv_vlabel_new.\n                                  assumption. rewrite v0. lia.\n                             ---- erewrite <- fl_raw_mark; eauto. subst g1 from.\n                                  rewrite <- lgd_raw_mark_eq. subst g'.\n                                  rewrite lcv_vlabel_new; try assumption.\n                                  split; try assumption. lia.\n                         *** split; [assumption|]. split; [lia | assumption].\n                     +++ Intros vret. destruct vret as [[g4 t_info4] roots4].\n                         simpl fst in *. simpl snd in *. Exists g4 t_info4.\n                         simpl in H67. subst roots4.\n                         assert (gen_start g3 from = gen_start g4 from). {\n                           eapply fr_gen_start; eauto.\n                           erewrite <- fl_graph_has_gen; eauto. } rewrite H67.\n                         assert (limit_address g3 t_info3 from =\n                                 limit_address g4 t_info4 from). {\n                           unfold limit_address. f_equal. 2: assumption. f_equal.\n                           destruct H70 as [? [? _]]. rewrite H71. reflexivity. }\n                         rewrite H71.\n                         assert (next_address t_info3 to = next_address t_info4 to). {\n                           unfold next_address. f_equal. destruct H70. assumption. }\n                         rewrite H72. clear H67 H71 H72.\n                         assert (thread_info_relation t_info' t_info4) by\n                             (apply tir_trans with t_info3; assumption).\n                         assert (forward_loop\n                                   from to (Z.to_nat (depth - 1))\n                                   (sublist 0 (i + 1)\n                                            (vertex_pos_pairs g1 (new_copied_v g to)))\n                                   g1 g4). {\n                            eapply forward_loop_add_tail_vpp; eauto. subst n' g1 from.\n                           rewrite <- lgd_raw_fld_length_eq. subst g'.\n                           rewrite lcv_vlabel_new; assumption. }\n                         entailer!.\n                 --- Intros g3 t_info3.\n                     assert (thread_info_relation t_info t_info3) by\n                         (apply tir_trans with t_info';\n                          [split; [| split]|]; assumption).\n                     rewrite sublist_all in H60.\n                     2: { rewrite Z.le_lteq. right. subst n' g1 from.\n                          rewrite vpp_Zlength,  <- lgd_raw_fld_length_eq.\n                          subst g'; rewrite lcv_vlabel_new; auto. }\n                     Opaque super_compatible. Exists g3 t_info3 roots.\n                     entailer!. simpl.\n                     replace (Z.to_nat depth) with (S (Z.to_nat (depth - 1))) by\n                         (rewrite <- Z2Nat.inj_succ; [f_equal|]; lia).\n                     rewrite Heqf, H12. simpl.\n                     constructor; [reflexivity | assumption..].\n                     Transparent super_compatible.\n              ** assert (depth = 0) by lia. subst depth. clear H56.\n                 deadvars!. clear Heqnv. forward.\n                 Exists g1 t_info' roots. entailer!. simpl. rewrite Heqf.\n                 simpl field2forward. rewrite H12. simpl. now constructor.\n      * forward_if. 1: exfalso; apply H22'; reflexivity.\n        rewrite H21 in n0. forward.\n        Exists g t_info roots. entailer!; simpl.\n        -- rewrite H12, Heqf. simpl. split; auto. split; [|split].\n           ++ constructor. auto.\n           ++ split; auto.\n           ++ apply tir_id.\n        -- unfold thread_info_rep. entailer!.\nQed.\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/CertiGC/verif_forward.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23104288922381275}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\nRequire Import Setoid.\nRequire Import ZArith.\nRequire Import Psatz.\n\n\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith. \n\nLocal Open Scope struct_scope.\n\nRequire Import FinProof.CommonProofs.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolClass.\nRequire Import depoolContract.SolidityNotations.\n\nRequire Import depoolContract.NewProofs.ProofHelpers.\nRequire Import depoolContract.DePoolFunc.\n\n(* Set Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100. *)\n\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\nRequire Import depoolContract.Lib.CommonCommon.\n\n(* Require Import MultiSigWallet.Proofs.tvmFunctionsProofs. *)\n\nImport DePoolSpec.LedgerClass.SolidityNotations. \n\nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope solidity_scope.\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\n\nRequire Import depoolContract.DePoolConsts.\nModule DePoolContract_Ф_completeRound (dc : DePoolConstsTypesSig XTypesSig StateMonadSig).\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig dc.\nModule ProofHelpers := ProofHelpers dc.\n\nImport dc.\nImport ProofHelpers.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\nOpaque Z.eqb Z.add Z.sub Z.div Z.mul hmapLookup hmapInsert Z.ltb Z.geb Z.leb Z.gtb Z.modulo deleteListPair.\n\n\nDefinition DePoolContract_Ф_completeRound_while1 (Л_maxQty Л_roundId: XInteger) : LedgerT (XBool # True) := \n         While  ( ↑17 D2! LocalState_ι_completeRound_Л_restParticipant ?> $ xInt0 ) do (\n                U0! Л_curGroup := ( ( ↑17 D2! LocalState_ι_completeRound_Л_restParticipant ) ?< ( $ Л_maxQty ) !|\n                                   ( ( (↑17 D2! LocalState_ι_completeRound_Л_msgQty) !+ $ xInt1 ) ?== $ DePool_ι_MAX_QTY_OF_OUT_ACTIONS ) ) ? \n             ( ↑17 D2! LocalState_ι_completeRound_Л_restParticipant ) :::  \n                 ( $ Л_maxQty ) ;\t\t                \n                ( ->sendMessage {||\n                contractMessage ::= {|| messageBounce ::= $xBoolFalse , messageFlag ::= $xInt1 ||} , \n                                contractFunction ::= DePoolContract_Ф_completeRoundF (!! $Л_roundId , $ Л_curGroup !!)\n                                ||}\t)  >>\n                ( ↑17 U1! LocalState_ι_completeRound_Л_restParticipant !-= $ Л_curGroup ) >>\n                continue! I\n        )  .\n\nDefinition DePoolContract_Ф_completeRound_while2 (Л_participantQty Л_roundId: XInteger) := \n         While  ( ↑17 D2! LocalState_ι_completeRound_Л_i ?< $ Л_participantQty ) do (\n                ( ->sendMessage {||\n                            contractMessage ::= {|| messageBounce ::= $xBoolFalse , messageFlag ::= $ xInt1 ||} , \n                            contractFunction ::= DePoolContract_Ф_completeRoundWithChunkF (!! $Л_roundId , $ DePool_ι_MAX_MSGS_PER_TR !!)\n                            ||}\t)  >>\n                    continue! I\t\t\n         ) .\n\nDefinition DePoolContract_Ф_completeRound' ( Л_roundId : XInteger64 )\n                                    ( Л_participantQty : XInteger32 ) \n                                    : LedgerT ( XErrorValue True XInteger ) := \nRequire2 {{ msg_sender () ?== tvm_address (),  $ Errors_ι_IS_NOT_DEPOOL }} ; \ntvm_accept () >> \nRequire2 {{ RoundsBase_Ф_isRound2 (! $ Л_roundId !) !| ↑12 D2! DePoolContract_ι_m_poolClosed , $ InternalErrors_ι_ERROR522 }} ; \nU0! Л_optRound := RoundsBase_Ф_fetchRound (! $ Л_roundId !) ; \nRequire2 {{ ($ Л_optRound) ->hasValue,  $ InternalErrors_ι_ERROR519 }} ; \nU0! Л_round := ($ Л_optRound) ->get ; \nRequire {{ ( ( $ Л_round ->> RoundsBase_ι_Round_ι_step ) ?== ( $ RoundsBase_ι_RoundStepP_ι_Completing ) ) , $ InternalErrors_ι_ERROR518 }} ; \n( ->sendMessage {||\n\t                contractMessage ::= {|| messageBounce ::= $xBoolFalse , messageFlag ::= $xInt1 ||} , \n\t\t\t           contractFunction ::= DePoolContract_Ф_completeRoundWithChunkF (!! $Л_roundId , $ xInt1 !!)\n\t\t\t\t\t||}\t) >> \ntvm_commit () >> \nU0! Л_outActionQty := ( ( $ Л_participantQty !+ ( $ DePool_ι_MAX_MSGS_PER_TR ) !- $ xInt1 ) !/ ( $ DePool_ι_MAX_MSGS_PER_TR ) ) ; \n(If ( $ Л_outActionQty ?> ( $ DePool_ι_MAX_QTY_OF_OUT_ACTIONS ) ) then  {\n\tU0! Л_maxQty := ( $ DePool_ι_MAX_QTY_OF_OUT_ACTIONS ) !* ($ DePool_ι_MAX_MSGS_PER_TR ) ; \n\t(↑17 U1! LocalState_ι_completeRound_Л_restParticipant := $ Л_participantQty) >> \n\n\t( ↑17 U1! LocalState_ι_completeRound_Л_msgQty := $ xInt0 ) >>\n        DePoolContract_Ф_completeRound_while1 Л_maxQty Л_roundId >> \n        $ I } \n        else {\n                ( ↑17 U1! LocalState_ι_completeRound_Л_i := $ xInt0 ) >>\n                DePoolContract_Ф_completeRound_while2 Л_participantQty Л_roundId >>  \n                $I\t\t\n        } ).\n\nOpaque DePoolContract_Ф_completeRound_while1 DePoolContract_Ф_completeRound_while2.\n\nLemma DePoolContract_Ф_completeRound'_exec : forall ( Л_roundId : XInteger64 ) \n                                                   ( Л_participantQty : XInteger32 ) \n                                                   (l: Ledger) , \n                                           \nlet req : bool := ( eval_state msg_sender l ) =? ( eval_state tvm_address  l )  in\nlet l_tvm_accept :=  exec_state ( ↓ tvm_accept ) l  in\nlet req1 : bool := (  ( eval_state ( ↓ RoundsBase_Ф_isRound2 Л_roundId ) l ) \n                      || ( eval_state ( ↑12 ε DePoolContract_ι_m_poolClosed ) l ) )%bool  in\nlet optRound := eval_state ( ↓ ( RoundsBase_Ф_fetchRound Л_roundId ) ) l_tvm_accept in\nlet req2 : bool :=  isSome optRound  in\nlet round := maybeGet optRound  in\nlet req3 : bool :=  eqb ( round ->> RoundsBase_ι_Round_ι_step ) RoundsBase_ι_RoundStepP_ι_Completing   in\n\nlet oldMessages := VMState_ι_messages ( Ledger_ι_VMState l_tvm_accept ) in\nlet newMessage  := {| contractAddress :=  0 ;\n                      contractFunction := DePoolContract_Ф_completeRoundWithChunkF Л_roundId 1 ;\n                      contractMessage := {| messageValue := default ;\n                                            messageFlag  := 1 ; \n                                            messageBounce := false\n                                            |} |} in \nlet l_message := {$ l_tvm_accept With ( VMState_ι_messages , newMessage :: oldMessages ) $} in  \nlet l_tvm_commit := exec_state ( ↓ tvm_commit ) l_message in\nlet MAX_MSGS_PER_TR := DePool_ι_MAX_MSGS_PER_TR in\nlet MAX_QTY_OF_OUT_ACTIONS := DePool_ι_MAX_QTY_OF_OUT_ACTIONS in\nlet outActionQty := (Л_participantQty + MAX_MSGS_PER_TR - 1) / MAX_MSGS_PER_TR in\n\nlet if1 : bool := outActionQty >? MAX_QTY_OF_OUT_ACTIONS in\nlet maxQty := MAX_QTY_OF_OUT_ACTIONS * MAX_MSGS_PER_TR in\n\nlet l1 := {$ l_tvm_commit With (LocalState_ι_completeRound_Л_restParticipant ,  Л_participantQty);\n                               (LocalState_ι_completeRound_Л_msgQty , 0) $} in\nlet l2 := {$ l_tvm_commit With (LocalState_ι_completeRound_Л_i , 0) $} in                               \n\nexec_state (DePoolContract_Ф_completeRound' Л_roundId Л_participantQty) l = \nif req then \n        if req1 then \n                if req2 then \n                        if req3 then \n                                if if1 then exec_state (DePoolContract_Ф_completeRound_while1 maxQty Л_roundId) l1 \n                                else exec_state (DePoolContract_Ф_completeRound_while2 Л_participantQty Л_roundId) l2\n                        else l_tvm_accept\n                else l_tvm_accept\n        else l_tvm_accept\nelse l.\nProof.\n        intros.\n        destructLedger l. \n        compute.\n        Time repeat destructIf_solve. \n        all: try destructFunction2 DePoolContract_Ф_completeRound_while1; auto. idtac.\n        all: try destructFunction2 DePoolContract_Ф_completeRound_while2; auto. \nQed. \n\nLemma DePoolContract_Ф_completeRound'_eval : forall ( Л_roundId : XInteger64 ) \n                                                   ( Л_participantQty : XInteger32 ) \n                                                   (l: Ledger) , \n                                           \nlet req : bool := ( eval_state msg_sender l ) =? ( eval_state tvm_address  l )  in\nlet l_tvm_accept :=  exec_state ( ↓ tvm_accept ) l  in\nlet req1 : bool := (  ( eval_state ( ↓ RoundsBase_Ф_isRound2 Л_roundId ) l ) \n                      || ( eval_state ( ↑12 ε DePoolContract_ι_m_poolClosed ) l ) )%bool  in\nlet optRound := eval_state ( ↓ ( RoundsBase_Ф_fetchRound Л_roundId ) ) l_tvm_accept in\nlet req2 : bool :=  isSome optRound  in\nlet round := maybeGet optRound  in\nlet req3 : bool :=  eqb ( round ->> RoundsBase_ι_Round_ι_step ) RoundsBase_ι_RoundStepP_ι_Completing   in\n\nlet oldMessages := VMState_ι_messages ( Ledger_ι_VMState l_tvm_accept ) in\nlet newMessage  := {| contractAddress :=  0 ;\n                      contractFunction := DePoolContract_Ф_completeRoundWithChunkF Л_roundId 1 ;\n                      contractMessage := {| messageValue := default ;\n                                            messageFlag  := 1 ; \n                                            messageBounce := false\n                                            |} |} in \nlet l_message := {$ l_tvm_accept With ( VMState_ι_messages , newMessage :: oldMessages ) $} in  \nlet l_tvm_commit := exec_state ( ↓ tvm_commit ) l_message in\nlet MAX_MSGS_PER_TR := DePool_ι_MAX_MSGS_PER_TR in\nlet MAX_QTY_OF_OUT_ACTIONS := DePool_ι_MAX_QTY_OF_OUT_ACTIONS in\nlet outActionQty := (Л_participantQty + MAX_MSGS_PER_TR - 1) / MAX_MSGS_PER_TR in\n\nlet if1 : bool := outActionQty >? MAX_QTY_OF_OUT_ACTIONS in\nlet maxQty := MAX_QTY_OF_OUT_ACTIONS * MAX_MSGS_PER_TR in\n\nlet l1 := {$ l_tvm_commit With (LocalState_ι_completeRound_Л_restParticipant ,  Л_participantQty);\n                               (LocalState_ι_completeRound_Л_msgQty , 0) $} in\nlet l2 := {$ l_tvm_commit With (LocalState_ι_completeRound_Л_i , 0) $} in                               \n\neval_state (DePoolContract_Ф_completeRound' Л_roundId Л_participantQty) l = \nif req then \n        if req1 then \n                if req2 then \n                        if req3 then Value I                              \n                        else Error InternalErrors_ι_ERROR518\n                else Error InternalErrors_ι_ERROR519\n        else Error InternalErrors_ι_ERROR522\nelse Error Errors_ι_IS_NOT_DEPOOL .\nProof.\n        intros.\n        destructLedger l. \n        compute.\n        Time repeat destructIf_solve. \n        all: try destructFunction2 DePoolContract_Ф_completeRound_while1; auto. idtac.\n        all: try destructFunction2 DePoolContract_Ф_completeRound_while2; auto. \nQed.\n\n\nEnd DePoolContract_Ф_completeRound.", "meta": {"author": "Pruvendo", "repo": "depool_contract", "sha": "6afe23011d62f65921ac2493df691ab888ffeb95", "save_path": "github-repos/coq/Pruvendo-depool_contract", "path": "github-repos/coq/Pruvendo-depool_contract/depool_contract-6afe23011d62f65921ac2493df691ab888ffeb95/src/NewProofs/DePoolContract_completeRound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.23101979396248626}}
{"text": "Require Import Common.exceptionMonad.\nRequire Import Common.AstCommon.\nRequire Import Common.certiClasses.\nRequire Import Common.certiClasses2.\nRequire Import Common.certiClasses3.\nRequire Import Coq.Unicode.Utf8.\nRequire Import SquiggleEq.tactics.\nRequire Import SquiggleEq.LibTactics.\nRequire Import Morphisms.\n\nClass MkApply (Term:Type) := mkApp : Term -> Term -> Term.\n\nClass CerticoqLinkableLanguage (Term:Type)\n  `{BigStepOpSem Term} `{GoodTerm Term} \n  `{QuestionHead Term} `{ObserveNthSubterm Term}\n  `{MkApply Term} \n:= \n{\n}.\n\nDefinition mkAppEx {Term:Type}  {mka: MkApply Term} (f:Term) (arg : exception Term):\n  exception Term:=\n  match arg with\n  | Ret arg => Ret (mkApp f arg)\n  | _ => arg\n  end.\n\nSection CompObsPreserving.\n\nContext (Src Dst: Type)\n  (* {SrcValue DstValue: Type} having a seperate type for values becomes awkward in this setup.\n     If really needed, one can always use sum types to combine the term and value types.*)\n          `{QuestionHead Src} `{ObserveNthSubterm Src}\n   `{QuestionHead Dst} `{ObserveNthSubterm Dst}\n   `{BigStepOpSem Src} `{BigStepOpSem Dst} `{GoodTerm Src}\n   `{CerticoqTranslation Src Dst}  `{MkApply Src}  `{MkApply Dst}.\n\n\nCoInductive compObsLeLink : Src -> Dst -> Prop :=\n| sameObsLink : forall (s : Src) (d : Dst),\n    (forall (o:Opt) (sv:Src),\n        s ⇓ sv\n        -> (exists (dv : Dst),\n              d ⇓ dv /\\\n              yesPreserved sv dv\n              /\\ (forall n:nat, liftLe compObsLeLink (observeNthSubterm n sv) (observeNthSubterm n dv))\n              /\\ (questionHead  Abs sv = true -> forall svArg, goodTerm svArg ->\n                   liftLe compObsLeLink\n                      (Some (mkApp sv svArg))\n                      (exception_option (mkAppEx dv (translate Src Dst o svArg))))\n          ))\n    -> compObsLeLink s d.\n\nInductive compObsLeLinkN : nat -> Src -> Dst -> Prop :=\n| sameObsLinkS : forall m (s : Src) (d : Dst),\n    (forall (o:Opt) (sv:Src),\n        s ⇓ sv\n        -> (exists (dv:Dst),\n              d ⇓ dv /\\\n              yesPreserved sv dv\n              /\\ (forall n:nat, liftLe (compObsLeLinkN m) (observeNthSubterm n sv) (observeNthSubterm n dv))\n              /\\ (questionHead  Abs sv = true -> forall svArg, goodTerm svArg ->\n                   liftLe (compObsLeLinkN m)\n                      (Some (mkApp sv svArg))\n                      (exception_option (mkAppEx dv (translate Src Dst o svArg))))\n          ))\n    -> compObsLeLinkN (S m) s d\n| sameObsLinkO : forall (s : Src) (d : Dst), compObsLeLinkN 0 s d.\n\n\n(** this part is generally easy and unconditional *)\nLemma fromCoInd s d:\n  compObsLeLink s d -> forall m, compObsLeLinkN m s d.\nProof using.\n  intros Hc m. revert Hc. revert d. revert s.\n  induction m as [ | m Hind]; intros ? ? Hc;\n    [ constructor; fail | ].\n  destruct Hc as [? ? Hc].\n  constructor.\n  intros o1 sv Hev. specialize (Hc o1 sv Hev).\n  destruct Hc as [dv Hc]. repnd.\n  exists dv. dands; eauto with certiclasses.\nQed.\n\nLemma toCoInd {dstDet: deterministicBigStep Dst}s d:\n  (forall m, compObsLeLinkN m s d) -> compObsLeLink s d.\nProof using.\n  revert d. revert s.\n  cofix toCoInd.\n  intros ? ? Hi.\n  constructor.\n  intros o ? Hev. pose proof Hi as Hib.\n  specialize (Hi 1); inversion Hi as [ ? ? ? Hc | ]; subst. clear Hi.\n  specialize (Hc o sv Hev).\n  destruct Hc as [dv Hc]. repnd.\n  exists dv.\n  dands; auto.\n  - clear Hc. intros n.\n    apply liftLeRimpl with (R1:= fun a b => forall m, compObsLeLinkN m a b); eauto.\n    \n    specialize (Hc2 n). invertsna Hc2 H0c;[ | constructor].\n    rename s0 into svn.\n    rename d0 into dvn.\n    constructor.\n    intros m.\n    specialize (Hib (S m)).\n    invertsna Hib Hib.\n    specialize (Hib o sv Hev).\n    destruct Hib as [dvv Hib]. repnd.\n    specialize (dstDet _ _ _ Hib0 Hc0). subst. clear Hib0 Hib.\n    specialize (Hib2 n).\n    rewrite <- H0c1, <- H0c0 in Hib2.\n    inverts Hib2. assumption.\n\n  - clear Hc2. intros Hq ? Hg.\n    specialize (Hc Hq _ Hg).\n    apply liftLeRimpl with (R1:= fun a b => forall m, compObsLeLinkN m a b); eauto.\n    invertsna Hc H0c.\n    constructor.\n    intros m.\n    specialize (Hib (S m)).\n    invertsna Hib Hib.\n    specialize (Hib o sv Hev).\n    destruct Hib as [dvv Hib]. repnd.\n    specialize (dstDet _ _ _ Hib0 Hc0). subst. clear Hib0 Hib2.\n    specialize (Hib Hq _ Hg).\n    rewrite  <- H0c0 in Hib.\n    inverts Hib. assumption.\nQed.\n        \nDefinition compObsPreservingLinkable :=\n   ∀ (o: Opt) (s:Src),\n    goodTerm s \n    -> liftLe compObsLeLink (Some s) (exception_option (translate Src Dst o s)).\n\nEnd CompObsPreserving.\n\nClass CerticoqLinkableTranslationCorrect {Src Dst : Type}\n  `{CerticoqLinkableLanguage Src} \n  `{CerticoqLinkableLanguage Dst}\n  `{CerticoqTranslation Src Dst}\n  := \n{\n  certiGoodPresLink : goodPreserving Src Dst;\n  obsePresLink : compObsPreservingLinkable Src Dst;\n}.\n\n\nGlobal Arguments CerticoqLinkableTranslationCorrect\n  {Src} {Dst} {H} {H0} {H1} {H2} {H3}  H4 {H5} {H6} {H7} {H8} {H9} H10 {H11}.\n\nNotation \"s ⊑ t\" := (compObsLeLink _ _ s t) (at level 65).\n\n\nSection ComposeLink.\nContext (Src Inter Dst : Type)\n        `{Ls: CerticoqLinkableLanguage Src}\n        `{Li: CerticoqLinkableLanguage Inter}\n        `{Ld: CerticoqLinkableLanguage Dst}\n  {t1 : CerticoqTranslation Src Inter}\n  {t2 : CerticoqTranslation Inter Dst}.\n\n\nLemma compObsLeLinkTransitive\n      {Hgpsi : goodPreserving Src Inter}\n      {Hgpid : goodPreserving Inter Dst}:\n   forall   (s : Src) (i : Inter) (d : Dst),\n  s ⊑ i\n  -> i ⊑ d \n  -> s ⊑ d.\nProof.\n  cofix compObsLeLinkTransitive.\n  intros ? ? ? Ha Hb.\n  inverts Ha as Hah.\n  inverts Hb as Hbh.\n  constructor; auto.\n  intros o ? Hevs.\n  destruct (Hah o _ Hevs) as [iv  Hci]. clear Hah.\n  destruct Hci as [Hevi Hci].\n  destruct Hci as [Hyesi Hsubi].\n  destruct (Hbh o _ Hevi) as [dv  Hcd]. clear Hbh.\n  destruct Hcd as [Hevd Hcd].\n  destruct Hcd as [Hyesd Hsubd].\n  exists dv. split;[ assumption|].\n  assert (forall (A B: Prop), A -> (A-> B) -> A/\\B) as Hp by (intros; tauto).\n  apply Hp;[|intros Hyessd; split]; clear Hp;\n    [eauto using (@yesPreservedTransitive Src Inter Dst) | | ];[|].\n- clear Hyesi Hyesd.\n  intros n.\n  apply proj1 in Hsubi.\n  apply proj1 in Hsubd.\n  specialize (Hsubi n).\n  specialize (Hsubd n).\n  destruct Hsubi;[| constructor ].\n  inversion Hsubd. subst. clear Hsubd.\n  constructor. eauto.\n- intros Habs.\n  apply proj2 in Hsubi.\n  apply proj2 in Hsubd.\n  intros ? Hgsv.\n  specialize (Hsubi Habs svArg Hgsv).\n  unfold yesPreserved in Hyesi.\n  specialize (Hyesi Abs).\n  rewrite Habs in Hyesi.\n  simpl in Hyesi.\n  specialize (Hsubd Hyesi).\n  inverts Hsubi as Hsub Heq.\n  unfold goodPreserving in *. \n  eapply Hgpsi with (o:=o) in Hgsv.\n  unfold composeTranslation, translate in *.\n  destruct (t1 o svArg) as [| ivArg];[inverts Heq|].\n  simpl in *. inverts Heq.\n  specialize (Hsubd ivArg Hgsv).\n  inverts Hsubd as Hsubd Heq.\n  destruct (t2 o ivArg) as [|dvArg ];[inverts Heq|].\n  simpl in *. inverts Heq.\n  constructor. eauto.\nQed.\n\nSection obsLeN.\nVariable n:nat.\nNotation \"s ⊑ t\" := (compObsLeLinkN _ _  n s t) (at level 65).\n\n(** same as as [compObsLeLinkTransitive] above *)\nLemma compObsLeLinkNTransitive\n      {Hgpsi : goodPreserving Src Inter}\n      {Hgpid : goodPreserving Inter Dst}:\n   forall   (s : Src) (i : Inter) (d : Dst),\n  s ⊑ i\n  -> i ⊑ d \n  -> s ⊑ d.\nProof.\n  induction n as [| m Hind];[ constructor |].\n  intros ? ? ? Ha Hb.\n  clear n. rename m into n.\n  inverts Ha as Hah.\n  inverts Hb as Hbh.\n  constructor; auto.\n  intros o ? Hevs.\n  destruct (Hah o _ Hevs) as [iv  Hci]. clear Hah.\n  destruct Hci as [Hevi Hci].\n  destruct Hci as [Hyesi Hsubi].\n  destruct (Hbh o _ Hevi) as [dv  Hcd]. clear Hbh.\n  destruct Hcd as [Hevd Hcd].\n  destruct Hcd as [Hyesd Hsubd].\n  exists dv. split;[ assumption|].\n  assert (forall (A B: Prop), A -> (A-> B) -> A/\\B) as Hp by (intros; tauto).\n  apply Hp;[|intros Hyessd; split]; clear Hp;\n    [eauto using (@yesPreservedTransitive Src Inter Dst) | | ];[|].\n- clear Hyesi Hyesd.\n  intros m.\n  apply proj1 in Hsubi.\n  apply proj1 in Hsubd.\n  specialize (Hsubi m).\n  specialize (Hsubd m).\n  destruct Hsubi;[| constructor ].\n  inversion Hsubd. subst. clear Hsubd.\n  constructor. eauto.\n- intros Habs.\n  apply proj2 in Hsubi.\n  apply proj2 in Hsubd.\n  intros ? Hgsv.\n  specialize (Hsubi Habs svArg Hgsv).\n  unfold yesPreserved in Hyesi.\n  specialize (Hyesi Abs).\n  rewrite Habs in Hyesi.\n  simpl in Hyesi.\n  specialize (Hsubd Hyesi).\n  inverts Hsubi as Hsub Heq.\n  unfold goodPreserving in *. \n  eapply Hgpsi with (o:=o) in Hgsv.\n  unfold composeTranslation, translate in *.\n  destruct (t1 o svArg) as [| ivArg];[inverts Heq|].\n  simpl in *. inverts Heq.\n  specialize (Hsubd ivArg Hgsv).\n  inverts Hsubd as Hsubd Heq.\n  destruct (t2 o ivArg) as [|dvArg ];[inverts Heq|].\n  simpl in *. inverts Heq.\n  constructor. eauto.\nQed.\n\nEnd obsLeN.\nGlobal Instance composeCerticoqLinkableTranslationCorrect\n(* we don't need a translation for the value type, although typically Src=SrcValue*)\n  {Ht1: CerticoqLinkableTranslationCorrect Ls Li}\n  {Ht2: CerticoqLinkableTranslationCorrect Li Ld}\n    : CerticoqLinkableTranslationCorrect Ls Ld.\nProof.\n  destruct Ht1, Ht2.\n  constructor; [eapply composePreservesGood; eauto; fail |].\n  intros o ? Hgoods.\n  specialize (obsePresLink0 o _ Hgoods).\n  inverts obsePresLink0 as Hle Heq.\n  unfold goodPreserving in *. \n  eapply certiGoodPresLink0 with (o:=o) in Hgoods.\n  unfold composeTranslation, translate in *.\n  destruct (t1 o s); compute in Hgoods; try contradiction.\n  compute in Heq. inverts Heq.\n  specialize (obsePresLink1 o _ Hgoods).\n  inverts obsePresLink1 as Hlei Heqi.\n  eapply certiGoodPresLink1 with (o:=o) in Hgoods.\n  unfold composeTranslation, translate in *. simpl.\n  destruct (t2 o i); compute in Hgoods; try contradiction.\n  simpl.\n  constructor.\n  inverts Heqi.\n  eapply compObsLeLinkTransitive; eauto.\n  Unshelve. eauto. eauto.\nQed.\n\n(* Outside this section, this definition should not depend at all on Src and Dst.*)\nDefinition leObsId : Inter -> Inter -> Prop :=  ((@compObsLeLink Inter Inter _ _ _ _ _ _ _ (fun o x => Ret x) _ _ )).\n\nDefinition eqObsId (a b : Inter) := leObsId a b /\\ leObsId b a. \n\n\nLemma sameValuesImpliesLeObsId a b: sameValues a b -> leObsId a b.\nProof using.\n  revert a b. cofix sameValuesImpliesLeObsId.\n  intros ? ? Hs. constructor. intros o sv Hsv.\n  specialize (proj1 (Hs _) Hsv). intros Hsvb.\n  exists sv. dands; auto; try reflexivity.\n- intros. apply liftLeRimpl with (R1:= sameValues); auto.\n  apply liftLeRefl. unfold Reflexive, sameValues. reflexivity.\n- intros. simpl. constructor. apply sameValuesImpliesLeObsId.\n  unfold Reflexive, sameValues. reflexivity.\nQed.\n\nLemma sameValuesImpliesEqObsId a b: sameValues a b -> eqObsId a b.\nProof using Dst H4 H5 H6 H7 H8 Inter Src t1 t2.\n  intros Hs. split; apply sameValuesImpliesLeObsId; auto.\n  unfold Reflexive, sameValues in *. firstorder.\nQed.\n\n\nLocal Instance compObsLeLinkRespectsEval:\n  Proper (eq ==> bigStepEval  ==> Basics.impl) (@compObsLeLink Src Inter _ _ _ _ _ _ _ _ _ _ ).\nProof using.\n  intros s1 s2 Heqs d1 d2 Hsvd Hs1. subst.\n  constructor.\n  intros ? Heval.\n  (* need that the second arg of bigStepeval is terminal *)\nAbort.\n\nEnd ComposeLink.\n\n\n\nArguments eqObsId {Inter} {H4} {H5} {H6} {H7} {H8}.\nArguments leObsId {Inter} {H4} {H5} {H6} {H7} {H8}.\n\nSection LinkObsProper.\nContext {Src Dst : Type}\n        `{Ls: CerticoqLinkableLanguage Src}\n        `{Ld: CerticoqLinkableLanguage Dst}.\nLemma compObsLeLink_proper_Feq t1 t2:\n  (forall o s, t1 o s =  t2 o s) -> forall a b,\n  (@compObsLeLink Src Dst _ _ _ _ _ _ _ t1 _ _ ) a b \n  -> (@compObsLeLink Src Dst _ _ _ _ _ _ _ t2 _ _ ) a b.\nProof using.\n  intros feq.\n  cofix compObsLeLink_proper_Feq.\n  intros ? ? Hl.\n  constructor. invertsn Hl.\n  intros o sv Hev. specialize (Hl o sv Hev). exrepnd.\n  exists dv. dands; eauto using  liftLeRimpl;[].\n  intros Hq sva Hga. specialize (Hl0 Hq sva Hga). unfold translate in *.\n  rewrite <- feq. simpl in *.\n  eauto using liftLeRimpl.\nQed.\n\n(* proof same as above *)\nLemma compObsLeLinkN_proper_Feq t1 t2:\n  (forall o s, t1 o s =  t2 o s) -> forall n a b,\n  (@compObsLeLinkN Src Dst _ _ _ _ _ _ _ t1  _ _ n) a b \n  -> (@compObsLeLinkN Src Dst _ _ _ _ _ _ _ t2  _ _ n) a b.\nProof using.\n  intros feq n.  induction n;[ constructor |].\n  intros ? ? Hl.\n  constructor. invertsn Hl.\n  intros o sv Hev. specialize (Hl o sv Hev). exrepnd.\n  exists dv. dands; eauto using  liftLeRimpl;[].\n  intros Hq sva Hga. specialize (Hl0 Hq sva Hga). unfold translate in *.\n  rewrite <- feq. simpl in *.\n  eauto using liftLeRimpl.\nQed.\n\nContext {t : CerticoqTranslation Src Dst}\n        {tg: goodPreserving Src Dst}.\n\n\n  \nLemma compObsLeLinkRespectsLe:\n  Proper ((Basics.flip leObsId) ==> leObsId ==> Basics.impl) (@compObsLeLink Src Dst _ _ _ _ _ _ _ _ _ _  ).\nProof using tg.\n  intros l1 l2 Heql r1 r2 Heqr Hc.\n  unfold leObsId, Basics.flip in *.\n  eapply compObsLeLinkTransitive with (t1:= fun o x => Ret x); eauto;\n    [apply goodPreservingId| ].\n  eapply compObsLeLinkTransitive with (t2:= fun o x => Ret x) in Hc; eauto; try assumption;\n    [|apply goodPreservingId];[].\n  eapply compObsLeLink_proper_Feq;[| exact Hc].\n  intros o s. unfold composeTranslation, translate.\n  destruct (t o s); reflexivity.\nQed.\n\nLemma compObsLeLinkNRespectsLe n:\n  Proper ((Basics.flip leObsId) ==> leObsId ==> Basics.impl) (@compObsLeLinkN  Src Dst _ _ _ _ _ _ _ _ _ _ n ).\nProof using tg.\n  intros l1 l2 Heql r1 r2 Heqr Hc.\n  unfold leObsId, Basics.flip in *.\n  apply fromCoInd with (m:=n)in Heql.\n  apply fromCoInd with (m:=n)in Heqr.\n  eapply compObsLeLinkNTransitive with (t1:= fun s x => Ret x); eauto;\n    [apply goodPreservingId|].\n  eapply compObsLeLinkNTransitive with (t2:= fun s x => Ret x) in Hc; eauto; try assumption;\n    [|apply goodPreservingId];[].\n  eapply compObsLeLinkN_proper_Feq;[| exact Hc].\n  intros o s. unfold composeTranslation, translate. destruct (t o s); reflexivity.\nQed.\n\nGlobal Instance compObsLeLinkRespectsEqObs:\n  Proper (eqObsId ==> eqObsId ==> iff) (@compObsLeLink Src Dst _ _ _ _ _ _ _ _ _ _  ).\nProof using tg.\n  intros  ? ? Hleq ? ? Hreq. unfold eqObsId in *. repnd.\n  split; apply compObsLeLinkRespectsLe; auto.\nQed.\n\nGlobal Instance compObsLeLinkNRespectsEqObs n :\n  Proper (eqObsId ==> eqObsId ==> iff) (@compObsLeLinkN Src Dst _ _ _ _ _ _ _ _ _ _ n).\nProof using tg.\n  intros  ? ? Hleq ? ? Hreq. unfold eqObsId in *. repnd.\n  split; apply compObsLeLinkNRespectsLe; auto.\nQed.\n\n\nGlobal Instance  compObsLeLinkRespectsSameVal:\n  Proper (sameValues ==> sameValues ==> iff) (@compObsLeLink Src Dst _ _ _ _ _ _ _ _ _ _  ).\nProof using H5 tg.\n  intros ? ? ? ? ? ?.\n  apply compObsLeLinkRespectsEqObs.\n  eapply sameValuesImpliesEqObsId; try eassumption.\n  exact (fun o x => Ret x). \n  eapply sameValuesImpliesEqObsId; try eassumption.\n  exact (fun o x => Ret x). \nQed.\n\nGlobal Instance  compObsLeLinkNRespectsSameVal n:\n  Proper (sameValues ==> sameValues ==> iff) (@compObsLeLinkN Src Dst _ _ _ _ _ _ _ _ _ _ n).\nProof using H5 tg.\n  intros ? ? ? ? ? ?.\n  apply compObsLeLinkNRespectsEqObs; eapply sameValuesImpliesEqObsId; try eassumption;\n  exact (fun o x => Ret x). \nQed.\n\nEnd LinkObsProper.\n\nSection EqObsEquiv.\nContext {Src Dst : Type}\n        `{Ls: CerticoqLinkableLanguage Src}.\n\nGlobal Instance compObsLeLinkSymm:\n  Symmetric eqObsId.\nProof using.\n  intros x y. unfold eqObsId. tauto.\nQed.\n\nGlobal Instance sameValuesEquiv:\n  Equivalence sameValues.\nProof using.\n  constructor; unfold sameValues;\n    intros x; firstorder.\nQed.\n\nGlobal Instance compObsLeLinkRefl:\n  Reflexive leObsId.\nProof using.\n  intros x. apply sameValuesImpliesLeObsId. reflexivity.\nQed.\n\nGlobal Instance compObsEqLinkRefl:\n  Reflexive eqObsId.\nProof using.\n  intros x. split; reflexivity.\nQed.\n\nGlobal Instance compObsLeLinkEquiv:\n  Equivalence eqObsId.\nProof using.\n  constructor; eauto with typeclass_instances.\n  intros ? ? ? H1eq  H2eq. unfold eqObsId, leObsId.\n  split.\n- eapply compObsLeLinkRespectsEqObs;[apply compObsEqLinkRefl| symmetry; eauto\n                                       | unfold eqObsId in *; tauto].\n- eapply compObsLeLinkRespectsEqObs; [apply compObsEqLinkRefl|  eauto\n                                      | unfold eqObsId in *; tauto].\nUnshelve.\n  apply goodPreservingId.\n  apply goodPreservingId.\nQed.\n\nEnd EqObsEquiv.\n\nSection LinkingIllustration.\nContext {Src Dst : Type}\n        `{Ls: CerticoqLinkableLanguage Src}\n        `{Ld: CerticoqLinkableLanguage Dst}\n        {comp1 : CerticoqTranslation Src Dst}\n        {Ht1: CerticoqLinkableTranslationCorrect Ls Ld}.\n\n(** Suppose [f] computes to a function (lambda) [fv] in the [Src] language *)\nVariable (o:Opt).\nVariable f:Src.\nVariable fv:Src.\nHypothesis fcomputes: f ⇓ fv.\nHypothesis flam : questionHead Abs fv = true. (** [fv] may say yes to other questions as well *)\n\n(** [f] compiles to [fd] *)\nVariable fd:Dst.\nHypothesis compilef : translate Src Dst o f = Ret fd.\n\n(** [fd] computes to [fdv] *)\nVariable fdv:Dst.\nHypothesis compilefd : fd ⇓ fdv.\n\n(** Now consider an argument [t] to [f] in Src. *)\nVariable t:Src.\n\nNotation \"s ⊑ t\" := (compObsLeLink _ _ s t) (at level 65).\n\n(** Suppose we SEPARATELY [t] compile by the SAME compiler it to get [td] *)\nVariable td:Dst.\nSection SameCompiler.\nHypothesis compilet : translate Src Dst o t = Ret td.\n\n\n(** The destination language has a notion of application. Consider the destination term: *)\nLet fdtd := mkApp fdv td.\n\n\n(** We would like [fdtd] be be observationally equal to [mkApp fv t], which is an easy\ncorrollary of the linkable correctness property: *)\nCorollary fdtdCorrect {dd : deterministicBigStep Dst}\n  : goodTerm f -> goodTerm t -> mkApp fv t  ⊑ mkApp fdv td.\nProof.\n  intros Hgf Hgt.\n  destruct Ht1.\n  specialize (obsePresLink0 o f Hgf).\n  rewrite compilef in obsePresLink0. simpl in *.\n  invertsn obsePresLink0.\n  invertsn obsePresLink0.\n  specialize (obsePresLink0 o fv fcomputes).\n  exrepnd. clear obsePresLink2 obsePresLink3.\n  unfold deterministicBigStep in dd.\n  apply dd with (v2:= fdv) in obsePresLink0;[ subst | assumption].\n  specialize (obsePresLink1 flam t Hgt).\n  rewrite compilet in obsePresLink1. simpl in obsePresLink1.\n  invertsn obsePresLink1. assumption.\nQed.\nEnd SameCompiler.\n\nDefinition appArgCongr : Prop :=\n  forall (ff tt1 tt2: Dst),\n    (* consider adding this:  goodTerm ff -> , which will need ⇓ to be goodpreserving*)\n     goodTerm tt1\n    -> goodTerm tt2\n    -> leObsId tt1 tt2\n    -> leObsId (mkApp ff tt1) (mkApp ff tt2).\n\nSection ManualTargetArgTargetRel.\n(** Now suppose, we use DIFFERENT compiler to compile [td]. First, we\nlist the needed properties for the other compiler [comp2] *)\n\nHypothesis mkAppCongrLe : appArgCongr.\n\nLemma mkAppCongr : forall (ff tt1 tt2: Dst),\n    (* consider adding this:  goodTerm ff -> , which will need ⇓ to be goodpreserving*)\n     goodTerm tt1\n    -> goodTerm tt2\n    -> eqObsId tt1 tt2\n    -> eqObsId (mkApp ff tt1) (mkApp ff tt2).\nProof using mkAppCongrLe.\n  intros ff ? ? H1g H2g ?.\n  specialize (mkAppCongrLe ff).\n  unfold eqObsId in *. repnd.\n  eauto.\nQed.\n\nInstance mkAppRW : Proper (eq ==> eqObsId ==> eqObsId) (@mkApp Dst _).\nProof using.\n  intros ? ? ? ? ? ?. subst.\n  apply mkAppCongr.\n  (* need goodTerm *)\nAbort.\n\nHypothesis compilet :  (@translate Src Dst comp1 o t) = Ret td.\n(** Suppose that instead of td, we wish to use another term td', which we produced manually\nor by magic. We also proved that it is a good term and is greater than td *)\nVariable td':Dst.\nHypothesis td'good: goodTerm td'.\nHypothesis td'Le : leObsId td td'.\n\n(** Again, consider the application term in the destination language, where the function\n  and the arg are compiled by different compilers *)\nLet fdtd := mkApp fdv td'.\n\n\n(** Again, we would like [fdtd] be be observationally equal to [mkApp fv t], which is a\ncorrollary of the linkable correctness property: *)\nCorollary fdtdCorrectDiff {dd : deterministicBigStep Dst}\n  : goodTerm f -> goodTerm t -> mkApp fv t  ⊑ mkApp fdv td'.\nProof.\n  intros Hgf Hgt.\n  destruct Ht1.\n  specialize (obsePresLink0 o f Hgf).\n  rewrite compilef in obsePresLink0. simpl in *.\n  invertsn obsePresLink0.\n  invertsn obsePresLink0.\n  specialize (obsePresLink0 o fv fcomputes).\n  exrepnd. clear obsePresLink2 obsePresLink3.\n  unfold deterministicBigStep in dd.\n  apply dd with (v2:= fdv) in obsePresLink0;[ subst | assumption].\n  specialize (obsePresLink1 flam t Hgt).\n  pose proof certiGoodPresLink0 as Hgpb.\n  specialize (certiGoodPresLink0 t o Hgt).\n  rewrite compilet in *. simpl in *.\n  invertsna obsePresLink1 Hinvf.\n  apply (mkAppCongrLe fdv) in td'Le; eauto;[].\n  eapply compObsLeLinkRespectsLe; [reflexivity | apply td'Le |].\n  exact Hinvf.\n  Unshelve. assumption.\nQed.\n\nEnd ManualTargetArgTargetRel.\n\n(** \nSimilar to the above section, except that the manually produced target argument [td']\nhas to be proved to be related to the corresponding [Src] term [t] instead of the\ncompilation result [td]. This was requested by Andrew Appel.\n*)\nSection ManualTargetArgSrcRel.\n\n  (** In this section, this is all we know about [td]. We dont anymore have the hypothesis\n  that [td] was obtained from compiling [t] *)\n  Hypothesis argRelated :  t ⊑ td.\n  Hypothesis tdGood :  goodTerm td.\n\n  Hypothesis mkAppCongrLe : appArgCongr.\n\nCorollary fdtdCorrectDiff {dd : deterministicBigStep Dst}\n  : goodTerm f -> goodTerm t -> mkApp fv t  ⊑ mkApp fdv td.\nProof.\n  intros Hgf Hgt.\n  destruct Ht1.\n  specialize (obsePresLink0 o f Hgf).\n  rewrite compilef in obsePresLink0. simpl in *.\n  invertsn obsePresLink0.\n  invertsn obsePresLink0.\n  specialize (obsePresLink0 o fv fcomputes).\n  exrepnd. clear obsePresLink2 obsePresLink3.\n  unfold deterministicBigStep in dd.\n  apply dd with (v2:= fdv) in obsePresLink0;[ subst | assumption].\n  specialize (obsePresLink1 flam t Hgt).\n  pose proof certiGoodPresLink0 as Hgpb.\n  specialize (certiGoodPresLink0 t o Hgt).\n  destruct Ht1.\n  specialize (obsePresLink0 o t Hgt).\n  destruct (@translate Src Dst comp1 o t) as [| tdc]; try contradiction.\n  simpl in *.\n  invertsna obsePresLink1 Hinvf.\n  invertsna obsePresLink0 Hinvt.\n  (** \n   [Hinvf] is what we get from using the correctness property of the compiler, instantiated\n   for the function [f]. We have to somehow replace [tdc] by [td] there. \n   Recall that [tdc] is the result of compiling [td]. \n\n   The only way to use [mkAppCongr], which is congruence in [Dst],\n   is to show that [tdc ⊑ td].\n   We may, however, choose to have a different assumption instead of [mkAppCongr].\n *)\n  \n  eapply compObsLeLinkRespectsLe; [reflexivity | apply (mkAppCongrLe _ tdc _) | ]; auto.\n\n(** \nThis goal seems unprovable. We have both [t ⊑ tdc] and [t ⊑ td].\nThat says nothing about the ordering between [tdc] and [td]. \n*)\n  \nAbort.\n\nEnd ManualTargetArgSrcRel.\n\nEnd LinkingIllustration.\n", "meta": {"author": "CertiCoq", "repo": "certicoq", "sha": "2405e1012e9c0a58e49002d9779bb65527d6c323", "save_path": "github-repos/coq/CertiCoq-certicoq", "path": "github-repos/coq/CertiCoq-certicoq/certicoq-2405e1012e9c0a58e49002d9779bb65527d6c323/theories/common/CertiClasses/certiClassesLinkable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.23101978845713902}}
{"text": "From ITree Require Import ITree.\nFrom Paco Require Import paco.\nFrom compcert Require Import Integers.\n\nRequire Import sflib.\n\nRequire Import StdlibExt.\nRequire Import IntegersExt.\nRequire Import SyncSysModel.\n\nRequire Import Executable.\nRequire Import PALSSystem.\n\nRequire Import ConvC2ITree.\n\nRequire Import AcStSystem.\nRequire Import SpecConsole SpecController SpecDevice.\nRequire Import AcStRefinement.\n\nFrom Coq Require Extraction ExtrOcamlBasic ExtrOcamlString.\n\nRequire Import ZArith List Lia.\n\nDefinition max_num_tasks: nat := 16.\nDefinition msg_size_k: Z := 1.\nDefinition msg_size: Z := 8.\n\nDefinition resize_bytes: bytes -> bytes? :=\n  (fun bs => Some (RTSysEnv.resize_bytes 8 bs)).\n\nDefinition oapp_con: AppMod.t ? :=\n  cprog2app console.prog max_num_tasks msg_size_k msg_size.\nDefinition oapp_ctrl1: AppMod.t ? :=\n  cprog2app (ctrl.prog 1) max_num_tasks msg_size_k msg_size.\nDefinition oapp_ctrl2: AppMod.t ? :=\n  cprog2app (ctrl.prog 2) max_num_tasks msg_size_k msg_size.\nDefinition oapp_dev1: AppMod.t ? :=\n  cprog2app (dev.prog 3) max_num_tasks msg_size_k msg_size.\nDefinition oapp_dev2: AppMod.t ? :=\n  cprog2app (dev.prog 4) max_num_tasks msg_size_k msg_size.\nDefinition oapp_dev3: AppMod.t ? :=\n  cprog2app (dev.prog 5) max_num_tasks msg_size_k msg_size.\n\nDefinition app_system : ExecutableSpec.t :=\n  let apps :=\n      match deopt_list [oapp_con; oapp_ctrl1; oapp_ctrl2; oapp_dev1; oapp_dev2; oapp_dev3] with\n      | None => []\n      | Some apps => apps\n      end\n  in\n  ExecutableSpec.mk _ _ ActiveStandby.period\n                    apps [[1; 2]]\n                    resize_bytes.\n\nDefinition app_system_itree: Z -> option Z -> itree _ unit :=\n  @ExecutableSpec.sys_itree _ _ app_system.\n\nCd \"./extr/active_standby_c2itree\".\nExtraction \"AppSystem.ml\" app_system app_system_itree.\nCd \"../..\".\n", "meta": {"author": "kim-yoonseung", "repo": "pals-thesis-dev", "sha": "1a165028f5461ed4d00a1e2720b3b1e4542f5dc2", "save_path": "github-repos/coq/kim-yoonseung-pals-thesis-dev", "path": "github-repos/coq/kim-yoonseung-pals-thesis-dev/pals-thesis-dev-1a165028f5461ed4d00a1e2720b3b1e4542f5dc2/extr/active_standby_c2itree/ExtractActiveStandby_C2ITree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.23099940948404143}}
{"text": "Require Import Coq.Sets.Ensembles Bedrock.Platform.AutoSep Bedrock.Platform.Malloc.\n\nSection adt.\n  Variable P : list W -> W -> HProp.\n  Variable res : nat.\n\n  Definition newS := SPEC(\"extra_stack\", \"len\") reserving res\n    PRE[V] [| V \"len\" >= $2 |] * mallocHeap 0\n    POST[R] Ex ls, P ls R * [| length ls = wordToNat (V \"len\") |] * mallocHeap 0.\n\n  Definition deleteS := SPEC(\"extra_stack\", \"self\", \"len\") reserving res\n    Al ls,\n    PRE[V] P ls (V \"self\") * [| length ls = wordToNat (V \"len\") |] * mallocHeap 0\n    POST[R] [| R = $0 |] * mallocHeap 0.\n\n  Definition copyS := SPEC(\"extra_stack\", \"self\", \"len\") reserving res\n    Al ls,\n    PRE[V] P ls (V \"self\") * [| length ls = wordToNat (V \"len\") |] * [| $2 <= V \"len\" |] * mallocHeap 0\n    POST[R] P ls (V \"self\") * P ls R * mallocHeap 0.\n\n  Definition getS := SPEC(\"extra_stack\", \"self\", \"pos\") reserving res\n    Al ls,\n    PRE[V] P ls (V \"self\") * [| V \"pos\" < natToW (length ls) |] * mallocHeap 0\n    POST[R] [| R = Array.sel ls (V \"pos\") |] * P ls (V \"self\") * mallocHeap 0.\n\n  Definition setS := SPEC(\"extra_stack\", \"self\", \"pos\", \"val\") reserving res\n    Al ls,\n    PRE[V] P ls (V \"self\") * [| V \"pos\" < natToW (length ls) |] * mallocHeap 0\n    POST[R] [| R = $0 |] * P (Array.upd ls (V \"pos\") (V \"val\")) (V \"self\") * mallocHeap 0.\nEnd adt.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Platform/Facade/examples/TupleF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23099940324324342}}
{"text": "(* Default settings (from HsToCoq.Coq.Preamble) *)\n\n(* Archivo que contiene la extension de las definiciones para eliminar elementos de un arbol rojinegro.\n\nEn varias funciones se agregaron casos extras para volver a las funciones totales, se cree que en las demostraciones esto\nva causar ruido y se tengan que eliminar esos casos haciendo uso de admits, ya que aunque por construccion NO se puede caer\nen esos casos, Coq pide que se demuestren, es posible que algo asi pase en el script de insercion con los dos casos que no se han podido demostrar.\n *)\n\n(* \nSe entiende que esta es una estrucutura un tanto compleja y que la herramienta todavia esta en su infancia y no genere\ncodigo 100% proof ready *)\nGeneralizable All Variables.\n\nUnset Implicit Arguments.\nSet Maximal Implicit Insertion.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Coq.Program.Tactics.\nRequire Coq.Program.Wf.\nRequire Import ARNDefiniciones.\n\nPrint ARNDefiniciones.\n(* Converted imports: *)\n\nRequire GHC.Base.\nRequire GHC.Err.\nRequire GHC.Types.\nImport GHC.Base.Notations.\n\n\n(* Pinta de rojo la raiz de un arbol\n *)\nDefinition red {a} `{GHC.Base.Ord a}: RB a -> RB a :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | T _ a x b => T R a x b\n    | _ => E\n    end.\n\nDefinition balance {a} `{GHC.Base.Ord a}\n   : RB a -> a -> RB a -> RB a :=\n  fun arg_0__ arg_1__ arg_2__ =>\n    match arg_0__, arg_1__, arg_2__ with\n    | T R a x b, y, T R c z d => T R (T B a x b) y (T B c z d)\n    | T R (T R a x b) y c, z, d => T R (T B a x b) y (T B c z d)\n    | T R a x (T R b y c), z, d => T R (T B a x b) y (T B c z d)\n    | a, x, T R b y (T R c z d) => T R (T B a x b) y (T B c z d)\n    | a, x, T R (T R b y c) z d => T R (T B a x b) y (T B c z d)\n    | a, x, b => T B a x b\n    end.\n\nDefinition balleft {a} `{GHC.Base.Ord a}\n   : RB a -> a -> RB a -> RB a :=\n  fun arg_0__ arg_1__ arg_2__ =>\n    match arg_0__, arg_1__, arg_2__ with\n    | T R a x b, y, c => T R (T B a x b) y c\n    | bl, x, T B a y b => balance bl x (T R a y b)\n    | bl, x, T R (T B a y b) z c => T R (T B bl x a) y (balance b z (red c))\n    | ti, x, tr => T R ti x tr (*caso extra para hacerlo total...*)\n    end.\n\nDefinition balright {a} `{GHC.Base.Ord a}\n   : RB a -> a -> RB a -> RB a :=\n  fun arg_0__ arg_1__ arg_2__ =>\n    match arg_0__, arg_1__, arg_2__ with\n    | a, x, T R b y c => T R a x (T B b y c)\n    | T B a x b, y, bl => balance (T R a x b) y bl\n    | T R a x (T B b y c), z, bl => T R (balance (red a) x b) y (T B c z bl)\n    | ti, x, tr => T R ti x tr (*caso extra para hacerlo total...*)\n    end.  \n\n(* Fixpoint appaux {a} `{GHC.Base.Ord a} (a: RB a) (b: RB a) :=\nmatch a, b with  *)\n\n\n(* maybe separating this function making an auxiliar fn(?)\n *)\nDefinition app {a} `{GHC.Base.Ord a}: RB a -> RB a -> RB a :=\n  fix app arg_0__ arg_1__\n        := match arg_0__, arg_1__ with\n           | E, x => x\n           | x, E => x\n           | T R a x b, T R c y d =>\n               match app b c with\n               | T R b' z c' => T R (T R a x b') z (T R c' y d)\n               | bc => T R a x (T R bc y d)\n               end\n           | T B a x b, T B c y d =>\n               match app b c with\n               | T R b' z c' => T R (T B a x b') z (T B c' y d)\n               | bc => balleft a x (T B bc y d)\n               end\n           | a, T R b x c => T R (app a b) x c\n           | T R a x b, c => T R a x (app b c)\n           end.\n\nDefinition delete : a -> RB a -> RB a :=\n  fun x t =>\n    let del :=\n      fix del arg_0__\n            := match arg_0__ with\n               | E => E\n               | T _ a y b =>\n                   if x GHC.Base.< y : bool then delfromLeft a y b else\n                   if x GHC.Base.> y : bool then delfromRight a y b else\n                   app a b\n               end with delfromLeft arg_5__ arg_6__ arg_7__\n                          := match arg_5__, arg_6__, arg_7__ with\n                             | (T B _ _ _ as a), y, b => balleft (del a) y b\n                             | a, y, b => T R (del a) y b\n                             end with delfromRight arg_11__ arg_12__ arg_13__\n                                        := match arg_11__, arg_12__, arg_13__ with\n                                           | a, y, (T B _ _ _ as b) => balright a y (del b)\n                                           | a, y, b => T R a y (del b)\n                                           end for del in\n    let delfromLeft :=\n      fix del arg_0__\n            := match arg_0__ with\n               | E => E\n               | T _ a y b =>\n                   if x GHC.Base.< y : bool then delfromLeft a y b else\n                   if x GHC.Base.> y : bool then delfromRight a y b else\n                   app a b\n               end with delfromLeft arg_5__ arg_6__ arg_7__\n                          := match arg_5__, arg_6__, arg_7__ with\n                             | (T B _ _ _ as a), y, b => balleft (del a) y b\n                             | a, y, b => T R (del a) y b\n                             end with delfromRight arg_11__ arg_12__ arg_13__\n                                        := match arg_11__, arg_12__, arg_13__ with\n                                           | a, y, (T B _ _ _ as b) => balright a y (del b)\n                                           | a, y, b => T R a y (del b)\n                                           end for delfromLeft in\n    let delfromRight :=\n      fix del arg_0__\n            := match arg_0__ with\n               | E => E\n               | T _ a y b =>\n                   if x GHC.Base.< y : bool then delfromLeft a y b else\n                   if x GHC.Base.> y : bool then delfromRight a y b else\n                   app a b\n               end with delfromLeft arg_5__ arg_6__ arg_7__\n                          := match arg_5__, arg_6__, arg_7__ with\n                             | (T B _ _ _ as a), y, b => balleft (del a) y b\n                             | a, y, b => T R (del a) y b\n                             end with delfromRight arg_11__ arg_12__ arg_13__\n                                        := match arg_11__, arg_12__, arg_13__ with\n                                           | a, y, (T B _ _ _ as b) => balright a y (del b)\n                                           | a, y, b => T R a y (del b)\n                                           end for delfromRight in\n    match del t with\n    | T _ a y b => T B a y b\n    | _ => E\n    end.\n\n(* External variables:\n     bool GHC.Base.op_zg__ GHC.Base.op_zl__ GHC.Err.Build_Default\n     GHC.Err.Default GHC.Err.error GHC.Err.patternFailure GHC.Types.Bool\n     GHC.Types.False a GHC.Types.True\n*)\n", "meta": {"author": "DavidFHCh", "repo": "Tesis-FTW", "sha": "f84ab8eb92f3984e973ce6a441262d9a8a62e9b0", "save_path": "github-repos/coq/DavidFHCh-Tesis-FTW", "path": "github-repos/coq/DavidFHCh-Tesis-FTW/Tesis-FTW-f84ab8eb92f3984e973ce6a441262d9a8a62e9b0/tesis/hs-to-coq/base/ARNEliminar.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23099940324324342}}
{"text": "From Coq Require Import FinFun Bool List Streams Logic.Epsilon Arith.Compare_dec Lia.\nImport ListNotations.\n\nFrom CasperCBC\n  Require Import\n    Lib.Preamble Lib.ListExtras Lib.ListSetExtras Lib.RealsExtras\n    VLSM.Common VLSM.Composition VLSM.ProjectionTraces.\n\n(** * VLSM Decisions on Consensus Values *)\n\n(* Need to add consensus values (and decision functions) to VLSM definitions? *)\nClass consensus_values :=\n  { C : Type;\n    about_C : exists (c1 c2 : C), c1 <> c2;\n  }.\n\nDefinition decision {message} (T : VLSM_type message) {CV : consensus_values}\n  := @state _ T -> option C.\n\nDefinition vdecision {message} (V : VLSM message) {CV : consensus_values}\n  := decision (type V).\n\nSection CommuteSingleton.\n\n  Context\n    {message : Type}\n    {CV : consensus_values}\n    (V : VLSM message).\n\n  (* 3.2.1 Decision finality *)\n\n  (* Definition of finality per document. *)\n  Definition final_original : vdecision V -> Prop :=\n    fun (D : vdecision V) => forall (tr : protocol_trace V),\n        forall (n1 n2 : nat) (s1 s2 : state) (c1 c2 : C),\n          (trace_nth (proj1_sig tr) n1 = Some s1) ->\n          (trace_nth (proj1_sig tr) n2 = Some s2) ->\n          (D s1 = (Some c1)) ->\n          (D s2 = (Some c2)) ->\n          c1 = c2.\n\n  (* Definition of finality using in_futures, which plays better with the estimator property *)\n  Definition final: vdecision V -> Prop :=\n  fun (D : vdecision V) => forall (s1 s2 : vstate V) (c1 c2 : C),\n        in_futures V s1 s2 ->\n        (D s1 = (Some c1)) ->\n        (D s2 = (Some c2)) ->\n        c1 = c2.\n\n  (* 3.3.1 Initial protocol state bivalence *)\n  Definition bivalent : vdecision V -> Prop :=\n    fun (D : vdecision V) =>\n      (* All initial states decide on None *)\n      (forall (s0 : state),\n        vinitial_state_prop V s0 ->\n        D s0 = None) /\\\n      (* Every protocol trace (already beginning from an initial state) contains a state deciding on each consensus value *)\n      (forall (c : C) ,\n          exists (tr : protocol_trace V) (s : state) (n : nat),\n            (trace_nth (proj1_sig tr) n) = Some s /\\ D s = (Some c)).\n\n  (* 3.3.2 No stuck states *)\n\n  Definition stuck_free : vdecision V -> Prop :=\n    fun (D : vdecision V) =>\n      (forall (s : state),\n          exists (tr : protocol_trace V)\n                 (decided_state : state)\n                 (n_s n_decided : nat)\n                 (c : C),\n         trace_nth (proj1_sig tr) n_s = Some s /\\\n         trace_nth (proj1_sig tr) n_decided = Some decided_state /\\\n         n_decided >= n_s /\\\n         D decided_state = Some c).\n\n  (* 3.3.3 Protocol definition symmetry *)\n  (* How do we formalize this property set-theoretically? *)\n\n  Definition behavior : vdecision V -> Prop :=\n    fun _ => True.\n\n  Definition symmetric : vdecision V -> Prop :=\n    fun (D : vdecision V) =>\n    exists (f : vdecision V -> vdecision V),\n      behavior D = behavior (f D).\n\nEnd CommuteSingleton.\n\nSection CommuteIndexed.\n\n  Context\n    {CV : consensus_values}\n    {message : Type}\n    {index : Type}\n    {Heqd : EqDecision index}\n    (IM : index -> VLSM message)\n    {Hi : Inhabited index}\n    (constraint : composite_label IM -> composite_state IM * option message -> Prop)\n    (X := composite_vlsm IM constraint)\n    (ID : forall i : index, vdecision (IM i)).\n\n  (* ** Decision consistency\n\n  First, let us introduce a definition of consistency which\n  looks at states as belonging to a trace.\n  *)\n\n  Definition consistent_original :=\n      forall (tr : protocol_trace X),\n      forall (n1 n2 : nat),\n      forall (j k : index),\n      forall (s1 s2 : vstate X),\n      forall (c1 c2 : C),\n      j <> k ->\n      trace_nth (proj1_sig tr) n1 = (Some s1) ->\n      trace_nth (proj1_sig tr) n2 = (Some s2) ->\n      (ID j) (s1 j) = (Some c1) ->\n      (ID k) (s2 k) = (Some c2) ->\n      c1 = c2.\n\n  (**\n\n  Now let us give an alternative definition based on [in_futures]:\n  *)\n\n  Definition consistent :=\n      forall\n        (s1 s2 : vstate X)\n        (Hfuture : in_futures X s1 s2)\n        (j k : index)\n        (Hneq : j <> k)\n        (c1 c2 : C)\n        (HDecided1 : (ID j) (s1 j) = Some c1)\n        (HDecided2 : (ID k) (s2 k) = Some c2)\n        , c1 = c2.\n\n\n  (**\n  Next two results show that the two definitions above are equivalent.\n  *)\n\n  Lemma consistent_to_original\n    (Hconsistent : consistent)\n    : consistent_original.\n  Proof.\n    intros tr n1 n2 j k s1 s2 c1 c2 Hneq Hs1 Hs2 HD1 HD2.\n    destruct (le_lt_dec n1 n2).\n    - specialize (in_futures_witness_reverse X s1 s2 tr n1 n2 l Hs1 Hs2)\n      ; intros Hfutures.\n      specialize (Hconsistent s1 s2 Hfutures j k Hneq c1 c2 HD1 HD2).\n      assumption.\n    - assert (Hle : n2 <= n1) by lia.\n      clear l.\n      specialize (in_futures_witness_reverse X s2 s1 tr n2 n1 Hle Hs2 Hs1)\n      ; intros Hfutures.\n      assert (Hneq' : k <> j)\n        by (intro Heq; elim Hneq; symmetry; assumption).\n      specialize (Hconsistent s2 s1 Hfutures k j Hneq' c2 c1 HD2 HD1).\n      symmetry.\n      assumption.\n    Qed.\n\n  Lemma original_to_consistent\n    (Horiginal : consistent_original)\n    : consistent.\n  Proof.\n    unfold consistent; intros.\n    specialize (in_futures_witness X s1 s2 Hfuture)\n    ; intros [tr [n1 [n2 [Hle [Hs1 Hs2]]]]].\n    specialize (Horiginal tr n1 n2 j k s1 s2 c1 c2 Hneq Hs1 Hs2 HDecided1 HDecided2).\n    assumption.\n  Qed.\n\n  (** The following is an attempt to include finality in the definition of consistency by dropping the requirement\n      that (j <> k). **)\n\n  Definition final_and_consistent :=\n      forall\n        (s1 s2 : vstate X)\n        (Hfuture : in_futures X s1 s2)\n        (j k : index)\n        (c1 c2 : C)\n        (HDecided1 : (ID j) (s1 j) = Some c1)\n        (HDecided2 : (ID k) (s2 k) = Some c2)\n        , c1 = c2.\n\n  Lemma final_and_consistent_implies_final\n      (Hcons : final_and_consistent)\n      (i : index)\n      (Hfr : finite_projection_friendly IM constraint i)\n      : final (composite_vlsm_constrained_projection IM constraint i) (ID i).\n  Proof.\n    intros s1 s2 c1 c2 Hfuturesi HD1 HD2.\n    specialize (projection_friendly_in_futures IM constraint i Hfr s1 s2 Hfuturesi)\n    ; intros [sX1 [sX2 [Hs1 [Hs2 HfuturesX]]]].\n    subst.\n    apply (Hcons sX1 sX2 HfuturesX i i c1 c2 HD1 HD2).\n  Qed.\n\n  Lemma final_and_consistent_implies_consistent\n      (Hcons : final_and_consistent)\n      : consistent.\n  Proof.\n    unfold consistent; intros.\n    apply (Hcons s1 s2 Hfuture j k c1 c2 HDecided1 HDecided2).\n  Qed.\n\n  Definition live :=\n    forall (tr : @Trace _ (type X)),\n      complete_trace_prop X tr ->\n      exists (s : vstate X) (n : nat) (i : index) (c : C),\n        trace_nth tr n = Some s /\\\n        (ID i) (s i) = Some c.\n\nEnd CommuteIndexed.\n\n(* Section 5 *)\n\nSection Estimators.\n\n  (* Defining the estimator function as a relation *)\n  Class Estimator state C :=\n    { estimator : state -> C -> Prop\n    ; estimator_total : forall s : state, exists c : C, estimator s c\n    }.\n\n  Context\n    {CV : consensus_values}\n    {message : Type}\n    (X : VLSM message)\n    (D : vdecision X)\n    (E : Estimator (vstate X) C)\n    (estimates := @estimator _ _ E)\n    .\n\n  Definition decision_estimator_property\n    := forall\n      (sigma : vstate X)\n      (c : C)\n      (HD : D sigma = Some c)\n      (sigma' : vstate X)\n      (Hreach : in_futures X sigma sigma')\n      (c' : C)\n      (Hc' : estimates sigma' c'),\n      c' = c.\n\n  Lemma estimator_only_has_decision\n    (Hde : decision_estimator_property)\n    (s : protocol_state X)\n    (c c_other : C)\n    (Hc  : D (proj1_sig s) = (Some c))\n    (Hc_other : estimates (proj1_sig s) c_other)\n    : c_other = c.\n  Proof.\n    intros.\n    destruct s as [s Hs].\n    apply Hde with (sigma := s) (sigma':= s); try assumption.\n    apply in_futures_refl.\n    assumption.\n  Qed.\n\n  Lemma estimator_surely_has_decision\n    (Hde : decision_estimator_property)\n    (s : protocol_state X)\n    (c : C)\n    (Hc  : D (proj1_sig s) = (Some c))\n    : estimates (proj1_sig s) c.\n   Proof.\n    intros.\n    assert(Hc_other : exists (c_other : C), (estimates (proj1_sig s) c_other)). {\n      apply estimator_total.\n    }\n    destruct Hc_other as [c_other Hc_other].\n    destruct s as [s Hs].\n    assert (Heq : c_other = c). {\n      apply Hde with (sigma := s) (sigma' := s); try assumption.\n      apply in_futures_refl.\n      assumption.\n    }\n    rewrite <- Heq.\n    assumption.\n   Qed.\n\n  (* We use the following intermediate result,\n     proven above (in two steps) via the estimator property:\n     (1) If D(state) = Some c then Estimator(state) = {c}.\n\n     We then fix s1 and s2, such that (in_futures s1 s2) and both are decided and note the following:\n     (2) Estimator(s2) = {Decision(s2)}, by (1)\n     (3) Estimator(s2) = {Decision(s1)}, by the estimator property.\n\n     Thus Decision(s2) = Decision(s1).\n   *)\n\n  Theorem decision_estimator_finality\n    : decision_estimator_property -> final X D.\n  Proof.\n    intros.\n    unfold final.\n    intros.\n    specialize (in_futures_protocol_snd X s1 s2 H0); intro Hps2.\n    apply estimator_only_has_decision with (s := (exist _ s2 Hps2)).\n    assumption.\n    assumption.\n    unfold decision_estimator_property in H.\n    assert(c2 = c1). {\n      apply H with (sigma := s1) (sigma' := s2).\n      assumption.\n      assumption.\n      apply (estimator_surely_has_decision H (exist _ s2 Hps2)).\n      assumption.\n    }\n    rewrite <- H3.\n    apply estimator_surely_has_decision.\n    assumption.\n    assumption.\n   Qed.\nEnd Estimators.\n\nSection composite_estimators.\n\n  Context\n    {CV : consensus_values}\n    {message : Type}\n    {index : Type}\n    {Heqd : EqDecision index}\n    (IM : index -> VLSM message)\n    {Hi : Inhabited index}\n    (constraint : composite_label IM -> composite_state IM * option message -> Prop)\n    (X := composite_vlsm IM constraint)\n    (ID : forall i : index, vdecision (IM i))\n    (IE : forall i : index, Estimator (vstate (IM i)) C).\n\n  Definition composite_projection_decision_estimator_property\n    (i : index)\n    (Xi := composite_vlsm_constrained_projection IM constraint i)\n    := decision_estimator_property Xi (ID i) (IE i).\n\nEnd composite_estimators.\n", "meta": {"author": "zunction", "repo": "casper-cbc-proofs", "sha": "92493810dd32a8301882f9eb8a0488a6ac9d0cd1", "save_path": "github-repos/coq/zunction-casper-cbc-proofs", "path": "github-repos/coq/zunction-casper-cbc-proofs/casper-cbc-proofs-92493810dd32a8301882f9eb8a0488a6ac9d0cd1/VLSM/Decisions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2309994032432434}}
{"text": "(** * Compiler Example *)\n(** This example illustrates the use of path-dependent types of length\n    greater than one which allows us to encode recursion between types in\n    nested modules *)\n\nRequire Import ExampleTactics.\nRequire Import String.\n\nSection CompilerExample.\n\nVariables DottyCore Tpe Symbol : typ_label.\nVariables dottyCore types typeRef symbols symbol symb tpe denotation srcPos : trm_label.\n\nNotation TpeImpl := (μ(typ_rcd {denotation ⦂ Id})).\nNotation SymbolImpl := (μ(typ_rcd {srcPos ⦂ Id})).\n\nHypothesis TS: types <> symbols.\nHypothesis ST: symb <> denotation.\nHypothesis TS': tpe <> srcPos.\n\nNotation typesType tpe_lower tpe_upper :=\n  (typ_rcd {Tpe >: tpe_lower <: tpe_upper} ∧\n     typ_rcd {typeRef ⦂ ∀(super•symbols↓Symbol)\n                         (super↓Tpe ∧ (typ_rcd {symb ⦂ ssuper•symbols↓Symbol}))}).\nNotation symbolsType symb_lower symb_upper :=\n  (typ_rcd {Symbol >: symb_lower <: symb_upper} ∧\n   typ_rcd {symbol ⦂ ∀(super•types↓Tpe)\n                      (super↓Symbol ∧ (typ_rcd {tpe ⦂ ssuper•types↓Tpe}))}).\nNotation DottyCorePackage tpe_lower tpe_upper symb_lower symb_upper :=\n  (typ_rcd {types ⦂ μ(typesType tpe_lower tpe_upper)} ∧\n   typ_rcd {symbols ⦂ μ(symbolsType symb_lower symb_upper)}).\n\nNotation DottyCoreAbstract := (DottyCorePackage ⊥ ⊤ ⊥ ⊤).\nNotation DottyCoreTight := (DottyCorePackage TpeImpl TpeImpl SymbolImpl SymbolImpl).\n\nDefinition t := (trm_val\n(ν(typ_rcd {DottyCore >: μ DottyCoreAbstract <: μ DottyCoreAbstract} ∧\n   typ_rcd {dottyCore ⦂ Lazy (super ↓ DottyCore)})\n  defs_nil Λ\n  {DottyCore ⦂= μ DottyCoreAbstract} Λ\n  {dottyCore :=\n     lazy (let_trm (trm_val (ν(DottyCoreTight)\n                              defs_nil Λ\n                              {types :=\n                                 defv (ν(typesType TpeImpl TpeImpl)\n                                        defs_nil Λ\n                                        {Tpe ⦂= TpeImpl} Λ\n                                        {typeRef :=\n                                           defv (λ(super•symbols↓Symbol)\n                                                  (let_trm (trm_val (ν(typ_rcd {symb ⦂ ({{ super }}) } ∧\n                                                                       typ_rcd {denotation ⦂ Id})\n                                                                      defs_nil Λ\n                                                                      {symb := defp super} Λ\n                                                                      {denotation := defv id})))) }) } Λ\n                              {symbols :=\n                                 defv (ν(symbolsType SymbolImpl SymbolImpl)\n                                        defs_nil Λ\n                                        {Symbol ⦂= SymbolImpl} Λ\n                                        {symbol :=\n                                           defv (λ(super•types↓Tpe)\n                                                  (let_trm (trm_val (ν(typ_rcd {tpe ⦂ {{ super }}} ∧\n                                                                       typ_rcd {srcPos ⦂ Id})\n                                                                      defs_nil Λ\n                                                                      {tpe := defp super} Λ\n                                                                      {srcPos := defv id}))))})})))})).\n\nNotation T :=\n  (μ(typ_rcd {DottyCore >: μ DottyCoreAbstract <: μ DottyCoreAbstract} ∧\n     typ_rcd {dottyCore ⦂ Lazy (super ↓ DottyCore)})).\n\nLemma compiler_typecheck :\n  empty ⊢ t : T.\nProof.\n  fresh_constructor. repeat apply ty_defs_cons; crush.\n  - Case \"dottyCore\"%string.\n    constructor. fresh_constructor. crush.\n    fresh_constructor.\n    + fresh_constructor. crush.\n      apply ty_defs_cons; crush.\n      * SCase \"types\"%string.\n        apply ty_defs_one. eapply ty_def_new; eauto.\n        { econstructor. constructor*. simpl. auto. }\n        crush. apply ty_defs_cons; crush.\n\n        constructor. fresh_constructor. crush. fresh_constructor.\n        *** remember_ctx G.\n            fresh_constructor. crush.\n            apply ty_defs_cons; crush.\n            **** apply ty_defs_one.\n                 econstructor.\n                 eapply ty_sub.\n                 ***** rewrite HeqG. constructor*.\n                 ***** eapply subtyp_sel1. rewrite proj_rewrite.\n                 constructor. apply ty_rcd_intro.\n                 eapply ty_sub. apply ty_rec_elim. constructor.\n                 eapply ty_sub. rewrite HeqG. constructor*. eauto.\n                 crush.\n            **** constructor. fresh_constructor. crush.\n        *** match goal with\n            | H: _ |- _ & ?y0 ~ ?T0' & ?y1 ~ ?T1' & ?y2 ~ ?T2' ⊢ _ : _ =>\n              remember T0' as T0; remember T1' as T1; remember T2' as T2\n            end.\n            remember_ctx G.\n            assert (binds y2 T2 G) as Hb%ty_var by rewrite* HeqG. crush.\n            apply ty_and_intro.\n            **** rewrite proj_rewrite. eapply ty_sub.\n                 2: {\n                   eapply subtyp_sel2. eapply ty_sub. apply ty_rec_elim. constructor.\n                   assert (binds y0 T0 G) as Hb'%ty_var by rewrite* HeqG.\n                   rewrite HeqT0 in Hb'. eapply ty_sub; eauto.\n                   unfold open_typ_p. rewrite HeqT1. simpl. eauto.\n                 }\n                 apply ty_rec_intro. crush.\n                 rewrite HeqT2 in Hb. apply ty_rec_elim in Hb.\n                 eapply ty_sub. eauto. crush.\n            **** assert (binds y0 T0 G) as Hb' by rewrite* HeqG.\n                 rewrite HeqT0 in Hb'. apply ty_var in Hb'.\n                 match goal with\n                 | H: _ ⊢ tvar y0 : ?T0''' ∧ ?T0'' |- _ =>\n                   remember T0'' as T0'; remember T0''' as T01\n                 end.\n                 rewrite HeqT2 in Hb.\n                 apply ty_rec_elim in Hb. unfold open_typ_p in Hb.\n                 simpl in *. rewrite HeqT1. rewrite proj_rewrite.\n                 apply ty_rcd_intro.\n                 eapply ty_sub.\n                 2: {\n                   eapply subtyp_sel2.\n                   assert (G ⊢ tvar y0 : T0') as Hy0 by eauto.\n                   rewrite HeqT0' in Hy0. apply ty_new_elim in Hy0.\n                   apply ty_rec_elim in Hy0. unfold open_typ_p in Hy0. simpl in *.\n                   eapply ty_sub. apply Hy0. crush.\n                 }\n                 eapply ty_sub. eapply ty_sngl. constructor. eapply ty_sub. apply Hb.\n                 eauto. rewrite HeqG. constructor*. rewrite HeqT1.\n                 eapply subtyp_sel1.\n                 assert (G ⊢ tvar y0 : T0') as Hy0 by eauto.\n                 rewrite HeqT0' in Hy0. apply ty_new_elim, ty_rec_elim in Hy0.\n                 unfold open_typ_p in Hy0. simpl in *. eapply ty_sub.\n                 apply Hy0. eauto.\n      * eapply ty_def_new; eauto.\n        { repeat econstructor. }\n        crush. apply ty_defs_cons; crush.\n        constructor. fresh_constructor. crush.\n        fresh_constructor.\n        *** remember_ctx G.\n            fresh_constructor. crush.\n            apply ty_defs_cons; crush.\n            **** apply ty_defs_one.\n                 econstructor.\n                 eapply ty_sub.\n                 ***** rewrite HeqG. constructor*.\n                 ***** eapply subtyp_sel1. rewrite proj_rewrite.\n                 constructor. apply ty_rcd_intro.\n                 eapply ty_sub. apply ty_rec_elim. constructor.\n                 eapply ty_sub. rewrite HeqG. constructor*. eauto. crush.\n            **** constructor. fresh_constructor. crush.\n        *** match goal with\n            | H: _ |- _ & ?y0 ~ ?T0' & ?y1 ~ ?T1' & ?y2 ~ ?T2' ⊢ _ : _ =>\n              remember T0' as T0; remember T1' as T1; remember T2' as T2\n            end.\n            remember_ctx G.\n            assert (binds y2 T2 G) as Hb%ty_var by rewrite* HeqG. crush.\n            apply ty_and_intro.\n            **** rewrite proj_rewrite. eapply ty_sub.\n                 2: {\n                   eapply subtyp_sel2. eapply ty_sub. apply ty_rec_elim. constructor.\n                   assert (binds y0 T0 G) as Hb'%ty_var by rewrite* HeqG.\n                   rewrite HeqT0 in Hb'. eapply ty_sub; eauto. crush.\n                 }\n                 apply ty_rec_intro. crush.\n                 rewrite HeqT2 in Hb. apply ty_rec_elim in Hb.\n                 eapply ty_sub. eauto. crush.\n            **** assert (binds y0 T0 G) as Hb' by rewrite* HeqG.\n                 rewrite HeqT0 in Hb'. apply ty_var in Hb'.\n                 match goal with\n                 | H: _ ⊢ tvar y0 : ?T0''' ∧ ?T0'' |- _ =>\n                   remember T0'' as T01; remember T0''' as T0'\n                 end.\n                 rewrite HeqT2 in Hb.\n                 apply ty_rec_elim in Hb. unfold open_typ_p in Hb.\n                 simpl in *. rewrite HeqT1. rewrite proj_rewrite.\n                 apply ty_rcd_intro.\n                 eapply ty_sub.\n                 2: {\n                   eapply subtyp_sel2.\n                   assert (G ⊢ tvar y0 : T0') as Hy0 by eauto.\n                   rewrite HeqT0' in Hy0. apply ty_new_elim in Hy0.\n                   apply ty_rec_elim in Hy0. unfold open_typ_p in Hy0. simpl in *.\n                   eapply ty_sub. apply Hy0. case_if. eauto.\n                 }\n                 eapply ty_sub. eapply ty_sngl. constructor. eapply ty_sub. apply Hb.\n                 eauto. rewrite HeqG. constructor*. rewrite HeqT1.\n                 eapply subtyp_sel1.\n                 assert (G ⊢ tvar y0 : T0') as Hy0 by eauto.\n                 rewrite HeqT0' in Hy0. apply ty_new_elim, ty_rec_elim in Hy0.\n                 unfold open_typ_p in Hy0. simpl in *. eapply ty_sub.\n                 apply Hy0. eauto.\n    + unfold open_trm. simpl. case_if.\n      match goal with\n      | H: _ |- ?G' & _ ~ ?T0' ⊢ _ : _ =>\n        remember G' as G; remember T0' as T0\n      end.\n      assert (binds y0 T0 (G & y0 ~ T0)) as Hb%ty_var by auto.\n      rewrite HeqT0 in Hb. apply ty_rec_elim in Hb.\n      eapply ty_sub. 2: {\n        repeat rewrite <- concat_assoc in HeqG.\n        rewrite concat_empty_l in HeqG.\n        match goal with\n        | H: G = z ~ ?Tz' & _ |- _ =>\n          remember Tz' as Tz\n        end.\n        assert (binds z Tz (G & y0 ~ T0)) as Hz%ty_var. {\n          rewrite HeqG. repeat eapply binds_concat_left; auto. apply binds_single_eq.\n        }\n        eapply subtyp_sel2. rewrite HeqTz in Hz.\n        eapply ty_sub. apply Hz. eauto.\n      }\n      apply ty_rec_intro.\n      unfold open_typ_p in *. simpl in *. repeat case_if.\n      match goal with\n      | H: _ ⊢ trm_path (pvar y0) : ?U' ∧ ?U'' |- _ =>\n        remember U' as S; remember U'' as U\n      end.\n      apply ty_and_intro.\n      * assert (G & y0 ~ T0 ⊢ tvar y0 : S) as Ht. {\n          rewrite HeqS, HeqT0. eapply ty_sub. apply Hb. rewrite HeqS. eauto.\n        }\n        rewrite HeqS in Ht. apply ty_rcd_intro.\n        apply ty_new_elim in Ht. apply ty_rec_intro. apply ty_rec_elim in Ht.\n        unfold open_typ_p in *. simpl in *. case_if.\n        apply ty_and_intro.\n        ** eapply ty_sub.\n           2: {\n             apply subtyp_typ. apply subtyp_bot. apply subtyp_top.\n           }\n           eapply ty_sub. apply Ht. eauto.\n        ** eapply ty_sub. apply Ht. eauto.\n      * assert (G & y0 ~ T0 ⊢ tvar y0 : U) as Ht. {\n          rewrite HeqU, HeqT0. eapply ty_sub. apply Hb. rewrite HeqU. eauto.\n        }\n        rewrite HeqU in Ht. apply ty_rcd_intro.\n        apply ty_new_elim in Ht. apply ty_rec_intro. apply ty_rec_elim in Ht.\n        unfold open_typ_p in *. simpl in *. case_if.\n        apply ty_and_intro.\n        ** eapply ty_sub.\n           2: {\n             apply subtyp_typ. apply subtyp_bot. apply subtyp_top.\n           }\n           eapply ty_sub. apply Ht. eauto.\n        ** eapply ty_sub. apply Ht. eauto.\nQed.\n\nEnd CompilerExample.\n", "meta": {"author": "Linyxus", "repo": "extended-pdot-calculus", "sha": "63292fb068514f3c6e039140bbe8a66276071f28", "save_path": "github-repos/coq/Linyxus-extended-pdot-calculus", "path": "github-repos/coq/Linyxus-extended-pdot-calculus/extended-pdot-calculus-63292fb068514f3c6e039140bbe8a66276071f28/src/CompilerExample.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2308893694745665}}
{"text": "(** This file proves the basic laws of the HeapLang program logic by applying\nthe Iris lifting lemmas. *)\n\nFrom iris.proofmode Require Import proofmode.\nFrom iris.bi.lib Require Import fractional.\nFrom transfinite.base_logic.lib Require Export gen_heap proph_map gen_inv_heap.\nFrom melocoton.language Require Export weakestpre lifting.\nFrom melocoton.c_interface Require Export resources.\nFrom melocoton.c_lang Require Export class_instances.\nFrom melocoton.c_lang Require Import tactics notation.\nFrom iris.prelude Require Import options.\n\nGlobal Program Instance heapG_langG_C {SI:indexT} `{heapG_C Σ}\n      : langG val C_lang Σ := {\n  state_interp σ := public_state_interp σ\n}.\n\nSection lifting.\nContext {SI:indexT}.\nContext `{!heapG_C Σ, !invG Σ}.\nContext {p:prog_environ C_lang Σ}.\nImplicit Types P Q : iProp Σ.\nImplicit Types Φ Ψ : val → iProp Σ.\nImplicit Types efs : list expr.\nImplicit Types σ : gmap loc heap_cell.\nImplicit Types v : val.\nImplicit Types l : loc.\n\n(*\n#[global] Instance wp'': Wp (iProp Σ) expr val stuckness := (@wp' (C_lang p) Σ _).\n#[global] Instance twp'': Twp (iProp Σ) expr val stuckness := (@twp' (C_lang p) Σ _).\n*)\n\n(** Recursive functions: we do not use this lemmas as it is easier to use Löb\ninduction directly, but this demonstrates that we can state the expected\nreasoning principle for recursive functions, without any visible ▷. *)\nLemma wp_rec_löb s E f e args Φ (Ψ : list val → iProp Σ) :\n   ⌜penv_prog s !! f = Some (Fun args e)⌝ -∗\n  □ ( □ (∀ vs res, Ψ vs -∗ ⌜zip_args args vs = Some res⌝ -∗ WP (FunCall ((&f)%V) (map Val vs)) @ s; E {{ Φ }}) -∗\n     ∀ vs res, Ψ vs -∗ ⌜zip_args args vs = Some res⌝ -∗ WP (subst_all res e) @ s; E {{ Φ }}) -∗\n  ∀ vs res , Ψ vs -∗ ⌜zip_args args vs = Some res⌝ -∗ WP (FunCall ((&f)%V) (map Val vs)) @ s; E {{ Φ }}.\nProof.\n  iIntros \"%Hp #Hrec\". iLöb as \"IH\". iIntros (v res) \"HΨ %Hres\".\n  iApply lifting.wp_pure_step_later. 1: eauto.\n  iIntros \"!>\". iApply (\"Hrec\" with \"[] HΨ\"). 2:done. iIntros \"!>\" (w res') \"HΨ %Hres'\".\n  iApply (\"IH\" with \"HΨ\"). iPureIntro. apply Hres'.\nQed.\n\n\nLemma wp_Malloc_seq E n :\n  (0 < n)%Z →\n  {{{ True }}} Malloc (Val $ LitV $ LitInt $ n) @ p; E\n  {{{ l, RET LitV (LitLoc l); [∗ list] i ∈ seq 0 (Z.to_nat n),\n      (l +ₗ (i : nat)) ↦C ? ∗ meta_token (l +ₗ (i : nat)) ⊤ }}}.\nProof.\n  iIntros (Hn Φ) \"_ HΦ\". iApply wp_lift_atomic_head_step; first done.\n  iIntros (σ1) \"Hσ\". iModIntro. iSplit; first (destruct n; eauto with lia head_step).\n  iIntros (e2 σ2 Hstep). inv_head_step. iModIntro.\n  iMod (gen_heap_alloc_big _ (heap_array _ (replicate (Z.to_nat n) Uninitialized)) with \"Hσ\")\n    as \"(Hσ & Hl & Hm)\".\n  { apply heap_array_map_disjoint.\n    rewrite replicate_length Z2Nat.id; auto with lia. }\n  iModIntro. iFrame. iApply \"HΦ\".\n  iApply big_sepL_sep. iSplitL \"Hl\".\n  - by iApply heap_array_to_seq_mapsto.\n  - iApply (heap_array_to_seq_meta with \"Hm\"). by rewrite replicate_length.\nQed.\n\nLemma wp_free s E l (v:option val) :\n  {{{ ▷ l O↦C (Some v) }}} Free (Val $ LitV $ LitLoc l) (Val $ LitV $ LitInt 1) @ s; E\n  {{{ RET LitV LitUnit; True }}}.\nProof.\n  iIntros (Φ) \"> Hl HΦ\". iApply (wp_step with \"HΦ\"). iApply wp_lift_atomic_head_step; first done.\n  iIntros (σ1) \"Hσ\". iDestruct (gen_heap_valid with \"Hσ Hl\") as \"%HH\". iModIntro.\n  iSplitR; first ( iPureIntro ).\n  1: { do 2 eexists. econstructor.\n       intros i H1 H2. exists v. rewrite <- HH. f_equal.\n       destruct l; cbn. unfold loc_add. f_equal. cbn. lia. }\n  iIntros (e2 σ2 Hstep); inv_head_step. iModIntro.\n  rewrite state_init_heap_singleton.\n  iMod (gen_heap_update (σ1) l (Some v) Deallocated with \"Hσ Hl\") as \"[$ Hl]\".\n  iModIntro. iFrame. iIntros \"HΦ\". iModIntro. by iApply \"HΦ\".\nQed.\n\nLemma wp_load s E l dq v :\n  {{{ ▷ l ↦C{dq} v }}} Load (Val $ LitV $ LitLoc l) @ s; E {{{ RET v; l ↦C{dq} v }}}.\nProof.\n  iIntros (Φ) \"> Hl HΦ\". iApply (wp_step with \"HΦ\"). iApply wp_lift_atomic_head_step; first done.\n  iIntros (σ1) \"Hσ\". iDestruct (gen_heap_valid with \"Hσ Hl\") as \"%HH\". iModIntro.\n  iSplitR; first ( iPureIntro; eauto with head_step).\n  iIntros (e2 σ2 Hstep); inv_head_step. iModIntro.\n  iModIntro. iFrame. iIntros \"HΦ\". iModIntro.\n  by iApply \"HΦ\".\nQed.\n\nLemma wp_store s E l (v':option val) v :\n  {{{ ▷ l O↦C Some v' }}} Store (Val $ LitV $ LitLoc l) (Val v) @ s; E\n  {{{ RET LitV LitUnit; l ↦C v }}}.\nProof.\n  iIntros (Φ) \"> Hl HΦ\". iApply (wp_step with \"HΦ\"). iApply wp_lift_atomic_head_step; first done.\n  iIntros (σ1) \"Hσ !>\". iDestruct (gen_heap_valid with \"Hσ Hl\") as %?.\n  iSplit; first by eauto with head_step.\n  iIntros (e2 σ2 Hstep); inv_head_step. iModIntro.\n  iMod (gen_heap_update with \"Hσ Hl\") as \"[$ Hl]\".\n  iModIntro. iFrame. iIntros \"HΦ\". iModIntro. by iApply \"HΦ\".\nQed.\n\nLemma wp_call' (s:prog_environ C_lang Σ) n args body body' vv E Φ :\n     ⌜(penv_prog s) !! n = Some (Fun args body)⌝\n  -∗ ⌜apply_function (Fun args body) vv = Some body'⌝\n  -∗ (|={E}=> ▷ |={E}=> WP body' @ s ; E {{v, Φ v}})\n  -∗ WP (FunCall ((&n)) (map Val vv)) @ s ; E {{v, Φ v}}.\nProof.\n  iIntros (Hlookup Happly) \"Hcont\". iApply wp_lift_step_fupd.\n  { cbv -[map unmap_val]. now rewrite map_unmap_val. }\n  iIntros (σ1) \"Hσ !>\".\n  iSplit.\n  { iPureIntro. eexists _,_. apply head_prim_step. econstructor; done. }\n  iIntros (v2 σ2 Hstep).\n  apply head_reducible_prim_step in Hstep; last by eauto with head_step.\n  inv_head_step. iMod \"Hcont\". do 2 iModIntro.\n  iMod \"Hcont\".\n  do 2 iModIntro. iFrame.\nQed.\n\nLemma wp_call (s:prog_environ C_lang Σ) n args body body' vv E Φ :\n     ⌜penv_prog s !! n = Some (Fun args body)⌝\n  -∗ ⌜apply_function (Fun args body) vv = Some body'⌝\n  -∗ (WP body' @ s ; E {{v, Φ v}})\n  -∗ WP (FunCall ((&n)) (map Val vv)) @ s ; E {{v, Φ v}}.\nProof.\n  iIntros (Hlookup Happly) \"Hcont\".\n  iApply wp_call'. 1-2: done. do 3 iModIntro. done.\nQed.\n\nEnd lifting.\n", "meta": {"author": "logsem", "repo": "melocoton", "sha": "b77eecc3381f53db0eb3c4cf1314e881a8dc41b3", "save_path": "github-repos/coq/logsem-melocoton", "path": "github-repos/coq/logsem-melocoton/melocoton-b77eecc3381f53db0eb3c4cf1314e881a8dc41b3/theories/c_lang/primitive_laws.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2308893694745665}}
{"text": "(* Standard library imports *)\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Program.Equality.\nImport ListNotations.\n(* Project related imports *)\nRequire Import GenericLemmas.\nRequire Import Names.\nRequire Import AST.\nRequire Import UtilsProgram.\nRequire Import UtilsSkeleton.\nRequire Import Skeleton.\nRequire Import Typechecker.\nRequire Import CtorizeI.\nRequire Import LiftComatch.\nRequire Import Subterm.\n(*Require Import FunInd.*)\n\n(**************************************************************************************************)\n(** * Constructorization Part II:                                                                *)\n(**                                                                                               *)\n(** In the second part of the algorithm we compute the new function bodies.                       *)\n(**************************************************************************************************)\n\nFixpoint constructorize_expr (tn : TypeName) (e : expr) : expr :=\n  match e with\n  | E_Var n => E_Var n\n  | E_Constr sn es => E_Constr sn (map (constructorize_expr tn) es)\n  | E_DestrCall sn e es =>\n      if eq_TypeName tn (fst (unscope sn))\n      then E_ConsFunCall sn (constructorize_expr tn e) (map (constructorize_expr tn) es)\n      else E_DestrCall sn (constructorize_expr tn e) (map (constructorize_expr tn) es)\n  | E_FunCall n es => E_FunCall n (map (constructorize_expr tn) es)\n  | E_GenFunCall sn es =>\n      if eq_TypeName tn (fst (unscope sn))\n      then E_Constr sn (map (constructorize_expr tn) es)\n      else E_GenFunCall sn (map (constructorize_expr tn) es)\n  | E_ConsFunCall sn e es => E_ConsFunCall sn (constructorize_expr tn e) (map (constructorize_expr tn) es)\n  | E_Match qn e bs cases t =>\n      E_Match qn (constructorize_expr tn e)\n              (map (fun x => (constructorize_expr tn (fst x), snd x)) bs)\n              (map (fun x => (fst x, constructorize_expr tn (snd x))) cases) t\n  | E_CoMatch qn bs cocases =>\n      (* Without lift/inline, we would have a case distinction... *)\n      (*\n      if eq_TypeName tn (fst qn)\n      (* ...but this case may actually never occur (and will not, thanks to comatch lifting) *)\n      then E_Constr (local qn) (map (fun x => constructorize_expr tn (fst x)) bs)\n      else *)\n      E_CoMatch qn (map (fun x => (constructorize_expr tn (fst x), snd x)) bs)\n                   (map (fun x => (fst x, constructorize_expr tn (snd x))) cocases)\n  | E_Let e1 e2 => E_Let (constructorize_expr tn e1) (constructorize_expr tn e2)\n  end.\n\n\nLemma filter_compose : forall {A} (l : list A) f g,\n  filter f (filter g l) = filter (fun x => andb (f x) (g x)) l.\nProof with auto.\nintros. induction l... simpl. case_eq (g a); intros.\n- case_eq (f a); intros.\n  + simpl. rewrite H0. f_equal...\n  + simpl. rewrite H0...\n- case_eq (f a); intros...\nQed.\n\n\nLemma constructorize_expr_preserves_typing : forall p tn e ctx t,\n  (forall e' n bs cocases, subterm e' e -> e' <> E_CoMatch (tn,n) bs cocases) ->\n  (program_skeleton p) / ctx |- e : t ->\n  (constructorize_to_skeleton p tn) / ctx |- (constructorize_expr tn e) : t.\nProof with try apply in_eq; try apply in_cons; eauto.\nintros. generalize dependent ctx. generalize dependent t. generalize H. clear H.\ninduction e using expr_strong_ind; intros.\n- inversion H0; subst. apply T_Var...\n- inversion H1; subst. simpl. apply T_Constr with (cargs:=cargs)...\n  + simpl. apply in_or_app. right...\n  + clear - H H0 H7.\n    assert (forall x y n bs cocases, In x ls -> subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n    { clear - H0. intros. apply H0. eapply Sub_Trans... apply Sub_Constr... }\n    clear H0. induction H7; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n    * inversion H; subst. apply H4... intros. apply H1 with (x:=e)...\n    * apply IHListTypeDeriv; try inversion H... intros. apply H1 with (x:=x0)...\n- simpl. case_eq (eq_TypeName tn (fst (unscope n))); intros.\n  + inversion H1; subst. destruct n.\n    * apply T_LocalConsFunCall with (argts:=dargs).\n      -- simpl. unfold new_cfunsigs_l. apply in_or_app. left.\n         rewrite in_map_iff. unfold cfunsigs_mapfun. exists (local q, dargs, t).\n         split... rewrite filter_In. split...\n      -- apply IHe... intros. unfold not in *. intros. eapply H0...\n         eapply Sub_Trans... apply Sub_DestrCall_e0...\n      -- assert (forall x y n bs cocases, In x ls -> subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n         { clear - H0. intros. apply H0. eapply Sub_Trans... apply Sub_DestrCall_es... }\n         clear - H H11 H3. induction H11; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n         ++ inversion H; subst. apply H4... intros. apply H3 with (x:=e)...\n         ++ apply IHListTypeDeriv; try inversion H... intros. apply H3 with (x:=x0)...\n    * apply T_GlobalConsFunCall with (argts:=dargs).\n      -- simpl. unfold new_cfunsigs_g. apply in_or_app. left.\n         rewrite in_map_iff. unfold cfunsigs_mapfun. exists (global q, dargs, t).\n         split... rewrite filter_In. split...\n      -- apply IHe... intros. unfold not in *. intros. eapply H0...\n         eapply Sub_Trans... apply Sub_DestrCall_e0...\n      -- assert (forall x y n bs cocases, In x ls -> subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n         { clear - H0. intros. apply H0. eapply Sub_Trans... apply Sub_DestrCall_es... }\n         clear - H H11 H3. induction H11; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n         ++ inversion H; subst. apply H4... intros. apply H3 with (x:=e)...\n         ++ apply IHListTypeDeriv; try inversion H... intros. apply H3 with (x:=x0)...\n  + inversion H1; subst. apply T_DestrCall with (dargs:=dargs).\n    * simpl. unfold new_dtors. rewrite filter_In. split... rewrite H2...\n    * apply IHe... intros. unfold not in *. intros. eapply H0...\n      eapply Sub_Trans... apply Sub_DestrCall_e0...\n    * assert (forall x y n bs cocases, In x ls -> subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n      { clear - H0. intros. apply H0. eapply Sub_Trans... apply Sub_DestrCall_es... }\n      clear - H H11 H3. induction H11; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n      ++ inversion H; subst. apply H4... intros. apply H3 with (x:=e)...\n      ++ apply IHListTypeDeriv; try inversion H... intros. apply H3 with (x:=x0)...\n- inversion H1; subst. simpl. apply T_FunCall with (argts:=argts)...\n  clear - H H0 H8.\n  assert (forall x y n bs cocases, In x ls -> subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n  { clear - H0. intros. apply H0. eapply Sub_Trans... apply Sub_FunCall... }\n  clear H0. induction H8; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n  * inversion H; subst. apply H4... intros. apply H1 with (x:=e)...\n  * apply IHListTypeDeriv; try inversion H... intros. apply H1 with (x:=x0)...\n- inversion H1; subst.\n  + simpl. apply T_GlobalConsFunCall with (argts:=argts).\n    * simpl. unfold new_cfunsigs_g. apply in_or_app...\n    * apply IHe... intros. unfold not in *. intros. eapply H0...\n      eapply Sub_Trans... apply Sub_ConsFunCall_e0...\n    * assert (forall x y n bs cocases, In x ls -> subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n      { clear - H0. intros. apply H0. eapply Sub_Trans... apply Sub_ConsFunCall_es... }\n      clear - H H10 H2. induction H10; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n      -- inversion H; subst. apply H4... intros. apply H2 with (x:=e)...\n      -- apply IHListTypeDeriv; try inversion H... intros. apply H2 with (x:=x0)...\n  + simpl. apply T_LocalConsFunCall with (argts:=argts).\n    * simpl. unfold new_cfunsigs_g. apply in_or_app...\n    * apply IHe... intros. unfold not in *. intros. eapply H0...\n      eapply Sub_Trans... apply Sub_ConsFunCall_e0...\n    * assert (forall x y n bs cocases, In x ls -> subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n      { clear - H0. intros. apply H0. eapply Sub_Trans... apply Sub_ConsFunCall_es... }\n      clear - H H10 H2. induction H10; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n      -- inversion H; subst. apply H4... intros. apply H2 with (x:=e)...\n      -- apply IHListTypeDeriv; try inversion H... intros. apply H2 with (x:=x0)...\n- simpl. case_eq (eq_TypeName tn (fst (unscope sn))); intros.\n  + inversion H1; subst.\n    * apply T_Constr with (cargs:=argts)...\n      -- simpl. unfold computeNewDatatype. apply in_or_app. left. apply in_or_app. left.\n         rewrite in_map_iff. exists (qn, argts). split... rewrite filter_In. split...\n         simpl in *. rewrite eq_TypeName_symm...\n      -- assert (forall x y n bs cocases, In x ls -> subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n         { clear - H0. intros. apply H0. eapply Sub_Trans... apply Sub_GenFunCall... }\n         clear - H H9 H3. induction H9; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n         ++ inversion H; subst. apply H4... intros. apply H3 with (x:=e)...\n         ++ apply IHListTypeDeriv; try inversion H... intros. apply H3 with (x:=x0)...\n    * apply T_Constr with (cargs:=argts)...\n      -- simpl. unfold computeNewDatatype. apply in_or_app. left. apply in_or_app. right.\n         rewrite in_map_iff. exists (qn, argts). split... rewrite filter_In. split...\n         simpl in *. rewrite eq_TypeName_symm...\n      -- assert (forall x y n bs cocases, In x ls -> subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n         { clear - H0. intros. apply H0. eapply Sub_Trans... apply Sub_GenFunCall... }\n         clear - H H9 H3. induction H9; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n         ++ inversion H; subst. apply H4... intros. apply H3 with (x:=e)...\n         ++ apply IHListTypeDeriv; try inversion H... intros. apply H3 with (x:=x0)...\n  + inversion H1; subst.\n    * apply T_GlobalGenFunCall with (argts:=argts).\n      -- simpl. unfold new_gfunsigs_g. rewrite filter_In. split... simpl in *. rewrite H2...\n      -- assert (forall x y n bs cocases, In x ls -> subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n         { clear - H0. intros. apply H0. eapply Sub_Trans... apply Sub_GenFunCall... }\n         clear - H H9 H3. induction H9; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n         ++ inversion H; subst. apply H4... intros. apply H3 with (x:=e)...\n         ++ apply IHListTypeDeriv; try inversion H... intros. apply H3 with (x:=x0)...\n    * apply T_LocalGenFunCall with (argts:=argts).\n      -- simpl. unfold new_gfunsigs_l. rewrite filter_In. split... simpl in *. rewrite H2...\n      -- assert (forall x y n bs cocases, In x ls -> subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n         { clear - H0. intros. apply H0. eapply Sub_Trans... apply Sub_GenFunCall... }\n         clear - H H9 H3. induction H9; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n         ++ inversion H; subst. apply H4... intros. apply H3 with (x:=e)...\n         ++ apply IHListTypeDeriv; try inversion H... intros. apply H3 with (x:=x0)...\n- simpl. inversion H2; subst.\n  apply T_Match with (bindings_exprs := map (constructorize_expr tn) bindings_exprs)\n    (bindings_types := bindings_types) (ctorlist := ctorlist).\n  + apply IHe... intros. unfold not in *. apply H1. eapply Sub_Trans... apply Sub_Match_e0.\n  + rewrite map_fst_f_combine...\n  + assert (forall x y n bs cocases,\n      In x (map fst (combine bindings_exprs bindings_types)) ->\n      subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n    { clear - H1. intros. apply H1. eapply Sub_Trans... apply Sub_Match_bs... }\n    clear - H0 H13 H3. induction H13; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n    * inversion H0; subst. apply H4... intros. unfold not in *. eapply H3...\n    * apply IHListTypeDeriv; try inversion H0... intros. apply H3 with (x:=x0)...\n  + unfold lookup_ctors. unfold lookup_ctors in *.\n    remember (filter (eq_TypeName (fst n)) (skeleton_dts (constructorize_to_skeleton p tn))) as fl.\n    simpl. clear - H14 Heqfl.\n    destruct (filter (eq_TypeName (fst n)) (skeleton_dts (program_skeleton p))) eqn:E; try discriminate.\n    inversion H14. subst ctorlist. clear H14. pose proof (in_eq t l). rewrite <- E in H.\n    rewrite filter_In in H. destruct H.\n    assert (exists t l, fl = t :: l) as flEq.\n    { case_eq (eq_TypeName (fst n) tn); intros.\n      - simpl in Heqfl. rewrite H1 in Heqfl. exists tn. eexists...\n      - simpl in Heqfl. rewrite H1 in Heqfl. rewrite E in Heqfl. exists t. exists l...\n    }\n    destruct flEq as [t' [l' flEq]]. rewrite flEq. clear t' l' flEq.\n    unfold computeNewDatatype.\n    rewrite filter_app. rewrite filter_app. f_equal. rewrite <- app_nil_l. f_equal.\n    case_eq (eq_TypeName t tn); intros.\n    * rewrite eq_TypeName_eq in H1. subst.\n      pose proof (skeleton_dts_cdts_disjoint (program_skeleton p)).\n      unfold dts_cdts_disjoint in H1.\n      pose proof (skeleton_gfun_sigs_in_cdts_l (program_skeleton p)) as H2.\n      unfold gfun_sigs_in_cdts in H2.\n      pose proof (skeleton_gfun_sigs_in_cdts_g (program_skeleton p)) as H2'.\n      unfold gfun_sigs_in_cdts in H2'.\n      case_eq ((filter (fun x => eq_TypeName (fst (fst x)) tn)\n        (skeleton_gfun_sigs_l (program_skeleton p)))); intros;\n      case_eq ((filter (fun x => eq_TypeName (fst (fst x)) tn)\n        (skeleton_gfun_sigs_g (program_skeleton p)))); intros; auto; exfalso.\n      -- pose proof (in_eq p0 l0). rewrite <- H4 in H5. rewrite filter_In in H5.\n         destruct H5. rewrite eq_TypeName_eq in H6. subst.\n         rewrite Forall_forall in H2'. pose proof (H2' _ H5). unfold not in H1.\n         apply H1 with (t:=fst (fst p0))...\n      -- pose proof (in_eq p0 l0). rewrite <- H3 in H5. rewrite filter_In in H5.\n         destruct H5. rewrite eq_TypeName_eq in H6. subst.\n         rewrite Forall_forall in H2. pose proof (H2 _ H5). unfold not in H1.\n         apply H1 with (t:=fst (fst p0))...\n      -- pose proof (in_eq p0 l0). rewrite <- H3 in H5. rewrite filter_In in H5.\n         destruct H5. rewrite eq_TypeName_eq in H6. subst.\n         rewrite Forall_forall in H2. pose proof (H2 _ H5). unfold not in H1.\n         apply H1 with (t:=fst (fst p0))...\n    * rewrite <- app_nil_l. f_equal;\n      match goal with |- ?l = [] => case_eq l; intros; auto;\n        exfalso; pose proof (in_eq p0 l0); rewrite <- H2 in H3; rewrite filter_In in H3;\n        destruct H3; rewrite in_map_iff in H3; do 2 (destruct H3); rewrite filter_In in H5;\n        destruct H5; destruct p0; inversion H3; subst; simpl in *;\n        rewrite eq_TypeName_eq in H0; rewrite H0 in H4;\n        rewrite eq_TypeName_eq in H6; rewrite eq_TypeName_eq in H4; subst;\n        unfold QName in *; rewrite H4 in H1; rewrite eq_TypeName_refl in H1; discriminate\n      end.\n  + rewrite Forall_forall in *. intros. rewrite <- map_fst_f_combine in H3.\n    rewrite in_map_iff in H3. do 2 (destruct H3). pose proof (H15 _ H4).\n    destruct x. destruct p0. destruct p1. destruct x0. destruct p0. destruct p1. subst.\n    inversion H3...\n  + assert (forall x, In x ls -> In x ls)...\n    generalize H3. generalize H16.\n    generalize (map (fun ctor => snd ctor ++ bindings_types) ctorlist).\n    generalize ls at - 4. clear - H H1. induction ls0; intros.\n    * inversion H16. subst. apply ListTypeDeriv'_Nil.\n    * inversion H16. subst. simpl. apply ListTypeDeriv'_Cons.\n      -- rewrite Forall_forall in H. destruct a. simpl. apply H...\n         ++ rewrite in_map_iff. exists (s,e0). split... apply H3...\n         ++ intros. apply H1. apply Sub_Trans with (e2:=e0)... apply Sub_Match_cases.\n            rewrite in_map_iff. exists (s,e0). split... apply H3...\n      -- apply IHls0... intros. apply H3...\n- simpl. case_eq (eq_TypeName tn (fst n)); intros.\n  + exfalso. unfold not in H1. rewrite eq_TypeName_eq in H3. subst. destruct n.\n    eapply H1; try eapply Sub_Refl...\n  + simpl. inversion H2. subst.\n    apply T_CoMatch with (bindings_exprs := map (constructorize_expr tn) bindings_exprs)\n    (bindings_types := bindings_types) (dtorlist := dtorlist).\n    * rewrite map_fst_f_combine...\n    * assert (forall x y n bs cocases,\n      In x (map fst (combine bindings_exprs bindings_types)) ->\n      subterm y x -> y <> E_CoMatch (tn,n) bs cocases).\n      { clear - H1. intros. apply H1. eapply Sub_Trans... apply Sub_CoMatch_bs... }\n      clear - H0 H8 H4. induction H8; try apply ListTypeDeriv_Nil. simpl. apply ListTypeDeriv_Cons.\n      -- inversion H0; subst. apply H3... intros. unfold not in *. eapply H4...\n      -- apply IHListTypeDeriv; try inversion H0... intros. apply H4 with (x:=x0)...\n    * unfold lookup_dtors. rewrite <- H11. f_equal. simpl. unfold new_cdts.\n      unfold lookup_dtors. unfold new_dtors.\n      generalize (skeleton_cdts (program_skeleton p)).\n      generalize (skeleton_dtors (program_skeleton p)). intros c c0.\n      repeat (rewrite filter_compose).\n      rewrite filter_ext with (g:=eq_TypeName (fst n)).\n      2 : { clear - H3. intros. case_eq (eq_TypeName (fst n) a); intros...\n            rewrite eq_TypeName_eq in H. subst. rewrite H3... }\n      rewrite filter_ext with\n        (g:=(fun x : ScopedName * list TypeName * TypeName =>\n          let (y, _) := x in let (n0, _) := y in eq_TypeName (fst (unscope n0)) (fst n)))...\n      clear - H3. intros. destruct a. destruct p.\n      case_eq (eq_TypeName (fst (unscope s)) (fst n)); intros...\n      rewrite eq_TypeName_eq in H. rewrite H. rewrite H3...\n    * rewrite Forall_forall in *. intros. rewrite <- map_fst_f_combine in H4.\n      rewrite in_map_iff in H4. do 2 (destruct H4). pose proof (H13 _ H5).\n      destruct x. destruct p0. destruct p1. destruct x0. destruct p0. destruct p1.\n      destruct p2. destruct p0. subst. inversion H4...\n    * assert (forall x, In x ls -> In x ls)...\n      generalize H4. generalize H14.\n      generalize (map (fun dtor => snd (fst dtor) ++ bindings_types) dtorlist).\n      generalize (map snd dtorlist).\n      generalize ls at - 3. clear - H H1. induction ls0; intros.\n      -- inversion H14. subst. apply ListTypeDeriv'_Nil.\n      -- inversion H14. subst. simpl. apply ListTypeDeriv'_Cons.\n         ++ rewrite Forall_forall in H. destruct a. simpl. apply H...\n            ** rewrite in_map_iff. exists (s,e). split... apply H4...\n            ** intros. apply H1. apply Sub_Trans with (e2:=e)... apply Sub_CoMatch_cocases.\n               rewrite in_map_iff. exists (s,e). split... apply H4...\n         ++ apply IHls0... intros. apply H4...\n- inversion H0. subst. simpl. apply T_Let with (t1:=t1).\n  + apply IHe1... intros. apply H. apply Sub_Trans with (e2:=e1)... apply Sub_Let_e1...\n  + apply IHe2... intros. apply H. apply Sub_Trans with (e2:=e2)... apply Sub_Let_e2...\nQed.\n\n", "meta": {"author": "ps-tuebingen", "repo": "decomposition-diversity", "sha": "28ab18c34f0a192c9b3d58caa709dee3e9129068", "save_path": "github-repos/coq/ps-tuebingen-decomposition-diversity", "path": "github-repos/coq/ps-tuebingen-decomposition-diversity/decomposition-diversity-28ab18c34f0a192c9b3d58caa709dee3e9129068/Formalization/CtorizeII.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.23088936366002438}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import AbsAccessor.Spec.\nRequire Import CtxtSwitch.Specs.restore_hcr_el2.\nRequire Import CtxtSwitch.LowSpecs.restore_hcr_el2.\nRequire Import CtxtSwitch.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       get_rec_common_sysregs_spec\n       sysreg_write_spec\n    .\n\n  Lemma restore_hcr_el2_spec_exists:\n    forall habd habd'  labd rec\n      (Hspec: restore_hcr_el2_spec rec habd = Some habd')\n      (Hrel: relate_RData habd labd),\n    exists labd', restore_hcr_el2_spec0 rec labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque ptr_eq.\n    intros. destruct Hrel. destruct rec.\n    unfold restore_hcr_el2_spec, restore_hcr_el2_spec0 in *.\n    repeat autounfold in *. simpl in *.\n    hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec;\n      repeat destruct_con; bool_rel; simpl in *; srewrite;\n        repeat (simpl_htarget; grewrite; simpl in * ).\n    destruct regs_is_int64_dec in *. autounfold in e. repeat rewrite e.\n    repeat simpl_update_reg.\n    eexists; split. reflexivity. constructor. reflexivity.\n    inv C3.\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/CtxtSwitch/RefProof/restore_hcr_el2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23088936366002435}}
{"text": "Require Import include_frm.\nRequire Import base_tac.\nRequire Import os_inv.\nRequire Import os_code_defs.\nRequire Import abs_op.\nRequire Import sep_auto.\nRequire Import Maps.\n\nRequire Import mem_join_lemmas.\nRequire Import lemmas_for_inv_prop.\n(* lemmas specific on memory(HalfPermMap) *)\n\nLemma mem_sub_sig_eq :\n  forall l a b p (m:mem),\n    sub (sig l (p, a)) m ->\n    sub (sig l (p, b)) m ->\n    a = b.\nProof.\n  unfold sub; intros.\n  destruct H, H0.\n  eapply mem_join_sig_eq; eauto.\nQed.\n\nLtac destruct_get :=\n  let a := fresh in\n  match goal with\n  | H : (match ?X with | Some _ => _ | None => _ end) |- _ => destruct X eqn : a; tryfalse; destruct_get\n  | _ => idtac\n  end.\n\nLemma osabst_join_sig_eq :\n  forall l a b (o:osabst) o1 o2,\n    join (sig l a) o1 o ->\n    join (sig l b) o2 o ->\n    a = b.\nProof.\n  intros.\n  pose proof H l.\n  pose proof H0 l.\n  rewrite OSAbstMod.get_sig_some in *.\n  destruct_get.\n  substs; auto.\nQed.\n\n\nLemma osabst_sub_sig_eq :\n  forall l a b (o:osabst),\n    sub (sig l a) o ->\n    sub (sig l b) o ->\n    a = b.\nProof.\n  unfold sub; intros.\n  destruct H, H0.\n  eapply osabst_join_sig_eq; eauto.\nQed.\n\nLemma mem_join_sig_sub_eq :\n  forall a b l p m1 m1' m2 m2' (m:mem),\n    join (sig l (p, a)) m1 m2 ->\n    join (sig l (p, b)) m1' m2' ->\n    sub m2 m -> sub m2' m ->\n    a = b.\nProof.\n  unfold sub; intros.\n  destruct H1, H2.\n  lets Hx1: HalfPermMap.map_join_assoc H H1.\n  lets Hx2: HalfPermMap.map_join_assoc H0 H2.\n  destruct Hx1; destruct H3.\n  destruct Hx2; destruct H5.\n  lets Hx: mem_join_sig_eq H3 H5; auto.\nQed.\n(* end *)\n\n\n(* lemmas on PermMap *)\nLemma join_sub_l {A B T:Type} {MC: PermMap A B T} :\n  forall m1 m2 m,\n    join m1 m2 m -> sub m1 m.\nProof.\n  intros.\n  unfold sub.\n  eexists; eauto.\nQed.\n\nLemma join_sub_r {A B T: Type} {MC: PermMap A B T} :\n  forall m1 m2 m,\n    join m1 m2 m -> sub m2 m.\nProof.\n  intros.\n  unfold sub.\n  eexists.\n  apply map_join_comm in H; eauto.\nQed.\n\nLemma sub_trans {A B T: Type} {MC: PermMap A B T} :\n  forall m1 m2 m3,\n    sub m1 m2 -> sub m2 m3 -> sub m1 m3.\nProof.\n  unfold sub; intros.\n  geat.\nQed.\n\nLemma join_unique {A B T: Type} {MC: PermMap A B T} :\n  forall m1 m2 m m',\n    join m1 m2 m -> join m1 m2 m' -> m = m'.\nProof.\n  intros.\n  geat.\nQed.\n\nLemma eq_join_eq {A B T: Type} {MC: PermMap A B T} :\n  forall m1 m1' m2 m2' M M',\n    join m1 m2 M ->\n    join m1' m2' M' ->\n    m1 = m1' -> m2 = m2' ->\n    M = M'.\nProof.\n  intros; substs.\n  eapply join_unique; eauto.\nQed.\n(* end *)\n\n \n(*--- auxiliary lemmas ------*)\nLemma sat_sep_conj_elim1 :\n  forall e e0 M i l O a P Q,\n    (e, e0, M, i, l, O, a) |= P ** Q ->\n    exists M1 M2 O1 O2, join M1 M2 M /\\ join O1 O2 O /\\\n                        (e, e0, M1, i, l, O1, a) |= P /\\\n                        (e, e0, M2, i, l, O2, a) |= Q. \nProof.\n  intros.\n  simpl in H; simpljoin.\n  do 4 eexists; repeat (split; eauto).\nQed.\n\nLemma isptr_ecbf_sll :\n  forall s head eventl t next,\n    s |= ecbf_sll head eventl  t next -> isptr head.\nProof.\n  intros.\n  unfold ecbf_sll in H.\n  destruct eventl.\n  simpl in H; simpljoin.\n  unfolds; auto.\n  unfold ecbf_sllseg in H; fold ecbf_sllseg in H.\n  destruct_s s.\n  simpl in H; simpljoin.\n  unfolds; right.\n  eauto.\nQed.\n\nLemma isptr_ecbf_sllseg :\n  forall s head eventl t next,\n    s |= ecbf_sllseg head Vnull eventl t next -> isptr head.\nProof.\n  intros.\n  unfold ecbf_sllseg in H.\n  destruct eventl.\n  simpl in H; simpljoin.\n  unfolds; auto.\n  unfold ecbf_sllseg in H; fold ecbf_sllseg in H.\n  destruct_s s.\n  simpl in H; simpljoin.\n  unfolds; right.\n  eauto.\nQed.\n\nLemma sll_isptr :\n  forall vl s head t next,\n    s |= sll head vl t next -> isptr head.\nProof.\n  inductions vl; intros.\n  simpl in H; simpljoin; unfolds; auto.\n  simpl in H; simpljoin.\n  unfolds; right; eauto.\nQed.\n\n\nLemma qblkf_sll_isptr :\n  forall qblkl head t next s,\n    s |= qblkf_sll head qblkl t next -> isptr head.\nProof.\n  inductions qblkl; intros.\n  simpl in H; simpljoin; unfolds; auto.\n  simpl in H; simpljoin; unfolds; right; eauto.\nQed.\n\nLemma evsllseg_isptr :\n  forall ectrl head msgql s,\n    s |= evsllseg head Vnull ectrl msgql -> isptr head.\nProof.\n  inductions ectrl; intros.\n  simpl in H; simpljoin; unfolds; auto.\n  simpl in H; destruct a; destruct msgql; tryfalse; simpl in H; simpljoin.\n  unfolds; right; eauto.\nQed.\n\n\nLemma qblkfsllseg_head_isptr:\n  forall l v1   t  n  P s, s |= qblkf_sllseg\n                                    v1 Vnull  l t n  ** P  -> isptr v1. \nProof.\n  inductions l ; intros; simpl in *; tryfalse;  simpljoin; \n   unfolds; simpl; eauto.\nQed.\n\n\nLemma qblkfsll_head_isptr : forall v l  t n P s, s |= qblkf_sll\n                                                   v l  t n ** P  -> isptr v.\nProof.\n  unfold qblkf_sll.\n  intros.\n  eapply  qblkfsllseg_head_isptr.\n  eauto.\nQed.\n\n\nLemma ecbfsllseg_head_isptr:\n  forall l v1   t  n  P s, s |= ecbf_sllseg\n                                    v1 Vnull  l t n  ** P  -> isptr v1. \nProof.\n  inductions l ; intros; simpl in *; tryfalse; simpljoin; \n  unfolds; simpl; eauto.\nQed.\n\n\nLemma ecbfsll_head_isptr : forall v l  t n P s, s |= ecbf_sll\n                                                   v l  t n ** P  -> isptr v.\nProof.\n  unfold ecbf_sll.\n  intros.\n  eapply ecbfsllseg_head_isptr.\n  eauto.\nQed.\n\nLemma  evsllseg_head_isptr : forall  s head l x P, \n                                s|= evsllseg head Vnull l x ** P  -> \n                                isptr head.\nProof.\n  introv Hsat.\n  destruct l; simpl evsllseg in *.\n  sep split in Hsat.\n  simpljoin.\n  subst; unfolds; auto.\n  destruct x.\n  simpl in Hsat; tryfalse.\n  sep destruct  Hsat.\n  sep split in Hsat.\n  simpljoin.\n  tryfalse.\n  destruct e.\n  unfold AEventNode in Hsat.\n  destruct e0. \n  unfold AOSEvent in Hsat.\n  unfold node in Hsat.\n  sep destroy Hsat.\n  simpljoin.\n  unfolds; auto.\n  right.\n  eexists; eauto.\n  unfold AOSEvent in Hsat.\n  unfold node in Hsat.\n  sep destroy Hsat.\n  simpljoin.\n  unfolds; auto.\n  right.\n  eexists; eauto.\n  unfold AOSEvent in Hsat.\n  unfold node in Hsat.\n  sep destroy Hsat.\n  simpljoin.\n  unfolds; auto.\n  right.\n  eexists; eauto.\n  unfold AOSEvent in Hsat.\n  unfold node in Hsat.\n  sep destroy Hsat.\n  simpljoin.\n  unfolds; auto.\n  right.\n  eexists; eauto.\nQed.\n(* end *)\n\n\n(* tactics *)\nLtac simpl_map1 :=\n  match goal with\n    | H:exists _, _ |- _ => destruct H; simpl_map1\n    | H:_ /\\ _ |- _ => destruct H; simpl_map1\n\n    | H: emposabst _ |- _ => unfold emposabst in H; subst; simpl_map1\n\n    | H:join empenv _ _ |- _ => apply map_join_comm in H; apply map_join_emp' in H; subst; simpl_map1\n    | H:join _ empenv _\n      |- _ =>\n      apply map_join_emp' in H; subst; simpl_map1\n    | |- join empenv _ _ => apply map_join_comm; apply map_join_emp; simpl_map1\n    | |- join _ empenv _ => apply map_join_emp; simpl_map1\n    | H:join ?a ?b ?ab |- join ?b ?a ?ab => apply map_join_comm; auto\n    | H:(_, _) = (_, _) |- _ => inversion H; clear H; simpl_map1\n    | H:?x = ?x |- _ => clear H; simpl_map1\n    | |- ?x = ?x => reflexivity\n    | |- join _ ?a ?a => apply map_join_comm; simpl_map1\n    | |- join ?a _ ?a => apply map_join_emp; simpl_map1\n    | |- empenv = _ => reflexivity; simpl_map1\n    | |- _ = empenv => reflexivity; simpl_map1\n    | H:True |- _ => clear H; simpl_map1\n    | |- True => auto\n    | _ => try (progress subst; simpl_map1)\n  end.\n\nLtac simpljoin1 := repeat progress simpl_map1.\n\nLtac mem_join_sub_solver :=\n  match goal with\n    | H: join ?m _ ?X |- sub ?m ?M =>\n      apply join_sub_l in H; apply sub_trans with (m2:=X); auto; mem_join_sub_solver\n    | H: join _ ?m ?X |- sub ?m ?M =>\n      apply join_sub_r in H; apply sub_trans with (m2:=X); auto; mem_join_sub_solver\n  end.\n\nLtac elim_sep_conj1 H head_H:= let a := fresh in apply sat_sep_conj_elim1 in H; do 4 destruct H; destruct H as [a H]; let b := fresh in destruct H as [b H]; let c := fresh in destruct H as [head_H H].\n\nLtac mem_sig_eq_solver M := let Hx:= fresh in\n  match goal with\n    | |- sig ?l1 (?p, ?v1) = sig ?l2 (?p, ?v2) =>\n      assert(sub (sig l1 (p, v1)) M) as _H1 by mem_join_sub_solver;\n        assert(sub (sig l2 (p, v2)) M) as _H2 by mem_join_sub_solver;\n        lets Hx: mem_sub_sig_eq _H1 _H2; rewrite Hx; auto\n  end.\n\nLtac mem_eq_solver1 M :=\n  eapply eq_join_eq; eauto; [mem_sig_eq_solver M |try (mem_eq_solver1 M)]; mem_sig_eq_solver M.\n\nLtac simpl_sat H := unfold sat in H; fold sat in H; simpl substmo in H; simpl getmem in H; simpl getabst in H; simpl empst in H.\n\n\nLtac mem_eq_solver' MM :=\n  eapply eq_join_eq; eauto;[\n    match goal with\n      | H: forall M : mem, sub ?m1 M -> sub ?m2 M -> ?m1 = ?m2 |- ?m1 = ?m2 => apply H with (M:= MM)\n    end;  mem_join_sub_solver | try (mem_eq_solver' MM)].\n\nLtac mem_eq_solver MM := try (mem_eq_solver' MM);\n    match goal with\n      | H: forall M : mem, sub ?m1 M -> sub ?m2 M -> ?m1 = ?m2 |- ?m1 = ?m2 => apply H with (M:= MM)\n    end;  mem_join_sub_solver.\n\n(*\nLtac osabst_join_sub_solver :=\n  match goal with\n    | H: OSAbstMod.join ?m _ ?X |- OSAbstMod.sub ?m ?M =>\n      apply OSAbstMod.join_sub_l in H; apply OSAbstMod.sub_trans with (m2:=X); auto; osabst_join_sub_solver\n    | H: OSAbstMod.join _ ?m ?X |- OSAbstMod.sub ?m ?M =>\n      apply OSAbstMod.join_sub_r in H; apply OSAbstMod.sub_trans with (m2:=X); auto; osabst_join_sub_solver\n  end.\n *)\n\nLtac osabst_eq_solver' OO :=\n  eapply eq_join_eq; eauto;[\n    match goal with\n      | H: forall o0 : osabst, sub ?m1 o0 -> sub ?m2 o0 -> ?m1 = ?m2 |- ?m1 = ?m2 => apply H with (o0:= OO)\n    end;  mem_join_sub_solver | try (osabst_eq_solver' OO)].\n\nLtac osabst_eq_solver OO := try (osabst_eq_solver' OO);\n    match goal with\n      | H: forall o0 : osabst, sub ?m1 o0 -> sub ?m2 o0 -> ?m1 = ?m2 |- ?m1 = ?m2 => apply H with (o0:=OO)\n    end;  mem_join_sub_solver.\n\nLtac un_eq_event_type_solver :=\n  match goal with\n    | H1: Some _ = Some _ , H2: Some _ = Some _ |- _ =>\n      rewrite H1 in H2; inverts H2\n  end.\n\n(* end *)\n \n\n(*lemmas*)\nLemma mapstoval_true_vptr_eq :\n  forall l a x x' m m' M,\n    mapstoval l (Tptr a) true (Vptr x) m -> mapstoval l (Tptr a) true (Vptr x') m' ->\n    sub m M -> sub m' M ->\n    x = x' /\\ m = m'.\nProof.\n  intros.\n  unfold mapstoval in H, H0; simpljoin1.\n  simpl in H1, H2; destruct x, x'; simpl in H3, H4; destruct l; simpljoin1.\n  unfold ptomval in *; substs.\n  assert(sub (sig (b1, (o + 1 + 1 + 1)%Z) (true, Pointer b i 0)) M).\n  mem_join_sub_solver.\n  assert(sub (sig (b1, (o + 1 + 1 + 1)%Z) (true, Pointer b0 i0 0)) M).\n  mem_join_sub_solver.\n\n  lets Hx: mem_sub_sig_eq H3 H5; inverts Hx.\n  split; auto.\n  clear H5 H3.\n  repeat (eapply eq_join_eq; eauto).\nQed.\n\nLemma mapstoval_false_vptr_eq :\n  forall l a x x' m m' M,\n    mapstoval l (Tptr a) false (Vptr x) m -> mapstoval l (Tptr a) false (Vptr x') m' ->\n    sub m M -> sub m' M ->\n    x = x' /\\ m = m'.\nProof.\n  intros.\n  unfold mapstoval in H, H0; simpljoin1.\n  simpl in H1, H2; destruct x, x'; simpl in H3, H4; destruct l; simpljoin1.\n  unfold ptomval in *; substs.\n  assert(sub (sig (b1, (o + 1 + 1 + 1)%Z) (false, Pointer b i 0)) M).\n  mem_join_sub_solver.\n  assert(sub (sig (b1, (o + 1 + 1 + 1)%Z) (false, Pointer b0 i0 0)) M).\n  mem_join_sub_solver.\n\n  lets Hx: mem_sub_sig_eq H3 H5; inverts Hx.\n  split; auto.\n  clear H5 H3.\n  repeat (eapply eq_join_eq; eauto).\nQed.\n\n\nLemma ptomvallist_true_mem_eq :\n  forall vl l m m' M,\n    sub m M -> sub m' M ->\n    ptomvallist l true vl m -> ptomvallist l true vl m' ->\n    m = m'.\nProof.\n  inductions vl; intros.\n  simpl in H1, H2; substs; auto.\n  simpl in H1, H2; destruct l; simpljoin1.\n  unfold ptomval in H3, H5; substs.\n  eapply eq_join_eq; eauto.\n  eapply IHvl with (M:=M); eauto; mem_join_sub_solver.\nQed.\n\nLemma ptomvallist_false_mem_eq :\n  forall vl l m m' M,\n    sub m M -> sub m' M ->\n    ptomvallist l false vl m -> ptomvallist l false vl m' ->\n    m = m'.\nProof.\n  inductions vl; intros.\n  simpl in H1, H2; substs; auto.\n  simpl in H1, H2; destruct l; simpljoin1.\n  unfold ptomval in H3, H5; substs.\n  eapply eq_join_eq; eauto.\n  eapply IHvl with (M:=M); eauto; mem_join_sub_solver.\nQed.\n\nLemma mapstoval_true_mem_eq :\n  forall l t v v' m m' M,\n    sub m M -> sub m' M ->\n    mapstoval l t true v m -> mapstoval l t true v' m' -> m = m'.\nProof.\n  unfold mapstoval; intros; destruct l; simpljoin1.\n  destruct t, v, v'; try (destruct a); try(destruct a0); simpl in H3, H4;\n  unfold ptomval in H3, H4; simpljoin1;\n  try solve [repeat (eapply eq_join_eq; eauto)];\n  try solve [lets Hx: mem_join_sig_sub_eq H1 H2 H H0; tryfalse];\n  try solve [lets Hx: mem_sub_sig_eq H H0; tryfalse];\n  try solve [mem_eq_solver1 M];\n  try solve [eapply ptomvallist_true_mem_eq; eauto].\n  lets Hx: mem_sub_sig_eq H H0; rewrite Hx; auto.\nQed.\n\nLemma mapstoval_false_mem_eq :\n  forall l t v v' m m' M,\n    sub m M -> sub m' M ->\n    mapstoval l t false v m -> mapstoval l t false v' m' -> m = m'.\nProof. \n  unfold mapstoval; intros; destruct l; simpljoin1.\n  destruct t, v, v'; try (destruct a); try(destruct a0); simpl in H3, H4;\n  unfold ptomval in H3, H4; simpljoin1;\n  try solve [repeat (eapply eq_join_eq; eauto)];\n  try solve [lets Hx: mem_join_sig_sub_eq H1 H2 H H0; tryfalse];\n  try solve [lets Hx: mem_sub_sig_eq H H0; tryfalse];\n  try solve [mem_eq_solver1 M];\n  try solve [eapply ptomvallist_false_mem_eq; eauto].\n  lets Hx: mem_sub_sig_eq H H0; rewrite Hx; auto.\nQed.\n\nFixpoint struct_atom_val_eq' (vl vl':vallist) (d:decllist) :=\n  match vl with\n    | nil =>\n      match vl' with\n        | nil => True\n        | _ :: _ => False\n      end\n    | v1 :: t1 =>\n      match vl' with\n        | nil => False\n        | v2 :: t2 =>\n          match d with\n            | dnil => False\n            | dcons id (Tstruct _ _) td => struct_atom_val_eq' t1 t2 td\n            | dcons id (Tarray _ _) td => struct_atom_val_eq' t1 t2 td\n            | dcons id _ td => v1 = v2 /\\ struct_atom_val_eq' t1 t2 td\n          end\n      end\n  end.\n\nDefinition struct_atom_val_eq vl vl' t :=\n  match t with\n    | Tstruct id dl => struct_atom_val_eq' vl vl' dl\n    | _ => False\n  end.\n\n\nLocal Open Scope Z_scope.\nLemma ptomvallist_true_sub_vl_eq :\n  forall vl1 vl2 l m1 m2 m,\n    ptomvallist l true vl1 m1 ->\n    ptomvallist l true vl2 m2 ->\n    length vl1 = length vl2 ->\n    sub m1 m -> sub m2 m ->\n    vl1 = vl2.\nProof.\n  inductions vl1; intros.\n  destruct vl2; auto.\n  simpl in H1; inversion H1.\n  \n  destruct vl2.\n  simpl in H1; inversion H1.\n\n  simpl in H1; inverts H1.\n  simpl in H; destruct l.\n\n  do 3 destruct H; destruct H1.\n  simpl in H0; do 3 destruct H0; destruct H6.\n\n  unfold ptomval in H1, H6; substs.\n  assert(a = m0).\n  unfolds in H2; destruct H2.\n  unfolds in H3; destruct H3.\n  lets Hx1: HalfPermMap.map_join_assoc H H1.\n  lets Hx2: HalfPermMap.map_join_assoc H0 H2.\n  simpljoin.\n  lets Hx: mem_join_sig_eq H6 H3; auto.\n  substs.\n  assert(vl1 = vl2).\n  assert(sub x0 m).\n  unfold sub.\n  unfold sub in H2.\n  geat.\n  assert(sub x2 m).\n  unfold sub.\n  unfold sub in H3.\n  geat.\n  apply IHvl1 with (m1:=x0) (m2:=x2) (m:=m) (l:=(b,o+1)); auto.\n  substs; auto.\nQed.\n\nLemma ptomvallist_false_sub_vl_eq :\n  forall vl1 vl2 l m1 m2 m,\n    ptomvallist l false vl1 m1 ->\n    ptomvallist l false vl2 m2 ->\n    length vl1 = length vl2 ->\n    sub m1 m -> sub m2 m ->\n    vl1 = vl2.\nProof.\n  inductions vl1; intros.\n  destruct vl2; auto.\n  simpl in H1; inversion H1.\n  \n  destruct vl2.\n  simpl in H1; inversion H1.\n\n  simpl in H1; inverts H1.\n  simpl in H; destruct l.\n\n  do 3 destruct H; destruct H1.\n  simpl in H0; do 3 destruct H0; destruct H6.\n\n  unfold ptomval in H1, H6; substs.\n  assert(a = m0).\n  unfolds in H2; destruct H2.\n  unfolds in H3; destruct H3.\n  lets Hx1: HalfPermMap.map_join_assoc H H1.\n  lets Hx2: HalfPermMap.map_join_assoc H0 H2.\n  simpljoin.\n  lets Hx: mem_join_sig_eq H6 H3; auto.\n  substs.\n  assert(vl1 = vl2).\n  assert(sub x0 m).\n  unfold sub.\n  unfold sub in H2.\n  geat.\n  assert(sub x2 m).\n  unfold sub.\n  unfold sub in H3.\n  geat.\n  apply IHvl1 with (m1:=x0) (m2:=x2) (m:=m) (l:=(b,o+1)); auto.\n  substs; auto.\nQed.\n\n\nLemma mapstoval_true_rule_type_val_match_eq :\n  forall l t v v' m m' M,\n    rule_type_val_match t v = true -> rule_type_val_match t v' = true ->\n    mapstoval l t true v m -> mapstoval l t true v' m' ->\n    sub m M -> sub m' M ->\n    v = v' /\\ m = m'.\nProof.\n  intros.\n  unfold mapstoval in H1, H2; simpljoin1.\n  destruct t; destruct v; destruct v'; simpl in H, H0; tryfalse;\n  simpl encode_val in H5, H6; try(destruct a); try(destruct a0);\n  try solve [split; auto; eapply ptomvallist_true_mem_eq; eauto];\n  try solve [lets Hx: ptomvallist_true_sub_vl_eq H5 H6 H4 H3; [simpl; auto | inverts Hx]].\n\n  assert(i = i0).\n  simpl in H5, H6; destruct l; unfold ptomval in *; simpljoin1.\n  lets Hx: mem_sub_sig_eq H3 H4.\n\n  destruct (Int.unsigned i <=? Byte.max_unsigned) eqn : eq1; tryfalse.\n  destruct (Int.unsigned i0 <=? Byte.max_unsigned) eqn : eq2; tryfalse.\n  apply Zle_is_le_bool in eq1; apply Zle_is_le_bool in eq2.\n  remember(Byte.repr (Int.unsigned i)) as X;\n    remember(Byte.repr (Int.unsigned i0)) as Y.\n  inverts Hx; substs.\n  lets Hx1: byte_repr_int_unsigned_eq eq1 eq2 H1; auto.\n  substs.\n  split; eauto.\n  eapply ptomvallist_true_mem_eq; eauto.\n  \n  lets Hx: ptomvallist_true_sub_vl_eq H6 H5 H3 H4.\n  simpl; auto.\n  remember (Byte.repr (Int.unsigned i)) as X1;\n    remember (Byte.repr (Int.unsigned i / 256)) as X2;\n    remember (Byte.repr (Int.unsigned i0)) as Y1;\n    remember (Byte.repr (Int.unsigned i0 / 256)) as Y2.\n  inverts Hx; substs.\n\n  destruct (Int.unsigned i <=? Int16.max_unsigned) eqn : eq1; tryfalse.\n  destruct (Int.unsigned i0 <=? Int16.max_unsigned) eqn : eq2; tryfalse.\n  apply Z.leb_le in eq1.\n  apply Z.leb_le in eq2.\n\n  apply byte_repr_eq in H2.  \n\n  assert(Int.unsigned i = Int.unsigned i0).\n  eapply div_256_byte_repr_eq; eauto.\n  assert(Int.repr (Int.unsigned i) = Int.repr (Int.unsigned i0)).\n  rewrite H7; auto.\n  do 2 rewrite Int.repr_unsigned in H8; substs.\n  split; auto.\n  eapply ptomvallist_true_mem_eq; eauto.\n  split.\n  apply zero_le_int_unsigned_div_256; auto.\n  apply z_le_int16_max_div_256_byte_max; auto.\n  split.\n  apply zero_le_int_unsigned_div_256; auto.\n  apply z_le_int16_max_div_256_byte_max; auto.\n\n  lets Hx: ptomvallist_true_sub_vl_eq H6 H5 H3 H4.\n  simpl; auto.\n  remember (Byte.repr (Int.unsigned i)) as X1;\n    remember (Byte.repr (Int.unsigned i / 256)) as X2;\n    remember (Byte.repr (Int.unsigned i / 256 / 256)) as X3;\n    remember (Byte.repr (Int.unsigned i / 256 / 256 / 256)) as X4;\n    remember (Byte.repr (Int.unsigned i0)) as Y1;\n    remember (Byte.repr (Int.unsigned i0 / 256)) as Y2;\n    remember (Byte.repr (Int.unsigned i0 / 256 / 256)) as Y3;\n    remember (Byte.repr (Int.unsigned i0 / 256 / 256 / 256)) as Y4.\n  inverts Hx; substs.\n  apply byte_repr_eq in H8.\n  assert(Int.unsigned i = Int.unsigned i0).\n  eapply div_256_byte_repr_eq; eauto.\n  eapply div_256_byte_repr_eq; eauto.\n  eapply div_256_byte_repr_eq; eauto.\n  assert(Int.repr (Int.unsigned i) = Int.repr (Int.unsigned i0)).\n  rewrite H9; auto.\n  do 2 rewrite Int.repr_unsigned in H10; substs.\n  split; auto.\n  eapply ptomvallist_true_mem_eq; eauto.\n  split.\n  apply zero_le_int_unsigned_div_256_256_256; auto.\n  apply z_le_int_max_div_256_256_256_byte_max; auto.\n  apply Int.unsigned_range_2.\n  split.\n  apply zero_le_int_unsigned_div_256_256_256; auto.\n  apply z_le_int_max_div_256_256_256_byte_max; auto.\n  apply Int.unsigned_range_2.\n  \n  lets Hx: ptomvallist_true_sub_vl_eq H5 H6 H4 H3; simpl; auto.\n  inverts Hx.\n  split; auto.\n  eapply ptomvallist_true_mem_eq; eauto.\n\n  lets Hx: ptomvallist_true_sub_vl_eq H5 H6 H4 H3; simpl; auto.\n  inverts Hx.\n  split; auto.\n  eapply ptomvallist_true_mem_eq; eauto.\nQed.\n\n\nLemma mapstoval_false_rule_type_val_match_eq :\n  forall l t v v' m m' M,\n    rule_type_val_match t v = true -> rule_type_val_match t v' = true ->\n    mapstoval l t false v m -> mapstoval l t false v' m' ->\n    sub m M -> sub m' M ->\n    v = v' /\\ m = m'.\nProof.\n  intros.\n  unfold mapstoval in H1, H2; simpljoin1.\n  destruct t; destruct v; destruct v'; simpl in H, H0; tryfalse;\n  simpl encode_val in H5, H6; try(destruct a); try(destruct a0);\n  try solve [split; auto; eapply ptomvallist_false_mem_eq; eauto];\n  try solve [lets Hx: ptomvallist_false_sub_vl_eq H5 H6 H4 H3; [simpl; auto | inverts Hx]].\n\n  assert(i = i0).\n  simpl in H5, H6; destruct l; unfold ptomval in *; simpljoin1.\n  lets Hx: mem_sub_sig_eq H3 H4.\n\n  destruct (Int.unsigned i <=? Byte.max_unsigned) eqn : eq1; tryfalse.\n  destruct (Int.unsigned i0 <=? Byte.max_unsigned) eqn : eq2; tryfalse.\n  apply Zle_is_le_bool in eq1; apply Zle_is_le_bool in eq2.\n  remember(Byte.repr (Int.unsigned i)) as X;\n    remember(Byte.repr (Int.unsigned i0)) as Y.\n  inverts Hx; substs.\n  lets Hx1: byte_repr_int_unsigned_eq eq1 eq2 H1; auto.\n  substs.\n  split; eauto.\n  eapply ptomvallist_false_mem_eq; eauto.\n  \n  lets Hx: ptomvallist_false_sub_vl_eq H6 H5 H3 H4.\n  simpl; auto.\n  remember (Byte.repr (Int.unsigned i)) as X1;\n    remember (Byte.repr (Int.unsigned i / 256)) as X2;\n    remember (Byte.repr (Int.unsigned i0)) as Y1;\n    remember (Byte.repr (Int.unsigned i0 / 256)) as Y2.\n  inverts Hx; substs.\n\n  destruct (Int.unsigned i <=? Int16.max_unsigned) eqn : eq1; tryfalse.\n  destruct (Int.unsigned i0 <=? Int16.max_unsigned) eqn : eq2; tryfalse.\n  apply Z.leb_le in eq1.\n  apply Z.leb_le in eq2.\n\n  apply byte_repr_eq in H2.  \n\n  assert(Int.unsigned i = Int.unsigned i0).\n  eapply div_256_byte_repr_eq; eauto.\n  assert(Int.repr (Int.unsigned i) = Int.repr (Int.unsigned i0)).\n  rewrite H7; auto.\n  do 2 rewrite Int.repr_unsigned in H8; substs.\n  split; auto.\n  eapply ptomvallist_false_mem_eq; eauto.\n  split.\n  apply zero_le_int_unsigned_div_256; auto.\n  apply z_le_int16_max_div_256_byte_max; auto.\n  split.\n  apply zero_le_int_unsigned_div_256; auto.\n  apply z_le_int16_max_div_256_byte_max; auto.\n\n  lets Hx: ptomvallist_false_sub_vl_eq H6 H5 H3 H4.\n  simpl; auto.\n  remember (Byte.repr (Int.unsigned i)) as X1;\n    remember (Byte.repr (Int.unsigned i / 256)) as X2;\n    remember (Byte.repr (Int.unsigned i / 256 / 256)) as X3;\n    remember (Byte.repr (Int.unsigned i / 256 / 256 / 256)) as X4;\n    remember (Byte.repr (Int.unsigned i0)) as Y1;\n    remember (Byte.repr (Int.unsigned i0 / 256)) as Y2;\n    remember (Byte.repr (Int.unsigned i0 / 256 / 256)) as Y3;\n    remember (Byte.repr (Int.unsigned i0 / 256 / 256 / 256)) as Y4.\n  inverts Hx; substs.\n  apply byte_repr_eq in H8.\n  assert(Int.unsigned i = Int.unsigned i0).\n  eapply div_256_byte_repr_eq; eauto.\n  eapply div_256_byte_repr_eq; eauto.\n  eapply div_256_byte_repr_eq; eauto.\n  assert(Int.repr (Int.unsigned i) = Int.repr (Int.unsigned i0)).\n  rewrite H9; auto.\n  do 2 rewrite Int.repr_unsigned in H10; substs.\n  split; auto.\n  eapply ptomvallist_false_mem_eq; eauto.\n  split.\n  apply zero_le_int_unsigned_div_256_256_256; auto.\n  apply z_le_int_max_div_256_256_256_byte_max; auto.\n  apply Int.unsigned_range_2.\n  split.\n  apply zero_le_int_unsigned_div_256_256_256; auto.\n  apply z_le_int_max_div_256_256_256_byte_max; auto.\n  apply Int.unsigned_range_2.\n  \n  lets Hx: ptomvallist_false_sub_vl_eq H5 H6 H4 H3; simpl; auto.\n  inverts Hx.\n  split; auto.\n  eapply ptomvallist_false_mem_eq; eauto.\n\n  lets Hx: ptomvallist_false_sub_vl_eq H5 H6 H4 H3; simpl; auto.\n  inverts Hx.\n  split; auto.\n  eapply ptomvallist_false_mem_eq; eauto.\nQed.\n\n\nLemma Astruct'_vl_eq :\n  forall vl vl' d l e e0 M1 M2 M i lo o1 o2 a,\n    struct_type_vallist_match' d vl -> struct_type_vallist_match' d vl' ->\n    (e, e0, M1, i, lo, o1, a) |= Astruct' l d vl ->\n    (e, e0, M2, i, lo, o2, a) |= Astruct' l d vl' ->\n    sub M1 M -> sub M2 M ->\n    struct_atom_val_eq' vl vl' d.\nProof.\n  inductions vl; intros.\n  destruct vl'; destruct d; simpl in H3, H4; tryfalse; auto.\n  \n  destruct vl'; destruct d; simpl in H3, H4; tryfalse;\n  simpl in H, H0.\n\n  destruct l; destruct t; simpl in H1, H2; simpljoin1;\n  try solve [\n        assert(sub x M) as _H1 by mem_join_sub_solver;\n        assert(sub x5 M) as _H2 by mem_join_sub_solver;\n        lets Hx1': mapstoval_true_rule_type_val_match_eq H H0 H14 H8 _H2; lets Hx1 : Hx1' _H1;\n        assert(sub x0 M) as _H3 by mem_join_sub_solver;\n        assert(sub x6 M) as _H4 by mem_join_sub_solver;\n        lets Hx2': IHvl H18 H17 H15 H9 _H4; lets Hx2: Hx2' _H3; simpljoin1;\n        simpl; auto;\n        simpljoin1\n      ];\n  try solve [simpl; eapply IHvl; eauto].\nQed.\n\n\nLemma node_vl_eq :\n  forall vl vl' head t M1 M2 M o1 o2 e e0 i l a,\n    (e, e0, M1, i, l, o1, a) |= node head vl t ->\n    (e, e0, M2, i, l, o2, a) |= node head vl' t ->\n    sub M1 M -> sub M2 M ->\n    struct_atom_val_eq vl vl' t.\nProof.\n  intros.\n  unfold node in H, H0.\n  destruct H, H0; simpl in H, H0; simpljoin1.\n  unfold Astruct in H7, H15.\n  destruct t; tryfalse; inverts H6; simpl in H10, H18.\n  simpl.\n  eapply Astruct'_vl_eq; eauto.\nQed.\n\nLemma struct_type_vallist_match_os_event : forall v, struct_type_vallist_match os_ucos_h.OS_EVENT v -> exists v1 v2 v3 v4 v5 v6, v = v1 :: v2 :: v3 :: v4 :: v5 :: v6 :: nil.\nProof.\n  intros.\n  unfold os_ucos_h.OS_EVENT in H.\n  simpl in H.\n  unfolds in H.\n  destruct v; tryfalse.\n  destruct v0; simpljoin1; tryfalse.\n  destruct v1; simpljoin1; tryfalse.\n  destruct v2; simpljoin1; tryfalse.\n  destruct v3; simpljoin1; tryfalse.\n  destruct v4; simpljoin1; tryfalse.\n  destruct v5; tryfalse;\n  do 6 eexists; eauto.\nQed.\n\nLemma osabst_eq_join_eq :\n  forall m1 m1' m2 m2' M M',\n    OSAbstMod.join m1 m2 M ->\n    OSAbstMod.join m1' m2' M' ->\n    m1 = m1' -> m2 = m2' ->\n    M = M'.\nProof.\n  intros; substs.\n  eapply OSAbstMod.join_unique; eauto.\nQed.\n\nLemma struct_type_vallist_match_os_q : forall v, struct_type_vallist_match os_ucos_h.OS_Q v -> exists v1 v2 v3 v4 v5 v6 v7 v8, v = v1 :: v2 :: v3 :: v4 :: v5 :: v6 :: v7 :: v8 :: nil.\nProof.\n  intros.\n  unfold os_ucos_h.OS_EVENT in H.\n  simpl in H.\n  unfolds in H.\n  destruct v; tryfalse.\n  destruct v0; simpljoin1; tryfalse.\n  destruct v1; simpljoin1; tryfalse.\n  destruct v2; simpljoin1; tryfalse.\n  destruct v3; simpljoin1; tryfalse.\n  destruct v4; simpljoin1; tryfalse.\n  destruct v5; simpljoin1; tryfalse.\n  destruct v6; simpljoin1; tryfalse.\n  destruct v7; simpljoin1; tryfalse.\n  do 4 eexists; eauto.\nQed.\n\n\nLemma struct_type_vallist_match_os_q_freeblk : forall v, struct_type_vallist_match os_ucos_h.OS_Q_FREEBLK v -> exists v1 v2, v = v1 :: v2 :: nil.\nProof.\n  intros.\n  unfold os_ucos_h.OS_EVENT in H.\n  simpl in H.\n  unfolds in H.\n  destruct v; tryfalse.\n  destruct v0; simpljoin1; tryfalse.\n  destruct v1; simpljoin1; tryfalse.\n  eauto.\nQed.\n\n\nLemma AOSEvent_osevent_eq :\n  forall osevent osevent' etbl etbl' l e e0 M1 M2 M i lo o1 o2 a,\n    (e, e0, M1, i, lo, o1, a) |= AOSEvent l osevent etbl ->\n    (e, e0, M2, i, lo, o2, a) |= AOSEvent l osevent' etbl' ->\n    sub M1 M -> sub M2 M ->\n    struct_atom_val_eq osevent osevent' os_ucos_h.OS_EVENT.\nProof.\n  unfold AOSEvent; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  eapply node_vl_eq with (M:=M); eauto; mem_join_sub_solver.\nQed.\n\nLemma AOSQCtr_osq_eq :\n  forall osq osq' l e e0 M1 M2 M i lo o1 o2 a,\n    (e, e0, M1, i, lo, o1, a) |= AOSQCtr l osq ->\n    (e, e0, M2, i, lo, o2, a) |= AOSQCtr l osq' ->\n    sub M1 M -> sub M2 M ->\n    struct_atom_val_eq osq osq' os_ucos_h.OS_Q.\nProof.\n  unfold AOSQCtr; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  eapply node_vl_eq with (M:=M); eauto; mem_join_sub_solver.\nQed.\n\nLemma AEventNode_osevent_eq :\n  forall v osevent osevent' etbl etbl' d d' e e0 M1 M2 M i lo o1 o2 a,\n    (e, e0, M1, i, lo, o1, a) |= AEventNode v osevent etbl d ->\n    (e, e0, M2, i, lo, o2, a) |= AEventNode v osevent' etbl' d' ->\n    sub M1 M -> sub M2 M ->\n    struct_atom_val_eq osevent osevent' os_ucos_h.OS_EVENT.\nProof.\n  unfold AEventNode; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  eapply AOSEvent_osevent_eq with (M:=M); eauto; mem_join_sub_solver.\nQed.\n(*end*)\n\n\n(* main lemma ?*)\nLemma a_isr_is: inv_isr_prop A_isr_is_prop.\nProof.\n  unfold inv_isr_prop;unfold A_isr_is_prop.\n  splits;intros;destruct s as [[]]; destruct t as [[[[]]]];destruct l as [[]].\n  unfold isr_is_prop in H;simpl in H; simpljoin1.\n  simpl;simpljoin1.\n  do 8 eexists;splits;simpljoin1.\n  eapply map_join_emp.\n  eapply map_join_emp.\n  split; eauto.\n  split; auto.\n  unfolds; auto.\n\n  do 6 eexists;splits;simpljoin1.\n  eapply map_join_emp.\n  eapply map_join_emp.\n  splits; eauto.\n  unfolds; auto.\n\n  unfold isr_is_prop.\n  intros.\n  apply H9 in H.\n  unfold isrupd.\n  destruct ( beq_nat i x1 );auto.\n\n  unfolds; auto.\n  \n  (*-----------------------*)\n  unfold isr_is_prop in H;simpl in H;simpljoin1.\n  simpl.\n  do 8 eexists;splits;simpljoin1.\n  eapply map_join_emp.\n  eapply map_join_emp.\n  splits; eauto.\n  unfolds; auto.\n\n  do 6 eexists;splits; eauto.\n  eapply map_join_emp.\n  eapply map_join_emp.\n  splits; eauto.\n  unfolds; auto.\n\n  unfold isr_is_prop.\n  intros.\n  unfold isrupd.\n  remember ( beq_nat i x1) as X.\n  destruct X.\n  symmetry in HeqX.\n  apply beq_nat_true in HeqX.\n  subst.\n  simpl in H.\n  destruct H.\n  left;auto.\n  simpl in H.\n  apply H9.\n  intro.\n  destruct H.\n  right;auto.\n  unfolds; auto.\n  \n  (*----------------------------*)\n  unfold isr_is_prop in H;simpl in H; simpljoin1.\n  simpl; eauto.\n  do 8 eexists;splits; eauto.\n  eapply map_join_emp; eauto.\n  eapply map_join_emp; eauto.\n  splits; eauto.\n  unfolds; auto.\n\n  do 6 eexists;splits;simpljoin1.\n  eapply map_join_emp; eauto.\n  eapply map_join_emp; eauto.\n  splits; eauto.\n  unfolds; auto.\n  unfold isr_is_prop.\n  simpl in H0, H1.\n  intros.\n  \n  assert (x1=i\\/x1<>i) by tauto.\n  destruct H2.\n  subst;auto.\n  subst x0.\n  apply H11.\n  intro.\n  destruct H.\n  simpl in H1.\n  destruct H1;tryfalse.\n  auto.\n  unfolds; auto.\n  \n  (*----------------------*)\n  unfold isr_is_prop in H;simpl in H; simpljoin1.\n  simpl;  eauto.\n  do 8 eexists;splits; eauto.\n  eapply map_join_emp; eauto.\n  eapply map_join_emp; eauto.\n  splits; eauto.\n  unfolds; auto.\n  \n  do 6 eexists;splits;simpljoin1.\n  eapply map_join_emp; eauto.\n  eapply map_join_emp; eauto.\n  splits; eauto.\n  unfolds; auto.\n  unfold isr_is_prop.\n  intros.\n  simpl in H0.\n  subst x.\n  unfold empisr.\n  auto.\n  unfolds; auto.\nQed.\n\n\n(*---- osabst emp lemmas ----*)\nLemma Astruct'_osabst_emp :\n  forall vl e e0 M i l o a0 lo d,\n    (e, e0, M, i, lo, o, a0) |= Astruct' l d vl ->\n    o = empabst.\nProof.\n  inductions vl; intros.\n  destruct d; simpl in H; simpljoin1; tryfalse.\n  destruct d; simpl in H; tryfalse.\n  destruct t; destruct l; simpl in H; simpljoin1; eapply IHvl; eauto.\nQed.\n\nLemma Astruct_osabst_emp :\n  forall e e0 M i l o a lo t vl,\n    (e, e0, M, i, lo, o, a) |= Astruct l t vl ->\n    o = empabst.\nProof.\n  intros.\n  unfold Astruct in H; destruct t; tryfalse.\n  eapply Astruct'_osabst_emp; eauto.\nQed.\n\nLemma node_osabst_emp :\n  forall head a t e e0 M i l o a0,\n    (e, e0, M, i, l, o, a0) |= node head a t ->\n    o = empabst.\nProof.\n  intros.\n  unfold node in H; sep pure.\n  eapply Astruct_osabst_emp; eauto.\nQed.\n\nLemma Aarray'_osabst_emp :\n  forall vl l n t e e0 M i lo o a0 ,\n    (e, e0, M, i, lo, o, a0) |= Aarray' l n t vl ->\n    o = empabst.\nProof.\n  inductions vl; intros.\n  destruct n; simpl in H; simpljoin1; tryfalse.\n  destruct n; simpl in H; tryfalse.\n  destruct l; simpl in H; simpljoin1.\n  eapply IHvl; eauto.\nQed.\n\nLemma Aarray_osabst_emp :\n  forall vl l t e e0 M i lo o a0 ,\n    (e, e0, M, i, lo, o, a0) |= Aarray l t vl ->\n    o = empabst.\nProof.\n  intros.\n  unfold Aarray in H; destruct t; tryfalse.\n  eapply Aarray'_osabst_emp; eauto.\nQed.\n\nLemma ecbf_sllseg_osabst_emp :\n  forall eventl e e0 M i l o a head tail t next,\n    (e, e0, M, i, l, o, a) |= ecbf_sllseg head tail eventl t next ->\n    o = empabst.\nProof.\n  inductions eventl; intros.\n  simpl in H; simpljoin1.\n  \n  unfold ecbf_sllseg in H; fold ecbf_sllseg in H.\n  simpl_sat H; simpljoin1.\n  \n  eapply node_osabst_emp in H8; substs.\n  eapply Aarray_osabst_emp in H18; eauto; substs.\n  \n  lets Hx: IHeventl H19; substs.\n  clear - H7 H17.\n  apply OSAbstMod.extensionality; intros.\n  pose proof H7 a; pose proof H17 a.\n  rewrite OSAbstMod.emp_sem in H0, H.\n  destruct(OSAbstMod.get x12 a); tryfalse.\n  destruct(OSAbstMod.get o a); tryfalse.\n  rewrite OSAbstMod.emp_sem; auto.\nQed.\n\nLemma ecbf_sll_osabst_emp :\n  forall eventl e e0 M i l o a head t next,\n    (e, e0, M, i, l, o, a) |= ecbf_sll head eventl t next ->\n    o = empabst.\nProof.\n  intros; unfold ecbf_sll in H.\n  apply ecbf_sllseg_osabst_emp in H; auto.\nQed.\n\nLemma sllseg_osabst_emp :\n  forall osql e e0 M i l o a head tail t next,\n    (e, e0, M, i, l, o, a) |= sllseg head tail osql t next ->\n    o = empabst.\nProof.\n  inductions osql; intros.\n  simpl in H; simpljoin1.\n  \n  unfold sllseg in H; fold sllseg in H.\n  simpl_sat H; simpljoin1.\n  \n  eapply node_osabst_emp in H13; substs.\n  \n  lets Hx: IHosql H14; substs.\n  clear - H12.\n  apply OSAbstMod.extensionality; intros.\n  pose proof H12 a.\n  rewrite OSAbstMod.emp_sem in H.\n  destruct(OSAbstMod.get o a); tryfalse.\n  rewrite OSAbstMod.emp_sem; auto.\nQed.\n\nLemma sll_osabst_emp :\n  forall osql e e0 M i l o a head t next,\n    (e, e0, M, i, l, o, a) |= sll head osql t next ->\n    o = empabst.\nProof.\n  intros; unfold sll in H.\n  apply sllseg_osabst_emp in H; auto.\nQed.\n\nLemma qblkf_sllseg_osabst_emp :\n  forall eventl e e0 M i l o a head tail t next,\n    (e, e0, M, i, l, o, a) |= qblkf_sllseg head tail eventl t next ->\n    o = empabst.\nProof.\n  inductions eventl; intros.\n  simpl in H; simpljoin1.\n  \n  unfold qblkf_sllseg in H; fold qblkf_sllseg in H.\n  simpl_sat H; simpljoin1.\n  \n  eapply node_osabst_emp in H8; substs.\n  eapply Aarray_osabst_emp in H18; eauto; substs.\n  \n  lets Hx: IHeventl H19; substs.\n  clear - H7 H17.\n  apply OSAbstMod.extensionality; intros.\n  pose proof H7 a; pose proof H17 a.\n  rewrite OSAbstMod.emp_sem in H0, H.\n  destruct(OSAbstMod.get x12 a); tryfalse.\n  destruct(OSAbstMod.get o a); tryfalse.\n  rewrite OSAbstMod.emp_sem; auto.\nQed.\n\nLemma qblkf_sll_osabst_emp :\n  forall eventl e e0 M i l o a head t next,\n    (e, e0, M, i, l, o, a) |= qblkf_sll head eventl t next ->\n    o = empabst.\nProof.\n  intros; unfold ecbf_sll in H.\n  apply qblkf_sllseg_osabst_emp in H; auto.\nQed.\n\nLemma AOSQCtr_osabst_emp :\n  forall l osq e e0 M i lo o a,\n    (e, e0, M, i, lo, o, a) |= AOSQCtr l osq ->\n    o = empabst.\nProof.\n  unfold AOSQCtr; intros.\n  simpl_sat H; simpljoin1.\n  eapply node_osabst_emp in H3; auto.\nQed.\n\nLemma AOSQBlk_osabst_emp :\n  forall l osqblk msgtbl e e0 M i lo o a,\n    (e, e0, M, i, lo, o, a) |= AOSQBlk l osqblk msgtbl ->\n    o = empabst.\nProof.\n  unfold AOSQBlk; intros.\n  simpl_sat H; simpljoin1.\n  eapply node_osabst_emp in H3.\n  eapply Aarray_osabst_emp in H9; substs.\n  apply OSAbstMod.extensionality; intros.\n  pose proof H2 a0.\n  rewrite OSAbstMod.emp_sem in *.\n  destruct(OSAbstMod.get o a0); tryfalse.\n  auto.\nQed.\n\nLemma AEventData_osabst_emp :\n  forall osevent d e e0 M i lo o a,\n    (e, e0, M, i, lo, o, a) |= AEventData osevent d ->\n    o = empabst.\nProof.\n  unfold AEventData; intros.\n  destruct d; try solve [simpl in H; simpljoin1].\n  simpl_sat H; simpljoin1.\n  unfold AMsgData in H9; simpl_sat H9; simpljoin1.\n  eapply AOSQCtr_osabst_emp in H4; eapply AOSQBlk_osabst_emp in H11; substs.\n  apply OSAbstMod.extensionality; intros.\n  pose proof H2 a0.\n  rewrite OSAbstMod.emp_sem in *.\n  destruct(OSAbstMod.get o a0); tryfalse; auto.\nQed.\n\nLemma AOSEvent_osabst_emp :\n  forall l osevent etbl e e0 M i lo o a,\n    (e, e0, M, i, lo, o, a) |= AOSEvent l osevent etbl ->\n    o = empabst.\nProof.\n  unfold AOSEvent; intros.\n  simpl_sat H; simpljoin1.\n  eapply node_osabst_emp in H3.\n  unfold AOSEventTbl in H8.\n  simpl_sat H8; simpljoin1.\n  eapply Aarray_osabst_emp in H6; auto.\nQed.\n\nLemma AEventNode_osabst_emp :\n  forall v osevent etbl d e e0 M i lo o a,\n    (e, e0, M, i, lo, o, a) |= AEventNode v osevent etbl d ->\n    o = empabst.\nProof.\n  unfold AEventNode; intros.\n  simpl_sat H; simpljoin1.\n  apply AOSEvent_osabst_emp in H3; apply AEventData_osabst_emp in H4.\n  substs.\n  apply OSAbstMod.extensionality; intros.\n  pose proof H2 a0.\n  rewrite OSAbstMod.emp_sem in *.\n  destruct(OSAbstMod.get o a0); tryfalse; auto.\nQed.\n\nLemma evsllseg_osabst_emp :\n  forall ectrl msgql head tail e e0 M i lo o a,\n    (e, e0, M, i, lo, o, a) |= evsllseg head tail ectrl msgql ->\n    o = empabst.\nProof.\n  inductions ectrl; intros.\n  simpl in H; simpljoin1.\n  unfold evsllseg in H; fold evsllseg in H; destruct msgql; tryfalse; destruct a.\n  simpl_sat H; simpljoin1.\n  apply AEventNode_osabst_emp in H8.\n  eapply IHectrl in H9; substs.\n  apply OSAbstMod.extensionality; intros.\n  pose proof H7 a.\n  rewrite OSAbstMod.emp_sem in *.\n  destruct(OSAbstMod.get o a); tryfalse; auto.\nQed.\n\n(* end *)\n\n\n(*---- precise lemmas -----*)\nLemma Astruct'_precise :\n  forall vl vl' l d M1 M2 o1 o2 e e0 i lo a,\n    struct_type_vallist_match' d vl ->\n    struct_type_vallist_match' d vl' ->\n    (e, e0, M1, i, lo, o1, a) |= Astruct' l d vl ->\n    (e, e0, M2, i, lo, o2, a) |= Astruct' l d vl' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  intros; inductions vl.\n  destruct vl'.\n  destruct d; simpl in H1, H2; simpljoin1; auto; tryfalse.\n  destruct d; simpl in H1, H2; simpljoin1; auto; tryfalse.\n  destruct vl'.\n  destruct d; simpl in H1, H2; simpljoin1; auto; tryfalse.\n  \n  destruct d; simpl in H, H0; tryfalse.\n  destruct l.\n  destruct t; simpljoin1;\n  try solve [lets Hx: IHvl H H0 H1 H2; auto];  \n  try solve [\n        simpl in H1; simpljoin1; simpl in H2; simpljoin1;\n        lets Hx: IHvl H4 H3 H9 H11; simpljoin1; split; intros; [\n          assert(sub x M) by mem_join_sub_solver;\n          assert(sub x1 M) by\n              mem_join_sub_solver;\n          lets Hx1:  mapstoval_true_mem_eq H13 H14 H8 H10;\n          substs;\n          eapply eq_join_eq; eauto;\n          mem_eq_solver M |\n          apply (H6 o); auto]\n      ].\nQed.\n\nLemma Astruct_precise :\n  forall vl vl' l t M1 M2 o1 o2 e e0 i lo a,\n    struct_type_vallist_match t vl ->\n    struct_type_vallist_match t vl' ->\n          (e, e0, M1, i, lo, o1, a) |= Astruct l t vl ->\n          (e, e0, M2, i, lo, o2, a) |= Astruct l t vl' ->\n          (forall M : mem,\n             sub M1 M -> sub M2 M -> M1 = M2) /\\\n          (forall o : osabst,\n             sub o1 o -> sub o2 o -> o1 = o2 ).\nProof.\n  intros.\n  destruct t; simpl in H, H0; tryfalse.\n  unfold Astruct in H1, H2.\n  lets Hx: Astruct'_precise H H0 H1 H2; auto.\nQed.\n\nLemma node_precise :\n  forall vl vl' head t M1 M2 o1 o2 e e0 i l a,\n    (e, e0, M1, i, l, o1, a) |= node head vl t ->\n    (e, e0, M2, i, l, o2, a) |= node head vl' t ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  intros.\n  simpl in H, H0; simpljoin1; inverts H4.    \n  lets Hx: Astruct_precise H16 H8 H13 H5; auto.\nQed.\n\nLemma Aarray'_precise :\n  forall vl vl' head n t M1 M2 o1 o2 e e0 i l a,\n    (e, e0, M1, i, l, o1, a) |= Aarray' head n t vl ->\n    (e, e0, M2, i, l, o2, a) |= Aarray' head n t vl' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  intro; inductions vl; intros.\n  destruct vl'; destruct n; simpl in H, H0; tryfalse.\n  simpljoin1; split;  intros; auto.\n  \n  destruct vl'; destruct n; simpl in H, H0; tryfalse.\n  destruct head.\n  \n  simpl in H, H0; simpljoin1.\n  lets Hx: IHvl H11 H5.\n  simpljoin1; split; intros.\n  eapply eq_join_eq; eauto.\n  eapply mapstoval_true_mem_eq with (M:=M); eauto; mem_join_sub_solver.\n  mem_eq_solver M.\n  apply H0 with (o:=o); eauto.\nQed.\n\nLemma Aarray_precise :\n  forall vl vl' head t M1 M2 o1 o2 e e0 i l a,\n    (e, e0, M1, i, l, o1, a) |= Aarray head t vl ->\n    (e, e0, M2, i, l, o2, a) |= Aarray head t vl' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).      \nProof.\n  intros.\n  unfold Aarray in H, H0.\n  destruct t; simpl in H, H0; tryfalse.\n  eapply Aarray'_precise; eauto.\nQed.\n\n\nLemma ecbf_sll_precise :\n  forall eventl eventl' head M1 M2 o1 o2 e e0 i l a,\n    (e, e0, M1, i, l, o1, a) |= ecbf_sll head eventl os_ucos_h.OS_EVENT V_OSEventListPtr ->\n    (e, e0, M2, i, l, o2, a) |= ecbf_sll head eventl' os_ucos_h.OS_EVENT V_OSEventListPtr ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  inductions eventl; intros.\n  simpl in H; simpljoin1.\n  destruct eventl'.\n  simpl in H0; simpljoin1; auto.\n  unfold ecbf_sll in H0; unfold ecbf_sllseg in H0; fold ecbf_sllseg in H0.\n  unfold node in H0; simpl in H0; simpljoin1; tryfalse.\n  destruct eventl'.\n  simpl in H0; simpljoin1.\n  unfold ecbf_sll in H; unfold ecbf_sllseg in H; fold ecbf_sllseg in H.\n  unfold node in H; simpl in H; simpljoin1; tryfalse.\n  unfold ecbf_sll in H, H0; unfold ecbf_sllseg in H, H0; fold ecbf_sllseg in H, H0.\n  simpl_sat H; simpljoin1; simpl_sat H0; simpljoin1.\n \n  lets Hx: node_precise H9 H12.\n  rewrite H14 in H22; inverts H22.\n  \n  lets Hx1: Aarray_precise H19 H27.\n\n  unfold ecbf_sll in IHeventl.\n  simpljoin1; split; intros.\n  \n  assert(x = x2).\n  assert(sub x8 M) by mem_join_sub_solver.\n  assert(sub x15 M) by mem_join_sub_solver.\n\n  lets Hx: node_vl_eq H9 H12 H13 H15.\n  simpl in Hx; unfold V_OSEventListPtr in H3, H4.\n  unfold node in H9, H12.\n  destruct H9, H12; sep split in H9; sep split in  H12; simpljoin1.\n  assert(exists a1 a2 a3 a4 a5 a6, a = a1::a2::a3::a4::a5::a6::nil).\n  eapply struct_type_vallist_match_os_event in H23; simpljoin1; do 6 eexists; eauto.\n  assert(exists v1 v2 v3 v4 v5 v6, v = v1::v2::v3::v4::v5::v6::nil).\n  eapply struct_type_vallist_match_os_event; eauto; do 6 eexists; eauto.\n  simpljoin1; simpl in Hx; simpl in H3, H4; simpljoin1; inversion H3; inversion H4; substs; auto.\n  substs.\n  \n  lets Hx2: IHeventl H20 H28.\n  simpljoin1; mem_eq_solver M.\n  \n  eapply ecbf_sllseg_osabst_emp in H20.\n  eapply ecbf_sllseg_osabst_emp in H28.\n  substs.\n  eapply osabst_eq_join_eq; eauto.\n  apply (H2 o).\n  clear - H5 H8.\n  unfold sub in *; geat.\n  clear - H10 H11.\n  unfold sub in *; geat.\n\n  eapply osabst_eq_join_eq; eauto.\n  apply (H0 o).\n  clear - H5 H8 H18.\n  unfold sub in *.\n  geat.\n  clear - H10 H11 H26.\n  unfold sub in *.\n  geat.\nQed.\n\n\nLemma AOSEventFreeList_precise :\n  forall eventl eventl' M1 M2 o1 o2 e e0 i l a,\n    (e, e0, M1, i, l, o1, a) |= AOSEventFreeList eventl ->\n    (e, e0, M2, i, l, o2, a) |= AOSEventFreeList eventl' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSEventFreeList; intros.\n  simpl in H, H0; simpljoin1.\n\n  rewrite H23 in H9; inverts H9.\n  split; intros.\n  assert(x = x6).\n\n  assert(isptr x).\n  eapply isptr_ecbf_sll; eauto.\n  assert(isptr x6).\n  eapply isptr_ecbf_sll; eauto.\n  destruct x, x6; auto;\n  try(unfolds in H2; destruct H2; simpljoin1; tryfalse);\n  try(unfolds in H3; destruct H3; simpljoin1; tryfalse).\n  unfolds in H10; simpljoin1; simpl in H4; simpljoin1.\n  \n  unfolds in H24; simpljoin1; simpl in H12; destruct a0; simpl in H12; simpljoin1.\n  clear - H4 H12 H1 H15 H H0 H3 H10.\n  unfold ptomval in H4; unfold ptomval in H12; substs.\n  assert(sub (sig (x20, Int.unsigned Int.zero) (true, Pointer b i0 3)) M).\n  mem_join_sub_solver.\n  assert(sub (sig (x20, Int.unsigned Int.zero) (true, MNull)) M).\n  mem_join_sub_solver.\n\n  lets Hx: mem_sub_sig_eq H2 H4; tryfalse.\n  \n  unfolds in H10; simpljoin1; simpl in H4; destruct a0; simpl in H4; simpljoin1.\n  unfolds in H24; simpljoin1; simpl in H12; simpljoin1.\n  clear - H4 H12 H1 H15 H H0 H3 H10.\n  unfold ptomval in H4; unfold ptomval in H12; substs.\n  assert(sub (sig (x20, Int.unsigned Int.zero) (true, Pointer b i0 3)) M).\n  mem_join_sub_solver.\n  assert(sub (sig (x20, Int.unsigned Int.zero) (true, MNull)) M).\n  mem_join_sub_solver.\n  lets Hx: mem_sub_sig_eq H2 H4; tryfalse.\n \n  inverts H2; inverts H3.\n  assert(sub x0 M).\n  apply join_sub_l in H1.\n  eapply sub_trans; eauto.\n  assert(sub x7 M).\n  apply join_sub_l in H15.\n  eapply sub_trans; eauto.\n  lets Hx: mapstoval_true_vptr_eq H10 H24 H2 H3; simpljoin1.\n  \n  substs.\n  \n  assert(x0 = x7).\n  eapply mapstoval_true_mem_eq with (M:=M); eauto; mem_join_sub_solver.\n  substs.\n  eapply eq_join_eq; eauto.\n  lets Hx: ecbf_sll_precise H19 H5; simpljoin1.\n  mem_eq_solver M.\n  \n  apply ecbf_sll_osabst_emp in H19; apply ecbf_sll_osabst_emp in H5.\n  substs; auto.\nQed.\n\n\nLemma osq_sll_precise :\n  forall osql osql' head e e0 M1 M2 i l o1 o2 a,\n    (e, e0, M1, i, l, o1, a) |= sll head osql os_ucos_h.OS_Q V_OSQPtr ->\n    (e, e0, M2, i, l, o2, a) |= sll head osql' os_ucos_h.OS_Q V_OSQPtr ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n           sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  inductions osql; intros.\n  simpl in H; simpljoin1.\n  destruct osql'.\n  simpl in H0; simpljoin1; auto.\n  unfold sll in H0; unfold sllseg in H0; fold sllseg in H0.\n  unfold node in H0; simpl in H0; simpljoin1; tryfalse.\n  destruct osql'.\n  simpl in H0; simpljoin1.\n  unfold sll in H; unfold sllseg in H; fold sllseg in H.\n  unfold node in H; simpl in H; simpljoin1; tryfalse.\n  unfold sll in H, H0; unfold sllseg in H, H0; fold sllseg in H, H0.\n  simpl_sat H; simpljoin1; simpl_sat H0; simpljoin1.\n  \n  lets Hx: node_precise H14 H19.\n  \n  unfold sll in IHosql.\n  simpljoin1; split; intros.\n  assert(x5 = x6).\n  assert(sub x12 M) by mem_join_sub_solver.\n  assert(sub x17 M) by mem_join_sub_solver.\n  lets Hx: node_vl_eq H14 H19 H5 H6.\n  simpl in Hx; unfold V_OSEventListPtr in H9, H10.\n  unfold node in H14, H19.\n  destruct H14, H19; sep split in H7; sep split in H8; simpljoin1.\n  assert(exists a1 a2 a3 a4 a5 a6 a7 a8, a = a1::a2::a3::a4::a5::a6::a7::a8::nil).\n  eapply struct_type_vallist_match_os_q; eauto.\n  assert(exists v1 v2 v3 v4 v5 v6 v7 v8, v = v1::v2::v3::v4::v5::v6::v7::v8::nil).\n  eapply struct_type_vallist_match_os_q; eauto.\n  simpljoin1; simpl in Hx; simpl in H9, H10; simpljoin1; inversion H9; inversion H10; substs; auto.\n  substs.\n  \n  lets Hx2: IHosql H15 H20.\n  simpljoin1; mem_eq_solver M.\n  \n  eapply sllseg_osabst_emp in H15.\n  eapply sllseg_osabst_emp in H20.\n  substs.\n  eapply osabst_eq_join_eq; eauto.\n  osabst_eq_solver o.\nQed.\n\n\nLemma AOSQFreeList_precise :\n  forall osql osql' e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= AOSQFreeList osql ->\n    (e, e0, M2, i, l, o2, a) |= AOSQFreeList osql' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSQFreeList; intros.\n  simpl in H, H0; simpljoin1.\n  rewrite H23 in H9; inverts H9.\n  split; intros.\n  assert(x = x6).\n  \n  assert(isptr x).\n  eapply sll_isptr; eauto.\n  assert(isptr x6).\n  eapply sll_isptr; eauto.\n  destruct x, x6; auto;\n  try(unfolds in H2; destruct H2; simpljoin1; tryfalse);\n  try(unfolds in H3; destruct H3; simpljoin1; tryfalse).\n  unfolds in H10; simpljoin1; simpl in H4; simpljoin1.\n  unfolds in H24; simpljoin1; simpl in H12; destruct a0; simpl in H12; simpljoin1.\n  clear - H4 H12 H1 H15 H H0 H3 H10.\n  unfold ptomval in H4; unfold ptomval in H12; substs.\n  assert(sub x7 M).\n  clear - H15 H.\n  unfold sub in *; geat.\n  assert(sub x0 M).\n  clear - H1 H0.\n  unfold sub in *; geat.\n  lets Hx: mem_join_sig_sub_eq H10 H3 H2 H4; tryfalse.\n  \n  unfolds in H10; simpljoin1; simpl in H4; destruct a0; simpl in H4; simpljoin1.\n  unfolds in H24; simpljoin1; simpl in H12; simpljoin1.\n  clear - H4 H12 H1 H15 H H0 H3 H10.\n  unfold ptomval in H4; unfold ptomval in H12; substs.\n  assert(sub x7 M).\n  clear - H15 H.\n  unfold sub in *; geat.\n  assert(sub x0 M).\n  clear - H1 H0.\n  unfold sub in *; geat.\n  lets Hx: mem_join_sig_sub_eq H10 H3 H2 H4; tryfalse.\n\n  inverts H2; inverts H3.\n  assert(sub x0 M).\n  apply join_sub_l in H1.\n  eapply sub_trans; eauto.\n  assert(sub x7 M).\n  apply join_sub_l in H15.\n  eapply sub_trans; eauto.\n  lets Hx: mapstoval_true_vptr_eq H10 H24 H2 H3; simpljoin1.\n\n  substs.\n  assert(x0 = x7).\n  eapply mapstoval_true_mem_eq with (M:=M); eauto; mem_join_sub_solver.\n  substs.\n  eapply eq_join_eq; eauto.\n  \n  lets Hx: osq_sll_precise H19 H5; simpljoin1.\n  mem_eq_solver M.\n  \n  apply sll_osabst_emp in H19; apply sll_osabst_emp in H5.\n  substs; auto.\nQed.\n\n    \nLemma qblkf_sll_precise :\n  forall qblkl qblkl' head e e0 M1 M2 i l o1 o2 a,\n    (e, e0, M1, i, l, o1, a) |= qblkf_sll head qblkl os_ucos_h.OS_Q_FREEBLK V_nextblk ->\n    (e, e0, M2, i, l, o2, a) |= qblkf_sll head qblkl' os_ucos_h.OS_Q_FREEBLK V_nextblk ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  inductions qblkl; intros.\n  simpl in H; simpljoin1.\n  destruct qblkl'.\n  simpl in H0; simpljoin1; auto.\n  unfold qblkf_sll in H0; unfold qblkf_sllseg in H0; fold qblkf_sllseg in H0.\n  unfold node in H0; simpl in H0; simpljoin1; tryfalse.\n  destruct qblkl'.\n  simpl in H0; simpljoin1.\n  unfold qblkf_sll in H; unfold qblkf_sll in H; fold qblkf_sll in H.\n  unfold node in H; simpl in H; simpljoin1; tryfalse.\n  unfold qblkf_sll in H, H0; unfold qblkf_sllseg in H, H0; fold qblkf_sllseg in H, H0.\n  simpl_sat H; simpljoin1; simpl_sat H0; simpljoin1.\n  lets Hx: node_precise H9 H12.\n  rewrite H14 in H22; inverts H22.\n    \n  lets Hx1: Aarray_precise H19 H27.\n  \n  unfold qblkf_sll in IHqblkl.\n  simpljoin1; split; intros.\n\n  assert(x = x2).\n  assert(sub x8 M) by mem_join_sub_solver.\n  assert(sub x15 M) by mem_join_sub_solver.\n  lets Hx: node_vl_eq H9 H12 H13 H15.\n  simpl in Hx; unfold V_OSQPtr in H3, H4.\n  unfold node in H9, H12.\n  destruct H9, H12; sep split in H9; sep split in  H12; simpljoin1.\n  assert(exists a1 a2 , a = a1::a2::nil).\n  \n  eapply struct_type_vallist_match_os_q_freeblk; eauto.\n  assert(exists v1 v2, v = v1::v2::nil).\n  eapply struct_type_vallist_match_os_q_freeblk; eauto.\n  simpljoin1; simpl in Hx; simpl in H3, H4; simpljoin1; inversion H3; inversion H4; substs; auto.\n  substs.\n    \n  lets Hx2: IHqblkl H20 H28.\n  simpljoin1; mem_eq_solver M.      \n  eapply qblkf_sllseg_osabst_emp in H20.\n  eapply qblkf_sllseg_osabst_emp in H28.\n  substs.\n  eapply osabst_eq_join_eq; eauto.\n  osabst_eq_solver o.\n  eapply osabst_eq_join_eq; eauto.\n  osabst_eq_solver o.\nQed.\n\nLemma AOSQFreeBlk_precise :\n  forall qblkl qblkl' e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= AOSQFreeBlk qblkl ->\n    (e, e0, M2, i, l, o2, a) |= AOSQFreeBlk qblkl' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n      (forall o : osabst,\n         sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSQFreeBlk; intros.\n  simpl in H, H0; simpljoin1.\n  rewrite H23 in H9; inverts H9.\n  split; intros.\n  assert(x = x6).\n  assert(isptr x).\n  eapply qblkf_sll_isptr; eauto.\n  assert(isptr x6).\n  eapply qblkf_sll_isptr; eauto.\n  destruct x, x6; auto;\n  try(unfolds in H2; destruct H2; simpljoin1; tryfalse);\n  try(unfolds in H3; destruct H3; simpljoin1; tryfalse).\n  unfolds in H10; simpljoin1; simpl in H4; simpljoin1.\n  unfolds in H24; simpljoin1; simpl in H12; destruct a0; simpl in H12; simpljoin1.\n  clear - H4 H12 H1 H15 H H0 H3 H10.\n  unfold ptomval in H4; unfold ptomval in H12; substs.\n  assert(sub x7 M) by mem_join_sub_solver.\n  assert(sub x0 M) by mem_join_sub_solver.\n  lets Hx: mem_join_sig_sub_eq H10 H3 H2 H4; tryfalse.\n  \n  unfolds in H10; simpljoin1; simpl in H4; destruct a0; simpl in H4; simpljoin1.\n  unfolds in H24; simpljoin1; simpl in H12; simpljoin1.\n  clear - H4 H12 H1 H15 H H0 H3 H10.\n  unfold ptomval in H4; unfold ptomval in H12; substs.\n  assert(sub x7 M) by mem_join_sub_solver.\n  assert(sub x0 M) by mem_join_sub_solver.\n  lets Hx: mem_join_sig_sub_eq H10 H3 H2 H4; tryfalse.\n  \n  inverts H2; inverts H3.\n  assert(sub x0 M).\n  apply join_sub_l in H1.\n  eapply sub_trans; eauto.\n  assert(sub x7 M).\n  apply join_sub_l in H15.\n  eapply sub_trans; eauto.\n  lets Hx: mapstoval_true_vptr_eq H10 H24 H2 H3; simpljoin1.\n\n  substs.\n  assert(x0 = x7).\n  eapply mapstoval_true_mem_eq with (M:=M); eauto; mem_join_sub_solver.\n  substs.\n  eapply eq_join_eq; eauto.\n  \n  lets Hx: qblkf_sll_precise H19 H5; simpljoin1.\n  mem_eq_solver M.\n    \n  apply qblkf_sll_osabst_emp in H19; apply qblkf_sll_osabst_emp in H5.\n  substs; auto.\nQed.\n\nLemma AOSEventTbl_precise :\n  forall l etbl etbl' e e0 M1 M2 i lo o1 o2 a,\n    (e, e0, M1, i, lo, o1, a) |= AOSEventTbl l etbl ->\n    (e, e0, M2, i, lo, o2, a) |= AOSEventTbl l etbl' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSEventTbl; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  lets Hx: Aarray_precise H11 H4; auto.\nQed.\n\nLemma AOSEvent_precise :\n  forall l osevent osevent' etbl etbl' e e0 M1 M2 i lo o1 o2 a,\n    (e, e0, M1, i, lo, o1, a) |= AOSEvent l osevent etbl ->\n    (e, e0, M2, i, lo, o2, a) |= AOSEvent l osevent' etbl' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSEvent; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  rewrite H14 in H40; inverts H40.\n        \n  lets Hx1: node_precise H30 H4.\n  \n  lets Hx2: AOSEventTbl_precise H35 H9.\n  simpljoin1; split; intros.\n  mem_eq_solver M.\n  osabst_eq_solver o.\nQed.\n\n\nLemma AOSQCtr_precise :\n  forall l osq osq' e e0 M1 M2 i lo o1 o2 a,\n    (e, e0, M1, i, lo, o1, a) |= AOSQCtr l osq ->\n    (e, e0, M2, i, lo, o2, a) |= AOSQCtr l osq' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSQCtr; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  eapply node_precise; eauto.\nQed.\n\n \nLemma AOSQBlk_precise :\n  forall l osqblk osqblk' msgtbl msgtbl' e e0 M1 M2 i lo o1 o2 a,\n    (e, e0, M1, i, lo, o1, a) |= AOSQBlk l osqblk msgtbl ->\n    (e, e0, M2, i, lo, o2, a) |= AOSQBlk l osqblk' msgtbl' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSQBlk; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  rewrite H21 in H9; inverts H9.\n  lets Hx1: node_precise H16 H4.\n  lets Hx2: Aarray_precise H22 H10.\n  simpljoin1; split; intros.\n  mem_eq_solver M.\n  osabst_eq_solver o.\nQed.\n\nLemma AMsgData_precise :\n  forall l osq osq' osqblk osqblk' msgtbl msgtbl' e e0 M1 M2 i lo o1 o2 a,\n    (e, e0, M1, i, lo, o1, a) |= AMsgData l osq osqblk msgtbl ->\n    (e, e0, M2, i, lo, o2, a) |= AMsgData l osq' osqblk' msgtbl' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n               sub o1 o -> sub o2 o -> o1 = o2).  \nProof.\n  unfold AMsgData; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  \n  intros.\n  simpljoin1; split; intros.\n  assert(struct_atom_val_eq osq osq' os_ucos_h.OS_Q /\\\n         struct_type_vallist_match os_ucos_h.OS_Q osq /\\\n                 struct_type_vallist_match os_ucos_h.OS_Q osq'\n        ).\n  split.\n  eapply AOSQCtr_osq_eq with (M:=M); eauto; mem_join_sub_solver.\n  unfold AOSQCtr in H4, H16; unfold node in H4, H16; simpl_sat H4; simpl_sat H16; simpljoin1.\n  split; auto.\n  simpljoin1; simpl in H2.\n  assert(exists t1 t2 t3 t4 t5 t6 t7 t8, osq = t1::t2::t3::t4::t5::t6::t7::t8::nil).\n  eapply struct_type_vallist_match_os_q; eauto.\n  assert(exists t1 t2 t3 t4 t5 t6 t7 t8, osq' = t1::t2::t3::t4::t5::t6::t7::t8::nil).\n  eapply struct_type_vallist_match_os_q; eauto.\n  simpljoin1.\n  simpl in H2; simpljoin1; unfold V_qfreeblk in H9, H21; simpl nth_val in H9, H21;\n  inverts H9; inverts H21.\n  \n  lets Hx1: AOSQCtr_precise H16 H4.\n  lets Hx2: AOSQBlk_precise H22 H10.\n  simpljoin1.\n  mem_eq_solver M.\n  \n  eapply AOSQCtr_osabst_emp in H16.\n  eapply AOSQCtr_osabst_emp in H4.\n  eapply AOSQBlk_osabst_emp in H22.\n  eapply AOSQBlk_osabst_emp in H10.\n  substs.\n  apply OSAbstMod.extensionality; intros.\n  pose proof H15 a0; pose proof H3 a0.\n  rewrite OSAbstMod.emp_sem in *.\n  destruct(OSAbstMod.get o1 a0);\n    destruct(OSAbstMod.get o2 a0);\n    tryfalse; auto.\nQed.\n\nLemma AEventData_precise :\n  forall osevent osevent' d d' e e0 M1 M2 i lo o1 o2 a,\n    (e, e0, M1, i, lo, o1, a) |= AEventData osevent d ->\n    (e, e0, M2, i, lo, o2, a) |= AEventData osevent' d' ->\n    struct_atom_val_eq osevent osevent' os_ucos_h.OS_EVENT ->\n    struct_type_vallist_match os_ucos_h.OS_EVENT osevent ->\n    struct_type_vallist_match os_ucos_h.OS_EVENT osevent' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AEventData; intros.\n  simpl in H1.\n  assert(exists v1 v2 v3 v4 v5 v6, osevent = v1::v2::v3::v4::v5::v6::nil).\n  eapply struct_type_vallist_match_os_event; eauto.\n  assert(exists t1 t2 t3 t4 t5 t6, osevent' = t1::t2::t3::t4::t5::t6::nil).\n  eapply struct_type_vallist_match_os_event; eauto.\n  simpljoin1.\n  simpl in H1; simpljoin1; unfold V_OSEventType in *; simpl nth_val in *. \n  destruct d, d'; simpl_sat H; simpl_sat H0; simpljoin1;\n  try solve [un_eq_event_type_solver];\n  try solve [simpljoin1; intros; auto].\n  unfold V_OSEventPtr, V_OSEventCnt in *; simpl nth_val in *.\n  inverts H20; inverts H25; inverts H6; inverts H11.\n  eapply AMsgData_precise; eauto.\nQed.\n\n\nLemma AEventNode_precise :\n  forall l osevent osevent' etbl etbl' d d' e e0 M1 M2 i lo o1 o2 a,\n    (e, e0, M1, i, lo, o1, a) |= AEventNode l osevent etbl d ->\n    (e, e0, M2, i, lo, o2, a) |= AEventNode l osevent' etbl' d' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AEventNode; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  \n  simpljoin1; split; intros.\n  assert(struct_atom_val_eq osevent osevent' os_ucos_h.OS_EVENT /\\\n         struct_type_vallist_match os_ucos_h.OS_EVENT osevent /\\\n         struct_type_vallist_match os_ucos_h.OS_EVENT osevent'\n        ).\n  split.\n  eapply AOSEvent_osevent_eq with (M:=M); eauto; mem_join_sub_solver.\n  unfold AOSEvent in H9, H4; unfold node in H9, H4.\n  simpl_sat H9; simpl_sat H4; simpljoin1; auto.\n  simpljoin1.\n  \n  lets Hx1: AEventData_precise H10 H5 H2 H7 H11.\n  lets Hx2: AOSEvent_precise H9 H4.\n  simpljoin1.\n  mem_eq_solver M.\n  \n  apply AOSEvent_osabst_emp in H9;\n    apply AOSEvent_osabst_emp in H4;\n    apply AEventData_osabst_emp in H10;\n    apply AEventData_osabst_emp in H5.\n  substs.\n  apply OSAbstMod.extensionality; intros.\n  pose proof H3 a0; pose proof H8 a0.\n  rewrite OSAbstMod.emp_sem in *.\n  destruct(OSAbstMod.get o2 a0);\n    destruct(OSAbstMod.get o1 a0);\n    tryfalse; auto.\nQed.\n\nLemma evsllseg_precise :\n  forall ectrl ectrl' msgql msgql' head e e0 M1 M2 i l o1 o2 a,\n    (e, e0, M1, i, l, o1, a) |= evsllseg head Vnull ectrl msgql ->\n    (e, e0, M2, i, l, o2, a) |= evsllseg head Vnull ectrl' msgql' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  inductions ectrl; intros.\n  simpl in H; simpljoin1.\n  destruct ectrl'.\n  simpl in H0; simpljoin1; auto.\n  unfold evsllseg in H0; fold evsllseg in H0; destruct msgql'; tryfalse; destruct e1.\n  unfold AEventNode in H0; simpl in H0; simpljoin1; tryfalse.\n  destruct ectrl'.\n  simpl in H0; simpljoin1.\n  unfold evsllseg in H; fold evsllseg in H; destruct msgql; tryfalse; destruct a.\n  unfold AEventNode in H; simpl in H; simpljoin1; tryfalse.\n  \n  unfold evsllseg in H, H0;  fold evsllseg in H, H0.\n  destruct msgql; destruct msgql'; tryfalse; destruct a, e1.\n  destruct H, H0;\n    simpl_sat H; simpljoin1; simpl_sat H0; simpljoin1.\n  \n  simpljoin1; split; intros.\n  assert(\n      struct_atom_val_eq v v1 os_ucos_h.OS_EVENT /\\\n      struct_type_vallist_match os_ucos_h.OS_EVENT v /\\\n      struct_type_vallist_match os_ucos_h.OS_EVENT v1\n    ).\n  split.\n\n  eapply AEventNode_osevent_eq with (M:=M); eauto; mem_join_sub_solver.\n  split;\n    unfold AEventNode in H9, H13; unfold AOSEvent in H9, H13; unfold node in H9, H13;\n    simpl_sat H9; simpl_sat H13; simpljoin1; auto.\n  simpljoin1.\n  simpl in H1.\n  assert(exists v1 v2 v3 v4 v5 v6, v = v1::v2::v3::v4::v5::v6::nil).\n  eapply struct_type_vallist_match_os_event; eauto.\n  assert(exists a1 a2 a3 a4 a5 a6, v1 = a1::a2::a3::a4::a5::a6::nil).\n  eapply struct_type_vallist_match_os_event; eauto.\n  simpljoin1.\n  simpl in H1; simpljoin1; unfold V_OSEventListPtr in *; simpl nth_val in *; inverts H3; inverts H4.\n  lets Hx1: AEventNode_precise H9 H13.\n  lets Hx2: IHectrl H10 H14.\n  simpljoin1.\n  mem_eq_solver M.\n\n  apply AEventNode_osabst_emp in H9;\n    apply AEventNode_osabst_emp in H13;\n    apply evsllseg_osabst_emp in H10;\n    apply evsllseg_osabst_emp in H14.\n  substs.\n  apply OSAbstMod.extensionality; intros.\n  pose proof H12 a; pose proof H8 a.\n  rewrite OSAbstMod.emp_sem in *.\n  destruct(OSAbstMod.get o1 a); destruct(OSAbstMod.get o2 a); tryfalse; auto.\nQed.\n\nLemma AECBList_precise :\n  forall ectrl ectrl' msgql msgql' ecbls ecbls' tcbls tcbls' e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= AECBList ectrl msgql ecbls tcbls ->\n    (e, e0, M2, i, l, o2, a) |= AECBList ectrl' msgql' ecbls' tcbls' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AECBList; intros.\n  simpl in H, H0; simpljoin1.\n  rewrite H16 in H37; inverts H37.\n  split; intros.\n  assert(x = x6).\n  assert(isptr x).\n  eapply evsllseg_isptr; eauto.\n  assert(isptr x6).\n  eapply evsllseg_isptr; eauto.\n  destruct x, x6; auto;\n  try(unfolds in H1; destruct H1; simpljoin1; tryfalse);\n  try(unfolds in H2; destruct H2; simpljoin1; tryfalse).\n  unfolds in H17; simpljoin1; simpl in H3; simpljoin1.\n  unfolds in H38; simpljoin1; simpl in H13; destruct a0; simpl in H13; simpljoin1.\n  clear - H3 H13 H2 H10 H H0 H8 H29.\n  unfold ptomval in H3; unfold ptomval in H13; substs.\n  assert(sub x27 M) by mem_join_sub_solver.\n  assert(sub x13 M) by mem_join_sub_solver.\n  lets Hx: mem_join_sig_sub_eq H10 H2 H1 H3; tryfalse.\n  \n  unfolds in H17; simpljoin1; simpl in H3; destruct a0; simpl in H3; simpljoin1.\n  unfolds in H38; simpljoin1; simpl in H13; simpljoin1.\n  clear - H3 H13 H2 H10 H H0 H8 H29.\n  unfold ptomval in H3; unfold ptomval in H13; substs.\n  assert(sub x27 M) by mem_join_sub_solver.\n  assert(sub x13 M) by mem_join_sub_solver.\n  lets Hx: mem_join_sig_sub_eq H10 H2 H1 H3; tryfalse.\n  \n  inverts H1; inverts H2.\n  assert(sub x13 M).\n  apply join_sub_l in H8.\n  eapply sub_trans; eauto.\n  assert(sub x27 M).\n  apply join_sub_l in H29.\n  eapply sub_trans; eauto.\n  lets Hx: mapstoval_true_vptr_eq H17 H38 H1 H2; simpljoin1.\n  substs.\n\n  assert(x13 = x27).\n  eapply mapstoval_true_mem_eq with (M:=M); eauto; mem_join_sub_solver.\n  substs.\n  eapply eq_join_eq; eauto.\n  \n  \n  lets Hx: evsllseg_precise H33 H12; simpljoin1.\n  mem_eq_solver M.\n\n  apply evsllseg_osabst_emp in H33; \n    apply evsllseg_osabst_emp in H12; substs; auto.\nQed.\n\nLemma AOSMapTbl_precise :\n  forall e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= AOSMapTbl ->\n    (e, e0, M2, i, l, o2, a) |= AOSMapTbl ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSMapTbl; unfold GAarray; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  simpl in H9, H4; simpljoin1.\n  rewrite H0 in H; inverts H.\n  rewrite <- H2 in H9.\n  unfold addrval_to_addr in H9; destruct x, x6; inverts H9.\n  assert(Int.repr (Int.unsigned i1) = Int.repr (Int.unsigned i0)).\n  rewrite H3; auto.\n  do 2 rewrite Int.repr_unsigned in H; substs.\n  eapply Aarray_precise; eauto.\nQed.\n\nLemma AOSUnMapTbl_precise :\n  forall e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= AOSUnMapTbl ->\n    (e, e0, M2, i, l, o2, a) |= AOSUnMapTbl ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSUnMapTbl; unfold GAarray; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  simpl in H9, H4; simpljoin1.\n  rewrite H0 in H; inverts H.\n  rewrite <- H2 in H9.\n  unfold addrval_to_addr in H9; destruct x, x6; inverts H9.\n  assert(Int.repr (Int.unsigned i1) = Int.repr (Int.unsigned i0)).\n  rewrite H3; auto.\n  do 2 rewrite Int.repr_unsigned in H; substs.\n  eapply Aarray_precise; eauto.\nQed.\n\nLemma AOSTCBPrioTbl_precise :\n  forall ptbl ptbl' rtbl rtbl' tcbls tcbls' vhold vhold' e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= AOSTCBPrioTbl ptbl rtbl tcbls vhold ->\n    (e, e0, M2, i, l, o2, a) |= AOSTCBPrioTbl ptbl' rtbl' tcbls' vhold' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSTCBPrioTbl; unfold GAarray; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  simpl in H73, H36; simpljoin1.\n  rewrite H0 in H; inverts H.\n  rewrite <- H2 in H6.\n  unfold addrval_to_addr in H6; destruct x49, x17; inverts H6.\n  assert(Int.repr (Int.unsigned i1) = Int.repr (Int.unsigned i0)).\n  rewrite H5; auto.\n  do 2 rewrite Int.repr_unsigned in H; substs.\n  simpl in H68, H31; simpljoin1.\n  rewrite H4 in H; inverts H.\n  simpljoin1; split; intros.\n  simpl in H69, H32; simpljoin1.\n  assert(x6 = x0).\n  rewrite <- H6 in H9.\n  unfold addrval_to_addr in H9; destruct vhold, vhold'.\n  inverts H9.\n  assert(Int.repr (Int.unsigned i1) = Int.repr (Int.unsigned i2)).\n  rewrite H11; auto.\n  do 2 rewrite Int.repr_unsigned in H3; substs.\n  eapply mapstoval_true_mem_eq with (M:=M); eauto; mem_join_sub_solver.\n  substs.\n  lets Hx: Aarray_precise H74 H37; simpljoin1.\n  eapply eq_join_eq; eauto.\n  apply H3 with (M:=M); mem_join_sub_solver.\n  apply Aarray_osabst_emp in H74; apply Aarray_osabst_emp in H37; substs.\n  simpl in H69, H32; simpljoin1.\nQed.\n \nLemma AOSIntNesting_precise :\n  forall e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= AOSIntNesting ->\n    (e, e0, M2, i, l, o2, a) |= AOSIntNesting ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSIntNesting; intros.\n  simpl in H, H0; simpljoin1.\n  rewrite H13 in H4; inverts H4.\n  simpljoin1; split; intros.\n  eapply mapstoval_true_mem_eq; eauto.\n  auto.\nQed.\n\nLemma AOSRdyTblGrp_precise :\n  forall rtbl rtbl' rgrp rgrp' e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= AOSRdyTblGrp rtbl rgrp ->\n    (e, e0, M2, i, l, o2, a) |= AOSRdyTblGrp rtbl' rgrp' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSRdyTblGrp; unfold AOSRdyTbl; unfold AOSRdyGrp; unfold GAarray; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n\n  simpl in H65, H32; simpljoin1.\n  rewrite H0 in H; inverts H.\n  rewrite <- H2 in H6.\n  unfold addrval_to_addr in H6; destruct x54, x29.\n  inverts H6.\n  assert(Int.repr (Int.unsigned i0) = Int.repr (Int.unsigned i1)).\n  rewrite H5; auto.\n  do 2 rewrite Int.repr_unsigned in H; substs.\n  \n  simpl in H50, H17; simpljoin1.\n  rewrite H21 in H9; inverts H9.\n  simpljoin1; split; intros.\n  assert(sub x6 M) by mem_join_sub_solver.\n  assert(sub x0 M) by mem_join_sub_solver.\n  lets Hx': mapstoval_true_rule_type_val_match_eq H51 H18 H22 H11 H4; lets Hx: Hx' H5; clear Hx'.\n  simpljoin1.\n  \n  lets Hx: Aarray_precise H33 H66; simpljoin1.\n  eapply eq_join_eq; eauto.\n  symmetry.\n  mem_eq_solver M.\n  \n  apply Aarray_osabst_emp in H33; apply Aarray_osabst_emp in H66.\n  substs; auto.\nQed.\n\nLemma AOSTime_precise :\n  forall t t' e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= AOSTime (Vint32 t) ->\n    (e, e0, M2, i, l, o2, a) |= AOSTime (Vint32 t') ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AOSTime; intros.\n  simpl in H, H0; simpljoin1;\n  rewrite H13 in H4; inverts H4.\n  simpljoin1; split; intros; auto.\n  lets Hx: mapstoval_true_rule_type_val_match_eq H5 H14 H0 H; simpl; auto.\n  simpljoin1.\nQed.\n\nLemma Aabsdata_precise :\n  forall id absdata absdata' e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= Aabsdata id absdata ->\n    (e, e0, M2, i, l, o2, a) |= Aabsdata id absdata' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  intros; simpl in H, H0.\n  simpljoin1; split; intros; auto.\n  lets Hx: osabst_sub_sig_eq H H0.\n  substs; auto.\nQed.\n\n\nLemma AGVars_precise :\n  forall e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= AGVars ->\n    (e, e0, M2, i, l, o2, a) |= AGVars ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold AGVars; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  simpl in H43, H4; simpljoin1.\n  rewrite H26 in H7; inverts H7.\n  \n  simpl in H53, H14; simpljoin1.\n  rewrite H24 in H5; inverts H5.\n\n  simpl in H58,  H19; simpljoin1.\n  rewrite H22 in H5; inverts H5.\n\n  simpl in H64, H25; simpljoin1.\n  rewrite H25 in H5; inverts H5.\n\n  simpl in H75, H36; simpljoin1.\n  rewrite H33 in H5; inverts H5.\n\n  simpl in H68, H29; simpljoin1.\n  rewrite H29 in H5; inverts H5.\n\n  simpljoin1; split; intros.\n  lets Hx1: mapstoval_true_mem_eq M H9 H27.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  lets Hx2: mapstoval_true_mem_eq M H7 H28.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  lets Hx3: mapstoval_true_mem_eq M H10 H31.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  lets Hx4: mapstoval_true_mem_eq M H12 H32.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  lets Hx5: mapstoval_true_mem_eq M H13 H34.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  lets Hx6: mapstoval_true_mem_eq M H8 H35.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  substs.\n  repeat (eapply eq_join_eq; eauto).\n\n  auto.\nQed.\n\nLemma A_isr_is_prop_precise :\n  forall e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= A_isr_is_prop ->\n    (e, e0, M2, i, l, o2, a) |= A_isr_is_prop ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold A_isr_is_prop; intros.\n  simpl in H, H0; simpljoin1; intros; auto.\nQed.\n\n\nLemma AOSTCBList_vptr :\n  forall s p1 p2 tcbl1 tcbcur tcbl2 rtbl ct tcbls,\n    s |= AOSTCBList p1 p2 tcbl1 (tcbcur :: tcbl2) rtbl ct tcbls ->\n    (exists x, p1 = Vptr x).\nProof.\n  unfold AOSTCBList; intros.\n  destruct_s s.\n  simpl_sat H; simpljoin1.\n  destruct tcbl1.\n  simpl in H8; simpljoin1; eauto.\n  unfold tcbdllseg in H8; unfold dllseg in H8; fold dllseg in H8.\n  simpl_sat H8; simpljoin1.\n  unfold node in H29; simpl_sat H29; simpljoin1.\n  eauto.\nQed.\n\nLemma tcbdllseg_compose:\n  forall s P h hp t1 tn1 t2 tn2 l1 l2,\n    s |= tcbdllseg h hp t1 tn1 l1 ** tcbdllseg tn1 t1 t2 tn2 l2 ** P->\n    s |= tcbdllseg h hp t2 tn2 (l1++l2) ** P.\nProof.\n  intros.\n\n  generalize s P h hp t1 tn1 t2 tn2 l2 H.\n  clear s P h hp t1 tn1 t2 tn2 l2 H.\n  induction l1.\n  intros.\n  unfold tcbdllseg in H.\n  unfold dllseg in H.\n  fold dllseg in H.\n  sep split in H.\n  subst.\n  simpl; auto.\n  intros.\n  simpl ( (a::l1) ++l2).\n\n  unfold tcbdllseg in *.\n  unfold dllseg in *.\n  fold dllseg in *.\n  sep normal.\n  \n  sep auto.\n  assert (s\n      |= dllseg x h t1 tn1 l1 OS_TCB_flag V_OSTCBPrev V_OSTCBNext **\n      dllseg tn1 t1 t2 tn2 l2 OS_TCB_flag V_OSTCBPrev V_OSTCBNext ** Aemp).\n  sep auto.\n  eapply IHl1 in H3.\n  sep auto.\n  auto.\nQed.\n\nLemma struct_type_vallist_match_os_tcb :\n  forall v, struct_type_vallist_match os_ucos_h.OS_TCB v ->\n            exists v1 v2 v3 v4 v5 v6 v7 v8 v9 v10, exists v11 v12, v = v1 :: v2 :: v3 :: v4 :: v5 :: v6 :: v7 :: v8 :: v9 :: v10 :: v11 :: v12 :: nil.\nProof.\n  intros.\n  unfold os_ucos_h.OS_TCB in H.\n  simpl in H.\n  unfolds in H.\n  destruct v; tryfalse.\n  destruct v0; simpljoin1; tryfalse.\n  destruct v1; simpljoin1; tryfalse.\n  destruct v2; simpljoin1; tryfalse.\n  destruct v3; simpljoin1; tryfalse.\n  destruct v4; simpljoin1; tryfalse.\n  destruct v5; simpljoin1; tryfalse.\n  destruct v6; simpljoin1; tryfalse.\n  destruct v7; simpljoin1; tryfalse.\n  destruct v8; simpljoin1; tryfalse.\n  destruct v9; simpljoin1; tryfalse.\n  destruct v10; simpljoin1; tryfalse.\n  destruct v11; simpljoin1; tryfalse.\n  do 12 eexists; eauto.\nQed.\n\nLemma dllseg_osabst_emp :\n  forall l head headprev tail tailnext t prev next e e0 M i lo o a0,\n    (e, e0, M, i, lo, o, a0) |= dllseg head headprev tail tailnext l t prev next -> o = empabst.\nProof.\n  inductions l; intros.\n  simpl in H; simpljoin1.\n  unfold dllseg in H; fold dllseg in H; simpl_sat H; simpljoin1.\n  apply node_osabst_emp in H18; substs.\n  eapply IHl in H19; substs.\n  apply OSAbstMod.extensionality; intros.\n  pose proof H17 a1.\n  rewrite OSAbstMod.emp_sem in *.\n  destruct(OSAbstMod.get o a1); tryfalse; auto.\nQed.\n\n(*current backup is inv_prop_bak3.v*)\n\nLemma disj_precise :\n  forall e e0 i l a M1 M2 o1 o2 P P' Q Q',\n    ((e, e0, M1, i, l, o1, a) |= P /\\\n     (e, e0, M2, i, l, o2, a) |= Q' -> False) ->\n    ((e, e0, M1, i, l, o1, a) |= Q /\\\n     (e, e0, M2, i, l, o2, a) |= P' -> False) ->\n    (\n      forall e e0 i l a M1 M2 o1 o2,\n        (e, e0, M1, i, l, o1, a) |= P ->\n        (e, e0, M2, i, l, o2, a) |= P' ->\n        (forall M : mem,\n            sub M1 M -> sub M2 M -> M1 = M2) /\\\n        (forall o : osabst,\n            sub o1 o -> sub o2 o -> o1 = o2)\n    ) ->\n    (\n      forall e e0 i l a M1 M2 o1 o2,\n        (e, e0, M1, i, l, o1, a) |= Q ->\n        (e, e0, M2, i, l, o2, a) |= Q' ->\n        (forall M : mem,\n            sub M1 M -> sub M2 M -> M1 = M2) /\\\n        (forall o : osabst,\n            sub o1 o -> sub o2 o -> o1 = o2)\n    ) ->\n    (e, e0, M1, i, l, o1, a) |= P \\\\// Q ->\n    (e, e0, M2, i, l, o2, a) |= P' \\\\// Q' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  intros.\n  destruct H3; destruct H4.\n\n  eapply H1; eauto.\n  false; eapply H; eauto.\n  false; eapply H0; eauto.\n  eapply H2; eauto.\nQed.\n\n\nLemma AOSTCBFreeList'_isptr :\n  forall s p l ct tcbls,\n    s |= AOSTCBFreeList' p l ct tcbls ->\n    isptr p.\nProof.\n  intros.\n  unfold AOSTCBFreeList' in H.\n  destruct_s s.\n  simpl_sat H; simpljoin1.\n  destruct H4.\n  unfold TCBFree_Not_Eq in H.\n  simpl_sat H; simpljoin1.\n  destruct l.\n  simpl in H11; simpljoin1.\n  unfolds; auto.\n  unfold assertion.sll in H11.\n  unfold sllseg in H11; fold sllseg in H11.\n  sep split in H11.\n  destruct H11.\n  simpl_sat H1; simpljoin1.\n  unfold node in H16; destruct H16.\n  sep split in H1; simpljoin1.\n  unfolds; eauto.\n\n  unfold TCBFree_Eq in H.\n  sep normal in H.\n  do 3 destruct H.\n  sep split in H; simpljoin1.\n  unfolds; eauto.\nQed.\n\nLemma mapstoval_vnull_vptr_mem_sub_false :\n  forall l a x m m' M,\n    mapstoval l (Tptr a) true Vnull m ->\n    mapstoval l (Tptr a) true (Vptr x) m' ->\n    sub m M -> sub m' M ->\n    False.\nProof.\n  intros.\n  unfold mapstoval in H, H0; simpljoin1.\n  simpl in H3, H4.\n  destruct x, l.\n  simpljoin1.\n  simpl in H3; simpljoin1.\n  assert(sub x M).\n  mem_join_sub_solver.\n  assert(sub x5 M).\n  mem_join_sub_solver.\n  unfold ptomval in H8, H0.\n  substs.\n  assert (get M (b0, o) = Some (true, MNull)).\n  clear - H14.\n\n\n  eapply mem_sub_sig_true_get; eauto.\n  assert (get M (b0, o) = Some (true, Pointer b i 3)).\n  clear - H16.\n  eapply mem_sub_sig_true_get; eauto.\n  rewrite H0 in H8; tryfalse.\nQed.\n\nLemma struct_type_vallist_match_os_tcb_flag :\n  forall v, struct_type_vallist_match OS_TCB_flag v ->\n            exists v1 v2 v3 v4 v5 v6 v7 v8 v9 v10, exists v11, v = v1 :: v2 :: v3 :: v4 :: v5 :: v6 :: v7 :: v8 :: v9 :: v10 :: v11 :: nil.\nProof.\n  intros.\n  unfold OS_TCB_flag in H.\n  simpl in H.\n  unfolds in H.\n  destruct v; tryfalse.\n  destruct v0; simpljoin1; tryfalse.\n  destruct v1; simpljoin1; tryfalse.\n  destruct v2; simpljoin1; tryfalse.\n  destruct v3; simpljoin1; tryfalse.\n  destruct v4; simpljoin1; tryfalse.\n  destruct v5; simpljoin1; tryfalse.\n  destruct v6; simpljoin1; tryfalse.\n  destruct v7; simpljoin1; tryfalse.\n  destruct v8; simpljoin1; tryfalse.\n  destruct v9; simpljoin1; tryfalse.\n  destruct v10; simpljoin1; tryfalse.\n  do 11 eexists; eauto.\nQed.\n\nLemma ostcb_flag_sll_precise :\n  forall lfree lfree' head e e0 M1 M2 i l o1 o2 a,\n    (e, e0, M1, i, l, o1, a) |= sll head lfree OS_TCB_flag V_OSTCBNext ->\n    (e, e0, M2, i, l, o2, a) |= sll head lfree' OS_TCB_flag V_OSTCBNext ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  inductions lfree; intros.\n  simpl in H; simpljoin1.\n  destruct lfree'.\n  simpl in H0; simpljoin1; auto.\n  unfold sll in H0; unfold sllseg in H0; fold sllseg in H0.\n  unfold node in H0; simpl in H0; simpljoin1; tryfalse.\n  destruct lfree'.\n  simpl in H0; simpljoin1.\n  unfold sll in H; unfold sllseg in H; fold sllseg in H.\n  unfold node in H; simpl in H; simpljoin1; tryfalse.\n  unfold sll in H, H0; unfold sllseg in H, H0; fold sllseg in H, H0.\n  simpl_sat H; simpljoin1; simpl_sat H0; simpljoin1.\n  \n  lets Hx: node_precise H14 H19.\n  \n  unfold sll in IHlfree.\n  simpljoin1; split; intros.\n  assert(x5 = x6).\n  assert(sub x12 M) by mem_join_sub_solver.\n  assert(sub x17 M) by mem_join_sub_solver.\n  lets Hx: node_vl_eq H14 H19 H5 H6.\n  simpl in Hx; unfold V_OSEventListPtr in H9, H10.\n  unfold node in H14, H19.\n  destruct H14, H19; sep split in H7; sep split in H8; simpljoin1.\n  assert(exists a1 a2 a3 a4 a5 a6 a7 a8 a9 a10, exists a11, a = a1::a2::a3::a4::a5::a6::a7::a8::a9::a10::a11::nil).\n  eapply struct_type_vallist_match_os_tcb_flag; eauto.\n  assert(exists v1 v2 v3 v4 v5 v6 v7 v8 v9 v10, exists v11, v = v1::v2::v3::v4::v5::v6::v7::v8::v9::v10::v11::nil).\n  eapply struct_type_vallist_match_os_tcb_flag; eauto.\n  simpljoin1; simpl in Hx; simpl in H9, H10; simpljoin1; inversion H9; inversion H10; substs; auto.\n  substs.\n  \n  lets Hx2: IHlfree H15 H20.\n  simpljoin1; mem_eq_solver M.\n  \n  eapply sllseg_osabst_emp in H15.\n  eapply sllseg_osabst_emp in H20.\n  substs.\n  eapply osabst_eq_join_eq; eauto.\n  osabst_eq_solver o.\nQed.\n\n\nFixpoint tcb_linked_list_same_next (vl1 vl2 : list vallist) :=\n  match vl1, vl2 with\n  | nil, nil => True\n  | h1::vl1', h2::vl2' =>\n    match (V_OSTCBNext h1), (V_OSTCBNext h2) with\n    | (Some a1), (Some a2) => a1 = a2 /\\ tcb_linked_list_same_next vl1' vl2'\n    | _, _ => False\n    end\n  | _, _ => False\n  end.\nLemma struct_atom_val_eq_V_OSTCBNext_eq :\n  forall vl1 vl2 x1 x2,\n    struct_atom_val_eq vl1 vl2 OS_TCB_flag ->\n    V_OSTCBNext vl1 = Some x1 ->\n    V_OSTCBNext vl2 = Some x2 ->\n    x1 = x2.\nProof.\n  intros.\n  destruct vl1;\n    unfolds in H0; simpl in H0; tryfalse.\n  destruct vl2;\n    unfolds in H1; simpl in H1; tryfalse.\n  inverts H0; inverts H1.\n  simpl in H; simpljoin1.\nQed.\n\nLemma tcb_linked_list_same_next_intro :\n  forall vl vl' p e e0 m i l o1 o2 a,\n    (e, e0, m, i, l, o1, a) |= assertion.sll p vl OS_TCB_flag V_OSTCBNext ->\n    (e, e0, m, i, l, o2, a) |= assertion.sll p vl' OS_TCB_flag V_OSTCBNext ->\n    tcb_linked_list_same_next vl vl'.\nProof.\n  inductions vl; intros.\n  destruct vl'.\n  simpl; auto.\n\n  unfold assertion.sll in H, H0.\n  unfold sllseg in *; fold sllseg in *.\n  sep split in H; sep split in H0; tryfalse.\n\n  destruct vl'.\n  unfold assertion.sll in H, H0.\n  unfold sllseg in *; fold sllseg in *.\n  sep split in H; sep split in H0; tryfalse.\n\n  unfold assertion.sll in H, H0.\n  unfold sllseg in *; fold sllseg in *.\n  sep normal in H; sep normal in H0.\n  destruct H, H0.\n  sep split in H; sep split in H0.\n  unfold tcb_linked_list_same_next; fold tcb_linked_list_same_next.\n  rewrite H1, H3.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  assert (sub x1 m).\n  eapply join_sub_l; eauto.\n  assert (sub x7 m).\n  eapply join_sub_l; eauto.\n  lets Hx: node_vl_eq H8 H13 H H0.\n  assert (x = x0).\n  clear - H1 H3 Hx.\n  symmetry.\n  eapply struct_atom_val_eq_V_OSTCBNext_eq; eauto.\n\n  substs.\n  split; auto.\n  lets Hx1: ostcb_flag_sll_precise H9 H14.\n  destruct Hx1.\n  assert (sub x2 m).\n  eapply join_sub_r; eauto.\n  assert (sub x8 m).\n  eapply join_sub_r; eauto.\n  lets Hx1: H6 H15 H16.\n  substs.\n  eapply IHvl; eauto.\nQed.\n    \nLemma sllfreeflag_precise :\n  forall vl vl' p e e0 i l a M1 M2 o1 o2,\n    tcb_linked_list_same_next vl vl' ->\n    (e, e0, M1, i, l, o1, a) |= sllfreeflag p vl ->\n    (e, e0, M2, i, l, o2, a) |= sllfreeflag p vl' ->\n    (forall M : mem,\n        sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n        sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  inductions vl; intros.\n  destruct vl'.\n  simpl in H0, H1; simpljoin1.\n  split; intros; auto.\n\n  unfold sllfreeflag in *.\n  unfold sllsegfreeflag in *; fold sllsegfreeflag in *.\n  sep split in H0.\n  do 2 destruct H1; sep split in H1.\n  substs; tryfalse.\n\n  destruct vl'.\n  unfold sllfreeflag in *.\n  unfold sllsegfreeflag in *; fold sllsegfreeflag in *.\n  sep split in H1.\n  do 2 destruct H0; sep split in H0.\n  substs; tryfalse.\n\n  unfold sllfreeflag in *.\n  unfold sllsegfreeflag in *; fold sllsegfreeflag in *.\n  do 2 destruct H0, H1.\n  sep split in H0; sep split in H1.\n  substs; inverts H4.\n  simpl_sat H0; simpl_sat H1; simpljoin1.\n\n  unfold tcb_linked_list_same_next in H; fold tcb_linked_list_same_next in H.\n  rewrite H3 in H.\n  rewrite H5 in H.\n  simpljoin1.\n  lets Hx: IHvl H0 H8 H13.\n  split; intros.\n  destruct Hx.\n  assert (sub x3 M).\n  mem_join_sub_solver.\n  assert (sub x9 M).\n  mem_join_sub_solver.\n  lets Hx1: H4 H14 H15.\n  substs.\n  assert (x = x8).\n  simpl in H12, H7; simpljoin1.\n  assert (sub x M).\n  mem_join_sub_solver.\n  assert (sub x8 M).\n  mem_join_sub_solver.\n  lets Hx: mapstoval_true_mem_eq H6 H11 H7 H12.\n  auto.\n  substs.\n  clear - H9 H2.\n  eapply join_unique; eauto.\n\n  simpl in H7, H12; simpljoin1.\n  eapply H10; eauto.\nQed.\n\nLemma sllfreeflag_osabst_emp :\n  forall vl p e e0 M i lo o a,\n    (e, e0, M, i, lo, o, a) |= sllfreeflag p vl ->\n    o = empabst.\nProof.\n  inductions vl; intros.\n  simpl in H; simpljoin1.\n\n  unfold sllfreeflag in *.\n  unfold sllsegfreeflag in H; fold sllsegfreeflag in H.\n  do 2 destruct H.\n  sep split in H.\n  simpl_sat H; simpljoin1.\n  simpl in H5; simpljoin1.\n  eapply IHvl; eauto.\nQed.\n\nLemma TCBFree_Not_Eq_precise :\n  forall e e0 i l a M1 M2 o1 o2 p ct vl vl',\n    (e, e0, M1, i, l, o1, a) |= TCBFree_Not_Eq p ct vl ->\n    (e, e0, M2, i, l, o2, a) |= TCBFree_Not_Eq p ct vl' ->\n    (forall M : mem,\n        sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n        sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  intros.\n  unfold TCBFree_Not_Eq in H, H0.\n  sep split in H.\n  sep split in H0.\n  \n  simpl_sat H; simpl_sat H0; simpljoin1.\n  split; intros.\n  assert(x5 = x).\n  lets Hx: ostcb_flag_sll_precise H11 H6.\n  destruct Hx.\n  apply H4 with (M:=M); mem_join_sub_solver.\n  substs.\n\n  lets Hx: tcb_linked_list_same_next_intro H11 H6.\n  lets Hx1: sllfreeflag_precise Hx H12 H7.\n  destruct Hx1.\n  assert (sub x6 M) by mem_join_sub_solver.\n  assert (sub x0 M) by mem_join_sub_solver.\n  lets Hx1: H4 H13 H14; substs.\n  eapply join_unique; eauto.\n  apply sll_osabst_emp in H11.\n  apply sll_osabst_emp in H6.\n  substs.\n  eapply sllfreeflag_osabst_emp in H12. \n  eapply sllfreeflag_osabst_emp in H7.\n  substs.\n  eapply eq_join_eq; eauto.\nQed.\n\nLemma Astruct_vl_eq :\n  forall vl vl' t l e e0 M1 M2 M i lo o1 o2 a,\n    struct_type_vallist_match t vl -> struct_type_vallist_match t vl' ->\n    (e, e0, M1, i, lo, o1, a) |= Astruct l t vl ->\n    (e, e0, M2, i, lo, o2, a) |= Astruct l t vl' ->\n    sub M1 M -> sub M2 M ->\n    struct_atom_val_eq vl vl' t.\nProof.\n  intros.\n  unfold struct_type_vallist_match in H, H0.\n  destruct t; tryfalse.\n  unfold Astruct in H1, H2.\n  eapply Astruct'_vl_eq; eauto.\nQed.\n\n\nLemma TCBFree_Eq_precise :\n  forall e e0 i l a M1 M2 o1 o2 p ct vl vl' tcbls tcbls',\n    (e, e0, M1, i, l, o1, a) |= TCBFree_Eq p ct vl tcbls ->\n    (e, e0, M2, i, l, o2, a) |= TCBFree_Eq p ct vl' tcbls' ->\n    (forall M : mem,\n        sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n        sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  intros.\n  unfold TCBFree_Eq in H, H0.\n  do 3 destruct H; sep split in H.\n  do 3 destruct H0; sep split in H0.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n\n  split; intros.\n  assert(x11 = x5).\n  lets Hx: Astruct_precise H28 H8; auto.\n  destruct Hx.\n  eapply H1 with (M := M); eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n  \n  assert (x1 = x4).\n  assert (sub x5 M).\n  mem_join_sub_solver.\n  lets Hx: Astruct_vl_eq H2 H4 H28 H8 H1.\n  lets Hx1: Hx H1; clear Hx.\n  eapply struct_atom_val_eq_V_OSTCBNext_eq; eauto.\n  substs.\n\n  assert (x23 = x36).\n  lets Hx: ostcb_flag_sll_precise H18 H38.\n  destruct Hx.\n  eapply H1 with (M := M).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n\n  assert (x24 = x37).\n  lets Hx: tcb_linked_list_same_next_intro H18 H38.\n  lets Hx1: sllfreeflag_precise Hx H19 H39.\n  destruct Hx1.\n  eapply H1 with (M := M); auto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n  \n  assert (x30 = x17).\n  simpl in H33, H13.\n  simpljoin1.\n  eapply mapstoval_false_mem_eq with (M := M); eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n\n  Ltac mem_eq_solver2 :=\n    match goal with\n    | H1: join ?m1 ?m2 ?M1, H2: join ?m3 ?m4 ?M2 |- ?M1 = ?M2 =>\n      eapply eq_join_eq; eauto; mem_eq_solver2\n    | _ => idtac\n    end.\n  \n  mem_eq_solver2.\n\n  apply Astruct_osabst_emp in H8.\n  apply Astruct_osabst_emp in H28.\n\n  apply sllfreeflag_osabst_emp in H39.\n  apply sllfreeflag_osabst_emp in H19.\n  \n  apply sll_osabst_emp in H38.\n  apply sll_osabst_emp in H18.\n\n  simpl in H33, H13.\n  simpljoin1.\nQed.\n\nLemma TCBFree_Not_Eq_osabst_emp :\n  forall p ct vl e e0 M i lo o a,\n    (e, e0, M, i, lo, o, a) |=TCBFree_Not_Eq p ct vl ->\n    o = empabst.\nProof.\n  intros.\n  unfold TCBFree_Not_Eq in H.\n  sep split in H.\n  simpl_sat H; simpljoin1.\n  apply sll_osabst_emp in H4.\n  apply sllfreeflag_osabst_emp in H5.\n  simpljoin1.\nQed.\n\nLemma TCBFree_Eq_osabst_emp :\n  forall p ct vl e e0 M i lo o a tcbls,\n    (e, e0, M, i, lo, o, a) |= TCBFree_Eq p ct vl tcbls ->\n    o = empabst.\nProof.\n  intros.\n  unfold TCBFree_Eq in H.\n  do 3 destruct H.\n  sep split in H.\n  simpl_sat H; simpljoin1.\n  apply sll_osabst_emp in H15.\n  apply sllfreeflag_osabst_emp in H16.\n  apply Astruct_osabst_emp in H5.\n  simpl in H10; simpljoin1.\nQed.\n\n\n(*should prove ct = ct' using HCurTCB*)\nLemma AOSTCBFreeList'_precise :\n  forall p p' vl vl' ct e e0 i l a M1 M2 o1 o2 tcbls tcbls',\n    (e, e0, M1, i, l, o1, a) |= AOSTCBFreeList' p vl ct tcbls ->\n    (e, e0, M2, i, l, o2, a) |= AOSTCBFreeList' p' vl' ct tcbls' ->\n    (forall M : mem,\n        sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n        sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  intros.\n  assert(isptr p).\n  eapply AOSTCBFreeList'_isptr; eauto.\n  assert(isptr p').\n  eapply AOSTCBFreeList'_isptr; eauto.\n  unfold AOSTCBFreeList' in *.\n  simpl_sat H.\n  simpl_sat H0.\n  simpljoin1.\n  split; intros.\n  assert (p = p' /\\ x5 = x).\n  simpl in H11, H6; simpljoin1.\n  rewrite H23 in H14; inverts H14.\n  destruct p, p';\n    unfold isptr in H1, H2; destruct H1, H2; simpljoin1; tryfalse.\n  split; auto.\n  eapply mapstoval_true_mem_eq; eauto.\n  instantiate (1:=M).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  false.\n  eapply mapstoval_vnull_vptr_mem_sub_false; eauto.\n  instantiate (1:=M).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  false.\n  eapply mapstoval_vnull_vptr_mem_sub_false; eauto.\n  instantiate (1:=M).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  assert (sub x M) by mem_join_sub_solver.\n  assert (sub x5 M) by mem_join_sub_solver.\n  lets Hx: mapstoval_true_vptr_eq H15 H24 H4 H5.\n  simpljoin1; auto.\n\n  simpljoin1.\n  lets Hx: disj_precise H7 H12.\n  intros.\n  clear H6 H7 H12 H11.\n  unfold TCBFree_Not_Eq, TCBFree_Eq in H4.\n  destruct H4; do 3 destruct H6.\n  sep split in H4; sep split in H6; simpljoin1.\n  tryfalse.\n\n  intros.\n  clear H6 H7 H12 H11.\n  unfold TCBFree_Not_Eq, TCBFree_Eq in H4.\n  destruct H4; do 3 destruct H4.\n  sep split in H4; sep split in H6; simpljoin1.\n  tryfalse.\n\n  intros.\n  eapply TCBFree_Not_Eq_precise; eauto.\n\n  intros.\n  eapply TCBFree_Eq_precise; eauto.\n\n  destruct Hx.\n  assert (x0 = x6).\n  eapply H4 with (M := M); eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n\n  mem_eq_solver2.\n\n  simpl in H11, H6; simpljoin1.\n\n  assert (o1 = empabst).\n  destruct H12.\n  \n  apply TCBFree_Not_Eq_osabst_emp in H4; auto.\n  apply TCBFree_Eq_osabst_emp in H4; auto.\n\n  assert (o2 = empabst).\n  destruct H7.\n  apply TCBFree_Not_Eq_osabst_emp in H5; auto.\n  apply TCBFree_Eq_osabst_emp in H5; auto.\n\n  simpljoin1.\nQed.\n\n\nLemma AOSTCBFreeList'_pfree_eq :\n  forall p p' vl vl' ct ct' e e0 i l a M M1 M2 o1 o2 tcbls tcbls',\n    (e, e0, M1, i, l, o1, a) |= AOSTCBFreeList' p vl ct tcbls ->\n    (e, e0, M2, i, l, o2, a) |= AOSTCBFreeList' p' vl' ct' tcbls' ->\n    sub M1 M -> sub M2 M ->    \n    p = p'.\nProof.\n  intros.\n  lets Hx: AOSTCBFreeList'_isptr H.\n  lets Hx1: AOSTCBFreeList'_isptr H0.\n    \n  unfold AOSTCBFreeList' in *.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  simpl in H11, H6; simpljoin1.\n  rewrite H21 in H11; inverts H11.\n  destruct p, p'; auto;\n    unfold isptr in *;\n    destruct Hx; destruct Hx1; simpljoin1; tryfalse.\n\n  false; eapply mapstoval_vnull_vptr_mem_sub_false with (M := M); eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  false; eapply mapstoval_vnull_vptr_mem_sub_false with (M := M); eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  eapply mapstoval_true_rule_type_val_match_eq with (M := M) (t := (Tptr os_ucos_h.OS_TCB) ).\n  simpl; auto.\n  simpl; auto.\n  eauto.\n  eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\nQed.\n\n\nLemma dllseg_os_tcb_flag_precise :\n  forall l l' head headprev headprev' tail tail' e e0 i lo a M1 M2 o1 o2,\n    (e, e0, M1, i, lo, o1, a) |= dllseg head headprev tail Vnull l OS_TCB_flag V_OSTCBPrev V_OSTCBNext ->\n    (e, e0, M2, i, lo, o2, a) |= dllseg head headprev' tail' Vnull l' OS_TCB_flag V_OSTCBPrev V_OSTCBNext ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  inductions l; intros.\n  destruct l'.\n  simpl in H, H0; simpljoin1; intros; auto.\n\n  simpl in H; simpljoin1.\n  unfold dllseg in H0; fold dllseg in H0.\n  simpl_sat H0; simpljoin1; tryfalse.\n  \n  destruct l'.\n  simpl in H0; simpljoin1.\n  unfold dllseg in H; fold dllseg in H; simpl_sat H; simpljoin1.\n  simpl in H18; simpljoin1; tryfalse.\n  unfold dllseg in H0, H; fold dllseg in H0, H; simpl_sat H0; simpl_sat H; simpljoin1.\n\n  simpljoin1; split;  intros.\n  assert(struct_atom_val_eq a v OS_TCB_flag).\n  eapply node_vl_eq with (M:=M); eauto; mem_join_sub_solver.\n  simpl in H1.\n  assert(exists v1 v2 v3 v4 v5 v6 v7 v8 v9 v10, exists v11, a = v1::v2::v3::v4::v5::v6::v7::v8::v9::v10::v11::nil).\n\n  unfold node in H45; simpl_sat H45; simpljoin1.\n  eapply struct_type_vallist_match_os_tcb_flag; eauto.\n  assert(exists v1 v2 v3 v4 v5 v6 v7 v8 v9 v10, exists v11, v = v1::v2::v3::v4::v5::v6::v7::v8::v9::v10::v11::nil).\n  unfold node in H19; simpl_sat H19; simpljoin1.\n  eapply struct_type_vallist_match_os_tcb_flag; eauto.\n  simpljoin1.\n\n  simpl in H1; simpljoin1.\n  unfold V_OSTCBNext in H9, H35; unfold V_OSTCBPrev in H40, H14; unfold nth_val in *.\n  inverts H9; inverts H14; inverts H35; inverts H40.\n\n  lets Hx1: IHl H46 H20.\n  lets Hx2: node_precise H45 H19; simpljoin1.\n  mem_eq_solver M.\n\n  apply node_osabst_emp in H45;\n    apply node_osabst_emp in H19;\n    apply dllseg_osabst_emp in H46;\n    apply dllseg_osabst_emp in H20;\n    substs.\n\n  eapply OSAbstMod.extensionality; intros.\n  pose proof H18 a1; pose proof H44 a1.\n  rewrite OSAbstMod.emp_sem in *.\n  destruct(OSAbstMod.get o1 a1 );\n    destruct(OSAbstMod.get o2 a1 );\n    tryfalse; auto.\nQed.\n\nLemma tcbdllseg_precise :\n  forall l l' head headprev headprev' tail tail' e e0 i lo a M1 M2 o1 o2,\n    (e, e0, M1, i, lo, o1, a) |= tcbdllseg head headprev tail Vnull l ->\n    (e, e0, M2, i, lo, o2, a) |= tcbdllseg head headprev' tail' Vnull l' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold tcbdllseg; intros.\n  eapply dllseg_os_tcb_flag_precise; eauto.\nQed.\n\nLemma tcbdllseg_osabst_emp :\n  forall l head headprev tail tailnext e e0 M i lo o a0,\n    (e, e0, M, i, lo, o, a0) |= tcbdllseg head headprev tail tailnext l -> o = empabst.\nProof.\n  unfold tcbdllseg; intros.\n  apply dllseg_osabst_emp in H; auto.\nQed.\n\nLemma tcb_linked_list_same_next_intro_dllseg :\n  forall vl vl' head headprev headprev' tail tail' e e0 m i l o1 o2 a,\n    (e, e0, m, i, l, o1, a) |= dllseg head headprev tail Vnull vl OS_TCB_flag V_OSTCBPrev V_OSTCBNext ->\n    (e, e0, m, i, l, o2, a) |= dllseg head headprev' tail' Vnull vl' OS_TCB_flag V_OSTCBPrev V_OSTCBNext ->\n    tcb_linked_list_same_next vl vl'.\nProof.\n  inductions vl; intros.\n  destruct vl'.\n  simpl; auto.\n\n  unfold dllseg in *; fold dllseg in *.\n  sep split in H; sep split in H0; tryfalse.\n  \n  destruct vl'.\n  unfold dllseg in *; fold dllseg in *.\n  sep split in H; sep split in H0; tryfalse.\n  \n  unfold dllseg in *; fold dllseg in *.\n  sep normal in H; sep normal in H0.\n  destruct H, H0.\n  sep split in H; sep split in H0.\n  unfold tcb_linked_list_same_next; fold tcb_linked_list_same_next.\n  rewrite H1, H4.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  assert (sub x1 m).\n  eapply join_sub_l; eauto.\n  assert (sub x7 m).\n  eapply join_sub_l; eauto.\n  lets Hx: node_vl_eq H15 H10 H0 H.\n  assert (x = x0).\n  clear - H1 H4 Hx.\n  eapply struct_atom_val_eq_V_OSTCBNext_eq; eauto.\n\n  substs.\n  split; auto.\n\n  lets Hx1: dllseg_os_tcb_flag_precise H11 H16.\n  destruct Hx1.\n  assert (sub x2 m).\n  eapply join_sub_r; eauto.\n  assert (sub x8 m).\n  eapply join_sub_r; eauto.\n  lets Hx1: H8 H17 H18.\n  substs. \n  eapply IHvl; eauto.\nQed.\n\nLemma tcb_linked_list_same_next_intro' :\n  forall vl vl' head tail tail' e e0 m i l o1 o2 a,\n    (e, e0, m, i, l, o1, a) |= tcbdllseg head Vnull tail Vnull vl ->\n    (e, e0, m, i, l, o2, a) |= tcbdllseg head Vnull tail' Vnull vl' ->\n    tcb_linked_list_same_next vl vl'.\nProof.\n  intros.\n  eapply tcb_linked_list_same_next_intro_dllseg; eauto.\nQed.\n\nLemma tcbdllseg_isvptr1:\n  forall l s p1 tail1 ct p z,\n    s |= tcbdllseg p1 z tail1 (Vptr ct) l ** p -> exists x, p1 = Vptr x.\nProof.\n  inductions l.\n  intros.\n  unfold tcbdllseg in H; simpl dllseg in H.\n  sep split in H.\n  eauto.\n  intros.\n  unfold tcbdllseg in H; simpl dllseg in H.\n  unfold node in H.\n  sep normal in H.\n  sep destruct  H.\n  sep split in H.\n  simpljoin1; eauto.\nQed.\n\nLemma tcblist_isptr :\n  forall s head tail vl rtbl tcbls P,\n    s |= tcblist head Vnull tail Vnull vl rtbl tcbls ** P ->\n    isptr head.\nProof.\n  intros.\n  destruct_s s.\n  destruct vl.\n  simpl in H; simpljoin1.\n  unfolds; eauto.\n\n  unfold tcblist in H.\n  sep split in H.\n  unfold tcbdllseg in H.\n  sep remember (1::nil)%nat in H.\n  eapply dllseg_head_isptr in H; auto.\nQed.\n\nLemma AOSTCBList'_isptr :\n  forall s p1 p2 l1 l2 rtbl hcurt tcbls pf,\n    s |= AOSTCBList' p1 p2 l1 l2 rtbl hcurt tcbls pf ->\n    isptr p1.\nProof.\n  intros.\n  unfold AOSTCBList' in H.\n  destruct H.\n  do 4 destruct H.\n  sep split in H; simpljoin1.\n  sep remember (2::nil)%nat in H.\n  eapply tcbdllseg_isvptr1 in H.\n  destruct H; substs; unfolds; eauto.\n\n  destruct H.\n  sep split in H; simpljoin1.\n  sep remember (3::nil)%nat in H.\n  eapply tcblist_isptr; eauto.\nQed.\n\nLemma dllsegflag_osabst_emp :\n  forall vl e e0 M i o a0 lo p headprev,\n    (e, e0, M, i, lo, o, a0) |= dllsegflag p headprev vl V_OSTCBNext ->\n    o = empabst.\nProof.\n  inductions vl; intros.\n  simpl in H; simpljoin1.\n\n  unfold dllsegflag in H; fold dllsegflag in H.\n  do 2 destruct H; sep split in H.\n  simpl_sat H; simpljoin1.\n  lets Hx: IHvl H6; substs.\n  simpl in H5; simpljoin1.\nQed.\n\nLemma tcbdllflag_osabst_emp :\n  forall vl e e0 M i o a0 lo p,\n    (e, e0, M, i, lo, o, a0) |= tcbdllflag p vl ->\n    o = empabst.\nProof.\n  intros.\n  unfold tcbdllflag in H.\n  eapply dllsegflag_osabst_emp; eauto.\nQed.\n\nLemma dllsegflag_precise :\n  forall vl vl' p headprev headprev' e e0 i l a M1 M2 o1 o2,\n    tcb_linked_list_same_next vl vl' ->\n    (e, e0, M1, i, l, o1, a) |= dllsegflag p headprev vl V_OSTCBNext ->\n    (e, e0, M2, i, l, o2, a) |= dllsegflag p headprev' vl' V_OSTCBNext ->\n    (forall M : mem,\n        sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n        sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  inductions vl; intros.\n  destruct vl'.\n  simpl in H0, H1; simpljoin1.\n  split; intros; auto.\n  \n  unfold sllfreeflag in *.\n  unfold sllsegfreeflag in *; fold sllsegfreeflag in *.\n  sep split in H0.\n  do 2 destruct H1; sep split in H1.\n  substs; tryfalse.\n  \n  destruct vl'.\n  unfold dllsegflag in *; fold dllsegflag in *.\n  sep split in H1.\n  do 2 destruct H0; sep split in H0.\n  substs; tryfalse.\n  \n  unfold sllfreeflag in *.\n  unfold sllsegfreeflag in *; fold sllsegfreeflag in *.\n  do 2 destruct H0, H1.\n  sep split in H0; sep split in H1.\n  substs; inverts H4.\n  simpl_sat H0; simpl_sat H1; simpljoin1.\n\n  unfold tcb_linked_list_same_next in H; fold tcb_linked_list_same_next in H.\n  rewrite H3 in H.\n  rewrite H5 in H.\n  simpljoin1.\n  lets Hx: IHvl H0 H8 H13.\n  split; intros.\n  destruct Hx.\n  assert (sub x3 M).\n  mem_join_sub_solver.\n  assert (sub x9 M).\n  mem_join_sub_solver.\n  lets Hx1: H4 H14 H15.\n  substs.\n  assert (x = x8).\n  simpl in H12, H7; simpljoin1.\n  assert (sub x M).\n  mem_join_sub_solver.\n  assert (sub x8 M).\n  mem_join_sub_solver.\n  lets Hx: mapstoval_false_mem_eq H6 H11 H7 H12.\n  auto.\n  substs.\n  clear - H9 H2.\n  eapply join_unique; eauto.\n\n  simpl in H7, H12; simpljoin1.\n  eapply H10; eauto.\nQed.\n\nLemma tcbdllflag_precise :\n  forall vl vl' p e e0 i l a M1 M2 o1 o2,\n    tcb_linked_list_same_next vl vl' ->\n    (e, e0, M1, i, l, o1, a) |= tcbdllflag p vl ->\n    (e, e0, M2, i, l, o2, a) |= tcbdllflag p vl' ->\n    (forall M : mem,\n        sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n        sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  intros.\n  unfold tcbdllflag in *.\n  eapply dllsegflag_precise; eauto.\nQed.\n\n(*pfree eq by the above lemma on AOSTCBFreeList*)\n(*ct eq can be obtained from HCurTid*)\nLemma AOSTCBList'_precise :\n  forall p1 p1' p2 p2' tcbl1 tcbl1' tcbcur tcbcur' tcbl2 tcbl2' rtbl rtbl' ct tcbls tcbls' pfree  e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= AOSTCBList' p1 p2 tcbl1 (tcbcur :: tcbl2) rtbl ct tcbls pfree ->\n    (e, e0, M2, i, l, o2, a) |= AOSTCBList' p1' p2' tcbl1' (tcbcur' :: tcbl2') rtbl' ct tcbls' pfree ->\n    (forall M : mem,\n        sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n        sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  intros.\n  eapply disj_precise; eauto.\n\n  intros.\n  destruct H1.\n  do 4 destruct H1; sep split in H1.\n  destruct H2; sep split in H2.\n  simpljoin1; tryfalse.\n\n  intros.\n  destruct H1.\n  destruct H1; sep split in H1.\n  do 4 destruct H2; sep split in H2.\n  simpljoin1; tryfalse.\n\n-\n  intros.\n  do 4 destruct H1; do 4 destruct H2.\n  sep split in H1; sep split in H2; simpljoin1.\n  \n  apply AOSTCBList'_isptr in H.\n  apply AOSTCBList'_isptr in H0.\n  clear H4 H5 H9 H10 H11 H12 H6 H7; clears.\n  sep lifts (2::4::nil)%nat in H2.\n  sep lifts (2::4::nil)%nat in H1.\n  apply tcbdllseg_compose in H2.\n  apply tcbdllseg_compose in H1.\n  \n  destruct p1, p1'; unfold isptr in H, H0; destruct H; destruct H0; simpljoin1; tryfalse.\n  clear H3 H8 H0 H; clears.\n  split; intros.\n  simpl_sat H2.\n  simpl_sat H1.\n  simpljoin1.\n  simpl in H26; simpljoin1.\n  simpl in H11; simpljoin1.\n  rewrite H9 in H11; inverts H11.\n  \n  assert (Vptr a = Vptr a1 /\\ x13 = x25).\n  eapply mapstoval_true_rule_type_val_match_eq with (M := M) (t := Tptr os_ucos_h.OS_TCB).\n  simpl; auto.\n  simpl; auto.\n  eauto.\n  eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  \n  simpljoin1.\n  inverts H1.\n  simpl in H31; simpl in H16; simpljoin1.\n  rewrite H31 in H11; inverts H11.\n  assert (x19 = x31).\n  eapply mapstoval_false_mem_eq with (M := M); eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  assert (x7 = x).\n  lets Hx: tcbdllseg_precise H21 H6.\n  destruct Hx.\n  eapply H2 with (M := M).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  substs.\n  lets Hx: tcb_linked_list_same_next_intro' H21 H6.\n  assert (x32 = x20).\n  lets Hx1: tcbdllflag_precise Hx H32 H17.\n  destruct Hx1.\n  eapply H1 with (M := M).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n  mem_eq_solver2.\n\n  simpl_sat H2; simpl_sat H1; simpljoin1.\n  unfold tcbdllseg in *.\n  apply dllseg_osabst_emp in H21;\n    apply dllseg_osabst_emp in H6.\n  simpl in H26, H31, H11, H16; simpljoin1.\n  eapply tcbdllflag_osabst_emp in H32;\n    eapply tcbdllflag_osabst_emp in H17.\n  simpljoin1.\n\n- \n  intros.\n  apply AOSTCBList'_isptr in H.\n  apply AOSTCBList'_isptr in H0.\n  destruct H1, H2.\n  unfold TCB_Not_In in *.\n  unfold tcblist in *.\n  sep split in H1; sep split in H2.\n  simpljoin1.\n  destruct p1, p1'; unfold isptr in H, H0; destruct H; destruct H0; simpljoin1; tryfalse.\n  inverts H6.\n  clear H H0 H3 H7 H8 H11 H4 H13 H5 H9; clears.\n  simpl_sat H2; simpl_sat H1; simpljoin1.\n  split; intros.\n  \n  assert (Vptr a2 = Vptr a1 /\\ x8 = x2).\n  simpl in H19, H4; simpljoin1.\n  rewrite H33 in H12; inverts H12.\n  eapply mapstoval_true_rule_type_val_match_eq with (M := M) (t := Tptr os_ucos_h.OS_TCB).\n  simpl; auto.\n  simpl; auto.\n  eauto.\n  eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  simpljoin1.\n  inverts H2.\n  \n  assert (x26 = x14).\n  simpl in H24, H9; simpljoin1.\n  rewrite H33 in H12.\n  inverts H12.\n  eapply mapstoval_false_mem_eq with (M := M).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  eauto.\n  eauto.\n  substs.\n\n  assert (x20 = x32).\n  lets Hx: tcbdllseg_precise H14 H29.\n  destruct Hx.\n  eapply H2 with (M := M).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n\n  assert (x21 = x33).\n  lets Hx: tcb_linked_list_same_next_intro' H14 H29.\n  lets Hx1: tcbdllflag_precise Hx H15 H30.\n  destruct Hx1.\n  eapply H2 with (M := M).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n  mem_eq_solver2.\n\n  simpl in H19, H24, H4, H9; simpljoin1.\n  apply tcbdllseg_osabst_emp in H29;\n    apply tcbdllseg_osabst_emp in H14.\n  apply tcbdllflag_osabst_emp in H30;\n    apply tcbdllflag_osabst_emp in H15.\n  simpljoin1.\nQed.\n\n\n(*\nLemma dllseg_ostcb_precise :\n  forall l l' head headprev headprev' tail tail' e e0 i lo a M1 M2 o1 o2,\n    (e, e0, M1, i, lo, o1, a) |= dllseg head headprev tail Vnull l os_ucos_h.OS_TCB V_OSTCBPrev V_OSTCBNext ->\n    (e, e0, M2, i, lo, o2, a) |= dllseg head headprev' tail' Vnull l' os_ucos_h.OS_TCB V_OSTCBPrev V_OSTCBNext ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  inductions l; intros.\n  destruct l'.\n  simpl in H, H0; simpljoin1; intros; auto.\n\n  simpl in H; simpljoin1.\n  unfold dllseg in H0; fold dllseg in H0.\n  simpl_sat H0; simpljoin1; tryfalse.\n  \n  destruct l'.\n  simpl in H0; simpljoin1.\n  unfold dllseg in H; fold dllseg in H; simpl_sat H; simpljoin1.\n  simpl in H18; simpljoin1; tryfalse.\n  unfold dllseg in H0, H; fold dllseg in H0, H; simpl_sat H0; simpl_sat H; simpljoin1.\n\n  simpljoin1; intros.\n  assert(struct_atom_val_eq a v os_ucos_h.OS_TCB).\n  eapply node_vl_eq with (M:=M); eauto; mem_join_sub_solver.\n  simpl in H1.\n  assert(exists v1 v2 v3 v4 v5 v6 v7 v8 v9 v10, exists v11, a = v1::v2::v3::v4::v5::v6::v7::v8::v9::v10::v11::nil).\n\n  unfold node in H45; simpl_sat H45; simpljoin1.\n  eapply struct_type_vallist_match_os_tcb; eauto.\n  assert(exists v1 v2 v3 v4 v5 v6 v7 v8 v9 v10, exists v11, v = v1::v2::v3::v4::v5::v6::v7::v8::v9::v10::v11::nil).\n  unfold node in H19; simpl_sat H19; simpljoin1.\n  eapply struct_type_vallist_match_os_tcb; eauto.\n  simpljoin1.\n\n  simpl in H1; simpljoin1.\n  unfold OSTCBInvDef.V_OSTCBNext in H9, H35; unfold OSTCBInvDef.V_OSTCBPrev in H40, H14; unfold nth_val in *.\n  inverts H9; inverts H14; inverts H35; inverts H40.\n\n  lets Hx1: IHl H46 H20.\n  lets Hx2: node_precise H45 H19; simpljoin1.\n  mem_eq_solver M.\n\n  apply node_osabst_emp in H45;\n    apply node_osabst_emp in H19;\n    apply dllseg_osabst_emp in H46;\n    apply dllseg_osabst_emp in H20;\n    substs.\n\n  eapply OSAbstMod.extensionality; intros.\n  pose proof H18 a1; pose proof H44 a1.\n  rewrite OSAbstMod.emp_sem in *.\n  destruct(OSAbstMod.get o1 a1 );\n    destruct(OSAbstMod.get o2 a1 );\n    tryfalse; auto.\nQed.\n\nLemma tcbdllseg_precise :\n  forall l l' head headprev headprev' tail tail' e e0 i lo a M1 M2 o1 o2,\n    (e, e0, M1, i, lo, o1, a) |= OSTCBInvDef.tcbdllseg head headprev tail Vnull l ->\n    (e, e0, M2, i, lo, o2, a) |= OSTCBInvDef.tcbdllseg head headprev' tail' Vnull l' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold OSTCBInvDef.tcbdllseg; intros.\n  eapply dllseg_ostcb_precise; eauto.\nQed.\n\nLemma tcbdllseg_osabst_emp :\n  forall l head headprev tail tailnext e e0 M i lo o a0,\n    (e, e0, M, i, lo, o, a0) |= OSTCBInvDef.tcbdllseg head headprev tail tailnext l -> o = empabst.\nProof.\n  unfold OSTCBInvDef.tcbdllseg; intros.\n  apply dllseg_osabst_emp in H; auto.\nQed.\n\n\nLemma AOSTCBList_precise :\n  forall p1 p1' p2 p2' tcbl1 tcbl1' tcbcur tcbcur' tcbl2 tcbl2' rtbl rtbl' ct ct' tcbls tcbls' e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= OSTCBInvDef.AOSTCBList p1 p2 tcbl1 (tcbcur :: tcbl2) rtbl ct tcbls ->\n    (e, e0, M2, i, l, o2, a) |= OSTCBInvDef.AOSTCBList p1' p2' tcbl1' (tcbcur' :: tcbl2') rtbl' ct' tcbls' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  intros.\n  lets Hx1: AOSTCBList_vptr H.\n  lets Hx2:  AOSTCBList_vptr H0.\n  simpljoin1.\n\n  unfold OSTCBInvDef.AOSTCBList in *.\n  do 4 destruct H0; sep split in H0.\n  do 4 destruct H; sep split in H.\n\n  simpljoin1; intros.\n  assert(x = x0).\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  simpl in H29, H14; simpljoin1.\n  rewrite H41 in H17; inverts H17.\n  eapply mapstoval_vptr_eq with (M:=M); eauto; mem_join_sub_solver.\n  substs.\n  \n  sep lifts (2::4::nil)%nat in H0.\n  sep lifts (2::4::nil)%nat in H.\n  apply tcbdllseg_compose in H0.\n  apply tcbdllseg_compose in H.\n\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  simpl in H19, H20, H29, H30; simpljoin1.\n  rewrite H53 in H35; rewrite H44 in H22; inverts H35; inverts H22.\n  assert(x20 = x26).\n  eapply mapstoval_mem_eq with (M:=M); eauto; mem_join_sub_solver. \n  assert(x21 = x27).\n  eapply mapstoval_mem_eq with (M:=M); eauto; mem_join_sub_solver.\n  substs.\n\n  lets Hx: tcbdllseg_precise H24 H14; simpljoin1.\n  eapply MemMod_eq_join_eq; eauto.\n  eapply H with (M:=M); mem_join_sub_solver.\n  eapply MemMod_eq_join_eq; eauto.\n\n  sep lifts (2::4::nil)%nat in H0.\n  sep lifts (2::4::nil)%nat in H.\n  apply tcbdllseg_compose in H0.\n  apply tcbdllseg_compose in H.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  \n  apply tcbdllseg_osabst_emp in H24.\n  apply tcbdllseg_osabst_emp in H14.\n  simpl in H29, H30, H19, H20; simpljoin1.\nQed.\n\n\nLemma ostcb_sll_precise :\n  forall lfree lfree' head e e0 M1 M2 i l o1 o2 a,\n    (e, e0, M1, i, l, o1, a) |= sll head lfree os_ucos_h.OS_TCB OSTCBInvDef.V_OSTCBNext ->\n    (e, e0, M2, i, l, o2, a) |= sll head lfree' os_ucos_h.OS_TCB OSTCBInvDef.V_OSTCBNext ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  inductions lfree; intros.\n  simpl in H; simpljoin1.\n  destruct lfree'.\n  simpl in H0; simpljoin1; auto.\n  unfold sll in H0; unfold sllseg in H0; fold sllseg in H0.\n  unfold node in H0; simpl in H0; simpljoin1; tryfalse.\n  destruct lfree'.\n  simpl in H0; simpljoin1.\n  unfold sll in H; unfold sllseg in H; fold sllseg in H.\n  unfold node in H; simpl in H; simpljoin1; tryfalse.\n  unfold sll in H, H0; unfold sllseg in H, H0; fold sllseg in H, H0.\n  simpl_sat H; simpljoin1; simpl_sat H0; simpljoin1.\n  \n  lets Hx: node_precise H14 H19.\n  \n  unfold sll in IHlfree.\n  simpljoin1; intros.\n  assert(x5 = x6).\n  assert(sub x12 M) by mem_join_sub_solver.\n  assert(sub x17 M) by mem_join_sub_solver.\n  lets Hx: node_vl_eq H14 H19 H5 H6.\n  simpl in Hx; unfold V_OSEventListPtr in H9, H10.\n  unfold node in H14, H19.\n  destruct H14, H19; sep split in H7; sep split in H8; simpljoin1.\n  assert(exists a1 a2 a3 a4 a5 a6 a7 a8 a9 a10, exists a11, a = a1::a2::a3::a4::a5::a6::a7::a8::a9::a10::a11::nil).\n  eapply struct_type_vallist_match_os_tcb; eauto.\n  assert(exists v1 v2 v3 v4 v5 v6 v7 v8 v9 v10, exists v11, v = v1::v2::v3::v4::v5::v6::v7::v8::v9::v10::v11::nil).\n  eapply struct_type_vallist_match_os_tcb; eauto.\n  simpljoin1; simpl in Hx; simpl in H9, H10; simpljoin1; inversion H9; inversion H10; substs; auto.\n  substs.\n  \n  lets Hx2: IHlfree H15 H20.\n  simpljoin1; mem_eq_solver M.\n  \n  eapply sllseg_osabst_emp in H15.\n  eapply sllseg_osabst_emp in H20.\n  substs.\n  eapply osabst_eq_join_eq; eauto.\n  osabst_eq_solver o.\nQed.\n\n\nLemma AOSTCBFreeList_precise :\n  forall ptfree ptfree' lfree lfree' e e0 i l a M1 M2 o1 o2,\n    (e, e0, M1, i, l, o1, a) |= OSTCBInvDef.AOSTCBFreeList ptfree lfree ->\n    (e, e0, M2, i, l, o2, a) |= OSTCBInvDef.AOSTCBFreeList ptfree' lfree' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o : osabst,\n       sub o1 o -> sub o2 o -> o1 = o2).\nProof.\n  unfold OSTCBInvDef.AOSTCBFreeList; intros.\n  simpl_sat H; simpl_sat H0; simpljoin1.\n  simpl in H9, H4; simpljoin1.\n  rewrite H19 in H9; inverts H9.\n  \n  simpljoin1; intros.\n  assert(ptfree = ptfree').\n  assert(isptr ptfree).\n  eapply sll_isptr; eauto.\n  assert(isptr ptfree').\n  eapply sll_isptr; eauto.\n  destruct ptfree, ptfree'; auto;\n  try(unfolds in H2; destruct H2; simpljoin1; tryfalse);\n  try(unfolds in H3; destruct H3; simpljoin1; tryfalse).\n  unfolds in H20; simpljoin1; simpl in H4; simpljoin1.\n  unfolds in H11; simpljoin1; simpl in H13; destruct a0; simpl in H13; simpljoin1.\n  clear - H4 H13 H3 H11 H1 H6 H H0.\n  unfold ptomval in H4; unfold ptomval in H13; substs.\n  assert(sub (memory.MemMod.sig (x21, Int.unsigned Int.zero) (Pointer b i0 3)) M).\n  mem_join_sub_solver.\n  assert(sub (memory.MemMod.sig (x21, Int.unsigned Int.zero) MNull) M).\n  mem_join_sub_solver.\n  unfold sub in H2, H4.\n  unfold memory.MemMod.lookup in H2, H4.\n  pose proof H2 (x21, Int.unsigned Int.zero) (Pointer b i0 3).\n  pose proof H4 (x21, Int.unsigned Int.zero) MNull.\n  rewrite memory.MemMod.get_sig_some in H5.\n  rewrite memory.MemMod.get_sig_some in H7.\n  assert(Some (Pointer b i0 3) = Some (Pointer b i0 3)) by auto.\n  assert(Some MNull = Some MNull) by auto.\n  apply H5 in H8; apply H7 in H9.\n  rewrite H8 in H9; inverts H9.\n  \n  unfolds in H11; simpljoin1; simpl in H4; destruct a0; simpl in H4;  simpljoin1.\n  unfolds in H20; simpljoin1; simpl in H14; simpljoin1.\n  clear - H4 H14 H3 H12 H H0 H1 H6.\n  unfold ptomval in H4; unfold ptomval in H14; substs.\n  assert(sub (memory.MemMod.sig (x21, Int.unsigned Int.zero) (Pointer b i0 3)) M).\n  mem_join_sub_solver.\n  assert(sub (memory.MemMod.sig (x21, Int.unsigned Int.zero) MNull) M).\n  mem_join_sub_solver.\n  unfold sub in H2, H4.\n  unfold memory.MemMod.lookup in H2, H4.\n  pose proof H2 (x21, Int.unsigned Int.zero) (Pointer b i0 3).\n  pose proof H4 (x21, Int.unsigned Int.zero) MNull.\n  rewrite memory.MemMod.get_sig_some in H5.\n  rewrite memory.MemMod.get_sig_some in H7.\n  assert(Some (Pointer b i0 3) = Some (Pointer b i0 3)) by auto.\n  assert(Some MNull = Some MNull) by auto.\n  apply H5 in H8; apply H7 in H9.\n  rewrite H8 in H9; inverts H9.\n\n  inverts H2; inverts H3.\n  assert(sub x M).\n  apply memory.MemMod.join_sub_l in H1.\n  eapply sub_trans; eauto.\n  assert(sub x5 M).\n  apply memory.MemMod.join_sub_l in H6.\n  eapply sub_trans; eauto.\n  lets Hx: mapstoval_vptr_eq H20 H11 H3 H2; simpljoin1.\n  substs.\n  \n  assert(x = x5).\n  eapply mapstoval_mem_eq with (M:=M); eauto; mem_join_sub_solver.\n  substs.\n  eapply MemMod_eq_join_eq; eauto.\n  \n  lets Hx: ostcb_sll_precise H10 H5; simpljoin1.\n  mem_eq_solver M.\n  \n  apply sll_osabst_emp in H10; apply sll_osabst_emp in H5.\n  substs; auto.\nQed.\n*)\n\nLemma AOSTCBList'_ct_eq :\n  forall p1 p1' p2 p2' l1 l1' l2 l2' rtbl rtbl' ct ct'\n    tcbls tcbls' pfree pfree'\n    e e0 i lo a M1 M2 M o1 o2,\n    (e, e0, M1, i, lo, o1, a) |= AOSTCBList' p1 p2 l1 l2 rtbl ct tcbls pfree ->\n    (e, e0, M2, i, lo, o2, a) |= AOSTCBList' p1' p2' l1' l2' rtbl' ct' tcbls' pfree' ->\n    sub M1 M -> sub M2 M ->\n    ct = ct'.\nProof.\n  intros.\n  unfold AOSTCBList' in *.\n  destruct H, H0.\n  \n  do 4 destruct H.\n  do 4 destruct H0.\n  sep split in H; sep split in H0; simpljoin1.\n  sep remember (3::nil)%nat in H0.\n  sep remember (3::nil)%nat in H.\n  simpl in H0; simpl in H; simpljoin1.\n  rewrite H37 in H23; inverts H23.\n  eapply mapstoval_false_vptr_eq with (M := M); eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  do 4 destruct H.\n  destruct H0.\n  sep split in H; sep split in H0; simpljoin1.\n  sep remember (2::nil)%nat in H0.\n  sep remember (3::nil)%nat in H.\n  simpl in H0; simpl in H; simpljoin1.\n  rewrite H33 in H19; inverts H19.\n  eapply mapstoval_false_vptr_eq with (M := M); eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  do 4 destruct H0.\n  destruct H.\n  sep split in H; sep split in H0; simpljoin1.\n  sep remember (3::nil)%nat in H0.\n  sep remember (2::nil)%nat in H.\n  simpl in H0; simpl in H; simpljoin1.\n  rewrite H33 in H19; inverts H19.\n  eapply mapstoval_false_vptr_eq with (M := M); eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n\n  destruct H.\n  destruct H0.\n  sep split in H; sep split in H0; simpljoin1.\n  sep remember (2::nil)%nat in H0.\n  sep remember (2::nil)%nat in H.\n  simpl in H0; simpl in H; simpljoin1.\n  rewrite H29 in H15; inverts H15.\n  eapply mapstoval_false_vptr_eq with (M := M); eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\nQed.\n\nLemma AOSTCBList'_osabst_emp :\n  forall e e0 M i o a0 lo p1 p2 l1 l2 rtbl hcurt tcbls pf,\n    (e, e0, M, i, lo, o, a0) |= AOSTCBList' p1 p2 l1 l2 rtbl hcurt tcbls pf ->\n    o = empabst.\nProof.\n  intros.\n  unfold AOSTCBList' in H.\n  destruct H.\n  do 4 destruct H.\n  sep split in H.\n  clear H0 H1 H2 H3 H4.\n  sep lifts (2::4::nil)%nat in H.\n  eapply tcbdllseg_compose in H.\n  simpl_sat H; simpljoin1.\n  simpl in H8; simpljoin1.\n  apply tcbdllseg_osabst_emp in H3.\n  apply tcbdllflag_osabst_emp in H14.\n  simpl in H13; simpljoin1.\n\n  destruct H.\n  unfold tcblist in H.\n  unfold TCB_Not_In in H.\n  sep normal in H; sep split in H.\n  simpl_sat H; simpljoin1.\n  clear H0 H2 H1 H19.\n  simpl in H7.\n  simpl in H12.\n  simpljoin1.\n  apply tcbdllseg_osabst_emp in H17.\n  apply tcbdllflag_osabst_emp in H18.\n  simpljoin1.\nQed.\n\nLemma AOSTCBFreeList'_osabst_emp :\n  forall e e0 M i o a0 lo ptfree lfree ct tcbls,\n    (e, e0, M, i, lo, o, a0) |= AOSTCBFreeList' ptfree lfree ct tcbls->\n    o = empabst.\nProof.\n  intros.\n  unfold AOSTCBFreeList' in H.\n  simpl_sat H.\n  simpljoin1.\n  destruct H4.\n  unfold TCBFree_Not_Eq in H.\n  sep split in H.\n  clear H1.\n  simpl_sat H.\n  simpl in H3.\n  simpljoin1.\n  apply sll_osabst_emp in H6.\n  apply sllfreeflag_osabst_emp in H7.\n  simpljoin1.\n\n  unfold TCBFree_Eq in H.\n  do 3 destruct H.\n  sep split in H.\n  clear H1 H4.\n  simpl_sat H.\n  simpl in H3.\n  simpljoin1.\n  apply Astruct_osabst_emp in H6.\n  apply sll_osabst_emp in H16.\n  apply sllfreeflag_osabst_emp in H17.\n  simpl in H11; simpljoin1.\nQed.\n\n(*main lemmas*)\nLemma OSInv_precise : precise OSInv.\nProof.\n  unfold precise; intros.\n  destruct s; destruct r; destruct t; destruct p; destruct s; destruct p; simpl substmo in *.\n  unfold OSInv in *.\n  do 20 destruct H, H0.\n  sep remember (9::10::nil)%nat in H;\n    sep remember (9::10::nil)%nat in H0.\n  sep remember (3::nil)%nat in H;\n    sep remember (3::nil)%nat in H0.\n  simpl in H, H0; simpljoin1.\n\n  assert (\n      (forall M : mem, sub x39 M -> sub x45 M -> x39 = x45) /\\\n      (forall o0 : osabst, sub x42 o0 -> sub x48 o0 -> x42 = x48)\n    ).\n  clear H14 H9.\n  rename H8 into H; rename H13 into H0.\n  \n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx1: AOSEventFreeList_precise _H _H0; clear _H _H0.\n\n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx2: AOSQFreeList_precise _H _H0; clear _H _H0.\n\n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx3: AOSQFreeBlk_precise _H _H0; clear _H _H0.\n  \n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx4: AECBList_precise _H _H0; clear _H _H0.\n  \n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx5: AOSMapTbl_precise _H _H0; clear _H _H0.\n  \n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx6: AOSUnMapTbl_precise _H _H0; clear _H _H0.\n  \n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx7: AOSTCBPrioTbl_precise _H _H0; clear _H _H0.\n\n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx8: AOSIntNesting_precise _H _H0; clear _H _H0.\n  \n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx11: AOSRdyTblGrp_precise _H _H0; clear _H _H0.\n  \n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx12: AOSTime_precise _H _H0; clear _H _H0.\n  \n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx13: Aabsdata_precise _H _H0; clear _H _H0.\n  \n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx14: Aabsdata_precise _H _H0; clear _H _H0.\n  \n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx15: Aabsdata_precise _H _H0; clear _H _H0.\n  \n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx16: Aabsdata_precise _H _H0; clear _H _H0.\n\n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n  lets Hx17: AGVars_precise _H _H0; clear _H _H0.\n\n  sep split in H; sep split in H0.\n\n  lets Hx18: A_isr_is_prop_precise H H0; clear H H0.\n\n  simpljoin1; split; intros.\n  mem_eq_solver M.\n  osabst_eq_solver o0.\n\n  (**)\n  clear H13 H8.\n  split; intros.\n\n  assert (x32 = x31).\n  simpl_sat H9; simpl_sat H14; simpljoin1.\n  eapply AOSTCBList'_ct_eq with (M := M); eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n  \n  destruct H.\n  assert (x39 = x45).\n  eapply H with (M := M).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n\n  simpl_sat H9.\n  simpl_sat H14.\n  simpljoin1.\n  assert (x35 = x36).\n  eapply AOSTCBFreeList'_pfree_eq with (M := M); eauto.\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  \n  lets Hx: AOSTCBFreeList'_precise H18 H13.\n  destruct Hx.\n  assert (x52 = x39).\n  eapply H4 with (M := M).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n\n  lets Hx: AOSTCBList'_precise H11 H17.\n  destruct Hx.\n  assert (x32 = x51).\n  eapply H3 with (M := M).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n  mem_eq_solver2.\n\n  destruct H.\n  assert (x42 = x48).\n  eapply H2 with (o0 := o0).\n  mem_join_sub_solver.\n  mem_join_sub_solver.\n  substs.\n\n  simpl_sat H9.\n  simpl_sat H14.\n  simpljoin1.\n  apply AOSTCBList'_osabst_emp in H17.\n  apply AOSTCBList'_osabst_emp in H11.\n  apply AOSTCBFreeList'_osabst_emp in H18.\n  apply AOSTCBFreeList'_osabst_emp in H13.\n  simpljoin1.\nQed.\n\n\n\n(*----is isr irrelvant lemmas----*)\nLtac destr_and_inst H v:= let s := fresh v in (destruct H as [s H]; exists s).\n\nLtac simpl_sat_goal := unfold sat; fold sat; unfold substmo; unfold substaskst; unfold getmem; unfold getabst; unfold get_smem; unfold get_mem.\n\nLtac cancel_pure H := sep split in H; sep split; auto.\n\nLtac solve_sat H := simpl_sat H; simpl_sat_goal; simpljoin1; do 6 eexists; repeat(split; eauto); eauto.\n\nLtac get_isr_is_prop H := unfold OSInv in H; simpljoin1; do 20 destruct H; sep remember (19::nil)%nat in H; simpl in H; simpljoin1.\n\nLtac solve_sat_auto :=\n  match goal with\n    | H: _ |= ?P ** ?Q |- _ => sep remember (1::nil)%nat in H; solve_sat H; solve_sat_auto\n    | _ => idtac\n  end.\n\n\nLemma is_isr_irrel_Astruct' :\n  forall vl l d a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= Astruct' l d vl ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= Astruct' l d vl.\nProof.\n  inductions vl; intros.\n  destruct d; simpl in H; simpl; auto.\n  \n  destruct d; simpl in H; tryfalse.\n          \n  destruct t; destruct l;\n  try solve [\n        simpl in H; simpl; simpljoin1;\n        do 6 eexists; repeat(split; eauto);\n        apply OSAbstMod.join_emp; auto;\n        eapply IHvl];\n  try solve [\n        simpl; eapply IHvl; eauto].\nQed.\n\nLemma is_isr_irrel_Astruct :\n  forall vl l t a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= Astruct l t vl ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= Astruct l t vl.\nProof.\n  unfold Astruct; intros; destruct t; tryfalse.\n  eapply is_isr_irrel_Astruct'; eauto.\nQed.\n\nLemma is_isr_irrel_node :\n  forall vl v t a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= node v vl t ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= node v vl t.\nProof.\n  unfold node; intros.\n  destr_and_inst H v.\n  sep split in H; sep split; auto.\n  \n  eapply is_isr_irrel_Astruct; eauto.\nQed.\n\nLemma is_isr_irrel_Aarray' :\n  forall vl l n t a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= Aarray' l n t vl ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= Aarray' l n t vl.\nProof.\n  inductions vl; destruct n; intros.\n  simpl in H; simpl;auto.\n  simpl in H; tryfalse.\n  \n  simpl in H; tryfalse.\n  simpl in H; destruct l; simpl.\n  simpl in H; simpljoin1.\n  do 6 eexists; repeat (split; eauto).\n  apply OSAbstMod.join_emp; auto.\nQed.\n\nLemma is_isr_irrel_Aarray :\n  forall vl l t a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= Aarray l t vl ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= Aarray l t vl.\nProof.\n  unfold Aarray; intros.\n  destruct t; tryfalse.\n  eapply is_isr_irrel_Aarray'; eauto.\nQed.\n\nLemma is_isr_irrel_sllseg :\n  forall l head tail t next a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= sllseg head tail l t next ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= sllseg head tail l t next.\nProof.\n  inductions l; intros.\n  simpl in H; simpl; simpljoin1; splits; auto.\n  unfolds; auto.\n  \n  unfold sllseg in H; fold sllseg in H.\n  unfold sllseg; fold sllseg.\n  sep split in H; sep split; auto.\n  destr_and_inst H v.\n  sep split in H; sep split; auto.\n  simpl_sat H; simpl_sat_goal; simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  eapply is_isr_irrel_node; eauto.\nQed.\n\nLemma is_isr_irrel_sll :\n  forall l head t next a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= sll head l t next ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= sll head l t next.\nProof.\n  unfold sll; intros.      \n  eapply is_isr_irrel_sllseg; eauto.\nQed.\n\nLemma is_isr_AOSEvent :\n  forall v osevent etbl a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= AOSEvent v osevent etbl ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= AOSEvent v osevent etbl.\nProof.\n  unfold AOSEvent; intros.\n  do 2 destr_and_inst H v.\n  sep split in H; sep split; auto.\n  simpl_sat H; simpl_sat_goal; simpljoin1.\n  do 6 eexists; repeat (split; eauto).\n  eapply is_isr_irrel_node; eauto.\n  \n  unfold AOSEventTbl in *.\n  sep split in H7; sep split; auto.\n  eapply is_isr_irrel_Aarray; eauto.\nQed.\n\nLemma is_isr_AEventData :\n  forall osevent d a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= AEventData osevent d ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= AEventData osevent d.\nProof.\n  unfold AEventData; intros.\n  destruct d; try (sep split in H; sep split; auto).\n  unfold AMsgData in *.\n  destr_and_inst H v.\n  sep split in H; sep split; auto.\n  clear - H.\n  simpl_sat H; simpl_sat_goal; simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  clear - H3.\n  unfold AOSQCtr in *.\n  sep split in H3; sep split; auto.\n  eapply is_isr_irrel_node; eauto.\n  clear - H4.\n  unfold AOSQBlk in *.\n  destr_and_inst H4 v.\n  sep split in H4; sep split; auto.\n  simpl_sat H4; simpl_sat_goal; simpljoin1.\n  do 6 eexists; repeat (split; eauto).\n  eapply is_isr_irrel_node; eauto.\n  eapply is_isr_irrel_Aarray; eauto.\nQed.\n\nLemma is_isr_AEventNode :\n  forall v osevent etbl d a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= AEventNode v osevent etbl d ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= AEventNode v osevent etbl d.\nProof.\n  unfold AEventNode in *; intros.\n  simpl_sat H; simpl_sat_goal.\n  simpljoin1.\n  do 6 eexists; repeat (split; eauto).\n  clear - H3.\n  \n  eapply is_isr_AOSEvent; eauto.\n  clear - H4.\n  eapply is_isr_AEventData; eauto.\nQed.\n\n\nLemma is_isr_qblkf_evsllseg :\n  forall vl head tail ecbls a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= evsllseg head tail vl ecbls  ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= evsllseg head tail vl ecbls.\nProof.\n  inductions vl; intros.\n  simpl in H; simpl; simpljoin1.\n  splits; eauto.\n  unfolds; auto.\n  \n  unfold evsllseg in H; fold evsllseg in H.\n  unfold evsllseg; fold evsllseg.\n  destruct ecbls; tryfalse; destruct a.\n  destr_and_inst H v.\n  sep split in H; sep split; auto.\n  simpl_sat H; simpl_sat_goal; simpljoin1.\n  do 6 eexists; repeat (split; eauto).\n  clear - H4.\n  \n  eapply is_isr_AEventNode; eauto.\nQed.\n\n\nLemma is_isr_dllseg :\n  forall l head headprev tail tailnext t prev next a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= dllseg head headprev tail tailnext l t prev next->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= dllseg head headprev tail tailnext l t prev next.\nProof.\n  inductions l; intros.\n  simpl in H; simpl; simpljoin1.\n  do 6 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  unfold emposabst; splits; auto.\n  unfolds; auto.\n\n  unfold dllseg in H; fold dllseg in H.\n  unfold dllseg; fold dllseg.\n  sep split in H; sep split; auto.\n  destr_and_inst H v.\n  cancel_pure H.\n\n  solve_sat H.\n  eapply is_isr_irrel_node; eauto.\nQed.\n\n\nLemma is_isr_tcbdllseg :\n  forall head headprev tail tailnext l a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= tcbdllseg head headprev tail tailnext l->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= tcbdllseg head headprev tail tailnext l.\nProof.\n  unfold tcbdllseg; intros.\n  eapply is_isr_dllseg; eauto.\nQed.\n\n\nLemma is_isr_qblkf_sllseg :\n  forall l head tailnext t next a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= qblkf_sllseg head tailnext l t next  ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= qblkf_sllseg head tailnext l t next.\nProof.\n  inductions l; intros.\n  simpl in H; simpl; simpljoin1.\n  splits; eauto.\n  unfolds; auto.\n\n  unfold qblkf_sllseg in H; fold qblkf_sllseg in H.\n  unfold qblkf_sllseg; fold qblkf_sllseg.\n  do 3 destr_and_inst H v.\n  sep split in H; sep split; auto.\n  simpl_sat H; simpl_sat_goal; simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  eapply is_isr_irrel_node; eauto.\n  do 6 eexists; repeat(split; eauto).\n  eapply is_isr_irrel_Aarray; eauto.\nQed.\n(*--end--*)\n\nLemma is_isr_sllsegfreeflag :\n  forall l head tailnext next a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= sllsegfreeflag head tailnext l next->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= sllsegfreeflag head tailnext l next.\nProof.\n  inductions l; intros.\n  simpl in H; simpljoin1.\n  simpl.\n  unfold emposabst; auto.\n\n  unfold sllsegfreeflag in *; fold sllsegfreeflag in *.\n  do 2 destruct H.\n  exists x0 x1.\n  sep split in H.\n  sep split; auto.\n  simpl_sat H; simpljoin1.\n  simpl.\n  do 6 eexists; splits; eauto.\nQed.\n\nLemma is_isr_sllfreeflag :\n  forall head l a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= sllfreeflag head l->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= sllfreeflag head l.\nProof.\n  intros.\n  unfold sllfreeflag in *.\n  eapply is_isr_sllsegfreeflag; eauto.\nQed.\n\nLemma is_isr_dllsegflag :\n  forall l head tailnext next a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= dllsegflag head tailnext l next->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= dllsegflag head tailnext l next.\nProof.\n  inductions l; intros.\n  simpl in H; simpljoin1.\n  simpl.\n  do 6 eexists; splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst; auto.\n  unfolds; auto.\n\n  unfold dllsegflag in *; fold dllsegflag in *.\n  do 2 destruct H.\n  exists x0 x1.\n  sep split in H.\n  sep split; auto.\n  simpl_sat H; simpljoin1.\n  simpl.\n  do 6 eexists; splits; eauto.\nQed.\n\nLemma is_isr_tcbdllflag :\n  forall head l a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= tcbdllflag head l->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= tcbdllflag head l.\nProof.\n  intros.\n  unfold tcbdllflag in *.\n  eapply is_isr_dllsegflag; eauto.\nQed.\n\n(*main lemma*)\nLemma OSInv_isr_is_irrel :\n  forall a b c ir ir' ie0 si si' cs0 x aop,\n    (a, b, c, ir, (ie0, si, cs0), x, aop) |= OSInv -> isr_is_prop ir' si' ->\n    (a, b, c, ir', (ie0, si', cs0), x, aop) |= OSInv.\nProof.\n  unfold OSInv; intros.\n  rename H0 into Hxxx.\n  do 20 destr_and_inst H v.\n  \n  sep remember (1::nil)%nat in H.\n  simpl in H; simpl; simpljoin1.\n  do 6 eexists; splits; eauto.\n  do 4 eexists; do 3 exists empabst.\n  splits; eauto.\n  symmetry; eapply ecbf_sllseg_osabst_emp; eauto.\n  apply map_join_emp.\n  \n  do 4 eexists; do 3 exists empabst; splits; eauto.\n  apply map_join_comm.\n  apply map_join_emp.\n  apply map_join_emp.\n  eexists; splits; eauto.\n  unfolds; auto.\n  unfolds; auto.\n\n  \n  clear - H10.\n  (*ecbf_sll isr_is_irrel*)\n  unfold ecbf_sll in *.\n  inductions v.\n  simpl in H10; simpljoin1.\n  simpl; intuition.\n  unfolds; auto.\n\n  unfold ecbf_sllseg in H10; fold ecbf_sllseg in H10.\n  unfold ecbf_sllseg; fold ecbf_sllseg.\n  do 3 destr_and_inst H10 v.\n  \n  sep split in H10; sep split; auto.\n  simpl_sat H10.\n  simpl_sat_goal. \n  simpljoin1.\n\n  do 3 eexists; do 3 exists empabst.\n  repeat (split; eauto).\n  lets Hx : node_osabst_emp H5; substs.\n  \n  eapply is_isr_irrel_node; eauto.\n  \n  do 6 eexists; repeat(split; eauto).\n  eapply OSAbstMod.join_emp; auto.\n  lets Hx: Aarray_osabst_emp H10; substs.\n\n  eapply is_isr_irrel_Aarray; eauto.\n  \n  sep remember (1::nil)%nat in H5.\n  simpl_sat H5; simpl_sat_goal.\n  simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n\n  (*AOSQFreeList is_isr_irrel*)\n  clear - H7.\n  unfold AOSQFreeList in *.\n  simpl_sat H7; simpl_sat_goal; simpljoin1.\n  do 7 eexists; repeat(split; eauto).\n  simpl in H3; simpl; simpljoin1.\n  do 7 eexists; splits; eauto.\n  apply map_join_comm; apply map_join_emp.\n  apply map_join_emp.\n  eexists; splits; eauto.\n  unfolds; auto.\n  unfolds; auto.\n\n  clear - H4.\n  \n  eapply is_isr_irrel_sll; eauto.\n  clear - H8 Hxxx.\n\n  sep remember (1::nil)%nat in H8.\n  simpl_sat H8; simpl_sat_goal.\n  simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  clear - H4.\n  \n  (*AOSQFreeBlk is_isr_irrel*)\n  unfold AOSQFreeBlk in *.\n  simpl_sat H4; simpl_sat_goal; simpljoin1.\n  do 7 eexists; repeat(split; eauto).\n  simpl in H3; simpl; simpljoin1.\n  do 7 eexists; splits; eauto.\n  apply map_join_comm; apply map_join_emp.\n  apply map_join_emp.\n  eexists; splits; eauto.\n  unfolds; auto.\n  unfolds; auto.\n  \n  \n  clear - H4.\n  unfold qblkf_sll.\n  unfold qblkf_sll in *.\n  \n  eapply is_isr_qblkf_sllseg; eauto.\n  clear - H5 Hxxx.\n\n  sep remember (1::nil)%nat in H5.\n  simpl_sat H5; simpl_sat_goal.\n  simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  clear - H4.\n  \n  (*AECBList is_isr_irrel*)\n  unfold AECBList in *.\n  destr_and_inst H4 v.\n  sep split in H4; sep split; auto.\n  simpl_sat H4; simpl_sat_goal; simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n\n  clear - H5.\n\n  eapply is_isr_qblkf_evsllseg; eauto.\n\n  sep remember (1::nil)%nat in H5.\n  simpl_sat H5; simpl_sat_goal.\n  simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  clear - H7.\n  unfold AOSMapTbl in *; unfold GAarray in *.\n  destr_and_inst H7 v.\n  simpl_sat H7; simpl_sat_goal; simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  eapply is_isr_irrel_Aarray; eauto.\n  clear - H8 Hxxx.\n\n  sep remember (1::nil)%nat in H8.\n  simpl_sat H8; simpl_sat_goal.\n  simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  clear - H4.\n  unfold AOSUnMapTbl in *; unfold GAarray in *.\n  destr_and_inst H4 v.\n  simpl_sat H4; simpl_sat_goal; simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  eapply is_isr_irrel_Aarray; eauto.\n  clear - H5 Hxxx.\n\n  sep remember (1::nil)%nat in H5.\n  simpl_sat H5; simpl_sat_goal.\n  simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  clear - H4.\n  unfold AOSTCBPrioTbl in *.\n  sep split in H4; sep split; auto.\n  simpl_sat H4; simpl_sat_goal; simpljoin1.\n  \n  do 6 eexists; repeat (split; eauto).\n  unfold GAarray in *.\n  destr_and_inst H6 v.\n  simpl_sat H6; simpl_sat_goal; simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  eapply is_isr_irrel_Aarray; eauto.\n  do 6 eexists; repeat(split; eauto).\n  eexists; simpl in H12; simpl; eauto.\n  clear - H5 Hxxx.\n\n  sep remember (1::nil)%nat in H5.\n  simpl_sat H5; simpl_sat_goal.\n  simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  clear - H5 Hxxx.\n  \n  sep remember (1::nil)%nat in H5.\n  simpl_sat H5; simpl_sat_goal.\n  simpljoin1.\n  do 6 eexists; repeat(split; eauto).\n  clear - H4.\n\n  unfold AOSTCBList' in *.\n  destruct H4.\n  left.\n  do 4 destruct H.\n  exists x0 x1 x2 x4.\n  sep split in H.\n  sep split; auto.\n  simpl_sat H; simpljoin1.\n  simpl_sat_goal.\n  do 6 eexists.\n  splits; eauto.\n  do 6 eexists; splits; eauto.\n  eapply is_isr_tcbdllseg; eauto.\n  do 6 eexists; splits; eauto.\n  do 6 eexists; splits; eauto.\n  eapply is_isr_tcbdllseg; eauto.  \n  eapply is_isr_tcbdllflag; eauto.\n\n  right.\n  destruct H.\n  exists x0.\n  sep split in H.\n  sep split; auto.\n  simpl_sat H; simpljoin1.\n  simpl_sat_goal.\n  do 6 eexists.\n  splits; eauto.\n  do 6 eexists.\n  splits; eauto.\n  do 6 eexists.\n  splits; eauto.\n  unfold tcblist in *.\n  sep split in H15.\n  sep split; auto.\n  eapply is_isr_tcbdllseg; eauto.\n  do 6 eexists.\n  splits; eauto.\n  eapply is_isr_tcbdllflag; eauto.\n  \n  clear - H5 Hxxx.\n  sep remember (1::nil)%nat in H5.\n  solve_sat H5.\n  clear - H4.\n  unfold AOSTCBFreeList' in *.\n  simpl_sat H4; simpljoin1.\n  simpl_sat_goal.\n  do 6 eexists; splits; eauto.\n  destruct H4.\n  left.\n  unfold TCBFree_Not_Eq in *.\n  sep split in H.\n  sep split; auto.\n  simpl_sat H; simpljoin1.\n  simpl_sat_goal.\n  do 6 eexists.\n  splits; eauto.\n  eapply is_isr_irrel_sll; eauto.  \n  eapply is_isr_sllfreeflag; eauto.\n\n  right.\n  unfold TCBFree_Eq in *.\n  do 3 destruct H.\n  exists x2 x6 x7.\n  sep split in H.\n  sep split; auto.\n  simpl_sat H; simpljoin1.\n  simpl_sat_goal.\n  do 6 eexists.\n  splits; eauto.\n  eapply is_isr_irrel_Astruct; eauto.\n  do 6 eexists.\n  splits; eauto.\n  do 6 eexists.\n  splits; eauto.\n  eapply is_isr_irrel_sll; eauto.\n  eapply is_isr_sllfreeflag; eauto.\n  \n  clear - H5 Hxxx.\n  sep remember (1::nil)%nat in H5.\n  solve_sat H5.\n  clear - H4.\n  unfold AOSRdyTblGrp in *.\n  cancel_pure H4; clear - H4.\n  solve_sat H4.\n  unfold AOSRdyTbl in *.\n  cancel_pure H3.\n  unfold GAarray in *.\n  destr_and_inst H3 v.\n  solve_sat H3.\n  eapply is_isr_irrel_Aarray; eauto.\n  clear - H5 Hxxx.\n\n  cancel_pure H5.\n  solve_sat_auto.\n  \n  clear - H21 Hxxx.\n  simpl in H21; simpl; simpljoin1.\n  do 8 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  splits; eauto.\n  unfolds; auto.\n\n  do 6 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  splits; eauto.\n  unfolds; auto.\n  unfolds; auto.\nQed.\n\n\n(*----good inv asrt lemmas ----*)\nLemma GoodInvAsrt_Astruct' :\n  forall vl l d, GoodInvAsrt (Astruct' l d vl).\nProof.\n  inductions vl; intros.\n  destruct d; simpl; auto.\n  destruct d; simpl; auto.\n  destruct t; destruct l; try solve [simpl; split; auto];\n  try solve [simpl; apply IHvl].\nQed.\n\nLemma GoodInvAsrt_Astruct :\n  forall vl l t, GoodInvAsrt (Astruct l t vl).\nProof.\n  intros.\n  destruct t; simpl; auto.\n  apply GoodInvAsrt_Astruct'.\nQed.\n\nLemma GoodInvAsrt_Aarray' :\n  forall vl l n t, GoodInvAsrt (Aarray' l n t vl).\nProof.\n  inductions vl; intros.\n  destruct n; simpl; auto.\n  destruct n; destruct l; simpl; auto.\nQed.\n\nLemma GoodInvAsrt_Aarray :\n  forall vl l t, GoodInvAsrt (Aarray l t vl).\nProof.\n  intros.\n  destruct t; simpl; auto.\n  apply GoodInvAsrt_Aarray'.\nQed.\n\nLemma GoodInvAsrt_AEventNode : forall v1 v2 v3 v4,  GoodInvAsrt (AEventNode v1 v2 v3 v4).\nProof.\n  intros.\n  unfold AEventNode; unfold GoodInvAsrt; fold GoodInvAsrt; split.\n\n  unfold AOSEvent.\n  unfold GoodInvAsrt; fold GoodInvAsrt; intros.\n  repeat(split; auto).\n\n  apply GoodInvAsrt_Astruct.\n\n  apply GoodInvAsrt_Aarray.\n  unfold AEventData; destruct v4; try solve [simpl; auto].\n  unfold GoodInvAsrt; fold GoodInvAsrt.\n  repeat (split; auto).\n  apply GoodInvAsrt_Astruct.\n  apply GoodInvAsrt_Astruct.\n  apply GoodInvAsrt_Aarray.\nQed.\n\nLemma GoodInvAsrt_dllseg :\n  forall vl head headprev tail tailnext t prev next,\n    GoodInvAsrt (dllseg head headprev tail tailnext vl t prev next).\nProof.\n  inductions vl; intros.\n  simpl; auto.\n  simpl; split; auto.\n  intros.\n  repeat (split; auto).\n  unfold Astruct; destruct t; simpl; auto.\n\n  apply GoodInvAsrt_Astruct'.\nQed.\n\nLemma GoodInvAsrt_dllsegflag :\n  forall vl head tailnext next,\n    GoodInvAsrt (dllsegflag head tailnext vl next).\nProof.\n  inductions vl; intros.\n  simpl; auto.\n  simpl; split; auto.\nQed.\n\nLemma GoodInvAsrt_tcbdllflag :\n  forall vl head,\n    GoodInvAsrt (tcbdllflag head vl).\nProof.\n  intros.\n  unfold tcbdllflag.\n  apply GoodInvAsrt_dllsegflag.\nQed.\n\nLemma GoodInvAsrt_sllseg :\n  forall l head tailnext t next,\n    GoodInvAsrt (sllseg head tailnext l t next).\nProof.\n  inductions l.\n  simpl; auto.\n  simpl; split; auto.\n  intro.\n  splits; auto.\n  intro.\n  split; auto.\n  apply GoodInvAsrt_Astruct.\nQed.\n\nLemma GoodInvAsrt_sll :\n  forall head l t next,\n    GoodInvAsrt (sll head l t next).\nProof.\n  intros.\n  unfold sll.\n  apply GoodInvAsrt_sllseg.\nQed.\n\nLemma GoodInvAsrt_sllsegfreeflag :\n  forall vl head tailnext next,\n    GoodInvAsrt (sllsegfreeflag head tailnext vl next).\nProof.\n  inductions vl; intros.\n  simpl; auto.\n  simpl; intros.\n  splits; auto.\nQed.\n\nLemma GoodInvAsrt_sllfreeflag :\n  forall head l,\n    GoodInvAsrt (sllfreeflag head l).\nProof.\n  intros.\n  unfold sllfreeflag.\n  apply GoodInvAsrt_sllsegfreeflag.\nQed.\n    \n\n(*---end of auxiliary lemmas----*)\n\nLemma invprop : inv_prop OSInv.\nProof.\n  unfolds.\n  split.\n  apply OSInv_precise. \n  unfolds.\n  \n  split; intros.\n  destruct_s s; simpl set_isr_s.\n\n  eapply OSInv_isr_is_irrel; eauto.\n  get_isr_is_prop H. clear - H15.\n  \n  unfold isr_is_prop in *; intros.\n  apply H15 in H.\n  unfold isrupd.\n  destruct(beq_nat i x); auto.\n\n  split; intros.\n  destruct_s s; simpl set_isisr_s.\n  eapply OSInv_isr_is_irrel; eauto.\n  get_isr_is_prop H; clear - H15.\n  \n  unfold isr_is_prop in *; intros.\n  unfold isrupd.\n  destruct(beq_nat i x) eqn : eq1.\n  false; apply H.\n  simpl; left.\n  apply beq_nat_true in eq1; auto.\n  apply H15.\n  intro; apply H.\n  simpl; right; auto.\n  \n  split; intros.\n  destruct_s s; simpl set_is_s.\n  simpl get_isr_s in H0; simpl get_is_s in H1.\n  eapply OSInv_isr_is_irrel; eauto.\n  get_isr_is_prop H; clear - H16 H0.\n  unfold isr_is_prop in *; intros.\n  destruct(beq_nat i x) eqn : eq1.\n  apply beq_nat_true in eq1; substs; auto.\n  apply H16.\n  intro; apply H.\n  simpl in H1; destruct H1; substs.\n  rewrite <- beq_nat_refl in eq1; tryfalse.\n  auto.\n\n  destruct_s s; simpl set_is_s.\n  simpl get_isr_s in H0; substs.\n  eapply OSInv_isr_is_irrel; eauto.\n  unfolds; intros.\n  unfold empisr; auto.\nQed.\n\n\nLemma goodinv:  GoodInvAsrt OSInv.\nProof.\n  unfold OSInv.\n  simpl; intros.\n  repeat (split; auto).\n  clears.\n  gen x19; inductions x; intros.\n  simpl; auto.\n  simpl; repeat (split; auto).\n  repeat (destruct a; [simpl; auto | try (destruct a); simpl; split; auto]).\n  repeat (destruct x2; [simpl; auto | try (destruct x1); simpl; split; auto]).\n  eapply IHx.\n\n  clears.\n  gen x19; inductions x0; intros.\n  simpl; auto.\n  simpl; repeat(split; auto).\n  repeat (destruct a; [simpl; auto | try (destruct a); simpl; split; auto]).\n  eapply IHx0.\n\n  clears.\n  gen x19; inductions x1; intros.\n  simpl; auto.\n  simpl; repeat(split; auto).\n  repeat (destruct a; [simpl; auto | try (destruct a); simpl; split; auto]).  \n  repeat (destruct x2; [simpl; auto | try (destruct x0); simpl; split; auto]).\n  apply IHx1.\n\n  clears.\n  gen x2 x19; inductions x3; intros.\n  simpl; auto.\n  simpl; repeat(split; auto).\n  destruct x2.\n  simpl; auto.\n  destruct a.\n  unfold GoodInvAsrt; fold GoodInvAsrt; intros.\n  split; auto.\n  split.\n\n  apply GoodInvAsrt_AEventNode.\n  apply IHx3.\n  \n    \n  destruct x19; simpl; repeat(split; auto).\n  destruct x19; simpl; repeat(split; auto).\n  repeat (destruct x4; [simpl; auto | try (destruct x19); simpl; split; auto]).\n  \n  clears.\n  unfold tcbdllseg.\n\n  apply GoodInvAsrt_dllseg.\n  repeat (destruct x8; [simpl; auto | simpl; split; auto]).\n  apply GoodInvAsrt_dllseg.\n\n  apply GoodInvAsrt_tcbdllflag.\n  unfold tcbdllseg; apply GoodInvAsrt_dllseg.\n  apply GoodInvAsrt_tcbdllflag.\n  apply GoodInvAsrt_sll.\n\n  clears.\n  gen x17; inductions x18; intros.\n  simpl; auto.\n  simpl; repeat(split; auto).\n  repeat (destruct a; [simpl; auto | simpl; split; auto]).\n  eapply IHx18.\n  repeat (destruct x20; [simpl; auto | try (destruct x15); simpl; split; auto]).\n  apply GoodInvAsrt_sll.\n  apply GoodInvAsrt_sllfreeflag.\n  repeat (destruct x10; [simpl; auto | try (destruct x19); simpl; split; auto]).\nQed.\n\nLemma goodinv_aemp :\n  GoodInvAsrt aemp_isr_is.\nProof.\n  unfold aemp_isr_is.\n  unfold A_isr_is_prop.\n  unfold GoodInvAsrt; auto.\nQed.\n\nLemma invprop_aemp :\n  inv_prop aemp_isr_is.\nProof.\n  unfolds; split.\n  unfolds; destruct_s s; intros.\n  simpl in H, H0; simpljoin1; intros; auto.\n\n  unfolds; split; intros.\n  destruct_s s.\n  simpl in H; simpl; simpljoin1.\n  do 6 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  unfold emposabst; split; auto.\n\n  do 8 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  unfold emposabst; splits; eauto.\n  \n  do 6 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  unfold emposabst; splits; eauto.\n  \n  unfold isr_is_prop in *; intros.\n  apply H14 in H.\n  unfolds.\n  destruct(beq_nat i x); auto.\n  unfolds; auto.\n  \n  split; intros.\n  destruct_s s.\n  simpl in H; simpl; simpljoin1.\n  do 6 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  unfold emposabst; splits; eauto.\n  \n  do 8 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  unfold emposabst; splits; eauto.\n    \n  do 6 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  unfold emposabst; splits; eauto.\n\n  unfold isr_is_prop in *; intros.\n  unfold isrupd.\n  destruct( beq_nat i x ) eqn :eq1.\n  false; apply H; simpl; left.\n  apply beq_nat_true in eq1; auto.\n  apply H14; intro; apply H.\n  simpl; right; auto. \n  unfolds; auto.\n\n  split; intros.\n  destruct_s s; simpl in H; simpl; simpljoin1.\n  do 6 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  unfold emposabst; splits; eauto.\n\n  \n  do 8 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  unfold emposabst; splits; eauto.\n \n  do 6 eexists.\n  split; eauto.\n  split.\n  apply map_join_emp.\n  split; eauto.\n  split.\n  apply map_join_emp.\n  split.\n  splits; eauto.\n  unfolds; auto.\n  splits; eauto.\n  \n  unfold isr_is_prop in *; unfold get_isr_s in H0; unfold get_is_s in H1; intros.\n  destruct( beq_nat i x ) eqn :eq1.\n  apply beq_nat_true in eq1; substs; auto.\n  apply H16; intro; apply H; substs.\n  simpl in H2; destruct H2; substs.\n  rewrite <- beq_nat_refl in eq1; tryfalse.\n  auto.\n  unfolds; auto.\n\n  destruct_s s; simpl in H; simpl; simpljoin1.\n  simpl in H0; substs.\n  do 6 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  unfold emposabst; split; auto.\n\n  do 8 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  splits; eauto.\n  unfolds; auto.\n\n  do 6 eexists.\n  split; eauto.\n  split.\n  apply map_join_emp.\n  split; eauto.\n  split.\n  apply map_join_emp.\n  split.\n  splits; eauto.\n  unfolds; auto.\n  splits; eauto.\n  unfolds.\n  intros.\n  unfolds; auto.\n  unfolds; auto.\nQed.\n\n\nLemma atoy_inv'_precise :\n  forall e e0 M1 M2 i i0 i1 c o1 o2 a,\n    (e, e0, M1, i, (i0, i1, c), o1, a) |= atoy_inv' ->\n    (e, e0, M2, i, (i0, i1, c), o2, a) |= atoy_inv' ->\n    (forall M : mem,\n       sub M1 M -> sub M2 M -> M1 = M2) /\\\n    (forall o0 : osabst,\n       sub o1 o0 -> sub o2 o0 -> o1 = o2).\nProof.\n  intros.\n  unfold atoy_inv' in *.\n  simpl in H, H0; simpljoin1; split; auto; intros.\n  rewrite H13 in H4; inverts H4.\n  eapply mapstoval_true_mem_eq; eauto.\nQed.\n\n\nLemma OSInv_prop :\n  forall o O O' aop,\n    (o, O, aop) |= OSInv -> disjoint O O' -> O' = empabst.\nProof.\n  intros.\n  unfold OSInv in H.\n  sep normal in H; sep destruct H.\n  \n  eapply extensionality; intros.\n  rewrite emp_sem.\n  destruct a.\n\n  sep remember (14::nil)%nat in H.\n  simpl in H; simpljoin1.\n  eapply osabst_disjoint_join_sig_get_none; eauto.\n\n  sep remember (13::nil)%nat in H.\n  simpl in H; simpljoin1.\n  eapply osabst_disjoint_join_sig_get_none; eauto.\n  \n  sep remember (15::nil)%nat in H.\n  simpl in H; simpljoin1.\n  eapply osabst_disjoint_join_sig_get_none; eauto.\n  \n  sep remember (16::nil)%nat in H.\n  simpl in H; simpljoin1.\n  eapply osabst_disjoint_join_sig_get_none; eauto.\nQed.\n\n  \nLemma goodinv_atoy :\n  GoodInvAsrt atoy_inv.\nProof.\n  unfold atoy_inv.\n  unfold atoy_inv'.\n  unfold A_isr_is_prop.\n  unfold GoodInvAsrt; simpl;auto.\nQed.\n\nLemma invprop_atoyinv :\n  inv_prop atoy_inv.\nProof.\n  unfolds; split.\n  unfolds; intros; destruct_s s; unfold substmo in *; unfold substaskst in *.\n  unfold atoy_inv in *.\n  elim_sep_conj1 H _H; elim_sep_conj1 H0 _H0.\n\n  lets Hx1: atoy_inv'_precise _H _H0.\n  lets Hx2: A_isr_is_prop_precise H H0.\n  simpljoin1; split; intros.\n  mem_eq_solver M.\n  osabst_eq_solver o0.\n\n  unfolds.\n  split; intros. \n  unfold atoy_inv in *.\n  destruct_s s.\n  unfold set_isr_s; unfold get_isr_s.\n  solve_sat_auto.\n  unfold A_isr_is_prop in *.\n  simpl in H5; simpljoin1.\n  simpl.\n  do 8 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  splits; eauto.\n  unfolds; auto.\n\n  do 6 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  splits; eauto.\n  unfolds; auto.\n\n  clear - H12.\n  unfold isr_is_prop in *; intros.\n  apply H12 in H.\n  unfold isrupd.\n  destruct(beq_nat i x); auto.\n  unfolds; auto.\n  \n  split; intros.\n  destruct_s s.\n  unfold set_isisr_s; unfold get_is_s; unfold get_isr_s.\n  unfold atoy_inv in *.\n  solve_sat_auto.\n  simpl in H5; simpljoin1.\n  simpl.\n  do 8 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  splits; eauto.\n  unfolds; auto.\n\n  do 6 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  splits; eauto.\n  unfolds; auto.\n\n  clear - H12.\n  unfold isr_is_prop in *; intros.\n  unfold isrupd.\n  destruct(beq_nat i x) eqn : eq1.\n  false; apply H.\n  simpl; left.\n  apply beq_nat_true in eq1; auto.\n  apply H12.\n  intro; apply H.\n  simpl; right; auto.\n  unfolds; auto.\n  \n  split; intros.\n  destruct_s s.\n  unfold set_isr_s, get_is_s, get_isr_s in *.\n  unfold atoy_inv in *.\n  solve_sat_auto.\n  unfold set_is_s.\n  simpl in H7; simpljoin1.\n  simpl.\n  do 8 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  splits; eauto.\n  unfolds; auto.\n\n  do 6 eexists.\n  split; eauto.\n  split.\n  apply map_join_emp.\n  split; auto.\n  split.\n  apply map_join_emp.\n  repeat (split; eauto).\n\n  unfold isr_is_prop in *; intros.\n  destruct( beq_nat i x ) eqn :eq1.\n  apply beq_nat_true in eq1; substs; auto.\n  apply H13; intro; apply H; substs.\n  simpl in H1; destruct H1; substs.\n  rewrite <- beq_nat_refl in eq1; tryfalse.\n  auto.\n\n  destruct_s s.\n  unfold get_isr_s in *; substs.\n  unfold atoy_inv in *.\n  solve_sat_auto.\n  unfold set_is_s.\n  simpl in H5; simpljoin1.\n  simpl.\n  \n  do 8 eexists; splits; eauto.\n  apply map_join_emp.\n  apply map_join_emp.\n  unfold emposabst.\n  splits; eauto.\n\n  do 6 eexists.\n  split; eauto.\n  split.\n  apply map_join_emp.\n  split; auto.\n  split.\n  apply map_join_emp.\n  repeat (split; eauto).\nQed.\n\nDefinition I (n:hid) :=\n  match n with \n  | 0%nat => mkinvasrt goodinv invprop\n  | 1%nat => mkinvasrt goodinv_atoy invprop_atoyinv\n  | _ => mkinvasrt goodinv_aemp invprop_aemp\n  end.\n\nLemma disj_star_elim_disj_dup:\n  forall p q r, ( p \\\\// q )** r ==> (p ** r) \\\\// (q ** r).\nProof.\n  intros.\n  simpl in *;simpljoin.\n  destruct H3;simpljoin.\n  left.\n  do 6 eexists;splits;eauto.\n  right.\n  do 6 eexists;splits;eauto.\nQed.\n\n\n(*added by zhanghui*)\nLemma osq_inv_in:\n  forall n e e0 m x i1 c O ab, \n    (forall i : hid, x i = false)->\n    (e, e0, m, x, (false, i1, c), O, ab)\n      |= invlth_isr I 0%nat n ->\n    (e, e0, m, x, (false, i1, c), O, ab)\n      |= EX p1 p2 tcbl1 tcbcur tcbl2 ct tcbls rtbl pf,\n  (AOSTCBList' p1 p2 tcbl1 (tcbcur :: tcbl2) rtbl ct tcbls pf) ** HCurTCB ct** Atrue.\nProof.\n  inductions n.\n  introv Hfor Hsat.\n  unfold invlth_isr in Hsat.\n  replace (0-0)%nat with (0%nat) in Hsat by omega.\n  unfold starinv_isr in Hsat.\n  sep destruct Hsat.\n  destruct Hsat.\n  simpl in H.\n  simpljoin1.\n  tryfalse.\n  assert (getinv (I 0%nat) = OSInv) by auto.\n  rewrite H0 in H.\n  remember (([|x0 0%nat = false|] //\\\\ Aisr x0) ) as P.\n  clear HeqP.\n  unfold OSInv in H.\n  sep normal in H.\n  do 20 destruct H.\n  sep remember (9::nil)%nat in H.\n  exists x7 x8 x9 x10 x11 x17.\n  exists x15 x12 x19.\n  sep auto.\n  \n  introv Hfor Hsat.\n  unfold invlth_isr in Hsat.\n  replace (S n-0)%nat with (S n%nat) in Hsat by omega.\n  unfold starinv_isr in Hsat.\n  fold starinv_isr in Hsat.\n  remember ( starinv_isr I 1%nat n) as P.\n  clear HeqP.\n  sep normal in Hsat.\n  destruct Hsat.  \n  \n  apply disj_star_elim_disj_dup in H.\n  destruct H.\n  simpl in H.\n  simpljoin1.\n  tryfalse.\n  assert (getinv (I 0%nat) = OSInv) by auto.\n  rewrite H0 in H.\n  remember (([|x0 0%nat = false|] //\\\\ Aisr x0) ) as d.\n  clear Heqd.\n  unfold OSInv in H.\n  sep auto.\nQed.\n\n\nLemma join_join_disj_copy :\n  forall m1 m2 m3 m4 m5,\n    TcbMod.join m1 m2 m3 -> TcbMod.join m4 m5 m2 -> TcbMod.disj m1 m4.\nProof.\n  intros.\n  intro.\n  pose proof H a.\n  pose proof H0 a.\n  \n  destruct (TcbMod.get m1 a);\n    destruct (TcbMod.get m2 a);\n    destruct (TcbMod.get m3 a);\n    destruct (TcbMod.get m4 a);\n    destruct (TcbMod.get m5 a);\n    tryfalse; auto.\nQed.\n\nLemma TCBList_P_combine_copy :\n  forall l1 l2 v1 v2 rtbl tcbls1 tcbls2 tcbls,\n    TcbMod.join tcbls1 tcbls2 tcbls ->\n    TCBList_P v1 l1 rtbl tcbls1 ->\n    TCBList_P v2 l2 rtbl tcbls2 ->\n    l1 <> nil ->\n    V_OSTCBNext (last l1 nil) = Some v2 ->\n    TCBList_P v1 (l1++l2) rtbl tcbls.\nProof.\n  intros.\n  destruct l1; tryfalse.\n  \n  clear H2.\n  gen v.\n  inductions l1; intros.\n  simpl in H3.\n  simpl.\n  simpl in H0; simpljoin1.\n  do 4 eexists; repeat split; eauto.\n\n  clear - H H4.\n  unfold TcbJoin in *.\n  intro.\n  pose proof H a; clear H.\n  pose proof H4 a; clear H4.\n  rewrite TcbMod.emp_sem in H.\n  unfold sig in *; simpl in *.\n  destruct (TcbMod.get tcbls1 a);\n    destruct (TcbMod.get tcbls2 a);\n    destruct (TcbMod.get tcbls a);\n    destruct (TcbMod.get (TcbMod.sig x x2) a);\n    tryfalse; substs; auto.\n  \n  rewrite <- app_comm_cons.\n  unfold TCBList_P; fold TCBList_P.\n  remember (a::l1) as lx.\n  unfold TCBList_P in H0; fold TCBList_P in H0.\n  substs.\n  simpljoin1. \n  do 4 eexists; repeat split; eauto.\n  instantiate (1:=TcbMod.merge x1 tcbls2).\n  clear - H H4.\n  unfold TcbJoin in *.\n  intro.\n  pose proof H a; clear H.\n  pose proof H4 a; clear H4.\n  unfold sig in *; simpl in *.\n  rewrite TcbMod.merge_sem.\n  destruct (TcbMod.get x1 a);\n    destruct (TcbMod.get tcbls a);\n    destruct (TcbMod.get tcbls1 a);\n    destruct (TcbMod.get tcbls2 a);\n    destruct (TcbMod.get (TcbMod.sig x x2) a);\n    tryfalse; substs; auto.\n\n  eapply IHl1; eauto.\n\n  clear - H H4.\n  apply TcbMod.join_merge_disj.\n  unfold TcbJoin in H4.\n  apply TcbMod.join_comm in H.\n  apply TcbMod.join_comm in H4.\n  apply TcbMod.disj_sym.\n  eapply join_join_disj_copy; eauto.\nQed.\n\nLemma tcb_list_split_by_tcbls :\n  forall l tls tid htcb s head hprev tail tnext rtbl P,\n    get tls tid = Some htcb ->\n    TCBList_P head l rtbl tls ->\n    s |= tcbdllseg head hprev tail tnext l ** P ->\n    (exists l1 tcbnode l2 tls1 tls2 tail1,\n       s |= tcbdllseg head hprev tail1 (Vptr tid) l1 **\n         tcbdllseg (Vptr tid) tail1 tail tnext (tcbnode :: l2) ** P /\\\n       TCBList_P head l1 rtbl tls1 /\\\n       TCBList_P (Vptr tid) (tcbnode :: l2) rtbl tls2 /\\\n       join tls1 tls2 tls /\\ l = l1 ++ tcbnode :: l2).\nProof.\n  inductions l; intros.\n  simpl in H0; substs.\n  rewrite TcbMod.emp_sem in H; tryfalse.\n\n  simpl in H0; simpljoin1.\n  destruct (tidspec.beq tid x) eqn : eq1.\n  pose proof tidspec.beq_true_eq tid x eq1; substs.\n  exists (nil(A:=vallist)) a l TcbMod.emp tls hprev.\n  simpljoin1; splits.\n  sep auto.\n  destruct_s s.\n  simpl in H1; simpljoin1.\n  simpl.\n  do 6 eexists; splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst; auto.\n  unfolds; auto.\n\n  unfold tcbdllseg in H1.\n  unfold dllseg in H1; fold dllseg in H1.\n  destruct_s s.\n  sep split in H1.\n  simpl_sat H1; simpljoin1.\n  simpl; auto.\n  simpl.\n  do 4 eexists; repeat (split; eauto).\n  apply TcbMod.join_emp; auto.\n  rewrite app_nil_l; auto.\n  \n  unfold tcbdllseg in H1.\n  unfold dllseg in H1; fold dllseg in H1.\n  destruct_s s.\n  sep split in H1.\n  simpl_sat H1; simpljoin1.  \n  assert((e, e0, (merge x23 x4), i, (i0, i1, c), (merge x26 x7), a0)\n           |= dllseg x9 (Vptr x) tail tnext l OS_TCB_flag V_OSTCBPrev\n           V_OSTCBNext ** P).\n  simpl_sat_goal.\n  exists x23 x4; eexists.\n  exists x26 x7; eexists.\n  splits; eauto.\n  eapply join_merge_disj.\n  eapply mem_join_join_disjoint; eauto.\n  apply join_comm; eauto.\n  eapply join_merge_disj.\n  eapply osabst_join_join_disjoint; eauto.\n  apply join_comm; eauto.\n\n  assert(get x1 tid = Some htcb).\n  clear - H H3 eq1.\n  unfolds in H3.\n  pose proof H3 tid.\n  rewrite TcbMod.get_sig_none in H0.\n  unfold get in H; simpl in H.\n  rewrite H in H0.\n  unfold get; simpl.\n  destruct(TcbMod.get x1 tid); tryfalse.\n  substs; auto.\n  apply tidspec.beq_false_neq in eq1.\n  auto.\n\n  rewrite H2 in H14; inverts H14.\n  unfold tcbdllseg at 1 in IHl.\n  lets Hx: IHl H7 H5 H1.\n  simpljoin1.\n  \n  exists (a::x0) x5 x8 (TcbMod.merge (TcbMod.sig x x2) x10) x11 x12.\n  simpljoin1; splits; auto.\n  simpl_sat H9; simpljoin1.\n  simpl_sat_goal.\n  \n  exists (merge x22 x13) x14 m (merge x25 x16) x17 o.\n  splits; eauto.\n  clear - H14 H6 H21.\n\n  eapply mem_join_join_join_merge_join_merge; eauto.\n  \n  clear - H16 H8 H23.\n  eapply osabst_join_join_join_merge_join_merge; eauto.\n  \n  unfold tcbdllseg; unfold dllseg; fold dllseg.\n  sep split; auto.\n  exists x9.\n  sep split; auto.\n  simpl_sat_goal.\n  exists x22 x13; eexists.\n  exists x25 x16; eexists.\n  splits; eauto.\n  clear - H6 H21 H14.\n  eapply join_merge_disj.\n  \n  eapply mem_join_join_join_merge_disjoint.\n  eapply H6.\n  eauto.\n  eauto.\n\n  clear - H8 H23 H16.\n  eapply join_merge_disj.\n  eapply osabst_join_join_join_merge_disjoint.\n  eapply H8.\n  eauto.\n  eauto.\n\n  exists x19 x20 x14 x24 x27 x17.\n  splits; eauto.\n  \n  simpl; do 4 eexists; splits; eauto.\n  clear - H3 H13.\n  unfold TcbJoin in *.\n  unfolds; intros.\n  pose proof H3 a; pose proof H13 a.\n  unfold sig in *; simpl in *.\n  rewrite TcbMod.merge_sem.\n  destruct(TcbMod.get (TcbMod.sig x x2) a);\n    destruct (TcbMod.get x1 a);\n    destruct (TcbMod.get tls a);\n    destruct (TcbMod.get x10 a);\n    destruct (TcbMod.get x11 a); tryfalse; auto.\n \n  clear - H3 H13.\n  unfold TcbJoin in *.\n  unfolds; intros.\n  simpl.\n  unfolds; intros.\n  pose proof H3 a; pose proof H13 a.\n  unfold sig in *; simpl in *.\n  rewrite TcbMod.merge_sem.\n  destruct(TcbMod.get (TcbMod.sig x x2) a);\n    destruct (TcbMod.get x1 a);\n    destruct (TcbMod.get tls a);\n    destruct (TcbMod.get x10 a);\n    destruct (TcbMod.get x11 a); tryfalse; substs; auto.\nQed.\n\nLemma starinv_isr_osabst_emp :\n  forall n i e e0 M isr st O ab,\n    (i > 0)%nat ->\n    (forall i0, isr i0 = false) ->\n    (e, e0, M, isr, st, O, ab) |= starinv_isr I i n ->\n    O = OSAbstMod.emp.\nProof.\n  inductions n; intros.\n  simpl in H1; simpljoin1.\n  destruct H1; simpljoin1.\n  destruct i.\n  omega.\n  destruct i.\n  simpl in H6; simpljoin1.\n  simpl in H6; simpljoin1.\n  simpl in H1; simpljoin1.\n  destruct H5; simpljoin1.\n  pose proof H0 i; rewrite H1 in H2; false.\n  lets Hx: IHn H6; eauto.\n  destruct i.\n  omega.\n  destruct i.\n  simpl in H9; simpljoin1.\n  simpl in H9; simpljoin1.\nQed.\n\n\nLemma tcbdllseg_last_nextptr :\n  forall l s head hprev tail tid h P,\n    s |= tcbdllseg head hprev tail (Vptr tid) (h::l) ** P ->\n    V_OSTCBNext (last (h :: l) nil) = Some (Vptr tid).\nProof.\n  inductions l; intros.\n  destruct_s s.\n  unfold tcbdllseg in H; unfold dllseg in H.\n  simpl_sat H; simpljoin1.\n  simpl; auto.\n\n  remember (a::l) as xxx.\n  unfold tcbdllseg in *.\n  unfold dllseg in H; fold dllseg in H.\n  sep pure.\n  destruct_s s.\n  sep remember (1::nil)%nat in H.\n  simpl_sat H; simpljoin1.\n  lets Hx: IHl H8.\n  simpl last in *; auto.\nQed.\n\n(*\nLemma AOSTCBList_set_curtid :\n  forall e e0 M M' is st O ab b tp p1 p2 l1 curtcb l2 rtbl hcurt hcurt' tcbls,\n    RH_CurTCB hcurt' tcbls ->\n    EnvMod.get e OSTCBCur = Some (b, Tptr tp) ->\n    store (Tptr tp) M (b, 0) (Vptr hcurt') = Some M' ->\n    (e, e0, M, is, st, O, ab) |= AOSTCBList p1 p2 l1 (curtcb :: l2) rtbl hcurt tcbls ->\n    exists p2' l1' curtcb' l2', (e, e0, M', is, st, O, ab) |= AOSTCBList p1 p2' l1' (curtcb' :: l2') rtbl hcurt' tcbls.\nProof.\n  intros.\n  exists (Vptr hcurt').\n  unfold AOSTCBList in H2.\n  sep pure.\n  unfold RH_CurTCB in H; do 3 destruct H.\n  pose proof H4 hcurt'.\n  rewrite H in H7.\n  destruct(TcbMod.get x1 hcurt') eqn : eq1;\n    destruct(TcbMod.get x2 hcurt') eqn : eq2;\n    tryfalse; substs.\n  \n  sep lift 2%nat in H2.\n  lets Hx : TCBList_P_split_by_tcbls eq1 H5 H2.\n  simpljoin1.\n  exists x6 x7 (x8 ++ (curtcb :: l2)).\n  unfold AOSTCBList.\n  exists x11 x0 x9 (TcbMod.merge x10 x2).\n  sep split; auto.\n  sep remember (4::nil)%nat in H7.\n  simpl_sat H7; simpljoin1.\n  assert(exists x12', store (Tptr tp) x12 (b, 0) (Vptr hcurt') = Some x12').\n  simpl in H15; simpljoin1.\n  rewrite H0 in H17; inverts H17.\n  lets Hx : lmachLib.store_mapstoval_frame H18 H1; eauto.\n  simpljoin1; eauto.\n  simpljoin1.\n  sep remember (3::nil)%nat.\n  simpl_sat_goal.\n  exists x14 x13 M' x15 x16 O.\n  repeat (split; eauto).\n  eapply join_store; eauto.\n  clear - H15 H7 H0.\n  simpl in H15; simpljoin1.\n  rewrite H0 in H4; inverts H4.\n  simpl.\n  eexists; exists empmem x14 x14 OSAbstMod.emp OSAbstMod.emp OSAbstMod.emp.\n  repeat (split; eauto).\n  apply MemMod.join_emp; auto.\n  eexists.\n  repeat (split; eauto).\n  lets Hx :lmachLib.store_mapstoval_frame1 x12 MemMod.emp H5 H7.\n  eapply MemMod.join_emp; auto.\n  simpljoin1; auto.\n\n  substs.\n  clear - H16.\n  sep auto.\n  assert (H\n            |= tcbdllseg (Vptr hcurt') x11 x (Vptr hcurt) (x7 :: x8) **\n            tcbdllseg (Vptr hcurt) x x0 Vnull (curtcb :: l2) ** Aemp).\n  sep auto.\n  lets Hx: tcbdllseg_compose H0.\n  sep auto.\n\n  replace (x7 :: x8 ++ curtcb :: l2) with ((x7 :: x8) ++ curtcb :: l2).\n  eapply TCBList_P_combine_copy; eauto.\n  clear - H4 H10.\n  unfolds; intro.\n  pose proof H4 a; pose proof H10 a.\n  rewrite TcbMod.merge_sem.\n  destruct (TcbMod.get x1 a);\n    destruct (TcbMod.get x2 a);\n    destruct (TcbMod.get tcbls a);\n    destruct (TcbMod.get x9 a);\n    destruct (TcbMod.get x10 a);\n    tryfalse; substs; auto.\n  clear - H7.\n  sep lift 2%nat in H7.\n\n  eapply tcbdllseg_last_nextptr; eauto.\n\n  rewrite app_comm_cons; auto.\n  clear - H4 H10.\n  unfolds; intros.\n  pose proof H4 a; pose proof H10 a.\n  rewrite TcbMod.merge_sem.\n  destruct (TcbMod.get x1 a);\n    destruct (TcbMod.get x2 a);\n    destruct (TcbMod.get tcbls a);\n    destruct (TcbMod.get x9 a);\n    destruct (TcbMod.get x10 a);\n    tryfalse; substs; auto.\n  \n  sep lift 4%nat in H2.\n  lets Hx : TCBList_P_split_by_tcbls eq2 H6 H2.\n  simpljoin1.\n  exists (l1++x6) x7 x8.\n  unfold AOSTCBList.\n  exists x11 x0 (TcbMod.merge x1 x9) x10.\n  sep split; auto.\n  sep remember (5::nil)%nat in H7.\n  simpl_sat H7; simpljoin1.\n  assert(exists x12', store (Tptr tp) x12 (b, 0) (Vptr hcurt') = Some x12').\n  simpl in H15; simpljoin1.\n  rewrite H0 in H17; inverts H17.\n  lets Hx : lmachLib.store_mapstoval_frame H18 H1; eauto.\n  simpljoin1; eauto.\n  simpljoin1.\n  sep remember (3::nil)%nat.\n  simpl_sat_goal.\n  exists x14 x13 M' x15 x16 O.\n  repeat (split; eauto).\n  eapply join_store; eauto.\n  \n  clear - H15 H7 H0.\n  simpl in H15; simpljoin1.\n  rewrite H0 in H4; inverts H4.\n  simpl.\n  eexists; exists empmem x14 x14 OSAbstMod.emp OSAbstMod.emp OSAbstMod.emp.\n  repeat (split; eauto).\n  apply MemMod.join_emp; auto.\n  eexists.\n  repeat (split; eauto).\n  lets Hx :lmachLib.store_mapstoval_frame1 x12 MemMod.emp H5 H7.\n  eapply MemMod.join_emp; auto.\n  simpljoin1; auto.\n\n  substs.\n  clear - H16.\n  sep auto.\n  sep lift 2%nat in H16.\n  assert (H |= tcbdllseg p1 Vnull x (Vptr hcurt) l1 **\n            tcbdllseg (Vptr hcurt) x x11 (Vptr hcurt') x6 ** Aemp).\n  sep auto.\n  lets Hx: tcbdllseg_compose H0.\n  sep auto.\n\n  destruct l1.\n  simpl in H5; substs.\n  simpl.\n  assert ((TcbMod.merge TcbMod.emp x9) = x9).\n  apply TcbMod.extensionality; intro.\n  rewrite TcbMod.merge_sem; rewrite TcbMod.emp_sem.\n  destruct( TcbMod.get x9 a); auto.\n  rewrite H5.\n  unfold tcbdllseg at 2 in H2; unfold dllseg in H2.\n  sep split in H2; substs; auto.\n\n  eapply TCBList_P_combine_copy; eauto.\n  clear - H4 H10.\n  unfolds; intro.\n  pose proof H4 a; pose proof H10 a.\n  rewrite TcbMod.merge_sem.\n  destruct (TcbMod.get x1 a);\n    destruct (TcbMod.get x2 a);\n    destruct (TcbMod.get tcbls a);\n    destruct (TcbMod.get x9 a);\n    destruct (TcbMod.get x10 a);\n    tryfalse; auto.\n\n  sep lift 3%nat in H2.\n  eapply tcbdllseg_last_nextptr; eauto.\n  \n  clear - H4 H10.\n  unfolds; intro.\n  pose proof H4 a; pose proof H10 a.\n  rewrite TcbMod.merge_sem.\n  destruct (TcbMod.get x1 a);\n    destruct (TcbMod.get x2 a);\n    destruct (TcbMod.get tcbls a);\n    destruct (TcbMod.get x9 a);\n    destruct (TcbMod.get x10 a);\n    tryfalse; substs; auto.\nQed.\n\n\nLemma OSInv_set_curtid :\n  forall e e0 M M' isr st O ab b tp tid,\n    EnvMod.get e OSTCBCur = Some (b, Tptr tp) ->\n    store (Tptr tp) M (b, 0) (Vptr tid) = Some M' ->\n    (e, e0, M, isr, st, O, ab) |= AHprio GetHPrio tid ** Atrue ->\n    (e, e0, M, isr, st, O, ab) |= OSInv ->\n    (e, e0, M', isr, st, OSAbstMod.set O curtid (oscurt tid), ab) |= OSInv.\nProof.\n  intros.\n  unfold OSInv in H2.\n  do 20 destruct H2.\n  sep split in H2.\n\n  sep remember (9::nil)%nat in H2.\n  unfold sat in H2; fold sat in H2; simpl substmo in H2; simpl getmem in H2; simpl getabst in H2; simpljoin1.\n  assert(exists x19', store (Tptr tp) x19 (b, 0) (Vptr tid) = Some x19').\n  simpl; destruct tid.\n  unfold AOSTCBList in H9.\n  destruct H9.\n  do 3 destruct H2.\n  sep remember (3::nil)%nat in H2.\n  simpl in H2; simpljoin1.\n  rewrite H in H17; inverts H17.\n  unfold mapstoval in H18; simpljoin1.\n  sep split in H13; simpljoin1.\n  simpl in H5; destruct x15.\n  unfold ptomvallist in H5; unfold ptomval in H5;  simpljoin1.\n  unfold storebytes.\n  clear - H7 H15 H5 H17.\n  assert(Int.unsigned Int.zero = 0).\n  rewrite Int.unsigned_zero; auto.\n  rewrite H in H5, H15, H17.\n  Ltac join_get_solver :=\n    match goal with \n      | H: MemMod.join (MemMod.sig ?x ?y) _ ?O |- MemMod.get ?O ?x = Some ?y =>\n        eapply MemMod.join_get_get_l; eauto\n      | H: MemMod.join ?O1 ?O2 ?O |- MemMod.get ?O ?x = Some ?y =>\n        eapply MemMod.join_get_get_r; [eauto | join_get_solver]\n    end.\n  assert(MemMod.get x19 (x40, 0) = Some (Pointer b i0 3)).\n  eapply MemMod.join_get_get_l.\n  eapply H7.\n  join_get_solver.\n  rewrite MemMod.get_sig_some; auto.\n  rewrite H0.\n  assert(MemMod.get x19 (x40, 0 + 1) = Some (Pointer b i0 2)).\n  eapply MemMod.join_get_get_l.\n  eapply H7.\n  join_get_solver.\n  rewrite MemMod.get_sig_some; auto.\n  rewrite H1.\n  assert(MemMod.get x19 (x40, 0 + 1 + 1) = Some (Pointer b i0 1)).\n  eapply MemMod.join_get_get_l.\n  eapply H7.\n  join_get_solver.\n  rewrite MemMod.get_sig_some; auto.\n  rewrite H2.\n  assert(MemMod.get x19 (x40, 0 + 1 + 1 + 1) = Some (Pointer b i0 0)).\n  eapply MemMod.join_get_get_l.\n  eapply H7.\n  do 3 (eapply MemMod.join_get_get_r; eauto).\n  rewrite MemMod.get_sig_some; auto.\n  rewrite H3.\n  eexists; eauto.\n  destruct H2.\n  assert(RH_CurTCB tid x13).\n  simpl in H1; simpljoin1.\n  unfolds in H12; simpljoin1.\n  pose proof H11 abtcblsid.\n  rewrite H1 in H13.\n  destruct (OSAbstMod.get x28 abtcblsid); tryfalse.\n  destruct (OSAbstMod.get O abtcblsid) eqn : eq1; tryfalse.\n  substs.\n  assert (OSAbstMod.get O abtcblsid = Some (abstcblist x13)).\n  sep remember (13::nil)%nat in H10.\n  simpl in H10; simpljoin1.\n  pose proof H16 abtcblsid.\n  rewrite OSAbstMod.get_sig_some in H10.\n  destruct (OSAbstMod.get x34 abtcblsid); tryfalse.\n  destruct (OSAbstMod.get x23 abtcblsid) eqn : eq2; tryfalse.\n  substs.\n  pose proof H8 abtcblsid.\n  rewrite eq2 in H10.\n  destruct(OSAbstMod.get x22 abtcblsid); tryfalse.\n  destruct( OSAbstMod.get O abtcblsid); tryfalse.\n  substs; auto.\n  rewrite eq1 in H13; inverts H13.\n  unfolds; eauto.\n  \n  lets Hx: AOSTCBList_set_curtid H5 H H2 H9.\n  simpljoin1.\n  unfold OSInv.\n  exists x x0 x1 x2 x3 x4.\n  exists x5 x24 x25 x26 x27.\n  exists x10 x11 x12 x13 x14.\n  exists tid x16 x17 x18.\n  sep remember (15::nil)%nat in H10.\n  simpl in H10; simpljoin1.\n  sep split; auto.\n  sep remember (9::nil)%nat.\n  unfold sat; fold sat; simpl substmo; simpl getmem; simpl getabst.\n  exists x21 x20 M' x22 (OSAbstMod.set x23 curtid (oscurt tid)) (OSAbstMod.set O curtid (oscurt tid)).\n  repeat (split; eauto).\n  eapply join_store; eauto.\n\n\n  clear - H8 H14.\n  eapply OSAbstMod.join_set_r; eauto.\n  unfolds.\n  pose proof H14 curtid.\n  rewrite OSAbstMod.get_sig_some in H.\n  destruct(OSAbstMod.get x32 curtid); tryfalse.\n  destruct(OSAbstMod.get x23 curtid); tryfalse; substs; eauto.\n  \n  substs.\n  sep remember (15::nil)%nat.\n  simpl.\n  exists empmem x20 x20 (OSAbstMod.sig curtid (oscurt tid)) x32 (OSAbstMod.set x23 curtid (oscurt tid)).\n  repeat (split; eauto).\n  eapply MemMod.join_emp; eauto.\n  clear - H14.\n  unfolds; intro.\n  pose proof H14 a.\n  destruct (absdataidspec.beq curtid a) eqn : eq1.\n  pose proof absdataidspec.beq_true_eq eq1; substs.\n  rewrite OSAbstMod.get_sig_some in *.\n  rewrite OSAbstMod.set_a_get_a; auto.\n  destruct(OSAbstMod.get x32 curtid); tryfalse; auto.\n\n  pose proof absdataidspec.beq_false_neq eq1.\n  rewrite OSAbstMod.get_sig_none in *; auto.\n  rewrite OSAbstMod.set_a_get_a'; auto.\nQed.\n*)\n\nLemma atoy_inv_osabst_emp :\n  forall e e0 M isr st o ab,\n    (e, e0, M, isr, st, o, ab) |= atoy_inv ->\n    o = OSAbstMod.emp.\nProof.\n  intros.\n  simpl in H; simpljoin1.\nQed.\n\n(*\nLemma AHprio_starinv_isr_atoy_inv_false :\n  forall e e0 M M1 M2 isr st O o1 o2 ab n i tid,\n    OSAbstMod.join o1 o2 O -> (i > 0)%nat -> (forall i : hid, isr i = false) ->\n    (e, e0, M, isr, st, O, ab) |= AHprio GetHPrio tid ** Atrue ->\n    (e, e0, M1, isr, st, o2, ab) |= starinv_isr I i n ->\n    (e, e0, M2, isr, st, o1, ab) |= atoy_inv ->\n    False.\nProof.\n  intros.\n  apply starinv_isr_osabst_emp in H3; auto.\n  apply atoy_inv_osabst_emp in H4; auto.\n  substs.\n  simpl in H2; simpljoin1.\n  unfolds in H6; simpljoin1.\n  pose proof H5 abtcblsid.\n  rewrite OSAbstMod.emp_sem in H6.\n  rewrite H in H6.\n  destruct (OSAbstMod.get x3 abtcblsid); tryfalse.\nQed.\n*)\n\n(*\nLemma starinv_isr_set_highest_tid :\n  forall n low i0 e e0 m c O ab tid b tp M' x11,\n    (forall i : hid, x11 i = false) ->\n    EnvMod.get e OSTCBCur = Some (b, Tptr tp) ->\n    store (Tptr tp) m (b, 0) (Vptr tid) = Some M' ->\n    (e, e0, m, x11, (false, i0, c), O, ab) |= AHprio GetHPrio tid ** Atrue ->\n    (e, e0, m, x11, (false, i0, c), O, ab) |= starinv_isr I low n ->\n    (e, e0, M', x11, (false, i0, c), OSAbstMod.set O curtid (oscurt tid), ab) |= starinv_isr I low n.\nProof.\n  inductions n; intros.\n  unfold starinv_isr in *.\n  destruct H3.\n  destruct H3.\n  destruct H3; simpl in H3; simpl in H4; simpljoin1.\n  pose proof H low; rewrite H3 in H4; tryfalse.\n  simpl in H3; simpljoin1.\n  exists x;right.\n  simpl.\n  exists empmem M' M' OSAbstMod.emp (OSAbstMod.set O curtid (oscurt tid)) (OSAbstMod.set O curtid (oscurt tid)).\n  repeat (split; eauto).\n  eapply MemMod.join_emp; auto.\n  eapply OSAbstMod.join_emp; auto.\n  destruct low.\n  unfold I in *; unfold getinv in *.\n\n\n  eapply OSInv_set_curtid; eauto.\n\n  destruct low.\n  unfold I in *; unfold getinv in *.\n  simpl in H8; simpljoin1.\n  simpl in H2; simpljoin1.\n  unfolds in H6; simpljoin1.\n  pose proof H5 abtcblsid.\n  rewrite H2 in H8.\n  rewrite OSAbstMod.emp_sem in H8.\n  destruct(OSAbstMod.get x3 abtcblsid); tryfalse.\n\n  unfold I in *; unfold getinv in *.\n  simpl in H8; simpljoin1.\n  simpl in H2; simpljoin1.\n  unfolds in H6; simpljoin1.\n  pose proof H5 abtcblsid.\n  rewrite OSAbstMod.emp_sem in H8.\n  rewrite H2 in H8.\n  destruct (OSAbstMod.get x3 abtcblsid); tryfalse.\n  \n  unfold starinv_isr in *; fold starinv_isr in *.\n  simpl in H3; simpljoin1.\n  destruct H7; simpljoin1.\n  pose proof H low; tryfalse.\n  cut((e, e0, M', x5, (false, i0, c), OSAbstMod.set O curtid (oscurt tid), ab)\n        |= (getinv (I low)) ** starinv_isr I (S low) n).\n  intro.\n  clear - H3 H10.\n  simpl in H3; simpljoin1.\n  simpl.\n  do 6 eexists; repeat (split; eauto).\n  exists x5; right.\n  do 6 eexists; repeat (split; eauto).\n  apply MemMod.join_emp; auto.\n  apply OSAbstMod.join_emp; auto.\n  \n  destruct low.\n  unfold I in *; fold I in *; unfold getinv in *.\n  assert(exists x1, store (Tptr tp) x (b, 0) (Vptr tid) = Some x1).\n  unfold OSInv in H11.\n  unfold AOSTCBList in H11.\n  sep pure.\n  sep remember (3::nil)%nat in H11.\n  simpl in H11; simpljoin1.\n  rewrite H0 in H23; inverts H23.\n  lets Hx : lmachLib.store_mapstoval_frame (MemMod.merge x29 x0) H24 H1; eauto.\n  clear - H4 H15.\n  unfolds; intro.\n  pose proof H4 a.\n  pose proof H15 a.\n  rewrite MemMod.merge_sem.\n  destruct(MemMod.get x a);\n    destruct(MemMod.get x0 a);\n    destruct(MemMod.get m a);\n    destruct(MemMod.get x28 a);\n    destruct(MemMod.get x29 a);\n    tryfalse; substs; auto.\n\n  simpljoin1.\n  eapply lmachLib.store_mono; eauto.\n\n  simpljoin1.\n  unfold sat; fold sat; simpl substmo; simpl getmem; simpl getabst.\n  exists x1 x0 M' (OSAbstMod.set x2 curtid (oscurt tid)) x3 (OSAbstMod.set O curtid (oscurt tid)).\n  repeat (split; eauto).\n  eapply join_store; eauto.\n\n  clear - H6 H11.\n  eapply OSAbstMod.join_set_l; eauto.\n  unfolds.\n  unfold OSInv in H11.\n  destruct H11; do 19 destruct H.\n  sep remember (16::nil)%nat in H.\n  simpl_sat H; simpljoin1.\n  pose proof H3 curtid.\n  rewrite OSAbstMod.get_sig_some in H.\n  destruct(OSAbstMod.get x27 curtid); tryfalse.\n  destruct(OSAbstMod.get x2 curtid); tryfalse.\n  eauto.\n\n  eapply OSInv_set_curtid; eauto.\n  \n  lets Hx : starinv_isr_osabst_emp H8; eauto.\n  substs.\n  simpl in H2.\n  do 6 destruct H2. (*simpljoin1 will clear H6 ?*)\n  destruct H2; destruct H5.\n  destruct H7.\n  destruct H9.\n  destruct H12.\n  destruct H12.\n  substs.\n  unfolds in H12.\n  destruct H12.\n  do 4 destruct H2.\n  pose proof H9 abtcblsid.\n  rewrite H2 in H12.\n  destruct(OSAbstMod.get x8 abtcblsid); tryfalse.\n  destruct(OSAbstMod.get O abtcblsid) eqn : eq1; tryfalse.\n  substs.\n  pose proof H6 abtcblsid.\n  rewrite OSAbstMod.emp_sem in H12.\n  rewrite eq1 in H12.\n  destruct(OSAbstMod.get x2 abtcblsid) eqn : eq2; tryfalse.\n  substs.\n  simpl.\n  \n  do 3 eexists; exists x2; do 2 eexists; repeat (split; eauto).\n  apply MemMod.join_emp; eauto.\n  apply OSAbstMod.join_comm; apply OSAbstMod.join_emp; eauto.\n  unfolds.\n  do 4 eexists; repeat (split; eauto).\n  \n  destruct low.\n  unfold I in *; fold I in *; unfold getinv in *.\n  (*    unfold sat; fold sat; simpl substmo; simpl getmem; simpl getabst.\n    assert(exists x0', store (Tptr tp) x0 (b, 0) (Vptr tid) = Some x0').\n   *)\n  false.\n  lets Hx: AHprio_starinv_isr_atoy_inv_false 2%nat H6 H H2 H8.\n  omega.\n  apply Hx; eauto.\n  \n  unfold I in *; fold I in *; unfold getinv in *. \n\n  assert(x2 = OSAbstMod.emp).\n  simpl in H11; simpljoin1.\n  apply starinv_isr_osabst_emp in H8; eauto.\n  substs.\n  simpl in H2; simpljoin1.\n  unfolds in H8; simpljoin1.\n  pose proof H7 abtcblsid.\n  rewrite OSAbstMod.emp_sem in H8.\n  rewrite H2 in H8.\n  destruct (OSAbstMod.get x6 abtcblsid); tryfalse.\n  omega.\nQed.\n*)\n\nLemma GoodSched_GetHPrio : GoodSched GetHPrio.\nProof.\n  unfolds.\n  splits; intros.\n  unfold GetHPrio in *; simpljoin1.\n  do 4 eexists.\n  splits; eauto.\n  eapply join_get_l; eauto.\n\n  unfold GetHPrio in *; simpljoin1.\n  do 2 eexists; splits; eauto.\n  \n  \n  unfold GetHPrio in *; simpljoin1.\n  assert (get O abtcblsid = Some (abstcblist x3)).\n  eapply join_get_l; eauto.\n  rewrite H1 in H8; inverts H8.\n  do 4 eexists; splits; eauto.\nQed.\n\nLemma aemp_isr_elim_dup:\n  forall o O ab P,\n    (o, O , ab) |= aemp_isr_is ** P -> (o, O, ab) |= P.\nProof.\n  introv Hsat.\n  simpl in Hsat.\n  simpljoin.\n  destruct o as [[[[]]]].\n  simpl in *.\n  destruct l.\n  destruct p.\n  assert (m=x0) by join auto.\n  assert (O=x3) by join auto.\n  subst.\n  auto.\nQed.\n\nLemma atoy_abst_elim_dup :\n  forall o O ab P,\n    (o,O,ab) |= atoy_inv ** P ->\n    exists o', (o',O,ab) |= P.\nProof.\n  introv Hsat.\n  unfold atoy_inv in Hsat.\n  simpl in Hsat.\n  simpljoin.\n  destruct o as [[[[]]]].\n  simpl in *.\n  simpljoin.\n  destruct l.\n  destruct p.\n  eexists .\n  assert (O = x3) by join auto.\n  subst.\n  eauto.\nQed.\n\nRequire Import invariant_prop.\n\nLemma mapstoval_false_join_load_vptr :\n  forall l x a m1 m2 m,\n    mapstoval l (Tptr x) false (Vptr a) m1 ->\n    join m1 m2 m ->\n    load (Tptr x) m l = Some (Vptr a).\nProof.\n  intros.\n  unfold mapstoval in H; simpljoin1.\n  unfold load.\n  unfold loadm.\n  destruct l.\n  lets Hx: symbolic_lemmas.ptomvallist_loadbytes H1.\n  lets Hx1: lmachLib.loadbytes_mono H0 Hx.\n  rewrite Hx in Hx1.\n  rewrite encode_val_length in Hx1.\n  rewrite Hx1.\n  rewrite symbolic_lemmas.type_val_mach_encode_val_decode_val; auto.\nQed.\n\n(*\nDefinition GoodI1 :=\n  fun (I : Inv) (sd : ossched) (pa : LocalInv) =>\n    (forall (o : taskst) (O0 O' : osabst) (ab : absop) (OO : osabst),\n        (o, O0, ab) |= starinv_noisr I 0%nat (S INUM) -> join O0 O' OO -> O' = empabst) /\\\n    (forall (o : taskst) (O : osabst) (ab : absop) (tid : addrval),\n        (o, O, ab) |= SWINVt I tid ->\n        exists b tp,\n          get (get_genv (get_smem o)) OSTCBCur = Some (b, Tptr tp) /\\\n          load (Tptr tp) (get_mem (get_smem o)) (b, 0) = Some (Vptr tid) /\\\n          get O curtid = Some (oscurt tid)) /\\\n    (forall (o : taskst) (O : osabst) (ab : absop) (tid : tid) \n            (b : block) (tp : type) (M' : mem) (ct : addrval),\n        (o, O, ab) |= SWINVt I ct ->\n        (o, O, ab) |= AHprio sd tid ** Atrue ->\n        get (get_genv (get_smem o)) OSTCBCur = Some (b, Tptr tp) ->\n        store (Tptr tp) (get_mem (get_smem o)) (b, 0) (Vptr tid) = Some M' ->\n        exists tls,\n          get O abtcblsid = Some (abstcblist tls) /\\\n          (indom tls ct /\\ (substaskst o M', set O curtid (oscurt tid), ab) |= SWINVt I tid \\/\n                           ~ indom tls ct /\\\n           (forall (Mx : mem) (Ox : osabst) (MM : mem) (OO : osabst),\n               satp (substaskst o Mx) Ox (EX lg : list logicvar, pa ct lg) ->\n               join M' Mx MM ->\n               join O Ox OO -> (substaskst o MM, set OO curtid (oscurt tid), ab) |= SWINVt I tid))) /\\\n    GoodSched sd.\n*)\n\nDefinition AOSTCBList'' :=\n  fun (p1 p2 : val) (l1 l2 : list vallist) (rtbl : vallist)\n      (hcurt : addrval) (tcbls : TcbMod.map) (pf : val) =>\n    ((EX (tail1 tail2 : val) (tcbls1 tcbls2 : TcbMod.map),\n      GV OSTCBList @ Tptr os_ucos_h.OS_TCB |-> p1 **\n         tcbdllseg p1 Vnull tail1 p2 l1 **\n         tcbdllseg p2 tail1 tail2 Vnull l2 **\n         [|p1 <> Vnull /\\ p2 = Vptr hcurt|] **\n         [|join tcbls1 tcbls2 tcbls|] **\n         [|TCBList_P p1 l1 rtbl tcbls1|] **\n         [|TCBList_P p2 l2 rtbl tcbls2|] **\n         tcbdllflag p1 (l1 ++ l2) ** [|p2 <> pf|])\n       \\\\//\n       ( EX (tail : val),\n         GV OSTCBList @ Tptr os_ucos_h.OS_TCB |-> p1 **\n            tcblist p1 Vnull tail Vnull (l1 ++ l2) rtbl tcbls **\n            TCB_Not_In p2 p1 (l1 ++ l2) **\n            tcbdllflag p1 (l1 ++ l2) **\n            [|p1 <> Vnull /\\ p2 = Vptr hcurt|] ** [|p2 = pf|])).\n\nLemma AOSTCBList'_AOSTCBList'' :\n  forall a b c d e f g h P,\n    AOSTCBList' a b c d e f g h **P <==>   GV OSTCBCur @ Tptr os_ucos_h.OS_TCB |-r-> b ** AOSTCBList'' a b c d e f g h **P.\nProof.\n  intros.\n  unfold AOSTCBList'; unfold AOSTCBList''.\n  split; intros; sep cancel P. \n  destruct H.\n  sep destruct H.\n  sep cancel 3%nat 1%nat.\n  left.\n  sep auto; eauto.\n  sep destruct H.\n  sep cancel 2%nat 1%nat.\n  right.\n  sep auto; eauto.\n\n  sep lift 2%nat in H.\n  apply disj_split in H.\n  destruct H.\n  left.\n  sep auto; eauto.\n  right.\n  sep auto; eauto.\nQed.\n\nDefinition osinv'' :=\n  EX (eventl osql qblkl : list vallist) (msgql : list EventData)\n     (ectrl : list EventCtr) (ptbl : vallist) (p1 p2 : val)\n     (tcbl1 : list vallist) (tcbcur : vallist) (tcbl2 : list vallist)\n     (rtbl : vallist) (rgrp : val) (ecbls : EcbMod.map) \n     (tcbls : TcbMod.map) (t : int32) (ct vhold : addrval) \n     (ptfree : val) (lfree : list vallist),\n  GV OSTCBCur @ Tptr os_ucos_h.OS_TCB |-r-> p2 **\n                                               AOSTCBList'' p1 p2 tcbl1 (tcbcur :: tcbl2) rtbl ct tcbls ptfree **\n                                               AOSEventFreeList eventl **\n                                               AOSQFreeList osql **\n                                               AOSQFreeBlk qblkl **\n                                               AECBList ectrl msgql ecbls tcbls **\n                                               AOSMapTbl **\n                                               AOSUnMapTbl **\n                                               AOSTCBPrioTbl ptbl rtbl tcbls vhold **\n                                               AOSIntNesting **\n                                               AOSTCBFreeList' ptfree lfree ct tcbls  **\n                                               AOSRdyTblGrp rtbl rgrp **\n                                               AOSTime (Vint32 t) **\n                                               HECBList ecbls **\n                                               HTCBList tcbls **\n                                               HTime t **\n                                               HCurTCB ct **\n                                               AGVars ** [|RH_TCBList_ECBList_P ecbls tcbls ct|] ** A_isr_is_prop.\n\nLemma osinv''_OSInv: forall P,\n    osinv'' ** P <==> OSInv ** P.\nProof.\n  unfold osinv'', OSInv.\n  split.\n  intros.\n  sep cancel P.\n  sep destruct H.\n  rewrite <- AOSTCBList'_AOSTCBList'' in H.\n  sep auto.\n  intros.\n  sep cancel P.\n  sep destruct H.\n  sep eexists.\n  rewrite <- AOSTCBList'_AOSTCBList'' .\n  sep auto.\nQed.\n\nLemma tcblist_indom_ptr_in_tcblist :\n  forall vltcb head rtbl tcbls ct,\n    TCBList_P head vltcb rtbl tcbls ->\n    indom tcbls ct ->\n    ptr_in_tcblist (Vptr ct) head vltcb.\nProof.\n  inductions vltcb; intros.\n  simpl in H; substs.\n  unfolds in H0; destruct H0.\n  rewrite emp_sem in H; tryfalse.\n\n  unfold1 TCBList_P in H; simpljoin1.\n  unfold ptr_in_tcblist.\n  unfold1 ptr_in_tcbdllseg.\n  destruct (beq_val (Vptr ct) (Vptr x)) eqn : eq1; auto.\n  rewrite H1.\n  eapply IHvltcb; eauto.\n  clear - H2 H0 eq1.\n  unfold indom in *; simpljoin1.\n  exists x0.\n  unfolds in H2.\n  assert (ct <> x).\n  intro; substs.\n  unfold beq_val in eq1.\n  unfolds in eq1.\n  destruct x.\n  rewrite beq_pos_Pos_eqb_eq in eq1.\n  rewrite Int.eq_true in eq1.\n  assert (b = b) by auto.\n  apply Pos.eqb_eq in H0.\n  rewrite H0 in eq1.\n  simpl in eq1; tryfalse.\n  clear eq1.\n  hy.\nQed.\n\nLemma tcbdllseg_sll_neq :\n  forall ct lfree pf s tid x x7 x8 x11 H,\n    s\n      |= tcbdllseg (Vptr tid) x11 x ct (x7 :: x8) **\n      assertion.sll pf lfree OS_TCB_flag V_OSTCBNext ** H ->\n    pf <> Vptr tid.\nProof.\n  intros.\n  intro; substs.\n  unfold assertion.sll in H0.\n  destruct lfree.\n  unfold sllseg in H0; fold sllseg in H0; sep split in H0; tryfalse.\n  unfold sllseg in H0; fold sllseg in H0.\n  unfold tcbdllseg in H0.\n  unfold dllseg in H0; fold dllseg in H0.\n  sep normal in H0.\n  sep destruct H0.\n  sep split in H0; simpljoin1.\n  inverts H1; inverts H3.\n  sep lifts (1::3::nil)%nat in H0.\n  eapply os_inv.node_OS_TCB_dup_false; eauto.\nQed.\n\nLemma AOSTCBList'_AOSTCBFreeList_set_curtid_not_indom\n  : forall (p1 p2 : val) (l1 : list vallist) (curtcb : vallist)\n           (l2 : list vallist) (rtbl : vallist) (ct : addrval)\n           (tcbls : TcbMod.map) (lfree : list vallist) \n           (pf : val) (P : asrt) (tid : Modules.tid) e e0 isr st ab M O Mx Ox MM OO,\n    RH_CurTCB tid tcbls ->\n    ~indom tcbls ct ->\n    (e, e0, M, isr, st, O, ab)\n      |= AOSTCBList'' p1 p2 l1 (curtcb :: l2) rtbl ct tcbls pf **\n      AOSTCBFreeList' pf lfree ct tcbls ** P ->\n    join M Mx MM ->\n    join O Ox OO ->\n    (e, e0, Mx, isr, st, Ox, ab) |= EX lg : list logicvar, OSLInv ct lg ->\n                                                           exists l1' curtcb' l2' pf' lfree',\n                                                             (e, e0, MM, isr, st, OO, ab)\n                                                               |= AOSTCBList'' p1 (Vptr tid) l1' (curtcb' :: l2') rtbl tid tcbls\n                                                               pf' ** AOSTCBFreeList' pf' lfree' tid tcbls ** P.\nProof.\n  intros.\n  rename H0 into H_indom.\n  rename H1 into H0.\n  unfold AOSTCBList'' in H0.\n  unfold AOSTCBFreeList' in H0.\n  \n  (*4 cases*)\n  apply disj_split in H0.\n  destruct H0.\n  sep normal in H0; sep destruct H0.\n  sep split in H0.\n  sep lift 6%nat in H0.\n  apply disj_split in H0.\n  destruct H0.\n\n  (*1 false*)\n  simpljoin1.\n  unfold1 TCBList_P in H7.\n  simpljoin1.\n  inverts H7.\n  clear - H5 H10 H_indom.\n  false.\n  apply H_indom.\n  unfold indom.\n  exists x6.\n  unfolds in H10.\n  eapply join_get_r; eauto.\n  eapply join_get_l; eauto.\n  apply get_sig_some.\n\n  (*2 false*)\n  unfold TCBFree_Eq in H0.\n  sep normal in H0; sep destruct H0.\n  sep split in H0.\n  simpljoin1.\n  tryfalse.\n\n  sep normal in H0; sep destruct H0.\n  sep split in H0.\n  sep lift 6%nat in H0.\n  apply disj_split in H0.\n  destruct H0.\n  (*3 false*)\n  unfold TCBFree_Not_Eq in H0.\n  sep normal in H0; sep destruct H0.\n  sep split in H0.\n  simpljoin1.\n  tryfalse.\n\n  (*4*)\n  simpljoin1.\n  unfold TCBFree_Eq in H0.\n  sep normal in H0.\n  sep destruct H0.\n  sep split in H0; simpljoin1.\n  unfolds in H; simpljoin1.\n  sep lift 6%nat in H0.\n  unfold tcblist in H0.\n  sep split in H0.\n  lets Hx: tcb_list_split_by_tcbls H H5 H0.\n  simpljoin1.\n  exists x7 x8 x9.\n  exists (Vptr ct) (x1::x0).\n  unfold AOSTCBList''.\n  apply disj_split.\n  left.\n  sep lift 2%nat.\n  unfold AOSTCBFreeList'.\n  sep normal.\n  exists x12 x x10 x11.\n  sep lift 11%nat.\n  apply disj_split.\n  left.\n  sep split; auto.\n  unfold TCB_Not_In in H10.\n  sep split in H10.\n  sep remember (3::4::5::6::nil)%nat in H10.\n  sep remember (5::nil)%nat in H10.\n  sep lift 2%nat in H10.\n  simpl in H10; simpljoin1.\n  sep remember (1::nil)%nat.\n  simpl_sat_goal.\n  exists (merge x13 Mx) x14 MM.\n  exists (merge x16 Ox) x17 OO.\n  splits; eauto.\n  eapply mem_join_join_merge13_join'; eauto.\n  eapply join_join_merge1; eauto.\n  apply join_comm in H3; eauto.\n  assert (\n      (e, e0, merge x13 Mx, isr, st, merge x16 Ox, ab)\n        |= (EX lg : list logicvar, OSLInv ct lg) ** Astruct ct OS_TCB_flag x1 **\n        PV get_off_addr ct flag_off @ Tint8 |-r-> Vint32 (Int.repr 0) **\n                                                         assertion.sll x2 x0 OS_TCB_flag V_OSTCBNext ** sllfreeflag x2 x0\n    ).\n  sep remember (1::nil)%nat.\n  simpl_sat_goal.\n  exists Mx x13; eexists.\n  exists Ox x16; eexists.\n  splits; eauto.\n  apply join_comm.\n  apply join_merge_disj.\n  clear - H19 H2.\n  eapply mem_join_join_disjoint; eauto.\n  apply join_comm.\n  apply join_merge_disj.\n  eapply osabst_join_join_disjoint; eauto.\n  unfold OSLInv in H17.\n  sep normal in H17.\n  sep destruct H17.\n  sep split in H17; simpljoin1.\n  sep lifts (1::3::nil)%nat in H17.\n  apply sep_combine_lemmas.PV_combine_ro_frm in H17.\n  sep split in H17.\n  unfold TCBFree_Not_Eq.\n  sep split.\n  unfold  assertion.sll in *.\n  unfold1 sllseg.\n  unfold sllfreeflag in *.\n  unfold1 sllsegfreeflag.\n  sep normal.\n  sep eexists.\n  sep split; eauto.\n  inverts H24.\n  unfold node; sep normal.\n  sep eexists.\n  sep split; eauto.\n  assert (x18 = (Vint32 (Int.repr 0))).\n  clear - H10 H20.\n  unfolds in H20; destruct H20.\n  substs.\n  simpl in H10; tryfalse.\n  auto.\n  substs.\n  sep auto.\n\n  clear - H H_indom.\n  intro.\n  inverts H0.\n  unfolds in H_indom.\n  apply H_indom.\n  unfold indom.\n  eauto.\n\n  substs.\n  sep auto.\n  rewrite <- H15.\n  auto.\n\n  clear - H H_indom.\n  intro.\n  inverts H0.\n  unfolds in H_indom.\n  apply H_indom.\n  unfold indom.\n  eauto.\nQed.\n\nLemma AOSTCBList'_AOSTCBFreeList_set_curtid_indom :\n  forall p1 p2 l1 curtcb l2 rtbl ct tcbls lfree pf s P tid,\n    RH_CurTCB tid tcbls ->\n    indom tcbls ct ->\n    s |= AOSTCBList'' p1 p2 l1 (curtcb::l2) rtbl ct tcbls pf **\n      AOSTCBFreeList' pf lfree ct tcbls ** P ->\n    exists l1' curtcb' l2' pf' lfree',\n      s |= AOSTCBList'' p1 (Vptr tid) l1' (curtcb' :: l2') rtbl tid tcbls pf' **\n        AOSTCBFreeList' pf' lfree' tid tcbls ** P.\nProof.\n  intros.\n  rename H0 into H_indom.\n  rename H1 into H0.\n  unfold AOSTCBList'' in H0.\n  unfold AOSTCBFreeList' in H0.\n  \n  (*4 cases*)\n  apply disj_split in H0.\n  destruct H0.\n  sep normal in H0; sep destruct H0.\n  sep split in H0.\n  sep lift 6%nat in H0.\n  apply disj_split in H0.\n  destruct H0.\n\n  (*1*)\n  unfold TCBFree_Not_Eq in H0.\n  sep split in H0; simpljoin1.\n  unfolds in H; simpljoin1.\n  sep lifts (4::5::nil)%nat in H0.\n  pose proof H2 tid.\n  unfold get in H; simpl in H.\n  rewrite H in H7.\n  destruct (TcbMod.get x1 tid) eqn : eq1;\n    destruct (TcbMod.get x2 tid) eqn : eq2;\n    tryfalse.\n  substs.\n  (*tid in x1*)\n  lets Hx : tcb_list_split_by_tcbls eq1 H3 H0.\n  simpljoin1.\n  assert (\n      s |= tcbdllseg p1 Vnull x11 (Vptr tid) x6 **\n        tcbdllseg (Vptr tid) x11 x (Vptr ct) (x7 :: x8) **\n        tcbdllseg (Vptr ct) x x0 Vnull (curtcb :: l2) **\n        assertion.sll pf lfree OS_TCB_flag V_OSTCBNext **\n        sllfreeflag pf lfree **\n        GV OSTCBList @ Tptr os_ucos_h.OS_TCB |-> p1 **\n        tcbdllflag p1 ((x6 ++ x7 :: x8) ++ curtcb :: l2) **\n        GV OSTCBFreeList @ Tptr os_ucos_h.OS_TCB |-> pf ** P  \n    ) as H7_bak by auto.\n  sep lifts (2::3::nil)%nat in H7.\n  assert (V_OSTCBNext (last (x7 :: x8) nil) = Some (Vptr ct)) as H_last.\n  eapply tcbdllseg_last_nextptr in H7; auto.\n  eapply tcbdllseg_compose in H7.\n  \n  lets Hx: TCBList_P_combine_copy H9 H4.\n  instantiate (1:=merge x10 x2).\n  clear - H2 H10.\n  eapply TcbMod.join_merge_disj.\n  apply join_comm in H10.\n  eapply TcbMod.join_join_disj_l; eauto.\n  assert (x7 :: x8 <> nil) by auto.\n  apply Hx in H11; auto; clear Hx.\n  replace ((x7 :: x8) ++ curtcb :: l2) with (x7 :: x8 ++ curtcb :: l2) in H7, H11.\n  exists x6 x7 (x8 ++ curtcb :: l2) pf lfree.\n  unfold AOSTCBList''.\n  apply disj_split.\n  left.\n  sep normal.\n  do 4 eexists.\n  sep split; eauto.\n  sep cancel 5%nat 1%nat.\n  sep cancel 2%nat 1%nat.\n  sep cancel 1%nat 1%nat.\n  replace ((x6 ++ x7 :: x8) ++ curtcb :: l2) with (x6 ++ x7 :: x8 ++ curtcb :: l2) in H7.\n  sep cancel 3%nat 1%nat.\n  unfold AOSTCBFreeList'.\n  sep auto.\n  left.\n  unfold TCBFree_Not_Eq.\n  sep auto.\n  clear - H7_bak.\n  sep remember (2::4::nil)%nat in H7_bak; clear HeqH.\n  clears.\n  eapply tcbdllseg_sll_neq; eauto.\n  \n  rewrite <- app_assoc.\n  auto.\n  \n  clear - H7_bak.\n  sep remember (2::4::nil)%nat in H7_bak; clear HeqH.\n  clears.\n  assert (pf <> Vptr tid).\n  eapply tcbdllseg_sll_neq; eauto.\n  auto.\n  clear - H2 H10.\n  eapply join_merge23_join; eauto.\n  rewrite app_comm_cons; auto.\n\n  (*tid in x2*)\n  substs.\n  sep lift 2%nat in H0.\n  lets Hx : tcb_list_split_by_tcbls eq2 H4 H0.\n  simpljoin1.\n  assert (\n      s\n        |= tcbdllseg (Vptr ct) x x11 (Vptr tid) x6 **\n        tcbdllseg (Vptr tid) x11 x0 Vnull (x7 :: x8) **\n        tcbdllseg p1 Vnull x (Vptr ct) l1 **\n        assertion.sll pf lfree OS_TCB_flag V_OSTCBNext **\n        sllfreeflag pf lfree **\n        GV OSTCBList @ Tptr os_ucos_h.OS_TCB |-> p1 **\n        tcbdllflag p1 (l1 ++ curtcb :: l2) **\n        GV OSTCBFreeList @ Tptr os_ucos_h.OS_TCB |-> pf ** P\n    ) as H7_bak by auto.\n  exists (l1 ++ x6) x7 x8 pf lfree.\n  unfold AOSTCBList''.\n  apply disj_split.\n  left.\n  sep normal.\n  exists x11 x0 (merge x1 x9) x10.\n  sep split; eauto.\n  sep cancel 6%nat 1%nat.\n  sep cancel 2%nat 2%nat.\n  rewrite H11 in H7_bak.\n  replace (l1 ++ x6 ++ x7 :: x8) with ((l1 ++ x6) ++ x7 :: x8) in H7_bak.\n  sep cancel 5%nat 2%nat.\n  unfold AOSTCBFreeList'.\n  sep auto.\n  sep lift 2%nat.\n  apply disj_split.\n  left.\n  unfold TCBFree_Not_Eq.\n  sep lifts (2::1::nil)%nat in H7_bak.\n  eapply tcbdllseg_compose in H7_bak.\n  sep auto.\n\n  clear - H7.\n  sep lifts (2::4::nil)%nat in H7.\n  eapply tcbdllseg_sll_neq; eauto.\n  \n  rewrite <- app_assoc.\n  auto.\n\n  assert (pf <> Vptr tid).\n  sep lifts (2::4::nil)%nat in H7.\n  eapply tcbdllseg_sll_neq; eauto.\n  auto.\n\n  clear - H1 H3 H8 H10 H2 H7.\n  destruct l1.\n  rewrite app_nil_l.\n  simpl in H3; simpljoin1.\n  sep remember (3::nil)%nat in H7.\n  destruct_s s.\n  simpl in H7; simpljoin1.\n  rewrite jl_merge_emp'.\n  auto.\n  eapply TCBList_P_combine_copy; eauto.\n  clear - H2 H10.\n  eapply TcbMod.join_merge_disj.\n  apply join_comm in H2.\n  apply TcbMod.disj_comm.\n  eapply TcbMod.join_join_disj_l; eauto.\n  sep lift 3%nat in H7.\n  eapply tcbdllseg_last_nextptr; eauto.\n\n  clear - H2 H10.\n  eapply join_join_join_merge; eauto.\n\n  (*2 false*)\n  unfold TCBFree_Eq in H0.\n  sep normal in H0; sep destruct H0.\n  sep split in H0.\n  simpljoin1.\n  tryfalse.\n\n  sep normal in H0; sep destruct H0.\n  sep split in H0.\n  sep lift 6%nat in H0.\n  apply disj_split in H0.\n  destruct H0.\n  (*3 false*)\n  unfold TCBFree_Not_Eq in H0.\n  sep normal in H0; sep destruct H0.\n  sep split in H0.\n  simpljoin1.\n  tryfalse.\n\n  (*4*)\n  simpljoin1.\n\n  unfold TCB_Not_In in H0.\n  unfold tcblist in H0.\n  sep split in H0.\n  lets Hx: tcblist_indom_ptr_in_tcblist H2 H_indom.\n  simpljoin1.\n  false; apply H3; auto.\nQed.\n\nLemma OSInv_set_curtid1 :\n  forall e e0 M M' isr st O ab b tp tp0 tid ct P,\n    EnvMod.get e OSTCBCur = Some (b, Tptr tp) ->\n    store (Tptr tp) M (b, 0) (Vptr tid) = Some M' ->\n    (e, e0, M, isr, st, O, ab) |= AHprio GetHPrio tid ** Atrue ->\n    (e, e0, M, isr, st, O, ab) |= OSInv ** GV OSTCBCur @ Tptr tp0 |-r-> Vptr ct ** P ->\n                                                                    exists tls,\n                                                                      get O abtcblsid = Some (abstcblist tls) /\\\n                                                                      (indom tls ct /\\\n                                                                       (e, e0, M', isr, st, set O curtid (oscurt tid), ab)\n                                                                         |= OSInv ** GV OSTCBCur @ Tptr tp0 |-r-> Vptr tid ** P \\/\n                                                                                                                  ~ indom tls ct /\\\n                                                                                                                  (forall (Mx : mem) (Ox : osabst) (MM : mem) (OO : osabst),\n                                                                                                                      satp (e, e0, Mx, isr, st) Ox (EX lg, OSLInv ct lg) ->\n                                                                                                                      join M' Mx MM ->\n                                                                                                                      join O Ox OO ->\n                                                                                                                      (e, e0, MM, isr, st, set OO curtid (oscurt tid), ab)\n                                                                                                                        |=  OSInv ** GV OSTCBCur @ Tptr tp0 |-r-> Vptr tid ** P)).\nProof.\n  intros.\n  rewrite <- osinv''_OSInv in H2.\n  unfold osinv'' in H2.\n  sep normal in H2.\n  sep destruct H2.\n  assert (get O abtcblsid = Some (abstcblist x13)).\n  sep remember (15::nil)%nat in H2.\n  simpl in H2; simpljoin1.\n  eapply join_get_l; eauto.\n  eexists.\n  split; eauto.\n  \n\n  assert (os_ucos_h.OS_TCB = tp0).\n  sep remember (1::21::nil)%nat in H2.\n  simpl in H2; simpljoin1.\n  rewrite H27 in H18; inverts H18.\n  auto.\n  subst tp0.\n  \n  assert (x6 = Vptr x15).\n  sep remember (2::nil)%nat in H2.\n  simpl in H2; simpljoin1.\n  destruct H8; simpljoin1; auto.\n  substs.\n  sep remember (1::21::nil)%nat in H2.\n  eapply sep_combine_lemmas.GV_combine_ro_frm in H2.\n  sep split in H2.\n  simpl in H2; simpljoin1.\n  assert (x15 = ct).\n  clear - H5.\n  simpl in H5.\n  destruct x15; destruct ct.\n  inverts H5; auto.\n  substs.\n  \n  assert (indom x13 ct \\/ ~ indom x13 ct).\n  unfold indom.\n  destruct (get x13 ct) eqn : eq1; clear - eq1.\n  left; eauto.\n  right.\n  intro; destruct H; tryfalse.\n  destruct H2.\n  (*indom tcbls ct*)\n  left.\n  split; auto.\n  rewrite <- osinv''_OSInv.\n  unfold osinv''.\n  sep normal.\n  unfolds in H14; simpl in H14.\n  rewrite H in H14; inverts H14.\n  lets Hx: lmachLib.store_mapstoval_frame H15 H6 H0.\n  simpljoin1.\n\n  sep lifts (1::10::nil)%nat in H10.\n  lets Hx: AOSTCBList'_AOSTCBFreeList_set_curtid_indom H10; auto.\n  unfolds.\n  instantiate (TEMP11 := tid).\n  clear - H1 H3.\n  simpl in H1; simpljoin1.\n  unfolds in H4; simpljoin1.\n  assert (get O abtcblsid = Some (abstcblist x)).\n  eapply join_get_l; eauto.\n  rewrite H3 in H5.\n  inverts H5.\n  eauto.\n  simpljoin1.\n  sep eexists.\n\n  sep lifts (1::21::nil)%nat.\n  eapply sep_combine_lemmas.GV_combine_ro'_frm; eauto.\n  sep remember (1::nil)%nat.\n  simpl.\n  exists x15 x19.\n  do 4 eexists.\n  splits; eauto.\n  eapply join_emp; eauto.\n  do 7 eexists.\n  splits; eauto.\n  eapply join_emp; eauto.\n  eapply join_emp; eauto.\n  eexists.\n  unfold emposabst; splits; eauto.\n  unfolds.\n  eexists; splits; eauto.\n  unfolds in H15; simpljoin1.\n  unfold store in H4.\n  lets Hx: lmachLib.storebytes_ptomvallist_eqlen_infer p H4.\n  simpl.\n  destruct tid; destruct ct; simpl; auto.\n  auto.\n  unfolds; auto.\n  substs.\n  sep remember (16::nil)%nat in H5.\n  simpl in H5; simpljoin1.\n  sep remember (16::nil)%nat.\n  simpl.\n  do 6 eexists.\n  splits; eauto.\n  eapply join_emp; auto.\n  eapply join_sig_set; eauto.\n  substs.\n  sep auto.\n\n  (*not indom 13 ct*)\n  right.\n  split; auto.\n  intros.\n\n  pose proof H4 ab.\n  rewrite <- osinv''_OSInv.\n  unfold osinv''.\n  sep normal.\n  unfolds in H14; simpl in H14.\n  rewrite H in H14; inverts H14.\n  lets Hx: lmachLib.store_mapstoval_frame H15 H6 H0.\n  simpljoin1.\n\n  sep remember (1::nil)%nat in H10.\n  assert ((e, e0, M', isr, st, O, ab)\n            |=  GV OSTCBCur @ Tptr os_ucos_h.OS_TCB |-> (Vptr tid) ** AOSTCBList'' x5 (Vptr ct) x7 (x8 :: x9) x10 ct x13 x17 ** H5).\n  substs.\n  sep remember (1::nil)%nat.\n  simpl.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  do 7 eexists.\n  splits; eauto.\n  eapply join_emp; eauto.\n  apply join_emp; eauto.\n  eexists.\n  splits; eauto.\n  unfolds; auto.\n  unfolds.\n  eexists; splits; eauto.\n  unfolds in H15; simpljoin1.\n  eapply lmachLib.storebytes_ptomvallist_eqlen_infer; eauto.\n  simpl; destruct tid, ct; auto.\n  unfolds; auto.\n  substs.\n  sep lifts (2::11::nil)%nat in H13.\n  lets Hx: AOSTCBList'_AOSTCBFreeList_set_curtid_not_indom H13 H7 H8 H9.\n  unfolds.\n  instantiate (TEMP10 := tid).\n  clear - H1 H3.\n  simpl in H1; simpljoin1.\n  unfolds in H4; simpljoin1.\n  assert (get O abtcblsid = Some (abstcblist x)).\n  eapply join_get_l; eauto.\n  rewrite H3 in H5.\n  inverts H5.\n  eauto.\n  auto.\n  simpljoin1.\n  sep eexists.\n  sep lifts (1::21::nil)%nat.\n  eapply sep_combine_lemmas.GV_combine_ro'_frm; eauto.\n  sep remember (17::nil)%nat in H5.\n  simpl in H5; simpljoin1.\n  sep remember (17::nil)%nat.\n  simpl.\n  exists empmem MM.\n  do 4 eexists.\n  splits; eauto.\n  eapply join_emp; auto.\n  eapply join_sig_set; eauto.\n  substs.\n  sep auto.\nQed.\n\n\nLemma AHprio_starinv_isr_atoy_inv_false :\n  forall e e0 M M1 M2 isr st O o1 o2 ab n i tid,\n    join o1 o2 O -> (i > 0)%nat -> (forall i : hid, isr i = false) ->\n    (e, e0, M, isr, st, O, ab) |= AHprio GetHPrio tid ** Atrue ->\n    (e, e0, M1, isr, st, o2, ab) |= starinv_isr I i n ->\n    (e, e0, M2, isr, st, o1, ab) |= atoy_inv ->\n    False.\nProof.\n  intros.\n  apply starinv_isr_osabst_emp in H3; auto.\n  apply atoy_inv_osabst_emp in H4; auto.\n  substs.\n  simpl in H2; simpljoin1.\n  unfolds in H6; simpljoin1.\n  pose proof H5 abtcblsid.\n  pose proof H abtcblsid.\n  rewrite OSAbstMod.emp_sem in H8.\n  destruct (OSAbstMod.get O abtcblsid) eqn : eq1; tryfalse.\n  destruct (OSAbstMod.get x2 abtcblsid) eqn: eq2; tryfalse.\n  destruct (OSAbstMod.get x3 abtcblsid); tryfalse.\n  destruct (OSAbstMod.get x3 abtcblsid) eqn : eq3; tryfalse.\n  unfold get in H2; simpl in H2; rewrite H2 in eq2; tryfalse.\nQed.\n\nLemma starinv_isr_set_highest_tid :\n  forall n low i0 e e0 m c O ab tid b tp tp' ct M' x11 i,\n    (forall i : hid, x11 i = false) ->\n    EnvMod.get e OSTCBCur = Some (b, Tptr tp) ->\n    store (Tptr tp) m (b, 0) (Vptr tid) = Some M' ->\n    (e, e0, m, x11, (i, i0, c), O, ab) |= AHprio GetHPrio tid ** Atrue -> \n    (e, e0, m, x11, (i, i0, c), O, ab) |= GV OSTCBCur @ Tptr tp' |-r-> Vptr ct ** starinv_isr I low n ->\n                                                                   (exists tls,\n                                                                       get O abtcblsid = Some (abstcblist tls) /\\\n                                                                       (indom tls ct /\\\n                                                                        (e, e0, M', x11, (i, i0, c), set O curtid (oscurt tid), ab)\n                                                                          |= starinv_isr I low n ** (EX tp0 : type, GV OSTCBCur @ Tptr tp0 |-r-> Vptr tid) \\/\n                                                                        ~ indom tls ct /\\\n                                                                        (forall (Mx : mem) (Ox : osabst) (MM : mem) (OO : osabst),\n                                                                            satp (e, e0, Mx, x11, (i, i0, c)) Ox (EX lg, OSLInv ct lg) ->\n                                                                            join M' Mx MM ->\n                                                                            join O Ox OO ->\n                                                                            (e, e0, MM, x11, (i, i0, c), set OO curtid (oscurt tid), ab)\n                                                                              |= starinv_isr I low n ** (EX tp0 : type, GV OSTCBCur @ Tptr tp0 |-r-> Vptr tid)))).\nProof.\n  inductions n; intros.\n  unfold starinv_isr in *.\n  destruct low.\n  sep normal in H3.\n  destruct H3.\n  apply disj_split in H3.\n  destruct H3.\n  simpl in H3; simpljoin1.\n  tryfalse. \n  sep remember (1::nil)%nat in H3.\n  simpl in H3; simpljoin1.\n\n  unfold I in *; unfold getinv in *.\n  \n\n  assert ((e, e0, m, x, (i, i0, c), O, ab)\n            |= OSInv ** GV OSTCBCur @ Tptr tp' |-r-> Vptr ct ** Aemp).\n  sep auto.\n  lets Hx: OSInv_set_curtid1 H0 H1 H2 H3.\n  simpljoin1.\n  eexists.\n  splits; eauto.\n  destruct H5; simpljoin1.\n  left.\n  split; auto.\n  sep normal.\n  sep eexists.\n  sep lift 2%nat.\n  apply disj_split.\n  right.\n  sep normal.\n  sep remember (1::nil)%nat.\n  simpl.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep auto.\n  right.\n  split; auto.\n  intros.\n  lets Hx: H6 H7 H10 H11.\n  sep normal.\n  sep eexists.\n  sep lift 2%nat.\n  apply disj_split.\n  right.\n  sep normal.\n  sep remember (1::nil)%nat.\n  simpl.\n  substs.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; eauto.\n  sep auto.\n\n  destruct low.\n  simpl getinv in *.\n  sep normal in H3.\n  destruct H3.\n  apply disj_split in H3.\n  destruct H3.\n  simpl in H3; simpljoin1; tryfalse.\n  sep remember (1::nil)%nat in H3.\n  simpl in H3; simpljoin1.\n  unfold atoy_inv in H9.\n  unfold A_isr_is_prop in H9.\n  unfold atoy_inv' in H9.\n  simpl in H9; simpljoin1.\n  simpl in H2; simpljoin1.\n  unfolds in H7; simpljoin1.\n  apply map_join_pos in H6; simpljoin1.\n  rewrite emp_sem in H2; tryfalse.\n  \n  simpl getinv in *.\n  sep normal in H3.\n  destruct H3.\n  apply disj_split in H3.\n  destruct H3.\n  simpl in H3; simpljoin1; tryfalse.\n  sep remember (1::nil)%nat in H3.\n  simpl in H3; simpljoin1.\n  unfold aemp_isr_is in H9.\n  unfold A_isr_is_prop in H9.\n  simpl in H9; simpljoin1.\n  simpl in H2; simpljoin1.\n  unfolds in H6; simpljoin1.\n  apply map_join_pos in H5; simpljoin1.\n  rewrite emp_sem in H2; tryfalse.\n\n  (*ind case*)\n  unfold starinv_isr in *; fold starinv_isr in *.\n  sep normal in H3; destruct H3.\n  (*  sep normal; exists x. *)\n  apply disj_split in H3.\n  destruct H3.\n  simpl in H3; simpljoin1; tryfalse.\n  sep remember (1::nil)%nat in H3.\n  simpl in H3; simpljoin1.\n\n  destruct low.\n  unfold I in *; fold I in *; unfold getinv in *.\n  eapply OSInv_set_curtid1 in H9; eauto.\n  simpljoin1.\n  destruct H4; simpljoin1.\n  eexists; splits; eauto.\n  left.\n  split; auto.\n  sep normal.\n  sep eexists.\n  sep lift 2%nat.\n  apply disj_split.\n  right.\n  sep normal.\n  sep remember (1::nil)%nat.\n  simpl.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; eauto.\n  apply join_emp; eauto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep auto.\n\n  eexists.\n  splits; eauto.\n  right.\n  split; eauto.\n  intros.\n  lets Hx: H5 H6 H7 H9.\n  sep normal.\n  sep eexists.\n  sep lift 2%nat.\n  apply disj_split.\n  right.\n  sep normal.\n  sep remember (1::nil)%nat.\n  simpl.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; eauto.\n  apply join_emp; eauto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep auto.\n  \n  destruct low.\n  unfold I in *; fold I in *; unfold getinv in *.\n  false.\n\n\n  simpl_sat H9; simpljoin1.\n  simpl in H13; simpljoin1.\n  eapply AHprio_starinv_isr_atoy_inv_false with (i:=2%nat); eauto.\n\n  sep remember (1::nil)%nat in H9.\n  simpl_sat H9; simpljoin1.\n  simpl in H9; simpljoin1.\n  lets Hx: IHn H H0 H1 H2 H10.\n  simpljoin1.\n  eexists; splits; eauto.\n  destruct H4; simpljoin1.\n  left.\n  split; auto.\n  sep normal in H5; destruct H5.\n  sep normal.\n  sep eexists.\n  sep lift 2%nat.\n  apply disj_split.\n  right.\n  sep normal.\n  sep remember (1::nil)%nat.\n  simpl.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; eauto.\n  apply join_emp; eauto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  simpl getinv.\n  unfold aemp_isr_is.\n  unfold A_isr_is_prop.\n  sep auto.\n\n  right.\n  split; auto.\n  intros.\n  lets Hx: H5 H6 H7 H9.\n  sep normal in Hx; destruct Hx.\n  sep normal.\n  sep eexists.\n  sep lift 2%nat.\n  apply disj_split.\n  right.\n  sep normal.\n  sep remember (1::nil)%nat.\n  simpl.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; eauto.\n  apply join_emp; eauto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  simpl getinv.\n  unfold aemp_isr_is.\n  unfold A_isr_is_prop.\n  sep auto.\nQed.\n\n\nLemma GoodI_I :\n  GoodI I GetHPrio OSLInv.\nProof.\n  intros.\n  unfold GoodI.\n  splits.\n-\n  unfolds INUM.\n  intros.\n  unfold starinv_noisr in H.\n  assert (getinv (I 0%nat) = OSInv) by auto.\n  rewrite H1 in H.\n  assert (getinv (I 1%nat) = atoy_inv) by auto. \n  assert (getinv (I 2%nat) = aemp_isr_is ) by auto.\n  assert (getinv (I 3%nat) = aemp_isr_is) by auto.\n  rewrite H3 in H.  \n  rewrite H2 in H.\n  rewrite H4 in H.\n  sep lift 4%nat in H.\n  apply aemp_isr_elim_dup in H.\n  sep lift 3%nat in H.\n  apply aemp_isr_elim_dup in H.\n  sep lift 2%nat in H.\n  apply atoy_abst_elim_dup in H.\n  simpljoin1.\n  eapply OSInv_prop; eauto.\n  eapply my_join_disj; eauto.\n\n-\n  introv Hsw.\n  unfold SWINVt in Hsw.\n  destruct o as [[[[]]]].\n  simpl_sat Hsw; simpljoin1.\n  simpl in H4; simpljoin1.\n  exists x11 x5.\n  splits; eauto.\n  simpl get_mem.\n  apply join_comm in H0.\n  eapply mapstoval_false_join_load_vptr; eauto.\n  \n  unfold SWINV in H3.\n  simpl_sat H3; simpljoin1.\n  unfold getie in *; unfold gettaskst in *.\n  destruct l; destruct p.\n  simpl in H12.\n  simpl in H18; simpljoin1.\n  lets Hres : osq_inv_in H2 H12.\n  sep destruct Hres.\n\n  simpl_sat Hres; simpljoin1.\n  simpl in H15; simpljoin1.\n  unfold AOSTCBList' in H5.\n  destruct H5.\n  do 4 destruct H.\n  sep split in H.\n  simpljoin1.\n  clear H3 H5 H8 H9 H10; clears.\n  sep remember (3::nil)%nat in H.\n  simpl in H; simpljoin1.\n  rewrite H6 in H17; inverts H17.\n  assert (Vptr tid = Vptr x8 /\\ x0 = x2).\n  eapply mapstoval_false_rule_type_val_match_eq with (M := m) (t := Tptr os_ucos_h.OS_TCB).\n  simpl; auto.\n  simpl; auto.\n  eauto.\n  eauto. \n  eapply join_sub_r; eauto.\n\n  apply join_sub_l in H5; apply sub_trans with (m2 := x13); auto.\n  apply join_sub_l in H1; apply sub_trans with (m2 := x); auto.\n  apply join_sub_l in H0; apply sub_trans with (m2 := m); auto.\n  unfold sub.\n  eexists emp.\n  apply join_comm.\n  apply join_emp; auto.\n\n  destruct H; substs.\n  inverts H.\n  eapply join_get_r; eauto.\n  eapply join_get_l; eauto.\n\n  destruct H.\n  sep split in H.\n  simpljoin1.\n  sep remember (2::nil)%nat in H.\n  simpl in H; simpljoin1.\n  rewrite H6 in H18; inverts H18.\n  assert (Vptr tid = Vptr x8 /\\ x0 = x2).\n  eapply mapstoval_false_rule_type_val_match_eq with (M := m) (t := Tptr os_ucos_h.OS_TCB).\n  simpl; auto.\n  simpl; auto.\n  eauto.\n  eauto. \n  eapply join_sub_r; eauto.\n\n  apply join_sub_l in H8; apply sub_trans with (m2 := x13); auto.\n  apply join_sub_l in H1; apply sub_trans with (m2 := x); auto.\n  apply join_sub_l in H0; apply sub_trans with (m2 := m); auto.\n  unfold sub.\n  eexists emp.\n  apply join_comm.\n  apply join_emp; auto.\n\n  destruct H; substs.\n  inverts H.\n  eapply join_get_r; eauto.\n  eapply join_get_l; eauto.\n\n-\n  introv Hsw Hpr Hget Hs.\n  destruct o as [[[[]]]].\n  simpl in Hget.\n  unfold get_smem in Hs; unfold get_mem in Hs.\n  unfold SWINVt in *.\n  unfold substaskst.\n  unfold SWINV in *.\n  sep normal in Hsw.\n  destruct Hsw; destruct H.\n\n  sep remember (2::4::5::nil)%nat in H.\n  simpl in H; simpljoin1.\n  destruct l; destruct p.\n  substs.\n\n  unfold invlth_isr in *.\n  rewrite Nat.sub_0_r in *.\n  lets Hx: starinv_isr_set_highest_tid H18 Hget Hs Hpr H15.\n  simpljoin1.\n  eexists.\n  splits;eauto.\n  destruct H0; simpljoin1.\n  left.\n  split; auto.\n  sep normal in H1; destruct H1.\n  sep remember (1::nil)%nat.\n  simpl.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  eexists.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep remember (1::nil)%nat.\n  simpl.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep normal.\n  sep eexists.\n  rewrite Nat.sub_0_r.\n  sep remember (2::nil)%nat.\n  simpl.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep auto.\n  rewrite Nat.add_0_r.\n  auto.\n\n  right.\n  split; auto.\n  intros.\n  lets Hx: H1 H2 H3 H4.\n  sep normal in Hx.\n  destruct Hx.\n  sep remember (1::nil)%nat.\n  simpl.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  eexists.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep remember (1::nil)%nat.\n  simpl.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep normal.\n  pose proof H2 ab.\n  destruct H6.\n  unfold OSLInv in H6.\n  destruct H6.\n  simpl in H6; simpljoin1.\n  sep eexists.\n  rewrite Nat.sub_0_r.\n  sep remember (2::nil)%nat.\n  simpl.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  rewrite Nat.add_0_r.\n  sep auto.\n\n- apply GoodSched_GetHPrio.\nQed.\n\n(*GoodI_I backup\n\nLemma GoodI_I :\n  GoodI I GetHPrio OSLInv.\nProof.\n  intros.\n  unfold GoodI.\n  splits.\n  \n-\n  unfolds INUM.\n  intros.\n  unfold starinv_noisr in H.\n  assert (getinv (I 0%nat) = OSInv) by auto.\n  rewrite H1 in H.\n  assert (getinv (I 1%nat) = atoy_inv) by auto. \n  assert (getinv (I 2%nat) = aemp_isr_is ) by auto.\n  assert (getinv (I 3%nat) = aemp_isr_is) by auto.\n  rewrite H3 in H.  \n  rewrite H2 in H.\n  rewrite H4 in H.\n  sep lift 4%nat in H.\n  apply aemp_isr_elim_dup in H.\n  sep lift 3%nat in H.\n  apply aemp_isr_elim_dup in H.\n  sep lift 2%nat in H.\n  apply atoy_abst_elim_dup in H.\n  simpljoin1.\n  eapply OSInv_prop; eauto.\n  eapply my_join_disj; eauto.\n\n-\n  introv Hsw.\n  unfold SWINVt in Hsw.\n  destruct o as [[[[]]]].\n  simpl_sat Hsw; simpljoin1.\n  simpl in H4; simpljoin1.\n  exists x11 x5.\n  splits; eauto.\n  simpl get_mem.\n  apply join_comm in H0.\n  eapply mapstoval_false_join_load_vptr; eauto.\n  \n  unfold SWINV in H3.\n  simpl_sat H3; simpljoin1.\n  unfold getie in *; unfold gettaskst in *.\n  destruct l; destruct p.\n  simpl in H12.\n  simpl in H18; simpljoin1.\n  lets Hres : osq_inv_in H2 H12.\n  sep destruct Hres.\n\n  simpl_sat Hres; simpljoin1.\n  simpl in H15; simpljoin1.\n  unfold AOSTCBList' in H5.\n  destruct H5.\n  do 4 destruct H.\n  sep split in H.\n  simpljoin1.\n  clear H3 H5 H8 H9 H10; clears.\n  sep remember (3::nil)%nat in H.\n  simpl in H; simpljoin1.\n  rewrite H6 in H17; inverts H17.\n  assert (Vptr tid = Vptr x8 /\\ x0 = x2).\n  eapply mapstoval_false_rule_type_val_match_eq with (M := m) (t := Tptr os_ucos_h.OS_TCB).\n  simpl; auto.\n  simpl; auto.\n  eauto.\n  eauto. \n  eapply join_sub_r; eauto.\n\n  apply join_sub_l in H5; apply sub_trans with (m2 := x13); auto.\n  apply join_sub_l in H1; apply sub_trans with (m2 := x); auto.\n  apply join_sub_l in H0; apply sub_trans with (m2 := m); auto.\n  unfold sub.\n  eexists emp.\n  apply join_comm.\n  apply join_emp; auto.\n\n  destruct H; substs.\n  inverts H.\n  eapply join_get_r; eauto.\n  eapply join_get_l; eauto.\n\n  destruct H.\n  sep split in H.\n  simpljoin1.\n  sep remember (2::nil)%nat in H.\n  simpl in H; simpljoin1.\n  rewrite H6 in H18; inverts H18.\n  assert (Vptr tid = Vptr x8 /\\ x0 = x2).\n  eapply mapstoval_false_rule_type_val_match_eq with (M := m) (t := Tptr os_ucos_h.OS_TCB).\n  simpl; auto.\n  simpl; auto.\n  eauto.\n  eauto. \n  eapply join_sub_r; eauto.\n\n  apply join_sub_l in H8; apply sub_trans with (m2 := x13); auto.\n  apply join_sub_l in H1; apply sub_trans with (m2 := x); auto.\n  apply join_sub_l in H0; apply sub_trans with (m2 := m); auto.\n  unfold sub.\n  eexists emp.\n  apply join_comm.\n  apply join_emp; auto.\n\n  destruct H; substs.\n  inverts H.\n  eapply join_get_r; eauto.\n  eapply join_get_l; eauto.\n\n-\n  introv Hsw Hpr Hget Hs.\n  destruct o as [[[[]]]].\n  simpl in Hget.\n  unfold get_smem in Hs; unfold get_mem in Hs.\n  unfold SWINVt in *.\n  unfold substaskst.\n  unfold SWINV in *.\n  sep normal in Hsw.\n  destruct Hsw; destruct H.\n\n  sep remember (2::4::5::nil)%nat in H.\n  simpl in H; simpljoin1.\n  destruct l; destruct p.\n  substs.\n(*  \n  sep normal.\n  exists x x0.\n  sep remember (2::4::5::nil)%nat in H.\n  sep remember (2::4::5::nil)%nat.\n  simpl in H.\n  simpl; simpljoin1.\n  do 6 eexists.\n  splits; eauto.\n  eapply join_emp; auto.\n  eapply join_emp; auto.\n  unfold emposabst; splits; auto.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  eexists.\n  unfold emposabst.\n  splits; eauto.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; auto.\n  destruct l, p.\n*)\n\n  Definition AOSTCBList'' :=\n    fun (p1 p2 : val) (l1 l2 : list vallist) (rtbl : vallist)\n        (hcurt : addrval) (tcbls : TcbMod.map) (pf : val) =>\n      ((EX (tail1 tail2 : val) (tcbls1 tcbls2 : TcbMod.map),\n        GV OSTCBList @ Tptr os_ucos_h.OS_TCB |-> p1 **\n           tcbdllseg p1 Vnull tail1 p2 l1 **\n           tcbdllseg p2 tail1 tail2 Vnull l2 **\n           [|p1 <> Vnull /\\ p2 = Vptr hcurt|] **\n           [|join tcbls1 tcbls2 tcbls|] **\n           [|TCBList_P p1 l1 rtbl tcbls1|] **\n           [|TCBList_P p2 l2 rtbl tcbls2|] **\n           tcbdllflag p1 (l1 ++ l2) ** [|p2 <> pf|])\n         \\\\//\n         ( EX (tail : val),\n           GV OSTCBList @ Tptr os_ucos_h.OS_TCB |-> p1 **\n              tcblist p1 Vnull tail Vnull (l1 ++ l2) rtbl tcbls **\n              TCB_Not_In p2 p1 (l1 ++ l2) **\n              tcbdllflag p1 (l1 ++ l2) **\n              [|p1 <> Vnull /\\ p2 = Vptr hcurt|] ** [|p2 = pf|])).\n  \n  Lemma AOSTCBList'_AOSTCBList'' :\n    forall a b c d e f g h P,\n      AOSTCBList' a b c d e f g h **P <==>   GV OSTCBCur @ Tptr os_ucos_h.OS_TCB |-r-> b ** AOSTCBList'' a b c d e f g h **P.\n  Proof.\n    intros.\n    unfold AOSTCBList'; unfold AOSTCBList''.\n    split; intros; sep cancel P. \n    destruct H.\n    sep destruct H.\n    sep cancel 3%nat 1%nat.\n    left.\n    sep auto; eauto.\n    sep destruct H.\n    sep cancel 2%nat 1%nat.\n    right.\n    sep auto; eauto.\n\n    sep lift 2%nat in H.\n    apply disj_split in H.\n    destruct H.\n    left.\n    sep auto; eauto.\n    right.\n    sep auto; eauto.\n  Qed.\n  \n  Definition osinv'' :=\n    EX (eventl osql qblkl : list vallist) (msgql : list EventData)\n       (ectrl : list EventCtr) (ptbl : vallist) (p1 p2 : val)\n       (tcbl1 : list vallist) (tcbcur : vallist) (tcbl2 : list vallist)\n       (rtbl : vallist) (rgrp : val) (ecbls : EcbMod.map) \n       (tcbls : TcbMod.map) (t : int32) (ct vhold : addrval) \n       (ptfree : val) (lfree : list vallist),\n    GV OSTCBCur @ Tptr os_ucos_h.OS_TCB |-r-> p2 **\n    AOSTCBList'' p1 p2 tcbl1 (tcbcur :: tcbl2) rtbl ct tcbls ptfree **\n    AOSEventFreeList eventl **\n    AOSQFreeList osql **\n    AOSQFreeBlk qblkl **\n    AECBList ectrl msgql ecbls tcbls **\n    AOSMapTbl **\n    AOSUnMapTbl **\n    AOSTCBPrioTbl ptbl rtbl tcbls vhold **\n    AOSIntNesting **\n    AOSTCBFreeList' ptfree lfree ct tcbls  **\n    AOSRdyTblGrp rtbl rgrp **\n    AOSTime (Vint32 t) **\n    HECBList ecbls **\n    HTCBList tcbls **\n    HTime t **\n    HCurTCB ct **\n    AGVars ** [|RH_TCBList_ECBList_P ecbls tcbls ct|] ** A_isr_is_prop.\n  \n  Lemma osinv''_OSInv: forall P,\n      osinv'' ** P <==> OSInv ** P.\n  Proof.\n    unfold osinv'', OSInv.\n    split.\n    intros.\n    sep cancel P.\n    sep destruct H.\n    rewrite <- AOSTCBList'_AOSTCBList'' in H.\n    sep auto.\n    intros.\n    sep cancel P.\n    sep destruct H.\n    sep eexists.\n    rewrite <- AOSTCBList'_AOSTCBList'' .\n    sep auto.\n  Qed.\n\n  Lemma starinv_isr_set_highest_tid :\n    forall n low i0 e e0 m c O ab tid b tp tp' ct M' x11 i,\n      (forall i : hid, x11 i = false) ->\n      EnvMod.get e OSTCBCur = Some (b, Tptr tp) ->\n      store (Tptr tp) m (b, 0) (Vptr tid) = Some M' ->\n      (e, e0, m, x11, (i, i0, c), O, ab) |= AHprio GetHPrio tid ** Atrue -> \n      (e, e0, m, x11, (i, i0, c), O, ab) |= GV OSTCBCur @ Tptr tp' |-r-> Vptr ct ** starinv_isr I low n ->\n      (exists tls,\n          get O abtcblsid = Some (abstcblist tls) /\\\n          (indom tls ct /\\\n           (e, e0, M', x11, (i, i0, c), set O curtid (oscurt tid), ab)\n             |= starinv_isr I low n ** (EX tp0 : type, GV OSTCBCur @ Tptr tp0 |-r-> Vptr tid) \\/\n           ~ indom tls ct /\\\n           (forall (Mx : mem) (Ox : osabst) (MM : mem) (OO : osabst),\n               satp (e, e0, Mx, x11, (i, i0, c)) Ox (EX lg, OSLInv ct lg) ->\n               join M' Mx MM ->\n               join O Ox OO ->\n               (e, e0, MM, x11, (i, i0, c), set OO curtid (oscurt tid), ab)\n                 |= starinv_isr I low n ** (EX tp0 : type, GV OSTCBCur @ Tptr tp0 |-r-> Vptr tid)))).\n  Proof.\n    inductions n; intros.\n    unfold starinv_isr in *.\n    destruct low.\n    sep normal in H3.\n    destruct H3.\n    apply disj_split in H3.\n    destruct H3.\n    simpl in H3; simpljoin1.\n    tryfalse. \n    sep remember (1::nil)%nat in H3.\n    simpl in H3; simpljoin1.\n\n    unfold I in *; unfold getinv in *.\n(*    sep normal.\n    sep eexists.\n    rewrite disj_split.\n    right.\n    sep normal.\n    sep remember (1::nil)%nat.\n    simpl_sat_goal.\n    do 6 eexists.\n    splits; eauto. \n    apply join_emp; auto. \n    apply join_emp; auto.\n    simpl; splits; eauto.\n    unfold emposabst; splits; eauto.\n    unfolds; auto.\n    substs.  \n *)\n    \n    Lemma OSInv_set_curtid1 :\n      forall e e0 M M' isr st O ab b tp tp0 tid ct P,\n        EnvMod.get e OSTCBCur = Some (b, Tptr tp) ->\n        store (Tptr tp) M (b, 0) (Vptr tid) = Some M' ->\n        (e, e0, M, isr, st, O, ab) |= AHprio GetHPrio tid ** Atrue ->\n        (e, e0, M, isr, st, O, ab) |= OSInv ** GV OSTCBCur @ Tptr tp0 |-r-> Vptr ct ** P ->\n    exists tls,\n      get O abtcblsid = Some (abstcblist tls) /\\\n      (indom tls ct /\\\n       (e, e0, M', isr, st, set O curtid (oscurt tid), ab)\n         |= OSInv ** GV OSTCBCur @ Tptr tp0 |-r-> Vptr tid ** P \\/\n    ~ indom tls ct /\\\n    (forall (Mx : mem) (Ox : osabst) (MM : mem) (OO : osabst),\n     satp (e, e0, Mx, isr, st) Ox (EX lg, OSLInv ct lg) ->\n     join M' Mx MM ->\n     join O Ox OO ->\n     (e, e0, MM, isr, st, set OO curtid (oscurt tid), ab)\n     |=  OSInv ** GV OSTCBCur @ Tptr tp0 |-r-> Vptr tid ** P)).\n  Proof.\n    intros.\n    rewrite <- osinv''_OSInv in H2.\n    unfold osinv'' in H2.\n    sep normal in H2.\n    sep destruct H2.\n    assert (get O abtcblsid = Some (abstcblist x13)).\n    sep remember (15::nil)%nat in H2.\n    simpl in H2; simpljoin1.\n    eapply join_get_l; eauto.\n    eexists.\n    split; eauto.\n    \n(*    rewrite <- osinv''_OSInv.\n    unfold osinv'' in *.\n    sep normal in H2.\n    sep destruct H2.\n *)\n    \n    Lemma AOSTCBList'_AOSTCBFreeList_set_curtid_indom :\n      forall p1 p2 l1 curtcb l2 rtbl ct tcbls lfree pf s P tid,\n        RH_CurTCB tid tcbls ->\n        indom tcbls ct ->\n        s |= AOSTCBList'' p1 p2 l1 (curtcb::l2) rtbl ct tcbls pf **\n          AOSTCBFreeList' pf lfree ct tcbls ** P ->\n        exists l1' curtcb' l2' pf' lfree',\n          s |= AOSTCBList'' p1 (Vptr tid) l1' (curtcb' :: l2') rtbl tid tcbls pf' **\n            AOSTCBFreeList' pf' lfree' tid tcbls ** P.\n    Proof.\n      intros.\n      rename H0 into H_indom.\n      rename H1 into H0.\n      unfold AOSTCBList'' in H0.\n      unfold AOSTCBFreeList' in H0.\n      \n      (*4 cases*)\n      apply disj_split in H0.\n      destruct H0.\n      sep normal in H0; sep destruct H0.\n      sep split in H0.\n      sep lift 6%nat in H0.\n      apply disj_split in H0.\n      destruct H0.\n\n      (*1*)\n      unfold TCBFree_Not_Eq in H0.\n      sep split in H0; simpljoin1.\n      unfolds in H; simpljoin1.\n      sep lifts (4::5::nil)%nat in H0.\n      pose proof H2 tid.\n      unfold get in H; simpl in H.\n      rewrite H in H7.\n      destruct (TcbMod.get x1 tid) eqn : eq1;\n        destruct (TcbMod.get x2 tid) eqn : eq2;\n        tryfalse.\n      substs.\n      (*tid in x1*)\n      lets Hx : tcb_list_split_by_tcbls eq1 H3 H0.\n      simpljoin1.\n      assert (\n        s |= tcbdllseg p1 Vnull x11 (Vptr tid) x6 **\n          tcbdllseg (Vptr tid) x11 x (Vptr ct) (x7 :: x8) **\n          tcbdllseg (Vptr ct) x x0 Vnull (curtcb :: l2) **\n          assertion.sll pf lfree OS_TCB_flag V_OSTCBNext **\n          sllfreeflag pf lfree **\n          GV OSTCBList @ Tptr os_ucos_h.OS_TCB |-> p1 **\n          tcbdllflag p1 ((x6 ++ x7 :: x8) ++ curtcb :: l2) **\n          GV OSTCBFreeList @ Tptr os_ucos_h.OS_TCB |-> pf ** P  \n        ) as H7_bak by auto.\n      sep lifts (2::3::nil)%nat in H7.\n      assert (V_OSTCBNext (last (x7 :: x8) nil) = Some (Vptr ct)) as H_last.\n      eapply tcbdllseg_last_nextptr in H7; auto.\n      eapply tcbdllseg_compose in H7.\n      \n      lets Hx: TCBList_P_combine_copy H9 H4.\n      instantiate (1:=merge x10 x2).\n      clear - H2 H10.\n      eapply TcbMod.join_merge_disj.\n      apply join_comm in H10.\n      eapply TcbMod.join_join_disj_l; eauto.\n      assert (x7 :: x8 <> nil) by auto.\n      apply Hx in H11; auto; clear Hx.\n      replace ((x7 :: x8) ++ curtcb :: l2) with (x7 :: x8 ++ curtcb :: l2) in H7, H11.\n      exists x6 x7 (x8 ++ curtcb :: l2) pf lfree.\n      unfold AOSTCBList''.\n      apply disj_split.\n      left.\n      sep normal.\n      do 4 eexists.\n      sep split; eauto.\n      sep cancel 5%nat 1%nat.\n      sep cancel 2%nat 1%nat.\n      sep cancel 1%nat 1%nat.\n      replace ((x6 ++ x7 :: x8) ++ curtcb :: l2) with (x6 ++ x7 :: x8 ++ curtcb :: l2) in H7.\n      sep cancel 3%nat 1%nat.\n      unfold AOSTCBFreeList'.\n      sep auto.\n      left.\n      unfold TCBFree_Not_Eq.\n      sep auto.\n      clear - H7_bak.\n      sep remember (2::4::nil)%nat in H7_bak; clear HeqH.\n      clears.\n      Lemma tcbdllseg_sll_neq :\n        forall ct lfree pf s tid x x7 x8 x11 H,\n          s\n           |= tcbdllseg (Vptr tid) x11 x ct (x7 :: x8) **\n           assertion.sll pf lfree OS_TCB_flag V_OSTCBNext ** H ->\n          pf <> Vptr tid.\n      Proof.\n        intros.\n        intro; substs.\n        unfold assertion.sll in H0.\n        destruct lfree.\n        unfold sllseg in H0; fold sllseg in H0; sep split in H0; tryfalse.\n        unfold sllseg in H0; fold sllseg in H0.\n        unfold tcbdllseg in H0.\n        unfold dllseg in H0; fold dllseg in H0.\n        sep normal in H0.\n        sep destruct H0.\n        sep split in H0; simpljoin1.\n        inverts H1; inverts H3.\n        sep lifts (1::3::nil)%nat in H0.\n        eapply os_inv.node_OS_TCB_dup_false; eauto.\n      Qed.\n      eapply tcbdllseg_sll_neq; eauto.\n      \n      rewrite <- app_assoc.\n      auto.\n      \n      clear - H7_bak.\n      sep remember (2::4::nil)%nat in H7_bak; clear HeqH.\n      clears.\n      assert (pf <> Vptr tid).\n      eapply tcbdllseg_sll_neq; eauto.\n      auto.\n      clear - H2 H10.\n      eapply join_merge23_join; eauto.\n      rewrite app_comm_cons; auto.\n\n      (*tid in x2*)\n      substs.\n      sep lift 2%nat in H0.\n      lets Hx : tcb_list_split_by_tcbls eq2 H4 H0.\n      simpljoin1.\n      assert (\n        s\n       |= tcbdllseg (Vptr ct) x x11 (Vptr tid) x6 **\n          tcbdllseg (Vptr tid) x11 x0 Vnull (x7 :: x8) **\n          tcbdllseg p1 Vnull x (Vptr ct) l1 **\n          assertion.sll pf lfree OS_TCB_flag V_OSTCBNext **\n          sllfreeflag pf lfree **\n          GV OSTCBList @ Tptr os_ucos_h.OS_TCB |-> p1 **\n          tcbdllflag p1 (l1 ++ curtcb :: l2) **\n          GV OSTCBFreeList @ Tptr os_ucos_h.OS_TCB |-> pf ** P\n        ) as H7_bak by auto.\n(*      assert (V_OSTCBNext (last l1 nil) = Some (Vptr ct)) as H_last.\n(* ** ac:       Check  TCBList_P_combine_copy. *)\n\n     \n      eapply tcbdllseg_last_nextptr in H7; auto.\n      eapply tcbdllseg_compose in H7.\n *)\n      exists (l1 ++ x6) x7 x8 pf lfree.\n      unfold AOSTCBList''.\n      apply disj_split.\n      left.\n      sep normal.\n      exists x11 x0 (merge x1 x9) x10.\n      sep split; eauto.\n      sep cancel 6%nat 1%nat.\n      sep cancel 2%nat 2%nat.\n      rewrite H11 in H7_bak.\n      replace (l1 ++ x6 ++ x7 :: x8) with ((l1 ++ x6) ++ x7 :: x8) in H7_bak.\n      sep cancel 5%nat 2%nat.\n      unfold AOSTCBFreeList'.\n      sep auto.\n      sep lift 2%nat.\n      apply disj_split.\n      left.\n      unfold TCBFree_Not_Eq.\n      sep lifts (2::1::nil)%nat in H7_bak.\n      eapply tcbdllseg_compose in H7_bak.\n      sep auto.\n\n      clear - H7.\n      sep lifts (2::4::nil)%nat in H7.\n      eapply tcbdllseg_sll_neq; eauto.\n      \n      rewrite <- app_assoc.\n      auto.\n\n      assert (pf <> Vptr tid).\n      sep lifts (2::4::nil)%nat in H7.\n      eapply tcbdllseg_sll_neq; eauto.\n      auto.\n\n      clear - H1 H3 H8 H10 H2 H7.\n      destruct l1.\n      rewrite app_nil_l.\n      simpl in H3; simpljoin1.\n      sep remember (3::nil)%nat in H7.\n      destruct_s s.\n      simpl in H7; simpljoin1.\n      rewrite jl_merge_emp'.\n      auto.\n      eapply TCBList_P_combine_copy; eauto.\n      clear - H2 H10.\n      eapply TcbMod.join_merge_disj.\n      apply join_comm in H2.\n      apply TcbMod.disj_comm.\n      eapply TcbMod.join_join_disj_l; eauto.\n      sep lift 3%nat in H7.\n      eapply tcbdllseg_last_nextptr; eauto.\n\n      clear - H2 H10.\n      eapply join_join_join_merge; eauto.\n\n      (*2 false*)\n      unfold TCBFree_Eq in H0.\n      sep normal in H0; sep destruct H0.\n      sep split in H0.\n      simpljoin1.\n      tryfalse.\n\n      sep normal in H0; sep destruct H0.\n      sep split in H0.\n      sep lift 6%nat in H0.\n      apply disj_split in H0.\n      destruct H0.\n      (*3 false*)\n      unfold TCBFree_Not_Eq in H0.\n      sep normal in H0; sep destruct H0.\n      sep split in H0.\n      simpljoin1.\n      tryfalse.\n\n      (*4*)\n      simpljoin1.\n      \n      Lemma tcblist_indom_ptr_in_tcblist :\n        forall vltcb head rtbl tcbls ct,\n          TCBList_P head vltcb rtbl tcbls ->\n          indom tcbls ct ->\n          ptr_in_tcblist (Vptr ct) head vltcb.\n      Proof.\n        inductions vltcb; intros.\n        simpl in H; substs.\n        unfolds in H0; destruct H0.\n        rewrite emp_sem in H; tryfalse.\n\n        unfold1 TCBList_P in H; simpljoin1.\n        unfold ptr_in_tcblist.\n        unfold1 ptr_in_tcbdllseg.\n        destruct (beq_val (Vptr ct) (Vptr x)) eqn : eq1; auto.\n        rewrite H1.\n        eapply IHvltcb; eauto.\n        clear - H2 H0 eq1.\n        unfold indom in *; simpljoin1.\n        exists x0.\n        unfolds in H2.\n        assert (ct <> x).\n        intro; substs.\n        unfold beq_val in eq1.\n        unfolds in eq1.\n        destruct x.\n        rewrite beq_pos_Pos_eqb_eq in eq1.\n        rewrite Int.eq_true in eq1.\n        assert (b = b) by auto.\n        apply Pos.eqb_eq in H0.\n        rewrite H0 in eq1.\n        simpl in eq1; tryfalse.\n        clear eq1.\n        hy.\n      Qed.\n\n      unfold TCB_Not_In in H0.\n      unfold tcblist in H0.\n      sep split in H0.\n      lets Hx: tcblist_indom_ptr_in_tcblist H2 H_indom.\n      simpljoin1.\n      false; apply H3; auto.\n    Qed.\n\n    assert (os_ucos_h.OS_TCB = tp0).\n    sep remember (1::21::nil)%nat in H2.\n    simpl in H2; simpljoin1.\n    rewrite H27 in H18; inverts H18.\n    auto.\n    subst tp0.\n    \n    assert (x6 = Vptr x15).\n    sep remember (2::nil)%nat in H2.\n    simpl in H2; simpljoin1.\n    destruct H8; simpljoin1; auto.\n    substs.\n    sep remember (1::21::nil)%nat in H2.\n    eapply sep_combine_lemmas.GV_combine_ro_frm in H2.\n    sep split in H2.\n    simpl in H2; simpljoin1.\n    assert (x15 = ct).\n    clear - H5.\n    simpl in H5.\n    destruct x15; destruct ct.\n    inverts H5; auto.\n    substs.\n    \n    assert (indom x13 ct \\/ ~ indom x13 ct).\n    unfold indom.\n    destruct (get x13 ct) eqn : eq1; clear - eq1.\n    left; eauto.\n    right.\n    intro; destruct H; tryfalse.\n    destruct H2.\n    (*indom tcbls ct*)\n    left.\n    split; auto.\n    rewrite <- osinv''_OSInv.\n    unfold osinv''.\n    sep normal.\n    unfolds in H14; simpl in H14.\n    rewrite H in H14; inverts H14.\n    lets Hx: lmachLib.store_mapstoval_frame H15 H6 H0.\n    simpljoin1.\n\n    sep lifts (1::10::nil)%nat in H10.\n    lets Hx: AOSTCBList'_AOSTCBFreeList_set_curtid_indom H10; auto.\n    unfolds.\n    instantiate (TEMP11 := tid).\n    clear - H1 H3.\n    simpl in H1; simpljoin1.\n    unfolds in H4; simpljoin1.\n    assert (get O abtcblsid = Some (abstcblist x)).\n    eapply join_get_l; eauto.\n    rewrite H3 in H5.\n    inverts H5.\n    eauto.\n    simpljoin1.\n    sep eexists.\n\n    sep lifts (1::21::nil)%nat.\n    eapply sep_combine_lemmas.GV_combine_ro'_frm; eauto.\n    sep remember (1::nil)%nat.\n    simpl.\n    exists x15 x19.\n    do 4 eexists.\n    splits; eauto.\n    eapply join_emp; eauto.\n    do 7 eexists.\n    splits; eauto.\n    eapply join_emp; eauto.\n    eapply join_emp; eauto.\n    eexists.\n    unfold emposabst; splits; eauto.\n    unfolds.\n    eexists; splits; eauto.\n    unfolds in H15; simpljoin1.\n    unfold store in H4.\n    lets Hx: lmachLib.storebytes_ptomvallist_eqlen_infer p H4.\n    simpl.\n    destruct tid; destruct ct; simpl; auto.\n    auto.\n    unfolds; auto.\n    substs.\n    sep remember (16::nil)%nat in H5.\n    simpl in H5; simpljoin1.\n    sep remember (16::nil)%nat.\n    simpl.\n    do 6 eexists.\n    splits; eauto.\n    eapply join_emp; auto.\n    eapply join_sig_set; eauto.\n    substs.\n    sep auto.\n\n    (*not indom 13 ct*)\n    right.\n    split; auto.\n    intros.\n\n    pose proof H4 ab.\n    \n    Lemma AOSTCBList'_AOSTCBFreeList_set_curtid_not_indom\n      : forall (p1 p2 : val) (l1 : list vallist) (curtcb : vallist)\n               (l2 : list vallist) (rtbl : vallist) (ct : addrval)\n               (tcbls : TcbMod.map) (lfree : list vallist) \n               (pf : val) (P : asrt) (tid : Modules.tid) e e0 isr st ab M O Mx Ox MM OO,\n        RH_CurTCB tid tcbls ->\n        ~indom tcbls ct ->\n        (e, e0, M, isr, st, O, ab)\n          |= AOSTCBList'' p1 p2 l1 (curtcb :: l2) rtbl ct tcbls pf **\n          AOSTCBFreeList' pf lfree ct tcbls ** P ->\n        join M Mx MM ->\n        join O Ox OO ->\n        (e, e0, Mx, isr, st, Ox, ab) |= EX lg : list logicvar, OSLInv ct lg ->\n        exists l1' curtcb' l2' pf' lfree',\n          (e, e0, MM, isr, st, OO, ab)\n            |= AOSTCBList'' p1 (Vptr tid) l1' (curtcb' :: l2') rtbl tid tcbls\n            pf' ** AOSTCBFreeList' pf' lfree' tid tcbls ** P.\n    Proof.\n      intros.\n      rename H0 into H_indom.\n      rename H1 into H0.\n      unfold AOSTCBList'' in H0.\n      unfold AOSTCBFreeList' in H0.\n      \n      (*4 cases*)\n      apply disj_split in H0.\n      destruct H0.\n      sep normal in H0; sep destruct H0.\n      sep split in H0.\n      sep lift 6%nat in H0.\n      apply disj_split in H0.\n      destruct H0.\n\n      (*1 false*)\n      simpljoin1.\n      unfold1 TCBList_P in H7.\n      simpljoin1.\n      inverts H7.\n      clear - H5 H10 H_indom.\n      false.\n      apply H_indom.\n      unfold indom.\n      exists x6.\n      unfolds in H10.\n      eapply join_get_r; eauto.\n      eapply join_get_l; eauto.\n      apply get_sig_some.\n\n      (*2 false*)\n      unfold TCBFree_Eq in H0.\n      sep normal in H0; sep destruct H0.\n      sep split in H0.\n      simpljoin1.\n      tryfalse.\n\n      sep normal in H0; sep destruct H0.\n      sep split in H0.\n      sep lift 6%nat in H0.\n      apply disj_split in H0.\n      destruct H0.\n      (*3 false*)\n      unfold TCBFree_Not_Eq in H0.\n      sep normal in H0; sep destruct H0.\n      sep split in H0.\n      simpljoin1.\n      tryfalse.\n\n      (*4*)\n      simpljoin1.\n      unfold TCBFree_Eq in H0.\n      sep normal in H0.\n      sep destruct H0.\n      sep split in H0; simpljoin1.\n      unfolds in H; simpljoin1.\n      sep lift 6%nat in H0.\n      unfold tcblist in H0.\n      sep split in H0.\n      lets Hx: tcb_list_split_by_tcbls H H5 H0.\n      simpljoin1.\n      exists x7 x8 x9.\n      exists (Vptr ct) (x1::x0).\n      unfold AOSTCBList''.\n      apply disj_split.\n      left.\n      sep lift 2%nat.\n      unfold AOSTCBFreeList'.\n      sep normal.\n      exists x12 x x10 x11.\n      sep lift 11%nat.\n      apply disj_split.\n      left.\n      sep split; auto.\n      unfold TCB_Not_In in H10.\n      sep split in H10.\n      sep remember (3::4::5::6::nil)%nat in H10.\n      sep remember (5::nil)%nat in H10.\n      sep lift 2%nat in H10.\n      simpl in H10; simpljoin1.\n      sep remember (1::nil)%nat.\n      simpl_sat_goal.\n      exists (merge x13 Mx) x14 MM.\n      exists (merge x16 Ox) x17 OO.\n      splits; eauto.\n      eapply mem_join_join_merge13_join'; eauto.\n      eapply join_join_merge1; eauto.\n      apply join_comm in H3; eauto.\n      assert (\n          (e, e0, merge x13 Mx, isr, st, merge x16 Ox, ab)\n            |= (EX lg : list logicvar, OSLInv ct lg) ** Astruct ct OS_TCB_flag x1 **\n           PV get_off_addr ct flag_off @ Tint8 |-r-> Vint32 (Int.repr 0) **\n           assertion.sll x2 x0 OS_TCB_flag V_OSTCBNext ** sllfreeflag x2 x0\n        ).\n      sep remember (1::nil)%nat.\n      simpl_sat_goal.\n      exists Mx x13; eexists.\n      exists Ox x16; eexists.\n      splits; eauto.\n      apply join_comm.\n      apply join_merge_disj.\n      clear - H19 H2.\n      eapply mem_join_join_disjoint; eauto.\n      apply join_comm.\n      apply join_merge_disj.\n      eapply osabst_join_join_disjoint; eauto.\n      unfold OSLInv in H17.\n      sep normal in H17.\n      sep destruct H17.\n      sep split in H17; simpljoin1.\n      sep lifts (1::3::nil)%nat in H17.\n      apply sep_combine_lemmas.PV_combine_ro_frm in H17.\n      sep split in H17.\n      unfold TCBFree_Not_Eq.\n      sep split.\n      unfold  assertion.sll in *.\n      unfold1 sllseg.\n      unfold sllfreeflag in *.\n      unfold1 sllsegfreeflag.\n      sep normal.\n      sep eexists.\n      sep split; eauto.\n      inverts H24.\n      unfold node; sep normal.\n      sep eexists.\n      sep split; eauto.\n      assert (x18 = (Vint32 (Int.repr 0))).\n      clear - H10 H20.\n      unfolds in H20; destruct H20.\n      substs.\n      simpl in H10; tryfalse.\n      auto.\n      substs.\n      sep auto.\n\n      clear - H H_indom.\n      intro.\n      inverts H0.\n      unfolds in H_indom.\n      apply H_indom.\n      unfold indom.\n      eauto.\n\n      substs.\n      sep auto.\n      rewrite <- H15.\n      auto.\n\n      clear - H H_indom.\n      intro.\n      inverts H0.\n      unfolds in H_indom.\n      apply H_indom.\n      unfold indom.\n      eauto.\n    Qed.\n\n    rewrite <- osinv''_OSInv.\n    unfold osinv''.\n    sep normal.\n    unfolds in H14; simpl in H14.\n    rewrite H in H14; inverts H14.\n    lets Hx: lmachLib.store_mapstoval_frame H15 H6 H0.\n    simpljoin1.\n\n    sep remember (1::nil)%nat in H10.\n    assert ((e, e0, M', isr, st, O, ab)\n              |=  GV OSTCBCur @ Tptr os_ucos_h.OS_TCB |-> (Vptr tid) ** AOSTCBList'' x5 (Vptr ct) x7 (x8 :: x9) x10 ct x13 x17 ** H5).\n    substs.\n    sep remember (1::nil)%nat.\n    simpl.\n    do 6 eexists.\n    splits; eauto.\n    apply join_emp; auto.\n    do 7 eexists.\n    splits; eauto.\n    eapply join_emp; eauto.\n    apply join_emp; eauto.\n    eexists.\n    splits; eauto.\n    unfolds; auto.\n    unfolds.\n    eexists; splits; eauto.\n    unfolds in H15; simpljoin1.\n    eapply lmachLib.storebytes_ptomvallist_eqlen_infer; eauto.\n    simpl; destruct tid, ct; auto.\n    unfolds; auto.\n    substs.\n    sep lifts (2::11::nil)%nat in H13.\n    lets Hx: AOSTCBList'_AOSTCBFreeList_set_curtid_not_indom H13 H7 H8 H9.\n    unfolds.\n    instantiate (TEMP10 := tid).\n    clear - H1 H3.\n    simpl in H1; simpljoin1.\n    unfolds in H4; simpljoin1.\n    assert (get O abtcblsid = Some (abstcblist x)).\n    eapply join_get_l; eauto.\n    rewrite H3 in H5.\n    inverts H5.\n    eauto.\n    auto.\n    simpljoin1.\n    sep eexists.\n    sep lifts (1::21::nil)%nat.\n    eapply sep_combine_lemmas.GV_combine_ro'_frm; eauto.\n    sep remember (17::nil)%nat in H5.\n    simpl in H5; simpljoin1.\n    sep remember (17::nil)%nat.\n    simpl.\n    exists empmem MM.\n    do 4 eexists.\n    splits; eauto.\n    eapply join_emp; auto.\n    eapply join_sig_set; eauto.\n    substs.\n    sep auto.\n  Qed.\n\n  assert ((e, e0, m, x, (i, i0, c), O, ab)\n            |= OSInv ** GV OSTCBCur @ Tptr tp' |-r-> Vptr ct ** Aemp).\n  sep auto.\n  lets Hx: OSInv_set_curtid1 H0 H1 H2 H3.\n  simpljoin1.\n  eexists.\n  splits; eauto.\n  destruct H5; simpljoin1.\n  left.\n  split; auto.\n  sep normal.\n  sep eexists.\n  sep lift 2%nat.\n  apply disj_split.\n  right.\n  sep normal.\n  sep remember (1::nil)%nat.\n  simpl.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep auto.\n  right.\n  split; auto.\n  intros.\n  lets Hx: H6 H7 H10 H11.\n  sep normal.\n  sep eexists.\n  sep lift 2%nat.\n  apply disj_split.\n  right.\n  sep normal.\n  sep remember (1::nil)%nat.\n  simpl.\n  substs.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; eauto.\n  sep auto.\n\n  destruct low.\n  simpl getinv in *.\n  sep normal in H3.\n  destruct H3.\n  apply disj_split in H3.\n  destruct H3.\n  simpl in H3; simpljoin1; tryfalse.\n  sep remember (1::nil)%nat in H3.\n  simpl in H3; simpljoin1.\n  unfold atoy_inv in H9.\n  unfold A_isr_is_prop in H9.\n  unfold atoy_inv' in H9.\n  simpl in H9; simpljoin1.\n  simpl in H2; simpljoin1.\n  unfolds in H7; simpljoin1.\n  apply map_join_pos in H6; simpljoin1.\n  rewrite emp_sem in H2; tryfalse.\n  \n  simpl getinv in *.\n  sep normal in H3.\n  destruct H3.\n  apply disj_split in H3.\n  destruct H3.\n  simpl in H3; simpljoin1; tryfalse.\n  sep remember (1::nil)%nat in H3.\n  simpl in H3; simpljoin1.\n  unfold aemp_isr_is in H9.\n  unfold A_isr_is_prop in H9.\n  simpl in H9; simpljoin1.\n  simpl in H2; simpljoin1.\n  unfolds in H6; simpljoin1.\n  apply map_join_pos in H5; simpljoin1.\n  rewrite emp_sem in H2; tryfalse.\n\n  (*ind case*)\n  unfold starinv_isr in *; fold starinv_isr in *.\n  sep normal in H3; destruct H3.\n(*  sep normal; exists x. *)\n  apply disj_split in H3.\n  destruct H3.\n  simpl in H3; simpljoin1; tryfalse.\n  sep remember (1::nil)%nat in H3.\n  simpl in H3; simpljoin1.\n\n  destruct low.\n  unfold I in *; fold I in *; unfold getinv in *.\n  eapply OSInv_set_curtid1 in H9; eauto.\n  simpljoin1.\n  destruct H4; simpljoin1.\n  eexists; splits; eauto.\n  left.\n  split; auto.\n  sep normal.\n  sep eexists.\n  sep lift 2%nat.\n  apply disj_split.\n  right.\n  sep normal.\n  sep remember (1::nil)%nat.\n  simpl.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; eauto.\n  apply join_emp; eauto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep auto.\n\n  eexists.\n  splits; eauto.\n  right.\n  split; eauto.\n  intros.\n  lets Hx: H5 H6 H7 H9.\n  sep normal.\n  sep eexists.\n  sep lift 2%nat.\n  apply disj_split.\n  right.\n  sep normal.\n  sep remember (1::nil)%nat.\n  simpl.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; eauto.\n  apply join_emp; eauto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep auto.\n  \n  destruct low.\n  unfold I in *; fold I in *; unfold getinv in *.\n  false.\n\n  Lemma AHprio_starinv_isr_atoy_inv_false :\n    forall e e0 M M1 M2 isr st O o1 o2 ab n i tid,\n      join o1 o2 O -> (i > 0)%nat -> (forall i : hid, isr i = false) ->\n      (e, e0, M, isr, st, O, ab) |= AHprio GetHPrio tid ** Atrue ->\n      (e, e0, M1, isr, st, o2, ab) |= starinv_isr I i n ->\n      (e, e0, M2, isr, st, o1, ab) |= atoy_inv ->\n      False.\n  Proof.\n    intros.\n    apply starinv_isr_osabst_emp in H3; auto.\n    apply atoy_inv_osabst_emp in H4; auto.\n    substs.\n    simpl in H2; simpljoin1.\n    unfolds in H6; simpljoin1.\n    pose proof H5 abtcblsid.\n    pose proof H abtcblsid.\n    rewrite OSAbstMod.emp_sem in H8.\n    destruct (OSAbstMod.get O abtcblsid) eqn : eq1; tryfalse.\n    destruct (OSAbstMod.get x2 abtcblsid) eqn: eq2; tryfalse.\n    destruct (OSAbstMod.get x3 abtcblsid); tryfalse.\n    destruct (OSAbstMod.get x3 abtcblsid) eqn : eq3; tryfalse.\n    unfold get in H2; simpl in H2; rewrite H2 in eq2; tryfalse.\n  Qed.\n\n  simpl_sat H9; simpljoin1.\n  simpl in H13; simpljoin1.\n  eapply AHprio_starinv_isr_atoy_inv_false with (i:=2%nat); eauto.\n\n  sep remember (1::nil)%nat in H9.\n  simpl_sat H9; simpljoin1.\n  simpl in H9; simpljoin1.\n  lets Hx: IHn H H0 H1 H2 H10.\n  simpljoin1.\n  eexists; splits; eauto.\n  destruct H4; simpljoin1.\n  left.\n  split; auto.\n  sep normal in H5; destruct H5.\n  sep normal.\n  sep eexists.\n  sep lift 2%nat.\n  apply disj_split.\n  right.\n  sep normal.\n  sep remember (1::nil)%nat.\n  simpl.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; eauto.\n  apply join_emp; eauto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  simpl getinv.\n  unfold aemp_isr_is.\n  unfold A_isr_is_prop.\n  sep auto.\n\n  right.\n  split; auto.\n  intros.\n  lets Hx: H5 H6 H7 H9.\n  sep normal in Hx; destruct Hx.\n  sep normal.\n  sep eexists.\n  sep lift 2%nat.\n  apply disj_split.\n  right.\n  sep normal.\n  sep remember (1::nil)%nat.\n  simpl.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; eauto.\n  apply join_emp; eauto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  simpl getinv.\n  unfold aemp_isr_is.\n  unfold A_isr_is_prop.\n  sep auto.\n  Qed.\n\n  unfold invlth_isr in *.\n  rewrite Nat.sub_0_r in *.\n  lets Hx: starinv_isr_set_highest_tid H18 Hget Hs Hpr H15.\n  simpljoin1.\n  eexists.\n  splits;eauto.\n  destruct H0; simpljoin1.\n  left.\n  split; auto.\n  sep normal in H1; destruct H1.\n  sep remember (1::nil)%nat.\n  simpl.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  eexists.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep remember (1::nil)%nat.\n  simpl.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep normal.\n  sep eexists.\n  rewrite Nat.sub_0_r.\n  sep remember (2::nil)%nat.\n  simpl.\n  do 6 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep auto.\n  rewrite Nat.add_0_r.\n  auto.\n\n  right.\n  split; auto.\n  intros.\n  lets Hx: H1 H2 H3 H4.\n  sep normal in Hx.\n  destruct Hx.\n  sep remember (1::nil)%nat.\n  simpl.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  eexists.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep remember (1::nil)%nat.\n  simpl.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  sep normal.\n  pose proof H2 ab.\n  destruct H6.\n  unfold OSLInv in H6.\n  destruct H6.\n  simpl in H6; simpljoin1.\n  sep eexists.\n  rewrite Nat.sub_0_r.\n  sep remember (2::nil)%nat.\n  simpl.\n  exists empmem.\n  do 5 eexists.\n  splits; eauto.\n  apply join_emp; auto.\n  apply join_emp; auto.\n  unfold emposabst.\n  splits; eauto.\n  substs.\n  rewrite Nat.add_0_r.\n  sep auto.\n\n- apply GoodSched_GetHPrio.\nQed.\n\n\n\n*)\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/spec/inv_prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2308715719113836}}
{"text": "(****************************************************************************)\n(* Copyright 2020 The Project Oak Authors                                   *)\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\nRequire Import Cava.Cava.\nRequire Import Cava.CavaProperties.\nRequire Import AesSpec.AES256.\nRequire Import AesSpec.StateTypeConversions.\nRequire Import AesImpl.Pkg.\nRequire Import AesImpl.ShiftRowsCircuit.\nImport StateTypeConversions.LittleEndian.\n\nSection Equivalence.\n  Local Notation byte := (Vector.t bool 8).\n  Local Notation state := (Vector.t (Vector.t byte 4) 4) (only parsing).\n  Local Notation key := (Vector.t (Vector.t byte 4) 4) (only parsing).\n\n  Lemma shift_rows_equiv (is_decrypt : bool) (st : state) :\n    aes_shift_rows is_decrypt st\n    = AES256.aes_shift_rows_circuit_spec is_decrypt st.\n  Proof.\n    (* simplify RHS (specification) *)\n    cbv [aes_shift_rows_circuit_spec\n           AES256.shift_rows AES256.inv_shift_rows\n           ShiftRows.shift_rows ShiftRows.inv_shift_rows].\n    cbv [to_flat from_flat BigEndian.from_list_rows BigEndian.to_list_rows].\n    autorewrite with conversions push_length push_to_list.\n    cbn [List.map map]. autorewrite with push_to_list.\n    cbv [ShiftRows.shift_rows_start ShiftRows.inv_shift_row].\n    autorewrite with push_length. cbn [seq map2].\n    autorewrite with push_of_list_sized. cbn [map].\n\n    cbv [aes_shift_rows]. simpl_ident.\n\n    (* break state vector into 16 bytes *)\n    constant_vector_simpl st.\n    repeat match goal with\n           | v := _ : Vector.t byte 4 |- _ => constant_vector_simpl v\n    end; clear.\n\n    (* simplify LHS (implementation) *)\n    cbv [aes_circ_byte_shift]. simpl_ident.\n    repeat lazymatch goal with\n           | |- context [map (@indexConst _ _ ?A _ [?x]%list) ?y] =>\n             erewrite map_ext with (f:=@indexConst seqType _ A _ [x]%list)\n                                   (g:=fun n => [nth_default (defaultCombValue A) n x])\n               by (intros; rewrite !(@indexConst_singleton (Vec Bit 8));\n                   reflexivity)\n           end.\n    rewrite !map_map.\n    cbn [map].\n    repeat match goal with\n           | |- context [Nat.modulo ?n ?m] => compute_expr (Nat.modulo n m)\n           end.\n    cbn [map length fold_left PeanoNat.Nat.max seq List.nth\n             List.map nth_default List.rev app].\n\n    (* prove the two sides are equivalent *)\n    destruct is_decrypt.\n    { fequal_list; fequal_vector;\n        cbn - [bitvec_to_byte byte_to_bitvec];\n        rewrite !bitvec_to_byte_to_bitvec; reflexivity. }\n    { fequal_list; fequal_vector;\n        cbn - [bitvec_to_byte byte_to_bitvec];\n        rewrite !bitvec_to_byte_to_bitvec; reflexivity. }\n  Qed.\nEnd Equivalence.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/silveroak-opentitan/aes/Impl/ShiftRowsEquivalence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23087157191138358}}
{"text": "Load \"tact_DH2\".\n\n  \n  \n \n\nTheorem Pi1_Pi2'': phi4 ~ phi34.\nProof.\n\n\n  repeat unf_phi. \nsimpl. \n  \nassert(H: (ostomsg t15) # (ostomsg t35)).\nsimpl.\n \n repeat unf. \n\nrepeat rewrite andB_elm'' with (b1:= (EQ_M (to x1) (i 1)) ) (b2:= (EQ_M (act x1) new)  ).\n false_to_sesns_all; simpl. \nrepeat redg; repeat rewrite IFTFb.\naply_breq.\n repeat redg;  repeat rewrite IFTFb. \naply_breq.  \n repeat redg;  repeat rewrite IFTFb.\nfalse_to_sesns_all; simpl. \n repeat redg;  repeat rewrite IFTFb.\naply_breq.  \n repeat redg;  repeat rewrite IFTFb.\nfalse_to_sesns_all; simpl. \n  repeat redg;  repeat rewrite IFTFb.\naply_breq.  \n repeat redg;  repeat rewrite IFTFb.\nfalse_to_sesns_all; simpl. \n  repeat redg;  repeat rewrite IFTFb.\n aply_breq.  \n repeat redg;  repeat rewrite IFTFb.\nrepeat aply_andB_elm.\nfalse_to_sesns_all; simpl. \nrepeat redg;  repeat rewrite IFTFb.\n aply_breq.  \n repeat redg;  repeat rewrite IFTFb. reflexivity. \nfalse_to_sesns_all; simpl. \nrepeat redg;  repeat rewrite IFTFb.\n aply_breq.  \n repeat redg;  repeat rewrite IFTFb.\naply_breq.  \n repeat redg;  repeat rewrite IFTFb. reflexivity. \nfalse_to_sesns_all; simpl. \n repeat redg;  repeat rewrite IFTFb.\naply_breq.  \napply eqm in H. rewrite H. reflexivity. \n\nQed.\n ", "meta": {"author": "ajayeeralla", "repo": "compSoundProofsWOracleMoves", "sha": "8480855887a9092d16dc183ce6ed19315a3ffa96", "save_path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves", "path": "github-repos/coq/ajayeeralla-compSoundProofsWOracleMoves/compSoundProofsWOracleMoves-8480855887a9092d16dc183ce6ed19315a3ffa96/DH2_Pi1_Pi2''.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.23087156540677795}}
{"text": "(* (c) Copyright Microsoft Corporation and Inria. All rights reserved. *)\nRequire Import ssreflect.\nRequire Import ssrbool.\nRequire Import funs.\nRequire Import dataset.\nRequire Import ssrnat.\nRequire Import seq.\nRequire Import paths.\nRequire Import finset.\nRequire Import connect.\nRequire Import hypermap.\nRequire Import geometry.\nRequire Import color.\nRequire Import coloring.\nRequire Import quiz.\nRequire Import cfmap.\nRequire Import cfquiz.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* Compile a sequencs of (reducible) configurations into a set of quizzes,  *)\n(* and store them in a tree structure according to the arities of the three *)\n(* center regions. Rotations and reflections are also stored, so that the   *)\n(* reducibility search can do a single lookup per triangle in the searched  *)\n(* part (see file redpart.v).                                               *)\n(* The middle nodes of the tree have four branches, for each of the arities *)\n(* 5, 6, 7 and 8; the top node also has four branches, but with a different *)\n(* interpretation: the first is a subtree for arities less than 9, and the  *)\n(* other three for arities 9, 10, and 11 (we don't need to store those      *)\n(* lower in the tree, since only the most central region of our             *)\n(* configurations can have more than 8 sides). Also, since such a large     *)\n(* region can only match the hub, we don't store the rotations of its quiz. *)\n(*   The quiz fork and trees are traversed in the inner loop of the         *)\n(* unavoidability computation, so, like parts, their representation has     *)\n(* been compressed, with the quiz triples integrated in the list structure, *)\n(* and the tree structure feeding directly in the list structure.           *)\n\nInductive quiz_tree : Set :=\n  | QztNil : quiz_tree\n  | QztLeaf : forall q1 q2 q3 : question, quiz_tree -> quiz_tree\n  | QztNode : forall t5 t6 t7 t8 : quiz_tree, quiz_tree\n  | QztHubNode : forall t58 t9 t10 t11 : quiz_tree, quiz_tree.\n\n(* Not-nil test.                                                            *)\n\nDefinition qzt_proper qt' := if qt' is QztNil then false else true.\n\n(* Update/store operations.                                                 *)\n\nFixpoint qzt_put1 (qa : qarity) (qr : quiz_tree -> quiz_tree) (t : quiz_tree)\n    {struct t} : quiz_tree :=\n  match t, qa with\n  | QztNode t5 t6 t7 t8, Qa5 => QztNode (qr t5) t6 t7 t8\n  | QztNode t5 t6 t7 t8, Qa6 => QztNode t5 (qr t6) t7 t8\n  | QztNode t5 t6 t7 t8, Qa7 => QztNode t5 t6 (qr t7) t8\n  | QztNode t5 t6 t7 t8, Qa8 => QztNode t5 t6 t7 (qr t8)\n  | QztHubNode t58 t9 t10 t11, Qa9 => QztHubNode t58 (qr t9) t10 t11\n  | QztHubNode t58 t9 t10 t11, Qa10 => QztHubNode t58 t9 (qr t10) t11\n  | QztHubNode t58 t9 t10 t11, Qa11 => QztHubNode t58 t9 t10 (qr t11)\n  | QztHubNode t58 t9 t10 t11, _ =>\n      QztHubNode (qzt_put1 qa qr t58) t9 t10 t11\n  | _, _ => t\n  end.\n\nDefinition qzt_put3 qa1 qa2 qa3 q1 q2 q3 :=\n  qzt_put1 qa1 (qzt_put1 qa2 (qzt_put1 qa3 (QztLeaf q1 q2 q3))).\n\nDefinition qzt_put3rot qa1 qa2 qa3 q1 q2 q3 t :=\n  qzt_put3 qa1 qa2 qa3 q1 q2 q3\n    (qzt_put3 qa2 qa3 qa1 q2 q3 q1 (qzt_put3 qa3 qa1 qa2 q3 q1 q2 t)).\n\nDefinition qzt_put (qa1 qa2 qa3 : qarity) q1 q2 q3 :=\n  if 8 < qa1 then qzt_put3 qa1 qa2 qa3 q1 q2 q3 else\n  qzt_put3rot qa1 qa2 qa3 q1 q2 q3.\n\nDefinition qzt_empty :=\n  let mkn t := QztNode t t t t in\n  let n2 := mkn (mkn QztNil) in QztHubNode (mkn n2) n2 n2 n2.\n\nDefinition normq q :=\n  match q with\n  | Qask1 qa => QaskLR qa Qask0 Qask0\n  | QaskL qa ql => QaskLR qa ql Qask0\n  | QaskR qa qr => QaskLR qa Qask0 qr\n  | _ => q\n  end.\n\nDefinition store_qz qz :=\n  if qz is Quiz (QaskR qa1 q1) (QaskR qa2 q2) then\n      match normq q1, normq q2 with\n      | QaskLR qa1r q1l q1r, QaskLR qa2r q2l q2r =>\n          if qa1r < qa2r then qzt_put qa1 qa2 qa1r q1l q2 q1r else\n                              qzt_put qa1 qa2r qa2 q1 q2r q2l\n      | QaskLR qa1r q1l q1r, _ => qzt_put qa1 qa2 qa1r q1l q2 q1r\n      | _, QaskLR qa2r q2l q2r => qzt_put qa1 qa2r qa2 q1 q2r q2l\n      | _, _ => fun t => t\n      end\n  else fun t => t.\n\nDefinition store_cf_qz qz (sym : bool) t :=\n   store_qz qz (if sym then t else store_qz (flipqz qz) t).\n\nFixpoint cfquiz_tree_rec (qt : quiz_tree) (cfs : configseq)\n          {struct cfs} : quiz_tree :=\n  if cfs is Adds cf cfs' then\n    if store_cf_qz (cfquiz cf) (cfsym cf) qt is QztHubNode t58 t9 t10 t11 then\n      cfquiz_tree_rec (QztHubNode t58 t9 t10 t11) cfs'\n    else QztNil\n  else qt.\n\nDefinition cfquiz_tree := cfquiz_tree_rec qzt_empty.\n\n(* Sanity checks; both computations should return the same result *)\n(* (3361 for the full config list).                               *)\n\nFixpoint qzt_size (t : quiz_tree) : nat :=\n  match t with\n  | QztLeaf _ _ _ t' => S (qzt_size t')\n  | QztNode t5 t6 t7 t8 =>\n      qzt_size t5 + (qzt_size t6 + (qzt_size t7 + qzt_size t8))\n  | QztHubNode t58 t9 t10 t11 =>\n      qzt_size t58 + (qzt_size t9 + (qzt_size t10 + qzt_size t11))\n  | _ => 0\n  end.\n\nDefinition cf_main_arity cf :=\n  if cfquiz cf is Quiz (QaskR qa _) _ then qa : nat else 0.\n\nDefinition cf_qzt_size1 cf :=\n  let nperm := if cf_main_arity cf <= 8 then 3 else 1 in\n  if cfsym cf then nperm else double nperm.\n\nDefinition cf_qzt_size := foldr (fun cf => plus (cf_qzt_size1 cf)) 0.\n\nDefinition configs_compiled cfs := qzt_size (cfquiz_tree cfs) = cf_qzt_size cfs.\n\n(* end of sanity checks. *)\n\nFixpoint qzt_get1 (qa : qarity) (t : quiz_tree) {struct t} : quiz_tree :=\n  match t, qa with\n  | QztNode t' _ _ _, Qa5 => t'\n  | QztNode _ t' _ _, Qa6 => t'\n  | QztNode _ _ t' _, Qa7 => t'\n  | QztNode _ _ _ t', Qa8 => t'\n  | QztHubNode _ t' _ _, Qa9 => t'\n  | QztHubNode _ _ t' _, Qa10 => t'\n  | QztHubNode _ _ _ t', Qa11 => t'\n  | QztHubNode t' _ _ _, _ => qzt_get1 qa t'\n  | _, _ => QztNil\n  end.\n\nDefinition qzt_get2 qa2 qa3 t := qzt_get1 qa3 (qzt_get1 qa2 t).\n\nDefinition qzt_get3 qa1 qa2 qa3 t := qzt_get2 qa2 qa3 (qzt_get1 qa1 t).\n\nSection FitQuizTree.\n\nVariables (cfs : configseq) (g : hypermap).\nHypothesis Hg : plain_cubic g.\nLet De2 := plain_eq Hg.\nLet Dn3 := cubic_eq Hg.\n\nLemma fit_normq : forall (x : g) q, fitq x (normq q) = fitq x q.\nProof. by move=> x q; case: q => *; rewrite /fitq /= ?cats0. Qed.\n\nVariable x1 : g.\nNotation x2 := (node x1).\nNotation x3 := (node x2).\nLet ax1 := qarity_of_nat (arity x1).\nLet ax2 := qarity_of_nat (arity x2).\nLet ax3 := qarity_of_nat (arity x3).\n\nNotation \"x '=a' y\" := ((x : nat) =d arity y) (at level 70, only parsing).\nDefinition qzt_fita := and3b (ax1 =a x1) (ax2 =a x2) (ax3 =a x3).\n\nFixpoint qzt_fitl (t : quiz_tree) : bool :=\n  if t is QztLeaf q1 q2 q3 t' then\n      and3b (fitq (qstepR x1) q1) (fitq (qstepR x2) q2) (fitq (qstepR x3) q3)\n    || qzt_fitl t'\n  else false.\n\nDefinition qzt_fit t := qzt_fita && qzt_fitl (qzt_get3 ax1 ax2 ax3 t).\n\nNotation quiz3 := (fun qa1 qa2 qa3 q1 q2 q3 =>\n   Quiz (QaskR qa1 (QaskLR qa3 q1 q3)) (QaskR qa2 q2)).\n\nLemma qzt_get_put1 : forall qa qa' qr t,\n    qa = qa' /\\ qr (qzt_get1 qa t) = qzt_get1 qa (qzt_put1 qa' qr t)\n \\/ qzt_get1 qa t = qzt_get1 qa (qzt_put1 qa' qr t).\nProof. move=> qa qa' qr; elim; auto; case qa'; auto; case qa; auto. Qed.\n\nLet Hfp1 := qzt_get_put1.\nLemma qzt_fit_put3 : forall qa1 qa2 qa3 q1 q2 q3 t,\n                     qzt_fit (qzt_put3 qa1 qa2 qa3 q1 q2 q3 t) ->\n fitqz (edge x2) (quiz3 qa1 qa2 qa3 q1 q2 q3) \\/ qzt_fit t.\nProof.\nmove=> qa1 qa2 qa3 q1 q2 q3 t; case/andP=> [Hax]; rewrite /qzt_fit Hax.\nrewrite /fitqz /= /eqd /= eqseqE -arity_face Enode /qstepR De2 /qstepL Dn3 -!catA.\nrewrite /= 2!fitq_cat maps_adds eqseq_adds; case/and3P: Hax; do 3 move/eqP => <-.\nrewrite /qzt_get3 /qzt_get2 /qzt_put3; set qr := QztLeaf q1 q2 q3.\ncase: (Hfp1 ax1 qa1 (qzt_put1 qa2 (qzt_put1 qa3 qr)) t) => [[<- <-]|<-]; auto.\ncase: (Hfp1 ax2 qa2 (qzt_put1 qa3 qr) (qzt_get1 ax1 t)) => [[<- <-]|<-]; auto.\ncase: (Hfp1 ax3 qa3 qr (qzt_get1 ax2 (qzt_get1 ax1 t))) => [[<- <-]|<-]; auto.\nrewrite !set11 /= {1}[andb]lock andbC -lock; case/orP; auto.\nQed.\n\nLemma fitqz_rot : forall (y : g) qa1 qa2 qa3 q1 q2 q3,\n  fitqz y (quiz3 qa1 qa2 qa3 q1 q2 q3)\n   = fitqz (edge (face y)) (quiz3 qa3 qa1 qa2 q3 q1 q2).\nProof.\nmove=> y qa1 qa2 qa3 q1 q2 q3; rewrite /fitqz /= /eqd /= !eqseqE -!catA.\nrewrite !fitq_cat !maps_adds !eqseq_adds /qstepL /qstepR !De2 Eface.\nrewrite -{1}[node (edge y)]Enode !arity_face -{1 2}[edge y]Eedge De2 Dn3.\nrewrite -{8 9}[y]De2 Eedge.\ncase: (qa1 =a y) => /=; last by rewrite !andbF.\ncongr andb; rewrite andbC -!andbA.\nby case (qa2 =a edge y); last by rewrite /= !andbF.\nQed.\n\nLemma qzt_fit_put : forall qa1 qa2 qa3 q1 q2 q3 t,\n   qzt_fit (qzt_put qa1 qa2 qa3 q1 q2 q3 t) ->\n (exists y : g, fitqz y (quiz3 qa1 qa2 qa3 q1 q2 q3)) \\/ qzt_fit t.\nProof.\nmove=> qa1 qa2 qa3 q1 q2 q3 t; rewrite /qzt_put /qzt_put3rot.\ncase (8 < qa1); first by case/qzt_fit_put3; auto; left; exists (edge x2).\ncase/qzt_fit_put3; first by left; exists (edge x2).\ncase/qzt_fit_put3; first by rewrite fitqz_rot Enode; left; exists (edge x1).\ncase/qzt_fit_put3; auto.\nby rewrite 2!fitqz_rot -[x1]Dn3 !Enode; left; exists (edge x3).\nQed.\n\nLemma fitqz_swap : forall (y : g) qa1 qa2 qa3 q1 q2 q3,\n fitqz y (quiz3 qa1 qa2 qa3 q1 q2 q3) =\n   fitqz (face y) (Quiz (QaskR qa1 q1) (QaskR qa3 (QaskLR qa2 q3 q2))).\nProof.\nmove=> y qa1 qa2 qa3 q1 q2 q3; rewrite /fitqz /= /eqd /= !eqseqE -!catA.\nrewrite !fitq_cat !maps_adds !eqseq_adds fitq_cat.\nrewrite /qstepR /qstepL !De2 -{1}[node (edge y)]Enode !arity_face Eface.\nby rewrite -{1 2}[edge y]Eedge De2 Dn3 -{10 11}[y]De2 Eedge; repeat BoolCongr.\nQed.\n\nLemma qzt_fit_store : forall qz t, qzt_fit (store_qz qz t) ->\n  (isQuizR qz /\\ exists y : g, fitqz y qz) \\/ qzt_fit t.\nProof.\nmove=> [q1 q2] t; case: q1; auto; case: q2; auto => qa2 q2 qa1 q1 Hx.\nset qz := Quiz _ _; set G := (exists y : g, fitqz y qz) \\/ qzt_fit t.\nsuffice: G by move=> [H|H]; [ left; split | right ].\nhave HxG1: forall qa1r q1l q1r, normq q1 = QaskLR qa1r q1l q1r ->\n    qzt_fit (qzt_put qa1 qa2 qa1r q1l q2 q1r t) -> G.\n  move=> qa1r q1l q1r Dq1'; case/qzt_fit_put; last by right.\n  move=> [y Hy]; left; exists y; move: Hy; rewrite -Dq1' /fitqz /eqd /= !eqseqE.\n  by rewrite fitq_cat fit_normq -fitq_cat.\nhave HxG2: forall qa2r q2l q2r, normq q2 = QaskLR qa2r q2l q2r ->\n    qzt_fit (qzt_put qa1 qa2r qa2 q1 q2r q2l t) -> G.\n  move=> qa2r q2l q2r Dq2'; case/qzt_fit_put; last by right.\n  move=> [y Hy]; left; exists (face y); apply: etrans Hy.\n  rewrite fitqz_swap -Dq2' /fitqz /eqd /= !eqseqE !fitq_cat !maps_adds.\n  by rewrite !eqseq_adds !andbA; congr andb; symmetry; apply: fit_normq.\nmove: Hx; simpl; case: {-1}(normq q1) (erefl (normq q1));\n case: {-1}(normq q2) (erefl (normq q2)); first [ by right | eauto ].\nmove=> qa2r q2l q2r Dq2 qa1r q1l q1r Dq1; case (qa1r < qa2r); eauto.\nQed.\n\nLemma qzt_fit_store_cf : forall qz sym t, qzt_fit (store_cf_qz qz sym t) ->\n    isQuizR qz /\\ ((exists y : g, fitqz y qz) \\/ (exists y : mirror g, fitqz y qz))\n \\/ qzt_fit t.\nProof.\nmove=> qz sym t; rewrite /store_cf_qz /=.\ncase: sym; repeat case/qzt_fit_store; auto; move=> [Hqz Hgqz]; left;\n try by split; auto.\nhave Hqz': (isQuizR qz) by case: (qz) Hqz => [q1 q2]; case q1; case q2.\nsplit; auto; right; case: Hgqz => [y Hy]; rewrite fitqz_flip //= in Hy.\nby exists (face y).\nQed.\n\nLemma qzt_fit_cfquiz : forall cfs, qzt_fit (cfquiz_tree cfs) ->\n exists2 cf, cfs cf &\n exists2 qz, (exists y : g, fitqz y qz) \\/ (exists y : mirror g, fitqz y qz)\n          & embeddable (cfring cf) /\\ (exists u, valid_quiz (cfring cf) u qz).\nProof.\nmove=> cfs'; rewrite /cfquiz_tree.\nhave: qzt_fit qzt_empty = false.\n  by rewrite /qzt_fit andbC; case: ax1 => //; case: ax2 => //; case ax3.\nelim: cfs' qzt_empty => [|cf cfs' Hrec] qt0 Hqt0 /=; first by rewrite Hqt0.\nhave Hqt00: qzt_fit QztNil = false by apply: andbF.\nset qt := store_cf_qz _ _ qt0.\ncase Dqt: qt => [|q1 q2 q3 t|t5 t6 t7 t8|t58 t9 t10 t11]; try by rewrite Hqt00.\n rewrite -{t58 t9 t10 t11}Dqt => Hqt'; case Hqt: (qzt_fit qt).\n  case/qzt_fit_store_cf: Hqt; last by rewrite Hqt0.\n  move=> [Hqz Hgqz]; exists cf; [ apply: setU11 | exists (cfquiz cf); auto ].\n  by split; [ apply embeddable_cfquiz | apply valid_cfquiz ].\n  case: {Hrec Hqt' Hqt}(Hrec _ Hqt Hqt') => [cf' Hcf' Hx].\nby exists cf'; first by apply setU1r.\nQed.\n\nDefinition qzt_truncate t :=\n  if t is  QztHubNode (QztNode _ _ _ _ as t58) _ _ _ then t58 else t.\n\nLemma qzt_get1_truncate : forall qa t,\n let t' := qzt_get1 qa (qzt_truncate t) in\n qzt_proper t' -> t' = qzt_get1 qa t.\nProof. by do 3 case=> //. Qed.\n\nEnd FitQuizTree.\n\n(*  global sanity check, using the functions define above\nRequire configurations.\n\nEval Compute in (qzt_size (cfquiz_tree the_configs)).\nEval Compute in (cf_qzt_size the_configs).\nGoal (configs_compiled the_configs).\nSplit.\nSave the_configs_compiled.\n*)\n\n\nUnset Implicit Arguments.", "meta": {"author": "tangentforks", "repo": "FourColorTheorem", "sha": "eb30720f9e773fdcbf13dc6c61fdb245587cf401", "save_path": "github-repos/coq/tangentforks-FourColorTheorem", "path": "github-repos/coq/tangentforks-FourColorTheorem/FourColorTheorem-eb30720f9e773fdcbf13dc6c61fdb245587cf401/quiztree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.23086889855450624}}
{"text": "Require Import os_code_defs.\nRequire Import os_ucos_h.\n\nLocal Open Scope code_scope.\n\nDefinition PlaceHolder:= &ₐ OSPlaceHolder′.\n                          \n(*\nDefinition OSTaskChangePrio_impl :=\nInt32 ·OSTaskChangePrio·(⌞oldprio @ Int8u; newprio @ Int8u⌟)··{\n      ⌞\n        ptcb @ OS_TCB∗;\n        x @ Int8u;\n        y @ Int8u;\n        bitx @ Int8u;\n        bity @ Int8u\n      ⌟;\n\n      If( (oldprio′ ≥ ′OS_LOWEST_PRIO &&ₑ oldprio′ !=ₑ ′OS_PRIO_SELF) ||ₑ (newprio′ ≥ ′OS_LOWEST_PRIO) )\n      {\n        RETURN ′OS_PRIO_INVALID\n      };ₛ\n          \n      ENTER_CRITICAL;ₛ\n      If (OSTCBPrioTbl′[newprio′] !=ₑ NULL) (*newprio exist or newprio is vhold*)\n      {\n        EXIT_CRITICAL;ₛ\n        RETURN ′OS_PRIO_EXIST\n      };ₛ\n\n      If (oldprio′ ==ₑ ′OS_PRIO_SELF)\n      {\n        oldprio′ =ₑ OSTCBCur′→OSTCBPrio\n      };ₛ\n\n      If (OSTCBPrioTbl′[oldprio′] ==ₑ NULL)\n      {\n        EXIT_CRITICAL;ₛ\n        RETURN ′OS_PRIO_ERR\n      };ₛ\n\n      If (OSTCBPrioTbl′[oldprio′] ==ₑ PlaceHolder)\n      {\n        EXIT_CRITICAL;ₛ\n        RETURN ′OS_PRIO_ERR\n      };ₛ\n\n      y′ =ₑ ′newprio ≫ ′3;ₛ\n      bity′ =ₑ ′OSMapTbl[′y];ₛ\n      x′ =ₑ ′newprio &ₑ ′7;ₛ\n      bitx′ =ₑ ′OSMapTbl[′x];ₛ\n                    \n      ptcb′ =ₑ OSTCBPrioTbl′[oldprio′];ₛ\n      OSTCBPrioTbl′[oldprio′] =ₑ NULL;ₛ\n\n      IF((OSRdyTbl′[ptcb′→OSTCBY] &&ₑ ptcb′→OSTCBBitX) !=ₑ ′0)\n      {\n        OS_RdyTblClearBit(­ptcb′­);ₛ\n        OSRdyGrp′ =ₑ ′OSRdyGrp |ₑ ′bity;ₛ\n        OSRdyTbl′[y′] =ₑ ′OSRdyTbl[y′] |ₑ ′bitx\n      }\n      ELSE\n      {\n        pevent′ =ₑ ′ptcb→OSTCBEventPtr;ₛ\n        If(pevent′ !=ₑ NULL)\n        {\n          pevent′→OSEventTbl[ptcb′→OSTCBY] &= ∼ptcb′→OSTCBBitX;ₛ\n          If(pevent′→OSEventTbl[ptcb′→OSTCBY] ==ₑ ′0)\n          {\n            pevent′→OSEventGrp &= ′ptcb→OSTCBBitY\n          };ₛ\n          pevent′→OSEventGrp =ₑ pevent′→OSEventGrp |ₑ ′bity;ₛ\n          pevent′→OSEventTbl[y′] =ₑ pevent′→OSEventTbl[y′] |ₑ ′bitx\n        }        \n      };ₛ\n\n      OSTCBPrioTbl′[newprio′] =ₑ ′ptcb;ₛ\n      ptcb′→OSTCBPrio =ₑ ′newprio;ₛ\n      ptcb′→OSTCBY =ₑ ′y;ₛ\n      ptcb′→OSTCBX =ₑ ′x;ₛ\n      ptcb′→OSTCBBitY =ₑ ′bity;ₛ\n      ptcb′→OSTCBBitX =ₑ ′bitx;ₛ\n\n      EXIT_CRITICAL;ₛ\n      OS_Sched(­);ₛ\n      RETURN ′OS_NO_ERR\n }·.\n*)\nDefinition STKINIT (a : expr * expr * expr ) :=\n  let ( vt, v3 ) := a in let (v1, v2) := vt in  sprim (stkinit v1 v2 v3).\n\nDefinition OSTaskCreate_impl :=\nInt8u ·OSTaskCreate·(⌞task @ Void∗; pdata @ Void∗; prio @ Int8u⌟)··{\n       ⌞ err @ Int8u⌟;\n\n       If(prio′ >ₑ ′OS_LOWEST_PRIO) {\n           RETURN ′OS_PRIO_INVALID\n       };ₛ\n           \n       ENTER_CRITICAL;ₛ\n       If (OSTCBPrioTbl′[prio′] ==ₑ NULL){\n           (*OSTCBPrioTbl′[prio′] =ₑ ′ 1;ₛ (*Fix Me*)\n           EXIT_CRITICAL;ₛ *)\n         \n           err′ =ᶠ OS_TCBInit(·prio′ (*, task′, pdata′*) ·);ₛ\n           IF (err′ ==ₑ ′OS_NO_ERR) {\n               (*ENTER_CRITICAL;ₛ*)\n               STKINIT (task′, pdata′,  OSTCBPrioTbl′[prio′ ]);ₛ\n               (* ++ OSTaskCtr′;ₛ *)\n               EXIT_CRITICAL;ₛ\n               (* If (OSRunning′ ==ₑ CTrue) { *)\n                OS_Sched(­)\n               (* } *)\n           }ELSE{\n               (*ENTER_CRITICAL;ₛ*)\n               (* OSTCBPrioTbl′[prio′] =ₑ NULL;ₛ *)\n               EXIT_CRITICAL\n           };ₛ\n           RETURN  err′ \n       };ₛ\n       EXIT_CRITICAL;ₛ\n       RETURN  ′OS_PRIO_EXIST\n}·.\n\nDefinition STKFREE (a : expr ) :=\n  sprim (stkfree a).\n \nRequire Import inline_definitions.\nRequire Import inline_bittblfunctions.\n\nDefinition OSTaskDel_impl := \nInt8u ·OSTaskDel·(⌞prio @ Int8u⌟)··{\n      ⌞\n        pevent @ OS_EVENT∗;\n        ptcb @ OS_TCB∗;\n        self @ Int8u;\n        x @ OS_TCB∗\n      ⌟;\n(*      \n      If (OSIntNesting′ >ₑ ′0){\n          RETURN (OSTaskDel) ′OS_TASK_DEL_ISR\n      };ₛ\n*)\n\n      If (prio′ ==ₑ ′OS_IDLE_PRIO) {\n          RETURN ′OS_TASK_DEL_IDLE\n      };ₛ\n      If (prio′ ≥ ′OS_LOWEST_PRIO (* &&ₑ prio′ !=ₑ ′OS_PRIO_SELF *)){\n          RETURN ′OS_PRIO_INVALID\n      };ₛ\n      ENTER_CRITICAL;ₛ\n      (* If(prio′ ==ₑ ′OS_PRIO_SELF)\n       * {\n       *     prio′ =ₑ OSTCBCur′→OSTCBPrio;ₛ\n       *     If (prio′ ==ₑ ′OS_IDLE_PRIO)\n       *     {\n       *       EXIT_CRITICAL;ₛ\n       *       RETURN ′OS_TASK_DEL_IDLE\n       *     }\n       * };ₛ        *)\n      ptcb′ =ₑ OSTCBPrioTbl′[prio′];ₛ\n\n     If (ptcb′ ==ₑ NULL){\n        EXIT_CRITICAL;ₛ\n        RETURN ′OS_TASK_DEL_ERR\n      };ₛ\n      If (ptcb′ ==ₑ PlaceHolder){\n        EXIT_CRITICAL;ₛ\n        RETURN ′OS_TASK_DEL_ERR\n      };ₛ\n      self′ =ᶠ OS_IsSomeMutexOwner(·ptcb′·);ₛ\n      If (self′==ₑ ′ 1){\n        EXIT_CRITICAL;ₛ\n        RETURN ′OS_TASK_DEL_SOME_MUTEX_OWNER\n      };ₛ\n      If (ptcb′→OSTCBNext ==ₑ NULL){\n        EXIT_CRITICAL;ₛ\n        RETURN ′OS_TASK_DEL_HAS_NO_NEXT\n      };ₛ\n \n      (* If (ptcb′ !=ₑ NULL){ *)\n\n      inline_call inline_bittbl_clearbit ((OSRdyGrp ′):: (OSRdyTbl ′)::(ptcb ′ → OSTCBBitX)::(ptcb ′ → OSTCBBitY)::(ptcb ′ → OSTCBY)::nil);ₛ\n\n\n      (* OSRdyTbl′[ptcb′→OSTCBY] &= ∼ptcb′→OSTCBBitX;ₛ\n       * If(OSRdyTbl′[ptcb′→OSTCBY] ==ₑ ′0){\n       *     OSRdyGrp′  &= ∼ptcb′→OSTCBBitY\n       * };ₛ *)\n      pevent′ =ₑ ptcb′→OSTCBEventPtr;ₛ\n      If (pevent′ !=ₑ NULL){\n\n          inline_call inline_bittbl_clearbit ((pevent′→OSEventGrp):: (pevent′→OSEventTbl)::(ptcb ′ → OSTCBBitX)::(ptcb ′ → OSTCBBitY)::(ptcb ′ → OSTCBY)::nil)\n          (* pevent′→OSEventTbl[ptcb′→OSTCBY] =ₑ pevent′→OSEventTbl[ptcb′→OSTCBY] &ₑ (∼ptcb′→OSTCBBitX);ₛ\n           * If(pevent′→OSEventTbl[ptcb′→OSTCBY] ==ₑ ′0){\n           *     pevent′→OSEventGrp =ₑ pevent′→OSEventGrp &ₑ (∼ptcb′→OSTCBBitY)\n           * } *)\n      };ₛ\n      ptcb′→OSTCBDly =ₑ ′0;ₛ\n      ptcb′→OSTCBStat =ₑ ′OS_STAT_RDY;ₛ\n      (* −−OSTaskCtr′;ₛ *)\n      OSTCBPrioTbl′[prio′] =ₑ NULL;ₛ\n      ptcb′→OSTCBEventPtr =ₑ NULL;ₛ\n      IF (ptcb′→OSTCBPrev ==ₑ NULL){\n          x ′=ₑ ptcb′→OSTCBNext;ₛ\n          x′→OSTCBPrev =ₑ NULL;ₛ\n          OSTCBList′ =ₑ x′\n      }ELSE{\n          x′ =ₑ ptcb′→OSTCBPrev;ₛ\n          x′→OSTCBNext =ₑ ptcb′→OSTCBNext;ₛ\n          x′ =ₑ ptcb′→OSTCBNext;ₛ\n          x′→OSTCBPrev =ₑ ptcb′→OSTCBPrev\n      };ₛ\n      ptcb′→OSTCBNext =ₑ OSTCBFreeList′;ₛ\n      OSTCBFreeList′ =ₑ ptcb′;ₛ\n      STKFREE (    ptcb′  );ₛ\n      ptcb′→OSTCBflag =ₑ ′0;ₛ\n      EXIT_CRITICAL;ₛ\n      OS_Sched(­);ₛ\n      RETURN ′OS_NO_ERR\n      (* };ₛ *)\n      (* EXIT_CRITICAL;ₛ *)\n      (* RETURN ′OS_TASK_DEL_ERR *)\n}·. \n\n\n(* ** ac: Check (inline_call inline_bittbl_clearbit ((OSRdyGrp ′):: (OSRdyTbl ′)::(ptcb ′ → OSTCBBitX)::(ptcb ′ → OSTCBBitY)::(ptcb ′ → OSTCBY)::nil)) . *)\n(* ** ac: Eval simpl in (inline_call inline_bittbl_clearbit ((OSRdyGrp ′):: (OSRdyTbl ′)::(ptcb ′ → OSTCBBitX)::(ptcb ′ → OSTCBBitY)::(ptcb ′ → OSTCBY)::nil)). *)\n\n(* Eval simpl in (          inline_call inline_bittbl_clearbit ((pevent′→OSEventGrp):: (pevent′→OSEventTbl)::(ptcb ′ → OSTCBBitX)::(ptcb ′ → OSTCBBitY)::(ptcb ′ → OSTCBY)::nil)\n *)\n(*               ). *)\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/code/os_task.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.3415824927356586, "lm_q1q2_score": 0.23082935691860404}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import XOmega.\n\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import Conventions.\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\n\nRequire Import AbstractDataType.\nRequire Import Soundness.\n\nRequire Import SecurityCommon.\nRequire Import FunctionalExtensionality.\n\nOpen Scope Z_scope.\n\n(* This file defines the observation function for mCertiKOS.\n   Paper Reference: Section 4 *)\n\nSection WITHMEM.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n  Context `{Hcomp: CompatData RData}.\n\n  (* A typeclass for defining observation functions over mCertiKOS abstract state \n     (type cdata RData). As in the paper, the function takes both a principal\n     and a state as parameters, and produces a value of an arbitrary observation type.\n     Observable equivalence is defined to be equality of observations.\n     We add a property over principals to allow for distinguishing trusted processes\n     from untrusted processes (the final security proof will only apply to principals\n     for which the property holds). *)\n  Class Observer (obs : Type) :=\n    {\n      obs_id : Z;\n      obs_id_prop: obs_id > high_id;\n\n      observe : cdata RData -> obs;\n      obs_eq s1 s2 := observe s1 = observe s2\n    }.\n\n  Lemma obs_eq_equiv {obs} {o : Observer obs} : Equivalence (obs_eq(Observer:=o)).\n  Proof.\n    constructor; unfold obs_eq; congruence.\n  Qed.\n\n  Section OBS_EQ.\n\n    (* This is the virtual address space observation function, which produces\n       an option value for each virtual address location, based on whether\n       that location is mapped in the process's page tables. As explained in\n       the paper, it is *crucial* that this observation hides physical\n       address locations like the pi variable below (pi is the physical\n       page index; \"PTADRR pi vadr\" is defined as pi*PGSIZE + (vadr % PGSIZE)). *)\n\n    Function vread i vadr (ptp: PMapPool) (hp : FlatMem.flatmem) :=\n      (* User space addresses are between constants adr_low and adr_high *)\n      if zle_lt adr_low vadr adr_high then\n        (* first level of page tables *)\n        match ZMap.get (PDX vadr) (ZMap.get i ptp) with\n          | PDEValid _ pte =>\n            (* second level of page tables *)\n            match ZMap.get (PTX vadr) pte with\n              | PTEValid pi _ => Some (ZMap.get (PTADDR pi vadr) hp)\n              | _ => None\n            end\n          | _ => None\n        end\n      else None.\n\n    (* Various permission bits in the page tables must be observable. This\n       is mostly only needed for the SafeSecure lemma. *)\n\n    Inductive ObsPerm :=\n    | ObsValid : PTPerm -> PPgInfo -> ObsPerm\n    | ObsPDEID : ObsPerm\n    | ObsPDEUnPresent : ObsPerm\n    | ObsPDEUndef : ObsPerm\n    | ObsPTEUnPresent : ObsPerm\n    | ObsPTEUndef : ObsPerm.\n\n    Function vread_perm i vadr (ptp: PMapPool) (pp : PPermT) :=\n      if zle_lt adr_low vadr adr_high then\n        match ZMap.get (PDX vadr) (ZMap.get i ptp) with\n          | PDEValid _ pte =>\n            match ZMap.get (PTX vadr) pte with\n              | PTEValid v p => Some (ObsValid p (ZMap.get v pp))\n              | PTEUnPresent => Some ObsPTEUnPresent\n              | PTEUndef => Some ObsPTEUndef\n            end\n          | PDEUnPresent => Some ObsPDEUnPresent\n          | PDEID => Some ObsPDEID\n          | PDEUndef => Some ObsPDEUndef\n        end\n      else None.\n\n    (* The type of observations over abstract data *)\n    Record my_obs :=\n      {\n        observe_HP: Z -> option FlatMem.flatmem_val;\n        observe_perm: Z -> option ObsPerm;\n        observe_AC_quota: Z;\n        observe_AC_nchildren: nat;\n        observe_AC_used: bool;\n        observe_cid: bool;\n        observe_kctxt: regset;          \n        observe_uctxt: UContext;\n        observe_ti: option int;\n        observe_OUT: list DeviceAction;\n        observe_ikern: option bool;\n        observe_ihost: option bool;\n        observe_pg: option bool;\n        observe_ipt: option bool;\n        observe_init: option bool\n      }.\n\n    (* For some reason, the f_equal tactic takes an extremely long time for this definition \n       of my_obs (too many fields maybe?). Following is a specialization of the tactic\n       that terminates immediately. *)\n    Fact f_equal_my_obs :\n      forall a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15\n             b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15,\n        a1 = b1 -> a2 = b2 -> a3 = b3 -> a4 = b4 -> a5 = b5 -> \n        a6 = b6 -> a7 = b7 -> a8 = b8 -> a9 = b9 -> a10 = b10 -> \n        a11 = b11 -> a12 = b12 -> a13 = b13 -> a14 = b14 -> a15 = b15 ->\n        Build_my_obs a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 =\n        Build_my_obs b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15.\n    Proof.\n      intros; subst; reflexivity.\n    Qed.\n\n    (* The observation function for abstract data.\n       Paper Reference: Section 4 *)\n    Definition my_observe (i: Z) (d: cdata RData) : my_obs :=\n      {|\n        observe_HP vadr:= vread i vadr (ptpool d) (HP d);\n        observe_perm vadr:= vread_perm i vadr (ptpool d) (pperm d);\n        observe_AC_quota:= \n          cquota (ZMap.get i (AC d)) - cusage (ZMap.get i (AC d));\n        observe_AC_nchildren:= length (cchildren (ZMap.get i (AC d)));\n        observe_AC_used:= cused (ZMap.get i (AC d));\n        observe_cid:= zeq i (cid d);\n        observe_kctxt:= ZMap.get i (kctxt d);          \n        observe_uctxt:= ZMap.get i (uctxt d);\n        observe_ti:= if zeq i (cid d) then Some (fst (ti d)) else None;\n        observe_OUT:= ZMap.get i (devout d);\n\n        (* the following global flags only need to be observable for the SafeSecure proof *)\n        observe_ikern:= if zeq i (cid d) then Some (ikern d) else None;\n        observe_ihost:= if zeq i (cid d) then Some (ihost d) else None;\n        observe_pg:= if zeq i (cid d) then Some (pg d) else None;\n        observe_ipt:= if zeq i (cid d) then Some (ipt d) else None;\n        observe_init:= if zeq i (cid d) then Some (init d) else None\n      |}.\n\n    (* An observable equivalence relation defined for convenience *)\n    Record my_obs_eq (i: Z) (d1 d2: cdata RData) :=\n      {\n        obs_eq_HP: \n          forall vadr, \n            vread i vadr (ptpool d1) (HP d1) = vread i vadr (ptpool d2) (HP d2);\n        obs_eq_perm: \n          forall vadr, \n            vread_perm i vadr (ptpool d1) (pperm d1) = vread_perm i vadr (ptpool d2) (pperm d2);\n        obs_eq_AC_quota: \n          cquota (ZMap.get i (AC d1)) - cusage (ZMap.get i (AC d1)) = \n          cquota (ZMap.get i (AC d2)) - cusage (ZMap.get i (AC d2));\n        obs_eq_AC_nchildren: length (cchildren (ZMap.get i (AC d1))) = \n                             length (cchildren (ZMap.get i (AC d2)));\n        obs_eq_AC_used: cused (ZMap.get i (AC d1)) = cused (ZMap.get i (AC d2));\n        obs_eq_cid: i = cid d1 <-> i = cid d2;\n        obs_eq_kctxt: ZMap.get i (kctxt d1) = ZMap.get i (kctxt d2);          \n        obs_eq_uctxt: ZMap.get i (uctxt d1) = ZMap.get i (uctxt d2);\n        obs_eq_ti: i = cid d1 -> fst (ti d1) = fst (ti d2);\n        obs_eq_OUT: ZMap.get i (devout d1) = ZMap.get i (devout d2);\n        obs_eq_ikern: i = cid d1 -> ikern d1 = ikern d2;\n        obs_eq_ihost: i = cid d1 -> ihost d1 = ihost d2;\n        obs_eq_pg: i = cid d1 -> pg d1 = pg d2;\n        obs_eq_ipt: i = cid d1 -> ipt d1 = ipt d2;\n        obs_eq_init: i = cid d1 -> init d1 = init d2\n      }.\n\n    (* Proof that the observable equivalence relation is \n       consistent with the observation function *)\n    Lemma my_obs_eq_convert : \n      forall i d1 d2, my_obs_eq i d1 d2 <-> my_observe i d1 = my_observe i d2.\n    Proof.\n      intros i d1 d2; split; intro.\n      - unfold my_observe.\n        apply f_equal_my_obs.\n        + extensionality vadr; apply obs_eq_HP; auto.\n        + extensionality vadr; apply obs_eq_perm; auto.\n        + apply obs_eq_AC_quota; auto.\n        + apply obs_eq_AC_nchildren; auto.\n        + apply obs_eq_AC_used; auto.\n        + destruct (zeq i (cid d1)); destruct (zeq i (cid d2)); simpl; auto.\n          erewrite obs_eq_cid in e; eauto; contradiction.\n          erewrite <- obs_eq_cid in e; eauto; contradiction.\n        + apply obs_eq_kctxt; auto.\n        + apply obs_eq_uctxt; auto.\n        + destruct (zeq i (cid d1)); destruct (zeq i (cid d2)); simpl; auto.\n          f_equal; eapply obs_eq_ti; eauto.\n          erewrite obs_eq_cid in e; eauto; contradiction.\n          erewrite <- obs_eq_cid in e; eauto; contradiction.\n        + apply obs_eq_OUT; auto.\n        + destruct (zeq i (cid d1)); destruct (zeq i (cid d2)); simpl; auto.\n          f_equal; eapply obs_eq_ikern; eauto.\n          erewrite obs_eq_cid in e; eauto; contradiction.\n          erewrite <- obs_eq_cid in e; eauto; contradiction.\n        + destruct (zeq i (cid d1)); destruct (zeq i (cid d2)); simpl; auto.\n          f_equal; eapply obs_eq_ihost; eauto.\n          erewrite obs_eq_cid in e; eauto; contradiction.\n          erewrite <- obs_eq_cid in e; eauto; contradiction.\n        + destruct (zeq i (cid d1)); destruct (zeq i (cid d2)); simpl; auto.\n          f_equal; eapply obs_eq_pg; eauto.\n          erewrite obs_eq_cid in e; eauto; contradiction.\n          erewrite <- obs_eq_cid in e; eauto; contradiction.\n        + destruct (zeq i (cid d1)); destruct (zeq i (cid d2)); simpl; auto.\n          f_equal; eapply obs_eq_ipt; eauto.\n          erewrite obs_eq_cid in e; eauto; contradiction.\n          erewrite <- obs_eq_cid in e; eauto; contradiction.\n        + destruct (zeq i (cid d1)); destruct (zeq i (cid d2)); simpl; auto.\n          f_equal; eapply obs_eq_init; eauto.\n          erewrite obs_eq_cid in e; eauto; contradiction.\n          erewrite <- obs_eq_cid in e; eauto; contradiction.\n      - inv H; constructor; auto; \n          try solve [destruct (zeq i (cid d1)); destruct (zeq i (cid d2)); inv H6; intuition].\n        + apply equal_f; auto.\n        + apply equal_f; auto.\n    Qed.\n\n  End OBS_EQ.\n\n  Section WITHOBS.\n\n    Variable id : Z.\n    \n    Hypothesis id_prop: id > high_id.\n\n    Instance user_observer : Observer my_obs.\n    Proof.\n      apply (Build_Observer _ id id_prop (my_observe id)).\n    Defined.\n\n  End WITHOBS.\n\nEnd WITHMEM.\n\n  Lemma quota_convert :\n    forall x y, (x <? y) = (0 <? y - x).\n  Proof.\n    intros.\n    destruct (x <? y) eqn:H1; destruct (0 <? y - x) eqn:H2; auto.\n    rewrite Z.ltb_lt in H1; rewrite Z.ltb_nlt in H2; omega.\n    rewrite Z.ltb_nlt in H1; rewrite Z.ltb_lt in H2; omega.\n  Qed.\n\n  Lemma quota_convert' :\n    forall x y, (cusage x <? cquota y) = (0 <? cquota y - cusage x).\n  Proof.\n    intros; apply quota_convert.\n  Qed.\n\n  Close Scope Z_scope.\n\n  Ltac obs_eq_rewrite Hobs_eq :=\n      try rewrite <- (obs_eq_HP _ _ _ Hobs_eq) in *;\n      try rewrite quota_convert' in *;\n      try rewrite <- (obs_eq_AC_quota _ _ _ Hobs_eq) in *;\n      try rewrite <- (obs_eq_AC_nchildren _ _ _ Hobs_eq) in *;\n      try rewrite <- (obs_eq_AC_used _ _ _ Hobs_eq) in *;\n      try match goal with\n            | [ H : id = cid ?d |- _ ] =>\n              rewrite <- H in *;\n              rewrite <- (proj1 (obs_eq_cid _ _ _ Hobs_eq)) in *; auto\n          end;\n      auto; try rewrite <- (obs_eq_kctxt _ _ _ Hobs_eq) in *;\n      try rewrite <- (obs_eq_uctxt _ _ _ Hobs_eq) in *;\n      try rewrite <- (obs_eq_OUT _ _ _ Hobs_eq) in *;\n      try rewrite <- (obs_eq_ti _ _ _ Hobs_eq) in *; auto.\n\n  Ltac obs_eq_rewrites Hobs_eq := repeat obs_eq_rewrite Hobs_eq.\n\n  Ltac solve_obs_eq Hobs_eq := \n    destruct Hobs_eq; constructor; simpl; auto; zmap_solve; try congruence.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/security/ObsEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.23077619959095882}}
{"text": "Require Import Coq.Sorting.Permutation.\nRequire Import Coq.Sorting.Sorting.\nRequire Import Coq.Structures.Orders.\nRequire Import VST.veric.base.\nRequire Import VST.veric.Clight_lemmas.\nRequire Import VST.veric.type_induction.\nRequire Import VST.veric.composite_compute.\n\n(* This file contains three computational align criteria.\n   1: the hardware alignof is not larger than alignof (and additional criterion for array).\n   2: all fields are aligned as hardware requires. size as a multiple of hardware alignof.\n   3: all value is well-aligned stored.\n   The third one is the final specification we want. *)\n\nSection align_compatible_rec.\n\nContext (cenv: composite_env).\n\nInductive align_compatible_rec: type -> Z -> Prop :=\n| align_compatible_rec_by_value: forall t ch z, access_mode t = By_value ch -> (Memdata.align_chunk ch | z) -> align_compatible_rec t z\n| align_compatible_rec_Tarray: forall t n a z, (forall i, 0 <= i < n -> align_compatible_rec t (z + sizeof cenv t * i)) -> align_compatible_rec (Tarray t n a) z\n| align_compatible_rec_Tstruct: forall i a co z, cenv ! i = Some co -> (forall i0 t0 z0, field_type i0 (co_members co) = Errors.OK t0 -> field_offset cenv i0 (co_members co) = Errors.OK z0 -> align_compatible_rec t0 (z + z0)) -> align_compatible_rec (Tstruct i a) z\n| align_compatible_rec_Tunion: forall i a co z, cenv ! i = Some co -> (forall i0 t0, field_type i0 (co_members co) = Errors.OK t0 -> align_compatible_rec t0 z) -> align_compatible_rec (Tunion i a) z.\n\nLemma align_compatible_rec_by_value_inv : forall t ch z,\n  access_mode t = By_value ch ->\n  align_compatible_rec t z -> (Memdata.align_chunk ch | z).\nProof.\n  intros.\n  inv H0.\n  + rewrite H in H1; inv H1; auto.\n  + inv H.\n  + inv H.\n  + inv H.\nQed.\n\nLemma align_compatible_rec_Tarray_inv: forall t n a z,\n  align_compatible_rec (Tarray t n a) z ->\n  (forall i : Z, 0 <= i < n -> align_compatible_rec t (z + sizeof cenv t * i)).\nProof.\n  intros.\n  inv H.\n  + inv H1.\n  + auto.\nQed.\n\nLemma align_compatible_rec_Tstruct_inv: forall i a co z,\n  cenv ! i = Some co ->\n  align_compatible_rec (Tstruct i a) z ->\n  (forall i0 t0 z0, field_type i0 (co_members co) = Errors.OK t0 -> field_offset cenv i0 (co_members co) = Errors.OK z0 -> align_compatible_rec t0 (z + z0)).\nProof.\n  intros.\n  inv H0.\n  + inv H3.\n  + rewrite H in H5; inv H5.\n    eauto.\nQed.\n  \nLemma align_compatible_rec_Tunion_inv: forall i a co z,\n  cenv ! i = Some co ->\n  align_compatible_rec (Tunion i a) z ->\n  (forall i0 t0, field_type i0 (co_members co) = Errors.OK t0 -> align_compatible_rec t0 z).\nProof.\n  intros.\n  inv H0.\n  + inv H2.\n  + rewrite H in H4; inv H4.\n    eauto.\nQed.\n\nEnd align_compatible_rec.\n\nLemma align_chunk_1248: forall ch, align_chunk ch = 1 \\/ align_chunk ch = 2 \\/ align_chunk ch = 4 \\/ align_chunk ch = 8.\nProof.\n  intros.\n  destruct ch; simpl;\n  auto.\nQed.\n\nLemma align_chunk_two_p:\n  forall ch, exists n, align_chunk ch = two_power_nat n.\nProof.\n  intros.\n  pose proof align_chunk_1248 ch as [| [| [|]]]; rewrite H.\n  + exists 0%nat; auto.\n  + exists 1%nat; auto.\n  + exists 2%nat; auto.\n  + exists 3%nat; auto.\nQed.\n\nFixpoint hardware_alignof (ha_env: PTree.t Z) t: Z :=\n  match t with\n  | Tarray t' _ _ => hardware_alignof ha_env t'\n  | Tstruct id _ =>\n      match ha_env ! id with\n      | Some ha => ha\n      | None => 1\n      end\n  | Tunion id _ =>\n      match ha_env ! id with\n      | Some ha => ha\n      | None => 1\n      end\n  | _ => match access_mode t with\n         | By_value ch => Memdata.align_chunk ch\n         | _ => 1\n         end\n  end.\n\nFixpoint hardware_alignof_composite (ha_env: PTree.t Z) (m: members): Z :=\n  match m with\n  | nil => 1\n  | (_, t) :: m' => Z.max (hardware_alignof ha_env t) (hardware_alignof_composite ha_env m')\n  end.\n\nDefinition hardware_alignof_env (cenv: composite_env): PTree.t Z :=\n  let l := composite_reorder.rebuild_composite_elements cenv in\n  fold_right (fun (ic: positive * composite) (T0: PTree.t Z) => let (i, co) := ic in let T := T0 in PTree.set i (hardware_alignof_composite T (co_members co)) T) (PTree.empty _) l.\n\nDefinition hardware_alignof_env_consistent (cenv: composite_env) (ha_env: PTree.t Z): Prop :=\n  forall i co ha,\n    cenv ! i = Some co ->\n    ha_env ! i = Some ha ->\n    ha = hardware_alignof_composite ha_env (co_members co).\n\nDefinition hardware_alignof_env_complete (cenv: composite_env) (ha_env: PTree.t Z): Prop :=\n  forall i,\n    (exists co, cenv ! i = Some co) <->\n    (exists ha, ha_env ! i = Some ha).\n\nModule Type HARDWARE_ALIGNOF_FACTS.\n\n  Axiom hardware_alignof_consistency:\n    forall (cenv: composite_env) (ha_env: PTree.t Z),\n      composite_env_consistent cenv ->\n      ha_env = hardware_alignof_env cenv ->\n      hardware_alignof_env_consistent cenv ha_env.\n\n  Axiom hardware_alignof_completeness:\n    forall (cenv: composite_env) (ha_env: PTree.t Z),\n      ha_env = hardware_alignof_env cenv ->\n      hardware_alignof_env_complete cenv ha_env.\n\nEnd HARDWARE_ALIGNOF_FACTS.\n\nModule hardware_alignof_facts: HARDWARE_ALIGNOF_FACTS.\n\nLemma aux1: forall T co,\n  (fix fm (l : list (ident * type * Z)) : Z :=\n     match l with\n     | nil => 1\n     | (_, _, ha) :: l' => Z.max ha (fm l')\n     end)\n    (map\n       (fun it0 : positive * type =>\n        let (i0, t0) := it0 in\n        (i0, t0,\n        type_func.F\n          (fun t : type =>\n           match access_mode t with\n           | By_value ch => align_chunk ch\n           | By_reference => 1\n           | By_copy => 1\n           | By_nothing => 1\n           end) (fun (ha : Z) (_ : type) (_: Z) (_ : attr) => ha)\n          (fun (ha : Z) (_ : ident) (_ : attr) => ha)\n          (fun (ha : Z) (_ : ident) (_ : attr) => ha) T t0)) (co_members co)) =\n                    hardware_alignof_composite T (co_members co).\nProof.\n  intros; unfold hardware_alignof_composite, hardware_alignof.\n  induction (co_members co) as [| [i t] ?].\n  + auto.\n  + simpl.\n    f_equal; auto.\n    clear.\n    induction t; auto.\nQed.\n\nLemma aux2: forall (cenv: composite_env),\n  type_func.Env\n          (fun t : type =>\n           match access_mode t with\n           | By_value ch => align_chunk ch\n           | By_reference => 1\n           | By_copy => 1\n           | By_nothing => 1\n           end) (fun (ha : Z) (_ : type) (_: Z) (_ : attr) => ha)\n          (fun (ha : Z) (_ : ident) (_ : attr) => ha)\n          (fun (ha : Z) (_ : ident) (_ : attr) => ha)\n          (fun _ : struct_or_union =>\n           fix fm (l : list (ident * type * Z)) : Z :=\n             match l with\n             | nil => 1\n             | (_, _, ha) :: l' => Z.max ha (fm l')\n             end) (composite_reorder.rebuild_composite_elements cenv) =\n  hardware_alignof_env cenv.\nProof.\n  intros.\n  unfold type_func.Env, type_func.env_rec, hardware_alignof_env.\n  f_equal.\n  extensionality ic.\n  destruct ic as [i co].\n  extensionality T.\n  f_equal.\n  apply aux1.\nQed.\n\nLemma hardware_alignof_consistency (cenv: composite_env) (ha_env: PTree.t Z):\n  composite_env_consistent cenv ->\n  ha_env = hardware_alignof_env cenv ->\n  forall i co ha,\n    cenv ! i = Some co ->\n    ha_env ! i = Some ha ->\n    ha = hardware_alignof_composite ha_env (co_members co).\nProof.\n  intros.\n  pose proof @composite_reorder_consistent Z cenv\n             (fun t =>\n                match access_mode t with\n                | By_value ch => Memdata.align_chunk ch\n                | _ => 1\n                end)\n             (fun ha _ _ _ => ha)\n             (fun ha _ _ => ha)\n             (fun ha _ _ => ha)\n             (fun _ =>\n                fix fm (l: list (ident * type * Z)): Z :=\n                match l with\n                | nil => 1\n                | (_, _, ha) :: l' => Z.max ha (fm l')\n                end)\n             H\n    as HH.\n  hnf in HH.\n  subst ha_env.\n  rewrite aux2 in HH.\n  specialize (HH _ _ ha H1 H2).\n  rewrite HH, aux1; auto.\nQed.\n\nLemma hardware_alignof_completeness (cenv: composite_env) (ha_env: PTree.t Z):\n  ha_env = hardware_alignof_env cenv ->\n  forall i,\n    (exists co, cenv ! i = Some co) <->\n    (exists ha, ha_env ! i = Some ha).\nProof.\n  intros.\n  pose proof @composite_reorder_complete Z cenv\n             (fun t =>\n                match access_mode t with\n                | By_value ch => Memdata.align_chunk ch\n                | _ => 1\n                end)\n             (fun ha _ _ _ => ha)\n             (fun ha _ _ => ha)\n             (fun ha _ _ => ha)\n             (fun _ =>\n                fix fm (l: list (ident * type * Z)): Z :=\n                match l with\n                | nil => 1\n                | (_, _, ha) :: l' => Z.max ha (fm l')\n                end)\n    as HH.\n  hnf in HH.\n  subst.\n  rewrite aux2 in HH.\n  auto.\nQed.\n\nEnd hardware_alignof_facts.\n\nExport hardware_alignof_facts.\n\nLemma hardware_alignof_two_p: forall (cenv: composite_env) (ha_env: PTree.t Z),\n  composite_env_consistent cenv ->\n  hardware_alignof_env_consistent cenv ha_env ->\n  hardware_alignof_env_complete cenv ha_env ->\n  forall t, exists n,\n  hardware_alignof ha_env t = two_power_nat n.\nProof.\n  intros ? ? CENV_CONS HA_ENV_CONS HA_ENV_COMPL ?.\n  type_induction t cenv CENV_CONS.\n  + exists 0%nat; reflexivity.\n  + destruct s, i; try solve [exists 0%nat; reflexivity | exists 1%nat; reflexivity | exists 2%nat; reflexivity | exists 3%nat; reflexivity].\n  + destruct s; try solve [exists 0%nat; reflexivity | exists 1%nat; reflexivity | exists 2%nat; reflexivity | exists 3%nat; reflexivity].\n  + destruct f; try solve [exists 0%nat; reflexivity | exists 1%nat; reflexivity | exists 2%nat; reflexivity | exists 3%nat; reflexivity].\n  + exists 2%nat; reflexivity.\n  + simpl.\n    auto.\n  + exists 0%nat; reflexivity.\n  + simpl.\n    pose proof HA_ENV_CONS id; pose proof HA_ENV_COMPL id.\n    destruct (cenv ! id) as [co |] eqn:?H, (ha_env ! id) eqn:?H.\n    Focus 2. { pose proof proj1 H0 (ex_intro _ _ eq_refl) as [? ?]; congruence. } Unfocus.\n    Focus 2. { pose proof proj2 H0 (ex_intro _ _ eq_refl) as [? ?]; congruence. } Unfocus.\n    - specialize (H _ _ eq_refl eq_refl).\n      subst z.\n      clear - IH.\n      induction IH.\n      * exists 0%nat; reflexivity.\n      * destruct x as [i t], H as [n1 ?], IHIH as [n2 ?].\n        simpl in H |- *.\n        rewrite H, H0.\n        rewrite max_two_power_nat.\n        eexists; reflexivity.\n    - exists 0%nat; reflexivity.\n  + simpl.\n    pose proof HA_ENV_CONS id; pose proof HA_ENV_COMPL id.\n    destruct (cenv ! id) as [co |] eqn:?H, (ha_env ! id) eqn:?H.\n    Focus 2. { pose proof proj1 H0 (ex_intro _ _ eq_refl) as [? ?]; congruence. } Unfocus.\n    Focus 2. { pose proof proj2 H0 (ex_intro _ _ eq_refl) as [? ?]; congruence. } Unfocus.\n    - specialize (H _ _ eq_refl eq_refl).\n      subst z.\n      clear - IH.\n      induction IH.\n      * exists 0%nat; reflexivity.\n      * destruct x as [i t], H as [n1 ?], IHIH as [n2 ?].\n        simpl in H |- *.\n        rewrite H, H0.\n        rewrite max_two_power_nat.\n        eexists; reflexivity.\n    - exists 0%nat; reflexivity.\nQed.\n\nLemma hardware_alignof_pos: forall (cenv: composite_env) (ha_env: PTree.t Z),\n  composite_env_consistent cenv ->\n  hardware_alignof_env_consistent cenv ha_env ->\n  hardware_alignof_env_complete cenv ha_env ->\n  forall t,\n  hardware_alignof ha_env t > 0.\nProof.\n  intros.\n  pose proof hardware_alignof_two_p _ _ H H0 H1 t as [n ?].\n  rewrite H2.\n  apply two_power_nat_pos.\nQed.\n\nLemma hardware_alignof_composite_two_p: forall (cenv: composite_env) (ha_env: PTree.t Z),\n  composite_env_consistent cenv ->\n  hardware_alignof_env_consistent cenv ha_env ->\n  hardware_alignof_env_complete cenv ha_env ->\n  forall m, exists n,\n    hardware_alignof_composite ha_env m = two_power_nat n.\nProof.\n  intros.\n  induction m as [| [i t] ?].\n  + exists 0%nat.\n    reflexivity.\n  + destruct IHm as [n1 ?], (hardware_alignof_two_p _ _ H H0 H1 t) as [n2 ?].\n    simpl.\n    rewrite H2, H3.\n    rewrite max_two_power_nat.\n    eexists; reflexivity.\nQed.\n\nHint Resolve alignof_two_p: align.\nHint Resolve align_chunk_two_p: align.\nHint Extern 10 (exists n: nat, hardware_alignof _ _ = two_power_nat n) => (eapply hardware_alignof_two_p; eassumption): align.\nHint Extern 10 (exists n: nat, hardware_alignof_composite _ _ = two_power_nat n) => (eapply hardware_alignof_composite_two_p; eassumption): align.\n\nLemma hardware_alignof_by_value: forall ha_env t ch,\n  access_mode t = By_value ch ->\n  hardware_alignof ha_env t = align_chunk ch.\nProof.\n  intros.\n  destruct t as [| [| | |] [|] | [|] | [|] | | | | |]; inv H; auto.\nQed.\n\nLemma align_compatible_rec_hardware_alignof_divide: forall cenv ha_env t z1 z2,\n  composite_env_consistent cenv ->\n  composite_env_complete_legal_cosu_type cenv ->\n  hardware_alignof_env_consistent cenv ha_env ->\n  hardware_alignof_env_complete cenv ha_env ->\n  complete_legal_cosu_type cenv t = true ->\n  (hardware_alignof ha_env t | z1 - z2) ->\n  (align_compatible_rec cenv t z1 <-> align_compatible_rec cenv t z2).\nProof.\n  intros ? ? ? ? ? CENV_CONS CENV_COSU HA_ENV_CONS HA_ENV_COMPL.\n  revert t z1 z2.\n  assert (BY_VALUE: forall t z1 z2, (exists ch, access_mode t = By_value ch) -> (hardware_alignof ha_env t | z1 - z2) -> align_compatible_rec cenv t z1 <-> align_compatible_rec cenv t z2).\n  Focus 1. {\n    intros ? ? ? [? ?] ?.\n    split; intros.\n    + eapply align_compatible_rec_by_value_inv in H1; eauto.\n      eapply align_compatible_rec_by_value; eauto.\n      replace z2 with (z1 - (z1 - z2)) by omega.\n      erewrite hardware_alignof_by_value in H0 by eauto.\n      apply Z.divide_sub_r; auto.\n    + eapply align_compatible_rec_by_value_inv in H1; eauto.\n      eapply align_compatible_rec_by_value; eauto.\n      replace z1 with (z2 + (z1 - z2)) by omega.\n      erewrite hardware_alignof_by_value in H0 by eauto.\n      apply Z.divide_add_r; auto.\n  } Unfocus.\n  intro t; type_induction t cenv CENV_CONS; intros.\n  + split; intros; inv H1; inv H2.\n  + eapply BY_VALUE; auto.\n    destruct s, i; eexists; reflexivity.\n  + eapply BY_VALUE; auto.\n    destruct s; eexists; reflexivity.\n  + eapply BY_VALUE; auto.\n    destruct f; eexists; reflexivity.\n  + eapply BY_VALUE; auto.\n    eexists; reflexivity.\n  + simpl in H0.\n    split; intros; apply align_compatible_rec_Tarray; intros;\n    eapply align_compatible_rec_Tarray_inv in H1; eauto.\n    - specialize (IH (z1 + sizeof cenv t0 * i) (z2 + sizeof cenv t0 * i)).\n      replace (z1 + sizeof cenv t0 * i - (z2 + sizeof cenv t0 * i)) with (z1 - z2) in IH by omega.\n      tauto.\n    - specialize (IH (z1 + sizeof cenv t0 * i) (z2 + sizeof cenv t0 * i)).\n      replace (z1 + sizeof cenv t0 * i - (z2 + sizeof cenv t0 * i)) with (z1 - z2) in IH by omega.\n      tauto.\n  + split; intros; inv H1; inv H2; econstructor.\n  + simpl in H, H0.\n    destruct (cenv ! id) as [co |] eqn:?H; [| inv H].\n    destruct (co_su co) eqn:?H; inv H.\n    assert (forall i0 t0 ofs0,\n              field_type i0 (co_members co) = Errors.OK t0 ->\n              field_offset cenv i0 (co_members co) = Errors.OK ofs0 ->\n              (align_compatible_rec cenv t0 (z1 + ofs0) <->\n               align_compatible_rec cenv t0 (z2 + ofs0))) as HH;\n    [ | split; intros; eapply align_compatible_rec_Tstruct; eauto;\n        intros; eapply align_compatible_rec_Tstruct_inv in H; eauto;\n        eapply HH; eauto].\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ co H1) as [ha ?].\n    rewrite H in H0.\n    pose proof HA_ENV_CONS _ _ _ H1 H.\n    rewrite H3 in H0.\n    pose proof CENV_COSU _ _ H1.\n    clear H H1 H2 H3 ha.\n    intros. clear H1.\n    induction IH as [| [i t] ?].\n    - inv H.\n    - simpl in H, H0, H4.\n      autorewrite with align in H0, H4.\n      if_tac in H.\n      * subst i; inv H.\n        apply H1; [simpl; tauto |].\n        replace (z1 + ofs0 - (z2 + ofs0)) with (z1 - z2) by omega; tauto.\n      * apply IHIH; tauto.\n  + simpl in H, H0.\n    destruct (cenv ! id) as [co |] eqn:?H; [| inv H].\n    destruct (co_su co) eqn:?H; inv H.\n    assert (forall i0 t0,\n              field_type i0 (co_members co) = Errors.OK t0 ->\n              (align_compatible_rec cenv t0 z1 <->\n               align_compatible_rec cenv t0 z2)) as HH;\n    [ | split; intros; eapply align_compatible_rec_Tunion; eauto;\n        intros; eapply align_compatible_rec_Tunion_inv in H; eauto;\n        eapply HH; eauto].\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ co H1) as [ha ?].\n    rewrite H in H0.\n    pose proof HA_ENV_CONS _ _ _ H1 H.\n    rewrite H3 in H0.\n    pose proof CENV_COSU _ _ H1.\n    clear H H1 H2 H3 ha.\n    intros.\n    induction IH as [| [i t] ?].\n    - inv H.\n    - simpl in H, H0, H4.\n      autorewrite with align in H0, H4.\n      if_tac in H.\n      * subst i; inv H.\n        apply H1; simpl; tauto.\n      * apply IHIH; tauto.\nQed.\n\nLemma align_compatible_rec_hardware_1: forall cenv ha_env t z,\n  composite_env_consistent cenv ->\n  composite_env_complete_legal_cosu_type cenv ->\n  hardware_alignof_env_consistent cenv ha_env ->\n  hardware_alignof_env_complete cenv ha_env ->\n  complete_legal_cosu_type cenv t = true ->\n  hardware_alignof ha_env t = 1 ->\n  align_compatible_rec cenv t z.\nProof.\n  intros ? ? ? ? CENV_CONS CENV_COSU HA_ENV_CONS HA_ENV_COMPL.\n  revert z; type_induction t cenv CENV_CONS; intros.\n  + inv H.\n  + destruct s, i; inv H0;\n    econstructor; try reflexivity; apply Z.divide_1_l.\n  + destruct s; inv H0.\n  + destruct f; inv H0.\n  + inv H0.\n  + apply align_compatible_rec_Tarray.\n    intros.\n    apply IH; auto.\n  + inv H.\n  + simpl in H, H0.\n    destruct (cenv ! id) as [co |] eqn:?H; [| inv H].\n    destruct (co_su co) eqn:?H; inv H.\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ co H1) as [ha ?].\n    rewrite H in H0.\n    pose proof HA_ENV_CONS _ _ _ H1 H.\n    rewrite H3 in H0.\n    pose proof CENV_COSU _ _ H1.\n    eapply align_compatible_rec_Tstruct; eauto.\n    clear H H1 H2 H3 ha.\n    intros; clear H1.\n    induction IH as [| [i t] ?].\n    - inv H.\n    - simpl in H, H0, H4.\n      autorewrite with align in H0, H4.\n      destruct H0, H4.\n      if_tac in H.\n      * subst i; inv H.\n        apply H1; auto.\n      * apply IHIH; auto.\n  + simpl in H, H0.\n    destruct (cenv ! id) as [co |] eqn:?H; [| inv H].\n    destruct (co_su co) eqn:?H; inv H.\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ co H1) as [ha ?].\n    rewrite H in H0.\n    pose proof HA_ENV_CONS _ _ _ H1 H.\n    rewrite H3 in H0.\n    pose proof CENV_COSU _ _ H1.\n    eapply align_compatible_rec_Tunion; eauto.\n    clear H H1 H2 H3 ha.\n    intros.\n    induction IH as [| [i t] ?].\n    - inv H.\n    - simpl in H, H0, H4.\n      autorewrite with align in H0, H4.\n      destruct H0, H4.\n      if_tac in H.\n      * subst i; inv H.\n        apply H1; auto.\n      * apply IHIH; auto.\nQed.\n\nModule Type LEGAL_ALIGNAS.\n\n  Parameter legal_alignas_obs: Type.\n  Parameter legal_alignas_type: composite_env -> PTree.t Z -> PTree.t legal_alignas_obs -> type -> legal_alignas_obs.\n  Parameter legal_alignas_composite: composite_env -> PTree.t Z -> PTree.t legal_alignas_obs -> composite -> legal_alignas_obs.\n  Parameter legal_alignas_env: composite_env -> PTree.t Z -> PTree.t legal_alignas_obs.\n  Parameter is_aligned_aux: legal_alignas_obs -> Z -> Z -> bool.  \n\nEnd LEGAL_ALIGNAS.\n\nModule LegalAlignasDefsGen (LegalAlignas: LEGAL_ALIGNAS).\n\n  Import LegalAlignas.\n\n  Definition legal_alignas_env_consistent (cenv: composite_env) (ha_env: PTree.t Z) (la_env: PTree.t legal_alignas_obs): Prop :=\n    forall i co la,\n      cenv ! i = Some co ->\n      la_env ! i = Some la ->\n      la = legal_alignas_composite cenv ha_env la_env co.\n\n  Definition legal_alignas_env_complete (cenv: composite_env) (la_env: PTree.t legal_alignas_obs): Prop :=\n    forall i,\n      (exists co, cenv ! i = Some co) <->\n      (exists la, la_env ! i = Some la).\n\n  Definition is_aligned cenv ha_env la_env (t: type) (ofs: Z): bool := is_aligned_aux (legal_alignas_type cenv ha_env la_env t) (hardware_alignof ha_env t) ofs.\n\n  Definition legal_alignas_env_sound (cenv: composite_env) (ha_env: PTree.t Z) (la_env: PTree.t legal_alignas_obs): Prop :=\n    forall ofs t,\n      complete_legal_cosu_type cenv t = true ->\n      is_aligned cenv ha_env la_env t ofs = true ->\n      align_compatible_rec cenv t ofs.\n\nEnd LegalAlignasDefsGen.\n\nModule Type LEGAL_ALIGNAS_FACTS.\n\n  Declare Module LegalAlignas: LEGAL_ALIGNAS.\n  Module LegalAlignasDefs := LegalAlignasDefsGen (LegalAlignas).\n  Export LegalAlignas LegalAlignasDefs.\n\n  Axiom legal_alignas_env_consistency: forall cenv ha_env,\n    composite_env_consistent cenv ->\n    legal_alignas_env_consistent cenv ha_env (legal_alignas_env cenv ha_env).\n\n  Axiom legal_alignas_env_completeness: forall cenv ha_env,\n    legal_alignas_env_complete cenv (legal_alignas_env cenv ha_env).\n\n  Axiom legal_alignas_soundness: forall cenv ha_env la_env,\n    composite_env_consistent cenv ->\n    composite_env_complete_legal_cosu_type cenv ->\n    hardware_alignof_env_consistent cenv ha_env ->\n    hardware_alignof_env_complete cenv ha_env ->\n    legal_alignas_env_consistent cenv ha_env la_env ->\n    legal_alignas_env_complete cenv la_env ->\n    legal_alignas_env_sound cenv ha_env la_env.\n\nEnd LEGAL_ALIGNAS_FACTS.\n\nModule LegalAlignasStrict <: LEGAL_ALIGNAS.\n\nSection legal_alignas.\n\nContext (cenv: composite_env) (ha_env: PTree.t Z).\n\nDefinition legal_alignas_obs: Type := bool.\n\nFixpoint legal_alignas_type (la_env: PTree.t bool) t: bool :=\n  (hardware_alignof ha_env t <=? alignof cenv t) &&\n  match t with\n  | Tarray t' _ _ => (sizeof cenv t' mod alignof cenv t' =? 0) && legal_alignas_type la_env t'\n  | Tstruct id _ =>\n      match la_env ! id with\n      | Some la => la\n      | None => false\n      end\n  | Tunion id _ =>\n      match la_env ! id with\n      | Some la => la\n      | None => false\n      end\n  | _ => match access_mode t with\n         | By_value ch => true\n         | _ => false\n         end\n  end.\n\nFixpoint legal_alignas_members (la_env: PTree.t bool) (m: members): bool :=\n  match m with\n  | nil => true\n  | (_, t) :: m' => (legal_alignas_type la_env t) && (legal_alignas_members la_env m')\n  end.\n\nDefinition legal_alignas_composite (la_env: PTree.t bool) (co: composite): bool :=\n  legal_alignas_members la_env (co_members co).\n\nDefinition legal_alignas_env: PTree.t bool :=\n  let l := composite_reorder.rebuild_composite_elements cenv in\n  fold_right (fun (ic: positive * composite) (T0: PTree.t bool) => let (i, co) := ic in let T := T0 in PTree.set i (legal_alignas_composite T co) T) (PTree.empty _) l.\n\nDefinition is_aligned_aux (b: bool) (ha: Z) (ofs: Z) := b && ((ofs mod ha) =? 0).\n\nEnd legal_alignas.\n\nEnd LegalAlignasStrict.\n\nModule LegalAlignasStrictFacts: LEGAL_ALIGNAS_FACTS with Module LegalAlignas := LegalAlignasStrict.\n\nModule LegalAlignas := LegalAlignasStrict.\nModule LegalAlignasDefs := LegalAlignasDefsGen (LegalAlignas).\nExport LegalAlignas LegalAlignasDefs.\n\nSection legal_alignas.\n\nContext (cenv: composite_env) (ha_env: PTree.t Z).\n\nLemma aux1: forall T co,\n      (fix fm (l : list (ident * type * bool)) : bool :=\n          match l with\n          | nil => true\n          | (_, _, la) :: l' => la && fm l'\n          end)\n         (map\n            (fun it0 : positive * type =>\n             let (i0, t0) := it0 in\n             (i0, t0,\n             type_func.F\n               (fun t : type =>\n                (hardware_alignof ha_env t <=? alignof cenv t) &&\n                match access_mode t with\n                | By_value _ => true\n                | By_reference => false\n                | By_copy => false\n                | By_nothing => false\n                end)\n               (fun (la : bool) (t : type) (n : Z) (a0 : attr) =>\n                (hardware_alignof ha_env (Tarray t n a0) <=? alignof cenv (Tarray t n a0)) && ((sizeof cenv t mod alignof cenv t =? 0) && la))\n               (fun (la : bool) (id : ident) (a0 : attr) =>\n                (hardware_alignof ha_env (Tstruct id a0) <=? alignof cenv (Tstruct id a0)) && la)\n               (fun (la : bool) (id : ident) (a0 : attr) =>\n                (hardware_alignof ha_env (Tunion id a0) <=? alignof cenv (Tunion id a0)) && la) T t0)) (co_members co)) =\n      legal_alignas_composite cenv ha_env T co.\nProof.\n  intros; unfold legal_alignas_composite, legal_alignas_members, legal_alignas_type.\n  induction (co_members co) as [| [i t] ?].\n  + auto.\n  + simpl.\n    f_equal; auto.\n    clear.\n    induction t; auto.\n    - simpl.\n      rewrite IHt.\n      auto.\n    - simpl.\n      destruct (T ! i); auto.\n    - simpl.\n      destruct (T ! i); auto.\nQed.\n\nLemma aux2:\n    (type_func.Env\n          (fun t : type =>\n           (hardware_alignof ha_env t <=? alignof cenv t) &&\n           match access_mode t with\n           | By_value _ => true\n           | By_reference => false\n           | By_copy => false\n           | By_nothing => false\n           end)\n          (fun (la : bool) (t : type) (n : Z) (a0 : attr) =>\n           (hardware_alignof ha_env (Tarray t n a0) <=? alignof cenv (Tarray t n a0)) && ((sizeof cenv t mod alignof cenv t =? 0) && la))\n          (fun (la : bool) (id : ident) (a0 : attr) =>\n           (hardware_alignof ha_env (Tstruct id a0) <=? alignof cenv (Tstruct id a0)) && la)\n          (fun (la : bool) (id : ident) (a0 : attr) =>\n           (hardware_alignof ha_env (Tunion id a0) <=? alignof cenv (Tunion id a0)) && la)\n          (fun _ : struct_or_union =>\n           fix fm (l : list (ident * type * bool)) : bool :=\n             match l with\n             | nil => true\n             | (_, _, la) :: l' => la && fm l'\n             end) (composite_reorder.rebuild_composite_elements cenv)) =\n    legal_alignas_env cenv ha_env.\nProof.\n  intros.\n  unfold type_func.Env, type_func.env_rec, legal_alignas_env.\n  f_equal.\n  extensionality ic.\n  destruct ic as [i co].\n  extensionality T.\n  f_equal.\n  apply aux1.\nQed.\n\nEnd legal_alignas.\n\nTheorem legal_alignas_env_consistency:\n  forall (cenv: composite_env) (ha_env: PTree.t Z),\n    composite_env_consistent cenv ->\n    legal_alignas_env_consistent cenv ha_env (legal_alignas_env cenv ha_env).\nProof.\n  intros.\n  pose proof @composite_reorder_consistent bool cenv\n             (fun t => (hardware_alignof ha_env t <=? alignof cenv t) &&\n                match access_mode t with\n                | By_value _ => true\n                | _ => false\n                end)\n             (fun la t n a => (hardware_alignof ha_env (Tarray t n a) <=? alignof cenv (Tarray t n a)) && ((sizeof cenv t mod alignof cenv t =? 0) && la))\n             (fun la id a => (hardware_alignof ha_env (Tstruct id a) <=? alignof cenv (Tstruct id a)) && la)\n             (fun la id a => (hardware_alignof ha_env (Tunion id a) <=? alignof cenv (Tunion id a)) && la)\n             (fun _ =>\n                fix fm (l: list (ident * type * bool)): bool :=\n                match l with\n                | nil => true\n                | (_, _, la) :: l' => la && (fm l')\n                end)\n             H\n    as HH.\n  hnf in HH.\n  rewrite aux2 in HH.\n  hnf; intros.\n  specialize (HH _ _ la H0 H1).\n  rewrite HH, aux1; auto.\nQed.\n\nTheorem legal_alignas_env_completeness:\n  forall (cenv: composite_env) (ha_env: PTree.t Z),\n    legal_alignas_env_complete cenv (legal_alignas_env cenv ha_env).\nProof.\n  intros.\n  pose proof @composite_reorder_complete bool cenv\n             (fun t => (hardware_alignof ha_env t <=? alignof cenv t) &&\n                match access_mode t with\n                | By_value _ => true\n                | _ => false\n                end)\n             (fun la t n a => (hardware_alignof ha_env (Tarray t n a) <=? alignof cenv (Tarray t n a)) && ((sizeof cenv t mod alignof cenv t =? 0) && la))\n             (fun la id a => (hardware_alignof ha_env (Tstruct id a) <=? alignof cenv (Tstruct id a)) && la)\n             (fun la id a => (hardware_alignof ha_env (Tunion id a) <=? alignof cenv (Tunion id a)) && la)\n             (fun _ =>\n                fix fm (l: list (ident * type * bool)): bool :=\n                match l with\n                | nil => true\n                | (_, _, la) :: l' => la && (fm l')\n                end)\n    as HH.\n  hnf in HH.\n  rewrite aux2 in HH.\n  auto.\nQed.\n\nSection soundness.\n\nContext (cenv: composite_env)\n        (ha_env: PTree.t Z)\n        (la_env: PTree.t bool)\n        (CENV_CONSI: composite_env_consistent cenv)\n        (CENV_COSU: composite_env_complete_legal_cosu_type cenv)\n        (HA_ENV_CONSI: hardware_alignof_env_consistent cenv ha_env)\n        (HA_ENV_COMPL: hardware_alignof_env_complete cenv ha_env)\n        (LA_ENV_CONSI: legal_alignas_env_consistent cenv ha_env la_env)\n        (LA_ENV_COMPL: legal_alignas_env_complete cenv la_env).\n\nLemma legal_alignas_type_divide: forall t,\n  legal_alignas_type cenv ha_env la_env t = true ->\n  (hardware_alignof ha_env t | alignof cenv t).\nProof.\n  intros.\n  assert (hardware_alignof ha_env t <=? alignof cenv t = true).\n  Focus 1. {\n    destruct t; simpl in H |- *;\n    solve [inv H | rewrite andb_true_iff in H; tauto].\n  } Unfocus.\n  autorewrite with align in H0.\n  auto.\nQed.\n\nLemma by_value_sound:\n  forall t ofs,\n    is_aligned cenv ha_env la_env t ofs = true ->\n    (exists ch, access_mode t = By_value ch) ->\n    align_compatible_rec cenv t ofs.\nProof.\n  intros.\n  unfold is_aligned, is_aligned_aux, legal_alignas_type, hardware_alignof in H.\n  destruct H0 as [ch ?].\n  assert ((align_chunk ch <=? alignof cenv t) && true && (ofs mod align_chunk ch =? 0) = true) by\n    (destruct t; try solve [inversion H0]; rewrite H0 in H; auto); clear H.\n  autorewrite with align in H1.\n  destruct H1 as [_ ?].\n  eapply align_compatible_rec_by_value; eauto.\nQed.\n\nTheorem legal_alignas_soundness:\n  legal_alignas_env_sound cenv ha_env la_env.\nProof.\n  pose proof CENV_COSU.\n  clear CENV_COSU H.\n  intros.\n  hnf; intros ? ? _ ?.\n  revert ofs H; type_induction t cenv CENV_CONSI; intros.\n  + inversion H.\n  + eapply by_value_sound; eauto.\n    destruct i, s; eexists; try reflexivity.\n  + eapply by_value_sound; eauto.\n    destruct s; eexists; try reflexivity.\n  + eapply by_value_sound; eauto.\n    destruct f; eexists; try reflexivity.\n  + eapply by_value_sound; eauto.\n    eexists; try reflexivity.\n  + apply align_compatible_rec_Tarray; intros.\n    apply IH; clear IH.\n    unfold is_aligned, is_aligned_aux in H |- *.\n    Opaque alignof. simpl in H |- *. Transparent alignof.\n    autorewrite with align in H |- *.\n    destruct H as [[? [? ?]] ?].\n    split; auto.\n    apply Z.divide_add_r; auto.\n    apply Z.divide_mul_l.\n    clear H H3.\n    apply legal_alignas_type_divide in H2.\n    eapply Z.divide_trans; try eassumption.\n  + inv H.\n  + unfold is_aligned, is_aligned_aux in H, IH.\n    Opaque alignof. simpl in H, IH. Transparent alignof.\n    destruct (la_env ! id) as [la |] eqn:?H.\n    Focus 2. {\n      rewrite (andb_comm _ false) in H.\n      inv H.\n    } Unfocus.\n    pose proof proj2 (LA_ENV_COMPL id) (ex_intro _ _ H0) as [co ?].\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ _ H1) as [ha ?].\n    rewrite H1 in IH; rewrite H2 in H.\n    rewrite (HA_ENV_CONSI id _ _ H1 H2) in H.\n    rewrite (LA_ENV_CONSI id _ _ H1 H0) in H.\n    eapply align_compatible_rec_Tstruct; [eassumption | intros].\n    pose proof field_offset_aligned _ _ _ _ _ H4 H3.\n    unfold field_offset in H4.\n    clear H0 H1 H2 H4.\n    unfold legal_alignas_composite in *.\n    induction IH as [| [i t] ?].\n    - inv H3.\n    - Opaque alignof. simpl in H0, H3, H. Transparent alignof.\n      if_tac in H3.\n      * subst i0; inv H3.\n        apply H0; simpl.\n        autorewrite with align in H |- *.\n        destruct H as [[_ [? ?]] [? ?]].\n        split; auto.\n        apply Z.divide_add_r; auto.\n        apply legal_alignas_type_divide in H.\n        apply Z.divide_trans with (alignof cenv t0); try eassumption.\n      * apply IHIH; auto.\n        autorewrite with align in H |- *.\n        split; [split |]; tauto.\n  + unfold is_aligned, is_aligned_aux in H, IH.\n    Opaque alignof. simpl in H, IH. Transparent alignof.\n    destruct (la_env ! id) as [la |] eqn:?H.\n    Focus 2. {\n      rewrite (andb_comm _ false) in H.\n      inv H.\n    } Unfocus.\n    pose proof proj2 (LA_ENV_COMPL id) (ex_intro _ _ H0) as [co ?].\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ _ H1) as [ha ?].\n    rewrite H1 in IH; rewrite H2 in H.\n    rewrite (HA_ENV_CONSI id _ _ H1 H2) in H.\n    rewrite (LA_ENV_CONSI id _ _ H1 H0) in H.\n    eapply align_compatible_rec_Tunion; [eassumption | intros].\n    clear H0 H1 H2.\n    unfold legal_alignas_composite in *.\n    induction IH as [| [i t] ?].\n    - inv H3.\n    - Opaque alignof. simpl in H0, H3, H. Transparent alignof.\n      if_tac in H3.\n      * subst i0; inv H3.\n        apply H0; simpl.\n        autorewrite with align in H |- *.\n        destruct H as [[_ [? ?]] [? ?]].\n        split; auto.\n      * apply IHIH; auto.\n        autorewrite with align in H |- *.\n        split; [split |]; tauto.\nQed.\n\nEnd soundness.\n\nEnd LegalAlignasStrictFacts.\n\nModule LegalAlignasStrong <: LEGAL_ALIGNAS.\n\nSection legal_alignas.\n\nContext (cenv: composite_env) (ha_env: PTree.t Z).\n\nDefinition legal_alignas_obs: Type := bool.\n\nFixpoint legal_alignas_type (la_env: PTree.t bool) t: bool :=\n  match t with\n  | Tarray t' _ _ => (sizeof cenv t' mod hardware_alignof ha_env t' =? 0) && legal_alignas_type la_env t'\n  | Tstruct id _ =>\n      match la_env ! id with\n      | Some la => la\n      | None => false\n      end\n  | Tunion id _ =>\n      match la_env ! id with\n      | Some la => la\n      | None => false\n      end\n  | _ => match access_mode t with\n         | By_value ch => true\n         | _ => false\n         end\n  end.\n\nFixpoint legal_alignas_struct_members_rec (la_env: PTree.t bool) (m: members) (pos: Z): bool :=\n  match m with\n  | nil => true\n  | (_, t) :: m' => (align pos (alignof cenv t) mod hardware_alignof ha_env t =? 0) && (legal_alignas_type la_env t) && (legal_alignas_struct_members_rec la_env m' (align pos (alignof cenv t) + sizeof cenv t))\n  end.\n\nFixpoint legal_alignas_union_members_rec (la_env: PTree.t bool) (m: members): bool :=\n  match m with\n  | nil => true\n  | (_, t) :: m' => (legal_alignas_type la_env t) && (legal_alignas_union_members_rec la_env m')\n  end.\n\nDefinition legal_alignas_composite (la_env: PTree.t bool) (co: composite): bool :=\n  match co_su co with\n  | Struct => legal_alignas_struct_members_rec la_env (co_members co) 0\n  | Union => legal_alignas_union_members_rec la_env (co_members co)\n  end.\n\nDefinition legal_alignas_env: PTree.t bool :=\n  let l := composite_reorder.rebuild_composite_elements cenv in\n  fold_right (fun (ic: positive * composite) (T0: PTree.t bool) => let (i, co) := ic in let T := T0 in PTree.set i (legal_alignas_composite T co) T) (PTree.empty _) l.\n\nDefinition is_aligned_aux (b: bool) (ha: Z) (ofs: Z) := b && ((ofs mod ha) =? 0).\n\nEnd legal_alignas.\n\nEnd LegalAlignasStrong.\n\nModule LegalAlignasStrongFacts: LEGAL_ALIGNAS_FACTS with Module LegalAlignas := LegalAlignasStrong.\n\nModule LegalAlignas := LegalAlignasStrong.\nModule LegalAlignasDefs := LegalAlignasDefsGen (LegalAlignas).\nExport LegalAlignas LegalAlignasDefs.\n\nSection legal_alignas.\n\nContext (cenv: composite_env) (ha_env: PTree.t Z).\n\nLemma aux1: forall T co,\n  match co_su co with\n  | Struct =>\n      (fix fm (pos : Z) (l : list (ident * type * bool)) {struct l} : bool :=\n         match l with\n         | nil => true\n         | (_, t, la) :: l' =>\n             (align pos (alignof cenv t) mod hardware_alignof ha_env t =? 0) &&\n             la && fm (align pos (alignof cenv t) + sizeof cenv t) l'\n         end) 0\n  | Union =>\n      fix fm (l : list (ident * type * bool)) : bool :=\n        match l with\n        | nil => true\n        | (_, _, la) :: l' => la && fm l'\n        end\n  end\n    (map\n       (fun it0 : positive * type =>\n        let (i0, t0) := it0 in\n        (i0, t0,\n        type_func.F\n          (fun t : type =>\n           match access_mode t with\n           | By_value _ => true\n           | By_reference => false\n           | By_copy => false\n           | By_nothing => false\n           end)\n          (fun (la : bool) (t : type) (_ : Z) (_ : attr) =>\n           (sizeof cenv t mod hardware_alignof ha_env t =? 0) && la)\n          (fun (la : bool) (_ : ident) (_ : attr) => la)\n          (fun (la : bool) (_ : ident) (_ : attr) => la) T t0)) \n       (co_members co)) = legal_alignas_composite cenv ha_env T co.\nProof.\n  intros; unfold legal_alignas_composite, legal_alignas_type.\n  destruct (co_su co).\n  {\n  generalize 0 at 2 4.\n  induction (co_members co) as [| [i t] ?]; intros.\n  + auto.\n  + simpl.\n    f_equal; [f_equal |]; auto.\n    clear.\n    induction t; auto.\n    simpl.\n    rewrite IHt.\n    auto.\n  }\n  {\n  induction (co_members co) as [| [i t] ?]; intros.\n  + auto.\n  + simpl.\n    f_equal; [f_equal |]; auto.\n    clear.\n    induction t; auto.\n    simpl.\n    rewrite IHt.\n    auto.\n  }\nQed.\n\nLemma aux2:\n    (type_func.Env\n                  (fun t : type =>\n                   match access_mode t with\n                   | By_value _ => true\n                   | By_reference => false\n                   | By_copy => false\n                   | By_nothing => false\n                   end)\n                  (fun (la : bool) (t : type) (_ : Z) (_ : attr) =>\n                   (sizeof cenv t mod hardware_alignof ha_env t =? 0) && la)\n                  (fun (la : bool) (_ : ident) (_ : attr) => la)\n                  (fun (la : bool) (_ : ident) (_ : attr) => la)\n                  (fun su : struct_or_union =>\n                   match su with\n                   | Struct =>\n                       (fix\n                        fm (pos : Z) (l : list (ident * type * bool)) {struct l} :\n                          bool :=\n                          match l with\n                          | nil => true\n                          | (_, t, la) :: l' =>\n                              (align pos (alignof cenv t)\n                               mod hardware_alignof ha_env t =? 0) && la &&\n                              fm (align pos (alignof cenv t) + sizeof cenv t) l'\n                          end) 0\n                   | Union =>\n                       fix fm (l : list (ident * type * bool)) : bool :=\n                         match l with\n                         | nil => true\n                         | (_, _, la) :: l' => la && fm l'\n                         end\n                   end) (composite_reorder.rebuild_composite_elements cenv)) =\n    legal_alignas_env cenv ha_env.\nProof.\n  intros.\n  unfold type_func.Env, type_func.env_rec, legal_alignas_env.\n  f_equal.\n  extensionality ic.\n  destruct ic as [i co].\n  extensionality T.\n  f_equal.\n  apply aux1.\nQed.\n\nEnd legal_alignas.\n\nTheorem legal_alignas_env_consistency:\n  forall (cenv: composite_env) (ha_env: PTree.t Z),\n    composite_env_consistent cenv ->\n    legal_alignas_env_consistent cenv ha_env (legal_alignas_env cenv ha_env).\nProof.\n  intros.\n  pose proof @composite_reorder_consistent bool cenv\n             (fun t =>\n                match access_mode t with\n                | By_value _ => true\n                | _ => false\n                end)\n             (fun la t n a => ((sizeof cenv t mod hardware_alignof ha_env t =? 0) && la))\n             (fun la id a => la)\n             (fun la id a => la)\n             (fun su =>\n                match su with\n                | Struct =>\n                   (fix fm (pos: Z) (l: list (ident * type * bool)) : bool :=\n                    match l with\n                    | nil => true\n                    | (_, t, la) :: l' => (align pos (alignof cenv t) mod hardware_alignof ha_env t =? 0) && la && (fm (align pos (alignof cenv t) + sizeof cenv t) l')\n                    end) 0\n                | Union =>\n                   (fix fm (l: list (ident * type * bool)) : bool :=\n                    match l with\n                    | nil => true\n                    | (_, t, la) :: l' => la && (fm l')\n                    end)\n                end)\n             H\n    as HH.\n  hnf in HH.\n  rewrite aux2 in HH.\n  hnf; intros.\n  specialize (HH _ _ la H0 H1).\n  rewrite HH, <- aux1; auto.\nQed.\n\nTheorem legal_alignas_env_completeness:\n  forall (cenv: composite_env) (ha_env: PTree.t Z),\n    legal_alignas_env_complete cenv (legal_alignas_env cenv ha_env).\nProof.\n  intros.\n  pose proof @composite_reorder_complete bool cenv\n             (fun t =>\n                match access_mode t with\n                | By_value _ => true\n                | _ => false\n                end)\n             (fun la t n a => ((sizeof cenv t mod hardware_alignof ha_env t =? 0) && la))\n             (fun la id a => la)\n             (fun la id a => la)\n             (fun su =>\n                match su with\n                | Struct =>\n                   (fix fm (pos: Z) (l: list (ident * type * bool)) : bool :=\n                    match l with\n                    | nil => true\n                    | (_, t, la) :: l' => (align pos (alignof cenv t) mod hardware_alignof ha_env t =? 0) && la && (fm (align pos (alignof cenv t) + sizeof cenv t) l')\n                    end) 0\n                | Union =>\n                   (fix fm (l: list (ident * type * bool)) : bool :=\n                    match l with\n                    | nil => true\n                    | (_, t, la) :: l' => la && (fm l')\n                    end)\n                end)\n    as HH.\n  hnf in HH.\n  rewrite aux2 in HH.\n  auto.\nQed.\n\nSection soundness.\n\nContext (cenv: composite_env)\n        (ha_env: PTree.t Z)\n        (la_env: PTree.t bool)\n        (CENV_CONSI: composite_env_consistent cenv)\n        (CENV_COSU: composite_env_complete_legal_cosu_type cenv)\n        (HA_ENV_CONSI: hardware_alignof_env_consistent cenv ha_env)\n        (HA_ENV_COMPL: hardware_alignof_env_complete cenv ha_env)\n        (LA_ENV_CONSI: legal_alignas_env_consistent cenv ha_env la_env)\n        (LA_ENV_COMPL: legal_alignas_env_complete cenv la_env).\n\nLemma by_value_sound:\n  forall t ofs,\n    is_aligned cenv ha_env la_env t ofs = true ->\n    (exists ch, access_mode t = By_value ch) ->\n    align_compatible_rec cenv t ofs.\nProof.\n  intros.\n  unfold is_aligned, is_aligned_aux, legal_alignas_type, hardware_alignof in H.\n  destruct H0 as [ch ?].\n  assert ((ofs mod align_chunk ch =? 0) = true) by\n    (destruct t; try solve [inversion H0]; rewrite H0 in H; auto); clear H.\n  autorewrite with align in H1.\n  eapply align_compatible_rec_by_value; eauto.\nQed.\n\nTheorem legal_alignas_soundness:\n  legal_alignas_env_sound cenv ha_env la_env.\nProof.\n  intros.\n  hnf; intros.\n  revert ofs H H0; type_induction t cenv CENV_CONSI; intros.\n  + inversion H0.\n  + eapply by_value_sound; eauto.\n    destruct i, s; eexists; try reflexivity.\n  + eapply by_value_sound; eauto.\n    destruct s; eexists; try reflexivity.\n  + eapply by_value_sound; eauto.\n    destruct f; eexists; try reflexivity.\n  + eapply by_value_sound; eauto.\n    eexists; try reflexivity.\n  + apply align_compatible_rec_Tarray; intros.\n    apply IH; clear IH; [auto |].\n    unfold is_aligned, is_aligned_aux in H0 |- *.\n    simpl in H0 |- *.\n    autorewrite with align in H0 |- *.\n    destruct H0 as [[? ?] ?].\n    split; auto.\n    apply Z.divide_add_r; auto.\n    apply Z.divide_mul_l; auto.\n  + inv H.\n  + unfold is_aligned, is_aligned_aux in H0, IH.\n    simpl in H, H0, IH.\n    destruct (la_env ! id) as [la |] eqn:?H; [| inv H0].\n    pose proof proj2 (LA_ENV_COMPL id) (ex_intro _ _ H1) as [co ?].\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ _ H2) as [ha ?].\n    pose proof CENV_COSU _ _ H2.\n    rewrite H2 in IH, H; rewrite H3 in H0.\n    rewrite (HA_ENV_CONSI id _ _ H2 H3) in H0.\n    rewrite (LA_ENV_CONSI id _ _ H2 H1) in H0.\n    autorewrite with align in H0 |- *.\n    destruct H0.\n    unfold legal_alignas_composite in H0.\n    destruct (co_su co); [| inv H].\n    eapply align_compatible_rec_Tstruct; [eassumption | intros].\n    unfold field_offset in H7.\n    clear H H1 H2 H3.\n    revert H0 H4 H5 H6 H7; generalize 0;\n    induction IH as [| [i t] ?]; intros.\n    - inv H6.\n    - simpl in H, H0, H4, H5, H6, H7.\n      if_tac in H6.\n      * subst i0; inv H6; inv H7.\n        autorewrite with align in H4, H5, H0 |- *.\n        destruct H0 as [[? ?] ?], H4 as [? ?], H5 as [? ?].\n        apply H; simpl; [tauto |].\n        autorewrite with align.\n        split; auto.\n        apply Z.divide_add_r; auto.\n      * autorewrite with align in H0, H4, H5.\n        destruct H4, H5.\n        apply (IHIH (align z (alignof cenv t) + sizeof cenv t)); auto.\n        tauto.\n  + unfold is_aligned, is_aligned_aux in H0, IH.\n    simpl in H, H0, IH.\n    destruct (la_env ! id) as [la |] eqn:?H; [| inv H0].\n    pose proof proj2 (LA_ENV_COMPL id) (ex_intro _ _ H1) as [co ?].\n    pose proof proj1 (HA_ENV_COMPL id) (ex_intro _ _ H2) as [ha ?].\n    pose proof CENV_COSU _ _ H2.\n    rewrite H2 in IH, H; rewrite H3 in H0.\n    rewrite (HA_ENV_CONSI id _ _ H2 H3) in H0.\n    rewrite (LA_ENV_CONSI id _ _ H2 H1) in H0.\n    autorewrite with align in H0 |- *.\n    destruct H0.\n    unfold legal_alignas_composite in H0.\n    destruct (co_su co); [inv H |].\n    eapply align_compatible_rec_Tunion; [eassumption | intros].\n    clear H H1 H2 H3.\n    revert H0 H4 H5 H6;\n    induction IH as [| [i t] ?]; intros.\n    - inv H6.\n    - simpl in H, H0, H4, H5, H6.\n      if_tac in H6.\n      * subst i0; inv H6.\n        autorewrite with align in H4, H5, H0 |- *.\n        destruct H0 as [? ?], H4 as [? ?], H5 as [? ?].\n        apply H; simpl; [tauto |].\n        autorewrite with align.\n        split; auto.\n      * autorewrite with align in H0, H4, H5.\n        destruct H4, H5.\n        apply IHIH; auto.\n        tauto.\nQed.\n\nEnd soundness.\n\nEnd LegalAlignasStrongFacts.\n\nModule Export LegalAlignasFacts := LegalAlignasStrongFacts.\n\n\n\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/veric/align_mem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.2307761906313558}}
{"text": "From hahn Require Import Hahn.\nRequire Import PromisingLib.\nFrom Promising Require Import TView View Time Event Cell Thread Memory Configuration.\n\nFrom imm Require Import Events.\nFrom imm Require Import Execution.\nFrom imm Require Import imm_s.\nFrom imm Require Import imm_s_hb.\nFrom imm Require Import imm_bob imm_s_ppo.\n\nRequire Import PArith.\nRequire Import Event_imm_promise.\nFrom imm Require Import CombRelations.\nFrom imm Require Import CombRelationsMore.\nFrom imm Require Import TraversalConfig.\nRequire Import MaxValue.\nFrom imm Require Import ViewRelHelpers.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection ViewRel.\nVariable G : execution.\nVariable WF : Wf G.\nVariable sc : relation actid.\n\nNotation \"'acts'\" := G.(acts).\nNotation \"'co'\" := G.(co).\nNotation \"'sw'\" := G.(sw).\nNotation \"'hb'\" := G.(hb).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rf'\" := G.(rf).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'lab'\" := G.(lab).\nNotation \"'msg_rel'\" := G.(msg_rel).\nNotation \"'urr'\" := (urr G sc).\nNotation \"'release'\" := G.(release).\nNotation \"'t_cur'\" := (t_cur G sc).\nNotation \"'t_acq'\" := (t_acq G sc).\nNotation \"'t_rel'\" := (t_rel G sc).\nNotation \"'rfe'\" := G.(rfe).\nNotation \"'rfi'\" := G.(rfi).\n\nNotation \"'E'\" := G.(acts_set).\nNotation \"'R'\" := (fun a => is_true (is_r lab a)).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\nNotation \"'Loc_' l\" := (fun x => loc lab x = Some l) (at level 1). (* , format \"'Loc_'  l\"). *)\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'W_'\" := (fun l => W ∩₁ Loc_ l).\n(* Notation \"'RW'\" := (fun x => R x \\/ W x). *)\nNotation \"'FR'\" := (fun x => F x \\/ R x).\nNotation \"'FW'\" := (fun x => F x \\/ W x).\n\nNotation \"'Pln'\" := (fun a => is_true (is_only_pln lab a)).\nNotation \"'Rlx'\" := (is_rlx lab).\nNotation \"'Rel'\" := (is_rel lab).\nNotation \"'Acq'\" := (is_acq lab).\nNotation \"'Acqrel'\" := (is_acqrel lab).\nNotation \"'Sc'\" := (fun a => is_true (is_sc lab a)).\n\nDefinition sim_msg f_to b rel :=\n  forall l, max_value f_to \n              (fun a => msg_rel sc l a b \\/ Loc_ l b /\\ a = b) \n              (LocFun.find l rel.(View.rlx)).\n\nDefinition sim_mem_helper f_to b from v rel :=\n  ⟪ VAL: Some v = val lab b ⟫ /\\\n  ⟪ FROM: Time.lt from (f_to b) \\/ \n    is_init b /\\ from = Time.bot /\\ (f_to b) = Time.bot ⟫ /\\ \n  ⟪ SIMMSG: sim_msg f_to b rel ⟫.\n\nDefinition sim_rel C f_to rel i :=\n  forall l' l, max_value f_to \n    (t_rel i l l' C ∪₁\n     if Loc.eq_dec l l'\n     then W_ l' ∩₁ Tid_ i ∩₁ C\n     else ∅)\n    (LocFun.find l (LocFun.find l' rel).(View.rlx)).\n\nDefinition sim_cur C f_to cur i :=\n  forall l,\n    max_value f_to (t_cur i l C) \n    (LocFun.find l cur.(View.rlx)).\n\nDefinition sim_acq C f_to acq i :=\n  forall l,\n    max_value f_to (t_acq i l C) \n    (LocFun.find l acq.(View.rlx)).\n\nDefinition sim_tview C f_to tview i :=\n  ⟪ CUR: sim_cur C f_to tview.(TView.cur) i ⟫ /\\\n  ⟪ ACQ: sim_acq C f_to tview.(TView.acq) i ⟫ /\\\n  ⟪ REL: sim_rel C f_to tview.(TView.rel) i ⟫.\n\nLemma sim_tview_read_step\n      f_to f_from\n      w r locr valr xrmw ordr C tview thread rel mem\n      (COH : coherence G)\n      (Wf_sc : wf_sc G sc)\n      (SIMTVIEW : sim_tview C f_to tview thread)\n      (RRLX : Rlx r)\n      (NC : ~ C r)\n      (SBC : forall y, C y /\\ tid y = tid r -> sb y r)\n      (PRC : doma (sb ⨾ ⦗ eq r ⦘) C)\n      (RF : rf w r)\n      (TID : tid r = thread)\n      (RPARAMS : lab r = Aload xrmw ordr locr valr)\n      (GET : Memory.get locr (f_to w) mem =\n             Some (f_from w, Message.mk valr rel))\n      (HELPER : sim_mem_helper f_to w (f_from w) valr rel.(View.unwrap)) :\n  sim_tview\n    (C ∪₁ eq r) f_to\n    (TView.read_tview tview locr (f_to w) rel (rmod ordr))\n    thread.\nProof using WF.\n  assert (R r) as RR by type_solver.\n  assert (W w) as WW by (apply (wf_rfD WF) in RF; revert RF; basic_solver).\n  assert (Loc_ locr w) as WLOC.\n  { assert (loc lab w = loc lab r) as H.\n    { eapply loceq_rf; eauto. }\n    by rewrite H; unfold loc; rewrite RPARAMS. }\n  assert (~ is_init r) as RNINIT.\n  { intros INIT. apply (init_w WF) in INIT. type_solver. }\n  assert (E r) as RACTS by (apply (wf_rfE WF) in RF; revert RF; basic_solver).\n  assert (loc lab r = Some locr) as RLOC.\n  { by unfold loc; rewrite RPARAMS. }\n\n  assert (~ F r) as NF.\n  { intros H. type_solver. }\n  \n  assert (Ordering.le Ordering.relaxed (rmod ordr) = Rlx r) as ORDRLX.\n    by unfold is_rlx, mode_le, mod; rewrite RPARAMS; destruct ordr; simpls.\n  assert (Ordering.le Ordering.acqrel (rmod ordr) = Acq r) as ORDACQ.\n    by unfold is_acq, mode_le, mod; rewrite RPARAMS; destruct ordr; simpls.\n\n  assert \n    (forall l (P : actid -> bool),\n     dom_rel\n     ((msg_rel sc l ∪ ⦗Loc_ l⦘) ⨾ rf ⨾ ⦗P⦘ ⨾ ⦗eq r⦘) ≡₁\n     if P r\n     then\n       (fun a => msg_rel sc l a w \\/ loc lab w = Some l /\\ a = w)\n     else ∅) as MSGALT.\n  { ins; desf; [|basic_solver 21].\n    split; [|basic_solver 21].\n    unfolder; ins; desc.\n    assert (z = w); subst.\n      by eapply (wf_rff WF); eauto.\n    basic_solver 21. }\n\n  assert (forall l, W_ l ∩₁ eq r ≡₁ ∅) as DR'.\n    by type_solver 21.\n\n  assert (forall S l, W_ l ∩₁ eq r ∪₁ S ≡₁ S) as DR.\n   by intros; rewrite DR'; apply set_union_empty_l.\n\n  assert (forall l l',\n   t_rel (tid r) l l' (C ∪₁ eq r) ∪₁\n   (if LocSet.Facts.eq_dec l l'\n    then W ∩₁ Loc_ l' ∩₁ Tid_ (tid r) ∩₁ (C ∪₁ eq r)\n    else ∅) ≡₁\n   t_rel (tid r) l l' C ∪₁\n   (if LocSet.Facts.eq_dec l l'\n    then W ∩₁ Loc_ l' ∩₁ Tid_ (tid r) ∩₁ C\n    else ∅)) as RELALT.\n  { ins; rewrite t_rel_union_eqv; auto.\n    by desf; apply set_equiv_union; [done| type_solver 21].\n    by revert PRC; basic_solver. }\n\n  red in SIMTVIEW; desf.\n  red in CUR; desf.\n  red in ACQ; desf.\n  red in REL; desf.\n  cdes HELPER; clear FROM.\n  red in SIMMSG; desf.\n  red; splits; intros l; simpls;\n    unfold LocFun.find, TimeMap.join in *;\n    (try rewrite ORDRLX); try (rewrite ORDACQ).\n  { eapply max_value_same_set.\n    2: apply t_cur_urr_union_eqv; auto; revert PRC; basic_solver.\n    rewrite Time.join_assoc.\n    unfold CombRelations.t_cur, CombRelations.c_cur in CUR.\n    eapply max_value_join; eauto.\n    eapply max_value_join; eauto.\n    { eapply max_value_same_set; [|by apply DR].\n      eapply max_value_same_set; [|by eapply dom_rel_r; eauto].\n      unfold TimeMap.singleton, LocFun.add, LocFun.find, LocFun.init.\n      destruct (LocSet.Facts.eq_dec l locr); simpls; subst.\n      all: unfold TimeMap.singleton, LocFun.add, LocFun.find, LocFun.init.\n      { by apply max_value_singleton; rewrite Loc.eq_dec_eq. }\n      rewrite Loc.eq_dec_neq; auto.\n      apply max_value_empty; intros x HH; desf. }\n    specialize (MSGALT l (Acq)).\n    eapply max_value_same_set; [|by apply MSGALT].\n    destruct (Acq r) eqn: RACQ; unfold View.rlx; simpls.\n    by apply max_value_empty; intros x HH; desf. }\n  { eapply max_value_same_set.\n    2: apply t_acq_urr_union_eqv; auto; revert PRC; basic_solver.\n    rewrite Time.join_assoc.\n    unfold CombRelations.t_acq, CombRelations.c_acq in ACQ.\n    eapply max_value_join; eauto.\n    eapply max_value_join; eauto.\n    { eapply max_value_same_set; [|by apply DR].\n      eapply max_value_same_set; [|by eapply (dom_rel_r WF l); eauto].\n      destruct (LocSet.Facts.eq_dec l locr); simpls; subst;\n        unfold TimeMap.singleton, LocFun.add, LocFun.find, LocFun.init.\n      { by rewrite Loc.eq_dec_eq; apply max_value_singleton. }\n      rewrite Loc.eq_dec_neq; auto.\n      apply max_value_empty; intros x HH; desf. }\n    apply set_equiv_union; [reflexivity|].\n    specialize (MSGALT l (fun x => true)).\n    simpl in MSGALT. rewrite <- MSGALT.\n    arewrite (⦗fun _ : actid => true⦘ ≡ ⦗fun _ : actid => True⦘).\n    { split; intros x y H; red; red in H; desf. }\n    by rewrite seq_id_l. }\n  intros l'.\n  by eapply max_value_same_set; [apply REL| apply RELALT].\nQed.\n\nLemma sim_tview_write_step f_to f_from\n      w locw valw xmw ordw C tview thread rel mem sc_view\n      (COH : coherence G)\n      (Wf_sc : wf_sc G sc)\n      (CINE : C ⊆₁ E)\n      (CCLOS : doma (sb ⨾ ⦗C⦘) C)\n      (SIMTVIEW : sim_tview C f_to tview thread)\n      (NC : ~ C w)\n      (SBC : forall y, C y /\\ tid y = tid w -> sb y w)\n      (PRC : doma (sb ⨾ ⦗ eq w ⦘) C)\n      (TID : tid w = thread)\n      (NINIT : ~ is_init w)\n      (WACTS : E w)\n      (WPARAMS : lab w = Astore xmw ordw locw valw)\n      (GET : Memory.get locw (f_to w) mem =\n             Some (f_from w, Message.mk valw rel))\n      (HELPER : sim_mem_helper f_to w (f_from w) valw rel.(View.unwrap))\n : sim_tview\n    (C ∪₁ eq w) f_to\n    (TView.write_tview\n       tview sc_view locw (f_to w) (wmod ordw))\n    thread.\nProof using WF.\n  assert (W w) as WW.\n  { by unfold is_w; rewrite WPARAMS. }\n  assert (loc lab w = Some locw) as LOC.\n  { by unfold loc; rewrite WPARAMS. }\n  assert (~ F w) as NF.\n  { intros H; type_solver. }\n\n  assert (forall S l, S ∪₁ dom_rel (⦗Loc_ l⦘ ⨾ rf ⨾ ⦗eq w⦘) ≡₁ S) as DR1.\n    by ins; rewrite (dom_r (wf_rfD WF)); type_solver.\n\n  assert (forall S O l,\n             S ∪₁\n             dom_rel ((msg_rel sc l ∪ ⦗Loc_ l⦘) ⨾ rf ⨾ ⦗O⦘ ⨾ ⦗eq w⦘) ≡₁ S)\n    as DR2.\n    by ins; rewrite (dom_r (wf_rfD WF)); type_solver.\n\n  assert (forall S l,\n             S ∪₁\n             dom_rel ((msg_rel sc l ∪ ⦗Loc_ l⦘) ⨾ rf ⨾ ⦗eq w⦘) ≡₁ S)\n    as DR5.\n  { ins.\n    arewrite (⦗eq w⦘ ≡ ⦗ fun _ => True ⦘ ⨾ ⦗eq w⦘).\n    2: by apply DR2.\n    by rewrite seq_id_l. }\n  \n  assert (forall l,\n             W_ l ∩₁ eq w ≡₁\n             if LocSet.Facts.eq_dec l locw then eq w else ∅) as DR3.\n    by basic_solver.\n\n  assert (Ordering.le Ordering.acqrel (wmod ordw) = Rel w)\n    as ORDREL.\n  { unfold is_rel, mode_le, mod; rewrite WPARAMS; destruct ordw; simpls. }\n  \n  red in SIMTVIEW; desf.\n  red in CUR; desf.\n  red in ACQ; desf.\n  red in REL; desf.\n  cdes HELPER; clear FROM.\n  red in SIMMSG; desf.\n  red; splits; intros l; simpls;\n    unfold LocFun.find, TimeMap.join in *; try (rewrite ORDREL).\n  { eapply max_value_same_set.\n    2: apply t_cur_urr_union_eqv; auto; revert PRC; basic_solver.\n    unfold CombRelations.t_cur, CombRelations.c_cur in CUR.\n    eapply max_value_join; eauto.\n    eapply max_value_same_set; [|eapply DR2].\n    eapply max_value_same_set; [|eapply DR1].\n    eapply max_value_same_set; [|eapply DR3].\n    unfold TimeMap.singleton, LocFun.add, LocFun.find, LocFun.init.\n    destruct (LocSet.Facts.eq_dec l locw); simpls; subst.\n    { by apply max_value_singleton. }\n    apply max_value_empty; intros x HH; desf. }\n  { eapply max_value_same_set.\n    2: apply t_acq_urr_union_eqv; auto; revert PRC; basic_solver.\n    unfold CombRelations.t_acq, CombRelations.c_acq in ACQ.\n    eapply max_value_join; eauto.\n    eapply max_value_same_set; [|eapply DR5].\n    eapply max_value_same_set; [|eapply DR1].\n    eapply max_value_same_set; [|eapply DR3].\n    unfold TimeMap.singleton, LocFun.add, LocFun.find, LocFun.init.\n    destruct (LocSet.Facts.eq_dec l locw); simpls; subst.\n    { by apply max_value_singleton. }\n    apply max_value_empty; intros x HH; desf. }\n  { intros l0; eapply max_value_same_set; [|eapply t_rel_w_union_eqv; eauto]; cycle 2.\n    3: by apply urr_refl.\n{\nins.\nrewrite ((urr_rel_n_f_alt_union_eqv WF) sc Wf_sc l1 l' C w (tid w)); eauto.\nbasic_solver 42.\nrevert PRC; basic_solver 42.\n}\n    unfold TimeMap.join, TimeMap.singleton,View.singleton_ur,\n    LocFun.add, LocFun.find, LocFun.init.\n    destruct (LocSet.Facts.eq_dec l locw); simpls; subst.\n    destruct (Rel w); simpls; eapply max_value_join; eauto.\n    all: unfold LocFun.find, LocFun.init, TimeMap.singleton, LocFun.add.\n    all: destruct (Loc.eq_dec l0 locw).\n    1,3: by apply max_value_singleton; auto.\n    all: by apply max_value_empty; auto. }\nQed.\n\nLemma sim_tview_f_issued f_to f_to' T tview thread\n      (TCCOH : tc_coherent G sc T)\n      (IMMCON : imm_consistent G sc)\n      (RELCOV : W ∩₁ Rel ∩₁ issued T ⊆₁ covered T)\n      (ISSEQ : forall e (ISS: issued T e), f_to' e = f_to e)\n      (SIMTVIEW : sim_tview (covered T) f_to tview thread):\n  sim_tview (covered T) f_to' tview thread.\nProof using WF.\n  cdes SIMTVIEW.\n  red; splits; red; ins; eapply max_value_new_f.\n  1, 3, 5: by eauto.\n  { intros x H. apply t_cur_covered in H; auto. }\n  { intros x H. apply t_acq_covered in H; auto. }\n  intros x [H|H].\n  { apply t_rel_covered in H; auto. }\n  destruct (classic (l = l')) as [LEQ|LNEQ].\n  2: by rewrite Loc.eq_dec_neq in H; desf.\n  apply ISSEQ.\n  subst; rewrite Loc.eq_dec_eq in H.\n  generalize (w_covered_issued TCCOH).\n  revert H; basic_solver 21.\nQed.\n\nLemma sim_sc_fence_step\n      T f_to\n      f ordf ordr ordw tview thread sc_view\n      (TCCOH : tc_coherent G sc T)\n      (RELCOV : W ∩₁ Rel ∩₁ issued T ⊆₁ covered T)\n      (IMMCON : imm_consistent G sc)\n      (NEXT : next G (covered T) f)\n      (TID : tid f = thread)\n      (FPARAMS : lab f = Afence ordf)\n      (SAME_MOD : fmod ordf ordr ordw)\n      (SIMTVIEW : sim_tview (covered T) f_to tview thread)\n      (SC_VIEW :\n         forall (l : Loc.t),\n           max_value f_to (S_tm G l (covered T)) (LocFun.find l sc_view)) :\n  forall l : Loc.t,\n    max_value f_to (S_tm G l (covered T ∪₁ eq f))\n              (LocFun.find\n                 l (TView.write_fence_sc\n                      (TView.read_fence_tview tview ordr) \n                      sc_view ordw)).\nProof using WF.\n  cdes IMMCON.\n  intros l. specialize (SC_VIEW l).\n  destruct (classic (is_sc lab f)) as [FISSC|FISNOSC].\n  all: unfold TView.write_fence_sc.\n  { assert (Ordering.le Ordering.seqcst ordw /\\\n            Ordering.le Ordering.acqrel ordr) as [LLW LLR].\n    { red in SAME_MOD.\n      unfold is_sc, mod in FISSC. rewrite FPARAMS in FISSC.\n      desf; desf. }\n    unfold TView.read_fence_tview.\n    rewrite LLW, LLR; simpls.\n    unfold LocFun.find, TimeMap.join.\n    eapply max_value_same_set.\n    2: by eapply s_tm_cov_sc_fence; eauto.\n    eapply max_value_join.\n    3: by eauto.\n    { done. }\n    apply SIMTVIEW. }\n  assert (covered T ⊆₁ covered T ∪₁ eq f) as CCC.\n  { basic_solver. }\n  eapply max_value_same_set.\n  2: apply s_tm_n_f_steps.\n  3: by apply CCC.\n  2: by apply TCCOH.\n  2: by intros r COVEQ COVT [FF FF']; destruct COVEQ; subst.\n  assert (~ Ordering.le Ordering.seqcst ordw) as LL; [|by desf].\n  intros H. subst.\n  assert (ordw = Ordering.seqcst) as SS.\n  { destruct ordw; desf. }\n  unfold is_sc, mod in FISNOSC.\n  red in SAME_MOD; simpls;\n    rewrite FPARAMS in *; simpls.\n  destruct ordf; desf.\nQed.\n\nLemma sim_tview_fence_step T\n      f_to\n      f ordf ordr ordw tview thread sc_view\n      (TCCOH : tc_coherent G sc T)\n      (RELCOV : W ∩₁ Rel ∩₁ issued T ⊆₁ covered T)\n      (IMMCON : imm_consistent G sc)\n      (COV : coverable G sc T f)\n      (NCOV : ~ covered T f)\n      (TID : tid f = thread)\n      (SAME_MOD : fmod ordf ordr ordw)\n      (FPARAMS : lab f = Afence ordf)\n      (SIMTVIEW : sim_tview (covered T) f_to tview thread)\n      (SC_VIEW :\n         ~ (E∩₁F∩₁Sc ⊆₁ (covered T)) ->\n         forall (l : Loc.t),\n           max_value f_to (S_tm G l (covered T)) (LocFun.find l sc_view)) :\n  sim_tview (covered T ∪₁ eq f) f_to\n    (TView.write_fence_tview\n       (TView.read_fence_tview tview ordr) \n       sc_view ordw) (tid f).\nProof using WF.\n  cdes IMMCON.\n  assert (is_f lab f) as FENCE.\n  { by unfold is_f; rewrite FPARAMS. }\n  assert (E f) as EF.\n  { apply COV. }\n  red; splits.\n  all: unfold TView.read_fence_tview, TView.write_fence_tview,\n    TView.write_fence_sc; simpls.\n  all: red; simpls.\n  { intros l.\n    eapply max_value_same_set.\n    2: apply t_cur_fence_step; eauto.\n    red in SAME_MOD.\n    unfold is_sc, is_acq, mod; rewrite FPARAMS in *.\n    destruct ordf; simpls; destruct SAME_MOD; subst.\n    all: desf; simpls.\n    1-5: by apply SIMTVIEW.\n    unfold set_union; unfold LocFun.find.\n    eapply max_value_join.\n    { apply SC_VIEW.\n      intros H. apply NCOV. apply H; split; [split|]; auto.\n      unfold is_sc, mod. by rewrite FPARAMS. }\n    { by apply SIMTVIEW. }\n    basic_solver. }\n  { intros l.\n    eapply max_value_same_set.\n    2: by apply t_acq_fence_step.\n    red in SAME_MOD.\n    unfold is_sc, is_acq, mod; rewrite FPARAMS in *.\n    destruct ordf; simpls; destruct SAME_MOD; subst.\n    all: desf; simpls.\n    1-5: unfold LocFun.find, TimeMap.join, TimeMap.bot; simpls.\n    1-5: eapply max_value_join; eauto; [|apply max_value_empty; intros x H; desf].\n    1-5: by apply SIMTVIEW.\n    rewrite TimeMap.join_comm, TimeMap.join_assoc, TimeMap.join_comm.\n    eapply max_value_join; eauto.\n    { rewrite TimeMap.le_join_r; [by apply SIMTVIEW|].\n      apply TimeMap.le_PreOrder. }\n    apply SC_VIEW.\n    intros H. apply NCOV. apply H; split; [split|]; auto.\n    unfold is_sc, mod. by rewrite FPARAMS. }\n  intros l' l.\n  eapply max_value_same_set; [| by eapply t_rel_fence_step].\n  red in SAME_MOD.\n  unfold is_sc, is_acq, is_acqrel, is_rel, mod; rewrite FPARAMS in *.\n  destruct ordf; simpls; destruct SAME_MOD; subst.\n  all: cdes SIMTVIEW; red in REL.\n  all: desf; simpls.\n  unfold LocFun.find, TimeMap.join, TimeMap.bot; simpls.\n  eapply max_value_join; eauto.\n  apply SC_VIEW.\n  intros H. apply NCOV. apply H; split; [split|]; auto.\n  unfold is_sc, mod. by rewrite FPARAMS.\nQed.\n\nLemma sim_tview_other_thread_step f_to\n      C C' tview thread\n      (CINIT : is_init ∩₁ E ⊆₁ C)\n      (CINCL : C ⊆₁ C')\n      (CE : C' ⊆₁ E)\n      (COVSTEP : forall a, tid a = thread -> C' a -> C a)\n      (SIMTVIEW : sim_tview C f_to tview thread) :\n  sim_tview C' f_to tview thread.\nProof using.\n  red; splits; red; splits; ins.\n  all: eapply max_value_same_set.\n  all: try by (apply SIMTVIEW).\n  { apply t_cur_other_thread; eauto. }\n  { apply t_acq_other_thread; eauto. }\n  apply t_rel_if_other_thread; eauto.\nQed.\n\nEnd ViewRel.\n", "meta": {"author": "weakmemory", "repo": "promising1ToImm", "sha": "f27e87f0c2d037b30f0bc13763af39a11bb949a1", "save_path": "github-repos/coq/weakmemory-promising1ToImm", "path": "github-repos/coq/weakmemory-promising1ToImm/promising1ToImm-f27e87f0c2d037b30f0bc13763af39a11bb949a1/src/ViewRel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2305376083932364}}
{"text": "(** Defines the notion of a \"distributed execution with crashes\", and some\nderived notions/lemmas. *)\nFrom Perennial.program_logic Require Export language crash_lang.\nFrom iris.prelude Require Import options.\n\nSection dist_language.\n  Context {Λ: language}.\n  Context {CS: crash_semantics Λ}.\n\n  Record dist_node :=\n    { boot : expr Λ;\n      tpool : list (expr Λ);\n      local_state : state Λ }.\n\n  Record node_init_cfg :=\n    { init_restart : expr Λ;\n      init_thread : expr Λ;\n      init_local_state : state Λ }.\n\n  Definition dist_cfg : Type := list dist_node * global_state Λ.\n\n  Inductive dist_step : dist_cfg → list (observation Λ) → dist_cfg → Prop :=\n  | dist_step_machine ρ1 κs ρ2 m eb t1 σ1 t2 σ2 :\n      ρ1.1 !! m = Some {| boot := eb; tpool := t1; local_state := σ1 |} →\n      ρ2.1 = <[ m := {| boot := eb; tpool := t2; local_state := σ2|}]> ρ1.1 →\n      step (t1, (σ1,ρ1.2)) κs (t2, (σ2,ρ2.2)) →\n      dist_step ρ1 κs ρ2\n  | dist_step_crash ρ1 ρ2 m eb σ1 σ2 tp :\n      ρ1.1 !! m = Some {| boot := eb; tpool := tp; local_state := σ1 |} →\n      ρ2.1 = <[ m := {| boot := eb; tpool := [eb]; local_state := σ2 |}]> ρ1.1 →\n      ρ2.2 = ρ1.2 →\n      crash_prim_step CS σ1 σ2 →\n      dist_step ρ1 [] ρ2.\n\n  Inductive dist_nsteps : nat → dist_cfg → list (observation Λ) → dist_cfg → Prop :=\n    | dist_nsteps_refl ρ :\n       dist_nsteps 0 ρ [] ρ\n    | dist_nsteps_l n ρ1 ρ2 ρ3 κ κs :\n       dist_step ρ1 κ ρ2 →\n       dist_nsteps n ρ2 κs ρ3 →\n       dist_nsteps (S n) ρ1 (κ ++ κs) ρ3.\n  Local Hint Constructors dist_nsteps : core.\n\n  Definition erased_dist_step (ρ1 ρ2 : dist_cfg) := ∃ κ, dist_step ρ1 κ ρ2.\n\n  Lemma erased_dist_steps_nsteps ρ1 ρ2 :\n    rtc erased_dist_step ρ1 ρ2 ↔ ∃ n κs, dist_nsteps n ρ1 κs ρ2.\n  Proof.\n    split.\n    - induction 1; firstorder eauto.\n    - intros (n & κs & Hsteps). unfold erased_dist_step.\n      induction Hsteps; eauto using rtc_refl, rtc_l.\n  Qed.\n\n  Definition not_stuck_node (dn: dist_node) (g: global_state Λ) :=\n    ∀ e, e ∈ tpool dn → not_stuck e (local_state dn) g.\n\n  (* Generate a dist_cfg from:\n     (1) a list of init program, boot program, and initial local state for each node\n     (2) a global state.\n     Starting thread pool on each node is a single thread running the initial program *)\n  Definition starting_dist_cfg (eσs : list node_init_cfg) g : dist_cfg :=\n    (map (λ ρ, {| boot := init_restart ρ;\n                  local_state := init_local_state ρ;\n                  tpool := [init_thread ρ] |}) eσs, g).\n\nEnd dist_language.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_logic/dist_lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2305350219743038}}
{"text": "(* This code is copyrighted by its authors; it is distributed under  *)\n(* the terms of the LGPL license (see LICENSE and description files) *)\n\n(****************************************************************************)\n(*                                                                          *)\n(*                                                                          *)\n(*                Solange Coupet-Grimal & Line Jakubiec-Jamet               *)\n(*                                                                          *)\n(*                                                                          *)\n(*             Laboratoire d'Informatique Fondamentale de Marseille         *)\n(*                   CMI et Faculté des Sciences de Luminy                  *)\n(*                                                                          *)\n(*           e-mail:{Solange.Coupet,Line.Jakubiec}@lif.univ-mrs.fr          *)\n(*                                                                          *)\n(*                                                                          *)\n(*                            Developped in Coq v6                          *)\n(*                            Ported to Coq v7                              *)\n(*                            Translated to Coq v8                          *)\n(*                                                                          *)\n(*                             July 12nd 2005                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                           Arbitration_Specif.v                           *)\n(****************************************************************************)\n \n\nRequire Export Arbiter4_Specif.\nRequire Export Arbitration.\nRequire Export PriorityDecode_Proof.\nRequire Export Timing_Proof.\nRequire Import Timing_Arbiter.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n\nSection Arbitration_Specification.\n\n  Let Input_type :=\n    (bool * (d_list bool 4 * (d_list bool 4 * d_list (d_list bool 2) 4)))%type.\n\n  Let Output_type :=\n    (d_list bool 3 * d_list bool 3 * (d_list bool 3 * d_list bool 3))%type.\n\n\n(** The automaton describing the behaviour of ARBITER has 5 states **)\n\n  Inductive label_A : Set :=\n    | WAIT_BEGIN_A : label_A\n    | TRIGGER_A : label_A\n    | START_A : label_A\n    | ACTIVE_A : label_A\n    | NOT_TRIGGER_A : label_A. \n\n  Definition STATE_A : Set :=\n    (label_A *\n     (d_list (bool * bool) 4 * (d_list bool 4 * d_list (d_list bool 4) 4)))%type.\n\n\n\n(** Automaton describing the transitions from a state to another **)\n\n\n  Definition Trans_Arbitration (i : Input_type) (s : STATE_A) : STATE_A :=\n    let (fs, t) := i in\n    let (act, p') := t in\n    let (pri, route) := p' in\n    let (s', t) := s in\n    let (g, p) := t in\n    let (d, l) := p in\n    match s' with\n    | WAIT_BEGIN_A =>\n        match fs with\n        | true =>\n            (START_A, (g, (l4_tttt, Convert_and_filter (act, (pri, route)))))\n        | false =>\n            (WAIT_BEGIN_A, (g, (d, Convert_and_filter (act, (pri, route)))))\n        end\n    | TRIGGER_A =>\n        match fs with\n        | true =>\n            (START_A, (g, (l4_tttt, Convert_and_filter (act, (pri, route)))))\n        | false =>\n            (WAIT_BEGIN_A, (g, (d, Convert_and_filter (act, (pri, route)))))\n        end\n    | START_A =>\n        match fs with\n        | true =>\n            (START_A, (g, (l4_tttt, Convert_and_filter (act, (pri, route)))))\n        | false =>\n            match Ackor act with\n            | true =>\n                (ACTIVE_A, (g, (d, Convert_and_filter (act, (pri, route)))))\n            | false =>\n                (START_A,\n                (g, (l4_tttt, Convert_and_filter (act, (pri, route)))))\n            end\n        end\n    | ACTIVE_A =>\n        match fs with\n        | true =>\n            (START_A, (g, (l4_tttt, Convert_and_filter (act, (pri, route)))))\n        | false =>\n            match Ackor (d_map (Ackor (n:=3)) l) with\n            | true =>\n                (TRIGGER_A,\n                (d_Map_List4_pdt_Grant l g,\n                (Output_requested l, Convert_and_filter (act, (pri, route)))))\n            | false =>\n                (NOT_TRIGGER_A,\n                (g, (d, Convert_and_filter (act, (pri, route)))))\n            end\n        end\n    | NOT_TRIGGER_A =>\n        match fs with\n        | true =>\n            (START_A, (g, (l4_tttt, Convert_and_filter (act, (pri, route)))))\n        | false =>\n            (NOT_TRIGGER_A, (g, (d, Convert_and_filter (act, (pri, route)))))\n        end\n    end.\n\n\n(** The output function returns the result of ARBITRATION **)\n\n  Definition Out_Arbitration (s : STATE_A) : Output_type :=\n    let (_, t) := s in\n    let (g, p) := t in\n    let (d, _) := p in\n    (List3 (fst (Fst_of_l4 g)) (snd (Fst_of_l4 g)) (Fst_of_l4 d),\n    List3 (fst (Scd_of_l4 g)) (snd (Scd_of_l4 g)) (Scd_of_l4 d),\n    (List3 (fst (Thd_of_l4 g)) (snd (Thd_of_l4 g)) (Thd_of_l4 d),\n    List3 (fst (Fth_of_l4 g)) (snd (Fth_of_l4 g)) (Fth_of_l4 d))). \n\n\n(** States stream **)\n\n  Definition States_ARBITRATION :\n    Stream Input_type -> STATE_A -> Stream STATE_A :=\n    States_Mealy Trans_Arbitration.\n\n\n\n(** Intented behaviour **)\n\n  Definition Behaviour_ARBITRATION := Moore Trans_Arbitration Out_Arbitration.\n\n\n(** Transformation of Behaviour_ARBITRATION to a Mealy automaton **)\n\n  Definition Out_Arbitration_Mealy :=\n    Out_Mealy (Input_type:=Input_type) Out_Arbitration.\n\n  Lemma equiv_out_Arbitration_Moore_Mealy :\n   forall (i : Input_type) (s : STATE_A),\n   Out_Arbitration s = Out_Arbitration_Mealy i s.\n  auto.\n  Qed.\n\n\n  Lemma Equiv_Arbitration_Moore_Mealy :\n   forall (s : STATE_A) (i : Stream Input_type),\n   EqS (Behaviour_ARBITRATION i s)\n     (Mealy Trans_Arbitration Out_Arbitration_Mealy i s).\n  intros s i.\n  unfold Behaviour_ARBITRATION in |- *; unfold Out_Arbitration_Mealy in |- *;\n   apply Equiv_Moore_Mealy.\n  Qed.\n\n\n\n(** Invariant definition **)\n\n  Definition R_A (s_A : STATE_A)\n    (s : state_id * (label_t * STATE_p) * STATE_a4) : Prop :=\n    let (s_tpi, s_a4) := s in\n    let (sA, t) := s_A in\n    let (_, stp) := s_tpi in\n    let (st, s_p) := stp in\n    let (sp, l) := s_p in\n    let (sa4, p) := s_a4 in\n    let (G, p') := t in\n    let (D, L) := p' in\n    let (g, d) := p in\n    (sA = WAIT_BEGIN_A /\\ st = START_t /\\ sa4 = WAIT_a4 /\\ sp = START_p \\/\n     sA = WAIT_BEGIN_A /\\ st = START_t /\\ sa4 = WAIT_a4 /\\ sp = DECODE_p \\/\n     sA = START_A /\\\n     st = WAIT_t /\\ sa4 = START_a4 /\\ sp = DECODE_p /\\ D = l4_tttt \\/\n     sA = ACTIVE_A /\\\n     st = ROUTE_t /\\ sa4 = START_a4 /\\ sp = DECODE_p /\\ D = l4_tttt \\/\n     sA = NOT_TRIGGER_A /\\\n     st = START_t /\\ sa4 = START_a4 /\\ sp = DECODE_p /\\ D = l4_tttt \\/\n     sA = TRIGGER_A /\\\n     st = START_t /\\ sa4 = AT_LEAST_ONE_IS_ACTIVE_a4 /\\ sp = DECODE_p) /\\\n    G = g /\\ D = d /\\ L = l.\n\n\n\n(** There is an hypothesis on input signals here **)\n\n  Definition P_A (i : Input_type) (sA : STATE_A)\n    (s : state_id * (label_t * STATE_p) * STATE_a4) :=\n    let (s_tpi, _) := s in\n    let (_, stp) := s_tpi in\n    let (st, _) := stp in let (fs, _) := i in P_Timing fs st.\n\n\nEnd Arbitration_Specification.", "meta": {"author": "coq-contribs", "repo": "fairisle", "sha": "e36087a6b7e52ef3c6dcfdeba1298e8fde1260a0", "save_path": "github-repos/coq/coq-contribs-fairisle", "path": "github-repos/coq/coq-contribs-fairisle/fairisle-e36087a6b7e52ef3c6dcfdeba1298e8fde1260a0/Fairisle/PROOFS/Arbitration_Specif.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.23045024508312995}}
{"text": "From stdpp Require Import finite.\nFrom trillium.prelude Require Import quantifiers finitary.\nFrom iris.algebra Require Import auth excl csum agree.\nFrom iris.base_logic Require Import invariants.\nFrom iris.proofmode Require Import tactics.\nFrom aneris.prelude Require Import gset_map misc.\nFrom aneris.aneris_lang.state_interp Require Import state_interp.\nFrom aneris.aneris_lang Require Import\n     lang resources network events proofmode adequacy.\nFrom aneris.examples Require Export minimal_example_code.\n\n\nDefinition incr_exampleM : Model := model nat (λ m n, n = (m + 1)%nat) 0%nat.\n\nDefinition incr_res : cmra := authR (optionUR (csumR (exclR unitO) (agreeR (leibnizO loc)))).\n\nSection resources.\n  Context `{!inG Σ incr_res}.\n\n  Definition oloc_to_res (ol : option loc) : option (csum (excl unit) (agree loc)) :=\n    match ol with\n    | Some l => Some (Cinr (to_agree l))\n    | None => Some (Cinl (Excl ()))\n    end.\n\n  Definition incrloc_full (γ : gname) (ol : option loc) : iProp Σ :=\n    own γ (● oloc_to_res ol).\n\n  Definition incrloc_frag (γ : gname) (ol : option loc) : iProp Σ :=\n    own γ (◯ oloc_to_res ol).\n\n  Lemma incloc_create : ⊢ |==> ∃ γ, incrloc_full γ None ∗ incrloc_frag γ None.\n  Proof. setoid_rewrite <- own_op; apply own_alloc. apply auth_both_valid; done. Qed.\n\n  Lemma incrloc_agree γ ol ol' : incrloc_full γ ol -∗ incrloc_frag γ ol' -∗ ⌜ol = ol'⌝.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct (own_valid_2 with \"H1 H2\") as %Hvl.\n    apply auth_both_valid_discrete in Hvl as [Hvl1 Hvl2].\n    destruct ol; destruct ol'; [| | |done].\n    - apply Some_csum_included in Hvl1 as [|[(?&?&?&?)|(?&?&?&?&Hvl1)]]; simplify_eq.\n      revert Hvl1; rewrite Some_included_total; intros ->%to_agree_included%leibniz_equiv; done.\n    - apply Some_csum_included in Hvl1 as [|[(?&?&?&?&?)|(?&?&?&?&?)]]; simplify_eq.\n    - apply Some_csum_included in Hvl1 as [|[(?&?&?&?&?)|(?&?&?&?&?)]]; simplify_eq.\n  Qed.\n\n  Lemma incrloc_update γ l :\n    incrloc_full γ None -∗ incrloc_frag γ None ==∗ incrloc_full γ (Some l) ∗ incrloc_frag γ (Some l).\n  Proof.\n    iIntros \"H1 H2\".\n    setoid_rewrite <- own_op.\n    iApply (own_update_2 with \"H1 H2\").\n    apply auth_update.\n    apply option_local_update.\n    apply exclusive_local_update; done.\n  Qed.\n\nEnd resources.\n\nSection proof.\n  Context `{!anerisG incr_exampleM Σ, !inG Σ incr_res}.\n\n  Context (ip : ip_address).\n\n  Definition ICIname : namespace := nroot .@ \"incr\".\n\n  Definition incr_inv γ : iProp Σ :=\n    inv ICIname ((incrloc_full γ None ∗ alloc_evs \"s\" [] ∗ frag_st 0%nat) ∨\n                 (∃ l (n : nat), incrloc_full γ (Some l) ∗\n                    l ↦[ip] #n ∗\n                    (∃ σ h, alloc_evs \"s\" [allocObs ip \"s\" l #0 σ h] ∗\n                        ⌜valid_allocObs ip l σ h⌝) ∗\n                    frag_st n)).\n\n  Lemma incr_inv_init γ E :\n    incrloc_full γ None -∗ alloc_evs \"s\" [] -∗ frag_st 0%nat ={E}=∗ incr_inv γ.\n  Proof.\n    iIntros \"? ? ?\".\n    iApply inv_alloc; iNext; iLeft; iFrame.\n  Qed.\n\n  Lemma WP_incr_loop γ l :\n    {{{incr_inv γ ∗ incrloc_frag γ (Some l) }}} incr_loop #l @[ip] {{{ RET #(); False }}}.\n  Proof.\n    iIntros (Φ) \"#[Hinv Hl] _\".\n    iLöb as \"IH\".\n    rewrite /incr_loop.\n    wp_pures.\n    wp_bind (!_)%E.\n    iInv ICIname as \"[[>H _]|H]\" \"Hcl\".\n    { iDestruct (incrloc_agree with \"H Hl\") as %?; done. }\n    iDestruct \"H\" as (l' n) \"(>Hfl & Hln & Hev & Hfg)\".\n    iDestruct (incrloc_agree with \"Hfl Hl\") as %?; simplify_eq.\n    wp_load.\n    iMod (\"Hcl\" with \"[Hfl Hln Hev Hfg]\") as \"_\".\n    { iRight; iExists _, _; iFrame. }\n    iModIntro.\n    wp_pures.\n    wp_bind (CAS _ _ _).\n    iInv ICIname as \"[[>H _]|H]\" \"Hcl\".\n    { iDestruct (incrloc_agree with \"H Hl\") as %?; done. }\n    iDestruct \"H\" as (l' m) \"(>Hfl & Hln & Hev & >Hfg)\".\n    iDestruct (incrloc_agree with \"Hfl Hl\") as %?; simplify_eq.\n    destruct (decide (n = m)) as [->|].\n    - iApply aneris_wp_atomic_take_step_model.\n      iModIntro.\n      iExists _, (m + 1)%nat; iFrame; iSplit.\n      { iPureIntro; right; done. }\n      wp_cas_suc.\n      iIntros \"Hfg\".\n      iApply fupd_mask_intro; first done.\n      iIntros \"_\".\n      iMod (\"Hcl\" with \"[Hfl Hln Hev Hfg]\") as \"_\".\n      { replace #(m + 1) with #(m + 1)%nat by by repeat f_equal; lia.\n        iRight; iExists _, _; iFrame. }\n      iModIntro.\n      do 2 wp_pure _; done.\n    - wp_cas_fail.\n      { intros ?; simplify_eq. }\n      iMod (\"Hcl\" with \"[Hfl Hln Hev Hfg]\") as \"_\".\n      { iRight; iExists _, _; iFrame. }\n      iModIntro.\n      do 2 wp_pure _; done.\n  Qed.\n\n  Lemma WP_incr_example γ :\n    {{{incr_inv γ ∗ incrloc_frag γ None }}} incr_example @[ip] {{{ RET #(); False }}}.\n  Proof.\n    iIntros (Φ) \"[#Hinv Hl] _\".\n    rewrite /incr_example.\n    wp_bind (ref<<_>> _)%E.\n    iInv ICIname as \"[H|H]\" \"Hcl\"; last first.\n    { iDestruct \"H\" as (? ?) \"[>H _]\".\n      iDestruct (incrloc_agree with \"H Hl\") as %?; done. }\n    iDestruct \"H\" as \"(Hfl & Hev & Hfg)\".\n    wp_apply (aneris_wp_alloc_tracked with \"Hev\").\n    iIntros (l h σ) \"(Hl0 & Hev1 & Hev2)\".\n    iMod (incrloc_update with \"Hfl Hl\") as \"[Hfl #Hl]\".\n    iMod (\"Hcl\" with \"[Hfl Hl0 Hev1 Hev2 Hfg]\") as \"_\".\n    { iNext; iRight. iExists _, _; iFrame; eauto. }\n    iModIntro.\n    wp_pures.\n    wp_apply aneris_wp_fork.\n    iSplitL.\n    - iNext.\n      wp_pures.\n      iApply WP_incr_loop; [by iFrame \"#\"|].\n      iNext; iIntros \"?\"; done.\n    - iNext.\n      iApply WP_incr_loop; [by iFrame \"#\"|].\n      iNext; iIntros \"?\"; done.\n  Qed.\n\nEnd proof.\n\nDefinition heap_grows (c c' : cfg aneris_lang) : Prop :=\n  dom c.2.(state_heaps) ⊆ dom c'.2.(state_heaps) ∧\n  ∀ ip h h',\n    c.2.(state_heaps) !! ip = Some h →\n    c'.2.(state_heaps) !! ip = Some h' →\n    dom h ⊆ dom h'.\n\nGlobal Instance heap_grows_PreOder : PreOrder heap_grows.\nProof.\n  rewrite /heap_grows; split; first by intros ?; set_solver.\n  intros c1 c2 c3 [Hc121 Hc122] [Hc231 Hc232].\n  split; first set_solver.\n  intros ip h h' Hh Hh'.\n  assert (is_Some (c2.2.(state_heaps) !! ip)) as [h'' Hh''].\n  { apply elem_of_dom. apply elem_of_dom_2 in Hh. set_solver. }\n  set_solver.\nQed.\n\nLemma valid_exec_heap_grows (ex : execution_trace aneris_lang) :\n  valid_exec ex → trace_steps (λ x _ y, heap_grows x y) ex.\nProof.\n  induction ex as [c|ex IHex c']; first by constructor.\n  intros Hexvl.\n  eapply valid_exec_exec_extend_inv in Hexvl as [Hecvl (c & <-%last_eq_trace_ends_in & Hstep)].\n  econstructor; [done| |by apply IHex].\n  rewrite /heap_grows.\n  inversion Hstep as [????????? Htrl ? Hpstep|????? Htrl ? Hcfgstep]; simplify_eq/=; last first.\n  { rewrite Htrl; simpl in *.\n    inversion Hcfgstep; simpl in *; set_solver. }\n  rewrite Htrl; simpl in *.\n  inversion Hpstep as [????? Hhstep]; simplify_eq/=.\n  inversion Hhstep as [??????? Hbstep|ip' ??????? Hbstep|ip' |]; simplify_eq/=.\n  - inversion Hbstep; simplify_eq/=; set_solver.\n  - rewrite dom_insert.\n    split; first set_solver.\n    intros ip.\n    destruct (decide (ip = ip')) as [->|].\n    + rewrite lookup_insert; intros ????; simplify_eq/=.\n      inversion Hbstep; simplify_eq/=; set_solver.\n    + rewrite lookup_insert_ne; last done; set_solver.\n  - rewrite dom_insert.\n    split; first set_solver.\n    intros ip.\n    destruct (decide (ip = ip')) as [->|].\n    + rewrite lookup_insert; intros ????; simplify_eq/=.\n    + rewrite lookup_insert_ne; last done; set_solver.\n  - set_solver.\nQed.\n\nDefinition incr_sim ip (ex : execution_trace aneris_lang) (atr : finite_trace nat ()) : Prop :=\n  trace_length ex = trace_length atr ∧\n  ((events_of_trace (allocEV \"s\") ex = [] ∧ ∀ i n, atr !! i = Some n → n = 0)%nat ∨\n  (∃ l (n : nat),\n      (∃ σ h, events_of_trace (allocEV \"s\") ex = [allocObs ip \"s\" l #0 σ h] ∧\n              valid_allocObs ip l σ h) ∧\n      ∃ h,\n        (trace_last ex).2.(state_heaps) !! ip = Some h ∧\n        h !! l = Some #n ∧\n        trace_last atr = n ∧\n        (∀ i c h' v,\n            ex !! i = Some c →\n            state_heaps c.2 !! ip = Some h' →\n            h' !! l = Some v →\n            ∃ (m : nat), v = #m ∧ atr !! i = Some m ∧ m ≤ n) ∧\n        (∀ m, m ≤ n → ∃ i c h',\n              ex !! i = Some c ∧ state_heaps c.2 !! ip = Some h' ∧ h' !! l = Some #m ∧\n              atr !! i = Some m)))%nat.\n\nDefinition init_state ip := {|\n  state_heaps :=  {[ip := ∅ ]};\n  state_sockets := {[ip := ∅ ]};\n  state_ms := ∅; |}.\n\nLemma incr_exampleM_finitary : aneris_model_rel_finitary incr_exampleM.\nProof.\n  intros n.\n  apply finite_smaller_card_nat.\n  apply sig_finite_eq1.\nQed.\n\nLemma gcounter_adequacy ip :\n  @continued_simulation aneris_lang (aneris_to_trace_model incr_exampleM)\n    (incr_sim ip)\n    {tr[ ([mkExpr ip incr_example], init_state ip) ]}\n    {tr[ 0%nat ]}.\nProof.\n  eapply (simulation_adequacy #[anerisΣ incr_exampleM; GFunctor incr_res] incr_exampleM\n                              NotStuck ∅ {[\"s\"]} ∅ ∅ ∅ (λ _, True) _ ip).\n  { set_solver. }\n  { set_solver. }\n  { apply aneris_sim_rel_finitary, incr_exampleM_finitary. }\n  { set_solver. }\n  { set_solver. }\n  { set_solver. }\n  { set_solver. }\n  iIntros (?) \"!#\".\n  iExists (λ _, True)%I.\n  iIntros \"_ _ _ #? Hevs _ _ _ _ Hfg\".\n  rewrite big_sepS_singleton.\n  assert (inG #[ anerisΣ incr_exampleM; GFunctor incr_res] incr_res).\n  { assert (subG (GFunctor incr_res) #[ anerisΣ incr_exampleM; GFunctor incr_res]).\n    apply _. solve_inG. }\n  iMod incloc_create as (γ) \"[Hf Hl]\".\n  iMod (incr_inv_init ip with \"Hf Hevs Hfg\") as \"#Hinv\".\n  iModIntro.\n  iSplit; [done|].\n  iSplitL.\n  { iPoseProof (WP_incr_example _ _ (λ _, True)%I with \"[$Hl//] []\") as \"H\".\n    - iNext; iIntros \"?\"; done.\n    - rewrite aneris_wp_unfold /aneris_wp_def.\n      iApply (wp_wand with \"[H]\"); first by iApply \"H\".\n      auto. }\n  iIntros (ex atr c Hvs Hexs Hatrs Hexe Hcntr _) \"(Hevs & HSI & Hmdl & %Hvalid & Hsteps) _\".\n  destruct (valid_system_trace_start_or_contract ex atr) as [[-> ->]|Hcontr]; first done.\n  { erewrite !first_eq_trace_starts_in; [|eassumption|eassumption].\n    iMod fupd_mask_subseteq as \"_\"; [|iModIntro]; first done.\n    iPureIntro.\n    split; [done|].\n    left; split.\n    - rewrite events_of_singleton_trace; done.\n    - intros [] ? ?; simplify_eq/=; done. }\n  destruct Hcontr as (ex' & atr' & oζ & ℓ & Hex' & Hatr').\n  specialize (Hcntr ex' atr' oζ ℓ Hex' Hatr') as [Hlen Hmrel].\n  rewrite /incr_sim.\n  destruct atr as [|atr m]; first by apply not_trace_contract_singleton in Hatr'.\n  apply trace_contract_of_extend in Hatr'; simplify_eq.\n  destruct ex as [|ex oζ' c']; first by apply not_trace_contract_singleton in Hex'.\n  apply trace_contract_of_extend in Hex'; simplify_eq.\n  iInv ICIname as \">[H|H]\" \"_\"; iApply fupd_mask_intro_discard; [set_solver| |set_solver|].\n  - iDestruct \"H\" as \"(Hfl & Haev & Hfg)\".\n    rewrite /incr_sim.\n    simpl.\n    destruct Hex' as [-> ->]. destruct Hatr' as [-> ->].\n    iSplit; [rewrite /= Hlen //|].\n    iLeft.\n    iDestruct \"Hevs\" as (? ? lbls) \"(_ & _ & _ & _ & _ & Hevs)\".\n    iDestruct (alloc_evs_lookup with \"Hevs Haev\") as %Haevlu.\n    apply lookup_fn_to_gmap in Haevlu as [Haevs _].\n    rewrite Haevs.\n    iSplit; first done.\n    iIntros (i n Hin).\n    destruct (decide (i = trace_length atr)).\n    + rewrite trace_lookup_last in Hin; last by simpl in *; lia.\n      simplify_eq. simpl.\n      iDestruct (auth_frag_st_agree with \"Hmdl Hfg\") as %->; done.\n    + destruct (events_of_trace_extend_app (allocEV \"s\") ex c' oζ) as (evs & Hevslen & Hevs & _).\n      { eapply valid_system_trace_valid_exec_trace; done. }\n      rewrite Haevs in Hevs.\n      symmetry in Hevs; apply app_eq_nil in Hevs as [Hevs _].\n      pose proof (trace_lookup_lt_Some_1 _ _ _ Hin); simpl in *.\n      rewrite trace_lookup_extend_lt in Hin; last lia.\n      destruct Hmrel as [Hmrel|Hmrel]; last first.\n      { rewrite Hevs in Hmrel. destruct Hmrel as (?&?&(?&?&?&?)&?); done. }\n      iPureIntro.\n      by eapply Hmrel.\n  - iDestruct \"H\" as (l n) \"(Hfl & Hln & Haev & Hfg)\".\n    iDestruct \"Haev\" as (σ h) \"[Haev %Haevvl]\".\n    destruct Hex' as [-> ->]. destruct Hatr' as [-> ->].\n    iSplit; [rewrite /= Hlen //|].\n    iRight.\n    iDestruct \"Hevs\" as (? ? lbls) \"(_ & _ & _ & _ & _ & Hevs)\".\n    iDestruct (alloc_evs_lookup with \"Hevs Haev\") as %Haevlu.\n    apply lookup_fn_to_gmap in Haevlu as [Haevs _].\n    rewrite Haevs.\n    iExists l, n.\n    iSplit; first by eauto.\n    iDestruct (aneris_state_interp_heap_valid with \"HSI Hln\") as %(h'&Hh'&Hh'ln).\n    iExists _.\n    iSplit; first done.\n    iSplit; first done.\n    iDestruct (auth_frag_st_agree with \"Hmdl Hfg\") as %Hst.\n    destruct (events_of_trace_extend_app (allocEV \"s\") ex c' oζ) as (evs & Hevslen & Hevs & Hevs').\n    { eapply valid_system_trace_valid_exec_trace; done. }\n    iPureIntro.\n    rewrite Haevs in Hevs.\n    destruct (events_of_trace (allocEV \"s\") ex) as [|aev evs'] eqn:Haevseq.\n    + destruct Hmrel as [Hmrel|Hmrel]; last first.\n      { destruct Hmrel as (?&?&(?&?&?&?)&?); done. }\n      assert (trace_last atr = 0) as Hatrlast.\n      { apply Hmrel with (pred (trace_length atr)). apply trace_lookup_last.\n        pose proof (trace_length_at_least atr); simpl in *; lia. }\n      simplify_eq/=.\n      split; first done.\n      edestruct Hevs' as (K & tp1 & tp2 & efs & Hpres & Hpree & Hposts & Hposte);\n        first by apply elem_of_list_singleton.\n      simplify_eq/=.\n      rewrite Hposts /= lookup_insert in Hh'; simplify_eq/=.\n      rewrite lookup_insert in Hh'ln; simplify_eq/=.\n      assert (n = 0) as -> by lia.\n      split; last first.\n      { intros m Hm.\n        assert (m = 0) as -> by lia.\n        eexists (trace_length ex), _, _.\n        rewrite !trace_lookup_last //=; last rewrite Hlen //.\n        split; first done.\n        rewrite Hposts /= lookup_insert.\n        split; first done.\n        rewrite lookup_insert; done. }\n      intros i c'' h' v Hi Hh' Hv.\n      pose proof (trace_lookup_lt_Some_1 _ _ _ Hi); simpl in *.\n      destruct (decide (i = trace_length ex)) as [->|].\n      * rewrite trace_lookup_last in Hi; last done.\n        simplify_eq/=.\n        rewrite Hposts /= lookup_insert in Hh'.\n        simplify_eq/=.\n        rewrite lookup_insert in Hv; simplify_eq.\n        eexists 0; split; first done.\n        rewrite trace_lookup_last; simpl; eauto with lia.\n      * assert (heap_grows c'' (trace_last ex)) as [_ Hheaps].\n        { rewrite -rt_rtc_same.\n          apply valid_system_trace_valid_exec_trace in Hvs.\n          pose proof (trace_length_at_least ex).\n          eapply (trace_steps_lookup\n                    _ _ (valid_exec_heap_grows _ Hvs)\n                    i (pred (trace_length ex)) c'' (trace_last ex)).\n          - pose proof (trace_length_at_least ex).\n            (* lia bug!? *)\n            apply PeanoNat.Nat.lt_le_pred.\n            apply Nat.le_neq; split; last done.\n            apply lt_n_Sm_le; done.\n          - done.\n          - rewrite trace_lookup_extend_lt; last first.\n            { apply lt_pred_n_n. eauto. }\n            rewrite trace_lookup_last; [done|].\n            rewrite -(S_pred _ 0) //. }\n        destruct Haevvl as [Haevvl1 Haevvl2].\n        specialize (Hheaps _ _ _ Hh' Haevvl1).\n        assert (is_Some (h !! l)) as [? ?]; last by simplify_eq.\n        apply (elem_of_dom (D := gset loc)).\n        apply (elem_of_dom_2 (D := gset loc)) in Hv.\n        set_solver.\n    + simplify_eq Hevs; clear Hevs; intros <- Hevs.\n      symmetry in Hevs; apply app_eq_nil in Hevs as [? ?]; simplify_eq/=.\n      split; first done.\n      destruct Hmrel as [Hmrel|Hmrel].\n      { destruct Hmrel as [? ?]; done. }\n      destruct Hmrel as (l' & k & Hl' & Hatrk & h'' & Hh'' & Hh''l'k & Hrel1 & Hrel2).\n      destruct Hl' as (σ' & h3 & Haevs' & [Haevvl'1 Haevvl'2]).\n      destruct Haevvl as [Haevvl1 Haevvl2].\n      simplify_eq /=.\n      assert (trace_last atr ≤ n ≤ trace_last atr + 1).\n      { simpl in *. rewrite /user_model_evolution /= in Hvalid. lia. }\n      split.\n      * intros i c'' h4 v Hc'' Hh4 Hv.\n        destruct (decide (i < trace_length ex)).\n        -- rewrite trace_lookup_extend_lt in Hc''; last done.\n           rewrite trace_lookup_extend_lt; last lia.\n           destruct (Hrel1 i c'' h4 v) as (m' & ? & ? & ?); [done|done|done|]; simplify_eq.\n           eauto with lia.\n        -- pose proof (trace_lookup_lt_Some_1 _ _ _ Hc''); simpl in *.\n           assert (i = trace_length ex) as ->. (* lia bug! *)\n           { assert (i ≤ trace_length ex) by by apply lt_n_Sm_le. lia. }\n           rewrite trace_lookup_extend; last by simpl in *; lia.\n           rewrite trace_lookup_extend in Hc''; last done.\n           simplify_eq; eauto.\n      * intros m Hm.\n        destruct (decide (m = n)) as [->|].\n        { eexists (trace_length ex), _, _.\n          repeat (rewrite trace_lookup_extend; last solve [lia|done]); done. }\n        destruct (Hrel2 m) as (i & ? & ? & Hexi & ? & ? & ?); first lia.\n        pose proof (trace_lookup_lt_Some_1 _ _ _ Hexi).\n        eexists i, _, _.\n        rewrite trace_lookup_extend_lt; last first.\n        { assert (trace_length ex = trace_length atr) as <-. lia. done. }\n        rewrite trace_lookup_extend_lt; done.\nQed.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/minimal_example/minimal_example_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2303209245686154}}
{"text": "From mathcomp Require Import\n  ssreflect ssrfun ssrbool eqtype ssrnat seq choice ssrint.\nFrom extructures Require Import ord fmap.\nFrom CoqUtils Require Import word.\n\nRequire Import lib.utils common.types.\n\nImport DoNotation.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nModule Concrete.\n\nLocal Open Scope word_scope.\n\nRecord mvec (mt : machine_types) : Type := MVec {\n  cop  : opcode;\n  ctpc : mword mt;\n  cti  : mword mt;\n  ct1  : mword mt;\n  ct2  : mword mt;\n  ct3  : mword mt\n}.\n\nDefinition mvec_eqb mt (m1 m2 : mvec mt) : bool :=\n  [&& cop m1 == cop m2,\n      ctpc m1 == ctpc m2,\n      cti m1 == cti m2,\n      ct1 m1 == ct1 m2 &\n      ct2 m1 == ct2 m2] && (ct3 m1 == ct3 m2).\n\nLemma mvec_eqbP mt : Equality.axiom (@mvec_eqb mt).\nProof.\n  move => m1 m2.\n  case: m1 => *. case: m2 => *.\n  apply (iffP andP); simpl.\n  - by move => [/and5P [/eqP -> /eqP -> /eqP -> /eqP -> /eqP ->] /eqP ->].\n  - move => [-> -> -> -> -> ->]. by rewrite !eqxx.\nQed.\n\nDefinition mvec_eqMixin mt := EqMixin (@mvec_eqbP mt).\nCanonical mvec_eqType mt :=\n  Eval hnf in EqType (mvec mt) (@mvec_eqMixin mt).\n\nSection MVecOrdType.\n\nVariable mt : machine_types.\n\nDefinition tuple_of_mvec (mv : mvec mt) :=\n  (cop mv, ctpc mv, cti mv, ct1 mv, ct2 mv, ct3 mv).\n\nDefinition mvec_of_tuple tup : mvec mt :=\n  let: (cop, ctpc, cti, ct1, ct2, ct3) := tup in\n  MVec cop ctpc cti ct1 ct2 ct3.\n\nLemma tuple_of_mvecK : cancel tuple_of_mvec mvec_of_tuple.\nProof. by case. Qed.\n\nDefinition mvec_choiceMixin := CanChoiceMixin tuple_of_mvecK.\nCanonical mvec_choiceType := Eval hnf in ChoiceType (mvec mt) mvec_choiceMixin.\nDefinition mvec_ordMixin := CanOrdMixin tuple_of_mvecK.\nCanonical mvec_ordType := Eval hnf in OrdType (mvec mt) mvec_ordMixin.\n\nEnd MVecOrdType.\n\nRecord rvec (mt : machine_types) : Type := RVec {\n  ctrpc : mword mt;\n  ctr   : mword mt\n}.\n\nDefinition rvec_eqb mt (r1 r2 : rvec mt) : bool :=\n  [&& ctrpc r1 == ctrpc r2 & ctr r1 == ctr r2].\n\nLemma rvec_eqbP mt : Equality.axiom (@rvec_eqb mt).\nProof.\n  move => r1 r2.\n  case: r1 => *. case: r2 => *.\n  apply (iffP andP); simpl.\n  - by move => [/eqP -> /eqP ->].\n  - move => [-> ->]. by rewrite !eqxx.\nQed.\n\nDefinition rvec_eqMixin mt := EqMixin (@rvec_eqbP mt).\nCanonical rvec_eqType mt :=\n  Eval hnf in EqType (rvec mt) (rvec_eqMixin mt).\n\nDefinition rules mt := {fmap mvec mt -> rvec mt}.\n\nSection WithClasses.\n\nContext (mt : machine_types).\nContext (ops : machine_ops mt).\n\nLet mvec := mvec mt.\nLet rvec := rvec mt.\nLet rules := rules mt.\nLet atom := atom (mword mt) (mword mt).\n\n(* If we were doing good modularization, these would be abstract! *)\nDefinition cache_line_addr : mword mt := 0%w.\n(* BCP: Call it fault_handler_addr? *)\nDefinition fault_handler_start : mword mt := as_word 8.\nDefinition TNone   : mword mt := as_word 8.\nDefinition TMonitor : mword mt := 0.\n\nContext {spops : machine_ops_spec ops}.\n\nDefinition Mop : mword mt := (cache_line_addr + 0)%w.\nDefinition Mtpc : mword mt := (cache_line_addr + 1)%w.\nDefinition Mti : mword mt := (cache_line_addr + as_word 2)%w.\nDefinition Mt1 : mword mt := (cache_line_addr + as_word 3)%w.\nDefinition Mt2 : mword mt := (cache_line_addr + as_word 4)%w.\nDefinition Mt3 : mword mt := (cache_line_addr + as_word 5)%w.\nDefinition Mtrpc : mword mt := (cache_line_addr + as_word 6)%w.\nDefinition Mtr : mword mt := (cache_line_addr + as_word 7)%w.\n\nDefinition mvec_fields := [:: Mop; Mtpc; Mti; Mt1; Mt2; Mt3].\nDefinition rvec_fields := [:: Mtrpc; Mtr].\nDefinition mvec_and_rvec_fields := mvec_fields ++ rvec_fields.\n\nInductive mvec_part : Set :=\n  | mvp_tpc : mvec_part\n  | mvp_ti  : mvec_part\n  | mvp_t1  : mvec_part\n  | mvp_t2  : mvec_part\n  | mvp_t3  : mvec_part.\n\nDefinition DCMask := mvec_part -> bool.\n\nRecord CTMask : Set := mkCTMask {\n  ct_trpc : option mvec_part;\n  ct_tr   : option mvec_part\n}.\n\nRecord Mask : Set := {\n  dc : DCMask; (* don't care *)\n  ct : CTMask  (* copy through *)\n}.\n\nDefinition Masks := bool -> opcode -> Mask.\n\nDefinition mask_dc (dcm : DCMask) (mv : mvec) : mvec :=\n  let '(MVec op tpc ti t1 t2 t3) := mv in\n  MVec op\n    (if dcm mvp_tpc then TNone else tpc)\n    (if dcm mvp_ti  then TNone else ti)\n    (if dcm mvp_t1  then TNone else t1)\n    (if dcm mvp_t2  then TNone else t2)\n    (if dcm mvp_t3  then TNone else t3).\n\nDefinition copy_mvec_part (mv : mvec) (tag : mword mt)\n    (x : option mvec_part) : mword mt :=\n  match x with\n  | Some mvp_tpc => ctpc mv\n  | Some mvp_ti  => cti mv\n  | Some mvp_t1  => ct1 mv\n  | Some mvp_t2  => ct2 mv\n  | Some mvp_t3  => ct3 mv\n  | None         => tag\n  end.\n\nDefinition copy (mv : mvec) (rv : rvec) (ctm : CTMask) : rvec :=\n  RVec (copy_mvec_part mv (ctrpc rv) (ct_trpc ctm))\n         (copy_mvec_part mv (ctr   rv) (ct_tr   ctm)).\n\nDefinition is_monitor_tag (tpc:mword mt) : bool := tpc == TMonitor.\n\nDefinition cache_lookup (cache : rules)\n    (masks : Masks) (mv : mvec) : option rvec :=\n  let mask := masks (is_monitor_tag (ctpc mv)) (cop mv) in\n  let masked_mv := mask_dc (dc mask) mv in\n  do! rv <- getm cache masked_mv;\n  Some (copy mv rv (ct mask)).\n\nLocal Notation memory := {fmap mword mt -> atom}.\nLocal Notation registers := {fmap reg mt -> atom}.\n\nRecord state := State {\n  mem   : memory;\n  regs  : registers;\n  cache : rules;\n  pc    : atom;\n  epc   : atom\n}.\n\nDefinition pcv (s : state) := vala (pc s).\nDefinition pct (s : state) := taga (pc s).\n\nLemma state_eta (cst : state) :\n  cst = State (mem cst)\n                (regs cst)\n                (cache cst)\n                (pcv cst)@(pct cst)\n                (epc cst).\nProof. by case: cst=> ? ? ? [? ?] ?. Qed.\n\n(* Need to do this masking both on lookup, and on rule add, right?\n   This is optional; the software could do it *)\nDefinition add_rule (cache : rules) (masks : Masks) (mem : memory) : option rules :=\n  do! aop   <- mem Mop;\n  do! atpc  <- mem Mtpc;\n  do! ati   <- mem Mti;\n  do! at1   <- mem Mt1;\n  do! at2   <- mem Mt2;\n  do! at3   <- mem Mt3;\n  do! atrpc <- mem Mtrpc;\n  do! atr   <- mem Mtr;\n  do! op    <- op_of_word (vala aop);\n  let dcm := dc (masks false op) in\n  let mv := mask_dc dcm (MVec op (vala atpc)\n                              (vala ati) (vala at1) (vala at2) (vala at3)) in\n  Some (setm cache mv (RVec (vala atrpc) (vala atr))).\n\nDefinition store_mvec (mem : memory) (mv : mvec) : memory :=\n  unionm [fmap (Mop, (word_of_op (cop mv))@TMonitor);\n               (Mtpc, (ctpc mv)@TMonitor);\n               (Mti, (cti mv)@TMonitor);\n               (Mt1, (ct1 mv)@TMonitor);\n               (Mt2, (ct2 mv)@TMonitor);\n               (Mt3, (ct3 mv)@TMonitor)]\n         mem.\n\nSection ConcreteSection.\n\nVariable masks : Masks.\n\nLocal Notation \"x .+1\" := (x + 1)%w.\n\n(* The mvector is written at fixed locations in monitor memory where\n   the fault handler can access them (using the same addresses as for\n   add_rule: Mop, Mtpc, etc.) *)\nDefinition miss_state (st : state) (mvec : mvec) : state :=\n  let mem' := store_mvec (mem st) mvec in\n  State mem' (regs st) (cache st) fault_handler_start@TMonitor (pc st).\n\n\n(* The next functions build the next state by looking up on the cache,\n   finding the appropriate tag values for the results and using those\n   combined with its arguments (new register value and/or new pc value\n   *)\n(* TODO: find better name for these ... lookup? *)\n(* BCP: check? *)\n\nDefinition next_state (st : state) (mvec : mvec)\n                      (k : rvec -> option state) : option state :=\n  let lookup := cache_lookup (cache st) masks mvec in\n  match lookup with\n  | Some rvec => k rvec\n  | None => Some (miss_state st mvec)\n  end.\n\nDefinition next_state_reg_and_pc (st : state) (mvec : mvec) (r : reg mt) x pc' : option state :=\n  next_state st mvec (fun rvec =>\n    do! reg' <- updm (regs st) r x@(ctr rvec);\n    Some (State (mem st) reg' (cache st) pc'@(ctrpc rvec) (epc st))).\n\nDefinition next_state_reg (st : state) (mvec : mvec) r x : option state :=\n  next_state_reg_and_pc st mvec r x (vala (pc st)).+1.\n\nDefinition next_state_pc (st : state) (mvec : mvec) x : option state :=\n  next_state st mvec (fun rvec =>\n    Some (State (mem st) (regs st) (cache st) x@(ctrpc rvec) (epc st))).\n\nInductive step (st st' : state) : Prop :=\n| step_nop :\n    forall mem reg cache pc epc tpc i ti,\n    forall (ST : st = State mem reg cache pc@tpc epc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (Nop _)),\n    let mv := MVec NOP tpc ti TNone TNone TNone in\n    forall (NEXT : next_state_pc st mv (pc.+1) = Some st'),\n      step st st'\n| step_const :\n    forall mem reg cache pc epc n r tpc i ti old told,\n    forall (ST : st = State mem reg cache pc@tpc epc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (Const n r)),\n    forall (OLD : reg r = Some old@told),\n    let mv := MVec CONST tpc ti told TNone TNone in\n    forall (NEXT : next_state_reg st mv r (swcast n) = Some st'),\n      step st st'\n| step_mov :\n    forall mem reg cache pc epc r1 w1 r2 tpc i ti t1 old told,\n    forall (ST : st = State mem reg cache pc@tpc epc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (Mov r1 r2)),\n    forall (REG1 : reg r1 = Some w1@t1),\n    forall (OLD : reg r2 = Some old@told),\n    let mv := MVec MOV tpc ti t1 told TNone in\n    forall (NEXT : next_state_reg st mv r2 w1 = Some st'),\n      step st st'\n| step_binop :\n    forall mem reg cache pc epc op r1 r2 r3 w1 w2 tpc i ti t1 t2 old told,\n    forall (ST : st = State mem reg cache pc@tpc epc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (Binop op r1 r2 r3)),\n    forall (REG1 : reg r1 = Some w1@t1),\n    forall (REG2 : reg r2 = Some w2@t2),\n    forall (OLD : reg r3 = Some old@told),\n    let mv := MVec (BINOP op) tpc ti t1 t2 told in\n    forall (NEXT : next_state_reg st mv r3 (binop_denote op w1 w2) =\n                   Some st'),\n      step st st'\n| step_load :\n    forall mem reg cache pc epc r1 r2 w1 w2 tpc i ti t1 t2 old told,\n    forall (ST : st = State mem reg cache pc@tpc epc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (Load r1 r2)),\n    forall (REG1 : reg r1 = Some w1@t1),\n    forall (M1 : mem w1 = Some w2@t2),\n    forall (OLD : reg r2 = Some old@told),\n    let mv := MVec LOAD tpc ti t1 t2 told in\n    forall (NEXT : next_state_reg st mv r2 w2 = Some st'),\n      step st st'\n| step_store :\n    forall mem reg cache pc epc r1 r2 w1 w2 w3 tpc i ti t1 t2 t3,\n    forall (ST : st = State mem reg cache pc@tpc epc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (Store r1 r2)),\n    forall (REG1 : reg r1 = Some w1@t1),\n    forall (REG2 : reg r2 = Some w2@t2),\n    forall (M1 : mem w1 = Some w3@t3),\n    let mv := MVec STORE tpc ti t1 t2 t3 in\n    forall (NEXT :\n      next_state st mv (fun rvec =>\n        do! mem' <- updm mem w1 w2@(ctr rvec);\n        Some (State mem' reg cache (pc.+1)@(ctrpc rvec) epc)) = Some st'),\n      step st st'\n| step_jump :\n    forall mem reg cache pc epc r w tpc i ti t1,\n    forall (ST : st = State mem reg cache pc@tpc epc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (Jump r)),\n    forall (REG : reg r = Some w@t1),\n    let mv := MVec JUMP tpc ti t1 TNone TNone in\n    forall (NEXT : next_state_pc st mv w = Some st'),\n      step st st'\n| step_bnz :\n    forall mem reg cache pc epc r n w tpc i ti t1,\n    forall (ST : st = State mem reg cache pc@tpc epc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (Bnz r n)),\n    forall (REG : reg r = Some w@t1),\n    let mv := MVec BNZ tpc ti t1 TNone TNone in\n    let pc' := pc + if w == 0 then 1 else swcast n in\n    forall (NEXT : next_state_pc st mv pc' = Some st'),\n      step st st'\n| step_jal :\n    forall mem reg cache pc epc r w tpc i ti t1 old told,\n    forall (ST : st = State mem reg cache pc@tpc epc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (Jal r)),\n    forall (REG : reg r = Some w@t1),\n    forall (OLD: reg ra = Some old@told),\n    let mv := MVec JAL tpc ti t1 told TNone in\n    forall (NEXT : next_state_reg_and_pc st mv ra (pc.+1) w = Some st'),\n      step st st'\n| step_jumpepc :\n    forall mem reg cache pc tpc w tepc i ti,\n    forall (ST : st = State mem reg cache pc@tpc w@tepc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (JumpEpc _)),\n    let mv := MVec JUMPEPC tpc ti tepc TNone TNone in\n    forall (NEXT : next_state_pc st mv w = Some st'),\n      step st st'\n| step_addrule :\n    forall mem reg cache pc epc tpc i ti,\n    forall (ST : st = State mem reg cache pc@tpc epc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (AddRule _)),\n    let mv := MVec ADDRULE tpc ti TNone TNone TNone in\n    forall (NEXT :\n      next_state st mv (fun rvec =>\n        do! cache' <- add_rule cache masks mem;\n        Some (State mem reg cache' (pc.+1)@(ctrpc rvec) epc)) = Some st'),\n      step st st'\n| step_gettag :\n    forall mem reg cache pc epc r1 r2 w tpc i ti t1 old told,\n    forall (ST : st = State mem reg cache pc@tpc epc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (GetTag r1 r2)),\n    forall (REG : reg r1 = Some w@t1),\n    forall (OLD : reg r2 = Some old@told),\n    let mv := MVec GETTAG tpc ti t1 told TNone in\n    forall (NEXT : next_state_reg st mv r2 t1 = Some st'),\n      step st st'\n| step_puttag :\n    forall mem reg cache pc epc r1 r2 r3 w t tpc i ti t1 t2 old told,\n    forall (ST : st = State mem reg cache pc@tpc epc),\n    forall (PC : mem pc = Some i@ti),\n    forall (INST : decode_instr i = Some (PutTag r1 r2 r3)),\n    forall (REG1 : reg r1 = Some w@t1),\n    forall (REG2 : reg r2 = Some t@t2),\n    forall (OLD: reg r3 = Some old@told),\n    let mv := MVec PUTTAG tpc ti t1 t2 told in\n    forall (NEXT :\n      next_state st mv (fun rvec =>\n        do! reg' <- updm reg r3 w@t;\n        Some (State mem reg' cache (pc.+1@(ctrpc rvec)) epc)) = Some st'),\n      step st st'.\n\nEnd ConcreteSection.\n\nEnd WithClasses.\n\nNotation memory mt := {fmap mword mt -> atom (mword mt) (mword mt)}.\nNotation registers mt := {fmap reg mt -> atom (mword mt) (mword mt)}.\n\nEnd Concrete.\n\nModule Exports.\n\nImport Concrete.\n\nDefinition state_eqb mt : rel (state mt) :=\n  [rel s1 s2 | [&& mem s1 == mem s2,\n                   regs s1 == regs s2,\n                   cache s1 == cache s2,\n                   pc s1 == pc s2 &\n                   epc s1 == epc s2] ].\n\nLemma state_eqbP mt : Equality.axiom (@state_eqb mt).\nProof.\n  move => [? ? ? ? ?] [? ? ? ? ?].\n  apply (iffP and5P); simpl.\n  - by move => [/eqP -> /eqP -> /eqP -> /eqP -> /eqP ->].\n  - by move => [-> -> -> -> ->].\nQed.\n\nDefinition state_eqMixin mt := EqMixin (@state_eqbP mt).\nCanonical state_eqType mt := EqType (state mt) (@state_eqMixin mt).\n\nEnd Exports.\n\nExport Exports.\n\nArguments Concrete.State {_} _ _ _ _ _.\nArguments Concrete.TNone {mt}.\nArguments Concrete.TMonitor {mt}.\n", "meta": {"author": "micro-policies", "repo": "micro-policies-coq", "sha": "28163163c88387fc24475ed219f5705f9e0d4fc6", "save_path": "github-repos/coq/micro-policies-micro-policies-coq", "path": "github-repos/coq/micro-policies-micro-policies-coq/micro-policies-coq-28163163c88387fc24475ed219f5705f9e0d4fc6/concrete/concrete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23023565490675166}}
{"text": "Require Import Terms.\nRequire Import LBracketSyntax.\nRequire Import LThrowBigStep. (* reuse helpers *)\n\n(** * Continuations and partial configurations *)\n\nInductive Frame : Type :=\n| RLet : Var -> Tm -> Frame\n| RRet : Env -> Frame\n| RBrk : Lab -> Lab -> Frame (* final label + original pc *)\n| RCatch : Var -> Tm -> Frame.\n\nDefinition Cont := list Frame.\n\nDefinition PCfg := prod (prod Lab Env) Cont.\n\nInductive RCfg : Type :=\n| CR : Tm -> RCfg     (* term to be reduced *)\n| CA : Atom -> RCfg   (* return atom *)\n| CT : Excp -> RCfg.  (* thrown exception *)\n\nDefinition Cfg := prod PCfg RCfg.\n\nDefinition result_to_rcfg r :=\n  match r with\n  | Suc a => CA a\n  | Throw e => CT e\n  end.\n\n(** * Small-step Semantics for LambdaThrow *)\n\nNotation \"b @ L\" := (b,L) (at level 5).\n\nNotation \"<< pc , r , k , X >>\" := (((pc, r), k), X) (at level 5).\n\n(** The reduction relation. *)\nDefinition step (c : Cfg) : Cfg :=\n  match c with\n  (* s_var *)\n  | << pc, rho, k, CR (TVar x) >> =>\n    match get rho x with\n    | Some a => << pc, rho, k, CA a >>\n    | None => << pc, rho, k, CT eUnbound >>\n    end\n  (* s_const *)\n  | << pc, rho, k, CR (TConst c) >> =>\n    << pc, rho, k, CA (VConst c)@bot>>\n  (* s_let_start *)\n  | << pc, rho, k, CR (TLet x t1 t2) >> =>\n    << pc, rho, RLet x t2 :: k, CR t1 >>\n  (* s_let_bind *)\n  | << pc, rho, RLet x t :: k, CA a >> =>\n    << pc, (x,a) :: rho, RRet rho :: k, CR t >>\n  (* s_let_unwind *)\n  | << pc, rho, RLet x t :: k, CT e >> =>\n    << pc, rho, k, CT e >>\n  (* s_abs *)\n  | << pc, rho, k, CR (TAbs x t) >> =>\n    << pc, rho, k, CA (VClos rho x t)@bot >>\n  (* s_app *)\n  | << pc, rho, k, CR (TApp x1 x2) >> =>\n    match get rho x1, get rho x2 with\n    | Some (VClos rho' x t)@L, Some a =>\n      << pc\\_/L, (x,a) :: rho', RRet rho :: k, CR t >>\n    | Some (v,L), Some a =>\n      << pc\\_/L, rho, k, CT eType >>\n    | _, _ => \n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_return *)\n  | << pc, rho, RRet rho' :: k, CA a >> =>\n    << pc, rho', k, CA a >>\n  (* s_return_unwind *)\n  | << pc, rho, RRet rho' :: k, CT e >> =>\n    << pc, rho', k, CT e >>\n  (* s_inx *)\n  | << pc, rho, k, CR (TInx d x) >> =>\n    match get rho x with\n    | Some a =>\n      << pc, rho, k, CA (VInx d a)@bot >>\n    | _ =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_match *)\n  | << pc, rho, k, CR (TMatch x x' t1 t2) >> =>\n    match get rho x with\n    | Some (VInx DLeft a, l) =>\n      << pc\\_/l, (x',a) :: rho, RRet rho :: k, CR t1 >>\n    | Some (VInx DRight a, l) =>\n      << pc\\_/l, (x',a) :: rho, RRet rho :: k, CR t2 >>\n    | Some (_,l) =>\n      << pc\\_/l, rho, k, CT eType >>\n    | _ =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_tag *)\n  | << pc, rho, k, CR (TTag x) >> =>\n    match get rho x with\n    | Some (v,l) =>\n      << pc, rho, k, CA (vTag (tag_of v))@l >>\n    | _ =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_bop *)\n  | << pc, rho, k, CR (TBOp b x' x'') >> =>\n    match get rho x', get rho x'' with\n    | Some v'@l', Some v''@l'' =>\n      << pc\\_/l'\\_/l'', rho, k, result_to_rcfg (bop_result b v' v'')  >>\n    | _,_  =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_bracket_start *)\n  | << pc, rho, k, CR (TBracket x t) >> =>\n    match get rho x with\n    | Some (VConst (CLab L))@L' =>\n      << pc\\_/L', rho, RBrk L (pc\\_/L') :: k, CR t >>\n    | Some (v,L') => \n      << pc\\_/L', rho, k, CT eType >>\n    | None =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_bracket_end *)\n  | << pc, rho, RBrk L' pc' :: k, CA v@L >> =>\n    << pc', rho, k, CA (bracket_val (Suc v@L) pc (L' \\_/ pc'))@L' >>\n  | << pc, rho, RBrk L' pc' :: k, CT e >> =>\n    << pc', rho, k, CA (bracket_val (Throw e) pc (L' \\_/ pc'))@L' >>\n  (* s_label_of *)\n  | << pc, rho, k, CR (TLabelOf x) >> =>\n    match get rho x with\n    | Some (_,l) =>\n      << pc, rho, k, CA (vLab l)@bot >>\n    | _ =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_get_pc *)\n  | << pc, rho, k, CR TGetPc >> =>\n    << pc, rho, k, CA (vLab pc)@bot >>\n  (* s_throw *)\n  | << pc, rho, k, CR (TThrow x) >> =>\n    match get rho x with\n    | Some (v,l) =>\n      << pc\\_/l, rho, k, CT (throw_excp v) >>\n    | _ =>\n      << pc, rho, k, CT eUnbound >>\n    end\n  (* s_catch *)\n  | << pc, rho, k, CR (TCatch t x t') >> =>\n    << pc, rho, RCatch x t' :: k, CR t >>\n  (* s_catch_no_excp *)\n  | << pc, rho, RCatch x t' :: k, CA a >> =>\n    << pc, rho, k, CA a >>\n  (* s_catch_excp *)\n  | << pc, rho, RCatch x t' :: k, CT e >> =>\n    << pc, (x,(vExcp e)@bot) :: rho, RRet rho :: k, CR t' >>\n  (* stack underflow (you're already done?) *)\n  | << pc, rho, nil, CA _ >> =>\n      << pc, rho, nil, CT eStack >>\n  | << pc, rho, nil, CT _ >> =>\n      << pc, rho, nil, CT eStack >>\n  (* terms not from this language *)\n  | << pc, rho, k, CR (TMkNav _) >> =>\n      << pc, rho, k, CT eLanguage >>\n  | << pc, rho, k, CR (TToSum _) >> =>\n      << pc, rho, k, CT eLanguage >>\n  end.\n\n(* There are 7 different kinds of steps,\n   here is how the stack evolves for each of them:\n1. CR -> CR -- stack: push\n2. CR -> CA -- stack: no change\n3. CA -> CR -- stack: pop + maybe push (beta does pop but not push)\n4. CA -> CA -- stack: pop\n5. CA -> CT -- stack: no change (throw)\n6. CT -> CT -- stack: clear (unwind)\n7. CT -> CA -- stack: pop (catch)\n*)\n\nDefinition final (c : Cfg) : bool :=\n  match c with\n  | << pc, rho, nil, CA _ >> => true\n  | << pc, rho, nil, CT _ >> => true\n  | _ => false\n  end.\n\nFixpoint nstep (n : nat) (cm : Cfg*nat) : Cfg*nat :=\n  match n with\n  | S n' =>\n    match cm with\n    | (c,m) => if final c then (c,m) else nstep n' (step c, m+1)\n    end\n  | O => cm\n  end.\n\nFixpoint lnstep (n : nat) (cl : Cfg*(list Cfg)) : Cfg*(list Cfg) :=\n  match n with\n  | S n' =>\n    match cl with\n    | (c,l) => if final c then (c,l) else lnstep n' (step c, c::l)\n    end\n  | O => cl\n  end.\n\nDefinition mstep (n : nat) (t : Tm) : Cfg*nat :=\n  nstep n (<< bot, nil, nil, CR t >>, 0).\n\nDefinition lmstep (n : nat) (t : Tm) : Cfg*(list Cfg) :=\n  lnstep n (<< bot, nil, nil, CR t >>, []).\n\nDefinition sstep (n : nat) (t : Tm) : option ((Result*Lab)*nat) :=\n  match mstep n t with\n  | (<< pc, rho, nil, CA a >>, m) => Some ((Suc a,pc),m)\n  | (<< pc, rho, nil, CT e >>, m) => Some ((Throw e,pc),m)\n  | _ => None (* looping or need more steps *)\n  end.\n", "meta": {"author": "mgree", "repo": "navdifc", "sha": "cde33f3ef7170b59653e252513ec6fc7ed78983a", "save_path": "github-repos/coq/mgree-navdifc", "path": "github-repos/coq/mgree-navdifc/navdifc-cde33f3ef7170b59653e252513ec6fc7ed78983a/LThrowSmallStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.23023564916092623}}
{"text": "From Coq Require Import Bool List Program Lia.\nFrom MetaCoq.Template Require Import config utils.\nRequire Import MetaCoq.Template.Universes.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICValidity PCUICGeneration\n     PCUICTyping PCUICWeakeningEnv PCUICWeakening.\n\nFrom MetaCoq.PCUIC Require Import PCUICSigmaCalculus.\nSet Printing All.\n\nDefinition universes_decl_extends (u v: universes_decl) : Type :=\n  match (u,v) with\n  | (Monomorphic_ctx u', Monomorphic_ctx v') => LevelSet.Subset (fst u') (fst v') * ConstraintSet.Subset (snd u') (snd v')\n  | (Polymorphic_ctx u', Polymorphic_ctx v') => True\n  | _ => False\n  end.\n\nLemma universes_decl_extends_wf_local `{checker_flags} Σ Γ (wfΓ : wf_local Σ Γ):\n  All_local_env_over typing\n         (fun (Σ : global_env_ext) (Γ : context) (_ : wf_local Σ Γ)\n            (t T : term) (_ : Σ;;; Γ |- t : T) =>\n          forall u : ContextSet.t,\n          (*satisfiable_udecl Σ.1 (Monomorphic_ctx u) ->*)\n          universes_decl_extends Σ.2 (Monomorphic_ctx u) ->\n          (Σ.1, Monomorphic_ctx u);;; Γ |- t : T) Σ Γ wfΓ ->\n  forall u, (*satisfiable_udecl Σ.1 (Monomorphic_ctx u) ->*)\n            universes_decl_extends Σ.2 (Monomorphic_ctx u) ->\n            wf_local (Σ.1, Monomorphic_ctx u) Γ.\nProof.\n  intros. induction X; econstructor; pose (X1 := X0);\n    specialize p with u; apply p in X1;\n    pose (X2 := X1);\n    try (apply typing_wf_local in X2; specialize p0 with u; apply p0 in X0);\n    try solve [eauto|eassumption]; exists (tu.π1); eassumption.\nQed.\n\nLemma weakening_universe_decl_cumul `{CF:checker_flags} Σ u Γ M N :\n  (*satisfiable_udecl Σ.1 (Monomorphic_ctx u) ->*)\n  universes_decl_extends Σ.2 (Monomorphic_ctx u) ->\n  cumul Σ Γ M N -> cumul (Σ.1, (Monomorphic_ctx u)) Γ M N.\nProof.\n  intros (*st*) univ;\n    destruct (Σ.2) eqn: Σ_eq; revgoals; first exfalso; subst; auto.\n  induction 1; simpl.\n  - econstructor. eapply (PCUICWeakeningEnv.leq_term_subset); revgoals. eassumption.\n    unfold global_ext_constraints, ConstraintSet.Subset; intros.\n    rewrite ConstraintSet.union_spec.\n    rewrite ConstraintSet.union_spec in H.\n    cbn in univ. destruct H; eauto using univ, H.\n    left. simpl. apply (snd univ). rewrite Σ_eq in H.\n    eassumption.\n  - econstructor 2; eauto.\n  - econstructor 3; eauto.\n  - econstructor 4; eauto.\n  - econstructor 5; eauto.\nQed.\n\nLemma global_ext_univ_ext Sigma v u:\n  universes_decl_extends v u ->\n  LevelSet.Subset (global_ext_levels (Sigma, v)) (global_ext_levels (Sigma, u)).\nProof.\n  intros.\n  destruct v eqn: v_eq; destruct u eqn: u_eq; revgoals; try solve[(exfalso; auto)].\n  1: admit.\n  unfold global_ext_levels, levels_of_udecl, LevelSet.Subset.\n  simpl. intros.\n  apply LevelSet.union_spec. apply LevelSet.union_spec in H.\n  destruct H; auto; left. now apply (fst X).\nAdmitted.\n\nLemma weakening_universe_decl_consist `{checker_flags} Σ phi t u:\n  (*satisfiable_udecl Σ.1 (Monomorphic_ctx u) ->*)\n  universes_decl_extends Σ.2 (Monomorphic_ctx u) ->\n  consistent_instance_ext Σ phi t ->\n  consistent_instance_ext (Σ.1, Monomorphic_ctx u) phi t.\nProof.\n  intros univ.\n  unfold consistent_instance_ext, consistent_instance. destruct phi.\n  - trivial.\n  - destruct 1 as [prop [mem [eq vc]]]. split; auto. split.\n    + apply forallb_forall. intros x. intros IN. eapply forallb_forall in mem.\n      apply LevelSet.mem_spec. apply LevelSet.mem_spec in mem.\n      eapply global_ext_univ_ext; eauto. eassumption.\n    + split; eauto.\n      unfold valid_constraints. unfold valid_constraints in vc.\n      destruct check_univs; eauto.\n      unfold valid_constraints0.  unfold valid_constraints0 in vc.\n      intros. apply vc.\n      unfold satisfies. unfold satisfies in H0.\n      unfold ConstraintSet.For_all. unfold ConstraintSet.For_all in H0.\n      intros x ins. apply H0.\n      unfold global_ext_constraints. unfold global_ext_constraints in ins.\n      apply ConstraintSet.union_spec. apply ConstraintSet.union_spec in ins.\n      destruct ins; auto. left. simpl.\n      destruct (Σ.2) eqn: Σ_eq; revgoals. exfalso. auto.\n      apply (snd univ). eassumption.\nQed.\n\n\nLemma weakening_env_univ `{checker_flags}:\n  env_prop (fun Σ Γ t T =>\n              forall u, universes_decl_extends Σ.2 (Monomorphic_ctx u) -> (Σ.1, (Monomorphic_ctx u)) ;;; Γ |- t : T).\nProof.\n  apply typing_ind_env; intros; rename_all_hyps.\n    all: (destruct (Σ.2) eqn: Σ_eq; revgoals; first exfalso; auto;\n          try solve[(econstructor; eauto)|eassumption]).\n  - econstructor.\n    + eapply universes_decl_extends_wf_local; eauto; rewrite Σ_eq; eassumption.\n    + eauto.\n  - econstructor.\n    + eapply universes_decl_extends_wf_local; eauto; rewrite Σ_eq; eassumption.\n    + unfold global_ext_levels, levels_of_udecl.\n      unfold global_ext_levels, levels_of_udecl in H0.\n      apply LevelSet.union_spec. apply LevelSet.union_spec in H0.\n      destruct H0; eauto using H0, X0.\n      left. apply (fst X0). rewrite Σ_eq in H0. eassumption.\n  - econstructor; eauto.\n    + eapply universes_decl_extends_wf_local; eauto; rewrite Σ_eq; eassumption.\n    + unfold consistent_instance_ext. unfold consistent_instance_ext in H1.\n      eapply weakening_universe_decl_consist; try (rewrite Σ_eq); eauto.\n  - econstructor; eauto.\n    + eapply universes_decl_extends_wf_local; eauto; rewrite Σ_eq; eassumption.\n    + eapply weakening_universe_decl_consist; try (rewrite Σ_eq); eauto.\n  - econstructor; eauto using X, X0.\n    + eapply universes_decl_extends_wf_local; eauto. rewrite Σ_eq. eassumption.\n    + eapply weakening_universe_decl_consist; try (rewrite Σ_eq); eauto.\n  - econstructor; eauto using X, X0.\n    close_Forall. intros; intuition.\n  - econstructor; eauto.\n    eapply All_local_env_impl. eapply X. simpl; intros.\n    unfold lift_typing in *; destruct T; intuition eauto.\n    apply b; try rewrite Σ_eq; eauto.\n    destruct X2 as [s [tyu Hu]]. exists s. eapply Hu; try rewrite Σ_eq; eauto.\n    eapply All_impl; eauto; simpl; intuition eauto.\n  - econstructor; eauto.\n    eapply All_local_env_impl. eapply X.\n    simpl; intros.\n    unfold lift_typing in *; destruct T; intuition eauto.\n    eapply b; try rewrite Σ_eq; eauto.\n    destruct X2 as [s [tyu Hu]]. exists s. eapply Hu; try rewrite Σ_eq; eauto.\n    eapply All_impl; eauto; simpl; intuition eauto.\n  - econstructor. eauto.\n    destruct X2 as [isB|[s [Hu Ps]]].\n    + left; auto. destruct isB. destruct x as [ctx' [s' [Heq Hu]]].\n      exists ctx', s'. split; eauto.\n      eapply universes_decl_extends_wf_local; eauto. rewrite Σ_eq. eassumption.\n    + right. exists s. eapply Ps; auto.\n    + destruct Σ as [Σ φ].\n      eapply weakening_universe_decl_cumul; try rewrite Σ_eq; cbn in wfΓ; eassumption.\nQed.\n\nDefinition weaken_decl_univ_prop `{checker_flags}\n           (P : global_env_ext -> context -> term -> option term -> Type) :=\n  forall Σ v u, wf Σ -> universes_decl_extends v (Monomorphic_ctx u) -> forall Γ t T, P (Σ, v) Γ t T -> P (Σ, (Monomorphic_ctx u)) Γ t T.\n\nLemma weaken_decl_univ_prop_typing `{checker_flags}:\n  weaken_decl_univ_prop (lift_typing typing).\nProof.\n  red. intros * * * * *.\n  destruct T; simpl.\n  - intros Ht.\n    eapply (weakening_env_univ (_, _)); eauto.\n    eapply typing_wf_local in Ht; eauto.\n  - intros [s Ht]. exists s.\n    eapply (weakening_env_univ (_, _)); eauto. eapply typing_wf_local in Ht; eauto.\nQed.\n\nLemma from_validity `{checker_flags} Sigma u Gamma T:\n  isWfArity_or_Type (Sigma, u) Gamma T ->\n  {u' & (universes_decl_extends u u') × {s & ((Sigma, u') ;;; Gamma |- T : tSort s)}}.\nProof.\n  intros.\n  destruct X as [isWf | isT];\n  revgoals.\n  - exists u. split.\n    1: {unfold universes_decl_extends, LevelSet.Subset, ConstraintSet.Subset; destruct u; auto. }\n    exact isT.\n  - destruct isWf as [ctx [s [desteq all_ctx]]].\n    dependent induction all_ctx. (*as [all_nil | all_ass | all_def].*)\n    + unfold app_context in x.\n      symmetry in x.\n      apply List.app_eq_nil in x. destruct x as [ctxnil gammanil]. subst.\n      assert (T = tSort s). {\n        induction T; unfold destArity in desteq; try inversion desteq; auto.\n        1-2: rewrite destArity_app in desteq.\n        1: destruct (destArity nil T2). 3: destruct (destArity nil T3).\n        1-4:cbn in desteq; try destruct p; inversion desteq;\n            unfold snoc, app_context in H2; symmetry in H2;\n            contradict H2; apply List.app_cons_not_nil. } clear desteq.\n      subst.\n      eexists. split; revgoals.\n      eexists.\n    + admit. (*eexists. split; revgoals. eexists.*)\n    + admit.\nAdmitted.\n", "meta": {"author": "uds-psl", "repo": "metacoq_plugins", "sha": "a599eb394f7413dfec8b4e96c52ee894d058d039", "save_path": "github-repos/coq/uds-psl-metacoq_plugins", "path": "github-repos/coq/uds-psl-metacoq_plugins/metacoq_plugins-a599eb394f7413dfec8b4e96c52ee894d058d039/subterm/universes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23023564341510075}}
{"text": "Require Import VST.floyd.base2.\nImport ListNotations.\nImport compcert.lib.Maps.\n\nModule PosOrder <: Orders.TotalLeBool.\n  Definition t := positive.\n  Definition leb := Pos.leb.\n  Theorem leb_total : forall a1 a2, Pos.leb a1 a2 = true \\/ Pos.leb a2 a1 = true.\n  Proof.  intros. \n    pose proof (Pos.leb_spec a1 a2).\n    pose proof (Pos.leb_spec a2 a1).\n    inv H; inv H0; auto.\n    clear - H2 H3. \n    pose proof (Pos.lt_trans _ _ _ H2 H3).\n    apply Pos.lt_irrefl in H. contradiction.\n  Qed.\nEnd PosOrder.\nModule SortPos := Mergesort.Sort(PosOrder).\n\nModule CompOrder <: Orders.TotalLeBool.\n  Definition t := composite_definition.\n  Definition leb := fun x y => Pos.leb (name_composite_def x) (name_composite_def y).\n  Theorem leb_total : forall a1 a2, leb a1 a2 = true \\/ leb a2 a1 = true.\n  Proof.  intros. unfold leb. \n    pose proof (Pos.leb_spec (name_composite_def a1) (name_composite_def a2)).\n    pose proof (Pos.leb_spec (name_composite_def a2) (name_composite_def a1)).\n    inv H; inv H0; auto.\n    clear - H2 H3. \n    pose proof (Pos.lt_trans _ _ _ H2 H3).\n    apply Pos.lt_irrefl in H. contradiction.\n  Qed.\nEnd CompOrder.\nModule SortComp := Mergesort.Sort(CompOrder).\n\nModule GlobdefOrder <: Orders.TotalLeBool.\n  Definition t := (ident * globdef (fundef function) type)%type.\n  Definition leb := fun x y : (ident * globdef (fundef function) type)=> Pos.leb (fst x) (fst y).\n  Theorem leb_total : forall a1 a2, leb a1 a2 = true \\/ leb a2 a1 = true.\n  Proof.  intros. unfold leb. \n    pose proof (Pos.leb_spec (fst a1) (fst a2)).\n    pose proof (Pos.leb_spec (fst a2) (fst a1)).\n    inv H; inv H0; auto.\n    clear - H2 H3. \n    pose proof (Pos.lt_trans _ _ _ H2 H3).\n    apply Pos.lt_irrefl in H. contradiction.\n  Qed.\nEnd GlobdefOrder.\nModule SortGlobdef := Mergesort.Sort(GlobdefOrder).\n\nDefinition isnil {A} (al: list A) := \n   match al with nil => true | _ => false end.\n\nLemma prod_eq_dec {A B} (Ha: forall (a1 a2:A), {a1 = a2} + {a1<>a2})\n      (Hb: forall (b1 b2:B), {b1 = b2} + {b1<>b2}):\n      forall (x y : A * B), {x=y} + {x<>y}.\nProof. intros. destruct x as [a1 b1]. destruct y as [a2 b2].\ndestruct (Ha a1 a2); [ subst | right; congruence].\ndestruct (Hb b1 b2); [ subst; left; trivial | right; congruence].\nDefined. \n\nLemma function_eq_dec (f g: function): { f=g } + { f <> g }.\nProof.\ndestruct f as [rtF ccF paramsF varsF tempsF bodyF].\ndestruct g as [rtG ccG paramsG varsG tempsG bodyG].\ndestruct (type_eq rtF rtG); [ subst | right; congruence].\ndestruct (calling_convention_eq ccF ccG); [ subst | right; congruence].\ndestruct (list_eq_dec (prod_eq_dec ident_eq type_eq) paramsF paramsG); [ subst | right; congruence].\ndestruct (list_eq_dec (prod_eq_dec ident_eq type_eq) varsF varsG); [ subst | right; congruence].\ndestruct (list_eq_dec (prod_eq_dec ident_eq type_eq) tempsF tempsG); [ subst | right; congruence].\ndestruct (semax_lemmas.eq_dec_statement bodyF bodyG); [ subst; left; trivial | right; congruence].\nDefined.\n\nDefinition merge_globdef (g1 g2: globdef (fundef function) type) :=\n match g1, g2 with\n | Gfun (External _ _ _ _), Gfun (External _ _ _ _) => \n     Errors.OK g1  (* SHOULD CHECK g1=g2 *)\n | Gfun (External _ _ _ _), Gfun (Internal f2) => \n     Errors.OK g2  (* SHOULD CHECK TYPES MATCH *)\n | Gfun (Internal f1), Gfun (External _ _ _ _) =>\n    Errors.OK g1  (* SHOULD CHECK TYPES MATCH *)\n | Gfun (Internal f), Gfun (Internal g) => Errors.OK g1 (*this is OK \n      since VSU.ComponentJoin contains hypothesis Fundefs_match*) \n    (*Errors.Error [Errors.MSG \"internal function clash\"]*)\n   (* if function_eq_dec f g then Errors.OK g1\n    else Errors.Error [Errors.MSG \"internal function clash\"]*)\n | Gvar {| gvar_info := i1; gvar_init := l1; gvar_readonly := r1; gvar_volatile := v1 |},\n   Gvar {| gvar_info := i2; gvar_init := l2; gvar_readonly := r2; gvar_volatile := v2 |} =>\n   if (eqb_type i1 i2 &&\n      bool_eq r1 r2 &&\n      bool_eq v1 v2)%bool\n   then if isnil l1 \n           then Errors.OK g2 \n           else if isnil l2 then Errors.OK g1 \n           else Errors.Error [Errors.MSG \"Gvars both initialized\"]\n   else Errors.Error [Errors.MSG \"Gvar type/readonly/volatile clash\"]\n  | _, _ => Errors.Error [Errors.MSG \"Gvar versus Gfun\"]\n end.\n\nFunction merge_global_definitions'\n    (d1 d2: list (ident * globdef (fundef function) type))\n    (fuel: nat) :=\n match fuel with\n | O => Errors.Error [Errors.MSG \"out of fuel\"]\n | S fuel' => \n  match d1, d2 with\n  | nil, _ => Errors.OK d2\n  | _, nil => Errors.OK d1\n  | (i1,g1)::d1', (i2,g2)::d2' => \n     if Pos.ltb i1 i2 \n     then match merge_global_definitions' d1' d2 fuel' with\n            | Errors.OK dl => Errors.OK ((i1,g1)::dl)\n            | err => err\n            end\n     else if Pos.ltb i2 i1\n     then match merge_global_definitions' d1 d2' fuel' with\n            | Errors.OK dl => Errors.OK ((i2,g2)::dl)\n            | err => err\n            end\n    else match merge_globdef g1 g2 with\n           | Errors.OK g => match merge_global_definitions' d1' d2' fuel' with\n                     | Errors.OK dl => Errors.OK ((i1,g)::dl)\n                     | Errors.Error el => Errors.Error el\n                    end\n            | Errors.Error err => Errors.Error (Errors.POS i1 :: err)\n            end\n end end.\n\nDefinition merge_global_definitions\n    (d1 d2: list (ident * globdef (fundef function) type)) :=\n merge_global_definitions' d1 d2 (length d1 + length d2).\n\nFixpoint merge_prog_types' (e1 e2: list composite_definition)\n                 (fuel: nat) \n              : Errors.res (list composite_definition) :=\n match fuel with\n | O => Errors.Error [Errors.MSG \"ran out of fuel in composites\"]\n | S fuel' => \n match e1, e2 with\n | nil, _ => Errors.OK e2\n | _, nil => Errors.OK e1\n | (Composite i1 su1 m1 a1 as c1) :: e1', \n   (Composite i2 su2 m2 a2 as c2) :: e2' =>\n   if Pos.ltb i1 i2 \n   then Errors.bind (merge_prog_types' e1' e2 fuel')\n          (fun e => Errors.OK (c1::e))\n   else if Pos.ltb i2 i1 \n   then Errors.bind (merge_prog_types' e1 e2' fuel')\n          (fun e => Errors.OK (c2::e))\n   else if (eqb_su su1 su2 &&\n              eqb_list eqb_member m1 m2 &&\n              eqb_attr a1 a2)%bool\n   then Errors.bind (merge_prog_types' e1' e2' fuel')\n          (fun e => Errors.OK (c1::e))\n   else Errors.Error [Errors.MSG \"struct/union does not match:\"; Errors.POS i1]\n end\nend.\n\nDefinition merge_prog_types e1 e2 :=\n merge_prog_types' e1 e2 (S(length e1 + length e2)).\n \nDefinition link_progs (prog1 prog2 : Clight.program) : \n  Errors.res Clight.program :=\n match prog1, prog2 with\n  {|prog_defs := d1;\n    prog_public := p1;\n    prog_main := m1;\n    prog_types := t1;\n    prog_comp_env := e1;\n    prog_comp_env_eq := q1|},\n  {|prog_defs := d2;\n    prog_public := p2;\n    prog_main := m2;\n    prog_types := t2;\n    prog_comp_env := e2;\n    prog_comp_env_eq := q2|}  =>\n Errors.bind (merge_global_definitions \n               (SortGlobdef.sort d1) (SortGlobdef.sort d2)) (fun d =>\n Errors.bind (merge_prog_types (SortComp.sort t1) (SortComp.sort t2)) (fun t =>\n match build_composite_env t as e \n       return (build_composite_env t = e -> Errors.res Clight.program) with\n | Errors.Error err => fun _ => Errors.Error err\n | Errors.OK e =>  fun q => \n if negb (eqb_ident m1 m2) \n   then Errors.Error [Errors.MSG \"main identifiers differ\"]\n   else\n    Errors.OK {| prog_defs := d;\n    prog_public := SortPos.merge (SortPos.sort p1) (SortPos.sort p2);\n    prog_main := m2;\n    prog_types := t;\n    prog_comp_env := e;\n    prog_comp_env_eq := q|} \n   end eq_refl ))\nend.\n\nDefinition link_progs_list (pl: list Clight.program) : \n  Errors.res Clight.program :=\n match pl with\n | nil => Errors.Error [Errors.MSG \"no programs to link\"]\n | p::pl' => List.fold_left (fun q p =>\n                  match q with\n                  | Errors.Error e => q\n                  | Errors.OK q' => link_progs q' p\n                  end) pl' (Errors.OK p)\n  end.\n\nLtac link_progs_list pl :=\n let q := constr:(linking.link_progs_list pl) in\n let q := eval hnf in q in\n let q := eval cbv beta iota delta [linking.SortComp.sort] in q in\n let q := eval simpl in q in\n match q with\n | Errors.Error ?e => fail 1 e\n | Errors.OK ?q' => exact q'\n end.\n\n(*duplicate of lemma in globals_lemas*)\nLemma prog_defs_Clight_mkprogram:\n forall c g p m w,\n prog_defs (Clightdefs.mkprogram c g p m w) = g.\nProof.\nintros. unfold Clightdefs.mkprogram.\ndestruct ( build_composite_env' c w).\nreflexivity.\nQed.\n\nLemma prog_types_Clight_mkprogram:\n  forall (c : list composite_definition) (g : list (ident * globdef Clight.fundef type)) (p : list ident) \n    (m : ident) (w : wf_composites c), prog_types (Clightdefs.mkprogram c g p m w) = c.\nProof. intros. unfold prog_types. unfold Clightdefs.mkprogram.\ndestruct (build_composite_env' c w ); trivial.\nQed. \n\nModule NEW_LINK_PROGS.  (* Everything in this Module should perhaps be moved to floyd/linking.v *)\n\n(* All of this complexity is because the naturally computed proof whose type is\n     build_composite_env t12 = Errors.OK e12\n  blows up:  the nested environments explode exponentially.\n And that's a pity, because after all we have  proof irrelevance.  But I could not\n think of a better way than this to exploit proof irrelevance.  -- Andrew, 7/24/2020\n*)\nDefinition carefully_link_progs (prog1 prog2 : Clight.program) \n  (MAIN: prog_main prog1 = prog_main prog2)\n  (d12: list (ident * globdef (fundef function) type))\n  (Hd12: merge_global_definitions \n               (SortGlobdef.sort (prog_defs prog1)) (SortGlobdef.sort (prog_defs prog2)) = Errors.OK d12)\n  (t12: list composite_definition) \n  (Ht12: merge_prog_types (SortComp.sort (prog_types prog1)) (SortComp.sort (prog_types prog2)) = Errors.OK t12)\n  (e12: composite_env)\n  (He12: build_composite_env t12 = Errors.OK e12)\n  : Clight.program := \n {| prog_defs := d12;\n    prog_public := SortPos.merge (SortPos.sort (prog_public prog1)) (SortPos.sort (prog_public prog2));\n    prog_main := prog_main prog2;\n    prog_types := t12;\n    prog_comp_env := e12;\n    prog_comp_env_eq := He12|} .\n\nLemma Gt_neq_Lt: Gt = Lt -> False.\nProof. congruence. Qed.\n\nLemma prove_exists_align_attr:\n  forall d, two_power_nat (Z.to_nat (Z.log2 d)) = d ->\n    exists n, align_attr noattr d = two_power_nat n.\nProof.\nintros.\nexists (Z.to_nat (Z.log2 d)).\nrewrite H. reflexivity.\nQed.\n\nLemma prove_align_attr:\n  forall i j,  (j/i)*i=j -> (align_attr noattr i | j).\nProof. intros. exists (j/i). symmetry. apply H. Qed. \n\nLtac process_composite_definitions_step := \nrepeat\nmatch goal with\n|- Errors.bind match ?z with _ => _ end  _  = _ => \n  set (j := z); hnf in j; simpl in j; subst j; cbv beta iota\nend;\n match goal with |- context [Ctypes.composite_of_def_obligation_1 _ _ _ _] =>\n   set (x := Ctypes.composite_of_def_obligation_1 _ _ _ _);\n  simpl in x;\n  match type of x with ?t => \n    replace x with (Gt_neq_Lt : t) by apply proof_irr\n end; \n  clear x\nend;\n match goal with |- context [Ctypes.composite_of_def_obligation_2 _ _ _] =>\n   set (x := Ctypes.composite_of_def_obligation_2 _ _ _);\n  simpl in x;\n  match type of x with (exists i, align_attr noattr ?d = two_power_nat i) => \n    replace x with (prove_exists_align_attr d (eq_refl _)) by apply proof_irr\n end; \n  clear x\nend;\nrepeat\n  match goal with |- context [Ctypes.composite_of_def_obligation_3 _ _ _ _] =>\n   set (x := Ctypes.composite_of_def_obligation_3 _ _ _ _);\n  simpl in x;\n  match type of x with (align_attr noattr ?i | ?j)  => \n    replace x with (prove_align_attr i j (eq_refl _)) by apply proof_irr\n end; \n  clear x\nend;\nchange (Errors.bind (Errors.OK ?x) ?f) with (f x); cbv beta iota.\n\nLtac process_composite_definitions :=\n simpl;\n unfold build_composite_env; \n unfold add_composite_definitions, composite_of_def; \n simpl align; simpl align_attr; simpl rank_members;\n simpl PTree.set;\n repeat process_composite_definitions_step;\n reflexivity.\n\nLtac do_merge_global_definitions := \nmatch goal with |- context [SortGlobdef.sort ?x] =>\n set (j :=SortGlobdef.sort x); hnf in j; simpl in j; subst j\nend;\nmatch goal with |- context [SortGlobdef.sort ?x] =>\n set (j :=SortGlobdef.sort x); hnf in j; simpl in j; subst j\nend;\nmatch goal with |- ?A = _ =>\n set (j :=A); hnf in j; simpl in j; subst j\nend; reflexivity.\n\nLtac do_merge_prog_types := \nmatch goal with |- context [SortComp.sort ?x] =>\n set (j :=SortComp.sort x); hnf in j; simpl in j; subst j\nend;\nmatch goal with |- context [SortComp.sort ?x] =>\n set (j :=SortComp.sort x); hnf in j; simpl in j; subst j\nend;\nmatch goal with |- ?A = _ =>\n set (j :=A); hnf in j; simpl in j; subst j\nend; reflexivity.  \n\nLtac do_link_progs_step1 p1 p2 := \n  eapply (carefully_link_progs p1 p2 (eq_refl _));\n  [time \"merge_global\" do_merge_global_definitions\n  |time \"merge_types\" do_merge_prog_types\n  |time \"process_composites\" process_composite_definitions].\n\nLtac do_merge_global_definitions_unfold p1 p2 :=\n  unfold p1; try rewrite prog_defs_Clight_mkprogram;\n  unfold p2; try rewrite prog_defs_Clight_mkprogram;\n  do_merge_global_definitions.\n\nLtac do_merge_prog_types_unfold p1 p2 :=\n unfold p1; try rewrite prog_types_Clight_mkprogram;\n unfold p2; try rewrite prog_types_Clight_mkprogram;\n  do_merge_prog_types.\n\nLtac do_link_progs_step1_unfold p1 p2 := \n  eapply (carefully_link_progs p1 p2 (eq_refl _));\n  [time \"merge_global\" do_merge_global_definitions_unfold p1 p2\n  |time \"merge_types\" do_merge_prog_types_unfold p1 p2\n  |time \"process_composites\" process_composite_definitions].\n\nLtac do_link_progs_step2 p := \nlet x := eval hnf in p in\nmatch x with\n {| prog_defs := ?d;\n    prog_public := ?p;\n    prog_main := ?m;\n    prog_types := ?t;\n    prog_comp_env := ?e;\n    prog_comp_env_eq := _ |} =>\nrefine  {| prog_defs := d;\n    prog_public := p;\n    prog_main := m;\n    prog_types := t;\n    prog_comp_env := e;\n    prog_comp_env_eq := _ |} \nend;\nabstract (exact (prog_comp_env_eq p)).\n\nEnd NEW_LINK_PROGS.\n(* Now, to use NEW_LINK_PROGS, it is unfortunately necessary to do this in two steps*)\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/floyd/linking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.23023063713646127}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nRequire Export Coq.Strings.String.\nRequire Import Coq.Classes.RelationClasses.\n\nFrom Fairness Require Export ITreeLib FairBeh Mod.\nFrom Fairness Require Import pind.\nFrom Fairness Require Import PCMLarge.\n\nSet Implicit Arguments.\n\n\n\nSection PRIMIVIESIM.\n  Context `{M: URA.t}.\n\n  Variable state_src: Type.\n  Variable state_tgt: Type.\n\n  Variable _ident_src: ID.\n  Definition ident_src := sum_tid _ident_src.\n  Variable _ident_tgt: ID.\n  Definition ident_tgt := sum_tid _ident_tgt.\n\n  Variable wf_src: WF.\n  Variable wf_tgt: WF.\n\n  Let srcE := programE _ident_src state_src.\n  Let tgtE := programE _ident_tgt state_tgt.\n\n  Definition shared :=\n    (TIdSet.t *\n       (@imap ident_src wf_src) *\n       (@imap ident_tgt wf_tgt) *\n       state_src *\n       state_tgt)%type.\n\n  Let shared_rel: Type := shared -> Prop.\n\n  Variable I: shared -> URA.car -> Prop.\n\n  Variant __lsim\n          (tid: thread_id)\n          (lsim: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          (_lsim: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel),bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n  | lsim_ret\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      r_src r_tgt\n      (LSIM: RR r_src r_tgt r_ctx (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (Ret r_src) (Ret r_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_tauL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (Tau itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_chooseL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X ktr_src itr_tgt\n      (LSIM: exists x, _lsim _ _ RR true f_tgt r_ctx (ktr_src x) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Choose X) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_rmwL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X rmw ktr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src (snd (rmw st_src) : X)) itr_tgt (ths, im_src, im_tgt, fst (rmw st_src), st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Rmw rmw) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_tidL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src tid) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (GetTid) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_UB\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Undefined) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_fairL\n      f_src f_tgt r_ctx\n      ths im_src0 im_tgt st_src st_tgt\n      f ktr_src itr_tgt\n      (LSIM: exists im_src1,\n          (<<FAIR: fair_update im_src0 im_src1 (prism_fmap inrp f)>>) /\\\n            (<<LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src tt) itr_tgt (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Fair f) >>= ktr_src) itr_tgt (ths, im_src0, im_tgt, st_src, st_tgt)\n\n  | lsim_tauR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: _lsim _ _ RR f_src true r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (Tau itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_chooseR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X itr_src ktr_tgt\n      (LSIM: forall x, _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt x) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (Choose X) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_rmwR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X rmw itr_src ktr_tgt\n      (LSIM: _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt (snd (rmw st_tgt) : X)) (ths, im_src, im_tgt, st_src, fst (rmw st_tgt)))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (Rmw rmw) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_tidR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src ktr_tgt\n      (LSIM: _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt tid) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (GetTid) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_fairR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt0 st_src st_tgt\n      f itr_src ktr_tgt\n      (LSIM: forall im_tgt1\n                   (FAIR: fair_update im_tgt0 im_tgt1 (prism_fmap inrp f)),\n          (<<LSIM: _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt tt) (ths, im_src, im_tgt1, st_src, st_tgt)>>))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (Fair f) >>= ktr_tgt) (ths, im_src, im_tgt0, st_src, st_tgt)\n\n  | lsim_observe\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src ktr_tgt\n      (LSIM: forall ret,\n          lsim _ _ RR true true r_ctx (ktr_src ret) (ktr_tgt ret) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Observe fn args) >>= ktr_src) (trigger (Observe fn args) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_call\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src itr_tgt\n    : __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Call fn args) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_yieldL\n      f_src f_tgt r_ctx\n      ths im_src0 im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (LSIM: exists im_src1,\n          (<<FAIR: fair_update im_src0 im_src1 (prism_fmap inlp (tids_fmap tid ths))>>) /\\\n            (<<LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src tt) (trigger (Yield) >>= itr_tgt) (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= itr_tgt) (ths, im_src0, im_tgt, st_src, st_tgt)\n  | lsim_yieldR\n      f_src f_tgt r_ctx0\n      ths0 im_src0 im_tgt0 st_src0 st_tgt0\n      r_own r_shared\n      ktr_src ktr_tgt\n      (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared)\n      (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx0))\n      (LSIM: forall ths1 im_src1 im_tgt1 st_src1 st_tgt1 r_shared1 r_ctx1\n                    (INV: I (ths1, im_src1, im_tgt1, st_src1, st_tgt1) r_shared1)\n                    (VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx1))\n                    im_tgt2\n                    (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths1))),\n          _lsim _ _ RR f_src true r_ctx1 (trigger (Yield) >>= ktr_src) (ktr_tgt tt) (ths1, im_src1, im_tgt2, st_src1, st_tgt1))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx0 (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n  | lsim_sync\n      f_src f_tgt r_ctx0\n      ths0 im_src0 im_tgt0 st_src0 st_tgt0\n      r_own r_shared\n      ktr_src ktr_tgt\n      (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared)\n      (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx0))\n      (LSIM: forall ths1 im_src1 im_tgt1 st_src1 st_tgt1 r_shared1 r_ctx1\n               (INV: I (ths1, im_src1, im_tgt1, st_src1, st_tgt1) r_shared1)\n               (VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx1))\n               im_tgt2\n               (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths1))),\n          (exists im_src2,\n              (<<FAIR: fair_update im_src1 im_src2 (prism_fmap inlp (tids_fmap tid ths1))>>) /\\\n                (<<LSIM: lsim _ _ RR true true r_ctx1 (ktr_src tt) (ktr_tgt tt) (ths1, im_src2, im_tgt2, st_src1, st_tgt1)>>)))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx0 (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n\n  | lsim_progress\n      r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: lsim _ _ RR false false r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR true true r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  .\n\n  Definition lsim (tid: thread_id)\n             R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel):\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n    paco9 (fun r => pind9 (__lsim tid r) top9) bot9 R_src R_tgt RR.\n\n  Lemma __lsim_mon tid:\n    forall r r' (LE: r <9= r'), (__lsim tid r) <10= (__lsim tid r').\n  Proof.\n    ii. inv PR; try (econs; eauto; fail).\n    eapply lsim_sync; eauto. i. hexploit LSIM. eapply INV0. eapply VALID0. all: eauto. i; des. esplits; eauto.\n  Qed.\n\n  Lemma _lsim_mon tid: forall r, monotone9 (__lsim tid r).\n  Proof.\n    ii. inv IN; try (econs; eauto; fail).\n    { des. econs; eauto. }\n    { des. econs; eauto. }\n    { econs. i. eapply LE. eapply LSIM. eauto. }\n    { des. econs; esplits; eauto. }\n  Qed.\n\n  Lemma lsim_mon tid: forall q, monotone9 (fun r => pind9 (__lsim tid r) q).\n  Proof.\n    ii. eapply pind9_mon_gen; eauto.\n    ii. eapply __lsim_mon; eauto.\n  Qed.\n\n  Variant lsim_resetC\n          (r: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n    | lsim_resetC_intro\n        src tgt shr r_ctx\n        ps0 pt0 ps1 pt1\n        (REL: r _ _ RR ps1 pt1 r_ctx src tgt shr)\n        (SRC: ps1 = true -> ps0 = true)\n        (TGT: pt1 = true -> pt0 = true)\n      :\n      lsim_resetC r RR ps0 pt0 r_ctx src tgt shr\n  .\n\n  Lemma lsim_resetC_spec tid\n    :\n    lsim_resetC <10= gupaco9 (fun r => pind9 (__lsim tid r) top9) (cpn9 (fun r => pind9 (__lsim tid r) top9)).\n  Proof.\n    eapply wrespect9_uclo; eauto with paco.\n    { eapply lsim_mon. }\n    econs.\n    { ii. inv IN. econs; eauto. }\n    i. inv PR. eapply GF in REL.\n    eapply pind9_acc in REL.\n    instantiate (1:= (fun R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel) ps1 pt1 r_ctx src tgt shr =>\n                        forall ps0 pt0,\n                          (ps1 = true -> ps0 = true) ->\n                          (pt1 = true -> pt0 = true) ->\n                          pind9 (__lsim tid (rclo9 lsim_resetC r)) top9 R0 R1 RR ps0 pt0 r_ctx src tgt shr)) in REL; eauto.\n    ss. i. eapply pind9_unfold in PR.\n    2:{ eapply _lsim_mon. }\n    rename PR into LSIM. inv LSIM.\n\n    { eapply pind9_fold. econs; eauto. }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind9_fold. eapply lsim_tauL. split; ss.\n      hexploit IH; eauto.\n    }\n\n    { des. eapply pind9_fold. eapply lsim_chooseL. esplits; eauto. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_rmwL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_tidL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_UB. }\n\n    { des. eapply pind9_fold. eapply lsim_fairL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind9_fold. eapply lsim_tauR. split; ss.\n      hexploit IH. eauto. all: eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_chooseR. i. split; ss. specialize (LSIM0 x).\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_rmwR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_tidR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_fairR. i. split; ss. specialize (LSIM0 _ FAIR).\n      des. destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_observe. i. eapply rclo9_base. auto. }\n\n    { eapply pind9_fold. eapply lsim_call. }\n\n    { des. eapply pind9_fold. eapply lsim_yieldL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_yieldR; eauto. i.\n      hexploit LSIM0; eauto. clear LSIM0. intros LSIM0.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. split; ss; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_sync; eauto. i.\n      hexploit LSIM0. eapply INV0. eapply VALID0. all: eauto. i; des. esplits; eauto.\n      eapply rclo9_base. auto.\n    }\n\n    { pclearbot. hexploit H; ss; i. hexploit H0; ss; i. clarify.\n      eapply pind9_fold. eapply lsim_progress. eapply rclo9_base. auto. }\n  Qed.\n\n  Lemma lsim_reset_prog\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        src tgt shr\n        ps0 pt0 ps1 pt1 r_ctx\n        (LSIM: lsim tid RR ps1 pt1 r_ctx src tgt shr)\n        (SRC: ps1 = true -> ps0 = true)\n        (TGT: pt1 = true -> pt0 = true)\n    :\n    lsim tid RR ps0 pt0 r_ctx src tgt shr.\n  Proof.\n    ginit.\n    { eapply lsim_mon. }\n    { eapply cpn9_wcompat. eapply lsim_mon. }\n    guclo lsim_resetC_spec.\n    { eapply lsim_mon. }\n    econs; eauto. gfinal.\n    { eapply lsim_mon. }\n    right. auto.\n  Qed.\n\n  Lemma lsim_set_prog\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        r_ctx src tgt shr\n        (LSIM: lsim tid RR true true r_ctx src tgt shr)\n    :\n    forall ps pt, lsim tid RR ps pt r_ctx src tgt shr.\n  Proof.\n    i. revert_until tid. pcofix CIH. i.\n    remember true as ps0 in LSIM at 1. remember true as pt0 in LSIM at 1.\n    move LSIM before CIH. revert_until LSIM. punfold LSIM.\n    2:{ eapply lsim_mon. }\n    eapply pind9_acc in LSIM.\n\n    { instantiate (1:= (fun R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel) ps0 pt0 r_ctx src tgt shr =>\n                          ps0 = true ->\n                          pt0 = true ->\n                          forall ps pt,\n                            paco9\n                              (fun r0 =>\n                                 pind9 (__lsim tid r0) top9) r R0 R1 RR ps pt r_ctx src tgt shr)) in LSIM; auto. }\n\n    ss. clear ps0 pt0 r_ctx src tgt shr LSIM.\n    intros rr DEC IH R0' R1' RR' gps gpt r_ctx src tgt shr LSIM. clear DEC.\n    intros Egps Egpt ps pt.\n    eapply pind9_unfold in LSIM.\n    2:{ eapply _lsim_mon. }\n    inv LSIM.\n\n    { pfold. eapply pind9_fold. econs; eauto. }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      pfold. eapply pind9_fold. eapply lsim_tauL. split; ss.\n      hexploit IH. eauto. all: eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { des. pfold. eapply pind9_fold. eapply lsim_chooseL. esplits; eauto. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_rmwL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_tidL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_UB. }\n\n    { des. pfold. eapply pind9_fold. eapply lsim_fairL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      pfold. eapply pind9_fold. eapply lsim_tauR. split; ss.\n      hexploit IH. eauto. all: eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_chooseR. i. split; ss. specialize (LSIM0 x).\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_rmwR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_tidR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_fairR. i. split; ss. specialize (LSIM0 _ FAIR).\n      des. destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_observe. i. eapply upaco9_mon_bot; eauto. }\n\n    { pfold. eapply pind9_fold. eapply lsim_call. }\n\n    { des. pfold. eapply pind9_fold. eapply lsim_yieldL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_yieldR; eauto. i.\n      hexploit LSIM0; eauto. clear LSIM0. intros LSIM0.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. split; ss. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_sync; eauto. i.\n      hexploit LSIM0. eapply INV0. eapply VALID0. all: eauto. i; des. esplits; eauto.\n      eapply upaco9_mon_bot; eauto.\n    }\n\n    { pclearbot. eapply paco9_mon_bot. eapply lsim_reset_prog. eauto. all: ss. }\n\n  Qed.\n\n  Variant lsim_rrC\n          (r: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n    | lsim_rrC_intro\n        (RR0: R_src -> R_tgt -> URA.car -> shared_rel)\n        src tgt shr r_ctx ps pt\n        (REL: r _ _ RR0 ps pt r_ctx src tgt shr)\n        (IMPL: forall r0 r1 r_ctx shr, (RR0 r0 r1 r_ctx shr) -> (RR r0 r1 r_ctx shr))\n      :\n      lsim_rrC r RR ps pt r_ctx src tgt shr\n  .\n\n  Lemma lsim_rrC_spec tid\n    :\n    lsim_rrC <10= gupaco9 (fun r => pind9 (__lsim tid r) top9) (cpn9 (fun r => pind9 (__lsim tid r) top9)).\n  Proof.\n    eapply wrespect9_uclo; eauto with paco.\n    { eapply lsim_mon. }\n    econs.\n    { ii. inv IN. econs; eauto. }\n    i. inv PR. eapply GF in REL.\n    rename REL into LSIM.\n    move LSIM before GF. revert_until LSIM.\n    pattern x0, x1, RR0, x3, x4, x5, x6, x7, x8.\n    revert x0 x1 RR0 x3 x4 x5 x6 x7 x8 LSIM. apply pind9_acc.\n    intros rr _ IH. intros R0 R1 RR0 ps pt r_ctx src tgt shr LSIM.\n    intros RR1. i.\n    eapply pind9_unfold in LSIM.\n    2:{ eapply _lsim_mon. }\n    inv LSIM.\n\n    { eapply pind9_fold. econs; eauto. }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind9_fold. eapply lsim_tauL. split; ss.\n      hexploit IH; eauto.\n    }\n\n    { des. eapply pind9_fold. eapply lsim_chooseL. esplits; eauto. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_rmwL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_tidL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_UB. }\n\n    { des. eapply pind9_fold. eapply lsim_fairL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind9_fold. eapply lsim_tauR. split; ss.\n      hexploit IH. eauto. all: eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_chooseR. i. split; ss. specialize (LSIM0 x).\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_rmwR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_tidR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_fairR. i. split; ss. specialize (LSIM0 _ FAIR).\n      des. destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_observe. i.\n      eapply rclo9_clo. econs; eauto. eapply rclo9_base; auto. }\n\n    { eapply pind9_fold. eapply lsim_call. }\n\n    { des. eapply pind9_fold. eapply lsim_yieldL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_yieldR; eauto. i.\n      hexploit LSIM0; eauto. clear LSIM0. intros LSIM0.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. split; ss; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_sync; eauto. i.\n      hexploit LSIM0. eapply INV0. eapply VALID0. all: eauto. i; des. esplits; eauto.\n      eapply rclo9_clo. econs; eauto. eapply rclo9_base; auto.\n    }\n\n    { eapply pind9_fold. eapply lsim_progress.\n      eapply rclo9_clo. econs; eauto. eapply rclo9_base; eauto.\n    }\n\n  Qed.\n\n  Definition local_RR {R0 R1} (RR: R0 -> R1 -> Prop) tid:\n    R0 -> R1 -> URA.car -> shared_rel :=\n    fun (r_src: R0) (r_tgt: R1) (r_ctx: URA.car) '(ths2, im_src1, im_tgt1, st_src1, st_tgt1) =>\n      (exists ths3 r_own r_shared,\n          (<<THS: NatMap.remove tid ths2 = ths3>>) /\\\n            (<<VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx)>>) /\\\n            (<<INV: I (ths3, im_src1, im_tgt1, st_src1, st_tgt1) r_shared>>) /\\\n            (<<RET: RR r_src r_tgt>>)).\n\n  Definition local_sim {R0 R1} (RR: R0 -> R1 -> Prop) src tgt :=\n    forall ths0 im_src0 im_tgt0 st_src0 st_tgt0 r_shared0 r_ctx0\n           (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared0)\n           tid ths1\n           (THS: TIdSet.add_new tid ths0 ths1)\n           (VALID: URA.wf (r_shared0 ⋅ r_ctx0)),\n    forall im_tgt0'\n      (UPD: fair_update im_tgt0 im_tgt0' (prism_fmap inlp (fun t => if (tid_dec t tid) then Flag.success else Flag.emp))),\n    exists r_shared1 r_own im_src0',\n      (<<INV: I (ths1, im_src0', im_tgt0', st_src0, st_tgt0) r_shared1>>) /\\\n        (<<VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx0)>>) /\\\n        (forall ths im_src1 im_tgt1 st_src st_tgt r_shared2 r_ctx2\n                (INV: I (ths, im_src1, im_tgt1, st_src, st_tgt) r_shared2)\n                (VALID: URA.wf (r_shared2 ⋅ r_own ⋅ r_ctx2)),\n          forall im_tgt2 (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths))),\n          exists im_src2,\n            (<<SRC: fair_update im_src1 im_src2 (prism_fmap inlp (tids_fmap tid ths))>>) /\\\n              (<<LSIM: forall fs ft,\n                  lsim\n                    tid\n                    (@local_RR R0 R1 RR tid)\n                    fs ft\n                    r_ctx2\n                    src tgt\n                    (ths, im_src2, im_tgt2, st_src, st_tgt)\n                    >>)).\n\n  Definition local_sim_init {R0 R1} (RR: R0 -> R1 -> Prop) (r_own: URA.car) tid src tgt :=\n    forall ths im_src im_tgt st_src st_tgt r_shared r_ctx\n      (INV: I (ths, im_src, im_tgt, st_src, st_tgt) r_shared)\n      (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx)),\n    forall im_tgt1 (FAIR: fair_update im_tgt im_tgt1 (prism_fmap inlp (tids_fmap tid ths))),\n    exists im_src1,\n      (<<SRC: fair_update im_src im_src1 (prism_fmap inlp (tids_fmap tid ths))>>) /\\\n        forall fs ft,\n          lsim\n            tid\n            (@local_RR R0 R1 RR tid)\n            fs ft\n            r_ctx\n            src tgt\n            (ths, im_src1, im_tgt1, st_src, st_tgt).\n\nEnd PRIMIVIESIM.\n#[export] Hint Constructors __lsim: core.\n#[export] Hint Unfold lsim: core.\n#[export] Hint Resolve __lsim_mon: paco.\n#[export] Hint Resolve _lsim_mon: paco.\n#[export] Hint Resolve lsim_mon: paco.\n\n\n\nModule ModSim.\n  Section MODSIM.\n\n    Variable md_src: Mod.t.\n    Variable md_tgt: Mod.t.\n\n    Record mod_sim: Prop :=\n      mk {\n          wf_src : WF;\n          wf_tgt : WF;\n          wf_tgt_inhabited: inhabited wf_tgt.(T);\n          wf_tgt_open: forall (o0: wf_tgt.(T)), exists o1, wf_tgt.(lt) o0 o1;\n\n          world: URA.t;\n\n          (* I: (@shared md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt) -> world -> Prop; *)\n          init: forall im_tgt,\n          exists (I: (@shared md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt) -> world -> Prop),\n          (exists im_src r_shared,\n            (I (NatSet.empty, im_src, im_tgt, md_src.(Mod.st_init), md_tgt.(Mod.st_init)) r_shared) /\\\n              (URA.wf r_shared)) /\\\n          (forall fn args, match md_src.(Mod.funs) fn, md_tgt.(Mod.funs) fn with\n                           | Some ktr_src, Some ktr_tgt => local_sim I (@eq Any.t) (ktr_src args) (ktr_tgt args)\n                           | None        , None         => True\n                           | _           , _            => False\n                           end);\n        }.\n  End MODSIM.\nEnd ModSim.\n\n\nFrom Fairness Require Import Concurrency.\n\nModule UserSim.\n  Section MODSIM.\n\n    Variable md_src: Mod.t.\n    Variable md_tgt: Mod.t.\n\n    Record sim (p_src: Th.t _) (p_tgt: Th.t _) : Prop :=\n      mk {\n          wf_src : WF;\n          wf_tgt : WF;\n          wf_tgt_inhabited: inhabited wf_tgt.(T);\n          wf_tgt_open: forall (o0: wf_tgt.(T)), exists o1, wf_tgt.(lt) o0 o1;\n\n          world: URA.t;\n\n          (* I: (@shared md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt) -> world -> Prop; *)\n          funs: forall im_tgt,\n          exists (I: (@shared md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt) -> world -> Prop),\n          exists im_src rs r_shared,\n            (<<INIT: I (key_set p_src, im_src, im_tgt, md_src.(Mod.st_init), md_tgt.(Mod.st_init)) r_shared>>) /\\\n              (<<SIM: Forall3\n                        (fun '(t1, src) '(t2, tgt) '(t3, r) =>\n                           t1 = t2 /\\ t1 = t3 /\\\n                           @local_sim_init _ md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt I _ _ (@eq Any.t) r t1 src tgt)\n                        (Th.elements p_src) (Th.elements p_tgt) (NatMap.elements rs)>>) /\\\n              (<<WF: URA.wf (r_shared ⋅ NatMap.fold (fun _ r s => r ⋅ s) rs ε)>>)\n        }.\n  End MODSIM.\nEnd UserSim.\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/src/simulation/ModSimStid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.38121957328625583, "lm_q1q2_score": 0.23023063594699583}}
{"text": "From iris.algebra Require Import\n  proofmode_classes.\n\nFrom caml5 Require Import\n  prelude.\nFrom caml5.algebra Require Export\n  base.\nFrom caml5.algebra Require Import\n  Z_min\n  lib.auth_option.\n\nImplicit Types n m p : Z.\n\nDefinition auth_Z_min :=\n  auth_option Z_min_R.\nDefinition auth_Z_min_R :=\n  auth_option_R Z_min_R.\nDefinition auth_Z_min_UR :=\n  auth_option_UR Z_min_R.\n\nDefinition auth_Z_min_auth dq n : auth_Z_min_UR :=\n  ●O{dq} Build_Z_min n ⋅ ◯O Build_Z_min n.\nDefinition auth_Z_min_frag n : auth_Z_min_UR :=\n  ◯O Build_Z_min n.\n\n#[global] Instance auth_Z_min_cmra_discrete :\n  CmraDiscrete auth_Z_min_R.\nProof.\n  apply _.\nQed.\n\n#[global] Instance auth_Z_min_auth_core_id n :\n  CoreId (auth_Z_min_auth DfracDiscarded n).\nProof.\n  apply _.\nQed.\n#[global] Instance auth_Z_min_frag_core_id n :\n  CoreId (auth_Z_min_frag n).\nProof.\n  apply _.\nQed.\n\nLemma auth_Z_min_auth_dfrac_op dq1 dq2 n :\n  auth_Z_min_auth (dq1 ⋅ dq2) n ≡ auth_Z_min_auth dq1 n ⋅ auth_Z_min_auth dq2 n.\nProof.\n  rewrite /auth_Z_min_auth auth_option_auth_dfrac_op.\n  rewrite (comm _ (●O{dq2} _)) -!assoc (assoc _ (◯O _)) -core_id_dup (comm _ (◯O _)) //.\nQed.\n#[global] Instance auth_Z_min_auth_dfrac_is_op dq dq1 dq2 n :\n  IsOp dq dq1 dq2 →\n  IsOp' (auth_Z_min_auth dq n) (auth_Z_min_auth dq1 n) (auth_Z_min_auth dq2 n).\nProof.\n  rewrite /IsOp' /IsOp => ->. rewrite auth_Z_min_auth_dfrac_op //.\nQed.\n\nLemma auth_Z_min_frag_op n1 n2 :\n  auth_Z_min_frag (n1 `min` n2) = auth_Z_min_frag n1 ⋅ auth_Z_min_frag n2.\nProof.\n  rewrite -auth_option_frag_op Z_min_op_eq //.\nQed.\n#[global] Instance auth_Z_min_frag_is_op n n1 n2 :\n  IsOp (Build_Z_min n) (Build_Z_min n1) (Build_Z_min n2) →\n  IsOp' (auth_Z_min_frag n) (auth_Z_min_frag n1) (auth_Z_min_frag n2).\nProof.\n  rewrite /IsOp' /IsOp /auth_Z_min_frag => -> //.\nQed.\n\nLemma auth_Z_min_auth_frag_op dq n :\n  auth_Z_min_auth dq n ≡ auth_Z_min_auth dq n ⋅ auth_Z_min_frag n.\nProof.\n  rewrite -!assoc -auth_option_frag_op -core_id_dup //.\nQed.\n\nLemma auth_Z_min_frag_op_le n n' :\n  (n ≤ n')%Z →\n  auth_Z_min_frag n = auth_Z_min_frag n' ⋅ auth_Z_min_frag n.\nProof.\n  intros. rewrite -auth_Z_min_frag_op Z.min_r //.\nQed.\n\nLemma auth_Z_min_auth_dfrac_valid dq n :\n  ✓ auth_Z_min_auth dq n ↔\n  ✓ dq.\nProof.\n  rewrite auth_option_both_dfrac_valid_discrete /=. naive_solver.\nQed.\nLemma auth_Z_min_auth_valid n :\n  ✓ auth_Z_min_auth (DfracOwn 1) n.\nProof.\n  rewrite auth_Z_min_auth_dfrac_valid //.\nQed.\n\nLemma auth_Z_min_auth_dfrac_op_valid dq1 n1 dq2 n2 :\n  ✓ (auth_Z_min_auth dq1 n1 ⋅ auth_Z_min_auth dq2 n2) ↔\n  ✓ (dq1 ⋅ dq2) ∧ n1 = n2.\nProof.\n  rewrite /auth_Z_min_auth (comm _ (●O{dq2} _)) -!assoc (assoc _ (◯O _)).\n  rewrite -auth_option_frag_op (comm _ (◯O _)) assoc. split.\n  - move => /cmra_valid_op_l /auth_option_auth_dfrac_op_valid. naive_solver.\n  - intros [? ->]. rewrite -core_id_dup -auth_option_auth_dfrac_op.\n    apply auth_option_both_dfrac_valid_discrete. naive_solver.\nQed.\nLemma auth_Z_min_auth_op_valid n1 n2 :\n  ✓ (auth_Z_min_auth (DfracOwn 1) n1 ⋅ auth_Z_min_auth (DfracOwn 1) n2) ↔\n  False.\nProof.\n  rewrite auth_Z_min_auth_dfrac_op_valid. naive_solver.\nQed.\n\nLemma auth_Z_min_both_dfrac_valid dq n m :\n  ✓ (auth_Z_min_auth dq n ⋅ auth_Z_min_frag m) ↔\n  ✓ dq ∧ (n ≤ m)%Z.\nProof.\n  rewrite -assoc -auth_option_frag_op auth_option_both_dfrac_valid_discrete.\n  rewrite Z_min_included Z_min_op_eq /=. naive_solver lia.\nQed.\nLemma auth_Z_min_both_valid n m :\n  ✓ (auth_Z_min_auth (DfracOwn 1) n ⋅ auth_Z_min_frag m) ↔\n  (n ≤ m)%Z.\nProof.\n  rewrite auth_Z_min_both_dfrac_valid dfrac_valid_own. naive_solver.\nQed.\n\nLemma auth_Z_min_frag_mono n1 n2 :\n  (n2 ≤ n1)%Z →\n  auth_Z_min_frag n1 ≼ auth_Z_min_frag n2.\nProof.\n  intros. apply auth_option_frag_mono, Z_min_included. done.\nQed.\n\nLemma auth_Z_min_included dq n :\n  auth_Z_min_frag n ≼ auth_Z_min_auth dq n.\nProof.\n  apply cmra_included_r.\nQed.\n\nLemma auth_Z_min_auth_persist dq n :\n  auth_Z_min_auth dq n ~~> auth_Z_min_auth DfracDiscarded n.\nProof.\n  eapply cmra_update_op_proper; last done.\n  eapply auth_option_auth_persist.\nQed.\nLemma auth_Z_min_auth_update {n} n' :\n  (n' ≤ n)%Z →\n  auth_Z_min_auth (DfracOwn 1) n ~~> auth_Z_min_auth (DfracOwn 1) n'.\nProof.\n  intros. apply auth_option_both_update, Z_min_local_update. done.\nQed.\n\n#[global] Opaque auth_Z_min_auth.\n#[global] Opaque auth_Z_min_frag.\n", "meta": {"author": "clef-men", "repo": "caml5", "sha": "0de06d5792138eb17877ed1536a0401b7a322ee2", "save_path": "github-repos/coq/clef-men-caml5", "path": "github-repos/coq/clef-men-caml5/caml5-0de06d5792138eb17877ed1536a0401b7a322ee2/theories/algebra/lib/auth_Z_min.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318194686359, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.23023062626612084}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.logical_compare.\nInstance CompSpecs : compspecs.\nProof. make_compspecs prog. Defined.\n\n(****  START *)\n\nDefinition logical_and_result v1 v2 : int :=\n   if Int.eq v1 Int.zero then Int.zero else v2.\n\nDefinition logical_or_result v1 v2 : int :=\n  if Int.eq v1 Int.zero then v2 else Int.one.\n\nFixpoint quick_shortcut_logical (s: statement) : option ident :=\nmatch s with\n| Sifthenelse _\n     (Sset id (Econst_int _ (Tint I32 Signed {| attr_volatile := false; attr_alignas := None |})))\n     s2 => match quick_shortcut_logical s2 with None => None | Some id2 =>\n                 if ident_eq id id2 then Some id else None\n                end\n| Sifthenelse e1 s2\n     (Sset id (Econst_int _ (Tint I32 Signed {| attr_volatile := false; attr_alignas := None |})))\n      => match quick_shortcut_logical s2 with None => None | Some id2 =>\n                 if ident_eq id id2 then Some id else None\n            end\n| Sset id (Ecast _ (Tint IBool Unsigned {| attr_volatile := false; attr_alignas := None |})) =>\n        Some id\n| _ => None\nend.\n\nFixpoint shortcut_logical (eval: expr -> option val) (tid: ident) (s: statement)\n            : option (int * list expr) :=\nmatch s with\n| Sifthenelse e1\n     (Sset id (Econst_int one (Tint I32 Signed {| attr_volatile := false; attr_alignas := None |})))\n     s2 => if andb (eqb_ident id tid) (Int.eq one Int.one)\n                then match eval e1 with\n                        | Some (Vint v1) =>\n                           match shortcut_logical eval tid s2 with\n                           | Some (v2, el) => Some (logical_or_result v1 v2, e1 :: el)\n                           | _ => None\n                           end\n                        | _ => None\n                        end\n                else None\n| Sifthenelse e1 s2\n     (Sset id (Econst_int zero (Tint I32 Signed {| attr_volatile := false; attr_alignas := None |})))\n      => if andb (eqb_ident id tid) (Int.eq zero Int.zero)\n            then match eval e1 with\n                     | Some (Vint v1) =>\n                      match shortcut_logical eval tid s2 with\n                      | Some (v2, el) => Some (logical_and_result v1 v2, e1 :: el)\n                      | _ => None\n                      end\n                   | _ => None\n                end\n            else None\n| Sset id (Ecast e (Tint IBool Unsigned {| attr_volatile := false; attr_alignas := None |})) =>\n        if eqb_ident id tid\n        then match eval (Ecast e tbool) with\n                 | Some (Vint v) => Some (v, (Ecast e tbool :: nil))\n                 | _ => None\n                end\n        else None\n| _ => None\nend.\n\nLemma semax_shortcut_logical:\n  forall Espec {cs: compspecs} Delta P Q R tid s v Qtemp Qvar GV el,\n   quick_shortcut_logical s = Some tid ->\n   typeof_temp Delta tid = Some tint ->\n   local2ptree Q = (Qtemp, Qvar, nil, GV) ->\n   Qtemp ! tid = None ->\n   shortcut_logical (msubst_eval_expr Delta Qtemp Qvar GV) tid s = Some (v, el) ->\n   ENTAIL Delta, PROPx P (LOCALx Q (SEPx R)) |-- fold_right (fun e q => tc_expr Delta e && q) TT el ->\n   @semax cs Espec Delta (PROPx P (LOCALx Q (SEPx R)))\n          s (normal_ret_assert (PROPx P (LOCALx (temp tid (Vint v) :: Q) (SEPx R)))).\nAdmitted.\n\n(***** END *)\n\nDefinition do_or_spec :=\n DECLARE _do_or\n  WITH a: int, b : int\n  PRE [ _a OF tbool, _b OF tbool ]\n        PROP () LOCAL (temp _a (Vint a); temp _b (Vint b)) SEP ()\n  POST [ tbool ]\n        PROP() LOCAL (temp ret_temp (Vint (logical_or_result a b)))\n        SEP().\n\n\nDefinition do_and_spec :=\n DECLARE _do_and\n  WITH a: int, b : int\n  PRE [ _a OF tbool, _b OF tbool ]\n        PROP () LOCAL (temp _a (Vint a); temp _b (Vint b)) SEP ()\n  POST [ tbool ]\n        PROP() LOCAL (temp ret_temp (Vint (logical_and_result a b)))\n        SEP().\n\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv: globals\n  PRE  [] main_pre prog nil gv\n  POST [ tint ] main_post prog nil gv.\n\nDefinition Vprog : varspecs := nil.\n\nDefinition Gprog : funspecs :=\n      ltac:(with_library prog [do_or_spec; do_and_spec; main_spec]).\n\nLtac do_semax_shortcut_logical :=\n eapply semax_shortcut_logical;\n   [ reflexivity | reflexivity | prove_local2ptree\n   | reflexivity | reflexivity\n   | unfold fold_right; entailer  ].\n\nLemma body_do_or: semax_body Vprog Gprog f_do_or do_or_spec.\nProof.\nstart_function.\n\neapply semax_seq'; [do_semax_shortcut_logical | abbreviate_semax].\nforward.\ndestruct H,H0; subst; simpl; entailer!.\nQed.\n\nLemma body_do_and: semax_body Vprog Gprog f_do_and do_and_spec.\nProof.\nstart_function.\neapply semax_seq'; [do_semax_shortcut_logical | abbreviate_semax].\nforward.\ndestruct H,H0; subst; simpl; entailer!.\nQed.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nforward.\nQed.\n\nExisting Instance NullExtension.Espec.\n\nLemma prog_correct:\n  semax_prog prog Vprog Gprog.\nProof.\nprove_semax_prog.\nsemax_func_cons body_do_or.\nsemax_func_cons body_do_and.\nsemax_func_cons body_main.\nQed.\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/progs/verif_logical_compare.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23017174404733068}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness proof for IA32 generation: auxiliary results. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Errors.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Op.\nRequire Import Locations.\nRequire Import Mach.\nRequire Import Machsem.\nRequire Import Machtyping.\nRequire Import Asm.\nRequire Import Asmgen.\nRequire Import Conventions.\n\nOpen Local Scope error_monad_scope.\n\n(** * Correspondence between Mach registers and IA32 registers *)\n\nHint Extern 2 (_ <> _) => congruence: ppcgen.\n\nLemma preg_of_injective:\n  forall r1 r2, preg_of r1 = preg_of r2 -> r1 = r2.\nProof.\n  destruct r1; destruct r2; simpl; intros; reflexivity || discriminate.\nQed.\n\nLemma preg_of_not_ESP:\n  forall r, preg_of r <> ESP.\nProof.\n  destruct r; simpl; congruence.\nQed.\n\nLemma preg_of_not_PC:\n  forall r, preg_of r <> PC.\nProof.\n  destruct r; simpl; congruence.\nQed.\n\nHint Resolve preg_of_not_ESP preg_of_not_PC: ppcgen.\n\nLemma ireg_of_eq:\n  forall r r', ireg_of r = OK r' -> preg_of r = IR r'.\nProof.\n  unfold ireg_of; intros. destruct (preg_of r); inv H; auto.\nQed.\n\nLemma freg_of_eq:\n  forall r r', freg_of r = OK r' -> preg_of r = FR r'.\nProof.\n  unfold freg_of; intros. destruct (preg_of r); inv H; auto.\nQed.\n\n(** Agreement between Mach register sets and IA32 register sets. *)\n\nRecord agree (ms: Mach.regset) (sp: val) (rs: Asm.regset) : Prop := mkagree {\n  agree_sp: rs#ESP = sp;\n  agree_sp_def: sp <> Vundef;\n  agree_mregs: forall r: mreg, Val.lessdef (ms r) (rs#(preg_of r))\n}.\n\nLemma preg_val:\n  forall ms sp rs r,\n  agree ms sp rs -> Val.lessdef (ms r) rs#(preg_of r).\nProof.\n  intros. destruct H. auto.\nQed.\n\nLemma preg_vals:\n  forall ms sp rs, agree ms sp rs ->\n  forall l, Val.lessdef_list (map ms l) (map rs (map preg_of l)).\nProof.\n  induction l; simpl. constructor. constructor. eapply preg_val; eauto. auto.\nQed.\n\nLemma ireg_val:\n  forall ms sp rs r r',\n  agree ms sp rs ->\n  ireg_of r = OK r' ->\n  Val.lessdef (ms r) rs#r'.\nProof.\n  intros. rewrite <- (ireg_of_eq _ _ H0). eapply preg_val; eauto.\nQed.\n\nLemma freg_val:\n  forall ms sp rs r r',\n  agree ms sp rs ->\n  freg_of r = OK r' ->\n  Val.lessdef (ms r) (rs#r').\nProof.\n  intros. rewrite <- (freg_of_eq _ _ H0). eapply preg_val; eauto.\nQed.\n\nLemma sp_val:\n  forall ms sp rs,\n  agree ms sp rs ->\n  sp = rs#ESP.\nProof.\n  intros. destruct H; auto.\nQed.\n\nHint Resolve preg_val ireg_val freg_val sp_val: ppcgen.\n\nDefinition important_preg (r: preg) : bool :=\n  match r with\n  | PC => false\n  | IR _ => true\n  | FR _ => true\n  | ST0 => true\n  | CR _ => false\n  | RA => false\n  end.\n\nLemma preg_of_important:\n  forall r, important_preg (preg_of r) = true.\nProof.\n  intros. destruct r; reflexivity.\nQed.\n\nLemma important_diff:\n  forall r r',\n  important_preg r = true -> important_preg r' = false -> r <> r'.\nProof.\n  congruence.\nQed.\nHint Resolve important_diff: ppcgen.\n\nLemma agree_exten:\n  forall ms sp rs rs',\n  agree ms sp rs ->\n  (forall r, important_preg r = true -> rs'#r = rs#r) ->\n  agree ms sp rs'.\nProof.\n  intros. destruct H. split. \n  rewrite H0; auto. auto.\n  intros. rewrite H0; auto. apply preg_of_important.\nQed.\n\n(** Preservation of register agreement under various assignments. *)\n\nLemma agree_set_mreg:\n  forall ms sp rs r v rs',\n  agree ms sp rs ->\n  Val.lessdef v (rs'#(preg_of r)) ->\n  (forall r', important_preg r' = true -> r' <> preg_of r -> rs'#r' = rs#r') ->\n  agree (Regmap.set r v ms) sp rs'.\nProof.\n  intros. destruct H. split.\n  rewrite H1; auto. apply sym_not_equal. apply preg_of_not_ESP.\n  auto.\n  intros. unfold Regmap.set. destruct (RegEq.eq r0 r). congruence. \n  rewrite H1. auto. apply preg_of_important.\n  red; intros; elim n. eapply preg_of_injective; eauto.\nQed.\n\nLemma agree_set_other:\n  forall ms sp rs r v,\n  agree ms sp rs ->\n  important_preg r = false ->\n  agree ms sp (rs#r <- v).\nProof.\n  intros. apply agree_exten with rs. auto.\n  intros. apply Pregmap.gso. congruence.\nQed.\n\nLemma agree_nextinstr:\n  forall ms sp rs,\n  agree ms sp rs -> agree ms sp (nextinstr rs).\nProof.\n  intros. unfold nextinstr. apply agree_set_other. auto. auto.\nQed.\n\nLemma agree_undef_unimportant_regs:\n  forall ms sp rl rs,\n  agree ms sp rs ->\n  (forall r, In r rl -> important_preg r = false) ->\n  agree ms sp (undef_regs rl rs).\nProof.\n  induction rl; simpl; intros. auto.\n  apply IHrl. apply agree_exten with rs; auto.\n  intros. apply Pregmap.gso. red; intros; subst.\n  assert (important_preg a = false) by auto. congruence.\n  intros. apply H0; auto.\nQed.\n\nLemma agree_nextinstr_nf:\n  forall ms sp rs,\n  agree ms sp rs -> agree ms sp (nextinstr_nf rs).\nProof.\n  intros. unfold nextinstr_nf. apply agree_nextinstr. \n  apply agree_undef_unimportant_regs. auto.\n  intro. simpl. ElimOrEq; auto.\nQed.\n\nDefinition nontemp_preg (r: preg) : bool :=\n  match r with\n  | PC => false\n  | IR ECX => false\n  | IR EDX => false\n  | IR _ => true\n  | FR XMM6 => false\n  | FR XMM7 => false\n  | FR _ => true\n  | ST0 => false\n  | CR _ => false\n  | RA => false\n  end.\n\nLemma nontemp_diff:\n  forall r r',\n  nontemp_preg r = true -> nontemp_preg r' = false -> r <> r'.\nProof.\n  congruence.\nQed.\n\nHint Resolve nontemp_diff: ppcgen.\n\nLemma agree_exten_temps:\n  forall ms sp rs rs',\n  agree ms sp rs ->\n  (forall r, nontemp_preg r = true -> rs'#r = rs#r) ->\n  agree (undef_temps ms) sp rs'.\nProof.\n  intros. destruct H. split. \n  rewrite H0; auto. auto. \n  intros. unfold undef_temps. \n  destruct (In_dec mreg_eq r temporary_regs).\n  rewrite Mach.undef_regs_same; auto. \n  rewrite Mach.undef_regs_other; auto. rewrite H0; auto.\n  simpl in n. destruct r; auto; intuition.\nQed.\n\nLemma agree_undef_move:\n  forall ms sp rs rs',\n  agree ms sp rs ->\n  (forall r, important_preg r = true -> r <> ST0 -> rs'#r = rs#r) ->\n  agree (undef_move ms) sp rs'.\nProof.\n  intros. destruct H. split. \n  rewrite H0; auto. congruence. auto. \n  intros. unfold undef_move. \n  destruct (In_dec mreg_eq r destroyed_at_move_regs).\n  rewrite Mach.undef_regs_same; auto. \n  rewrite Mach.undef_regs_other; auto.\n  assert (important_preg (preg_of r) = true /\\ preg_of r <> ST0).\n    simpl in n. destruct r; simpl; auto; intuition congruence.\n  destruct H. rewrite H0; auto.\nQed.\n\nLemma agree_set_undef_mreg:\n  forall ms sp rs r v rs',\n  agree ms sp rs ->\n  Val.lessdef v (rs'#(preg_of r)) ->\n  (forall r', nontemp_preg r' = true -> r' <> preg_of r -> rs'#r' = rs#r') ->\n  agree (Regmap.set r v (undef_temps ms)) sp rs'.\nProof.\n  intros. apply agree_set_mreg with (rs'#(preg_of r) <- (rs#(preg_of r))); auto.\n  eapply agree_exten_temps; eauto. \n  intros. unfold Pregmap.set. destruct (PregEq.eq r0 (preg_of r)). \n  congruence. auto. \n  intros. rewrite Pregmap.gso; auto. \nQed.\n\nLemma agree_set_undef_move_mreg:\n  forall ms sp rs r v rs',\n  agree ms sp rs ->\n  Val.lessdef v (rs'#(preg_of r)) ->\n  (forall r', important_preg r' = true /\\ r' <> ST0 -> r' <> preg_of r -> rs'#r' = rs#r') ->\n  agree (Regmap.set r v (undef_move ms)) sp rs'.\nProof.\n  intros. apply agree_set_mreg with (rs'#(preg_of r) <- (rs#(preg_of r))); auto.\n  eapply agree_undef_move; eauto. \n  intros. unfold Pregmap.set. destruct (PregEq.eq r0 (preg_of r)). \n  congruence. auto. \n  intros. rewrite Pregmap.gso; auto. \nQed.\n\n(** Useful properties of the PC register. *)\n\nLemma nextinstr_inv:\n  forall r rs,\n  r <> PC ->\n  (nextinstr rs)#r = rs#r.\nProof.\n  intros. unfold nextinstr. apply Pregmap.gso. red; intro; subst. auto.\nQed.\n\nLemma nextinstr_inv2:\n  forall r rs,\n  nontemp_preg r = true ->\n  (nextinstr rs)#r = rs#r.\nProof.\n  intros. apply nextinstr_inv. red; intro; subst; discriminate.\nQed.\n\nLemma nextinstr_set_preg:\n  forall rs m v,\n  (nextinstr (rs#(preg_of m) <- v))#PC = Val.add rs#PC Vone.\nProof.\n  intros. unfold nextinstr. rewrite Pregmap.gss. \n  rewrite Pregmap.gso. auto. apply sym_not_eq. apply preg_of_not_PC. \nQed.\n\nLemma nextinstr_nf_inv:\n  forall r rs, \n  match r with PC => False | CR _ => False | _ => True end ->\n  (nextinstr_nf rs)#r = rs#r.\nProof.\n  intros. unfold nextinstr_nf. rewrite nextinstr_inv. \n  simpl. repeat rewrite Pregmap.gso; auto.\n  red; intro; subst; contradiction.\n  red; intro; subst; contradiction.\n  red; intro; subst; contradiction.\n  red; intro; subst; contradiction.\n  red; intro; subst; contradiction.\nQed.\n\nLemma nextinstr_nf_inv1:\n  forall r rs,\n  important_preg r = true -> (nextinstr_nf rs)#r = rs#r.\nProof.\n  intros. apply nextinstr_nf_inv. unfold important_preg in H. \n  destruct r; auto; congruence.\nQed.\n\nLemma nextinstr_nf_inv2:\n  forall r rs, \n  nontemp_preg r = true -> (nextinstr_nf rs)#r = rs#r.\nProof.\n  intros. apply nextinstr_nf_inv. unfold nontemp_preg in H. \n  destruct r; auto; congruence.\nQed.\n\nLemma nextinstr_nf_set_preg:\n  forall rs m v,\n  (nextinstr_nf (rs#(preg_of m) <- v))#PC = Val.add rs#PC Vone.\nProof.\n  intros. unfold nextinstr_nf.\n  transitivity (nextinstr (rs#(preg_of m) <- v) PC). auto.\n  apply nextinstr_set_preg.\nQed.\n\n(** Connection between Mach and Asm calling conventions for external\n    functions. *)\n\nLemma extcall_arg_match:\n  forall ms sp rs m m' l v,\n  agree ms sp rs ->\n  Machsem.extcall_arg ms m sp l v ->\n  Mem.extends m m' ->\n  exists v', Asm.extcall_arg rs m' l v' /\\ Val.lessdef v v'.\nProof.\n  intros. inv H0.\n  exists (rs#(preg_of r)); split. constructor. eauto with ppcgen.\n  unfold load_stack in H2. \n  exploit Mem.loadv_extends; eauto. intros [v' [A B]].\n  rewrite (sp_val _ _ _ H) in A. \n  exists v'; split; auto. destruct ty; econstructor; eauto.\nQed.\n\nLemma extcall_args_match:\n  forall ms sp rs m m', agree ms sp rs -> Mem.extends m m' ->\n  forall ll vl,\n  list_forall2 (Machsem.extcall_arg ms m sp) ll vl ->\n  exists vl', list_forall2 (Asm.extcall_arg rs m') ll vl' /\\ Val.lessdef_list vl vl'.\nProof.\n  induction 3.\n  exists (@nil val); split; constructor.\n  exploit extcall_arg_match; eauto. intros [v1' [A B]].\n  destruct IHlist_forall2 as [vl' [C D]].\n  exists(v1' :: vl'); split. constructor; auto. constructor; auto.\nQed.\n\nLemma extcall_arguments_match:\n  forall ms m sp rs sg args m',\n  agree ms sp rs ->\n  Machsem.extcall_arguments ms m sp sg args ->\n  Mem.extends m m' ->\n  exists args', Asm.extcall_arguments rs m' sg args' /\\ Val.lessdef_list args args'.\nProof.\n  unfold Machsem.extcall_arguments, Asm.extcall_arguments; intros.\n  eapply extcall_args_match; eauto.\nQed.\n\n(** Translation of arguments to annotations. *)\n\nLemma annot_arg_match:\n  forall ms sp rs m m' p v,\n  agree ms sp rs ->\n  Mem.extends m m' ->\n  Machsem.annot_arg ms m sp p v ->\n  exists v', Asm.annot_arg rs m' (transl_annot_param p) v' /\\ Val.lessdef v v'.\nProof.\n  intros. inv H1; simpl.\n(* reg *)\n  exists (rs (preg_of r)); split. \n  unfold preg_of. destruct (mreg_type r); constructor. \n  eapply preg_val; eauto.\n(* stack *)\n  exploit Mem.load_extends; eauto. intros [v' [A B]].\n  exists v'; split; auto. \n  inv H. econstructor; eauto. \nQed.\n\nLemma annot_arguments_match:\n  forall ms sp rs m m', agree ms sp rs -> Mem.extends m m' ->\n  forall pl vl,\n  Machsem.annot_arguments ms m sp pl vl ->\n  exists vl', Asm.annot_arguments rs m' (map transl_annot_param pl) vl'\n           /\\ Val.lessdef_list vl vl'.\nProof.\n  induction 3; intros. \n  exists (@nil val); split. constructor. constructor.\n  exploit annot_arg_match; eauto. intros [v1' [A B]].\n  destruct IHlist_forall2 as [vl' [C D]].\n  exists (v1' :: vl'); split; constructor; auto.\nQed.\n\n(** * Execution of straight-line code *)\n\nSection STRAIGHTLINE.\n\nVariable ge: genv.\nVariable fn: code.\n\n(** Straight-line code is composed of processor instructions that execute\n  in sequence (no branches, no function calls and returns).\n  The following inductive predicate relates the machine states\n  before and after executing a straight-line sequence of instructions.\n  Instructions are taken from the first list instead of being fetched\n  from memory. *)\n\nInductive exec_straight: code -> regset -> mem -> \n                         code -> regset -> mem -> Prop :=\n  | exec_straight_one:\n      forall i1 c rs1 m1 rs2 m2,\n      exec_instr ge fn i1 rs1 m1 = Next rs2 m2 ->\n      rs2#PC = Val.add rs1#PC Vone ->\n      exec_straight (i1 :: c) rs1 m1 c rs2 m2\n  | exec_straight_step:\n      forall i c rs1 m1 rs2 m2 c' rs3 m3,\n      exec_instr ge fn i rs1 m1 = Next rs2 m2 ->\n      rs2#PC = Val.add rs1#PC Vone ->\n      exec_straight c rs2 m2 c' rs3 m3 ->\n      exec_straight (i :: c) rs1 m1 c' rs3 m3.\n\nLemma exec_straight_trans:\n  forall c1 rs1 m1 c2 rs2 m2 c3 rs3 m3,\n  exec_straight c1 rs1 m1 c2 rs2 m2 ->\n  exec_straight c2 rs2 m2 c3 rs3 m3 ->\n  exec_straight c1 rs1 m1 c3 rs3 m3.\nProof.\n  induction 1; intros.\n  apply exec_straight_step with rs2 m2; auto.\n  apply exec_straight_step with rs2 m2; auto.\nQed.\n\nLemma exec_straight_two:\n  forall i1 i2 c rs1 m1 rs2 m2 rs3 m3,\n  exec_instr ge fn i1 rs1 m1 = Next rs2 m2 ->\n  exec_instr ge fn i2 rs2 m2 = Next rs3 m3 ->\n  rs2#PC = Val.add rs1#PC Vone ->\n  rs3#PC = Val.add rs2#PC Vone ->\n  exec_straight (i1 :: i2 :: c) rs1 m1 c rs3 m3.\nProof.\n  intros. apply exec_straight_step with rs2 m2; auto.\n  apply exec_straight_one; auto.\nQed.\n\nLemma exec_straight_three:\n  forall i1 i2 i3 c rs1 m1 rs2 m2 rs3 m3 rs4 m4,\n  exec_instr ge fn i1 rs1 m1 = Next rs2 m2 ->\n  exec_instr ge fn i2 rs2 m2 = Next rs3 m3 ->\n  exec_instr ge fn i3 rs3 m3 = Next rs4 m4 ->\n  rs2#PC = Val.add rs1#PC Vone ->\n  rs3#PC = Val.add rs2#PC Vone ->\n  rs4#PC = Val.add rs3#PC Vone ->\n  exec_straight (i1 :: i2 :: i3 :: c) rs1 m1 c rs4 m4.\nProof.\n  intros. apply exec_straight_step with rs2 m2; auto.\n  eapply exec_straight_two; eauto.\nQed.\n\n(** * Correctness of IA32 constructor functions *)\n\n(** Smart constructor for moves. *)\n\nLemma mk_mov_correct:\n  forall rd rs k c rs1 m,\n  mk_mov rd rs k = OK c ->\n  exists rs2,\n     exec_straight c rs1 m k rs2 m\n  /\\ rs2#rd = rs1#rs\n  /\\ forall r, important_preg r = true -> r <> ST0 -> r <> rd -> rs2#r = rs1#r.\nProof.\n  unfold mk_mov; intros. \n  destruct rd; try (monadInv H); destruct rs; monadInv H.\n(* mov *)\n  econstructor. split. apply exec_straight_one. simpl. eauto. auto. \n  split. rewrite nextinstr_inv; auto with ppcgen. apply Pregmap.gss.\n  intros. rewrite nextinstr_inv; auto with ppcgen. apply Pregmap.gso. auto. \n(* movd *)\n  econstructor. split. apply exec_straight_one. simpl. eauto. auto. \n  split. rewrite nextinstr_inv; auto with ppcgen. apply Pregmap.gss.\n  intros. rewrite nextinstr_inv; auto with ppcgen. apply Pregmap.gso. auto. \n(* getfp0 *)\n  econstructor. split. apply exec_straight_one. simpl. eauto. auto. \n  split. rewrite nextinstr_inv; auto with ppcgen. \n  rewrite Pregmap.gso; auto with ppcgen.\n  apply Pregmap.gss.\n  intros. rewrite nextinstr_inv; auto with ppcgen. rewrite Pregmap.gso; auto. rewrite Pregmap.gso; auto.\n(* setfp0 *)\n  econstructor. split. apply exec_straight_one. simpl. eauto. auto. \n  split. auto. \n  intros. rewrite nextinstr_inv; auto with ppcgen. apply Pregmap.gso. auto. \nQed.\n\n(** Smart constructor for shifts *)\n\nLtac SRes :=\n  match goal with\n  | [ |- nextinstr _ _ = _ ] => rewrite nextinstr_inv; [auto | auto with ppcgen]\n  | [ |- nextinstr_nf _ _ = _ ] => rewrite nextinstr_nf_inv; [auto | auto with ppcgen]\n  | [ |- Pregmap.get ?x (Pregmap.set ?x _ _) = _ ] => rewrite Pregmap.gss; auto\n  | [ |- Pregmap.set ?x _ _ ?x = _ ] => rewrite Pregmap.gss; auto\n  | [ |- Pregmap.get _ (Pregmap.set _ _ _) = _ ] => rewrite Pregmap.gso; [auto | auto with ppcgen]\n  | [ |- Pregmap.set _ _ _ _ = _ ] => rewrite Pregmap.gso; [auto | auto with ppcgen]\n  end.\n\nLtac SOther :=\n  match goal with\n  | [ |- nextinstr _ _ = _ ] => rewrite nextinstr_inv; [auto | auto with ppcgen]\n  | [ |- nextinstr_nf _ _ = _ ] => rewrite nextinstr_nf_inv2; [auto | auto with ppcgen]\n  | [ |- Pregmap.get ?x (Pregmap.set ?x _ _) = _ ] => rewrite Pregmap.gss; auto\n  | [ |- Pregmap.set ?x _ _ ?x = _ ] => rewrite Pregmap.gss; auto\n  | [ |- Pregmap.get _ (Pregmap.set _ _ _) = _ ] => rewrite Pregmap.gso; [auto | auto with ppcgen]\n  | [ |- Pregmap.set _ _ _ _ = _ ] => rewrite Pregmap.gso; [auto | auto with ppcgen]\n  end.\n\nLemma mk_shift_correct:\n  forall sinstr ssem r1 r2 k c rs1 m,\n  mk_shift sinstr r1 r2 k = OK c ->\n  (forall r c rs m,\n   exec_instr ge c (sinstr r) rs m = Next (nextinstr_nf (rs#r <- (ssem rs#r rs#ECX))) m) ->\n  exists rs2,\n     exec_straight c rs1 m k rs2 m\n  /\\ rs2#r1 = ssem rs1#r1 rs1#r2\n  /\\ forall r, nontemp_preg r = true -> r <> r1 -> rs2#r = rs1#r.\nProof.\n  unfold mk_shift; intros. \n  destruct (ireg_eq r2 ECX).\n(* fast case *)\n  monadInv H.\n  econstructor. split. apply exec_straight_one. apply H0. auto. \n  split. repeat SRes.\n  intros. repeat SOther.\n(* xchg case *)\n  destruct (ireg_eq r1 ECX); monadInv H. \n  econstructor. split. eapply exec_straight_three.\n  simpl; eauto. \n  apply H0.\n  simpl; eauto.\n  auto. auto. auto. \n  split. repeat SRes. repeat rewrite nextinstr_inv; auto with ppcgen. \n  rewrite Pregmap.gss. decEq. rewrite Pregmap.gso; auto with ppcgen. apply Pregmap.gss.\n  intros. destruct (preg_eq r r2). subst. repeat SRes. repeat SOther.\n(* general case *)\n  econstructor. split. eapply exec_straight_two. simpl; eauto. apply H0. \n  auto. auto. \n  split. repeat SRes. repeat rewrite nextinstr_inv; auto with ppcgen.\n  rewrite Pregmap.gss. decEq. rewrite Pregmap.gso; auto. congruence.\n  intros. repeat SOther.\nQed.\n\n(** Parallel move 2 *)\n\nLemma mk_mov2_correct:\n  forall src1 dst1 src2 dst2 k rs m,\n  dst1 <> dst2 ->\n  exists rs',\n     exec_straight (mk_mov2 src1 dst1 src2 dst2 k) rs m k rs' m\n  /\\ rs'#dst1 = rs#src1\n  /\\ rs'#dst2 = rs#src2\n  /\\ forall r, r <> PC -> r <> dst1 -> r <> dst2 -> rs'#r = rs#r.\nProof.\n  intros. unfold mk_mov2. \n(* single moves *)\n  destruct (ireg_eq src1 dst1). subst.\n  econstructor; split. apply exec_straight_one. simpl; eauto. auto.\n  split. repeat SRes. split. repeat SRes. intros; repeat SOther. \n  destruct (ireg_eq src2 dst2). subst.\n  econstructor; split. apply exec_straight_one. simpl; eauto. auto.\n  split. repeat SRes. split. repeat SRes. intros; repeat SOther. \n(* xchg *)\n  destruct (ireg_eq src2 dst1). destruct (ireg_eq src1 dst2).\n  subst. econstructor; split. apply exec_straight_one. simpl; eauto. auto.\n  split. repeat SRes. split. repeat SRes. intros; repeat SOther.\n(* move 2; move 1 *)\n  subst. econstructor; split. eapply exec_straight_two.\n  simpl; eauto. simpl; eauto. auto. auto.\n  split. repeat SRes. split. repeat SRes. intros; repeat SOther.\n(* move 1; move 2*)\n  subst. econstructor; split. eapply exec_straight_two.\n  simpl; eauto. simpl; eauto. auto. auto.\n  split. repeat SRes. split. repeat SRes. intros; repeat SOther.\nQed.\n\n(** Smart constructor for division *)\n\nLemma mk_div_correct:\n  forall mkinstr dsem msem r1 r2 k c (rs1: regset) m vq vr,\n  mk_div mkinstr r1 r2 k = OK c ->\n  (forall r c rs m,\n   exec_instr ge c (mkinstr r) rs m =\n      let vn := rs#EAX in let vd := (rs#EDX <- Vundef)#r in\n      match dsem vn vd, msem vn vd with\n      | Some vq, Some vr => Next (nextinstr_nf (rs#EAX <- vq #EDX <- vr)) m\n      | _, _ => Stuck\n      end) ->\n  dsem rs1#r1 rs1#r2 = Some vq ->\n  msem rs1#r1 rs1#r2 = Some vr ->\n  exists rs2,\n     exec_straight c rs1 m k rs2 m\n  /\\ rs2#r1 = vq\n  /\\ forall r, nontemp_preg r = true -> r <> r1 -> rs2#r = rs1#r.\nProof.\n  unfold mk_div; intros. \n  destruct (ireg_eq r1 EAX). destruct (ireg_eq r2 EDX); monadInv H.\n(* r1=EAX r2=EDX *)\n  econstructor. split. eapply exec_straight_two. simpl; eauto. \n  rewrite H0.\n  change (nextinstr rs1 # ECX <- (rs1 EDX) EAX) with (rs1#EAX). \n  change ((nextinstr rs1 # ECX <- (rs1 EDX)) # EDX <- Vundef ECX) with (rs1#EDX).\n  rewrite H1. rewrite H2. eauto. auto. auto. \n  split. SRes. \n  intros. repeat SOther.\n(* r1=EAX r2<>EDX *)\n  econstructor. split. eapply exec_straight_one. rewrite H0. \n  replace (rs1 # EDX <- Vundef r2) with (rs1 r2). rewrite H1; rewrite H2. eauto. \n  symmetry. SOther. auto.\n  split. SRes.\n  intros. repeat SOther. \n(* r1 <> EAX *)\n  monadInv H.\n  set (rs2 := nextinstr (rs1#XMM7 <- (rs1#EAX))).\n  exploit (mk_mov2_correct r1 EAX r2 ECX). congruence. instantiate (1 := rs2). \n  intros [rs3 [A [B [C D]]]].\n  econstructor; split.\n  apply exec_straight_step with rs2 m; auto.\n  eapply exec_straight_trans. eexact A. \n  eapply exec_straight_three.\n  rewrite H0. replace (rs3 EAX) with (rs1 r1). replace (rs3 # EDX <- Vundef ECX) with (rs1 r2).\n  rewrite H1; rewrite H2. eauto.  \n  simpl; eauto. simpl; eauto.\n  auto. auto. auto. \n  split. repeat SRes.\n  intros. destruct (preg_eq r EAX). subst.\n  repeat SRes. rewrite D; auto with ppcgen. \n  repeat SOther. rewrite D; auto with ppcgen. unfold rs2; repeat SOther.\nQed.\n\n(** Smart constructor for modulus *)\n\nLemma mk_mod_correct:\n forall mkinstr dsem msem r1 r2 k c (rs1: regset) m vq vr,\n  mk_mod mkinstr r1 r2 k = OK c ->\n  (forall r c rs m,\n   exec_instr ge c (mkinstr r) rs m =\n      let vn := rs#EAX in let vd := (rs#EDX <- Vundef)#r in\n      match dsem vn vd, msem vn vd with\n      | Some vq, Some vr => Next (nextinstr_nf (rs#EAX <- vq #EDX <- vr)) m\n      | _, _ => Stuck\n      end) ->\n  dsem rs1#r1 rs1#r2 = Some vq ->\n  msem rs1#r1 rs1#r2 = Some vr ->\n  exists rs2,\n     exec_straight c rs1 m k rs2 m\n  /\\ rs2#r1 = vr\n  /\\ forall r, nontemp_preg r = true -> r <> r1 -> rs2#r = rs1#r.\nProof.\n  unfold mk_mod; intros. \n  destruct (ireg_eq r1 EAX). destruct (ireg_eq r2 EDX); monadInv H.\n(* r1=EAX r2=EDX *)\n  econstructor. split. eapply exec_straight_three.\n  simpl; eauto.\n  rewrite H0.\n  change (nextinstr rs1 # ECX <- (rs1 EDX) EAX) with (rs1#EAX). \n  change ((nextinstr rs1 # ECX <- (rs1 EDX)) # EDX <- Vundef ECX) with (rs1#EDX).\n  rewrite H1. rewrite H2. eauto.\n  simpl; eauto.\n  auto. auto. auto. \n  split. SRes. \n  intros. repeat SOther.\n(* r1=EAX r2<>EDX *)\n  econstructor. split. eapply exec_straight_two. rewrite H0. \n  replace (rs1 # EDX <- Vundef r2) with (rs1 r2). rewrite H1; rewrite H2. eauto. \n  symmetry. SOther. \n  simpl; eauto. \n  auto. auto. \n  split. SRes.\n  intros. repeat SOther. \n(* r1 <> EAX *)\n  monadInv H.\n  set (rs2 := nextinstr (rs1#XMM7 <- (rs1#EAX))).\n  exploit (mk_mov2_correct r1 EAX r2 ECX). congruence. instantiate (1 := rs2). \n  intros [rs3 [A [B [C D]]]].\n  econstructor; split.\n  apply exec_straight_step with rs2 m; auto.\n  eapply exec_straight_trans. eexact A. \n  eapply exec_straight_three.\n  rewrite H0. replace (rs3 EAX) with (rs1 r1). replace (rs3 # EDX <- Vundef ECX) with (rs1 r2).\n  rewrite H1; rewrite H2. eauto.  \n  simpl; eauto. simpl; eauto.\n  auto. auto. auto. \n  split. repeat SRes.\n  intros. destruct (preg_eq r EAX). subst.\n  repeat SRes. rewrite D; auto with ppcgen. \n  repeat SOther. rewrite D; auto with ppcgen. unfold rs2; repeat SOther.\nQed.\n\nRemark divs_mods_exist:\n  forall v1 v2,\n  match Val.divs v1 v2, Val.mods v1 v2 with\n  | Some _, Some _ => True\n  | None, None => True\n  | _, _ => False\n  end.\nProof.\n  intros. unfold Val.divs, Val.mods. destruct v1; auto. destruct v2; auto.\n  destruct (Int.eq i0 Int.zero || Int.eq i (Int.repr Int.min_signed) && Int.eq i0 Int.mone); auto. \nQed.\n\nRemark divu_modu_exist:\n  forall v1 v2,\n  match Val.divu v1 v2, Val.modu v1 v2 with\n  | Some _, Some _ => True\n  | None, None => True\n  | _, _ => False\n  end.\nProof.\n  intros. unfold Val.divu, Val.modu. destruct v1; auto. destruct v2; auto.\n  destruct (Int.eq i0 Int.zero); auto. \nQed.\n\n(** Smart constructor for [shrx] *)\n\nLemma mk_shrximm_correct:\n  forall r1 n k c (rs1: regset) v m,\n  mk_shrximm r1 n k = OK c ->\n  Val.shrx (rs1#r1) (Vint n) = Some v ->\n  exists rs2,\n     exec_straight c rs1 m k rs2 m\n  /\\ rs2#r1 = v\n  /\\ forall r, nontemp_preg r = true -> r <> r1 -> rs2#r = rs1#r.\nProof.\n  unfold mk_shrximm; intros. inv H.\n  exploit Val.shrx_shr; eauto. intros [x [y [A [B C]]]].\n  inversion B; clear B; subst y; subst v; clear H0.\n  set (tmp := if ireg_eq r1 ECX then EDX else ECX).\n  assert (TMP1: tmp <> r1). unfold tmp; destruct (ireg_eq r1 ECX); congruence. \n  assert (TMP2: nontemp_preg tmp = false). unfold tmp; destruct (ireg_eq r1 ECX); auto. \n  set (tnm1 := Int.sub (Int.shl Int.one n) Int.one).\n  set (x' := Int.add x tnm1).\n  set (rs2 := nextinstr (compare_ints (Vint x) (Vint Int.zero) rs1 m)).\n  set (rs3 := nextinstr (rs2#tmp <- (Vint x'))).\n  set (rs4 := nextinstr (if Int.lt x Int.zero then rs3#r1 <- (Vint x') else rs3)).\n  set (rs5 := nextinstr_nf (rs4#r1 <- (Val.shr rs4#r1 (Vint n)))).\n  assert (rs3#r1 = Vint x). unfold rs3. SRes. SRes. \n  assert (rs3#tmp = Vint x'). unfold rs3. SRes. SRes. \n  exists rs5. split. \n  apply exec_straight_step with rs2 m. simpl. rewrite A. simpl. rewrite Int.and_idem. auto. auto.\n  apply exec_straight_step with rs3 m. simpl. \n  change (rs2 r1) with (rs1 r1). rewrite A. simpl. \n  rewrite (Int.add_commut Int.zero tnm1). rewrite Int.add_zero. auto. auto.\n  apply exec_straight_step with rs4 m. simpl. \n  change (rs3 SOF) with (rs2 SOF). unfold rs2. rewrite nextinstr_inv; auto with ppcgen. \n  unfold compare_ints. rewrite Pregmap.gso; auto with ppcgen. rewrite Pregmap.gss.\n  unfold Val.cmp. simpl. unfold rs4. destruct (Int.lt x Int.zero); simpl; auto. rewrite H0; auto.\n  unfold rs4. destruct (Int.lt x Int.zero); simpl; auto.\n  apply exec_straight_one. auto. auto.\n  split. unfold rs5. SRes. SRes. unfold rs4. rewrite nextinstr_inv; auto with ppcgen.\n  destruct (Int.lt x Int.zero). rewrite Pregmap.gss. rewrite A; auto. rewrite A; rewrite H; auto.\n  intros. unfold rs5. repeat SOther. unfold rs4. SOther.\n  transitivity (rs3#r). destruct (Int.lt x Int.zero). SOther. auto. \n  unfold rs3. repeat SOther. unfold rs2. repeat SOther. \n  unfold compare_ints. repeat SOther. \nQed.\n\n(** Smart constructor for integer conversions *)\n\nLemma mk_intconv_correct:\n  forall mk sem rd rs k c rs1 m,\n  mk_intconv mk rd rs k = OK c ->\n  (forall c rd rs r m,\n   exec_instr ge c (mk rd rs) r m = Next (nextinstr (r#rd <- (sem r#rs))) m) ->\n  exists rs2,\n     exec_straight c rs1 m k rs2 m\n  /\\ rs2#rd = sem rs1#rs\n  /\\ forall r, nontemp_preg r = true -> r <> rd -> rs2#r = rs1#r.\nProof.\n  unfold mk_intconv; intros. destruct (low_ireg rs); monadInv H.\n  econstructor. split. apply exec_straight_one. rewrite H0. eauto. auto. \n  split. repeat SRes.\n  intros. repeat SOther.\n  econstructor. split. eapply exec_straight_two. \n  simpl. eauto. apply H0. auto. auto. \n  split. repeat SRes. \n  intros. repeat SOther. \nQed.\n\n(** Smart constructor for small stores *)\n\nLemma addressing_mentions_correct:\n  forall a r (rs1 rs2: regset),\n  (forall (r': ireg), r' <> r -> rs1 r' = rs2 r') ->\n  addressing_mentions a r = false ->\n  eval_addrmode ge a rs1 = eval_addrmode ge a rs2.\nProof.\n  intros until rs2; intro AG. unfold addressing_mentions, eval_addrmode.\n  destruct a. intros. destruct (orb_false_elim _ _ H). unfold proj_sumbool in *.\n  decEq. destruct base; auto. apply AG. destruct (ireg_eq r i); congruence.\n  decEq. destruct ofs as [[r' sc] | ]; auto. rewrite AG; auto. destruct (ireg_eq r r'); congruence.\nQed.\n\nLemma mk_smallstore_correct:\n  forall chunk sto addr r k c rs1 m1 m2,\n  mk_smallstore sto addr r k = OK c ->\n  Mem.storev chunk m1 (eval_addrmode ge addr rs1) (rs1 r) = Some m2 ->\n  (forall c r addr rs m,\n   exec_instr ge c (sto addr r) rs m = exec_store ge chunk m addr rs r) ->\n  exists rs2,\n     exec_straight c rs1 m1 k rs2 m2\n  /\\ forall r, nontemp_preg r = true -> rs2#r = rs1#r.\nProof.\n  unfold mk_smallstore; intros. \n  remember (low_ireg r) as low. destruct low.\n(* low reg *)\n  monadInv H. econstructor; split. apply exec_straight_one. rewrite H1. \n  unfold exec_store. rewrite H0. eauto. auto. \n  intros. SOther.\n(* high reg *)\n   remember (addressing_mentions addr ECX) as mentions. destruct mentions; monadInv H.\n(* ECX is mentioned. *)\n  assert (r <> ECX). red; intros; subst r; discriminate. \n  set (rs2 := nextinstr (rs1#ECX <- (eval_addrmode ge addr rs1))).\n  set (rs3 := nextinstr (rs2#EDX <- (rs1 r))).\n  econstructor; split.\n  apply exec_straight_three with rs2 m1 rs3 m1. \n  simpl. auto. \n  simpl. replace (rs2 r) with (rs1 r). auto. symmetry. unfold rs2. repeat SRes. \n  rewrite H1. unfold exec_store. simpl. rewrite Int.add_zero. \n  change (rs3 EDX) with (rs1 r).\n  change (rs3 ECX) with (eval_addrmode ge addr rs1).\n  replace (Val.add (eval_addrmode ge addr rs1) (Vint Int.zero))\n     with (eval_addrmode ge addr rs1).\n  rewrite H0. eauto.\n  destruct (eval_addrmode ge addr rs1); simpl in H0; try discriminate.\n  simpl. rewrite Int.add_zero; auto. \n  auto. auto. auto. \n  intros. repeat SOther. unfold rs3. repeat SOther. unfold rs2. repeat SOther.\n(* ECX is not mentioned *)\n  set (rs2 := nextinstr (rs1#ECX <- (rs1 r))).\n  econstructor; split.\n  apply exec_straight_two with rs2 m1.\n  simpl. auto.\n  rewrite H1. unfold exec_store. \n  rewrite (addressing_mentions_correct addr ECX rs2 rs1); auto.\n  change (rs2 ECX) with (rs1 r). rewrite H0. eauto. \n  intros. unfold rs2. rewrite nextinstr_inv; auto with ppcgen. apply Pregmap.gso; auto with ppcgen.\n  auto. auto. \n  intros. rewrite dec_eq_false. repeat SOther. unfold rs2. repeat SOther. congruence.\nQed.\n\n(** Accessing slots in the stack frame *)\n\nLemma loadind_correct:\n  forall (base: ireg) ofs ty dst k (rs: regset) c m v,\n  loadind base ofs ty dst k = OK c ->\n  Mem.loadv (chunk_of_type ty) m (Val.add rs#base (Vint ofs)) = Some v ->\n  exists rs',\n     exec_straight c rs m k rs' m\n  /\\ rs'#(preg_of dst) = v\n  /\\ forall r, important_preg r = true -> r <> preg_of dst -> rs'#r = rs#r.\nProof.\n  unfold loadind; intros.\n  set (addr := Addrmode (Some base) None (inl (ident * int) ofs)) in *.\n  assert (eval_addrmode ge addr rs = Val.add rs#base (Vint ofs)).\n    unfold addr. simpl. rewrite Int.add_commut; rewrite Int.add_zero; auto. \n  destruct ty; simpl in H0.\n  (* int *)\n  monadInv H.\n  rewrite (ireg_of_eq _ _ EQ). econstructor.\n  split. apply exec_straight_one. simpl. unfold exec_load. rewrite H1. rewrite H0.\n  eauto. auto. \n  split. repeat SRes. \n  intros. rewrite nextinstr_nf_inv1; auto. SOther.\n  (* float *)\n  exists (nextinstr_nf (rs#(preg_of dst) <- v)).\n  split. destruct (preg_of dst); inv H; apply exec_straight_one; simpl; auto.\n  unfold exec_load. rewrite H1; rewrite H0; auto. \n  unfold exec_load. rewrite H1; rewrite H0; auto. \n  split. rewrite nextinstr_nf_inv1. SRes. apply preg_of_important.\n  intros. rewrite nextinstr_nf_inv1; auto. SOther.\nQed.\n\nLemma storeind_correct:\n  forall (base: ireg) ofs ty src k (rs: regset) c m m',\n  storeind src base ofs ty k = OK c ->\n  Mem.storev (chunk_of_type ty) m (Val.add rs#base (Vint ofs)) (rs#(preg_of src)) = Some m' ->\n  exists rs',\n     exec_straight c rs m k rs' m'\n  /\\ forall r, important_preg r = true -> r <> ST0 -> rs'#r = rs#r.\nProof.\n  unfold storeind; intros.\n  set (addr := Addrmode (Some base) None (inl (ident * int) ofs)) in *.\n  assert (eval_addrmode ge addr rs = Val.add rs#base (Vint ofs)).\n    unfold addr. simpl. rewrite Int.add_commut; rewrite Int.add_zero; auto. \n  destruct ty; simpl in H0.\n  (* int *)\n  monadInv H.\n  rewrite (ireg_of_eq _ _ EQ) in H0. econstructor.\n  split. apply exec_straight_one. simpl. unfold exec_store. rewrite H1. rewrite H0.\n  eauto. auto. \n  intros. apply nextinstr_nf_inv1; auto. \n  (* float *)\n  destruct (preg_of src); inv H.\n  econstructor; split. apply exec_straight_one.\n  simpl. unfold exec_store. rewrite H1; rewrite H0. eauto. auto.\n  intros. apply nextinstr_nf_inv1; auto.\n  econstructor; split. apply exec_straight_one.\n  simpl. unfold exec_store. rewrite H1; rewrite H0. eauto. auto.\n  intros. rewrite nextinstr_nf_inv1; auto. rewrite dec_eq_true. apply Pregmap.gso; auto.\nQed.\n\n(** Translation of addressing modes *)\n\nLemma transl_addressing_mode_correct:\n  forall addr args am (rs: regset) v,\n  transl_addressing addr args = OK am ->\n  eval_addressing ge (rs ESP) addr (List.map rs (List.map preg_of args)) = Some v ->\n  Val.lessdef v (eval_addrmode ge am rs).\nProof.\n  assert (A: forall n, Int.add Int.zero n = n). \n    intros. rewrite Int.add_commut. apply Int.add_zero.\n  assert (B: forall n i, (if Int.eq i Int.one then Vint n else Vint (Int.mul n i)) = Vint (Int.mul n i)).\n    intros. predSpec Int.eq Int.eq_spec i Int.one. \n    subst i. rewrite Int.mul_one. auto. auto.\n  assert (C: forall v i,\n    Val.lessdef (Val.mul v (Vint i))\n               (if Int.eq i Int.one then v else Val.mul v (Vint i))).\n    intros. predSpec Int.eq Int.eq_spec i Int.one.\n    subst i. destruct v; simpl; auto. rewrite Int.mul_one; auto.\n    destruct v; simpl; auto.\n  unfold transl_addressing; intros.\n  destruct addr; repeat (destruct args; try discriminate); simpl in H0; inv H0.\n(* indexed *)\n  monadInv H. rewrite (ireg_of_eq _ _ EQ). simpl. rewrite A; auto.\n(* indexed2 *)\n  monadInv H. rewrite (ireg_of_eq _ _ EQ); rewrite (ireg_of_eq _ _ EQ1). simpl.\n  rewrite Val.add_assoc; auto. \n(* scaled *)\n  monadInv H. rewrite (ireg_of_eq _ _ EQ). unfold eval_addrmode. \n  rewrite Val.add_permut. simpl. rewrite A. apply Val.add_lessdef; auto. \n(* indexed2scaled *)\n  monadInv H. rewrite (ireg_of_eq _ _ EQ); rewrite (ireg_of_eq _ _ EQ1); simpl.\n  apply Val.add_lessdef; auto. apply Val.add_lessdef; auto. \n(* global *)\n  inv H. simpl. unfold symbol_address, symbol_offset.\n  destruct (Genv.find_symbol ge i); simpl; auto. repeat rewrite Int.add_zero. auto.\n(* based *)\n  monadInv H. rewrite (ireg_of_eq _ _ EQ). simpl.\n  unfold symbol_address, symbol_offset. destruct (Genv.find_symbol ge i); simpl; auto.\n  rewrite Int.add_zero. rewrite Val.add_commut. auto. \n(* basedscaled *)\n  monadInv H. rewrite (ireg_of_eq _ _ EQ). unfold eval_addrmode. \n  rewrite (Val.add_commut Vzero). rewrite Val.add_assoc. rewrite Val.add_permut.\n  apply Val.add_lessdef; auto. destruct (rs x); simpl; auto. rewrite B. simpl.\n  rewrite Int.add_zero. auto.\n(* instack *)\n  inv H; simpl. rewrite A; auto.\nQed.\n\n(** Processor conditions and comparisons *)\n\nLemma compare_ints_spec:\n  forall rs v1 v2 m,\n  let rs' := nextinstr (compare_ints v1 v2 rs m) in\n     rs'#ZF = Val.cmpu (Mem.valid_pointer m) Ceq v1 v2\n  /\\ rs'#CF = Val.cmpu (Mem.valid_pointer m) Clt v1 v2\n  /\\ rs'#SOF = Val.cmp Clt v1 v2\n  /\\ (forall r, nontemp_preg r = true -> rs'#r = rs#r).\nProof.\n  intros. unfold rs'; unfold compare_ints.\n  split. auto. \n  split. auto.\n  split. auto.\n  intros. repeat SOther. \nQed.\n\nLemma int_signed_eq:\n  forall x y, Int.eq x y = zeq (Int.signed x) (Int.signed y).\nProof.\n  intros. unfold Int.eq. unfold proj_sumbool. \n  destruct (zeq (Int.unsigned x) (Int.unsigned y));\n  destruct (zeq (Int.signed x) (Int.signed y)); auto.\n  elim n. unfold Int.signed. rewrite e; auto.\n  elim n. apply Int.eqm_small_eq; auto with ints. \n  eapply Int.eqm_trans. apply Int.eqm_sym. apply Int.eqm_signed_unsigned.\n  rewrite e. apply Int.eqm_signed_unsigned. \nQed.\n\nLemma int_not_lt:\n  forall x y, negb (Int.lt y x) = (Int.lt x y || Int.eq x y).\nProof.\n  intros. unfold Int.lt. rewrite int_signed_eq. unfold proj_sumbool.\n  destruct (zlt (Int.signed y) (Int.signed x)).\n  rewrite zlt_false. rewrite zeq_false. auto. omega. omega.\n  destruct (zeq (Int.signed x) (Int.signed y)). \n  rewrite zlt_false. auto. omega. \n  rewrite zlt_true. auto. omega.\nQed.\n\nLemma int_lt_not:\n  forall x y, Int.lt y x = negb (Int.lt x y) && negb (Int.eq x y).\nProof.\n  intros. rewrite <- negb_orb. rewrite <- int_not_lt. rewrite negb_involutive. auto.\nQed.\n\nLemma int_not_ltu:\n  forall x y, negb (Int.ltu y x) = (Int.ltu x y || Int.eq x y).\nProof.\n  intros. unfold Int.ltu, Int.eq.\n  destruct (zlt (Int.unsigned y) (Int.unsigned x)).\n  rewrite zlt_false. rewrite zeq_false. auto. omega. omega.\n  destruct (zeq (Int.unsigned x) (Int.unsigned y)). \n  rewrite zlt_false. auto. omega. \n  rewrite zlt_true. auto. omega.\nQed.\n\nLemma int_ltu_not:\n  forall x y, Int.ltu y x = negb (Int.ltu x y) && negb (Int.eq x y).\nProof.\n  intros. rewrite <- negb_orb. rewrite <- int_not_ltu. rewrite negb_involutive. auto.\nQed.\n\nLemma testcond_for_signed_comparison_correct:\n  forall c v1 v2 rs m b,\n  Val.cmp_bool c v1 v2 = Some b ->\n  eval_testcond (testcond_for_signed_comparison c)\n                (nextinstr (compare_ints v1 v2 rs m)) = Some b.\nProof.\n  intros. generalize (compare_ints_spec rs v1 v2 m).\n  set (rs' := nextinstr (compare_ints v1 v2 rs m)).\n  intros [A [B [C D]]].\n  destruct v1; destruct v2; simpl in H; inv H.\n  unfold eval_testcond. rewrite A; rewrite B; rewrite C. unfold Val.cmp, Val.cmpu.\n  destruct c; simpl.\n  destruct (Int.eq i i0); auto.\n  destruct (Int.eq i i0); auto.\n  destruct (Int.lt i i0); auto.\n  rewrite int_not_lt. destruct (Int.lt i i0); simpl; destruct (Int.eq i i0); auto.\n  rewrite (int_lt_not i i0). destruct (Int.lt i i0); destruct (Int.eq i i0); reflexivity.\n  destruct (Int.lt i i0); reflexivity.\nQed.\n\nLemma testcond_for_unsigned_comparison_correct:\n  forall c v1 v2 rs m b,\n  Val.cmpu_bool (Mem.valid_pointer m) c v1 v2 = Some b ->\n  eval_testcond (testcond_for_unsigned_comparison c)\n                (nextinstr (compare_ints v1 v2 rs m)) = Some b.\nProof.\n  intros. generalize (compare_ints_spec rs v1 v2 m).\n  set (rs' := nextinstr (compare_ints v1 v2 rs m)).\n  intros [A [B [C D]]].\n  unfold eval_testcond. rewrite A; rewrite B; rewrite C. unfold Val.cmpu, Val.cmp.\n  destruct v1; destruct v2; simpl in H; inv H.\n(* int int *)\n  destruct c; simpl; auto.\n  destruct (Int.eq i i0); reflexivity.\n  destruct (Int.eq i i0); auto.\n  destruct (Int.ltu i i0); auto.\n  rewrite int_not_ltu. destruct (Int.ltu i i0); simpl; destruct (Int.eq i i0); auto.\n  rewrite (int_ltu_not i i0). destruct (Int.ltu i i0); destruct (Int.eq i i0); reflexivity.\n  destruct (Int.ltu i i0); reflexivity.\n(* int ptr *)\n  destruct (Int.eq i Int.zero) as []_eqn; try discriminate.\n  destruct c; simpl in *; inv H1.\n  rewrite Heqb1; reflexivity. \n  rewrite Heqb1; reflexivity.\n(* ptr int *)\n  destruct (Int.eq i0 Int.zero) as []_eqn; try discriminate.\n  destruct c; simpl in *; inv H1.\n  rewrite Heqb1; reflexivity. \n  rewrite Heqb1; reflexivity.\n(* ptr ptr *)\n  simpl. \n  destruct (Mem.valid_pointer m b0 (Int.unsigned i) &&\n            Mem.valid_pointer m b1 (Int.unsigned i0)); try discriminate.\n  destruct (zeq b0 b1).\n  inversion H1.\n  destruct c; simpl; auto.\n  destruct (Int.eq i i0); reflexivity.\n  destruct (Int.eq i i0); auto.\n  destruct (Int.ltu i i0); auto.\n  rewrite int_not_ltu. destruct (Int.ltu i i0); simpl; destruct (Int.eq i i0); auto.\n  rewrite (int_ltu_not i i0). destruct (Int.ltu i i0); destruct (Int.eq i i0); reflexivity.\n  destruct (Int.ltu i i0); reflexivity.\n  destruct c; simpl in *; inv H1; reflexivity.\nQed.\n\nLemma compare_floats_spec:\n  forall rs n1 n2,\n  let rs' := nextinstr (compare_floats (Vfloat n1) (Vfloat n2) rs) in\n     rs'#ZF = Val.of_bool (negb (Float.cmp Cne n1 n2))\n  /\\ rs'#CF = Val.of_bool (negb (Float.cmp Cge n1 n2))\n  /\\ rs'#PF = Val.of_bool (negb (Float.cmp Ceq n1 n2 || Float.cmp Clt n1 n2 || Float.cmp Cgt n1 n2))\n  /\\ (forall r, nontemp_preg r = true -> rs'#r = rs#r).\nProof.\n  intros. unfold rs'; unfold compare_floats.\n  split. auto. \n  split. auto.\n  split. auto.\n  intros. repeat SOther. \nQed.\n\nDefinition eval_extcond (xc: extcond) (rs: regset) : option bool :=\n  match xc with\n  | Cond_base c =>\n      eval_testcond c rs\n  | Cond_and c1 c2 =>\n      match eval_testcond c1 rs, eval_testcond c2 rs with\n      | Some b1, Some b2 => Some (b1 && b2)\n      | _, _ => None\n      end\n  | Cond_or c1 c2 =>\n      match eval_testcond c1 rs, eval_testcond c2 rs with\n      | Some b1, Some b2 => Some (b1 || b2)\n      | _, _ => None\n      end\n  end.\n\n(*******\n\nDefinition swap_floats {A: Type} (c: comparison) (n1 n2: A) : A :=\n  match c with\n  | Clt | Cle => n2\n  | Ceq | Cne | Cgt | Cge => n1\n  end.\n\nLemma testcond_for_float_comparison_correct:\n  forall c v1 v2 rs b,\n  Val.cmpf_bool c v1 v2 = Some b ->\n  eval_extcond (testcond_for_condition (Ccompf c))\n               (nextinstr (compare_floats (swap_floats c v1 v2)\n                                         (swap_floats c v2 v1) rs)) = Some b.\nProof.\n  intros. destruct v1; destruct v2; simpl in H; inv H.\n  assert (SWP: forall f1 f2, Vfloat (swap_floats c f1 f2) = swap_floats c (Vfloat f1) (Vfloat f2)).\n    destruct c; auto.\n  generalize (compare_floats_spec rs (swap_floats c f f0) (swap_floats c f0 f)).\n  repeat rewrite <- SWP.\n  set (rs' := nextinstr (compare_floats (Vfloat (swap_floats c f f0))\n                                      (Vfloat (swap_floats c f0 f)) rs)).\n  intros [A [B [C D]]].\n  unfold eval_extcond, eval_testcond. rewrite A; rewrite B; rewrite C.\n  destruct c; simpl.\n(* eq *)\n  rewrite Float.cmp_ne_eq.\n  destruct (Float.cmp Ceq f f0). auto.\n  simpl. destruct (Float.cmp Clt f f0 || Float.cmp Cgt f f0); auto.\n(* ne *)\n  rewrite Float.cmp_ne_eq.\n  destruct (Float.cmp Ceq f f0). auto.\n  simpl. destruct (Float.cmp Clt f f0 || Float.cmp Cgt f f0); auto.\n(* lt *)\n  rewrite <- (Float.cmp_swap Cge f f0).\n  rewrite <- (Float.cmp_swap Cne f f0).\n  simpl.\n  rewrite Float.cmp_ne_eq. rewrite Float.cmp_le_lt_eq.\n  caseEq (Float.cmp Clt f f0); intros; simpl.\n  caseEq (Float.cmp Ceq f f0); intros; simpl. \n  elimtype False. eapply Float.cmp_lt_eq_false; eauto. \n  auto. \n  destruct (Float.cmp Ceq f f0); auto.\n(* le *)\n  rewrite <- (Float.cmp_swap Cge f f0). simpl.\n  destruct (Float.cmp Cle f f0); auto.\n(* gt *)\n  rewrite Float.cmp_ne_eq. rewrite Float.cmp_ge_gt_eq. \n  caseEq (Float.cmp Cgt f f0); intros; simpl.\n  caseEq (Float.cmp Ceq f f0); intros; simpl. \n  elimtype False. eapply Float.cmp_gt_eq_false; eauto. \n  auto. \n  destruct (Float.cmp Ceq f f0); auto.\n(* ge *)\n  destruct (Float.cmp Cge f f0); auto.\nQed.\n\nLemma testcond_for_neg_float_comparison_correct:\n  forall c n1 n2 rs,\n  eval_extcond (testcond_for_condition (Cnotcompf c))\n               (nextinstr (compare_floats (Vfloat (swap_floats c n1 n2))\n                                          (Vfloat (swap_floats c n2 n1)) rs)) =\n  Some(negb(Float.cmp c n1 n2)).\nProof.\n  intros.\n  generalize (compare_floats_spec rs (swap_floats c n1 n2) (swap_floats c n2 n1)).\n  set (rs' := nextinstr (compare_floats (Vfloat (swap_floats c n1 n2))\n                                        (Vfloat (swap_floats c n2 n1)) rs)).\n  intros [A [B [C D]]].\n  unfold eval_extcond, eval_testcond. rewrite A; rewrite B; rewrite C.\n  destruct c; simpl.\n(* eq *)\n  rewrite Float.cmp_ne_eq.\n  caseEq (Float.cmp Ceq n1 n2); intros.\n  auto.\n  simpl. destruct (Float.cmp Clt n1 n2 || Float.cmp Cgt n1 n2); auto.\n(* ne *)\n  rewrite Float.cmp_ne_eq.\n  caseEq (Float.cmp Ceq n1 n2); intros.\n  auto.\n  simpl. destruct (Float.cmp Clt n1 n2 || Float.cmp Cgt n1 n2); auto.\n(* lt *)\n  rewrite <- (Float.cmp_swap Cge n1 n2).\n  rewrite <- (Float.cmp_swap Cne n1 n2).\n  simpl.\n  rewrite Float.cmp_ne_eq. rewrite Float.cmp_le_lt_eq.\n  caseEq (Float.cmp Clt n1 n2); intros; simpl.\n  caseEq (Float.cmp Ceq n1 n2); intros; simpl. \n  elimtype False. eapply Float.cmp_lt_eq_false; eauto.\n  auto. \n  destruct (Float.cmp Ceq n1 n2); auto.\n(* le *)\n  rewrite <- (Float.cmp_swap Cge n1 n2). simpl.\n  destruct (Float.cmp Cle n1 n2); auto.\n(* gt *)\n  rewrite Float.cmp_ne_eq. rewrite Float.cmp_ge_gt_eq. \n  caseEq (Float.cmp Cgt n1 n2); intros; simpl.\n  caseEq (Float.cmp Ceq n1 n2); intros; simpl. \n  elimtype False. eapply Float.cmp_gt_eq_false; eauto. \n  auto. \n  destruct (Float.cmp Ceq n1 n2); auto.\n(* ge *)\n  destruct (Float.cmp Cge n1 n2); auto.\nQed.\n***************)\n\nDefinition swap_floats {A: Type} (c: comparison) (n1 n2: A) : A :=\n  match c with\n  | Clt | Cle => n2\n  | Ceq | Cne | Cgt | Cge => n1\n  end.\n\nLemma testcond_for_float_comparison_correct:\n  forall c n1 n2 rs,\n  eval_extcond (testcond_for_condition (Ccompf c))\n               (nextinstr (compare_floats (Vfloat (swap_floats c n1 n2))\n                                          (Vfloat (swap_floats c n2 n1)) rs)) =\n  Some(Float.cmp c n1 n2).\nProof.\n  intros.\n  generalize (compare_floats_spec rs (swap_floats c n1 n2) (swap_floats c n2 n1)).\n  set (rs' := nextinstr (compare_floats (Vfloat (swap_floats c n1 n2))\n                                        (Vfloat (swap_floats c n2 n1)) rs)).\n  intros [A [B [C D]]].\n  unfold eval_extcond, eval_testcond. rewrite A; rewrite B; rewrite C.\n  destruct c; simpl.\n(* eq *)\n  rewrite Float.cmp_ne_eq.\n  caseEq (Float.cmp Ceq n1 n2); intros.\n  auto.\n  simpl. destruct (Float.cmp Clt n1 n2 || Float.cmp Cgt n1 n2); auto.\n(* ne *)\n  rewrite Float.cmp_ne_eq.\n  caseEq (Float.cmp Ceq n1 n2); intros.\n  auto.\n  simpl. destruct (Float.cmp Clt n1 n2 || Float.cmp Cgt n1 n2); auto.\n(* lt *)\n  rewrite <- (Float.cmp_swap Cge n1 n2).\n  rewrite <- (Float.cmp_swap Cne n1 n2).\n  simpl.\n  rewrite Float.cmp_ne_eq. rewrite Float.cmp_le_lt_eq.\n  caseEq (Float.cmp Clt n1 n2); intros; simpl.\n  caseEq (Float.cmp Ceq n1 n2); intros; simpl. \n  elimtype False. eapply Float.cmp_lt_eq_false; eauto. \n  auto. \n  destruct (Float.cmp Ceq n1 n2); auto.\n(* le *)\n  rewrite <- (Float.cmp_swap Cge n1 n2). simpl.\n  destruct (Float.cmp Cle n1 n2); auto.\n(* gt *)\n  rewrite Float.cmp_ne_eq. rewrite Float.cmp_ge_gt_eq. \n  caseEq (Float.cmp Cgt n1 n2); intros; simpl.\n  caseEq (Float.cmp Ceq n1 n2); intros; simpl. \n  elimtype False. eapply Float.cmp_gt_eq_false; eauto. \n  auto. \n  destruct (Float.cmp Ceq n1 n2); auto.\n(* ge *)\n  destruct (Float.cmp Cge n1 n2); auto.\nQed.\n\nLemma testcond_for_neg_float_comparison_correct:\n  forall c n1 n2 rs,\n  eval_extcond (testcond_for_condition (Cnotcompf c))\n               (nextinstr (compare_floats (Vfloat (swap_floats c n1 n2))\n                                          (Vfloat (swap_floats c n2 n1)) rs)) =\n  Some(negb(Float.cmp c n1 n2)).\nProof.\n  intros.\n  generalize (compare_floats_spec rs (swap_floats c n1 n2) (swap_floats c n2 n1)).\n  set (rs' := nextinstr (compare_floats (Vfloat (swap_floats c n1 n2))\n                                        (Vfloat (swap_floats c n2 n1)) rs)).\n  intros [A [B [C D]]].\n  unfold eval_extcond, eval_testcond. rewrite A; rewrite B; rewrite C.\n  destruct c; simpl.\n(* eq *)\n  rewrite Float.cmp_ne_eq.\n  caseEq (Float.cmp Ceq n1 n2); intros.\n  auto.\n  simpl. destruct (Float.cmp Clt n1 n2 || Float.cmp Cgt n1 n2); auto.\n(* ne *)\n  rewrite Float.cmp_ne_eq.\n  caseEq (Float.cmp Ceq n1 n2); intros.\n  auto.\n  simpl. destruct (Float.cmp Clt n1 n2 || Float.cmp Cgt n1 n2); auto.\n(* lt *)\n  rewrite <- (Float.cmp_swap Cge n1 n2).\n  rewrite <- (Float.cmp_swap Cne n1 n2).\n  simpl.\n  rewrite Float.cmp_ne_eq. rewrite Float.cmp_le_lt_eq.\n  caseEq (Float.cmp Clt n1 n2); intros; simpl.\n  caseEq (Float.cmp Ceq n1 n2); intros; simpl. \n  elimtype False. eapply Float.cmp_lt_eq_false; eauto.\n  auto. \n  destruct (Float.cmp Ceq n1 n2); auto.\n(* le *)\n  rewrite <- (Float.cmp_swap Cge n1 n2). simpl.\n  destruct (Float.cmp Cle n1 n2); auto.\n(* gt *)\n  rewrite Float.cmp_ne_eq. rewrite Float.cmp_ge_gt_eq. \n  caseEq (Float.cmp Cgt n1 n2); intros; simpl.\n  caseEq (Float.cmp Ceq n1 n2); intros; simpl. \n  elimtype False. eapply Float.cmp_gt_eq_false; eauto. \n  auto. \n  destruct (Float.cmp Ceq n1 n2); auto.\n(* ge *)\n  destruct (Float.cmp Cge n1 n2); auto.\nQed.\n\nRemark swap_floats_commut:\n  forall c x y, swap_floats c (Vfloat x) (Vfloat y) = Vfloat (swap_floats c x y).\nProof.\n  intros. destruct c; auto. \nQed.\n\nRemark compare_floats_inv:\n  forall vx vy rs r,\n  r <> CR ZF -> r <> CR CF -> r <> CR PF -> r <> CR SOF ->\n  compare_floats vx vy rs r = rs r.\nProof.\n  intros. \n  assert (DFL: undef_regs (CR ZF :: CR CF :: CR PF :: CR SOF :: nil) rs r = rs r).\n    simpl. repeat SOther.\n  unfold compare_floats; destruct vx; destruct vy; auto. repeat SOther.\nQed.  \n\nLemma transl_cond_correct:\n  forall cond args k c rs m,\n  transl_cond cond args k = OK c ->\n  exists rs',\n     exec_straight c rs m k rs' m\n  /\\ match eval_condition cond (map rs (map preg_of args)) m with\n     | None => True\n     | Some b => eval_extcond (testcond_for_condition cond) rs' = Some b\n     end\n  /\\ forall r, nontemp_preg r = true -> rs'#r = rs r.\nProof.\n  unfold transl_cond; intros. \n  destruct cond; repeat (destruct args; try discriminate); monadInv H.\n(* comp *)\n  simpl. rewrite (ireg_of_eq _ _ EQ). rewrite (ireg_of_eq _ _ EQ1).\n  econstructor. split. apply exec_straight_one. simpl. eauto. auto.\n  split. destruct (Val.cmp_bool c0 (rs x) (rs x0)) as []_eqn; auto.\n  eapply testcond_for_signed_comparison_correct; eauto. \n  intros. unfold compare_ints. repeat SOther.\n(* compu *)\n  simpl. rewrite (ireg_of_eq _ _ EQ). rewrite (ireg_of_eq _ _ EQ1).\n  econstructor. split. apply exec_straight_one. simpl. eauto. auto.\n  split. destruct (Val.cmpu_bool (Mem.valid_pointer m) c0 (rs x) (rs x0)) as []_eqn; auto.\n  eapply testcond_for_unsigned_comparison_correct; eauto. \n  intros. unfold compare_ints. repeat SOther.\n(* compimm *)\n  simpl. rewrite (ireg_of_eq _ _ EQ). destruct (Int.eq_dec i Int.zero).\n  econstructor; split. apply exec_straight_one. simpl; eauto. auto. \n  split. destruct (rs x); simpl; auto. subst. rewrite Int.and_idem.\n  eapply testcond_for_signed_comparison_correct; eauto. \n  intros. unfold compare_ints. repeat SOther.\n  econstructor; split. apply exec_straight_one. simpl; eauto. auto. \n  split. destruct (Val.cmp_bool c0 (rs x) (Vint i)) as []_eqn; auto.\n  eapply testcond_for_signed_comparison_correct; eauto. \n  intros. unfold compare_ints. repeat SOther.\n(* compuimm *)\n  simpl. rewrite (ireg_of_eq _ _ EQ).\n  econstructor. split. apply exec_straight_one. simpl. eauto. auto.\n  split. destruct (Val.cmpu_bool (Mem.valid_pointer m) c0 (rs x) (Vint i)) as []_eqn; auto.\n  eapply testcond_for_unsigned_comparison_correct; eauto. \n  intros. unfold compare_ints. repeat SOther.\n(* compf *)\n  simpl. rewrite (freg_of_eq _ _ EQ). rewrite (freg_of_eq _ _ EQ1).\n  exists (nextinstr (compare_floats (swap_floats c0 (rs x) (rs x0)) (swap_floats c0 (rs x0) (rs x)) rs)).\n  split. apply exec_straight_one. \n  destruct c0; simpl; auto.\n  unfold nextinstr. rewrite Pregmap.gss. rewrite compare_floats_inv; auto with ppcgen. \n  split. destruct (rs x); destruct (rs x0); simpl; auto.\n  repeat rewrite swap_floats_commut. apply testcond_for_float_comparison_correct.\n  intros. SOther. apply compare_floats_inv; auto with ppcgen. \n(* notcompf *)\n  simpl. rewrite (freg_of_eq _ _ EQ). rewrite (freg_of_eq _ _ EQ1).\n  exists (nextinstr (compare_floats (swap_floats c0 (rs x) (rs x0)) (swap_floats c0 (rs x0) (rs x)) rs)).\n  split. apply exec_straight_one. \n  destruct c0; simpl; auto.\n  unfold nextinstr. rewrite Pregmap.gss. rewrite compare_floats_inv; auto with ppcgen. \n  split. destruct (rs x); destruct (rs x0); simpl; auto.\n  repeat rewrite swap_floats_commut. apply testcond_for_neg_float_comparison_correct.\n  intros. SOther. apply compare_floats_inv; auto with ppcgen. \n(* maskzero *)\n  simpl. rewrite (ireg_of_eq _ _ EQ).\n  econstructor. split. apply exec_straight_one. simpl; eauto. auto.\n  split. destruct (rs x); simpl; auto. \n  generalize (compare_ints_spec rs (Vint (Int.and i0 i)) Vzero m).\n  intros [A B]. rewrite A. unfold Val.cmpu; simpl. destruct (Int.eq (Int.and i0 i) Int.zero); auto.\n  intros. unfold compare_ints. repeat SOther.\n(* masknotzero *)\n  simpl. rewrite (ireg_of_eq _ _ EQ).\n  econstructor. split. apply exec_straight_one. simpl; eauto. auto.\n  split. destruct (rs x); simpl; auto. \n  generalize (compare_ints_spec rs (Vint (Int.and i0 i)) Vzero m).\n  intros [A B]. rewrite A. unfold Val.cmpu; simpl. destruct (Int.eq (Int.and i0 i) Int.zero); auto.\n  intros. unfold compare_ints. repeat SOther.\nQed.\n\nRemark eval_testcond_nextinstr:\n  forall c rs, eval_testcond c (nextinstr rs) = eval_testcond c rs.\nProof.\n  intros. unfold eval_testcond. repeat rewrite nextinstr_inv; auto with ppcgen.\nQed.\n\nRemark eval_testcond_set_ireg:\n  forall c rs r v, eval_testcond c (rs#(IR r) <- v) = eval_testcond c rs.\nProof.\n  intros. unfold eval_testcond. repeat rewrite Pregmap.gso; auto with ppcgen.\nQed.\n\nLemma mk_setcc_correct:\n  forall cond rd k rs1 m,\n  exists rs2,\n  exec_straight (mk_setcc cond rd k) rs1 m k rs2 m\n  /\\ rs2#rd = Val.of_optbool(eval_extcond cond rs1)\n  /\\ forall r, nontemp_preg r = true -> r <> rd -> rs2#r = rs1#r.\nProof.\n  intros. destruct cond; simpl in *.\n(* base *)\n  econstructor; split.\n  apply exec_straight_one. simpl; eauto. auto. \n  split. SRes. SRes. \n  intros; repeat SOther.\n(* or *)\n  assert (Val.of_optbool\n    match eval_testcond c1 rs1 with\n    | Some b1 =>\n        match eval_testcond c2 rs1 with\n        | Some b2 => Some (b1 || b2)\n        | None => None\n        end\n    | None => None\n    end =\n    Val.or (Val.of_optbool (eval_testcond c1 rs1)) (Val.of_optbool (eval_testcond c2 rs1))).\n  destruct (eval_testcond c1 rs1). destruct (eval_testcond c2 rs1). \n  destruct b; destruct b0; auto.\n  destruct b; auto.\n  auto.\n  rewrite H; clear H.\n  destruct (ireg_eq rd EDX).\n  subst rd. econstructor; split.\n  eapply exec_straight_three.\n  simpl; eauto.\n  simpl. rewrite eval_testcond_nextinstr. repeat rewrite eval_testcond_set_ireg. eauto.\n  simpl; eauto.\n  auto. auto. auto.\n  split. SRes. \n  intros. repeat SOther.\n  econstructor; split.\n  eapply exec_straight_three.\n  simpl; eauto.\n  simpl. rewrite eval_testcond_nextinstr. repeat rewrite eval_testcond_set_ireg. eauto. \n  simpl. eauto. \n  auto. auto. auto.\n  split. repeat SRes. rewrite Val.or_commut. decEq; repeat SRes. \n  intros. repeat SOther.\n(* and *)\n  assert (Val.of_optbool\n    match eval_testcond c1 rs1 with\n    | Some b1 =>\n        match eval_testcond c2 rs1 with\n        | Some b2 => Some (b1 && b2)\n        | None => None\n        end\n    | None => None\n    end =\n    Val.and (Val.of_optbool (eval_testcond c1 rs1)) (Val.of_optbool (eval_testcond c2 rs1))).\n  destruct (eval_testcond c1 rs1). destruct (eval_testcond c2 rs1). \n  destruct b; destruct b0; auto.\n  destruct b; auto.\n  auto.\n  rewrite H; clear H.\n  destruct (ireg_eq rd EDX).\n  subst rd. econstructor; split.\n  eapply exec_straight_three.\n  simpl; eauto.\n  simpl. rewrite eval_testcond_nextinstr. repeat rewrite eval_testcond_set_ireg. eauto.\n  simpl; eauto.\n  auto. auto. auto.\n  split. SRes. \n  intros. repeat SOther.\n  econstructor; split.\n  eapply exec_straight_three.\n  simpl; eauto.\n  simpl. rewrite eval_testcond_nextinstr. repeat rewrite eval_testcond_set_ireg. eauto. \n  simpl. eauto. \n  auto. auto. auto.\n  split. repeat SRes. rewrite Val.and_commut. decEq; repeat SRes. \n  intros. repeat SOther.\nQed.\n\n(** Translation of arithmetic operations. *)\n\nLtac ArgsInv :=\n  match goal with\n  | [ H: Error _ = OK _ |- _ ] => discriminate\n  | [ H: match ?args with nil => _ | _ :: _ => _ end = OK _ |- _ ] => destruct args; ArgsInv\n  | [ H: bind _ _ = OK _ |- _ ] => monadInv H; ArgsInv\n  | [ H: assertion _ = OK _ |- _ ] => monadInv H; subst; ArgsInv\n  | [ H: ireg_of _ = OK _ |- _ ] => simpl in *; rewrite (ireg_of_eq _ _ H) in *; clear H; ArgsInv\n  | [ H: freg_of _ = OK _ |- _ ] => simpl in *; rewrite (freg_of_eq _ _ H) in *; clear H; ArgsInv\n  | _ => idtac\n  end.\n\nLtac TranslOp :=\n  econstructor; split;\n  [ apply exec_straight_one; [ simpl; eauto | auto ] \n  | split; [ repeat SRes | intros; repeat SOther ]].\n\n\nLemma transl_op_correct:\n  forall op args res k c (rs: regset) m v,\n  transl_op op args res k = OK c ->\n  eval_operation ge (rs#ESP) op (map rs (map preg_of args)) m = Some v ->\n  exists rs',\n     exec_straight c rs m k rs' m\n  /\\ Val.lessdef v rs'#(preg_of res)\n  /\\ forall r, \n     match op with Omove => important_preg r = true /\\ r <> ST0 | _ => nontemp_preg r = true end ->\n     r <> preg_of res -> rs' r = rs r.\nProof.\n  intros until v; intros TR EV.\n  assert (SAME:\n  (exists rs',\n     exec_straight c rs m k rs' m\n  /\\ rs'#(preg_of res) = v\n  /\\ forall r, \n     match op with Omove => important_preg r = true /\\ r <> ST0 | _ => nontemp_preg r = true end ->\n     r <> preg_of res -> rs' r = rs r) ->\n  exists rs',\n     exec_straight c rs m k rs' m\n  /\\ Val.lessdef v rs'#(preg_of res)\n  /\\ forall r, \n     match op with Omove => important_preg r = true /\\ r <> ST0 | _ => nontemp_preg r = true end ->\n     r <> preg_of res -> rs' r = rs r).\n  intros [rs' [A [B C]]]. subst v. exists rs'; auto. \n\n  destruct op; simpl in TR; ArgsInv; simpl in EV; try (inv EV); try (apply SAME; TranslOp; fail).\n(* move *)\n  exploit mk_mov_correct; eauto. intros [rs2 [A [B C]]]. \n  apply SAME. exists rs2. split. eauto. split. simpl. auto. intros. destruct H; auto.\n(* intconst *)\n  apply SAME. destruct (Int.eq_dec i Int.zero). subst i. TranslOp. TranslOp.\n(* floatconst *)\n  apply SAME. destruct (Float.eq_dec f Float.zero). subst f. TranslOp. TranslOp.\n(* cast8signed *)\n  apply SAME. eapply mk_intconv_correct; eauto.\n(* cast8unsigned *)\n  apply SAME. eapply mk_intconv_correct; eauto. \n(* cast16signed *)\n  apply SAME. eapply mk_intconv_correct; eauto.\n(* cast16unsigned *)\n  apply SAME. eapply mk_intconv_correct; eauto.\n(* div *)\n  apply SAME.\n  specialize (divs_mods_exist (rs x0) (rs x1)). rewrite H0. \n  destruct (Val.mods (rs x0) (rs x1)) as [vr|]_eqn; intros; try contradiction.\n  eapply mk_div_correct with (dsem := Val.divs) (msem := Val.mods); eauto.\n(* divu *)\n  apply SAME.\n  specialize (divu_modu_exist (rs x0) (rs x1)). rewrite H0. \n  destruct (Val.modu (rs x0) (rs x1)) as [vr|]_eqn; intros; try contradiction.\n  eapply mk_div_correct with (dsem := Val.divu) (msem := Val.modu); eauto.\n(* mod *)\n  apply SAME.\n  specialize (divs_mods_exist (rs x0) (rs x1)). rewrite H0. \n  destruct (Val.divs (rs x0) (rs x1)) as [vq|]_eqn; intros; try contradiction.\n  eapply mk_mod_correct with (dsem := Val.divs) (msem := Val.mods); eauto.\n(* modu *)\n  apply SAME.\n  specialize (divu_modu_exist (rs x0) (rs x1)). rewrite H0. \n  destruct (Val.divu (rs x0) (rs x1)) as [vq|]_eqn; intros; try contradiction.\n  eapply mk_mod_correct with (dsem := Val.divu) (msem := Val.modu); eauto.\n(* shl *)\n  apply SAME. eapply mk_shift_correct; eauto. \n(* shr *)\n  apply SAME. eapply mk_shift_correct; eauto. \n(* shrximm *)\n  apply SAME. eapply mk_shrximm_correct; eauto.\n(* shru *)\n  apply SAME. eapply mk_shift_correct; eauto.\n(* lea *)\n  exploit transl_addressing_mode_correct; eauto. intros EA.\n  TranslOp. rewrite nextinstr_inv; auto with ppcgen. rewrite Pregmap.gss; auto.\n(* intoffloat *)\n  apply SAME. TranslOp. rewrite H0; auto.\n(* floatofint *)\n  apply SAME. TranslOp. rewrite H0; auto.\n(* condition *)\n  exploit transl_cond_correct; eauto. intros [rs2 [P [Q R]]].\n  exploit mk_setcc_correct; eauto. intros [rs3 [S [T U]]].\n  exists rs3.\n  split. eapply exec_straight_trans. eexact P. eexact S.\n  split. rewrite T. destruct (eval_condition c0 rs ## (preg_of ## args) m).\n  rewrite Q. auto.\n  simpl; auto.\n  intros. transitivity (rs2 r); auto.\nQed.\n\n(** Translation of memory loads. *)\n\nLemma transl_load_correct:\n  forall chunk addr args dest k c (rs: regset) m a v,\n  transl_load chunk addr args dest k = OK c ->\n  eval_addressing ge (rs#ESP) addr (map rs (map preg_of args)) = Some a ->\n  Mem.loadv chunk m a = Some v ->\n  exists rs',\n     exec_straight c rs m k rs' m\n  /\\ rs'#(preg_of dest) = v\n  /\\ forall r, nontemp_preg r = true -> r <> preg_of dest -> rs'#r = rs#r.\nProof.\n  unfold transl_load; intros. monadInv H. \n  exploit transl_addressing_mode_correct; eauto. intro EA.\n  assert (EA': eval_addrmode ge x rs = a). destruct a; simpl in H1; try discriminate; inv EA; auto.\n  set (rs2 := nextinstr_nf (rs#(preg_of dest) <- v)).\n  assert (exec_load ge chunk m x rs (preg_of dest) = Next rs2 m).\n    unfold exec_load. rewrite EA'. rewrite H1. auto.\n  assert (rs2 PC = Val.add (rs PC) Vone).\n    transitivity (Val.add ((rs#(preg_of dest) <- v) PC) Vone).\n    auto. decEq. apply Pregmap.gso; auto with ppcgen.\n  exists rs2. split. \n  destruct chunk; ArgsInv; apply exec_straight_one; auto.\n  (* Mfloat64 -> Mfloat64al32 *)\n  rewrite <- H. simpl. unfold exec_load. rewrite H1.\n  destruct (eval_addrmode ge x rs); simpl in *; try discriminate.\n  erewrite Mem.load_float64al32; eauto. \n  split. unfold rs2. rewrite nextinstr_nf_inv1. SRes. apply preg_of_important.\n  intros. unfold rs2. repeat SOther. \nQed.\n\nLemma transl_store_correct:\n  forall chunk addr args src k c (rs: regset) m a m',\n  transl_store chunk addr args src k = OK c ->\n  eval_addressing ge (rs#ESP) addr (map rs (map preg_of args)) = Some a ->\n  Mem.storev chunk m a (rs (preg_of src)) = Some m' ->\n  exists rs',\n     exec_straight c rs m k rs' m'\n  /\\ forall r, nontemp_preg r = true -> rs'#r = rs#r.\nProof.\n  unfold transl_store; intros. monadInv H. \n  exploit transl_addressing_mode_correct; eauto. intro EA.\n  assert (EA': eval_addrmode ge x rs = a). destruct a; simpl in H1; try discriminate; inv EA; auto.\n  rewrite <- EA' in H1. destruct chunk; ArgsInv.\n(* int8signed *)\n  eapply mk_smallstore_correct; eauto.\n  intros. simpl. unfold exec_store.\n  destruct (eval_addrmode ge addr0 rs0); simpl; auto. rewrite Mem.store_signed_unsigned_8; auto.\n(* int8unsigned *)\n  eapply mk_smallstore_correct; eauto.\n(* int16signed *)\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_store. \n  replace (Mem.storev Mint16unsigned m (eval_addrmode ge x rs) (rs x0))\n     with (Mem.storev Mint16signed m (eval_addrmode ge x rs) (rs x0)).\n  rewrite H1. eauto.\n  destruct (eval_addrmode ge x rs); simpl; auto. rewrite Mem.store_signed_unsigned_16; auto.\n  auto.\n  intros. SOther.\n(* int16unsigned *)\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_store. rewrite H1. eauto. auto.\n  intros. SOther.\n(* int32 *)\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_store. rewrite H1. eauto. auto.\n  intros. SOther.\n(* float32 *)\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_store. rewrite H1. eauto. auto.\n  intros. SOther.\n(* float64 *)\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_store. erewrite Mem.storev_float64al32; eauto. auto.\n  intros. SOther.\n(* float64al32 *)\n  econstructor; split.\n  apply exec_straight_one. simpl. unfold exec_store. rewrite H1. eauto. auto.\n  intros. SOther.\nQed.\n\nEnd STRAIGHTLINE.\n\n", "meta": {"author": "Ptival", "repo": "compcert-alias", "sha": "c839efb9cd2a4c27add46a1868fe0444d1dfdd9e", "save_path": "github-repos/coq/Ptival-compcert-alias", "path": "github-repos/coq/Ptival-compcert-alias/compcert-alias-c839efb9cd2a4c27add46a1868fe0444d1dfdd9e/ia32/Asmgenproof1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23017174404733065}}
{"text": "(** * Port map evaluation relation. *)\n\n(** Defines the relation that evaluates input and output port maps.\n\n    The evaluation of an input port map association (resp. output port\n    map association) modifies the state of the design instance (resp. the\n    embedding design). *)\n\nRequire Import common.CoqLib.\nRequire Import common.GlobalTypes.\nRequire Import common.NatSet.\nRequire Import common.NatMap.\n\nRequire Import hvhdl.SemanticalDomains.\nRequire Import hvhdl.Environment.\nRequire Import hvhdl.AbstractSyntax.\nRequire Import hvhdl.ExpressionEvaluation.\nRequire Import hvhdl.HVhdlTypes.\n\n(** Defines the evaluation relation for input port maps.\n    \n    The evaluation of an input port map possibly modifies the value of\n    the input ports in the signal store [sst__c]. *)\n\nInductive MIP (Δ Δ__c : ElDesign) (sst sst__c : IdMap value) : list ipassoc -> IdMap value -> Prop := \n\n(** An empty list of port associations does not change the state\n    [sst__c] of the component instance. *)\n| MIPNil : MIP Δ Δ__c sst sst__c [] sst__c \n\n(** Evaluates a non-empty list of port associations. *)\n| MIPCons :\n    forall ipa lofipas sst__c' sst__c'',\n      VIPAssoc Δ Δ__c sst sst__c ipa sst__c' ->\n      MIP Δ Δ__c sst sst__c' lofipas sst__c'' ->\n      MIP Δ Δ__c sst sst__c (ipa :: lofipas) sst__c''\n\n(** Defines the relation that evaluates a single association present\n    in an input port map.  *)\nwith VIPAssoc (Δ Δ__c : ElDesign) (sst sst__c : IdMap value) : ipassoc -> IdMap value -> Prop := \n\n(** Evaluates a input port map association, with a simple port\n    identifier in the formal part. *)\n  \n| VIPAssocSimple :\n    forall id e v t,\n      \n      (* * Premises * *)\n      VExpr Δ sst EmptyLEnv false e v ->\n      IsOfType v t ->\n\n      (* * Side conditions (where sstc = <S,C,E>) * *)\n      NatMap.MapsTo id (Input t) Δ__c -> (* id ∈ Ins(Δc) and Δc(id) = t *)\n\n      (* * Conclusion * *)\n      VIPAssoc Δ Δ__c sst sst__c (ipa_ ($id) e) (add id v sst__c)\n\n(** Evaluates a input port map association, with an indexed port\n    identifier in the formal part.  *)\n  \n| VIPAssocPartial :\n    forall id e ei v n__i t l u aofv idx_in_bounds,\n      \n      (* * Premises * *)\n      VExpr Δ sst EmptyLEnv false e v ->\n      IsOfType v t ->\n      VExpr EmptyElDesign EmptySStore EmptyLEnv false ei (Vnat n__i) ->\n      IsOfType (Vnat n__i) (Tnat l u) ->\n        \n      (* * Side conditions * *)\n      NatMap.MapsTo id (Input (Tarray t l u)) Δ__c -> (* id ∈ Ins(Δc) and Δc(id) = array(t,l,u) *)\n      NatMap.MapsTo id (Varr aofv) sst__c -> (* [id ∈ sst__c] and [sst__c(id) = aofv] *)\n      let i := (N.to_nat (n__i - l)) in\n      \n      (* * Conclusion * *)\n      VIPAssoc Δ Δ__c sst sst__c (ipa_ (id $[[ei]]) e) (add id (Varr (set_at v i aofv idx_in_bounds)) sst__c).\n    \n(** Defines the evaluation relation for output port maps.\n    \n    The evaluation of an output port map modifies the signal store\n    [sst] of the embedding design. *)\n\nInductive MOP (Δ Δ__c : ElDesign) (sst sst__c : IdMap value) : list opassoc -> IdMap value -> Prop :=\n\n(** An empty list of port associations does not change the state\n    [sst] of the embedding design. *)\n  \n| MapopNil : MOP Δ Δ__c sst sst__c [] sst \n\n(** Evaluates a non-empty list of port associations. *)\n| MapopCons :\n    forall {opa lofopas sst' sst''},\n      VOPAssoc Δ Δ__c sst sst__c opa sst' ->\n      MOP Δ Δ__c sst' sst__c lofopas sst'' ->\n      MOP Δ Δ__c sst sst__c (opa :: lofopas) sst''\n\n(** Defines the relation that evaluates an output port map\n    association.  *)\nwith VOPAssoc (Δ Δ__c : ElDesign) (sst sst__c : IdMap value) : opassoc -> IdMap value -> Prop :=\n\n(** Evaluates an association where the formal part is not bound, i.e\n    the actual part is [None] (the \"open\" keyword is used in concrete\n    VHDL syntax) *)\n| VOPAssocOpen : forall id__f, VOPAssoc Δ Δ__c sst sst__c (opa_simpl id__f None) sst\n\n(** Evaluates an output port map association where the actual part is\n    a simple declared signal or output port identifier.\n    \n    Case when the formal part is a simple identifier. *)\n\n| VOPAssocSimpleToSimple :\n    forall id__f id__a v t,\n      \n      (* * Premises * *)\n      VExpr Δ__c sst__c EmptyLEnv true (#id__f) v ->\n      IsOfType v t ->\n      \n      (* * Side conditions * *)\n\n      (* [id__a ∈ S(Δ) ∪ O(Δ) and Δ(id__a) = t] *)\n      (MapsTo id__a (Internal t) Δ \\/ MapsTo id__a (Output t) Δ) -> \n      \n      (* * Conclusion * *)\n      VOPAssoc Δ Δ__c sst sst__c (opa_simpl id__f (Some ($id__a))) (add id__a v sst)\n\n(** Evaluates an output port map association where the actual part is\n    a simple declared signal or output port identifier.\n    \n    Case when the formal part is an indexed identifier. *)\n\n| VOPAssocIdxToSimple :\n  forall id__f e__i id__a v t,\n    \n    (* * Premises * *)\n    VExpr Δ__c sst__c EmptyLEnv true (id__f [[e__i]]) v ->\n    IsOfType v t ->\n    \n    (* * Side conditions * *)\n\n    (* [id__a ∈ S(Δ) ∪ O(Δ) and Δ(id__a) = t] *)\n    (MapsTo id__a (Internal t) Δ \\/ MapsTo id__a (Output t) Δ) -> \n    \n    (* * Conclusion * *)\n    VOPAssoc Δ Δ__c sst sst__c (opa_idx id__f e__i ($id__a)) (add id__a v sst)\n               \n(** Evaluates an \"out\" port map association, with an indexed declared\n    signal or port identifier in the actual part.\n    \n    Case when the formal part is a simple identifier.  *)\n  \n| VOPAssocSimpleToPartial :\n    forall id__f id__a ei v n__i t l u aofv idx_in_bounds,\n      \n      (* * Premises * *)\n      VExpr Δ__c sst__c EmptyLEnv true (#id__f) v ->\n      IsOfType v t ->\n      VExpr EmptyElDesign EmptySStore EmptyLEnv false ei (Vnat n__i) ->\n      IsOfType (Vnat n__i) (Tnat l u) ->\n      \n      (* * Side conditions * *)\n      \n      (* [id__a ∈ Sigs(Δ) ∪ Outs(Δ) and Δ(id__a) = array(t,l,u)] *)\n      (MapsTo id__a (Internal (Tarray t l u)) Δ \\/ MapsTo id__a (Output (Tarray t l u)) Δ) -> \n      MapsTo id__a (Varr aofv) sst -> (* [id__a ∈ sst and sst(id__a) = aofv] *)\n      let i := (N.to_nat (n__i - l)) in\n      let aofv' := set_at v i aofv idx_in_bounds in\n      \n      (* * Conclusion * *)\n      VOPAssoc Δ Δ__c sst sst__c (opa_simpl id__f (Some (id__a $[[ei]]))) (add id__a (Varr aofv') sst)\n\n(** Evaluates an \"out\" port map association, with an indexed declared\n    signal or port identifier in the actual part.\n    \n    Case when the formal part is an indexed identifier.  *)\n  \n| VOPAssocIdxToPartial :\n  forall id__f e__i' id__a ei v n__i t l u aofv idx_in_bounds,\n    \n    (* * Premises * *)\n    VExpr Δ__c sst__c EmptyLEnv true (id__f [[e__i']]) v ->\n    IsOfType v t ->\n    VExpr EmptyElDesign EmptySStore EmptyLEnv false ei (Vnat n__i) ->\n    IsOfType (Vnat n__i) (Tnat l u) ->\n    \n    (* * Side conditions * *)\n    \n    (* [id__a ∈ Sigs(Δ) ∪ Outs(Δ) and Δ(id__a) = array(t,l,u)] *)\n    (MapsTo id__a (Internal (Tarray t l u)) Δ \\/ MapsTo id__a (Output (Tarray t l u)) Δ) -> \n    MapsTo id__a (Varr aofv) sst -> (* [id__a ∈ sst and sst(id__a) = aofv] *)\n    let i := (N.to_nat (n__i - l)) in\n    let aofv' := set_at v i aofv idx_in_bounds in\n    \n    (* * Conclusion * *)\n    VOPAssoc Δ Δ__c sst sst__c (opa_idx id__f e__i' (id__a $[[ei]])) (add id__a (Varr aofv') sst).\n\n               \n\n", "meta": {"author": "viampietro", "repo": "ver-hilecop", "sha": "cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4", "save_path": "github-repos/coq/viampietro-ver-hilecop", "path": "github-repos/coq/viampietro-ver-hilecop/ver-hilecop-cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4/hvhdl/PortMapEvaluation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23017117030618783}}
{"text": "(** Defines the relation that elaborates the generic clause of a\n    design, as declared in abstract syntax.\n    \n    The result is the addition of entries refering to generic constant\n    declarations in the design environment.  *)\n\nRequire Import common.CoqLib.\nRequire Import common.GlobalTypes.\n\nRequire Import hvhdl.AbstractSyntax.\nRequire Import hvhdl.SemanticalDomains.\nRequire Import hvhdl.Environment.\nRequire Import hvhdl.ExpressionEvaluation.\nRequire Import hvhdl.StaticExpressions.\nRequire Import hvhdl.TypeElaboration.\nRequire Import hvhdl.HVhdlTypes.\n\nImport NatMap.\n\n(** The generic constant elaboration relation.\n    \n    The [M__g] parameter is the dimensioning function; that is, the\n    function yielding the values assigned to the generic constants\n    being elaborated.  *)\n\nInductive EGens (Δ : ElDesign) (M__g : IdMap value) : list gdecl -> ElDesign -> Prop :=\n\n(** Elaborates an empty list of generic constant declaration. *)\n| EGensNil: EGens Δ M__g [] Δ\n\n(** Elaborates a non-empty list of generic constant declaration. *)\n| EGensCons:\n    forall gd lofgdecls Δ' Δ'',\n      EGen Δ M__g gd Δ' ->\n      EGens Δ' M__g lofgdecls Δ'' ->\n      EGens Δ M__g (gd :: lofgdecls) Δ''\n    \n(** Defines the elaboration relation for one generic constant declaration. *)\nwith EGen (Δ : ElDesign) (M__g : IdMap value) : gdecl -> ElDesign -> Prop :=\n  \n(* Elaboration with given a dimensioning value. *)\n| EGenM__G :\n    forall idg τ e t dv v,\n      \n      (* Premises *)\n      ETypeg τ t ->\n      IsLStaticExpr e ->\n      VExpr EmptyElDesign EmptySStore EmptyLEnv false e dv ->\n      IsOfType dv t ->\n      IsOfType v t ->\n      \n      (* Side conditions *)\n      ~NatMap.In idg Δ -> (* idg ∉ Δ *)\n      MapsTo idg v M__g ->  (* idg ∈ M and M(idg) = v *)\n      \n      (* Conclusion *)\n      EGen Δ M__g (gdecl_ idg τ e) (MkElDesign (add idg (Generic t v) Δ))\n\n(* Elaboration with default value. *)\n| EGenDefault :\n    forall idg τ e t dv,\n      \n      (* Premises *)\n      ETypeg τ t ->\n      IsLStaticExpr e ->\n      VExpr EmptyElDesign EmptySStore EmptyLEnv false e dv ->\n      IsOfType dv t ->\n\n      (* Side conditions *)\n      ~NatMap.In idg Δ ->      (* idg ∉ Δ *)\n      ~NatMap.In idg M__g ->     (* idg ∉ M *)\n      \n      (* Conclusion *)\n      EGen Δ M__g (gdecl_ idg τ e) (MkElDesign (add idg (Generic t dv) Δ)).\n\n      \n\n", "meta": {"author": "viampietro", "repo": "ver-hilecop", "sha": "cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4", "save_path": "github-repos/coq/viampietro-ver-hilecop", "path": "github-repos/coq/viampietro-ver-hilecop/ver-hilecop-cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4/hvhdl/GenericElaboration.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2301711703061878}}
{"text": "(* This code is copyrighted by its authors; it is distributed under  *)\n(* the terms of the LGPL license (see LICENSE and description files) *)\n\n(****************************************************************************)\n(*                                                                          *)\n(*                                                                          *)\n(*                Solange Coupet-Grimal & Line Jakubiec-Jamet               *)\n(*                                                                          *)\n(*                                                                          *)\n(*             Laboratoire d'Informatique Fondamentale de Marseille         *)\n(*                   CMI et Faculté des Sciences de Luminy                  *)\n(*                                                                          *)\n(*           e-mail:{Solange.Coupet,Line.Jakubiec}@lif.univ-mrs.fr          *)\n(*                                                                          *)\n(*                                                                          *)\n(*                            Developped in Coq v6                          *)\n(*                            Ported to Coq v7                              *)\n(*                            Translated to Coq v8                          *)\n(*                                                                          *)\n(*                             July 12nd 2005                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                              Timing_Proof.v                              *)\n(****************************************************************************)\n\n\nRequire Export Arbitration.\nRequire Export Bool_Compl.\nRequire Export Moore_Mealy.\n\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n\nSection Timing_Correctness.\n\n  Let Input_type := (bool * d_list bool 4)%type.\n\n  Let Output_type := bool.\n\n\n(** The automaton describing the behaviour of TIMING has 3 states **)\n\n  Inductive label_t : Set :=\n    | START_t : label_t\n    | WAIT_t : label_t\n    | ROUTE_t : label_t. \n\n\n\n(** Automaton describing the transitions from a state to another **)\n\n  Definition Trans_Timing (i : Input_type) (s : label_t) : label_t :=\n    let (fs, act) := i in\n    match s with\n    | START_t => match fs with\n                 | true => WAIT_t\n                 | false => START_t\n                 end\n    | WAIT_t =>\n        match Ackor act with\n        | true => match fs with\n                  | true => WAIT_t\n                  | false => ROUTE_t\n                  end\n        | false => WAIT_t\n        end\n    | ROUTE_t => match fs with\n                 | true => WAIT_t\n                 | false => START_t\n                 end\n    end.\n\n\n(** Each label_t corresponds to a result **)\n\n  Definition Out_Timing (s : label_t) : Output_type :=\n    match s with\n    | START_t => false\n    | WAIT_t => false\n    | ROUTE_t => true\n    end.\n\n\n\n(** States stream **)\n\n  Definition States_TIMING := States_Mealy Trans_Timing.\n\n\n(** Intented behaviour **)\n\n  Definition Behaviour_TIMING := Moore Trans_Timing Out_Timing.\n\n\n\n(** Transformation of Behaviour_TIMING to a Mealy automaton **)\n\n  Definition Out_Timing_Mealy :=\n    Out_Mealy (Input_type:=Input_type) Out_Timing.\n\n  Lemma equiv_out_Timing :\n   forall (i : Input_type) (s : label_t), Out_Timing s = Out_Timing_Mealy i s.\n  Proof.\n  auto.\n  Qed.\n\n\n  Lemma Equiv_Timing_Moore_Mealy :\n   forall (s : label_t) (i : Stream Input_type),\n   EqS (Behaviour_TIMING i s) (Mealy Trans_Timing Out_Timing_Mealy i s).\n  Proof.\n  intros s i.\n  unfold Behaviour_TIMING in |- *; unfold Out_Timing_Mealy in |- *;\n   apply Equiv_Moore_Mealy.\n  Qed.\n\n\n\n(** Stream of states for Structure_TIMING **)\n\n  Definition States_Structure_TIMING := States_Mealy Timing_Aux.\n\n\n(** No invariant property *)\n\n  Let Reg_type := d_list bool 2. (* Type of the registers of TIMING *)\n\n  Let Cst_True (i : Input_type) (s : label_t) (b : Reg_type) := True.\n\n\n(** Output relation **)\n\n  Definition R_Timing (s : label_t) (l : Reg_type) :=\n    Fst_of_l2 l = Out_Timing s /\\\n    (s = START_t /\\ Scd_of_l2 l = false \\/\n     s = WAIT_t /\\ Scd_of_l2 l = true \\/ s = ROUTE_t /\\ Scd_of_l2 l = true).\n\n\n(** Proof : correctness of the TIMING UNIT **)\n\n\n  Lemma Cst_True_inv_t :\n   forall (i : Stream Input_type) (s : label_t) (l : Reg_type),\n   Inv Cst_True i (States_TIMING i s) (States_Structure_TIMING i l).\n\n  Proof.\n  cofix Cst_True_inv_t.\n  intros i s l.\n  apply Inv_Ok.\n  unfold Cst_True in |- *; auto.\n  Qed.\n\n\n\n (* Combinational proof *)\n\n  Lemma Invariant_relation_t :\n   Inv_under_P Trans_Timing Timing_Aux Cst_True R_Timing.\n\n  Proof.\n  unfold Inv_under_P in |- *; unfold R_Timing in |- *.\n  intros i s l H_True R; clear H_True; elim i; intros fs act.\n  elim R; clear R.\n  intros H1 H2.\n\n (* s=START_t /\\ (Scd_of_l2 l)=false *)\n  elim H2; clear H2; intros H2.\n  elim H2; clear H2; intros H2 H3.\n  unfold Timing_Aux in |- *; unfold Timing in |- *; simpl in |- *.\n  generalize H1; clear H1; rewrite H2; simpl in |- *.\n  intros H1; rewrite H1; rewrite H3; simpl in |- *.\n  case fs; simpl in |- *.\n  split; auto.\n  unfold AND4 in |- *; unfold AND2 in |- *; simpl in |- *.\n  elim andb_sym; simpl in |- *; auto.\n  split; auto.\n  unfold AND4 in |- *; unfold AND2 in |- *; simpl in |- *.\n  elim andb_sym; simpl in |- *; auto.\n\n (* s=WAIT_t /\\ (Scd_of_l2 l)=true *)\n  elim H2; clear H2; intros H2.\n  elim H2; clear H2; intros H2 H3.\n  unfold Timing_Aux in |- *; unfold Timing in |- *; simpl in |- *.\n  generalize H1; clear H1; rewrite H2; simpl in |- *.\n  intros H1; rewrite H1; rewrite H3; simpl in |- *.\n  case (Ackor act); simpl in |- *; auto.\n  case fs; simpl in |- *; auto.\n  split; auto.\n  right; left; auto.\n  split; auto.\n  unfold List2 in |- *; unfold Scd_of_l2 in |- *; simpl in |- *;\n   auto with bool.\n\n (* s=ROUTE_t /\\ (Scd_of_l2 l)=true *)\n  elim H2; clear H2; intros H2 H3.\n  unfold Timing_Aux in |- *; unfold Timing in |- *; simpl in |- *.\n  generalize H1; clear H1; rewrite H2; simpl in |- *.\n  intros H1; rewrite H1; rewrite H3; simpl in |- *.\n  case fs; simpl in |- *; auto.\n  split; auto.\n  unfold AND4 in |- *; unfold AND2 in |- *; simpl in |- *.\n  elim andb_sym; simpl in |- *; auto.\n  split; auto.\n  unfold AND4 in |- *; unfold AND2 in |- *; simpl in |- *.\n  elim andb_sym; simpl in |- *; auto.\n  Qed.\n\n\n (* R_Timing is an output relation *)\n\n  Lemma Output_relation_t :\n   Output_rel Out_Timing_Mealy Out_Struct_Timing R_Timing.\n\n  Proof.\n  unfold Output_rel in |- *; unfold R_Timing in |- *; intros i s l H.\n  elim H; clear H.\n  intros H1 H2.\n  elim H2; clear H2; intro H2.\n  elim H2; clear H2; intros H2 H3.\n  generalize H1; clear H1; unfold Fst_of_l2 in |- *; rewrite H2;\n   simpl in |- *; intro H; auto.\n  elim H2; clear H2; intros H2.\n  elim H2; clear H2; intros H2 H3.\n  generalize H1; clear H1; unfold Fst_of_l2 in |- *; rewrite H2;\n   simpl in |- *; intro H; auto.\n  elim H2; clear H2; intros H2 H3.\n  generalize H1; clear H1; unfold Fst_of_l2 in |- *; rewrite H2;\n   simpl in |- *; intro H; auto.\n  Qed.\n\n\n (* Temporal proof *)\n\n  Lemma Correct_TIMING :\n   forall (i : Stream Input_type) (l : Reg_type) (s : label_t),\n   R_Timing s l -> EqS (Behaviour_TIMING i s) (Structure_TIMING i l).\n\n  Proof.\n  intros i l s HR.\n  unfold Behaviour_TIMING in |- *; unfold Structure_TIMING in |- *.\n  apply\n   (Equiv_2_Mealy Invariant_relation_t Output_relation_t\n      (Cst_True_inv_t i s l) HR).\n\n  Qed.\n\n\nEnd Timing_Correctness.\n", "meta": {"author": "coq-contribs", "repo": "fairisle", "sha": "e36087a6b7e52ef3c6dcfdeba1298e8fde1260a0", "save_path": "github-repos/coq/coq-contribs-fairisle", "path": "github-repos/coq/coq-contribs-fairisle/fairisle-e36087a6b7e52ef3c6dcfdeba1298e8fde1260a0/Fairisle/PROOFS/Timing_Proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2301711703061878}}
{"text": "(****************************************************************************)\n(* Copyright 2020 The Project Oak Authors                                   *)\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\nRequire Import Cava.Cava.\nRequire Import Cava.Lib.Vec.\nRequire Import AesSpec.StateTypeConversions.\nRequire Import AesSpec.Tests.CipherTest.\nRequire Import AesSpec.Tests.Common.\nLocal Open Scope vector_scope.\n\nModule Notations.\n  Notation state := (Vec (Vec (Vec Bit 8) 4) 4) (only parsing).\n  Notation key := (Vec (Vec (Vec Bit 8) 4) 4) (only parsing).\n  Notation keypair := (Vec (Vec (Vec (Vec Bit 8) 4) 4) 2) (only parsing).\nEnd Notations.\n\n(* A function to convert a matrix of nat values to a value of type state *)\nDefinition fromNatState (i : Vector.t (Vector.t nat 4) 4 ): Vector.t (Vector.t Byte.byte 4) 4\n  := Vector.map (Vector.map (fun v => bitvec_to_byte (N2Bv_sized 8 (N.of_nat v)))) i.\n\n(* A function to convert a state value to a matrix of nat values. *)\nDefinition toNatState (i: Vector.t (Vector.t Byte.byte 4) 4) : Vector.t (Vector.t nat 4) 4\n  := Vector.map (Vector.map (fun v => N.to_nat (Bv2N (byte_to_bitvec v)))) i.\n\n(* A function to convert a matrix of nat values to a matrix of bitvecs *)\nDefinition fromNatVec (i : Vector.t (Vector.t nat 4) 4 ): Vector.t (Vector.t (Vector.t bool 8) 4) 4\n  := Vector.map (Vector.map (fun v => N2Bv_sized 8 (N.of_nat v))) i.\n\n(* A function to convert a bitvec matrix to a nat matrix. *)\nDefinition toNatVec (i: Vector.t (Vector.t (Vector.t bool 8) 4) 4) : Vector.t (Vector.t nat 4) 4\n  := Vector.map (Vector.map (fun v => N.to_nat (Bv2N v))) i.\n\nLocal Notation byte := (Vec Bit 8) (only parsing).\nLocal Notation \"v [@ n ]\" := (indexConst v n) (at level 1, format \"v [@ n ]\").\n\nSection WithCava.\n  Context {signal} {semantics : Cava signal}.\n\n  Definition bitvec_to_signal {n : nat} (lut : Vector.t bool n) : signal (Vec Bit n) :=\n    Vec.bitvec_literal lut.\n\n  Definition bitvecvec_to_signal {a b : nat} (lut : Vector.t (Vector.t bool b) a)\n    : cava (signal (Vec (Vec Bit b) a)) :=\n    packV (Vector.map bitvec_to_signal lut).\n\n  Definition natvec_to_signal_sized {n : nat} (size : nat) (lut : Vector.t nat n)\n    : cava (signal (Vec (Vec Bit size) n)) :=\n    bitvecvec_to_signal (Vector.map (nat_to_bitvec_sized size) lut).\n\n  Definition aes_transpose {n m}\n      (matrix : signal (Vec (Vec byte n) m))\n    : cava (signal (Vec (Vec byte m) n)) :=\n    Vec.transpose matrix.\n\n  Definition aes_mul2\n    (x : signal byte)\n    : cava (signal byte) :=\n\n    x0 <- x[@0] ;;\n    x1 <- x[@1] ;;\n    x2 <- x[@2] ;;\n    x3 <- x[@3] ;;\n    x4 <- x[@4] ;;\n    x5 <- x[@5] ;;\n    x6 <- x[@6] ;;\n    x7 <- x[@7] ;;\n\n    a <- xor2 (x0, x7) ;;\n    b <- xor2 (x2, x7) ;;\n    c <- xor2 (x3, x7) ;;\n\n    packV\n      [x7;\n      a;\n      x1;\n      b;\n      c;\n      x4;\n      x5;\n      x6\n      ].\n\n  Definition aes_mul4\n    : signal byte -> cava (signal byte) :=\n    aes_mul2 >=> aes_mul2.\n\n  Definition zero_byte : cava (signal byte) := Vec.const zero 8.\n\n  (* function automatic logic [31:0] aes_circ_byte_shift(logic [31:0] in, logic [1:0] shift);\n    logic [31:0] out;\n    logic [31:0] s;\n    s = {30'b0,shift};\n    out = {in[8*((7-s)%4) +: 8], in[8*((6-s)%4) +: 8],\n           in[8*((5-s)%4) +: 8], in[8*((4-s)%4) +: 8]};\n    return out;\n  endfunction *)\n  Definition aes_circ_byte_shift (shift: nat) (input: signal (Vec byte 4)):\n    cava (signal (Vec byte 4)) :=\n    let indices := [4 - shift; 5 - shift; 6 - shift; 7 - shift] in\n    let indices := Vector.map (fun x => Nat.modulo x 4) indices in\n    Vec.map_literal (indexConst input) indices.\n\n  Definition IDLE_S := bitvec_to_signal (nat_to_bitvec_sized 3 0).\n  Definition INIT_S := bitvec_to_signal (nat_to_bitvec_sized 3 1).\n  Definition ROUND_S := bitvec_to_signal (nat_to_bitvec_sized 3 2).\n  Definition FINISH_S := bitvec_to_signal (nat_to_bitvec_sized 3 3).\n  Definition CLEAR_S_S := bitvec_to_signal (nat_to_bitvec_sized 3 4).\n  Definition CLEAR_KD_S := bitvec_to_signal (nat_to_bitvec_sized 3 5).\n\n  Definition STATE_INIT := bitvec_to_signal (nat_to_bitvec_sized 2 0).\n  Definition STATE_ROUND := bitvec_to_signal (nat_to_bitvec_sized 2 1).\n  Definition STATE_CLEAR := bitvec_to_signal (nat_to_bitvec_sized 2 2).\n\n  Definition KEY_FULL_ENC_INIT := bitvec_to_signal (nat_to_bitvec_sized 2 0).\n  Definition KEY_FULL_DEC_INIT := bitvec_to_signal (nat_to_bitvec_sized 2 1).\n  Definition KEY_FULL_ROUND := bitvec_to_signal (nat_to_bitvec_sized 2 2).\n  Definition KEY_FULL_CLEAR := bitvec_to_signal (nat_to_bitvec_sized 2 3).\n\n  Definition ADD_RK_INIT := bitvec_to_signal (nat_to_bitvec_sized 2 0).\n  Definition ADD_RK_ROUND := bitvec_to_signal (nat_to_bitvec_sized 2 1).\n  Definition ADD_RK_FINAL := bitvec_to_signal (nat_to_bitvec_sized 2 2).\n\n  Definition KEY_INIT_INPUT := constant false.\n  Definition KEY_INIT_CLEAR := constant true.\n\n  Definition KEY_DEC_EXPAND := constant false.\n  Definition KEY_DEC_CLEAR := constant true.\n\n  Definition KEY_WORDS_0123 := bitvec_to_signal (nat_to_bitvec_sized 2 0).\n  Definition KEY_WORDS_2345 := bitvec_to_signal (nat_to_bitvec_sized 2 1).\n  Definition KEY_WORDS_4567 := bitvec_to_signal (nat_to_bitvec_sized 2 2).\n  Definition KEY_WORDS_ZERO := bitvec_to_signal (nat_to_bitvec_sized 2 3).\n\n  Definition AES_128 := bitvec_to_signal (nat_to_bitvec_sized 3 1).\n  Definition AES_192 := bitvec_to_signal (nat_to_bitvec_sized 3 2).\n  Definition AES_256 := bitvec_to_signal (nat_to_bitvec_sized 3 4).\n\n  Definition ROUND_KEY_DIRECT := constant false.\n  Definition ROUND_KEY_MIXED := constant true.\n\n  Import BitVecNotations.\n  Open Scope bitvec_scope.\n\n  Definition aes_mvm_acc (acc: signal (Vec Bit 8)) (mat: cava (signal (Vec Bit 8))) (vec: cava (signal Bit))\n    : cava (signal (Vec Bit 8)) :=\n    vec <- vec ;;\n    mat <- mat >>= Vec.map (fun x => and2 (x, vec)) ;;\n    acc ^ mat.\n\n  Definition aes_mvm (vec_b: signal (Vec Bit 8)) (mat_a: signal (Vec (Vec Bit 8) 8))\n    : cava (signal (Vec Bit 8)) :=\n    _1 <- aes_mvm_acc (bitvec_to_signal(nat_to_bitvec_sized 8 0)) mat_a[@0] vec_b[@7] ;;\n    _2 <- aes_mvm_acc _1 mat_a[@1] vec_b[@6] ;;\n    _3 <- aes_mvm_acc _2 mat_a[@2] vec_b[@5] ;;\n    _4 <- aes_mvm_acc _3 mat_a[@3] vec_b[@4] ;;\n    _5 <- aes_mvm_acc _4 mat_a[@4] vec_b[@3] ;;\n    _6 <- aes_mvm_acc _5 mat_a[@5] vec_b[@2] ;;\n    _7 <- aes_mvm_acc _6 mat_a[@6] vec_b[@1] ;;\n    aes_mvm_acc _7 mat_a[@7] vec_b[@0] .\n\nEnd WithCava.\n\n(* These values are arbitrary and are to be used as inputs for generating\n  SystemVerilog testbenches. The expected output tested in the generated test bench is created\n  from the Cava semantics for AES sub components on these arbitrary inputs. *)\nDefinition test_state\n  : Vector.t (Vector.t nat 4) 4\n  := [[219; 19; 83; 69];\n      [242; 10; 34; 92];\n      [1; 1; 1; 1];\n      [45; 38; 49; 76]\n  ].\n\nDefinition test_key\n  : Vector.t (Vector.t nat 4) 4\n  := [[219; 19; 83; 69];\n      [242; 10; 34; 92];\n      [1; 1; 1; 1];\n      [45; 38; 49; 76]\n  ].\n\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/silveroak-opentitan/aes/Impl/Pkg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23017116392807727}}
{"text": "Load \"tact_nsl2\".\n   \nTheorem pi1_pi2: phi4 ~ phi24.\nunfold phi4, phi24. \nassert( (ostomsg t25) # O).\nrepeat unf. \n\nsimpl.  simpl. \n\n (*\napply RESTR_rev with (ml1:= [t15; t14; t13; t12; msg (pk (N 2)); msg (pk (N 1))]) (ml2:=  [t25; t14; t13; t12; msg (pk (N 2)); msg (pk (N 1))]).\n\n(*assert( (ostomsg t25) # O). *)\nrepeat unf. simpl.\n*)\nrepeat unf; simpl.\nLtac aply_andBcomm m1 :=\nmatch goal with\n|[|- context[ ?B & (EQ_M ?M m1) ] ] => rewrite andB_comm with (b1:= B) (b2:= (EQ_M M m1))\nend.\nrepeat aply_andBcomm (nc 3).\n\npose proof (EQ_BRmsg_msg').\nLtac aply_eqbr B m5  :=\n match goal with\n| [|- context [(if_then_else_M ((EQ_M ?M1 m5) & B) ?M3 ?M4)] ] => rewrite EQ_BRmsg_msg'  with (m1:= M1) (m2:= m5) (m:= M1) (b:= B) (m3:= M3) (m4:=M4)    end.\n\n aply_eqbr  (EQ_M (to x2) (i 1)) (nc 3). \nsimpl.\n \n\n\n repeat rewrite  EQ_BRmsg_msg' with (m1 := (pi1 (dec x2 (sk (N 1)))) ) (m2:= (nc 3)) (m:= (pi1 (dec x2 (sk (N 1)))) ) (b:=  (EQ_M (to x2) (i 1))) (m3:=      (if_then_else_M\n                           ((((EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1))) &\n                             (EQ_M (to x1) (i 1))) &\n                            (notb (EQ_M (act x2) new))) & \n                           (EQ_M (act x1) new) (pi1 (dec x2 (sk (N 1))))\n                           (if_then_else_M (EQ_M (reveal x3) (i 2)) O\n                              (if_then_else_M (EQ_M (to x3) (i 2))\n                                 (enc\n                                    (pi1 (dec x3 (sk (N 2))),\n                                    (nc 4, pk (N 2)))\n                                    (pi2 (dec x3 (sk (N 2)))) \n                                    (sr 6)) O)))). \nsimpl. \nrepeat rewrite  EQ_BRmsg_msg' with (m1 := (pi1 (dec x2 (sk (N 1)))) ) (m2:= (nc 3)) (m:= (pi1 (dec x2 (sk (N 1)))) ) (b:=  (EQ_M (to x2) (i 1))) (m3:=    (if_then_else_M\n                           ((((EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1))) &\n                             (EQ_M (to x1) (i 1))) &\n                            (notb (EQ_M (act x2) new))) & \n                           (EQ_M (act x1) new)\n                           (if_then_else_M (EQ_M (reveal x4) (i 2)) O\n                              (if_then_else_M (EQ_M (to x4) (i 2))\n                                 (enc\n                                    (pi1 (dec x4 (sk (N 2))),\n                                    (nc 4, pk (N 2)))\n                                    (pi2 (dec x4 (sk (N 2)))) \n                                    (sr 9)) O))\n                           (if_then_else_M (EQ_M (reveal x3) (i 2)) O\n                              (if_then_else_M (EQ_M (to x3) (i 2))\n                                 (if_then_else_M\n                                    (EQ_M (reveal x4) (i 2)) &\n                                    (EQ_M (to x1) (i 2))\n                                    (pi1 (dec x1 (sk (N 2))))\n                                    (if_then_else_M\n                                       (EQ_M (reveal x4) (i 2)) &\n                                       (EQ_M (to x2) (i 2))\n                                       (pi1 (dec x2 (sk (N 2))))\n                                       (if_then_else_M\n                                          (EQ_M (reveal x4) (i 2)) &\n                                          (EQ_M (to x3) (i 2))\n                                          (pi1 (dec x3 (sk (N 2))))\n                                          (if_then_else_M\n                                             ((((EQ_M (reveal x4) (i 1)) &\n                                                (EQ_M (to x2) (i 1))) &\n                                               (EQ_M (to x1) (i 1))) &\n                                              (notb (EQ_M (act x2) new))) &\n                                             (EQ_M (act x1) new)\n                                             (pi1 (dec x2 (sk (N 1))))\n                                             (if_then_else_M\n                                                ((((EQ_M (reveal x4) (i 1)) &\n                                                  (EQ_M (to x3) (i 1))) &\n                                                  (EQ_M (to x1) (i 1))) &\n                                                 (notb (EQ_M (act x3) new))) &\n                                                (EQ_M (act x1) new)\n                                                (pi1 (dec x3 (sk (N 1))))\n                                                (if_then_else_M\n                                                  ((((EQ_M (reveal x4) (i 1)) &\n                                                  (EQ_M (to x3) (i 1))) &\n                                                  (EQ_M (to x2) (i 1))) &\n                                                  (notb (EQ_M (act x3) new))) &\n                                                  (EQ_M (act x2) new)\n                                                  (pi1 (dec x3 (sk (N 1)))) O))))))\n                                 O)))).\nsimpl. \nrepeat rewrite  EQ_BRmsg_msg' with (m1 := (pi1 (dec x2 (sk (N 1)))) ) (m2:= (nc 3)) (m:= (pi1 (dec x2 (sk (N 1)))) ) (b:=  (EQ_M (to x3) (i 1))) (m3:=    (if_then_else_M\n                                    (EQ_M (reveal x4) (i 2)) &\n                                    (EQ_M (to x1) (i 2))\n                                    (pi1 (dec x1 (sk (N 2))))\n                                    (if_then_else_M\n                                       (EQ_M (reveal x4) (i 2)) &\n                                       (EQ_M (to x2) (i 2))\n                                       (pi1 (dec x2 (sk (N 2))))\n                                       (if_then_else_M\n                                          (EQ_M (reveal x4) (i 2)) &\n                                          (EQ_M (to x3) (i 2))\n                                          (pi1 (dec x3 (sk (N 2))))\n                                          (if_then_else_M\n                                             ((((EQ_M (reveal x4) (i 1)) &\n                                                (EQ_M (to x2) (i 1))) &\n                                               (EQ_M (to x1) (i 1))) &\n                                              (notb (EQ_M (act x2) new))) &\n                                             (EQ_M (act x1) new)\n                                             (pi1 (dec x2 (sk (N 1))))\n                                             (if_then_else_M\n                                                ((((EQ_M (reveal x4) (i 1)) &\n                                                  (EQ_M (to x3) (i 1))) &\n                                                  (EQ_M (to x1) (i 1))) &\n                                                 (notb (EQ_M (act x3) new))) &\n                                                (EQ_M (act x1) new)\n                                                (pi1 (dec x3 (sk (N 1))))\n                                                (if_then_else_M\n                                                  ((((EQ_M (reveal x4) (i 1)) &\n                                                  (EQ_M (to x3) (i 1))) &\n                                                  (EQ_M (to x2) (i 1))) &\n                                                  (notb (EQ_M (act x3) new))) &\n                                                  (EQ_M (act x2) new)\n                                                  (pi1 (dec x3 (sk (N 1)))) O))))))).\nsimpl.\n\nrepeat rewrite  EQ_BRmsg_msg' with (m1 := (pi1 (dec x2 (sk (N 1)))) ) (m2:= (nc 3)) (m:= (pi1 (dec x2 (sk (N 1)))) ) (b:=  (EQ_M (to x2) (i 1))) (m3:=  (if_then_else_M\n      ((((EQ_M (reveal x3) (i 1)) & (EQ_M (to x2) (i 1))) &\n        (EQ_M (to x1) (i 1))) & (notb (EQ_M (act x2) new))) &\n      (EQ_M (act x1) new)\n      (if_then_else_M (EQ_M (reveal x4) (i 2)) O\n         (if_then_else_M (EQ_M (to x4) (i 2))\n            (enc (pi1 (dec x4 (sk (N 2))), (nc 4, pk (N 2)))\n               (pi2 (dec x4 (sk (N 2)))) (sr 9)) O))\n      (if_then_else_M (EQ_M (reveal x3) (i 2)) O\n         (if_then_else_M (EQ_M (to x3) (i 2))\n            (if_then_else_M\n               (((((((EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 1))) &\n                    (EQ_M (to x2) (i 2))) & (EQ_M (to x1) (i 1))) &\n                  (notb (EQ_M (act x3) new))) & (EQ_M (act x1) new)) &\n                (EQ_M (pi1 (dec x3 (sk (N 1)))) (nc 3))) &\n               (EQ_M (pi1 (dec x2 (sk (N 2)))) (nc 3)) \n               (nc 5)\n               (if_then_else_M\n                  (((((((EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1))) &\n                       (EQ_M (to x2) (i 2))) & (EQ_M (to x1) (i 1))) &\n                     (notb (EQ_M (act x3) new))) & \n                    (EQ_M (act x1) new)) &\n                   (EQ_M (pi1 (dec x3 (sk (N 1)))) (nc 3))) &\n                  (EQ_M (pi1 (dec x2 (sk (N 2)))) (nc 3)) \n                  (nc 5)\n                  (if_then_else_M\n                     (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2))\n                     (pi1 (dec x1 (sk (N 2))))\n                     (if_then_else_M\n                        (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2))\n                        (pi1 (dec x2 (sk (N 2))))\n                        (if_then_else_M\n                           (EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 2))\n                           (pi1 (dec x3 (sk (N 2))))\n                           (if_then_else_M\n                              ((((EQ_M (reveal x4) (i 1)) &\n                                 (EQ_M (to x2) (i 1))) & \n                                (EQ_M (to x1) (i 1))) &\n                               (notb (EQ_M (act x2) new))) &\n                              (EQ_M (act x1) new) (pi1 (dec x2 (sk (N 1))))\n                              (if_then_else_M\n                                 ((((EQ_M (reveal x4) (i 1)) &\n                                    (EQ_M (to x3) (i 1))) &\n                                   (EQ_M (to x1) (i 1))) &\n                                  (notb (EQ_M (act x3) new))) &\n                                 (EQ_M (act x1) new)\n                                 (pi1 (dec x3 (sk (N 1))))\n                                 (if_then_else_M\n                                    ((((EQ_M (reveal x4) (i 1)) &\n                                       (EQ_M (to x3) (i 1))) &\n                                      (EQ_M (to x2) (i 1))) &\n                                     (notb (EQ_M (act x3) new))) &\n                                    (EQ_M (act x2) new)\n                                    (pi1 (dec x3 (sk (N 1)))) O)))))))) O)))). \nsimpl. \n\nrepeat rewrite  EQ_BRmsg_msg' with (m1 := (pi1 (dec x2 (sk (N 1)))) ) (m2:= (nc 3)) (m:= (pi1 (dec x2 (sk (N 1)))) ) (b:=  (EQ_M (to x3) (i 1))) (m3:=  (if_then_else_M\n      (((((((EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 1))) &\n           (EQ_M (to x2) (i 2))) & (EQ_M (to x1) (i 1))) &\n         (notb (EQ_M (act x3) new))) & (EQ_M (act x1) new)) &\n       (EQ_M (pi1 (dec x3 (sk (N 1)))) (nc 3))) &\n      (EQ_M (pi1 (dec x2 (sk (N 2)))) (nc 3)) (nc 5)\n      (if_then_else_M\n         (((((((EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1))) &\n              (EQ_M (to x2) (i 2))) & (EQ_M (to x1) (i 1))) &\n            (notb (EQ_M (act x3) new))) & (EQ_M (act x1) new)) &\n          (EQ_M (pi1 (dec x3 (sk (N 1)))) (nc 3))) &\n         (EQ_M (pi1 (dec x2 (sk (N 2)))) (nc 3)) (nc 5)\n         (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x1) (i 2))\n            (pi1 (dec x1 (sk (N 2))))\n            (if_then_else_M (EQ_M (reveal x4) (i 2)) & (EQ_M (to x2) (i 2))\n               (pi1 (dec x2 (sk (N 2))))\n               (if_then_else_M\n                  (EQ_M (reveal x4) (i 2)) & (EQ_M (to x3) (i 2))\n                  (pi1 (dec x3 (sk (N 2))))\n                  (if_then_else_M\n                     ((((EQ_M (reveal x4) (i 1)) & (EQ_M (to x2) (i 1))) &\n                       (EQ_M (to x1) (i 1))) & (notb (EQ_M (act x2) new))) &\n                     (EQ_M (act x1) new) (pi1 (dec x2 (sk (N 1))))\n                     (if_then_else_M\n                        ((((EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1))) &\n                          (EQ_M (to x1) (i 1))) & (notb (EQ_M (act x3) new))) &\n                        (EQ_M (act x1) new) (pi1 (dec x3 (sk (N 1))))\n                        (if_then_else_M\n                           ((((EQ_M (reveal x4) (i 1)) & (EQ_M (to x3) (i 1))) &\n                             (EQ_M (to x2) (i 1))) &\n                            (notb (EQ_M (act x3) new))) & \n                           (EQ_M (act x2) new) (pi1 (dec x3 (sk (N 1)))) O))))))))). \nsimpl.\n\n\n(*assert((ostomsg t15) # (ostomsg t25)).\nsimpl. unfold qb10_ss, qb01_ss. unfold qb11_s. unfold qa12. unfold qa02_s.*)\n (*qb20_s qb21*)\n\n\napply  IFBRANCH_M4 with (ml1:=[msg (pk (N 1)); msg (pk (N 2))]) (ml2 := [msg (pk (N 1)); msg (pk (N 2))]); try  reflexivity;  simpl.\napply  IFBRANCH_M4 with (ml1:=[msg (pk (N 1)); msg (pk (N 2)) ; bol (EQ_M (reveal x1) (i 1))]) (ml2 := [msg (pk (N 1)); msg (pk (N 2)) ; bol (EQ_M (reveal x1) (i 1))]); try  reflexivity;  simpl. \napply  IFBRANCH_M4 with (ml1:=[msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2))]) (ml2 := [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2))]) ;try  reflexivity;  simpl. \n\napply  IFBRANCH_M3 with (ml1:= [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1))]) (ml2 := [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1))]); try  reflexivity;  simpl. \n\napply  IFBRANCH_M3 with (ml1:= [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1))]) (ml2 := [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1))]); try  reflexivity;  simpl. \napply  IFBRANCH_M3 with (ml1:= [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (reveal x2) (i 2))]) (ml2 := [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (reveal x2) (i 2))]); try  reflexivity;  simpl. \n\napply  IFBRANCH_M2 with (ml1:= [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (pi1 (dec x2 (sk (N 1)))) (nc 3)) & (EQ_M (to x2) (i 1));\n    msg\n      (enc (pi1 (pi2 (dec (f mphi1) (pi2 (k (N 1))))))\n         (pi2 (pi2 (dec (f mphi1) (pi2 (k (N 1)))))) \n         (rs (N 1)))]) (ml2 := [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (pi1 (dec x2 (sk (N 1)))) (nc 3)) & (EQ_M (to x2) (i 1));\n    msg\n      (enc (pi1 (pi2 (dec (f mphi1) (pi2 (k (N 1))))))\n         (pi2 (pi2 (dec (f mphi1) (pi2 (k (N 1)))))) \n         (rs (N 1)))]); try  reflexivity;  simpl. \napply  IFBRANCH_M2 with (ml1:= [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (pi1 (dec x2 (sk (N 1)))) (nc 3)) & (EQ_M (to x2) (i 1));\n    msg\n      (enc (pi1 (pi2 (dec (f mphi1) (pi2 (k (N 1))))))\n         (pi2 (pi2 (dec (f mphi1) (pi2 (k (N 1)))))) \n         (rs (N 1)));\n    bol\n      (if_then_else_B\n         (if_then_else_B\n            (if_then_else_B\n               (if_then_else_B (EQ_M (reveal (f mphi2)) (i 1))\n                  (EQ_M (to (f mphi1)) (i 1)) FAlse)\n               (EQ_M (to (f mphi0)) (i 1)) FAlse)\n            (if_then_else_B (EQ_M (act (f mphi1)) new) FAlse TRue) FAlse)\n         (EQ_M (act (f mphi0)) new) FAlse)]) (ml2 := [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (pi1 (dec x2 (sk (N 1)))) (nc 3)) & (EQ_M (to x2) (i 1));\n    msg\n      (enc (pi1 (pi2 (dec (f mphi1) (pi2 (k (N 1))))))\n         (pi2 (pi2 (dec (f mphi1) (pi2 (k (N 1)))))) \n         (rs (N 1)));\n    bol\n      (if_then_else_B\n         (if_then_else_B\n            (if_then_else_B\n               (if_then_else_B (EQ_M (reveal (f mphi2)) (i 1))\n                  (EQ_M (to (f mphi1)) (i 1)) FAlse)\n               (EQ_M (to (f mphi0)) (i 1)) FAlse)\n            (if_then_else_B (EQ_M (act (f mphi1)) new) FAlse TRue) FAlse)\n         (EQ_M (act (f mphi0)) new) FAlse)]); try  reflexivity;  simpl. \n\n\napply  IFBRANCH_M2 with (ml1:= [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (pi1 (dec x2 (sk (N 1)))) (nc 3)) & (EQ_M (to x2) (i 1));\n    msg\n      (enc (pi1 (pi2 (dec (f mphi1) (pi2 (k (N 1))))))\n         (pi2 (pi2 (dec (f mphi1) (pi2 (k (N 1)))))) \n         (rs (N 1)));\n    bol\n      (if_then_else_B\n         (if_then_else_B\n            (if_then_else_B\n               (if_then_else_B (EQ_M (reveal (f mphi2)) (i 1))\n                  (EQ_M (to (f mphi1)) (i 1)) FAlse)\n               (EQ_M (to (f mphi0)) (i 1)) FAlse)\n            (if_then_else_B (EQ_M (act (f mphi1)) new) FAlse TRue) FAlse)\n         (EQ_M (act (f mphi0)) new) FAlse);\n    bol (EQ_M (reveal (f mphi2)) (i 2))]) (ml2 := [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (pi1 (dec x2 (sk (N 1)))) (nc 3)) & (EQ_M (to x2) (i 1));\n    msg\n      (enc (pi1 (pi2 (dec (f mphi1) (pi2 (k (N 1))))))\n         (pi2 (pi2 (dec (f mphi1) (pi2 (k (N 1)))))) \n         (rs (N 1)));\n    bol\n      (if_then_else_B\n         (if_then_else_B\n            (if_then_else_B\n               (if_then_else_B (EQ_M (reveal (f mphi2)) (i 1))\n                  (EQ_M (to (f mphi1)) (i 1)) FAlse)\n               (EQ_M (to (f mphi0)) (i 1)) FAlse)\n            (if_then_else_B (EQ_M (act (f mphi1)) new) FAlse TRue) FAlse)\n         (EQ_M (act (f mphi0)) new) FAlse);\n    bol (EQ_M (reveal (f mphi2)) (i 2))]); try  reflexivity;  simpl. \napply  IFBRANCH_M1 with (ml1:=[msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (pi1 (dec x2 (sk (N 1)))) (nc 3)) & (EQ_M (to x2) (i 1));\n    msg\n      (enc (pi1 (pi2 (dec (f mphi1) (pi2 (k (N 1))))))\n         (pi2 (pi2 (dec (f mphi1) (pi2 (k (N 1)))))) \n         (rs (N 1)));\n    bol\n      (if_then_else_B\n         (if_then_else_B\n            (if_then_else_B\n               (if_then_else_B (EQ_M (reveal (f mphi2)) (i 1))\n                  (EQ_M (to (f mphi1)) (i 1)) FAlse)\n               (EQ_M (to (f mphi0)) (i 1)) FAlse)\n            (if_then_else_B (EQ_M (act (f mphi1)) new) FAlse TRue) FAlse)\n         (EQ_M (act (f mphi0)) new) FAlse);\n    bol (EQ_M (reveal (f mphi2)) (i 2)); bol (EQ_M (to (f mphi2)) (i 2));\n    msg\n      (enc (pi1 (dec (f mphi2) (pi2 (k (N 2)))), (nc 4, pi1 (k (N 2))))\n         (pi2 (dec (f mphi2) (pi2 (k (N 2))))) (rs (N 1)))]) (ml2 :=[msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (pi1 (dec x2 (sk (N 1)))) (nc 3)) & (EQ_M (to x2) (i 1));\n    msg\n      (enc (pi1 (pi2 (dec (f mphi1) (pi2 (k (N 1))))))\n         (pi2 (pi2 (dec (f mphi1) (pi2 (k (N 1)))))) \n         (rs (N 1)));\n    bol\n      (if_then_else_B\n         (if_then_else_B\n            (if_then_else_B\n               (if_then_else_B (EQ_M (reveal (f mphi2)) (i 1))\n                  (EQ_M (to (f mphi1)) (i 1)) FAlse)\n               (EQ_M (to (f mphi0)) (i 1)) FAlse)\n            (if_then_else_B (EQ_M (act (f mphi1)) new) FAlse TRue) FAlse)\n         (EQ_M (act (f mphi0)) new) FAlse);\n    bol (EQ_M (reveal (f mphi2)) (i 2)); bol (EQ_M (to (f mphi2)) (i 2));\n    msg\n      (enc (pi1 (dec (f mphi2) (pi2 (k (N 2)))), (nc 4, pi1 (k (N 2))))\n         (pi2 (dec (f mphi2) (pi2 (k (N 2))))) (rs (N 1)))]); try  reflexivity;  simpl. \nFocus 2.  \napply   IFBRANCH_M1 with (ml1:=[msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (pi1 (dec x2 (sk (N 1)))) (nc 3)) & (EQ_M (to x2) (i 1));\n    msg\n      (enc (pi1 (pi2 (dec (f mphi1) (pi2 (k (N 1))))))\n         (pi2 (pi2 (dec (f mphi1) (pi2 (k (N 1)))))) \n         (rs (N 1)));\n    bol\n      (if_then_else_B\n         (if_then_else_B\n            (if_then_else_B\n               (if_then_else_B (EQ_M (reveal (f mphi2)) (i 1))\n                  (EQ_M (to (f mphi1)) (i 1)) FAlse)\n               (EQ_M (to (f mphi0)) (i 1)) FAlse)\n            (if_then_else_B (EQ_M (act (f mphi1)) new) FAlse TRue) FAlse)\n         (EQ_M (act (f mphi0)) new) FAlse);\n    bol (EQ_M (reveal (f mphi2)) (i 2)); bol (EQ_M (to (f mphi2)) (i 2));\n    msg\n      (enc (pi1 (dec (f mphi2) (pi2 (k (N 2)))), (nc 4, pi1 (k (N 2))))\n         (pi2 (dec (f mphi2) (pi2 (k (N 2))))) (rs (N 1)));\n    bol\n      (if_then_else_B (EQ_M (reveal (f mphi3)) (i 2))\n         (EQ_M (to (f mphi0)) (i 2)) FAlse)]) (ml2 := [msg (pk (N 1)); msg (pk (N 2)); bol (EQ_M (reveal x1) (i 1));\n    bol (EQ_M (reveal x1) (i 2));\n    bol (EQ_M (to x1) (i 1)) & (EQ_M (act x1) new);\n    msg (enc (nc 3, pk (N 1)) (pk (N 2)) (sr 1));\n    bol (EQ_M (reveal x2) (i 1)); bol (EQ_M (reveal x2) (i 2));\n    bol (EQ_M (pi1 (dec x2 (sk (N 1)))) (nc 3)) & (EQ_M (to x2) (i 1));\n    msg\n      (enc (pi1 (pi2 (dec (f mphi1) (pi2 (k (N 1))))))\n         (pi2 (pi2 (dec (f mphi1) (pi2 (k (N 1)))))) \n         (rs (N 1)));\n    bol\n      (if_then_else_B\n         (if_then_else_B\n            (if_then_else_B\n               (if_then_else_B (EQ_M (reveal (f mphi2)) (i 1))\n                  (EQ_M (to (f mphi1)) (i 1)) FAlse)\n               (EQ_M (to (f mphi0)) (i 1)) FAlse)\n            (if_then_else_B (EQ_M (act (f mphi1)) new) FAlse TRue) FAlse)\n         (EQ_M (act (f mphi0)) new) FAlse);\n    bol (EQ_M (reveal (f mphi2)) (i 2)); bol (EQ_M (to (f mphi2)) (i 2));\n    msg\n      (enc (pi1 (dec (f mphi2) (pi2 (k (N 2)))), (nc 4, pi1 (k (N 2))))\n         (pi2 (dec (f mphi2) (pi2 (k (N 2))))) (rs (N 1)));\n    bol\n      (if_then_else_B (EQ_M (reveal (f mphi3)) (i 2))\n         (EQ_M (to (f mphi0)) (i 2)) FAlse)]); try  reflexivity;  simpl. \n\n(*\nLtac ifbr1 :=\nmatch goal with \n|[|- (?L1 ++ (if_then_else_M ?B ?M1 ?M2)) ~ ?L2 ++ (if_then_else_M ?B1 ?M3 ?M4)] => pose proof(IFBRANCH_M1)\n(*apply IFBRANCH_M1 with (ml1:= L1) (ml2:= L2) (b:=B) (b':= B1); try reflexivity; simpl*)\nend. *)\n\napply RESTR_rev with (ml1:= \napply IFBRANCH_M1.\naply_breq_same.\n\n\nrepeat redg; repeat rewrite IFTFb.\n\naply_breq_same.\n repeat rewrite andB_elm'' with (b1 := (EQ_M (to x1) (i 1)))(b2:= (EQ_M (act x1) new)).\n false_to_sesns_all.\naply_breq. \nrepeat redg; repeat rewrite IFTFb.\n false_to_sesns_all.\naply_breq. \nrepeat redg; repeat rewrite IFTFb.\naply_breq. \n\nrepeat redg; repeat rewrite IFTFb. \n aply_breq_same.\n repeat rewrite andB_elm'' with (b1 := (EQ_M (to (f mphi1)) (i 1)))(b2:=  (EQ_M (pi1 (dec (f mphi1) (pi2 (k (N 1))))) (nc 3))).\nfalse_to_sesns_all. \naply_breq.\nrepeat redg; repeat rewrite IFTFb. \npose proof(EQ_BRmsg_msg''). \n\nrewrite EQ_BRmsg_msg''' with (m1 := (pi1 (dec (f mphi1) (pi2 (k (N 1))))) ) (m2:= (nc 3)) (m:= (pi1 (dec (f mphi1) (pi2 (k (N 1))))) ) (m3:=  (if_then_else_M\n         (if_then_else_B (EQ_M (reveal (f mphi2)) (i 1))\n            (if_then_else_B (EQ_M (act (f mphi1)) new) FAlse TRue) FAlse)\n         (if_then_else_M (EQ_M (reveal (f mphi3)) (i 2)) O\n            (if_then_else_M (EQ_M (to (f mphi3)) (i 2))\n               (enc\n                  (pi1 (dec (f mphi3) (pi2 (k (N 2)))),\n                  (nc 4, pi1 (k (N 2))))\n                  (pi2 (dec (f mphi3) (pi2 (k (N 2))))) \n                  (rs (N 1))) O))\n         (if_then_else_M (EQ_M (reveal (f mphi2)) (i 2)) O\n            (if_then_else_M (EQ_M (to (f mphi2)) (i 2))\n               (if_then_else_M\n                  (if_then_else_B (EQ_M (reveal (f mphi3)) (i 2))\n                     (EQ_M (to (f mphi2)) (i 2)) FAlse)\n                  (pi1 (dec (f mphi2) (pi2 (k (N 2)))))\n                  (if_then_else_M\n                     (if_then_else_B (EQ_M (reveal (f mphi3)) (i 1))\n                        (if_then_else_B (EQ_M (act (f mphi1)) new) FAlse TRue)\n                        FAlse) (pi1 (dec (f mphi1) (pi2 (k (N 1)))))\n                     (if_then_else_M\n                        (if_then_else_B\n                           (if_then_else_B (EQ_M (reveal (f mphi3)) (i 1))\n                              (EQ_M (to (f mphi2)) (i 1)) FAlse)\n                           (if_then_else_B (EQ_M (act (f mphi2)) new) FAlse\n                              TRue) FAlse)\n                        (pi1 (dec (f mphi2) (pi2 (k (N 1)))))\n                        (if_then_else_M\n                           (if_then_else_B\n                              (if_then_else_B\n                                 (if_then_else_B\n                                    (EQ_M (reveal (f mphi3)) (i 1))\n                                    (EQ_M (to (f mphi2)) (i 1)) FAlse)\n                                 (if_then_else_B (EQ_M (act (f mphi2)) new)\n                                    FAlse TRue) FAlse)\n                              (EQ_M (act (f mphi1)) new) FAlse)\n                           (pi1 (dec (f mphi2) (pi2 (k (N 1))))) O)))) O))))  .\nsimpl. \nrepeat redg; repeat rewrite IFTFb.\n\naply_breq.\nfalse_to_sesns_all. \naply_breq. \nfalse_to_sesns_all. \naply_breq. \nrepeat redg; repeat rewrite IFTFb.\nrepeat rewrite andB_elm'' with (b1 := (EQ_M (to (f mphi2)) (i 1)))(b2:=  (EQ_M (pi1 (dec (f mphi1) (pi2 (k (N 1))))) (nc 3))).\nfalse_to_sesns_all. simpl. \n\naply_breq.\n\nrepeat redg; repeat rewrite IFTFb.\n rewrite EQ_BRmsg_msg''' with (m1 := (pi1 (dec (f mphi1) (pi2 (k (N 1))))) ) (m2:= (nc 3)) (m:= (pi1 (dec (f mphi1) (pi2 (k (N 1))))) ) (m3:= (if_then_else_M (EQ_M (reveal (f mphi3)) (i 2))\n         (pi1 (dec (f mphi1) (pi2 (k (N 2)))))\n         (if_then_else_M\n            (if_then_else_B (EQ_M (reveal (f mphi3)) (i 1))\n               (if_then_else_B (EQ_M (act (f mphi2)) new) FAlse TRue) FAlse)\n            (pi1 (dec (f mphi2) (pi2 (k (N 1))))) O))). simpl. \n rewrite EQ_BRmsg_msg''' with (m1 := (pi1 (dec (f mphi1) (pi2 (k (N 1))))) ) (m2:= (nc 3)) (m:= (pi1 (dec (f mphi1) (pi2 (k (N 1))))) ) (m3:=  (if_then_else_M\n           (if_then_else_B\n              (if_then_else_B\n                 (if_then_else_B (EQ_M (reveal (f mphi3)) (i 2))\n                    (if_then_else_B (EQ_M (act (f mphi2)) new) FAlse TRue)\n                    FAlse)\n                 (EQ_M (pi1 (dec (f mphi2) (pi2 (k (N 1))))) (nc 3)) FAlse)\n              (EQ_M (pi1 (dec (f mphi1) (pi2 (k (N 2))))) (nc 3)) FAlse)\n           (nc 5)\n           (if_then_else_M\n              (if_then_else_B\n                 (if_then_else_B\n                    (if_then_else_B (EQ_M (reveal (f mphi3)) (i 1))\n                       (if_then_else_B (EQ_M (act (f mphi2)) new) FAlse TRue)\n                       FAlse)\n                    (EQ_M (pi1 (dec (f mphi2) (pi2 (k (N 1))))) (nc 3)) FAlse)\n                 (EQ_M (pi1 (dec (f mphi1) (pi2 (k (N 2))))) (nc 3)) FAlse)\n              (nc 5)\n              (if_then_else_M (EQ_M (reveal (f mphi3)) (i 2))\n                 (pi1 (dec (f mphi1) (pi2 (k (N 2)))))\n                 (if_then_else_M\n                    (if_then_else_B (EQ_M (reveal (f mphi3)) (i 1))\n                       (if_then_else_B (EQ_M (act (f mphi2)) new) FAlse TRue)\n                       FAlse) (pi1 (dec (f mphi2) (pi2 (k (N 1))))) O))))).  simpl. \naply_breq. \nfalse_to_sesns_all.  simpl. \nrewrite andB_assoc with (b1:= (EQ_M (reveal (f mphi3)) (i 2))) (b2:= (if_then_else_B (EQ_M (act (f mphi2)) new) FAlse TRue)) (b3:= (EQ_M (pi1 (dec (f mphi2) (pi2 (k (N 1))))) (nc 3))).\n\nrewrite andB_assoc with (b1:= (EQ_M (reveal (f mphi3)) (i 2))) (b2:=  ((if_then_else_B (EQ_M (act (f mphi2)) new) FAlse TRue) &\n            (EQ_M (pi1 (dec (f mphi2) (pi2 (k (N 1))))) (nc 3)))) (b3:= (EQ_M (pi1 (dec (f mphi1) (pi2 (k (N 2))))) (nc 3))).\nrewrite andB_elm'' with (b1:= (EQ_M (reveal (f mphi3)) (i 2))) (b2:=  (((if_then_else_B (EQ_M (act (f mphi2)) new) FAlse TRue) &\n          (EQ_M (pi1 (dec (f mphi2) (pi2 (k (N 1))))) (nc 3))) &\n         (EQ_M (pi1 (dec (f mphi1) (pi2 (k (N 2))))) (nc 3))) ). \nfalse_to_sesns_all. simpl. \n\n\naply_breq. \nrepeat redg; repeat rewrite IFTFb.\nrewrite <- IFSAME_M with (b:= (if_then_else_B\n           (if_then_else_B\n              (if_then_else_B (EQ_M (act (f mphi2)) new) FAlse TRue)\n              (EQ_M (pi1 (dec (f mphi2) (pi2 (k (N 1))))) (nc 3)) FAlse)\n           (EQ_M (pi1 (dec (f mphi1) (pi2 (k (N 2))))) (nc 3)) FAlse))  at 1. \n repeat rewrite andB_elm'' with (b1:= (if_then_else_B\n            (if_then_else_B (EQ_M (act (f mphi2)) new) FAlse TRue)\n            (EQ_M (pi1 (dec (f mphi2) (pi2 (k (N 1))))) (nc 3)) FAlse)) (b2:=  (EQ_M (pi1 (dec (f mphi1) (pi2 (k (N 2))))) (nc 3))).\nrepeat rewrite andB_elm'' with (b1:= (if_then_else_B (EQ_M (act (f mphi2)) new) FAlse TRue)) (b2:= (EQ_M (pi1 (dec (f mphi2) (pi2 (k (N 1))))) (nc 3))).\naply_breq. \naply_breq. \nrewrite <- IFSAME_M with (b:= (EQ_M (pi1 (dec (f mphi1) (pi2 (k (N 2))))) (nc 3)))  at 1.\naply_breq. \nFocus 3.  \nfalse_to_sesns_all.  simpl. \n aply_breq.  \nrepeat redg; repeat rewrite IFTFb. reflexivity. \nsimpl. \n\naply_breq_same.\nassert(qa10_ss # qb10_ss).\n\nrepeat unf.\nassert(qa01_ss # qb01_ss).\nrepeat unf.\n \n\napply breq_msgeq1'. simpl.\n\naply_breq_same.", "meta": {"author": "ajayeeralla", "repo": "compSoundProofs", "sha": "3d85841b55bbff36e5884e07f62a60ea95645969", "save_path": "github-repos/coq/ajayeeralla-compSoundProofs", "path": "github-repos/coq/ajayeeralla-compSoundProofs/compSoundProofs-3d85841b55bbff36e5884e07f62a60ea95645969/nsl2-pi1~pi2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23017116392807727}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\n\n(* Formalisation of several Objective Caml basic types *)\n\n(* integers *)\n\n  Parameter ml_int : Set.\n  Parameter ml_eq_int : forall m n : ml_int, {m = n} + {m <> n}.\n  Parameter ml_zero : ml_int.\n  Parameter ml_succ : ml_int -> ml_int.\n\n  Parameter ml_int_pred : forall m n : ml_int, ml_succ m = ml_succ n -> m = n.\n(* This axiom is wrong in practice: (ml_succ -1)=ml_zero *)\n  Axiom dangerous_discr : forall n : ml_int, ml_zero <> ml_succ n.\n\n  Parameter\n    ml_int_case :\n      forall n : ml_int, {m : ml_int | n = ml_succ m} + {n = ml_zero}.\n\n  Fixpoint int_of_nat (n : nat) : ml_int :=\n    match n with\n    | O => ml_zero\n    | S k => ml_succ (int_of_nat k)\n    end.\n\n  Lemma dangerous_int_injection :\n   forall i j : nat, int_of_nat i = int_of_nat j -> i = j.\nsimple induction i; simple destruct j; simpl in |- *; intros; auto.\nelim dangerous_discr with (int_of_nat n); auto.\n\nelim dangerous_discr with (int_of_nat n); auto.\n\nelim H with n0; auto.\napply ml_int_pred; auto.\nQed.\n\n\n(* strings *)\n  Parameter ml_string : Set.\n  Parameter ml_eq_string : forall s1 s2 : ml_string, {s1 = s2} + {s1 <> s2}.\n\n(* will be realized by (fun n -> \"x\"^int_of_string n) *)\n  Parameter ml_x_int : ml_int -> ml_string.\n  Parameter\n    ml_x_int_inj : forall m n : ml_int, ml_x_int m = ml_x_int n -> m = n.\n\n", "meta": {"author": "coq-contribs", "repo": "coq-in-coq", "sha": "0e6fb33eb41c5612ec119966acf93adabe6764a9", "save_path": "github-repos/coq/coq-contribs-coq-in-coq", "path": "github-repos/coq/coq-contribs-coq-in-coq/coq-in-coq-0e6fb33eb41c5612ec119966acf93adabe6764a9/theories/MlTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.23017116392807724}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Import QArith_base.\nRequire Import tactics2.\nRequire Import list_util.\nRequire Import Eqdep_dec.\n\n\nRequire Import Node.\nRequire Import Msg.\nRequire Import Crypto.\nRequire Import EventOrdering.\nRequire Import Process.\nRequire Import PairState.\n\n\nSection Loop.\n\nContext { pn     : @Node }.\nContext { pm     : @Msg }.\nContext { pk     : @Key }.\n\nDefinition simple_state_machine_upd {SX S I T U : Type}\n           (upd : SUpdate S T U)\n           (X   : Update SX I T) : Update (S * SX) I U :=\n  fun state i =>\n    let (s,sx) := state in\n    let (sxop, t) := X sx i in\n    let (s', o) := upd s t in\n    (option_map (fun sx' => (s', sx')) sxop, o).\n\nDefinition simple_state_machineSM {SX S I T U : Type}\n           (upd  : SUpdate S T U)\n           (init : S)\n           (X    : StateMachine SX I T)\n  : StateMachine (S * SX) I U :=\n  mkSM (simple_state_machine_upd upd (sm_update X))\n       (init, sm_state X).\n\nDefinition n_simple_state_machineSM {SX S I T U : Type}\n           (upd  : SUpdate S T U)\n           (init : S)\n           (X    : NStateMachine SX I T)\n  : NStateMachine (S * SX) I U :=\n  fun n => simple_state_machineSM upd init (X n).\n\nDefinition state_machine_upd {SX S I T U : Type}\n           (upd : Update S T U)\n           (X   : Update SX I T) : Update (S * SX) I U :=\n  fun state i =>\n    let (s,sx) := state in\n    let (sxop, t) := X sx i in\n    let (sop, o) := upd s t in\n    match sop, sxop with\n    | Some s', Some sx' => (Some (s', sx'), o)\n    | _, _ => (None, o)\n    end.\n\nDefinition state_machineSM {SX S I T U : Type}\n           (upd  : Update S T U)\n           (init : S)\n           (X    : StateMachine SX I T)\n  : StateMachine (S * SX) I U :=\n  mkSM (state_machine_upd upd (sm_update X))\n       (init, sm_state X).\n\nDefinition n_state_machineSM {SX S I T U : Type}\n           (upd  : Update S T U)\n           (init : S)\n           (X    : NStateMachine SX I T)\n  : NStateMachine (S * SX) I U :=\n  fun n => state_machineSM upd init (X n).\n\nLemma simple_state_machineSM_state_iff :\n  forall {S SX T U}\n         (upd  : SUpdate S T U)\n         (init : S)\n         (X    : StateMachine SX msg T)\n         (eo   : EventOrdering)\n         (e    : Event)\n         (s    : S)\n         (sx   : SX),\n    state_sm_on_event (simple_state_machineSM upd init X) e = Some (s, sx)\n    <->\n    exists t s' sx',\n      state_sm_on_event X e = Some sx\n      /\\ output_sm_on_event X e = Some t\n      /\\ state_sm_before_event (simple_state_machineSM upd init X) e = Some (s', sx')\n      /\\ state_sm_before_event X e = Some sx'\n      /\\ op_update X sx' (trigger e) = Some (Some sx, t)\n      /\\ s = fst (upd s' t).\nProof.\n  intros S SX T U upd init X eo.\n  induction e as [e ind] using predHappenedBeforeInd; introv; simpl.\n  rewrite (state_sm_on_event_unroll (simple_state_machineSM _ _ _)).\n  rewrite (state_sm_on_event_unroll X).\n  destruct (dec_isFirst e) as [d|d]; simpl in *.\n\n  - split; intro h.\n\n    + apply op_state_some_iff in h; exrepnd.\n      allrw; simpl.\n      unfold op_state; simpl.\n      unfold simple_state_machine_upd in h0; simpl in h0.\n      repeat (dest_cases w); simpl in *.\n      destruct w0; simpl in *; ginv.\n      exists w1 init (sm_state X); dands; auto; try congruence.\n\n      {\n        rewrite output_sm_on_event_unroll.\n        destruct (dec_isFirst e); tcsp; simpl.\n        allrw; simpl; auto.\n        unfold op_output; simpl.\n        allrw <- ; simpl; auto.\n      }\n\n      {\n        rewrite state_sm_before_event_unroll.\n        destruct (dec_isFirst e); tcsp; simpl.\n      }\n\n      {\n        rewrite state_sm_before_event_unroll.\n        destruct (dec_isFirst e); tcsp; simpl.\n      }\n\n      {\n        allrw <- ; simpl; auto.\n      }\n\n    + exrepnd; ginv; subst.\n      apply op_state_some_iff in h1; exrepnd.\n      apply op_update_some_iff in h5; exrepnd; ginv.\n      rewrite h1 in *; ginv.\n      unfold op_state; simpl.\n      repeat (dest_cases w); simpl in *; subst.\n      unfold option_map.\n      rewrite state_sm_before_event_unroll in h3.\n      rewrite state_sm_before_event_unroll in h4.\n      destruct (dec_isFirst e); tcsp; simpl; ginv.\n      rewrite <- Heqw in *; ginv.\n\n  - remember (state_sm_on_event (simple_state_machineSM upd init X) (local_pred e)) as sop.\n    symmetry in Heqsop; destruct sop; simpl in *.\n\n    + destruct p.\n      apply ind in Heqsop;[|apply local_pred_is_direct_pred;auto].\n      exrepnd; subst; simpl in *.\n      dest_cases y; symmetry in Heqy; simpl in *.\n      dest_cases z; symmetry in Heqz; simpl in *.\n      destruct y0; simpl in *; split; intro h; tcsp; ginv;\n        repeat (allrw; simpl in * ).\n\n      * exists y1 (fst (upd s' t)) s1; dands; auto; allrw; simpl; auto.\n\n        {\n          rewrite output_sm_on_event_unroll; destruct (dec_isFirst e); tcsp.\n          repeat (allrw; simpl; tcsp).\n        }\n\n        {\n          rewrite state_sm_before_event_unroll.\n          destruct (dec_isFirst e); tcsp; GC.\n          repeat (allrw; simpl).\n          dest_cases w; symmetry in Heqw; simpl in *; auto.\n        }\n\n        {\n          rewrite state_sm_before_event_as_state_sm_on_event_pred; auto.\n        }\n\n      * exrepnd; subst; simpl in *; ginv.\n        rewrite Heqsop1 in h1; simpl in *.\n        rewrite Heqy in h1; simpl in *; ginv.\n        rewrite state_sm_before_event_as_state_sm_on_event_pred in h4; auto.\n        rewrite Heqsop1 in h4; ginv.\n        rewrite h5 in Heqy; ginv.\n        apply implies_eq_fst in Heqz; simpl in Heqz; subst.\n\n        f_equal; f_equal.\n        rewrite state_sm_before_event_unroll in h3.\n        destruct (dec_isFirst e); tcsp; GC.\n        rewrite Heqsop3 in h3; simpl in *.\n        rewrite Heqsop5 in h3; simpl in *.\n        dest_cases w; symmetry in Heqw; simpl in *; ginv.\n\n      * assert False; tcsp.\n        exrepnd; subst; simpl in *; ginv.\n        rewrite Heqsop1 in h1; simpl in h1.\n        rewrite Heqy in h1; simpl in *; ginv.\n\n    + split; intro h; ginv.\n      exrepnd; subst; simpl in *.\n      assert False; tcsp.\n\n      rewrite state_sm_before_event_as_state_sm_on_event_pred in h3; auto.\n      rewrite Heqsop in h3; ginv.\nQed.\n\nLemma simple_state_machineSM_output_iff0 :\n  forall {S SX T U}\n         (upd  : SUpdate S T U)\n         (init : S)\n         (X    : StateMachine SX msg T)\n         (eo   : EventOrdering)\n         (e    : Event)\n         (u    : U),\n    output_sm_on_event (simple_state_machineSM upd init X) e = Some u\n    <->\n    exists t s sx,\n      output_sm_on_event X e = Some t\n      /\\ state_sm_before_event (simple_state_machineSM upd init X) e = Some (s,sx)\n      /\\ u = snd (upd s t).\nProof.\n  introv.\n  rewrite (output_sm_on_event_unroll (simple_state_machineSM _ _ _)).\n  rewrite (output_sm_on_event_unroll X).\n  destruct (dec_isFirst e) as [d|d]; simpl in *.\n\n  - split; intro h; ginv.\n\n    + dest_cases w; symmetry in Heqw; simpl in *; auto; ginv.\n      dest_cases y; symmetry in Heqy; simpl in *.\n      apply implies_eq_snd in Heqy; simpl in Heqy; subst.\n      exists w1 init (sm_state X); dands; auto.\n      rewrite state_sm_before_event_unroll.\n      destruct (dec_isFirst e); tcsp; ginv; simpl.\n\n    + exrepnd; subst; ginv; simpl in *.\n      dest_cases w; symmetry in Heqw; simpl in *; auto.\n      dest_cases y; symmetry in Heqy; simpl in *; auto.\n      apply implies_eq_snd in Heqy; simpl in Heqy; subst.\n      rewrite state_sm_before_event_unroll in h2.\n      destruct (dec_isFirst e); tcsp; simpl in *; ginv.\n\n  - split; intro h.\n\n    + remember (state_sm_on_event (simple_state_machineSM upd init X) (local_pred e)) as sop.\n      symmetry in Heqsop; destruct sop; simpl in *; ginv;[].\n      destruct p; simpl in *.\n\n      apply simple_state_machineSM_state_iff in Heqsop.\n      exrepnd; subst; simpl in *.\n      repeat (allrw; simpl in * ).\n      dest_cases w; symmetry in Heqw; simpl in *.\n      dest_cases y; symmetry in Heqy; simpl in *.\n      apply implies_eq_snd in Heqy; simpl in Heqy; subst.\n\n      exists w1 (fst (upd s' t)) s0.\n      dands; auto.\n\n      rewrite state_sm_before_event_unroll.\n      destruct (dec_isFirst e); tcsp; GC.\n      repeat (allrw; simpl).\n      dest_cases y; symmetry in Heqy; simpl in *; auto.\n\n    + exrepnd; subst; simpl in *.\n      rewrite state_sm_before_event_as_state_sm_on_event_pred in h2; auto.\n      allrw; simpl.\n\n      apply simple_state_machineSM_state_iff in h2.\n      exrepnd; subst.\n      rewrite h2 in h1; simpl in h1; ginv.\n      dest_cases w; symmetry in Heqw; simpl in *.\n      dest_cases y; symmetry in Heqy; simpl in *; auto.\nQed.\n\n\nLemma simple_state_machineSM_output_iff :\n  forall {S SX T U}\n         (upd  : SUpdate S T U)\n         (init : S)\n         (X    : StateMachine SX msg T)\n         (eo   : EventOrdering)\n         (e    : Event)\n         (u    : U),\n    output_sm_on_event (simple_state_machineSM upd init X) e = Some u\n    <->\n    exists t s,\n      output_sm_on_event X e = Some t\n      /\\ SM_state_before_event (simple_state_machineSM upd init X) e s\n      /\\ u = snd (upd s t).\nProof.\n  introv.\n  rewrite simple_state_machineSM_output_iff0.\n  split; intro h; exrepnd; subst; unfold SM_state_before_event in *; allrw.\n\n  - exists t s; dands; auto.\n\n  - remember (state_sm_before_event (simple_state_machineSM upd init X) e) as sop;\n      destruct sop; tcsp; destruct p; subst.\n    exists t s s1; dands; auto.\nQed.\n\nLemma simple_state_machineSM_list_output_iff :\n  forall {S SX T U}\n         (upd  : SUpdate S T (list U))\n         (init : S)\n         (X    : StateMachine SX msg T)\n         (eo   : EventOrdering)\n         (e    : Event)\n         (u    : U),\n    In u (loutput_sm_on_event (simple_state_machineSM upd init X) e)\n    <->\n    exists t s,\n      output_sm_on_event X e = Some t\n      /\\ SM_state_before_event (simple_state_machineSM upd init X) e s\n      /\\ In u (snd (upd s t)).\nProof.\n  introv.\n  unfold loutput_sm_on_event.\n  remember (output_sm_on_event (simple_state_machineSM upd init X) e) as sop.\n  symmetry in Heqsop; destruct sop; simpl in *.\n  - apply simple_state_machineSM_output_iff in Heqsop; exrepnd; subst; simpl in *.\n    split; intro h.\n    + exists t s; dands; auto.\n    + exrepnd.\n      rewrite Heqsop0 in h0; ginv.\n      unfold SM_state_before_event in *.\n      remember (state_sm_before_event (simple_state_machineSM upd init X) e) as p.\n      symmetry in Heqp; destruct p; tcsp.\n      destruct p; simpl in *; repeat subst; auto.\n  - split; intro h; tcsp.\n    exrepnd.\n    unfold SM_state_before_event in *.\n    remember (state_sm_before_event (simple_state_machineSM upd init X) e) as p.\n    symmetry in Heqp; destruct p; tcsp.\n    destruct p; simpl in *; repeat subst; auto.\n    apply output_sm_on_event_none_implies_state_sm_before_event_none in Heqsop.\n    rewrite Heqsop in Heqp; ginv.\nQed.\n\nLemma state_machineSM_state_iff :\n  forall {S SX T U}\n         (upd  : Update S T U)\n         (init : S)\n         (X    : StateMachine SX msg T)\n         (eo   : EventOrdering)\n         (e    : Event)\n         (s    : S)\n         (sx   : SX),\n    state_sm_on_event (state_machineSM upd init X) e = Some (s, sx)\n    <->\n    exists t s' sx',\n      state_sm_on_event X e = Some sx\n      /\\ output_sm_on_event X e = Some t\n      /\\ state_sm_before_event (state_machineSM upd init X) e = Some (s', sx')\n      /\\ state_sm_before_event X e = Some sx'\n      /\\ sm_update X sx' (trigger e) = (Some sx, t)\n      /\\ Some s = fst (upd s' t).\nProof.\n  intros S SX T U upd init X eo.\n  induction e as [e ind] using predHappenedBeforeInd; introv; simpl.\n  rewrite (state_sm_on_event_unroll (state_machineSM _ _ _)).\n  rewrite (state_sm_on_event_unroll X).\n  destruct (dec_isFirst e) as [d|d]; simpl in *.\n\n  - dest_cases w; symmetry in Heqw; simpl.\n    dest_cases y; symmetry in Heqy; simpl.\n    destruct y0, w0; simpl; auto.\n\n    + split; intro h; ginv.\n\n      * exists w1 init (sm_state X).\n        dands; auto; allrw; simpl; auto.\n\n        {\n          rewrite output_sm_on_event_unroll.\n          destruct (dec_isFirst e); tcsp; simpl.\n          allrw; simpl; auto.\n        }\n\n        {\n          rewrite state_sm_before_event_unroll.\n          destruct (dec_isFirst e); tcsp; simpl.\n        }\n\n        {\n          rewrite state_sm_before_event_unroll.\n          destruct (dec_isFirst e); tcsp; simpl.\n        }\n\n      * exrepnd; ginv; simpl in *.\n        rewrite state_sm_before_event_unroll in h3.\n        destruct (dec_isFirst e); tcsp; ginv.\n        rewrite Heqw in h5; ginv.\n        rewrite Heqy in h0; simpl in *; ginv.\n\n    + split; intro h; exrepnd; ginv.\n\n    + split; intro h; exrepnd; ginv.\n      assert False; tcsp.\n\n      rewrite output_sm_on_event_unroll in h2.\n      destruct (dec_isFirst e); tcsp; GC.\n      rewrite Heqw in h2; simpl in *; ginv.\n\n      rewrite state_sm_before_event_unroll in h4.\n      destruct (dec_isFirst e); tcsp; GC; ginv.\n\n      rewrite state_sm_before_event_unroll in h3.\n      destruct (dec_isFirst e); tcsp; GC; ginv.\n\n      rewrite Heqy in h0; simpl in *; ginv.\n\n    + split; intro h; exrepnd; ginv.\n\n  - remember (state_sm_on_event (state_machineSM upd init X) (local_pred e)) as sop.\n    symmetry in Heqsop; destruct sop; simpl in *.\n\n    + destruct p.\n      apply ind in Heqsop;[|apply local_pred_is_direct_pred;auto].\n      exrepnd; subst; simpl in *.\n      dest_cases y; symmetry in Heqy; simpl in *.\n      dest_cases z; symmetry in Heqz; simpl in *.\n      destruct z0, y0; simpl in *; split; intro h; tcsp; ginv;\n        repeat (allrw; simpl in * ).\n\n      * exists y1 s0 s1; dands; auto; allrw; simpl; auto.\n\n        {\n          rewrite output_sm_on_event_unroll; destruct (dec_isFirst e); tcsp.\n          repeat (allrw; simpl; tcsp).\n        }\n\n        {\n          rewrite state_sm_before_event_unroll.\n          destruct (dec_isFirst e); tcsp; GC.\n          repeat (allrw; simpl).\n          dest_cases w; symmetry in Heqw; simpl in *; auto.\n          destruct w0; simpl in *; ginv.\n        }\n\n        {\n          rewrite state_sm_before_event_as_state_sm_on_event_pred; auto.\n        }\n\n      * exrepnd; subst; simpl in *; ginv.\n        rewrite Heqsop1 in h1; simpl in *.\n        rewrite Heqy in h1; simpl in *; ginv.\n        rewrite state_sm_before_event_as_state_sm_on_event_pred in h4; auto.\n        rewrite Heqsop1 in h4; ginv.\n        rewrite h5 in Heqy; ginv.\n        apply implies_eq_fst in Heqz; simpl in Heqz; subst.\n\n        f_equal; f_equal.\n        rewrite state_sm_before_event_unroll in h3.\n        destruct (dec_isFirst e); tcsp; GC.\n        rewrite Heqsop3 in h3; simpl in *.\n        rewrite Heqsop5 in h3; simpl in *.\n        dest_cases w; symmetry in Heqw; simpl in *; ginv.\n        destruct w0; simpl in *; ginv.\n        rewrite Heqz in h0; ginv.\n\n      * assert False; tcsp.\n        exrepnd; subst; simpl in *; ginv.\n        rewrite Heqsop1 in h1; simpl in h1.\n        rewrite Heqy in h1; simpl in *; ginv.\n\n      * assert False; tcsp.\n        exrepnd; subst; simpl in *; ginv.\n        rewrite Heqsop1 in h1; simpl in h1.\n        rewrite Heqy in h1; simpl in *; ginv.\n\n        rewrite state_sm_before_event_as_state_sm_on_event_pred in h4; auto.\n        rewrite Heqsop1 in h4; ginv.\n        rewrite h5 in Heqy; ginv.\n\n        rewrite state_sm_before_event_unroll in h3.\n        destruct (dec_isFirst e); tcsp; GC.\n        rewrite Heqsop3 in h3; simpl in *.\n        rewrite Heqsop5 in h3; simpl in *.\n        dest_cases w; symmetry in Heqw; simpl in *; ginv.\n        destruct w0; simpl in *; ginv.\n        rewrite Heqz in h0; ginv.\n\n      * assert False; tcsp.\n        exrepnd; subst; simpl in *; ginv.\n        rewrite Heqsop1 in h1; simpl in h1.\n        rewrite Heqy in h1; simpl in *; ginv.\n\n    + split; intro h; ginv.\n      exrepnd; subst; simpl in *.\n      assert False; tcsp.\n\n      rewrite state_sm_before_event_as_state_sm_on_event_pred in h3; auto.\n      rewrite Heqsop in h3; ginv.\nQed.\n\nLemma state_machineSM_output_iff0 :\n  forall {S SX T U}\n         (upd  : Update S T U)\n         (init : S)\n         (X    : StateMachine SX msg T)\n         (eo   : EventOrdering)\n         (e    : Event)\n         (u    : U),\n    output_sm_on_event (state_machineSM upd init X) e = Some u\n    <->\n    exists t s sx,\n      output_sm_on_event X e = Some t\n      /\\ state_sm_before_event (state_machineSM upd init X) e = Some (s,sx)\n      /\\ u = snd (upd s t).\nProof.\n  introv.\n  rewrite (output_sm_on_event_unroll (state_machineSM _ _ _)).\n  rewrite (output_sm_on_event_unroll X).\n  destruct (dec_isFirst e) as [d|d]; simpl in *.\n\n  - split; intro h; ginv.\n\n    + dest_cases w; symmetry in Heqw; simpl in *; auto; ginv.\n      dest_cases y; symmetry in Heqy; simpl in *.\n\n      exists w1 init (sm_state X); dands; auto.\n\n      { rewrite state_sm_before_event_unroll.\n        destruct (dec_isFirst e); tcsp; ginv; simpl. }\n\n      { destruct y0, w0; simpl; allrw; simpl; auto. }\n\n    + exrepnd; subst; ginv; simpl in *.\n      dest_cases w; symmetry in Heqw; simpl in *; auto.\n      dest_cases y; symmetry in Heqy; simpl in *; auto.\n      rewrite state_sm_before_event_unroll in h2.\n      destruct (dec_isFirst e); tcsp; simpl in *; ginv.\n\n      destruct y0, w0; simpl; allrw; auto.\n\n  - split; intro h.\n\n    + remember (state_sm_on_event (state_machineSM upd init X) (local_pred e)) as sop.\n      symmetry in Heqsop; destruct sop; simpl in *; ginv;[].\n      destruct p; simpl in *.\n\n      apply state_machineSM_state_iff in Heqsop.\n      exrepnd; subst; simpl in *.\n      repeat (allrw; simpl in * ).\n      dest_cases w; symmetry in Heqw; simpl in *.\n      dest_cases y; symmetry in Heqy; simpl in *.\n\n      exists w1 s s0.\n      dands; auto.\n\n      { rewrite state_sm_before_event_unroll.\n        destruct (dec_isFirst e); tcsp; GC.\n        repeat (allrw; simpl).\n        dest_cases y; symmetry in Heqy; simpl in *; auto.\n        destruct y2; simpl in *; ginv. }\n\n      { destruct y0, w0; simpl in *; allrw; simpl; auto. }\n\n    + exrepnd; subst; simpl in *.\n      rewrite state_sm_before_event_as_state_sm_on_event_pred in h2; auto.\n      allrw; simpl.\n\n      apply state_machineSM_state_iff in h2.\n      exrepnd; subst.\n      rewrite h2 in h1; simpl in h1; ginv.\n      dest_cases w; symmetry in Heqw; simpl in *.\n      dest_cases y; symmetry in Heqy; simpl in *; auto.\n      destruct y0, w0; simpl; auto.\nQed.\n\nLemma state_machineSM_output_iff :\n  forall {S SX T U}\n         (upd  : Update S T U)\n         (init : S)\n         (X    : StateMachine SX msg T)\n         (eo   : EventOrdering)\n         (e    : Event)\n         (u    : U),\n    output_sm_on_event (state_machineSM upd init X) e = Some u\n    <->\n    exists t s,\n      output_sm_on_event X e = Some t\n      /\\ SM_state_before_event (state_machineSM upd init X) e s\n      /\\ u = snd (upd s t).\nProof.\n  introv.\n  rewrite state_machineSM_output_iff0.\n  split; intro h; exrepnd; subst; unfold SM_state_before_event in *; allrw.\n\n  - exists t s; dands; auto.\n\n  - remember (state_sm_before_event (state_machineSM upd init X) e) as sop;\n      destruct sop; tcsp; destruct p; subst.\n    exists t s s1; dands; auto.\nQed.\n\nLemma state_machineSM_list_output_iff :\n  forall {S SX T U}\n         (upd  : Update S T (list U))\n         (init : S)\n         (X    : StateMachine SX msg T)\n         (eo   : EventOrdering)\n         (e    : Event)\n         (u    : U),\n    In u (loutput_sm_on_event (state_machineSM upd init X) e)\n    <->\n    exists t s,\n      output_sm_on_event X e = Some t\n      /\\ SM_state_before_event (state_machineSM upd init X) e s\n      /\\ In u (snd (upd s t)).\nProof.\n  introv.\n  unfold loutput_sm_on_event.\n  remember (output_sm_on_event (state_machineSM upd init X) e) as sop.\n  symmetry in Heqsop; destruct sop; simpl in *.\n  - apply state_machineSM_output_iff in Heqsop; exrepnd; subst; simpl in *.\n    split; intro h.\n    + exists t s; dands; auto.\n    + exrepnd.\n      rewrite Heqsop0 in h0; ginv.\n      unfold SM_state_before_event in *.\n      remember (state_sm_before_event (state_machineSM upd init X) e) as p.\n      symmetry in Heqp; destruct p; tcsp.\n      destruct p; simpl in *; repeat subst; auto.\n  - split; intro h; tcsp.\n    exrepnd.\n    unfold SM_state_before_event in *.\n    remember (state_sm_before_event (state_machineSM upd init X) e) as p.\n    symmetry in Heqp; destruct p; tcsp.\n    destruct p; simpl in *; repeat subst; auto.\n    apply output_sm_on_event_none_implies_state_sm_before_event_none in Heqsop.\n    rewrite Heqsop in Heqp; ginv.\nQed.\n\nEnd Loop.\n", "meta": {"author": "vrahli", "repo": "Velisarios", "sha": "6fb353b18610cd79210755fcc90123536c367aaa", "save_path": "github-repos/coq/vrahli-Velisarios", "path": "github-repos/coq/vrahli-Velisarios/Velisarios-6fb353b18610cd79210755fcc90123536c367aaa/components/Loop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.23004916204957926}}
{"text": "Require Import riscv.Proofs.DecodeEncodeProver.\nRequire Import riscv.Proofs.DecodeEncodeI.\nRequire Import riscv.Proofs.DecodeEncodeM.\nRequire Import riscv.Proofs.DecodeEncodeA.\nRequire Import riscv.Proofs.DecodeEncodeI64.\nRequire Import riscv.Proofs.DecodeEncodeM64.\nRequire Import riscv.Proofs.DecodeEncodeA64.\nRequire Import riscv.Proofs.DecodeEncodeCSR.\n\nLemma decode_encode: forall (inst: Instruction) (iset: InstructionSet),\n    verify inst iset ->\n    decode iset (encode inst) = inst.\nProof.\n  destruct inst; intros.\n  - apply decodeI_encode; assumption.\n  - apply decodeM_encode; assumption.\n  - apply decodeA_encode; assumption.\n  - destruct H as [R V].\n    (* F is not supported and therefore verify_iset returns False for it *)\n    change False in V. destruct V.\n  - apply decodeI64_encode; assumption.\n  - apply decodeM64_encode; assumption.\n  - apply decodeA64_encode; assumption.\n  - destruct H as [R V].\n    (* F64 is not supported and therefore verify_iset returns False for it *)\n    change False in V. destruct V.\n  - apply decodeCSR_encode; assumption.\n  - destruct H as [R V].\n    (* invalid instruction is invalid *)\n    change False in V. destruct V.\nQed.\n", "meta": {"author": "mit-plv", "repo": "riscv-coq", "sha": "55c9cc88a6734550bdd913bfdf482d498c6354e6", "save_path": "github-repos/coq/mit-plv-riscv-coq", "path": "github-repos/coq/mit-plv-riscv-coq/riscv-coq-55c9cc88a6734550bdd913bfdf482d498c6354e6/src/riscv/Proofs/DecodeEncode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23004915594047903}}
{"text": "Require Import\n        List.\n\nRequire Import\n        ERC20\n        Events\n        LibModel\n        Maps\n        Messages\n        States\n        Types.\n\nRequire Import\n        FeeHolder.\n\n\nModule BurnManager.\n\n  Section Burn.\n\n    Definition burn_require (wst: WorldState) (token: address) : Prop :=\n      burnMgr_lrcAddress (wst_burn_manager_state wst) = token.\n\n    Definition burn_trans (wst: WorldState) (token: address)\n               (wst': WorldState) (retval: RetVal) (events: list Event) : Prop :=\n      exists wst1 events1 wst2 events2,\n        let balance := AA2V.get (feeholder_feeBalances (wst_feeholder_state wst))\n                                (token, burnMgr_feeHolderAddress (wst_burn_manager_state wst)) in\n        let sender := wst_burn_manager_addr wst in\n        FeeHolder.model wst (msg_withdrawBurned sender token balance)\n                        wst1 (RetBool true) events1 /\\\n        ERC20s.model wst1 (msg_erc20_burn sender token balance)\n                     wst2 (RetBool true) events2 /\\\n        wst' = wst2 /\\\n        retval = RetBool true /\\\n        events = events1 ++ events2.\n\n    Definition burn_spec (sender token: address) :=\n      {|\n        fspec_require :=\n          fun wst =>\n            burn_require wst token;\n\n        fspec_trans :=\n          fun wst wst' retval =>\n           exists events,\n             burn_trans wst token wst' retval events;\n\n        fspec_events :=\n          fun wst events =>\n            exists wst' retval,\n              burn_trans wst token wst' retval events;\n      |}.\n\n  End Burn.\n\n  Definition get_spec (msg: BurnManagerMsg) : FSpec :=\n    match msg with\n    | msg_burn sender token => burn_spec sender token\n    end.\n\n  Definition model\n             (wst: WorldState)\n             (msg: BurnManagerMsg)\n             (wst': WorldState)\n             (retval: RetVal)\n             (events: list Event)\n    : Prop :=\n    fspec_sat (get_spec msg) wst wst' retval events.\n\nEnd BurnManager.", "meta": {"author": "sec-bit", "repo": "loopring-protocol2-verification", "sha": "bfb2101faccbefd592a8f63d42e01aae41b06930", "save_path": "github-repos/coq/sec-bit-loopring-protocol2-verification", "path": "github-repos/coq/sec-bit-loopring-protocol2-verification/loopring-protocol2-verification-bfb2101faccbefd592a8f63d42e01aae41b06930/Models/BurnManager.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23004915594047903}}
{"text": "From mathcomp Require Import\n  ssreflect eqtype fintype ssrfun ssrbool ssrnat seq ssrint ssrnum ssralg\n  finset generic_quotient finfun.\nFrom extructures Require Import ord fmap.\nFrom CoqUtils Require Import hseq word.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Bullet Behavior \"Strict Subproofs\".\n\nRequire Import lib.utils lib.fmap_utils lib.ssr_set_utils.\nRequire Import common.types common.segment.\nRequire Import concrete.concrete concrete.int_32.\nRequire Import symbolic.symbolic symbolic.int_32 symbolic.exec.\nRequire Import compartmentalization.common compartmentalization.symbolic.\nRequire Import compartmentalization.isolate_sets.\nRequire Import os.os.\n\nRequire Extraction.\n\nExtraction Language Haskell.\n\nExtract Inductive unit => \"()\" [\"()\"].\n\nExtract Inductive prod => \"(,)\" [\"(,)\"].\nExtract Inductive sigT => \"(,)\" [\"(,)\"].\nExtract Inductive sigT2 => \"(,,)\" [\"(,,)\"].\nExtract Constant prod_rect    => \"Prelude.uncurry\".\nExtract Constant prod_uncurry => \"Prelude.curry\".\nExtract Constant sigT_rect    => \"Prelude.uncurry\".\nExtract Constant fst          => \"Prelude.fst\".\nExtract Constant snd          => \"Prelude.snd\".\nExtract Constant projT1       => \"Prelude.fst\".\nExtract Constant projT2       => \"Prelude.snd\".\n(* choice *)\nExtract Constant choice.tag_of_pair => \"Prelude.id\".\nExtract Constant choice.pair_of_tag => \"Prelude.id\".\n\nExtract Inductive bool         => \"Prelude.Bool\" [\"Prelude.True\" \"Prelude.False\"].\nExtract Inductive sumbool      => \"Prelude.Bool\" [\"Prelude.True\" \"Prelude.False\"].\nExtract Inductive Bool.reflect => \"Prelude.Bool\" [\"Prelude.True\" \"Prelude.False\"].\nExtract Constant andb             => \"(Prelude.&&)\".\nExtract Constant orb              => \"(Prelude.||)\".\nExtract Constant xorb             => \"(Prelude./=)\".\nExtract Constant negb             => \"Prelude.not\".\nExtract Constant bool_choice      => \"Prelude.id\".\nExtract Constant Bool.bool_dec    => \"(Prelude.==)\".\nExtract Constant Bool.eqb         => \"(Prelude.==)\".\nExtract Constant Bool.iff_reflect => \"Prelude.id\".\nExtract Constant Bool.reflect_dec => \"Prelude.flip Prelude.const\".\nExtract Constant addb             => \"(Prelude./=)\". (* addb == xor *)\nExtract Constant eqb              => \"(Prelude.==)\".\nExtract Constant isSome           => \"Data.Maybe.isJust\".\nExtract Constant is_inl           => \"Data.Either.isLeft\".\nExtract Constant is_left          => \"Prelude.id\".\nExtract Constant is_inleft        => \"Data.Maybe.isJust\".\nExtract Constant compareb         => \"(Prelude.$)\".\n\n(* Like booleans, but super important! *)\nExtract Inductive reflect => \"Prelude.Bool\" [\"Prelude.True\" \"Prelude.False\"].\nExtract Constant introP   => \"Prelude.id\".\nExtract Constant sumboolP => \"Prelude.id\".\nExtract Constant idP      => \"Prelude.id\".\nExtract Constant idPn     => \"Prelude.not\".\nExtract Constant negP     => \"Prelude.not\".\nExtract Constant negPn    => \"Prelude.id\".\nExtract Constant negPf    => \"Prelude.not\".\nExtract Constant andP     => \"(Prelude.&&)\".\nExtract Constant and3P    => \"\\b1 b2 b3 -> b1 Prelude.&& b2 Prelude.&& b3\".\nExtract Constant and4P    => \"\\b1 b2 b3 b4 -> b1 Prelude.&& b2 Prelude.&& b3 Prelude.&& b4\".\nExtract Constant and5P    => \"\\b1 b2 b3 b4 b5 -> b1 Prelude.&& b2 Prelude.&& b3 Prelude.&& b4 Prelude.&& b5\".\nExtract Constant orP      => \"(Prelude.||)\".\nExtract Constant or3P     => \"\\b1 b2 b3 -> b1 Prelude.|| b2 Prelude.|| b3\".\nExtract Constant or4P     => \"\\b1 b2 b3 b4 -> b1 Prelude.|| b2 Prelude.|| b3 Prelude.|| b4\".\nExtract Constant nandP    => \"\\b1 b2 -> Prelude.not (b1 Prelude.&& b2)\".\nExtract Constant norP     => \"\\b1 b2 -> Prelude.not (b1 Prelude.|| b2)\".\nExtract Constant addbP    => \"(Prelude./=)\".\nExtract Constant compareP => \"(Prelude.$)\".\n\nExtract Inductive alt_spec => \"Prelude.Bool\" [\"Prelude.True\" \"Prelude.False\"].\n\nExtract Inductive option => \"Prelude.Maybe\" [\"Prelude.Just\" \"Prelude.Nothing\"].\nExtract Inductive sumor  => \"Prelude.Maybe\" [\"Prelude.Just\" \"Prelude.Nothing\"].\nExtract Constant option_rect    => \"Prelude.flip Prelude.maybe\".\nExtract Constant option_map     => \"Prelude.fmap\".\nExtract Constant Option.apply   => \"Prelude.flip Prelude.maybe\".\nExtract Constant Option.default => \"Data.Maybe.fromMaybe\".\nExtract Constant Option.bind    => \"(Prelude.=<<)\".\nExtract Constant Option.map     => \"Prelude.fmap\".\n\nExtract Inductive sum => \"Prelude.Either\" [\"Prelude.Left\" \"Prelude.Right\"].\nExtract Constant sum_rect => \"Prelude.either\".\n\nExtract Inductive list => \"[]\" [\"[]\" \"(:)\"].\nExtract Constant length  => \"Data.List.genericLength\".\nExtract Constant app     => \"(Prelude.++)\".\n(* seq *)\nExtract Constant size    => \"Data.List.genericLength\".\nExtract Constant nilp    => \"Prelude.null\".\nExtract Constant nilP    => \"Prelude.null\".\nExtract Constant nseq    => \"Prelude.replicate Prelude.. Prelude.fromInteger\".\nExtract Constant cat     => \"(Prelude.++)\".\nExtract Constant filter  => \"Prelude.filter\".\nExtract Constant has     => \"Prelude.any\".\nExtract Constant all     => \"Prelude.all\".\nExtract Constant drop    => \"Prelude.drop Prelude.. Prelude.fromInteger\".\nExtract Constant take    => \"Prelude.take Prelude.. Prelude.fromInteger\".\nExtract Constant rev     => \"Prelude.reverse\".\nExtract Constant map     => \"Prelude.map\".\nExtract Constant pmap    => \"Data.Maybe.mapMaybe\".\nExtract Constant iota    => \"\\f t -> [f .. f Prelude.+ t Prelude.- 1]\".\nExtract Constant foldr   => \"Prelude.foldr\".\nExtract Constant sumn    => \"Prelude.sum\".\nExtract Constant foldl   => \"Data.List.foldl'\".\nExtract Constant scanl   => \"Prelude.scanl\".\nExtract Constant zip     => \"Prelude.zip\".\nExtract Constant flatten => \"Prelude.concat\".\n(* choice *)\nExtract Constant choice.seq_of_opt => \"Prelude.maybe [] Prelude.return\".\n\nExtract Inductive comparison  => \"Prelude.Ordering\" [\"Prelude.EQ\" \"Prelude.LT\" \"Prelude.GT\"].\nExtract Inductive CompareSpec => \"Prelude.Ordering\" [\"Prelude.EQ\" \"Prelude.LT\" \"Prelude.GT\"].\n  (* Like `comparison`, but with proofs -- except those have been erased *)\n\nExtract Inductive nat => \"Prelude.Integer\" [\"(0 :: Prelude.Integer)\" \"(Prelude.+ 1)\"]\n                         \"(\\fO fS n -> if n Prelude.== 0 then fO () else fS (n Prelude.- 1))\".\nExtract Constant Peano.pred      => \"\\x -> Prelude.max (x Prelude.- 1) 0\".\nExtract Constant Peano.plus      => \"(Prelude.+)\".\nExtract Constant Peano.minus     => \"\\x y -> Prelude.max (x Prelude.- y) 0\".\nExtract Constant Peano.mult      => \"(Prelude.*)\".\nExtract Constant Peano.max       => \"Prelude.max\".\nExtract Constant Peano.min       => \"Prelude.min\".\n(* ssrnat *)\nExtract Constant eqn             => \"(Prelude.==)\".\nExtract Constant addn_rec        => \"(Prelude.+)\".\nExtract Constant addn            => \"(Prelude.+)\".\nExtract Constant subn_rec        => \"\\x y -> Prelude.max (x Prelude.- y) 0\".\nExtract Constant subn            => \"\\x y -> Prelude.max (x Prelude.- y) 0\".\nExtract Constant leq             => \"(Prelude.<=)\".\nExtract Constant maxn            => \"Prelude.max\".\nExtract Constant minn            => \"Prelude.min\".\nExtract Constant muln_rec        => \"(Prelude.*)\".\nExtract Constant muln            => \"(Prelude.*)\".\nExtract Constant expn_rec        => \"(Prelude.^)\".\nExtract Constant expn            => \"(Prelude.^)\".\nExtract Constant fact_rec        => \"Prelude.product Prelude.. Prelude.enumFromTo 1\".\nExtract Constant factorial       => \"Prelude.product Prelude.. Prelude.enumFromTo 1\".\nExtract Constant nat_of_bool     => \"\\b -> (if b then 1 else 0 :: Prelude.Integer)\".\nExtract Constant odd             => \"Prelude.odd\".\nExtract Constant double_rec      => \"(2 Prelude.*)\".\nExtract Constant double          => \"(2 Prelude.*)\".\nExtract Constant half            => \"(`Prelude.quot` 2)\".\nExtract Constant uphalf          => \"\\x -> (x Prelude.+ 1) `Prelude.quot` 2\".\nExtract Constant NatTrec.add     => \"(Prelude.+)\".\nExtract Constant NatTrec.add_mul => \"\\x y acc -> (x Prelude.* y) Prelude.+ acc\".\nExtract Constant NatTrec.mul     => \"(Prelude.*)\".\nExtract Constant NatTrec.mul_exp => \"\\x y acc -> (x Prelude.^ y) Prelude.* acc\".\nExtract Constant NatTrec.exp     => \"(Prelude.^)\".\nExtract Constant NatTrec.odd     => \"Prelude.odd\".\nExtract Constant NatTrec.double  => \"(2 Prelude.*)\".\nExtract Constant nat_of_pos      => \"Prelude.id\".\nExtract Constant nat_of_bin      => \"Prelude.id\".\nExtract Constant bin_of_nat      => \"Prelude.id\".\n(* ssr div *)\nExtract Constant div.edivn    => \"\\x y -> if y Prelude.== 0 then (0,x) else x `Prelude.quotRem` y\".\nExtract Constant div.divn     => \"\\x y -> if y Prelude.== 0 then 0     else x `Prelude.quot`    y\".\nExtract Constant div.modn     => \"\\x y -> if y Prelude.== 0 then x     else x `Prelude.rem`     y\".\nExtract Constant div.gcdn_rec => \"Prelude.gcd\".\nExtract Constant div.gcdn     => \"Prelude.gcd\".\nExtract Constant div.lcmn     => \"Prelude.lcm\".\n\nExtract Inductive BinNums.positive =>\n  \"Prelude.Integer\"\n  [\"((Prelude.+ 1) Prelude.. (2 Prelude.*))\"\n   \"(2 Prelude.*)\"\n   \"(1 :: Prelude.Integer)\"]\n  \"(\\fxI fxO fxH p -> if p Prelude.== 1 then fxH p else (if Data.Bits.testBit p 0 then fxI else fxO) (p `Data.Bits.shiftR` 1))\".\nExtract Inductive BinNums.N =>\n  \"Prelude.Integer\" [\"(0 :: Prelude.Integer)\" \"Prelude.id\"]\n  \"(\\fN0 fNpos n -> if n Prelude.== 0 then fN0 () else fNpos n)\".\nExtract Inductive BinNums.Z =>\n  \"Prelude.Integer\" [\"(0 :: Prelude.Integer)\" \"Prelude.id\" \"Prelude.negate\"]\n  \"(\\fZ0 fZpos fZneg z -> case z `Prelude.compare` 0 of { Prelude.GT -> fZpos z ; Prelude.EQ -> fZ0 () ; Prelude.LT -> fZneg (- z) })\".\n\nExtract Constant BinPos.Pos.succ         => \"(Prelude.+ 1)\".\nExtract Constant BinPos.Pos.add          => \"(Prelude.+)\".\nExtract Constant BinPos.Pos.add_carry    => \"\\x y -> x Prelude.+ y Prelude.+ 1\".\nExtract Constant BinPos.Pos.pred_double  => \"\\x -> (2 Prelude.* x) Prelude.- 1\".\nExtract Constant BinPos.Pos.pred         => \"\\x -> Prelude.max (x Prelude.- 1) 1\".\nExtract Constant BinPos.Pos.pred_N       => \"Prelude.subtract 1\".\nExtract Constant BinPos.Pos.sub          => \"\\x y -> Prelude.max (x Prelude.- y) 1\".\nExtract Constant BinPos.Pos.mul          => \"(Prelude.*)\".\nExtract Constant BinPos.Pos.pow          => \"(Prelude.^)\".\nExtract Constant BinPos.Pos.square       => \"(Prelude.^ 2)\".\nExtract Constant BinPos.Pos.div2         => \"\\x -> Prelude.max (x `Prelude.quot` 2) 1\".\nExtract Constant BinPos.Pos.div2_up      => \"\\x -> (x Prelude.+ 1) `Prelude.quot` 2\".\nExtract Constant BinPos.Pos.compare      => \"Prelude.compare\".\nExtract Constant BinPos.Pos.min          => \"Prelude.min\".\nExtract Constant BinPos.Pos.max          => \"Prelude.max\".\nExtract Constant BinPos.Pos.eqb          => \"(Prelude.==)\".\nExtract Constant BinPos.Pos.leb          => \"(Prelude.<=)\".\nExtract Constant BinPos.Pos.ltb          => \"(Prelude.<)\".\nExtract Constant BinPos.Pos.gcd          => \"Prelude.gcd\".\nExtract Constant BinPos.Pos.Nsucc_double => \"\\x -> 2 Prelude.* x Prelude.+ 1\".\nExtract Constant BinPos.Pos.Ndouble      => \"(2 Prelude.*)\".\nExtract Constant BinPos.Pos.lor          => \"(Data.Bits..|.)\".\nExtract Constant BinPos.Pos.land         => \"(Data.Bits..&.)\".\nExtract Constant BinPos.Pos.ldiff        => \"\\x y -> x Data.Bits..&. Data.Bits.complement y\".\nExtract Constant BinPos.Pos.lxor         => \"Data.Bits.xor\".\nExtract Constant BinPos.Pos.shiftl_nat   => \"\\x s -> x `Data.Bits.shiftL` (Prelude.fromInteger s)\".\nExtract Constant BinPos.Pos.shiftr_nat   => \"\\x s -> Prelude.max (x `Data.Bits.shiftR` (Prelude.fromInteger s)) 1\".\nExtract Constant BinPos.Pos.shiftl       => \"\\x s -> x `Data.Bits.shiftL` (Prelude.fromInteger s)\".\nExtract Constant BinPos.Pos.shiftr       => \"\\x s -> Prelude.max (x `Data.Bits.shiftR` (Prelude.fromInteger s)) 1\".\nExtract Constant BinPos.Pos.testbit_nat  => \"\\x b -> Data.Bits.testBit x (Prelude.fromInteger b)\".\nExtract Constant BinPos.Pos.testbit      => \"\\x b -> Data.Bits.testBit x (Prelude.fromInteger b)\".\nExtract Constant BinPos.Pos.to_nat       => \"Prelude.id\".\nExtract Constant BinPos.Pos.of_nat       => \"Prelude.max 1\".\nExtract Constant BinPos.Pos.of_succ_nat  => \"(Prelude.+ 1)\".\nExtract Constant BinPos.Pos.eq_dec       => \"(Prelude.==)\".\n\nExtract Constant BinNat.N.zero         => \"0 :: Prelude.Integer\".\nExtract Constant BinNat.N.one          => \"1 :: Prelude.Integer\".\nExtract Constant BinNat.N.two          => \"2 :: Prelude.Integer\".\nExtract Constant BinNat.N.succ_double  => \"\\x -> 2 Prelude.* x Prelude.+ 1\".\nExtract Constant BinNat.N.double       => \"(2 Prelude.*)\".\nExtract Constant BinNat.N.succ         => \"(Prelude.+ 1)\".\nExtract Constant BinNat.N.pred         => \"\\x -> Prelude.max (x Prelude.- 1) 0\".\nExtract Constant BinNat.N.succ_pos     => \"(Prelude.+ 1)\".\nExtract Constant BinNat.N.add          => \"(Prelude.+)\".\nExtract Constant BinNat.N.sub          => \"\\x y -> Prelude.max (x Prelude.- y) 0\".\nExtract Constant BinNat.N.mul          => \"(Prelude.*)\".\nExtract Constant BinNat.N.compare      => \"Prelude.compare\".\nExtract Constant BinNat.N.eqb          => \"(Prelude.==)\".\nExtract Constant BinNat.N.leb          => \"(Prelude.<=)\".\nExtract Constant BinNat.N.ltb          => \"(Prelude.<)\".\nExtract Constant BinNat.N.min          => \"Prelude.min\".\nExtract Constant BinNat.N.max          => \"Prelude.max\".\nExtract Constant BinNat.N.div2         => \"(`Prelude.quot` 2)\".\nExtract Constant BinNat.N.even         => \"Prelude.even\".\nExtract Constant BinNat.N.odd          => \"Prelude.odd\".\nExtract Constant BinNat.N.pow          => \"(Prelude.^)\".\nExtract Constant BinNat.N.square       => \"(Prelude.^ 2)\".\nExtract Constant BinNat.N.pos_div_eucl => \"\\x y -> if y Prelude.== 0 then (0,x) else x `Prelude.quotRem` y\".\nExtract Constant BinNat.N.div_eucl     => \"\\x y -> if y Prelude.== 0 then (0,x) else x `Prelude.quotRem` y\".\nExtract Constant BinNat.N.div          => \"Prelude.quot\".\nExtract Constant BinNat.N.modulo       => \"Prelude.rem\".\nExtract Constant BinNat.N.gcd          => \"Prelude.gcd\".\nExtract Constant BinNat.N.lor          => \"(Data.Bits..|.)\".\nExtract Constant BinNat.N.land         => \"(Data.Bits..&.)\".\nExtract Constant BinNat.N.ldiff        => \"\\x y -> x Data.Bits..&. Data.Bits.complement y\".\nExtract Constant BinNat.N.lxor         => \"Data.Bits.xor\".\nExtract Constant BinNat.N.shiftl_nat   => \"\\x s -> x `Data.Bits.shiftL` (Prelude.fromInteger s)\".\nExtract Constant BinNat.N.shiftr_nat   => \"\\x s -> x `Data.Bits.shiftR` (Prelude.fromInteger s)\".\nExtract Constant BinNat.N.shiftl       => \"\\x s -> x `Data.Bits.shiftL` (Prelude.fromInteger s)\".\nExtract Constant BinNat.N.shiftr       => \"\\x s -> x `Data.Bits.shiftR` (Prelude.fromInteger s)\".\nExtract Constant BinNat.N.testbit_nat  => \"\\x b -> Data.Bits.testBit x (Prelude.fromInteger b)\".\nExtract Constant BinNat.N.testbit      => \"\\x b -> Data.Bits.testBit x (Prelude.fromInteger b)\".\nExtract Constant BinNat.N.to_nat       => \"Prelude.id\".\nExtract Constant BinNat.N.of_nat       => \"Prelude.id\".\nExtract Constant BinNat.N.eq_dec       => \"(Prelude.==)\".\nExtract Constant BinNat.N.lcm          => \"Prelude.lcm\".\nExtract Constant BinNat.N.setbit       => \"\\x b -> Data.Bits.setBit x (Prelude.fromInteger b)\".\nExtract Constant BinNat.N.clearbit     => \"\\x b -> Data.Bits.clearBit x (Prelude.fromInteger b)\".\n\nExtract Inductive int => \"Prelude.Integer\"\n                         [\"Prelude.id\" \"(Prelude.negate Prelude.. (Prelude.+1))\"]\n                         \"(\\fP fN n -> if n Prelude.>= 0 then fP n else fN (Prelude.abs n Prelude.- 1))\".\nExtract Constant intZmod.addz   => \"(Prelude.+)\".\nExtract Constant intZmod.oppz   => \"Prelude.negate\".\nExtract Constant intRing.mulz   => \"(Prelude.*)\".\nExtract Constant absz           => \"Prelude.abs\".\nExtract Constant intOrdered.lez => \"(Prelude.<=)\".\nExtract Constant intOrdered.ltz => \"(Prelude.<)\".\n(* intmul? (no)  exprz? (maybe)  sgz? (probably not) *)\n(* Extract Constant int_eqMixin    => \"Eqtype.coq_CanEqMixin (Prelude.==) (unsafeCoerce natsum_of_int) (unsafeCoerce int_of_natsum)\". *)\n(* ^ The above doesn't work because `(==)' needs to be an eqtype.  Thus,\n   equality will be a bit slower than it should be. *)\n\nExtract Constant intdiv.divz => \"\\x y -> unsafeCoerce (if y Prelude.== 0 then 0 else x `Prelude.div` y)\". (* I cannot BELIEVE I need unsafeCoerce here. *)\nExtract Constant intdiv.modz => \"\\x y -> if y Prelude.== 0 then x else x `Prelude.mod` Prelude.abs y\".\n\nExtract Inductive rat.rat => \"Prelude.Rational\" [\"(Prelude.uncurry (Data.Ratio.%))\"]\n                             \"(\\f q -> f (Data.Ratio.numerator q, Data.Ratio.denominator q))\".\nExtract Constant rat.valq   => \"\\q -> (Data.Ratio.numerator q, Data.Ratio.denominator q)\".\nExtract Constant rat.ratz   => \"Prelude.fromInteger\".\nExtract Constant rat.numq   => \"Data.Ratio.numerator\".\nExtract Constant rat.denq   => \"Data.Ratio.denominator\".\nExtract Constant rat.fracq  => \"Prelude.uncurry (Data.Ratio.%)\".\nExtract Constant rat.zeroq  => \"0\".\nExtract Constant rat.oneq   => \"1\".\nExtract Constant rat.addq   => \"(Prelude.+)\".\nExtract Constant rat.oppq   => \"Prelude.negate\".\nExtract Constant rat.mulq   => \"(Prelude.*)\".\nExtract Constant rat.invq   => \"Prelude.recip\".\nExtract Constant rat.subq   => \"(Prelude.-)\".\nExtract Constant rat.divq   => \"\\x y -> if y Prelude.== 0 then 0 else x Prelude./ y\".\nExtract Constant rat.le_rat => \"(Prelude.<=)\".\nExtract Constant rat.lt_rat => \"(Prelude.<)\".\n\n(* The `zmodp' stuff for Ordinals should mostly extract efficiently!  I'm not\n   sure about `Zp_inv', though, in particular its use of `div.egcdn'. *)\n\n(* Word arithmetic is left alone -- the bitwise hacks don't seem worth it, and\n   we can't just extract `word 32' to `Int32', so... yeah.  We do deal with the\n   bitwise stuff to avoid finfuns, though.  *)\n\nExtract Constant negw => \"\\k (Word w) -> as_word k (Data.Bits.complement w)\".\nExtract Constant andw => \"\\_ (Word w1) (Word w2) -> Word (w1  Data.Bits..&.  w2)\".\nExtract Constant orw  => \"\\_ (Word w1) (Word w2) -> Word (w1  Data.Bits..|.  w2)\".\nExtract Constant xorw => \"\\_ (Word w1) (Word w2) -> Word (w1 `Data.Bits.xor` w2)\".\n\nExtract Inductive set_type => \"Finset.Coq_set_type\"\n                              [\"(finsetAbstract \"\"FinSet constructor\"\")\"]\n                              \"(finsetAbstract \"\"FinSet case\"\")\".\nExtract Constant set_type_rect    => \"finsetAbstract \"\"set_type_rect\"\"\".\nExtract Constant set_type_rec     => \"finsetAbstract \"\"set_type_rec\"\"\".\nExtract Constant finfun_of_set    => \"finsetAbstract \"\"finfun_of_set\"\"\".\nExtract Constant SetDef.finset    => \"finsetAbstract \"\"SetDef.finset\"\"\".\nExtract Constant Imset.imset      => \"finsetAbstract \"\"Imset.imset\"\"\".\nExtract Constant Imset.imset2     => \"finsetAbstract \"\"Imset.imset2\"\"\".\nExtract Constant preimset         => \"finsetAbstract \"\"preimset\"\"\".\n(*\nExtract Constant set_subType      => \"finsetAbstract \"\"set_subType\"\"\".\nExtract Constant set_choiceMixin  => \"finsetAbstract \"\"set_choiceMixin\"\"\".\nExtract Constant set_choiceType   => \"finsetAbstract \"\"set_choiceType\"\"\".\nExtract Constant set_countMixin   => \"finsetAbstract \"\"set_countMixin\"\"\".\nExtract Constant set_countType    => \"finsetAbstract \"\"set_countType\"\"\".\nExtract Constant set_subCountType => \"finsetAbstract \"\"set_subCountType\"\"\".\nExtract Constant set_finMixin     => \"finsetAbstract \"\"set_finMixin\"\"\".\nExtract Constant set_finType      => \"finsetAbstract \"\"set_finType\"\"\".\nExtract Constant set_subFinType   => \"finsetAbstract \"\"set_subFinType\"\"\".\nExtract Constant set_predType     => \"finsetAbstract \"\"set_predType\"\"\".\n...\n*)\n\nExtract Constant set_eqMixin => \"withFintypeOrd' (Eqtype.equality__mixin (Prelude.==) (finsetAbstract \"\"set_eqMixin/eqP\"\"))\".\n\nExtract Constant SetDef.pred_of_set => \"withFintypeOrd' (unsafeCoerce Prelude.. Prelude.flip Data.Set.member)\".\n\nExtract Constant set0     => \"\\_ -> Data.Set.empty\".\nExtract Constant setTfor  => \"finsetFinite \"\"setTfor\"\"\".\nExtract Constant set1     => \"\\_ x -> Data.Set.singleton (unitAny x)\".\nExtract Constant setU     => \"withFintypeOrd' Data.Set.union\".\nExtract Constant setI     => \"withFintypeOrd' Data.Set.intersection\".\nExtract Constant setC     => \"finsetFinite \"\"setC\"\"\".\nExtract Constant setD     => \"withFintypeOrd' Data.Set.difference\".\nExtract Constant ssetI    => \"withFintypeOrd' (\\xss ys -> flattenedSet (Data.Set.filter (`Data.Set.isSubsetOf` ys) (nestedSet xss)))\".\nExtract Constant powerset => \"withFintypeOrd' (\\s -> flattenedSet (setPowerset s))\".\nExtract Constant setX     => \"\\_ _ xs ys ->\n  unsafeCoerce (Data.Set.fromDistinctAscList [ (x,y) | x <- Data.Set.toAscList xs\n                                                     , y <- Data.Set.toAscList ys ])\".\n  (* Due to Dan Weston's mailing list post at\n     https://mail.haskell.org/pipermail/haskell-cafe/2007-August/029859.html;\n     the proof obligation for `fromDistinctAscList' is fulfilled by\n     construction *)\n\n(* Not confident about the `unsafeCoerce' in this one *)\nExtract Constant set_0Vmem => \"\\_ s -> if Data.Set.null s then Prelude.Left () else Prelude.Right (unsafeCoerce (Data.Set.findMin s))\".\n\n(* Not sure about cover, pblock, trivIset, partition, is_transversal, transversal *)\n(* Also not sure about minset and maxset *)\n\n(* Cardinality *will* break, too *)\n\n(* `enum_set` is a specialized `enum` -- see `lib/ssr_set_utils.v` for why we\n   need it.  Since `lib.ssr_set_utils` is so small, it apparently doesn't have\n   `unsafeCoerce`, so we borrow one.*)\nExtract Constant enum_set => \"\\_ ->\n  (Finset.unsafeCoerce :: [GHC.Base.Any] -> [()]) Prelude.. Data.Set.toList\".\n\n(* We extract `atom` specially just for a better name.  We could do this for\n   other types (e.g. `Coq_binop` -> `Binop`, but atoms get more use and really\n   benefit from the fancy constructor. *)\nExtract Inductive atom  => \"Types.Atom\" [\"(Types.:@)\"].\n\n(* `isolate_get_range' needs to be fixed up --\n   `[set i : mword mt in some_predicate]` uses the `finfun' machinery!  So we\n   just reimplement a mix of the extracted version (in the `let`), the Coq\n   version (using Haskell's `do` notation), and replace the `[set i ...]` stuff\n   with a Haskell `[l..h]` range!  We can safely do this by moving in and out of\n   `Coq_word` without checks, since everything between `l` and `h` is guaranteed\n   to be a valid word.  Since `compartmentalization.isolate_sets` is so small,\n   it apparently doesn't have `__`, so we borrow one. *)\nExtract Constant isolate_get_range => \"\\mt to_word m p -> do {\n  let { wsz      = Types.word_size mt ;\n        get_m    = Partmap.getm (Word.word_ordType wsz) m Prelude.. unsafeCoerce ;\n        add1     = Prelude.flip (Word.addw wsz) (Word.onew wsz) ;\n        to_hsInt = Word.ord_of_word Types.__ Prelude.. to_word ;\n        fromList = Finset.forgetToCoqSet Prelude.. Data.Set.fromList } ;\n  low  <- get_m p ;\n  high <- get_m (add1 p) ;\n  Prelude.Just (fromList (Prelude.map Word.Word [to_hsInt low .. to_hsInt high])) }\".\n\n(* eqtypes get included comparator functions -- the definition of the type is\n   stored in extra/eqtype.hs *)\nExtract Inductive Equality.mixin_of => \"Eqtype.Equality__Coq_mixin_of\" [\"Eqtype.equality__mixin\"]\n                                       \"(\\f em -> case em of Eqtype.Equality__Mixin eqb eqP _ -> f eqb eqP)\".\nExtract Constant sub_eqMixin => \"\\t p sT ->\n  Equality__Mixin\n    (\\x y -> eq_op t (val p sT x) (val p sT y))\n    (val_eqP t p sT)\n    (\\x y -> compare_op t (val p sT x) (val p sT y))\".\nExtract Constant SubEqMixin => \"\\t p sT ->\n  let {vP = val_eqP t p sT} in\n  case sT of {\n   SubType v sub p0 ->\n     Equality__Mixin\n       (\\x y -> eq_op t (v x) (v y))\n       vP\n       (\\x y -> compare_op t (v x) (v y))\n  }\".\nExtract Constant sig_eqMixin => \"\\t p ->\n  Equality__Mixin\n    (\\x y -> eq_op t (Specif.proj1_sig x) (Specif.proj1_sig y))\n    (unsafeCoerce (val_eqP t (\\x -> p x) (sig_subType p)))\n    (\\x y -> compare_op t (Specif.proj1_sig x) (Specif.proj1_sig y))\".\nExtract Constant prod_eqMixin => \"\\t1 t2 ->\n  Equality__Mixin\n    (Ssrbool.rel_of_simpl_rel (pair_eq t1 t2))\n    (pair_eqP t1 t2)\n    (\\(x1,x2) (y1,y2) -> compare_op t1 x1 y1 Data.Monoid.<> compare_op t2 x2 y2)\".\nExtract Constant option_eqMixin => \"\\t ->\n  Equality__Mixin (opt_eq t) (opt_eqP t)\n    (\\mx my -> case (mx,my) of {\n                 (Prelude.Nothing, Prelude.Nothing) -> Prelude.EQ;\n                 (Prelude.Nothing, Prelude.Just _)  -> Prelude.LT;\n                 (Prelude.Just _,  Prelude.Nothing) -> Prelude.GT;\n                 (Prelude.Just x,  Prelude.Just y)  -> compare_op t x y})\".\nExtract Constant tag_eqMixin => \"\\i t_ ->\n  Equality__Mixin (tag_eq i t_) (tag_eqP i t_)\n                  (\\x1 x2 -> compare_op i             (tag x1)    (tag x2) Data.Monoid.<>\n                             compare_op (t_ (tag x1)) (tagged x1) (tagged_as i x1 x2))\".\nExtract Constant sum_eqMixin => \"\\t1 t2 ->\n  Equality__Mixin (sum_eq t1 t2) (sum_eqP t1 t2)\n    (\\x12 y12 -> case (x12, y12) of {\n                   (Prelude.Left  x1, Prelude.Left  y1) -> compare_op t1 x1 y1;\n                   (Prelude.Right x2, Prelude.Right y2) -> compare_op t2 x2 y2;\n                   (Prelude.Left  _,  Prelude.Right _)  -> Prelude.LT;\n                   (Prelude.Right _,  Prelude.Left  _)  -> Prelude.GT })\".\n\n(* The type `finfun_type` is horribly inefficient, but I don't believe we ever\n   use it, as long as we extract sets properly. *)\nExtract Constant finfun.eqMixin => \"\\aT rT ->\n  Eqtype.Equality__Mixin (\\x y ->\n    Eqtype.eq_op\n      (Tuple.tuple_eqType\n        (Fintype._CardDef__card aT\n          (Ssrbool.mem Ssrbool.predPredType\n            (Ssrbool.sort_of_simpl_pred Ssrbool.pred_of_argType))) rT)\n      (unsafeCoerce (fgraph aT x)) (unsafeCoerce (fgraph aT y)))\n    (unsafeCoerce\n      (Eqtype.val_eqP\n        (Tuple.tuple_eqType\n          (Fintype._CardDef__card aT\n            (Ssrbool.mem Ssrbool.predPredType\n              (Ssrbool.sort_of_simpl_pred Ssrbool.pred_of_argType))) rT)\n        (\\x -> Prelude.True) (unsafeCoerce (finfun_subType aT))))\n    (\\x y ->\n      Eqtype.compare_op\n        (Tuple.tuple_eqType\n          (Fintype._CardDef__card aT\n            (Ssrbool.mem Ssrbool.predPredType\n              (Ssrbool.sort_of_simpl_pred Ssrbool.pred_of_argType))) rT)\n        (unsafeCoerce (fgraph aT x)) (unsafeCoerce (fgraph aT y)))\".\n\nExtract Constant fingroup.group_eqMixin => \"\\gT ->\n  Eqtype.Equality__Mixin (\\x y ->\n    Eqtype.eq_op (group_set_eqType (_FinGroup__base gT))\n      (unsafeCoerce (gval gT x)) (unsafeCoerce (gval gT y)))\n    (unsafeCoerce\n      (Eqtype.val_eqP (group_set_eqType (_FinGroup__base gT))\n        (unsafeCoerce (group_set gT)) (unsafeCoerce (group_subType gT))))\n    (\\x y ->\n      Eqtype.compare_op (group_set_eqType (_FinGroup__base gT))\n        (unsafeCoerce (gval gT x)) (unsafeCoerce (gval gT y)))\".\n\nExtract Constant fingroup.subg_eqMixin => \"\\gT g ->\n  Eqtype.Equality__Mixin (\\x y ->\n    Eqtype.eq_op (_FinGroup__arg_eqType (_FinGroup__base gT)) (sgval gT g x)\n      (sgval gT g y))\n    (unsafeCoerce\n      (Eqtype.val_eqP (_FinGroup__arg_eqType (_FinGroup__base gT)) (\\x ->\n        Ssrbool.in_mem x\n          (Ssrbool.mem Ssrbool.predPredType\n            (Finset._SetDef__pred_of_set\n              (_FinGroup__arg_finType (_FinGroup__base gT)) (gval gT g))))\n        (subg_subType gT g)))\n    (\\x y ->\n      Eqtype.compare_op (_FinGroup__arg_eqType (_FinGroup__base gT)) (sgval gT g x)\n        (sgval gT g y))\".\n\nExtract Constant choice.tree_eqMixin => \"\\t ->\n  let { (<=>) :: GenTree__Coq_tree Eqtype.Equality__Coq_sort\n              -> GenTree__Coq_tree Eqtype.Equality__Coq_sort\n              -> Prelude.Ordering\n      ; GenTree__Leaf x    <=> GenTree__Leaf y    = Eqtype.compare_op t x y\n      ; GenTree__Leaf _    <=> GenTree__Node _ _  = Prelude.LT\n      ; GenTree__Node _ _  <=> GenTree__Leaf _    = Prelude.GT\n      ; GenTree__Node m xs <=> GenTree__Node n ys =\n          (m `Prelude.compare` n) Data.Monoid.<>\n          (Eqtype.compare_op\n            (unsafeCoerce (Seq.seq_eqMixin (unsafeCoerce (tree_eqMixin t))))\n            (unsafeCoerce xs)\n            (unsafeCoerce ys)) }\n  in Data.Reflection.Constraint.providing (Data.Reflection.Constraint.Ord (<=>))\n       (Eqtype.coq_PcanEqMixin\n          (Seq.seq_eqType (Eqtype.sum_eqType Ssrnat.nat_eqType t))\n          (unsafeCoerce _GenTree__encode) (unsafeCoerce _GenTree__decode))\".\n\nExtract Constant fintype.seq_sub_eqMixin => \"\\t s ->\n  Eqtype.Equality__Mixin (\\x y ->\n    Eqtype.eq_op (Choice._Choice__eqType t) (ssval t s x) (ssval t s y))\n    (unsafeCoerce\n      (Eqtype.val_eqP (Choice._Choice__eqType t) (\\x ->\n        Ssrbool.in_mem x\n          (Ssrbool.mem (Seq.seq_predType (Choice._Choice__eqType t))\n            (unsafeCoerce s))) (seq_sub_subType t s)))\n    (\\x y -> Eqtype.compare_op (Choice._Choice__eqType t) (ssval t s x) (ssval t s y))\".\n\nExtract Constant hseq.hseq_eqMixin => \"\\t_ idx ->\n  Eqtype.Equality__Mixin (hseq_eq t_ idx) (hseq_eqP t_ idx) (hseq_compare t_ idx)\".\nExtract Constant hseq.HSeqChoiceType.hseq_choiceMixin =>\n  \"GHC.Stack.errorWithStackTrace \"\"_HSeqChoiceType__hseq_choiceMixin: failed to compile with infinite type errors\"\"\".\n\nExtract Constant poly.polynomial_eqMixin => \"\\r ->\n  Eqtype.Equality__Mixin (\\x y ->\n    Eqtype.eq_op (Seq.seq_eqType (Ssralg._GRing__Ring__eqType r))\n      (unsafeCoerce (polyseq r x)) (unsafeCoerce (polyseq r y)))\n    (unsafeCoerce\n      (Eqtype.val_eqP (Seq.seq_eqType (Ssralg._GRing__Ring__eqType r)) (\\x ->\n        Datatypes.negb\n          (Eqtype.eq_op (Ssralg._GRing__Ring__eqType r)\n            (Seq.last (Ssralg._GRing__one r) (unsafeCoerce x))\n            (Ssralg._GRing__zero (Ssralg._GRing__Ring__zmodType r))))\n        (unsafeCoerce (polynomial_subType r))))\n    (\\x y ->\n      Eqtype.compare_op (Seq.seq_eqType (Ssralg._GRing__Ring__eqType r))\n        (unsafeCoerce (polyseq r x)) (unsafeCoerce (polyseq r y)))\".\n\nExtract Constant quotient.coset_eqMixin => \"\\gT a ->\n  Eqtype.Equality__Mixin (\\x y ->\n    Eqtype.eq_op (Fingroup.group_set_eqType (Fingroup._FinGroup__base gT))\n      (unsafeCoerce (set_of_coset gT a x))\n      (unsafeCoerce (set_of_coset gT a y)))\n    (unsafeCoerce\n      (Eqtype.val_eqP\n        (Fingroup.group_set_eqType (Fingroup._FinGroup__base gT))\n        (Ssrbool.pred_of_simpl (coset_range gT a))\n        (unsafeCoerce (coset_subType gT a))))\n    (\\x y ->\n      Eqtype.compare_op (Fingroup.group_set_eqType (Fingroup._FinGroup__base gT))\n        (unsafeCoerce (set_of_coset gT a x))\n        (unsafeCoerce (set_of_coset gT a y)))\".\n\nExtract Constant seq_eqMixin => \"\\t ->\n  let {[]     <=> []     = Prelude.EQ;\n       []     <=> (_:_)  = Prelude.LT;\n       (_:_)  <=> []     = Prelude.GT;\n       (x:xs) <=> (y:ys) = Eqtype.compare_op t x y Data.Monoid.<> xs <=> ys}\n  in Eqtype.Equality__Mixin (eqseq t) (eqseqP t) (<=>)\".\n\nExtract Constant tuple.tuple_eqMixin => \"\\n t ->\n  Eqtype.Equality__Mixin (\\x y ->\n    Eqtype.eq_op (Seq.seq_eqType t) (unsafeCoerce (tval n x))\n      (unsafeCoerce (tval n y)))\n    (unsafeCoerce\n      (Eqtype.val_eqP (Seq.seq_eqType t) (\\x ->\n        Eqtype.eq_op Ssrnat.nat_eqType\n          (unsafeCoerce (Seq.size (unsafeCoerce x))) (unsafeCoerce n))\n        (unsafeCoerce (tuple_subType n))))\n    (\\x y ->\n      Eqtype.compare_op\n        (Seq.seq_eqType t)\n        (unsafeCoerce (tval n x))\n        (unsafeCoerce (tval n y)))\".\n\nExtract Constant atom_eqMixin => \"\\vEM tEM ->\n  Eqtype.Equality__Mixin\n    (atom_eqb  vEM tEM)\n    (atom_eqbP vEM tEM)\n    (\\(v1 :@ t1) (v2 :@ t2) ->\n        Eqtype.compare_op vEM v1 v2 Data.Monoid.<> Eqtype.compare_op tEM t1 t2)\".\n\nExtract Constant symbolic.Exports.state_eqMixin => \"\\mt p ->\n  Eqtype.Equality__Mixin\n    (_Exports__state_eqb  mt p)\n    (_Exports__state_eqbP mt p)\n    (_Exports__state_cmp  mt p)\".\n\nExtract Constant data_tag_eqMixin => \"\\mt ->\n  Eqtype.Equality__Mixin\n    (_Sym__Exports__data_tag_eq  mt)\n    (_Sym__Exports__data_tag_eqP mt)\n    (_Sym__Exports__data_tag_cmp mt)\".\n\nExtract Constant Sym.compartmentalization_internal_eqMixin => \"\\mt ->\n  Eqtype.Equality__Mixin\n    (_Sym__compartmentalization_internal_eqb  mt)\n    (_Sym__compartmentalization_internal_eqbP mt)\n    (_Sym__compartmentalization_internal_cmp  mt)\".\n\nExtract Constant concrete.Exports.state_eqMixin => \"\\mt ->\n  Eqtype.Equality__Mixin\n    (_Exports__state_eqb  mt)\n    (_Exports__state_eqbP mt)\n    (_Exports__state_cmp  mt)\".\n\nExtract Constant rules.mtag_eqMixin => \"\\tty ->\n  let { (<=>) :: Coq_mtag -> Coq_mtag -> Prelude.Ordering\n      ; User  u1 <=> User  u2 = Eqtype.compare_op (Symbolic._Symbolic__mem_tag_type   tty) u1 u2\n      ; Entry e1 <=> Entry e2 = Eqtype.compare_op (Symbolic._Symbolic__entry_tag_type tty) e1 e2\n      ; User  _  <=> Entry _  = Prelude.LT\n      ; Entry _  <=> User  _  = Prelude.GT }\n  in Data.Reflection.Constraint.providing (Data.Reflection.Constraint.Ord (<=>))\n       (Eqtype.coq_CanEqMixin\n         (Eqtype.sum_eqType\n           (Symbolic._Symbolic__mem_tag_type tty)\n           (Symbolic._Symbolic__entry_tag_type tty))\n         (unsafeCoerce (sum_of_mtag tty))\n         (unsafeCoerce (mtag_of_sum tty)))\".\n\n(* The following function, when extracted, fail to typecheck and I don't\n   understand why -- or much care. *)\nExtract Constant generic_quotient.enc_mod_rel =>\n  \"GHC.Stack.errorWithStackTrace \"\"enc_mod_rel: failed to compile with a type error\"\"\".\n\n(* I've ignored most of the pure math stuff in MathComp (beyond what was\n   necessary for the `eqType' change) -- we don't use it, and it's quite\n   complicated.  This includes polynomials and matrices/linear algebra -- we\n   certainly *could* use those things (they aren't super pure), but we don't,\n   and there's plenty of extraction work already. *)\n\n(* `concrete/exec.v'                  -> `exec.hs'\n   `symbolic/exec.v'                  -> `exec0.hs'\n   `concrete/int_32.v'                -> `int_32.hs'\n   `symbolic/int_32.v'                -> `int_0.hs'\n   `symbolic/symbolic.v'              -> `symbolic.hs'\n   `compartmentalization/symbolic.hs' -> `symbolic0.hs' *)\n", "meta": {"author": "micro-policies", "repo": "micro-policies-coq", "sha": "28163163c88387fc24475ed219f5705f9e0d4fc6", "save_path": "github-repos/coq/micro-policies-micro-policies-coq", "path": "github-repos/coq/micro-policies-micro-policies-coq/micro-policies-coq-28163163c88387fc24475ed219f5705f9e0d4fc6/extraction/extraction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23004915594047903}}
{"text": "\nRequire Export Iron.Language.SystemF2Effect.Type.\nRequire Export Iron.Language.SystemF2Effect.Value.\nRequire Export Iron.Language.SystemF2Effect.Step.Pure.\nRequire Export Iron.Language.SystemF2Effect.Store.Prop.\n\n\n(********************************************************************)\n(* Frames *)\nInductive frame : Set :=\n (* Holds the continuation of a let-expression while the right\n    of the binding is being evaluated. *)\n | FLet   : ty  -> exp      -> frame\n\n (* Private region.\n    If the first argument is some region identifier then this new\n    private region will be merged with that one when leaving its scope, \n    otherwise the region is deallocated. *)\n | FPriv  : option nat -> nat -> frame.\nHint Constructors frame.\n\n\nDefinition isFPriv (p2 : nat) (f : frame)\n := exists p1, f = FPriv p1 p2.\nHint Unfold isFPriv.\n\n\n(* Frame stacks *)\nDefinition stack := list frame.\nHint Unfold stack.\n\n\n(********************************************************************)\n(* Context sensitive reductions. *)\nInductive \n StepF :  store -> stprops -> stack -> exp \n       -> store -> stprops -> stack -> exp \n       -> Prop :=\n\n (* Pure evaluation *****************************)\n (* Pure evaluation in a context. *)\n | SfStep\n   :  forall ss sp fs x x'\n   ,  StepP           x           x'\n   -> StepF  ss sp fs x  ss sp fs x'\n\n (* Let contexts ********************************)\n (* Push the continuation for a let-expression onto the stack. *)\n | SfLetPush\n   :  forall ss sp fs t x1 x2\n   ,  StepF  ss sp  fs               (XLet t x1 x2)\n             ss sp (fs :> FLet t x2)  x1\n\n (* Substitute value of the bound variable into the let body. *)\n | SfLetPop\n   :  forall ss sp  fs t v1 x2\n   ,  StepF  ss sp (fs :> FLet t x2) (XVal v1)\n             ss sp  fs               (substVX 0 v1 x2)\n\n (* Region operators ****************************)\n (* Create a private region. *)\n | SfPrivatePush\n   :  forall ss sp fs x p\n   ,  p = allocRegion sp\n   -> StepF  ss sp                       fs                  (XPrivate x)\n             ss (SRegion p <: sp)       (fs :> FPriv None p) (substTX 0 (TRgn p) x)\n\n (* Pop the frame for a private region and delete it from the heap. *)\n | SfPrivatePop\n   :  forall ss sp  fs v1 p\n   ,  StepF  ss                         sp (fs :> FPriv None p) (XVal v1)\n             (map (deallocRegion p) ss) sp  fs                  (XVal v1)\n\n (* Begin extending an existing region. *)\n | SfExtendPush\n   :  forall ss sp fs x p1 p2\n   ,  p2 = allocRegion sp\n   -> StepF ss sp                  fs                        (XExtend (TRgn p1) x)\n            ss (SRegion p2 <: sp) (fs :> FPriv (Some p1) p2) (substTX 0 (TRgn p2) x)\n\n (* Pop the frame for a region extension and merge it with the existing one. *)\n | SfExtendPop\n   :  forall ss sp fs p1 p2 v1\n   ,  StepF  ss                      sp (fs :> FPriv (Some p1) p2) (XVal v1)\n             (map (mergeB p1 p2) ss) sp fs                   (XVal (mergeV p1 p2 v1))\n\n (* Store operators *****************************)\n (* Allocate a reference. *) \n | SfStoreAlloc\n   :  forall ss sp fs p1 v1\n   ,  StepF  ss                    sp  fs (XAlloc (TRgn p1) v1)\n             (StValue p1 v1 <: ss) sp  fs (XVal (VLoc (length ss)))\n\n (* Read from a reference. *)\n | SfStoreRead\n   :  forall ss sp fs l v p\n   ,  get l ss = Some (StValue p v)\n   -> StepF ss                     sp  fs (XRead (TRgn p)  (VLoc l)) \n            ss                     sp  fs (XVal v)\n\n (* Write to a reference. *)\n | SfStoreWrite\n   :  forall ss sp fs l p v1 v2 \n   ,  get l ss = Some (StValue p v1)\n   -> StepF  ss sp fs                 (XWrite (TRgn p) (VLoc l) v2)\n             (update l (StValue p v2) ss) sp fs (XVal (VConst CUnit)).\n\nHint Constructors StepF.\n\n\n\n(********************************************************************)\nLemma stepF_extends_stprops\n :  forall  ss1 sp1 fs1 x1  ss2 sp2 fs2 x2\n ,  StepF   ss1 sp1 fs1 x1  ss2 sp2 fs2 x2\n -> extends sp2 sp1.\nProof.\n intros. \n induction H; eauto.\nQed.\n\n", "meta": {"author": "discus-lang", "repo": "iron", "sha": "75c007375eb62e1c0be4b8b8eb17a0fe66880039", "save_path": "github-repos/coq/discus-lang-iron", "path": "github-repos/coq/discus-lang-iron/iron-75c007375eb62e1c0be4b8b8eb17a0fe66880039/done/Iron/Language/SystemF2Effect/Step/Frame.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23004915594047903}}
{"text": "(* Default settings (from HsToCoq.Coq.Preamble) *)\n\nGeneralizable All Variables.\n\nUnset Implicit Arguments.\nSet Maximal Implicit Insertion.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Coq.Program.Tactics.\nRequire Coq.Program.Wf.\n\n(* Converted imports: *)\n\nRequire Data.Graph.Inductive.Graph.\nRequire Data.Graph.Inductive.Internal.Heap.\nRequire Data.Graph.Inductive.Internal.RootPath.\nRequire Err.\nRequire GHC.Base.\nRequire GHC.DeferredFix.\nRequire GHC.Err.\nRequire GHC.Num.\nRequire GHC.Real.\nImport GHC.Base.Notations.\nImport GHC.Num.Notations.\n\n(* No type declarations to convert. *)\n\n(* Midamble *)\n\nProgram Instance Dijkstra_Default {b} `{Err.Default b} : Err.Default (b * Data.Graph.Inductive.Graph.LPath b *\n                                    Data.Graph.Inductive.Internal.Heap.Heap b (Data.Graph.Inductive.Graph.LPath b)).\nNext Obligation.\ndestruct H. apply (default, Data.Graph.Inductive.Graph.LP nil, Data.Graph.Inductive.Internal.Heap.empty).\nDefined.\n(* Converted value declarations: *)\n\nDefinition expand {b} {a} `{(GHC.Real.Real b)}\n   : b ->\n     Data.Graph.Inductive.Graph.LPath b ->\n     Data.Graph.Inductive.Graph.Context a b ->\n     list (Data.Graph.Inductive.Internal.Heap.Heap b\n           (Data.Graph.Inductive.Graph.LPath b)) :=\n  fun arg_0__ arg_1__ arg_2__ =>\n    match arg_0__, arg_1__, arg_2__ with\n    | d, Data.Graph.Inductive.Graph.LP p, pair (pair (pair _ _) _) s =>\n        GHC.Base.map (fun '(pair l v) =>\n                        Data.Graph.Inductive.Internal.Heap.unit (l GHC.Num.+ d)\n                        (Data.Graph.Inductive.Graph.LP (cons (pair v (l GHC.Num.+ d)) p))) s\n    end.\n\nDefinition dijkstra {gr} {b} {a} `{Data.Graph.Inductive.Graph.Graph gr}\n  `{GHC.Real.Real b} `{Err.Default b}\n   : Data.Graph.Inductive.Internal.Heap.Heap b (Data.Graph.Inductive.Graph.LPath\n                                              b) ->\n     gr a b -> Data.Graph.Inductive.Internal.RootPath.LRTree b :=\n  GHC.DeferredFix.deferredFix2 (fun dijkstra\n                                (arg_0__\n                                  : Data.Graph.Inductive.Internal.Heap.Heap b (Data.Graph.Inductive.Graph.LPath\n                                                                             b))\n                                (arg_1__ : gr a b) =>\n                                  match arg_0__, arg_1__ with\n                                  | h, g =>\n                                      if orb (Data.Graph.Inductive.Internal.Heap.isEmpty h)\n                                             (Data.Graph.Inductive.Graph.isEmpty g) : bool\n                                      then nil else\n                                      match arg_0__, arg_1__ with\n                                      | h, g =>\n                                          match Data.Graph.Inductive.Internal.Heap.splitMin h with\n                                          | pair (pair _ (Data.Graph.Inductive.Graph.LP (cons (pair v d) _) as p)) h' =>\n                                              match Data.Graph.Inductive.Graph.match_ v g with\n                                              | pair (Some c) g' =>\n                                                  cons p (dijkstra (Data.Graph.Inductive.Internal.Heap.mergeAll (cons h'\n                                                                                                                      (expand\n                                                                                                                       d\n                                                                                                                       p\n                                                                                                                       c)))\n                                                        g')\n                                              | pair None g' => dijkstra h' g'\n                                              end\n                                          | _ => GHC.Err.patternFailure\n                                          end\n                                      end\n                                  end).\n\nDefinition spTree {gr} {b} {a} `{Data.Graph.Inductive.Graph.Graph gr}\n  `{GHC.Real.Real b}\n   : Data.Graph.Inductive.Graph.Node ->\n     gr a b -> Data.Graph.Inductive.Internal.RootPath.LRTree b :=\n  fun v =>\n    dijkstra (Data.Graph.Inductive.Internal.Heap.unit #0\n              (Data.Graph.Inductive.Graph.LP (cons (pair v #0) nil))).\n\nDefinition sp {gr} {b} {a} `{Data.Graph.Inductive.Graph.Graph gr}\n  `{GHC.Real.Real b}\n   : Data.Graph.Inductive.Graph.Node ->\n     Data.Graph.Inductive.Graph.Node ->\n     gr a b -> option Data.Graph.Inductive.Graph.Path :=\n  fun s t g =>\n    match Data.Graph.Inductive.Internal.RootPath.getLPathNodes t (spTree s g) with\n    | nil => None\n    | p => Some p\n    end.\n\nDefinition spLength {gr} {b} {a} `{Data.Graph.Inductive.Graph.Graph gr}\n  `{GHC.Real.Real b}\n   : Data.Graph.Inductive.Graph.Node ->\n     Data.Graph.Inductive.Graph.Node -> gr a b -> option b :=\n  fun s t =>\n    Data.Graph.Inductive.Internal.RootPath.getDistance t GHC.Base.∘ spTree s.\n\n(* External variables:\n     None Some bool cons list nil option orb pair Data.Graph.Inductive.Graph.Context\n     Data.Graph.Inductive.Graph.Graph Data.Graph.Inductive.Graph.LP\n     Data.Graph.Inductive.Graph.LPath Data.Graph.Inductive.Graph.Node\n     Data.Graph.Inductive.Graph.Path Data.Graph.Inductive.Graph.isEmpty\n     Data.Graph.Inductive.Graph.match_ Data.Graph.Inductive.Internal.Heap.Heap\n     Data.Graph.Inductive.Internal.Heap.isEmpty\n     Data.Graph.Inductive.Internal.Heap.mergeAll\n     Data.Graph.Inductive.Internal.Heap.splitMin\n     Data.Graph.Inductive.Internal.Heap.unit\n     Data.Graph.Inductive.Internal.RootPath.LRTree\n     Data.Graph.Inductive.Internal.RootPath.getDistance\n     Data.Graph.Inductive.Internal.RootPath.getLPathNodes Err.Default GHC.Base.map\n     GHC.Base.op_z2218U__ GHC.DeferredFix.deferredFix2 GHC.Err.patternFailure\n     GHC.Num.fromInteger GHC.Num.op_zp__ GHC.Real.Real\n*)\n", "meta": {"author": "antalsz", "repo": "hs-to-coq", "sha": "cd62a35fff22cb6022a8935581746df658264f0f", "save_path": "github-repos/coq/antalsz-hs-to-coq", "path": "github-repos/coq/antalsz-hs-to-coq/hs-to-coq-cd62a35fff22cb6022a8935581746df658264f0f/examples/graph/lib/Data/Graph/Inductive/Query/SP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23004914983137886}}
{"text": "From Perennial.program_proof Require Import disk_prelude.\n\nSection goose.\nContext `{!heapGS Σ}.\nImplicit Types v : val.\nImplicit Types z : Z.\nImplicit Types s : Slice.t.\nImplicit Types (stk:stuckness) (E: coPset).\n\nDefinition is_block (s:Slice.t) (q: Qp) (b:Block) :=\n  is_slice_small s byteT q (Block_to_vals b).\n\nDefinition is_block_full (s:Slice.t) (b:Block) :=\n  is_slice s byteT 1 (Block_to_vals b).\n\nGlobal Instance is_block_timeless s q b :\n  Timeless (is_block s q b) := _.\n\nGlobal Instance is_block_fractional s b :\n  fractional.Fractional (λ q, is_block s q b).\nProof. apply is_slice_small_fractional. Qed.\n\nTheorem is_block_not_nil s q b :\n  is_block s q b -∗\n  ⌜ s ≠ Slice.nil ⌝.\nProof.\n  iIntros \"Hb\".\n  rewrite /is_block.\n  iDestruct (is_slice_small_not_null with \"Hb\") as \"%Hnull\"; eauto.\n  { rewrite /Block_to_vals fmap_length.\n    rewrite vec_to_list_length.\n    rewrite /block_bytes. lia. }\n  iPureIntro.\n  destruct s. rewrite /Slice.nil. simpl in *. congruence.\nQed.\n\nDefinition list_to_block (l: list u8) : Block :=\n  match decide (length l = Z.to_nat 4096) with\n  | left H => eq_rect _ _ (list_to_vec l) _ H\n  | _ => inhabitant\n  end.\n\nLemma vec_to_list_to_vec_eq_rect A (l: list A) n (H: length l = n) :\n  vec_to_list (eq_rect _ _ (list_to_vec l) _ H) = l.\nProof.\n  rewrite <- H; simpl.\n  rewrite vec_to_list_to_vec.\n  auto.\nQed.\n\nTheorem list_to_block_to_list l :\n  length l = Z.to_nat 4096 ->\n  vec_to_list (list_to_block l) = l.\nProof.\n  intros H.\n  rewrite /list_to_block /Block_to_vals.\n  rewrite decide_True_pi.\n  rewrite vec_to_list_to_vec_eq_rect; auto.\nQed.\n\nTheorem list_to_block_to_vals l :\n  length l = Z.to_nat 4096 ->\n  Block_to_vals (list_to_block l) = b2val <$> l.\nProof.\n  intros H.\n  rewrite /Block_to_vals list_to_block_to_list //.\nQed.\n\nTheorem block_list_inj l (b: Block) :\n  l = vec_to_list b →\n  b = list_to_block l.\nProof.\n  intros ->.\n  apply vec_to_list_inj2.\n  rewrite list_to_block_to_list //.\n  rewrite vec_to_list_length //.\nQed.\n\nTheorem block_to_list_to_block i :\n  list_to_block (vec_to_list i) = i.\nProof.\n  symmetry.\n  apply block_list_inj.\n  auto.\nQed.\n\nLemma array_to_block l q (bs: list byte) :\n  length bs = Z.to_nat 4096 ->\n  l ↦∗[byteT]{q} (b2val <$> bs) -∗ mapsto_block l q (list_to_block bs).\nProof.\n  rewrite /array /mapsto_block.\n  iIntros (H) \"Hl\".\n  rewrite -> list_to_block_to_vals by auto.\n  rewrite heap_array_to_list.\n  rewrite !big_sepL_fmap.\n  setoid_rewrite Z.mul_1_l.\n  iApply (big_sepL_impl with \"Hl\"); simpl.\n  iModIntro.\n  iIntros (i x) \"% Hl\".\n  iApply (byte_mapsto_untype with \"Hl\").\nQed.\n\nLemma array_to_block_array l q b :\n  array l q byteT (Block_to_vals b) ⊣⊢ mapsto_block l q b.\nProof.\n  rewrite /mapsto_block /array.\n  rewrite heap_array_to_list.\n  rewrite ?big_sepL_fmap.\n  setoid_rewrite Z.mul_1_l.\n  apply big_opL_proper.\n  intros k y Heq.\n  rewrite /Block_to_vals in Heq.\n  rewrite /b2val.\n  rewrite byte_mapsto_untype //.\nQed.\n\nLemma slice_to_block_array s q b :\n  is_slice_small s byteT q (Block_to_vals b) -∗ mapsto_block s.(Slice.ptr) q b.\nProof.\n  rewrite /is_slice_small.\n  iIntros \"[Ha _]\".\n  by iApply array_to_block_array.\nQed.\n\nLemma block_array_to_slice_raw l q b :\n  mapsto_block l q b -∗ l ↦∗[byteT]{q} Block_to_vals b ∗ ⌜length (Block_to_vals b) = int.nat 4096⌝.\nProof.\n  iIntros \"Hm\".\n  rewrite /is_slice_small.\n  iSplitL.\n  { iApply array_to_block_array. done. }\n  iPureIntro.\n  rewrite length_Block_to_vals.\n  simpl. done.\nQed.\n\nTransparent disk.Read disk.Write.\n\nLtac inv_undefined :=\n  match goal with\n  | [ H: relation.denote (match ?e with | _ => _ end) _ _ _ |- _ ] =>\n    destruct e; try (apply suchThat_false in H; contradiction)\n  end.\n\nLocal Ltac solve_atomic :=\n  apply strongly_atomic_atomic, ectx_language_atomic;\n  [ apply heap_head_atomic; cbn [relation.denote head_trans]; intros * H;\n    repeat inv_undefined;\n    try solve [ apply atomically_is_val in H; auto ]\n    |apply ectxi_language_sub_redexes_are_values; intros [] **; naive_solver].\n\nTheorem wp_Write_atomic (a: u64) s q b :\n  ⊢ {{{ is_slice_small s byteT q (Block_to_vals b) }}}\n  <<< ∀∀ b0, int.Z a d↦ b0 >>>\n    Write #a (slice_val s) @ ∅\n  <<< int.Z a d↦ b >>>\n  {{{ RET #(); is_slice_small s byteT q (Block_to_vals b) }}}.\nProof.\n  iIntros \"!#\" (Φ) \"Hs Hupd\".\n  wp_call.\n  wp_call.\n  iDestruct (is_slice_small_sz with \"Hs\") as %Hsz.\n  iDestruct (is_slice_small_wf with \"Hs\") as %Hwf.\n  iApply (wp_ncatomic _ _ ∅).\n  { solve_atomic. inversion H. subst. monad_inv. inversion H0. subst. inversion H2. subst.\n    inversion H4. subst. inversion H6. subst. inversion H7. econstructor. eauto. }\n  rewrite difference_empty_L.\n  iMod \"Hupd\" as (b0) \"[Hda Hupd]\"; iModIntro.\n  wp_apply (wp_WriteOp with \"[Hda Hs]\").\n  { iIntros \"!>\".\n    iExists b0.\n    iFrame.\n    by iApply slice_to_block_array. }\n  iIntros \"[Hda Hmapsto]\".\n  iMod (\"Hupd\" with \"Hda\") as \"HQ\".\n  iModIntro.\n  iApply \"HQ\".\n  rewrite /is_slice_small.\n  iFrame.\n  iSplitL; auto.\n  by iApply array_to_block_array.\nQed.\n\nTheorem wp_Write_triple E' (Q: iProp Σ) (a: u64) s q b :\n  {{{ is_slice_small s byteT q (Block_to_vals b) ∗\n      (|NC={⊤,E'}=> ∃ b0, int.Z a d↦ b0 ∗ (int.Z a d↦ b -∗ |NC={E',⊤}=> Q)) }}}\n    Write #a (slice_val s)\n  {{{ RET #(); is_slice_small s byteT q (Block_to_vals b) ∗ Q }}}.\nProof.\n  iIntros (Φ) \"[Hs Hupd] HΦ\". iApply (wp_Write_atomic with \"Hs\").\n  rewrite difference_empty_L. iNext.\n  iMod \"Hupd\" as (b0) \"[Hda Hclose]\".\n  iApply ncfupd_mask_intro; first set_solver+.\n  iIntros \"HcloseE\". iExists b0.\n  iFrame. iIntros \"Hda\". iMod \"HcloseE\" as \"_\". iMod (\"Hclose\" with \"Hda\").\n  iIntros \"!> Hs\". iApply \"HΦ\". iFrame.\nQed.\n\nTheorem wp_Write (a: u64) s q b :\n  {{{ ∃ b0, int.Z a d↦ b0 ∗ is_slice_small s byteT q (Block_to_vals b) }}}\n    Write #a (slice_val s)\n  {{{ RET #(); int.Z a d↦ b ∗ is_slice_small s byteT q (Block_to_vals b) }}}.\nProof.\n  iIntros (Φ) \"Hpre HΦ\".\n  iDestruct \"Hpre\" as (b0) \"[Hda Hs]\".\n  wp_apply (wp_Write_atomic with \"Hs\").\n  iApply ncfupd_mask_intro; first set_solver+.\n  iIntros \"Hclose\". iExists _. iFrame.\n  iIntros \"Hda\". iMod \"Hclose\" as \"_\".\n  iIntros \"!> Hs\". iApply \"HΦ\". iFrame.\nQed.\n\nTheorem wp_Write' (z: Z) (a: u64) s q b :\n  {{{ ⌜int.Z a = z⌝ ∗ ▷ ∃ b0, z d↦ b0 ∗ is_slice_small s byteT q (Block_to_vals b) }}}\n    Write #a (slice_val s)\n  {{{ RET #(); z d↦ b ∗ is_slice_small s byteT q (Block_to_vals b) }}}.\nProof.\n  iIntros (Φ) \"[<- >Hpre] HΦ\".\n  iApply (wp_Write with \"[$Hpre]\").\n  eauto.\nQed.\n\nLemma wp_Read_atomic (a: u64) q :\n  ⊢ <<< ∀∀ b, int.Z a d↦{q} b >>>\n      Read #a @ ∅\n    <<< int.Z a d↦{q} b >>>\n    {{{ s, RET slice_val s; is_block_full s b }}}.\nProof.\n  iIntros \"!#\" (Φ) \"Hupd\".\n  wp_call.\n  wp_bind (ExternalOp _ _).\n  rewrite difference_empty_L.\n  iMod \"Hupd\" as (b) \"[Hda Hupd]\".\n  { solve_atomic. inversion H. subst. monad_inv. inversion H0. subst. inversion H2. subst.\n    inversion H4. subst. inversion H6. subst. inversion H7. econstructor. eauto. }\n  wp_apply (wp_ReadOp with \"Hda\").\n  iIntros (l) \"(Hda&Hl)\".\n  iMod (\"Hupd\" with \"Hda\") as \"HQ\"; iModIntro.\n  iDestruct (block_array_to_slice_raw with \"Hl\") as \"Hs\".\n  wp_pures.\n  wp_apply (wp_raw_slice with \"Hs\").\n  iIntros (s) \"Hs\".\n  iApply \"HQ\"; iFrame.\nQed.\n\nLemma wp_ReadTo_atomic (a: u64) b0 s q :\n  ⊢ {{{ is_block_full s b0 }}}\n  <<< ∀∀ b, int.Z a d↦{q} b >>>\n      ReadTo #a (slice_val s) @ ∅\n    <<< int.Z a d↦{q} b >>>\n    {{{ RET #(); is_block_full s b }}}.\nProof.\n  iIntros \"!#\" (Φ) \"Hs Hupd\".\n  wp_call.\n  iDestruct (is_slice_sz with \"Hs\") as %Hsz.\n  iDestruct (is_slice_wf with \"Hs\") as %Hwf.\n  wp_bind (ExternalOp _ _).\n  iApply (wp_ncatomic _ _ ∅).\n  { solve_atomic. inversion H. subst. monad_inv. inversion H0. subst. inversion H2. subst.\n    inversion H4. subst. inversion H6. subst. inversion H7. econstructor. eauto. }\n  rewrite difference_empty_L.\n  iMod \"Hupd\" as (db0) \"[Hda Hupd]\"; iModIntro.\n  wp_apply (wp_ReadOp with \"[$Hda]\").\n  iIntros (l) \"(Hda&Hl)\".\n  iMod (\"Hupd\" with \"Hda\") as \"HQ\".\n  iModIntro.\n  wp_pures.\n  wp_apply wp_slice_ptr.\n  iDestruct \"Hs\" as \"[Hs Hcap]\".\n  rewrite /is_slice_small.\n  iDestruct \"Hs\" as \"[Hs _]\".\n  wp_apply (wp_MemCpy_rec with \"[Hs Hl]\").\n  { iFrame.\n    iDestruct (array_to_block_array with \"Hl\") as \"$\".\n    iPureIntro.\n    rewrite !length_Block_to_vals.\n    rewrite /block_bytes.\n    split; [ reflexivity | ].\n    cbv; congruence.\n  }\n  rewrite take_ge; last first.\n  { rewrite length_Block_to_vals.\n    rewrite /block_bytes //. }\n  iIntros \"[Hs Hl]\".\n  iApply \"HQ\".\n  rewrite /is_block_full /is_slice /is_slice_small.\n  iFrame.\n  iPureIntro.\n  move: Hsz; rewrite !length_Block_to_vals //.\nQed.\n\nLemma wp_Read_triple E' (Q: Block -> iProp Σ) (a: u64) q :\n  {{{ |NC={⊤,E'}=> ∃ b, int.Z a d↦{q} b ∗ (int.Z a d↦{q} b -∗ |NC={E',⊤}=> Q b) }}}\n    Read #a\n  {{{ s b, RET slice_val s;\n      Q b ∗ is_block_full s b }}}.\nProof.\n  iIntros (Φ) \"Hupd HΦ\". iApply wp_Read_atomic.\n  rewrite difference_empty_L. iNext.\n  iMod \"Hupd\" as (b0) \"[Hda Hclose]\".\n  iApply ncfupd_mask_intro; first set_solver+.\n  iIntros \"HcloseE\". iExists _. iFrame.\n  iIntros \"Hda\". iMod \"HcloseE\" as \"_\". iMod (\"Hclose\" with \"Hda\").\n  iIntros \"!> * Hs\". iApply \"HΦ\". iFrame.\nQed.\n\nLemma wp_Read (a: u64) q b :\n  {{{ int.Z a d↦{q} b }}}\n    Read #a\n  {{{ s, RET slice_val s;\n      int.Z a d↦{q} b ∗ is_block_full s b }}}.\nProof.\n  iIntros (Φ) \"Hda HΦ\".\n  wp_apply wp_Read_atomic.\n  iApply ncfupd_mask_intro; first set_solver+.\n  iIntros \"HcloseE\". iExists _. iFrame.\n  iIntros \"Hda\". iMod \"HcloseE\" as \"_\".\n  iIntros \"!> * Hs\". iApply (\"HΦ\" with \"[$]\").\nQed.\n\nLemma wp_Barrier stk E  :\n  {{{ True }}}\n    Barrier #() @ stk; E\n  {{{ RET #(); True }}}.\nProof.\n  iIntros (Φ) \"_ HΦ\".\n  wp_call.\n  iApply (\"HΦ\" with \"[//]\").\nQed.\n\nLemma wpc_Barrier stk E1 :\n  {{{ True }}}\n    Barrier #() @ stk; E1\n  {{{ RET #(); True }}}\n  {{{ True }}}.\nProof.\n  iIntros (Φ Φc) \"_ HΦ\".\n  rewrite /Barrier.\n  wpc_pures; auto.\n  - by crash_case.\n  - iRight in \"HΦ\".\n    iApply (\"HΦ\" with \"[//]\").\n  - by crash_case.\nQed.\n\nLemma wpc_Read stk E1 (a: u64) q b :\n  {{{ int.Z a d↦{q} b }}}\n    Read #a @ stk; E1\n  {{{ s, RET slice_val s;\n      int.Z a d↦{q} b ∗\n      is_slice s byteT 1%Qp (Block_to_vals b) }}}\n  {{{ int.Z a d↦{q} b }}}.\nProof.\n  iIntros (Φ Φc) \"Hda HΦ\".\n  rewrite /Read.\n  wpc_pures.\n  { by crash_case. }\n  wpc_bind (ExternalOp _ _).\n  assert (Atomic StronglyAtomic (ExternalOp ReadOp #a)).\n  {\n    solve_atomic. inversion H. subst. monad_inv. inversion H0. subst. inversion H2. subst.\n    inversion H4. subst. inversion H6. subst. inversion H7. econstructor. eauto.\n  }\n  wpc_atomic; iFrame.\n  wp_apply (wp_ReadOp with \"Hda\").\n  iIntros (l) \"(Hda&Hl)\".\n  iDestruct (block_array_to_slice_raw with \"Hl\") as \"Hs\".\n  iSplit.\n  { iDestruct \"HΦ\" as \"(HΦ&_)\".\n    iModIntro.\n    iDestruct (\"HΦ\" with \"[$]\") as \"H\". repeat iModIntro; auto. }\n  iModIntro. wpc_pures; first by crash_case.\n  wpc_frame \"Hda HΦ\".\n  { by crash_case. }\n  wp_apply (wp_raw_slice with \"Hs\").\n  iIntros (s) \"Hs\".\n  iIntros \"(?&HΦ)\". iApply \"HΦ\".\n  iFrame.\nQed.\n\nTheorem wpc_Write_ncfupd {stk E1} E1' (a: u64) s q b :\n  ∀ Φ Φc,\n    is_block s q b -∗\n    (Φc ∧ |NC={E1,E1'}=> ∃ b0, int.Z a d↦ b0 ∗ ▷ (int.Z a d↦ b -∗ |NC={E1',E1}=>\n          Φc ∧ (is_block s q b -∗ Φ #()))) -∗\n    WPC Write #a (slice_val s) @ stk; E1 {{ Φ }} {{ Φc }}.\nProof.\n  iIntros (Φ Φc) \"Hs Hfupd\".\n  rewrite /Write /slice.ptr.\n  wpc_pures.\n  { iLeft in \"Hfupd\". iFrame. }\n  iDestruct (is_slice_small_sz with \"Hs\") as %Hsz.\n  iDestruct (is_slice_small_wf with \"Hs\") as %Hwf.\n  assert (Atomic StronglyAtomic (ExternalOp WriteOp (#a, #s.(Slice.ptr))%V)).\n  {\n    solve_atomic. inversion H. subst. monad_inv. inversion H0. subst. inversion H2. subst.\n    inversion H4. subst. inversion H6. subst. inversion H7. econstructor. eauto.\n  }\n  wpc_atomic.\n  iRight in \"Hfupd\".\n  iMod \"Hfupd\" as (b0) \"[Hda HQ]\".\n  wp_apply (wp_WriteOp with \"[Hda Hs]\").\n  { iIntros \"!>\".\n    iExists b0; iFrame.\n    by iApply slice_to_block_array. }\n  iIntros \"[Hda Hmapsto]\".\n  iMod (\"HQ\" with \"Hda\") as \"HQ\".\n  iModIntro.\n  iSplit.\n  - iDestruct \"HQ\" as \"(HQ&_)\". iModIntro. by repeat iModIntro.\n  - iModIntro. iRight in \"HQ\". iApply \"HQ\".\n    iFrame.\n    destruct s; simpl in Hsz.\n    replace sz with (U64 4096).\n    + iDestruct (block_array_to_slice_raw with \"Hmapsto\") as \"[? %]\".\n      rewrite /is_block /is_slice_small. iFrame.\n      iPureIntro. simpl. split; first done. simpl in Hwf. word.\n    + rewrite length_Block_to_vals in Hsz.\n      change block_bytes with (Z.to_nat 4096) in Hsz.\n      word.\nQed.\n\n(* This is a TaDA-syle logically atomic spec, so the HoCAP-style sugar does not work. *)\nTheorem wpc_Write_fupd {stk E1} E1' (a: u64) s q b :\n  ∀ Φ Φc,\n    is_block s q b -∗\n    (Φc ∧ |={E1,E1'}=> ∃ b0, int.Z a d↦ b0 ∗ ▷ (int.Z a d↦ b ={E1',E1}=∗\n          Φc ∧ (is_block s q b -∗ Φ #()))) -∗\n    WPC Write #a (slice_val s) @ stk; E1 {{ Φ }} {{ Φc }}.\nProof.\n  iIntros (??) \"Hblock HΦc\".\n  wpc_apply (wpc_Write_ncfupd with \"[$]\").\n  iSplit.\n  - by iLeft in \"HΦc\".\n  - iRight in \"HΦc\". iApply fupd_ncfupd. iMod \"HΦc\" as (?) \"(?&H1)\".\n    iModIntro. iExists _. iFrame. iNext. iIntros \"H2\".\n      by iMod (\"H1\" with \"[$]\").\nQed.\n\nTheorem wpc_Write_fupd_triple {stk E1} E1' (Q Qc: iProp Σ) (a: u64) s q b :\n  {{{ is_block s q b ∗\n      (Qc ∧ |={E1,E1'}=> ∃ b0, int.Z a d↦ b0 ∗ ▷ (int.Z a d↦ b ={E1',E1}=∗ Qc ∧ Q)) }}}\n    Write #a (slice_val s) @ stk; E1\n  {{{ RET #(); is_block s q b ∗ Qc ∧ Q }}}\n  {{{ Qc }}}.\nProof.\n  iIntros (Φ Φc) \"Hpre HΦ\".\n  iDestruct \"Hpre\" as \"[Hs Hfupd]\".\n  iApply (wpc_Write_fupd with \"Hs\"). iSplit.\n  { iLeft in \"Hfupd\". iLeft in \"HΦ\". iApply \"HΦ\". iFrame. }\n  iRight in \"Hfupd\". iMod \"Hfupd\" as (b0) \"[Hv Hclose]\". iModIntro.\n  iExists b0. iFrame. iIntros \"!> Hv\". iMod (\"Hclose\" with \"Hv\") as \"HQ\".\n  iModIntro. iSplit.\n  { iLeft in \"HΦ\". iLeft in \"HQ\". iApply \"HΦ\". iFrame. }\n  iRight in \"HΦ\". iIntros \"Hblock\". iApply \"HΦ\". iFrame.\nQed.\n\nTheorem wpc_Write' stk E1 (a: u64) s q b0 b :\n  {{{ int.Z a d↦ b0 ∗ is_block s q b }}}\n    Write #a (slice_val s) @ stk; E1\n  {{{ RET #(); int.Z a d↦ b ∗ is_block s q b }}}\n  {{{ (int.Z a d↦ b0 ∨ int.Z a d↦ b) }}}.\nProof.\n  iIntros (Φ Φc) \"Hpre HΦ\".\n  iDestruct \"Hpre\" as \"[Hda Hs]\".\n  wpc_apply (wpc_Write_fupd with \"[$Hs]\").\n  iSplit.\n  { crash_case.\n    eauto. }\n  iModIntro.\n  iExists _; iFrame.\n  iIntros \"!> Hda !>\".\n  iSplit.\n  { crash_case; eauto. }\n  iRight in \"HΦ\".\n  iIntros \"Hb\".\n  iApply \"HΦ\"; iFrame.\nQed.\n\nTheorem wpc_Write stk E1 (a: u64) s q b :\n  {{{ ∃ b0, int.Z a d↦ b0 ∗ is_block s q b }}}\n    Write #a (slice_val s) @ stk; E1\n  {{{ RET #(); int.Z a d↦ b ∗ is_block s q b }}}\n  {{{ ∃ b', int.Z a d↦ b' }}}.\nProof.\n  iIntros (Φ Φc) \"Hpre HΦ\".\n  iDestruct \"Hpre\" as (b0) \"[Hda Hs]\".\n  wpc_apply (wpc_Write' with \"[$Hda $Hs]\").\n  iSplit.\n  { iLeft in \"HΦ\". iIntros \"[Hda|Hda]\"; iApply \"HΦ\"; eauto. }\n  iIntros \"!> [Hda Hb]\".\n  iRight in \"HΦ\".\n  iApply \"HΦ\"; iFrame.\nQed.\n\nTheorem slice_to_block s q bs :\n  s.(Slice.sz) = 4096 ->\n  is_slice_small s byteT q (b2val <$> bs) -∗\n  mapsto_block s.(Slice.ptr) q (list_to_block bs).\nProof.\n  iIntros (Hsz) \"Hs\".\n  rewrite /is_slice_small.\n  iDestruct \"Hs\" as \"[Hl %]\".\n  rewrite fmap_length in H.\n  iApply (array_to_block with \"Hl\").\n  assert (int.Z (Slice.sz s) = 4096).\n  { rewrite Hsz. reflexivity. }\n  lia.\nQed.\n\nEnd goose.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/disk_lib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22997364162397255}}
{"text": "(** * MOV instruction *)\nRequire Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype tuple.\nRequire Import procstate procstatemonad bitsops bitsprops bitsopsprops.\nRequire Import spec SPred septac spec safe triple basic basicprog spectac.\nRequire Import instr instrcodec eval monad monadinst reader pointsto cursor.\nRequire Import Setoid RelationClasses Morphisms.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nRequire Import Relations.\nRequire Import instrsyntax.\n\nLocal Open Scope instr_scope.\n\nRequire Import x86.instrrules.core.\n\n(** ** Generic rule *)\nLemma MOV_rule d ds oldv:\n  |-- specAtDstSrc ds (fun V v =>\n      basic (V oldv) (MOVOP d ds) (V v)).\nProof. do_instrrule_triple. Qed.\n\nLtac basicMOV :=\n  rewrite /makeMOV;\n  let R := lazymatch goal with\n             | |- |-- basic ?p (@MOVOP ?d ?a) ?q => constr:(@MOV_rule d a)\n           end in\n  basicapply R.\n\n\n(** We open a section in order to localize the hints *)\nSection InstrRules.\n\nHint Unfold\n  specAtDstSrc specAtSrc specAtRegMemDst specAtMemSpec specAtMemSpecDst\n  DWORDRegMemR BYTERegMemR DWORDRegMemM DWORDRegImmI fromSingletonMemSpec\n  DWORDorBYTEregIs natAsDWORD BYTEtoDWORD\n  makeMOV makeBOP makeUOP\n  : basicapply.\nHint Rewrite\n  addB0 low_catB : basicapply.\n\n(** ** Register to register *)\nLemma MOV_RR_rule (r1 r2:Reg) v1 v2:\n  |-- basic (r1 ~= v1 ** r2 ~= v2) (MOV r1, r2) (r1 ~= v2 ** r2 ~= v2).\nProof. basicMOV. Qed.\n\nLemma MOV_RanyR_rule (r1 r2:Reg) v2:\n  |-- basic (r1? ** r2 ~= v2) (MOV r1, r2) (r1 ~= v2 ** r2 ~= v2).\nProof. unhideReg r1 => old. basicMOV. Qed.\n\n(** ** Immediate to register *)\nLemma MOV_RI_rule (r:Reg) (v1 v2:DWORD) :\n  |-- basic (r ~= v1) (MOV r, v2) (r ~= v2).\nProof. basicMOV. Qed.\n\nLemma MOV_RanyI_rule (r:Reg) (v2:DWORD) :\n  |-- basic r? (MOV r, v2) (r ~= v2).\nProof. unhideReg r => old. basicMOV. Qed.\n\n(** ** Memory to register *)\nLemma MOV_RM_rule (pd:DWORD) (r1 r2:Reg) offset (v1 v2: DWORD) :\n  |-- basic (r1 ~= v1 ** r2 ~= pd ** pd +# offset :-> v2)\n            (MOV r1, [r2 + offset])\n            (r1 ~= v2 ** r2 ~= pd ** pd +# offset :-> v2).\nProof. basicMOV. Qed.\n\nLemma MOV_RanyM_rule (pd:DWORD) (r1 r2:Reg) offset (v2: DWORD) :\n  |-- basic (r1? ** r2 ~= pd ** pd +# offset :-> v2)\n            (MOV r1, [r2 + offset])\n            (r1 ~= v2 ** r2 ~= pd ** pd +# offset :-> v2).\nProof. unhideReg r1 => old. basicMOV. Qed.\n\nLemma MOV_RM0_rule (pd:DWORD) (r1 r2:Reg) (v1 v2: DWORD) :\n  |-- basic (r1 ~= v1 ** r2 ~= pd ** pd :-> v2)\n            (MOV r1, [r2])\n            (r1 ~= v2 ** r2 ~= pd ** pd :-> v2).\nProof. basicMOV. Qed.\n\nLemma MOV_RanyM0_rule (pd:DWORD) (r1 r2:Reg) (v2: DWORD) :\n  |-- basic (r1? ** r2 ~= pd ** pd :-> v2)\n            (MOV r1, [r2])\n            (r1 ~= v2 ** r2 ~= pd ** pd :-> v2).\nProof. unhideReg r1 => old. basicMOV. Qed.\n\n(** ** Register to memory *)\nLemma MOV_MR_rule (p: DWORD) (r1 r2: Reg) offset (v1 v2:DWORD) :\n  |-- basic (r1~=p ** p +# offset :-> v1 ** r2~=v2)\n            (MOV [r1 + offset], r2)\n            (r1~=p ** p +# offset :-> v2 ** r2~=v2).\nProof. basicMOV. Qed.\n\n(** ** Immediate to memory *)\nLemma MOV_MI_rule dword (pd:DWORD) (r:Reg) offset (v w:DWORDorBYTE dword) :\n  |-- basic (r ~= pd ** pd +# offset :-> v)\n            (MOVOP _ (DstSrcMI dword (mkMemSpec (Some(r, None)) #offset) w))\n            (r ~= pd ** pd +# offset :-> w).\nProof. basicMOV. Qed.\n\nLemma MOV_M0R_rule (pd:DWORD) (r1 r2:Reg) (v1 v2: DWORD) :\n  |-- basic (r1 ~= pd ** pd :-> v1 ** r2 ~= v2)\n            (MOV [r1], r2)\n            (r1 ~= pd ** pd :-> v2 ** r2 ~= v2).\nProof. basicMOV. Qed.\n\n\nLemma MOV_MbR_rule (p: DWORD) (r1:Reg) (r2: BYTEReg) offset (v1:BYTE) (v2:BYTE) :\n  |-- basic (r1 ~= p ** p +# offset :-> v1 ** BYTEregIs r2 v2)\n            (MOV [r1 + offset], r2)\n            (r1 ~= p ** p +# offset :-> v2 ** BYTEregIs r2 v2).\nProof. basicMOV. Qed.\n\nLemma MOV_MbR_ruleGen d (p: DWORD) (r1:Reg) (r2: DWORDorBYTEReg d) offset (v1 v2:DWORDorBYTE d):\n  |-- basic (r1 ~= p ** p +# offset :-> v1 ** DWORDorBYTEregIs r2 v2)\n            (MOVOP d (DstSrcMR d (mkMemSpec (Some(r1,None)) #offset) r2))\n            (r1 ~= p ** p +# offset :-> v2 ** DWORDorBYTEregIs r2 v2).\nProof.\n  destruct d.\n  { apply MOV_MR_rule. }\n  { apply MOV_MbR_rule. }\nQed.\n\nLemma MOV_RMb_rule (p: DWORD) (r1:Reg) (r2:BYTEReg) offset (v1:BYTE) (v2:BYTE) :\n  |-- basic (r1 ~= p ** p +# offset :-> v1 ** BYTEregIs r2 v2)\n            (MOV r2, [r1 + offset])\n            (r1 ~= p ** p +# offset :-> v1 ** BYTEregIs r2 v1).\nProof. basicMOV. Qed.\n\nLemma MOV_MbI_rule (pd:DWORD) (r1:Reg) offset (v1 v2:BYTE) :\n  |-- basic (r1 ~= pd ** pd +# offset :-> v1)\n            (MOV BYTE [r1 + offset], v2)\n            (r1 ~= pd ** pd +# offset :-> v2).\nProof. basicMOV. Qed.\nEnd InstrRules.\n", "meta": {"author": "jbj", "repo": "x86proved", "sha": "d314fa6d23c064a2be4bf686ac7da16a591fda01", "save_path": "github-repos/coq/jbj-x86proved", "path": "github-repos/coq/jbj-x86proved/x86proved-d314fa6d23c064a2be4bf686ac7da16a591fda01/src/x86/instrrules/mov.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22997364162397252}}
{"text": "Require Import Label.\nRequire Import Language Types.\nRequire Import Lemmas.\nRequire Import Coq.Lists.List.\nRequire Import bijection.\nRequire Import decision. \n\n\n\nInductive L_equivalence_tm : tm -> heap -> tm -> heap ->  (bijection oid oid )->  Prop :=\n  | L_equivalence_tm_eq_Tvar : forall id1 id2 h1 h2  φ , \n      id1 = id2 -> L_equivalence_tm (Tvar id1) h1 (Tvar id2) h2  φ\n  | L_equivalence_tm_eq_eq_cmp : forall e1 e2 a1 a2 h1 h2  φ,\n      L_equivalence_tm e1 h1 e2 h2  φ->\n      L_equivalence_tm a1 h1 a2 h2  φ->\n      L_equivalence_tm (EqCmp e1 a1) h1 (EqCmp e2 a2) h2  φ\n  | L_equivalence_tm_eq_null : forall h1 h2  φ,  \n      L_equivalence_tm null h1 null h2 φ\n  | L_equivalence_tm_eq_fieldaccess : forall e1 e2 f h1 h2 φ,\n      L_equivalence_tm e1 h1 e2 h2 φ->\n      L_equivalence_tm (FieldAccess e1 f) h1 (FieldAccess e2 f) h2  φ\n  | L_equivalence_tm_eq_methodcall : forall e1 e2 a1 a2 meth h1 h2  φ,\n      L_equivalence_tm e1 h1 e2 h2  φ->\n      L_equivalence_tm a1 h1 a2 h2  φ->\n      L_equivalence_tm (MethodCall e1 meth a1) h1 (MethodCall e2 meth a2) h2  φ\n  | L_equivalence_tm_eq_newexp : forall cls1 cls2 h1 h2  φ,\n      cls1 = cls2 ->\n      L_equivalence_tm (NewExp cls1) h1 (NewExp cls2) h2  φ\n  | L_equivalence_tm_eq_ture : forall h1 h2  φ,\n      L_equivalence_tm B_true h1 B_true h2  φ\n  | L_equivalence_tm_eq_false : forall h1 h2  φ,    \n      L_equivalence_tm B_false h1 B_false h2  φ\n  | L_equivalence_tm_eq_label : forall l1 l2 h1 h2  φ, \n      l1 = l2 ->\n      L_equivalence_tm (l l1) h1 (l l2) h2  φ\n  | L_equivalence_tm_eq_labelData : forall e1 e2 l1 l2 h1 h2  φ,\n      L_equivalence_tm e1 h1 e2 h2  φ->\n      l1 = l2 ->\n      L_equivalence_tm (labelData e1 l1) h1 (labelData e2 l2) h2  φ\n  | L_equivalence_tm_eq_unlabel : forall e1 e2 h1 h2  φ,\n      L_equivalence_tm e1 h1 e2 h2  φ->\n      L_equivalence_tm (unlabel e1) h1 (unlabel e2) h2 φ\n  | L_equivalence_tm_eq_labelOf : forall e1 e2 h1 h2  φ,\n      L_equivalence_tm e1 h1 e2 h2  φ->\n      L_equivalence_tm (labelOf e1) h1 (labelOf e2) h2  φ\n  | L_equivalence_tm_eq_unlabelOpaque : forall e1 e2 h1 h2 φ,\n      L_equivalence_tm e1 h1 e2 h2  φ->\n      L_equivalence_tm (unlabelOpaque e1) h1 (unlabelOpaque e2) h2  φ\n  | L_equivalence_tm_eq_raiseLabel : forall e1 e2 h1 h2 l1 l2 φ,\n      L_equivalence_tm e1 h1 e2 h2  φ->\n      l1 = l2 ->\n      L_equivalence_tm (raiseLabel e1 l1) h1 (raiseLabel e2 l2) h2  φ                     \n  | L_equivalence_tm_eq_skip : forall h1 h2 φ ,\n      L_equivalence_tm Skip h1 Skip h2 φ\n  | L_equivalence_tm_eq_Assignment : forall e1 e2 x1 x2 h1 h2 φ, \n      L_equivalence_tm e1 h1 e2 h2 φ->\n      x1 = x2->\n      L_equivalence_tm (Assignment x1 e1) h1 (Assignment x2 e2) h2 φ\n  | L_equivalence_tm_eq_FieldWrite : forall e1 e2 f1 f2 e1' e2' h1 h2 φ,\n      L_equivalence_tm e1 h1 e2 h2 φ->\n      f1 = f2 ->\n      L_equivalence_tm e1' h1 e2' h2 φ ->\n      L_equivalence_tm (FieldWrite e1 f1 e1') h1 (FieldWrite e2 f2 e2') h2 φ\n  | L_equivalence_tm_eq_if : forall s1 s2 s1' s2' g g' h1 h2 φ,\n      L_equivalence_tm g h1 g' h2 φ ->\n      L_equivalence_tm s1 h1 s1' h2 φ->\n      L_equivalence_tm s2 h1 s2' h2 φ->\n      L_equivalence_tm (If g s1 s2) h1 (If g' s1' s2') h2 φ\n  | L_equivalence_tm_eq_Sequence : forall s1 s2 s1' s2' h1 h2 φ, \n      L_equivalence_tm s1 h1 s1' h2 φ->\n      L_equivalence_tm s2 h1 s2' h2 φ->\n      L_equivalence_tm (Sequence s1 s2) h1 (Sequence s1' s2') h2 φ\n  | L_equivalence_tm_eq_object_L : forall o1 o2 h1 h2 cls1 F1 lb1 cls2 F2 lb2 φ, \n      left φ o1 = Some o2 ->\n      Some (Heap_OBJ cls1 F1 lb1) = lookup_heap_obj h1 o1 ->\n      flow_to lb1 L_Label = true ->\n      Some (Heap_OBJ cls2 F2 lb2) = lookup_heap_obj h2 o2 ->\n      flow_to lb2 L_Label = true ->\n      L_equivalence_tm (ObjId o1) h1 (ObjId o2) h2 φ\n  | L_equivalence_tm_eq_object_H : forall o1 o2 h1 h2 cls1 cls2 F1 lb1 F2 lb2 φ, \n      Some (Heap_OBJ cls1 F1 lb1) = lookup_heap_obj h1 o1 ->\n      flow_to lb1 L_Label = false  ->\n      Some (Heap_OBJ cls2 F2 lb2) = lookup_heap_obj h2 o2 ->\n      flow_to lb2 L_Label = false  ->\n      L_equivalence_tm (ObjId o1) h1 (ObjId o2) h2 φ                     \n  | L_equivalence_tm_eq_v_l_L : forall lb e1 e2 h1 h2 φ, \n      flow_to lb L_Label = true ->\n      L_equivalence_tm e1 h1 e2 h2 φ->\n      (* modification here *)\n      value e1 -> value e2 ->\n      L_equivalence_tm (v_l e1 lb) h1 (v_l e2 lb) h2 φ\n  | L_equivalence_tm_eq_v_l_H : forall e1 e2 l1 l2 h1 h2 φ, \n      flow_to l1 L_Label = false ->\n      flow_to l2 L_Label = false ->\n       value e1 -> value e2 ->\n      L_equivalence_tm (v_l e1 l1) h1 (v_l e2 l2) h2 φ\n  | L_equivalence_tm_eq_v_opa_l_L : forall lb e1 e2 h1 h2 φ, \n      flow_to lb L_Label = true ->\n      value e1 -> value e2 ->\n      L_equivalence_tm e1 h1 e2 h2 φ->\n      L_equivalence_tm (v_opa_l e1 lb) h1 (v_opa_l e2 lb) h2 φ\n  | L_equivalence_tm_eq_v_opa_l_H : forall e1 e2 l1 l2 h1 h2 φ, \n      flow_to l1 L_Label = false ->\n      flow_to l2 L_Label = false ->\n      value e1 -> value e2 ->\n      L_equivalence_tm (v_opa_l e1 l1) h1 (v_opa_l e2 l2) h2 φ\n  (*\n  | L_equivalence_tm_eq_dot : forall h1 h2 φ,\n      L_equivalence_tm (dot) h1 (dot) h2 φ *)\n  | L_equivalence_tm_eq_hole : forall h1 h2 φ,\n      L_equivalence_tm (hole) h1 (hole) h2 φ\n  | L_equivalence_tm_eq_return_hole : forall h1 h2 φ,\n      L_equivalence_tm (return_hole) h1 (return_hole) h2 φ.\nHint Constructors L_equivalence_tm.\n\nInductive L_equivalence_object : oid -> heap -> oid -> heap -> (bijection oid oid )-> Prop :=\n(*\n   | object_same : forall o h, \n        L_equivalence_object o h o h\n   | object_equal_H : forall o1 o2 h1 h2 lb1 lb2 cls1 cls2 F1 F2,\n        Some (Heap_OBJ cls1 F1 lb1) = lookup_heap_obj h1 o1 -> \n        Some (Heap_OBJ cls2 F2 lb2) = lookup_heap_obj h2 o2 ->\n        flow_to lb1 L_Label = false ->\n        flow_to lb2 L_Label = false ->\n        L_equivalence_object o1 h1 o2 h2*)\n   | object_equal_L : forall o1 o2 h1 h2 lb1 lb2 cls1 cls2 F1 F2 φ,\n        Some (Heap_OBJ cls1 F1 lb1) = lookup_heap_obj h1 o1 -> \n        Some (Heap_OBJ cls2 F2 lb2) = lookup_heap_obj h2 o2 ->\n        flow_to lb1 L_Label = true ->\n        flow_to lb2 L_Label = true ->\n        ((cls1 = cls2) /\\ \n            (forall fname, F1 fname = None <-> F2 fname = None )  /\\\n            (forall fname, F1 fname = Some null <-> F2 fname = Some null ) /\\\n            (forall fname fo1 fo2,\n                F1 fname = Some (ObjId fo1)\n                -> F2 fname = Some (ObjId fo2) ->\n                (exists cls_f1 cls_f2 lof1 lof2 FF1 FF2,\n                    lookup_heap_obj h1 fo1 = Some (Heap_OBJ cls_f1 FF1 lof1)\n                 /\\ lookup_heap_obj h2 fo2 = Some (Heap_OBJ cls_f2 FF2 lof2)\n                 /\\ (\n                   ( left φ fo1 = Some fo2\n                     /\\ flow_to lof2 L_Label = true\n                     /\\ flow_to lof1 L_Label = true\n                     /\\ cls_f1 = cls_f2 )  \\/\n                    ( flow_to lof2 L_Label = false\n                     /\\ flow_to lof1 L_Label = false)\n            )))\n        )-> L_equivalence_object o1 h1 o2 h2 φ.\nHint Constructors L_equivalence_object.\n\n\nInductive L_equivalence_store : stack_frame -> heap -> stack_frame -> heap ->  (bijection oid oid ) -> Prop :=\n| L_equivalence_store_L : forall  sf1 sf2 h1 h2  φ ,\n    (forall v1 v2 x,\n      sf1 x = Some v1 ->\n    value v1 ->\n    sf2 x = Some v2 ->\n    value v2 -> \n    L_equivalence_tm v1 h1 v2 h2  φ ) /\\\n    (sf1 = empty_stack_frame <->\n     sf2 = empty_stack_frame\n    ) ->\n    L_equivalence_store sf1 h1 sf2 h2 φ.\nHint Constructors L_equivalence_store.\n\n\n\nInductive L_equivalence_heap : heap -> heap ->  (bijection oid oid ) -> Prop :=\n  | L_eq_heap : forall h1 h2 φ ,\n      (forall o1 o2, left φ o1 = Some o2 ->\n                     L_equivalence_object o1 h1 o2 h2 φ) ->\n      (forall o, lookup_heap_obj h1 o = None ->\n                 left φ o = None) ->\n       (forall o, lookup_heap_obj h2 o = None ->\n                 right φ o = None) ->\n      (forall o cls F lb, lookup_heap_obj h1 o = Some (Heap_OBJ cls F lb)->\n                 flow_to lb L_Label = false ->\n                 left φ o = None) ->\n      (forall o cls F lb, lookup_heap_obj h2 o = Some (Heap_OBJ cls F lb)->\n                 flow_to lb L_Label = false ->\n                 right φ o = None) ->\n                              L_equivalence_heap h1 h2 φ.\nHint Constructors L_equivalence_heap.\n\nLemma oid_decision : forall a1 a2 : oid, Decision (a1 = a2).\n  intros. \n  unfold Decision.\n  case_eq (beq_oid a1 a2); intro. \n  apply beq_oid_equal in H. auto.\n  assert (a1 <> a2). intro contra.\n  apply  beq_equal_oid in contra. rewrite contra in H. inversion H.\n  auto. \nDefined.\nHint Resolve oid_decision.\n\n\n\n\nLemma extend_heap_preserve_l_eq_heap : forall t1 h1 h1' t2 h2 h2'  lb2 cls_def ct φ ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_tm t1 h1 t2 h2 φ ->\n  L_equivalence_heap h1 h2 φ ->\n  flow_to lb2 L_Label = true ->\n  h1' = (add_heap_obj h1 (get_fresh_oid h1) \n        (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2)) ->\n  h2' = (add_heap_obj h2 (get_fresh_oid h2) \n        (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2)) ->\n  exists φ', L_equivalence_heap h1' h2' φ'.\n  Proof with eauto. \n  intros  t1 h1 h1' t2 h2 h2' lb2 cls_def ct φ. \n  intros.\n  inversion H2.  subst; auto.\n  remember (add_heap_obj h1 (get_fresh_oid h1) \n        (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2)) as h1'.\n  remember (add_heap_obj h2 (get_fresh_oid h2) \n                         (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2)) as h2'.\n  assert (lookup_heap_obj h1 (get_fresh_oid h1)  = None). \n  apply fresh_oid_heap with ct; auto.   \n  assert (lookup_heap_obj h2 (get_fresh_oid h2)  = None). \n  apply fresh_oid_heap with ct; auto. \n  apply H7 in H4. apply H8 in H5.\n  assert (forall a1 a2 : oid, Decision (a1 = a2)). auto.\n  Check extend_bijection.\n  remember (get_fresh_oid h1) as  o3.\n  remember (get_fresh_oid h2) as o4. \n  exists  (extend_bijection φ o3 o4 H4 H5).\n  assert ( beq_oid (get_fresh_oid h1) (get_fresh_oid h1) = true) by (apply beq_oid_same).\n  assert ( beq_oid (get_fresh_oid h2) (get_fresh_oid h2) = true) by (apply beq_oid_same).\n  apply  L_eq_heap.\n  intros.\n  \n  destruct (oid_decision o3 o1). subst; auto. simpl in H14.\n  destruct (decide (get_fresh_oid h1 = get_fresh_oid h1) ) in H14. inversion H14; subst; auto. \n\n  remember (add_heap_obj h1 (get_fresh_oid h1) \n        (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2)) as h1'.\n  remember (add_heap_obj h2 (get_fresh_oid h2) \n                         (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2)) as h2'.\n  assert (lookup_heap_obj h1' (get_fresh_oid h1) = Some (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2) ).\n  subst; auto.\n    assert (lookup_heap_obj h2' (get_fresh_oid h2) = Some (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2) ).\n  subst; auto.\n  apply object_equal_L with lb2 lb2 cls_def cls_def (init_field_map (find_fields cls_def) empty_field_map) (init_field_map (find_fields cls_def) empty_field_map); auto.\n  split; auto. \n  split; auto. split; auto.  split; auto.\n  split; auto.   \n  intros.  \n  pose proof (initilized_fields_empty (find_fields cls_def) fname).\n  \n  destruct H19;\n    rewrite H19 in H18; inversion H18.\n  intuition.  \n   assert (left (extend_bijection φ o3 o4 H4 H5)  o1 = \n           left φ o1) by (apply left_extend_bijection_neq; auto).\n   rewrite H14 in H15. assert (left φ o1 = Some o2). auto.\n   apply H6 in H16. inversion H16; subst; auto.\n   destruct H21; subst; auto. destruct H22; subst; auto.\n\n  \n  assert ( lookup_heap_obj\n     (add_heap_obj h1 (get_fresh_oid h1)\n       (Heap_OBJ cls_def\n          (init_field_map (find_fields cls_def) empty_field_map) lb2)) o1 = Some (Heap_OBJ cls2 F1 lb1) ).\n  apply extend_heap_lookup_eq; auto. \n\n  destruct (oid_decision (get_fresh_oid h2) o2 ).\n   assert (lookup_heap_obj h2 (get_fresh_oid h2)  = None). \n   apply fresh_oid_heap with ct; auto.  rewrite e in H24.\n   rewrite H24 in H18. inversion H18.\n   \n   assert ( lookup_heap_obj\n     (add_heap_obj h2 (get_fresh_oid h2)\n       (Heap_OBJ cls_def\n          (init_field_map (find_fields cls_def) empty_field_map) lb2)) o2 = Some (Heap_OBJ cls2 F2 lb0) ).\n   apply extend_heap_lookup_eq; auto.\n\n   apply object_equal_L with lb1 lb0 cls2 cls2 F1 F2; auto.\n   split; auto. split; auto.\n   split; auto. \n   intros.\n   destruct H22. destruct H24. auto. \n\n   intros.\n   destruct H22. \n   destruct H27 with fname fo1 fo2; auto. rename x into cls_f1.\n   destruct H28 as [cls_f2].\n   destruct H28 as [lof1].    destruct H28 as [lof2].\n   destruct H28 as [FF1].    destruct H28 as [FF2].   \n\n   destruct H28. destruct H29. destruct H30.\n   destruct H30. destruct H31. destruct H32.\n   \n   exists cls_f1. exists cls_f2.\n   exists lof1. exists lof2.\n   exists FF1. exists FF2. \n   split; auto. \n   apply extend_heap_lookup_eq; auto.\n   apply lookup_extend_heap_fresh_oid with ct  (Heap_OBJ cls_f1 FF1 lof1) ; auto. \n   split; auto. \n   apply extend_heap_lookup_eq; auto. \n   apply lookup_extend_heap_fresh_oid with ct  (Heap_OBJ cls_f2 FF2 lof2) ; auto. \n   assert (fo1 <> get_fresh_oid h1  ).\n   apply lookup_extend_heap_fresh_oid with ct  (Heap_OBJ cls_f1 FF1 lof1) ; auto.\n   assert (left (extend_bijection φ (get_fresh_oid h1) (get_fresh_oid h2) H4 H5)  fo1 = \n           left φ fo1) by (apply left_extend_bijection_neq; auto).\n   left. split; auto. \n   rewrite H35.   auto.\n\n\n\n\n   exists cls_f1. exists cls_f2.\n   exists lof1. exists lof2.\n   exists FF1. exists FF2. \n   split; auto. \n   apply extend_heap_lookup_eq; auto.\n   apply lookup_extend_heap_fresh_oid with ct  (Heap_OBJ cls_f1 FF1 lof1) ; auto. \n   split; auto. \n   apply extend_heap_lookup_eq; auto. \n   apply lookup_extend_heap_fresh_oid with ct  (Heap_OBJ cls_f2 FF2 lof2) ; auto. \n\n   \n   \n   intros. subst; auto.  destruct (oid_decision (get_fresh_oid h1) o). subst; auto.\n   unfold  lookup_heap_obj in H14. unfold add_heap_obj in H14.\n   \n   rewrite H12 in H14. inversion H14.\n   remember (extend_bijection φ (get_fresh_oid h1) (get_fresh_oid h2) H4 H5) as φ'.\n   rewrite   Heqφ'.\n   assert (left (extend_bijection φ (get_fresh_oid h1) (get_fresh_oid h2) H4 H5)  o = \n           left φ o) by (apply left_extend_bijection_neq; auto).\n   assert ( lookup_heap_obj h1 o = None) by (apply lookup_extended_heap_none with\n                                                 (Heap_OBJ cls_def (init_field_map (find_fields cls_def)\n                                                                                   empty_field_map) lb2) ; auto).\n   rewrite H15.  apply H7 in H16. auto.\n   rewrite   Heqh2'. intros. subst. \n   destruct (oid_decision (get_fresh_oid h2) o). subst; auto.\n   unfold  lookup_heap_obj in H14. unfold add_heap_obj in H14.\n   rewrite H13 in H14. inversion H14.\n\n   assert (right (extend_bijection φ (get_fresh_oid h1) (get_fresh_oid h2) H4 H5)  o = \n           right φ o). (apply right_extend_bijection_neq; auto).\n   assert ( lookup_heap_obj h2 o = None) by (apply lookup_extended_heap_none with\n                                                 (Heap_OBJ cls_def (init_field_map (find_fields cls_def)\n                                                                                   empty_field_map) lb2) ; auto).\n   rewrite H15. apply H8 in H16. auto.\n   intros.\n   destruct (oid_decision o3 o). subst; auto. simpl in H14.\n   rewrite H12 in H14. inversion H14. subst; auto. rewrite H3 in H15. inversion H15.\n   subst; auto.\n\n   unfold lookup_heap_obj in H14. unfold add_heap_obj in H14.\n   assert (o <> get_fresh_oid h1) by (auto). apply  beq_oid_not_equal in H16. rewrite H16 in H14.\n   fold lookup_heap_obj in H14. apply H9 in H14.\n   assert (left (extend_bijection φ (get_fresh_oid h1) (get_fresh_oid h2) H4 H5)  o = \n           left φ o) by (apply left_extend_bijection_neq; auto). rewrite H17; auto. auto. \n\n\n   intros.\n   destruct (oid_decision o4 o). subst; auto. simpl in H14.\n   rewrite H13 in H14. inversion H14. subst; auto. rewrite H3 in H15. inversion H15.\n   subst; auto.\n\n   unfold lookup_heap_obj in H14. unfold add_heap_obj in H14.\n   assert (o <> get_fresh_oid h2) by (auto). apply  beq_oid_not_equal in H16. rewrite H16 in H14.\n   fold lookup_heap_obj in H14. apply H10 in H14.\n   assert (right (extend_bijection φ (get_fresh_oid h1) (get_fresh_oid h2) H4 H5)  o = \n           right φ o) by (apply right_extend_bijection_neq; auto). rewrite H17; auto. auto. \nQed. Hint Resolve extend_heap_preserve_l_eq_heap.   \n   \n\nInductive L_equivalence_fs : list tm -> heap -> list tm -> heap -> (bijection oid oid ) -> Prop:=\n  | L_equal_fs_nil : forall h1 h2 φ,\n    L_equivalence_fs nil h1 nil h2 φ\n  | L_equal_fs : forall fs1 fs2 h1 h2 top1 top2 φ, \n    L_equivalence_tm top1 h1 top2 h2 φ-> \n    L_equivalence_fs fs1 h1 fs2 h2 φ->\n    L_equivalence_fs (top1 :: fs1) h1 (top2 :: fs2) h2 φ.\nHint Constructors L_equivalence_fs.\n\n\n\n\nInductive L_eq_container : container -> heap -> container -> heap -> (bijection oid oid ) -> Prop :=\n  (*\n  | L_eq_same : forall ctn h φ, \n      L_eq_container ctn h ctn h φ *)\n  | L_eq_ctn : forall t1 t2 lb1 lb2 sf1 sf2 h1 h2 fs1 fs2 φ,\n      flow_to lb1 L_Label = true ->\n      flow_to lb2 L_Label = true ->\n      L_equivalence_tm t1 h1 t2 h2 φ->\n      L_equivalence_fs fs1 h1 fs2 h2 φ ->\n      L_equivalence_store sf1 h1 sf2 h2 φ ->\n    L_eq_container (Container t1 fs1 lb1 sf1) h1 (Container t2 fs2 lb2 sf2) h2 φ.\nHint Constructors L_eq_container. \n\nInductive L_eq_ctns : list container -> heap -> list container -> heap -> (bijection oid oid ) ->Prop :=\n  | L_eq_ctns_nil : forall h1 h2  φ,\n      L_eq_ctns nil h1 nil h2  φ\n  | L_eq_ctns_list : forall ctn1 ctns1 ctn2 ctns2 h1 h2  φ,\n      L_eq_container ctn1 h1 ctn2 h2 φ ->\n      L_eq_ctns ctns1 h1 ctns2 h2 φ ->\n       L_eq_ctns (ctn1 :: ctns1) h1 (ctn2 :: ctns2) h2  φ.\nHint Constructors L_eq_ctns. \n\n(* only called on configs with high containers at top *)\nFixpoint low_component (ct : Class_table) (ctn : container) (ctns_stack : list container) (h : heap) : config :=\nmatch ctn with \n | (Container t fs lb sf) =>\n       if (flow_to lb L_Label) then (Config ct (Container t fs lb sf) ctns_stack h) \n          else match ctns_stack with \n                | nil => (Config ct (Container null nil L_Label empty_stack_frame) nil h) \n                | ctn :: ctns' => low_component ct ctn ctns' h\n                end\nend.\nHint Unfold low_component.\n\nInductive L_equivalence_config : config -> config -> (bijection oid oid ) -> Prop :=\n  | L_equivalence_config_L : forall ct t1 fs1 lb1 lb2 sf1 t2 fs2 sf2 ctns1 ctns2 h1 h2 φ, \n      flow_to lb1 L_Label = true ->\n      flow_to lb2 L_Label = true ->\n      L_eq_container  (Container t1 fs1 lb1 sf1) h1 (Container t2 fs2 lb2 sf2) h2 φ->\n      L_eq_ctns ctns1 h1 ctns2 h2 φ ->\n      L_equivalence_config (Config ct (Container t1 fs1 lb1 sf1) ctns1 h1) (Config ct (Container t2 fs2 lb2 sf2) ctns2 h2)  φ\n  | L_equivalence_config_H : forall ct t1 fs1 lb1 sf1 t2 fs2 lb2 sf2 ctns1 ctns2 h1 h2  φ, \n      flow_to lb1 L_Label = false ->\n      flow_to lb2 L_Label = false ->\n       L_equivalence_config (low_component ct (Container t1 fs1 lb1 sf1) ctns1 h1)\n      (low_component ct (Container t2 fs2 lb2 sf2) ctns2 h2) φ  ->\n      L_equivalence_config (Config ct (Container t1 fs1 lb1 sf1) ctns1 h1) (Config ct (Container t2 fs2 lb2 sf2) ctns2 h2)  φ.  \nHint Constructors L_equivalence_config.\n\n(*\nLemma same_config_L_eq : forall ctn ctns ct h,\n     L_equivalence_config (Config ct ctn ctns h)  (Config ct ctn ctns h).\nProof with eauto. intros. destruct ctn. case_eq (flow_to l L_Label); intro. \n                  apply L_equivalence_config_L; auto.\napply L_equivalence_config_H; auto. \ngeneralize dependent t. generalize dependent f.\ngeneralize dependent l. generalize dependent s.\ninduction ctns; subst; auto. intros. unfold low_component. rewrite H; auto.\nintros. destruct a. unfold low_component. rewrite H; auto. \nauto.  fold low_component. case_eq (flow_to l0 L_Label); intro.\ndestruct ctns; auto. unfold low_component.\nrewrite H0; auto. destruct c.  unfold low_component.\nrewrite H0; auto.\ndestruct ctns; auto.\nQed. \nHint Resolve  same_config_L_eq.\n*)\n\nLemma value_L_eq : forall e v h1 h2  φ, \n  value v ->\n  L_equivalence_tm e h1 v h2  φ ->\n  value e.\nProof. intros. generalize dependent e. \n       induction v; subst; inversion H; auto;\n         intros;  inversion H0; subst; auto.\n       inversion H3; subst. auto. auto.\n       inversion H3; subst. auto. auto.\nQed. Hint Resolve       value_L_eq .  \n\nLemma value_L_eq2 : forall e v h1 h2  φ, \n  value v ->\n  L_equivalence_tm v h1 e h2  φ ->\n  value e.\nProof. intros. generalize dependent e.\n       induction v; subst; inversion H; auto;\n         intros;  inversion H0; subst; auto.\n       inversion H3; subst; auto.\n       inversion H3; subst; auto.\n       \nQed. \nHint Resolve value_L_eq2.\n\n(*\nLemma value_L_eq : forall e v h1 h2 T1 T2 ct  φ, \n  tm_has_type ct empty_context h1 e T1 -> \n  tm_has_type ct empty_context h2 v T2 -> \n  value v ->\n  L_equivalence_tm e h1 v h2  φ ->\n  value e.\nProof. intros. generalize dependent e. generalize dependent T1. generalize dependent T2.\n       induction v; subst; inversion H1; auto;\n         intros;  inversion H2; subst; auto.  inversion H3; subst. auto.\ninversion H3; subst; auto.  inversion H5; subst; auto. inversion H4. subst;auto. \ninversion H4. subst;auto.  inversion H5; subst; auto. inversion H4. subst;auto. \ninversion H4. subst;auto.\nQed. \nHint Resolve value_L_eq.\n\n\n\nLemma value_L_eq2 : forall e v h1 h2 T1 T2 ct  φ, \n  tm_has_type ct empty_context h2 e T2 -> \n  tm_has_type ct empty_context h1 v T1 -> \n  value v ->\n  L_equivalence_tm v h1 e h2  φ ->\n  value e.\nProof. intros. generalize dependent e. generalize dependent T1. generalize dependent T2.   induction v; subst; inversion H1; auto;\nintros;  inversion H2; subst; auto.  inversion H3; subst. auto. \ninversion H3; subst; auto.  inversion H5; subst; auto. inversion H4. subst;auto. \ninversion H4. subst;auto.  inversion H5; subst; auto. inversion H4. subst;auto. \ninversion H4. subst;auto.\nQed. \nHint Resolve value_L_eq2.\n *)\n\nLemma lookup_extended_heap : forall h o cls F lb ct ho,\n  wfe_heap ct h ->  \n  lookup_heap_obj h o =  Some (Heap_OBJ cls F lb) ->\n  lookup_heap_obj h o =\n     lookup_heap_obj (add_heap_obj h (get_fresh_oid h) ho) o.\nProof. intros. \n  assert (o <> (get_fresh_oid h) ).\n  intro contra. assert (lookup_heap_obj h (get_fresh_oid h) = None). \n  apply fresh_oid_heap with ct; auto. rewrite <- contra in H1. rewrite H1 in H0. \n  inversion H0. \n  unfold  lookup_heap_obj. unfold add_heap_obj.\n  assert (beq_oid o (get_fresh_oid h) = false).  apply beq_oid_not_equal. auto. \n  rewrite H2.  fold lookup_heap_obj. auto. Qed.\nHint Resolve lookup_extended_heap. \n\n\n  \n\nLemma cls_def_eq : forall o o0 cls fields lx cls0 fields0 lx0 h1' h2'  φ,\n    Some (Heap_OBJ cls fields lx) = lookup_heap_obj h1' o ->\n    Some (Heap_OBJ cls0 fields0 lx0) = lookup_heap_obj h2' o0 ->\n    bijection.left φ o = Some o0 ->\n    L_equivalence_heap h1' h2' φ ->\n    cls = cls0.\nProof with eauto.\n  intros. inversion H2; subst; auto.\n  destruct H3 with o o0; auto. rewrite <- H8 in H.  inversion H; subst; auto.\n  rewrite <- H9 in H0.  inversion H0; subst; auto.\n  apply H12. Qed.\nHint Resolve  cls_def_eq.\n\n\nLemma surface_syntax_L_equal : forall body h1 h2 φ, \n    surface_syntax body = true ->\n    L_equivalence_heap h1 h2 φ ->\n    L_equivalence_tm body h1 body h2 φ.\nProof with eauto. \n  intros.\n  induction body; subst;  inversion H; auto;\n    try (apply surface_syntax_if in H2; destruct H2; apply IHbody1 in H1; \n         apply IHbody2 in H2; auto).  \n  apply surface_syntax_triple in H2. destruct H2.\n  destruct H2. auto. \nQed.  \nHint Resolve surface_syntax_L_equal.\n\nLemma extend_bijection_preserve_tm_eq  {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} :\n  forall  φ o o' H1 H2 h1 h2 t1 t2,\n     L_equivalence_tm t1 h1 t2 h2  φ ->\n     L_equivalence_tm t1 h1 t2  h2 (bijection.extend_bijection φ o o' H1 H2).\nProof with eauto.\n  intros.\n  induction H; subst; auto.  \n  apply L_equivalence_tm_eq_object_L with cls1 F1 lb1 cls2 F2 lb2; auto.\n  \n  assert (left (extend_bijection φ o o' H1 H2)  o1 = \n          left φ o1).\n  apply left_extend_bijection_neq; auto.\n  intro contra. subst; auto. rewrite H in H1. inversion H1. \n  rewrite H6. auto.\n  apply L_equivalence_tm_eq_object_H with cls1 cls2  F1 lb1  F2 lb2; auto.\nQed.\nHint Resolve  extend_bijection_preserve_tm_eq.\n\n\nLemma extend_bijection_preserve_fs_eq  {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} :\n  forall  φ o o' H1 H2 h1 h2 fs1 fs2,\n    L_equivalence_fs fs1 h1 fs2 h2  φ ->\n    L_equivalence_fs fs1 h1 fs2 h2 (bijection.extend_bijection φ o o' H1 H2).\nProof with eauto.\n  intros.\n  induction H. auto.\n  auto.\nQed. Hint Resolve extend_bijection_preserve_fs_eq.\n\nLemma sf_decision :\n  forall (sf: stack_frame) x ,  (exists v,  sf x = Some v) \\/ sf x = None.\nProof with eauto.\n  intros.\n  destruct sf.\n  left; exists t; auto.\n  right. auto.    \nDefined.\nHint Resolve sf_decision.\n\nLemma extend_bijection_preserve_store_eq  {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} :\n  forall  φ o o' H1 H2 h1 h2 sf1 sf2,\n    L_equivalence_store sf1 h1 sf2 h2  φ ->\n    L_equivalence_store sf1 h1 sf2 h2 (bijection.extend_bijection φ o o' H1 H2).\nProof with eauto.\n  intros.\n  inversion H; subst;auto.\n  apply L_equivalence_store_L; auto.\n  split; auto. destruct H0.\n  intros.\n  assert (L_equivalence_tm v1 h1 v2 h2 φ).\n  apply H0 with x; auto.\n  apply extend_bijection_preserve_tm_eq ; auto.\n  destruct H0; auto. \nQed. Hint Resolve  extend_bijection_preserve_store_eq.\n\n\nLemma extend_bijection_preserve_ctn_eq  {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} :\n  forall  φ o o' H1 H2 h1 h2 ctn1 ctn2,\n    L_eq_container ctn1 h1 ctn2 h2 φ ->\n    L_eq_container ctn1 h1 ctn2 h2 (bijection.extend_bijection φ o o' H1 H2).\nProof with eauto.\n  intros.\n  induction H; subst; auto.\n  Qed. Hint Resolve extend_bijection_preserve_ctn_eq.\n\nLemma extend_bijection_preserve_stack_eq  {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} :\n  forall  φ o o' H1 H2 h1 h2 ctns_stack1 ctns_stack2,\n    L_eq_ctns ctns_stack1 h1 ctns_stack2 h2  φ ->\n    L_eq_ctns ctns_stack1 h1 ctns_stack2 h2 (bijection.extend_bijection φ o o' H1 H2).\nProof with eauto.\n  intros.\n  induction H. auto.\n  subst; auto.\nQed. Hint Resolve extend_bijection_preserve_stack_eq.\n\nLemma extend_heap_preserve_L_eq_tm {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall t1 h1  t2 h2  lb2 cls_def ct  (φ:bijection oid oid)  φ'  (H1: (left φ (get_fresh_oid h1)  = None)) ( H2: (right φ (get_fresh_oid h2)  = None)) ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_tm t1 h1 t2 h2 φ ->\n  L_equivalence_heap h1 h2 φ ->\n  φ' = (extend_bijection φ (get_fresh_oid h1)(get_fresh_oid h2) H1 H2) ->\n  (L_equivalence_tm t1 (add_heap_obj h1 (get_fresh_oid h1) \n                                     (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2))\n                    t2 (add_heap_obj h2 (get_fresh_oid h2)\n                      (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2)) φ').\nProof.\n  intros t1 h1  t2 h2  lb2 cls_def ct φ φ' H1 H2.\n  intros.\n  generalize dependent t2. \n  induction t1; intros; inversion H3; subst; auto.\n\n  apply L_equivalence_tm_eq_object_L with cls1 F1 lb1 cls2 F2 lb0; auto.\n  assert (left (extend_bijection φ ( get_fresh_oid h1) ( get_fresh_oid h2) H1 H2)  o = \n          left φ o).\n  apply left_extend_bijection_neq; auto.\n  intro contra. subst; auto. rewrite H7 in H1. inversion H1. \n  rewrite H5. auto.\n  assert (o <> get_fresh_oid h1).\n  apply lookup_extend_heap_fresh_oid with\n      ct\n      (Heap_OBJ cls1 F1 lb1); auto.\n  apply beq_oid_not_equal in H5; auto.\n  unfold lookup_heap_obj. unfold add_heap_obj.\n  rewrite H5. fold lookup_heap_obj. auto.\n\n  assert (o2 <> get_fresh_oid h2).\n  apply lookup_extend_heap_fresh_oid with\n      ct\n      (Heap_OBJ cls2 F2 lb0); auto.\n  apply beq_oid_not_equal in H5; auto.\n  unfold lookup_heap_obj. unfold add_heap_obj.\n  rewrite H5. fold lookup_heap_obj. auto.\n\n  apply L_equivalence_tm_eq_object_H with cls1 cls2  F1 lb1 F2 lb0; auto.\n\n    assert (o <> get_fresh_oid h1).\n  apply lookup_extend_heap_fresh_oid with\n      ct\n      (Heap_OBJ cls1 F1 lb1); auto.\n  apply beq_oid_not_equal in H5; auto.\n  unfold lookup_heap_obj. unfold add_heap_obj.\n  rewrite H5. fold lookup_heap_obj. auto.\n\n  assert (o2 <> get_fresh_oid h2).\n  apply lookup_extend_heap_fresh_oid with\n      ct\n      (Heap_OBJ cls2 F2 lb0); auto.\n  apply beq_oid_not_equal in H5; auto.\n  unfold lookup_heap_obj. unfold add_heap_obj.\n  rewrite H5. fold lookup_heap_obj. auto.\nQed.\nHint Resolve  extend_heap_preserve_L_eq_tm.\n\nLemma extend_heap_preserve_L_eq_fs {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall fs1 h1  fs2 h2  lb2 cls_def ct  (φ:bijection oid oid)  φ'  (H1: (left φ (get_fresh_oid h1)  = None)) ( H2: (right φ (get_fresh_oid h2)  = None)) ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_fs fs1 h1 fs2 h2 φ ->\n  L_equivalence_heap h1 h2 φ ->\n  φ' = (extend_bijection φ (get_fresh_oid h1)(get_fresh_oid h2) H1 H2) ->\n  (L_equivalence_fs fs1 (add_heap_obj h1 (get_fresh_oid h1) \n                                     (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2))\n                    fs2 (add_heap_obj h2 (get_fresh_oid h2)\n                      (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2)) φ').\nProof.\n  intros fs1 h1  fs2 h2  lb2 cls_def ct φ φ' H1 H2.\n  intros.\n  generalize dependent fs2. \n  induction fs1; intros; inversion H3; subst; auto.\n  apply  L_equal_fs; auto.\n  apply extend_heap_preserve_L_eq_tm with ct φ H1 H2; auto. \nQed. Hint Resolve  extend_heap_preserve_L_eq_fs.\n\nLemma extend_heap_preserve_L_eq_store {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall sf1 h1  sf2 h2  lb2 cls_def ct  (φ:bijection oid oid)  φ'  (H1: (left φ (get_fresh_oid h1)  = None)) ( H2: (right φ (get_fresh_oid h2)  = None)) ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_store sf1 h1 sf2 h2 φ ->\n  L_equivalence_heap h1 h2 φ ->\n  wfe_stack_frame ct h1 sf1 ->\n   wfe_stack_frame ct h2 sf2 ->\n  φ' = (extend_bijection φ (get_fresh_oid h1)(get_fresh_oid h2) H1 H2) ->\n  (L_equivalence_store sf1 (add_heap_obj h1 (get_fresh_oid h1) \n                                     (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2))\n                    sf2 (add_heap_obj h2 (get_fresh_oid h2)\n                      (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2)) φ').\nProof.\n  intros sf1 h1  sf2 h2  lb2 cls_def ct φ φ' H1 H2.\n  intros.\n  inversion H4; subst; auto.\n  inversion H3; subst; auto. \n  apply L_equivalence_store_L; auto.\n  intros. destruct H7.\n  split; auto. intros. \n  assert (L_equivalence_tm v1 h1 v2 h2 φ).\n  apply H7 with x; auto.  \n  apply extend_heap_preserve_L_eq_tm with ct φ H1 H2; auto.\n  \nQed. Hint Resolve  extend_heap_preserve_L_eq_store. \n\n\n\nLemma extend_heap_preserve_L_eq_ctn {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} :\n  forall h1  h2  lb cls_def ct  (φ:bijection oid oid)  φ'\n         (H1: (left φ (get_fresh_oid h1)  = None)) ( H2: (right φ (get_fresh_oid h2)  = None))\n  ctn1 ctn2,\n    wfe_heap ct h2 ->  wfe_heap ct h1 ->\n    valid_ctn ct ctn1 h1 -> valid_ctn ct ctn2 h2  ->\n  L_eq_container ctn1 h1 ctn2 h2 φ ->\n  L_equivalence_heap h1 h2 φ ->\n  φ' = (extend_bijection φ (get_fresh_oid h1)(get_fresh_oid h2) H1 H2) ->\n  (L_eq_container ctn1 (add_heap_obj h1 (get_fresh_oid h1) \n                                     (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb))\n                    ctn2 (add_heap_obj h2 (get_fresh_oid h2)\n                      (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb)) φ').\nProof.\n  intros h1  h2  lb cls_def ct φ  φ' H1 H2 ctn1 ctn2.\n  intros.\n  \n  generalize dependent ctn2. \n  induction ctn1; intros;subst; auto;\n  inversion H5; subst; auto.\n  apply  L_eq_ctn; auto. \n  apply extend_heap_preserve_L_eq_tm with ct φ H1 H2; auto.\n  apply extend_heap_preserve_L_eq_fs with ct φ H1 H2; auto.\n  apply extend_heap_preserve_L_eq_store with ct φ H1 H2; auto.\n  inversion H3; auto. inversion H4; auto. \nQed. Hint Resolve extend_heap_preserve_L_eq_ctn. \n\nLemma extend_heap_preserve_L_eq_ctns {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall ctns1 h1  ctns2 h2  lb2 cls_def ct  (φ:bijection oid oid)  φ'  (H1: (left φ (get_fresh_oid h1)  = None)) ( H2: (right φ (get_fresh_oid h2)  = None)) ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_eq_ctns ctns1 h1 ctns2 h2 φ ->\n  L_equivalence_heap h1 h2 φ ->\n  valid_ctns ct ctns1 h1 ->\n  valid_ctns ct ctns2 h2 -> \n  φ' = (extend_bijection φ (get_fresh_oid h1)(get_fresh_oid h2) H1 H2) ->\n  (L_eq_ctns ctns1 (add_heap_obj h1 (get_fresh_oid h1) \n                                     (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2))\n                    ctns2 (add_heap_obj h2 (get_fresh_oid h2)\n                      (Heap_OBJ  cls_def (init_field_map (find_fields cls_def) empty_field_map) lb2)) φ').\nProof.\n  intros ctns1 h1 ctns2 h2  lb2 cls_def ct φ φ' H1 H2.\n  intros.\n  generalize dependent ctns2.  \n  induction ctns1; intros; inversion H3; subst; auto.\n  apply L_eq_ctns_list; auto.  \n  apply extend_heap_preserve_L_eq_ctn with ct φ H1 H2; auto.\n  inversion H5; auto. inversion H6; auto.\n  apply   IHctns1; auto. \n  inversion H5; auto. inversion H6; auto.\nQed. Hint Resolve extend_heap_preserve_L_eq_ctns.\n\n\nLemma low_component_with_L_Label : forall ct t fs lb sf ctns h,\n    flow_to lb L_Label = true ->\n    low_component ct (Container t fs lb sf) ctns h =\n    Config ct (Container t fs lb sf) ctns h.\nProof.\n  intros .     \n  induction ctns.\n  unfold low_component.  rewrite H. auto.\n  unfold low_component.  rewrite H. auto.\nQed. Hint Resolve low_component_with_L_Label.\n\n  \nLemma low_component_irrelevant : forall ctn1 ctn2 ctns1 ctns2 h1 h2 φ ct,\n      L_eq_container ctn1 h1 ctn2 h2 φ ->\n      L_eq_ctns ctns1 h1 ctns2 h2 φ ->\n      L_equivalence_config (low_component ct ctn1 ctns1 h1) (low_component ct ctn2 ctns2 h2) φ.\nProof with eauto.\n  intros. destruct ctn1. destruct ctn2.\n  inversion H; subst; auto.\n  case_eq (flow_to l0 L_Label); intro.\n  generalize dependent ctns2. \n   induction ctns1. intros. \n   inversion H0; subst; auto. unfold low_component. rewrite H1; auto.\n   intros.\n   rewrite H12. auto. \n\n   intros. \n   inversion H0; subst; auto. unfold low_component. rewrite H1; auto.\n   rewrite H12; auto. rewrite H13 in H1. inversion H1. \n   \n(*\n   generalize dependent t0. generalize dependent f0.\n   generalize dependent l0. generalize dependent s0. \n   generalize dependent ctns2. \n  induction ctns1. intros. inversion H0; subst; auto.\n  unfold low_component. rewrite H1; auto.\n  \n  intros. inversion H0; subst; auto. \n  unfold low_component. rewrite H1; auto. fold low_component.\n  destruct a. destruct ctn2. inversion H4; subst; auto.\n  case_eq (flow_to l1 L_Label); intro.\n  assert ((low_component ct (Container t1 f1 l1 s1) ctns1 h2) =\n          Config ct (Container t1 f1 l1 s1) ctns1 h2 ).\n  apply low_component_with_L_Label. auto. rewrite H3.\n  assert ((low_component ct (Container t1 f1 l1 s1) ctns3 h2) =\n          Config ct (Container t1 f1 l1 s1) ctns3 h2 ).\n  apply low_component_with_L_Label. auto. rewrite H6.\n  auto.\n  apply IHctns1; auto. \n\n  assert ((low_component ct (Container t f l s) ctns1 h2) =\n          Config ct (Container t f l s) ctns1 h2 ).\n  apply low_component_with_L_Label. auto. rewrite H2.\n  assert ((low_component ct (Container t1 f1 l1 s1) ctns3 h2) =\n          Config ct (Container t1 f1 l1 s1) ctns3 h2 ).\n  apply low_component_with_L_Label. auto. rewrite H3.\n  auto.\n\n  assert ((low_component ct (Container t f l s) ctns1 h1) =\n          Config ct (Container t f l s) ctns1 h1 ).\n  apply low_component_with_L_Label. auto. rewrite H1.\n  assert ((low_component ct (Container t0 f0 l0 s0) ctns2 h2) =\n          Config ct (Container t0 f0 l0 s0) ctns2 h2 ).\n  apply low_component_with_L_Label. auto. rewrite H2.\n  auto.*)\nQed.\nHint Resolve low_component_irrelevant.\n\nLemma update_field_preserve_L_eq_tm {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} :\n  forall  (φ:bijection oid oid) h1 h2 ct cls F lo o lb1 lx\n          cls0 F0 lo0 o0 lb2 lx0 t1 t2 v v0 f0,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_tm t1 h1 t2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to (join_label lb1 lx) lo  = true ->\n  Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n  flow_to (join_label lb2 lx0) lo0 = true ->\n  L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n  L_equivalence_tm (v_opa_l v lx) h1 (v_opa_l v0 lx0) h2 φ ->\n  flow_to lb1 L_Label = true ->\n  flow_to lb2 L_Label = true ->\n  value v ->\n  value v0 ->\n  L_equivalence_tm t1 (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f0 v) lo))\n                    t2 (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0)) φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo o lb1 lx cls0 F0 lo0 o0 lb2 lx0 t1 t2 v v0 f0.\n  intros.\n  \n  inversion H8; subst; auto.\n  assert ( flow_to (join_label lb1 lx0) L_Label = true).\n  apply join_L_label_flow_to_L; auto.\n  apply L_Label_flow_to_L in H13. rewrite H13 in H4. \n\n  assert ( flow_to (join_label lb2 lx0) L_Label = true).\n  apply join_L_label_flow_to_L; auto.\n(*  apply L_Label_flow_to_L in H14. rewrite H14 in H6.  *)\n\n  generalize dependent t2;  \n    induction t1; intros;     inversion H2; subst; auto.  \n\n  case_eq (beq_oid o1 o); intro.\n  apply beq_oid_equal in H15.\n  remember (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f0 v) lo))  as h'.\n  assert (Some  (Heap_OBJ cls (fields_update F f0 v) lo) = lookup_heap_obj h' o).\n  apply lookup_updated with h1 (Heap_OBJ cls1 F1 lb0) ; rewrite <- H15; subst;  auto.\n  case_eq (beq_oid o3 o0); intro.\n  apply beq_oid_equal in H26.\n  remember (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0))  as h2'.\n  assert (Some   (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0)  = lookup_heap_obj h2' o0).\n  apply lookup_updated with h2 (Heap_OBJ cls2 F2 lb3) ; rewrite <- H26; subst;  auto.\n  inversion H7; subst; auto. \n  apply L_equivalence_tm_eq_object_L with cls (fields_update F f0 v) lo cls0\n                                          (fields_update F0 f0 v0) lo0; subst; auto.\n  try (rewrite_lookup).\n  try (rewrite_lookup).\n\n  try (rewrite_lookup).\n  subst; auto. \n\n  remember (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0))  as h2'.\n  assert (Some (Heap_OBJ cls2 F2 lb3) = lookup_heap_obj h2' o3).\n  apply lookup_updated_not_affected with  o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0) h2; auto. intro contra. rewrite contra in H26. pose proof (beq_oid_same o0).\n  try (inconsist).\n  inversion H7; subst; auto. \n  apply L_equivalence_tm_eq_object_L with cls (fields_update F f0 v) lo cls2\n                                          F2 lb3; subst; auto.\n  try (rewrite_lookup).\n  try (rewrite_lookup).\n  remember (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f0 v) lo))  as h'.\n  assert (  Some (Heap_OBJ cls1 F1 lb0)  = lookup_heap_obj h' o1).\n  apply lookup_updated_not_affected with  o (Heap_OBJ cls (fields_update F f0 v) lo) h1; auto.\n  intro contra.\n  try (beq_oid_inconsist).\n\n  case_eq (beq_oid o3 o0); intro.\n  apply beq_oid_equal in H26.\n  remember (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0))  as h2'.\n  assert (Some   (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0)  = lookup_heap_obj h2' o0).\n  apply lookup_updated with h2 (Heap_OBJ cls2 F2 lb3) ; rewrite <- H26; subst;  auto.\n  inversion H7; subst; auto. \n  apply L_equivalence_tm_eq_object_L with cls1 F1 lb0 cls0\n                                          (fields_update F0 f0 v0) lo0; subst; auto.\n  try (rewrite_lookup).\n  try (rewrite_lookup).\n  remember (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0))  as h2'.\n  assert (Some (Heap_OBJ cls2 F2 lb3) = lookup_heap_obj h2' o3).\n  apply lookup_updated_not_affected with  o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0) h2; auto. intro contra.\n  try (beq_oid_inconsist).\n\n  apply L_equivalence_tm_eq_object_L with cls1 F1 lb0 cls2\n                                          F2 lb3; subst; auto.\n\n\n  case_eq (beq_oid o1 o); intro.\n  apply beq_oid_equal in H15. rewrite H15 in H16.\n  rewrite <- H16 in H3; inversion H3; subst; auto. \n  remember (update_heap_obj h1 o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0))  as h'.\n  assert (Some (Heap_OBJ cls1 (fields_update F1 f0 v) lb0) = lookup_heap_obj h' o).\n  apply lookup_updated with h1 (Heap_OBJ cls1 F1 lb0); auto. \n  case_eq (beq_oid o3 o0); intro.\n  apply beq_oid_equal in H24.\n  remember (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0))  as h2'.\n  assert (Some   (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0)  = lookup_heap_obj h2' o0).\n  apply lookup_updated with h2 (Heap_OBJ cls2 F2 lb3) ; rewrite <- H24; subst;  auto.\n  apply L_equivalence_tm_eq_object_H with cls1 cls0 (fields_update F1 f0 v) lb0\n                                          (fields_update F0 f0 v0) lo0; subst; auto.\n  try (rewrite_lookup).\n\n  remember (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0))  as h2'.\n  assert (Some (Heap_OBJ cls2 F2 lb3) = lookup_heap_obj h2' o3).\n  apply lookup_updated_not_affected with  o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0) h2; auto.\n  intro contra.  try (beq_oid_inconsist).\n  \n  apply L_equivalence_tm_eq_object_H with cls1 cls2  (fields_update F1 f0 v) lb0\n                                          F2 lb3; subst; auto.\n\n  remember ((update_heap_obj h1 o (Heap_OBJ cls (fields_update F f0 v) lo)))  as h'.\n  assert (  Some (Heap_OBJ cls1 F1 lb0)  = lookup_heap_obj h' o1).\n  apply lookup_updated_not_affected with  o (Heap_OBJ cls (fields_update F f0 v) lo) h1; auto.\n  intro contra.\n  try (beq_oid_inconsist).\n  \n  case_eq (beq_oid o3 o0); intro.\n  apply beq_oid_equal in H25.\n  rewrite H25 in H20. rewrite <- H20 in H5; inversion H5; subst; auto.\n\n  remember ((update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)))  as h2'.\n  assert (Some (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)  = lookup_heap_obj h2' o0).\n  apply lookup_updated with h2 (Heap_OBJ cls2 F2 lb3); subst;  auto.\n  apply L_equivalence_tm_eq_object_H with cls1 cls2 F1 lb0 \n                                          (fields_update F2 f0 v0) lb3; subst; auto.\n  remember (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0))  as h2'.  \n  assert (Some (Heap_OBJ cls2 F2 lb3) = lookup_heap_obj h2' o3).\n  apply lookup_updated_not_affected with  o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0) h2; auto.\n  intro contra.\n  try (beq_oid_inconsist).\n  apply L_equivalence_tm_eq_object_H with cls1 cls2 F1 lb0\n                                          F2 lb3; subst; auto.\n\n   \n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lx lb1; auto. \n  assert ( flow_to (join_label lb2 lx0) L_Label = false).\n  apply flow_join_label with lx0 lb2; auto. \n\n  \n  assert (flow_to lo L_Label = false).\n  apply flow_transitive with (join_label lb1 lx); auto. \n  assert (flow_to lo0 L_Label = false).\n  apply flow_transitive with (join_label lb2 lx0); auto.\n\n\n  generalize dependent t2.  \n  induction t1; intros;inversion H2; subst; auto.\n\n  case_eq (beq_oid o1 o); intro.\n  apply beq_oid_equal in H18.\n  rewrite H18 in H21. rewrite <- H21 in H3; inversion H3; subst; auto.\n  try (inconsist).\n\n  case_eq (beq_oid o3 o0); intro.\n  apply beq_oid_equal in H27.\n  rewrite H27 in H25.\n  try (rewrite_lookup).\n\n  remember (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f0 v) lo))  as h'.\n  assert (  Some (Heap_OBJ cls1 F1 lb0)  = lookup_heap_obj h' o1).\n  apply lookup_updated_not_affected with  o (Heap_OBJ cls (fields_update F f0 v) lo) h1; auto.\n  intro contra.\n  try (beq_oid_inconsist).\n\n\n  remember (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0))  as h2'.\n  assert (Some (Heap_OBJ cls2 F2 lb3) = lookup_heap_obj h2' o3).\n  apply lookup_updated_not_affected with  o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0) h2; auto.\n  intro contra.\n  try (beq_oid_inconsist).\n\n  apply L_equivalence_tm_eq_object_L with cls1  F1 lb0 cls2\n                                          F2 lb3; subst; auto.\n\n  case_eq (beq_oid o1 o); intro.\n  apply beq_oid_equal in H18.\n  remember (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f0 v) lo))  as h'.\n  assert (Some  (Heap_OBJ cls (fields_update F f0 v) lo) = lookup_heap_obj h' o).\n  apply lookup_updated with h1 (Heap_OBJ cls1 F1 lb0) ; rewrite <- H18; subst;  auto.\n  case_eq (beq_oid o3 o0); intro.\n  apply beq_oid_equal in H27.\n  subst; auto.\n  rewrite <- H24 in H5; inversion H5; subst; auto. \n  rewrite <- H20 in H3; inversion H3; subst; auto.\n  remember (update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3))  as h2'.\n  assert (Some (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)  = lookup_heap_obj h2' o0).\n  apply lookup_updated with h2  (Heap_OBJ cls2 F2 lb3) ;  subst;  auto.\n  \n  apply L_equivalence_tm_eq_object_H with cls1 cls2 (fields_update F1 f0 v) lb0\n                                          (fields_update F2 f0 v0) lb3; subst; auto.\n  subst; auto.\n  rewrite <- H20 in H3; inversion H3; subst; auto.\n  remember (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0))  as h2'.\n  \n  assert (Some (Heap_OBJ cls2 F2 lb3)  = lookup_heap_obj h2' o3).\n  apply lookup_updated_not_affected with  o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0) h2; auto.\n  intro contra. rewrite contra in H27. pose proof (beq_oid_same o0).\n  try (inconsist).\n  apply L_equivalence_tm_eq_object_H with cls1 cls2 (fields_update F1 f0 v) lb0 \n                                          F2 lb3; subst; auto.\n  \n remember ((update_heap_obj h1 o (Heap_OBJ cls (fields_update F f0 v) lo)))  as h'.\n  assert (  Some (Heap_OBJ cls1 F1 lb0)  = lookup_heap_obj h' o1).\n  apply lookup_updated_not_affected with  o (Heap_OBJ cls (fields_update F f0 v) lo) h1; auto.\n  intro contra. rewrite contra in H18. pose proof (beq_oid_same o).\n  try (inconsist).\n  case_eq (beq_oid o3 o0); intro.  \n  apply beq_oid_equal in H27.\n  subst; auto.\n  rewrite <- H24 in H5; inversion H5; subst; auto.   \n  remember ((update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)))  as h2'.\n  assert (Some (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)  = lookup_heap_obj h2' o0).\n  apply lookup_updated with h2 (Heap_OBJ cls2 F2 lb3); subst;  auto.\n  apply L_equivalence_tm_eq_object_H with cls1 cls2 F1 lb0 \n                                          (fields_update F2 f0 v0) lb3; subst; auto.\n  remember (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0))  as h2'.\n  \n  assert (Some (Heap_OBJ cls2 F2 lb3) = lookup_heap_obj h2' o3).\n  apply lookup_updated_not_affected with  o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0) h2; auto.\n  intro contra.\n  rewrite contra in H27. pose proof (beq_oid_same o0).\n  try (inconsist).\n  apply L_equivalence_tm_eq_object_H with cls1 cls2 F1 lb0\n                                          F2 lb3; subst; auto.\nQed.  Hint Resolve  update_field_preserve_L_eq_tm.\n\n\n\nLemma update_field_preserve_L_eq_fs {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} :\n  forall  (φ:bijection oid oid) h1 h2 ct cls F lo o lb1 lx\n          cls0 F0 lo0 o0 lb2 lx0 fs1 fs2  v v0 f0,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_fs fs1 h1 fs2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n  flow_to (join_label lb2 lx0) lo0 = true ->\n  L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n  L_equivalence_tm (v_opa_l v lx) h1 (v_opa_l v0 lx0) h2 φ ->\n  flow_to lb1 L_Label = true ->\n  flow_to lb2 L_Label = true ->\n  value v ->\n  value v0 ->\n  L_equivalence_fs fs1 (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f0 v) lo))\n                    fs2 (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0)) φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo o lb1 lx cls0 F0 lo0 o0 lb2 lx0 fs1 fs2 v v0 f0.\n  intros.\n  generalize dependent fs2. \n  induction fs1; intros; inversion H2; subst; auto.\n  apply  L_equal_fs; auto.\n  apply update_field_preserve_L_eq_tm with ct lb1 lx lb2 lx0; auto.\n  \nQed. Hint Resolve update_field_preserve_L_eq_fs.\n\n\nLemma update_field_preserve_L_eq_store {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} :\n  forall  (φ:bijection oid oid) h1 h2 ct cls F lo o lb1 lx\n          cls0 F0 lo0 o0 lb2 lx0 sf1 sf2  v v0 f0,\n    wfe_heap ct h2 ->  wfe_heap ct h1 ->\n    wfe_stack_frame ct h1 sf1 -> wfe_stack_frame ct h2 sf2 ->\n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_store sf1 h1 sf2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to  (join_label lb1 lx) lo = true ->\n  Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n  flow_to  (join_label lb2 lx0) lo0 = true ->\n  L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n  L_equivalence_tm (v_opa_l v lx) h1 (v_opa_l v0 lx0) h2 φ ->\n  flow_to lb1 L_Label = true ->\n  flow_to lb2 L_Label = true ->\n  value v ->\n  value v0 ->\n  L_equivalence_store sf1 (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f0 v) lo))\n                    sf2 (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0)) φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo o lb1 lx cls0 F0 lo0 o0 lb2 lx0 sf1 sf2 v v0 f0.\n  intros.\n\n  inversion H3; subst; auto.\n  \n  intros. inversion H10; subst; auto.\n  inversion H4; subst; auto.\n  apply L_equivalence_store_L; auto.\n  intros. destruct H20.\n  split; auto. intros. \n  assert (L_equivalence_tm v1 h1 v2 h2 φ).\n  apply H20 with x; auto.  \n  apply  update_field_preserve_L_eq_tm with ct lb1 lx0 lb2 lx0; auto. \n\n\n  inversion H4; subst; auto. \n  apply L_equivalence_store_L; auto.\n  destruct H20.\n  split; auto. intros. \n  assert (L_equivalence_tm v1 h1 v2 h2 φ).\n  apply H20 with x; auto.  \n  apply  update_field_preserve_L_eq_tm with ct lb1 lx lb2 lx0; auto. \nQed. \nHint Resolve update_field_preserve_L_eq_store.\n\n\n\n\nLemma update_field_preserve_L_eq_ctn {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} :\n  forall  (φ:bijection oid oid) h1 h2 ct cls F lo o lb1 lx\n          cls0 F0 lo0 o0 lb2 lx0 ctn1 ctn2 v v0 f0,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_eq_container ctn1 h1 ctn2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n  flow_to (join_label lb2 lx0) lo0 = true ->\n  L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n  L_equivalence_tm (v_opa_l v lx) h1 (v_opa_l v0 lx0) h2 φ ->\n  flow_to lb1 L_Label = true ->\n  flow_to lb2 L_Label = true ->\n  value v ->\n  value v0 ->\n  valid_ctn ct ctn1 h1 ->   valid_ctn ct ctn2 h2 ->\n  L_eq_container ctn1 (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f0 v) lo))\n                    ctn2 (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0)) φ.\nProof with eauto.\n  intros.\n  inversion H2; subst; auto.\n  apply L_eq_ctn; auto.\n  auto. \n  apply update_field_preserve_L_eq_tm with ct lb1 lx lb2 lx0; auto.\n  apply update_field_preserve_L_eq_fs with ct lb1 lx lb2 lx0; auto.\n  apply update_field_preserve_L_eq_store with ct lb1 lx lb2 lx0; auto.\n  inversion H13; auto. inversion H14; auto. \nQed. Hint Resolve update_field_preserve_L_eq_ctn.\n  \nLemma update_field_preserve_L_eq_ctns {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} :\n  forall  (φ:bijection oid oid) h1 h2 ct cls F lo o lb1 lx\n          cls0 F0 lo0 o0 lb2 lx0 ctns1 ctns2 v v0 f0,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_eq_ctns ctns1 h1 ctns2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to  (join_label lb1 lx) lo = true ->\n  Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n  flow_to (join_label lb2 lx0) lo0 = true ->\n  L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n  L_equivalence_tm (v_opa_l v lx) h1 (v_opa_l v0 lx0) h2 φ ->\n  flow_to lb1 L_Label = true ->\n  flow_to lb2 L_Label = true ->\n  value v ->\n  value v0 ->\n  valid_ctns ct ctns1 h1 ->   valid_ctns ct ctns2 h2 ->\n  L_eq_ctns ctns1 (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f0 v) lo))\n                    ctns2 (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0)) φ.\nProof with eauto.\n  intros.\n  generalize dependent ctns2.\n  induction ctns1; intros; inversion H2; subst; auto.  \n  apply L_eq_ctns_list; auto.  \n  apply update_field_preserve_L_eq_ctn with ct lb1 lx lb2 lx0; auto.\n  inversion H13; auto. \n  inversion H14; auto. \n  apply   IHctns1; auto. \n  inversion H13; auto. \n  inversion H14; auto. \n  \nQed. Hint Resolve update_field_preserve_L_eq_ctns.\n\n(*\nLemma value_L_eq_ : forall e v h1 h2 T1 T2 ct  φ gamma1 gamma2, \n  tm_has_type ct gamma1 h1 e T1 -> \n  tm_has_type ct gamma2 h2 v T2 -> \n  value v ->\n  L_equivalence_tm e h1 v h2  φ ->\n  value e.\nProof. intros. generalize dependent e. generalize dependent T1. generalize dependent T2.   induction v; subst; inversion H1; auto;\nintros;  inversion H2; subst; auto.  inversion H3; subst. auto. \ninversion H3; subst; auto.  inversion H5; subst; auto. inversion H4. subst;auto. \ninversion H4. subst;auto.  inversion H5; subst; auto. inversion H4. subst;auto. \ninversion H4. subst;auto.\nQed. \nHint Resolve value_L_eq_.\n\nLemma value_L_eq2_ : forall e v h1 h2 T1 T2 ct  φ gamma2 gamma1, \n  tm_has_type ct gamma2 h2 e T2 -> \n  tm_has_type ct gamma1 h1 v T1 -> \n  value v ->\n  L_equivalence_tm v h1 e h2  φ ->\n  value e.\nProof. intros. generalize dependent e. generalize dependent T1. generalize dependent T2.   induction v; subst; inversion H1; auto;\nintros;  inversion H2; subst; auto.  inversion H3; subst. auto. \ninversion H3; subst; auto.  inversion H5; subst; auto. inversion H4. subst;auto. \ninversion H4. subst;auto.  inversion H5; subst; auto. inversion H4. subst;auto. \ninversion H4. subst;auto.\nQed. \nHint Resolve value_L_eq2.\n*)\n\n\n\n(*\n\nInductive eq_φ : (bijection.bijection oid oid) -> heap -> Prop :=\n| same_mapping : forall h φ, \n    (forall o  cls F lb,\n    lookup_heap_obj h o = Some (Heap_OBJ cls F lb) ->\n    flow_to lb L_Label = true ->\n    bijection.left φ o = Some o) ->\n    eq_φ φ h.                             \nHint Constructors eq_φ.                       \n\nLemma same_tm_L_eq : forall ct t h gamma  φ,\n    eq_φ φ h -> \n    forall T, tm_has_type ct gamma h  t T ->\n    L_equivalence_tm t h t h φ.\nProof with eauto.\n  intros.\n  generalize dependent T. \n  induction t; subst; auto; intros; inversion H0; subst; auto;\n  try ( apply IHt in H5; auto).\n  try ( apply IHt in H3; auto).\n  apply IHt1 in H4. \n  apply IHt2 in H5. auto. \n  apply IHt in H9. auto. \n  apply IHt in H7. auto.\n  apply IHt1 in H4. \n  apply IHt2 in H8. auto. \n  apply IHt1 in H7.\n  apply IHt2 in H9.\n  apply IHt3 in H10. auto. \n  apply IHt1 in H6. apply IHt2 in H8. auto.\n  destruct H7 as [F]. destruct H1 as [lo].\n  case_eq (flow_to lo L_Label); intro.\n  apply L_equivalence_tm_eq_object_L with cls_def F lo cls_def F\nlo; auto. \n  inversion H; subst; auto.\n  apply H5 with cls_def F lo; auto.\n  apply L_equivalence_tm_eq_object_H with cls_def F lo cls_def F\n                                          lo; auto.\n  apply IHt in H7; auto. case_eq (flow_to l L_Label); intro; auto.   \n  apply IHt in H7; auto. case_eq (flow_to l L_Label); intro; auto. \nQed. Hint Resolve  same_tm_L_eq.   \n\nLemma same_fs_L_eq : forall ct h gamma fs φ,\n    eq_φ φ h -> \n    forall T, fs_has_type ct gamma h fs T ->\n    L_equivalence_fs fs h fs h φ.\nProof with eauto.\n  induction fs; intros. auto.\n  apply  L_equal_fs; auto.\n  inversion H0; subst;  auto; \n    try (apply same_tm_L_eq with ct gamma T0; auto).\n  (apply same_tm_L_eq with ct gamma (OpaqueLabeledTy (classTy returnT)); auto).\n  inversion H3; subst; auto.\n  remember ( (update_typing empty_context arg_id0 (classTy arguT0))) as Gamma'.\n  apply T_MethodCall with Gamma' T cls_def0 body0 arg_id0 arguT0; auto.\n\n  (apply same_tm_L_eq with ct gamma (OpaqueLabeledTy (classTy returnT)); auto).\n  inversion H3; subst; auto.\n  remember ( (update_typing empty_context arg_id0 (classTy arguT0))) as Gamma'.\n  apply T_MethodCall with Gamma' T cls_def0 body0 arg_id0 arguT0; auto. \n\n  (apply same_tm_L_eq with ct gamma voidTy; auto).\n  (apply same_tm_L_eq with ct gamma voidTy; auto).\n  inversion H0; subst; auto;  try (apply   IHfs with (ArrowTy T0 T'); auto; fail);\n    try (apply   IHfs with (ArrowTy T1 T'); auto; fail).\n  apply IHfs with (ArrowTy  (classTy cls') T'); auto.\n  apply IHfs with  (ArrowTy (OpaqueLabeledTy (classTy returnT)) T'); auto.\n  apply IHfs with (ArrowTy (OpaqueLabeledTy (classTy returnT)) T'); auto.\n  apply IHfs with (ArrowTy (LabelelTy T0) T'); auto.\n  apply IHfs with (ArrowTy LabelTy T'); auto.\n  apply IHfs with (ArrowTy voidTy T'); auto.\n  apply IHfs with (ArrowTy voidTy T'); auto.\n  apply IHfs with (ArrowTy voidTy T'); auto.\nQed. Hint Resolve same_fs_L_eq. \n\n\nLemma same_val_L_eq : forall ct h v φ,\n    eq_φ φ h ->\n    wfe_stack_val ct h v ->\n    L_equivalence_tm v h v h φ.\nProof with eauto.\n  intros. induction H0; auto.\n  remember (class_def cls_name field_defs method_defs) as cls. \n  case_eq (flow_to lo L_Label); intro. \n  apply L_equivalence_tm_eq_object_L with cls F lo cls F lo; auto.\n  inversion H; subst; auto.\n  remember (class_def cls_name field_defs method_defs) as cls.\n  apply H3 with cls F lo; auto. \n  apply L_equivalence_tm_eq_object_H with cls F lo cls F lo; auto.\n\n  case_eq (flow_to lb L_Label); intro.\n  apply L_equivalence_tm_eq_v_l_L; auto.\n  apply L_equivalence_tm_eq_v_l_H; auto.  \n\n  case_eq (flow_to lb L_Label); intro.\n  apply L_equivalence_tm_eq_v_opa_l_L; auto.\n  apply L_equivalence_tm_eq_v_opa_l_H; auto.    \nQed. Hint Resolve  same_val_L_eq.\n\n  \nLemma same_store_L_eq : forall ct h sf φ,\n    eq_φ φ h ->\n    wfe_stack_frame ct h sf ->\n    L_equivalence_store sf h sf h φ.\nProof with eauto.\n  intros.\n  inversion H0; subst; auto. \n  apply  L_equivalence_store_L.\n\n  intros. exists o1; split; auto.\n  apply same_val_L_eq with ct; auto.\n  apply H1 with x; auto. \n\n  intros. exists o2; split; auto.\n  apply same_val_L_eq with ct; auto.\n  apply H1 with x; auto. \n\n  intros. exists v1; split; auto.\n  apply same_val_L_eq with ct; auto.\n  assert ( wfe_stack_val ct h (v_l v1 lb)).\n  apply H1 with x; auto.\n  inversion H4; subst; auto. \n\n  intros. exists v2; split; auto.\n  apply same_val_L_eq with ct; auto.\n  assert ( wfe_stack_val ct h (v_l v2 lb)).\n  apply H1 with x; auto.\n  inversion H4; subst; auto. \n\n  intros. exists v1; split; auto.\n  apply same_val_L_eq with ct; auto.\n  assert ( wfe_stack_val ct h (v_opa_l v1 lb)).\n  apply H1 with x; auto.\n  inversion H4; subst; auto. \n\n  intros. exists v2; split; auto.\n  apply same_val_L_eq with ct; auto.\n  assert ( wfe_stack_val ct h (v_opa_l v2 lb)).\n  apply H1 with x; auto.\n  inversion H4; subst; auto. \nQed. Hint Resolve same_store_L_eq.\n\nLemma same_ctn_L_eq : forall ct h T t fs lb sf  φ gamma,\n    eq_φ φ h ->\n    valid_ctn ct (Container t fs lb sf) h ->\n    ctn_has_type ct gamma h (Container t fs lb sf) T ->\n    flow_to lb L_Label = true ->\n    L_eq_container (Container t fs lb sf) h (Container t fs lb sf) h φ.\nProof with eauto.\n  intros.\n  apply L_eq_ctn; auto. auto.\n  inversion H1; subst; auto.\n  apply same_tm_L_eq with ct gamma T0; auto. \n  apply same_tm_L_eq with ct gamma T0; auto. \n\n  inversion H1; subst; auto.\n  apply  same_fs_L_eq with ct gamma (ArrowTy T0 T'); auto. \n  apply  same_fs_L_eq with ct gamma (ArrowTy T1 T'); auto\n  apply same_store_L_eq with ct; auto.\n  inversion H0; auto.\nQed. Hint Resolve  same_ctn_L_eq. \n *)\n\n\nLemma extend_h1_with_H_preserve_bijection : forall ct h1 h2 φ cls lo F,\n    wfe_heap ct h1 ->\n    L_equivalence_heap h1 h2 φ ->\n    flow_to lo L_Label = false ->   \n  L_equivalence_heap (add_heap_obj h1 (get_fresh_oid h1)\n                                   (Heap_OBJ cls F lo)) h2 φ.\nProof with eauto.\n  intros.\n  inversion H0; subst; auto.\n  apply L_eq_heap; auto.\n  - intros. apply H2 in H7. inversion H7; subst; auto.\n    apply object_equal_L with lb1 lb2 cls1 cls2 F1 F2; auto.\n\n    assert (lookup_heap_obj (add_heap_obj h1 (get_fresh_oid h1)\n                                   (Heap_OBJ cls F lo)) o1 = Some (Heap_OBJ cls1 F1 lb1)).\n    apply extend_heap_lookup_eq; auto.\n    apply lookup_extend_heap_fresh_oid with ct  (Heap_OBJ cls1 F1 lb1) ; auto.\n    auto. destruct H12. destruct H13. destruct H14.\n    split; auto. split; auto. split; auto. \n    intros.\n    destruct H15 with fname fo1 fo2; auto.\n    destruct H18 as [cls_f2]. rename x into cls_f1.\n    destruct H18 as [lof1]. destruct H18 as [lof2].\n    destruct H18 as [FF1]. destruct H18 as [FF2].\n    destruct H18; auto. \n    destruct H19.\n    destruct H20. \n    exists cls_f1.     exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2. \n    split; auto.\n    apply extend_heap_lookup_eq; auto.\n    apply lookup_extend_heap_fresh_oid with ct (Heap_OBJ cls_f1 FF1 lof1) ; auto.\n\n    exists cls_f1.     exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2. \n    split; auto.\n    apply extend_heap_lookup_eq; auto.\n    apply lookup_extend_heap_fresh_oid with ct (Heap_OBJ cls_f1 FF1 lof1) ; auto.\n    \n    \n  - intros.\n    apply lookup_extended_heap_none in H7; auto.\n  - intros. \n    case_eq (beq_oid o (get_fresh_oid h1)); intro.\n    assert (lookup_heap_obj h1 o = None).\n    apply fresh_oid_heap with ct; auto.\n    apply H3 in H10. auto.\n    apply lookup_extend_heap_for_existing in H7; auto.\n    apply H5 in H7; auto. \nQed.  Hint Resolve   extend_h1_with_H_preserve_bijection.\n\nLemma extend_h2_with_H_preserve_bijection : forall ct h1 h2 φ cls lo F,\n    wfe_heap ct h2 ->\n    L_equivalence_heap h1 h2 φ ->\n    flow_to lo L_Label = false ->   \n  L_equivalence_heap h1 (add_heap_obj h2 (get_fresh_oid h2)\n                                   (Heap_OBJ cls F lo)) φ.\nProof with eauto.\n  intros.\n  inversion H0; subst; auto.\n  apply L_eq_heap; auto.\n  - intros. apply H2 in H7. inversion H7; subst; auto.\n    apply object_equal_L with lb1 lb2 cls1 cls2 F1 F2; auto.\n\n    assert (lookup_heap_obj (add_heap_obj h2 (get_fresh_oid h2)\n                                   (Heap_OBJ cls F lo)) o2 = Some (Heap_OBJ cls2 F2 lb2)).\n    apply extend_heap_lookup_eq; auto.\n    apply lookup_extend_heap_fresh_oid with ct  (Heap_OBJ cls2 F2 lb2) ; auto.\n    auto.\n    destruct H12.\n    destruct H13. destruct H14.  \n    split; auto. split; auto. split; auto. \n    \n    intros.\n    destruct H15 with fname fo1 fo2; auto.\n\n    destruct H18 as [cls_f2]. rename x into cls_f1.\n    destruct H18 as [lof1]. destruct H18 as [lof2].\n    destruct H18 as [FF1]. destruct H18 as [FF2].\n    destruct H18; auto. \n    destruct H19.\n    destruct H20.\n    exists cls_f1.     exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2. \n    split; auto. split; auto. \n    apply extend_heap_lookup_eq; auto.\n    apply lookup_extend_heap_fresh_oid with ct (Heap_OBJ cls_f2 FF2 lof2) ; auto.\n\n    exists cls_f1.     exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2. \n    split; auto. split; auto. \n    apply extend_heap_lookup_eq; auto.\n    apply lookup_extend_heap_fresh_oid with ct (Heap_OBJ cls_f2 FF2 lof2) ; auto.\n  - intros.\n    apply lookup_extended_heap_none in H7; auto.\n  - intros. \n    case_eq (beq_oid o (get_fresh_oid h2)); intro.\n    assert (lookup_heap_obj h2 o = None).\n    apply fresh_oid_heap with ct; auto.\n    apply H4 in H10. auto.\n    apply lookup_extend_heap_for_existing in H7; auto.\n    apply H6 in H7; auto. \nQed.  Hint Resolve  extend_h2_with_H_preserve_bijection.\n  \n\nLemma extend_h1_with_H_preserve_tm_eq : forall t1 t2 ct h1 h2 φ cls lo F,\n     wfe_heap ct h1 ->\n     flow_to lo L_Label = false ->\n     L_equivalence_tm t1 h1 t2 h2 φ ->\n     L_equivalence_tm t1 (add_heap_obj h1 (get_fresh_oid h1) (Heap_OBJ cls F lo)) t2 h2 φ.\nProof with eauto.\n  intros.\n  generalize dependent t2. \n  induction t1; intros; inversion H1; subst; auto.\n  apply L_equivalence_tm_eq_object_L with cls1 F1 lb1 cls2 F2 lb2; auto.\n  assert (lookup_heap_obj (add_heap_obj h1 (get_fresh_oid h1)\n                                   (Heap_OBJ cls F lo)) o = Some (Heap_OBJ cls1 F1 lb1)).\n  apply extend_heap_lookup_eq; auto.\n  apply lookup_extend_heap_fresh_oid with ct  (Heap_OBJ cls1 F1 lb1) ; auto.\n  auto.\n\n\n  apply L_equivalence_tm_eq_object_H with cls1 cls2 F1 lb1  F2 lb2; auto.\n  assert (lookup_heap_obj (add_heap_obj h1 (get_fresh_oid h1)\n                                   (Heap_OBJ cls F lo)) o = Some (Heap_OBJ cls1 F1 lb1)).\n  apply extend_heap_lookup_eq; auto.\n  apply lookup_extend_heap_fresh_oid with ct  (Heap_OBJ cls1 F1 lb1) ; auto.\n  auto.\nQed. Hint Resolve extend_h1_with_H_preserve_tm_eq.   \n\n\nLemma extend_h2_with_H_preserve_tm_eq : forall t1 t2 ct h1 h2 φ cls lo F,\n     wfe_heap ct h2 ->\n     flow_to lo L_Label = false ->\n     L_equivalence_tm t1 h1 t2 h2 φ ->\n     L_equivalence_tm t1 h1  t2 (add_heap_obj h2 (get_fresh_oid h2) (Heap_OBJ cls F lo)) φ.\nProof with eauto.\n  intros.\n  generalize dependent t2. \n  induction t1; intros; inversion H1; subst; auto.\n  apply L_equivalence_tm_eq_object_L with cls1 F1 lb1 cls2 F2 lb2; auto.\n  assert (lookup_heap_obj (add_heap_obj h2 (get_fresh_oid h2)\n                                   (Heap_OBJ cls F lo)) o2 = Some (Heap_OBJ cls2 F2 lb2)).\n  apply extend_heap_lookup_eq; auto.\n  apply lookup_extend_heap_fresh_oid with ct  (Heap_OBJ cls2 F2 lb2) ; auto.\n  auto.\n\n\n  apply L_equivalence_tm_eq_object_H with cls1 cls2 F1 lb1  F2 lb2; auto.\n  assert (lookup_heap_obj (add_heap_obj h2 (get_fresh_oid h2)\n                                   (Heap_OBJ cls F lo)) o2 = Some (Heap_OBJ cls2 F2 lb2)).\n  apply extend_heap_lookup_eq; auto.\n  apply lookup_extend_heap_fresh_oid with ct  (Heap_OBJ cls2 F2 lb2) ; auto.\n  auto.\nQed. Hint Resolve extend_h2_with_H_preserve_tm_eq.   \n\n\nLemma extend_h1_with_H_preserve_fs_eq : forall fs1 fs2 ct h1 h2 φ cls lo F,\n     wfe_heap ct h1 ->\n     flow_to lo L_Label = false ->\n     L_equivalence_fs fs1 h1 fs2 h2 φ ->\n     L_equivalence_fs fs1 (add_heap_obj h1 (get_fresh_oid h1) (Heap_OBJ cls F lo)) fs2 h2 φ.\nProof with eauto.\n  intros.\n  generalize dependent fs2. \n  induction fs1; intros; inversion H1; subst; auto.\n  apply L_equal_fs; auto.\n  apply  extend_h1_with_H_preserve_tm_eq with ct; auto. \nQed. Hint Resolve extend_h1_with_H_preserve_fs_eq.\n\nLemma extend_h2_with_H_preserve_fs_eq : forall fs1 fs2 ct h1 h2 φ cls lo F,\n     wfe_heap ct h2 ->\n     flow_to lo L_Label = false ->\n     L_equivalence_fs fs1 h1 fs2 h2 φ ->\n     L_equivalence_fs fs1 h1 fs2 (add_heap_obj h2 (get_fresh_oid h2) (Heap_OBJ cls F lo)) φ.\nProof with eauto.\n  intros.\n  generalize dependent fs2. \n  induction fs1; intros; inversion H1; subst; auto.\n  apply L_equal_fs; auto.\n  apply  extend_h2_with_H_preserve_tm_eq with ct; auto. \nQed. Hint Resolve extend_h2_with_H_preserve_fs_eq.\n\n\nLemma extend_h1_with_H_preserve_sf_eq : forall sf1 sf2 ct h1 h2 φ cls lo F,\n    wfe_heap ct h1 ->\n    wfe_heap ct h2 ->\n    wfe_stack_frame ct h1 sf1 ->\n    wfe_stack_frame ct h2 sf2 ->\n     flow_to lo L_Label = false ->\n     L_equivalence_store sf1 h1 sf2 h2 φ ->\n     L_equivalence_store sf1 (add_heap_obj h1 (get_fresh_oid h1) (Heap_OBJ cls F lo)) sf2 h2 φ.\nProof with eauto.\n  intros.\n  inversion H1; subst; auto.\n  inversion H2; subst; auto.\n  inversion H4; subst; auto. \n  \n  apply  L_equivalence_store_L; auto.\n  intros. destruct H7.\n  split; auto. intros. \n  assert (L_equivalence_tm v1 h1 v2 h2 φ).\n  apply H7 with x; auto.  \n \n  apply extend_h1_with_H_preserve_tm_eq with ct ; auto. \n Qed. Hint Resolve extend_h1_with_H_preserve_sf_eq.\n\n\nLemma extend_h2_with_H_preserve_sf_eq : forall sf1 sf2 ct h1 h2 φ cls lo F,\n    wfe_heap ct h1 ->\n    wfe_heap ct h2 ->\n    wfe_stack_frame ct h1 sf1 ->\n    wfe_stack_frame ct h2 sf2 ->\n     flow_to lo L_Label = false ->\n     L_equivalence_store sf1 h1 sf2 h2 φ ->\n     L_equivalence_store sf1 h1 sf2 (add_heap_obj h2 (get_fresh_oid h2) (Heap_OBJ cls F lo)) φ.\nProof with eauto.\n  intros.\n  inversion H1; subst; auto.\n  inversion H2; subst; auto.\n  inversion H4; subst; auto.\n  apply  L_equivalence_store_L; auto.\n  intros. destruct H7.\n  split; auto. intros. \n  assert (L_equivalence_tm v1 h1 v2 h2 φ).\n  apply H7 with x; auto.  \n  apply extend_h2_with_H_preserve_tm_eq with ct ; auto. \n Qed. Hint Resolve extend_h2_with_H_preserve_sf_eq.\n\nLemma extend_h1_with_H_preserve_ctn_eq : forall ct\n    t1 fs1 lb1 sf1\n    t2 fs2 lb2 sf2\n    h1 h2 φ cls lo F,\n    wfe_heap ct h1 ->\n    wfe_heap ct h2 ->\n    valid_ctn ct ((Container t1 fs1 lb1 sf1)) h1  ->\n    valid_ctn ct ((Container t2 fs2 lb2 sf2)) h2  ->\n    L_equivalence_heap h1 h2 φ ->\n    L_eq_container (Container t1 fs1 lb1 sf1) h1\n                   (Container t2 fs2 lb2 sf2) h2 φ ->\n    flow_to lo L_Label = false  ->\n    L_eq_container (Container t1 fs1 lb1 sf1)\n    (add_heap_obj h1 (get_fresh_oid h1) (Heap_OBJ cls F lo))  \n    (Container t2 fs2 lb2 sf2) h2 φ.\nProof with eauto.\n  intros.\n  inversion H1; subst; auto.\n  inversion H2; subst; auto.\n  inversion H4; subst; auto. \n  apply L_eq_ctn; auto.\n  apply extend_h1_with_H_preserve_tm_eq with ct; auto.\n  apply extend_h1_with_H_preserve_fs_eq with ct; auto.\n  apply extend_h1_with_H_preserve_sf_eq with ct; auto.\nQed. Hint Resolve   extend_h1_with_H_preserve_ctn_eq.\n\nLemma extend_h2_with_H_preserve_ctn_eq : forall ct\n    t1 fs1 lb1 sf1\n    t2 fs2 lb2 sf2\n    h1 h2 φ cls lo F,\n    wfe_heap ct h1 ->\n    wfe_heap ct h2 ->\n    valid_ctn ct ((Container t1 fs1 lb1 sf1)) h1  ->\n    valid_ctn ct ((Container t2 fs2 lb2 sf2)) h2  ->\n    L_equivalence_heap h1 h2 φ ->\n    L_eq_container (Container t1 fs1 lb1 sf1) h1\n                   (Container t2 fs2 lb2 sf2) h2 φ ->\n    flow_to lo L_Label = false  ->\n    L_eq_container (Container t1 fs1 lb1 sf1)\n                   h1\n                   (Container t2 fs2 lb2 sf2)\n                   (add_heap_obj h2 (get_fresh_oid h2) (Heap_OBJ cls F lo))   φ.\nProof with eauto.\n  intros.\n  inversion H1; subst; auto.\n  inversion H2; subst; auto.\n  inversion H4; subst; auto. \n  apply L_eq_ctn; auto.\n  apply extend_h2_with_H_preserve_tm_eq with ct; auto.\n  apply extend_h2_with_H_preserve_fs_eq with ct; auto.\n  apply extend_h2_with_H_preserve_sf_eq with ct; auto.\nQed. Hint Resolve   extend_h2_with_H_preserve_ctn_eq.\n\nLemma extend_h1_with_H_preserve_ctns_eq : forall ct ctns1 ctns2\n    h1 h2 φ cls lo F,\n    valid_ctns ct ctns1 h1 ->   valid_ctns ct ctns2 h2 ->\n    wfe_heap ct h1 -> wfe_heap ct h2 ->\n     L_equivalence_heap h1 h2 φ ->\n    L_eq_ctns  ctns1  h1 ctns2 h2 φ ->\n    flow_to lo L_Label = false  ->\n    L_eq_ctns  ctns1 (add_heap_obj h1 (get_fresh_oid h1) (Heap_OBJ cls F lo))\n     ctns2  h2  φ.\nProof with eauto.\n  intros.\n  generalize dependent ctns2.\n  induction ctns1; subst; auto.\n  intros. inversion H4; subst; auto. \n  intros. inversion H4; subst; auto. \n  apply L_eq_ctns_list; auto. \n\n  inversion H; subst; auto.\n  inversion H0; subst; auto. \n  destruct a. destruct ctn2. \n  apply extend_h1_with_H_preserve_ctn_eq with ct; auto.\n  apply   IHctns1; auto.   \n  inversion H; subst; auto.\n  inversion H0; subst; auto. \nQed.  Hint Resolve  extend_h1_with_H_preserve_ctns_eq.\n\nLemma extend_h2_with_H_preserve_ctns_eq : forall ct ctns1 ctns2\n    h1 h2 φ cls lo F,\n    valid_ctns ct ctns1 h1 ->   valid_ctns ct ctns2 h2 ->\n    wfe_heap ct h1 -> wfe_heap ct h2 ->\n     L_equivalence_heap h1 h2 φ ->\n    L_eq_ctns  ctns1  h1 ctns2 h2 φ ->\n    flow_to lo L_Label = false  ->\n    L_eq_ctns  ctns1 h1\n     ctns2  (add_heap_obj h2 (get_fresh_oid h2) (Heap_OBJ cls F lo))  φ.\nProof with eauto.\n  intros.\n  generalize dependent ctns2.\n  induction ctns1; subst; auto.\n  intros. inversion H4; subst; auto. \n  intros. inversion H4; subst; auto. \n  apply L_eq_ctns_list; auto. \n\n  inversion H; subst; auto.\n  inversion H0; subst; auto. \n  destruct a. destruct ctn2. \n  apply extend_h2_with_H_preserve_ctn_eq with ct; auto.\n  apply   IHctns1; auto.   \n  inversion H; subst; auto.\n  inversion H0; subst; auto. \nQed.  Hint Resolve  extend_h2_with_H_preserve_ctns_eq.\n\nLemma low_component_transitive : forall ct t1 fs1 lb1 sf1 t2 fs2 lb2 sf2 h ctns,\n    flow_to lb1 L_Label = false ->\n    flow_to lb2 L_Label = false ->\n    low_component ct (Container t1 fs1 lb1 sf1) ctns h =\n    low_component ct (Container t2 fs2 lb2 sf2) ctns h.\nProof with eauto.\n  intros.\n  unfold low_component.  destruct ctns; rewrite H; rewrite H0; auto.  \nQed. Hint Resolve low_component_transitive .\n\n  \nLemma low_component_lead_to_L : forall ct1 t fs lb sf  h1 ct2 ctn2 ctns1 ctns2 h2,  \n    Config ct1 (Container t fs lb sf) ctns1 h1 = low_component ct2 ctn2 ctns2 h2 ->\n    ct1 = ct2 /\\ h1 = h2 /\\ flow_to lb L_Label = true.\nProof with eauto.\n  intros.\n  destruct ctn2.\n  case_eq (flow_to l L_Label); intro.\n  unfold low_component in H.\n\n  + induction ctns2.\n    rewrite H0 in H.\n    inversion H; subst; auto.\n\n    rewrite H0 in H.\n    inversion H; subst;auto. \n\n  + induction ctns2.\n    unfold low_component in H.\n    rewrite H0 in H.\n    inversion H; subst; auto.\n\n    unfold low_component in H.\n    rewrite H0 in H.\n    fold low_component in H.\n     destruct a.\n    case_eq (flow_to l0 L_Label); intro.\n    unfold low_component in H.\n    destruct ctns2. \n    rewrite H1 in H.\n    inversion H; subst;auto.\n    rewrite H1 in H.\n    inversion H; subst;auto.\n\n    assert (low_component ct2 (Container t1 f0 l0 s0) ctns2 h2 =\n            low_component ct2 (Container t0 f l s) ctns2 h2).\n    apply low_component_transitive; auto.\n    rewrite H2 in H. auto. \nQed. Hint Resolve     low_component_lead_to_L.\n\n\nLemma low_component_irrelevant_to_heap :  forall ct1 t fs lb sf  h1 ct2 ctn2 ctns1 ctns2 h2 ,  \n    Config ct1 (Container t fs lb sf) ctns1 h1 = low_component ct2 ctn2 ctns2 h1 ->\n    Config ct1 (Container t fs lb sf) ctns1 h2 = low_component ct2 ctn2 ctns2 h2.\nProof with eauto.\n  intros.\n  \n  generalize dependent ctn2.   induction ctns2; intros. \n  - unfold low_component in H.\n    destruct ctn2. \n    case_eq (flow_to l L_Label); intro.\n    rewrite H0 in H. inversion H;subst; auto.\n    unfold low_component. rewrite H0. inversion H; subst; auto.\n\n    rewrite H0 in H.  inversion H; subst; auto.\n    unfold low_component. rewrite H0. auto. \n  - unfold low_component in H.\n    destruct ctn2. \n    case_eq (flow_to l L_Label); intro.\n    rewrite H0 in H. inversion H; subst; auto.\n    unfold low_component. rewrite H0. inversion H; subst; auto.\n\n    rewrite H0 in H. fold low_component in H.\n    destruct a.\n    case_eq (flow_to l0 L_Label); intro.\n    unfold low_component. rewrite H0. fold low_component. auto.\n    unfold low_component. rewrite H0. fold low_component. auto.\nQed. Hint Resolve low_component_irrelevant_to_heap.\n\n                                              \n    \n\nLemma valid_preservation_low_component : forall ct ctn ctns h\n                                                ctn' ctns' h', \n    Config ct ctn' ctns' h' =\n    low_component ct ctn ctns h ->\n    valid_ctn ct ctn h ->\n    valid_ctns ct ctns h ->\n    valid_ctn ct ctn' h' /\\ valid_ctns ct ctns' h'.\nProof with eauto.\n  intros.\n  generalize dependent ctn.   induction ctns; intros.\n  destruct ctn.\n  case_eq (flow_to l L_Label); intro.\n  unfold low_component in H.\n  rewrite H2 in H. inversion H; subst; auto.\n  split; auto.\n  unfold low_component in H.\n  rewrite H2 in H. inversion H; subst; auto.\n  apply valid_container; auto.\n  intro. intro contra; inversion contra.\n  intro. intro contra; inversion contra.\n  apply stack_frame_wfe; auto; intros; inversion H3.\n  \n\n \n  unfold low_component in H.\n  rewrite H2 in H. inversion H; subst; auto.\n\n  destruct ctn.\n  case_eq (flow_to l L_Label); intro.\n  \n  unfold low_component in H.\n  rewrite H2 in H. inversion H; subst; auto.\n\n  unfold low_component in H.\n  rewrite H2 in H. fold low_component in H.\n\n  apply IHctns with a; auto .\n  inversion H1; auto.\n  inversion H1; auto. \nQed. Hint Resolve   valid_preservation_low_component.\n  \n\nLemma extend_h1_with_H_preserve_config_eq : forall ct ctns1 ctns2\n    ctn1 ctn2\n    h1 h2 φ cls lo F,\n    valid_config (Config ct ctn1 ctns1  h1)  ->\n    valid_config (Config ct ctn2 ctns2  h2)  ->\n    L_equivalence_heap h1 h2 φ ->\n    L_equivalence_config (Config ct ctn1 ctns1  h1)\n                   (Config ct ctn2 ctns2  h2) φ ->\n    flow_to lo L_Label = false  ->\n    L_equivalence_config\n    (Config ct ctn1 ctns1 (add_heap_obj h1 (get_fresh_oid h1) (Heap_OBJ cls F lo)))\n    (Config ct ctn2 ctns2  h2) φ.\nProof with eauto.\n  intros.\n  \n  remember (Config ct ctn1 ctns1 h1) as config1.\n  remember (Config ct ctn2 ctns2 h2) as config2.\n  generalize dependent ctn1. generalize dependent ctn2.\n  generalize dependent ctns1. generalize dependent ctns2. \n  induction H2; subst; intros; inversion Heqconfig1; inversion Heqconfig2; subst; auto.\n  apply L_equivalence_config_L; auto.\n  inversion H; auto. inversion H0; auto. \n  apply extend_h1_with_H_preserve_ctn_eq with ct; auto.\n  inversion H; auto. inversion H0; auto. \n  apply extend_h1_with_H_preserve_ctns_eq with ct; auto.\n\n  \n  induction ctns3. induction ctns0.\n  apply L_equivalence_config_H; auto.\n  unfold low_component.  \n  rewrite H2; rewrite H4.\n  apply L_equivalence_config_L; auto. \n\n  inversion H. inversion H0. subst; auto.\n  apply extend_h1_with_H_preserve_ctn_eq with ct ;  auto.\n  apply valid_container; auto. intros.\n  intro contra. inversion contra.\n  intro. intro contra; inversion contra.\n  apply stack_frame_wfe; auto.\n  intros.      inversion H6.\n  apply valid_container; auto.\n  intro. intro contra; inversion contra.\n  intro. intro contra; inversion contra.\n  apply stack_frame_wfe; auto.\n  intros.      inversion H6.\n\n  apply L_eq_ctn; auto.\n  apply L_equivalence_store_L; auto.\n  split; auto; intros.  inversion H6.\n  split; auto.  \n  \n\n  +  apply L_equivalence_config_H; auto.\n     remember (low_component ct (Container t2 fs2 lb2 sf2) (a :: ctns0) h2)\n       as conf.\n     destruct conf. destruct c0.\n     assert (c = ct /\\ h = h2 /\\ flow_to l0 L_Label = true ).\n     apply low_component_lead_to_L with t f s (Container t2 fs2 lb2 sf2)\n                                       l (a :: ctns0); auto.\n     destruct H6.  destruct H7; subst; auto.\n     assert (valid_ctn ct (Container t f l0 s)  h2 /\\ valid_ctns ct l h2).\n     apply valid_preservation_low_component with (Container t2 fs2 lb2 sf2)\n                                                 (a :: ctns0)\n                                                 h2  ; auto.\n     inversion H0; auto. inversion H0; auto. \n     unfold low_component.  rewrite H2. \n     unfold low_component in H5. rewrite H2 in H5.\n     inversion H5; subst; auto.\n     apply L_equivalence_config_L; auto.    \n     apply extend_h1_with_H_preserve_ctn_eq with ct; auto.\n     inversion H; auto. inversion H0; auto.\n     apply valid_container; auto.\n     intro. intro contra; inversion contra.\n     intro. intro contra; inversion contra.\n     apply stack_frame_wfe; auto; intros; inversion H7.\n\n     apply H6.\n     apply extend_h1_with_H_preserve_ctns_eq with ct; auto.\n     apply H6.\n     inversion H; auto.  inversion H0; auto.\n     try (inconsist_label).\n     inversion H5. inversion H5.     \n  + apply L_equivalence_config_H; auto.\n  remember (low_component ct (Container t1 fs1 lb1 sf1) (a :: ctns3) h1) as conf1.\n  remember ((low_component ct (Container t2 fs2 lb2 sf2) ctns0 h2)) as conf2.\n  destruct conf1. destruct conf2.\n  destruct c0. \n  assert (c = ct /\\ h = h1 /\\ flow_to l1 L_Label = true).\n  apply low_component_lead_to_L with t f s (Container t1 fs1 lb1 sf1) l (a :: ctns3)  ; auto. \n\n  destruct c2. \n  assert (c1 = ct /\\ h0 = h2 /\\ flow_to l2 L_Label = true).\n  apply low_component_lead_to_L with t0 f0 s0 (Container t2 fs2 lb2 sf2) l0 ctns0  ; auto.\n  destruct H6. destruct H8.\n  destruct H7. destruct H10.     subst. auto.\n  inversion H; subst; auto. inversion H0; subst; auto. \n  assert (valid_ctn ct (Container t f l1 s)  h1 /\\ valid_ctns ct l h1).\n  apply valid_preservation_low_component with (Container t1 fs1 lb1 sf1)\n                                                 (a :: ctns3)\n                                                 h1  ; auto.\n  assert (valid_ctn ct (Container t0 f0 l2 s0)  h2 /\\ valid_ctns ct l0 h2).\n  apply valid_preservation_low_component with (Container t2 fs2 lb2 sf2)\n                                                 ctns0\n                                                 h2  ; auto.\n  \n  assert (Config ct (Container t f l1 s) l (add_heap_obj h1 (get_fresh_oid h1) (Heap_OBJ cls F lo))\n          = (low_component ct (Container t1 fs1 lb1 sf1) (a :: ctns3)\n                          (add_heap_obj h1 (get_fresh_oid h1) (Heap_OBJ cls F lo)))\n         ).\n  eauto using low_component_irrelevant_to_heap. rewrite <- H8.  \n  apply   L_equivalence_config_L; auto.\n  apply extend_h1_with_H_preserve_ctn_eq with ct; auto.\n  inversion H; auto. inversion H0; auto.\n  apply H6.\n  apply H7.\n  inversion H5; subst; auto.\n  try (inconsist_label).\n  inversion H5; subst; auto.\n  apply extend_h1_with_H_preserve_ctns_eq with ct; auto.\n  apply H6. apply H7.\n\n  try (inconsist_label).\n  inversion H5.  inversion H5.\n\n  inversion H5.\n  inversion H5.  \nQed. Hint Resolve  extend_h1_with_H_preserve_config_eq.\n\n\nLemma extend_h2_with_H_preserve_config_eq : forall ct ctns1 ctns2\n    ctn1 ctn2\n    h1 h2 φ cls lo F,\n    valid_config (Config ct ctn1 ctns1  h1)  ->\n    valid_config (Config ct ctn2 ctns2  h2)  ->\n    L_equivalence_heap h1 h2 φ ->\n    L_equivalence_config (Config ct ctn1 ctns1  h1)\n                   (Config ct ctn2 ctns2  h2) φ ->\n    flow_to lo L_Label = false  ->\n    L_equivalence_config\n    (Config ct ctn1 ctns1 h1)\n    (Config ct ctn2 ctns2  (add_heap_obj h2 (get_fresh_oid h2) (Heap_OBJ cls F lo))) φ.\nProof with eauto.\n  intros.\n  \n  remember (Config ct ctn1 ctns1 h1) as config1.\n  remember (Config ct ctn2 ctns2 h2) as config2.\n  generalize dependent ctn1. generalize dependent ctn2.\n  generalize dependent ctns1. generalize dependent ctns2. \n  induction H2; subst; intros; inversion Heqconfig1; inversion Heqconfig2; subst; auto.\n  apply L_equivalence_config_L; auto.\n  inversion H; auto. inversion H0; auto. \n  apply extend_h2_with_H_preserve_ctn_eq with ct; auto.\n  inversion H; auto. inversion H0; auto. \n  apply extend_h2_with_H_preserve_ctns_eq with ct; auto.\n  \n  induction ctns3. induction ctns0.\n  apply L_equivalence_config_H; auto.\n  unfold low_component.  \n  rewrite H2; rewrite H4.\n  apply L_equivalence_config_L; auto.\n\n  inversion H. inversion H0. subst; auto. \n  apply extend_h2_with_H_preserve_ctn_eq with ct ;  auto.\n  apply valid_container; auto. intros.\n  intro contra. inversion contra.\n  intro. intro contra; inversion contra.\n  apply stack_frame_wfe; auto.\n  intros.      inversion H6.\n  apply valid_container; auto.\n  intro. intro contra; inversion contra.\n  intro. intro contra; inversion contra.\n  apply stack_frame_wfe; auto.\n  intros.      inversion H6.\n\n  +  \n  apply L_eq_ctn; auto.\n  apply L_equivalence_store_L; auto.\n  split; auto; intros.  inversion H6.\n  split; auto.  \n     \n\n  +  apply L_equivalence_config_H; auto.\n     remember\n       ((low_component ct (Container t2 fs2 lb2 sf2) (a :: ctns0) h2)) as conf.\n     destruct conf. destruct c0.\n     assert (c = ct /\\\n             h = h2 /\\\n             flow_to l0 L_Label = true ).\n     apply low_component_lead_to_L with t f s (Container t2 fs2 lb2 sf2)\n                                       l (a :: ctns0); auto.\n     destruct H6.  destruct H7; subst; auto.\n\n     assert (Config ct (Container t f l0 s) l\n                    (add_heap_obj h2 (get_fresh_oid h2) (Heap_OBJ cls F lo))\n          = (low_component ct (Container t2 fs2 lb2 sf2) (a :: ctns0)\n                          (add_heap_obj h2 (get_fresh_oid h2) (Heap_OBJ cls F lo)))\n         ).\n     apply low_component_irrelevant_to_heap with h2;auto.  rewrite <- H6.\n     assert (valid_ctn ct (Container t f l0 s)\n                       h2\n             /\\ valid_ctns ct l h2).\n     apply valid_preservation_low_component with (Container t2 fs2 lb2 sf2)\n                                                 (a :: ctns0)\n                                                 h2  ; auto.\n     inversion H0; auto.  inversion H0. auto. \n\n     inversion H5; subst; auto. \n     unfold low_component.  rewrite H2. \n     unfold low_component in H5. rewrite H2 in H5.\n     apply L_equivalence_config_L; auto.    \n     apply extend_h2_with_H_preserve_ctn_eq with ct; auto.\n     inversion H; auto. inversion H0; auto.\n      apply valid_container; auto.\n     intro. intro contra; inversion contra.\n     intro. intro contra; inversion contra.\n     apply stack_frame_wfe; auto; intros; inversion H10.\n     apply H7.\n     rewrite H2 in H9. inversion H9; subst; auto.  \n     apply extend_h2_with_H_preserve_ctns_eq with ct; auto.     \n     apply H7.\n     inversion H; auto. inversion H0; auto.\n     rewrite H2 in H9. inversion H9; subst; auto.\n     try (inconsist_label).\n\n     inversion H5. inversion H5. \n     \n  + apply L_equivalence_config_H; auto.\n  remember (low_component ct (Container t1 fs1 lb1 sf1) (a :: ctns3) h1) as conf1.\n  remember ((low_component ct (Container t2 fs2 lb2 sf2) ctns0 h2)) as conf2.\n  destruct conf1. destruct conf2.\n  destruct c0. \n  assert (c = ct /\\ h = h1 /\\ flow_to l1 L_Label = true).\n  apply low_component_lead_to_L with t f s (Container t1 fs1 lb1 sf1) l (a :: ctns3)  ; auto. \n\n  destruct c2. \n  assert (c1 = ct /\\ h0 = h2 /\\ flow_to l2 L_Label = true).\n  apply low_component_lead_to_L with t0 f0 s0 (Container t2 fs2 lb2 sf2) l0 ctns0  ; auto.\n  destruct H6. destruct H8.\n  destruct H7. destruct H10.     subst. auto.\n  inversion H; subst; auto. inversion H0; subst; auto. \n  assert (valid_ctn ct (Container t f l1 s)  h1 /\\ valid_ctns ct l h1).\n  apply valid_preservation_low_component with (Container t1 fs1 lb1 sf1)\n                                                 (a :: ctns3)\n                                                 h1  ; auto.\n  assert (valid_ctn ct (Container t0 f0 l2 s0)  h2 /\\ valid_ctns ct l0 h2).\n  apply valid_preservation_low_component with (Container t2 fs2 lb2 sf2)\n                                                 ctns0\n                                                 h2  ; auto.\n  \n  assert (Config ct (Container t0 f0 l2 s0) l0\n                 (add_heap_obj h2 (get_fresh_oid h2) (Heap_OBJ cls F lo))\n          = (low_component ct (Container t2 fs2 lb2 sf2) ctns0\n                          (add_heap_obj h2 (get_fresh_oid h2) (Heap_OBJ cls F lo)))\n         ).\n  eauto using low_component_irrelevant_to_heap. rewrite <- H8.  \n  apply   L_equivalence_config_L; auto.\n  apply extend_h2_with_H_preserve_ctn_eq with ct; auto.\n  inversion H; auto. inversion H0; auto.\n  apply H6.\n  apply H7.\n  inversion H5; subst; auto.\n  try (inconsist_label).\n  inversion H5; subst; auto.\n  apply extend_h2_with_H_preserve_ctns_eq with ct; auto.\n  apply H6. apply H7.\n\n  try (inconsist_label).\n  inversion H5.  inversion H5.\n\n  inversion H5.\n  inversion H5.  \nQed. Hint Resolve  extend_h2_with_H_preserve_config_eq.\n\n\n\nLemma update_h1_with_H_preserve_bijection : forall ct h1 h2 φ cls lo F f v o lb1\n  lx,\n    wfe_heap ct h1 ->\n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    flow_to (join_label lb1 lx) lo = true ->\n    flow_to lb1 L_Label = false ->\n    L_equivalence_heap\n    (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo)) h2 φ.\n    \nProof with eauto.\n  intros. \n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lb1 lx; auto.\n  apply  join_label_commutative; auto.\n  \n  inversion H0; subst; auto.\n  apply L_eq_heap; auto.\n  - intros. apply H5 in H10. inversion H10; subst; auto.\n    case_eq (beq_oid o1 o); intro. apply beq_oid_equal in H16.\n    rewrite H16 in H11. rewrite <- H11 in H1. inversion H1; subst.\n    assert (flow_to lb0 (join_label lb1 lx) = false).\n    apply  flow_no_H_to_L; auto. \n    try (inconsist_label).\n    assert (flow_to lb0 L_Label = false).\n    apply flow_transitive with (join_label lb1 lx); auto. \n    try (inconsist_label).    \n\n    apply object_equal_L with lb0 lb2 cls1 cls2 F1 F2; auto.\n    assert ( Some (Heap_OBJ cls1 F1 lb0) =\n      lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo)) o1).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls (fields_update F f v) lo) h1; auto.\n    intro contra.\n    try (beq_oid_inconsist).\n\n    auto. destruct H15.\n    destruct H17. destruct H18. \n   \n    split; auto.\n    split; auto. split; auto. \n\n    intros. \n    destruct H19 with fname fo1 fo2; auto.\n    destruct H22 as [cls_f2]. rename x into cls_f1.\n    destruct H22 as [lof1]. destruct H22 as [lof2].\n    destruct H22 as [FF1]. destruct H22 as [FF2].\n    \n    destruct H22; auto.  destruct H23. destruct H24.\n    destruct H24.\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2. \n    split; auto.\n    assert ( Some   (Heap_OBJ cls_f1 FF1 lof1)\n      = lookup_heap_obj\n          (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo)) fo1).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls (fields_update F f v) lo) h1; auto.\n    intro contra. apply H5 in H24. inversion H24. subst; auto.\n    rewrite <- H1 in H26. inversion H26. subst; auto. \n\n    assert (flow_to lo L_Label  = false).\n    apply  flow_transitive with (join_label lb1 lx); auto.\n    try (inconsist_label). auto.\n\n    case_eq (beq_oid fo1 o); intro.\n    exists cls. exists cls_f2.\n    exists lo. exists lof2.\n    exists (fields_update F f v) . exists FF2. \n    split; auto.\n    apply beq_oid_equal in H25; subst; auto.\n    assert (Some (Heap_OBJ cls (fields_update F f v) lo)\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo)) o).\n    eauto using lookup_updated.  auto.\n\n    split; auto.\n    right; split; auto.\n    destruct H24; auto.\n    apply beq_oid_equal in H25; subst; auto.\n    rewrite H22 in H1; inversion H1; subst; apply H24. \n    \n    \n    assert ( Some   (Heap_OBJ cls_f1 FF1 lof1)\n      = lookup_heap_obj\n          (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo)) fo1).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls (fields_update F f v) lo) h1; auto.\n    intro contra. subst; auto.\n    assert (beq_oid o o = true). apply beq_oid_same.\n    rewrite H25 in H15; inversion H15. \n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto. \n\n    \n  - intros.\n    apply lookup_updated_heap_must_none in H10.\n    auto. \n  - intros.\n    case_eq (beq_oid o0 o); intro.\n    apply beq_oid_equal in H12.\n    rewrite <- H12 in H1. apply H8 with cls F lo; auto.\n    apply flow_transitive with (join_label lb1 lx); auto.\n\n    assert (Some (Heap_OBJ cls0 F0 lb) = lookup_heap_obj h1 o0).\n    apply lookup_updated_not_affected_reverse\n      with o (Heap_OBJ cls (fields_update F f v) lo)\n           (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo)); auto.\n    intro contra. rewrite contra in H12.\n    assert (beq_oid o o = true). apply beq_oid_same.\n    rewrite H12 in H13. inversion H13.\n    apply H8 with cls0 F0 lb; auto. \nQed. Hint Resolve  update_h1_with_H_preserve_bijection.   \n\n\nLemma update_h2_with_H_preserve_bijection : forall ct h1 h2 φ cls lo F f v o lb1\n  lx,\n    wfe_heap ct h1 ->\n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n    flow_to (join_label lb1 lx) lo = true ->\n    flow_to lb1 L_Label = false ->\n    L_equivalence_heap h1\n    (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)) φ.\n    \nProof with eauto.\n  intros. \n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lb1 lx; auto.\n  apply  join_label_commutative; auto.\n  \n  inversion H0; subst; auto.\n  apply L_eq_heap; auto.\n  - intros. apply H5 in H10. inversion H10; subst; auto.\n    case_eq (beq_oid o2 o); intro. apply beq_oid_equal in H16.\n    rewrite H16 in H12. rewrite <- H12 in H1. inversion H1; subst.\n    assert (flow_to lb2 (join_label lb1 lx) = false).\n    apply  flow_no_H_to_L; auto.\n    \n    try (inconsist_label).\n    assert (flow_to lb2 L_Label = false).\n    apply flow_transitive with (join_label lb1 lx); auto. \n    try (inconsist_label).    \n\n    apply object_equal_L with lb0 lb2 cls1 cls2 F1 F2; auto.\n    assert ( Some (Heap_OBJ cls2 F2 lb2) =\n      lookup_heap_obj (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)) o2).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls (fields_update F f v) lo) h2; auto.\n    intro contra.\n    try (beq_oid_inconsist).\n\n    auto. destruct H15.\n    destruct H17. destruct H18. \n    split; auto.\n    split; auto. split; auto.\n    \n    intros. \n    destruct H19 with fname fo1 fo2; auto.\n    destruct H22 as [cls_f2]. rename x into cls_f1.\n    destruct H22 as [lof1]. destruct H22 as [lof2].\n    destruct H22 as [FF1]. destruct H22 as [FF2].\n    \n    destruct H22; auto.  destruct H23. destruct H24.\n    destruct H24.\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2. \n    split; auto.\n    assert ( Some   (Heap_OBJ cls_f2 FF2 lof2)\n      = lookup_heap_obj\n          (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)) fo2).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls (fields_update F f v) lo) h2; auto.\n    intro contra. apply H5 in H24. inversion H24. subst; auto.\n    rewrite <- H1 in H27. inversion H27. subst; auto. \n\n    assert (flow_to lo L_Label  = false).\n    apply  flow_transitive with (join_label lb1 lx); auto.\n    try (inconsist_label). auto.\n\n    case_eq (beq_oid fo2 o); intro.\n    exists cls_f1. exists cls.\n    exists lof1. exists lo.\n    exists FF1. \n    exists (fields_update F f v) .  \n    split; auto. split; auto. \n    apply beq_oid_equal in H25; subst; auto.\n    assert (Some (Heap_OBJ cls (fields_update F f v) lo)\n            = lookup_heap_obj (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)) o).\n    eauto using lookup_updated.  auto.\n\n    right; split; auto.\n    destruct H24; auto.\n    apply beq_oid_equal in H25; subst; auto.\n    rewrite H23 in H1; inversion H1; subst; apply H24.\n\n    apply H24. \n    \n    \n    assert ( Some   (Heap_OBJ cls_f2 FF2 lof2)\n      = lookup_heap_obj\n          (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)) fo2).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls (fields_update F f v) lo) h2; auto.\n    intro contra. subst; auto.\n    assert (beq_oid o o = true). apply beq_oid_same.\n    rewrite H25 in H15; inversion H15. \n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto. \n\n\n    \n  - intros.\n    apply lookup_updated_heap_must_none in H10.\n    auto. \n  - intros.\n    case_eq (beq_oid o0 o); intro.\n    apply beq_oid_equal in H12.\n    rewrite <- H12 in H1. apply H9 with cls F lo; auto.\n    apply flow_transitive with (join_label lb1 lx); auto.\n\n    assert (Some (Heap_OBJ cls0 F0 lb) = lookup_heap_obj h2 o0).\n    apply lookup_updated_not_affected_reverse\n      with o (Heap_OBJ cls (fields_update F f v) lo)\n           (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)); auto.\n    intro contra. rewrite contra in H12.\n    assert (beq_oid o o = true). apply beq_oid_same.\n    rewrite H12 in H13. inversion H13.\n    apply H9 with cls0 F0 lb; auto. \nQed. Hint Resolve  update_h2_with_H_preserve_bijection.   \n\n\n\n\n\n\nLemma update_field_h1_preserve_L_eq_tm  :\n  forall  φ h1 h2 ct cls F lo o lb1 lx\n          t1 t2 v f ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_tm t1 h1 t2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  value v ->\n  (*tm_has_type ct gamma h1 ((FieldWrite (ObjId o) f (unlabelOpaque (v_opa_l v lx)))) T ->*)\n  L_equivalence_tm t1 (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo))\n                    t2 h2 φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo o lb1 lx t1 t2 v f.\n  intros.\n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lb1 lx; auto.\n  apply  join_label_commutative; auto.\n\n  \n  assert (flow_to lo L_Label = false).\n  apply flow_transitive with (join_label lb1 lx); auto. \n\n  generalize dependent t2.  \n  induction t1; intros;inversion H2; subst; auto.\n\n  apply L_equivalence_tm_eq_object_L  with cls1 F1 lb0 cls2 F2 lb2; subst; auto.\n  apply lookup_updated_not_affected with o (Heap_OBJ cls (fields_update F f v) lo) h1; auto.\n  intro contra. rewrite contra in H11. rewrite <- H11 in H3. inversion H3; subst; auto.\n  try (inconsist_label).\n\n  case_eq (beq_oid o0 o); intro.\n  apply beq_oid_equal in H9. subst; auto.\n  rewrite <- H10 in H3; inversion H3; subst; auto. \n  apply L_equivalence_tm_eq_object_H  with cls1 cls2 (fields_update F1 f v) lb0  F2 lb2; subst; auto.\n  apply lookup_updated with h1 ((Heap_OBJ cls1 F1 lb0) ); auto.\n\n  apply L_equivalence_tm_eq_object_H  with cls1 cls2  F1 lb0  F2 lb2; subst; auto.\n  apply lookup_updated_not_affected with o (Heap_OBJ cls (fields_update F f v) lo) h1; auto.\n  intro contra.  rewrite contra in H9. pose proof (beq_oid_same o).\n  rewrite H9 in H14; inversion H14. \nQed. Hint Resolve   update_field_h1_preserve_L_eq_tm.\n\n\n\n\nLemma update_field_h2_preserve_L_eq_tm  :\n  forall  φ h1 h2 ct cls F lo o lb1 lx\n          t1 t2 v f ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_tm t1 h1 t2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n  flow_to (join_label lb1 lx) lo  = true ->\n  flow_to lb1 L_Label = false ->\n  value v ->\n  L_equivalence_tm t1 h1\n                    t2 (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)) φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo o lb1 lx t1 t2 v f.\n  intros.\n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lb1 lx; auto.\n  apply  join_label_commutative; auto.\n\n  assert (flow_to lo L_Label = false).\n  apply flow_transitive with (join_label lb1 lx); auto. \n\n  generalize dependent t2.  \n  induction t1; intros;inversion H2; subst; auto.\n\n  apply L_equivalence_tm_eq_object_L  with cls1 F1 lb0 cls2 F2 lb2; subst; auto.\n  apply lookup_updated_not_affected with o (Heap_OBJ cls (fields_update F f v) lo) h2; auto.\n  intro contra. rewrite contra in H13. rewrite <- H13 in H3. inversion H3; subst; auto.\n  try (inconsist_label).\n\n  case_eq (beq_oid o2 o); intro.\n  apply beq_oid_equal in H9. subst; auto.\n  rewrite <- H12 in H3; inversion H3; subst; auto. \n  apply L_equivalence_tm_eq_object_H  with cls1 cls2 F1 lb0 (fields_update F2 f v) lb2; subst; auto.\n  apply lookup_updated with h2 ((Heap_OBJ cls2 F2 lb2) ); auto.\n\n  apply L_equivalence_tm_eq_object_H  with cls1 cls2 F1 lb0 F2 lb2; subst; auto.\n  apply lookup_updated_not_affected with o (Heap_OBJ cls (fields_update F f v) lo) h2; auto.\n  intro contra.  rewrite contra in H9. pose proof (beq_oid_same o).\n  rewrite H9 in H14; inversion H14. \nQed. Hint Resolve   update_field_h2_preserve_L_eq_tm.\n\n\nLemma update_field_h1_preserve_L_eq_fs  :\n  forall  φ h1 h2 ct cls F lo o lb1 lx\n          fs1 fs2 v f ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_fs fs1 h1 fs2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  value v ->\n  L_equivalence_fs fs1 (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo))\n                    fs2 h2 φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo o lb1 lx fs1 fs2 v f.\n  intros.\n  generalize dependent fs2.\n  induction fs1; intros; inversion H2; subst; auto.\n\n  apply L_equal_fs; auto.\n  apply update_field_h1_preserve_L_eq_tm with ct lb1 lx; auto.\nQed. Hint Resolve update_field_h1_preserve_L_eq_fs.\n\n\nLemma update_field_h2_preserve_L_eq_fs :\n  forall  φ h1 h2 ct cls F lo o lb1 lx\n          fs1 fs2 v f ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_fs fs1 h1 fs2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  value v ->\n  L_equivalence_fs fs1 h1\n                    fs2 (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)) φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo o lb1 lx fs1 fs2 v f.\n  intros.\n  generalize dependent fs2.\n  induction fs1; intros; inversion H2; subst; auto.\n\n  apply L_equal_fs; auto.\n  apply update_field_h2_preserve_L_eq_tm with ct lb1 lx; auto.\nQed. Hint Resolve update_field_h2_preserve_L_eq_fs.\n\n\nLemma update_field_h1_preserve_L_eq_store :\n  forall  φ h1 h2 ct cls F lo o lb1 lx\n          sf1 sf2 v f ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_store sf1 h1 sf2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  value v ->\n  L_equivalence_store sf1 (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo))\n                    sf2 h2 φ.\nProof with eauto.\n  intros  φ h1 h2 ct cls F lo o lb1 lx\n          sf1 sf2 v f.\n  intros.\n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lb1 lx; auto.\n  apply  join_label_commutative; auto.\n\n  assert (flow_to lo L_Label = false).\n  apply flow_transitive with (join_label lb1 lx); auto. \n\n  inversion H2; subst; auto. \n  apply L_equivalence_store_L; auto.\n  destruct H9.\n  split; auto; intros.\n  apply update_field_h1_preserve_L_eq_tm with ct lb1 lx; auto.\n  apply  H9 with x; auto. \nQed. Hint Resolve update_field_h1_preserve_L_eq_store.\n\n\n\nLemma update_field_h2_preserve_L_eq_store  :\n  forall  φ h1 h2 ct cls F lo o lb1 lx\n          sf1 sf2 v f ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_store sf1 h1 sf2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  value v ->\n  L_equivalence_store sf1 h1\n                    sf2 (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)) φ.\nProof with eauto.\n  intros  φ h1 h2 ct cls F lo o lb1 lx\n          sf1 sf2 v f.\n  intros.\n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lb1 lx; auto.\n  apply  join_label_commutative; auto.\n\n  assert (flow_to lo L_Label = false).\n  apply flow_transitive with (join_label lb1 lx); auto. \n\n  inversion H2; subst; auto. \n  apply L_equivalence_store_L; auto.\n  intros.\n  destruct H9; auto.\n  split; auto.\n  intros.\n  apply update_field_h2_preserve_L_eq_tm with ct lb1 lx; auto.\n  apply H9 with x; auto. \nQed. Hint Resolve update_field_h2_preserve_L_eq_store.\n    \n\n\n\nLemma update_field_h1_preserve_L_eq_ctn :\n  forall  φ h1 h2 ct cls F lo o lb1 lx\n          ctn1 ctn2 v f ,\n   wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_eq_container ctn1 h1 ctn2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to  (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  value v ->\n  L_eq_container ctn1 (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo))\n                    ctn2 h2 φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo o lb1 lx ctn1 ctn2 v f.\n  intros.\n  generalize dependent ctn2.\n  induction ctn1; intros; inversion H2; subst; auto.\n  apply  L_eq_ctn; auto.\n  apply update_field_h1_preserve_L_eq_tm with ct lb1 lx; auto.\n  apply update_field_h1_preserve_L_eq_fs with ct lb1 lx; auto.\n  apply update_field_h1_preserve_L_eq_store with ct lb1 lx; auto.\nQed. Hint Resolve update_field_h1_preserve_L_eq_ctn. \n\n\n\nLemma update_field_h2_preserve_L_eq_ctn:\n  forall  φ h1 h2 ct cls F lo o lb1 lx\n          ctn1 ctn2 v f ,\n   wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_eq_container ctn1 h1 ctn2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  value v ->\n  L_eq_container ctn1 h1\n                    ctn2 (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)) φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo o lb1 lx ctn1 ctn2 v f.\n  intros.\n  generalize dependent ctn2.\n  induction ctn1; intros; inversion H2; subst; auto.\n  apply  L_eq_ctn; auto.\n  apply update_field_h2_preserve_L_eq_tm with ct lb1 lx; auto.\n  apply update_field_h2_preserve_L_eq_fs with ct lb1 lx; auto.\n  apply update_field_h2_preserve_L_eq_store with ct lb1 lx; auto.\nQed. Hint Resolve update_field_h2_preserve_L_eq_ctn.\n\n  \n\nLemma update_field_h1_preserve_L_eq_ctns :\n  forall  φ h1 h2 ct cls F lo o lb1 lx\n          ctns1 ctns2 v f ,\n   wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_eq_ctns ctns1 h1 ctns2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  value v ->\n  L_eq_ctns ctns1 (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo))\n                    ctns2 h2 φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo o lb1 lx ctns1 ctns2 v f.\n  intros.\n  generalize dependent ctns2.\n  induction ctns1; intros; inversion H2; subst; auto.\n  apply  L_eq_ctns_list; auto.\n  apply update_field_h1_preserve_L_eq_ctn with ct lb1 lx; auto.\nQed. Hint Resolve update_field_h1_preserve_L_eq_ctns.\n\n\nLemma update_field_h2_preserve_L_eq_ctns :\n  forall  φ h1 h2 ct cls F lo o lb1 lx\n          ctns1 ctns2 v f ,\n   wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_eq_ctns ctns1 h1 ctns2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n  flow_to (join_label lb1 lx) lo  = true ->\n  flow_to lb1 L_Label = false ->\n  value v ->\n  L_eq_ctns ctns1 h1\n                    ctns2 (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)) φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo o lb1 lx ctns1 ctns2 v f.\n  intros.\n  generalize dependent ctns1.\n  induction ctns2; intros; inversion H2; subst; auto.\n  apply  L_eq_ctns_list; auto.\n  apply update_field_h2_preserve_L_eq_ctn with ct lb1 lx; auto.\nQed. Hint Resolve update_field_h2_preserve_L_eq_ctns.\n\n\nLemma update_field_h1_preserve_config_eq :\n  forall  φ h1 h2 ct cls F lo o lb1 lx\n          ctn1 ctn2 ctns1 ctns2 v f,\n    wfe_heap ct h2 ->  wfe_heap ct h1 -> \n    L_equivalence_heap h1 h2 φ ->\n    L_equivalence_config (Config ct ctn1 ctns1  h1)\n                         (Config ct ctn2 ctns2  h2) φ ->\n\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    flow_to  (join_label lb1 lx) lo = true ->\n    flow_to lb1 L_Label = false ->\n    value v ->\n    L_equivalence_config\n      (Config ct ctn1 ctns1 (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo)))\n      (Config ct ctn2 ctns2  h2)  φ.\nProof with eauto.\n  intros.\n  \n  remember (Config ct ctn1 ctns1 h1) as config1.\n  remember (Config ct ctn2 ctns2 h2) as config2.\n  generalize dependent ctn1. generalize dependent ctn2.\n  generalize dependent ctns1. generalize dependent ctns2. \n  induction H2; subst; intros; inversion Heqconfig1; inversion Heqconfig2; subst; auto.\n  apply L_equivalence_config_L; auto.\n  apply update_field_h1_preserve_L_eq_ctn with ct lb1 lx; auto.\n  apply update_field_h1_preserve_L_eq_ctns with ct lb1 lx; auto.\n\n  \n  induction ctns3. induction ctns0.\n  apply L_equivalence_config_H; auto.\n  unfold low_component.  \n  rewrite H2; rewrite H7.\n  apply L_equivalence_config_L; auto.\n  apply L_eq_ctn; auto.\n  apply L_equivalence_store_L; auto; intros; try (inversion H9).\n  split; auto.\n  intros; inversion H9.\n  split; auto. \n\n  apply L_equivalence_config_H; auto.\n  unfold low_component.  \n  rewrite H2; rewrite H7.\n  fold low_component.\n  unfold low_component  in H8.\n  rewrite H2 in H8. rewrite H7 in H8.\n  fold low_component  in H8.\n\n  assert (  L_equivalence_config\n    (Config ct (Container hole nil L_Label empty_stack_frame) nil\n       (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo)))\n    (Config ct (Container hole nil L_Label empty_stack_frame) nil h1)  φ).\n  apply L_equivalence_config_L; auto.\n  apply L_eq_ctn; auto.\n  apply L_equivalence_store_L; auto; intros;\n    try (inversion H9).\n  intros. split; auto.\n  intros. inversion H9. \n  split; auto.  \n\n  \n  remember ((low_component ct a ctns0 h2)) as conf.\n  destruct conf. destruct c0. \n  assert (c = ct /\\ h = h2 /\\ flow_to l0 L_Label = true).\n  apply low_component_lead_to_L with t f0 s a \n                                     l  ctns0; auto. \n  \n  destruct H10. destruct H11. subst; auto. \n  apply L_equivalence_config_L; auto.\n  apply update_field_h1_preserve_L_eq_ctn with ct lb1 lx; auto.\n  inversion H8; subst;  auto. \n  try (inconsist_label).\n  inversion H8; subst;  auto.  \n  inversion H29; subst;  auto. \n  try (inconsist_label).\n  inversion H8. inversion H8. \n\n  + apply L_equivalence_config_H; auto.\n  remember (low_component ct (Container t1 fs1 lb0 sf1) (a :: ctns3) h1) as conf1.\n  remember ((low_component ct (Container t2 fs2 lb2 sf2) ctns0 h2)) as conf2.\n  destruct conf1. destruct conf2.\n  destruct c0. \n  assert (c = ct /\\ h = h1 /\\ flow_to l1 L_Label = true).\n  apply low_component_lead_to_L with t f0 s (Container t1 fs1 lb0 sf1) l (a :: ctns3)  ; auto. \n\n  destruct c2. \n  assert (c1 = ct /\\ h0 = h2 /\\ flow_to l2 L_Label = true).\n  apply low_component_lead_to_L with t0 f1 s0 (Container t2 fs2 lb2 sf2) l0 ctns0  ; auto.\n  destruct H9. destruct H11.\n  destruct H10. destruct H13.     subst. auto.\n (*\n  inversion H; subst; auto. inversion H0; subst; auto. \n  assert (valid_ctn ct (Container t f l1 s)  h1 /\\ valid_ctns ct l h1).\n  apply valid_preservation_low_component with (Container t1 fs1 lb1 sf1)\n                                                 (a :: ctns3)\n                                                 h1  ; auto.\n  assert (valid_ctn ct (Container t0 f0 l2 s0)  h2 /\\ valid_ctns ct l0 h2).\n  apply valid_preservation_low_component with (Container t2 fs2 lb2 sf2)\n                                                 ctns0\n                                                 h2  ; auto.\n  *)\n  assert (Config ct (Container t f0 l1 s) l (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo))\n          = (low_component ct (Container t1 fs1 lb0 sf1) (a :: ctns3)\n                           (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f v) lo)))\n         ).\n  apply low_component_irrelevant_to_heap with h1; auto.  \n  rewrite <- H9.  \n  apply   L_equivalence_config_L; auto.\n  apply update_field_h1_preserve_L_eq_ctn  with ct lb1 lx; auto.\n  inversion H8; subst; auto. \n  try (inconsist_label).\n  apply update_field_h1_preserve_L_eq_ctns  with ct lb1 lx; auto.\n  inversion H8; subst; auto. \n  try (inconsist_label).\n  inversion H8.  inversion H8.\n  inversion H8. inversion H8. \nQed. Hint Resolve update_field_h1_preserve_config_eq.\n\n\nLemma update_field_h2_preserve_config_eq :\n  forall  φ h1 h2 ct cls F lo o lb1 lx\n          ctn1 ctn2 ctns1 ctns2 v f,\n    wfe_heap ct h2 ->  wfe_heap ct h1 -> \n    L_equivalence_heap h1 h2 φ ->\n    L_equivalence_config (Config ct ctn1 ctns1  h1)\n                         (Config ct ctn2 ctns2  h2) φ ->\n\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n    flow_to  (join_label lb1 lx) lo = true ->\n    flow_to lb1 L_Label = false ->\n    value v ->\n    L_equivalence_config\n      (Config ct ctn1 ctns1 h1)\n      (Config ct ctn2 ctns2  (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)))  φ.\nProof with eauto.\n  intros.\n  \n  remember (Config ct ctn1 ctns1 h1) as config1.\n  remember (Config ct ctn2 ctns2 h2) as config2.\n  generalize dependent ctn1. generalize dependent ctn2.\n  generalize dependent ctns1. generalize dependent ctns2. \n  induction H2; subst; intros; inversion Heqconfig1; inversion Heqconfig2; subst; auto.\n  apply L_equivalence_config_L; auto.\n  apply update_field_h2_preserve_L_eq_ctn with ct lb1 lx; auto.\n  apply update_field_h2_preserve_L_eq_ctns with ct lb1 lx; auto.\n\n  \n  induction ctns3. induction ctns0.\n  apply L_equivalence_config_H; auto.\n  unfold low_component.  \n  rewrite H2; rewrite H7.\n  apply L_equivalence_config_L; auto.\n  apply L_eq_ctn; auto.\n  apply L_equivalence_store_L; auto; intros; try (empty_sf).\n  split; auto.\n  intros; try (empty_sf).\n  split; auto. \n\n\n  apply L_equivalence_config_H; auto.\n  unfold low_component.  \n  rewrite H2; rewrite H7.\n  fold low_component.\n  unfold low_component  in H8.\n  rewrite H2 in H8. rewrite H7 in H8.\n  fold low_component  in H8.\n\n  \n  assert (  L_equivalence_config\n    (Config ct (Container hole nil L_Label empty_stack_frame) nil\n       h1 )\n    (Config ct (Container hole nil L_Label empty_stack_frame) nil\n    (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)))  φ).\n  apply L_equivalence_config_L; auto.\n  apply L_eq_ctn; auto.\n  apply L_equivalence_store_L; auto; intros; try (empty_sf).\n  split; auto.\n  intros; try (empty_sf).\n  split; auto. \n\n  \n  remember ((low_component ct a ctns0 h2)) as conf.\n  destruct conf. destruct c0. \n  assert (c = ct /\\ h = h2 /\\ flow_to l0 L_Label = true).\n  apply low_component_lead_to_L with t f0 s a \n                                     l  ctns0; auto.  \n  destruct H10. destruct H11. subst; auto.\n\n  assert (Config ct (Container t f0 l0 s) l\n                 (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)) \n          = (low_component ct a ctns0 (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)))).\n  apply low_component_irrelevant_to_heap with h2; auto. rewrite <- H10.  \n  apply L_equivalence_config_L; auto.\n  apply update_field_h2_preserve_L_eq_ctn with ct lb1 lx; auto.\n  inversion H8; subst;  auto.  \n  try (inconsist_label).\n  inversion H8; subst;  auto.\n  apply update_field_h2_preserve_L_eq_ctns with ct lb1 lx; auto.\n  try (inconsist_label).\n  inversion H8.\n  inversion H8. \n\n\n  + apply L_equivalence_config_H; auto.\n  remember (low_component ct (Container t1 fs1 lb0 sf1) (a :: ctns3) h1) as conf1.\n  remember ((low_component ct (Container t2 fs2 lb2 sf2) ctns0 h2)) as conf2.\n  destruct conf1. destruct conf2.\n  destruct c0. \n  assert (c = ct /\\ h = h1 /\\ flow_to l1 L_Label = true).\n  apply low_component_lead_to_L with t f0 s (Container t1 fs1 lb0 sf1) l (a :: ctns3)  ; auto. \n\n  destruct c2. \n  assert (c1 = ct /\\ h0 = h2 /\\ flow_to l2 L_Label = true).\n  apply low_component_lead_to_L with t0 f1 s0 (Container t2 fs2 lb2 sf2) l0 ctns0  ; auto.\n  destruct H9. destruct H11.\n  destruct H10. destruct H13.     subst; auto.\n  assert (Config ct (Container t0 f1 l2 s0) l0 (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo))\n          = (low_component ct (Container t2 fs2 lb2 sf2)  ctns0\n                           (update_heap_obj h2 o (Heap_OBJ cls (fields_update F f v) lo)))\n         ).\n  apply low_component_irrelevant_to_heap with h2; auto.  \n  rewrite <- H9.  \n  apply   L_equivalence_config_L; auto.\n  apply update_field_h2_preserve_L_eq_ctn  with ct lb1 lx; auto.\n  inversion H8; subst; auto. \n  try (inconsist_label).\n  apply update_field_h2_preserve_L_eq_ctns  with ct lb1 lx; auto.\n  inversion H8; subst; auto. \n  try (inconsist_label).\n  inversion H8.  inversion H8.\n  inversion H8. inversion H8. \nQed. Hint Resolve update_field_h2_preserve_config_eq.\n\n\n\nLemma value_of_fields : forall h o cls F lb f ct gamma T v,  \n    wfe_heap ct h -> field_wfe_heap ct h ->\n    Some (Heap_OBJ cls F lb) = lookup_heap_obj h o ->\n    tm_has_type ct gamma h (FieldWrite (ObjId o) f v) T ->\n    F f = Some null \\/ exists o', F f = Some (ObjId o').\nProof.\n  intros  h o cls F lb f ct gamma T v.\n  intro H_wfe_heap. intro H_wfe_fields. \n  intro Hy. intro H_typing.  inversion H_typing. inversion H2;subst; auto. \n  destruct H17 as [F']. destruct H as [lo]. rewrite H in Hy. inversion Hy. subst.\n  destruct H16 as [field_defs]. destruct H0 as [method_defs].\n  rewrite <- H8 in H12. inversion H12. subst.\n  inversion H_wfe_fields. subst.\n  destruct H0 with o (class_def clsT field_defs method_defs) F' clsT lo method_defs field_defs\n                   f cls'; auto. destruct H1.\n  destruct H3. left. subst; auto. \n  destruct H3 as [o']. destruct H3 as [F0]. destruct H3 as [lx].\n  destruct H3. destruct H3. destruct H3. right. exists o'. subst; auto.\nQed. Hint Resolve  value_of_fields. \n\n\n\n  (* heap bijection preservation *)\nLemma update_field_preserve_bijection : forall ct h1 h2 φ cls F lo\n                                                 cls0 F0 lo0\n                                                 lx lx0 v v0 f0\n                                                 o o0 lb1 lb2\n                                                 ,\n    \n    (v = null \\/\n       (exists (o0 : oid) (cls0 : CLASS) (F0 : FieldMap) (lo0 : Label),\n          v = ObjId o0 /\\ Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h1 o0 /\\ flow_to lo0 lo = true)) ->\n    (v0 = null \\/\n        (exists (o0 : oid) (cls0 : CLASS) (F0 : FieldMap) (lo1 : Label),\n           v0 = ObjId o0 /\\ Some (Heap_OBJ cls0 F0 lo1) = lookup_heap_obj h2 o0 /\\ flow_to lo1 lo0 = true) ) ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n      wfe_heap ct h2 -> field_wfe_heap ct h2 ->\n      \n      L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    flow_to (join_label lb1 lx) lo = true ->\n    flow_to (join_label lb2 lx0) lo0 = true ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    L_equivalence_tm (v_opa_l v lx) h1 (v_opa_l v0 lx0) h2 φ ->\n    L_equivalence_heap (update_heap_obj h1 o (Heap_OBJ cls (fields_update F f0 v) lo))\n                       (update_heap_obj h2 o0 (Heap_OBJ cls0 (fields_update F0 f0 v0) lo0)) φ.\n    \nProof with eauto.\n  intros ct h1 h2 φ cls F lo\n         cls0 F0 lo0\n         lx lx0 v v0 f0\n         o o0 lb1 lb2.\n        \n  intros H_v. intro H_v0. intros.   \n  inversion H8; subst; auto.\n  rewrite <- H15 in H4; inversion H4; subst; auto.\n  rewrite <- H17 in H5; inversion H5; subst; auto.\n  inversion H11; subst; auto.\n  (* opa_l has low label*)\n  inversion H3; subst; auto.\n  apply L_eq_heap; auto.\n  \n  - intros.\n    assert (L_equivalence_object o1 h1 o2 h2 φ) as H_eq_o1_o2.          \n    apply H12; auto. \n    inversion H_eq_o1_o2; subst; auto. \n    case_eq (beq_oid o1 o); intro.\n    apply beq_oid_equal in H32.\n    rewrite H32 in H25. rewrite <- H25 in H15. inversion H15; subst.\n    assert ( Some  (Heap_OBJ cls0 (fields_update F0 f0 v) lb4)  =\n      lookup_heap_obj  (update_heap_obj h1 o (Heap_OBJ cls0 (fields_update F0 f0 v) lb4))  o).\n    apply lookup_updated with h1  (Heap_OBJ cls0 F0 lb4); auto.\n\n    case_eq (beq_oid o2 o0); intro.\n    apply beq_oid_equal in H33.\n    rewrite H33 in H28. rewrite <- H28 in H17; inversion H17; subst; auto.  \n\n    assert ( Some  (Heap_OBJ cls3 (fields_update F3 f0 v0) lb5)  =\n      lookup_heap_obj  (update_heap_obj h2 o0 (Heap_OBJ cls3 (fields_update F3 f0 v0) lb5))  o0).\n    apply lookup_updated with h2  (Heap_OBJ cls3 F3 lb5); auto.\n    apply object_equal_L with lb4 lb5 cls0 cls3\n                              (fields_update F0 f0 v)\n                              (fields_update F3 f0 v0); auto.\n    destruct H31. destruct H34. destruct H35.\n    split; auto.\n    split; auto.\n    intro. split; auto.\n    intro. unfold  fields_update in H37.\n    case_eq (beq_id f0 fname); intro.\n    rewrite H38 in H37.  inversion H37. \n    rewrite H38 in H37.  apply H34 in H37. \n    unfold  fields_update. rewrite H38. auto.\n\n    intro. unfold  fields_update in H37.\n    case_eq (beq_id f0 fname); intro.\n    rewrite H38 in H37.  inversion H37. \n    rewrite H38 in H37.  destruct H34 with fname.\n    apply H40 in H37. \n    unfold  fields_update. rewrite H38. auto.\n\n    split; auto.\n    intro. split; auto.\n    intro. unfold  fields_update in H37.\n    (* case_eq (beq_id f0 fname) *)\n    case_eq (beq_id f0 fname); intro.\n    rewrite H38 in H37.  inversion H37.\n    rewrite H40 in H27; inversion H27; auto. \n    unfold  fields_update. rewrite H38. auto.\n\n    rewrite H38 in H37. apply H35 in H37. \n    unfold  fields_update. rewrite H38. auto.\n\n    intro. unfold  fields_update in H37.\n    case_eq (beq_id f0 fname); intro.\n    rewrite H38 in H37.  inversion H37.\n    rewrite H40 in H27; inversion H27; auto. \n    unfold  fields_update. rewrite H38. auto.\n\n    rewrite H38 in H37. destruct H35 with fname.\n    apply H40 in H37. \n    unfold  fields_update. rewrite H38. auto.\n\n    intros. unfold  fields_update in H37. \n    unfold  fields_update in H38.\n    case_eq (beq_id f0 fname); intro.\n    rewrite H39 in H37. rewrite H39 in H38.\n    inversion H37. inversion H38. \n\n    case_eq (beq_oid fo1 o); intro.\n    apply beq_oid_equal in H40.\n    rewrite <- H40 in H25. \n    assert (Some (Heap_OBJ cls0 (fields_update F0 f0 (ObjId fo1)) lb4)\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls0 (fields_update F0 f0 (ObjId fo1)) lb4)) fo1).\n    apply lookup_updated with h1 (Heap_OBJ cls0 F0 lb4); auto.\n    rewrite H40. auto.\n\n    \n    case_eq (beq_oid fo2 o0); intro.\n    apply beq_oid_equal in H44.\n    rewrite <- H44 in H28. \n    assert (Some (Heap_OBJ cls3 (fields_update F3 f0 (ObjId fo2)) lb5)\n            = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls3 (fields_update F3 f0 (ObjId fo2)) lb5)) fo2).\n    apply lookup_updated with h2 (Heap_OBJ cls3 F3 lb5); auto.\n    rewrite H44. auto.\n    exists cls0. exists cls3. exists lb4. exists lb5.\n    exists (fields_update F0 f0 (ObjId fo1)).\n    exists (fields_update F3 f0 (ObjId fo2)).\n    split; auto. split; auto.\n    subst; auto.\n\n    (* if fo1 = o, then fo2 must be equal to o2*)\n    subst; auto.\n    inversion H11; subst; auto.\n    inversion H50; subst; auto.\n    rewrite H41 in H14; inversion H14; subst; auto.\n\n    pose proof (beq_oid_same o0).\n    try (inconsist).\n    rewrite <- H41 in H25; inversion H25; subst; auto.\n    try (inconsist_label).\n\n    assert (flow_to (join_label lb1 lx0) L_Label = false).\n    apply flow_join_label with lx0 lb1; auto. \n\n    assert (flow_to lb5 L_Label = false).\n    apply flow_transitive with (join_label lb1 lx0); auto.\n    try (inconsist_label).\n    try (inconsist).\n\n    (* beq_oid fo1 o = false*)\n    subst; auto. \n    inversion H27; subst; auto.\n    case_eq (beq_oid fo2 o0); intro.\n    \n    (* inconsist assumption *)\n    apply beq_oid_equal in H31.\n    subst; auto.\n    apply right_left in H14.\n    apply right_left in H42.\n    rewrite H42 in H14.\n    inversion H14; subst; auto. \n    pose proof (beq_oid_same o).\n    try (inconsist).\n\n    (* beq_oid fo2 o0 = false*)\n    assert (Some (Heap_OBJ cls1 F1 lb0) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls3 (fields_update F0 f0 (ObjId fo1)) lb4)) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls3 (fields_update F0 f0 (ObjId fo1)) lb4)  h1; auto.\n    intro contra. rewrite contra in H40.\n    pose proof (beq_oid_same o). try (inconsist).\n\n    assert (Some (Heap_OBJ cls2 F2 lb3) =\n           lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls3 (fields_update F3 f0 (ObjId fo2)) lb5)) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls3 (fields_update F3 f0 (ObjId fo2)) lb5) h2; auto.\n    intro contra. rewrite contra in H31.\n    pose proof (beq_oid_same o0). try (inconsist).\n\n    exists cls1. exists cls2.\n    exists lb0. exists lb3.\n    exists F1. exists F2.  \n    split; auto. split; auto.\n    left. split; auto.   split; auto. split; auto.\n    apply H12 in H42. inversion H42; subst; auto.\n    rewrite <- H48 in H43; inversion H43; subst; auto.\n    rewrite <- H49 in H45; inversion H45; subst; auto.\n    apply H52. \n    \n    \n    (*cannot assign H objects to L objects*)\n    destruct H_v.  inversion H31.\n    destruct H31 as [o'].\n    destruct H31 as [cls'].\n    destruct H31 as [F'].\n    destruct H31 as [lo'].\n    destruct H31.\n    inversion H31; subst; auto.\n    destruct H41.\n    rewrite <- H42 in H41; inversion H41; subst; auto.\n    assert (flow_to lb4 L_Label = false).\n    apply flow_transitive with lb0; auto.\n    try (inconsist).\n\n\n\n\n    rewrite H39 in H37. rewrite H39 in H38.\n    destruct H36 with fname fo1 fo2; auto.\n    destruct H40 as [cls_f2]. rename x into cls_f1.\n    destruct H40 as [lof1]. destruct H40 as [lof2].\n    destruct H40 as [FF1]. destruct H40 as [FF2]. \n    destruct H40. destruct H41.\n    \n    case_eq (beq_oid fo1 o); intro.\n    apply beq_oid_equal in H43.\n    rewrite <- H43 in H25.\n    assert (Some (Heap_OBJ cls0 (fields_update F0 f0 v) lb4)\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls0 (fields_update F0 f0 v) lb4)) fo1).\n    apply lookup_updated with h1 (Heap_OBJ cls0 F0 lb4); auto.\n    rewrite H43; auto.\n\n    \n    case_eq (beq_oid fo2 o0); intro.\n    apply beq_oid_equal in H45.\n    rewrite <- H45 in H28. \n    assert (Some (Heap_OBJ cls3 (fields_update F3 f0 v0) lb5)\n            = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls3 (fields_update F3 f0 v0) lb5)) fo2).\n    apply lookup_updated with h2 (Heap_OBJ cls3 F3 lb5); auto.\n    rewrite H45. auto.\n    exists cls0. exists cls3.\n    exists lb4. exists lb5.\n    exists (fields_update F0 f0 v). exists (fields_update F3 f0 v0).\n    split; auto.\n    split; auto.\n    destruct H42. \n    left; split; auto.  apply H42.\n    subst; auto. \n    \n    (* if fo1 = o, then fo2 must be equal to o2*)\n    subst; auto.\n    destruct H42. destruct H31. \n    rewrite  H31 in H14; inversion H14; subst; auto.\n    pose proof (beq_oid_same o0).\n    try (inconsist).\n\n    destruct H31.\n    apply H20 in H40; auto. rewrite H40 in H24; inversion H24. \n\n    (* beq_oid fo1 o = false*)\n    case_eq (beq_oid fo2 o0); intro.\n    \n    (* inconsist assumption *)\n    apply beq_oid_equal in H44.\n    subst; auto.\n    apply right_left in H14.\n    \n    destruct H42. destruct H31. \n    apply right_left in H31.\n    rewrite H31 in H14.\n    inversion H14; subst; auto. \n    pose proof (beq_oid_same o).\n    try (inconsist).\n\n    rewrite H41 in H28; inversion H28; subst; auto.\n    destruct H31. try (inconsist).\n    \n\n    (* beq_oid fo2 o0 = false*)\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls0 (fields_update F0 f0 v) lb4)) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls0 (fields_update F0 f0 v) lb4)  h1; auto.\n    intro contra. rewrite contra in H43.\n    pose proof (beq_oid_same o). try (inconsist).\n\n    assert (Some  (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls3 (fields_update F3 f0 v0) lb5)) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls3 (fields_update F3 f0 v0) lb5) h2; auto.\n    intro contra. rewrite contra in H44.\n    pose proof (beq_oid_same o0). try (inconsist).\n\n    exists  cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2. \n    split; auto.\n\n    rewrite H14 in H24. inversion H24. subst; auto.\n    pose proof (beq_oid_same o2).\n    try (inconsist).\n\n    (*beq_oid o2 o0 = true*)\n    case_eq (beq_oid o2 o0); intro.\n    apply beq_oid_equal in H33.\n    subst; auto. \n    apply right_left in H14.\n    apply right_left in H24.\n    rewrite H14 in H24; inversion H24; subst; auto.\n    pose proof (beq_oid_same o1).\n    try (inconsist).\n\n     assert (Some  (Heap_OBJ cls0 F0 lb4)  =\n           lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0))  o1\n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0) h1; auto.\n    intro contra. rewrite contra in H32.\n    pose proof (beq_oid_same o).\n    try (inconsist).\n\n\n    assert (Some  (Heap_OBJ cls3 F3 lb5)  =\n           lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3))  o2\n           ).\n    apply lookup_updated_not_affected with o0  (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)  h2; auto.\n    intro contra. rewrite contra in H33.\n    pose proof (beq_oid_same o0).\n    try (inconsist). \n    apply  object_equal_L with lb4 lb5 cls0 cls3 F0 F3; auto.\n\n    destruct H31. destruct H36. destruct H37. \n    split; auto. split; auto. split; auto.\n\n    intros.\n    destruct H38 with fname fo1 fo2; auto.\n    rename x into cls_f1. destruct H41 as [cls_f2].\n    destruct H41 as [lof1]. destruct H41 as [lof2].\n    destruct H41 as [FF1]. destruct H41 as [FF2].\n    destruct H41.   destruct H42.\n\n    \n    case_eq (beq_oid fo1 o); intro.\n    apply beq_oid_equal in H44.\n    subst; auto.\n    rewrite H14 in H43. destruct H43. destruct H31. \n    inversion H31; subst; auto. \n    assert (Some (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)) o).\n    apply lookup_updated with h1 (Heap_OBJ cls_f1 FF1 lof1); auto.\n\n    assert (Some (Heap_OBJ cls2  (fields_update F2 f0 v0) lb3)\n            = lookup_heap_obj (update_heap_obj h2 fo2 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)) fo2).\n    apply lookup_updated with h2 (Heap_OBJ cls_f2 FF2 lof2); auto.\n    exists cls1. exists cls2.\n    exists lb0. exists lb3.\n    exists (fields_update F1 f0 v).\n    exists (fields_update F2 f0 v0). \n    split; auto.\n    split; auto.\n    left; auto.\n    split; auto.\n    split; auto. split; auto.\n    rewrite H41 in H15; inversion H15; subst; auto.\n    rewrite H42 in H17; inversion H17; subst; auto.\n    apply H43. \n\n\n    (*flow_to lof2 L_Label = false /\\ flow_to lof1 L_Label = false*)\n    rewrite H41 in H15; inversion H15; subst; auto.\n    destruct H31.\n    rewrite H43 in H16; inversion H16. \n    \n\n    (*beq_oid fo1 o = false*)\n        \n    case_eq (beq_oid fo2 o0); intro.\n    apply beq_oid_equal in H45.\n    rewrite H45 in H43.\n    destruct H43.\n    destruct H43.\n    apply right_left in H43.\n    apply right_left in H14.\n    rewrite H43 in H14; inversion H14; subst; auto.\n    pose proof (beq_oid_same o).\n    try (inconsist).\n\n    (* beq_oid fo2 o0 = false*)\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)) fo1\n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)  h1; auto.\n    intro contra. rewrite contra in H44.\n    pose proof (beq_oid_same o); try (inconsist).\n\n\n    subst; auto.\n    rewrite H42 in H17; inversion H17; subst; auto.\n    destruct H43. try (inconsist).\n\n    assert (Some  (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3) h2; auto.\n    subst; auto. \n\n    intro contra. rewrite contra in H45.\n    pose proof (beq_oid_same o0). try (inconsist).\n\n\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto.\n    assert ( Some (Heap_OBJ cls_f1 FF1 lof1) =\n             lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)) fo1).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0) h1; auto.\n    intro contra. rewrite contra in H44. assert (beq_oid o o = true).\n    apply beq_oid_same. try(inconsist).\n    auto. \n\n  - (* None -> left φ o1 = None *)\n    intros. apply lookup_updated_heap_must_none in H24.\n    apply H13 in H24. auto. \n\n  - (* o1 = None -> right φ o1 = None *)\n    intros. apply lookup_updated_heap_must_none in H24.\n    apply H18 in H24. auto.\n\n  - (* flow_to lb L_Label = false  *)\n    intros.\n    case_eq (beq_oid o1 o); intro.\n    assert ( Some (Heap_OBJ cls F lb) = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)) o1 ). auto.\n    apply lookup_updated_heap_new_obj in H29; auto.\n    inversion H29; subst; auto.\n    try (inconsist).\n    \n    assert (Some (Heap_OBJ cls F lb) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)) o1\n           ). auto.\n    apply lookup_updated_heap_old_obj in H29; auto.\n    assert ( lookup_heap_obj h1 o1 = Some (Heap_OBJ cls F lb) ); auto.\n    apply H20 in H30; auto. \n\n  - (*flow_to lb L_Label = false -> right φ o1 = None *)\n    intros.\n    case_eq (beq_oid o1 o0); intro.\n    assert ( Some (Heap_OBJ cls F lb) = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)) o1 ). auto.\n    apply lookup_updated_heap_new_obj in H29; auto.\n    inversion H29; subst; auto.\n    try (inconsist).\n    \n    assert (Some (Heap_OBJ cls F lb) =\n            lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)) o1\n           ). auto.\n    apply lookup_updated_heap_old_obj in H29; auto.\n    assert ( lookup_heap_obj h2 o1 = Some (Heap_OBJ cls F lb) ); auto.\n    apply H22 in H30; auto.\n\n  - (*cannot happen *)\n    assert (flow_to (join_label lb2 lx0) L_Label = false).\n    apply flow_join_label with lx0 lb2; auto.\n    assert (flow_to lb3 L_Label = false).\n    apply flow_transitive with (join_label lb2 lx0); auto.  \n    try (inconsist).\n    \n    \n  - (* object with h label *)\n    intros.\n    rewrite <- H14 in H4; inversion H4; subst; auto.\n    rewrite <- H16 in H5; inversion H5; subst; auto.\n\n    inversion H3; subst; auto. \n    apply  L_eq_heap; auto.\n    + intros. assert ( L_equivalence_object o1 h1 o2 h2 φ). \n      apply H12. auto.  inversion H22; subst; auto.\n      case_eq (beq_oid o1 o); intro.\n      (*impossible*)\n      apply beq_oid_equal in H28.\n      rewrite H28 in H23.\n      rewrite <- H23 in H14; inversion H14; subst; auto.\n      try (inconsist).\n      case_eq (beq_oid o2 o0); intro.\n      apply beq_oid_equal in H29.\n      rewrite H29 in H24.\n      rewrite <- H24 in H16; inversion H16; subst; auto.\n      try (inconsist).\n\n      assert (Some (Heap_OBJ cls0 F0 lb4) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)) o1\n           ).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)  h1; auto.\n      intro contra. rewrite contra in H28.\n      pose proof (beq_oid_same o). try (inconsist).\n\n      assert (Some (Heap_OBJ cls3 F3 lb5) =\n            lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)) o2\n             ).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)  h2; auto.\n      intro contra. rewrite contra in H29.\n      pose proof (beq_oid_same o0). try (inconsist).\n\n      apply object_equal_L with lb4 lb5 cls0 cls3 F0 F3; auto.\n      destruct H27. destruct H32. destruct H33. \n      split; auto. split; auto. split; auto.\n\n      intros.\n      destruct H34 with fname fo1 fo2; auto.\n      destruct H37 as [cls_f2]. rename x into cls_f1.\n      destruct H37 as [lof1]. destruct H37 as [lof2].\n      destruct H37 as [FF1]. destruct H37 as [FF2].\n      destruct H37.  destruct H38.\n\n      destruct H39. destruct H39.\n      assert (L_equivalence_object fo1 h1 fo2 h2 φ).\n      apply H12; auto. \n      inversion H41; subst; auto.\n\n      case_eq (beq_oid fo1 o); intro.\n      apply beq_oid_equal in H27.\n      rewrite H27 in H42. rewrite <- H42 in H14; inversion H14; subst; auto.\n      try (inconsist).\n    \n      case_eq (beq_oid fo2 o0); intro.\n      apply beq_oid_equal in H47.\n      rewrite H47 in H43. rewrite <- H43 in H16; inversion H16; subst; auto.\n      try (inconsist).\n\n      assert (Some  (Heap_OBJ cls4 F4 lb6) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)) fo1\n             ).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)  h1; auto.\n      intro contra. rewrite contra in H27.\n      pose proof (beq_oid_same o). try (inconsist).\n\n      assert (Some  (Heap_OBJ cls5 F5 lb7) =\n           lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)) fo2\n           ).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3) h2; auto.\n      intro contra. rewrite contra in H47.\n      pose proof (beq_oid_same o0). try (inconsist).\n\n\n      exists cls4. exists cls5.\n      exists lb6. exists lb7.\n      exists F4. exists F5. \n      split; auto.\n      split; auto.\n      left; auto.\n      split; auto.  split; auto. split; auto. apply H46.\n\n      subst; auto.\n      case_eq (beq_oid fo1 o); intro.\n      apply beq_oid_equal in H27.\n      subst; auto.\n      assert (Some (Heap_OBJ cls1 (fields_update F1 f0 v) lb0) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)) o).\n      apply lookup_updated with h1 (Heap_OBJ cls_f1 FF1 lof1); auto.\n\n      case_eq (beq_oid fo2 o0); intro.\n      apply beq_oid_equal in H40.      \n      subst; auto. \n      assert (Some (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)  =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)) o0).\n      apply lookup_updated with h2 (Heap_OBJ cls_f2 FF2 lof2); auto.\n      \n      exists cls1. exists cls2.\n      exists lb0. exists lb3.\n      exists (fields_update F1 f0 v). exists (fields_update F2 f0 v0).\n      split; auto.\n\n\n      assert (Some (Heap_OBJ cls_f2 FF2 lof2)  =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)) fo2).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3) h2; auto.\n      intro contra. rewrite contra in H40.\n      assert (beq_oid o0 o0 = true). apply beq_oid_same. try (inconsist).\n\n      exists cls1. exists cls_f2.\n      exists lb0. exists lof2.\n      exists (fields_update F1 f0 v). exists FF2.\n      split; auto. split; auto.\n      right. split; auto. apply H39. \n       \n      \n      case_eq (beq_oid fo2 o0); intro.\n      apply beq_oid_equal in H40.      \n      subst; auto. \n      assert (Some (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)  =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)) o0).\n      apply lookup_updated with h2 (Heap_OBJ cls_f2 FF2 lof2); auto.\n\n\n      assert (Some  (Heap_OBJ cls_f1 FF1 lof1) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)) fo1).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0) h1; auto.\n      intro contra. rewrite contra in H27.\n      assert (beq_oid o o = true). apply beq_oid_same. try (inconsist).      \n      \n      exists cls_f1. exists cls2.\n      exists lof1. exists lb3.\n      exists FF1. exists (fields_update F2 f0 v0).\n      split; auto. split; auto.\n      right; auto.  split; auto. apply H39. \n\n\n      assert (Some (Heap_OBJ cls_f2 FF2 lof2)  =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3)) fo2).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 (fields_update F2 f0 v0) lb3) h2; auto.\n      intro contra. rewrite contra in H40.\n      assert (beq_oid o0 o0 = true). apply beq_oid_same. try (inconsist).\n\n      assert (Some  (Heap_OBJ cls_f1 FF1 lof1) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0)) fo1).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls1 (fields_update F1 f0 v) lb0) h1; auto.\n      intro contra. rewrite contra in H27.\n      assert (beq_oid o o = true). apply beq_oid_same. try (inconsist).      \n\n      exists cls_f1. exists cls_f2.\n      exists lof1. exists lof2.\n      exists FF1. exists FF2.\n      split; auto. \n    + intros.\n      apply lookup_updated_heap_must_none in H21.\n      apply H13 in H21. auto. \n\n    + intros. \n      apply lookup_updated_heap_must_none in H21.\n      apply H17 in H21. auto.\n\n    + intros.\n      case_eq (beq_oid o1 o); intro.\n      apply  beq_oid_equal in H23.\n      rewrite <- H23 in H14.\n      destruct H19 with o1 cls1 F1 lb0; auto.\n\n      assert (Some (Heap_OBJ cls F lb) =\n              lookup_heap_obj h1 o1\n             ).\n      apply lookup_updated_heap_old_obj with  cls1 (fields_update F1 f0 v) lb0 o; auto.\n      destruct H19 with o1 cls F lb; auto. \n\n    + intros.\n      case_eq (beq_oid o1 o0); intro.\n      apply  beq_oid_equal in H23.\n      rewrite <- H23 in H16.\n      destruct H20 with o1 cls2 F2 lb3; auto.\n\n      assert (Some (Heap_OBJ cls F lb) =\n              lookup_heap_obj h2 o1\n             ).\n      apply lookup_updated_heap_old_obj with  cls2 (fields_update F2 f0 v0) lb3 o0; auto.\n      destruct H20 with o1 cls F lb; auto. \nQed. \n\n\n\n\nLemma change_obj_lbl_h1_with_H_preserve_bijection : forall ct h1 h2 φ cls lo lo' F o lb1\n  lx,\n    wfe_heap ct h1 ->\n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    flow_to (join_label lb1 lx) lo = true ->\n    flow_to lb1 L_Label = false ->\n    flow_to lo lo' = true ->\n    L_equivalence_heap\n    (update_heap_obj h1 o (Heap_OBJ cls F lo')) h2 φ.\n    \nProof with eauto.\n  intros. \n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lb1 lx; auto.\n  apply  join_label_commutative; auto.\n  \n  inversion H0; subst; auto.\n  apply L_eq_heap; auto.\n  - intros. apply H6 in H11. inversion H11; subst; auto.\n    case_eq (beq_oid o1 o); intro. apply beq_oid_equal in H17.\n    rewrite H17 in H12. rewrite <- H12 in H1. inversion H1; subst.\n    assert (flow_to lb0 (join_label lb1 lx) = false).\n    apply  flow_no_H_to_L; auto.\n    assert (flow_to lb0 L_Label = false).\n    apply flow_transitive with (join_label lb1 lx); auto. \n    try (inconsist_label).\n\n    apply object_equal_L with lb0 lb2 cls1 cls2 F1 F2; auto.\n    assert ( Some (Heap_OBJ cls1 F1 lb0) =\n      lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o1).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h1; auto.\n    intro contra.\n    try (beq_oid_inconsist).\n\n    auto. destruct H16.\n    destruct H18. destruct H19.\n    \n    split; auto.\n    split; auto. split; auto.\n    \n    intros. \n    destruct H20 with fname fo1 fo2; auto.\n    destruct H23 as [cls_f2]. rename x into cls_f1.\n    destruct H23 as [lof1]. destruct H23 as [lof2].\n    destruct H23 as [FF1]. destruct H23 as [FF2].\n    \n    destruct H23; auto.  destruct H24. destruct H25.\n    destruct H25.\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2. \n    split; auto.\n    assert ( Some   (Heap_OBJ cls_f1 FF1 lof1)\n      = lookup_heap_obj\n          (update_heap_obj h1 o (Heap_OBJ cls F lo')) fo1).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h1; auto.\n    intro contra. apply H6 in H25. inversion H25. subst; auto.\n    rewrite <- H1 in H27. inversion H27. subst; auto. \n\n    assert (flow_to lo L_Label  = false).\n    apply  flow_transitive with (join_label lb1 lx); auto.\n    try (inconsist_label). auto.\n\n    case_eq (beq_oid fo1 o); intro.\n    exists cls. exists cls_f2.\n    exists lo'. exists lof2.\n    exists F . exists FF2. \n    split; auto.\n    apply beq_oid_equal in H26; subst; auto.\n    assert (Some (Heap_OBJ cls F lo')\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o).\n    eauto using lookup_updated.  auto.\n\n    split; auto.\n    right; split; auto.\n    destruct H25; auto.\n    apply beq_oid_equal in H26; subst; auto.\n    rewrite H23 in H1. inversion H1. subst.\n    destruct H25. \n    apply flow_transitive with lof1; auto. \n    \n    \n    assert ( Some   (Heap_OBJ cls_f1 FF1 lof1)\n      = lookup_heap_obj\n          (update_heap_obj h1 o (Heap_OBJ cls F lo')) fo1).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h1; auto.\n    intro contra. subst; auto.\n    assert (beq_oid o o = true). apply beq_oid_same.\n    try (inconsist).\n    \n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto. \n\n    \n  - intros.\n    apply lookup_updated_heap_must_none in H11.\n    auto. \n  - intros.\n    case_eq (beq_oid o0 o); intro.\n    apply beq_oid_equal in H13.\n    rewrite <- H13 in H1. apply H9 with cls F lo; auto.\n    apply flow_transitive with (join_label lb1 lx); auto.\n\n    assert (Some (Heap_OBJ cls0 F0 lb) = lookup_heap_obj h1 o0).\n    apply lookup_updated_not_affected_reverse\n      with o (Heap_OBJ cls F lo')\n           (update_heap_obj h1 o (Heap_OBJ cls F lo')); auto.\n    intro contra. rewrite contra in H13.\n    assert (beq_oid o o = true). apply beq_oid_same.\n    rewrite H13 in H14. inversion H14.\n    apply H9 with cls0 F0 lb; auto. \nQed. Hint Resolve  change_obj_lbl_h1_with_H_preserve_bijection.\n\n\n\nLemma change_obj_lbl_h2_with_H_preserve_bijection : forall ct h1 h2 φ cls lo lo' F o lb1\n  lx,\n    wfe_heap ct h1 ->\n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n    flow_to (join_label lb1 lx) lo = true ->\n    flow_to lb1 L_Label = false ->\n    flow_to lo lo' = true ->\n    L_equivalence_heap h1\n    (update_heap_obj h2 o (Heap_OBJ cls F lo')) φ.\n    \nProof with eauto.\n  intros. \n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lb1 lx; auto.\n  apply  join_label_commutative; auto.\n  \n  inversion H0; subst; auto.\n  apply L_eq_heap; auto.\n  - intros. apply H6 in H11. inversion H11; subst; auto.\n    case_eq (beq_oid o2 o); intro. apply beq_oid_equal in H17.\n    rewrite H17 in H13. rewrite <- H13 in H1. inversion H1; subst.\n    assert (flow_to lb2 (join_label lb1 lx) = false).\n    apply  flow_no_H_to_L; auto.\n    \n    assert (flow_to lb2 L_Label = false).\n    apply flow_transitive with (join_label lb1 lx); auto. \n    try (inconsist_label).    \n\n    apply object_equal_L with lb0 lb2 cls1 cls2 F1 F2; auto.\n    assert ( Some (Heap_OBJ cls2 F2 lb2) =\n      lookup_heap_obj (update_heap_obj h2 o (Heap_OBJ cls F lo')) o2).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h2; auto.\n    intro contra.\n    try (beq_oid_inconsist).\n\n    auto. destruct H16.\n    destruct H18. destruct H19.\n    \n    split; auto.\n    split; auto. split; auto.\n    \n    intros. \n    destruct H20 with fname fo1 fo2; auto.\n    destruct H23 as [cls_f2]. rename x into cls_f1.\n    destruct H23 as [lof1]. destruct H23 as [lof2].\n    destruct H23 as [FF1]. destruct H23 as [FF2].\n    \n    destruct H23; auto.  destruct H24. destruct H25.\n    destruct H25.\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2. \n    split; auto.\n    assert ( Some   (Heap_OBJ cls_f2 FF2 lof2)\n      = lookup_heap_obj\n          (update_heap_obj h2 o (Heap_OBJ cls F lo')) fo2).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h2; auto.\n    intro contra. apply H6 in H25. inversion H25. subst; auto.\n    rewrite <- H1 in H28. inversion H28. subst; auto. \n\n    assert (flow_to lo L_Label  = false).\n    apply  flow_transitive with (join_label lb1 lx); auto.\n    try (inconsist_label). auto.\n\n    case_eq (beq_oid fo2 o); intro.\n    exists cls_f1. exists cls.\n    exists lof1. exists lo'.\n    exists FF1. \n    exists F.  \n    split; auto. split; auto. \n    apply beq_oid_equal in H26; subst; auto.\n    assert (Some (Heap_OBJ cls F lo')\n            = lookup_heap_obj (update_heap_obj h2 o (Heap_OBJ cls F lo')) o).\n    eauto using lookup_updated.  auto.\n\n    right; split; auto.\n    destruct H25; auto.\n    apply beq_oid_equal in H26; subst; auto.\n    rewrite H24 in H1; inversion H1; subst.\n    apply flow_transitive with lof2; auto. \n    apply H25.\n   \n    assert ( Some   (Heap_OBJ cls_f2 FF2 lof2)\n      = lookup_heap_obj\n          (update_heap_obj h2 o (Heap_OBJ cls F lo')) fo2).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h2; auto.\n    intro contra. subst; auto.\n    assert (beq_oid o o = true). apply beq_oid_same.\n    rewrite H26 in H16; inversion H16. \n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto. \n\n\n    \n  - intros.\n    apply lookup_updated_heap_must_none in H11.\n    auto. \n  - intros.\n    case_eq (beq_oid o0 o); intro.\n    apply beq_oid_equal in H13.\n    rewrite <- H13 in H1. apply H10 with cls F lo; auto.\n    apply flow_transitive with (join_label lb1 lx); auto.\n\n    assert (Some (Heap_OBJ cls0 F0 lb) = lookup_heap_obj h2 o0).\n    apply lookup_updated_not_affected_reverse\n      with o (Heap_OBJ cls F lo')\n           (update_heap_obj h2 o (Heap_OBJ cls F lo')); auto.\n    intro contra. rewrite contra in H13.\n    assert (beq_oid o o = true). apply beq_oid_same.\n    rewrite H13 in H14. inversion H14.\n    apply H10 with cls0 F0 lb; auto. \nQed. Hint Resolve change_obj_lbl_h2_with_H_preserve_bijection.   \n\n\n\n\n\nLemma change_obj_lbl_h1_preserve_L_eq_tm  :\n  forall  φ h1 h2 ct cls F lo lo' o lb1 lx\n          t1 t2,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_tm t1 h1 t2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  flow_to lo lo' = true ->\n  L_equivalence_tm t1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                    t2 h2 φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo lo' o lb1 lx\n          t1 t2.\n  intros.\n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lb1 lx; auto.\n  apply  join_label_commutative; auto.\n  \n  assert (flow_to lo L_Label = false).\n  apply flow_transitive with (join_label lb1 lx); auto. \n\n  generalize dependent t2.  \n  induction t1; intros;inversion H2; subst; auto.\n\n  apply L_equivalence_tm_eq_object_L  with cls1 F1 lb0 cls2 F2 lb2; subst; auto.\n  apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h1; auto.\n  intro contra. rewrite contra in H11. rewrite <- H11 in H3. inversion H3; subst; auto.\n  try (inconsist_label).\n\n  case_eq (beq_oid o0 o); intro.\n  apply beq_oid_equal in H9. subst; auto.\n  rewrite <- H10 in H3; inversion H3; subst; auto. \n  apply L_equivalence_tm_eq_object_H  with cls1 cls2 F1 lo' F2 lb2; subst; auto.\n  apply lookup_updated with h1 ((Heap_OBJ cls1 F1 lb0) ); auto.\n  apply flow_transitive with lb0; auto. \n\n  apply L_equivalence_tm_eq_object_H  with cls1 cls2  F1 lb0  F2 lb2; subst; auto.\n  apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h1; auto.\n  intro contra.  rewrite contra in H9. pose proof (beq_oid_same o).\n  rewrite H9 in H14; inversion H14. \nQed. Hint Resolve  change_obj_lbl_h1_preserve_L_eq_tm.\n\n\n\n\nLemma change_obj_lbl_h2_preserve_L_eq_tm :\n  forall φ h1 h2 ct cls F lo lo' o lb1 lx\n          t1 t2,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_tm t1 h1 t2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n  flow_to (join_label lb1 lx) lo  = true ->\n  flow_to lb1 L_Label = false ->\n  flow_to lo lo' = true ->\n  L_equivalence_tm t1 h1\n                    t2 (update_heap_obj h2 o (Heap_OBJ cls F lo')) φ.\nProof with eauto. \n  intros  φ h1 h2 ct cls F lo lo' o lb1 lx\n          t1 t2.\n  intros.\n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lb1 lx; auto.\n  apply  join_label_commutative; auto.\n\n  assert (flow_to lo L_Label = false).\n  apply flow_transitive with (join_label lb1 lx); auto. \n\n  generalize dependent t2.  \n  induction t1; intros;inversion H2; subst; auto.\n\n  apply L_equivalence_tm_eq_object_L  with cls1 F1 lb0 cls2 F2 lb2; subst; auto.\n  apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h2; auto.\n  intro contra. rewrite contra in H13. rewrite <- H13 in H3. inversion H3; subst; auto.\n  try (inconsist_label).\n\n  case_eq (beq_oid o2 o); intro.\n  apply beq_oid_equal in H9. subst; auto.\n  rewrite <- H12 in H3; inversion H3; subst; auto. \n  apply L_equivalence_tm_eq_object_H  with cls1 cls2 F1 lb0 F2 lo'; subst; auto.\n  apply lookup_updated with h2 ((Heap_OBJ cls2 F2 lb2) ); auto.\n  apply flow_transitive with lb2; auto. \n\n  apply L_equivalence_tm_eq_object_H  with cls1 cls2 F1 lb0 F2 lb2; subst; auto.\n  apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h2; auto.\n  intro contra.  rewrite contra in H9. pose proof (beq_oid_same o).\n  rewrite H9 in H14; inversion H14. \nQed. Hint Resolve change_obj_lbl_h2_preserve_L_eq_tm.\n\n\nLemma change_obj_lbl_h1_preserve_L_eq_fs  :\n  forall   φ h1 h2 ct cls F lo lo' o lb1 lx\n           fs1 fs2,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_fs fs1 h1 fs2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  flow_to lo lo' = true ->\n  L_equivalence_fs fs1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                    fs2 h2 φ.\nProof with eauto. \n  intros  φ h1 h2 ct cls F lo lo' o lb1 lx\n           fs1 fs2.\n  intros.\n  generalize dependent fs2.\n  induction fs1; intros; inversion H2; subst; auto.\n\n  apply L_equal_fs; auto.\n  eauto using change_obj_lbl_h1_preserve_L_eq_tm.\nQed. Hint Resolve change_obj_lbl_h1_preserve_L_eq_fs.\n\n\nLemma change_obj_lbl_h2_preserve_L_eq_fs  :\n  forall  φ h1 h2 ct cls F lo lo' o lb1 lx\n           fs1 fs2 ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_fs fs1 h1 fs2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  flow_to lo lo' = true ->\n  L_equivalence_fs fs1 h1\n                    fs2 (update_heap_obj h2 o (Heap_OBJ cls F lo')) φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo lo' o lb1 lx\n           fs1 fs2.\n  intros.\n  generalize dependent fs2.\n  induction fs1; intros; inversion H2; subst; auto.\n\n  apply L_equal_fs; auto.\n  eauto using change_obj_lbl_h2_preserve_L_eq_tm.\nQed. Hint Resolve change_obj_lbl_h2_preserve_L_eq_fs.\n\n\nLemma  change_obj_lbl_h1_preserve_L_eq_store  :\n  forall  φ h1 h2 ct cls F lo lo' o lb1 lx\n          sf1 sf2 ,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_store sf1 h1 sf2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  flow_to lo lo' = true ->\n  L_equivalence_store sf1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                    sf2 h2 φ.\nProof with eauto.\n  intros   φ h1 h2 ct cls F lo lo' o lb1 lx\n          sf1 sf2.\n  intros.\n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lb1 lx; auto.\n  apply  join_label_commutative; auto.\n\n  assert (flow_to lo L_Label = false).\n  apply flow_transitive with (join_label lb1 lx); auto. \n\n  inversion H2; subst; auto. \n  apply L_equivalence_store_L; auto.\n  destruct H9.\n  split; auto; intros.\n  eauto using change_obj_lbl_h1_preserve_L_eq_tm.\nQed. Hint Resolve  change_obj_lbl_h1_preserve_L_eq_store.\n\n\n\nLemma  change_obj_lbl_h2_preserve_L_eq_store :\n  forall  φ h1 h2 ct cls F lo lo' o lb1 lx\n          sf1 sf2,\n  wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_equivalence_store sf1 h1 sf2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  flow_to lo lo' = true ->\n  L_equivalence_store sf1 h1\n                    sf2 (update_heap_obj h2 o (Heap_OBJ cls F lo')) φ.\nProof with eauto.\n  intros  φ h1 h2 ct cls F lo lo' o lb1 lx\n          sf1 sf2.\n  intros.\n  assert ( flow_to (join_label lb1 lx) L_Label = false).\n  apply flow_join_label with lb1 lx; auto.\n  apply  join_label_commutative; auto.\n\n  assert (flow_to lo L_Label = false).\n  apply flow_transitive with (join_label lb1 lx); auto. \n\n  inversion H2; subst; auto. \n  apply L_equivalence_store_L; auto.\n  intros.\n  destruct H9; auto.\n  split; auto.\n  intros.\n  eauto using change_obj_lbl_h2_preserve_L_eq_tm.\nQed. Hint Resolve  change_obj_lbl_h2_preserve_L_eq_store.\n    \n\n\n\nLemma change_obj_lbl_h1_preserve_L_eq_ctn :\n  forall  φ h1 h2 ct cls F lo lo' o lb1 lx\n          ctn1 ctn2 ,\n   wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_eq_container ctn1 h1 ctn2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to  (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  flow_to lo lo' = true ->\n  L_eq_container ctn1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                    ctn2 h2 φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo lo' o lb1 lx\n          ctn1 ctn2.\n  intros.\n  generalize dependent ctn2.\n  induction ctn1; intros; inversion H2; subst; auto.\n  apply  L_eq_ctn; auto.\n  eauto using change_obj_lbl_h1_preserve_L_eq_tm.\n  eauto using change_obj_lbl_h1_preserve_L_eq_fs.\n  eauto using change_obj_lbl_h1_preserve_L_eq_store.\nQed. Hint Resolve change_obj_lbl_h1_preserve_L_eq_ctn. \n\n\n\nLemma change_obj_lbl_h2_preserve_L_eq_ctn:\n  forall  φ h1 h2 ct cls F lo lo' o lb1 lx\n          ctn1 ctn2  ,\n   wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_eq_container ctn1 h1 ctn2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  flow_to lo lo' = true ->\n  L_eq_container ctn1 h1\n                    ctn2 (update_heap_obj h2 o (Heap_OBJ cls F lo')) φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo lo' o lb1 lx\n          ctn1 ctn2 .\n  intros.\n  generalize dependent ctn2.\n  induction ctn1; intros; inversion H2; subst; auto.\n  apply  L_eq_ctn; auto.\n  eauto using change_obj_lbl_h2_preserve_L_eq_tm.\n  eauto using change_obj_lbl_h2_preserve_L_eq_fs.\n  eauto using change_obj_lbl_h2_preserve_L_eq_store.\nQed. Hint Resolve change_obj_lbl_h2_preserve_L_eq_ctn.\n\n  \n\nLemma change_obj_lbl_h1_preserve_L_eq_ctns  :\n  forall  φ h1 h2 ct cls F lo lo' o lb1 lx\n          ctns1 ctns2 ,\n   wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_eq_ctns ctns1 h1 ctns2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n  flow_to (join_label lb1 lx) lo = true ->\n  flow_to lb1 L_Label = false ->\n  flow_to lo lo' = true ->\n  L_eq_ctns ctns1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                    ctns2 h2 φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo lo' o lb1 lx\n          ctns1 ctns2.\n  intros.\n  generalize dependent ctns2.\n  induction ctns1; intros; inversion H2; subst; auto.\n  apply  L_eq_ctns_list; auto.\n  eauto using  change_obj_lbl_h2_preserve_L_eq_ctn.\nQed. Hint Resolve change_obj_lbl_h1_preserve_L_eq_ctns.\n\n\nLemma change_obj_lbl_h2_preserve_L_eq_ctns :\n  forall  φ h1 h2 ct cls F lo lo' o lb1 lx\n          ctns1 ctns2 ,\n   wfe_heap ct h2 ->  wfe_heap ct h1 -> \n  L_equivalence_heap h1 h2 φ ->\n  L_eq_ctns ctns1 h1 ctns2 h2 φ ->\n  Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n  flow_to (join_label lb1 lx) lo  = true ->\n  flow_to lb1 L_Label = false ->\n  flow_to lo lo' = true ->\n  L_eq_ctns ctns1 h1\n                    ctns2 (update_heap_obj h2 o (Heap_OBJ cls F lo')) φ.\nProof with eauto. \n  intros φ h1 h2 ct cls F lo lo' o lb1 lx\n          ctns1 ctns2.\n  intros.\n  generalize dependent ctns1.\n  induction ctns2; intros; inversion H2; subst; auto.\n  apply  L_eq_ctns_list; auto.\n  eauto using  change_obj_lbl_h2_preserve_L_eq_ctn.\nQed. Hint Resolve change_obj_lbl_h2_preserve_L_eq_ctns.\n\n\nLemma change_obj_lbl_h1_preserve_config_eq :\n  forall  φ h1 h2 ct cls F lo lo' o lb1 lx\n          ctn1 ctn2 ctns1 ctns2,\n    wfe_heap ct h2 ->  wfe_heap ct h1 -> \n    L_equivalence_heap h1 h2 φ ->\n    L_equivalence_config (Config ct ctn1 ctns1  h1)\n                         (Config ct ctn2 ctns2  h2) φ ->\n\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    flow_to  (join_label lb1 lx) lo = true ->\n    flow_to lb1 L_Label = false ->\n    flow_to lo lo' = true ->\n    L_equivalence_config\n      (Config ct ctn1 ctns1 (update_heap_obj h1 o (Heap_OBJ cls F lo')))\n      (Config ct ctn2 ctns2  h2)  φ.\nProof with eauto.\n  intros.\n  \n  remember (Config ct ctn1 ctns1 h1) as config1.\n  remember (Config ct ctn2 ctns2 h2) as config2.\n  generalize dependent ctn1. generalize dependent ctn2.\n  generalize dependent ctns1. generalize dependent ctns2. \n  induction H2; subst; intros; inversion Heqconfig1; inversion Heqconfig2; subst; auto.\n  apply L_equivalence_config_L; auto.\n  eauto using change_obj_lbl_h2_preserve_L_eq_ctn.\n  eauto using change_obj_lbl_h2_preserve_L_eq_ctns.\n\n  \n  induction ctns3. induction ctns0.\n  apply L_equivalence_config_H; auto.\n  unfold low_component.  \n  rewrite H2; rewrite H7.\n  apply L_equivalence_config_L; auto.\n  apply L_eq_ctn; auto.\n  apply L_equivalence_store_L; auto; intros; try (inversion H9).\n  split; auto.\n  intros; inversion H9.\n  split; auto. \n\n  apply L_equivalence_config_H; auto.\n  unfold low_component.  \n  rewrite H2; rewrite H7.\n  fold low_component.\n  unfold low_component  in H8.\n  rewrite H2 in H8. rewrite H7 in H8.\n  fold low_component  in H8.\n\n  assert (  L_equivalence_config\n    (Config ct (Container hole nil L_Label empty_stack_frame) nil\n       (update_heap_obj h1 o (Heap_OBJ cls F lo')))\n    (Config ct (Container hole nil L_Label empty_stack_frame) nil h1)  φ).\n  apply L_equivalence_config_L; auto.\n  apply L_eq_ctn; auto.\n  apply L_equivalence_store_L; auto; intros;\n    try (inversion H9).\n  intros. split; auto.\n  intros. inversion H9. \n  split; auto.  \n\n  \n  remember ((low_component ct a ctns0 h2)) as conf.\n  destruct conf. destruct c0. \n  assert (c = ct /\\ h = h2 /\\ flow_to l0 L_Label = true).\n  eauto using low_component_lead_to_L.\n  \n  destruct H10. destruct H11. subst; auto. \n  apply L_equivalence_config_L; auto.\n  apply change_obj_lbl_h1_preserve_L_eq_ctn with ct lo lb1 lx; auto. \n  inversion H8; subst;  auto. \n  try (inconsist_label).\n  inversion H8; subst;  auto.  \n  inversion H29; subst;  auto. \n  try (inconsist_label).\n  inversion H8. inversion H8. \n\n  + apply L_equivalence_config_H; auto.\n  remember (low_component ct (Container t1 fs1 lb0 sf1) (a :: ctns3) h1) as conf1.\n  remember ((low_component ct (Container t2 fs2 lb2 sf2) ctns0 h2)) as conf2.\n  destruct conf1. destruct conf2.\n  destruct c0. \n  assert (c = ct /\\ h = h1 /\\ flow_to l1 L_Label = true).\n  eauto using low_component_lead_to_L. \n\n  destruct c2. \n  assert (c1 = ct /\\ h0 = h2 /\\ flow_to l2 L_Label = true).\n  eauto using low_component_lead_to_L. \n  destruct H9. destruct H11.\n  destruct H10. destruct H13.     subst. auto.\n\n  assert (Config ct (Container t f l1 s) l (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n          = (low_component ct (Container t1 fs1 lb0 sf1) (a :: ctns3)\n                           (update_heap_obj h1 o (Heap_OBJ cls F lo')))\n         ).\n  apply low_component_irrelevant_to_heap with h1; auto.\n  rewrite <- H9. \n  apply  L_equivalence_config_L; auto.\n  \n  apply change_obj_lbl_h1_preserve_L_eq_ctn  with ct lo lb1 lx; auto.\n  inversion H8; subst; auto. \n  try (inconsist_label).\n  apply change_obj_lbl_h1_preserve_L_eq_ctns  with ct lo lb1 lx; auto.\n  inversion H8; subst; auto. \n  try (inconsist_label).\n  inversion H8.  inversion H8.\n  inversion H8. inversion H8. \nQed. Hint Resolve change_obj_lbl_h1_preserve_config_eq.\n\n\nLemma change_obj_lbl_h2_preserve_config_eq:\n  forall  φ h1 h2 ct cls F lo lo' o lb1 lx\n          ctn1 ctn2 ctns1 ctns2,\n    wfe_heap ct h2 ->  wfe_heap ct h1 -> \n    L_equivalence_heap h1 h2 φ ->\n    L_equivalence_config (Config ct ctn1 ctns1  h1)\n                         (Config ct ctn2 ctns2  h2) φ ->\n\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h2 o ->\n    flow_to  (join_label lb1 lx) lo = true ->\n    flow_to lb1 L_Label = false ->\n    flow_to lo lo' = true ->\n    L_equivalence_config\n      (Config ct ctn1 ctns1 h1)\n      (Config ct ctn2 ctns2  (update_heap_obj h2 o (Heap_OBJ cls F lo')))  φ.\nProof with eauto.\n  intros.\n  \n  remember (Config ct ctn1 ctns1 h1) as config1.\n  remember (Config ct ctn2 ctns2 h2) as config2.\n  generalize dependent ctn1. generalize dependent ctn2.\n  generalize dependent ctns1. generalize dependent ctns2. \n  induction H2; subst; intros; inversion Heqconfig1; inversion Heqconfig2; subst; auto.\n  apply L_equivalence_config_L; auto.\n  eauto using change_obj_lbl_h2_preserve_L_eq_ctn.\n  eauto using change_obj_lbl_h2_preserve_L_eq_ctns.\n\n  \n  induction ctns3. induction ctns0.\n  apply L_equivalence_config_H; auto.\n  unfold low_component.  \n  rewrite H2; rewrite H7.\n  apply L_equivalence_config_L; auto.\n  apply L_eq_ctn; auto.\n  apply L_equivalence_store_L; auto; intros; try (empty_sf).\n  split; auto.\n  intros; try (empty_sf).\n  split; auto. \n\n\n  apply L_equivalence_config_H; auto.\n  unfold low_component.  \n  rewrite H2; rewrite H7.\n  fold low_component.\n  unfold low_component  in H8.\n  rewrite H2 in H8. rewrite H7 in H8.\n  fold low_component  in H8.\n\n  \n  assert (  L_equivalence_config\n    (Config ct (Container hole nil L_Label empty_stack_frame) nil\n       h1 )\n    (Config ct (Container hole nil L_Label empty_stack_frame) nil\n    (update_heap_obj h2 o (Heap_OBJ cls F lo')))  φ).\n  apply L_equivalence_config_L; auto.\n  apply L_eq_ctn; auto.\n  apply L_equivalence_store_L; auto; intros; try (empty_sf).\n  split; auto.\n  intros; try (empty_sf).\n  split; auto. \n\n  \n  remember ((low_component ct a ctns0 h2)) as conf.\n  destruct conf. destruct c0. \n  assert (c = ct /\\ h = h2 /\\ flow_to l0 L_Label = true).\n  eauto using low_component_lead_to_L. \n  destruct H10. destruct H11. subst; auto.\n\n  assert (Config ct (Container t f l0 s) l\n                 (update_heap_obj h2 o (Heap_OBJ cls F lo')) \n          = (low_component ct a ctns0 (update_heap_obj h2 o (Heap_OBJ cls F lo')))).\n  apply low_component_irrelevant_to_heap with h2; auto. rewrite <- H10.  \n  apply L_equivalence_config_L; auto.\n  apply change_obj_lbl_h2_preserve_L_eq_ctn with ct lo lb1 lx; auto.\n  inversion H8; subst;  auto.  \n  try (inconsist_label).\n  inversion H8; subst;  auto.\n  apply change_obj_lbl_h2_preserve_L_eq_ctns with ct lo lb1 lx; auto.\n  try (inconsist_label).\n  inversion H8.\n  inversion H8. \n\n\n  + apply L_equivalence_config_H; auto.\n  remember (low_component ct (Container t1 fs1 lb0 sf1) (a :: ctns3) h1) as conf1.\n  remember ((low_component ct (Container t2 fs2 lb2 sf2) ctns0 h2)) as conf2.\n  destruct conf1. destruct conf2.\n  destruct c0. \n  assert (c = ct /\\ h = h1 /\\ flow_to l1 L_Label = true).\n  apply low_component_lead_to_L with t f s (Container t1 fs1 lb0 sf1) l (a :: ctns3)  ; auto. \n\n  destruct c2. \n  assert (c1 = ct /\\ h0 = h2 /\\ flow_to l2 L_Label = true).\n  eauto using low_component_lead_to_L.\n  destruct H9. destruct H11.\n  destruct H10. destruct H13.     subst; auto.\n  assert (Config ct (Container t0 f0 l2 s0) l0 (update_heap_obj h2 o (Heap_OBJ cls F lo'))\n          = (low_component ct (Container t2 fs2 lb2 sf2)  ctns0\n                           (update_heap_obj h2 o (Heap_OBJ cls F lo')))\n         ).\n  apply low_component_irrelevant_to_heap with h2; auto.  \n  rewrite <- H9.  \n  apply   L_equivalence_config_L; auto.\n  apply change_obj_lbl_h2_preserve_L_eq_ctn  with ct lo lb1 lx; auto.\n  inversion H8; subst; auto. \n  try (inconsist_label).\n  apply change_obj_lbl_h2_preserve_L_eq_ctns  with ct lo lb1 lx; auto.\n  inversion H8; subst; auto. \n  try (inconsist_label).\n  inversion H8.  inversion H8.\n  inversion H8. inversion H8. \nQed. Hint Resolve change_obj_lbl_h2_preserve_config_eq.\n\n\n  (* heap bijection preservation *)\nLemma change_obj_preserve_bijection : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n                                                 ,\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    exists φ', \n      L_equivalence_heap\n        (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n        (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ'.\n    \nProof with eauto.\n  intros ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0.\n  intros.   \n  inversion H6; subst; auto.\n  rewrite <- H16 in H4; inversion H4; subst; auto.\n  rewrite <- H18 in H5; inversion H5; subst; auto.\n\n  inversion H3; subst; auto.\n\n  case_eq (flow_to lo' L_Label); intro.\n  exists φ. apply  L_eq_heap; auto.\n  \n  - intros.\n    assert (L_equivalence_object o1 h1 o2 h2 φ) as H_eq_o1_o2.          \n    apply H13; auto. \n    inversion H_eq_o1_o2; subst; auto. \n    case_eq (beq_oid o1 o); intro.\n    apply beq_oid_equal in H30.\n    rewrite H30 in H25. rewrite <- H25 in H16. inversion H16; subst.\n    assert ( Some  (Heap_OBJ cls0 F0 lo')  =\n      lookup_heap_obj  (update_heap_obj h1 o (Heap_OBJ cls0 F0 lo'))  o).\n    apply lookup_updated with h1  (Heap_OBJ cls0 F0 lb4); auto.\n\n    case_eq (beq_oid o2 o0); intro.\n    apply beq_oid_equal in H31.\n    rewrite H31 in H26. rewrite <- H26 in H18; inversion H18; subst; auto.  \n\n    assert ( Some  (Heap_OBJ cls3 F3 lo')  =\n      lookup_heap_obj  (update_heap_obj h2 o0 (Heap_OBJ cls3 F3 lo'))  o0).\n    apply lookup_updated with h2  (Heap_OBJ cls3 F3 lb5); auto.\n    apply object_equal_L with lo' lo' cls0 cls3\n                              F0 F3\n                              ; auto.\n    destruct H29. destruct H32. destruct H33. \n    split; auto. split; auto.\n    split; auto. \n    intros.\n\n    destruct H34 with fname fo1 fo2; auto. rename x into cls_f1.\n    destruct H37 as [cls_f2]. destruct H37 as [lof1].\n    destruct H37 as [lof2]. destruct H37 as [FF1]. destruct H37 as [FF2].\n    destruct H37. destruct H38.  destruct H39. \n\n    (* fields are both L *)\n    case_eq (beq_oid fo1 o); intro.\n    apply beq_oid_equal in H40.\n    rewrite <- H40 in H25. \n    assert (Some (Heap_OBJ cls0 F0 lo')\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls0 F0 lo')) fo1).\n    apply lookup_updated with h1 (Heap_OBJ cls0 F0 lb4); auto.\n    rewrite H40; auto.\n\n    \n    case_eq (beq_oid fo2 o0); intro.\n    apply beq_oid_equal in H42.\n    rewrite <- H42 in H26. \n    assert (Some (Heap_OBJ cls3 F3 lo')\n            = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls3 F3 lo')) fo2).\n    apply lookup_updated with h2 (Heap_OBJ cls3 F3 lb5); auto.\n    rewrite H42. auto.\n    \n    exists cls0. exists cls3. exists lo'. exists lo'.\n    exists F0.\n    exists F3.\n    split; auto. split; auto.\n    subst; auto.\n\n    (* if fo1 = o, then fo2 must be equal to o2*)\n    subst; auto.\n    destruct H39. rewrite H29 in H24; inversion H24; subst; auto.\n    pose proof (beq_oid_same o0).\n    try (inconsist).\n\n    (* beq_oid fo1 o = false*)\n    subst; auto.\n    case_eq (beq_oid fo2 o0); intro.\n    \n    (* inconsist assumption *)\n    apply beq_oid_equal in H29.\n    subst; auto.\n    apply right_left in H15.\n    destruct H39. \n    apply right_left in H29.\n    rewrite H29 in H15.\n    inversion H15; subst; auto. \n    pose proof (beq_oid_same o).\n    try (inconsist).\n\n    (* beq_oid fo2 o0 = false*)\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls3 F0 lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls3 F0 lo')  h1; auto.\n    intro contra. rewrite contra in H40.\n    pose proof (beq_oid_same o). try (inconsist).\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls3 F3 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls3 F3 lo') h2; auto.\n    intro contra. rewrite contra in H29.\n    pose proof (beq_oid_same o0). try (inconsist).\n\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto.\n\n\n(* fields are both H *)\n    case_eq (beq_oid fo1 o); intro.\n    (*inconsistency fo1 and o cannot equal*)\n    apply beq_oid_equal in H40.\n    rewrite <- H40 in H25. \n    assert (Some (Heap_OBJ cls0 F0 lo')\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls0 F0 lo')) fo1).\n    apply lookup_updated with h1 (Heap_OBJ cls0 F0 lb4); auto.\n    rewrite H40. auto.\n    subst; auto.\n    rewrite H37 in H25; inversion H25; subst; auto.\n    destruct H39.\n    try (inconsist).\n    \n    case_eq (beq_oid fo2 o0); intro.\n    (*inconsistency fo2 and o0 cannot equal*)\n    apply beq_oid_equal in H41.\n    subst; auto. \n    rewrite H38 in H26; inversion H26; subst; auto.\n    destruct H39. try (inconsist).\n\n\n    (* fo1 <> o and fo2 <> o0 *)\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls0 F0 lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls0 F0 lo')  h1; auto.\n    intro contra. rewrite contra in H40.\n    pose proof (beq_oid_same o). try (inconsist).\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls3 F3 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls3 F3 lo')  h2; auto.\n    intro contra. rewrite contra in H41.\n    pose proof (beq_oid_same o0). try (inconsist).\n\n    \n    exists cls_f1. exists cls_f2. exists lof1. exists lof2.\n    exists FF1.\n    exists FF2.\n    split; auto.\n\n    assert (Some (Heap_OBJ cls3 F3 lb5) =\n           lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) o2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n    intro contra. rewrite contra in H31.\n    assert (beq_oid o0 o0 = true). apply beq_oid_same.\n    try (inconsist).\n    \n\n    (* (beq_oid o1 o) = true and beq_oid o2 o0 = false *)\n    apply object_equal_L with lo' lb5 cls0 cls3\n                              F0 F3 ; auto.   \n    destruct H29. destruct H33. destruct H34. \n    split; auto. split; auto.\n    split; auto.\n    \n    intros.\n    destruct H35 with fname fo1 fo2; auto. rename x into cls_f1.\n    destruct H38 as [cls_f2]. destruct H38 as [lof1].\n    destruct H38 as [lof2]. destruct H38 as [FF1]. destruct H38 as [FF2].\n    destruct H38.  destruct H39. \n\n    \n    (* fields are both L *)\n    case_eq (beq_oid fo1 o); intro.\n    apply beq_oid_equal in H41.\n    rewrite <- H41 in H25. \n    assert (Some (Heap_OBJ cls0 F0 lo')\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls0 F0 lo')) fo1).\n    apply lookup_updated with h1 (Heap_OBJ cls0 F0 lb4); auto.\n    rewrite H41; auto.\n    \n    case_eq (beq_oid fo2 o0); intro.\n    apply beq_oid_equal in H43.\n    assert (Some (Heap_OBJ cls2 F2 lo')\n            = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) fo2).\n    apply lookup_updated with h2  (Heap_OBJ cls_f2 FF2 lof2); auto.\n    rewrite H43. auto.\n    \n    exists cls0. exists cls2. exists lo'. exists lo'.\n    exists F0.\n    exists F2.\n    split; auto. split; auto.\n    subst; auto.\n\n    destruct H40. destruct H29.\n    rewrite H24 in H29. inversion H29. rewrite H43 in H31.\n    assert (beq_oid o0 o0 = true).\n    apply beq_oid_same.  try (inconsist).\n    rewrite H39 in H18. inversion H18; subst; auto.\n    destruct H29. try (inconsist).\n\n\n    (* beq_oid fo2 o0 = false \n       beq_oid o2 o0 = false\n       o = o1 \n       fo1 = o *)    \n    \n    (* if fo1 = o, then fo2 must be equal to o2*)\n    subst; auto.\n    destruct H40. destruct H29. rewrite H29 in H15; inversion H15; subst; auto.\n    pose proof (beq_oid_same o0).\n    try (inconsist).\n\n\n    rewrite H15 in H24; inversion H24; subst; auto. \n    pose proof (beq_oid_same o2).\n    try (inconsist).\n\n    (* beq_oid fo1 o = false*)\n    subst; auto.\n    case_eq (beq_oid fo2 o0); intro.\n    \n    (* inconsist assumption *)\n    apply beq_oid_equal in H29.\n    subst; auto.\n    apply right_left in H15.\n    destruct H40.\n    \n    destruct H29. \n    apply right_left in H29.\n    rewrite H29 in H15.\n    inversion H15; subst; auto. \n    pose proof (beq_oid_same o).\n    try (inconsist).\n\n    apply left_right in H15.\n    rewrite H24 in H15; inversion H15; subst; auto.\n    rewrite H39 in H18; inversion H18; subst; auto.\n    destruct H29; try (inconsist).\n\n    (* beq_oid fo2 o0 = false*)\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n    intro contra. rewrite contra in H29.\n    pose proof (beq_oid_same o0). try (inconsist).\n\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls3 F0 lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls3 F0 lo')  h1; auto.\n    intro contra. rewrite contra in H41.\n    pose proof (beq_oid_same o). try (inconsist).\n\n\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto.\n\n    (*beq_oid o1 o = false *)\n    \n    assert ( Some (Heap_OBJ cls0 F0 lb4)  =\n      lookup_heap_obj  (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo'))  o1).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo') h1; auto.\n    intro contra. rewrite contra in H30.\n    assert (beq_oid o o = true). apply beq_oid_same.\n    try (inconsist).\n\n    case_eq (beq_oid o2 o0); intro.\n    (* cannot happen *)\n    apply beq_oid_equal in H32.\n    subst; auto.\n    apply right_left in H15.\n    apply right_left in H24.\n    rewrite H24 in H15. inversion H15; subst; auto.\n    assert (beq_oid o o = true). apply beq_oid_same.\n    try (inconsist).\n\n    assert ( Some (Heap_OBJ cls3 F3 lb5)  =\n      lookup_heap_obj  (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo'))  o2).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n    intro contra. rewrite contra in H32.\n    pose proof (beq_oid_same o0). try (inconsist).\n\n\n    \n    apply object_equal_L with lb4 lb5 cls0 cls3\n                              F0 F3\n                              ; auto.\n    destruct H29. destruct H34. destruct H35. \n    split; auto. split; auto.\n    split; auto. \n    intros.\n\n    destruct H36 with fname fo1 fo2; auto. rename x into cls_f1.\n    destruct H39 as [cls_f2]. destruct H39 as [lof1].\n    destruct H39 as [lof2]. destruct H39 as [FF1]. destruct H39 as [FF2].\n    destruct H39. destruct H40.  destruct H41. \n\n    (* fields are both L *)\n    case_eq (beq_oid fo1 o); intro.\n    apply beq_oid_equal in H42.\n    subst; auto. \n    assert (Some (Heap_OBJ cls1 F1 lo')\n            = lookup_heap_obj (update_heap_obj h1 o  (Heap_OBJ cls1 F1 lo')) o).\n    apply lookup_updated with h1 (Heap_OBJ cls_f1 FF1 lof1); auto.\n    \n    case_eq (beq_oid fo2 o0); intro.\n    apply beq_oid_equal in H42.\n    subst; auto. \n    assert (Some (Heap_OBJ cls2 F2 lo')\n            = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) o0).\n    apply lookup_updated with h2 (Heap_OBJ cls2 F2 lb3); auto.\n    \n    exists cls1. exists cls2. exists lo'. exists lo'.\n    exists F1.\n    exists F2.\n    split; auto. split; auto.\n    left; auto. split; auto.\n    split; auto. split; auto.\n    rewrite H40 in H18; inversion H18; subst; auto.\n    rewrite H39 in H16; inversion H16; subst; auto.\n    apply H41. \n\n    (* beq_oid fo2 o0 = false*)\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls2 F2 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n    intro contra. rewrite contra in H42.\n    pose proof (beq_oid_same o0). try (inconsist).\n\n    exists cls1. exists cls_f2.\n    exists lo'. exists lof2.\n    exists F1. exists FF2.\n    split; auto. split; auto.\n    left; auto.\n    split; auto. apply H41.\n    split; auto. apply H41.\n    split; auto. rewrite H39 in H16;inversion H16; subst; auto.\n    apply H41.\n\n    (* beq_oid fo1 o = false *)\n    subst; auto.\n    case_eq (beq_oid fo2 o0); intro.\n    \n    (* inconsist assumption *)\n    apply beq_oid_equal in H29.\n    subst; auto.\n    apply right_left in H15.\n    destruct H41.\n     \n    apply right_left in H29.\n    rewrite H29 in H15.\n    inversion H15; subst; auto. \n    pose proof (beq_oid_same o).\n    try (inconsist).\n\n    (* beq_oid fo2 o0 = false*)\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n    intro contra. rewrite contra in H29.\n    pose proof (beq_oid_same o0). try (inconsist).\n\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo')  h1; auto.\n    intro contra. rewrite contra in H42.\n    pose proof (beq_oid_same o). try (inconsist).\n\n\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto.\n\n\n\n(* fields are both H *)\n    case_eq (beq_oid fo1 o); intro.\n    (*inconsistency fo1 and o cannot equal*)\n    apply beq_oid_equal in H42.\n    subst; auto.\n    rewrite H39 in H16; inversion H16; subst; auto.\n    destruct H41. try (inconsist).\n\n\n    (*beq_oid fo1 o = false *)\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo')  h1; auto.\n    intro contra. rewrite contra in H42.\n    pose proof (beq_oid_same o). try (inconsist).\n    \n    case_eq (beq_oid fo2 o0); intro.\n    (*inconsistency fo2 and o0 cannot equal*)\n    apply beq_oid_equal in H44.\n    subst; auto. \n    rewrite H40 in H18; inversion H18; subst; auto.\n    destruct H41. try (inconsist).\n\n    (* only the case fo1 <> o and fo2 <> o0 is feasible  *)\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls2 F2 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo')  h2; auto.\n    intro contra. rewrite contra in H44.\n    pose proof (beq_oid_same o0). try (inconsist).\n\n    \n    exists cls_f1. exists cls_f2. exists lof1. exists lof2.\n    exists FF1.\n    exists FF2.\n    split; auto.\n\n  - (* None -> left φ o1 = None *)\n    intros. apply lookup_updated_heap_must_none in H24.\n    apply H14 in H24. auto. \n\n  - (* o1 = None -> right φ o1 = None *)\n    intros. apply lookup_updated_heap_must_none in H24.\n    apply H19 in H24. auto.\n\n  - (* flow_to lb L_Label = false  *)\n    intros.\n    case_eq (beq_oid o1 o); intro.\n    assert ( Some (Heap_OBJ cls F lb) = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) o1 ). auto.\n    apply lookup_updated_heap_new_obj in H27; auto.\n    inversion H27; subst; auto.\n    try (inconsist).\n    \n    assert (Some (Heap_OBJ cls F lb) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) o1\n           ). auto.\n    apply lookup_updated_heap_old_obj in H27; auto.\n    assert ( lookup_heap_obj h1 o1 = Some (Heap_OBJ cls F lb) ); auto.\n    apply H21 in H28; auto. \n\n  - (*flow_to lb L_Label = false -> right φ o1 = None *)\n    intros.\n    case_eq (beq_oid o1 o0); intro.\n    assert ( Some (Heap_OBJ cls F lb) = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) o1 ). auto.\n    apply lookup_updated_heap_new_obj in H27; auto.\n    inversion H27; subst; auto.\n    try (inconsist).\n    \n    assert (Some (Heap_OBJ cls F lb) =\n            lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) o1\n           ). auto.\n    apply lookup_updated_heap_old_obj in H27; auto.\n    assert ( lookup_heap_obj h2 o1 = Some (Heap_OBJ cls F lb) ); auto.\n    apply H22 in H28; auto.\n\n  - (*flow_to lo' L_Label = false *)\n\n    \n    assert (L_equivalence_object o h1 o0 h2 φ) as H_eq_o1_o2.          \n    apply H13; auto. \n    inversion H_eq_o1_o2; subst; auto.\n    assert (forall a1 a2 : oid, Decision (a1 = a2)) as H_d_oid.\n    auto. \n    \n    remember (reduce_bijection φ o o0 H15) as φ'.\n    exists φ'.\n    apply L_eq_heap; auto.\n\n    + intros.\n      case_eq (beq_oid o1 o); intro.\n      (* cannot happen *)\n      apply beq_oid_equal in H30. subst; auto. \n      assert (left (reduce_bijection φ o o0 H15) o = None). apply reduce_bijection_lookup_eq_left; auto.\n      rewrite H30 in H29; inversion H29.\n\n      (* o1 <> o *)\n      Lemma beq_oid_false_mark : forall o1 o2,\n          beq_oid o1 o2 = false -> o1 <> o2.\n      Proof with eauto.\n        intros.\n        intro contra. subst; auto. assert (beq_oid o2 o2 = true).\n        apply beq_oid_same. try (inconsist).\n      Qed. Hint Resolve beq_oid_false_mark.\n\n      apply beq_oid_false_mark in H30.\n      assert (left (reduce_bijection φ o o0 H15) o1 = left φ o1).\n      apply reduce_bijection_lookup_neq_left. auto.\n      \n      subst; auto. assert (left φ o1 = Some o2). rewrite <- H31.  rewrite H29. auto.\n\n      case_eq (beq_oid o2 o0); intro.\n      apply beq_oid_equal in H33. subst; auto.\n      assert (left φ o = Some o0). auto. \n      apply right_left in H32. apply right_left in H33.\n      rewrite H32 in H33. inversion H33. \n\n      rewrite H35 in H30; try (contradiction).\n      \n      apply H13 in H32. inversion H32; subst; auto.       \n    \n      assert ( Some  (Heap_OBJ cls4 F4 lb6)  =\n      lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo'))  o1).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo')  h1; auto.\n\n      \n      assert ( Some (Heap_OBJ cls5 F5 lb7)  =\n      lookup_heap_obj  (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo'))  o2).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo')  h2; auto.\n      apply object_equal_L with lb6 lb7 cls4 cls5\n                              F4 F5\n      ; auto.\n      destruct H38. destruct H41. destruct H42. \n      split; auto. split; auto.\n      split; auto. \n      intros.\n\n      destruct H43 with fname fo1 fo2; auto. rename x into cls_f1.\n      destruct H46 as [cls_f2]. destruct H46 as [lof1].\n      destruct H46 as [lof2]. destruct H46 as [FF1]. destruct H46 as [FF2].\n      destruct H46. destruct H47.  destruct H48. \n\n\n      (* fields are both L *)\n      case_eq (beq_oid fo1 o); intro.\n      apply beq_oid_equal in H49.\n      assert (fo2 = o0).\n      destruct H48. assert (left φ o = Some o0); auto.\n      subst; auto. rewrite H48 in H51; inversion H51; subst; auto. \n      assert (Some (Heap_OBJ cls1 F1 lo')\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) fo1).\n      apply lookup_updated with h1 (Heap_OBJ cls_f1 FF1 lof1); auto.\n      rewrite H49; auto.\n\n      assert (Some (Heap_OBJ cls2 F2 lo')\n            = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) fo2).\n      apply lookup_updated with h2 (Heap_OBJ cls_f2 FF2 lof2); auto.\n      rewrite H50. auto.\n\n      exists cls1. exists cls2. exists lo'. exists lo'.\n      exists F1.\n      exists F2.\n\n      split; auto. \n\n      (* beq_oid fo1 o = false*)\n      subst; auto.\n      assert (fo2 <> o0).\n      intro contra. subst; auto.\n      destruct H48.\n      assert (left φ o = Some o0). auto.\n      apply right_left in H38.\n      apply right_left in H50. rewrite H50 in H38; inversion H38; subst; auto.\n      assert (beq_oid fo1 fo1 = true). apply beq_oid_same. try (inconsist).\n      apply beq_oid_not_equal in H38. \n\n    (* beq_oid fo2 o0 = false*)\n      assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo')  h1; auto.\n \n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0   (Heap_OBJ cls2 F2 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0  (Heap_OBJ cls2 F2 lo') h2; auto.\n\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto. split; auto. left; auto.\n    destruct H48. \n\n    assert (left (reduce_bijection φ o o0 H15) fo1 = left φ fo1).\n    apply reduce_bijection_lookup_neq_left.\n    intro contra. \n    rewrite contra in H49.\n    assert (beq_oid fo1 fo1 = true).\n    apply beq_oid_same. try (inconsist).\n    split; auto. rewrite <- H53 in H48; auto. \n\n(* fields are both H *)\n    case_eq (beq_oid fo1 o); intro.\n    (*inconsistency fo1 and o cannot equal*)\n    apply beq_oid_equal in H49.\n    rewrite <- H49 in H24.\n    rewrite H46 in H24; inversion H24; subst; auto.\n    destruct H48. try (inconsist).\n\n    assert (fo2 <> o0).\n    intro contra. subst; auto.\n    rewrite H47 in H25; inversion H25; subst; auto.\n    destruct H48. try (inconsist).\n    apply beq_oid_not_equal in H50. \n\n\n    (* fo1 <> o and fo2 <> o0 *)\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo')  h1; auto.\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls2 F2 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo')  h2; auto.\n    \n    exists cls_f1. exists cls_f2. exists lof1. exists lof2.\n    exists FF1.\n    exists FF2.\n    split; auto.\n\n\n    +   (* None -> left φ o1 = None *)\n    intros. apply lookup_updated_heap_must_none in H29.\n    apply H14 in H29. subst; auto.\n    case_eq (beq_oid o o1); intro.\n    ++ apply beq_oid_equal in H30.  subst; auto.\n       apply reduce_bijection_lookup_eq_left.\n    ++ apply beq_oid_false_mark in H30.\n       assert (left (reduce_bijection φ o o0 H15) o1 = left φ o1).\n       apply reduce_bijection_lookup_neq_left; auto.\n       rewrite H31. rewrite H29.\n       auto. \n      \n    + (* o1 = None -> right φ o1 = None *)\n    intros. apply lookup_updated_heap_must_none in H29.\n    apply H19 in H29.\n    case_eq (beq_oid o0 o1); intro.\n    ++ apply beq_oid_equal in H30.  subst; auto.\n       apply reduce_bijection_lookup_eq_right.\n    ++ apply beq_oid_false_mark in H30.\n       assert (right (reduce_bijection φ o o0 H15) o1 = right φ o1).\n       apply reduce_bijection_lookup_neq_right; auto.\n       subst; auto. \n       rewrite H31. rewrite H29.\n       auto. \n\n    + (* flow_to lb L_Label = false  *)\n    intros.\n    case_eq (beq_oid o1 o); intro.\n    ++ apply beq_oid_equal in H31. subst; auto.\n       apply reduce_bijection_lookup_eq_left.\n    ++ \n    assert ( Some (Heap_OBJ cls F lb) = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) o1 ). auto.\n    apply lookup_updated_heap_old_obj in H32; auto.\n    assert (left φ o1 = None). \n    apply H21 with cls F lb; auto.\n    assert (left (reduce_bijection φ o o0 H15) o1 = left φ o1).\n    apply reduce_bijection_lookup_neq_left; auto.\n    intro contra. subst; auto. assert (beq_oid o1 o1 = true). apply beq_oid_same. try (inconsist).\n    subst; auto. \n    rewrite H34. auto. \n\n  + (*flow_to lb L_Label = false -> right φ o1 = None *)\n    intros.\n    case_eq (beq_oid o1 o0); intro.\n    ++ apply beq_oid_equal in H31; subst; auto.\n       apply reduce_bijection_lookup_eq_right.\n    ++ \n    assert ( Some (Heap_OBJ cls F lb) = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) o1); auto. \n    apply lookup_updated_heap_old_obj in H32; auto.\n    assert (right φ o1 = None). \n    apply H22 with cls F lb; auto.\n    assert (right (reduce_bijection φ o o0 H15) o1 = right φ o1).\n    apply reduce_bijection_lookup_neq_right; auto.\n    intro contra. subst; auto. assert (beq_oid o1 o1 = true). apply beq_oid_same. try (inconsist).\n    subst; auto. \n    rewrite H34. auto. \n\n  - (*flow_to lo' L_Label = false *)    \n   (* object with h label *)\n    exists φ.\n    intros.\n    rewrite <- H15 in H4; inversion H4; subst; auto.\n    rewrite <- H17 in H5; inversion H5; subst; auto.\n\n    inversion H3; subst; auto. \n    apply  L_eq_heap; auto.\n    + intros. assert ( L_equivalence_object o1 h1 o2 h2 φ). \n      apply H13. auto.  inversion H23; subst; auto.\n      case_eq (beq_oid o1 o); intro.\n      (*impossible*)\n      apply beq_oid_equal in H29.\n      rewrite H29 in H24.\n      rewrite <- H24 in H15; inversion H15; subst; auto.\n      try (inconsist).\n\n      case_eq (beq_oid o2 o0); intro.\n      apply beq_oid_equal in H30.\n      rewrite H30 in H25.\n      rewrite <- H25 in H17; inversion H17; subst; auto.\n      try (inconsist).\n\n      assert (Some (Heap_OBJ cls0 F0 lb4) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) o1\n           ).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo')  h1; auto.\n\n      assert (Some (Heap_OBJ cls3 F3 lb5) =\n            lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) o2\n             ).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo')  h2; auto.\n\n      apply object_equal_L with lb4 lb5 cls0 cls3 F0 F3; auto.\n\n      destruct H28. destruct H33. destruct H34. \n      split; auto. split; auto. split; auto.\n      intros.\n      destruct H35 with fname fo1 fo2; auto.\n      destruct H38 as [cls_f2]. rename x into cls_f1.\n      destruct H38 as [lof1]. destruct H38 as [lof2].\n      destruct H38 as [FF1]. destruct H38 as [FF2].\n      destruct H38.  destruct H39.\n\n      destruct H40.\n      ++ destruct H40.\n      assert (L_equivalence_object fo1 h1 fo2 h2 φ).\n      apply H13; auto. \n      inversion H42; subst; auto.\n\n      case_eq (beq_oid fo1 o); intro.\n      apply beq_oid_equal in H28.\n      rewrite H28 in H43. rewrite <- H43 in H15; inversion H15; subst; auto.\n      try (inconsist).\n    \n      case_eq (beq_oid fo2 o0); intro.\n      apply beq_oid_equal in H48.\n      rewrite H48 in H44. rewrite <- H44 in H17; inversion H17; subst; auto.\n      try (inconsist).\n\n      assert (Some  (Heap_OBJ cls4 F4 lb6) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) fo1\n             ).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo')  h1; auto.\n      \n      assert (Some  (Heap_OBJ cls5 F5 lb7) =\n           lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) fo2\n           ).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n      \n\n      exists cls4. exists cls5.\n      exists lb6. exists lb7.\n      exists F4. exists F5. \n      split; auto.\n      split; auto.\n      left; auto.\n      split; auto.  split; auto. split; auto. apply H47.\n\n      ++ \n      subst; auto.\n      case_eq (beq_oid fo1 o); intro.\n      apply beq_oid_equal in H28.\n      subst; auto.\n      assert (Some (Heap_OBJ cls1 F1 lo')  =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) o).\n      apply lookup_updated with h1 (Heap_OBJ cls_f1 FF1 lof1); auto.\n\n      case_eq (beq_oid fo2 o0); intro.\n      apply beq_oid_equal in H41.      \n      subst; auto. \n      assert (Some (Heap_OBJ cls2 F2 lo')  =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) o0).\n      apply lookup_updated with h2 (Heap_OBJ cls_f2 FF2 lof2); auto.\n      \n      exists cls1. exists cls2.\n      exists lo'. exists lo'.\n      exists F1. exists F2.\n      split; auto.\n      split; auto.\n      assert (flow_to lo' L_Label = false).\n      apply flow_transitive with lb0; auto. \n      right. split ; auto.\n\n\n      assert (Some (Heap_OBJ cls_f2 FF2 lof2)  =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) fo2).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n      \n      exists cls1. exists cls_f2.\n      exists lo'. exists lof2.\n      exists F1. exists FF2.\n      split; auto. split; auto.\n      assert (flow_to lo' L_Label = false).\n      apply flow_transitive with lb0; auto. \n      right. split; auto. apply H40. \n       \n      \n      case_eq (beq_oid fo2 o0); intro.\n      apply beq_oid_equal in H41.      \n      subst; auto. \n      assert (Some (Heap_OBJ cls2 F2 lo')  =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) o0).\n      apply lookup_updated with h2 (Heap_OBJ cls_f2 FF2 lof2); auto.\n\n\n      assert (Some  (Heap_OBJ cls_f1 FF1 lof1) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) fo1).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo') h1; auto.\n      \n      exists cls_f1. exists cls2.\n      exists lof1. exists lo'.\n      exists FF1. exists F2.\n      split; auto. split; auto.\n      assert (flow_to lo' L_Label = false).\n      apply flow_transitive with lb0; auto. \n      right; auto.  split; auto. apply H40. \n\n\n      assert (Some (Heap_OBJ cls_f2 FF2 lof2)  =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) fo2).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n      \n      assert (Some  (Heap_OBJ cls_f1 FF1 lof1) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) fo1).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo') h1; auto.\n      \n      exists cls_f1. exists cls_f2.\n      exists lof1. exists lof2.\n      exists FF1. exists FF2.\n      split; auto. \n    + intros.\n      apply lookup_updated_heap_must_none in H22.\n      apply H14 in H22. auto. \n\n    + intros. \n      apply lookup_updated_heap_must_none in H22.\n      apply H18 in H22. auto.\n\n    + intros.\n      case_eq (beq_oid o1 o); intro.\n      apply  beq_oid_equal in H24.\n      rewrite <- H24 in H15.\n      destruct H20 with o1 cls1 F1 lb0; auto.\n\n      assert (Some (Heap_OBJ cls F lb) =\n              lookup_heap_obj h1 o1\n             ).\n      apply lookup_updated_heap_old_obj with  cls1 F1 lo' o; auto.\n      destruct H20 with o1 cls F lb; auto. \n\n    + intros.\n      case_eq (beq_oid o1 o0); intro.\n      apply  beq_oid_equal in H24.\n      rewrite <- H24 in H17.\n      destruct H21 with o1 cls2 F2 lb3; auto.\n\n      assert (Some (Heap_OBJ cls F lb) =\n              lookup_heap_obj h2 o1\n             ).\n      apply lookup_updated_heap_old_obj with  cls2 F2 lo' o0; auto.\n      destruct H21 with o1 cls F lb; auto. \nQed. Hint Resolve change_obj_preserve_bijection. \n\n\n\n\n\n\n\n  (* heap bijection preservation *)\nLemma lbl_L_change_obj_both_lbl_preserve_bijection : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0 ,\n    flow_to lo' L_Label = true ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n      L_equivalence_heap\n        (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n        (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ.\n    \nProof with eauto.\n  intros ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0.\n  intros.   \n  inversion H7; subst; auto.\n  rewrite <- H17 in H5; inversion H5; subst; auto.\n  rewrite <- H19 in H6; inversion H6; subst; auto.\n\n  inversion H4; subst; auto.\n  apply  L_eq_heap; auto.\n  \n  - intros.\n    assert (L_equivalence_object o1 h1 o2 h2 φ) as H_eq_o1_o2.          \n    apply H14; auto. \n    inversion H_eq_o1_o2; subst; auto. \n    case_eq (beq_oid o1 o); intro.\n    apply beq_oid_equal in H30.\n    rewrite H30 in H25. rewrite <- H25 in H17. inversion H17; subst.\n    assert ( Some  (Heap_OBJ cls0 F0 lo')  =\n      lookup_heap_obj  (update_heap_obj h1 o (Heap_OBJ cls0 F0 lo'))  o).\n    apply lookup_updated with h1  (Heap_OBJ cls0 F0 lb4); auto.\n\n    case_eq (beq_oid o2 o0); intro.\n    apply beq_oid_equal in H31.\n    rewrite H31 in H26. rewrite <- H26 in H19; inversion H19; subst; auto.  \n\n    assert ( Some  (Heap_OBJ cls3 F3 lo')  =\n      lookup_heap_obj  (update_heap_obj h2 o0 (Heap_OBJ cls3 F3 lo'))  o0).\n    apply lookup_updated with h2  (Heap_OBJ cls3 F3 lb5); auto.\n    apply object_equal_L with lo' lo' cls0 cls3\n                              F0 F3\n                              ; auto.\n    destruct H29. destruct H32. destruct H33. \n    split; auto. split; auto.\n    split; auto. \n    intros.\n\n    destruct H34 with fname fo1 fo2; auto. rename x into cls_f1.\n    destruct H37 as [cls_f2]. destruct H37 as [lof1].\n    destruct H37 as [lof2]. destruct H37 as [FF1]. destruct H37 as [FF2].\n    destruct H37. destruct H38.  destruct H39. \n\n    (* fields are both L *)\n    case_eq (beq_oid fo1 o); intro.\n    apply beq_oid_equal in H40.\n    rewrite <- H40 in H25. \n    assert (Some (Heap_OBJ cls0 F0 lo')\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls0 F0 lo')) fo1).\n    apply lookup_updated with h1 (Heap_OBJ cls0 F0 lb4); auto.\n    rewrite H40; auto.\n\n    \n    case_eq (beq_oid fo2 o0); intro.\n    apply beq_oid_equal in H42.\n    rewrite <- H42 in H26. \n    assert (Some (Heap_OBJ cls3 F3 lo')\n            = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls3 F3 lo')) fo2).\n    apply lookup_updated with h2 (Heap_OBJ cls3 F3 lb5); auto.\n    rewrite H42. auto.\n    \n    exists cls0. exists cls3. exists lo'. exists lo'.\n    exists F0.\n    exists F3.\n    split; auto. split; auto.\n    subst; auto.\n\n    (* if fo1 = o, then fo2 must be equal to o2*)\n    subst; auto.\n    destruct H39. rewrite H29 in H24; inversion H24; subst; auto.\n    pose proof (beq_oid_same o0).\n    try (inconsist).\n\n    (* beq_oid fo1 o = false*)\n    subst; auto.\n    case_eq (beq_oid fo2 o0); intro.\n    \n    (* inconsist assumption *)\n    apply beq_oid_equal in H29.\n    subst; auto.\n    apply right_left in H16.\n    destruct H39. \n    apply right_left in H29.\n    rewrite H29 in H16.\n    inversion H16; subst; auto. \n    pose proof (beq_oid_same o).\n    try (inconsist).\n\n    (* beq_oid fo2 o0 = false*)\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls3 F0 lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls3 F0 lo')  h1; auto.\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls3 F3 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls3 F3 lo') h2; auto.\n\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto.\n\n\n(* fields are both H *)\n    case_eq (beq_oid fo1 o); intro.\n    (*inconsistency fo1 and o cannot equal*)\n    apply beq_oid_equal in H40.\n    rewrite <- H40 in H25. \n    assert (Some (Heap_OBJ cls0 F0 lo')\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls0 F0 lo')) fo1).\n    apply lookup_updated with h1 (Heap_OBJ cls0 F0 lb4); auto.\n    rewrite H40. auto.\n    subst; auto.\n    rewrite H37 in H25; inversion H25; subst; auto.\n    destruct H39.\n    try (inconsist).\n    \n    case_eq (beq_oid fo2 o0); intro.\n    (*inconsistency fo2 and o0 cannot equal*)\n    apply beq_oid_equal in H41.\n    subst; auto. \n    rewrite H38 in H26; inversion H26; subst; auto.\n    destruct H39. try (inconsist).\n\n\n    (* fo1 <> o and fo2 <> o0 *)\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls0 F0 lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls0 F0 lo')  h1; auto.\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls3 F3 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls3 F3 lo')  h2; auto.\n\n    \n    exists cls_f1. exists cls_f2. exists lof1. exists lof2.\n    exists FF1.\n    exists FF2.\n    split; auto.\n\n    assert (Some (Heap_OBJ cls3 F3 lb5) =\n           lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) o2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n    \n\n    (* (beq_oid o1 o) = true and beq_oid o2 o0 = false *)\n    apply object_equal_L with lo' lb5 cls0 cls3\n                              F0 F3 ; auto.   \n    destruct H29. destruct H33. destruct H34. \n    split; auto. split; auto.\n    split; auto.\n    \n    intros.\n    destruct H35 with fname fo1 fo2; auto. rename x into cls_f1.\n    destruct H38 as [cls_f2]. destruct H38 as [lof1].\n    destruct H38 as [lof2]. destruct H38 as [FF1]. destruct H38 as [FF2].\n    destruct H38.  destruct H39. \n\n    \n    (* fields are both L *)\n    case_eq (beq_oid fo1 o); intro.\n    apply beq_oid_equal in H41.\n    rewrite <- H41 in H25. \n    assert (Some (Heap_OBJ cls0 F0 lo')\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls0 F0 lo')) fo1).\n    apply lookup_updated with h1 (Heap_OBJ cls0 F0 lb4); auto.\n    rewrite H41; auto.\n    \n    case_eq (beq_oid fo2 o0); intro.\n    apply beq_oid_equal in H43.\n    assert (Some (Heap_OBJ cls2 F2 lo')\n            = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) fo2).\n    apply lookup_updated with h2  (Heap_OBJ cls_f2 FF2 lof2); auto.\n    rewrite H43. auto.\n    \n    exists cls0. exists cls2. exists lo'. exists lo'.\n    exists F0.\n    exists F2.\n    split; auto. split; auto.\n    subst; auto.\n\n    destruct H40. destruct H29.\n    rewrite H24 in H29. inversion H29. rewrite H43 in H31.\n    assert (beq_oid o0 o0 = true).\n    apply beq_oid_same.  try (inconsist).\n    rewrite H39 in H19. inversion H19; subst; auto.\n    destruct H29. try (inconsist).\n\n\n    (* beq_oid fo2 o0 = false \n       beq_oid o2 o0 = false\n       o = o1 \n       fo1 = o *)    \n    \n    (* if fo1 = o, then fo2 must be equal to o2*)\n    subst; auto.\n    destruct H40. destruct H29. rewrite H29 in H16; inversion H16; subst; auto.\n    pose proof (beq_oid_same o0).\n    try (inconsist).\n\n\n    rewrite H16 in H24; inversion H24; subst; auto. \n    pose proof (beq_oid_same o2).\n    try (inconsist).\n\n    (* beq_oid fo1 o = false*)\n    subst; auto.\n    case_eq (beq_oid fo2 o0); intro.\n    \n    (* inconsist assumption *)\n    apply beq_oid_equal in H29.\n    subst; auto.\n    apply right_left in H16.\n    destruct H40.\n    \n    destruct H29. \n    apply right_left in H29.\n    rewrite H29 in H16.\n    inversion H16; subst; auto. \n    pose proof (beq_oid_same o).\n    try (inconsist).\n\n    apply left_right in H16.\n    rewrite H24 in H16; inversion H16; subst; auto.\n    rewrite H39 in H19; inversion H19; subst; auto.\n    destruct H29; try (inconsist).\n\n    (* beq_oid fo2 o0 = false*)\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n    \n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls3 F0 lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls3 F0 lo')  h1; auto.\n    \n\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto.\n\n    (*beq_oid o1 o = false *)\n    \n    assert ( Some (Heap_OBJ cls0 F0 lb4)  =\n      lookup_heap_obj  (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo'))  o1).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo') h1; auto.\n\n    case_eq (beq_oid o2 o0); intro.\n    (* cannot happen *)\n    apply beq_oid_equal in H32.\n    subst; auto.\n    apply right_left in H16.\n    apply right_left in H24.\n    rewrite H24 in H16. inversion H16; subst; auto.\n    assert (beq_oid o o = true). apply beq_oid_same.\n    try (inconsist).\n\n    assert ( Some (Heap_OBJ cls3 F3 lb5)  =\n      lookup_heap_obj  (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo'))  o2).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n\n\n    \n    apply object_equal_L with lb4 lb5 cls0 cls3\n                              F0 F3\n                              ; auto.\n    destruct H29. destruct H34. destruct H35. \n    split; auto. split; auto.\n    split; auto. \n    intros.\n\n    destruct H36 with fname fo1 fo2; auto. rename x into cls_f1.\n    destruct H39 as [cls_f2]. destruct H39 as [lof1].\n    destruct H39 as [lof2]. destruct H39 as [FF1]. destruct H39 as [FF2].\n    destruct H39. destruct H40.  destruct H41. \n\n    (* fields are both L *)\n    case_eq (beq_oid fo1 o); intro.\n    apply beq_oid_equal in H42.\n    subst; auto. \n    assert (Some (Heap_OBJ cls1 F1 lo')\n            = lookup_heap_obj (update_heap_obj h1 o  (Heap_OBJ cls1 F1 lo')) o).\n    apply lookup_updated with h1 (Heap_OBJ cls_f1 FF1 lof1); auto.\n    \n    case_eq (beq_oid fo2 o0); intro.\n    apply beq_oid_equal in H42.\n    subst; auto. \n    assert (Some (Heap_OBJ cls2 F2 lo')\n            = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) o0).\n    apply lookup_updated with h2 (Heap_OBJ cls2 F2 lb3); auto.\n    \n    exists cls1. exists cls2. exists lo'. exists lo'.\n    exists F1.\n    exists F2.\n    split; auto. split; auto.\n    left; auto. split; auto.\n    split; auto. split; auto.\n    rewrite H40 in H19; inversion H19; subst; auto.\n    rewrite H39 in H17; inversion H17; subst; auto.\n    apply H41. \n\n    (* beq_oid fo2 o0 = false*)\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls2 F2 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n    \n    exists cls1. exists cls_f2.\n    exists lo'. exists lof2.\n    exists F1. exists FF2.\n    split; auto. split; auto.\n    left; auto.\n    split; auto. apply H41.\n    split; auto. apply H41.\n    split; auto. rewrite H39 in H17;inversion H17; subst; auto.\n    apply H41.\n\n    (* beq_oid fo1 o = false *)\n    subst; auto.\n    case_eq (beq_oid fo2 o0); intro.\n    \n    (* inconsist assumption *)\n    apply beq_oid_equal in H29.\n    subst; auto.\n    apply right_left in H16.\n    destruct H41.\n     \n    apply right_left in H29.\n    rewrite H29 in H16.\n    inversion H16; subst; auto. \n    pose proof (beq_oid_same o).\n    try (inconsist).\n\n    (* beq_oid fo2 o0 = false*)\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo') h2; auto.\n\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo')  h1; auto.\n\n\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto.\n\n\n\n(* fields are both H *)\n    case_eq (beq_oid fo1 o); intro.\n    (*inconsistency fo1 and o cannot equal*)\n    apply beq_oid_equal in H42.\n    subst; auto.\n    rewrite H39 in H17; inversion H17; subst; auto.\n    destruct H41. try (inconsist).\n\n\n    (*beq_oid fo1 o = false *)\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls1 F1 lo')  h1; auto.\n    \n    case_eq (beq_oid fo2 o0); intro.\n    (*inconsistency fo2 and o0 cannot equal*)\n    apply beq_oid_equal in H44.\n    subst; auto. \n    rewrite H40 in H19; inversion H19; subst; auto.\n    destruct H41. try (inconsist).\n\n    (* only the case fo1 <> o and fo2 <> o0 is feasible  *)\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls2 F2 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls2 F2 lo')  h2; auto.\n\n    \n    exists cls_f1. exists cls_f2. exists lof1. exists lof2.\n    exists FF1.\n    exists FF2.\n    split; auto.\n\n  - (* None -> left φ o1 = None *)\n    intros. apply lookup_updated_heap_must_none in H24.\n    apply H15 in H24. auto. \n\n  - (* o1 = None -> right φ o1 = None *)\n    intros. apply lookup_updated_heap_must_none in H24.\n    apply H20 in H24. auto.\n\n  - (* flow_to lb L_Label = false  *)\n    intros.\n    case_eq (beq_oid o1 o); intro.\n    assert ( Some (Heap_OBJ cls F lb) = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) o1 ). auto.\n    apply lookup_updated_heap_new_obj in H27; auto.\n    inversion H27; subst; auto.\n    try (inconsist).\n    \n    assert (Some (Heap_OBJ cls F lb) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls1 F1 lo')) o1\n           ). auto.\n    apply lookup_updated_heap_old_obj in H27; auto.\n    assert ( lookup_heap_obj h1 o1 = Some (Heap_OBJ cls F lb) ); auto.\n    apply H22 in H28; auto. \n\n  - (*flow_to lb L_Label = false -> right φ o1 = None *)\n    intros.\n    case_eq (beq_oid o1 o0); intro.\n    assert ( Some (Heap_OBJ cls F lb) = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) o1 ). auto.\n    apply lookup_updated_heap_new_obj in H27; auto.\n    inversion H27; subst; auto.\n    try (inconsist).\n    \n    assert (Some (Heap_OBJ cls F lb) =\n            lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls2 F2 lo')) o1\n           ). auto.\n    apply lookup_updated_heap_old_obj in H27; auto.\n    assert ( lookup_heap_obj h2 o1 = Some (Heap_OBJ cls F lb) ); auto.\n    apply H23 in H28; auto.\n\n  - (*flow_to lo' L_Label = false *)\n    rewrite <- H16 in H5. inversion H5; subst; auto.\n    assert (flow_to lo' L_Label = false).\n    apply flow_transitive with lb0; auto.\n    try (inconsist).\n   \nQed. Hint Resolve lbl_L_change_obj_both_lbl_preserve_bijection. \n\n\n\n  (* heap bijection preservation *)\nLemma lbl_H_raise_obj_both_lbl_preserve_bijection {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  φ' (Hφ : (left φ o = Some o0)),\n    flow_to lo' L_Label = false ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    φ' =  (reduce_bijection φ o o0 Hφ) ->\n      L_equivalence_heap\n        (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n        (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ'.\n    \nProof with eauto.\n  intros.   \n(*  inversion H7; subst; auto.\n  rewrite <- H17 in H5; inversion H5; subst; auto.\n  rewrite <- H19 in H6; inversion H6; subst; auto.\n*)\n  inversion H4; subst; auto.\n  \n  - (*flow_to lo' L_Label = false *)\n\n    \n    assert (L_equivalence_object o h1 o0 h2 φ) as H_eq_o1_o2.          \n    apply H15; auto. \n    inversion H_eq_o1_o2; subst; auto.    \n    apply L_eq_heap; auto.\n\n    + intros.\n      case_eq (beq_oid o1 o); intro.\n      (* cannot happen *)\n      apply beq_oid_equal in H25. subst; auto. \n      assert (left (reduce_bijection φ o o0 Hφ) o = None). apply reduce_bijection_lookup_eq_left; auto.\n      rewrite H25 in H24; inversion H24.\n\n      apply beq_oid_false_mark in H25.\n      assert (left (reduce_bijection φ o o0 Hφ) o1 = left φ o1).\n      apply reduce_bijection_lookup_neq_left. auto.\n      \n      subst; auto. assert (left φ o1 = Some o2). rewrite <- H26.  rewrite H24. auto.\n\n      case_eq (beq_oid o2 o0); intro.\n      apply beq_oid_equal in H28. subst; auto.\n      assert (left φ o = Some o0). auto. \n      apply right_left in H27. apply right_left in H28.\n      rewrite H27 in H28. inversion H28. \n\n      rewrite H30 in H25; try (contradiction).\n      \n      apply H15 in H27. inversion H27; subst; auto.       \n    \n      assert ( Some (Heap_OBJ cls3 F3 lb4)  =\n      lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo'))  o1).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls F lo')  h1; auto.\n\n      \n      assert ( Some (Heap_OBJ cls4 F4 lb5)  =\n      lookup_heap_obj  (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo'))  o2).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls0 F0 lo')  h2; auto.\n      apply object_equal_L with lb4 lb5 cls3 cls4\n                              F3 F4\n      ; auto.\n      destruct H33. destruct H36. destruct H37. \n      split; auto. split; auto.\n      split; auto. \n      intros.\n\n      destruct H38 with fname fo1 fo2; auto. rename x into cls_f1.\n      destruct H41 as [cls_f2]. destruct H41 as [lof1].\n      destruct H41 as [lof2]. destruct H41 as [FF1]. destruct H41 as [FF2].\n      destruct H41. destruct H42.  destruct H43. \n\n\n      (* fields are both L *)\n      case_eq (beq_oid fo1 o); intro.\n      apply beq_oid_equal in H44.\n      assert (fo2 = o0).\n      destruct H43. assert (left φ o = Some o0); auto.\n      subst; auto. rewrite H43 in H46; inversion H46; subst; auto. \n      assert (Some (Heap_OBJ cls F lo')\n            = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) fo1).\n      apply lookup_updated with h1 (Heap_OBJ cls_f1 FF1 lof1); auto.\n      rewrite H44; auto.\n\n      assert (Some (Heap_OBJ cls0 F0 lo')\n            = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) fo2).\n      apply lookup_updated with h2 (Heap_OBJ cls_f2 FF2 lof2); auto.\n      rewrite H45. auto.\n\n      exists cls. exists cls0. exists lo'. exists lo'.\n      exists F.\n      exists F0.\n\n      split; auto. \n\n      (* beq_oid fo1 o = false*)\n      subst; auto.\n      assert (fo2 <> o0).\n      intro contra. subst; auto.\n      destruct H43.\n      assert (left φ o = Some o0). auto.\n      apply right_left in H33.\n      apply right_left in H45. rewrite H45 in H33; inversion H33; subst; auto.\n      assert (beq_oid fo1 fo1 = true). apply beq_oid_same. try (inconsist).\n      apply beq_oid_not_equal in H33. \n\n    (* beq_oid fo2 o0 = false*)\n      assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo')  h1; auto.\n \n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0   (Heap_OBJ cls0 F0 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0  (Heap_OBJ cls0 F0 lo') h2; auto.\n\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto. split; auto. left; auto.\n    destruct H43. \n\n    assert (left (reduce_bijection φ o o0 Hφ ) fo1 = left φ fo1).\n    apply reduce_bijection_lookup_neq_left.\n    intro contra. \n    rewrite contra in H44.\n    assert (beq_oid fo1 fo1 = true).\n    apply beq_oid_same. try (inconsist).\n    split; auto. rewrite <- H48 in H43; auto. \n\n(* fields are both H *)\n    case_eq (beq_oid fo1 o); intro.\n    (*inconsistency fo1 and o cannot equal*)\n    apply beq_oid_equal in H44.\n    rewrite <- H44 in H14.\n    rewrite H41 in H14; inversion H14; subst; auto.\n    destruct H43. try (inconsist).\n\n    assert (fo2 <> o0).\n    intro contra. subst; auto.\n    rewrite H42 in H20; inversion H20; subst; auto.\n    destruct H43. try (inconsist).\n    apply beq_oid_not_equal in H45. \n\n\n    (* fo1 <> o and fo2 <> o0 *)\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo')  h1; auto.\n\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls0 F0 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls0 F0 lo')  h2; auto.\n    \n    exists cls_f1. exists cls_f2. exists lof1. exists lof2.\n    exists FF1.\n    exists FF2.\n    split; auto.\n\n\n    +   (* None -> left φ o1 = None *)\n    intros. apply lookup_updated_heap_must_none in H24.\n    apply H16 in H24. subst; auto.\n    case_eq (beq_oid o o1); intro.\n    ++ apply beq_oid_equal in H25.  subst; auto.\n       apply reduce_bijection_lookup_eq_left.\n    ++ apply beq_oid_false_mark in H25.\n       assert (left (reduce_bijection φ o o0 Hφ) o1 = left φ o1).\n       apply reduce_bijection_lookup_neq_left; auto.\n       rewrite H26. rewrite H24.\n       auto. \n      \n    + (* o1 = None -> right φ o1 = None *)\n    intros. apply lookup_updated_heap_must_none in H24.\n    apply H17 in H24.\n    case_eq (beq_oid o0 o1); intro.\n    ++ apply beq_oid_equal in H25.  subst; auto.\n       apply reduce_bijection_lookup_eq_right.\n    ++ apply beq_oid_false_mark in H25.\n       assert (right (reduce_bijection φ o o0 Hφ) o1 = right φ o1).\n       apply reduce_bijection_lookup_neq_right; auto.\n       subst; auto. \n       rewrite H26. rewrite H24.\n       auto. \n\n    + (* flow_to lb L_Label = false  *)\n    intros.\n    case_eq (beq_oid o1 o); intro.\n    ++ apply beq_oid_equal in H26. subst; auto.\n       apply reduce_bijection_lookup_eq_left.\n    ++ \n    assert ( Some (Heap_OBJ cls3 F3 lb) = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o1). auto.\n    apply lookup_updated_heap_old_obj in H27; auto.\n    assert (left φ o1 = None). \n    apply H18 with cls3 F3 lb; auto.\n    assert (left (reduce_bijection φ o o0 Hφ) o1 = left φ o1).\n    apply reduce_bijection_lookup_neq_left; auto.\n    intro contra. subst; auto.\n    assert (beq_oid o1 o1 = true). apply beq_oid_same. try (inconsist).\n    subst; auto. \n    rewrite H29. auto. \n\n  + (*flow_to lb L_Label = false -> right φ o1 = None *)\n    intros.\n    case_eq (beq_oid o1 o0); intro.\n    ++ apply beq_oid_equal in H26; subst; auto.\n       apply reduce_bijection_lookup_eq_right.\n    ++ \n    assert ( Some (Heap_OBJ cls3 F3 lb) = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) o1); auto. \n    apply lookup_updated_heap_old_obj in H27; auto.\n    assert (right φ o1 = None). \n    apply H19 with cls3 F3 lb; auto.\n    assert (right (reduce_bijection φ o o0 Hφ) o1 = right φ o1).\n    apply reduce_bijection_lookup_neq_right; auto.\n    intro contra.\n    subst; auto. assert (beq_oid o1 o1 = true). apply beq_oid_same. try (inconsist).\n    subst; auto. \n    rewrite H29. auto. \n\nQed. Hint Resolve lbl_H_raise_obj_both_lbl_preserve_bijection. \n\n\n  (* heap bijection preservation *)\nLemma lbl_H_change_obj_both_lbl_preserve_bijection {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0,\n    flow_to lo' L_Label = false ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = false ->\n    flow_to lo0 L_Label = false ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_equivalence_heap\n        (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n        (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ.\n    \nProof with eauto.\n  intros.   \n  inversion H4; subst; auto.  \n  (*flow_to lo' L_Label = false *)\n  apply L_eq_heap; auto.\n  + intros.\n    case_eq (beq_oid o1 o); intro.\n      (* cannot happen *)\n    apply beq_oid_equal in H22. subst; auto.\n    apply H16 in H21. \n    inversion H21; subst; auto.\n    rewrite <- H22 in H5; inversion H5; subst; auto.\n    try (inconsist).\n\n    assert (o0 <> o2).\n    intro contra. subst; auto.\n    apply H16 in H21. \n    inversion H21; subst; auto.\n    rewrite <- H24 in H6; inversion H6; subst; auto.\n    try (inconsist).\n\n    apply beq_oid_not_equal in H23. \n\n    apply H16 in H21; inversion H21; subst; auto. \n\n    assert ( Some (Heap_OBJ cls1 F1 lb0)  =\n             lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo'))  o1).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo')  h1; auto.\n    \n    assert ( Some (Heap_OBJ cls2 F2 lb3)  =\n      lookup_heap_obj  (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo'))  o2).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls0 F0 lo')  h2; auto.\n\n    intro contra. subst; auto.\n    assert (beq_oid o0 o0 = true). apply beq_oid_same.\n    try (inconsist).\n\n    apply object_equal_L with lb0 lb3 cls1 cls2\n                              F1 F2; auto.\n\n    destruct H28. destruct H31. destruct H32. \n    split; auto. split; auto.\n    split; auto. \n\n    intros.\n    destruct H33 with fname fo1 fo2; auto. rename x into cls_f1.\n    destruct H36 as [cls_f2]. destruct H36 as [lof1].\n    destruct H36 as [lof2]. destruct H36 as [FF1]. destruct H36 as [FF2].\n    destruct H36. destruct H37.  destruct H38. \n\n\n      (* fields are both L *)\n    case_eq (beq_oid fo1 o); intro.\n    (*cannot happen *)\n    apply beq_oid_equal in H39.\n    subst; auto.\n    destruct H38. destruct H38. destruct H39.\n    rewrite H36 in H5; inversion H5; subst; auto.\n    try (inconsist).\n\n    assert (fo2 <> o0).\n    intro contra. subst; auto.\n    rewrite H37 in H6; inversion H6; subst; auto.\n    destruct H38. destruct H38.\n    try (inconsist).\n\n    apply beq_oid_not_equal in H40. \n\n    (* beq_oid fo1 o = false*)\n    (* beq_oid fo2 o0 = false*)\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo')  h1; auto.\n \n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0   (Heap_OBJ cls0 F0 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0  (Heap_OBJ cls0 F0 lo') h2; auto.\n\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto.\n\n    \n(* fields are both H *)\n    case_eq (beq_oid fo1 o); intro.\n    apply beq_oid_equal in H39; subst; auto.\n    assert (Some (Heap_OBJ cls F lo') =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o\n           ).\n    apply lookup_updated with h1 (Heap_OBJ cls_f1 FF1 lof1); auto.\n\n    case_eq (beq_oid fo2 o0); intro.\n    apply beq_oid_equal in H39; subst; auto.\n    assert (Some (Heap_OBJ cls0 F0 lo') =\n            lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) o0\n           ).\n    apply lookup_updated with h2 (Heap_OBJ cls_f2 FF2 lof2); auto.\n\n    exists cls. exists cls0.\n    exists lo'. exists lo'.\n    exists F. exists F0.\n    split; auto.\n\n    (* fo1 = o and fo2 <> o0 *)\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls0 F0 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls0 F0 lo')  h2; auto.\n    exists cls. exists cls_f2.\n    exists lo'. exists lof2.\n    exists F. exists FF2.\n    split; auto. split; auto.\n    right. split; auto. apply H38.\n\n    (* fo1 <> o *)\n    assert (Some (Heap_OBJ cls_f1 FF1 lof1) =\n            lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) fo1 \n           ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo')  h1; auto.\n\n    (* fo1 <> o and fo2 = o0 *)\n    case_eq (beq_oid fo2 o0); intro.\n    apply beq_oid_equal in H41; subst; auto.\n    assert (Some (Heap_OBJ cls0 F0 lo') =\n            lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) o0\n           ).\n    apply lookup_updated with h2 (Heap_OBJ cls_f2 FF2 lof2); auto.\n\n    exists cls_f1. exists cls0.\n    exists lof1. exists lo'.\n    exists FF1. exists F0.\n    split; auto. split; auto.\n    right. split; auto. apply H38. \n\n    (* fo1 <> o and fo2 <> o0 *)\n    assert (Some (Heap_OBJ cls_f2 FF2 lof2) =\n           lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls0 F0 lo')) fo2\n           ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls0 F0 lo')  h2; auto.\n    exists cls_f1. exists cls_f2.\n    exists lof1. exists lof2.\n    exists FF1. exists FF2.\n    split; auto.\n\n  +   (* None -> left φ o1 = None *)\n    intros. apply lookup_updated_heap_must_none in H21.\n    apply H17 in H21. subst; auto.\n      \n  + (* o1 = None -> right φ o1 = None *)\n    intros. apply lookup_updated_heap_must_none in H21.\n    apply H18 in H21; auto. \n\n  + (* flow_to lb L_Label = false  *)\n    intros.\n    case_eq (beq_oid o1 o); intro.\n    ++ apply beq_oid_equal in H23. subst; auto.\n       apply H19 with cls F lo; auto.  \n    ++ \n      assert ( Some (Heap_OBJ cls1 F1 lb) = lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o1). auto.\n      apply lookup_updated_heap_old_obj in H24; auto.\n      apply H19 with cls1 F1 lb; auto. \n\n  + (*flow_to lb L_Label = false -> right φ o1 = None *)\n    intros.\n    case_eq (beq_oid o1 o0); intro.\n    ++ apply beq_oid_equal in H23; subst; auto.\n       apply H20 with cls0 F0 lo0; auto. \n    ++ \n    assert ( Some (Heap_OBJ cls1 F1 lb) = lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) o1); auto. \n    apply lookup_updated_heap_old_obj in H24; auto.\n    apply H20 with cls1 F1 lb; auto. \n\nQed. Hint Resolve lbl_H_change_obj_both_lbl_preserve_bijection. \n\n\n\n\nLemma lbl_L_change_obj_both_lbl_preserve_l_eq_tm: forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  t1 t2,\n    flow_to lo' L_Label = true ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    L_equivalence_tm t1 h1 t2 h2 φ ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_equivalence_tm t1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                     t2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ.\nProof with eauto.\n  intros.\n\n  inversion H7; subst; auto.\n  - generalize dependent t2.\n    induction t1; intros; inversion H8; subst; auto.\n    case_eq (beq_oid o1 o); intro.\n    apply beq_oid_equal in H15; subst; auto.\n    + rewrite H16 in H17; inversion H17; subst; auto.\n      assert (Some (Heap_OBJ cls F lo') =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o ).\n      apply lookup_updated with h1 (Heap_OBJ cls3 F3 lb4); auto.\n\n      assert (Some (Heap_OBJ cls0 F0 lo') =\n              lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls0 F0 lo')) o0 ).\n      apply lookup_updated with h2 (Heap_OBJ cls4 F4 lb5); auto.  \n      \n      apply L_equivalence_tm_eq_object_L with cls F lo' cls0 F0 lo'; auto.\n\n    + assert (o3 <> o0).\n      intro contra. subst; auto.\n      apply right_left in H16.\n      apply right_left in H17.\n      rewrite H16 in H17; inversion H17; subst; auto.\n      assert (beq_oid o o = true). apply beq_oid_same.\n      try (inconsist).\n      apply beq_oid_not_equal in H26.\n\n      assert (Some (Heap_OBJ cls3 F3 lb4) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o1 ).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h1; auto.\n      \n      assert (Some (Heap_OBJ cls4 F4 lb5) =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) o3 ).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls0 F0 lo') h2; auto.\n      apply  L_equivalence_tm_eq_object_L with cls3 F3 lb4 cls4 F4 lb5; auto.\n\n    + assert (o1 <> o). intro contra.\n      subst; auto.\n      rewrite <- H16 in H18; inversion H18; subst; auto.\n      try (inconsist).\n\n      assert (o3 <> o0). intro contra.\n      subst; auto.\n      rewrite <- H23 in H20; inversion H20; subst; auto.\n      try (inconsist).\n\n      apply beq_oid_not_equal in H15.       apply beq_oid_not_equal in H25.\n      assert (Some (Heap_OBJ cls3 F3 lb4) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o1 ).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h1; auto.\n      \n      assert (Some (Heap_OBJ cls4 F4 lb5) =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) o3 ).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls0 F0 lo') h2; auto.\n      apply  L_equivalence_tm_eq_object_H with cls3 cls4 F3 lb4 F4 lb5; auto.\n\n  - rewrite <- H5 in H17; inversion H17; subst; auto. \n    assert (flow_to lo' L_Label = false).\n    apply flow_transitive with lo; auto.\n    try (inconsist).\nQed. Hint Resolve     lbl_L_change_obj_both_lbl_preserve_l_eq_tm.  \n\n\n\nLemma lbl_H_raise_obj_both_lbl_preserve_l_eq_tm {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  φ' (Hφ : (left φ o = Some o0)) t1 t2,\n    flow_to lo' L_Label = false ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = true ->\n    flow_to lo0 L_Label = true ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    φ' =  (reduce_bijection φ o o0 Hφ) ->\n    L_equivalence_tm t1 h1 t2 h2 φ ->\n    L_equivalence_tm t1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                     t2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ'.\n    \nProof with eauto.\n  intros.   \n  generalize dependent t2.\n  induction t1; intros; inversion H17; subst; auto.\n\n  - case_eq (beq_oid o1 o); intro.\n    apply beq_oid_equal in H16; subst; auto.\n    + rewrite Hφ in H19; inversion H19; subst; auto.\n      assert (Some (Heap_OBJ cls F lo') =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o ).\n      apply lookup_updated with h1 (Heap_OBJ cls1 F1 lb0); auto.\n\n      assert (Some (Heap_OBJ cls0 F0 lo') =\n              lookup_heap_obj (update_heap_obj h2 o3  (Heap_OBJ cls0 F0 lo')) o3 ).\n      apply lookup_updated with h2 (Heap_OBJ cls2 F2 lb3); auto.  \n      \n      apply L_equivalence_tm_eq_object_H with cls cls0 F lo' F0 lo'; auto.\n\n    + assert (o3 <> o0).\n      intro contra. subst; auto.\n      apply right_left in Hφ.\n      apply right_left in H19.\n      rewrite Hφ in H19; inversion H19; subst; auto.\n      assert (beq_oid o1 o1 = true). apply beq_oid_same.\n      try (inconsist).\n      apply beq_oid_not_equal in H18.\n\n      assert (Some (Heap_OBJ cls1 F1 lb0) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o1 ).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h1; auto.\n      \n      assert (Some (Heap_OBJ cls2 F2 lb3) =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) o3 ).\n      apply lookup_updated_not_affected with o0 (Heap_OBJ cls0 F0 lo') h2; auto.\n      apply  L_equivalence_tm_eq_object_L with cls1 F1 lb0 cls2 F2 lb3; auto.\n      assert (left (reduce_bijection φ o o0 Hφ) o1 = left φ o1).\n      apply reduce_bijection_lookup_neq_left.\n      intro contra. subst; auto.\n      assert (beq_oid o1 o1 = true). apply beq_oid_same.\n      try (inconsist).\n      rewrite H26. auto.\n\n  - assert (o1 <> o). intro contra.\n    subst; auto.\n    inversion H17; subst; auto.\n    rewrite <- H24 in H19; inversion H19; subst; auto.\n    try (inconsist).\n\n    \n    rewrite <- H19 in H5; inversion H5; subst; auto.\n    try (inconsist).\n\n    assert (o3 <> o0). intro contra.\n    subst; auto.\n    rewrite <- H21 in H6; inversion H6; subst; auto.\n    try (inconsist).\n\n    apply beq_oid_not_equal in H16.       apply beq_oid_not_equal in H18.\n    assert (Some (Heap_OBJ cls1 F1 lb0) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o1 ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h1; auto.\n      \n    assert (Some (Heap_OBJ cls2 F2 lb3) =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) o3 ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls0 F0 lo') h2; auto.\n    apply  L_equivalence_tm_eq_object_H with cls1 cls2 F1 lb0 F2 lb3; auto.\nQed. Hint Resolve lbl_H_raise_obj_both_lbl_preserve_l_eq_tm.\n\n\n\nLemma lbl_H_change_obj_both_lbl_preserve_l_eq_tm {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  t1 t2,\n    flow_to lo' L_Label = false ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = false ->\n    flow_to lo0 L_Label = false ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_equivalence_tm t1 h1 t2 h2 φ ->\n    L_equivalence_tm t1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                     t2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ.\n    \nProof with eauto.\n  intros.   \n  generalize dependent t2.\n  induction t1; intros; inversion H16; subst; auto.\n\n  - assert (o1 <> o). intro contra.\n    subst; auto.\n    rewrite <- H5 in H19; inversion H19; subst; auto.\n    try (inconsist).\n\n    assert (o3 <> o0). intro contra.\n    subst; auto.\n    rewrite <- H21 in H6; inversion H6; subst; auto.\n    try (inconsist).\n\n    apply beq_oid_not_equal in H17.       apply beq_oid_not_equal in H23.\n    assert (Some (Heap_OBJ cls1 F1 lb0) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o1 ).\n    apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h1; auto.\n      \n    assert (Some (Heap_OBJ cls2 F2 lb3) =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) o3 ).\n    apply lookup_updated_not_affected with o0 (Heap_OBJ cls0 F0 lo') h2; auto.\n    apply  L_equivalence_tm_eq_object_L with cls1 F1 lb0 cls2 F2  lb3; auto.\n\n  - case_eq (beq_oid o1 o); intro.\n    + apply beq_oid_equal in H17; subst; auto.\n      assert (Some (Heap_OBJ cls F lo') =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o ).\n      apply lookup_updated with h1 (Heap_OBJ cls1 F1 lb0); auto.\n      case_eq (beq_oid o3 o0); intro.\n      ++ apply beq_oid_equal in H22; subst; auto.\n         assert (Some (Heap_OBJ cls0 F0 lo') =\n              lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls0 F0 lo')) o0 ).\n         apply lookup_updated with h2 (Heap_OBJ cls2 F2 lb3); auto.\n         apply L_equivalence_tm_eq_object_H with cls cls0 F lo'  F0 lo'; auto.\n      ++ assert (Some (Heap_OBJ cls2 F2 lb3) =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) o3 ).\n         apply lookup_updated_not_affected with o0 (Heap_OBJ cls0 F0 lo') h2; auto.\n         apply L_equivalence_tm_eq_object_H with cls cls2 F lo'  F2 lb3; auto.\n    + assert (Some (Heap_OBJ cls1 F1 lb0) =\n              lookup_heap_obj (update_heap_obj h1 o (Heap_OBJ cls F lo')) o1 ).\n      apply lookup_updated_not_affected with o (Heap_OBJ cls F lo') h1; auto.\n      case_eq (beq_oid o3 o0); intro.\n      ++ apply beq_oid_equal in H23; subst; auto.\n         assert (Some (Heap_OBJ cls0 F0 lo') =\n              lookup_heap_obj (update_heap_obj h2 o0  (Heap_OBJ cls0 F0 lo')) o0 ).\n         apply lookup_updated with h2 (Heap_OBJ cls2 F2 lb3); auto.\n         apply L_equivalence_tm_eq_object_H with cls1 cls0 F1 lb0  F0 lo'; auto.\n\n      ++ assert (Some (Heap_OBJ cls2 F2 lb3) =\n              lookup_heap_obj (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) o3 ).\n         apply lookup_updated_not_affected with o0 (Heap_OBJ cls0 F0 lo') h2; auto.\n         apply L_equivalence_tm_eq_object_H with cls1 cls2 F1 lb0  F2 lb3; auto.\nQed. Hint Resolve lbl_H_change_obj_both_lbl_preserve_l_eq_tm. \n\n\n\nLemma lbl_H_raise_obj_both_lbl_preserve_l_eq_fs {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  φ' (Hφ : (left φ o = Some o0)) fs1 fs2,\n    flow_to lo' L_Label = false ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = true ->\n    flow_to lo0 L_Label = true ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    φ' =  (reduce_bijection φ o o0 Hφ) ->\n    L_equivalence_fs fs1 h1 fs2 h2 φ ->\n    L_equivalence_fs fs1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                     fs2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ'.\nProof with eauto.\n  intros.\n  generalize dependent fs2.\n  induction fs1; intros; inversion H17; subst; auto.\n  apply L_equal_fs; auto.\n  apply lbl_H_raise_obj_both_lbl_preserve_l_eq_tm with  ct φ lo lo0 lb1 lb2\nHφ; auto. \nQed. Hint Resolve lbl_H_raise_obj_both_lbl_preserve_l_eq_fs.\n  \n\n\n\nLemma lbl_H_change_obj_both_lbl_preserve_l_eq_fs {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  fs1 fs2,\n    flow_to lo' L_Label = false ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = false ->\n    flow_to lo0 L_Label = false ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_equivalence_fs fs1 h1 fs2 h2 φ ->\n    L_equivalence_fs fs1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                     fs2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ.\nProof with eauto.\n  intros.\n  generalize dependent fs2.\n  induction fs1; intros; inversion H16; subst; auto.\n  apply L_equal_fs; auto.\n  apply lbl_H_change_obj_both_lbl_preserve_l_eq_tm with  ct lo lo0 lb1 lb2; auto. \nQed. Hint Resolve lbl_H_change_obj_both_lbl_preserve_l_eq_fs.\n\n\nLemma lbl_H_raise_obj_both_lbl_preserve_l_eq_store {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  φ' (Hφ : (left φ o = Some o0)) sf1 sf2,\n    flow_to lo' L_Label = false ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = true ->\n    flow_to lo0 L_Label = true ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    φ' =  (reduce_bijection φ o o0 Hφ) ->\n    L_equivalence_store sf1 h1 sf2 h2 φ ->\n    L_equivalence_store sf1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                     sf2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ'.\nProof with eauto.\n  intros.\n  \n  inversion H17; subst; auto. \n  apply L_equivalence_store_L; auto.\n  split; auto. intros. \n  assert (L_equivalence_tm v1 h1 v2 h2 φ).\n  apply H18 with x; auto.\n  apply lbl_H_raise_obj_both_lbl_preserve_l_eq_tm with ct φ lo lo0 lb1 lb2\n                                                       Hφ;auto.\n  apply H18.   \nQed. Hint Resolve lbl_H_raise_obj_both_lbl_preserve_l_eq_store .\n\nLemma lbl_H_change_obj_both_lbl_preserve_l_eq_store {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  sf1 sf2,\n    flow_to lo' L_Label = false ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = false ->\n    flow_to lo0 L_Label = false ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_equivalence_store sf1 h1 sf2 h2 φ ->\n    L_equivalence_store sf1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                     sf2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ.\nProof with eauto.\n  intros.\n  inversion H16; subst; auto. \n  apply L_equivalence_store_L; auto.\n  split; auto. intros. \n  assert (L_equivalence_tm v1 h1 v2 h2 φ).\n  apply H17 with x; auto.\n  apply lbl_H_change_obj_both_lbl_preserve_l_eq_tm with ct lo lo0 lb1 lb2\n                                                       ;auto.\n  apply H17.  \nQed. Hint Resolve lbl_H_change_obj_both_lbl_preserve_l_eq_store.\n\n\n\n\n\nLemma lbl_H_raise_obj_both_lbl_preserve_l_eq_ctn {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  φ' (Hφ : (left φ o = Some o0)) ctn1 ctn2,\n    flow_to lo' L_Label = false ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = true ->\n    flow_to lo0 L_Label = true ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    φ' =  (reduce_bijection φ o o0 Hφ) ->\n    L_eq_container ctn1 h1 ctn2 h2 φ ->\n    L_eq_container ctn1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                     ctn2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ'.\nProof with eauto.\n  intros.  \n  generalize dependent ctn2. \n  induction ctn1; intros;subst; auto;\n  inversion H17; subst; auto.\n  apply  L_eq_ctn; auto.\n  apply lbl_H_raise_obj_both_lbl_preserve_l_eq_tm with ct φ lo lo0 lb1 lb2 Hφ; auto.\n  apply lbl_H_raise_obj_both_lbl_preserve_l_eq_fs with ct φ lo lo0 lb1 lb2 Hφ; auto. \n  apply lbl_H_raise_obj_both_lbl_preserve_l_eq_store with ct φ lo lo0 lb1 lb2 Hφ; auto. \nQed. Hint Resolve lbl_H_raise_obj_both_lbl_preserve_l_eq_ctn.\n\nLemma lbl_H_change_obj_both_lbl_preserve_l_eq_ctn {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  ctn1 ctn2,\n    flow_to lo' L_Label = false ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = false ->\n    flow_to lo0 L_Label = false ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_eq_container ctn1 h1 ctn2 h2 φ ->\n    L_eq_container ctn1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                     ctn2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ.\nProof with eauto.\n  intros.\n  generalize dependent ctn2. \n  induction ctn1; intros;subst; auto;\n  inversion H16; subst; auto.\n  apply  L_eq_ctn; auto.\n  apply lbl_H_change_obj_both_lbl_preserve_l_eq_tm with ct lo lo0 lb1 lb2; auto.\n  apply lbl_H_change_obj_both_lbl_preserve_l_eq_fs with ct lo lo0 lb1 lb2; auto. \n  apply lbl_H_change_obj_both_lbl_preserve_l_eq_store with ct lo lo0 lb1 lb2; auto. \nQed. Hint Resolve lbl_H_change_obj_both_lbl_preserve_l_eq_ctn.\n\n\n\nLemma lbl_H_raise_obj_both_lbl_preserve_l_eq_ctns {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  φ' (Hφ : (left φ o = Some o0)) ctns1 ctns2,\n    flow_to lo' L_Label = false ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = true ->\n    flow_to lo0 L_Label = true ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    φ' =  (reduce_bijection φ o o0 Hφ) ->\n    L_eq_ctns ctns1 h1 ctns2 h2 φ ->\n    L_eq_ctns ctns1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                     ctns2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ'.\nProof with eauto.\n  intros.  \n  generalize dependent ctns2. \n  induction ctns1; intros;subst; auto;\n  inversion H17; subst; auto.\n  apply  L_eq_ctns_list; auto.\n  apply lbl_H_raise_obj_both_lbl_preserve_l_eq_ctn with ct φ lo lo0 lb1 lb2 Hφ; auto.\nQed. Hint Resolve lbl_H_raise_obj_both_lbl_preserve_l_eq_ctns.\n\nLemma lbl_H_change_obj_both_lbl_preserve_l_eq_ctns {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  ctns1 ctns2,\n    flow_to lo' L_Label = false ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = false ->\n    flow_to lo0 L_Label = false ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_eq_ctns ctns1 h1 ctns2 h2 φ ->\n    L_eq_ctns ctns1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                     ctns2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ.\nProof with eauto.\n  intros.\n  generalize dependent ctns2. \n  induction ctns1; intros;subst; auto;\n  inversion H16; subst; auto.\n  apply  L_eq_ctns_list; auto.\n  apply lbl_H_change_obj_both_lbl_preserve_l_eq_ctn with ct lo lo0 lb1 lb2; auto.\nQed. Hint Resolve lbl_H_change_obj_both_lbl_preserve_l_eq_ctns.\n\n\nLemma lbl_L_change_obj_both_lbl_preserve_l_eq_fs: forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  fs1 fs2,\n    flow_to lo' L_Label = true ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_equivalence_fs fs1 h1 fs2 h2 φ ->\n    L_equivalence_fs fs1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                     fs2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ.\nProof with eauto.\n  intros.\n  generalize dependent fs2.\n  induction fs1; intros; inversion H14; subst; auto.\n  apply L_equal_fs; auto.\n  apply lbl_L_change_obj_both_lbl_preserve_l_eq_tm with  ct lo lo0 lb1 lb2; auto. \nQed. Hint Resolve lbl_L_change_obj_both_lbl_preserve_l_eq_fs.\n  \n  \n\n\nLemma lbl_L_change_obj_both_lbl_preserve_l_eq_store: forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  sf1 sf2,\n    flow_to lo' L_Label = true ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_equivalence_store sf1 h1 sf2 h2 φ ->\n    L_equivalence_store sf1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                        sf2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ.\nProof with eauto.\n    intros.\n    inversion H14; subst; auto. \n    apply L_equivalence_store_L; auto.\n    split; auto. intros. \n    assert (L_equivalence_tm v1 h1 v2 h2 φ).\n    apply H15 with x; auto.\n    apply lbl_L_change_obj_both_lbl_preserve_l_eq_tm with ct lo lo0 lb1 lb2\n                                                       ;auto.\n    apply H15. \nQed. Hint Resolve lbl_L_change_obj_both_lbl_preserve_l_eq_store.\n    \n\n\nLemma lbl_L_change_obj_both_lbl_preserve_l_eq_ctn: forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  ctn1 ctn2,\n    flow_to lo' L_Label = true ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_eq_container ctn1 h1 ctn2 h2 φ ->\n    L_eq_container ctn1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                        ctn2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ.\nProof with eauto.\n  intros.\n  generalize dependent ctn2. \n  induction ctn1; intros;subst; auto;\n  inversion H14; subst; auto.\n  apply  L_eq_ctn; auto.\n  apply lbl_L_change_obj_both_lbl_preserve_l_eq_tm with ct lo lo0 lb1 lb2; auto.\n  apply lbl_L_change_obj_both_lbl_preserve_l_eq_fs with ct lo lo0 lb1 lb2; auto. \n  apply lbl_L_change_obj_both_lbl_preserve_l_eq_store with ct lo lo0 lb1 lb2; auto. \nQed. Hint Resolve lbl_L_change_obj_both_lbl_preserve_l_eq_ctn.\n\n\n\n\nLemma lbl_L_change_obj_both_lbl_preserve_l_eq_ctns: forall  ct h1 h2 φ lo lo0 lo' F F0 o o0 lb1 lb2 cls cls0\n  ctns1 ctns2,\n    flow_to lo' L_Label = true ->\n    wfe_heap ct h1 -> field_wfe_heap ct h1 ->\n    wfe_heap ct h2 -> field_wfe_heap ct h2 ->  \n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_eq_ctns ctns1 h1 ctns2 h2 φ ->\n    L_eq_ctns ctns1 (update_heap_obj h1 o (Heap_OBJ cls F lo'))\n                        ctns2 (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo')) φ.\nProof with eauto.\n  intros.\n  generalize dependent ctns2. \n  induction ctns1; intros;subst; auto;\n  inversion H14; subst; auto.\n  apply  L_eq_ctns_list; auto.\n  apply lbl_L_change_obj_both_lbl_preserve_l_eq_ctn with ct lo lo0 lb1 lb2; auto. \nQed. Hint Resolve lbl_L_change_obj_both_lbl_preserve_l_eq_ctns.\n  \n\n\nLemma lbl_L_change_obj_both_lbl_preserve_l_eq_config: forall  ct h1 h2 φ lo lo0 lo' F F0 o o0\n                                                              t1 fs1 sf1 lb1\n                                                              t2 fs2 sf2 lb2 cls cls0 ctns1 ctns2,\n    flow_to lo' L_Label = true ->\n    valid_config (Config ct (Container t1 fs1 lb1 sf1 ) ctns1  h1)  ->\n    valid_config (Config ct (Container t2 fs2 lb2 sf2) ctns2  h2)  ->\n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_equivalence_config (Config ct (Container t1 fs1 lb1 sf1) ctns1  h1)\n                   (Config ct (Container t2 fs2 lb2 sf2) ctns2  h2) φ ->\n    L_equivalence_config (Config ct (Container t1 fs1 lb1 sf1) ctns1  (update_heap_obj h1 o (Heap_OBJ cls F lo')))\n                   (Config ct (Container t2 fs2 lb2 sf2) ctns2  (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo'))) φ .\nProof with eauto.\n  intros.\n  inversion H0; subst; auto.\n  inversion H21; subst; auto.\n  inversion H1; subst; auto.\n  inversion H31; subst; auto. \n  \n\n  remember (Config ct (Container t1 fs1 lb1 sf1 ) ctns1  h1) as config1.\n  remember (Config ct (Container t2 fs2 lb2 sf2) ctns2  h2) as config2.\n\n  generalize dependent t1. generalize dependent t2.\n  generalize dependent fs1. generalize dependent fs2.\n  generalize dependent sf1. generalize dependent sf2.\n  generalize dependent ctns1. generalize dependent ctns2. \n  induction H12; subst; intros; inversion Heqconfig1; inversion Heqconfig2; subst; auto.\n\n  - apply L_equivalence_config_L; auto.\n    apply lbl_L_change_obj_both_lbl_preserve_l_eq_ctn with ct lo lo0 lb1 lb2; auto.\n    apply lbl_L_change_obj_both_lbl_preserve_l_eq_ctns with ct lo lo0 lb1 lb2; auto.\n  - try (inconsist).\nQed. Hint Resolve lbl_L_change_obj_both_lbl_preserve_l_eq_config. \n\n\n\n\nLemma lbl_H_raise_obj_both_lbl_preserve_l_eq_config {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} : forall\n    ct h1 h2 φ lo lo0 lo' F F0 o o0\n    t1 fs1 sf1 lb1\n    t2 fs2 sf2 lb2 cls cls0 ctns1 ctns2\n    φ' (Hφ : (left φ o = Some o0)),\n    flow_to lo' L_Label = false ->\n    valid_config (Config ct (Container t1 fs1 lb1 sf1 ) ctns1  h1)  ->\n    valid_config (Config ct (Container t2 fs2 lb2 sf2) ctns2  h2)  ->\n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = true ->\n    flow_to lo0 L_Label = true ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    φ' =  (reduce_bijection φ o o0 Hφ) ->\n    L_equivalence_config (Config ct (Container t1 fs1 lb1 sf1) ctns1  h1)\n                   (Config ct (Container t2 fs2 lb2 sf2) ctns2  h2) φ ->\n    L_equivalence_config (Config ct (Container t1 fs1 lb1 sf1) ctns1  (update_heap_obj h1 o (Heap_OBJ cls F lo')))\n                   (Config ct (Container t2 fs2 lb2 sf2) ctns2  (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo'))) φ' .\nProof with eauto.\n  intros.  \n  inversion H0; subst; auto.\n  inversion H24; subst; auto.\n  inversion H1; subst; auto.\n  inversion H33; subst; auto.   \n\n  remember (Config ct (Container t1 fs1 lb1 sf1 ) ctns1  h1) as config1.\n  remember (Config ct (Container t2 fs2 lb2 sf2) ctns2  h2) as config2.\n\n  generalize dependent t1. generalize dependent t2.\n  generalize dependent fs1. generalize dependent fs2.\n  generalize dependent sf1. generalize dependent sf2.\n  generalize dependent ctns1. generalize dependent ctns2. \n  induction H15; subst; intros; inversion Heqconfig1; inversion Heqconfig2; subst; auto.\n\n  - apply L_equivalence_config_L; auto.\n    apply lbl_H_raise_obj_both_lbl_preserve_l_eq_ctn with ct φ lo lo0 lb1 lb2 Hφ; auto.\n    apply lbl_H_raise_obj_both_lbl_preserve_l_eq_ctns with ct φ lo lo0 lb1 lb2 Hφ; auto.\n  - try (inconsist).\nQed. Hint Resolve lbl_H_raise_obj_both_lbl_preserve_l_eq_config. \n\n\n\nLemma lbl_H_change_obj_both_lbl_preserve_l_eq_config {DecOid : forall a1 a2 : oid, Decision (a1 = a2)} :\n  forall  ct h1 h2 φ lo lo0 lo' F F0 o o0\n    t1 fs1 sf1 lb1\n    t2 fs2 sf2 lb2 cls cls0 ctns1 ctns2,\n    flow_to lo' L_Label = false ->\n    valid_config (Config ct (Container t1 fs1 lb1 sf1 ) ctns1  h1)  ->\n    valid_config (Config ct (Container t2 fs2 lb2 sf2) ctns2  h2)  ->\n    L_equivalence_heap h1 h2 φ ->\n    Some (Heap_OBJ cls F lo) = lookup_heap_obj h1 o ->\n    Some (Heap_OBJ cls0 F0 lo0) = lookup_heap_obj h2 o0 ->\n    L_equivalence_tm (ObjId o) h1 (ObjId o0) h2 φ ->\n    flow_to lo L_Label = false ->\n    flow_to lo0 L_Label = false ->\n    flow_to lb1 L_Label = true ->\n    flow_to lb2 L_Label = true ->\n    flow_to lb1 lo = true ->\n    flow_to lb2 lo0 = true ->\n    flow_to lo lo' = true ->\n    flow_to lo0 lo' = true ->\n    L_equivalence_config (Config ct (Container t1 fs1 lb1 sf1) ctns1  h1)\n                   (Config ct (Container t2 fs2 lb2 sf2) ctns2  h2) φ ->\n    L_equivalence_config (Config ct (Container t1 fs1 lb1 sf1) ctns1  (update_heap_obj h1 o (Heap_OBJ cls F lo')))\n                   (Config ct (Container t2 fs2 lb2 sf2) ctns2  (update_heap_obj h2 o0 (Heap_OBJ cls0 F0 lo'))) φ .\nProof with eauto.\n  intros.  \n  inversion H0; subst; auto.\n  inversion H23; subst; auto.\n  inversion H1; subst; auto.\n  inversion H33; subst; auto.   \n\n  remember (Config ct (Container t1 fs1 lb1 sf1 ) ctns1  h1) as config1.\n  remember (Config ct (Container t2 fs2 lb2 sf2) ctns2  h2) as config2.\n\n  generalize dependent t1. generalize dependent t2.\n  generalize dependent fs1. generalize dependent fs2.\n  generalize dependent sf1. generalize dependent sf2.\n  generalize dependent ctns1. generalize dependent ctns2. \n  induction H14; subst; intros; inversion Heqconfig1; inversion Heqconfig2; subst; auto.\n\n  - apply L_equivalence_config_L; auto.\n    apply lbl_H_change_obj_both_lbl_preserve_l_eq_ctn with ct lo lo0 lb1 lb2; auto.\n    apply lbl_H_change_obj_both_lbl_preserve_l_eq_ctns with ct lo lo0 lb1 lb2; auto.\n  - try (inconsist).\nQed. Hint Resolve lbl_H_change_obj_both_lbl_preserve_l_eq_config. \n\n", "meta": {"author": "HarvardPL", "repo": "CIFC", "sha": "39a86edcfc25f26d9698026fec5beafd4d87c7da", "save_path": "github-repos/coq/HarvardPL-CIFC", "path": "github-repos/coq/HarvardPL-CIFC/CIFC-39a86edcfc25f26d9698026fec5beafd4d87c7da/obj_float_label/Low_eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.22996647805794782}}
{"text": "(** This file contains the naive implementation of a decompression\nalgorithm for deflate streams. It is extremely slow and memory\nconsuming, and was mainly made to test the specification against small\ndatasets. It is *not* meant for actual usage. *)\n\nRequire Import CpdtTactics.\n\nRequire Import Coq.Logic.Decidable.\nRequire Import Coq.Arith.Compare_dec.\n\nRequire Import Coq.Numbers.NatInt.NZOrder.\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Coq.Vectors.Vector.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Vectors.Fin.\nRequire Import Coq.Arith.Div2.\n\nRequire Import Coq.NArith.BinNatDef.\nRequire Import Coq.NArith.BinNat.\nRequire Import Coq.PArith.BinPos.\nRequire Import NArith.\nRequire Import Coq.QArith.QArith_base.\nRequire Import Coq.Strings.String.\nRequire Import Ascii.\nRequire Import Program.\n\nRequire Import Shorthand.\nRequire Import DeflateCoding.\nRequire Import KraftVec.\nRequire Import KraftList.\nRequire Import Combi.\nRequire Import Transports.\nRequire Import Prefix.\nRequire Import LSB.\nRequire Import Repeat.\nRequire Import Backreferences.\nRequire Import StrongDec.\nRequire Import EncodingRelation.\n\nLocal Open Scope nat_scope.\n\nLemma nBitsEq : forall l m n, nBits n l m <-> (l = m /\\ ll l = n).\nProof.\n  intros l m n.\n  revert l m.\n  induction n.\n  intros l m.\n  split.\n  intro nb.\n  inversion nb.\n  crush.\n  intros [lm lb].\n  destruct l.\n  crush.\n  constructor.\n  reflexivity.\n  reflexivity.\n  inversion lb.\n\n  intros l m.\n  split.\n  intro nb.\n  split.\n  inversion nb.\n  match goal with\n    | K : OneBit _ _ |- _ => inversion K\n  end.\n  simpl.\n  f_equal.\n  apply IHn.\n  trivial.\n  inversion nb.\n  simpl.\n  f_equal.\n  apply (proj1 (IHn br ar)).\n  trivial.\n\n  intros [lm lb].\n  destruct l.\n  inversion lb.\n  replace (b :: l) with ([b] ++ l) in lm ; [|reflexivity].\n  rewrite <- lm.\n  constructor.\n  constructor.\n  apply IHn.\n  crush.\nQed.\n\nLemma OneByteEq : forall (b : Byte), OneByte (inl b) (to_list b).\nProof.\n  intro b.\n  apply AppCombineF.\n  unfold nBitsVec.\n  apply nBitsEq.\n  split.  \n  reflexivity.\n  apply to_list_length.\nQed.\n\n(* Old definition of nBytesDirect. *)\nInductive nBytesDirect_old : nat -> SequenceWithBackRefs Byte -> LB -> Prop :=\n| nBytesDirect0 : nBytesDirect_old 0 nil nil\n| nBytesDirectS : forall n a b bools thebyte,\n                    nBytesDirect_old n a b -> bools = to_list thebyte ->\n                    nBytesDirect_old (S n) ((inl thebyte) :: a) (bools ++ b).\n\n(* Old definition of nBytesDirect is equivalent to new one. *)\nGoal forall n swbr lb, nBytesDirect n swbr lb <-> nBytesDirect_old n swbr lb.\nProof.\n  induction n as [|n IHn].\n  + intros swbr lb.\n    split.\n    - intro nbd.\n      inversion nbd.\n      crush.\n      constructor.\n    - intro nbdo.\n      inversion nbdo.\n      constructor.\n      reflexivity.\n      reflexivity.\n  + intros swbr lb.\n    split.\n    - intro nbd.\n      unfold nBytesDirect in nbd.\n      inversion nbd as [A B C D E F G H].\n      inversion E as [I J K L M [N_ N] O P].\n      constructor.\n      apply IHn.\n      apply F.\n      unfold nBitsVec in M.\n      rewrite -> (proj1 (proj1 (nBitsEq _ _ _) M)).\n      rewrite -> N.\n      rewrite -> app_nil_r.\n      reflexivity.\n    - intro nbdo.\n      inversion nbdo.\n      constructor.\n      crush.\n      apply AppCombineF.\n      unfold nBitsVec.\n      apply nBitsEq.\n      crush.\n      apply to_list_length.\n      apply IHn.\n      trivial.\nQed.\n\n(* old definition of readBitsLSB *)\nInductive readBitsLSB_old (length : nat) : nat -> LB -> Prop :=\n| mkRBLSB : forall l n, ll l = length -> LSBnat l n -> readBitsLSB_old length n l.\n\nGoal forall length n lb, readBitsLSB length n lb <-> readBitsLSB_old length n lb.\nProof.\n  intros length n lb.\n  split.\n  intro rbl.\n  inversion rbl.\n  constructor.\n  match goal with\n    | K : nTimesCons _ _ _ _, L : _ /\\ _ = Bnil |- _ =>\n      destruct L as [L_ L];\n      apply nBitsEq in K;\n        destruct K as [A B];\n        rewrite <- A;\n        rewrite -> L;\n        rewrite -> app_nil_r;\n        trivial\n  end.\n  match goal with\n    | K : nTimesCons _ _ _ _, L : _ /\\ _ = Bnil |- _ =>\n      destruct L as [L_ L];\n      apply nBitsEq in K;\n        destruct K as [A B];\n        rewrite <- A;\n        rewrite -> L;\n        rewrite -> app_nil_r;\n        apply ListToNat_correct\n  end.\n  intro rblo.\n  inversion rblo.\n  replace n with (ListToNat lb).\n  apply AppCombineF.\n  apply nBitsEq.\n  crush.\n  eapply LSBnat_unique.\n  apply ListToNat_correct.\n  trivial.\nQed.\n\n(** Plausibility check: *)\nGoal nBytesDirect 3 [ inl (of_list [false; false; false; false; false; false; false; false]);\n                      inl (of_list [false; false; false; false; false; false; false; true]);\n                      inl (of_list [false; false; false; false; false; false; true; false]) ]\n     [false; false; false; false; false; false; false; false;\n      false; false; false; false; false; false; false; true;\n      false; false; false; false; false; false; true; false].\nProof.\n  replace [false; false; false; false; false; false; false; false;\n           false; false; false; false; false; false; false; true;\n           false; false; false; false; false; false; true; false]\n  with ([false; false; false; false; false; false; false; false]\n          ++ [false; false; false; false; false; false; false; true]\n          ++ [false; false; false; false; false; false; true; false]\n          ++ []); [|reflexivity].\n  constructor.\n  apply AppCombineF.\n  apply nBitsEq.\n  crush.\n  constructor.\n  apply AppCombineF.\n  apply nBitsEq.\n  crush.\n  constructor.\n  apply AppCombineF.\n  apply nBitsEq.\n  crush.\n  constructor.\n  reflexivity.\n  reflexivity.\nQed.\n\n(** Lemmata to convince us that the definition is correct *)\n\n(** There can never be a back reference *)\n\nGoal forall n L S x, nBytesDirect n S L -> ~ In (inr x) S.\nProof.\n  induction n.\n  intros L S x H.\n  inversion H as [A B].\n  rewrite -> A.\n  auto.\n\n  intros L S x H.\n  inversion H as [A B C D E F G J].\n  intros [QQ | QQQ].\n  inversion E.\n  crush.\n\n  eapply IHn.\n  exact F.\n  exact QQQ.\nQed.\n\nTheorem nBytesInputLength : forall n L S,\n                              nBytesDirect n L S -> ll S = 8 * n.\nProof.\n  induction n.\n  intros L S H.\n  inversion H.\n  crush.\n\n  intros L S nbd.\n  inversion nbd as [A B C D E F G H].\n  rewrite -> app_length.\n  rewrite -> (IHn _ _ F).\n  inversion E as [J K M N O [P_ P] Q R].\n  rewrite -> app_length.\n  rewrite -> P.\n  apply nBitsEq in O.\n  destruct O as [O T].\n  rewrite <- O.\n  rewrite -> to_list_length.\n  simpl.\n  omega.\nDefined.\n\nLemma OneBitStrongUnique : StrongUnique OneBit.\nProof.\n  intros a b la las lb lbs apps oa ob.\n  destruct a.\n  destruct b.\n  inversion oa.\n  inversion ob.\n  auto.\n  inversion oa as [Aa Ba Ca].\n  inversion ob as [Ab Bb Cb].\n  rewrite <- Ca in apps.\n  rewrite <- Cb in apps.\n  crush.\n\n  destruct b.\n  inversion oa as [Aa Ba Ca].\n  inversion ob as [Ab Bb Cb].\n  rewrite <- Ca in apps.\n  rewrite <- Cb in apps.\n  crush.\n  inversion oa.\n  inversion ob.\n  auto.\nQed.\n\nLemma OneBitStrongDec : StrongDec OneBit.\nProof.\n  intro l.\n  destruct l.\n  apply inr.\n  split.\n  exact \"OneBit_ShortRead\"%string.\n  intros [a [l' [l'' [lapp oba]]]].\n  destruct l'.\n  inversion oba.\n  crush.\n  apply inl.\n  exists b.\n  exists [b].\n  exists l.\n  crush.\n  constructor.\nDefined.\n\nLemma nBitsStrongDecStrongUnique : forall n, StrongDec (nBits n) * StrongUnique (nBits n).\nProof.\n  intro n. \n  apply nTimesStrongDecStrongUnique.\n  exact \"nBits\"%string.\n  apply OneBitStrongUnique.\n  apply OneBitStrongDec.\nDefined.\n\nLemma nBitsVecStrongDecStrongUnique : forall n, StrongDec (nBitsVec n) * StrongUnique (nBitsVec n).\nProof.\n  intro n.\n  split.\n  intro l.\n  destruct (fst (nBitsStrongDecStrongUnique n) l) as [[a [l' [l'' [lapp nb]]]]|[reason no]].\n  apply inl.\n  rewrite <- (proj2 (proj1 (nBitsEq _ _ _) nb)).\n  exists (of_list a).\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  unfold nBitsVec.\n  rewrite -> to_list_of_list_opp.\n  rewrite -> (proj2 (proj1 (nBitsEq _ _ _) nb)).\n  exact nb.\n\n  apply inr.\n  split.\n  exact \"nBitsVec\"%string.\n  intros [a [l' [l'' [lapp nbv]]]].\n  apply no.\n  unfold nBitsVec in nbv.\n  exists (to_list a).\n  exists l'.\n  exists l''.\n  auto.\n\n  intros a b la las lb lbs apps nba nbb.\n  destruct (snd (nBitsStrongDecStrongUnique n) (to_list a) (to_list b) la las lb lbs apps).\n  trivial.\n  trivial.\n  split.\n  apply to_list_inj.\n  trivial.\n  trivial.\nQed.\n\nLemma OneByteStrongDecStrongUnique : StrongDec OneByte * StrongUnique OneByte.\nProof.\n  split.\n  apply CombineStrongDecStrongUnique.\n  apply nBitsVecStrongDecStrongUnique.\n  apply nBitsVecStrongDecStrongUnique.\n  intro q.\n  split.\n  apply nullStrongUnique.\n  apply nullStrongDec.\n\n  apply CombineStrongDecStrongUnique.\n  apply nBitsVecStrongDecStrongUnique.\n  apply nBitsVecStrongDecStrongUnique.\n  intro q.\n  split.\n  apply nullStrongUnique.\n  apply nullStrongDec.\nDefined.\n\nTheorem nBytesDirectStrongDecStrongUnique :\n  forall n, StrongDec (nBytesDirect n) * StrongUnique (nBytesDirect n).\nProof.\n  intros n.\n  apply nTimesStrongDecStrongUnique.\n  exact \"nBytes\"%string.\n  apply OneByteStrongDecStrongUnique.\n  apply OneByteStrongDecStrongUnique.\nDefined.  \n\n(* For compatibility *)\nTheorem nBytesDirectStrongUnique : forall n, StrongUnique (nBytesDirect n).\nProof.\n  apply nBytesDirectStrongDecStrongUnique.\nQed.\n\nLemma readBitsLSBStrongDecStrongUnique :\n  forall length,  StrongDec (readBitsLSB length) * StrongUnique (readBitsLSB length).\nProof.\n  intro length.\n  split.\n  apply CombineStrongDecStrongUnique.\n  apply nTimesStrongDecStrongUnique.\n  exact \"readBitsLSB\"%string.\n  apply OneBitStrongUnique.\n  apply OneBitStrongDec.\n  apply nTimesStrongDecStrongUnique.\n  exact \"readBitsLSB\"%string.\n  apply OneBitStrongUnique.\n  apply OneBitStrongDec.\n\n  intro Q.\n  split.\n  apply nullStrongUnique.\n  apply nullStrongDec.\n  apply CombineStrongDecStrongUnique.\n  apply nTimesStrongDecStrongUnique.\n  exact \"readBitsLSB\"%string.\n  apply OneBitStrongUnique.\n  apply OneBitStrongDec.\n  apply nTimesStrongDecStrongUnique.\n  exact \"readBitsLSB\"%string.\n  apply OneBitStrongUnique.\n  apply OneBitStrongDec.\n\n  intro Q.\n  split.\n  apply nullStrongUnique.\n  apply nullStrongDec.\nDefined.\n\n(* For Backward Compatibility *)\nLemma readBitsLSBStrongUnique : forall length, StrongUnique (readBitsLSB length).\nProof.\n  apply readBitsLSBStrongDecStrongUnique.\nDefined.\nLemma readBitsLSBStrongDec : forall length, StrongDec (readBitsLSB length).\nProof.\n  apply readBitsLSBStrongDecStrongUnique.\nDefined.\n\nTheorem nBytesDirectStrongDec : forall n, StrongDec (nBytesDirect n).\nProof.\n  apply nBytesDirectStrongDecStrongUnique. \nDefined.\n\nTheorem UncompressedBlockDirectStrongUniqueStrongDec : StrongUnique UncompressedBlockDirect * StrongDec UncompressedBlockDirect.\nProof.\n  apply CombineStrongDecStrongUnique.\n  apply readBitsLSBStrongUnique.\n  apply readBitsLSBStrongDec.\n  intro len.\n  apply CombineStrongDecStrongUnique.\n  apply readBitsLSBStrongUnique.\n  apply readBitsLSBStrongDec.\n  intro nlen.\n  split.\n  apply AndStrongUnique.\n  apply nBytesDirectStrongUnique.\n  apply AndStrongDec.\n  destruct (eq_nat_dec (len + nlen) (2 ^ 16 - 1)) as [e|e].\n  auto.\n  apply inr.\n  split.\n  exact \"In UncompressedBlockDirectStrongUniqueStrongDec: Header Checksum failed.\"%string.\n  auto.\n  apply nBytesDirectStrongDec.\nDefined.\n\nLemma CLCHeaderRaw_inplen : forall (hclen : nat) (input : LB) (output : list nat),\n                              CLCHeaderRaw hclen input output -> ll input = 3 * hclen.\nProof.\n  induction hclen.\n  intros input output clch.\n  inversion clch.\n  auto.\n\n  intros input output clch.\n  inversion clch.\n  rewrite -> app_length.\n  rewrite -> H1.\n  rewrite -> (IHhclen i o).\n  omega.\n  trivial.\nDefined.\n\nLemma CLCHeaderRawUnique : forall hclen input output1 output2, CLCHeaderRaw hclen input output1 -> CLCHeaderRaw hclen input output2 -> output1 = output2.\nProof.  \n  induction hclen.\n  intros input output1 output2 clch1 clch2.\n  inversion clch1.\n  inversion clch2.\n  reflexivity.\n\n  intros input output1 output2 clch1 clch2.\n  inversion clch1 as [|hc1 inp1 outp1 n1 i1 o1 j1 m1 A1 B1 C1].\n  inversion clch2 as [|hc2 inp2 outp2 n2 i2 o2 j2 m2 A2 B2 C2].\n\n  destruct (app_ll i1 inp1 i2 inp2) as [ie inpe].\n  rewrite -> B2.\n  rewrite -> B1.\n  reflexivity.\n  rewrite -> j2.\n  rewrite -> j1.\n  reflexivity.\n\n  assert (oo  : outp1 = outp2).\n  apply (IHhclen inp1).\n  trivial.\n  rewrite -> inpe.\n  trivial.\n  rewrite -> oo.\n  f_equal.\n  apply (LSBnat_unique i1).\n  trivial.\n  rewrite -> ie.\n  trivial.\nDefined.\n\nTheorem CLCHeaderRawParse : forall m l, {o : list nat & {l' : LB & {l'' | l = l' ++ l'' /\\ CLCHeaderRaw m l' o}}}\n                                        + (string * ({o : list nat & {l' : LB & {l'' | l = l' ++ l'' /\\ CLCHeaderRaw m l' o}}} -> False)).\nProof.\n  induction m.\n\n  intro l.\n  apply inl.\n  exists (nil(A:=nat)).\n  exists Bnil.\n  exists l.\n  split.\n  auto.\n  constructor.\n\n  intro l.\n  destruct (slice_list 3 l) as [[l1 [l2 [l1l2 lll1]]]|no].\n  destruct (IHm l2) as [[o [l' [l'' [l2app clch]]]]|[reason IHmNo]].\n  apply inl.\n  exists ((ListToNat l1) :: o).\n  exists (l1 ++ l').\n  exists l''.\n  split.\n  rewrite <- app_assoc.\n  rewrite <- l2app.\n  auto.\n  constructor.\n  trivial.\n  trivial.\n  apply ListToNat_correct.\n\n  apply inr.\n  split.\n  exact reason.\n  intro Q.\n  destruct Q as [o [l' [l'' [lapp clch]]]].\n  inversion clch. (* TODO *)\n  contradict IHmNo.\n  exists o0.\n  exists i.\n  exists l''.\n  split.\n  apply (app_ll l1 l2 m0 (i ++ l'')).\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  rewrite <- lapp.\n  auto.\n  rewrite -> lll1.\n  auto.\n  trivial.\n\n  apply inr.\n  split.\n  exact \"In CLCHeaderRawParse: not enough bits.\"%string.\n  intro Q.\n  destruct Q as [o [l' [l'' [lapp clch]]]].\n  inversion clch. (* TODO *)\n  contradict no.\n  exists m0.\n  exists (i ++ l'').\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  auto.\n  trivial.\nDefined.\n\nLemma CLCHeaderPaddedUnique : forall hclen input output1 output2,\n                               CLCHeaderPadded hclen input output1 ->\n                               CLCHeaderPadded hclen input output2 ->\n                               output1 = output2.\nProof.\n  intros hclen input output1 output2 clchp1 clchp2.\n  inversion clchp1 as [m1 o1 A1 B1 C1].\n  inversion clchp2 as [m2 o2 A2 B2 C2].\n  assert (oo : o1 = o2).\n  apply (CLCHeaderRawUnique hclen input).\n  trivial.\n  trivial.\n  rewrite -> oo in B1.  \n  assert (mm : m1 = m2).\n  assert (llo1 : 19 = ll o2 + m1).\n  rewrite <- C1.\n  rewrite <- (rep_length m1 0).\n  rewrite <- app_length.\n  rewrite <- B1.\n  reflexivity.\n  assert (llo2 : 19 = ll o2 + m2).\n  rewrite <- C2.\n  rewrite <- (rep_length m2 0).\n  rewrite <- app_length.\n  rewrite <- B2.\n  reflexivity.\n  omega.\n  rewrite -> B1.\n  rewrite -> B2.\n  rewrite -> mm.\n  reflexivity.\nDefined.\n\nLemma CLCHeaderPaddedParse_1 : forall m i l, CLCHeaderRaw m i l -> ll l = m.\nProof.\n  induction m.\n  intros i l clch.\n  inversion clch.\n  reflexivity.\n  intros i l clch.\n  inversion clch.\n  unfold ll.\n  f_equal.\n  unfold ll in IHm.\n  rewrite -> (IHm i0). (* todo *)\n  trivial.\n  trivial.\nDefined.\n\nTheorem CLCHeaderPaddedParse : forall m l, {o : list nat & {l' : LB & {l'' | l = l' ++ l'' /\\ CLCHeaderPadded m l' o}}}\n                                           + (string * ({o : list nat & {l' : LB & {l'' | l = l' ++ l'' /\\ CLCHeaderPadded m l' o}}} -> False)).\nProof.\n  intros m l.\n\n  destruct (nat_compare m 20) eqn:ncm.\n\n  assert (M : m = 20).\n  apply nat_compare_eq.\n  trivial.\n\n  rewrite -> M.\n\n  apply inr.\n  split.\n  exact \"In CLCHeaderPaddedParse: m = 20. THIS SHOULD BE IMPOSSIBLE!\"%string.\n  intro Q.\n  destruct Q as [o [l' [l'' [lapp clchp]]]].\n  inversion clchp. (* TODO *)\n\n  assert (LL : ll output1 = 20).\n  apply (CLCHeaderPaddedParse_1 _ l').\n  trivial.\n  rewrite -> H0 in H1.\n  rewrite -> app_length in H1.\n  omega.\n\n  assert (M : m < 20).\n  apply nat_compare_lt.\n  trivial.\n\n  destruct (CLCHeaderRawParse m l) as [[o[l'[l''[lapp clch]]]]|[reason no]].\n  apply inl.\n  exists (o ++ repeat (19 - m) 0).\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  apply (makeCLCHeaderPadded m l' (o ++ repeat (19 - m) 0) (19 - m) o).\n  trivial.\n  trivial.\n  rewrite -> app_length.\n  rewrite -> rep_length.\n  rewrite -> (CLCHeaderPaddedParse_1 m l').\n  omega.\n  trivial.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In CLCHeaderPaddedParse: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [o [l' [l'' [lapp clchp]]]].\n  inversion clchp. (* TODO *)\n  contradict no.\n  exists output1.\n  exists l'.\n  exists l''.\n  auto.\n\n  (* TODO: this is similar to the m = 20 case *)\n  assert (M : m > 20).\n  apply nat_compare_gt.\n  trivial.\n\n  apply inr.\n  split.\n  exact \"In CLCHeaderPaddedParse: m > 20. THIS SHOULD BE IMPOSSIBLE!\"%string.\n  intro Q.\n  destruct Q as [o [l' [l'' [lapp clchp]]]].\n  inversion clchp. (* TODO *)\n  rewrite -> H0 in H1.\n  rewrite -> app_length in H1.\n  rewrite -> (CLCHeaderPaddedParse_1 m l') in H1.\n  omega.\n  trivial.\nDefined.\n\n\nLemma list_nat_ineq_nth_error : forall (l1 l2 : list nat), l1 <> l2 -> {m | nth_error l1 m <> nth_error l2 m}.\nProof.\n  induction l1 as [|l1a l1b].\n\n  destruct l2.\n  intro Q.\n  contradict Q.\n  reflexivity.\n\n  intro neq.\n  exists 0.\n  intro Q.\n  inversion Q.\n\n  destruct l2 as [|l2a l2b].\n  intro neq.\n  exists 0.\n  intro Q.\n  inversion Q.\n\n  intro neq.\n  destruct (eq_nat_dec l1a l2a).\n  assert (nneq : l1b <> l2b).\n  intro Q.\n  contradict neq.\n  rewrite -> e.\n  rewrite -> Q.\n  reflexivity.\n\n  destruct (IHl1b l2b nneq) as [m nnneq].\n  exists (S m).\n  compute.\n  compute in nnneq.\n  trivial.\n\n  exists 0.\n  compute.\n  intro Q.\n  contradict n.\n  inversion Q.\n  reflexivity.\nDefined.\n\n(* TODO: Rename this, it is also used in CLCHeaderPermutedUnique *)\nLemma CLCHeaderParse_1 : forall hclen input output, CLCHeaderPermuted hclen input output -> ll output = 19.\nProof.\n  intros hclen input output clch.\n  inversion clch.\n  inversion H.\n\n  do 19 (destruct output1; [inversion H3 | idtac]).\n  destruct output1.\n\n  set (H' := H0 2).\n\n  do 19 (destruct output; [inversion H'|idtac]).\n\n  destruct output.\n  reflexivity.\n\n  set (H'' := H0 19).\n  compute in H''.\n  inversion H''.\n\n  inversion H3.\nDefined.\n\nLemma ntherror_max : forall {A} (l : list A) (n : nat),\n                       ll l <= n -> nth_error l n = error.\nProof.\n  intro A.\n  induction l. \n\n  destruct n.\n  auto.\n  auto.\n\n  destruct n.\n  intro Q.\n  inversion Q.\n\n  intro lll'.\n  assert (lll : ll l <= n).\n  compute in lll'.\n  compute.\n  omega.\n  unfold nth_error.\n  unfold nth_error in IHl.\n  rewrite -> (IHl n lll).\n  reflexivity.\nDefined.\n\nLemma CLCHeaderPermutedUnique : forall hclen input output1 output2,\n                                  CLCHeaderPermuted hclen input output1 ->\n                                  CLCHeaderPermuted hclen input output2 ->\n                                  output1 = output2.\nProof.\n  intros hclen input output1 output2 clch1 clch2.\n  inversion clch1 as [o1 A1 B1].\n  inversion clch2 as [o2 A2 B2].\n  assert (oo : o1 = o2).\n  apply (CLCHeaderPaddedUnique hclen input).\n  trivial.\n  trivial.\n  rewrite -> oo in B1.\n  destruct (list_eq_dec eq_nat_dec output1 output2) as [y | n].\n  trivial.\n  assert (C : forall m, nth_error output1 (nth m HCLensNat 19) = nth_error output2 (nth m HCLensNat 19)).\n  intro m.\n  rewrite -> B1.\n  rewrite -> B2.\n  reflexivity.\n  destruct (list_nat_ineq_nth_error output1 output2 n) as [m mn].\n  assert (out1len : ll output1 = 19).\n  apply (CLCHeaderParse_1 hclen input).\n  trivial.\n  assert (out2len : ll output2 = 19).\n  apply (CLCHeaderParse_1 hclen input).\n  trivial.\n\n  (* TODO: shorter *)\n  contradict mn.\n  unfold HCLensNat in C.\n  destruct m.\n  apply (C 3).\n  destruct m.\n  apply (C 17).\n  destruct m.\n  apply (C 15).\n  destruct m.\n  apply (C 13).\n  destruct m.\n  apply (C 11).\n  destruct m.\n  apply (C 9).\n  destruct m.\n  apply (C 7).\n  destruct m.\n  apply (C 5).\n  destruct m.\n  apply (C 4).\n  destruct m.\n  apply (C 6).\n  destruct m.\n  apply (C 8).\n  destruct m.\n  apply (C 10).\n  destruct m.\n  apply (C 12).\n  destruct m.\n  apply (C 14).\n  destruct m.\n  apply (C 16).\n  destruct m.\n  apply (C 18).\n  destruct m.\n  apply (C 0).\n  destruct m.\n  apply (C 1).\n  destruct m.\n  apply (C 2).\n\n  rewrite -> ntherror_max.\n  rewrite -> ntherror_max.\n  reflexivity.\n  omega.\n  omega.\nDefined.\n\nTheorem CLCHeaderPermutedParse_1 : forall (l' : list nat), (ll l' = 19) -> {l | ll l' = ll l /\\ forall m, nth_error l (nth m HCLensNat 19) = nth_error l' m}.\nProof.\n  intros l ll.\n\n  exists (map (fun n => nth n l 19) [3; 17; 15; 13; 11; 9; 7; 5; 4; 6; 8; 10; 12; 14; 16; 18; 0; 1; 2]).\n\n  do 19 (destruct l; [inversion ll|idtac]).\n  destruct l.\n  split.\n  reflexivity.\n  do 20 (destruct m; [reflexivity|idtac]).\n  reflexivity.\n  inversion ll.\nDefined.\n\nTheorem CLCHeaderPermutedParse : forall m l, {o : list nat & {l' : LB & {l'' | l = l' ++ l'' /\\ CLCHeaderPermuted m l' o}}}\n                                             + (string * ({o : list nat & {l' : LB & {l'' | l = l' ++ l'' /\\ CLCHeaderPermuted m l' o}}} -> False)).\nProof.\n  intros m l.\n  destruct (CLCHeaderPaddedParse m l) as [[o[l'[l''[lapp clchp]]]]|[reason no]].\n  apply inl.\n  assert (olen : ll o = 19).\n  inversion clchp.\n  trivial.\n  destruct (CLCHeaderPermutedParse_1 o olen) as [x [llxo all]].\n  exists x.\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  apply (makeCLCHeaderPermuted m l' x o).\n  trivial.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In CLCHeaderPermutedParse: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [o [l' [l'' [lapp clchp]]]].\n  inversion clchp.\n  contradict no.\n  exists output1.\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  trivial.\nDefined.\n\n\nTheorem CLCHeaderStrongUnique : forall hclen, StrongUnique (CLCHeader hclen).\nProof.\n  intros hclen output1 output2 input1 rest1 input2 rest2 H H0 H1.\n  inversion H0.\n  inversion H1.\n  inversion H2.\n  inversion H4.\n  inversion H6.\n  inversion H8.\n  assert (ll input1 = ll input2).\n  rewrite -> (CLCHeaderRaw_inplen hclen input2 output5).\n  apply (CLCHeaderRaw_inplen _ _ output4).\n  trivial.\n  trivial.\n  destruct (app_ll input1 rest1 input2 rest2) as [inps rests].\n  trivial.\n  trivial.\n  assert (cooks : cooked = cooked0).\n  apply (CLCHeaderPermutedUnique hclen input1).\n  trivial.\n  rewrite -> inps.\n  trivial.\n  split.\n  rewrite <- cooks in H5.\n  apply uniqueness.\n  destruct H3.\n  destruct H5.\n  rewrite -> e.\n  rewrite -> e0.\n  assert (EQ : eq = eq0).\n  apply proof_irrelevance.\n  rewrite -> EQ.\n  reflexivity.\n  firstorder.\nDefined.\n\nTheorem CLCHeaderStrongDec : forall hclen, StrongDec (CLCHeader hclen).\nProof.\n  intros m l.\n\n  destruct (CLCHeaderPermutedParse m l) as [[o [l' [l'' [lapp clchp]]]]|[reason no]].\n  assert (H : ll o = 19).\n  inversion clchp.\n  apply (CLCHeaderParse_1 m l').\n  trivial.\n\n  destruct (Qle_bool (kraft_nvec (of_list o)) 1%Q) eqn:kleb.\n  assert (kle : ((kraft_nvec (of_list o)) <= 1)%Q).\n  apply Qle_bool_iff.\n  trivial.\n  apply inl.\n  destruct (existence (ll o) (of_list o) kle) as [x e].\n\n  do 19 (dependent destruction o; [inversion H | idtac]).\n  dependent destruction o.\n\n  compute in x.\n  exists x.\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n\n  (* TODO: GROSS!!! *)\n  apply (makeCLCHeader m x _ [n; n0; n1; n2; n3; n4; n5; n6; n7; n8; n9; n10; n11; n12; n13; n14; n15; n16; n17]).\n  trivial.\n  apply (makeCodingOfSequence [n; n0; n1; n2; n3; n4; n5; n6; n7; n8; n9; n10; n11; n12; n13; n14; n15; n16; n17] x eq_refl).\n  auto.\n\n  inversion H.\n\n  (* the cases remain where it does *not* work: *)\n\n  (* Qle_bool (kraft_nvec (of_list o)) 1 = false -- but we know kraft's inequality must hold *)\n  apply inr.\n\n  split.\n  exact (\"In CLCHeaderStrongDec: CLC Header does not satisfy Kraft's Inequality. (\" ++ blstring l)%string.\n  intro Q.\n  destruct Q as [o0 [l'0 [l''0 [lapp0 clch]]]].\n  inversion clch as [cooked H0 H1].\n  destruct (app_ll l' l'' l'0 l''0) as [lheads ltails].\n  rewrite <- lapp.\n  trivial.\n  inversion clchp. (* TODO *)\n  inversion H2.\n  rewrite -> (CLCHeaderRaw_inplen m l' output0).\n  inversion H0. inversion H7.\n  rewrite -> (CLCHeaderRaw_inplen m l'0 output3).\n  reflexivity.\n  trivial.\n  trivial.\n  assert (coook : cooked = o).\n  apply (CLCHeaderPermutedUnique m l').\n  rewrite -> lheads.\n  trivial.\n  trivial.\n\n  assert (contra : (kraft_nvec (of_list o) <= 1)%Q).\n  assert (contra' : kraft_d o0 == kraft_nvec (of_list o)).\n  inversion H1.\n\n  destruct o0 as [Co0 pfo0 llo0 ceo0 deno0].\n  unfold kraft_d.\n  unfold C.\n  unfold cd in H2.\n  unfold C in H2.\n  unfold kraft_vec.\n  unfold kraft_nvec.\n  rewrite -> H2.\n  rewrite <- coook.\n  rewrite -> vec_id_map.\n  rewrite -> vec_id_fold.\n  reflexivity.\n  rewrite <- contra'.\n  apply kraft_ineq.\n  assert (Qle_bool (kraft_nvec (of_list o)) 1 = true).\n  apply Qle_bool_iff.\n  trivial.\n  rewrite -> H2 in kleb.\n  inversion kleb.\n\n  (* No permuted header *)\n  apply inr.\n  split.\n  exact (\"In CLCHeaderStrongDec: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [o [l' [l'' [lapp clch]]]].\n  inversion clch. (* TODO *)\n  contradict no.\n  exists cooked.\n  exists l'.\n  exists l''.\n  auto.\nDefined.\n\nTheorem CompressedWithExtraBitsStrongUnique : forall {m} coding mincode xbitnums bases maxs,\n                                              StrongUnique (CompressedWithExtraBits (m:=m) coding mincode xbitnums bases maxs).\nProof.\n  intros m coding mincode xbitnums bases maxs a b la las lb lbs apps cweb1 cweb2.\n  inversion cweb1 as [base extra code max xbitnum bbits xbits H H0 H1 H1_ H2 H3 H3_ H4 H5].  \n  inversion cweb2 as [base0 extra0 code0 max0 xbitnum0 bbits0 xbits0 H6 H7 H8 H8_ H9 H10 H10_ H11 H12].\n  assert (codes : code = code0).\n  assert (mincode + code = mincode + code0).\n  apply (dc_StrongUnique coding (mincode + code) (mincode + code0) bbits (xbits ++ las) bbits0 (xbits0 ++ lbs)).\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  rewrite -> H12.\n  rewrite -> H5.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n  rewrite <- codes in H7.\n  rewrite -> H0 in H7.\n  inversion H7.\n  rewrite <- codes in H6.\n  assert (bbitss : bbits = bbits0).\n  destruct H as [X1 X2].\n  destruct (vnth_is_correct _ _ _ X1) as [xa ea].\n  destruct H6 as [Y1 Y2].\n  destruct (vnth_is_correct _ _ _ Y1) as [ya da].\n  assert (ON : (of_nat_lt xa) = (of_nat_lt ya)).\n  apply of_nat_ext.\n  rewrite <- ON in da.\n  rewrite -> da in ea.\n  auto.\n  assert (lalb : bbits ++ xbits = bbits0 ++ xbits0).\n  apply (app_ll _ las _ lbs).\n  rewrite -> H12.\n  rewrite -> H5.\n  trivial.\n  rewrite -> app_length.\n  rewrite -> app_length.\n  rewrite -> H9.\n  rewrite -> H2.\n  rewrite -> bbitss.\n  rewrite -> H14.\n  reflexivity.\n  split.\n  rewrite <- codes in H8.\n  rewrite -> H1 in H8.\n  inversion H8.\n  assert(extra = extra0).\n  assert (xbitss : xbits = xbits0).\n  apply (app_ll bbits xbits bbits0 xbits0).\n  trivial.\n  rewrite -> bbitss.\n  reflexivity.\n  apply (LSBnat_unique xbits).\n  trivial.\n  rewrite -> xbitss.\n  trivial.\n  omega.\n  trivial.\nDefined.\n\nTheorem CompressedWithExtraBitsStrongDec: forall {m} coding mincode xbitnums bases maxs,\n                                            StrongDec (CompressedWithExtraBits (m:=m) coding mincode xbitnums bases maxs).\nProof.\n  intros m coding mincode xbitnums bases maxs l.\n  destruct (dc_StrongDec coding l) as [[a [l' [l'' [lapp dce]]]]|[reason no]].\n  destruct (le_dec mincode a) as [mle | ale].\n  assert (minc : mincode + (a - mincode) = a).\n  omega.\n  rewrite <- minc in dce.\n  destruct (nth_error xbitnums (a - mincode)) as [xbitnum |] eqn:xbe.\n  destruct (nth_error bases (a - mincode)) as [base |] eqn:bse.\n  destruct (nth_error maxs (a - mincode)) as [max |] eqn:mxe.\n  destruct (slice_list xbitnum l'') as [[l1 [l2 [l1app lbl1]]]|no].\n  destruct (le_dec (base + ListToNat l1) max) as [le_max | gt_max].\n  apply inl.\n  exists (base + ListToNat l1).\n  exists (l' ++ l1).\n  exists l2.\n  split.\n  rewrite <- app_assoc.\n  rewrite -> l1app.\n  trivial.\n  apply (complength _ _ _ _ _ _ _ (a - mincode) max xbitnum).\n  trivial.\n  trivial.\n  trivial.\n  trivial.\n  trivial.\n  apply ListToNat_correct.\n  exact le_max.\n\n  apply inr.\n  split.\n  exact \"In CompressedWithExtraBitsStrongDec: Encoded point above maximum.\"%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app cweb]]]].\n  inversion cweb as [A1 B1 C1 D1 E1 F1 G1 H1 I1 J1 K1 L1 M1 N1 O1 P1].\n  destruct (dc_StrongUnique coding (mincode + (a - mincode)) (mincode + C1) l' l'' F1 (G1 ++ l''0)) as [Q R];\n    [ rewrite -> app_assoc;\n      rewrite -> P1;\n      rewrite <- l'app;\n      auto\n    | trivial\n    | trivial\n    | idtac ].\n\n  destruct (app_ll_r G1 l''0 l1 l2) as [S T].\n  apply app_inv_head with F1.\n  rewrite -> app_assoc.\n  rewrite -> P1.\n  rewrite -> l1app.\n  rewrite <- R.\n  rewrite <- l'app.\n  trivial.\n\n  assert (N : (lb F1 + lb G1) + lb l''0 = (lb l' + lb l1) + lb l2).\n  rewrite <- app_length.\n  rewrite -> P1.\n  rewrite <- app_length.\n  rewrite <- l'app.\n  rewrite <- plus_assoc.  \n  rewrite <- app_length.\n  rewrite -> l1app.\n  rewrite <- app_length.\n  f_equal.\n  auto.\n  assert (c1max : C1 = a - mincode).\n  omega.\n  rewrite -> c1max in I1.\n  rewrite -> xbe in I1.\n  inversion I1 as [E1xbe].\n  rewrite -> R in N.\n  abstract(omega).\n\n  assert (B1 = ListToNat l1).\n  eapply LSBnat_unique.\n  apply M1.\n  rewrite -> S.\n  apply ListToNat_correct.\n  assert (c1max : C1 = a - mincode).\n  omega.\n  rewrite -> c1max in J1.\n  rewrite -> bse in J1.\n  inversion J1.\n  rewrite -> c1max in K1.\n  rewrite -> mxe in K1.\n  inversion K1.\n  omega.\n\n  apply inr.\n  split.\n  exact \"In CompressedWithExtraBitsStrongDec: Not enough suffix bits.\"%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app cweb]]]].\n  inversion cweb.\n  contradict no.\n  exists xbits.\n  exists l''0.\n\n  assert (ON' : code = a - mincode).\n  destruct (eq_nat_dec (mincode + code) (mincode + (a - mincode))).\n  omega.\n  destruct (prefix_common bbits l' l).\n  exists (xbits ++ l''0).\n  rewrite -> app_assoc.\n  rewrite -> H7.\n  auto.\n  exists l''.\n  auto.\n  contradict p.\n  apply (prefix_free' coding (mincode + code) (mincode + (a - mincode))).\n  trivial.\n  trivial.\n  trivial.\n  contradict p.\n  apply (prefix_free' coding (mincode + (a - mincode))  (mincode + code)).\n  auto.\n  trivial.\n  trivial.\n  assert (later : lb xbits = xbitnum).\n  rewrite <- ON' in xbe.\n  rewrite -> xbe in H0.\n  inversion H0.\n  trivial.\n  split.\n  assert (bbits = l').\n  rewrite <- ON' in dce.\n  destruct dce as [X1 X2].\n  destruct H as [Y1 Y2].\n  destruct (vnth_is_correct _ _ _ X1) as [xa ea].\n  destruct (vnth_is_correct _ _ _ Y1) as [ya da].\n  assert (ON : (of_nat_lt xa) = (of_nat_lt ya)).\n  apply of_nat_ext.\n  rewrite -> ON in ea.\n  rewrite -> ea in da.\n  auto.\n  apply (app_ll bbits _ l' _).\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  rewrite -> H7.\n  auto.\n  rewrite <- H8.\n  reflexivity.\n  exact later.\n\n  apply inr.\n  split.\n  exact \"In CompressedWithExtraBitsStrongDec: Max-array-index too large.\"%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app cweb]]]].\n  inversion cweb as [A B C D E F G H I J K L M N O P].\n  destruct (dc_StrongUnique coding (mincode + (a - mincode)) (mincode + C) l' l'' F (G ++ l''0)).\n  rewrite -> app_assoc.\n  rewrite -> P.\n  rewrite <- lapp.\n  auto.\n  trivial.\n  trivial.\n  assert (aC : a - mincode = C).\n  omega.\n  rewrite <- aC in K.\n  rewrite -> mxe in K.\n  inversion K.  \n\n  apply inr.\n  split.\n  exact \"In CompressedWithExtraBitsStrongDec: Base-array-index too large.\"%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app cweb]]]].\n  inversion cweb.\n  destruct (eq_nat_dec (a - mincode) code) as [eeq|eneq].\n  rewrite -> eeq in bse.\n  rewrite -> bse in H1.\n  inversion H1.\n  destruct (prefix_common bbits l' l) as [p|p].\n  exists (xbits ++ l''0).\n  rewrite -> app_assoc.\n  rewrite -> H7.\n  auto.\n  exists l''.\n  auto.\n  contradict p.\n  apply (prefix_free' coding (mincode + code) (mincode + (a - mincode))).\n  omega.\n  trivial.\n  trivial.\n  contradict p.\n  apply (prefix_free' coding (mincode + (a - mincode)) (mincode + code)).\n  omega.\n  trivial.\n  trivial.\n\n  apply inr.\n  split.\n  exact \"In CompressedWithExtraBitsStrongDec: Bitnum-array-index too large.\"%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app cweb]]]].\n  inversion cweb.\n  destruct (eq_nat_dec code (a - mincode)) as [e|e].\n  rewrite <- e in xbe.\n  rewrite -> xbe in H0.\n  inversion H0.\n  destruct (prefix_common bbits l' l) as [p|p].\n  exists (xbits ++ l''0).\n  rewrite -> app_assoc.\n  rewrite -> H7.\n  auto.\n  exists l''.\n  auto.\n  contradict p.\n  apply (prefix_free' coding (mincode + code) (mincode + (a - mincode))).\n  omega.\n  trivial.\n  trivial.\n  contradict p.\n  apply (prefix_free' coding (mincode + (a - mincode)) (mincode + code)).\n  omega.\n  trivial.\n  trivial.\n\n  (* ~ mincode <= a *)\n  apply inr.\n  split.\n  exact \"In CompressedWithExtraBitsStrongDec: Decoded character is smaller that minimal allowed character.\"%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app cweb]]]].\n  inversion cweb.\n  destruct (eq_nat_dec a (mincode + code)) as [e|e].\n  omega.\n  destruct (prefix_common bbits l' l) as [p|p].\n  exists (xbits ++ l''0).\n  rewrite -> app_assoc.\n  rewrite -> H7.\n  auto.\n  exists l''.\n  auto.\n  contradict p.\n  apply (prefix_free' coding (mincode + code) a).\n  auto.\n  trivial.\n  trivial.\n  contradict p.\n  apply (prefix_free' coding a (mincode + code)).\n  auto.\n  trivial.\n  trivial.\n\n  (* {a : nat & {l' : LB & {l'' : LB | l = l' ++ l'' /\\ dc_enc coding a l'}}} -> False *)\n  apply inr.\n  split.\n  exact (\"In CompressedWithExtraBitsStrongDec: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp cweb]]]].\n  inversion cweb.\n  contradict no.\n  exists (mincode + code).\n  exists bbits.\n  exists (xbits ++ l'').\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H7.\n  trivial.\n  trivial.\nDefined.\n\nLemma CommonCodeLengthsSWBRlen : forall clc n inp out,\n                                   CommonCodeLengthsSWBR clc n out inp ->\n                                   n = brlen out.\nProof.\n  intros clc n inp out cswbr.\n  induction cswbr.\n  reflexivity.\n  simpl.\n  omega.\n  simpl.\n  omega.\n  simpl.\n  omega.\n  simpl.\n  omega.\nQed.\n\nLemma CommonCodeLengthsSWBRStrongDec : forall clc n, StrongDec (CommonCodeLengthsSWBR clc n).\nProof.\n  intros clc n_ l_.\n  refine ((fix f l n m (mge : n <= m) {struct m} :\n             {a : SequenceWithBackRefs nat &\n                                       {l' : LB &\n                                                {l'' : LB | l = l' ++ l'' /\\ CommonCodeLengthsSWBR clc n a l'}}} +\n             string *\n             ({a : SequenceWithBackRefs nat &\n                                        {l' : LB &\n                                                 {l'' : LB | l = l' ++ l'' /\\ CommonCodeLengthsSWBR clc n a l'}}} ->\n              False)\n           := _) l_ n_ n_ (le_refl n_)).\n\n  destruct n.\n  apply inl.\n  exists (nil (A:=(nat+nat*nat))).\n  exists Bnil.\n  exists l.\n  split.\n  reflexivity.\n  constructor.\n  destruct m.\n  omega.\n\n  destruct (CompressedWithExtraBitsStrongDec clc 16 [2] [3] [6] l) as [[a [l' [l'' [lapp cweb]]]]|[reason16 no16]].\n  destruct (le_dec a (S n)) as [a_le_n|a_nle_n].\n  assert (mge' : S n - a <= m).\n  inversion cweb as [base extra code max xbitnum bbits xbits H H0 H1 H1_ H2 H3 H4 H4_ H5].\n  destruct code.\n  inversion H1.\n  omega.\n  destruct code.\n  inversion H0.\n  inversion H0.\n  destruct (f l'' (S n - a) m mge') as [[a0 [l'0 [l''0 [l'app ccls]]]]|[reason no_f]].\n  apply inl.\n  exists (inr (a, 1) :: a0).\n  exists (l' ++ l'0).\n  exists l''0.\n  split.\n  rewrite <- app_assoc.\n  rewrite <- l'app.\n  trivial.\n  replace (S n) with (S n - a + a).\n  apply cswbr16.\n  trivial.\n  trivial.\n  omega.\n\n  apply inr.\n  split.\n  exact reason.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app ccls]]]].\n  destruct ccls.\n  contradict no_f.\n  exists (nil (A:=nat+nat*nat)).\n  exists Bnil.\n  exists l''.\n  split.\n  reflexivity.\n  constructor.\n\n  destruct cweb.\n  destruct (dc_StrongUnique clc (16 + code) m0 bbits (xbits ++ l'') input (lb1 ++ l''0)).\n  rewrite -> app_assoc.\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n\n  contradict no_f.\n  destruct (CompressedWithExtraBitsStrongUnique clc 16 [2] [3] [6] a m0 l' l'' input (lb1 ++ l''0)) as [eq1 eq2].\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  trivial.\n  trivial.\n  trivial.\n  exists brs.\n  exists lb1.\n  exists l''0.\n  split.\n  apply (app_ll l' _ input _).\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  trivial.\n  f_equal.\n  trivial.\n  replace (n0 + m0 - a) with n0.\n  trivial.\n  omega.\n\n  destruct cweb as [base extra code max xbitnum bbits xbits H2 H2_ H3 H4 H5 H5_].\n  destruct H as [base0 extra0 code0 max0 xbitnum0 bbits0 xbits0 H7_ H8 H10 H10_].\n  destruct (dc_StrongUnique clc (16 + code) (17 + code0) bbits (xbits ++ l'') bbits0 (xbits0 ++ lb1 ++ l''0)) as [eq1 eq2].\n  repeat rewrite -> app_assoc.\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  \n  destruct code.\n  omega.\n  destruct code.\n  inversion H3.\n  inversion H3.\n\n  destruct cweb.\n  destruct H.\n  destruct (dc_StrongUnique clc (16 + code) (18 + code0) bbits (xbits ++ l'') bbits0 (xbits0 ++ lb1 ++ l''0)) as [eq1 eq2].\n  repeat rewrite -> app_assoc.\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  destruct code.\n  omega.\n  destruct code.\n  inversion H3.\n  inversion H3.\n\n  apply inr.\n  split.\n  exact (\"In CommonCodeLengthsSWBRStrongDec: Code 16 would produce more codes than hlit+hdist allow. (\" ++ blstring l ++ \")\")%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app ccls]]]].\n  inversion ccls.\n  destruct cweb.\n  destruct (dc_StrongUnique clc (16 + code) m0 bbits (xbits ++ l'') input (lb1 ++ l''0)) as [eq1 eq2].\n  repeat rewrite -> app_assoc.\n  rewrite -> H4.\n  rewrite <- l'app.\n  auto.\n  trivial.\n  trivial.\n  omega.\n\n  destruct (CompressedWithExtraBitsStrongUnique clc 16 [2] [3] [6] a m0 l' l'' input (lb1 ++ l''0)) as [eq1 eq2].\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n\n  destruct cweb.\n  destruct H1.\n  destruct (dc_StrongUnique clc (16 + code) (17 + code0) bbits (xbits ++ l'') bbits0 (xbits0 ++ lb1 ++ l''0)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H3.\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  destruct code.\n  omega.\n  destruct code.\n  inversion H5.\n  inversion H5.\n\n  destruct cweb.\n  destruct H1.\n  destruct (dc_StrongUnique clc (16 + code) (18 + code0) bbits (xbits ++ l'') bbits0 (xbits0 ++ lb1 ++ l''0)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H3.\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  destruct code.\n  omega.\n  destruct code.\n  inversion H5.\n  inversion H5.\n\n  destruct (CompressedWithExtraBitsStrongDec clc 17 [3] [3-1] [10-1] l) as [[a [l' [l'' [lapp cweb]]]]|[reason17 no17]].\n  destruct (le_dec (S a) (S n)) as [a_le_n|a_nle_n].\n  assert (mge' : S n - S a <= m).\n  inversion cweb.\n  destruct code.\n  inversion H1.\n  omega.\n  destruct code.\n  inversion H0.\n  inversion H0.\n  destruct (f l'' (S n - S a) m mge') as [[a0 [l'0 [l''0 [l'app ccls]]]]|[reason no_f]].\n  apply inl.\n  exists (inl 0 :: inr (a, 1) :: a0).\n  exists (l' ++ l'0).\n  exists l''0.\n  split.\n  rewrite <- app_assoc.\n  rewrite <- l'app.\n  trivial.\n  replace (S n) with (S n - S a + a + 1).\n  apply cswbr17.\n  trivial.\n  trivial.\n  omega.\n\n  apply inr.\n  split.\n  exact reason.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app ccls]]]].\n  destruct ccls.\n  contradict no_f.\n  exists (nil (A:=nat+nat*nat)).\n  exists Bnil.\n  exists l''.\n  split.\n  reflexivity.\n  constructor.\n\n  destruct cweb.\n  destruct (dc_StrongUnique clc (17 + code) m0 bbits (xbits ++ l'') input (lb1 ++ l''0)).\n  rewrite -> app_assoc.\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n\n  destruct cweb.\n  destruct H.\n  destruct (dc_StrongUnique clc (17 + code) (16 + code0) bbits (xbits ++ l'') bbits0 (xbits0 ++ lb1 ++ l''0)) as [eq1 eq2].\n  repeat rewrite -> app_assoc.\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  destruct code0.\n  omega.\n  destruct code0.\n  inversion H7.\n  inversion H7.\n\n  contradict no_f.\n  destruct (CompressedWithExtraBitsStrongUnique clc 17 [3] [3-1] [10-1] a m0 l' l'' input (lb1 ++ l''0)) as [eq1 eq2].\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  trivial.\n  trivial.\n  trivial.\n  exists brs.\n  exists lb1.\n  exists l''0.\n  split.\n  apply (app_ll l' _ input _).\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  trivial.\n  f_equal.\n  trivial.\n  replace (n0 + m0 + 1 - S a) with n0.\n  trivial.\n  omega.\n\n  destruct cweb.\n  destruct H.\n  destruct (dc_StrongUnique clc (17 + code) (18 + code0) bbits (xbits ++ l'') bbits0 (xbits0 ++ lb1 ++ l''0)) as [eq1 eq2].\n  repeat rewrite -> app_assoc.\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  destruct code.\n  omega.\n  destruct code.\n  inversion H1.\n  inversion H1.\n\n  apply inr.\n  split.\n  exact (\"In CommonCodeLengthsSWBRStrongDec: Code 17 would produce more codes than hlit+hdist allow. (\" ++ blstring l ++ \")\")%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app ccls]]]].\n  inversion ccls.\n  destruct cweb.\n  destruct (dc_StrongUnique clc (17 + code) m0 bbits (xbits ++ l'') input (lb1 ++ l''0)) as [eq1 eq2].\n  repeat rewrite -> app_assoc.\n  rewrite -> H4.\n  rewrite <- l'app.\n  auto.\n  trivial.\n  trivial.\n  omega.\n\n  destruct cweb.\n  destruct H1.\n  destruct (dc_StrongUnique clc (17 + code) (16 + code0) bbits (xbits ++ l'') bbits0 (xbits0 ++ lb1 ++ l''0)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H3.\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  destruct code0.\n  omega.\n  destruct code0.\n  inversion H11.\n  inversion H11.\n\n  destruct (CompressedWithExtraBitsStrongUnique clc 17 [3] [3-1] [10-1] a m0 l' l'' input (lb1 ++ l''0)) as [eq1 eq2].\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n\n  destruct cweb.\n  destruct H1.\n  destruct (dc_StrongUnique clc (17 + code) (18 + code0) bbits (xbits ++ l'') bbits0 (xbits0 ++ lb1 ++ l''0)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H3.\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  destruct code.\n  omega.\n  destruct code.\n  inversion H5.\n  inversion H5.\n\n  destruct (CompressedWithExtraBitsStrongDec clc 18 [7] [11-1] [138-1] l) as [[a [l' [l'' [lapp cweb]]]]|[reason18 no18]].\n  destruct (le_dec (S a) (S n)) as [a_le_n|a_nle_n].\n  assert (mge' : S n - S a <= m).\n  inversion cweb.\n  destruct code.\n  inversion H1.\n  omega.\n  destruct code.\n  inversion H0.\n  inversion H0.\n  destruct (f l'' (S n - S a) m mge') as [[a0 [l'0 [l''0 [l'app ccls]]]]|[reason no_f]].\n  apply inl.\n  exists (inl 0 :: inr (a, 1) :: a0).\n  exists (l' ++ l'0).\n  exists l''0.\n  split.\n  rewrite <- app_assoc.\n  rewrite <- l'app.\n  trivial.\n  replace (S n) with (S n - S a + a + 1).\n  apply cswbr18.\n  trivial.\n  trivial.\n  omega.\n\n  apply inr.\n  split.\n  exact reason.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app ccls]]]].\n  destruct ccls.\n  contradict no_f.\n  exists (nil (A:=nat+nat*nat)).\n  exists Bnil.\n  exists l''.\n  split.\n  reflexivity.\n  constructor.\n\n  destruct cweb.\n  destruct (dc_StrongUnique clc (18 + code) m0 bbits (xbits ++ l'') input (lb1 ++ l''0)).\n  rewrite -> app_assoc.\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n\n  destruct cweb.\n  destruct H.\n  destruct (dc_StrongUnique clc (18 + code) (16 + code0) bbits (xbits ++ l'') bbits0 (xbits0 ++ lb1 ++ l''0)) as [eq1 eq2].\n  repeat rewrite -> app_assoc.\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  destruct code0.\n  omega.\n  destruct code0.\n  inversion H7.\n  inversion H7.\n\n  destruct cweb.\n  destruct H.\n  destruct (dc_StrongUnique clc (18 + code) (17 + code0) bbits (xbits ++ l'') bbits0 (xbits0 ++ lb1 ++ l''0)) as [eq1 eq2].\n  repeat rewrite -> app_assoc.\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  destruct code0.\n  omega.\n  destruct code0.\n  inversion H7.\n  inversion H7.\n\n  contradict no_f.\n  destruct (CompressedWithExtraBitsStrongUnique clc 18 [7] [11-1] [138-1] a m0 l' l'' input (lb1 ++ l''0)) as [eq1 eq2].\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  trivial.\n  trivial.\n  trivial.\n  exists brs.\n  exists lb1.\n  exists l''0.\n  split.\n  apply (app_ll l' _ input _).\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  trivial.\n  f_equal.\n  trivial.\n  replace (n0 + m0 + 1 - S a) with n0.\n  trivial.\n  omega.\n\n  apply inr.\n  split.\n  exact (\"In CommonCodeLengthsSWBRStrongDec: Code 18 would produce more codes than hlit+hdist allow. (\" ++ blstring l ++ \")\")%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app ccls]]]].\n  inversion ccls.\n  destruct cweb.\n  destruct (dc_StrongUnique clc (18 + code) m0 bbits (xbits ++ l'') input (lb1 ++ l''0)) as [eq1 eq2].\n  repeat rewrite -> app_assoc.\n  rewrite -> H4.\n  rewrite <- l'app.\n  auto.\n  trivial.\n  trivial.\n  omega.\n\n  destruct cweb.\n  destruct H1.\n  destruct (dc_StrongUnique clc (18 + code) (16 + code0) bbits (xbits ++ l'') bbits0 (xbits0 ++ lb1 ++ l''0)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H3.\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  destruct code0.\n  omega.\n  destruct code0.\n  inversion H11.\n  inversion H11.\n\n  destruct cweb.\n  destruct H1.\n  destruct (dc_StrongUnique clc (18 + code) (17 + code0) bbits (xbits ++ l'') bbits0 (xbits0 ++ lb1 ++ l''0)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H3.\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  destruct code0.\n  omega.\n  destruct code0.\n  inversion H11.\n  inversion H11.\n\n  destruct (CompressedWithExtraBitsStrongUnique clc 18 [7] [11-1] [138-1] a m0 l' l'' input (lb1 ++ l''0)) as [eq1 eq2].\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n\n  destruct (dc_StrongDec clc l) as [[a [l' [l'' [lapp dce]]]]|[reason no]].\n  destruct (eq_nat_dec a 16) as [a_is_16|a_isnt_16].\n  destruct (slice_list 2 l'') as [[l1 [l2 [l1app l1ll]]]|no].\n  contradict no16.\n  exists (3 + ListToNat l1).\n  exists (l' ++ l1).\n  exists l2.\n  split.\n  rewrite <- app_assoc.\n  rewrite -> l1app.\n  trivial.\n  eapply (complength _ _ _ _ _ 3 (ListToNat l1) 0 6 2 l' l1).\n  rewrite -> a_is_16 in dce.\n  auto.\n  reflexivity.\n  reflexivity.\n  trivial.\n  trivial.\n  apply ListToNat_correct.\n  assert (ListToNat l1 < 4).\n  replace 4 with (2 ^ lb l1).\n  eapply lsb_power.\n  apply ListToNat_correct.\n  rewrite -> l1ll.\n  reflexivity.\n  omega.\n  \n  apply inr.\n  split.\n  exact (\"dc_enc fail in CommonCodeLengthsSWBRStrongDec[16]: THIS SHOULD NEVER HAPPEN! (\" ++ blstring l ++ \")\")%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app cls]]]].\n  inversion cls.\n  destruct (dc_StrongUnique clc a m0 l' l'' input (lb1 ++ l''0)).\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  rewrite -> app_assoc.\n  rewrite -> H4.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n  contradict no16.\n  exists m0.\n  exists input.\n  exists (lb1 ++ l''0).\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  contradict no17.\n  exists m0.\n  exists input.\n  exists (lb1 ++ l''0).\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  contradict no18.\n  exists m0.\n  exists input.\n  exists (lb1 ++ l''0).\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n\n  destruct (eq_nat_dec a 17) as [a_is_17|a_isnt_17].\n  destruct (slice_list 3 l'') as [[l1 [l2 [l1app l1ll]]]|no].\n  contradict no17.\n  exists (3 - 1 + ListToNat l1).\n  exists (l' ++ l1).\n  exists l2.\n  split.\n  rewrite <- app_assoc.\n  rewrite -> l1app.\n  trivial.\n  apply (complength _ _ _ _ _ (3 - 1) (ListToNat l1) 0 (10 - 1) 3 l' l1).\n  rewrite -> a_is_17 in dce.\n  auto.\n  reflexivity.\n  reflexivity.\n  reflexivity.\n  trivial.\n  apply ListToNat_correct.\n  assert (ListToNat l1 < 8).\n  replace 8 with (2 ^ (lb l1)).\n  apply lsb_power.\n  apply ListToNat_correct.\n  rewrite -> l1ll.\n  reflexivity.\n  omega.\n\n  apply inr.\n  split.\n  exact (\"dc_enc fail in CommonCodeLengthsSWBRStrongDec[17]: THIS SHOULD NEVER HAPPEN! (\" ++ blstring l ++ \")\")%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app cls]]]].\n  inversion cls.\n  destruct (dc_StrongUnique clc a m0 l' l'' input (lb1 ++ l''0)).\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  rewrite -> app_assoc.\n  rewrite -> H4.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n  contradict no16.\n  exists m0.\n  exists input.\n  exists (lb1 ++ l''0).\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  contradict no17.\n  exists m0.\n  exists input.\n  exists (lb1 ++ l''0).\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  contradict no18.\n  exists m0.\n  exists input.\n  exists (lb1 ++ l''0).\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n\n  destruct (eq_nat_dec a 18) as [a_is_18|a_isnt_18].\n  destruct (slice_list 7 l'') as [[l1 [l2 [l1app l1ll]]]|no].\n  contradict no18.\n  exists (11 - 1 + ListToNat l1).\n  exists (l' ++ l1).\n  exists l2.\n  split.\n  rewrite <- app_assoc.\n  rewrite -> l1app.\n  trivial.\n  apply (complength _ _ _ _ _ (11 - 1) (ListToNat l1) 0 (138 - 1) 7 l' l1).\n  rewrite -> a_is_18 in dce.\n  auto.\n  reflexivity.\n  reflexivity.\n  reflexivity.\n  trivial.\n  apply ListToNat_correct.\n  assert (ListToNat l1 < 128).\n  replace 128 with (2 ^ lb l1).\n  apply lsb_power.\n  apply ListToNat_correct.\n  rewrite -> l1ll.\n  reflexivity.\n  omega.\n\n  apply inr.\n  split.\n  exact (\"dc_enc fail in CommonCodeLengthsSWBRStrongDec[18]: THIS SHOULD NEVER HAPPEN! (\" ++ blstring l ++ \")\")%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app cls]]]].\n  inversion cls.\n  destruct (dc_StrongUnique clc a m0 l' l'' input (lb1 ++ l''0)).\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  rewrite -> app_assoc.\n  rewrite -> H4.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n  contradict no16.\n  exists m0.\n  exists input.\n  exists (lb1 ++ l''0).\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  contradict no17.\n  exists m0.\n  exists input.\n  exists (lb1 ++ l''0).\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  contradict no18.\n  exists m0.\n  exists input.\n  exists (lb1 ++ l''0).\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n\n  assert (a < 19).\n  apply (dc_max clc a l').\n  trivial.\n\n  (* ok. now we need to show a < 16 *)\n  assert (a_lt_16 : a < 16).\n  omega.\n  destruct (f l'' n m) as [[a0 [l'0 [l''0 [l'app clsw]]]]|[reason no_f]].\n  omega.\n  apply inl.\n  exists (inl a :: a0).\n  exists (l' ++ l'0).\n  exists l''0.\n  split.\n  rewrite <- app_assoc.\n  rewrite <- l'app.\n  trivial.\n  replace (S n) with (n + 1).\n  constructor.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n\n  apply inr.\n  split.\n  apply reason.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app cswbr]]]].\n  inversion cswbr.\n  contradict no_f.\n  exists brs.\n  exists lb1.\n  exists l''0.\n  split.\n  apply (app_ll l' _ input _).\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  rewrite -> H5.\n  trivial.\n  destruct (dc_StrongUnique clc a m0 l' l'' input (lb1 ++ l''0)).\n  rewrite <- lapp.\n  rewrite -> app_assoc.\n  rewrite -> H5.\n  trivial.\n  trivial.\n  trivial.\n  f_equal.\n  trivial.\n  replace n with n0.\n  trivial.\n  omega.\n  destruct H2.\n  destruct (dc_StrongUnique clc a (16 + code) l' l'' bbits (xbits ++ lb1 ++ l''0)).\n  rewrite <- lapp.\n  repeat rewrite -> app_assoc.\n  rewrite -> H4.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n  destruct H2.\n  destruct (dc_StrongUnique clc a (17 + code) l' l'' bbits (xbits ++ lb1 ++ l''0)).\n  rewrite <- lapp.\n  repeat rewrite -> app_assoc.\n  rewrite -> H4.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n  destruct H2.\n  destruct (dc_StrongUnique clc a (18 + code) l' l'' bbits (xbits ++ lb1 ++ l''0)).\n  rewrite <- lapp.\n  repeat rewrite -> app_assoc.\n  rewrite -> H4.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n\n  apply inr.\n  split.\n  exact (\"In CommonCodeLengthsSWBRStrongDec[<16]: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [l'app cswbr]]]].\n  inversion cswbr.\n  contradict no.\n  exists m0.\n  exists input.\n  exists (lb1 ++ l'').\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H4.\n  trivial.\n  trivial.\n\n  destruct H1.\n  contradict no.\n  exists (16 + code).\n  exists bbits.\n  exists (xbits ++ lb1 ++ l'').\n  split.\n  repeat rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  destruct H1.\n  contradict no.\n  exists (17 + code).\n  exists bbits.\n  exists (xbits ++ lb1 ++ l'').\n  split.\n  repeat rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  destruct H1.\n  contradict no.\n  exists (18 + code).\n  exists bbits.\n  exists (xbits ++ lb1 ++ l'').\n  split.\n  repeat rewrite -> app_assoc.\n  rewrite -> H3.\n  trivial.\n  trivial.\nDefined.\n\nLemma CommonCodeLengthsSWBRStrongUnique : forall clc n, StrongUnique (CommonCodeLengthsSWBR clc n).\nProof.\n  intros clc n_.\n  refine ((fix f n m0 (le : n <= m0) {struct m0} : StrongUnique (CommonCodeLengthsSWBR clc n) := _) n_ n_ (le_refl n_)).\n\n  intros a b la las lb lbs apps csa csb.\n  inversion csa.\n  inversion csb.\n  auto.\n  omega.\n  replace m with 0 in H3.\n  inversion H3.\n  destruct code.\n  inversion H10.\n  omega.\n  destruct code.\n  inversion H10.\n  inversion H10.\n  omega.\n  replace m with 0 in H3.\n  inversion H3.\n  destruct code.\n  inversion H10.\n  omega.\n  destruct code.\n  inversion H10.\n  inversion H10.\n  omega.\n  replace m with 0 in H3.\n  inversion H3.\n  destruct code.\n  inversion H10.\n  omega.\n  destruct code.\n  inversion H10.\n  inversion H10.\n  omega.\n\n  inversion csb.\n  omega.\n  destruct (dc_StrongUnique clc m1 m input0 (lb0 ++ lbs) input (lb1 ++ las)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H10.\n  rewrite -> H4.\n  auto.\n  trivial.\n  trivial.\n  destruct m0.\n  omega.\n  assert (le' : n0 <= m0).\n  omega.\n  destruct (f n0 m0 le' brs0 brs lb0 lbs lb1 las) as [A B].\n  apply (app_ll input0 _ input _).\n  repeat rewrite -> app_assoc.\n  rewrite -> H10.\n  rewrite -> H4.\n  auto.\n  rewrite -> H12.\n  reflexivity.\n  replace n0 with n1.\n  trivial.\n  omega.\n  trivial.\n  rewrite -> A.\n  rewrite -> B.\n  rewrite -> H12.\n  rewrite -> H11.\n  auto.\n\n  destruct H6.\n  destruct (dc_StrongUnique clc m (16 + code) input (lb1 ++ las) bbits (xbits ++ lb0 ++ lbs)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H9.\n  rewrite -> H4.\n  auto.\n  trivial.\n  trivial.\n  omega.\n  destruct H6.\n  destruct (dc_StrongUnique clc m (17 + code) input (lb1 ++ las) bbits (xbits ++ lb0 ++ lbs)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H9.\n  rewrite -> H4.\n  auto.\n  trivial.\n  trivial.\n  omega.\n  destruct H6.\n  destruct (dc_StrongUnique clc m (18 + code) input (lb1 ++ las) bbits (xbits ++ lb0 ++ lbs)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H9.\n  rewrite -> H4.\n  auto.\n  trivial.\n  trivial.\n  omega.\n\n  destruct m0.\n  replace m with 0 in H0.\n  inversion H0.\n  destruct code.\n  inversion H7.\n  omega.\n  destruct code.\n  inversion H6.\n  inversion H6.\n  omega.\n\n  inversion csb.\n  replace m with 0 in H0.\n  inversion H0.\n  destruct code.\n  inversion H10.\n  omega.\n  destruct code.\n  inversion H9.\n  inversion H9.\n  omega.\n\n  destruct H0.\n  destruct (dc_StrongUnique clc (16 + code) m1 bbits (xbits ++ lb1 ++ las) input0 (lb0 ++ lbs)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H9.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n\n  destruct (CompressedWithExtraBitsStrongUnique clc 16 [2] [3] [6] m m1 input (lb1 ++ las) input0 (lb0 ++ lbs)) as [web1 web2].\n  repeat rewrite -> app_assoc.\n  rewrite -> H8.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n\n  destruct m.\n  replace m1 with 0 in H5.\n  inversion H5.\n  destruct code.\n  inversion H12.\n  omega.\n  destruct code.\n  inversion H12.\n  inversion H12.\n\n  assert (le' : n0 <= m0).\n  omega.\n  destruct (f n0 m0 le' brs brs0 lb1 las lb0 lbs) as [H9 H10].\n  apply (app_ll input _ input0 _).\n  repeat rewrite -> app_assoc.\n  rewrite -> H8.\n  rewrite -> H3.\n  auto.\n  f_equal.\n  auto.\n  trivial.\n  replace n0 with n1.\n  trivial.\n  omega.\n\n  rewrite -> web1.\n  rewrite -> web2.\n  rewrite -> H9.\n  rewrite -> H10.\n\n  auto.\n\n  destruct H0.\n  destruct H5.\n  destruct (dc_StrongUnique clc (16 + code) (17 + code0) bbits (xbits ++ lb1 ++ las) bbits0 (xbits0 ++ lb0 ++ lbs)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H8.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n  destruct code.\n  omega.\n  destruct code.\n  inversion H9.\n  inversion H9.\n\n  destruct H0.\n  destruct H5.\n  destruct (dc_StrongUnique clc (16 + code) (18 + code0) bbits (xbits ++ lb1 ++ las) bbits0 (xbits0 ++ lb0 ++ lbs)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H8.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n  destruct code.\n  omega.\n  destruct code.\n  inversion H9.\n  inversion H9.\n\n  inversion csb.\n  replace m with 0 in H0.\n  inversion H0.\n  destruct code.\n  inversion H10.\n  omega.\n  destruct code.\n  inversion H9.\n  inversion H9.\n  omega.\n\n  destruct H0.\n  destruct (dc_StrongUnique clc (17 + code) m1 bbits (xbits ++ lb1 ++ las) input0 (lb0 ++ lbs)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H9.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n\n  destruct H0.\n  destruct H5.\n  destruct (dc_StrongUnique clc (17 + code) (16 + code0) bbits (xbits ++ lb1 ++ las) bbits0 (xbits0 ++ lb0 ++ lbs)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H8.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n  destruct code0.\n  omega.\n  destruct code0.\n  inversion H15.\n  inversion H15.\n\n  destruct (CompressedWithExtraBitsStrongUnique clc 17 [3] [3-1] [10-1] m m1 input (lb1 ++ las) input0 (lb0 ++ lbs)) as [web1 web2].\n  repeat rewrite -> app_assoc.\n  rewrite -> H8.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n\n  destruct m0.\n  omega.\n  destruct m.\n  replace m1 with 0 in H5.\n  inversion H5.\n  destruct code.\n  inversion H12.\n  omega.\n  destruct code.\n  inversion H12.\n  inversion H12.\n\n  assert (le' : n0 <= m0).\n  omega.\n  destruct (f n0 m0 le' brs brs0 lb1 las lb0 lbs) as [H9 H10].\n  apply (app_ll input _ input0 _).\n  repeat rewrite -> app_assoc.\n  rewrite -> H8.\n  rewrite -> H3.\n  auto.\n  f_equal.\n  auto.\n  trivial.\n  replace n0 with n1.\n  trivial.\n  omega.\n\n  rewrite -> web1.\n  rewrite -> web2.\n  rewrite -> H9.\n  rewrite -> H10.\n\n  auto.\n\n  destruct H0.\n  destruct H5.\n  destruct (dc_StrongUnique clc (17 + code) (18 + code0) bbits (xbits ++ lb1 ++ las) bbits0 (xbits0 ++ lb0 ++ lbs)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H8.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n  destruct code.\n  omega.\n  destruct code.\n  inversion H9.\n  inversion H9.\n\n  inversion csb.\n  replace m with 0 in H0.\n  inversion H0.\n  destruct code.\n  inversion H10.\n  omega.\n  destruct code.\n  inversion H9.\n  inversion H9.\n  omega.\n\n  destruct H0.\n  destruct (dc_StrongUnique clc (18 + code) m1 bbits (xbits ++ lb1 ++ las) input0 (lb0 ++ lbs)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H9.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n  omega.\n\n  destruct H0.\n  destruct H5.\n  destruct (dc_StrongUnique clc (18 + code) (16 + code0) bbits (xbits ++ lb1 ++ las) bbits0 (xbits0 ++ lb0 ++ lbs)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H8.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n  destruct code0.\n  omega.\n  destruct code0.\n  inversion H15.\n  inversion H15.\n\n  destruct H0.\n  destruct H5.\n  destruct (dc_StrongUnique clc (18 + code) (17 + code0) bbits (xbits ++ lb1 ++ las) bbits0 (xbits0 ++ lb0 ++ lbs)).\n  repeat rewrite -> app_assoc.\n  rewrite -> H8.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n  destruct code0.\n  omega.\n  destruct code0.\n  inversion H15.\n  inversion H15.\n\n  destruct (CompressedWithExtraBitsStrongUnique clc 18 [7] [11-1] [138 - 1] m m1 input (lb1 ++ las) input0 (lb0 ++ lbs)) as [web1 web2].\n  repeat rewrite -> app_assoc.\n  rewrite -> H8.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  trivial.\n\n  destruct m0.\n  omega.\n  destruct m.\n  replace m1 with 0 in H5.\n  inversion H5.\n  destruct code.\n  inversion H12.\n  omega.\n  destruct code.\n  inversion H12.\n  inversion H12.\n\n  assert (le' : n0 <= m0).\n  omega.\n  destruct (f n0 m0 le' brs brs0 lb1 las lb0 lbs) as [H9 H10].\n  apply (app_ll input _ input0 _).\n  repeat rewrite -> app_assoc.\n  rewrite -> H8.\n  rewrite -> H3.\n  auto.\n  f_equal.\n  auto.\n  trivial.\n  replace n0 with n1.\n  trivial.\n  omega.\n\n  rewrite -> web1.\n  rewrite -> web2.\n  rewrite -> H9.\n  rewrite -> H10.\n\n  auto.\nDefined.\n\nLemma CommonCodeLengthsNlen : forall clc n output input,\n                                CommonCodeLengthsN clc n output input ->\n                                ll output = n.\nProof.\n  intros clc n output input H.\n  destruct H as [C H H0].\n  assert (H1 : ll output = brlen C).\n  apply rbrs_brlen.\n  trivial.\n  rewrite -> H1.\n  symmetry.\n  apply (CommonCodeLengthsSWBRlen clc _ input).\n  trivial.\nQed.\n\n\nLemma CommonCodeLengthsNStrongDec : forall (clc : deflateCoding 19) (n : nat), StrongDec (CommonCodeLengthsN clc n).\nProof.\n  intros clc n l.\n  destruct (CommonCodeLengthsSWBRStrongDec clc n l) as [[a [l' [l'' [lapp cclswbr]]]]|[reason no]].\n  destruct (ResolveBackReferencesDec a) as [[out rbr]|no].\n  apply inl.\n  exists out.\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  exact (ccl clc n out l' a cclswbr rbr).  \n  apply inr.\n  split.\n  exact \"In CommonCodeLengthsNStrongDec: Illegal Back-Reference.\"%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app cclN]]]].\n  inversion cclN.\n  contradict no.\n  assert (Ca : C = a).\n  apply (CommonCodeLengthsSWBRStrongUnique clc n C a l'0 l''0 l' l'').\n  rewrite <- l'app.\n  trivial.\n  trivial.\n  trivial.\n  rewrite -> Ca in H0.\n  exists a0.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In CommonCodeLengthsNStrongDec: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp cclN]]]].\n  inversion cclN.\n  contradict no.\n  exists C.\n  exists l'.\n  exists l''.\n  firstorder.\nDefined.\n\nLemma CommonCodeLengthsNStrongUnique : forall (clc : deflateCoding 19) (n : nat), StrongUnique (CommonCodeLengthsN clc n).\nProof.\n  intros clc n a b la las lb lbs apps ccla cclb.\n  inversion ccla.\n  inversion cclb.\n  assert (X : C = C0 /\\ la = lb).\n  apply (CommonCodeLengthsSWBRStrongUnique clc n C C0 la las lb lbs).\n  trivial.\n  trivial.\n  trivial.\n  destruct X as [cc0 ab].\n  split.\n  apply (ResolveBackReferencesUnique C a b).\n  trivial.\n  rewrite -> cc0.\n  trivial.\n  trivial.\nDefined.\n\nLemma SplitCodeLengthsStrongUnique : forall clc hlit hdist, StrongUnique (fun x => SplitCodeLengths clc hlit hdist (fst x) (snd x)).\nProof.\n  intros clc hlit hdist a b la las lb lbs apps scla sclb.\n  inversion scla.\n  inversion sclb.\n\n  destruct (CommonCodeLengthsNStrongUnique clc (hlit + hdist) (litlenL ++ distL) (litlenL0 ++ distL0) la las lb lbs apps) as [A B].\n  trivial.\n  trivial.\n  destruct (app_ll litlenL distL litlenL0 distL0 A) as [C D].\n  rewrite -> H.\n  auto.\n  split.\n  destruct a as [a1 a2].\n  destruct b as [b1 b2].\n  unfold fst in H6.\n  unfold fst in H1.\n  assert (X : a1 = b1).\n  apply to_list_inj.\n  rewrite -> H1.\n  rewrite -> H6.\n  rewrite -> C.\n  assert (E : lm = lm0).\n  assert (ll litlenL + lm = 288).\n  rewrite <- (to_list_length a1).\n  replace lm with (ll (repeat lm 0)).\n  rewrite <- app_length.\n  rewrite <- H1.\n  reflexivity.\n  apply rep_length.\n  assert (ll litlenL0 + lm0 = 288).\n  rewrite <- (to_list_length b1).\n  replace lm0 with (ll (repeat lm0 0)).\n  rewrite <- app_length.\n  rewrite <- H6.\n  reflexivity.\n  apply rep_length.\n  omega.\n\n  rewrite -> E.\n  reflexivity.\n\n  assert (Y : a2 = b2).\n  apply to_list_inj.\n  unfold snd in H2.\n  rewrite -> H2.\n  unfold snd in H7.\n  rewrite -> H7.\n  assert (G : ld = ld0).\n  assert (ll distL + ld = 32).\n  rewrite <- (to_list_length a2).\n  replace ld with (ll (repeat ld 0)).\n  rewrite <- app_length.\n  rewrite <- H2.\n  reflexivity.\n  apply rep_length.\n  assert (ll distL0 + ld0 = 32).\n  rewrite <- (to_list_length b2).\n  replace ld0 with (ll (repeat ld0 0)).\n  rewrite <- app_length.\n  rewrite <- H7.\n  reflexivity.\n  apply rep_length.\n  omega.\n  rewrite -> D.\n  rewrite -> G.\n  reflexivity.\n  rewrite -> X.\n  rewrite -> Y.\n  reflexivity.\n  exact B.\nDefined.\n\nLemma SplitCodeLengthsStrongDec : forall clc hlit hdist, StrongDec (fun x => SplitCodeLengths clc hlit hdist (fst x) (snd x)).\nProof.\n  intros clc hlit hdist l.\n  destruct (le_dec hlit 288) as [hlit_le_288 | hlit_nle_288].\n  destruct (le_dec hdist 32) as [dist_le_32 | dist_nle_32].\n\n  destruct (CommonCodeLengthsNStrongDec clc (hlit + hdist) l) as [[a [l' [l'' [lapp ccn]]]]|[reason noccn]].\n  assert (lens : ll a = hlit + hdist).\n  apply (CommonCodeLengthsNlen clc (hlit + hdist) a l' ccn).\n  assert (hlitl : hlit <= ll a).\n  omega.\n  destruct (slice_list_le _ _ hlitl) as [l1 [l2 [l1app slc]]].\n  set (litlen' := of_list (l1 ++ repeat (288 - hlit) 0)).\n  assert (litleneq : ll (l1 ++ repeat (288 - hlit) 0) = 288).\n  rewrite -> app_length.\n  rewrite -> slc.\n  rewrite -> rep_length.\n  omega.\n  set (dist' := of_list (l2 ++ repeat (32 - hdist) 0)).\n  assert (disteq : ll (l2 ++ repeat (32 - hdist) 0) = 32).\n  rewrite -> app_length.\n  assert (slc' : ll l2 = hdist).\n  rewrite <- l1app in lens.\n  rewrite -> app_length in lens.\n  omega.\n  rewrite -> slc'.\n  rewrite -> rep_length.\n  omega.\n  apply inl.\n  exists (vec_id litleneq litlen', vec_id disteq dist').\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  unfold fst.\n  unfold snd.\n  apply (makeSplitCodeLengths _ _ _ _ _ _ l1 l2 (288 - hlit) (32 - hdist)).\n  trivial.\n  trivial.\n  rewrite <- l1app in lens.\n  rewrite -> app_length in lens.\n  omega.\n  unfold litlen'.\n  dependent destruction litleneq.\n  rewrite -> vec_id_destroy.\n  rewrite -> to_list_of_list_opp.\n  rewrite -> app_length.\n  rewrite -> rep_length.\n  rewrite -> slc.\n  replace (hlit + (288 - hlit) - hlit) with (288 - hlit).\n  reflexivity.\n  omega.\n  unfold dist'.\n  dependent destruction disteq.\n  rewrite -> vec_id_destroy.\n  rewrite -> to_list_of_list_opp.\n  rewrite -> app_length.\n  rewrite -> rep_length.\n  replace (ll l2 + (32 - hdist) - hdist) with (32 - hdist).\n  reflexivity.\n  rewrite <- l1app in lens.\n  rewrite -> app_length in lens.\n  omega.\n  rewrite -> l1app.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In SplitCodeLengthsStrongDec: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp scl]]]].\n  inversion scl.\n  contradict noccn.\n  exists (litlenL ++ distL).\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In SplitCodeLengthsStrongDec: dist is not <= 32 : THIS SHOULD NEVER HAPPEN! (\" ++ blstring l ++ \")\")%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp scl]]]].\n  inversion scl.\n  assert (ll (to_list (snd a)) = hdist + ld).\n  rewrite -> H2.\n  rewrite <- H0.\n  rewrite -> app_length.\n  rewrite -> rep_length.\n  reflexivity.\n  rewrite -> to_list_length in H4.\n  omega.\n  apply inr.\n  split.\n  exact (\"In SplitCodeLengthsStrongDec: hlit is not <= 32 : THIS SHOULD NEVER HAPPEN! (\" ++ blstring l ++ \")\")%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp scl]]]].\n  inversion scl.\n  assert (ll (to_list (fst a)) = hlit + lm).\n  rewrite -> H1.\n  rewrite <- H.\n  rewrite -> app_length.\n  rewrite -> rep_length.\n  reflexivity.\n  rewrite -> to_list_length in H4.\n  omega.\nQed.\n\nTheorem LitLenDistStrongUnique : forall clc hlit hdist,\n                                 StrongUnique (fun l => LitLenDist clc hlit hdist (fst l) (snd l)).\nProof.\n  intros clc hlit hdist a b l1 l1s l2 l2s apps H0 H1.\n  destruct a as [litlen1 dist1].\n  destruct b as [litlen2 dist2].\n  unfold fst in H0.\n  unfold snd in H0.\n  unfold fst in H1.\n  unfold snd in H1.\n  inversion H0.\n  inversion H1.\n  destruct (SplitCodeLengthsStrongUnique clc hlit hdist\n                                       ((Vmap lb (C 288 litlen1)),(Vmap lb (C 32 dist1)))\n                                       ((Vmap lb (C 288 litlen2)),(Vmap lb (C 32 dist2))) l1 l1s l2 l2s).\n  trivial.\n  unfold fst.\n  unfold snd.\n  trivial.\n  unfold fst.\n  unfold snd.\n  trivial.\n  inversion H3.\n  split.\n  assert (X : litlen1 = litlen2).\n  apply uniqueness.\n  auto.\n  assert (Y : dist1 = dist2).\n  apply uniqueness.\n  auto.\n  rewrite -> X.\n  rewrite -> Y.\n  reflexivity.\n  trivial.\nDefined.\n\nTheorem LitLenDistStrongDec : forall clc hlit hdist, StrongDec (fun x => LitLenDist clc hlit hdist (fst x) (snd x)).\nProof.\n  intros clc hlit dist l.\n  destruct (SplitCodeLengthsStrongDec clc hlit dist l) as [[a [l' [l'' [lapp scl]]]]|[reason no]].\n  destruct ((Qlt_le_dec 1 (kraft_nvec (fst a)))%Q).\n\n  apply inr.\n  split.\n  exact (\"In LitLenDistStrongDec: Lit/Len code lengths do not satisfy kraft's inequality.(\" ++ blstring l ++ \")\")%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app litlendist]]]].\n  inversion litlendist.\n  assert (L : Vmap lb (C _ (fst a0)) = fst a).\n  destruct (SplitCodeLengthsStrongUnique clc hlit dist\n                                    ((Vmap lb (C 288 (fst a0))), (Vmap lb (C 32 (snd a0))))\n                                    ((fst a), (snd a))\n                                    l'0 l''0 l' l'').\n  rewrite <- l'app.\n  trivial.\n  exact H.\n  exact scl.\n  inversion H0.\n  reflexivity.\n  assert (Q : (1 >= kraft_nvec (fst a))%Q).\n  rewrite <- L.\n  apply kraft_ineq.\n  exact (Qlt_not_le _ _ q Q).\n\n  destruct ((Qlt_le_dec 1 (kraft_nvec (snd a)))%Q).\n  apply inr.\n  split.\n  exact (\"In LitLenDistStrongDec: Distance code lengths do not satisfy kraft's inequality.(\" ++ blstring l ++ \")\")%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app litlendist]]]].\n  assert (L : Vmap lb (C _ (snd a0)) = snd a).\n  destruct (SplitCodeLengthsStrongUnique clc hlit dist\n                                    ((Vmap lb (C 288 (fst a0))), (Vmap lb (C 32 (snd a0))))\n                                    ((fst a), (snd a))\n                                    l'0 l''0 l' l'').\n  rewrite <- l'app.\n  trivial.\n  inversion litlendist.\n  exact H.\n  exact scl.\n  inversion H.\n  reflexivity.\n  assert (Q : (1 >= kraft_nvec (snd a))%Q).\n  rewrite <- L.\n  apply kraft_ineq.\n  exact (Qlt_not_le _ _ q0 Q).\n  apply inl.\n  destruct (existence _ _ q) as [D1 M1].\n  destruct (existence _ _ q0) as [D2 M2].\n  exists (D1, D2).\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  constructor.\n  unfold fst.\n  unfold snd.\n  rewrite <- M1.\n  rewrite <- M2.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In LitLenDistStrongDec: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp litlendist]]]].\n  contradict no.\n  inversion litlendist.\n  exists ((Vmap lb (C 288 (fst a))), (Vmap lb (C 32 (snd a)))).\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  exact H.\nDefined.\n\n(* TODO : use this in the above proofs, where the same situation frequently occurs *)\nLemma prefix_lemma : forall {m} (coding : deflateCoding m) a b c x y,\n                       dc_enc coding a x -> dc_enc coding b y -> prefix x c -> prefix y c -> a = b /\\ x = y.\nProof.\n  intros.\n  destruct (eq_nat_dec a b).\n  split.\n  exact e.\n  rewrite -> e in H.\n  destruct H.\n  destruct H0.\n  destruct (vnth_is_correct _ _ _ H) as [K L].\n  destruct (vnth_is_correct _ _ _ H0) as [M N].\n  assert (KM : of_nat_lt M = of_nat_lt K).\n  apply of_nat_ext.\n  rewrite <- KM in L.\n  rewrite -> L in N.\n  exact N.\n  destruct (prefix_common x y c H1 H2).\n  contradict p.\n  apply (prefix_free' coding a b).\n  exact n.\n  exact H.\n  exact H0.\n  contradict p.\n  apply (prefix_free' coding b a).\n  auto.\n  exact H0.\n  exact H.\nDefined.\n\nTheorem CompressedSWBRStrongUnique : forall litlen dist, StrongUnique (CompressedSWBR litlen dist).\nProof.\n  intros litlen dist a b la las lb lbs apps cswbr1 cswbr2.\n  revert b lb cswbr2 las lbs apps.\n  dependent induction cswbr1.\n  intros b lb cswbr2.\n  dependent destruction cswbr2.\n  intros las lbs apps.\n  split.\n  reflexivity.\n  apply (dc_StrongUnique litlen 256 256 l las l0 lbs).\n  trivial.\n  trivial.\n  trivial.\n\n  intros las lbs apps.\n  destruct (prefix_lemma litlen 256 (ByteToNat n) (l ++ las) l l0) as [K1 K2].\n  trivial.\n  trivial.\n  exists las.\n  reflexivity.\n  exists (prev_lb ++ lbs).\n  rewrite -> app_assoc.\n  auto.\n  assert (K3 : ByteToNat n < 256).\n  apply ByteToNatMax.\n  omega.\n\n  intros las lbs apps.\n  dependent destruction H0.\n  destruct (prefix_lemma litlen 256 (257 + code) (l ++ las) l bbits) as [K1 K2].\n  trivial.\n  trivial.\n  exists las.\n  reflexivity.\n  exists (xbits ++ dbits ++ prev_lb ++ lbs).\n  rewrite -> apps.\n  repeat (rewrite <- app_assoc; try reflexivity).\n  abstract(omega).\n\n  intros b lb cswbr2.\n  dependent destruction cswbr2.\n  intros las lbs apps.\n  destruct (prefix_lemma litlen 256 (ByteToNat n) ((l ++ prev_lb) ++ las) l0 l) as [K1 K2].\n  exact H0.\n  exact H.\n  rewrite -> apps.\n  exists lbs.\n  reflexivity.\n  exists (prev_lb ++ las).\n  apply app_assoc.\n  assert (K3 : ByteToNat n < 256).\n  apply ByteToNatMax.\n  omega.\n\n  intros las lbs apps.\n  destruct (prefix_lemma litlen (ByteToNat n) (ByteToNat n0) ((l ++ prev_lb) ++ las) l l0) as [K1 K2].\n  trivial.\n  trivial.\n  exists (prev_lb ++ las).\n  apply app_assoc.\n  rewrite -> apps.\n  exists (prev_lb0 ++ lbs).\n  apply app_assoc.\n\n  assert (preveq : prev_lb = prev_lb0).\n  apply (IHcswbr1 prev_swbr0 prev_lb0 cswbr2 las lbs).\n  apply (app_ll l _ l0 _).\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  exact apps.\n  rewrite -> K2.\n  reflexivity.\n  rewrite -> preveq.\n  rewrite -> K2.\n  assert (K1' : n = n0).\n  apply ByteToNat_inj.\n  trivial.\n  rewrite -> K1'.\n  split.\n  f_equal.\n  destruct (IHcswbr1 prev_swbr0 prev_lb0 cswbr2 las lbs) as [H1 H2].\n  apply (app_ll l _ l0 _).\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  trivial.\n  rewrite -> K2.\n  reflexivity.\n  exact H1.\n  reflexivity.\n\n  dependent destruction H0.\n  intros las lbs apps.\n  destruct (prefix_lemma litlen (257 + code) (ByteToNat n) ((l ++ prev_lb) ++ las) bbits l) as [K1 K2].\n  trivial.\n  trivial.\n  rewrite -> apps.\n  exists (xbits ++ dbits ++ prev_lb0 ++ lbs).\n  repeat (rewrite -> app_assoc; try reflexivity).\n  exists (prev_lb ++ las).\n  apply app_assoc.\n  assert (ByteToNat n < 256).\n  apply ByteToNatMax.\n  omega.\n\n  dependent destruction H.\n  intros b lb swbr.\n  dependent destruction swbr.\n  intros las lbs apps.\n  destruct (prefix_lemma litlen (257 + code) 256 (l ++ lbs) bbits l) as [K1 K2].\n  trivial.\n  trivial.\n  rewrite <- apps.\n  exists (xbits ++ dbits ++ prev_lb ++ las).\n  repeat (rewrite -> app_assoc; try reflexivity).\n  exists lbs.\n  reflexivity.\n  omega.\n\n  intros las lbs apps.\n  destruct (prefix_lemma litlen (257 + code) (ByteToNat n) ((l ++ prev_lb0) ++ lbs) bbits l) as [K1 K2].\n  trivial.\n  trivial.\n  rewrite <- apps.\n  exists (xbits ++ dbits ++ prev_lb ++ las).\n  repeat (rewrite -> app_assoc; try reflexivity).\n  exists (prev_lb0 ++ lbs).\n  apply app_assoc.\n  assert (K3 : ByteToNat n < 256).\n  apply ByteToNatMax.\n  omega.\n\n  intros las lbs apps.\n  dependent destruction H7.\n  destruct (prefix_lemma litlen (257 + code0) (257 + code) (((bbits ++ xbits) ++ dbits ++ prev_lb) ++ las) bbits0 bbits) as [R A].\n  trivial.\n  trivial.\n  rewrite -> apps.\n  exists (xbits0 ++ dbits0 ++ prev_lb0 ++ lbs).\n  repeat (rewrite -> app_assoc; try reflexivity).  \n  exists (xbits ++ dbits ++ prev_lb ++ las).\n  repeat (rewrite -> app_assoc; try reflexivity).\n  assert (A' : xbits ++ dbits ++ prev_lb ++ las = xbits0 ++ dbits0 ++ prev_lb0 ++ lbs).\n  apply (app_ll bbits _ bbits0 _).\n  repeat (try rewrite -> app_assoc in apps; try rewrite -> app_assoc; try exact apps).\n  rewrite -> A.\n  reflexivity.\n  assert (B : xbits = xbits0).\n  apply (app_ll _ (dbits ++ prev_lb ++ las) _ (dbits0 ++ prev_lb0 ++ lbs)).\n  exact A'.\n  assert (R' : code0 = code).\n  omega.\n  rewrite -> R' in H8.\n  rewrite -> H0 in H8.\n  inversion H8.\n  rewrite -> H11.\n  rewrite -> H3.\n  exact H16.\n  assert (B' : dbits ++ prev_lb ++ las = dbits0 ++ prev_lb0 ++ lbs).\n  apply (app_ll xbits _ xbits0 _).\n  exact A'.\n  rewrite -> B.\n  reflexivity.\n  unfold CompressedDist in H14.\n  unfold CompressedDist in H6.\n  destruct (CompressedWithExtraBitsStrongUnique dist 0 distCodeExtraBits distCodeBase distCodeMax d d0 dbits (prev_lb ++ las) dbits0 (prev_lb0 ++ lbs)) as [H11_ C].\n  exact B'.\n  trivial.\n  trivial.\n  assert (C' : prev_lb ++ las = prev_lb0 ++ lbs).\n  apply (app_ll dbits _ dbits0 _).\n  exact B'.\n  rewrite -> C.\n  reflexivity.\n  destruct (IHcswbr1 prev_swbr0 prev_lb0 swbr las lbs C') as [E D].\n  rewrite -> A.\n  rewrite -> B.\n  rewrite -> C.\n  rewrite -> D.\n  rewrite -> E.\n  rewrite -> H11_.\n  split.\n\n  assert (cc : code0 = code).\n  omega.\n  rewrite <- cc in H1.\n  rewrite -> H1 in H9.\n  inversion H9.\n  assert (G : extra = extra0).\n  apply (LSBnat_unique xbits).\n  trivial.\n  rewrite -> B.\n  trivial.\n  rewrite -> G.\n  reflexivity.\n  reflexivity.\nDefined.\n\nTheorem CompressedSWBRStrongDec: forall litlen dist, StrongDec (CompressedSWBR litlen dist).\nProof.\n  intros litlen dist l'.\n  refine ((fix f l n (ge : n >= ll l) {struct n} := _) l' (ll l') _).\n\n  destruct (dc_StrongDec litlen l) as [[a [l1 [l1b [lapp dce]]]]|[reason no]].\n  destruct (nat_compare a 256) eqn:nc.\n\n  apply inl.\n  exists (nil(A:=Byte+nat*nat)).\n  exists l1.\n  exists l1b.\n  split.\n  trivial.\n  constructor.\n  replace a with 256 in dce.\n  trivial.\n  symmetry.\n  apply nat_compare_eq.\n  trivial.\n\n  destruct n.\n  destruct dce.\n  rewrite -> lapp in ge.\n  destruct l1.\n  contradict H0.\n  reflexivity.\n  compute in ge.\n  omega.\n\n  assert (ale : a < 256).\n  apply nat_compare_lt.\n  exact nc.\n  destruct (f l1b n) as [s|[freason no]].\n  destruct l1.\n  destruct dce.\n  contradict H0.\n  reflexivity.\n  rewrite -> lapp in ge.\n  rewrite -> app_length in ge.\n  unfold ll in ge.\n  unfold ll.\n  omega.\n  destruct s as [a0 [l'0 [l'' [l1bapp cswbr]]]].\n  apply inl.\n  destruct (NatToByte a ale) as [abyte alsb].\n  exists (inl abyte :: a0).\n  exists (l1 ++ l'0).\n  exists l''.\n  split.\n  rewrite <- app_assoc.\n  rewrite <- l1bapp.\n  trivial.\n  constructor.\n  rewrite -> alsb.\n  trivial.\n  trivial.\n\n  apply inr.\n  split.\n  exact freason.\n  intro Q.\n  destruct Q as [a0 [l'0 [l'' [l1bapp cswbr]]]].\n  inversion cswbr.\n  destruct (prefix_lemma litlen a 256 l l1 l'0) as [R A].\n  trivial.\n  trivial.\n  exists l1b.\n  auto.\n  exists l''.\n  auto.\n  omega.\n\n  contradict no.\n  exists prev_swbr.\n  exists prev_lb.\n  exists l''.\n  split.\n  apply (app_ll l1 _ l0 _).\n  rewrite -> app_assoc.\n  rewrite -> H2.\n  rewrite <- l1bapp.\n  auto.\n  destruct (prefix_lemma litlen a (ByteToNat n0) l l1 l0) as [R A].\n  trivial.\n  trivial.\n  exists l1b.\n  auto.\n  exists (prev_lb ++ l'').\n  rewrite -> app_assoc.\n  rewrite -> H2.\n  auto.\n  rewrite -> A.\n  reflexivity.\n  trivial.\n\n  inversion H0.\n  destruct (prefix_lemma litlen a (257 + code) l l1 bbits) as [R A].\n  trivial.\n  trivial.\n  exists l1b.\n  auto.\n  exists (xbits ++ dbits ++ prev_lb ++ l'').\n  repeat (try rewrite -> app_assoc).\n  rewrite -> H12.\n  repeat (try rewrite -> app_assoc in H3).\n  rewrite -> H3.\n  auto.\n  omega.\n\n  assert (agt : a > 256).\n  apply nat_compare_gt.\n  exact nc.\n\n  destruct (CompressedWithExtraBitsStrongDec litlen 257 repeatCodeExtraBits repeatCodeBase repeatCodeMax l) as [[len [l'0 [l'' [l'app cweb1]]]]|[reason no]].\n  destruct (CompressedWithExtraBitsStrongDec dist 0 distCodeExtraBits distCodeBase distCodeMax l'') as [[dst [l'1 [l''1 [l''app cweb2]]]]|[reason no]].\n  destruct n.\n  destruct dce.\n  rewrite -> lapp in ge.\n  destruct l1.\n  contradict H0.\n  reflexivity.\n  compute in ge.\n  omega.\n  assert (n >= lb l''1).\n  rewrite -> l'app in ge.\n  rewrite -> l''app in ge.\n  inversion cweb1 as [base extra code max xbitnum bbits xbits H H0 H1 H1_ H2 H3 H3_ H4 H5].\n  rewrite <- H5 in ge.\n  rewrite <- app_assoc in ge.\n  destruct H.\n  destruct bbits.\n  contradict H6.\n  reflexivity.\n  assert (S n >= S (lb bbits) + lb xbits + lb l'1 + lb l''1).\n  replace (S (lb bbits)) with (lb (b :: bbits)).\n  rewrite <- app_length.\n  rewrite <- app_length.\n  rewrite <- app_length.\n  rewrite <- app_assoc.\n  rewrite <- app_assoc.\n  exact ge.\n  reflexivity.\n  omega.\n  destruct (f l''1 n) as [s | [freason no]].\n  trivial.\n  destruct s as [a0 [l'2 [l''0 [lapp2 cswbr3]]]].\n  apply inl.\n  exists (inr (len, dst) :: a0).\n  exists (l'0 ++ l'1 ++ l'2).\n  exists (l''0).\n  split.\n  rewrite <- app_assoc.\n  rewrite <- app_assoc.\n  rewrite <- lapp2.\n  rewrite <- l''app.\n  trivial.\n  constructor.\n  trivial.\n  trivial.\n  trivial.\n\n  apply inr.\n  split.\n  exact freason.\n  intro Q.\n  destruct Q as [a0 [l'2 [l''0 [lapp2 cswbr]]]].\n  inversion cswbr.\n  inversion cweb1.\n  destruct (prefix_lemma litlen a 256 l l1 l'2) as [R A].\n  trivial.\n  trivial.\n  exists l1b.\n  auto.\n  exists l''0.\n  auto.\n  omega.\n\n  destruct (prefix_lemma litlen a (ByteToNat n0) l l1 l0) as [R A].\n  trivial.\n  trivial.\n  exists l1b.\n  auto.\n  exists (prev_lb ++ l''0).\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  auto.\n  assert (ByteToNat n0 < 256).\n  apply ByteToNatMax.\n  omega.\n\n  contradict no.\n  exists prev_swbr.\n  exists prev_lb.\n  exists (l''0).\n  split.\n  apply (app_ll (l'0 ++ l'1) _ (lbits ++ dbits) _).\n  rewrite <- app_assoc.\n  rewrite <- l''app.\n  rewrite <- l'app.\n  rewrite -> app_assoc.\n  rewrite -> app_assoc in H4.\n  rewrite -> H4.\n  trivial.\n  assert (L_eq : l'0 = lbits).\n  unfold CompressedLength in H1.\n  apply (CompressedWithExtraBitsStrongUnique litlen 257 repeatCodeExtraBits repeatCodeBase repeatCodeMax len l0 l'0 l'' lbits (dbits ++ prev_lb ++ l''0)).\n  rewrite -> app_assoc in H4.\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  rewrite -> H4.\n  rewrite <- lapp2.\n  auto.\n  trivial.\n  trivial.\n  assert (R_eq : l'' = dbits ++ prev_lb ++ l''0).\n  apply (app_ll l'0 _ lbits _).\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  rewrite -> app_assoc in H4.\n  rewrite -> H4.\n  rewrite <- lapp2.\n  auto.\n  rewrite -> L_eq.\n  reflexivity.\n  assert (D_eq : l'1 = dbits).\n  unfold CompressedDist in H2.\n  apply (CompressedWithExtraBitsStrongUnique dist 0 distCodeExtraBits distCodeBase distCodeMax dst d l'1 l''1 dbits (prev_lb ++ l''0)).\n  rewrite <- l''app.\n  trivial.\n  trivial.\n  trivial.\n  rewrite -> L_eq.\n  rewrite -> D_eq.\n  reflexivity.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In CompressedSWBRStrongDec, while parsing distance code: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [a0 [l'1 [l''0 [lapp2 cswbr]]]].\n  inversion cswbr.\n  destruct (prefix_lemma litlen a 256 l l1 l'1) as [R A].\n  trivial.\n  trivial.\n  exists l1b.\n  auto.\n  exists l''0.\n  auto.\n  omega.\n\n  destruct (prefix_lemma litlen a (ByteToNat n0) l l1 l0) as [R A].\n  trivial.\n  trivial.\n  exists l1b.\n  auto.\n  exists (prev_lb ++ l''0).\n  rewrite -> app_assoc.\n  rewrite -> H2.\n  auto.\n  assert (ByteToNat n0 < 256).\n  apply ByteToNatMax.\n  omega.\n\n  contradict no.\n  exists d.\n  exists dbits.\n  exists (prev_lb ++ l''0).\n  split.\n  apply (app_ll l'0 _ lbits _).\n  rewrite <- l'app.\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  rewrite -> app_assoc in H3.\n  rewrite -> H3.\n  trivial.\n  replace l'0 with lbits.\n  reflexivity.\n  apply (CompressedWithExtraBitsStrongUnique litlen 257 repeatCodeExtraBits repeatCodeBase repeatCodeMax l0 len lbits (dbits ++ prev_lb ++ l''0) l'0 l'').\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  rewrite -> app_assoc in H3.\n  rewrite -> H3.\n  rewrite <- lapp2.\n  trivial.\n  trivial.\n  trivial.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In CompressedSWBRStrongDec, while parsing repeat code: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l'' [lapp2 cswbr]]]].\n  inversion cswbr.\n  destruct (prefix_lemma litlen a 256 l l1 l'0).\n  trivial.\n  trivial.\n  exists l1b.\n  auto.\n  exists l''.\n  auto.\n  omega.\n\n  destruct (prefix_lemma litlen a (ByteToNat n0) l l1 l0).\n  trivial.\n  trivial.\n  exists l1b.\n  auto.\n  exists (prev_lb ++ l'').\n  rewrite -> app_assoc.\n  rewrite -> H2.\n  auto.\n  assert (ByteToNat n0 < 256).\n  apply ByteToNatMax.\n  omega.\n\n  contradict no.\n  exists l0.\n  exists lbits.\n  exists (dbits ++ prev_lb ++ l'').\n  split.\n  repeat (try rewrite -> app_assoc).\n  rewrite -> app_assoc in H3.\n  rewrite -> H3.\n  auto.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In CompressedSWBRStrongDec, while parsing literal code: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l'0 [l'' [lapp cswbr]]]].\n  inversion cswbr.\n  contradict no.\n  exists 256.\n  exists l'0.\n  exists l''.\n  firstorder.\n\n  contradict no.\n  exists (ByteToNat n0).\n  exists l0.\n  exists (prev_lb ++ l'').\n  split.\n  rewrite -> app_assoc.\n  rewrite -> H2.\n  auto.\n  trivial.\n\n  inversion H0 as [base extra code max xbitnum bbits xbits H4 H5 H6 H6_ H7 H8 H8_ H9].\n  contradict no.\n  exists (257 + code).\n  exists bbits.\n  exists (xbits ++ dbits ++ prev_lb ++ l'').\n  split.\n  repeat (try rewrite -> app_assoc).\n  rewrite -> H10.\n  rewrite -> app_assoc in H3.\n  rewrite -> H3.\n  trivial.\n  trivial.\n  omega.\nDefined.\n\n\nTheorem DynamicallyCompressedHeaderStrongUniqueStrongDec :\n  StrongUnique DynamicallyCompressedHeader * StrongDec DynamicallyCompressedHeader.\nProof.\n  apply CombineStrongDecStrongUnique.\n  apply readBitsLSBStrongUnique.\n  apply readBitsLSBStrongDec.\n  intro bq.\n  apply CombineStrongDecStrongUnique.\n  apply readBitsLSBStrongUnique.\n  apply readBitsLSBStrongDec.\n  intro bq0.\n  apply CombineStrongDecStrongUnique.\n  apply readBitsLSBStrongUnique.\n  apply readBitsLSBStrongDec.\n  intro bq1.\n  apply CombineStrongDecStrongUnique.\n  apply CLCHeaderStrongUnique.\n  apply CLCHeaderStrongDec.\n  intro bq2.\n  split.\n  apply LitLenDistStrongUnique.\n  apply LitLenDistStrongDec.\nDefined.\n\nTheorem DynamicallyCompressedBlockStrongUniqueStrongDec :\n  StrongUnique DynamicallyCompressedBlock * StrongDec DynamicallyCompressedBlock.\nProof.\n  apply CombineStrongDecStrongUnique.\n  apply DynamicallyCompressedHeaderStrongUniqueStrongDec.\n  apply DynamicallyCompressedHeaderStrongUniqueStrongDec.\n  intro bq.\n  split.\n  apply CompressedSWBRStrongUnique.\n  apply CompressedSWBRStrongDec.\nDefined.\n\n\nTheorem StaticallyCompressedBlockStrongUnique : StrongUnique StaticallyCompressedBlock.\nProof.\n  intros a b la las lb lbs apps scba scbb.\n  inversion scba.\n  inversion scbb.\n  apply (CompressedSWBRStrongUnique fixed_lit_code fixed_dist_code a b la las lb lbs).\n  trivial.\n  trivial.\n  trivial.\nDefined.\n\nTheorem StaticallyCompressedBlockStrongDec : StrongDec StaticallyCompressedBlock.\nProof.\n  intro l.\n  destruct (CompressedSWBRStrongDec fixed_lit_code fixed_dist_code l) as [[a [l' [l'' [lapp cswbr]]]]|[reason no]].\n  apply inl.\n  exists a.\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  constructor.\n  trivial.\n  apply inr.\n  split.\n  exact (\"In StaticallyCompressedBlockStrongDec: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp scb]]]].\n  inversion scb.\n  contradict no.\n  exists a.\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  trivial.\nDefined.\n\nTheorem OneBlockWithPaddingStrongUnique : forall n, StrongUnique (fun out => OneBlockWithPadding out n).\nProof.\n  intros n a b la las lb lbs apps wua wub.\n  inversion wua.\n  inversion wub.\n  destruct (fst DynamicallyCompressedBlockStrongUniqueStrongDec a b dcb las dcb0 lbs) as [H5 H6].\n  apply (app_ll [false; true] _ [false; true] _).\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  replace ([false; true] ++ dcb) with la.\n  replace ([false; true] ++ dcb0) with lb.\n  trivial.\n  reflexivity.\n  trivial.\n  trivial.\n  split.\n  trivial.\n  rewrite -> H6.\n  reflexivity.\n\n  rewrite <- H1 in apps.\n  rewrite <- H4 in apps.\n  inversion apps.\n\n  rewrite <- H1 in apps.\n  rewrite <- H6 in apps.\n  inversion apps.\n\n  inversion wub.\n  rewrite <- H1 in apps.\n  rewrite <- H4 in apps.\n  inversion apps.\n\n  destruct (StaticallyCompressedBlockStrongUnique a b scb las scb0 lbs) as [scbs gcbs].\n  apply (app_ll [true; false] _ [true; false] _).\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  replace ([true; false] ++ scb) with la.\n  replace ([true; false] ++ scb0) with lb.\n  trivial.\n  reflexivity.\n  trivial.\n  trivial.\n  split.\n  trivial.\n  rewrite -> gcbs.\n  trivial.\n  rewrite <- H6 in apps.\n  rewrite <- H1 in apps.\n  inversion apps.\n  inversion wub.\n\n  rewrite <- H3 in apps.\n  rewrite <- H6 in apps.\n  inversion apps.\n\n  rewrite <- H3 in apps.\n  rewrite <- H6 in apps.\n  inversion apps.\n\n  assert (pads : pad = pad0).\n  apply (app_ll _ (ucb ++ las) _ (ucb0 ++ lbs)).\n  apply (cons_inj (a:=false) (c:=false)).\n  apply (cons_inj (a:=false) (c:=false)).\n  repeat (try rewrite -> app_comm_cons).\n  repeat (try rewrite -> app_assoc).\n  repeat (try rewrite -> app_comm_cons in H3).\n  repeat (try rewrite -> app_comm_cons in H8).\n  rewrite -> H8.\n  rewrite -> H3.\n  trivial.\n\n  replace (ll (_ :: _ :: pad)) with (S (S (ll pad))) in H0.\n  replace (ll (_ :: _ :: pad0)) with (S (S (ll pad0))) in H5.\n  omega.\n  reflexivity.\n  reflexivity.\n  destruct (fst UncompressedBlockDirectStrongUniqueStrongDec a b ucb las ucb0 lbs) as [H9 H10].\n  apply (app_ll (false :: false :: pad) _ (false :: false :: pad0)).\n  rewrite -> app_comm_cons in H8.\n  rewrite -> app_comm_cons in H8.\n  rewrite -> app_comm_cons in H3.\n  rewrite -> app_comm_cons in H3.\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  rewrite -> H8.\n  trivial.\n  rewrite -> pads.\n  reflexivity.\n  trivial.\n  trivial.\n  split.\n  trivial.\n  rewrite -> H10.\n  rewrite -> pads.\n  reflexivity.\nDefined.\n\nLemma DivisionByEightLemma : forall n,\n                               {m : nat & {o : nat | o < 8 /\\ n + o = 8 * m}}.\nProof.\n  intro n.\n  assert (H : n = 8 * (n / 8) + n mod 8).\n  apply div_mod.\n  omega.\n  destruct (eq_nat_dec (n mod 8) 0).\n  exists (n / 8).\n  exists 0.\n  split.\n  omega.\n  omega.\n  exists (n / 8 + 1).\n  exists (8 - n mod 8).\n  split.\n  assert (n mod 8 < 8).\n  apply mod_bound_pos.\n  omega.\n  omega.\n  omega.\n  assert (n mod 8 < 8).\n  apply mod_bound_pos.\n  omega.\n  omega.\n  omega.\nDefined.\n\nTheorem OneBlockWithPaddingStrongDec : forall n, StrongDec (fun out => OneBlockWithPadding out n).\nProof.\n  intros n l.\n  destruct l as [| b l].\n  apply inr.\n  split.\n  exact \"In OneBlockWithPaddingStrongDec: not enough header bits.\"%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp phail]]]].\n  inversion phail.\n  destruct l'.\n  inversion H1.\n  inversion lapp.\n  destruct l'.\n  inversion H1.\n  inversion lapp.\n  destruct l'.\n  inversion H3.\n  inversion lapp.\n\n  destruct l as [|b0 l].\n  apply inr.\n  split.\n  exact \"In OneBlockWithPaddingStrongDec: not enough header bits.\"%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp phail]]]].\n  inversion phail.\n  destruct l'.\n  inversion H1.\n  destruct l'.\n  inversion H1.\n  inversion lapp.\n  destruct l'.\n  inversion H1.\n  destruct l'.\n  inversion H1.\n  inversion lapp.\n  destruct l'.\n  inversion H3.\n  destruct l'.\n  inversion H3.\n  inversion lapp.\n\n  destruct b.\n  destruct b0.\n\n  (* true true *)\n  apply inr.\n  split.\n  exact (\"In OneBlockWithPaddingStrongDec: header bits [true; true] not allowed.(\" ++ blstring l ++ \")\")%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp phail]]]].\n  inversion phail.\n  destruct l'.\n  inversion H1.\n  destruct l'.\n  inversion H1.\n  inversion lapp.\n  rewrite <- H3 in H1.\n  rewrite <- H4 in H1.\n  inversion H1.\n  destruct l'.\n  inversion H1.\n  destruct l'.\n  inversion H1.\n  inversion lapp.\n  rewrite <- H3 in H1.\n  rewrite <- H4 in H1.\n  inversion H1.\n  destruct l'.\n  inversion H3.\n  destruct l'.\n  inversion H3.\n  inversion lapp.\n  rewrite <- H5 in H3.\n  rewrite <- H6 in H3.\n  inversion H3.\n\n  (* true false - statically compressed block - CONTRARY TO THE STANDARD *)\n  destruct (StaticallyCompressedBlockStrongDec l) as [[a [l' [l'' [lapp scba]]]]|[reason no]].\n  apply inl.\n  exists a.\n  exists (true :: false :: l').\n  exists l''.\n  split.\n  rewrite -> lapp.\n  reflexivity.\n  constructor.\n  exact scba.\n\n  apply inr.\n  split.\n  exact (\"In OneBlockWithPaddingStrongDec while parsing statically compressed block:\" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp obwp]]]].\n  inversion obwp.\n  rewrite <- H1 in lapp.\n  inversion lapp.\n  contradict no.\n  exists a.\n  exists scb.\n  exists l''.\n  split.\n  rewrite <- H1 in lapp.\n  inversion lapp.\n  reflexivity.\n  trivial.\n  rewrite <- H3 in lapp.\n  inversion lapp.\n\n  destruct b0.\n\n  (* false true - dynamically compressed block *)\n  destruct (snd DynamicallyCompressedBlockStrongUniqueStrongDec l) as [[a [l' [l'' [lapp dcba]]]]|[reason no]].\n  apply inl.\n  exists a.\n  exists (false :: true :: l').\n  exists l''.\n  split.\n  rewrite <- app_comm_cons.\n  rewrite <- app_comm_cons.\n  rewrite <- lapp.\n  reflexivity.\n  constructor.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In OneBlockWithPaddingStrongDec while parsing dynamically compressed block:\" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp obwp]]]].\n  inversion obwp.\n  contradict no.\n  exists a.\n  exists dcb.\n  exists l''.\n  split.\n  rewrite <- H1 in lapp.\n  inversion lapp.\n  reflexivity.\n  trivial.\n\n  rewrite <- H1 in lapp.\n  inversion lapp.\n  rewrite <- H3 in lapp.\n  inversion lapp.\n\n  (* false false - uncompressed block *)\n  destruct (DivisionByEightLemma (n + 2)) as [m [o [ole eql]]].\n  destruct (slice_list o l) as [[l1 [l2 [lapp ll1]]]|no].\n  destruct (snd UncompressedBlockDirectStrongUniqueStrongDec l2) as [[a [l' [l'' [l2app ucbd]]]]|[reason no]].\n  apply inl.\n  exists a.\n  exists (false :: false :: l1 ++ l').\n  exists l''.\n  split.\n  rewrite <- app_comm_cons.\n  rewrite <- app_comm_cons.\n  rewrite <- app_assoc.\n  rewrite <- l2app.\n  rewrite -> lapp.\n  reflexivity.\n  apply (obwpUCB _ _ n m).\n  trivial.\n  replace (lb (false :: false :: l1)) with (S (S (lb l1))).\n  rewrite -> ll1.\n  omega.\n  reflexivity.\n  omega.\n\n  apply inr.\n  split.\n  exact (\"In OneBlockWithPaddingStrongDec while parsing uncompressed block (after padding):\" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [l'app obwp]]]].\n  inversion obwp.\n  rewrite <- H1 in l'app.\n  inversion l'app.\n  rewrite <- H1 in l'app.\n  inversion l'app.\n  contradict no.\n  exists a.\n  exists ucb.\n  exists l''.\n  split.\n  apply (app_ll (false :: false :: l1) _ (false :: false :: pad) _).\n  rewrite -> app_assoc.\n  rewrite -> app_comm_cons in H3.\n  rewrite -> app_comm_cons in H3.\n  rewrite -> H3.\n  rewrite <- app_comm_cons.\n  rewrite <- app_comm_cons.\n  rewrite -> lapp.\n  trivial.\n  replace (lb (false :: false :: pad)) with (S (S (lb pad))) in H0.\n  replace (lb (false :: false :: pad)) with (S (S (lb pad))).\n  replace (lb (false :: false :: l1)) with (S (S (lb l1))).\n  omega.\n  reflexivity.\n  reflexivity.\n  reflexivity.\n  trivial.\n\n  apply inr.\n  split.\n  exact \"In OneBlockWithPaddingStrongDec while parsing statically compressed block: not enough padding-bits\"%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp obwp]]]].\n  inversion obwp.\n  rewrite <- H1 in lapp.\n  inversion lapp.\n  rewrite <- H1 in lapp.\n  inversion lapp.\n  contradict no.\n  exists pad.\n  exists (ucb ++ l'').\n  split.\n  apply (app_ll [false; false] _ [false; false] _).\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  rewrite -> app_comm_cons in H3.\n  rewrite -> app_comm_cons in H3.\n  replace (([false; false] ++ pad) ++ ucb) with l'.\n  auto.\n  auto.\n  replace (lb (_ :: _ :: pad)) with (S (S (lb pad))) in H0.\n  omega.\n  reflexivity.\nDefined.\n\nTheorem ManyBlocksStrongUnique : forall n, StrongUnique (ManyBlocks n).\nProof.\n  intros n a b la las lb lbs apps mba mbb.\n  revert b lb lbs apps mbb.\n  induction mba.\n  intros b lb lbs apps mbb.\n  destruct mbb.\n  destruct (OneBlockWithPaddingStrongUnique (n + 1) out out0 inp las inp0 lbs) as [A B].\n  inversion apps. \n  reflexivity.\n  trivial.\n  trivial.\n  split.\n  trivial.\n  f_equal.\n  trivial.\n  inversion apps.\n\n  intros b lb lbs apps mbb.\n  destruct mbb.\n  inversion apps.\n  destruct (OneBlockWithPaddingStrongUnique (n + 1) out1 out0 inp1 (inp2 ++ las) inp0 (inp3 ++ lbs)) as [A B].\n  rewrite -> app_comm_cons in apps.\n  rewrite <- app_assoc in apps.\n  rewrite -> app_comm_cons in apps.\n  rewrite <- app_assoc in apps.\n  rewrite <- app_comm_cons in apps.\n  rewrite <- app_comm_cons in apps.\n  inversion apps.\n  reflexivity.\n  trivial.\n  trivial.\n  assert (K : inp2 ++ las = inp3 ++ lbs).\n  apply (app_ll (false :: inp1) _ (false :: inp0) _ ).\n  rewrite -> app_assoc.\n  rewrite -> app_assoc.\n  rewrite -> app_comm_cons in apps.\n  trivial.\n  rewrite -> B.\n  reflexivity.\n  rewrite <- B in mbb.\n  destruct (IHmba _ _ lbs K mbb) as [C D].\n  rewrite -> A.\n  rewrite -> B.\n  rewrite -> C.\n  rewrite -> D.\n  auto.\nDefined.\n\nTheorem ManyBlocksStrongDec' : forall n, StrongDec (ManyBlocks n).\nProof.\n  intros n_ l_.\n  refine ((fix f n l m (eq : ll l <= m) {struct m} := _) n_ l_ (ll l_) _).\n\n  destruct l as [|b l].\n  apply inr.\n  split.\n  exact \"In ManyBlocksStrongDec': input is empty.\"%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp mb]]]].\n  destruct l'.\n  inversion mb.\n  inversion lapp.\n\n  destruct (OneBlockWithPaddingStrongDec (n + 1) l) as [[a [l' [l'' [lapp obwp]]]]|[reason no]].\n  destruct b.\n\n  (* b = true : last block *)\n  apply inl.\n  exists a.\n  exists (true :: l').\n  exists l''.\n  split.\n  rewrite <- app_comm_cons.\n  rewrite <- lapp.\n  reflexivity.\n  constructor.\n  trivial.\n\n  (* b = false : not last block *)\n  destruct m.\n  compute in eq.\n  omega.\n  assert (lm : ll l'' <= m).\n  destruct l'.\n  inversion obwp.\n  assert (S(lb l') + lb l'' <= m).\n  replace (S (lb l')) with (lb (b :: l')).\n  rewrite <- app_length.\n  rewrite <- lapp.\n  compute.\n  compute in eq.\n  omega.\n  reflexivity.\n  omega.\n  destruct (f (n + 1 + ll l') l'' m lm) as [[a0 [l'0 [l''0 [l''app mbx]]]]|[freason no]].\n  apply inl.\n  exists (a ++ a0).\n  exists (false :: l' ++ l'0).\n  exists l''0.\n  split.\n  rewrite -> lapp.\n  rewrite -> l''app.\n  rewrite -> app_comm_cons.\n  rewrite -> app_comm_cons.\n  rewrite -> app_assoc.\n  reflexivity.\n  constructor.\n  trivial.\n  trivial.\n\n  apply inr.\n  split.\n  exact freason.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app mb]]]].\n  inversion mb.\n  rewrite <- H2 in l'app.\n  inversion l'app.\n\n  contradict no.\n  exists out2.\n  exists inp2.\n  exists l''0.\n  destruct (OneBlockWithPaddingStrongUnique (n+1) a out1 l' l'' inp1 (inp2 ++ l''0)).\n  rewrite <- lapp.\n  rewrite <- H3 in l'app.\n  inversion l'app.\n  symmetry.\n  apply app_assoc.\n  trivial.\n  trivial.\n\n  split.\n  apply (app_ll (false :: l') _ (false :: inp1) _).\n  rewrite -> app_assoc.\n  rewrite -> app_comm_cons in H3.\n  rewrite -> H3.\n  rewrite <- l'app.\n  rewrite <- app_comm_cons.\n  f_equal.\n  auto.\n  rewrite -> H5.\n  reflexivity.\n  rewrite -> H5.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In ManyBlocksStrongDec': \" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [blapp mb]]]].\n  inversion mb.\n  contradict no.\n  exists a.\n  exists inp.\n  exists l''.\n  split.\n  apply (app_ll [b] _ [true]).\n  rewrite -> app_assoc.\n  replace ([true] ++ inp) with l'.\n  auto.\n  reflexivity.\n  trivial.\n  contradict no.\n  exists out1.\n  exists inp1.\n  exists (inp2 ++ l'').\n  split.\n  apply (app_ll [b] _ [false]).\n  rewrite -> app_assoc.\n  replace ([false] ++ inp1) with (false :: inp1).\n  rewrite -> app_comm_cons in H3.\n  rewrite -> app_assoc.\n  rewrite -> H3.\n  compute.\n  compute in blapp.\n  trivial.\n  auto.\n  reflexivity.\n  trivial.\n  omega.\nDefined.\n\n(** TODO: trying to postpone the concatenation to the end *)\nInductive ManyBlocks' : nat -> list (SequenceWithBackRefs Byte) -> LB -> Prop :=\n| lastBlock' : forall n inp out, OneBlockWithPadding out (n + 1) inp -> ManyBlocks' n [out] (true :: inp)\n| middleBlock' : forall n inp1 inp2 out1 out2,\n    OneBlockWithPadding out1 (n + 1) inp1 ->\n    ManyBlocks' (n + 1 + ll inp1) out2 inp2 ->\n    ManyBlocks' n (out1 :: out2) (false :: inp1 ++ inp2).\n\nLemma ManyBlocks'StrongUnique : forall n, StrongUnique (ManyBlocks' n).\nProof.\n  intro n.\n  apply StrongUniqueLemma.\n  split.\n\n  intros a b l mba.\n  revert b.\n  dependent induction mba.\n  intros b mb.\n  inversion mb.\n  f_equal.\n  apply (OneBlockWithPaddingStrongUnique (n + 1) _ _ inp [] inp [] eq_refl).\n  trivial.\n  trivial.\n\n  intros b mb'.\n  inversion mb'.\n  destruct (OneBlockWithPaddingStrongUnique (n + 1) out1 out0 inp1 inp2 inp0 inp3) as [K1 K2].\n  auto.\n  trivial.\n  trivial.\n\n  rewrite -> K1.\n  destruct (app_ll inp0 inp3 inp1 inp2) as [K3 K4].\n  trivial.\n  rewrite -> K2.\n  reflexivity.\n\n  rewrite -> (IHmba out3).\n  reflexivity.\n  rewrite <- K4.\n  rewrite <- K3.\n  trivial.\n\n  intros a b l l' mba.\n  revert l' b.\n  dependent induction mba.\n  intros l' b mbb.\n  dependent destruction mbb.\n  destruct (OneBlockWithPaddingStrongUnique (n + 1) out out0 inp l' (inp ++ l') []).\n  symmetry.\n  apply app_nil_r.\n  trivial.\n  trivial.\n  destruct (app_ll inp [] inp l').\n  rewrite -> app_nil_r.\n  trivial.\n  reflexivity.\n  auto.\n\n  intros l' b mbb.\n  dependent destruction mbb.\n\n  destruct (OneBlockWithPaddingStrongUnique (n + 1) out1 out0 inp1 (inp2 ++ l') inp0 inp3) as [O1 O2].\n  rewrite -> app_assoc.\n  auto.\n  auto.\n  auto.\n  eapply IHmba.\n  destruct (app_ll inp0 inp3 inp1 (inp2 ++ l')) as [N1 N2].\n  rewrite -> app_assoc.\n  auto.\n  f_equal.\n  auto.\n  rewrite <- N2.\n  rewrite <- N1.\n  apply mbb.\nQed.\n\nLemma ManyBlocks'StrongDec : forall n, StrongDec (ManyBlocks' n).\nProof.\n  intros n l_.\n  revert n.\n\n  refine ((fix rc l m (ml : ll l <= m) {struct m} := _) l_ (ll l_) (le_refl (ll l_))).\n\n  intro n.\n\n  destruct l as [|endp l].\n  apply inr.\n  split.\n  exact (\"In ManyBlocks'StrongDec: Got empty input sequence.\")%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp mb']]]].\n  destruct l'.\n  inversion mb'.\n  inversion lapp.\n\n  destruct m.\n  compute in ml.\n  omega.\n\n  destruct (OneBlockWithPaddingStrongDec (n + 1) l) as [[a [l' [l'' [lapp obwp]]]]|[reason no]].\n  destruct endp.\n  apply inl.\n  exists [a].\n  exists (true :: l').\n  exists l''.\n  split.\n  rewrite -> lapp.\n  rewrite -> app_comm_cons.\n  reflexivity.\n  constructor.\n  exact obwp.\n\n  assert (ml' : lb l'' <= m).\n  rewrite -> lapp in ml.\n  rewrite -> app_comm_cons in ml.\n  rewrite -> app_length in ml.\n  replace (lb (_ :: _)) with (S (lb l')) in ml.\n  omega.\n  reflexivity.\n  destruct (rc l'' m ml' (n + 1 + ll l')) as [[a0 [l'0 [l''0 [l'app mb']]]]|[reason no]].\n  apply inl.\n  exists (a :: a0).\n  exists (false :: l' ++ l'0).\n  exists l''0.\n  split.\n  rewrite -> lapp.\n  rewrite -> l'app.\n  rewrite -> app_assoc.\n  rewrite -> app_comm_cons.\n  reflexivity.\n  constructor.\n  trivial.\n  trivial.\n\n  apply inr.\n  split.\n  exact reason.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [xapp xmb]]]].\n  inversion xmb as [A B C D E F G| A B C D E F G H I J].\n\n  rewrite <- G in xapp.\n  inversion xapp.\n\n\n  destruct (OneBlockWithPaddingStrongUnique (n + 1) a D l' l'' B (C ++ l''0)) as [K L].\n  rewrite <- lapp.\n  rewrite <- J in xapp.\n  rewrite <- app_comm_cons in xapp.\n  inversion xapp.\n  symmetry.\n  apply app_assoc.\n  trivial.\n  trivial.\n  contradict no.\n  exists E.\n  exists C.\n  exists l''0.\n  split.\n  apply (app_ll (false :: l') _ (false :: B) _).\n  rewrite -> app_comm_cons in J.\n  rewrite -> app_assoc.\n  rewrite -> J.\n  rewrite <- app_comm_cons.\n  rewrite <- lapp.\n  rewrite <- xapp.\n  reflexivity.\n  rewrite -> L.\n  reflexivity.\n  rewrite -> L.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In ManyBlocks'StrongDec: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp mb]]]].\n  dependent destruction mb.\n  contradict no.\n  exists out.\n  exists inp.\n  exists l''.\n  split.\n  inversion lapp.\n  reflexivity.\n  trivial.\n  contradict no.\n  exists out1.\n  exists inp1. \n  exists (inp2 ++ l'').\n  split.\n  rewrite <- app_comm_cons in lapp.\n  rewrite -> app_assoc.\n  inversion lapp.\n  reflexivity.\n  trivial.\nQed.\n\nLemma MBMBD : forall l n lb, ManyBlocks' n l lb -> ManyBlocks n (foldlist [] (@app (Byte + nat*nat)) l) lb.\nProof.\n  induction l.\n  intros n lb mb.\n  inversion mb.\n  intros n lb mb.\n  inversion mb.\n  constructor.\n  unfold foldlist.\n  rewrite -> app_nil_r.\n  trivial.\n  constructor.\n  auto.\n  apply IHl.\n  auto.\nQed.\n\nLemma MBDMB : forall l n lb, ManyBlocks n l lb -> exists l', ManyBlocks' n l' lb.\nProof.\n  intros l n lb mb.\n  induction mb.\n  exists [out].\n  constructor.\n  trivial.\n\n  destruct IHmb as [l' mb'].\n  exists (out1 :: l').\n  constructor.\n  trivial.\n  trivial.\nQed.\n\nTheorem ManyBlocksStrongDec : forall n, StrongDec (ManyBlocks n).\nProof.\n  intros n l.\n  destruct (ManyBlocks'StrongDec n l).\n  apply inl.\n  destruct s as [a [l' [l'' [lapp mb]]]].\n  exists (foldlist [] (@app (Byte + nat*nat)) a).\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  apply MBMBD.\n  trivial.\n\n  apply inr.\n  destruct p as [reason no].\n  split.\n  exact reason.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp mb]]]].\n  destruct (MBDMB _ _ _ mb) as [l_ H].\n  contradict no.\n  exists l_.\n  exists l'.\n  exists l''.\n  split.\n  apply lapp.\n  auto.\nDefined.\n\nTheorem DeflateEncodesStrongUnique : StrongUnique DeflateEncodes.\nProof.\n  intros a b la las lb lbs apps dea deb.\n  inversion dea.\n  inversion deb.\n  destruct (ManyBlocksStrongUnique 0 swbr swbr0 la las lb lbs apps) as [A B].\n  trivial.\n  trivial.\n  split.\n  apply (ResolveBackReferencesUnique swbr).\n  trivial.\n  rewrite -> A.\n  trivial.\n  exact B.\nDefined.\n\nTheorem DeflateEncodesStrongDec : StrongDec DeflateEncodes.\nProof.\n  intro l.\n  destruct (ManyBlocksStrongDec 0 l) as [[a [l' [l'' [lapp mb]]]]|[reason no]].\n  destruct (ResolveBackReferencesDec a) as [[output rbr]| no].\n  apply inl.\n  exists output.\n  exists l'.\n  exists l''.\n  split.\n  trivial.\n  apply (deflateEncodes _ _ a mb rbr).\n\n  apply inr.\n  split.\n  exact \"In DeflateEncodesStrongDec: Illegal back-reference.\"%string.\n  intro Q.\n  destruct Q as [a0 [l'0 [l''0 [l'app denc]]]].\n  inversion denc.\n  contradict no.\n  exists a0.\n  destruct (ManyBlocksStrongUnique 0 a swbr l' l'' l'0 l''0) as [A B].\n  rewrite <- lapp.\n  trivial.\n  trivial.\n  trivial.\n  rewrite -> A.\n  trivial.\n\n  apply inr.\n  split.\n  exact (\"In DeflateEncodesStrongDec: \" ++ reason)%string.\n  intro Q.\n  destruct Q as [a [l' [l'' [lapp dce]]]].\n  inversion dce.\n  contradict no.\n  exists swbr.\n  exists l'.\n  exists l''.\n  auto.\nDefined.\n\n(*Definition DeflateTest (l : LB) :  sum (list LB) string.\n  destruct (DeflateEncodesStrongDec l) as [[o [l' [l'' ?]]]|[reason ?]].\n  apply (inl (map to_list o)).\n  apply (inr reason).\nDefined.*)\n\n(* TODO: This would not be necessary if we changed the definition of\nstrToNat in Shorthand.v, and we should do so and merge this into the\ndissertation text *)\n\nFixpoint strToNat_' (str : string) (n : nat) : option nat :=\n  match str with\n    | EmptyString => Some n\n    | String \"0\" str => strToNat_' str ((10 * n) + 0)\n    | String \"1\" str => strToNat_' str ((10 * n) + 1)\n    | String \"2\" str => strToNat_' str ((10 * n) + 2)\n    | String \"3\" str => strToNat_' str ((10 * n) + 3)\n    | String \"4\" str => strToNat_' str ((10 * n) + 4)\n    | String \"5\" str => strToNat_' str ((10 * n) + 5)\n    | String \"6\" str => strToNat_' str ((10 * n) + 6)\n    | String \"7\" str => strToNat_' str ((10 * n) + 7)\n    | String \"8\" str => strToNat_' str ((10 * n) + 8)\n    | String \"9\" str => strToNat_' str ((10 * n) + 9)\n    | _ => None\n  end.\n\nFunctional Scheme strToNat_'_ind := Induction for strToNat_' Sort Prop.\n\nFunction strToNat' (str : string) := strToNat_' str 0.\n\nLemma strToNat__ : forall str, strToNat' str = strToNat str.\nProof.\n  induction str; [reflexivity | compute; reflexivity].\nQed.\n\nFixpoint strToZ_ (str : string) (n : Z) : option Z :=\n   match str with\n     | EmptyString => Some n\n     | String \"0\" str => strToZ_ str ((10 * n) + 0)\n     | String \"1\" str => strToZ_ str ((10 * n) + 1)\n     | String \"2\" str => strToZ_ str ((10 * n) + 2)\n     | String \"3\" str => strToZ_ str ((10 * n) + 3)\n     | String \"4\" str => strToZ_ str ((10 * n) + 4)\n     | String \"5\" str => strToZ_ str ((10 * n) + 5)\n     | String \"6\" str => strToZ_ str ((10 * n) + 6)\n     | String \"7\" str => strToZ_ str ((10 * n) + 7)\n     | String \"8\" str => strToZ_ str ((10 * n) + 8)\n     | String \"9\" str => strToZ_ str ((10 * n) + 9)\n     | _ => None\n   end.\n\nFunction strToZ (strn : string) : option Z := strToZ_ strn 0.\n\nDefinition D (s : string) :=\n  forceOption Z parseError (strToZ s) ParseError.\n\nLemma dD_ : forall (strn : string) n m, strToNat_' strn n = Some m ->\n                                        Some (Z.of_nat m) = strToZ_ strn (Z.of_nat n).\nProof.\n  induction strn as [|chr strn IHstrn].\n\n  intros n m eq.\n  inversion eq.\n  reflexivity.\n\n  intros n m eq.\n\n  (* berzerk *)\n  destruct chr as [b0 b1 b2 b3 b4 b5 b6 b7].\n  destruct b0.\n  destruct b1.\n  destruct b2.\n  destruct b3.\n  inversion eq.\n  destruct b4.\n  destruct b5.\n  destruct b6.\n  inversion eq.\n  destruct b7.\n  inversion eq.\n\n  (* 7 *)\n  assert (Q : strToZ_ (String \"7\" strn) (Z.of_nat n) = strToZ_ strn (Z.of_nat (10 * n + 7)));\n  [ repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul);\n    reflexivity\n  | ].\n  rewrite -> Q.\n  apply IHstrn.\n  apply eq.\n\n  inversion eq.\n  inversion eq.\n  destruct b3.\n  inversion eq.\n  destruct b4.\n  destruct b5.\n  destruct b6.\n  inversion eq.\n  destruct b7.\n  inversion eq.\n\n  (* 3 *)\n  assert (Q : strToZ_ (String \"3\" strn) (Z.of_nat n) = strToZ_ strn (Z.of_nat (10 * n + 3)));\n  [ repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul);\n    reflexivity\n  | ].\n  rewrite -> Q.\n  apply IHstrn.\n  apply eq.\n\n  inversion eq.\n  inversion eq.\n  destruct b2.\n  destruct b3.\n  inversion eq.\n  destruct b4.\n  destruct b5.\n  destruct b6.\n  inversion eq.\n  destruct b7.\n  inversion eq.\n\n  (* 5 *)\n  assert (Q : strToZ_ (String \"5\" strn) (Z.of_nat n) = strToZ_ strn (Z.of_nat (10 * n + 5)));\n  [ repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul);\n    reflexivity\n  | ].\n  rewrite -> Q.\n  apply IHstrn.\n  apply eq.\n\n  inversion eq.\n  inversion eq.\n  destruct b3.\n  destruct b4.\n  destruct b5.\n  destruct b6.\n  inversion eq.\n  destruct b7.\n  inversion eq.\n\n  (* 9 *)\n  assert (Q : strToZ_ (String \"9\" strn) (Z.of_nat n) = strToZ_ strn (Z.of_nat (10 * n + 9)));\n  [ repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul);\n    reflexivity\n  | ].\n  rewrite -> Q.\n  apply IHstrn.\n  apply eq.\n\n  inversion eq.\n  inversion eq.\n  destruct b4.\n  destruct b5.\n  destruct b6.\n  inversion eq.\n  destruct b7.\n  inversion eq.\n\n  (* 1 *)\n  assert (Q : strToZ_ (String \"1\" strn) (Z.of_nat n) = strToZ_ strn (Z.of_nat (10 * n + 1)));\n  [ repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul);\n    reflexivity\n  | ].\n  rewrite -> Q.\n  apply IHstrn.\n  apply eq.\n\n  inversion eq.\n  inversion eq.\n  destruct b1.\n  destruct b2.\n  destruct b3.\n  inversion eq.\n  destruct b4.\n  destruct b5.\n  destruct b6.\n  inversion eq.\n  destruct b7.\n  inversion eq.\n\n  (* 6 *)\n  assert (Q : strToZ_ (String \"6\" strn) (Z.of_nat n) = strToZ_ strn (Z.of_nat (10 * n + 6)));\n  [ repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul);\n    reflexivity\n  | ].\n  rewrite -> Q.\n  apply IHstrn.\n  apply eq.\n\n  inversion eq.\n  inversion eq.\n  destruct b3.\n  inversion eq.\n  destruct b4.\n  destruct b5.\n  destruct b6.\n  inversion eq.\n  destruct b7.\n  inversion eq.\n\n  (* 2 *)\n  assert (Q : strToZ_ (String \"2\" strn) (Z.of_nat n) = strToZ_ strn (Z.of_nat (10 * n + 2)));\n  [ repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul);\n    reflexivity\n  | ].\n  rewrite -> Q.\n  apply IHstrn.\n  apply eq.\n\n  inversion eq.\n  inversion eq.\n  destruct b2.\n  destruct b3.\n  inversion eq.\n  destruct b4.\n  destruct b5.\n  destruct b6.\n  inversion eq.\n  destruct b7.\n  inversion eq.\n\n  (* 4 *)\n  assert (Q : strToZ_ (String \"4\" strn) (Z.of_nat n) = strToZ_ strn (Z.of_nat (10 * n + 4)));\n  [ repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul);\n    reflexivity\n  | ].\n  rewrite -> Q.\n  apply IHstrn.\n  apply eq.\n\n  inversion eq.\n  inversion eq.\n  destruct b3.\n  destruct b4.\n  destruct b5.\n  destruct b6.\n  inversion eq.\n  destruct b7.\n  inversion eq.\n\n  (* 8 *)\n  assert (Q : strToZ_ (String \"8\" strn) (Z.of_nat n) = strToZ_ strn (Z.of_nat (10 * n + 8)));\n  [ repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul);\n    reflexivity\n  | ].\n  rewrite -> Q.\n  apply IHstrn.\n  apply eq.\n\n  inversion eq.\n  inversion eq.\n  destruct b4.\n  destruct b5.\n  destruct b6.\n  inversion eq.\n  destruct b7.\n  inversion eq.\n\n  (* 0 *)\n  assert (Q : strToZ_ (String \"0\" strn) (Z.of_nat n) = strToZ_ strn (Z.of_nat (10 * n + 0)));\n  [ repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul);\n    reflexivity\n  | ].\n  rewrite -> Q.\n  apply IHstrn.\n  apply eq.\n\n  inversion eq.\n  inversion eq.\nQed.\n\nLemma dD : forall (strn : string) n, strToNat strn = Some n -> Some (Z.of_nat n) = strToZ strn.\nProof.\n  intros strn n eq.\n  rewrite <- strToNat__ in eq.\n  unfold strToNat' in eq.\n  unfold strToZ.\n  replace (0%Z) with (Z.of_nat 0); [ | reflexivity].\n\n  apply dD_.\n  trivial.\nQed.\n\nDefinition distCodeBase' :=\n  [ D\"1\"     ; D\"2\"     ; D\"3\"     ; D\"4\"     ;\n    D\"5\"     ; D\"7\"     ; D\"9\"     ; D\"13\"    ;\n    D\"17\"    ; D\"25\"    ; D\"33\"    ; D\"49\"    ;\n    D\"65\"    ; D\"97\"    ; D\"129\"   ; D\"193\"   ;\n    D\"257\"   ; D\"385\"   ; D\"513\"   ; D\"769\"   ;\n    D\"1025\"  ; D\"1537\"  ; D\"2049\"  ; D\"3073\"  ;\n    D\"4097\"  ; D\"6145\"  ; D\"8193\"  ; D\"12289\" ;\n    D\"16385\" ; D\"24577\" ].\n\nDefinition distCodeMax' :=\n  [ D\"1\"     ; D\"2\"     ; D\"3\"     ; D\"4\"     ;\n    D\"6\"     ; D\"8\"     ; D\"12\"    ; D\"16\"    ;\n    D\"24\"    ; D\"32\"    ; D\"48\"    ; D\"64\"    ;\n    D\"96\"    ; D\"128\"   ; D\"192\"   ; D\"256\"   ;\n    D\"384\"   ; D\"512\"   ; D\"768\"   ; D\"1024\"  ;\n    D\"1536\"  ; D\"2048\"  ; D\"3072\"  ; D\"4096\"  ;\n    D\"6144\"  ; D\"8192\"  ; D\"12288\" ; D\"16384\" ;\n    D\"24576\" ; D\"32768\" ].\n\nLemma distCodeBase'correct : map Z.of_nat distCodeBase = distCodeBase'.\nProof.\n  unfold distCodeBase.\n  unfold map.\n  unfold d.\n  unfold forceOption.\n  unfold strToNat.\n\n  repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul).\n  reflexivity.\nQed.\n\nLemma distCodeMax'correct : map Z.of_nat distCodeMax = distCodeMax'.\nProof.\n  unfold distCodeMax.\n  unfold map.\n  unfold d.\n  unfold forceOption.\n  unfold strToNat.\n\n  repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul).\n  reflexivity.\nQed.\n\nLemma LitLenBounded : forall litlen l lbits,\n                        CompressedLength litlen l lbits -> 3 <= l <= 258.\nProof.\n  intros litlen l lbits cl.\n  inversion cl as [A B C D E F G H I J K L M N O P].\n  unfold repeatCodeBase in J.\n  unfold repeatCodeMax in K.\n\n  repeat (destruct C as [|C];\n          [ compute in J;\n            compute in K;\n            inversion J;\n            inversion K;\n            abstract omega |\n            (solve [inversion J] || idtac)]).\nQed.\n\n(* TODO: Woanders. *)\nFunction oapp {A B} (f : A -> B) (g : option A) := match g with | None => None | Some a => Some (f a) end.\n\nLemma nth_error_oapp : forall {A B} (f : A -> B) n l, oapp f (nth_error l n) = nth_error (map f l) n.\nProof.\n  intros A B f n l.\n  revert f n.\n  induction l.\n  intros f n.\n  destruct n; reflexivity.\n  intros f n.\n  destruct n.\n  reflexivity.\n  apply IHl.\nQed.\n\nLemma DistBounded : forall denc dist dbits,\n                      CompressedDist denc dist dbits -> 1 <= dist <= d \"32768\".\nProof.\n  intros denc dist dbits cd.\n  inversion cd as [A B C D_ E F G H I J K L M N O P].\n  assert (B0 : (Z.of_nat B >= 0)%Z).\n  omega.\n\n  assert (Cb : oapp Z.of_nat (nth_error distCodeBase C) = nth_error distCodeBase' C).\n  rewrite <- distCodeBase'correct.\n  apply nth_error_oapp.\n\n  rewrite -> J in Cb.\n  simpl in Cb.\n  \n  assert (Cm : oapp Z.of_nat (nth_error distCodeMax C) = nth_error distCodeMax' C).\n  rewrite <- distCodeMax'correct.\n  apply nth_error_oapp.\n\n  rewrite -> K in Cm.\n  simpl in Cm.\n\n  assert (Max : Z.of_nat (d \"32768\") = D \"32768\"%string).\n  unfold d.\n  unfold D.\n  unfold forceOption.\n  unfold strToNat.\n  unfold strToZ.\n  unfold strToZ_.\n  repeat (rewrite -> Znat.Nat2Z.inj_add || rewrite -> Znat.Nat2Z.inj_mul).\n  reflexivity.\n\n  assert (1%Z <= (Z.of_nat A) + (Z.of_nat B) <= Z.of_nat (d \"32768\"))%Z.\n  rewrite -> Max.\n\n  repeat (destruct C as [|C];\n         [ inversion Cb as [Cb_];\n           rewrite -> Cb_;\n           inversion Cm as [Cm_];\n           unfold D in Cm_;\n           unfold forceOption in Cm_;\n           unfold strToZ in Cm_;\n           unfold strToZ_ in Cm_;\n           unfold D;\n           unfold forceOption;\n           unfold strToZ;\n           unfold strToZ_;\n           abstract omega | ]).\n\n  destruct C as [|C].\n  inversion Cm as [Cm_].  \n  assert (D \"24576\" <= D \"32768\")%Z; [intro Q; inversion Q|].\n  assert (Z.of_nat A + Z.of_nat B <= Z.of_nat D_)%Z.\n  omega.\n  split.\n  inversion Cb as [Cb_].\n  rewrite -> Cb_.\n  assert (1 <= D \"16385\")%Z; [intro Q; inversion Q|].\n  omega.\n  omega.\n\n  destruct C as [|C].\n  inversion Cm as [Cm_].\n  split.\n  inversion Cb as [Cb_].\n  rewrite -> Cb_.\n  assert (1 <= D \"24577\")%Z; [intro Q; inversion Q|].\n  omega.\n  omega.\n\n  destruct C as [|C].\n  inversion Cm as [Cm_].\n  inversion Cm.\n  omega.\nQed.\n\nLemma CompressedSwbrBounded : forall litlen dist swbr l,\n                                CompressedSWBR litlen dist swbr l ->\n                                BackRefsBounded 3 258 1 (d\"32768\") swbr.\nProof.\n  intros litlen dist.\n\n  induction swbr.\n  intros.\n  constructor.\n\n  intros l cswbr.\n  destruct a as [a | [a b]].\n  constructor.\n  constructor.\n  inversion cswbr as [|? l2 ? ? ? R|].\n  apply (IHswbr l2).\n  exact R.\n\n  constructor.\n  inversion cswbr.\n\n  match goal with\n    | K : CompressedDist _ _ _ |- _ => apply DistBounded in K\n  end.\n  match goal with\n    | K : CompressedLength _ _ _ |- _ => apply LitLenBounded in K\n  end.\n  constructor; omega.\n  inversion cswbr.\n  eapply IHswbr.\n  match goal with\n    | K : CompressedSWBR _ _ swbr _ |- _ => exact K\n  end.\nQed.\n\nLemma DynamicallyCompressedBlockBounded\n: forall swbr l, DynamicallyCompressedBlock swbr l ->\n                 BackRefsBounded 3 258 1 (d\"32768\") swbr.\nProof.\n  intros swbr l dcb.\n  inversion dcb.\n  match goal with\n    | K : pi2 _ _ = swbr |- _ => compute in K; rewrite <- K\n  end.\n  eapply CompressedSwbrBounded.\n  eauto.\nQed.\n\nLemma StaticallyCompressedBlockBounded\n: forall swbr l, StaticallyCompressedBlock swbr l ->\n                 BackRefsBounded 3 258 1 (d\"32768\") swbr.\nProof.\n  intros swbr l scb.\n  inversion scb.\n  eapply CompressedSwbrBounded.\n  eauto.\nQed.\n\nLemma nBytesDirectBounded : forall n l swbr, nBytesDirect n swbr l -> \n                                             BackRefsBounded 3 258 1 (d\"32768\") swbr.\nProof.\n  (********************)\n  induction n.\n  intros l swbr nbd.\n  inversion nbd as [A B].\n  rewrite -> A.\n  constructor.\n\n  intros l swbr nbd.\n  inversion nbd as [k t c d A].\n  \n  \n  inversion A.\n  constructor.\n  constructor.\n  eapply IHn.\n  eauto.\nQed.\n\nLemma UncompressedBlockDirectBounded\n: forall swbr l, UncompressedBlockDirect swbr l -> BackRefsBounded 3 258 1 (d\"32768\") swbr.\nProof.\n  intros swbr l ucb.\n  inversion ucb.\n  match goal with\n    | K : pi2 _ _ = swbr |- _ => compute in K; rewrite <- K\n  end.\n\n  match goal with\n    | K : ((readBitsLSB 16) >>= _) _ _ |- _ => inversion K\n  end.\n\n  match goal with\n    | K : _ /\\ nBytesDirect _ ?A _,\n      L : pi2 _ ?A = _ |- _ =>\n      destruct K as [K1 K2];\n        eapply nBytesDirectBounded;\n        compute in L; rewrite <- L; eauto\n  end.\nQed.\n\nLemma OneBlockWithPaddingBounded\n: forall swbr n l, OneBlockWithPadding swbr n l ->\n                   BackRefsBounded 3 258 1 (d\"32768\") swbr.\nProof.\n  intros swbr n l obwp.\n  inversion obwp.\n  eapply DynamicallyCompressedBlockBounded.\n  eauto.\n  eapply StaticallyCompressedBlockBounded.\n  eauto.\n  eapply UncompressedBlockDirectBounded.\n  eauto.\nQed.\n\nLemma ManyBlocksBounded : forall n swbr l,\n                            ManyBlocks n swbr l ->\n                            BackRefsBounded 3 258 1 (d\"32768\") swbr.\nProof.\n  intros n swbr l mb.\n  induction mb.\n  eapply OneBlockWithPaddingBounded.\n  eauto.\n  apply app_forall.\n  eapply OneBlockWithPaddingBounded.\n  eauto.\n  auto.\nQed.", "meta": {"author": "dasuxullebt", "repo": "DampFnudeL", "sha": "6b0496d0ed5af23199bf0a03e04dbb9bb0373873", "save_path": "github-repos/coq/dasuxullebt-DampFnudeL", "path": "github-repos/coq/dasuxullebt-DampFnudeL/DampFnudeL-6b0496d0ed5af23199bf0a03e04dbb9bb0373873/EncodingRelationProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.22996647376678372}}
{"text": "(*Generated by Sail from riscv_duopod.*)\nRequire Import Sail.Base.\nRequire Import Sail.Real.\nRequire Import riscv_duopod_types.\nRequire Import mem_metadata.\nRequire Import riscv_extras.\nImport ListNotations.\nOpen Scope string.\nOpen Scope bool.\nOpen Scope Z.\n\n\nDefinition is_none {a : Type} (opt : option a) : bool :=\n   match opt with | Some _ => false | None => true end.\n\nDefinition is_some {a : Type} (opt : option a) : bool :=\n   match opt with | Some _ => true | None => false end.\n\nDefinition eq_unit (_ : unit) (_ : unit) : {_bool : bool & ArithFact (_bool)} := build_ex (true).\n\nDefinition neq_int (x : Z) (y : Z) : {_bool : bool & ArithFact (Bool.eqb (negb (x =? y)) _bool)} :=\n   build_ex (negb (Z.eqb x y)).\n\nDefinition neq_bool (x : bool) (y : bool) : bool := negb (Bool.eqb x y).\n\nDefinition __id (x : Z) : {_retval : Z & ArithFact (_retval =? x)} := build_ex (x).\n\nDefinition fdiv_int (n : Z) (m : Z) : Z :=\n   if sumbool_of_bool (andb (Z.ltb n 0) (Z.gtb m 0)) then Z.sub (Z.quot (Z.add n 1) m) 1\n   else if sumbool_of_bool (andb (Z.gtb n 0) (Z.ltb m 0)) then Z.sub (Z.quot (Z.sub n 1) m) 1\n   else Z.quot n m.\n\nDefinition fmod_int (n : Z) (m : Z) : Z := Z.sub n (Z.mul m (fdiv_int n m)).\n\nDefinition concat_str_bits {n : Z} (str : string) (x : mword n) : string :=\n   String.append str (string_of_bits x).\n\nDefinition concat_str_dec (str : string) (x : Z) : string := String.append str (dec_str x).\n\n\n\nDefinition sail_mask {v0 : Z} (len : Z) (v : mword v0) `{ArithFact ((len >=? 0) && (v0 >=? 0))}\n: mword len :=\n   if sumbool_of_bool (Z.leb len (length_mword v)) then vector_truncate v len else zero_extend v len.\n\nDefinition sail_ones (n : Z) `{ArithFact (n >=? 0)} : mword n := not_vec (zeros n).\n\nDefinition slice_mask (n : Z) (i : Z) (l : Z) `{ArithFact (n >=? 0)} : mword n :=\n   if sumbool_of_bool (Z.geb l n) then shiftl (sail_ones n) i\n   else\n     let one : bits n := sail_mask n ('b\"1\"  : bits 1) in\n     shiftl (sub_vec (shiftl one l) one) i.\n\nDefinition read_kind_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 11))} : read_kind :=\n   let l__33 := arg_ in\n   if sumbool_of_bool (Z.eqb l__33 0) then Read_plain\n   else if sumbool_of_bool (Z.eqb l__33 1) then Read_reserve\n   else if sumbool_of_bool (Z.eqb l__33 2) then Read_acquire\n   else if sumbool_of_bool (Z.eqb l__33 3) then Read_exclusive\n   else if sumbool_of_bool (Z.eqb l__33 4) then Read_exclusive_acquire\n   else if sumbool_of_bool (Z.eqb l__33 5) then Read_stream\n   else if sumbool_of_bool (Z.eqb l__33 6) then Read_RISCV_acquire\n   else if sumbool_of_bool (Z.eqb l__33 7) then Read_RISCV_strong_acquire\n   else if sumbool_of_bool (Z.eqb l__33 8) then Read_RISCV_reserved\n   else if sumbool_of_bool (Z.eqb l__33 9) then Read_RISCV_reserved_acquire\n   else if sumbool_of_bool (Z.eqb l__33 10) then Read_RISCV_reserved_strong_acquire\n   else Read_X86_locked.\n\nDefinition num_of_read_kind (arg_ : read_kind) : {e : Z & ArithFact ((0 <=? e) && (e <=? 11))} :=\n   build_ex (\n      match arg_ with\n      | Read_plain => 0\n      | Read_reserve => 1\n      | Read_acquire => 2\n      | Read_exclusive => 3\n      | Read_exclusive_acquire => 4\n      | Read_stream => 5\n      | Read_RISCV_acquire => 6\n      | Read_RISCV_strong_acquire => 7\n      | Read_RISCV_reserved => 8\n      | Read_RISCV_reserved_acquire => 9\n      | Read_RISCV_reserved_strong_acquire => 10\n      | Read_X86_locked => 11\n      end\n   ).\n\nDefinition write_kind_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 10))} : write_kind :=\n   let l__23 := arg_ in\n   if sumbool_of_bool (Z.eqb l__23 0) then Write_plain\n   else if sumbool_of_bool (Z.eqb l__23 1) then Write_conditional\n   else if sumbool_of_bool (Z.eqb l__23 2) then Write_release\n   else if sumbool_of_bool (Z.eqb l__23 3) then Write_exclusive\n   else if sumbool_of_bool (Z.eqb l__23 4) then Write_exclusive_release\n   else if sumbool_of_bool (Z.eqb l__23 5) then Write_RISCV_release\n   else if sumbool_of_bool (Z.eqb l__23 6) then Write_RISCV_strong_release\n   else if sumbool_of_bool (Z.eqb l__23 7) then Write_RISCV_conditional\n   else if sumbool_of_bool (Z.eqb l__23 8) then Write_RISCV_conditional_release\n   else if sumbool_of_bool (Z.eqb l__23 9) then Write_RISCV_conditional_strong_release\n   else Write_X86_locked.\n\nDefinition num_of_write_kind (arg_ : write_kind) : {e : Z & ArithFact ((0 <=? e) && (e <=? 10))} :=\n   build_ex (\n      match arg_ with\n      | Write_plain => 0\n      | Write_conditional => 1\n      | Write_release => 2\n      | Write_exclusive => 3\n      | Write_exclusive_release => 4\n      | Write_RISCV_release => 5\n      | Write_RISCV_strong_release => 6\n      | Write_RISCV_conditional => 7\n      | Write_RISCV_conditional_release => 8\n      | Write_RISCV_conditional_strong_release => 9\n      | Write_X86_locked => 10\n      end\n   ).\n\nDefinition a64_barrier_domain_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 3))}\n: a64_barrier_domain :=\n   let l__20 := arg_ in\n   if sumbool_of_bool (Z.eqb l__20 0) then A64_FullShare\n   else if sumbool_of_bool (Z.eqb l__20 1) then A64_InnerShare\n   else if sumbool_of_bool (Z.eqb l__20 2) then A64_OuterShare\n   else A64_NonShare.\n\nDefinition num_of_a64_barrier_domain (arg_ : a64_barrier_domain)\n: {e : Z & ArithFact ((0 <=? e) && (e <=? 3))} :=\n   build_ex (\n      match arg_ with\n      | A64_FullShare => 0\n      | A64_InnerShare => 1\n      | A64_OuterShare => 2\n      | A64_NonShare => 3\n      end\n   ).\n\nDefinition a64_barrier_type_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 2))}\n: a64_barrier_type :=\n   let l__18 := arg_ in\n   if sumbool_of_bool (Z.eqb l__18 0) then A64_barrier_all\n   else if sumbool_of_bool (Z.eqb l__18 1) then A64_barrier_LD\n   else A64_barrier_ST.\n\nDefinition num_of_a64_barrier_type (arg_ : a64_barrier_type)\n: {e : Z & ArithFact ((0 <=? e) && (e <=? 2))} :=\n   build_ex (match arg_ with | A64_barrier_all => 0 | A64_barrier_LD => 1 | A64_barrier_ST => 2 end).\n\nDefinition trans_kind_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 2))} : trans_kind :=\n   let l__16 := arg_ in\n   if sumbool_of_bool (Z.eqb l__16 0) then Transaction_start\n   else if sumbool_of_bool (Z.eqb l__16 1) then Transaction_commit\n   else Transaction_abort.\n\nDefinition num_of_trans_kind (arg_ : trans_kind) : {e : Z & ArithFact ((0 <=? e) && (e <=? 2))} :=\n   build_ex (\n      match arg_ with\n      | Transaction_start => 0\n      | Transaction_commit => 1\n      | Transaction_abort => 2\n      end\n   ).\n\nDefinition cache_op_kind_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 10))}\n: cache_op_kind :=\n   let l__6 := arg_ in\n   if sumbool_of_bool (Z.eqb l__6 0) then Cache_op_D_IVAC\n   else if sumbool_of_bool (Z.eqb l__6 1) then Cache_op_D_ISW\n   else if sumbool_of_bool (Z.eqb l__6 2) then Cache_op_D_CSW\n   else if sumbool_of_bool (Z.eqb l__6 3) then Cache_op_D_CISW\n   else if sumbool_of_bool (Z.eqb l__6 4) then Cache_op_D_ZVA\n   else if sumbool_of_bool (Z.eqb l__6 5) then Cache_op_D_CVAC\n   else if sumbool_of_bool (Z.eqb l__6 6) then Cache_op_D_CVAU\n   else if sumbool_of_bool (Z.eqb l__6 7) then Cache_op_D_CIVAC\n   else if sumbool_of_bool (Z.eqb l__6 8) then Cache_op_I_IALLUIS\n   else if sumbool_of_bool (Z.eqb l__6 9) then Cache_op_I_IALLU\n   else Cache_op_I_IVAU.\n\nDefinition num_of_cache_op_kind (arg_ : cache_op_kind)\n: {e : Z & ArithFact ((0 <=? e) && (e <=? 10))} :=\n   build_ex (\n      match arg_ with\n      | Cache_op_D_IVAC => 0\n      | Cache_op_D_ISW => 1\n      | Cache_op_D_CSW => 2\n      | Cache_op_D_CISW => 3\n      | Cache_op_D_ZVA => 4\n      | Cache_op_D_CVAC => 5\n      | Cache_op_D_CVAU => 6\n      | Cache_op_D_CIVAC => 7\n      | Cache_op_I_IALLUIS => 8\n      | Cache_op_I_IALLU => 9\n      | Cache_op_I_IVAU => 10\n      end\n   ).\n\nDefinition not_bit (b : bitU) : bitU := if eq_bit b B1 then B0 else B1.\n\nDefinition neq_vec {n : Z} (x : mword n) (y : mword n) : bool := negb (eq_vec x y).\n\n\n\nDefinition string_of_bit (b : bitU) : M (string) :=\n   (match b with | B0 => returnm \"0b0\" | B1 => returnm \"0b1\" | _ => exit tt  : M (string) end)\n    : M (string).\n\nDefinition get_config_print_instr '(tt : unit) : bool := false.\n\nDefinition get_config_print_reg '(tt : unit) : bool := false.\n\nDefinition get_config_print_mem '(tt : unit) : bool := false.\n\nDefinition get_config_print_platform '(tt : unit) : bool := false.\n\nDefinition EXTS {n : Z} (m : Z) (v : mword n) `{ArithFact (m >=? n)} : mword m := sign_extend v m.\n\nDefinition EXTZ {n : Z} (m : Z) (v : mword n) `{ArithFact (m >=? n)} : mword m := zero_extend v m.\n\nDefinition zeros_implicit (n : Z) `{ArithFact (n >=? 0)} : mword n := zeros n.\n\nDefinition zeros (n : Z) `{ArithFact (n >=? 0)} : mword n :=\n   autocast (replicate_bits ('b\"0\"  : mword 1) n).\n\nDefinition ones (n : Z) `{ArithFact (n >=? 0)} : mword n := sail_ones n.\n\nDefinition bool_to_bits (x : bool) : mword 1 :=\n   if sumbool_of_bool x then 'b\"1\"  : mword 1 else 'b\"0\"  : mword 1.\n\nDefinition bit_to_bool (b : bitU) : M (bool) :=\n   (match b with | B1 => returnm true | B0 => returnm false | _ => exit tt  : M (bool) end)\n    : M (bool).\n\nDefinition to_bits (l : Z) (n : Z) `{ArithFact (l >=? 0)} : mword l := get_slice_int l n 0.\n\nDefinition zopz0zI_s {n : Z} (x : mword n) (y : mword n) `{ArithFact (n >? 0)} : bool :=\n   Z.ltb (projT1 (sint x)) (projT1 (sint y)).\n\nDefinition zopz0zKzJ_s {n : Z} (x : mword n) (y : mword n) `{ArithFact (n >? 0)} : bool :=\n   Z.geb (projT1 (sint x)) (projT1 (sint y)).\n\nDefinition zopz0zI_u {n : Z} (x : mword n) (y : mword n) : bool :=\n   Z.ltb (projT1 (uint x)) (projT1 (uint y)).\n\nDefinition zopz0zKzJ_u {n : Z} (x : mword n) (y : mword n) : bool :=\n   Z.geb (projT1 (uint x)) (projT1 (uint y)).\n\nDefinition zopz0zIzJ_u {n : Z} (x : mword n) (y : mword n) : bool :=\n   Z.leb (projT1 (uint x)) (projT1 (uint y)).\n\nDefinition shift_right_arith64 (v : mword 64) (shift : mword 6) : mword 64 :=\n   let v128 : bits 128 := EXTS 128 v in\n   subrange_vec_dec (shift_bits_right v128 shift) 63 0.\n\nDefinition shift_right_arith32 (v : mword 32) (shift : mword 5) : mword 32 :=\n   let v64 : bits 64 := EXTS 64 v in\n   subrange_vec_dec (shift_bits_right v64 shift) 31 0.\n\nAxiom spc_forwards_matches : forall  (_ : unit) , bool.\n\nAxiom spc_backwards_matches : forall  (_ : string) , bool.\n\nAxiom opt_spc_forwards_matches : forall  (_ : unit) , bool.\n\nAxiom opt_spc_backwards_matches : forall  (_ : string) , bool.\n\nAxiom def_spc_forwards_matches : forall  (_ : unit) , bool.\n\nAxiom def_spc_backwards_matches : forall  (_ : string) , bool.\n\nAxiom hex_bits_forwards : forall {n : Z} (_ : (Z * mword n)) , string.\n\nAxiom hex_bits_backwards : forall {n : Z} (_ : string) , (Z * mword n).\n\nAxiom hex_bits_forwards_matches : forall {n : Z} (_ : (Z * mword n)) , bool.\n\nAxiom hex_bits_backwards_matches : forall  (_ : string) , bool.\n\nAxiom hex_bits_matches_prefix : forall\n{n : Z}\n(_ : string)\n,\noption (((Z * mword n) * {n : Z & ArithFact (n >=? 0)})).\n\nFixpoint _rec_n_leading_spaces (s : string) (_reclimit : Z) (_acc : Acc (Zwf 0) _reclimit)\n{struct _acc} : M ({n : Z & ArithFact (n >=? 0)}).\nexact (\n   assert_exp' (Z.geb _reclimit 0) \"recursion limit reached\" >>= fun _ =>\n   let p0_ := s in\n   (if generic_eq p0_ \"\" then returnm (build_ex 0)\n    else\n      let p0_ := string_take s 1 in\n      (if generic_eq p0_ \" \" then\n         (_rec_n_leading_spaces (string_drop s 1) (Z.sub _reclimit 1) (_limit_reduces _acc)) >>= fun '(existT _ w__0 _ : {n : Z & ArithFact (n >=?\n           0)}) =>\n         returnm (build_ex (Z.add 1 w__0))\n       else returnm (build_ex 0))\n       : M ({n : Z & ArithFact (n >=? 0)}))\n    : M ({n : Z & ArithFact (n >=? 0)})\n).\nDefined.\n\n\nDefinition n_leading_spaces (s : string) : M ({n : Z & ArithFact (n >=? 0)}) :=\n   (_rec_n_leading_spaces s ((projT1 (string_length s))  : Z) (Zwf_guarded _))\n    : M ({n : Z & ArithFact (n >=? 0)}).\n\nDefinition spc_forwards '(tt : unit) : string := \" \".\n\nDefinition spc_backwards (s : string) : unit := tt.\n\nDefinition spc_matches_prefix (s : string) : M (option ((unit * {n : Z & ArithFact (n >=? 0)}))) :=\n   (n_leading_spaces s) >>= fun '(existT _ n _) =>\n   let l__5 := n in\n   returnm (if sumbool_of_bool (Z.eqb l__5 0) then None else Some (tt, build_ex n)).\n\nDefinition opt_spc_forwards '(tt : unit) : string := \"\".\n\nDefinition opt_spc_backwards (s : string) : unit := tt.\n\nDefinition opt_spc_matches_prefix (s : string) : M (option ((unit * {n : Z & ArithFact (n >=? 0)}))) :=\n   (n_leading_spaces s) >>= fun '(existT _ w__0 _ : {n : Z & ArithFact (n >=? 0)}) =>\n   returnm (Some (tt, build_ex w__0)).\n\nDefinition def_spc_forwards '(tt : unit) : string := \" \".\n\nDefinition def_spc_backwards (s : string) : unit := tt.\n\nDefinition def_spc_matches_prefix (s : string) : M (option ((unit * {n : Z & ArithFact (n >=? 0)}))) :=\n   (opt_spc_matches_prefix s)  : M (option ((unit * {n : Z & ArithFact (n >=? 0)}))).\n\nDefinition rX (r : mword 5) : M (mword 64) :=\n   let b__0 := r in\n   (if eq_vec b__0 ('b\"00000\"  : mword 5) then returnm (EXTZ 64 (Ox\"0\"  : mword 4))\n    else\n      read_reg Xs_ref >>= fun w__0 : vec (mword 64) 32 =>\n      returnm (vec_access_dec w__0 (projT1 (uint r))))\n    : M (mword 64).\n\nDefinition wX (r : mword 5) (v : mword 64) : M (unit) :=\n   (if neq_vec r ('b\"00000\"  : mword 5) then\n      read_reg Xs_ref >>= fun w__0 : vec (mword 64) 32 =>\n      write_reg Xs_ref (vec_update_dec w__0 (projT1 (uint r)) v)\n       : M (unit)\n    else returnm tt)\n    : M (unit).\n\nDefinition read_mem (addr : mword 64) (width : Z) `{ArithFact (width >=? 0)} : M (mword (8 * width)) :=\n   (MEMr 64 width (EXTZ 64 (Ox\"0\"  : mword 4)) addr)  : M (mword (8 * width)).\n\nDefinition iop_of_num (arg_ : Z) `{ArithFact ((0 <=? arg_) && (arg_ <=? 5))} : iop :=\n   let l__0 := arg_ in\n   if sumbool_of_bool (Z.eqb l__0 0) then RISCV_ADDI\n   else if sumbool_of_bool (Z.eqb l__0 1) then RISCV_SLTI\n   else if sumbool_of_bool (Z.eqb l__0 2) then RISCV_SLTIU\n   else if sumbool_of_bool (Z.eqb l__0 3) then RISCV_XORI\n   else if sumbool_of_bool (Z.eqb l__0 4) then RISCV_ORI\n   else RISCV_ANDI.\n\nDefinition num_of_iop (arg_ : iop) : {e : Z & ArithFact ((0 <=? e) && (e <=? 5))} :=\n   build_ex (\n      match arg_ with\n      | RISCV_ADDI => 0\n      | RISCV_SLTI => 1\n      | RISCV_SLTIU => 2\n      | RISCV_XORI => 3\n      | RISCV_ORI => 4\n      | RISCV_ANDI => 5\n      end\n   ).\n\nDefinition execute_LOAD (imm : mword 12) (rs1 : mword 5) (rd : mword 5) : M (unit) :=\n   (rX rs1) >>= fun w__0 : mword 64 =>\n   let addr : xlenbits := add_vec w__0 (EXTS 64 imm) in\n   (read_mem addr 8) >>= fun result : xlenbits => (wX rd result)  : M (unit).\n\nDefinition execute_ITYPE (arg0 : mword 12) (arg1 : mword 5) (arg2 : mword 5) (arg3 : iop) : M (unit) :=\n   let merge_var := (arg0, arg1, arg2, arg3) in\n   (match merge_var with\n    | (imm, rs1, rd, RISCV_ADDI) =>\n       (rX rs1) >>= fun rs1_val =>\n       let imm_ext : xlenbits := EXTS 64 imm in\n       let result := add_vec rs1_val imm_ext in\n       (wX rd result)\n        : M (unit)\n    | _ => exit tt  : M (unit)\n    end)\n    : M (unit).\n\nDefinition execute (merge_var : ast) : M (unit) :=\n   (match merge_var with\n    | ITYPE (imm, rs1, rd, arg3) => (execute_ITYPE imm rs1 rd arg3)  : M (unit)\n    | LOAD (imm, rs1, rd) => (execute_LOAD imm rs1 rd)  : M (unit)\n    end)\n    : M (unit).\n\nDefinition decode (v__0 : mword 32) : option ast :=\n   if andb (eq_vec (subrange_vec_dec v__0 14 12) ('b\"000\"  : mword (14 - 12 + 1)))\n        (eq_vec (subrange_vec_dec v__0 6 0) ('b\"0010011\"  : mword (6 - 0 + 1))) then\n     let imm : bits 12 := subrange_vec_dec v__0 31 20 in\n     let rs1 : regbits := subrange_vec_dec v__0 19 15 in\n     let rd : regbits := subrange_vec_dec v__0 11 7 in\n     let imm : bits 12 := subrange_vec_dec v__0 31 20 in\n     Some (ITYPE (imm, rs1, rd, RISCV_ADDI))\n   else if andb (eq_vec (subrange_vec_dec v__0 14 12) ('b\"011\"  : mword (14 - 12 + 1)))\n             (eq_vec (subrange_vec_dec v__0 6 0) ('b\"0000011\"  : mword (6 - 0 + 1))) then\n     let imm : bits 12 := subrange_vec_dec v__0 31 20 in\n     let rs1 : regbits := subrange_vec_dec v__0 19 15 in\n     let rd : regbits := subrange_vec_dec v__0 11 7 in\n     let imm : bits 12 := subrange_vec_dec v__0 31 20 in\n     Some (LOAD (imm, rs1, rd))\n   else None.\n\nDefinition initial_regstate : regstate :=\n{| Xs :=\n     (vec_of_list_len [Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64;Ox\"0000000000000000\"  : mword 64;\n                       Ox\"0000000000000000\"\n                        : mword 64;Ox\"0000000000000000\"  : mword 64]); \n   nextPC := (Ox\"0000000000000000\"  : mword 64); \n   PC := (Ox\"0000000000000000\"  : mword 64) |}.\nHint Unfold initial_regstate : sail.\n\n\n", "meta": {"author": "riscvarchive", "repo": "riscv-sail-archive", "sha": "31b53ea1b7c678a10c3f9caf08b7574d71aad9a6", "save_path": "github-repos/coq/riscvarchive-riscv-sail-archive", "path": "github-repos/coq/riscvarchive-riscv-sail-archive/riscv-sail-archive-31b53ea1b7c678a10c3f9caf08b7574d71aad9a6/prover_snapshots/coq/duopod/riscv_duopod.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.2299664694756198}}
{"text": "From iris.proofmode Require Export classes.\nFrom iris.algebra Require Export cmra.\n\n(* There are various versions of [IsOp] with different modes:\n\n- [IsOp a b1 b2]: this one has no mode, it can be used regardless of whether\n  any of the arguments is an evar. This class has only one direct instance:\n  [IsOp (a ⋅ b) a b].\n- [IsOp' a b1 b2]: requires either [a] to start with a constructor, OR [b1] and\n  [b2] to start with a constructor. All usual instances should be of this\n  class to avoid loops.\n- [IsOp'LR a b1 b2]: requires either [a] to start with a constructor. This one\n  has just one instance: [IsOp'LR (a ⋅ b) a b] with a very low precendence.\n  This is important so that when performing, for example, an [iDestruct] on\n  [own γ (q1 + q2)] where [q1] and [q2] are fractions, we actually get\n  [own γ q1] and [own γ q2] instead of [own γ ((q1 + q2)/2)] twice.\n*)\nClass IsOp {A : cmraT} (a b1 b2 : A) := is_op : a ≡ b1 ⋅ b2.\nArguments is_op {_} _ _ _ {_}.\nHint Mode IsOp + - - - : typeclass_instances.\n\nInstance is_op_op {A : cmraT} (a b : A) : IsOp (a ⋅ b) a b | 100.\nProof. by rewrite /IsOp. Qed.\n\nClass IsOp' {A : cmraT} (a b1 b2 : A) := is_op' :> IsOp a b1 b2.\nHint Mode IsOp' + ! - - : typeclass_instances.\nHint Mode IsOp' + - ! ! : typeclass_instances.\n\nClass IsOp'LR {A : cmraT} (a b1 b2 : A) := is_op_lr : IsOp a b1 b2.\nExisting Instance is_op_lr | 0.\nHint Mode IsOp'LR + ! - - : typeclass_instances.\nInstance is_op_lr_op {A : cmraT} (a b : A) : IsOp'LR (a ⋅ b) a b | 0.\nProof. by rewrite /IsOp'LR /IsOp. Qed.\n\n(* FromOp *)\n(* TODO: Worst case there could be a lot of backtracking on these instances,\ntry to refactor. *)\nGlobal Instance is_op_pair {A B : cmraT} (a b1 b2 : A) (a' b1' b2' : B) :\n  IsOp a b1 b2 → IsOp a' b1' b2' → IsOp' (a,a') (b1,b1') (b2,b2').\nProof. by constructor. Qed.\nGlobal Instance is_op_pair_core_id_l {A B : cmraT} (a : A) (a' b1' b2' : B) :\n  CoreId a → IsOp a' b1' b2' → IsOp' (a,a') (a,b1') (a,b2').\nProof. constructor=> //=. by rewrite -core_id_dup. Qed.\nGlobal Instance is_op_pair_core_id_r {A B : cmraT} (a b1 b2 : A) (a' : B) :\n  CoreId a' → IsOp a b1 b2 → IsOp' (a,a') (b1,a') (b2,a').\nProof. constructor=> //=. by rewrite -core_id_dup. Qed.\n\nGlobal Instance is_op_Some {A : cmraT} (a : A) b1 b2 :\n  IsOp a b1 b2 → IsOp' (Some a) (Some b1) (Some b2).\nProof. by constructor. Qed.\n(* This one has a higher precendence than [is_op_op] so we get a [+] instead of\nan [⋅]. *)\nGlobal Instance is_op_plus (n1 n2 : nat) : IsOp (n1 + n2) n1 n2.\nProof. done. Qed.", "meta": {"author": "izgzhen", "repo": "iris-coq", "sha": "4a1eb8a3d20789af6265b9011939be8274da042c", "save_path": "github-repos/coq/izgzhen-iris-coq", "path": "github-repos/coq/izgzhen-iris-coq/iris-coq-4a1eb8a3d20789af6265b9011939be8274da042c/theories/algebra/proofmode_classes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.22996167308736684}}
{"text": "(*\n * © 2020 Massachusetts Institute of Technology.\n * MIT Proprietary, Subject to FAR52.227-11 Patent Rights - Ownership by the Contractor (May 2014)\n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n     List.\n\nFrom SPICY Require Import\n     MyPrelude\n     Maps\n     ChMaps\n     Messages\n     Keys\n     Automation\n     Tactics\n     Simulation\n     SyntacticallySafe\n     AdversaryUniverse\n\n     ModelCheck.Commutation\n     ModelCheck.InvariantSearch\n     ModelCheck.ProtocolFunctions\n     ModelCheck.ModelCheck\n     ModelCheck.SilentStepElimination\n     ModelCheck.SteppingTactics\n     ModelCheck.UniverseInversionLemmas\n.\n\nFrom protocols Require Import\n     NetAuth.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations\n       SimulationAutomation.\n\nFrom Frap Require Import Sets.\n\nModule Foo <: Sets.EMPTY.\nEnd Foo.\nModule Import SN := Sets.SetNotations(Foo).\n\nSet Implicit Arguments.\n\nOpen Scope protocol_scope.\n\nModule NetAuthProtocolSecure <: AutomatedSafeProtocolSS.\n\n  Import NetAuthProtocol.\n\n  (* Some things may need to change here.  t__hon is where we place the \n   * type that the protocol computes.  It is set to Nat now, because we\n   * return a natual number.\n   *)\n  Definition t__hon := Nat.\n  Definition t__adv := Unit.\n  Definition b    := tt.\n\n  (* These two variables hook up the starting points for both specification and\n   * implementation universes.  If you followed the template above, this shouldn't\n   * need to be changed.\n   *)\n  Definition iu0  := ideal_univ_start.\n  Definition ru0  := real_univ_start.\n\n  Import Gen Tacs.\n\n  (* These are here to help the proof automation.  Don't change. *)\n  #[export] Hint Unfold t__hon t__adv b ru0 iu0 ideal_univ_start real_univ_start : core.\n  #[export] Hint Unfold\n       mkiU mkiUsr mkrU mkrUsr\n       mkKeys\n    : core.\n\n  Lemma finitelyRuns : exists n, runningTimeMeasure ru0 n.\n  Proof.\n    autounfold; simpl.\n    eexists.\n    econstructor; simpl; find_runtime.\n\n    Unshelve.\n    all: exact 0.\n  Qed.\n\n  Require Import Coq.Program.Equality.\n\n  Lemma typechecks : syntactically_safe_U ru0.\n  Proof.\n    unfold syntactically_safe_U; intros.\n    autounfold\n    ; subst\n    ; simpl in *.\n\n    unfold compute_ids; simpl.\n\n    focus_user; simpl\n    ; try solve [ do 2 eexists; split\n                  ; [ unshelve (repeat typechecks1)\n                      ; match goal with\n                        | [ |- bool ] => exact true\n                        | [ |- list safe_typ ] => exact []\n                        end\n                    | repeat verify_context_soundness ] ].\n\n\n    Unshelve.\n    all : exact TyDontCare.\n  Qed.\n    \n  Lemma summarizable : exists summaries, summarize_univ ru0 summaries.\n  Proof.\n    autounfold; unfold summarize_univ; simpl; intros.\n    unshelve (\n        eexists; intros; focus_user; simpl\n        ; (exists useless_summary; split; [ build_summary |]; eauto using useless_summary_summarizes)\n      ) ; exact $0.\n  Qed.\n    \n  Lemma lameness : @lameAdv t__adv b (RealWorld.adversary ru0).\n  Proof.\n    unfold lameAdv; autounfold; simpl; eauto.\n  Qed.\n\n  Set Ltac Profiling.\n\n  Lemma safe_invariant :\n    invariantFor\n      {| Initial := {(ru0, iu0, true)}; Step := @stepSS t__hon t__adv  |}\n      (@noresends_inv t__hon t__adv).\n  Proof.\n    unfold invariantFor\n    ; unfold Initial, Step\n    ; intros\n    ; simpl in *\n    ; split_ors\n    ; try contradiction\n    ; subst.\n\n    autounfold in H0\n    ; unfold fold_left, fst, snd in *.\n    \n    time (\n        repeat transition_system_step\n      ).\n\n    Unshelve.\n    all: exact 0  || auto.\n  Qed.\n\n  Show Ltac Profile.\n\n  Lemma U_good : @universe_starts_sane _ Unit b ru0.\n  Proof.\n    autounfold;\n      unfold universe_starts_sane; simpl.\n    repeat (apply conj); intros; eauto.\n    - focus_user; auto.\n    - econstructor.\n    - unfold AdversarySafety.keys_honest; rewrite Forall_natmap_forall; intros.\n      unfold mkrUsr; simpl.\n      rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty; eauto.\n    - unfold lameAdv; simpl; eauto.\n  Qed.\n\n  Lemma universe_starts_safe : universe_ok ru0.\n  Proof.\n    pose proof (adversary_is_lame_adv_univ_ok_clauses U_good).\n    \n    unfold universe_ok\n    ; autounfold\n    ; simpl\n    ; intuition eauto\n    .\n\n    - econstructor; eauto.\n    - unfold keys_and_permissions_good; solve_simple_maps; intuition eauto.\n      solve_simple_maps; eauto.\n\n      rewrite Forall_natmap_forall; intros.\n\n      solve_simple_maps; simpl\n      ; unfold permission_heap_good; intros;\n        solve_simple_maps; solve_concrete_maps; eauto.\n\n    - unfold user_cipher_queues_ok.\n      rewrite Forall_natmap_forall; intros.\n      focus_user\n      ; simpl in *; econstructor; eauto.\n\n    - unfold honest_nonces_ok, honest_user_nonces_ok, honest_nonces_ok\n      ; repeat simple apply conj\n      ; intros\n      ; clean_map_lookups\n      ; intros\n      ; focus_user\n      ; try contradiction; try discriminate; simpl;\n        repeat (apply conj); intros; clean_map_lookups; eauto.\n\n    - unfold honest_users_only_honest_keys; intros.\n      focus_user;\n        subst;\n        simpl in *;\n        clean_map_lookups;\n        unfold mkrUsr; simpl; \n          rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty;\n          eauto;\n          simpl in *;\n          solve_concrete_perm_merges;\n          solve_concrete_maps;\n          solve_simple_maps;\n          eauto.\n  Qed.\n\nEnd NetAuthProtocolSecure.\n", "meta": {"author": "mit-ll", "repo": "SPICY", "sha": "ad89c31a093ed2e0b7b4ef55c87ec9b175749fe0", "save_path": "github-repos/coq/mit-ll-SPICY", "path": "github-repos/coq/mit-ll-SPICY/SPICY-ad89c31a093ed2e0b7b4ef55c87ec9b175749fe0/protocols/Verification/NetAuthSecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102775181399, "lm_q2_score": 0.3629692193015555, "lm_q1q2_score": 0.22990843392834087}}
{"text": "Require Import Decision.\nRequire Import Semantics. (* for [module_layer_disjoint] *)\nRequire Export MakeProgramSpec.\n\nLocal Arguments ret : simpl never.\nLocal Arguments bind : simpl never.\n\nSection MAKE_PROGRAM_FACTS.\n  Context `{Hmkp: MakeProgram}.\n  Context `{Hpf: ProgramFormat}.\n  Context `{Hmodule: !Modules ident Fm (globvar Vm) module}.\n  Context `{Hlayer: !Layers ident primsem (globvar Vm) layer}.\n\n  Global Instance top_preo A:\n    @PreOrder A ⊤%rel.\n  Proof.\n    firstorder.\n  Qed.\n\n  (** * Preliminaries *)\n\n  (** ** Using [make_program_noconflict] *)\n\n  Lemma make_program_make_globalenv {D} ML p:\n    make_program D ML = OK p ->\n    make_globalenv D ML = OK (Genv.globalenv p).\n  Proof.\n    intros Hp.\n    unfold make_globalenv.\n    rewrite Hp.\n    reflexivity.\n  Qed.\n\n  Lemma make_globalenv_make_program {D} ML ge:\n    make_globalenv D ML = OK ge ->\n    exists p, make_program D ML = OK p.\n  Proof.\n    intros Hge.\n    unfold make_globalenv in Hge.\n    inv_monad Hge.\n    eauto.\n  Qed.\n\n  Ltac noconflict_for H i :=\n    lazymatch type of H with\n      | make_program _ (?M, ?L) = _ =>\n        let tac :=\n          destruct (make_program_noconflict _ _ _ _ i H); eauto; discriminate\n        in\n          try assert (HMfi: get_module_function i M = OK None) by tac;\n          try assert (HMvi: get_module_variable i M = OK None) by tac;\n          try assert (HLpi: get_layer_primitive i L = OK None) by tac;\n          try assert (HLvi: get_layer_globalvar i L = OK None) by tac;\n          try assert (HMLv: get_layer_globalvar i L = get_module_variable i M) by tac\n      | make_globalenv _ _ = _ =>\n        let p := fresh \"p\" in\n        let Hp := fresh \"H\" p in\n          destruct (make_globalenv_make_program _ _ H) as [p Hp];\n          noconflict_for Hp i\n    end.\n\n  (** ** Elementary relations for [make_program_rel] *)\n\n  (** We're going to prove many theorems by constructing\n    relation families that encode constraints on the module-layer pair\n    corresponding to the theorem's premises, then showing that once\n    the relations are transported to the program or global\n    environment, they entail our conclusion. To facilitate this\n    process we introduce the following language.\n\n    So far the following relations can be used:\n      - [mprc_empty] imposes no contraints on the program;\n      - [mprc_fun i κ] requires that the program define [i] to be the\n        internal function [κ];\n      - [mprc_prim i σ] requires that the program define [i] to be the\n        primitive with specification [σ];\n      - [mprc_var i τ] requires that the program define [i] to be the\n        global variable with definition [τ].\n\n    Of course, we could come up with something much more general,\n    however this suffices for now. *)\n\n  Inductive mprc D :=\n    | mprc_empty\n    | mprc_fun (i: ident) (κ: Fm)\n    | mprc_prim (i: ident) (σ: primsem D)\n    | mprc_var (i: ident) (τ: globvar Vm).\n\n  Definition mprc_funrel {D} (R: mprc D): funrel D D :=\n    fun j =>\n      (eq /\\\n       match R with\n         | mprc_fun i κ =>\n           if decide (i = j) then fun x y => y = Some (inl κ) else ⊤\n         | mprc_prim i σ =>\n           if decide (i = j) then fun x y => y = Some (inr σ) else ⊤\n         | _ =>\n           ⊤\n       end)%rel.\n\n  Definition mprc_varrel {D} (R: mprc D): varrel :=\n    fun j =>\n      (eq /\\\n       match R with\n         | mprc_var i τ =>\n           if decide (i = j) then fun x y => y = Some τ else ⊤\n         | _ =>\n           ⊤\n       end)%rel.\n\n  (** We will be interested in establishing that a module-layer pair\n    is related to itself, and expoiting the fact that the resulting\n    global environement is the related to itself as well. *)\n\n  Definition mprc_pre {D} (R: @mprc D) (ML: module * layer D) :=\n    match R with\n      | mprc_empty =>\n        True\n      | mprc_fun i κ =>\n        get_module_function i (fst ML) = OK (Some κ)\n      | mprc_prim i σ =>\n        get_layer_primitive i (snd ML) = OK (Some σ)\n      | mprc_var i τ =>\n        get_module_variable i (fst ML) = OK (Some τ) \\/\n        get_layer_globalvar i (snd ML) = OK (Some τ)\n    end.\n\n  (** XXX: we need this for the proof below; perhaps it should be in coqrel. *)\n\n  Lemma rel_inter_preo {A} (R1 R2: rel A A):\n    PreOrder R1 ->\n    PreOrder R2 ->\n    PreOrder (R1 /\\ R2).\n  Proof.\n    intros HR1 HR2.\n    split.\n    - intros x.\n      rauto.\n    - intros x y z Hxy Hyz.\n      split; etransitivity; rauto.\n  Qed.\n\n  Hint Extern 2 (PreOrder (_ /\\ _)) =>\n    eapply rel_inter_preo : typeclass_instances.\n\n  Lemma mprc_pre_sound {D} R ML:\n    @mprc_pre D R ML ->\n    module_layer_rel D D (mprc_funrel R) (mprc_varrel R) ML ML.\n  Proof.\n    destruct ML as [M L], R;\n    unfold mprc_pre, mprc_funrel, mprc_varrel, fst, snd;\n    intros H j;\n    try destruct H as [H|H];\n    try destruct (decide (i = j)); subst;\n    split;\n    try reflexivity;\n    unfold get_module_layer_function, get_module_layer_variable, fst, snd;\n    rewrite H.\n    - destruct (get_layer_primitive j L) as [[|]|]; repeat constructor.\n    - destruct (get_module_function j M) as [[|]|]; repeat constructor.\n    - destruct (get_layer_globalvar j L) as [[ τ'|]|]; repeat constructor.\n      destruct (GlobalVars.globalvar_eq_dec τ τ').\n      + subst. autorewrite with res_option_globalvar. repeat constructor.\n      + rewrite GlobalVars.res_option_globalvar_oplus_diff by assumption.\n        constructor.\n    - destruct (get_module_variable j M) as [[ τ' |]|]; repeat constructor.\n      destruct (GlobalVars.globalvar_eq_dec τ' τ).\n      + subst. autorewrite with res_option_globalvar. repeat constructor.\n      + rewrite GlobalVars.res_option_globalvar_oplus_diff by assumption.\n        constructor.\n  Qed.\n\n  Definition mprc_post {D} (R: @mprc D) (ge: Genv.t Fp Vp) :=\n    match R with\n      | mprc_empty =>\n        True\n      | mprc_fun i κ =>\n        exists fdef b,\n          make_internal κ = OK fdef /\\\n          Genv.find_symbol ge i = Some b /\\\n          Genv.find_funct_ptr ge b = Some fdef\n      | mprc_prim i σ =>\n        exists fdef b,\n          make_external D i σ = OK fdef /\\\n          Genv.find_symbol ge i = Some b /\\\n          Genv.find_funct_ptr ge b = Some fdef\n      | mprc_var i τ =>\n        exists vdef b,\n          make_varinfo τ = OK vdef /\\\n          Genv.find_symbol ge i = Some b /\\\n          Genv.find_var_info ge b = Some vdef\n    end.\n\n  Lemma mprc_post_complete {D} R ge:\n    genv_rel\n      (fundef_rel D D (mprc_funrel R))\n      (vardef_rel (mprc_varrel R))\n      ge ge ->\n    @mprc_post D R ge.\n  Proof.\n    intros H.\n    destruct R; simpl; eauto;\n    [ pose proof (genv_rel_find_funct_ptr _ _ _ _ i H) as H' ..\n    | pose proof (genv_rel_find_var_info _ _ _ _ i H) as H' ];\n    inv_monad H';\n    destruct H2 as [? ?];\n    simpl in *;\n    (destruct (decide (i = i)); [ | congruence]; subst);\n    inversion H1; clear H1; subst;\n    inv_monad H3;\n    simpl in *;\n    eauto.\n  Qed.\n\n  (** We can use the relational property of [make_program] with\n    [mprc_funrel] and [mprc_varrel] to brige these two things. *)\n\n  Instance mprc_funrel_mpr D (R: mprc D) i:\n    OptionRelationForward (mprc_funrel R i).\n  Proof.\n    destruct R; simpl; intros x y Hxy Hy;\n    try destruct (decide (_ = _)); inversion Hxy; congruence.\n  Qed.\n\n  Instance mprc_varrel_mpr D (R: mprc D) i:\n    OptionRelationForward (mprc_varrel R i).\n  Proof.\n    destruct R; simpl; intros x y Hxy Hy;\n    try destruct (decide (_ = _)); inversion Hxy; congruence.\n  Qed.\n\n  Instance mprc_funrel_err D (R: mprc D) i:\n    Monotonic (make_fundef D i) (mprc_funrel R i @@ Some ++> impl @@ isError).\n  Proof.\n    intros x y [Hxy _].\n    inversion Hxy; subst; reflexivity.\n  Qed.\n\n  Instance mprc_varrel_err D (R: mprc D) i:\n    Monotonic make_varinfo (mprc_varrel R i @@ Some ++> impl @@ isError).\n  Proof.\n    intros x y [Hxy _].\n    inversion Hxy; subst; reflexivity.\n  Qed.\n\n  Lemma make_globalenv_rel_mprc D R ML ge:\n    make_globalenv D ML = OK ge ->\n    module_layer_rel D D (mprc_funrel R) (mprc_varrel R) ML ML ->\n    genv_rel (fundef_rel D D (mprc_funrel R)) (vardef_rel (mprc_varrel R)) ge ge.\n  Proof.\n    intros Hge HML.\n    assert (Hge':\n      res_le (genv_rel (fundef_rel D D (mprc_funrel R))\n                       (vardef_rel (mprc_varrel R))) (OK ge) (OK ge)).\n    {\n      rewrite <- !Hge.\n      (* FIXME: solve_monotonic should work *)\n      eapply make_globalenv_rel; eauto.\n      typeclasses eauto.\n    }\n    inversion Hge'.\n    assumption.\n  Qed.\n\n  (** We can now design a tactic that puts all of these components together. *)\n\n  Ltac use_mprc H R :=\n    lazymatch type of H with\n      | make_program ?D ?ML = _ =>\n        let Hge := fresh \"Hge\" in\n        pose proof (make_program_make_globalenv _ _ H) as Hge;\n        use_mprc Hge R\n      | make_globalenv ?D ?ML = _ =>\n        let HR := fresh \"HR\" in\n        pose proof H as HR;\n        eapply (make_globalenv_rel_mprc _ R) in HR;\n        [ eapply mprc_post_complete in HR;\n          simpl in H\n        | eapply mprc_pre_sound;\n          simpl;\n          get_module_normalize;\n          get_layer_normalize ]\n    end.\n\n  (** ** Other useful lemmas *)\n\n  Instance res_le_refl `(Reflexive):\n    Reflexive (res_le R).\n  Proof.\n    intros [|]; constructor; reflexivity.\n  Qed.\n\n  Global Instance module_layer_rel_refl D RF RV:\n    (forall i, Reflexive (RF i)) ->\n    (forall i, Reflexive (RV i)) ->\n    Reflexive (module_layer_rel D D RF RV).\n  Proof.\n    intros HRF HRV [M L] i.\n    split; reflexivity.\n  Qed.\n\n  Lemma make_globalenv_stencil_matches D ML ge:\n    make_globalenv D ML = OK ge ->\n    stencil_matches ge.\n  Proof.\n    intros Hge.\n    eapply genv_le_stencil_matches_l.\n    eapply (make_globalenv_rel_mprc D (mprc_empty D)); eauto.\n    unfold mprc_funrel, mprc_varrel.\n    reflexivity.\n  Qed.\n\n  Hint Resolve make_globalenv_stencil_matches.\n\n  (** * Properties relating module-layer pairs with their global environments *)\n\n  (** ** Intensional properties about single-binding module-layer pairs *)\n\n  (** Those are only used in [MakeProgramInv] and we may want to\n    relocate them there. *)\n\n  Lemma make_globalenv_external {D} (i: ident) (σ: primsem D) ge:\n    make_globalenv D (∅, i ↦ σ) = ret ge ->\n    exists σdef b,\n      make_external D i σ = OK σdef /\\\n      Genv.find_symbol ge i = Some b /\\\n      Genv.find_funct_ptr ge b = Some σdef.\n  Proof.\n    intros Hge.\n    use_mprc Hge (mprc_prim D i σ); eauto.\n  Qed.\n\n  Lemma make_globalenv_internal {D} (i: ident) (f: Fm) ge:\n    make_globalenv D (i ↦ f, ∅) = ret ge ->\n    exists fdef b,\n      make_internal f = OK fdef /\\\n      Genv.find_symbol ge i = Some b /\\\n      Genv.find_funct_ptr ge b = Some fdef.\n  Proof.\n    intros Hge.\n    use_mprc Hge (mprc_fun D i f); eauto.\n  Qed.\n\n  Lemma make_globalenv_module_globvar {D} (i: ident) (τ: globvar Vm) ge:\n    make_globalenv D (i ↦ τ, ∅) = ret ge ->\n    exists vdef b,\n      make_varinfo τ = OK vdef /\\\n      Genv.find_symbol ge i = Some b /\\\n      Genv.find_var_info ge b = Some vdef.\n  Proof.\n    intros Hge.\n    use_mprc Hge (mprc_var D i τ); eauto.\n  Qed.\n\n  Lemma make_globalenv_layer_globvar {D} (i: ident) (τ: globvar Vm) ge:\n    make_globalenv D (∅, i ↦ τ) = ret ge ->\n    exists vdef b,\n      make_varinfo τ = OK vdef /\\\n      Genv.find_symbol ge i = Some b /\\\n      Genv.find_var_info ge b = Some vdef.\n  Proof.\n    intros Hge.\n    use_mprc Hge (mprc_var D i τ); eauto.\n  Qed.\n\n  (** ** Extensional properties *)\n\n  (** Those are used by legacy code, and we may want to remove them if\n    they end up unused after we migrate everything to use the\n    relational property of [make_program] instead of painstakingly\n    moving back-and-forth between the representations of modules and\n    their global environments. *)\n\n  Lemma make_globalenv_get_module_function {D} M L ge i fi f:\n    make_globalenv D (M, L) = OK ge ->\n    get_module_function i M = OK (Some fi) ->\n    make_internal fi = OK f ->\n    exists b,\n      Genv.find_symbol ge i = Some b /\\\n      Genv.find_funct_ptr ge b = Some f.\n  Proof.\n    intros Hge HMi Hfi.\n    use_mprc Hge (mprc_fun D i fi); eauto.\n    destruct HR as (f' & b & Hf' & HR).\n    replace f with f' by congruence.\n    eauto.\n  Qed.\n\n  Lemma make_globalenv_get_module_variable {D} M L ge i vi v:\n    make_globalenv D (M, L) = OK ge ->\n    get_module_variable i M = OK (Some vi) ->\n    make_varinfo vi = OK v ->\n    exists b,\n      Genv.find_symbol ge i = Some b /\\\n      Genv.find_var_info ge b = Some v.\n  Proof.\n    intros Hge HMi Hvi.\n    use_mprc Hge (mprc_var D i vi); eauto.\n    destruct HR as (v' & b & Hv' & Hb & Hbv').\n    assert (v' = v) by congruence; subst.\n    eauto.\n  Qed.\n\n  Lemma make_globalenv_get_layer_primitive {D} M L ge i fe f:\n    make_globalenv D (M, L) = OK ge ->\n    get_layer_primitive i L = OK (Some fe) ->\n    make_external D i fe = OK f ->\n    exists b,\n      Genv.find_symbol ge i = Some b /\\\n      Genv.find_funct_ptr ge b = Some f.\n  Proof.\n    intros Hge HMi Hfe.\n    use_mprc Hge (mprc_prim D i fe); eauto.\n    destruct HR as (f' & b & Hf' & HR).\n    replace f with f' by congruence.\n    eauto.\n  Qed.\n\n  Lemma make_globalenv_get_layer_globalvar {D} M L ge i vi v:\n    make_globalenv D (M, L) = OK ge ->\n    get_layer_globalvar i L = OK (Some vi) ->\n    make_varinfo vi = OK v ->\n    exists b,\n      Genv.find_symbol ge i = Some b /\\\n      Genv.find_var_info ge b = Some v.\n  Proof.\n    intros Hge HMi Hvi.\n    use_mprc Hge (mprc_var D i vi); eauto.\n    destruct HR as (v' & b & Hv' & Hb & Hbv').\n    assert (v' = v) by congruence; subst.\n    eauto.\n  Qed.\n\n  (** ** Consequences of single hypotheses *)\n\n  Lemma genv_find_symbol_glob_threshold {F V} (ge: Genv.t F V) i b:\n    stencil_matches ge ->\n    Genv.find_symbol ge i = Some b ->\n    (i < glob_threshold)%positive.\n  Proof.\n    intros Hge.\n    rewrite stencil_matches_symbols by eauto.\n    Local Transparent find_symbol.\n    unfold find_symbol, find_symbol_upto.\n    destruct (decide (i < glob_threshold)%positive).\n    - tauto.\n    - discriminate.\n  Qed.\n\n  Hint Resolve genv_find_symbol_glob_threshold.\n  Hint Extern 1 (isOK _) => eexists.\n\n  (** * Alternative monotonicity theorems *)\n\n  (** The specification of [make_program] is a very general relational\n    property, however prior to this we were already using simpler\n    monotonicity properties to characterize some aspects of\n    [make_program]. Here we prove those properties for backward\n    compatibility. We will want to remove those eventually. *)\n\n  Lemma module_layer_rel_intro:\n    forall (D1 D2: layerdata)\n      (ML1: module * layer D1)\n      (ML2: module * layer D2)\n      (R: simrel D1 D2)\n      (LESIM: ( le * sim R)%rel ML1 ML2),\n      module_layer_rel D1 D2 (fun _ => option_le (eq + sim R)) (fun _ => option_le eq) ML1 ML2.\n  Proof.\n    intros D1 D2 (M1 & L1) (M2 & L2) R (Hle & Hsim); simpl in *.\n    split.\n    - unfold get_module_layer_function; simpl.\n      repeat match goal with\n             | |- res_le _ (res_option_inj ?a ?b) _ =>\n               let A := fresh \"A\" in\n               let f := fresh \"f\" in\n               let msg := fresh \"msg\" in\n               destruct a as [[f|]|msg] eqn:A; simpl;\n                 let B := fresh \"B\" in\n                 let v := fresh \"v\" in\n                 let msg := fresh \"msg\" in\n                 destruct b as [[v|]|msg] eqn:B; simpl\n             | H: le ?M1 ?M2, A: get_module_function ?i ?M1 = _ |- _\n               =>\n               generalize (get_module_function_monotonic i _ _ H); rewrite A;\n                 let C := fresh \"C\" in\n                 intro C; inv C; revert A\n             | H: sim ?R ?L1 ?L2, A: get_layer_primitive ?i ?L1 = _ |- _\n               =>\n               generalize (get_layer_primitive_sim_monotonic _ _ R i _ _ H); rewrite A;\n                 let C := fresh \"C\" in\n                 intro C; inv C; revert A\n             | H: option_le _ (Some _) _ |- _ => inv H\n             | |- _ => simpl; repeat constructor\n             end; intros; repeat rstep.\n      + destruct y0; repeat constructor.\n      + destruct y; repeat constructor. auto.\n      + destruct y; repeat constructor.\n      + destruct y; repeat constructor.\n    - unfold get_module_layer_variable; simpl.\n      repeat match goal with\n             | |- res_le _ (_ (get_module_variable ?i ?M1) ?b) _ =>\n               let A := fresh \"A\" in\n               let f := fresh \"f\" in\n               let msg := fresh \"msg\" in\n               destruct (get_module_variable i M1) as [[f|]|msg] eqn:A; simpl;\n                 let B := fresh \"B\" in\n                 let v := fresh \"v\" in\n                 let msg := fresh \"msg\" in\n                 destruct b as [[v|]|msg] eqn:B; simpl\n             | H: le ?M1 ?M2, A: get_module_variable ?i ?M1 = _ |- _\n               =>\n               generalize (get_module_variable_monotonic i _ _ H); rewrite A;\n                 let C := fresh \"C\" in\n                 intro C; inv C; revert A\n             | H: sim ?R ?L1 ?L2, A: get_layer_globalvar ?i ?L1 = _ |- _\n               =>\n               generalize (get_layer_globalvar_sim_monotonic _ _ R i _ _ H); rewrite A;\n                 let C := fresh \"C\" in\n                 intro C; inv C; revert A\n             | H: option_le _ (Some _) _ |- _ => inv H\n             end; intros; repeat rstep.\n  Qed.\n\n  Global Instance make_program_monotonic:\n    Monotonic\n      make_program\n      (forallr -, (≤) * (≤) ++> res_le (program_le (fun _ => eq))).\n  Proof.\n    intros D ML1 ML2 HML.\n    unfold program_le.\n    assert\n      ((- ==> subrel)%rel\n         (fundef_rel D D (fun i => option_le (eq + sim id)))\n         (fun i => option_le eq)).\n    {\n      intros i x y Hxy.\n      destruct Hxy as [fm1 fp1 Hf1 fm2 fp2 Hf2 Hfm].\n      destruct Hf1, Hf2; inversion Hfm; constructor; subst.\n      destruct H3; try congruence.\n      unfold match_fundef in *; simpl in *.\n      pose proof (make_external_monotonic i i eq_refl _ _ H1) as Hme.\n      destruct Hme; congruence.\n    }\n    assert\n      ((- ==> subrel)%rel\n         (vardef_rel (fun i => option_le eq))\n         (fun i => option_le eq)).\n    {\n      intros i x y Hxy.\n      destruct Hxy as [vm1 vp1 Hv1 vm2 vp2 Hv2 Hvm].\n      + destruct Hv1, Hv2; inversion Hvm; constructor; subst.\n        unfold match_vardef in *; simpl in *.\n        congruence.\n    }\n    pose (subrel_at := fun A B (R1 R2: rel A B) (HR: subrel R1 R2) x y (H: R1 x y) => HR x y H).\n    eapply @subrel_at.\n    - eapply res_le_monotonic.\n      eapply program_subrel;\n      eassumption.\n    - assert\n        (forall i,\n           Monotonic\n             (make_fundef D i)\n             (option_le (eq + sim id) @@ (Some) ++> impl @@ (isError))).\n      {\n        intros i f1 f2 Hf.\n        inversion Hf; clear Hf; subst.\n        unfold make_fundef.\n        repeat rstep.\n        + subst.\n          reflexivity.\n        + eapply @make_external_monotonic; eauto. (* ?? *)\n      }\n      assert\n        (Monotonic make_varinfo (option_le eq @@ (Some) ++> impl @@ (isError))).\n      {\n        intros v1 v2 Hv.\n        inversion Hv; clear Hv; subst.\n        reflexivity.\n      }\n      eapply make_program_rel. (** FIXME: monotonicity should work *)\n      + typeclasses eauto.\n      + apply module_layer_rel_intro; auto.\n  Qed.\n\n  Global Instance make_program_monotonic_params:\n    Params (@make_program) 2.\n\n  Global Instance make_globalenv_monotonic:\n    Monotonic\n      make_globalenv\n      (forallr -, (≤) * (≤) ++> res_le (genv_le (fun _ => eq))).\n  Proof.\n    unfold make_globalenv, ret; simpl.\n    rauto.\n  Qed.\n\n  Global Instance make_globalenv_monotonic_params:\n    Params (@make_globalenv) 2.\n\n  Global Instance make_program_sim_monotonic:\n    Monotonic\n      (fun D => make_external D)\n      (forallr R, - ==> sim R ++> res_le eq) ->\n    Monotonic\n      (fun D => make_program D)\n      (forallr R, (≤) * sim R ++> res_le (program_le (fun _ => eq))).\n  Proof.\n    intros Hme D1 D2 R ML1 ML2 HML.\n    unfold program_le.\n    assert\n      ((- ==> subrel)%rel\n         (fundef_rel D1 D2 (fun i => option_le (eq + sim R)))\n         (fun i => option_le eq)).\n    {\n      intros i x y Hxy.\n      destruct Hxy as [fm1 fp1 Hf1 fm2 fp2 Hf2 Hfm].\n      destruct Hf1, Hf2; inversion Hfm; constructor; subst.\n      destruct H3; unfold match_fundef in *; simpl in *; try congruence.\n      pose proof (Hme D1 D2 R i _ _ H1) as Hme'.\n      simpl in *.\n      destruct Hme'; congruence.\n    }\n    assert\n      ((- ==> subrel)%rel\n         (vardef_rel (fun i => option_le eq))\n         (fun i => option_le eq)).\n    {\n      intros i x y Hxy.\n      destruct Hxy as [vm1 vp1 Hv1 vm2 vp2 Hv2 Hvm].\n      + destruct Hv1, Hv2; inversion Hvm; constructor; subst.\n        unfold match_vardef in *; simpl in *.\n        congruence.\n    }\n    pose (subrel_at := fun A B (R1 R2: rel A B) (HR: subrel R1 R2) x y (H: R1 x y) => HR x y H).\n    eapply @subrel_at.\n    - eapply res_le_monotonic.\n      eapply program_subrel; eassumption.\n    - assert\n        (forall i,\n           Related\n             (make_fundef D1 i)\n             (make_fundef D2 i)\n             (option_le (eq + sim R) @@ (Some) ++> impl @@ (isError))).\n      {\n        intros i f1 f2 Hf.\n        inversion Hf; clear Hf; subst.\n        unfold make_fundef.\n        repeat rstep.\n        + subst.\n          reflexivity.\n        + eapply Hme; eauto.\n      }\n      assert\n        (Monotonic make_varinfo (option_le eq @@ (Some) ++> impl @@ (isError))).\n      {\n        intros v1 v2 Hv.\n        inversion Hv; clear Hv; subst.\n        reflexivity.\n      }\n      eapply make_program_rel. (** FIXME: monotonicity should work *)\n      + typeclasses eauto.\n      + apply module_layer_rel_intro; auto.\n  Qed.\n\n  (** * Other global properties *)\n\n  Lemma make_program_layer_ok {D} M L:\n    isOK (make_program D (M, L)) ->\n    LayerOK L.\n  Proof.\n    intros [p Hp] i.\n    split.\n    - destruct (make_program_noconflict D M L p i Hp); eauto.\n    - destruct (make_program_noconflict D M L p i Hp); eauto.\n    - destruct (make_program_noconflict D M L p i Hp); eauto.\n  Qed.\n\n  Lemma make_program_module_ok {D} M L:\n    isOK (make_program D (M, L)) ->\n    ModuleOK M.\n  Proof.\n    intros [p Hp] i.\n    split.\n    - destruct (make_program_noconflict D M L p i Hp); eauto.\n    - destruct (make_program_noconflict D M L p i Hp); eauto.\n    - destruct (make_program_noconflict D M L p i Hp); eauto.\n  Qed.\n\n  Lemma make_program_module_layer_disjoint {D} M L:\n    isOK (make_program D (M, L)) ->\n    module_layer_disjoint M L.\n  Proof.\n    intros [p Hp] i.\n    apply (make_program_noconflict D M L p i Hp).\n  Qed.\n\n  (** Our specification is probably not sufficient to prove\n    [make_program_exists] below, but it should be possible to replace\n    uses of that lemma.\n\n      <<<\n      make_program_exists {D} (L: _ D) M:\n        LayerOK L ->\n        ModuleOK M ->\n        (forall i fe, get_layer_primitive i L = OK (Some fe) ->\n                      isOK (make_external D i fe) /\\\n                      isOKNone (get_module_function i M) /\\\n                      isOKNone (get_module_variable i M) /\\\n                      (i < glob_threshold)%positive) ->\n        (forall i fi, get_module_function i M = OK (Some fi) ->\n                      isOK (make_internal fi) /\\\n                      isOKNone (get_layer_primitive i L) /\\\n                      isOKNone (get_layer_globalvar i L) /\\\n                      (i < glob_threshold)%positive) ->\n        (forall i v, get_layer_globalvar i L = OK (Some v) ->\n                     isOKNone (get_module_function i M) /\\\n                     isOKNone (get_module_variable i M) /\\\n                     (i < glob_threshold)%positive) ->\n        (forall i v, get_module_variable i M = OK (Some v) ->\n                     isOKNone (get_layer_primitive i L) /\\\n                     isOKNone (get_layer_globalvar i L) /\\\n                     (i < glob_threshold)%positive) ->\n        isOK (make_program D (M, L))\n      >>>\n  *)\n\n  (** We could add this one to the spec, but actually it should be\n    enough that the [main] of two programs are equal, we don't need to\n    know the specific identifier.\n\n      <<<\n      make_program_prog_main\n        {D} (L: layer D)\n        (M: module) (p: _)\n        (prog: make_program D (M, L) = OK p)\n      :\n        (prog_main p) = xH;\n      >>>\n   *)\nEnd MAKE_PROGRAM_FACTS.\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/CAL/liblayers/compcertx/MakeProgramFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.22978018499994896}}
{"text": "Require Export TrInccount.\nRequire Export TrInckn.\n\n\nSection TrIncvreq_mon.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext        }.\n  Context { minbft_context      : MinBFT_context      }.\n  Context { m_initial_keys      : MinBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys   }.\n  Context { usig_hash           : USIG_hash           }.\n  Context { minbft_auth         : MinBFT_auth         }.\n\n\n  Lemma vreq_monotonic_step :\n    forall {eo : EventOrdering} (e : Event) r s u l s' c t (ls : MinBFTls),\n      M_run_ls_on_this_one_event (MinBFTlocalSys_new r s u l) e = Some ls\n      -> state_of_component MAINname ls = Some s'\n      -> find_latest_executed_request c (vreq s) = Some t\n      -> exists t',\n          find_latest_executed_request c (vreq s') = Some t'\n          /\\ t <= t'.\n  Proof.\n    introv run eqst find.\n    apply map_option_Some in run; exrepnd; simpl in *; rev_Some; minbft_simp.\n    unfold M_run_ls_on_input_ls, M_run_ls_on_input in *; simpl in *.\n    autorewrite with minbft in *.\n\n    Time minbft_dest_msg Case;\n      repeat (simpl in *; autorewrite with minbft in * );\n      repeat smash_minbft2; eauto.\n  Qed.\n\n  Lemma vreq_monotonic :\n    forall {eo : EventOrdering} (e1 e2 : Event) s1 s2 c t,\n      is_replica e1\n      -> e1 ⊏ e2\n      -> M_state_sys_on_event MinBFTsys e1 MAINname = Some s1\n      -> M_state_sys_before_event MinBFTsys e2 MAINname = Some s2\n      -> find_latest_executed_request c (vreq s1) = Some t\n      -> exists t',\n          find_latest_executed_request c (vreq s2) = Some t'\n          /\\ t <= t'.\n  Proof.\n    introv isrep lte eqsta eqstb find.\n    unfold M_state_sys_on_event, M_state_sys_before_event in *.\n    unfold is_replica in *; exrepnd.\n    applydup local_implies_loc in lte as eqloc.\n    rewrite <- eqloc in *.\n    rewrite isrep0 in *; simpl in *.\n\n    unfold M_state_ls_on_event, M_state_ls_before_event in *.\n    apply map_option_Some in eqsta; exrepnd; rev_Some.\n    apply map_option_Some in eqstb; exrepnd; rev_Some.\n\n    clear eqloc isrep0.\n\n    revert dependent a0.\n    revert dependent s2.\n    revert dependent e2.\n\n    induction e2 as [e ind] using predHappenedBeforeInd;[]; introv lte eqst2 comp2.\n\n    apply local_implies_pred_or_local in lte; repndors.\n\n    { rewrite M_run_ls_before_event_as_M_run_ls_on_event_pred in eqst2; eauto 3 with eo;[].\n      unfold local_pred in eqst2; rewrite lte in eqst2.\n      rewrite eqsta1 in eqst2; ginv.\n      rewrite comp2 in eqsta0; ginv.\n      eexists; dands; eauto. }\n\n    exrepnd.\n    pose proof (ind e0) as ind; repeat (autodimp ind hyp);[].\n    rewrite M_run_ls_before_event_unroll in eqst2.\n    assert (~ isFirst e) as nif by eauto 3 with eo.\n    destruct (dec_isFirst e) as [d|d]; tcsp;[].\n    apply map_option_Some in eqst2; exrepnd; rev_Some.\n    applydup M_run_ls_before_event_ls_is_minbft in eqst1; exrepnd; subst; simpl in *.\n    unfold local_pred in eqst0; rewrite lte1 in eqst0.\n    unfold local_pred in eqst1; rewrite lte1 in eqst1.\n\n    pose proof (ind s (MinBFTlocalSys_new r s s0 s3)) as ind.\n    repeat (autodimp ind hyp);[].\n    exrepnd.\n    eapply vreq_monotonic_step in eqst0; try exact ind1;[|eauto].\n    exrepnd.\n    eexists; dands; eauto; try omega.\n  Qed.\n\nEnd TrIncvreq_mon.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/TrIncvreq_mon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.22978018499994893}}
{"text": "Require Import List String.\nImport ListNotations.\nOpen Scope string.\n\nFrom MetaCoq.Template Require Import All.\nImport MonadNotation.\nFrom ASUB Require Import AssocList Language Quotes Utils DeBruijnMap Monad TemplateMonadUtils Names GallinaGen GenM VariableDSL.\nLoad Termutil.\n\nModule helper.\n  Import GenM.Notations GenM.\n\n  (** Generate all the liftings (= Up = fatarrow^y_x) for all pairs of sorts in the current component.\n   ** So that we can later build the lifting functions \"X_ty_ty\", \"X_ty_vl\" etc. *)\n  Definition getUps (component: list tId) (remove: list (tId * tId)) : (list (tId * tId) * list (Binder * tId)) :=\n    let cart := cartesian_product component component in\n    let cart := list_diff_prod cart remove in\n    let singles := map (fun '(x, y) => (Single x, y)) cart in\n    (* let blists := map (fun '(x, y) => (BinderList (\"p\", x), y)) cart in *)\n    (* TODO scoped append blists *)\n    (cart, singles).\n  \n  Definition upList_ty :=\n    let m := substSorts <- substOf \"ty\";;\n             let '(_, upList) := getUps substSorts [] in\n             pure upList in\n    match run m (Hsig_example.mySig, initial_env) empty_state with\n    | inl _ => []\n    | inr (_, _, x) => x\n    end.\n\n  Definition upList_tm :=\n    let m := substSorts_ty <- substOf \"ty\";;\n             substSorts <- substOf \"tm\";;\n             let '(combinations, _) := getUps substSorts_ty [] in\n             let '(_, upList) := getUps substSorts combinations in\n             pure upList in\n    match run m (Hsig_example.mySig, initial_env) empty_state with\n    | inr (_, _, x) => x\n    | _ => []\n    end.\nEnd helper.\nImport helper.\n\nModule inductives.\n  Import GenM GenM.Notations.\n  \n  (** get the quoted type of an argument *)\n  Definition getArgType (p: Position) : t nterm :=\n    let '{| pos_binders := _;\n            pos_head := hd |} := p in\n    let sort := match hd with\n                | Atom sort => sort\n                (* TODO funapp *)\n                | FunApp _ _ _ => \"\"\n                end in\n    pure (nRef sort).\n\n  (* Generates the type of a variable constructor for a sort\n db : base deBruijn index, should move into a reader monad *)\n  Definition genVarConstrType (sort: tId) : nterm :=\n    let s := genVarArg sort in\n    let typ := mknArr s [nRef sort] in\n    typ.\n\n  (* generates the type of a single argument of a constructor *)\n  Definition genArg (sort: string) (pos : Position) : t nterm :=\n    let '{| pos_binders := pos_binders; pos_head := pos_head |} := pos in\n    match pos_head with\n    | Atom argSort =>\n      (* TODO lift scopes *)\n      (* have to differentiate between sorts in the current component and sorts that are already in the environment *)\n      pure (nRef argSort)\n    (* TODO implement funapp case *)\n    | FunApp _ _ _ => pure nat_\n    end.\n\n  (** * Generates the type of a given constructor for a sort *)\n  Definition genConstructor (sort: tId) (c: Constructor) : t nterm :=\n    let '{| con_parameters := con_parameters;\n            con_name := _;\n            con_positions := con_positions |} := c in\n    (* need to fold over the positions to update the dbmap.\n     * Also remember that arg needs to be appended to the list because it's a left fold *)\n    up_n_x <- a_map (genArg sort) con_positions;;\n    (* todo take care of parameters *)\n    let targetType := nRef sort in\n    pure (mknArrRev up_n_x targetType).\n\n  (** * Generates a one_inductive_entry which holds the information for a single inductive type for a given sort based on the spec *)\n  Definition genOneInductive (dbmap: DB.t) (sort: tId) : t one_inductive_entry :=\n    ctors <- constructors sort;;\n    sortIsOpen <- isOpen sort;;\n    (* introScopeVar *)\n    let ctor_names := map con_name ctors in\n    ctor_ntypes <- a_map (genConstructor sort) ctors;;\n    (* maybe we also add a variable constructor *)\n    let '(ctor_names, ctor_ntypes) :=\n        if sortIsOpen\n        then (varConstrName sort :: ctor_names, genVarConstrType sort :: ctor_ntypes)\n        else (ctor_names, ctor_ntypes) in\n    (* register the type & ctor names to be put in the environment later *)\n    register_names (sort :: ctor_names);;\n    (* translate into TemplateCoq terms *)\n    ctor_types <- a_map (translate dbmap) ctor_ntypes;;\n    pure {|\n        mind_entry_typename := sort;\n        mind_entry_arity := tSort Universe.type0;\n        mind_entry_consnames := ctor_names;\n        mind_entry_lc := ctor_types \n      |}.\n\n  (** * Generates a mutual_inductive_entry which combines multiple one_inductive_entry's into a mutual inductive type definition.\n   ** * For each sort in the component, a one_inductive_entry is generated *)\n  Definition genMutualInductive (component: list tId) : t mutual_inductive_entry :=\n    (* the entries already use deBruin numbers as if they were sequentially bound.\n     * i.e. the last entry has index 0. Therefore we can just add the component *)\n    (* only generate the definable sorts *)\n    def_sorts <- a_filter isDefinable component;;\n    let dbmap := DB.adds def_sorts DB.empty in\n    (* component also would contain predefined types like nat so we pass in def_sorts all the way down to genVarConstrType so that we also get nat out of the environment *)\n    entries <- a_map (genOneInductive dbmap) def_sorts;;\n    pure {|\n        mind_entry_record := None;\n        mind_entry_finite := Finite;\n        mind_entry_params := [];\n        mind_entry_inds := entries;\n        mind_entry_universes := Monomorphic_entry (LevelSet.empty, ConstraintSet.empty);\n        mind_entry_template := false;\n        mind_entry_variance := None;\n        mind_entry_private := None;\n      |}.\n\n  (* Eval cbv in (run (genMutualInductive [\"ty\"]) Hsig_example.mySig empty_state). *)\nEnd inductives.\nImport inductives.\n\n(** * TemplateMonad function to generate and unquote inductive types.\n ** * It returns an updated environment that contains the new types and their constructors. *)\nDefinition mkInductive (s: Signature) (component: list tId) (env: SFMap.t term) : TemplateMonad (SFMap.t term) :=\n  match GenM.run (genMutualInductive component) (s, env) empty_state with\n  | inr (_, state, mind) =>\n    tmMkInductive mind;;\n    tm_update_env state env\n  | inl e => tmFail e\n  end.\n\nMetaCoq Run (mkInductive Hsig_example.mySig [\"ty\"%string] GenM.initial_env  >>= tmEval TemplateMonad.Common.all >>= mkInductive Hsig_example.mySig [\"tm\"; \"vl\"] >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env0\").\n\n\nDefinition nlemma : Type := string * nterm * nterm.\nDefinition lemma : Type := string * term * term.\n\nModule congruences.\n  Import GenM GenM.Notations.\n\n  Definition congrName (sort: tId) := sep \"congr\" sort.\n        \n  (** * generates the terms for the congruence lemmas for a constructor of an inductive type *)\n  Definition genCongruence (sort: tId) (ctor: Constructor) : t nlemma :=\n    let '{| con_parameters := con_parameters;\n            con_name := con_name;\n            con_positions := con_positions |} := ctor in\n    let ctor_tm := nRef con_name in\n    (* arguments to the lemma *)\n    let ss := getPattern \"s\" con_positions in\n    let ts := getPattern \"t\" con_positions in\n    arg_tys <- a_map getArgType con_positions;;\n    let eqs := map2 (fun s t => eq_ (nRef s) (nRef t)) ss ts in\n    let Hs := getPattern \"H\" con_positions in\n    (* building the binders of the lemma *)\n    let bss := combine ss arg_tys in\n    let bts := combine ts arg_tys in\n    let beqs := combine Hs eqs in\n    let proof := add_binders (bss ++ bts ++ beqs) in\n    (* body of the lemma *)\n    let (_, proof') := fold_left\n                         (fun '(i, tm) '(arg_typ, s, t, H) =>\n                            let feq_args := map nRef (firstn i ts ++ [\"x\"] ++ skipn (S i) ss) in\n                            let feq_lam := nLambda \"x\" nHole (nApp ctor_tm feq_args) in\n                            let feq := f_equal_ feq_lam (nRef s) (nRef t) (nRef H) in\n                            (S i, eq_trans_ tm feq))\n                         (combine (combine (combine arg_tys ss) ts) Hs)\n                         (0, eq_refl_) in\n    (* generate and register lemma name *)\n    let name := congrName con_name in\n    register_name name;;\n    (* generate the type of the lemma *)\n    let type := add_tbinders (bss ++ bts ++ beqs) in\n    let type' := eq_ (nApp ctor_tm (map nRef ss)) (nApp ctor_tm (map nRef ts)) in\n    pure (name, type type', proof proof').\n\n\n  (** * generates the terms for the congruence lemmas of the constructors of an inductive type *)\n  Definition genCongruences (sort: tId) : t (list lemma) :=\n    ctors <- constructors sort;;\n    a_map (fun ctor => translate_lemma (genCongruence sort ctor)) ctors.\nEnd congruences.\nImport congruences.\n\n\n(* Definition bind' := @bind TemplateMonad TemplateMonad_Monad. *)\n(* Arguments bind' {t u}. *)\n\n(* TODO seems like I still can't use implicit arguments.\n * The problem is now that to use tmUnquoteTyped I would need a Coq type (not in the MetaCoq AST) but when I unquote it, the typechecker does not know it's actually a type.\n * But in theory this should be possible to resolve by defining something like tmUnquoteType (no d) that gives me back a type (in this case the typed_term is not interesting because the first element will always be \"Type\") *)\n(* Definition mkLemma '(lname, lbody, ltype) : TemplateMonad unit := *)\n(*   bind' (tmUnquote ltype) *)\n(*        (fun type : typed_term => *)\n(*           bind' (tmEval lazy (my_projT2 type)) *)\n(*                (fun type0 : _ => *)\n(*                   bind' (tmUnquoteTyped type0 lbody) *)\n(*                        (fun body : _ => *)\n(*                           bind' (tmDefinitionRed lname (Some TemplateMonad.Common.all) body) *)\n(*                                (fun _ => tmReturn tt)))). *)\n\n(** * Helper function that does the actual unquoting to define alemma *)\n(* Definition mkLemma' '(lname, lbody) : TemplateMonad unit := *)\n(*   body <- tmUnquote lbody;; *)\n(*   body <- tmEval lazy (my_projT2 body);; *)\n(*   (* TODO In System F the all constructor shadowed the reductionStrategy. Is there a better way to avoid redefined names? I could put all unquoted definitions into their own module *) *)\n(*   tmDefinitionRed lname (Some TemplateMonad.Common.all) body;; *)\n(*   tmReturn tt. *)\n\n(* (** * TemplateMonad function to generate and unquote lemmas. *) *)\n(* Definition mkLemma (m: GenM.t (list (string * term))) (s: Signature) (env: SFMap.t term): TemplateMonad (SFMap.t term) := *)\n(*   match GenM.run m s empty_state with *)\n(*   | inl e => tmFail e *)\n(*   | inr (_, state, lemmas) => *)\n(*     tm_mapM mkLemma' lemmas;;  *)\n(*     tm_update_env state *)\n(*   end.  *)\n\nDefinition mkLemmasTyped (m: GenM.t (list lemma)) (s: Signature) (env: SFMap.t term): TemplateMonad (SFMap.t term) :=\n  match GenM.run m (s, env) empty_state with\n  | inl e => tmFail e\n  | inr (_, state, lemmas) =>\n    tm_mapM tmTypedDefinition lemmas;; \n    tm_update_env state env\n  end. \n\nDefinition mkCongruences (sort: tId) := mkLemmasTyped (genCongruences sort).\n\nMetaCoq Run (mkLemmasTyped (genCongruences \"ty\") Hsig_example.mySig env0 >>= tmEval TemplateMonad.Common.all >>=\n                          mkLemmasTyped (genCongruences \"tm\") Hsig_example.mySig >>= tmEval TemplateMonad.Common.all >>= mkLemmasTyped (genCongruences \"vl\") Hsig_example.mySig >>= tmEval TemplateMonad.Common.all >>=\n                          tmDefinition \"env1\").\n\nModule renamings.\n  Import GenM.Notations GenM.\n\n  (* TODO if I want to actually use isRec I would need to change the dbody of all the fexprs so I probably won't use it. *)\n  (* convert a list of fixpoint bodies into as many fixpoint definitions. Each fixpoint definitions references all the fixpoint bodies but has a different index into the list of bodies. *)\n  Definition buildFixpoint (fixBodies: list (def nterm)) (isRec: bool) : t (list lemma) :=\n    fixNames <- a_map get_fix_name fixBodies;;\n    register_names fixNames;;\n    let fixExprs :=  mapi (fun n _ => nFix fixBodies n) fixBodies in\n    fixExprs <- a_map (translate DB.empty) fixExprs;;\n    pure (map2 (fun name t => (name, hole, t)) fixNames fixExprs).\n\n  Definition upRenName (x: string) (b: Binder) :=\n    match b with\n    | Single sort' => sepd [\"upRen\"; x; sort']\n    end.\n  Definition upName (x: string) (b: Binder) :=\n    match b with\n    | Single sort' => sepd [\"up\"; x; sort']\n    end.\n\n  Definition renName (x: string) := sep \"ren\" x.\n\n  Definition genUpRen (bs: Binder * tId) : t (string * nterm * nterm) :=\n    let '(binder, sort) := bs in\n    let '(xi, bxi) := genRenS \"xi\" in\n    (* let '(_, bpms) := bparameters binder in *)\n    let preProof := definitionBody sort binder (up_ren_ xi) xi in\n    let proof := add_binders [ bxi ] preProof in\n    let preType := nArr nat_ nat_ in\n    let type := add_tbinders [bxi] preType in\n    let name := upRenName sort binder in\n    register_name name;;\n    pure (name, type, proof).\n\n  Definition genUpRens (bss: list (Binder * tId)) : t (list (string * term * term)) :=\n    a_map (fun bs => translate_lemma (genUpRen bs)) bss.\n\n  Definition aname_ (name: string) : aname := {| binder_name := nNamed name; binder_relevance := Relevant |}.\n\n  (* TODO implement *)\n  (* Definition mk_underscore_pattern (scope: tId) := []. *)\n\n  Definition hasArgs (sort: tId) : t bool :=\n    substSorts <- substOf sort;;\n    match substSorts with\n    | [] => pure false\n    | _ => pure true\n    end.\n\n  Definition branch_ (underscoreNum: nat) (binders: list string) (body: nterm) : (nat * nterm) :=\n    let paramNum := underscoreNum + List.length binders in\n    let binders := List.map (fun n => (n, nHole)) binders in\n    let body := add_binders binders body in\n    (paramNum, body).\n  \n  Definition mk_var_pattern (sort: tId) (var_case_body: nterm -> t nterm) : t (list (nat * nterm)) :=\n    sortIsOpen <- isOpen sort;;\n    if sortIsOpen\n    then\n      let s0 := \"s0\" in\n      var_body <- var_case_body (nRef s0);;\n      pure [ branch_ 0 [s0] var_body ]\n    else pure [].\n\n  Definition up (sort: tId) (f: tId -> Binder -> nterm -> nterm) (n: list nterm) (b: Binder) : t (list nterm) :=\n    substSorts <- substOf sort;;\n    pure (map2 (fun p n_i => f p b n_i) substSorts n).\n\n  Definition ups (sort: tId) (f: string -> Binder -> nterm -> nterm) := m_fold_left (up sort f).\n\n  Definition succ_ (n: nterm) (z: string) (b: Binder) :=\n    match b with\n    | Single x => if eqb z x\n                 then nApp (nRef \"S\") [n] else n\n    end.\n  \n  Definition upScope (sort: tId) (binders: list Binder) (terms: list nterm) := ups sort (fun (z: string) (b: Binder) (n: nterm) => succ_ n z b) terms binders.\n\n  Definition upRen (sort: tId) (binders: list Binder) (terms: list nterm) := ups sort (fun (z: string) (b: Binder) (xi: nterm) => nApp (nRef (upRenName z b)) [ xi ]) terms binders.\n\n  Definition upSubstS (sort: tId) (binders: list Binder) (terms: list nterm) := ups sort (fun (z: string) (b: Binder) (sigma: nterm) => nApp (nRef (upName z b)) [ sigma ]) terms binders.\n\n  Definition up' (x: string) (f: tId -> Binder -> nterm -> t nterm) (n: list nterm) (b: Binder) : t (list nterm) :=\n    substSorts <- substOf x;;\n    a_map (fun '(p, n_i) => f p b n_i) (combine substSorts n).\n\n  Definition upEq (sort: tId) (binders: list Binder) (terms: list nterm) (f: tId -> Binder -> nterm -> t nterm) :=\n    m_fold_left (up' sort f) terms binders.\n  \n  Definition upSubst (sort: tId) (binders: list Binder) (st: SubstTy) :=\n    match st with\n    | SubstScope ns nts => fmap (fun nts => SubstScope ns nts) (upScope sort binders nts)\n    | SubstRen nts => fmap (fun nts => SubstRen nts) (upRen sort binders nts)\n    | SubstSubst nts => fmap (fun nts => SubstSubst nts) (upSubstS sort binders nts)\n    | SubstEq nts f => fmap (fun nts => SubstEq nts f) (upEq sort binders nts f)\n    end.\n  \n  Definition cast (sort sort': tId) (nts: list nterm) :=\n    substSorts <- substOf sort;;\n    substSorts' <- substOf sort';;\n    pure (List.fold_right (fun '(x, v) ws => if list_mem x substSorts' then v :: ws else ws)\n                          [] (combine substSorts nts)).\n\n  Definition castSubst (sort sort': tId) (st: SubstTy) :=\n    match st with\n    | SubstScope ns nts => fmap (fun nts => SubstScope ns nts) (cast sort sort' nts)\n    | SubstRen nts => fmap (fun nts => SubstRen nts) (cast sort sort' nts)\n    | SubstSubst nts => fmap (fun nts => SubstSubst nts) (cast sort sort' nts)\n    | SubstEq nts f => fmap (fun nts => SubstEq nts f) (cast sort sort' nts)\n    end.\n\n  Definition castUpSubst (sort: tId) (binders: list Binder) (sort': tId) (st: SubstTy) : t SubstTy :=\n    st' <- castSubst sort sort' st;;\n    upSubst sort' binders st'.\n\n  Definition abs_ref x t := nLambda x nHole t.\n\n  Fixpoint arg_map (sort: tId) (args: list SubstTy) (name: string -> string) (no_args: nterm -> nterm) (funsem: string -> list nterm -> nterm) (bs: list Binder) (arg: ArgumentHead) :=\n    match arg with\n    | Atom y =>\n      b <- hasArgs y;;\n      args <- a_map (castUpSubst sort bs y) args;;\n      pure (if b\n            then nApp (nRef (name y)) (flat_map sty_terms args)\n            else abs_ref \"x\" (no_args (nRef \"x\")))\n    | FunApp f p xs =>\n      res <- a_map (arg_map sort args name no_args funsem bs) xs;;\n      pure (funsem f res)\n    end.\n\n  \n  Definition mk_constr_pattern (s: string) (sort: tId) (args: list SubstTy) (name: string -> string) (no_args: nterm -> nterm) (sem: list string -> string -> list nterm -> nterm) (funsem: string -> list nterm -> nterm) (ctor: Constructor) : t (nat * nterm) :=\n    let '{| con_parameters := cparameters; con_name := cname; con_positions := cpositions |} := ctor in\n    let ss := getPattern \"s\" cpositions in\n    positions <- a_map (fun '(s, {| pos_binders := binders; pos_head := head |}) =>\n                         fmap2 nApp (arg_map sort args name no_args funsem binders head) (pure [ nRef s ]))\n                      (combine ss cpositions);;\n    let paramNames := List.map fst cparameters in\n    pure (branch_ 0 (List.app paramNames ss) (sem paramNames cname positions)).\n  \n  Definition traversal (sort: tId) (name: string -> string) (no_args: nterm -> nterm) (ret: nterm -> nterm) (bargs: list (string * nterm)) (args: list SubstTy) (var_case_body: nterm -> t nterm) (sem: list string -> string -> list nterm -> nterm) (funsem: string -> list nterm -> nterm) : t (def nterm) :=\n    ctors <- constructors sort;;\n    let s := \"s\" in\n    let lambdas := List.app bargs [(s, nRef sort)] in\n    (** * the structural argument\n     * it's always the last one so it's the length of all outermost binders\n     * TODO can we move all other binders outside and have the mutual fixpoint bodies only take this argument?\n     * FIX: only set to length of bargs since we start counting at 0\n     *)\n    let argNum := List.length bargs in\n    (** * the type of the fixpoint *)\n    let innerType := ret (nRef s) in\n    let type := add_tbinders lambdas innerType in\n    (** * the body of the fixpoint *)\n    var_pattern <- mk_var_pattern sort var_case_body;;\n    constr_patterns <- a_map (mk_constr_pattern s sort args name no_args sem funsem) ctors;;\n    (* TODO calculate number of parameters *)\n    (* DONE fix elemination predicate. I tried putting a hole as the return type but Coq is not smart enough to infer it. But we can use the return type function we already have available. *)\n    let innerBody := nCase sort 0 (nLambda s (nRef sort) innerType) (nRef s) (List.app var_pattern constr_patterns) in\n    let body := add_binders lambdas innerBody in\n    pure {| dname := aname_ (name sort); dtype := type; dbody := body; rarg := argNum |}.\n\n  Definition genRen (name: string) (sort: tId) : t (SubstTy * list (string * nterm)) :=\n    substSorts <- substOf sort;;\n    let names := List.map (sep name) substSorts in\n    let binders := List.map (fun name => (name, nArr nat_ nat_)) names in\n    pure (SubstRen (List.map nRef names), binders).\n\n  Definition toVar (sort: tId) (ts: SubstTy) : t nterm :=\n    substSorts <- substOf sort;;\n    let zs := List.filter (fun '(substSort, _) => eqb sort substSort) (combine substSorts (sty_terms ts)) in\n    match zs with\n    | [] => error \"toVar was called with incompatible sort and substitution vector.\"\n    | z::_ => pure (snd z)\n    end.\n\n  Definition app_constr (cname: string) (rest: list nterm) : nterm :=\n    match rest with\n    | [] => nRef cname\n    | _ => nApp (nRef cname) rest\n    end.\n\n  Definition map_ f ts := nApp (nRef (sep f \"map\")) ts.\n\n  Definition genRenaming (sort: tId) : t (def nterm) :=\n    '(xis, bxis) <- genRen \"xi\" sort;;\n    substSorts <- substOf sort;;\n    let ret := fun _ => nRef sort in\n    traversal sort renName Datatypes.id ret bxis [ xis ]\n              (fun s => toVarT <- toVar sort xis;;\n                     pure (nApp (nRef (varConstrName sort)) [ nApp toVarT [ s ] ]))\n              (fun paramNames cname positions => app_constr cname (List.app (List.map nRef paramNames) positions))\n              map_.\n  \n  Definition genRenamings (component: NEList.t tId) : t (list lemma) :=\n    let componentL := NEList.to_list component in\n    isRec <- isRecursive component;;\n    fexprs <- a_map genRenaming componentL;;\n    buildFixpoint fexprs isRec.\nEnd renamings.\nImport renamings.\n\nMetaCoq Run (mkLemmasTyped (genUpRens upList_ty) Hsig_example.mySig env1 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env2\").\n\nMetaCoq Run (mkLemmasTyped (genRenamings (\"ty\", [])) Hsig_example.mySig env2 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env3\").\n\nMetaCoq Run (mkLemmasTyped (genUpRens upList_tm) Hsig_example.mySig env3 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env4\").\n\nMetaCoq Run (mkLemmasTyped (genRenamings (\"tm\", [\"vl\"])) Hsig_example.mySig env4 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env5\").\n\n\nModule substitutions.\n  Import GenM.Notations GenM.\n  (* From ASUB Require Import core. *)\n\n  \n  Definition substName (x: string) := sep \"subst\" x.\n\n  (* TODO first component should be nterm directly? *)\n  Definition genSubstS (name: string) (sort: tId) : nterm * (string * nterm) :=\n    (nRef name, (name, nArr nat_ (nRef sort))).\n  Definition genSubst (name: string) (sort: tId) :=\n    substSorts <- substOf sort;;\n    let names := List.map (sep name) substSorts in\n    let binders := map2 (fun name substSort => (name, nArr nat_ (nRef substSort))) names substSorts in\n    pure (SubstSubst (List.map nRef names), binders).\n\n  Definition var_constr (sort: tId) := nRef (varConstrName sort).\n\n  Definition shift (hasRen: bool) (substSorts: list tId) (sort: tId) :=\n    if hasRen\n    then shift_\n    else funcomp_ shift_ (nApp (var_constr sort) (List.map (fun _ => nHole) substSorts)).\n\n  Definition patternSId (sort: tId) (binder: Binder) :=\n    substSorts <- substOf sort;;\n    hasRen <- hasRenaming sort;;\n    up sort (fun substSort b _ => match b with\n                               | Single bsort =>\n                                 if eqb substSort bsort then shift hasRen substSorts substSort else id_\n                               end)\n       (List.map nRef substSorts) binder.\n            \n    \n  Definition mk_scons (sort: tId) (binder: Binder) (sigma: nterm) :=\n    match binder with\n    | Single sort' => if eqb sort sort'\n                     then\n                       let zero := nApp (nRef (varConstrName sort)) [var_zero_] in\n                       scons_ zero sigma\n                     else sigma\n    end.\n\n  Definition upSubstT (binder: Binder) (sort: tId) (sigma: nterm) : t nterm :=\n    hasRen <- hasRenaming sort;;\n    pat <- patternSId sort binder;;\n    let f := if hasRen\n             then nRef (renName sort)\n             else nRef (substName sort) in\n    let sigma' := sigma >>> (nApp f pat) in\n    pure (mk_scons sort binder sigma').                   \n\n  Definition genUp (bs: Binder * tId) : t nlemma :=\n    let '(binder, sort) := bs in\n    let '(sigma, bsigma) := genSubstS \"sigma\" sort in\n    (* let '(_, bpms) := bparameters binder in *)\n    innerBody <- upSubstT binder sort sigma;;\n    let body := add_binders [ bsigma ] innerBody in\n    let innerType := nArr nat_ (nRef sort) in\n    let type := add_tbinders [ bsigma ] innerType in\n    let name := upName sort binder in\n    register_name name;;\n    pure (name, type, body).\n\n  Definition genUps (bss: list (Binder * tId)) : t (list lemma) :=\n    a_map (fun bs => translate_lemma (genUp bs)) bss.\n\n  (** Generate the substitution function\n   ** e.g. subst_ty *)\n  Definition genSubstitution (sort: tId) : t (def nterm) :=\n    '(sigmas, bsigmas) <- genSubst \"sigma\" sort;;\n    traversal sort substName Datatypes.id (fun _ => nRef sort) bsigmas [ sigmas ]\n              (fun s =>\n                 toVarT <- toVar sort sigmas;;\n                 pure (nApp toVarT [ s ]))\n              (fun paramNames cname positions => app_constr cname (List.app (List.map nRef paramNames) positions))\n              map_.\n    \n  Definition genSubstitutions (component: NEList.t tId) : t (list lemma) :=\n    let componentL := NEList.to_list component in\n    isRec <- isRecursive component;;\n    fexprs <- a_map genSubstitution componentL;;\n    buildFixpoint fexprs isRec.\n    \nEnd substitutions.\nImport substitutions.\n\nMetaCoq Run (mkLemmasTyped (genUps upList_ty) Hsig_example.mySig env5 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env6\").\n\nMetaCoq Run (mkLemmasTyped (genSubstitutions (\"ty\", [])) Hsig_example.mySig env6 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env7\").\n\nMetaCoq Run (mkLemmasTyped (genUps upList_tm) Hsig_example.mySig env7 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env8\").\n\nMetaCoq Run (mkLemmasTyped (genSubstitutions (\"tm\", [\"vl\"])) Hsig_example.mySig env8 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env9\").\n\nModule idsubsts.\n  Import GenM.Notations GenM.\n\n  (** Create an extensional equivalence between unary functions s & t\n   ** forall x, s x = t x *)\n  Definition equiv_ (n: nterm) (s t: nterm) : nterm :=\n    let equality := eq_ (nApp s [ n ]) (nApp t [ n ]) in\n    equality.\n\n  Definition introDBVar (name: string) : nterm * (string * nterm) :=\n    (nRef name, (name, nat_)).\n  Definition genEqS (name: string) (bn: string * nterm) (sigma tau: nterm) : nterm * (string * nterm) :=\n    let '(n, nt) := bn in\n    (nRef name, (name, nProd n nt (equiv_ (nRef n) sigma tau))).\n\n  MetaCoq Run (tmQuote (match 0 with S n => n | O => O  end ) >>= tmPrint).\n\n  (* TODO f does not really need to be a function? *)\n  Definition matchFin_ (bn: string * nterm) (equality: nterm) (s: nterm) (f: nterm -> nterm) (b: nterm) :=\n    let '(n, nt) := bn in\n    let branches := [ (0, b); (1, nLambda \"n'\" nat_ (f (nRef \"n'\"))) ] in\n    let elimPred := nLambda n nt equality in\n    nCase \"nat\" 0 elimPred s branches.\n\n\n  Definition upIdName (sort: tId) (b: Binder) :=\n    match b with\n    | Single x => sepd [\"upId\"; x; sort]\n    end.\n  \n  Definition genUpId (bs: Binder * tId) : t nlemma :=\n    let '(binder, sort) := bs in\n    let '(sigma, bsigma) := genSubstS \"sigma\" sort in\n    let '(n, bn) := introDBVar \"n\" in\n    let '(eq, beq) := genEqS \"Eq\" bn sigma (nRef (varConstrName sort)) in\n    (** * type *)\n    let innerType := equiv_ n\n                       (nApp (nRef (upName sort binder)) [ sigma ])\n                       (nRef (varConstrName sort)) in\n    let type := add_tbinders [ bsigma; beq; bn ] innerType in\n    (** * body *)\n    shift <- patternSId sort binder;;\n    hasRen <- hasRenaming sort;;\n    let t := fun (n: nterm) =>\n               ap_ (nApp (nRef (if hasRen then renName sort else substName sort)) shift)\n                   (nApp eq [ n ]) in\n    let innerBody := definitionBody sort binder\n                                    (matchFin_ bn innerType n t eq_refl_) (t n) in\n    let body := add_binders [ bsigma; beq; bn ] innerBody in\n    (** * name *)\n    let name := upIdName sort binder in\n    register_name name;;\n    pure (name, type, body).\n  \n  Definition genUpIds (bss: list (Binder * tId)) : t (list lemma) :=\n    a_map (fun bs => translate_lemma (genUpId bs)) bss.\n\n  Definition mk_var_apps (sort: tId) : t (list nterm) :=\n    substSorts <- substOf sort;;\n    a_map (fun substSort => pure (nRef (varConstrName substSort))) substSorts.\n\n  Definition genEq (name: string) (sort: tId) (sigmas taus: list nterm) (f: string -> Binder -> nterm -> t nterm) :=\n    substSorts <- substOf sort;;\n    let names := List.map (sep name) substSorts in\n    let binders := map2 (fun n '(s, t) => (n, nProd \"x\" nHole (equiv_ (nRef \"x\") s t))) names (combine sigmas taus) in\n    pure (SubstEq (List.map nRef names) f, binders).\n\n  Definition idSubstName (sort: tId) := sep \"idSubst\" sort.\n  Definition mapId_ f ts := nApp (nRef (sep f \"id\")) ts.\n  Definition no_args_default := fun s => nApp eq_refl_ [ s ].\n\n  Fixpoint list_fill {A: Type} (a: A) (n: nat) : list A :=\n    match n with\n    | O => []\n    | S n => a :: list_fill a n\n    end.\n\n  (* TODO bettenr way to find out length of implicit arguments to congr.\n   * It would probably be best to save that information also in the environment.\n   * Like a list of all arguments where I mark which ones should be implicit *)\n  Definition sem_default := (fun (paramNames: list string) cname positions =>\n                               nApp (nRef (congrName cname)) (List.app (list_fill nHole (2 * List.length positions)) positions)).\n    \n  Definition genIdLemma (sort: tId) : t (def nterm) :=\n    '(sigmas, bsigmas) <- genSubst \"sigma\" sort;;\n    substSorts <- substOf sort;;\n    eqs' <- mk_var_apps sort;;\n    '(eqs, beqs) <- genEq \"Eq\" sort (sty_terms sigmas) eqs'\n                         (fun x y s => pure (nApp (nRef (upIdName x y)) [nHole; s]));;\n    let ret := fun s =>\n                 eq_ (nApp (nRef (substName sort)) (List.app (sty_terms sigmas) [ s ])) s in\n    traversal sort idSubstName no_args_default ret (List.app bsigmas beqs) [ sigmas; eqs ]\n              (fun s =>\n                 toVarT <- toVar sort eqs;;\n                 pure (nApp toVarT [ s ]))\n              sem_default\n              mapId_.\n  \n  Definition genIdLemmas (component: NEList.t tId) : t (list lemma) :=\n    let componentL := NEList.to_list component in\n    isRec <- isRecursive component;;\n    fexprs <- a_map genIdLemma componentL;;\n    buildFixpoint fexprs isRec.\nEnd idsubsts.\nImport idsubsts.\n\nMetaCoq Run (mkLemmasTyped (genUpIds upList_ty) Hsig_example.mySig env9 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env10\").\n\nMetaCoq Run (mkLemmasTyped (genIdLemmas (\"ty\", [])) Hsig_example.mySig env10 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env11\").\n\nMetaCoq Run (mkLemmasTyped (genUpIds upList_tm) Hsig_example.mySig env11 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env12\").\n\nMetaCoq Run (mkLemmasTyped (genIdLemmas (\"tm\", [\"vl\"])) Hsig_example.mySig env12 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env13\").\n\nModule extensionality.\n  Import GenM.Notations GenM.\n\n  Definition upNameGen (name: string) (sort: tId) (binder: Binder) :=\n    match binder with\n    | Single sort' => sepd [name; sort'; sort]\n    end.\n\n  Definition upExtRenName := upNameGen \"upExtRen\".\n  Definition upExtName := upNameGen \"upExt\".\n  \n  Definition genUpExtRen (bs: Binder * tId) : t nlemma :=\n    let '(binder, sort) := bs in\n    let '(xi, bxi) := genRenS \"xi\" in\n    let '(zeta, bzeta) := genRenS \"zeta\" in\n    let '(x, bx) := introDBVar \"x\" in\n    let '(eq, beq) := genEqS \"Eq\" bx xi zeta in\n    (* type *)\n    let innerType := equiv_ x (nApp (nRef (upRenName sort binder)) [ xi ]) (nApp (nRef (upRenName sort binder)) [ zeta ]) in\n    let type := add_tbinders [ bxi; bzeta; beq; bx ] innerType in\n    (* body *)\n    let innerBody := definitionBody sort binder\n                                    (matchFin_ bx innerType x (fun n => ap_ shift_ (nApp eq [n])) eq_refl_)\n                                    (nApp eq [x]) in\n    let body := add_binders [ bxi; bzeta; beq; bx ] innerBody in\n    (* name *)\n    let name := upExtRenName sort binder in\n    register_name name;;\n    pure (name, type, body).\n  \n  Definition genUpExtRens (bss: list (Binder * tId)) : t (list lemma) :=\n    a_map (fun bs => translate_lemma (genUpExtRen bs)) bss.\n\n  Definition mapExt_ f ts := nApp (nRef (sep f \"ext\")) ts.\n  Definition extRenName sort := sep \"extRen\" sort.\n  Definition extName sort := sep \"ext\" sort.\n  \n  Definition genExtRen (sort: tId) : t (def nterm) :=\n    '(xis, bxis) <- genRen \"xi\" sort;;\n    '(zetas, bzetas) <- genRen \"zeta\" sort;;\n    '(eqs, beqs) <- genEq \"Eq\" sort (sty_terms xis) (sty_terms zetas)\n                         (fun x y s => pure (nApp (nRef (upExtRenName x y)) [nHole; nHole; s]));;\n    (* type *)\n    let ret := fun s => eq_ (nApp (nRef (renName sort)) (List.app (sty_terms xis) [s]))\n                         (nApp (nRef (renName sort)) (List.app (sty_terms zetas) [s])) in\n    traversal sort extRenName no_args_default ret (List.concat [bxis; bzetas; beqs]) [xis; zetas; eqs]\n              (fun z =>\n                 toVarT <- toVar sort eqs;;\n                 pure (ap_ (nRef (varConstrName sort)) (nApp toVarT [z])))\n              sem_default\n              mapExt_.\n\n  Definition genExtRens (component: NEList.t tId) : t (list lemma) :=\n    let componentL := NEList.to_list component in\n    isRec <- isRecursive component;;\n    fexprs <- a_map genExtRen componentL;;\n    buildFixpoint fexprs isRec.\n\n  Definition genUpExt (bs: Binder * tId) : t nlemma :=\n    let '(binder, sort) := bs in\n    let '(sigma, bsigma) := genSubstS \"sigma\" sort in\n    let '(tau, btau) := genSubstS \"tau\" sort in\n    let '(x, bx) := introDBVar \"x\" in\n    let '(eq, beq) := genEqS \"Eq\" bx sigma tau in\n    (* type *)\n    let innerType := equiv_ x (nApp (nRef (upName sort binder)) [ sigma ]) (nApp (nRef (upName sort binder)) [ tau ]) in\n    let type := add_tbinders [ bsigma; btau; beq; bx ] innerType in\n    (* body *)\n    shift <- patternSId sort binder;;\n    hasRen <- hasRenaming sort;;\n    let innerBodyHelper := fun n => ap_ (nApp (nRef (if hasRen then renName sort else substName sort)) shift)\n                                     (nApp eq [n]) in\n    let innerBody := definitionBody sort binder\n                                    (matchFin_ bx innerType x innerBodyHelper eq_refl_)\n                                    (innerBodyHelper x) in\n    let body := add_binders [ bsigma; btau; beq; bx ] innerBody in\n    (* name *)\n    let name := upExtName sort binder in\n    register_name name;;\n    pure (name, type, body).\n    \n  Definition genUpExts (bss: list (Binder * tId)) : t (list lemma) :=\n    a_map (fun bs => translate_lemma (genUpExt bs)) bss.\n\n  Definition genExt (sort: tId) : t (def nterm) :=\n    '(sigmas, bsigmas) <- genSubst \"sigma\" sort;;\n    '(taus, btaus) <- genSubst \"tau\" sort;;\n    '(eqs, beqs) <- genEq \"Eq\" sort (sty_terms sigmas) (sty_terms taus)\n                         (fun x y s => pure (nApp (nRef (upExtName x y)) [nHole; nHole; s]));;\n    let ret := fun s => eq_ (nApp (nRef (substName sort)) (List.app (sty_terms sigmas) [s]))\n                         (nApp (nRef (substName sort)) (List.app (sty_terms taus) [s])) in\n    traversal sort extName no_args_default ret (List.concat [bsigmas; btaus; beqs]) [sigmas; taus; eqs]\n              (fun z =>\n                 toVarT <- toVar sort eqs;;\n                 pure (nApp toVarT [z]))\n              sem_default\n              mapExt_.\n    \n  Definition genExts (component: NEList.t tId) : t (list lemma) :=\n    let componentL := NEList.to_list component in\n    isRec <- isRecursive component;;\n    fexprs <- a_map genExt componentL;;\n    buildFixpoint fexprs isRec.\n\nEnd extensionality.\nImport extensionality.\n\nMetaCoq Run (mkLemmasTyped (genUpExtRens upList_ty) Hsig_example.mySig env13 >>= tmEval TemplateMonad.Common.all >>=\n             mkLemmasTyped (genUpExts upList_ty) Hsig_example.mySig >>= tmEval TemplateMonad.Common.all >>=\n             tmDefinition \"env14\").\n\nMetaCoq Run (mkLemmasTyped (genUpExtRens upList_tm) Hsig_example.mySig env14 >>= tmEval TemplateMonad.Common.all >>=\n             mkLemmasTyped (genUpExts upList_tm) Hsig_example.mySig >>= tmEval TemplateMonad.Common.all >>=\n             tmDefinition \"env15\").\n\nMetaCoq Run (mkLemmasTyped (genExtRens (\"ty\", [])) Hsig_example.mySig env15 >>= tmEval TemplateMonad.Common.all >>=\n             mkLemmasTyped (genExts (\"ty\", [])) Hsig_example.mySig >>= tmEval TemplateMonad.Common.all >>=\n                           tmDefinition \"env16\").\n\nMetaCoq Run (mkLemmasTyped (genExtRens (\"tm\", [\"vl\"])) Hsig_example.mySig env16 >>= tmEval TemplateMonad.Common.all >>=\n             mkLemmasTyped (genExts (\"tm\", [\"vl\"])) Hsig_example.mySig >>= tmEval TemplateMonad.Common.all >>=\n                           tmDefinition \"env17\").\n\nModule renRen.\n  Import GenM.Notations GenM.\n  \n  Definition upRenRenName := upNameGen \"up_ren_ren\".\n\n  Definition genUpRenRen (bs: Binder * tId) : t nlemma :=\n    let '(binder, sort) := bs in\n    let '(xi, bxi) := genRenS \"xi\" in\n    let '(zeta, bzeta) := genRenS \"zeta\" in\n    let '(rho, brho) := genRenS \"rho\" in\n    let '(x, bx) := introDBVar \"x\" in\n    let '(eq, beq) := genEqS \"Eq\" bx (xi >>> zeta) rho in\n    (* type *)\n    let innerType := equiv_ x ((nApp (nRef (upRenName sort binder)) [xi])\n                                 >>> (nApp (nRef (upRenName sort binder)) [zeta]))\n                            (nApp (nRef (upRenName sort binder)) [rho]) in\n    let type := add_tbinders [bxi; bzeta; brho; beq; bx] innerType in\n    (* body *)\n    (* a.d. here I have to take care to also pass x to up_ren_ren and to eq in the second case of definitionBody *)\n    let innerBody := definitionBody sort binder (nApp up_ren_ren_ [xi; zeta; rho; eq; x]) (nApp eq [x]) in\n    let body := add_binders [bxi; bzeta; brho; beq; bx] innerBody in \n    (* name *)\n    let name := upRenRenName sort binder in\n    register_name name;;\n    pure (name, type, body).\n\n  Definition genUpRenRens (bss: list (Binder * tId)) : t (list lemma) :=\n    a_map (fun bs => translate_lemma (genUpRenRen bs)) bss.\n\n  Definition compRenRenName x := sep \"compRenRen\" x.\n  Definition mapComp_ f ts := nApp (nRef (sep f \"comp\")) ts.\n\n  Definition genCompRenRen (sort: tId) : t (def nterm) :=\n    '(xis, bxis) <- genRen \"xi\" sort;;\n    '(zetas, bzetas) <- genRen \"zeta\" sort;;\n    '(rhos, brhos) <- genRen \"rho\" sort;;\n    '(eqs, beqs) <- genEq \"Eq\" sort\n                         (map2 funcomp_ (sty_terms zetas) (sty_terms xis))\n                         (sty_terms rhos)\n                         (fun x y s => match y with\n                                    | Single z => if eqb z x\n                                                        (* TODO do I need an x to pass to up_ren_ren here *)\n                                                 then pure (nApp up_ren_ren_ [nHole; nHole; nHole; s])\n                                                 else pure s\n                                    end);;\n    let ret := fun s => eq_ (nApp (nRef (renName sort)) (List.app (sty_terms zetas)\n                                                        [ nApp (nRef (renName sort)) (List.app (sty_terms xis) [s]) ]))\n                         (nApp (nRef (renName sort)) (List.app (sty_terms rhos) [s])) in\n    traversal sort compRenRenName no_args_default ret (List.concat [bxis; bzetas; brhos; beqs]) [xis; zetas; rhos; eqs]\n              (fun n =>\n                 toVarT <- toVar sort eqs;;\n                 pure (ap_ (nRef (varConstrName sort)) (nApp toVarT [n])))\n              sem_default\n              mapComp_.\n              \n  Definition genFixpoint (genF : tId -> t (def nterm)) (component: NEList.t tId) : t (list lemma) :=\n    let componentL := NEList.to_list component in\n    isRec <- isRecursive component;;\n    fexprs <- a_map genF componentL;;\n    buildFixpoint fexprs isRec.\n\n  Definition genCompRenRens := genFixpoint genCompRenRen.\nEnd renRen.\nImport renRen.\n\nMetaCoq Run (mkLemmasTyped (genUpRenRens upList_ty) Hsig_example.mySig env17 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env18\").\n\nMetaCoq Run (mkLemmasTyped (genUpRenRens upList_tm) Hsig_example.mySig env18 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env19\").\n\nMetaCoq Run (mkLemmasTyped (genCompRenRens (\"ty\", [])) Hsig_example.mySig env19 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env20\").\n\nMetaCoq Run (mkLemmasTyped (genCompRenRens (\"tm\", [\"vl\"])) Hsig_example.mySig env20 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env21\").\n\nModule renSubst.\n  Import GenM.Notations GenM.\n  \n  Definition upRenSubstName := upNameGen \"up_ren_subst\".\n  Definition compRenSubstName x := sep \"compRenSubst\" x.\n\n  Definition app_ref n ts := nApp (nRef n) ts.\n\n  Definition genUpRenSubst (bs: Binder * tId) : t nlemma :=\n    let '(binder, sort) := bs in\n    let '(xi, bxi) := genRenS \"xi\" in\n    let '(tau, btau) := genSubstS \"tau\" sort in\n    let '(theta, btheta) := genSubstS \"theta\" sort in\n    let '(x, bx) := introDBVar \"x\" in\n    let '(eq, beq) := genEqS \"Eq\" bx (xi >>> tau) theta in\n    (* type *)\n    let innerType := equiv_ x ((app_ref (upRenName sort binder) [xi])\n                                 >>> (app_ref (upName sort binder) [tau]))\n                            (app_ref (upName sort binder) [theta]) in\n    let type := add_tbinders [bxi; btau; btheta; beq; bx] innerType in\n    (* body *)\n    shift <- patternSId sort binder;;\n    let innerBodyHelper := fun n => ap_ (app_ref (renName sort) shift) (nApp eq [n]) in\n    let innerBody := definitionBody sort binder\n                                    (matchFin_ bx innerType x innerBodyHelper eq_refl_)\n                                    (innerBodyHelper x) in\n    let body := add_binders [bxi; btau; btheta; beq; bx] innerBody in\n    (* name *)\n    let name := upRenSubstName sort binder in\n    register_name name;;\n    pure (name, type, body).\n\n  Definition genUpRenSubsts (bss: list (Binder * tId)) : t (list lemma) :=\n    a_map (fun bs => translate_lemma (genUpRenSubst bs)) bss.\n  \n  Definition genCompRenSubst (sort: tId) : t (def nterm) :=\n    '(xis, bxis) <- genRen \"xi\" sort;;\n    '(taus, btaus) <- genSubst \"tau\" sort;;\n    '(thetas, bthetas) <- genSubst \"theta\" sort;;\n    '(eqs, beqs) <- genEq \"Eq\" sort\n                         (map2 funcomp_ (sty_terms taus) (sty_terms xis))\n                         (sty_terms thetas)\n                         (fun x y s => pure (app_ref (upRenSubstName x y) [nHole; nHole; nHole; s]));;\n    (* type *)\n    let ret := fun s => eq_ (app_ref (substName sort) (List.app (sty_terms taus)\n                                                             [app_ref (renName sort) (List.app (sty_terms xis) [s])]))\n                         (app_ref (substName sort) (List.app (sty_terms thetas) [s])) in\n    traversal sort compRenSubstName no_args_default ret (List.concat [bxis; btaus; bthetas; beqs]) [xis; taus; thetas; eqs]\n              (fun n =>\n                 toVarT <- toVar sort eqs;;\n                 pure (nApp toVarT [n]))\n              sem_default\n              mapComp_.\n    \n  Definition genCompRenSubsts := genFixpoint genCompRenSubst.\nEnd renSubst.\nImport renSubst.\n\nMetaCoq Run (mkLemmasTyped (genUpRenSubsts upList_ty) Hsig_example.mySig env21 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env22\").\n\n(* From ASUB Require Import core. *)\n\n(* Lemma up_ren_subst'_ty_ty (xi : nat -> nat) (tau : nat -> ty) *)\n(*   (theta : nat -> ty) (Eq : forall x, funcomp tau xi x = theta x) : *)\n(*   forall x, funcomp (up_ty_ty tau) (upRen_ty_ty xi) x = up_ty_ty theta x. *)\n(* Proof. *)\n(* exact (up_ren_subst_ty_ty xi tau theta Eq). *)\n(* Qed. *)\n\n(* MetaCoq Run (tm_update_env {| st_names := [\"up_ren_subst'_ty_ty\"] |} env22 >>= tmDefinition \"env22'\"). *)\n\n(* DONE the type of up_ren_subst_ty_ty is evaluated too much so this fails. If I define a lemma with the correct type I can use the same proof (see above) and then it works.\n * It worked when I used the hnf reduction strategy in my unquoteTyped helper function *)\nMetaCoq Run (mkLemmasTyped (genUpRenSubsts upList_tm) Hsig_example.mySig env22 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env23\").\n\nMetaCoq Run (mkLemmasTyped (genCompRenSubsts (\"ty\", [])) Hsig_example.mySig env23 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env24\").\n\nMetaCoq Run (mkLemmasTyped (genCompRenSubsts (\"tm\", [\"vl\"])) Hsig_example.mySig env24 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env25\").\n\nModule substRen.\n  Import GenM.Notations GenM.\n  \n  Definition upSubstRenName := upNameGen \"up_subst_ren\".\n  Definition compSubstRenName x := sep \"compSubstRen\" x.\n\n  Definition const {A B} (a: A) (b: B) : A := a.\n\n  Definition genUpSubstRen (bs: Binder * tId) : t nlemma :=\n    let '(binder, sort) := bs in\n    let '(sigma, bsigma) := genSubstS \"sigma\" sort in\n    '(zetas, bzetas) <- genRen \"zeta\" sort;;\n    let '(theta, btheta) := genSubstS \"theta\" sort in\n    let '(x, bx) := introDBVar \"x\" in\n    (* sigma >> <zeta> =1 theta *)\n    let '(eq, beq) := genEqS \"Eq\" bx (sigma >>> (app_ref (renName sort) (sty_terms zetas))) theta in\n    zetas' <- upSubst sort [binder] zetas;;\n    pat <- patternSId sort binder;;\n    (* type *)\n    let innerType := equiv_ x ((app_ref (upName sort binder) [sigma])\n                                 >>> (app_ref (renName sort) (sty_terms zetas')))\n                            (app_ref (upName sort binder) [theta]) in\n    let type := add_tbinders (List.concat [[bsigma]; bzetas; [btheta]; [beq]; [bx]]) innerType in\n    (* body *)\n    let compRenRenArgs := fun n => List.concat [map2 funcomp_ pat (sty_terms zetas);\n                                            List.map (const (abs_ref \"x\" eq_refl_)) pat;\n                                            [ nApp sigma [n] ]] in\n    let innerBodyHelper n :=\n        eq_trans_ (app_ref (compRenRenName sort)\n                           (List.concat [pat; sty_terms zetas'; compRenRenArgs n]))\n                  (eq_trans_ (eq_sym_ (app_ref (compRenRenName sort)\n                                               (List.concat [sty_terms zetas; pat; compRenRenArgs n])))\n                             (ap_ (app_ref (renName sort) pat)\n                                  (nApp eq [n]))) in\n    let innerBody := definitionBody sort binder\n                                    (matchFin_ bx innerType x innerBodyHelper eq_refl_)\n                                    (innerBodyHelper x) in\n    let body := add_binders (List.concat [[bsigma]; bzetas; [btheta]; [beq]; [bx]]) innerBody in\n    (* name *)\n    let name := upSubstRenName sort binder in\n    register_name name;;\n    pure (name, type, body).\n\n  Definition genUpSubstRens (bss: list (Binder * tId)) : t (list lemma) :=\n    a_map (fun bs => translate_lemma (genUpSubstRen bs)) bss.\n\n  Definition comp_ren_or_subst (sort: tId) (stys1 stys2: SubstTy) :=\n    substSorts <- substOf sort;;\n    renOrSubstName <- match stys1 with\n                   | SubstRen _ => pure renName\n                   | SubstSubst _ => pure substName\n                   | _ => error \"comp_ren_or_subst called with wrong subst_ty\"\n                   end;;\n    a_map2 (fun substSort sty2 =>\n              stys1' <- castSubst sort substSort stys1;;\n              pure (sty2 >>> app_ref (renOrSubstName substSort) (sty_terms stys1')))\n           substSorts (sty_terms stys2).                         \n  \n  Definition genCompSubstRen (sort: tId) : t (def nterm) :=\n    '(sigmas, bsigmas) <- genSubst \"sigma\" sort;;\n    '(zetas, bzetas) <- genRen \"zeta\" sort;;\n    '(thetas, bthetas) <- genSubst \"theta\" sort;;\n    sigmazeta <- comp_ren_or_subst sort zetas sigmas;;\n    '(eqs, beqs) <- genEq \"Eq\" sort sigmazeta (sty_terms thetas)\n                         (fun x y s =>\n                            zetas' <- castSubst sort x zetas;;\n                            pure (app_ref (upSubstRenName x y)\n                                          (List.concat [[nHole];\n                                                       List.map (const nHole) (sty_terms zetas');\n                                                       [nHole; s]])));;\n    (* type *)\n    let ret s := eq_ (app_ref (renName sort)\n                              (List.app (sty_terms zetas)\n                                        [app_ref (substName sort) (List.app (sty_terms sigmas) [s])]))\n                     (app_ref (substName sort) (List.app (sty_terms thetas) [s])) in\n    traversal sort compSubstRenName no_args_default ret (List.concat [bsigmas; bzetas; bthetas; beqs]) [sigmas; zetas; thetas; eqs]\n              (fun n =>\n                 toVarT <- toVar sort eqs;;\n                 pure (nApp toVarT [n]))\n              sem_default\n              mapComp_.\n\n    \n  Definition genCompSubstRens := genFixpoint genCompSubstRen.\nEnd substRen.\nImport substRen.\n\nMetaCoq Run (mkLemmasTyped (genUpSubstRens upList_ty) Hsig_example.mySig env25 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env26\").\n\nMetaCoq Run (mkLemmasTyped (genUpSubstRens upList_tm) Hsig_example.mySig env26 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env27\").\n\nMetaCoq Run (mkLemmasTyped (genCompSubstRens (\"ty\", [])) Hsig_example.mySig env27 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env28\").\n\nMetaCoq Run (mkLemmasTyped (genCompSubstRens (\"tm\", [\"vl\"])) Hsig_example.mySig env28 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env29\").\n\nModule substSubst.\n  Import GenM.Notations GenM.\n  \n  Definition upSubstSubstName := upNameGen \"up_subst_subst\".\n  Definition compSubstSubstName x := sep \"compSubstSubst\" x.\n\n  Definition genUpSubstSubst (bs: Binder * tId) : t nlemma :=\n    let '(binder, sort) := bs in\n    let '(sigma, bsigma) := genSubstS \"sigma\" sort in\n    '(taus, btaus) <- genSubst \"tau\" sort;;\n    let '(theta, btheta) := genSubstS \"theta\" sort in\n    let '(x, bx) := introDBVar \"x\" in\n    let '(eq, beq) := genEqS \"Eq\" bx\n                             (sigma >>> app_ref (substName sort) (sty_terms taus))\n                             theta in\n    taus' <- upSubst sort [binder] taus;;\n    pat <- patternSId sort binder;;\n    (* type *)\n    let innerType := equiv_ x ((app_ref (upName sort binder) [sigma])\n                                 >>> (app_ref (substName sort) (sty_terms taus')))\n                            (app_ref (upName sort binder) [theta]) in\n    let type := add_tbinders (List.concat [[bsigma]; btaus; [btheta; beq; bx]]) innerType in\n    (* body *)\n    pat' <- comp_ren_or_subst sort (SubstRen pat) taus;;\n    let compRenSubstArgs n := List.concat [ List.map (const (abs_ref \"x\" eq_refl_)) pat;\n                                          [ nApp sigma [n] ] ] in\n    let innerBodyHelper :=\n        fun n => eq_trans_ (app_ref (compRenSubstName sort) (List.concat [pat; sty_terms taus';\n                                                                      map2 funcomp_ (sty_terms taus') pat;\n                                                                      compRenSubstArgs n]))\n                        (eq_trans_ (eq_sym_ (app_ref (compSubstRenName sort)\n                                                     (List.concat [sty_terms taus; pat; pat';\n                                                                  compRenSubstArgs n])))\n                                   (ap_ (app_ref (renName sort) pat) (nApp eq [n]))) in\n    let innerBody := definitionBody sort binder\n                                    (matchFin_ bx innerType x innerBodyHelper eq_refl_)\n                                    (innerBodyHelper x) in\n    let body := add_binders (List.concat [[bsigma]; btaus; [btheta; beq; bx]]) innerBody in\n    (* name *)\n    let name := upSubstSubstName sort binder in\n    register_name name;;\n    pure (name, type, body).\n\n  Definition genUpSubstSubsts (bss: list (Binder * tId)) : t (list lemma) :=\n    a_map (fun bs => translate_lemma (genUpSubstSubst bs)) bss.\n\n  Definition genCompSubstSubst (sort: tId) : t (def nterm) :=\n    '(sigmas, bsigmas) <- genSubst \"sigma\" sort;;\n    '(taus, btaus) <- genSubst \"tau\" sort;;\n    '(thetas, bthetas) <- genSubst \"theta\" sort;;\n    sigmatau <- comp_ren_or_subst sort taus sigmas;;\n    '(eqs, beqs) <- genEq \"Eq\" sort sigmatau (sty_terms thetas)\n                         (fun x y s =>\n                            taus' <- castSubst sort x taus;;\n                            pure (app_ref (upSubstSubstName x y)\n                                          (List.concat [[nHole];\n                                                       List.map (const nHole) (sty_terms taus');\n                                                       [nHole; s]])));;\n    (* type *)\n    let ret s := eq_ (app_ref (substName sort) (List.app (sty_terms taus)\n                                                         [app_ref (substName sort) (List.app (sty_terms sigmas)\n                                                                                             [s])]))\n                     (app_ref (substName sort) (List.app (sty_terms thetas) [s])) in\n    traversal sort compSubstSubstName no_args_default ret (List.concat [bsigmas; btaus; bthetas; beqs]) [sigmas; taus; thetas; eqs]\n              (fun n =>\n                 toVarT <- toVar sort eqs;;\n                 pure (nApp toVarT [n]))\n              sem_default\n              mapComp_.\n    \n  Definition genCompSubstSubsts := genFixpoint genCompSubstSubst.\nEnd substSubst.\nImport substSubst.\n\nMetaCoq Run (mkLemmasTyped (genUpSubstSubsts upList_ty) Hsig_example.mySig env29 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env30\").\n\nMetaCoq Run (mkLemmasTyped (genUpSubstSubsts upList_tm) Hsig_example.mySig env30 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env31\").\n\nMetaCoq Run (mkLemmasTyped (genCompSubstSubsts (\"ty\", [])) Hsig_example.mySig env31 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env32\").\n\nMetaCoq Run (mkLemmasTyped (genCompSubstSubsts (\"tm\", [\"vl\"])) Hsig_example.mySig env32 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env33\").\n\nModule rinstInst.\n  Import GenM.Notations GenM.\n  \n  Definition upRinstInstName := upNameGen \"up_rinst_inst\".\n  Definition rinstInstFunName x := sep \"rinst_inst\" x.\n  Definition rinstInstName x := sep \"rinstInst\" x.\n\n  Definition genUpRinstInst (bs: Binder * tId) : t nlemma :=\n    let '(binder, sort) := bs in\n    let '(xi, bxi) := genRenS \"xi\" in\n    let '(sigma, bsigma) := genSubstS \"sigma\" sort in\n    let '(x, bx) := introDBVar \"x\" in\n    let '(eq, beq) := genEqS \"Eq\" bx (xi >>> app_ref (varConstrName sort) []) sigma in\n    (* type *)\n    let innerType := equiv_ x ((app_ref (upRenName sort binder) [xi])\n                                 >>> (app_ref (varConstrName sort) []))\n                            (app_ref (upName sort binder) [sigma]) in\n    let type := add_tbinders [bxi; bsigma; beq; bx] innerType in\n    (* body *)\n    shift <- patternSId sort binder;;\n    let innerBodyHelper n := ap_ (app_ref (renName sort) shift) (nApp eq [n]) in\n    let innerBody := definitionBody sort binder\n                                    (matchFin_ bx innerType x innerBodyHelper eq_refl_)\n                                    (innerBodyHelper x) in\n    let body := add_binders [bxi; bsigma; beq; bx] innerBody in\n    (* name *)\n    let name := upRinstInstName sort binder in\n    register_name name;;\n    pure (name, type, body).\n    \n  Definition genUpRinstInsts (bss: list (Binder * tId)) : t (list lemma) :=\n    a_map (fun bs => translate_lemma (genUpRinstInst bs)) bss.\n\n  Definition substify (sort: tId) (xis: SubstTy) :=\n    substSorts <- substOf sort;;\n    a_map2 (fun substSort xi =>\n              pure (xi >>> app_ref (varConstrName substSort) []))\n           substSorts (sty_terms xis).\n\n  Definition genRinstInst (sort: tId) : t (def nterm) :=\n    '(xis, bxis) <- genRen \"xi\" sort;;\n    '(sigmas, bsigmas) <- genSubst \"sigma\" sort;;\n    xis' <- substify sort xis;;\n    '(eqs, beqs) <- genEq \"Eq\" sort xis' (sty_terms sigmas)\n                         (fun x y s => pure (app_ref (upRinstInstName x y) [nHole; nHole; s]));;\n    let ret s := eq_ (app_ref (renName sort) (List.app (sty_terms xis) [s]))\n                     (app_ref (substName sort) (List.app (sty_terms sigmas) [s])) in\n    traversal sort rinstInstFunName no_args_default ret (List.concat [bxis; bsigmas; beqs]) [xis; sigmas; eqs]\n              (fun n =>\n                 toVarT <- toVar sort eqs;;\n                 pure (nApp toVarT [n]))\n              sem_default\n              mapComp_.\n    \n  Definition genRinstInsts := genFixpoint genRinstInst.\n\n  Definition introSortVar (name: string) (sort: tId) : nterm * (string * nterm) :=\n    (nRef name, (name, app_ref sort [])).\n\n  Definition genLemmaRinstInst (sort: tId) :=\n    '(xis, bxis) <- genRen \"xi\" sort;;\n    xis_subst <- substify sort xis;;\n    let '(x, bx) := introSortVar \"x\" sort in\n    (* type *)\n    let innerType := eq_ (app_ref (renName sort) (List.app (sty_terms xis) [x]))\n                         (app_ref (substName sort) (List.app xis_subst [x])) in\n    let type := add_tbinders (List.app bxis [bx]) innerType in\n    (* body *)\n    substSorts <- substOf sort;;\n    let innerBody := app_ref (rinstInstFunName sort)\n                             (List.concat [sty_terms xis;\n                                          List.map (const nHole) substSorts;\n                                          List.map (const (abs_ref \"x\" eq_refl_)) substSorts;\n                                          [ x ]]) in\n    let body := add_binders (List.app bxis [bx]) innerBody in\n    (* name *)\n    let name := rinstInstName sort in\n    register_name name;;\n    pure (name, type, body).\n                \n  Definition genLemmaRinstInsts (sorts: list tId) : t (list lemma) :=\n    a_map (fun sort => translate_lemma (genLemmaRinstInst sort)) sorts.\nEnd rinstInst.\nImport rinstInst.\n\nMetaCoq Run (mkLemmasTyped (genUpRinstInsts upList_ty) Hsig_example.mySig env33 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env34\").\n\nMetaCoq Run (mkLemmasTyped (genUpRinstInsts upList_tm) Hsig_example.mySig env34 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env35\").\n\nMetaCoq Run (mkLemmasTyped (genRinstInsts (\"ty\", [])) Hsig_example.mySig env35 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env36\").\n\nMetaCoq Run (mkLemmasTyped (genRinstInsts (\"tm\", [\"vl\"])) Hsig_example.mySig env36 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env37\").\n\nMetaCoq Run (mkLemmasTyped (genLemmaRinstInsts [\"ty\"]) Hsig_example.mySig env37 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env38\").\n\nMetaCoq Run (mkLemmasTyped (genLemmaRinstInsts [\"tm\"; \"vl\"]) Hsig_example.mySig env38 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env39\").\n\nModule instId.\n  Import GenM.Notations GenM.\n  \n  Definition rinstIdName x := sep \"rinstId\" x.\n  Definition instIdName x := sep \"instId\" x.\n  MetaCoq Quote Definition eq_ind_r_q := @eq_ind_r.\n  Definition eq_ind_r_ p px eqyx := nApp (nTerm eq_ind_r_q) [nHole; nHole; p; px; nHole; eqyx ].\n\n  Definition genLemmaInstId (sort: tId) : t nlemma :=\n    substSorts <- substOf sort;;\n    vars <- mk_var_apps sort;;\n    let '(s, bs) := introSortVar \"s\" sort in\n    (* type *)\n    let innerType := eq_ (app_ref (substName sort) (List.app vars [s])) s in\n    let type := add_tbinders [bs] innerType in\n    (* body *)\n    let innerBody := app_ref (idSubstName sort)\n                             (List.concat [vars;\n                                          List.map (const (abs_ref \"x\" eq_refl_)) substSorts;\n                                          [s]]) in\n    let body := add_binders [bs] innerBody in\n    (* name *)\n    let name := instIdName sort in\n    register_name name;;\n    pure (name, type, body).\n\n  Definition genLemmaInstIds (sorts: list tId) : t (list lemma) :=\n    a_map (fun sort => translate_lemma (genLemmaInstId sort)) sorts.\n\n  Definition genLemmaRinstId (sort: tId) : t nlemma :=\n    substSorts <- substOf sort;;\n    vars <- mk_var_apps sort;;\n    let ids := List.map (const id_) substSorts in\n    let '(s, bs) := introSortVar \"s\" sort in\n    (* type *)\n    let innerType := eq_ (app_ref (renName sort) (List.app ids [s])) s in\n    let type := add_tbinders [bs] innerType in\n    (* body *)\n    let innerBody := eq_ind_r_ (abs_ref \"t\" (eq_ (nRef \"t\") s))\n                               (app_ref (instIdName sort) [s])\n                               (app_ref (rinstInstName sort) (List.app ids [s])) in\n    let body := add_binders [bs] innerBody in\n    (* name *)\n    let name := rinstIdName sort in\n    register_name name;;\n    pure (name, type, body).\n                         \n  Definition genLemmaRinstIds (sorts: list tId) : t (list lemma) :=\n    a_map (fun sort => translate_lemma (genLemmaRinstId sort)) sorts.\nEnd instId.\nImport instId.\n\nMetaCoq Run (mkLemmasTyped (genLemmaInstIds [\"ty\"]) Hsig_example.mySig env39 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env40\").\n\nMetaCoq Run (mkLemmasTyped (genLemmaInstIds [\"tm\"; \"vl\"]) Hsig_example.mySig env40 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env41\").\n\nMetaCoq Run (mkLemmasTyped (genLemmaRinstIds [\"ty\"]) Hsig_example.mySig env41 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env42\").\n\nMetaCoq Run (mkLemmasTyped (genLemmaRinstIds [\"tm\"; \"vl\"]) Hsig_example.mySig env42 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env43\").\n\n\nModule varL.\n  Import GenM.Notations GenM.\n\n  Definition varLRenName x := sep \"varLRen\" x.\n  Definition varLName x := sep \"varL\" x.\n\n  Definition genVarL (sort: tId) :=\n    '(sigmas, bsigmas) <- genSubst \"sigma\" sort;;\n    sigma <- toVar sort sigmas;;\n    let '(x, bx) := introDBVar \"x\" in\n    (* type *)\n    let innerType := eq_ (app_ref (substName sort)\n                                  (List.app (sty_terms sigmas)\n                                            [ app_constr (varConstrName sort) [x] ]))\n                         (nApp sigma [x]) in\n    let type := add_tbinders (List.app bsigmas [bx]) innerType in\n    (* body *)\n    let innerBody := eq_refl_ in\n    let body := add_binders (List.app bsigmas [bx]) innerBody in\n    (* name *)\n    let name := varLName sort in\n    pure (name, type, body).\n\n  Definition genVarLs (sorts: list tId) : t (list lemma) :=\n    varSorts <- a_filter isOpen sorts;;\n    a_map (fun sort => translate_lemma (genVarL sort)) varSorts.\n\n  Definition genVarLRen (sort: tId) :=\n    '(xis, bxis) <- genRen \"subst\" sort;;\n    xi <- toVar sort xis;;\n    let '(x, bx) := introDBVar \"x\" in\n    (* type *)\n    let innerType := eq_ (app_ref (renName sort)\n                                  (List.app (sty_terms xis)\n                                            [ app_constr (varConstrName sort) [x] ]))\n                         (app_constr (varConstrName sort) [nApp xi [x] ]) in\n    let type := add_tbinders (List.app bxis [bx]) innerType in\n    (* body *)\n    let innerBody := eq_refl_ in\n    let body := add_binders (List.app bxis [bx]) innerBody in\n    (* name *)\n    let name := varLRenName sort in\n    pure (name, type, body).\n\n  Definition genVarLRens (sorts: list tId) : t (list lemma) :=\n    varSorts <- a_filter isOpen sorts;;\n    a_map (fun sort => translate_lemma (genVarLRen sort)) varSorts.\n  \nEnd varL.\nImport varL.\n\nMetaCoq Run (mkLemmasTyped (genVarLs [\"ty\"]) Hsig_example.mySig env43 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env44\").\n\nMetaCoq Run (mkLemmasTyped (genVarLs [\"tm\"; \"vl\"]) Hsig_example.mySig env44 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env45\").\n\nMetaCoq Run (mkLemmasTyped (genVarLRens [\"ty\"]) Hsig_example.mySig env45 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env46\").\n\nMetaCoq Run (mkLemmasTyped (genVarLRens [\"tm\"; \"vl\"]) Hsig_example.mySig env46 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env47\").\n\n\nModule comps.\n  Import GenM.Notations GenM.\n  Definition funcomps_ ss ts := map2 funcomp_ (sty_terms ss) (sty_terms ts).\n  Notation \"tt <<>> ss\" := (funcomps_ ss tt) (at level 70, no associativity).\n\n  Definition renRenName x := sep \"renRen\" x.\n  Definition renSubstName x := sep \"renSubst\" x.\n  Definition substRenName x := sep \"substRen\" x.\n  Definition substSubstName x := sep \"substSubst\" x.\n\n\n  Definition genLemmaCompRenRen (sort: tId) : t nlemma :=\n    '(xis, bxis) <- genRen \"xi\" sort;;\n    '(zetas, bzetas) <- genRen \"zeta\" sort;;\n    let sigmazeta := xis <<>> zetas in\n    substSorts <- substOf sort;;\n    let '(s, bs) := introSortVar \"s\" sort in\n    (* type *)\n    let innerType := eq_ (app_ref (renName sort)\n                                  (List.app (sty_terms zetas)\n                                            [ app_ref (renName sort) (List.app (sty_terms xis) [s]) ]))\n                         (app_ref (renName sort)\n                                  (List.app sigmazeta [s])) in\n    let type := add_tbinders (List.concat [bxis; bzetas; [bs]]) innerType in\n    (* body *)\n    let innerBody := app_ref (compRenRenName sort)\n                             (List.concat [ sty_terms xis;\n                                          sty_terms zetas;\n                                          List.map (const nHole) substSorts;\n                                          List.map (const (abs_ref \"x\" eq_refl_)) substSorts;\n                                          [s]]) in\n    let body := add_binders (List.concat [bxis; bzetas; [bs]]) innerBody in\n    (* name *)\n    let name := renRenName sort in\n    pure (name, type, body).\n\n  Definition genLemmaCompRenRens (sorts: list tId) : t (list lemma) :=\n    a_map (fun sort => translate_lemma (genLemmaCompRenRen sort)) sorts.\n  \n\n  Definition genLemmaCompRenSubst (sort: tId) : t nlemma :=\n    '(xis, bxis) <- genRen \"xi\" sort;;\n    '(taus, btaus) <- genSubst \"tau\" sort;;\n    substSorts <- substOf sort;;\n    let '(s, bs) := introSortVar \"s\" sort in\n    (* type *)\n    let xitaus := xis <<>> taus in\n    let innerType := eq_ (app_ref (substName sort)\n                                  (List.app (sty_terms taus)\n                                            [ app_ref (renName sort)\n                                                      (List.app (sty_terms xis) [s]) ]))\n                         (app_ref (substName sort)\n                                  (List.app xitaus [s])) in\n    let type := add_tbinders (List.concat [bxis; btaus; [bs]]) innerType in\n    (* body *)\n    let innerBody := app_ref (compRenSubstName sort)\n                             (List.concat [ sty_terms xis;\n                                          sty_terms taus;\n                                          List.map (const nHole) substSorts;\n                                          List.map (const (abs_ref \"n\" eq_refl_)) substSorts;\n                                          [s] ]) in\n    let body := add_binders (List.concat [bxis; btaus; [bs]]) innerBody in\n    (* name *)\n    let name := renSubstName sort in\n    pure (name, type, body).\n\n  Definition genLemmaCompRenSubsts (sorts: list tId) : t (list lemma) :=\n    a_map (fun sort => translate_lemma (genLemmaCompRenSubst  sort)) sorts.\n\n\n  Definition genLemmaCompSubstRen (sort: tId) : t nlemma :=\n    '(sigmas, bsigmas) <- genSubst \"sigma\" sort;;\n    '(zetas, bzetas) <- genRen \"zeta\" sort;;\n    substSorts <- substOf sort;;\n    let '(s, bs) := introSortVar \"s\" sort in\n    (* type *)\n    sigmazetas <- comp_ren_or_subst sort zetas sigmas;;\n    let innerType := eq_ (app_ref (renName sort)\n                                  (List.app (sty_terms zetas)\n                                            [ app_ref (substName sort)\n                                                      (List.app (sty_terms sigmas) [s]) ]))\n                         (app_ref (substName sort) (List.app sigmazetas [s])) in\n    let type := add_tbinders (List.concat [bsigmas; bzetas; [bs]]) innerType in\n    (* body *)\n    let innerBody := app_ref (compSubstRenName sort)\n                             (List.concat [ sty_terms sigmas;\n                                          sty_terms zetas;\n                                          List.map (const nHole) substSorts;\n                                          List.map (const (abs_ref \"n\" eq_refl_)) substSorts;\n                                          [s] ]) in\n    let body := add_binders (List.concat [bsigmas; bzetas; [bs]]) innerBody in\n    (* name *)\n    let name := substRenName sort in\n    pure (name, type, body).\n\n  Definition genLemmaCompSubstRens (sorts: list tId) : t (list lemma) :=\n    a_map (fun sort => translate_lemma (genLemmaCompSubstRen  sort)) sorts.\n\n\n  Definition genLemmaCompSubstSubst (sort: tId) : t nlemma :=\n    '(sigmas, bsigmas) <- genSubst \"sigma\" sort;;\n    '(taus, btaus) <- genSubst \"tau\" sort;;\n    substSorts <- substOf sort;;\n    let '(s, bs) := introSortVar \"s\" sort in\n    (* type *)\n    sigmataus <- comp_ren_or_subst sort taus sigmas;;\n    let innerType := eq_ (app_ref (substName sort)\n                                  (List.app (sty_terms taus)\n                                            [ app_ref (substName sort)\n                                                      (List.app (sty_terms sigmas) [s]) ]))\n                         (app_ref (substName sort) (List.app sigmataus [s])) in\n    let type := add_tbinders (List.concat [bsigmas; btaus; [bs]]) innerType in\n    (* body *)\n    let innerBody := app_ref (compSubstSubstName sort)\n                             (List.concat [sty_terms sigmas;\n                                          sty_terms taus;\n                                          List.map (const nHole) substSorts;\n                                          List.map (const (abs_ref \"n\" eq_refl_)) substSorts;\n                                          [s] ]) in\n    let body := add_binders (List.concat [bsigmas; btaus; [bs]]) innerBody in\n    (* name *)\n    let name := substSubstName sort in\n    pure (name, type, body).\n\n  \n  Definition genLemmaCompSubstSubsts (sorts: list tId) : t (list lemma) :=\n    a_map (fun sort => translate_lemma (genLemmaCompSubstSubst  sort)) sorts.\n\nEnd comps.\nImport comps.\n\nMetaCoq Run (mkLemmasTyped (genLemmaCompRenRens [\"ty\"]) Hsig_example.mySig env47 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env48\").\n\nMetaCoq Run (mkLemmasTyped (genLemmaCompRenRens [\"tm\"; \"vl\"]) Hsig_example.mySig env48 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env49\").\n\nMetaCoq Run (mkLemmasTyped (genLemmaCompRenSubsts [\"ty\"]) Hsig_example.mySig env49 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env50\").\n\nMetaCoq Run (mkLemmasTyped (genLemmaCompRenSubsts [\"tm\"; \"vl\"]) Hsig_example.mySig env50 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env51\").\n\nMetaCoq Run (mkLemmasTyped (genLemmaCompSubstRens [\"ty\"]) Hsig_example.mySig env51 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env52\").\n\nMetaCoq Run (mkLemmasTyped (genLemmaCompSubstRens [\"tm\"; \"vl\"]) Hsig_example.mySig env52 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env53\").\n\nMetaCoq Run (mkLemmasTyped (genLemmaCompSubstSubsts [\"ty\"]) Hsig_example.mySig env53 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env54\").\n\nMetaCoq Run (mkLemmasTyped (genLemmaCompSubstSubsts [\"tm\"; \"vl\"]) Hsig_example.mySig env54 >>= tmEval TemplateMonad.Common.all >>= tmDefinition \"env55\").\n\n(* MetaCoq Run (match GenM.run (genUpExts upList_ty) (Hsig_example.mySig, env13) empty_state with *)\n(*              | inr (_, _, x) => *)\n(*                tmEval TemplateMonad.Common.all x >>= tmPrint *)\n(*              | _ => tmFail \"fail\" *)\n(*              end). *)\n\n(* TODO better document the way to debug this.\n * you can set everything opaque except the thing you want to see the AST of *)\n(*\nModule foo.\n  From ASUB Require Import unscoped.\n  Opaque ren_ty.\n  Opaque ap.\n  Opaque shift.\n  Opaque up_ty_ty.\n  \n Lemma upId_ty_ty (sigma : nat -> ty) (Eq : forall x, sigma x = var_ty x) :\n  forall n, up_ty_ty sigma n = var_ty n.\nProof.\nexact (fun n =>\n       match n with\n       | S n' => ap (ren_ty shift) (Eq n')\n       | O => eq_refl\n       end).\nQed.\n\nMetaCoq Quote Definition foo_source := Eval compute in upId_ty_ty.\nEnd foo.\n *)\n\nDefinition generate (env: SFMap.t term) (component: NEList.t tId) (upList: list (Binder * tId)) : TemplateMonad (SFMap.t term) :=\n  let s := Hsig_example.mySig in\n  let componentL := NEList.to_list component in\n  (** * Inductive Types *)\n  (* generate the inductive types *)\n  env <- mkInductive s componentL env;;\n  (** * Congruence Lemmas *)\n  (* if we generate multiple lemmas we need to keep updating the environment in a fold *)\n  env <- tm_foldM (fun env sort => mkLemmasTyped (genCongruences sort) s env) componentL env;;\n  (* TODO check if component has binders\n   * should probably use a nonempty list for the component then *)\n  (** * Renamings *)\n  env <- mkLemmasTyped (genUpRens upList) s env;;\n  env <- mkLemmasTyped (genRenamings component) s env;;\n  (** * Substitutions *)\n  env <- mkLemmasTyped (genUps upList) s env;;\n  env <- mkLemmasTyped (genSubstitutions component) s env;;\n  (** * idSubst *)\n  env <- mkLemmasTyped (genUpIds upList) s env;;\n  env <- mkLemmasTyped (genIdLemmas component) s env;;\n  (** * Extensionality *)\n  env <- mkLemmasTyped (genUpExtRens upList) s env;;\n  env <- mkLemmasTyped (genExtRens component) s env;;\n  env <- mkLemmasTyped (genUpExts upList) s env;;\n  env <- mkLemmasTyped (genExts component) s env;;\n  (** * Combinations *)\n  env <- mkLemmasTyped (genUpRenRens upList) s env;;\n  env <- mkLemmasTyped (genCompRenRens component) s env;;\n  env <- mkLemmasTyped (genUpRenSubsts upList) s env;;\n  env <- mkLemmasTyped (genCompRenSubsts component) s env;;\n  env <- mkLemmasTyped (genUpSubstRens upList) s env;;\n  env <- mkLemmasTyped (genCompSubstRens component) s env;;\n  env <- mkLemmasTyped (genUpSubstSubsts upList) s env;;\n  env <- mkLemmasTyped (genCompSubstSubsts component) s env;;\n  (** * rinstInst *)\n  env <- mkLemmasTyped (genUpRinstInsts upList) s env;;\n  env <- mkLemmasTyped (genRinstInsts component) s env;;\n  env <- mkLemmasTyped (genLemmaRinstInsts componentL) s env;;\n  (** * rinstId/instId *)\n  env <- mkLemmasTyped (genLemmaInstIds componentL) s env;;\n  env <- mkLemmasTyped (genLemmaRinstIds componentL) s env;;\n  (** * varL *)\n  env <- mkLemmasTyped (genVarLs componentL) s env;;\n  env <- mkLemmasTyped (genVarLRens componentL) s env;;\n  (** * Combinations *)\n  env <- mkLemmasTyped (genLemmaCompRenRens componentL) s env;;\n  env <- mkLemmasTyped (genLemmaCompRenSubsts componentL) s env;;\n  env <- mkLemmasTyped (genLemmaCompSubstRens componentL) s env;;\n  env <- mkLemmasTyped (genLemmaCompSubstSubsts componentL) s env;;\n  tmReturn env.\n\nCompute upList_tm.\n\nFrom ASUB Require unscoped core.\nRequire Import Setoid Morphisms.\n\nModule generation.\n  (* Compute (GenM.run (genUpRens upList_ty) Hsig_example.mySig empty_state). *)\n  Time MetaCoq Run (generate initial_env (\"ty\",[]) upList_ty >>= tmEval TemplateMonad.Common.all >>=\n                             fun env => generate env (\"tm\", [\"vl\"]) upList_tm >>= tmEval TemplateMonad.Common.all >>=\n                                              tmDefinition \"env1\").\n\n  Import unscoped core UnscopedNotations.\n  (* TODO the morphisms must still be generated *)\n  Instance subst_ty_morphism :\n    (Proper (respectful (pointwise_relation _ eq) (respectful eq eq))\n            (@subst_ty)).\n  Proof.\n    exact (fun f_ty g_ty Eq_ty s t Eq_st =>\n             eq_ind s (fun t' => subst_ty f_ty s = subst_ty g_ty t')\n                    (ext_ty f_ty g_ty Eq_ty s) t Eq_st).\n  Qed.\n\n  Instance ren_ty_morphism :\n    (Proper (respectful (pointwise_relation _ eq) (respectful eq eq)) (@ren_ty)).\n  Proof.\n    exact (fun f_ty g_ty Eq_ty s t Eq_st =>\n             eq_ind s (fun t' => ren_ty f_ty s = ren_ty g_ty t')\n                    (extRen_ty f_ty g_ty Eq_ty s) t Eq_st).\n  Qed.\n\n\n  (* DONE prove the default lemma. If this works we're on the right track *)\n  Goal forall (f: nat -> ty) (s t: ty),\n      subst_ty f (subst_ty (scons t var_ty) s) = subst_ty (scons (subst_ty f t) var_ty) (subst_ty (up_ty_ty f) s).\n  Proof.\n    intros *.\n    rewrite ?substSubst_ty.\n    unfold up_ty_ty, funcomp.\n    fsimpl.\n    setoid_rewrite varL_ty.\n    setoid_rewrite renSubst_ty.\n    setoid_rewrite instId_ty.\n    fsimpl. minimize.\n    reflexivity.\n  Qed. \nEnd generation.\n\n\n", "meta": {"author": "addap", "repo": "autosubst-metacoq", "sha": "f597778fd0c4fa17d9cd63fed101c59a15ad0949", "save_path": "github-repos/coq/addap-autosubst-metacoq", "path": "github-repos/coq/addap-autosubst-metacoq/autosubst-metacoq-f597778fd0c4fa17d9cd63fed101c59a15ad0949/src/CodeGenerator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.22978018499994887}}
{"text": "Require Export WellFormedness.\nRequire Import SyntaxProp.\nRequire Import TypesProp.\nRequire Import Shared.\n\n(*\n========================\nField and method lookup\n========================\n*)\n\n\nLemma wfProgram_wfMethodDecl :\n  forall P t' c ms m mtd,\n    wfProgram P t' ->\n    methods P (TClass c) = Some ms ->\n    methodLookup ms m = Some mtd ->\n    wfMethodDecl P c mtd.\nProof with auto.\n  introv wfP Hmethods mLookup.\n  inv wfP.\n  unfold methods in Hmethods.\n  remember (classLookup (cds, ids, e) c) as cLookup.\n  symmetry in HeqcLookup.\n  destruct cLookup as [[c' i fs ms'] |]...\n  inv_eq.\n  assert (Heq : c = c') by\n      (unfold classLookup in HeqcLookup;\n       apply find_true in HeqcLookup;\n       apply beq_nat_eq; auto).\n  subst.\n  lookup_forall as wfCls.\n  inv wfCls.\n  lookup_forall mtd as wfMtd...\nQed.\n\n\nCorollary dyn_wfFieldLookup :\n  forall P Gamma c F fs f t,\n    wfFields P Gamma c F ->\n    fields P (TClass c) = Some fs ->\n    fieldLookup fs f = Some (Field f t) ->\n    exists v, F f = Some v /\\ P; Gamma |- (EVal v) \\in t.\nProof with eauto.\n  introv wfF Hfields fLookup.\n  inv wfF. rewrite_and_invert...\nQed.\n\nHint Immediate dyn_wfFieldLookup.\n\n(*\n------------\nMethod sigs\n------------\n*)\n\nHint Constructors methodSigs.\n\nLemma extractSigs_sound :\n  forall mtds m x t t',\n    (exists e, methodLookup mtds m = Some (Method m (x, t) t' e)) <->\n    methodSigLookup (extractSigs mtds) m = Some (MethodSig m (x, t) t').\nProof with eauto.\n  intros. split.\n  + gen t t' m x.\n    induction mtds as [|[m [x t] t' e]]; simpl;\n    introv H; inv H as [e' Hsigs]...\n    cases_if... inv_eq.\n  + gen t t' m x.\n    induction mtds as [|[m [x t] t' e]]; simpl;\n    introv mLookup; inv mLookup...\n    cases_if; crush...\nQed.\n\nLemma methodSigs_deterministic :\n  forall P t msigs1 msigs2,\n    methodSigs P t msigs1 ->\n    methodSigs P t msigs2 ->\n    msigs1 = msigs2.\nProof with eauto.\n  introv Hsigs1 Hsigs2.\n  gen msigs2.\n  induction Hsigs1; introv Hsigs2;\n  inv Hsigs2; try(rewrite_and_invert)...\n  rewrite IHHsigs1_1 with msigs3...\n  rewrite IHHsigs1_2 with msigs4...\nQed.\n\nLemma methodSigs_wfType_exists :\n  forall P t' t,\n    wfProgram P t' ->\n    (wfType P t <->\n     exists msigs, methodSigs P t msigs).\nProof with eauto.\n  introv [? ? ? wfCds wfIds wfExpr].\n  split.\n  + intros wfT.\n    inv wfT as [c cLookup|i iLookup|]...\n    - apply classLookup_not_none in cLookup as [i [fs [ms]]]...\n    - apply interfaceLookup_not_none in iLookup.\n      inv iLookup as [[msigs]|[i1 [i2]]]...\n      * intros. lookup_forall as wfId. inv wfId...\n  + intros Hex. destruct Hex as [msigs Hsigs].\n    destruct t; inv Hsigs; constructor; crush.\nQed.\n\nLemma methodSigs_sub :\n  forall P t t1 t2 m msigs1 msigs2 msig,\n    wfProgram P t ->\n    subtypeOf P t1 t2 ->\n    methodSigs P t1 msigs1 ->\n    methodSigs P t2 msigs2 ->\n    methodSigLookup msigs2 m = Some msig ->\n    methodSigLookup msigs1 m = Some msig.\nProof with eauto using\n                 methodSigs_deterministic,\n                 methodSigs_wfType_exists,\n                 subtypeOf_wfTypeSub,\n                 subtypeOf_wfTypeSup.\n  introv [? ? ? ? wfCds wfIds wfExpr] Hsub\n         Hsigs1 Hsigs2 Hsig.\n  gen msigs1 msigs2 msig.\n  subtypeOf_cases(induction Hsub) Case; intros.\n  + Case \"Sub_Class\".\n    lookup_forall as wfCd. inv wfCd.\n    assert (msigs2 = (extractSigs ms))...\n    subst. inv Hsigs1; rewrite_and_invert.\n  + Case \"Sub_InterfaceLeft\".\n    inv Hsigs1; rewrite_and_invert.\n    assert (msigs0 = msigs2)...\n    subst. apply find_app...\n  + inv Hsigs1; rewrite_and_invert.\n    assert (msigs2 = msigs3)...\n    subst. apply find_app2...\n    lookup_forall as wfId.\n    inverts wfId as Hsigs3 Hsigs4 sigsDisjoint1 sigsDisjoint2.\n    assert (msigs0 = msigs1)...\n    assert (msigs2 = msigs3)...\n    subst. fold (methodSigLookup msigs1 m).\n    eapply sigsDisjoint2...\n  + asserts_rewrite (msigs1 = msigs2)...\n  + rename msigs2 into msigs3.\n    rename Hsigs2 into Hsigs3.\n    assert (wfT1: wfType (cds, ids, e) t1)...\n    assert (wfT2: wfType (cds, ids, e) t2)...\n    eapply methodSigs_wfType_exists in wfT2 as []...\n(*  + inv Hsigs2. inv Hsig.*)\nQed.\n\n(*\n==============\nConfiguration\n==============\n*)\n\n(*\n---------\nwfFields\n---------\n*)\n\nLemma wfFields_declsToFields :\n  forall P t' c i fs ms Gamma,\n    wfProgram P t' ->\n    wfEnv P Gamma ->\n    classLookup P c = Some (Cls c i fs ms) ->\n    wfFields P Gamma c (declsToFields fs).\nProof with eauto using\n                 fields_wfFieldDecl,\n                 declsToFields_null.\n  introv wfProgram wfEnv Hlookup.\n  assert (fields P (TClass c) = Some fs)\n    by (unfolds; rewrite Hlookup; auto).\n  assert (Forall (wfFieldDecl P) fs)...\n  econstructor...\n  intros.\n  lookup_forall as wfF. inv wfF...\nQed.\n\nLemma wfFields_extend :\n  forall P Gamma c fs f t F v,\n    fields P (TClass c) = Some fs ->\n    fieldLookup fs f = Some (Field f t) ->\n    wfFields P Gamma c F ->\n    P; Gamma |- EVal v \\in t ->\n    wfFields P Gamma c (extend F f v).\nProof with eauto with env.\n  introv Hfields fLookup wfF hasType.\n  econstructor...\n  introv fLookup'.\n  inv wfF.\n  case_extend; repeat rewrite_and_invert...\nQed.\n\nLemma wfFields_envExtend :\n  forall P t' Gamma c F l c',\n    wfProgram P t' ->\n    wfFields P Gamma c F ->\n    wfEnv P Gamma ->\n    fresh Gamma (env_loc l) ->\n    wfType P (TClass c') ->\n    wfFields P (extend Gamma (env_loc l) (TClass c')) c F.\nProof with eauto using hasType_extend_loc.\n  introv wfP wfF wfGamma Hfresh wfT.\n  inverts wfF as Hfields wfFlds.\n  econstructor...\n  introv Hlookup.\n  apply wfFlds in Hlookup as (v & Heq & hasType)...\nQed.\n\nLemma wfFields_invariance :\n  forall P t' c Gamma Gamma' F,\n    wfProgram P t' ->\n    (forall l, Gamma (env_loc l) = Gamma' (env_loc l)) ->\n    wfEnv P Gamma' ->\n    wfFields P Gamma c F ->\n    wfFields P Gamma' c F.\nProof with eauto using hasType_wfType.\n  introv wfP envSub wfGamma' wfF.\n  inverts wfF as Hfields wfFld.\n  econstructor...\n  introv fLookup.\n  apply wfFld in fLookup as (v & Ff & hasType).\n  exists v. split...\n  destruct v...\n  + inv hasType.\n    econstructor...\n    rewrite <- envSub...\nQed.\n\nLemma wfHeap_wfObject :\n  forall P Gamma H l c F L,\n    wfHeap P Gamma H ->\n    heapLookup H l = Some (c, F, L) ->\n    wfFields P Gamma c F.\nProof with eauto.\n  introv wfH Hlookup.\n  inverts wfH as _ envModelsHeap heapMirrorsEnv.\n  assert (Hl: heapLookup H l <> None) by crush.\n  apply heapMirrorsEnv in Hl.\n  destruct Hl as [c' envLookup].\n  apply envModelsHeap in envLookup as (F' & L' & ? & ?).\n  rewrite_and_invert.\nQed.\n\nLemma wfHeap_wfFields :\n  forall P Gamma H l c F RL,\n    wfHeap P Gamma H ->\n    heapLookup H l = Some (c, F, RL) ->\n    wfFields P Gamma c F.\nProof with eauto.\n  introv wfH Hlookup.\n  eapply wfHeap_wfObject in Hlookup as []...\n  constructors...\nQed.\n\n(*\n-------\nwfHeap\n-------\n*)\n\nHint Constructors wfHeap.\n\nLemma wfHeap_fresh :\n  forall P Gamma H l,\n    wfHeap P Gamma H ->\n    heapLookup H l = None ->\n    fresh Gamma (env_loc l).\nProof with eauto.\n  introv wfH Hlookup.\n  inverts wfH as wfGamma envModelsHeap heapMirrorsEnv.\n  unfold fresh. remember (Gamma (env_loc l)) as t...\n  destruct t...\n  symmetry in Heqt.\n  assert (tClass: exists c, t = TClass c) by (inv wfGamma; eauto).\n  inv tClass as [c''].\n  apply envModelsHeap in Heqt.\n  inv Heqt as [F' [RL [contra]]]. rewrite_and_invert.\nQed.\n\nLemma wfHeap_extend :\n  forall P t' Gamma H c F L,\n    wfProgram P t' ->\n    wfHeap P Gamma H ->\n    wfType P (TClass c) ->\n    wfFields P Gamma c F ->\n    wfHeap P (extend Gamma (env_loc (length H)) (TClass c)) (heapExtend H (c, F, L)).\nProof with eauto with env.\n  introv wfP wfH wfT wfF.\n  inverts wfH as wfGamma envModelsHeap heapMirrorsEnv.\n  constructor...\n  + introv envLookup.\n    destruct (id_eq_dec l (length H)).\n    - subst. simpl_extend_hyp. inv_eq.\n      rewrite heapExtend_lookup_len.\n      eexists; eexists; split...\n      eapply wfFields_envExtend...\n      eapply wfHeap_fresh...\n      apply heapLookup_ge...\n    - rewrite extend_neq in envLookup...\n      rewrite heapExtend_lookup_nlen...\n      apply envModelsHeap in envLookup as (F' & RL' & Hlookup & wfF')...\n      eexists; eexists; split...\n      eapply wfFields_envExtend...\n      eapply wfHeap_fresh...\n      apply heapLookup_ge...\n  + introv Hlookup.\n    destruct (id_eq_dec l (length H))...\n    rewrite heapExtend_lookup_nlen in Hlookup...\nQed.\n\nLemma wfHeap_update :\n  forall P Gamma H l c F RL RL' F',\n    wfHeap P Gamma H ->\n    heapLookup H l = Some (c, F, RL) ->\n    wfFields P Gamma c F' ->\n    wfHeap P Gamma (heapUpdate H l (c, F', RL')).\nProof with eauto.\n  introv wfH Hlookup wfF'.\n  inverts wfH as wfGamma envModelsHeap heapMirrorsEnv.\n  constructor...\n  + introv envLookup.\n    destruct (id_eq_dec l l0).\n    - subst.\n      rewrite lookup_heapUpdate_eq\n        by (apply heapLookup_lt; eauto).\n      apply envModelsHeap in envLookup as (F'' & RL'' & Hlookup' & wfF'').\n      rewrite_and_invert...\n    - rewrite lookup_heapUpdate_neq...\n  + introv Hlookup'.\n    apply heapMirrorsEnv.\n    destruct (id_eq_dec l l0).\n    - subst.\n      rewrite heapLookup_not_none...\n    - rewrite lookup_heapUpdate_neq in Hlookup'...\nQed.\n\nLemma wfHeap_invariance :\n  forall P t' Gamma Gamma' H,\n    wfProgram P t' ->\n    (forall l, Gamma (env_loc l) = Gamma' (env_loc l)) ->\n    wfEnv P Gamma' ->\n    wfHeap P Gamma H ->\n    wfHeap P Gamma' H.\nProof with eauto using wfFields_invariance.\n  introv wfP envEquiv wfGamma' wfH.\n  inverts wfH as wfGamma envModelsHeap heapMirrorsEnv.\n  constructor...\n  + introv envLookup. rewrite <- envEquiv in envLookup.\n    apply envModelsHeap in envLookup.\n    inv envLookup as (F & RL & Hlookup & wfF)...\n  + introv Hlookup. rewrite <- envEquiv...\nQed.\n\n(*\n--------\nwfVars\n--------\n*)\n\nHint Constructors wfVars.\n\nLemma wfVars_invariance :\n  forall P t' Gamma Gamma' fsyms V,\n    wfProgram P t' ->\n    (forall x, Gamma x = Gamma' x) ->\n    wfEnv P Gamma' ->\n    wfVars P Gamma fsyms V ->\n    wfVars P Gamma' fsyms V.\nProof with eauto.\n  introv wfP envEquiv wfGamma' wfV.\n  inverts wfV as wfGamma envModelsVars varsMirrorEnv Hfresh.\n  constructor...\n  + introv Vlookup.\n    rewrite <- envEquiv in Vlookup.\n    apply envModelsVars in Vlookup as (v & Vlookup & hasType).\n    eapply hasType_subsumption with (Gamma' := Gamma') in hasType; crush...\n  + introv. rewrite <- envEquiv...\nQed.\n\nLemma wfVars_extend :\n  forall P t' Gamma n m V v t,\n    wfProgram P t' ->\n    wfVars P Gamma n V ->\n    P; Gamma |- EVal v \\in t ->\n    m < n ->\n    wfVars P (extend Gamma (env_var (DV (DVar m))) t)\n           n (extend V (DVar m) v).\nProof with eauto with env.\n  introv wfP wfV hasType Hlt.\n  inverts wfV as wfGamma envModelsVars varsMirrorEnv Hfresh.\n  constructor; eauto 3 with env.\n  + introv envLookup.\n    destruct (id_eq_dec (DVar m) x).\n    - subst. simpl_extend_hyp.\n      inv_eq.\n      exists v.\n      split...\n      inv hasType...\n    - rewrite extend_neq in envLookup...\n      apply envModelsVars in envLookup as (v' & Vlookup & hasType').\n      exists v'.\n      split...\n      inv hasType'...\n  + introv Hle. unfold fresh.\n    assert (m < n')\n        by omega.\n    case_extend; [inv_eq | apply Hfresh]; omega.\nQed.\n\nLemma wfVars_heapExtend :\n  forall Gamma P t' n V l c,\n    wfProgram P t' ->\n    wfVars P Gamma n V ->\n    fresh Gamma (env_loc l) ->\n    wfType P (TClass c) ->\n    wfVars P (extend Gamma (env_loc l) (TClass c)) n V.\nProof with eauto with env.\n  introv wfP wfV Hfresh wfT.\n  inverts wfV as wfGamma envModelsVars varsMirrorEnv freshVars.\n  constructor...\n  + introv envLookup.\n    simpl_extend_hyp.\n    apply envModelsVars in envLookup as (v & Vlookup & hasType).\n    exists v.\n    split...\n    inv hasType...\nQed.\n\nLemma wfVars_ge :\n  forall P Gamma n V m,\n    wfVars P Gamma n V ->\n    n <= m ->\n    wfVars P Gamma m V.\nProof with eauto.\n  introv wfV Hge.\n  inverts wfV as wfGamma envModels varsMirror Hfresh.\n  econstructor...\n  introv Hle.\n  assert (n <= n') by omega...\nQed.\n\n(*\n----------\nwfLocking\n----------\n*)\n\nHint Constructors wfHeldLocks.\nHint Constructors wfLocks.\nHint Constructors disjointLocks.\nHint Constructors wfLocking.\n\nLemma wfHeldLocks_heapExtend :\n  forall H Ls c F RL,\n    wfHeldLocks H Ls ->\n    wfHeldLocks (heapExtend H (c, F, RL)) Ls.\nProof with eauto.\n  introv wfLs.\n  constructor.\n  induction wfLs as [wfLs]...\n  rewrite Forall_forall in wfLs.\n  apply Forall_forall.\n  introv HIn.\n  apply wfLs in HIn as [].\n  assert (Hlt: l < length H) by\n      (eapply heapLookup_lt; eauto)...\n  econstructor...\n  rewrite heapExtend_lookup_nlen...\n  omega.\nQed.\n\nLemma wfLocking_heapExtend :\n  forall H T c F RL,\n    wfLocking H T ->\n    wfLocking (heapExtend H (c, F, RL)) T.\nProof with eauto using wfHeldLocks_heapExtend.\n  introv wfL.\n  induction wfL...\nQed.\n\nLemma wfHeldLocks_heapUpdate :\n  forall H Ls l c F F' L L',\n    wfHeldLocks H Ls ->\n    heapLookup H l = Some (c, F, L) ->\n    (In l Ls -> L' = LLocked) ->\n    wfHeldLocks (heapUpdate H l (c, F', L')) Ls.\nProof with eauto.\n  introv wfLs Hlookup HRL'.\n  induction wfLs as [wfLs]...\n  rewrite Forall_forall in wfLs.\n  constructors.\n  apply Forall_forall.\n  introv HIn.\n  assert(wfL: wfLock H x)...\n  inverts wfL as Hlookup' HRL.\n  destruct (id_eq_dec l x).\n  + subst. rewrite_and_invert.\n    apply HRL' in HIn. subst.\n    apply WF_Lock with c0 F'...\n    rewrite lookup_heapUpdate_eq...\n    apply heapLookup_lt...\n  + econstructor...\n    rewrite lookup_heapUpdate_neq...\nQed.\n\nLemma wfLocking_heapUpdate :\n  forall H T l c F F' L L',\n    wfLocking H T ->\n    heapLookup H l = Some (c, F, L) ->\n    (In l (heldLocks T) -> L' = LLocked) ->\n    wfLocking (heapUpdate H l (c, F', L')) T.\nProof with eauto using wfHeldLocks_heapUpdate.\n  introv wfL Hlookup HL.\n  induction wfL; simpls...\n  crush.\nQed.\n\nLemma wfHeldLocks_taken :\n  forall H Ls l c L F,\n    wfHeldLocks H Ls ->\n    In l Ls ->\n    heapLookup H l = Some (c, F, L) ->\n    L = LLocked.\nProof with eauto.\n  introv wfLs HIn Hlookup.\n  induction wfLs as [wfLs]...\n  rewrite Forall_forall in wfLs.\n  apply wfLs in HIn. inv HIn.\n  rewrite_and_invert...\nQed.\n\nLemma wfLocks_econtext :\n  forall Ls e ctx,\n    is_econtext ctx ->\n    wfLocks Ls (ctx e) ->\n    wfLocks Ls e.\nProof with eauto using in_or_app.\n  introv Hctx wfL.\n  inv Hctx;\n    inverts wfL as Hlocks Hdup;\n    simpl in *...\n  + eapply NoDup_app in Hdup as []...\n  + inv Hdup...\nQed.\n\nLemma wfLocking_econtext :\n  forall ctx H Ls e,\n    is_econtext ctx ->\n    wfLocking H (T_Thread Ls (ctx e)) ->\n    wfLocking H (T_Thread Ls e).\nProof with eauto using wfLocks_econtext.\n  introv Hctx wfL.\n  inv wfL...\nQed.\n\nLemma wfLocking_subst :\n  forall H Ls e x y,\n    wfLocking H (T_Thread Ls e) ->\n    wfLocking H (T_Thread Ls (subst x y e)).\nProof with eauto.\n  introv wfL.\n  inverts wfL as wfLs Hdup wfL wfRl.\n  econstructor...\n  econstructor...\n  + rewrite <- locks_subst...\n    inv wfL...\n  + rewrite <- locks_subst...\n    inv wfL...\nQed.\n\nLemma locks_static :\n  forall e,\n    exprStatic e ->\n    locks e = nil.\nProof with eauto using app_eq_nil.\n  introv Hstatic.\n  induction Hstatic; simpl...\n  apply app_eq_nil...\nQed.\n\nLemma wfLocking_static :\n  forall H Ls e,\n    wfHeldLocks H Ls ->\n    NoDup Ls ->\n    exprStatic e ->\n    wfLocking H (T_Thread Ls e).\nProof with eauto using locks_static.\n  introv wfLs Hdup Hstatic.\n  assert (HL: locks e = nil)...\n  econstructor...\n  econstructor; rewrite HL...\n  introv HIn... inv HIn.\nQed.\n\nLemma disjointLocks_commutative :\n  forall T1 T2,\n    disjointLocks T1 T2 ->\n    disjointLocks T2 T1.\nProof with eauto.\n  introv Hdisj.\n  inv Hdisj. constructors...\nQed.\n\nLemma disjointLocks_async :\n  forall T T1 T2 e,\n    disjointLocks T1 T /\\\n    disjointLocks T2 T\n     <->\n    disjointLocks (T_Async T1 T2 e) T.\nProof with eauto using in_or_app.\n  split.\n  + introv Hdisj.\n    inverts Hdisj as Hdisj1 Hdisj2.\n    inverts Hdisj1. inverts Hdisj2.\n    constructor; simpl.\n    - introv HIn.\n      apply in_app_or in HIn as [|HIn]...\n    - introv HIn.\n      apply not_in_app...\n  + introv Hdisj.\n    inverts Hdisj as Hdisj1 Hdisj2.\n    simpls.\n    splits.\n    - constructor...\n      introv HIn.\n      apply Hdisj2 in HIn...\n    - constructor...\n      introv HIn.\n      apply Hdisj2 in HIn.\n      eapply not_in_app in HIn as []...\nQed.\n\nLemma disjointLocks_leftmost :\n  forall T1 T2,\n    disjointLocks T1 T2 ->\n    disjointLocks (T_EXN (leftmost_locks T1)) T2.\nProof with eauto using in_or_app.\n  introv Hdisj.\n  induction T1; simpls; inv Hdisj...\n  apply IHT1_1.\n  econstructor; crush...\nQed.\n\nLemma wfHeldLocks_app :\n  forall H Ls1 Ls2,\n    (wfHeldLocks H Ls1 /\\ wfHeldLocks H Ls2 <-> wfHeldLocks H (Ls1 ++ Ls2)).\nProof with eauto using in_eq, in_cons.\n  split.\n  + introv wfLs.\n    inverts wfLs as wfLs1 wfLs2.\n    constructor.\n    apply Forall_app...\n    inv wfLs1...\n    inv wfLs2...\n  + introv wfLs.\n    induction Ls1 as [|l]; simpls...\n    inverts wfLs as wfLs.\n    inverts wfLs as wfL wfLs'.\n    assert(wfLs: wfHeldLocks H (Ls1 ++ Ls2))...\n    apply IHLs1 in wfLs as [wfLs1 wfLs2]...\n    split...\n    econstructor...\n    econstructor...\n    apply Forall_forall.\n    rewrite Forall_forall in wfLs'.\n    introv HIn.\n    assert (HIn': In x (Ls1 ++ Ls2))\n      by eauto using in_or_app...\nQed.\n\nLemma wfHeldLocks_cons :\n  forall H Ls l,\n    wfHeldLocks H Ls ->\n    wfLock H l ->\n    wfHeldLocks H (l :: Ls).\nProof with eauto.\n  introv wfLs wfL.\n  inv wfLs...\nQed.\n\nLemma wfHeldLocks_leftmost :\n  forall H T,\n    wfLocking H T ->\n    wfHeldLocks H (leftmost_locks T).\nProof with eauto.\n  introv wfL.\n  induction T; inv wfL...\nQed.\n\nLemma wfHeldLocks_remove :\n  forall H Ls L eq_dec,\n    wfHeldLocks H Ls ->\n    wfHeldLocks H (remove eq_dec L Ls).\nProof with eauto using wfHeldLocks_cons.\n  introv wfLs.\n  induction Ls as [| l]...\n  inverts wfLs as wfLs.\n  inverts wfLs.\n  simpl. cases_if...\nQed.\n\nCorollary wfLocking_wfHeldLocks :\n  forall H T,\n    wfLocking H T ->\n    wfHeldLocks H (heldLocks T).\nProof with eauto.\n  introv wfL.\n  induction T; simpls; inv wfL...\n  apply wfHeldLocks_app...\nQed.\n\n(*\n----------\nwfThreads\n----------\n*)\n\nHint Constructors wfThreads.\n\nCorollary wfThreads_wfEnv :\n  forall P t' Gamma T t,\n    wfProgram P t' ->\n    wfThreads P Gamma T t ->\n    wfEnv P Gamma.\nProof with eauto with env.\n  introv wfP wfT. inv wfT...\nQed.\n\nHint Immediate wfThreads_wfEnv.\n\nLemma wfThreads_invariance :\n  forall P t' Gamma Gamma' T t,\n    wfProgram P t' ->\n    (forall x, Gamma x = Gamma' x) ->\n    wfThreads P Gamma T t ->\n    wfThreads P Gamma' T t.\nProof with eauto using hasType_subsumption,\n                       wfEnv_equiv with env.\n  introv wfP Hequiv wfT.\n  induction wfT...\nQed.\n\nLemma wfThreads_subsumption :\n  forall P t' Gamma Gamma' T t,\n    wfProgram P t' ->\n    wfSubsumption Gamma Gamma' ->\n    wfEnv P Gamma' ->\n    wfThreads P Gamma T t ->\n    wfThreads P Gamma' T t.\nProof with eauto using hasType_subsumption with env.\n  introv wfP wfEnv' Hsub wfT.\n  induction wfT...\nQed.\n\nLemma wfThreads_heapExtend :\n  forall P t' Gamma T t c l,\n    wfProgram P t' ->\n    wfType P (TClass c) ->\n    fresh Gamma (env_loc l) ->\n    wfThreads P Gamma T t ->\n    wfThreads P (extend Gamma (env_loc l) (TClass c)) T t.\nProof with eauto using hasType_extend_loc with env.\n  introv wfP wfTy Hfresh wfT.\n  generalize dependent t.\n  induction T; intros; inv wfT...\nQed.\n\n(*\n----------------\nwfConfiguration\n----------------\n*)\n\nHint Constructors wfConfiguration.\n\nLemma wfConfiguration_substitution :\n  forall P Gamma H V n Ls e e' t,\n    freeVars e' = nil ->\n    P; Gamma |- e' \\in t ->\n    wfLocking H (T_Thread Ls e') ->\n    wfConfiguration P Gamma (H, V, n, T_Thread Ls e) t ->\n    wfConfiguration P Gamma (H, V, n, T_Thread Ls e') t.\nProof with eauto.\n  introv Hfree hasType wfL wfCfg.\n  inverts wfCfg...\nQed.\n\nLemma wfConfiguration_heapExtend :\n  forall P t' Gamma H V n T t c F L,\n    wfProgram P t' ->\n    wfConfiguration P Gamma (H, V, n, T) t ->\n    wfType P (TClass c) ->\n    wfFields P Gamma c F ->\n    wfConfiguration P (extend Gamma (env_loc (length H)) (TClass c))\n                    ((heapExtend H (c, F, L)), V, n, T) t.\nProof with eauto 6 using\n                 wfHeap_extend,\n                 wfVars_heapExtend,\n                 wfThreads_heapExtend,\n                 wfLocking_heapExtend with env.\n  introv wfP wfCfg wfTy wfF.\n  inverts wfCfg.\n  assert(fresh Gamma (env_loc (length H)))\n    by eauto using wfHeap_fresh, heapLookup_ge...\nQed.\n\nLemma wfConfiguration_heapUpdate :\n  forall P t' Gamma H V n T t l c F L L' F',\n    wfProgram P t' ->\n    wfConfiguration P Gamma (H, V, n, T) t ->\n    heapLookup H l = Some (c, F, L) ->\n    wfFields P Gamma c F' ->\n    (In l (heldLocks T) -> L' = LLocked) ->\n    wfConfiguration P Gamma\n                    ((heapUpdate H l (c, F', L')), V, n, T) t.\nProof with eauto using\n                 wfHeap_update,\n                 wfLocking_heapUpdate.\n  introv wfP wfCfg HLookup wfF' HL.\n  inverts wfCfg...\nQed.\n", "meta": {"author": "EliasC", "repo": "oolong", "sha": "f449d42f70da1c404883860296ec4f2c5ed088b7", "save_path": "github-repos/coq/EliasC-oolong", "path": "github-repos/coq/EliasC-oolong/oolong-f449d42f70da1c404883860296ec4f2c5ed088b7/coq/vanilla/WellFormednessProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2297239013092188}}
{"text": "(**\n  This file is a part of a formalisation of a subset of Core Erlang.\n\n  In this file, we define CIU equivalence for sequential Core Erlang.\n  We prove that CIU equivalence coicides with logical relations.\n*)\n\nRequire Export Compatibility.\n\nImport ListNotations.\n\nDefinition CIU (e1 e2 : Exp) : Prop :=\n  EXPCLOSED e1 /\\ EXPCLOSED e2 /\\\n  forall F, FSCLOSED F -> | F, e1 | ↓ -> | F, e2 | ↓.\n\nDefinition CIU_open (Γ : nat) (e1 e2 : Exp) :=\n  forall ξ, SUBSCOPE Γ ⊢ ξ ∷ 0 ->\n  CIU (e1.[ξ]) (e2.[ξ]).\n\nLemma CIU_closed :\n  forall e1 e2,\n  CIU e1 e2 -> EXPCLOSED e1 /\\ EXPCLOSED e2.\nProof.\n  intros. unfold CIU in H. intuition.\nQed.\n\nLemma CIU_closed_l : forall {e1 e2},\n    CIU e1 e2 ->\n    EXPCLOSED e1.\nProof.\n  intros.\n  apply CIU_closed in H.\n  intuition.\nQed.\n\nGlobal Hint Resolve CIU_closed_l : core.\n\nLemma CIU_closed_r : forall {e1 e2},\n    CIU e1 e2 ->\n    EXPCLOSED e2.\nProof.\n  intros.\n  apply CIU_closed in H.\n  intuition.\nQed.\n\nGlobal Hint Resolve CIU_closed_r : core.\n\nLemma CIU_open_scope : forall {Γ e1 e2},\n    CIU_open Γ e1 e2 ->\n    EXP Γ ⊢ e1 /\\ EXP Γ ⊢ e2.\nProof.\n  intros.\n  unfold CIU_open in H.\n  split;\n    eapply subst_implies_scope_exp; eauto.\nQed.\n\nLemma CIU_open_scope_l : forall {Γ e1 e2},\n    CIU_open Γ e1 e2 ->\n    EXP Γ ⊢ e1.\nProof.\n  intros.\n  apply CIU_open_scope in H.\n  intuition.\nQed.\n\nGlobal Hint Resolve CIU_open_scope_l : core.\n\nLemma CIU_open_scope_r : forall {Γ e1 e2},\n    CIU_open Γ e1 e2 ->\n    EXP Γ ⊢ e2.\nProof.\n  intros.\n  apply CIU_open_scope in H.\n  intuition.\nQed.\n\n\nGlobal Hint Resolve CIU_open_scope_r : core.\n\nLemma Erel_implies_CIU : forall Γ e1 e2,\n  Erel_open Γ e1 e2 ->\n  CIU_open Γ e1 e2.\nProof.\n  intros.\n  unfold CIU_open; intros.\n  unfold CIU.\n  split. 2: split.\n  - apply -> (subst_preserves_scope_exp); eauto.\n  - apply -> (subst_preserves_scope_exp); eauto.\n  - unfold Erel_open, Erel, exp_rel in H. intros. destruct H2.\n    specialize (H x ξ ξ (Grel_Fundamental _ _ H0 _)). destruct H, H3.\n    eapply H4 in H2; eauto. apply Frel_Fundamental_closed. auto.\nQed.\n\nLemma Erel_comp_CIU_implies_Erel : forall {Γ e1 e2 e3},\n    Erel_open Γ e1 e2 ->\n    CIU_open Γ e2 e3 ->\n    Erel_open Γ e1 e3.\nProof.\n  intros Γ e1 e2 e3 HErel HCIU.\n  unfold Erel_open, Erel, exp_rel.\n  intros.\n  inversion H as [Hξ1 [Hξ2 _]].\n  split. 2: split. 1-2: apply -> subst_preserves_scope_exp; eauto.\n  intros. eapply HErel in H1; eauto. eapply HCIU in H1; eauto.\nQed.\n\nLemma CIU_implies_Erel : forall {Γ e1 e2},\n    CIU_open Γ e1 e2 ->\n    Erel_open Γ e1 e2.\nProof.\n  intros.\n  eapply Erel_comp_CIU_implies_Erel; eauto.\nQed.\n\nTheorem CIU_iff_Erel : forall {Γ e1 e2},\n    CIU_open Γ e1 e2 <->\n    Erel_open Γ e1 e2.\nProof.\n  intuition (auto using CIU_implies_Erel, Erel_implies_CIU).\nQed.\n\nTheorem CIU_eval : forall e1 v,\n  EXPCLOSED e1 ->\n  ⟨ [], e1 ⟩ -->* v -> CIU e1 v /\\ CIU v e1.\nProof.\n  intros. split. split. 2: split. auto.\n  apply step_any_closedness in H0; auto. now constructor.\n  intros. destruct H2, H0, H3. eapply frame_indep_nil in H3.\n  eapply terminates_step_any. 2: exact H3. eexists. exact H2.\n\n  split. 2: split. 2: auto.\n  apply step_any_closedness in H0; auto. now constructor.\n  intros. destruct H2, H0, H3. eapply frame_indep_nil in H3.\n  exists (x + x0).\n  eapply term_step_term. exact H3. 2: lia. replace (x + x0 - x0) with x by lia. exact H2.\nQed.\n\nTheorem CIU_list_parts : forall e1 e2 e1' e2',\n  VALCLOSED e1 -> VALCLOSED e2 -> VALCLOSED e1' -> VALCLOSED e2' ->\n  CIU (ECons e1 e2) (ECons e1' e2')\n->\n  CIU e1 e1' /\\ CIU e2 e2'.\nProof.\n  intros. destruct H3 as [? [? ?]].\n  split; split.\n  1, 3: constructor; auto.\n  all: split. 1, 3: constructor; auto.\n  * intros. assert (FSCLOSED (FCase (PCons PVar PVar) (EVar 0) inf :: F)). {\n       constructor; auto. constructor; auto. 2: repeat constructor.\n       simpl. do 2 constructor. auto. inversion H8. inversion H8.\n     }\n     specialize (H5 (FCase (PCons PVar PVar) (EVar 0) inf :: F) H8).\n     destruct H7.\n     assert (| FCase (PCons PVar PVar) (EVar 0) inf :: F, ECons e1 e2 | ↓). {\n       exists (4 + x). apply term_cons.\n       constructor; auto. constructor; auto. eapply term_case_true.\n       constructor; auto. reflexivity.\n       simpl. auto.\n     }\n     apply H5 in H9. destruct H9.\n     inversion H9; subst; try inversion_is_value.\n     inversion H14; subst; try inversion_is_value.\n     inversion H16; subst; try inversion_is_value.\n     inversion H19; subst; try inversion_is_value.\n     - simpl in H23. inversion H23. subst. simpl in H24. eexists; eassumption.\n     - apply inf_diverges in H24. contradiction.\n  * intros. assert (FSCLOSED (FCase (PCons PVar PVar) (EVar 1) inf :: F)). {\n       constructor; auto. constructor; auto.\n       do 2 constructor.\n       do 2 constructor. auto. intros. inversion H8. inversion H8.\n     }\n     specialize (H5 (FCase (PCons PVar PVar) (EVar 1) inf :: F) H8).\n     destruct H7.\n     assert (| FCase (PCons PVar PVar) (EVar 1) inf :: F, ECons e1 e2 | ↓). {\n       exists (4 + x). apply term_cons.\n       constructor; auto. constructor; auto. eapply term_case_true.\n       constructor; auto. reflexivity.\n       simpl. auto.\n     }\n     apply H5 in H9. destruct H9.\n     inversion H9; subst; try inversion_is_value.\n     inversion H14; subst; try inversion_is_value.\n     inversion H16; subst; try inversion_is_value.\n     inversion H19; subst; try inversion_is_value.\n     - simpl in H23. inversion H23. subst. simpl in H24. eexists; eassumption.\n     - apply inf_diverges in H24. contradiction.\nQed.\n\n(* Theorem CIU_implies_Vrel :\n  forall e1 e2, VALCLOSED e1 -> VALCLOSED e2 -> CIU e1 e2 -> CIU e2 e1 (* for comfort *)\n -> \n  forall n, Vrel n e1 e2.\nProof.\n  induction e1; destruct e2; intros; try inversion_is_value; rewrite Vrel_Fix_eq;\n    simpl; destruct H1 as [Ecl1 [Ecl2 H1]]; destruct H2 as [Ecl1' [Ecl2' H2]]; try lia.\n  * split. 2: split. 1-2: constructor.\n    epose proof (H1 [FCase (PLit l) (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    simpl in H11. break_match_hyp. now apply Z.eqb_eq in Heqb. congruence.\n    now apply inf_diverges in H12.\n  * epose proof (H1 [FCase (PLit l) (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    inversion H11.\n    now apply inf_diverges in H12.\n  * epose proof (H1 [FCase (PLit l) (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    inversion H11.\n    now apply inf_diverges in H12.\n  * epose proof (H1 [FCase (PLit l) (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    inversion H11.\n    now apply inf_diverges in H12.\n  * epose proof (H2 [FCase (PLit l) (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    inversion H11.\n    now apply inf_diverges in H12.\n  * split. 2: split. 1-2: auto.\n    epose proof (H1 (FCase (PLit 0) (ELit 0) (EApp ))).\n  * epose proof (H2 [FCase PNil (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    inversion H11.\n    now apply inf_diverges in H12.\n  * epose proof (H2 [FCase PNil (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    inversion H11.\n    now apply inf_diverges in H12.\n  * epose proof (H1 [FCase PNil (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    inversion H11.\n    now apply inf_diverges in H12.\n  * epose proof (H1 [FCase PNil (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    inversion H11.\n    now apply inf_diverges in H12.\n  * split; constructor; auto.\n  * epose proof (H1 [FCase PNil (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    inversion H11.\n    now apply inf_diverges in H12.\n  * epose proof (H1 [FCase (PCons PVar PVar) (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    inversion H11.\n    now apply inf_diverges in H12.\n  * epose proof (H1 [FCase (PCons PVar PVar) (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    inversion H11.\n    now apply inf_diverges in H12.\n  * epose proof (H1 [FCase (PCons PVar PVar) (ELit 0) inf] _ _).\n    destruct H3. inversion H3; subst; try inversion_is_value.\n    inversion H11.\n    now apply inf_diverges in H12.\n  * split. 2: split. 1-2: auto. inversion H. inversion H0. subst.\n    assert (CIU e1_1 e2_1). {\n      apply (CIU_list_parts e1_1 e1_2 e2_1 e2_2); auto.\n      split. 2: split. 1-2: do 2 constructor; auto.\n      intros. destruct H4.\n      inversion H4; subst; try inversion_is_value.\n      inversion H13; subst; try inversion_is_value.\n      inversion H15; subst; try inversion_is_value.\n      assert (exists k, | F, VCons e1_1 e1_2 | k ↓). { eexists; eauto. } apply H1 in H7.\n      destruct H7. exists (3 + x). constructor; auto. constructor; auto. constructor; auto.\n      auto.\n   }\n   assert (CIU e1_2 e2_2). {\n      apply (CIU_list_parts e1_1 e1_2 e2_1 e2_2); auto.\n      split. 2: split. 1-2: do 2 constructor; auto.\n      intros. destruct H7.\n      inversion H7; subst; try inversion_is_value.\n      inversion H14; subst; try inversion_is_value.\n      inversion H16; subst; try inversion_is_value.\n      assert (exists k, | F, VCons e1_1 e1_2 | k ↓). { eexists; eauto. } apply H1 in H8.\n      destruct H8. exists (3 + x). constructor; auto. constructor; auto. constructor; auto.\n      auto.\n   }\n   assert (CIU e2_1 e1_1). {\n      apply (CIU_list_parts e2_1 e2_2 e1_1 e1_2); auto.\n      split. 2: split. 1-2: do 2 constructor; auto.\n      intros. destruct H8.\n      inversion H8; subst; try inversion_is_value.\n      inversion H15; subst; try inversion_is_value.\n      inversion H17; subst; try inversion_is_value.\n      assert (exists k, | F, VCons e2_1 e2_2 | k ↓). { eexists; eauto. } apply H2 in H11.\n      destruct H11. exists (3 + x). constructor; auto. constructor; auto. constructor; auto.\n      auto.\n   }\n   assert (CIU e2_2 e1_2). {\n      apply (CIU_list_parts e2_1 e2_2 e1_1 e1_2); auto.\n      split. 2: split. 1-2: do 2 constructor; auto.\n      intros. destruct H11.\n      inversion H11; subst; try inversion_is_value.\n      inversion H16; subst; try inversion_is_value.\n      inversion H18; subst; try inversion_is_value.\n      assert (exists k, | F, VCons e2_1 e2_2 | k ↓). { eexists; eauto. } apply H2 in H12.\n      destruct H12. exists (3 + x). constructor; auto. constructor; auto. constructor; auto.\n      auto.\n   }\n   do 2 rewrite <- Vrel_Fix_eq. split.\n   - apply IHe1_1; auto.\n   - apply IHe1_2; auto.\nUnshelve.\n  \nQed. *)\n", "meta": {"author": "harp-project", "repo": "Core-Erlang-mini", "sha": "19283cbac84b8b30602cd3b04978e8a3689a66f2", "save_path": "github-repos/coq/harp-project-Core-Erlang-mini", "path": "github-repos/coq/harp-project-Core-Erlang-mini/Core-Erlang-mini-19283cbac84b8b30602cd3b04978e8a3689a66f2/src/CIU.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2297239013092188}}
{"text": "From mathcomp.ssreflect Require Import ssreflect seq ssrbool ssrfun.\nRequire Import Coq.Classes.Morphisms.\n\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.AST.     (*for typ*)\nRequire Import compcert.common.Values. (*for val*)\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.lib.Integers.\n\nRequire Import VST.msl.Axioms.\nRequire Import Coq.ZArith.ZArith.\nRequire Import VST.concurrency.common.core_semantics.\nRequire Import VST.sepcomp.event_semantics.\nRequire Export VST.concurrency.common.semantics.\nRequire Export VST.concurrency.common.lksize.\nRequire Import VST.concurrency.common.threadPool.\n\nRequire Import VST.concurrency.common.machine_semantics.\nRequire Import VST.concurrency.common.permissions.\nRequire Import VST.concurrency.compiler.mem_equiv.\nRequire Import VST.concurrency.common.bounded_maps.\nRequire Import VST.concurrency.common.addressFiniteMap.\nRequire Import VST.concurrency.common.scheduler.\nRequire Import Coq.Program.Program.\n(*Require Import VST.concurrency.common.safety.\nRequire Import VST.concurrency.common.coinductive_safety.*)\n\n(* Require Import VST.veric.res_predicates. *)\n(* Require Import VST.veric.Clight_new. *)\n\nRequire Import VST.concurrency.common.HybridMachineSig.\n(* Require Import VST.concurrency.CoreSemantics_sum. *)\n\n\nModule DryHybridMachine.\n  Import Events ThreadPool.\n\n  Instance dryResources: Resources:=\n    {| res := access_map * access_map;\n       lock_info := access_map * access_map |}.\n\n  Section DryHybridMachine.\n        \n    (** Assume some threadwise semantics *)\n    Context {Sem: Semantics}\n            {tpool : @ThreadPool.ThreadPool dryResources Sem}.\n    \n    Notation C:= (@semC Sem).\n    Notation G:= (@semG Sem).\n    Notation semSem:= (@semSem Sem).\n\n    Notation thread_pool := (@t dryResources Sem).\n    (** Memories*)\n    Definition richMem: Type:= mem.\n    Definition dryMem: richMem -> mem:= fun x => x.\n    \n    (** The state respects the memory*)\n    \n    Record mem_compatible (tp: thread_pool) m : Prop :=\n      { compat_th :> forall {tid} (cnt: containsThread tp tid),\n            permMapLt (getThreadR cnt).1 (getMaxPerm m) /\\\n            permMapLt (getThreadR cnt).2 (getMaxPerm m);\n        compat_lp : forall l pmaps, lockRes tp l = Some pmaps ->\n                               permMapLt pmaps.1 (getMaxPerm m) /\\\n                               permMapLt pmaps.2 (getMaxPerm m);\n        lockRes_blocks: forall l rmap, lockRes tp l = Some rmap ->\n                                  Mem.valid_block m l.1}.\n\n    \n      Lemma  mem_compat_restrPermMap:\n        forall m perms st\n          (permMapLt: permMapLt perms (getMaxPerm m)),\n          (mem_compatible st m) ->\n          (mem_compatible st (restrPermMap permMapLt)).\n      Proof.\n        intros.\n        inversion H; econstructor.\n        - intros; unfold permissions.permMapLt.\n          split; intros;\n            erewrite getMax_restr; \n            eapply compat_th0.\n        - intros; unfold permissions.permMapLt.\n          split; intros;\n            erewrite getMax_restr; \n            eapply compat_lp0; eauto.\n        - intros. eapply restrPermMap_valid; eauto.\n      Qed.\n\n    (* should there be something that says that if something is a lock then\n     someone has at least readable permission on it?*)\n    Record invariant (tp: thread_pool) :=\n      { no_race_thr :\n          forall i j (cnti: containsThread tp i) (cntj: containsThread tp j)\n            (Hneq: i <> j),\n            permMapsDisjoint2 (getThreadR cnti)\n                              (getThreadR cntj); (*thread's resources are disjoint *)\n        no_race_lr:\n          forall laddr1 laddr2 rmap1 rmap2\n            (Hneq: laddr1 <> laddr2)\n            (Hres1: lockRes tp laddr1 = Some rmap1)\n            (Hres2: lockRes tp laddr2 = Some rmap2),\n            permMapsDisjoint2 rmap1 rmap2; (*lock's resources are disjoint *)\n        no_race:\n          forall i laddr (cnti: containsThread tp i) rmap\n            (Hres: lockRes tp laddr = Some rmap),\n            permMapsDisjoint2 (getThreadR cnti) rmap; (*resources are disjoint\n             between threads and locks*)\n\n        (* if an address is a lock then there can be no data\n             permission above non-empty for this address*)\n        thread_data_lock_coh:\n          forall i (cnti: containsThread tp i),\n            (forall j (cntj: containsThread tp j),\n                permMapCoherence (getThreadR cntj).1 (getThreadR cnti).2) /\\\n            (forall laddr rmap,\n                lockRes tp laddr = Some rmap ->\n                permMapCoherence rmap.1 (getThreadR cnti).2);\n        locks_data_lock_coh:\n          forall laddr rmap\n            (Hres: lockRes tp laddr = Some rmap),\n            (forall j (cntj: containsThread tp j),\n                permMapCoherence (getThreadR cntj).1 rmap.2) /\\\n            (forall laddr' rmap',\n                lockRes tp laddr' = Some rmap' ->\n                permMapCoherence rmap'.1 rmap.2);\n        lockRes_valid: lr_valid (lockRes tp) (*well-formed locks*)\n      }.\n\n    (** Steps*)\n    Inductive dry_step {tid0 tp m} (cnt: containsThread tp tid0)\n              (Hcompatible: mem_compatible tp m) :\n      thread_pool -> mem -> seq.seq mem_event -> Prop :=\n    | step_dry :\n        forall (tp':thread_pool) c m1 m' (c' : C) ev\n          (** Instal the permission's of the thread on non-lock locations*)\n          (Hrestrict_pmap: restrPermMap (Hcompatible tid0 cnt).1 = m1)\n          (Hinv: invariant tp)\n          (Hcode: getThreadC cnt = Krun c)\n          (Hcorestep: ev_step semSem c m1 ev c' m')\n          (** the new data resources of the thread are the ones on the\n           memory, the lock ones are unchanged by internal steps*)\n          (Htp': tp' = updThread cnt (Krun c') (getCurPerm m', (getThreadR cnt).2)),\n          dry_step cnt Hcompatible tp' m' ev.\n\n    Definition option_function {A B} (opt_f: option (A -> B)) (x:A): option B:=\n      match opt_f with\n        Some f => Some (f x)\n      | None => None\n      end.\n    Infix \"??\" := option_function (at level 80, right associativity).\n\n    Definition build_delta_content (dm: delta_map) (m:mem): delta_content :=\n      PTree.map (fun b dm_f =>\n                   fun ofs =>\n                     match dm_f ofs with\n                     | None | Some (None) \n                     | Some (Some Nonempty) => None\n                     | Some _ => Some (ZMap.get ofs (Maps.PMap.get b (Mem.mem_contents m)))\n                     end) dm.\n    \n      \n    \n    Inductive ext_step {isCoarse:bool} {tid0 tp m}\n              (cnt0:containsThread tp tid0)(Hcompat:mem_compatible tp m):\n      thread_pool -> mem -> sync_event -> Prop :=\n    | step_acquire :\n        forall (tp' tp'':thread_pool) marg m0 m1 c m' b ofs\n          (pmap : lock_info)\n          (pmap_tid' : access_map)\n          (virtueThread : delta_map * delta_map)\n          (Hbounded: if isCoarse then\n                       ( sub_map virtueThread.1 (getMaxPerm m).2 /\\\n                         sub_map virtueThread.2 (getMaxPerm m).2)\n                     else\n                       True ),\n          let newThreadPerm := (computeMap (getThreadR cnt0).1 virtueThread.1,\n                                computeMap (getThreadR cnt0).2 virtueThread.2) in\n          forall\n            (Hinv : invariant tp)\n            (Hcode: getThreadC cnt0 = Kblocked c)\n            (* To check if the machine is at an external step and load its arguments install the thread data permissions*)\n            (Hrestrict_pmap_arg: restrPermMap (Hcompat tid0 cnt0).1 = marg)\n            (Hat_external: semantics.at_external semSem c marg = Some (LOCK, Vptr b ofs::nil))\n            (** install the thread's permissions on lock locations*)\n            (Hrestrict_pmap0: restrPermMap (Hcompat tid0 cnt0).2 = m0)\n            (** To acquire the lock the thread must have [Readable] permission on it*)\n            (Haccess: Mem.range_perm m0 b (Ptrofs.intval ofs) ((Ptrofs.intval ofs) + LKSIZE) Cur Readable)\n            (** check if the lock is free*)\n            (Hload: Mem.load Mint32 m0 b (Ptrofs.intval ofs) = Some (Vint Int.one))\n            (** set the permissions on the lock location equal to the max permissions on the memory*)\n            (Hset_perm: setPermBlock (Some Writable)\n                                     b (Ptrofs.intval ofs) ((getThreadR cnt0).2) LKSIZE_nat = pmap_tid')\n            (Hlt': permMapLt pmap_tid' (getMaxPerm m))\n            (Hlt_new: if isCoarse then\n                       ( permMapLt (fst newThreadPerm) (getMaxPerm m) /\\\n                         permMapLt (snd newThreadPerm) (getMaxPerm m))\n                     else True )\n            (Hrestrict_pmap: restrPermMap Hlt' = m1)\n            (** acquire the lock*)\n            (Hstore: Mem.store Mint32 m1 b (Ptrofs.intval ofs) (Vint Int.zero) = Some m')\n            (HisLock: lockRes tp (b, Ptrofs.intval ofs) = Some pmap)\n            (Hangel1: permMapJoin pmap.1 (getThreadR cnt0).1 newThreadPerm.1)\n            (Hangel2: permMapJoin pmap.2 (getThreadR cnt0).2 newThreadPerm.2)\n            (Htp': tp' = updThread cnt0 (Kresume c Vundef) newThreadPerm)\n            (** acquiring the lock leaves empty permissions at the resource pool*)\n            (Htp'': tp'' = updLockSet tp' (b, Ptrofs.intval ofs) (empty_map, empty_map)),\n            ext_step cnt0 Hcompat tp'' m'\n                     (acquire (b, Ptrofs.intval ofs)\n                              (Some (build_delta_content (fst virtueThread) m')))\n\n    | step_release :\n        forall (tp' tp'':thread_pool) marg m0 m1 c m' b ofs virtueThread virtueLP pmap_tid' rmap\n          (Hbounded: if isCoarse then\n                       ( sub_map virtueThread.1 (getMaxPerm m).2 /\\\n                         sub_map virtueThread.2 (getMaxPerm m).2)\n                     else\n                       True )\n          (HboundedLP: if isCoarse then\n                         ( map_empty_def virtueLP.1 /\\\n                           map_empty_def virtueLP.2 /\\\n                           sub_map virtueLP.1.2 (getMaxPerm m).2 /\\\n                           sub_map virtueLP.2.2 (getMaxPerm m).2)\n                       else\n                         True ),\n          let newThreadPerm := (computeMap (getThreadR cnt0).1 virtueThread.1,\n                                computeMap (getThreadR cnt0).2 virtueThread.2) in\n          forall\n            (Hinv : invariant tp)\n            (Hcode: getThreadC cnt0 = Kblocked c)\n            (* To check if the machine is at an external step and load its arguments install the thread data permissions*)\n            (Hrestrict_pmap_arg: restrPermMap (Hcompat tid0 cnt0).1 = marg)\n            (Hat_external: semantics.at_external semSem c marg =\n                           Some (UNLOCK, Vptr b ofs::nil))\n            (** install the thread's permissions on lock locations *)\n            (Hrestrict_pmap0: restrPermMap (Hcompat tid0 cnt0).2 = m0)\n            (** To release the lock the thread must have [Readable] permission on it*)\n            (Haccess: Mem.range_perm m0 b (Ptrofs.intval ofs) ((Ptrofs.intval ofs) + LKSIZE) Cur Readable)\n            (Hload: Mem.load Mint32 m0 b (Ptrofs.intval ofs) = Some (Vint Int.zero))\n            (** set the permissions on the lock location equal to [Writable]*)\n            (Hset_perm: setPermBlock (Some Writable)\n                                     b (Ptrofs.intval ofs) ((getThreadR cnt0).2) LKSIZE_nat = pmap_tid')\n            (Hlt': permMapLt pmap_tid' (getMaxPerm m))\n            (Hrestrict_pmap: restrPermMap Hlt' = m1)\n            (** release the lock *)\n            (Hstore: Mem.store Mint32 m1 b (Ptrofs.intval ofs) (Vint Int.one) = Some m')\n            (HisLock: lockRes tp (b, Ptrofs.intval ofs) = Some rmap)\n            (Hrmap: forall b ofs, rmap.1 !! b ofs = None /\\ rmap.2 !! b ofs = None)\n            (Hangel1: permMapJoin newThreadPerm.1 virtueLP.1 (getThreadR cnt0).1)\n            (Hangel2: permMapJoin newThreadPerm.2 virtueLP.2 (getThreadR cnt0).2)\n            (Htp': tp' = updThread cnt0 (Kresume c Vundef)\n                                   (computeMap (getThreadR cnt0).1 virtueThread.1,\n                                    computeMap (getThreadR cnt0).2 virtueThread.2))\n            (Htp'': tp'' = updLockSet tp' (b, Ptrofs.intval ofs) virtueLP),\n            ext_step cnt0 Hcompat tp'' m'\n                     (release (b, Ptrofs.intval ofs)\n                              (Some (build_delta_content (fst virtueThread) m')))\n    | step_create :\n        forall (tp_upd tp':thread_pool) c marg b ofs arg virtue1 virtue2\n          (Hbounded: if isCoarse then\n                       ( sub_map virtue1.1 (getMaxPerm m).2 /\\\n                         sub_map virtue1.2 (getMaxPerm m).2)\n                     else\n                       True )\n          (Hbounded_new: if isCoarse then\n                           ( sub_map virtue2.1 (getMaxPerm m).2 /\\\n                             sub_map virtue2.2 (getMaxPerm m).2)\n                         else\n                           True ),\n          let threadPerm' := (computeMap (getThreadR cnt0).1 virtue1.1,\n                              computeMap (getThreadR cnt0).2 virtue1.2) in\n          let newThreadPerm := (computeMap empty_map virtue2.1,\n                                computeMap empty_map virtue2.2) in\n          forall\n            (Hinv : invariant tp)\n            (Hcode: getThreadC cnt0 = Kblocked c)\n            (* To check if the machine is at an external step and load its arguments install the thread data permissions*)\n            (Hrestrict_pmap_arg: restrPermMap (Hcompat tid0 cnt0).1 = marg)\n            (Hat_external: semantics.at_external semSem c marg = Some (CREATE, Vptr b ofs::arg::nil))\n            (Harg: Val.inject (Mem.flat_inj (Mem.nextblock m)) arg arg)\n            (** we do not need to enforce the almost empty predicate on thread\n           spawn as long as it's considered a synchronizing operation *)\n            (Hangel1: permMapJoin newThreadPerm.1 threadPerm'.1 (getThreadR cnt0).1)\n            (Hangel2: permMapJoin newThreadPerm.2 threadPerm'.2 (getThreadR cnt0).2)\n            (Htp_upd: tp_upd = updThread cnt0 (Kresume c Vundef) threadPerm')\n            (Htp': tp' = addThread tp_upd (Vptr b ofs) arg newThreadPerm),\n            ext_step cnt0 Hcompat tp' m\n                     (spawn (b, Ptrofs.intval ofs)\n                            (Some (build_delta_content (fst virtue1) m))\n                            (Some (build_delta_content (fst virtue2) m)))\n\n\n    | step_mklock :\n        forall  (tp' tp'': thread_pool) marg m1 c m' b ofs pmap_tid',\n          let: pmap_tid := getThreadR cnt0 in\n          forall\n            (Hinv : invariant tp)\n            (Hcode: getThreadC cnt0 = Kblocked c)\n            (* To check if the machine is at an external step and load its arguments install the thread data permissions*)\n            (Hrestrict_pmap_arg: restrPermMap (Hcompat tid0 cnt0).1 = marg)\n            (Hat_external: semantics.at_external semSem c marg = Some (MKLOCK, Vptr b ofs::nil))\n            (** install the thread's data permissions*)\n            (Hrestrict_pmap: restrPermMap (Hcompat tid0 cnt0).1 = m1)\n            (** To create the lock the thread must have [Writable] permission on it*)\n            (Hfreeable: Mem.range_perm m1 b (Ptrofs.intval ofs) ((Ptrofs.intval ofs) + LKSIZE) Cur Writable)\n            (** lock is created in acquired state*)\n            (Hstore: Mem.store Mint32 m1 b (Ptrofs.intval ofs) (Vint Int.zero) = Some m')\n            (** The thread's data permissions are set to Nonempty*)\n            (Hdata_perm: setPermBlock\n                           (Some Nonempty)\n                           b\n                           (Ptrofs.intval ofs)\n                           pmap_tid.1\n                           LKSIZE_nat = pmap_tid'.1)\n            (** thread lock permission is increased *)\n            (Hlock_perm: setPermBlock\n                           (Some Writable)\n                           b\n                           (Ptrofs.intval ofs)\n                           pmap_tid.2\n                           LKSIZE_nat = pmap_tid'.2)\n            (** Require that [(b, Ptrofs.intval ofs)] was not a lock*)\n            (HlockRes: lockRes tp (b, Ptrofs.intval ofs) = None)\n            (Htp': tp' = updThread cnt0 (Kresume c Vundef) pmap_tid')\n            (** the lock has no resources initially *)\n            (Htp'': tp'' = updLockSet tp' (b, Ptrofs.intval ofs) (empty_map, empty_map)),\n            ext_step cnt0 Hcompat tp'' m' (mklock (b, Ptrofs.intval ofs))\n\n    | step_freelock :\n        forall  (tp' tp'': thread_pool) c marg b ofs pmap_tid' m1 pdata rmap\n           (Hbounded: if isCoarse then\n                        ( bounded_maps.bounded_nat_func' pdata LKSIZE_nat)\n                      else\n                        True ),\n          let: pmap_tid := getThreadR cnt0 in\n          forall\n            (Hinv: invariant tp)\n            (Hcode: getThreadC cnt0 = Kblocked c)\n            (* To check if the machine is at an external step and load its arguments install the thread data permissions*)\n            (Hrestrict_pmap_arg: restrPermMap (Hcompat tid0 cnt0).1 = marg)\n            (Hat_external: semantics.at_external semSem c marg = Some (FREE_LOCK, Vptr b ofs::nil))\n            (** If this address is a lock*)\n            (His_lock: lockRes tp (b, (Ptrofs.intval ofs)) = Some rmap)\n            (** And the lock is taken *)\n            (Hrmap: forall b ofs, rmap.1 !! b ofs = None /\\ rmap.2 !! b ofs = None)\n            (** Install the thread's lock permissions*)\n            (Hrestrict_pmap: restrPermMap (Hcompat tid0 cnt0).2 = m1)\n            (** To free the lock the thread must have at least Writable on it*)\n            (Hfreeable: Mem.range_perm m1 b (Ptrofs.intval ofs) ((Ptrofs.intval ofs) + LKSIZE) Cur Writable)\n            (** lock permissions of the thread are dropped to empty *)\n            (Hlock_perm: setPermBlock\n                           None\n                           b\n                           (Ptrofs.intval ofs)\n                           pmap_tid.2\n                           LKSIZE_nat = pmap_tid'.2)\n            (** data permissions are computed in a non-deterministic way *)\n            (Hneq_perms: forall i,\n                (0 <= Z.of_nat i < LKSIZE)%Z ->\n                Mem.perm_order'' (pdata (S i)) (Some Writable)\n            )\n            (*Hpdata: perm_order pdata Writable*)\n            (Hdata_perm: setPermBlock_var (*=setPermBlockfunc*)\n                           pdata\n                           b\n                           (Ptrofs.intval ofs)\n                           pmap_tid.1\n                           LKSIZE_nat = pmap_tid'.1)\n            (Htp': tp' = updThread cnt0 (Kresume c Vundef) pmap_tid')\n            (Htp'': tp'' = remLockSet tp' (b, Ptrofs.intval ofs)),\n            ext_step cnt0 Hcompat  tp'' m (freelock (b, Ptrofs.intval ofs))\n    | step_acqfail :\n        forall  c b ofs marg m1\n           (Hinv : invariant tp)\n           (Hcode: getThreadC cnt0 = Kblocked c)\n           (* To check if the machine is at an external step and load its arguments install the thread data permissions*)\n           (Hrestrict_pmap_arg: restrPermMap (Hcompat tid0 cnt0).1 = marg)\n           (Hat_external: semantics.at_external semSem c marg = Some (LOCK, Vptr b ofs::nil))\n           (** Install the thread's lock permissions*)\n           (Hrestrict_pmap: restrPermMap (Hcompat tid0 cnt0).2 = m1)\n           (** To acquire the lock the thread must have [Readable] permission on it*)\n           (Haccess: Mem.range_perm m1 b (Ptrofs.intval ofs) ((Ptrofs.intval ofs) + LKSIZE) Cur Readable)\n           (** Lock is already acquired.*)\n           (Hload: Mem.load Mint32 m1 b (Ptrofs.intval ofs) = Some (Vint Int.zero)),\n          ext_step cnt0 Hcompat tp m (failacq (b, Ptrofs.intval ofs)).\n\n    Definition threadStep: forall {tid0 ms m},\n        containsThread ms tid0 -> mem_compatible ms m ->\n        thread_pool -> mem -> seq.seq mem_event -> Prop:=\n      @dry_step.\n\n    Lemma threadStep_at_Krun:\n      forall i tp m cnt cmpt tp' m' tr,\n        @threadStep i tp m cnt cmpt tp' m' tr ->\n        (exists q, @getThreadC _ _ _ i tp cnt = Krun q).\n    Proof.\n      intros.\n      inversion H; subst;\n        now eauto.\n    Qed.\n    \n    Lemma threadStep_equal_run:\n      forall i tp m cnt cmpt tp' m' tr,\n        @threadStep i tp m cnt cmpt tp' m' tr ->\n        forall j,\n          (exists cntj q, @getThreadC _ _ _ j tp cntj = Krun q) <->\n          (exists cntj' q', @getThreadC _ _ _ j tp' cntj' = Krun q').\n    Proof.\n      intros. split.\n      - intros [cntj [ q running]].\n        inversion H; subst.\n        assert (cntj':=cntj).\n        (* XXX: eapply does not work here. report? *)\n        pose proof (cntUpdate (Krun c') (getCurPerm m', (getThreadR cnt)#2) cnt cntj') as cntj''.\n        exists cntj''.\n        destruct (NatTID.eq_tid_dec i j).\n        + subst j; exists c'.\n          rewrite gssThreadCode; reflexivity.\n        + exists q.\n          erewrite gsoThreadCode;\n            now eauto.\n      - intros [cntj' [ q' running]].\n        inversion H; subst.\n        assert (cntj:=cntj').\n        eapply cntUpdate' with(c0:=Krun c')(p:=(getCurPerm m', (getThreadR cnt)#2)) in cntj; eauto.\n        exists cntj.\n        destruct (NatTID.eq_tid_dec i j).\n        + subst j; exists c.\n          rewrite <- Hcode.\n          f_equal.\n          apply cnt_irr.\n        + exists q'.\n          rewrite gsoThreadCode in running; auto.\n    Qed.\n\n    Definition syncStep (isCoarse:bool) :\n      forall {tid0 ms m},\n        containsThread ms tid0 -> mem_compatible ms m ->\n        thread_pool -> mem -> sync_event -> Prop:=\n      @ext_step isCoarse.\n\n    Lemma syncstep_equal_run:\n      forall b i tp m cnt cmpt tp' m' tr,\n        @syncStep b i tp m cnt cmpt tp' m' tr ->\n        forall j,\n          (exists cntj q, @getThreadC _ _ _ j tp cntj = Krun q) <->\n          (exists cntj' q', @getThreadC _ _ _ j tp' cntj' = Krun q').\n    Proof.\n      intros b i tp m cnt cmpt tp' m' tr H j; split.\n      - intros [cntj [ q running]].\n        destruct (NatTID.eq_tid_dec i j).\n        + subst j. generalize running; clear running.\n          inversion H; subst;\n            match goal with\n            | [ H: getThreadC ?cnt = Kblocked ?c |- _ ] =>\n              replace cnt with cntj in H by apply cnt_irr;\n                intros HH; rewrite HH in H; inversion H\n            end.\n        + (*this should be easy to automate or shorten*)\n          inversion H; subst.\n          * exists (cntUpdateL _ _\n                          (cntUpdate (Kresume c Vundef) _\n                                     _ cntj)), q.\n            rewrite gLockSetCode.\n            apply cntUpdate;\n              now auto.\n            intros.\n            rewrite gsoThreadCode; assumption.\n          * exists ( (cntUpdateL _ _\n                            (cntUpdate (Kresume c Vundef) _ _ cntj))), q.\n            rewrite gLockSetCode.\n            apply cntUpdate;\n              now auto.\n            intros.\n            rewrite gsoThreadCode; assumption.\n          * exists (cntAdd _ _ _\n                      (cntUpdate (Kresume c Vundef) _ _ cntj)), q.\n            erewrite gsoAddCode .\n            rewrite gsoThreadCode; assumption.\n          * exists ( (cntUpdateL _ _\n                            (cntUpdate (Kresume c Vundef) _ _ cntj))), q.\n            rewrite gLockSetCode.\n            apply cntUpdate;\n              now auto.\n            intros.\n            rewrite gsoThreadCode; assumption.\n          * exists ( (cntRemoveL _\n                            (cntUpdate (Kresume c Vundef) _ _ cntj))), q.\n            rewrite gRemLockSetCode.\n            apply cntUpdate;\n              now auto.\n            intros.\n            rewrite gsoThreadCode; assumption.\n          * exists cntj, q; assumption.\n      - intros [cntj [ q running]].\n        destruct (NatTID.eq_tid_dec i j).\n        + subst j. generalize running; clear running;\n          inversion H; subst; intros;\n            try (exfalso;\n                 erewrite gLockSetCode with (cnti := cntUpdateL' _ _ cntj) in running;\n                 rewrite gssThreadCode in running;\n                 discriminate).\n          \n          { (*addthread*)\n            assert (cntj':=cntj).\n            eapply cntAdd' in cntj'; destruct cntj' as [ [HH HHH] | HH].\n            * exfalso.\n              assert (Heq: getThreadC cntj = getThreadC HH)\n                by (rewrite gsoAddCode; reflexivity).\n              rewrite Heq in running.\n              rewrite gssThreadCode in running.\n              discriminate.\n            * erewrite gssAddCode in running; eauto.\n              discriminate. }\n          { (*remove lock*)\n            pose proof (cntUpdate' _ _ cnt (cntRemoveL' _ cntj)) as cnti.\n            erewrite  gRemLockSetCode with (cnti0 := cntRemoveL' _ cntj) in running.\n            rewrite gssThreadCode in running.\n            discriminate. }\n          { (*acquire lock*)\n            do 2 eexists; eauto.\n          }           \n        + generalize running; clear running.\n          inversion H; subst;\n          intros.\n          - exists (cntUpdate' _ _ cnt (cntUpdateL' _ _ cntj)), q.\n            rewrite <- running.\n            rewrite gLockSetCode.\n            eapply cntUpdateL'; eauto.\n            intros.\n            rewrite gsoThreadCode; eauto.\n            eapply cntUpdate'; eapply cntUpdateL'; eauto.\n            intros.\n            erewrite cnt_irr with (cnt1 := Hyp1).\n            reflexivity.\n          - exists (cntUpdate' _ _ cnt (cntUpdateL' _ _ cntj)), q.\n            rewrite <- running.\n            rewrite gLockSetCode.\n            eapply cntUpdateL'; eauto.\n            intros.\n            rewrite gsoThreadCode; eauto.\n            eapply cntUpdate'; eapply cntUpdateL'; eauto.\n            intros.\n            erewrite cnt_irr with (cnt1 := Hyp1).\n            reflexivity.\n          -  (*Add thread case*)\n            assert (cntj':=cntj).\n            eapply cntAdd' in cntj'; destruct cntj' as [ [HH HHH] | HH].\n            * pose proof (cntUpdate' _ _ _ HH) as cntj0.\n              exists cntj0, q.\n              rewrite <- running.\n              erewrite gsoAddCode with (cntj1 := HH).\n              rewrite gsoThreadCode;\n                now eauto.\n            * exfalso.\n              erewrite gssAddCode in running; eauto. discriminate.\n          - exists (cntUpdate' _ _ cnt (cntUpdateL' _ _ cntj)), q.\n            rewrite <- running.\n            rewrite gLockSetCode.\n            eapply cntUpdateL'; eauto.\n            intros.\n            rewrite gsoThreadCode; eauto.\n            eapply cntUpdate'; eapply cntUpdateL'; eauto.\n            intros.\n            erewrite cnt_irr with (cnt1 := Hyp1).\n            reflexivity.\n          -  exists (cntUpdate' _ _ cnt (cntRemoveL' _ cntj)), q.\n             rewrite <- running.\n             rewrite gRemLockSetCode.\n             eapply cntRemoveL'; eauto.\n             intros.\n             rewrite gsoThreadCode; eauto.\n             eapply cntUpdate'; eapply cntRemoveL'; eauto.\n             intros.\n             erewrite cnt_irr with (cnt1 := Hyp1).\n             reflexivity.\n          - do 2 eexists;\n              now eauto.\n            Grab Existential Variables.\n            apply cntUpdate;\n              now eauto.\n    Qed.\n\n    Lemma syncstep_not_running:\n      forall b i tp m cnt cmpt tp' m' tr,\n        @syncStep b i tp m cnt cmpt tp' m' tr ->\n        forall cntj q, ~ @getThreadC _ _ _ i tp cntj = Krun q.\n    Proof.\n      intros.\n      inversion H;\n        match goal with\n        | [ H: getThreadC ?cnt = _ |- _ ] =>\n          erewrite (cnt_irr _ _ _ cnt);\n            rewrite H; intros AA; inversion AA\n        end.\n    Qed.\n\n\n    Definition initial_machine pmap c := mkPool (Krun c) (pmap, empty_map).\n\n    Definition init_mach (pmap : option res) (m: mem)\n               (ms:thread_pool) (m' : mem) (v:val) (args:list val) : Prop :=\n      exists c, semantics.initial_core semSem 0 m c m' v args /\\\n           ms = mkPool (Krun c) (getCurPerm m', empty_map).\n    Set Printing All.\n\n\n\n\n\n    Definition install_perm tp m tid (Hcmpt: mem_compatible tp m) (Hcnt: containsThread tp tid) m' :=\n      m' = restrPermMap (Hcmpt tid Hcnt).1.\n\n    Definition add_block tp m tid (Hcmpt: mem_compatible tp m) (Hcnt: containsThread tp tid) m' :=\n      (getCurPerm m', (getThreadR Hcnt).2).\n\n    (** The signature of a Dry HybridMachine *)\n    (** This can be used to instantiate a Dry CoarseHybridMachine or a Dry\n    FineHybridMachine *)\n    \n    Instance DryHybridMachineSig: @HybridMachineSig.MachineSig dryResources Sem tpool :=\n      (@HybridMachineSig.Build_MachineSig dryResources Sem tpool\n                             richMem\n                             dryMem\n                             mem_compatible\n                             invariant\n                             install_perm\n                             add_block\n                             (@threadStep)\n                             threadStep_at_Krun\n                             threadStep_equal_run\n                             (@syncStep)\n                             syncstep_equal_run\n                             syncstep_not_running\n                             init_mach\n      ).\n\n    \n  End DryHybridMachine.\n\n  \n  \n  Section HybDryMachineLemmas.\n\n    (* Lemmas that don't need semantics/threadpool*)\n    \n      Lemma build_delta_content_restr: forall d m p Hlt,\n        build_delta_content d (@restrPermMap p m Hlt) = build_delta_content d m.\n      Proof.\n        reflexivity.\n      Qed.\n\n      (** Assume some threadwise semantics *)\n      Context {Sem: Semantics}\n            {tpool : @ThreadPool.ThreadPool dryResources Sem}.\n    \n      \n      (*TODO: This lemma should probably be moved. *)\n      Lemma threads_canonical:\n        forall ds m i (cnt:containsThread ds i),\n          mem_compatible ds m ->\n          isCanonical (getThreadR cnt).1 /\\\n          isCanonical (getThreadR cnt).2.\n        intros.\n        destruct (compat_th _ _ H cnt);\n          eauto using canonical_lt.\n      Qed.\n      (** most of these lemmas are in DryMachinLemmas*)\n\n      (** *Invariant Lemmas*)\n\n      (** ** Updating the machine state**)\n      (* Many invaraint lemmas were removed from here. *)\n      \n    \n    Notation thread_perms st i cnt:= (fst (@getThreadR _ _ _ st i cnt)).\n    Notation lock_perms st i cnt:= (snd (@getThreadR  _ _ _ st i cnt)).\n    Record thread_compat st i\n           (cnt:containsThread st i) m:=\n      { th_comp: permMapLt (thread_perms _ _ cnt) (getMaxPerm m);\n        lock_comp: permMapLt (lock_perms _ _ cnt) (getMaxPerm m)}.\n    Instance thread_compat_proper st i:\n        Proper (Logic.eq ==> Max_equiv ==> iff) (@thread_compat st i).\n      Proof. setoid_help.proper_iff;\n               setoid_help.proper_intros; subst.\n             constructor.\n             - eapply permMapLt_equiv.\n               reflexivity.\n               symmetry; apply H0.\n               eapply H1.\n             - eapply permMapLt_equiv.\n               reflexivity.\n               symmetry; apply H0.\n               eapply H1.\n      Qed.\n    Lemma mem_compatible_thread_compat:\n      forall (st1 : ThreadPool.t) (m1 : mem) (tid : nat)\n        (cnt1 : containsThread st1 tid),\n        mem_compatible st1 m1 -> thread_compat _ _ cnt1 m1.\n    Proof. intros * H; constructor; apply H. Qed.\n    Lemma mem_compat_Max:\n        forall Sem Tp st m m',\n          Max_equiv m m' ->\n          Mem.nextblock m = Mem.nextblock m' ->\n          @mem_compatible Sem Tp st m ->\n          @mem_compatible Sem Tp st m'.\n      Proof.\n        intros * Hmax Hnb H.\n        assert (Hmax':access_map_equiv (getMaxPerm m) (getMaxPerm m'))\n          by eapply Hmax.\n        constructor; intros;\n          repeat rewrite <- Hmax';\n          try eapply H; eauto.\n        unfold Mem.valid_block; rewrite <- Hnb;\n          eapply H; eauto.\n      Qed.\n\n  End HybDryMachineLemmas.\n    \nEnd DryHybridMachine.\n\nExport DryHybridMachine.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/concurrency/common/HybridMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22957436137001658}}
{"text": "Require Import RelationClasses.\nRequire Import Coq.Logic.PropExtensionality.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Global.\nRequire Import Local.\nRequire Import Thread.\n\nRequire Import Cover.\n\nRequire Import PFConsistent.\nRequire Import Certify.\nRequire Import Mapping.\n\nSet Implicit Arguments.\n\n\nDefinition is_cancel (e: ThreadEvent.t): Prop :=\n  match e with\n  | ThreadEvent.cancel _ _ _ => True\n  | _ => False\n  end.\n\n\nModule CurrentCertify.\nSection CurrentCertify.\n  Variable (lang: language).\n\n  Variant canceled_reserves (dom: list (Loc.t * Time.t)) (rsv rsvc: Memory.t): Prop :=\n    | canceled_reserves_intro\n        (SOUND: Memory.le rsvc rsv)\n        (COMPLETE: forall loc from to msg\n                          (GET: Memory.get loc to rsvc = Some (from, msg)),\n            List.In (loc, to) dom)\n  .\n\n  Variant canceled_local (dom: list (Loc.t * Time.t)) (lc lcc: Local.t): Prop :=\n    | canceled_local_intro\n        (TVIEW: lcc.(Local.tview) = lc.(Local.tview))\n        (PROMISES: lcc.(Local.promises) = lc.(Local.promises))\n        (RESERVES: canceled_reserves dom lc.(Local.reserves) lcc.(Local.reserves))\n  .\n\n  Variant canceled_memory (rsv rsvc mem memc: Memory.t): Prop :=\n    | canceled_memory_intro\n        (SOUND: Memory.le memc mem)\n        (COMPLETE: Memory.messages_le mem memc)\n        (RESERVES: forall loc from to msg\n                          (GET: Memory.get loc to rsv = Some (from, msg))\n                          (GETC: Memory.get loc to rsvc = None),\n            Memory.get loc to memc = None)\n  .\n\n  Variant canceled_thread (dom: list (Loc.t * Time.t)) (th thc: Thread.t lang): Prop :=\n    | canceled_thread_intro\n        (STATE: thc.(Thread.state) = th.(Thread.state))\n        (LOCAL: canceled_local dom th.(Thread.local) thc.(Thread.local))\n        (SC: th.(Thread.global).(Global.sc) = thc.(Thread.global).(Global.sc))\n        (GPROMISES: th.(Thread.global).(Global.promises) = thc.(Thread.global).(Global.promises))\n        (MEMORY: canceled_memory th.(Thread.local).(Local.reserves)\n                                 thc.(Thread.local).(Local.reserves)\n                                 th.(Thread.global).(Global.memory)\n                                 thc.(Thread.global).(Global.memory))\n  .\n\n  Lemma canceled_thread_refl\n        (th: Thread.t lang)\n        (LC_WF: Local.wf th.(Thread.local) th.(Thread.global)):\n    exists dom,\n      canceled_thread dom th th.\n  Proof.\n    inv LC_WF. inv RESERVES_FINITE.\n    exists x. econs; ss.\n    { econs; ss. econs; ss. }\n    { econs; ss. i. congr. }\n  Qed.\n\n  Lemma canceled_thread_step\n        loc to dom\n        th thc1\n        (CANCELED1: canceled_thread ((loc, to)::dom) th thc1)\n        (LC_WF: Local.wf thc1.(Thread.local) thc1.(Thread.global)):\n    (<<CANCELED2: canceled_thread dom th thc1>>) \\/\n    exists from thc2,\n      (<<CANCEL: Thread.step (ThreadEvent.cancel loc from to) thc1 thc2>>) /\\\n      (<<CANCELED2: canceled_thread dom th thc2>>).\n  Proof.\n    destruct th as [st [tview prm rsv] [sc gprm mem]].\n    destruct thc1 as [stc1 [tviewc1 prmc1 rsvc1] [scc1 gprmc1 memc1]].\n    inv CANCELED1. inv LOCAL. ss. subst.\n    destruct (Memory.get loc to rsvc1) as [[from msg]|] eqn:X; cycle 1.\n    { left. econs; ss. econs; ss.\n      inv RESERVES. econs; ss. i.\n      exploit COMPLETE; eauto. i. des; ss.\n      inv x0. congr.\n    }\n    right. inv LC_WF. ss.\n    exploit RESERVES_ONLY; eauto. i. subst.\n    exploit Memory.remove_exists; try exact X. i. des.\n    exploit Memory.remove_exists_le; try exact x0; eauto. i. des.\n    hexploit Memory.remove_le; try exact x0. i.\n    hexploit Memory.remove_le; try exact x1. i.\n    esplits.\n    { econs. econs. econs; eauto. }\n    { econs; ss.\n      { econs; ss.\n        inv RESERVES. econs; [etrans; eauto|]. i.\n        revert GET. erewrite Memory.remove_o; eauto. condtac; ss. i.\n        exploit COMPLETE; eauto. i. des; ss; congr.\n      }\n      { inv MEMORY. econs; ss.\n        { etrans; eauto. }\n        { ii. erewrite Memory.remove_o; eauto.\n          condtac; ss; eauto. des. subst.\n          exploit Memory.remove_get0; try exact x1. i. des.\n          exploit SOUND; eauto. i. congr.\n        }\n        { i. revert GETC.\n          erewrite Memory.remove_o; eauto. condtac; ss; i.\n          { des. subst.\n            exploit Memory.remove_get0; try exact x1. i. des. ss.\n          }\n          { guardH o.\n            exploit RESERVES1; eauto. i.\n            erewrite Memory.remove_o; eauto. condtac; ss.\n          }\n        }\n      }\n    }\n  Qed.\n\n  Lemma canceled_thread_steps\n        dom\n        th thc1\n        (CANCELED1: canceled_thread dom th thc1)\n        (LC_WF: Local.wf thc1.(Thread.local) thc1.(Thread.global))\n        (GL_WF: Global.wf thc1.(Thread.global)):\n    exists thc2,\n      (<<CANCEL: rtc (pstep (@Thread.step _) is_cancel) thc1 thc2>>) /\\\n      (<<CANCELED2: canceled_thread [] th thc2>>).\n  Proof.\n    revert th thc1 CANCELED1 LC_WF GL_WF.\n    induction dom; i; eauto.\n    destruct a as [loc to].\n    exploit canceled_thread_step; eauto. i. des; eauto.\n    exploit Thread.step_future; eauto. i. des.\n    exploit IHdom; eauto. i. des.\n    esplits; try exact CANCELED0.\n    econs 2; eauto. econs; eauto. ss.\n  Qed.\n\n  Lemma cancel_reserves\n        th\n        (LC_WF: Local.wf th.(Thread.local) th.(Thread.global))\n        (GL_WF: Global.wf th.(Thread.global)):\n    exists thc,\n      (<<CANCEL: rtc (pstep (@Thread.step _) is_cancel) th thc>>) /\\\n      (<<CANCELED: canceled_thread [] th thc>>).\n  Proof.\n    exploit canceled_thread_refl; eauto. i. des.\n    exploit canceled_thread_steps; eauto.\n  Qed.\n\n  Lemma canceled_map\n        (th thc: Thread.t lang)\n        (CANCELED: canceled_thread [] th thc)\n        (LC_WF: Local.wf th.(Thread.local) th.(Thread.global))\n        (GL_WF: Global.wf th.(Thread.global)):\n    exists f,\n      (<<F: f = fun loc ts fts =>\n                  ts = fts /\\\n                  exists from to msg,\n                    Memory.get loc to th.(Thread.global).(Global.memory) = Some (from, msg) /\\\n                    __guard__ (ts = from \\/ ts = to)>>) /\\\n      (<<MAP_WF: map_wf f>>) /\\\n      (<<MAP: thread_map_racy_promise f (Thread.cap_of th) thc>>).\n  Proof.\n    destruct th as [st [tview prm rsv] [sc gprm mem]].\n    destruct thc as [stc [tviewc prmc rsvc] [scc gprmc memc]].\n    inv CANCELED. inv LOCAL. ss. subst.\n    esplits; try refl.\n    { (* map_wf *)\n      econs; ii; subst.\n      { esplits; ss; try apply GL_WF. left. ss. }\n      { exists (List.concat\n                  (List.map (fun e => [fst e; fst (snd e)]) (DOMap.elements (Cell.raw (mem loc))))).\n        i. des. subst.\n        exploit DOMap.elements_correct; eauto. i.\n        remember (DOMap.elements (Cell.raw (mem loc))) as l.\n        clear - l x0 MAP1.\n        revert fts from to msg MAP1 x0.\n        induction l; ss; i. des; eauto.\n        subst. ss. unguard. des; auto.\n      }\n      { des. subst. ss. }\n      { des. subst. ss. }\n      { des. subst. ss. }\n      { des. subst. ss. }\n    }\n\n    (* thread_map *)\n    econs; ss.\n    { (* local_map *)\n      econs. eapply closed_tview_map; try apply LC_WF. s. i.\n      esplits; eauto. right. ss.\n    }\n    { (* global_map *)\n      specialize (@Memory.cap_of_cap mem). intro CAP.\n      hexploit Memory.cap_le; eauto. intro LE.\n      inv RESERVES. inv MEMORY.\n      econs. econs; ss; i.\n      { destruct msg; auto. right.\n        exploit Memory.cap_inv; eauto. i. des; ss.\n        exploit COMPLETE0; eauto. i.\n        esplits; unguard; eauto.\n        inv GL_WF. inv MEM_CLOSED.\n        exploit CLOSED; eauto. s. i. des. inv MSG_CLOSED.\n        econs. eapply closed_opt_view_map; eauto. i.\n        esplits; eauto.\n      }\n      { exploit SOUND0; eauto. i.\n        esplits; eauto; (try refl); unguard; auto; i.\n        { inv CAP. exploit SOUND1; eauto. i.\n          econs; eauto.\n        }\n        { inv LC_WF. ss.\n          exploit RESERVES0; eauto. i.\n          exploit Memory.get_disjoint; [exact x1|exact x0|]. i. des; ss. subst.\n          exploit RESERVES; eauto; try congr.\n          destruct (Memory.get loc fto rsvc) as [[]|] eqn:X; ss.\n          exploit COMPLETE; eauto. ss.\n        }\n      }\n    }\n  Qed.\n\n  Lemma canceled_certify_racy_promise\n        th thc loc\n        (CANCELED: canceled_thread [] th thc)\n        (LC_WF: Local.wf th.(Thread.local) th.(Thread.global))\n        (GL_WF: Global.wf th.(Thread.global))\n        (LC_WF_C: Local.wf thc.(Thread.local) thc.(Thread.global))\n        (GL_WF_C: Global.wf thc.(Thread.global))\n        (CERTIFY: certify_racy_promise loc (Thread.cap_of th)):\n    @pf_certify_racy_promise lang loc thc.\n  Proof.\n    exploit Local.cap_wf; try exact CAP; try exact LC_WF. intro LC_WF_CAP.\n    exploit Global.cap_wf; try exact GL_WF. intro GL_WF_CAP.\n    exploit canceled_map; eauto. i. des.\n    eapply map_certify_racy_promise; try exact CERTIFY; eauto.\n  Qed.\n\n  Lemma current_certify_racy_promise\n        th loc\n        (LC_WF: Local.wf th.(Thread.local) th.(Thread.global))\n        (GL_WF: Global.wf th.(Thread.global))\n        (CERTIFY: certify_racy_promise loc (Thread.cap_of th)):\n    @certify_racy_promise lang loc th.\n  Proof.\n    exploit cancel_reserves; eauto. i. des.\n    exploit Thread.rtc_all_step_future;\n      try eapply rtc_implies; try exact CANCEL; eauto.\n    { i. inv H. econs. eauto. }\n    i. des.\n    exploit canceled_certify_racy_promise; eauto. i.\n    inv x0.\n    - econs 1; try exact STEP_FAILURE; eauto.\n      etrans.\n      + eapply rtc_implies; try exact CANCEL.\n        i. inv H. econs; eauto. destruct e0; ss. auto.\n      + eapply rtc_implies; try exact STEPS.\n        i. inv H. des. econs; eauto. split; ss.\n        destruct e0; ss.\n    - econs 2; try exact STEP_FULFILL; eauto.\n      etrans.\n      + eapply rtc_implies; try exact CANCEL.\n        i. inv H. econs; eauto. destruct e; ss. auto.\n      + eapply rtc_implies; try exact STEPS.\n        i. inv H. des. econs; eauto. split; ss.\n        destruct e; ss.\n  Qed.\n\n  Lemma promise_step_sim_thread\n        th1 th2 loc\n        (STEP: @Thread.step lang (ThreadEvent.promise loc) th1 th2):\n    PFConsistent.sim_thread th1 th2.\n  Proof.\n    exploit Thread.step_promises_minus; eauto. i.\n    inv STEP; inv LOCAL. inv LOCAL0. inv PROMISE; ss.\n    econs; ss; try apply PFConsistent.sim_memory_PreOrder.\n    eapply BoolMap.add_le; eauto.\n  Qed.\n\n  Lemma rtc_step_consistent_ceritfy_racy_promise\n        th0 th1 th2 loc\n        (LC_WF: Local.wf th0.(Thread.local) th0.(Thread.global))\n        (GL_WF: Global.wf th0.(Thread.global))\n        (STEP: Thread.step (ThreadEvent.promise loc) th0 th1)\n        (STEPS: rtc (@Thread.all_step lang) th1 th2)\n        (CONSISTENT: Thread.consistent th2):\n    certify_racy_promise loc th0.\n  Proof.\n    cut (certify_racy_promise loc th1).\n    { exploit promise_step_sim_thread; eauto. i. inv H.\n      { exploit PFConsistent.sim_thread_rtc_non_sc_step;\n          try eapply rtc_implies; try exact STEPS0; eauto.\n        { i. inv H. des. econs; eauto. }\n        i. des.\n        exploit Thread.rtc_all_step_future;\n          try eapply rtc_implies; try exact STEPS_SRC; eauto.\n        { i. inv H. econs; eauto. }\n        i. des.\n        exploit PFConsistent.sim_thread_step; try exact STEP_FAILURE; eauto. i. des.\n        unguard. des; subst; try by (destruct e; ss).\n        inv STEP_SRC; ss.\n        econs 1; eauto.\n      }\n      { exploit PFConsistent.sim_thread_rtc_non_sc_step;\n          try eapply rtc_implies; try exact STEPS0; eauto.\n        { i. inv H. des. econs; eauto. }\n        i. des.\n        exploit Thread.rtc_all_step_future;\n          try eapply rtc_implies; try exact STEPS_SRC; eauto.\n        { i. inv H. econs; eauto. }\n        i. des.\n        exploit PFConsistent.sim_thread_step; try exact STEP_FAILURE; eauto. i. des.\n        unguard. des; subst; ss.\n        inv STEP_SRC; ss.\n        econs 2; eauto.\n        eapply TimeFacts.le_lt_lt; eauto.\n        eapply Memory.le_max_ts; try apply GL_WF2. apply SIM2.\n      }\n    }\n\n    assert (PROMISED: th1.(Thread.local).(Local.promises) loc = true).\n    { inv STEP; inv LOCAL. inv LOCAL0. inv PROMISE.\n      exploit BoolMap.add_get0; try exact ADD. i. des. ss.\n    }\n    exploit Thread.step_future; eauto. i. des.\n    clear th0 LC_WF GL_WF STEP TVIEW_FUTURE GL_FUTURE.\n    exploit PFConsistent.rtc_all_step_rtc_non_sc_step; eauto. i. des; cycle 1.\n    { (* failure during rtc step *)\n      exploit PFConsistent.sim_thread_rtc_non_sc_step; try exact STEPS1; eauto.\n      { apply PFConsistent.sim_thread_PreOrder. }\n      i. des.\n      exploit Thread.rtc_all_step_future;\n        try eapply rtc_implies; try exact STEPS_SRC; eauto.\n      { i. inv H. econs. eauto. }\n      i. des.\n      exploit PFConsistent.sim_thread_step; try exact STEP_FAILURE; eauto. i. des.\n      unguard. des; subst; cycle 1.\n      { destruct e; ss. }\n      inv STEP_SRC; ss.\n      econs 1; try exact STEP; eauto.\n    }\n    { (* sc during rtc step *)\n      exploit PFConsistent.sim_thread_rtc_non_sc_step; try exact STEPS1; eauto.\n      { apply PFConsistent.sim_thread_PreOrder. }\n      i. des.\n      exploit rtc_pf_step_certify_racy_promise; try exact STEPS_SRC; eauto.\n      destruct (th2_src.(Thread.local).(Local.promises) loc) eqn:GETP; ss.\n      inv SIM2. exploit PROMISES0; eauto.\n      rewrite PROMISES. ss.\n    }\n    subst.\n    destruct (th2.(Thread.local).(Local.promises) loc) eqn:PROMISED2; cycle 1.\n    { (* fulfilled during rtc step *)\n      exploit PFConsistent.sim_thread_rtc_non_sc_step; try exact STEPS1; eauto.\n      { apply PFConsistent.sim_thread_PreOrder. }\n      i. des.\n      exploit rtc_pf_step_certify_racy_promise; try exact STEPS_SRC; eauto.\n      destruct (th2_src.(Thread.local).(Local.promises) loc) eqn:GETP; ss.\n      inv SIM2. exploit PROMISES; eauto.\n    }\n    (* fulfilled during certification *)\n    exploit Thread.rtc_all_step_future; try exact STEPS; eauto. i. des.\n    exploit PFConsistent.consistent_pf_consistent; eauto. i.\n    exploit pf_consistent_certify_racy_promise; eauto. i.\n    exploit current_certify_racy_promise; try exact x1; eauto. i.\n    move STEPS1 at bottom. inv x2.\n    { exploit PFConsistent.sim_thread_rtc_non_sc_step;\n        try exact LC_WF2; try exact GL_WF2; try apply PFConsistent.sim_thread_PreOrder.\n      { etrans; [exact STEPS1|].\n        eapply rtc_implies; try exact STEPS0.\n        i. inv H. des. econs; eauto.\n      }\n      i. des.\n      exploit Thread.rtc_all_step_future;\n        try eapply rtc_implies; try exact STEPS_SRC; ss.\n      { i. inv H. econs. eauto. }\n      i. des.\n      exploit PFConsistent.sim_thread_step; try exact SIM2; eauto. i. des.\n      unguard. des; subst; try by (destruct e; ss).\n      inv STEP_SRC; ss.\n      econs 1; eauto.\n    }\n    { exploit PFConsistent.sim_thread_rtc_non_sc_step;\n        try exact LC_WF2; try exact GL_WF2; try apply PFConsistent.sim_thread_PreOrder.\n      { etrans; [exact STEPS1|].\n        eapply rtc_implies; try exact STEPS0.\n        i. inv H. des. econs; eauto.\n      }\n      i. des.\n      exploit Thread.rtc_all_step_future;\n        try eapply rtc_implies; try exact STEPS_SRC; ss.\n      { i. inv H. econs. eauto. }\n      i. des.\n      exploit PFConsistent.sim_thread_step; try exact SIM2; eauto. i. des.\n      unguard. des; subst; ss.\n      inv STEP_SRC; ss.\n      econs 2; eauto.\n      eapply TimeFacts.le_lt_lt; eauto.\n      inv SIM2. inv MEMORY.\n      eapply Memory.le_max_ts; try apply GL_WF1. apply SOUND.\n    }\n  Qed.\nEnd CurrentCertify.\nEnd CurrentCertify.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/prop/CurrentCertify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177488, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2295743558477295}}
{"text": "From hahn Require Import Hahn.\nRequire Import Logic.IndefiniteDescription.\nFrom Promising Require Import Configuration TView View Time Event Cell Thread Memory.\nRequire Import PromisingLib.\nRequire Import MaxValue.\nRequire Import MemoryAux.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\n(* Proposition \"up_memory memory memory'\" states that each message in memory' has\n   a counterpart in memory w/ smaller or equal left timestamp border. *)\nRecord up_memory memory memory' :=\n  { TOU :\n      forall loc t val f' view'\n             (INT : Memory.get loc t memory' =\n                    Some (f', Message.mk val view')),\n      exists f view,\n        ⟪ INF : Memory.get loc t memory =\n                 Some (f, Message.mk val view) ⟫ /\\\n        ⟪ FFT : Time.le f' f ⟫ /\\\n        ⟪ VVT : View.opt_le view view' ⟫ ;\n    TOUIN :\n      forall loc t' val' f' view' m\n             (IMU : Interval.mem (f', t') m)\n             (INT : Memory.get loc t' memory' =\n                    Some (f', Message.mk val' view')),\n      exists t f val view,\n        ⟪ INF : Memory.get loc t memory =\n                 Some (f, Message.mk val view) ⟫ /\\\n        ⟪ IMP : Interval.mem (f, t) m ⟫ ;\n    FROMU :\n      forall loc t val f view\n             (INT : Memory.get loc t memory =\n                    Some (f, Message.mk val view)),\n      exists f' t' val' view',\n        ⟪ INT : Memory.get loc t' memory' =\n                 Some (f', Message.mk val' view') ⟫ /\\\n        ⟪ ILE : Interval.le (f, t) (f', t') ⟫;\n  }.\n\nLemma up_memory_refl memory :\n  up_memory memory memory.\nProof using.\n  constructor; ins.\n  { eexists. eexists. splits; eauto.\n    all: reflexivity. }\n  { repeat eexists; eauto.\n    all: apply IMU. }\n  repeat eexists; eauto.\n  all: reflexivity.\nQed.\n\nLemma exists_all_conj_disj (A B : Type) (P Q R : A -> B -> Prop)\n      (HH : exists f, forall a : A, P a f /\\ Q a f /\\ R a f) :\n  exists f, (forall a : A, P a f) /\\ (forall a : A, Q a f) /\\\n            (forall a : A, R a f).\nProof using. desf. exists f. splits; apply HH. Qed.\n\nLemma up_memory_closed_bigger_timemap memory memory' tmap\n      (FUTURE  : Memory.future Memory.init memory)\n      (INHAB   : Memory.inhabited memory')\n      (TM_CLOS : Memory.closed_timemap tmap memory)\n      (UP_MEM  : up_memory memory memory') :\n  exists tmap',\n    ⟪ TM_LE  : TimeMap.le tmap tmap' ⟫ /\\\n    ⟪ TM_CLOS : Memory.closed_timemap tmap' memory' ⟫ /\\\n    ⟪ TM_EQ :\n      forall loc to from val view view'\n             (TS_LT'     : ts_lt_or_bot memory')\n             (MSG_DISJ   : message_disjoint memory')\n             (GET  : Memory.get loc to memory =\n                     Some (from, Message.mk val view))\n             (GET' : Memory.get loc to memory' =\n                     Some (from, Message.mk val view'))\n             (TLE  : Time.le (tmap loc) to),\n        Time.le (tmap' loc) to ⟫.\nProof using.\n  unnw.\n  unfold TimeMap.le.\n  unfold Memory.closed_timemap.\n  unfold TimeMap.t.\n  apply exists_all_conj_disj.\n\n  set (R := fun a b =>\n    Time.le (tmap a) b /\\\n    (exists (from : Time.t) (val : Const.t) (released : option View.t),\n       Memory.get a b memory' =\n       Some (from, {| Message.val := val; Message.released := released |})) /\\\n    (forall to from val view view',\n        ts_lt_or_bot memory' ->\n        message_disjoint memory' ->\n        Memory.get a to memory =\n          Some (from, Message.mk val view) ->\n        Memory.get a to memory' =\n          Some (from, Message.mk val view') ->\n        Time.le (tmap a) to ->\n        Time.le b to)).\n  apply functional_choice with (R:=R).\n  unfold R. clear R.\n  intros l.\n  specialize (TM_CLOS l). desf.\n  \n  set (GET := TM_CLOS).\n  apply ts_lt_or_bot_future_init in GET; auto.\n  desf.\n  { eexists. splits; auto.\n    { reflexivity. }\n    2: by ins.\n    rewrite GET in *. repeat eexists.\n    apply INHAB. }\n  assert (tmap l <> Time.bot) as XX.\n  { intros HH. rewrite HH in *.\n    eapply MaxValue.time_lt_bot. eauto. }\n  set (TM_CLOS' := TM_CLOS).\n  eapply UP_MEM in TM_CLOS'.\n  desf.\n  eexists. splits; eauto.\n  { apply ILE. }\n  ins.\n  destruct (Time.le_lt_dec t' to) as [|LT]; auto.\n  exfalso.\n  \n  set (CC := H2).\n  eapply H in CC.\n  desf.\n  { apply Time.le_lteq in H3.\n    desf. eapply MaxValue.time_lt_bot; eauto. }\n  eapply H0 in H2. apply H2 in INT.\n  destruct INT as [AA|AA].\n  { subst. eapply Time.lt_strorder. eauto. }\n  eapply AA; constructor; simpls.\n  2: reflexivity.\n  { done. }\n  2: { apply Time.le_lteq. by left. }\n  eapply TimeFacts.lt_le_lt; eauto.\n  eapply TimeFacts.le_lt_lt.\n  { apply ILE. }\n  simpls.\nQed.\n\nLemma up_memory_closed_bigger_view memory memory' view\n      (FUTURE  : Memory.future Memory.init memory)\n      (INHAB   : Memory.inhabited memory')\n      (VW_CLOS : Memory.closed_opt_view view memory)\n      (VW_WF : View.opt_wf view)\n      (UP_MEM : up_memory memory memory') :\n  exists view',\n    ⟪ VW_LE  : View.opt_le view view' ⟫ /\\\n    ⟪ VW_CLOS : Memory.closed_opt_view view' memory' ⟫ /\\\n    ⟪ VW_WF : View.opt_wf view' ⟫ /\\\n    ⟪ VW_EQ :\n      forall loc to from val released released'\n             (TS_LT'     : ts_lt_or_bot memory')\n             (MSG_DISJ   : message_disjoint memory')\n             (GET  : Memory.get loc to memory =\n                     Some (from, Message.mk val released))\n             (GET' : Memory.get loc to memory' =\n                     Some (from, Message.mk val released'))\n             (TLE  : Time.le (View.rlx (View.unwrap view) loc) to),\n        Time.le (View.rlx (View.unwrap view') loc) to ⟫.\nProof using.\n  destruct view as [view|].\n  2: { exists None. splits; auto.\n       { reflexivity. }\n       constructor. }\n  destruct view as [tmap_pln tmap].\n  edestruct up_memory_closed_bigger_timemap with\n      (memory:=memory) (memory':=memory') as [tmap']; eauto.\n  { inv VW_CLOS. destruct CLOSED. apply RLX. }\n  desc.\n  exists (Some (View.mk tmap' tmap')).\n  splits; auto.\n  { constructor. constructor; simpls.\n    etransitivity; eauto.\n    inv VW_WF. inv WF. }\n  { constructor. constructor; simpls. }\n  constructor. constructor.\n  reflexivity.\nQed.\n\nLemma up_memory_add_exists_r_view_eq memory memory' memory_add\n           loc from to val released released'\n           (ADD      : Memory.add memory loc from to val released memory_add)\n           (VW_WF    : View.opt_wf released')\n           (LE       : View.opt_le released released')\n           (UP_MEM   : up_memory memory memory') :\n  exists memory_add',\n    ⟪ ADDU       : Memory.add memory' loc from to val released' memory_add' ⟫ /\\\n    ⟪ UP_MEM_ADD : up_memory memory_add memory_add' ⟫.\nProof using.\n  assert (ADD':=ADD).\n  destruct ADD'. destruct ADD0.\n  edestruct Memory.add_exists with (mem1:=memory') (released:=released')\n    as [memory_add' MM]; eauto.\n  { ins. destruct msg2 as [v rel].\n    red. ins.\n    eapply UP_MEM in RHS; eauto. desc.\n    eapply DISJOINT; eauto. }\n  exists memory_add'. splits; eauto.\n  constructor; ins.\n  { erewrite Memory.add_o; eauto.\n    erewrite Memory.add_o in INT; eauto.\n    destruct (loc_ts_eq_dec (loc0, t) (loc, to)) as [[AA BB]|AA]; simpls.\n    2: by apply UP_MEM.\n    desf. repeat eexists; unnw; auto.\n    reflexivity. }\n  { erewrite Memory.add_o in INT; eauto.\n    desf.\n    { simpls. desf.\n      repeat eexists.\n      2,3: by apply IMU.\n      erewrite Memory.add_o; eauto.\n      rewrite loc_ts_eq_dec_eq; eauto. }\n    eapply UP_MEM in IMU; eauto.\n    desc.\n    repeat eexists.\n    2,3: by apply IMP.\n    eapply Memory.add_get1; eauto. }\n  erewrite Memory.add_o in INT; eauto.\n  destruct (loc_ts_eq_dec (loc0, t) (loc, to)) as [[AA BB]|AA]; simpls.\n  { desf. repeat eexists; eauto.\n    2,3: reflexivity.\n    erewrite Memory.add_o; eauto.\n    rewrite loc_ts_eq_dec_eq. eauto. }\n  apply UP_MEM in INT. desc.\n  destruct ILE.\n  repeat eexists; eauto.\n  eapply Memory.add_get1; eauto.\nQed.\n\nLemma up_memory_add_bigger_view memory_add memory' memory_add''\n           loc from to val released released'\n           (VW_LE : View.opt_le released released')\n           (VW_WF : View.opt_wf released')\n           (ADDU : Memory.add memory' loc from to val released memory_add'')\n           (UP_MEM_ADD : up_memory memory_add memory_add'') :\n  exists memory_add',\n    ⟪ ADDU : Memory.add memory' loc from to val released' memory_add' ⟫ /\\\n    ⟪ UP_MEM_ADD : up_memory memory_add memory_add' ⟫.\nProof using.\n  inv ADDU. inv ADD.\n  edestruct Memory.add_exists with (released:=released')\n    as [memory_add' ADD']; eauto.\n  eexists. splits; eauto.\n  constructor; ins.\n  { assert (exists view'',\n               ⟪ VLE : View.opt_le view'' view' ⟫ /\\\n               ⟪ INT' :\n                 Memory.get loc0 t (LocFun.add loc r memory') =\n                 Some (f', Message.mk val0 view'') ⟫) as [view''].\n    { erewrite Memory.add_o in INT; eauto.\n      desf.\n      { simpls; desf.\n        eexists. splits; eauto.\n        erewrite Memory.add_o; eauto.\n          by rewrite loc_ts_eq_dec_eq. }\n      erewrite Memory.add_o; eauto.\n      rewrite loc_ts_eq_dec_neq; auto.\n      eexists. splits; [|by eauto].\n      reflexivity. }\n    desc.\n    eapply (TOU UP_MEM_ADD) in INT'.\n    desc. eexists. eexists.\n    splits; eauto. etransitivity; eauto. }\n  { assert (exists view'',\n               ⟪ VLE : View.opt_le view'' view' ⟫ /\\\n               ⟪ INT' :\n                 Memory.get loc0 t' (LocFun.add loc r memory') =\n                 Some (f', Message.mk val' view'') ⟫) as [view''].\n    { erewrite Memory.add_o in INT; eauto.\n      desf.\n      { simpls; desf.\n        eexists. splits; eauto.\n        erewrite Memory.add_o; eauto.\n          by rewrite loc_ts_eq_dec_eq. }\n      erewrite Memory.add_o; eauto.\n      rewrite loc_ts_eq_dec_neq; auto.\n      eexists. splits; [|by eauto].\n      reflexivity. }\n    desc.\n    eapply (TOUIN UP_MEM_ADD) in INT'; eauto. }\n  eapply (FROMU UP_MEM_ADD) in INT; eauto.\n  desc.\n  erewrite Memory.add_o in INT0; eauto.\n  desf.\n  { simpls; desf. repeat eexists.\n    2,3: by apply ILE.\n    erewrite Memory.add_o; eauto.\n    rewrite loc_ts_eq_dec_eq. by unnw. }\n  repeat eexists.\n  2,3: by apply ILE.\n  erewrite Memory.add_o; eauto.\n  rewrite loc_ts_eq_dec_neq; auto. eauto.\nQed.\n\nLemma up_memory_add_exists_r memory memory' memory_add\n           loc from to val released\n           (FUTURE  : Memory.future Memory.init memory)\n           (FUTURE' : Memory.future Memory.init memory')\n           (FUTURE_ADD : Memory.future memory memory_add)\n           (VW_CLOS : Memory.closed_opt_view released memory_add)\n           (ULE : Time.le (View.rlx (View.unwrap released) loc) to)\n           (ADD : Memory.add memory loc from to val released memory_add)\n           (UP_MEM: up_memory memory memory') :\n  exists released' memory_add',\n    ⟪ LE : View.opt_le released released' ⟫ /\\\n    ⟪ VW_WF : View.opt_wf released' ⟫ /\\\n    ⟪ ADDU : Memory.add memory' loc from to val released' memory_add' ⟫ /\\\n    ⟪ FUTURE : Memory.future Memory.init memory_add' ⟫ /\\\n    ⟪ UP_MEM_ADD : up_memory memory_add memory_add' ⟫.\nProof using.\n  assert (View.opt_wf released) as VW_WF.\n  { inv ADD. inv ADD0. }\n  edestruct up_memory_add_exists_r_view_eq as [memory_add'']; eauto.\n  { reflexivity. }\n  desc.\n  edestruct up_memory_closed_bigger_view with\n      (memory:=memory_add) (memory':=memory_add'') as [released']; eauto.\n  { etransitivity; [|by eauto].\n    done. }\n  { eapply Memory.add_inhabited; eauto.\n      by apply inhabited_future_init. }\n  desc.\n  edestruct up_memory_add_bigger_view as [memory_add']; eauto.\n  desc.\n  eexists. eexists. splits; eauto.\n  etransitivity; eauto.\n  apply clos_rt1n_step.\n\n  assert (Time.le (View.rlx (View.unwrap released') loc) to) as TT.\n  { eapply VW_EQ; eauto.\n    { eapply ts_lt_or_bot_add; [|by eauto].\n        by apply ts_lt_or_bot_future_init. }\n    { eapply message_disjoint_add; eauto.\n        by apply message_disjoint_future_init. }\n    all: erewrite Memory.add_o; eauto.\n    all: by rewrite loc_ts_eq_dec_eq. }\n\n  econstructor.\n  { apply Memory.op_add. eauto. }\n  2: done.\n  eapply Memory.add_closed with (mem1:=memory') (released:=released'); eauto.\n  { eapply Memory.future_closed; eauto.\n    apply Memory.init_closed. }\n  2: { erewrite Memory.add_o; eauto.\n         by rewrite loc_ts_eq_dec_eq. }\n  destruct released'; constructor.\n  inv VW_CLOS0.\n  destruct CLOSED as [AA BB].\n  red in AA. red in BB.\n  clear -AA BB ADDU ADDU0.\n  constructor.\n  all: red; intros loc'.\n  all:  specialize (AA loc'); specialize (BB loc').\n  all: desc.\n  all: erewrite Memory.add_o; eauto.\n  all: erewrite Memory.add_o in AA; [|by eauto].\n  all: erewrite Memory.add_o in BB; [|by eauto].\n  all: desf; eauto.\nQed.\n\nLemma up_memory_add_exists_l memory memory' memory_add'\n           loc from to val released released'\n           (ADD : Memory.add memory' loc from to val released' memory_add')\n           (MSG_DISJ : message_disjoint memory)\n           (TS_LT    : ts_lt_or_bot memory)\n           (INHAB'   : Memory.inhabited memory')\n           (LE : View.opt_le released released')\n           (VWF : View.opt_wf released)\n           (UP_MEM: up_memory memory memory') :\n  exists memory_add,\n    ⟪ ADDU : Memory.add memory loc from to val released memory_add ⟫ /\\\n    ⟪ UP_MEM_ADD : up_memory memory_add memory_add' ⟫ /\\\n    ⟪ MSG_DISJ : message_disjoint memory_add ⟫ /\\\n    ⟪ TS_LT    : ts_lt_or_bot memory_add ⟫ /\\\n    ⟪ INHAB'   : Memory.inhabited memory_add' ⟫.\nProof using.\n  assert (ADD':=ADD).\n  destruct ADD'. destruct ADD0.\n  edestruct Memory.add_exists with (mem1:=memory) (released:=released)\n    as [memory_add MM]; eauto.\n  { ins. destruct msg2 as [v rel].\n    apply (FROMU UP_MEM) in GET2.\n    desc. apply DISJOINT in INT.\n    symmetry.\n    eapply Interval.le_disjoint; eauto.\n    by symmetry. }\n  exists memory_add; splits; eauto.\n  4: by eapply Memory.add_inhabited; eauto.\n  3: by eapply ts_lt_or_bot_add; eauto.\n  2: by eapply message_disjoint_add; eauto.\n  constructor; ins.\n  { erewrite Memory.add_o; eauto.\n    erewrite Memory.add_o in INT; eauto.\n    destruct (loc_ts_eq_dec (loc0, t) (loc, to)) as [[AA BB]|AA]; simpls.\n    2: by apply UP_MEM.\n    desf. repeat eexists; unnw; auto.\n    reflexivity. }\n  { erewrite Memory.add_o in INT; eauto.\n    desf.\n    { simpls. desf.\n      repeat eexists.\n      2,3: by apply IMU.\n      erewrite Memory.add_o; eauto.\n      rewrite loc_ts_eq_dec_eq; eauto. }\n    eapply UP_MEM in IMU; eauto. desc.\n    repeat eexists.\n    2,3: by apply IMP.\n    eapply Memory.add_get1; eauto. }\n  erewrite Memory.add_o in INT; eauto.\n  destruct (loc_ts_eq_dec (loc0, t) (loc, to)) as [[AA BB]|AA]; simpls.\n  { desf. repeat eexists; eauto.\n    2,3: reflexivity.\n    erewrite Memory.add_o; eauto.\n    rewrite loc_ts_eq_dec_eq. eauto. }\n  apply UP_MEM in INT. desc.\n  destruct ILE.\n  repeat eexists; eauto.\n  eapply Memory.add_get1; eauto.\nQed.\n\nLemma up_memory_add_exists_l_view_eq memory memory' memory_add'\n           loc from to val released\n           (ADD : Memory.add memory' loc from to val released memory_add')\n           (MSG_DISJ : message_disjoint memory)\n           (TS_LT    : ts_lt_or_bot memory)\n           (INHAB'   : Memory.inhabited memory')\n           (UP_MEM: up_memory memory memory') :\n  exists memory_add,\n    ⟪ ADDU : Memory.add memory loc from to val released memory_add ⟫ /\\\n    ⟪ UP_MEM_ADD : up_memory memory_add memory_add' ⟫ /\\\n    ⟪ MSG_DISJ : message_disjoint memory_add ⟫ /\\\n    ⟪ TS_LT    : ts_lt_or_bot memory_add ⟫ /\\\n    ⟪ INHAB'   : Memory.inhabited memory_add' ⟫.\nProof using.\n  eapply up_memory_add_exists_l; eauto.\n  { reflexivity. }\n  inv ADD. inv ADD0.\nQed.\n\nLemma up_memory_closed_view view memory memory'\n      (UP_MEM : up_memory memory memory')\n      (CLOS : Memory.closed_view view memory') :\n  Memory.closed_view view memory.\nProof using.\n  destruct CLOS.\n  constructor; red; ins.\n  2: specialize (RLX loc).\n  specialize (PLN loc).\n  all: desc.\n  2: apply UP_MEM in RLX.\n  apply UP_MEM in PLN.\n  all: desc.\n  all: repeat eexists; eauto.\nQed.\n\nLemma up_memory_closed_opt_view view memory memory'\n      (UP_MEM : up_memory memory memory')\n      (CLOS : Memory.closed_opt_view view memory') :\n  Memory.closed_opt_view view memory.\nProof using.\n  destruct view.\n  2: by apply Memory.closed_opt_view_none.\n  apply Memory.closed_opt_view_some.\n  inv CLOS.\n  eapply up_memory_closed_view; eauto.\nQed.\n\n(* TODO: add explanation *)\nLemma future_memory_to_append_memory\n      memory memory'\n      (FUTURE_INIT : Memory.future Memory.init memory)\n      (FUTURE : Memory.future memory memory') :\n  exists memory'',\n    ⟪ FUTURE : Memory.future Memory.init memory'' ⟫ /\\\n    ⟪ MEM_LE   : Memory.le memory memory'' ⟫ /\\\n    ⟪ UP_MEM   : up_memory memory' memory'' ⟫.\nProof using.\n  assert (Memory.future Memory.init memory') as FUTURE_INIT'.\n  { etransitivity; eauto. }\n  apply clos_rt1n_rt in FUTURE.\n  apply clos_rt_rtn1 in FUTURE.\n  induction FUTURE.\n  { eexists. splits; eauto.\n    { reflexivity. }\n    apply up_memory_refl. }\n  assert (Memory.future Memory.init y) as YY.\n  { etransitivity; [by apply FUTURE_INIT|].\n    apply clos_rt_rt1n_iff.\n      by apply clos_rt_rtn1_iff. }\n  destruct IHFUTURE as [memory'']; auto.\n  desc.\n  set (H':=H).\n  destruct H'.\n  destruct OP.\n  { edestruct up_memory_add_exists_r with\n        (released:=released) (memory:=y) (memory':=memory'') (memory_add:=z)\n      as [released' [memory_add]]; eauto.\n    { by apply clos_rt1n_step. }\n    desc.\n    exists memory_add. splits; auto.\n    etransitivity; eauto.\n    eapply memory_add_le; eauto. }\n  2: { exists memory''. splits; auto.\n       constructor; ins.\n       { apply (TOU UP_MEM) in INT.\n         desc.\n         assert (UU := INF). \n         eapply Memory.lower_get1 in UU; eauto.\n         desc. rewrite UU.\n         eexists. eexists. splits; eauto.\n         etransitivity; eauto. }\n       { ins. eapply (TOUIN UP_MEM) in INT; eauto.\n         desc.\n         eapply Memory.lower_get1 in INF; eauto.\n         desc. repeat eexists; eauto.\n         all: apply IMP. }\n       erewrite Memory.lower_o in INT; eauto.\n       destruct (loc_ts_eq_dec (loc0, t) (loc, to)) as [[AA BB]|AA]; simpls.\n       2: by eapply FROMU; eauto.\n       desf.\n       destruct LOWER. destruct LOWER.\n       eapply FROMU in GET2; eauto. }\n  exists memory''. splits; auto.\n  constructor; ins.\n  { apply (TOU UP_MEM) in INT. desc.\n    assert (UU := INF).\n    eapply Memory.split_get1 in UU; eauto.\n    desc. rewrite UU.\n    eexists. eexists. splits; eauto. }\n  { eapply UP_MEM in IMU; eauto. desc.\n    destruct (loc_ts_eq_dec (loc0, t) (loc, to)) as [[AA BB]|AA]; simpls; subst.\n    { edestruct Memory.split_get0 as [HH _]; eauto.\n      rewrite HH in INF. inv INF. }\n    destruct (loc_ts_eq_dec (loc0, t) (loc, to3)) as [[BB CC]|BB]; simpls; subst.\n    2: { repeat eexists.\n         2,3: by apply IMP.\n         erewrite Memory.split_o; eauto.\n         repeat (rewrite loc_ts_eq_dec_neq; eauto). }\n    assert (f = from); subst.\n    { destruct SPLIT. destruct SPLIT.\n      unfold Memory.get, Cell.get in INF.\n      rewrite GET2 in INF. desf. }\n    destruct (Time.le_lt_dec m to) as [BB|BB].\n    { repeat eexists.\n      3: by apply BB.\n      2: by apply IMP.\n      erewrite Memory.split_o; eauto.\n      rewrite loc_ts_eq_dec_eq.\n      eauto. }\n    exists to3. exists to. repeat eexists; simpls.\n    2: by apply IMP.\n    erewrite Memory.split_o; eauto.\n    rewrite loc_ts_eq_dec_neq; auto.\n    rewrite loc_ts_eq_dec_eq; auto. }\n  erewrite Memory.split_o in INT; eauto.\n  destruct (loc_ts_eq_dec (loc0, t) (loc, to)) as [[AA BB]|AA]; simpls.\n  { desf.\n    destruct SPLIT. destruct SPLIT.\n    eapply FROMU in GET2; eauto. desc.\n    eexists. eexists. eexists. eexists.\n    splits; eauto.\n    destruct ILE.\n    constructor; splits; simpls.\n    apply Time.le_lteq. left.\n    eapply TimeFacts.lt_le_lt; eauto. }\n  destruct (loc_ts_eq_dec (loc0, t) (loc, to3)) as [[BB CC]|BB]; simpls.\n  2: by eapply FROMU; eauto.\n  desf.\n  destruct SPLIT. destruct SPLIT.\n  eapply FROMU in GET2; eauto. desc.\n  eexists. eexists. eexists. eexists.\n  splits; eauto.\n  destruct ILE.\n  constructor; simpls.\n  apply Time.le_lteq. left.\n  eapply TimeFacts.le_lt_lt; eauto.\nQed.\n\nLemma up_memory_split_exists memory memory' memory_split'\n      loc from to ts val val' released released' view\n      (UP_MEM   : up_memory memory memory')\n      (MSG_DISJ : message_disjoint memory)\n      (TS_LT    : ts_lt_or_bot memory)\n      (INHAB'   : Memory.inhabited memory')\n      (VWF : View.opt_wf released)\n      (VLE : View.opt_le released released')\n      (SP' : Memory.split\n               memory' loc from to ts val val' released' view memory_split')\n      (GET : Memory.get loc ts memory = Some (from, Message.mk val' view)):\n  exists memory_split,\n    ⟪ SP : Memory.split memory loc from to ts val val' released view memory_split ⟫ /\\\n    ⟪ UP_SP : up_memory memory_split memory_split' ⟫ /\\\n    ⟪ MSG_DISJ : message_disjoint memory_split ⟫ /\\\n    ⟪ TS_LT    : ts_lt_or_bot memory_split ⟫ /\\\n    ⟪ INHAB'   : Memory.inhabited memory_split' ⟫.\nProof using.\n  assert (Memory.get loc ts memory' = Some (from, Message.mk val' view)) as GET'.\n  { eapply memory_split_get_old. eauto. }\n  assert (ts <> to) as TT.\n  { intros HH. subst. inv SP'. inv SPLIT.\n      by apply Time.lt_strorder in TS23. }\n  set (SP'' := SP'). destruct SP''.\n  destruct SPLIT.\n  edestruct Memory.split_exists with (mem1:=memory) (released2:=released) as [memory_split];\n    eauto.\n  exists memory_split. splits; eauto.\n  constructor; ins.\n  { erewrite Memory.split_o in INT; eauto.\n    erewrite Memory.split_o; eauto.\n    desf; simpls; desc; subst.\n    3: by apply UP_MEM.\n    all: eexists; eexists; splits; eauto; reflexivity. }\n  { erewrite Memory.split_o in INT; eauto.\n    desf; simpls; desc; subst.\n    { repeat eexists; simpls; eauto.\n      2,3: by apply IMU.\n      erewrite Memory.split_o; eauto.\n      rewrite loc_ts_eq_dec_eq; simpls. }\n    { repeat eexists; simpls; eauto.\n      2,3: by apply IMU.\n      erewrite Memory.split_o; eauto.\n      rewrite loc_ts_eq_dec_neq; simpls.\n      rewrite (loc_ts_eq_dec_eq loc ts); simpls. }\n    eapply (TOUIN UP_MEM) in INT; eauto. desc.\n    destruct (loc_ts_eq_dec (loc0,t) (loc,ts)) as [[AA BB]|BB]; simpls; subst.\n    { destruct (Time.le_lt_dec m to) as [LL|LL].\n      { repeat eexists; simpls; eauto.\n        2: by apply IMP.\n        erewrite Memory.split_o; eauto.\n        rewrite loc_ts_eq_dec_eq; simpls.\n        rewrite INF in GET. inv GET. }\n      repeat eexists; simpls; eauto.\n      2: by apply IMP.\n      erewrite Memory.split_o; eauto.\n      erewrite loc_ts_eq_dec_neq; eauto.\n      erewrite loc_ts_eq_dec_eq; eauto. }\n    repeat eexists; simpls; eauto.\n    2,3: by apply IMP.\n    simpls.\n    erewrite Memory.split_o; eauto.\n    repeat erewrite loc_ts_eq_dec_neq; eauto.\n    destruct (classic (loc0 = loc)) as [|LNEQ]; [subst; right| by left].\n    intros HH. subst.\n    edestruct Memory.split_get0 as [AA]; eauto.\n    rewrite AA in INF. inv INF. }\n  4: by eapply Memory.split_inhabited; eauto.\n  3: by eapply ts_lt_or_bot_split; eauto.\n  2: by eapply message_disjoint_split; eauto.\n  ins.\n  erewrite Memory.split_o in INT; eauto.\n  desf; simpls; desc; subst.\n  { repeat eexists; simpls.\n    2,3: reflexivity.\n    erewrite Memory.split_o; eauto.\n    rewrite loc_ts_eq_dec_eq; eauto. }\n  { repeat eexists; simpls.\n    2,3: reflexivity.\n    erewrite Memory.split_o; eauto.\n    rewrite loc_ts_eq_dec_neq; eauto.\n    rewrite loc_ts_eq_dec_eq; eauto. }\n  set (INT' := INT).\n  apply (FROMU UP_MEM) in INT'. desc.\n  destruct (loc_ts_eq_dec (loc0,t') (loc,ts)) as [[AA BB]|BB]; simpls; subst.\n  2: { repeat eexists; simpls; eauto.\n       2,3: by apply ILE.\n       simpls.\n       erewrite Memory.split_o; eauto.\n       repeat erewrite loc_ts_eq_dec_neq; eauto.\n       destruct (classic (loc0 = loc)) as [|LNEQ]; [subst; right| by left].\n       intros HH. subst.\n       clear -INT0 SP'.\n       edestruct Memory.split_get0 as [AA]; eauto.\n       rewrite AA in INT0. inv INT0. }\n  desf.\n  set (UU := INT).\n  eapply TS_LT in UU; eauto. desf.\n  { assert (Memory.inhabited (LocFun.add loc r memory')) as XX.\n    { eapply Memory.split_inhabited; eauto. }\n    repeat eexists.\n    2,3: reflexivity.\n    apply XX. }\n  desf.\n  exfalso.\n  clear -ILE o0 GET INT H FTLT MSG_DISJ.\n  eapply interval_le_not_disjoint.\n  3,4: by eauto.\n  all: eauto.\n  { inv ILE. simpls.\n    eapply TimeFacts.lt_le_lt; eauto.\n    eapply TimeFacts.le_lt_lt; eauto. }\n  eapply MSG_DISJ in INT; eauto. eapply INT in GET; eauto.\n  desf.\nQed.\n\nLemma up_memory_split_exists_view_eq memory memory' memory_split'\n      loc from to ts val val' released released'\n      (UP_MEM : up_memory memory memory')\n      (MSG_DISJ : message_disjoint memory)\n      (TS_LT    : ts_lt_or_bot memory)\n      (INHAB'   : Memory.inhabited memory')\n      (SP' : Memory.split\n               memory' loc from to ts val val' released released' memory_split')\n      (GET : Memory.get loc ts memory = Some (from, Message.mk val' released')):\n  exists memory_split,\n    ⟪ SP : Memory.split memory loc from to ts val val' released released' memory_split ⟫ /\\\n    ⟪ UP_SP : up_memory memory_split memory_split' ⟫ /\\\n    ⟪ MSG_DISJ : message_disjoint memory_split ⟫ /\\\n    ⟪ TS_LT    : ts_lt_or_bot memory_split ⟫ /\\\n    ⟪ INHAB'   : Memory.inhabited memory_split' ⟫.\nProof using.\n  eapply up_memory_split_exists; eauto.\n  2: reflexivity.\n  inv SP'. inv SPLIT.\nQed.\n\nLemma up_memory_lower_exists memory memory' memory_lower'\n      loc from to val view released released'\n      (UP_MEM : up_memory memory memory')\n      (MSG_DISJ : message_disjoint memory)\n      (TS_LT    : ts_lt_or_bot memory)\n      (INHAB'   : Memory.inhabited memory')\n      (VWF : View.opt_wf released)\n      (VLE : View.opt_le released released')\n      (LW' : Memory.lower\n               memory' loc from to val view released' memory_lower')\n      (GET : Memory.get loc to memory = Some (from, Message.mk val view)):\n  exists memory_lower,\n    ⟪ LW : Memory.lower memory loc from to val view released memory_lower ⟫ /\\\n    ⟪ UP_LW : up_memory memory_lower memory_lower' ⟫ /\\\n    ⟪ MSG_DISJ : message_disjoint memory_lower ⟫ /\\\n    ⟪ TS_LT    : ts_lt_or_bot memory_lower ⟫ /\\\n    ⟪ INHAB'   : Memory.inhabited memory_lower' ⟫.\nProof using.\n  inv LW'. inv LOWER.\n  edestruct Memory.lower_exists with (mem1:=memory) (released1:=view) (released2:=released)\n    as [memory_lower]; eauto.\n  { etransitivity; eauto. }\n  exists memory_lower. splits; eauto.\n  constructor; ins.\n  { erewrite Memory.lower_o in INT; eauto.\n    erewrite Memory.lower_o; eauto.\n    desf; simpls; desc; subst.\n    2: by apply UP_MEM.\n    eexists; eexists. splits; eauto; reflexivity. }\n  { erewrite Memory.lower_o in INT; eauto.\n    desf; simpls; desc; subst.\n    { repeat eexists; simpls; eauto.\n      2,3: by apply IMU.\n      erewrite Memory.lower_o; eauto.\n      rewrite loc_ts_eq_dec_eq; simpls. }\n    eapply (TOUIN UP_MEM) in INT; eauto. desc.\n    destruct (loc_ts_eq_dec (loc0, t) (loc, to)); simpls.\n    { clear o. desf. repeat eexists.\n      2,3: by apply IMP.\n      erewrite Memory.lower_o; eauto.\n        by rewrite loc_ts_eq_dec_eq. }\n    repeat eexists.\n    2,3: by apply IMP.\n    erewrite Memory.lower_o; eauto.\n    rewrite loc_ts_eq_dec_neq; eauto. }\n  4: by eapply Memory.lower_inhabited; eauto.\n  3: by eapply ts_lt_or_bot_lower; eauto.\n  2: by eapply message_disjoint_lower; eauto.\n  ins.\n  erewrite Memory.lower_o in INT; eauto.\n  desf; simpls; desc; subst.\n  { repeat eexists; simpls.\n    2,3: reflexivity.\n    erewrite Memory.lower_o; eauto.\n    rewrite loc_ts_eq_dec_eq; eauto. }\n  apply UP_MEM in INT. desc.\n  destruct (loc_ts_eq_dec (loc0, t') (loc, to)); simpls.\n  { desf. repeat eexists.\n    2,3: by apply ILE.\n    erewrite Memory.lower_o; eauto.\n    rewrite loc_ts_eq_dec_eq; eauto.\n    inv LW'. inv LOWER0. unfold Memory.get, Cell.get in INT0.\n    rewrite INT0 in GET0. inv GET0. }\n  repeat eexists.\n  2,3: by apply ILE.\n  erewrite Memory.lower_o; eauto.\n  rewrite loc_ts_eq_dec_neq; eauto.\nQed.\n\nLemma up_memory_lower_exists_view_eq memory memory' memory_lower'\n      loc from to val released released'\n      (UP_MEM : up_memory memory memory')\n      (MSG_DISJ : message_disjoint memory)\n      (TS_LT    : ts_lt_or_bot memory)\n      (INHAB'   : Memory.inhabited memory')\n      (LW' : Memory.lower\n               memory' loc from to val released released' memory_lower')\n      (GET : Memory.get loc to memory = Some (from, Message.mk val released)):\n  exists memory_lower,\n    ⟪ LW : Memory.lower memory loc from to val released released' memory_lower ⟫ /\\\n    ⟪ UP_LW : up_memory memory_lower memory_lower' ⟫ /\\\n    ⟪ MSG_DISJ : message_disjoint memory_lower ⟫ /\\\n    ⟪ TS_LT    : ts_lt_or_bot memory_lower ⟫ /\\\n    ⟪ INHAB'   : Memory.inhabited memory_lower' ⟫.\nProof using.\n  eapply up_memory_lower_exists; eauto.\n  2: reflexivity.\n  inv LW'. inv LOWER.\nQed.\n\nRecord future_sim_rel lang (tc tc' : Thread.t lang) :=\n  { ST     : tc.(Thread.state) = tc'.(Thread.state);\n    PROM   : tc.(Thread.local).(Local.promises) = tc'.(Thread.local).(Local.promises);\n    TVIEW  : TView.le_ tc.(Thread.local).(Local.tview) tc'.(Thread.local).(Local.tview);\n    SC_LE  : TimeMap.le tc.(Thread.sc) tc'.(Thread.sc);\n    UP_MEM : up_memory tc.(Thread.memory) tc'.(Thread.memory);\n    MSG_DISJ : message_disjoint tc.(Thread.memory);\n    TS_LT    : ts_lt_or_bot tc.(Thread.memory);\n    REL_WF   : message_view_wf tc.(Thread.memory);\n    INHAB'   : Memory.inhabited tc'.(Thread.memory);\n  }.\n\nLemma future_sim_step lang (tc tc' tc_new' : Thread.t lang)\n      (WF  : Local.wf tc .(Thread.local) tc .(Thread.memory))\n      (WF' : Local.wf tc'.(Thread.local) tc'.(Thread.memory))\n      (STEP : Thread.tau_step (lang:=lang) tc' tc_new')\n      (SIM : future_sim_rel tc tc') :\n  exists tc_new,\n      ⟪ STEP : (Thread.tau_step (lang:=lang))⁺ tc tc_new ⟫ /\\\n      ⟪ SIM : future_sim_rel tc_new tc_new' ⟫.\nProof using.\n  destruct SIM.\n  destruct STEP. destruct TSTEP.\n  destruct STEP.\n  { destruct STEP.\n    destruct lc1. destruct lc2.\n    destruct tc  as [st_ [] sc_ mem_].\n    simpls; subst. \n    destruct LOCAL. simpls.\n    assert (exists mem_2,\n               ⟪ MM1 : Memory.promise promises mem_ loc from to val released\n                              promises2 mem_2 kind ⟫ /\\\n               ⟪ MM2 : Memory.closed_opt_view released mem_2 ⟫ /\\\n               ⟪ MM3 : Time.le (View.rlx (View.unwrap released) loc) to ⟫ /\\\n               ⟪ MMU : up_memory mem_2 mem2 ⟫ /\\\n               ⟪ MMD : message_disjoint mem_2 ⟫ /\\\n               ⟪ MMT : ts_lt_or_bot mem_2 ⟫ /\\\n               ⟪ MMI : Memory.inhabited mem2 ⟫\n           ) as [mem_2].\n    { destruct PROMISE.\n      { edestruct up_memory_add_exists_l_view_eq with (memory:=mem_) as [mem_2]; eauto.\n        desc. exists mem_2. splits; auto.\n        { by apply Memory.promise_add. }\n        eapply up_memory_closed_opt_view; eauto. }\n      { edestruct up_memory_split_exists_view_eq with\n            (memory:=mem_) (memory':=mem1) as [mem_2]; eauto.\n        { inv PROMISES. inv SPLIT. by apply WF in GET2. }\n        desc.\n        exists mem_2. splits; auto.\n        { by apply Memory.promise_split. }\n        eapply up_memory_closed_opt_view; eauto. }\n      edestruct up_memory_lower_exists_view_eq with (memory:=mem_) (memory':=mem1) as [mem_2];\n          eauto.\n      { inv PROMISES. inv LOWER. by apply WF in GET2. }\n      desc.\n      exists mem_2. splits; auto.\n      { by apply Memory.promise_lower. }\n      eapply up_memory_closed_opt_view; eauto. }\n    desc.\n    eexists. splits.\n    { apply t_step. econstructor.\n      { econstructor. eapply Thread.step_promise.\n        repeat (econstructor; eauto). }\n      done. }\n    constructor; simpls.\n    eapply message_view_wf_promise; eauto. }\n  destruct STEP. simpls.\n  destruct lc1. destruct lc2.\n  destruct tc  as [st_ [] sc_ mem_].\n  simpls; subst. \n  inv LOCAL.\n  { eexists. splits.\n    { apply t_step. econstructor.\n      { econstructor. eapply Thread.step_program.\n        econstructor; eauto.\n        econstructor. }\n      done. }\n    constructor; simpls. }\n  { destruct LOCAL0. simpls.\n    apply (TOU UP_MEM0) in GET. desc.\n    eexists. splits.\n    { apply t_step. econstructor.\n      { econstructor. eapply Thread.step_program.\n        econstructor.\n        2: { eapply Local.step_read.\n             econstructor; eauto.\n             eapply TViewFacts.readable_mon; eauto.\n             2: reflexivity.\n             apply TVIEW0. }\n        eauto. }\n      done. }\n    constructor; simpls. subst.\n    unfold TView.read_tview.\n    constructor; simpls.\n    { by apply TVIEW0. }\n    all: apply view_le_rect; [|desf; [by apply View.unwrap_opt_le|reflexivity]].\n    all: apply view_le_rect; [|reflexivity].\n    all: apply TVIEW0. }\n  { destruct LOCAL0. simpls.\n    destruct WRITE.\n    set (released_ := TView.write_released tview1 sc_ loc to None ord).\n    assert (View.opt_le released_ released) as RLE.\n    { subst. unfold released_, TView.write_released.\n      desf; [|reflexivity].\n      apply View.opt_le_some.\n      apply view_le_rect; [reflexivity|].\n      unfold TView.write_tview. simpls.\n      unfold LocFun.add. desf.\n      all: apply view_le_rect; [|reflexivity].\n      all: apply TVIEW0. }\n    assert (View.opt_wf released_) as VWF.\n    { unfold released_, TView.write_released.\n      desf; constructor.\n      rewrite View.join_bot_l.\n      unfold TView.write_tview; simpls.\n      unfold LocFun.add. rewrite Loc.eq_dec_eq.\n      unfold View.join. constructor; desf; simpls.\n      all: apply timemap_le_rect; [|reflexivity].\n      all: apply WF. }\n    assert (TView.le_ (TView.write_tview tview1 sc_ loc to ord)\n                      (TView.write_tview tview sc1 loc to ord)) as WV.\n    { unfold TView.write_tview. constructor; simpls.\n      ins. unfold LocFun.find, LocFun.add.\n      desf.\n      all: try (apply view_le_rect; [apply TVIEW0|reflexivity]).\n      apply TVIEW0. }\n    destruct PROMISE.\n    { (* add case *)\n      edestruct up_memory_add_exists_l with (memory:=mem_) (released:=released_)\n        as [mem_']; eauto.\n      desc.\n      assert (exists (promise_ : Memory.t),\n                 Memory.add promises loc from to val released_ promise_)\n        as [promise_ PP].\n      { eapply Memory.add_exists_le.\n        { apply WF. }\n        apply ADDU. }\n      assert (exists (promise_' : Memory.t),\n                 Memory.remove promise_ loc from to val released_ promise_')\n        as [promise_' RR].\n      { apply Memory.remove_exists.\n        erewrite Memory.add_o; eauto.\n          by rewrite loc_ts_eq_dec_eq. }\n      eexists. splits.\n      { apply t_step.\n        econstructor.\n        { econstructor. eapply Thread.step_program.\n          econstructor.\n          2: { eapply Local.step_write.\n               econstructor.\n               { done. }\n               { constructor. eapply TimeFacts.le_lt_lt.\n                 2: by apply WRITABLE.\n                 apply TVIEW0. }\n               2: by eauto.\n               econstructor; eauto.\n               apply Memory.promise_add; eauto.\n               etransitivity; eauto.\n               subst.\n               unfold TView.write_released.\n               desf; simpls.\n               2: by apply Time.bot_spec.\n               repeat (rewrite TimeMap.le_join_r; [|by apply TimeMap.bot_spec]).\n               unfold LocFun.add. rewrite !Loc.eq_dec_eq.\n               desf; unfold View.join; simpls.\n               all: apply timemap_le_rect; [apply TVIEW0|reflexivity]. }\n          eauto. }\n        done. }\n      constructor; simpls.\n      all: try by apply UP_EXTRA.\n      apply Memory.ext.\n      ins.\n      erewrite Memory.remove_o; eauto.\n      erewrite Memory.remove_o with (mem2:=promises2); [|by apply REMOVE].\n      desf.\n      erewrite Memory.add_o; eauto.\n      erewrite Memory.add_o with (mem2:=promises1); [|by apply PROMISES].\n      desf; simpls; desf.\n      eapply message_view_wf_add; eauto. }\n    { (* split case *)\n      edestruct up_memory_split_exists with (memory:=mem_) (released:=released_) as [mem_'];\n        eauto.\n      { inv PROMISES. inv SPLIT. by apply WF in GET2. }\n      desc.\n      assert (exists (promise_ : Memory.t),\n                 Memory.split promises loc from to ts3 val val3 released_ released3 promise_)\n        as [promise_ PP].\n      { inv PROMISES. inv SPLIT.\n        apply Memory.split_exists; auto. }\n      assert (exists (promise_' : Memory.t),\n                 Memory.remove promise_ loc from to val released_ promise_')\n        as [promise_' RR].\n      { apply Memory.remove_exists.\n        erewrite Memory.split_o; eauto.\n          by rewrite loc_ts_eq_dec_eq. }\n      eexists. splits.\n      { apply t_step.\n        econstructor.\n        { econstructor. eapply Thread.step_program.\n          econstructor.\n          2: { eapply Local.step_write.\n               econstructor.\n               { done. }\n               { constructor. eapply TimeFacts.le_lt_lt.\n                 2: by apply WRITABLE.\n                 apply TVIEW0. }\n               2: by eauto.\n               econstructor; eauto.\n               apply Memory.promise_split; eauto.\n               etransitivity; eauto.\n               subst.\n               unfold TView.write_released.\n               desf; simpls.\n               2: by apply Time.bot_spec.\n               repeat (rewrite TimeMap.le_join_r; [|by apply TimeMap.bot_spec]).\n               unfold LocFun.add. rewrite !Loc.eq_dec_eq.\n               desf; unfold View.join; simpls.\n               all: apply timemap_le_rect; [apply TVIEW0|reflexivity]. }\n          eauto. }\n        done. }\n      constructor; simpls.\n      apply Memory.ext.\n      ins.\n      erewrite Memory.remove_o; eauto.\n      erewrite Memory.remove_o with (mem2:=promises2); [|by apply REMOVE].\n      desf.\n      erewrite Memory.split_o; eauto.\n      erewrite Memory.split_o with (mem2:=promises1); [|by apply PROMISES].\n      desf; simpls; desf.\n      eapply message_view_wf_split; eauto. }\n    (* lower case *)\n    edestruct up_memory_lower_exists with (memory:=mem_) (released:=released_) as [mem_'];\n      eauto.\n    { inv PROMISES. inv LOWER. by apply WF in GET2. }\n    assert (exists (promise_ : Memory.t),\n               Memory.lower promises loc from to val released0 released_ promise_)\n      as [promise_ PP].\n    { inv PROMISES. inv LOWER.\n      apply Memory.lower_exists; auto.\n      etransitivity; eauto. }\n    assert (exists (promise_' : Memory.t),\n               Memory.remove promise_ loc from to val released_ promise_')\n      as [promise_' RR].\n    { apply Memory.remove_exists.\n      erewrite Memory.lower_o; eauto.\n        by rewrite loc_ts_eq_dec_eq. }\n    desc.\n    eexists. splits.\n    { apply t_step.\n      econstructor.\n      { econstructor. eapply Thread.step_program.\n        econstructor.\n        2: { eapply Local.step_write.\n             econstructor.\n             { done. }\n             { constructor. eapply TimeFacts.le_lt_lt.\n               2: by apply WRITABLE.\n               apply TVIEW0. }\n             2: by eauto.\n             econstructor; eauto.\n             apply Memory.promise_lower; eauto.\n             etransitivity; eauto.\n             subst.\n             unfold TView.write_released.\n             desf; simpls.\n             2: by apply Time.bot_spec.\n             repeat (rewrite TimeMap.le_join_r; [|by apply TimeMap.bot_spec]).\n             unfold LocFun.add. rewrite !Loc.eq_dec_eq.\n             desf; unfold View.join; simpls.\n             all: apply timemap_le_rect; [apply TVIEW0|reflexivity]. }\n        eauto. }\n      done. }\n    constructor; simpls.\n    apply Memory.ext.\n    ins.\n    erewrite Memory.remove_o; eauto.\n    erewrite Memory.remove_o with (mem2:=promises2); [|by apply REMOVE].\n    desf.\n    erewrite Memory.lower_o; eauto.\n    erewrite Memory.lower_o with (mem2:=promises1); [|by apply PROMISES].\n    desf; simpls; desf.\n    eapply message_view_wf_lower; eauto. }\n  { (* RMW cover case *)\n    destruct LOCAL1. simpls.\n    destruct LOCAL2. simpls.\n    destruct WRITE.\n    set (GET' := GET).\n    apply (TOU UP_MEM0) in GET'. desc.\n    set (tview_ := TView.read_tview tview1 loc tsr view ordr).\n    set (released_ := TView.write_released tview_ sc_ loc tsw view ordw).\n    assert (View.le (View.unwrap view) (View.unwrap releasedr)) as XX.\n    { by apply View.unwrap_opt_le. }\n    assert (View.opt_le released_ releasedw) as RLE.\n    { subst. unfold released_, TView.write_released.\n      desf; [|reflexivity].\n      apply View.opt_le_some.\n      apply view_le_rect; auto.\n      unfold TView.write_tview. simpls.\n      unfold LocFun.add. desf.\n      all: repeat (apply view_le_rect); auto.\n      all: try reflexivity.\n      all: by apply TVIEW0. }\n    assert (View.wf (View.unwrap view)) as VVWF.\n    { apply REL_WF0 in INF. inv INF. apply View.bot_wf. }\n    assert (View.opt_wf released_) as VWF.\n    { unfold released_, TView.write_released.\n      desf; constructor.\n      apply View.join_wf; auto.\n      unfold TView.write_tview; simpls.\n      unfold LocFun.add. rewrite Loc.eq_dec_eq.\n      unfold View.join. constructor; desf; simpls.\n      all: repeat (apply timemap_le_rect).\n      all: try by apply WF.\n      all: try reflexivity.\n      2: by apply VVWF.\n      all: unfold View.singleton_ur_if, View.singleton_ur, View.singleton_rw.\n      all: desf; simpls.\n      all: try reflexivity.\n      all: apply TimeMap.bot_spec. }\n    assert (TimeMap.le (View.rlx (View.unwrap view)) (View.rlx (View.unwrap releasedr)))\n      as VLE.\n    { by apply View.unwrap_opt_le. }\n    assert (TimeMap.le\n              (View.rlx (TView.cur tview_))\n              (View.rlx (TView.cur tview2))) as TLE.\n    { intros ll.\n      rewrite <- TVIEW1. unfold TView.read_tview. simpls.\n      repeat apply timemap_le_rect.\n      { apply TVIEW0. }\n      { reflexivity. }\n      desf.\n      reflexivity. }\n    assert (TView.le_ (TView.write_tview tview_ sc_ loc tsw ordw)\n                      (TView.write_tview tview2 sc1 loc tsw ordw)) as WV.\n    { rewrite <- TVIEW1.\n      unfold TView.write_tview. constructor; simpls.\n      all: ins; unfold LocFun.find, LocFun.add.\n      all: desf.\n      all: repeat apply view_le_rect; auto.\n      all: try reflexivity.\n      all: apply TVIEW0. }\n    destruct PROMISE.\n    { (* add case *)\n      edestruct up_memory_add_exists_l with (memory:=mem_) (released:=released_)\n        as [mem_']; eauto.\n      desc.\n      assert (exists (promise_ : Memory.t),\n                 Memory.add promises loc tsr tsw valw released_ promise_)\n        as [promise_ PP].\n      { eapply Memory.add_exists_le.\n        { apply WF. }\n        apply ADDU. }\n      assert (exists (promise_' : Memory.t),\n                 Memory.remove promise_ loc tsr tsw valw released_ promise_')\n        as [promise_' RR].\n      { apply Memory.remove_exists.\n        erewrite Memory.add_o; eauto.\n          by rewrite loc_ts_eq_dec_eq. }\n      eexists. splits.\n      { apply t_step.\n        econstructor.\n        { econstructor. eapply Thread.step_program.\n          econstructor.\n          2: { eapply Local.step_update.\n               { econstructor; eauto.\n                 eapply TViewFacts.readable_mon; eauto.\n                 2: reflexivity.\n                 apply TVIEW0. }\n               econstructor.\n               { done. }\n               { constructor. eapply TimeFacts.le_lt_lt; auto.\n                   by apply WRITABLE. }\n               2: by eauto.\n               econstructor; eauto.\n               apply Memory.promise_add; eauto.\n               etransitivity; eauto.\n               subst.\n               unfold TView.write_released.\n               desf; simpls.\n               2: by apply Time.bot_spec.\n               apply timemap_le_rect; auto.\n               unfold LocFun.add. rewrite !Loc.eq_dec_eq.\n               desf; unfold View.join; simpls.\n               all: repeat apply timemap_le_rect; auto.\n               all: try reflexivity.\n               all: apply TVIEW0. }\n          eauto. }\n        done. }\n      constructor; simpls.\n      2: by eapply message_view_wf_add; eauto.\n      apply Memory.ext.\n      ins.\n      erewrite Memory.remove_o; eauto.\n      erewrite Memory.remove_o with (mem2:=promises2); [|by apply REMOVE].\n      desf.\n      all: erewrite Memory.add_o; eauto.\n      all: erewrite Memory.add_o with (mem2:=promises1); [|by apply PROMISES].\n      all: desf; simpls; desf. }\n    { (* split case *)\n      edestruct up_memory_split_exists with (memory:=mem_) (released:=released_) as [mem_'];\n        eauto.\n      { inv PROMISES. inv SPLIT. by apply WF in GET2. }\n      desc.\n      assert (exists (promise_ : Memory.t),\n                 Memory.split promises loc tsr tsw ts3 valw val3 released_ released3 promise_)\n        as [promise_ PP].\n      { inv PROMISES. inv SPLIT.\n        apply Memory.split_exists; auto. }\n      assert (exists (promise_' : Memory.t),\n                 Memory.remove promise_ loc tsr tsw valw released_ promise_')\n        as [promise_' RR].\n      { apply Memory.remove_exists.\n        erewrite Memory.split_o; eauto.\n          by rewrite loc_ts_eq_dec_eq. }\n      eexists. splits.\n      { apply t_step.\n        econstructor.\n        { econstructor. eapply Thread.step_program.\n          econstructor.\n          2: { eapply Local.step_update.\n               { econstructor; eauto.\n                 eapply TViewFacts.readable_mon; eauto.\n                 2: reflexivity.\n                 apply TVIEW0. }\n               econstructor.\n               { done. }\n               { constructor. eapply TimeFacts.le_lt_lt; auto.\n                   by apply WRITABLE. }\n               2: by eauto.\n               econstructor; eauto.\n               apply Memory.promise_split; eauto.\n               etransitivity; eauto.\n               subst.\n               unfold TView.write_released.\n               desf; simpls.\n               2: by apply Time.bot_spec.\n               apply timemap_le_rect; auto.\n               unfold LocFun.add. rewrite !Loc.eq_dec_eq.\n               desf; unfold View.join; simpls.\n               all: repeat apply timemap_le_rect; auto.\n               all: try reflexivity.\n               all: apply TVIEW0. }\n          eauto. }\n        done. }\n      constructor; simpls.\n      apply Memory.ext.\n      ins.\n      erewrite Memory.remove_o; eauto.\n      erewrite Memory.remove_o with (mem2:=promises2); [|by apply REMOVE].\n      desf.\n      3: { eapply message_view_wf_split; eauto. }\n      all: erewrite Memory.split_o; eauto.\n      all: erewrite Memory.split_o with (mem2:=promises1); [|by apply PROMISES].\n      all: desf; simpls; desf. }\n    (* lower case *)\n    edestruct up_memory_lower_exists with (memory:=mem_) (released:=released_) as [mem_'];\n      eauto.\n    { inv PROMISES. inv LOWER. by apply WF in GET2. }\n    assert (exists (promise_ : Memory.t),\n               Memory.lower promises loc tsr tsw valw released0 released_ promise_)\n      as [promise_ PP].\n    { inv PROMISES. inv LOWER.\n      apply Memory.lower_exists; auto.\n      etransitivity; eauto. }\n    assert (exists (promise_' : Memory.t),\n               Memory.remove promise_ loc tsr tsw valw released_ promise_')\n      as [promise_' RR].\n    { apply Memory.remove_exists.\n      erewrite Memory.lower_o; eauto.\n        by rewrite loc_ts_eq_dec_eq. }\n    desc.\n    eexists. splits.\n    { apply t_step.\n        econstructor.\n        { econstructor. eapply Thread.step_program.\n          econstructor.\n          2: { eapply Local.step_update.\n               { econstructor; eauto.\n                 eapply TViewFacts.readable_mon; eauto.\n                 2: reflexivity.\n                 apply TVIEW0. }\n               econstructor.\n               { done. }\n               { constructor. eapply TimeFacts.le_lt_lt; auto.\n                   by apply WRITABLE. }\n               2: by eauto.\n               econstructor; eauto.\n               apply Memory.promise_lower; eauto.\n               etransitivity; eauto.\n               subst.\n               unfold TView.write_released.\n               desf; simpls.\n               2: by apply Time.bot_spec.\n               apply timemap_le_rect; auto.\n               unfold LocFun.add. rewrite !Loc.eq_dec_eq.\n               desf; unfold View.join; simpls.\n               all: repeat apply timemap_le_rect; auto.\n               all: try reflexivity.\n               all: apply TVIEW0. }\n          eauto. }\n        done. }\n    constructor; simpls.\n    apply Memory.ext.\n    ins.\n    erewrite Memory.remove_o; eauto.\n    erewrite Memory.remove_o with (mem2:=promises2); [|by apply REMOVE].\n    desf.\n    3: { eapply message_view_wf_lower; eauto. }\n    all: erewrite Memory.lower_o; eauto.\n    all: erewrite Memory.lower_o with (mem2:=promises1); [|by apply PROMISES].\n    all: desf; simpls; desf. }\n  destruct LOCAL0. simpls.\n  eexists. splits.\n  { apply t_step. econstructor.\n    { econstructor. eapply Thread.step_program.\n      econstructor.\n      2: { eapply Local.step_fence.\n           econstructor; eauto. }\n      eauto. }\n    done. }\n  constructor; simpls; subst.\n  { unfold TView.write_fence_tview.\n    constructor; simpls.\n    { ins. unfold LocFun.find.\n      desf.\n      2-4: by apply TVIEW0.\n      constructor; simpls.\n      all: unfold TView.write_fence_sc, TView.read_fence_tview; desf; simpls.\n      all: apply timemap_le_rect; auto.\n      all: apply TVIEW0. }\n    { desf.\n      2-3: by apply TVIEW0.\n      constructor; simpls.\n      all: unfold TView.write_fence_sc, TView.read_fence_tview; desf; simpls.\n      all: apply timemap_le_rect; auto.\n      all: apply TVIEW0. }\n    desf.\n    2: by rewrite !view_join_bot_r; apply TVIEW0.\n    constructor; simpls.\n    all: unfold TView.write_fence_sc, TView.read_fence_tview; desf; simpls.\n    all: repeat (apply timemap_le_rect); auto.\n    all: apply TVIEW0. }\n  unfold TView.write_fence_sc, TView.read_fence_tview; desf; simpls.\n  all: repeat (apply timemap_le_rect); auto.\n  all: apply TVIEW0.\nQed.\n\nLemma future_memory_switch\n      lang (state : Language.Language.state lang)\n      local sc_view memory sc_view' memory'\n      (FUTURE_INIT : Memory.future Memory.init memory)\n      (FUTURE      : Memory.future memory memory')\n      (SC_LE       : TimeMap.le sc_view sc_view')\n      (PROMISES    : Memory.le (Local.promises local) memory')\n      (LOCAL_WF    : Local.wf local memory)\n      (SC_CLOS     : Memory.closed_timemap sc_view' memory') :\n  exists sc_view'' memory'',\n    ⟪ MEM_LE : Memory.le memory memory'' ⟫ /\\\n    ⟪ FUTURE : Memory.future Memory.init memory'' ⟫ /\\\n    ⟪ SC_LE  : TimeMap.le sc_view sc_view'' ⟫ /\\\n    ⟪ LOCAL_WF : Local.wf local memory'' ⟫ /\\\n    ⟪ SC_CLOS : Memory.closed_timemap sc_view'' memory'' ⟫ /\\\n    ⟪ MEM_CLOS : Memory.closed memory' ⟫ /\\\n    ⟪ STEPS :\n      forall (thread_conf : Thread.t lang)\n             (EXEC : rtc (Thread.tau_step (lang:=lang))\n                         (Thread.mk lang state local sc_view'' memory'')\n                         thread_conf),\n      exists (thread_conf' : Thread.t lang),\n        ⟪ STEPS :\n          rtc (Thread.tau_step (lang:=lang))\n              (Thread.mk lang state local sc_view' memory')\n              thread_conf' ⟫ /\\\n        ⟪ SIM : future_sim_rel thread_conf' thread_conf ⟫ ⟫.\nProof using.\n  assert (Memory.closed memory') as MEM_CLOS'.\n  { eapply Memory.future_closed; eauto.\n    eapply Memory.future_closed; eauto.\n    apply Memory.init_closed. }\n  edestruct future_memory_to_append_memory with (memory:=memory) (memory':=memory')\n    as [memory'']; eauto.\n  desc.\n  edestruct up_memory_closed_bigger_timemap with (memory:=memory') (memory':=memory'')\n    as [sc_view'']; eauto.\n  { by etransitivity; [|by eauto]. }\n  { by apply inhabited_future_init. }\n  desc.\n  exists sc_view''. exists memory''.\n  assert (Local.wf local memory') as LOCAL_WF'.\n  { constructor; auto.\n    1,3: by apply LOCAL_WF.\n    constructor; ins.\n    all: eapply Memory.future_closed_view; eauto.\n    all: apply LOCAL_WF. }\n  assert (Local.wf local memory'') as LOCAL_WF''.\n  { constructor.\n    1,4: by apply LOCAL_WF.\n    { constructor; ins.\n      all: eapply closed_view_le; eauto.\n      all: apply LOCAL_WF. }\n    etransitivity; [apply LOCAL_WF|apply MEM_LE]. }\n  splits; auto.\n  { etransitivity; eauto. }\n  ins.\n  assert (future_sim_rel\n            (Thread.mk _ state local sc_view'  memory' )\n            (Thread.mk _ state local sc_view'' memory'')) as XX.\n  { constructor; simpls.\n    { reflexivity. }\n    { apply message_disjoint_future_init.\n        by etransitivity; [|by eauto]. }\n    { apply ts_lt_or_bot_future_init.\n        by etransitivity; [|by eauto]. }\n    2: by apply inhabited_future_init.\n    apply message_view_wf_future_init.\n      by etransitivity; [|by eauto]. }\n  clear -EXEC LOCAL_WF LOCAL_WF' LOCAL_WF'' MEM_CLOS' XX SC_CLOS TM_CLOS FUTURE0.\n  apply clos_rt_rt1n_iff in EXEC.\n  apply clos_rt_rtn1_iff in EXEC.\n  induction EXEC.\n  { eexists. splits.\n    { reflexivity. }\n    done. }\n  desc.\n  assert (Local.wf (Thread.local thread_conf') (Thread.memory thread_conf')) as AA.\n  { eapply Thread.rtc_tau_step_future; eauto. }\n  assert (Local.wf (Thread.local y) (Thread.memory y)) as BB.\n  { apply clos_rt_rtn1_iff in EXEC.\n    apply clos_rt_rt1n in EXEC.\n    eapply Thread.rtc_tau_step_future; eauto.\n    all: simpls.\n    eapply Memory.future_closed; [|by eauto].\n    apply Memory.init_closed. }\n  eapply future_sim_step in H.\n  { desc. eexists. splits.\n    2: by eauto.\n    apply clos_rt_rt1n_iff.\n    eapply rt_trans.\n    { apply clos_rt_rt1n_iff. eauto. }\n    apply clos_trans_in_rt; eauto. }\n  all: auto.\nQed.\n", "meta": {"author": "weakmemory", "repo": "promising1ToImm", "sha": "f27e87f0c2d037b30f0bc13763af39a11bb949a1", "save_path": "github-repos/coq/weakmemory-promising1ToImm", "path": "github-repos/coq/weakmemory-promising1ToImm/promising1ToImm-f27e87f0c2d037b30f0bc13763af39a11bb949a1/src/PromiseFuture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.22955673784412686}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Export DistributedReferenceCounting.machine4.machine.\nRequire Export DistributedReferenceCounting.machine4.cardinal.\nRequire Export DistributedReferenceCounting.machine4.comm.\n\nUnset Standard Proposition Elimination Names.\n\n(** Changes with machine1:\n   - As receive table owner equals 1, initally,\n     I should add -1\n   - Base cases had to be changed\n   - inductive case, proof is unchanged\n*)\n   \n\n\nSection INVARIANT1.\n\nRemark add_reduce1 :\n forall x1 x2 y : Z, x1 = x2 -> (y + x1 - 1)%Z = (y + x2 - 1)%Z.\nProof.\n  intros; omega.\nQed.\n\nLemma invariant1_init :\n sigma_send_table send_init =\n (sigma_receive_table rec_init + sigma_weight bag_init - 1)%Z.\nProof.\n  unfold send_init, rec_init, bag_init in |- *.\n  unfold sigma_send_table, sigma_receive_table, sigma_weight in |- *.\n  unfold sigma_table in |- *.\n  simpl in |- *.\n  rewrite sigma_null.\n  replace\n   (sigma2_table Site LS LS (queue Message) (fun _ _ : Site => cardinal)\n      (fun _ _ : Site => empty Message)) with 0%Z.\n  rewrite (sigma_sigma_but Site owner eq_site_dec).\n  case (eq_site_dec owner owner); intro.\n  unfold Int in |- *.\n  rewrite sigma_but_null.\n  omega.\n  \n  intros.\n  case (eq_site_dec s owner).\n  intro; elim H; auto.\n  \n  auto.\n  \n  elim n; auto.\n  \n  apply finite_site.\n  \n  unfold sigma2_table in |- *.\n  unfold sigma_table in |- *.\n  symmetry  in |- *.\n  simpl in |- *.\n  rewrite sigma_null.\n  apply sigma_null.\nQed.\n\n\n\nLemma invariant1_inductive :\n forall (c : Config) (t : class_trans c),\n legal c ->\n sigma_send_table (st c) =\n (sigma_receive_table (rt c) + sigma_weight (bm c) - 1)%Z ->\n sigma_send_table (st (transition c t)) =\n (sigma_receive_table (rt (transition c t)) +\n  sigma_weight (bm (transition c t)) - 1)%Z.\n\nProof.\n  simple induction t.\n\n  (* 1 *)\n\n  intros; simpl in |- *.\n  rewrite sigma_weight_post_message.\n  rewrite sigma_inc_send_table.\n  unfold cardinal_count in |- *; unfold fun_sum in |- *; simpl in |- *.\n  rewrite H0; omega.\n\n  (* 2 *)\n  \n  intros; simpl in |- *.\n  rewrite (sigma_weight_collect_message dec).\n  rewrite sigma_dec_send_table.\n  unfold cardinal_count in |- *; unfold fun_sum in |- *; simpl in |- *.\n  rewrite H0; omega.\n  auto.\n\n  (* 3 *)\n  \n  intros; simpl in |- *.\n  rewrite sigma_weight_post_message.\n  rewrite sigma_inc_send_table.\n  rewrite sigma_weight_collect_message with (m := inc_dec s3).\n  unfold cardinal_count in |- *; unfold fun_sum in |- *; simpl in |- *.\n  rewrite H0; omega.\n  auto.\n\n  (* 4 *)\n  \n  intros; simpl in |- *.\n  rewrite sigma_weight_post_message.\n  rewrite sigma_weight_collect_message with (m := copy).\n  unfold cardinal_count in |- *; unfold fun_sum in |- *; simpl in |- *.\n  rewrite H0; omega.\n  auto.\n\n  (* 5 *)\n  \n  intros; simpl in |- *.\n  rewrite sigma_weight_collect_message with (m := copy).\n  rewrite sigma_set_receive_table.\n  unfold cardinal_count in |- *; unfold fun_sum in |- *; simpl in |- *.\n  rewrite H0; omega.\n  auto.\n  auto.\n\n  (* 6 *)\n  \n  intros; simpl in |- *.\n  rewrite sigma_weight_post_message.\n  rewrite sigma_weight_collect_message with (m := copy).\n  rewrite sigma_set_receive_table.\n  unfold cardinal_count in |- *; unfold fun_sum in |- *; simpl in |- *.\n  rewrite H0; omega.\n  auto.\n  auto.\n  \n  (* 7 *)\n\n  intros; simpl in |- *.\n  rewrite sigma_weight_post_message.\n  rewrite sigma_reset_receive_table.\n  unfold cardinal_count in |- *; unfold fun_sum in |- *; simpl in |- *.\n  rewrite H0; omega.\n  auto.\n\n\n  (* optim 1 *)\n\n  intros; simpl in |- *.\n  rewrite sigma_weight_post_message.\n  rewrite sigma_weight_change_queue with (s3 := s2).\n  unfold cardinal_count in |- *; unfold fun_sum in |- *; simpl in |- *.\n  omega.\n  auto.\n\n  (* optim 2 *)\n\n  simpl in |- *; intros.\n  rewrite H0.\n  apply add_reduce1.\n  unfold sigma_weight in |- *.\n  unfold sigma2_table in |- *.\n  apply sigma_table_simpl.\n  apply funct_eq.\n  intro.\n  unfold sigma_table in |- *.\n  apply sigma_simpl.\n  intros.\n  case (eq_queue_dec e1 s1 x s2); intro.\n  decompose [and] a.\n  rewrite H2; rewrite H3.\n  rewrite that_queue.\n  rewrite e.\n  cut (cardinal (append Message q1 q2) = cardinal (append Message q3 q4)).\n  unfold cardinal in |- *.\n  rewrite reduce_append.\n  rewrite reduce_append.\n  omega.\n  rewrite e0; auto.\n  rewrite other_queue.\n  auto.\n  auto.\nQed.\n\n\nLemma invariant1 :\n forall c : Config,\n legal c ->\n sigma_send_table (st c) =\n (sigma_receive_table (rt c) + sigma_weight (bm c) - 1)%Z.\nProof.\n  intros.\n  elim H.\n  apply invariant1_init.\n  exact invariant1_inductive.\nQed.\n\n\n\n\nEnd INVARIANT1.\n\n", "meta": {"author": "coq-contribs", "repo": "distributed-reference-counting", "sha": "6552f14cce0ea374c98adcbee0476ae268d64a7e", "save_path": "github-repos/coq/coq-contribs-distributed-reference-counting", "path": "github-repos/coq/coq-contribs-distributed-reference-counting/distributed-reference-counting-6552f14cce0ea374c98adcbee0476ae268d64a7e/machine4/invariant1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.22955673216721217}}
{"text": "From stdpp Require Export set.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import auth.\nFrom iris.base_logic Require Import big_op.\nFrom iris.base_logic.lib Require Import fractional.\nFrom iris.program_logic Require Import hoare.\nFrom iris.heap_lang Require Export proofmode lang lifting notation.\nFrom iris.heap_lang.lib Require Export lock.\nFrom iris_hashtable Require Export hashtable_model.\nFrom iris_hashtable Require Import util modulo forloop array hashtable_buckets.\n\nSection hashtable.\n  \n  Context Σ Key Hash map `{FinMap Key map , heapG Σ, !Hashable Σ Key Hash, !Array Σ(*, !tableG Σ*)}.\n  Variable lck : lock Σ.\n\n  Definition create_table : val :=\n    λ: \"n\", let: \"arr\" := make_array (\"n\",#()) in\n            (for: \"i\" := #0 to \"n\" do \"arr\".[\"i\"] :=\n               (ref NONE, newlock lck #())) ;;\n            (\"arr\", \"n\").\n\n  Definition index : val :=\n    λ: \"k\" \"n\", modulo (hashf \"k\", \"n\").\n  \n  Definition table_insert : val :=\n    λ: \"t\" \"k\" \"x\", let: \"arr\" := Fst \"t\" in\n                    let: \"n\" := Snd \"t\" in\n                    let: \"bl\" := \"arr\".[index \"k\" \"n\"] in\n                    let: \"b\" := Fst \"bl\" in\n                    let: \"l\" := Snd \"bl\" in\n                    acquire lck \"l\" ;;\n                    \"b\" <- SOME (\"k\", \"x\", !\"b\") ;;\n                    release lck \"l\".\n\n  Definition table_lookup : val :=\n    λ: \"t\" \"k\",\n      let: \"arr\" := Fst \"t\" in\n      let: \"n\" := Snd \"t\" in\n      let: \"b\" := !(Fst (\"arr\".[index \"k\" \"n\"])) in\n      (rec: \"go\" \"b\" :=\n            match: \"b\" with\n              NONE => NONE\n            | SOME \"kxb\" => let: \"k'\" := Fst (Fst \"kxb\") in\n                            let: \"x\" := Snd (Fst \"kxb\") in\n                            let: \"b\" := Snd \"kxb\" in\n                            if: equalf \"k\" \"k'\"\n                            then SOME \"x\"\n                            else \"go\" \"b\"\n            end) \"b\".\n\n  Definition table_remove : val :=\n    λ: \"t\" \"k\",\n      let: \"arr\" := Fst \"t\" in\n      let: \"n\" := Snd \"t\" in\n      let: \"bl\" := (\"arr\".[index \"k\" \"n\"]) in\n      let: \"b\" := Fst \"bl\" in\n      let: \"l\" := Snd \"bl\" in\n      acquire lck \"l\" ;;\n      let: \"res\" :=\n         (rec: \"go\" \"b\" :=\n            match: \"b\" with\n              NONE => NONE\n            | SOME \"kxb\" => let: \"k'\" := Fst (Fst \"kxb\") in\n                            let: \"x\" := Snd (Fst \"kxb\") in\n                            let: \"b\" := Snd \"kxb\" in\n                            if: equalf \"k\" \"k'\"\n                            then SOME (\"x\", \"b\")\n                            else match: \"go\" \"b\" with\n                                   NONE => NONE\n                                 | SOME \"p\" => SOME (Fst \"p\", SOME (\"k'\", \"x\", Snd \"p\"))\n                                 end\n            end) !\"b\" in\n      match: \"res\" with\n        NONE => release lck \"l\" ;; NONE\n      | SOME \"p\" => \"b\" <- Snd \"p\" ;;\n                    release lck \"l\" ;;\n                    SOME (Fst \"p\")\n      end.\n\n  Definition table_fold : val :=\n    λ: \"f\" \"t\" \"a\",\n      (rec: \"outer\" \"i\" \"a\" :=\n        if: \"i\" < (Snd \"t\") then\n          let: \"b\" := !(Fst ((Fst \"t\").[\"i\"])) in\n          let: \"a\" :=\n             (rec: \"inner\" \"b\" \"a\" :=\n                match: \"b\" with\n                  NONE => \"a\"\n                | SOME \"b\"\n                  => let: \"k\" := Fst (Fst \"b\") in\n                     let: \"x\" := Snd (Fst \"b\") in\n                     let: \"b\" := Snd \"b\" in\n                     let: \"a\" := \"f\" \"k\" \"x\" \"a\" in\n                     \"inner\" \"b\" \"a\"\n                end) \"b\" \"a\" in\n          \n          \"outer\" (\"i\" + #1) \"a\"\n        else\n          \"a\") #0 \"a\".\n  \n\n  Implicit Type m : map (list val).\n  Local Arguments content {_ _ _ _ _ _ _ _} _ _.\n  Local Arguments no_garbage {_ _ _ _ _ _} _.\n  Local Arguments have_keys {_ _ _ _ _ _} _.\n\n  Definition is_table N P t :=\n   (∃ arr refs locks, \n      ⌜t = (arr, #(length refs))%V⌝ ∗\n      ⌜length refs > 0⌝ ∗\n      ⌜length refs = length locks⌝ ∗\n      ([∗ list] i ↦ lr ∈ zip locks refs,\n        let '(l, r) := lr in\n        ∃ lname, is_lock lck (N.@(S i)) lname l (r ↦{1/2} -)) ∗\n      inv (N.@0)\n       (array arr (zip_with PairV (LitV ∘ LitLoc <$> refs) locks) ∗\n        ∃ m data,\n          ⌜table_wf m⌝ ∗\n          ⌜content m data⌝ ∗\n          ⌜no_garbage data⌝ ∗\n          ⌜have_keys data⌝ ∗\n          ⌜length data = length refs⌝ ∗\n          P m ∗ \n          [∗ list] rb ∈ zip refs data,\n           let '(r, b) := rb in\n           r ↦{1/2} bucket b))%I.\n  \n  Instance is_locks_persistent N `(lr : (val * B)) P:\n    PersistentP\n      (let (l, r) := lr in\n          ∃ γ, is_lock lck (N.@(S i)) γ l (P l r))%I.\n  Proof. destruct lr as [? ?]. typeclasses eauto. Qed.\n  \n  Global Instance is_table_persistent N P t : PersistentP (is_table N P t).\n  Proof. typeclasses eauto. Qed.\n  \n  Lemma create_table_spec N P n : n > 0 -> {{{P ∅}}} create_table #n {{{t, RET t ; is_table N P t}}}.\n  Proof.\n    iIntros (Hn Φ) \"HP HΦ\".\n    wp_lam. wp_bind (make_array _). iApply wp_wand.\n    iApply (make_array_spec _ #()). iIntros (arr) \"Harr\". wp_lam.   \n    \n    wp_for (fun i' : Z =>\n              ∃ locks refs (i : nat),\n                ⌜i' = i⌝ ∗\n                ⌜i = length refs⌝ ∗\n                ⌜i = length locks⌝ ∗\n                array arr (zip_with PairV (LitV ∘ LitLoc <$> refs) locks ++ replicate (n - i) #()) ∗\n                [∗ list] i ↦ lr ∈ zip locks refs,\n                  (lr.2) ↦{1/2} NONEV ∗\n                  ∃ lname, is_lock lck (N.@(S i)) lname (lr.1)\n                               ((lr.2) ↦{1/2}-))%I with \"[Harr]\". \n    - iExists [], [], 0. rewrite big_sepL_nil -minus_n_O /=. by iFrame.\n    - iIntros (i') \"% HInv\".\n      iDestruct \"HInv\" as (locks refs i) \"[% [% [% [Harr Hlr]]]]\".\n      simplify_eq. wp_alloc r as \"Hr\".\n      iDestruct (fractional_half_1 with \"Hr\") as \"[Hr1 Hr2]\". \n      wp_apply (newlock_spec _ _ (N.@(S (length refs))) with \"[Hr1]\") ; last first.\n      iIntros (lk lname) \"Hlk\".\n      wp_apply (array_store_spec _ _ (#r, lk) with \"[Harr]\") ; [|done|].\n      rewrite app_length replicate_length zip_with_length fmap_length. lia.\n      iIntros \"Harr\". iExists (locks ++ [lk]), (refs ++ [r]), (S (length refs)).\n      do 2 rewrite app_length. simpl.\n      do 3 (iSplit ; first (iPureIntro ; lia)).\n      iSplitL \"Harr\". rewrite fmap_app zip_with_app ; last by rewrite fmap_length.\n      rewrite {1}(plus_n_O (length refs))\n        -{1}(fmap_length (LitV ∘ LitLoc) refs)\n        -(zip_with_length_l_eq PairV (LitV ∘ LitLoc <$> refs) locks) ; last by rewrite fmap_length.\n      rewrite insert_app_r.\n      rewrite (_:n = S (pred n)) ; last lia.\n      rewrite -minus_Sn_m ; last lia.\n      rewrite replicate_S /= cons_middle app_assoc. iFrame.\n      rewrite zip_with_app ; last done.\n      iApply big_sepL_app. iFrame.\n      rewrite -plus_n_O zip_with_length_r_eq /= //. eauto.\n      eauto.\n    - iIntros \"HInv\". iDestruct \"HInv\" as (locks refs ?) \"[% [% [% [Harr Hlrs]]]]\".\n      iDestruct (big_sepL_sepL with \"Hlrs\") as \"[Hparts #Hlks]\".\n      simplify_eq. iMod (inv_alloc (N.@0) _  with \"[-HΦ]\") as \"#HInv\" ; last first.\n      wp_lam. iApply \"HΦ\". iExists arr, refs, locks.\n      repeat (iSplit ; first eauto).\n      repeat rewrite big_sepL_zip_with.\n      iApply (big_sepL_mono with \"Hlks\").\n      iIntros (i lk ?) \"Hlks\". iIntros (r ?).\n      iDestruct (\"Hlks\" $! r with \"[]\") as \"$\". done.\n      iExact \"HInv\".\n      iNext. rewrite -minus_n_n /= app_nil_r.\n      iFrame. iExists ∅, (replicate (length refs) []).\n      repeat (iSplit ; first eauto using table_wf_empty, content_empty, no_garbage_empty, have_keys_empty, replicate_length).\n      iFrame.\n      rewrite {2}(zip_with_flip _ refs).\n      repeat rewrite big_sepL_zip_with.\n      iApply (big_sepL_mono with \"Hparts\").\n      iIntros (i r ?) \"Hlrs\". iIntros (b Hb).\n      apply lookup_replicate in Hb. destruct Hb as [-> ?].\n      assert (is_Some (locks !! i)) as [lk ?].\n      { apply lookup_lt_is_Some. by rewrite -(_:length refs = length locks). }\n      iDestruct (\"Hlrs\" $! lk with \"[]\") as \"Hlr\" ; done.\n  Qed.\n  \n  Lemma index_spec (k : val) k' (n : nat) :\n    as_key k = Some k' ->\n    WP index k #n {{v, ⌜ v = #(Hash k' mod n)%nat⌝}}%I.\n  Proof.\n    intro HKey.\n    do 2 wp_lam.\n    wp_bind (hashf _).\n    iApply (wp_wand).\n    iApply (hash_spec _ _ HKey).\n    iIntros (h) \"%\".\n    iSimplifyEq.\n    iApply (wp_wand).\n    iApply (modulo_spec).\n    iIntros (f) \"%\". iPureIntro. simplify_eq.\n    by rewrite Z2Nat_inj_mod.\n  Qed.\n  \n  Lemma table_insert_spec N P Q k k' x t:\n    as_key k' = Some k ->\n    {{{is_table N P t ∗ ∀ m, P m ={⊤∖↑N}=∗ P (insert_val m k x) ∗ Q }}}\n      table_insert t k' x {{{RET #(); Q}}}.\n  Proof.\n    iIntros (Hkey Φ) \"[#HTable HPins] HΦ\".\n    iDestruct \"HTable\" as (arr refs locks) \"[% [% [% [Hlocks HInv]]]]\".\n    rename_last Hrefs_locks.\n    simplify_eq.\n    do 3 wp_lam. wp_proj. wp_lam. wp_proj. wp_lam. wp_bind (index _ _).\n    iApply wp_wand. iApply (index_spec _ _ _ Hkey).\n    iIntros (?) \"%\". simplify_eq. wp_bind (array_load _).\n    iInv (N.@0) as \"[Harr Hrest]\" \"HClose\".\n    assert (is_Some (locks !! (Hash k `mod` length refs))) as [lk Hlk].\n    { apply lookup_lt_is_Some. rewrite -Hrefs_locks.\n      apply mod_bound_pos. lia. done. }\n    assert (is_Some (refs !! (Hash k `mod` length refs))) as [r Hr].\n    { apply lookup_lt_is_Some. apply mod_bound_pos. lia. done. }\n    wp_apply (array_load_spec _ _ (#r, lk) (Hash k `mod` length refs) with \"Harr\").\n    by rewrite lookup_zip_with list_lookup_fmap Hlk Hr. \n    iIntros \"Harr\". iMod (\"HClose\" with \"[Harr Hrest]\") as \"_\"; first (iNext; iFrame).\n    iModIntro. wp_lam. wp_proj. wp_lam. wp_proj. wp_lam.\n    iDestruct (big_sepL_lookup _ _ _ (lk, r)  with \"Hlocks\") as (lname) \"Hlock\".\n    by erewrite lookup_zip_with, Hlk, Hr.\n    wp_apply (acquire_spec with \"Hlock\").\n    iIntros \"[Hlocked Hr1]\". iDestruct \"Hr1\" as (?) \"Hr1\".\n    wp_lam. wp_bind (! _)%E.\n    iInv (N.@0) as \"[Harr Hrest]\" \"HClose\".\n    iDestruct \"Hrest\" as (m data) \"[>% [>% [>% [>% [>% [HP Hrbs]]]]]]\".\n    rename_last Hdata_refs.\n    assert (is_Some (data !! (Hash k `mod` length refs))) as [b Hb].\n    { apply lookup_lt_is_Some. rewrite Hdata_refs.\n      apply mod_bound_pos. lia. done. }\n    iDestruct (big_sepL_lookup_acc _ _ _ (r, b) with \"Hrbs\") as \"[>Hr2 Hrbs]\".\n    by erewrite lookup_zip_with, Hr, Hb.\n    iDestruct (mapsto_agree with \"Hr1 Hr2\") as \"%\". simplify_eq.\n    wp_load.\n    iMod (\"HClose\" with \"[Harr HP Hr2 Hrbs]\") as \"_\".\n    iDestruct (\"Hrbs\" with \"Hr2\") as \"?\". iFrame. iExists m, data. iFrame. eauto.\n    iModIntro. clear dependent m data. wp_bind (_ <- _)%E.\n    iInv (N.@0) as \"[Harr Hrest]\" \"HClose\".\n    iDestruct \"Hrest\" as (m data) \"[>% [>% [>% [>% [>% [HP Hrbs]]]]]]\".\n    rename_last Hdata_refs.\n    assert (is_Some (data !! (Hash k `mod` length refs))) as [b' Hb'].\n    { apply lookup_lt_is_Some. rewrite Hdata_refs.\n      apply mod_bound_pos. lia. done. }\n    rewrite -{1}(take_drop_middle _ _ _ Hb') -{7}(take_drop_middle _ _ _ Hr).\n    repeat rewrite zip_with_app. repeat rewrite zip_with_cons.\n    iDestruct (big_sepL_app with \"Hrbs\") as \"[Htake Hdrop]\".\n    iDestruct (big_sepL_cons with \"Hdrop\") as \"[>Hr2 Hdrop]\".\n    iDestruct (mapsto_agree with \"Hr1 Hr2\") as \"%\". rename_last HbEq. rewrite HbEq.\n    iDestruct (fractional_half_2 with \"Hr1 Hr2\") as \"Hr\". apply _. wp_store.\n    iDestruct (\"HPins\" with \"HP\") as \"HPins\".\n    iDestruct (fupd_mask_mono _ (⊤ ∖ ↑N.@0) with \"HPins\") as \">[HP HQ]\". solve_ndisj.\n    iDestruct \"Hr\" as \"[Hr1 Hr2]\".\n    iMod (\"HClose\" with \"[-Hr1 HΦ Hlocked HQ]\") as \"_\".\n    {\n      iFrame. iExists (insert_val m k x), (insert_data _ _ data k (k', x)). iFrame. iNext.\n      iSplit. iPureIntro. by apply table_wf_insert_val.\n      iSplit. iPureIntro. eapply content_insert ; try first [done | apply _ | lia].\n      iSplit. iPureIntro. by apply no_garbage_insert.\n      iSplit. iPureIntro. by apply have_keys_insert.\n      iSplit. iPureIntro. by rewrite /insert_data insert_length.\n      erewrite <-(take_drop_middle (insert_data _ _ _ _ _)).\n      rewrite /insert_data take_insert ; last reflexivity.\n      rewrite drop_insert ; last lia.\n      rewrite -{12}(take_drop_middle _ _ _ Hr).\n      repeat rewrite zip_with_app. repeat rewrite zip_with_cons.\n      rewrite big_sepL_app big_sepL_cons Hdata_refs.\n      iFrame. rewrite /bucket -/(bucket ((k', x) :: b')). iApply \"Hr2\".\n      rewrite take_length take_length Hdata_refs //.\n      rewrite /insert_data /lookup_data Hdata_refs.\n      rewrite Hb' /=. apply list_lookup_insert.\n      rewrite Hdata_refs.\n      apply mod_bound_pos ; [lia|done].\n    }\n    iModIntro. wp_lam.\n    wp_apply (release_spec with \"[Hlocked Hr1]\"). iFrame \"Hlock Hlocked\".\n    eauto. iIntros. iApply (\"HΦ\" with \"HQ\").\n   \n    rewrite 2!take_length Hdata_refs //.\n  Qed.\n\n  Lemma table_remove_spec N P Q Q' k k' t:\n    as_key k' = Some k ->\n    {{{is_table N P t ∗\n       (∀ m,\n         ⌜m !! k = None⌝ -∗ P m ={⊤∖↑N}=∗ P m ∗ Q') ∧\n       ∀ m x xs,\n         ⌜m !! k = Some (x :: xs)⌝ -∗ P m ={⊤∖↑N}=∗ P (remove_val m k) ∗ Q k x}}}\n      table_remove t k'\n      {{{v x, RET v; ⌜v = NONEV⌝ ∗ Q' ∨ (⌜v = SOMEV x⌝ ∗ Q k x)}}}.\n  Proof.\n    iIntros (HKey Φ) \"[HTable HQ] HΦ\".\n    iDestruct \"HTable\" as (arr refs locks) \"[% [% [% [#Hlocks #HInv]]]]\".\n    rename_last Hrefs_locks. simplify_eq.\n    do 2 wp_lam. wp_proj. wp_lam. wp_proj. wp_lam.\n    wp_bind (index _ _). iApply wp_wand. iApply index_spec. exact HKey.\n    iIntros (?) \"%\". simplify_eq.\n    wp_bind (array_load _).\n    iInv (N.@0) as \"[Harr Hrest]\" \"HClose\".\n    assert (is_Some (locks !! (Hash k `mod` length refs))) as [lk Hlk].\n    { apply lookup_lt_is_Some. rewrite -Hrefs_locks.\n      apply mod_bound_pos. lia. done. }\n    assert (is_Some (refs !! (Hash k `mod` length refs))) as [r Hr].\n    { apply lookup_lt_is_Some. apply mod_bound_pos. lia. done. }\n    wp_apply (array_load_spec _ _ (#r, lk) (Hash k `mod` length refs) with \"Harr\").\n    by rewrite lookup_zip_with list_lookup_fmap Hlk Hr.\n    iIntros \"Harr\". iMod (\"HClose\" with \"[$Harr $Hrest]\") as \"_\".\n    iModIntro. wp_lam. wp_proj. wp_lam. wp_proj. wp_lam.\n    iDestruct (big_sepL_lookup _ _ _ (lk, r) with \"Hlocks\") as (lname) \"Hlock\".\n    erewrite lookup_zip_with, Hlk, Hr. reflexivity.\n    wp_apply (acquire_spec with \"Hlock\").\n    iIntros \"[Hlocked Hr1]\".\n    iDestruct \"Hr1\" as (?) \"Hr1\". wp_lam. wp_bind (! _)%E.\n    iInv (N.@0) as \"[Harr Hrest]\" \"HClose\".\n    iDestruct \"Hrest\" as (m data) \"[>% [>% [>% [>% [>% [HP Hrbs]]]]]]\".\n    rename_last Hdata_refs. rename_last HHKeys. rename_last HNG. rename_last Hcontent. rename_last Hwf.\n    assert (is_Some (data !! (Hash k `mod` length refs))) as [b Hb].\n    { apply lookup_lt_is_Some. rewrite (_:length data = length refs) ; last done.\n      apply mod_bound_pos. lia. done. }\n    iDestruct (big_sepL_lookup_acc _ _ _ (r, b) with \"Hrbs\") as \"[>Hr2 Hrbs]\".\n    by erewrite lookup_zip_with, Hr, Hb.\n    iDestruct (mapsto_agree with \"Hr1 Hr2\") as \"%\". simplify_eq.\n    wp_load.\n\n    iAssert (WP (rec: \"go\" \"b\"\n                 := match: \"b\" with\n                      InjL <> => InjL #()\n                    | InjR \"kxb\" =>\n                      let: \"k'\" := Fst (Fst \"kxb\") in\n                      let: \"x\" := Snd (Fst \"kxb\") in\n                      let: \"b\" := Snd \"kxb\" in\n                      if: (equalf k') \"k'\" then InjR (\"x\", \"b\")\n                      else match: \"go\" \"b\" with\n                             InjL <> => InjL #()\n                           | InjR \"p\" =>\n                             InjR (Fst \"p\", InjR (\"k'\", \"x\", Snd \"p\"))\n                           end\n                    end) (bucket b)\n                {{v,  ⌜(v = NONEV /\\ bucket_filter _ _ Hash k b = []) ∨\n                       (∃ k'' x b' b'',\n                           bucket_filter _ _ Hash k b = (k'', x)::b'' /\\\n                           v = SOMEV (x, bucket b') /\\\n                           b' = bucket_remove _ _ Hash k b)⌝}})%I as \"Hloop\".\n    { assert (Hsuff: b = [] ++ b) by done.\n      assert (Hpref: [] = bucket_filter _ _ Hash k []) by done.\n      revert Hsuff Hpref. generalize b at 2 3 4 5 6. generalize ([] : bucket_data) at 1 3.\n      intros b'' b' Hsuff Hpref. iRevert (b'' Hsuff Hpref).\n      iInduction b' as [|[k'' x] b'] \"IH\".\n      - iIntros. wp_rec. wp_match. iFrame. by iLeft.\n      - iIntros (b'') \"% %\". rename_last Hpref. simplify_eq. simpl.\n        pose proof (proj1 (Forall_lookup _ _) HHKeys _ _ Hb) as HKeysb.\n        rewrite ->Forall_app, Forall_cons in HKeysb.\n        destruct HKeysb as [? [[k''' Hkey'] ?]].\n        wp_rec. wp_match. wp_proj. wp_proj. wp_lam. do 2 wp_proj. wp_lam. wp_proj. wp_lam.\n        wp_bind (equalf _ _). iApply wp_wand. by iApply equal_spec.\n        iIntros (?) \"%\". simplify_eq.\n        case_bool_decide.\n        + simplify_eq. wp_if. iPureIntro. right.\n          exists k'', x, b'.\n          rewrite /bucket_filter /filter /= decide_True ; last done.\n          rewrite decide_True ; eauto.\n        + assert (as_key k'' ≠ Some k).\n          rewrite Hkey'. injection. intros <-. contradiction.\n          wp_if. wp_bind ((rec: _ _ := _) _)%E. iApply (wp_wand with \"[-]\").\n          iApply (\"IH\" $! (b'' ++ [(k'', x)])).\n          iPureIntro. by rewrite -app_assoc.\n          iPureIntro. unfold bucket_filter in *. rewrite filter_app -Hpref /=.\n          by rewrite /filter /= decide_False. \n          iIntros (?) \"%\". rename_last HInv.\n          decompose [and or ex] HInv. \n          * simplify_eq. wp_match. rewrite /bucket_filter /filter /= decide_False ; eauto.\n          * simplify_eq/=. wp_match. do 2 wp_proj. iFrame. iRight. iPureIntro.\n            eexists _ , _ , ((_,_)::_).\n            rewrite /bucket_filter /filter /= decide_False ; last done.\n            rewrite decide_False ; eauto.\n    }\n    assert (HlookupData: lookup_data _ Hash data k = b) by by rewrite /lookup_data Hdata_refs Hb.\n    \n    case_eq (m !! k) ; [intros [|x ?] Hx | intros HNone] ;\n      [destruct (Hwf _ _ Hx) as [? [? ?]] ; discriminate |..] ;\n      last (iDestruct \"HQ\" as \"[HQ' _]\" ; iDestruct (\"HQ'\" with \"[%] HP\") as \"HQ'\" ; try done ;\n            iDestruct (fupd_mask_mono _ (⊤ ∖ ↑N.@0) with \"HQ'\") as \">[HP HQ']\" ; try solve_ndisj).\n    all: iMod (\"HClose\" with \"[Harr HP Hr2 Hrbs]\") as \"_\" ;\n      try (iDestruct (\"Hrbs\" with \"Hr2\") as \"?\" ; iFrame ; iExists m, data ; iFrame ; eauto).\n    all: iModIntro ; wp_bind ((rec: _ _ := _) (bucket _))%E ; iApply (wp_wand with \"Hloop\") ;\n      iIntros (?) \"%\" ; rename_last HInv ;\n      destruct HInv as [[-> Hfilt] | [x' [k'' [? [? [Hfilt [-> ->]]]]]]].\n\n    all: destruct Hcontent as [Hin Hnin] ; try specialize (Hin _ _ Hx) ; try specialize (Hnin _ HNone).\n    all: try rewrite Hin HlookupData Hfilt /= in Hx ; try destruct (Hwf _ _ Hx) as [? [? ?]].\n    all: try by rewrite -HlookupData -Hnin in Hfilt.\n    - wp_lam. wp_match. wp_proj. wp_bind (_ <- _)%E.\n      iInv (N.@0) as \"[Harr Hrest]\" \"HClose\". clear dependent m data.\n      iDestruct \"Hrest\" as (m data) \"[>% [>% [>% [>% [>% [HP Hrbs]]]]]]\".\n      rename_last Hdata_refs. rename_last HHKeys. rename_last HNG. rename_last Hcontent.\n      assert (is_Some (data !! (Hash k `mod` length refs))) as [b' Hb'].\n      { apply lookup_lt_is_Some. rewrite Hdata_refs.\n        apply mod_bound_pos. lia. done. }\n      rewrite -{1}(take_drop_middle _ _ _ Hb') -{7}(take_drop_middle _ _ _ Hr).\n      repeat rewrite zip_with_app. repeat rewrite zip_with_cons.\n      iDestruct (big_sepL_app with \"Hrbs\") as \"[Htake Hdrop]\".\n      iDestruct (big_sepL_cons with \"Hdrop\") as \"[>Hr2 Hdrop]\".\n      iDestruct (mapsto_agree with \"Hr2 Hr1\") as \"%\".\n      rename_last HbEq. apply (inj bucket) in HbEq. simplify_eq.\n      iDestruct (fractional_half_2 with \"Hr1 Hr2\") as \"Hr\". apply _. wp_store.\n      iDestruct \"Hr\" as \"[Hr1 Hr2]\".\n      iDestruct \"HQ\" as \"[_ HQ]\". iDestruct (\"HQ\" with \"[%] HP\") as \"HQ\".\n      { assert (HlookupData: lookup_data _ Hash data k = b).\n        rewrite /lookup_data Hdata_refs Hb' //.\n        destruct Hcontent as [Hin Hnin]. case_eq (m !! k).\n        - intros ? Hlookup. rewrite (Hin _ _ Hlookup) HlookupData Hfilt //.\n        - intros Hn. rewrite -HlookupData -(Hnin _ Hn) // in Hfilt.\n      }\n      iDestruct (fupd_mask_mono _ (⊤ ∖ ↑N.@0) with \"HQ\") as \">[HP HQ]\". solve_ndisj.\n      iMod (\"HClose\" with \"[-Hr1 HΦ Hlocked HQ]\") as \"_\".\n      {\n        iFrame. iNext.\n        iExists (remove_val m k),\n        (<[Hash k mod length data := bucket_remove _ _ _ k (lookup_data _ _ data k)]>data).\n        iSplit. iPureIntro. by apply table_wf_remove_val.\n        iSplit. iPureIntro. eapply content_remove ; try first [done | apply _ | lia].\n        iSplit. iPureIntro. by apply no_garbage_remove.\n        iSplit. iPureIntro. by apply have_keys_remove.\n        iSplit. iPureIntro. by rewrite /insert_data insert_length.\n        erewrite <-(take_drop_middle (<[_ := _]> _)).\n        rewrite /insert_data take_insert ; last reflexivity.\n        rewrite drop_insert ; last lia.\n        rewrite -{12}(take_drop_middle _ _ _ Hr).\n        repeat rewrite zip_with_app. repeat rewrite zip_with_cons.\n        rewrite big_sepL_app big_sepL_cons Hdata_refs.\n        iFrame.\n        rewrite 2!take_length Hdata_refs //.\n        rewrite /insert_data /lookup_data Hdata_refs.\n        rewrite Hb' /= list_lookup_insert. done.\n        rewrite Hdata_refs. apply mod_bound_pos ; [lia|done].\n      }\n      iModIntro. wp_lam.\n      wp_apply (release_spec with \"[Hlocked Hr1]\"). iFrame \"Hlock Hlocked\". eauto.\n      iIntros \"_\". wp_lam. wp_proj. iApply \"HΦ\". eauto.\n      rewrite 2!take_length Hdata_refs //.\n    - wp_lam. wp_match. wp_apply (release_spec with \"[$Hlock $Hlocked Hr1]\").\n      eauto. iIntros \"_\". wp_lam. iApply \"HΦ\". iLeft. eauto.\n      Unshelve. exact #().\n  Qed.\n  \n  Lemma table_lookup_spec N P Q Q' k k' t:\n    as_key k' = Some k ->\n    {{{is_table N P t ∗\n       (∀ m,\n          ⌜m !! k = None⌝ -∗ P m ={⊤∖↑N}=∗ P m ∗ Q') ∧\n       ∀ m x xs,\n         ⌜m !! k = Some (x :: xs)⌝ -∗ P m ={⊤∖↑N}=∗ P m ∗ Q k x}}}\n      table_lookup t k'\n      {{{v x, RET v; ⌜v = NONEV⌝ ∗ Q' ∨ (⌜v = SOMEV x⌝ ∗ Q k x)}}}.\n  Proof.\n    iIntros (HKey Φ) \"[HTable HQ] HΦ\".\n    iDestruct \"HTable\" as (arr refs locks) \"[% [% [% [_ #Inv]]]]\".\n    rename_last Hrefs_locks. simplify_eq.\n    do 2 wp_lam. wp_proj. wp_lam. wp_proj. wp_lam.\n    wp_bind (index _ _). iApply wp_wand. iApply index_spec. exact HKey.\n    iIntros (?) \"%\". simplify_eq.\n    wp_bind (array_load _).\n    iInv (N.@0) as \"[Harr Hrest]\" \"HClose\".\n    assert (is_Some (locks !! (Hash k `mod` length refs))) as [lk Hlk].\n    { apply lookup_lt_is_Some. rewrite -Hrefs_locks.\n      apply mod_bound_pos. lia. done. }\n    assert (is_Some (refs !! (Hash k `mod` length refs))) as [r Hr].\n    { apply lookup_lt_is_Some. apply mod_bound_pos. lia. done. }\n    wp_apply (array_load_spec _ _ (#r, lk) (Hash k `mod` length refs) with \"Harr\").\n    by rewrite lookup_zip_with list_lookup_fmap Hlk Hr.\n    iIntros \"Harr\". iMod (\"HClose\" with \"[$Harr $Hrest]\") as \"_\".\n    iModIntro. wp_proj. wp_bind (! _)%E.\n    iInv (N.@0) as \"[Harr Hrest]\" \"HClose\".\n    iDestruct \"Hrest\" as (m data) \"[>% [>% [>% [>% [>% [HP Hrbs]]]]]]\".\n    rename_last Hdata_refs. rename_last HHKeys. rename_last HNG. rename_last Hcontent. rename_last Hwf.\n    assert (is_Some (data !! (Hash k `mod` length refs))) as [b Hb].\n    { apply lookup_lt_is_Some. rewrite (_:length data = length refs) ; last done.\n      apply mod_bound_pos. lia. done. }\n    iDestruct (big_sepL_lookup_acc _ _ _ (r, b) with \"Hrbs\") as \"[Hr1 Hrbs]\".\n    by erewrite lookup_zip_with, Hr, Hb.\n    wp_load.\n\n    iAssert\n      (WP (rec: \"go\" \"b\"\n           := match: \"b\" with\n                InjL <> => InjL #()\n              | InjR \"kxb\" =>\n                let: \"k'\" := Fst (Fst \"kxb\") in\n                let: \"x\" := Snd (Fst \"kxb\") in\n                let: \"b\" := Snd \"kxb\" in\n                if: (equalf k') \"k'\"\n                then InjR \"x\"\n                else \"go\" \"b\" end) \n          (bucket b)\n          {{ v, ⌜v = InjLV #() ∧ bucket_filter Σ Key Hash k b = [] ∨\n                (∃ (x k'' : val) b',\n                    v = InjRV x ∧\n                    bucket_filter Σ Key Hash k b = (k'', x)::b')⌝ }})%I as \"Hloop\".\n    {\n      assert (Hsuff: b = [] ++ b) by done.\n      assert (Hpref: [] = bucket_filter _ _ Hash k []) by done.\n      revert Hsuff Hpref. generalize b at 2 3 4 5. generalize ([] : bucket_data) at 1 3.\n      intros b'' b' Hsuff Hpref. iRevert (b'' Hsuff Hpref).\n      iInduction b' as [|[k'' x] b'] \"IH\".\n      - iIntros. wp_rec. wp_match. by iLeft.\n      - iIntros (b'') \"% %\".\n        rename_last Hpref. simplify_eq.\n        pose proof (proj1 (Forall_lookup _ _) HHKeys _ _ Hb) as HKeysb.\n        rewrite ->Forall_app, Forall_cons in HKeysb.\n        destruct HKeysb as [? [[k''' Hkey'] ?]].\n        wp_rec. wp_match. repeat first [wp_proj | wp_lam].\n        wp_bind (equalf _ _). iApply wp_wand. by iApply equal_spec.\n        iIntros (?) \"%\". simplify_eq.\n        case_bool_decide.\n        + simplify_eq.          \n          wp_if. iPureIntro. right.\n          exists x, k''.\n          rewrite /bucket_filter /filter /= decide_True ; eauto.\n        + wp_if.\n          assert (as_key k'' ≠ Some k).\n          rewrite Hkey'. injection. intros <-. contradiction.\n          iApply (wp_wand with \"[-]\"). iApply (\"IH\" $! (b'' ++ [(k'', x)])).\n          iPureIntro. by rewrite -app_assoc.\n          iPureIntro. unfold bucket_filter in *. rewrite filter_app -Hpref /=.\n          by rewrite /filter /= decide_False. \n          iIntros (?) \"%\". rename_last HInv.\n          decompose [and or ex] HInv. \n          * simplify_eq. rewrite /bucket_filter /filter /= decide_False ; eauto.\n          * simplify_eq. iPureIntro. right.\n            eexists _ , _ .\n            rewrite /bucket_filter /filter /= decide_False ; eauto. \n    }\n    assert (HlookupData: lookup_data _ Hash data k = b).\n    by rewrite /lookup_data Hdata_refs Hb.\n\n    case_eq (m !! k) ; [intros [|x ?] Hx | intros HNone] ;\n      [destruct (Hwf _ _ Hx) as [? [? ?]] ; discriminate |..] ;\n      [ iDestruct \"HQ\" as \"[_ HQ]\" | iDestruct \"HQ\" as \"[HQ _]\"] ;\n      iDestruct (\"HQ\" with \"[%] HP\") as \"HQ\" ; try done ;\n      iDestruct (fupd_mask_mono _ (⊤ ∖ ↑N.@0) with \"HQ\") as \">[HP HQ]\" ; try solve_ndisj.\n    all: iMod (\"HClose\" with \"[Harr HP Hr1 Hrbs]\") as \"_\" ;\n      try (iDestruct (\"Hrbs\" with \"Hr1\") as \"?\" ; iFrame ; iExists m, data ; iFrame ; eauto).\n    all: iModIntro ; wp_lam ; iApply (wp_wand with \"Hloop\") ;\n      iIntros (?) \"%\" ; rename_last HInv ;\n      destruct HInv as [[-> Hfilt] | [x' [k'' [? [-> Hfilt]]]]] ; iApply \"HΦ\".\n\n    all: destruct Hcontent as [Hin Hnin] ;\n      first [specialize (Hin _ _ Hx) ; clear Hnin | specialize (Hnin _ HNone)].\n    all: try rewrite Hin HlookupData Hfilt /= in Hx ; try by destruct (Hwf _ _ Hx) as [? [? ?]].\n    all: try rewrite -HlookupData -Hnin // in Hfilt.\n    - rewrite HlookupData Hfilt in Hin. injection Hin as ->. eauto.\n    - eauto. \n    Unshelve. all: exact #().\n  Qed.\n            \nEnd hashtable.", "meta": {"author": "esbengc", "repo": "iris-hashtable", "sha": "03d47d13b1d318a681175cf6c2697914d00a9675", "save_path": "github-repos/coq/esbengc-iris-hashtable", "path": "github-repos/coq/esbengc-iris-hashtable/iris-hashtable-03d47d13b1d318a681175cf6c2697914d00a9675/hashtable_conc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.22953429595699956}}
{"text": "Require Import Coq.Lists.List.\nFrom MetaCoq.Lob.Template Require Export QuoteGround.Coq.Init.\nImport ListNotations.\n\nLocal Notation iffT A B := (prod (A -> B) (B -> A)).\nLemma iff_forall_eq_some {A v P} : iffT match v return Type with Some v => P v | None => True end (forall a : A, v = Some a -> P a).\nProof.\n  split; destruct v; auto; intros ??; inversion 1; subst; assumption.\nDefined.\nLemma iff_forall_neq_nil {A} {v : list A} {P} : iffT match v return Type with nil => True | _ => P end (v <> nil -> P).\nProof.\n  split; destruct v; intuition congruence.\nDefined.\n#[export] Instance quote_forall_eq_some {A v P} {q : ground_quotable (match v return Type with Some v => P v | None => True end)} {qv : quotation_of v} {qA : quotation_of A} {qP : quotation_of P} : ground_quotable (forall a : A, v = Some a -> P a)\n  := ground_quotable_of_iffT iff_forall_eq_some.\n#[export] Instance quote_forall_neq_nil {A v P} {q : ground_quotable (match v return Type with nil => True | _ => P end)} {qv : quotation_of v} {qA : quotation_of A} {qP : quotation_of P} : ground_quotable (v <> @nil A -> P)\n  := ground_quotable_of_iffT iff_forall_neq_nil.\n#[export] Instance quote_is_true_or_l {b} {P : Prop} {qP : quotation_of P} {quoteP : ground_quotable P} : ground_quotable (is_true b \\/ P).\nProof.\n  apply quote_or_dec_l; try exact _; cbv [is_true]; decide equality.\nDefined.\n#[export] Instance quote_is_true_or_r {b} {P : Prop} {qP : quotation_of P} {quoteP : ground_quotable P} : ground_quotable (P \\/ is_true b).\nProof.\n  apply quote_or_dec_r; try exact _; cbv [is_true]; decide equality.\nDefined.\n\n#[export] Hint Cut [ ( _ *) quote_forall_eq_some ( _ * ) quote_forall_eq_some ] : typeclass_instances.\n#[export] Hint Cut [ ( _ *) quote_forall_neq_nil ( _ * ) quote_forall_neq_nil ] : typeclass_instances.\n", "meta": {"author": "JasonGross", "repo": "metacoq-lob", "sha": "acfc938eb79cac82c3c7d306f6d7010a4ad6492e", "save_path": "github-repos/coq/JasonGross-metacoq-lob", "path": "github-repos/coq/JasonGross-metacoq-lob/metacoq-lob-acfc938eb79cac82c3c7d306f6d7010a4ad6492e/theories/Template/QuoteGround/Coq/Misc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22953429595699948}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import AbsAccessor.Spec.\nRequire Import RealmTimerHandler.Spec.\nRequire Import RealmSyncHandlerAux.Specs.handle_timer_sysreg_trap.\nRequire Import RealmSyncHandlerAux.LowSpecs.handle_timer_sysreg_trap.\nRequire Import RealmSyncHandlerAux.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       ESR_EL2_SYSREG_IS_WRITE_spec\n       sysreg_write_spec\n       sysreg_read_spec\n    .\n\n  Lemma handle_sysreg_access_trap_spec_exists:\n    forall habd habd'  labd rec esr\n      (Hspec: handle_timer_sysreg_trap_spec rec esr habd = Some habd')\n      (Hrel: relate_RData habd labd),\n    exists labd', handle_timer_sysreg_trap_spec0 rec esr labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque\n          handle_vtimer_sysreg_write_spec\n          handle_ptimer_sysreg_write_spec\n          handle_vtimer_sysreg_read_spec\n          handle_ptimer_sysreg_read_spec.\n    intros. destruct Hrel. destruct rec.\n    unfold handle_timer_sysreg_trap_spec, handle_timer_sysreg_trap_spec0 in *.\n    repeat autounfold in *. simpl in *.\n    hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec;\n      repeat (repeat destruct_con; repeat destruct_dis); simpl in *; srewrite; repeat simpl_update_reg;\n        repeat (simpl_htarget; grewrite; simpl in *; try solve_bool_range);\n        try solve[eexists; split; [reflexivity|constructor; reflexivity]].\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RealmSyncHandler/RefProof/handle_sysreg_access_trap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22953429595699948}}
{"text": "Require Import Events.\nRequire Import Values.\nRequire Import AST.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import CoqlibC.\nRequire Import Skeleton.\nRequire Import ModSem.\nRequire Import SimSymb.\nRequire Import Integers.\nRequire Import ASTC.\nRequire Import Maps.\nRequire Import LinkingC.\n\nRequire Import Syntax Sem Mod ModSem.\nRequire Import SimMem SimModSem SimMod.\nRequire Import Sound SemProps.\n\nSet Implicit Arguments.\n\n\n\n\n\nModule ProgPair.\nSection PROGPAIR.\nContext `{SM: SimMem.class} {SS: SimSymb.class SM} {SU: Sound.class}.\n\n  Definition t := list ModPair.t.\n\n  Definition sim (pp: t) := List.Forall ModPair.sim pp.\n\n  Definition src (pp: t): program := List.map ModPair.src pp.\n  Definition tgt (pp: t): program := List.map ModPair.tgt pp.\n\n  (* Definition ss_link (pp: t): option SimSymb.t := link_list (List.map ModPair.ss pp). *)\n  (* ############ TODO: *)\n  (* ModPair.wf mp0 /\\ ModPair.wf mp1 /\\ link mp0.(src) mp1.(src) = Some /\\ link mp1.(tgt) mp1.(tgt) = Some *)\n  (* =================> link mp0.(ss) mp1.(ss) suceeds. *)\n  (* Move ModPair.wf into SimSymb and obligate its proof? *)\n\nEnd PROGPAIR.\nEnd ProgPair.\n\nHint Unfold ProgPair.sim ProgPair.src ProgPair.tgt.\n(* Hint Unfold ProgPair.ss_link. *)\n\n\n\n\n\n\nSection SIM.\nContext `{SM: SimMem.class} {SS: SimSymb.class SM} {SU: Sound.class}.\n\n  Variable pp: ProgPair.t.\n  Hypothesis SIMPROG: ProgPair.sim pp.\n  Let p_src := (ProgPair.src pp).\n  Let p_tgt := (ProgPair.tgt pp).\n\n\n\n  Theorem sim_link_sk\n          sk_link_src\n          (LOADSRC: (link_sk p_src) = Some sk_link_src)\n          (WF: forall md, In md p_src -> <<WF: Sk.wf md>>):\n      exists ss_link sk_link_tgt,\n        <<LOADTGT: (link_sk p_tgt) = Some sk_link_tgt>>\n        /\\ <<SIMSK: SimSymb.wf ss_link>>\n        /\\ <<SKSRC: ss_link.(SimSymb.src) = sk_link_src>>\n        /\\ <<SKTGT: ss_link.(SimSymb.tgt) = sk_link_tgt>>\n        /\\ <<LE: Forall (fun mp => (SimSymb.le mp.(ModPair.ss) ss_link)) pp>>.\n  Proof.\n    u. subst_locals. ginduction pp; ii; ss. destruct a; ss.\n    unfold ProgPair.src in *. unfold link_sk in *. ss. destruct (classic (t = [])).\n    { clarify; ss. cbn in *. clarify. clear IHt. inv SIMPROG. inv H2. inv H1. ss.\n      esplits; eauto. econs; eauto. ss. refl.\n    }\n    rename H into NNIL. eapply link_list_cons_inv in LOADSRC; cycle 1.\n    { destruct t; ss. }\n    des. rename sk_link_src into sk_link_link_src. rename restl into sk_link_src.\n    inv SIMPROG. exploit IHt; eauto. intro IH; des.\n    inv H1. ss. exploit (SimSymb.wf_link).\n    3: { rewrite SKSRC. eapply HD. }\n    all: eauto.\n    { rewrite SKSRC. eapply WF; et. }\n    { eapply link_list_preserves_wf_sk; eauto. }\n    { eapply SimSymb.wf_preserves_wf; et. rewrite SKSRC. eapply WF; et. }\n    { eapply SimSymb.wf_preserves_wf; et. eapply link_list_preserves_wf_sk; eauto. }\n    i; des. esplits; eauto.\n    - eapply link_list_cons; eauto.\n      rewrite SKTGT in LINKTGT. ss.\n    - econs; eauto. rewrite Forall_forall in *. ii.\n      all ltac:(fun H => apply link_list_linkorder in H). des.\n      rewrite Forall_forall in *. etrans; eauto.\n  Qed.\n\nEnd SIM.\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/proof/SimProg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22953429595699948}}
{"text": "Require Export Fiat.QueryStructure.Implementation.DataStructures.Bags.BagsInterface\n        Fiat.QueryStructure.Implementation.DataStructures.Bags.CountingListBags\n        Fiat.QueryStructure.Implementation.DataStructures.Bags.TreeBags\n        Fiat.QueryStructure.Specification.Representation.Tuple\n        Fiat.QueryStructure.Specification.Representation.Heading\n        Coq.Lists.List Coq.Program.Program\n        Fiat.Common.ilist.\nRequire Import Coq.Bool.Bool Coq.Strings.String\n        Coq.Structures.OrderedTypeEx Coq.NArith.BinNat\n        Coq.ZArith.ZArith_dec Coq.Arith.Arith\n        Coq.FSets.FMapAVL\n        Fiat.Common.Ensembles.EnsembleListEquivalence\n        Fiat.Common.String_as_OT\n        Fiat.Common.List.ListFacts\n        Fiat.Common.ilist2\n        Fiat.Common.Ensembles.IndexedEnsembles\n        Fiat.Common.DecideableEnsembles\n        Fiat.QueryStructure.Implementation.Operations.General.QueryRefinements\n        Fiat.QueryStructure.Implementation.Operations.General.EmptyRefinements\n        Fiat.QueryStructure.Specification.Representation.QueryStructureNotations\n        Fiat.Common.List.PermutationFacts\n        Fiat.Common.List.ListMorphisms\n        Fiat.QueryStructure.Specification.Operations.Delete\n        Fiat.QueryStructure.Implementation.Operations.General.DeleteRefinements\n        Fiat.QueryStructure.Implementation.Operations.List.ListQueryRefinements.\n\nUnset Implicit Arguments.\n\nDefinition TSearchTermMatcher (heading: RawHeading) := (@RawTuple heading -> bool).\n\nDefinition RawTupleEqualityMatcher\n           {heading: RawHeading}\n           (attr: Attributes heading)\n           (value: Domain heading attr)\n           {ens_dec: DecideableEnsemble (fun x : Domain heading attr => value = x)} :=\n  fun tuple => dec (tuple attr).\n\nDefinition RawTupleDisequalityMatcher\n           {heading: RawHeading}\n           (attr: Attributes heading)\n           (value: Domain heading attr)\n           {ens_dec: DecideableEnsemble (fun x : Domain heading attr => value = x)} :=\n  fun tuple => negb (dec (tuple attr)).\n\nModule NIndexedMap := FMapAVL.Make N_as_OT.\nModule ZIndexedMap := FMapAVL.Make Z_as_OT.\nModule NatIndexedMap := FMapAVL.Make Nat_as_OT.\nModule StringIndexedMap := FMapAVL.Make String_as_OT.\n\nModule NTreeBag := TreeBag NIndexedMap.\nModule ZTreeBag := TreeBag ZIndexedMap.\nModule NatTreeBag := TreeBag NatIndexedMap.\nModule StringTreeBag := TreeBag StringIndexedMap.\n\nDefinition NTreeType      := @NTreeBag.IndexedBag.\nDefinition ZTreeType      := @ZTreeBag.IndexedBag.\nDefinition NatTreeType    := @NatTreeBag.IndexedBag.\nDefinition StringTreeType := @StringTreeBag.IndexedBag.\n\nRecord ProperAttribute {heading} :=\n  {\n    Attribute : Attributes heading;\n    ProperlyTyped: { Domain heading Attribute = BinNums.N } + { Domain heading Attribute = BinNums.Z } +\n                   { Domain heading Attribute = nat } + { Domain heading Attribute = string }\n  }.\n\nDefinition ProperAttributeToFMap\n           {heading}\n           (pattr : @ProperAttribute heading)\n: Type -> Type :=\n  let (attr', cast) := pattr in\n  match cast with\n    | inleft (inleft (left cast'))  => @NTreeBag.IndexedBag\n    | inleft (inleft (right cast')) => @ZTreeBag.IndexedBag\n    | inleft (inright cast')         => @NatTreeBag.IndexedBag\n    | inright cast'                  => @StringTreeBag.IndexedBag\n  end.\n\nFixpoint NestedTreeFromAttributes\n         {heading}\n         (indices : list (@ProperAttribute heading))\n: Type :=\n  match indices with\n    | [] => @CountingList (@RawTuple heading)\n    | idx :: indices' =>\n      ProperAttributeToFMap idx (NestedTreeFromAttributes indices')\n  end.\n\nDefinition ProperAttributeToFMapKey\n           {heading}\n           (pattr : @ProperAttribute heading)\n: Type :=\n  let (attr', cast) := pattr in\n  match cast with\n    | inleft (inleft (left cast'))  => @NTreeBag.TKey\n    | inleft (inleft (right cast')) => @ZTreeBag.TKey\n    | inleft (inright cast')         => @NatTreeBag.TKey\n    | inright cast'                  => @StringTreeBag.TKey\n  end.\n\nFixpoint BuildSearchTermFromAttributes {heading}\n         (indices : list (@ProperAttribute heading))\n: Type :=\n  match indices with\n    | [] => (@RawTuple heading -> bool)\n    | idx :: indices' => prod (option (ProperAttributeToFMapKey idx)) (BuildSearchTermFromAttributes indices')\n  end.\n\nDefinition ProperAttribute_eq {heading}\n           (index : @ProperAttribute heading)\n           (k : ProperAttributeToFMapKey index)\n           (attr : Domain heading (Attribute index))\n: bool.\nProof.\n  destruct index; simpl in *.\n  destruct (ProperlyTyped0) as [ [ [ | ] | ]| ];\n    rewrite e in attr.\n  exact (if (N_eq_dec attr k) then true else false).\n  exact (if (Z_eq_dec attr k) then true else false).\n  exact (if (eq_nat_dec attr k) then true else false).\n  exact (if (string_dec attr k) then true else false).\nDefined.\n\nFixpoint SearchTermFromAttributesMatcher {heading}\n         (indices : list (@ProperAttribute heading))\n: BuildSearchTermFromAttributes indices -> @RawTuple heading -> bool :=\n  match indices return\n        BuildSearchTermFromAttributes indices -> @RawTuple heading -> bool\n  with\n    | nil => fun f tup => f tup\n    | index :: indices' =>\n      (fun (H : BuildSearchTermFromAttributes indices' -> @RawTuple heading -> bool)\n           (f : prod (option (ProperAttributeToFMapKey index))\n                     (BuildSearchTermFromAttributes indices'))\n           (tup : @RawTuple heading) =>\n         match f with\n           | (Some k, index') => (ProperAttribute_eq index k (GetAttributeRaw tup (Attribute index))) && (H index' tup)\n           | (None, index') => H index' tup\n         end) (SearchTermFromAttributesMatcher indices')\n  end.\n\n\nDefinition cast {T1 T2: Type} (eq: T1 = T2) (x: T1) : T2.\nProof.\n  subst; auto.\nDefined.\n\nDefinition ProperAttributeToBag\n           {heading}\n           TBag TSearchTerm TUpdateTerm\n           (TBagAsBag : Bag TBag (@RawTuple heading) TSearchTerm TUpdateTerm)\n           (pattr : @ProperAttribute heading)\n: Bag (ProperAttributeToFMap pattr TBag) (@RawTuple heading)\n      (prod (option (ProperAttributeToFMapKey pattr)) TSearchTerm) TUpdateTerm :=\n  match pattr as pattr' return\n        Bag (ProperAttributeToFMap pattr' TBag) (@RawTuple heading)\n            (prod (option (ProperAttributeToFMapKey pattr')) TSearchTerm) TUpdateTerm with\n    | {| Attribute := attr; ProperlyTyped := inleft (inleft (left cast')) |}\n      => NTreeBag.IndexedBagAsBag TBagAsBag (fun x => cast cast' (GetAttributeRaw x attr))\n    | {| Attribute := attr; ProperlyTyped := inleft (inleft (right cast')) |}\n      => ZTreeBag.IndexedBagAsBag TBagAsBag (fun x => cast cast' (GetAttributeRaw x attr))\n    | {| Attribute := attr; ProperlyTyped := inleft (inright cast') |}\n      => NatTreeBag.IndexedBagAsBag TBagAsBag (fun x => cast cast' (GetAttributeRaw x attr))\n    | {| Attribute := attr; ProperlyTyped := inright cast' |}\n      => StringTreeBag.IndexedBagAsBag TBagAsBag (fun x => cast cast' (GetAttributeRaw x attr))\n  end.\n\nFixpoint NestedTreeFromAttributesAsBag\n         heading\n         TUpdateTerm\n         (bupdate_transform : TUpdateTerm -> @RawTuple heading -> @RawTuple heading)\n         (indices : list (@ProperAttribute heading))\n: Bag (NestedTreeFromAttributes indices)\n      (@RawTuple heading)\n      (BuildSearchTermFromAttributes indices)\n      TUpdateTerm :=\n  match indices return\n        Bag (NestedTreeFromAttributes indices)\n            (@RawTuple heading)\n            (BuildSearchTermFromAttributes indices)\n            TUpdateTerm with\n    | [] => CountingListAsBag bupdate_transform\n    | idx :: indices' => ProperAttributeToBag\n                           _ _ _\n                           (NestedTreeFromAttributesAsBag heading _ bupdate_transform indices') idx\n  end.\n\nDefinition IndexedTreeUpdateTermType heading :=\n  @RawTuple heading -> @RawTuple heading.\n\nDefinition IndexedTreebupdate_transform heading\n           (upd : IndexedTreeUpdateTermType heading)\n\n: @RawTuple heading -> @RawTuple heading := upd.\n\nInstance NestedTreeFromAttributesAsBag'\n         {heading}\n         (indices : list (@ProperAttribute heading))\n: Bag (NestedTreeFromAttributes indices)\n      (@RawTuple heading)\n      (BuildSearchTermFromAttributes indices)\n      (IndexedTreeUpdateTermType heading) :=\n  NestedTreeFromAttributesAsBag\n    heading (IndexedTreeUpdateTermType heading)\n    (IndexedTreebupdate_transform heading)\n    indices.\n\nDefinition ProperAttributeToRepInv\n           {heading}\n           TBag TSearchTerm TUpdateTerm\n           (RepInv : TBag -> Prop)\n           (TBagAsBag : Bag TBag (@RawTuple heading) TSearchTerm TUpdateTerm)\n           (pattr : @ProperAttribute heading)\n: (@RawTuple heading -> ProperAttributeToFMapKey pattr)\n  -> ProperAttributeToFMap pattr TBag -> Prop  :=\n  match pattr as pattr' return\n        (@RawTuple heading -> ProperAttributeToFMapKey pattr')\n        -> ProperAttributeToFMap pattr' TBag -> Prop with\n    | {| Attribute := attr; ProperlyTyped := inleft (inleft (left cast')) |}\n      => NTreeBag.IndexedBag_RepInv TBagAsBag RepInv\n    | {| Attribute := attr; ProperlyTyped := inleft (inleft (right cast')) |}\n      => ZTreeBag.IndexedBag_RepInv TBagAsBag RepInv\n    | {| Attribute := attr; ProperlyTyped := inleft (inright cast') |}\n      => NatTreeBag.IndexedBag_RepInv TBagAsBag RepInv\n    | {| Attribute := attr; ProperlyTyped := inright cast' |}\n      => StringTreeBag.IndexedBag_RepInv TBagAsBag RepInv\n  end.\n\nDefinition ProperAttributeToProjection\n           {heading}\n           (pattr : @ProperAttribute heading)\n: @RawTuple heading -> ProperAttributeToFMapKey pattr :=\n  match pattr as pattr' return\n        @RawTuple heading -> ProperAttributeToFMapKey pattr' with\n    | {| Attribute := attr; ProperlyTyped := inleft (inleft (left cast')) |}\n      => fun x => cast cast' (GetAttributeRaw x attr)\n    | {| Attribute := attr; ProperlyTyped := inleft (inleft (right cast')) |}\n      => fun x => cast cast' (GetAttributeRaw x attr)\n    | {| Attribute := attr; ProperlyTyped := inleft (inright cast') |}\n      => fun x => cast cast' (GetAttributeRaw x attr)\n    | {| Attribute := attr; ProperlyTyped := inright cast' |}\n      => fun x => cast cast' (GetAttributeRaw x attr)\n  end.\n\nDefinition ProperAttributeToValidUpdate\n           {heading}\n           TBag TSearchTerm TUpdateTerm\n           (ValidUpdate : TUpdateTerm -> Prop)\n           (TBagAsBag : Bag TBag (@RawTuple heading) TSearchTerm TUpdateTerm)\n           (pattr : @ProperAttribute heading)\n: (@RawTuple heading -> ProperAttributeToFMapKey pattr)\n  -> TUpdateTerm -> Prop  :=\n  match pattr as pattr' return\n        (@RawTuple heading -> ProperAttributeToFMapKey pattr')\n        -> TUpdateTerm -> Prop with\n    | {| Attribute := attr; ProperlyTyped := inleft (inleft (left cast')) |}\n      => NTreeBag.IndexedBag_ValidUpdate TBagAsBag ValidUpdate\n    | {| Attribute := attr; ProperlyTyped := inleft (inleft (right cast')) |}\n      => ZTreeBag.IndexedBag_ValidUpdate TBagAsBag ValidUpdate\n    | {| Attribute := attr; ProperlyTyped := inleft (inright cast') |}\n      => NatTreeBag.IndexedBag_ValidUpdate TBagAsBag ValidUpdate\n    | {| Attribute := attr; ProperlyTyped := inright cast' |}\n      => StringTreeBag.IndexedBag_ValidUpdate TBagAsBag ValidUpdate\n  end.\n\nDefinition ProperAttributeToCorrectBag\n           {heading}\n           TBag TSearchTerm TUpdateTerm\n           (TBagAsBag : Bag TBag (@RawTuple heading) TSearchTerm TUpdateTerm)\n           (RepInv : TBag -> Prop)\n           (ValidUpdate : TUpdateTerm -> Prop)\n           (TBagAsCorrectBag : CorrectBag RepInv ValidUpdate TBagAsBag)\n           (pattr : @ProperAttribute heading)\n:  CorrectBag (ProperAttributeToRepInv _ _ _ RepInv TBagAsBag pattr\n                                       (ProperAttributeToProjection pattr))\n              (ProperAttributeToValidUpdate  _ _ _ ValidUpdate TBagAsBag pattr\n                                             (ProperAttributeToProjection pattr))\n              (ProperAttributeToBag TBag TSearchTerm TUpdateTerm TBagAsBag pattr) :=\n  match pattr as pattr' return\n        CorrectBag (ProperAttributeToRepInv _ _ _ RepInv TBagAsBag pattr'\n                                            (ProperAttributeToProjection pattr'))\n                   (ProperAttributeToValidUpdate  _ _ _ ValidUpdate TBagAsBag pattr'\n                                                  (ProperAttributeToProjection pattr'))\n                   (ProperAttributeToBag TBag TSearchTerm TUpdateTerm TBagAsBag pattr') with\n    | {| Attribute := attr; ProperlyTyped := inleft (inleft (left cast')) |}\n      => NTreeBag.IndexedBagAsCorrectBag TBagAsBag RepInv ValidUpdate TBagAsCorrectBag\n                                         (fun x => cast cast' (GetAttributeRaw x attr))\n    | {| Attribute := attr; ProperlyTyped := inleft (inleft (right cast')) |}\n      => ZTreeBag.IndexedBagAsCorrectBag TBagAsBag RepInv ValidUpdate TBagAsCorrectBag\n                                         (fun x => cast cast' (GetAttributeRaw x attr))\n    | {| Attribute := attr; ProperlyTyped := inleft (inright cast') |}\n      => NatTreeBag.IndexedBagAsCorrectBag TBagAsBag RepInv ValidUpdate TBagAsCorrectBag\n                                           (fun x => cast cast' (GetAttributeRaw x attr))\n    | {| Attribute := attr; ProperlyTyped := inright cast' |}\n      => StringTreeBag.IndexedBagAsCorrectBag TBagAsBag RepInv ValidUpdate TBagAsCorrectBag\n                                              (fun x => cast cast' (GetAttributeRaw x attr))\n  end.\n\nFixpoint ProperAttributesToRepInv\n         {heading}\n         TUpdateTerm\n         (bupdate_transform : TUpdateTerm -> @RawTuple heading -> @RawTuple heading)\n         (indices : list (@ProperAttribute heading))\n: NestedTreeFromAttributes indices -> Prop :=\n  match indices return NestedTreeFromAttributes indices -> Prop with\n    | [] => CountingList_RepInv\n    | idx :: indices' =>\n      ProperAttributeToRepInv _ _ TUpdateTerm\n                              (ProperAttributesToRepInv TUpdateTerm bupdate_transform indices')\n                              (NestedTreeFromAttributesAsBag heading TUpdateTerm bupdate_transform indices') idx\n                              (ProperAttributeToProjection idx)\n  end.\n\nFixpoint ProperAttributesToValidUpdate\n         {heading}\n         TUpdateTerm\n         (bupdate_transform : TUpdateTerm -> @RawTuple heading -> @RawTuple heading)\n         (indices : list (@ProperAttribute heading))\n: TUpdateTerm -> Prop :=\n  match indices return TUpdateTerm -> Prop with\n    | [] => CountingList_ValidUpdate\n    | idx :: indices' =>\n      ProperAttributeToValidUpdate _ _ TUpdateTerm\n                                   (ProperAttributesToValidUpdate TUpdateTerm bupdate_transform indices')\n                                   (NestedTreeFromAttributesAsBag heading TUpdateTerm bupdate_transform indices') idx\n                                   (ProperAttributeToProjection idx)\n  end.\n\nProgram Fixpoint NestedTreeFromAttributesAsCorrectBag\n        heading\n        TUpdateTerm\n        (bupdate_transform : TUpdateTerm -> @RawTuple heading -> @RawTuple heading)\n        (indices : list (@ProperAttribute heading))\n: CorrectBag (ProperAttributesToRepInv TUpdateTerm bupdate_transform indices)\n             (ProperAttributesToValidUpdate TUpdateTerm bupdate_transform indices)\n             (NestedTreeFromAttributesAsBag heading TUpdateTerm\n                                            bupdate_transform indices) :=\n  match indices return\n        CorrectBag (ProperAttributesToRepInv TUpdateTerm bupdate_transform indices)\n                   (ProperAttributesToValidUpdate TUpdateTerm bupdate_transform indices)\n                   (NestedTreeFromAttributesAsBag heading TUpdateTerm\n                                                  bupdate_transform indices) with\n    | [] => CountingListAsCorrectBag bupdate_transform\n    | idx :: indices' =>\n      ProperAttributeToCorrectBag\n        _ _ _\n        (NestedTreeFromAttributesAsBag heading TUpdateTerm bupdate_transform indices')\n        (ProperAttributesToRepInv TUpdateTerm bupdate_transform indices')\n        (ProperAttributesToValidUpdate TUpdateTerm bupdate_transform indices')\n        (NestedTreeFromAttributesAsCorrectBag heading TUpdateTerm bupdate_transform\n                                              indices')\n        idx\n  end.\n\nLemma bupdate_transform_NestedTree :\n  forall heading\n         TUpdateTerm\n         (bupdate_transform' : TUpdateTerm -> @RawTuple heading -> @RawTuple heading)\n         (indices : list (@ProperAttribute heading)),\n    bupdate_transform\n      (Bag := NestedTreeFromAttributesAsBag _ _ bupdate_transform' indices) =\n    bupdate_transform'.\nProof.\n  induction indices; simpl; eauto.\n  destruct a as [attr [ [ [s | s] | s] | s ] ]; simpl in *; eauto.\nQed.\n\nLemma KeyPreservingUpdateFAsUpdateTermOK {heading}\n: forall (indices indices' : list (@ProperAttribute heading))\n         (f : @RawTuple heading -> @RawTuple heading),\n    (forall a, List.In a indices -> List.In a indices')\n    -> (forall K tup,\n          List.In K indices'\n          -> GetAttributeRaw (f tup) (@Attribute _ K) = GetAttributeRaw tup (@Attribute _ K))\n    -> ProperAttributesToValidUpdate (@RawTuple heading -> @RawTuple heading)\n                                     (fun upd tup => upd tup)\n                                     indices f.\nProof.\n  induction indices; simpl; intuition.\n  - unfold CountingList_ValidUpdate; auto.\n  - destruct a as [attr [ [ [s | s] | s] | s ] ]; simpl in *.\n    + unfold NTreeBag.IndexedBag_ValidUpdate; intuition.\n      eapply (IHindices indices'); eauto.\n      rewrite bupdate_transform_NestedTree, <- H1.\n      erewrite (H0 {| Attribute := attr; ProperlyTyped := inleft (inleft in_left) |});\n        simpl; eauto.\n    + unfold ZTreeBag.IndexedBag_ValidUpdate; intuition.\n      eapply (IHindices indices'); eauto.\n      rewrite bupdate_transform_NestedTree, <- H1.\n      erewrite (H0 {| Attribute := attr; ProperlyTyped := inleft (inleft in_right) |});\n        simpl; eauto.\n    + unfold NatTreeBag.IndexedBag_ValidUpdate; intuition.\n      eapply (IHindices indices'); eauto.\n      rewrite bupdate_transform_NestedTree, <- H1.\n      erewrite (H0 {| Attribute := attr; ProperlyTyped := inleft (inright s) |});\n        simpl; eauto.\n    + unfold StringTreeBag.IndexedBag_ValidUpdate; intuition.\n      eapply (IHindices indices'); eauto.\n      rewrite bupdate_transform_NestedTree, <- H1.\n      erewrite (H0 {| Attribute := attr; ProperlyTyped := inright s |});\n        simpl; eauto.\nQed.\n\nInstance NestedTreeFromAttributesAsCorrectBag_UpdateF\n         {heading}\n         (indices : list (@ProperAttribute heading))\n: CorrectBag (ProperAttributesToRepInv _ _ indices)\n             (ProperAttributesToValidUpdate _ _ indices)\n             (NestedTreeFromAttributesAsBag heading\n                                            (@RawTuple heading -> @RawTuple heading)\n                                            (fun upd tup => upd tup)\n                                            indices)\n  := NestedTreeFromAttributesAsCorrectBag heading _ _ _ .\n\nDefinition NestedTreeFromAttributesAsCorrectBagPlusProof\n           {heading}\n           (indices : list (@ProperAttribute heading))\n: BagPlusProof (@RawTuple heading) :=\n  {| CorrectBagPlus := (NestedTreeFromAttributesAsCorrectBag_UpdateF indices) |}.\n\nDefinition CheckType {heading} (attr: Attributes heading) (rightT: _) :=\n  {| Attribute := attr; ProperlyTyped := rightT |}.\n\n\n(* An equivalence relation between Ensembles of RawTuples and Bags\n   which incorporates the bag's representation invariant. *)\n\nDefinition EnsembleBagEquivalence\n           {heading : RawHeading}\n           (bagplus : BagPlusProof (@RawTuple heading))\n           (ens : Ensemble (@IndexedRawTuple heading))\n           (store : BagTypePlus bagplus)\n: Prop :=\n  ens ≃ benumerate (Bag := BagPlus bagplus) store /\\\n  RepInvPlus bagplus store.\n\nInstance EnsembleIndexedTreeEquivalence_AbsR\n         {heading : RawHeading}\n         {bagplus : BagPlusProof (@RawTuple heading)}\n: @UnConstrRelationAbsRClass (@IndexedRawTuple heading) (BagTypePlus bagplus) :=\n  {| UnConstrRelationAbsR := EnsembleBagEquivalence bagplus |}.\n\n(* We now prove that [empty] is a valid abstraction of the\n   empty database. *)\n\nLemma bempty_correct_DB :\n  forall {TContainer TSearchTerm TUpdateTerm : Type}\n         {db_schema : RawQueryStructureSchema}\n         {index : Fin.t _}\n         {store_is_bag : Bag TContainer RawTuple TSearchTerm TUpdateTerm}\n         (RepInv : TContainer -> Prop)\n         (ValidUpdate : TUpdateTerm -> Prop),\n    CorrectBag RepInv ValidUpdate store_is_bag\n    -> EnsembleIndexedListEquivalence\n         (GetUnConstrRelation (imap2 rawRel (Build_EmptyRelations (qschemaSchemas db_schema))) index)\n         (benumerate bempty).\nProof.\n  intros.\n  erewrite benumerate_empty_eq_nil by eauto.\n  apply EnsembleIndexedListEquivalence_Empty.\nQed.\n\nCorollary bemptyPlus_correct_DB :\n  forall {db_schema : RawQueryStructureSchema}\n         {index : Fin.t _}\n         {bag_plus : BagPlusProof (@RawTuple _)},\n    GetUnConstrRelation (imap2 rawRel (Build_EmptyRelations (qschemaSchemas db_schema))) index ≃\n                        bempty (Bag := BagPlus bag_plus).\nProof.\n  destruct bag_plus; intros; simpl; constructor.\n  eapply bempty_correct_DB; eauto.\n  apply bempty_RepInv.\nQed.\n\n(* We now prove that [binsert] is a valid abstraction of the\n   adding a tuple to the ensemble modeling the database. *)\n\n\nLemma binsert_correct_DB\n      db_schema qs index\n      (bag_plus : BagPlusProof (@RawTuple _))\n:  forall (store: BagTypePlus bag_plus),\n     GetUnConstrRelation qs index ≃ store\n     -> forall tuple bound\n               (ValidBound : UnConstrFreshIdx (GetUnConstrRelation qs index) bound),\n          EnsembleIndexedListEquivalence\n            (GetUnConstrRelation\n               (@UpdateUnConstrRelation db_schema qs index\n                                        (EnsembleInsert\n                                           {| elementIndex := bound;\n                                              indexedElement := tuple |}\n                                           (GetUnConstrRelation qs index))) index)\n            (benumerate (binsert (Bag := BagPlus bag_plus) store tuple)).\nProof.\n  intros * store_eqv; destruct store_eqv as (store_eqv, store_WF).\n  unfold EnsembleIndexedTreeEquivalence_AbsR, UnConstrFreshIdx,\n  EnsembleBagEquivalence, EnsembleIndexedListEquivalence,\n  UnIndexedEnsembleListEquivalence, EnsembleListEquivalence in *.\n\n  setoid_rewrite get_update_unconstr_eq.\n  setoid_rewrite in_ensemble_insert_iff.\n  setoid_rewrite NoDup_modulo_permutation.\n  split; intros.\n\n  unfold UnConstrFreshIdx; exists (S bound); intros; intuition; subst; simpl.\n  unfold EnsembleInsert in *; intuition; subst; simpl; omega.\n  (* erewrite binsert_enumerate_length by eauto with typeclass_instances.\n    intuition; subst;\n    [ | apply lt_S];\n    intuition. *)\n\n  destruct store_eqv as (indices & [ l' (map & equiv & nodup ) ]); eauto.\n\n  destruct (permutation_map_cons indexedElement (binsert_enumerate tuple store store_WF)\n                                 {| elementIndex := bound;\n                                    indexedElement := tuple |} l' eq_refl map)\n    as [ l'0 (map' & perm) ].\n\n  exists l'0.\n  split; [ assumption | split ].\n\n  setoid_rewrite perm; setoid_rewrite equiv;\n  simpl; intuition eauto.\n\n  eexists (bound :: _); split; try apply perm; eauto.\n\n  constructor; eauto.\n  unfold not; intros.\n  rewrite in_map_iff in H0; destruct_ex; intuition; subst.\n  apply equiv in H3; apply H in H3; destruct x; simpl in *; omega.\n\n  setoid_rewrite perm; reflexivity.\nQed.\n\nCorollary binsertPlus_correct_DB :\n  forall {db_schema : RawQueryStructureSchema}\n         qs\n         (index : Fin.t _)\n         (bag_plus : BagPlusProof RawTuple)\n         store,\n    GetUnConstrRelation qs index ≃ store\n    -> forall\n      tuple bound\n      (ValidBound : UnConstrFreshIdx (GetUnConstrRelation qs index) bound),\n      GetUnConstrRelation\n        (@UpdateUnConstrRelation db_schema qs index\n                                 (EnsembleInsert\n                                    {| elementIndex := bound;\n                                       indexedElement := tuple |}\n                                    (GetUnConstrRelation qs index))) index\n        ≃ binsert (Bag := BagPlus bag_plus) store tuple.\nProof.\n  simpl; intros; constructor.\n  - eapply binsert_correct_DB; eauto.\n  - eapply binsert_RepInv; apply H.\nQed.\n\nLemma bdelete_correct_DB_fst {qsSchema}\n: forall (qs : UnConstrQueryStructure qsSchema)\n         (Ridx : Fin.t _)\n         bag_plus\n         bag\n         (equiv_bag : EnsembleBagEquivalence bag_plus (GetUnConstrRelation qs Ridx) bag)\n         (DT : Ensemble RawTuple)\n         (DT_Dec : DecideableEnsemble DT)\n         search_term,\n    ExtensionalEq (@dec _ _ DT_Dec)\n                  (bfind_matcher (Bag := BagPlus bag_plus) search_term)\n    -> refine {x | QSDeletedTuples qs Ridx DT x}\n              (ret (fst (bdelete bag search_term))).\nProof.\n  intros; setoid_rewrite DeletedTuplesFor; auto.\n  destruct equiv_bag as [ [ [bound ValidBound] [l [eq_bag [NoDup_l equiv_l] ] ] ] RepInv_bag];\n    subst.\n  rewrite refine_List_Query_In.\n  rewrite refine_List_Query_In_Where, refine_List_For_Query_In_Return_Permutation,\n  (filter_by_equiv _ _ H), map_id, <- partition_filter_eq.\n  rewrite refine_pick_val.\n  reflexivity.\n  destruct (bdelete_correct bag search_term RepInv_bag) as [_ Perm_bdelete];\n    eauto.\n\n  unfold BagPlusProofAsBag, QSGetNRelSchemaHeading, GetNRelSchemaHeading,\n  GetNRelSchema in *.\n  rewrite Perm_bdelete; reflexivity.\n  econstructor.\n  eexists _; eauto.\n  unfold UnIndexedEnsembleListEquivalence; eexists; eauto.\nQed.\n\nLemma bdelete_correct_DB_snd\n      db_schema qs index\n      (bag_plus : BagPlusProof RawTuple)\n:  forall (store: BagTypePlus bag_plus),\n     GetUnConstrRelation qs index ≃ store\n     -> forall (DeletedRawTuples : Ensemble RawTuple)\n               (DT_Dec : DecideableEnsemble DeletedRawTuples),\n          EnsembleIndexedListEquivalence\n            (GetUnConstrRelation\n               (@UpdateUnConstrRelation db_schema qs index\n                                        (EnsembleDelete (GetUnConstrRelation qs index)\n                                                        DeletedRawTuples)) index)\n            (snd (List.partition (@dec _ _ DT_Dec)\n                                 (benumerate store))).\nProof.\n  simpl; unfold EnsembleDelete, EnsembleBagEquivalence, Ensembles.In, Complement; simpl;\n  unfold EnsembleIndexedListEquivalence, UnIndexedEnsembleListEquivalence,\n  EnsembleListEquivalence; intros; intuition; destruct_ex; intuition; subst.\n  repeat setoid_rewrite get_update_unconstr_eq; simpl; intros.\n  exists x0.\n  unfold UnConstrFreshIdx in *; intros; apply H; destruct H3; eauto.\n  exists (snd (partition (@dec IndexedRawTuple (fun t => DeletedRawTuples (indexedElement t)) _ ) x)); intuition.\n  - unfold BagPlusProofAsBag; rewrite <- H2.\n    repeat rewrite partition_filter_neq.\n    clear; induction x; simpl; eauto.\n    unfold indexedRawTuple in *;\n      find_if_inside; simpl; eauto; rewrite <- IHx; reflexivity.\n  - rewrite get_update_unconstr_eq in H3.\n    destruct H3; unfold In in *.\n    apply H0 in H3; eapply In_partition in H3; intuition; try apply H6.\n    apply In_partition_matched in H6; apply dec_decides_P in H6; exfalso; eauto.\n  - rewrite get_update_unconstr_eq; constructor.\n    eapply H0; eapply In_partition; eauto.\n    unfold In; intros.\n    apply In_partition_unmatched in H3.\n    simpl in *; apply dec_decides_P in H5.\n    unfold indexedRawTuple, GetNRelSchema in *;\n      rewrite H3 in H5; congruence.\n  - revert H4; clear; induction x; simpl; eauto.\n    intros; inversion H4; subst.\n    case_eq (partition (fun x0 => @dec IndexedRawTuple (fun t => DeletedRawTuples (indexedElement t)) _ x0) x); intros; simpl in *; rewrite H.\n    rewrite H in IHx; apply IHx in H2;\n    case_eq (@dec IndexedRawTuple (fun t => DeletedRawTuples (indexedElement t)) _ a);\n    intros; simpl in *; rewrite H0; simpl; eauto.\n    constructor; eauto.\n    unfold not; intros; apply H1.\n    generalize l l0 H H3; clear; induction x; simpl; intros.\n    + injections; simpl in *; eauto.\n    + case_eq (partition (fun x0 : IndexedRawTuple => dec (indexedRawTuple x0)) x).\n      intros; rewrite H0 in H; find_if_inside; injections.\n      eauto.\n      simpl in H3; intuition.\n      eauto.\nQed.\n\nLemma bdeletePlus_correct_DB_snd\n      db_schema qs index\n      bag_plus\n:  forall (store: BagTypePlus bag_plus),\n     EnsembleBagEquivalence bag_plus (GetUnConstrRelation qs index) store\n     -> forall (DeletedRawTuples : Ensemble RawTuple)\n               (DT_Dec : DecideableEnsemble DeletedRawTuples)\n               search_term,\n          ExtensionalEq (@dec _ _ DT_Dec)\n                        (bfind_matcher (Bag := BagPlus bag_plus) search_term)\n          -> EnsembleBagEquivalence\n               bag_plus\n               (GetUnConstrRelation\n                  (@UpdateUnConstrRelation db_schema qs index\n                                           (EnsembleDelete (GetUnConstrRelation qs index)\n                                                           DeletedRawTuples)) index)\n               (snd (bdelete store search_term)).\nProof.\n  intros; unfold ExtensionalEq, EnsembleBagEquivalence in *.\n  unfold EnsembleBagEquivalence.\n  repeat rewrite get_update_unconstr_eq; simpl; intros.\n\n  split;\n    [\n      | eapply bdelete_RepInv; intuition ].\n  simpl in *;\n    unfold EnsembleListEquivalence, EnsembleIndexedListEquivalence,\n    UnConstrFreshIdx, EnsembleDelete, Complement in *; intuition; destruct_ex; intuition; intros.\n  exists x; intros; eapply H; destruct H1; unfold List.In in *; eauto.\n  unfold UnIndexedEnsembleListEquivalence, EnsembleListEquivalence in *.\n  generalize (bdelete_correct store search_term H2); destruct_ex; intuition.\n  rewrite partition_filter_neq in H1.\n  unfold BagPlusProofAsBag in *; simpl in *; rewrite <- H4 in H1.\n  clear H6 H H2 H4.\n  remember (GetUnConstrRelation qs index) as u.\n  generalize DeletedRawTuples DT_Dec x0 u H1 H0 H3 H7; clear.\n  induction (benumerate (snd (bdelete store search_term))); intros.\n  - eexists []; simpl; intuition.\n    + destruct H; destruct H2; unfold In in *.\n      apply H3 in H.\n      apply Permutation_nil in H1.\n      apply dec_decides_P; rewrite H0.\n      revert H1 H; clear; induction x0; simpl; eauto.\n      case_eq (bfind_matcher (Bag := BagPlus bag_plus) search_term (indexedElement a)); simpl; intros.\n      intuition; subst; eauto.\n      discriminate.\n    + constructor.\n  - assert (exists a',\n              List.In a' x0 /\\ indexedElement a' = a\n              /\\ (bfind_matcher (Bag := BagPlus bag_plus) search_term (indexedElement a') = false)).\n    generalize (@Permutation_in _ _ _ a H1 (or_introl (refl_equal _))).\n    rewrite filter_map; clear; induction x0; simpl;\n    intuition.\n    revert H;\n      case_eq (bfind_matcher (Bag := BagPlus bag_plus) search_term (indexedElement a0)); simpl; intros; eauto.\n    apply IHx0 in H0; destruct_ex; intuition eauto.\n    subst; intuition eauto.\n    destruct_ex; intuition eauto.\n    destruct_ex.\n    assert (exists x0',\n              Permutation x0 (x :: x0') /\\\n              ~ List.In x x0').\n    {\n      intuition; subst.\n      repeat rewrite filter_map; generalize x H2 H7; clear;\n      induction x0; intros; simpl in *|-; intuition; subst; eauto.\n      inversion H7; subst; exists x0; intuition.\n      apply H1; apply in_map_iff; eexists; eauto.\n      inversion H7; subst.\n      destruct (IHx0 _ H H3); intuition; eexists (a :: x1).\n      rewrite H1; intuition.\n      constructor.\n      simpl in H0; intuition; subst; eauto.\n      apply H2; apply in_map_iff; eexists; eauto.\n    }\n    destruct_ex; intuition; subst.\n    rewrite filter_map in H1; rewrite H in H1; simpl in *.\n    rewrite H8 in *; simpl in *.\n    destruct (IHl DeletedRawTuples DT_Dec x1\n                  (fun tup => Ensembles.In _ u tup /\\ tup <> x)); eauto;\n    clear IHl.\n    + rewrite filter_map; eapply Permutation_cons_inv; eauto.\n    + intuition; intros.\n      destruct H2; apply H3 in H2.\n      eapply Permutation_in in H; eauto.\n      simpl in *; intuition.\n      constructor.\n      eapply H3.\n      symmetry in H; eapply Permutation_in; eauto.\n      simpl; eauto.\n      intros; subst; simpl; congruence.\n    + assert (NoDup (map elementIndex (x :: x1))).\n      eapply NoDup_Permutation_rewrite.\n      eapply Permutation_map; eauto.\n      eauto.\n      inversion H2; subst; eauto.\n    + eexists (x :: x2); simpl; intuition.\n      * rewrite H5; auto.\n      * unfold In in H9; inversion H9; subst; unfold In in *.\n        apply H3 in H11; pose proof (Permutation_in _ H H11).\n        simpl in H5; intuition.\n        right; apply Permutation_cons_inv in H1.\n        eapply H2; econstructor; unfold In; intuition.\n        apply H3 in H11; eauto.\n        subst; eauto.\n      * subst; unfold In in *.\n        constructor; unfold In.\n        apply H3.\n        eapply Permutation_in; eauto.\n        rewrite <- H0 in H8; intros; apply dec_decides_P in H5; congruence.\n      * unfold In; constructor.\n        apply H2 in H11; inversion H11; subst; unfold In in *; intuition.\n        unfold In in *.\n        intros; apply dec_decides_P in H9; subst.\n        apply Permutation_cons_inv in H1.\n        assert (List.In (indexedElement x3) (map indexedElement x2)) as in_x2' by\n              (rewrite in_map_iff; eauto);\n          pose proof (Permutation_in (indexedElement x3) H1 in_x2').\n        rewrite in_map_iff in H5; destruct_ex; intuition.\n        rewrite filter_In in H13; intuition; subst.\n        rewrite <- H0, H12, H9 in H14; discriminate.\n      * constructor; eauto.\n        intro In_x; subst; apply Permutation_cons_inv in H1.\n        pose proof (permutation_map_base _ H1 _  (refl_equal _));\n          destruct_ex; intuition.\n        rewrite in_map_iff in *; destruct_ex; intuition.\n        apply H2 in H13; inversion H13; subst; unfold In in *; intuition.\n        apply H3 in H15.\n        pose proof (Permutation_in _ H H15); simpl in *; intuition.\n        assert (~ List.In (elementIndex x) (map elementIndex x1)).\n        { eapply Permutation_map with (f := elementIndex) in H.\n          pose proof (NoDup_Permutation_rewrite _ _ H H7).\n          simpl in *; inversion H5; subst; eauto.\n        }\n        apply H5; rewrite in_map_iff; eexists; split; eauto.\nQed.\n\nArguments bdelete : simpl never.\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/QueryStructure/Implementation/DataStructures/Bags/BagsOfTuples.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241911813151, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.2295307021500839}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.ZArith.ZArith.\nRequire Import riscv.Utility.Monads.\nRequire Import riscv.Utility.MonadNotations.\nRequire Export riscv.Utility.FreeMonad.\nRequire Import riscv.Spec.Decode.\nRequire Import riscv.Spec.Machine.\nRequire Import riscv.Utility.Utility.\nRequire Import riscv.Spec.Primitives.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import coqutil.Datatypes.List.\nRequire Import coqutil.Datatypes.ListSet.\nRequire Export riscv.Platform.RiscvMachine.\nRequire Export riscv.Platform.MaterializeRiscvProgram.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Map.Properties.\nRequire Import coqutil.Word.Properties.\nRequire Import coqutil.Datatypes.PropSet.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import coqutil.Tactics.fwd.\nRequire Import riscv.Platform.Sane.\n\nLocal Open Scope Z_scope.\nLocal Open Scope bool_scope.\n\nSection Riscv.\n  Import free.\n  Context {width: Z} {BW: Bitwidth width} {word: word width} {word_ok: word.ok word}.\n  Context {Mem: map.map word byte} {Registers: map.map Register word}.\n\n  Add Ring wring : (word.ring_theory (word := word))\n      (preprocess [autorewrite with rew_word_morphism],\n       morphism (word.ring_morph (word := word)),\n       constants [word_cst]).\n\n  Definition store(n: nat)(ctxid: SourceType) a v mach post :=\n    match Memory.store_bytes n mach.(getMem) a v with\n    | Some m => post (withXAddrs (invalidateWrittenXAddrs n a mach.(getXAddrs)) (withMem m mach))\n    | None => False\n    end.\n\n  Definition load(n: nat)(ctxid: SourceType) a mach post :=\n    (ctxid = Fetch -> isXAddr4 a mach.(getXAddrs)) /\\\n    match Memory.load_bytes n mach.(getMem) a with\n    | Some v => post v mach\n    | None => False\n    end.\n\n  Definition updatePc(mach: RiscvMachine): RiscvMachine :=\n    withPc mach.(getNextPc) (withNextPc (word.add mach.(getNextPc) (word.of_Z 4)) mach).\n\n  Definition getReg(regs: Registers)(reg: Z): word :=\n    if ((0 <? reg) && (reg <? 32)) then\n      match map.get regs reg with\n      | Some x => x\n      | None => word.of_Z 0\n      end\n    else word.of_Z 0.\n\n  Definition setReg(reg: Z)(v: word)(regs: Registers): Registers :=\n    if ((0 <? reg) && (reg <? 32)) then map.put regs reg v else regs.\n\n  Definition interpret_action (a : riscv_primitive) (mach : RiscvMachine) :\n    (primitive_result a -> RiscvMachine -> Prop) -> (RiscvMachine -> Prop) -> Prop :=\n    match a with\n    | GetRegister reg => fun (postF: word -> RiscvMachine -> Prop) postA =>\n        let v := getReg mach.(getRegs) reg in\n        postF v mach\n    | SetRegister reg v => fun postF postA =>\n        let regs := setReg reg v mach.(getRegs) in\n        postF tt (withRegs regs mach)\n    | GetPC => fun postF postA => postF mach.(getPc) mach\n    | SetPC newPC => fun postF postA => postF tt (withNextPc newPC mach)\n    | LoadByte ctxid a => fun postF postA => load 1 ctxid a mach postF\n    | LoadHalf ctxid a => fun postF postA => load 2 ctxid a mach postF\n    | LoadWord ctxid a => fun postF postA => load 4 ctxid a mach postF\n    | LoadDouble ctxid a => fun postF postA => load 8 ctxid a mach postF\n    | StoreByte ctxid a v => fun postF postA => store 1 ctxid a v mach (postF tt)\n    | StoreHalf ctxid a v => fun postF postA => store 2 ctxid a v mach (postF tt)\n    | StoreWord ctxid a v => fun postF postA => store 4 ctxid a v mach (postF tt)\n    | StoreDouble ctxid a v => fun postF postA => store 8 ctxid a v mach (postF tt)\n    | StartCycle => fun postF postA =>\n        postF tt (withNextPc (word.add mach.(getPc) (word.of_Z 4)) mach)\n    | EndCycleNormal => fun postF postA => postF tt (updatePc mach)\n    | EndCycleEarly _ => fun postF postA => postA (updatePc mach) (* ignores postF containing the continuation *)\n    | MakeReservation _\n    | ClearReservation _\n    | CheckReservation _\n    | GetCSRField _\n    | SetCSRField _ _\n    | GetPrivMode\n    | SetPrivMode _\n    | Fence _ _\n        => fun postF postA => False\n    end.\n\n  Definition no_M(mach: RiscvMachine): Prop :=\n      forall a v,\n        isXAddr4 a mach.(getXAddrs) ->\n        word.unsigned a mod 4 = 0 ->\n        Memory.load_bytes 4 mach.(getMem) a = Some v ->\n        forall minst, decode RV32IM (LittleEndian.combine 4 v) <> MInstruction minst.\n\n  Instance MinimalNoMulPrimitivesParams:\n    PrimitivesParams (free riscv_primitive primitive_result) RiscvMachine :=\n  {|\n    Primitives.mcomp_sat A m mach postF :=\n      @free.interpret _ _ _ interpret_action A m mach postF (fun _ => False);\n    Primitives.is_initial_register_value x := True;\n    Primitives.nonmem_load _ _ _ _ _ := False;\n    Primitives.nonmem_store _ _ _ _ _ _ := False;\n    Primitives.valid_machine := no_M;\n  |}.\n\n  Lemma load_weaken_post n c a m (post1 post2:_->_->Prop)\n    (H: forall r s, post1 r s -> post2 r s)\n    : load n c a m post1 -> load n c a m post2.\n  Proof.\n    cbv [load nonmem_load].\n    destruct (Memory.load_bytes n (getMem m) a); intuition eauto.\n  Qed.\n\n  Lemma store_weaken_post n c a v m (post1 post2:_->Prop)\n    (H: forall s, post1 s -> post2 s)\n    : store n c a v m post1 -> store n c a v m post2.\n  Proof.\n    cbv [store nonmem_store].\n    destruct (Memory.store_bytes n (getMem m) a); intuition eauto.\n  Qed.\n\n  Lemma interpret_action_weaken_post a (postF1 postF2: _ -> _ -> Prop) (postA1 postA2: _ -> Prop):\n    (forall r s, postF1 r s -> postF2 r s) ->\n    (forall s, postA1 s -> postA2 s) ->\n    forall s, interpret_action a s postF1 postA1 -> interpret_action a s postF2 postA2.\n  Proof.\n    destruct a; cbn; try solve [intuition eauto].\n    all : eauto using load_weaken_post, store_weaken_post.\n  Qed.\n\n  Global Instance MinimalNoMulSatisfies_mcomp_sat_spec: mcomp_sat_spec MinimalNoMulPrimitivesParams.\n  Proof.\n    split; cbv [mcomp_sat MinimalNoMulPrimitivesParams Bind Return Monad_free].\n    { symmetry. eapply interpret_bind_ex_mid, interpret_action_weaken_post. }\n    { symmetry; intros. rewrite interpret_ret; eapply iff_refl. }\n  Qed.\n\n  Lemma preserve_undef_on{memOk: map.ok Mem}: forall n (m m': Mem) a w s,\n      Memory.store_bytes n m a w = Some m' ->\n      map.undef_on m s ->\n      map.undef_on m' s.\n  Proof.\n    eauto using map.same_domain_preserves_undef_on, Memory.store_bytes_preserves_domain.\n  Qed.\n\n  Lemma removeXAddr_bw: forall (a1 a2: word) xaddrs,\n      isXAddr1 a1 (removeXAddr a2 xaddrs) ->\n      isXAddr1 a1 xaddrs.\n  Proof.\n    unfold isXAddr1, removeXAddr.\n    intros.\n    eapply filter_In.\n    eassumption.\n  Qed.\n\n  Lemma invalidateWrittenXAddrs_bw: forall n (a r: word) xa,\n      In a (invalidateWrittenXAddrs n r xa) ->\n      In a xa.\n  Proof.\n    induction n; cbn; intros.\n    - assumption.\n    - eapply IHn. eapply removeXAddr_bw. unfold isXAddr1. eassumption.\n  Qed.\n\n  Lemma put_preserves_getmany_of_tuple{memOk: map.ok Mem}:\n    forall n (t: HList.tuple word n) (m: Mem) (r: word) b,\n      ~In r (HList.tuple.to_list t) ->\n      map.getmany_of_tuple m t =\n      map.getmany_of_tuple (map.put m r b) t.\n  Proof.\n    induction n; intros.\n    - destruct t. reflexivity.\n    - destruct t as (w & t). cbn in H|-*.\n      unfold map.getmany_of_tuple in IHn.\n      erewrite IHn.\n      2: {\n        intro C. eapply H. right. exact C.\n      }\n      rewrite ?map.get_put_dec.\n      destr (word.eqb r w). 2: reflexivity.\n      exfalso. apply H. auto.\n  Qed.\n\n  Lemma transfer_load4bytes_to_previous_mem{memOk: map.ok Mem}:\n    forall n (a: word) v m m' r w someSet,\n      Memory.store_bytes n m r w = Some m' ->\n      (* a notin r..r+n *)\n      isXAddr4 a (invalidateWrittenXAddrs n r someSet) ->\n      Memory.load_bytes 4 m' a = Some v ->\n      Memory.load_bytes 4 m a = Some v.\n  Proof.\n    induction n; intros.\n    - cbn in H. congruence.\n    - unfold Memory.store_bytes in *. fwd. cbn in H0. destruct w as [b w].\n      cbn -[HList.tuple Memory.load_bytes] in H1.\n      cbn in E. fwd.\n      unfold Memory.load_bytes at 1 in IHn.\n      unfold map.getmany_of_tuple, Memory.footprint in IHn.\n      specialize IHn with (m := m) (r := (word.add r (word.of_Z 1))).\n      rewrite E1 in IHn.\n      eapply IHn.\n      + reflexivity.\n      + instantiate (1 := someSet). clear -H0.\n        unfold isXAddr4 in *. fwd. eauto 10 using removeXAddr_bw.\n      + unfold Memory.load_bytes in *.\n        etransitivity. 2: eassumption.\n        unfold Memory.unchecked_store_bytes, Memory.footprint.\n        eapply put_preserves_getmany_of_tuple.\n        cbn. clear -H0 word_ok. unfold isXAddr4, isXAddr1 in H0. fwd.\n        intro C.\n        unfold removeXAddr in *.\n        apply_in_hyps filter_In.\n        fwd.\n        apply_in_hyps Bool.negb_true_iff.\n        apply_in_hyps Properties.word.eqb_false.\n        repeat destruct C as [C | C]; try assumption;\n          match type of C with\n          | ?l = _ => ring_simplify l in C\n          end;\n          subst r;\n          congruence.\n  Qed.\n\n  Lemma isXAddr4_uninvalidate: forall (a: word) n r xa,\n      isXAddr4 a (invalidateWrittenXAddrs n r xa) ->\n      isXAddr4 a xa.\n  Proof.\n    unfold isXAddr4, isXAddr1. intros. fwd. eauto 10 using invalidateWrittenXAddrs_bw.\n  Qed.\n\n  Lemma interpret_action_total{memOk: map.ok Mem} a s postF postA :\n    no_M s ->\n    interpret_action a s postF postA ->\n    exists s', no_M s' /\\ (postA s' \\/ exists v', postF v' s').\n  Proof.\n    destruct s, a; cbn -[HList.tuple Memory.load_bytes invalidateWrittenXAddrs];\n      cbv [load store no_M]; cbn -[HList.tuple Memory.load_bytes invalidateWrittenXAddrs];\n        repeat destruct_one_match;\n        intuition idtac;\n        repeat lazymatch goal with\n               | H : postF _ ?mach |- exists _ : RiscvMachine, _ =>\n                 exists mach; cbn [RiscvMachine.getMem RiscvMachine.getXAddrs]\n               | H : postA ?mach |- exists _ : RiscvMachine, _ =>\n                 exists mach; cbn [RiscvMachine.getMem RiscvMachine.getXAddrs]\n               | Hexists : (exists v, ?P), Hforall : (forall v, ?P -> _) |- _ =>\n                 let v := fresh \"v\" in\n                 destruct Hexists as [v Hexists];\n                   specialize (Hforall v Hexists)\n               end;\n        ssplit; eauto; cbn -[HList.tuple Memory.load_bytes invalidateWrittenXAddrs];\n        change removeXAddr with (@List.removeb word word.eqb);\n        rewrite ?ListSet.of_list_removeb;\n        intuition eauto 10 using transfer_load4bytes_to_previous_mem, isXAddr4_uninvalidate.\n  Qed.\n\n  Lemma interpret_action_total'{memOk: map.ok Mem} a s post :\n    no_M s ->\n    interpret_action a s post (fun _ : RiscvMachine => False) ->\n    exists v s', post v s' /\\ no_M s'.\n  Proof.\n    intros. pose proof interpret_action_total as P.\n    specialize P with (postA := (fun _ : RiscvMachine => False)). simpl in P.\n    specialize (P _ _ _ H H0).\n    destruct P as (s' & ? & ?).\n    destruct H2 as [[] | (v' & ?)].\n    eauto.\n  Qed.\n\n  Import coqutil.Tactics.Tactics.\n\n  Lemma interpret_action_appendonly a s postF postA :\n    interpret_action a s postF postA ->\n    interpret_action a s (fun _ s' => endswith s'.(getLog) s.(getLog))\n                           (fun s' => endswith s'.(getLog) s.(getLog)).\n  Proof.\n    destruct s, a; cbn; cbv [load store nonmem_load nonmem_store]; cbn;\n      repeat destruct_one_match;\n      intuition eauto using endswith_refl, endswith_cons_l.\n  Qed.\n\n  (* NOTE: maybe instead a generic lemma to push /\\ into postcondition? *)\n  Lemma interpret_action_appendonly' a s postF postA :\n    interpret_action a s postF postA ->\n    interpret_action a s (fun v s' => postF v s' /\\ endswith s'.(getLog) s.(getLog))\n                         (fun   s' => postA   s' /\\ endswith s'.(getLog) s.(getLog)).\n  Proof.\n    destruct s, a; cbn; cbv [load store nonmem_load nonmem_store]; cbn;\n      repeat destruct_one_match; intros; destruct_products; try split;\n        intuition eauto using endswith_refl, endswith_cons_l.\n  Qed.\n\n  Lemma interpret_action_appendonly'' a s post :\n    interpret_action a s post (fun _ : RiscvMachine => False) ->\n    interpret_action a s (fun v s' => post v s' /\\ endswith s'.(getLog) s.(getLog))\n                         (fun _ : RiscvMachine => False).\n  Proof.\n    intros. pose proof interpret_action_appendonly' as P.\n    specialize (P _ _ _ (fun _ : RiscvMachine => False) H). simpl in P.\n    eapply interpret_action_weaken_post. 3: exact P. all: simpl; intuition eauto.\n  Qed.\n\n  Lemma interpret_action_preserves_valid{memOk: map.ok Mem} a s postF postA :\n    no_M s ->\n    interpret_action a s postF postA ->\n    interpret_action a s (fun v s' => postF v s' /\\ no_M s')\n                         (fun s' => postA s' /\\ no_M s').\n  Proof.\n    destruct s, a; cbn; cbv [load store no_M];\n      cbn -[HList.tuple Memory.load_bytes invalidateWrittenXAddrs];\n      repeat destruct_one_match; intros; destruct_products; try split;\n        change removeXAddr with (@List.removeb word word.eqb);\n        rewrite ?ListSet.of_list_removeb;\n        intuition eauto 10 using transfer_load4bytes_to_previous_mem, isXAddr4_uninvalidate.\n  Qed.\n\n  Lemma interpret_action_preserves_valid'{memOk: map.ok Mem} a s post :\n    no_M s ->\n    interpret_action a s post (fun _ : RiscvMachine => False) ->\n    interpret_action a s (fun v s' => post v s' /\\ no_M s')\n                         (fun _ : RiscvMachine => False).\n  Proof.\n    intros. pose proof interpret_action_preserves_valid as P.\n    specialize (P _ _ _ (fun _ : RiscvMachine => False) H H0). simpl in P.\n    eapply interpret_action_weaken_post. 3: exact P. all: simpl; intuition eauto.\n  Qed.\n\n  Global Instance MinimalNoMulPrimitivesSane{memOk: map.ok Mem} :\n    PrimitivesSane MinimalNoMulPrimitivesParams.\n  Proof.\n    split; cbv [mcomp_sane valid_machine MinimalNoMulPrimitivesParams]; intros *; intros D M;\n      (split; [ exact (interpret_action_total' _ st _ D M)\n              | eapply interpret_action_preserves_valid'; try eassumption;\n                eapply interpret_action_appendonly''; try eassumption ]).\n  Qed.\n\n  Global Instance MinimalNoMulSatisfiesPrimitives{memOk: map.ok Mem} :\n    Primitives MinimalNoMulPrimitivesParams.\n  Proof.\n    split; try exact _.\n    all : cbv [mcomp_sat spec_load spec_store MinimalNoMulPrimitivesParams invalidateWrittenXAddrs].\n    all: intros;\n      repeat match goal with\n      | _ => progress subst\n      | _ => Option.inversion_option\n      | _ => progress cbn -[Memory.load_bytes Memory.store_bytes HList.tuple]\n      | _ => progress cbv [valid_register is_initial_register_value load store Memory.loadByte Memory.loadHalf Memory.loadWord Memory.loadDouble Memory.storeByte Memory.storeHalf Memory.storeWord Memory.storeDouble] in *\n      | H : exists _, _ |- _ => destruct H\n      | H : _ /\\ _ |- _ => destruct H\n      | |- _ => solve [ intuition (eauto || blia) ]\n      | H : _ \\/ _ |- _ => destruct H\n      | |- context[match ?x with _ => _ end] => destruct x eqn:?\n      | |- _ => progress unfold getReg, setReg\n      | |-_ /\\ _ => split\n      end.\n      (* setRegister *)\n      destruct initialL; eassumption.\n  Qed.\n\nEnd Riscv.\n", "meta": {"author": "mit-plv", "repo": "riscv-coq", "sha": "55c9cc88a6734550bdd913bfdf482d498c6354e6", "save_path": "github-repos/coq/mit-plv-riscv-coq", "path": "github-repos/coq/mit-plv-riscv-coq/riscv-coq-55c9cc88a6734550bdd913bfdf482d498c6354e6/src/riscv/Platform/MinimalNoMul.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.22951144032772766}}
{"text": "Require Import Verdi.Verdi.\nRequire Import Verdi.HandlerMonad.\nRequire Import StructTact.Fin.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import Verdi.StatePacketPacketDecomposition.\nRequire Import Verdi.LabeledNet.\n\nRequire Import InfSeqExt.infseq.\nRequire Import InfSeqExt.classical.\n\nSet Implicit Arguments.\n\nSection LockServ.\n\n  Variable num_Clients : nat.\n\n  Definition Client_index := (fin num_Clients).\n\n  Inductive Name :=\n  | Client : Client_index -> Name\n  | Server : Name.\n\n  Definition list_Clients := map Client (all_fin num_Clients).\n\n  Definition Name_eq_dec : forall a b : Name, {a = b} + {a <> b}.\n    decide equality. apply fin_eq_dec.\n  Qed.\n\n  Inductive Msg :=\n  | Lock   : Msg\n  | Unlock : Msg\n  | Locked : Msg.\n\n  Definition Msg_eq_dec : forall a b : Msg, {a = b} + {a <> b}.\n    decide equality.\n  Qed.\n    \n  Definition Input := Msg.\n  Definition Output := Msg.\n\n  Record Data := mkData { queue : list Client_index ; held : bool }.\n\n  Definition init_data (n : Name) : Data := mkData [] false.\n\n  Inductive Label :=\n  | InputLock : Client_index -> Label\n  | InputUnlock : Client_index -> Label\n  | MsgUnlock : Label\n  | MsgLock : Client_index -> Label\n  | MsgLocked : Client_index -> Label\n  | Nop\n  | Silent.\n\n  Definition Handler (S : Type) := GenHandler (Name * Msg) S Output Label.\n\n  Definition ClientNetHandler (i : Client_index) (m : Msg) : Handler Data :=\n    match m with\n      | Locked => (put (mkData [] true)) ;; write_output Locked ;; ret (MsgLocked i)\n      | _ => ret Nop\n    end.\n\n  Definition ClientIOHandler (i : Client_index) (m : Msg) : Handler Data :=\n    match m with\n      | Lock => send (Server, Lock) ;; ret (InputLock i)\n      | Unlock => data <- get ;;\n                 when (held data)\n                   (put (mkData [] false) >>\n                        send (Server, Unlock));;\n                   ret (InputUnlock i)\n      | _ => ret Nop\n    end.\n  \n  Definition ServerNetHandler (src : Name) (m : Msg) : Handler Data :=\n    st <- get ;;\n    let q := queue st in\n    match m with\n      | Lock =>\n        match src with\n          | Server => ret Nop\n          | Client c =>\n            when (null q) (send (src, Locked)) >> put (mkData (q++[c]) (held st)) >> ret (MsgLock c)\n        end\n      | Unlock => match q with\n                   | _ :: x :: xs => put (mkData (x :: xs) (held st)) >> send (Client x, Locked)\n                   | _ => put (mkData [] (held st))\n                 end ;;\n                 ret MsgUnlock\n      | _ => ret Nop\n    end.\n\n  Definition ServerIOHandler (m : Msg) : Handler Data := ret Nop.\n\n  Definition NetHandler (nm src : Name) (m : Msg) : Handler Data :=\n    match nm with\n      | Client c => ClientNetHandler c m\n      | Server   => ServerNetHandler src m\n    end.\n\n  Definition InputHandler (nm : Name) (m : Msg) : Handler Data :=\n    match nm with\n      | Client c => ClientIOHandler c m\n      | Server   => ServerIOHandler m\n    end.\n\n  Ltac handler_unfold :=\n    repeat (monad_unfold; unfold NetHandler,\n                                 InputHandler,\n                                 ServerNetHandler,\n                                 ClientNetHandler,\n                                 ClientIOHandler,\n                                 ServerIOHandler in *).\n\n\n\n  Definition Nodes := Server :: list_Clients.\n\n  Theorem In_n_Nodes :\n    forall n : Name, In n Nodes.\n  Proof using.\n    intros.\n    unfold Nodes, list_Clients.\n    simpl.\n    destruct n.\n    - right.\n      apply in_map.\n      apply all_fin_all.\n    - left.\n      reflexivity.\n  Qed.\n\n  Theorem nodup :\n    NoDup Nodes.\n  Proof using.\n    unfold Nodes, list_Clients.\n    apply NoDup_cons.\n    - in_crush. discriminate.\n    - apply NoDup_map_injective.\n      + intros. congruence.\n      + apply all_fin_NoDup.\n  Qed.\n\n\n\n  Global Instance LockServ_BaseParams : BaseParams :=\n    {\n      data   := Data ;\n      input  := Input ;\n      output := Output\n    }.\n\n  Global Instance LockServ_LabeledParams : LabeledMultiParams LockServ_BaseParams :=\n    {\n      lb_name := Name ;\n      lb_msg  := Msg ;\n      lb_msg_eq_dec := Msg_eq_dec ;\n      lb_name_eq_dec := Name_eq_dec ;\n      lb_nodes := Nodes ;\n      lb_all_names_nodes := In_n_Nodes ;\n      lb_no_dup_nodes := nodup ;\n      label := Label ;\n      label_silent := Silent;\n      lb_init_handlers := init_data ;\n      lb_net_handlers := fun dst src msg s =>\n                        runGenHandler s (NetHandler dst src msg) ;\n      lb_input_handlers := fun nm msg s =>\n                          runGenHandler s (InputHandler nm msg)\n    }.\n\n  Global Instance LockServ_MultiParams : MultiParams LockServ_BaseParams :=\n    unlabeled_multi_params.\n\n  (* This is the fundamental safety property of the system:\n       No two different clients can (think they) hold\n       the lock at once.\n   *)\n  Definition mutual_exclusion (sigma : name -> data) : Prop :=\n    forall m n,\n      held (sigma (Client m)) = true ->\n      held (sigma (Client n)) = true ->\n      m = n.\n\n  (* The system enforces mutual exclusion at the server. Whenever a\n     client believs it holds the lock, that client is at the head of the\n     server's queue. *)\n  Definition locks_correct (sigma : name -> data) : Prop :=\n    forall n,\n      held (sigma (Client n)) = true ->\n      exists t,\n        queue (sigma Server) = n :: t.\n\n  (* We first show that this actually implies mutual exclusion. *)\n  Lemma locks_correct_implies_mutex :\n    forall sigma,\n      locks_correct sigma ->\n      mutual_exclusion sigma.\n  Proof using.\n    unfold locks_correct, mutual_exclusion.\n    intros.\n    repeat find_apply_hyp_hyp.\n    break_exists.\n    find_rewrite. find_inversion.\n    auto.\n  Qed.\n\n  Definition valid_unlock q h c p :=\n    pSrc p = Client c /\\\n    (exists t, q = c :: t) /\\\n    h = false.\n\n  Definition locks_correct_unlock (sigma : name -> data) (p : packet) : Prop :=\n    pBody p = Unlock ->\n    exists c, valid_unlock (queue (sigma Server)) (held (sigma (Client c))) c p.\n\n  Definition valid_locked q h c p :=\n      pDst p = Client c /\\\n      (exists t, q = c :: t) /\\\n      h = false.\n\n  Definition locks_correct_locked (sigma : name -> data) (p : packet) : Prop :=\n    pBody p = Locked ->\n    exists c, valid_locked (queue (sigma Server)) (held (sigma (Client c))) c p.\n\n\n  Definition LockServ_network_invariant (sigma : name -> data) (p : packet) : Prop :=\n    locks_correct_unlock sigma p /\\\n    locks_correct_locked sigma p.\n\n  Definition LockServ_network_network_invariant (p q : packet) : Prop :=\n    (pBody p = Unlock -> pBody q = Unlock -> False) /\\\n    (pBody p = Locked -> pBody q = Unlock -> False) /\\\n    (pBody p = Unlock -> pBody q = Locked -> False) /\\\n    (pBody p = Locked -> pBody q = Locked -> False).\n\n  Lemma nwnw_sym :\n    forall p q,\n      LockServ_network_network_invariant p q ->\n      LockServ_network_network_invariant q p.\n  Proof using.\n    unfold LockServ_network_network_invariant.\n    intuition.\n  Qed.\n\n  Lemma locks_correct_init :\n    locks_correct init_handlers.\n  Proof using.\n    unfold locks_correct. simpl. discriminate.\n  Qed.\n\n  Lemma InputHandler_cases :\n    forall h i st u out st' ms,\n      InputHandler h i st = (u, out, st', ms) ->\n      (exists c, h = Client c /\\\n                 ((i = Lock /\\ out = [] /\\ st' = st /\\ ms = [(Server, Lock)]) \\/\n                  (i = Unlock /\\ out = [] /\\ held st' = false /\\\n                   ((held st = true /\\ ms = [(Server, Unlock)]) \\/\n                    (st' = st /\\ ms = []))))) \\/\n      (out = [] /\\ st' = st /\\ ms = []).\n  Proof using.\n    handler_unfold.\n    intros.\n    repeat break_match; repeat tuple_inversion;\n      subst; simpl in *; subst; simpl in *.\n    - left. eexists. intuition.\n    - left. eexists. intuition.\n    - left. eexists. intuition.\n    - auto.\n    - auto.\n  Qed.\n\n  Lemma locks_correct_update_false :\n    forall sigma st' x,\n      locks_correct sigma ->\n      held st' = false ->\n      locks_correct (update name_eq_dec sigma (Client x) st').\n  Proof using.\n    unfold locks_correct.\n    intuition.\n    destruct (Name_eq_dec (Client x) (Client n)).\n    - find_inversion. exfalso.\n      rewrite_update.\n      congruence.\n    - rewrite_update.\n      auto.\n  Qed.\n\n  Ltac set_up_input_handlers :=\n    intros;\n    find_apply_lem_hyp InputHandler_cases;\n    intuition idtac; try break_exists; intuition idtac; subst;\n    repeat find_rewrite;\n    simpl in *; intuition idtac; repeat find_inversion;\n    try now rewrite update_nop_ext.\n\n  Lemma locks_correct_input_handlers :\n    forall h i sigma u st' out ms,\n      InputHandler h i (sigma h) = (u, out, st', ms) ->\n      locks_correct sigma ->\n      locks_correct (update name_eq_dec sigma h st').\n  Proof using.\n    set_up_input_handlers;\n    auto using locks_correct_update_false.\n  Qed.\n\n  Lemma ClientNetHandler_cases :\n    forall c m st u out st' ms,\n      ClientNetHandler c m st = (u, out, st', ms) ->\n      ms = [] /\\\n      ((st' = st /\\ out = [] /\\ m <> Locked) \\/\n       (m = Locked /\\ out = [Locked] /\\ held st' = true)).\n  Proof using.\n    handler_unfold.\n    intros.\n    repeat break_match; repeat tuple_inversion; subst; intuition (auto; congruence).\n  Qed.\n\n  Lemma ServerNetHandler_cases :\n    forall src m st u out st' ms,\n      ServerNetHandler src m st = (u, out, st', ms) ->\n      out = [] /\\\n      ((exists c, src = Client c /\\\n                  (m = Lock /\\\n                  queue st' = queue st ++ [c] /\\\n                  ((queue st = [] /\\ ms = [(Client c, Locked)]) \\/\n                   (queue st <> [] /\\ ms = [])))) \\/\n       ((m = Unlock /\\\n                   queue st' = tail (queue st) /\\\n                   ((queue st' = [] /\\ ms = []) \\/\n                    (exists next t, queue st' = next :: t /\\ ms = [(Client next, Locked)])))) \\/\n       ms = [] /\\ st' = st /\\ m <> Unlock).\n  Proof using.\n    handler_unfold.\n    intros.\n    repeat break_match; repeat tuple_inversion; subst.\n    - find_apply_lem_hyp null_sound. find_rewrite. simpl.\n      intuition. left. eexists. intuition.\n    - simpl. find_apply_lem_hyp null_false_neq_nil.\n      intuition. left. eexists. intuition.\n    - simpl. intuition (auto; congruence).\n    - simpl. destruct st; simpl in *; subst; intuition (auto; congruence).\n    - simpl in *. intuition.\n    - simpl in *. intuition eauto.\n    - simpl. intuition (auto; congruence).\n  Qed.\n\n  Definition at_head_of_queue sigma c := (exists t, queue (sigma Server) = c :: t).\n\n  Lemma at_head_of_queue_intro :\n    forall sigma c t,\n      queue (sigma Server) = c :: t ->\n      at_head_of_queue sigma c.\n  Proof using.\n    unfold at_head_of_queue.\n    firstorder.\n  Qed.\n\n  Lemma locks_correct_update_true :\n    forall sigma c st',\n      held st' = true ->\n      at_head_of_queue sigma c ->\n      locks_correct sigma ->\n      locks_correct (update name_eq_dec sigma (Client c) st').\n  Proof using.\n    unfold locks_correct.\n    intros.\n    destruct (Name_eq_dec (Client c) (Client n)); rewrite_update; try find_inversion; auto.\n  Qed.\n\n  Lemma locks_correct_locked_at_head :\n    forall sigma p c,\n      pDst p = Client c ->\n      pBody p = Locked ->\n      locks_correct_locked sigma p ->\n      at_head_of_queue sigma c.\n  Proof using.\n    unfold locks_correct_locked.\n    firstorder.\n    repeat find_rewrite. find_inversion.\n    eauto using at_head_of_queue_intro.\n  Qed.\n\n  Lemma all_clients_false_locks_correct_server_update :\n    forall sigma st,\n      (forall c, held (sigma (Client c)) = false) ->\n      locks_correct (update name_eq_dec sigma Server st).\n  Proof using.\n    unfold locks_correct.\n    intros.\n    rewrite_update.\n    now find_higher_order_rewrite.\n  Qed.\n\n  Lemma locks_correct_true_at_head_of_queue :\n    forall sigma x,\n      locks_correct sigma ->\n      held (sigma (Client x)) = true ->\n      at_head_of_queue sigma x.\n  Proof using.\n    unfold locks_correct.\n    intros.\n    find_apply_hyp_hyp. break_exists.\n    eauto using at_head_of_queue_intro.\n  Qed.\n\n  Lemma at_head_of_nil :\n    forall sigma c,\n      at_head_of_queue sigma c ->\n      queue (sigma Server) = [] ->\n      False.\n  Proof using.\n    unfold at_head_of_queue.\n    firstorder.\n    congruence.\n  Qed.\n\n  Lemma empty_queue_all_clients_false :\n    forall sigma,\n      locks_correct sigma ->\n      queue (sigma Server) = [] ->\n      (forall c, held (sigma (Client c)) = false).\n  Proof using.\n    intuition.\n    destruct (held (sigma (Client c))) eqn:?; auto.\n    exfalso. eauto using at_head_of_nil, locks_correct_true_at_head_of_queue.\n  Qed.\n\n  Lemma unlock_in_flight_all_clients_false :\n    forall sigma p,\n      pBody p = Unlock ->\n      locks_correct_unlock sigma p ->\n      locks_correct sigma ->\n      (forall c, held (sigma (Client c)) = false).\n  Proof using.\n    intros.\n    destruct (held (sigma (Client c))) eqn:?; auto.\n    firstorder.\n    find_copy_apply_lem_hyp locks_correct_true_at_head_of_queue; auto.\n    unfold at_head_of_queue in *. break_exists.\n    congruence.\n  Qed.\n\n  Lemma locks_correct_at_head_preserved :\n    forall sigma st',\n      locks_correct sigma ->\n      (forall c, at_head_of_queue sigma c -> at_head_of_queue (update name_eq_dec sigma Server st') c) ->\n      locks_correct (update name_eq_dec sigma Server st').\n  Proof using.\n    unfold locks_correct, at_head_of_queue.\n    firstorder.\n    rewrite_update.\n    eauto.\n  Qed.\n\n  Lemma snoc_at_head_of_queue_preserved :\n    forall sigma st' x,\n      queue st' = queue (sigma Server) ++ [x] ->\n      (forall c, at_head_of_queue sigma c -> at_head_of_queue (update name_eq_dec sigma Server st') c).\n  Proof using.\n    unfold at_head_of_queue.\n    intuition. break_exists.\n    rewrite_update.\n    find_rewrite.\n    eauto.\n  Qed.\n\n  Ltac set_up_net_handlers :=\n    intros;\n    match goal with\n      | [ H : context [ NetHandler (pDst ?p) _ _ _ ] |- _ ] =>\n        destruct (pDst p) eqn:?\n    end; simpl in *;\n    [find_apply_lem_hyp ClientNetHandler_cases |\n     find_apply_lem_hyp ServerNetHandler_cases; intuition; try break_exists ];\n    intuition; subst;\n    simpl in *; intuition;\n    repeat find_rewrite;\n    repeat find_inversion;\n    simpl in *;\n    try now rewrite update_nop_ext.\n\n\n  Lemma locks_correct_net_handlers :\n    forall p sigma u st' out ms,\n      NetHandler (pDst p) (pSrc p) (pBody p) (sigma (pDst p)) = (u, out, st', ms) ->\n      locks_correct sigma ->\n      locks_correct_unlock sigma p ->\n      locks_correct_locked sigma p ->\n      locks_correct (update name_eq_dec sigma (pDst p) st').\n  Proof using.\n    set_up_net_handlers;\n    eauto using\n          locks_correct_update_true, locks_correct_locked_at_head,\n          all_clients_false_locks_correct_server_update, empty_queue_all_clients_false,\n          locks_correct_at_head_preserved, snoc_at_head_of_queue_preserved,\n          all_clients_false_locks_correct_server_update, unlock_in_flight_all_clients_false.\n  Qed.\n\n  Lemma locks_correct_unlock_sent_lock :\n    forall sigma p,\n      pBody p = Lock ->\n      locks_correct_unlock sigma p.\n  Proof using.\n    unfold locks_correct_unlock.\n    intuition. congruence.\n  Qed.\n\n  Lemma locks_correct_unlock_sent_locked :\n    forall sigma p,\n      pBody p = Locked ->\n      locks_correct_unlock sigma p.\n  Proof using.\n    unfold locks_correct_unlock.\n    intuition. congruence.\n  Qed.\n\n  Lemma locks_correct_unlock_input_handlers_old :\n    forall h i sigma u st' out ms p,\n      InputHandler h i (sigma h) = (u, out, st', ms) ->\n      locks_correct sigma ->\n      locks_correct_unlock sigma p ->\n      locks_correct_unlock (update name_eq_dec sigma h st') p.\n  Proof using.\n    set_up_input_handlers.\n    destruct (pBody p) eqn:?.\n    - auto using locks_correct_unlock_sent_lock.\n    - now erewrite unlock_in_flight_all_clients_false in * by eauto.\n    - auto using locks_correct_unlock_sent_locked.\n  Qed.\n\n  Lemma locked_in_flight_all_clients_false :\n    forall sigma p,\n      pBody p = Locked ->\n      locks_correct_locked sigma p ->\n      locks_correct sigma ->\n      (forall c, held (sigma (Client c)) = false).\n  Proof using.\n    intros.\n    destruct (held (sigma (Client c))) eqn:?; auto.\n    firstorder.\n    find_copy_apply_lem_hyp locks_correct_true_at_head_of_queue; auto.\n    unfold at_head_of_queue in *. break_exists.\n    congruence.\n  Qed.\n\n  Lemma locks_correct_locked_sent_lock :\n    forall sigma p,\n      pBody p = Lock ->\n      locks_correct_locked sigma p.\n  Proof using.\n    unfold locks_correct_locked.\n    intuition. congruence.\n  Qed.\n\n  Lemma locks_correct_locked_sent_unlock :\n    forall sigma p,\n      pBody p = Unlock ->\n      locks_correct_locked sigma p.\n  Proof using.\n    unfold locks_correct_locked.\n    intuition. congruence.\n  Qed.\n\n  Lemma locks_correct_locked_input_handlers_old :\n    forall h i sigma u st' out ms p,\n      InputHandler h i (sigma h) = (u, out, st', ms) ->\n      locks_correct sigma ->\n      locks_correct_locked sigma p ->\n      locks_correct_locked (update name_eq_dec sigma h st') p.\n  Proof using.\n    set_up_input_handlers.\n    destruct (pBody p) eqn:?.\n    - auto using locks_correct_locked_sent_lock.\n    - auto using locks_correct_locked_sent_unlock.\n    - now erewrite locked_in_flight_all_clients_false in * by eauto.\n  Qed.\n\n  Lemma locks_correct_unlock_true_to_false :\n    forall sigma p x st',\n      at_head_of_queue sigma x ->\n      held st' = false ->\n      pSrc p = Client x ->\n      locks_correct_unlock (update name_eq_dec sigma (Client x) st') p.\n  Proof using.\n    unfold locks_correct_unlock, valid_unlock.\n    intros.\n    exists x.\n    intuition; now rewrite_update.\n  Qed.\n\n  Lemma locks_correct_unlock_input_handlers_new :\n    forall h i sigma u st' out ms p,\n      InputHandler h i (sigma h) = (u, out, st', ms) ->\n      locks_correct sigma ->\n      In (pDst p, pBody p) ms ->\n      pSrc p = h ->\n      locks_correct_unlock (update name_eq_dec sigma h st') p.\n  Proof using.\n    set_up_input_handlers;\n\n    auto using locks_correct_unlock_sent_lock,\n               locks_correct_unlock_true_to_false,\n               locks_correct_true_at_head_of_queue.\n  Qed.\n\n  Lemma locks_correct_locked_input_handlers_new :\n    forall h i sigma u st' out ms p,\n      InputHandler h i (sigma h) = (u, out, st', ms) ->\n      In (pDst p, pBody p) ms ->\n      locks_correct_locked (update name_eq_dec sigma h st') p.\n  Proof using.\n    set_up_input_handlers;\n    auto using locks_correct_locked_sent_lock, locks_correct_locked_sent_unlock.\n  Qed.\n\n  Lemma nwnw_locked_lock :\n    forall p q,\n      LockServ_network_network_invariant p q ->\n      pBody p = Locked ->\n      pBody q = Lock.\n  Proof using.\n    unfold LockServ_network_network_invariant.\n    intros.\n    destruct (pBody q); intuition; try discriminate.\n  Qed.\n\n  Lemma nwnw_unlock_lock :\n    forall p q,\n      LockServ_network_network_invariant p q ->\n      pBody p = Unlock ->\n      pBody q = Lock.\n  Proof using.\n    unfold LockServ_network_network_invariant.\n    intros.\n    destruct (pBody q); intuition; try discriminate.\n  Qed.\n\n  Lemma locks_correct_unlock_at_head :\n    forall sigma p c,\n      pSrc p = Client c ->\n      pBody p = Unlock ->\n      locks_correct_unlock sigma p ->\n      at_head_of_queue sigma c.\n  Proof using.\n    unfold locks_correct_unlock.\n    intros.\n    find_apply_hyp_hyp. clear H1.\n    break_exists.\n    unfold valid_unlock in *. intuition.\n    break_exists.\n    repeat find_rewrite. repeat find_inversion.\n    eauto using at_head_of_queue_intro.\n  Qed.\n\n  Lemma locks_correct_unlock_at_head_preserved :\n    forall sigma st' p,\n      locks_correct_unlock sigma p ->\n      (forall c, at_head_of_queue sigma c -> at_head_of_queue (update name_eq_dec sigma Server st') c) ->\n      locks_correct_unlock (update name_eq_dec sigma Server st') p.\n  Proof using.\n    unfold locks_correct_unlock, valid_unlock.\n    intuition.\n    break_exists.\n    exists x.\n    intuition.\n    - firstorder.\n    - now rewrite_update.\n  Qed.\n\n  Lemma nil_at_head_of_queue_preserved :\n    forall c sigma sigma',\n      queue (sigma Server) = [] ->\n      at_head_of_queue sigma c ->\n      at_head_of_queue sigma' c.\n  Proof using.\n    unfold at_head_of_queue.\n    firstorder.\n    congruence.\n  Qed.\n\n  Lemma locks_correct_unlock_net_handlers_old :\n    forall p sigma u st' out ms q,\n      NetHandler (pDst p) (pSrc p) (pBody p) (sigma (pDst p)) = (u, out, st', ms) ->\n      locks_correct sigma ->\n      locks_correct_unlock sigma q ->\n      LockServ_network_network_invariant p q ->\n      locks_correct_unlock (update name_eq_dec sigma (pDst p) st') q.\n  Proof using.\n    set_up_net_handlers;\n    eauto using locks_correct_unlock_sent_lock, nwnw_locked_lock,\n                locks_correct_unlock_at_head_preserved, snoc_at_head_of_queue_preserved,\n                nwnw_unlock_lock, nil_at_head_of_queue_preserved.\n  Qed.\n\n  Lemma locks_correct_locked_at_head_preserved :\n    forall sigma st' p,\n      locks_correct_locked sigma p ->\n      (forall c, at_head_of_queue sigma c -> at_head_of_queue (update name_eq_dec sigma Server st') c) ->\n      locks_correct_locked (update name_eq_dec sigma Server st') p.\n  Proof using.\n    unfold locks_correct_locked, valid_locked.\n    intuition.\n    break_exists.\n    exists x.\n    intuition.\n    - firstorder.\n    - now rewrite_update.\n  Qed.\n\n  Lemma locks_correct_locked_net_handlers_old :\n    forall p sigma u st' out ms q,\n      NetHandler (pDst p) (pSrc p) (pBody p) (sigma (pDst p)) = (u, out, st', ms) ->\n      locks_correct sigma ->\n      locks_correct_locked sigma q ->\n      LockServ_network_network_invariant p q ->\n      locks_correct_locked (update name_eq_dec sigma (pDst p) st') q.\n  Proof using.\n    set_up_net_handlers;\n    eauto using locks_correct_locked_sent_lock, nwnw_locked_lock,\n      locks_correct_locked_at_head_preserved, snoc_at_head_of_queue_preserved,\n      nwnw_unlock_lock, nil_at_head_of_queue_preserved.\n  Qed.\n\n  Lemma locks_correct_unlock_net_handlers_new :\n    forall p sigma u st' out ms q,\n      NetHandler (pDst p) (pSrc p) (pBody p) (sigma (pDst p)) = (u, out, st', ms) ->\n      locks_correct sigma ->\n      In (pDst q, pBody q) ms ->\n      locks_correct_unlock (update name_eq_dec sigma (pDst p) st') q.\n  Proof using.\n    set_up_net_handlers;\n    auto using locks_correct_unlock_sent_locked.\n  Qed.\n\n  Lemma locks_correct_locked_intro :\n    forall sigma p c t st',\n      pDst p = Client c ->\n      held (sigma (Client c)) = false ->\n      queue st' = c :: t ->\n      locks_correct_locked (update name_eq_dec sigma Server st') p.\n  Proof using.\n    unfold locks_correct_locked, valid_locked.\n    intros.\n    exists c.\n    intuition.\n    - exists t. now rewrite_update.\n    - now rewrite_update.\n  Qed.\n\n  Lemma locks_correct_locked_net_handlers_new :\n    forall p sigma u st' out ms q,\n      NetHandler (pDst p) (pSrc p) (pBody p) (sigma (pDst p)) = (u, out, st', ms) ->\n      locks_correct sigma ->\n      locks_correct_unlock sigma p ->\n      In (pDst q, pBody q) ms ->\n      locks_correct_locked (update name_eq_dec sigma (pDst p) st') q.\n  Proof using.\n    set_up_net_handlers;\n    eauto using locks_correct_locked_intro,\n                empty_queue_all_clients_false,\n                unlock_in_flight_all_clients_false.\n  Qed.\n\n  Lemma nwnw_lock :\n    forall p p',\n      pBody p = Lock ->\n      LockServ_network_network_invariant p p'.\n  Proof using.\n    unfold LockServ_network_network_invariant.\n    intuition; simpl in *; congruence.\n  Qed.\n\n  Lemma LockServ_nwnw_input_handlers_old_new :\n    forall h i sigma u st' out ms p p',\n      InputHandler h i (sigma h) = (u, out, st', ms) ->\n      locks_correct sigma ->\n      LockServ_network_invariant sigma p ->\n      In (pDst p', pBody p') ms ->\n      pSrc p' = h ->\n      LockServ_network_network_invariant p p'.\n  Proof using.\n    unfold LockServ_network_invariant.\n    set_up_input_handlers.\n    - auto using nwnw_sym, nwnw_lock.\n    - destruct (pBody p) eqn:?.\n      + auto using nwnw_lock.\n      + now erewrite unlock_in_flight_all_clients_false in * by eauto.\n      + now erewrite locked_in_flight_all_clients_false in * by eauto.\n  Qed.\n\n  Lemma LockServ_nwnw_input_handlers_new_new :\n    forall h i sigma u st' out ms,\n      InputHandler h i (sigma h) = (u, out, st', ms) ->\n      distinct_pairs_and LockServ_network_network_invariant\n                         (map (fun m => mkPacket h (fst m) (snd m)) ms).\n  Proof using.\n    set_up_input_handlers.\n  Qed.\n\n  Lemma nw_empty_queue_lock :\n    forall sigma p,\n      LockServ_network_invariant sigma p ->\n      queue (sigma Server) = [] ->\n      pBody p = Lock.\n  Proof using.\n    unfold LockServ_network_invariant,\n    locks_correct_unlock, locks_correct_locked,\n    valid_unlock, valid_locked.\n    intuition.\n    destruct (pBody p) eqn:?; intuition; break_exists; intuition; break_exists;\n    congruence.\n  Qed.\n\n  Lemma LockServ_nwnw_net_handlers_old_new :\n    forall p sigma u st' out ms q p',\n      NetHandler (pDst p) (pSrc p) (pBody p) (sigma (pDst p)) = (u, out, st', ms) ->\n      locks_correct sigma ->\n      LockServ_network_invariant sigma p ->\n      LockServ_network_invariant sigma q ->\n      LockServ_network_network_invariant p q ->\n      In (pDst p', pBody p') ms ->\n      LockServ_network_network_invariant p' q.\n  Proof using.\n    set_up_net_handlers;\n    eauto using nwnw_sym, nwnw_lock, nw_empty_queue_lock, nwnw_unlock_lock.\n  Qed.\n\n  Lemma LockServ_nwnw_net_handlers_new_new :\n    forall p sigma u st' out ms,\n      NetHandler (pDst p) (pSrc p) (pBody p) (sigma (pDst p)) = (u, out, st', ms) ->\n      locks_correct sigma ->\n      LockServ_network_invariant sigma p ->\n      distinct_pairs_and LockServ_network_network_invariant\n                         (map (fun m => mkPacket (pDst p) (fst m) (snd m)) ms).\n  Proof using.\n    set_up_net_handlers.\n  Qed.\n\n  Ltac unlabeled_unfold :=\n    unfold unlabeled_net_handlers, unlabeled_input_handlers in *.\n  \n  Instance LockServ_Decompositition : Decomposition _ LockServ_MultiParams.\n  apply Build_Decomposition with (state_invariant := locks_correct)\n                                 (network_invariant := LockServ_network_invariant)\n                                 (network_network_invariant := LockServ_network_network_invariant);\n    simpl; intros; monad_unfold; unlabeled_unfold; repeat break_let; repeat find_inversion.\n  - auto using nwnw_sym.\n  - auto using locks_correct_init.\n  - eauto using locks_correct_input_handlers.\n  - unfold LockServ_network_invariant in *. intuition.\n    eauto using locks_correct_net_handlers.\n  - unfold LockServ_network_invariant in *.\n    intuition eauto using locks_correct_unlock_input_handlers_old,\n                          locks_correct_locked_input_handlers_old.\n  - unfold LockServ_network_invariant in *.\n    intuition eauto using locks_correct_unlock_input_handlers_new,\n                          locks_correct_locked_input_handlers_new.\n  - unfold LockServ_network_invariant in *.\n    intuition eauto using locks_correct_unlock_net_handlers_old,\n                          locks_correct_locked_net_handlers_old.\n  - unfold LockServ_network_invariant in *.\n    intuition eauto using locks_correct_unlock_net_handlers_new,\n                          locks_correct_locked_net_handlers_new.\n  - eauto using LockServ_nwnw_input_handlers_old_new.\n  - eauto using LockServ_nwnw_input_handlers_new_new.\n  - eauto using LockServ_nwnw_net_handlers_old_new.\n  - eauto using LockServ_nwnw_net_handlers_new_new.\n  Defined.\n\n  Theorem true_in_reachable_mutual_exclusion :\n    true_in_reachable step_async step_async_init (fun net => mutual_exclusion (nwState net)).\n  Proof using.\n    pose proof decomposition_invariant.\n    find_apply_lem_hyp inductive_invariant_true_in_reachable.\n    unfold true_in_reachable in *.\n    intros.\n    apply locks_correct_implies_mutex.\n    match goal with\n    | [ H : _ |- _ ] => apply H\n    end.\n    auto.\n  Qed.\n\n  Fixpoint last_holder' (holder : option Client_index) (trace : list (name * (input + list output))) : option Client_index :=\n    match trace with\n      | [] => holder\n      | (Client n, inl Unlock) :: tr => match holder with\n                                          | None => last_holder' holder tr\n                                          | Some m => if fin_eq_dec _ n m\n                                                      then last_holder' None tr\n                                                      else last_holder' holder tr\n                                        end\n\n      | (Client n, inr [Locked]) :: tr => last_holder' (Some n) tr\n      | (n, _) :: tr => last_holder' holder tr\n    end.\n\n  Fixpoint trace_mutual_exclusion' (holder : option Client_index) (trace : list (name * (input + list output))) : Prop :=\n    match trace with\n      | [] => True\n      | (Client n, (inl Unlock)) :: tr' => match holder with\n                                             | Some m => if fin_eq_dec _ n m\n                                                         then trace_mutual_exclusion' None tr'\n                                                         else trace_mutual_exclusion' holder tr'\n                                             | _ => trace_mutual_exclusion' holder tr'\n                                           end\n      | (n, (inl _)) :: tr' => trace_mutual_exclusion' holder tr'\n      | (Client n, (inr [Locked])) :: tr' => match holder with\n                                               | None => trace_mutual_exclusion' (Some n) tr'\n                                               | Some _ => False\n                                             end\n      | (_, (inr [])) :: tr' => trace_mutual_exclusion' holder tr'\n      | (_, (inr _)) :: tr' => False\n    end.\n\n  Definition trace_mutual_exclusion (trace : list (name * (input + list output))) : Prop :=\n    trace_mutual_exclusion' None trace.\n\n  Definition last_holder (trace : list (name * (input + list output))) : option Client_index :=\n    last_holder' None trace.\n\n  Lemma cross_relation :\n    forall (P : network -> list (name * (input + list output)) -> Prop),\n      P step_async_init [] ->\n      (forall st st' tr ev,\n         step_async_star step_async_init st tr ->\n         P st tr ->\n         step_async st st' ev ->\n         P st' (tr ++ ev)) ->\n      forall st tr,\n        step_async_star step_async_init st tr ->\n        P st tr.\n  Proof using.\n    intros.\n    find_apply_lem_hyp refl_trans_1n_n1_trace.\n    prep_induction H1.\n    induction H1; intros; subst; eauto.\n    eapply H3; eauto.\n    - apply refl_trans_n1_1n_trace. auto.\n    - apply IHrefl_trans_n1_trace; auto.\n  Qed.\n\n  Lemma trace_mutex'_no_out_extend :\n    forall tr n h,\n      trace_mutual_exclusion' h tr ->\n      trace_mutual_exclusion' h (tr ++ [(n, inr [])]).\n  Proof using.\n    induction tr; intuition; unfold trace_mutual_exclusion in *; simpl in *;\n    repeat break_match; subst; intuition.\n  Qed.\n\n  Lemma last_holder'_no_out_inv :\n    forall tr h c n,\n      last_holder' h (tr ++ [(c, inr [])]) = Some n ->\n      last_holder' h tr = Some n.\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; subst; intuition; eauto.\n  Qed.\n\n  Lemma last_holder'_no_out_extend :\n    forall tr h c n,\n      last_holder' h tr = Some n ->\n      last_holder' h (tr ++ [(c, inr [])]) = Some n.\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; subst; intuition.\n  Qed.\n\n  Lemma decomposition_reachable_nw_invariant :\n    forall st tr p,\n      step_async_star step_async_init st tr ->\n      In p (nwPackets st) ->\n      network_invariant (nwState st) p.\n  Proof using.\n    pose proof decomposition_invariant.\n    find_apply_lem_hyp inductive_invariant_true_in_reachable.\n    unfold true_in_reachable, reachable in *.\n    intuition.\n    unfold composed_invariant in *.\n    apply H; eauto.\n  Qed.\n\n  Lemma trace_mutex'_locked_extend :\n    forall tr h n,\n      trace_mutual_exclusion' h tr ->\n      last_holder' h tr = None ->\n      trace_mutual_exclusion' h (tr ++ [(Client n, inr [Locked])]).\n  Proof using.\n    induction tr; intros; simpl in *.\n    - subst. auto.\n    - simpl in *. repeat break_match; subst; intuition.\n  Qed.\n\n  Lemma reachable_intro :\n    forall a tr,\n      step_async_star step_async_init a tr ->\n      reachable step_async step_async_init a.\n  Proof using.\n    unfold reachable.\n    intros. eauto.\n  Qed.\n\n  Lemma locks_correct_locked_invariant :\n    forall st p,\n      reachable step_async step_async_init st ->\n      In p (nwPackets st) ->\n      locks_correct_locked (nwState st) p.\n  Proof using.\n    intros.\n    pose proof decomposition_invariant.\n    find_apply_lem_hyp inductive_invariant_true_in_reachable.\n    unfold true_in_reachable in *. apply H1; auto.\n  Qed.\n\n  Lemma locks_correct_invariant :\n    forall st,\n      reachable step_async step_async_init st ->\n      locks_correct (nwState st).\n  Proof using.\n    intros.\n    pose proof decomposition_invariant.\n    find_apply_lem_hyp inductive_invariant_true_in_reachable.\n    unfold true_in_reachable in *. apply H0; auto.\n  Qed.\n\n  Lemma mutual_exclusion_invariant :\n    forall st,\n      reachable step_async step_async_init st ->\n      mutual_exclusion (nwState st).\n  Proof using.\n    intros.\n    apply locks_correct_implies_mutex.\n    auto using locks_correct_invariant.\n  Qed.\n\n  Lemma last_holder'_locked_some_eq :\n    forall tr h c n,\n      last_holder' h (tr ++ [(Client c, inr [Locked])]) = Some n ->\n      c = n.\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; subst; eauto.\n    congruence.\n  Qed.\n\n  Ltac my_update_destruct :=\n    match goal with\n      | [H : context [ update _ _ ?x _ ?y ] |- _ ] => destruct (Name_eq_dec x y)\n      | [ |- context [ update _ _ ?x _ ?y ] ] => destruct (Name_eq_dec x y)\n    end.\n\n  Lemma last_holder'_server_extend :\n    forall tr h i,\n      last_holder' h (tr ++ [(Server, inl i)]) = last_holder' h tr.\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; auto.\n  Qed.\n\n  Lemma last_holder'_locked_extend :\n    forall tr h n,\n      last_holder' h (tr ++ [(Client n, inr [Locked])]) = Some n.\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; auto.\n  Qed.\n\n  Lemma trace_mutual_exclusion'_extend_input :\n    forall tr h c i,\n      i <> Unlock ->\n      trace_mutual_exclusion' h tr ->\n      trace_mutual_exclusion' h (tr ++ [(Client c, inl i)]).\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; intuition.\n  Qed.\n\n  Lemma trace_mutual_exclusion'_extend_input_server :\n    forall tr h i,\n      trace_mutual_exclusion' h tr ->\n      trace_mutual_exclusion' h (tr ++ [(Server, inl i)]).\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; intuition.\n  Qed.\n\n  Lemma last_holder'_input_inv :\n    forall tr h c i n,\n      i <> Unlock ->\n      last_holder' h (tr ++ [(Client c, inl i)]) = Some n ->\n      last_holder' h tr = Some n.\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; auto; try congruence; subst; eauto.\n  Qed.\n\n  Lemma last_holder'_input_inv_server :\n    forall tr h i n,\n      last_holder' h (tr ++ [(Server, inl i)]) = Some n ->\n      last_holder' h tr = Some n.\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; auto; try congruence; subst; eauto.\n  Qed.\n\n  Lemma last_holder'_input_extend :\n    forall tr h c i n,\n      i <> Unlock ->\n      last_holder' h tr = Some n ->\n      last_holder' h (tr ++ [(Client c, inl i)]) = Some n.\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; auto.\n    congruence.\n  Qed.\n\n  Lemma trace_mutex'_unlock_extend :\n    forall tr h c,\n      trace_mutual_exclusion' h tr ->\n      trace_mutual_exclusion' h (tr ++ [(Client c, inl Unlock)]).\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; intuition (auto; try congruence).\n  Qed.\n\n  Lemma last_holder'_unlock_none :\n    forall tr h c,\n      last_holder' h tr = Some c ->\n      last_holder' h (tr ++ [(Client c, inl Unlock)]) = None.\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; intuition.\n    congruence.\n  Qed.\n\n  Lemma last_holder_unlock_none :\n    forall tr c,\n      last_holder tr = Some c ->\n      last_holder (tr ++ [(Client c, inl Unlock)]) = None.\n  Proof using.\n    intros.\n    apply last_holder'_unlock_none. auto.\n  Qed.\n\n  Lemma last_holder_some_unlock_inv :\n    forall tr h c n,\n      last_holder' h (tr ++ [(Client c, inl Unlock)]) = Some n ->\n      last_holder' h tr = Some n.\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; subst;\n    intuition; try congruence; eauto.\n  Qed.\n\n  Lemma last_holder'_neq_unlock_extend :\n    forall tr h n c,\n      last_holder' h tr = Some n ->\n      n <> c ->\n      last_holder' h (tr ++ [(Client c, inl Unlock)]) = Some n.\n  Proof using.\n    induction tr; intros; simpl in *; repeat break_match; subst; try congruence; intuition.\n  Qed.\n\n  Lemma LockServ_mutual_exclusion_trace :\n    forall st tr,\n      step_async_star step_async_init st tr ->\n      trace_mutual_exclusion tr /\\\n      (forall n, last_holder tr = Some n -> held (nwState st (Client n)) = true) /\\\n      (forall n, held (nwState st (Client n)) = true -> last_holder tr = Some n).\n  Proof using.\n    apply cross_relation; intros.\n    - intuition.\n      + red. red. auto.\n      + unfold last_holder in *. simpl in *. discriminate.\n      + unfold last_holder in *. simpl in *. discriminate.\n    - match goal with\n        | [ H : step_async _ _ _ |- _ ] => invcs H\n      end; monad_unfold; unlabeled_unfold;\n        unfold lb_net_handlers, lb_input_handlers in *; simpl in *;\n          repeat break_let; repeat find_inversion.\n      + unfold NetHandler in *. break_match.\n        * find_apply_lem_hyp ClientNetHandler_cases; eauto.\n          break_and.\n          { break_or_hyp.\n            - intuition; subst.\n              + apply trace_mutex'_no_out_extend; auto.\n              + rewrite update_nop_ext.\n                find_apply_lem_hyp last_holder'_no_out_inv.\n                auto.\n              + match goal with\n                  | [ H : _ |- _ ] => rewrite update_nop in H\n                end.\n                find_apply_hyp_hyp.\n                apply last_holder'_no_out_extend. auto.\n            - intuition; subst.\n              + apply trace_mutex'_locked_extend. auto.\n                destruct (last_holder' None tr) eqn:?; auto.\n                find_apply_hyp_hyp.\n                erewrite locked_in_flight_all_clients_false in * by\n                  eauto using locks_correct_locked_invariant, reachable_intro,\n                              locks_correct_invariant.\n                discriminate.\n              + my_update_destruct; try find_inversion; rewrite_update; auto.\n                find_apply_lem_hyp last_holder'_locked_some_eq. congruence.\n              + my_update_destruct; try find_inversion; rewrite_update.\n                * apply last_holder'_locked_extend.\n                * erewrite locked_in_flight_all_clients_false in * by\n                      eauto using locks_correct_locked_invariant, reachable_intro,\n                                  locks_correct_invariant.\n                  discriminate.\n          }\n        * { find_apply_lem_hyp ServerNetHandler_cases. break_and. subst.\n            repeat split.\n            - apply trace_mutex'_no_out_extend. auto.\n            - intros. my_update_destruct; try discriminate.\n              rewrite_update.\n              find_apply_lem_hyp last_holder'_no_out_inv.\n              auto.\n            - intros. my_update_destruct; try discriminate; rewrite_update.\n              apply last_holder'_no_out_extend. auto.\n          }\n      + unfold InputHandler in *. break_match.\n        * unfold ClientIOHandler in *.\n          { monad_unfold.\n            repeat break_match; repeat find_inversion; intuition;\n            repeat rewrite snoc_assoc in *;\n            try apply trace_mutex'_no_out_extend;\n            try find_apply_lem_hyp last_holder'_no_out_inv;\n            try (apply last_holder'_no_out_extend; auto).\n            - apply trace_mutual_exclusion'_extend_input; auto. congruence.\n            - rewrite update_nop_ext.\n              find_apply_lem_hyp last_holder'_input_inv; try congruence.\n              auto.\n            - match goal with\n                | [ H : _ |- _ ] => rewrite update_nop in H\n              end.\n              apply last_holder'_input_extend; auto. congruence.\n            - apply trace_mutex'_unlock_extend; auto.\n            - rewrite last_holder_unlock_none in *; auto. discriminate.\n            - my_update_destruct; try find_inversion; rewrite_update.\n              + discriminate.\n              + assert (mutual_exclusion (nwState st))\n                       by eauto using mutual_exclusion_invariant, reachable_intro.\n                unfold mutual_exclusion in *.\n                assert (c = n) by eauto. congruence.\n            - apply trace_mutex'_unlock_extend. auto.\n            - rewrite update_nop.\n              find_apply_lem_hyp last_holder_some_unlock_inv.\n              auto.\n            - match goal with\n                | [ H : _ |- _ ] => rewrite update_nop in H\n              end.\n              assert (n <> c) by congruence.\n              find_apply_hyp_hyp.\n              apply last_holder'_neq_unlock_extend; auto.\n            - apply trace_mutual_exclusion'_extend_input; auto. congruence.\n            - rewrite update_nop_ext. find_apply_lem_hyp last_holder'_input_inv; try congruence.\n              auto.\n            - match goal with\n                | [ H : _ |- _ ] => rewrite update_nop in H\n              end.\n              apply last_holder'_input_extend; auto. congruence.\n          }\n        * unfold ServerIOHandler in *.\n          monad_unfold. find_inversion.\n          { intuition;\n            repeat rewrite snoc_assoc in *.\n            - apply trace_mutex'_no_out_extend.\n              apply trace_mutual_exclusion'_extend_input_server. auto.\n            - find_apply_lem_hyp last_holder'_no_out_inv.\n              rewrite update_nop. find_apply_lem_hyp last_holder'_input_inv_server. auto.\n            - apply last_holder'_no_out_extend; auto.\n              rewrite_update. unfold last_holder. rewrite last_holder'_server_extend.\n              auto.\n          }\n  Qed.\n\n  Lemma head_grant_state_unlock :\n    forall st tr c t,\n      step_async_star step_async_init st tr ->\n      queue (nwState st Server) = c :: t ->\n      (In (mkPacket Server (Client c) Locked) (nwPackets st)) \\/\n      (held (nwState st (Client c)) = true) \\/\n      (In (mkPacket (Client c) Server Unlock) (nwPackets st)).\n  Proof using.\n    intros.\n    find_apply_lem_hyp refl_trans_1n_n1_trace.\n    prep_induction H.\n    induction H; intros; subst.\n    - discriminate.\n    - match goal with\n        | [ H : step_async _ _ _ |- _ ] => invcs H\n      end; unlabeled_unfold;\n        unfold lb_net_handlers, lb_input_handlers in *; simpl in *;\n          monad_unfold;\n          repeat break_let; repeat find_inversion.\n      + unfold NetHandler in *.\n        break_match; rewrite_update.\n        * find_apply_lem_hyp ClientNetHandler_cases.\n          intuition.\n          -- subst. rewrite update_nop_ext.\n             find_apply_lem_hyp IHrefl_trans_n1_trace; auto; [idtac].\n             repeat find_rewrite.\n             simpl.\n             in_crush.\n             discriminate.\n          -- subst.\n             find_apply_lem_hyp refl_trans_n1_1n_trace.\n             find_apply_lem_hyp reachable_intro.\n             match goal with\n             | [ H : reachable _ _ _ |- _ ] =>\n               let H' := fresh H in\n               pose H as H';\n                 eapply locks_correct_locked_invariant with (p := p) in H';\n                 [| now repeat find_rewrite; in_crush];\n                 eapply locks_correct_locked_at_head in H'; eauto\n             end.\n             unfold at_head_of_queue in *. break_exists. find_rewrite. find_inversion.\n             rewrite_update. auto.\n        * find_apply_lem_hyp ServerNetHandler_cases. intuition.\n          -- break_exists. intuition.\n             ++ subst. repeat find_rewrite. simpl in *.\n                find_inversion. auto.\n             ++ subst. repeat find_rewrite.\n                destruct (queue (nwState x' Server)); try congruence.\n                simpl in *. find_inversion.\n                do 2 insterU IHrefl_trans_n1_trace.\n                repeat conclude_using eauto.\n                intuition.\n                ** in_crush. discriminate.\n                ** in_crush. discriminate.\n          -- congruence.\n          -- break_exists. intuition. subst. simpl.\n             repeat find_rewrite. find_inversion. auto.\n          -- subst. simpl.\n             find_apply_hyp_hyp. intuition.\n             ++ repeat find_rewrite. in_crush. discriminate.\n             ++ repeat find_rewrite. in_crush.\n      + find_apply_lem_hyp InputHandler_cases.\n        intuition.\n        * break_exists. break_and. subst.\n          rewrite_update.\n          find_apply_hyp_hyp.\n          intuition.\n          -- subst. rewrite update_nop_ext. auto.\n          -- find_apply_lem_hyp refl_trans_n1_1n_trace.\n             find_apply_lem_hyp reachable_intro.\n             match goal with\n             | [ H : reachable _ _ _ |- _ ] =>\n               pose H as Hmutex;\n                 eapply mutual_exclusion_invariant in Hmutex\n             end.\n             unfold mutual_exclusion in *.\n             assert (c = x) by auto. clear Hmutex.\n             subst. simpl. auto.\n          -- subst. rewrite_update. auto.\n        * subst. simpl. rewrite update_nop_ext in *.\n          match goal with\n          | [ H : _ |- _ ] => apply IHrefl_trans_n1_trace in H; auto\n          end.\n  Qed.\n\n(* LIVENESS *)\n  \n  Lemma InputHandler_lbcases :\n    forall h i st l out st' ms,\n      InputHandler h i st = (l, out, st', ms) ->\n      (exists c, h = Client c /\\\n                 ((i = Lock /\\ out = [] /\\ st' = st /\\ ms = [(Server, Lock)] /\\ l = InputLock c) \\/\n                  (l = InputUnlock c /\\ i = Unlock /\\ out = [] /\\ held st' = false /\\\n                   ((held st = true /\\ ms = [(Server, Unlock)]) \\/\n                    (st' = st /\\ ms = []))))) \\/\n      (out = [] /\\ st' = st /\\ ms = [] /\\ l = Nop).\n  Proof using.\n    handler_unfold.\n    intros.\n    repeat break_match; repeat tuple_inversion;\n      subst; simpl in *; subst; simpl in *.\n    - left. eexists. intuition.\n    - left. eexists. intuition.\n    - left. eexists. intuition.\n    - auto.\n    - auto.\n  Qed.\n\n  Lemma ClientNetHandler_lbcases :\n    forall c m st l out st' ms,\n      ClientNetHandler c m st = (l, out, st', ms) ->\n      ms = [] /\\\n      ((st' = st /\\ out = [] /\\ l = Nop) \\/\n       (m = Locked /\\ out = [Locked] /\\ held st' = true /\\ l = MsgLocked c)).\n  Proof using.\n    handler_unfold.\n    intros.\n    repeat break_match; repeat tuple_inversion; subst; intuition.\n  Qed.\n  \n  Lemma ServerNetHandler_lbcases :\n    forall src m st l out st' ms,\n      ServerNetHandler src m st = (l, out, st', ms) ->\n      out = [] /\\\n      ((exists c, src = Client c /\\\n                  (m = Lock /\\\n                   l = MsgLock c /\\\n                   queue st' = queue st ++ [c] /\\\n                  ((queue st = [] /\\ ms = [(Client c, Locked)]) \\/\n                   (queue st <> [] /\\ ms = [])))) \\/\n       ((m = Unlock /\\ l = MsgUnlock /\\\n                   queue st' = tail (queue st) /\\\n                   ((queue st' = [] /\\ ms = []) \\/\n                    (exists next t, queue st' = next :: t /\\ ms = [(Client next, Locked)])))) \\/\n       ms = [] /\\ st' = st /\\ l = Nop).\n  Proof using.\n    handler_unfold.\n    intros.\n    repeat break_match; repeat tuple_inversion; subst.\n    - find_apply_lem_hyp null_sound. find_rewrite. simpl.\n      intuition. left. eexists. intuition.\n    - simpl. find_apply_lem_hyp null_false_neq_nil.\n      intuition. left. eexists. intuition.\n    - simpl. intuition.\n    - simpl. destruct st; simpl in *; subst; intuition.\n    - simpl in *. intuition.\n    - simpl in *. intuition eauto.\n    - simpl. intuition.\n  Qed.\n\n  Definition message_enables_label p l :=\n    forall net,\n      In p (nwPackets net) ->\n      lb_step_ex lb_step_async l net.\n  \n  Lemma Lock_enables_MsgLock :\n    forall i,\n      message_enables_label (mkPacket (Client i) Server Lock) (MsgLock i).\n  Proof using.\n    unfold message_enables_label.\n    intros.\n    find_apply_lem_hyp in_split.\n    break_exists_name xs. break_exists_name ys.\n    unfold enabled.\n    destruct (ServerNetHandler (Client i) Lock (nwState net Server)) eqn:?.\n    destruct p. destruct p.\n    cut (l0 = MsgLock i); intros.\n    subst.\n    - repeat eexists. econstructor; eauto.\n    - handler_unfold. repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Definition message_delivered_label p l :=\n    forall l' net net' tr,\n      lb_step_async net l' net' tr ->\n      In p (nwPackets net) ->\n      ~ In p (nwPackets net') ->\n      l = l'.\n\n  Lemma In_split_not_In :\n    forall A (p : A) p' xs ys zs,\n      In p (xs ++ p' :: ys) ->\n      ~ In p (zs ++ xs ++ ys) ->\n      p = p'.\n  Proof using.\n    intros.\n    find_apply_lem_hyp in_app_iff.\n    simpl in *; intuition;\n      find_false; apply in_app_iff; right; apply in_app_iff; auto.\n  Qed.\n\n  Lemma Lock_delivered_MsgLock :\n    forall i,\n      message_delivered_label (mkPacket (Client i) Server Lock) (MsgLock i).\n  Proof using.\n    unfold message_delivered_label.\n    intros.\n    invcs H.\n    - repeat find_rewrite.\n      find_eapply_lem_hyp In_split_not_In; eauto. subst.\n      monad_unfold. simpl in *.\n      handler_unfold. repeat break_match; repeat find_inversion; auto.\n    - unfold not in *. find_false.\n      apply in_app_iff; auto.\n    - intuition.\n  Qed.\n\n  Definition label_eq_dec :\n    forall x y : label,\n      {x = y} + {x <> y}.\n  Proof using.\n    decide equality; apply fin_eq_dec.\n  Qed.\n  \n  Lemma messages_trigger_labels :\n    forall l p,\n      message_enables_label p l ->\n      message_delivered_label p l ->\n      forall s,\n      lb_step_execution lb_step_async s ->\n      In p (nwPackets (evt_a (hd s))) ->\n      weak_until (now (enabled lb_step_async l))\n                 (now (occurred l))\n                 s.\n  Proof using.\n    intros l p Henabled Hdelivered.\n    cofix c.\n    destruct s. destruct e.\n    simpl.\n    intros Hexec Hin.\n    invcs Hexec.\n    destruct (label_eq_dec l evt_l).\n    - subst evt_l.\n      apply W0. simpl. reflexivity.\n    - apply W_tl.\n      + simpl.\n        unfold message_enables_label in *.\n        unfold enabled. simpl. now auto.\n      + simpl.\n        apply c; auto.\n        simpl.\n        match goal with\n        | |- In ?p ?ps =>\n          destruct (In_dec packet_eq_dec p ps)\n        end; auto.\n        unfold message_delivered_label in *.\n        now find_apply_hyp_hyp.\n  Qed.\n\n  Lemma message_labels_eventually_occur :\n    forall l p,\n      l <> label_silent ->\n      message_enables_label p l ->\n      message_delivered_label p l ->\n      forall s,\n        weak_fairness lb_step_async label_silent s ->\n        lb_step_execution lb_step_async s ->\n        In p (nwPackets (evt_a (hd s))) ->\n        eventually (now (occurred l)) s.\n  Proof using.\n    intros.\n    find_eapply_lem_hyp messages_trigger_labels; eauto.\n    find_apply_lem_hyp weak_until_until_or_always.\n    intuition.\n    - now eauto using until_eventually.\n    - find_apply_lem_hyp always_continuously.\n      eapply_prop_hyp weak_fairness continuously; auto.\n      destruct s.\n      now find_apply_lem_hyp always_now.\n  Qed.\n\n  Ltac coinductive_case CIH :=\n    apply W_tl; simpl in *; auto;\n    apply CIH; simpl in *; auto.\n\n  Lemma Nth_app :\n    forall A (l : list A) l' a n,\n      Nth l n a ->\n      Nth (l ++ l') n a.\n  Proof using.\n    induction l; intros; simpl in *; try solve_by_inversion.\n    invcs H.\n    - constructor.\n    - constructor. auto.\n  Qed.\n\n  Lemma Nth_tl :\n    forall A (l : list A) a n,\n      Nth l (S n) a ->\n      Nth (List.tl l) n a.\n  Proof using.\n    induction l; intros; solve_by_inversion.\n  Qed.\n    \n  Lemma clients_only_move_up_in_queue :\n    forall n c s,\n      lb_step_execution lb_step_async s ->\n      Nth (queue (nwState (evt_a (hd s)) Server)) (S n) c ->\n      weak_until (fun s => Nth (queue (nwState (evt_a (hd s)) Server)) (S n) c)\n                 (next (fun s => Nth (queue (nwState (evt_a (hd s)) Server)) n c\n                        /\\ (n = 0 -> In (mkPacket Server (Client c) Locked)\n                                      (nwPackets (evt_a (hd s))))))\n                 s.\n  Proof using.\n    intros n c.\n    cofix CIH.\n    destruct s.\n    destruct e.\n    intros Hexec HNth.\n    invcs Hexec.\n    invcs H1.\n    - unfold runGenHandler, NetHandler in *.\n      break_match.\n      + coinductive_case CIH.\n        find_rewrite. simpl.\n        now rewrite_update.\n      + find_apply_lem_hyp ServerNetHandler_lbcases.\n        intuition.\n        * coinductive_case CIH. \n          repeat find_rewrite. simpl.\n          rewrite_update.\n          break_exists.\n          intuition; repeat find_rewrite; try solve_by_inversion.\n          now eauto using Nth_app.\n        * exfalso. clear CIH.\n          subst.\n          invcs HNth.\n          repeat find_reverse_rewrite. simpl in *.\n          repeat find_rewrite. now solve_by_inversion.\n        * clear CIH.\n          apply W0. simpl.\n          fold LockServ_MultiParams in *. (* typeclass stuff *)\n          repeat find_rewrite. simpl.\n          rewrite_update. repeat find_rewrite.\n          intuition eauto using Nth_tl.\n          break_exists.\n          intuition. subst.\n          find_apply_lem_hyp Nth_tl.\n          repeat find_rewrite.\n          invcs HNth. auto.\n        * coinductive_case CIH. \n          repeat find_rewrite. simpl.\n          now rewrite_update.\n    - unfold runGenHandler in *.\n      find_apply_lem_hyp InputHandler_cases.\n      intuition.\n      + break_exists. break_and. subst.\n        coinductive_case CIH.\n        repeat find_rewrite. simpl.\n        now rewrite_update.\n      + coinductive_case CIH.\n        repeat find_rewrite. simpl.\n        update_destruct; subst; now rewrite_update.\n    - coinductive_case CIH.\n  Qed.\n\n  Lemma MsgUnlock_moves_client :\n    forall n c s,\n      lb_step_execution lb_step_async s ->\n      Nth (queue (nwState (evt_a (hd s)) Server)) (S n) c ->\n      now (occurred MsgUnlock) s ->\n      next (fun s => Nth (queue (nwState (evt_a (hd s)) Server)) n c\n                  /\\ (n = 0 -> In (mkPacket Server (Client c) Locked)\n                                (nwPackets (evt_a (hd s))))) s.\n  Proof using.\n    intros n c s Hexec HNth Hlabel.\n    destruct s. simpl.\n    invcs Hexec.\n    match goal with\n    | H : lb_step_async _ _ _ _ |- _ => invcs H\n    end.\n    - unfold occurred in *.\n      match goal with\n      | H : MsgUnlock = _ |- _ => symmetry in H; repeat find_rewrite; clear H\n      end.\n      monad_unfold. unfold NetHandler in *.\n      break_match.\n      + find_apply_lem_hyp ClientNetHandler_lbcases.\n        intuition; congruence.\n      + find_apply_lem_hyp ServerNetHandler_lbcases.\n        (* not using intuition because i don't want to break\n           or in the goal *)\n        repeat (break_and; try break_or_hyp);\n          break_exists;\n        repeat (break_and; try break_or_hyp);\n        try congruence.\n        * exfalso.\n          repeat find_rewrite.\n          invcs HNth.\n          repeat find_reverse_rewrite.\n          simpl in *. subst. solve_by_inversion.\n        * fold LockServ_MultiParams in *. (* typeclass stuff *)\n          repeat find_rewrite.\n          simpl in *.\n          find_apply_lem_hyp Nth_tl.\n          repeat find_rewrite.\n          intuition; [|intros; subst; solve_by_inversion].\n          rewrite_update. congruence.\n    - unfold occurred in *.\n      match goal with\n      | H : MsgUnlock = _ |- _ => symmetry in H; repeat find_rewrite; clear H\n      end.\n      monad_unfold. find_apply_lem_hyp InputHandler_lbcases.\n      intuition; break_exists; intuition; congruence.\n    - unfold occurred in *. congruence.\n  Qed.\n\n  Lemma Unlock_enables_MsgUnlock :\n    forall n,\n      message_enables_label (mkPacket n Server Unlock) MsgUnlock.\n  Proof using.\n    unfold message_enables_label.\n    intros.\n    find_apply_lem_hyp in_split.\n    break_exists_name xs. break_exists_name ys.\n    unfold enabled.\n    destruct (ServerNetHandler n Unlock (nwState net Server)) eqn:?.\n    destruct p. destruct p.\n    cut (l0 = MsgUnlock); intros.\n    subst.\n    - repeat eexists. econstructor; eauto.\n    - handler_unfold. repeat break_match; repeat find_inversion; auto.\n  Qed.\n  \n  Lemma Unlock_delivered_MsgUnlock :\n    forall n,\n      message_delivered_label (mkPacket n Server Unlock) MsgUnlock.\n  Proof using.\n    unfold message_delivered_label.\n    intros.\n    invcs H.\n    - repeat find_rewrite.\n      find_eapply_lem_hyp In_split_not_In; eauto. subst.\n      monad_unfold. simpl in *.\n      handler_unfold. repeat break_match; repeat find_inversion; auto.\n    - unfold not in *. find_false.\n      apply in_app_iff; auto.\n    - intuition.\n  Qed.\n\n  Lemma Unlock_in_network_eventually_MsgUnlock :\n    forall c s,\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      In (mkPacket c Server Unlock) (nwPackets (evt_a (hd s))) ->\n      eventually (now (occurred MsgUnlock)) s.\n  Proof using.\n    intros.\n    eapply message_labels_eventually_occur;\n      eauto using Unlock_enables_MsgUnlock, Unlock_delivered_MsgUnlock.\n    unfold label_silent. simpl. congruence.\n  Qed.\n\n  Lemma Nth_something_at_head :\n    forall A (l : list A) n x,\n      Nth l n x ->\n      exists y l',\n        l = y :: l'.\n  Proof using.\n    intros.\n    solve_by_inversion' eauto.\n  Qed.\n\n  Lemma InputUnlock_held :\n    forall s c,\n      lb_step_execution lb_step_async s ->\n      held (nwState (evt_a (hd s)) (Client c)) = true ->\n      now (occurred (InputUnlock c)) s ->\n      next (fun s => In (mkPacket (Client c) Server Unlock) (nwPackets (evt_a (hd s)))) s.\n  Proof using.\n    intros.\n    invcs H.\n    invcs H2.\n    - monad_unfold.\n      unfold NetHandler in *.\n      break_match_hyp.\n      + unfold occurred in *.\n        find_apply_lem_hyp ClientNetHandler_lbcases; intuition; congruence.\n      + unfold occurred in *.\n        find_apply_lem_hyp ServerNetHandler_lbcases; intuition;\n          break_exists; intuition; congruence.\n    - monad_unfold.\n      find_apply_lem_hyp InputHandler_lbcases.\n      intuition; try congruence.\n      break_exists. intuition; try congruence.\n      fold LockServ_MultiParams in *. (* typeclass stuff *)\n      repeat find_rewrite.\n      simpl. left. unfold occurred in *.\n      congruence.\n    - unfold occurred in *. congruence.\n  Qed.\n\n  Lemma InputHandler_Client_Unlock :\n    forall c sigma,\n      exists sigma' os ms,\n        InputHandler (Client c) Unlock sigma = (InputUnlock c, os, sigma', ms).\n  Proof using.\n    intros.\n    unfold InputHandler. unfold ClientIOHandler.\n    monad_unfold. repeat break_let.\n    find_inversion. eauto.\n  Qed.\n  \n  Lemma InputUnlock_enabled :\n    forall s c,\n      lb_step_execution lb_step_async s ->\n      now (enabled lb_step_async (InputUnlock c)) s.\n  Proof using.\n    intros.\n    destruct s. simpl.\n    unfold enabled, enabled.\n    pose proof (InputHandler_Client_Unlock c (nwState (evt_a e) (Client c))).\n    break_exists.\n    repeat eexists.\n    unfold InputHandler in *. unfold ClientIOHandler in *.\n    eapply LabeledStepAsync_input with (h := (Client c)) (inp := Unlock); eauto.\n  Qed.\n\n  Lemma InputUnlock_continuously_enabled :\n    forall s c,\n      lb_step_execution lb_step_async s ->\n      cont_enabled lb_step_async (InputUnlock c) s.\n  Proof using.\n    unfold cont_enabled.\n    intros.\n    apply always_continuously.\n    eapply always_monotonic;\n      [|eapply always_inv; eauto; eauto using lb_step_execution_invar];\n      eauto using InputUnlock_enabled.\n  Qed.\n\n  Lemma held_until_Unlock :\n    forall c s,\n      lb_step_execution lb_step_async s ->\n      held (nwState (evt_a (hd s)) (Client c)) = true ->\n      weak_until (fun s => held (nwState (evt_a (hd s)) (Client c)) = true)\n                 (next (fun s => In (mkPacket (Client c) Server Unlock) (nwPackets (evt_a (hd s)))))\n                 s.\n  Proof using.\n    intros c.\n    cofix CIH.\n    destruct s. simpl.\n    intros.\n    invcs H.\n    invcs H3.\n    - coinductive_case CIH.\n      monad_unfold.\n      unfold NetHandler in *.\n      break_match_hyp.\n      + find_apply_lem_hyp ClientNetHandler_cases.\n        repeat find_rewrite. simpl.\n        intuition;\n          update_destruct_max_simplify; repeat find_rewrite; auto.\n      + find_apply_lem_hyp ServerNetHandler_cases.\n        repeat find_rewrite. simpl.\n        intuition; break_exists; intuition;\n          rewrite_update; repeat find_rewrite; auto.\n    - monad_unfold.\n      find_apply_lem_hyp InputHandler_lbcases.\n      intuition; break_exists; intuition.\n      + coinductive_case CIH.\n        repeat find_rewrite.\n        simpl.\n        update_destruct_max_simplify; repeat find_rewrite; auto.\n      + subst. \n        destruct (fin_eq_dec _ c x).\n        * clear CIH. subst.\n          apply W0; simpl.\n          fold LockServ_MultiParams in *. (* typeclass stuff *)\n          repeat find_rewrite.\n          simpl. auto.\n        * coinductive_case CIH.\n          repeat find_rewrite.\n          simpl. now rewrite_update.\n      + coinductive_case CIH.\n        clear CIH.\n        repeat find_rewrite.\n        simpl.\n        update_destruct_max_simplify; repeat find_rewrite; auto.\n      + coinductive_case CIH. clear CIH.\n        repeat find_rewrite.\n        simpl. \n        update_destruct_max_simplify; repeat find_rewrite; auto.\n    - coinductive_case CIH.\n      congruence.\n  Qed.\n\n  Lemma held_eventually_InputUnlock :\n    forall c s,\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      eventually (now (occurred (InputUnlock c))) s.\n  Proof using.\n    intros.\n    pose proof (@InputUnlock_continuously_enabled s c). intuition.\n    eapply_prop_hyp weak_fairness cont_enabled; [|now unfold label_silent].\n    solve_by_inversion.\n  Qed.\n    \n  Lemma held_eventually_Unlock :\n    forall s c,\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      held (nwState (evt_a (hd s)) (Client c)) = true ->\n      eventually (fun s => In (mkPacket (Client c) Server Unlock)\n                           (nwPackets (evt_a (hd s)))) s.\n  Proof using.\n    intros. apply eventually_next.\n    match goal with\n    | H : context [held] |- _ =>\n      pattern s in H\n    end.\n    match goal with\n    | H1 : ?J1 s, H2 : ?J2 s, H3 : ?J3 s |- _ =>\n      assert ((J1 /\\_ J2 /\\_ J3) s) by (now unfold and_tl);\n        eapply weak_until_eventually with (J := (and_tl J1 (and_tl J2 J3)))\n    end; simpl in *.\n    2:now unfold and_tl.\n    3:eauto using held_eventually_InputUnlock.\n    - intros. unfold and_tl in *. intuition.\n      eapply InputUnlock_held; eauto.\n    - apply weak_until_always; eauto using lb_step_execution_invar, always_inv.\n      apply weak_until_always; eauto using weak_fairness_invar, always_inv.\n      eauto using held_until_Unlock.\n  Qed.\n    \n  Lemma Locked_enables_MsgLocked :\n    forall i, message_enables_label\n           {| pSrc := Server; pDst := Client i; pBody := Locked |}\n           (MsgLocked i).\n  Proof using.\n    unfold message_enables_label, enabled.\n    intros.\n    find_apply_lem_hyp in_split.\n    break_exists_name xs. break_exists_name ys.\n    do 2 eexists.\n    eapply LabeledStepAsync_deliver; eauto.\n    simpl. monad_unfold. simpl. eauto.\n  Qed.\n\n  Lemma Locked_delivered_MsgLocked :\n    forall i, message_delivered_label\n           {| pSrc := Server; pDst := Client i; pBody := Locked |}\n           (MsgLocked i).\n  Proof using.\n    unfold message_delivered_label.\n    intros.\n    invcs H.\n    - repeat find_rewrite.\n      find_eapply_lem_hyp In_split_not_In; eauto. subst.\n      monad_unfold. simpl in *.\n      handler_unfold. repeat break_match; repeat find_inversion; auto.\n    - unfold not in *. find_false.\n      apply in_app_iff; auto.\n    - intuition.\n  Qed.\n\n  Lemma Locked_in_network_eventually_MsgLocked :\n    forall i s,\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      In (mkPacket Server (Client i) Locked) (nwPackets (evt_a (hd s))) ->\n      eventually (now (occurred (MsgLocked i))) s.\n  Proof using.\n    intros.\n    eapply message_labels_eventually_occur;\n      eauto using Locked_enables_MsgLocked, Locked_delivered_MsgLocked.\n    unfold label_silent. simpl. congruence.\n  Qed.\n  \n  Lemma MsgLocked_held :\n    forall s c,\n      lb_step_execution lb_step_async s ->\n      now (occurred (MsgLocked c)) s ->\n      next (fun s => held (nwState (evt_a (hd s)) (Client c)) = true) s.\n  Proof using.\n    intros.\n    invcs H.\n    invcs H1.\n    - monad_unfold.\n      unfold NetHandler in *.\n      break_match_hyp.\n      + unfold occurred in *.\n        fold LockServ_MultiParams in *. (* typeclass stuff *)\n        repeat find_rewrite. simpl.\n        find_apply_lem_hyp ClientNetHandler_lbcases; intuition; subst;\n          update_destruct_max_simplify; congruence.\n      + unfold occurred in *.\n        find_apply_lem_hyp ServerNetHandler_lbcases; intuition;\n          break_exists; intuition; congruence.\n    - monad_unfold.\n      find_apply_lem_hyp InputHandler_lbcases.\n      intuition; break_exists; intuition; congruence.\n    - congruence.\n  Qed.\n\n  Lemma eventually_Unlock :\n    forall n c s,\n      event_step_star step_async step_async_init (hd s) ->\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      Nth (queue (nwState (evt_a (hd s)) Server)) (S n) c ->\n      exists c,\n        eventually (fun s => In (mkPacket c Server Unlock) (nwPackets (evt_a (hd s)))) s.\n  Proof using.\n    intros.\n    find_apply_lem_hyp Nth_something_at_head.\n    break_exists_name holder. break_exists.\n    exists (Client holder).\n    remember H0 as Hlbs; clear HeqHlbs.\n    invcs H0.\n    find_eapply_lem_hyp head_grant_state_unlock; eauto.\n    intuition.\n    - (* eventually the Locked message is delivered, after which this is\n         the same as the next case. *)\n      eapply eventually_trans\n      with (inv := lb_step_execution lb_step_async /\\_\n                   weak_fairness\n                     (lb_step_async(labeled_multi_params := LockServ_LabeledParams))\n                     Silent)\n             (P := now (occurred (MsgLocked holder))).\n      all:unfold and_tl in *; intuition.\n      + eauto using lb_step_execution_invar.\n      + eauto using weak_fairness_invar.\n      + (* need `now (MsgLocked i) -> held i = true`, then identical to next case below. *)\n        find_apply_lem_hyp MsgLocked_held; eauto.\n        destruct s.\n        simpl in *.\n        eauto using lb_step_execution_invar, weak_fairness_invar,\n          E_next, held_eventually_Unlock.\n      + apply Locked_in_network_eventually_MsgLocked; auto.\n    - eauto using held_eventually_Unlock.\n    - eauto using E0.\n  Qed.\n  \n  Lemma eventually_MsgUnlock :\n    forall n c s,\n      event_step_star step_async step_async_init (hd s) ->\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      Nth (queue (nwState (evt_a (hd s)) Server)) (S n) c ->\n      eventually (now (occurred MsgUnlock)) s.\n  Proof using.\n    intros n c s Hstar Hexec Hfair HNth.\n    pattern s in Hexec. pattern s in Hfair.\n    find_copy_eapply_lem_hyp eventually_Unlock; eauto.\n    break_exists.\n    match goal with\n    | H1 : (fun x => ?J1) s, H2 : (fun x => ?J2) s |- _ =>\n      assert (and_tl (fun x => J1) (fun x => J2) s) as Hand by (now unfold and_tl);\n        clear H1; clear H2\n    end; simpl in *.\n    eapply eventually_trans.\n    4:eauto. 3:apply Hand.\n    2:intros; eapply Unlock_in_network_eventually_MsgUnlock.\n    all:unfold and_tl in *; intuition eauto.\n    - eauto using lb_step_execution_invar.\n    - simpl. eauto using weak_fairness_invar.\n  Qed.\n  \n    \n  (* Sketch: eventually an Unlock happens, so eventually a MsgUnlock\n     happens, so eventually a client moves up the queue. when this\n     happens, the server will send it a Locked msg if it's at the\n     head.\n\n     Gonna use weak_until_eventually and probs eventually_next\n *)\n  Lemma clients_move_up_in_queue :\n    forall n c s,\n      event_step_star step_async step_async_init (hd s) ->\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      Nth (queue (nwState (evt_a (hd s)) Server)) (S n) c ->\n      eventually (fun s => Nth (queue (nwState (evt_a (hd s)) Server)) n c\n                        /\\ (n = 0 -> In (mkPacket Server (Client c) Locked)\n                                     (nwPackets (evt_a (hd s)))))\n                 s.\n  Proof using.\n    intros n c s Hstar Hexec Hfair HNth.\n    apply eventually_next.\n    pattern s in HNth.\n    match goal with\n    | H1 : ?J1 s, H2 : ?J2 s, H3 : ?J3 s |- _ =>\n      assert ((J1 /\\_ J2 /\\_ J3) s) by (now unfold and_tl);\n        eapply weak_until_eventually with (J := (and_tl J1 (and_tl J2 J3)))\n    end; simpl in *.\n    2:now unfold and_tl.\n    3:eauto using eventually_MsgUnlock.\n    - intros. unfold and_tl in *. intuition.\n      eapply MsgUnlock_moves_client; eauto.\n    - apply weak_until_always; eauto using lb_step_execution_invar, always_inv.\n      apply weak_until_always; eauto using weak_fairness_invar, always_inv.\n      eauto using clients_only_move_up_in_queue.\n  Qed.\n\n  Lemma clients_move_way_up_in_queue :\n    forall n n' c s,\n      n' <= n ->\n      event_step_star step_async step_async_init (hd s) ->\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      (Nth (queue (nwState (evt_a (hd s)) Server)) (S n) c\n       /\\ (S n = 0 -> In (mkPacket Server (Client c) Locked)\n                                     (nwPackets (evt_a (hd s))))) ->\n      eventually (fun s => Nth (queue (nwState (evt_a (hd s)) Server)) n' c\n                        /\\ (n' = 0 -> In (mkPacket Server (Client c) Locked)\n                                     (nwPackets (evt_a (hd s)))))\n                 s.\n  Proof using.\n    induction n; intros; simpl in *; auto.\n    - intuition.\n      assert (n' = 0) by omega. subst.\n      eauto using clients_move_up_in_queue.\n    - match goal with\n      | H : _ (hd s) |- _ =>\n        pattern s in H\n      end.\n      match goal with\n      | H1 : ?J1 s, H2 : ?J2 s, H3 : ?J3 s |- _ =>\n        assert ((J1 /\\_ J2 /\\_ J3) s) as Hand by (now unfold and_tl);\n          clear H1; clear H2; clear H3\n      end; simpl in *.\n      find_apply_lem_hyp le_lt_eq_dec. intuition.\n      + assert (n' <= n) by omega.\n        find_eapply_lem_hyp clients_move_up_in_queue; eauto;\n          try solve [unfold and_tl in *; intuition]; [idtac].\n        eapply eventually_trans. 4:eauto.\n        3:apply Hand. all:unfold and_tl in *.\n        all:intuition eauto using lb_step_execution_invar, weak_fairness_invar.\n        find_apply_lem_hyp step_async_star_lb_step_execution; auto.\n        destruct s0. simpl in *.\n        find_apply_lem_hyp always_Cons.\n        intuition.\n        find_apply_lem_hyp always_Cons.\n        intuition.\n      + subst. unfold and_tl in *. intuition.\n        eauto using clients_move_up_in_queue.\n  Qed.\n\n  Lemma clients_get_lock_messages :\n    forall n c s,\n      event_step_star step_async step_async_init (hd s) ->\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      Nth (queue (nwState (evt_a (hd s)) Server)) (S n) c ->\n      eventually (fun s =>\n                    In (mkPacket Server (Client c) Locked)\n                       (nwPackets (evt_a (hd s)))) s.\n  Proof using.\n    intros.\n    pose proof (@clients_move_way_up_in_queue n 0 c s).\n    pose proof (Nat.le_0_l n).\n    repeat concludes. conclude_using ltac:(intuition; congruence).\n    eapply eventually_monotonic_simple; [|eauto].\n    intros. simpl in *. intuition.\n  Qed.\n\n  Lemma InputLock_Lock :\n    forall s c,\n      lb_step_execution lb_step_async s ->\n      now (occurred (InputLock c)) s ->\n      next (fun s => In (mkPacket (Client c) Server Lock) (nwPackets (evt_a (hd s)))) s.\n  Proof using.\n    intros.\n    invcs H.\n    invcs H1.\n    - monad_unfold.\n      unfold NetHandler in *.\n      break_match_hyp.\n      + unfold occurred in *.\n        find_apply_lem_hyp ClientNetHandler_lbcases; intuition; congruence.\n      + unfold occurred in *.\n        find_apply_lem_hyp ServerNetHandler_lbcases; intuition;\n          break_exists; intuition; congruence.\n    - monad_unfold.\n      find_apply_lem_hyp InputHandler_lbcases.\n      intuition; try congruence.\n      break_exists. intuition; try congruence.\n      fold LockServ_MultiParams in *. (* typeclass stuff *)\n      repeat find_rewrite.\n      simpl. left. unfold occurred in *.\n      congruence.\n    - unfold occurred in *. congruence.\n  Qed.\n  \n  Lemma Lock_in_network_eventually_MsgLock :\n    forall c s,\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      In (mkPacket (Client c) Server Lock) (nwPackets (evt_a (hd s))) ->\n      eventually (now (occurred (MsgLock c))) s.\n  Proof using.\n    intros.\n    eapply message_labels_eventually_occur;\n      eauto using Lock_enables_MsgLock, Lock_delivered_MsgLock.\n    unfold label_silent. simpl. congruence.\n  Qed.\n\n  Lemma InputLock_eventually_MsgLock :\n    forall c s,\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      now (occurred (InputLock c)) s ->\n      eventually (now (occurred (MsgLock c))) s.\n  Proof using.\n    intros.\n    find_apply_lem_hyp InputLock_Lock; auto.\n    destruct s.\n    simpl in *.\n    eauto using E_next, Lock_in_network_eventually_MsgLock,\n       lb_step_execution_invar, weak_fairness_invar.\n  Qed.\n\n  Lemma Nth_snoc :\n    forall A (l : list A) x,\n      Nth (l ++ [x]) (length l) x.\n  Proof using.\n    intros.\n    induction l; simpl in *; constructor; auto.\n  Qed.\n\n  Lemma MsgLock_in_queue_or_Locked :\n    forall c s,\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      now (occurred (MsgLock c)) s ->\n      next (fun s =>\n              In (mkPacket Server (Client c) Locked)\n                 (nwPackets (evt_a (hd s)))) s \\/\n      exists n,\n        next (fun s =>\n                Nth (queue (nwState (evt_a (hd s)) Server)) (S n) c) s.\n  Proof using.\n    intros.\n    invcs H.\n    invcs H2.\n    - monad_unfold.\n      unfold NetHandler in *.\n      break_match_hyp.\n      + unfold occurred in *.\n        find_apply_lem_hyp ClientNetHandler_lbcases; intuition; congruence.\n      + unfold occurred in *.\n        find_apply_lem_hyp ServerNetHandler_lbcases; intuition;\n          break_exists; intuition; try congruence; [left|right];\n            fold LockServ_MultiParams in *; (* typeclass stuff *)\n            repeat find_rewrite; simpl.\n        * left. congruence.\n        * update_destruct_max_simplify; try congruence.\n          find_inversion.\n          repeat find_rewrite.\n          destruct (queue (nwState (evt_a e) Server)) eqn:?; try congruence.\n          exists (length l). simpl.\n          constructor.\n          apply Nth_snoc.\n    - monad_unfold.\n      find_apply_lem_hyp InputHandler_lbcases.\n      intuition; try congruence.\n      break_exists. intuition; congruence.\n    - unfold occurred in *. congruence.\n  Qed.\n\n  Lemma MsgLock_Locked :\n    forall c s,\n      event_step_star step_async step_async_init (hd s) ->\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      now (occurred (MsgLock c)) s ->\n      eventually\n        (fun s => In (mkPacket Server (Client c) Locked)\n                  (nwPackets (evt_a (hd s)))) s.\n  Proof using.\n    intros.\n    find_apply_lem_hyp MsgLock_in_queue_or_Locked; auto.\n    intuition.\n    - destruct s; simpl in *; eauto using E_next, E0.\n    - break_exists.\n      destruct s; simpl in *.\n      apply E_next.\n      eapply clients_get_lock_messages;\n        eauto using lb_step_execution_invar,\n                    weak_fairness_invar.\n      find_apply_lem_hyp step_async_star_lb_step_execution; auto.\n      destruct s. simpl.\n      do 2 (find_apply_lem_hyp always_Cons; intuition).\n  Qed.\n\n  Lemma MsgLock_eventually_MsgLocked :\n    forall c s,\n      event_step_star step_async step_async_init (hd s) ->\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      now (occurred (MsgLock c)) s ->\n      eventually (now (occurred (MsgLocked c))) s.\n  Proof using.\n    intros c s Hss Hlbs Hfair.\n    match goal with\n    | H : _ (hd s) |- _ =>\n      pattern s in H\n    end.\n    match goal with\n    | H1 : ?J1 s, H2 : ?J2 s, H3 : ?J3 s |- _ =>\n      assert ((J1 /\\_ J2 /\\_ J3) s) as Hand by (now unfold and_tl);\n        clear H1; clear H2; clear H3\n    end; simpl in *. intros.\n    eapply eventually_trans.\n    4:eapply MsgLock_Locked; eauto; unfold and_tl in *; intuition.\n    3:apply Hand. all:unfold and_tl in *.\n    all:intuition eauto using lb_step_execution_invar, weak_fairness_invar.\n    - find_apply_lem_hyp step_async_star_lb_step_execution; auto.\n      destruct s0. simpl in *.\n      find_apply_lem_hyp always_Cons.\n      intuition.\n      find_apply_lem_hyp always_Cons.\n      intuition.\n    - eauto using Locked_in_network_eventually_MsgLocked.\n  Qed.\n  \n  (* label-based correctness theorem *)\n  Theorem locking_clients_eventually_receive_lock_lb :\n    forall c s,\n      event_step_star step_async step_async_init (hd s) ->\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      now (occurred (InputLock c)) s ->\n      eventually (now (occurred (MsgLocked c))) s.\n  Proof using.\n    intros c s Hss Hlbs Hfair.\n    match goal with\n    | H : _ (hd s) |- _ =>\n      pattern s in H\n    end.\n    match goal with\n    | H1 : ?J1 s, H2 : ?J2 s, H3 : ?J3 s |- _ =>\n      assert ((J1 /\\_ J2 /\\_ J3) s) as Hand by (now unfold and_tl);\n        clear H1; clear H2; clear H3\n    end; simpl in *. intros.\n    eapply eventually_trans.\n    4:eapply InputLock_eventually_MsgLock; eauto; unfold and_tl in *; intuition.\n    3:apply Hand. all:unfold and_tl in *.\n    all:intuition eauto using lb_step_execution_invar, weak_fairness_invar.\n    - find_apply_lem_hyp step_async_star_lb_step_execution; auto.\n      destruct s0. simpl in *.\n      find_apply_lem_hyp always_Cons.\n      intuition.\n      find_apply_lem_hyp always_Cons.\n      intuition.\n    - eauto using MsgLock_eventually_MsgLocked.\n  Qed.\n\n  (* label + state-based correctness theorem *)\n  Theorem locking_clients_eventually_receive_lock_st :\n    forall c s,\n      event_step_star step_async step_async_init (hd s) ->\n      lb_step_execution lb_step_async s ->\n      weak_fairness lb_step_async label_silent s ->\n      now (occurred (InputLock c)) s ->\n      eventually (fun s => held (nwState (evt_a (hd s)) (Client c)) = true) s.\n  Proof using.\n    intros.\n    find_eapply_lem_hyp locking_clients_eventually_receive_lock_lb; eauto.\n    apply eventually_next.\n    eapply eventually_monotonic with (J := lb_step_execution lb_step_async).\n    4:eauto.\n    all:eauto using lb_step_execution_invar.\n    eauto using MsgLocked_held.\n  Qed.\n  \nEnd LockServ.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/verdi/systems/LiveLockServ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.22945855034484888}}
{"text": "Require Import language.\nRequire Import msl.base.\nRequire Import msl.seplog.\nRequire Import msl.alg_seplog.\n\nLocal Open Scope logic.\n\nDefinition lift0 {B} (P: B) : env -> B := fun _ => P.\nDefinition lift1 {A1 B} (P: A1 -> B) (f1: env -> A1) : env -> B := fun rho => P (f1 rho).\nDefinition lift2 {A1 A2 B} (P: A1 -> A2 -> B) (f1: env -> A1) (f2: env -> A2): \n   env -> B := fun rho => P (f1 rho) (f2 rho).\n\nDefinition subst' {A} (x: var) (e: env -> adr) (P: env -> A) : env -> A := fun s => subst x (e s) P s.\n\nDefinition neq {A} (x y: A) := ~(x=y).\nDefinition local {A}{NA: NatDed A} (P: env -> Prop) : env -> A := fun s => prop (P s).\n\n\nModule Type SEMAX_LIFT.\n\n  Parameter mpred : Type.\n  Parameter Nm: NatDed mpred.  Existing Instance Nm.\n  Parameter Sm: SepLog mpred.  Existing Instance Sm.\n  Parameter Cm: ClassicalSep mpred.  Existing Instance Cm.\n  Parameter Im: Indir mpred.  Existing Instance Im.\n  Parameter Rm: RecIndir mpred.  Existing Instance Rm.\n  Parameter SIm: SepIndir mpred.  Existing Instance SIm.\n  Parameter SRm: SepRec mpred.  Existing Instance SRm.\n\n  Parameter mapsto: forall (v1 v2: adr), mpred.\n\n  Axiom mapsto_conflict:  forall a b c, mapsto a b  *  mapsto a c |-- FF.\n\n  Definition assert := env -> mpred.\n  Bind Scope logic with assert.\n\n  Definition funspec := (list var * assert)%type.\n  Definition funspecs := table adr funspec.\n\n  Definition call (P: list var * assert) (vl: list adr) : mpred := \n     (!! (length vl = length (fst P)) && snd P (arguments (fst P) vl)). \n  Parameter cont: forall (nP: funspec)  (v: adr), mpred.\n\nDefinition funassert (G: funspecs) : mpred := \n   (ALL  i:_, ALL P:_,  !! (table_get G i = Some P) --> cont P i)  && \n   (ALL  i:_, ALL P:_,  cont P i --> !! exists P', table_get G i = Some P').\n\n\n  Axiom funassert_get:\n  forall G v nP,  funassert  G && cont nP v |--\n                      EX P':assert, (ALL vl:list adr, |> ! (call nP vl <=> call (fst nP,P') vl)) && !! (table_get G v = Some (fst nP,P')).\n\n  Parameter allocpool: forall (b: adr), mpred.\n  Axiom alloc: forall b, allocpool b = ((!! (b > 0) && mapsto b 0) * allocpool (S b)).\n\n  Parameter semax : varset -> funspecs -> assert -> control -> Prop.\n  Parameter semax_func: forall (G: funspecs) (p: program) (G': funspecs), Prop.\n\n  Axiom semax_func_nil: forall G, semax_func G nil nil.\n  Axiom semax_func_cons: \n   forall  fs id f vars P (G G': funspecs),\n      inlist id (map (@fst adr (list var * control)) fs) = false ->\n      list_nodups vars = true ->\n      length vars = length (fst P) ->\n(*      semax vars G (fun s => call P (map s vars)) f -> *)\n      semax vars G (lift1 (call P) (fun s => map s vars)) f ->\n      semax_func G fs G' ->\n      semax_func G ((id, (vars,f))::fs) ((id, P) :: G').\n\n  Definition program_proved (p: program) :=\n   exists G, semax_func G p G \n                            /\\ table_get G 0 = Some  (0::nil, lift1 allocpool (eval (Var 0))).\n\n  Axiom semax_sound: \n  forall p, program_proved p -> forall n, run p n <> None.\n\n  Axiom semax_go:  forall vars G (P: funspec) x ys,   \n    typecheck vars (Go x ys) = true ->\n    semax vars G (lift1 (cont P) (eval x) && lift1 (call P) (eval_list ys)) (Go x ys) .\n\nAxiom semax_assign: forall x y c vars G P,\n    expcheck vars y = true ->\n    semax (vs_add x vars) G P c -> \n    semax vars G (|> subst' x (eval y) P) (Do x := y ; c). \n\nAxiom semax_if: forall x c1 c2 vars G (P: assert),\n    expcheck vars x = true ->\n    semax vars G (local (lift2 neq (eval x) (lift0 0)) && P) c1 ->\n    semax vars G (local (lift2 eq (eval x) (lift0 0)) && P) c2 ->\n    semax vars G P (If x Then c1 Else c2).\n\nAxiom semax_load:  forall x y z c vars G P,\n    expcheck vars y = true ->\n    semax (vs_add x vars) G P c -> \n    semax vars G ((lift2 mapsto (eval y) (lift0 z) * TT) && |> subst' x (lift0 z) P)\n               (Do x := Mem y ; c).\n\nAxiom semax_store: forall x y v c vars G (P: assert),\n    expcheck vars x = true ->\n    expcheck vars y = true ->\n    semax vars G (lift2 mapsto (eval x) (eval y) * P) c ->\n    semax vars G (lift2 mapsto (eval x) (lift0 v)  * P)  (Do Mem x  := y ; c).\n\nAxiom semax_pre: \n  forall P P' vars G c, (forall s, P s |-- P' s) -> semax vars G P' c -> semax vars G P c.\n\nAxiom semax_exp: forall A vars G (P: A -> assert) c,\n    typecheck vars c = true ->\n    (forall v:A, semax vars G (P v) c) ->\n    semax vars G (EX v:A, (P v)) c.\n\nAxiom semax_exp': forall A (any: A) vars G (P: A -> assert) c,\n    (forall v:A, semax vars G (P v) c) ->\n    semax vars G (EX v:A, (P v)) c.\n\nAxiom semax_prop:\n  forall (R: Prop) vars G P c,\n      typecheck vars c = true ->\n      (R -> semax vars G P c) ->\n      semax vars G (!!R && P) c.\n\nAxiom semax_G:\n   forall vars G P c, semax vars G (P && lift0 (funassert G)) c -> semax vars G P c.\n\nEnd SEMAX_LIFT.\n\nRequire Import seplogic.\nModule S2 (Module S2: SEMAX) : SEMAX_LIFT := S2.\n\n\n   \n", "meta": {"author": "abakst", "repo": "art-theory", "sha": "a51e8b5e00cbeb0cfec9815e179ff0d69eb4a27f", "save_path": "github-repos/coq/abakst-art-theory", "path": "github-repos/coq/abakst-art-theory/art-theory-a51e8b5e00cbeb0cfec9815e179ff0d69eb4a27f/vst/examples/cont/lift_seplogic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.22940833931364144}}
{"text": "Require Import Omega.\nRequire Import Bool.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Behavior.\n\nRequire Import PromiseConsistent.\nRequire Import Trace.\nRequire Import MemoryProps.\nRequire Import JoinedView.\n\nRequire Import PFStep.\nRequire Import OrdStep.\nRequire Import RAStep.\nRequire Import Stable.\nRequire Import PFtoRASimThread.\nRequire Import PFtoRAThread.\n\nSet Implicit Arguments.\n\n\nModule PFtoRA.\n  Section PFtoRA.\n    Variable L: Loc.t -> bool.\n\n    (* well-formedness *)\n\n    Inductive wf_pf (c: Configuration.t): Prop :=\n    | wf_pf_intro\n        (WF: Configuration.wf c)\n        (PF: PF.pf_configuration L c)\n    .\n\n    Definition wf_j := JConfiguration.wf.\n\n    Inductive wf_ra (rels: ReleaseWrites.t) (c: Configuration.t): Prop :=\n    | wf_ra_intro\n        (WF: Configuration.wf c)\n        (RELS: forall tid lang st lc\n                 (TH: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st, lc)),\n            ReleaseWrites.wf rels (Local.promises lc) (Configuration.memory c))\n    .\n\n    Lemma wf_pf_thread\n          c tid lang st lc\n          (WF: wf_pf c)\n          (FIND: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st, lc)):\n      PFtoRAThread.wf_pf (Thread.mk _ st lc (Configuration.sc c) (Configuration.memory c)).\n    Proof.\n      inv WF. inv WF0. inv WF.\n      hexploit THREADS; eauto. i.\n      econs; eauto.\n    Qed.\n\n    Lemma wf_j_thread\n          views c tid lang st lc\n          (WF: wf_j views c)\n          (FIND: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st, lc)):\n      PFtoRAThread.wf_j views (Thread.mk _ st lc (Configuration.sc c) (Configuration.memory c)).\n    Proof.\n      inv WF. inv WF0. inv WF.\n      hexploit THREADS; eauto. i.\n      hexploit REL; eauto. i.\n      econs; eauto.\n    Qed.\n\n    Lemma wf_ra_thread\n          rels c tid lang st lc\n          (WF: wf_ra rels c)\n          (FIND: IdentMap.find tid (Configuration.threads c) = Some (existT _ lang st, lc)):\n      PFtoRAThread.wf_ra rels (Thread.mk _ st lc (Configuration.sc c) (Configuration.memory c)).\n    Proof.\n      inv WF. inv WF0. inv WF.\n      hexploit THREADS; eauto. i.\n      hexploit RELS; eauto. i.\n      econs; eauto.\n    Qed.\n\n    Lemma step_pf_future\n          e tid c1 c2\n          (WF1: wf_pf c1)\n          (STEP: PFConfiguration.step L e tid c1 c2):\n      <<WF2: wf_pf c2>>.\n    Proof.\n      exploit PFConfiguration.step_future; eauto; try apply WF1. i. des. ss.\n    Qed.\n\n    Lemma step_j_future\n          e tid c1 c2 views1 views2\n          (WF1: wf_j views1 c1)\n          (STEP: JConfiguration.single_step e tid c1 c2 views1 views2):\n      <<WF2: wf_j views2 c2>>.\n    Proof.\n      eapply JConfiguration.single_step_future; eauto.\n    Qed.\n\n    Lemma step_ra_future\n          e tid rels1 rels2 c1 c2\n          (WF1: wf_ra rels1 c1)\n          (STEP: RAConfiguration.step L e tid rels1 rels2 c1 c2):\n      <<WF2: wf_ra rels2 c2>>.\n    Proof.\n      exploit RAConfiguration.step_future; try eapply WF1; eauto. i. des.\n      inv STEP. ss.\n      assert (STEPS': RAThread.steps L rels1 rels2\n                                     (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1))\n                                     (Thread.mk _ st4 lc4 sc4 memory4)).\n      { exploit RAThread.tau_steps_steps;\n          try eapply RAThread.cancel_steps_tau_steps; try exact CANCELS. i.\n        exploit RAThread.opt_step_steps; try exact STEP0. i.\n        exploit RAThread.tau_steps_steps;\n          try eapply RAThread.reserve_steps_tau_steps; try exact RESERVES. i.\n        eapply RAThread.steps_trans; [eauto|].\n        eapply RAThread.steps_trans; eauto. }\n      exploit wf_ra_thread; eauto. i.\n      hexploit RAThread.steps_rels_wf; try exact STEPS'; try apply x1. s. i.\n      econs; ss. i. Configuration.simplify; ss.\n      exploit wf_ra_thread; try eapply TH; eauto. i.\n      inv WF1. inv WF. inv WF0.\n      exploit DISJOINT; try exact n; eauto. i.\n      hexploit RAThread.steps_rels_disjoint; try exact x; eauto. apply x1.\n    Qed.\n\n    Lemma steps_pf_future\n          c1 c2\n          (WF1: wf_pf c1)\n          (STEPS: rtc (PFConfiguration.all_step L) c1 c2):\n      <<WF2: wf_pf c2>>.\n    Proof.\n      exploit PFConfiguration.rtc_all_step_future; try apply WF1; eauto. i. des.\n      econs; ss.\n    Qed.\n\n    Lemma steps_j_future\n          c1 c2 views1 views2\n          (WF1: wf_j views1 c1)\n          (STEPS: JConfiguration.single_steps c1 c2 views1 views2):\n      <<WF2: wf_j views2 c2>>.\n    Proof.\n      eapply JConfiguration.single_steps_future; eauto.\n    Qed.\n\n    Lemma steps_ra_future\n          rels1 rels2 c1 c2\n          (WF1: wf_ra rels1 c1)\n          (STEPS: RAConfiguration.steps L rels1 rels2 c1 c2):\n      <<WF2: wf_ra rels2 c2>>.\n    Proof.\n      revert WF1. induction STEPS; i; ss.\n      exploit step_ra_future; eauto.\n    Qed.\n\n\n    (* sim *)\n\n    Inductive sim_thread_sl (views: Loc.t -> Time.t -> list View.t) (rels: ReleaseWrites.t)\n              (sc_pf sc_j sc_ra: TimeMap.t) (mem_pf mem_j mem_ra: Memory.t):\n      forall (sl_pf sl_j sl_ra: {lang: language & Language.state lang} * Local.t), Prop :=\n    | sim_thread_sl_intro\n        lang st_pf lc_pf st_j lc_j st_ra lc_ra\n        (SIM: PFtoRAThread.sim_thread L views rels\n                                      (Thread.mk lang st_pf lc_pf sc_pf mem_pf)\n                                      (Thread.mk lang st_j lc_j sc_j mem_j)\n                                      (Thread.mk lang st_ra lc_ra sc_ra mem_ra)):\n        sim_thread_sl views rels sc_pf sc_j sc_ra mem_pf mem_j mem_ra\n                      (existT _ lang st_pf, lc_pf) (existT _ lang st_j, lc_j) (existT _ lang st_ra, lc_ra)\n    .\n\n    Inductive sim_conf (views: Loc.t -> Time.t -> list View.t) (rels: ReleaseWrites.t):\n      forall (c_pf c_j c_ra: Configuration.t), Prop :=\n    | sim_conf_intro\n        ths_pf sc_pf mem_pf\n        ths_j sc_j mem_j\n        ths_ra sc_ra mem_ra\n        (THS: forall tid,\n            option_rel3\n              (sim_thread_sl views rels sc_pf sc_j sc_ra mem_pf mem_j mem_ra)\n              (IdentMap.find tid ths_pf)\n              (IdentMap.find tid ths_j)\n              (IdentMap.find tid ths_ra)):\n        sim_conf views rels\n                 (Configuration.mk ths_pf sc_pf mem_pf)\n                 (Configuration.mk ths_j sc_j mem_j)\n                 (Configuration.mk ths_ra sc_ra mem_ra)\n    .\n\n    Lemma init_wf_pf syn:\n      wf_pf (Configuration.init syn).\n    Proof.\n      econs; eauto using Configuration.init_wf, PF.configuration_init_pf.\n    Qed.\n\n    Lemma init_wf_j syn:\n      wf_j (fun _ => fun _ => []) (Configuration.init syn).\n    Proof.\n      econs; eauto using Configuration.init_wf.\n      - i. ss.\n        unfold Threads.init in *.\n        rewrite IdentMap.Facts.map_o in *.\n        destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                    (@sigT _ (@Language.syntax ProgramEvent.t)) tid syn); inv TH.\n        apply inj_pair2 in H1. subst. ss. ii.\n        rewrite Memory.bot_get in *. ss.\n      - ss. econs; ss. i.\n        unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n        apply DOMap.singleton_find_inv in GET. des. inv GET0.\n      - ss.\n    Qed.\n\n    Lemma init_wf_ra syn:\n      wf_ra [] (Configuration.init syn).\n    Proof.\n      econs; eauto using Configuration.init_wf. i. ss.\n    Qed.\n\n    Lemma init_sim_conf syn:\n      sim_conf (fun _ => fun _ => []) []\n               (Configuration.init syn) (Configuration.init syn) (Configuration.init syn).\n    Proof.\n      econs; ss. i. unfold option_rel3.\n      destruct (IdentMap.find tid (Threads.init syn)) as [[[lang st] lc]|] eqn:FIND; ss.\n      unfold Threads.init in *.\n      rewrite IdentMap.Facts.map_o in *.\n      destruct (@UsualFMapPositive.UsualPositiveMap'.find\n                  (@sigT _ (@Language.syntax ProgramEvent.t)) tid syn); inv FIND.\n      apply inj_pair2 in H1. subst.\n      econs. econs; ss.\n      - econs; ss; try refl. econs; try refl. ii.\n        rewrite Memory.bot_get. ss.\n      - econs; ss.\n        + econs; ss.\n          * econs; ss. i. condtac; ss. refl.\n          * ii. rewrite Memory.bot_get in *. ss.\n        + econs; ss; i.\n          * unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n            apply DOMap.singleton_find_inv in GET_SRC. des. inv GET_SRC0.\n            esplits; ss. econs. condtac; ss.\n          * unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n            apply DOMap.singleton_find_inv in GET_TGT. des. inv GET_TGT0.\n            esplits; ss. econs. condtac; ss.\n      - econs; ss. ii.\n        unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n        apply DOMap.singleton_find_inv in GET. des. inv GET0.\n      - econs; ss. ii.\n        unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n        apply DOMap.singleton_find_inv in GET. des. inv GET0.\n      - econs; ss. ii. des; ss.\n        unfold Memory.get, Memory.init, Cell.get, Cell.init in *. ss.\n        apply DOMap.singleton_find_inv in GET. des. inv GET1.\n    Qed.\n\n    Lemma sim_conf_terminal\n          views rrels c_pf c_j c_ra\n          (SIM: sim_conf views rrels c_pf c_j c_ra)\n          (TERMINAL: Configuration.is_terminal c_pf):\n      Configuration.is_terminal c_ra.\n    Proof.\n      ii. inv SIM. specialize (THS tid).\n      unfold option_rel3 in *. ss. des_ifs.\n      destruct p as [[]]. destruct p0 as [[]]. inv THS.\n      apply inj_pair2 in H7. apply inj_pair2 in H4. apply inj_pair2 in H1. subst.\n      inv SIM. inv SIM_JOINED. inv SIM_RA. ss.\n      apply inj_pair2 in H2. apply inj_pair2 in H6. subst.\n      exploit TERMINAL; eauto. i. des.\n      split; ss.\n      inv THREAD. econs.\n      inv LOCAL0. rewrite PROMISES0.\n      eapply JSim.sim_local_memory_bot; eauto.\n    Qed.\n\n\n    (* step *)\n\n    Lemma sim_conf_step\n          views1 rels1 c1_pf c1_j c1_ra\n          tid e_pf c2_pf\n          (SIM1: sim_conf views1 rels1 c1_pf c1_j c1_ra)\n          (WF1_PF: wf_pf c1_pf)\n          (WF1_J: wf_j views1 c1_j)\n          (WF1_RA: wf_ra rels1 c1_ra)\n          (STEP: PFConfiguration.step L e_pf tid c1_pf c2_pf):\n      (exists e_j c2_j views2 e_ra rels2 c2_ra,\n          (<<STEP_J: JConfiguration.single_step e_j tid c1_j c2_j views1 views2>>) /\\\n          (<<STEP_RA: RAConfiguration.step L e_ra tid rels1 rels2 c1_ra c2_ra>>) /\\\n          (<<EVENT_J: JSim.sim_event e_j e_pf>>) /\\\n          (<<EVENT_RA: PFtoRASimThread.sim_event e_ra e_j>>) /\\\n          (<<SIM2: sim_conf views2 rels2 c2_pf c2_j c2_ra>>)) \\/\n      (<<RACE: RARaceW.ra_race_steps L rels1 c1_ra>>).\n    Proof.\n      dup SIM1. inv SIM0. inv STEP. ss.\n      dup THS. specialize (THS0 tid). unfold option_rel3 in THS0. des_ifs.\n      inv THS0. apply inj_pair2 in H1. subst.\n      exploit wf_pf_thread; eauto. s. i.\n      exploit wf_j_thread; eauto. s. i.\n      exploit wf_ra_thread; eauto. s. i.\n      exploit PFtoRAThread.sim_thread_cancel_steps; eauto.\n      { exploit PFtoRAThread.cancel_steps_pf_future; eauto. i.\n        exploit PFtoRAThread.opt_step_pf_future; eauto. i.\n        exploit PFtoRAThread.reserve_steps_pf_future; eauto. i.\n        destruct (classic (e_pf = ThreadEvent.failure)).\n        - subst. inv STEP0. inv STEP; inv STEP0. inv LOCAL. inv LOCAL0. ss.\n        - eapply opt_step_promise_consistent; eauto; try apply x3.\n          eapply rtc_reserve_step_promise_consistent; eauto.\n          eapply consistent_promise_consistent;\n            try eapply PF.pf_consistent_consistent; eauto; try apply x5.\n      }\n      i. des.\n      exploit PFtoRAThread.cancel_steps_pf_future; eauto. i.\n      exploit PFtoRAThread.cancel_steps_j_future; eauto. i.\n      exploit PFtoRAThread.cancel_steps_ra_future; eauto. i.\n      exploit PFtoRAThread.sim_thread_opt_step; eauto.\n      { exploit PFtoRAThread.opt_step_pf_future; eauto. i.\n        exploit PFtoRAThread.reserve_steps_pf_future; eauto. i.\n        destruct (classic (e_pf = ThreadEvent.failure)).\n        - subst. inv STEP0. inv STEP; inv STEP0. inv LOCAL. inv LOCAL0. ss.\n        - eapply rtc_reserve_step_promise_consistent; eauto.\n          eapply consistent_promise_consistent;\n            try eapply PF.pf_consistent_consistent; eauto; try apply x7.\n      }\n      i. des; cycle 1.\n      { right. unfold RARaceW.ra_race_steps.\n        esplits; [econs 1|..]; eauto. s.\n        eapply RAThread.tau_steps_steps.\n        eapply RAThread.cancel_steps_tau_steps; eauto. }\n      exploit PFtoRAThread.opt_step_pf_future; eauto. i.\n      exploit PFtoRAThread.opt_step_j_future; eauto. i.\n      exploit PFtoRAThread.opt_step_ra_future; eauto. i.\n      exploit PFtoRAThread.sim_thread_reserve_steps; eauto.\n      { exploit PFtoRAThread.reserve_steps_pf_future; eauto. i.\n        destruct (classic (e_pf = ThreadEvent.failure)).\n        - subst. inv STEP0. inv STEP; inv STEP0. inv LOCAL. inv LOCAL0.\n          eapply rtc_reserve_step_promise_consistent2; eauto. ss.\n        - eapply consistent_promise_consistent;\n            try eapply PF.pf_consistent_consistent; eauto; try apply x9.\n      }\n      i. des.\n      exploit PFtoRAThread.reserve_steps_pf_future; eauto. i.\n      exploit PFtoRAThread.reserve_steps_j_future; eauto. i.\n      exploit PFtoRAThread.reserve_steps_ra_future; eauto. i.\n      assert (STEPS': RAThread.steps L rels1 rels2 (Thread.mk _ st_ra lc_ra sc_ra mem_ra) e2_ra1).\n      { exploit RAThread.tau_steps_steps;\n          try eapply RAThread.cancel_steps_tau_steps; try exact STEP_RA. i.\n        exploit RAThread.opt_step_steps; eauto. i.\n        exploit RAThread.tau_steps_steps;\n          try eapply RAThread.reserve_steps_tau_steps; try exact STEP_RA1. i.\n        eapply RAThread.steps_trans; eauto.\n        eapply RAThread.steps_trans; eauto. }\n\n      destruct (classic (e_pf = ThreadEvent.failure)).\n      { subst. inv EVENT_J. inv EVENT_RA.\n        destruct e2_j1 as [st4_j lc4_j sc4_j mem4_j], e2_ra1 as [st4_ra lc4_ra sc4_ra mem4_ra].\n        left. esplits.\n        - econs; eauto. ss.\n        - econs; eauto. ss.\n        - ss.\n        - econs.\n        - econs; ss. i.\n          repeat rewrite IdentMap.gsspec. condtac; ss.\n          specialize (THS tid0). unfold option_rel3 in THS. des_ifs. inv THS. ss.\n          inv SIM4. ss. econs. econs; s; eauto; try apply SIM3.\n          * inv SIM_JOINED.\n            apply inj_pair2 in H2. apply inj_pair2 in H6. subst.\n            econs; s; eauto; try by (inv SIM3; inv SIM_JOINED; ss).\n            exploit JThread.rtc_cancel_step_future; eauto; try apply x1. s. i. des.\n            exploit JThread.opt_step_future; eauto; try apply x1. s. i. des.\n            exploit JThread.rtc_reserve_step_future; eauto. s. i. des.\n            eapply JSim.sim_local_le; try exact LOCAL.\n            etrans; eauto. refl.\n          * inv SIM_RA. ss. subst.\n            econs; s; eauto; try by (inv SIM3; inv SIM_RA; ss).\n            inv LOCAL. econs; ss. i.\n            exploit wf_ra_thread; try exact WF1_RA; try eapply Heq4. s. i.\n            eapply RAThread.steps_rels_disjoint; try exact STEPS'; ss; try apply x2; try apply x12.\n            inv WF1_RA. inv WF. inv WF0. ss.\n            eapply DISJOINT; [|eapply Heq1|eapply Heq4]. congr.\n          * econs; try apply SIM3; try apply NORMAL_J.\n          * econs; try apply SIM3; try apply NORMAL_RA.\n          * econs; s; try apply SIM3; try apply STABLE_RA.\n            exploit RAThread.steps_future; try exact STEPS'; try apply x2. s. i. des.\n            exploit wf_ra_thread; try exact WF1_RA; try eapply Heq4. s. i.\n            exploit Stable.future_stable_tview; try eapply STABLE_RA; try apply x12; eauto.\n      }\n\n      exploit PFtoRAThread.sim_thread_consistent; try eapply CONSISTENT; eauto. i. des; cycle 1.\n      { right. unfold RARaceW.ra_race_steps.\n        esplits; [econs 1|..]; try eapply RACE; eauto. s.\n        eapply RAThread.steps_trans; eauto.\n        eapply RAThread.tau_steps_steps; eauto. }\n      destruct e2_j1 as [st4_j lc4_j sc4_j mem4_j], e2_ra1 as [st4_ra lc4_ra sc4_ra mem4_ra].\n      left. esplits.\n      - econs; eauto.\n      - econs; eauto.\n      - ss.\n      - ss.\n      - econs; ss. i.\n        repeat rewrite IdentMap.gsspec. condtac; ss.\n        specialize (THS tid0). unfold option_rel3 in THS. des_ifs. inv THS. ss.\n        inv SIM4. ss. econs. econs; s; eauto; try apply SIM3.\n        * inv SIM_JOINED.\n          apply inj_pair2 in H3. apply inj_pair2 in H7. subst.\n          econs; s; eauto; try by (inv SIM3; inv SIM_JOINED; ss).\n          exploit JThread.rtc_cancel_step_future; eauto; try apply x1. s. i. des.\n          exploit JThread.opt_step_future; eauto; try apply x1. s. i. des.\n          exploit JThread.rtc_reserve_step_future; eauto. s. i. des.\n          eapply JSim.sim_local_le; try exact LOCAL.\n          etrans; eauto. refl.\n        * inv SIM_RA. ss. subst.\n          econs; s; eauto; try by (inv SIM3; inv SIM_RA; ss).\n          inv LOCAL. econs; ss. i.\n          exploit wf_ra_thread; try exact WF1_RA; try eapply Heq4. s. i.\n          eapply RAThread.steps_rels_disjoint; try exact STEPS'; ss; try apply x2; try apply x12.\n          inv WF1_RA. inv WF. inv WF0. ss.\n          eapply DISJOINT; [|eapply Heq1|eapply Heq4]. congr.\n        * econs; try apply SIM3; try apply NORMAL_J.\n        * econs; try apply SIM3; try apply NORMAL_RA.\n        * econs; s; try apply SIM3; try apply STABLE_RA.\n          exploit RAThread.steps_future; try exact STEPS'; try apply x2. s. i. des.\n          exploit wf_ra_thread; try exact WF1_RA; try eapply Heq4. s. i.\n          exploit Stable.future_stable_tview; try eapply STABLE_RA; try apply x12; eauto.\n    Qed.\n\n    Lemma sim_conf_steps\n          views1 rels1 c1_pf c1_j c1_ra\n          c2_pf\n          (SIM1: sim_conf views1 rels1 c1_pf c1_j c1_ra)\n          (WF1_PF: wf_pf c1_pf)\n          (WF1_J: wf_j views1 c1_j)\n          (WF1_RA: wf_ra rels1 c1_ra)\n          (STEPS: rtc (PFConfiguration.all_step L) c1_pf c2_pf):\n      (exists c2_j views2 rels2 c2_ra,\n          (<<STEPS_RA: RAConfiguration.steps L rels1 rels2 c1_ra c2_ra>>) /\\\n          (<<STEPS_J: JConfiguration.single_steps c1_j c2_j views1 views2>>) /\\\n          (<<SIM2: sim_conf views2 rels2 c2_pf c2_j c2_ra>>)) \\/\n      (<<RACE: RARaceW.ra_race_steps L rels1 c1_ra>>).\n    Proof.\n      revert views1 rels1 c1_j c1_ra SIM1 WF1_PF WF1_J WF1_RA.\n      induction STEPS; i.\n      { left. esplits; try by econs 1. ss. }\n      inv H. exploit sim_conf_step; eauto. i. des; eauto.\n      exploit step_pf_future; eauto. i. des.\n      exploit step_j_future; eauto. i. des.\n      exploit step_ra_future; eauto. i. des.\n      exploit IHSTEPS; eauto. i. des.\n      - left. esplits.\n        + econs 2; eauto.\n        + econs 2; eauto.\n        + ss.\n      - right. unfold RARaceW.ra_race_steps in *. des.\n        esplits; [econs 2; eauto|..]; eauto.\n    Qed.\n\n\n    (* racefree *)\n\n    Lemma sim_conf_racy_read\n          views1 rels1 c1_pf c1_j c1_ra\n          loc ts e_pf tid c2_pf\n          (SIM1: sim_conf views1 rels1 c1_pf c1_j c1_ra)\n          (WF1_PF: wf_pf c1_pf)\n          (WF1_J: wf_j views1 c1_j)\n          (WF1_RA: wf_ra rels1 c1_ra)\n          (STEP: PFRace.racy_read_step L loc ts e_pf tid c1_pf c2_pf)\n          (LOC: L loc)\n          (RELS: ~ List.In (loc, ts) rels1):\n      (<<RACE: RARaceW.ra_race_steps L rels1 c1_ra>>).\n    Proof.\n      inv STEP. inv SIM1. ss.\n      specialize (THS tid). unfold option_rel3 in THS. des_ifs.\n      inv THS. apply inj_pair2 in H1. subst.\n      exploit wf_pf_thread; eauto. s. i.\n      exploit wf_j_thread; eauto. s. i.\n      exploit wf_ra_thread; eauto. s. i.\n      exploit PFtoRAThread.sim_thread_cancel_steps; eauto.\n      { destruct (classic (e_pf = ThreadEvent.failure)).\n        - subst. inv STEP0; inv STEP; inv STEP0. inv LOCAL. inv LOCAL0. ss.\n        - exploit PFtoRAThread.cancel_steps_pf_future; eauto. i.\n          exploit PFtoRAThread.opt_step_pf_future; eauto. i.\n          exploit PFtoRAThread.reserve_steps_pf_future; eauto. i.\n          eapply opt_step_promise_consistent; eauto; try eapply x3.\n          eapply rtc_reserve_step_promise_consistent; eauto.\n          eapply consistent_promise_consistent; try eapply PF.pf_consistent_consistent;\n            try eapply CONSISTENT; try eapply x5; eauto.\n      }\n      i. des.\n      exploit PFtoRAThread.cancel_steps_pf_future; try eapply x0; eauto. i.\n      exploit PFtoRAThread.cancel_steps_j_future; try eapply x1; eauto. i.\n      exploit PFtoRAThread.cancel_steps_ra_future; try eapply x2; eauto. i.\n      exploit PFtoRAThread.sim_thread_opt_step; eauto.\n      { destruct (classic (e_pf = ThreadEvent.failure)).\n        - subst. inv STEP0; inv STEP; inv STEP0. inv LOCAL. inv LOCAL0. ss.\n        - exploit PFtoRAThread.opt_step_pf_future; eauto. i.\n          exploit PFtoRAThread.reserve_steps_pf_future; eauto. i.\n          eapply rtc_reserve_step_promise_consistent; eauto.\n          eapply consistent_promise_consistent; try eapply PF.pf_consistent_consistent;\n            try eapply CONSISTENT; try eapply x7; eauto.\n      }\n      i. unfold RARaceW.ra_race_steps. des; cycle 1.\n      { esplits; [econs 1|..]; eauto. s.\n        eapply RAThread.tau_steps_steps; eapply RAThread.cancel_steps_tau_steps; eauto. }\n      hexploit PFtoRASimThread.sim_local_promise_consistent; try eapply SIM2.\n      { inv SIM2. inv SIM_JOINED.\n        apply inj_pair2 in H2. apply inj_pair2 in  H3. subst. ss.\n        eapply JSim.sim_local_promise_consistent; eauto.\n        exploit PFtoRAThread.reserve_steps_pf_future; eauto. i.\n        destruct (classic (e_pf = ThreadEvent.failure)).\n        - subst. inv STEP0; inv STEP; inv STEP0. inv LOCAL0. inv LOCAL1. ss.\n        - exploit PFtoRAThread.opt_step_pf_future; eauto. i. des.\n          exploit PFtoRAThread.reserve_steps_pf_future; eauto. i.\n          hexploit consistent_promise_consistent; try eapply PF.pf_consistent_consistent;\n            try eapply CONSISTENT; try eapply x8; eauto. s. i.\n          hexploit rtc_reserve_step_promise_consistent; try exact H1; eauto. i.\n          hexploit opt_step_promise_consistent; try eapply x6; eauto.\n      }\n      i. inv READ; inv EVENT_J; inv EVENT_RA; ss.\n      - inv STEP_RA0. esplits; [econs 1|..]; eauto; ss.\n        + eapply RAThread.tau_steps_steps; eapply RAThread.cancel_steps_tau_steps; eauto.\n        + unfold RARaceW.ra_race. splits; eauto.\n          inv SIM2. inv SIM_JOINED. inv SIM_RA.\n          apply inj_pair2 in H3. apply inj_pair2 in H4. subst. ss.\n          inv LOCAL0. inv TVIEW. rewrite CUR.\n          eapply TimeFacts.le_lt_lt; eauto. condtac.\n          * inv LOCAL. inv TVIEW. inv CUR0. apply RLX.\n          * inv LOCAL. inv TVIEW. inv CUR0.\n            inv NORMAL_J. inv NORMAL_TVIEW. ss. rewrite CUR0; ss.\n      - inv STEP_RA0. esplits; [econs 1|..]; eauto; ss.\n        + eapply RAThread.tau_steps_steps; eapply RAThread.cancel_steps_tau_steps; eauto.\n        + unfold RARaceW.ra_race. splits; eauto.\n          inv SIM2. inv SIM_JOINED. inv SIM_RA.\n          apply inj_pair2 in H3. apply inj_pair2 in H4. subst. ss.\n          inv LOCAL0. inv TVIEW. rewrite CUR.\n          eapply TimeFacts.le_lt_lt; eauto. condtac.\n          * inv LOCAL. inv TVIEW. inv CUR0. apply RLX.\n          * inv LOCAL. inv TVIEW. inv CUR0.\n            inv NORMAL_J. inv NORMAL_TVIEW. ss. rewrite CUR0; ss.\n    Qed.\n\n    Lemma sim_conf_racefree\n          views rels c_pf c_j c_ra\n          (SIM: sim_conf views rels c_pf c_j c_ra)\n          (WF_PF: wf_pf c_pf)\n          (WF_J: wf_j views c_j)\n          (WF_RA: wf_ra rels c_ra)\n          (RA_RACEFREE: RARaceW.racefree L rels c_ra):\n      PFRace.racefree_view L c_pf.\n    Proof.\n      ii. exploit sim_conf_steps; eauto. i. des; cycle 1.\n      { unfold RARaceW.ra_race_steps in *. des. eauto. }\n      exploit steps_pf_future; eauto. i. des.\n      exploit steps_j_future; eauto. i. des.\n      exploit steps_ra_future; eauto. i. des.\n      inv WRITE.\n      exploit sim_conf_step; try exact STEP; eauto. i. des; cycle 1.\n      { unfold RARaceW.ra_race_steps in *. des.\n        eapply RA_RACEFREE; cycle 1; eauto.\n        eapply RAConfiguration.steps_trans; eauto. }\n      assert (WRITE_RA: ~ List.In (loc, ts) rels0).\n      { inv WRITE0; inv EVENT_J; inv EVENT_RA; ss.\n        - hexploit RAConfiguration.write_rels; try exact STEP_RA; try eapply x2; ss. i.\n          inv STEP_RA. inv STEP0; ss. inv STEP1.\n          unfold ReleaseWrites.append. ss. condtac; ss. condtac; ss.\n          destruct ordw; ss.\n        - hexploit RAConfiguration.write_rels; try exact STEP_RA; try eapply x2; ss. i.\n          inv STEP_RA. inv STEP0; ss. inv STEP1.\n          unfold ReleaseWrites.append. ss. condtac; ss. condtac; ss.\n          destruct ordw; ss.\n      }\n      exploit step_pf_future; try exact STEP; eauto. i. des.\n      exploit step_j_future; try exact STEP_J; eauto. i. des.\n      exploit step_ra_future; try exact STEP_RA; eauto. i. des.\n      exploit sim_conf_steps; try exact CSTEPS2; eauto. i. des; cycle 1.\n      { unfold RARaceW.ra_race_steps in *. des.\n        eapply RA_RACEFREE; cycle 1; eauto.\n        eapply RAConfiguration.steps_trans; [eauto|].\n        econs 2; eauto. }\n      exploit steps_pf_future; try exact CSTEPS2; eauto. i. des.\n      exploit steps_j_future; try exact STEPS_J0; eauto. i. des.\n      exploit steps_ra_future; try exact STEPS_RA0; eauto. i. des.\n      assert (READ_RA: ~ List.In (loc, ts) rels1).\n      { inv WRITE0; inv EVENT_J; inv EVENT_RA; ss.\n        - exploit RAConfiguration.write_get_None; try exact STEP_RA; ss; try apply x2. i. des.\n          eapply RAConfiguration.steps_rels; eauto.\n        - exploit RAConfiguration.write_get_None; try exact STEP_RA; ss; try apply x2. i. des.\n          eapply RAConfiguration.steps_rels; eauto.\n      }\n      exploit sim_conf_racy_read; eauto. unfold RARaceW.ra_race_steps. i. des.\n      eapply RA_RACEFREE; cycle 1; eauto.\n      eapply RAConfiguration.steps_trans; eauto.\n      eapply RAConfiguration.steps_trans; eauto.\n      econs 2; eauto.\n    Qed.\n\n\n    (* behaviors *)\n\n    Lemma sim_conf_behavior\n          views rels c_pf c_j c_ra\n          (SIM: sim_conf views rels c_pf c_j c_ra)\n          (WF_PF: wf_pf c_pf)\n          (WF_J: wf_j views c_j)\n          (WF_RA: wf_ra rels c_ra)\n          (RACEFREE: RARaceW.racefree L rels c_ra):\n      behaviors (PFConfiguration.machine_step L) c_pf <1=\n      behaviors (@OrdConfiguration.machine_step L Ordering.acqrel) c_ra.\n    Proof.\n      i. revert views rels c_j c_ra SIM WF_PF WF_J WF_RA RACEFREE.\n      induction PR; i.\n      - econs 1. eapply sim_conf_terminal; eauto.\n      - inv STEP. exploit sim_conf_step; eauto. i. des.\n        + exploit RARaceW.step_ord_step; eauto. i.\n          inv EVENT_J; inv EVENT_RA; ss. inv H0.\n          econs 2.\n          { replace (MachineEvent.syscall e) with\n                (ThreadEvent.get_machine_event (ThreadEvent.syscall e)) by ss.\n            econs; eauto. }\n          hexploit RARaceW.step_racefree; eauto. i.\n          exploit step_pf_future; eauto. i. des.\n          exploit step_j_future; eauto. i. des.\n          exploit step_ra_future; eauto.\n        + exfalso. unfold RARaceW.ra_race_steps in *. des. eauto.\n      - inv STEP. exploit sim_conf_step; eauto. i. des.\n        + exploit RARaceW.step_ord_step; eauto. i.\n          inv EVENT_J; inv EVENT_RA; ss. inv H0.\n          econs 3.\n          replace MachineEvent.failure with (ThreadEvent.get_machine_event ThreadEvent.failure) by ss.\n          econs; eauto.\n        + exfalso. unfold RARaceW.ra_race_steps in *. des. eauto.\n      - inv STEP. exploit sim_conf_step; eauto. i. des.\n        + exploit RARaceW.step_ord_step; eauto. i.\n          econs 4.\n          { replace MachineEvent.silent with (ThreadEvent.get_machine_event e_ra); cycle 1.\n            { inv EVENT_J; inv EVENT_RA; ss. }\n            econs; eauto.\n          }\n          hexploit RARaceW.step_racefree; eauto. i.\n          exploit step_pf_future; eauto. i. des.\n          exploit step_j_future; eauto. i. des.\n          exploit step_ra_future; eauto.\n        + exfalso. unfold RARaceW.ra_race_steps in *. des. eauto.\n    Qed.\n  End PFtoRA.\nEnd PFtoRA.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/ldrfra/PFtoRA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.22940833931364138}}
{"text": "Require Import RelationClasses.\n\nFrom Paco Require Import paco.\nFrom sflib Require Import sflib.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Loc.\nRequire Import Time.\nFrom PromisingLib Require Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\nRequire Import Behavior.\n\nRequire Import Pred.\nRequire Import Trace.\nRequire Import OrderedTimes.\nRequire Import PFConsistentStrong.\n\nSet Implicit Arguments.\n\n\n\nInductive times_configuration_step_strong (times: Loc.t -> Time.t -> Prop)\n  : forall (tr tr_cert: Trace.t)\n           (e:MachineEvent.t) (tid:Ident.t) (c1 c2:Configuration.t), Prop :=\n| times_configuration_step_strong_intro\n    lang tr e tr' pf tid c1 st1 lc1 e2 st3 lc3 sc3 memory3 tr_cert\n    (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))\n    (STEPS: Trace.steps tr' (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1)) e2)\n    (SILENT: List.Forall (fun the => ThreadEvent.get_machine_event (snd the) = MachineEvent.silent) tr')\n    (STEP: Thread.step pf e e2 (Thread.mk _ st3 lc3 sc3 memory3))\n    (TR: tr = tr'++[((Thread.local e2), e)])\n    (CONSISTENT: forall (EVENT: ThreadEvent.get_machine_event e <> MachineEvent.failure),\n        pf_consistent_super_strong (Thread.mk _ st3 lc3 sc3 memory3) tr_cert times)\n    (CERTBOT: ThreadEvent.get_machine_event e = MachineEvent.failure \\/ (exists se, e = ThreadEvent.syscall se) -> tr_cert = [])\n    (CERTBOTNIL: (Local.promises lc3) = Memory.bot -> tr_cert = [])\n    (TIMES: List.Forall (fun thte => wf_time_evt times (snd thte)) tr)\n  :\n    times_configuration_step_strong\n      times tr tr_cert\n      (ThreadEvent.get_machine_event e) tid c1 (Configuration.mk (IdentMap.add tid (existT _ _ st3, lc3) (Configuration.threads c1)) sc3 memory3)\n.\n\nInductive times_configuration_step (times: Loc.t -> Time.t -> Prop)\n  : forall (tr tr_cert: Trace.t)\n           (e:MachineEvent.t) (tid:Ident.t) (c1 c2:Configuration.t), Prop :=\n| times_configuration_step_intro\n    lang tr e tr' pf tid c1 st1 lc1 e2 st3 lc3 sc3 memory3 tr_cert\n    (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))\n    (STEPS: Trace.steps tr' (Thread.mk _ st1 lc1 (Configuration.sc c1) (Configuration.memory c1)) e2)\n    (SILENT: List.Forall (fun the => ThreadEvent.get_machine_event (snd the) = MachineEvent.silent) tr')\n    (STEP: Thread.step pf e e2 (Thread.mk _ st3 lc3 sc3 memory3))\n    (TR: tr = tr'++[((Thread.local e2), e)])\n    (CONSISTENT: forall (EVENT: ThreadEvent.get_machine_event e <> MachineEvent.failure),\n        pf_consistent_super_strong (Thread.mk _ st3 lc3 sc3 memory3) tr_cert times)\n    (CERTBOT: ThreadEvent.get_machine_event e = MachineEvent.failure \\/ (exists se, e = ThreadEvent.syscall se) -> tr_cert = [])\n    (TIMES: List.Forall (fun thte => wf_time_evt times (snd thte)) tr)\n  :\n    times_configuration_step\n      times tr tr_cert\n      (ThreadEvent.get_machine_event e) tid c1 (Configuration.mk (IdentMap.add tid (existT _ _ st3, lc3) (Configuration.threads c1)) sc3 memory3)\n.\n\nLemma times_configuration_step_strong_step\n  :\n    times_configuration_step_strong <7= times_configuration_step.\nProof.\n  i. inv PR. econs; eauto.\nQed.\n\nInductive times_configuration_step_strong_all (times: Loc.t -> Time.t -> Prop)\n          (e:MachineEvent.t) (tid:Ident.t) (c1 c2:Configuration.t): Prop :=\n| times_configuration_step_strong_all_intro\n    tr tr_cert\n    (STEP: @times_configuration_step_strong times tr tr_cert e tid c1 c2)\n.\n\nLemma times_configuration_step_configuration_step times tr tr_cert e tid c1 c2\n      (STEP: @times_configuration_step times tr tr_cert e tid c1 c2)\n      (WF: Configuration.wf c1)\n  :\n    Configuration.step e tid c1 c2.\nProof.\n  inv STEP. eapply Trace.silent_steps_tau_steps in STEPS; eauto.\n  destruct (classic (ThreadEvent.get_machine_event e0 = MachineEvent.failure)).\n  { econs; eauto. ss. }\n  { inv WF. exploit Thread.rtc_tau_step_future; ss; eauto.\n    { eapply WF0; eauto. } i. des.\n    exploit Thread.step_future; ss; eauto. ss. i. des.\n    econs; eauto. i. eapply pf_consistent_super_strong_consistent; eauto.\n  }\nQed.\n\nLemma times_configuration_step_future\n      times tr tr_cert e tid c1 c2\n      (STEP: @times_configuration_step times tr tr_cert e tid c1 c2)\n      (WF1: Configuration.wf c1):\n  (<<WF2: Configuration.wf c2>>) /\\\n  (<<SC_FUTURE: TimeMap.le (Configuration.sc c1) (Configuration.sc c2)>>) /\\\n  (<<MEM_FUTURE: Memory.future (Configuration.memory c1) (Configuration.memory c2)>>).\nProof.\n  eapply times_configuration_step_configuration_step in STEP; eauto.\n  eapply Configuration.step_future; eauto.\nQed.\n\nInductive times_configuration_opt_step (times: Loc.t -> Time.t -> Prop)\n  : forall (tr tr_cert: Trace.t)\n           (e:MachineEvent.t) (tid:Ident.t) (c1 c2:Configuration.t), Prop :=\n| times_configuration_opt_step_some\n    tr tr_cert e tid c1 c2\n    (STEP: @times_configuration_step times tr tr_cert e tid c1 c2)\n  :\n    times_configuration_opt_step times tr tr_cert e tid c1 c2\n| times_configuration_opt_step_none\n    tid c\n  :\n    @times_configuration_opt_step times [] [] MachineEvent.silent tid c c\n.\n\nLemma times_configuration_opt_step_future\n      times tr tr_cert e tid c1 c2\n      (STEP: @times_configuration_opt_step times tr tr_cert e tid c1 c2)\n      (WF1: Configuration.wf c1):\n  (<<WF2: Configuration.wf c2>>) /\\\n  (<<SC_FUTURE: TimeMap.le (Configuration.sc c1) (Configuration.sc c2)>>) /\\\n  (<<MEM_FUTURE: Memory.future (Configuration.memory c1) (Configuration.memory c2)>>).\nProof.\n  inv STEP.\n  { eapply times_configuration_step_future; eauto. }\n  { splits; auto. refl. }\nQed.\n\nLemma times_configuration_step_strong_mon times0 times1\n      (LE: times0 <2= times1)\n  :\n    times_configuration_step_strong times0 <6= times_configuration_step_strong times1.\nProof.\n  i. inv PR. econs; eauto.\n  { i. hexploit CONSISTENT; eauto. i. des. esplits; eauto.\n    eapply pf_consistent_super_strong_mon; eauto. }\n  { eapply List.Forall_impl; eauto. i. eapply wf_time_evt_mon; eauto. }\nQed.\n\nLemma times_configuration_step_mon times0 times1\n      (LE: times0 <2= times1)\n  :\n    times_configuration_step times0 <6= times_configuration_step times1.\nProof.\n  i. inv PR. econs; eauto.\n  { i. hexploit CONSISTENT; eauto. i. des. esplits; eauto.\n    eapply pf_consistent_super_strong_mon; eauto. }\n  { eapply List.Forall_impl; eauto. i. eapply wf_time_evt_mon; eauto. }\nQed.\n\nLemma times_configuration_step_strong_all_mon times0 times1\n      (LE: times0 <2= times1)\n  :\n    times_configuration_step_strong_all times0 <4= times_configuration_step_strong_all times1.\nProof.\n  i. inv PR. econs. eapply times_configuration_step_strong_mon; eauto.\nQed.\n\nLemma times_configuration_step_exists c0 c1 tid e\n      (STEP: Configuration.step e tid c0 c1)\n      (WF: Configuration.wf c0)\n  :\n    exists times tr tr_cert,\n      ((<<STEP: @times_configuration_step_strong times tr tr_cert e tid c0 c1>>) \\/\n       exists c1',\n         (<<STEP: @times_configuration_step_strong times tr tr_cert MachineEvent.failure tid c0 c1'>>))\n      /\\\n      (<<WO: forall loc, well_ordered (times loc)>>).\nProof.\n  inv STEP.\n  destruct (classic (Thread.steps_failure (Thread.mk _ st1 lc1 c0.(Configuration.sc) c0.(Configuration.memory)))) as [FAILURE|NFAILURE].\n  { clear STEPS STEP0 EVENT. red in FAILURE. des. destruct e3.\n    eapply Trace.tau_steps_silent_steps in STEPS. des.\n    hexploit (trace_times_list_exists tr). i. des.\n    hexploit step_times_list_exists; eauto. i. des.\n    replace MachineEvent.failure with (ThreadEvent.get_machine_event e); auto.\n    eexists (fun loc ts => List.In ts (times loc ++ times0 loc)), (tr++_), []. splits.\n    { right. esplits. econs; eauto; ss. eapply Forall_app.\n      { eapply List.Forall_impl; eauto. i. ss. eapply wf_time_evt_mon; eauto.\n        i. ss. eapply List.in_or_app; eauto. }\n      { econs; ss. eapply wf_time_evt_mon; eauto.\n        i. ss. eapply List.in_or_app; eauto. }\n    }\n    { i. eapply finite_well_ordered. }\n  }\n  assert (NORMAL: ThreadEvent.get_machine_event e0 <> MachineEvent.failure).\n  { ii. eapply NFAILURE. red. esplits; eauto.\n    replace pf with true in *; eauto. inv STEP0; inv STEP; ss.\n  }\n  dup STEPS. eapply Trace.tau_steps_silent_steps in STEPS. des.\n  hexploit (trace_times_list_exists tr). i. des.\n  hexploit step_times_list_exists; eauto. i. des.\n  hexploit EVENT; ss.\n  dup WF. inv WF. exploit Trace.steps_future; eauto.\n  { ss. eapply WF1; eauto. } i. des. ss.\n  hexploit Thread.step_future; eauto. i. des. ss.\n  destruct (classic ((Local.promises lc3) = Memory.bot)) as [EQBOT|NEQBOT].\n  { eexists (fun loc ts => List.In ts (times loc ++ times0 loc)), (tr++_), []. splits.\n    { left. econs; eauto.\n      { i. esplits. eapply promises_bot_certify_nil; eauto. }\n      { eapply Forall_app.\n        { eapply List.Forall_impl; eauto. i. eapply wf_time_evt_mon; try apply H0.\n          i. ss. eapply List.in_or_app; eauto. }\n        { econs; ss. eapply wf_time_evt_mon; try apply WFTIME0.\n          i. ss. eapply List.in_or_app; eauto. }\n      }\n    }\n    { i. eapply finite_well_ordered. }\n  }\n  destruct (ThreadEvent.get_machine_event e0) eqn:EQ; ss; cycle 1.\n  { inv STEP0; inv STEP; ss. inv LOCAL; ss.\n    inv LOCAL0; ss. exfalso. eapply NEQBOT; eauto. }\n  eapply consistent_pf_consistent_super_strong in H; eauto. des.\n  { red in FAILURE. des. exfalso. eapply NFAILURE. red. esplits.\n    { etrans.\n      { eapply STEPS0. }\n      econs 2.\n      { econs; [|eapply EQ]. econs; eauto. }\n      { eauto. }\n    }\n    { eauto. }\n    { eauto. }\n  }\n  eexists (certimes \\2/ (fun loc ts => List.In ts (times loc ++ times0 loc))), (tr++_), tr0. splits.\n  { left. rewrite <- EQ. econs; eauto.\n    { i. esplits. eapply pf_consistent_super_strong_mon; eauto. }\n    { rewrite EQ. i. des; ss; clarify. }\n    { ii. ss. }\n    { eapply Forall_app.\n      { eapply List.Forall_impl; eauto. i. eapply wf_time_evt_mon; try apply H.\n        i. ss. right. eapply List.in_or_app; eauto. }\n      { econs; ss. eapply wf_time_evt_mon; try apply WFTIME0.\n        i. ss. right. eapply List.in_or_app; eauto. }\n    }\n  }\n  { i. eapply join_well_ordered; eauto. eapply finite_well_ordered. }\nQed.\n\nLemma times_configuration_behavior_configuration_behavior times c\n      (WF: Configuration.wf c)\n  :\n    behaviors (times_configuration_step_strong_all times) c <2=\n    behaviors (Configuration.step) c.\nProof.\n  i. ginduction PR; eauto.\n  { i. econs 1. eauto. }\n  { i. inv STEP. eapply times_configuration_step_strong_step in STEP0.\n    eapply times_configuration_step_configuration_step in STEP0; eauto.\n    econs 2; eauto. eapply IHPR; eauto.\n    eapply Configuration.step_future; eauto.\n  }\n  { i. inv STEP. eapply times_configuration_step_strong_step in STEP0.\n    eapply times_configuration_step_configuration_step in STEP0; eauto.\n    econs 3; eauto.\n  }\n  { i. inv STEP. eapply times_configuration_step_strong_step in STEP0.\n    eapply times_configuration_step_configuration_step in STEP0; eauto.\n    econs 4; eauto. eapply IHPR; eauto.\n    eapply Configuration.step_future; eauto.\n  }\n  { i. econs 5; eauto. }\nQed.\n\nLemma times_configuration_step_same_behaviors c f beh\n      (WF: Configuration.wf c)\n      (BEH: behaviors Configuration.step c f beh)\n  :\n    exists times,\n      (<<BEH: behaviors (times_configuration_step_strong_all times) c f beh>>) /\\\n      (<<WO: forall loc, well_ordered (times loc)>>) /\\\n      (<<INCR: forall nat loc, times loc (incr_time_seq nat)>>) /\\\n      (<<BOT: forall loc, times loc Time.bot>>)\n.\nProof.\n  ginduction BEH.\n  { i. exists (fun loc => incr_times \\1/ eq Time.bot). splits.\n    { econs 1; eauto. }\n    { i. eapply join_well_ordered; eauto.\n      { eapply incr_times_well_ordered. }\n      { eapply singleton_well_ordered. }\n    }\n    { i. left. eexists. eauto. }\n    { auto. }\n  }\n  { i. exploit IHBEH.\n    { eapply Configuration.step_future; eauto. } i. des.\n    exploit times_configuration_step_exists; eauto. i. des.\n    { exists (times \\2/ times0). splits.\n      { econs 2; eauto.\n        { econs. eapply times_configuration_step_strong_mon; eauto. }\n        { eapply le_step_behavior_improve; try apply BEH0.\n          eapply times_configuration_step_strong_all_mon; auto. }\n      }\n      { i. eapply join_well_ordered; eauto. }\n      { auto. }\n      { auto. }\n    }\n    { exists (times \\2/ times0). splits.\n      { econs 3; eauto.\n        { econs. eapply times_configuration_step_strong_mon; eauto. }\n      }\n      { i. eapply join_well_ordered; eauto. }\n      { auto. }\n      { auto. }\n    }\n  }\n  { i. exploit times_configuration_step_exists; eauto. i. des.\n    { exists (times \\2/ (fun loc => incr_times) \\2/ (fun _ => eq Time.bot)). splits; eauto.\n      { econs 3; eauto. econs; eauto.\n        eapply times_configuration_step_strong_mon; eauto. }\n      { i. eapply join_well_ordered; eauto.\n        { eapply join_well_ordered; eauto. eapply incr_times_well_ordered. }\n        { eapply singleton_well_ordered. }\n      }\n      { i. left. right. eexists. eauto. }\n    }\n    { exists (times \\2/ (fun loc => incr_times) \\2/ (fun _ => eq Time.bot)). splits; eauto.\n      { econs 3; eauto.\n        { econs. eapply times_configuration_step_strong_mon; eauto. }\n      }\n      { i. eapply join_well_ordered; eauto.\n        { eapply join_well_ordered; eauto. eapply incr_times_well_ordered. }\n        { eapply singleton_well_ordered. }\n      }\n      { i. left. right. eexists. eauto. }\n    }\n  }\n  { i. exploit IHBEH.\n    { eapply Configuration.step_future; eauto. } i. des.\n    exploit times_configuration_step_exists; eauto. i. des.\n    { exists (times \\2/ times0). splits.\n      { econs 4; eauto.\n        { econs. eapply times_configuration_step_strong_mon; eauto. }\n        { eapply le_step_behavior_improve; try apply BEH0.\n          eapply times_configuration_step_strong_all_mon; auto. }\n      }\n      { i. eapply join_well_ordered; eauto. }\n      { auto. }\n      { auto. }\n    }\n    { exists (times \\2/ times0). splits.\n      { econs 3; eauto.\n        { econs. eapply times_configuration_step_strong_mon; eauto. }\n      }\n      { i. eapply join_well_ordered; eauto. }\n      { auto. }\n      { auto. }\n    }\n  }\n  { i. esplits.\n    { econs 5. }\n    { instantiate (1:=((fun loc => incr_times) \\2/ (fun _ => eq Time.bot))).\n      i. eapply join_well_ordered; eauto.\n      { eapply incr_times_well_ordered. }\n      { eapply singleton_well_ordered. }\n    }\n    { i. left. eexists. eauto. }\n    { i. right. auto. }\n  }\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/ldrfpf/TimeTraced.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.3522017752483203, "lm_q1q2_score": 0.22940833488470894}}
{"text": "From mathcomp Require Import ssreflect ssrfun eqtype seq ssrint.\nFrom CoqUtils Require Import word.\nFrom extructures Require Import fmap fset.\n\nRequire Import MicroPolicies.Types.\nRequire Import MicroPolicies.Symbolic.\nRequire Import MicroPolicies.LRC.\nRequire Import MicroPolicies.Instance.\n\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\nRequire Export Extraction.Definitions.\n\nOpen Scope string_scope.\n\n(* TL TODO: switch to Show type class, cf coqstring_of_Z *)\n\nAxiom coqstring_of_word : forall {k}, word k -> string.\n(* TL TODO: move this to Extraction.v *)\nExtract Constant coqstring_of_word => \"(fun _ w -> let Word x = Lazy.force w in coqstring_of_camlstring (Big.to_string x))\".\n\nDefinition coqstring_of_nat (n : nat) : string := coqstring_of_word (@as_word 32 (Posz n)).\n\nFixpoint coqstring_of_nat_list_aux (l : list nat) : string :=\n  match l with\n  | nil => \"]\"\n  | cons n nil => \" \" ++ coqstring_of_nat n ++ \" ]\"\n  | cons n l' => \" \" ++ coqstring_of_nat n ++ \";\"\n  end.\n\nDefinition coqstring_of_nat_list (l : list nat) : string :=\n  \"[\" ++ coqstring_of_nat_list_aux l.\n\n\nDefinition coqstring_of_value_tag (t : value_tag) : string :=\n  match t with\n    | Ret n => \"Ret \" ++ coqstring_of_nat n\n    | Other => \"Other\"\n  end.\n\nDefinition coqstring_of_ratom (a : ratom) : string :=\n  \"{ value: \" ++ coqstring_of_word (vala a) ++ \"; \" ++ \"tag: \" ++ coqstring_of_value_tag (taga a) ++ \" }\".\n\nDefinition coqstring_of_regs (regs : { fmap reg mt -> ratom }) : string :=\n  \"regs:{\n  \" ++ foldl (fun s r =>\n  \"reg \" ++ coqstring_of_word (fst r) ++ \" : \" ++ coqstring_of_ratom (snd r) ++ \"\n  \" ++ s) \"\" regs ++ \"}\n  \".\n\nDefinition coqstring_of_instr (i : instr mt) : string :=\n  match i with\n  | Nop => \"Nop\"\n  | Const i r => \"Const r_\" ++ coqstring_of_word r ++ \" <- \" ++ coqstring_of_word i\n  | Mov r1 r2 => \"Mov \" ++ coqstring_of_word r1 ++ \" -> \" ++ coqstring_of_word r2\n  | Binop o r1 r2 r3 => \"Binop [TODO]\"\n  | Load r1 r2 => \"Load [TODO]\"\n  | Store r1 r2 => \"Store [TODO]\"\n  | Jump r => \"Jump r_\" ++ coqstring_of_word r\n  | Bnz r i => \"Bnz [TODO]\"\n  | Jal i => \"Jal \" ++ coqstring_of_word i\n  | JumpEpc => \"JumpEpc\"\n  | AddRule => \"AddRule\"\n  | GetTag r1 r2 => \"GetTag [TODO]\"\n  | PutTag r1 r2 r3 => \"PutTag [TODO]\"\n  | Halt => \"Halt\"\n  end.\n\nDefinition coqstring_of_entry e  :=\n  match e with\n  | None => \"\"\n  | Some (p, l) => coqstring_of_nat p ++ \": \" ++ coqstring_of_nat_list l\n  end.\n\n\nDefinition coqstring_of_mem_tag (t : mem_tag) :=\n  \"{ vtag: \" ++ coqstring_of_value_tag (vtag t) ++\n  \"; color: \" ++ coqstring_of_nat (color t) ++\n  \"; entry: \" ++ coqstring_of_entry (entry t) ++ \"; }\".\n\nDefinition coqstring_of_matom (a : matom) : string :=\n  let value := match decode_instr (vala a) with\n               | Some i => coqstring_of_instr i\n               | None => coqstring_of_word (vala a)\n               end in\n\"{ value: \" ++ value ++ \"; \" ++ \"\n      tag: \" ++ coqstring_of_mem_tag (taga a) ++ \" }\".\n\nDefinition coqstring_of_mem (mem : { fmap mword mt -> matom }) : string :=\n  \"mem:{\n\" ++ foldl (fun s m =>\n              coqstring_of_word (fst m) ++ \" : \" ++ coqstring_of_matom (snd m) ++ \"\n\" ++ s) \"\" mem ++ \"}\n\".\n\nDefinition coqstring_of_pc_tag (t : pc_tag) : string :=\n  match t with\n  | Level n => \"Level \" ++ coqstring_of_nat n\n  end.\n\nDefinition coqstring_of_pc (pc : atom (mword mt) pc_tag) : string :=\n  \"pc: \" ++ coqstring_of_word (vala pc) ++ \"; \" ++ coqstring_of_pc_tag (taga pc) ++ \"\n\".\n\nDefinition coqstring_of_internal (_ : unit) : string := \"\".\n\n\nDefinition coqstring_of_state (st : state) : string :=\n\"============================\n\" ++ coqstring_of_pc (Symbolic.pc st)\n  ++ coqstring_of_internal (Symbolic.internal st)\n  ++ coqstring_of_regs (Symbolic.regs st)\n  ++ coqstring_of_mem (Symbolic.mem st) ++\n\"============================\n\".\n\n\n(* Require Import CompCert.Events. *)\n(* From QuickChick Require Import QuickChick. *)\n\n(* Definition coqstring_of_Z (z : BinNums.Z) := show z. *)\n\n(* Definition coqstring_of_event (e : event) := *)\n(*   match e with *)\n(*   | ECall c p r c' => \"(ECall \" ++ coqstring_of_nat c ++ \" \" *)\n(*                                 ++ coqstring_of_nat p ++ \" \" *)\n(*                                 ++ coqstring_of_Z r   ++ \" \" *)\n(*                                 ++ coqstring_of_nat c' ++ \")\" *)\n(*   | ERet c r c' => \"(ERet \" ++ coqstring_of_nat c ++ \" \" *)\n(*                             ++ coqstring_of_Z r   ++ \" \" *)\n(*                             ++ coqstring_of_nat c' ++ \")\" *)\n(*   end. *)\n", "meta": {"author": "secure-compilation", "repo": "when-good-components-go-bad", "sha": "7bef0fa18780f1e9699abcdadd61e15bf3aba95d", "save_path": "github-repos/coq/secure-compilation-when-good-components-go-bad", "path": "github-repos/coq/secure-compilation-when-good-components-go-bad/when-good-components-go-bad-7bef0fa18780f1e9699abcdadd61e15bf3aba95d/MicroPolicies/Printer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.22936331116887343}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\nRequire Export list.\n\n\nDefinition hidden_disjoint {T} a b := @disjoint T a b.\n\nLtac disj_flat_map_step :=\n  match goal with\n    | [ H1 : disjoint ?a (flat_map ?f ?l), H2 : LIn ?x ?l |- _ ] =>\n      let k := fresh H1 in\n      let h := fresh H2 in\n      assert (disjoint a (flat_map f l)) as k by trivial;\n        trw_h disjoint_flat_map_r k;\n        assert (LIn x l) as h by trivial;\n        apply k in h;\n        clear k;\n         fold (hidden_disjoint a (flat_map f l)) in H1\n    | [ H1 : disjoint (flat_map ?f ?l) ?a, H2 : LIn ?x ?l |- _ ] =>\n      let k := fresh H1 in\n      let h := fresh H2 in\n      assert (disjoint (flat_map f l) a) as k by trivial;\n        trw_h disjoint_flat_map_l k;\n        assert (LIn x l) as h by trivial;\n        apply k in h;\n        clear k;\n         fold (hidden_disjoint (flat_map f l) a) in H1\n   end.\n\nLtac disj_flat_map := (repeat disj_flat_map_step); allunfold (@hidden_disjoint).\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/util/list_tacs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22936330534058058}}
{"text": "(* USIG instance *)\n\nRequire Export MinBFTprops0.\nRequire Export MinBFTrep.\nRequire Export MinBFTstate.\nRequire Export MinBFTsubs.\nRequire Export MinBFTtacts2.\n\n\nSection MinBFTmon.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext        }.\n  Context { minbft_context      : MinBFT_context      }.\n  Context { m_initial_keys      : MinBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys   }.\n  Context { usig_hash           : USIG_hash           }.\n  Context { minbft_auth         : MinBFT_auth         }.\n\n\n  Lemma le_usig_counter_increment_USIG :\n    forall u, usig_counter u <= usig_counter (increment_USIG u).\n  Proof.\n    tcsp.\n  Qed.\n  Hint Resolve le_usig_counter_increment_USIG : minbft.\n\n  Lemma monotonicity_local :\n    forall {eo : EventOrdering}\n           (e : Event)\n           (s1 s2 : USIG_state),\n      is_replica e\n      -> M_state_sys_before_event MinBFTsys e USIGname = Some s1\n      -> M_state_sys_on_event MinBFTsys e USIGname = Some s2\n      -> usig_counter s1 <= usig_counter s2.\n  Proof.\n    introv isr eqst1 eqst2.\n\n    apply map_option_Some in eqst1.\n    apply map_option_Some in eqst2.\n\n    unfold is_replica in isr.\n    destruct isr as [r isr].\n    rewrite isr in *; simpl in *.\n    exrepnd; rev_Some.\n\n    applydup M_run_ls_on_event_ls_is_minbft in eqst2; exrepnd; subst; simpl in *.\n    rewrite M_run_ls_on_event_unroll2 in eqst2.\n    rewrite eqst1 in eqst2; simpl in *.\n    applydup M_run_ls_before_event_ls_is_minbft in eqst1; exrepnd; subst; simpl in *.\n    autorewrite with minbft in *; minbft_simp.\n    clear eqst1.\n\n    apply map_option_Some in eqst2; exrepnd; minbft_simp.\n    unfold M_run_ls_on_input_ls, M_run_ls_on_input in eqst0.\n    autorewrite with comp minbft in *.\n\n    Time minbft_dest_msg Case;\n      repeat (simpl in *; autorewrite with comp minbft in *; smash_minbft2).\n  Qed.\n\n  Lemma monotonicity_local2 :\n    forall {eo : EventOrdering}\n           (e1 e2 : Event)\n           (s1 s2 : USIG_state),\n      is_replica e2\n      -> e1 ⊂ e2\n      -> M_state_sys_on_event MinBFTsys e1 USIGname = Some s1\n      -> M_state_sys_on_event MinBFTsys e2 USIGname = Some s2\n      -> usig_counter s1 <= usig_counter s2.\n  Proof.\n    introv isr lte eqst1 eqst2.\n    applydup pred_implies_local_pred in lte.\n    subst.\n    rewrite <- M_state_sys_before_event_as_M_state_sys_on_event_pred in eqst1; eauto 3 with eo.\n    eapply monotonicity_local; eauto.\n  Qed.\n\n  Lemma monotonicity :\n    forall {eo : EventOrdering}\n           (e1 e2 : Event)\n           (s1 s2 : USIG_state),\n      is_replica e2\n      -> M_state_sys_on_event MinBFTsys e1 USIGname = Some s1\n      -> M_state_sys_on_event MinBFTsys e2 USIGname = Some s2\n      -> e1 ⊑ e2\n      -> usig_counter s1 <= usig_counter s2.\n  Proof.\n    intros eo e1 e2; revert e1.\n    induction e2 as [e2 ind] using predHappenedBeforeInd;[]; introv isrep eqst1 eqst2 lte.\n\n    apply localHappenedBeforeLe_implies_or2 in lte; repndors; subst; tcsp;[|].\n\n    { rewrite eqst1 in eqst2; ginv. }\n\n    apply local_implies_pred_or_local in lte; repndors; exrepnd.\n\n    {\n      eapply (@M_state_sys_before_event_if_on_event_direct_pred _ _ _ _ _ _ _ _ USIGname) in lte;[|eauto].\n      eapply monotonicity_local; eauto.\n    }\n\n    pose proof (M_state_sys_on_event_some_between e e2 MinBFTsys USIGname s2) as q.\n    repeat (autodimp q hyp); eauto 3 with eo minbft comp;[].\n    exrepnd.\n\n    pose proof (ind e lte1 e1 s1 s') as ind; repeat (autodimp ind hyp); eauto 3 with eo minbft comp.\n    pose proof (monotonicity_local2 e e2 s' s2) as q; repeat (autodimp q hyp); try omega.\n  Qed.\n\n\nEnd MinBFTmon.\n\n\nHint Resolve le_usig_counter_increment_USIG : minbft.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MinBFTmon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22936330534058053}}
{"text": "(** Porting the OCaml version of the forcing translation plugin.\n\n    Some notes:\n    - the Yoneda embedding is removed from the translation and should be provided by\n      the user, if required;\n    - porting the OCaml code required to change de Bruijn indices to start from 0,\n      and not from 1 as in the Coq's kernel (hopefully, fixed everywhere);\n    - only the translation for the negative fragment is supported for now. *)\n\nRequire Import List Arith Nat.\nRequire Import String.\nRequire Import Template.monad_utils Template.Ast\n        Template.Template Template.LiftSubst Template.Checker Template.utils\n        Template.AstUtils Template.LiftSubst.\nRequire Import Forcing.translation_utils.\nRequire Import Forcing.TFUtils.\n\nImport ListNotations MonadNotation.\n\nLocal Open Scope string_scope.\n\nDefinition list_to_string {A : Type} f (xs : list A) : string\n  := (List.fold_left append (List.map (fun i => f i ++ \" \") xs) \"\").\n\n(** We add a composition and an identity as a part of a categorical structe that must\n    be provided by a user, since the Yoneda embedding is not a part of\n    the plugin anymore (instead, it could be done externally by a\n    user) *)\n\nRecord category : Type :=\n  mkCat { cat_obj : term;\n          (** Objects. Must be of type [Type]. *)\n\n          cat_hom : term;\n          (** Morphisms. Must be of type [cat_obj -> cat_obj -> Type]. *)\n\n          cat_id : term;\n          (** Identity. Must be of the type [forall {a : cat_obj}, cat_hom a a]  *)\n\n          cat_comp : term;\n          (** Composition. Must be of the type\n              [forall {a b c : cat_obj}, cat_hom b c -> cat_hom a b -> cat_hom a c] *)\n        }.\n\nDefinition makeCatS (obj hom id_ comp : string) :=\n  {| cat_obj := tConst obj [];\n     cat_hom := tConst hom [];\n     cat_id := tConst id_ [];\n     cat_comp := tConst comp [];\n  |}.\n\n\nQuote Definition cat_def := Eval compute in category.\n\nDefinition obj_name := nNamed \"R\".\nDefinition knt_name := nNamed \"k\".\n\n(** We assume that there is a hidden topmost variable [p : Obj] in the context *)\n\nDefinition pos_name := nNamed \"p\".\nDefinition hom_name := nNamed \"α\".\n\n(** Optimization of cuts *)\n(* TODO: for now it is just an ordinary tApp; could be changed if we need it later *)\n\nDefinition mkOptApp t args := tApp t args.\n(* The original OCaml inplementation  *)\n(* let mkOptApp (t, args) = *)\n(*   let len = Array.length args in *)\n(*   try *)\n(*     let (_, t) = Term.decompose_lam_n len t in *)\n(*     Vars.substl (CArray.rev_to_list args) t *)\n(*   with _ -> *)\n(* mkApp (t, args) *)\n\n\n(** Forcing translation *)\nInductive forcing_condition :=\n| fcVar : forcing_condition\n| fcLift : forcing_condition.\n\nRecord forcing_context :=\n  mkFCtxt { f_context : list forcing_condition;\n            f_category : category;\n            f_translator : tsl_table;\n            (* A map associating to all source constant a forced constant *)\n          }.\n\nDefinition fcond_to_string fc :=\n  match fc with\n  | fcVar => \"fcVar\"\n  | fcLift => \"fcLift\"\n  end.\n\n\n(* WARNING: tRel indices start from 0 in Tempalte Coq and *not* from 1 as for mkRel in the kernel  *)\n\nFixpoint last_condition fc :=\n  match fc with\n  | [] => 0\n  | fcVar :: fctx => 1 + last_condition fctx\n  | fcLift :: fctx => 1\n  end.\n\nFixpoint only_vars (fctx : list forcing_condition) : bool :=\n  match fctx with\n  | [] => true\n  | fcVar :: tl => only_vars tl\n  | fcLift :: _ => false\n  end.\n\nDefinition top_condition (fctx : list forcing_condition) : nat :=\n  let fld_with acc f :=\n      match f with\n      | fcVar => 1 + acc\n      | fcLift => 2 + acc\n      end in\n  List.fold_left fld_with fctx 0.\n\n(* Collects all the morphisms up to a given variable.\n   Returns the resulting list along with the (optional) index\n   corresponding to the domian of the last morphism in the composition.\n   We return [None] if there is no morphism left in the list\n   *after* the given variable *)\nFixpoint gather_morphisms_internal i n fctx : list nat * option nat :=\n  if (Nat.eqb n 0) then ([], match fctx with\n                             | [] => None\n                             | _  =>  if (only_vars fctx) then None\n                                      else Some (i + last_condition fctx)\n                             end)\n  else match fctx with\n       | [] => ([], None)\n       | fcVar :: fctx => gather_morphisms_internal (i + 1) (n - 1) fctx\n       | fcLift :: fctx => let (i',b) := gather_morphisms_internal (i + 2) n fctx\n                           in  (i :: i', b)\n       end.\n\n(** We return all the morphisms for the variable (represented as a de\n    Bruijn index) and index of the domain of the last morphism in the\n    comosition *)\nDefinition gather_morphisms (n : nat) (fctx : forcing_context) : list nat * option nat :=\n  gather_morphisms_internal 0 (n+1) (f_context fctx).\n\nDefinition morphism_var (n : nat) (fctx : forcing_context) : term :=\n  let (morphs, next_cond) := gather_morphisms n fctx in\n  let last := tRel (last_condition fctx.(f_context)) in\n  let cat := (f_category fctx) in\n  let fold_with (accu : term) (i j : nat) :=\n      tApp cat.(cat_comp) [tRel (j+1); tRel (i+1); last; accu; tRel i] in\n  let init := tApp cat.(cat_id) [last] in\n  let fix f_left l accu {struct l} :=\n      match l with\n      | [] => accu\n      | i :: t =>\n        match t with\n        (* We have to use this to handle a special case: the top level\n           condition.  There are two cases: we have traversed all the\n           forcing context (i.e. next_cond=None), or we found the\n           variable before we traversed the whole forcing context (and\n           there are some morphism after the variable in the\n           context). In first case we know that the last morphism in\n           the composition is from the top-level forcing condition *)\n        | [] => let top_rel :=\n                    match next_cond with\n                    | None => tRel (top_condition fctx.(f_context))\n                    | Some i => tRel i\n                    end in\n                tApp cat.(cat_comp) [top_rel; tRel (i+1); last; accu; tRel i]\n        | j :: t' => f_left t (fold_with accu i j)\n        end\n      end in\n  (* tVar (list_to_string fcond_to_string fctx.(f_context)). *)\n  f_left morphs init.\n  (* in *)\n  (* List.fold_left fold_with morphs init. *)\n\n(* The original OCaml code *)\n(* let morphism_var n fctx = *)\n(*   let morphs = gather_morphisms n fctx in *)\n(*   let last = mkRel (last_condition fctx) in *)\n(*   let fold accu i = *)\n(*     trns fctx.category dummy dummy last (mkRel i) accu *)\n(*   in *)\n(* List.fold_left fold (refl fctx.category last) morphs *)\n\n\n(** A stub for the actual evar_map definition *)\nDefinition evar_map := unit.\n\nModule Environ.\n  (** Stub for global environment Environ *)\n\n  Definition rel_declaration := unit.\n\n  Record env := { env_globals : global_declarations }.\n\n  Definition empty_env := {| env_globals := [] |}.\n\n  Definition rel_context (e : env) : list rel_declaration := [].\n\n  Definition of_global_context (c : global_context) : env :=  {| env_globals := fst c |}.\n\n  Definition to_global_context (E : env) : global_context :=\n    Typing.reconstruct_global_context E.(env_globals).\nEnd Environ.\n\nDefinition get_var_shift n fctx :=\n  let fix get n fctx :=\n      if (Nat.eqb n 0 ) then 0\n      else\n        match fctx with\n        | [] => n\n        | fcVar :: fctx => 1 + get (n - 1) fctx\n        | fcLift :: fctx => 2 + get n fctx\n      end\n  in\n  get (n + 1) fctx.(f_context).\n\n\n(* Some examples to play with  *)\nDefinition Obj := Type.\nDefinition Hom := (fun x y => x -> y).\nDefinition Id_hom := @id.\nDefinition Comp := @Coq.Program.Basics.compose.\n\nDefinition test_cat : category :=\n  makeCatS \"Obj\" \"Hom\" \"Id_hom\" \"Comp\".\n\nDefinition test_fctx :=\n  {| f_context := [fcLift; fcLift; fcVar; fcLift];\n     f_category := test_cat;\n     f_translator := []|}.\n\nEval compute in gather_morphisms 0 test_fctx.\nEval compute in get_var_shift 1 test_fctx.\nEval compute in morphism_var 1 test_fctx.\n\n\n(* We convert the result of checking for relevance in a stupid way :)\n   TODO: think about the error propagation *)\nDefinition from_rel_result (rl : rel_result) : relevance :=\n  match rl with\n  | RelOk r => r\n  | RelNotSort _ => Relevant\n  | RelTypingError _ => Relevant\n  end.\n\n\n(* TODO: move inference of the relevance to another place,\n   since it does not change during the translation.\n   Probably a good place is [translate] function that calls [otranslate]  *)\n\n(** Produces a forcing condition along with corresponding morphism.\n    We need to determine the relevance of the types of morphisms and objects in the category.\n    In order to do that we use the [relevance_of_type] function, and this function requires a global context, so now\n    [get_ctx_lift] also takes is as a parameter *)\nDefinition get_ctx_lift (cat : category) (env : Environ.env) (last_fc : nat) :=\n  let g_ctx := Environ.env_globals env in\n  let relevance_of_arg := from_rel_result (relevance_of_type g_ctx [] cat.(cat_obj)) in\n  (* We are interested in the relevance of [hom x y] for any [x] and [y] of the appropriate type.\n     So, we create a dummy context with two entries and the feed it into the [relevance_of_type] *)\n  let dummy_ctx :=\n      [Build_context_decl nAnon relevance_of_arg None cat.(cat_obj);\n       Build_context_decl nAnon relevance_of_arg None cat.(cat_obj)] in\n  let dummy_app := (tApp cat.(cat_hom) [tRel 1; tRel 0]) in\n  let relevance_hom :=\n      from_rel_result (relevance_of_type (Environ.env_globals env) dummy_ctx dummy_app) in\n  [ vass hom_name relevance_hom (tApp cat.(cat_hom) [(tRel (1 + last_fc)); (tRel 0)]);\n    vass pos_name relevance_of_arg cat.(cat_obj) ].\n\nDefinition extend_forcing_ctx (fctx : forcing_context) (f : forcing_condition):=\n  {| f_context := f :: fctx.(f_context);\n     f_category := fctx.(f_category);\n     f_translator := fctx.(f_translator)|}.\n\n\n(** Packing the extension of a context and of a forcing context together *)\nDefinition extend (env : Environ.env) (fctx : forcing_context) : list context_decl * forcing_context :=\n  let ext := get_ctx_lift fctx.(f_category) env (last_condition fctx.(f_context)) in\n  (ext, extend_forcing_ctx fctx fcLift).\n\nDefinition add_variable fctx :=\n  {| f_context := fcVar :: fctx.(f_context);\n     f_category := fctx.(f_category);\n     f_translator := fctx.(f_translator)|}.\n\n(** Handling of globals *)\n\nDefinition translate_var (fctx : forcing_context) (n : nat) : term :=\n  let p := tRel (last_condition fctx.(f_context)) in\n  let f := morphism_var n fctx in\n  let m := get_var_shift n fctx in\n  (* We subsrtact 1 from m because indicies start from 0 *)\n  tApp (tRel (m-1)) [p; f].\n\nDefinition get_inductive (fctx : forcing_context) (ind : inductive) : inductive :=\n  let gr := IndRef ind in\n  let gr_ := lookup_default fctx.(f_translator) gr in\n  match gr_ with\n  | tInd ind_ _ => ind_\n  | _ => {| inductive_mind := \"inductive translation not found: \" ++ ind.(inductive_mind); inductive_ind := 0 |}\n  end.\n\nDefinition should_not_be_ind := tVar \"Should not be an application of an inductive type constructor\".\n\nDefinition apply_global (env : Environ.env) (sigma : evar_map) gr (u : universe_instance) fctx :=\n  (** FIXME -- a comment from the OCaml source code *)\n  (* The parameter [u] is never used in the definition *)\n  let p' := lookup_default fctx.(f_translator) gr in\n  (* let (sigma, c) := Evd.fresh_global env sigma p' in *)\n  let last := last_condition fctx.(f_context) in\n  match gr with\n  | IndRef _ => (sigma, should_not_be_ind)\n  | _ => (sigma, tApp p' [ tRel last ])\n  end.\n\n\n(** Forcing translation core *)\n\nDefinition not_supported := tVar \"Not supported\".\n\nDefinition is_prop (s : universe) :=\n  match s with\n  | [(Level.lProp, false)] => true\n  | _ => false\n  end.\n\nFixpoint sep_last' {A} (xs : list A) : option (A *list A) :=\n  match xs with\n    [] => None\n  | hd::[] => Some (hd,[])\n  | hd::tl => match (sep_last' tl) with\n              | None => None\n              | Some (l,tl) => Some (l,hd::tl)\n              end\n  end.\n\nFixpoint sep_last {A} (xs : list A) : option (A *list A) :=\n  match xs with\n    [] => None\n  | hd::tl => Some (hd,tl)\n  end.\n\n\nDefinition id_translate sigma c : unit * term :=\n  (sigma, c).\n\nDefinition otranslate_type (tr : Environ.env -> forcing_context -> evar_map -> term -> unit * term)\n           (env : Environ.env) (fctx : forcing_context) (sigma : evar_map) (t : term)\n  : unit * term :=\n  let (sigma, t_) := tr env fctx sigma t in\n  let last := tRel (last_condition fctx.(f_context)) in\n  let t_ := mkOptApp t_ [ last; tApp fctx.(f_category).(cat_id) [last]] in\n(sigma, t_).\n\nDefinition otranslate_boxed (tr : Environ.env -> forcing_context -> evar_map -> term -> unit * term)\n           (env : Environ.env) (fctx : forcing_context) (sigma : evar_map) (t : term)\n  : unit * term :=\n  let (ext, ufctx) := extend env fctx in\n  let (sigma, t_) := tr env ufctx sigma t in\n  let t_ := it_mkLambda_or_LetIn t_ ext in\n  (sigma, t_).\n\nDefinition otranslate_boxed_type (tr : Environ.env -> forcing_context -> evar_map -> term -> unit * term) env fctx sigma t :=\n  let (ext, ufctx) := extend env fctx in\n  let (sigma, t_) := otranslate_type tr env ufctx sigma t in\n  let t_ := it_mkProd_or_LetIn t_ ext in\n  (sigma, t_).\n\nQuote Recursively Definition bazz := prod.\nQuote Definition bar := (fun (a b : nat) => a = b).\n\nDefinition lookup_ind Σ ind i (u : list Level.t) (* TODO Universes *) :\n  option one_inductive_body :=\n    match lookup_env Σ ind with\n    | Some (InductiveDecl _ mib) => nth_error mib.(ind_bodies) i\n    |  _ => None\n    end.\n\nDefinition lookup_mind Σ ind (u : list Level.t) (* TODO Universes *) :\n  option mutual_inductive_entry :=\n    match lookup_env Σ ind with\n    | Some (InductiveDecl _ mib) => Some (mind_body_to_entry mib)\n    |  _ => None\n    end.\n\n\nFixpoint list_init_rev {A} (n : nat) (f : nat -> A) : list A :=\n  match n with\n  | O => []\n  | S n' => f n' :: list_init_rev n' f\n  end.\n\nDefinition list_init {A} (n : nat) (f : nat -> A) : list A := List.rev (list_init_rev n f).\n\n(*Ported from the OCaml implementation *)\nFixpoint mapi {A B} (i : nat) (f : nat -> A -> B) (xs : list A) : list B :=\n  match xs with\n  | [] => []\n  | a::l => let r := f i a in r :: mapi (i + 1) f l\n  end.\n\nDefinition map_local_entry (f : term -> term) (ent : local_entry) : local_entry :=\n  match ent with\n  | LocalDef t => LocalDef (f t)\n  | LocalAssum t => LocalAssum (f t)\n  end.\n\nDefinition substn_decl i n (d : context_decl) : context_decl :=\n  {| decl_name := d.(decl_name);\n     decl_relevance := d.(decl_relevance);\n     decl_body := match d.(decl_body) with None => None | Some t => Some (subst i n t) end;\n     decl_type := subst i n d.(decl_type) |}.\n\n\nDefinition dummy_ctx_decl : context_decl :=\n  {| decl_name := nAnon;\n     decl_relevance := Relevant;\n     decl_body := None;\n     decl_type := tVar \"Inductive not declared\"|}.\n\n  Fixpoint decompose_prod_r (t : term) : (list name * list relevance * list term) * term :=\n  match t with\n  | tProd n r A B =>\n    let (nrAs, B) := decompose_prod_r B in\n    match nrAs with\n    | (ns, rs, As) => (n :: ns, r :: rs, A :: As, B)\n    end\n  | _ => ([], [], [], t)\n  end.\n\n  Fixpoint zip3_with {A B C D : Type} (xs : list A) (ys : list B) (zs : list C)\n           (f : A -> B -> C -> D)\n    : list D :=\n    match xs,ys,zs with\n    | [],_,_ => []\n    | _,[],_ => []\n    | _,_,[] => []\n    | x :: xs', y :: ys', z :: zs' => f x y z :: zip3_with xs' ys' zs' f\n    end.\n\n  Definition to_rel_context (ns : list name) (rs : list relevance) (tys : list term) :=\n    let vars := zip3_with ns rs tys (fun a b c => (a,b,c)) in\n    let fn p := match p with\n                  | (nam,r,ty) => {| decl_name := nam;\n                                     decl_relevance := r;\n                                     decl_body := None;\n                                     decl_type := ty |}\n                end in\n    List.map fn vars.\n\n(** Builds a translation for the inductive type occuring in the term.\n    Assumes that the type itself is prevously translated and added to\n    the translation table and to the global context *)\nDefinition otranslate_ind\n           (tr : Environ.env -> forcing_context -> evar_map -> term -> unit * term)\n           (env : Environ.env) (fctx : forcing_context) (sigma :evar_map) (ind : inductive) (u : universe_instance) (args : list term) :=\n  (* Looking up in the translation table *)\n  let ind_ := get_inductive fctx ind in\n  (* Looking up in the global environment for the actual body of the translated inductive *)\n  let oib' := lookup_ind (Environ.to_global_context env)\n                         ind_.(inductive_mind) ind_.(inductive_ind) [] in\n  (* Translating arguments *)\n  let fold sigma t := otranslate_boxed tr env fctx sigma t in\n  let fix fold_map_fix a args :=\n      match args with\n      | [] => (a, [])\n      | hd :: tl =>\n        let (a_, c_) := fold sigma hd in\n        let (a__, cs) := fold_map_fix a_ tl in\n        (a__, c_ :: cs)\n      end in\n  let (sigma, args_) := fold_map_fix sigma args in\n  (* Recovering a context consisting of parameters and indices of the given inductive type *)\n  let ind_ctx ind := match (decompose_prod_r ind.(ind_type)) with\n                     | (ns,rs,tys,_) => to_rel_context ns rs tys\n                     end\n  in\n  let all_params :=\n      match oib' with\n      | Some t => ind_ctx t\n      | None => [dummy_ctx_decl]\n      end\n  in\n  (** First parameter is the toplevel forcing condition *)\n  let (_, paramtyp) :=\n      match oib' with\n      | Some t => option_get (dummy_ctx_decl,[]) (sep_last all_params)\n      | None => (dummy_ctx_decl,[dummy_ctx_decl])\n      end in\n  let nparams := List.length paramtyp in\n  let last := last_condition fctx.(f_context) in\n  let fctx := List.fold_left (fun accu _ => add_variable accu) paramtyp fctx in\n  (* We extend the focring context with a new lift *)\n  let (ext, fctx) := extend env fctx in\n  let mk_var n :=\n    let m := nparams - n - 1 in\n    let (ext0, fctx) := extend env fctx in\n    let ans := translate_var fctx m in\n    it_mkLambda_or_LetIn ans ext0\n  in\n  let params := list_init nparams mk_var in\n  (* Now, we apply the translation of the inductive type to a new forcing condition *)\n  let app := tApp (tInd ind_ u) (tRel (last_condition fctx.(f_context)) :: params) in\n  (* We have to substitute the focring condition which was the last one\n     before we extended the forcing conetxt *)\n  let map_p i c := substn_decl (tRel last) (nparams - i - 1) c in\n  let paramtyp' := List.rev paramtyp in\n  let paramtyp_subst := mapi 0 map_p paramtyp' in\n  let ans := it_mkLambda_or_LetIn app (ext ++ paramtyp_subst)%list in\n  (sigma, mkOptApp ans args_).\n\n(** Adds lambda abstractions build from the context [Γ] on top if the given term [body] *)\nDefinition lambda_prefix Γ body := it_mkLambda_or_LetIn body Γ.\n\n(** Adds Π's build from the context [Γ] on top if the given term [body] *)\nDefinition pi_prefix Γ body := it_mkProd_or_LetIn body Γ.\n\n(** Returns a function, wrapping\n    give term [t] into [λ (q : cat) (f : Hom(σₑ,q)) . t],\n    where σₑ is the last forcing condition of σ.\n    See Notaion 1 in DSoF paper. *)\nDefinition λ_q_f (env : Environ.env) (σ : forcing_context) : forcing_context * (term -> term) :=\n  let ext_ctx := get_ctx_lift σ.(f_category) env (last_condition σ.(f_context)) in\n  let ext_fctx := extend_forcing_ctx σ fcLift in\n  (ext_fctx, lambda_prefix ext_ctx).\n\n(** Similarly to [λ_q_f], but for [Π q f].\n    See Notaion 1 in DSoF paper. *)\nDefinition Π_q_f (env : Environ.env) (σ : forcing_context) : forcing_context * (term -> term) :=\n  let ext_ctx := get_ctx_lift σ.(f_category) env (last_condition σ.(f_context)) in\n  let ext_fctx := extend_forcing_ctx σ fcLift in\n  (ext_fctx, pi_prefix ext_ctx).\n\nFixpoint otranslate (env : Environ.env) (fctx : forcing_context)\n         (sigma : evar_map) (c : term) {struct c} : evar_map * term :=\n  match c with\n| tRel n =>\n  let ans := translate_var fctx n in\n  (* let ans := tVar (list_to_string fcond_to_string fctx.(f_context) ++ \" | tRel \" ++ string_of_int n) in *)\n    (sigma, ans)\n| tSort s =>\n  let (sigma, s') :=\n      if is_prop s then (sigma, s)\n    else\n      (* TODO: Not sure how to deal with the universe variable generation *)\n      (* Evd.new_sort_variable Evd.univ_flexible sigma *)\n      (* Probably, use an empty list as a universe param *)\n      (* For now, we just return the original universe, as it is given in the paper *)\n      (sigma, s)\n  in\n  let (fctx_ext, λqf) := λ_q_f env fctx in\n  (* TODO: universe variable generation *)\n  (* let sigma := Evd.set_leq_sort env sigma s s' in *)\n  let (_, Πrg) := Π_q_f env fctx_ext in\n  let tpe := Πrg (tSort s') in\n  (sigma, λqf tpe)\n| tCast c k t =>\n  let (sigma, c_) := otranslate env fctx sigma c in\n  let (sigma, t_) := otranslate_type otranslate env fctx sigma t in\n  let ans := tCast c_ k t_ in\n  (sigma, ans)\n| tProd na r t u =>\n  let (ext0, fctx) := extend env fctx in\n  (** Translation of t *)\n  let (sigma, t_) := otranslate_boxed_type otranslate env fctx sigma t in\n  (** Translation of u *)\n  let ufctx := add_variable fctx in\n  let (sigma, u_) := otranslate_type otranslate env ufctx sigma u in\n  (** Result *)\n  let ans := tProd na r t_ u_ in\n  let lam := it_mkLambda_or_LetIn ans ext0 in\n  (sigma, lam)\n| tLambda na r t u =>\n  (** Translation of t *)\n  let (sigma, t_) := otranslate_boxed_type otranslate env fctx sigma t in\n  (** Translation of u *)\n  let ufctx := add_variable fctx in\n  let (sigma, u_) := otranslate env ufctx sigma u in\n  let ans := tLambda na r t_ u_ in\n  (sigma, ans)\n| tLetIn na r c t u =>\n  let (sigma, c_) := otranslate_boxed otranslate env fctx sigma c in\n  let (sigma, t_) := otranslate_boxed_type otranslate env fctx sigma t in\n  let ufctx := add_variable fctx in\n  let (sigma, u_) := otranslate env ufctx sigma u in\n  (sigma, tLetIn na r c_ t_ u_)\n| tApp (tInd t u) args  => otranslate_ind otranslate env fctx sigma t u args\n| tApp t args =>\n  let (sigma, t_) := otranslate env fctx sigma t in\n  let fold sigma u := otranslate_boxed otranslate env fctx sigma u in\n  (* implementing a specialised version of fold_map' from ftUtils as a nested fix *)\n  let fix fold_map_fix a args :=\n      match args with\n      | [] => (a, [])\n      | hd :: tl =>\n        let (a_, c_) := fold sigma hd in\n        let (a__, cs) := fold_map_fix a_ tl in\n        (a__, c_ :: cs)\n      end in\n  let (sigma, args_) := fold_map_fix sigma args in\n  (* the original OCaml code *)\n  (* let fold sigma u = otranslate_boxed env fctx sigma u in *)\n  (* let (sigma, args_) = CArray.fold_map fold sigma args in *)\n  let app := tApp t_ args_ in  (sigma, app)\n| tVar id => (* [VarRef] is not defined as a constuctor for [global_reference] in Template Coq *)\n  (sigma, not_supported)\n  (* apply_global env sigma (VarRef id) Instance.empty fctx *)\n| tConst p u =>  apply_global env sigma (ConstRef p) u fctx\n| tInd ind u => otranslate_ind otranslate env fctx sigma ind u []\n| tConstruct c u _ => (sigma, not_supported)\n  (* apply_global env sigma (ConstructRef c) u fctx *)\n| tCase ci rel r c p => (sigma, not_supported)\n(* Comment out this case as well, since inductive types are not yet supported by this translation *)\n   (* let ind_ = get_inductive fctx ci.ci_ind in *)\n   (* let ci_ = Inductiveops.make_case_info env ind_ ci.ci_pp_info.style in *)\n   (* let (sigma, c_) = otranslate env fctx sigma c in *)\n   (* let fix_return_clause env fctx sigma r = *)\n   (*   (** The return clause structure is fun indexes self => Q *)\n   (*       All indices must be boxed, but self only needs to be translated *) *)\n   (*   let (args, r_) = decompose_lam_assum r in *)\n   (*   let ((na, _, self), args) = match args with h :: t -> (h, t) | _ -> assert false in *)\n   (*   let fold (sigma, fctx) (na, o, u) =  *)\n   (*    (** For every translated index, the corresponding variable is added *)\n   (*        to the forcing context *) *)\n   (*     let (sigma, u_) = otranslate_boxed_type env fctx sigma u in *)\n   (*     let fctx = add_variable fctx in *)\n   (*     (sigma, fctx), (na, o, u_) *)\n   (*   in *)\n   (*   let (sigma, fctx), args = CList.fold_map fold (sigma, fctx) args in *)\n   (*   let (sigma, self_) = otranslate_type env fctx sigma self in *)\n   (*   let fctx_ = add_variable fctx in *)\n   (*   let (sigma, r_) = otranslate_type env fctx_ sigma r_ in *)\n   (*   let (ext, ufctx) = extend fctx in *)\n   (*   let selfid = Id.of_string \"self\" in *)\n   (*   let r_ = Reductionops.nf_betadeltaiota env Evd.empty r_ in  *)\n   (*   let r_ = Vars.substnl [it_mkLambda_or_LetIn (mkVar selfid) ext] 1 (Vars.lift 1 r_) in *)\n   (*   let r_ = Reductionops.nf_beta Evd.empty r_ in  *)\n   (*   let r_ = Vars.subst_var selfid r_ in *)\n   (*   let r_ = it_mkLambda_or_LetIn r_ ((na, None, self_) :: args) in  *)\n   (*   (sigma, r_)        *)\n   (* in *)\n   (* let (sigma, r_) = fix_return_clause env fctx sigma r in *)\n   (* let fold sigma u = otranslate env fctx sigma u in *)\n   (* let (sigma, p_) = CArray.fold_map fold sigma p in *)\n   (* (sigma, mkCase (ci_, r_, c_, p_)) *)\n| tFix _ _ => (sigma, not_supported)\n| tCoFix _ _ => (sigma, not_supported)\n| tProj _ _ => (sigma, not_supported)\n| tMeta _ => (sigma, not_supported)\n| tEvar _ _ => (sigma, not_supported)\n  end.\n\nDefinition empty translator cat lift env :=\n  let ctx := Environ.rel_context env in\n  let empty := {| f_context := []; f_category := cat; f_translator := translator; |} in\n  let empty := List.fold_right (fun _ fctx => add_variable fctx) empty ctx in\n  let fix flift fctx n :=\n      match n with\n      | O => fctx\n      | S n' => flift (snd (extend env fctx)) n'\n      end\n  in\n  flift empty (match lift with None => 0 | Some n => n end).\n\n\n(** The toplevel option allows to close over the topmost forcing condition *)\n\nDefinition toplevel_term (cat : category) (c : term) : term\n  := tLambda pos_name Relevant cat.(cat_obj) c.\n\nDefinition toplevel_type (cat : category) (c : term) : term\n  := tProd pos_name Relevant cat.(cat_obj) c.\n\nDefinition translate (toplevel : bool) lift translator cat env sigma c :=\n  let empty := empty translator cat lift env in\n  let (sigma, c) := otranslate env empty sigma c in\n  let ans := if toplevel then toplevel_term cat c else c in\n  (sigma, ans).\n\nDefinition translate_simple (toplevel : bool) (cat : category) (c : term) : term :=\n  let (_, c_) := translate toplevel None [] cat Environ.empty_env tt c in c_.\n\nDefinition translate_type (toplevel : bool) lift translator cat env sigma c :=\n  let empty := empty translator cat lift env in\n  let (sigma, c) := otranslate_type otranslate env empty sigma c in\n  let ans := if toplevel then tProd pos_name Relevant cat.(cat_obj) c else c in\n  (sigma, ans).\n\nDefinition translate_type_simple (toplevel : bool) (cat : category) (c : term) : term :=\n  let (_, c_) := translate_type toplevel None [] cat Environ.empty_env tt c in c_.\n\n\nDefinition otranslate_context (env : Environ.env) (fctx : forcing_context)\n           (sigma : evar_map) (ctx : context)\n  : evar_map * context :=\n  let fold (a : context_decl) (b : evar_map * forcing_context * context) :=\n      match b with\n       (sigma, fctx, ctx_) =>\n       let (sigma, body_) := match a.(decl_body) with\n                             | None => (sigma, None)\n                             | Some _ => (sigma, Some (tVar (\"something went wrong\")))\n                             end\n       in\n       let (ext, tfctx) := extend env fctx in\n       let (sigma, t_) := otranslate_type otranslate env tfctx sigma a.(decl_type) in\n       let t_ := it_mkProd_or_LetIn t_ ext in\n       let decl_ := Build_context_decl a.(decl_name) a.(decl_relevance) body_ t_ in\n       let fctx := add_variable fctx in\n       (sigma, fctx, decl_ :: ctx_)\n      end\n  in\n  match (List.fold_right fold (sigma, fctx, []) ctx) with\n    (sigma, _, ctx_) => (sigma, ctx_)\n  end.\n\nDefinition toplevel_context (cat : category) (ctx : context) : context :=\n  Build_context_decl pos_name Relevant None cat.(cat_obj) :: ctx.\n\nDefinition translate_context (toplevel : bool) (lift : option nat)\n           (translator : tsl_table) (cat : category)\n           (env : Environ.env) (sigma : evar_map) (ctx : context)\n  : evar_map * context :=\n  let empty := empty translator cat lift env in\n  let (sigma, ctx_) := otranslate_context env empty sigma ctx in\n  let ctx__ := if toplevel then  toplevel_context cat ctx_ else ctx_ in\n  (sigma, ctx__).\n\nDefinition translate_context_simple (toplevel : bool) (cat : category) (ctx : context) : context :=\n  let (_, c_) := translate_context toplevel None [] cat Environ.empty_env tt ctx in c_.\n\n(* A bridge to the monadic translation utils *)\n\nDefinition f_translate (cat : category) (tsl_ctx : tsl_context) (trm : term)\n  : tsl_result term :=\n  Success (snd (translate true None\n                          (snd tsl_ctx)\n                          cat\n                          ({| Environ.env_globals := (fst (fst tsl_ctx)) |})\n                          tt\n                          trm)).\n\nDefinition f_translate_type (cat : category) (tsl_ctx : tsl_context) (trm : term)\n  : tsl_result term :=\n  Success (snd (translate_type true None\n                               (snd tsl_ctx)\n                               cat\n                               ({| Environ.env_globals := (fst (fst tsl_ctx)) |})\n                               tt\n                               trm)).\n\nDefinition ForcingTranslation (cat : category) : Translation :=\n  {| tsl_id := tsl_ident;\n     tsl_tm := f_translate cat;\n     tsl_ty := f_translate_type cat;\n     tsl_ind := fun _ _ _ _ => Error TranslationNotHandeled;\n     (* tsl_context -> kername -> kername -> mutual_inductive_body *)\n     (*             -> tsl_result (tsl_table * list mutual_inductive_body) *)\n  |}.\n\nDefinition add_translation (ctx : tsl_context) (e : global_reference * term): tsl_context :=\n  let (Σ, E) := ctx in\n  (Σ, e :: E).\n", "meta": {"author": "loic-p", "repo": "cubical_forcing", "sha": "3c606c3e5f2cb85a397dc13851fc43ace816b4a1", "save_path": "github-repos/coq/loic-p-cubical_forcing", "path": "github-repos/coq/loic-p-cubical_forcing/cubical_forcing-3c606c3e5f2cb85a397dc13851fc43ace816b4a1/forcing/TemplateForcing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22936225321083056}}
{"text": "Require Import Utils.\nRequire Import String.\nRequire Import JsNumber.\nOpen Scope list_scope.\nModule Heap := HeapUtils.Heap.\n\n\n\n\nRequire Import Syntax.\n\n\n(* LambdaJS values and objects *)\n\n\n\n(* Some vocabulary:\n* All of LambdaJS data is passed as value location (think of locations as\n* pointers), so there is an heap mapping locations to values, and optionnally\n* another one mapping names to locations.\n* Moreover, objects are mutable values. To emulate mutability with Coq, we\n* represent objects as pointer values, and the pointer is used to fetch\n* them from the objects heap. *)\n\n\n(****** Basic stuff ******)\n\nDefinition id := string.\nDefinition closure_id := nat.\nDefinition value_loc := nat.\nDefinition object_ptr := nat.\n\nDefinition loc_heap_type := Heap.heap id value_loc.\n\n(****** Objects ******)\n\n(* (The code in this section comes mostly from JSCert.) *)\n\n(* Named data property attributes *)\nRecord attributes_data := attributes_data_intro {\n   attributes_data_value : value_loc;\n   attributes_data_writable : bool;\n   attributes_data_enumerable : bool;\n   attributes_data_configurable : bool }.\n\n(* Named accessor property attributes *)\nRecord attributes_accessor := attributes_accessor_intro {\n   attributes_accessor_get : value_loc;\n   attributes_accessor_set : value_loc;\n   attributes_accessor_enumerable : bool;\n   attributes_accessor_configurable : bool }.\n\n(* Property attributes *)\nInductive attributes :=\n  | attributes_data_of : attributes_data -> attributes\n  | attributes_accessor_of : attributes_accessor -> attributes.\n\n\nDefinition prop_name := string.\nDefinition class_name := string.\nDefinition object_properties := Heap.heap prop_name attributes.\n\nRecord object := object_intro {\n   object_proto : value_loc;\n   object_class : class_name;\n   object_extensible : bool;\n   object_prim_value : option value_loc;\n   object_properties_ : object_properties;\n   object_code : option value_loc }.\n\nFixpoint name_in_list (name : prop_name) (names : list prop_name) : bool :=\n  match names with\n  | nil => false\n  | hd :: tl =>\n    if (decide(name = hd)) then\n      true\n    else\n      name_in_list name tl\n  end\n.\n\nDefinition get_object_property (object : object) (name : prop_name) : option attributes :=\n  Heap.read_option (object_properties_ object) name\n.\nDefinition set_object_property (obj : object) (name : prop_name) (attrs : attributes) : object :=\n  match obj with (object_intro p c e p' props code) =>\n    let props2 := Heap.write props name attrs in\n    object_intro p c e p' props2 code\n  end\n.\n\n(******* Finally, values. *******)\n\nInductive value : Type :=\n| Null\n| Undefined\n| Number : Syntax.number -> value\n| String : string -> value\n| True\n| False\n| Object : object_ptr -> value\n| Closure : closure_id -> loc_heap_type -> list id -> Syntax.expression -> value (* closure_id is for making closures comparable with stx= *)\n.\n\n", "meta": {"author": "progval", "repo": "LambdaCert", "sha": "138f258fb397e7733426dcb90e70ecbde9c6d161", "save_path": "github-repos/coq/progval-LambdaCert", "path": "github-repos/coq/progval-LambdaCert/LambdaCert-138f258fb397e7733426dcb90e70ecbde9c6d161/LambdaS5/coq/Values.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.2290882247135855}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Bool.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import ZArith NArith Nnat Ndec Ndigits.\nFrom IntMap Require Import Map.\nFrom IntMap Require Import Allmaps.\nRequire Import Wf_nat.\nRequire Import EqNat.\nRequire Import Peano_dec.\nRequire Import Ensembles.\nRequire Import Finite_sets.\nRequire Import Finite_sets_facts.\nRequire Import Image.\nRequire Import List.\nRequire Import Compare.\n \nRequire Import misc.\nRequire Import bool_fun.\nRequire Import myMap.\nRequire Import config.\nRequire Import alloc.\nRequire Import make.\nRequire Import neg.\nRequire Import or.\nRequire Import univ.\nRequire Import op.\nRequire Import tauto.\nRequire Import quant.\nRequire Import gc.\nRequire Import mu.\n\nSection New.\n\nVariable N : nat.\n\nDefinition var_env'_dash (ve : var_env') (n : nat) :=\n  if leb N n then ve (n - N) else false.\n\nDefinition var_env''_dash (ve : var_env'') :=\n  var_env'_to_env'' N (2 * N) (var_env'_dash (var_env''_to_env' ve)).\n \nFixpoint be_dash (be : bool_expr) : bool_expr :=\n  match be with\n  | Zero => Zero\n  | One => One\n  | Var x => Var (N_of_nat (N + nat_of_N x))\n  | Neg be' => Neg (be_dash be')\n  | Or be1 be2 => Or (be_dash be1) (be_dash be2)\n  | ANd be1 be2 => ANd (be_dash be1) (be_dash be2)\n  | Impl be1 be2 => Impl (be_dash be1) (be_dash be2)\n  | Iff be1 be2 => Iff (be_dash be1) (be_dash be2)\n  end.\n \nFixpoint renamef (f : ad -> ad) (be : bool_expr) {struct be} : bool_expr :=\n  match be with\n  | Zero => Zero\n  | One => One\n  | Var x => Var (f x)\n  | Neg be' => Neg (renamef f be')\n  | Or be1 be2 => Or (renamef f be1) (renamef f be2)\n  | ANd be1 be2 => ANd (renamef f be1) (renamef f be2)\n  | Impl be1 be2 => Impl (renamef f be1) (renamef f be2)\n  | Iff be1 be2 => Iff (renamef f be1) (renamef f be2)\n  end.\n\nDefinition renfnat (n m : nat) := if leb n m then m else m + N.\n\nDefinition renfnad (n : nat) (x : ad) := N_of_nat (renfnat n (nat_of_N x)). \n\nLemma dash_renf :\n forall be : bool_expr,\n be_ok (var_lu 0 N) be -> be_dash be = renamef (renfnad N) be.\nProof.\n  simple induction be.  reflexivity.  reflexivity.  unfold renamef in |- *.  simpl in |- *.\n  unfold renfnad in |- *.  unfold renfnat in |- *.  intros.  elim (var_ok_inv _ _ H).\n  cut (var_lu 0 N b = true).  intro.  unfold var_lu in H0.\n  elim (andb_prop _ _ H0).  intros.\n  replace (leb N (nat_of_N b)) with false.\n  rewrite (plus_comm N (nat_of_N b)).  reflexivity.  symmetry  in |- *.\n  apply leb_correct_conv.  unfold lt in |- *.  apply leb_complete.  assumption.  \n  apply var_ok_inv.  assumption.  intros.  simpl in |- *.  rewrite H.  reflexivity.  \n  apply neg_ok_inv.  assumption.  intros.  simpl in |- *.  rewrite H.  rewrite H0.\n  reflexivity.  exact (proj2 (or_ok_inv _ _ _ H1)).  \n  exact (proj1 (or_ok_inv _ _ _ H1)).  intros.  simpl in |- *.  rewrite H.\n  rewrite H0.  reflexivity.  exact (proj2 (and_ok_inv _ _ _ H1)).  \n  exact (proj1 (and_ok_inv _ _ _ H1)).  intros.  simpl in |- *.  rewrite H.\n  rewrite H0.  reflexivity.  exact (proj2 (impl_ok_inv _ _ _ H1)).  \n  exact (proj1 (impl_ok_inv _ _ _ H1)).  intros.  simpl in |- *.  rewrite H.\n  rewrite H0.  reflexivity.  exact (proj2 (iff_ok_inv _ _ _ H1)).  \n  exact (proj1 (iff_ok_inv _ _ _ H1)).\nQed.\n\nLemma dash_be_ok :\n forall be : bool_expr,\n be_ok (var_lu 0 N) be -> be_ok (var_lu N (2 * N)) (be_dash be).\nProof.\n  simple induction be.  intro.  apply zero_ok.  intro.  apply one_ok.  intros.  simpl in |- *.\n  apply var_ok.  inversion H.  unfold var_lu in H1.  elim (andb_prop _ _ H1).\n  intros.  unfold var_lu in |- *.  apply andb_true_intro.  split.\n  rewrite (nat_of_N_of_nat (N + nat_of_N b)).  apply leb_correct.\n  apply le_plus_l.  rewrite (nat_of_N_of_nat (N + nat_of_N b)).\n  replace (S (N + nat_of_N b)) with (S N + nat_of_N b).\n  rewrite (plus_Snm_nSm N (nat_of_N b)).  apply leb_correct.\n  apply plus_le_compat.  apply le_n.  rewrite <- (plus_n_O N).\n  apply leb_complete.  assumption.  simpl in |- *.  reflexivity.  simpl in |- *.  intros.\n  inversion H0.  apply neg_ok.  apply H.  assumption.  simpl in |- *.  intros.\n  inversion H1.  apply or_ok; [ apply H; assumption | apply H0; assumption ].\n  simpl in |- *.  intros.  inversion H1.\n  apply and_ok; [ apply H; assumption | apply H0; assumption ].  simpl in |- *.  intros.\n  inversion H1.  apply impl_ok; [ apply H; assumption | apply H0; assumption ].\n  simpl in |- *.  intros.  inversion H1.\n  apply iff_ok; [ apply H; assumption | apply H0; assumption ].\nQed.\n\nLemma eval_dash_lemma1 :\n forall (be : bool_expr) (ve : var_env'),\n eval_be' be ve = eval_be' (be_dash be) (var_env'_dash ve).\nProof.\n  simple induction be.  unfold eval_be' in |- *.  simpl in |- *.  unfold bool_fun_zero in |- *.  reflexivity.\n  unfold eval_be' in |- *.  simpl in |- *.  unfold bool_fun_one in |- *.  reflexivity.  simpl in |- *.\n  unfold eval_be' in |- *.  simpl in |- *.  unfold bool_fun_var in |- *.  unfold var_env'_dash in |- *.\n  unfold var_env'_to_env in |- *.  intros.\n  rewrite (nat_of_N_of_nat (N + nat_of_N b)).\n  elim (sumbool_of_bool (leb N (N + nat_of_N b))).  intro y.  rewrite y.\n  rewrite (minus_plus N (nat_of_N b)).  reflexivity.\n  replace (leb N (N + nat_of_N b)) with true.  intro.  discriminate.  \n  symmetry  in |- *.  apply leb_correct.  apply le_plus_l.  intros.  simpl in |- *.\n  unfold eval_be' in |- *.  unfold eval_be' in H.  simpl in |- *.  unfold bool_fun_neg in |- *.\n  rewrite (H ve).  reflexivity.  unfold eval_be' in |- *.  simpl in |- *.  unfold bool_fun_or in |- *.\n  intros.  rewrite (H ve).  rewrite (H0 ve).  reflexivity.  unfold eval_be' in |- *.\n  simpl in |- *.  unfold bool_fun_and in |- *.  intros.  rewrite (H ve).  rewrite (H0 ve).\n  reflexivity.  unfold eval_be' in |- *.  simpl in |- *.  unfold bool_fun_impl in |- *.  intros.\n  rewrite (H ve).  rewrite (H0 ve).  reflexivity.  unfold eval_be' in |- *.  simpl in |- *.\n  unfold bool_fun_iff in |- *.  intros.  rewrite (H ve).  rewrite (H0 ve).  reflexivity.\nQed.\n \nDefinition var_env_or (ve1 ve2 : var_env) (x : ad) := ve1 x || ve2 x.\nDefinition var_env'_or (ve1 ve2 : var_env') (x : nat) := ve1 x || ve2 x.\n \nLemma forall_lemma1 :\n forall (be : bool_expr) (ve : var_env) (a : ad),\n bool_fun_of_bool_expr (forall_ a be) ve = true ->\n bool_fun_of_bool_expr be ve = true.\nProof.\n  intros.  rewrite (forall_OK a be ve) in H.  unfold bool_fun_forall in H.\n  unfold bool_fun_and in H.  elim (andb_prop _ _ H).  intros.\n  elim (sumbool_of_bool (ve a)).  intro y.  rewrite <- H0.\n  unfold bool_fun_restrict in |- *.  apply (bool_fun_of_be_ext be).  intros.\n  unfold augment in |- *.  elim (sumbool_of_bool (Neqb a x)).  intro y0.  rewrite y0.\n  rewrite (Neqb_complete _ _ y0) in y.  assumption.  intro y0.  rewrite y0.\n  reflexivity.  intro y.  rewrite <- H1.  unfold bool_fun_restrict in |- *.\n  apply (bool_fun_of_be_ext be).  intros.  unfold augment in |- *.\n  elim (sumbool_of_bool (Neqb a x)).  intro y0.  rewrite y0.\n  rewrite (Neqb_complete _ _ y0) in y.  assumption.  intro y0.  rewrite y0.\n  reflexivity.\nQed.\n\nLemma renamef_ext :\n forall (be : bool_expr) (f g : ad -> ad),\n (forall x : ad, f x = g x) -> renamef f be = renamef g be.\nProof.\n  simple induction be.  reflexivity.  reflexivity.  simpl in |- *.  intros.  rewrite (H b).\n  reflexivity.  intros.  simpl in |- *.  rewrite (H _ _ H0).  reflexivity.  intros.\n  simpl in |- *.  rewrite (H _ _ H1).  rewrite (H0 _ _ H1).  reflexivity.  intros.\n  simpl in |- *.  rewrite (H _ _ H1).  rewrite (H0 _ _ H1).  reflexivity.  intros.\n  simpl in |- *.  rewrite (H _ _ H1).  rewrite (H0 _ _ H1).  reflexivity.  intros.\n  simpl in |- *.  rewrite (H _ _ H1).  rewrite (H0 _ _ H1).  reflexivity.\nQed.\n\nLemma renamef_id : forall be : bool_expr, renamef (fun x => x) be = be.\nProof.\n  simple induction be.  reflexivity.  reflexivity.  reflexivity.  intros.  simpl in |- *.\n  rewrite H.  reflexivity.  intros.  simpl in |- *.  rewrite H.  rewrite H0.\n  reflexivity.  intros.  simpl in |- *.  rewrite H.  rewrite H0.  reflexivity.  intros.\n  simpl in |- *.  rewrite H.  rewrite H0.  reflexivity.  intros.  simpl in |- *.  rewrite H.\n  rewrite H0.  reflexivity.\nQed.\n\nLemma renamefS :\n forall (be : bool_expr) (n : nat),\n n < N ->\n renamef (renfnad (S n)) be =\n subst (ap n) (Var (ap' N n)) (renamef (renfnad n) be).\nProof.\n  simple induction be.  simpl in |- *.  reflexivity.  reflexivity.  intros.  simpl in |- *.\n  unfold renfnad at 2 in |- *.  unfold renfnat in |- *.\n  elim (sumbool_of_bool (leb n (nat_of_N b))).  intro y.  rewrite y.\n  rewrite (N_of_nat_of_N b).  unfold ap in |- *.\n  elim (sumbool_of_bool (Neqb (N_of_nat n) b)).  intro y0.  rewrite y0.\n  unfold renfnad, ap' in |- *.  unfold renfnat in |- *.  rewrite <- (Neqb_complete _ _ y0).\n  rewrite (nat_of_N_of_nat n).  replace (leb (S n) n) with false.\n  rewrite (plus_comm n N).  reflexivity.  symmetry  in |- *.  apply leb_correct_conv.\n  auto.  intro y0.  rewrite y0.  unfold renfnad in |- *.  unfold renfnat in |- *.  rewrite y.\n  rewrite (N_of_nat_of_N b).  replace (leb (S n) (nat_of_N b)) with true.\n  rewrite (N_of_nat_of_N b).  reflexivity.  symmetry  in |- *.\n  elim (le_le_S_eq _ _ (leb_complete _ _ y)).  intro.  apply leb_correct.\n  assumption.  intro.  rewrite H0 in y0.  rewrite (N_of_nat_of_N b) in y0.\n  rewrite (Neqb_correct b) in y0.  discriminate.  intro y.  rewrite y.\n  unfold renfnad at 1 in |- *.  unfold renfnat at 1 in |- *.\n  replace (leb (S n) (nat_of_N b)) with false.\n  replace (Neqb (ap n) (N_of_nat (nat_of_N b + N))) with false.\n  unfold renfnad in |- *.  unfold renfnat in |- *.  rewrite y.  reflexivity.  symmetry  in |- *.\n  apply not_true_is_false.  unfold not in |- *; intro.  unfold ap in H0.\n  rewrite <- (nat_of_N_of_nat n) in H.\n  rewrite (Neqb_complete _ _ H0) in H.\n  rewrite (nat_of_N_of_nat (nat_of_N b + N)) in H.  apply (lt_irrefl N).\n  apply le_lt_trans with (m := nat_of_N b + N).  apply le_plus_r.\n  assumption.  symmetry  in |- *.  apply not_true_is_false.  unfold not in |- *; intro.\n  cut (leb n (nat_of_N b) = true).  intro.  rewrite H1 in y.  discriminate.\n  apply leb_correct.  apply le_trans with (m := S n).  apply le_S.  apply le_n.  apply leb_complete.  assumption.  intros.  simpl in |- *.  rewrite (H n H0).\n  reflexivity.  intros.  simpl in |- *.  rewrite (H n H1).  rewrite (H0 n H1).\n  reflexivity.  intros.  simpl in |- *.  rewrite (H n H1).  rewrite (H0 n H1).\n  reflexivity.  intros.  simpl in |- *.  rewrite (H n H1).  rewrite (H0 n H1).\n  reflexivity.  intros.  simpl in |- *.  rewrite (H n H1).  rewrite (H0 n H1).\n  reflexivity.\nQed.\n\nLemma replacel_lemma :\n forall (n : nat) (be : bool_expr),\n n <= N -> replacel be (lx_1 n) (lx'_1 N n) = renamef (renfnad n) be.\nProof.\n  simple induction n.  simpl in |- *.  unfold renfnad in |- *.  unfold renfnat in |- *.  intro.  intro.\n  replace\n   (renamef\n      (fun x : ad =>\n       N_of_nat\n         match leb 0 (nat_of_N x) with\n         | true => nat_of_N x\n         | false => nat_of_N x + N\n         end) be) with (renamef (fun x => x) be).\n  symmetry  in |- *.  apply renamef_id.  apply renamef_ext.  intro.\n  rewrite (leb_correct 0 (nat_of_N x) (le_O_n _)).  symmetry  in |- *.\n  apply N_of_nat_of_N.  simpl in |- *.  intros.  rewrite (H be).  unfold replace in |- *.\n  symmetry  in |- *.  unfold replace in |- *.  apply renamefS.  assumption.\n  apply le_trans with (m := S n0).  apply le_S.  apply le_n.  assumption.\nQed.\n\nLemma replacel_lemma2 :\n forall be : bool_expr,\n be_ok (var_lu 0 N) be -> replacel be (lx N) (lx' N) = be_dash be.\nProof.\n  intros.  unfold lx, lx' in |- *.  rewrite (replacel_lemma N be (le_n _)).  symmetry  in |- *.\n  apply dash_renf.  assumption.\nQed.\n\nLemma exl_semantics :\n forall (lx : list ad) (be : bool_expr) (ve : var_env'),\n (forall n : nat, ve n = true -> ~ In (N_of_nat n) lx) ->\n no_dup_list _ lx ->\n (eval_be' (exl be lx) ve = true <->\n  (exists ve' : var_env',\n     (forall n : nat, ve' n = true -> In (N_of_nat n) lx) /\\\n     eval_be' be (var_env'_or ve ve') = true)).\nProof.\n  simple induction lx.  simpl in |- *.  intros be ve H H00.  split.  intro.\n  split with (fun n : nat => false).  split.  intros.  discriminate.  unfold var_env'_or in |- *.\n  rewrite <- H0.  unfold eval_be' in |- *.  apply (bool_fun_of_be_ext be).\n  unfold var_env'_to_env in |- *.  intro.  elim (ve (nat_of_N x)); reflexivity.  \n  intros.  elim H0; clear H0.  intros ve' H0.  inversion H0.  clear H0.\n  rewrite <- H2.  unfold eval_be' in |- *.  apply (bool_fun_of_be_ext be).\n  unfold var_env'_to_env in |- *.  unfold var_env'_or in |- *.  intro.\n  replace (ve' (nat_of_N x)) with false.  elim (ve (nat_of_N x)); reflexivity.\n  symmetry  in |- *.  apply not_true_is_false.  unfold not in |- *; intro.  exact (H1 _ H0).  \n  intros a l H be ve H0 H00.  split.  intros.  simpl in H1.\n  unfold eval_be' in H1.\n  rewrite (ex_OK a (exl be l) (var_env'_to_env ve)) in H1.\n  unfold bool_fun_ex in H1.  unfold bool_fun_or in H1.\n  unfold bool_fun_restrict in H1.  elim (orb_prop _ _ H1); clear H1; intros.\n  elim\n   (H be\n      (fun n : nat =>\n       match Neqb (N_of_nat n) a with\n       | true => true\n       | false => ve n\n       end)).\n  intros.  clear H3.  elim H2.  intros ve' H3.  inversion H3.  clear H3.\n  split\n   with\n     (fun n : nat =>\n      match Neqb (N_of_nat n) a with\n      | true => true\n      | false => ve' n\n      end).\n  split.  intros.  elim (sumbool_of_bool (Neqb (N_of_nat n) a)).  intro y.\n  rewrite <- (Neqb_complete _ _ y).  left.  reflexivity.  intro y.\n  rewrite y in H3.  right.  apply H4; assumption.  \n  replace\n   (eval_be' be\n      (var_env'_or ve\n         (fun n : nat =>\n          match Neqb (N_of_nat n) a with\n          | true => true\n          | false => ve' n\n          end))) with\n   (eval_be' be\n      (var_env'_or\n         (fun n : nat =>\n          match Neqb (N_of_nat n) a with\n          | true => true\n          | false => ve n\n          end) ve')).\n  assumption.  unfold eval_be', var_env'_or in |- *.  apply (bool_fun_of_be_ext be).\n  unfold var_env'_to_env in |- *.  intro.  rewrite (N_of_nat_of_N x).\n  elim (Neqb x a).  auto with bool.  auto with bool.  unfold eval_be' in |- *.\n  replace\n   (bool_fun_of_bool_expr (exl be l)\n      (var_env'_to_env\n         (fun n : nat =>\n          match Neqb (N_of_nat n) a with\n          | true => true\n          | false => ve n\n          end))) with\n   (bool_fun_of_bool_expr (exl be l) (augment (var_env'_to_env ve) a true)).\n  assumption.  apply (bool_fun_of_be_ext (exl be l)).\n  unfold augment, var_env'_to_env in |- *.  intro.  rewrite (N_of_nat_of_N x).\n  rewrite (Neqb_comm a x).  reflexivity.  intros.\n  elim (sumbool_of_bool (Neqb (N_of_nat n) a)).  intro y.\n  rewrite (Neqb_complete _ _ y).  apply no_dup_cons_no_in.  assumption.  intro y.\n  rewrite y in H2.  simpl in H0.  exact (fun x => H0 _ H2 (or_intror _ x)).  \n  apply no_dup_cons_no_dup with (a := a).  assumption.  \n  elim\n   (H be\n      (fun n : nat =>\n       match Neqb (N_of_nat n) a with\n       | true => false\n       | false => ve n\n       end)).\n  intros.  clear H3 H.  elim H2.  intros ve' H.  inversion H.  clear H.\n  clear H2.  split with ve'.  split.  intros.  right.  apply H3.  assumption.\n  rewrite <- H4.  unfold eval_be' in |- *.  apply (bool_fun_of_be_ext be).\n  unfold var_env'_to_env, var_env'_or in |- *.  intro.  rewrite (N_of_nat_of_N x).\n  elim (sumbool_of_bool (Neqb x a)).  intro y.  rewrite y.  simpl in |- *.\n  rewrite (Neqb_complete _ _ y).  elim (sumbool_of_bool (ve (nat_of_N a))).\n  intro y0.  elim (H0 _ y0).  rewrite (N_of_nat_of_N a).  left.  reflexivity.  \n  intro y0.  rewrite y0.  reflexivity.  intro y.  rewrite y.  reflexivity.  \n  rewrite <- H1.  unfold eval_be' in |- *.  apply (bool_fun_of_be_ext (exl be l)).\n  unfold var_env'_to_env, augment in |- *.  intro.  rewrite (N_of_nat_of_N x).\n  rewrite (Neqb_comm a x).  reflexivity.  intros.\n  elim (sumbool_of_bool (Neqb (N_of_nat n) a)).  intro y.\n  rewrite (Neqb_complete _ _ y).  apply no_dup_cons_no_in.  assumption.  intro y.\n  rewrite y in H2.  exact (fun x => H0 _ H2 (or_intror _ x)).  \n  apply no_dup_cons_no_dup with (a := a).  assumption.  intros.  elim H1; clear H1.\n  intros ve' H1.  inversion H1.  clear H1.  simpl in |- *.  unfold eval_be' in |- *.\n  rewrite (ex_OK a (exl be l) (var_env'_to_env ve)).  unfold bool_fun_ex in |- *.\n  unfold bool_fun_or in |- *.  unfold bool_fun_restrict in |- *.\n  elim (sumbool_of_bool (ve' (nat_of_N a))).  intro y.\n  elim\n   (H be\n      (fun n : nat =>\n       match Neqb (N_of_nat n) a with\n       | true => true\n       | false => ve n\n       end)).\n  intros.  clear H1 H.  apply orb_true_intro.  left.\n  replace\n   (bool_fun_of_bool_expr (exl be l) (augment (var_env'_to_env ve) a true))\n   with\n   (eval_be' (exl be l)\n      (fun n : nat =>\n       match Neqb (N_of_nat n) a with\n       | true => true\n       | false => ve n\n       end)).\n  apply H4.  split\n   with\n     (fun n : nat =>\n      match Neqb (N_of_nat n) a with\n      | true => false\n      | false => ve' n\n      end).\n  split.  intros.  elim (sumbool_of_bool (Neqb (N_of_nat n) a)).  intro y0.\n  rewrite y0 in H.  discriminate.  intro y0.  rewrite y0 in H.  elim (H2 _ H).\n  intro.  rewrite <- H1 in y0.  rewrite (Neqb_correct a) in y0.  discriminate.\n  auto.  replace\n   (eval_be' be\n      (var_env'_or\n         (fun n : nat =>\n          match Neqb (N_of_nat n) a with\n          | true => true\n          | false => ve n\n          end)\n         (fun n : nat =>\n          match Neqb (N_of_nat n) a with\n          | true => false\n          | false => ve' n\n          end))) with (eval_be' be (var_env'_or ve ve')).\n  assumption.  unfold eval_be' in |- *.  apply (bool_fun_of_be_ext be).  intro x.\n  unfold var_env'_to_env, var_env'_or in |- *.  rewrite (N_of_nat_of_N x).\n  elim (sumbool_of_bool (Neqb x a)).  intro y0.  rewrite y0.\n  rewrite (Neqb_complete _ _ y0).  rewrite y.  auto with bool.  intro y0.\n  rewrite y0.  reflexivity.  unfold eval_be' in |- *.\n  apply (bool_fun_of_be_ext (exl be l)).  unfold var_env'_to_env, augment in |- *.\n  intros.  rewrite (N_of_nat_of_N x).  rewrite (Neqb_comm a x).  reflexivity.\n  intros.  elim (sumbool_of_bool (Neqb (N_of_nat n) a)).  intro y0.\n  rewrite (Neqb_complete _ _ y0).  apply no_dup_cons_no_in.  assumption.\n  intro y0.  rewrite y0 in H1.  exact (fun x => H0 _ H1 (or_intror _ x)).  \n  apply no_dup_cons_no_dup with (a := a).  assumption.  intro y.  elim (H be ve).\n  intros.  clear H H1.  apply orb_true_intro.  right.  rewrite <- H4.\n  unfold eval_be' in |- *.  apply (bool_fun_of_be_ext (exl be l)).\n  unfold augment, var_env'_to_env in |- *.  intro.  elim (sumbool_of_bool (Neqb a x)).\n  intro y0.  rewrite y0.  symmetry  in |- *.  rewrite <- (Neqb_complete _ _ y0).\n  apply not_true_is_false.  unfold not in |- *; intro.  apply (H0 _ H).  left.\n  symmetry  in |- *.  apply N_of_nat_of_N.  intro y0.  rewrite y0.  reflexivity.\n  split with ve'.  split.  intros.  elim (H2 _ H).  intro.  rewrite H1 in y.\n  rewrite (nat_of_N_of_nat n) in y.  rewrite H in y.  discriminate.  auto.  \n  assumption.  intros.  exact (fun x => H0 _ H1 (or_intror _ x)).  \n  apply no_dup_cons_no_dup with (a := a).  assumption.  \nQed.\n\nLemma univl_semantics :\n forall (lx : list ad) (be : bool_expr) (ve : var_env'),\n (forall n : nat, ve n = true -> ~ In (N_of_nat n) lx) ->\n no_dup_list _ lx ->\n (eval_be' (univl be lx) ve = true <->\n  (forall ve' : var_env',\n   (forall n : nat, ve' n = true -> In (N_of_nat n) lx) ->\n   eval_be' be (var_env'_or ve ve') = true)).\nProof.\n  simple induction lx.  simpl in |- *.  intros be ve H H00.  intros.  split.  intro.  intros.\n  unfold eval_be' in |- *.\n  replace (bool_fun_of_bool_expr be (var_env'_to_env (var_env'_or ve ve')))\n   with (bool_fun_of_bool_expr be (var_env'_to_env ve)).\n  assumption.  apply (bool_fun_of_be_ext be).  intros.  unfold var_env'_or in |- *.\n  unfold var_env'_to_env in |- *.  replace (ve' (nat_of_N x)) with false.\n  elim (ve (nat_of_N x)); reflexivity.  symmetry  in |- *.  apply not_true_is_false.\n  unfold not in |- *; intro.  exact (H1 _ H2).  intros.\n  replace (eval_be' be ve) with\n   (eval_be' be (var_env'_or ve (fun n => false))).\n  apply H0.  intros.  discriminate.  unfold eval_be' in |- *.\n  apply (bool_fun_of_be_ext be).  intro.  unfold var_env'_to_env in |- *.\n  unfold var_env'_or in |- *.  elim (ve (nat_of_N x)); reflexivity.  simpl in |- *.\n  intros a l H be ve H0 H00.  intros.  split.  intros.  unfold eval_be' in H1.\n  elim (sumbool_of_bool (ve' (nat_of_N a))).  intro y.\n  rewrite (forall_OK a (univl be l) (var_env'_to_env ve)) in H1.\n  unfold bool_fun_forall in H1.  unfold bool_fun_and in H1.\n  elim (andb_prop _ _ H1).  intros.  clear H1.  clear H4.\n  unfold bool_fun_restrict in H3.\n  replace (eval_be' be (var_env'_or ve ve')) with\n   (eval_be' be\n      (var_env'_or\n         (fun n : nat =>\n          match Neqb (N_of_nat n) a with\n          | true => true\n          | false => ve n\n          end)\n         (fun n : nat =>\n          match Neqb (N_of_nat n) a with\n          | true => false\n          | false => ve' n\n          end))).\n  elim\n   (H be\n      (fun n : nat =>\n       match Neqb (N_of_nat n) a with\n       | true => true\n       | false => ve n\n       end)).\n  intros.  clear H4.  apply H1.  unfold augment in H3.  unfold eval_be' in |- *.\n  replace\n   (bool_fun_of_bool_expr (univl be l)\n      (var_env'_to_env\n         (fun n : nat =>\n          match Neqb (N_of_nat n) a with\n          | true => true\n          | false => ve n\n          end))) with\n   (bool_fun_of_bool_expr (univl be l)\n      (fun y : BDDvar =>\n       match Neqb a y with\n       | true => true\n       | false => var_env'_to_env ve y\n       end)).\n  assumption.  apply (bool_fun_of_be_ext (univl be l)).  intros.\n  unfold var_env'_to_env in |- *.  rewrite (N_of_nat_of_N x).\n  rewrite (Neqb_comm a x).  reflexivity.  intros.\n  elim (sumbool_of_bool (Neqb (N_of_nat n) a)).  intro y0.  rewrite y0 in H4.\n  discriminate.  intro y0.  rewrite y0 in H4.  elim (H2 _ H4).  intro.\n  rewrite <- H5 in y0.  rewrite (Neqb_correct a) in y0.  discriminate.\n  trivial.  intros.  elim (sumbool_of_bool (Neqb (N_of_nat n) a)).  intro y0.\n  apply no_dup_cons_no_in.  rewrite (Neqb_complete _ _ y0).  assumption.  \n  intro y0.  rewrite y0 in H1.  unfold not in |- *; intro.  apply (H0 _ H1).  auto.  \n  apply no_dup_cons_no_dup with (a := a).  assumption.  unfold eval_be' in |- *.\n  apply (bool_fun_of_be_ext be).  intros.  unfold var_env'_to_env, var_env'_or in |- *.\n  rewrite (N_of_nat_of_N x).  elim (sumbool_of_bool (Neqb x a)).  intro y0.\n  rewrite y0.  simpl in |- *.  rewrite (Neqb_complete _ _ y0).  rewrite y.\n  auto with bool.  intro y0.  rewrite y0.  reflexivity.  intro y.  elim (H be ve).\n  intros.  clear H4.  apply H3.  unfold eval_be' in |- *.\n  apply forall_lemma1 with (a := a).  assumption.  intros.  elim (H2 _ H4).  intro.\n  rewrite H5 in y.  rewrite (nat_of_N_of_nat n) in y.  rewrite y in H4.\n  discriminate.  auto.  intros.  unfold not in |- *; intro.  apply (H0 _ H3).  auto.\n  apply no_dup_cons_no_dup with (a := a).  assumption.  intros.  unfold eval_be' in |- *.\n  rewrite (forall_OK a (univl be l) (var_env'_to_env ve)).\n  unfold bool_fun_forall in |- *.  unfold bool_fun_and in |- *.  apply andb_true_intro.  split.\n  unfold bool_fun_restrict in |- *.\n  elim\n   (H be\n      (fun n : nat =>\n       match Neqb (N_of_nat n) a with\n       | true => true\n       | false => ve n\n       end)).\n  intros.  clear H2.\n  replace\n   (bool_fun_of_bool_expr (univl be l) (augment (var_env'_to_env ve) a true))\n   with\n   (eval_be' (univl be l)\n      (fun n : nat =>\n       match Neqb (N_of_nat n) a with\n       | true => true\n       | false => ve n\n       end)).\n  apply H3.  intros.\n  replace\n   (eval_be' be\n      (var_env'_or\n         (fun n : nat =>\n          match Neqb (N_of_nat n) a with\n          | true => true\n          | false => ve n\n          end) ve')) with\n   (eval_be' be\n      (var_env'_or ve\n         (fun n : nat =>\n          match Neqb (N_of_nat n) a with\n          | true => true\n          | false => ve' n\n          end))).\n  apply H1.  intros.  elim (sumbool_of_bool (Neqb (N_of_nat n) a)).  intro y.\n  left.  rewrite (Neqb_complete _ _ y).  reflexivity.  intro y.\n  rewrite y in H4.  right.  apply H2.  assumption.  unfold eval_be' in |- *.\n  apply (bool_fun_of_be_ext be).  intros.  unfold var_env'_to_env, var_env'_or in |- *.\n  rewrite (N_of_nat_of_N x).  elim (sumbool_of_bool (Neqb x a)).  intro y.\n  rewrite y.  auto with bool.  intro y.  rewrite y.  reflexivity.\n  unfold eval_be' in |- *.  unfold var_env'_to_env in |- *.\n  apply (bool_fun_of_be_ext (univl be l)).  intro.  rewrite (N_of_nat_of_N x).\n  unfold augment in |- *.  rewrite (Neqb_comm a x).  reflexivity.  intros.\n  elim (sumbool_of_bool (Neqb (N_of_nat n) a)).  intro y.\n  apply no_dup_cons_no_in.  rewrite (Neqb_complete _ _ y).  assumption.  \n  intro y.  rewrite y in H2.  exact (fun x => H0 _ H2 (or_intror _ x)).  \n  apply no_dup_cons_no_dup with (a := a).  assumption.  unfold bool_fun_restrict in |- *.\n  elim (H be ve).  intros.  clear H2.\n  replace\n   (bool_fun_of_bool_expr (univl be l) (augment (var_env'_to_env ve) a false))\n   with (eval_be' (univl be l) ve).\n  apply H3.  intros.  apply H1.  intros.  auto.  unfold eval_be' in |- *.\n  apply (bool_fun_of_be_ext (univl be l)).  intro.\n  unfold var_env'_to_env, augment in |- *.  elim (sumbool_of_bool (Neqb a x)).  intro y.\n  rewrite y.  rewrite <- (Neqb_complete _ _ y).  apply not_true_is_false.\n  unfold not in |- *.  intro.  elim (H0 (nat_of_N a)).  assumption.  left.\n  rewrite (N_of_nat_of_N a).  reflexivity.  intro y.  rewrite y.  reflexivity.\n  intros.  exact (fun x => H0 _ H2 (or_intror _ x)).\n  apply no_dup_cons_no_dup with (a := a).  assumption.\nQed.\n\nLemma bool_fun_of_be_ext1 :\n forall (be : bool_expr) (ve ve' : var_env'),\n (forall x : ad,\n  be_x_free x be = true -> ve (nat_of_N x) = ve' (nat_of_N x)) ->\n eval_be' be ve = eval_be' be ve'.\nProof.\n  simple induction be.  reflexivity.  reflexivity.  intros.  simpl in H.\n  unfold eval_be' in |- *.  simpl in |- *.  unfold bool_fun_var in |- *.  unfold var_env'_to_env in |- *.\n  rewrite (H b).  reflexivity.  apply Neqb_correct.  simpl in |- *.  intros.\n  unfold eval_be' in |- *.  simpl in |- *.  unfold eval_be' in H.  unfold bool_fun_neg in |- *.\n  rewrite (H ve ve' H0).  reflexivity.  unfold eval_be' in |- *.  simpl in |- *.\n  unfold bool_fun_or in |- *.  intros.  rewrite (H ve ve').  rewrite (H0 ve ve').\n  reflexivity.  intros.  apply H1.  rewrite H2.  auto with bool.  intros.\n  apply H1.  rewrite H2.  auto with bool.  unfold eval_be' in |- *.  simpl in |- *.\n  unfold bool_fun_and in |- *.  simpl in |- *.  intros.  rewrite (H ve ve').\n  rewrite (H0 ve ve').  reflexivity.  intros.  apply H1.  rewrite H2.\n  auto with bool.  intros.  apply H1.  rewrite H2.  auto with bool.  \n  unfold eval_be' in |- *.  simpl in |- *.  unfold bool_fun_impl in |- *.  intros.  rewrite (H ve ve').\n  rewrite (H0 ve ve').  reflexivity.  intros.  apply H1.  rewrite H2.\n  auto with bool.  intros.  apply H1.  rewrite H2.  auto with bool.  \n  unfold eval_be' in |- *.  simpl in |- *.  unfold bool_fun_iff in |- *.  intros.  rewrite (H ve ve').\n  rewrite (H0 ve ve').  reflexivity.  intros.  apply H1.  rewrite H2.\n  auto with bool.  intros.  apply H1.  rewrite H2.  auto with bool.\nQed.\n\n\nLemma no_dup_lx'_1 : forall n : nat, no_dup_list _ (lx'_1 N n).\nProof.\n  simple induction n.  simpl in |- *.  apply no_dup_nil.  simpl in |- *.  intros.  apply no_dup_cons.\n  unfold not in |- *; intro.  elim (in_lx'_1_conv _ _ _ H0).  intros.\n  elim (lt_irrefl _ H2).  assumption.\nQed.\n\nLemma mu_all_eval_semantics1 :\n forall t be : bool_expr,\n be_ok (var_lu 0 N) be ->\n forall ve : var_env',\n (forall n : nat, ve n = true -> var_lu 0 N (N_of_nat n) = true) ->\n eval_be' (mu_all_eval N t be) ve = true ->\n forall ve' : var_env',\n (forall n : nat, ve' n = true -> var_lu 0 N (N_of_nat n) = true) ->\n eval_be' t (var_env'_or ve (var_env'_dash ve')) = true ->\n eval_be' be ve' = true.\nProof.\n  intros.  unfold mu_all_eval in H1.  rewrite (replacel_lemma2 be H) in H1.\n  rewrite (eval_dash_lemma1 be ve').\n  elim (univl_semantics (lx' N) (Impl t (be_dash be)) ve).  intros.  clear H5.\n  cut\n   (eval_be' (Impl t (be_dash be)) (var_env'_or ve (var_env'_dash ve')) =\n    true).\n  intro.  cut (eval_be' (be_dash be) (var_env'_or ve (var_env'_dash ve')) = true).\n  intro.  rewrite <- H6.  apply bool_fun_of_be_ext1.  intros.\n  unfold var_env'_or in |- *.  replace (ve (nat_of_N x)) with false.  reflexivity.\n  symmetry  in |- *.  apply not_true_is_false.  unfold not in |- *; intro.\n  cut (var_lu 0 N x = true).  cut (var_lu N (2 * N) x = true).  intros.\n  unfold var_lu in H9, H10.  elim (andb_prop _ _ H9).\n  elim (andb_prop _ _ H10).  intros.  apply (lt_irrefl N).\n  apply le_lt_trans with (m := nat_of_N x).  apply leb_complete; assumption.\n  unfold lt in |- *.  apply leb_complete; assumption.  \n  apply (be_ok_be_x_free (var_lu N (2 * N)) (be_dash be)).\n  apply dash_be_ok.  assumption.  assumption.  rewrite <- (N_of_nat_of_N x).\n  apply H0.  assumption.  unfold eval_be' in |- *.  unfold eval_be' in H5.  simpl in H5.\n  unfold bool_fun_impl in H5.  unfold eval_be' in H3.  rewrite H3 in H5.\n  simpl in H5.  assumption.  apply H4.  assumption.  intros.\n  unfold var_env'_dash in H5.  elim (sumbool_of_bool (leb N n)).  intro y.\n  rewrite y in H5.  apply in_lx'.  apply leb_complete; assumption.  \n  cut (var_lu 0 N (N_of_nat (n - N)) = true).  unfold var_lu in |- *.  intro.\n  elim (andb_prop _ _ H6).  intros.\n  rewrite (nat_of_N_of_nat (n - N)) in H8.  simpl in |- *.\n  rewrite <- (plus_n_O N).  replace n with (n - N + N).\n  replace (S (n - N + N)) with (S (n - N) + N).\n  apply plus_le_compat.  apply leb_complete; assumption.  apply le_n.\n  reflexivity.  rewrite (plus_comm (n - N) N).  symmetry  in |- *.\n  apply le_plus_minus.  apply leb_complete; assumption.  apply H2.\n  assumption.  intro y.  rewrite y in H5.  discriminate.  intros.\n  unfold not in |- *; intro.  unfold lx' in H5.  elim (in_lx'_1_conv N N n H5).  intro.\n  intro.  unfold var_lu in H0.  elim (andb_prop _ _ (H0 n H4)).  intros.\n  apply (lt_irrefl N).  apply le_lt_trans with (m := n).  assumption.  unfold lt in |- *.\n  rewrite (nat_of_N_of_nat n) in H9.  apply leb_complete; assumption.\n  unfold lx' in |- *.  apply no_dup_lx'_1.\nQed.\n\nLemma mu_ex_eval_semantics1 :\n forall t be : bool_expr,\n be_ok (var_lu 0 N) be ->\n forall ve : var_env',\n (forall n : nat, ve n = true -> var_lu 0 N (N_of_nat n) = true) ->\n eval_be' (mu_ex_eval N t be) ve = true ->\n exists ve' : var_env',\n   (forall n : nat, ve' n = true -> var_lu 0 N (N_of_nat n) = true) /\\\n   eval_be' t (var_env'_or ve (var_env'_dash ve')) = true /\\\n   eval_be' be ve' = true.\nProof.\n  intros.  unfold mu_ex_eval in H1.  rewrite (replacel_lemma2 be H) in H1.\n  elim (exl_semantics (lx' N) (ANd t (be_dash be)) ve).  intros.  clear H3.\n  elim (H2 H1).  intros ve' H3.  inversion H3.  clear H2 H3.\n  split with (fun n : nat => ve' (N + n)).  split.  intros.  unfold var_lu in |- *.\n  apply andb_true_intro.  rewrite (nat_of_N_of_nat n).  split.\n  apply leb_correct.  apply le_O_n.  elim (in_lx'_1_conv _ _ _ (H4 _ H2)).\n  intros.  apply leb_correct.  unfold lt in H6.\n  rewrite (Splus_nm N n) in H6.  rewrite (plus_Snm_nSm N n) in H6.\n  apply (fun p n m : nat => plus_le_reg_l n m p) with (p := N).  assumption.  unfold eval_be' in H5.\n  simpl in H5.  unfold bool_fun_and in H5.  elim (andb_prop _ _ H5).  intros.\n  split.  rewrite <- H2.  unfold eval_be' in |- *.  apply (bool_fun_of_be_ext t).\n  unfold var_env'_to_env, var_env'_or, var_env'_dash in |- *.  intros.\n  elim (sumbool_of_bool (leb N (nat_of_N x))).  intro y.  rewrite y.\n  rewrite <- (le_plus_minus N (nat_of_N x)).  reflexivity.\n  apply leb_complete; assumption.  intro y.  rewrite y.\n  replace (ve' (nat_of_N x)) with false.  reflexivity.  symmetry  in |- *.\n  apply not_true_is_false.  unfold not in |- *; intro.  unfold lx' in H4.\n  elim (in_lx'_1_conv _ _ _ (H4 _ H6)).  intros.\n  rewrite (leb_correct _ _ H7) in y; discriminate.\n  rewrite (eval_dash_lemma1 be (fun n : nat => ve' (N + n))).  rewrite <- H3.\n  fold (eval_be' (be_dash be) (var_env'_or ve ve')) in |- *.  apply bool_fun_of_be_ext1.\n  intros.  unfold var_env'_or in |- *.  unfold var_env'_dash in |- *.\n  cut (var_lu N (2 * N) x = true).  unfold var_lu in |- *.  intro.\n  elim (andb_prop _ _ H7).  intros.  rewrite H8.\n  replace (ve (nat_of_N x)) with false.  simpl in |- *.\n  rewrite <- (le_plus_minus N (nat_of_N x)).  reflexivity.\n  apply leb_complete.  assumption.  symmetry  in |- *.  apply not_true_is_false.\n  unfold not in |- *; intro.  unfold var_lu in H0.  elim (andb_prop _ _ (H0 _ H10)).\n  intros.  rewrite (N_of_nat_of_N x) in H12.  apply (lt_irrefl N).\n  apply le_lt_trans with (m := nat_of_N x).  apply leb_complete; assumption.    unfold lt in |- *.  apply leb_complete; assumption.  \n  apply be_ok_be_x_free with (be := be_dash be).  apply dash_be_ok.  assumption.  \n  assumption.  intros.  unfold lx' in |- *.  unfold not in |- *; intro.\n  elim (in_lx'_1_conv _ _ _ H3).  intros.  unfold var_lu in H0.\n  elim (andb_prop _ _ (H0 _ H2)).  rewrite (nat_of_N_of_nat n).  intros.\n  apply (lt_irrefl N).  apply le_lt_trans with (m := n).  assumption.  unfold lt in |- *.\n  apply leb_complete.  assumption.  unfold lx' in |- *.  apply no_dup_lx'_1.\nQed.\n\nLemma mu_ex_eval_semantics2 :\n forall t be : bool_expr,\n be_ok (var_lu 0 N) be ->\n forall ve : var_env',\n (forall n : nat, ve n = true -> var_lu 0 N (N_of_nat n) = true) ->\n (exists ve' : var_env',\n    (forall n : nat, ve' n = true -> var_lu 0 N (N_of_nat n) = true) /\\\n    eval_be' t (var_env'_or ve (var_env'_dash ve')) = true /\\\n    eval_be' be ve' = true) -> eval_be' (mu_ex_eval N t be) ve = true.\nProof.\n  unfold mu_ex_eval in |- *.  intros.  rewrite (replacel_lemma2 be H).  elim H1.\n  clear H1.  intros ve' H1.  inversion H1.  inversion H3.  clear H3 H1.\n  elim (exl_semantics (lx' N) (ANd t (be_dash be)) ve).  intros.  clear H1.\n  apply H3.  clear H3.  split with (var_env'_dash ve').  split.\n  unfold var_env'_dash in |- *.  intros.  elim (sumbool_of_bool (leb N n)).  intros y.\n  apply in_lx'.  apply leb_complete.  assumption.  rewrite y in H1.\n  unfold var_lu in H2.  elim (andb_prop _ _ (H2 _ H1)).\n  rewrite (nat_of_N_of_nat (n - N)).  intros.  simpl in |- *.\n  rewrite <- (plus_n_O N).  replace n with (n - N + N).\n  replace (S (n - N + N)) with (S (n - N) + N).\n  apply plus_le_compat.  apply leb_complete; assumption.  apply le_n.  \n  reflexivity.  rewrite (plus_comm (n - N) N).  symmetry  in |- *.\n  apply le_plus_minus.  apply leb_complete; assumption.  intro y.\n  rewrite y in H1.  discriminate.  unfold eval_be' in |- *.  simpl in |- *.\n  unfold bool_fun_and in |- *.  apply andb_true_intro.  split.  exact H4.  \n  fold (eval_be' (be_dash be) (var_env'_or ve (var_env'_dash ve'))) in |- *.\n  rewrite (eval_dash_lemma1 be ve') in H5.  rewrite <- H5.\n  apply (bool_fun_of_be_ext1 (be_dash be)).  intros.  unfold var_env'_or in |- *.\n  replace (ve (nat_of_N x)) with false.  reflexivity.  symmetry  in |- *.\n  apply not_true_is_false.  unfold not in |- *; intro.  unfold var_lu in H0.\n  elim (andb_prop _ _ (H0 _ H3)).  rewrite (N_of_nat_of_N x).  intros.\n  elim (andb_prop _ _ (be_ok_be_x_free _ _ (dash_be_ok _ H) _ H1)).  intros.\n  apply (lt_irrefl N).  apply le_lt_trans with (m := nat_of_N x).\n  apply leb_complete; assumption.  unfold lt in |- *.\n  apply leb_complete; assumption.  unfold not in |- *; intros.  unfold lx' in H3.\n  elim (in_lx'_1_conv _ _ _ H3).  intros.  unfold var_lu in H0.\n  elim (andb_prop _ _ (H0 _ H1)).  rewrite (nat_of_N_of_nat n).  intros.\n  apply (lt_irrefl N).  apply le_lt_trans with (m := n).  assumption.  unfold lt in |- *.\n  apply leb_complete.  assumption.  unfold lx' in |- *.  apply no_dup_lx'_1.\nQed.\n\nLemma mu_all_eval_semantics2 :\n forall t be : bool_expr,\n be_ok (var_lu 0 N) be ->\n forall ve : var_env',\n (forall n : nat, ve n = true -> var_lu 0 N (N_of_nat n) = true) ->\n (forall ve' : var_env',\n  (forall n : nat, ve' n = true -> var_lu 0 N (N_of_nat n) = true) ->\n  eval_be' t (var_env'_or ve (var_env'_dash ve')) = true ->\n  eval_be' be ve' = true) -> eval_be' (mu_all_eval N t be) ve = true.\nProof.\n  unfold mu_all_eval in |- *.  intros.  rewrite (replacel_lemma2 be H).\n  elim (univl_semantics (lx' N) (Impl t (be_dash be)) ve).  intros.  clear H2.\n  apply H3.  intros.  clear H3.  unfold eval_be' in |- *.  simpl in |- *.  unfold bool_fun_impl in |- *.\n  elim\n   (sumbool_of_bool\n      (bool_fun_of_bool_expr t (var_env'_to_env (var_env'_or ve ve')))).\n  intro y.  rewrite y.  simpl in |- *.  unfold eval_be' in H1.\n  rewrite <- (H1 (fun n : nat => ve' (N + n))).\n  fold (eval_be' be (fun n : nat => ve' (N + n))) in |- *.\n  rewrite (eval_dash_lemma1 be (fun n : nat => ve' (N + n))).\n  fold (eval_be' (be_dash be) (var_env'_or ve ve')) in |- *.  apply bool_fun_of_be_ext1.\n  intros.  intros.  unfold var_env'_or in |- *.  unfold var_env'_dash in |- *.\n  cut (var_lu N (2 * N) x = true).  unfold var_lu in |- *.  intro.\n  elim (andb_prop _ _ H4).  intros.  rewrite H5.\n  replace (ve (nat_of_N x)) with false.  simpl in |- *.\n  rewrite <- (le_plus_minus N (nat_of_N x)).  reflexivity.  \n  apply leb_complete.  assumption.  symmetry  in |- *.  apply not_true_is_false.\n  unfold not in |- *; intro.  unfold var_lu in H0.  elim (andb_prop _ _ (H0 _ H7)).\n  intros.  rewrite (N_of_nat_of_N x) in H9.  apply (lt_irrefl N).\n  apply le_lt_trans with (m := nat_of_N x).  apply leb_complete; assumption.  \n  unfold lt in |- *.  apply leb_complete; assumption.  \n  apply be_ok_be_x_free with (be := be_dash be).  apply dash_be_ok.  assumption.  \n  assumption.  intros.  unfold var_lu in |- *.  apply andb_true_intro.  split.\n  apply leb_correct.  apply le_O_n.  rewrite (nat_of_N_of_nat n).\n  unfold lx' in H2.  elim (in_lx'_1_conv _ _ _ (H2 _ H3)).  intros.\n  unfold lt in H5.  rewrite (plus_comm N n) in H5.  rewrite (Splus_nm n N) in H5.\n  apply leb_correct.  apply (fun p n m : nat => plus_le_reg_l n m p) with (p := N).\n  rewrite (plus_comm N (S n)).  assumption.  rewrite <- y.\n  fold\n   (eval_be' t (var_env'_or ve (var_env'_dash (fun n : nat => ve' (N + n)))))\n   in |- *.\n  fold (eval_be' t (var_env'_or ve ve')) in |- *.  apply bool_fun_of_be_ext1.  intros.\n  unfold var_env'_or in |- *.\n  replace (var_env'_dash (fun n : nat => ve' (N + n)) (nat_of_N x)) with\n   (ve' (nat_of_N x)).\n  reflexivity.  unfold var_env'_dash in |- *.\n  elim (sumbool_of_bool (leb N (nat_of_N x))).  intro y0.  rewrite y0.\n  rewrite <- (le_plus_minus N (nat_of_N x)).  reflexivity.\n  apply leb_complete; assumption.  intro y0.  rewrite y0.\n  apply not_true_is_false.  unfold not in |- *; intro.  unfold lx' in H2.\n  elim (in_lx'_1_conv _ _ _ (H2 _ H4)).  intros.\n  rewrite (leb_correct _ _ H5) in y0; discriminate.  intro y.  rewrite y.\n  reflexivity.  intros.  unfold not in |- *; intro.  unfold lx' in H3.\n  elim (in_lx'_1_conv N N n H3).  intro.  intro.  unfold var_lu in H0.\n  elim (andb_prop _ _ (H0 n H2)).  intros.  apply (lt_irrefl N).\n  apply le_lt_trans with (m := n).  assumption.  unfold lt in |- *.\n  rewrite (nat_of_N_of_nat n) in H7.  apply leb_complete; assumption.\n  unfold lx' in |- *.  apply no_dup_lx'_1.\nQed.\n\nEnd New.", "meta": {"author": "coq-contribs", "repo": "smc", "sha": "e175520faa82eda0f014d300705612892fc7e778", "save_path": "github-repos/coq/coq-contribs-smc", "path": "github-repos/coq/coq-contribs-smc/smc-e175520faa82eda0f014d300705612892fc7e778/munew.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.22899327150761625}}
{"text": "Require Import floyd.proofauto.\nRequire Import mc_reify.funcs.\nRequire Import mc_reify.types.\nRequire Import mc_reify.reify.\nRequire Import MirrorCore.Lambda.ExprCore.\n\nDefinition initialized_temp (id : positive) (t : PTree.t (type * bool)) :=\nmatch (t ! id) with\n| Some (ty, _) =>\n  PTree.set id (ty, true) t\n| None => t\nend.\n\n\nFixpoint update_temp (t : PTree.t (type * bool)) (s : statement) :=\n match s with\n | Sskip | Scontinue | Sbreak => t\n | Sassign e1 e2 => t (*already there?*)\n | Sset id e2 => (initialized_temp id t)\n | Ssequence s1 s2 => let t' := update_temp t s1 in\n                      update_temp t' s2\n | Sifthenelse b s1 s2 => join_te (update_temp t s1) (update_temp t s2)\n | Sloop _ _ => t\n | Sswitch e ls => update_temp_labeled t ls\n | Scall (Some id) _ _ => (initialized_temp id t)\n | _ => t  (* et cetera *)\nend\nwith update_temp_labeled (t : PTree.t (type * bool)) (ls : labeled_statements) :=\n       match ls with\n         | LSnil => t\n         | LScons _ s ls' =>\n           join_te (update_temp t s) (update_temp_labeled t ls')\n       end.\n\nLemma initialized_temp_eq : forall t v r gt gs i,\ninitialized i (mk_tycontext t v r gt gs) = mk_tycontext (initialized_temp i t) v r gt gs.\nProof.\nintros.\nunfold initialized, temp_types, initialized_temp. simpl. destruct (t ! i); auto.\ndestruct p; auto.\nQed.\n\nLemma update_temp_eq : forall t v r gt gs s,\nupdate_tycon (mk_tycontext t v r gt gs) s = (mk_tycontext (update_temp t s) v r gt gs)\nwith\nupdate_temp_labeled_eq : forall t v r gt gs s,\njoin_tycon_labeled s (mk_tycontext t v r gt gs) = (mk_tycontext (update_temp_labeled t s) v r gt gs).\nProof.\nintros.\ndestruct s; intros;\nsimpl; try rewrite initialized_temp_eq; try reflexivity.\ndestruct o; try rewrite initialized_temp_eq; auto.\nrepeat rewrite update_temp_eq. reflexivity.\nunfold join_tycon.\nrepeat rewrite update_temp_eq. reflexivity.\nrepeat rewrite update_temp_labeled_eq. reflexivity.\n\nintros.\ndestruct s; intros; simpl; try reflexivity.\nunfold join_tycon. repeat rewrite update_temp_eq.\nrewrite update_temp_labeled_eq. reflexivity.\nQed.\n\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/mc_reify/update_tycon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.22899326553173602}}
{"text": "From Coq Require Import Program ssreflect ssrbool List.\nFrom MetaCoq.Template Require Import config utils Kernames MCRelations.\n\n\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICPrimitive\n  PCUICReduction\n  PCUICReflect PCUICWeakeningEnvConv PCUICWeakeningEnvTyp PCUICCasesContexts\n  PCUICWeakeningConv PCUICWeakeningTyp\n  PCUICContextConversionTyp\n  PCUICTyping PCUICGlobalEnv PCUICInversion PCUICGeneration\n  PCUICConfluence PCUICConversion\n  PCUICUnivSubstitutionTyp\n  PCUICCumulativity PCUICSR PCUICSafeLemmata\n  PCUICValidity PCUICPrincipality PCUICElimination\n  PCUICOnFreeVars PCUICWellScopedCumulativity PCUICSN PCUICCanonicity.\n\nFrom MetaCoq Require Import PCUICArities PCUICSpine.\nFrom MetaCoq.PCUIC Require PCUICWcbvEval.\n\nSection firstorder.\n\n  Context {Σ : global_env_ext}.\n  Context {Σb : list (kername × bool)}.\n\n  Fixpoint plookup_env {A} (Σ : list (kername × A)) (kn : kername) {struct Σ} : option A :=\n  match Σ with\n  | [] => None\n  | d :: tl => if eq_kername kn d.1 then Some d.2 else plookup_env tl kn\n  end.\n  (*\n  Definition zo_type (t : term) :=\n    match (PCUICAstUtils.decompose_app t).1 with\n    | tProd _ _ _ => false\n    | tSort _ => false\n    | tInd (mkInd nm i) _ => match (plookup_env Σb nm) with\n                             | Some l => nth i l false | None => false\n                             end\n    | _ => true\n    end. *)\n\n  Definition firstorder_type (n k : nat) (t : term) :=\n    match (PCUICAstUtils.decompose_app t).1 with\n    | tInd (mkInd nm i) u => match (plookup_env Σb nm) with\n                             | Some b => b | None => false\n                             end\n    | tRel i => (k <=? i) && (i <? n + k)\n    | _ => false\n    end.\n  (*\n  Definition firstorder_type (t : term) :=\n    match (PCUICAstUtils.decompose_app t).1 with\n    | tInd (mkInd nm i) _ => match (plookup_env Σb nm) with\n                             | Some l => nth i l false | None => false\n                             end\n    | _ => false\n    end. *)\n\n  Definition firstorder_con mind (c : constructor_body) :=\n    let inds := #|mind.(ind_bodies)| in\n    alli (fun k '({| decl_body := b ; decl_type := t ; decl_name := n|}) =>\n      firstorder_type inds k t) 0\n      (List.rev (c.(cstr_args) ++ mind.(ind_params)))%list.\n\n  Definition firstorder_oneind mind (ind : one_inductive_body) :=\n    forallb (firstorder_con mind) ind.(ind_ctors) && negb (Universe.is_level (ind_sort ind)).\n\n  Definition firstorder_mutind (mind : mutual_inductive_body) :=\n    (* if forallb (fun decl => firstorder_type decl.(decl_type)) mind.(ind_params) then *)\n    (mind.(ind_finite) == Finite) &&\n    forallb (firstorder_oneind mind) mind.(ind_bodies)\n    (* else repeat false (length mind.(ind_bodies)). *).\n\n  Definition firstorder_ind (i : inductive) :=\n    match lookup_env Σ.1 (inductive_mind i) with\n    | Some (InductiveDecl mind) => firstorder_mutind mind\n    | _ => false\n    end.\n\nEnd firstorder.\n\nFixpoint firstorder_env' (Σ : global_declarations) :=\n  match Σ with\n  | nil => []\n  | (nm, ConstantDecl _) :: Σ' =>\n    let Σb := firstorder_env' Σ' in\n    ((nm, false) :: Σb)\n  | (nm, InductiveDecl mind) :: Σ' =>\n    let Σb := firstorder_env' Σ' in\n    ((nm, @firstorder_mutind Σb mind) :: Σb)\n  end.\n\nDefinition firstorder_env (Σ : global_env_ext) :=\n  firstorder_env' Σ.1.(declarations).\n\nSection cf.\n\nContext {cf : config.checker_flags}.\n\nDefinition isPropositional Σ ind b :=\n  match lookup_env Σ (inductive_mind ind) with\n  | Some (InductiveDecl mdecl) =>\n    match nth_error mdecl.(ind_bodies) (inductive_ind ind) with\n    | Some idecl =>\n      match destArity [] idecl.(ind_type) with\n      | Some (_, s) => is_propositional s = b\n      | None => False\n      end\n    | None => False\n    end\n  | _ => False\n  end.\n\nInductive firstorder_value Σ Γ : term -> Prop :=\n| firstorder_value_C i n ui u args pandi :\n   Σ ;;; Γ |- mkApps (tConstruct i n ui) args :\n   mkApps (tInd i u) pandi ->\n   Forall (firstorder_value Σ Γ) args ->\n   isPropositional Σ i false ->\n   firstorder_value Σ Γ (mkApps (tConstruct i n ui) args).\n\nLemma firstorder_value_inds :\n forall (Σ : global_env_ext) (Γ : context) (P : term -> Prop),\n(forall (i : inductive) (n : nat) (ui u : Instance.t)\n   (args pandi : list term),\n Σ;;; Γ |- mkApps (tConstruct i n ui) args : mkApps (tInd i u) pandi ->\n Forall (firstorder_value Σ Γ) args ->\n Forall P args ->\n isPropositional (PCUICEnvironment.fst_ctx Σ) i false ->\n P (mkApps (tConstruct i n ui) args)) ->\nforall t : term, firstorder_value Σ Γ t -> P t.\nProof using Type.\n  intros ? ? ? ?. fix rec 2. intros t [ ]. eapply H; eauto.\n  clear - H0 rec.\n  induction H0; econstructor; eauto.\nQed.\n\nLemma firstorder_ind_propositional {Σ : global_env_ext} i mind oind :\n  squash (wf_ext Σ) ->\n  declared_inductive Σ i mind oind ->\n  @firstorder_ind Σ (firstorder_env Σ) i ->\n  isPropositional Σ i false.\nProof using Type.\n  intros Hwf d. pose proof d as [d1 d2]. intros H. red in d1. unfold firstorder_ind in H.\n  red. sq.\n  unfold PCUICEnvironment.fst_ctx in *. rewrite d1 in H |- *.\n  solve_all.\n  unfold firstorder_mutind in H.\n  rewrite d2. move/andP: H => [ind H0].\n  eapply forallb_nth_error in H0; tea.\n  erewrite d2 in H0. cbn in H0.\n  unfold firstorder_oneind in H0. solve_all.\n  destruct (ind_sort oind) eqn:E2; inv H0.\n  eapply PCUICInductives.declared_inductive_type in d.\n  rewrite d. rewrite E2.\n  now rewrite destArity_it_mkProd_or_LetIn.\nQed.\n\nInductive firstorder_spine Σ (Γ : context) : term -> list term -> term -> Type :=\n| firstorder_spine_nil ty ty' :\n    isType Σ Γ ty ->\n    isType Σ Γ ty' ->\n    Σ ;;; Γ ⊢ ty ≤ ty' ->\n    firstorder_spine Σ Γ ty [] ty'\n\n| firstorder_spine_cons ty hd tl na i u args B B' mind oind :\n    isType Σ Γ ty ->\n    isType Σ Γ (tProd na (mkApps (tInd i u) args) B) ->\n    Σ ;;; Γ ⊢ ty ≤ tProd na (mkApps (tInd i u) args) B ->\n    declared_inductive Σ i mind oind ->\n    Σ ;;; Γ |- hd : (mkApps (tInd i u) args) ->\n    @firstorder_ind Σ (@firstorder_env Σ) i ->\n    firstorder_spine Σ Γ (subst10 hd B) tl B' ->\n    firstorder_spine Σ Γ ty (hd :: tl) B'.\n\nInductive instantiated {Σ} (Γ : context) : term -> Type :=\n| instantiated_mkApps i u args : instantiated Γ (mkApps (tInd i u) args)\n| instantiated_LetIn na d b ty :\n  instantiated Γ (ty {0 := d}) ->\n  instantiated Γ (tLetIn na d b ty)\n| instantiated_tProd na B i u args :\n  @firstorder_ind Σ (@firstorder_env Σ) i ->\n    (forall x,\n       (* Σ ;;; Γ |- x : mkApps (tInd i u) args ->  *)\n      instantiated Γ (subst10 x B)) ->\n    instantiated Γ (tProd na (mkApps (tInd i u) args) B).\n\nImport PCUICLiftSubst.\nLemma isType_context_conversion {Σ : global_env_ext} {wfΣ : wf Σ} {Γ Δ} {T} :\n  isType Σ Γ T ->\n  Σ ⊢ Γ = Δ ->\n  wf_local Σ Δ ->\n  isType Σ Δ T.\nProof using Type.\n  intros [s Hs]. exists s. eapply context_conversion; tea. now eapply ws_cumul_ctx_pb_forget.\nQed.\n\nLemma typing_spine_arity_spine {Σ : global_env_ext} {wfΣ : wf Σ} Γ Δ args T' i u pars :\n  typing_spine Σ Γ (it_mkProd_or_LetIn Δ (mkApps (tInd i u) pars)) args T' ->\n  arity_spine Σ Γ (it_mkProd_or_LetIn Δ (mkApps (tInd i u) pars)) args T'.\nProof using Type.\n  intros H. revert args pars T' H.\n  induction Δ using PCUICInduction.ctx_length_rev_ind; intros args pars T' H.\n  - cbn. depelim H.\n    + econstructor; eauto.\n    + eapply invert_cumul_ind_prod in w. eauto.\n  - cbn. depelim H.\n    + econstructor; eauto.\n    + rewrite it_mkProd_or_LetIn_app in w, i0 |- *. cbn. destruct d as [name [body |] type]; cbn in *.\n      -- constructor. rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps. eapply X. now len.\n         econstructor; tea. eapply isType_tLetIn_red in i0.\n         rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps Nat.add_0_r in i0. now rewrite Nat.add_0_r. pcuic.\n         etransitivity; tea. eapply into_ws_cumul_pb. 2,4:fvs.\n         econstructor 3. 2:{ econstructor. }\n         rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps //. constructor 1. reflexivity.\n         eapply isType_tLetIn_red in i0. 2:pcuic.\n         rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps in i0.\n         now eapply isType_open.\n      -- eapply cumul_Prod_inv in w as []. econstructor.\n         ++ eapply type_ws_cumul_pb. 3: eapply PCUICContextConversion.ws_cumul_pb_eq_le; symmetry. all:eauto.\n            eapply isType_tProd in i0. eapply i0.\n         ++ rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn. autorewrite with subst.\n            cbn. eapply X. len. lia.\n            eapply typing_spine_strengthen. eauto.\n            2:{ replace (it_mkProd_or_LetIn (subst_context [hd] 0 Γ0)\n            (mkApps (tInd i u) (map (subst [hd] (#|Γ0| + 0)) pars))) with ((PCUICAst.subst10 hd (it_mkProd_or_LetIn Γ0 (mkApps (tInd i u) pars)))).\n            2:{ rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn. now autorewrite with subst. }\n            eapply substitution0_ws_cumul_pb. eauto. eauto.\n            }\n            replace (it_mkProd_or_LetIn (subst_context [hd] 0 Γ0)\n            (mkApps (tInd i u) (map (subst [hd] (#|Γ0| + 0)) pars))) with ((PCUICAst.subst10 hd (it_mkProd_or_LetIn Γ0 (mkApps (tInd i u) pars)))).\n            2:{ rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn. now autorewrite with subst. }\n            eapply isType_subst. eapply PCUICSubstitution.subslet_ass_tip. eauto.\n            eapply isType_tProd in i0 as [_ tprod].\n            eapply isType_context_conversion; tea. constructor. eapply ws_cumul_ctx_pb_refl. now eapply typing_wf_local, PCUICClosedTyp.wf_local_closed_context in t.\n            constructor; tea. constructor. pcuic. eapply validity in t. now eauto.\nQed.\n\nLemma leb_spect : forall x y : nat, BoolSpecSet (x <= y) (y < x) (x <=? y).\nProof using Type.\n  intros x y. destruct (x <=? y) eqn:E;\n  econstructor; destruct (Nat.leb_spec x y); lia.\nQed.\n\nLemma nth_error_inds {ind u mind n} : n < #|ind_bodies mind| ->\n  nth_error (inds ind u mind.(ind_bodies)) n = Some (tInd (mkInd ind (#|mind.(ind_bodies)| - S n)) u).\nProof using Type.\n  unfold inds.\n  induction #|ind_bodies mind| in n |- *.\n  - intros hm. inv hm.\n  - intros hn. destruct n => /=. lia_f_equal.\n    eapply IHn0. lia.\nQed.\n\nLemma alli_subst_instance (Γ : context) u p :\n  (forall k t, p k t = p k t@[u]) ->\n  forall n,\n    alli (fun (k : nat) '{| decl_type := t |} => p k t) n Γ =\n    alli (fun (k : nat) '{| decl_type := t |} => p k t) n Γ@[u].\nProof using Type.\n  intros hp.\n  induction Γ; cbn => //.\n  move=> n. destruct a; cbn. f_equal. apply hp. apply IHΓ.\nQed.\n\nArguments firstorder_mutind : clear implicits.\n\nLemma plookup_env_lookup_env {Σ : global_env_ext} kn b :\n  plookup_env (firstorder_env Σ) kn = Some b ->\n  ∑ Σ' decl, lookup_env Σ kn = Some decl ×\n    extends_decls Σ' Σ ×\n    match decl with\n    | ConstantDecl _ => b = false\n    | InductiveDecl mind =>\n      b = firstorder_mutind (firstorder_env' (declarations Σ')) mind\n    end.\nProof using.\n  destruct Σ as [[univs Σ retro] ext].\n  induction Σ; cbn => //.\n  destruct a as [kn' d] => //. cbn.\n  case: eqb_specT.\n  * intros ->.\n    destruct d => //; cbn; rewrite eqb_refl => [=] <-;\n    exists {| universes := univs; declarations := Σ; retroknowledge := retro |}.\n    eexists; split => //. cbn. split => //.\n    red. split => //. eexists (_ :: []); cbn; trea.\n    eexists; split => //. cbn; split => //.\n    red. split => //. eexists (_ :: []); cbn; trea.\n  * intros neq h.\n    destruct d => //. cbn in h.\n    move: h. case: eqb_specT=> // _ h'.\n    unfold firstorder_env in IHΣ. cbn in IHΣ.\n    specialize (IHΣ h') as [Σ' [decl [Hdecl [ext' ?]]]].\n    exists Σ', decl; split => //. split => //.\n    destruct ext' as [equ [Σ'' eq]]. split => //.\n    eexists (_ :: Σ''). cbn in *. rewrite eq. trea.\n    move: h. cbn. apply neqb in neq. rewrite (negbTE neq).\n    intros h'; specialize (IHΣ h') as [Σ' [decl [Hdecl [ext' ?]]]].\n    exists Σ', decl; split => //. split => //.\n    destruct ext' as [equ [Σ'' eq]]. split => //.\n    eexists (_ :: Σ''). cbn in *. rewrite eq. trea.\nQed.\n\nLemma firstorder_spine_let {Σ : global_env_ext} {wfΣ : wf Σ} {Γ na a A B args T'} :\n  firstorder_spine Σ Γ (B {0 := a}) args T' ->\n  isType Σ Γ (tLetIn na a A B) ->\n  firstorder_spine Σ Γ (tLetIn na a A B) args T'.\nProof using Type.\n  intros H; depind H.\n  - constructor; auto.\n    etransitivity; tea. eapply cumulSpec_cumulAlgo_curry; tea; fvs.\n    eapply cumul_zeta.\n  - intros. econstructor. tea.\n    2:{ etransitivity; tea.\n        eapply cumulSpec_cumulAlgo_curry; tea; fvs.\n        eapply cumul_zeta. }\n    all:tea.\nQed.\n\nLemma instantiated_typing_spine_firstorder_spine {Σ : global_env_ext} {wfΣ : wf Σ} Γ T args T' :\n  instantiated (Σ := Σ) Γ T ->\n  arity_spine Σ Γ T args T' ->\n  isType Σ Γ T ->\n  firstorder_spine Σ Γ T args T'.\nProof using Type.\n  intros hi hsp.\n  revert hi; induction hsp; intros hi isty.\n  - constructor => //. now eapply isType_ws_cumul_pb_refl.\n  - econstructor; eauto.\n  - depelim hi. solve_discr. eapply firstorder_spine_let; eauto. eapply IHhsp => //.\n    now eapply isType_tLetIn_red in isty; pcuic.\n  - depelim hi. solve_discr.\n    specialize (i1 hd). specialize (IHhsp i1).\n    destruct (validity t) as [s Hs]. eapply inversion_mkApps in Hs as [? [hi _]].\n    eapply inversion_Ind in hi as [mdecl [idecl [decli [? ?]]]].\n    econstructor; tea. 2:{ eapply IHhsp. eapply isType_apply in isty; tea. }\n    now eapply isType_ws_cumul_pb_refl. eauto.\nQed.\n\nArguments firstorder_type : clear implicits.\n\n(* Lemma firstorder_env'_app x y :\n  firstorder_env' (x ++ y) = firstorder_env' x ++ firstorder_env' y.\nProof.\n  induction x in y |- *; cbn => //.\n  destruct a => //. destruct g => //. cbn. f_equal; eauto.\n  cbn; f_equal; eauto.\n  f_equal. f_equal. eauto. *)\n\nImport PCUICGlobalMaps.\n\nLemma fresh_global_app decls decls' kn :\n  fresh_global kn (decls ++ decls') ->\n  fresh_global kn decls /\\ fresh_global kn decls'.\nProof.\n  induction decls => /= //.\n  - intros f; split => //.\n  - intros f; depelim f.\n    specialize (IHdecls f) as [].\n    split; eauto. constructor => //.\nQed.\n\nLemma plookup_env_Some_not_fresh g kn b :\n  plookup_env (firstorder_env' g) kn = Some b ->\n  ~ PCUICGlobalMaps.fresh_global kn g.\nProof.\n  induction g; cbn => //.\n  destruct a => //. destruct g0 => //.\n  - cbn.\n    case: eqb_spec.\n    + move=> -> [=].\n      intros neq hf. depelim hf. now cbn in H.\n    + move=> neq hl hf.\n      apply IHg => //. now depelim hf.\n  - cbn.\n    case: eqb_spec.\n    + move=> -> [=].\n      intros neq hf. depelim hf. now cbn in H.\n    + move=> neq hl hf.\n      apply IHg => //. now depelim hf.\nQed.\n\nLemma plookup_env_extends {Σ Σ' : global_env} kn b :\n  extends_decls Σ' Σ ->\n  wf Σ ->\n  plookup_env (firstorder_env' (declarations Σ')) kn = Some b ->\n  plookup_env (firstorder_env' (declarations Σ)) kn = Some b.\nProof.\n  intros [equ [Σ'' eq] eqr]. rewrite eq.\n  clear equ eqr. intros []. clear o.\n  rewrite eq in o0. clear eq. move: o0.\n  generalize (declarations Σ'). clear Σ'.\n  induction Σ''.\n  - cbn => //.\n  - cbn. destruct a => //. intros gs ong.\n    depelim ong. specialize (IHΣ'' _ ong).\n    destruct o as [f ? ? ?].\n    destruct g => //.\n    * intros hl. specialize (IHΣ'' hl).\n      eapply plookup_env_Some_not_fresh in hl.\n      cbn. case: eqb_spec.\n      + intros <-.  apply fresh_global_app in f as [].\n        contradiction.\n      + now intros neq.\n    * intros hl. specialize (IHΣ'' hl).\n      eapply plookup_env_Some_not_fresh in hl.\n      cbn. case: eqb_spec.\n      + intros <-. apply fresh_global_app in f as [].\n        contradiction.\n      + now intros neq.\nQed.\n\nLemma firstorder_mutind_ext {Σ Σ' : global_env_ext} m :\n  extends_decls Σ' Σ ->\n  wf Σ ->\n  firstorder_mutind (firstorder_env' (declarations Σ')) m ->\n  firstorder_mutind (firstorder_env Σ) m.\nProof.\n  intros [equ [Σ'' eq]] wf.\n  unfold firstorder_env. rewrite eq.\n  unfold firstorder_mutind.\n  move/andP => [] -> /=. apply forallb_impl => x _.\n  unfold firstorder_oneind.\n  move/andP => [] h -> /=; rewrite andb_true_r.\n  eapply forallb_impl; tea => c _.\n  unfold firstorder_con.\n  eapply alli_impl => i [] _ _ ty.\n  unfold firstorder_type.\n  destruct decompose_app => // /=.\n  destruct t => //. destruct ind => //.\n  destruct plookup_env eqn:hl => //. destruct b => //.\n  eapply (plookup_env_extends (Σ:=Σ)) in hl. 2:split; eauto.\n  rewrite eq in hl. rewrite hl //. apply wf.\nQed.\n\nLemma firstorder_args {Σ : global_env_ext} {wfΣ : wf Σ} { mind cbody i n ui args u pandi oind} :\n  declared_constructor Σ (i, n) mind oind cbody ->\n  PCUICArities.typing_spine Σ [] (type_of_constructor mind cbody (i, n) ui) args (mkApps (tInd i u) pandi) ->\n  @firstorder_ind Σ (@firstorder_env Σ) i ->\n  firstorder_spine Σ [] (type_of_constructor mind cbody (i, n) ui) args (mkApps (tInd i u) pandi).\nProof using Type.\n  intros Hdecl Hspine Hind. revert Hspine.\n  unshelve edestruct @declared_constructor_inv with (Hdecl := Hdecl); eauto. eapply weaken_env_prop_typing.\n\n  (* revert Hspine. *) unfold type_of_constructor.\n  erewrite cstr_eq. 2: eapply p.\n  rewrite <- it_mkProd_or_LetIn_app.\n  rewrite PCUICUnivSubst.subst_instance_it_mkProd_or_LetIn.\n  rewrite PCUICSpine.subst0_it_mkProd_or_LetIn. intros Hspine.\n\n  match goal with\n   | [ |- firstorder_spine _ _ ?T _ _ ] =>\n  assert (@instantiated Σ [] T) as Hi end.\n  { clear Hspine. destruct Hdecl as [[d1 d3] d2]. pose proof d3 as Hdecl.\n    unfold firstorder_ind in Hind.\n    rewrite d1 in Hind. solve_all. clear a.\n    move/andP: Hind => [indf H0].\n    eapply forallb_nth_error in H0 as H'.\n    erewrite d3 in H'.\n    unfold firstorder_oneind in H'. cbn in H'.\n    rtoProp.\n    eapply nth_error_forallb in H. 2: eauto.\n    unfold firstorder_con in H.\n    revert H. cbn.\n    unfold cstr_concl.\n    rewrite PCUICUnivSubst.subst_instance_mkApps subst_mkApps.\n    rewrite subst_instance_length app_length.\n    unfold cstr_concl_head. rewrite PCUICInductives.subst_inds_concl_head. now eapply nth_error_Some_length in Hdecl.\n    rewrite -app_length.\n    generalize (cstr_args cbody ++ ind_params mind)%list.\n    clear -wfΣ d1 indf H1 H0 Hdecl.\n    (* generalize conclusion to mkApps tInd args *)\n    intros c.\n    change (list context_decl) with context in c.\n    move: (map (subst (inds _ _ _) _) _).\n    intros args.\n    rewrite (alli_subst_instance _ ui (fun k t => firstorder_type _ #|ind_bodies mind| k t)).\n    { intros k t.\n      rewrite /firstorder_type.\n      rewrite -PCUICUnivSubstitutionConv.subst_instance_decompose_app /=.\n      destruct (decompose_app) => //=. destruct t0 => //. }\n    replace (List.rev c)@[ui] with (List.rev c@[ui]).\n    2:{ rewrite /subst_instance /subst_instance_context /map_context map_rev //. }\n    revert args.\n    induction (c@[ui]) using PCUICInduction.ctx_length_rev_ind => args.\n    - unfold cstr_concl, cstr_concl_head. cbn.\n      autorewrite with substu subst.\n      rewrite subst_context_nil. cbn -[subst0].\n      econstructor.\n    - rewrite rev_app_distr /=. destruct d as [na [b|] t].\n      + move=> /andP[] fot foΓ.\n        rewrite subst_context_app /=.\n        rewrite it_mkProd_or_LetIn_app /= /mkProd_or_LetIn /=.\n        constructor.\n        rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps /=. len.\n        rewrite -subst_app_context' // PCUICSigmaCalculus.subst_context_decompo.\n        cbn. len. eapply X. now len.\n        rewrite -subst_telescope_subst_context. clear -foΓ.\n        revert foΓ. move: (lift0 #|ind_bodies mind| _).\n        generalize 0.\n        induction (List.rev Γ) => //.\n        cbn -[subst_telescope]. intros n t.\n        destruct a; cbn -[subst_telescope].\n        move/andP => [] fo fol.\n        rewrite PCUICContextSubst.subst_telescope_cons /=.\n        apply/andP; split; eauto.\n        clear -fo.\n        move: fo.\n        unfold firstorder_type; cbn.\n        destruct (decompose_app decl_type) eqn:da.\n        rewrite (decompose_app_inv da) subst_mkApps /=.\n        destruct t0 => //=.\n        { move/andP => [/Nat.leb_le hn /Nat.ltb_lt hn'].\n          destruct (Nat.leb_spec n n0).\n          destruct (n0 - n) eqn:E. lia.\n          cbn. rewrite nth_error_nil /=.\n          rewrite decompose_app_mkApps //=.\n          apply/andP. split. apply Nat.leb_le. lia. apply Nat.ltb_lt. lia.\n          cbn.\n          rewrite decompose_app_mkApps //=.\n          apply/andP. split. apply Nat.leb_le. lia. apply Nat.ltb_lt. lia. }\n        { destruct ind => //. rewrite decompose_app_mkApps //. }\n      + move=> /andP[] fot foΓ.\n        rewrite subst_context_app /=.\n        rewrite it_mkProd_or_LetIn_app /= /mkProd_or_LetIn /=.\n        unfold firstorder_type in fot.\n        destruct ((PCUICAstUtils.decompose_app t)) eqn:E.\n        cbn in fot. destruct t0; try solve [inv fot].\n        * rewrite (decompose_app_inv E) /= subst_mkApps.\n          rewrite Nat.add_0_r in fot. eapply Nat.ltb_lt in fot.\n          cbn. rewrite nth_error_inds. lia. cbn.\n          econstructor.\n          { rewrite /firstorder_ind d1 /= /firstorder_mutind indf H0 //. }\n          intros x.\n          rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps /=. len.\n          rewrite -subst_app_context' // PCUICSigmaCalculus.subst_context_decompo.\n          cbn. len. eapply X. now len.\n          rewrite -subst_telescope_subst_context. clear -foΓ.\n          revert foΓ. generalize (lift0 #|ind_bodies mind| x).\n          generalize 0.\n          induction (List.rev Γ) => //.\n          cbn -[subst_telescope]. intros n t.\n          destruct a; cbn -[subst_telescope].\n          move/andP => [] fo fol.\n          rewrite PCUICContextSubst.subst_telescope_cons /=.\n          apply/andP; split; eauto.\n          clear -fo.\n          move: fo.\n          unfold firstorder_type; cbn.\n          destruct (decompose_app decl_type) eqn:da.\n          rewrite (decompose_app_inv da) subst_mkApps /=.\n          destruct t0 => //=.\n          { move/andP => [/Nat.leb_le hn /Nat.ltb_lt hn'].\n            destruct (Nat.leb_spec n n0).\n            destruct (n0 - n) eqn:E. lia.\n            cbn. rewrite nth_error_nil /=.\n            rewrite decompose_app_mkApps //=.\n            apply/andP. split. apply Nat.leb_le. lia. apply Nat.ltb_lt. lia.\n            cbn.\n            rewrite decompose_app_mkApps //=.\n            apply/andP. split. apply Nat.leb_le. lia. apply Nat.ltb_lt. lia. }\n          { destruct ind => //. rewrite decompose_app_mkApps //. }\n        * rewrite (decompose_app_inv E) subst_mkApps //=.\n          constructor. {\n             unfold firstorder_ind. destruct ind. cbn in *.\n             destruct plookup_env eqn:hp => //.\n             eapply plookup_env_lookup_env in hp as [Σ' [decl [eq [ext he]]]].\n             rewrite eq. destruct decl; subst b => //.\n             eapply (firstorder_mutind_ext (Σ' := (empty_ext Σ'))); tea. }\n          intros x. rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps /=; len.\n          rewrite -subst_app_context' // PCUICSigmaCalculus.subst_context_decompo.\n          eapply X. now len. len.\n          rewrite -subst_telescope_subst_context. clear -foΓ.\n          revert foΓ. generalize (lift0 #|ind_bodies mind| x).\n          generalize 0.\n          induction (List.rev Γ) => //.\n          cbn -[subst_telescope]. intros n t.\n          destruct a; cbn -[subst_telescope].\n          move/andP => [] fo fol.\n          rewrite PCUICContextSubst.subst_telescope_cons /=.\n          apply/andP; split; eauto.\n          clear -fo.\n          move: fo.\n          unfold firstorder_type; cbn.\n          destruct (decompose_app decl_type) eqn:da.\n          rewrite (decompose_app_inv da) subst_mkApps /=.\n          destruct t0 => //=.\n          { move/andP => [/Nat.leb_le hn /Nat.ltb_lt hn'].\n            destruct (Nat.leb_spec n n0).\n            destruct (n0 - n) eqn:E. lia.\n            cbn. rewrite nth_error_nil /=.\n            rewrite decompose_app_mkApps //=.\n            apply/andP. split. apply Nat.leb_le. lia. apply Nat.ltb_lt. lia.\n            cbn.\n            rewrite decompose_app_mkApps //=.\n            apply/andP. split. apply Nat.leb_le. lia. apply Nat.ltb_lt. lia. }\n          { destruct ind => //. rewrite decompose_app_mkApps //. }\n  }\n  cbn in Hi |- *.\n  revert Hi Hspine. cbn.\n  unfold cstr_concl, cstr_concl_head.\n  autorewrite with substu subst.\n  rewrite subst_instance_length app_length.\n  rewrite PCUICInductives.subst_inds_concl_head. { cbn. destruct Hdecl as [[d1 d2] d3]. eapply nth_error_Some. rewrite d2. congruence. }\n  match goal with [ |- context[mkApps _ ?args]] => generalize args end.\n  intros args' Hi Spine.\n  eapply instantiated_typing_spine_firstorder_spine; tea.\n  now eapply typing_spine_arity_spine in Spine.\n  now eapply typing_spine_isType_dom in Spine.\nQed.\n\nLemma invert_cumul_it_mkProd_or_LetIn_Sort_Ind {Σ : global_env_ext} {wfΣ : wf Σ} {Γ Δ s i u args} :\n  Σ ;;; Γ ⊢ it_mkProd_or_LetIn Δ (tSort s) ≤ mkApps (tInd i u) args -> False.\nProof using Type.\n  induction Δ using PCUICInduction.ctx_length_rev_ind; cbn.\n  - eapply invert_cumul_sort_ind.\n  - rewrite it_mkProd_or_LetIn_app; destruct d as [na [b|] ty]; cbn.\n    * intros hl.\n      eapply ws_cumul_pb_LetIn_l_inv in hl.\n      rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn in hl.\n      eapply H, hl. now len.\n    * intros hl. now eapply invert_cumul_prod_ind in hl.\nQed.\n\nLemma firstorder_value_spec Σ t i u args mind :\n  wf_ext Σ -> wf_local Σ [] ->\n   Σ ;;; [] |- t : mkApps (tInd i u) args ->\n  PCUICWcbvEval.value Σ t ->\n  lookup_env Σ (i.(inductive_mind)) = Some (InductiveDecl mind) ->\n  @firstorder_ind Σ (firstorder_env Σ) i ->\n  firstorder_value Σ [] t.\nProof using Type.\n  intros Hwf Hwfl Hty Hvalue.\n  revert mind i u args Hty.\n\n  induction Hvalue as [ t Hvalue | t args' Hhead Hargs IH ] using PCUICWcbvEval.value_values_ind;\n   intros mind i u args Hty Hlookup Hfo.\n  - destruct t; inversion_clear Hvalue.\n    + exfalso. eapply inversion_Sort in Hty as (? & ? & Hcumul); eauto.\n      now eapply invert_cumul_sort_ind in Hcumul.\n    + exfalso. eapply inversion_Prod in Hty as (? & ? & ? & ? & Hcumul); eauto.\n      now eapply invert_cumul_sort_ind in Hcumul.\n    + exfalso. eapply inversion_Lambda in Hty as (? & ? & ? & ? & Hcumul); eauto.\n      now eapply invert_cumul_prod_ind in Hcumul.\n    + exfalso. eapply inversion_Ind in Hty as (? & ? & ? & ? & ? & ?); eauto.\n      eapply PCUICInductives.declared_inductive_type in d.\n      rewrite d in w.\n      destruct (ind_params x ,,, ind_indices x0) as [ | [? [] ?] ? _] using rev_ind.\n      * cbn in w. now eapply invert_cumul_sort_ind in w.\n      * rewrite it_mkProd_or_LetIn_app in w. cbn in w.\n        eapply ws_cumul_pb_LetIn_l_inv in w.\n        rewrite /subst1 PCUICUnivSubst.subst_instance_it_mkProd_or_LetIn PCUICLiftSubst.subst_it_mkProd_or_LetIn in w.\n        now eapply invert_cumul_it_mkProd_or_LetIn_Sort_Ind in w.\n      * rewrite it_mkProd_or_LetIn_app in w. cbn in w.\n        now eapply invert_cumul_prod_ind in w.\n    + eapply inversion_Construct in Hty as Hty'; eauto.\n      destruct Hty' as (? & ? & ? & ? & ? & ? & ?).\n      assert (ind = i) as ->. {\n         eapply PCUICInductiveInversion.Construct_Ind_ind_eq with (args := []); eauto.\n      }\n      eapply firstorder_value_C with (args := []); eauto.\n      eapply firstorder_ind_propositional; eauto. sq. eauto.\n      now eapply (declared_constructor_inductive (ind := (i, _))).\n    + exfalso. eapply invert_fix_ind with (args := []) in Hty as [].\n      destruct unfold_fix as [ [] | ]; auto. eapply nth_error_nil.\n    + exfalso. eapply (typing_cofix_coind (args := [])) in Hty. red in Hty.\n      red in Hfo. unfold firstorder_ind in Hfo.\n      rewrite Hlookup in Hfo.\n      eapply andb_true_iff in Hfo as [Hfo _].\n      rewrite /check_recursivity_kind Hlookup in Hty.\n      apply eqb_eq in Hfo, Hty. congruence.\n    + eapply inversion_Prim in Hty as [prim_ty [cdecl [wf hp hdecl [s []] cum]]]; eauto.\n      now eapply invert_cumul_axiom_ind in cum; tea.\n  - destruct t; inv Hhead.\n    + exfalso. now eapply invert_ind_ind in Hty.\n    + apply inversion_mkApps in Hty as Hcon; auto.\n      destruct Hcon as (?&typ_ctor& spine).\n      apply inversion_Construct in typ_ctor as (?&?&?&?&?&?&?); auto.\n      pose proof d as [[d' _] _]. red in d'. cbn in *. unfold PCUICEnvironment.fst_ctx in *.\n      eapply @PCUICInductiveInversion.Construct_Ind_ind_eq with (mdecl := x0) in Hty as Hty'; eauto.\n      destruct Hty' as (([[[]]] & ?)  & ? & ? & ? & ? & _). subst.\n      econstructor; eauto.\n      2:{ eapply firstorder_ind_propositional; sq; eauto. eapply declared_constructor_inductive in d. eauto. }\n      eapply PCUICSpine.typing_spine_strengthen in spine. 3: eauto.\n      2: eapply PCUICInductiveInversion.declared_constructor_valid_ty; eauto.\n\n      eapply firstorder_args in spine; eauto.\n      clear c0 c1 e0 w Hty H0 Hargs.\n      induction spine.\n      * econstructor.\n      * destruct d as [d1 d2]. inv IH.\n        econstructor. inv X.\n        eapply H0. tea. eapply d0. exact i3.\n        inv X. eapply IHspine; eauto.\n     + exfalso.\n       destruct PCUICWcbvEval.cunfold_fix as [[] | ] eqn:E; inversion H.\n       eapply invert_fix_ind in Hty. auto.\n       unfold unfold_fix. unfold PCUICWcbvEval.cunfold_fix in E.\n       destruct (nth_error mfix idx); auto.\n       inversion E; subst; clear E.\n       eapply nth_error_None. lia.\n    + exfalso. eapply (typing_cofix_coind (args := args')) in Hty.\n      red in Hfo. unfold firstorder_ind in Hfo.\n      rewrite Hlookup in Hfo.\n      eapply andb_true_iff in Hfo as [Hfo _].\n      rewrite /check_recursivity_kind Hlookup in Hty.\n      apply eqb_eq in Hfo, Hty. congruence.\nQed.\n\nEnd cf.\n", "meta": {"author": "SwampertX", "repo": "undergraduate-thesis", "sha": "b0c78984b94e56f1372a7195bd0babaab10fca8d", "save_path": "github-repos/coq/SwampertX-undergraduate-thesis", "path": "github-repos/coq/SwampertX-undergraduate-thesis/undergraduate-thesis-b0c78984b94e56f1372a7195bd0babaab10fca8d/final-report-new/code/v2/pcuic/theories/PCUICFirstorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2289932595558558}}
{"text": "Require Import Verdi.GhostSimulations.\nRequire Import VerdiRaft.Raft.\n\nRequire Import VerdiRaft.RaftRefinementInterface.\n\nSection RaftMsgRefinementInterface.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Definition ghost_log : Type := list entry.\n\n  Lemma ghost_log_eq_dec : forall x y : ghost_log, {x = y} + {x <> y}.\n  Proof using. \n    decide equality.\n    apply entry_eq_dec.\n  Qed.\n\n  Definition write_ghost_log (h : name) (st : @data raft_refined_base_params) : ghost_log := log (snd st).\n\n  Instance ghost_log_params : MsgGhostMultiParams raft_refined_multi_params :=\n    {| ghost_msg := ghost_log ;\n       ghost_msg_eq_dec := ghost_log_eq_dec ;\n       ghost_msg_default := [] ;\n       write_ghost_msg := write_ghost_log\n    |}.\n\n  Definition raft_msg_refined_base_params := mgv_refined_base_params.\n  Definition raft_msg_refined_multi_params := mgv_refined_multi_params.\n  Definition raft_msg_refined_failure_params := mgv_refined_failure_params.\n\n  Hint Extern 3 (@BaseParams) => apply raft_msg_refined_base_params : typeclass_instances.\n  Hint Extern 3 (@MultiParams _) => apply raft_msg_refined_multi_params : typeclass_instances.\n  Hint Extern 3 (@FailureParams _ _) => apply raft_msg_refined_failure_params : typeclass_instances.\n\n  Inductive msg_refined_raft_intermediate_reachable : network -> Prop :=\n  | MRRIR_init : msg_refined_raft_intermediate_reachable step_async_init\n  | MRRIR_step_failure :\n      forall failed net failed' net' out,\n        msg_refined_raft_intermediate_reachable net ->\n        step_failure (failed, net) (failed', net') out ->\n        msg_refined_raft_intermediate_reachable net'\n  | MRRIR_handleInput :\n      forall net h inp gd out d l ps' st',\n        msg_refined_raft_intermediate_reachable net ->\n        handleInput h inp (snd (nwState net h)) = (out, d, l) ->\n        update_elections_data_input h inp (nwState net h) = gd ->\n        (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d) h') ->\n        (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                           In p' (send_packets h (add_ghost_msg h (gd, d) l))) ->\n        msg_refined_raft_intermediate_reachable (mkNetwork ps' st')\n  | MRRIR_handleMessage :\n      forall p net xs ys st' ps' gd d l,\n        msg_refined_raft_intermediate_reachable net ->\n        handleMessage (pSrc p) (pDst p) (snd (pBody p)) (snd (nwState net (pDst p))) = (d, l) ->\n        update_elections_data_net (pDst p) (pSrc p) (snd (pBody p)) (nwState net (pDst p)) = gd ->\n        nwPackets net = xs ++ p :: ys ->\n        (forall h, st' h = update name_eq_dec (nwState net) (pDst p) (gd, d) h) ->\n        (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                           In p' (send_packets (pDst p) (@add_ghost_msg _ _ ghost_log_params (pDst p) (gd, d) l))) ->\n        msg_refined_raft_intermediate_reachable (mkNetwork ps' st')\n  | MRRIR_doLeader :\n      forall net st' ps' h os gd d d' ms,\n        msg_refined_raft_intermediate_reachable net ->\n        doLeader d h = (os, d', ms) ->\n        nwState net h = (gd, d) ->\n        (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d') h') ->\n        (forall p, In p ps' -> In p (nwPackets net) \\/\n                         In p (send_packets h (add_ghost_msg h (gd, d') ms))) ->\n        msg_refined_raft_intermediate_reachable (mkNetwork ps' st')\n  | MRRIR_doGenericServer :\n      forall net st' ps' os gd d d' ms h,\n        msg_refined_raft_intermediate_reachable net ->\n        doGenericServer h d = (os, d', ms) ->\n        nwState net h = (gd, d) ->\n        (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d') h') ->\n        (forall p, In p ps' -> In p (nwPackets net) \\/\n                         In p (send_packets h (add_ghost_msg h (gd, d') ms))) ->\n        msg_refined_raft_intermediate_reachable (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_client_request (P : network -> Prop) :=\n    forall h net st' ps' gd out d l client id c,\n      handleClientRequest h (snd (nwState net h)) client id c = (out, d, l) ->\n      gd = update_elections_data_client_request h (nwState net h) client id c ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                         In p' (send_packets h (add_ghost_msg h (gd, d) l))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_timeout (P : network -> Prop) :=\n    forall net h st' ps' gd out d l,\n      handleTimeout h (snd (nwState net h)) = (out, d, l) ->\n      gd = update_elections_data_timeout h (nwState net h) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                               In p' (send_packets h (add_ghost_msg h (gd, d) l))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_append_entries (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t n pli plt es ci,\n      handleAppendEntries (pDst p) (snd (nwState net (pDst p))) t n pli plt es ci = (d, m) ->\n      gd = update_elections_data_appendEntries (pDst p) (nwState net (pDst p)) t n pli plt es ci ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update name_eq_dec (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         p' = mkPacket (pDst p) (pSrc p) (write_ghost_log (pDst p) (gd, d), m)) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_append_entries_reply (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t es res,\n      handleAppendEntriesReply (pDst p) (snd (nwState net (pDst p))) (pSrc p) t es res = (d, m) ->\n      gd = (fst (nwState net (pDst p))) ->\n      snd (pBody p) = AppendEntriesReply t es res ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update name_eq_dec (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         In p' (send_packets (pDst p) (@add_ghost_msg _ _ ghost_log_params (pDst p) (gd, d) m))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_request_vote (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t cid lli llt,\n      handleRequestVote (pDst p) (snd (nwState net (pDst p))) t (pSrc p) lli llt  = (d, m) ->\n      gd = update_elections_data_requestVote (pDst p) (pSrc p) t (pSrc p) lli llt (nwState net (pDst p)) ->\n      snd (pBody p) = RequestVote t cid lli llt ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update name_eq_dec (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         p' = mkPacket (pDst p) (pSrc p) (write_ghost_log (pDst p) (gd, d), m)) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_request_vote_reply (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d t v,\n      handleRequestVoteReply (pDst p) (snd (nwState net (pDst p))) (pSrc p) t v = d ->\n      gd = update_elections_data_requestVoteReply (pDst p) (pSrc p) t v (nwState net (pDst p)) ->\n      snd (pBody p) = RequestVoteReply t v ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update name_eq_dec (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys)) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_do_leader (P : network -> Prop) :=\n    forall net st' ps' gd d h os d' ms,\n      doLeader d h = (os, d', ms) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwState net h = (gd, d) ->\n      (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d') h') ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/\n                             In p (send_packets h (add_ghost_msg h (gd, d') ms))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_do_generic_server (P : network -> Prop) :=\n    forall net st' ps' gd d os d' ms h,\n      doGenericServer h d = (os, d', ms) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwState net h = (gd, d) ->\n      (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d') h') ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/\n                             In p (send_packets h (add_ghost_msg h (gd, d') ms))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_state_same_packet_subset (P : network -> Prop) :=\n    forall net net',\n      (forall h, nwState net h = nwState net' h) ->\n      (forall p, In p (nwPackets net') -> In p (nwPackets net)) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      P net'.\n\n  Definition msg_refined_raft_net_invariant_reboot (P : network -> Prop) :=\n    forall net net' gd d h d',\n      reboot d = d' ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwState net h = (gd, d) ->\n      (forall h', nwState net' h' = update name_eq_dec (nwState net) h (gd, d') h') ->\n      nwPackets net = nwPackets net' ->\n      P net'.\n\n  Definition msg_refined_raft_net_invariant_init (P : network -> Prop) :=\n    P step_async_init.\n  \n  Definition msg_refined_raft_net_invariant_client_request' (P : network -> Prop) :=\n    forall h net st' ps' gd out d l client id c,\n      handleClientRequest h (snd (nwState net h)) client id c = (out, d, l) ->\n      gd = update_elections_data_client_request h (nwState net h) client id c ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                         In p' (send_packets h (add_ghost_msg h (gd, d) l))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_timeout' (P : network -> Prop) :=\n    forall net h st' ps' gd out d l,\n      handleTimeout h (snd (nwState net h)) = (out, d, l) ->\n      gd = update_elections_data_timeout h (nwState net h) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                               In p' (send_packets h (add_ghost_msg h (gd, d) l))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_append_entries' (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t n pli plt es ci,\n      handleAppendEntries (pDst p) (snd (nwState net (pDst p))) t n pli plt es ci = (d, m) ->\n      gd = update_elections_data_appendEntries (pDst p) (nwState net (pDst p)) t n pli plt es ci ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update name_eq_dec (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         p' = mkPacket (pDst p) (pSrc p) (write_ghost_log (pDst p) (gd, d), m)) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_append_entries_reply' (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t es res,\n      handleAppendEntriesReply (pDst p) (snd (nwState net (pDst p))) (pSrc p) t es res = (d, m) ->\n      gd = (fst (nwState net (pDst p))) ->\n      snd (pBody p) = AppendEntriesReply t es res ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update name_eq_dec (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         In p' (send_packets (pDst p) (@add_ghost_msg _ _ ghost_log_params (pDst p) (gd, d) m))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_request_vote' (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t cid lli llt,\n      handleRequestVote (pDst p) (snd (nwState net (pDst p))) t (pSrc p) lli llt  = (d, m) ->\n      gd = update_elections_data_requestVote (pDst p) (pSrc p) t (pSrc p) lli llt (nwState net (pDst p)) ->\n      snd (pBody p) = RequestVote t cid lli llt ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update name_eq_dec (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         p' = mkPacket (pDst p) (pSrc p) (write_ghost_log (pDst p) (gd, d), m)) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_request_vote_reply' (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d t v,\n      handleRequestVoteReply (pDst p) (snd (nwState net (pDst p))) (pSrc p) t v = d ->\n      gd = update_elections_data_requestVoteReply (pDst p) (pSrc p) t v (nwState net (pDst p)) ->\n      snd (pBody p) = RequestVoteReply t v ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update name_eq_dec (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys)) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_do_leader' (P : network -> Prop) :=\n    forall net st' ps' gd d h os d' ms,\n      doLeader d h = (os, d', ms) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      nwState net h = (gd, d) ->\n      (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d') h') ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/\n                             In p (send_packets h (add_ghost_msg h (gd, d') ms))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_do_generic_server' (P : network -> Prop) :=\n    forall net st' ps' gd d os d' ms h,\n      doGenericServer h d = (os, d', ms) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      nwState net h = (gd, d) ->\n      (forall h', st' h' = update name_eq_dec (nwState net) h (gd, d') h') ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/\n                             In p (send_packets h (add_ghost_msg h (gd, d') ms))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_state_same_packet_subset' (P : network -> Prop) :=\n    forall net net',\n      (forall h, nwState net h = nwState net' h) ->\n      (forall p, In p (nwPackets net') -> In p (nwPackets net)) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      P net'.\n\n  Definition msg_refined_raft_net_invariant_reboot' (P : network -> Prop) :=\n    forall net net' gd d h d',\n      reboot d = d' ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable net' ->\n      nwState net h = (gd, d) ->\n      (forall h', nwState net' h' = update name_eq_dec (nwState net) h (gd, d') h') ->\n      nwPackets net = nwPackets net' ->\n      P net'.\n\n  Lemma msg_refined_raft_net_invariant_client_request'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_client_request net ->\n      msg_refined_raft_net_invariant_client_request' net.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_client_request, msg_refined_raft_net_invariant_client_request'.\n    intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_timeout'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_timeout net ->\n      msg_refined_raft_net_invariant_timeout' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_timeout, msg_refined_raft_net_invariant_timeout'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_append_entries'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_append_entries net ->\n      msg_refined_raft_net_invariant_append_entries' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_append_entries, msg_refined_raft_net_invariant_append_entries'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_append_entries_reply'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_append_entries_reply net ->\n      msg_refined_raft_net_invariant_append_entries_reply' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_append_entries_reply, msg_refined_raft_net_invariant_append_entries_reply'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_request_vote'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_request_vote net ->\n      msg_refined_raft_net_invariant_request_vote' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_request_vote, msg_refined_raft_net_invariant_request_vote'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_request_vote_reply'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_request_vote_reply net ->\n      msg_refined_raft_net_invariant_request_vote_reply' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_request_vote_reply, msg_refined_raft_net_invariant_request_vote_reply'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_do_leader'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_do_leader net ->\n      msg_refined_raft_net_invariant_do_leader' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_do_leader, msg_refined_raft_net_invariant_do_leader'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_do_generic_server'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_do_generic_server net ->\n      msg_refined_raft_net_invariant_do_generic_server' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_do_generic_server, msg_refined_raft_net_invariant_do_generic_server'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_reboot'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_reboot net ->\n      msg_refined_raft_net_invariant_reboot' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_reboot, msg_refined_raft_net_invariant_reboot'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_subset'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_state_same_packet_subset net ->\n      msg_refined_raft_net_invariant_state_same_packet_subset' net.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_state_same_packet_subset, msg_refined_raft_net_invariant_state_same_packet_subset'.\n    intuition eauto.\n  Qed.\n\n\n  Class raft_msg_refinement_interface : Prop :=\n    {\n      msg_refined_raft_net_invariant :\n        forall P net,\n          msg_refined_raft_net_invariant_init P ->\n          msg_refined_raft_net_invariant_client_request P ->\n          msg_refined_raft_net_invariant_timeout P ->\n          msg_refined_raft_net_invariant_append_entries P ->\n          msg_refined_raft_net_invariant_append_entries_reply P ->\n          msg_refined_raft_net_invariant_request_vote P ->\n          msg_refined_raft_net_invariant_request_vote_reply P ->\n          msg_refined_raft_net_invariant_do_leader P ->\n          msg_refined_raft_net_invariant_do_generic_server P ->\n          msg_refined_raft_net_invariant_state_same_packet_subset P ->\n          msg_refined_raft_net_invariant_reboot P ->\n          msg_refined_raft_intermediate_reachable net ->\n          P net;\n      msg_refined_raft_net_invariant' :\n        forall P net,\n          msg_refined_raft_net_invariant_init P ->\n          msg_refined_raft_net_invariant_client_request' P ->\n          msg_refined_raft_net_invariant_timeout' P ->\n          msg_refined_raft_net_invariant_append_entries' P ->\n          msg_refined_raft_net_invariant_append_entries_reply' P ->\n          msg_refined_raft_net_invariant_request_vote' P ->\n          msg_refined_raft_net_invariant_request_vote_reply' P ->\n          msg_refined_raft_net_invariant_do_leader' P ->\n          msg_refined_raft_net_invariant_do_generic_server' P ->\n          msg_refined_raft_net_invariant_state_same_packet_subset' P ->\n          msg_refined_raft_net_invariant_reboot' P ->\n          msg_refined_raft_intermediate_reachable net ->\n          P net;\n      msg_lift_prop :\n        forall (P : _ -> Prop),\n          (forall net, refined_raft_intermediate_reachable net -> P net) ->\n          (forall net, msg_refined_raft_intermediate_reachable net -> P (mgv_deghost net));\n      msg_lift_prop_all_the_way :\n        forall (P : _ -> Prop),\n          (forall net, raft_intermediate_reachable net -> P net) ->\n          (forall (net : @network _ raft_msg_refined_multi_params), msg_refined_raft_intermediate_reachable net -> P (deghost (mgv_deghost net)));\n      msg_lower_prop :\n        forall P : _ -> Prop,\n          (forall net, msg_refined_raft_intermediate_reachable net -> P (mgv_deghost net)) ->\n          (forall net, refined_raft_intermediate_reachable net -> P net);\n      msg_lower_prop_all_the_way :\n        forall P : _ -> Prop,\n          (forall (net : @network _ raft_msg_refined_multi_params), msg_refined_raft_intermediate_reachable net -> P (deghost (mgv_deghost net))) ->\n          (forall net, raft_intermediate_reachable net -> P net);\n      msg_deghost_spec :\n        forall (net : @network _ raft_msg_refined_multi_params) h,\n          nwState (mgv_deghost net) h = nwState net h;\n      msg_simulation_1 :\n        forall net,\n          msg_refined_raft_intermediate_reachable net ->\n          refined_raft_intermediate_reachable (mgv_deghost net)\n    }.\n\n\nEnd RaftMsgRefinementInterface.\n\n#[global]\nHint Extern 3 (@BaseParams) => apply raft_msg_refined_base_params : typeclass_instances.\n#[global]\nHint Extern 3 (@MultiParams _) => apply raft_msg_refined_multi_params : typeclass_instances.\n#[global]\nHint Extern 3 (@FailureParams _ _) => apply raft_msg_refined_failure_params : typeclass_instances.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft/RaftMsgRefinementInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.22892602194636885}}
{"text": "Require Import Coqlib.                                                                 \nRequire Import Maps.            \nRequire Import LibTactics.   \n        \nRequire Import Integers.  \nOpen Scope Z_scope.        \nImport ListNotations.  \n   \nSet Asymmetric Patterns.  \n        \nRequire Import state.    \nRequire Import language.  \n \nSet Implicit Arguments.    \nUnset Strict Implicit. \n               \nRequire Import logic.\n    \nRequire Import lemmas.\nRequire Import lemmas_ins.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nRequire Import integer_lemma.\n\nRequire Import sep_lemma.\nRequire Import reg_lemma.\nRequire Import derived_rule.\n\nRequire Import tm_dly_lemma.\n\nRequire Import code.\nRequire Import ctxswitch_spec.\n\nRequire Import lemma1.\n\nOpen Scope nat.\nOpen Scope code_scope.\nOpen Scope mem_scope.\n\nTheorem RegSaveProof :\n  forall vl,\n    spec |- {{ reg_save_pre vl }}\n             regsave\n           {{ reg_save_post vl }}.\nProof.\n  intros.\n  unfold reg_save_pre.\n  unfold reg_save_post.\n  hoare_ex_intro_pre.\n  eapply Pure_intro_rule.\n  introv Hlgvl.\n  renames x' to fmg, x'0 to fmo, x'1 to fml, x'2 to fmi.\n  renames x'3 to ctx, x'5 to vy, x'7 to id, x'8 to vi, x'9 to F.\n  renames x'4 to l, x'6 to retf.\n  hoare_lift_pre 5.\n  eapply Pure_intro_rule.\n  introv Hpure.\n  destruct Hpure as [Hsp [Hctx_addr Hretf] ].\n  destruct fmg, fmo, fml, fmi.\n  simpl in Hsp.\n  simpl in Hretf.\n  inversion Hsp; subst.\n  inversion Hretf; subst.\n  destruct ctx as [l ctx].\n  simpl get_ctx_addr.\n  destruct ctx as [ [ [rl ri] rg] ry].\n  hoare_lift_pre 2.\n  unfold context at 1.\n  unfold context' at 1.\n  eapply backward_rule.\n  introv Hs.\n  asrt_to_line_in Hs 3.\n  eauto.\n  unfold regsave.\n \n  save_reg_unfold.\n  hoare_lift_pre 2.\n  save_reg_unfold.\n  hoare_lift_pre 3.\n  save_reg_unfold.\n  eapply backward_rule.\n  introv Hs.\n  unfold save_reg at 1 in Hs.\n  asrt_to_line_in Hs 8.\n  simpl_sep_liftn_in Hs 9.\n  simpl_sep_liftn_in Hs 9.\n  unfold save_reg at 1 in Hs.\n  asrt_to_line_in Hs 8.\n  simpl_sep_liftn_in Hs 9.\n  simpl_sep_liftn_in Hs 17.\n  unfold save_reg at 1 in Hs.\n  asrt_to_line_in Hs 4.\n  simpl_sep_liftn_in Hs 5.\n  eauto.\n\n  Ltac solve_st_ctx :=\n    eapply seq_rule;\n    [TimReduce_simpl; eapply st_rule_reg; eauto;\n    try solve [simpl; repeat (rewrite Int.add_assoc); eauto] | simpl get_genreg_val].\n  \n  (** st l0 (l5 + OS_L0_OFFSET) *)\n  unfold OS_L0_OFFSET.\n  hoare_lift_pre 22.\n  solve_st_ctx.\n  simpl.\n  rewrite in_range0; eauto.\n  rewrite Int.add_zero; eauto.\n\n  (** st l1 (l5 + OS_L1_OFFSET) *)\n  unfold OS_L1_OFFSET.\n  hoare_lift_pre 3.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st l2 (l5 + OS_L2_OFFSET) *)\n  unfold OS_L2_OFFSET.\n  hoare_lift_pre 4.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st l3 (l5 + OS_L3_OFFSET) *)\n  unfold OS_L3_OFFSET.\n  hoare_lift_pre 5.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st i0 (l5 + OS_I0_OFFSET) *)\n  unfold OS_I0_OFFSET.\n  hoare_lift_pre 6.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st i1 (l5 + OS_I1_OFFSET) *)\n  unfold OS_I1_OFFSET.\n  hoare_lift_pre 7.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st i2 (l5 + OS_I2_OFFSET) *)\n  unfold OS_I2_OFFSET.\n  hoare_lift_pre 8.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st i3 (l5 + OS_I3_OFFSET) *)\n  unfold OS_I3_OFFSET.\n  hoare_lift_pre 9.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st i4 (l5 + OS_I4_OFFSET) *)\n  unfold OS_I4_OFFSET.\n  hoare_lift_pre 10.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st i5 (l5 + OS_I5_OFFSET) *)\n  unfold OS_I5_OFFSET.\n  hoare_lift_pre 11.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st i6 (l5 + OS_I6_OFFSET) *)\n  unfold OS_I6_OFFSET.\n  hoare_lift_pre 12.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st i7 (l5 + OS_I7_OFFSET) *)\n  unfold OS_I2_OFFSET.\n  hoare_lift_pre 13.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** rd y l6 *)\n  hoare_lift_pre 23.\n  hoare_lift_pre 2.\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply rd_rule_reg; eauto.\n  simpl upd_genreg.\n\n  (** st l6 (l5 + OS_Y_OFFSET) *)\n  hoare_lift_pre 23.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st g1 (l5 + OS_G1_OFFSET) *)\n  unfold OS_G1_OFFSET. \n  hoare_lift_pre 17.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st g2 (l5 + OS_G2_OFFSET) *)\n  unfold OS_G2_OFFSET. \n  hoare_lift_pre 18.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st g3 (l5 + OS_G3_OFFSET) *)\n  unfold OS_G3_OFFSET. \n  hoare_lift_pre 19.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st g4 (l5 + OS_G4_OFFSET) *)\n  unfold OS_G4_OFFSET. \n  hoare_lift_pre 20.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n \n  (** st g5 (l5 + OS_G5_OFFSET) *)\n  unfold OS_G5_OFFSET. \n  hoare_lift_pre 21.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st g6 (l5 + OS_G6_OFFSET) *)\n  unfold OS_G6_OFFSET. \n  hoare_lift_pre 22.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  (** st g7 (l5 + OS_G7_OFFSET) *)\n  unfold OS_G7_OFFSET. \n  hoare_lift_pre 23.\n  hoare_lift_pre 2.\n  solve_st_ctx.\n\n  eapply retl_rule; eauto.\n  TimReduce_simpl.\n  eapply nop_rule; eauto.\n  introv Hs.\n  sep_ex_intro.\n  eapply sep_pure_l_intro; eauto.\n  simpl update_frame.\n  sep_cancel1 1 1. \n  instantiate (1 :=\n                 (l, (w15 :: w16 :: w17 :: w18 :: nil,\n                      w23 :: w24 :: w25 :: w26 :: w27 :: w28 :: w29 :: w30 :: nil,\n                      a11 :: w0 :: w1 :: w2 :: w3 :: w4 :: w5 :: w6 :: nil, vy))\n              ).\n  sep_cancel1 9 2.\n  sep_cancel1 22 2.\n  unfold context, context'.\n  asrt_to_line 3.\n  unfold save_reg at 1.\n  asrt_to_line 4.\n  simpl_sep_liftn 5.\n  simpl_sep_liftn 5.\n  unfold save_reg at 1.\n  asrt_to_line 8.\n  simpl_sep_liftn 9.\n  simpl_sep_liftn 13.\n  unfold save_reg at 1.\n  asrt_to_line 8.\n  simpl_sep_liftn 9.\n\n  sep_cancel1 1 8.\n  sep_cancel1 1 7.\n  sep_cancel1 1 6.\n  sep_cancel1 1 5.\n  sep_cancel1 1 4.\n  sep_cancel1 1 3.\n  sep_cancel1 1 2.\n  sep_cancel1 1 14.\n  sep_cancel1 13 1.\n  sep_cancel1 1 8.\n  sep_cancel1 1 7.\n  sep_cancel1 1 6.\n  sep_cancel1 1 5.\n  sep_cancel1 1 4.\n  sep_cancel1 1 3.\n  sep_cancel1 1 2.\n  sep_cancel1 1 1.\n  sep_cancel1 1 4.\n  sep_cancel1 1 3.\n  sep_cancel1 1 2.\n  sep_cancel1 1 1.\n  instantiate (1 := Aemp).\n  eapply astar_emp_intro_r; eauto.\n\n  eapply astar_emp_elim_r.\n  eapply sep_pure_l_intro; eauto.\n  simpl.\n  repeat (split; eauto).\n\n  unfold fretSta.\n  TimReduce_simpl.\n  introv Hs Hs'.\n  destruct_state s.\n  destruct_state s'.\n  eapply getR_eq_get_genreg_val1 with (rr := r15) in Hs.\n  simpl get_genreg_val in Hs.\n  sep_ex_elim_in Hs'.\n  eapply sep_pure_l_elim in Hs'.\n  destruct Hs' as [Hlgvl1 Hs'].\n  inversion Hlgvl1; subst.\n  simpl update_frame in Hs'.\n  eapply getR_eq_get_genreg_val1 with (rr := r15) in Hs'.\n  simpl get_genreg_val in Hs'.\n  simpl.\n  clear - Hs Hs'.\n  unfolds get_R.\n  destruct (r r15); tryfalse.\n  inversion Hs; subst.\n  destruct (r0 r15); tryfalse.\n  inversion Hs'; subst.\n  eauto.\nQed.\n\n  ", "meta": {"author": "luckywangwang", "repo": "CertiSparc", "sha": "b5c4ff0d1b723537a645b6c5578b8749ed1c813e", "save_path": "github-repos/coq/luckywangwang-CertiSparc", "path": "github-repos/coq/luckywangwang-CertiSparc/CertiSparc-b5c4ff0d1b723537a645b6c5578b8749ed1c813e/coqimp/contextswitch/proof/RegSaveProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2289175744627975}}
{"text": "(** * Basic Attention Token contract *)\n(** Proofs for BAToken contract defined in [ConCert.Examples.BAT.BAT]. *)\nFrom Coq Require Import Lia.\nFrom Coq Require Import List. Import ListNotations.\nFrom Coq Require Import ZArith_base.\nFrom ConCert.Utils Require Import Automation.\nFrom ConCert.Utils Require Import Extras.\nFrom ConCert.Utils Require Import RecordUpdate.\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import BuildUtils.\nFrom ConCert.Execution Require Import Containers.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Execution Require Import ContractCommon.\nFrom ConCert.Execution Require Import ResultMonad.\nFrom ConCert.Examples.BAT Require Import BATCommon.\nFrom ConCert.Examples.BAT Require Import BAT.\nFrom ConCert.Examples.EIP20 Require EIP20Token.\nFrom ConCert.Examples.EIP20 Require EIP20TokenCorrect.\n\n\n\n(** * Contract properties *)\nSection Theories.\n  (* begind hide *)\n  Context {BaseTypes : ChainBase}.\n  Open Scope N_scope.\n  (* Tactics to simplify proof steps *)\n  Tactic Notation \"contract_simpl\" := contract_simpl @receive @init.\n\n  Ltac destruct_message :=\n    repeat match goal with\n    | msg : option Msg |- _ => destruct msg\n    | msg : Msg |- _ => destruct msg\n    | msg : EIP20Token.Msg |- _ => destruct msg\n    | H : Blockchain.receive _ _ _ _ None = Ok _ |- _ => now contract_simpl\n    | H : receive _ _ _ None = Ok _ |- _ => now contract_simpl\n    end.\n  (* end hide *)\n\n\n\n  (** ** Transfer correct *)\n\n  Lemma try_transfer_balance_correct : forall prev_state new_state chain ctx to amount new_acts,\n    receive chain ctx prev_state (Some (transfer to amount)) = Ok (new_state, new_acts) ->\n    EIP20TokenCorrect.transfer_balance_update_correct (token_state prev_state) (token_state new_state)\n      ctx.(ctx_from) to amount = true.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_transfer_balance_correct; eauto.\n  Qed.\n\n  Lemma try_transfer_preserves_total_supply : forall prev_state new_state chain ctx to amount new_acts,\n    receive chain ctx prev_state (Some (transfer to amount)) = Ok (new_state, new_acts) ->\n      (total_supply prev_state) = (total_supply new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_transfer_preserves_total_supply; eauto.\n  Qed.\n\n  Lemma try_transfer_preserves_allowances : forall prev_state new_state chain ctx to amount new_acts,\n    receive chain ctx prev_state (Some (transfer to amount)) = Ok (new_state, new_acts) ->\n      (allowances prev_state) = (allowances new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_transfer_preserves_allowances; eauto.\n  Qed.\n\n  Lemma try_transfer_preserves_other_balances : forall prev_state new_state chain ctx to amount new_acts,\n    receive chain ctx prev_state (Some (transfer to amount)) = Ok (new_state, new_acts) ->\n      forall account, account <> (ctx_from ctx) -> account <> to ->\n        FMap.find account (balances prev_state) = FMap.find account (balances new_state).\n  Proof.\n    intros * receive_some account account_not_sender account_not_to.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_transfer_preserves_other_balances; eauto.\n  Qed.\n\n  Lemma try_transfer_is_some : forall state chain ctx to amount,\n    (ctx_amount ctx <= 0)%Z /\\\n    amount <= with_default 0 (FMap.find (ctx_from ctx) (balances state))\n      <-> isOk (receive chain ctx state (Some (transfer to amount))) = true.\n  Proof.\n    intros.\n    unfold balances. cbn.\n    destruct_match eqn:receive;\n      now erewrite EIP20TokenCorrect.try_transfer_is_some, receive.\n  Qed.\n\n\n\n  (** ** Transfer_from correct *)\n\n  Lemma try_transfer_from_balance_correct : forall prev_state new_state chain ctx from to amount new_acts,\n    receive chain ctx prev_state (Some (transfer_from from to amount)) = Ok (new_state, new_acts) ->\n    EIP20TokenCorrect.transfer_balance_update_correct (token_state prev_state) (token_state new_state) from to amount = true /\\\n    EIP20TokenCorrect.transfer_from_allowances_update_correct (token_state prev_state) (token_state new_state) from ctx.(ctx_from) amount = true.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_transfer_from_balance_correct; eauto.\n  Qed.\n\n  Lemma try_transfer_from_preserves_total_supply : forall prev_state new_state chain ctx from to amount new_acts,\n    receive chain ctx prev_state (Some (transfer_from from to amount)) = Ok (new_state, new_acts) ->\n      (total_supply prev_state) = (total_supply new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_transfer_from_preserves_total_supply; eauto.\n  Qed.\n\n  Lemma try_transfer_from_preserves_other_balances : forall prev_state new_state chain ctx from to amount new_acts,\n    receive chain ctx prev_state (Some (transfer_from from to amount)) = Ok (new_state, new_acts) ->\n      forall account, account <> from -> account <> to ->\n        FMap.find account (balances prev_state) = FMap.find account (balances new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_transfer_from_preserves_other_balances; eauto.\n  Qed.\n\n  Lemma try_transfer_from_preserves_other_allowances : forall prev_state new_state chain ctx from to amount new_acts,\n    receive chain ctx prev_state (Some (transfer_from from to amount)) = Ok (new_state, new_acts) ->\n      forall account, account <> from ->\n        FMap.find account (allowances prev_state) = FMap.find account (allowances new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_transfer_from_preserves_other_allowances; eauto.\n  Qed.\n\n  Lemma try_transfer_from_preserves_other_allowance : forall prev_state new_state chain ctx from to amount new_acts,\n    receive chain ctx prev_state (Some (transfer_from from to amount)) = Ok (new_state, new_acts) ->\n      forall account, account <> (ctx_from ctx) ->\n        get_allowance (token_state prev_state) from account = get_allowance (token_state new_state) from account.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_transfer_from_preserves_other_allowance; eauto.\n  Qed.\n\n  Lemma try_transfer_from_is_some : forall state chain ctx from to amount,\n    let get_allowance_ account := FMap.find account (with_default (@FMap.empty (FMap Address TokenValue) _) (FMap.find from (allowances state))) in\n    (ctx_amount ctx >? 0)%Z = false ->\n    isSome (FMap.find from (allowances state)) = true\n    /\\ isSome (get_allowance_ (ctx_from ctx)) = true\n    /\\ amount <= with_default 0 (FMap.find from (balances state))\n    /\\ amount <= with_default 0 (get_allowance_ (ctx_from ctx))\n      <-> isOk (receive chain ctx state (Some (transfer_from from to amount))) = true.\n  Proof.\n    intros * amount_zero.\n    unfold balances, allowances, get_allowance_. cbn.\n    destruct_match eqn:receive;\n      now erewrite EIP20TokenCorrect.try_transfer_from_is_some, receive.\n  Qed.\n\n\n\n  (** ** Approve correct *)\n\n  Lemma try_approve_allowance_correct : forall prev_state new_state chain ctx delegate amount new_acts,\n    receive chain ctx prev_state (Some (approve delegate amount)) = Ok (new_state, new_acts) ->\n    EIP20TokenCorrect.approve_allowance_update_correct (token_state new_state) ctx.(ctx_from) delegate amount = true.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_approve_allowance_correct; eauto.\n  Qed.\n\n  Lemma try_approve_preserves_total_supply : forall prev_state new_state chain ctx delegate amount new_acts,\n    receive chain ctx prev_state (Some (approve delegate amount)) = Ok (new_state, new_acts) ->\n      (total_supply prev_state) = (total_supply new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_approve_preserves_total_supply; eauto.\n  Qed.\n\n  Lemma try_approve_preserves_balances : forall prev_state new_state chain ctx delegate amount new_acts,\n    receive chain ctx prev_state (Some (approve delegate amount)) = Ok (new_state, new_acts) ->\n      (balances prev_state) = (balances new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_approve_preserves_balances; eauto.\n  Qed.\n\n  Lemma try_approve_preserves_other_allowances : forall prev_state new_state chain ctx delegate amount new_acts,\n    receive chain ctx prev_state (Some (approve delegate amount)) = Ok (new_state, new_acts) ->\n      forall account, account <> (ctx_from ctx) ->\n        FMap.find account (allowances prev_state) = FMap.find account (allowances new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_approve_preserves_other_allowances; eauto.\n  Qed.\n\n  Lemma try_approve_preserves_other_allowance : forall prev_state new_state chain ctx delegate amount new_acts,\n    receive chain ctx prev_state (Some (approve delegate amount)) = Ok (new_state, new_acts) ->\n      forall account, account <> delegate ->\n        get_allowance (token_state prev_state) (ctx_from ctx) account = get_allowance (token_state new_state) (ctx_from ctx) account.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_approve_preserves_other_allowance; eauto.\n  Qed.\n\n  Lemma try_approve_is_some : forall state chain ctx delegate amount,\n    (ctx_amount ctx >? 0)%Z = false <-> isOk (receive chain ctx state (Some (approve delegate amount))) = true.\n  Proof.\n    intros.\n    cbn.\n    destruct_match eqn:receive;\n      now erewrite EIP20TokenCorrect.try_approve_is_some, receive.\n  Qed.\n\n\n\n  (** ** EIP20 functions only changes token_state *)\n\n  Lemma eip_only_changes_token_state : forall prev_state new_state chain ctx m new_acts,\n    receive chain ctx prev_state (Some (tokenMsg m)) = Ok (new_state, new_acts) ->\n      prev_state<|token_state := (token_state new_state)|> = new_state.\n  Proof.\n    intros * receive_some.\n    now contract_simpl.\n  Qed.\n\n\n\n  (** ** EIP20 functions not payable *)\n\n  Lemma eip20_not_payable : forall prev_state new_state chain ctx m new_acts,\n    receive chain ctx prev_state (Some (tokenMsg m)) = Ok (new_state, new_acts) ->\n      (ctx_amount ctx <= 0)%Z.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now eapply EIP20TokenCorrect.EIP20_not_payable.\n  Qed.\n\n\n\n  (** ** EIP20 functions produces no acts *)\n\n  Lemma eip20_new_acts_correct : forall prev_state new_state chain ctx m new_acts,\n    receive chain ctx prev_state (Some (tokenMsg m)) = Ok (new_state, new_acts) ->\n      new_acts = [].\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now eapply EIP20TokenCorrect.EIP20_no_acts.\n  Qed.\n\n\n\n  (** ** Create_tokens correct *)\n\n  Lemma try_create_tokens_balance_correct : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some create_tokens) = Ok (new_state, new_acts) ->\n      with_default 0 (FMap.find (ctx_from ctx) (balances prev_state)) =\n      with_default 0 (FMap.find (ctx_from ctx) (balances new_state)) - ((Z.to_N (ctx_amount ctx)) * (tokenExchangeRate prev_state)).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    setoid_rewrite EIP20TokenCorrect.add_is_partial_alter_plus; auto.\n    destruct (FMap.find (ctx_from ctx) (balances prev_state)) eqn:from_balance;\n      setoid_rewrite from_balance;\n      setoid_rewrite FMap.find_add; cbn;\n      now rewrite N.add_sub.\n  Qed.\n\n  Lemma try_create_tokens_total_supply_correct : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some create_tokens) = Ok (new_state, new_acts) ->\n      (total_supply prev_state) + ((Z.to_N (ctx_amount ctx)) * (tokenExchangeRate prev_state)) =\n      (total_supply new_state).\n  Proof.\n    intros * receive_some.\n    now contract_simpl.\n  Qed.\n\n  Lemma try_create_tokens_preserves_other_balances : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some create_tokens) = Ok (new_state, new_acts) ->\n      forall account, account <> (ctx_from ctx) ->\n        FMap.find account (balances prev_state) = FMap.find account (balances new_state).\n  Proof.\n    intros * receive_some account account_not_sender.\n    contract_simpl.\n    setoid_rewrite EIP20TokenCorrect.add_is_partial_alter_plus; auto.\n    now setoid_rewrite FMap.find_add_ne.\n  Qed.\n\n  Lemma try_create_tokens_preserves_allowances : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some create_tokens) = Ok (new_state, new_acts) ->\n      (allowances prev_state) = (allowances new_state).\n  Proof.\n    intros * receive_some.\n    now contract_simpl.\n  Qed.\n\n  Lemma try_create_tokens_only_change_token_state : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some create_tokens) = Ok (new_state, new_acts) ->\n      prev_state<|token_state := (token_state new_state)|> = new_state.\n  Proof.\n    intros * receive_some.\n    now contract_simpl.\n  Qed.\n\n  Lemma try_create_tokens_is_some : forall state chain ctx,\n    Z.lt 0 (ctx_amount ctx)\n    /\\ (isFinalized state) = false\n    /\\ ((fundingStart state) <= (current_slot chain))%nat\n    /\\ ((current_slot chain) <= (fundingEnd state))%nat\n    /\\ (total_supply state) + ((Z.to_N (ctx_amount ctx)) * (tokenExchangeRate state)) <= (tokenCreationCap state)\n      <-> exists x y, receive chain ctx state (Some create_tokens) = Ok (x, y).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl;\n      propify;\n      try easy.\n    - rename H4 into receive_some.\n      destruct_match eqn:funding_active in receive_some.\n      destruct_match eqn:amount_nonnegative in receive_some.\n      destruct_match eqn:cap_not_hit in receive_some; try congruence.\n      all : contract_simpl;\n        propify;\n        destruct_hyps;\n        destruct_or_hyps; try easy.\n  Qed.\n\n  Lemma try_create_tokens_acts_correct : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some create_tokens) = Ok (new_state, new_acts) ->\n      new_acts = [].\n  Proof.\n    intros.\n    contract_simpl.\n  Qed.\n\n  Lemma try_create_tokens_amount_correct : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some create_tokens) = Ok (new_state, new_acts) ->\n      Z.lt 0 ctx.(ctx_amount).\n  Proof.\n    intros.\n    contract_simpl.\n    now rewrite Z.leb_gt in *.\n  Qed.\n\n\n\n  (** ** Finalize correct *)\n\n  Lemma try_finalize_isFinalized_correct : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some finalize) = Ok (new_state, new_acts) ->\n      (isFinalized prev_state) = false /\\ (isFinalized new_state) = true.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    split; auto.\n    now propify.\n  Qed.\n\n  Lemma try_finalize_only_change_isFinalized : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some finalize) = Ok (new_state, new_acts) ->\n      prev_state<|isFinalized := (isFinalized new_state)|> = new_state.\n  Proof.\n    intros * receive_some.\n    now contract_simpl.\n  Qed.\n\n  Lemma try_finalize_preserves_total_supply : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some finalize) = Ok (new_state, new_acts) ->\n      (total_supply prev_state) = (total_supply new_state).\n  Proof.\n    intros * receive_some.\n    apply try_finalize_only_change_isFinalized in receive_some.\n    now rewrite <- receive_some.\n  Qed.\n\n  Lemma try_finalize_is_some : forall state chain ctx,\n    (ctx_amount ctx >? 0)%Z = false\n    /\\ (isFinalized state) = false\n    /\\ (ctx_from ctx) = (fundDeposit state)\n    /\\ (tokenCreationMin state) <= (total_supply state)\n    /\\ ((fundingEnd state) < (current_slot chain) \\/ (tokenCreationCap state) = (total_supply state))%nat\n      <-> exists x y, receive chain ctx state (Some finalize) = Ok (x, y).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl;\n      propify;\n      destruct_or_hyps;\n      try easy;\n      try now destruct_address_eq.\n  Qed.\n\n  Lemma try_finalize_acts_correct : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some finalize) = Ok (new_state, new_acts) ->\n      new_acts =\n      [act_transfer\n        (fundDeposit prev_state)\n        (ctx_contract_balance ctx)\n      ].\n  Proof.\n    intros.\n    contract_simpl.\n  Qed.\n\n\n\n  (** ** Refund correct *)\n\n  Lemma try_refund_balance_correct : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some refund) = Ok (new_state, new_acts) ->\n      with_default 0 (FMap.find (ctx_from ctx) (balances new_state)) = 0.\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now setoid_rewrite FMap.find_add.\n  Qed.\n\n  Lemma try_refund_total_supply_correct : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some refund) = Ok (new_state, new_acts) ->\n      (total_supply prev_state) - (with_default 0 (FMap.find (ctx_from ctx) (balances prev_state))) =\n      (total_supply new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    now result_to_option.\n  Qed.\n\n  Lemma try_refund_preserves_other_balances : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some refund) = Ok (new_state, new_acts) ->\n      forall account, account <> (ctx_from ctx) ->\n        FMap.find account (balances prev_state) = FMap.find account (balances new_state).\n  Proof.\n    intros * receive_some account account_not_sender.\n    contract_simpl.\n    now setoid_rewrite FMap.find_add_ne.\n  Qed.\n\n  Lemma try_refund_preserves_allowances : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some refund) = Ok (new_state, new_acts) ->\n      (allowances prev_state) = (allowances new_state).\n  Proof.\n    intros * receive_some.\n    now contract_simpl.\n  Qed.\n\n  Lemma try_refund_only_change_token_state : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some refund) = Ok (new_state, new_acts) ->\n      prev_state<|token_state := (token_state new_state)|> = new_state.\n  Proof.\n    intros * receive_some.\n    now contract_simpl.\n  Qed.\n\n  Lemma try_refund_is_some : forall state chain ctx,\n    (ctx_amount ctx >? 0)%Z = false\n    /\\ (isFinalized state) = false\n    /\\ ((fundingEnd state) < (current_slot chain))%nat\n    /\\ (total_supply state) < (tokenCreationMin state)\n    /\\ (ctx_from ctx) <> (batFundDeposit state)\n    /\\ 0 < with_default 0 (FMap.find (ctx_from ctx) (balances state))\n      <-> exists x y, receive chain ctx state (Some refund) = Ok (x, y).\n  Proof.\n    split;\n      intros;\n      destruct_hyps;\n      contract_simpl;\n      propify;\n      destruct_or_hyps;\n      try result_to_option;\n      subst; cbn in *;\n      try easy;\n      now destruct_address_eq.\n  Qed.\n\n  Lemma try_refund_acts_correct : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some refund) = Ok (new_state, new_acts) ->\n      new_acts =\n      [act_transfer\n        (ctx_from ctx)\n        (Z.of_N (with_default 0 (FMap.find (ctx_from ctx) (balances prev_state)) / (tokenExchangeRate prev_state)))\n      ].\n  Proof.\n    intros.\n    contract_simpl.\n    now result_to_option.\n  Qed.\n\n\n\n  (** ** Init correct *)\n\n  Lemma init_bat_balance_correct : forall state chain ctx setup,\n    init chain ctx setup = Ok (state) ->\n      with_default 0 (FMap.find state.(batFundDeposit) (balances state)) = setup.(_batFund).\n  Proof.\n    intros * init_some.\n    contract_simpl.\n    now setoid_rewrite FMap.find_add.\n  Qed.\n\n  Lemma init_other_balances_correct : forall state chain ctx setup,\n    init chain ctx setup = Ok (state) ->\n      forall account, account <> state.(batFundDeposit) ->\n      with_default 0 (FMap.find account (balances state)) = 0.\n  Proof.\n    intros * init_some account account_not_funddeposit.\n    contract_simpl.\n    now setoid_rewrite FMap.find_add_ne.\n  Qed.\n\n  Lemma init_allowances_correct : forall state chain ctx setup,\n    init chain ctx setup = Ok (state) ->\n      (allowances state) = FMap.empty.\n  Proof.\n    intros * init_some.\n    now contract_simpl.\n  Qed.\n\n  Lemma init_isFinalized_correct : forall state chain ctx setup,\n    init chain ctx setup = Ok (state) ->\n      state.(isFinalized) = false.\n  Proof.\n    intros * init_some.\n    now contract_simpl.\n  Qed.\n\n  Lemma init_total_supply_correct : forall state chain ctx setup,\n    init chain ctx setup = Ok (state) ->\n      (total_supply state) = setup.(_batFund).\n  Proof.\n    intros * init_some.\n    now contract_simpl.\n  Qed.\n\n  Lemma init_constants_correct : forall state chain ctx setup,\n    init chain ctx setup = Ok (state) ->\n      state.(fundDeposit) = setup.(_fundDeposit)\n      /\\ state.(batFundDeposit) = setup.(_batFundDeposit)\n      /\\ state.(fundingStart) = setup.(_fundingStart)\n      /\\ state.(fundingEnd) = setup.(_fundingEnd)\n      /\\ state.(tokenExchangeRate) = setup.(_tokenExchangeRate)\n      /\\ state.(tokenCreationCap) = setup.(_tokenCreationCap)\n      /\\ state.(tokenCreationMin) = setup.(_tokenCreationMin)\n      /\\ state.(initSupply) = setup.(_batFund).\n  Proof.\n    intros * init_some.\n    now contract_simpl.\n  Qed.\n\n\n\n  (** ** Functions preserve sum of balances *)\n\n  Lemma try_transfer_preserves_balances_sum : forall prev_state new_state chain ctx to amount new_acts,\n    receive chain ctx prev_state (Some (transfer to amount)) = Ok (new_state, new_acts) ->\n      (sum_balances prev_state) = (sum_balances new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_transfer_preserves_balances_sum; eauto.\n  Qed.\n\n  Lemma try_transfer_from_preserves_balances_sum : forall prev_state new_state chain ctx from to amount new_acts,\n    receive chain ctx prev_state (Some (transfer_from from to amount)) = Ok (new_state, new_acts) ->\n      (sum_balances prev_state) = (sum_balances new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_transfer_from_preserves_balances_sum; eauto.\n  Qed.\n\n  Lemma try_approve_preserves_balances_sum : forall prev_state new_state chain ctx delegate amount new_acts,\n    receive chain ctx prev_state (Some (approve delegate amount)) = Ok (new_state, new_acts) ->\n      (sum_balances prev_state) = (sum_balances new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    eapply EIP20TokenCorrect.try_approve_preserves_balances_sum; eauto.\n  Qed.\n\n  Lemma try_create_tokens_update_balances_sum : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some create_tokens) = Ok (new_state, new_acts) ->\n      (sum_balances prev_state) + ((Z.to_N (ctx_amount ctx)) * (tokenExchangeRate prev_state)) = (sum_balances new_state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    unfold EIP20Token.sum_balances. cbn in *.\n    setoid_rewrite EIP20TokenCorrect.add_is_partial_alter_plus; auto.\n    destruct (FMap.find (ctx_from ctx) (balances prev_state)) eqn:from_balance.\n    - setoid_rewrite from_balance.\n      setoid_rewrite FMap.elements_add_existing; eauto.\n      erewrite sumN_split with (x := (ctx_from ctx, _)) (y := (ctx_from ctx, _)) by eauto.\n      now rewrite sumN_swap, fin_maps.map_to_list_delete, N.add_comm.\n    - setoid_rewrite from_balance.\n      setoid_rewrite FMap.elements_add; auto.\n      now rewrite N.add_comm.\n  Qed.\n\n  Lemma try_finalize_preserves_balances_sum : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some finalize) = Ok (new_state, new_acts) ->\n      (sum_balances prev_state) = (sum_balances new_state).\n  Proof.\n    intros * receive_some.\n    now contract_simpl.\n  Qed.\n\n  Lemma try_refund_update_balances_sum : forall prev_state new_state chain ctx new_acts,\n    receive chain ctx prev_state (Some refund) = Ok (new_state, new_acts) ->\n      (sum_balances prev_state) = (sum_balances new_state) + (with_default 0 (FMap.find (ctx_from ctx) (balances prev_state))).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    unfold EIP20Token.sum_balances.\n    result_to_option.\n    setoid_rewrite FMap.elements_add_existing; eauto.\n    simpl with_default.\n    change t with ((fun '(_, v) => v) (ctx_from ctx, t)).\n    now rewrite sumN_inv, sumN_swap, fin_maps.map_to_list_delete.\n  Qed.\n\n  Lemma init_preserves_balances_sum : forall state chain ctx setup,\n    init chain ctx setup = Ok (state) ->\n      (sum_balances state) = (total_supply state).\n  Proof.\n    intros * receive_some.\n    contract_simpl.\n    unfold EIP20Token.sum_balances.\n    subst. cbn.\n    setoid_rewrite FMap.elements_add; auto.\n    rewrite fin_maps.map_to_list_empty.\n    now apply N.add_0_r.\n  Qed.\n\n\n\n  (** ** Sum of balances always equals total supply *)\n\n  (** In any reachable state the sum of token balance\n      will be equal to the total supply of tokens *)\n  Lemma sum_balances_eq_total_supply bstate caddr :\n    reachable bstate ->\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate,\n      contract_state bstate caddr = Some cstate\n      /\\ (total_supply cstate) = (sum_balances cstate).\n  Proof.\n    intros * reach deployed.\n    apply (lift_contract_state_prop contract);\n      intros *; auto; clear reach deployed bstate caddr.\n    - intros init_some.\n      now apply init_preserves_balances_sum in init_some.\n    - intros IH receive_some.\n      unfold Blockchain.receive in receive_some.\n      cbn in receive_some.\n      destruct_message.\n      + now erewrite <- try_transfer_preserves_balances_sum,\n                    <- try_transfer_preserves_total_supply.\n      + now erewrite <- try_transfer_from_preserves_balances_sum,\n                    <- try_transfer_from_preserves_total_supply.\n      + now erewrite <- try_approve_preserves_balances_sum,\n                    <- try_approve_preserves_total_supply.\n      + now erewrite <- try_create_tokens_update_balances_sum,\n                    <- try_create_tokens_total_supply_correct; eauto.\n      + now erewrite <- try_finalize_preserves_balances_sum,\n                    <- try_finalize_preserves_total_supply.\n      + apply try_refund_update_balances_sum in receive_some as balance_sum.\n        now apply try_refund_total_supply_correct in receive_some.\n  Qed.\n\n\n\n  (** ** Total supply can only grow before funding fails *)\n\n  (** If funding period is active or funding goal was hit then the\n      total supply of tokens cannot decrease *)\n  Lemma receive_total_supply_increasing : forall prev_state new_state chain ctx msg new_acts,\n    ((current_slot chain) <= (fundingEnd prev_state))%nat \\/ tokenCreationMin prev_state <= total_supply prev_state->\n    receive chain ctx prev_state msg = Ok (new_state, new_acts) ->\n        (total_supply prev_state) <= (total_supply new_state).\n  Proof.\n    intros * funding_active receive_some.\n    destruct_message.\n    - apply try_transfer_preserves_total_supply in receive_some. lia.\n    - apply try_transfer_from_preserves_total_supply in receive_some. lia.\n    - apply try_approve_preserves_total_supply in receive_some. lia.\n    - apply try_create_tokens_total_supply_correct in receive_some.\n      rewrite <- receive_some. apply N.le_add_r.\n    - apply try_finalize_preserves_total_supply in receive_some. lia.\n    - specialize try_refund_is_some as [_ refund_implications].\n      rewrite receive_some in refund_implications.\n      now destruct refund_implications.\n  Qed.\n\n\n\n  (** ** Constants are constant *)\n\n  (** Constants should never change after receiving msg *)\n  Lemma receive_preserves_constants : forall prev_state new_state chain ctx msg new_acts,\n    receive chain ctx prev_state msg = Ok (new_state, new_acts) ->\n        prev_state.(fundDeposit) = new_state.(fundDeposit)\n      /\\ prev_state.(batFundDeposit) = new_state.(batFundDeposit)\n      /\\ prev_state.(fundingStart) = new_state.(fundingStart)\n      /\\ prev_state.(fundingEnd) = new_state.(fundingEnd)\n      /\\ prev_state.(tokenExchangeRate) = new_state.(tokenExchangeRate)\n      /\\ prev_state.(tokenCreationCap) = new_state.(tokenCreationCap)\n      /\\ prev_state.(tokenCreationMin) = new_state.(tokenCreationMin)\n      /\\ prev_state.(initSupply) = new_state.(initSupply).\n  Proof.\n    intros * receive_some.\n    destruct_message; now contract_simpl.\n  Qed.\n\n  (** Constants are always equal to the initial assignment *)\n  Lemma constants_are_constant bstate caddr (trace : ChainTrace empty_state bstate) :\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists deploy_info cstate,\n      deployment_info _ trace caddr = Some deploy_info\n      /\\ contract_state bstate caddr = Some cstate\n      /\\ let setup := deploy_info.(deployment_setup) in\n          cstate.(fundDeposit) = setup.(_fundDeposit)\n        /\\ cstate.(batFundDeposit) = setup.(_batFundDeposit)\n        /\\ cstate.(fundingStart) = setup.(_fundingStart)\n        /\\ cstate.(fundingEnd) = setup.(_fundingEnd)\n        /\\ cstate.(tokenExchangeRate) = setup.(_tokenExchangeRate)\n        /\\ cstate.(tokenCreationCap) = setup.(_tokenCreationCap)\n        /\\ cstate.(tokenCreationMin) = setup.(_tokenCreationMin)\n        /\\ cstate.(initSupply) = setup.(_batFund).\n  Proof.\n    apply (lift_dep_info_contract_state_prop contract); intros *.\n    - intros init_some.\n      now apply init_constants_correct in init_some.\n    - intros IH receive_some.\n      now apply receive_preserves_constants in receive_some.\n  Qed.\n\n\n\n  (** ** Finalize cannot be undone *)\n\n  (** Once the contract is in the finalized state it cannot leave it *)\n  Lemma final_is_final : forall prev_state new_state chain ctx msg new_acts,\n    (isFinalized prev_state) = true /\\\n    receive chain ctx prev_state msg = Ok (new_state, new_acts) ->\n      (isFinalized new_state) = true.\n  Proof.\n    intros * (finalized & receive_some).\n    destruct_message;\n      try now rewrite <- (eip_only_changes_token_state _ _ _ _ _ _ receive_some).\n    - now rewrite <- (try_create_tokens_only_change_token_state _ _ _ _ _ receive_some).\n    - now apply try_finalize_isFinalized_correct in receive_some.\n    - now rewrite <- (try_refund_only_change_token_state _ _ _ _ _ receive_some).\n  Qed.\n\n\n\n  (** ** Cannot finalize if goal not hit *)\n\n  Lemma no_finalization_before_goal bstate caddr :\n    reachable bstate ->\n    env_contracts bstate caddr = Some (contract : WeakContract) ->\n    exists cstate,\n      contract_state bstate caddr = Some cstate\n      /\\ (total_supply cstate < tokenCreationMin cstate -> isFinalized cstate = false).\n  Proof.\n    intros * reach deployed.\n    apply (lift_contract_state_prop contract);\n      intros *; auto; clear reach deployed bstate caddr.\n    - intros ? init_some.\n      unfold Blockchain.init in *.\n      now eapply init_isFinalized_correct.\n    - intros IH receive_some ?.\n      destruct_message;\n        try apply eip_only_changes_token_state in receive_some as finalized_unchanged.\n      + apply try_transfer_preserves_total_supply in receive_some as supply_unchanged.\n        now rewrite supply_unchanged, <- finalized_unchanged in *.\n      + apply try_transfer_from_preserves_total_supply in receive_some as supply_unchanged.\n        now rewrite supply_unchanged, <- finalized_unchanged in *.\n      + apply try_approve_preserves_total_supply in receive_some as supply_unchanged.\n        now rewrite supply_unchanged, <- finalized_unchanged in *.\n      + contract_simpl.\n        now propify.\n      + contract_simpl.\n        propify.\n        now rewrite <- N.nlt_ge in *.\n      + contract_simpl.\n        now propify.\n  Qed.\n\n\n\n  (** ** It is always possible to finalize *)\n\n  (** Prove that it is always possible to reach a state where the token is finalized if the funding\n      goal was reached *)\n  Lemma can_finalize_if_creation_min : forall bstate (reward : Amount) (caddr creator : Address),\n    address_is_contract creator = false ->\n    (reward >= 0)%Z ->\n    reachable bstate ->\n    emptyable (chain_state_queue bstate) ->\n    (exists cstate,\n      env_contracts bstate caddr = Some (BAT.contract : WeakContract)\n      /\\ env_contract_states bstate caddr = Some (serializeState cstate)\n      /\\ (tokenCreationMin cstate) <= (total_supply cstate)\n      /\\ address_is_contract (fundDeposit cstate) = false)\n        ->\n        exists bstate', reachable_through bstate bstate'\n          /\\ emptyable (chain_state_queue bstate')\n          /\\ exists cstate',\n          env_contracts bstate' caddr = Some (BAT.contract : WeakContract)\n          /\\ env_contract_states bstate' caddr = Some (serializeState cstate')\n          /\\ (isFinalized cstate') = true.\n  Proof.\n    intros * Hcreator Hreward bstate_reachable bstate_queue H.\n    (* Empty the action queue so that we can add new blocks *)\n    empty_queue H; destruct H as (cstate & contract_deployed & contract_state & creation_min & fund_deposit_not_contract);\n      (* Prove that H is preserved after transfers, discarding invalid actions, calling other contracts and deploying contracts *)\n      only 3: destruct (address_eqdec caddr to_addr);\n      try (now eexists; rewrite_environment_equiv; repeat split; eauto;\n          cbn; destruct_address_eq; try easy).\n    - (* Prove that H is preserved after calls to the contract *)\n      clear amount_nonnegative enough_balance reward Hreward creator Hcreator\n        bstate_queue bstate_reachable bstate new_acts_eq act_eq.\n      subst.\n      rewrite contract_deployed in deployed.\n      inversion deployed. subst.\n      rewrite contract_state in deployed_state.\n      inversion deployed_state. subst.\n      clear deployed_state deployed.\n      apply wc_receive_strong in receive_some as\n        (prev_state' & msg' & new_state' & serialize_prev_state & _ & serialize_new_state & receive_some).\n      setoid_rewrite deserialize_serialize in serialize_prev_state.\n      inversion serialize_prev_state. subst.\n      clear serialize_prev_state.\n      apply receive_total_supply_increasing in receive_some as total_supply_increasing; try (cbn; lia).\n      apply receive_preserves_constants in receive_some as (? & ? & ? & ? & ? & ? & ? & ?).\n      repeat match goal with\n      | H : _ prev_state' = _ new_state' |- _=> try rewrite H in *; clear H\n      end.\n      exists new_state'.\n      rewrite_environment_equiv; cbn; repeat split; eauto;\n      cbn; destruct_address_eq; try easy.\n      eapply N.le_trans; eauto.\n    - update_all.\n      (* First check if contract is already finalized, if it is, we just use the current state to finish proof *)\n      destruct (isFinalized cstate) eqn:finalized;\n        [eexists; rewrite queue; split; eauto; split; eauto; eapply empty_queue_is_emptyable |].\n      (* Fast forward time/slot to \"fundingEnd\" so that we know for sure that the funding period is not active\n          in the next block *)\n      forward_time (cstate.(fundingEnd)); eauto.\n      (* forward_time gives us a new ChainState, so we no longer need the old one therefore\n          we call update_all to replace all occurrences of the old ChainState with the new one *)\n      update_all.\n      (* Now we know that the funding period is over or on its last slot and the funding minimum has been hit.\n        So now we can add a new block containing a finalize call *)\n      add_block [(finalize_act cstate caddr)] 1%nat; eauto. apply list.Forall_singleton, address_eq_refl.\n      (* The hypothesis \"slot_hit\" no longer holds so we have to update it manually before calling update_all *)\n      update (S (fundingEnd cstate) <= current_slot bstate0)%nat in slot_hit by\n        (rewrite_environment_equiv; cbn; easy).\n      update_all.\n      clear reward Hreward creator Hcreator.\n\n      (* We can now evaluate the action we added giving us a ChainState where\n          the token is in its finalized state *)\n      evaluate_action BAT.contract; try easy.\n      + (* Prove that there is enough balance to evaluate action *)\n        now apply account_balance_nonnegative.\n      + (* Prove that receive action returns Some *)\n        specialize (try_finalize_is_some cstate bstate0) as ((new_cstate & new_act & receive_some) & _); cycle 1.\n        * specialize try_finalize_isFinalized_correct as [_ finalized_new_cstate]; eauto.\n          now erewrite <- (try_finalize_only_change_isFinalized _ _ _ _ _ receive_some),\n                      finalized_new_cstate, (try_finalize_acts_correct _ _ _ _ _ receive_some) in receive_some.\n        * repeat split; eauto.\n      + cbn in *.\n        clear contract_state slot_hit creation_min.\n        update_all;\n          [rewrite queue0; do 3 f_equal; repeat (rewrite_environment_equiv; cbn; destruct_address_eq; try easy)|].\n        (* Finally we need to evaluate the new transfer action that finalize produced *)\n        evaluate_transfer; try easy.\n        * (* Prove that the transfer is nonnegative *)\n          destruct_address_eq;\n          try rewrite Z.add_0_r;\n          now apply account_balance_nonnegative.\n        * (* Prove that there is enough balance to evaluate the transfer *)\n          destruct_address_eq;\n          try rewrite Z.add_0_r;\n          apply Z.le_ge, Z.le_refl.\n        * exists bstate0.\n          split; eauto.\n          rewrite queue.\n          split; try apply empty_queue_is_emptyable.\n          eexists.\n          now repeat split; try (rewrite_environment_equiv; cbn; eauto).\n  Qed.\n\n  (** Prove that it is always possible to reach a state where the token is finalized if there\n      is enough money in the blockchain and the contract constants have valid values *)\n  Lemma can_finalize_if_deployed : forall deployed_bstate (reward : Amount) (caddr creator : Address) accounts,\n    address_is_contract creator = false ->\n    (reward >= 0)%Z ->\n    reachable deployed_bstate ->\n    emptyable (chain_state_queue deployed_bstate) ->\n    NoDup accounts ->\n    Forall (fun acc => address_is_contract acc = false) accounts ->\n    (exists deployed_cstate,\n      env_contracts deployed_bstate caddr = Some (BAT.contract : WeakContract)\n      /\\ env_contract_states deployed_bstate caddr = Some (serializeState deployed_cstate)\n      /\\ (((tokenCreationMin deployed_cstate) - (total_supply deployed_cstate))) <=\n              ((Z.to_N (spendable_balance deployed_bstate accounts)) * (tokenExchangeRate deployed_cstate))\n      /\\ deployed_cstate.(tokenExchangeRate) <= deployed_cstate.(tokenCreationCap) - deployed_cstate.(tokenCreationMin)\n      /\\ ((fundingStart deployed_cstate) <= (current_slot (env_chain deployed_bstate)))%nat\n      /\\ ((current_slot (env_chain deployed_bstate)) < (fundingEnd deployed_cstate))%nat\n      /\\ address_is_contract (fundDeposit deployed_cstate) = false\n      /\\ deployed_cstate.(tokenExchangeRate) <> 0)\n        ->\n        exists bstate, reachable_through deployed_bstate bstate\n          /\\ emptyable (chain_state_queue bstate)\n          /\\ exists cstate,\n          env_contracts bstate caddr = Some (BAT.contract : WeakContract)\n          /\\ env_contract_states bstate caddr = Some (serializeState cstate)\n          /\\ (isFinalized cstate) = true.\n  Proof.\n    intros * Hcreator Hreward reach' empty accounts_unique accounts_not_contracts H.\n    (* Empty the action queue so that we can add new blocks *)\n    empty_queue H; destruct H as\n      (cstate & contract_deployed & contract_state & enough_balance_to_fund &\n      can_hit_fund_min & funding_period_started & funding_period_not_over &\n      fund_deposit_not_contract & echange_rate_nonzero);\n      (* Prove that H is preserved after transfers, discarding invalid actions, calling other contracts and deploying contracts *)\n      only 3: destruct (address_eqdec caddr to_addr);\n      try now exists cstate;\n          repeat split; eauto;\n            try (rewrite_environment_equiv; cbn; (easy || now destruct_address_eq));\n          eapply N.le_trans; [apply enough_balance_to_fund | apply N.mul_le_mono_r, Z2N.inj_le; try now apply spendable_balance_positive];\n          eapply spendable_consume_act; eauto;\n            intros; rewrite_environment_equiv; subst; (try destruct msg);\n            cbn; destruct_address_eq; try easy; lia.\n    - (* Prove that H is preserved after calls to the contract *)\n      clear enough_balance reward Hreward creator Hcreator empty reach'\n        deployed_bstate new_acts_eq accounts_unique accounts_not_contracts.\n      subst.\n      rewrite contract_deployed in deployed.\n      inversion deployed.\n      rewrite contract_state in deployed_state.\n      inversion deployed_state.\n      subst.\n      clear deployed_state deployed.\n      apply wc_receive_strong in receive_some as\n        (prev_state' & msg' & new_state' & serialize_prev_state & serialize_msg & serialize_new_state & receive_some).\n      setoid_rewrite deserialize_serialize in serialize_prev_state.\n      inversion serialize_prev_state. subst.\n      clear serialize_prev_state.\n      apply receive_total_supply_increasing in receive_some as total_supply_increasing; try (cbn; lia).\n      apply receive_preserves_constants in receive_some as (? & ? & ? & ? & ? & ? & ? & ?).\n      repeat match goal with\n      | H : _ prev_state' = _ new_state' |- _=> try rewrite H in *; clear H\n      end.\n      eexists new_state'.\n      repeat split; eauto;\n        try (rewrite_environment_equiv; cbn; (easy || now destruct_address_eq)).\n      eapply N.le_trans in enough_balance_to_fund; [| apply N.sub_le_mono_l, total_supply_increasing].\n      eapply N.le_trans.\n      apply enough_balance_to_fund.\n      apply N.mul_le_mono_r, Z2N.inj_le; try now apply spendable_balance_positive.\n      eapply spendable_consume_act; eauto;\n        intros; rewrite_environment_equiv; subst; destruct msg;\n        cbn; destruct_address_eq; try easy; lia.\n    - (* Update goal and eliminate all occurrences of old ChainState *)\n      update_all.\n      (* Now that the queue is empty we can switch from using spendable_balance\n        to total_balance to simplify the proof *)\n      rewrite spendable_eq_total_balance in enough_balance_to_fund; eauto.\n\n      (* First check if contract is already finalized, if it is, we just use the current state to finish proof *)\n      destruct (isFinalized cstate) eqn:finalized;\n        [eexists; split; eauto; rewrite queue; split; eauto; apply empty_queue_is_emptyable |].\n\n      (* Next add a new block containing enough create_tokens actions to reach funding goal *)\n      add_block (create_token_acts (bstate<|env_account_balances := add_balance creator reward bstate.(env_account_balances)|>) caddr accounts\n              ((tokenCreationMin cstate) - (total_supply cstate)) cstate.(tokenExchangeRate)) 1%nat;\n        only 1: apply Hcreator; eauto; [now apply All_Forall.In_Forall, create_token_acts_is_account | apply create_token_acts_origin_correct |].\n      (* Prove that the funding period is still not over *)\n      update ((current_slot bstate0) <= (fundingEnd cstate))%nat in funding_period_not_over by\n        (rewrite_environment_equiv; cbn; lia).\n      (* Prove that the environment in the new ChainState is correct *)\n      update (setter_from_getter_Environment_env_account_balances\n                (fun _ : Address -> Amount => add_balance creator reward (env_account_balances bstate)) bstate)\n        with bstate0.(chain_state_env) in queue0 by\n        (rewrite queue0; apply create_token_acts_eq; intros; now rewrite_environment_equiv).\n      (* Prove that there is still enough balance in accounts to hit funding goal *)\n      update bstate with bstate0 in enough_balance_to_fund.\n      { eapply N.le_trans; eauto.\n        apply N.mul_le_mono_r, Z2N.inj_le;\n          try now apply total_balance_positive.\n        apply (total_balance_le bstate).\n        intros. rewrite_environment_equiv. cbn.\n        destruct_address_eq; lia.\n      }\n      update_all.\n      generalize dependent bstate0.\n      generalize dependent cstate.\n\n      (* Next we do induction on account to evaluate all the actions added to the queue *)\n      induction accounts; intros.\n      + (* If the queue is empty then we know that the funding goal was hit\n            and can then apply can_finalize_if_creation_min *)\n        clear accounts_unique accounts_not_contracts can_hit_fund_min echange_rate_nonzero\n              finalized funding_period_not_over funding_period_started.\n        apply N.le_0_r, N.sub_0_le in enough_balance_to_fund.\n        specialize (can_finalize_if_creation_min bstate0 reward caddr creator).\n        intros []; eauto.\n        rewrite queue0.\n        apply empty_queue_is_emptyable.\n      + clear reward Hreward creator Hcreator.\n        apply NoDup_cons_iff in accounts_unique as [accounts_unique accounts_unique'].\n        apply list.Forall_cons in accounts_not_contracts as [accounts_not_contracts accounts_not_contracts'].\n\n        (* Check if funding goal was already hit *)\n        destruct (tokenCreationMin cstate - total_supply cstate) eqn:tokens_left_to_fund.\n        * (* If funding goal is reached then we know that create_token_acts will not\n              produce any more actions, so the queue is actually empty.\n            Therefore we can directly apply the induction hypothesis *)\n          eapply IHaccounts; eauto.\n        -- now rewrite tokens_left_to_fund.\n        -- rewrite tokens_left_to_fund.\n            apply N.le_0_l.\n        * rewrite <- tokens_left_to_fund in *.\n          (* We check if the account balance is 0 *)\n          destruct (0 <? env_account_balances bstate0 a)%Z eqn:balance_positive; cycle 1;\n            [apply Z.ltb_ge in balance_positive | apply Z.ltb_lt in balance_positive].\n          { (* If account balance is 0 then we need to discard the action as it\n                cannot be evaluated *)\n            assert (amount_zero : (forall x, x <= 0 -> Z.to_N x = 0%N)%Z) by lia.\n            rewrite create_token_acts_cons, amount_zero, N.min_0_r, N.mul_0_l, N.sub_0_r in queue0 by lia.\n            discard_invalid_action; eauto.\n            - (* Prove that the action cannot be evaluated since create_tokens\n                  requires to be called with amount > 0 *)\n              clear dependent accounts.\n              clear dependent cstate.\n              clear p reach0 accounts_not_contracts balance_positive.\n              intros * eval.\n              destruct_action_eval;\n                try destruct msg; inversion act_eq; subst.\n              rewrite contract_deployed in deployed.\n              inversion deployed. subst.\n              clear deployed.\n              apply wc_receive_strong in receive_some as\n                (prev_state' & msg' & new_state' & serialize_prev_state & serialize_msg & serialize_new_state & receive_some).\n              destruct_match in serialize_msg; try congruence.\n              cbn in serialize_msg.\n              setoid_rewrite deserialize_serialize in serialize_msg.\n              inversion serialize_msg. subst.\n              now apply try_create_tokens_amount_correct in receive_some.\n            - (* Apply induction hypothesis *)\n              edestruct IHaccounts with (bstate0 := bstate) (cstate := cstate) as\n                (bstate_new & reach_new & emptyable_new & H); eauto; try (rewrite_environment_equiv; eauto).\n              + rewrite queue.\n                apply create_token_acts_eq.\n                intros. now rewrite_environment_equiv.\n              + rewrite total_balance_distr, N.add_comm in enough_balance_to_fund; eauto.\n                erewrite (total_balance_eq _ bstate0) by (intros; now rewrite_environment_equiv).\n                lia.\n          }\n\n          (* Now we know that the action is valid we need to evaluate it *)\n          evaluate_action BAT.contract; try easy;\n            only 1-4: clear fund_deposit_not_contract accounts_not_contracts IHaccounts.\n          -- (* Prove that there is an action in the queue *)\n            now rewrite create_token_acts_cons by lia.\n          -- (* Prove that amount is nonnegative *)\n            apply Z.le_ge, N2Z.is_nonneg.\n          -- (* Prove that amount <= account balance *)\n            nia.\n          -- (* Prove that receive returns Some *)\n            clear dependent accounts.\n            clear contract_deployed contract_state.\n            apply Nat.ltb_ge in funding_period_started.\n            apply Nat.ltb_ge in funding_period_not_over.\n            cbn.\n            rewrite finalized, funding_period_started, funding_period_not_over, N2Z.inj_min, Z2N.id;\n              try (apply Z.ge_le, account_balance_nonnegative; eauto).\n            clear finalized funding_period_started funding_period_not_over.\n            cbn.\n            destruct_match eqn:receive_some.\n            destruct_match eqn:match_amount in receive_some; destruct_throw_if match_amount.\n            destruct_match eqn:match_cap in receive_some; destruct_throw_if match_cap;\n              injection receive_some as <-; reflexivity.\n            destruct_match eqn:match_amount in receive_some; destruct_throw_if match_amount.\n            destruct_match eqn:match_cap in receive_some; destruct_throw_if match_cap.\n          --- (* Prove contradiction between match_amount, match_cap and can_hit_fund_min *)\n              apply N.ltb_lt in match_cap.\n              apply Z.leb_gt, Z.min_glb_lt_iff in match_amount as [min_left min_right].\n              rewrite Z2N.inj_min, N2Z.id, <- N.mul_min_distr_r, <- N.add_min_distr_l, N.min_glb_lt_iff in match_cap.\n              destruct match_cap as [match_cap_left match_cap_right].\n              apply N.lt_le_trans with (p := (tokenCreationMin cstate) + tokenExchangeRate cstate) in match_cap_left.\n              nia.\n              rewrite N.mul_add_distr_r, N.mul_1_l.\n              rewrite N.add_assoc, N.add_comm, N.add_assoc.\n              rewrite <- N.add_le_mono_r.\n              apply N_le_sub. lia.\n              now apply N_div_mul_le.\n          --- (* Prove contradiction between match_amount, balance_positive *)\n              apply Zle_bool_imp_le, Z.min_le in match_amount as [min_left | min_right].\n            ---- rewrite <- N2Z.inj_0 in min_left.\n                now apply N2Z.inj_le, N_le_add_distr in min_left.\n            ---- lia.\n          -- assert (caddr_not_in_accounts : ~ In caddr accounts) by\n              (intro; rewrite Forall_forall in accounts_not_contracts'; apply accounts_not_contracts' in H; now apply contract_addr_format in contract_deployed).\n            (* Apply induction hypothesis *)\n            edestruct IHaccounts as (bstate_new & reach_new & emptyable_new & H);\n              clear IHaccounts accounts_not_contracts balance_positive queue0 tokens_left_to_fund p;\n              only 12: (rewrite deployed_state; eauto);\n              try (rewrite_environment_equiv; eauto);\n              cbn; try rewrite Z2N.inj_min, N2Z.id;\n              clear deployed_state contract_deployed funding_period_started funding_period_not_over\n              can_hit_fund_min fund_deposit_not_contract finalized contract_state.\n          --- (* Prove that the queues of the two ChainStates are equivalent *)\n              rewrite queue, N.sub_add_distr.\n              apply create_token_acts_eq.\n              intros. rewrite_environment_equiv. cbn. now destruct_address_eq.\n          --- (* Prove that there still is enough balance to hit funding goal *)\n              clear queue accounts_not_contracts'.\n              edestruct N.min_dec.\n            ---- cbn. rewrite e.\n                eapply N.le_trans; [| apply N.le_0_l].\n                rewrite N.mul_add_distr_r, N.mul_1_l.\n                apply N.le_0_r.\n                rewrite N.sub_add_distr.\n                rewrite N.sub_add_distr.\n                apply N.sub_0_le.\n                now apply N_le_div_mul.\n            ---- rewrite total_balance_distr, N.add_comm in enough_balance_to_fund; eauto.\n                erewrite (total_balance_eq _ bstate0) by\n                  (intros; rewrite_environment_equiv; cbn; now destruct_address_eq).\n                apply N.le_sub_le_add_r in enough_balance_to_fund.\n                rewrite <- N.sub_add_distr in enough_balance_to_fund.\n                eapply N.le_trans; [| apply enough_balance_to_fund].\n                apply N.sub_le_mono_l, N.add_le_mono_l, N.mul_le_mono_r.\n                lia.\n  Qed.\n\n  Lemma can_deploy_and_finalize : forall bstate (reward : Amount) (caddr creator : Address) accounts setup,\n    address_is_contract creator = false ->\n    (reward >= 0)%Z ->\n    reachable bstate ->\n    chain_state_queue bstate = [] ->\n    NoDup accounts ->\n    Forall (fun acc => address_is_contract acc = false) accounts ->\n    address_is_contract caddr = true ->\n    env_contracts bstate caddr = None ->\n    (((_tokenCreationMin setup) - (_batFund setup))) <=\n              ((Z.to_N (spendable_balance bstate accounts)) * (_tokenExchangeRate setup)) ->\n    setup.(_tokenExchangeRate) <= setup.(_tokenCreationCap) - setup.(_tokenCreationMin) ->\n    ((_fundingStart setup) < (_fundingEnd setup))%nat ->\n    (S (current_slot (env_chain bstate)) < (_fundingStart setup))%nat ->\n    address_is_contract (_fundDeposit setup) = false ->\n    setup.(_tokenExchangeRate) <> 0 ->\n    exists bstate',\n      reachable_through bstate bstate'\n      /\\ emptyable (chain_state_queue bstate')\n      /\\ exists cstate,\n      env_contracts bstate' caddr = Some (BAT.contract : WeakContract)\n      /\\ env_contract_states bstate' caddr = Some (serializeState cstate)\n      /\\ (isFinalized cstate) = true.\n  Proof.\n    intros * Hcreator Hreward\n          bstate_reachable\n          bstate_queue\n          accounts_unique\n          accounts_not_contracts\n          caddr_is_contract\n          contract_not_deployed\n          enough_balance_to_fund\n          can_hit_fund_min\n          funding_period_nonempty\n          funding_period_not_started\n          fund_deposit_not_contract\n          echange_rate_nonzero.\n\n    add_block [(deploy_act setup BAT.contract creator)] 1%nat; eauto. apply list.Forall_singleton, address_eq_refl.\n    update ((current_slot bstate0) < _fundingStart setup)%nat in funding_period_not_started by\n      (rewrite_environment_equiv; cbn; lia).\n    update bstate with bstate0 in enough_balance_to_fund by\n      (eapply N.le_trans; [apply enough_balance_to_fund | apply N.mul_le_mono_r, Z2N.inj_le; try now apply spendable_balance_positive];\n      unfold spendable_balance, pending_usage; rewrite queue, bstate_queue; apply sumZ_le;\n      intros; rewrite_environment_equiv; cbn; destruct_address_eq; try lia).\n    update_all.\n\n    deploy_contract BAT.contract; eauto; try lia; try now apply account_balance_nonnegative.\n    specialize constants_are_constant as (dep_info & cstate' & deploy_info' & deployed_state' & ? & ? & ? & ? & ? & ? & ? & ?); eauto.\n    unfold contract_state in deployed_state'. cbn in deployed_state'.\n    rewrite deployed_state, deserialize_serialize in deployed_state'.\n    inversion deployed_state'. subst cstate'. clear deployed_state'.\n    rewrite deploy_info in deploy_info'.\n    inversion deploy_info'. subst dep_info. clear deploy_info'.\n    cbn in *.\n    repeat match goal with\n    | H : _ cstate = _ setup |- _=> rewrite <- H in *; clear H\n    end.\n    update (initSupply cstate) with (total_supply cstate) in enough_balance_to_fund by\n      (eapply N.le_trans; [apply N.sub_le_mono_l, N.eq_le_incl | apply enough_balance_to_fund]; now rewrite Heqcstate).\n    update bstate0 with bstate in enough_balance_to_fund by\n      (eapply N.le_trans; [apply enough_balance_to_fund | apply N.mul_le_mono_r, Z2N.inj_le; try now apply spendable_balance_positive];\n      eapply spendable_consume_act; eauto; intros; rewrite_environment_equiv; subst; cbn; destruct_address_eq; try easy; lia).\n    clear dependent trace.\n    update_all.\n\n    forward_time_exact (cstate.(fundingStart)); eauto.\n    update bstate with bstate0 in enough_balance_to_fund by\n      (inversion header_valid;\n      eapply N.le_trans; [apply enough_balance_to_fund | apply N.mul_le_mono_r, Z2N.inj_le; try now apply spendable_balance_positive];\n      unfold spendable_balance, pending_usage; rewrite queue, queue0; apply sumZ_le;\n      intros; rewrite_environment_equiv; cbn; destruct_address_eq; try lia).\n    clear funding_period_not_started.\n    update_all.\n\n    eapply can_finalize_if_deployed; eauto.\n    - rewrite queue. apply empty_queue_is_emptyable.\n    - eexists.\n      intuition.\n  Qed.\n\n\n\n  (** ** Refund guarantee *)\n\n  (** The BAToken contract should guarantee that all tokens (except for the free initSupply given to batFundDeposit)\n      can be fully refunded. However, as shown in the property based tests this is not the case, so we can only prove\n      a weaker result stating that refund msgs can always be consumed. This does not guarantee refunding as the\n      proof does not state that the new actions produced by refund entrypoint can be evaluated. Thus, it is not\n      guaranteed that the state changes will be applied *)\n  Lemma weak_refund_guarantee : forall bstate cstate caddr account acts,\n    let refund_act := build_act account account (act_call caddr 0 refund) in\n    reachable bstate ->\n    env_contracts bstate caddr = Some (BAT.contract : WeakContract) ->\n    env_contract_states bstate caddr = Some (serialize cstate) ->\n    chain_state_queue bstate = refund_act :: acts ->\n    (fundingEnd cstate < current_slot bstate)%nat -> (* funding period is over *)\n    total_supply cstate < tokenCreationMin cstate -> (* funding failed *)\n    account <> batFundDeposit cstate -> (* sender is not batFundDeposit *)\n    0 < with_default 0 (FMap.find account (balances cstate)) -> (* account owns some tokens *)\n    exists new_bstate new_acts, chain_state_queue new_bstate = new_acts ++ acts /\\\n      inhabited (ActionEvaluation bstate refund_act new_bstate new_acts).\n  Proof.\n    intros * reach deployed deployed_state queue funding_over funding_failed account_not_batfund has_tokens.\n    subst refund_act.\n    eapply no_finalization_before_goal in reach as not_finalized; eauto.\n    destruct not_finalized as (cstate' & deployed_state' & not_finalized).\n    cbn in deployed_state'.\n    rewrite deployed_state, deserialize_serialize in deployed_state'.\n    inversion deployed_state'.\n    subst cstate'. clear deployed_state'.\n    eexists {| chain_state_env := _; chain_state_queue := _ |}.\n    eexists.\n    split; cycle 1.\n    - constructor.\n      eapply eval_call with (msg := Some _); eauto.\n      + lia.\n      + now apply Z.ge_le, account_balance_nonnegative.\n      + specialize try_refund_is_some as [[new_cstate [resp_acts receive_some]] _]; cycle 1.\n        * apply wc_receive_to_receive.\n          unfold Blockchain.receive.\n          rewrite receive_some.\n          contract_simpl.\n          rename H1 into account_balance_some.\n          result_to_option.\n          replace t with (with_default 0 (FMap.find account (balances cstate))); auto.\n          now rewrite account_balance_some.\n        * repeat split; eauto.\n      + now constructor.\n    - eauto.\n  Qed.\n\nEnd Theories.\n", "meta": {"author": "AU-COBRA", "repo": "ConCert", "sha": "55ffd996fe89d41677a2ff368d3a5e4be1e997b7", "save_path": "github-repos/coq/AU-COBRA-ConCert", "path": "github-repos/coq/AU-COBRA-ConCert/ConCert-55ffd996fe89d41677a2ff368d3a5e4be1e997b7/examples/bat/BATCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22891756827824322}}
{"text": "Require Import String.\nRequire Import Coq.Strings.Ascii.\nRequire FMapWeakList.\nRequire Export Coq.Structures.OrderedTypeEx.\nRequire Import Lists.List.\nImport ListNotations.\nRequire Import JaSyntax.\nRequire Import JaProgram.\nRequire Import JaTactics.\nOpen Scope list_scope.\nRequire Import NPeano.\nRequire Import PeanoNat.\nOpen Scope nat_scope.\nRequire Import Coq.Program.Equality.\n\nFrom Hammer Require Import Reconstr.\n\n\n(**\n  By [extends CC cn dn] we mean that in the program [CC] the class of name [cn] is declared\n  as a direct subclass of [dn]. This is the formalisation of the *direct subtype relation, <_1* \n  as defined in Section 4.10 of Java Language Specification.\n*)\nInductive extends : JFProgram -> JFClassName -> JFClassName -> Prop  :=\n| base : forall cn dn fields methods CC ex fields' methods',\n           In (JFCDecl dn ex fields' methods') CC ->\n           extends ((JFCDecl cn (Some dn) fields methods) :: CC)%list cn dn\n(** As written in Section 8.1.4 of Java Language Specification,\n    \"The optional extends clause in a normal class declaration specifies the direct \n    superclass of the current class.\"\n    We add here the check of the accessibility of the superclass as further it\n    is written that\n    \"The ClassType must name an accessible class type (§6.6), or a compile-time \n    error occurs.\" *)\n| ind  : forall cn1 cn2 dn1 dn2 fields methods CC, \n           extends CC cn2 dn2 ->\n           extends ((JFCDecl cn1 dn1 fields methods) :: CC)%list cn2 dn2.\n(** The extension of the direct subtype relation to the whole program. *)\n\n\nHint Constructors extends : myhints.\n\nLemma extends_in_first:\n  forall CC cn dn,\n    extends CC cn dn ->\n    (exists flds mthds,  In (JFCDecl cn (Some dn) flds mthds) CC).\nProof.\n  induction CC; scrush.\nQed.\n\nLemma extends_in_second:\n  forall CC cn dn,\n    extends CC cn dn ->\n    (exists ex flds mthds,  In (JFCDecl dn ex flds mthds) CC).\nProof.\n  induction CC; scrush.\nQed.\n\nLemma extends_in_second_second:\n  forall CC cn dn,\n    extends CC cn dn ->\n    forall CC' cd,\n      CC = cd :: CC' ->\n      (exists ex fields' methods',  In (JFCDecl dn ex fields' methods') CC').\nProof.\n  induction 1.\n  + sauto.\n  + destruct CC; scrush.\nQed.\n\nLemma base_deep:\n  forall CC DD cn dn dd fields methods,\n    find_class DD dn = Some dd ->\n    extends (CC ++ JFCDecl cn (Some dn) fields methods :: DD) cn dn.\nProof.\n  induction CC.\n  + intros.\n    simpl.\n    destruct dd.\n    generalize H;intros;eapply find_class_eq_name in H0;subst.\n    eapply find_class_in in H.\n    eapply base; eauto.\n  + intros.\n    simpl.\n    destruct a.\n    eapply ind.\n    eauto.\nQed.\n    \n\nLemma in_exists_decl_dec:\n  forall CC cn,  \n    (exists ex flds mthds, In (JFCDecl cn ex flds mthds) CC) \\/\n    ~ (exists ex flds mthds, In (JFCDecl cn ex flds mthds) CC).\nProof.    \n  induction CC.\n  + intros.\n    right.\n    sauto.\n  + intros.\n    destruct a.\n    destruct (JFClassName_dec cn0 cn).\n    ++ subst.\n       left.\n       sauto.\n    ++ destruct (IHCC cn).\n       +++ left.\n           sauto.\n       +++ right.\n           intro.\n           apply H.\n           decompose_ex H0.\n           inversion H0;sauto.\nQed.\n    \n\nLemma extends_dec:\n  forall CC cn dn,\n    extends CC cn dn \\/ ~extends CC cn dn.\nProof.\n  induction CC.\n  + sauto.\n  + destruct a.\n    intros.\n    destruct (JFClassName_dec cn0 cn).\n    ++ subst.\n       destruct (IHCC cn dn).\n       +++ left.\n           eauto using ind.\n       +++ destruct ex.\n           ++++ pose (in_exists_decl_dec CC dn).\n                destruct o.\n                * decompose_ex H0.\n                  destruct (JFClassName_dec dn j).\n                  ** left.\n                     rewrite e.\n                     eapply base.\n                     sauto.\n                  ** right.\n                     intro.\n                     inversion H1.\n                     *** congruence.\n                     *** contradiction.\n                * right.\n                  intro.\n                  inversion H1.\n                  ** subst.\n                     eapply H0.\n                     sauto.\n                  ** contradiction.\n           ++++ right.\n                intro.\n                inversion H0.\n                contradiction.\n    ++ destruct (IHCC cn0 dn).\n       +++ left.\n           constructor 2.\n           assumption.\n       +++ right.\n           intro.\n           inversion H0;sauto.\nQed.\n\nLemma extends_narrower:\n  forall (CC : list JFClassDeclaration) (cn dn en : JFClassName)\n    (ex : option JFClassName) (fields : list JFFieldDeclaration)\n    (methods : list JFMethodDeclaration),\n    extends (JFCDecl cn ex fields methods :: CC) dn en ->\n    dn<>cn ->\n    extends CC dn en.\nProof.\n  scrush.\nQed.\n\nLemma extends_neq:\n  forall CC D1 C D0 ex fields methods,\n  names_unique (JFCDecl D1 ex fields methods :: CC) ->\n  (exists cname dname : JFClassName,\n         C = JFClass cname /\\\n         D0 = JFClass dname /\\\n         extends (JFCDecl D1 ex fields methods :: CC) cname dname) ->\n  D0 <> JFClass D1.\nProof.\n  intros.\n  destruct H0, H0.\n  decompose [and] H0; clear H0.\n  eapply extends_in_second_second  in H4; [idtac | reflexivity].\n  pose names_unique_zero; pose count_occ_not_In; scrush.\nQed.\n\nLemma extends_neq_none:\n  forall CC D1 cname dname fields methods,\n    names_unique (JFCDecl D1 None fields methods :: CC) ->\n    extends (JFCDecl D1 None fields methods :: CC) cname dname ->\n    D1 <> cname.\nProof.\n  assert (forall L cname dname,\n             names_unique L ->\n             extends L cname dname ->\n             forall CC D1 fields methods, L = JFCDecl D1 None fields methods :: CC ->\n             D1 <> cname); [idtac | scrush].\n  induction 2.\n  + sauto.\n  + intros ? ? ? ? H2.\n    injection H2.\n    pose extends_in_first; pose count_occ_zero_is_class_name_false; scrush.\nQed.\n\nLemma extends_equals_first:\n  forall C D E fields methods CC, \n    names_unique (JFCDecl C (Some D) fields methods :: CC) ->\n      extends (JFCDecl C (Some D) fields methods :: CC) C E ->\n      E = D.\nProof.\n  intros C D E fields methods CC Nuq Ext.\n  inversion Ext.\n  * auto.\n  * subst.\n    assert (forall x, In x CC -> decl_once CC x).\n    assert (names_unique CC) by scrush.\n    apply Forall_forall; auto.\n    pose extends_in_first; scrush.\nQed.\n\n\nLemma names_unique_extends_non_refl:\n  forall CC C D,\n    names_unique CC -> extends CC C D -> C <> D.\nProof.\n  intros CC C D Nuq H.\n  induction H.\n  pose count_occ_In; scrush.\n  eauto.\nQed.\n\nLemma extends_not_extends:\n  forall CC cn dn,\n    extends CC cn dn ->\n    forall hd DD,\n      CC = (hd :: DD) ->\n      ~ extends DD cn dn ->\n      exists fields methods,\n        hd = JFCDecl cn (Some dn)  fields methods.\nProof.\n  induction 1.\n  + intros.\n    injection H0;intros.\n    subst.\n    do 2 eexists.\n    eauto.\n  + intros.\n    injection H0;intros;subst.\n    contradiction.\nQed.\n\nLemma extends_monotone:\n  forall CC cname dname,\n    extends CC cname dname ->\n    forall CC' DD  E,\n    CC = (CC' ++ DD) ->\n    extends (CC' ++ E :: DD) cname dname.\nProof.\n  induction 1.\n  + intros.\n    destruct CC'.\n    ++ simpl in *.\n       rewrite <- H0.\n       destruct E.\n       eapply ind.\n       eapply base;eauto.\n    ++ simpl in H0.\n       injection H0;intros.\n       subst.\n       simpl.\n       eapply base.\n       eapply in_or_app.\n       eapply in_app_or in H.\n       sauto.\n  + inversion H.\n    ++ subst.\n       intros.\n       induction CC'.\n       +++ simpl in *.\n           subst.\n           destruct E.\n           apply ind.\n           apply ind.\n           eauto.\n       +++ simpl in *.\n           injection H1;intros.\n           subst.\n           apply ind.\n           eauto.\n    ++ intros.\n       subst.\n       destruct CC'.\n       +++ simpl in *.\n           subst.\n           destruct E.\n           apply ind.\n           apply ind.\n           auto.\n       +++ simpl in *.\n           injection H4;intros.\n           subst.\n           apply ind.\n           eauto.\nQed.\n\nLemma names_unique_extends_eq:\n  forall CC D1 j fields methods dname,\n    names_unique (JFCDecl D1 (Some j) fields methods :: CC) ->\n    extends (JFCDecl D1 (Some j) fields methods :: CC) D1 dname ->\n    j = dname.\nProof.\n  intros.\n  inversion H0.\n  - auto.\n  - assert  (exists\n                (ex0 : JFClassName) (fields' : list JFFieldDeclaration) \n                (methods' : list JFMethodDeclaration),\n                In (JFCDecl D1 (Some ex0) fields' methods') CC)\n      by eauto using extends_in_first.\n    destruct H9. destruct H9. destruct H9.\n    assert (count_occ Bool.bool_dec (map (is_class_name D1) CC) true = 0)\n      by eauto using names_unique_count_zero.\n    apply <- count_occ_not_In in H10.\n    assert False.\n    replace true with (is_class_name D1 (JFCDecl D1 (Some x) x0 x1)) in H10.\n    apply H10.\n    apply in_map.\n    auto.\n    apply is_class_name_name.\n    tauto.\nQed.\n\nLemma extends_unique_dir:\n  forall CC cn dn en,\n    names_unique CC ->\n    extends CC cn dn ->\n    extends CC cn en -> dn = en.\nProof.\n  induction CC.\n  + intros.\n    inversion H0.\n  + intros.\n    inversion H0;subst.\n    ++ inversion H1;subst.\n       +++ auto.\n       +++ eapply extends_equals_first in H1;eauto.\n    ++ inversion H1;subst.\n       +++ eapply extends_equals_first in H0;eauto.\n       +++ eauto.\nQed.\n\nLemma double_extends:\n  forall CC cname dname,\n    names_unique CC ->\n    extends CC cname dname ->\n    extends CC dname cname -> cname = dname.\nProof.\n  induction 2.\n  + intros.\n    destruct (JFClassName_dec cn dn);auto.\n    eapply extends_narrower in H1;try congruence.\n    eapply extends_in_second in H1.\n    decompose_ex H1.\n    eapply names_unique_in_neq in H;eauto.\n    contradiction.\n  + intros.\n    destruct (JFClassName_dec cn1 dn2).\n    ++ subst.\n       eapply extends_in_second in H0.\n       decompose_ex H0.\n       eapply names_unique_in_neq in H;eauto.\n       contradiction.\n    ++ eapply extends_narrower in H1;try congruence.\n       eauto.\nQed.\n\n\nHint Resolve extends_equals_first extends_narrower names_unique_extends_non_refl base_deep extends_monotone extends_unique_dir : myhints.\nHint Resolve extends_equals_first extends_narrower names_unique_extends_non_refl base_deep extends_monotone extends_unique_dir.\n\nLemma extends_narrower_deep_eqfirst:\n  forall CC cn en,\n    extends CC cn en ->\n    forall CC' CC'' dn flds mthds,\n           CC = (CC' ++ JFCDecl cn (Some dn) flds mthds :: CC'') ->\n           dn <> en ->\n           cn <> en ->\n           extends (CC' ++ CC'') cn en.\nProof.\n  induction 1.\n  + intros.\n    destruct CC'.\n    ++ simpl in *.\n       injection H0;intros.\n       subst;contradiction.\n    ++ simpl in H0; injection H0;intros.\n       subst j.\n       simpl.\n       eapply base.\n       rewrite H3 in H.\n       eapply in_app_or in H.\n       destruct H.\n       eapply in_or_app.\n       left; eauto.\n       eapply in_or_app.\n       right.\n       simpl in H.\n       destruct H.\n       injection H;intros;congruence.\n       eauto.\n  + intros.\n    destruct CC'.\n    ++ simpl in H0.\n       injection H0;intros;subst.\n       simpl.\n       auto.\n    ++ simpl in *.\n       injection H0;intros;subst j.\n       eapply IHextends in H3;eauto.\n       replace (JFCDecl cn1 dn1 fields methods :: CC' ++ CC'') with ([] ++ (JFCDecl cn1 dn1 fields methods :: CC' ++ CC''))\n         by eauto using app_nil_l.\n       eauto.\nQed.\n\nLemma extends_narrower_deep_neqfirst:\n  forall CC cn en,\n    extends CC cn en ->\n    forall CC' CC'' dn ex flds mthds,\n           CC = (CC' ++ JFCDecl dn ex flds mthds :: CC'') ->\n           cn <> dn ->\n           dn <> en ->\n           extends (CC' ++ CC'') cn en.\nProof.\n  induction 1.\n  + intros.\n    destruct CC'.\n    ++ simpl in *.\n       injection H0;intros;subst.\n       contradiction.\n    ++ simpl in *.\n       injection H0;intros;subst.\n       eapply base.\n       eapply in_app_or in H.\n       destruct H.\n       eapply in_or_app.\n       eauto.\n       eapply in_or_app.\n       simpl in H.\n       eauto.\n       destruct H; try (injection H;intros;subst;congruence).\n       eauto.\n  + intros.\n    destruct CC'.\n    ++ simpl in *.\n       injection H0;intros;subst;clear H0.\n       auto.\n    ++ simpl in *.\n       injection H0;intros;subst.\n       generalize H1;intros.\n       eapply IHextends in H1;eauto.\n       eapply ind. auto.\nQed.\n\n\nHint Resolve extends_narrower_deep_neqfirst extends_narrower_deep_eqfirst : myhints.\nHint Resolve extends_narrower_deep_neqfirst extends_narrower_deep_eqfirst.\n\n    \nFixpoint number_of_extends (CC:JFProgram) (cn:JFClassName) :=\n  match CC with\n    | [] => None\n    | (JFCDecl x (Some ex) fields' methods') :: CC' =>\n      if JFClassName_dec x cn\n      then match (number_of_extends CC' ex) with\n             | None => None\n             | Some n => Some (n+1)\n           end\n      else number_of_extends CC' cn\n    | (JFCDecl x None fields' methods') :: CC' =>\n      if JFClassName_dec x JFObjectName\n      then if JFClassName_dec cn JFObjectName\n           then Some 0\n           else number_of_extends CC' cn\n      else None\n  end.\n\nLemma number_of_extends_compose:\n  forall ex flds mthds CC C D n,\n    D<>C ->\n    number_of_extends CC C = Some n ->\n    number_of_extends ((JFCDecl D (Some ex) flds mthds) :: CC) C = Some n.\nProof.\n  scrush.\nQed.\n\n\nLemma number_of_extends_compose_eq:\n  forall flds mthds CC C D n,\n    number_of_extends CC C = Some n ->\n    number_of_extends ((JFCDecl D (Some C) flds mthds) :: CC) D = Some (n+1).\nProof.\n  scrush.\nQed.\n\n\n\n\nLemma number_of_extends_decompose:\n  forall ex flds mthds CC C n,\n    number_of_extends ((JFCDecl C (Some ex) flds mthds) :: CC) C = Some n ->\n    number_of_extends CC ex = Some (n-1) /\\ n > 0.\nProof.\n  intros.\n  unfold number_of_extends in H.\n  destruct (JFClassName_dec C C).\n  fold (number_of_extends CC ex) in H.\n  destruct (number_of_extends CC ex).\n  + injection H.\n    intros.\n    rewrite <- H0.\n    auto with zarith.\n  + discriminate H.\n  + tauto.\nQed.\n\n\nLemma number_of_extends_decompose_neq:\n  forall ex flds mthds CC C D n,\n    C<>D ->\n    number_of_extends ((JFCDecl C ex flds mthds) :: CC) D = Some n ->\n    number_of_extends CC D = Some n.\nProof.\n  scrush.\nQed.\n\nLemma number_of_extends_none:\n  forall CC D fields methods,\n    D <> JFObjectName ->\n    number_of_extends (JFCDecl D None fields methods :: CC) D = None.\nProof.\n  scrush.\nQed.\n\n\nLemma number_of_extends_find_class_simple:\n  forall CC j n,\n    number_of_extends CC j = Some (n) ->\n         exists x, find_class CC j = Some x.\nProof.\n  induction CC.\n  * sauto.\n  * intros.\n    unfold number_of_extends in H.\n    destruct a.\n    destruct ex.\n    destruct (JFClassName_dec cn j).\n    clear H.\n    scrush.\n    scrush.\n    fold (number_of_extends CC j) in H.\n    destruct (JFClassName_dec j JFObjectName).\n    scrush.\n    scrush.\nQed.\n\nLemma number_of_extends_zero:\n  forall CC cn,\n    number_of_extends CC cn = Some 0 ->\n    cn = JFObjectName.\nProof.\n  induction CC; scrush.\nQed.\n\nLemma number_of_extends_object:\n  forall CC C n,\n    number_of_extends CC C = Some n ->\n    program_contains CC JFObjectName = true.\nProof.\n  induction CC.\n  + intros.\n    discriminate H.\n  + intros.\n    simpl in H.\n    destruct a.\n    destruct ex.\n    ++ destruct (JFClassName_dec cn C).\n       +++ subst.\n           destruct (number_of_extends CC j) eqn:?; try discriminate H.\n           eapply IHCC in Heqo.\n           eauto using program_contains_further.\n       +++ eapply IHCC in H.\n           eauto using program_contains_further.\n    ++ destruct (JFClassName_dec cn JFObjectName); try discriminate H.\n       destruct (JFClassName_dec C JFObjectName); try discriminate H; try (subst;auto).\nQed.\n\n\n\n   \nLemma names_unique_number_of_extends_loop:\n  forall C flds mthds CC,\n         names_unique ((JFCDecl C (Some C) flds mthds) :: CC) ->\n         number_of_extends ((JFCDecl C (Some C) flds mthds) :: CC) C = None.\nProof.\n  pose number_of_extends_find_class_simple; pose names_unique_zero;\n    pose find_class_program_contains; pose program_contains_counts_occ;\n      scrush.\nQed.\n\n\nHint Resolve number_of_extends_compose number_of_extends_compose_eq number_of_extends_decompose\n     number_of_extends_decompose_neq number_of_extends_none : myhints.\n  \n\n\n\n\nLemma number_of_extends_find_class:\n  forall (CC:JFProgram) (cn dn:JFClassName) fields methods (n:nat),\n    names_unique (JFCDecl cn (Some dn) fields methods :: CC) ->\n    number_of_extends (JFCDecl cn (Some dn) fields methods :: CC) cn =\n       Some n ->\n  exists dd : JFClassDeclaration,\n    find_class (JFCDecl cn (Some dn) fields methods :: CC) dn = Some dd.\nProof.\n  induction CC.\n  - sauto.\n  - intros.\n    destruct a.\n    assert ({cn0=dn}+{cn0<>dn}) by auto using JFClassName_dec.\n    destruct H1.\n    * subst cn0. (* cn0 = dn *)\n      assert (cn<>dn). {\n        eapply names_unique_extends_non_refl;eauto.\n        eapply base.\n        simpl.\n        left;eauto.\n      }\n      eapply find_class_lift_cons.\n      simpl.\n      destruct (JFClassName_dec dn dn);try contradiction.\n      auto.\n    * assert ({cn=dn} + {cn<>dn}) by apply JFClassName_dec.\n      destruct H1.\n      + rewrite e in *.\n        simpl.\n        destruct (JFClassName_dec dn dn).\n        exists (JFCDecl dn (Some dn) fields methods).\n        auto.\n        tauto.\n      + assert (exists dd : JFClassDeclaration,\n                  find_class (JFCDecl cn (Some dn) fields methods :: CC) dn = \n                  Some dd). {\n          apply (IHCC cn dn fields methods n);eauto.\n          apply number_of_extends_decompose in H0;eauto.\n          destruct H0.\n          eapply number_of_extends_decompose_neq in H0;eauto.\n          eapply number_of_extends_compose_eq in H0;eauto.\n          replace (n -1 + 1) with n in H0 by (rewrite  Nat.sub_add; eauto).\n          eauto.\n        }\n        decompose_ex H1.\n        eapply find_class_further_neq in H1;eauto.\n        exists dd.\n        eapply find_class_same in H1;try apply n0;eauto.\n        eapply find_class_same in H1;eauto.\nQed.\n    \nDefinition subtype_well_founded (CC:JFProgram) :=\n  forall (C:JFClassName) (cd:JFClassDeclaration),\n    find_class CC C = Some cd -> exists (n:nat), number_of_extends CC C = Some n.\n\n\n  \nLemma subtype_well_founded_further:\n  forall CC cd,\n    names_unique (cd::CC) ->\n    subtype_well_founded (cd :: CC) -> subtype_well_founded CC.\nProof.\n  intros.\n  unfold subtype_well_founded in *.\n  intros.\n  destruct cd. \n  assert (count_occ Bool.bool_dec (map (is_class_name cn) CC) true = 0) by\n      (apply (names_unique_count_zero CC cn ex fields methods); auto).\n  assert (C <> cn) by\n      (try apply (is_class_and_occ_zero CC C cn cd0);\n       auto using (names_unique_further CC (JFCDecl cn ex fields methods))).\n  destruct ex.\n  assert ({j=C} + {j<>C}) by apply JFClassName_dec.\n  destruct H4.\n  - rewrite e in *.\n    lapply (H0 cn (JFCDecl cn (Some C) fields methods)).\n    intros.\n    destruct H4.\n    exists (x-1).\n    apply (number_of_extends_decompose C fields methods CC cn x); auto.\n    unfold find_class.\n    destruct (JFClassName_dec cn cn).\n    trivial.\n    tauto.\n  - lapply (H0 C cd0); intros.\n    destruct H4.\n    exists x.\n    auto using (number_of_extends_decompose_neq (Some j) fields methods CC cn C).\n    apply find_class_same; auto.\n  - assert ( exists n : nat,\n               number_of_extends (JFCDecl cn None fields methods :: CC) C = Some n).\n    apply (H0 C cd0).\n    apply (find_class_same CC cn C None fields methods cd0).\n    auto.\n    auto.\n    destruct H4.\n    unfold number_of_extends in H4.\n    destruct (JFClassName_dec cn JFObjectName).\n    destruct (JFClassName_dec C JFObjectName).\n    rewrite e in *.\n    rewrite e0 in *.\n    tauto.\n    fold (number_of_extends CC C) in H4.\n    exists x; auto.\n    discriminate H4.\nQed.\n\nLemma subtype_well_founded_decompose_program:\n  forall CC CC',\n    names_unique (CC ++ CC') ->\n    subtype_well_founded (CC ++ CC') -> subtype_well_founded CC'.\nProof.\n  induction CC.\n  + sauto. \n  + pose subtype_well_founded_further; scrush.\nQed.\n\nLemma subtype_get_superclass:\n  forall (CC:JFProgram) (C x ex:JFClassName) fields methods,\n      names_unique CC ->\n      subtype_well_founded CC ->\n      find_class CC C = Some (JFCDecl x (Some ex) fields methods) ->\n      exists cd,\n      find_class CC ex = Some cd.\nProof.\n  induction CC.\n  + intros.\n    compute in H0.\n    discriminate H1.\n  +  intros.\n    destruct a.\n    assert ({cn=ex}+{cn<>ex}) by apply JFClassName_dec; destruct H2; auto.\n    ++ exists (JFCDecl cn ex0 fields0 methods0).\n       simpl.\n       rewrite e.\n       destruct (JFClassName_dec ex ex); auto.\n       tauto.\n    ++ assert ({C=cn} + {C <> cn}) by apply JFClassName_dec; destruct H2; auto.\n       +++ subst C.\n           simpl in H1.\n           destruct (JFClassName_dec cn cn);try contradiction.\n           injection H1;auto.\n           intros.\n           subst x.\n           unfold subtype_well_founded in H0.\n           assert ({cn=ex}+{cn<>ex}) by apply JFClassName_dec; destruct H5; auto.\n           ++++ rewrite e0 in *.\n                exists (JFCDecl ex ex0 fields0 methods0).\n                simpl.\n                destruct (JFClassName_dec ex ex); try contradiction.\n           ++++ assert ( exists n : nat,\n                           number_of_extends (JFCDecl cn ex0 fields0 methods0 :: CC) cn = Some n).\n                apply (H0 cn (JFCDecl cn ex0 fields0 methods0)).\n                simpl.\n                destruct (JFClassName_dec cn cn); try contradiction.\n                auto.\n                destruct H5.\n                rewrite H4 in *.\n                eapply number_of_extends_find_class;eauto.\n       +++ simpl.\n           destruct (JFClassName_dec cn ex);try contradiction.\n           eapply IHCC;eauto 4 using subtype_well_founded_further, find_class_further_neq.\nQed.\n\n    \nLemma subtype_well_founded_superclass:\n  forall (CC:JFProgram) (C D:JFClassName) (ex:option JFClassName) fields methods,\n    subtype_well_founded CC ->\n    names_unique CC ->\n    find_class CC C = Some (JFCDecl D ex fields methods) ->\n    C <> JFObjectName ->\n    exists D',\n      find_class CC C = Some (JFCDecl D (Some D') fields methods).\nProof.\n  induction CC.\n  + intros.\n    simpl in H1.\n    discriminate H1.\n  + intros.\n    simpl.\n    destruct a.\n    simpl in H1.\n    destruct (JFClassName_dec cn C).\n    ++ subst.\n       unfold subtype_well_founded in H.\n       simpl in H1.\n       assert (exists n : nat, number_of_extends (JFCDecl C ex0 fields0 methods0 :: CC) C = Some n).\n       {\n         eapply (H C).\n         unfold find_class.\n         destruct (JFClassName_dec C C); try contradiction.\n         auto.\n       } \n       unfold number_of_extends in H3.\n       fold number_of_extends in H3.\n       injection H1;clear H1;intros;subst.\n       destruct ex.\n       +++ eexists. auto.\n       +++ simpl in H3.\n           destruct (JFClassName_dec D JFObjectName); try contradiction.\n           destruct H3.\n           discriminate H1.\n    ++ eapply IHCC; eauto.\n       eapply subtype_well_founded_further; eauto.\nQed.\n\nLemma find_class_extends:\n  forall CC cname name dname fields methods D,\n    find_class CC cname = Some (JFCDecl name (Some dname) fields methods) ->\n    find_class CC dname = Some D ->\n    subtype_well_founded CC ->\n    names_unique CC ->\n    cname <> dname ->\n    extends CC cname dname.\nProof.\n  induction CC.\n  + intros.\n    simpl in H.\n    discriminate H.\n  + intros.\n    destruct a.\n    simpl in H.\n    destruct (JFClassName_dec cn cname).\n    ++ (* cn = cname *)\n      subst.\n      injection H;intros;clear H;subst.\n      destruct D. \n      assert (dname=cn) by eauto using find_class_eq_name.\n      subst.\n      eapply find_class_in in H0.\n      apply in_inv in H0.\n      destruct H0.\n      +++ injection H;intros;clear H;subst.\n          contradiction.\n      +++ eauto using base.\n    ++ (* cn <> cname *)\n      apply ind.\n      assert (exists CC0 CC1,\n                  CC = CC0 ++ ((JFCDecl name (Some dname) fields methods) :: CC1))\n         by eauto using find_class_decompose_program.\n      destruct H4 as [CC0 [CC1 H4]].\n      rewrite H4 in *.\n      assert (exists D', find_class\n                           (JFCDecl name (Some dname) fields methods ::CC1)\n                           dname = Some D').\n      {\n        rewrite app_comm_cons in H1.\n        assert (subtype_well_founded\n                  (JFCDecl name (Some dname) fields methods :: CC1))\n          by (rewrite app_comm_cons in H2;\n              eauto using subtype_well_founded_decompose_program).\n        eapply subtype_get_superclass;eauto 3 using subtype_well_founded_further.\n        assert (find_class (JFCDecl name (Some dname) fields methods :: CC1)\n                           name =\n                Some (JFCDecl name (Some dname) fields methods)).\n        simpl.\n        destruct (JFClassName_dec name name); try contradiction;auto.\n        apply H6.\n      }\n      destruct H5.\n      assert (exists C',\n                 find_class\n                   (CC0 ++ (JFCDecl name (Some dname) fields methods) :: CC1)\n                   dname = Some C') by eauto with myhints.\n      destruct H6.\n      eapply IHCC; eauto 2 using subtype_well_founded_further.\nQed.\n\n\nLemma subtype_well_founded_contains_object:\n  forall CC name cl,\n    names_unique CC ->\n    subtype_well_founded CC ->\n    find_class CC name = Some cl ->\n    program_contains CC JFObjectName = true.\nProof.\n  induction CC.\n  * intros.\n    unfold find_class in H1.\n    discriminate H1.\n  * intros.\n    destruct a.\n    destruct (JFClassName_dec cn JFObjectName).\n    rewrite e.\n    unfold program_contains.\n    destruct (JFClassName_dec JFObjectName JFObjectName).\n    - auto.\n    - intuition.\n    - destruct (JFClassName_dec cn name).\n      destruct CC.\n      (* CC = [] *)\n      -- unfold subtype_well_founded in H0.\n         destruct ex.\n         unfold number_of_extends in H0.\n         lapply (H0 cn cl); intros.\n         destruct H2.\n         destruct (JFClassName_dec cn cn).\n         discriminate H2.\n         discriminate H2.\n         rewrite e in *.\n         auto.\n         unfold number_of_extends in H0.\n         lapply (H0 cn cl); intros.\n         destruct (JFClassName_dec cn JFObjectName).\n         auto.\n         destruct H2.\n         discriminate H2.\n         lapply (H0 cn cl); intros.\n         destruct (JFClassName_dec cn JFObjectName).\n         intuition.\n         destruct H2.\n         discriminate H2.\n         auto.\n         rewrite e in *.\n         auto.\n      (* CC = hd :: tl *)\n      -- destruct j.\n         lapply (IHCC cn0 (JFCDecl cn0 ex0 fields0 methods0));intros.\n         assert (program_contains (JFCDecl cn0 ex0 fields0 methods0 :: CC) JFObjectName = true).\n         apply H2.\n         + eapply subtype_well_founded_further.\n           apply H.\n           apply H0.\n         + apply find_class_eq.\n         + eapply program_contains_further.\n           auto.\n         + eapply names_unique_further.\n           apply H.\n      -- assert (program_contains CC JFObjectName = true). {\n           apply (IHCC name cl);eauto using subtype_well_founded_further, find_class_further_neq.\n         }\n         eauto using program_contains_further.\nQed.\n\nLemma subtype_well_founded_program_contains_further:\n  forall CC a b,\n    names_unique (a::b::CC) ->\n    (program_contains (a::b::CC) JFObjectName) = true ->\n    subtype_well_founded (a::b::CC) ->\n    (program_contains (b::CC) JFObjectName) = true.\nProof.\n  induction CC.\n  * intros.\n    destruct a.\n    destruct b.\n    destruct (JFClassName_dec cn JFObjectName).\n    ** subst.\n       assert (JFObjectName <> cn0)\n         by (eapply names_unique_in_neq;eauto;apply in_eq).\n       unfold subtype_well_founded in H1.\n       assert (exists n : nat,\n                  number_of_extends\n                    [JFCDecl JFObjectName ex fields methods;\n                     JFCDecl cn0 ex0 fields0 methods0] cn0 = Some n).\n       eapply H1.\n       eapply find_class_same;eauto 2.\n       apply find_class_eq.\n       unfold number_of_extends in H3.\n       destruct ex.\n       *** destruct (JFClassName_dec JFObjectName cn0);try contradiction.\n           destruct ex0.\n           destruct (JFClassName_dec cn0 cn0);destruct H3;discriminate H3.\n           destruct (JFClassName_dec cn0 JFObjectName);\n             try (rewrite e in *;contradiction).\n           destruct H3.\n           discriminate H3.\n       *** destruct (JFClassName_dec JFObjectName JFObjectName);\n             try contradiction.\n           clear e.\n           destruct H3.\n           destruct (JFClassName_dec cn0 JFObjectName);\n             try rewrite e in *;try contradiction.\n           destruct ex0.\n           destruct (JFClassName_dec cn0 cn0);discriminate H3.\n           discriminate H3.\n    ** eapply program_contains_further_neq;eauto.\n  * intros.\n    destruct b.\n    eapply subtype_well_founded_contains_object;eauto 2.\n    eauto using subtype_well_founded_further.\n    eapply find_class_eq.\nQed.\n\nLemma number_of_extends_compose_none_eq:\n  forall flds mthds CC C D n,\n    subtype_well_founded ((JFCDecl D None flds mthds) :: CC) ->\n    number_of_extends CC C = Some n ->\n    C<>D ->\n    number_of_extends ((JFCDecl D None flds mthds) :: CC) C = Some n.\nProof.\n  intros.\n  simpl.\n  destruct (JFClassName_dec D JFObjectName).\n  + subst.\n    destruct (JFClassName_dec C JFObjectName);try contradiction;auto.\n  + unfold subtype_well_founded in H.\n    pose find_class_eq.\n    eapply H in e.\n    decompose_ex e.\n    scrush.\nQed.\n\n\nLemma number_of_extends_some:\n  forall CC dcl CC0,\n    names_unique CC ->\n    subtype_well_founded CC ->\n    CC = dcl :: CC0 ->\n    exists n C, number_of_extends CC C = Some n.\nProof.\n  induction CC.\n  + intros. discriminate H1.\n  + intros.\n    injection H1;intros;subst. clear H1.\n    destruct dcl.\n    destruct CC0.\n    ++ simpl.\n       unfold subtype_well_founded in H0.\n       pose find_class_eq.\n       eapply H0 in e.\n       decompose_ex e.\n       simpl in e.\n       destruct ex; try (destruct (JFClassName_dec cn cn);try contradiction; try discriminate e).\n       destruct (JFClassName_dec cn JFObjectName); try discriminate e.\n       exists 0, cn.\n       destruct (JFClassName_dec cn JFObjectName);try contradiction;auto.\n    ++ generalize H0;intros.\n       eapply subtype_well_founded_further in H1;eauto.\n       eapply IHCC in H1;eauto.\n       decompose_ex H1.\n       destruct (JFClassName_dec C cn).\n       +++ subst.\n           eapply number_of_extends_find_class_simple in H1;eauto.\n           decompose_ex H1.\n           destruct x.\n           generalize H1;intros.\n           eapply find_class_eq_name in H2.\n           subst.\n           eapply find_class_in in H1.\n           eapply names_unique_in_neq in H1;eauto.\n           contradiction.\n       +++ exists n, C.\n           destruct ex.\n           ++++ eapply number_of_extends_compose;\n                  auto with zarith.\n           ++++ eapply number_of_extends_compose_none_eq;eauto.\nQed.\n  \nLemma subtype_well_founded_neq:\n  forall CC name name' fields methods,\n    names_unique  (JFCDecl name (Some name') fields methods :: CC) ->\n    subtype_well_founded (JFCDecl name (Some name') fields methods :: CC) ->\n    name <> name'.\nProof.\n  intros.\n  unfold subtype_well_founded in H0.\n  intro.\n  subst name'.\n  specialize H0 with name (JFCDecl name (Some name) fields methods).\n  lapply H0;intros.\n  destruct H1.\n  assert (number_of_extends CC name = Some (x - 1) /\\ x > 0) by eauto using number_of_extends_decompose.\n  assert (exists x : JFClassDeclaration, find_class CC name = Some x).\n  eapply number_of_extends_find_class_simple.\n  decompose [and] H2;clear H2.\n  apply H3.\n  assert (count_occ Bool.bool_dec (map (is_class_name name) CC) true = 0) by eauto.\n  destruct H3.\n  assert (name<>name) by eauto 3 using is_class_and_occ_zero.\n  tauto.\n  apply find_class_eq.\nQed.\n\nLemma subtype_well_founded_find_class_neq:\n  forall CC name name' fields methods,\n    names_unique  CC ->\n    subtype_well_founded CC ->\n    find_class CC name = Some (JFCDecl name (Some name') fields methods) ->\n    name <> name'.\nProof.\n  induction CC.\n  + intros.\n    discriminate H1.\n  + intros.\n    destruct a.\n    simpl in H1.\n    destruct (JFClassName_dec cn name).\n    ++ subst.\n       injection H1;intros.\n       subst.\n       eauto using subtype_well_founded_neq.\n    ++ eauto 4 using subtype_well_founded_further.\nQed.\n\n\n\n(** The property that all class names occur in the program uniquely. *)\nDefinition if_not_extended_then_object (cd:JFClassDeclaration) :=\n  match cd with\n    | JFCDecl cn None _ _ => cn = JFObjectName\n    | JFCDecl _ (Some _) _ _ => cd = cd\n  end.\n\n(** The property that only Object class is not an extension of another class *)\nDefinition extensions_in_all_but_object (CC:JFProgram) :=\n  Forall (if_not_extended_then_object) CC.\n\nLemma extensions_in_all_but_object_further:\nforall (CC:JFProgram) (cd:JFClassDeclaration),\n    extensions_in_all_but_object (cd::CC) ->\n    extensions_in_all_but_object CC.\nProof.\n  intros.\n  unfold extensions_in_all_but_object in *.\n  apply Forall_forall.\n  assert (forall x : JFClassDeclaration, In x (cd::CC) -> if_not_extended_then_object x).\n  apply Forall_forall.\n  auto.\n  firstorder.\nQed.\n\nLemma names_unique_subtype_well_founded_extensions_in_all_but_object:\nforall (CC:JFProgram) (cd:JFClassDeclaration),\n  names_unique CC ->\n  subtype_well_founded CC ->\n  extensions_in_all_but_object CC.\nProof.\n  induction CC.\n  + intros.\n    unfold extensions_in_all_but_object.\n    auto.\n  + intros.\n    destruct a.\n    destruct (JFClassName_dec cn JFObjectName).\n    ++ subst.\n       unfold extensions_in_all_but_object.\n       eapply Forall_cons;eauto.\n       +++ simpl.\n           destruct ex;auto.\n       +++ fold (extensions_in_all_but_object CC).\n           unfold subtype_well_founded in H0.\n           eapply IHCC;eauto using subtype_well_founded_further.\n    ++ unfold extensions_in_all_but_object.\n       eapply Forall_cons;eauto.\n       +++ simpl.\n           destruct ex; eauto.\n           unfold subtype_well_founded in H0.\n           pose find_class_eq as Fcl.\n           apply H0 in Fcl.\n           decompose_ex Fcl.\n           simpl in Fcl.\n           destruct (JFClassName_dec cn JFObjectName);try contradiction.\n           inversion Fcl.\n       +++ fold (extensions_in_all_but_object CC).\n           unfold subtype_well_founded in H0.\n           eapply IHCC;eauto using subtype_well_founded_further.\nQed.\n\nHint Resolve  extensions_in_all_but_object_further subtype_well_founded_further subtype_well_founded_decompose_program.\n  \n(** The property that Object class is not extended. As\n    Java Language Specification says in Section 8.1.4:\n    \"The extends clause must not appear in the definition \n    of the class Object, or a compile-time error occurs, \n    because it is the primordial class and has no direct superclass.\" *)\nDefinition object_not_extended (cd:JFClassDeclaration) :=\n  match cd with\n    | JFCDecl cn ex _ _ => cn = JFObjectName -> ex = None\n  end.\n\n\n(** A single check that Object is not extended is\n    lifted to the whole program. *)\nDefinition object_is_not_extended (CC:JFProgram) :=\n  Forall (object_not_extended) CC.\n\nLemma object_is_not_extended_further:\nforall (CC:JFProgram) (cd:JFClassDeclaration),\n    object_is_not_extended (cd::CC) ->\n    object_is_not_extended CC.\nProof.\n  intros.\n  unfold object_is_not_extended in *.\n  apply Forall_forall.\n  assert (forall x : JFClassDeclaration, In x (cd::CC) -> object_not_extended x).\n  apply Forall_forall.\n  auto.\n  firstorder.\nQed.\n\nLemma object_is_not_extended_first:\n  forall (CC:JFProgram) cn x fs ms,\n    object_is_not_extended (JFCDecl cn (Some x) fs ms :: CC) ->\n    cn <> JFObjectName.\nProof.\n  intros.\n  unfold object_is_not_extended in H.\n  apply Forall_inv in H.\n  unfold object_not_extended in H.\n  intro.\n  lapply H; intros.\n  discriminate H1.\n  auto.\nQed.\n\nLemma extends_further_object:\n  forall (CC:JFProgram) (cd:JFClassDeclaration) (cn dn:JFClassName),\n   object_is_not_extended (cd :: CC) ->\n   JFObject = JFClass cn -> extends (cd :: CC) cn dn -> extends CC cn dn.\nProof.\n  induction CC.\n  + intros.\n    destruct cd.\n    unfold object_is_not_extended in *.\n    apply Forall_inv in H.\n    unfold object_not_extended in *.\n    inversion H1.\n    repeat destruct H9.\n    auto.\n  + intros.\n    inversion H1.\n    unfold JFObject in H0.\n    injection H0; intros.\n    rewrite <- H7 in *.\n    unfold object_is_not_extended in H.\n    apply Forall_inv in H.\n    rewrite <- H2 in H.\n    unfold object_not_extended in H.\n    lapply H.\n    intros.\n    discriminate H8.\n    auto.\n    auto.\nQed.\n\nLemma object_is_not_extended_extends_neq:\n  forall CC cn dn,\n    object_is_not_extended CC ->\n    extends CC cn dn ->\n    cn <> JFObjectName.\nProof.\n  induction 2.\n  + eauto 2 using object_is_not_extended_first.\n  + eauto 3 using object_is_not_extended_further.\nQed.\n\nLemma number_of_extends_object_is_not_extended:\n  forall CC cd CC0,\n    names_unique CC ->\n    subtype_well_founded CC ->\n    CC = cd :: CC0 ->\n    object_is_not_extended CC.\nProof.\n  induction CC.\n  + intros cd CC0 Nuq.\n    intros.\n    discriminate H0.\n  + intros cd CC0 Nuq.\n    intros.\n    rename H into GH0.\n    generalize GH0;intros.\n    destruct a.\n    destruct ex.\n    ++ unfold subtype_well_founded in GH1.\n       pose find_class_eq.\n       eapply GH1 in e.\n       decompose_ex e.\n       simpl in e.\n       destruct (JFClassName_dec cn cn);try contradiction.\n       destruct (number_of_extends CC j) eqn:?; try congruence.\n       +++ generalize Heqo;intros.\n           eapply number_of_extends_object in Heqo0;eauto.\n           destruct (JFClassName_dec cn JFObjectName).\n           ++++ subst.\n                eapply program_contains_find_class in Heqo0.\n                decompose_ex Heqo0.\n                destruct cd0.\n                generalize Heqo0;intros.\n                eapply find_class_eq_name in Heqo1.\n                subst.\n                eapply find_class_in in Heqo0.\n                eapply names_unique_in_neq in Heqo0;eauto 1.\n                contradiction.\n           ++++ unfold object_is_not_extended.\n                eapply Forall_cons; try (simpl;contradiction).\n                fold (object_is_not_extended CC).\n                destruct CC; try discriminate Heqo0.\n                eauto.\n    ++ destruct (JFClassName_dec cn JFObjectName).\n       +++ subst.\n           unfold object_is_not_extended.\n           apply Forall_cons; simpl;auto.\n           fold (object_is_not_extended CC).\n           destruct CC.\n           ++++ unfold object_is_not_extended;auto.\n           ++++ destruct j.\n                unfold subtype_well_founded in GH0.\n                assert (JFObjectName <> cn). {\n                  intro.\n                  rewrite H in Nuq.\n                  eapply names_unique_in_neq in Nuq.\n                  eapply Nuq.\n                  trivial. \n                  eapply in_eq.\n                }\n                eauto.\n       +++ unfold object_is_not_extended.\n           apply Forall_cons; simpl;auto.\n           destruct CC.\n           ++++ auto.\n           ++++ eapply IHCC;eauto 2.\nQed.\n\nHint Resolve  object_is_not_extended_extends_neq extends_further_object object_is_not_extended_first object_is_not_extended_further.\n    \n\nInductive subtyping (CC: JFProgram) : JFCId -> JFCId -> Prop :=\n| subrefl  : forall (C:JFCId), subtyping CC C C\n| subobj   : forall (C:JFCId), subtyping CC C JFObject\n| botobj   : forall (C:JFCId), subtyping CC JFBotClass C\n| substep  : forall (C:JFCId) (D:JFCId) (E:JFCId)\n                    (cn:JFClassName) (dn:JFClassName),\n               C = JFClass cn -> D = JFClass dn ->\n               extends CC cn dn ->\n               subtyping CC D E -> subtyping CC C E.\n\nHint Constructors subtyping.\n\n  \nLemma subtyping_further:\n  forall (CC:JFProgram) (C:JFCId) (D:JFCId) (cd:JFClassDeclaration),\n    subtyping CC C D -> subtyping (cd :: CC) C D.\nProof. \n  induction 1.\n  * auto.\n  * apply subobj.\n  * auto.\n  * eapply (substep (cd :: CC) C D E).\n    + eauto.\n    + eauto.\n    + inversion H1.\n      - destruct cd.\n        apply ind.\n        rewrite <- H5 in *.\n        rewrite <- H6 in *.\n        rewrite H4.\n        auto.\n      - destruct cd. apply ind.\n        rewrite H4.\n        auto.\n    + auto.\nQed.\n\nLemma subtyping_further_deep:\n  forall (CC:JFProgram) (CC':JFProgram) (DD:JFProgram) (C:JFCId) (D:JFCId) (cd:JFClassDeclaration),\n    subtyping CC C D ->\n    CC = CC' ++ DD ->\n    subtyping (CC' ++ cd :: DD) C D.\nProof.\n  induction 1; eauto.\nQed.\n\nLemma substep_deep:\n  forall DD dn decl CC cn fields methods,\n    find_class DD dn = Some decl ->\n    subtyping (CC ++ JFCDecl cn (Some dn) fields methods :: DD) (JFClass cn) (JFClass dn).\nProof.\n  induction CC.\n  + intros.\n    simpl.\n    eapply substep; try trivial.\n    destruct decl.\n    generalize H;intros; eapply find_class_eq_name in H0; subst.\n    eapply base; eauto using find_class_in.\n  + intros.\n    simpl.\n    eapply subtyping_further.\n    eauto.\nQed.\n\nLemma subtyping_first_in:\n  forall CC C D cn dn,\n    subtyping CC C D ->\n    C = (JFClass cn) ->\n    D = (JFClass dn) ->\n    D <> JFObject ->\n    cn <> dn ->\n    exists ex flds mthds,\n      In (JFCDecl cn ex flds mthds) CC.\nProof.\n  induction 1;try congruence.\n  intros.\n  subst.\n  eapply extends_in_first in H1.\n  injection H3;clear H3;intros;subst.\n  sauto.\nQed.\n\nLemma subtyping_find_class_further:\n  forall CC D E,\n    subtyping CC D E ->\n    forall  CC0 cd cn' ex fields methods dn en,\n      CC = (cd :: CC0) ->\n      cd = JFCDecl cn' ex fields methods ->\n      D = (JFClass dn) ->\n      E = (JFClass en) ->\n      E <> JFObject ->\n      dn <> en ->\n      dn <> cn' ->\n      exists cd, find_class CC0 dn = Some cd.\nProof.\n  intros CC D E.\n  intro.\n  induction H.\n  * intros.\n    congruence.\n  * intros.\n    contradiction.\n  * intros.\n    congruence.\n  * intros.\n    subst.\n    injection H5;intros;clear H5.\n    subst.\n    eapply extends_in_first in H1.\n    destruct H1. destruct H.\n    eapply in_inv in H.\n    destruct H.\n    ** congruence.\n    ** eapply in_find_class_raw in H.\n       do 3 destruct H.\n       clear -H.\n       firstorder.\nQed.\n\n\n\n    \nLemma object_is_not_subtype:\n  forall (CC:JFProgram) (C:JFCId),\n    names_unique CC -> \n    object_is_not_extended CC ->\n    extensions_in_all_but_object CC ->\n    subtyping CC JFObject C -> C = JFObject.\nProof.\n  intros until 3.\n  cut (forall D, subtyping CC D C -> D = JFObject -> C = JFObject); eauto.\n  induction 1; intros; trivial; try discriminate.\n  apply IHsubtyping.\n  unfold JFObject in *.\n  match goal with\n    [ H : (extends _ _ _) |- _ ] => apply object_is_not_extended_extends_neq in H; eauto 1\n  end.\n  congruence.\nQed.\n\nLemma subtrans : forall (CC:JFProgram) (C:JFCId) (D:JFCId) (E:JFCId),\n                   (program_contains CC JFObjectName) = true ->\n                   names_unique CC -> \n                   object_is_not_extended CC ->\n                   extensions_in_all_but_object CC ->\n                   subtyping CC C D -> subtyping CC D E -> subtyping CC C E.\nProof.\n  induction 5.\n  * trivial.\n  * intro Hsub.\n    apply object_is_not_subtype in Hsub; eauto 1.\n    subst.\n    constructor.\n  * intros; constructor.\n  * intros.\n    eauto.\nQed.\n\n\n\nLemma subtyping_less:\n  forall CC C D,\n    subtyping CC C D ->\n    forall  dn en,\n    subtyping CC C (JFClass en) ->\n    D = (JFClass dn) ->\n    dn <> en ->\n    dn <> JFObjectName ->\n    en <> JFObjectName ->\n    names_unique CC ->\n    (subtyping CC D (JFClass en)) \\/ (subtyping CC (JFClass en) D) \\/ (C = JFBotClass).\nProof.\n  induction 1.\n  + intros.\n    left;auto.\n  + intros.\n    inversion H;subst.\n    ++ right;left;auto.\n    ++ contradiction.\n    ++ right;right;auto.\n    ++ unfold JFObject in H0.\n       congruence.\n  + intros.\n    right;right;auto.\n  + intros.\n    inversion H3;subst.\n    ++ injection H10;intros.\n       subst.\n       right;left.\n       eapply substep;try apply H1;eauto.\n    ++ contradiction.\n    ++ discriminate H9.\n    ++ injection H9;intros.\n       subst.\n       eapply extends_unique_dir in H11;try eapply H1;eauto.\n       subst.\n       eapply IHsubtyping in H12;eauto 1.\n       destruct H12 as [H12|H12];try tauto.\n       destruct H12 as [H12|H12];try tauto.\n       discriminate H12.\nQed.\n\n    \nLemma subtyping_greater_in:\n  forall CC C D,\n    subtyping CC C D ->\n    forall cn dn,\n    C = (JFClass cn) ->\n    D = (JFClass dn) ->\n    names_unique CC ->\n    object_is_not_extended CC ->\n    extensions_in_all_but_object CC ->\n    cn <> dn ->\n    dn <> JFObjectName ->\n    exists ex fields methods,\n      In (JFCDecl dn ex fields methods) CC.\nProof.\n  intros CC C D.\n  intro.\n  induction H.\n  * intros.\n    congruence.\n  * intros.\n    injection H0;intros.\n    rewrite H6 in *.\n    contradiction.\n  * intros.\n    discriminate H.\n  * intros.\n    subst. \n    injection H3;intros;clear H3;subst.\n    destruct (JFClassName_dec dn dn0).\n    ** subst.\n       destruct CC.\n       *** inversion H1.\n       *** assert (exists\n                      (ex : option JFClassName)\n                      (fields : list JFFieldDeclaration) \n                      (methods : list JFMethodDeclaration),\n                      In (JFCDecl dn0 ex fields methods) CC).\n           eapply extends_in_second_second;eauto.\n           do 3 destruct H.\n           exists x, x0, x1.\n           eauto using in_cons.\n    ** eapply IHsubtyping;eauto.\nQed.\n               \n       \nLemma subtyping_further_neq:\n  forall CC CC0 D E,\n    subtyping CC0 D E ->\n    names_unique CC0 -> \n    forall cn ex fields methods,\n      CC0 = (JFCDecl cn ex fields methods :: CC) ->\n      D <> JFClass cn ->\n      subtyping CC D E.\nProof.\n  induction 1.\n  - auto.\n  - auto.\n  - auto.\n  - intros.\n    eapply substep.\n    + eauto.\n    + apply H0.\n    + eapply extends_narrower.\n      rewrite H4 in H1.\n      eauto.\n      congruence.\n    + assert (D <> JFClass cn0).\n      eapply extends_neq.\n      rewrite H4 in H3.\n      eauto.\n      exists cn,dn.\n      rewrite H4 in H1.\n      eauto.\n      eapply IHsubtyping.\n      * eauto.\n      * eauto.\n      * auto.\nQed.\n\n\n\n\nLemma subtyping_not_bot:\n  forall CC C D,\n    subtyping CC C D -> D = JFBotClass  -> C = JFBotClass.\nProof.\n  induction 1.\n  + auto.\n  + intros.\n    discriminate H.\n  + auto.\n  + intros.\n    lapply IHsubtyping.\n    intros.\n    subst D.\n    discriminate H4.\n    auto.\nQed.\n\n\n\n\nLemma extends_subtyping_eq:\n  forall CC C D,\n    subtyping CC D C ->\n    forall cn dn,\n      D = (JFClass dn) ->\n      C = (JFClass cn) ->\n      names_unique CC ->\n      object_is_not_extended CC ->\n      extensions_in_all_but_object CC ->\n      extends CC cn dn ->\n      cn = dn.\nProof.\n  induction CC.\n  + intros.\n    inversion H5.\n  + intros.\n    destruct a.\n    destruct (JFClassName_dec cn cn0).\n    ++ subst.\n       destruct (JFClassName_dec dn cn0).\n       +++ subst;auto.\n       +++ eapply subtyping_further_neq in H;eauto 2;try congruence.\n           eapply subtyping_greater_in in H;eauto 2;try congruence.\n           decompose_ex H.\n           eapply names_unique_in_neq in H;eauto 1.\n           contradiction.\n    ++ subst.\n       destruct (JFClassName_dec cn0 dn).\n       +++ subst.\n           eapply extends_narrower in H5;eauto 2.\n           eapply extends_in_second in H5;eauto 2.\n           decompose_ex H5.\n           eapply names_unique_in_neq in H5;eauto 1.\n           contradiction.\n       +++ eapply extends_narrower in H5;eauto 2.\n           eapply subtyping_further_neq in H;eauto 2;try congruence.\n           eauto 5.\nQed.\n           \nLemma subantisymm :\n  forall CC C D,\n    names_unique CC ->\n    object_is_not_extended CC ->\n    extensions_in_all_but_object CC ->\n    subtyping CC C D -> subtyping CC D C -> C = D.\nProof.\n  induction CC.\n  * intros.\n    inversion H2;eauto 2;subst.\n    ** eauto 2 using object_is_not_subtype.\n    ** eapply subtyping_not_bot in H3;eauto 2.\n    ** inversion H6.\n  * intros.\n    destruct a.\n    destruct C;try (eapply subtyping_not_bot in H3;eauto 2;congruence).\n    destruct D;eauto 2 using subtyping_not_bot.\n    destruct (JFClassName_dec cn cn0).\n    ** subst.\n       destruct (JFClassName_dec cn1 cn0);try congruence.\n       destruct (JFClassName_dec cn0 JFObjectName); try (subst; eapply object_is_not_subtype in H2;eauto 2).\n       eapply subtyping_further_neq in H3;eauto 2;try congruence.\n       eapply subtyping_greater_in in H3;eauto 2;try congruence.\n       decompose_ex H3.\n       eapply names_unique_in_neq in H3;eauto 1.\n       contradiction.\n    ** destruct (JFClassName_dec cn cn1).\n       *** subst.\n           generalize H1;intros.\n           destruct (JFClassName_dec cn1 JFObjectName); try (subst; eapply object_is_not_subtype in H1;eauto 2).\n           eapply subtyping_further_neq in H2;eauto 2;try congruence.\n           eapply subtyping_greater_in in H2;eauto 2;try congruence.\n           decompose_ex H2.\n           eapply names_unique_in_neq in H2;eauto 1.\n           contradiction.\n       *** eapply subtyping_further_neq in H2;eauto 2;try congruence.\n           eapply subtyping_further_neq in H3;eauto 2;try congruence.\n           eauto.\nQed.\n           \nLemma subtyping_compl_monotone:\n  forall CC' C D,\n    subtyping CC' C D ->\n    forall d CC DD E,\n      CC' = (d :: CC) ++ DD ->\n      subtyping ((d :: CC) ++ E :: DD) C D.\nProof.\n  induction 1;eauto.\nQed.\n  \n\nLemma subtyping_monotone:\n  forall CC C D,\n    subtyping CC C D ->\n    forall CC' DD E,\n      CC = (CC' ++ DD) ->\n      subtyping (CC' ++ E :: DD) C D.\nProof.\n  induction 1;eauto.\nQed.\n\n\n(* subtyping decidability *)\n\nLemma skipping_extends_loop:\n  forall (CC : JFProgram) (C E : JFCId),\n    subtyping CC C E ->\n    forall D cn dn,\n      C <> E ->\n      E <> JFObject ->\n      C = JFClass cn ->\n      D = JFClass dn ->\n      extends CC cn dn ->\n      subtyping CC D E ->\n      exists dn', extends CC cn dn' /\\ subtyping CC (JFClass dn') E /\\ dn' <> cn.\nProof.\n  induction 1.\n  + intros.\n    subst. congruence.\n  + congruence.\n  + intros.\n    discriminate H1.\n  + intros ? cn0 dn0.\n    intros.\n    subst.\n    destruct (JFClassName_dec cn0 dn0).\n    ++ subst.\n       injection H5;clear H5;intro;subst.\n       inversion H2; try (subst; exists dn; repeat split;eauto;congruence).\n       subst.\n       injection H; clear H;intro;subst.\n       destruct (JFClassName_dec cn dn0).\n       +++ subst;eapply IHsubtyping;eauto.\n       +++ exists cn.\n           intuition.\n    ++ exists dn0;intuition.\nQed.\n\n    \n\n\nInductive subtyping_witness : JFProgram -> JFProgram -> JFClassName -> JFClassName -> Prop  :=\n| empty_witness : forall CC cn, subtyping_witness [] CC cn cn\n| head_witness :\n    forall DD DD' DD'' CC cn cn' dn fields methods cd,\n      DD = DD' ++ (JFCDecl cn (Some cn') fields methods :: DD'') ->\n      ~ In (JFCDecl cn (Some cn') fields methods) DD' ->\n      find_class DD'' cn' = Some cd ->\n      subtyping_witness CC DD cn' dn ->\n      subtyping_witness (JFCDecl cn (Some cn') fields methods :: CC) DD cn dn.\n\nHint Constructors subtyping_witness : myhints.\nHint Constructors subtyping_witness.\n\nLemma subtyping_witness_only_some:\n  forall CC DD cn dn en ex flds mthds,\n    subtyping_witness CC DD cn dn ->\n    In (JFCDecl en ex flds mthds) CC -> exists dn, ex = Some dn.\nProof.\n  induction CC.\n  + intros.\n    inversion H0.\n  + intros.\n    inversion H.\n    subst.\n    simpl in H0.\n    destruct H0.\n    ++ injection H0;clear H0;intros;subst.\n       eexists;eauto.\n    ++ eapply IHCC in H0;eauto.\nQed.\n       \nLemma decompose_double_app:\n  forall A,\n  forall n (DD:list A) DD' EE EE',\n    length DD = n ->\n    DD ++ DD' = EE ++ EE' ->\n    (exists DD'', DD = EE ++ DD'' /\\ EE' = DD'' ++ DD') \\/\n    (exists DD'', EE = DD ++ DD'' /\\ DD' = DD'' ++ EE').\nProof.\n  induction n.\n  + intros.\n    eapply length_zero_iff_nil in H.\n    subst.\n    right.\n    exists EE.\n    simpl in *.\n    eauto.\n  + intros.\n    destruct DD; try inversion H.\n    assert (length EE <= n+1 \\/ n+1 < length EE)\n      by eauto using Nat.le_gt_cases.\n    destruct H1.\n    ++ left.\n       generalize H1.\n       generalize H0.\n       generalize EE.\n       induction EE0.\n       +++ exists (a :: DD).\n           simpl in *.\n           eauto.\n       +++ intros.\n           simpl in H3.\n           injection H3;intros.\n           subst.\n           eapply IHn in H5;eauto.\n           destruct H5.\n           ++++ decompose_ex H2.\n                decompose_and H2.\n                subst.\n                eexists.\n                simpl.\n                auto.\n           ++++ simpl in H4.\n                decompose_ex H2.\n                decompose_and H2.\n                eapply f_equal in H5.\n                rewrite app_length in H5.\n                rewrite H5 in H4.\n                assert (length DD'' =0) by eauto with zarith.\n                apply length_zero_iff_nil in H2.\n                subst.\n                simpl in H3.\n                injection H3;intros;subst.\n                eapply app_inv_tail in H2.\n                subst.\n                exists [].\n                simpl.\n                rewrite app_nil_r.\n                eauto.\n    ++ right.\n       generalize H0.\n       generalize H1.\n       generalize EE.\n       induction EE0.\n       +++ intros.\n           simpl in H3.\n           eauto with zarith.\n           pose (NPeano.Nat.nlt_0_r (n+1)).\n           contradiction.\n       +++ intros.\n           simpl in H4.\n           injection H4;intros;subst a0.\n           eapply IHn in H5;eauto.\n           destruct H5.\n           ++++ decompose_ex H5.\n                decompose_and H5.\n                subst.\n                rewrite app_assoc in H0.\n                eapply app_inv_tail in H0.\n                rewrite app_comm_cons in H0.\n                eapply app_inv_tail in H0.\n                subst EE.\n                simpl in H1.\n                rewrite app_length in H1.\n                assert (length DD'' < 0) by eauto with zarith.\n                pose (Nat.nlt_0_r (Datatypes.length DD'')).\n                contradiction.\n           ++++ decompose_ex H5.\n                decompose_and H5.\n                subst.\n                exists DD'';eauto.\nQed.\n                \nLemma subtyping_witness_monotone:\n  forall CC DD DD' cn dn,\n    subtyping_witness CC (DD ++ DD') cn dn ->\n    forall dd,\n    subtyping_witness CC (DD ++ dd :: DD') cn dn.\nProof.\n  induction CC.\n  + intros.\n    inversion H.\n    subst.\n    eauto.\n  + intros.\n    inversion H.\n    subst.\n    eapply decompose_double_app in H2;eauto.\n    destruct H2.\n    ++ decompose_ex H0.\n       decompose_and H0.\n       subst DD.\n       destruct DD''0.\n       +++ simpl in H2. subst DD'.\n           destruct (JFClassDeclaration_dec dd (JFCDecl cn (Some cn') fields methods)).\n           ++++ subst dd.\n                eapply find_class_lift_cons in H4.\n                decompose_ex H4.\n                eapply head_witness; try eapply H4; try eapply H3.\n                simpl in *.\n                rewrite app_nil_r.\n                eauto.\n                eapply IHCC;eauto.\n           ++++ assert (~ In (JFCDecl cn (Some cn') fields methods) (DD'0 ++ [dd])). {\n                  intro.\n                  apply H3.\n                  eapply in_app_or in H0.\n                  simpl in H0.\n                  destruct H0;eauto.\n                  destruct H0;eauto; try contradiction.\n                } \n                eapply head_witness; try eapply H4; try eapply H0.\n                rewrite app_nil_r.\n                fold (app [dd] (JFCDecl cn (Some cn') fields methods :: DD'')).\n                rewrite app_assoc.\n                auto.\n                eapply IHCC;eauto.\n       +++ simpl in H2.\n           injection H2;intros.\n           subst j.\n           subst DD''.\n           eapply find_class_lift_cons_inside in H4.\n           decompose_ex H4.\n           eapply head_witness; try apply H3;try apply H4.\n           rewrite <- app_assoc.\n           simpl.\n           eauto.\n           eapply IHCC;eauto.\n    ++ decompose_ex H0.\n       decompose_and H0.\n       subst DD'.\n       destruct DD''0.\n       +++ rewrite app_nil_r in H1. subst DD'0.\n           destruct (JFClassDeclaration_dec dd (JFCDecl cn (Some cn') fields methods)).\n           ++++ subst dd.\n                eapply find_class_lift_cons in H4.\n                decompose_ex H4.\n                eapply head_witness; try eapply H4; try eapply H3.\n                simpl in *.\n                eauto.\n                eapply IHCC;eauto.\n           ++++ assert (~ In (JFCDecl cn (Some cn') fields methods) (DD ++ [dd])). {\n                  intro.\n                  apply H3.\n                  eapply in_app_or in H0.\n                  simpl in H0.\n                  destruct H0; eauto.\n                  destruct H0;eauto; try contradiction.\n                }\n                eapply head_witness; try eapply H4; try eapply H0.\n                simpl.\n                fold (app [dd] (JFCDecl cn (Some cn') fields methods :: DD'')).\n                rewrite app_assoc.\n                auto.\n                eapply IHCC;eauto.\n       +++ destruct (JFClassDeclaration_dec dd (JFCDecl cn (Some cn') fields methods)).\n           ++++ subst dd.\n                assert (~ In (JFCDecl cn (Some cn') fields methods) DD). {\n                  intro.\n                  apply H3.\n                  subst.\n                  eapply in_or_app.\n                  left;eauto.\n                }\n                subst DD'0.\n                eapply find_class_lift_cons in H4.\n                decompose_ex H4.\n                eapply find_class_lift in H4.\n                decompose_ex H4.\n                rewrite <- app_comm_cons.\n                eapply head_witness; try apply H4;try apply H0.\n                rewrite app_comm_cons.\n                eauto.\n                eapply IHCC;eauto.\n           ++++ assert (~ In (JFCDecl cn (Some cn') fields methods) (DD ++ dd :: (j :: DD''0))). {\n                  intro.\n                  apply H3.\n                  subst.\n                  eapply in_app_or in H0.\n                  apply in_or_app.\n                  destruct H0.\n                  + left;eauto.\n                  + simpl in H0.\n                    destruct H0.\n                    ++ contradiction.\n                    ++ simpl.\n                       eauto.\n                }\n                subst DD'0.\n                eapply head_witness; try apply H4;try apply H0.\n                rewrite app_comm_cons.\n                rewrite app_assoc.\n                eauto.\n                eapply IHCC;eauto.\nQed.\n\n\nLemma subtyping_witness_smaller_none:\n  forall CC DD cn0 fields methods cn dn,\n  subtyping_witness CC (JFCDecl cn0 None fields methods :: DD) cn dn ->\n  subtyping_witness CC DD cn dn.\nProof.\n  induction CC.\n  + intros.\n    inversion H.\n    subst.\n    eauto.\n  + intros.\n    inversion H.\n    subst.\n    destruct DD'.\n    ++ simpl in H2.\n       injection H2;intros;eauto.\n       inversion H6.\n    ++ simpl in H2.\n       injection H2;intros.\n       eapply head_witness;try eapply H0;eauto.\n       intro.\n       eapply H3.\n       simpl.\n       eauto.\nQed.\n\n\nLemma in_split_notfirst:\n  forall A (eq_dec: forall (x:A) (y:A), {x=y} + {x<>y}),\n  forall l (x:A),\n    In x l -> exists l1 l2, l = l1 ++ (x :: l2) /\\ ~ (In x l1).\nProof.\n  induction l.\n  + intros.\n    inversion H.\n  + intros.\n    destruct (eq_dec x a).\n    ++ subst.\n       exists [], l.\n       split;simpl;auto.\n    ++ simpl in H.\n       destruct H; try congruence.\n       eapply IHl in H.\n       decompose_ex H.\n       decompose [and] H.\n       subst.\n       do 2 eexists.\n       split.\n       rewrite app_comm_cons.\n       auto.\n       intro.\n       apply H1.\n       simpl in H0.\n       destruct H0; try congruence.\nQed.\n\nLemma not_in_first_eq:\n  forall A,\n  forall l1 l1' l2 l2' (x:A) ,\n    l1 ++ x :: l1' = l2 ++ x :: l2' ->\n    ~ In x l1 ->\n    ~ In x l2 ->\n    l1 = l2 /\\ l1' = l2'.\nProof.\n  induction l1.\n  + intros.\n    simpl in H.\n    destruct l2.\n    ++ simpl in H.\n       injection H;intros.\n       subst.\n       auto.\n    ++ simpl in H.\n       simpl in H1.\n       injection H;intros;subst.\n       assert False.\n       apply H1.\n       left;auto.\n       contradiction.\n  + intros.\n    simpl in H.\n    destruct l2.\n    ++ simpl in H.\n       injection H;intros.\n       subst.\n       simpl in H0.\n       assert False.\n       apply H0;left;auto.\n       contradiction.\n    ++ simpl in H.\n       injection H;intros.\n       subst a0.\n       eapply IHl1 in H2.\n       decompose [and] H2.\n       subst.\n       auto.\n       eauto using in_cons.\n       eauto using in_cons.\nQed.\n\n\nLemma subtyping_witness_dec:\n  forall CC DD cn dn,\n    subtyping_witness CC DD cn dn \\/ ~ subtyping_witness CC DD cn dn.\nProof.\n  induction CC.\n  + intros.\n    destruct (JFClassName_dec cn dn).\n    ++ subst.\n       left.\n       auto.\n    ++ right.\n       sauto.\n  + intros.\n    destruct a eqn:?.\n    destruct (JFClassName_dec cn0 cn); [|right;intro;inversion H; try contradiction].\n    subst cn0.\n    destruct ex; [|right;intro;inversion H].\n    destruct (in_dec JFClassDeclaration_dec a DD).\n    ++ eapply in_split_notfirst in i.\n        decompose_ex i.\n        decompose [and] i; clear i.\n        subst DD.\n        destruct (find_class l2 j) eqn:?.\n        +++ edestruct (IHCC (l1 ++ a :: l2)).\n             ++++ left. eapply head_witness.\n                  subst a; eauto.\n                  subst a; eauto.\n                  eauto.\n                  eauto.\n             ++++ right.\n                  intro.\n                  inversion H1.\n                  subst.\n                  eapply not_in_first_eq in H11;eauto.\n        +++ right.\n            intro.\n            inversion H.\n            subst.\n            eapply not_in_first_eq in H10;eauto.\n            destruct H10.\n            subst.\n            rewrite Heqo in H11;discriminate H11.\n        +++ eapply JFClassDeclaration_dec.\n    ++ right.\n       intro.\n       inversion H.\n       subst.\n       apply n.\n       eapply in_or_app.\n       right.\n       simpl.\n       auto.\nQed.\n\n\nLemma subtyping_witness_trans:\n  forall CC DD CC0 cn dn en,\n    subtyping_witness CC DD cn dn ->\n    subtyping_witness CC0 DD dn en ->\n    subtyping_witness (CC ++ CC0) DD cn en.\nProof.\n  induction 1.\n  + intros.\n    simpl;eauto.\n  + intros.\n    simpl.\n    eapply head_witness;try apply H0;try apply H1;trivial.\n    eauto.\nQed.\n\nLemma subtyping_witness_find_class:\n  forall CC DD cn dn,\n    subtyping_witness CC DD cn dn ->\n    cn <> dn ->\n    exists cd, find_class DD dn = Some cd.\nProof.\n  induction 1.\n  + intros;contradiction.\n  + intros.\n    destruct (JFClassName_dec cn' dn).\n    ++ subst cn'.\n       subst.\n       eapply find_class_lift_cons in H1.\n       decompose_ex H1.\n       eapply find_class_lift in H1.\n       decompose_ex H1.\n       eexists;eauto.\n    ++ eapply IHsubtyping_witness;eauto.\nQed.\n\n\nLemma subtyping_witness_skip_result:\n  forall CC' CC DD CC'' cn cn' dn dn' fields methods,\n    subtyping_witness CC DD cn cn' ->\n    CC = CC' ++ (JFCDecl dn (Some dn') fields methods) :: CC'' ->\n    subtyping_witness CC'' DD dn' cn'.\nProof.\n  induction CC'.\n  + intros.\n    simpl in H0.\n    inversion H.\n    ++ subst.\n       inversion H1.\n    ++ subst.\n       injection H5;clear H5;intros;subst.\n       auto.\n  + intros.\n    inversion H; subst.\n    ++ simpl in H1.\n       inversion H1.\n    ++ simpl in H5.\n       injection H5;clear H5;intros;subst.\n       eapply IHCC' in H4;eauto.\nQed.\n\nLemma subtyping_witness_last_decl:\n  forall CC DD cn cn' a CC',\n    subtyping_witness CC DD cn cn' ->\n    CC = a :: CC' ->\n    exists CC'' dn fields methods,\n      CC = CC'' ++ [JFCDecl dn (Some cn') fields methods].\nProof.\n  induction CC.\n  + intros.\n    inversion H0.\n  + intros.\n    inversion H; subst.\n    destruct CC.\n    ++ inversion H9;subst.\n       exists [].\n       do 3 eexists.\n       simpl;eauto.\n    ++ eapply IHCC in H9;auto.\n       decompose_ex H9.\n       do 4 eexists.\n       rewrite H9.\n       rewrite app_comm_cons.\n       eauto.\nQed.\n\nLemma subtyping_witness_skip_loop:\n  forall CC DD CC' CC'' cn cn' dn fields methods,\n    subtyping_witness CC DD cn' dn ->\n    CC = CC' ++ (JFCDecl cn (Some cn') fields methods) :: CC'' ->\n    subtyping_witness CC'' DD cn' dn.\nProof.\n  induction CC''.\n  + intros.\n    assert (exists j CC'', CC = j :: CC''). {\n      destruct CC'.\n      ++ simpl in H0.\n         eexists;eexists.\n         subst;eauto.\n      ++ simpl in H0.\n         eexists;eexists.\n         subst;eauto.\n    }\n    decompose_ex H1.\n    eapply subtyping_witness_last_decl in H;eauto.\n    decompose_ex H.\n    clear H1.\n    subst.\n    eapply app_inj_tail in H.\n    decompose_and H.\n    injection H1;intros;subst.\n    eauto.\n  + intros.\n    inversion H.\n    ++ subst.\n       destruct CC'.\n       +++ simpl in H1.\n           inversion H1.\n       +++ simpl in H1.\n           inversion H1.\n    ++ subst.\n       destruct CC'.\n       +++ simpl in H5.\n           injection H5;intros.\n           subst.\n           auto.\n       +++ eapply subtyping_witness_skip_result in H4.\n           eauto.\n           simpl in H5.\n           injection H5;intros.\n           eauto.\nQed.\n\nLemma is_name_in_or_out:\n  forall cn CC,\n    (exists ex fields' methods', In (JFCDecl cn ex fields' methods') CC) \\/\n    (forall ex (fields' : list JFFieldDeclaration) (methods' : list JFMethodDeclaration),\n        ~ In (JFCDecl cn ex fields' methods') CC).\nProof.\n  induction CC.\n  * right.\n    intros.\n    simpl.\n    auto.\n  * destruct IHCC.\n    ** left.\n       decompose_ex H.\n       do 3 eexists.\n       simpl.\n       right.\n       eauto.\n    ** destruct a.\n       destruct (JFClassName_dec cn cn0).\n       *** subst.\n           left.\n           do 3 eexists.\n           simpl.\n           left.\n           eauto.\n       *** right.\n           intros.\n           intro.\n           eapply H.\n           simpl in H0.\n           destruct H0;try congruence.\n           eauto.\nQed.\n\nLemma in_exists_last:\n  forall CC cn ex fields methods,\n    In (JFCDecl cn ex fields methods) CC ->\n    exists CC' CC'' ex' fields' methods',\n      CC = CC' ++ (JFCDecl cn ex' fields' methods') :: CC'' /\\\n      forall ex'' fields'' methods'', ~ In (JFCDecl cn ex'' fields'' methods'') CC''.\nProof.\n  induction CC.\n  + intros.\n    inversion H.\n  + intros *. destruct (JFClassDeclaration_dec a  (JFCDecl cn ex fields methods)).\n    ++ subst a.\n       intros.\n       pose (is_name_in_or_out cn CC) as H0.\n       destruct H0.\n       +++ decompose_ex H0.\n           eapply IHCC in H0.\n           destruct H0.\n           decompose_ex H0.\n           decompose_and H0.\n           do 5 eexists.\n           split; try eapply H2.\n           rewrite H1.\n           rewrite app_comm_cons.\n           auto.\n       +++  exists [];do 4 eexists.\n            split; try eapply H0.\n            simpl.\n            eauto.\n    ++ intro.\n       simpl in H.\n       destruct H;try congruence.\n       eapply IHCC in H.\n       decompose_ex H.\n       decompose_and H.\n       do 5 eexists.\n       split; try apply H1.\n       subst CC.\n       rewrite app_comm_cons.\n       auto.\nQed.\n\n\nLemma inversion_subtyping_witness:\n  forall CC' CC'' DD cn dn fields methods cn' dn',\n    subtyping_witness (CC' ++ JFCDecl cn (Some dn) fields methods :: CC'') DD cn' dn' ->\n    exists DD' DD'' cd,\n      DD = DD' ++ JFCDecl cn (Some dn) fields methods :: DD'' /\\\n      ~ In (JFCDecl cn (Some dn) fields methods) DD' /\\\n      find_class DD'' dn = Some cd.\nProof.\n  induction CC'.\n  + intros.\n    simpl in *.\n    inversion H.\n    subst.\n    eexists;eauto.\n  + intros.\n    simpl in H.\n    inversion H.\n    subst.\n    eapply IHCC' in H8.\n    decompose_ex H8.\n    decompose_and H8.\n    eexists;eauto.\nQed.\n\nLemma subtyping_witness_loop_exit:\n  forall n CC,\n    length CC <= n ->\n    forall  DD cn dn,\n      length CC > 0 ->\n    subtyping_witness CC DD cn dn ->\n    exists CC' CC'' cn' fields methods, subtyping_witness (JFCDecl cn (Some cn') fields methods :: CC') DD cn dn /\\\n                                        CC = CC'' ++ JFCDecl cn (Some cn') fields methods :: CC' /\\\n                                        forall cn'' fields' methods', ~ In (JFCDecl cn (Some cn'') fields' methods') CC'.\nProof.\n  induction n.\n  + intros.\n    eapply le_n_0_eq in H.\n    symmetry in H.\n    eapply length_zero_iff_nil in H.\n    subst.\n    auto with zarith.\n    simpl in H0.\n    eapply gt_irrefl in H0.\n    contradiction.\n  + intros.\n    destruct CC.\n    ++ intros.\n       inversion H0;subst;contradiction.\n    ++ pose (is_name_in_or_out cn CC) as H2.\n       destruct H2.\n       +++ decompose_ex H2. (* exists cn in CC *)\n           generalize H1;intros.\n           eapply subtyping_witness_only_some in H3;simpl;eauto.\n           decompose_ex H3.\n           subst ex.\n           generalize H2;intros.\n           eapply in_exists_last in H3.\n           decompose_ex H3.\n           decompose_and H3. (* we've found the last occurrence of cn in CC *)\n           generalize H1;intros.\n           subst CC.\n           assert (In (JFCDecl cn ex' fields'0 methods'0) (j :: CC' ++ JFCDecl cn ex' fields'0 methods'0 :: CC'')). {\n             rewrite app_comm_cons.\n             eapply in_or_app.\n             right.\n             simpl.\n             left;trivial.\n           }\n           eapply subtyping_witness_only_some in H3; try apply H4.\n           decompose_ex H3.\n           subst ex'.\n           generalize H1;intros.\n           eapply subtyping_witness_skip_result in H3; try (subst; rewrite app_comm_cons;trivial).\n           do 5 eexists.\n           split;[|split];eauto.\n           rewrite app_comm_cons in H1.\n           eapply inversion_subtyping_witness in H1.\n           decompose_ex H1.\n           decompose_and H1.           \n           eapply head_witness;eauto.\n       +++ generalize H1;intros.\n           inversion H3.\n           subst.\n           exists CC, [].\n           do 3 eexists.\n           eauto.\nQed.\n\nLemma subtyping_witness_find_class_first:\n  forall CC DD cn dn,\n    subtyping_witness CC DD cn dn ->\n    cn <> dn ->\n    exists cd, find_class DD cn = Some cd.\nProof.\n  induction 1.\n  + intros;contradiction.\n  + intros.\n    subst DD.\n    eapply find_class_lift.\n    eapply find_class_eq.\nQed.\n\n\nLemma new_is_in:\n  forall CC DD cn dn cd cn0 ex fields methods,\n  (forall CC' : JFProgram, ~ subtyping_witness CC' DD cn dn) ->\n  subtyping_witness (cd :: CC) (JFCDecl cn0 ex fields methods :: DD) cn dn ->\n  exists CC0 CC1,\n    cd :: CC = CC0 ++ (JFCDecl cn0 ex fields methods) :: CC1.\nProof.\n  induction CC.\n  + intros.\n    inversion H0;subst.\n    inversion H9;subst.\n    destruct DD'.\n    ++ simpl in H3.\n       injection H3;intros;subst.\n       exists [], [];simpl;eauto.\n    ++ simpl in H3.\n       injection H3;intros.\n       eapply head_witness in H1;eauto.\n       +++ eapply H in H1.\n           contradiction.\n       +++ intro.\n           eapply H4.\n           simpl.\n           eauto.\n  + intros.\n    inversion H0.\n    subst.\n    destruct DD'.\n    ++ injection H3;intros;subst.\n       exists [].\n       eexists.\n       simpl.\n       eauto.\n    ++ eapply IHCC in H9.\n       +++ decompose_ex H9.\n           do 2 eexists;rewrite H9.\n           rewrite app_comm_cons.\n           eauto.\n       +++ intros.\n           intro.\n           eapply H.\n           simpl in H3.\n           injection H3;intros.\n           subst DD.\n           eapply head_witness in H1;trivial;try apply H5; try apply H1;simpl in H4;eauto.\nQed.\n\nLemma subtyping_witness_following_decl:\n  forall CC CC' DD cn dn fields methods j2 cn' dn',\n    subtyping_witness (CC ++ JFCDecl cn (Some dn) fields methods :: j2 :: CC') DD cn' dn' ->\n    exists ex fields' methods', j2 = JFCDecl dn ex fields' methods'.\nProof.\n  induction CC.\n  + intros.\n    simpl in H.\n    inversion H.\n    subst.\n    inversion H11.\n    subst.\n    do 3 eexists; eauto.\n  + intros.\n    inversion H.\n    subst.\n    eapply IHCC in H8.\n    decompose_ex H8.\n    subst.\n    do 3 eexists; eauto.\nQed.\n\nLemma subtyping_witness_incl:\n  forall CC DD cn dn,\n    subtyping_witness CC DD cn dn ->\n    incl CC DD.\nProof.\n  induction CC.\n  + intros.\n    unfold incl.\n    intros.\n    inversion H0.\n  + intros.\n    inversion H.\n    subst.\n    eapply IHCC in H8.\n    unfold incl in *.\n    intros.\n    simpl in H0.\n    destruct H0.\n    ++ subst.\n       eapply in_or_app.\n       right;simpl;auto.\n    ++ eauto.\nQed.\n\nLemma subtyping_witness_subtyping_witness_beginning:\n  forall CC cn dn fields methods CC' DD cn' dn',\n    subtyping_witness (CC ++ JFCDecl cn (Some dn) fields methods :: CC') DD cn' dn' ->\n    subtyping_witness CC DD cn' cn.\nProof.\n  induction CC.\n  + intros.\n    simpl in H.\n    inversion H.\n    subst.\n    eauto.\n  + intros.\n    inversion H.\n    subst.\n    eapply IHCC in H8.\n    decompose_ex H8.\n    eapply head_witness in H8;eauto.\nQed.\n\nLemma subtyping_witness_narrowing:\n  forall CC dn ex fields methods CC' DD cn,\n    subtyping_witness (CC ++ JFCDecl dn ex fields methods :: CC') (JFCDecl dn ex fields methods :: DD) cn dn ->\n    cn <> dn ->\n    ~ In (JFCDecl dn ex fields methods) CC ->\n    incl CC DD ->\n    exists CC'', subtyping_witness CC'' DD cn dn.\nProof.\n  induction CC.\n  * intros.\n    simpl in H.\n    inversion H.\n    subst.\n    contradiction.\n  * intros.\n    inversion H.\n    subst.\n    destruct (JFClassName_dec cn' dn).\n    ** subst.\n       destruct DD'.\n       *** simpl in H5.\n           injection H5;intros;subst.\n           exists [];eauto.\n       *** exists [JFCDecl cn (Some dn) fields0 methods0].\n           simpl in H5.\n           injection H5;intros.\n           eapply head_witness;try eapply H3;eauto.\n           intro.\n           apply H6.\n           simpl;eauto.\n    ** destruct DD'.\n       *** simpl in H5.\n           injection H5;intros;subst.\n           contradiction.\n       *** eapply IHCC in H11;eauto.\n           **** decompose_ex H11.\n                simpl in H5.\n                injection H5;intros.\n                eapply head_witness in H11; try eapply H7; try eapply H3.\n                eexists;eapply H11.\n                intro;apply H6;right;auto.\n           **** intro;apply H1;right;auto.\n           **** unfold incl in *.\n                intros.\n                apply H2.\n                simpl. auto.\nQed.\n\nLemma incl_app_left:\n  forall A, forall (CC:list A) DD EE,\n    incl (CC ++ DD) EE ->\n    incl CC EE.\nProof.\n  induction CC.\n  + intros.\n    unfold incl.\n    intros. inversion H0.\n  + intros.\n    simpl in H.\n    eapply incl_cons.\n    ++ unfold incl in H.\n       eapply H.\n       simpl.\n       eauto.\n    ++ unfold incl in *.\n       intros.\n       eapply H.\n       eauto using in_cons, in_or_app.\nQed.\n       \nLemma subtyping_witness_strong_dec:\n  forall DD cn dn,\n    (exists CC,subtyping_witness CC DD cn dn) \\/ (forall CC,~ subtyping_witness CC DD cn dn).\nProof.\n  induction DD.\n  + intros.\n    destruct (JFClassName_dec cn dn).\n    ++ subst.\n       left.\n       eexists.\n       auto.\n    ++ right.\n       intro. intro.\n       inversion H.\n       +++ subst.\n           contradiction.\n       +++ subst. \n           eapply f_equal in H0.\n           rewrite app_length in H0.\n           simpl in H0.\n           rewrite Nat.add_succ_r in H0.\n           congruence.\n  + intros.\n    pose (IHDD cn dn) as IHDDcndn.\n    destruct IHDDcndn.\n    ++ decompose_ex H.\n       left.\n       exists CC.\n       rewrite <- (app_nil_l (a :: DD)).\n       eauto using subtyping_witness_monotone.\n    ++ destruct a.\n       destruct ex.\n       +++ pose (IHDD cn cn0) as IHDDcncn0.\n           destruct IHDDcncn0.\n           ++++ pose (IHDD j dn) as IHDDjdn.\n                destruct IHDDjdn.\n                * decompose_ex H0.\n                  decompose_ex H1.\n                  destruct (find_class DD j) eqn:?.\n                  ** left.\n                     eapply (subtyping_witness_monotone CC [] DD) in H0.\n                     eapply (subtyping_witness_monotone CC0 [] DD) in H1.\n                     eapply head_witness in H1;try apply Heqo;trivial;auto.\n                     simpl in *.\n                     eapply (subtyping_witness_trans CC (JFCDecl cn0 (Some j) fields methods :: DD) (JFCDecl cn0 (Some j) fields methods :: CC0)) in H0;\n                       [|apply H1].\n                     eexists;eauto.\n                  ** right.\n                     intros.\n                     intro.\n                     destruct (JFClassName_dec cn dn);[subst;eapply H;eauto|].\n                     generalize H2;intros.\n                     eapply subtyping_witness_find_class in H2;eauto.\n                     decompose_ex H2.\n                     destruct (JFClassName_dec dn cn0).\n                     *** subst. eauto.\n                         eapply H;eauto.\n                     *** eapply find_class_further_neq in H2;eauto.\n                         destruct (JFClassName_dec j dn).\n                         **** subst j.\n                              rewrite H2 in *.\n                              inversion  Heqo.\n                         **** eapply subtyping_witness_find_class_first in H1;eauto.\n                              decompose_ex H1.\n                              rewrite H1 in *.\n                              inversion Heqo.\n                * right.\n                  intro.\n                  intro.\n                  destruct CC.\n                  ** inversion H2;subst.\n                     eapply H.\n                     eauto.\n                  ** generalize H2;intro.\n                     eapply new_is_in in H2;eauto.\n                     decompose_ex H2.\n                     rewrite H2 in *.\n                     eapply subtyping_witness_skip_result in H3;eauto.\n                     generalize H3;intro.\n                     destruct CC1.\n                     *** inversion H4;subst.\n                         eapply H1.\n                         eauto.\n                     *** destruct (JFClassName_dec j dn);try (subst;eapply H1;eauto).\n                         eapply subtyping_witness_loop_exit in H4;simpl; eauto with zarith.\n                         decompose_ex H4.\n                         decompose_and H4.\n                         generalize H5;intros.\n                         eapply new_is_in in H5;eauto.\n                         decompose_ex H5.\n                         rewrite H5 in H4.\n                         destruct CC3.\n                         **** assert (exists a CC, CC2 ++ [JFCDecl cn0 (Some j) fields methods] = a :: CC) by\n                               (destruct CC2; simpl; do 2 eexists; eauto).\n                              decompose_ex H6.\n                              eapply subtyping_witness_last_decl in H4;eauto.\n                              decompose_ex H4.\n                              eapply app_inj_tail in H4.\n                              decompose_and H4.\n                              injection H10;intros;contradiction.\n                         **** generalize H4;intros.\n                              eapply subtyping_witness_following_decl in H6;eauto.\n                              decompose_ex H6.\n                              subst.\n                              assert (forall (cn'' : JFClassName) (fields0' : list JFFieldDeclaration) (methods0' : list JFMethodDeclaration),\n                                         ~ In (JFCDecl j (Some cn'') fields0' methods0') (JFCDecl j ex fields' methods' :: CC3)). {\n                                destruct CC2.\n                                + simpl in H5. injection H5;intros.\n                                  intro.\n                                  eapply H8.\n                                  rewrite H6.\n                                  apply H13.\n                                + simpl in H5.   injection H5;intros.\n                                  intro.\n                                  eapply H8.\n                                  rewrite H6.\n                                  eapply in_or_app.\n                                  right.\n                                  simpl.\n                                  eauto.\n                              }\n                              assert (In (JFCDecl j ex fields' methods') (CC2 ++ JFCDecl cn0 (Some j) fields methods :: JFCDecl j ex fields' methods' :: CC3))\n                                by (eapply in_app_iff;simpl; eauto).\n                              eapply subtyping_witness_only_some in H4; try eapply H9.\n                              decompose_ex H4.\n                              subst.\n                              pose (H6 dn0 fields' methods') as dead.\n                              simpl in dead.\n                              assert False.\n                              apply dead. left;trivial.\n                              contradiction.\n                         ++++ right.\n                              intros.\n                              intro.\n                              generalize H1;intros.\n                              destruct CC; [inversion H1;subst; eapply H; auto|].\n                              eapply new_is_in in H2;eauto.\n                              decompose_ex H2.\n                              rewrite H2 in H1.\n                              eapply subtyping_witness_subtyping_witness_beginning in H1.\n                              generalize H1;intros.\n                              destruct CC0;[inversion H3;subst;eapply H0;eauto|].\n                              generalize H3;intros.\n                              eapply new_is_in in H3;eauto.\n                              decompose_ex H3.\n                              assert (In (JFCDecl cn0 (Some j) fields methods) (j1 :: CC0))\n                                by (rewrite H3; eapply in_app_iff; simpl; eauto).\n                              eapply in_split_notfirst in H5;try apply JFClassDeclaration_dec.\n                              decompose_ex H5.\n                              decompose_and H5.\n                              rewrite H6 in H1.\n                              destruct (JFClassName_dec cn cn0); [subst;eapply H0;eauto|].\n                              eapply subtyping_witness_narrowing in H1;eauto.\n                              decompose_ex H1.\n                              eapply H0;eauto.\n                              eapply subtyping_witness_incl in H1.\n                              eapply incl_app_left in H1.\n                              unfold incl.\n                              intros.\n                              unfold incl in H1.\n                              simpl in H1.\n                              generalize H5;intros.\n                              eapply H1 in H5.\n                              destruct H5.\n                              * subst a.\n                                contradiction.\n                              * auto.\n                     +++ right.\n                         intros.\n                         intro.\n                         destruct CC.\n                         ++++ inversion H0.\n                              subst.\n                              eapply H.\n                              eauto.\n                         ++++ generalize H0;intros.\n                              eapply new_is_in in H0;eauto.\n                              decompose_ex H0.\n                              assert (In (JFCDecl cn0 None fields methods) (j::CC))\n                                by (rewrite H0; eapply in_app_iff; simpl;eauto).\n                              eapply subtyping_witness_only_some in H1; try apply H2.\n                              decompose_ex H1;inversion H1.\n                              Unshelve.\n                              eapply [].\nQed.\n\nLemma subtyping_witness_subtyping:\n  forall CC DD cn dn,\n    subtyping_witness CC DD cn dn -> subtyping DD (JFClass cn) (JFClass dn).\nProof.\n  induction 1.\n  + auto.\n  + eapply substep.\n    trivial.\n    Focus 2.\n    subst DD.\n    eapply base_deep;eauto.\n    trivial.\n    subst DD.\n    eauto using subtyping_further_deep.\nQed.\n\n\n\n\nLemma extends_notfirst_find_class:\n  forall CC cn dn,\n    extends CC cn dn ->\n    exists CC' CC'' flds mthds dd,\n      CC = CC' ++ (JFCDecl cn (Some dn) flds mthds) :: CC'' /\\\n      ~ In (JFCDecl cn (Some dn) flds mthds) CC' /\\\n      find_class CC'' dn = Some dd.\nProof.\n  induction 1.\n  + intros.\n    eapply in_find_class_raw in H.\n    decompose_ex H.\n    exists [].\n    do 4 eexists.\n    simpl.\n    split;eauto.\n  + decompose_ex IHextends.\n    decompose_and IHextends.\n    destruct CC'.\n    ++ simpl in *.\n       subst.\n       destruct (JFClassDeclaration_dec (JFCDecl cn1 dn1 fields methods) (JFCDecl cn2 (Some dn2) flds mthds)).\n       +++ injection e;intros;clear e.\n           subst.\n           exists  [].\n           eapply find_class_lift_cons in H3.\n           decompose_ex H3.\n           do 4 eexists.\n           simpl.\n           split.\n           trivial.\n           split.\n           trivial.\n           eapply H3.\n       +++ exists [JFCDecl cn1 dn1 fields methods].\n           do 4 eexists.\n           simpl.\n           split.\n           trivial.\n           split.\n           tauto.\n           eapply H3.\n    ++ destruct (JFClassDeclaration_dec (JFCDecl cn1 dn1 fields methods) (JFCDecl cn2 (Some dn2) flds mthds)).\n       +++ injection e;intros;clear e.\n           subst.\n           exists  [].\n           eapply find_class_lift_cons in H3.\n           decompose_ex H3.\n           eapply find_class_lift in H3.\n           decompose_ex H3.\n           do 4 eexists.\n           simpl.\n           split.\n           trivial.\n           split.\n           tauto.\n           rewrite app_comm_cons.\n           eapply H3.\n       +++ subst CC.\n           exists (JFCDecl cn1 dn1 fields methods :: (j :: CC')).\n           exists CC''.\n           do 3 eexists.\n           split.\n           simpl.\n           trivial.\n           split.\n           intro.\n           apply H2.\n           simpl in H0.\n           destruct H0;try contradiction.\n           eauto.\nQed.  \n\n\nLemma subtyping_subtyping_witness:\n  forall DD,\n    forall  cid did,\n      subtyping DD cid did ->\n       forall cn dn,\n    cid = (JFClass cn) ->\n    did = (JFClass dn) ->\n    cid <> did ->\n    did <> JFObject -> exists CC, subtyping_witness CC DD cn dn.\nProof.\n  induction 1.\n  + intros; contradiction.\n  + intros; contradiction.\n  + intros; congruence.\n  + intros.\n    subst.\n    injection H3; clear H3;intros;subst.\n    destruct (JFClassName_dec dn dn0).\n    ++ subst.\n       generalize H1;intros.\n       eapply extends_notfirst_find_class in H1.\n       decompose_ex H1.\n       decompose_and H1.\n       eexists.\n       eapply head_witness;eauto using JFClassDeclaration_dec.\n    ++ assert (JFClass dn <> JFClass dn0) by congruence.\n       eapply IHsubtyping in H ; trivial;try congruence.\n       decompose_ex H.\n       generalize H1;intros.\n       eapply extends_notfirst_find_class in H1.\n       decompose_ex H1.\n       decompose_and H1.\n       eexists.\n       eapply head_witness.\n       apply H3.\n       apply H7.\n       apply H8.\n       apply H.\nQed.\n\nLemma subtyping_dec:\n  forall CC C D,\n    subtyping CC C D \\/ ~ subtyping CC C D.\nProof.\n  intros *.\n  destruct C; eauto.\n  destruct D; [|right;intro;eapply subtyping_not_bot in H;inversion H;auto].\n  pose (subtyping_witness_strong_dec CC cn cn0) as Sdec.\n  destruct Sdec.\n  * decompose_ex H.\n    left.\n    eauto using subtyping_witness_subtyping.\n  * destruct (JFClassName_dec cn cn0).\n    ** subst; left; eauto.\n    ** destruct (JFClassName_dec cn0 JFObjectName).\n       *** subst; left; eauto.\n       *** right.\n           intro.\n           eapply subtyping_subtyping_witness in H0;eauto;try congruence.\n           **** decompose_ex H0.\n                eapply H;eauto.\n           **** unfold JFObject;congruence.\nQed.\n\n\nLemma subtyping_find_class:\n  forall CC C D cn,\n    C <> D -> \n    D <> JFObject ->\n    JFClass cn = C ->\n    names_unique CC ->\n    subtyping CC C D ->\n    exists cd, find_class CC cn = Some cd.\nProof.\n  intros.\n  inversion H3.\n  + intuition.\n  + congruence.\n  + congruence.\n  + assert (exists\n               (ex0 : JFClassName) (fields' : list JFFieldDeclaration) \n               (methods' : list JFMethodDeclaration),\n               In (JFCDecl cn0 (Some ex0) fields' methods') CC)\n      by eauto 3 using  extends_in_first.\n    destruct H10, H10, H10.\n    assert (cn0=cn) by congruence.\n    subst cn0.\n    exists (JFCDecl cn (Some x) x0 x1).\n    eauto 2.\nQed.\n\n    \n    \nLemma subtyping_find_class_gt:\n  forall CC C D dn,\n    C <> D ->\n    C <> JFBotClass ->\n    JFClass dn = D ->\n    names_unique CC ->\n    subtype_well_founded CC ->\n    program_contains CC JFObjectName = true ->\n    subtyping CC C D ->\n    exists dd, find_class CC dn = Some dd.\nProof.\n  induction CC.\n  + intros.\n    simpl in H4.\n    discriminate H4.\n  + intros C D dn CDneq CJFB DidD Nuq Swf PctsObj Sub.\n    inversion Sub.\n    ++ contradiction.\n    ++ subst.\n       injection H0;intros.\n       subst.\n       apply program_contains_find_class;auto.\n    ++ subst. contradiction.\n    ++ subst.\n       destruct a.\n       unfold find_class.\n       destruct (JFClassName_dec cn0 dn).\n       +++ eexists;eauto.\n       +++ fold (find_class CC dn).\n           assert (exists\n                      (ex0 : option JFClassName)\n                      (fields' : list JFFieldDeclaration) \n                      (methods' : list JFMethodDeclaration),\n                      In (JFCDecl dn0 ex0 fields' methods') CC)\n             by eauto using extends_in_second_second.\n           do 3 destruct H.\n           destruct (JFClassName_dec cn0 cn).\n           * subst.\n             destruct (JFClassName_dec cn dn0).\n             ** subst.\n                assert (JFClass dn0 <> JFClass dn0).\n                eapply extends_neq;eauto.\n                contradiction.\n             ** assert (JFClass cn <> JFClass dn) by congruence.\n                destruct (JFClassName_dec dn0 dn).\n                *** subst; eauto.\n                *** assert (subtyping CC (JFClass dn0) (JFClass dn)) by\n                      (eapply subtyping_further_neq ;\n                       try apply H2;eauto 2; congruence).\n                    eapply IHCC;\n                      try apply H3; try apply CDneq;\n                        try apply CJFB;try congruence;eauto 2.\n                    {\n                      destruct CC.\n                      * inversion H.\n                      * eauto using subtype_well_founded_program_contains_further.\n                    }\n           * subst.\n             assert (JFClass dn <> JFClass cn0) by congruence.\n             destruct (JFClassName_dec dn0 dn).\n             ** subst; eauto.\n             ** assert (JFClass dn0 <> JFClass dn) by congruence.\n                eapply IHCC; try eapply H4; eauto 2.\n                *** discriminate.\n                *** destruct CC.\n                    **** inversion H.\n                    **** eauto using subtype_well_founded_program_contains_further.\n                *** eapply subtyping_further_neq; eauto.\n                    eapply extends_neq;eauto.\nQed.\n\nLemma subtyping_neq_object:\n  forall CC dn D,\n    object_is_not_extended CC ->\n    (JFClass dn) <> D  ->\n    subtyping CC (JFClass dn) D ->\n    JFClass dn <> JFObject.\nProof.\n  intros.\n  inversion H1.\n  + tauto.\n  + congruence.\n  + injection.\n    eapply object_is_not_extended_extends_neq.\n    eauto.\n    assert (dn=cn) by congruence.\n    rewrite H9 in *.\n    eauto.\nQed.\n\n             \nHint Resolve subtyping_further object_is_not_subtype subtrans subtyping_further_neq subtyping_find_class.\n\n  \nLemma subtyping_object_supremum:\n  forall CC C,\n    names_unique CC ->\n    object_is_not_extended CC ->\n    extensions_in_all_but_object CC ->\n      subtype_well_founded CC ->\n    subtyping CC JFObject C ->\n    C = JFObject.\nProof.\n  induction CC.\n  * intros.\n    inversion H3.\n    ** auto.\n    ** auto.\n    ** subst.\n       inversion H6.\n  * intros.\n    apply IHCC;eauto 2.\n    destruct a.\n    destruct (JFCId_dec (JFClass cn) JFObject).\n    assert (C = JFObject).\n    eapply object_is_not_subtype;\n      try apply H;eauto.\n    rewrite H4.\n    apply subrefl.\n    eauto 2.\nQed.\n\nHint Resolve  subtyping_neq_object subtyping_object_supremum.\n\n\n\n(**\n   Effective version of the subtyping that returns booleans\n   instead predicting the property. The function is correct\n   only when the program is well formed.\n*)\nFixpoint subtype_class_bool (CC:JFProgram) (cn dn: JFClassName) : bool :=\n  if JFClassName_dec cn dn\n  then true\n  else if JFClassName_dec dn JFObjectName\n       then true\n       else\n         match CC with\n           | [] => false\n           | JFCDecl cn' (Some dn') _ _ :: CC' =>\n             if JFClassName_dec cn cn'\n             then if JFClassName_dec dn' dn\n                  then true\n                  else subtype_class_bool CC' dn' dn\n             else subtype_class_bool CC' cn dn\n           | JFCDecl cn' None _ _ :: CC' =>\n             if JFClassName_dec cn cn'\n             then false\n             else subtype_class_bool CC' cn dn\n         end.\n\n\n\nLemma subtype_class_bool_simple:\n  forall CC cn dn fields methods,\n    subtype_class_bool (JFCDecl cn (Some dn) fields methods :: CC) cn dn = true.\nProof.\n  intros.\n  unfold subtype_class_bool.\n  destruct (JFClassName_dec cn dn).\n  * auto.\n  * destruct (JFClassName_dec dn JFObjectName); try auto.\n    destruct (JFClassName_dec cn cn); try contradiction.\n    destruct (JFClassName_dec dn dn); try contradiction.\n    auto.\nQed.\n\nLemma subtype_class_bool_same:\n  forall CC cn,\n    subtype_class_bool CC cn cn = true.\nProof.\n  intros.\n  unfold subtype_class_bool.\n  destruct CC;destruct (JFClassName_dec cn cn); auto.\nQed.\n\nLemma subtype_class_bool_object:\n  forall CC cn,\n    subtype_class_bool CC cn JFObjectName = true.\nProof.\n  intros.\n  unfold subtype_class_bool.\n  destruct CC;destruct (JFClassName_dec cn JFObjectName); auto.\nQed.\n\nHint Resolve subtype_class_bool_same subtype_class_bool_object.\n\nLemma subtype_class_bool_direct_extends:\n  forall CC cn dn flds mthds,\n    subtype_class_bool (JFCDecl cn (Some dn) flds mthds :: CC) cn dn = true.\nProof.\n  intros.\n  unfold subtype_class_bool.\n  destruct (JFClassName_dec cn dn); try subst cn; auto.\n  destruct (JFClassName_dec dn JFObjectName); try subst dn; auto.\n  destruct (JFClassName_dec cn cn); try tauto.\n  destruct (JFClassName_dec dn dn); try tauto.\nQed.\n\nHint Resolve subtype_class_bool_direct_extends.\n\n\nLemma subtype_class_bool_eq:\n  forall CC cn cn' dn' flds mthds,\n  subtype_class_bool CC cn' dn' = true ->\n  subtype_class_bool (JFCDecl cn (Some cn') flds mthds :: CC) cn dn'=true.\nProof.\n  destruct CC.\n  * unfold subtype_class_bool.\n    intros.\n    destruct (JFClassName_dec cn dn'); auto.\n    destruct (JFClassName_dec dn' JFObjectName); auto.\n    destruct (JFClassName_dec cn cn); auto.\n    destruct (JFClassName_dec cn' dn'); auto.\n  * intros.\n    unfold subtype_class_bool.\n    unfold subtype_class_bool in H.\n    destruct (JFClassName_dec cn dn'); try subst cn; auto.\n    destruct (JFClassName_dec dn' JFObjectName); try subst dn'; auto.\n    destruct (JFClassName_dec cn cn); try tauto.\n    destruct (JFClassName_dec cn' dn'); try auto.\nQed.\n\n\nHint Resolve subtype_class_bool_eq.\n\n\nLemma subtype_class_bool_neq:\n  forall CC cn dn en ex flds mthds,\n    subtype_class_bool CC cn dn = true ->\n    cn<>en ->\n    subtype_class_bool (JFCDecl en ex flds mthds :: CC) cn dn = true.\nProof.\n  destruct CC.\n  - intros.\n    simpl in H.\n    simpl.\n    destruct (JFClassName_dec cn dn); eauto 2.\n    destruct (JFClassName_dec dn JFObjectName); eauto 2.\n    discriminate H.\n  - intros.\n    destruct (JFClassName_dec cn dn); try rewrite e; eauto 2. \n    destruct (JFClassName_dec dn JFObjectName); try rewrite e; eauto 2.\n    destruct ex.\n    + unfold subtype_class_bool.\n      unfold subtype_class_bool in H.\n      destruct (JFClassName_dec cn dn); try rewrite e; eauto 2.\n      destruct (JFClassName_dec dn JFObjectName); try rewrite e; eauto 2.\n      destruct (JFClassName_dec cn en); eauto 3.\n    + unfold subtype_class_bool.\n      unfold subtype_class_bool in H.\n      destruct (JFClassName_dec cn dn); try rewrite e; eauto 2.\n      destruct (JFClassName_dec dn JFObjectName); try rewrite e; eauto 2.\n      destruct (JFClassName_dec cn en); eauto 3.\nQed.\n\nLemma subtype_class_bool_object_left:\n  forall CC cn,\n    subtype_well_founded CC ->\n    names_unique CC ->\n    subtype_class_bool CC JFObjectName cn = true ->\n    cn = JFObjectName.\nProof.\n  induction CC.\n  + intros cn Swf Nuq H0.\n    unfold subtype_class_bool in H0.\n    destruct (JFClassName_dec JFObjectName cn);\n      destruct (JFClassName_dec cn JFObjectName); auto.\n    try discriminate H0.\n  + intros cn Swf Nuq H0.\n    generalize H0;intros.\n    unfold subtype_class_bool in H0.\n    fold subtype_class_bool in H0.\n    destruct (JFClassName_dec JFObjectName cn);\n      destruct (JFClassName_dec cn JFObjectName); auto.\n    destruct a;destruct ex.\n    ++ destruct (JFClassName_dec JFObjectName cn0).\n       +++ subst.\n           unfold subtype_well_founded in Swf.\n           pose find_class_eq.\n           apply Swf in e.\n           decompose_ex e.\n           eapply number_of_extends_decompose in e.\n           destruct e.\n           eapply number_of_extends_object in H.\n           eapply program_contains_find_class in H.\n           decompose_ex H.\n           destruct cd.\n           generalize H;intros.\n           eapply find_class_eq_name in H3;subst.\n           eapply find_class_in in H.\n           eapply names_unique_in_neq in Nuq;eauto.\n           contradiction.\n       +++ eapply IHCC in H0;eauto.\n    ++ destruct (JFClassName_dec JFObjectName cn0); try discriminate H0.\n       eapply IHCC in H0;eauto.\nQed.\n    \n\nHint Resolve subtype_class_bool_neq.\n\n\n\n\nLemma extends_subtype_bool_complete:\n  forall CC cn dn,\n    names_unique CC ->\n    program_contains CC JFObjectName = true ->\n    object_is_not_extended CC ->\n    subtype_well_founded CC ->\n    JFClass cn <> JFObject ->\n    extends CC cn dn ->\n    subtype_class_bool CC cn dn = true.\nProof.\n  induction CC.\n  - intros.\n    inversion H4.\n  - intros. inversion H4.\n    + eauto. \n    + assert (  exists\n                 (ex0 : JFClassName) (fields' : list JFFieldDeclaration) \n                 (methods' : list JFMethodDeclaration),\n                 In (JFCDecl cn (Some ex0) fields' methods') CC) by eauto using extends_in_first.\n      decompose_ex H10.\n      subst.\n      assert (cn1<>cn) by eauto 2 with myhints.\n      eapply subtype_class_bool_neq.\n      eapply IHCC; eauto 3.\n      eapply subtype_well_founded_contains_object;eauto 3.\n      auto.\nQed.\n\nLemma decompose_subtype_class_bool:\n  forall CC cn dn en xn fields methods,\n    (cn = en -> subtype_class_bool CC xn dn = true) ->\n    (cn <> en -> subtype_class_bool CC cn dn = true) ->\n    subtype_class_bool (JFCDecl en (Some xn) fields methods :: CC) cn dn = true.\nProof.\n  intros.\n  simpl.\n  destruct (JFClassName_dec cn dn); eauto 2.\n  destruct (JFClassName_dec dn JFObjectName); eauto 2.\n  destruct (JFClassName_dec cn en).\n  - destruct (JFClassName_dec xn dn).\n    * auto.\n    * auto.\n  - apply H0.\n    auto.\nQed.\n\nLemma decompose_subtype_class_bool_none:\n  forall CC cn dn en fields methods,\n    cn <> en ->\n    subtype_class_bool CC cn dn = true ->\n    subtype_class_bool (JFCDecl en None fields methods :: CC) cn dn = true.\nProof.\n  intros.\n  simpl.\n  destruct (JFClassName_dec cn dn); eauto 2.\n  destruct (JFClassName_dec dn JFObjectName); eauto 2.\n  destruct (JFClassName_dec cn en).\n  + congruence.\n  + auto.\nQed.\n\n\nLemma subtype_class_bool_find_class:\n  forall cn dn,\n    cn <> dn ->\n    dn <> JFObjectName ->\n    forall CC,\n    subtype_class_bool CC cn dn = true ->\n    exists cd, find_class CC cn = Some cd.\nProof.\n  induction CC;intros.\n  + simpl in H1.\n    destruct (JFClassName_dec cn dn).\n    congruence.\n    destruct (JFClassName_dec dn JFObjectName).\n    congruence.\n    discriminate H1.\n  + destruct a.\n    destruct (JFClassName_dec cn0 cn).\n    * subst cn0.\n      exists (JFCDecl cn ex fields methods).\n      eapply find_class_eq.\n    * unfold subtype_class_bool in H1.\n      destruct (JFClassName_dec cn dn).\n      - subst dn.\n        tauto.\n      - destruct (JFClassName_dec dn JFObjectName).\n        { subst dn.\n          lapply IHCC; intros.\n          destruct H2.\n          exists x.\n          eapply find_class_same; eauto.\n          eauto.\n        }\n        { destruct ex.\n          + destruct (JFClassName_dec cn cn0).\n            * congruence.\n            * lapply IHCC; eauto.\n              intros.\n              destruct H2.\n              exists x.\n              clear H1.\n              eauto using find_class_same.\n          + fold (subtype_class_bool CC cn dn) in H1.\n            lapply IHCC; eauto 2; intros.\n            ++ destruct H2.\n               exists x.\n               clear H1.\n               eauto using find_class_same.\n            ++ destruct (JFClassName_dec cn cn0); eauto.\n        }\nQed.\n\n\n\n\nLemma subtype_class_bool_find_class_second:\n  forall CC cn dn,\n    cn <> dn ->\n    dn <> JFObjectName ->\n    subtype_well_founded CC ->\n    names_unique CC ->\n    subtype_class_bool CC cn dn = true ->\n    exists dd, find_class CC dn = Some dd.\nProof.\n  induction CC.\n  + scrush.\n  + intros Cn Dn CnDn DnObj Swf Nuq Scb.\n    destruct a.\n    destruct (JFClassName_dec Cn Dn); try contradiction.\n    generalize Swf;intros.\n    simpl in Scb.\n    destr_discr Scb; try contradiction.\n    destr_discr Scb; try contradiction.\n    destruct ex.\n    destruct (JFClassName_dec Cn cn).\n    ++ subst.\n       destruct (JFClassName_dec j Dn).\n       +++ subst.\n           eapply subtype_get_superclass in Swf0;eauto 2;\n             try eapply find_class_eq.\n       +++ generalize Scb;intros.\n           eapply IHCC in Scb0;eauto 2.\n           sauto.\n    ++ eapply IHCC in Scb;eauto 2.\n       sauto.\n    ++ destruct (JFClassName_dec Cn cn);try congruence.\n       eapply IHCC in Scb;eauto 2.\n       sauto.\nQed.\n\nLemma subtype_class_bool_refl:\n  forall CC cn dn,\n    subtype_well_founded CC ->\n    names_unique CC ->\n    subtype_class_bool CC cn dn = true ->\n    subtype_class_bool CC dn cn = true ->\n    cn = dn.\nProof.\n  induction CC.\n  + intros Cn Dn Swf Nuq H H0.\n    simpl in H.\n    simpl in H0.\n    destruct (JFClassName_dec Cn Dn);\n      destruct (JFClassName_dec Dn Cn); try contradiction; auto 2.\n    destruct (JFClassName_dec Dn JFObjectName);\n      destruct (JFClassName_dec Cn JFObjectName); subst; try contradiction;\n        try discriminate H0; try discriminate H.\n  + intros  Cn Dn Swf Nuq H H0.\n    generalize H;\n      generalize H0;intros.\n    simpl in H.\n    simpl in H0.\n    destruct (JFClassName_dec Cn Dn);\n      destruct (JFClassName_dec Dn Cn); try contradiction; auto 2.\n    destruct (JFClassName_dec Dn JFObjectName);\n      destruct (JFClassName_dec Cn JFObjectName); subst; try contradiction;\n        try discriminate H0; try discriminate H.\n    ++ eapply subtype_class_bool_object_left in H1;eauto 2.\n    ++ eapply subtype_class_bool_object_left in H2;eauto 2.\n    ++ destruct a; destruct ex.\n       +++ destruct (JFClassName_dec Cn cn);\n             destruct (JFClassName_dec Dn cn);subst;try contradiction.\n           ++++ eapply subtype_class_bool_find_class_second in H0;eauto 2.\n                destruct H0.\n                destruct x.\n                generalize H0;intros.\n                eapply find_class_eq_name in H3;subst.\n                eapply find_class_in in H0;auto 2.\n                eapply names_unique_in_neq in Nuq;eauto 2;contradiction.\n           ++++ eapply subtype_class_bool_find_class_second in H;eauto 2.\n                destruct H.\n                destruct x.\n                generalize H;intros.\n                eapply find_class_eq_name in H3;subst.\n                eapply find_class_in in H;auto 2.\n                eapply names_unique_in_neq in Nuq;eauto 2;contradiction.\n           ++++ eapply IHCC in H0;eauto 2.\n       +++ destruct (JFClassName_dec Cn cn); try discriminate H.\n           destruct (JFClassName_dec Dn cn); try discriminate H0.\n           eapply IHCC in H0;eauto 2.\nQed.\n\n\nLemma subtype_class_bool_subtyping:\n  forall CC cn dn,\n    names_unique CC ->\n    subtype_well_founded CC ->\n    subtype_class_bool CC cn dn = true ->\n    subtyping CC (JFClass cn) (JFClass dn).\nProof.\n  induction CC.\n  + intros.\n    sauto.\n  + intros cn dn.\n    intros Nuq Swf Scb.\n    simpl in Scb.\n    repeat destr_discr Scb;auto.\n    ++ sauto.\n    ++ sauto.\n    ++ subst.\n       eapply substep;eauto 1.\n       unfold subtype_well_founded in Swf.\n       pose find_class_eq as FclsD.\n       apply Swf in FclsD.\n       decompose_ex FclsD.\n       simpl in FclsD.\n       destruct (JFClassName_dec cn0 cn0); try contradiction.\n       destruct (number_of_extends CC dn) eqn:?.\n       +++ eapply number_of_extends_find_class_simple in Heqo.\n           decompose_ex Heqo.\n           destruct x.\n           eapply find_class_in in Heqo;eauto.\n           eapply base;eauto.\n       +++ inversion FclsD.\n    ++ subst.\n       generalize Swf;intros.\n       eapply subtype_well_founded_neq in Swf0;eauto.\n       destruct (JFClassName_dec JFObjectName dn).\n       +++ subst; eauto.\n       +++ generalize Scb;intros.\n           eapply IHCC in Scb0;eauto 2.\n           generalize Scb0;intros.\n           eapply subtyping_further in Scb1.\n           eapply subtyping_find_class in Scb0;eauto 2; unfold JFObject; try congruence.\n           decompose_ex Scb0.\n           destruct cd.\n           generalize Scb0;intros.\n           eapply find_class_in in Scb0.\n           eapply base in Scb0.\n           eapply substep; try eapply Scb1; try eapply Scb0; auto 1.\n    ++ eapply subtyping_further.\n       generalize Scb;intros.\n       eapply subtype_class_bool_find_class_second in Scb0;eauto.\n    ++ eapply subtyping_further.\n       generalize Scb;intros.\n       eapply subtype_class_bool_find_class_second in Scb0;eauto.\nQed.\n       \nHint Resolve subtype_class_bool_simple decompose_subtype_class_bool\n     extends_subtype_bool_complete decompose_subtype_class_bool_none\n     subtype_class_bool_subtyping.\n\n\n\n\n\nHint Resolve names_unique_count_zero.\n\n\n\nLemma subtype_class_bool_complete :\n  forall CC C D,\n    names_unique CC ->\n    subtype_well_founded CC ->\n    subtyping CC C D  ->\n    forall  cn dn,\n      C = (JFClass cn) ->\n      D = (JFClass dn) ->\n      JFClass cn <> JFObject ->\n      cn <> dn ->\n        subtype_class_bool CC cn dn = true.\nProof.\n  induction CC; intros C D H  H2 H3 Cid Did H4 H5 H6 H8.\n  + inversion H3.\n    ++ subst. injection H1;intros;subst.\n       contradiction.\n    ++ subst. injection H1;intros;subst.\n       simpl.\n       destruct (JFClassName_dec Cid JFObjectName); try contradiction;auto.\n    ++ subst. inversion H0.\n    ++ subst.\n       inversion H7.\n  + inversion H3.\n    - congruence.\n    - assert (Did = JFObjectName) by (unfold JFObject in *; congruence).\n      subst.\n      eauto.\n    - subst. \n      discriminate H0.\n    - destruct a.\n      subst.\n      destruct ex.\n      -- apply decompose_subtype_class_bool.\n         --- intros.\n             assert (cn = cn0) by congruence.\n             subst.\n             assert (dn=j) by eauto. \n             subst j.\n             destruct (JFClassName_dec dn Did); try rewrite e; eauto 2.\n             eapply subtyping_further_neq in H9;eauto 2.\n             eapply IHCC;eauto 2. (* subtype_class_bool CC j Did = true *)\n             ---- subst.\n                  eapply (subtyping_neq_object (JFCDecl cn0 (Some dn) fields methods :: CC) dn (JFClass Did));\n                    auto;try congruence.\n                  unfold subtype_well_founded in H2.\n                  pose find_class_eq as Fceq.\n                  apply H2 in Fceq.\n                  decompose_ex Fceq.\n                  eapply number_of_extends_object_is_not_extended;eauto 2.\n             ---- eapply extends_neq;eauto.\n         --- intros.\n             { destruct (JFClassName_dec Cid Did); eauto 3.\n               destruct (JFClassName_dec Did JFObjectName); try rewrite e; eauto 2.\n               eapply subtyping_further_neq in H3;eauto 2; try congruence.\n               injection H0;intros;subst cn;clear H0.\n               eapply IHCC;  eauto 2.\n             }\n      -- assert (Cid=cn) by congruence.\n         subst Cid.\n         eapply extends_neq_none in H7;eauto 2.\n         apply decompose_subtype_class_bool_none;eauto 2.\n         eapply subtyping_further_neq in H3;eauto 2; try congruence.\n         eapply IHCC; eauto 2 using find_class_further_neq.\nQed.\n\n\n\n\n\n(** This is the `lifting' of the class subtyping to subtyping on class\n    identifiers.\n *)\nDefinition subtype_bool (CC:JFProgram) (C D: JFCId) : bool := \n  match C, D with\n  | JFBotClass, _ => true\n  | _, JFBotClass => false\n  | JFClass cn, JFClass dn => subtype_class_bool CC cn dn\n  end.\n\n\nInductive leqAnnLS : JFProgram -> JFCId -> JFMId -> JFAMod -> JFAMod -> Prop:=\n| isLSTrueAnn : forall (CC:JFProgram) (C:JFCId) (cn:JFClassName) (m:JFMId) (ra:JFAMod) (rb:JFAMod),\n    C = JFClass cn ->\n    isLSForId CC cn m ->\n    leqAnn ra rb ->\n    leqAnnLS CC C m ra rb\n| isLSFalseAnn : forall (CC:JFProgram) (C:JFCId) (cn:JFClassName) (m:JFMId) (ra:JFAMod) (rb:JFAMod),\n    C = JFClass cn ->\n    ~ isLSForId CC cn m ->\n    leqAnnLS CC C m ra rb.\n\n\n(**\n   We have two related orders on JFACIds that depend on whether the method\n   local sensitive or not local sensitive. It is defined as \n   <:^{\\isLocalSensitive(C,m)} in Section~{sec:type-system}.\n*)\nInductive leqIsLS : JFProgram -> JFCId -> JFMId -> JFACId -> JFACId -> Prop :=\n| isLSTrue : forall (CC:JFProgram) (Cid:JFCId) (cn:JFClassName)\n                    (mid:JFMId) (ls:JFACId) (lc:JFCId) (la:JFAMod) (rs:JFACId) (rc:JFCId) (ra:JFAMod),\n    Cid = JFClass cn ->\n    isLSForId CC cn mid ->\n    ls = (lc, la) ->\n    rs = (rc, ra) ->\n    subtyping CC lc rc ->\n    leqAnn la ra ->\n    leqIsLS CC Cid mid ls rs\n| isLSFalse : forall (CC:JFProgram) (Cid:JFCId) (cn:JFClassName)\n                    (mid:JFMId) (ls:JFACId) (lc:JFCId) (la:JFAMod) (rs:JFACId) (rc:JFCId) (ra:JFAMod),\n    Cid = JFClass cn ->\n    ~ isLSForId CC cn mid ->\n    ls = (lc, la) ->\n    rs = (rc, ra) ->\n    subtyping CC lc rc ->\n    leqIsLS CC Cid mid ls rs.\n\nLemma leqIsLS_refl:\n  forall CC C cn mid ls,\n    C = JFClass cn ->\n    leqIsLS CC C mid ls ls.\nProof.\n  intros.\n  assert (isLSForId CC cn mid \\/ ~isLSForId CC cn mid) by auto with myhints.\n  destruct ls.\n  destruct H0.\n  + eapply isLSTrue;eauto with myhints.\n  + eapply isLSFalse;eauto with myhints.\nQed.\n\nLemma leqIsLS_trans:\n  forall CC C cn mid mu mu' mu'',\n    (program_contains CC JFObjectName) = true ->\n    names_unique CC -> \n    object_is_not_extended CC ->\n    extensions_in_all_but_object CC ->\n    C = JFClass cn ->\n    leqIsLS CC C mid mu mu' ->\n    leqIsLS CC C mid mu' mu'' ->\n    leqIsLS CC C mid mu mu''.\nProof.\n  intros CC Cid cname mid mu mu' mu''.\n  intros Pctns Nuq Oine Einabo Cideq LeqISLSmumu' LeqISLSmu'mu''.\n  assert (isLSForId CC cname mid \\/ ~isLSForId CC cname mid)\n    as IsLSDec by auto with myhints.\n  destruct mu as [C md].\n  destruct mu'' as [C'' md''].\n  destruct LeqISLSmumu' as [CC cname0 mid ls lc la rs rc ra\n                              Cideq' IsLSForcname0 lseq rseq Sub LeqAnn|\n                            CC' cid cname0 mid ls lc la rs rc ra\n                               Cideq'\n                               IsLSForcname0 lseq rseq Sub].\n  + subst.\n    injection IsLSForcname0;intros;clear IsLSForcname0;subst.\n    eapply isLSTrue;try apply Cideq;auto;\n    try (inversion LeqISLSmu'mu'' as [CC' Cid cname mid0 ls0 lc la0 rs0 rc ra0\n                                       Mideq IsLSForIdcname raeq C''eq Sub'\n                                       LeqAnn'|\n                                    CC' Cid cname mid0 ls0 lc la0 rs0 rc ra0\n                                       Mideq IsLSForIdcname raeq C''eq Sub'];\n         (subst;\n          injection Mideq;intros;clear Mideq;\n          injection raeq;intros;clear raeq;\n          injection C''eq;intros;clear C''eq;\n          subst;\n          subst)).\n    ++ eauto using subtrans.\n    ++ eauto using subtrans.\n    ++ eauto using leqAnn_trans.\n    ++ contradiction.\n  + subst.\n    injection Cideq';intros;clear Cideq';subst.\n    eapply isLSFalse;try apply IsLSForcname0;auto.\n    inversion LeqISLSmu'mu'' as [CC'' Cid cname mid0 ls0 lc' la0 rs0 rc' ra0\n                                    Mideq IsLSForIdcname raeq C''eq Sub'\n                                    LeqAnn'|\n                                 CC'' Cid cname mid0 ls0 l'c la0 rs0 rc' ra0\n                                    Mideq IsLSForIdcname raeq C''eq Sub'];\n    (subst;\n         injection Mideq;intros;clear Mideq;\n           injection raeq;intros;clear raeq;\n            injection C''eq;intros;clear C''eq;\n              subst;\n       eauto using subtrans).\nQed.\n\nLemma minimalIsLS:\n  forall CC m C amod cn md,\n    methodLookup CC cn m = Some md ->\n    leqIsLS CC (JFClass cn) m (JFBotClass,  JFrwr) (C, amod).\nProof.\n  intros.\n  edestruct (isLSForId_dec CC cn m).\n  * inversion H0.\n    eapply isLSTrue; eauto with myhints.\n  * eapply isLSFalse; eauto.\nQed.\n\nHint Resolve minimalIsLS leqIsLS_refl leqIsLS_trans.\n\n(**\n   Lifting of an inequality predicate that compares using a given parameter predicate [P] an element\n   of JFACId with a list of JFACId's. It holds true when at least one comparison holds.\n*)\nInductive isLeqIn : (JFACId -> JFACId -> Prop) -> JFACId -> list JFACId -> Prop :=\n  | consNotIn : forall  (P:JFACId -> JFACId -> Prop) (caid:JFACId) (daid:JFACId) (l:list JFACId),\n      ~P caid daid ->\n      isLeqIn P caid l ->\n      isLeqIn P caid (daid :: l)\n  | consIsIn : forall  (P:JFACId -> JFACId -> Prop) (caid:JFACId) (daid:JFACId) (l:list JFACId),\n      P caid daid ->\n      isLeqIn P caid (daid :: l).\n\n\n\n\nLemma sub_leq_leqIsLS : forall CC Cid Cname mid mu1 mu2 D1 D2,\n    Cid = JFClass Cname ->\n    leqAnn mu1 mu2 ->\n    subtyping CC D1 D2 ->\n    leqIsLS CC Cid mid (D1,mu1) (D2,mu2).\nProof.\n  intros.\n  assert (isLSForId CC Cname mid \\/ ~isLSForId CC Cname mid)\n    as IsLSDec by auto with myhints.\n  destruct IsLSDec.\n  + econstructor 1; eauto 1.\n  + econstructor 2; eauto 1.  \nQed.\n\nLemma sub_leq_not_leqIsLS : forall CC Cid Cname mid mu1 mu2 D1 D2,\n    Cid = JFClass Cname ->\n    ~isLSForId CC Cname mid ->\n    subtyping CC D1 D2 ->\n    leqIsLS CC Cid mid (D1,mu1) (D2,mu2).\nProof.\n  intros.\n  + econstructor 2; eauto 1.  \nQed.\n\nLemma leqIsLS_sub : forall CC Cid mid mu1 mu2 D1 D2,\n    leqIsLS CC Cid mid (D1,mu1) (D2,mu2) ->\n    subtyping CC D1 D2.\nProof.\n  inversion 1; sauto.\nQed.\n\nLemma leqIsLS_dec : forall CC Cid mid d d',\n    leqIsLS CC Cid mid d d' \\/ ~leqIsLS CC Cid mid d d'.\nProof.\n  intros.\n  destruct d.\n  destruct d'.\n  destruct (subtyping_dec CC j j1).\n  + destruct (leqAnn_dec j0 j2).\n    ++ destruct Cid.\n       +++ destruct (isLSForId_dec CC cn mid).\n           ++++ left; eapply isLSTrue;eauto.\n           ++++ left; eapply isLSFalse;eauto.\n       +++ right.\n           intro.\n           inversion H1; congruence.\n    ++ destruct Cid.\n       +++ destruct (isLSForId_dec CC cn mid).\n           ++++ right.\n                intro.\n                inversion H2; try congruence.\n           ++++ left; eapply isLSFalse;eauto.\n       +++ right.\n           intro.\n           inversion H1; congruence.\n  + right.\n    intro.\n    apply H.\n    inversion H0;subst;injection H3;intros;injection H4;intros;subst;eauto.\nQed.\n\nHint Resolve leqIsLS_sub.\n                        \nLemma leqIsLS_leqAnn :\n  forall CC Cid mid C1 mu1 C2 mu2,\n    leqIsLS CC (JFClass Cid) mid (C1,mu1) (C2,mu2) ->\n    isLSForId CC Cid mid ->                           \n    leqAnn mu1 mu2.\nProof.\n  inversion 1; congruence.\nQed.\n\nHint Resolve leqIsLS_leqAnn.\n\nDefinition leqACId (CC:JFProgram) (C D:JFACId) : Prop :=\n  let (Cc,Can) := C in\n  let (Dc,Dan) := D in\n  subtyping CC Cc Dc /\\ leqAnn Can Dan.\n\nLemma leqACId_refl:\n  forall (CC:JFProgram) (C:JFACId),\n    leqACId CC C C.\nProof.\n  intros.\n  unfold leqACId.\n  destruct C.\n  auto with myhints.\nQed.\n\nLemma leqACId_trans:\n  forall (CC:JFProgram) (C D E:JFACId),\n    (program_contains CC JFObjectName) = true ->\n    names_unique CC -> \n    object_is_not_extended CC ->\n    extensions_in_all_but_object CC ->\n    leqACId CC C D -> leqACId CC D E -> leqACId CC C E.\nProof.\n  intros CC C D E Pcont Nu Onex extns lCD lDE.\n  unfold leqACId in *.\n  destruct C.\n  destruct D.\n  destruct E.\n  intuition.\n  + inversion H.\n    ++ rewrite H4 in *.\n      eapply subtrans;eauto 2.\n    ++ rewrite <- H4 in *.\n       eauto 2.\n    ++ rewrite <- H4 in *.\n       eauto 2.\n    ++ eapply subtrans;eauto 2.\n  + eauto 2 with myhints.\nQed.\n\nHint Resolve leqACId_refl leqACId_trans.\n\n\nLemma leqACId_leqIsLS :\n  forall CC Cn mid Acid1 Acid2, leqACId CC Acid1 Acid2 -> leqIsLS CC (JFClass Cn) mid Acid1 Acid2.\nProof.\n  destruct Acid1 as (C1,mu1).\n  destruct Acid2 as (C2,mu2).\n  \n  destruct 1.\n  edestruct isLSForId_dec.\n  + econstructor 1; eauto 1.\n  + econstructor 2; eauto 1.\nQed.\n\nHint Resolve leqACId_leqIsLS.\n\n\n(** The lower bound operation for the lattice of class types. *)\n(** [Cid ⊓ Did = Some Eid] iff [Cid Did ∈ CC] *)\nDefinition infClass (CC:JFProgram) (Cid Did:JFCId) :=\n  match Cid with\n  | JFClass cn => match Did with\n                  | JFClass dn =>\n                    if subtype_class_bool CC cn dn\n                    then JFClass cn\n                    else if subtype_class_bool CC dn cn\n                         then JFClass dn\n                         else JFBotClass\n                  | JFBotClass => JFBotClass\n                  end\n  | JFBotClass => JFBotClass\n  end.\n\n\nLemma infClass_comm:\n  forall CC Cid Did C,\n    subtype_well_founded CC ->\n    names_unique CC ->\n    infClass CC Cid Did = C ->\n    infClass CC Did Cid = C.\nProof.\n  intros CC Cid Did C Swf Nuq H.\n  unfold infClass in H.\n  unfold infClass.\n  destruct Cid, Did;eauto.\n  destruct (JFClassName_dec cn cn0);\n    destruct (JFClassName_dec cn0 cn);\n    subst; auto.\n  destruct (subtype_class_bool CC cn cn0) eqn:?;\n           destruct (subtype_class_bool CC cn0 cn) eqn:?; try auto.\n  eapply subtype_class_bool_refl in Heqb;eauto.\n  subst;auto.\nQed.\n\nLemma infClass_subtype_class_bool:\n  forall CC Cn Dn En,\n    infClass CC (JFClass Cn) (JFClass Dn) = JFClass En ->\n    subtype_class_bool CC En Cn = true.\nProof.\n  intros.\n  simpl in H.\n  destruct (subtype_class_bool CC Cn Dn) eqn:?; simplify_eq H;intros;subst;eauto 2.\n  destruct (subtype_class_bool CC Dn Cn) eqn:?; simplify_eq H;intros;subst;eauto 2.\nQed.\n\n(** [C1 ≤: C1 ⊓ C2] *)\nLemma infClass_subL : forall CC Cid Cid1 Cid2,\n    names_unique CC ->\n    subtype_well_founded CC ->\n    infClass CC Cid1 Cid2 = Cid -> subtyping CC Cid Cid1.\nProof.\n  intros.\n  unfold infClass in H1.\n  destruct Cid1, Cid2;subst;eauto 1.\n  destruct (subtype_class_bool CC cn cn0) eqn:?;eauto 1.\n  destruct (subtype_class_bool CC cn0 cn) eqn:?;eauto 1.\n  destruct (JFClassName_dec cn cn0);subst;eauto 1.\n  destruct (JFClassName_dec cn JFObjectName);eauto 1.\n  + subst. auto.\n  + generalize Heqb0;intros.\n    eapply subtype_class_bool_find_class_second in Heqb1; eauto 2.\nQed.\n\n\n(** [C2 ≤: C1 ⊓ C2] *)\nLemma infClass_subR : forall CC Cid Cid1 Cid2,\n    names_unique CC ->\n    subtype_well_founded CC ->\n    infClass CC Cid1 Cid2 = Cid -> subtyping CC Cid Cid2.\nProof.\n  intros.\n  eapply infClass_comm in H1;eauto 2.\n  eapply infClass_subL;eauto 2.\nQed.\n\n\n(** [C ≤: C1 -> C ≤: C2 -> C ≤: C1 ⊓ C2] *)\nLemma infClass_inf : forall CC Cid Cid' Cid1 Cid2,\n    subtyping CC Cid Cid1 -> subtyping CC Cid Cid2 ->\n    names_unique CC ->\n    subtype_well_founded CC ->\n    infClass CC Cid1 Cid2 = Cid' -> subtyping CC Cid Cid'.\nProof.\n  intros.\n  destruct Cid1, Cid2.\n  + simpl in H3.\n    destruct (subtype_class_bool CC cn cn0) eqn:?.\n    ++ subst;eauto 2.\n    ++ destruct (subtype_class_bool CC cn0 cn) eqn:?.\n       +++ subst;eauto 2.\n       +++ subst.\n           destruct (JFClassName_dec cn JFObjectName);\n             subst. try (rewrite subtype_class_bool_object in Heqb0; discriminate Heqb0).\n           destruct (JFClassName_dec cn0 JFObjectName);\n             subst; try (rewrite subtype_class_bool_object in Heqb; discriminate Heqb).\n           destruct (JFClassName_dec cn cn0);\n             subst; try (rewrite subtype_class_bool_same in Heqb; discriminate Heqb).\n           eapply subtyping_less in H;eauto 2.\n           destruct H.\n           * destruct CC.\n             ** inversion H;subst.\n                *** contradiction.\n                *** rewrite subtype_class_bool_object in Heqb0.\n                    discriminate Heqb0.\n                *** inversion H5.\n             ** generalize H1;intros.\n                eapply number_of_extends_some in H3;eauto 2.\n                decompose_ex H3.\n                generalize H1;intros.\n                eapply number_of_extends_object_is_not_extended in H4;eauto 2.\n                generalize H1;intros.\n                eapply subtyping_find_class in H5;eauto 2;unfold JFObject; try congruence.\n                decompose_ex H5.\n                eapply subtype_class_bool_complete in H;eauto 2;unfold JFObject;try congruence.\n           * destruct H.\n             ** destruct CC.\n                *** inversion H;subst.\n                    **** contradiction.\n                    **** contradiction.\n                    **** inversion H5.\n                *** generalize H1;intros.\n                    eapply number_of_extends_some in H3;eauto 2.\n                    decompose_ex H3.\n                    generalize H1;intros.\n                    eapply number_of_extends_object_is_not_extended in H4;eauto 2.\n                    generalize H1;intros.\n                    eapply subtyping_find_class in H5;eauto 2;unfold JFObject; try congruence.\n                    decompose_ex H5.\n                    eapply subtype_class_bool_complete in H;eauto 2;unfold JFObject;try congruence.\n             ** subst;eauto 2.\n  + sauto.\n  + sauto.\n  + sauto.\nQed.\n\nLemma infClass_trichotomy:\n  forall CC Cid Did,\n    infClass CC Cid Did = Cid \\/ infClass CC Cid Did = Did \\/ infClass CC Cid Did = JFBotClass.\nProof.\n  intros.\n  unfold infClass.\n  destruct Cid;eauto.\n  destruct Did;eauto.\n  destruct (subtype_class_bool CC cn cn0);eauto.\n  destruct (subtype_class_bool CC cn0 cn);eauto.\nQed.\n  \n(** Greatest lower bound of [acid1] and [acid2] *)\n(** [acid1 ⊓ acid2 = Some acid] iff [acid, acid2 ∈ CC] *)\n\nDefinition infACId (CC:JFProgram) (acid1 acid2:JFACId) :=\n  let (tp1,an1) := acid1 in\n  let (tp2,an2) := acid2 in\n  (infClass CC tp1 tp2, infAnn an1 an2).\n\n\nLemma infACId_infClass : forall CC Cid1 mu1 Cid2 mu2 Cid mu,\n    infACId CC (Cid1,mu1) (Cid2,mu2) = (Cid,mu) ->\n    infClass CC Cid1 Cid2 = Cid.\nProof.\n  intros until 0.\n  unfold infACId.\n  congruence.\nQed.\n\nLemma infACId_infAnn : forall CC Cid1 mu1 Cid2 mu2 Cid mu,\n    infACId CC (Cid1,mu1) (Cid2,mu2) = (Cid,mu) ->\n    infAnn mu1 mu2 = mu.\nProof.\n  intros until 0.\n  unfold infACId.\n  congruence.\nQed.\n\n\n\nLemma infACId_comm:\n  forall CC Cid Did C,\n    subtype_well_founded CC ->\n    names_unique CC ->\n    infACId CC Cid Did = C ->\n    infACId CC Did Cid = C.\nProof.\n  intros.\n  unfold infACId in H1.\n  unfold infACId.\n  destruct Did, Cid.\n  destruct (infClass CC j1 j) eqn:?;try discriminate H1.\n  + eapply infClass_comm in Heqj3;eauto.\n    rewrite Heqj3.\n    rewrite <- H1.\n    replace (infAnn j0 j2) with (infAnn j2 j0);auto.\n    unfold infAnn.\n    destruct j2;destruct j0;eauto.\n  + eapply infClass_comm in Heqj3;eauto.\n    rewrite Heqj3.\n    replace (infAnn j0 j2) with (infAnn j2 j0);auto.\n    unfold infAnn.\n    destruct j2;destruct j0;eauto.\nQed.\n\n(** [acid1 ≤: acid1 ⊓ acid2] *)\nLemma infACId_leqIsLS_L:\n  forall CC acid1 acid2 acid Cn mid,\n    names_unique CC ->\n    subtype_well_founded CC -> \n    infACId CC acid1 acid2 = acid ->\n    leqIsLS CC (JFClass Cn) mid acid acid1.\nProof.\n  intros CC acid1 acid2 acid Cn mid.\n  intros Nuq Swf.\n  intros.\n  destruct acid1 as (C1,mu1).\n  destruct acid2 as (C2,mu2).\n  simpl in H.\n  destruct acid as (C,mu).\n  injection H;intros.\n  edestruct isLSForId_dec.\n  + econstructor 1;eauto 2 with myhints.\n    destruct C; eauto 1.\n    destruct C1, C2; try discriminate H1.\n    eapply infClass_subtype_class_bool in H1;eauto 2.\n  + econstructor 2;eauto 2.\n    destruct C; eauto 2.\n    destruct C1, C2; try discriminate H1.\n    eapply infClass_subtype_class_bool in H1;eauto 2.\nQed.\n\n\n(** [acid2 ≤: acid1 ⊓ acid2] *)\nLemma infACId_leqIsLS_R:\n  forall CC acida acidb acidc Cn mid,\n    names_unique CC ->\n    subtype_well_founded CC -> \n    infACId CC acida acidb = acidc ->\n    leqIsLS CC (JFClass Cn) mid acidc acidb.\nProof.\n  intros CC acida acidb acidc Cn mid.\n  intros Nuq Swf.\n  intros.\n  eapply infACId_comm in H;eauto 2.\n  eapply infACId_leqIsLS_L in H;eauto 2.\nQed.\n\n(** [acid ≤: acid1 -> acid ≤: acid2 -> acid ≤: acid1 ⊓ acid2] *)\nLemma infACId_leqIsLS_largest:\n  forall CC acid acid' acid1 acid2 Cn mid,\n    names_unique CC ->\n    subtype_well_founded CC -> \n    leqIsLS CC (JFClass Cn) mid acid acid1 ->\n    leqIsLS CC (JFClass Cn) mid acid acid2 ->\n    infACId CC acid1 acid2 = acid' ->\n    leqIsLS CC (JFClass Cn) mid acid acid'.\nProof.\n  intros CC acid acid' acid1 acid2 Cn mid.\n  intros Nuq Swf.\n  intros Leq0 Leq1 InfACId.\n  destruct acid, acid'.\n  destruct acid1, acid2.\n  generalize InfACId;intros.\n  eapply infACId_infAnn in InfACId0.\n  generalize InfACId;intros.\n  eapply infACId_infClass in InfACId1.\n  destruct (isLSForId_dec CC Cn mid).\n  + eapply sub_leq_leqIsLS;eauto.\n    ++ inversion Leq0; try congruence.\n       simplify_eq H2;\n         simplify_eq H3;intros.\n       subst.\n       clear H2 H3.\n       inversion Leq1; try congruence.\n       simplify_eq H6;\n         simplify_eq H7;intros.\n       subst.\n       clear H6 H7;eauto using infAnn_inf.\n    ++ inversion Leq0; try congruence.\n       simplify_eq H2;\n         simplify_eq H3;intros.\n       subst.\n       clear H2 H3.\n       inversion Leq1; try congruence.\n       simplify_eq H6;\n         simplify_eq H7;intros.\n       subst.\n       clear H6 H7.\n       eapply infClass_inf.\n       apply H4.\n       apply H8.\n       auto.\n       auto.\n       auto.\n  + eapply sub_leq_not_leqIsLS;eauto 2.\n    inversion Leq0; try congruence.\n    simplify_eq H2;\n      simplify_eq H3;intros.\n    subst.\n    clear H2 H3.\n    inversion Leq1; try congruence.\n    simplify_eq H5;\n      simplify_eq H6;intros.\n    subst.\n    clear H5 H6.\n    eapply infClass_inf.\n    apply H4.\n    apply H7.\n    auto.\n    auto.\n    auto.\nQed.\n\n\n(**\n   Lifting of an inequality predicate that compares using a given parameter predicate P a list\n   of JFACId's with a list of JFACId's. It holds true when at least one comparison holds.\n*)\nInductive isLeqIncluded : (JFACId -> JFACId -> Prop) -> list JFACId -> list JFACId -> Prop :=\n  | emptyFirst : forall  (CC:JFACId -> JFACId -> Prop) (l2:list JFACId),\n      isLeqIncluded CC [] l2\n  | consFirst : forall  (CC:JFACId -> JFACId -> Prop) (caid:JFACId) (l1:list JFACId) (l2:list JFACId),\n      isLeqIn CC caid l2 ->\n      isLeqIncluded CC l1 l2 ->\n      isLeqIncluded CC (caid :: l1) l2.\n\nLemma leqISLS_isLeqIn:\n  forall l CC C m a a' cname,\n    program_contains CC JFObjectName = true ->\n    names_unique CC ->\n    object_is_not_extended CC ->\n    extensions_in_all_but_object CC ->\n    C = JFClass cname ->\n    leqIsLS CC C m a a' ->\n    isLeqIn (leqIsLS CC C m) a' l ->\n    isLeqIn (leqIsLS CC C m) a l.\nProof.\n  induction l.\n  + intros CC C m a a' cname Pcont Nuq Oine Eiabo Ceq. intros.\n    inversion H0.\n  + intros CC C m a0 a' cname Pcont Nuq Oine Eiabo Ceq. intros.\n    inversion H0.\n    ++ subst.\n       eapply IHl in H6; try apply H;eauto.\n       destruct (leqIsLS_dec CC (JFClass cname) m a0 a).\n       +++ constructor 2;eauto.\n       +++ constructor 1;eauto.\n    ++ subst.\n       constructor 2;eauto 2.\nQed.\n\nLemma leqIsLS_isLeqIncluded:\n  forall CC cid m C mu D nu,\n    leqIsLS CC cid m (C, mu) (D, nu) ->\n    isLeqIncluded (leqIsLS CC cid m) [(C,mu)] [(D, nu)].\nProof.\n  intros.\n  eapply consFirst;eauto.\n  eapply consIsIn;eauto.\n  constructor.\nQed.\n  \nLemma isLeqIncluded_monotone:\n  forall CC C m a l1 l2,\n    isLeqIncluded (leqIsLS CC C m) (a :: l1) l2 ->\n    isLeqIncluded (leqIsLS CC C m) l1 l2.\nProof.\n  destruct l1.\n  + sauto.\n  + intros.\n    constructor 2.\n    ++ inversion H.\n       subst.\n       inversion H5.\n       auto.\n    ++ inversion H.\n       subst.\n       inversion H5.\n       auto.\nQed.\n\nLemma isLeqIn_isLeqIncluded:\n  forall CC C cn m a l1 l2,\n    program_contains CC JFObjectName = true ->\n    names_unique CC ->\n    object_is_not_extended CC ->\n    extensions_in_all_but_object CC ->\n    C = JFClass cn ->\n    isLeqIn (leqIsLS CC C m) a l1 ->\n    isLeqIncluded (leqIsLS CC C m) l1 l2 ->\n    isLeqIn (leqIsLS CC C m) a l2.\nProof.\n  induction l1.\n  + intros.\n    inversion H4.\n  + intros.\n    inversion H4.\n    ++ subst.\n       eapply IHl1;eauto.\n       inversion H5.\n       subst.\n       eauto using isLeqIncluded_monotone.\n    ++ subst.\n       inversion H5.\n       subst.\n       eauto 2 using leqISLS_isLeqIn.\nQed.\n\nLemma isLeqIncluded_trans:\n  forall CC C cn m l1 l2 l3,\n    program_contains CC JFObjectName = true ->\n    names_unique CC ->\n    object_is_not_extended CC ->\n    extensions_in_all_but_object CC ->\n    C = JFClass cn ->\n    isLeqIncluded (leqIsLS CC C m) l1 l2 ->\n    isLeqIncluded (leqIsLS CC C m) l2 l3 ->\n    isLeqIncluded (leqIsLS CC C m) l1 l3.\nProof.\n  intros.\n  induction l1.\n  + constructor.\n  + constructor 2.\n    inversion H4.\n    subst.\n    eauto using isLeqIn_isLeqIncluded.\n    eauto using isLeqIncluded_monotone.\nQed.\n\nDefinition leqAcid_bool (CC:JFProgram) (acid1:JFACId) (acid2:JFACId) :=\n  match acid1 with\n  | (C,mu) => match acid2 with\n              | (C',mu') => andb (subtype_bool CC C C') (leqAnn_bool mu mu')\n              end\n  end.\n\n", "meta": {"author": "jbujak", "repo": "jafun", "sha": "4b9b2d21ba06e6a98c885c8bf2cc202f52595058", "save_path": "github-repos/coq/jbujak-jafun", "path": "github-repos/coq/jbujak-jafun/jafun-4b9b2d21ba06e6a98c885c8bf2cc202f52595058/JaSubtype.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891307678321, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22885293194751755}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool eqtype seq.\nRequire Import Init_ext ssrZ ZArith_ext seq_ext uniq_tac machine_int.\nRequire Import multi_int encode_decode integral_type.\nImport MachineInt.\nRequire Import mips_bipl mips_tactics mips_syntax mips_mint.\nImport mips_bipl.expr_m.\nRequire Import simu.\nImport simu.simu_m.\nRequire Import multi_halve_u_prg multi_halve_u_triple multi_halve_u_termination.\n\nLocal Open Scope heap_scope.\nLocal Open Scope assoc_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope machine_int_scope.\nLocal Open Scope asm_expr_scope.\nLocal Open Scope zarith_ext_scope.\n\nLemma multi_halve_u_safe_termination a0 a1 a2 a3 rx x rk d :\n  uniq(rk, rx, a0, a1, a2, a3, r0) ->\n  safe_termination (state_mint (x |=> unsign rk rx \\U+ d))\n    (multi_halve_u rk rx a0 a1 a2 a3).\nProof.\nmove=> Hset.\nrewrite /safe_termination => st s h st_s_h.\ncase/(multi_halve_u_termination s h) : (Hset) => x0 exec_mips.\napply constructive_indefinite_description'.\nhave H1 : u2Z ([ rx ]_ s) + 4 * Z_of_nat '|u2Z ([rk ]_ s)| < Zbeta 1.\n  apply state_mint_head_unsign_fit with x d st h.\n  by apply st_s_h.\nhave H3 : size (Z2ints 32 '|u2Z ([ rk ]_ s)| ([ x ]_st)%pseudo_expr) = '|u2Z ([rk ]_ s)|.\n  by rewrite size_Z2ints.\nmove: (multi_halve_u_triple _ _ _ _ _ _ Hset _ _ H1 _ H3) => Htriple.\nmove: (triple_exec_precond _ _ _ Htriple _ _ _ exec_mips (iota\n      '|u2Z ([rx ]_ s) / 4| '|u2Z ([rk ]_ s)|)).\napply.\nsplit; first by [].\nsplit.\n- rewrite Z_of_nat_Zabs_nat //; by apply min_u2Z.\n- apply (state_mint_var_mint _ _ _ _ x (unsign rk rx)) in st_s_h; last by assoc_get_Some.\n  by apply st_s_h.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/begcd/multi_halve_u_safe_termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22885293194751752}}
{"text": "From iris Require Import program_logic.weakestpre.\nFrom st.STLCmuVS Require Import lang wkpre.\nFrom iris.proofmode Require Import tactics.\n\nSection lift.\n\n  Context `{Σ : !gFunctors}.\n  Context `{irisGS_inst : !irisGS STLCmuVS_lang Σ}.\n\n  Context (s : stuckness).\n\n  Definition lift (Φ : valO -n> valO -n> iPropO Σ) : exprO → exprO → iProp Σ :=\n    fun eᵢ eₛ => (WP eᵢ @ s ; top {{ vᵢ, ∃ vₛ, ⌜ rtc STLCmuVS_step eₛ (of_val vₛ) ⌝ ∧ Φ vᵢ vₛ }})%I.\n\n  Definition liftl (Φ : valO -n> valO -n> iPropO Σ) : exprO → exprO → iProp Σ :=\n    fun eₛ eᵢ => (WP eᵢ @ s ; top {{ vᵢ, ∃ vₛ, ⌜ rtc STLCmuVS_step eₛ (of_val vₛ) ⌝ ∧ Φ vₛ vᵢ }})%I.\n\n  Lemma bla eᵢ eₛ Φ : lift Φ eᵢ eₛ ⊣⊢ liftl (λne x x', Φ x' x) eₛ eᵢ.\n  Proof. auto. Qed.\n\n  Lemma lift_bind (Φ Ψ : valO -n> valO -n> iPropO Σ) (Kᵢ Kₛ : ectx STLCmuVS_ectx_lang) (eᵢ eₛ : expr) :\n    (lift Φ eᵢ eₛ ∗ ∀ vᵢ vₛ, Φ vᵢ vₛ -∗ lift Ψ (fill Kᵢ (of_val vᵢ)) (fill Kₛ (of_val vₛ))) ⊢ lift Ψ (fill Kᵢ eᵢ) (fill Kₛ eₛ).\n  Proof.\n    iIntros \"[HΦeN H]\". rewrite /lift.\n    iApply wp_bind. iApply (wp_wand with \"HΦeN\").\n    iIntros (v). iIntros \"des\". iDestruct \"des\" as (v') \"[%HNv' Hvv']\".\n    iSpecialize (\"H\" $! v v' with \"Hvv'\").\n    iApply (wp_wand with \"H\").\n    iIntros (w). iIntros \"des\". iDestruct \"des\" as (w') \"[%HKₛv'w' Hww']\".\n    iExists w'. iFrame. iPureIntro.\n    apply (rtc_transitive _ (fill Kₛ v')); auto. simpl in *.\n    by apply (rtc_STLCmuVS_step_ctx (fill Kₛ)).\n  Qed.\n\n  Lemma lift_bind' (Φ Ψ : valO -n> valO -n> iPropO Σ) (Kᵢ Kₛ : ectx STLCmuVS_ectx_lang) (eᵢ eₛ : expr) :\n    ⊢ lift Φ eᵢ eₛ -∗ (∀ vᵢ vₛ, Φ vᵢ vₛ -∗ lift Ψ (fill Kᵢ (of_val vᵢ)) (fill Kₛ (of_val vₛ))) -∗ lift Ψ (fill Kᵢ eᵢ) (fill Kₛ eₛ).\n  Proof. iIntros \"HΦeN H\". rewrite /lift. iApply lift_bind. iFrame \"HΦeN\". auto. Qed.\n\n  Lemma lift_bind'' (Kᵢ Kₛ : list ectx_item) (Φ Ψ : valO -n> valO -n> iPropO Σ) (eᵢ eₛ : expr) :\n    ⊢ lift Φ eᵢ eₛ -∗ (∀ vᵢ vₛ, Φ vᵢ vₛ -∗ lift Ψ (fill Kᵢ (of_val vᵢ)) (fill Kₛ (of_val vₛ))) -∗ lift Ψ (fill Kᵢ eᵢ) (fill Kₛ eₛ).\n  Proof. iApply lift_bind'. Qed.\n\n  Hint Extern 5 (IntoVal _ _) => eapply of_to_val; fast_done : typeclass_instances.\n  Hint Extern 10 (IntoVal _ _) =>\n    rewrite /IntoVal; eapply of_to_val; rewrite /= !to_of_val /=; solve [ eauto ] : typeclass_instances.\n\n  Lemma lift_val (Ψ : valO -n> valO -n> iPropO Σ) (vᵢ vₛ : val) : (Ψ vᵢ vₛ) ⊢ lift Ψ vᵢ vₛ.\n  Proof. iIntros \"Hv\". rewrite /lift. iApply wp_value. iExists vₛ. auto. Qed.\n\n  (* lemmas for impl side; lets only have _later lemmas for lift *)\n\n  Lemma lift_nsteps_later Φ e e' eₛ n (H : nsteps STLCmuVS_step n e e') : ▷^n lift Φ e' eₛ ⊢ lift Φ e eₛ.\n  Proof. by iApply wp_nsteps_later. Qed.\n\n  Lemma lift_PureExec_later Φ e e' eₛ n (H : PureExec True n e e') : ▷^n lift Φ e' eₛ ⊢ lift Φ e eₛ.\n  Proof. by iApply wp_PureExec_later. Qed.\n\n  Lemma lift_step_later Φ e e' eₛ (H : STLCmuVS_step e e') : ▷ lift Φ e' eₛ ⊢ lift Φ e eₛ.\n  Proof. by iApply wp_step_later. Qed.\n\n  (* lemmas for impl side; no_later *)\n\n  Lemma lift_rtc_steps_impl Φ e e' eₛ (H : rtc STLCmuVS_step e e') : lift Φ e' eₛ ⊢ lift Φ e eₛ.\n  Proof. by iApply wp_rtc_steps. Qed.\n\n  (* lemmas for spec sideᵢ *)\n\n  Lemma lift_rtc_steps Φ eᵢ e e' (H : rtc STLCmuVS_step e e') : lift Φ eᵢ e' ⊢ lift Φ eᵢ e.\n  Proof.\n    iIntros \"H\". iApply (wp_wand with \"H\").\n    iIntros (v) \"des\". iDestruct \"des\" as (w') \"[%H1 H2]\". iExists w'. iFrame \"H2\".\n    iPureIntro. by eapply rtc_transitive.\n  Qed.\n\n  Lemma lift_step Φ eᵢ e e' (H : STLCmuVS_step e e') : lift Φ eᵢ e' ⊢ lift Φ eᵢ e.\n  Proof. iApply lift_rtc_steps. by apply rtc_once. Qed.\n\n  Lemma lift_impl (Φ Ψ : valO -n> valO -n> iPropO Σ) (H : ∀ v v', Φ v v' ⊢ Ψ v v') :\n    ∀ e e', lift Φ e e' ⊢ lift Ψ e e'.\n  Proof.\n    iIntros (e e') \"Hee'\". rewrite /lift.\n    iApply (wp_wand with \"Hee'\"). iIntros (v) \"Hdes\".\n    iDestruct \"Hdes\" as (v') \"[%He'v' HΦ]\".\n    iExists v'. iSplit. auto. by iApply H.\n  Qed.\n\n  Lemma lift_equiv (Φ Ψ : valO -n> valO -n> iPropO Σ) (H : ∀ v v', Φ v v' ⊣⊢ Ψ v v') :\n    ∀ e e', lift Φ e e' ⊣⊢ lift Ψ e e'.\n  Proof. iIntros (e e'). iSplit; iApply lift_impl; iIntros (v v') \"Hvv'\"; by iApply H. Qed.\n\n  Lemma lift_wand (Φ Ψ : valO -n> valO -n> iPropO Σ) e e' :\n    ⊢ (∀ v v', Φ v v' -∗ Ψ v v') -∗ lift Φ e e' -∗ lift Ψ e e'.\n  Proof.\n    iIntros \"H Hee'\". rewrite /lift.\n    iApply (wp_wand with \"Hee'\"). iIntros (v) \"Hdes\".\n    iDestruct \"Hdes\" as (v') \"[%He'v' HΦ]\".\n    iExists v'. iSplit. auto. by iApply \"H\".\n  Qed.\n\n  Lemma anti_step_help e1 e2 v : STLCmuVS_step e1 e2 → rtc STLCmuVS_step e1 (of_val v) → rtc STLCmuVS_step e2 (of_val v).\n  Proof.\n    intros H Hs.\n    inversion Hs; subst.\n    - exfalso. assert (to_val v = None) as Hn by eapply (language.val_stuck _ _ _ _ _ _ H).\n      by rewrite to_of_val in Hn.\n    - by rewrite (prim_step_det _ _ _ _ _ H0 H) in H1.\n  Qed.\n\n  Lemma anti_steps_help e1 e2 v : rtc STLCmuVS_step e1 e2 → rtc STLCmuVS_step e1 (of_val v) → rtc STLCmuVS_step e2 (of_val v).\n  Proof.\n    intros H Hs. destruct (iffLR (rtc_nsteps _ _) H) as [m Hm].\n    revert H Hs Hm. revert v e1 e2. induction m.\n    - simpl. intros. inversion Hm. by subst.\n    - intros. inversion Hm. subst.\n      pose proof (anti_step_help _ _ _ H1 Hs).\n      eapply (IHm _ _ _ (rtc_nsteps_2 _ _ _ H2) H0 H2).\n  Qed.\n\n  Lemma lift_anti_steps_spec Φ eᵢ e1 e2 (H : rtc STLCmuVS_step e1 e2) : lift Φ eᵢ e1 ⊢ lift Φ eᵢ e2.\n  Proof.\n    iIntros \"H\". iApply (wp_wand with \"H\"). iIntros (v) \"des\".\n    iDestruct \"des\" as (v') \"[%Hs H]\". iExists v'. iFrame \"H\".\n    iPureIntro. by eapply anti_steps_help.\n  Qed.\n\nEnd lift.\n\nNotation \"lift!\" := (lift NotStuck).\nNotation \"lift?\" := (lift MaybeStuck).\n", "meta": {"author": "scaup", "repo": "sem_backs_st", "sha": "e14aa7f421de94df5c1369d2b4b44d8644243cec", "save_path": "github-repos/coq/scaup-sem_backs_st", "path": "github-repos/coq/scaup-sem_backs_st/sem_backs_st-e14aa7f421de94df5c1369d2b4b44d8644243cec/theories/STLCmuVS/logrel/generic/lift.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22885293194751752}}
{"text": "From ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import Containers.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Execution.Test Require Import QCTest.\nFrom ConCert.Examples.iTokenBuggy Require Import iTokenBuggy.\nImport MonadNotation.\nFrom Coq Require Import List. Import ListNotations.\nFrom Coq Require Import ZArith.\n\nModule Type iTokenBuggyGensInfo.\n  Parameter contract_addr : Address.\n  Parameter gAccount : G Address.\nEnd iTokenBuggyGensInfo.\n\nModule iTokenBuggyGens (Info : iTokenBuggyGensInfo).\n  Import Info.\n  Arguments SerializedValue : clear implicits.\n  Arguments deserialize : clear implicits.\n  Arguments serialize : clear implicits.\n\n  Definition serializeMsg := @serialize iTokenBuggy.Msg _.\n\n  Local Open Scope N_scope.\n\n  Definition sampleFMapOpt {A B : Type}\n                          `{countable.Countable A}\n                          `{base.EqDecision A}\n                           (m : FMap A B)\n                           : GOpt (A * B) :=\n    TestUtils.sampleFMapOpt m.\n\n  (* Note: not optimal implementation. Should filter on\n     balances map instead of first sampling and then filtering *)\n  Definition gApprove (state : iTokenBuggy.State) : GOpt (Address * Msg) :=\n  '((addr1, balance1), (addr2, balance2)) <- sample2UniqueFMapOpt state.(balances) ;;\n    if 0 <? balance1\n    then amount <- choose (0, balance1) ;; returnGenSome (addr1, approve addr2 amount)\n    else if 0 <? balance2\n    then amount <- choose (0, balance2) ;; returnGenSome (addr2, approve addr1 amount)\n    else returnGen None.\n\n  Definition gTransfer_from (state : iTokenBuggy.State) : GOpt (Address * Msg) :=\n  '(allower, allowance_map) <- sampleFMapOpt state.(allowances) ;;\n  '(delegate, allowance) <- sampleFMapOpt allowance_map ;;\n  '(receiver,_) <- sampleFMapOpt state.(balances) ;;\n    let allower_balance := (FMap_find_ allower state.(balances) 0) in\n    amount <- (if allower_balance =? 0\n              then returnGen 0\n              else choose (0, N.min allowance allower_balance)) ;;\n    returnGenSome (delegate, transfer_from allower receiver amount).\n\n  Definition gMint (c : Environment)\n                   (state : iTokenBuggy.State)\n                   : GOpt (Address * Msg) :=\n    addr <- gAccount ;;\n    (* fix the number of minted tokens to 0, 1, or 2*)\n    amount <- choose (0, 2) ;;\n    returnGenSome (addr, mint amount ).\n\n  Definition gBurn (state : iTokenBuggy.State) : GOpt (Address * Msg) :=\n  '(addr, balance) <- sampleFMapOpt_filter state.(balances) (fun '(_,balance) => 0 <? balance) ;;\n    (* we purposely give it a small chance to try to burn more than allowed, hence +2*)\n    amount <- choose (0, balance + 2) ;;\n    returnGenSome (addr, burn amount).\n\n  Local Close Scope N_scope.\n  (* Main generator. *)\n  Definition giTokenBuggyAction (env : Environment) : GOpt Action :=\n    let call caller_addr contract_addr msg :=\n        returnGenSome {|\n            act_origin := caller_addr;\n            act_from := caller_addr;\n            act_body := act_call contract_addr 0%Z (serializeMsg msg)\n          |} in\n    state <- returnGen (get_contract_state iTokenBuggy.State env contract_addr) ;;\n    backtrack [\n      (* mint *)\n      (1, '(caller, msg) <- gMint env state ;;\n          call caller contract_addr msg\n      ) ;\n      (* burn *)\n      (1, '(caller, msg) <- gBurn state ;;\n          call caller contract_addr msg\n      ) ;\n      (* transfer_from *)\n      (4, '(caller, msg) <- gTransfer_from state ;;\n          call caller contract_addr msg\n      );\n      (* approve *)\n      (2, '(caller, msg) <- gApprove state ;;\n          call caller contract_addr msg\n      )\n    ].\n\nEnd iTokenBuggyGens.\n", "meta": {"author": "AU-COBRA", "repo": "ConCert", "sha": "55ffd996fe89d41677a2ff368d3a5e4be1e997b7", "save_path": "github-repos/coq/AU-COBRA-ConCert", "path": "github-repos/coq/AU-COBRA-ConCert/ConCert-55ffd996fe89d41677a2ff368d3a5e4be1e997b7/examples/iTokenBuggy/iTokenBuggyGens.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.22885293194751746}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ZArith_ext seq_ext machine_int uniq_tac.\nImport MachineInt.\nRequire Import mips_cmd mips_tactics mips_contrib.\nImport expr_m.\nRequire Import mont_mul_strict_prg mont_mul_termination multi_lt_termination.\nRequire Import multi_sub_u_u_termination multi_zero_u_termination.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope mips_expr_scope.\nLocal Open Scope mips_cmd_scope.\nLocal Open Scope uniq_scope.\n\nLemma mont_mul_strict_termination s h k alpha x y z m one ext int_ X_ B2K_ Y_ M_ quot C_ t s_ :\n  uniq(k, alpha, x, y, z, m, one, ext, int_, X_, B2K_, Y_, M_, quot, C_, t, s_, r0) ->\n  { si | Some (s, h) -- mont_mul_strict k alpha x y z m one ext int_ X_ B2K_ Y_ M_ quot C_ t s_ ---> si }.\nProof.\nmove=> Hset; rewrite /mont_mul_strict.\napply exists_seq_P2 with (fun si => True).\n- case/(termination_montgomery s h) : Hset => si Hsi; by exists si.\n- move=> [si hi] Psi.\n  + apply exists_ifte.\n    * apply exists_seq_P2 with (fun _ => True).\n      - have : uniq(k, z, m, X_, B2K_, int_, ext, M_, Y_, r0) by Uniq_uniq r0.\n        case/(multi_lt_termination si hi) => sj Hsj; by exists sj.\n      - move=> [sj hj] Psj.\n        + apply exists_ifte.\n          * have : uniq(k, m, z, ext, int_, quot, C_, M_, B2K_, r0) by Uniq_uniq r0.\n            move/(multi_sub_u_u_termination sj hj z) => [sk Hk]; by exists sk.\n          * apply exists_nop; by move: {Psj}(Psj _ (refl_equal _)).\n    * apply exists_addiu_seq.\n      exists_sw_new l Hl z0 Hz0.\n      repeat Reg_upd.\n      apply exists_addiu_seq.\n      repeat Reg_upd.\n      have : uniq(ext, m, z, Y_, int_, quot, C_, M_, B2K_, r0) by Uniq_uniq r0.\n      set s0 := store.upd _ _ _. set h0 := heap.upd _ _ _.\n      move/(multi_sub_u_u_termination s0 h0 z) => [sk Hk].\n      eexists; by apply Hk.\nQed.\n\nLemma mont_mul_strict_init_termination s h k alpha x y z m one ext int_ X_ B2K_ Y_ M_ quot C_ t s_ :\n  uniq(k, alpha, x, y, z, m, one, ext, int_, X_, B2K_, Y_, M_, quot, C_, t, s_, r0) ->\n    { si | Some (s, h) -- mont_mul_strict_init k alpha x y z m one ext int_ X_ B2K_ Y_ M_ quot C_ t s_ ---> si }.\nProof.\nmove=> Hset; rewrite /mont_mul_strict_init.\napply exists_seq_P2 with (fun _ => True).\n- have : uniq(k, z, ext, M_, r0) by Uniq_uniq r0.\n  case/(multi_zero_u_termination s h) => si Hsi; by exists si.\n- move=> [si hi] Psi.\n  + apply exists_seq_P2 with (Q := fun sj => True).\n    * by apply exists_mflhxu_seq_P, exists_mthi_seq_P, exists_mtlo_P.\n    * move=> [sj hj] HPsj.\n      - have : uniq(k, alpha, x, y, z, m, one, ext, int_, X_, B2K_, Y_, M_, quot, C_, t, s_, r0) by Uniq_uniq r0.\n        case/(mont_mul_strict_termination sj hj) => x0 Hx0; by exists x0.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/cryptoasm/mont_mul_strict_termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.22884559723156378}}
{"text": "Require Import Coq.Lists.List.\nRequire Import BinNums BinInt.\n\nImport ListNotations.\n\nRequire Import Types Ops BValues Syntax Typing BEnv BMemory Validity External.\n\nFrom compcert Require Import Integers Floats Maps Smallstep.\nFrom compcert Require Import Globalenvs.\nFrom compcert Require AST Events.\nModule CAST := AST.\n\nSection SEMANTICS.\n\nVariable ge: genv.\n\nSection EXPR.\n\nVariable m: mem.\nVariable e: env.\nVariable f: function.\n(* Variable arrszvar: list (ident * ident).\n   Variable te: tenv. *)\n\nInductive eval_expr: expr -> value -> Prop :=\n| eval_Const_int: forall sz sig n,\n  eval_expr (Econst (Cint sz sig n)) (Vint sz sig n)\n| eval_Const_int64: forall sig n,\n  eval_expr (Econst (Cint64 sig n)) (Vint64 sig n)\n| eval_Const_float32: forall f,\n  eval_expr (Econst (Cfloat32 f)) (Vfloat32 f)\n| eval_Const_float64: forall f,\n  eval_expr (Econst (Cfloat64 f)) (Vfloat64 f)\n| eval_Var: forall id v t,\n  e!id = Some v ->\n  f.(fn_tenv)!id = Some t ->\n  well_typed_value v t ->\n  eval_expr (Evar id) v\n| eval_Cast: forall exp t t1 v1 v,\n  eval_expr exp v1 ->\n  well_typed_value v1 t1 ->\n  sem_cast v1 t1 t = Some v ->\n  eval_expr (Ecast exp t1 t) v\n| eval_Unop: forall op k e1 v1 v,\n  eval_expr e1 v1 ->\n  sem_unop op k v1 = Some v ->\n  eval_expr (Eunop op k e1) v\n| eval_Binop_arith: forall op k e1 e2 v1 v2 v,\n  eval_expr e1 v1 ->\n  eval_expr e2 v2 ->\n  sem_binarith_operation op k v1 v2 = Some v ->\n  eval_expr (Ebinop_arith op k e1 e2) v\n| eval_Binop_logical: forall op e1 e2 v1 v2 v,\n  eval_expr e1 v1 ->\n  eval_expr e2 v2 ->\n  sem_logical_operation op v1 v2 = Some v ->\n  eval_expr (Ebinop_logical op e1 e2) v\n| eval_Binop_cmp: forall op k e1 e2 v1 v2 v,\n  eval_expr e1 v1 ->\n  eval_expr e2 v2 ->\n  sem_cmp_operation op k v1 v2 = Some v ->\n  eval_expr (Ebinop_cmp op k e1 e2) v\n| eval_Binop_cmpu: forall op k e1 e2 v1 v2 v,\n  eval_expr e1 v1 ->\n  eval_expr e2 v2 ->\n  sem_cmpu_operation op k v1 v2 = Some v ->\n  eval_expr (Ebinop_cmpu op k e1 e2) v\n| eval_Arr_access: forall id idx idarr blk lv szvar n i v b t,\n  e!id = Some (Varr idarr lv) ->\n  f.(fn_tenv)!id = Some (Tarr b t) ->\n  eval_expr idx (Vint64 Unsigned i) ->\n  In (id, szvar) f.(fn_arrszvar) ->\n  e!szvar = Some (Vint64 Unsigned n) ->\n  m!idarr = Some blk ->\n  blk.(blk_values) = lv ->\n  blk.(blk_type) = t ->\n  Int64.unsigned i < Int64.unsigned n ->\n  nth_error lv (Z.to_nat (Int64.unsigned i)) = Some v ->\n  eval_expr (Earr_access id idx) v.\n(* | eval_Mutarr_access: forall id idx idarr blk szvar n i v t,\n     e!id = Some (Vmutarr idarr) ->\n     f.(fn_tenv)!id = Some (Tarr true t) ->\n     eval_expr idx (Vint64 Unsigned i) ->\n     In (id, szvar) f.(fn_arrszvar) ->\n     e!szvar = Some (Vint64 Unsigned n) ->\n     m!idarr = Some blk ->\n     blk.(blk_type) = t ->\n     Int64.unsigned i < Int64.unsigned n ->\n     nth_error blk.(blk_values) (Z.to_nat (Int64.unsigned i)) = Some v ->\n     eval_expr (Earr_access id idx) v. *)\n\nInductive eval_exprlist: list expr -> list value -> Prop :=\n| eval_Enil: eval_exprlist [] []\n| eval_Econs: forall e v le lv,\n  eval_expr e v ->\n  eval_exprlist le lv ->\n  eval_exprlist (e :: le) (v :: lv).\n\nLemma eval_exprlist_app:\n  forall le1 le2 lv1 lv2,\n    eval_exprlist le1 lv1 ->\n    eval_exprlist le2 lv2 ->\n    eval_exprlist (le1 ++ le2) (lv1 ++ lv2).\nProof.\n  intros. revert lv1 H. induction le1.\n  + intros. inversion_clear H. apply H0.\n  + intros. inversion_clear H. simpl.\n    specialize (IHle1 _ H2). apply eval_Econs; assumption.\nQed.\n\nEnd EXPR.\n\n\nSection STATEMENT.\n\nInductive cont : Type :=\n| Kstop: cont\n| Kseq: stmt -> cont -> cont\n| Kreturnto: option ident -> env -> function -> cont -> cont\n| Kloop: stmt -> cont -> cont.\n\nInductive state : Type :=\n| State\n    (m: mem)\n    (e: env)\n    (f: function)\n    (s: stmt)\n    (k: cont) : state\n| Callstate\n    (m:    mem)\n    (fd:   fundef)\n    (args: list value)\n    (k:    cont) : state\n| Returnstate\n    (m:   mem)\n    (res: value)\n    (k:   cont) : state.\n\nInductive eval_identlist (e: env) (f: function): list ident -> list value -> Prop :=\n| eval_ident_Enil: eval_identlist e f [] []\n| eval_ident_Econs: forall id v lids lv t,\n  e!id = Some v ->\n  f.(fn_tenv)!id = Some t ->\n  well_typed_value v t ->\n  eval_identlist e f lids lv ->\n  eval_identlist e f (id :: lids) (v :: lv).\n\nFixpoint destructCont (k: cont) : cont :=\n  match k with\n  | Kseq _ k | Kloop _ k => destructCont k\n  | _ => k\n  end.\n\nDefinition is_Kreturnto (k: cont) :=\n  match k with\n  | Kreturnto _ _ _ _ => True\n  | _ => False\n  end.\n\nInductive step_stmt: state -> state -> Prop :=\n(* Sskip *)\n| step_skip: forall m e f s k,\n  step_stmt (State m e f Sskip (Kseq s k)) (State m e f s k)\n| step_skip_loop: forall m e f s k,\n  step_stmt (State m e f Sskip (Kloop s k)) (State m e f (Sloop s) k)\n| step_skip_returnto: forall m e f k,\n  is_Kreturnto k ->\n  well_typed_value Vunit f.(fn_sig).(sig_res) ->\n  step_stmt (State m e f Sskip k)\n            (Returnstate m Vunit k)\n(* Sassign *)\n| step_assign: forall m e f k id exp v,\n  eval_expr m e f exp v ->\n  step_stmt (State m e f (Sassign id exp) k) (State m (PTree.set id v e) f Sskip k)\n(* Sarr_assign *)\n| step_arr_assign: forall m e f k id idx exp idarr lv blk i v v' szvar n t m' e',\n  e!id = Some (Varr idarr lv) ->\n  eval_expr m e f idx (Vint64 Unsigned i) ->\n  In (id, szvar) f.(fn_arrszvar) ->\n  e!szvar = Some (Vint64 Unsigned n) ->\n  Int64.unsigned i < Int64.unsigned n ->\n  eval_expr m e f exp v ->\n  f.(fn_tenv)!id = Some (Tarr true t) ->\n  well_typed_value v t ->\n  sem_cast v t t = Some v' ->\n  m!idarr = Some blk ->\n  blk.(blk_type) = t ->\n  blk.(blk_values) = lv ->\n  write_array m e id (Int64.unsigned i) v' = Some (m', e') ->\n  step_stmt (State m e f (Sarr_assign id idx exp) k) (State m' e f Sskip k)\n(* Scall *)\n| step_call_internal: forall m e f k idvar idf args vargs vargs' f',\n  ge!idf = Some (Internal f') ->\n  valid_call m e f (Internal f') args ->\n  length args = length f'.(fn_sig).(sig_args) ->\n  match_sig_args_typ f.(fn_tenv) f'.(fn_sig).(sig_args) args ->\n  eval_identlist e f args vargs ->\n  check_cast_args vargs f'.(fn_sig).(sig_args) = Some vargs' ->\n  step_stmt (State m e f (Scall idvar idf args) k)\n            (Callstate m (Internal f') vargs' (Kreturnto idvar e f k))\n| step_call_external: forall m e f k idvar idf args vargs vargs' ef m' v,\n  ge!idf = Some (External ef) ->\n  length args = length (ef_sig ef).(sig_args) ->\n  match_sig_args_typ f.(fn_tenv) (ef_sig ef).(sig_args) args ->\n  eval_identlist e f args vargs ->\n  check_cast_args vargs (ef_sig ef).(sig_args) = Some vargs' ->\n  external_call ef m vargs' v m' ->\n  step_stmt (State m e f (Scall idvar idf args) k)\n            (State m' (set_optenv e idvar v) f Sskip k)\n(* Callstate *)\n| step_call_Internal: forall m fd f vargs k e,\n  fd = Internal f ->\n  build_func_env (PTree.empty value) f.(fn_params) vargs = Some e ->\n  step_stmt (Callstate m fd vargs k) (State m e f f.(fn_body) k)\n(* Sreturn *)\n| step_return: forall m e f k exp v v',\n  eval_expr m e f exp v ->\n  well_typed_value v f.(fn_sig).(sig_res) ->\n  sem_cast v f.(fn_sig).(sig_res) f.(fn_sig).(sig_res) = Some v' ->\n  step_stmt (State m e f (Sreturn exp) k)\n            (Returnstate m v' (destructCont k))\n(* Returnstate *)\n| step_returnstate_noident: forall m v e f k,\n  step_stmt (Returnstate m v (Kreturnto None e f k))\n            (State m e f Sskip k)\n| step_returnstate: forall m v id e f k,\n  step_stmt (Returnstate m v (Kreturnto (Some id) e f k))\n            (State m (PTree.set id v e) f Sskip k)\n(* Sseq *)\n| step_seq: forall m e f k s1 s2,\n  step_stmt (State m e f (Sseq s1 s2) k) (State m e f s1 (Kseq s2 k))\n(* Sifthenelse *)\n| step_ifthenelse: forall m e f k cond b s1 s2,\n  eval_expr m e f cond (Vbool b) ->\n  step_stmt (State m e f (Sifthenelse cond s1 s2) k) (State m e f (if b then s1 else s2) k)\n(* Sloop *)\n| step_loop: forall m e f s k,\n  step_stmt (State m e f (Sloop s) k) (State m e f s (Kloop s k))\n(* Sbreak *)\n| step_break_skip: forall m e f s k,\n  step_stmt (State m e f Sbreak (Kseq s k)) (State m e f Sbreak k)\n| step_break_loop: forall m e f s k,\n  step_stmt (State m e f Sbreak (Kloop s k)) (State m e f Sskip k)\n(* Scontinue *)\n| step_continue_skip: forall m e f s k,\n  step_stmt (State m e f Scontinue (Kseq s k)) (State m e f Scontinue k)\n| step_continue_loop: forall m e f s k,\n  step_stmt (State m e f Scontinue (Kloop s k)) (State m e f (Sloop s) k)\n(* Serror *)\n| step_error: forall m e f k,\n  step_stmt (State m e f Serror k) (State m e f Serror k).\n\nInductive reachable_state (s: state): state -> Prop :=\n| RS_id: reachable_state s s\n| RS_step: forall s1 s2,\n    step_stmt s s1 ->\n    reachable_state s1 s2 ->\n    reachable_state s s2.\n\nLemma reachable_state_one_step (s1 s2: state):\n  step_stmt s1 s2 ->\n  reachable_state s1 s2.\nProof.\n  intros. apply (RS_step _ s2). exact H. apply RS_id.\nQed.\n\nEnd STATEMENT.\n\nInductive initial_state (p: program) : state -> Prop :=\n| initial_state_intro: forall f,\n  (genv_of_program p) ! (prog_main p) = Some (Internal f) ->\n  f.(fn_sig) = {| sig_args := []; sig_res := Tint I32 Signed |} ->\n  initial_state p (Callstate empty_mem (Internal f) [] Kstop).\n\nInductive final_state : state -> int -> Prop :=\n| final_state_intro: forall m sz sig i,\n  final_state (Returnstate m (Vint sz sig i) Kstop) i.\n\nEnd SEMANTICS.\n\nSection COMPCERT_SEMANTICS.\n\nDefinition step_events (ge: genv) (st1: state) (t: Events.trace) (st2: state): Prop :=\n  t = Events.E0 /\\ step_stmt ge st1 st2.\n\nDefinition to_AST_globdef (l: list (ident * fundef)) : list (ident * CAST.globdef fundef typ):=\n  map (fun x => (fst x, CAST.Gfun (snd x))) l.\n\nDefinition to_genv (prog_defs: list (ident * fundef)) : Genv.t fundef typ :=\n  Genv.add_globals (Genv.empty_genv fundef typ (map fst prog_defs)) (to_AST_globdef prog_defs).\n\nDefinition semantics p :=\n  Semantics_gen step_events (initial_state p) final_state (genv_of_program p) (to_genv p.(prog_defs)).\n\nEnd COMPCERT_SEMANTICS.\n\n\nCreate HintDb semantics.\nGlobal Hint Constructors eval_expr eval_exprlist eval_identlist : semantics.\nGlobal Hint Constructors step_stmt reachable_state : semantics.\nGlobal Hint Resolve eval_exprlist_app : semanticsnb.\nGlobal Hint Resolve reachable_state_one_step : semantics.\n\nInductive valid_cont (ge: genv) (f: function): cont -> Prop :=\n| valid_Kstop:\n  valid_cont ge f Kstop\n| valid_Kseq: forall s k,\n  valid_stmt ge f s ->\n  valid_cont ge f k ->\n  valid_cont ge f (Kseq s k)\n| valid_Kloop: forall s k,\n  valid_stmt ge f (Sloop s) ->\n  valid_cont ge f k ->\n  valid_cont ge f (Kloop s k)\n| valid_Kreturnto: forall id e' f' k,\n  valid_cont ge f' k ->\n  valid_cont ge f (Kreturnto id e' f' k).\n", "meta": {"author": "josuemoreau", "repo": "stage-M2-JFLA", "sha": "b5c3370d0c0c9c4f4e9a9b9d8558db6a605c1f3a", "save_path": "github-repos/coq/josuemoreau-stage-M2-JFLA", "path": "github-repos/coq/josuemoreau-stage-M2-JFLA/stage-M2-JFLA-b5c3370d0c0c9c4f4e9a9b9d8558db6a605c1f3a/SemanticsBlocking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22884559723156375}}
{"text": "Require Import VST.floyd.functional_base VST.floyd.proofauto.\nRequire Import VST.floyd.library.\nRequire Import indices.stringlist.\nRequire Import indices.unordered_interface.\nRequire Import indices.unordered_flat.\nRequire Import indices.verif_stringlist.\nRequire Import indices.definitions.\n\nImport UnorderedIndex.\n\nLemma in_whole_in_fst: forall a l,\n  SetoidList.InA (stringlist_model.Raw.PX.eqk (elt:=V)) a l -> In (fst a) (map fst l).\nProof. \n  intros. induction l.\n  - inversion H; inversion H0; inversion H2.\n  - simpl. apply SetoidList.InA_cons in H. inversion H; clear H.\n     + left. destruct a, a0. inversion H0. simpl in H. subst. auto.\n     + right. auto.\nQed. \n\nLemma notin_whole_notin_fst:  forall a l,\n   ~SetoidList.InA (stringlist_model.Raw.PX.eqk (elt:=V)) a l -> ~In (fst a) (map fst l).\nProof.\n  intros. induction l.\n  - unfold not. intros. inversion H0.\n  - simpl.\n     rewrite SetoidList.InA_cons in H.\n     apply Classical_Prop.not_or_and in H.\n     apply Classical_Prop.and_not_or. split.\n     + inversion H; clear H. \n        unfold stringlist_model.Raw.PX.eqk in H0. auto.\n     + inversion H; clear H. auto.\nQed.\n\nLemma lstnodup: forall lst, NoDup (map fst (stringlist_model.elements (elt:=V) lst)).\nProof. \n  intros. assert \n  (K: SetoidList.NoDupA (stringlist_model.Raw.PX.eqk (elt:=V)) (stringlist_model.this lst)).\n  apply stringlist_model.NoDup.\n  assert (M: (stringlist_model.this lst) = (stringlist_model.elements (elt:=V) lst)) by auto.\n  rewrite M in K. clear M.\n  induction (stringlist_model.elements (elt:=V) lst); auto.\n  - simpl. apply NoDup_nil.\n  - simpl. inversion K; subst. apply IHl in H2.\n     apply NoDup_cons; auto. clear H2 K IHl.\n     apply notin_whole_notin_fst. auto.\nQed.\n\nDefinition stringlist_index : index :=\n  {| key := stringlist_model.key;\n     eq_dec_key := Str_as_DT.eq_dec;\n     default_key := \"\"%string;\n     key_repr := fun sh s p => string_rep s p;\n     key_type := tschar;\n\n     default_value := nullV;\n\n     t := stringlist_model.t V;\n     t_repr := fun sh lst p => stringlist_rep lst p;\n     t_type := t_stringlist;\n     \n     create := stringlist_model.empty V;\n\n     cursor_repr := fun mc p => stringlist_cursor_rep mc p;\n\n     flatten := fun lst => mk_flat _  (stringlist_model.elements (elt:=V) lst) (lstnodup lst);\n     \n     insert := fun t k v => stringlist_model.add k v t;\n\n   |}.\n\nDefinition create_funspec := create_spec(stringlist_index).\nDefinition stringlist_create_spec := (_stringlist_new, create_funspec).\n\nDefinition lookup_funspec := lookup_spec(stringlist_index).\nDefinition stringlist_lookup_spec := (_stringlist_lookup, lookup_funspec).\n\nDefinition insert_funspec := insert_spec(stringlist_index).\nDefinition stringlist_insert_spec := (_stringlist_insert, insert_funspec).\n\nDefinition malloc_funspec := malloc_spec'.\nDefinition malloc_spec := (_malloc, malloc_funspec).\n\nDefinition exit_funspec := exit_spec'.\nDefinition exit_spec := (_exit, exit_funspec).\n\nDefinition cardinality_funspec := cardinality_spec(stringlist_index).\nDefinition stringlist_cardinality_spec := (_stringlist_cardinality, cardinality_funspec).\n\nDefinition move_to_first_funspec := move_to_first_spec(stringlist_index).\nDefinition stringlist_move_to_first_spec := (_stringlist_move_to_first, move_to_first_funspec).\n\nDefinition move_to_next_funspec := move_to_next_spec(stringlist_index).\nDefinition stringlist_move_to_next_spec := (_stringlist_move_to_next, move_to_next_funspec).\n\nDefinition get_cursor_funspec := get_cursor_spec(stringlist_index).\nDefinition stringlist_get_cursor_spec := (_stringlist_get_cursor, get_cursor_funspec).\n\nDefinition Gprog : funspecs := [ new_scell_spec; strcmp_spec; malloc_spec;\n    exit_spec; stringlist_create_spec; stringlist_lookup_spec; stringlist_insert_spec;\n    stringlist_cardinality_spec; stringlist_move_to_first_spec;\n    stringlist_move_to_next_spec; stringlist_get_cursor_spec].\n\n(* ==================== HELPERS ==================== *)\n\nDefinition strlst_rep (add: val) (cellptr: val) (lst: list(string*V)) :=\n  (data_at Ews (tptr t_scell) cellptr add * scell_rep lst cellptr)%logic.\n\nLemma not_stringlist_raw_in_inv :\n  forall (elt : Type) (k k' : string) (e : elt) (l : list (string * elt)),\n  ~stringlist_model.Raw.PX.In k ((k', e) :: l) -> ~(k = k' \\/ stringlist_model.Raw.PX.In k l).\nProof.\n  intros. \n  unfold not. intros. apply H. inversion H0.\n  - rewrite H1 in H. unfold not in H. unfold stringlist_model.Raw.PX.In in H.\n     exfalso. apply H. exists e. auto.\n  - exfalso. unfold not in H. apply H. unfold stringlist_model.Raw.PX.In in *.\n     inversion H1. exists x. auto.\nQed.\n\nLemma notin_lst_add_end: forall lst k (v: V),\n  ~stringlist_model.Raw.PX.In k lst ->\n  lst ++ [(k, v)] = stringlist_model.Raw.add k v lst.\nProof.\n  intros. induction lst; try auto.\n  simpl. destruct a. apply not_stringlist_raw_in_inv in H.\n  apply Decidable.not_or in H. inversion H; clear H.\n  destruct (Str_as_DT.eq_dec k s); try contradiction.\n  apply IHlst in H1. rewrite H1. auto.\nQed.\n\nLemma notin_lst_add_middle: forall lst1 lst2 k (v: V) (v0: V),\n  ~stringlist_model.Raw.PX.In k lst1 ->\n  lst1 ++ (k, v) :: lst2 = stringlist_model.Raw.add k v (lst1 ++ (k, v0) :: lst2).\nProof.\n  intros. induction lst1.\n  - simpl. destruct (Str_as_DT.eq_dec k k); try auto.\n     unfold not in n. unfold Str_as_DT.eq in n. contradiction.\n  - simpl. destruct a. apply not_stringlist_raw_in_inv in H.\n     apply Decidable.not_or in H. inversion H; clear H.\n     destruct (Str_as_DT.eq_dec k s); try contradiction.\n     apply IHlst1 in H1. rewrite H1. auto.\nQed.\n\nRequire Import Coq.Program.Equality. \nLemma stringlistfind_eq_find: forall m k,\n  find Str_as_DT.eq_dec (stringlist_model.elements (elt:=V) m) k =\n  stringlist_model.find (elt:=V) k m.\nProof.\n  intros. unfold stringlist_model.find. unfold stringlist_model.Raw.find. unfold stringlist_model.Raw.t.\n  replace (stringlist_model.this m) with (stringlist_model.elements (elt:=V) m); auto.\n  induction (stringlist_model.elements (elt:=V) m); auto.\n  destruct a. simpl. destruct (Str_as_DT.eq_dec k0 k).\n     + unfold Str_as_DT.eq in e. subst. destruct (Str_as_DT.eq_dec k k); auto.\n         unfold Str_as_DT.eq in n. contradiction.\n     + destruct (Str_as_DT.eq_dec k k0). unfold Str_as_DT.eq in e.\n         unfold Str_as_DT.eq in n. symmetry in e. contradiction.\n         auto.\nQed.\n\nLemma find_middle: forall s lst1 lst2 v, ~ In s (map fst lst1 ++ map fst lst2) -> \n                          @find stringlist_model.key V Str_as_DT.eq_dec (lst1 ++ (s, v) :: lst2) s = Some v.\nProof. \n  induction lst1, lst2; intros.\n  - simpl. destruct (Str_as_DT.eq_dec s s); auto. unfold Str_as_DT.eq in n. contradiction.\n  - simpl. destruct (Str_as_DT.eq_dec s s); auto. unfold Str_as_DT.eq in n. contradiction.\n  - remember [] as k. simpl in H. apply Decidable.not_or in H. inversion H; clear H.\n     rewrite Heqk in H1.\n     eapply (IHlst1 [] v) in H1. simpl.  destruct a. simpl in H0.\n     destruct (Str_as_DT.eq_dec k0 s); auto. contradiction. subst. eapply H1.\n  - remember (p :: lst2) as k. simpl in H. apply Decidable.not_or in H. inversion H; clear H.\n     eapply (IHlst1 k v) in H1. simpl. destruct a. simpl in H0.\n     destruct (Str_as_DT.eq_dec k0 s); auto. contradiction.\nQed.\n\nLemma find_add: forall k v m,\n  @find stringlist_model.key V Str_as_DT.eq_dec (stringlist_model.Raw.add k v (stringlist_model.this m)) k = Some v.\nProof. \n  intros. induction (stringlist_model.this m).\n  - simpl. destruct (Str_as_DT.eq_dec k k); auto. unfold not in n. \n     unfold Str_as_DT.eq in n. contradiction.\n  - simpl. destruct a. destruct (Str_as_DT.eq_dec k s).\n     + simpl. destruct (Str_as_DT.eq_dec k k); auto.\n        unfold not in n. unfold Str_as_DT.eq in n. contradiction.\n     + simpl. destruct (Str_as_DT.eq_dec s k). exfalso; apply n; auto.\n        rewrite IHt0. auto.\nQed.\n\nLemma list_byte_neq: forall s str, \n  string_to_list_byte s <> string_to_list_byte str -> s <> str.\nProof.\n  intros. generalize dependent str. induction s.\n  - unfold not. intros. apply H. apply list_byte_eq in H0. auto.\n  - unfold not. intros. apply H. apply list_byte_eq. auto.\nQed.\n\nLemma notin_cons: forall k lst k0 (v0: V),\n  ~ stringlist_model.Raw.PX.In k lst ->\n  k0 <> k ->\n  ~ stringlist_model.Raw.PX.In k (lst ++ [(k0, v0)]).\nProof.\n  intros. destruct lst.\n  - simpl. unfold stringlist_model.Raw.PX.In. unfold not. intros.\n     inversion H1. inversion H2; subst.\n     + inversion H4. simpl in H3. symmetry in H3. contradiction.\n     + inversion H4.\n  - simpl. unfold stringlist_model.Raw.PX.In. unfold not. intros.\n     inversion H1; clear H1. inversion H2; subst.\n     + inversion H3. destruct p; simpl in *; subst. apply H.\n         unfold stringlist_model.Raw.PX.In. exists v. auto.\n     + clear H3.\n         apply H. unfold stringlist_model.Raw.PX.In. exists x.\n         unfold stringlist_model.Raw.PX.MapsTo in *.\n         apply \n         (@SetoidList.InA_app _ (stringlist_model.Raw.PX.eqke (elt:=V)) (p::lst) ([(k0,v0)]) (k, x)) \n         in H2. inversion H2; clear H2; auto.\n         unfold not in H0. inversion H1; subst; inversion H3; subst; simpl in *.\n         symmetry in H2. contradiction.\nQed.\n\nLemma data_at_stringlist_ptr: forall cell_ptr p,\n  data_at Ews t_stringlist cell_ptr p |-- data_at Ews (tptr t_scell) cell_ptr p.\nProof. \n  intros. unfold_data_at (data_at _ _ _ p). rewrite field_at_data_at.\n  unfold field_address. if_tac; simpl; auto.\n  * entailer!.\n  * entailer!. apply field_compatible_isptr in H0. inversion H0.\nQed.\n\n(* ==================== GET CURSOR ==================== *)\n\nDefinition undef_cursor (p vret : val) : mpred :=\n  (malloc_token Ews t_cursor vret * data_at Ews t_cursor (p, Vundef) vret)%logic. \n\nLemma body_stringlist_get_cursor: semax_body Vprog Gprog \n    f_stringlist_get_cursor stringlist_get_cursor_spec.\nProof.\n  unfold stringlist_get_cursor_spec. unfold get_cursor_funspec.\n  unfold get_cursor_spec. start_function.\n  simpl. Intros. forward. forward_call (t_cursor, gv).\n  { split; try auto; try omega. simpl. easy. }\n  { Intros vret. autorewrite with norm. \n    forward_if (vret <> nullval). if_tac; entailer!.\n    { rewrite if_true by auto. forward_call 1. entailer!. }\n    { forward. entailer!. }\n    { Intros. rewrite if_false by auto. Intros. forward.\n      simpl. \n      forward_loop \n      (EX lst1: list (string * V), EX lst2: list (string * V), EX p0: val,\n      PROP( lst1 ++ lst2 = stringlist_model.elements m /\\ \n                not (stringlist_model.Raw.PX.In k lst1)) \n      LOCAL(temp _mc vret; temp _cur (Vptrofs(Ptrofs.repr(Zlength(lst1)))); \n                 gvars gv; temp _p p; temp _key q; temp _q p0)\n      SEP(mem_mgr gv;\n            stringlist_hole_rep lst2 m p p0 * string_rep k q *\n            undef_cursor p vret))\n      (* break cond *)\n      break: \n      (EX lst2: list (string * V), EX p0: val, PROP ( )\n      LOCAL (temp _mc vret; temp _cur (Vlong (Int64.repr 0)); \n                  gvars gv; temp _p p; temp _key q; temp _q p0)\n      SEP (mem_mgr gv; stringlist_hole_rep lst2 m p p0; \n             string_rep k q; undef_cursor p vret)).\n      { unfold stringlist_rep. Intros cell_ptr. forward.\n        Exists (@nil (string * V)) (stringlist_model.elements m).\n        Exists cell_ptr.\n        unfold stringlist_hole_rep.\n        Exists cell_ptr. autorewrite with sublist. entailer!.\n        { inversion H8. inversion H9. }\n        { unfold undef_cursor.  cancel. apply wand_refl_cancel_right. }}\n      { Intros lst1 lst2 p0. forward_if (p0 <> nullval).\n        { unfold stringlist_hole_rep. Intros cell_ptr. entailer!. }\n        { forward. entailer!. }\n        { forward. Exists lst2 p0. entailer!. admit. }\n        { destruct lst2.\n          { unfold stringlist_hole_rep. Intros cell_ptr.\n            unfold scell_rep; fold scell_rep. Intros. contradiction. }\n          { unfold stringlist_hole_rep. Intros cell_ptr. destruct p1.\n            unfold scell_rep at 1; fold scell_rep. Intros q0 str_ptr.\n            forward. \n            forward_call (str_ptr, string_to_list_byte s, q, string_to_list_byte k).\n            { unfold cstring. unfold string_rep.\n              repeat rewrite length_string_list_byte_eq. cancel. }\n            Intros vret0. forward_if. destruct Int.eq_dec in H3.\n            { unfold undef_cursor. Intros. forward. forward.\n              Exists vret. unfold cursor. Exists (m, 0). entailer!.\n              simpl t_repr. simpl key_repr. simpl cursor_repr.\n              unfold string_rep. unfold cstring at 2. repeat rewrite length_string_list_byte_eq.\n              cancel. unfold stringlist_rep. Exists cell_ptr. cancel.\n              unfold stringlist_cursor_rep. Exists p. cancel.\n              apply wand_sepcon_adjoint.\n              assert (K: (cstring Ews (string_to_list_byte s) str_ptr * malloc_token Ews t_scell p0 *\n                 data_at Ews t_scell (str_ptr, (V_repr v, q0)) p0 *\n                 malloc_token Ews (tarray tschar (Zlength (string_to_list_byte s) + 1)) str_ptr *\n                 scell_rep lst2 q0)%logic |-- \n                 scell_rep ((s, v) :: lst2) p0).\n                 { unfold scell_rep at 2; fold scell_rep. Exists q0 str_ptr.\n                   unfold cstring. unfold string_rep. rewrite length_string_list_byte_eq.\n                   cancel. }\n              sep_apply K. apply wand_sepcon_adjoint. admit. \n              (* apply modus_ponens_wand. *) }\n            { unfold not in n. contradiction. }\n            { forward. forward. Exists (lst1 ++ [(s, v)]) lst2. Exists q0.\n              entailer!. \n              { repeat split. \n                 { rewrite <- H0. rewrite app_assoc_reverse. simpl. auto. }\n                 { destruct (Int.eq_dec vret0 Int.zero) in H3.\n                   contradiction. unfold not. intros. unfold stringlist_model.Raw.PX.In in H15. \n                   unfold stringlist_model.Raw.PX.In in H1. unfold not in H1.\n                   unfold stringlist_model.Raw.PX.MapsTo in H15. inversion H15. \n                   rewrite SetoidList.InA_app_iff in H16. inversion H16.\n                   { unfold stringlist_model.Raw.PX.MapsTo in H1. apply H1. exists x. auto. }\n                   { inversion H17. inversion H19. simpl in H21. rewrite H21 in H3. \n                      contradiction. inversion H19. }}\n                   { admit. }}\n               { admit. }}}}}\n      { Intros lst2 p0. unfold undef_cursor. Intros. forward. forward.\n        Exists vret (m, 0). entailer!. simpl. cancel. unfold stringlist_cursor_rep.\n        Exists p. cancel. unfold stringlist_hole_rep. Intros cell_ptr.\n        unfold stringlist_rep at 1. Exists cell_ptr. cancel. admit.\n        (* apply modus_ponens_wand. *)  } \n\n(* need to fix the double definition of stringlist and also the cursor number *)\nAdmitted.\n\n\n\n(* ==================== MOVE TO NEXT ==================== *)\n\nLemma body_stringlist_move_to_next: semax_body Vprog Gprog \n    f_stringlist_move_to_next stringlist_move_to_next_spec.\nProof. \n  unfold stringlist_move_to_next_spec. unfold move_to_next_funspec.\n  unfold move_to_next_spec. start_function. \n  forward. simpl. unfold stringlist_cursor_rep. Intros strlst_p.\n  sep_apply stringlist_rep_local_facts.\n  simpl. forward.\n  forward. forward_call (sh, strlst_p, m).\n    { simpl. entailer!. }\n    { forward. autorewrite with norm.\n      remember (Int64.repr (prevcur + 1)) as nextcur.\n      remember (Int64.repr (Zlength (elements (flatten stringlist_index m)))) as length.\n      remember (Int64.ltu nextcur length) as cond1.\n      remember (Int64.ltu (Int64.repr 0) nextcur) as cond2.\n      remember (andb cond1 cond2) as condition.\n      forward_if\n        (PROP ( )\n        LOCAL (temp _cur (Vlong nextcur);\n                    temp _length (Vlong length); temp _lst strlst_p; \n                    temp _mc p; temp _mcc p; temp _t'2 (if condition then Vtrue else Vfalse))\n        SEP (t_repr stringlist_index sh m strlst_p; mem_mgr gv;\n               malloc_token Ews t_cursor p;\n               data_at Ews t_cursor (strlst_p, Vlong (Int64.repr prevcur)) p)).\n      { forward. entailer!. unfold cardinality in H.\n        rewrite H. simpl. unfold Val.of_bool. auto. }\n      { forward. entailer!. unfold cardinality in H. rewrite H. simpl. auto. }\n      { forward_if\n        (PROP ( )\n        LOCAL (temp _cur (Vlong nextcur); temp _length (Vlong length);\n                    temp _lst strlst_p; temp _mc p; temp _mcc p;\n                    temp _t'2 (if condition then Vtrue else Vfalse))\n        SEP (mem_mgr gv;\n         cursor_repr stringlist_index\n           (move_to_next stringlist_index (m, prevcur)) p)).\n      destruct condition.\n        { forward. entailer!.\n          assert (K: (move_to_next stringlist_index (m, prevcur)) = (m, prevcur+1)).\n          { simpl in *. rewrite <- Heqcondition. auto. }\n          rewrite K. simpl. unfold stringlist_cursor_rep.\n          Exists strlst_p. entailer!. }\n        { inversion H. }\n        { forward. entailer!. \n          assert (K: (move_to_next stringlist_index (m, prevcur)) = (m, 0)).\n          { simpl in *. rewrite H. auto. }\n          rewrite K. simpl. unfold stringlist_cursor_rep.\n          Exists strlst_p. entailer!. } \n       forward. Exists p. entailer!. }}\nQed.\n\n\n(* ==================== MOVE TO FIRST ==================== *)\n\nLemma body_stringlist_move_to_first: semax_body Vprog Gprog \n    f_stringlist_move_to_first stringlist_move_to_first_spec.\nProof. \n  unfold stringlist_move_to_first_spec. unfold move_to_first_funspec.\n  unfold move_to_first_spec. start_function. \n  forward. simpl. unfold stringlist_cursor_rep. Intros strlst_p.\n  simpl.\n  forward. forward. Exists p. simpl. unfold stringlist_cursor_rep.\n  entailer!. Exists strlst_p. simpl. entailer!.\nQed.\n\n\n(* ================== CARDINALITY ================== *)\n\n\nLemma body_stringlist_cardinality: semax_body Vprog Gprog \n    f_stringlist_cardinality stringlist_cardinality_spec.\nProof. \n  unfold stringlist_cardinality_spec. unfold cardinality_funspec.\n  unfold cardinality_spec. start_function. \n  forward. simpl. unfold stringlist_rep. Intros cell_ptr.\n  simpl in m.  \n  (* invariant *)\n   forward_loop \n  (EX lst1: list (string * V), EX lst2: list (string * V), EX p0: val,\n  PROP( lst1 ++ lst2 = stringlist_model.elements m) \n  LOCAL(temp _q p0; temp _size (Vptrofs (Ptrofs.repr (Zlength(lst1)))); temp _p p)\n  SEP(stringlist_hole_rep lst2 m p p0))\n  (* break cond *)\n  break: \n  (PROP () \n  LOCAL(temp _size (Vptrofs (Ptrofs.repr (Zlength(stringlist_model.elements m)))))\n  SEP((stringlist_rep m p))).\n  (* holds on entry *)\n  - forward.\n     Exists (@nil (string * V)) (stringlist_model.elements m) cell_ptr.\n     entailer!. unfold stringlist_hole_rep. Exists cell_ptr. entailer!.\n     apply wand_refl_cancel_right.\n  (* holds on iteration *)\n  - Intros lst1 lst2 p0. unfold stringlist_hole_rep.\n     Intros cp0. forward_if (p0 <> nullval).\n     { forward. entailer!. }\n     { forward. autorewrite with norm. \n       entailer!.\n       { assert (K: nullval = nullval) by auto.  apply H4 in K.\n         subst. rewrite <- H. autorewrite with sublist. auto. }\n       unfold stringlist_rep. Exists cp0.\n       cancel. apply modus_ponens_wand. }\n      { forward. autorewrite with norm. destruct lst2.\n        (* lst2 empty *)\n       { unfold scell_rep; fold scell_rep. Intros. contradiction. }\n         (* lst2 not empty *)\n       { destruct p1.\n         unfold scell_rep at 1; fold scell_rep. Intros q0 str_ptr.\n         forward. entailer!.\n         Exists (lst1 ++ [(s,v)]) lst2 q0. entailer!.\n         split.\n         { rewrite app_assoc_reverse. simpl. auto. }\n         { f_equal. f_equal. rewrite Zlength_app. easy. }\n         unfold stringlist_hole_rep. Exists cp0. \n         entailer!. apply wand_frame_intro'.\n         apply wand_sepcon_adjoint. apply wand_frame_intro'. \n         assert (W: (malloc_token Ews t_scell p0 * \n                         data_at Ews t_scell (str_ptr, (V_repr v, q0)) p0 *\n                         string_rep s str_ptr *\n                         malloc_token Ews (tarray tschar (Z.of_nat (length s) + 1)) str_ptr * \n                         scell_rep lst2 q0)%logic |-- scell_rep ((s, v) :: lst2) p0).\n         { unfold scell_rep at 2; fold scell_rep. Exists q0 str_ptr. cancel. }\n         sep_apply W. sep_apply modus_ponens_wand. cancel. }}\n - autorewrite with norm. forward. \nQed.\n\n\n\n(* ==================== LOOKUP ==================== *)\n\nLemma body_stringlist_lookup: semax_body Vprog Gprog \n    f_stringlist_lookup stringlist_lookup_spec.\nProof. unfold stringlist_lookup_spec. unfold lookup_funspec. unfold lookup_spec.\n  start_function. simpl. remember m as lst. remember k as str.\n  (* loop invariant *)\n  forward_loop \n  (EX lst1: list (string * V), EX lst2: list (string * V), EX p0: val,\n  PROP( lst1 ++ lst2 = stringlist_model.elements lst /\\ not (stringlist_model.Raw.PX.In str lst1)) \n  LOCAL(temp _q p0; temp _key q)\n  SEP(mem_mgr gv; stringlist_hole_rep lst2 lst p p0 * string_rep str q))\n  (* break cond *)\n  break: \n  (PROP (nullval = proj1_sig (lookup stringlist_index m k)) \n  LOCAL()\n  SEP((mem_mgr gv * stringlist_rep lst p * string_rep str q))).\n (* invariant holds entering loop*) \n  - unfold stringlist_rep. Intros cell_ptr. forward. \n     Exists (@nil (string * V)) (stringlist_model.elements lst).\n     Exists cell_ptr.\n     unfold stringlist_hole_rep.\n     Exists cell_ptr. autorewrite with sublist. entailer!.\n     { inversion H4. inversion H5. }\n     { apply wand_refl_cancel_right. }\n  (* invariant holds in the loop *)\n  - Intros lst1 lst2 p0. forward_if (p0 <> nullval).\n    { unfold stringlist_hole_rep. Intros cell_ptr. entailer!. }\n    { forward. entailer!. }\n    { (* break inv used *) unfold stringlist_hole_rep. Intros cell_ptr.\n      rewrite H1.  forward. entailer!.\n      { assert (K: nullval = nullval). auto. apply H5 in K. \n        subst. autorewrite with sublist in H.\n        rewrite H in H0. replace (lookup stringlist_index m k) with nullV; auto.\n        unfold lookup. simpl. simpl in k. simpl in m. apply notin_lst_find_none in H0.\n        assert \n        (P: @find stringlist_model.key V Str_as_DT.eq_dec (stringlist_model.elements (elt:=V) m) k = None).\n        { rewrite <- H0.\n          apply stringlistfind_eq_find. }\n          rewrite P; auto. }\n        { unfold stringlist_rep. Exists cell_ptr. cancel.\n         apply modus_ponens_wand. }}\n    { destruct lst2. \n        (* lst2 empty *)\n       { unfold stringlist_hole_rep. Intros cell_ptr.\n         unfold scell_rep; fold scell_rep. Intros. contradiction. }\n         (* lst2 not empty *)\n       { unfold stringlist_hole_rep. Intros cell_ptr. destruct p1.\n         unfold scell_rep at 1; fold scell_rep. Intros q0 str_ptr.\n         forward. \n         forward_call (str_ptr, string_to_list_byte s, q, string_to_list_byte str).\n         { unfold cstring. unfold string_rep.\n           repeat rewrite length_string_list_byte_eq. cancel. }\n         Intros vret. forward_if.\n         { destruct (Int.eq_dec vret Int.zero) in H2.\n           { forward.\n              { unfold V in v. entailer!.\n                destruct v. auto. }\n              { forward. entailer!.\n                { assert (M: lookup stringlist_index m k = v).\n                  { apply list_byte_eq in H2; rewrite <- H2. unfold lookup. simpl in k. simpl in m.\n                    assert (K: stringlist_model.elements m = (elements (flatten stringlist_index m))) by auto.\n                    rewrite <- K. rewrite <- H. simpl.\n                    assert \n                    (P: @find stringlist_model.key V Str_as_DT.eq_dec (lst1 ++ (s, v) :: lst2) s \n                     = (Some v)).\n                    { assert (W: NoDup (map fst (stringlist_model.elements (elt:=V) m))).\n                      apply lstnodup. rewrite <- H in W. rewrite map_app in W. simpl in W. \n                      apply (@NoDup_remove_2 string (map fst (lst1)) (map fst (lst2)) s) in W.\n                      apply find_middle; auto. }\n                    rewrite P. auto. } rewrite M; simpl; auto. } \n                 simpl t_repr. simpl key_repr. unfold string_rep. unfold cstring at 2. rewrite length_string_list_byte_eq.\n                 cancel. unfold stringlist_rep. Exists cell_ptr. cancel.\n                 apply wand_sepcon_adjoint.\n                 assert (K: (cstring Ews (string_to_list_byte s) str_ptr * malloc_token Ews t_scell p0 *\n                 data_at Ews t_scell (str_ptr, (V_repr v, q0)) p0 *\n                 malloc_token Ews (tarray tschar (Zlength (string_to_list_byte s) + 1)) str_ptr *\n                 scell_rep lst2 q0)%logic |-- \n                 scell_rep ((s, v) :: lst2) p0).\n                 { unfold scell_rep at 2; fold scell_rep. Exists q0 str_ptr.\n                   unfold cstring. unfold string_rep. rewrite length_string_list_byte_eq.\n                   cancel. }\n                  sep_apply K. apply wand_sepcon_adjoint. apply modus_ponens_wand. }}\n           { contradiction. }}\n          { destruct (Int.eq_dec vret Int.zero) in H2.\n            contradiction.\n            abbreviate_semax. forward. Exists (lst1 ++ [(s, v)]) lst2.\n            Exists q0. entailer!.\n            { split.\n              { rewrite <- H. rewrite app_assoc_reverse. simpl. auto. }\n              { unfold not. intros. unfold stringlist_model.Raw.PX.In in H14. \n                unfold stringlist_model.Raw.PX.In in H0. unfold not in H0.\n                unfold stringlist_model.Raw.PX.MapsTo in H14. inversion H14. \n                rewrite SetoidList.InA_app_iff in H15. inversion H15.\n                { unfold stringlist_model.Raw.PX.MapsTo in H0. apply H0. exists x. auto. }\n                { inversion H16. inversion H18. simpl in H20. rewrite H20 in H2. \n                  contradiction. inversion H18. }}}\n             { unfold string_rep. unfold cstring at 2. rewrite length_string_list_byte_eq.\n               cancel. unfold stringlist_hole_rep. Exists cell_ptr. \n               entailer!. apply wand_frame_intro'.\n               apply wand_sepcon_adjoint. apply wand_frame_intro'.\n               assert (K: (cstring Ews (string_to_list_byte s) str_ptr * malloc_token Ews t_scell p0 *\n               data_at Ews t_scell (str_ptr, (V_repr v, q0)) p0 *\n               malloc_token Ews (tarray tschar (Zlength (string_to_list_byte s) + 1)) str_ptr * \n               scell_rep lst2 q0)%logic |-- \n               scell_rep ((s, v) :: lst2) p0).\n               { unfold scell_rep at 2; fold scell_rep. Exists q0 str_ptr.\n                 unfold cstring. unfold string_rep. rewrite length_string_list_byte_eq.\n                 cancel. }\n               sep_apply K. apply modus_ponens_wand. }}}}\n  (* invariant holds after loop *) (* break inv used *)\n  - forward. entailer!. simpl. auto. \nQed.\n  \n\n\n\n\n(* ==================== CREATE ==================== *)\n\nLemma body_stringlist_create: semax_body Vprog Gprog \n    f_stringlist_new stringlist_create_spec.\nProof. \n  unfold stringlist_create_spec. unfold create_funspec.\n  unfold create_spec.\n  start_function. \n  forward_call (t_stringlist, gv).\n  { split3; auto. cbn. computable. }\n  Intros p. \n  forward_if\n    (PROP ( )\n     LOCAL (temp _p p; gvars gv)\n     SEP (mem_mgr gv; malloc_token Ews t_stringlist p * data_at_ Ews t_stringlist p)).\n  { destruct eq_dec; entailer. }\n  { forward_call 1. entailer. }\n  { forward. rewrite if_false by assumption. entailer. }\n  { Intros. forward. forward. Exists p. Exists (stringlist_model.empty V).\n    entailer!. simpl.\n    unfold stringlist_rep. unfold stringlist_model.empty. simpl.\n    Exists  (Vlong (Int64.repr 0)). entailer!. } \nQed.\n\n(* ==================== INSERT ==================== *)\n\n\nLemma body_stringlist_insert: semax_body Vprog Gprog \n    f_stringlist_insert stringlist_insert_spec.\nProof. \n  unfold stringlist_insert_spec. unfold insert_funspec. unfold insert_spec.\n  start_function.\n  simpl. Intros. unfold stringlist_rep. forward.\n  { Intros cell_ptr. rewrite data_at_isptr. entailer!. }\n  remember (offset_val (align 0 (alignof (tptr (Tstruct _scell noattr))))\n               mptr) as r.\n  (* invariant *)\n  forward_loop\n  (EX lst1, EX lst2, EX add,\n  PROP( lst1 ++ lst2 = stringlist_model.elements m /\\ not (stringlist_model.Raw.PX.In k lst1)\n            /\\ field_compatible t_stringlist [StructField _root] mptr) \n  LOCAL(gvars gv; temp _r add; temp _p mptr; temp _key kptr; temp _value (V_repr v)) \n  SEP(mem_mgr gv; string_rep k kptr; malloc_token Ews t_stringlist mptr;\n        EX cp2: val, strlst_rep add cp2 lst2 *\n        (ALL lst', ALL cpnew, EX cp', strlst_rep add cpnew lst' -* \n         strlst_rep mptr cp' (lst1 ++ lst')))).\n  (* invariant holds on entry *)\n  - entailer!. Exists (@nil (string * V)) (stringlist_model.elements m) mptr.\n     simpl. entailer!.\n     { inversion H5. inversion H6. }\n     { Exists cell_ptr. \n       assert (K: data_at Ews t_stringlist cell_ptr mptr |-- data_at Ews (tptr t_scell) cell_ptr mptr).\n       { unfold_data_at (data_at _ _ _ mptr). rewrite field_at_data_at.\n         unfold field_address. if_tac; simpl; auto.\n         * entailer!.\n         * entailer!. apply field_compatible_isptr in H6. inversion H6. }\n       sep_apply K. clear K. unfold strlst_rep at 1. cancel.\n       apply allp_right. intro. apply allp_right. intro. Exists v1.\n       apply wand_refl_cancel_right. }\n  (* invariant holds after *) \n  - Intros lst1 lst2 addr. Intros cellptr2. clear Heqr. unfold strlst_rep at 1. Intros.\n     forward. sep_apply scell_rep_local_facts. forward_if. \n     (* if list empty *)\n     +  rewrite H2. sep_apply string_rep_local_facts. Intros.\n         (* we know 2nd part is empty *)\n         assert (M: nullval = nullval) by auto. \n         apply H4 in M. rewrite M.\n         (* create new cell with (k,v) *) \n         forward_call (gv, kptr, k, v, nullval, (@nil (string * V))).\n         Intros vret. forward. forward. Exists (stringlist_model.add k v m). entailer!. \n         split. \n           { unfold lookup. simpl.\n             rewrite find_add. auto. }\n           { (* prove return null *) unfold lookup. simpl. \n             rewrite stringlistfind_eq_find. assert (W: stringlist_model.find (elt:=V) k m = None).\n             { apply notin_lst_find_none. rewrite <- H. autorewrite with sublist. auto. }\n             rewrite W. auto. }\n           { simpl t_repr. simpl key_repr. unfold stringlist_rep. \n             allp_left [(k, v)]. allp_left vret. Intros cp'. Exists cp'.\n             entailer!.\n             rewrite sepcon_assoc. rewrite sepcon_comm.\n             replace (scell_rep [(k, v)] vret * data_at Ews (tptr t_scell) vret addr)%logic\n             with (strlst_rep addr vret [(k,v)]). sep_apply modus_ponens_wand.\n             replace (@stringlist_model.elements V (@stringlist_model.add V k v m)) with (lst1 ++ [(k, v)]).\n             unfold strlst_rep; entailer!.\n             assert (K: data_at Ews (tptr t_scell) cp' mptr |-- data_at Ews t_stringlist cp' mptr).\n            { (* this is where we need the extra premise of field_compatible *)\n              unfold_data_at (data_at _ t_stringlist _ mptr). rewrite field_at_data_at.\n              unfold field_address. if_tac; simpl; auto.\n              * entailer!. * contradiction. } \n             sep_apply K. clear K. entailer!. \n            { autorewrite with sublist in H. simpl. unfold stringlist_model.elements in H.\n              unfold stringlist_model.Raw.elements in H. rewrite <- H.\n              apply (@notin_lst_add_end lst1 k v) in H0.\n              rewrite <- H0. reflexivity. }\n            { unfold strlst_rep. apply sepcon_comm. }}\n             \n      (* if list nonempty *)\n      + simpl. destruct lst2.\n          { Intros. assert (M: @nil (string * V) = @nil (string * V)); auto.\n            apply H3 in M. contradiction. }\n          { unfold scell_rep; fold scell_rep. destruct p. Intros q str_ptr.\n            forward.\n            forward_call (str_ptr, string_to_list_byte k0, kptr, string_to_list_byte k).\n            { unfold string_rep. unfold cstring. rewrite length_string_list_byte_eq.\n              entailer!. rewrite length_string_list_byte_eq. entailer!. }\n            Intros vret. forward_if.\n            { destruct (Int.eq_dec vret Int.zero); try contradiction.\n              apply list_byte_eq in H4; subst. forward.\n              { entailer!. unfold V in v0. destruct v0. auto. }\n              { forward. forward. Exists (stringlist_model.add k v m).\n                simpl. entailer!.\n                { unfold lookup. simpl. rewrite <- H. simpl in k.\n                  assert \n                  (P: @find stringlist_model.key V Str_as_DT.eq_dec (lst1 ++ (k, v0) :: lst2) k \n                         = (Some v0)).\n                        { assert (W: NoDup (map fst (stringlist_model.elements (elt:=V) m))).\n                          apply lstnodup. rewrite <- H in W. rewrite map_app in W. simpl in W. \n                          apply (@NoDup_remove_2 string (map fst (lst1)) (map fst (lst2)) k) in W.\n                          apply find_middle; auto. }\n                  rewrite P. split; auto. rewrite find_add. auto. }  \n                unfold string_rep. unfold cstring at 2. \n                rewrite length_string_list_byte_eq. cancel.\n                unfold stringlist_rep. \n                unfold strlst_rep. allp_left ((k, v) :: lst2).\n                allp_left cellptr2. Intros cp'. Exists cp'. cancel. \n                assert (M: (cstring Ews (string_to_list_byte k) str_ptr *\n                malloc_token Ews t_scell cellptr2 *\n                data_at Ews t_scell (str_ptr, (V_repr v, q)) cellptr2 * \n                malloc_token Ews (tarray tschar (Zlength (string_to_list_byte k) + 1)) str_ptr *\n                scell_rep lst2 q)%logic\n                |-- scell_rep ((k, v) :: lst2) cellptr2).\n                { unfold scell_rep at 2; fold scell_rep. Exists q str_ptr. \n                  cancel. unfold cstring. unfold string_rep.\n                  rewrite length_string_list_byte_eq. entailer!. }\n                sep_apply M. rewrite sepcon_comm.\n                rewrite sepcon_assoc. \n                remember (data_at Ews (tptr t_scell) cellptr2 addr * \n                scell_rep ((k, v) :: lst2) cellptr2)%logic as P.\n                remember (data_at Ews (tptr t_scell) cp' mptr * \n                scell_rep (lst1 ++ (k, v) :: lst2) cp')%logic as Q.\n                sep_apply wand_frame_elim''. subst Q. clear HeqP.\n                assert (K: data_at Ews (tptr t_scell) cp' mptr  |-- data_at Ews t_stringlist cp' mptr).\n                { unfold_data_at (data_at _ t_stringlist _ mptr). rewrite field_at_data_at.\n                  unfold field_address. if_tac; simpl; auto.\n                  * entailer!. * contradiction. }\n                sep_apply K; clear K; cancel. unfold key. \n                replace (@stringlist_model.elements V (@stringlist_model.add V k v m))\n                with (lst1 ++ (k, v) :: lst2).\n                entailer!. simpl.\n                unfold stringlist_model.elements in H.\n                unfold stringlist_model.Raw.elements in H. clear M. clear P. clear H3. \n                rewrite <- H.\n                apply notin_lst_add_middle. auto. }}\n              { forward. entailer!.\n                Exists (lst1 ++ [(k0,v0)]) lst2 (offset_val 16 cellptr2) q. entailer!.\n                { split.\n                  * rewrite app_assoc_reverse. simpl. rewrite H. auto.\n                  * apply notin_cons. auto. destruct (Int.eq_dec vret Int.zero).\n                    contradiction. apply list_byte_neq in H4.  auto. }\n                unfold cstring at 2. unfold string_rep.\n                rewrite length_string_list_byte_eq. entailer!.\n                unfold strlst_rep at 3. cancel.\n                unfold_data_at (data_at _ _ _ cellptr2).\n                rewrite (field_at_data_at' _ _ [StructField _next]). \n                simpl nested_field_type. simpl nested_field_offset.\n                entailer!.\n                apply allp_right. intro lst'. apply allp_right. intro cpnew.\n                allp_left ((k0,v0)::lst').\n                allp_left cellptr2. Intros cp'. Exists cp'.\n                rewrite <- wand_sepcon_adjoint.\n                assert (Q: ((cstring Ews (string_to_list_byte k0) str_ptr *\n                (malloc_token Ews t_scell cellptr2 *\n                (field_at Ews t_scell [StructField _key] str_ptr cellptr2 *\n                (malloc_token Ews\n                (tarray tschar (Zlength (string_to_list_byte k0) + 1)) str_ptr * \n                (field_at Ews t_scell [StructField _value] (V_repr v0) cellptr2 *\n                data_at Ews (tptr t_scell) cellptr2 addr))))) *\n                strlst_rep (offset_val 16 cellptr2) cpnew lst')%logic |-- strlst_rep addr cellptr2 ((k0, v0) :: lst')).\n                { unfold strlst_rep. cancel. unfold scell_rep at 2; fold scell_rep.\n                  Exists cpnew str_ptr. cancel.\n                  unfold cstring. unfold string_rep.\n                  rewrite length_string_list_byte_eq. entailer!. \n                  unfold_data_at (data_at _ _ _ cellptr2).\n                  rewrite (field_at_data_at _ _ [StructField _next]), field_address_offset.\n                  entailer!. auto. } sep_apply Q. sep_apply modus_ponens_wand. \n                rewrite app_assoc_reverse. simpl. entailer!. }}\nQed.\n\n\n", "meta": {"author": "PrincetonUniversity", "repo": "DeepSpecDB", "sha": "a67d933b4288498bd04c70748b7fa28f676983c3", "save_path": "github-repos/coq/PrincetonUniversity-DeepSpecDB", "path": "github-repos/coq/PrincetonUniversity-DeepSpecDB/DeepSpecDB-a67d933b4288498bd04c70748b7fa28f676983c3/verif/indices/stringlist_instance.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.22880355144169842}}
{"text": "Require Import Kami.AllNotations ProcKami.FU ProcKami.Div.\nRequire Import List.\n\nSection Alu.\n  Context `{procParams: ProcParams}.\n\n  Section Ty.\n    Variable ty: Kind -> Type.\n\n    Definition JumpInputType :=\n      STRUCT_TYPE {\n        \"pc\"                   :: VAddr;\n        \"new_pc\"               :: VAddr;\n        \"compressed?\"          :: Bool\n        }.\n\n    Definition JumpOutputType :=\n      STRUCT_TYPE {\n          \"misaligned?\" :: Bool ;\n          \"newPc\" :: VAddr ;\n          \"retPc\" :: VAddr }.\n\n    Local Open Scope kami_expr.\n\n    Local Definition jumpTag (jumpOut: JumpOutputType ## ty)\n      :  PktWithException ExecUpdPkt ## ty\n      := LETE jOut <- jumpOut;\n         LETC val1: RoutedReg <- (STRUCT {\n                                      \"tag\" ::= Const ty (natToWord RoutingTagSz IntRegTag);\n                                      \"data\" ::= SignExtendTruncLsb Rlen (#jOut @% \"retPc\")\n                                 });\n         LETC val2: RoutedReg <- (STRUCT {\n                                      \"tag\" ::= Const ty (natToWord RoutingTagSz PcTag);\n                                      \"data\" ::= SignExtendTruncLsb Rlen (#jOut @% \"newPc\")\n                                 });\n         LETC fullException: Exception <- ($(if misaligned_access\n                                                                then InstAccessFault\n                                                                else InstAddrMisaligned) : Exception @# ty);\n         LETC sndVal: Maybe Exception <-  STRUCT {\"valid\" ::= (#jOut @% \"misaligned?\") ;\n                                                  \"data\"  ::= #fullException };\n         LETC val\n           :  ExecUpdPkt\n           <- (noUpdPkt ty\n                 @%[\"val1\"\n                      <- (Valid #val1)]\n                 @%[\"val2\"\n                      <- (Valid #val2)]\n                 @%[\"taken?\" <- $$ true]) ;\n         LETC retval:\n           (PktWithException ExecUpdPkt)\n             <- STRUCT { \"fst\" ::= #val ;\n                         \"snd\" ::= #sndVal } ;\n         RetE #retval.\n\n    Local Definition transPC (sem_output_expr : JumpOutputType ## ty)\n      :  JumpOutputType ## ty\n      := LETE sem_output\n           :  JumpOutputType\n           <- sem_output_expr;\n         LETC newPc : VAddr\n           <- ZeroExtendTruncMsb Xlen (* bit type cast *)\n                ({<\n                   ZeroExtendTruncMsb (Xlen - 1) (#sem_output @% \"newPc\"),\n                   $$WO~0\n                >});\n         RetE (#sem_output @%[\"newPc\" <- #newPc]).\n\n    Local Close Scope kami_expr.\n\n  End Ty.\n\n  Local Open Scope kami_expr.\n\n  Definition Jump: FUEntry\n    := {|\n         fuName := \"jump\";\n         fuFunc\n           := fun ty (sem_in_pkt_expr : JumpInputType ## ty)\n                => LETE sem_in_pkt\n                     :  JumpInputType\n                     <- sem_in_pkt_expr;\n                   LETC new_pc\n                     :  VAddr\n                     <- #sem_in_pkt @% \"new_pc\";\n                   RetE\n                     (STRUCT {\n                        \"misaligned?\"\n                        ::= !($$allow_inst_misaligned) &&\n                             ((unsafeTruncLsb 2 #new_pc)$[1:1] != $0);\n                        \"newPc\" ::= #new_pc;\n                        \"retPc\"\n                          ::= ((#sem_in_pkt @% \"pc\") +\n                               (IF (#sem_in_pkt @% \"compressed?\")\n                                  then $2\n                                  else $4))\n                      } : JumpOutputType @# ty);\n         fuInsts\n           := {|\n                instName     := \"jal\" ; \n                xlens        := xlens_all;\n                extensions   := \"I\" :: nil;\n                ext_ctxt_off := nil;\n                uniqId       := fieldVal instSizeField ('b\"11\") ::\n                                fieldVal opcodeField ('b\"11011\") ::\n                                nil;\n                inputXform \n                  := fun ty (cfg_pkt : ContextCfgPkt @# ty) exec_context_pkt\n                       => LETE exec_pkt\n                            <- exec_context_pkt;\n                          LETC inst\n                            :  Inst\n                            <- #exec_pkt @% \"inst\";\n                          RetE\n                            (STRUCT {\n                               \"pc\" ::= #exec_pkt @% \"pc\";\n                               \"new_pc\"\n                                 ::= ((#exec_pkt @% \"pc\") +\n                                      (SignExtendTruncLsb Xlen \n                                         ({<\n                                           (#inst $[31:31]),\n                                           (#inst $[19:12]),\n                                           (#inst $[20:20]),\n                                           (#inst $[30:21]),\n                                           $$ WO~0\n                                         >})));\n                                \"compressed?\" ::= (#exec_pkt @% \"compressed?\")\n                             } : JumpInputType @# ty);\n                outputXform  := jumpTag;\n                optMemParams  := None ;\n                instHints    := falseHints<|hasRd := true|>\n              |} ::\n              {| instName     := \"jalr\" ; \n                 xlens        := xlens_all;\n                 extensions   := \"I\" :: nil;\n                 ext_ctxt_off := nil;\n                 uniqId       := fieldVal instSizeField ('b\"11\") ::\n                                 fieldVal opcodeField ('b\"11001\") ::\n                                 nil;\n                 inputXform\n                   := fun ty (cfg_pkt : ContextCfgPkt @# ty) expr_context_pkt\n                        => LETE exec_pkt\n                             <- expr_context_pkt;\n                           LETC inst\n                             :  Inst\n                             <- #exec_pkt @% \"inst\";\n                           RetE\n                             (STRUCT {\n                                \"pc\" ::= #exec_pkt @% \"pc\";\n                                \"new_pc\"\n                                  ::= SignExtendTruncLsb Xlen (* bit type cast *)\n                                        ({<\n                                          ZeroExtendTruncMsb (Xlen - 1)\n                                            ((xlen_sign_extend Xlen (cfg_pkt @% \"xlen\") (#exec_pkt @% \"reg1\")) +\n                                             (SignExtendTruncLsb Xlen (imm #inst))),\n                                          $$ WO~0\n                                        >});\n                                \"compressed?\" ::= (#exec_pkt @% \"compressed?\")\n                              } : JumpInputType @# ty);\n                 outputXform  := fun ty (sem_output_expr : JumpOutputType ## ty)\n                                   => jumpTag (transPC sem_output_expr);\n                 optMemParams  := None ;\n                 instHints    := falseHints<|hasRs1 := true|><|hasRd := true|>\n              |} ::\n              nil\n       |}.\n\n  Close Scope kami_expr.\nEnd Alu.\n", "meta": {"author": "sifive", "repo": "ProcKami", "sha": "7094363c5587d50653b918c323e043105fd172d6", "save_path": "github-repos/coq/sifive-ProcKami", "path": "github-repos/coq/sifive-ProcKami/ProcKami-7094363c5587d50653b918c323e043105fd172d6/RiscvIsaSpec/Insts/Alu/Jump.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602051, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2288035459891657}}
{"text": "Require Import Reals.\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.algebra Require Import gmap auth agree gset coPset.\nFrom iris.base_logic Require Import big_op soundness.\nFrom iris.base_logic.lib Require Import wsat.\nFrom iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Import prob_language prob_lifting.\nSet Default Proof Using \"Type\".\nImport uPred.\n\nFrom discprob.idxval Require Import pival pival_dist pidist_singleton idist_pidist_pair ival_dist irrel_equiv ival_pair.\nFrom discprob.basic Require Import monad.\n\n\nSection adequacy.\nContext {Λ : probLanguage}.\nContext `{stateG' Λ Σ} `{probG Σ}.\nImplicit Types e : expr Λ.\nImplicit Types P Q : iProp Σ.\nImplicit Types Φ : val Λ → iProp Σ.\nImplicit Types Φs : list (val Λ → iProp Σ).\n\nNotation world σ := (state_interp σ)%I.\n\nNotation wptp t := ([∗ list] ef ∈ t, WP ef {{ _, True }})%I.\n\nLemma wp_step' e1 σ1 c1 Φ:\n  language.to_val e1 = None →\n  world σ1 ∗ WP e1 {{ Φ }} ∗ aux_interp c1 ={⊤, ∅}=∗\n        ▷ (⌜reducible e1 σ1⌝ ∧ ∃ c2, ∀ e2 σ2 efs c3,\n        ⌜prim_step e1 σ1 e2 σ2 efs⌝ ={∅, ⊤}=∗ (world σ2 ∗ WP e2 {{ Φ }} ∗ wptp efs\n                                   ∗ step_interpR e1 σ1 c1 c2 e2 σ2 efs c3)).\nProof.\n  rewrite {1}wp_unfold /wp_pre. iIntros (Hnone). iIntros \"[Hσ [H Ha]]\".\n  rewrite Hnone.\n  iMod (\"H\" $! σ1 c1 with \"[$Hσ $Ha]\") as \"($ & H)\".\n  iModIntro; iNext.\n  iDestruct \"H\" as (c) \"H\".\n  iExists c. iIntros (e2 σ2 efs c3) \"%\".\n  iMod (\"H\" $! e2 σ2 efs c3 with \"[//]\") as \"($&$&$&$)\"; auto.\nQed.\n\nLemma wp_step e1 σ1 c1 Φ:\n  language.to_val e1 = None →\n  world σ1 ∗ WP e1 {{ Φ }} ∗ aux_interp c1 ={⊤, ∅}=∗\n        ▷ ∃ c2, ∀ e2 σ2 efs c3,\n        ⌜prim_step e1 σ1 e2 σ2 efs⌝ ={∅, ⊤}=∗ (world σ2 ∗ WP e2 {{ Φ }} ∗ wptp efs\n                                   ∗ step_interpR e1 σ1 c1 c2 e2 σ2 efs c3).\nProof.\n  iIntros (Hred) \"H\".\n  iPoseProof (wp_step' with \"H\") as \"H\"; auto.\n  iMod \"H\". iModIntro. iNext. \n  iDestruct \"H\" as \"(_ & $)\".\nQed.\n\nLemma wptp_step_hd e1 t σ1 c1 Φ :\n  language.to_val e1 = None →\n  world σ1 ∗ WP e1 {{ Φ }} ∗ wptp t ∗ aux_interp c1  ={⊤, ∅}=∗\n        ▷ (⌜ reducible e1 σ1⌝ ∧ ∃ c2, ∀ e2 σ2 efs c3,\n        ⌜prim_step e1 σ1 e2 σ2 efs⌝ ={∅, ⊤}=∗ (world σ2 ∗ WP e2 {{ Φ }} ∗ wptp (t ++ efs)\n                                   ∗ step_interpR e1 σ1 c1 c2 e2 σ2 efs c3)).\nProof.\n  iIntros (Hred) \"(HW&He&Ht&Ha)\".\n  iPoseProof (wp_step' with \"[HW He Ha]\") as \"H\"; [ eauto | eauto |].\n  { iFrame. }\n  iMod \"H\". iModIntro. iNext.\n  iDestruct \"H\" as \"(% & H)\".\n  iSplit; auto.\n  iDestruct \"H\" as (c) \"H\".\n  iExists c. iIntros (e2 σ2 efs c3) \"Hprim\".\n  iFrame. iSpecialize (\"H\" $! e2 σ2 efs c3 with \"Hprim\"); auto.\nQed.\n\nLemma rcons_app_single {A} (a: A) l : seq.rcons l a = seq.cat l (a :: nil).\nProof.\n  induction l => //=; by f_equal.\nQed.\n\nOpaque step_interpR.\n\nLemma wptp_step_tl e1 tl ei tr σ1 c1 Φ :\n  language.to_val ei = None →\n  world σ1 ∗ WP e1 {{ Φ }} ∗ wptp (tl ++ ei :: tr) ∗ aux_interp c1\n        ={⊤, ∅}=∗ ▷ (⌜ reducible ei σ1 ⌝ ∧  ∃ (c2: choice_type ei σ1 c1), ∀ ei' σ2 efs c3,\n        ⌜prim_step ei σ1 ei' σ2 efs⌝\n        ={∅, ⊤}=∗ (world σ2 ∗ WP e1 {{ Φ }} ∗ wptp (tl ++ ei' :: tr ++ efs) ∗ step_interpR ei σ1 c1 c2 ei' σ2 efs c3))%I.\nProof.\n  iIntros (Hred).\n  iIntros  \"(HW & He & ($ & Hei& $) & Hsl)\". iFrame \"He\".\n  iFrame.\n  iPoseProof (wp_step' with \"[HW Hei Hsl]\") as \"Hstep\"; [ done | iFrame | ].\n  iMod \"Hstep\"; iModIntro. iNext. \n  iDestruct \"Hstep\" as (Hred' c2) \"Hstep\".\n  iSplit; auto.\n  iExists c2. iIntros (e2 σ2 efs c3) \"Hprim\".\n  iMod (\"Hstep\" $! e2 σ2 efs c3 with \"Hprim\") as \"($&$&$&$)\"; auto. \nQed.\n\nLocal Open Scope nat_scope.\n\nTransparent step_interpR.\n\nLemma suffix_anti_symm {A} (l1 l2: list A) :\n  l1 `suffix_of` l2 → l2 `suffix_of` l1 → l1 = l2.\nProof.\n  destruct 1 as (ll1&Heq1).\n  destruct 1 as (ll2&Heq2).\n  rewrite Heq1 in Heq2.\n  apply (f_equal length) in Heq2.\n  rewrite ?app_length in Heq2.\n  destruct ll1, ll2; rewrite //= in Heq2; try omega; try auto.\nQed.\n\nDefinition coupling_post {X} (φ : val Λ → X → Prop) (x : language.cfg Λ) y :=\n  match x with\n  | (e :: t, σ) =>\n    match to_val e with\n    | None => False\n    | Some v => φ v y\n    end\n  | _ => False\n  end.\n\nRequire Import Logic.Eqdep_dec.\n\nLemma cat_app {A} (l1 l2: list A):\n  seq.cat l1 l2 = app l1 l2.\nProof. rewrite //=. Qed.\n\nLemma ic_bind_iProp {A1 A2 A1' A2'} (P: A1 → A2 → Prop) f1 f2 I1 Is2 Is0\n      (Q : A1' → A2' → Prop) (Ic: irrel_couplingP I1 Is2 P):\n  irrel_pidist (Is2 ≫= f2) Is0 →\n  ((∀ xyS: { xy: A1 * A2 | P (fst xy) (snd xy )},\n              (⌜ irrel_coupling_propP (f1 (fst (proj1_sig xyS)))\n                                      (f2 (snd (proj1_sig xyS))) Q ⌝ : iProp Σ))%I\n   ⊢ (⌜ irrel_coupling_propP (I1 ≫= f1) Is0 Q ⌝)%I).\nProof.\n  intros Hle.\n  iIntros (Hall).\n  iPureIntro. eapply irrel_coupling_prop_irrel_Proper; first done.\n  * eauto.\n  * done.\n  * eapply irrel_coupling_prop_bind; eauto.\n    ** eexists; eauto.\n    ** intros x y HP. eapply (Hall (exist _ (x, y) HP)). \nQed.\n\n\nTheorem wp_coupling {X: Type} n e t σ φ (Is0: pidist X)\n        (sch : scheduler) (tr: trace)\n        (Hterm: terminates sch (tr ++ ((e :: t, σ) :: nil)) n) :\n  (world σ ∗ WP e {{ v, ∃ (v' : X), ownProb (mret v') ∗ ⌜φ v v'⌝ }}\n         ∗ wptp t\n         ∗ aux_interp (existT X Is0))%I ⊢\n Nat.iter (S n) (λ P, |={⊤, ∅}▷=> P)\n          ⌜ irrel_coupling_propP (ivdist_trace_stepN_aux sch tr (e :: t) σ n) Is0 (coupling_post φ) ⌝.\nProof.\n  iStartProof.\n  iRevert (e t σ φ sch tr Is0 Hterm).\n  iInduction n as [|n] \"IH\";\n  iIntros (e t σ φ sch tr Is0 Hterm) \"H\".\n  - iAssert ( |={⊤, ∅}▷=> ⌜∃ v v', e = of_val v ∧ irrel_pidist (mret v') Is0\n                      ∧ coupling_post φ (of_val v :: t, σ) v'⌝)%I with \"[H]\"\n      as \"H\"; last first.\n    { rewrite //=.\n      iMod \"H\"; iModIntro; iNext. iMod \"H\"; iModIntro.\n      iDestruct \"H\" as %(v&v'&Heq1&Hle&Hpost); last first.\n      iPureIntro. unshelve (eexists); last done.\n      eapply irrel_coupling_mono_irrel.\n      * reflexivity. \n      * eassumption.\n      * subst. rewrite //=.\n        eapply irrel_coupling_mret; eauto.\n    }\n    edestruct (Hterm tr (e :: t, σ) 0) as (v&tp'&Heqval); eauto.\n    { econstructor. }\n    inversion Heqval; subst.\n    iExists v.\n    iDestruct \"H\" as \"(HW&He&Hwptp&Haux)\".\n    iAssert (|={⊤, ∅}▷=> ∃ (v' : X), ⌜irrel_pidist (mret v') Is0 ∧ φ v v'⌝)%I with\n        \"[HW He Hwptp Haux]\" as \"H\"; last first.\n    {\n      iMod \"H\"; iModIntro; iNext; iMod \"H\"; iModIntro.\n      iDestruct \"H\" as (v') \"Hp\". iDestruct \"Hp\" as %(Hle&Hφ).\n      iPureIntro. exists v'; split_and!; auto.\n      rewrite //= to_of_val //=.\n    }\n    iDestruct (wp_value_inv with \"He\") as \"H\".\n    rewrite /ownProb.\n    iMod \"H\" as (v') \"(H&Hphi)\".\n    iDestruct \"H\" as (Is') \"(Hle&Hown)\".\n      iApply (step_fupd_mask_mono ∅ _ _ ∅); [ auto | auto | ].\n    iModIntro; iNext; iModIntro.\n    rewrite /ownProbRaw.\n      iDestruct (own_valid_2 with \"Haux Hown\")\n          as %[(HeqTy&Heq_spi)%Excl_included _]%auth_valid_discrete_2; auto.\n      iClear \"Haux\". iClear \"Hown\". \n      iDestruct \"Hphi\" as %Hphi.\n      iDestruct \"Hle\" as %Hle.\n      iPureIntro. clear -Hphi Heq_spi Hle.\n      rewrite //= in Heq_spi.\n      exists v' => //=; split; auto.\n      etransitivity; first eassumption.\n      rewrite -Heq_spi.\n      rewrite -eq_rect_eq_dec; eauto; first reflexivity.\n      intros. apply ClassicalEpsilon.excluded_middle_informative.\n  - rewrite /ivdist_trace_stepN_aux.\n    rewrite -/ivdist_trace_stepN_aux.\n    rewrite /ivdist_trace_step.\n    specialize (terminates_S sch tr (e :: t, σ)) => Hterm_Some.\n    remember (sch (tr ++ [(e :: t, σ)])) as i eqn:Heq_sched.\n    destruct ((e :: t) !! i) as [ei|] eqn:Hlookup; last first.\n    { rewrite /ivdist_tpool_stepi. rewrite -Heq_sched Hlookup.\n      setoid_rewrite ivd_left_id.\n      setoid_rewrite ivd_left_id.\n      rewrite Nat_iter_S.\n      iApply (step_fupd_mask_mono ∅ _ _ ∅); [ done | done |].\n      iModIntro. iNext. iModIntro.\n      iApply \"IH\".\n      iPureIntro.\n      { subst. rewrite -cat_app. rewrite -seq.catA.\n        eapply terminates_stutter_None; eauto. }\n      eauto.\n    }\n    destruct (to_val ei) as [v|] eqn:Heq_val.\n    { rewrite /ivdist_tpool_stepi. rewrite -Heq_sched Hlookup.\n      setoid_rewrite ivdist_prim_step_val_mret; last first.\n      { rewrite //=. congruence. }\n      setoid_rewrite ivd_left_id.\n      setoid_rewrite ivd_left_id.\n      setoid_rewrite ivd_left_id.\n      rewrite Nat_iter_S.\n      iApply (step_fupd_mask_mono ∅ _ _ ∅); [ done | done |].\n      iModIntro. iNext. iModIntro.\n      iApply \"IH\".\n      iPureIntro.\n      { subst. rewrite -cat_app. rewrite -seq.catA.\n        eapply terminates_stutter_value; eauto. congruence. }\n      eauto.\n    }\n    symmetry in Heq_sched.\n    destruct i as [|i].\n    * rewrite Heq_sched.\n      inversion Hlookup; subst.\n      iPoseProof (wptp_step_hd ei t with \"[H]\") as \"Hstep\"; eauto.\n      rewrite Nat_iter_S.\n      iMod \"Hstep\"; iModIntro; iNext.\n      iDestruct \"Hstep\" as (Hred C) \"Hstep\".\n      destruct C as [Y m f Hequiv P Ic]. \n      iApply step_fupd_iter_mono.\n      { setoid_rewrite ivd_assoc.\n        setoid_rewrite ivd_assoc.\n        rewrite /projT1/projT2 in f Hequiv *.\n        simpl response_type.\n        \n        \n        rewrite -(ic_bind_iProp _ _ _ (ivdist_prim_step ei σ) _ Is0 (coupling_post φ) _); swap 1 3.\n        { eapply Hequiv. }\n        { eapply (irrel_coupling_support _ _ _ Ic). } \n        iIntros \"H\". iApply \"H\".\n      }\n      erewrite (@step_fupd_iter_forall_pure_mid _ _); last first.\n      { destruct (irrel_coupling_support_wit _ _ _ Ic) as ((x&y)&Hpf).\n        unshelve exists. eexists (x, y). rewrite //=.\n      }\n      iIntros (xyS).\n      destruct xyS as ((ei'&y)&HP).\n      destruct ei' as [ei' σ' efs|]; last first. \n      { exfalso. destruct HP as (HP&Hsupp1&?). eapply ival_red_non_stuck; eauto. }\n      \n      setoid_rewrite ivd_left_id. \n      setoid_rewrite ivd_left_id. \n      assert (prim_step ei σ ei' σ' efs).\n      { destruct HP as (HP&Hsupp1&?); by apply ivdist_non_stuck_red; eauto. }\n      assert ((∃ i Hpf, ival.ind Ic i = (exist _ (prim_res_step ei' σ' efs, y) Hpf)\n                        ∧ ival.val Ic i > 0)%R) as Hsupp.\n      { destruct HP as (HP&Hsupp1&?&(i0&?&?)).\n        exists i0, HP; repeat split; auto. }\n      iSpecialize (\"Hstep\" $! ei' σ' efs).\n      unshelve (iSpecialize (\"Hstep\" $! _)).\n      { eexists; eauto => //=. destruct HP; eauto. }\n      iSpecialize (\"Hstep\" with \"[% //]\"). iMod \"Hstep\".\n      iSpecialize (\"IH\" $! _ _ _ _ _ _ with \"[%] Hstep\"); last iFrame; auto.\n      { rewrite //=. rewrite -app_assoc. eapply Hterm_Some; eauto.\n        eapply (istep_atomic _ _ _ ei σ ei' σ' efs []); eauto; try f_equal. }\n    * rewrite /ivdist_tpool_stepi.\n      specialize (take_drop_middle _ _ _ Hlookup) => Hlook.\n      rewrite Heq_sched. rewrite Hlookup.\n      simpl in Hlookup.\n      rewrite -(take_drop_middle _ _ _ Hlookup).\n\n      iPoseProof (wptp_step_tl e _ ei with \"[H]\") as \"Hstep\"; eauto.\n      rewrite Nat_iter_S.\n      iMod \"Hstep\"; iModIntro; iNext.\n      iDestruct \"Hstep\" as (Hred C) \"Hstep\".\n      destruct C as [Y m f Hequiv P Ic]. \n      iApply step_fupd_iter_mono.\n      { setoid_rewrite ivd_assoc.\n        setoid_rewrite ivd_assoc.\n        rewrite /projT1/projT2 in f Hequiv *.\n        simpl response_type.\n        \n        \n        rewrite -(ic_bind_iProp _ _ _ (ivdist_prim_step ei σ) _ Is0 (coupling_post φ) _); swap 1 3.\n        { eapply Hequiv. }\n        { eapply (irrel_coupling_support _ _ _ Ic). } \n        iIntros \"H\". iApply \"H\".\n      }\n      erewrite (@step_fupd_iter_forall_pure_mid _ _); last first.\n      { destruct (irrel_coupling_support_wit _ _ _ Ic) as ((x&y)&Hpf).\n        unshelve exists. eexists (x, y). rewrite //=.\n      }\n      iIntros (xyS).\n      destruct xyS as ((ei'&y)&HP).\n      destruct ei' as [ei' σ' efs|]; last first. \n      { exfalso. destruct HP as (HP&Hsupp1&?). eapply ival_red_non_stuck; eauto. }\n\n      setoid_rewrite ivd_left_id. \n      setoid_rewrite ivd_left_id. \n      assert (prim_step ei σ ei' σ' efs).\n      { destruct HP as (HP&Hsupp1&?); by apply ivdist_non_stuck_red; eauto. }\n      assert ((∃ i Hpf, ival.ind Ic i = (exist _ (prim_res_step ei' σ' efs, y) Hpf)\n                        ∧ ival.val Ic i > 0)%R) as Hsupp.\n      { destruct HP as (HP&Hsupp1&?&(i0&?&?)).\n        exists i0, HP; repeat split; auto. }\n      iSpecialize (\"Hstep\" $! ei' σ' efs).\n      rewrite /rsupport.\n      rewrite //= in Hsupp.\n      unshelve (iSpecialize (\"Hstep\" $! _)).\n      { eexists; eauto. destruct HP; eauto. }\n      iSpecialize (\"Hstep\" with \"[% //]\"). iMod \"Hstep\".\n      repeat iMod \"Hstep\".\n      assert (terminates sch ((tr ++ ((e :: t, σ) :: nil))\n                                ++ (((seq.cat (take (S i) (e :: t))\n                                              (seq.cat (ei' :: drop (S (S i)) (e :: t)) efs), σ'))\n                                      :: nil)) n)\n        as Hterm'.\n      { rewrite //=. rewrite -app_assoc. eapply Hterm_Some; eauto.\n        eapply (istep_atomic _ _ _ ei σ ei' σ' efs (take (S i) (e :: t))); eauto; try f_equal.\n        - by rewrite take_drop_middle. \n        - rewrite take_length_le //.\n          specialize (lookup_lt_Some _ _ _ Hlookup) => //=; omega.\n      }\n      clear Hterm.\n      iSpecialize (\"IH\" $! _ _ _ _ _ _ _ with \"[%] Hstep\"); last iFrame; auto.\n      { eauto. }\n      iModIntro. rewrite //= in Hlook. rewrite Hlook //=.\nQed.\n\nEnd adequacy.\n\n\nClass probPreG (Λ: probLanguage) Σ := ProbPreG{\n  pre_probG_inG :> inG Σ (authR (optionUR (exclR (discreteC prob_state))));\n}.\n\nFrom iris.program_logic Require Import adequacy.\nTheorem wp_prob_adequacy {Y} `{invPreG Σ} `{@probPreG Λ Σ}\n        e σ φ  Is sch n:\n  (∀`{Hinv: invG Σ} (* `{Hprob : probG ex va st Λ Σ} *),\n      (|={⊤}=> ∃ (stateI: _ → iProp Σ) pname,\n      let _ : probG' Σ := ProbG Σ Hinv pname _ in\n      let _ : stateG' Λ Σ := StateG Λ Σ stateI in\n      stateI σ ∗ aux_interp (existT Y Is : prob_state) ∗\n             WP e {{ v, ∃ v' : Y, ownProb (mret v') ∗ ⌜φ v v'⌝ }})%I) →\n  terminates sch (((e :: nil), σ) :: nil) n →\n  irrel_couplingP (ivdist_tpool_stepN sch (e :: nil) σ n)\n                  Is\n                  (coupling_post φ).\n Proof.\n   intros Hwp Hterm. \n   apply ic_prop_to_wit.\n   eapply (step_fupd_soundness' _ (S (S n))).\n   iIntros (Hinv).\n   rewrite Nat_iter_S.\n   iMod (Hwp Hinv) as \"Hwp\".\n   iDestruct \"Hwp\" as (Istate γ) \"H\".\n   iDestruct \"H\" as \"(HIstate & Ha & Hwp)\".\n   iApply (step_fupd_mask_mono ∅ _ _ ∅); auto. iModIntro. iNext; iModIntro.\n   rewrite /ivdist_tpool_stepN.\n   efeed pose proof (@wp_coupling Λ) as Hcoup; eauto; last first.\n   iPoseProof (Hcoup with \"[HIstate Ha Hwp]\") as \"H\".\n   { iFrame.  rewrite //=. }\n   { eauto. }\n   { eauto. }\nQed.\n\nDefinition coerce_cfg {Λ : probLanguage} (f: language.val Λ → R) (r: R) (ρ: cfg Λ) : R :=\n  match fst ρ with\n  | [] => r\n  | e :: _ => match to_val e with\n              | Some v => f v \n              | _ => r\n              end\n  end.\n\nTheorem wp_prob_adequacy' {Y} `{invPreG Σ} `{@probPreG Λ Σ}\n        e σ φ  Is sch n:\n  (∀`{Hinv: invG Σ},\n      (|={⊤}=> ∃ (stateI: _ → iProp Σ), ∀ pname,\n      let _ : probG' Σ := ProbG Σ Hinv pname _ in\n      let _ : stateG' Λ Σ := StateG Λ Σ stateI in\n      stateI σ ∗ (ownProb Is -∗\n             WP e {{ v, ∃ (v' : Y), ownProb (mret v') ∗ ⌜φ v v'⌝ }}))%I) →\n  terminates sch (((e :: nil), σ) :: nil) n →\n  irrel_couplingP (ivdist_tpool_stepN sch (e :: nil) σ n)\n                  Is\n                  (coupling_post φ).\n Proof.\n   intros Hwp Hterm. \n   apply ic_prop_to_wit.\n   eapply (step_fupd_soundness' _ (S (S n))).\n   iIntros (Hinv).\n   rewrite Nat_iter_S.\n  iMod (own_alloc (● (Excl' (existT _ Is : discreteC prob_state)) ⋅\n                   ◯ (Excl' (existT _ Is : discreteC prob_state))))\n    as (γprob) \"[Hσ Hσf]\"; first done.\n   iMod (Hwp Hinv) as \"Hwp\".\n   iDestruct \"Hwp\" as (Istate) \"H\".\n   iSpecialize (\"H\" $! γprob).\n   iDestruct \"H\" as \"(HIstate & HaHwp)\".\n   iApply (step_fupd_mask_mono ∅ _ _ ∅); auto. iModIntro. iNext; iModIntro.\n   rewrite /ivdist_tpool_stepN.\n   set (Hprob := ProbG Σ _ γprob _).\n   efeed pose proof (@wp_coupling Λ _ {| stateG_interp := Istate |} Hprob) as Hcoup; eauto;\n     last first.\n   iPoseProof (Hcoup with \"[HIstate HaHwp Hσf Hσ]\") as \"H\".\n   { rewrite /ownProb/ownProbRaw//=. iFrame.\n     iSplitR \"\".\n     * iApply (\"HaHwp\" with \"[Hσf]\").\n       { iExists _; auto. }\n     * rewrite //=.\n   }\n   { eauto. }\n   { eauto. }\nQed.\n\nImport Rbar.\nFrom discprob.idxval Require Import extrema.\n\nTheorem wp_prob_adequacy_Ex_max {Y} `{invPreG Σ} `{@probPreG Λ Σ}\n        e σ φ (Is: pidist Y) sch f g d n:\n  (∀`{Hinv: invG Σ},\n      (|={⊤}=> ∃ (stateI: _ → iProp Σ), ∀ pname,\n      let _ : probG' Σ := ProbG Σ Hinv pname _ in\n      let _ : stateG' Λ Σ := StateG Λ Σ stateI in\n      stateI σ ∗ (ownProb Is -∗\n             WP e {{ v, ∃ (v' : Y), ownProb (mret v') ∗ ⌜φ v v'⌝ }}))%I) →\n  (∀ v v', φ v v' → f v = g v') →\n  terminates sch (((e :: nil), σ) :: nil) n →\n  bounded_fun_on g (λ x, In_psupport x Is) →\n  Rbar_le (extrema.Ex_ival (coerce_cfg f d) (ivdist_tpool_stepN sch [e] σ n))\n          (extrema.Ex_max g Is).\nProof.\n  rewrite /coerce_cfg.\n  intros. apply irrel_coupling_eq_Ex_max_supp; eauto.\n  eapply irrel_coupling_conseq; last eapply wp_prob_adequacy'; eauto.\n  { intros x y. rewrite /coupling_post.\n    destruct x as (l&?). destruct l => //=.\n    destruct to_val => //=. eauto. }\nQed.\n\nTheorem wp_prob_adequacy_Ex_min {Y} `{invPreG Σ} `{@probPreG Λ Σ}\n        e σ φ (Is: pidist Y) sch f g d n:\n  (∀`{Hinv: invG Σ},\n      (|={⊤}=> ∃ (stateI: _ → iProp Σ), ∀ pname,\n      let _ : probG' Σ := ProbG Σ Hinv pname _ in\n      let _ : stateG' Λ Σ := StateG Λ Σ stateI in\n      stateI σ ∗ (ownProb Is -∗\n             WP e {{ v, ∃ (v' : Y), ownProb (mret v') ∗ ⌜φ v v'⌝ }}))%I) →\n  (∀ v v', φ v v' → f v = g v') →\n  terminates sch (((e :: nil), σ) :: nil) n →\n  bounded_fun_on g (λ x, In_psupport x Is) →\n  Rbar_le (extrema.Ex_min g Is)\n          (extrema.Ex_ival (coerce_cfg f d) (ivdist_tpool_stepN sch [e] σ n)).\nProof.\n  rewrite /coerce_cfg.\n  intros. apply irrel_coupling_eq_Ex_min_supp; eauto.\n  eapply irrel_coupling_conseq; last eapply wp_prob_adequacy'; eauto.\n  { intros x y. rewrite /coupling_post.\n    destruct x as (l&?). destruct l => //=.\n    destruct to_val => //=. eauto. }\n Qed.\n\nTheorem wp_prob_adequacy_ex_Ex {Y} `{invPreG Σ} `{@probPreG Λ Σ}\n        e σ φ (Is: pidist Y) sch f g d n:\n  (∀`{Hinv: invG Σ},\n      (|={⊤}=> ∃ (stateI: _ → iProp Σ), ∀ pname,\n      let _ : probG' Σ := ProbG Σ Hinv pname _ in\n      let _ : stateG' Λ Σ := StateG Λ Σ stateI in\n      stateI σ ∗ (ownProb Is -∗\n             WP e {{ v, ∃ (v' : Y), ownProb (mret v') ∗ ⌜φ v v'⌝ }}))%I) →\n  (∀ v v', φ v v' → f v = g v') →\n  terminates sch (((e :: nil), σ) :: nil) n →\n  bounded_fun_on g (λ x, In_psupport x Is) →\n  ex_Ex_ival (coerce_cfg f d) (ivdist_tpool_stepN sch [e] σ n).\nProof.\n  rewrite /coerce_cfg.\n  intros. eapply irrel_coupling_eq_ex_Ex_supp; eauto.\n  eapply irrel_coupling_conseq; last eapply wp_prob_adequacy'; eauto.\n  { intros x y. rewrite /coupling_post.\n    destruct x as (l&?). destruct l => //=.\n    destruct to_val => //=. eauto. }\n Qed.\n\nTheorem wp_prob_safety_adequacy Σ Λ `{invPreG Σ} `{@probPreG Λ Σ} {X} (Is: pidist X) s e σ φ :\n  (∀ `{Hinv : invG Σ},\n     (|={⊤}=> ∃ (stateI : state Λ → iProp Σ), ∀ pname,\n      let _ : probG' Σ := ProbG Σ Hinv pname _ in\n      let _ : stateG' Λ Σ := StateG Λ Σ stateI in\n      stateI σ ∗ (ownProb Is -∗\n                          WP e @ s; ⊤ {{ v, ⌜φ v⌝ }}))%I) →\n  adequate s e σ φ.\nProof.\n  intros Hwp; eapply (wp_adequacy _ _); iIntros (?) \"\".\n  iMod (own_alloc (● (Excl' (existT _ Is : discreteC prob_state)) ⋅\n                   ◯ (Excl' (existT _ Is : discreteC prob_state))))\n    as (γprob) \"[Hσ Hσf]\"; first done.\n  iMod Hwp as (stateI) \"Hwp\".\n  iModIntro. iExists stateI. \n  set (Hprob := ProbG Σ Hinv γprob _).\n  set (irisG' := @probG_irisG _ Hprob _ {| stateG_interp := stateI |}).\n  iExists aux_state, aux_interp, choice_type, response_type, step_interpR.\n  iExists step_to_aux, response_inhabited.\n  iExists (existT _ Is : prob_state).\n  iDestruct (\"Hwp\" $! γprob) as \"($&Hwp)\". iFrame.\n  iSpecialize (\"Hwp\" with \"[Hσf]\").\n  { rewrite /ownProb/ownProbRaw; iExists _; iFrame. auto. }\n  auto.\nQed.", "meta": {"author": "jtassarotti", "repo": "polaris", "sha": "c7873f05214351d54cacf3d8482625ee33ad3288", "save_path": "github-repos/coq/jtassarotti-polaris", "path": "github-repos/coq/jtassarotti-polaris/polaris-c7873f05214351d54cacf3d8482625ee33ad3288/theories/program_logic/prob_adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.22880354598916566}}
{"text": "Require Import Integers.\nRequire Import Coqlib.\nRequire Import Maps.\n\nRequire Import Hardware.\nRequire Import ChipTactics.\n\nImport ListNotations.\nImport Int.\n\nDefinition SimpleSkipper :=\n  [(Imovb v0 (Int.repr 4));\n   (Iskeqb v0 (Int.repr 4));\n   (Imovb v0 (Int.repr 8));\n   (Icls)].\n\nLemma SimpleSkipper_is_ok:\n  exists n M IM RF St,\n  Run SimpleSkipper n = Fine M IM RF St /\\\n  RF#v0 = (repr 4).\nProof.\n  exists 3%nat. unfold SimpleSkipper. simpl_code. dec_eq_try.\n  deal_with_eq. dec_eq_try.\n  Fine_eq. intuition. dec_eq_try.\n  reflexivity.\nQed.", "meta": {"author": "holmuk", "repo": "coq-chip8", "sha": "50d4d01229bfdf9e9192763cbba35f0333ccbe73", "save_path": "github-repos/coq/holmuk-coq-chip8", "path": "github-repos/coq/holmuk-coq-chip8/coq-chip8-50d4d01229bfdf9e9192763cbba35f0333ccbe73/Examples/SimpleSkip.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2287275303209025}}
{"text": "(** * Bicolano: Semantic domains *)\n\n(* <Insert License Here>\n\n    $Id: Domain.v 69 2006-03-06 20:16:11Z davidpichardie $ *)\n\n(** Formalization of Java semantic domain.\n Based on The \"Java (TM) Virtual Machine Specification, Second Edition, \n  Tim Lindholm, Frank Yellin\"\n\n @author David Pichardie, ...  *)\n(* Hendra : - Modified to suit DEX program (removed operand stack).\n            - Removed reference comparison \n            - Also trim the system to contain only Arithmetic *)\n\nRequire Export DEX_Program.\nRequire Export Numeric.\nRequire Export List.\nOpen Scope Z_scope.\n\n(** All semantic domains and basic operation are encapsulated in a module signature *)\n\nModule Type DEX_SEMANTIC_DOMAIN.\n\n (** We depend on the choices done for program data structures *)\n Declare Module DEX_Prog : DEX_PROGRAM. Import DEX_Prog.\n\n Declare Module Byte  : NUMERIC with Definition power := 7%nat.\n Declare Module Short : NUMERIC with Definition power := 15%nat.\n Declare Module Int   : NUMERIC with Definition power := 31%nat.\n\n (** conversion *)\n Parameter b2i : Byte.t -> Int.t.\n Parameter s2i : Short.t -> Int.t. \n Parameter i2b : Int.t -> Byte.t. \n Parameter i2s : Int.t -> Short.t.\n Parameter i2bool : Int.t -> Byte.t.\n\n Inductive DEX_num : Set :=\n   | I : Int.t -> DEX_num\n   | B : Byte.t -> DEX_num\n   | Sh : Short.t -> DEX_num.\n \n (** Location is the domain of adresses in the heap *)\n\n(* Hendra 10082016 - Only concerns DVM_I\n Parameter DEX_Location : Set.\n Parameter DEX_Location_dec : forall loc1 loc2:DEX_Location,{loc1=loc2}+{~loc1=loc2}.\n*)\n\n Inductive DEX_value : Set :=\n   | Num : DEX_num -> DEX_value\n(* Hendra 10082016 - Only concerns DVM_I\n   | Ref: DEX_Location -> DEX_value\n   | Null : DEX_value*).\n\n Definition init_value (t:DEX_type) : DEX_value :=\n    match t with\n     (* Hendra 10082016 - Only concerns DVM_I | DEX_ReferenceType _ => Null*)\n     | DEX_PrimitiveType _ => Num (I (Int.const 0))\n    end.\n\n(* Hendra 10082016 - Only concerns DVM_I\n Definition init_field_value (f:DEX_Field) : DEX_value :=\n   match DEX_FIELD.initValue f with\n    | DEX_FIELD.Int z => Num (I (Int.const z))\n    | DEX_FIELD.NULL => Null\n    | DEX_FIELD.UNDEF => init_value (DEX_FIELDSIGNATURE.type (DEX_FIELD.signature f))\n  end.\n*)\n \n (** Domain of local variables *)\n Module Type DEX_REGISTERS.\n   Parameter t : Type.\n   Parameter get : t-> DEX_Reg -> option DEX_value.\n   Parameter update : t -> DEX_Reg -> DEX_value -> t.\n   Parameter dom : t -> list DEX_Reg.\n   (*Parameter ret : DEX_Reg.*)\n   (* Hendra 10082016 Removed r0 requirements? Parameter r0 : DEX_Reg. *)\n   Parameter get_update_new : forall l x v, get (update l x v) x = Some v.\n   Parameter get_update_old : forall l x y v,\n     x<>y -> get (update l x v) y = get l y.\n End DEX_REGISTERS.\n Declare Module DEX_Registers : DEX_REGISTERS.\n\n Parameter listreg2regs : DEX_Registers.t -> nat -> list DEX_Reg -> DEX_Registers.t.\n\n(* 290415 - Some Notes\n- According to verified DEX bytecode, every registers have\n  to have a value before used. This means we can safely assume\n  that we don't need the update to be option anymore because\n  the only possible case where it updates empty value is when\n  the source is empty, which has been taken care by the assumption\n- The special register ret and ex are assigned the number\n  65536 and 65537 respectively (in binary) because we know\n  that the maximum number of registers is 65535.\n*)\n\n(*\n (* Domain of operand stacks *) \n Module Type OPERANDSTACK.\n   Definition t : Set := list value.\n   Definition empty : t := nil.\n   Definition push : value -> t -> t := fun v t => cons v t.\n   Definition size : t -> nat := fun t  => length t .\n   Definition get_nth : t -> nat -> option value := fun s n => nth_error s n.\n End OPERANDSTACK.\n Declare Module OperandStack : OPERANDSTACK.\n\n (** Transfert fonction between operand stack and local variables necessary for invoke instructions *)\n Parameter stack2localvar : OperandStack.t -> nat -> LocalVar.t.\n Parameter stack2locvar_prop1 :\n   forall s n x, (n <= Var_toN x)%nat -> LocalVar.get (stack2localvar s n) x = None.\n Parameter stack2locvar_prop2 :\n   forall s n x, (Var_toN x < n)%nat ->\n     LocalVar.get (stack2localvar s n) x = OperandStack.get_nth s (n-(Var_toN x)-1)%nat.\n (** %%nat is a coq command for the notation system *)\n*)\n\n(* Hendra 10082016 - Only concerns DVM_I\n Module Type DEX_HEAP.\n   Parameter t : Type.\n\n   Inductive DEX_AdressingMode : Set :=\n     | StaticField : DEX_FieldSignature -> DEX_AdressingMode\n     | DynamicField : DEX_Location -> DEX_FieldSignature -> DEX_AdressingMode\n     | ArrayElement : DEX_Location -> Z -> DEX_AdressingMode.\n\n   Inductive DEX_LocationType : Type :=\n     | LocationObject : DEX_ClassName -> DEX_LocationType  \n     | LocationArray : Int.t -> DEX_type -> DEX_Method*DEX_PC -> DEX_LocationType.\n   (** (LocationArray length element_type) *)\n\n   Parameter get : t -> DEX_AdressingMode -> option DEX_value.\n   Parameter update : t -> DEX_AdressingMode -> DEX_value -> t.\n   Parameter typeof : t -> DEX_Location -> option DEX_LocationType.   \n     (** typeof h loc = None -> no object, no array allocated at location loc *)\n   Parameter new : t -> DEX_Program -> DEX_LocationType -> option (DEX_Location * t).\n     (** program is required to compute the size of the allocated element, i.e. to know\n        the Class associated with a ClassName  *)\n\n   (** Compatibility between a heap and an adress *)\n   Inductive Compat (h:t) : DEX_AdressingMode -> Prop :=\n     | CompatStatic : forall f,\n         Compat h (StaticField f)\n     | CompatObject : forall cn loc f,\n         typeof h loc = Some (LocationObject cn) ->\n         Compat h (DynamicField loc f)\n     | CompatArray : forall length tp loc i a,\n         0 <= i < Int.toZ length ->\n         typeof h loc = Some (LocationArray length tp a) ->\n         Compat h (ArrayElement loc i).\n\n   Parameter get_update_same : forall h am v, Compat h am ->  get (update h am v) am = Some v.\n   Parameter get_update_old : forall h am1 am2 v, am1<>am2 -> get (update h am1 v) am2 = get h am2.\n   Parameter get_uncompat : forall h am, ~ Compat h am -> get h am = None.\n\n   Parameter typeof_update_same : forall h loc am v,\n     typeof (update h am v) loc = typeof h loc.\n\n   Parameter new_fresh_location : forall (h:t) (p:DEX_Program) (lt:DEX_LocationType) (loc:DEX_Location) (h':t),\n     new h p lt = Some (loc,h') ->\n     typeof h loc = None.\n\n   Parameter new_typeof : forall (h:t) (p:DEX_Program) (lt:DEX_LocationType) (loc:DEX_Location) (h':t),\n     new h p lt = Some (loc,h') ->\n     typeof h' loc = Some lt.\n\n   Parameter new_typeof_old : forall (h:t) (p:DEX_Program) (lt:DEX_LocationType) (loc loc':DEX_Location) (h':t),\n     new h p lt = Some (loc,h') ->\n     loc <> loc' ->\n     typeof h' loc' = typeof h loc'.\n\n   Parameter new_defined_object_field : forall (h:t) (p:DEX_Program) (cn:DEX_ClassName) (fs:DEX_FieldSignature) (f:DEX_Field) (loc:DEX_Location) (h':t),\n     new h p (LocationObject cn) = Some (loc,h') ->\n     is_defined_field p cn fs f ->\n     get h' (DynamicField loc fs) = Some (init_field_value f).\n\n   Parameter new_undefined_object_field : forall (h:t) (p:DEX_Program) (cn:DEX_ClassName) (fs:DEX_FieldSignature) (loc:DEX_Location) (h':t),\n     new h p (LocationObject cn) = Some (loc,h') ->\n     ~ defined_field p cn fs ->\n     get h' (DynamicField loc fs) = None.\n \n  Parameter new_object_no_change : \n     forall (h:t) (p:DEX_Program) (cn:DEX_ClassName) (loc:DEX_Location) (h':t) (am:DEX_AdressingMode),\n     new h p (LocationObject cn) = Some (loc,h') ->\n     (forall (fs:DEX_FieldSignature), am <> (DynamicField loc fs)) ->\n     get h' am = get h am.\n\n  Parameter new_valid_array_index : forall (h:t) (p:DEX_Program) (length:Int.t) (tp:DEX_type) a (i:Z) (loc:DEX_Location) (h':t),\n     new h p (LocationArray length tp a) = Some (loc,h') ->\n     0 <= i < Int.toZ length ->\n     get h' (ArrayElement loc i) = Some (init_value tp).\n\n  Parameter new_unvalid_array_index : forall (h:t) (p:DEX_Program) (length:Int.t) (tp:DEX_type) a (i:Z) (loc:DEX_Location) (h':t),\n     new h p (LocationArray length tp a) = Some (loc,h') ->\n     ~ 0 <= i < Int.toZ length ->\n     get h' (ArrayElement loc i) = None.\n\n  Parameter new_array_no_change : \n     forall (h:t) (p:DEX_Program) (length:Int.t) (tp:DEX_type) a (loc:DEX_Location) (h':t) (am:DEX_AdressingMode),\n     new h p (LocationArray length tp a) = Some (loc,h') ->\n     (forall (i:Z), am <> (ArrayElement loc i)) ->\n     get h' am = get h am.\n\n(* These properties should be useless\n   Parameter get_static_some : forall (h:t) (p:Program) (fs:FieldSignature),\n     isStatic p fs ->\n     exists v, get h (StaticField fs) = Some v.\n\n   Parameter get_static_some : forall (h:t) (p:Program) (fs:FieldSignature),\n     ~ isStatic p fs ->\n     exists v, get h (StaticField fs) = None.\n*)\n\n End DEX_HEAP.\n Declare Module DEX_Heap : DEX_HEAP.\n*)\n\n  Inductive DEX_ReturnVal : Set :=\n   | Normal : option DEX_value -> DEX_ReturnVal\n   (* DEX | Exception : Location -> ReturnVal *).\n\n (** Domain of frames *)\n Module Type DEX_FRAME.\n   Inductive t : Type := \n      (*make : Method -> PC -> OperandStack.t -> LocalVar.t -> t.*)\n      make : DEX_Method -> DEX_PC -> DEX_Registers.t -> t.\n End DEX_FRAME.\n Declare Module DEX_Frame : DEX_FRAME.\n\n (** Domain of call stacks *)\n Module Type DEX_CALLSTACK.\n   Definition t : Type := list DEX_Frame.t.\n End DEX_CALLSTACK.\n Declare Module DEX_CallStack : DEX_CALLSTACK.\n(* DEX\n Module Type EXCEPTION_FRAME.\n   Inductive t : Type := \n      make : Method -> PC -> Location -> LocalVar.t -> t.\n End EXCEPTION_FRAME.\n Declare Module ExceptionFrame : EXCEPTION_FRAME.\n*)\n (** Domain of states *)\n Module Type DEX_STATE.\n   Inductive t : Type := \n      normal : (* Hendra 10082016 - Only concerns DVM_I DEX_Heap.t ->*) DEX_Frame.t -> DEX_CallStack.t -> t\n    (* DEX | exception : Heap.t -> ExceptionFrame.t -> DEX_CallStack.t -> t *).\n   Definition get_sf (s:t) : DEX_CallStack.t :=\n     match s with\n       normal (*_ *) _ sf => sf\n     (* | exception _ _ sf => sf *)\n     end.\n   Definition get_m (s:t) : DEX_Method :=\n     match s with\n       normal (*_ *) (DEX_Frame.make m _ _)_ => m\n     (* | exception _ (ExceptionFrame.make m _ _ _) _ => m *)\n     end.\n End DEX_STATE.\n Declare Module DEX_State : DEX_STATE.\n \n (** Some notations *)\n Notation St := DEX_State.normal.\n (* DEX Notation StE := DEX_State.exception. *)\n Notation Fr := DEX_Frame.make.\n (* DEX Notation FrE := DEX_ExceptionFrame.make. *)\n\n  (** compatibility between ArrayKind and type *)\n(* Hendra 10082016 - Only concerns DVM_I\n  Inductive compat_ArrayKind_type : DEX_ArrayKind -> DEX_type -> Prop :=\n    | compat_ArrayKind_type_ref : forall rt,\n        compat_ArrayKind_type DEX_Aarray (DEX_ReferenceType rt)\n    | compat_ArrayKind_type_int : \n        compat_ArrayKind_type DEX_Iarray (DEX_PrimitiveType DEX_INT)\n    | compat_ArrayKind_type_byte : \n        compat_ArrayKind_type DEX_Barray (DEX_PrimitiveType DEX_BYTE)\n    | compat_ArrayKind_type_bool : \n        compat_ArrayKind_type DEX_Barray (DEX_PrimitiveType DEX_BOOLEAN)\n    | compat_ArrayKind_type_short : \n        compat_ArrayKind_type DEX_Sarray (DEX_PrimitiveType DEX_SHORT).\n*)\n(*\n  Inductive isReference : DEX_value -> Prop :=\n  | isReference_null : isReference Null\n  | isReference_ref : forall loc, isReference (Ref loc).\n*)\n  (** compatibility between ValKind and value *) \n  Inductive compat_ValKind_value : DEX_ValKind -> DEX_value -> Prop :=\n    (*| compat_ValKind_value_ref : forall v,\n        isReference v -> compat_ValKind_value DEX_Aval v*)\n    | compat_ValKind_value_int : forall n,\n        compat_ValKind_value DEX_Ival (Num (I n)).\n\n  (** compatibility between ArrayKind and value *) \n(* Hendra 10082016 - Only concerns DVM_I\n  Inductive compat_ArrayKind_value : DEX_ArrayKind -> DEX_value -> Prop :=\n    | compat_ArrayKind_value_ref : forall v,\n        isReference v -> compat_ArrayKind_value DEX_Aarray v\n    | compat_ArrayKind_value_int : forall n,\n        compat_ArrayKind_value DEX_Iarray (Num (I n))\n    | compat_ArrayKind_value_byte : forall n,\n        compat_ArrayKind_value DEX_Barray (Num (B n))\n    | compat_ArrayKind_value_short : forall n,\n        compat_ArrayKind_value DEX_Sarray (Num (Sh n)).\n*)\n\n  (* convert a value to be pushed on the stack *)\n(* Hendra 10082916 - Only concerns DVM I - Definition conv_for_stack (v:DEX_value) : DEX_value :=\n    match v with\n    | Num (B b) => Num (I (b2i b))\n    | Num (Sh s) => Num (I (s2i s))\n    | _ => v\n    end. *)\n\n  (* convert a value to be store in an array *)\n(* Hendra 10082016 - Only concerns DVM_I\n  Definition conv_for_array (v:DEX_value) (t:DEX_type) : DEX_value :=\n    match v with\n    | Ref loc => v\n    | Num (I i) =>\n       match t with\n         DEX_ReferenceType _ => v (* impossible case *)\n       | DEX_PrimitiveType DEX_INT => v\n       | DEX_PrimitiveType DEX_BOOLEAN => Num (B (i2bool i))\n       | DEX_PrimitiveType DEX_BYTE => Num (B (i2b i))\n       | DEX_PrimitiveType DEX_SHORT => Num (Sh (i2s i))         \n       end\n    | _ => v (* impossible case *)\n    end.\n*)\n  (** [assign_compatible_num source target] holds if a numeric value [source] can be \n    assigned to a variable of type [target]. This point is not clear in the JVM spec. *)\n  Inductive assign_compatible_num : DEX_num -> DEX_primitiveType -> Prop :=\n   | assign_compatible_int_int : forall i, assign_compatible_num (I i) DEX_INT\n   | assign_compatible_short_int : forall sh, assign_compatible_num (Sh sh) DEX_INT\n   | assign_compatible_byte_int : forall b, assign_compatible_num (B b) DEX_INT\n   | assign_compatible_short_short : forall sh, assign_compatible_num (Sh sh) DEX_SHORT\n   | assign_compatible_byte_byte : forall b, assign_compatible_num (B b) DEX_BYTE\n   | assign_compatible_byte_boolean : forall b, assign_compatible_num (B b) DEX_BOOLEAN.\n\n  (** [assign_compatible h source target] holds if a value [source] can be \n    assigned to a variable of type [target] *)\n  Inductive assign_compatible (p:DEX_Program) (*h:DEX_Heap.t*) : DEX_value -> DEX_type -> Prop :=\n  (* Hendra 10082016 - Only concerns DVM_I\n   | assign_compatible_null : forall t, assign_compatible p h Null (DEX_ReferenceType t)\n   | assign_compatible_ref_object_val : forall (loc:DEX_Location) (t:DEX_refType) (cn:DEX_ClassName), \n       DEX_Heap.typeof h loc = Some (DEX_Heap.LocationObject cn) ->\n       compat_refType p (DEX_ClassType cn) t ->\n       assign_compatible p h (Ref loc) (DEX_ReferenceType t)\n   | assign_compatible_ref_array_val : forall (loc:DEX_Location) (t:DEX_refType) (length:Int.t) (tp:DEX_type) a, \n       DEX_Heap.typeof h loc = Some (DEX_Heap.LocationArray length tp a) ->\n       compat_refType p (DEX_ArrayType tp) t ->\n       assign_compatible p h (Ref loc) (DEX_ReferenceType t)\n  *)\n   | assign_compatible_num_val : forall (n:DEX_num) (t:DEX_primitiveType),\n       assign_compatible_num n t -> assign_compatible p (*h*) (Num n) (DEX_PrimitiveType t).\n\n(* DEX\n  Inductive SemCompRef : CompRef -> DEX_value -> DEX_value -> Prop :=\n  | SemCompRef_eq : forall v1 v2,\n       isReference v1 -> isReference v2 -> v1 = v2 ->\n     (****************************************************)\n          SemCompRef EqRef v1 v2\n  | SemCompRef_ne : forall v1 v2,\n       isReference v1 -> isReference v2 -> v1 <> v2 ->\n     (****************************************************)\n          SemCompRef NeRef v1 v2.\n*)\n\n  Definition SemCompInt (cmp:DEX_CompInt) (z1 z2: Z) : Prop :=\n    match cmp with\n      DEX_EqInt =>  z1=z2\n    | DEX_NeInt => z1<>z2\n    | DEX_LtInt => z1<z2\n    | DEX_LeInt => z1<=z2\n    | DEX_GtInt => z1>z2\n    | DEX_GeInt => z1>=z2\n    end.\n\n  Definition SemBinopInt (op:DEX_BinopInt) (i1 i2:Int.t) : Int.t :=\n    match op with \n    | DEX_AddInt => Int.add i1 i2\n    | DEX_AndInt => Int.and i1 i2\n    | DEX_DivInt => Int.div i1 i2\n    | DEX_MulInt => Int.mul i1 i2\n    | DEX_OrInt => Int.or i1 i2\n    | DEX_RemInt => Int.rem i1 i2\n    | DEX_ShlInt => Int.shl i1 i2\n    | DEX_ShrInt => Int.shr i1 i2\n    | DEX_SubInt => Int.sub i1 i2\n    | DEX_UshrInt => Int.ushr i1 i2\n    | DEX_XorInt => Int.xor i1 i2\n    end.\n\n  (** Lookup in the callstack if one frame catches the thrown exception *)\n  (* If an handler can catch the exception then the control flow is transferred \n     to the beginning of the handler and the exception caught is the only element \n     of the operand stack *)\n  (* If lookup in the topmost frame fails, the frame is popped and the lookup \n     continues in the next frame *)\n  (* FIXME: Check that the object pointed by loc is an instance of Throwable? - gd *)\n\n(*  Inductive CaughtException (p:Program) : Method -> PC*Heap.t*Location -> PC -> Prop :=\n    CaughtException_def : forall m pc h loc bm pc' e,\n      METHOD.body m = Some bm ->\n      Heap.typeof h loc = Some (Heap.LocationObject e) ->\n      lookup_handlers p (BYTECODEMETHOD.exceptionHandlers bm) pc e pc' ->\n      CaughtException p m (pc,h,loc) pc'.\n\n  Inductive UnCaughtException (p:Program) : Method -> PC*Heap.t*Location -> Prop :=\n    UnCaughtException_def : forall m pc h loc bm e,\n      METHOD.body m = Some bm ->\n      Heap.typeof h loc = Some (Heap.LocationObject e) ->\n      (forall pc', ~ lookup_handlers p (BYTECODEMETHOD.exceptionHandlers bm) pc e pc') ->\n      UnCaughtException p m (pc,h,loc). *)\n\n\nEnd DEX_SEMANTIC_DOMAIN.\n", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/DEX_Domain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2287275303209025}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Fiat.Common.Enumerable.\nRequire Import Fiat.Common.Enumerable.BoolProp.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Common.List.ListFacts.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Common.Gensym.\nRequire Import Fiat.Common.Tactics.BreakMatch.\nRequire Import Fiat.Common.Tactics.DestructHead.\n\nLocal Open Scope type_scope.\n\nDefinition default_nonterminal_carrierT : Type := nat.\n(** (nonterminal, production_index, drop_count) *)\nDefinition default_production_carrierT : Type\n  := default_nonterminal_carrierT * (nat * nat).\n\nGlobal Instance dnc_BoolDecR : BoolDecR default_nonterminal_carrierT := _.\nGlobal Instance dnc_BoolDec_bl : BoolDec_bl (@eq default_nonterminal_carrierT)\n  := _.\nGlobal Instance dnc_BoolDec_lb : BoolDec_lb (@eq default_nonterminal_carrierT)\n  := _.\n\nLocal Ltac eassumption' :=\n  idtac;\n  match goal with\n    | [ H : _ |- _ ] => solve [ refine H ]\n  end.\n\nDefinition default_production_carrierT_beq : default_production_carrierT -> default_production_carrierT -> bool\n  := Equality.beq.\nDefinition default_production_carrierT_bl\n: forall {x y}, default_production_carrierT_beq x y = true -> x = y\n  := Equality.bl.\nDefinition default_production_carrierT_lb\n: forall {x y}, x = y -> default_production_carrierT_beq x y = true\n  := Equality.lb.\n\nSection grammar.\n  Context {Char} {G : pregrammar' Char}.\n\n  Local Notation valid_nonterminals := (List.map fst (pregrammar_productions G)).\n\n  Definition some_invalid_nonterminal\n    := gensym valid_nonterminals.\n\n  Lemma some_invalid_nonterminal_invalid'\n  : ~List.In some_invalid_nonterminal valid_nonterminals.\n  Proof.\n    apply gensym_fresh.\n  Qed.\n  Lemma some_invalid_nonterminal_invalid\n  : ~List.In some_invalid_nonterminal (Valid_nonterminals G).\n  Proof.\n    intro H; apply some_invalid_nonterminal_invalid'.\n    assumption.\n  Qed.\n\n  Definition default_to_nonterminal\n  : default_nonterminal_carrierT -> String.string\n    := fun nt => List.nth nt valid_nonterminals some_invalid_nonterminal.\n\n  Definition default_of_nonterminal\n  : String.string -> default_nonterminal_carrierT\n    := fun nt => List.first_index_default\n                   (string_beq nt)\n                   (List.length valid_nonterminals)\n                   valid_nonterminals.\n\n  Lemma default_find_to_nonterminal idx\n  : List.first_index_error\n      (string_beq (default_to_nonterminal idx))\n      valid_nonterminals\n    = bool_rect\n        (fun _ => option _)\n        (Some idx)\n        (None)\n        (Compare_dec.leb (S idx) (List.length valid_nonterminals)).\n  Proof.\n    pose proof (nonterminals_unique G) as HNoDup.\n    hnf in HNoDup.\n    unfold pregrammar_nonterminals in *.\n    destruct (Compare_dec.leb (S idx) (List.length valid_nonterminals)) eqn:H0; simpl;\n      [ apply Compare_dec.leb_complete in H0\n      | apply Compare_dec.leb_complete_conv in H0 ].\n      { generalize dependent idx.\n        unfold default_to_nonterminal, default_to_nonterminal, Valid_nonterminals, grammar_of_pregrammar, pregrammar_nonterminals.\n        replace valid_nonterminals with (uniquize string_beq valid_nonterminals) by (rewrite HNoDup; reflexivity).\n        induction valid_nonterminals as [|x xs IHxs].\n        { simpl; intros; omega. }\n        { simpl.\n          simpl in *.\n          destruct (list_bin string_beq x (uniquize string_beq xs)) eqn:H''; try assumption.\n          { apply (f_equal (@List.length _)) in HNoDup.\n            simpl in *.\n            pose proof (uniquize_shorter xs string_beq) as H'.\n            rewrite HNoDup in H'.\n            exfalso; clear -H'.\n            omega. }\n          apply (f_equal (@List.tl _)) in HNoDup; simpl in *.\n          specialize (IHxs HNoDup).\n          intros [|idx].\n          { simpl.\n            rewrite (string_lb eq_refl); trivial. }\n          { simpl; intros H'.\n            specialize (IHxs idx (Le.le_S_n _ _ H')).\n            rewrite first_index_helper_first_index_error, IHxs by omega.\n            apply first_index_error_Some_correct in IHxs.\n            repeat match goal with\n                     | _ => exact (@string_lb)\n                     | _ => progress simpl in *\n                     | [ H : and _ _ |- _ ] => destruct H\n                     | [ H : ex _ |- _ ] => destruct H\n                     | [ |- context[if ?E then _ else _] ] => destruct E eqn:?\n                     | _ => reflexivity\n                     | [ |- Some _ = Some _ ] => apply f_equal\n                     | [ |- 0 = S _ ] => exfalso\n                     | [ H : string_beq _ _ = true |- _ ] => apply string_bl in H\n                     | _ => progress subst\n                     | [ H : _ = ?x |- _ ] => is_var x; subst x\n                     | [ H : S _ = S _ |- _ ] => apply (f_equal pred) in H\n                     | [ H : List.length (uniquize _ _) = List.length _ |- _ ]\n                       => apply uniquize_length in H\n                     | [ H : uniquize ?beq ?ls = ?ls, H' : context[uniquize ?beq ?ls] |- _ ]\n                       => rewrite H in H'\n                     | [ H : list_bin _ _ _ = false |- False ]\n                       => rewrite list_in_lb in H; [ discriminate | | ]\n                     | [ |- List.In (List.nth _ _ _) _ ] => apply List.nth_In; omega\n                     | [ |- context[List.nth_error ?n ?ls] ] => destruct (List.nth_error n ls) eqn:?\n                     | _ => congruence\n                     | _ => progress unfold BoolFacts.Bool.bool_rect_nodep in *\n                   end. } } }\n      { unfold default_to_nonterminal, default_to_nonterminal.\n        simpl.\n        rewrite List.nth_overflow by omega.\n        apply first_index_error_None_correct; intros elem H''.\n        destruct (string_beq some_invalid_nonterminal elem) eqn:H'''; trivial.\n        apply string_bl in H'''.\n        subst.\n        apply some_invalid_nonterminal_invalid' in H''; destruct H''. }\n  Qed.\n\n  Lemma list_to_productions_to_nonterminal nt\n  : Lookup_string G (default_to_nonterminal nt)\n    = Lookup_idx G nt.\n  Proof.\n    unfold Lookup_string, Lookup_idx.\n    unfold list_to_productions at 1; simpl.\n    unfold productions, production in *.\n    rewrite <- find_first_index_error by exact bl.\n    rewrite default_find_to_nonterminal.\n    set (ls' := pregrammar_productions G); clearbody ls'.\n    revert nt; induction ls' as [|x xs IHxs]; simpl; intro nt;\n    destruct nt; simpl; trivial;\n    rewrite <- IHxs; clear IHxs.\n    edestruct @Compare_dec.leb; simpl; reflexivity.\n  Qed.\n\n  Lemma nth_error_default_to_nonterminal nt_idx\n    : List.nth_error (pregrammar_productions G) nt_idx\n      = if nt_idx <? List.length (pregrammar_productions G)\n        then Some (default_to_nonterminal nt_idx, Lookup_idx G nt_idx)\n        else None.\n  Proof.\n    destruct (nt_idx <? List.length (pregrammar_productions G)) eqn:Hlt.\n    { apply Nat.ltb_lt in Hlt.\n      unfold Lookup_idx, default_to_nonterminal.\n      rewrite !nth_error_nth.\n      repeat match goal with\n             | _ => reflexivity\n             | _ => discriminate\n             | _ => omega\n             | _ => break_innermost_match_step\n             | _ => progress subst\n             | _ => progress destruct_head' sig\n             | _ => progress destruct_head' and\n             | [ H : ?x = Some ?y, H' : ?x = Some ?z |- _ ]\n               => assert (y = z) by congruence; (subst y || subst z)\n             | [ H : ?x = Some _ |- ?x = _ ] => rewrite H\n             | [ H : List.nth_error (List.map _ _) _ = Some _ |- _ ]\n               => apply ListFacts.nth_error_map'_strong in H\n             | [ H : List.nth_error (List.map ?f ?ls) ?idx = None |- _ ]\n               => let H' := fresh in\n                  destruct (List.nth_error ls idx) eqn:H';\n                    [ eapply List.map_nth_error in H'; rewrite H in H'; congruence\n                    | clear H ]\n             | _ => progress destruct_head' prod\n             | [ |- None = Some _ ] => exfalso\n             | [ H : List.nth_error _ _ = None |- False ]\n               => apply List.nth_error_None in H\n             end. }\n    { apply List.nth_error_None.\n      apply Nat.ltb_ge in Hlt; assumption. }\n  Qed.\n\n  Section index.\n    Context (idx : default_production_carrierT).\n\n    Let nt_idx := fst idx.\n    Let nts := (Lookup_idx G nt_idx).\n    Let ps_idx := List.length nts - S (fst (snd idx)).\n    Let drop_count := snd (snd idx).\n    Let ps := (List.nth ps_idx nts nil).\n\n    Definition default_to_production : production Char\n    := List.drop drop_count ps.\n\n    Definition default_production_tl : default_production_carrierT\n      := (nt_idx,\n          (fst (snd idx),\n           if Compare_dec.leb (S drop_count) (List.length ps)\n           then S drop_count\n           else drop_count)).\n\n    Definition default_production_carrier_valid : bool\n      := ((Compare_dec.leb (S nt_idx) (List.length (pregrammar_productions G)))\n            && ((Compare_dec.leb (S (fst (snd idx))) (List.length nts))\n                  && (Compare_dec.leb drop_count (List.length ps))))%bool.\n  End index.\n\n  Global Instance default_production_carrier_valid_enumerable\n  : Enumerable { idx : default_production_carrierT | is_true (default_production_carrier_valid idx) }.\n  Proof.\n    exact _.\n  Defined.\nEnd grammar.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/ContextFreeGrammar/Carriers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.22858879324576603}}
{"text": "From mathcomp Require Import all_ssreflect.\n\nFrom mathcomp Require Import finmap.\n\nFrom CKB Require Import Types Parameters Forest Setfs Messages States Network ConsensusHelper.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nDefinition G_syncing (gs : GState) :=\n  exists (can_bt : BlockTree) (can_bc : Blockchain) (can_u : UserId),\n    [/\\ holds can_u gs (has_chain can_bc),\n     largest_chain gs can_bc,\n     (valid_bt can_bt /\\ has_gb can_bt /\\ can_bc = btBlockchain can_bt /\\ good_bt can_bt),\n     (forall (u' : UserId),\n       peers (user_state gs u') = rem u' (enum userid_finType)) &\n     forall (u' : UserId),\n       holds u' gs (fun us => can_bt = foldl bt_upd (btree us) (blocks_for u' gs))\n    ].\n\nDefinition sync_inv (gs : GState) :=\n  Coh gs /\\ G_syncing gs.\n\n(* sync invariant holds in the initial state *)\nLemma sync_initial_state :\n  sync_inv initGState.\nProof.\n  rewrite /sync_inv; split.\n  exact Coh_init.\n  exists initBlockTree, [:: GenesisBlock], user; split.\n  - rewrite /holds /has_chain initGState_user.\n      by rewrite /initUState btBlockchain_initBlockTree eqxx.\n  - rewrite /largest_chain /holds /has_chain => u bc.\n    rewrite initGState_user => /eqP <-.\n      by rewrite btBlockchain_initBlockTree; left.\n  - repeat split; rewrite /initBlockTree.\n    + move => h b; rewrite fnd_set; case: ifP; last by rewrite fnd_fmap0.\n        by move => /eqP ->; case => ->.\n    + by rewrite /has_gb fnd_set eqxx.\n    + by rewrite -/initBlockTree btBlockchain_initBlockTree.\n    + move => b; rewrite -/initBlockTree => I; apply /andP.\n      split; rewrite compute_blockchain_initBlockTree //;\n        by [rewrite /good_blockchain eqxx | apply: init_valid_blockchain].\n  - by move => u; rewrite initGState_user /initUState /=.\n  - rewrite /holds => u.\n      by rewrite initGState_user /initUState /=.\nQed.\n\n(* sync invariant means eventual consensus *)\nLemma sync_eventual_consensus (gs : GState) :\n  sync_inv gs -> (forall (u : UserId), blocks_for u gs == [::]) ->\n  exists (bc : Blockchain), largest_chain gs bc /\\\n                            (forall (u : UserId), holds u gs (has_chain bc)).\nProof.\n  case => C [can_bt] [can_bc] [can_u] [H1 H2 [H3 [H4 [H5 H6]]] H7 H8] Hnil.\n  exists can_bc. split => // u.\n  move: (Hnil u) => /eqP Hnilb.\n  move: (H8 u). rewrite Hnilb /=.\n    by rewrite /has_chain /holds H5 => <-.\nQed.\n\n(* sync invariant holds as long as user states do not change *)\nLemma sync_no_change (gs : GState) :\n  forall (p1 p2 : seq Packet) (u : UserId) (us : UState),\n    let: gs' := {| user_state := setfs (user_state gs) u us;\n                   inflight_msg := p1;\n                   consumed_msg := p2 |} in\n    peers us = peers (user_state gs u) ->\n    btree us = btree (user_state gs u) ->\n    (forall (u : UserId), blocks_for u gs = blocks_for u gs') ->\n    G_syncing gs -> G_syncing gs'.\nProof.\n  move => p1 p2 u us Hpeers Hbtree H.\n  rewrite /G_syncing /largest_chain /holds /user_state.\n  case => bc [bt] [can_u] [H1 H2 H3 H4 H5].\n  exists bc, bt, can_u.\n  split => //= => [|u' bc'|u'|u']; rewrite setfsNK; case: ifP.\n    by rewrite /has_chain Hbtree /=; move /eqP => <-; apply: H1.\n    by move => _; apply: H1.\n    by rewrite /has_chain Hbtree /=; move /eqP => <- ; apply: H2.\n    by move => _; apply: H2.\n    by rewrite Hpeers /=; move /eqP => ->; apply: H4.\n    by move => _; apply: H4.\n    rewrite (H5 u') H => /eqP ->.\n    by rewrite /blocks_for Hbtree /=.\n    by rewrite (H5 u') H /blocks_for /=.\nQed.\n\nLemma irrelevant_message :\n  forall (gs : GState) (u : UserId) (p : Packet),\n    p \\in inflight_msg gs -> (forall (b : Block), msg p != BlkMsg b)->\n    blocks_for_rec [seq p0 <- inflight_msg gs | dst p0 == u] =\n    blocks_for_rec [seq p0 <- rem p (inflight_msg gs) | dst p0 == u].\nProof.\n  move => gs u p /rem_split => Hex Hn.\n  case: Hex => p1 [p2] [P_ext [P_nin P_rem]].\n  rewrite P_rem P_ext !filter_cat !blocks_for_split /=.\n  case: ifP => //= D.\n  case M: (msg p) => //= [b'].\n    by contradict M; apply /eqP.\nQed.\n\nLemma irrelevant_broadcast :\n  forall (u : UserId) (prs : seq UserId) (ps : seq Packet) (a : pred Packet) (m : Message),\n    (forall (b : Block), m != BlkMsg b) ->\n    blocks_for_rec [seq p <- ps ++ emitBroadcast u prs m | a p] =\n    blocks_for_rec [seq p <- ps | a p].\nProof.\n  move => u; elim => [|i prs IH] ps a m Hn /=; first by rewrite cats0.\n  rewrite -(IH ps a m Hn).\n  rewrite !filter_cat !blocks_for_split /=.\n  case: ifP => //=; case: m Hn => [b|ts|hs] Hn;\n    by [move: (Hn b); rewrite eqxx |].\nQed.\n\nLemma filter_all_nil {T : Type} :\n  forall (a : pred T) (s : seq T),\n    all (fun x => ~~ a x) s -> [seq t <- s | a t] = [::].\nProof.\n  move => a; elim => [|h s IH] => //=.\n  move => /andP [/negPf N A].\n    by rewrite N; apply: IH.\nQed.\n\nLemma relevant_broadcast :\n  forall (from u : UserId) (b : Block) (prs : seq UserId),\n  uniq prs -> u \\in prs -> VAF b ->\n  blocks_for_rec [seq p <- emitBroadcast from prs (BlkMsg b) | dst p == u] = [::b].\nProof.\n  move => from u b prs Uniq In V.\n  rewrite /emitBroadcast.\n  elim: prs Uniq In => [|p prs IH] Uniq In //.\n  move: Uniq => /= /andP [Hn Uniq].\n  move: In; rewrite inE => /orP; case => [/eqP E | H].\n  - subst p; rewrite eqxx /= V.\n    suff S : all (fun x => dst x != u) [seq {| src := from; dst := t; msg := BlkMsg b |} | t <- prs]\n      by rewrite filter_all_nil => //.\n    elim: prs Hn Uniq {IH} => [|p prs IH] //=.\n    rewrite inE negb_or => /andP; case => [Neq Nin].\n    move /andP => [PNin Uniq]; apply /andP; split; last by apply: IH.\n      by apply /negP; rewrite eq_sym; apply /negP.\n  - case: ifP => /eqP U; last by apply: IH.\n      by subst p; move: Hn; rewrite H.\nQed.\n\nLemma irrelevant_broadcast' :\n  forall (from u : UserId) (b : Block) (prs : seq UserId),\n  uniq prs -> u \\notin prs ->\n  blocks_for_rec [seq p <- emitBroadcast from prs (BlkMsg b) | dst p == u] = [::].\nProof.\n  move => from u b prs Uniq Nin.\n  rewrite /emitBroadcast.\n  elim: prs Uniq Nin => [|p prs IH] Uniq Nin //.\n  move: Uniq => /= /andP [Hn Uniq].\n  move: Nin. rewrite inE negb_or => /andP; case => Neq Nin.\n  rewrite eq_sym; move /negPf: Neq => ->.\n    by apply: IH.\nQed.\n  \nLemma foldl_blocks_for_upd :\n  forall (bt : {fmap HashValue -> Block}) (p : Packet) (ps : seq Packet) (a : pred Packet) (b : Block),\n    a p -> msg p = BlkMsg b -> VAF b ->\n    foldl bt_upd bt (undup (blocks_for_rec [seq p0 <- p :: ps | a p0])) =\n    foldl bt_upd (bt_upd bt b) (undup (blocks_for_rec [seq p0 <- ps | a p0])).\nProof.\n  move => bt p ps a b A M V.\n  rewrite /= A /= M V /=.\n  case: ifP => Hin; last by done.  \n  move: Hin; elim: (blocks_for_rec [seq p0 <- ps | a p0]) bt => [|b' bs IH] bt //=.\n  rewrite inE => /orP; move => [/eqP H | H].\n  - subst b'.\n    case: ifP => Hin; first by apply: IH.\n      by rewrite /= btupd_dupE.\n  - case: ifP => Hin; first by apply: IH.\n    rewrite /= bt_updC.\n      by apply: IH.\nQed.\n\nLemma blocks_for_cat :\n  forall (s1 s2 : seq Packet) (a : pred Packet),\n    blocks_for_rec [seq p <- s1 ++ s2 | a p] =\n    blocks_for_rec [seq p <- s1 | a p] ++ blocks_for_rec [seq p <- s2 | a p].\nProof.\n  elim => [|h s1 IH] s2 a //=.\n  case: ifP => A //=.\n  case M: (msg h) => [b|ts|hs] //.\n  case V: (VAF b) => //.\n    by rewrite cat_cons IH.\nQed.\n\nLemma relevant_message :\n  forall (gs : GState) (p : Packet) (bt : {fmap HashValue -> Block}) (b : Block),\n  valid_bt bt ->\n  p \\in inflight_msg gs ->\n  msg p = BlkMsg b -> VAF b ->\n  foldl bt_upd bt.[#b b <- b] (undup (blocks_for_rec [seq p0 <- rem p (inflight_msg gs) | dst p0 == dst p]))\n  = foldl bt_upd bt (undup (blocks_for_rec [seq p0 <- inflight_msg gs | dst p0 == dst p])).\nProof.\n  move => gs p bt b Hv Hin M V.\n  move: (rem_split Hin) => [s1] [s2] [Heq [Hn Hrem]].\n  rewrite Hrem Heq !blocks_for_cat !foldl_undup_split.\n  rewrite [foldl _ (foldl _ bt _) _]foldl_comm.\n  rewrite (@foldl_blocks_for_upd bt p s2 _ b) => //.\n    by rewrite foldl_comm.\nQed.\n\nLemma irrelevant_blkmsg:\n  forall (gs : GState) (p : Packet) (bt : {fmap HashValue -> Block}) (u : UserId),\n  p \\in inflight_msg gs ->\n  dst p == u = false -> \n  foldl bt_upd bt (undup (blocks_for_rec [seq p0 <- rem p (inflight_msg gs) | dst p0 == u]))\n  = foldl bt_upd bt (undup (blocks_for_rec [seq p0 <- inflight_msg gs | dst p0 == u])).\nProof.\n  move => gs p bt u Hin Ndst.\n  move: (rem_split Hin) => [s1] [s2] [Heq [Hn Hrem]].\n  rewrite Hrem Heq !blocks_for_cat !foldl_undup_split.\n    by rewrite /= Ndst.\nQed.\n\nLemma in_seq_undup {T : eqType} :\n  forall (s : seq T) (x : T),\n    x \\in s -> x \\in undup s.\nProof.\n  elim => [|h s IH] x //=.\n  rewrite inE => /orP; move => [/eqP H | H]; case: ifP => Hp.\n    by subst h; apply: IH.\n    by rewrite H mem_head.\n    by apply: IH.\n    by rewrite inE; apply /orP; right; apply: IH.\nQed.\n\nLemma in_undup_seq {T : eqType} :\n  forall (s : seq T) (x : T),\n    x \\in undup s -> x \\in s.\nProof.\n  elim => [|h s IH] x //=.\n  case: ifP => E; rewrite inE.\n    by move => /IH => H; apply /orP; right.\n  move => /orP [/eqP H | H].\n    by rewrite H mem_head.\n    by rewrite inE; apply /orP; right; apply: IH.\nQed.\n\nLemma block_in_queue :\n  forall (p : Packet) (b : Block) (u : UserId) (gs : GState),\n    p \\in inflight_msg gs -> dst p = u -> \n    msg p = BlkMsg b -> VAF b ->\n    b \\in blocks_for u gs. \nProof.\n  move => p b u gs Hin D M V.\n  rewrite /blocks_for.\n  elim: (inflight_msg gs) Hin => [|p' ps IH] //=.\n  rewrite inE => /orP; move => [/eqP H | H].\n    by rewrite -H D eqxx /= M V in_undup.\n  case: ifP => /eqP E /=; last by apply: IH.\n  case: (msg p').\n  move => b'; case: ifP => _; last by apply: IH.\n  apply: in_seq_undup; rewrite inE; apply /orP; right.\n  apply: in_undup_seq.\n    by apply: IH.\n    by move => _; apply: IH.\n    by move => _; apply: IH.\nQed.\n\nLemma notin_rem_peers :\n  forall (u u' : UserId),\n    u \\notin rem u' (rem u (enum userid_finType)).\nProof.\n  move => u u'.\n  move: (enum_uniq userid_finType) => U.\n  have H : u \\notin rem u (enum userid_finType).\n    by rewrite mem_rem_uniqF.\n  elim: (rem u (enum userid_finType)) H => [|p ps IH] //=.\n  rewrite inE negb_or => /andP; case => /negPf Neq Nin.\n  case: ifP => //= F.\n  rewrite inE negb_or; apply /andP; split.\n    by rewrite Neq.\n    by apply: IH.\nQed.\n\nLemma rem_in_mem {T : eqType} :\n  forall (s : seq T) (x y : T),\n    x <> y -> x \\in s -> x \\in rem y s.\nProof.\n  elim => [|z s IH] x y N //.\n  rewrite inE => /orP; case => [/eqP E | H].\n  - subst z; rewrite /=.\n    move /eqP/negPf: N => ->.\n      by rewrite inE eqxx.\n  - rewrite /=; case: ifP => E //.\n    rewrite inE; apply /orP; right.\n      by apply: IH.\nQed.\n\nLemma count1_impl_in {T : eqType} :\n  forall (s : seq T) (x : T),\n    count_mem x s = 1 -> x \\in s.\nProof.\n  elim => [|y s IH] x //=.\n  case E: (y == x) => /=.\n  - move /eqP: E => -> _.\n      by rewrite inE eqxx.\n  - rewrite add0n => /IH.\n      by rewrite inE orbC => ->. \nQed.\n\nLemma in_rem_peers :\n  forall (u1 u2 u3: UserId),\n    u1 <> u3 -> u3 <> u2 ->\n    u3 \\in rem u1 (rem u2 (enum userid_finType)).\nProof.\n  move => u1 u2 u3 N1 N2.\n  have H1 : u3 \\in rem u2 (enum userid_finType).\n  apply: rem_in_mem => //. rewrite enumT.\n  apply: count1_impl_in; apply: enumP.\n  apply: rem_in_mem => //.\n    by apply /eqP/negPf; move /eqP/negPf: N1; rewrite eq_sym.\nQed.\n    \n(* final theorem *) \nTheorem sync_inv_step (gs gs' : GState) (s : Schedule) :\n  sync_inv gs -> system_step gs gs' s -> sync_inv gs'.\nProof.\n  move => [C Isync] S; split; first by apply (Coh_step S).\n  case: S;\n  (* Idle *)\n  first by move => [_ <-].\n  (* Deliver *)\n  move => p.\n  case => [C_uiq C_valid C_gb] S_dst S_flight.\n  case P: (proc_msg _ _ _ _) => [us ps] ->.\n  case M: (msg p) => [b | ts | hs]; move: P; rewrite M /=.\n  \n  (* Block message *)\n  - case: ifP => V; last first.\n    (* invalid block *)\n    case => H_useq H_peq.\n    apply: sync_no_change; [by rewrite -H_useq..| | by done].\n    rewrite -H_peq /blocks_for /emitZero cats0 /= => u.\n    move: (rem_split S_flight) => [p1] [p2] [P_ext [P_nin P_rem]].\n    rewrite P_rem P_ext !filter_cat !blocks_for_split /=.\n      by case: ifP => //=; rewrite M V.\n    (* valid block *)\n    case: Isync => can_bt [can_bc] [can_u] [I_chain I_large [I_valid [I_gb [I_ext I_good]]] I_cliq I_sub].  \n    case: ifP => P; case => H_useq H_peq; exists can_bt, can_bc, can_u; split => //.\n    (* no missing transactions *)\n    (* has chain *)\n    +  rewrite /holds /=.\n       rewrite setfsNK; case: ifP => /eqP D; last by apply: I_chain.\n       rewrite -H_useq /receive_block_update.\n       move: I_chain; rewrite /holds /has_chain D /= => /eqP.\n       move: (I_sub (dst p)); rewrite /holds.\n       case U: (user_state gs (dst p)) => [u prs bt txp] /= Hbt Hc; apply /eqP.\n       have H : btBlockchain bt = btBlockchain (foldl bt_upd bt (blocks_for can_u gs))\n         by rewrite D Hc I_ext Hbt.\n       rewrite -Hc.\n       have Hin : b \\in blocks_for can_u gs.\n       apply: block_in_queue; [exact S_flight | by rewrite D | exact M | exact V].\n       have Hvalid : valid_bt bt by move: (C_valid (dst p)); rewrite /holds U.\n       have Hgb : has_gb bt by move: (C_gb (dst p)); rewrite /holds U.\n         by rewrite (btBlockchain_seq_same Hvalid Hgb Hin) //.\n     (* largest chain *)\n     + rewrite /largest_chain /holds /= => u bc.\n       rewrite setfsNK; case: ifP => /eqP D; last by apply: I_large.\n       rewrite -H_useq /has_chain => /eqP Hc.\n       have Hgeq : can_bc >=b btBlockchain (btree (user_state gs (dst p)))\n         by apply: (I_large (dst p)); rewrite /has_chain eqxx.\n       move: (I_sub (dst p)) Hgeq Hc; rewrite /holds.\n       case U: (user_state gs (dst p)) => [id prs bt' txp] /= => Hbt Hgeq Hc.\n       have H : can_bc = btBlockchain (foldl bt_upd bt' (blocks_for (dst p) gs))\n         by rewrite I_ext Hbt.\n       have Hin : b \\in blocks_for (dst p) gs.\n       apply: block_in_queue; [exact S_flight | done | exact M | exact V].\n       subst bc.\n       have Hvalid : valid_bt bt' by move: (C_valid (dst p)); rewrite /holds U.\n       have Hgb : has_gb bt' by move: (C_gb (dst p)); rewrite /holds U.\n         by apply: (btBlockchain_seq_sub_geq Hvalid Hgb Hin Hgeq);left.\n     (* cliq property *)\n     + move => u /=.\n       rewrite setfsNK; case: ifP => /eqP D; last by apply: I_cliq.\n       rewrite -H_useq /receive_block_update /= -D.\n       move: (I_cliq u) => <-.\n         by case: (user_state gs u).\n     (* eventual consensus *)\n     + rewrite /holds /= => u.\n       rewrite setfsNK /blocks_for /=; case: ifP => /eqP D.\n       * rewrite -H_useq /receive_block_update /=.\n         case U: (user_state gs (dst p)) => [u0 prs0 bt0 txp0] => /=.\n         rewrite filter_cat blocks_for_split foldl_undup_split.\n         rewrite D relevant_message; [|by move: (C_valid u); rewrite /holds D U/=|by done..].\n         move: (I_sub u); rewrite /holds /blocks_for D U /= => <-.\n         rewrite -H_peq /=; case: ifP => S //=; rewrite /broadcast_message U /=.\n         rewrite irrelevant_broadcast' //=;\n                 [by move: (C_uiq (dst p)); rewrite /holds U /=; apply: rem_uniq |\n                  move /eqP: S => ->; rewrite mem_rem_uniqF => //].\n         by move: (C_uiq (dst p)); rewrite /holds U /=.\n         rewrite irrelevant_broadcast' //=;\n                 [by move: (C_uiq (dst p)); rewrite /holds U /=; apply: rem_uniq |\n                  move: (I_cliq (dst p)); rewrite U /= => ->; apply: notin_rem_peers].\n       * rewrite filter_cat blocks_for_split foldl_undup_split.\n         move: (I_sub u). rewrite /holds /blocks_for.\n         rewrite irrelevant_blkmsg => //; last by apply /eqP => E; apply: D; rewrite E.\n         move => Hbt; rewrite -Hbt -H_peq /=.\n         case U: (user_state gs (dst p)) => [u0 prs0 bt0 txp0] => /=.\n         case: ifP => /eqP S //=.\n         ** rewrite S /broadcast_message.\n            rewrite irrelevant_broadcast' //=;\n              [by move: (C_uiq (dst p)); rewrite /holds U /=; apply: rem_uniq |\n              rewrite mem_rem_uniqF => //; by move: (C_uiq (dst p)); rewrite /holds U /=].\n         ** rewrite /broadcast_message.\n            rewrite relevant_broadcast //=;\n            [|by move: (C_uiq (dst p)); rewrite /holds U /=; apply: rem_uniq |\n              by move: (I_cliq (dst p)); rewrite U /= => ->;apply: in_rem_peers].\n            move: (I_sub (dst p)); rewrite /holds U /=.\n            move: (b_in_blocks_for V S_flight M) => Bin Btseq.\n            suff Hin : #b b \\in can_bt by rewrite /bt_upd btupd_in_noeffect.\n              by rewrite Btseq; apply: (foldl_btupd_in_mem_seq) => //;\n                 move: (C_valid (dst p)); rewrite /holds U /=.\n     (* missing transactions *)\n     (* has chain *)  \n     + rewrite /holds /=.\n       rewrite setfsNK; case: ifP => /eqP D; last by apply: I_chain.\n       rewrite -H_useq /receive_block_update.\n       move: I_chain; rewrite /holds /has_chain D /= => /eqP.\n       move: (I_sub (dst p)); rewrite /holds.\n       case U: (user_state gs (dst p)) => [u prs bt txp] /= Hbt Hc; apply /eqP.\n       have H: btBlockchain bt = btBlockchain (foldl bt_upd bt (blocks_for can_u gs))\n         by rewrite D Hc I_ext Hbt.\n       rewrite -Hc.\n       have Hin : b \\in blocks_for can_u gs.\n       apply: block_in_queue; [exact S_flight | done | exact M | exact V].\n       have Hvalid : valid_bt bt by move: (C_valid (dst p)); rewrite /holds U.\n       have Hgb : has_gb bt by move: (C_gb (dst p)); rewrite /holds U.\n         by rewrite (btBlockchain_seq_same Hvalid Hgb Hin) //.\n     (* largest chain *)\n     + rewrite /largest_chain /holds /= => u bc.\n       rewrite setfsNK; case: ifP => /eqP D; last by apply: I_large.\n       rewrite -H_useq /has_chain => /eqP Hc.\n       have Hgeq : can_bc >=b btBlockchain (btree (user_state gs (dst p)))\n         by apply: (I_large (dst p)); rewrite /has_chain eqxx.\n       move: (I_sub (dst p)) Hgeq Hc; rewrite /holds.\n       case U: (user_state gs (dst p)) => [id prs bt' txp] /= => Hbt Hgeq Hc.\n       have H : can_bc = btBlockchain (foldl bt_upd bt' (blocks_for (dst p) gs))\n         by rewrite I_ext Hbt.\n       have Hin : b \\in blocks_for (dst p) gs.\n       apply: block_in_queue; [exact S_flight | done | exact M | exact V].\n       subst bc.\n       have Hvalid : valid_bt bt' by move: (C_valid (dst p)); rewrite /holds U.\n       have Hgb : has_gb bt' by move: (C_gb (dst p)); rewrite /holds U.\n         by apply: (btBlockchain_seq_sub_geq Hvalid Hgb Hin Hgeq); left.\n     (* cliq property *)\n     + move => u /=.\n       rewrite setfsNK; case: ifP => /eqP D; last by apply: I_cliq.\n       rewrite -H_useq /receive_block_update /= -D.\n       move: (I_cliq u) => <-.\n         by case: (user_state gs u).\n     (* eventual consensus *)\n     + rewrite /holds /= => u.\n       rewrite setfsNK /blocks_for /=; case: ifP => /eqP D.\n       * rewrite -H_useq /receive_block_update /=.\n         case U: (user_state gs (dst p)) => [u0 prs0 bt0 txp0] => /=.\n         rewrite filter_cat blocks_for_split foldl_undup_split.\n         rewrite D relevant_message; [|by move: (C_valid u); rewrite /holds D U/=|by done..].\n         move: (I_sub u); rewrite /holds /blocks_for D U /= => <-.\n         rewrite -H_peq /=; rewrite /broadcast_message U /=.\n         rewrite irrelevant_broadcast' //=;\n           [by move: (C_uiq (dst p)); rewrite /holds U /=; apply: rem_uniq |\n           by move: (I_cliq (dst p)); rewrite U /= => ->; apply: notin_rem_peers].\n       * rewrite filter_cat blocks_for_split foldl_undup_split.\n         move: (I_sub u). rewrite /holds /blocks_for.\n         rewrite irrelevant_blkmsg => //; last by apply /eqP => E; apply: D; rewrite E.\n         move => Hbt; rewrite -Hbt -H_peq /=.\n         case U: (user_state gs (dst p)) => [u0 prs0 bt0 txp0] => /=.\n         case S: (src p == u); move /eqP: S => S.\n         ** rewrite S irrelevant_broadcast' //=.\n            by move: (C_uiq (dst p)); rewrite /holds U /=; apply: rem_uniq.\n            move: (I_cliq (dst p)); rewrite U /= => ->; rewrite mem_rem_uniqF //;\n              by apply: rem_uniq; rewrite enum_uniq.\n         ** rewrite relevant_broadcast //=;\n            [|by move: (C_uiq (dst p)); rewrite /holds U /=; apply: rem_uniq |\n             by move: (I_cliq (dst p)); rewrite U /= => ->;apply: in_rem_peers].\n            move: (I_sub (dst p)); rewrite /holds U /=.\n            move: (b_in_blocks_for V S_flight M) => Bin Btseq.\n            suff Hin : #b b \\in can_bt by rewrite /bt_upd btupd_in_noeffect.\n              by rewrite Btseq; apply: (foldl_btupd_in_mem_seq) => //;\n                 move: (C_valid (dst p)); rewrite /holds U /=.\n            \n  (* Transactions message *)\n  - case: ifP => A [H_useq H_peq].\n    (* old transactions *)\n    apply: sync_no_change; [by rewrite -H_useq..| | by done].\n    rewrite -H_peq /blocks_for /emitZero cats0 /= => u.\n      by rewrite (irrelevant_message u S_flight); last rewrite M. \n    (* new transactions *)\n    apply: sync_no_change; last by done.\n    rewrite -H_useq /receive_transactions_update /=.\n      by case: (user_state gs (dst p)).  \n    rewrite -H_useq /receive_transactions_update /=.\n      by case: (user_state gs (dst p)).\n    rewrite -H_peq /blocks_for /broadcast_message => u /=.\n    case: (user_state gs (dst p)) => id prs _ _.\n    rewrite irrelevant_broadcast; last by done.\n      by rewrite (irrelevant_message u S_flight); last rewrite M.\n      \n  (* Requests message *)\n  - case => H_useq H_peq.\n    apply: sync_no_change; [by rewrite -H_useq..| | by done].\n    rewrite -H_peq /blocks_for /response_to_transactions /emitOne /= => u.\n    rewrite (irrelevant_message u S_flight); last by rewrite M.\n    rewrite filter_cat blocks_for_split /=.\n      by case: ifP => //=; rewrite cats0.\n      \n  (* InternalTransition *)\n  move => u int; case => [C_uiq C_valid C_gb] Hallow.\n  case P: (proc_int _ _ _) => [us ps] ->.\n  case I: int => [ts|]; move: P; rewrite I.\n  (* Internal transactions emit *)\n  - case => H_useq H_peq.\n    apply: sync_no_change; last by done.\n    rewrite -H_useq /receive_transactions_update /=.\n      by case: (user_state gs u).\n    rewrite -H_useq /receive_transactions_update /=.\n      by case: (user_state gs u).\n    rewrite -H_peq /blocks_for => u' /=.\n    rewrite filter_cat blocks_for_split -[emitBroadcast _ _ _]cat0s.\n      by rewrite irrelevant_broadcast /=.\n      \n  (* Internal mine blocks *)\n  - rewrite /=. case: (genProof _ _ _); last first.\n    (* failing miner *)\n    case => H_useq H_peq; rewrite -H_peq /emitZero cat0s.\n    rewrite setfs_nupd; by done.\n    move => pfv.\n    case: ifP => V; last first.\n    case => <- <-; rewrite /emitZero cat0s.\n      by rewrite setfs_nupd.\n    (* successful miner *)\n    case: Isync => can_bt [can_bc] [can_u] [I_chain I_large [I_valid [I_gb [I_ext I_good]]] I_cliq I_sub].\n    move: V; set new_b := {|\n      prev_blk := #b last_blk (btBlockchain (btree (user_state gs u)));\n      prop_txs := [seq hashPID t\n                  | t <- txpool (user_state gs u)\n                    & t\n                        \\notin [seq t0 <- txpool (user_state gs u)\n                               | commTxsValid t0 (btBlockchain (btree (user_state gs u)))]];\n      comm_txs := [seq t <- txpool (user_state gs u) | commTxsValid t (btBlockchain (btree (user_state gs u)))];\n      proof := pfv |} => V.\n    case => H_useq H_peq.\n    (* updated canonical block tree is still comlete *)\n    have Good : good_bt can_bt.[#b new_b <- new_b].\n    rewrite /good_bt => b.\n    rewrite inE dom_setf in_fset1U => /orP.\n    case => [/eqP /hashB_inj Heq | Hin].\n    + subst b.\n      move: (btBlockchain_good can_bt) => Gbc.\n      have HP : prev_blk new_b = #b last_blk (btBlockchain (btree (user_state gs u))) by done.\n      move /andP: V => [Vnew Vall].\n      move: (btupd_mint_goodness (C_valid u) (C_gb u) (btBlockchain_good _) Vnew Vall HP); case => HG HV.\n      change (good_blockchain (compute_blockchain (bt_upd can_bt new_b) new_b) &&\n              valid_blockchain (compute_blockchain (bt_upd can_bt new_b) new_b)).\n      rewrite (I_sub u) /= bt_updE foldl_comm /=.\n      rewrite good_bt_add_seq_same_chain //;\n        [by rewrite HG HV\n        |by apply: btupd_validP (C_valid u)\n        |by apply: btupd_gbP (C_gb u)].\n    + move: (I_good b Hin) => /andP; case => HG HV.\n      move: (good_bt_add_block_same_chain new_b I_valid I_gb HG).\n        by rewrite /bt_upd => ->; rewrite HG HV.\n    (* consider whether the newly mined block contributes to the canonical chain *)\n    case T: (btBlockchain (btree us) >b can_bc); last first.\n    (* Case 1: new block does not contribute to the canonical chain *)\n    move: T => /FCR_ngtT T.\n    exists can_bt.[#b new_b <- new_b], can_bc, can_u; split => //.\n    (* has chain *)\n    + rewrite /holds /=.\n      rewrite setfsNK; case: ifP => /eqP E; last by apply: I_chain.\n      subst can_u; move: I_chain; rewrite /holds -H_useq /has_chain /= => /eqP E.\n      case: T => T; first by rewrite T -H_useq /= eqxx.\n      move: E T => <-; rewrite -H_useq /= => contra.\n      contradict contra; rewrite -FCR_ngt; apply: btBlockchain_btupd_geq;\n        [apply: C_valid | apply: C_gb].\n    (* largest chain *)\n    + rewrite /largest_chain /holds /= => u' bc'.\n      rewrite setfsNK; case: ifP => /eqP E; last by  apply: I_large.\n      rewrite -H_useq /has_chain /= => /eqP <-.\n        by move: T; rewrite -H_useq /=.\n    (* valid block forest and having GenesisBlock *)\n    + repeat split; [by apply: btupd_validP => // |  apply: btupd_gbP => // |  | ].\n    (* canonical chain is still the main chain of the extended block forest *)\n    + subst can_bc.\n      move: (btBlockchain_btupd_geq new_b I_valid I_gb); case => // Gt.\n      move: (I_sub u); rewrite /holds => Sub.\n      move /andP: V => [Vnew Vall].\n      have P : (prev_blk new_b = #b last_blk (btBlockchain (btree (user_state gs u)))) by subst new_b.\n      contradict Gt; apply: btupd_within => //;\n         [by apply: C_valid|by apply: C_gb|by subst new_b|by rewrite -H_useq /= in T|exact Sub].\n    (* the extended block forest is still complete *)\n    + exact Good.\n    (* cliq property *)\n    + rewrite /= => u'.\n      rewrite setfsNK; case: ifP => /eqP E; last by apply: I_cliq.\n        by rewrite -H_useq E /=; apply: I_cliq.\n    (* eventual consensus *)\n    + rewrite /holds /= => u'.\n      rewrite setfsNK; case: ifP => /eqP E.\n      * rewrite -H_useq E /blocks_for /=.\n        rewrite filter_cat blocks_for_split foldl_undup_split.\n        rewrite -H_peq irrelevant_broadcast' /=;\n                       [|by apply: C_uiq\n                        |by rewrite I_cliq mem_rem_uniqF //; apply: enum_uniq].\n        move: (I_sub u); rewrite /holds /blocks_for => ->.    \n        change (bt_upd (foldl bt_upd (btree (user_state gs u))\n                              (undup (blocks_for_rec [seq p <- inflight_msg gs | dst p == u]))) new_b\n                = foldl bt_upd (btree (user_state gs u)).[#b new_b <- new_b]\n                              (undup (blocks_for_rec [seq p <- inflight_msg gs | dst p == u]))).\n          by rewrite bt_updE foldl_comm.\n      * rewrite /blocks_for /=.\n        rewrite filter_cat blocks_for_split foldl_undup_split.\n        rewrite -H_peq relevant_broadcast /=;\n                       [|by apply: C_uiq\n                        |by rewrite I_cliq enumT; apply: rem_in_mem => //; apply: count1_impl_in; apply: enumP\n                        |by move /andP: V => [V _]].\n        move: (I_sub u'); rewrite /holds /blocks_for => ->.\n        change (bt_upd (foldl bt_upd (btree (user_state gs u'))\n                              (undup (blocks_for_rec [seq p <- inflight_msg gs | dst p == u']))) new_b\n                = foldl bt_upd (bt_upd (btree (user_state gs u')) new_b)\n                              (undup (blocks_for_rec [seq p <- inflight_msg gs | dst p == u']))).\n          by rewrite bt_updE foldl_comm.\n    (* Case 2: new block contributes to the canonical chain *)\n    exists can_bt.[#b new_b <- new_b], (btBlockchain (btree us)), u; split => //.\n    (* has chain *)\n    + by rewrite /holds /= setfsNK eqxx -H_useq /has_chain /=.\n    (* largest chain *)\n    + rewrite /largest_chain /holds /= => u' bc'.\n      rewrite setfsNK; case: ifP => /eqP E; first by rewrite /has_chain -H_useq /= => /eqP; left.\n      rewrite /has_chain -H_useq /= => /eqP <-.\n      move: (I_large u' (btBlockchain (btree (user_state gs u')))).\n      rewrite /holds /has_chain /= => /(_ (eqxx _)) H.\n        by apply: FCR_geq_trans H; right; rewrite -H_useq /= in T.\n    (* valid block forest and having GenesisBlock *)\n    + repeat split; [by apply: btupd_validP => // | apply: btupd_gbP => // | |].\n    (* canonical chain is still the main chain of the extended block forest *)\n    + move: (I_sub u); rewrite /holds -H_useq /= => Hbt; subst can_bc.\n      rewrite -H_useq /= in T.\n      rewrite (btupd_with_new I_valid I_gb _ _ _ _ T Hbt) //;\n        [by apply: C_valid|by apply: C_gb].\n    (* the extended block forest is still complete *)\n    + exact Good.\n    (* cliq property *)\n    + rewrite /= => u'.\n        by rewrite setfsNK; case: ifP => /eqP E; [rewrite E -H_useq | ]; rewrite I_cliq.\n    (* eventual consensus *)\n    + rewrite /holds /blocks_for /= => u'.\n      rewrite setfsNK; case: ifP => /eqP E.\n      rewrite -H_useq E /=.\n      rewrite filter_cat blocks_for_split foldl_undup_split.\n      rewrite -H_peq irrelevant_broadcast' /=;\n                     [|apply: C_uiq | rewrite I_cliq mem_rem_uniqF //; apply: enum_uniq].\n      move: (I_sub u); rewrite /holds /= => ->.\n      change (bt_upd (foldl bt_upd (btree (user_state gs u))\n                          (undup (blocks_for_rec [seq p <- inflight_msg gs | dst p == u]))) new_b\n            = foldl bt_upd (btree (user_state gs u)).[#b new_b <- new_b]\n                          (undup (blocks_for_rec [seq p <- inflight_msg gs | dst p == u]))).\n        by rewrite bt_updE foldl_comm.\n      rewrite filter_cat blocks_for_split foldl_undup_split.\n      rewrite -H_peq relevant_broadcast /=;\n                     [|by apply: C_uiq\n                      |by rewrite I_cliq enumT; apply: rem_in_mem => //; apply: count1_impl_in; apply: enumP\n                      |by move /andP: V => [V _]].\n      move: (I_sub u'); rewrite /holds /blocks_for => ->.\n      change (bt_upd (foldl bt_upd (btree (user_state gs u'))\n                            (undup (blocks_for_rec [seq p <- inflight_msg gs | dst p == u']))) new_b\n              = foldl bt_upd (bt_upd (btree (user_state gs u')) new_b)\n                            (undup (blocks_for_rec [seq p <- inflight_msg gs | dst p == u']))).\n        by rewrite bt_updE foldl_comm.\nQed.\n\nLemma sync_inv_reachable :\n  forall (gs gs': GState),\n    sync_inv gs -> reachable_state gs gs' -> sync_inv gs'.\nProof.\n  move => gs gs' S R; elim: R S => //.\n  - by move => gs1 gs2 s Step Sync; apply: (sync_inv_step Sync Step).\n  - move => gs1 gs2 gs3 R12 S12 R23 H23 S1. \n      by apply: (H23 (S12 S1)).\nQed.\n  \nLemma final_consensus :\n  forall (gs : GState),\n    reachable_state initGState gs ->\n    (forall (u : UserId), blocks_for u gs == [::]) ->\n    exists (bc : Blockchain), largest_chain gs bc /\\\n                              (forall (u : UserId), holds u gs (has_chain bc)).\nProof.\n  move => gs /(sync_inv_reachable sync_initial_state).\n    by apply: sync_eventual_consensus.\nQed.\n", "meta": {"author": "luan-xiaokun", "repo": "ckb-verification", "sha": "ce52949c83b43f2768c7b9dc72396bde1fef317c", "save_path": "github-repos/coq/luan-xiaokun-ckb-verification", "path": "github-repos/coq/luan-xiaokun-ckb-verification/ckb-verification-ce52949c83b43f2768c7b9dc72396bde1fef317c/Properties/Consensus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297745935070808, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.22858877518218998}}
{"text": "Require Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.SmartMap.\nRequire Import Crypto.Compilers.Wf.\nRequire Import Crypto.Compilers.WfInversion.\nRequire Import Crypto.Compilers.TypeInversion.\nRequire Import Crypto.Compilers.ExprInversion.\nRequire Import Crypto.Compilers.RewriterWf.\nRequire Import Crypto.Compilers.Z.Syntax.\nRequire Import Crypto.Compilers.Z.OpInversion.\nRequire Import Crypto.Compilers.Z.ArithmeticSimplifier.\nRequire Import Crypto.Compilers.Z.Syntax.Equality.\nRequire Import Crypto.Compilers.Z.Syntax.Util.\nRequire Import Crypto.Util.ZUtil.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.Sum.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Crypto.Util.HProp.\n\nLocal Notation exprf := (@exprf base_type op).\nLocal Notation expr := (@expr base_type op).\nLocal Notation wff := (@wff base_type op).\nLocal Notation Wf := (@Wf base_type op).\n\nLocal Ltac fin_t :=\n  first [ exact I\n        | reflexivity\n        | congruence\n        | assumption\n        | exfalso; assumption\n        | match goal with\n          | [ |- _ /\\ False ] => exfalso\n          | [ |- False /\\ _ ] => exfalso\n          | [ |- _ /\\ _ /\\ False ] => exfalso\n          | [ |- _ /\\ False /\\ _ ] => exfalso\n          | [ |- False /\\ _ /\\ _ ] => exfalso\n          end ].\nLocal Ltac break_t_step :=\n  first [ progress subst\n        | progress inversion_option\n        | progress inversion_sum\n        | progress inversion_expr\n        | progress inversion_prod\n        | progress invert_op\n        | progress inversion_flat_type\n        | progress destruct_head'_and\n        | progress destruct_head' iff\n        | progress destruct_head'_prod\n        | progress destruct_head'_sig\n        | progress specialize_by reflexivity\n        | progress eliminate_hprop_eq\n        | progress break_innermost_match_hyps_step\n        | progress break_innermost_match_step\n        | progress break_match_hyps\n        | progress inversion_wf_constr ].\n\n\nLemma interp_as_expr_or_const_None_iff {var1 var2 t} {G e1 e2}\n      (Hwf : @wff var1 var2 G t e1 e2)\n  : @interp_as_expr_or_const var1 t e1 = None\n    <-> @interp_as_expr_or_const var2 t e2 = None.\nProof.\n  induction Hwf;\n    repeat first [ fin_t\n                 | split; congruence\n                 | progress simpl in *\n                 | progress intros\n                 | break_t_step ].\nQed.\n\nLemma interp_as_expr_or_const_None_Some {var1 var2 t} {G e1 e2 v}\n      (Hwf : @wff var1 var2 G t e1 e2)\n  : @interp_as_expr_or_const var1 t e1 = None\n    -> @interp_as_expr_or_const var2 t e2 = Some v\n    -> False.\nProof.\n  erewrite interp_as_expr_or_const_None_iff by eassumption; congruence.\nQed.\n\nLemma interp_as_expr_or_const_Some_None {var1 var2 t} {G e1 e2 v}\n      (Hwf : @wff var1 var2 G t e1 e2)\n  : @interp_as_expr_or_const var1 t e1 = Some v\n    -> @interp_as_expr_or_const var2 t e2 = None\n    -> False.\nProof.\n  erewrite <- interp_as_expr_or_const_None_iff by eassumption; congruence.\nQed.\n\nLocal Ltac pret_step :=\n  first [ fin_t\n        | progress subst\n        | progress inversion_option\n        | progress inversion_prod\n        | progress simpl in *\n        | progress inversion_wf\n        | match goal with\n          | [ H : match interp_as_expr_or_const ?e with _ => _ end = Some _ |- _ ]\n            => is_var e; destruct (interp_as_expr_or_const e) eqn:?\n          end ].\n\nFixpoint wff_as_expr_or_const {var1 var2} G {t}\n  : interp_flat_type (@inverted_expr var1) t\n    -> interp_flat_type (@inverted_expr var2) t\n    -> Prop\n  := match t with\n     | Tbase T\n       => fun z1 z2 => match z1, z2 return Prop with\n                       | const_of z1, const_of z2 => z1 = z2\n                       | gen_expr e1, gen_expr e2\n                       | neg_expr e1, neg_expr e2\n                         => wff G e1 e2\n                       | const_of _, _\n                       | gen_expr _, _\n                       | neg_expr _, _\n                         => False\n                       end\n     | Unit => fun _ _ => True\n     | Prod A B => fun a b : interp_flat_type _ A * interp_flat_type _ B\n                   => and (@wff_as_expr_or_const var1 var2 G A (fst a) (fst b))\n                          (@wff_as_expr_or_const var1 var2 G B (snd a) (snd b))\n     end.\n\nLemma wff_interp_as_expr_or_const {var1 var2 t} {G e1 e2 v1 v2}\n      (Hwf : @wff var1 var2 G t e1 e2)\n  : @interp_as_expr_or_const var1 t e1 = Some v1\n    -> @interp_as_expr_or_const var2 t e2 = Some v2\n    -> wff_as_expr_or_const G v1 v2.\nProof.\n  induction Hwf;\n    repeat first [ progress subst\n                 | progress inversion_option\n                 | progress simpl in *\n                 | progress cbn [wff_as_expr_or_const]\n                 | reflexivity\n                 | break_innermost_match_hyps_step\n                 | intro\n                 | match goal with\n                   | [ H : forall z, Some _ = Some z -> _ |- _ ] => specialize (H _ eq_refl)\n                   | [ |- context[match ?e with _ => _ end] ]\n                     => is_var e; invert_one_op e\n                   end\n                 | break_innermost_match_step\n                 | solve [ auto with wf ] ].\nQed.\n\nLocal Ltac pose_wff _ :=\n  match goal with\n  | [ H1 : _ = Some _, H2 : _ = Some _, Hwf : wff _ _ _ |- _ ]\n    => pose proof (wff_interp_as_expr_or_const Hwf H1 H2); clear H1 H2\n  end.\n\nLemma Wf_SimplifyArith {convert_adc_to_sbb} {t} (e : Expr t)\n      (Hwf : Wf e)\n  : Wf (SimplifyArith convert_adc_to_sbb e).\nProof.\n  apply Wf_RewriteOp; [ | assumption ].\n  intros ???????? Hwf'; unfold simplify_op_expr.\n  repeat match goal with\n         | [ H : ?T |- ?T ] => exact H\n         | [ H : False |- _ ] => exfalso; assumption\n         | [ |- True ] => exact I\n         | [ H : false = true |- _ ] => exfalso; clear -H; discriminate\n         | [ H : true = false |- _ ] => exfalso; clear -H; discriminate\n         | [ H : None = Some _ |- _ ] => exfalso; clear -H; discriminate\n         | [ H : Some _ = None |- _ ] => exfalso; clear -H; discriminate\n         | [ H : TT = Op _ _ |- _ ] => exfalso; clear -H; discriminate\n         | [ H : invert_Op ?e = None, H' : wff _ (Op ?opc _) ?e |- _ ]\n           => progress (exfalso; clear -H H'; generalize dependent opc; intros; try (is_var e; destruct e))\n         | [ H : invert_Op ?e = None, H' : wff _ ?e (Op ?opc _) |- _ ]\n           => progress (exfalso; clear -H H'; generalize dependent opc; intros; try (is_var e; destruct e))\n         | _ => progress destruct_head'_and\n         | _ => progress subst\n         | _ => progress destruct_head'_prod\n         | _ => progress destruct_head'_sig\n         | _ => progress destruct_head'_sigT\n         | _ => inversion_base_type_constr_step\n         | _ => inversion_wf_step_constr\n         | _ => progress invert_expr_subst\n         | _ => progress rewrite_eta_match_base_type_impl\n         | [ H : ?x = ?x |- _ ] => clear H || (progress eliminate_hprop_eq)\n         | [ H : match ?e with @const_of _ _ _ => _ = _ | _ => _ end |- _ ]\n           => is_var e; destruct e\n         | [ H : match ?e with @const_of _ _ _ => False | _ => _ end |- _ ]\n           => is_var e; destruct e\n         | [ H1 : _ = Some _, H2 : _ = None, Hwf : wff _ _ _ |- _ ]\n           => pose proof (interp_as_expr_or_const_Some_None Hwf H1 H2); clear H1 H2\n         | [ H1 : _ = None, H2 : _ = Some _, Hwf : wff _ _ _ |- _ ]\n           => pose proof (interp_as_expr_or_const_None_Some Hwf H1 H2); clear H1 H2\n         | [ |- wff _ (Op _ _) (LetIn _ _) ] => exfalso\n         | [ |- wff _ (LetIn _ _) (Op _ _) ] => exfalso\n         | [ |- wff _ (Pair _ _) (LetIn _ _) ] => exfalso\n         | [ |- wff _ (LetIn _ _) (Pair _ _) ] => exfalso\n         | _ => pose_wff ()\n         | _ => progress cbn [fst snd projT1 projT2 interp_flat_type wff_as_expr_or_const eq_rect invert_Op] in *\n         | [ |- wff _ _ _ ] => constructor; intros\n         | [ H : match ?e with @const_of _ _ _ => _ | _ => _ end |- _ ]\n           => is_var e; destruct e\n         | [ |- context[match @interp_as_expr_or_const ?var ?t ?e with _ => _ end] ]\n           => destruct (@interp_as_expr_or_const var t e) eqn:?\n         | [ |- context[match base_type_eq_semidec_transparent ?t1 ?t2 with _ => _ end] ]\n           => destruct (base_type_eq_semidec_transparent t1 t2)\n         | [ |- context[match @invert_Op ?base_type ?op ?var ?t ?e with _ => _ end] ]\n           => destruct (@invert_Op base_type op var t e) eqn:?\n         | [ |- context[if BinInt.Z.eqb ?x ?y then _ else _] ]\n           => destruct (BinInt.Z.eqb x y) eqn:?\n         | [ |- context[if BinInt.Z.ltb ?x ?y then _ else _] ]\n           => destruct (BinInt.Z.ltb x y) eqn:?\n         | [ |- context[match ?e with @OpConst _ _ => _ | _ => _ end] ]\n           => is_var e; destruct e\n         | [ |- context[match ?e with @OpConst _ _ => _ | _ => _ end] ]\n           => is_var e; invert_one_op e; try exact I; break_innermost_match_step; intros\n         | [ |- List.In _ _ ] => progress (simpl; auto)\n         | _ => break_innermost_match_step\n         end.\nQed.\n\nHint Resolve Wf_SimplifyArith : wf.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Compilers/Z/ArithmeticSimplifierWf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2285809382931342}}
{"text": "(*\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\nRequire Import String.\nRequire Import List.\nRequire Import Arith.\nRequire Import EquivDec.\nRequire Import Utils.\nRequire Import DataRuntime.\nRequire Import OQL.\n\nSection OQLSize.\n  Context {fruntime:foreign_runtime}.\n\n  Fixpoint oql_expr_size (e:oql_expr) : nat \n    := match e with\n         | OConst d => 1\n         | OVar v => 1\n         | OTable v => 1\n         | OBinop op n₁ n₂ => S (oql_expr_size n₁ + oql_expr_size n₂)\n         | OUnop op n₁ => S (oql_expr_size n₁)\n         | OSFW se el we oe =>\n           let from_size :=\n               fold_left (fun x => fun e => x+oql_in_size e) el 0\n           in\n           S (oql_select_size se + from_size + oql_where_size we + oql_order_size oe)\n       end\n  with oql_select_size (se:oql_select_expr) :=\n    match se with\n    | OSelect e => oql_expr_size e\n    | OSelectDistinct e => oql_expr_size e\n    end\n  with oql_in_size (ie:oql_in_expr) :=\n    match ie with\n    | OIn v e => oql_expr_size e\n    | OInCast v brand_names e => oql_expr_size e\n    end\n  with oql_where_size (we:oql_where_expr) :=\n    match we with\n    | OTrue => 0\n    | OWhere e => oql_expr_size e\n    end\n  with oql_order_size (oe:oql_order_by_expr) :=\n    match oe with\n    | ONoOrder => 0\n    | OOrderBy e _ => oql_expr_size e\n    end.\n\n  Fixpoint oql_query_program_size (oq:oql_query_program) : nat\n    := match oq with\n      | ODefineQuery s e rest => S (oql_expr_size e + oql_query_program_size rest)\n      | OUndefineQuery s rest => S (oql_query_program_size rest)\n      | OQuery e => S (oql_expr_size e)\n      end.\n\n  Definition oql_size (q:oql) : nat\n    := oql_query_program_size q.\n  \nEnd OQLSize.\n\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/OQL/Lang/OQLSize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22849830350066827}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\n\nSet Implicit Arguments.\n\n\nModule MemoryMerge.\n  Lemma add_lower_add\n        mem0 loc from to msg1 msg2 mem1 mem2\n        (ADD1: Memory.add mem0 loc from to msg1 mem1)\n        (LOWER2: Memory.lower mem1 loc from to msg1 msg2 mem2):\n    Memory.add mem0 loc from to msg2 mem2.\n  Proof.\n    inv ADD1. inv ADD. inv LOWER2. inv LOWER.\n    rewrite LocFun.add_add_eq. econs; auto.\n    unfold Cell.add in *.\n    destruct r, r0. ss. subst.\n    unfold LocFun.add. condtac; [|congr]. s.\n    rewrite DOMap.add_add_eq. econs; auto.\n  Qed.\n\n  Lemma split_lower_split\n        mem0 loc ts1 ts2 ts3 msg2 msg2' msg3 mem1 mem2\n        (SPLIT1: Memory.split mem0 loc ts1 ts2 ts3 msg2 msg3 mem1)\n        (LOWER2: Memory.lower mem1 loc ts1 ts2 msg2 msg2' mem2):\n    Memory.split mem0 loc ts1 ts2 ts3 msg2' msg3 mem2.\n  Proof.\n    inv SPLIT1. inv SPLIT. inv LOWER2. inv LOWER.\n    rewrite LocFun.add_add_eq. econs; auto.\n    unfold Cell.split in *.\n    destruct r, r0. ss. subst.\n    unfold LocFun.add. condtac; [|congr]. s.\n    rewrite DOMap.add_add_eq. econs; auto.\n  Qed.\n\n  Lemma lower_lower_lower\n        mem0 loc from to msg0 msg1 msg2 mem1 mem2\n        (LOWER1: Memory.lower mem0 loc from to msg0 msg1 mem1)\n        (LOWER2: Memory.lower mem1 loc from to msg1 msg2 mem2):\n    Memory.lower mem0 loc from to msg0 msg2 mem2.\n  Proof.\n    inv LOWER1. inv LOWER. inv LOWER2. inv LOWER.\n    rewrite LocFun.add_add_eq. econs; auto.\n    unfold Cell.lower in *.\n    destruct r, r0. ss. subst.\n    unfold LocFun.add. condtac; [|congr]. s.\n    rewrite DOMap.add_add_eq. econs; auto.\n    etrans; eauto.\n  Qed.\n\n  Lemma promise_promise_promise\n        loc from to msg1 msg2 promises0 promises1 promises2 mem0 mem1 mem2 kind\n        (PROMISE1: Memory.promise promises0 mem0 loc from to msg1 promises1 mem1 kind)\n        (PROMISE2: Memory.promise promises1 mem1 loc from to msg2 promises2 mem2 (Memory.op_kind_lower msg1)):\n    Memory.promise promises0 mem0 loc from to msg2 promises2 mem2 kind.\n  Proof.\n    inv PROMISE2. inv PROMISE1.\n    - econs; eauto.\n      + eapply add_lower_add; eauto.\n      + eapply add_lower_add; eauto.\n      + i. inv MEM. inv LOWER. inv MSG_LE; ss; eauto.\n        eapply ATTACH; eauto. ss.\n    - econs; eauto.\n      + eapply split_lower_split; eauto.\n      + eapply split_lower_split; eauto.\n    - econs; eauto.\n      + eapply lower_lower_lower; eauto.\n      + eapply lower_lower_lower; eauto.\n    - exploit Memory.remove_get0; try exact PROMISES0. i. des.\n      exploit Memory.lower_get0; try exact PROMISES. i. des.\n      congr.\n  Qed.\n\n  Lemma promise_write_write\n        loc from to msg1 msg promises0 promises1 promises2 mem0 mem1 mem2 kind\n        (PROMISE1: Memory.promise promises0 mem0 loc from to msg1 promises1 mem1 kind)\n        (PROMISE2: Memory.write promises1 mem1 loc from to msg promises2 mem2 (Memory.op_kind_lower msg1)):\n    Memory.write promises0 mem0 loc from to msg promises2 mem2 kind.\n  Proof.\n    inv PROMISE2.\n    exploit promise_promise_promise; try exact PROMISE1; eauto.\n  Qed.\n\n  Lemma add_remove\n        loc from to msg mem0 mem1 mem2\n        (ADD1: Memory.add mem0 loc from to msg mem1)\n        (REMOVE2: Memory.remove mem1 loc from to msg mem2):\n    mem0 = mem2.\n  Proof.\n    apply Memory.ext. i. symmetry.\n    exploit Memory.add_get0; eauto. i. des.\n    erewrite Memory.remove_o; eauto. condtac; ss.\n    - des. subst. rewrite GET. ss.\n    - guardH o.\n      erewrite Memory.add_o; eauto. condtac; ss; eauto.\n  Qed.\nEnd MemoryMerge.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/prop/MemoryMerge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22849829711594613}}
{"text": "Require Export EnvLibA.\nRequire Export RelLibA.\nRequire Export PRelLibA.\n\nRequire Export Coq.Program.Equality.\nRequire Import Coq.Init.Specif.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Omega.\nRequire Import Coq.Lists.List.\nRequire Import Bool. \nRequire Import Coq.Logic.ProofIrrelevance.\n\nRequire Import StaticSemA.\nRequire Import DynamicSemA.\nRequire Import TRInductA.\nRequire Import WeakenA.\nRequire Import TSoundnessA.\nRequire Import IdModTypeA.\nRequire Import IdModPip.\nRequire Import DetermA.\nRequire Import AbbrevA.\nRequire Import HoareA.\nRequire Import THoareA.\nRequire Import Lib.\nRequire Import Pip_state.\nRequire Import Pip_stateLib.\nRequire Import Pip_Prop.\nRequire Import Pip_DependentTypeLemmas.\nRequire Import Pip_InternalLemmas.\nRequire Import Pip_writeVirtualInv_Lemmas.\nRequire Import Hoare_getFstShadow.\nImport ListNotations.\n\nModule Hoare_Test_VirtualInv.\n\nModule VirtualInv := Hoare_Test_FstShadow.\nExport VirtualInv.\n\n\n\n(**************************************************)\n\n(******* Program *)\n\n(** WriteVirtualInv -page -index -vaddress : writes the vaddress at key (page,index) in memory *)\n\nDefinition xf_writeVirtual (p: page) (i: index) (v: vaddr) : XFun unit unit := {|\n   b_mod := fun s _ => (writeVirtualInternal p i v s,tt)\n|}.\n\nInstance VT_unit : ValTyp unit.\n\nDefinition WriteVirtual (p: page) (i: index) (v: vaddr) : Exp :=\n  Modify unit unit VT_unit VT_unit (xf_writeVirtual p i v) (QV (cst unit tt)).  \n\n\n(******* Useful Lemmas *)\n\nLemma writeVirtualWp  table idx (addr : vaddr)  (P : Value -> state -> Prop) (fenv: funEnv) (env: valEnv) :\n{{fun  s => P (cst unit tt) {| currentPartition := currentPartition s;\n  memory := add table idx (VA addr) (memory s) beqPage beqIndex |} }} \nfenv >> env >> WriteVirtual table idx addr  {{P}}.\nProof.\nunfold THoareTriple_Eval.\nintros. \ninversion X;subst.\ninversion X0;subst.\nrepeat apply inj_pair2 in H6.\nrepeat apply inj_pair2 in H8.\nsubst.\nunfold xf_writeVirtual, b_eval, b_exec, b_mod in *.\nsimpl in *.\ninversion X1;subst.\nauto.\ninversion X2.\ninversion X2.\nQed.\n\n(******* Hoare Triple *)\n\nLemma writeVirtualInvNewProp (p : page) (i:index) (v:vaddr) (fenv: funEnv) (env: valEnv) :\n{{fun _ => True}}\nfenv >> env >> WriteVirtual p i v\n{{fun _ s => readVirtualInternal p i s.(memory) =  Some v}}.\nProof.\nunfold THoareTriple_Eval.\nintros.\nclear H k3 t k2 k1 tenv ftenv.\ninversion X;subst.\ninversion X0;subst.\nrepeat apply inj_pair2 in H5.\napply inj_pair2 in H7.\nsubst.\nunfold b_eval, b_exec, xf_writeVirtual, b_mod in *.\nsimpl in *.\ninversion X1;subst.\nunfold writeVirtualInternal.\nsimpl.\nunfold add.\nunfold readVirtualInternal.\nsimpl.\nspecialize beqPairsTrue with p i p i.\nintros.\nintuition.\nrewrite H.\nreflexivity.\ninversion X2.\ninversion X2.\nQed.\n\nLemma writeVirtualInv (vaInCurrentPartition vaChild: vaddr)  currentPart\ncurrentShadow descChild idxDescChild ptDescChild ptVaInCurPart idxvaInCurPart\nvainve isnotderiv currentPD ptVaInCurPartpd accessiblesrc presentmap ptDescChildpd idxDescChild1\npresentDescPhy phyDescChild pdChildphy ptVaChildpd idxvaChild presentvaChild phyVaChild \nsh2Childphy ptVaChildsh2 level (fenv: funEnv) (env: valEnv) :\nisnotderiv && accessiblesrc && presentmap && negb presentvaChild = true -> \nnegb presentDescPhy = false -> \n{{ fun s : state => propagatedPropertiesAddVaddr s vaInCurrentPartition vaChild currentPart\ncurrentShadow descChild idxDescChild ptDescChild ptVaInCurPart idxvaInCurPart\nvainve isnotderiv currentPD ptVaInCurPartpd accessiblesrc presentmap ptDescChildpd idxDescChild1\npresentDescPhy phyDescChild pdChildphy ptVaChildpd idxvaChild presentvaChild phyVaChild \nsh2Childphy ptVaChildsh2 level }} \n  fenv >> env >> WriteVirtual ptVaChildsh2 idxvaChild vaInCurrentPartition \n  {{ fun _ s => propagatedPropertiesAddVaddr s vaInCurrentPartition vaChild currentPart\ncurrentShadow descChild idxDescChild ptDescChild ptVaInCurPart idxvaInCurPart\nvainve isnotderiv currentPD ptVaInCurPartpd accessiblesrc presentmap ptDescChildpd idxDescChild1\npresentDescPhy phyDescChild pdChildphy ptVaChildpd idxvaChild presentvaChild phyVaChild \nsh2Childphy ptVaChildsh2 level /\\ \nreadVirtualInternal ptVaChildsh2 idxvaChild s.(memory) = Some vaInCurrentPartition }}.\nProof.\nintros.\neapply weakenEval.\neapply writeVirtualWp.\nsimpl; intros.\nsplit. \nunfold propagatedPropertiesAddVaddr in *.\nassert(Hlookup :exists entry, \n lookup ptVaChildsh2 idxvaChild (memory s) beqPage beqIndex = Some (VA entry)).\n{ assert(Hva : isVA ptVaChildsh2 (getIndexOfAddr vaChild fstLevel) s) by intuition.\n  unfold isVA in *.\n  assert(Hidx :  getIndexOfAddr vaChild fstLevel = idxvaChild) by intuition.\n clear H.\n subst. \n destruct(lookup ptVaChildsh2 (getIndexOfAddr vaChild fstLevel)\n          (memory s) beqPage beqIndex);intros; try now contradict Hva.\n destruct v; try now contradict Hva.\n do 2 f_equal.\n exists v;trivial. }\n destruct Hlookup as (entry & Hlookup).\nintuition try assumption.\n(** partitionsIsolation **)\n+ apply partitionsIsolationUpdateSh2 with entry;trivial.\n(** kernelDataIsolation **)\n+ apply kernelDataIsolationUpdateSh2 with entry;trivial.\n(** verticalSharing **)\n+ apply verticalSharingUpdateSh2 with entry;trivial. \n(** consistency **)\n+ apply consistencyUpdateSh2 with\n    entry vaChild\n    currentPart currentShadow descChild idxDescChild ptDescChild\n    ptVaInCurPart idxvaInCurPart vainve isnotderiv currentPD\n    ptVaInCurPartpd accessiblesrc presentmap ptDescChildpd idxDescChild1 presentDescPhy\n    phyDescChild pdChildphy ptVaChildpd presentvaChild phyVaChild\n    sh2Childphy level;trivial.\n  unfold propagatedPropertiesAddVaddr ;intuition.\n(** Propagated properties **)\n+ rewrite <- nextEntryIsPPUpdateSh2;trivial.\n  exact Hlookup.\n+ apply isVEUpdateSh2 with entry;trivial.\n+ apply getTableAddrRootUpdateSh2 with entry;trivial.\n+ apply entryPDFlagUpdateSh2 with entry;trivial.\n+ apply isVEUpdateSh2 with entry;trivial.\n+ apply getTableAddrRootUpdateSh2 with entry;trivial.\n+ apply isEntryVAUpdateSh2 with entry;trivial.\n+ rewrite <- nextEntryIsPPUpdateSh2;trivial.\n  exact Hlookup.\n+ apply isPEUpdateSh2 with entry;trivial.\n+ apply getTableAddrRootUpdateSh2 with entry;trivial.\n+ apply entryUserFlagUpdateSh2 with entry;trivial.\n+ apply entryPresentFlagUpdateSh2 with entry;trivial.\n+ apply isPEUpdateSh2 with entry;trivial.\n+ apply getTableAddrRootUpdateSh2 with entry;trivial.\n+ apply entryPresentFlagUpdateSh2 with entry;trivial.\n+ apply isEntryPageUpdateSh2  with entry;trivial.\n+ assert(Hchildren : forall part, getChildren part\n     {|\n     currentPartition := currentPartition s;\n     memory := add ptVaChildsh2 idxvaChild(VA vaInCurrentPartition) (memory s) beqPage\n                 beqIndex |} = getChildren part s).\n  { intros; symmetry; apply getChildrenUpdateSh2 with entry;trivial. } \n  rewrite Hchildren in *;trivial.\n+ rewrite <- nextEntryIsPPUpdateSh2;trivial.\n  exact Hlookup.\n+ apply isPEUpdateSh2 with entry;trivial.\n+ apply getTableAddrRootUpdateSh2 with entry;trivial.\n+ apply entryPresentFlagUpdateSh2 with entry;trivial.\n+ apply isEntryPageUpdateSh2  with entry;trivial.\n+ rewrite <- nextEntryIsPPUpdateSh2;trivial.\n  exact Hlookup.\n+ apply isVAUpdateSh2 with entry;trivial.\n+ apply getTableAddrRootUpdateSh2 with entry;trivial.\n(** new property **)\n+ unfold readVirtualInternal.\n  cbn.\n  assert (Htrue : beqPairs (ptVaChildsh2, idxvaChild) (ptVaChildsh2, idxvaChild) beqPage\n      beqIndex = true). \n  apply beqPairsTrue;split;trivial.\n  rewrite Htrue.\n  trivial.\nQed.\n\nEnd Hoare_Test_VirtualInv.\n", "meta": {"author": "CherifSami", "repo": "coq_internship", "sha": "9af1cca45a30d628acc158cb9babff5ed0eb9a51", "save_path": "github-repos/coq/CherifSami-coq_internship", "path": "github-repos/coq/CherifSami-coq_internship/coq_internship-9af1cca45a30d628acc158cb9babff5ed0eb9a51/developmentCS/Hoare_writeVirtualInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.22844636044777086}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Export EventOrdering.\n\n\nSection correct.\n\n  Context { pn  : @Node }.\n  Context { pk  : @Key }.\n  Context { m   : @Msg }.\n\n  Local Open Scope eo.\n\n  (* This defines what it means for a node [n] to be correct in a partial cut [L]\n     of an event ordering [eo]: the keys of all events [e1] happening before [e]\n     (an event of the partial cut [L]) at location [n], are different from the keys\n     held at other locations at events [e2] prior to [e] *)\n  Definition correct (eo : EventOrdering) (n : name) (L : list Event) :=\n    forall e e1 e2,\n      In e L\n      -> e1 ≼ e\n      -> e2 ≼ e\n      -> loc e1 = n\n      -> loc e2 <> n\n      -> disjoint (lkm_sending_keys (keys e1)) (lkm_sending_keys (keys e2)).\n\n  Definition correct_e {eo : EventOrdering} (e : Event) :=\n    correct eo (loc e) [e].\n\nEnd correct.\n", "meta": {"author": "vrahli", "repo": "Velisarios", "sha": "6fb353b18610cd79210755fcc90123536c367aaa", "save_path": "github-repos/coq/vrahli-Velisarios", "path": "github-repos/coq/vrahli-Velisarios/Velisarios-6fb353b18610cd79210755fcc90123536c367aaa/model/correct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22844636044777084}}
{"text": "Require Import Core.Core Core.VstTactics Core.StructNormalizer VstLib\n        ErrorWithWriter.\nRequire Import Core.Tactics.\n               \nRequire Import VST.floyd.proofauto.\nRequire Import Clight.ber_tlv_tag Exec.Ber_tlv_tag_serialize.\nRequire Import Core.Notations Core.SepLemmas.\n\nInstance CompSpecs : compspecs. Proof. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. Proof. mk_varspecs prog. Defined.\n\nOpen Scope Z.\n\nDefinition ber_tlv_tag_serialize_spec : ident * funspec :=\n  DECLARE _ber_tlv_tag_serialize\n  WITH tag : int, buf_b : block, buf_ofs : ptrofs, buf_size : Z\n  PRE[tuint, tptr tvoid, tuint]\n    PROP(buf_size = 0 \\/ buf_size = 32;\n         Ptrofs.unsigned buf_ofs + buf_size < Ptrofs.modulus)\n    PARAMS(Vint tag; (Vptr buf_b buf_ofs); Vint (Int.repr buf_size))\n    GLOBALS()\n    SEP(data_at Tsh (tarray tuchar buf_size)\n                    (default_val (tarray tuchar buf_size)) \n                    (Vptr buf_b buf_ofs))\n  POST[tuint]\n    PROP()\n    LOCAL(temp ret_temp\n               (Vint (Int.repr (snd (tag_serialize tag (Int.repr buf_size))))))\n    SEP(let (ls, z) := tag_serialize tag (Int.repr buf_size) in\n        data_at Tsh (tarray tuchar buf_size)\n                         (map Vint ls \n                              ++ sublist (len ls) buf_size \n                             (default_val (tarray tuchar buf_size)))\n                         (Vptr buf_b buf_ofs)).\n\nDefinition Gprog := ltac:(with_library prog [ber_tlv_tag_serialize_spec]).\n\nOpen Scope IntScope.\n\nTheorem ber_tlv_tag_serialize_correct : \n  semax_body Vprog Gprog (normalize_function f_ber_tlv_tag_serialize composites)\n             ber_tlv_tag_serialize_spec.\nAdmitted.\n(* Proof.\n  start_function.\n  remember (Int.shru tag (Int.repr 2)) as tval.\n  remember (Int.zero_ext 8 (((tag & Int.repr 3) << Int.repr 6) or tval)) as e0. \n  remember (default_val (tarray tuchar buf_size)) as default_list.\n  remember (Int.zero_ext 8 (((tag & Int.repr 3) << Int.repr 6) or Int.repr 31)) as e1.\n  assert (len default_list = buf_size) as LB.\n  {  subst; unfold default_val;\n        simpl;\n        try erewrite Zlength_list_repeat;\n        try nia; auto. }\n  pose proof (req_size_32 tval) as R.\n  repeat forward.\n  forward_if.\n  - forward_if (\n       PROP()\n       LOCAL()\n       SEP(if eq_dec (Int.repr buf_size) 0 \n           then data_at_ Tsh (tarray tuchar buf_size) (Vptr buf_b buf_ofs) \n           else data_at Tsh (tarray tuchar buf_size)\n                        (upd_Znth 0 (default_val (tarray tuchar buf_size))\n                                  (Vint e0)) (Vptr buf_b buf_ofs))).\n    + forward. \n      rewrite_if_b.\n      entailer!.\n    + forward.\n      rewrite_if_b.\n      entailer!.\n    + unfold POSTCONDITION.\n      unfold abbreviate. \n      try break_let.\n      forward.\n     break_if; unfold tag_serialize in *.\n     replace (30 >=? Int.unsigned (tag >>u Int.repr 2)) with true in *.\n     rewrite_if_b.\n     inversion Heqp.\n     entailer!.\n     autorewrite with sublist.\n     erewrite sublist_same_gen.\n     entailer!.\n     lia.\n     setoid_rewrite LB. lia.\n     symmetry.\n     Zbool_to_Prop.\n     lia.\n     replace (30 >=? Int.unsigned (tag >>u Int.repr 2)) with true in *.\n     rewrite_if_b.\n     inversion Heqp.\n     entailer!.\n     erewrite upd_Znth_unfold.\n     setoid_rewrite LB.\n     entailer!.\n     setoid_rewrite LB.\n     assert (buf_size <> 0%Z).\n     eapply repr_neq_e in n; try lia.\n     lia.\n     symmetry.\n     Zbool_to_Prop.\n     lia.\n  - (* 30 < tag *) \n    forward_if (\n       PROP()\n       LOCAL(if eq_dec (Int.repr buf_size) 0 \n             then temp _buf__1 (Vptr buf_b buf_ofs)\n             else temp _buf__1 (offset_val 1 (Vptr buf_b buf_ofs));\n             if eq_dec (Int.repr buf_size) 0 \n             then temp _size (Vint (Int.repr buf_size))\n             else temp _size (Vint (Int.repr (buf_size - 1)));\n            temp _tval (Vint tval))\n       SEP(if eq_dec (Int.repr buf_size) 0 \n           then data_at Tsh (tarray tuchar buf_size)\n                     (default_val (tarray tuchar buf_size)) (Vptr buf_b buf_ofs)  \n           else data_at Tsh (tarray tuchar buf_size)\n                        (upd_Znth 0 (default_val (tarray tuchar buf_size))\n                                  (Vint e1)) (Vptr buf_b buf_ofs))).\n    + rewrite <- LB.     \n      erewrite split_data_at_sublist_tuchar with (j := 1%Z).\n      erewrite sublist_one.\n      erewrite data_at_tuchar_singleton_array_eq.\n      Intros.\n      repeat forward.\n      repeat rewrite_if_b.\n      entailer!.\n      replace (len (default_val (tarray tuchar buf_size))) with buf_size.\n      auto.\n      erewrite upd_Znth_unfold.\n      erewrite sublist_nil.\n      erewrite app_nil_l.\n      remember (default_val (tarray tuchar buf_size)) as default_list.\n      remember (Int.zero_ext 8 (((tag & Int.repr 3) << Int.repr 6) or Int.repr 31)) as e1.     \n      erewrite <- split_non_empty_list with\n          (j1 := buf_size)\n          (ls :=  ([Vint e1] ++ sublist 1 (len default_list) default_list)).\n      entailer!.\n      reflexivity.\n      all: try nia;\n        unfold default_val;\n        simpl;\n        try erewrite Zlength_list_repeat;\n        try nia; auto.\n      all: autorewrite with sublist;\n      try erewrite Zlength_sublist_correct;\n          try nia;  try setoid_rewrite LB; try nia.\n    + forward.\n      repeat rewrite_if_b.\n      entailer!.\n    + break_if.\n      assert (buf_size = 0%Z) as S.\n      eapply repr_inj_unsigned; strip_repr.\n      assert ((30 >=? Int.unsigned (tag >>u Int.repr 2)) = false) as C.\n           { erewrite Z.geb_leb. \n             Zbool_to_Prop.\n             nia. }\n      ++ repeat forward.        \n         forward_loop \n      (EX i: Z, \n          PROP (i = 1%Z \\/ i = 2 \\/ i = 3 \\/ i = 4 \\/ i = 5; \n                forall j, 0 <= j < i ->\n                     (Int.shru tval (Int.repr j * Int.repr 7) == 0)%int = false)\n          LOCAL (temp _tval (Vint (Int.shru tag (Int.repr 2)));\n                 temp _i (Vint (Int.repr (i * 7)));\n                 temp _required_size (Vint (Int.repr i));\n                 temp _size (Vint (Int.repr buf_size));\n                 temp _buf__1 (Vptr buf_b buf_ofs))\n          SEP (data_at Tsh (tarray tuchar buf_size)\n                       (default_val (tarray tuchar buf_size))\n                       (Vptr buf_b buf_ofs)))\n      break: (let r := required_size (tag >>u(Int.repr 2)) in\n              PROP ()\n              LOCAL (temp _required_size (Vint (Int.repr r));\n                     temp _tval (Vint (tag >>u Int.repr 2));\n                     temp _i (Vint (Int.repr (r * 7)));\n                     temp _size (Vint (Int.repr buf_size));\n                     temp _buf__1 (Vptr buf_b buf_ofs))\n                 SEP (data_at Tsh (tarray tuchar buf_size)\n                              default_list\n                              (Vptr buf_b buf_ofs))).\n         * Exists 1%Z.\n           entailer!.\n           intros. \n           replace x with 0%Z by nia.\n           erewrite Int.shru_zero.\n           destruct  (Int.shru tag (Int.repr 2) == 0) eqn : T.\n           eapply int_eq_e in T.\n           rewrite T in *.\n           cbv in C.\n           congruence.\n           auto.\n         * Intro i.\n           forward_if; repeat forward.\n           forward_if;\n            repeat forward.\n           rewrite Int.unsigned_repr in H2.\n           entailer!.\n           rep_omega.\n           Exists (i + 1)%Z.\n           rewrite Int.unsigned_repr in H2;\n             try rep_omega.\n           entailer!.\n           split.\n        ** intros.\n           destruct (zeq j i).\n           subst.\n           eapply Int.eq_false.\n           autorewrite with norm.\n           eassumption.\n           eapply H4.\n           nia.\n        ** do 2 f_equal.\n           nia.\n        ** entailer!.\n           assert (required_size (tag >>u (Int.repr 2)) = i) as RS.\n           eapply required_size_spec; auto.\n           autorewrite with norm.\n           eassumption.\n           subst.\n           intuition.\n        ** entailer!.\n           rewrite Int.unsigned_repr in H2;\n             try rep_omega.\n           replace i with 5 in * by nia.\n           assert (required_size (tag >>u (Int.repr 2)) = 5) as RS.\n           eapply required_size_spec; auto.\n           autorewrite with norm.\n           cbn.\n           erewrite shr_lt_zero_35.\n           break_if; auto.\n           unfold Int.ltu in Heqb.\n           break_if; autorewrite with norm in *.\n           replace (Int.unsigned 0) with 0%Z in * by auto with ints.\n           nia.\n           congruence.\n           rewrite RS.\n           intuition.\n         * (* Post exec rest of the fn *)\n           simpl. \n           forward_if.\n           unfold POSTCONDITION.\n           unfold abbreviate. \n           try break_let.\n           forward.\n           unfold tag_serialize in *.\n           rewrite C in *.\n           repeat rewrite_if_b.\n           rewrite Int.unsigned_repr in H2;\n            try rep_omega.           \n           simpl in Heqp.\n           replace (-1 <? required_size (tag >>u Int.repr 2)) with true in *\n             by (symmetry; Zbool_to_Prop; lia).\n           inversion Heqp.  \n           autorewrite with sublist.\n           entailer!.\n           generalize H2.\n           strip_repr.\n           intro. subst. lia.\n           subst; strip_repr.\n           ++\n              assert (buf_size <> 0%Z) as S.\n              {  eapply repr_neq_e in n; lia. }\n              repeat forward. \n         forward_loop (EX i: Z, \n          PROP (i = 1%Z \\/ i = 2 \\/ i = 3 \\/ i = 4 \\/ i = 5; \n                forall j, 0 <= j < i ->\n                     (Int.shru tval (Int.repr j * Int.repr 7) == 0)%int = false)\n          LOCAL (temp _tval (Vint (tag >>u (Int.repr 2)));\n                 temp _i (Vint (Int.repr (i * 7)));\n                 temp _required_size (Vint (Int.repr i));\n                 temp _size (Vint (Int.repr (buf_size - 1)));\n                 temp _buf__1 (offset_val 1 (Vptr buf_b buf_ofs)))\n          SEP ((data_at Tsh (tarray tuchar buf_size)\n                        (upd_Znth 0 (default_val (tarray tuchar buf_size))\n                                  (Vint e1)) (Vptr buf_b buf_ofs))))\n      break: (let r := required_size (tag >>u (Int.repr 2)) in\n              PROP ()\n              LOCAL (temp _required_size (Vint (Int.repr r));\n                     temp _tval (Vint (tag >>u Int.repr 2));\n                     temp _i (Vint (Int.repr (r * 7)));\n                     temp _size (Vint (Int.repr (buf_size - 1)));\n                     temp _buf__1 (offset_val 1 (Vptr buf_b buf_ofs)))\n                 SEP ((data_at Tsh (tarray tuchar buf_size)\n                               (upd_Znth 0 (default_val (tarray tuchar buf_size)) \n                                         (Vint e1)) (Vptr buf_b buf_ofs)))).\n         * Exists 1%Z.\n           entailer!.\n           intros. \n           replace x with 0%Z by nia.\n           erewrite Int.shru_zero.\n           destruct  (Int.shru tag (Int.repr 2) == 0) eqn : T.\n           eapply int_eq_e in T.\n           rewrite T in *.\n           cbv in H1.\n           congruence.\n           auto.\n         * Intro i.\n           forward_if; repeat forward.\n           forward_if;\n             repeat forward.\n           rewrite Int.unsigned_repr in H2.\n           entailer!.\n           rep_omega.\n           Exists (i + 1)%Z.\n           rewrite Int.unsigned_repr in H2; try rep_omega.\n           entailer!.\n           split.\n        ** intros.\n           destruct (zeq j i).\n           subst.\n           eapply Int.eq_false.\n           autorewrite with norm.\n           eassumption.\n           eapply H4.\n           nia.\n        ** do 2 f_equal.\n           nia.\n        ** entailer!.\n           assert (required_size (tag >>u (Int.repr 2)) = i) as RS.\n           eapply required_size_spec; auto.\n           autorewrite with norm.\n           eassumption.\n           subst.\n           intuition.\n        ** entailer!.\n           rewrite Int.unsigned_repr in H2; try rep_omega.\n           replace i with 5 in * by nia.\n           assert (required_size (tag >>u (Int.repr 2)) = 5) as RS.\n           eapply required_size_spec; auto.\n           autorewrite with norm.\n           cbn.\n           erewrite shr_lt_zero_35.\n           break_if; auto.\n           unfold Int.ltu in Heqb.\n           break_if; autorewrite with norm in *.\n           replace (Int.unsigned 0) with 0%Z in * by auto with ints.\n           nia.\n           congruence.\n           rewrite RS.\n           intuition.\n         * (* Post exec rest of the fn *)\n            assert ((30 >=? Int.unsigned (tag >>u Int.repr 2)) = false) as C.\n           { erewrite Z.geb_leb. \n             Zbool_to_Prop.\n             nia. }\n           simpl.\n           forward_if.\n           unfold POSTCONDITION.\n           unfold abbreviate. \n           try break_let.\n           forward.\n           unfold tag_serialize in *.\n           rewrite C in *.         \n           rewrite Int.unsigned_repr in *;\n             try rep_omega.\n           forward.\n           forward.\n           normalize.\n           strip_repr.\n           remember (required_size tval) as r.\n           forward_loop (\n               EX v : Z, EX ls : list int,\n               PROP ((Int.unsigned Int.zero <= v)%Z; \n                     (v + 1 <= r)%Z;\n                     ls = \n                     serialize_tag_loop (r - v - 1)%Z (Z.to_nat v) tval)\n               LOCAL (temp _tval (Vint tval);\n                      temp _i (Vint (Int.repr ((r * 7) - (v + 1) * 7)%Z));\n                      temp _required_size (Vint (Int.repr r));\n                      temp _size (Vint (Int.repr (buf_size - 1)));\n                      temp _buf__1 (offset_val (v + 1) (Vptr buf_b buf_ofs));\n                      temp _end\n                      (Vptr buf_b\n                            (buf_ofs +\n                                    Ptrofs.repr (1 + \n                                                 required_size (tag >>u Int.repr 2))\n                                    - Ptrofs.repr 1)%ptrofs))\n               SEP (data_at Tsh (tarray tuchar 1) [Vint e1] (Vptr buf_b buf_ofs);\n                    data_at Tsh (tarray tuchar v) (map Vint ls)\n                            (offset_val 1 (Vptr buf_b buf_ofs));\n                    data_at Tsh (tarray tuchar (buf_size - v - 1)) \n                                    (sublist (v + 1) buf_size default_list) \n                                    (offset_val (v + 1) (Vptr buf_b buf_ofs))))\n          break: (let ls := serialize_tag_loop 0 (Z.to_nat r - 1) tval in\n                 PROP ()\n                 LOCAL (temp _tval (Vint (tag >>u Int.repr 2));\n                        temp _i (Vint 0%int);\n                        temp _required_size (Vint (Int.repr r));\n                        temp _size (Vint (Int.repr (buf_size - 1)));\n                        temp _buf__1 (offset_val r (Vptr buf_b buf_ofs));\n                        temp _end\n                             (Vptr buf_b\n                                   (buf_ofs +\n                                    Ptrofs.repr (1 + \n                                                 required_size (tag >>u Int.repr 2))\n                                    - Ptrofs.repr 1)%ptrofs))\n\n                 SEP (data_at Tsh (tarray tuchar 1) [Vint e1] (Vptr buf_b buf_ofs);\n                      data_at Tsh (tarray tuchar (len ls)) \n                              (map Vint ls)\n                              (offset_val 1 (Vptr buf_b buf_ofs));\n                      data_at Tsh (tarray tuchar (buf_size - len ls - 1)) \n                                    (sublist (len ls + 1) buf_size default_list) \n                                    (offset_val ((len ls) + 1) (Vptr buf_b buf_ofs)))).\n          *** Exists 0%Z.\n              Exists (@nil int).\n              erewrite data_at_tuchar_zero_array_eq.\n              entailer!.\n              erewrite <- data_at_app.\n              erewrite upd_Znth_unfold.\n              erewrite sublist_nil.\n              erewrite app_nil_l.\n              setoid_rewrite LB.\n              replace (1 + (buf_size - 1))%Z with buf_size by nia.\n              entailer!.\n              all: try setoid_rewrite LB;\n                autorewrite with sublist norm; cbn; auto;\n                  try rep_omega. \n          ***\n            Intros v ls.\n            forward_if.\n           +++\n             rewrite Int.unsigned_repr in H2; try rep_omega.\n             replace (Int.unsigned 0%int) with 0%Z in * by auto with ints.\n             assert (0 <= v + 1 <= (required_size (tag >>u Int.repr 2))) as VR.\n             { lia. } \n             unfold test_order_ptrs.\n             unfold sameblock.\n             subst.\n             destruct peq; [simpl  |contradiction].\n             apply andp_right.\n             { apply derives_trans \n                 with (Q := valid_pointer \n                              (Vptr buf_b (buf_ofs + Ptrofs.repr (v + 1))%ptrofs)).               \n                entailer!.\n               apply valid_pointer_weak. }\n             { assert (0 < buf_size - v - 1)%Z as LD by\n                     (try erewrite LB; nia).\n               assert (sizeof (tarray tuchar (buf_size - v - 1)) > 0) by (simpl; nia).\n               remember (default_val (tarray tuchar buf_size)) as default_list.\n               remember (required_size (tag >>u Int.repr 2)) as r.\n               assert (data_at Tsh (tarray tuchar (buf_size - v - 1))\n                               (sublist (v + 1) buf_size (default_val (tarray tuchar buf_size)))\n                               (Vptr buf_b (buf_ofs + Ptrofs.repr (v + 1))%ptrofs)\n                               |-- weak_valid_pointer\n                               (Vptr buf_b\n                                     (buf_ofs +  Ptrofs.repr (1 + r) - Ptrofs.repr 1)%ptrofs)).\n               { apply derives_trans \n                   with (Q := valid_pointer \n                                (Vptr buf_b (buf_ofs\n                                             + Ptrofs.repr\n                                                 (1 + r) - Ptrofs.repr 1)%ptrofs)). \n                 assert (sizeof (tarray tuchar (buf_size - v - 1)) > 0) by (simpl; nia).\n                 replace (buf_ofs + Ptrofs.repr (1 + r) - Ptrofs.repr 1)%ptrofs\n                   with (buf_ofs + Ptrofs.repr r)%ptrofs.\n                 Open Scope Z.\n                 erewrite data_at_app_gen\n                   with (j1 := r - (v + 1))\n                        (j2 := len default_list - r)\n                        (ls1 := sublist (v + 1) r default_list)\n                        (ls2 := sublist r (len default_list) default_list). \n                 assert ((buf_ofs + Ptrofs.repr (v + 1) + Ptrofs.repr (r - (v + 1)))%ptrofs =\n                         (buf_ofs + Ptrofs.repr r)%ptrofs) as PTR.\n                 {  ptrofs_compute_add_mul; try rep_omega.\n                    f_equal.\n                    rep_omega. }\n                 rewrite PTR.\n                 assert (sizeof (tarray tuchar (len default_list -  r)) > 0).\n                 { simpl.\n                   setoid_rewrite LB. \n                   nia. }\n                 eapply sepcon_valid_pointer2.\n                 eapply data_at_valid_ptr; auto.\n                 1-5:  replace (Int.unsigned 0%int) with 0%Z in * by auto with ints.\n                 4: erewrite sublist_split with (mid := r); subst; auto; try nia.\n                 all: try erewrite Zlength_sublist_correct;\n                   try nia;  try setoid_rewrite LB; try nia; auto.\n                 Focus 3. apply valid_pointer_weak. \n                 try erewrite Zlength_sublist_correct;\n                   try nia;  try setoid_rewrite LB; ptrofs_compute_add_mul; try rep_omega.\n                 erewrite Ptrofs.sub_add_opp.\n                 unfold Ptrofs.neg.\n                 normalize.\n                 f_equal.\n                 rewrite Ptrofs.unsigned_repr.\n                 f_equal.\n                 nia.\n                 rep_omega.  }\n               entailer!. } \n           +++ \n             Open Scope Z.\n             rewrite Int.unsigned_repr in H2; try rep_omega.\n             replace (Int.unsigned 0%int) with 0%Z in * by auto with ints.\n             eapply typed_true_ptr_lt in H6.\n             assert ( Ptrofs.unsigned buf_ofs +  v + 1 <\n                      Ptrofs.unsigned buf_ofs + 1 +\n                      required_size (tag >>u Int.repr 2) - 1) as PT.\n             { generalize H6.\n               unfold Ptrofs.sub.\n               ptrofs_compute_add_mul.             \n               all: subst; rep_omega_setup; auto with ints; \n                 autorewrite with norm; try rep_omega; try nia. }\n             unfold offset_val.\n             erewrite split_non_empty_list with \n                 (j2 := (len default_list - (v + 1) - 1)%Z)\n                 (ls' := (sublist (v + 1 + 1) buf_size default_list))\n                 (ls := (sublist (v + 1) buf_size default_list)).            \n             assert (v < required_size tval)%Z by (subst; lia).\n             Intros.\n             assert (len default_list - (v + 1) - 1 =\n                     len (sublist (v + 1 + 1) (len default_list) default_list)) as LEN.\n             { erewrite Zlength_sublist_correct.\n               nia.\n               rewrite LB.\n               all: try nia. }\n             forward.\n             entailer!.\n             unfold Int.iwordsize.\n             ints_compute_add_mul.\n             cbn - [required_size].\n             all: try rep_omega.\n             repeat forward.\n             remember\n               (Int.zero_ext 8\n                             (Int.repr 128\n                                       or (((tag >>u Int.repr 2) >>u\n                                                                 Int.repr ((required_size (tag >>u Int.repr 2) - (len ls)) * 7)) & Int.repr 127))%int)%int\n               as e_v.\n             Exists (v + 1) (ls ++ [(Int.zero_ext 8\n          (Int.repr 128 or ((tval >>u Int.repr (r * 7 - (v + 1) * 7)) & Int.repr 127))%int)]).\n             assert (v = len ls) as VLS.\n             { subst.\n               erewrite loop_len_req_size.\n               erewrite Z2Nat_id';\n                 erewrite Zmax0r; try nia. }\n             entailer!.\n             split.\n             erewrite Z.add_1_r at 3.\n             erewrite Z2Nat.inj_succ.       \n             simpl. f_equal. rewrite H5 at 1. \n             replace (required_size (tag >>u Int.repr 2)  - len ls - 1) \n               with (required_size (tag >>u Int.repr 2) - (len ls + 1) - 1 + 1) by list_solve.\n             reflexivity.\n             admit.\n             lia.\n             do 2 f_equal. nia.\n             replace (required_size (tag >>u Int.repr 2) * 7 - (len ls + 1) * 7)\n               with\n                 ((required_size (tag >>u Int.repr 2) - (len ls + 1)) * 7) by nia.\n             remember\n               (Int.zero_ext 8\n                             (Int.repr 128\n                                       or (((tag >>u Int.repr 2) >>u\n                            Int.repr ((required_size (tag >>u Int.repr 2)\n                                       - (len ls + 1)) * 7)) & \n                                           Int.repr 127))%int)%int\n               as e_v.\n             unfold offset_val.\n             simpl.\n             erewrite <- data_at_tuchar_singleton_array_eq.\n             remember (default_val (tarray tuchar buf_size)) as default_list.\n             replace (buf_ofs + Ptrofs.repr (len ls + 1) + 1)%ptrofs\n               with (buf_ofs +  Ptrofs.repr (len ls + 1 + 1))%ptrofs. \n             \n             replace (buf_ofs + Ptrofs.repr ((len ls) + 1))%ptrofs\n               with (buf_ofs + 1 + Ptrofs.repr (len ls))%ptrofs. \n             erewrite <- data_at_app.\n             erewrite map_app.\n             rewrite <- LB.\n             entailer!.\n             all: replace (Int.unsigned 0%int) with 0%Z in * \n               by (autorewrite with norm; auto);\n               autorewrite with list sublist;\n               try rep_omega.\n             all: ptrofs_compute_add_mul; \n               replace (Ptrofs.unsigned 1%ptrofs) with 1 by auto with ptrofs;\n               autorewrite with norm;\n               try nia; try rep_omega; f_equal; try nia.\n             instantiate (1 := Znth (v + 1) default_list).\n             erewrite sublist_split with (mid := v + 1 + 1).\n             erewrite sublist_len_1.\n             reflexivity.\n             all: try setoid_rewrite LB; try nia.\n             subst. rep_omega. \n           +++\n             Open Scope Z.\n             eapply typed_false_ptr_lt in H6.\n             replace (Int.unsigned 0%int) with 0 in * by auto with ints.\n             rewrite Int.unsigned_repr in H2; try rep_omega.\n             assert ( Ptrofs.unsigned buf_ofs +  v + 1 >=\n                      Ptrofs.unsigned buf_ofs + 1 +\n                      required_size (tag >>u Int.repr 2) - 1) as PT.\n             { generalize H6.\n               unfold Ptrofs.sub.\n               ptrofs_compute_add_mul.             \n               all: subst; rep_omega_setup; auto with ints; \n                 autorewrite with norm; try rep_omega; try nia. }\n             assert (required_size tval < buf_size) by (subst; nia).\n             assert (v + 1 >= required_size tval)%Z. \n             { subst; lia. } \n             assert (v + 1 = r) as V by nia.\n             rewrite V.\n             forward.\n             erewrite <- V in *.\n             replace (v + 1 - v - 1) with 0 in *.\n             replace (Z.to_nat (v + 1) - 1)%nat with (Z.to_nat v) in *.\n             erewrite <- H5.\n             entailer!.\n             replace 0%int with (Int.repr 0) by auto with ints.\n             do 2 f_equal.\n             lia.\n             erewrite Zlength_map.\n             entailer!.\n(*             f_equal.\n             unfold Ptrofs.sub.\n               ptrofs_compute_add_mul;\n                 rep_omega_setup; auto with ints; \n                 autorewrite with norm; try rep_omega; try nia.\n               f_equal.\n               lia.\n               erewrite Zlength_map.\n               entailer!. *)\n               replace 1%nat with (Z.to_nat 1) by auto with arith.\n               erewrite <- Z2Nat.inj_sub.\n               f_equal.\n               all: subst; try strip_repr.\n             ***\n               simpl.\n               rewrite Int.unsigned_repr in H2; try rep_omega.\n               unfold offset_val.\n               remember (serialize_tag_loop 0 (Z.to_nat r - 1) tval) as ls.\n               erewrite split_non_empty_list\n                 with (ls' := sublist (len ls + 1 + 1) buf_size default_list)\n                      (j2 := (buf_size - (len ls + 1 + 1))%Z)\n                      (ofs := (buf_ofs + Ptrofs.repr (len ls + 1))%ptrofs).\n               Intros.\n                assert (r = len ls + 1) as RLS.\n             { subst.\n               erewrite loop_len_req_size.\n               admit. }\n               erewrite RLS in *.\n               forward.\n               unfold POSTCONDITION.\n               unfold abbreviate.\n               break_let.\n               pose proof (req_size_32 tval).\n               assert (required_size tval < buf_size) by (subst; lia).\n               forward.\n               unfold tag_serialize in *.\n               rewrite C in *.\n               rewrite Int.unsigned_repr in *.\n               rewrite_if_b.\n                assert ((buf_size - 1 <? required_size (tag >>u Int.repr 2)) = false) as FS.\n                { Zbool_to_Prop.\n                  nia. }\n               rewrite FS in *.\n               inversion Heqp.\n               unfold offset_val.                   \n               erewrite <- data_at_tuchar_singleton_array_eq.\n               erewrite <- data_at_app.\n               replace (1 + len ls)%Z with (len ls + 1)%Z by nia.\n               erewrite <- data_at_app.\n               (* setoid_rewrite <- H6. *)\n               remember (Int.zero_ext 8 (((tag & Int.repr 3)\n                                            << Int.repr 6) or Int.repr 31)%int) as e0.\n               remember (Int.zero_ext 8 ((tag >>u Int.repr 2) & Int.repr 127)%int) as e_n.\n               replace (buf_ofs + Ptrofs.repr (len ls + 1) + 1)%ptrofs with \n                   (buf_ofs + Ptrofs.repr (len ls + 1 + 1))%ptrofs.\n               erewrite <- data_at_app.\n               replace (len ls + 1 + 1 + (buf_size - (len ls + 1 + 1))) with buf_size by nia.\n               unfold serialize_tag.\n               assert ((Z.to_nat (required_size (tag >>u Int.repr 2) - 1)) = \n                       (Z.to_nat (len ls + 1) - 1)%nat) as RLS by admit.\n               erewrite RLS in *.\n               erewrite <- Heqls.\n               erewrite <- Heqe_n.\n               autorewrite with sublist.\n               assert  (([Vint e0] ++ map Vint ls) ++ [Vint e_n] = map Vint (e0 :: ls ++ [e_n]))\n                       as V. admit.\n               setoid_rewrite V.\n               \n               entailer!.               \n               all: (autorewrite with sublist;\n                     try nia; auto).\n               all: try erewrite Zlength_sublist_correct;\n                 try nia.\n               Focus 4.\n               instantiate (1 := Znth (len ls + 1) default_list).\n               erewrite sublist_split with (mid := len ls + 1 + 1).\n               erewrite sublist_len_1.\n               reflexivity.\n               all: try setoid_rewrite LB; try  rep_omega.\n                simpl in H1.\n                subst.\n                erewrite loop_len_req_size.\n                replace 1%nat with (Z.to_nat 1) by auto with arith.\n                erewrite <- Z2Nat.inj_sub.\n                erewrite Z2Nat_id'.\n                erewrite Zmax0r;\n                  repeat rep_omega.\n                lia.\n                subst.\n                erewrite loop_len_req_size.\n                replace 1%nat with (Z.to_nat 1) by auto with arith.\n                erewrite <- Z2Nat.inj_sub.\n                erewrite Z2Nat_id'.\n                erewrite Zmax0r;\n                  repeat rep_omega.\n                lia.\n                do 2 f_equal.\n                all: try lia.\n               all: repeat ptrofs_compute_add_mul. \n               replace (Ptrofs.unsigned 1%ptrofs) with 1%Z by auto with ptrofs.\n               all: rep_omega_setup; auto with ints; \n                 autorewrite with norm; try rep_omega; try nia.\n               f_equal.\n               lia.\n               all:  try assert (r = len ls + 1) as RLS by admit; try erewrite <- RLS; try lia.\n               subst. lia.\n             *** subst. rep_omega.\nAdmitted.\n\n*)\n", "meta": {"author": "asosyuk", "repo": "asn1verification", "sha": "55395d63c2dcd512a28d9cd42d788e12f91e7641", "save_path": "github-repos/coq/asosyuk-asn1verification", "path": "github-repos/coq/asosyuk-asn1verification/asn1verification-55395d63c2dcd512a28d9cd42d788e12f91e7641/src/Lib/DWT/VST/Ber_tlv_tag_serialize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.2284463604477708}}
{"text": "Require Import Events.\nRequire Import Memory.\nRequire Import Coqlib.\nRequire Import compcert.common.Values.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import AST.\nRequire Import Globalenvs.\n\nRequire Import Axioms.\nRequire Import sepcomp.mem_lemmas. (*needed for definition of mem_forward etc*)\nRequire Import sepcomp.core_semantics.\n\nRequire Import sepcomp.StructuredInjections.\nRequire Import effect_semantics.\nRequire Import effect_simulations.\nRequire Import effect_simulations_lemmas.\nRequire Import sepcomp.forward_simulations_trans.\nRequire Import Wellfounded.\nRequire Import Relations.\nRequire Import effect_corediagram_trans.\n\nRequire Import effect_interpolants.\n(*Require Import effect_interpolation_proofs. not necessary - interface suffices*)\n\nDeclare Module EFFAX : EffectInterpolationAxioms.\n\nImport SM_simulation.\n\nLemma initial_inject_split: forall j m1 m3 (Inj:Mem.inject j m1 m3),\n  exists m2 j1 j2, j = compose_meminj j1 j2 /\\\n       Mem.inject j1 m1 m2 /\\ Mem.inject j2 m2 m3 /\\\n       (forall b1, (exists b3 d, compose_meminj j1 j2 b1 = Some(b3,d))\n                   <-> (exists b2 d1, j1 b1 = Some(b2,d1))) /\\\n       (forall b2 b3 d2, j2 b2 =Some(b3,d2) ->\n                   exists b1 d, compose_meminj j1 j2 b1 = Some(b3,d)) /\\\n      (forall b1 b2 ofs2, j1 b1 = Some(b2,ofs2) -> (b1=b2 /\\ ofs2=0)) /\\\n      (forall b2 b3 ofs3, j2 b2 = Some (b3, ofs3) ->\n               Mem.flat_inj 1%positive b2 = Some (b3, ofs3) \\/\n               (b2 = Mem.nextblock Mem.empty /\\\n                    compose_meminj j1 j2 (Mem.nextblock Mem.empty) = Some (b3, ofs3)) \\/\n               (exists m : positive,\n                   b2 = (Mem.nextblock Mem.empty + m)%positive /\\\n                   compose_meminj j1 j2 (Mem.nextblock Mem.empty + m)%positive =\n                   Some (b3, ofs3))).\nProof. intros.\n  destruct (EFFAX.interpolate_II_strongHeqMKI _ _ _\n     Forward_simulation_trans.empty_inj _ (Forward_simulation_trans.empty_fwd m1) _ _ Forward_simulation_trans.empty_inj _ (Forward_simulation_trans.empty_fwd m3) _ Inj)\n  as [m2 [j1 [j2 [J [X [Y [Inc1 [Inc2 [Inj12 [_ [Inj23 AA]]]]]]]]]]].\nintros b; intros.\n  destruct (compose_meminjD_Some _ _ _ _ _ H) as [? [? [? [? [? ?]]]]].\n    subst. destruct (flatinj_E _ _ _ _ H0) as [? [? ?]]. subst.\n         exfalso. xomega.\nintros b; intros.\n   unfold Mem.valid_block; simpl; split; intros N; xomega.\nsplit; intros. unfold Mem.valid_block in H0. simpl in H0. exfalso; xomega.\n  apply Mem.perm_valid_block in H0. unfold Mem.valid_block in H0. simpl in H0. exfalso; xomega.\nsplit; intros. unfold Mem.valid_block in H0. simpl in H0. exfalso; xomega.\n  apply Mem.perm_valid_block in H0. unfold Mem.valid_block in H0. simpl in H0. exfalso; xomega.\nsubst. exists m2, j1, j2.\nsplit; trivial.\nsplit; trivial.\nsplit; trivial.\ndestruct AA as [_ [_ [_ [_ [_ [XX YY]]]]]].\nsplit. intros.\n  split; intros. destruct H as [b3 [d COMP]].\n    destruct (compose_meminjD_Some _ _ _ _ _ COMP) as\n        [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear COMP.\n    exists b2, d1; trivial.\n  intros. destruct H as [b2 [d1 J1]].\n    destruct (X _ _ _ J1) as [FL | COMP]; trivial.\n    destruct (flatinj_E _ _ _ _ FL) as [? [? ?]].\n      subst. clear -H1. exfalso. xomega.\nsplit. intros.\n    destruct (Y _ _ _ H) as [FL | COMP]; trivial.\n    destruct (flatinj_E _ _ _ _ FL) as [? [? ?]].\n      subst. clear -H2. exfalso. xomega.\nsplit. intros.\n  destruct (XX _ _ _ H) as [AA | [AA | AA]].\n    apply flatinj_E in AA.\n      destruct AA as [? [? ?]]; subst. intuition.\n    destruct AA as [? [? ?]]; subst. intuition.\n    destruct AA as [mm [[? ?] ?]]; subst. intuition.\napply YY.\nQed.\n(*\nLemma initial_inject_split: forall j m1 m3 (Inj:Mem.inject j m1 m3),\n  exists m2 j1 j2, j = compose_meminj j1 j2 /\\\n       Mem.inject j1 m1 m2 /\\ Mem.inject j2 m2 m3 /\\\n       (forall b1, (exists b3 d, compose_meminj j1 j2 b1 = Some(b3,d))\n                   <-> (exists b2 d1, j1 b1 = Some(b2,d1))) /\\\n       (forall b2 b3 d2, j2 b2 =Some(b3,d2) ->\n                   exists b1 d, compose_meminj j1 j2 b1 = Some(b3,d)) /\\\n      (forall b1 b2 ofs2, j1 b1 = Some(b2,ofs2) -> (b1=b2 /\\ ofs2=0)) /\\\n      (forall b2 b3 ofs3, j2 b2 = Some (b3, ofs3) ->\n               Mem.flat_inj 1%positive b2 = Some (b3, ofs3) \\/\n               (b2 = Mem.nextblock Mem.empty /\\\n                    compose_meminj j1 j2 (Mem.nextblock Mem.empty) = Some (b3, ofs3)) \\/\n               (exists m : positive,\n                   b2 = (Mem.nextblock Mem.empty + m)%positive /\\\n                   compose_meminj j1 j2 (Mem.nextblock Mem.empty + m)%positive =\n                   Some (b3, ofs3))) /\\\n      (forall b1 b2 ofs2, j1 b1 = Some(b2,ofs2) -> (b1=b2 /\\ ofs2=0)) /\\\n      (forall b2 b3 ofs3, j2 b2 = Some (b3, ofs3) ->\n              Mem.flat_inj 1%positive b2 = Some (b3, ofs3) \\/\n              (b2 = Mem.nextblock Mem.empty /\\\n                compose_meminj j1 j2 (Mem.nextblock Mem.empty) = Some (b3, ofs3)) \\/\n              (exists m : positive,\n                b2 = (Mem.nextblock Mem.empty + m)%positive /\\\n                compose_meminj j1 j2 (Mem.nextblock Mem.empty + m)%positive =\n                Some (b3, ofs3))).\nProof. intros.\n  destruct (EFFAX.interpolate_II_strong _ _ _ Forward_simulation_trans.empty_inj _ (Forward_simulation_trans.empty_fwd m1) _ _ Forward_simulation_trans.empty_inj _ (Forward_simulation_trans.empty_fwd m3) _ Inj)\n  as [m2 [j1 [j2 [J [X [Y [Inc1 [Inc2 [Inj12 [_ [Inj23 _]]]]]]]]]]].\nintros b; intros.\n  destruct (compose_meminjD_Some _ _ _ _ _ H) as [? [? [? [? [? ?]]]]].\n    subst. destruct (flatinj_E _ _ _ _ H0) as [? [? ?]]. subst.\n         exfalso. xomega.\nintros b; intros.\n   unfold Mem.valid_block; simpl; split; intros N; xomega.\nsplit; intros. unfold Mem.valid_block in H0. simpl in H0. exfalso; xomega.\n  apply Mem.perm_valid_block in H0. unfold Mem.valid_block in H0. simpl in H0. exfalso; xomega.\nsplit; intros. unfold Mem.valid_block in H0. simpl in H0. exfalso; xomega.\n  apply Mem.perm_valid_block in H0. unfold Mem.valid_block in H0. simpl in H0. exfalso; xomega.\nsubst. exists m2, j1, j2.\nsplit; trivial.\nsplit; trivial.\nsplit; trivial.\nsplit. intros.\n  split; intros. destruct H as [b3 [d COMP]].\n    destruct (compose_meminjD_Some _ _ _ _ _ COMP) as\n        [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear COMP.\n    exists b2, d1; trivial.\n  intros. destruct H as [b2 [d1 J1]].\n    destruct (X _ _ _ J1) as [FL | COMP]; trivial.\n    destruct (flatinj_E _ _ _ _ FL) as [? [? ?]].\n      subst. clear -H1. exfalso. xomega.\nsplit. intros.\n    destruct (Y _ _ _ H) as [FL | COMP]; trivial.\n    destruct (flatinj_E _ _ _ _ FL) as [? [? ?]].\n      subst. clear -H2. exfalso. xomega.\nsplit; intros.\n  destruct (X _ _ _ H) as [AA | AA].\n    apply flatinj_E in AA.\n      destruct AA as [? [? ?]]; subst. intuition.\n\nQed.\n*)\n\nSection Eff_sim_trans.\nContext {F1 V1 C1 F2 V2 C2 F3 V3 C3:Type}\n        (Sem1 : @EffectSem (Genv.t F1 V1) C1)\n        (Sem2 : @EffectSem (Genv.t F2 V2) C2)\n        (Sem3 : @EffectSem (Genv.t F3 V3) C3)\n        (g1 : Genv.t F1 V1)\n        (g2 : Genv.t F2 V2)\n        (g3 : Genv.t F3 V3)\n        epts12 epts23 epts13\n        (EPC : entrypoints_compose epts12 epts23 epts13).\n\nTheorem eff_sim_trans: forall\n        (SIM12: @SM_simulation_inject _ _ _ _ _ _ Sem1 Sem2 g1 g2 epts12)\n        (SIM23: @SM_simulation_inject _ _ _ _ _ _ Sem2 Sem3 g2 g3 epts23),\n        @SM_simulation_inject _ _ _ _ _ _ Sem1 Sem3 g1 g3 epts13.\nProof. (*follows structure of forward_simulations_trans.injinj*)\n  intros.\n  destruct SIM12\n    as [core_data12 match_core12 core_ord12 core_ord_wf12\n      match_sm_wd12 genvs_dom_eq12 match_genv12\n      match_visible12 match_restrict12\n      match_sm_valid12 (*match_protected12*) core_initial12\n      core_diagram12 effcore_diagram12\n      core_halted12 core_at_external12 eff_after_external12].\n  destruct SIM23\n    as [core_data23 match_core23 core_ord23 core_ord_wf23\n      match_sm_wd23 genvs_dom_eq23 match_genv23\n      match_visible23 match_restrict23\n      match_sm_valid23 (*match_protected23*) core_initial23\n      core_diagram23 effcore_diagram23\n      core_halted23 core_at_external23 eff_after_external23].\n  eapply Build_SM_simulation_inject with\n    (core_ord := clos_trans _ (sem_compose_ord_eq_eq core_ord12 core_ord23 C2))\n    (match_state := fun d mu c1 m1 c3 m3 =>\n      match d with (d1,X,d2) =>\n        exists c2, exists m2, exists mu1, exists mu2,\n          X=Some c2 /\\ mu = compose_sm mu1 mu2 /\\\n          (locBlocksTgt mu1 = locBlocksSrc mu2 /\\\n           extBlocksTgt mu1 = extBlocksSrc mu2 /\\\n           (forall b, pubBlocksTgt mu1 b = true -> pubBlocksSrc mu2 b = true) /\\\n           (forall b, frgnBlocksTgt mu1 b = true -> frgnBlocksSrc mu2 b = true)) /\\\n          match_core12 d1 mu1 c1 m1 c2 m2 /\\ match_core23 d2 mu2 c2 m2 c3 m3\n      end).\n (*well_founded*)\n  eapply wf_clos_trans. eapply well_founded_sem_compose_ord_eq_eq; assumption.\n (*match_sm_wd*) clear - match_sm_wd12 match_sm_wd23.\n  intros. rename c2 into c3. rename m2 into m3.\n  destruct d as [[d12 cc2] d23].\n  destruct H as [c2 [m2 [mu12 [mu23 [X [J [INV [MC12 MC23]]]]]]]]; subst.\n  specialize (match_sm_wd12 _ _ _ _ _ _ MC12).\n  specialize (match_sm_wd23 _ _ _ _ _ _ MC23).\n  destruct INV as [INVa [INVb [INVc INVd]]].\n  eapply (compose_sm_wd); eauto.\n (*genvs_domain_eq*)\n  eapply genvs_domain_eq_trans; eassumption.\n (*match_genv for definition using\n       meminj_preserves_globals ge1 (foreign_of mu)\n  clear - genvs_dom_eq12 match_sm_wd12 match_genv12 match_genv23.\n  intros. rename c2 into c3. rename m2 into m3.\n  destruct d as [[d12 cc2] d23].\n  destruct H as [c2 [m2 [mu12 [mu23 [X [J [INV [MC12 MC23]]]]]]]]; subst.\n  specialize (match_genv12 _ _ _ _ _ _ MC12).\n  specialize (match_genv23 _ _ _ _ _ _ MC23).\n  apply meminj_preserves_genv2blocks.\n  apply meminj_preserves_genv2blocks in match_genv12.\n  apply meminj_preserves_genv2blocks in match_genv23.\n  rewrite compose_sm_foreign.\n    solve [eapply meminj_preserves_globals_ind_compose; eassumption].\n    eapply INV.\n    eauto.*)\n (*match_genv*)\n  clear - genvs_dom_eq12 match_sm_wd12 match_genv12 match_genv23.\n  intros. rename c2 into c3. rename m2 into m3.\n  destruct d as [[d12 cc2] d23].\n  destruct MC as [c2 [m2 [mu12 [mu23 [X [J [INV [MC12 MC23]]]]]]]]; subst.\n  destruct (match_genv12 _ _ _ _ _ _ MC12) as [GE12a GE12b].\n  destruct (match_genv23 _ _ _ _ _ _ MC23) as [GE23a GE23b].\n  split. apply meminj_preserves_genv2blocks.\n         apply meminj_preserves_genv2blocks in GE12a.\n         apply meminj_preserves_genv2blocks in GE23a.\n         rewrite compose_sm_extern.\n         solve [eapply meminj_preserves_globals_ind_compose; eassumption].\n  apply GE12b.\n (*match_visible*)\n    clear - match_sm_wd12 match_visible12.\n    intros. rename c2 into c3. rename m2 into m3.\n      destruct d as [[d12 cc2] d23].\n      destruct H as [c2 [m2 [mu12 [mu23 [X [J [INV [MC12 MC23]]]]]]]]; subst.\n      simpl. rewrite vis_compose_sm. eapply match_visible12. eassumption.\n (*match_restrict*)\n    clear - match_restrict12.\n    intros. rename c2 into c3. rename m2 into m3.\n    destruct d as [[d12 cc2] d23].\n    destruct H as [c2 [m2 [mu12 [mu23 [XX [J [INV [MC12 MC23]]]]]]]]; subst.\n    simpl in *.\n    exists c2, m2, (restrict_sm mu12 X), mu23.\n    specialize (match_restrict12 _ _ _ _ _ _ X MC12 H0 H1).\n    intuition.\n    unfold compose_sm; simpl.\n    f_equal; try (destruct mu12; reflexivity).\n      destruct mu12; simpl in *.\n        unfold compose_meminj, restrict. extensionality b.\n        remember (X b) as d.\n        destruct d; trivial.\n      destruct mu12; simpl in *.\n        unfold compose_meminj, restrict. extensionality b.\n        remember (X b) as d.\n        destruct d; trivial.\n      destruct mu12; simpl in *. assumption.\n      destruct mu12; simpl in *. assumption.\n      destruct mu12; simpl in *. apply (H2 _ H4).\n      destruct mu12; simpl in *. apply (H5 _ H4).\n (*sm_valid*)\n    clear - match_sm_valid12 match_sm_valid23.\n    intros. rename c2 into c3.  rename m2 into m3.\n    destruct d as [[d12 cc2] d23].\n    destruct H as [c2 [m2 [mu12 [mu23 [X [J [INV [MC12 MC23]]]]]]]]; subst.\n    specialize (match_sm_valid12 _ _ _ _ _ _ MC12).\n    specialize (match_sm_valid23 _ _ _ _ _ _ MC23).\n    unfold sm_valid, compose_sm. destruct mu12; destruct mu23; simpl in *.\n    split; intros. eapply match_sm_valid12. apply H.\n    eapply match_sm_valid23. apply H.\n (*match_protected\n    clear - match_sm_wd12 match_protected12\n            match_sm_wd23 match_protected23.\n    intros. rename c2 into c3.  rename m2 into m3.\n    destruct d as [[d12 cc2] d23].\n    destruct H as [c2 [m2 [mu12 [mu23 [X [J [INV [MC12 MC23]]]]]]]]; subst.\n    simpl. apply (match_protected12 _ _ _ _ _ _ MC12 _ H0 H1).*)\n (*initial_core*)\n   (*version where envirnment delivers structured injection:\n     to complete this proof, we'd have to replace the call to\n     initial_inject_split 3 line down to one to variant that merges\n     the results of the two lemmas in effect_interpolants, namely\n     effect_interp_II and interpolate_II_strongHeqMKI. That should be possible\n     but is left as future work.\n   clear - EPC genvs_dom_eq12 core_initial12 genvs_dom_eq23 core_initial23.\n   intros. rename m2 into m3. rename v2 into v3. rename vals2 into vals3.\n    rewrite (EPC v1 v3 sig) in H. destruct H as [v2 [EP12 EP23]].\n    (*assert (HT: Forall2 Val.has_type vals1 (sig_args sig)).\n      eapply forall_valinject_hastype; eassumption.*)\n    destruct (initial_inject_split _ _ _ H1)\n       as [m2 [j1 [j2 [J [Inj12 [Inj23 [X [Y [XX YY]]]]]]]]].\n    subst. rewrite J in *.\n    destruct (Forward_simulation_trans.forall_val_inject_split _ _ _ _ H2)\n       as [vals2 [ValsInj12 ValsInj23]].\n    assert (PG1: meminj_preserves_globals g1 j1).\n      clear - X Y XX YY H3 H4.\n      apply meminj_preserves_genv2blocks.\n      apply meminj_preserves_genv2blocks in H3.\n      destruct H3 as [AA [BB CC]].\n      split; intros.\n         specialize (AA _ H).\n         destruct (compose_meminjD_Some _ _ _ _ _ AA)\n            as [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear AA.\n         destruct (XX _ _ _ J1); subst. trivial.\n      split; intros.\n         specialize (BB _ H).\n         destruct (compose_meminjD_Some _ _ _ _ _ BB)\n            as [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear BB.\n         destruct (XX _ _ _ J1); subst. trivial.\n      destruct (XX _ _ _ H0); subst. trivial.\n  assert (PG2: meminj_preserves_globals g2 j2).\n    clear - XX YY X Y PG1 H3 genvs_dom_eq12.\n    apply meminj_preserves_genv2blocks.\n     apply meminj_preserves_genv2blocks in H3.\n      destruct H3 as [AA [BB CC]].\n     apply meminj_preserves_genv2blocks in PG1.\n      destruct PG1 as [AA1 [BB1 CC1]].\n      destruct genvs_dom_eq12.\n      split; intros.\n         apply H in H1.\n         specialize (AA1 _ H1). specialize (AA _ H1).\n         destruct (compose_meminjD_Some _ _ _ _ _ AA)\n            as [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear AA.\n         rewrite J1 in AA1. inv AA1. simpl in D. subst. trivial.\n      split; intros.\n         apply H0 in H1.\n         specialize (BB1 _ H1). specialize (BB _ H1).\n         destruct (compose_meminjD_Some _ _ _ _ _ BB)\n            as [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear BB.\n         rewrite J1 in BB1. inv BB1. simpl in D. subst. trivial.\n      apply H0 in H1.\n         specialize (BB1 _ H1). specialize (BB _ H1). rename b2 into b3.\n         destruct (compose_meminjD_Some _ _ _ _ _ BB)\n            as [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear BB.\n         destruct (XX _ _ _ J1); subst. simpl in D. subst.\n         clear BB1 XX.\n         destruct (YY _ _ _ H2) as [XX | [XX | XX]].\n           apply flatinj_E in XX. destruct XX as [? [? ?]]; subst. trivial.\n           destruct XX as [? ?]; subst.\n             apply (CC _ _ _ H1 H4).\n           destruct XX as [mm [? ?]]; subst.\n             apply (CC _ _ _ H1 H4).\n     exploit (core_initial12 _ _ _ EP12 vals1 _ _ _ vals2 _ H0 Inj12). with (vals2:=vals3); try eassumption.\n         rewrite J. eassumption.\n         rewrite J. eassumption.\n         rewrite J. eassumption.\n         (*eapply forall_valinject_hastype; eassumption.*)\n         intros. eapply H6.\n              rewrite (genvs_domain_eq_isGlobal _ _ genvs_dom_eq23) in H.\n              assumption.\n       intros [d12 [c2 [Ini2 MC12]]].\n     exploit (core_initial23 _ _ _ EP23 vals2); try eassumption.\n         rewrite J. eassumption.\n         rewrite J. eassumption.\n         rewrite J. eassumption.\n         (*eapply forall_valinject_hastype; eassumption.*)\n         intros. eapply H6.\n              rewrite (genvs_domain_eq_isGlobal _ _ genvs_dom_eq23) in H.\n              assumption.\n\n        assert (Q: forall b,  isGlobalBlock g2 b || getBlocks vals2 b = true ->\n                   exists jb d, j2 b = Some (jb, d) /\\\n                           isGlobalBlock g3 jb || getBlocks vals3 jb = true).\n          intros b' Hb'. apply orb_true_iff in Hb'.\n          destruct Hb' as [Hb' | Hb'].\n            rewrite (meminj_preserves_globals_isGlobalBlock _ _ PG2 _ Hb').\n              exists b', 0.\n              rewrite (genvs_domain_eq_isGlobal _ _ genvs_dom_eq23) in Hb'.\n              rewrite Hb'. intuition.\n          destruct (getBlocks_inject _ _ _  ValsInj23 _ Hb') as [bb [ofs [J2 GB2]]].\n              exists bb, ofs. intuition.\n        specialize (REACH_inject _ _ _ Inj23\n            (fun b' : block => isGlobalBlock g2 b' || getBlocks vals2 b')\n            (fun b' : block => isGlobalBlock g3 b' || getBlocks vals3 b')\n            Q). intros. as [b3 [d2 [J2 R3]]].\n        rewrite J2.\n        destruct (Y _ _ _ J2) as [b1 [d COMP]].\n        apply (H4 _ _ _ COMP).\n      intros b2 Hb2. remember (j2 b2) as d.\n        destruct d; inv Hb2; apply eq_sym in Heqd. destruct p.\n        eapply Mem.valid_block_inject_1; eassumption.\n      (*eapply forall_valinject_hastype; eassumption.*)\n      intros. destruct (X b1) as [_ J1Comp].\n              destruct J1Comp as [b3 [dd COMP]]. exists b2, d; trivial.\n              specialize (H4 _ _ _ COMP).\n              destruct (compose_meminjD_Some _ _ _ _ _ COMP)\n                as [bb2 [dd1 [dd2 [J1 [J2 D]]]]]; subst; clear COMP.\n              rewrite J1 in H; inv H. rewrite J2. apply H4.\n      intros.*)\n (*initial_core*)\n   clear - EPC genvs_dom_eq12 core_initial12 genvs_dom_eq23 core_initial23.\n   intros. rename m2 into m3. rename v2 into v3. rename vals2 into vals3.\n    rewrite (EPC v1 v3 sig) in H. destruct H as [v2 [EP12 EP23]].\n    (*assert (HT: Forall2 Val.has_type vals1 (sig_args sig)).\n      eapply forall_valinject_hastype; eassumption.*)\n    destruct (initial_inject_split _ _ _ H1)\n       as [m2 [j1 [j2 [J [Inj12 [Inj23 [X [Y [XX YY]]]]]]]]].\n    subst.\n    destruct (Forward_simulation_trans.forall_val_inject_split _ _ _ _ H2)\n       as [vals2 [ValsInj12 ValsInj23]].\n    assert (PG1: meminj_preserves_globals g1 j1).\n      clear - X Y XX YY H3 H4.\n      apply meminj_preserves_genv2blocks.\n      apply meminj_preserves_genv2blocks in H3.\n      destruct H3 as [AA [BB CC]].\n      split; intros.\n         specialize (AA _ H).\n         destruct (compose_meminjD_Some _ _ _ _ _ AA)\n            as [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear AA.\n         destruct (XX _ _ _ J1); subst. trivial.\n      split; intros.\n         specialize (BB _ H).\n         destruct (compose_meminjD_Some _ _ _ _ _ BB)\n            as [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear BB.\n         destruct (XX _ _ _ J1); subst. trivial.\n      destruct (XX _ _ _ H0); subst. trivial.\n  assert (PG2: meminj_preserves_globals g2 j2).\n    clear - XX YY X Y PG1 H3 genvs_dom_eq12.\n    apply meminj_preserves_genv2blocks.\n     apply meminj_preserves_genv2blocks in H3.\n      destruct H3 as [AA [BB CC]].\n     apply meminj_preserves_genv2blocks in PG1.\n      destruct PG1 as [AA1 [BB1 CC1]].\n      destruct genvs_dom_eq12.\n      split; intros.\n         apply H in H1.\n         specialize (AA1 _ H1). specialize (AA _ H1).\n         destruct (compose_meminjD_Some _ _ _ _ _ AA)\n            as [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear AA.\n         rewrite J1 in AA1. inv AA1. simpl in D. subst. trivial.\n      split; intros.\n         apply H0 in H1.\n         specialize (BB1 _ H1). specialize (BB _ H1).\n         destruct (compose_meminjD_Some _ _ _ _ _ BB)\n            as [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear BB.\n         rewrite J1 in BB1. inv BB1. simpl in D. subst. trivial.\n      apply H0 in H1.\n         specialize (BB1 _ H1). specialize (BB _ H1). rename b2 into b3.\n         destruct (compose_meminjD_Some _ _ _ _ _ BB)\n            as [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear BB.\n         destruct (XX _ _ _ J1); subst. simpl in D. subst.\n         clear BB1 XX.\n         destruct (YY _ _ _ H2) as [XX | [XX | XX]].\n           apply flatinj_E in XX. destruct XX as [? [? ?]]; subst. trivial.\n           destruct XX as [? ?]; subst.\n             apply (CC _ _ _ H1 H4).\n           destruct XX as [mm [? ?]]; subst.\n             apply (CC _ _ _ H1 H4).\n    destruct (core_initial12 _ _ _ EP12 _ _ _ _ vals2 _\n       DomS (fun b => match j2 b with None => false | Some (b3,d) => DomT b3 end) H0 Inj12)\n     as [d12 [c2 [Ini2 MC12]]]; try assumption.\n      (*eapply forall_valinject_hastype; eassumption.*)\n      intros. destruct (X b1) as [_ J1Comp].\n              destruct J1Comp as [b3 [dd COMP]]. exists b2, d; trivial.\n              specialize (H4 _ _ _ COMP).\n              destruct (compose_meminjD_Some _ _ _ _ _ COMP)\n                as [bb2 [dd1 [dd2 [J1 [J2 D]]]]]; subst; clear COMP.\n              rewrite J1 in H; inv H. rewrite J2. apply H4.\n      intros.\n        assert (Q: forall b,  isGlobalBlock g2 b || getBlocks vals2 b = true ->\n                   exists jb d, j2 b = Some (jb, d) /\\\n                           isGlobalBlock g3 jb || getBlocks vals3 jb = true).\n          intros b' Hb'. apply orb_true_iff in Hb'.\n          destruct Hb' as [Hb' | Hb'].\n            rewrite (meminj_preserves_globals_isGlobalBlock _ _ PG2 _ Hb').\n              exists b', 0.\n              rewrite (genvs_domain_eq_isGlobal _ _ genvs_dom_eq23) in Hb'.\n              rewrite Hb'. intuition.\n          destruct (getBlocks_inject _ _ _  ValsInj23 _ Hb') as [bb [ofs [J2 GB2]]].\n              exists bb, ofs. intuition.\n        destruct (REACH_inject _ _ _ Inj23\n            (fun b' : block => isGlobalBlock g2 b' || getBlocks vals2 b')\n            (fun b' : block => isGlobalBlock g3 b' || getBlocks vals3 b')\n            Q _ H) as [b3 [d2 [J2 R3]]].\n        rewrite J2.\n        destruct (Y _ _ _ J2) as [b1 [d COMP]].\n        apply (H4 _ _ _ COMP).\n      intros b2 Hb2. remember (j2 b2) as d.\n        destruct d; inv Hb2; apply eq_sym in Heqd. destruct p.\n        eapply Mem.valid_block_inject_1; eassumption.\n    destruct (core_initial23 _ _ _ EP23 _ _ _ _ vals3 _\n       (fun b => match j2 b with None => false | Some (b3,d) => DomT b3 end) DomT Ini2 Inj23)\n     as [d23 [c3 [Ini3 MC23]]]; try assumption.\n       intros b2 b3 d2 J2. rewrite J2.\n         destruct (Y _ _ _ J2) as [b1 [d COMP]].\n         destruct (H4 _ _ _ COMP). split; trivial.\n    intros b2 Hb2. remember (j2 b2) as d.\n        destruct d; inv Hb2; apply eq_sym in Heqd. destruct p.\n        eapply Mem.valid_block_inject_1; eassumption.\n    remember (initial_SM DomS\n            (fun b : block =>\n             match j2 b with\n             | Some (b3, _) => DomT b3\n             | None => false\n             end) (REACH m1 (fun b => isGlobalBlock g1 b || getBlocks vals1 b))\n                  (REACH m2 (fun b => isGlobalBlock g2 b || getBlocks vals2 b))\n            j1) as mu1.\n  remember (initial_SM\n            (fun b : block =>\n             match j2 b with\n             | Some (b3, _) => DomT b3\n             | None => false\n             end) DomT (REACH m2 (fun b => isGlobalBlock g2 b || getBlocks vals2 b))\n                       (REACH m3 (fun b => isGlobalBlock g3 b || getBlocks vals3 b))\n             j2) as mu2.\n  exists (d12,Some c2,d23).\n  exists c3.\n  split; trivial.\n  exists c2, m2, mu1, mu2.\n  split; trivial.\n  split. subst. unfold initial_SM, compose_sm; simpl.\n           f_equal.\n  split. subst; simpl. repeat (split; trivial).\n  split; trivial.\n (*core_diagram*)\n  clear - match_sm_wd12 match_sm_valid12 core_diagram12\n          match_sm_wd23 match_sm_valid23 core_diagram23.\n  intros. rename st2 into st3. rename m2 into m3.\n  destruct cd as [[d12 cc2] d23].\n  destruct H0 as [c2 [m2 [mu12 [mu23 [X [J [INV [MC12 MC23]]]]]]]]; subst.\n  eapply core_diagram_trans; try eassumption.\n (*effcore_diagram*)\n  clear - match_sm_wd12 match_sm_valid12 effcore_diagram12\n          match_sm_wd23 match_sm_valid23 effcore_diagram23.\n  intros. rename st2 into st3. rename m2 into m3.\n  destruct cd as [[d12 cc2] d23].\n  destruct H0 as [c2 [m2 [mu12 [mu23 [X [J [INV [MC12 MC23]]]]]]]]; subst.\n  eapply effcore_diagram_trans; eassumption.\n(*halted*)\n  clear - match_sm_wd12 core_halted12 match_sm_wd23 core_halted23.\n  intros. rename c2 into c3. rename m2 into m3.\n  destruct cd as [[d12 cc2] d23].\n  destruct H as [c2 [m2 [mu12 [mu23 [X [J [INV [MC12 MC23]]]]]]]]; subst.\n  destruct (core_halted12 _ _ _ _ _ _ _ MC12 H0) as\n     [v2 [MInj12 [RValsInject12 HaltedMid]]].\n  destruct (core_halted23 _ _ _ _ _ _ _ MC23 HaltedMid) as\n     [v3 [MInj23 [RValsInject23 HaltedTgt]]].\n  exists v3.\n  assert (WDmu12:= match_sm_wd12 _ _ _ _ _ _ MC12).\n  assert (WDmu23:= match_sm_wd23 _ _ _ _ _ _ MC23).\n  destruct INV as [INVa [INVb [INVc INVd]]].\n\n  split. rewrite compose_sm_as_inj; trivial.\n           eapply Mem.inject_compose; eassumption.\n  split. rewrite compose_sm_as_inj; trivial.\n         rewrite restrict_compose, vis_compose_sm; simpl.\n         eapply val_inject_compose; try eassumption.\n         eapply val_inject_incr; try eassumption.\n         apply restrict_incr.\n  assumption.\n(*at_external*)\n  clear - match_sm_wd12 core_at_external12 match_sm_wd23 core_at_external23.\n  intros. rename c2 into c3. rename m2 into m3.\n  rename H0 into AtExtSrc.\n  destruct cd as [[d12 cc2] d23].\n  destruct H as [st2 [m2 [mu12 [mu23 [Hst2 [HMu [GLUEINV [MC12 MC23]]]]]]]].\n  subst.\n  destruct (core_at_external12 _ _ _ _ _ _ _ _ _ MC12 AtExtSrc)\n    as [MInj12 [vals2 [ArgsInj12 (*[ArgsHT2*) AtExt2(*]*)]]]; clear core_at_external12.\n  destruct (core_at_external23 _ _ _ _ _ _ _ _ _ MC23 AtExt2)\n    as [MInj23 [vals3 [ArgsInj23 (*[ArgsHTTgt*) AtExtTgt(*]*)]]]; clear core_at_external23.\n  rewrite compose_sm_as_inj; try eauto.\n    split. eapply Mem.inject_compose; eassumption.\n    exists vals3.\n    split. rewrite restrict_compose, vis_compose_sm; simpl.\n           eapply forall_val_inject_compose; try eassumption.\n           eapply forall_vals_inject_restrictD; eassumption.\n    (*split;*) assumption.\n  eapply GLUEINV.\n  eapply GLUEINV.\n(*after_external*)\n  clear - match_sm_wd12 match_sm_valid12 core_at_external12 eff_after_external12\n          match_visible12 match_restrict12\n          match_sm_wd23 match_sm_valid23 core_at_external23 eff_after_external23.\n  intros. rename st2 into st3. rename m2 into m3.\n          rename vals2 into vals3'. rename m2' into m3'.\n          rename UnchLOOR into UnchLOOR13.\n  destruct cd as [[d12 cc2] d23].\n  destruct MatchMu as [st2 [m2 [mu12 [mu23 [Hst2 [HMu [GLUEINV [MC12 MC23]]]]]]]].\n  assert (WDmu12:= match_sm_wd12 _ _ _ _ _ _ MC12).\n  assert (WDmu23:= match_sm_wd23 _ _ _ _ _ _ MC23).\n  remember (fun b => locBlocksSrc mu12 b || frgnBlocksSrc mu12 b || mapped (as_inj (compose_sm mu12 mu23)) b)\n      as RESTR.\n  assert (NormMC12: match_core12 d12 (restrict_sm mu12 RESTR) st1 m1 st2 m2).\n     apply match_restrict12. apply MC12.\n     subst RESTR. clear. intuition.\n     subst RESTR.\n     clear UnchLOOR13 UnchPrivSrc Mu'Hyp mu' frgnTgtHyp frgnTgt'\n              frgnSrcHyp frgnSrc' FwdTgt FwdSrc RValInjNu' MemInjNu'\n              SMvalNu' WDnu' SEP INC m3' ret2 m1' ret1 nu' NuHyp nu\n              pubTgtHyp pubTgt' pubSrcHyp pubSrc' ValInjMu AtExtTgt\n              AtExtSrc eff_after_external23 core_at_external23\n              eff_after_external12 core_at_external12.\n     subst. intros b Hb. rewrite REACHAX in Hb.\n      destruct Hb as [L HL].\n      generalize dependent b.\n      induction L; simpl; intros; inv HL.\n        apply H.\n      specialize (IHL _ H1); clear H1.\n        apply orb_true_iff in IHL. apply orb_true_iff.\n        destruct IHL.\n          left. eapply (match_visible12 _ _ _ _ _ _ MC12).\n                eapply REACH_cons; try eassumption.\n                apply REACH_nil. apply H.\n          right. eapply (inject_REACH_closed _ _ _ MemInjMu).\n                eapply REACH_cons; try eassumption.\n                apply REACH_nil. apply H.\n  remember (restrict_sm mu12 RESTR) as nmu12.\n  assert (HmuNorm: mu = compose_sm nmu12 mu23).\n     clear UnchLOOR13 UnchPrivSrc Mu'Hyp mu' frgnTgtHyp frgnTgt'\n              frgnSrcHyp frgnSrc' FwdTgt FwdSrc RValInjNu' MemInjNu'\n              SMvalNu' WDnu' SEP INC m3' ret2 m1' ret1 nu' NuHyp nu\n              pubTgtHyp pubTgt' pubSrcHyp pubSrc' ValInjMu AtExtTgt\n              AtExtSrc eff_after_external23 core_at_external23\n              eff_after_external12 core_at_external12.\n      subst nmu12 mu RESTR. unfold compose_sm; simpl.\n          rewrite restrict_sm_extern.\n          rewrite (restrict_sm_local' _ WDmu12).\n          Focus 2. clear. intuition.\n          unfold restrict_sm; simpl.\n          destruct mu12; simpl in *.\n          f_equal.\n          extensionality b. unfold compose_meminj, restrict, mapped, as_inj, join; simpl.\n          remember (extern_of b) as d.\n          specialize (disjoint_extern_local _ WDmu12 b); simpl; intros DD.\n          destruct d; trivial; apply eq_sym in Heqd.\n            destruct p as [b2 d1].\n            destruct DD; try congruence.\n            rewrite H.\n            destruct (extern_DomRng _ WDmu12 _ _ _ Heqd); simpl in *.\n            assert (EE:= extBlocksSrc_locBlocksSrc _ WDmu12 _ H0); simpl in *.\n            rewrite EE; simpl.\n            remember (frgnBlocksSrc b) as q.\n            destruct q; apply eq_sym in Heqq; simpl in *. reflexivity.\n            remember (StructuredInjections.extern_of mu23 b2) as w.\n            destruct w; trivial. destruct p. rewrite <- Heqw. trivial.\n         remember (locBlocksSrc b) as q.\n         destruct q; simpl; trivial.\n         remember (frgnBlocksSrc b) as w.\n         destruct w; trivial; simpl; apply eq_sym in Heqw.\n         remember (local_of b) as t.\n         destruct t; simpl; trivial.\n         destruct p; apply eq_sym in Heqt.\n         destruct (local_DomRng _ WDmu12 _ _ _ Heqt); simpl in *. congruence.\n  clear MC12.\n  assert (WDnmu12:= match_sm_wd12 _ _ _ _ _ _ NormMC12).\n  clear HMu.\n  assert (WDmu: SM_wd (compose_sm nmu12 mu23)).\n    eapply compose_sm_wd; try eassumption.\n      subst. unfold restrict_sm, restrict; simpl. destruct mu12; simpl in *. apply GLUEINV.\n      subst. unfold restrict_sm, restrict; simpl. destruct mu12; simpl in *. apply GLUEINV.\n  clear match_restrict12 match_visible12.\n  assert (mu12_valid:= match_sm_valid12 _ _ _ _ _ _ NormMC12).\n  assert (mu23_valid:= match_sm_valid23 _ _ _ _ _ _ MC23).\n  rename ret2 into ret3.\n  destruct (core_at_external12 _ _ _ _ _ _ _ _ _ NormMC12 AtExtSrc)\n   as [MInj12 [vals2 [ArgsInj12 (*[ArgsHT2*) AtExt2(*]*)]]]; clear core_at_external12.\n  destruct (core_at_external23 _ _ _ _ _ _ _ _ _ MC23 AtExt2)\n   as [MInj23 [vals3 [ArgsInj23 (*[ArgsHT3*) AtExt3(*]*)]]]; clear core_at_external23.\n\n  (*Prove uniqueness of e, ef_sig, vals3. We do this by hand, instead of\n     rewrite AtExtTgt in AtExt3; inv Atext3 in order to avoid the subst\n     taht's inherent in inv AtExt3. Probably there's a better way to do this..*)\n  assert (e' = e /\\ ef_sig' = ef_sig /\\ vals3'=vals3).\n     rewrite AtExtTgt in AtExt3. inv AtExt3. intuition.\n  destruct H as [HH1 [HH2 HH3]].\n  rewrite HH1, HH2, HH3 in *. clear HH1 HH2 HH3 e' ef_sig' vals3' AtExt3.\n\n  (*clear MemInjMu. follows from MInj12 MInj23*)\n  specialize (eff_after_external12 _ _ _ _ _ _ _ _ _ _ _ _ MInj12\n        NormMC12 AtExtSrc AtExt2 ArgsInj12\n        _ (eq_refl _) _ (eq_refl _) _ (eq_refl _)).\n  specialize (eff_after_external23 _ _ _ _ _ _ _ _ _\n      _ _ _ MInj23 MC23 AtExt2 AtExtTgt ArgsInj23 _ (eq_refl _)\n      _ (eq_refl _) _ (eq_refl _)).\n  assert (LeakedCompSrc: locBlocksSrc mu = locBlocksSrc nmu12 /\\\n                         extBlocksSrc mu = extBlocksSrc nmu12 /\\\n                        exportedSrc mu vals1 = exportedSrc nmu12 vals1).\n     subst. clear - WDnmu12 WDmu. simpl.\n        rewrite restrict_sm_locBlocksSrc.\n        rewrite restrict_sm_extBlocksSrc.\n        unfold exportedSrc.\n        rewrite sharedSrc_iff_frgnpub; trivial. simpl.\n        rewrite sharedSrc_iff_frgnpub; trivial.\n        rewrite restrict_sm_frgnBlocksSrc, restrict_sm_pubBlocksSrc.\n        intuition.\n  destruct LeakedCompSrc as [LSa [LSb LSc]].\n    rewrite LSa, LSc in *. clear LSa LSb LSc.\n  assert (LeakedCompTgt: locBlocksTgt mu = locBlocksTgt mu23\n                       /\\ extBlocksTgt mu = extBlocksTgt mu23\n                       /\\ exportedTgt mu vals3 = exportedTgt mu23 vals3).\n     subst. clear - WDmu23 WDmu. simpl.\n        unfold exportedTgt, sharedTgt. simpl. intuition.\n  destruct LeakedCompTgt as [LTa [LTb LTc]].\n    rewrite LTa, LTc in *. clear LTa LTb LTc.\n   remember (fun b => locBlocksTgt nmu12 b &&\n             REACH m2 (exportedTgt nmu12 vals2) b) as pubTgtMid'.\n   remember (fun b => locBlocksSrc mu23 b &&\n             REACH m2 (exportedSrc mu23 vals2) b) as pubSrcMid'.\n   assert (MID: forall b, pubTgtMid' b = true -> pubSrcMid' b = true).\n        clear eff_after_external12 match_sm_valid23 eff_after_external23.\n        rewrite HeqpubTgtMid', HeqpubSrcMid'.\n        destruct GLUEINV as [GlueA [GlueB [GlueC GlueD]]].\n        subst.\n        clear UnchLOOR13 UnchPrivSrc SEP INC MemInjMu ArgsInj12 MInj12.\n\n        rewrite restrict_sm_locBlocksTgt. (*sm_extern_normalize_exportedTgt; trivial.*)\n           rewrite GlueA. intros b Hb. rewrite andb_true_iff in *.\n        destruct Hb. split; trivial.\n        eapply REACH_mono; try eassumption.\n        unfold exportedTgt, exportedSrc, sharedTgt.\n        rewrite restrict_sm_frgnBlocksTgt, restrict_sm_pubBlocksTgt.\n        rewrite sharedSrc_iff_frgnpub; trivial.\n        intros. repeat rewrite orb_true_iff in *.\n        intuition.\n  assert (NU: nu = compose_sm (replace_locals nmu12 pubSrc' pubTgtMid')\n              (replace_locals mu23 pubSrcMid' pubTgt')).\n     clear frgnSrcHyp frgnTgtHyp eff_after_external23.\n     subst. unfold compose_sm; simpl.\n     rewrite replace_locals_extern, replace_locals_local,\n             replace_locals_locBlocksSrc, replace_locals_locBlocksTgt,\n            replace_locals_pubBlocksSrc, replace_locals_pubBlocksTgt,\n            replace_locals_frgnBlocksSrc, replace_locals_frgnBlocksTgt,\n            replace_locals_extBlocksSrc, replace_locals_extBlocksTgt.\n     rewrite replace_locals_extern, replace_locals_local.\n     rewrite restrict_sm_extBlocksSrc, restrict_sm_locBlocksSrc,\n             restrict_sm_local, restrict_sm_extern.\n     f_equal.\n\n  clear NuHyp.\n  (*produce all the hypothesis necessary for applying interpolation*)\n  assert (MinjNu12: Mem.inject (as_inj (replace_locals nmu12 pubSrc' pubTgtMid')) m1 m2).\n     rewrite replace_locals_as_inj. assumption.\n  assert (MinjNu23: Mem.inject (as_inj (replace_locals mu23 pubSrcMid' pubTgt')) m2 m3).\n     rewrite replace_locals_as_inj. assumption.\n  assert (ArgsInj12R: Forall2\n    (val_inject\n       (as_inj\n          (restrict_sm mu12\n             (fun b : block =>\n              locBlocksSrc mu12 b || frgnBlocksSrc mu12 b\n              || mapped (as_inj (compose_sm mu12 mu23)) b)))) vals1 vals2).\n      clear - ArgsInj12 Heqnmu12 HeqRESTR.\n      rewrite restrict_sm_all. subst. rewrite restrict_sm_all in ArgsInj12.\n       rewrite restrict_nest in ArgsInj12.\n       eapply val_list_inject_forall_inject.\n       apply forall_inject_val_list_inject in ArgsInj12.\n       eapply val_list_inject_incr; try eassumption.\n       red; intros. destruct (restrictD_Some _ _ _ _ _ H); clear H.\n          unfold vis in H1. rewrite restrict_sm_locBlocksSrc, restrict_sm_frgnBlocksSrc in H1.\n          apply restrictI_Some; intuition.\n    intros. rewrite effect_properties.vis_restrict_sm in H.\n      unfold vis in H. intuition.\n  clear ArgsInj12.\n  assert (WDnu12: SM_wd (replace_locals nmu12 pubSrc' pubTgtMid')).\n       subst.\n       eapply replace_locals_wd; try eassumption.\n         intros. apply andb_true_iff in H.\n           destruct H as [locB R].\n           destruct (REACH_local_REACH _ WDnmu12 _ _ _ _\n              MInj12 ArgsInj12R _ R locB) as [b2 [d1 [LOC12 R2]]].\n           exists b2, d1; split; trivial.\n           rewrite andb_true_iff, R2.\n           split; trivial.\n           eapply local_locBlocks; eassumption.\n         intros. apply andb_true_iff in H. apply H.\n  assert (ArgsInj23R: Forall2 (val_inject (as_inj mu23)) vals2 vals3).\n       eapply val_list_inject_forall_inject.\n       apply forall_inject_val_list_inject in ArgsInj23.\n       eapply val_list_inject_incr; try eassumption.\n       apply restrict_incr.\n  clear ArgsInj23.\n  assert (WDnu23: SM_wd (replace_locals mu23 pubSrcMid' pubTgt')).\n       subst.\n       eapply replace_locals_wd; try eassumption.\n       destruct GLUEINV as [GIa [GIb [GIc GId]]]. subst.\n       intros b2; intros. apply andb_true_iff in H.\n           destruct H as [locB R].\n           destruct (REACH_local_REACH _ WDmu23 _ _ _ _\n              MInj23 ArgsInj23R _ R locB) as [b3 [d2 [LOC23 R3]]].\n           exists b3, d2; split; trivial.\n           rewrite andb_true_iff, R3.\n           split; trivial.\n           eapply local_locBlocks; eassumption.\n         intros. apply andb_true_iff in H. apply H.\n  assert (nu12_valid: sm_valid (replace_locals nmu12 pubSrc' pubTgtMid') m1 m2).\n     split. rewrite replace_locals_DOM. eapply mu12_valid.\n     rewrite replace_locals_RNG. eapply mu12_valid.\n  assert (nu23_valid: sm_valid (replace_locals mu23 pubSrcMid' pubTgt') m2 m3).\n     split. rewrite replace_locals_DOM. eapply mu23_valid.\n     rewrite replace_locals_RNG. eapply mu23_valid.\n  rewrite NU in INC, SEP.\n  destruct (EFFAX.effect_interp_II _ _ _ MinjNu12 _ FwdSrc\n      _ _ MinjNu23 _ FwdTgt nu' WDnu' SMvalNu' MemInjNu'\n      INC SEP nu12_valid nu23_valid)\n     as [m2' [nu12' [nu23' [X [Incr12 [Incr23 [MInj12'\n        [Fwd2 [MInj23' [Sep12 [Sep23 [nu12'valid\n        [nu23'valid [GLUEINV' [Norm' [UnchMidA UnchMidB]]]]]]]]]]]]]]]]; simpl in *.\n    (*discharge the unchOn application conditions*)\n       subst; apply UnchPrivSrc.\n       subst. apply UnchLOOR13.\n    (*discharge the GLUE application condition*)\n      rewrite replace_locals_extBlocksSrc, replace_locals_extBlocksTgt,\n            replace_locals_locBlocksSrc, replace_locals_locBlocksTgt,\n            replace_locals_pubBlocksSrc, replace_locals_pubBlocksTgt,\n            replace_locals_frgnBlocksSrc, replace_locals_frgnBlocksTgt.\n      destruct GLUEINV as [GLUEa [GLUEb [GLUEc GLUEd]]].\n      repeat (split; trivial).\n      subst. rewrite restrict_sm_locBlocksTgt; trivial.\n      subst. rewrite restrict_sm_extBlocksTgt; trivial.\n      subst. rewrite restrict_sm_frgnBlocksTgt; trivial.\n    (*discharge the Norm Hypothesis*)\n      rewrite Heqnmu12. do 2 rewrite replace_locals_extern.\n      rewrite restrict_sm_extern.\n      intros. destruct (restrictD_Some _ _ _ _ _ H) as [EX12 RR]; clear H.\n      subst RESTR nmu12.\n     clear UnchLOOR13 UnchPrivSrc Mu'Hyp mu' frgnTgtHyp frgnTgt'\n              frgnSrcHyp frgnSrc' FwdTgt FwdSrc RValInjNu' MemInjNu'\n              SMvalNu' WDnu' SEP INC m3' m1' ret1 nu'\n              pubTgtHyp pubSrcHyp ValInjMu AtExtTgt\n              AtExtSrc eff_after_external23\n              eff_after_external12 MinjNu23.\n      destruct (extern_DomRng _ WDmu12 _ _ _ EX12).\n      rewrite (extBlocksSrc_locBlocksSrc _ WDmu12 _ H) in RR; simpl in *.\n      remember (frgnBlocksSrc mu12 b1) as d.\n      destruct d; apply eq_sym in Heqd.\n        destruct (frgnSrc _ WDmu12 _ Heqd) as [bb2 [dd1 [Frg1 FT2]]]; clear Heqd.\n        apply foreign_in_extern in Frg1. rewrite Frg1 in EX12; inv EX12.\n        destruct GLUEINV as [_ [_ [_ FF]]]. apply FF in FT2.\n        destruct (frgnSrc _ WDmu23 _ FT2) as [b3 [d2 [Frg2 FT3]]]; clear FT2.\n        rewrite (foreign_in_extern _ _ _ _ Frg2). exists b3, d2; trivial.\n      simpl in RR. destruct (mappedD_true _ _ RR) as [[bb dd] M]; clear RR.\n        destruct (joinD_Some _ _ _ _ _ M) as [EXT | [EXT LOC]]; clear M;\n          rewrite compose_sm_extern in EXT.\n          destruct (compose_meminjD_Some _ _ _ _ _ EXT) as [bb2 [dd1 [dd2 [E1 [E2 D]]]]].\n          rewrite EX12 in E1. inv E1. rewrite E2. exists bb, dd2; trivial.\n        rewrite compose_sm_local in LOC.\n          destruct (compose_meminjD_Some _ _ _ _ _ LOC) as [bb2 [dd1 [dd2 [E1 [E2 D]]]]].\n          destruct (disjoint_extern_local _ WDmu12 b1); congruence.\n  assert (UnchMidC : Mem.unchanged_on (local_out_of_reach (replace_locals mu23 pubSrcMid' pubTgt') m2) m3 m3').\n    clear - WDmu23 HeqpubTgtMid' HeqpubSrcMid' MinjNu12 UnchLOOR13 WDnu12 NU pubSrcHyp Heqnmu12 HeqRESTR GLUEINV.\n    subst nmu12.\n    remember (replace_locals (restrict_sm mu12 RESTR) pubSrc' pubTgtMid') as kappa12.\n    remember (replace_locals mu23 pubSrcMid' pubTgt') as kappa23.\n    assert (GluePubKappa : forall b : block,\n          pubBlocksTgt kappa12 b = true -> pubBlocksSrc kappa23 b = true).\n       clear UnchLOOR13 WDnu12 MinjNu12.\n       subst kappa12 kappa23. rewrite replace_locals_pubBlocksSrc, replace_locals_pubBlocksTgt.\n       subst. rewrite restrict_sm_locBlocksTgt; intros; trivial.\n              apply andb_true_iff in H. destruct H.\n              destruct GLUEINV as [Ga [Gb [Gc Gd]]]. rewrite Ga in H.\n              rewrite H; simpl.\n              eapply REACH_mono; try eassumption.\n              unfold exportedTgt, exportedSrc, sharedTgt. rewrite sharedSrc_iff_frgnpub.\n              rewrite restrict_sm_frgnBlocksTgt, restrict_sm_pubBlocksTgt.\n              intros. do 2 rewrite orb_true_iff in H1.\n                do 2 rewrite orb_true_iff. intuition.\n           assumption.\n    clear Heqkappa12 Heqkappa23 GLUEINV.\n    subst.\n    unfold local_out_of_reach.\n    split; intros; rename b into b3.\n      destruct H as[locTgt3 LOOR23].\n      eapply UnchLOOR13; trivial; simpl.\n        split; simpl; trivial.\n        intros b1; intros; simpl in *.\n        remember (pubBlocksSrc kappa12 b1) as d.\n        destruct d; try (right; reflexivity).\n        left. apply eq_sym in Heqd.\n        destruct (compose_meminjD_Some _ _ _ _ _ H)\n          as [b2 [d1 [d2 [LOC1 [LOC2 D]]]]]; subst; clear H.\n        destruct (pubSrc _ WDnu12 _ Heqd) as [bb2 [dd1 [Pub12 PubTgt2]]].\n        rewrite (pub_in_local _ _ _ _ Pub12) in LOC1. inv LOC1.\n        apply GluePubKappa in PubTgt2.\n        destruct (LOOR23 _ _ LOC2); clear LOOR23.\n          intros N. apply H.\n          assert (Arith : ofs - (d1 + d2) + d1 = ofs - d2) by omega.\n          rewrite <- Arith.\n          eapply MinjNu12. eapply pub_in_all; try eassumption. apply N.\n        rewrite H in PubTgt2. discriminate.\n    destruct H as[locTgt3 LOOR23].\n      eapply UnchLOOR13; trivial; simpl.\n        split; trivial.\n        intros b1; intros; simpl in *.\n        remember (pubBlocksSrc kappa12 b1) as d.\n        destruct d; try (right; reflexivity).\n        left. apply eq_sym in Heqd.\n        destruct (compose_meminjD_Some _ _ _ _ _ H)\n          as [b2 [d1 [d2 [LOC1 [LOC2 D]]]]]; subst; clear H.\n        destruct (pubSrc _ WDnu12 _ Heqd) as [bb2 [dd1 [Pub12 PubTgt2]]].\n        rewrite (pub_in_local _ _ _ _ Pub12) in LOC1. inv LOC1.\n        apply GluePubKappa in PubTgt2.\n        destruct (LOOR23 _ _ LOC2); clear LOOR23.\n          intros N. apply H.\n          assert (Arith : ofs - (d1 + d2) + d1 = ofs - d2) by omega.\n          rewrite <- Arith.\n          eapply MinjNu12. eapply pub_in_all; try eassumption. apply N.\n        rewrite H in PubTgt2. discriminate.\n  (*next, prepare for application of eff_after_external12*)\n  destruct GLUEINV' as [WDnu12' [WDnu23' [GLUEa' [GLUEb' [GLUEc' GLUEd']]]]].\n  assert (exists ret2, val_inject (as_inj nu12') ret1 ret2 /\\\n                       val_inject (as_inj nu23') ret2 ret3 (*/\\\n                       Val.has_type ret2 (proj_sig_res ef_sig)*)).\n    subst. rewrite compose_sm_as_inj in RValInjNu'; trivial.\n    destruct (val_inject_split _ _ _ _ RValInjNu')\n      as [ret2 [RValInjNu12' RValInjNu23']].\n    exists ret2. repeat (split; trivial).\n    (*eapply valinject_hastype; eassumption.*)\n  destruct H as [ret2 [RValInjNu12' (*[*)RValInjNu23' (*RetType2]*)]].\n  subst.\n  specialize (eff_after_external12 nu12' ret1\n     m1' ret2 m2' Incr12 Sep12 WDnu12' nu12'valid MInj12' RValInjNu12'\n     FwdSrc Fwd2 (*RetType2*)).\n\n  destruct (eff_after_external12 _ (eq_refl _)\n      _ (eq_refl _) _ (eq_refl _))\n    as [d12' [c1' [c2' [AftExt1 [AftExt2 MC12']]]]]; clear eff_after_external12.\n   (*discharge unchangedOn-application conditions*)\n      apply UnchPrivSrc.\n      apply UnchMidB.\n\n  (*next, apply eff_after_external23*)\n  specialize (eff_after_external23 nu23').\n  destruct (eff_after_external23 ret2 m2'\n       ret3 m3' Incr23 Sep23 WDnu23' nu23'valid\n       MInj23' RValInjNu23' Fwd2 FwdTgt (*RetTypeTgt*)\n     _ (eq_refl _) _ (eq_refl _) _ (eq_refl _)) as\n     [d23' [c22' [c3' [AftExt22 [AftExt3 MC23']]]]];\n    subst; clear eff_after_external23.\n    (*discharge unchangedOn application conditions*)\n      apply UnchMidA.\n      apply UnchMidC.\n\n  (*finally, instantiate the existentials, and establish conclusion*)\n  rewrite AftExt22 in AftExt2. inv AftExt2.\n  clear GLUEINV.\n  exists (d12', Some c2', d23').\n  exists c1'. exists c3'.\n  split. assumption.\n  split. assumption.\n  exists c2'. exists m2'.\n  exists (replace_externs nu12'\n            (fun b => DomSrc nu12' b && (negb (locBlocksSrc nu12' b)\n                                     && REACH m1' (exportedSrc nu12' (ret1::nil)) b))\n            (fun b => DomTgt nu12' b && (negb (locBlocksTgt nu12' b)\n                                     && REACH m2' (exportedTgt nu12' (ret2::nil)) b))).\n  exists (replace_externs nu23'\n            (fun b => DomSrc nu23' b && (negb (locBlocksSrc nu23' b)\n                                     && REACH m2' (exportedSrc nu23' (ret2::nil)) b))\n            (fun b => DomTgt nu23' b && (negb (locBlocksTgt nu23' b)\n                                     && REACH m3' (exportedTgt nu23' (ret3::nil)) b))).\n  split. reflexivity.\n  unfold compose_sm. simpl.\n         repeat rewrite replace_externs_extBlocksSrc, replace_externs_extBlocksTgt,\n                 replace_externs_locBlocksSrc, replace_externs_locBlocksTgt,\n                 replace_externs_pubBlocksSrc, replace_externs_pubBlocksTgt,\n                 replace_externs_frgnBlocksSrc, replace_externs_frgnBlocksTgt.\n        rewrite replace_externs_extern, replace_externs_local.\n        rewrite replace_externs_extern, replace_externs_local.\n  split. f_equal; trivial.\n         unfold exportedSrc; simpl.\n           rewrite sharedSrc_iff_frgnpub; trivial.\n           rewrite sharedSrc_iff_frgnpub; trivial.\n  clear UnchLOOR13 UnchPrivSrc SEP INC MID UnchMidB Incr12\n        Sep12 WDnu12 nu12_valid MinjNu12 UnchMidC UnchMidA Sep23\n        Incr23 nu23_valid WDnu23 MinjNu23 MemInjMu ValInjMu.\n  split.\n    clear MC23' MC12'.\n    repeat (split; trivial). unfold DomTgt, DomSrc.\n    rewrite GLUEa', GLUEb'.\n         intros. do 2 rewrite andb_true_iff.\n                 do 2 rewrite andb_true_iff in H.\n                 destruct H as [HH1 [HH2 HH3]].\n                 split; trivial. split; trivial.\n                 eapply REACH_mono; try eassumption.\n                 unfold exportedTgt, exportedSrc; intros.\n                 apply orb_true_iff. apply orb_true_iff in H.\n                 destruct H.\n                   left; trivial.\n                   right. unfold sharedTgt in H.\n                          rewrite sharedSrc_iff_frgnpub.\n                          apply orb_true_intro.\n                          apply orb_prop in H.\n                          destruct H.\n                            left. intuition.\n                            right. intuition.\n               assumption.\n   split; assumption.\nQed.\n\nEnd Eff_sim_trans.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/sepcomp/submit_shmem/effect_simulations_trans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.3451052776934245, "lm_q1q2_score": 0.2284330778818424}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Crypto.Bedrock.Field.Common.Types.\nRequire Import Crypto.Language.API.\nLocal Open Scope Z_scope.\n\nImport API.Compilers.\nImport Types.Notations.\n\nSection VarnameSet.\n  Context \n    {width BW word mem locals env ext_spec varname_gen error}\n   `{parameters_sentinel : @parameters\n     width BW word mem locals env ext_spec varname_gen error}.\n  Context {listZ : rep.rep base_listZ}.\n  Existing Instance rep.Z.\n\n  (* Set of variable names used by an ltype *)\n  Fixpoint varname_set_base {t}\n    : base_ltype t -> PropSet.set string :=\n    match t with\n    | base.type.prod a b =>\n      fun x => PropSet.union (varname_set_base (fst x))\n                             (varname_set_base (snd x))\n    | base_listZ => rep.varname_set\n    | _ => rep.varname_set\n    end.\n  Fixpoint varname_set_args {t}\n    : type.for_each_lhs_of_arrow ltype t ->\n      PropSet.set string :=\n    match t as t0 return type.for_each_lhs_of_arrow _ t0 -> _ with\n    | type.base b => fun _:unit => PropSet.empty_set\n    | type.arrow (type.base a) b =>\n      fun (x:base_ltype a * _) =>\n        PropSet.union (varname_set_base (fst x))\n                      (varname_set_args (snd x))\n    | _ => fun _ => PropSet.empty_set (* garbage; invalid argument *)\n    end.\n  Definition varname_set {t} : ltype t -> PropSet.set string :=\n    match t with\n    | type.base _ => varname_set_base\n    | _ => fun _ => PropSet.empty_set\n    end.\n\n  Fixpoint varname_set_listonly {t}\n    : base_ltype t ->\n      PropSet.set string :=\n    match t with\n    | base.type.prod a b =>\n      fun x => PropSet.union (varname_set_listonly (fst x))\n                             (varname_set_listonly (snd x))\n    | base_listZ => rep.varname_set\n    | _ => fun _ => PropSet.empty_set\n    end.\n  Fixpoint varname_set_listexcl {t}\n    : base_ltype t ->\n      PropSet.set string :=\n    match t with\n    | base.type.prod a b =>\n      fun x => PropSet.union (varname_set_listexcl (fst x))\n                             (varname_set_listexcl (snd x))\n    | base_listZ => fun _ => PropSet.empty_set\n    | _ => rep.varname_set\n    end.\nEnd VarnameSet.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Bedrock/Field/Translation/Proofs/VarnameSet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22842631349622136}}
{"text": "Require Import Thread Arrays8.\n\n\nModule Type S.\n  Variables globalSched globalSock : W.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nModule M'''.\n  Definition globalSched := M.globalSched.\n\n  Open Scope Sep_scope.\n\n  Definition globalInv (fs : files) : HProp := Ex fr, globalSock =*> fr * [| fr %in fs |].\nEnd M'''.\n\nLtac unf := unfold M'''.globalSched, M'''.globalInv in *.\n\nModule T := Thread.Make(M''').\n\nImport T M'''.\nExport T M'''.\n\nDefinition hints : TacPackage.\n  prepare (materialize_buffer, buffer_split_tagged) buffer_join_tagged.\nDefined.\n\nLtac sep := T.sep unf hints.\n\nDefinition handlerS := SPEC reserving 49\n  Al fs, PREmain[_] sched fs * globalInv fs * mallocHeap 0.\n\nDefinition mainS := SPEC reserving 49\n  PREmain[_] globalSched =?> 1 * globalSock =?> 1 * mallocHeap 0.\n\nDefinition writeSomeS := SPEC(\"fr\", \"buf\", \"len\") reserving 36\n  Al fs, Al len,\n  PRE[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 len * [| (wordToNat (V \"len\") <= len)%nat |]\n    * sched fs * globalInv fs * mallocHeap 0\n  POST[_] Ex fs', [| fs %<= fs' |] * V \"buf\" =?>8 len * sched fs' * globalInv fs' * mallocHeap 0.\n\nDefinition m := bimport [[ \"malloc\"!\"malloc\" @ [mallocS],\n                           \"scheduler\"!\"init\" @ [initS], \"scheduler\"!\"exit\" @ [exitS],\n                           \"scheduler\"!\"spawn\" @ [spawnS], \"scheduler\"!\"listen\" @ [listenS],\n                           \"scheduler\"!\"accept\" @ [acceptS], \"scheduler\"!\"read\" @ [readS],\n                           \"scheduler\"!\"write\" @ [writeS], \"scheduler\"!\"close\" @ [closeS] ]]\n  bmodule \"test\" {{\n    bfunction \"writeSome\"(\"fr\", \"buf\", \"len\") [writeSomeS]\n      Assert [Al fs, Al len,\n        PRE[V] [| V \"fr\" %in fs |] * buffer_splitAt (wordToNat (V \"len\")) (V \"buf\") len\n          * [| (wordToNat (V \"len\") <= len)%nat |] * sched fs * globalInv fs * mallocHeap 0\n        POST[_] Ex fs', [| fs %<= fs' |] * buffer_joinAt (wordToNat (V \"len\")) (V \"buf\") len\n          * sched fs' * globalInv fs' * mallocHeap 0];;\n\n      Call \"scheduler\"!\"write\"(\"fr\", \"buf\", \"len\")\n      [PRE[_] Emp POST[_] Emp];;\n      Return 0\n    end with bfunctionNoRet \"handler\"(\"buf\", \"fr\", \"n\") [handlerS]\n      \"buf\" <-- Call \"malloc\"!\"malloc\"(0, 10)\n      [Al fs, PREmain[_, R] R =?> 10 * sched fs * globalInv fs * mallocHeap 0];;\n\n      Note [please_materialize_buffer 10];;\n\n      [Al fs, PREmain[V] V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0]\n      While (0 = 0) {\n        \"fr\" <-- Call \"scheduler\"!\"accept\"($[globalSock])\n        [Al fs, PREmain[V, R] [| R %in fs |] * V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0];;\n\n        \"n\" <-- Call \"scheduler\"!\"read\"(\"fr\", \"buf\", 40)\n        [Al fs, PREmain[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0];;\n\n        [Al fs, PREmain[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0]\n        While (\"n\" <> 0) {\n          If (\"n\" <= 40) {\n            Call \"test\"!\"writeSome\"(\"fr\", \"buf\", \"n\")\n            [Al fs, PREmain[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0]\n          } else {\n            Skip\n          };;\n\n          \"n\" <-- Call \"scheduler\"!\"read\"(\"fr\", \"buf\", 40)\n          [Al fs, PREmain[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0]\n        };;\n\n        Call \"scheduler\"!\"close\"(\"fr\")\n        [Al fs, PREmain[V] V \"buf\" =?>8 40 * sched fs * globalInv fs * mallocHeap 0]\n      }\n    end with bfunctionNoRet \"main\"(\"fr\", \"x\") [mainS]\n      Init\n      [Al fs, Al v, PREmain[_] sched fs * globalSock =*> v * mallocHeap 0];;\n\n      \"fr\" <-- Call \"scheduler\"!\"listen\"(8080%N)\n      [Al fs, Al v, PREmain[_, R] [| R %in fs |] * sched fs * globalSock =*> v * mallocHeap 0];;\n\n      globalSock *<- \"fr\";;\n\n      Spawn(\"test\"!\"handler\", 50)\n      [Al fs, PREmain[_] sched fs * globalInv fs * mallocHeap 0];;\n\n      Spawn(\"test\"!\"handler\", 50)\n      [Al fs, PREmain[_] sched fs * globalInv fs * mallocHeap 0];;\n\n      Exit 50\n    end\n  }}.\n\nOpaque allocated.\n\nLemma single_cell : forall p,\n  (p =?> 1 = (Ex v, p =*> v) * Emp)%Sep.\n  auto.\nQed.\n\nLemma le_40 : forall w : W,\n  w <= natToW 40\n  -> (wordToNat w <= 40)%nat.\n  intros; pre_nomega.\n  rewrite wordToNat_natToWord_idempotent in * by reflexivity; omega.\nQed.\n\nHint Immediate le_40.\n\nLtac t' := try rewrite (single_cell globalSock); sep; auto.\nLtac t := solve [ t'\n  | post; evaluate hints; descend;\n    try match goal with\n          | [ _ : context[locals ?ns ?X _ _] |- context[locals ?ns ?Y _ _] ] => equate X Y\n        end; t' ].\n\nTheorem ok : moduleOk m.\n  vcgen; abstract t.\nQed.\n\nEnd Make.\n", "meta": {"author": "gmalecha", "repo": "bedrock-mirror-shard", "sha": "ea7e5ad56a1d6392468b6823e0457dd44524bca7", "save_path": "github-repos/coq/gmalecha-bedrock-mirror-shard", "path": "github-repos/coq/gmalecha-bedrock-mirror-shard/bedrock-mirror-shard-ea7e5ad56a1d6392468b6823e0457dd44524bca7/platform/tests/Echo3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.22840144208036733}}
{"text": "Require Import Lia IndefiniteDescription Arith.\nFrom hahn Require Import Hahn.\nRequire Import AuxRel.\nRequire Import Labels.\nRequire Import Events.\nRequire Import Execution.\nRequire Import View.\n\nSet Implicit Arguments.\n\nRecord Message :=\n  Msg {\n      mloc : Loc ;\n      mval : Val ;\n      mts  : Timestamp ;\n      mview : View }.\n\nDefinition Memory := (Message -> Prop).\nDefinition State := (Memory * (Tid -> View))%type.\n\nDefinition Minit : Memory :=\n  fun m => mval m = 0 /\\ mts m = 0 /\\\n           mview m = fun _ => 0.\n\nDefinition Vinit : View := fun x => 0.\nDefinition Sinit : State := (Minit, fun tid => Vinit).\n\nInductive SCOH_label :=\n  | SCOH_event (e : Event) (tstamp : Timestamp) (view : View)\n  | SCOH_internal (t : Tid) (x : Loc) (tstamp : Timestamp).\n\nDefinition deflabel : SCOH_label := SCOH_internal 0 0 0.\n\nDefinition read_ts x :=\n  match x with\n  | SCOH_event _ ts _ => ts\n  | SCOH_internal _ _ _ => 0\n  end.\n\nDefinition write_ts x :=\n  match x with\n  | SCOH_event _ ts _ => S ts\n  | SCOH_internal _ _ _ => 0\n  end.\n\nDefinition tid_of x :=\n  match x with\n  | SCOH_event e _ _ => tid e\n  | SCOH_internal tid x _ => tid\n  end.\n\nDefinition is_external x :=\n  match x with\n  | SCOH_event (ThreadEvent _ _ _) _ _ => True\n  | _ => False\n  end.\n\nDefinition proj_ev x :=\n  match x with\n  | SCOH_event e _ _ => e\n  | SCOH_internal _ _ _ => InitEvent 0\n  end.\n\nDefinition trproj t :=\n  trace_map proj_ev (trace_filter is_external t).\n\nDefinition fresh_tstamp (m : Memory) x ts :=\n  ~ exists v view, m (Msg x v ts view).\n\nInductive SCOH_step (MV : State) (e: SCOH_label) (MV' : State) : Prop :=\n| SCOHstep_read t i x v tstamp view view'\n              (EQ: e = SCOH_event (ThreadEvent t i (Aload x v)) tstamp view')\n\t      (MSG: fst MV (Msg x v tstamp view))\n              (LEV: snd MV t x <= tstamp)\n              (MEM: fst MV' = fst MV)\n              (EQ': view' = upd (snd MV t) x tstamp)\n\t      (VIEW: snd MV' = upd (snd MV) t view')\n| SCOHstep_write t i x v tstamp view'\n               (EQ: e = SCOH_event (ThreadEvent t i (Astore x v)) tstamp view')\n               (EQ': view' = upd (snd MV t) x (S tstamp))\n               (LTV: snd MV t x < S tstamp)\n               (MEM: fst MV' = fst MV ∪₁ eq (Msg x v (S tstamp) view'))\n               (FRESH: fresh_tstamp (fst MV) x (S tstamp))\n\t       (VIEW: snd MV' = upd (snd MV) t view')\n| SCOHstep_rmw t i x vr vw tstamp view view'\n             (EQ: e = SCOH_event (ThreadEvent t i (Armw x vr vw)) tstamp view')\n\t     (MSG: fst MV (Msg x vr tstamp view))\n             (LEV: snd MV t x <= tstamp)\n             (EQ' : view' = upd (snd MV t) x (S tstamp))\n             (MEM: fst MV' = fst MV ∪₁ eq (Msg x vw (S tstamp) view'))\n             (FRESH: fresh_tstamp (fst MV) x (S tstamp))\n             (VIEW: snd MV' = upd (snd MV) t view')\n| SCOHstep_internal t x v tstamp view view'\n                  (EQ: e = SCOH_internal t x tstamp)\n\t\t  (MSG: fst MV (Msg x v tstamp view))\n                  (LEV: snd MV t x < tstamp)\n                  (MEM: fst MV' = fst MV)\n                  (EQ': view' = upd (snd MV t) x tstamp)\n\t\t  (VIEW: snd MV' = upd (snd MV) t view').\n\nDefinition scoh_lts :=\n  {| LTS_init := eq Sinit ;\n     LTS_step := SCOH_step ;\n     LTS_final := ∅ |}.\n\nDefinition run_fair (states : nat -> State) t : Prop :=\n  match t with\n  | trace_fin _ => True\n  | trace_inf fl =>\n    exists (threads : Tid -> Prop),\n    set_finite threads /\\\n    trace_elems t ⊆₁ tid_of ↓₁ threads /\\\n    forall i (tid : Tid) (TID: threads tid) x tstamp,\n    exists j,\n      i <= j /\\\n      (fl j = SCOH_internal tid x tstamp \\/\n       forall st'\n              (STEP: SCOH_step (states j) (SCOH_internal tid x tstamp) st'),\n         False)\n  end.\n\nDefinition SCOH_is_w lab :=\n  match lab with\n  | SCOH_event (ThreadEvent _ _ (Astore _ _)) ts view => True\n  | SCOH_event (ThreadEvent _ _ (Armw _ _ _)) ts view => True\n  | _ => False\n  end.\n\nDefinition SCOH_wmsg lab :=\n  match lab with\n  | SCOH_event (ThreadEvent t i (Astore x v)) ts view => Msg x v (S ts) view\n  | SCOH_event (ThreadEvent t i (Armw x vr vw)) ts view => Msg x vw (S ts) view\n  | _ => Msg 0 0 0 (fun _ => 0)\n  end.\n\nDefinition view_of x :=\n  match x with\n  | SCOH_event _ _ view => view\n  | SCOH_internal _ _ _ => fun _ => 0\n  end.\n\nInductive match_ev (e : Event) (l : SCOH_label) : Prop :=\n| ME_case t i lab tstamp view (EQe : e = ThreadEvent t i lab)\n          (EQl : l = SCOH_event e tstamp view).\n\nDefinition view_of' t x :=\n  match excluded_middle_informative\n          (exists xl, match_ev x xl /\\ trace_elems t xl) with\n  | left IN =>\n    view_of (proj1_sig\n               (IndefiniteDescription.constructive_indefinite_description\n                  _ IN))\n  | right _ => fun _ => 0\n  end.\n\nLemma view_of_init t x :\n  view_of' t (InitEvent x) = fun _ => 0.\nProof using.\n  unfold view_of'; desf.\n  exfalso; desf; destruct e; desf.\nQed.\n\nLemma SCOH_step_view_mono mem lab mem'\n      (STEP : SCOH_step mem lab mem') t :\n  view_le (snd mem t) (snd mem' t).\nProof using.\n  destruct STEP; ins; desf; ins.\n  all: rewrite VIEW; clear VIEW; unfold upd; desf.\n  all: try apply view_le_join_l.\n  all: red; unfold upd; ins; desf; lia.\nQed.\n\nLemma SCOH_step_view_ext mem lab mem'\n      (STEP : SCOH_step mem lab mem')\n      (EXT : is_external lab) :\n  view_le (snd mem (tid_of lab))\n          (view_of lab) /\\\n  view_of lab = snd mem' (tid_of lab).\nProof using.\n  destruct STEP; ins; desf; ins.\n  all: rewrite VIEW, upds; split; ins.\n  all: try apply view_le_join_l.\n  all: red; unfold upd; ins; desf; lia.\nQed.\n\nLemma SCOH_view_mono mem lab\n      (STEP : forall i, SCOH_step (mem i) (lab i) (mem (S i)))\n      i j (LE : i <= j) mytid x :\n  snd (mem i) mytid x <= snd (mem j) mytid x.\nProof using.\n  induction j; rewrite Nat.le_lteq in LE; desf; try lia.\n  rewrite Nat.lt_succ_r in *; intuition.\n  eapply Nat.le_trans, SCOH_step_view_mono; eauto.\nQed.\n\nSection RADeclarative.\n\nVariable G: execution. \n\nDefinition scoh_consistent :=\n  SCpL G  /\\\n  irreflexive ((rf G)⁻¹ ⨾ (co G ⨾ (co G))) /\\\n  << PORF : irreflexive (hb G) >>.\n\nLemma hb_irr (CONS : scoh_consistent) : irreflexive (hb G).\nProof using. apply CONS. Qed.\n\nLemma scoh_rmw_atomicity (WF: Wf G) (CONS : scoh_consistent) :\n  rmw_atomicity G.\nProof using.\n  unfold scoh_consistent, rmw_atomicity in *; desc.\n  rewrite wf_rfE, wf_rfD; ins; unfolder in *; ins; desf.\n  destruct (classic (x = y)) as [|NEQ]; desf.\n  { edestruct (CONS y). apply ct_step.\n    basic_solver. }\n  eapply (wf_co_total WF) in NEQ; ins; desf; ins.    \n  { splits; ins; intro; desf; eauto 10. }\n  { edestruct (CONS x). apply ct_ct.\n    exists y; split; apply t_step; basic_solver. }\n  unfolder. splits; auto.\n  apply wf_rfl in H0; ins.\nQed.\n \nLemma scoh_rf_irr (CONS : scoh_consistent) : irreflexive (rf G).\nProof using. rewrite rf_in_hb. by apply hb_irr. Qed.\n\nLemma rf_w_in_co (WF: Wf G) (CONS : scoh_consistent) :\n  (rf G) ⨾ ⦗is_w⦘ ⊆ (co G).\nProof using.\n  unfolder. intros x y [RF WY].\n  destruct (classic (x = y)) as [|NEQ]; subst.\n  { exfalso. eapply scoh_rf_irr; eauto. }\n  apply (wf_rfE WF) in RF. unfolder in RF. desf.\n  apply (wf_rfD WF) in RF0. unfolder in RF0. desf.\n  edestruct (wf_co_total WF) with (a:=x) (b:=y) as [|HH]; eauto.\n  1,2: unfolder; splits; eauto.\n  { symmetry. by apply (wf_rfl WF). }\n  exfalso.\n  cdes CONS. eapply CONS0.\n  apply ct_ct. eexists. split; apply ct_step.\n  all: basic_solver.\nQed.\n\n(* TODO: move to more appropriate place or replace with co_ninit. *)\nLemma co_init_r (WF: Wf G)\n      x y (CO : co G x y) (INITY : is_init y) :\n  False.\nProof.\n  apply co_ninit in CO; auto. unfolder in CO. desf.\nQed.\n\nEnd RADeclarative.\n", "meta": {"author": "weakmemory", "repo": "fairness", "sha": "537609d3c23490a82f11f13125d1f0ce4ce3fef8", "save_path": "github-repos/coq/weakmemory-fairness", "path": "github-repos/coq/weakmemory-fairness/fairness-537609d3c23490a82f11f13125d1f0ce4ce3fef8/src/equivalence/strong_coh/SCOHop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.22832587056525125}}
{"text": "From compcert Require Export Clightdefs.\nRequire Export VST.veric.base.\nRequire Export VST.veric.SeparationLogic.\nRequire Export VST.msl.Extensionality.\nRequire Export compcert.lib.Coqlib.\nRequire Export VST.msl.Coqlib2 VST.veric.coqlib4 VST.floyd.coqlib3.\nRequire Export VST.floyd.functional_base.\n\nLemma is_int_dec i s v: {is_int i s v} + {~ is_int i s v}.\nProof. destruct v; simpl; try solve [right; intros N; trivial].\ndestruct i.\n+ destruct s.\n    * destruct (zle Byte.min_signed (Int.signed i0)); [| right; omega].\n      destruct (zle (Int.signed i0) Byte.max_signed). left; omega. right; omega.\n    * destruct (zle (Int.unsigned i0) Byte.max_unsigned). left; omega. right; omega.\n+ destruct s.\n    * destruct (zle (-32768) (Int.signed i0)); [| right; omega].\n      destruct (zle (Int.signed i0) 32767). left; omega. right; omega.\n    * destruct (zle (Int.unsigned i0) 65535). left; omega. right; omega.\n+ left; trivial.\n+ destruct (Int.eq_dec i0 Int.zero); subst. left; left; trivial.\n    destruct (Int.eq_dec i0 Int.one); subst. left; right; trivial.\n    right. intros N; destruct N; contradiction.\nDefined.\n\nLemma tc_val_dec t v: {tc_val t v} + {~ tc_val t v}.\nProof. destruct t; simpl.\n+ right; intros N; trivial.\n+ apply is_int_dec.\n+ apply is_long_dec.\n+ destruct f. apply is_single_dec. apply is_float_dec.\n+ destruct ((eqb_type t Tvoid &&\n    eqb_attr a\n      {| attr_volatile := false; attr_alignas := Some log2_sizeof_pointer |})%bool).\n  apply is_pointer_or_integer_dec.\n  apply is_pointer_or_null_dec.\n+ apply is_pointer_or_null_dec.\n+ apply is_pointer_or_null_dec.\n+ apply isptr_dec.\n+ apply isptr_dec.\nDefined.\n\nLemma sem_add_pi_ptr:\n   forall {cs: compspecs}  t p i si,\n    isptr p ->\n    match si with\n    | Signed => Int.min_signed <= i <= Int.max_signed\n    | Unsigned => 0 <= i <= Int.max_unsigned\n    end ->\n    Cop.sem_add_ptr_int cenv_cs t si p (Vint (Int.repr i)) = Some (offset_val (sizeof t * i) p).\nProof.\n  intros. destruct p; try contradiction.\n  unfold offset_val, Cop.sem_add_ptr_int.\n  unfold Cop.ptrofs_of_int, Ptrofs.of_ints, Ptrofs.of_intu, Ptrofs.of_int.\n  f_equal. f_equal. f_equal.\n  destruct si; rewrite <- ptrofs_mul_repr;  f_equal.\n  rewrite Int.signed_repr by omega; auto.\n  rewrite Int.unsigned_repr by omega; auto.\nQed.\nHint Rewrite @sem_add_pi_ptr using (solve [auto with norm]) : norm.\n\nLemma sem_cast_i2i_correct_range: forall sz s v,\n  is_int sz s v -> sem_cast_i2i sz s v = Some v.\nProof.\n  intros.\n  destruct sz, s, v; try solve [inversion H]; simpl;\n  f_equal; f_equal; try apply sign_ext_inrange; try apply zero_ext_inrange; eauto.\n  + simpl in H; destruct H; subst; reflexivity.\n  + simpl in H; destruct H; subst; reflexivity.\nQed.\nHint Rewrite sem_cast_i2i_correct_range using (solve [auto with norm]) : norm.\n\nLemma sem_cast_neutral_ptr:\n  forall p, isptr p -> sem_cast_pointer p = Some p.\nProof. intros. destruct p; try contradiction; reflexivity. Qed.\nHint Rewrite sem_cast_neutral_ptr using (solve [auto with norm]): norm.\n\nLemma sem_cast_neutral_Vint: forall v,\n  sem_cast_pointer (Vint v) = Some (Vint v).\nProof.\n  intros. reflexivity.\nQed.\nHint Rewrite sem_cast_neutral_Vint : norm.\n\nDefinition isVint v := match v with Vint _ => True | _ => False end.\n\nLemma is_int_is_Vint: forall i s v, is_int i s v -> isVint v.\nProof. intros.\n destruct i,s,v; simpl; intros; auto.\nQed.\n\nLemma is_int_I32_Vint: forall s v, is_int I32 s (Vint v).\nProof.\nintros.\nhnf. auto.\nQed.\nHint Resolve is_int_I32_Vint.\n\nLemma sem_cast_neutral_int: forall v,\n  isVint v ->\n  sem_cast_pointer v = Some v.\nProof.\ndestruct v; simpl; intros; try contradiction; auto.\nQed.\n\nHint Rewrite sem_cast_neutral_int using\n  (auto;\n   match goal with H: is_int ?i ?s ?v |- isVint ?v => apply (is_int_is_Vint i s v H) end) : norm.\n\nLemma sizeof_tuchar: forall {cs: compspecs}, sizeof tuchar = 1%Z.\nProof. reflexivity. Qed.\nHint Rewrite @sizeof_tuchar: norm.\n\nHint Rewrite Z.mul_1_l Z.mul_1_r Z.add_0_l Z.add_0_r Z.sub_0_r : norm.\n\nHint Rewrite eval_id_same : norm.\nHint Rewrite eval_id_other using solve [clear; intro Hx; inversion Hx] : norm.\nHint Rewrite Int.sub_idem Int.sub_zero_l  Int.add_neg_zero : norm.\nHint Rewrite Ptrofs.sub_idem Ptrofs.sub_zero_l  Ptrofs.add_neg_zero : norm.\n\nLemma eval_expr_Etempvar:\n  forall {cs: compspecs}  i t, eval_expr (Etempvar i t) = eval_id i.\nProof. reflexivity.\nQed.\nHint Rewrite @eval_expr_Etempvar : eval.\n\nLemma eval_expr_binop: forall {cs: compspecs}  op a1 a2 t, eval_expr (Ebinop op a1 a2 t) =\n          `(eval_binop op (typeof a1) (typeof a2)) (eval_expr a1) (eval_expr a2).\nProof. reflexivity. Qed.\nHint Rewrite @eval_expr_binop : eval.\n\nLemma eval_expr_unop: forall {cs: compspecs} op a1 t, eval_expr (Eunop op a1 t) =\n          lift1 (eval_unop op (typeof a1)) (eval_expr a1).\nProof. reflexivity. Qed.\nHint Rewrite @eval_expr_unop : eval.\n\nHint Resolve  eval_expr_Etempvar.\n\nLemma eval_expr_Etempvar' : forall {cs: compspecs}  i t, eval_id i = eval_expr (Etempvar i t).\nProof. intros. symmetry; auto.\nQed.\nHint Resolve  @eval_expr_Etempvar'.\n\nHint Rewrite Int.add_zero  Int.add_zero_l Int.sub_zero_l : norm.\nHint Rewrite Ptrofs.add_zero  Ptrofs.add_zero_l Ptrofs.sub_zero_l : norm.\n\nLemma eval_var_env_set:\n  forall i t j v (rho: environ), eval_var i t (env_set rho j v) = eval_var i t rho.\nProof. reflexivity. Qed.\nHint Rewrite eval_var_env_set : norm.\n\nLemma eval_expropt_Some: forall {cs: compspecs}  e, eval_expropt (Some e) = `Some (eval_expr e).\nProof. reflexivity. Qed.\nLemma eval_expropt_None: forall  {cs: compspecs} , eval_expropt None = `None.\nProof. reflexivity. Qed.\nHint Rewrite @eval_expropt_Some @eval_expropt_None : eval.\n\nLemma deref_noload_tarray:\n  forall ty n, deref_noload (tarray ty n) = (fun v => v).\nProof.\n intros. extensionality v. reflexivity.\nQed.\nHint Rewrite deref_noload_tarray : norm.\n\nLemma deref_noload_Tarray:\n  forall ty n a, deref_noload (Tarray ty n a) = (fun v => v).\nProof.\n intros. extensionality v. reflexivity.\nQed.\nHint Rewrite deref_noload_Tarray : norm.\n\nLemma flip_lifted_eq:\n  forall (v1: environ -> val) (v2: val),\n    `eq v1 `(v2) = `(eq v2) v1.\nProof.\nintros. unfold_lift. extensionality rho. apply prop_ext; split; intro; auto.\nQed.\nHint Rewrite flip_lifted_eq : norm.\n\nLemma isptr_is_pointer_or_null:\n  forall v, isptr v -> is_pointer_or_null v.\nProof. intros. destruct v; inv H; simpl; auto.\nQed.\nHint Resolve isptr_is_pointer_or_null.\n\nDefinition add_ptr_int  {cs: compspecs}  (ty: type) (v: val) (i: Z) : val :=\n           eval_binop Cop.Oadd (tptr ty) tint v (Vint (Int.repr i)).\n\nLemma add_ptr_int_offset:\n  forall  {cs: compspecs}  t v n,\n  repable_signed (sizeof t) ->\n  repable_signed n ->\n  add_ptr_int t v n = offset_val (sizeof t * n) v.\nAbort. (* broken in CompCert 2.7 *)\n\nLemma typed_false_cmp:\n  forall op i j ,\n   typed_false tint (force_val (sem_cmp op tint tint (Vint i) (Vint j))) ->\n   Int.cmp (negate_comparison op) i j = true.\nProof.\nintros.\nunfold sem_cmp in H.\nunfold Cop.classify_cmp in H. simpl in H.\nrewrite Int.negate_cmp.\nunfold both_int, force_val, typed_false, strict_bool_val, sem_cast, classify_cast, tint in H.\ndestruct Archi.ptr64 eqn:Hp; simpl in H.\ndestruct (Int.cmp op i j); inv H; auto.\ndestruct (Int.cmp op i j); inv H; auto.\nQed.\n\nLemma typed_true_cmp:\n  forall op i j,\n   typed_true tint (force_val (sem_cmp op tint tint (Vint i) (Vint j))) ->\n   Int.cmp op i j = true.\nProof.\nintros.\nunfold sem_cmp in H.\nunfold Cop.classify_cmp in H. simpl in H.\nunfold both_int, force_val, typed_false, strict_bool_val, sem_cast, classify_cast, tint in H.\ndestruct Archi.ptr64 eqn:Hp; simpl in H.\ndestruct (Int.cmp op i j); inv H; auto.\ndestruct (Int.cmp op i j); inv H; auto.\nQed.\n\nDefinition Zcmp (op: comparison) : Z -> Z -> Prop :=\n match op with\n | Ceq => eq\n | Cne => (fun i j => i<>j)\n | Clt => Z.lt\n | Cle => Z.le\n | Cgt => Z.gt\n | Cge => Z.ge\n end.\n\nLemma int_cmp_repr:\n forall op i j, repable_signed i -> repable_signed j ->\n   Int.cmp op (Int.repr i) (Int.repr j) = true ->\n   Zcmp op i j.\nProof.\nintros.\nunfold Int.cmp, Int.eq, Int.lt in H1.\nreplace (if zeq (Int.unsigned (Int.repr i)) (Int.unsigned (Int.repr j))\n             then true else false)\n with (if zeq i j then true else false) in H1.\n2:{\ndestruct (zeq i j); destruct (zeq (Int.unsigned (Int.repr i)) (Int.unsigned (Int.repr j)));\n auto.\nsubst. contradiction n; auto.\nclear - H H0 e n.\napply Int.signed_repr in H. rewrite Int.signed_repr_eq in H.\napply Int.signed_repr in H0; rewrite Int.signed_repr_eq in H0.\ncontradiction n; clear n.\nrepeat rewrite Int.unsigned_repr_eq in e.\n match type of H with\n           | context [if ?a then _ else _] => destruct a\n           end;\n match type of H0 with\n           | context [if ?a then _ else _] => destruct a\n           end; omega.\n}\nunfold Zcmp.\nrewrite (Int.signed_repr _ H) in H1; rewrite (Int.signed_repr _ H0) in H1.\nrepeat match type of H1 with\n           | context [if ?a then _ else _] => destruct a\n           end; try omegaContradiction;\n destruct op; auto; simpl in *; try discriminate; omega.\nQed.\n\nLemma typed_false_cmp_repr:\n  forall op i j,\n   repable_signed i -> repable_signed j ->\n   typed_false tint (force_val (sem_cmp op tint tint\n                              (Vint (Int.repr i))\n                              (Vint (Int.repr j)) )) ->\n   Zcmp (negate_comparison op) i j.\nProof.\n intros.\n apply typed_false_cmp in H1.\n apply int_cmp_repr; auto.\nQed.\n\nLemma typed_true_cmp_repr:\n  forall op i j,\n   repable_signed i -> repable_signed j ->\n   typed_true tint (force_val (sem_cmp op tint tint\n                              (Vint (Int.repr i))\n                              (Vint (Int.repr j)) )) ->\n   Zcmp op i j.\nProof.\n intros.\n apply typed_true_cmp in H1.\n apply int_cmp_repr; auto.\nQed.\n\nLtac intcompare H :=\n (apply typed_false_cmp_repr in H || apply typed_true_cmp_repr in H);\n   [ simpl in H | auto; unfold repable_signed, Int.min_signed, Int.max_signed in *; omega .. ].\n\n\nLemma isptr_deref_noload:\n forall t p, access_mode t = By_reference -> isptr (deref_noload t p) = isptr p.\nProof.\nintros.\nunfold deref_noload. rewrite H. reflexivity.\nQed.\nHint Rewrite isptr_deref_noload using reflexivity : norm.\n\nDefinition headptr (v: val): Prop :=\n  exists b,  v = Vptr b Ptrofs.zero.\n\nLemma headptr_isptr: forall v,\n  headptr v -> isptr v.\nProof.\n  intros.\n  destruct H as [b ?].\n  subst.\n  hnf; auto.\nQed.\nHint Resolve headptr_isptr.\n\nLemma headptr_offset_zero: forall v,\n  headptr (offset_val 0 v) <->\n  headptr v.\nProof.\n  split; intros.\n  + destruct H as [b ?]; subst.\n    destruct v; try solve [inv H].\n    simpl in H.\n    remember (Ptrofs.add i (Ptrofs.repr 0)).\n    inversion H; subst.\n    rewrite Ptrofs.add_zero in H2; subst.\n    hnf; eauto.\n  + destruct H as [b ?]; subst.\n    exists b.\n    reflexivity.\nQed.\n\n(* Equality proofs for all constants from the Compcert Int, Int64, Ptrofs modules: *)\n\nLemma typed_false_ptr:\n  forall {t a v},  typed_false (Tpointer t a) v -> v=nullval.\nProof.\nunfold typed_false, strict_bool_val, nullval; simpl; intros.\ndestruct Archi.ptr64 eqn:Hp;\ndestruct v; try discriminate; f_equal.\nfirst [pose proof (Int64.eq_spec i Int64.zero); \n          destruct (Int64.eq i Int64.zero)\n       | pose proof (Int.eq_spec i Int.zero); \n         destruct (Int.eq i Int.zero)]; \n      subst; auto; discriminate.\nQed.\n\nLemma typed_true_ptr:\n  forall {t a v},  typed_true (Tpointer t a) v -> isptr v.\nProof.\nunfold typed_true, strict_bool_val; simpl; intros.\ndestruct v; try discriminate; simpl; auto;\ndestruct Archi.ptr64; try discriminate;\n revert H; simple_if_tac; intros; discriminate.\nQed.\n\nLemma int_cmp_repr':\n forall op i j, repable_signed i -> repable_signed j ->\n   Int.cmp op (Int.repr i) (Int.repr j) = false ->\n   Zcmp (negate_comparison op) i j.\nProof.\nintros.\napply int_cmp_repr; auto.\nrewrite Int.negate_cmp.\nrewrite H1; reflexivity.\nQed.\n\nLemma typed_false_of_bool:\n forall x, typed_false tint (Val.of_bool x) -> (x=false).\nProof.\nunfold typed_false; simpl.\nunfold strict_bool_val, Val.of_bool; simpl.\ndestruct x; simpl; intros; [inversion H | auto].\nQed.\n\nLemma typed_true_of_bool:\n forall x, typed_true tint (Val.of_bool x) -> (x=true).\nProof.\nunfold typed_true; simpl.\nunfold strict_bool_val, Val.of_bool; simpl.\ndestruct x; simpl; intros; [auto | inversion H].\nQed.\n\nLemma typed_false_tint:\n Archi.ptr64=false -> \n forall v, typed_false tint v -> v=nullval.\nProof.\nintros.\n hnf in H0. destruct v; inv H0.\n destruct (Int.eq i Int.zero) eqn:?; inv H2.\n apply int_eq_e in Heqb. subst.\n inv H; reflexivity.\nQed.\n\nLemma typed_false_tlong:\n Archi.ptr64=true -> \n forall v, typed_false tlong v -> v=nullval.\nProof.\nintros. unfold nullval. rewrite H.\n hnf in H0. destruct v; inv H0.\npose proof (Int64.eq_spec i Int64.zero).\n destruct (Int64.eq i Int64.zero); inv H2.\nreflexivity.\nQed.\n\nLemma typed_true_e:\n forall t v, typed_true t v -> v<>nullval.\nProof.\nintros.\n intro Hx. subst.\n hnf in H. unfold nullval, strict_bool_val in H.\n destruct Archi.ptr64, t; discriminate.\nQed.\n\nLemma typed_false_tint_Vint:\n  forall v, typed_false tint (Vint v) -> v = Int.zero.\nProof.\nintros.\nunfold typed_false, strict_bool_val in H. simpl in H.\npose proof (Int.eq_spec v Int.zero).\ndestruct (Int.eq v Int.zero); auto. inv H.\nQed.\n\nLemma typed_true_tint_Vint:\n  forall v, typed_true tint (Vint v) -> v <> Int.zero.\nProof.\nintros.\nunfold typed_true, strict_bool_val in H. simpl in H.\npose proof (Int.eq_spec v Int.zero).\ndestruct (Int.eq v Int.zero); auto. inv H.\nQed.\n\nLemma typed_true_tlong_Vlong:\n  forall v, typed_true tlong (Vlong v) -> v <> Int64.zero.\nProof.\nintros.\nunfold typed_true, strict_bool_val in H. simpl in H.\npose proof (Int64.eq_spec v Int64.zero).\ndestruct (Int64.eq v Int64.zero); auto. inv H.\nQed.\n\nLtac intro_redundant_prop :=\n  (* do it in this complicated way because the proof will come out smaller *)\nmatch goal with |- ?P -> _ =>\n  ((assert P by immediate; fail 1) || fail 1) || intros _\nend.\n\nLtac fancy_intro aggressive :=\n match goal with\n | |- ?P -> _ => match type of P with Prop => idtac end\n | |- ~ _ => idtac\n end;\n let H := fresh in\n intro H;\n try simple apply ptr_eq_e in H;\n try simple apply Vint_inj in H;\n try match type of H with\n | tc_val _ _ => unfold tc_val in H; try change (eqb_type _ _) with false in H; cbv iota in H\n end;\n match type of H with\n | ?P => clear H; \n              match goal with H': P |- _ => idtac end (* work around bug number 6998 in Coq *)\n             + (((assert (H:P) by (clear; immediate); fail 1) || fail 1) || idtac)\n                (* do it in this complicated way because the proof will come out smaller *)\n | ?x = ?y => constr_eq aggressive true;\n                     first [subst x | subst y\n                             | is_var x; rewrite H\n                             | is_var y; rewrite <- H\n                             | idtac]\n | headptr (_ ?x) => let Hx1 := fresh \"HP\" x in\n                     let Hx2 := fresh \"P\" x in\n                       rename H into Hx1;\n                       pose proof headptr_isptr _ Hx1 as Hx2\n | headptr ?x => let Hx1 := fresh \"HP\" x in\n                 let Hx2 := fresh \"P\" x in\n                   rename H into Hx1;\n                   pose proof headptr_isptr _ Hx1 as Hx2\n | isptr ?x => let Hx := fresh \"P\" x in rename H into Hx\n | is_pointer_or_null ?x => let Hx := fresh \"PN\" x in rename H into Hx\n | typed_false _ _ =>\n        first [simple apply typed_false_of_bool in H\n               | apply typed_false_tint_Vint in H\n               | apply (typed_false_tint (eq_refl _)) in H\n               | apply (typed_false_tlong (eq_refl _)) in H\n               | apply typed_false_ptr in H\n               | idtac ]\n | typed_true _ _ =>\n        first [simple apply typed_true_of_bool in H\n               | apply typed_true_tint_Vint in H\n               | apply typed_true_tlong_Vlong in H\n(*  This one is not portable 32/64 bits \n                | apply (typed_true_e tint) in H\n*)\n               | apply typed_true_ptr in H\n               | idtac ]\n (* | locald_denote _ _ => hnf in H *)\n | _ => try solve [discriminate H]\n end.\n\nLtac fancy_intros aggressive :=\n repeat match goal with\n  | |- (_ <= _ < _) -> _ => fancy_intro aggressive\n  | |- (_ < _ <= _) -> _ => fancy_intro aggressive\n  | |- (_ <= _ <= _) -> _ => fancy_intro aggressive\n  | |- (_ < _ < _) -> _ => fancy_intro aggressive\n  | |- (?A /\\ ?B) -> ?C => apply (@and_ind A B C) (* For some reason \"apply and_ind\" doesn't work the same *)\n  | |- _ -> _ => fancy_intro aggressive\n  end.\n\nLtac fold_types :=\n fold noattr tuint tint tschar tuchar;\n repeat match goal with\n | |- context [Tpointer ?t noattr] =>\n      change (Tpointer t noattr) with (tptr t)\n | |- context [Tarray ?t ?n noattr] =>\n      change (Tarray t n noattr) with (tarray t n)\n end.\n\nLtac fold_types1 :=\n  match goal with |- _ -> ?A =>\n  let a := fresh \"H\" in set (a:=A); fold_types; subst a\n  end.\n\nLemma is_int_Vbyte: forall c, is_int I8 Signed (Vbyte c).\nProof.\nintros. simpl. normalize. rewrite Int.signed_repr by rep_omega. rep_omega.\nQed.\nHint Resolve is_int_Vbyte.\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/floyd/val_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947155710233, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.22832585673974534}}
{"text": "(************************************************************************)\n(* Copyright (c) 2022, Gergei Bana, Rohit Chadha, Ajay Kumar Eeralla,   *)\n(* Qianli Zhang                                                         *)\n(*                                                                      *)\n(* This work is licensed under the MIT license. The license is          *)\n(* described in the file \"LICENSE\" available at the root of the source  *)\n(* or at https://opensource.org/licenses/MIT                            *)\n(************************************************************************)\n\nRequire Import Coq.micromega.Lia.\nRequire Export contexts.\n(* Require Export prop11. *)\nImport ListNotations.\n\n\n(********************************************************************)\n\n(* Proposition 15.8 *)\nProposition DoNegElim: forall b, bppt b -> (! ! b) = b.\n  intros.\n  rewrite (@If_morph (fun x => If x Then FAlse Else TRue)).\n  rewrite If_true.\n  rewrite If_false.\n  rewrite <- If_tf.\n  reflexivity.\n  all : ProveboolandContext.\nQed.\n\n\n(* Prop21 is similar to the Blindness property of a blind-signature scheme,  \n   but states that even if the attacker has access to the acceptance checks, the blind-signature game will still keep indistinguishable. *)\n\nProposition prop21: forall n0 n1 z, forall m0 m1 t :ppt, forall t0 t1,\n      n0 <> n1 ->\n  Fresh (nonce n0) (m0 :: m1 :: t :: z) -> FreshTermc (nonce n0) t0 -> FreshTermc (nonce n0) t1 ->\n  Fresh (nonce n1) (m0 :: m1 :: t :: z) -> FreshTermc (nonce n1) t0 -> FreshTermc (nonce n1) t1 ->\n  let bn0 := Brand (nonce n0) in\n  let bn1 := Brand (nonce n1) in\n  let ti0 := t0 [b m0 t bn0; b m1 t bn1] in\n  let ti1 := t1 [b m1 t bn0; b m0 t bn1] in\n  z ++ [b m0 t bn0; b m1 t bn1; acc m0 t bn0 ti0 & acc m1 t bn1 ti0 ; If acc m0 t bn0 ti0 & acc m1 t bn1 ti0 Then ＜ ub m0 t bn0 ti0, ub m1 t bn1 ti0 ＞ Else (＜ ⫠, ⫠ ＞)]\n  ~\n  z ++ [b m1 t bn0; b m0 t bn1; acc m1 t bn0 ti1 & acc m0 t bn1 ti1 ; If acc m1 t bn0 ti1 & acc m0 t bn1 ti1 Then ＜ ub m0 t bn1 ti1, ub m1 t bn0 ti1 ＞ Else (＜ ⫠, ⫠ ＞)].\nProof.\n  intros n0 n1 z m0 m1 t t0 t1 noteq. intros.\n  pose (Blindness z m0 m1 t (nonce n0) (nonce n1) t0 t1 H H0 H1 H2 H3 H4) as c. simpl in c.\n  apply (@cind_funcapp (fun lc =>  (firstn (length z) lc) ++ [(Nth (length z + 0) lc); (Nth (length z + 1) lc); (Nth (length z + 2) lc); ((π1 (Nth (length z + 2) lc)) ≟ ⫠) ])) in c;\n    unfold Nth in c;\n    repeat rewrite app_nth2_plus in c;\n    repeat rewrite firstn_app_exact in c;\n    unfold nth in c; simpl in c; fold ti0 ti1 in c. \n  rewrite (@If_morph (fun x => (π1 x) ≟ ⫠)) in c.\n  rewrite (@If_morph (fun x => (π1 x) ≟ ⫠)) in c.\n  repeat rewrite proj1pair in c.\n  rewrite ceqeq in c. (*  *)\n  fold bn0 bn1 in c. fold ti0 ti1 in c.\n  rewrite (AndComm (acc m1 t bn0 ti1) (acc m0 t bn1 ti1)) in c.\n  rewrite (@AndGuard2 (acc m0 t bn0 ti0) (acc m1 t bn1 ti0) (ub m0 t bn0 ti0 ≟ ⫠) FAlse TRue) in c.\n  rewrite (@AndGuard2 (acc m0 t bn1 ti1) (acc m1 t bn0 ti1) (ub m0 t bn1 ti1 ≟ ⫠) FAlse TRue) in c.\n  rewrite (AndComm (acc m0 t bn1 ti1) (acc m1 t bn0 ti1)) in c.\n  unfold bn0 , bn1 in c.\n  rewrite (UbNotUndefined m0 t (nonce n0) ti0) in c.\n  rewrite (UbNotUndefined m0 t (nonce n1) ti1) in c.\n  fold bn0 bn1 in c.\n  apply (@cind_funcapp (fun lc =>  (firstn (length z) lc) ++ [(Nth (length z + 0) lc); (Nth (length z + 1) lc); ! (Nth (length z + 3) lc); (Nth (length z + 2) lc) ])) in c;\n    unfold Nth in c; repeat rewrite app_nth2_plus in c; repeat rewrite firstn_app_exact in c; unfold nth in c; simpl in c.\n  rewrite DoNegElim in c. rewrite DoNegElim in c.\n  auto.\n  all : Provebool.\n  all : ProveboolandContext.\n  { apply frConc.\n  assert (t = Nth 2 (m0 :: m1 :: t :: z)).\n  auto.\n  rewrite H5.\n  ProveFresh.\n  assert (m0 = Nth 0 (m0 :: m1 :: t :: z)).\n  auto. rewrite H5.\n  ProveFresh. }\n  2: { apply frConc.\n  assert (t = Nth 2 (m0 :: m1 :: t :: z)).\n  auto.\n  rewrite H5.\n  ProveFresh.\n  assert (m0 = Nth 0 (m0 :: m1 :: t :: z)).\n  auto. rewrite H5.\n  ProveFresh. }\n  unfold ti1. apply FreshTermcfromNonceList in H4.\n  destruct H4. destruct H4. destruct H4. destruct H5.\n  destruct H6. rewrite H7.\n  apply  UbNUDAttContListTerm. assumption.\n  apply  UbNUDContextApp. apply UbNUDFresh. assumption.\n  apply  UbNUDContextConc.\n  apply UbNUDFreshTerm.\n  inversion H2. inversion H12. inversion H17. unfold bn0.\n  ProveFresh. unfold bn1. apply UbNUDContextConc. apply UbNUDBlindSign.\n  inversion H2; assumption. inversion H2. inversion H12. inversion H17; assumption.\n  apply UbNUDFresh. ProveFresh.\n   unfold ti0. apply FreshTermcfromNonceList in H0.\n  destruct H0. destruct H0. destruct H0. destruct H5.\n  destruct H6. rewrite H7.\n  apply  UbNUDAttContListTerm. assumption.\n  apply  UbNUDContextApp. apply UbNUDFresh. assumption.\n  apply  UbNUDContextConc.\n  apply UbNUDBlindSign.\n  inversion H; assumption. inversion H. inversion H12. inversion H17; assumption.\n  apply UbNUDFresh. unfold bn1.\n  inversion H. inversion H12. inversion H17.\n  ProveFresh.\nQed.\n", "meta": {"author": "kmilesz", "repo": "CCSA_FOO_Verification", "sha": "bb33875f975bcb266acacec1980b13c9631c273e", "save_path": "github-repos/coq/kmilesz-CCSA_FOO_Verification", "path": "github-repos/coq/kmilesz-CCSA_FOO_Verification/CCSA_FOO_Verification-bb33875f975bcb266acacec1980b13c9631c273e/FOO/prop21.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22812457749095047}}
{"text": "(* -------------------------------------------------------------------------- *\n *                     Vellvm - the Verified LLVM project                     *\n *                                                                            *\n *     Copyright (c) 2017 Steve Zdancewic <stevez@cis.upenn.edu>              *\n *                                                                            *\n *   This file is distributed under the terms of the GNU General Public       *\n *   License as published by the Free Software Foundation, either version     *\n *   3 of the License, or (at your option) any later version.                 *\n ---------------------------------------------------------------------------- *)\n\nRequire Import ZArith List String Omega.\nRequire Import ExtLib.Structures.Monads.\n\nRequire Import Vellvm.Util.\nRequire Import Vellvm.LLVMAst Vellvm.AstLib Vellvm.CFG Vellvm.CFGProp.\nRequire Import Vellvm.LLVMEvents Vellvm.Denotation.\n\nImport MonadNotation.\nImport ListNotations.\n\nSet Implicit Arguments.\nSet Contextual Implicit.\n\nModule DenotationProp(A:MemoryAddress.ADDRESS)(LLVMIO:LLVM_INTERACTIONS(A)).\n  Module SS := Denotation(A)(LLVMIO).\n  Import SS.\n  Import LLVMIO.DV.\n\n  Section Properties.\n\n  (* CB: THESE GO AWAY *)\n  (*\n  (** *Theorems about the environment *)\n  Section ENVFACTS.\n    \n    (** Lookup on an aliasing add, aka gss *)\n    Lemma lookup_env_hd : forall {X: Type} (id: ENV.key) (dv: X) (e: ENV.t X),\n      lookup_env (add_env id dv e) id = ret dv.\n    Proof.\n      intros.\n      unfold lookup_env. \n      unfold add_env.\n      erewrite ENV.find_1; auto.\n      apply ENV.add_1; auto.\n    Qed.\n\n\n\n    (** Lookup on a non-aliasing add, aka gso *)\n    Lemma lookup_env_tl : forall {X: Type} (id1 id2: ENV.key) (v1: X) (e: ENV.t X),\n        id1 <> id2 -> lookup_env (add_env id1 v1 e) id2 = lookup_env e id2.\n    Proof.\n      intros.\n      unfold lookup_env.\n      unfold add_env.\n\n      destruct (ENV.find id2 e) eqn: FINDID2.\n      - (** Some x **)\n        assert (ID2_MAPSTO: ENV.MapsTo id2 x e).\n        apply ENV.find_2; auto.\n\n        assert (ID2_MAPSTO_ADDED_E': ENV.MapsTo id2 x (ENV.add id1 v1 e)).\n        apply ENV.add_2; auto.\n        erewrite ENV.find_1; eauto.\n\n        \n\n      - assert (ID2_NOT_IN: ~ ENV.In  id2 e).\n        rewrite ENVFacts.not_find_in_iff; auto.\n\n        assert (ID2_NOT_IN_E': ~ ENV.In id2 (ENV.add id1 v1 e)).\n        intros CONTRA.\n        rewrite ENVFacts.add_in_iff in CONTRA.\n        destruct CONTRA; try contradiction.\n\n        rewrite ENVFacts.not_find_in_iff in ID2_NOT_IN_E'.\n        rewrite ID2_NOT_IN_E'.\n        auto.\n    Qed.  \n\n\n    (** Extract information from a lookup-of-add *)\n    Lemma lookup_add_env_inv :\n      forall {X: Type} (id1 id2: ENV.key) (u v: X) (e: ENV.t X)\n             {ID_EQ_DEC: forall id1 id2: ENV.key, {id1 = id2} + {id1 <> id2}}\n             (Hl: lookup_env (add_env id1 v e) id2 = ret u),\n        (id1 = id2 /\\ v = u) \\/ (id1 <> id2 /\\ lookup_env e id2 = ret u).\n    Proof.\n      intros.\n\n      assert (ID12_EQ_DEC: {id1 = id2}+ {id1 <> id2}).\n      auto.\n\n      destruct (ID12_EQ_DEC); subst.\n      - (* id1 = id2 *)\n        left.\n        split; auto.\n\n        rewrite lookup_env_hd in Hl.\n        inversion Hl; auto.\n        \n      - (* id1 <> id2 *)\n        right.\n        split; auto.\n        erewrite <- lookup_env_tl; eauto.\n    Qed.      \n  End ENVFACTS.\n   *)\n  (*\n  Definition pc_satisfies {T} (CFG:mcfg T) (p:pc) (P:cmd T -> Prop) : Prop :=\n    forall cmd, fetch T CFG p = Some cmd -> P cmd.\n*)\n\n  (* Move to AstLib.v ? *)\n  Definition is_Op {T} (i:instr T) : Prop :=\n    match i with\n    | INSTR_Op _ => True\n    | _ => False\n    end.\n\n  Definition is_Eff {T} (i:instr T) : Prop :=\n    match i with \n    | INSTR_Alloca t nb a => True\n    | INSTR_Load v t p a => True\n    | INSTR_Store v val p a => True\n    | _ => False    (* TODO: Think about call *)\n    end.\n  \n  Definition is_Call {T} (i:instr T) : Prop :=\n    match i with\n    | INSTR_Call _ _ => True\n    | _ => False\n    end.\n\n  (*\n  Definition pc_non_call {T} (CFG:mcfg T) (p:pc) : Prop :=\n    pc_satisfies CFG p (fun c => exists i, not (is_Call i) /\\ c = Inst i).\n   *)\n  (* \n  Ltac step_destruct :=\n    repeat (match goal with\n            | [ H : context[do _ <- trywith _ ?E; _] |- _ ] => destruct E; [simpl in H | solve [inversion H]]\n            | [ H : context[do _ <- ?E; _] |- _ ] => destruct E; [solve [inversion H] | simpl in H]\n            | [ H : context[match ?E with _ => _ end] |- _ ] => destruct E; try solve [inversion H]; simpl in H\n            | [ H : Step (?p, _ , _) = Step (?q, _, _) |- Some ?p = Some ?q ] => inversion H; auto\n            | [ H : ~ (is_Call (INSTR_Call _ _)) |- _ ] => simpl in H; contradiction\n            end).\n    *)\n\n  (* Not true for Call *)\n  (*\n  Lemma step_pc_incr_inversion:\n    forall CFG pc1 e1 k1 pc2 e2 k2\n      (Hpc: pc_non_call CFG pc1)\n      (Hstep: step CFG (pc1, e1, k1) = Step (pc2, e2, k2)),\n      incr_pc CFG pc1 = Some pc2.\n  Proof.\n    (*\n    intros CFG pc1 e1 k1 pc2 e2 k2 Hpc Hstep.\n    simpl in Hstep.\n    unfold pc_non_call in Hpc. unfold pc_satisfies in Hpc.\n    destruct (fetch CFG pc1); try solve [inversion Hstep]; simpl in Hstep.\n    specialize Hpc with (cmd0 := c). destruct Hpc as [i [Hi Hc]]; auto.\n    subst.\n    destruct (incr_pc CFG pc1); [simpl in Hstep | solve [inversion Hstep]].\n    step_destruct.*)\n    admit. (* TODO: fix up once the effects interface is stabilized *)\n  Admitted.\n*)\nEnd Properties.\n\n  \n  (*\n  Lemma stepD_Op_inversion :\n    forall CFG fn bid phis term,\n      let slc := slc_pc fn bid phis term in\n      forall cd1 e1 k1 id i pc2 e2 k2 \n        (Hi: is_Op i)\n        (HS1 : stepD CFG (slc ((id,i)::cd1), e1, k1) = Step (pc2, e2, k2)),\n        pc2 = slc cd1.\n  Proof.\n    intros CFG fn0 bid phis term slc cd1 e1 k1 id i pc2 e2 k2 Hi HS1.\n    inversion Hi.\n    subst.\n    simpl in HS1.\n    destruct id; simpl in *.\n    destruct (eval_op e1 None v); inversion HS1; auto.\n    inversion HS1.\n  Qed.\n\n  \n(* DenotationProp.v *)\nLemma stepD_Eff_weakening :\n  forall CFG fn bid phis term,\n    let slc := slc_pc fn bid phis term in\n    forall cd1 e1 k1 id i eff\n      (Hi: is_Eff i)\n      (HS1 : stepD CFG (slc ((id,i)::cd1), e1, k1) = Obs (Eff eff))\n      cd2,\n      stepD CFG (pc_app (slc ((id,i)::cd1)) cd2, e1, k1) = Obs (Eff (fmap (fun st => (pc_app (pc_of st) cd2, env_of st, stack_of st)) eff)).\nProof.\n  intros CFG fn0 bid phis term slc cd1 e1 k1 id i eff Hi HS1 cd2.\n  inversion Hi; subst; simpl in HS1; destruct id; simpl in *; inversion HS1; simpl.\n  - reflexivity.\n  - destruct p as [u ptr]; destruct (eval_op e1 (Some u) ptr).  simpl in HS1. inversion HS1. simpl in HS1.\n    destruct v0; try solve [inversion HS1].\n    simpl in *. inversion HS1.\n    reflexivity.\n  - destruct val as [t val]; destruct p as [u p].\n    destruct (eval_op e1 (Some t) val); try solve [inversion HS1].\n    destruct (eval_op e1 (Some u) p); try solve [inversion HS1].\n    simpl in *.\n    destruct v1; try solve [inversion HS1].\n    inversion HS1.\n    reflexivity.\nQed.    \n\n(* DenotationProp.v *)\nLemma stepD_Eff_Alloca_inversion :\n  forall CFG fn bid phis term,\n    let slc := slc_pc fn bid phis term in\n    forall cd e k id t nb al eff\n      (HS1 : stepD CFG (slc ((id,INSTR_Alloca t nb al)::cd), e, k) = Obs (Eff eff)),\n    exists lid,\n      id = IId lid /\\\n      eff = Alloca t (fun (a:value) => (slc cd, add_env lid a e, k)).\nProof.\n  intros CFG fn0 bid phis term slc cd e k id t nb al eff HS1.\n  simpl in HS1.\n  inversion HS1.\n  destruct id as [lid | lv].\n  exists lid. split; auto. inversion H0.\n  reflexivity.\n  inversion H0.\nQed.\n\n(* DenotationProp.v *)\nLemma stepD_Eff_Load_inversion :\n  forall CFG fn bid phis term,\n    let slc := slc_pc fn bid phis term in\n    forall cd e k id v t p al eff\n      (HS1 : stepD CFG (slc ((id,INSTR_Load v t p al)::cd), e, k) = Obs (Eff eff)),\n    exists lid a, \n      id = IId lid /\\\n      eff = (Load a (fun dv => (slc cd, add_env lid dv e, k))).\nProof.\n  intros CFG fn0 bid phis term slc cd e k id v t p al eff HS1. \n  simpl in HS1.\n  inversion HS1.\n  destruct id as [lid | lv].\n  exists lid.\n  destruct p as [u p].\n  destruct (eval_op e (Some u) p); try solve [inversion H0].\n  destruct v0; try solve [inversion H0].\n  simpl in H0.\n  exists a. split; auto. inversion H0. reflexivity.\n  inversion HS1.\nQed.\n\n(* DenotationProp.v *)\nLemma stepD_Eff_Store_inversion :\n  forall CFG fn bid phis term,\n    let slc := slc_pc fn bid phis term in\n    forall cd e k id v val p al eff\n      (HS1 : stepD CFG (slc ((id,INSTR_Store v val p al)::cd), e, k) = Obs (Eff eff)),\n    exists vid a dv, \n      id = IVoid vid /\\\n      eff = (Store a dv (fun _ => (slc cd, e, k))).\nProof.\n  intros CFG fn0 bid phis term slc cd e k id v val p al eff HS1. \n  simpl in HS1.\n  destruct id as [lid | lvid].\n  - inversion HS1.\n  - exists lvid.\n    destruct val as [u val].\n    destruct p as [w p].\n    destruct (eval_op e (Some u) val); try solve [inversion HS1].\n    destruct (eval_op e (Some w) p); try solve [inversion HS1].\n    simpl in HS1.\n    destruct v1; try solve [inversion HS1].\n    exists a. exists v0. inversion HS1.\n     subst. split; auto.\nQed.\n\n(* DenotationProp.v *)\nLemma stepD_Op_weakening :\n  forall CFG fn bid phis term,\n    let slc := slc_pc fn bid phis term in\n    forall id i cd1 e1 k1 pc2 e2 k2\n    (Hi : is_Op i)\n    (HS : stepD CFG (slc ((id,i)::cd1), e1, k1) = Step (pc2, e2, k2))\n    cd2,\n    stepD CFG (pc_app (slc ((id,i)::cd1)) cd2, e1, k1) = Step (pc_app pc2 cd2, e2, k2).\nProof.\n  intros CFG fn0 bid phis term slc id i cd1 e1 k1 pc2 e2 k2 Hi HS cd2.\n  inversion Hi.\n  subst.\n  simpl in HS.\n  destruct id; simpl in *.\n  destruct (eval_op e1 None v); inversion HS; auto.\n  inversion HS.\nQed.\n*)\n\nEnd DenotationProp.  \n\n", "meta": {"author": "amuppal18", "repo": "test", "sha": "4f6663f47786843480790e1b754ea117de435ff3", "save_path": "github-repos/coq/amuppal18-test", "path": "github-repos/coq/amuppal18-test/test-4f6663f47786843480790e1b754ea117de435ff3/src/coq/DenotationProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22812457195232252}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import TableDataOpsRef2.Spec.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef3.Specs.data_create3.\nRequire Import TableDataOpsRef3.LowSpecs.data_create3.\nRequire Import TableDataOpsRef3.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       data_create2_spec\n       data_create_spec\n    .\n\n  Lemma data_create3_spec_exists:\n    forall habd habd'  labd g_rd data_addr map_addr g_data g_src res\n      (Hspec: data_create3_spec g_rd data_addr map_addr g_data g_src habd = Some (habd', res))\n      (Hrel: relate_RData habd labd),\n    exists labd', data_create3_spec0 g_rd data_addr map_addr g_data g_src labd = Some (labd', res) /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque peq ptr_eq.\n    intros. duplicate Hrel. destruct D. clear hrepl lrepl. destruct g_data, g_src, g_rd.\n    unfold data_create3_spec, data_create3_spec0 in *.\n    unfold Assertion in *. rm_bind Hspec; rm_bind'. simpl in *.\n    unfold Assertion; rm_bind'; grewrite.\n    repeat simpl_hyp Hspec; extract_prop_dec; simpl_query_oracle; rm_bind'; grewrite.\n    - rewrite_oracle_rel rel_oracle C6.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n    - rewrite_oracle_rel rel_oracle C6.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n    - rewrite_oracle_rel rel_oracle C6.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n    - rewrite_oracle_rel rel_oracle C6.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n    - rewrite_oracle_rel rel_oracle C6.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef3/RefProof/data_create3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22812457195232252}}
{"text": "Require Import Lia.\nRequire Import Classical Peano_dec.\nFrom hahn Require Import Hahn.\nRequire Import AuxDef.\nRequire Import AuxRel2. \nRequire Import Events.\nRequire Import Execution.\nImport ListNotations.\nRequire Import FinExecution.\n\nDefinition mem_fair (G: execution) := fsupp (co G) /\\ fsupp (fr G). \n\nSection FairExecution.\n  Variable G: execution.\n  Hypothesis FAIR: mem_fair G.\n  Hypothesis WF: Wf G. \n\n  Lemma co_imm:\n    co G ≡ (immediate (co G))⁺.\n  Proof using WF FAIR. apply fsupp_imm_t; apply WF || apply FAIR. Qed. \n\n  Lemma nS_imm_co_in_sb\n        (S : actid -> Prop) w wnext\n        (WW : is_w (lab G) w)\n        (NSW : ~ S w)\n        (NCOIMM : immediate ((co G) ⨾ ⦗S⦘) w wnext)\n        (FOR_SPLIT : ⦗set_compl S⦘ ⨾ immediate (co G) ⊆ sb G) :\n    sb G w wnext.\n  Proof using WF FAIR.\n    assert (transitive (co G)) as COTRANS.\n    { apply (co_trans WF). }\n\n    assert (S wnext /\\ co G w wnext) as [ISSNEXT CONEXT].\n    { generalize NCOIMM. basic_solver. }\n    apply clos_trans_of_transitiveD; [apply sb_trans|].\n    apply (inclusion_t_t FOR_SPLIT).\n    eapply fsupp_imm_t in CONEXT; cycle 1.\n    { apply FAIR. }\n    { apply (co_irr WF). }\n    { apply (co_trans WF). }\n    apply t_rt_step in CONEXT. destruct CONEXT as [z [IMMS IMM]].\n    apply t_rt_step. exists z; split; [|apply seq_eqv_l; split; [|done]].\n    { apply rtE in IMMS. destruct IMMS as [IMMS|IMMS].\n      { red in IMMS; desf. apply rt_refl. }\n      assert (immediate ((co G) ⨾ ⦗S⦘) z wnext) as IMM'.\n      { red; split; [apply seq_eqv_r; split; auto|].\n        { (* TODO: is the last tactic needed? *)\n          apply clos_trans_immediate1; auto; try by apply ct_step. }\n        ins. eapply NCOIMM; [|by apply R2].\n        apply seq_eqv_r in R1; destruct R1 as [R1 R3].\n        apply seq_eqv_r; split; auto.\n        eapply (co_trans WF); [|by apply R1].\n        apply clos_trans_immediate1; auto. }\n      clear IMM.\n      induction IMMS.\n      { apply rt_step. apply seq_eqv_l; split; auto. }\n      assert (co G y wnext) as YNEXT.\n      { apply clos_trans_immediate1; auto.\n        eapply transitive_ct; [by apply IMMS2|].\n        eapply same_relation_exp.\n        { symmetry. apply fsupp_imm_t; apply FAIR || apply WF. }\n        unfolder in IMM'. basic_solver. }\n      assert (immediate ((co G) ⨾ ⦗S⦘) y wnext) as YNEXTIMM.\n      { red; split; [by apply seq_eqv_r; split|].\n        ins. eapply NCOIMM; [|by apply R2].\n        apply seq_eqv_r in R1; destruct R1 as [R1 R3].\n        apply seq_eqv_r; split; auto.\n        eapply (co_trans WF); [|by apply R1].\n        apply clos_trans_immediate1; auto. }\n      eapply rt_trans.\n      { by apply IHIMMS1. }\n      apply IHIMMS2; auto.\n      { apply (wf_coD WF) in YNEXT.\n        apply seq_eqv_l in YNEXT; desf. }\n      intros NISS. eapply NCOIMM; apply seq_eqv_r; split; auto.\n      2: by apply NISS.\n      2: done.\n      apply clos_trans_immediate1; auto. }\n    intros HH. apply rtE in IMMS; destruct IMMS as [IMSS|IMMS].\n    { red in IMSS; desf. }\n    eapply NCOIMM; apply seq_eqv_r; split; auto.\n    2: by apply HH.\n    all: apply clos_trans_immediate1; auto.\n    all: by apply ct_step.\n  Qed.\n  \n  Lemma fsupp_rf: fsupp (rf G).\n  Proof using WF.\n    apply functional_inv_fsupp. by inversion WF.\n  Qed.\n\n  Lemma fsupp_sb:\n    fsupp (⦗set_compl is_init⦘ ⨾ sb G).\n  Proof using WF.\n    unfold sb, ext_sb; unfolder; ins.\n    destruct y; [exists nil; ins; desf|].\n    exists (map (fun i => ThreadEvent thread i) (List.seq 0 index)).\n    intros e ((NIe & E0) & (SB & E)).\n    destruct e; [done| ]. destruct SB as [-> LT].\n    apply in_map_iff. eexists. split; eauto. by apply in_seq0_iff.\n  Qed.\n\n  Lemma fsupp_sb_loc:\n    fsupp (sb G ∩ same_loc (lab G)).\n  Proof using WF.\n    rewrite <- seq_id_l.\n    rewrite set_full_split with (S := is_init), id_union, seq_union_l.\n    apply fsupp_union.\n    2: { eapply fsupp_mori; [| by apply fsupp_sb; eauto].\n         red. basic_solver. }\n    \n    red. ins.\n    remember (loc (lab G) y) as ly. destruct ly. \n    { exists [InitEvent l].\n      intros x REL%seq_eqv_l. desc. destruct x; [| done].\n      simpl. left. f_equal. apply proj2 in REL0.\n      red in REL0.\n      unfold Events.loc in REL0 at 1. rewrite wf_init_lab in REL0; auto.\n      congruence. }\n    exists []. red. intros x REL%seq_eqv_l. desc.\n    apply proj2 in REL0. red in REL0.\n    destruct x; [| done]. \n    unfold Events.loc in REL0 at 1. rewrite wf_init_lab in REL0; auto.\n    congruence.\n  Qed.\n  \n  \nEnd FairExecution.\n\nLemma fin_exec_fair G (WF: Wf G) (FIN: fin_exec G):\n  mem_fair G.\nProof using.\n  red. apply fsupp_union_iff.\n  arewrite (co G ∪ fr G ≡ ⦗acts_set G⦘ ⨾ (co G ∪ fr G) ⨾ ⦗is_w (lab G)⦘).\n  { rewrite wf_coE, wf_frE, wf_coD, wf_frD; eauto. basic_solver 10. }\n  red. intros w.\n  destruct (classic (is_w (lab G) w)) as [W | NW].\n  2: { exists []. intros. apply seq_eqv_lr in REL. by desc. }\n  forward eapply is_w_loc as [l Lw]; eauto. \n  destruct FIN as [findom FIN].\n  exists (InitEvent l :: findom).\n  intros r REL%seq_eqv_lr. desc.\n  destruct r eqn:RR.\n  { simpl. left. f_equal. eapply hahn_inclusion_exp in REL0.\n    2: { rewrite wf_col, wf_frl, unionK; eauto. reflexivity. }\n    red in REL0. unfold loc in REL0 at 1. rewrite wf_init_lab in REL0; auto.\n    congruence. }\n  right. apply FIN. split; auto. \nQed. \n\nLemma fin_exec_full_fair G (WF: Wf G) (FIN: fin_exec_full G):\n  mem_fair G.\nProof using.\n  apply fin_exec_fair; auto. apply fin_exec_full_equiv in FIN. by desc. \nQed. \n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/basic/FairExecution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.22812456641369458}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.client_lemmas.\n\nLocal Open Scope logic.\n\n(*\nLemma gvar_globals_only:\n  forall i v rho, gvar i v rho -> gvar i v (globals_only rho).\nProof.\nunfold gvar; intros.\nunfold Map.get in *.\ndestruct (ve_of rho i) as [[? ?]|] eqn:?; try contradiction.\nunfold globals_only.\nsimpl. auto.\nQed.\nHint Resolve gvar_globals_only.\n*)\n\nLtac safe_auto_with_closed :=\n   (* won't instantiate evars by accident *)\n match goal with |- ?A =>\n          solve [first [has_evar A | auto 50 with closed]]\n end.\n\nLemma closed_env_set:\n forall {B} i v (P: environ -> B) rho,\n     closed_wrt_vars (eq i) P ->\n     P (env_set rho i v) = P rho.\nProof.\n intros. hnf in H.\n symmetry; destruct rho; apply H.\n intros; simpl; destruct (ident_eq i i0). left; auto.\n right; rewrite Map.gso; auto.\nQed.\nHint Rewrite @closed_env_set using safe_auto_with_closed : norm2.\n\nLemma subst_eval_id_eq:\n forall id v, subst id v (eval_id id) = v.\nProof. unfold subst, eval_id; intros. extensionality rho.\n    unfold force_val, env_set; simpl. rewrite Map.gss; auto.\nQed.\n\nLemma subst_eval_id_neq:\n  forall id v j, id<>j -> subst id v (eval_id j) = eval_id j.\nProof.\n    unfold subst, eval_id; intros. extensionality rho.\n    unfold force_val, env_set; simpl. rewrite Map.gso; auto.\nQed.\n\nHint Rewrite subst_eval_id_eq : subst.\nHint Rewrite subst_eval_id_neq using safe_auto_with_closed : subst.\n\n(*\nLemma subst_temp_eq:\n  forall i v w, subst i `v (temp i w) = `(eq w v).\nProof.\nunfold temp; intros; autorewrite with subst.\nextensionality rho; unfold_lift. reflexivity.\nQed.\n\nLemma subst_temp_neq:\n  forall i j v w, i<>j -> subst i v (temp j w) = temp j w.\nProof.\nunfold temp; intros. autorewrite with subst.\nf_equal. apply subst_eval_id_neq; auto.\nQed.\n\nLemma subst_var:\n   forall i j v t w,  subst i v (var j t w) = var j t w.\nProof.\nunfold var; intros; autorewrite with subst; auto.\nQed.\n\nHint Rewrite subst_var : subst.\nHint Rewrite subst_temp_eq : subst.\nHint Rewrite subst_temp_neq using safe_auto_with_closed : subst.\n*)\n\nFixpoint subst_eval_expr  {cs: compspecs}  (j: ident) (v: environ -> val) (e: expr) : environ -> val :=\n match e with\n | Econst_int i ty => `(Vint i)\n | Econst_long i ty => `(Vlong i)\n | Econst_float f ty => `(Vfloat f)\n | Econst_single f ty => `(Vsingle f)\n | Etempvar id ty => if eqb_ident j id then v else eval_id id\n | Eaddrof a ty => subst_eval_lvalue j v a\n | Eunop op a ty =>  `(eval_unop op (typeof a)) (subst_eval_expr j v a)\n | Ebinop op a1 a2 ty =>\n                  `(eval_binop op (typeof a1) (typeof a2)) (subst_eval_expr j v a1) (subst_eval_expr j v a2)\n | Ecast a ty => `(eval_cast (typeof a) ty) (subst_eval_expr j v a)\n | Evar id ty => eval_var id ty\n | Ederef a ty => subst_eval_expr j v a\n | Efield a i ty => `(eval_field (typeof a) i) (subst_eval_lvalue j v a)\n | Esizeof t ty => `(Vptrofs (Ptrofs.repr (sizeof t)))\n | Ealignof t ty => `(Vptrofs (Ptrofs.repr (alignof t)))\n end\n\n with subst_eval_lvalue {cs: compspecs} (j: ident) (v: environ -> val) (e: expr) : environ -> val :=\n match e with\n | Evar id ty => eval_var id ty\n | Ederef a ty => subst_eval_expr j v a\n | Efield a i ty => `(eval_field (typeof a) i) (subst_eval_lvalue j v a)\n | _  => `Vundef\n end.\n\nLemma subst_eval_expr_eq:\n    forall {cs: compspecs} j v e, subst j v (eval_expr e) = subst_eval_expr j v e\nwith subst_eval_lvalue_eq:\n    forall {cs: compspecs} j v e, subst j v (eval_lvalue e) = subst_eval_lvalue j v e.\nProof.\nintros cs j v; clear subst_eval_expr_eq; induction e; intros; simpl; try auto.\nunfold eqb_ident.\nunfold subst, eval_id, env_set, te_of. extensionality rho.\npose proof (Pos.eqb_spec j i).\ndestruct H. subst. rewrite Map.gss. reflexivity.\nrewrite Map.gso; auto.\nrewrite <- IHe; clear IHe.\nunfold_lift.\nextensionality rho; unfold subst.\nreflexivity.\nunfold_lift.\nextensionality rho; unfold subst.\nrewrite <- IHe1, <- IHe2; reflexivity.\nunfold_lift.\nextensionality rho; unfold subst.\nrewrite <- IHe; reflexivity.\nunfold_lift.\nrewrite <- subst_eval_lvalue_eq.\nextensionality rho; unfold subst.\nf_equal. f_equal.\n\nintros Delta j v; clear subst_eval_lvalue_eq; induction e; intros; simpl; try auto.\nunfold_lift.\nextensionality rho; unfold subst.\nrewrite <- IHe.\nf_equal.\nQed.\n\nHint Rewrite @subst_eval_expr_eq @subst_eval_lvalue_eq : subst.\n\n\nLemma closed_wrt_subst:\n  forall {A} id e (P: environ -> A), closed_wrt_vars (eq id) P -> subst id e P = P.\nProof.\nintros.\nunfold subst, closed_wrt_vars in *.\nextensionality rho.\nsymmetry.\napply H.\nintros.\ndestruct (eq_dec id i); auto.\nright.\nrewrite Map.gso; auto.\nQed.\n\nLemma closed_wrt_map_subst:\n   forall {A: Type} id e (Q: list (environ -> A)),\n         Forall (closed_wrt_vars (eq id)) Q ->\n         map (subst id e) Q = Q.\nProof.\ninduction Q; intros.\nsimpl; auto.\ninv H.\nsimpl; f_equal; auto.\napply closed_wrt_subst; auto.\nQed.\nHint Rewrite @closed_wrt_map_subst using safe_auto_with_closed : subst.\nHint Rewrite @closed_wrt_subst using safe_auto_with_closed : subst.\n\nLemma closed_wrt_map_subst':\n   forall {A: Type} id e (Q: list (environ -> A)),\n         Forall (closed_wrt_vars (eq id)) Q ->\n         @map (LiftEnviron A) _ (subst id e) Q = Q.\nProof.\napply @closed_wrt_map_subst.\nQed.\n\n(*Hint Rewrite @closed_wrt_map_subst' using safe_auto_with_closed : norm.*)\nHint Rewrite @closed_wrt_map_subst' using safe_auto_with_closed : subst.\nLemma closed_wrt_subst_eval_expr:\n  forall {cs: compspecs} j v e,\n   closed_wrt_vars (eq j) (eval_expr e) ->\n   subst_eval_expr j v e = eval_expr e.\nProof.\nintros; rewrite <- subst_eval_expr_eq.\napply closed_wrt_subst; auto.\nQed.\nLemma closed_wrt_subst_eval_lvalue:\n  forall {cs: compspecs} j v e,\n   closed_wrt_vars (eq j) (eval_lvalue e) ->\n   subst_eval_lvalue j v e = eval_lvalue e.\nProof.\nintros; rewrite <- subst_eval_lvalue_eq.\napply closed_wrt_subst; auto.\nQed.\nHint Rewrite @closed_wrt_subst_eval_expr using solve [auto 50 with closed] : subst.\nHint Rewrite @closed_wrt_subst_eval_lvalue using solve [auto 50 with closed] : subst.\n\nHint Unfold closed_wrt_modvars : closed.\n\nLemma closed_wrt_local: forall S P, closed_wrt_vars S P -> closed_wrt_vars S (local P).\nProof.\nintros.\nhnf in H|-*; intros.\nspecialize (H _ _ H0).\nunfold local, lift1.\nf_equal; auto.\nQed.\n\nLemma closed_wrtl_local: forall S P, closed_wrt_lvars S P -> closed_wrt_lvars S (local P).\nProof.\nintros.\nhnf in H|-*; intros.\nspecialize (H _ _ H0).\nunfold local, lift1.\nf_equal; auto.\nQed.\nHint Resolve closed_wrt_local closed_wrtl_local : closed.\n\nLemma closed_wrt_lift0: forall {A} S (Q: A), closed_wrt_vars S (lift0 Q).\nProof.\nintros.\nintros ? ? ?.\nunfold lift0; auto.\nQed.\nLemma closed_wrtl_lift0: forall {A} S (Q: A), closed_wrt_lvars S (lift0 Q).\nProof.\nintros.\nintros ? ? ?.\nunfold lift0; auto.\nQed.\nHint Resolve closed_wrt_lift0 closed_wrtl_lift0 : closed.\n\nLemma closed_wrt_lift0C: forall {B} S (Q: B),\n   closed_wrt_vars S (@liftx (LiftEnviron B) Q).\nProof.\nintros.\nintros ? ? ?.\nunfold_lift; auto.\nQed.\nLemma closed_wrtl_lift0C: forall {B} S (Q: B),\n   closed_wrt_lvars S (@liftx (LiftEnviron B) Q).\nProof.\nintros.\nintros ? ? ?.\nunfold_lift; auto.\nQed.\nHint Resolve @closed_wrt_lift0C @closed_wrtl_lift0C: closed.\n\nLemma closed_wrt_lift1: forall {A}{B} S (f: A -> B) P,\n        closed_wrt_vars S P ->\n        closed_wrt_vars S (lift1 f P).\nProof.\nintros.\nintros ? ? ?. specialize (H _ _ H0).\nunfold lift1; f_equal; auto.\nQed.\nLemma closed_wrtl_lift1: forall {A}{B} S (f: A -> B) P,\n        closed_wrt_lvars S P ->\n        closed_wrt_lvars S (lift1 f P).\nProof.\nintros.\nintros ? ? ?. specialize (H _ _ H0).\nunfold lift1; f_equal; auto.\nQed.\nHint Resolve closed_wrt_lift1 closed_wrtl_lift1 : closed.\n\nLemma closed_wrt_lift1C: forall {A}{B} S (f: A -> B) P,\n        closed_wrt_vars S P ->\n        closed_wrt_vars S (@liftx (Tarrow A (LiftEnviron B)) f P).\nProof.\nintros.\nintros ? ? ?. specialize (H _ _ H0).\nunfold_lift; f_equal; auto.\nQed.\nLemma closed_wrtl_lift1C: forall {A}{B} S (f: A -> B) P,\n        closed_wrt_lvars S P ->\n        closed_wrt_lvars S (@liftx (Tarrow A (LiftEnviron B)) f P).\nProof.\nintros.\nintros ? ? ?. specialize (H _ _ H0).\nunfold_lift; f_equal; auto.\nQed.\nHint Resolve @closed_wrt_lift1C @closed_wrtl_lift1C : closed.\n\nLemma closed_wrt_lift2: forall {A1 A2}{B} S (f: A1 -> A2 -> B) P1 P2,\n        closed_wrt_vars S P1 ->\n        closed_wrt_vars S P2 ->\n        closed_wrt_vars S (lift2 f P1 P2).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H1).\nspecialize (H0 _ _ H1).\nunfold lift2; f_equal; auto.\nQed.\nLemma closed_wrtl_lift2: forall {A1 A2}{B} S (f: A1 -> A2 -> B) P1 P2,\n        closed_wrt_lvars S P1 ->\n        closed_wrt_lvars S P2 ->\n        closed_wrt_lvars S (lift2 f P1 P2).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H1).\nspecialize (H0 _ _ H1).\nunfold lift2; f_equal; auto.\nQed.\nHint Resolve closed_wrt_lift2 closed_wrtl_lift2 : closed.\n\nLemma closed_wrt_lift2C: forall {A1 A2}{B} S (f: A1 -> A2 -> B) P1 P2,\n        closed_wrt_vars S P1 ->\n        closed_wrt_vars S P2 ->\n        closed_wrt_vars S (@liftx (Tarrow A1 (Tarrow A2 (LiftEnviron B))) f P1 P2).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H1).\nspecialize (H0 _ _ H1).\nunfold_lift; f_equal; auto.\nQed.\nLemma closed_wrtl_lift2C: forall {A1 A2}{B} S (f: A1 -> A2 -> B) P1 P2,\n        closed_wrt_lvars S P1 ->\n        closed_wrt_lvars S P2 ->\n        closed_wrt_lvars S (@liftx (Tarrow A1 (Tarrow A2 (LiftEnviron B))) f P1 P2).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H1).\nspecialize (H0 _ _ H1).\nunfold_lift; f_equal; auto.\nQed.\nHint Resolve @closed_wrt_lift2C @closed_wrtl_lift2C : closed.\n\nLemma closed_wrt_lift3: forall {A1 A2 A3}{B} S (f: A1 -> A2 -> A3 -> B) P1 P2 P3,\n        closed_wrt_vars S P1 ->\n        closed_wrt_vars S P2 ->\n        closed_wrt_vars S P3 ->\n        closed_wrt_vars S (lift3 f P1 P2 P3).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H2).\nspecialize (H0 _ _ H2).\nspecialize (H1 _ _ H2).\nunfold lift3; f_equal; auto.\nQed.\nLemma closed_wrtl_lift3: forall {A1 A2 A3}{B} S (f: A1 -> A2 -> A3 -> B) P1 P2 P3,\n        closed_wrt_lvars S P1 ->\n        closed_wrt_lvars S P2 ->\n        closed_wrt_lvars S P3 ->\n        closed_wrt_lvars S (lift3 f P1 P2 P3).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H2).\nspecialize (H0 _ _ H2).\nspecialize (H1 _ _ H2).\nunfold lift3; f_equal; auto.\nQed.\nHint Resolve closed_wrt_lift3 closed_wrtl_lift3 : closed.\n\nLemma closed_wrt_lift3C: forall {A1 A2 A3}{B} S (f: A1 -> A2 -> A3 -> B) P1 P2 P3,\n        closed_wrt_vars S P1 ->\n        closed_wrt_vars S P2 ->\n        closed_wrt_vars S P3 ->\n        closed_wrt_vars S (@liftx (Tarrow A1 (Tarrow A2 (Tarrow A3 (LiftEnviron B)))) f P1 P2 P3).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H2).\nspecialize (H0 _ _ H2).\nspecialize (H1 _ _ H2).\nunfold_lift. f_equal; auto.\nQed.\n\nLemma closed_wrtl_lift3C: forall {A1 A2 A3}{B} S (f: A1 -> A2 -> A3 -> B) P1 P2 P3,\n        closed_wrt_lvars S P1 ->\n        closed_wrt_lvars S P2 ->\n        closed_wrt_lvars S P3 ->\n        closed_wrt_lvars S (@liftx (Tarrow A1 (Tarrow A2 (Tarrow A3 (LiftEnviron B)))) f P1 P2 P3).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H2).\nspecialize (H0 _ _ H2).\nspecialize (H1 _ _ H2).\nunfold_lift. f_equal; auto.\nQed.\nHint Resolve @closed_wrt_lift3C @closed_wrtl_lift3C : closed.\n\nLemma closed_wrt_lift4: forall {A1 A2 A3 A4}{B} S (f: A1 -> A2 -> A3 -> A4 -> B)\n       P1 P2 P3 P4,\n        closed_wrt_vars S P1 ->\n        closed_wrt_vars S P2 ->\n        closed_wrt_vars S P3 ->\n        closed_wrt_vars S P4 ->\n        closed_wrt_vars S (lift4 f P1 P2 P3 P4).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H3).\nspecialize (H0 _ _ H3).\nspecialize (H1 _ _ H3).\nspecialize (H2 _ _ H3).\nunfold lift4; f_equal; auto.\nQed.\nLemma closed_wrtl_lift4: forall {A1 A2 A3 A4}{B} S (f: A1 -> A2 -> A3 -> A4 -> B)\n       P1 P2 P3 P4,\n        closed_wrt_lvars S P1 ->\n        closed_wrt_lvars S P2 ->\n        closed_wrt_lvars S P3 ->\n        closed_wrt_lvars S P4 ->\n        closed_wrt_lvars S (lift4 f P1 P2 P3 P4).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H3).\nspecialize (H0 _ _ H3).\nspecialize (H1 _ _ H3).\nspecialize (H2 _ _ H3).\nunfold lift4; f_equal; auto.\nQed.\nHint Resolve closed_wrt_lift4  closed_wrtl_lift4 : closed.\n\nLemma closed_wrt_lift4C: forall {A1 A2 A3 A4}{B} S (f: A1 -> A2 -> A3 -> A4 -> B) P1 P2 P3 P4,\n        closed_wrt_vars S P1 ->\n        closed_wrt_vars S P2 ->\n        closed_wrt_vars S P3 ->\n        closed_wrt_vars S P4 ->\n        closed_wrt_vars S (@liftx (Tarrow A1 (Tarrow A2 (Tarrow A3 (Tarrow A4 (LiftEnviron B))))) f P1 P2 P3 P4).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H3).\nspecialize (H0 _ _ H3).\nspecialize (H1 _ _ H3).\nspecialize (H2 _ _ H3).\nunfold liftx; simpl.\nunfold lift. f_equal; auto.\nQed.\nLemma closed_wrtl_lift4C: forall {A1 A2 A3 A4}{B} S (f: A1 -> A2 -> A3 -> A4 -> B) P1 P2 P3 P4,\n        closed_wrt_lvars S P1 ->\n        closed_wrt_lvars S P2 ->\n        closed_wrt_lvars S P3 ->\n        closed_wrt_lvars S P4 ->\n        closed_wrt_lvars S (@liftx (Tarrow A1 (Tarrow A2 (Tarrow A3 (Tarrow A4 (LiftEnviron B))))) f P1 P2 P3 P4).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H3).\nspecialize (H0 _ _ H3).\nspecialize (H1 _ _ H3).\nspecialize (H2 _ _ H3).\nunfold liftx; simpl.\nunfold lift. f_equal; auto.\nQed.\nHint Resolve @closed_wrt_lift4C @closed_wrtl_lift4C : closed.\n\nLemma closed_wrt_const:\n forall A (P: A) S, closed_wrt_vars S (fun rho: environ => P).\nProof.\nintros. hnf; intros.\nsimpl. auto.\nQed.\nLemma closed_wrtl_const:\n forall A (P: A) S, closed_wrt_lvars S (fun rho: environ => P).\nProof.\nintros. hnf; intros.\nsimpl. auto.\nQed.\nHint Resolve @closed_wrt_const @closed_wrtl_const : closed.\n\nLemma closed_wrt_eval_var:\n  forall S id t, closed_wrt_vars S (eval_var id t).\nProof.\nunfold closed_wrt_vars, eval_var; intros.\nsimpl.\nauto.\nQed.\nHint Resolve closed_wrt_eval_var : closed.\nLemma closed_wrtl_eval_var:\n  forall S id t, ~ S id -> closed_wrt_lvars S (eval_var id t).\nProof.\nunfold closed_wrt_lvars, eval_var; intros.\nsimpl.\ndestruct (H0 id); [contradiction | ].\nrewrite <- H1; auto.\nQed.\nHint Resolve closed_wrtl_eval_var : closed.\n\n(*\nLemma closed_wrt_var:\n  forall S id t v, closed_wrt_vars S (var id t v).\nProof.\nunfold var; intros.\nauto with closed.\nQed.\nHint Resolve closed_wrt_var : closed.\n\nLemma closed_wrtl_var:\n forall S id t v, ~ S id -> closed_wrt_lvars S (var id t v).\nProof.\nunfold var; intros; auto with closed.\nQed.\nHint Resolve closed_wrtl_var : closed.\n*)\n\nLemma closed_wrt_lvar:\n  forall S id t v, closed_wrt_vars S (locald_denote (lvar id t v)).\nProof.\nintros.\nhnf; intros; simpl.\ndestruct (Map.get (ve_of rho) id); auto.\nQed.\nHint Resolve closed_wrt_lvar : closed.\n\nLemma closed_wrt_gvars:\n  forall S gv, closed_wrt_vars S (locald_denote (gvars gv)).\nProof.\nintros.\nhnf; intros; simpl. reflexivity.\nQed.\nHint Resolve closed_wrt_gvars : closed.\n\nLemma closed_wrtl_gvars:\n  forall S gv, closed_wrt_lvars S (locald_denote (gvars gv)).\nProof.\nintros.\nhnf; intros; simpl. reflexivity.\nQed.\nHint Resolve closed_wrtl_gvars : closed.\n\nLemma closed_wrtl_lvar:\n forall  {cs: compspecs} S id t v,\n    ~ S id -> closed_wrt_lvars S (locald_denote (lvar id t v)).\nProof.\nintros.\nhnf; intros; simpl.\nunfold lvar_denote.\ndestruct (H0 id); try contradiction.\nrewrite H1; auto.\nQed.\nHint Resolve closed_wrtl_lvar : closed.\n\nDefinition expr_closed_wrt_lvars (S: ident -> Prop) (e: expr) : Prop :=\n  forall (cs: compspecs) rho ve',\n     (forall i, S i \\/ Map.get (ve_of rho) i = Map.get ve' i) ->\n     eval_expr e rho = eval_expr e (mkEnviron (ge_of rho) ve' (te_of rho)).\n\nDefinition lvalue_closed_wrt_lvars (S: ident -> Prop) (e: expr) : Prop :=\n  forall (cs: compspecs) rho ve',\n     (forall i, S i \\/ Map.get (ve_of rho) i = Map.get ve' i) ->\n     eval_lvalue e rho = eval_lvalue e (mkEnviron (ge_of rho) ve'  (te_of rho)).\n\nLemma closed_wrt_cmp_ptr : forall {cs: compspecs} S e1 e2 c,\n  expr_closed_wrt_vars S e1 ->\n  expr_closed_wrt_vars S e2 ->\n  closed_wrt_vars S (`(cmp_ptr_no_mem c) (eval_expr e1) (eval_expr e2)).\nProof.\nintros.\nunfold closed_wrt_vars. intros.\nsuper_unfold_lift.\nunfold expr_closed_wrt_vars in *.\nspecialize (H rho te' H1).\nspecialize (H0 rho te' H1).\nunfold cmp_ptr_no_mem. rewrite H0. rewrite H.\nreflexivity.\nQed.\nLemma closed_wrtl_cmp_ptr : forall {cs: compspecs} S e1 e2 c,\n  expr_closed_wrt_lvars S e1 ->\n  expr_closed_wrt_lvars S e2 ->\n  closed_wrt_lvars S (`(cmp_ptr_no_mem c) (eval_expr e1) (eval_expr e2)).\nProof.\nintros.\nunfold closed_wrt_lvars. intros.\nsuper_unfold_lift.\nunfold expr_closed_wrt_lvars in *.\nspecialize (H cs rho ve' H1).\nspecialize (H0 cs rho ve' H1).\nunfold cmp_ptr_no_mem. rewrite H0. rewrite H.\nreflexivity.\nQed.\nHint Resolve closed_wrt_cmp_ptr closed_wrtl_cmp_ptr: closed.\n\nLemma closed_wrt_eval_id: forall S i,\n    ~ S i -> closed_wrt_vars S (eval_id i).\nProof.\nintros.\nintros ? ? ?.\nunfold eval_id, force_val.\nsimpl.\ndestruct (H0 i).\ncontradiction.\nrewrite H1; auto.\nQed.\nLemma closed_wrtl_eval_id: forall S i,\n    closed_wrt_lvars S (eval_id i).\nProof.\nintros.\nintros ? ? ?.\nunfold eval_id, force_val.\nsimpl. auto.\nQed.\nHint Resolve closed_wrt_eval_id closed_wrtl_eval_id : closed.\n\nLemma closed_wrt_temp: forall S i v,\n    ~ S i -> closed_wrt_vars S (locald_denote (temp i v)).\nProof.\nintros.\nhnf; simpl; intros.\nunfold_lift.\nunfold eval_id; simpl.\ndestruct (H0 i).\ncontradiction.\nrewrite H1; auto.\nQed.\n\nLemma closed_wrtl_temp: forall S i v,\n    closed_wrt_lvars S (locald_denote (temp i v)).\nProof.\nintros.\nunfold locald_denote.\nhnf; intros. simpl.\nunfold eval_id; simpl. auto.\nQed.\nHint Resolve closed_wrt_temp closed_wrtl_temp : closed.\n\nLemma closed_wrt_get_result1 :\n  forall (S: ident -> Prop) i , ~ S i -> closed_wrt_vars S (get_result1 i).\nProof.\nintros. unfold get_result1. simpl.\n hnf; intros.\n simpl. f_equal.\napply (closed_wrt_eval_id _ _ H); auto.\nQed.\nLemma closed_wrtl_get_result1 :\n  forall (S: ident -> Prop) i , closed_wrt_lvars S (get_result1 i).\nProof.\nintros. unfold get_result1. simpl.\n hnf; intros.\n simpl. f_equal.\nQed.\nHint Resolve closed_wrt_get_result1 closed_wrtl_get_result1 : closed.\n\nLemma closed_wrt_tc_FF:\n forall {cs: compspecs} S e, closed_wrt_vars S (denote_tc_assert (tc_FF e)).\nProof.\n intros. hnf; intros. reflexivity.\nQed.\nLemma closed_wrtl_tc_FF:\n forall {cs: compspecs} S e, closed_wrt_lvars S (denote_tc_assert (tc_FF e)).\nProof.\n intros. hnf; intros. reflexivity.\nQed.\nHint Resolve closed_wrt_tc_FF closed_wrtl_tc_FF : closed.\n\nLemma closed_wrt_tc_TT:\n forall {cs: compspecs} S, closed_wrt_vars S (denote_tc_assert (tc_TT)).\nProof.\n intros. hnf; intros. reflexivity.\nQed.\nLemma closed_wrtl_tc_TT:\n forall {cs: compspecs} S, closed_wrt_lvars S (denote_tc_assert (tc_TT)).\nProof.\n intros. hnf; intros. reflexivity.\nQed.\nHint Resolve closed_wrt_tc_TT closed_wrtl_tc_TT : closed.\n\nLemma closed_wrt_andp: forall S (P Q: environ->mpred),\n  closed_wrt_vars S P -> closed_wrt_vars S Q ->\n  closed_wrt_vars S (P && Q).\nProof.\nintros; hnf in *; intros.\nsimpl. f_equal; eauto.\nQed.\nLemma closed_wrtl_andp: forall S (P Q: environ->mpred),\n  closed_wrt_lvars S P -> closed_wrt_lvars S Q ->\n  closed_wrt_lvars S (P && Q).\nProof.\nintros; hnf in *; intros.\nsimpl. f_equal; eauto.\nQed.\nHint Resolve closed_wrt_andp closed_wrtl_andp : closed.\n\nLemma closed_wrt_exp: forall {A} S (P: A -> environ->mpred),\n  (forall a, closed_wrt_vars S (P a)) ->\n  closed_wrt_vars S (exp P).\nProof.\nintros; hnf in *; intros.\nsimpl. apply exp_congr. intros a.\nspecialize (H a).\nhnf in H.\neauto.\nQed.\n\nLemma closed_wrtl_exp: forall {A} S (P: A -> environ->mpred),\n  (forall a, closed_wrt_lvars S (P a)) ->\n  closed_wrt_lvars S (exp P).\nProof.\nintros; hnf in *; intros.\nsimpl. apply exp_congr. intros a.\nspecialize (H a).\nhnf in H.\neauto.\nQed.\nHint Resolve closed_wrt_exp closed_wrtl_exp : closed.\n\nLemma closed_wrt_imp: forall S (P Q: environ->mpred),\n  closed_wrt_vars S P -> closed_wrt_vars S Q ->\n  closed_wrt_vars S (P --> Q).\nProof.\nintros; hnf in *; intros.\nsimpl. f_equal; eauto.\nQed.\nLemma closed_wrtl_imp: forall S (P Q: environ->mpred),\n  closed_wrt_lvars S P -> closed_wrt_lvars S Q ->\n  closed_wrt_lvars S (P --> Q).\nProof.\nintros; hnf in *; intros.\nsimpl. f_equal; eauto.\nQed.\nHint Resolve closed_wrt_imp closed_wrtl_imp : closed.\n\nLemma closed_wrt_sepcon: forall S (P Q: environ->mpred),\n  closed_wrt_vars S P -> closed_wrt_vars S Q ->\n  closed_wrt_vars S (P * Q).\nProof.\nintros; hnf in *; intros.\nsimpl. f_equal; eauto.\nQed.\nLemma closed_wrtl_sepcon: forall S (P Q: environ->mpred),\n  closed_wrt_lvars S P -> closed_wrt_lvars S Q ->\n  closed_wrt_lvars S (P * Q).\nProof.\nintros; hnf in *; intros.\nsimpl. f_equal; eauto.\nQed.\nHint Resolve closed_wrt_sepcon closed_wrtl_sepcon : closed.\n\nLemma closed_wrt_emp {A} {ND: NatDed A} {SL: SepLog A}:\n  forall S, closed_wrt_vars S emp.\nProof. repeat intro. reflexivity. Qed.\nLemma closed_wrtl_emp {A} {ND: NatDed A} {SL: SepLog A}:\n  forall S, closed_wrt_lvars S emp.\nProof. repeat intro. reflexivity. Qed.\nHint Resolve (@closed_wrt_emp mpred Nveric Sveric) (@closed_wrtl_emp mpred Nveric Sveric) : closed.\n\nLemma closed_wrt_allp: forall A S P,\n  (forall x: A, closed_wrt_vars S (P x)) ->\n  closed_wrt_vars S (allp P).\nProof.\nintros; hnf in *; intros.\nsimpl.\napply pred_ext; apply allp_right; intro x; apply (allp_left _ x);\nspecialize (H x rho te' H0);\napply derives_refl'; congruence.\nQed.\nLemma closed_wrtl_allp: forall A S P,\n  (forall x: A, closed_wrt_lvars S (P x)) ->\n  closed_wrt_lvars S (allp P).\nProof.\nintros; hnf in *; intros.\nsimpl.\napply pred_ext; apply allp_right; intro x; apply (allp_left _ x);\nspecialize (H x rho ve' H0);\napply derives_refl'; congruence.\nQed.\nHint Resolve closed_wrt_allp closed_wrtl_allp : closed.\n\nLemma closed_wrt_globvars:\n  forall S gv v, closed_wrt_vars S (globvars2pred gv v).\nProof.\nintros.\nunfold globvars2pred.\nhnf; intros. unfold lift2. f_equal.\ninduction v; simpl map; auto with closed.\nsimpl.\nf_equal; auto.\nunfold globvar2pred; destruct a; simpl.\ndestruct (gvar_volatile g) eqn:?; auto.\nforget (readonly2share (gvar_readonly g)) as sh.\nforget (gv i) as j.\nrevert j; induction (gvar_init g); intros; simpl; f_equal; auto.\nQed.\n\nLemma closed_wrtl_globvars:\n  forall S gv v, closed_wrt_lvars S (globvars2pred gv v).\nProof.\nintros.\nunfold globvars2pred.\nhnf; intros. unfold lift2. f_equal.\ninduction v; simpl map; auto with closed.\nsimpl.\nf_equal; auto.\nunfold globvar2pred; destruct a; simpl.\ndestruct (gvar_volatile g) eqn:?; auto.\nforget (readonly2share (gvar_readonly g)) as sh.\nforget (gv i) as j.\nrevert j; induction (gvar_init g); intros; simpl; f_equal; auto.\nQed.\nHint Resolve closed_wrt_globvars closed_wrtl_globvars: closed.\n\nLemma closed_wrt_main_pre:\n  forall prog u v S, closed_wrt_vars S (main_pre prog u v).\nProof.\nintros. apply closed_wrt_globvars. Qed.\nLemma closed_wrtl_main_pre:\n  forall prog u v S, closed_wrt_lvars S (main_pre prog u v).\nProof.\nintros. apply closed_wrtl_globvars. Qed.\nLemma closed_wrt_main_pre_ext:\n  forall {Espec : OracleKind} prog z u v S, closed_wrt_vars S (main_pre_ext prog z u v).\nProof.\nintros. unfold main_pre_ext. apply closed_wrt_sepcon; [apply closed_wrt_globvars | apply closed_wrt_const].\nQed.\nLemma closed_wrtl_main_pre_ext:\n  forall {Espec : OracleKind} prog z u v S, closed_wrt_lvars S (main_pre_ext prog z u v).\nProof.\nintros. unfold main_pre_ext. apply closed_wrtl_sepcon; [apply closed_wrtl_globvars | apply closed_wrtl_const].\nQed.\nHint Resolve closed_wrt_main_pre closed_wrtl_main_pre closed_wrt_main_pre_ext closed_wrtl_main_pre_ext : closed.\n\nLemma closed_wrt_not1:\n  forall (i j: ident),\n   i<>j ->\n   not (eq i j).\nProof.\nintros.\nhnf.\nintros; subst; congruence.\nQed.\nHint Resolve closed_wrt_not1 : closed.\n\nLemma closed_wrt_tc_andp:\n  forall {cs: compspecs} S a b,\n  closed_wrt_vars S (denote_tc_assert a) ->\n  closed_wrt_vars S (denote_tc_assert b) ->\n  closed_wrt_vars S (denote_tc_assert (tc_andp a b)).\nProof.\n intros.\n hnf; intros.\n repeat rewrite denote_tc_assert_andp; simpl; f_equal; auto.\nQed.\n\n\nLemma closed_wrt_tc_orp:\n  forall {cs: compspecs} S a b,\n  closed_wrt_vars S (denote_tc_assert a) ->\n  closed_wrt_vars S (denote_tc_assert b) ->\n  closed_wrt_vars S (denote_tc_assert (tc_orp a b)).\nProof.\n intros.\n hnf; intros.\n repeat rewrite denote_tc_assert_orp; simpl.\n f_equal; auto.\nQed.\n\nLemma closed_wrt_tc_bool:\n  forall {cs: compspecs} S b e, closed_wrt_vars S (denote_tc_assert (tc_bool b e)).\nProof.\n intros.\n hnf; intros.\n destruct b; simpl; auto.\nQed.\n\nLemma closed_wrt_tc_int_or_ptr_type:\n  forall {cs: compspecs} S t, \n  closed_wrt_vars S (denote_tc_assert (tc_int_or_ptr_type t)).\nProof.\n intros.\n apply closed_wrt_tc_bool.\nQed.\n\nHint Resolve closed_wrt_tc_andp closed_wrt_tc_orp closed_wrt_tc_bool\n              closed_wrt_tc_int_or_ptr_type : closed.\n\nLemma closed_wrtl_tc_andp:\n  forall {cs: compspecs} S a b,\n  closed_wrt_lvars S (denote_tc_assert a) ->\n  closed_wrt_lvars S (denote_tc_assert b) ->\n  closed_wrt_lvars S (denote_tc_assert (tc_andp a b)).\nProof.\n intros.\n hnf; intros.\n repeat rewrite denote_tc_assert_andp; simpl; f_equal; auto.\nQed.\n\n\nLemma closed_wrtl_tc_orp:\n  forall {cs: compspecs} S a b,\n  closed_wrt_lvars S (denote_tc_assert a) ->\n  closed_wrt_lvars S (denote_tc_assert b) ->\n  closed_wrt_lvars S (denote_tc_assert (tc_orp a b)).\nProof.\n intros.\n hnf; intros.\n repeat rewrite denote_tc_assert_orp; simpl.\n f_equal; auto.\nQed.\nLemma closed_wrtl_tc_bool:\n  forall {cs: compspecs} S b e, closed_wrt_lvars S (denote_tc_assert (tc_bool b e)).\nProof.\n intros.\n hnf; intros.\n destruct b; simpl; auto.\nQed.\nHint Resolve closed_wrtl_tc_andp closed_wrtl_tc_orp closed_wrtl_tc_bool : closed.\n\nLemma closed_wrt_tc_test_eq:\n  forall {cs: compspecs} S e e',\n          expr_closed_wrt_vars S e ->\n          expr_closed_wrt_vars S e' ->\n  closed_wrt_vars S\n     (denote_tc_assert\n        (tc_test_eq e e')).\nProof.\nintros.\nhnf; intros.\nrewrite !binop_lemmas2.denote_tc_assert_test_eq'.\nsimpl. unfold_lift. rewrite H, H0; auto.\nQed.\nLemma closed_wrtl_tc_test_eq:\n  forall {cs: compspecs} S e e',\n          expr_closed_wrt_lvars S e ->\n          expr_closed_wrt_lvars S e' ->\n  closed_wrt_lvars S\n     (denote_tc_assert\n        (tc_test_eq e e')).\nProof.\nintros.\nhnf; intros.\nrewrite !binop_lemmas2.denote_tc_assert_test_eq'.\nsimpl. unfold_lift. rewrite H, H0; auto.\nQed.\nHint Resolve  closed_wrt_tc_test_eq  closed_wrtl_tc_test_eq : closed.\n\nLemma closed_wrt_tc_test_order:\n  forall {cs: compspecs} S e e',\n          expr_closed_wrt_vars S e ->\n          expr_closed_wrt_vars S e' ->\n  closed_wrt_vars S\n     (denote_tc_assert\n        (tc_test_order e e')).\nProof.\nintros.\nhnf; intros.\nrewrite !binop_lemmas2.denote_tc_assert_test_order'.\nsimpl. unfold_lift. rewrite H, H0; auto.\nQed.\nLemma closed_wrtl_tc_test_order:\n  forall {cs: compspecs} S e e',\n          expr_closed_wrt_lvars S e ->\n          expr_closed_wrt_lvars S e' ->\n  closed_wrt_lvars S\n     (denote_tc_assert\n        (tc_test_order e e')).\nProof.\nintros.\nhnf; intros.\nrewrite !binop_lemmas2.denote_tc_assert_test_order'.\nsimpl. unfold_lift. rewrite H, H0; auto.\nQed.\nHint Resolve  closed_wrt_tc_test_order  closed_wrtl_tc_test_order : closed.\n\nLemma expr_closed_const_int:\n  forall {cs: compspecs} S i t, expr_closed_wrt_vars S (Econst_int i t).\nProof.\nintros. unfold expr_closed_wrt_vars. simpl; intros.\nsuper_unfold_lift. auto.\nQed.\nLemma expr_closedl_const_int:\n  forall S i t, expr_closed_wrt_lvars S (Econst_int i t).\nProof.\nintros. unfold expr_closed_wrt_lvars. simpl; intros.\nsuper_unfold_lift. auto.\nQed.\nHint Resolve expr_closed_const_int expr_closedl_const_int : closed.\n\n\nLemma closed_wrt_tc_iszero:\n  forall {cs: compspecs}  S e, expr_closed_wrt_vars S e ->\n    closed_wrt_vars S (expr2.denote_tc_assert (tc_iszero e)).\nProof.\nintros.\nrewrite binop_lemmas2.denote_tc_assert_iszero'.\nsimpl.\nhnf; intros. hnf in H. specialize (H _ _ H0).\nunfold_lift. rewrite <- H. auto.\nQed.\nHint Resolve closed_wrt_tc_iszero : closed.\n\nLemma closed_wrtl_tc_iszero:\n  forall {cs: compspecs}  S e, expr_closed_wrt_lvars S e ->\n    closed_wrt_lvars S (expr2.denote_tc_assert (tc_iszero e)).\nProof.\nintros.\nrewrite binop_lemmas2.denote_tc_assert_iszero'.\nhnf; intros. specialize (H _ _ _ H0).\nsimpl. unfold_lift; simpl. rewrite <- H; auto.\nQed.\nHint Resolve closed_wrtl_tc_iszero : closed.\n\nLemma closed_wrt_tc_isptr:\n forall {cs: compspecs} S e,\n     expr_closed_wrt_vars S e ->\n     closed_wrt_vars S (denote_tc_assert (tc_isptr e)).\nProof.\n intros.\n hnf; intros.\n specialize (H _ _ H0).\n simpl. unfold_lift. f_equal; auto.\nQed.\nHint Resolve closed_wrt_tc_isptr : closed.\n\nLemma closed_wrtl_tc_isptr:\n forall {cs: compspecs} S e,\n     expr_closed_wrt_lvars S e ->\n     closed_wrt_lvars S (denote_tc_assert (tc_isptr e)).\nProof.\n intros.\n hnf; intros. specialize (H _ _ _ H0).\n simpl. unfold_lift; simpl. rewrite <- H; auto.\nQed.\nHint Resolve closed_wrtl_tc_isptr : closed.\n\nLemma closed_wrt_tc_isint:\n forall {cs: compspecs} S e,\n     expr_closed_wrt_vars S e ->\n     closed_wrt_vars S (denote_tc_assert (tc_isint e)).\nProof.\n intros.\n hnf; intros.\n specialize (H _ _ H0).\n simpl. unfold_lift. f_equal; auto.\nQed.\nHint Resolve closed_wrt_tc_isint : closed.\n\nLemma closed_wrtl_tc_isint:\n forall {cs: compspecs} S e,\n     expr_closed_wrt_lvars S e ->\n     closed_wrt_lvars S (denote_tc_assert (tc_isint e)).\nProof.\n intros.\n hnf; intros.\n specialize (H _ _ _ H0).\n simpl. unfold_lift. f_equal; auto.\nQed.\nHint Resolve closed_wrtl_tc_isint : closed.\n\nLemma closed_wrt_tc_islong:\n forall {cs: compspecs} S e,\n     expr_closed_wrt_vars S e ->\n     closed_wrt_vars S (denote_tc_assert (tc_islong e)).\nProof.\n intros.\n hnf; intros.\n specialize (H _ _ H0).\n simpl. unfold_lift. f_equal; auto.\nQed.\nHint Resolve closed_wrt_tc_islong : closed.\n\nLemma closed_wrtl_tc_islong:\n forall {cs: compspecs} S e,\n     expr_closed_wrt_lvars S e ->\n     closed_wrt_lvars S (denote_tc_assert (tc_islong e)).\nProof.\n intros.\n hnf; intros.\n specialize (H _ _ _ H0).\n simpl. unfold_lift. f_equal; auto.\nQed.\nHint Resolve closed_wrtl_tc_islong : closed.\n\nLemma closed_wrt_isCastResultType:\n  forall {cs: compspecs} S e t t0,\n          expr_closed_wrt_vars S e ->\n          closed_wrt_vars S\n                 (denote_tc_assert (isCastResultType (implicit_deref t) t0 e)).\nProof.\n intros.\nrewrite expr_lemmas3.isCastR.\ndestruct (classify_cast (implicit_deref t) t0) eqn:?;\n  simpl; auto with closed;\n try solve [destruct t0 as [ | [ | | | ] [|] | [|] | [ | ] |  | | | | ]; simpl;\n                auto with closed; try reflexivity];\n  auto with closed;\n repeat simple_if_tac; try destruct si2; simpl; auto with closed.\n apply closed_wrt_tc_test_eq; auto with closed.\n hnf; intros. reflexivity.\nQed.\n\nLemma closed_wrtl_tc_Zge:\n  forall  {cs: compspecs} S e i,\n   expr_closed_wrt_lvars S e ->\n   closed_wrt_lvars S  (denote_tc_assert (tc_Zge e i)).\nProof.\nintros.\nhnf; intros. simpl. unfold_lift. rewrite (H _ _ _ H0). auto.\nQed.\n\nLemma closed_wrtl_tc_Zle:\n  forall  {cs: compspecs} S e i,\n   expr_closed_wrt_lvars S e ->\n   closed_wrt_lvars S  (denote_tc_assert (tc_Zle e i)).\nProof.\nintros.\nhnf; intros. simpl. unfold_lift. rewrite (H _ _ _ H0). auto.\nQed.\nHint Resolve closed_wrtl_tc_Zge closed_wrtl_tc_Zle : closed.\n\nLemma closed_wrtl_isCastResultType:\n  forall {cs: compspecs} S e t t0,\n          expr_closed_wrt_lvars S e ->\n          closed_wrt_lvars S\n                 (denote_tc_assert (isCastResultType (implicit_deref t) t0 e)).\nProof.\n intros.\nrewrite expr_lemmas3.isCastR.\n\nchange expr2.denote_tc_assert with denote_tc_assert.\ndestruct (classify_cast (implicit_deref t) t0) eqn:?;\n  auto with closed;\n try solve [destruct t0 as [ | [ | | | ] [|] | [|] | [ | ] |  | | | | ]; simpl;\n                auto with closed; try reflexivity];\nrepeat simple_if_tac;  auto with closed;\n try destruct si2; auto with closed.\n apply closed_wrtl_tc_test_eq; auto with closed.\n hnf; intros. reflexivity.\nQed.\n\nHint Resolve closed_wrt_isCastResultType closed_wrtl_isCastResultType : closed.\n\nLemma closed_wrt_tc_temp_id :\n  forall {cs: compspecs} Delta S e id t, expr_closed_wrt_vars S e ->\n                         expr_closed_wrt_vars S (Etempvar id t) ->\n             closed_wrt_vars S (tc_temp_id id t Delta e).\nProof.\nintros.\nunfold tc_temp_id.\nunfold typecheck_temp_id.\ndestruct ( (temp_types Delta) ! id) eqn:?; try destruct p; simpl; auto with closed.\nQed.\n\nLemma closed_wrtl_tc_temp_id :\n  forall {cs: compspecs} Delta S e id t, expr_closed_wrt_lvars S e ->\n                         expr_closed_wrt_lvars S (Etempvar id t) ->\n             closed_wrt_lvars S (tc_temp_id id t Delta e).\nProof.\nintros.\nunfold tc_temp_id.\nunfold typecheck_temp_id.\ndestruct ( (temp_types Delta) ! id) eqn:?; try destruct p; simpl; auto with closed.\nQed.\n\nHint Resolve closed_wrt_tc_temp_id closed_wrtl_tc_temp_id : closed.\n\nLemma expr_closed_tempvar:\n forall {cs: compspecs} S i t, ~ S i -> expr_closed_wrt_vars S (Etempvar i t).\nProof.\nintros.\nhnf; intros.\nsimpl. unfold eval_id. f_equal.\ndestruct (H0 i); auto.\ncontradiction.\nQed.\nLemma expr_closedl_tempvar:\n forall S i t, expr_closed_wrt_lvars S (Etempvar i t).\nProof.\nintros.\nhnf; intros.\nsimpl. unfold eval_id. f_equal.\nQed.\nHint Resolve expr_closed_tempvar expr_closedl_tempvar : closed.\n\nHint Extern 1 (not (@eq ident _ _)) => (let Hx := fresh in intro Hx; inversion Hx) : closed.\n\nLemma expr_closed_cast: forall {cs: compspecs} S e t,\n     expr_closed_wrt_vars S e ->\n     expr_closed_wrt_vars S (Ecast e t).\nProof.\n unfold expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift.\n destruct (H rho te' H0); auto.\nQed.\nLemma expr_closedl_cast: forall S e t,\n     expr_closed_wrt_lvars S e ->\n     expr_closed_wrt_lvars S (Ecast e t).\nProof.\n unfold expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift.\n destruct (H cs rho ve' H0); auto.\nQed.\nHint Resolve expr_closed_cast expr_closedl_cast : closed.\n\nLemma expr_closed_field: forall {cs: compspecs} S e f t,\n  lvalue_closed_wrt_vars S e ->\n  expr_closed_wrt_vars S (Efield e f t).\nProof.\n unfold lvalue_closed_wrt_vars, expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift.\n f_equal.\n apply H.  auto.\nQed.\nLemma expr_closedl_field: forall S e f t,\n  lvalue_closed_wrt_lvars S e ->\n  expr_closed_wrt_lvars S (Efield e f t).\nProof.\n unfold lvalue_closed_wrt_lvars, expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift.\n f_equal.\n apply H.  auto.\nQed.\nHint Resolve expr_closed_field expr_closedl_field : closed.\n\nLemma expr_closed_binop: forall {cs: compspecs} S op e1 e2 t,\n     expr_closed_wrt_vars S e1 ->\n     expr_closed_wrt_vars S e2 ->\n     expr_closed_wrt_vars S (Ebinop op e1 e2 t).\nProof.\n unfold expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift. f_equal; auto.\nQed.\nLemma expr_closedl_binop: forall S op e1 e2 t,\n     expr_closed_wrt_lvars S e1 ->\n     expr_closed_wrt_lvars S e2 ->\n     expr_closed_wrt_lvars S (Ebinop op e1 e2 t).\nProof.\n unfold expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift. f_equal; auto.\nQed.\nHint Resolve expr_closed_binop expr_closedl_binop : closed.\n\nLemma expr_closed_unop: forall {cs: compspecs} S op e t,\n     expr_closed_wrt_vars S e ->\n     expr_closed_wrt_vars S (Eunop op e t).\nProof.\n unfold expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift. f_equal; auto.\nQed.\nLemma expr_closedl_unop: forall S op e t,\n     expr_closed_wrt_lvars S e ->\n     expr_closed_wrt_lvars S (Eunop op e t).\nProof.\n unfold expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift. f_equal; auto.\nQed.\nHint Resolve expr_closed_unop expr_closedl_unop : closed.\n\nLemma closed_wrt_stackframe_of:\n  forall {cs: compspecs} S f, closed_wrt_vars S (stackframe_of f).\nProof.\nintros.\nunfold stackframe_of.\ninduction (fn_vars f); auto.\napply closed_wrt_emp.\napply closed_wrt_sepcon; [ | apply IHl].\nclear. destruct a; unfold var_block.\nhnf; intros. reflexivity.\nQed.\nHint Resolve closed_wrt_stackframe_of : closed.\n\nDefinition included {U} (S S': U -> Prop) := forall x, S x -> S' x.\n\nLemma closed_wrt_TT:\n forall  (S: ident -> Prop),\n  closed_wrt_vars S (@TT (environ -> mpred) _).\nProof.\nintros. hnf; intros. reflexivity.\nQed.\nLemma closed_wrtl_TT:\n forall  (S: ident -> Prop),\n  closed_wrt_lvars S (@TT (environ -> mpred) _).\nProof.\nintros. hnf; intros. reflexivity.\nQed.\nHint Resolve closed_wrt_TT closed_wrtl_TT : closed.\n\nLemma closed_wrt_subset:\n  forall (S S': ident -> Prop) (H: included S' S) B (f: environ -> B),\n       closed_wrt_vars S f -> closed_wrt_vars S' f.\nProof.\nintros. hnf. intros. specialize (H0 rho te').\napply H0.\nintro i; destruct (H1 i); auto.\nQed.\nLemma closed_wrtl_subset:\n  forall (S S': ident -> Prop) (H: included S' S) B (f: environ -> B),\n       closed_wrt_lvars S f -> closed_wrt_lvars S' f.\nProof.\nintros. hnf. intros. specialize (H0 rho ve').\napply H0.\nintro i; destruct (H1 i); auto.\nQed.\nHint Resolve closed_wrt_subset closed_wrtl_subset : closed.\n\nLemma closed_wrt_Forall_subset:\n  forall S S' (H: included S' S) B (f: list (environ -> B)),\n Forall (closed_wrt_vars S) f ->\n Forall (closed_wrt_vars S') f.\nProof.\ninduction f; simpl; auto.\nintro.\ninv H0.\nconstructor.\napply (closed_wrt_subset _ _ H). auto.\nauto.\nQed.\nLemma closed_wrtl_Forall_subset:\n  forall S S' (H: included S' S) B (f: list (environ -> B)),\n Forall (closed_wrt_lvars S) f ->\n Forall (closed_wrt_lvars S') f.\nProof.\ninduction f; simpl; auto.\nintro.\ninv H0.\nconstructor.\napply (closed_wrtl_subset _ _ H). auto.\nauto.\nQed.\n\nLemma lvalue_closed_tempvar:\n forall {cs: compspecs} S i t, ~ S i -> lvalue_closed_wrt_vars S (Etempvar i t).\nProof.\nsimpl; intros.\nhnf; intros.\nsimpl. reflexivity.\nQed.\nLemma lvalue_closedl_tempvar:\n forall S i t, lvalue_closed_wrt_lvars S (Etempvar i t).\nProof.\nsimpl; intros.\nhnf; intros.\nsimpl. reflexivity.\nQed.\nHint Resolve lvalue_closed_tempvar lvalue_closedl_tempvar : closed.\n\nLemma expr_closed_addrof: forall {cs: compspecs} S e t,\n     lvalue_closed_wrt_vars S e ->\n     expr_closed_wrt_vars S (Eaddrof e t).\nProof.\n unfold lvalue_closed_wrt_vars, expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift. apply H.  auto.\nQed.\nLemma expr_closedl_addrof: forall S e t,\n     lvalue_closed_wrt_lvars S e ->\n     expr_closed_wrt_lvars S (Eaddrof e t).\nProof.\n unfold lvalue_closed_wrt_lvars, expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift. apply H.  auto.\nQed.\nHint Resolve expr_closed_addrof expr_closedl_addrof : closed.\n\nLemma lvalue_closed_field: forall {cs: compspecs} S e f t,\n  lvalue_closed_wrt_vars S e ->\n  lvalue_closed_wrt_vars S (Efield e f t).\nProof.\n unfold lvalue_closed_wrt_vars, expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift. f_equal; apply H.  auto.\nQed.\nLemma lvalue_closedl_field: forall S e f t,\n  lvalue_closed_wrt_lvars S e ->\n  lvalue_closed_wrt_lvars S (Efield e f t).\nProof.\n unfold lvalue_closed_wrt_lvars, expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift. f_equal; apply H.  auto.\nQed.\nHint Resolve lvalue_closed_field lvalue_closedl_field : closed.\n\nLemma lvalue_closed_deref: forall {cs: compspecs} S e t,\n  expr_closed_wrt_vars S e ->\n  lvalue_closed_wrt_vars S (Ederef e t).\nProof.\n unfold lvalue_closed_wrt_vars, expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift. apply H.  auto.\nQed.\nLemma lvalue_closedl_deref: forall S e t,\n  expr_closed_wrt_lvars S e ->\n  lvalue_closed_wrt_lvars S (Ederef e t).\nProof.\n unfold lvalue_closed_wrt_lvars, expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift. apply H.  auto.\nQed.\nHint Resolve lvalue_closed_deref lvalue_closedl_deref: closed.\n\nFixpoint closed_eval_expr (j: ident) (e: expr) : bool :=\n match e with\n | Econst_int i ty => true\n | Econst_long i ty => true\n | Econst_float f ty => true\n | Econst_single f ty => true\n | Etempvar id ty => negb (eqb_ident j id)\n | Eaddrof a ty => closed_eval_lvalue j a\n | Eunop op a ty =>  closed_eval_expr j a\n | Ebinop op a1 a2 ty =>  andb (closed_eval_expr j a1) (closed_eval_expr j a2)\n | Ecast a ty => closed_eval_expr j a\n | Evar id ty => true\n | Ederef a ty => closed_eval_expr j a\n | Efield a i ty => closed_eval_lvalue j a\n | Esizeof _ _ => true\n | Ealignof _ _ => true\n end\n\n with closed_eval_lvalue (j: ident) (e: expr) : bool :=\n match e with\n | Evar id ty => true\n | Ederef a ty => closed_eval_expr j a\n | Efield a i ty => closed_eval_lvalue j a\n | _  => false\n end.\n\nLemma closed_eval_expr_e:\n    forall {cs: compspecs} j e, closed_eval_expr j e = true -> closed_wrt_vars (eq j) (eval_expr e)\nwith closed_eval_lvalue_e:\n    forall {cs: compspecs} j e, closed_eval_lvalue j e = true -> closed_wrt_vars (eq j) (eval_lvalue e).\nProof.\nintros cs j e; clear closed_eval_expr_e; induction e; intros; simpl; auto with closed.\nsimpl in H. destruct (eqb_ident j i) eqn:?; inv H.\napply Pos.eqb_neq in Heqb. auto with closed.\nsimpl in H.\nrewrite andb_true_iff in H. destruct H.\nauto with closed.\nintros Delta j e; clear closed_eval_lvalue_e; induction e; intros; simpl; auto with closed.\nQed.\n\nHint Extern 2 (closed_wrt_vars (eq _) (@eval_expr _ _)) => (apply closed_eval_expr_e; reflexivity) : closed.\nHint Extern 2 (closed_wrt_vars (eq _) (@eval_lvalue _ _)) => (apply closed_eval_lvalue_e; reflexivity) : closed.\n\nLemma closed_wrt_eval_expr: forall {cs: compspecs} S e,\n  expr_closed_wrt_vars S e ->\n  closed_wrt_vars S (eval_expr e).\nProof.\nunfold expr_closed_wrt_vars, closed_wrt_vars.\nintros.\napply H; auto.\nQed.\n(* Hint Resolve closed_wrt_eval_expr : closed. *)\n\nLemma closed_wrt_lvalue: forall {cs: compspecs} S e,\n  access_mode (typeof e) = By_reference ->\n  closed_wrt_vars S (eval_expr e) -> closed_wrt_vars S (eval_lvalue e).\nProof.\nintros.\ndestruct e; simpl in *; auto with closed;\nunfold closed_wrt_vars in *;\nintros; specialize (H0 _ _ H1); clear H1; super_unfold_lift;\nauto.\nQed.\n(* Hint Resolve closed_wrt_lvalue : closed. *)\n\nLemma closed_wrt_ideq: forall {cs: compspecs} a b e,\n  a <> b ->\n  closed_eval_expr a e = true ->\n  closed_wrt_vars (eq a) (fun rho => !! (eval_id b rho = eval_expr e rho)).\nProof.\nintros.\nhnf; intros.\nsimpl. f_equal.\nf_equal.\nspecialize (H1 b).\ndestruct H1; [contradiction | ].\nunfold eval_id; simpl. rewrite H1. auto.\nclear b H.\neapply closed_eval_expr_e in H0.\napply H0; auto.\nQed.\n\nHint Extern 2 (closed_wrt_vars (eq _) _) =>\n      (apply closed_wrt_ideq; [solve [let Hx := fresh in (intro Hx; inv Hx)] | reflexivity]) : closed.\n\nLemma closed_wrt_tc_nonzero:\n forall {cs: compspecs} S e,\n     closed_wrt_vars S (eval_expr e) ->\n     closed_wrt_vars S (denote_tc_assert (tc_nonzero e)).\nProof.\n intros.\n hnf; intros.\n specialize (H _ _ H0).\n repeat rewrite binop_lemmas2.denote_tc_assert_nonzero.\n rewrite <- H; auto.\nQed.\nHint Resolve closed_wrt_tc_nonzero : closed.\n\nLemma closed_wrt_binarithType:\n  forall {cs: compspecs} S t1 t2 t a b,\n  closed_wrt_vars S (denote_tc_assert (binarithType t1 t2 t a b)).\nProof.\n intros.\n unfold binarithType.\n destruct (Cop.classify_binarith t1 t2); simpl; auto with closed.\nQed.\nHint Resolve closed_wrt_binarithType : closed.\n\nLemma closed_wrt_tc_samebase :\n forall {cs: compspecs} S e1 e2,\n closed_wrt_vars S (eval_expr e1) ->\n closed_wrt_vars S (eval_expr e2) ->\n closed_wrt_vars S (denote_tc_assert (tc_samebase e1 e2)).\nProof.\n intros;  hnf; intros. simpl. unfold_lift. f_equal; auto.\nQed.\nHint Resolve closed_wrt_tc_samebase : closed.\n\nLemma closed_wrt_tc_ilt:\n  forall {cs: compspecs} S e n,\n    closed_wrt_vars S (eval_expr e) ->\n    closed_wrt_vars S (denote_tc_assert (tc_ilt e n)).\nProof.\n intros; hnf; intros.\n repeat rewrite binop_lemmas2.denote_tc_assert_ilt'.\n simpl. unfold_lift. f_equal. auto.\nQed.\nHint Resolve closed_wrt_tc_ilt : closed.\n\nLemma closed_wrt_tc_llt:\n  forall {cs: compspecs} S e n,\n    closed_wrt_vars S (eval_expr e) ->\n    closed_wrt_vars S (denote_tc_assert (tc_llt e n)).\nProof.\n intros; hnf; intros.\n repeat rewrite binop_lemmas2.denote_tc_assert_llt'.\n simpl. unfold_lift. f_equal. auto.\nQed.\nHint Resolve closed_wrt_tc_llt : closed.\n\nLemma closed_wrt_tc_Zge:\n  forall {cs: compspecs} S e n,\n    closed_wrt_vars S (eval_expr e) ->\n    closed_wrt_vars S (denote_tc_assert (tc_Zge e n)).\nProof.\n intros; hnf; intros.\n simpl. unfold_lift; f_equal; auto.\nQed.\nHint Resolve closed_wrt_tc_Zge : closed.\nLemma closed_wrt_tc_Zle:\n  forall {cs: compspecs} S e n,\n    closed_wrt_vars S (eval_expr e) ->\n    closed_wrt_vars S (denote_tc_assert (tc_Zle e n)).\nProof.\n intros; hnf; intros.\n simpl. unfold_lift; f_equal; auto.\nQed.\nHint Resolve closed_wrt_tc_Zle : closed.\n\nLemma closed_wrt_replace_nth:\n  forall {B} S n R (R1: environ -> B),\n    closed_wrt_vars S R1 ->\n    Forall (closed_wrt_vars S) R ->\n    Forall (closed_wrt_vars S) (replace_nth n R R1).\nProof.\nintros.\nrevert R H0; induction n; destruct R; simpl; intros; auto with closed;\ninv H0; constructor; auto with closed.\nQed.\nHint Resolve @closed_wrt_replace_nth : closed.\n\nLemma closed_wrt_tc_nodivover :\n forall {cs: compspecs} S e1 e2,\n closed_wrt_vars S (eval_expr e1) ->\n closed_wrt_vars S (eval_expr e2) ->\n closed_wrt_vars S (denote_tc_assert (tc_nodivover e1 e2)).\nProof.\n intros;  hnf; intros.\n repeat rewrite binop_lemmas2.denote_tc_assert_nodivover.\n rewrite <- H0; auto. rewrite <- H; auto.\nQed.\nHint Resolve closed_wrt_tc_nodivover : closed.\n\nLemma closed_wrt_tc_nosignedover:\n  forall op {CS: compspecs} S e1 e2,\n  closed_wrt_vars S (eval_expr e1) ->\n  closed_wrt_vars S (eval_expr e2) ->\n  closed_wrt_vars S (denote_tc_assert (tc_nosignedover op e1 e2)).\nProof.\nintros; hnf; intros.\nsimpl. unfold_lift.\nrewrite <- H; auto.\nrewrite <- H0; auto.\nQed.\nHint Resolve closed_wrt_tc_nosignedover : closed.\n\nLemma closed_wrt_tc_nobinover:\n  forall op {CS: compspecs} S e1 e2,\n  closed_wrt_vars S (eval_expr e1) ->\n  closed_wrt_vars S (eval_expr e2) ->\n  closed_wrt_vars S (denote_tc_assert (tc_nobinover op e1 e2)).\nProof.\nintros.\nunfold tc_nobinover.\nunfold if_expr_signed.\ndestruct (typeof e1); auto with closed.\ndestruct s; auto with closed.\ndestruct (eval_expr e1 any_environ); auto with closed;\ndestruct (eval_expr e2 any_environ); auto with closed.\nall: repeat simple_if_tac; auto with closed.\ndestruct (eval_expr e1 any_environ); auto with closed;\ndestruct (eval_expr e2 any_environ); auto with closed.\nall: try destruct s; repeat simple_if_tac; auto with closed.\nQed.\n\nHint Resolve closed_wrt_tc_nobinover : closed.\n\nLemma closed_wrt_tc_expr:\n  forall {cs: compspecs} Delta j e, closed_eval_expr j e = true ->\n             closed_wrt_vars (eq j) (tc_expr Delta e)\n with closed_wrt_tc_lvalue:\n  forall {cs: compspecs} Delta j e, closed_eval_lvalue j e = true ->\n             closed_wrt_vars (eq j) (tc_lvalue Delta e).\nProof.\n* clear closed_wrt_tc_expr.\nunfold tc_expr.\ninduction e; simpl; intros;\ntry solve [destruct t  as [ | [ | | | ] [ | ] | | [ | ] | | | | | ]; simpl; auto with closed].\n+\n  destruct (access_mode t);  simpl; auto with closed;\n  destruct (get_var_type Delta i); simpl; auto with closed.\n+\n  destruct ((temp_types Delta) ! i); simpl; auto with closed.\n  destruct (is_neutral_cast t0 t || same_base_type t0 t)%bool; simpl; auto with closed.\n  clear -  H.\n  hnf; intros.\n  specialize (H0 i).\n  pose proof (eqb_ident_spec j i).\n  destruct (eqb_ident j i); inv H.\n  destruct H0. apply H1 in H; inv H.\n  unfold denote_tc_initialized;  simpl.\n  f_equal.\n  apply exists_ext; intro v.\n  f_equal. rewrite H; auto.\n+ destruct (access_mode t) eqn:?H; simpl; auto with closed.\n  apply closed_wrt_tc_andp; auto with closed.\n  apply closed_wrt_tc_isptr; auto with closed.\n  apply closed_eval_expr_e; auto.\n+\n apply closed_wrt_tc_andp; auto with closed.\n apply closed_wrt_tc_lvalue; auto.\n+\n specialize (IHe H).\n apply closed_eval_expr_e in H.\n repeat apply closed_wrt_tc_andp; auto with closed.\n unfold isUnOpResultType.\n destruct u;\n destruct (typeof e) as   [ | [ | | | ] [ | ] | | [ | ] | | | | | ];\n   simpl; repeat apply closed_wrt_tc_andp; auto 50 with closed;\n  rewrite binop_lemmas2.denote_tc_assert_test_eq';\n  simpl; unfold_lift;\n  hnf; intros ? ? H8; simpl;\n  rewrite <- (H _ _ H8); auto.\n+\n  rewrite andb_true_iff in H. destruct H.\n specialize (IHe1 H). specialize (IHe2 H0).\n apply closed_eval_expr_e in H; apply closed_eval_expr_e in H0.\n repeat apply closed_wrt_tc_andp; auto with closed.\n unfold isBinOpResultType.\n destruct b; auto 50 with closed;\n try solve [destruct (Cop.classify_binarith (typeof e1) (typeof e2));\n                try destruct s;  auto with closed];\n try solve [destruct (Cop.classify_cmp (typeof e1) (typeof e2));\n                 simpl; auto 50 with closed].\n destruct (Cop.classify_add (typeof e1) (typeof e2)); auto 50 with closed.\n destruct (Cop.classify_sub (typeof e1) (typeof e2)); auto 50 with closed.\n destruct (Cop.classify_shift (typeof e1) (typeof e2)); auto 50 with closed.\n destruct (Cop.classify_shift (typeof e1) (typeof e2)); auto 50 with closed.\n\n+\n apply closed_wrt_tc_andp; auto with closed.\n specialize (IHe H).\n apply closed_eval_expr_e in H.\n unfold isCastResultType.\n destruct (classify_cast (typeof e) t); auto with closed;\n   try solve [ destruct t as [ | [ | | | ] [ | ]| [ | ] | [ | ] | | | | | ]; auto with closed].\nall: repeat simple_if_tac; try destruct si2; auto with closed.\n apply closed_wrt_tc_test_eq; auto with closed.\n hnf; intros; reflexivity.\n hnf; intros; reflexivity.\n+\n clear IHe.\n destruct (access_mode t); simpl; auto with closed.\n repeat apply closed_wrt_tc_andp; auto with closed.\n apply closed_wrt_tc_lvalue; auto.\n destruct (typeof e); simpl; auto with closed;\n destruct (cenv_cs ! i0); simpl; auto with closed.\n destruct (field_offset cenv_cs i (co_members c)); simpl; auto with closed.\n*\n clear closed_wrt_tc_lvalue.\n unfold tc_lvalue.\n induction e; simpl; intros; auto with closed.\n +\n destruct (get_var_type Delta i); simpl; auto with closed.\n +\n specialize (closed_wrt_tc_expr cs Delta _ _ H).\n apply closed_eval_expr_e in H.\n auto 50 with closed.\n +\n specialize (IHe H).\n apply closed_eval_lvalue_e  in H.\n repeat apply closed_wrt_tc_andp; auto with closed.\n destruct (typeof e); simpl; auto with closed;\n destruct (cenv_cs ! i0); simpl; auto with closed.\n destruct (field_offset cenv_cs i (co_members c)); simpl; auto with closed.\nQed.\n\nHint Resolve closed_wrt_tc_expr : closed.\nHint Resolve closed_wrt_tc_lvalue : closed.\n\n\nLemma closed_wrt_lift1':\n      forall (A B : Type) (S : ident -> Prop) (f : A -> B)\n         (P : environ -> A),\n       closed_wrt_vars S P -> closed_wrt_vars S (`f P).\nProof.\nintros.\napply closed_wrt_lift1.\nhnf; intros. simpl. f_equal.\napply H. auto.\nQed.\nHint Resolve closed_wrt_lift1' : closed.\n\nLemma closed_wrt_Econst_int:\n  forall {cs: compspecs} S i t, closed_wrt_vars S (eval_expr (Econst_int i t)).\nProof.\nsimpl; intros.\nauto with closed.\nQed.\nHint Resolve closed_wrt_Econst_int : closed.\n\nLemma closed_wrt_PROPx:\n forall S P Q, closed_wrt_vars S Q -> closed_wrt_vars S (PROPx P Q).\nProof.\nintros.\napply closed_wrt_andp; auto.\nhnf; intros. reflexivity.\nQed.\nLemma closed_wrtl_PROPx:\n forall S P Q, closed_wrt_lvars S Q -> closed_wrt_lvars S (PROPx P Q).\nProof.\nintros.\napply closed_wrtl_andp; auto.\nhnf; intros. reflexivity.\nQed.\nHint Resolve closed_wrt_PROPx closed_wrtl_PROPx: closed.\n\n\nLemma closed_wrt_LOCALx:\n forall S Q R, Forall (closed_wrt_vars S) (map locald_denote Q) ->\n                    closed_wrt_vars S R ->\n                    closed_wrt_vars S (LOCALx Q R).\nProof.\nintros.\napply closed_wrt_andp; auto.\nclear - H.\ninduction Q; simpl; intros.\nauto with closed.\nnormalize. autorewrite with norm1 norm2; normalize.\ninv H.\napply closed_wrt_andp; auto with closed.\nQed.\n\n\nLemma closed_wrtl_LOCALx:\n forall S Q R, Forall (closed_wrt_lvars S) (map locald_denote Q) ->\n                    closed_wrt_lvars S R ->\n                    closed_wrt_lvars S (LOCALx Q R).\nProof.\nintros.\napply closed_wrtl_andp; auto.\nclear - H.\ninduction Q; simpl; intros.\nauto with closed.\nnormalize. autorewrite with norm1 norm2; normalize.\ninv H.\napply closed_wrtl_andp; auto with closed.\nQed.\n(*\nLemma closed_wrt_LOCALx:\n forall S Q R, Forall (fun q => closed_wrt_vars S (local q)) Q ->\n                    closed_wrt_vars S R ->\n                    closed_wrt_vars S (LOCALx Q R).\nProof.\nintros.\napply closed_wrt_andp; auto.\nclear - H.\ninduction Q; simpl; intros.\nauto with closed.\nnormalize.\ninv H.\napply closed_wrt_andp; auto with closed.\nQed.\n*)\n\nHint Resolve closed_wrt_LOCALx closed_wrtl_LOCALx: closed.\n\nLemma closed_wrt_SEPx: forall S P,\n     closed_wrt_vars S (SEPx P).\nProof.\nintros.\nunfold SEPx.\nauto with closed.\nQed.\n\nLemma closed_wrtl_SEPx: forall S P,\n     closed_wrt_lvars S (SEPx P).\nProof.\nintros.\nunfold SEPx.\nauto with closed.\nQed.\nHint Resolve closed_wrt_SEPx closed_wrtl_SEPx: closed.\n\nLemma not_not_a_param_i:\n  forall (L: list (ident * type)) i,\n   In i (map (@fst _ _) L) ->\n   ~ not_a_param L i.\nProof.\nintros.\nintro. apply H0; auto.\nQed.\nHint Resolve not_not_a_param_i : closed.\n\nLemma in_map_fst1:\n forall (i: ident) (t: type) L,\n   In i (map (@fst _ _) ((i,t)::L)).\nProof.\nintros. left. reflexivity.\nQed.\nHint Resolve in_map_fst1 : closed.\n\nLemma in_map_fst2:\n forall (i: ident) a (L: list (ident*type)),\n   In i (map (@fst _ _) L) ->\n   In i (map (@fst _ _) (a::L)).\nProof.\nintros; right; auto.\nQed.\nHint Resolve in_map_fst2 : closed.\n\nLtac precondition_closed :=\n match goal with |- precondition_closed _ _ => idtac end;\n let x := fresh \"x\" in intro x;\n split;\n  repeat match goal with\n          | |- closed_wrt_vars _ (let (y,z) := ?x in _) => is_var x; destruct x\n          | |- closed_wrt_lvars _ (let (y,z) := ?x in _) => is_var x; destruct x\n          end;\n  [simpl not_a_param; auto 50 with closed\n  | simpl is_a_local; auto 50 with closed ].\n\nLemma Forall_map_cons:\n  forall {A B} (F: A -> Prop) (g: B -> A) b bl,\n  F (g b) -> Forall F (map g bl) ->\n  Forall F (map g (b::bl)).\nProof.\nsimpl.\nintros.\nconstructor; auto.\nQed.\n\nLemma Forall_map_nil:\n  forall {A B} (F: A -> Prop) (g: B -> A),\n  Forall F (map g nil).\nProof.\nsimpl.\nintros.\nconstructor; auto.\nQed.\nHint Resolve @Forall_map_cons @Forall_map_nil : closed.\nHint Resolve Forall_cons Forall_nil : closed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/floyd/closed_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22812456641369455}}
{"text": "(* GENERIC *)\n\nRequire Export MinBFTgen.\nRequire Export MinBFTcount_gen_tacs.\n\n\nSection MinBFTcount_gen1.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext        }.\n  Context { minbft_context      : MinBFT_context      }.\n  Context { m_initial_keys      : MinBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys   }.\n  Context { usig_hash           : USIG_hash           }.\n  Context { minbft_auth         : MinBFT_auth         }.\n\n  Context { ti : TrustedInfo }.\n\n\n  Lemma accepted_if_executed_previous_step :\n    forall {eo  : EventOrdering}\n           (e   : Event)\n           (req : Request)\n           (i   : nat)\n           (l   : list name)\n           (r   : Rep)\n           (s   : MAIN_state)\n           (subs : n_procs 1),\n      In (send_accept (accept req i) l)\n         (M_output_ls_on_this_one_event (MinBFTlocalSys_newP r s subs) e)\n      -> i = S (cexec s).\n  Proof.\n    introv h.\n    apply in_M_output_ls_on_this_one_event_implies in h; exrepnd; simpl in *; minbft_simp.\n    autorewrite with minbft comp in *.\n    Time minbft_dest_msg Case; simpl in *; tcsp; ginv; repeat smash_minbft2;\n      repndors; tcsp;\n        try (complete (inversion h0; subst; GC; eauto 4 with minbft));\n        repeat (try gdest; smash_minbft1_at_ h1; repeat hide_break; repnd;\n                simpl in *; repndors; ginv; tcsp; eauto 2 with minbft).\n  Qed.\n\nEnd MinBFTcount_gen1.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MinBFTcount_gen1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2281240142617566}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VFA.Maps.\nRequire Import VFA.SearchTree.\nRequire Import WandDemo.SearchTree_ext.\nRequire Import WandDemo.wand_frame.\nRequire Import WandDemo.wandQ_frame.\nRequire Import WandDemo.bst.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\nDefinition t_struct_tree := Tstruct _tree noattr.\n\nFixpoint tree_rep (t: tree val) (p: val) : mpred :=\n match t with\n | E => !!(p=nullval) && emp\n | T a x v b => !! (Int.min_signed <= Z.of_nat x <= Int.max_signed /\\ tc_val (tptr Tvoid) v) &&\n    EX pa:val, EX pb:val,\n    data_at Tsh t_struct_tree (Vint (Int.repr (Z.of_nat x)),(v,(pa,pb))) p *\n    tree_rep a pa * tree_rep b pb\n end.\n\nDefinition treebox_rep (t: tree val) (b: val) :=\n EX p: val, data_at Tsh (tptr t_struct_tree) p b * tree_rep t p.\n\nLemma tree_rep_spec: forall (t: tree val) (p: val),\n  tree_rep t p =\n  match t with\n  | E => !!(p=nullval) && emp\n  | T a x v b => !! (Int.min_signed <= Z.of_nat x <= Int.max_signed /\\ tc_val (tptr Tvoid) v) &&\n     EX pa:val, EX pb:val,\n     data_at Tsh t_struct_tree (Vint (Int.repr (Z.of_nat x)),(v,(pa,pb))) p *\n     tree_rep a pa * tree_rep b pb\n  end.\nProof.\n  intros.\n  destruct t; auto.\nQed.\n\nLemma treebox_rep_spec: forall (t: tree val) (b: val),\n  treebox_rep t b =\n  EX p: val,\n  data_at Tsh (tptr t_struct_tree) p b *\n  match t with\n  | E => !!(p=nullval) && emp\n  | T l x v r => !! (Int.min_signed <= Z.of_nat x <= Int.max_signed /\\ tc_val (tptr Tvoid) v) &&\n      field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat x))) p *\n      field_at Tsh t_struct_tree [StructField _value] v p *\n      treebox_rep l (field_address t_struct_tree [StructField _left] p) *\n      treebox_rep r (field_address t_struct_tree [StructField _right] p)\n  end.\nProof.\n  intros.\n  unfold treebox_rep at 1.\n  f_equal.\n  extensionality p.\n  destruct t; simpl.\n  + apply pred_ext; entailer!.\n  + unfold treebox_rep.\n    apply pred_ext; entailer!.\n    - Intros pa pb.\n      Exists pb pa.\n      unfold_data_at 1%nat.\n      rewrite (field_at_data_at _ t_struct_tree [StructField _left]).\n      rewrite (field_at_data_at _ t_struct_tree [StructField _right]).\n      cancel.\n    - Intros pa pb.\n      Exists pb pa.\n      unfold_data_at 3%nat.\n      rewrite (field_at_data_at _ t_struct_tree [StructField _left]).\n      rewrite (field_at_data_at _ t_struct_tree [StructField _right]).\n      cancel.\nQed.\n\nLemma treebox_rep_tree_rep: forall (t: tree val) (b: val),\n  treebox_rep t b = EX p: val, data_at Tsh (tptr t_struct_tree) p b * tree_rep t p.\nProof.\n  intros.\n  reflexivity.\nQed.\n\nLemma tree_rep_treebox_rep: forall (t: tree val) (p: val),\n  tree_rep t p =\n  match t with\n  | E => !!(p=nullval) && emp\n  | T l x v r => !! (Int.min_signed <= Z.of_nat x <= Int.max_signed /\\ tc_val (tptr Tvoid) v) &&\n      field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat x))) p *\n      field_at Tsh t_struct_tree [StructField _value] v p *\n      treebox_rep l (field_address t_struct_tree [StructField _left] p) *\n      treebox_rep r (field_address t_struct_tree [StructField _right] p)\n  end.\nProof.\n  intros.\n  destruct t; auto.\n  unfold treebox_rep; simpl.\n  apply pred_ext; Intros pa pb.\n  + Exists pb pa; entailer!.\n    unfold_data_at 1%nat.\n    cancel.\n    rewrite !field_at_data_at.\n    cancel.\n  + Exists pb pa; entailer!.\n    unfold_data_at 3%nat.\n    cancel.\n    rewrite !field_at_data_at.\n    cancel.\nQed.\n\nArguments tree_rep: simpl never.\nArguments treebox_rep: simpl never.\nOpaque treebox_rep tree_rep.\n\nLemma tree_rep_saturate_local:\n   forall t p, tree_rep t p |-- !! is_pointer_or_null p.\nProof.\n  intros.\n  rewrite tree_rep_treebox_rep.\n  destruct t;\n  entailer!.\nQed.\n\nHint Resolve tree_rep_saturate_local: saturate_local.\n\nLemma tree_rep_valid_pointer:\n  forall t p, tree_rep t p |-- valid_pointer p.\nProof.\n  intros.\n  rewrite tree_rep_treebox_rep.\n  destruct t; simpl;\n   normalize;\n   auto with valid_pointer.\n  repeat apply sepcon_valid_pointer1.\n  apply field_at_valid_ptr0; auto.\n  reflexivity.\nQed.\nHint Resolve tree_rep_valid_pointer: valid_pointer.\n\nLemma treebox_rep_saturate_local:\n   forall t b, treebox_rep t b |-- !! field_compatible (tptr t_struct_tree) [] b.\nProof.\nintros.\nrewrite treebox_rep_spec.\nIntros p.\ndestruct t;\nentailer!.\nQed.\n\nHint Resolve treebox_rep_saturate_local: saturate_local.\n\nLemma tree_rep_nullval: forall t,\n  tree_rep t nullval |-- !! (t = E).\nProof.\n  intros.\n  destruct t; [entailer! |].\n  rewrite tree_rep_treebox_rep.\n  entailer!.\nQed.\n\nHint Resolve tree_rep_nullval: saturate_local.\n\nLemma treebox_rep_leaf: forall x p b (v: val),\n  is_pointer_or_null v ->\n  Int.min_signed <= Z.of_nat x <= Int.max_signed ->\n  data_at Tsh t_struct_tree (Vint (Int.repr (Z.of_nat x)), (v, (nullval, nullval))) p * data_at Tsh (tptr t_struct_tree) p b |-- treebox_rep (T E x v E) b.\nProof.\n  intros.\n  rewrite treebox_rep_spec.\n  Exists p.\n  rewrite !treebox_rep_spec.\n  Exists nullval nullval.\n  unfold_data_at 1%nat.\n  entailer!.\n  rewrite !field_at_data_at.\n  cancel.\nQed.\n\nLemma treebox_rep_internal: forall l x v r b p,\n  Int.min_signed <= Z.of_nat x <= Int.max_signed ->\n  tc_val (tptr Tvoid) v ->\n  data_at Tsh (tptr t_struct_tree) p b *\n  field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat x))) p *\n  field_at Tsh t_struct_tree [StructField _value] v p *\n  treebox_rep l (field_address t_struct_tree [StructField _left] p) *\n  treebox_rep r (field_address t_struct_tree [StructField _right] p) |--\n  treebox_rep (T l x v r) b.\nProof.\n  intros.\n  rewrite (treebox_rep_spec (T _ _ _ _)).\n  Exists p.\n  entailer!.\nQed.\n\nLemma tree_rep_internal: forall l x v r (p p1 p2: val),\n  Int.min_signed <= Z.of_nat x <= Int.max_signed ->\n  tc_val (tptr Tvoid) v ->\n  data_at Tsh t_struct_tree (Vint (Int.repr (Z.of_nat x)), (v, (p1, p2))) p *\n  tree_rep l p1 *\n  tree_rep r p2 |--\n  tree_rep (T l x v r) p.\nProof.\n  intros.\n  rewrite (tree_rep_spec (T _ _ _ _)).\n  Exists p1 p2.\n  entailer!.\nQed.\n\nModule PartialTree_WandQFrame_Func_Hole.\n\nDefinition partialT (rep: tree val -> val -> mpred) (P: tree val -> tree val) (p_root p_in: val): mpred :=\n  ALL t: tree val, rep t p_in -* rep (P t) p_root.\n\nLemma partialT_rep_partialT_rep: forall rep pt12 pt23 p1 p2 p3,\n  partialT rep pt12 p2 p1 * partialT rep pt23 p3 p2 |-- partialT rep (Basics.compose pt23 pt12) p3 p1.\nProof.\n  intros.\n  unfold partialT.\n  sep_apply (wandQ_frame_refine _ _ (fun t => rep t p2 -* rep (pt23 t) p3) pt12).\n  rewrite sepcon_comm.\n  apply wandQ_frame_ver.\nQed.\n\nLemma emp_partialT_rep_H: forall rep p,\n  emp |-- partialT rep (fun t => t) p p.\nProof.\n  intros.\n  apply allp_right; intros.\n  apply wand_sepcon_adjoint.\n  normalize.\nQed.\n\nLemma rep_partialT_rep: forall rep t P p q,\n  rep t p * partialT rep P q p |-- rep (P t) q.\nProof.\n  intros.\n  exact (wandQ_frame_elim _ (fun t => rep t p) (fun t => rep (P t) q) t).\nQed.\n\nEnd PartialTree_WandQFrame_Func_Hole.\n\nModule PartialTreeboxRep_WandQFrame_Func_Hole.\n\nExport PartialTree_WandQFrame_Func_Hole.\n\nDefinition partial_treebox_rep := partialT treebox_rep.\n\nLemma partial_treebox_rep_singleton_left: forall (t2: tree val) k (v p b: val),\n  Int.min_signed <= Z.of_nat k <= Int.max_signed ->\n  is_pointer_or_null v ->\n  data_at Tsh (tptr t_struct_tree) p b *\n  field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat k))) p *\n  field_at Tsh t_struct_tree [StructField _value] v p *\n  treebox_rep t2 (field_address t_struct_tree [StructField _right] p)\n  |-- partial_treebox_rep (fun t1 => T t1 k v t2) b (field_address t_struct_tree [StructField _left] p).\nProof.\n  intros.\n  unfold partial_treebox_rep, partialT.\n  apply allp_right; intros t1.\n  rewrite <- wand_sepcon_adjoint.\n  rewrite (treebox_rep_spec (T t1 k v t2)).\n  Exists p.\n  entailer!.\nQed.\n\nLemma partial_treebox_rep_singleton_right: forall (t1: tree val) k (v p b: val),\n  Int.min_signed <= Z.of_nat k <= Int.max_signed ->\n  is_pointer_or_null v ->\n  data_at Tsh (tptr t_struct_tree) p b *\n  field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat k))) p *\n  field_at Tsh t_struct_tree [StructField _value] v p *\n  treebox_rep t1 (field_address t_struct_tree [StructField _left] p)\n  |-- partial_treebox_rep (fun t2 => T t1 k v t2) b (field_address t_struct_tree [StructField _right] p).\nProof.\n  intros.\n  unfold partial_treebox_rep, partialT.\n  apply allp_right; intros t2.\n  rewrite <- wand_sepcon_adjoint.\n  rewrite (treebox_rep_spec (T t1 k v t2)).\n  Exists p.\n  entailer!.\nQed.\n\nLemma partial_treebox_rep_partial_treebox_rep: forall pt12 pt23 p1 p2 p3,\n  partial_treebox_rep pt12 p2 p1 * partial_treebox_rep pt23 p3 p2 |-- partial_treebox_rep (Basics.compose pt23 pt12) p3 p1.\nProof. apply partialT_rep_partialT_rep. Qed.\n\nLemma emp_partial_treebox_rep_H: forall p,\n  emp |-- partial_treebox_rep (fun t => t) p p.\nProof. apply emp_partialT_rep_H. Qed.\n\nLemma treebox_rep_partial_treebox_rep: forall t pt p q,\n  treebox_rep t p * partial_treebox_rep pt q p |-- treebox_rep (pt t) q.\nProof. apply rep_partialT_rep. Qed.\n\nEnd PartialTreeboxRep_WandQFrame_Func_Hole.\n\nModule PartialTreeboxRep_WandFrame.\n\nLemma partial_treebox_rep_singleton_left: forall (t1' t2: tree val) k (v p b: val),\n  Int.min_signed <= Z.of_nat k <= Int.max_signed ->\n  is_pointer_or_null v ->\n  data_at Tsh (tptr t_struct_tree) p b *\n  field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat k))) p *\n  field_at Tsh t_struct_tree [StructField _value] v p *\n  treebox_rep t2 (field_address t_struct_tree [StructField _right] p)\n  |-- treebox_rep t1'\n        (field_address t_struct_tree [StructField _left] p) -*\n      treebox_rep (T t1' k v t2) b.\nProof.\n  intros.\n  rewrite (treebox_rep_spec (T t1' k v t2)).\n  rewrite <- wand_sepcon_adjoint.\n  Exists p.\n  entailer!.\nQed.\n\nLemma partial_treebox_rep_singleton_right: forall (t1 t2': tree val) k (v p b: val),\n  Int.min_signed <= Z.of_nat k <= Int.max_signed ->\n  is_pointer_or_null v ->\n  data_at Tsh (tptr t_struct_tree) p b *\n  field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat k))) p *\n  field_at Tsh t_struct_tree [StructField _value] v p *\n  treebox_rep t1 (field_address t_struct_tree [StructField _left] p)\n  |-- treebox_rep t2'\n       (field_address t_struct_tree [StructField _right] p) -*\n      treebox_rep (T t1 k v t2') b.\nProof.\n  intros.\n  rewrite (treebox_rep_spec (T t1 k v t2')).\n  rewrite <- wand_sepcon_adjoint.\n  Exists p.\n  entailer!.\nQed.\n\nLemma partial_treebox_rep_partial_treebox_rep: forall t1 t2 t3 p1 p2 p3,\n  (treebox_rep t1 p1 -* treebox_rep t2 p2) * (treebox_rep t2 p2 -* treebox_rep t3 p3) |-- treebox_rep t1 p1 -* treebox_rep t3 p3.\nProof.\n  intros.\n  apply wand_frame_ver.\nQed.\n\nLemma emp_partial_treebox_rep_H: forall t p,\n  emp |-- treebox_rep t p -* treebox_rep t p.\nProof.\n  intros.\n  apply wand_sepcon_adjoint.\n  normalize.\nQed.\n\nLemma treebox_rep_partial_treebox_rep: forall t t0 p p0,\n  treebox_rep t p * (treebox_rep t p -* treebox_rep t0 p0) |-- treebox_rep t0 p0.\nProof.\n  intros.\n  apply modus_ponens_wand.\nQed.\n\nEnd PartialTreeboxRep_WandFrame.\n\nModule PartialTreeboxRep_WandQFrame_Ind_Hole.\n\nDefinition partial_treebox_rep (pt: partial_tree val) (p_root p_in: val): mpred :=\n  ALL t: tree val, treebox_rep t p_in -* treebox_rep (partial_tree_tree pt t) p_root.\n\nLemma partial_treebox_rep_singleton_left: forall (t2: tree val) k (v p b: val),\n  Int.min_signed <= Z.of_nat k <= Int.max_signed ->\n  is_pointer_or_null v ->\n  data_at Tsh (tptr t_struct_tree) p b *\n  field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat k))) p *\n  field_at Tsh t_struct_tree [StructField _value] v p *\n  treebox_rep t2 (field_address t_struct_tree [StructField _right] p)\n  |-- partial_treebox_rep (L H k v t2) b (field_address t_struct_tree [StructField _left] p).\nProof.\n  intros.\n  unfold partial_treebox_rep.\n  apply allp_right; intros t1.\n  rewrite <- wand_sepcon_adjoint.\n  rewrite (treebox_rep_spec (T t1 k v t2)).\n  Exists p.\n  entailer!.\nQed.\n\nLemma partial_treebox_rep_singleton_right: forall (t1: tree val) k (v p b: val),\n  Int.min_signed <= Z.of_nat k <= Int.max_signed ->\n  is_pointer_or_null v ->\n  data_at Tsh (tptr t_struct_tree) p b *\n  field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat k))) p *\n  field_at Tsh t_struct_tree [StructField _value] v p *\n  treebox_rep t1 (field_address t_struct_tree [StructField _left] p)\n  |-- partial_treebox_rep (R t1 k v H) b (field_address t_struct_tree [StructField _right] p).\nProof.\n  intros.\n  unfold partial_treebox_rep.\n  apply allp_right; intros t2.\n  rewrite <- wand_sepcon_adjoint.\n  rewrite (treebox_rep_spec (T t1 k v t2)).\n  Exists p.\n  entailer!.\nQed.\n\nLemma partial_treebox_rep_partial_treebox_rep: forall pt12 pt23 p1 p2 p3,\n  partial_treebox_rep pt12 p2 p1 * partial_treebox_rep pt23 p3 p2 |-- partial_treebox_rep (partial_tree_partial_tree pt23 pt12) p3 p1.\nProof.\n  intros.\n  unfold partial_treebox_rep.\n  rewrite partial_tree_partial_tree_tree.\n  sep_apply (wandQ_frame_refine _ _ (fun t => treebox_rep t p2 -* treebox_rep (partial_tree_tree pt23 t) p3) (partial_tree_tree pt12)).\n  rewrite sepcon_comm.\n  apply wandQ_frame_ver.\nQed.\n\nLemma emp_partial_treebox_rep_H: forall p,\n  emp |-- partial_treebox_rep SearchTree_ext.H p p.\nProof.\n  intros.\n  apply allp_right; intros.\n  apply wand_sepcon_adjoint.\n  normalize.\n  simpl.\n  auto.\nQed.\n\nLemma treebox_rep_partial_treebox_rep: forall t pt p q,\n  treebox_rep t p * partial_treebox_rep pt q p |-- treebox_rep (partial_tree_tree pt t) q.\nProof.\n  intros.\n  unfold partial_treebox_rep.\n  change (treebox_rep (partial_tree_tree pt t) q)\n    with ((fun t => treebox_rep (partial_tree_tree pt t) q) t).\n  change (treebox_rep t p)\n    with ((fun t => treebox_rep t p) t).\n  apply wandQ_frame_elim.\nQed.\n\nEnd PartialTreeboxRep_WandQFrame_Ind_Hole.\n\nModule PartialTreeboxRep_Ind_Pred_Ind_Hole.\n\nFixpoint partial_treebox_rep (pt: partial_tree val) (p_root p_in: val): mpred :=\n  match pt with\n  | H => !! (p_root = p_in) && emp\n  | L pt1 x v t2 =>\n      EX p : val,\n        !! (Int.min_signed <= Z.of_nat x <= Int.max_signed /\\ tc_val (tptr Tvoid) v) &&\n        data_at Tsh (tptr t_struct_tree) p p_root *\n        field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat x))) p *\n        field_at Tsh t_struct_tree [StructField _value] v p *\n        partial_treebox_rep pt1 (field_address t_struct_tree [StructField _left] p) p_in *\n        treebox_rep t2 (field_address t_struct_tree [StructField _right] p)\n  | R t1 x v pt2 =>\n      EX p : val,\n        !! (Int.min_signed <= Z.of_nat x <= Int.max_signed /\\ tc_val (tptr Tvoid) v) &&\n        data_at Tsh (tptr t_struct_tree) p p_root *\n        field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat x))) p *\n        field_at Tsh t_struct_tree [StructField _value] v p *\n        treebox_rep t1 (field_address t_struct_tree [StructField _left] p) *\n        partial_treebox_rep pt2 (field_address t_struct_tree [StructField _right] p) p_in\n  end.\n\nLemma partial_treebox_rep_singleton_left: forall (t2: tree val) k (v p b: val),\n  Int.min_signed <= Z.of_nat k <= Int.max_signed ->\n  is_pointer_or_null v ->\n  data_at Tsh (tptr t_struct_tree) p b *\n  field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat k))) p *\n  field_at Tsh t_struct_tree [StructField _value] v p *\n  treebox_rep t2 (field_address t_struct_tree [StructField _right] p)\n  |-- partial_treebox_rep (L H k v t2) b (field_address t_struct_tree [StructField _left] p).\nProof.\n  intros.\n  unfold partial_treebox_rep.\n  Exists p.\n  entailer!.\nQed.\n\nLemma partial_treebox_rep_singleton_right: forall (t1: tree val) k (v p b: val),\n  Int.min_signed <= Z.of_nat k <= Int.max_signed ->\n  is_pointer_or_null v ->\n  data_at Tsh (tptr t_struct_tree) p b *\n  field_at Tsh t_struct_tree [StructField _key] (Vint (Int.repr (Z.of_nat k))) p *\n  field_at Tsh t_struct_tree [StructField _value] v p *\n  treebox_rep t1 (field_address t_struct_tree [StructField _left] p)\n  |-- partial_treebox_rep (R t1 k v H) b (field_address t_struct_tree [StructField _right] p).\nProof.\n  intros.\n  unfold partial_treebox_rep.\n  Exists p.\n  entailer!.\nQed.\n\nLemma partial_treebox_rep_partial_treebox_rep: forall pt12 pt23 p1 p2 p3,\n  partial_treebox_rep pt12 p2 p1 * partial_treebox_rep pt23 p3 p2 |-- partial_treebox_rep (partial_tree_partial_tree pt23 pt12) p3 p1.\nProof.\n  intros.\n  revert p3; induction pt23; intros.\n  + simpl.\n    entailer!.\n  + simpl.\n    Intros p.\n    Exists p.\n    entailer!.\n    apply IHpt23.\n  + simpl.\n    Intros p.\n    Exists p.\n    entailer!.\n    apply IHpt23.\nQed.\n\nLemma emp_partial_treebox_rep_H: forall p,\n  emp |-- partial_treebox_rep H p p.\nProof.\n  intros.\n  unfold partial_treebox_rep.\n  entailer!.\nQed.\n\nLemma treebox_rep_partial_treebox_rep: forall t pt p q,\n  treebox_rep t p * partial_treebox_rep pt q p |-- treebox_rep (partial_tree_tree pt t) q.\nProof.\n  intros.\n  revert q; induction pt; intros.\n  + simpl.\n    entailer!.\n  + simpl.\n    Intros p'.\n    rewrite (treebox_rep_spec (T (partial_tree_tree pt t) k v t0)).\n    Exists p'.\n    entailer!.\n    apply IHpt.\n  + simpl.\n    Intros p'.\n    rewrite (treebox_rep_spec (T t0 k v (partial_tree_tree pt t))).\n    Exists p'.\n    entailer!.\n    apply IHpt.\nQed.\n\nEnd PartialTreeboxRep_Ind_Pred_Ind_Hole.\n\nModule PartialTreeRep_WandQFrame_Func_Hole.\n\nExport PartialTree_WandQFrame_Func_Hole.\n\nDefinition partial_tree_rep := partialT tree_rep.\n\nLemma partial_tree_rep_singleton_left: forall (t2: tree val) k (v p p1 p2: val),\n  Int.min_signed <= Z.of_nat k <= Int.max_signed ->\n  is_pointer_or_null v ->\n  data_at Tsh t_struct_tree (Vint (Int.repr (Z.of_nat k)), (v, (p1, p2))) p *\n  tree_rep t2 p2\n  |-- partial_tree_rep (fun t1 => T t1 k v t2) p p1.\nProof.\n  intros.\n  unfold partial_tree_rep, partialT.\n  apply allp_right; intros t1.\n  rewrite <- wand_sepcon_adjoint.\n  rewrite (tree_rep_spec (T t1 k v t2)).\n  Exists p1 p2.\n  entailer!.\nQed.\n\nLemma partial_tree_rep_singleton_right: forall (t1: tree val) k (v p p1 p2: val),\n  Int.min_signed <= Z.of_nat k <= Int.max_signed ->\n  is_pointer_or_null v ->\n  data_at Tsh t_struct_tree (Vint (Int.repr (Z.of_nat k)), (v, (p1, p2))) p *\n  tree_rep t1 p1\n  |-- partial_tree_rep (fun t2 => T t1 k v t2) p p2.\nProof.\n  intros.\n  unfold partial_tree_rep, partialT.\n  apply allp_right; intros t2.\n  rewrite <- wand_sepcon_adjoint.\n  rewrite (tree_rep_spec (T t1 k v t2)).\n  Exists p1 p2.\n  entailer!.\nQed.\n\nLemma partial_tree_rep_partial_tree_rep: forall pt12 pt23 p1 p2 p3,\n  partial_tree_rep pt12 p2 p1 * partial_tree_rep pt23 p3 p2 |-- partial_tree_rep (Basics.compose pt23 pt12) p3 p1.\nProof. apply partialT_rep_partialT_rep. Qed.\n\nLemma emp_partial_tree_rep_H: forall p,\n  emp |-- partial_tree_rep (fun t => t) p p.\nProof. apply emp_partialT_rep_H. Qed.\n\nLemma tree_rep_partial_tree_rep: forall t pt p q,\n  tree_rep t p * partial_tree_rep pt q p |-- tree_rep (pt t) q.\nProof. apply rep_partialT_rep. Qed.\n\nEnd PartialTreeRep_WandQFrame_Func_Hole.\n\nDefinition Map_rep (m: total_map val) (p: val): mpred :=\n  EX t: tree val, !! (Abs val nullval t m /\\ SearchTree val t) && tree_rep t p.\n\nDefinition Mapbox_rep (m: total_map val) (p: val): mpred :=\n  EX q: val, data_at Tsh (tptr t_struct_tree) q p * Map_rep m q.\n\nLemma Mapbox_rep_unfold: forall (m: total_map val) (p: val),\n  Mapbox_rep m p = EX t: tree val, !! (Abs val nullval t m /\\ SearchTree val t) && treebox_rep t p.\nProof.\n  intros.\n  apply pred_ext.\n  + unfold Mapbox_rep, Map_rep; Intros q t.\n    Exists t.\n    rewrite treebox_rep_tree_rep.\n    Exists q.\n    entailer!.\n  + Intros t.\n    rewrite treebox_rep_tree_rep.\n    Intros q.\n    unfold Mapbox_rep, Map_rep; Exists q t.\n    entailer!.\nQed.\n\nOpaque Map_rep.\nArguments Map_rep: simpl never.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/wand_demo/wand_demo/bst_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.22806661194973313}}
{"text": "Require Import syntax.\nRequire Import alist.\nRequire Import Decs.\n\nRequire Import Metatheory.\nImport LLVMsyntax.\n\nRequire Import sflib.\n\nRequire Import TODO.\nRequire Import Ords.\n\nSet Implicit Arguments.\n\nLocal Open Scope OrdIdx_scope.\n\n(* TODO: Move to Ords.v *)\nModule Backport_Alt (E: OrdersAlt.OrderedTypeAlt) <: OrderedType.OrderedType.\n  Module OT := (OrdersAlt.OT_from_Alt E).\n  Include (OrdersAlt.Backport_OT OT).\nEnd Backport_Alt.\n\n(* TODO: move to Ords.v *)\nModule prod (E1 E2: AltUsual) <: AltUsual.\n\n  Definition t : Type := E1.t * E2.t.\n\n  Definition compare (x y: t): comparison :=\n    lexico_order [fun _ => E1.compare (fst x) (fst y) ; fun _ => E2.compare (snd x) (snd y)].\n\n  Lemma compare_sym\n        x y\n    :\n      <<SYM: compare y x = CompOpp (compare x y)>>\n  .\n  Proof.\n    destruct x as [x1 x2], y as [y1 y2]. unfold compare. red.\n    specialize (E1.compare_sym x1 y1). intro SYM_E1.\n    specialize (E2.compare_sym x2 y2). intro SYM_E2.\n    ss. des_ifs.\n  Qed.\n\n  Lemma leibniz_compare_eq1 x\n    : E1.compare x x = Eq.\n  Proof.\n    specialize (E1.compare_sym x x). i.\n    destruct (E1.compare x x) eqn:COMP; ss.\n  Qed.\n\n  Lemma leibniz_compare_eq2 x\n    : E2.compare x x = Eq.\n  Proof.\n    specialize (E2.compare_sym x x). i.\n    destruct (E2.compare x x) eqn:COMP; ss.\n  Qed.\n\n  Lemma compare_trans: forall\n      c x y z (* for compatibility with Alt *)\n      (XY: compare x y = c)\n      (YZ: compare y z = c)\n    ,\n      <<XZ: compare x z = c>>\n  .\n  Proof.\n    i. destruct x as [x1 x2], y as [y1 y2], z as [z1 z2].\n    unfold compare in *. red.\n    specialize (@E1.compare_trans c x1 y1 z1). intro TR_E1.\n    specialize (@E2.compare_trans c x2 y2 z2). intro TR_E2.\n    ss. des_ifs;\n          try (by exploit TR_E1; eauto);\n          try (by exploit TR_E2; eauto);\n      repeat match goal with\n             | [H: E1.compare ?a ?b = Eq |- _] =>\n               specialize (E1.compare_leibniz H); i; []; subst; clear H\n             | [H: E2.compare ?a ?b = Eq |- _] =>\n               specialize (E2.compare_leibniz H); i; []; subst; clear H\n             | [H: E1.compare ?a ?a = Lt |- _] =>\n               rewrite leibniz_compare_eq1 in H\n             | [H: E1.compare ?a ?a = Gt |- _] =>\n               rewrite leibniz_compare_eq1 in H\n             | [H: E2.compare ?a ?a = Lt |- _] =>\n               rewrite leibniz_compare_eq2 in H\n             | [H: E2.compare ?a ?a = Gt |- _] =>\n               rewrite leibniz_compare_eq2 in H\n      end; try congruence.\n  Qed.\n\n  Lemma compare_leibniz: forall\n      x y\n      (EQ: compare x y = Eq)\n    ,\n      x = y\n  .\n  Proof.\n    destruct x, y; ss. unfold compare. i. ss. des_ifs.\n    f_equal.\n    - apply E1.compare_leibniz; ss.\n    - apply E2.compare_leibniz; ss.\n  Qed.\n\nEnd prod.\n\n\n\n\nModule Tag <: AltUsual.\n  Inductive t_: Set :=\n  | physical\n  | previous\n  | ghost\n  .\n  Definition t := t_.\n  Definition eq := @eq t.\n  Definition eq_refl := @refl_equal t.\n  Definition eq_sym := @sym_eq t.\n  Definition eq_trans := @trans_eq t.\n  Definition eq_dec (x y:t): {x = y} + {x <> y}.\n    decide equality.\n  Defined.\n  Global Program Instance eq_equiv : Equivalence eq.\n\n  Definition is_previous x := match x with Tag.previous => true | _ => false end.\n  Definition is_ghost x := match x with Tag.ghost => true | _ => false end.\n\n  (* physical < previous < ghost *)\n  Definition ltb (x y: t): bool :=\n    match x, y with\n    | physical, previous => true\n    | physical, ghost => true\n    | previous, ghost => true\n    | _, _ => false\n    end.\n\n  (* Definition lt: t -> t -> Prop := ltb. *)\n\n  Definition compare (x y: t): comparison :=\n    if(eq_dec x y) then Eq else\n      (if (ltb x y) then Lt else Gt)\n  .\n\n  Lemma compare_sym : forall x y : t, << SYM: compare y x = CompOpp (compare x y) >>.\n  Proof. destruct x, y; ss. Qed.\n\n  Lemma compare_trans :\n     forall (c : comparison) (x y z : t),\n       compare x y = c -> compare y z = c -> << TR:compare x z = c >>.\n  Proof. i. destruct x, y, z; ss; des_ifs. Qed.\n\n  Lemma compare_leibniz : forall x y : t, compare x y = Eq -> x = y.\n  Proof. destruct x, y; ss. Qed.\n\nEnd Tag.\n\nHint Resolve Tag.eq_dec: EqDecDb.\n\n\nModule IdT <: AltUsual.\n  Include (prod Tag id).\n\n  Definition eq_dec (x y:t): {x = y} + {x <> y}.\n  Proof.\n    decide equality.\n    apply Tag.eq_dec.\n  Qed.\n\n  Definition lift (tag:Tag.t) (i:id): t := (tag, i).\n\nEnd IdT.\nHint Resolve IdT.eq_dec: EqDecDb.\n\nModule IdTFacts := AltUsualFacts IdT.\n\n\nModule IdT_OT := Backport_Alt IdT.\n\nModule IdTSet.\n  Include FSetAVLExtra IdT_OT.\n\n  Definition clear_idt (idt0: IdT.t) (t0: t): t :=\n    filter (fun x => negb (IdT.eq_dec idt0 x)) t0\n  .\n\nEnd IdTSet.\n\nModule IdTSetFacts := FSetFactsExtra IdT_OT IdTSet.\n\n\n(* Lemma IdT_equiv_compare_leibniz: *)\n(*   forall x y, IdT.compare x y = Eq <-> x = y. *)\n(* Proof. *)\n(*   intros. split. *)\n(*   - apply IdT.compare_leibniz. *)\n(*   - i. subst. apply IdTFacts.compare_refl. *)\n(* Qed. *)\n\nLemma InA_equiv:\n  forall X (eqA eqB: X -> X -> Prop)\n    (EQUIV: forall x y, eqA x y <-> eqB x y),\n  forall x l, InA eqA x l <-> InA eqB x l.\nProof.\n  intros.\n  induction l0.\n  { split; i; inv H. }\n  split; i; inv H.\n  - econs. apply EQUIV; auto.\n  - econs 2. apply IHl0; eauto.\n  - econs. apply EQUIV; auto.\n  - econs 2. apply IHl0; eauto.\nQed.\n\nLemma IdTSet_from_list_spec ids:\n  forall id, IdTSet.mem id (IdTSetFacts.from_list ids) <-> In id ids.\nProof.\n  i. rewrite IdTSetFacts.from_list_spec.\n  etransitivity; try apply InA_iff_In.\n  apply InA_equiv. split.\n  - apply IdT.compare_leibniz.\n  - i. subst. apply IdTFacts.compare_refl.\nQed.\n\nDefinition bop_canTrap (b0: bop): bool :=\n  match b0 with\n  | bop_udiv => true\n  | bop_sdiv => true\n  | bop_urem => true\n  | bop_srem => true\n  | _ => false\n  end\n.\n\nFixpoint const_canTrap (c:const): bool :=\n  match c with\n  | const_arr _ cl => existsb const_canTrap cl\n  | const_struct _ cl => existsb const_canTrap cl\n  | const_truncop _ c1 _ => const_canTrap c1\n  | const_extop _ c1 _ => const_canTrap c1\n  | const_castop _ c1 _ => const_canTrap c1\n  | const_gep _ c1 cl => const_canTrap c1 || existsb const_canTrap cl\n  | const_select c1 c2 c3 => const_canTrap c1 || const_canTrap c2 || const_canTrap c3\n  | const_icmp _ c1 c2 => const_canTrap c1 || const_canTrap c2\n  | const_fcmp _ c1 c2 => const_canTrap c1 || const_canTrap c2\n  | const_extractvalue c1 cl => const_canTrap c1 || existsb const_canTrap cl\n  | const_insertvalue c1 c2 cl => const_canTrap c1 || const_canTrap c2 || existsb const_canTrap cl\n  | const_bop b c1 c2 => const_canTrap c1 || const_canTrap c2 || bop_canTrap b\n  | const_fbop _ c1 c2 => const_canTrap c1 || const_canTrap c2\n  | _ => false\n  end.\n\n\nModule Value.\n  Definition t := value.\n\n  Definition get_ids(v: t): option id :=\n    match v with\n      | value_id i => Some i\n      | value_const _ => None\n    end.\n\n  Definition canTrap (v: t): bool :=\n    match v with\n    | value_const c =>\n      const_canTrap c\n    | _ => false\n    end\n  .\n\nEnd Value.\n\n\n\nModule ValueT <: AltUsual.\n  Inductive t_: Type :=\n  | id (x:IdT.t)\n  | const (c:const)\n  .\n  Definition t:= t_.\n  Definition eq_dec (x y:t): {x = y} + {x <> y}.\n  Proof.\n    decide equality.\n    apply IdT.eq_dec.\n    apply const_dec.\n  Qed.\n\n  Definition case_order v : OrdIdx.t :=\n    match v with\n    | id _ => 0\n    | const _ => 1\n    end.\n\n  Definition compare (v1 v2:t) : comparison :=\n    match v1, v2 with\n    | id x1, id x2 => IdT.compare x1 x2\n    | const c1, const c2 => const.compare c1 c2\n    | _, _ => OrdIdx.compare (case_order v1) (case_order v2)\n    end.\n\n  Lemma compare_sym\n        x y\n    : <<SYM: compare y x = CompOpp (compare x y)>>.\n  Proof.\n    destruct x, y; ss.\n    - apply IdT.compare_sym.\n    - apply const.compare_sym.\n  Qed.\n\n  Lemma compare_leibniz\n        x y\n        (EQ: compare x y = Eq)\n    : x = y.\n  Proof.\n    destruct x, y; ss.\n    - apply IdT.compare_leibniz in EQ. subst. eauto.\n    - apply const.compare_leibniz in EQ. subst. eauto.\n  Qed.\n\n  (* Ltac apply_trans := *)\n  (*   unfold NW in *; *)\n  (*   apply_trans_base; *)\n  (*   apply_trans_ typ.compare typ.compare_trans; *)\n  (*   apply_trans_IH t compare'; *)\n  (*   apply_trans_ (compare_list compare') *)\n  (*                (@compare_list_trans'' const compare' compare_leibniz compare_refl) *)\n  (* . *)\n\n  Lemma compare_trans\n        c x y z\n        (XY: compare x y = c)\n        (YZ: compare y z = c)\n    : <<XZ: compare x z = c>>.\n  Proof.\n    destruct c, x, y, z; ss;\n      try (by eapply IdT.compare_trans; eauto);\n      try (by eapply const.compare_trans; eauto).\n  Qed.\n\n  Definition lift (tag:Tag.t) (v:value): t :=\n    match v with\n    | value_id i => id (IdT.lift tag i)\n    | value_const c => const c\n    end.\n\n  Definition get_idTs (v: t): option IdT.t :=\n    match v with\n      | id i => Some i\n      | const _ => None\n    end.\n\n  Definition substitute (from: IdT.t) (to: ValueT.t) (body: ValueT.t): ValueT.t :=\n    match body with\n    | ValueT.id i => if(IdT.eq_dec from i) then to else body\n    | _ => body\n    end\n  .\n\n  Definition canTrap (v: t): bool :=\n    match v with\n    | ValueT.const c =>\n      const_canTrap c\n    | _ => false\n    end\n  .\n\nEnd ValueT.\n\nModule ValueTFacts := AltUsualFacts ValueT.\n\n\nHint Resolve ValueT.eq_dec: EqDecDb.\nCoercion ValueT.id: IdT.t >-> ValueT.t_.\nCoercion ValueT.const: const >-> ValueT.t_.\n\nModule ValueT_OT := Backport_Alt ValueT.\n\nModule ValueTSet := FSetAVLExtra ValueT_OT.\nModule ValueTSetFacts := FSetFactsExtra ValueT_OT ValueTSet.\n\nModule ValueTPair <: AltUsual.\n  Include prod ValueT ValueT.\n\n  Definition eq_dec (x y:t): {x = y} + {x <> y}.\n  Proof.\n    apply prod_dec;\n    apply ValueT.eq_dec.\n  Defined.\n\n  Definition get_idTs (vp: t): list IdT.t :=\n    (option_to_list (ValueT.get_idTs vp.(fst)))\n      ++ (option_to_list (ValueT.get_idTs vp.(snd))).\n\nEnd ValueTPair.\nHint Resolve ValueTPair.eq_dec: EqDecDb.\n\nModule ValueTPairFacts := AltUsualFacts ValueTPair. (* TODO: required? *)\nModule ValueTPair_OT := Backport_Alt ValueTPair.\n\n\nModule ValueTPairSet.\n  Include FSetAVLExtra ValueTPair_OT.\n\n  Definition clear_idt (idt: IdT.t) (t0: t): t :=\n    filter (fun xy => negb (list_inb IdT.eq_dec (ValueTPair.get_idTs xy) idt)) t0\n  .\n\nEnd ValueTPairSet.\n\nModule ValueTPairSetFacts := FSetFactsExtra ValueTPair_OT ValueTPairSet.\n\n\nModule sz_ValueT := prod sz ValueT.\nModule sz_ValueTFacts := AltUsualFacts sz_ValueT.\n\nModule Expr <: AltUsual.\n  Inductive t_: Type :=\n  | bop (b:bop) (s:sz) (v:ValueT.t) (w:ValueT.t)\n  | fbop (fb:fbop) (fp:floating_point) (v:ValueT.t) (w:ValueT.t)\n  | extractvalue (t:typ) (v:ValueT.t) (lc:list const) (u:typ)\n  | insertvalue (t:typ) (v:ValueT.t) (u:typ) (w:ValueT.t) (lc:list const)\n  | gep (ib:inbounds) (t:typ) (v:ValueT.t) (lsv:list (sz * ValueT.t)) (u:typ)\n  | trunc (top:truncop) (t:typ) (v:ValueT.t) (u:typ)\n  | ext (eop:extop) (t:typ) (v:ValueT.t) (u:typ)\n  | cast (cop:castop) (t:typ) (v:ValueT.t) (u:typ)\n  | icmp (c:cond) (t:typ) (v:ValueT.t) (w:ValueT.t)\n  | fcmp (fc:fcond) (fp:floating_point) (v:ValueT.t) (w:ValueT.t)\n  | select (v:ValueT.t) (t:typ) (w:ValueT.t) (z:ValueT.t)\n  | value (v:ValueT.t)\n  | load (v:ValueT.t) (t:typ) (a:align)\n  .\n\n  Definition t := t_.\n  Definition eq_dec (x y:t): {x = y} + {x <> y}.\n  Proof.\n    decide equality;\n      try (apply list_eq_dec);\n      try (apply prod_dec);\n      try (apply IdT.eq_dec);\n      try (apply ValueT.eq_dec);\n      try (apply id_dec);\n      try (apply Tag.eq_dec);\n      try (apply sz_dec);\n      try (apply bop_dec);\n      try (apply fbop_dec);\n      try (apply floating_point_dec);\n      try (apply typ_dec);\n      try (apply const_dec);\n      try (apply inbounds_dec);\n      try (apply truncop_dec);\n      try (apply extop_dec);\n      try (apply castop_dec);\n      try (apply cond_dec);\n      try (apply fcond_dec).\n  Defined.\n\n  Definition case_order e : OrdIdx.t :=\n    match e with\n    | bop _ _ _ _ => 0\n    | fbop _ _ _ _ => 1\n    | extractvalue _ _ _ _ => 2\n    | insertvalue _ _ _ _ _ => 3\n    | gep _ _ _ _ _ => 4\n    | trunc _ _ _ _ => 5\n    | ext _ _ _ _ => 6\n    | cast _ _ _ __ => 7\n    | icmp _ _ _ _ => 8\n    | fcmp _ _ _ _ => 9\n    | select _ _ _ _ => 10\n    | value _ => 11\n    | load _ _ _ => 12\n    end.\n\n  Definition compare' (e1 e2:t): comparison :=\n    match e1, e2 with\n    | bop b1 s1 v1 w1, bop b2 s2 v2 w2 =>\n      lexico_order [fun _ => bop.compare b1 b2 ; fun _ => sz.compare s1 s2 ;\n                      fun _ => ValueT.compare v1 v2 ; fun _ => ValueT.compare w1 w2]\n    | fbop fb1 fp1 v1 w1, fbop fb2 fp2 v2 w2 =>\n      lexico_order [fun _ => fbop.compare fb1 fb2 ; fun _ => floating_point.compare fp1 fp2 ;\n                      fun _ => ValueT.compare v1 v2 ; fun _ => ValueT.compare w1 w2]\n    | extractvalue t1 v1 lc1 u1, extractvalue t2 v2 lc2 u2 =>\n      lexico_order [fun _ => typ.compare t1 t2 ; fun _ => ValueT.compare v1 v2 ;\n                      fun _ => compare_list const.compare lc1 lc2 ;\n                      fun _ => typ.compare u1 u2]\n    | insertvalue t1 v1 u1 w1 lc1, insertvalue t2 v2 u2 w2 lc2 =>\n      lexico_order [fun _ => typ.compare t1 t2 ; fun _ => ValueT.compare v1 v2 ;\n                      fun _ => typ.compare u1 u2 ; fun _ => ValueT.compare w1 w2 ;\n                        fun _ => compare_list const.compare lc1 lc2]\n    | gep ib1 t1 v1 lsv1 u1, gep ib2 t2 v2 lsv2 u2 =>\n      lexico_order [fun _ => bool.compare ib1 ib2 ; fun _ => typ.compare t1 t2 ;\n                      fun _ => ValueT.compare v1 v2 ;\n                      fun _ => compare_list sz_ValueT.compare lsv1 lsv2 ;\n                      fun _ => typ.compare u1 u2]\n    | trunc top1 t1 v1 u1, trunc top2 t2 v2 u2 =>\n      lexico_order [fun _ => truncop.compare top1 top2 ; fun _ => typ.compare t1 t2 ;\n                      fun _ => ValueT.compare v1 v2 ; fun _ => typ.compare u1 u2]\n    | ext eop1 t1 v1 u1, ext eop2 t2 v2 u2 =>\n      lexico_order [fun _ => extop.compare eop1 eop2 ; fun _ => typ.compare t1 t2 ;\n                      fun _ => ValueT.compare v1 v2 ; fun _ => typ.compare u1 u2]\n    | cast cop1 t1 v1 u1, cast cop2 t2 v2 u2 =>\n      lexico_order [fun _ => castop.compare cop1 cop2 ; fun _ => typ.compare t1 t2 ;\n                      fun _ => ValueT.compare v1 v2 ; fun _ => typ.compare u1 u2]\n    | icmp c1 t1 v1 w1, icmp c2 t2 v2 w2 =>\n      lexico_order [fun _ => cond.compare c1 c2 ; fun _ => typ.compare t1 t2 ;\n                      fun _ => ValueT.compare v1 v2 ; fun _ => ValueT.compare w1 w2]\n    | fcmp c1 t1 v1 w1, fcmp c2 t2 v2 w2 =>\n      lexico_order [fun _ => fcond.compare c1 c2 ; fun _ => floating_point.compare t1 t2 ;\n                      fun _ => ValueT.compare v1 v2 ; fun _ => ValueT.compare w1 w2]\n    | select v1 t1 w1 z1, select v2 t2 w2 z2 =>\n      lexico_order [fun _ => ValueT.compare v1 v2 ; fun _ => typ.compare t1 t2 ;\n                      fun _ => ValueT.compare w1 w2 ; fun _ => ValueT.compare z1 z2]\n    | value v1, value v2 => ValueT.compare v1 v2\n    | load v1 t1 a1, load v2 t2 a2 =>\n      lexico_order [fun _ => ValueT.compare v1 v2 ; fun _ => typ.compare t1 t2 ;\n                      fun _ => sz.compare a1 a2]\n    | _, _ => OrdIdx.compare (case_order e1) (case_order e2)\n    end.\n\n  Definition compare := wrap_compare compare'.\n\n  Ltac comp_sym_list' cmp cmp_sym :=\n      match goal with\n      | [ |- context[match @compare_list ?X cmp ?a ?b with _ => _ end]] =>\n        rewrite (@compare_list_sym' X b a cmp cmp_sym); destruct (compare_list cmp b a)\n      end; ss.\n\n  Ltac comp_sym_tac :=\n    repeat\n      (try comp_sym floating_point.compare floating_point.compare_sym;\n       try comp_sym bop.compare bop.compare_sym;\n       try comp_sym fbop.compare fbop.compare_sym;\n       try comp_sym sz.compare sz.compare_sym;\n       try comp_sym ValueT.compare ValueT.compare_sym;\n       try comp_sym typ.compare typ.compare_sym;\n       try comp_sym bool.compare bool.compare_sym;\n\n       try comp_sym truncop.compare truncop.compare_sym;\n       try comp_sym extop.compare extop.compare_sym;\n       try comp_sym castop.compare castop.compare_sym;\n       try comp_sym bop.compare bop.compare_sym;\n       try comp_sym fbop.compare fbop.compare_sym;\n       try comp_sym cond.compare cond.compare_sym;\n       try comp_sym fcond.compare fcond.compare_sym;\n\n       try comp_sym_list ValueT.compare ValueT.compare_sym;\n       try comp_sym_list' const.compare const.compare_sym;\n       try comp_sym_list' bool.compare bool.compare_sym;\n       try comp_sym_list' sz_ValueT.compare sz_ValueT.compare_sym).\n  \n\n  Lemma compare_sym\n        x y\n    : <<SYM: compare y x = CompOpp (compare x y)>>.\n  Proof.\n    unfold compare, wrap_compare.\n    destruct x, y; simpl;\n      try (comp_sym_tac; congruence).\n    apply ValueT.compare_sym.\n  Qed.\n\n  Corollary compare_refl z:\n    compare z z = Eq.\n  Proof.\n    assert (compare z z = CompOpp (compare z z)).\n    { apply compare_sym. }\n    destruct (compare z z); ss.\n  Qed.\n\n  Ltac solve_leibniz_list' cmp cmp_l :=\n    repeat match goal with\n           | [H: compare_list cmp ?l1 ?l2 = Eq |- _] =>\n             apply (@compare_list_leibniz _ cmp cmp_l) in H; eauto\n           end; subst.\n\n  Ltac solve_leibniz' :=\n    solve_leibniz_base;\n    solve_leibniz_ typ.compare typ.compare_leibniz;\n    solve_leibniz_ const.compare const.compare_leibniz;\n    solve_leibniz_ ValueT.compare ValueT.compare_leibniz;\n    solve_leibniz_list' const.compare const.compare_leibniz;\n    solve_leibniz_list' sz_ValueT.compare sz_ValueT.compare_leibniz\n  .\n\n  Ltac finish_refl :=\n    unfold t, NW in *;\n    finish_refl_base;\n    finish_refl_ typ.compare typFacts.EOrigFacts.compare_refl;\n    finish_refl_ const.compare constFacts.EOrigFacts.compare_refl;\n    finish_refl_ ValueT.compare ValueTFacts.EOrigFacts.compare_refl;\n    finish_refl_ compare' compare_refl;\n    finish_refl_list t const const.compare const.compare_refl;\n    finish_refl_list t sz_ValueT.t sz_ValueT.compare sz_ValueTFacts.EOrigFacts.compare_refl;\n    try congruence\n  .\n\n  Lemma compare_leibniz\n        x y\n        (EQ: compare x y = Eq)\n    : x = y.\n  Proof.\n    unfold compare, wrap_compare in *.\n    destruct x; destruct y; ss;\n      try by des_ifs; solve_leibniz'.\n  Qed.\n\n  Ltac solve_leibniz :=\n    solve_leibniz';\n    \n    solve_leibniz_ compare' compare_leibniz;\n    solve_leibniz_list' compare' compare_leibniz\n  .\n\n  Ltac apply_trans_list cmp cmp_l cmp_r cmp_t :=\n    try match goal with\n        | [H1: compare_list cmp ?x ?y = ?c, H2: compare_list cmp ?y ?x = ?c |- _] =>\n          exploit (@compare_list_trans' _ cmp cmp_l cmp_r cmp_t c x y x); eauto; (idtac; []; i)\n        end;\n    try match goal with\n        | [H1: compare_list cmp ?x ?y = ?c, H2: compare_list cmp ?y ?z = ?c |- _] =>\n          exploit (@compare_list_trans' _ cmp cmp_l cmp_r cmp_t c x y z); eauto; (idtac; []; i)\n        end.\n\n  Ltac apply_trans :=\n    unfold NW in *;\n    apply_trans_base;\n    apply_trans_ typ.compare typ.compare_trans;\n    apply_trans_ const.compare const.compare_trans;\n    apply_trans_ ValueT.compare ValueT.compare_trans;\n\n    apply_trans_list const.compare const.compare_leibniz constFacts.EOrigFacts.compare_refl const.compare_trans;\n    apply_trans_list sz_ValueT.compare sz_ValueT.compare_leibniz sz_ValueTFacts.EOrigFacts.compare_refl sz_ValueT.compare_trans\n  .\n\n  Ltac l_des_ifs :=\n    clarify;\n    repeat \n      (match goal with \n       | |- context[match ?x with _ => _ end] =>\n         let H := fresh \"Heq\" in\n         destruct x as [] eqn:H; clarify\n       | H: context[ match ?x with _ => _ end ] |- _ =>\n         let H := fresh \"Heq\" in\n         destruct x as [] eqn:H; clarify\n       end; try congruence).\n\n  Lemma compare_trans\n        c x y z\n        (XY: compare x y = c)\n        (YZ: compare y z = c)\n    : <<XZ: compare x z = c>>.\n  Proof.\n    unfold compare, wrap_compare in *.\n    Time (destruct c, x, y; try discriminate;\n            destruct z; try discriminate; eauto);\n      abstract (simpl in *; des_ifs; solve_leibniz; apply_trans; finish_refl). (* 142 sec*)\n  Qed.\n\n  Definition get_valueTs (e: t): list ValueT.t :=\n    match e with\n      | (Expr.bop _ _ v1 v2) => [v1 ; v2]\n      | (Expr.fbop _ _ v1 v2) => [v1 ; v2]\n      | (Expr.extractvalue _ v _ _) => [v]\n      | (Expr.insertvalue _ v1 _ v2 _) => [v1 ; v2]\n      | (Expr.gep _ _ v vl _) => v :: (List.map snd vl)\n      | (Expr.trunc _ _ v _) => [v]\n      | (Expr.ext _ _ v _) => [v]\n      | (Expr.cast _ _ v _) => [v]\n      | (Expr.icmp _ _ v1 v2) => [v1 ; v2]\n      | (Expr.fcmp _ _ v1 v2) => [v1 ; v2]\n      | (Expr.select v1 _ v2 v3) => [v1 ; v2 ; v3]\n      | (Expr.value v) => [v]\n      | (Expr.load v _ _) => [v]\n    end.\n\n  Definition same_modulo_value (e1 e2:Expr.t): bool :=\n    match e1, e2 with\n    | Expr.bop b1 s1 v1 w1, Expr.bop b2 s2 v2 w2 =>\n      (bop_dec b1 b2)\n        && (sz_dec s1 s2)\n    | Expr.fbop fb1 fp1 v1 w1, Expr.fbop fb2 fp2 v2 w2 =>\n      (fbop_dec fb1 fb2)\n        && (floating_point_dec fp1 fp2)\n    | Expr.extractvalue t1 v1 lc1 u1, Expr.extractvalue t2 v2 lc2 u2 =>\n      (typ_dec t1 t2)\n        && (list_forallb2 const_eqb lc1 lc2)\n        && (typ_dec u1 u2)\n    | Expr.insertvalue t1 v1 t'1 v'1 lc1, Expr.insertvalue t2 v2 t'2 v'2 lc2 =>\n      (typ_dec t1 t2)\n        && (typ_dec t'1 t'2)\n        && (list_forallb2 const_eqb lc1 lc2)\n    | Expr.gep ib1 t1 v1 lsv1 u1, Expr.gep ib2 t2 v2 lsv2 u2 =>\n      (inbounds_dec ib1 ib2)\n        && (typ_dec t1 t2)\n        && (list_eq_dec sz_dec\n                        (List.map fst lsv1)\n                        (List.map fst lsv2))\n        && (typ_dec u1 u2)\n    | Expr.trunc top1 t1 v1 u1, Expr.trunc top2 t2 v2 u2 =>\n      (truncop_dec top1 top2)\n        && (typ_dec t1 t2)\n        && (typ_dec u1 u2)\n    | Expr.ext eop1 t1 v1 u1, Expr.ext eop2 t2 v2 u2 =>\n      (extop_dec eop1 eop2)\n        && (typ_dec t1 t2)\n        && (typ_dec u1 u2)\n    | Expr.cast cop1 t1 v1 u1, Expr.cast cop2 t2 v2 u2 =>\n      (castop_dec cop1 cop2)\n        && (typ_dec t1 t2)\n        && (typ_dec u1 u2)\n    | Expr.icmp c1 t1 v1 w1, Expr.icmp c2 t2 v2 w2  =>\n      (cond_dec c1 c2)\n        && (typ_dec t1 t2)\n    | Expr.fcmp fc1 fp1 v1 w1, Expr.fcmp fc2 fp2 v2 w2  =>\n      (fcond_dec fc1 fc2)\n        && (floating_point_dec fp1 fp2)\n    | Expr.select v1 t1 w1 z1, Expr.select v2 t2 w2 z2 =>\n      (typ_dec t1 t2)\n    | Expr.value v1, Expr.value v2 =>\n      true\n    | Expr.load v1 t1 a1, Expr.load v2 t2 a2 =>\n      (typ_dec t1 t2)\n        && (Decs.align_dec a1 a2)\n    | _, _ => false\n    end.\n\n  Definition get_idTs (e: t): list IdT.t :=\n    TODO.filter_map ValueT.get_idTs (get_valueTs e).\n\n  Definition map_valueTs (e: t) (f: ValueT.t -> ValueT.t): t :=\n    match e with\n    | (Expr.bop _blah _blah2 v1 v2) =>\n      Expr.bop _blah _blah2 (f v1) (f v2)\n    | (Expr.fbop _blah _blah2 v1 v2) =>\n      Expr.fbop _blah _blah2 (f v1) (f v2)\n    | (Expr.extractvalue _blah v _blah2 _blah3) =>\n      (Expr.extractvalue _blah (f v) _blah2 _blah3)\n    | (Expr.insertvalue _blah v1 _blah2 v2 _blah3) =>\n      (Expr.insertvalue _blah (f v1) _blah2 (f v2) _blah3)\n    | (Expr.gep _blah _blah2 v vl _blah3) =>\n      (Expr.gep _blah _blah2 (f v)\n                (List.map (fun x => (fst x, (f (snd x)))) vl) _blah3)\n    | (Expr.trunc _blah _blah2 v _blah3) =>\n      (Expr.trunc _blah _blah2 (f v) _blah3)\n    | (Expr.ext _blah _blah2 v _blah3) =>\n      (Expr.ext _blah _blah2 (f v) _blah3)\n    | (Expr.cast _blah _blah2 v _blah3) =>\n      (Expr.cast _blah _blah2 (f v) _blah3)\n    | (Expr.icmp _blah _blah2 v1 v2) =>\n      (Expr.icmp _blah _blah2 (f v1) (f v2))\n    | (Expr.fcmp _blah _blah2 v1 v2) =>\n      (Expr.fcmp _blah _blah2 (f v1) (f v2))\n    | (Expr.select v1 _blah v2 v3) =>\n      (Expr.select (f v1) _blah (f v2) (f v3))\n    | (Expr.value v) =>\n      (Expr.value (f v))\n    | (Expr.load v _blah _blah2) =>\n      (Expr.load (f v) _blah _blah2)\n    end.\n\n  Definition substitute (from: IdT.t) (to: ValueT.t) (body: t): t :=\n    (Expr.map_valueTs body (ValueT.substitute from to))\n  .\n\n  Definition is_load (e: t): bool :=\n    match e with\n    | Expr.load _ _ _ => true\n    | _ => false\n    end\n  .\n\nEnd Expr.\nHint Resolve Expr.eq_dec: EqDecDb.\nCoercion Expr.value: ValueT.t >-> Expr.t_.\n\nModule Expr_OT := Backport_Alt Expr.\nModule ExprSet := FSetAVLExtra Expr_OT.\n\nModule ExprPair <: AltUsual.\n  Include prod Expr Expr.\n  Definition eq_dec (x y:t): {x = y} + {x <> y}.\n  Proof.\n    apply prod_dec;\n      apply Expr.eq_dec.\n  Defined.\n\n  Definition get_idTs (ep: t): list IdT.t :=\n    (Expr.get_idTs ep.(fst))\n      ++ (Expr.get_idTs ep.(snd)).\nEnd ExprPair.\n\nModule ExprPairFacts := AltUsualFacts ExprPair.\n\nModule ExprPair_OT := Backport_Alt ExprPair.\nModule ExprPairSet.\n  Include FSetAVLExtra ExprPair_OT.\n\n  Definition clear_idt (idt: IdT.t) (t0: t): t :=\n    filter (fun xy => negb (list_inb IdT.eq_dec (ExprPair.get_idTs xy) idt)) t0\n  .\nEnd ExprPairSet.\n\nModule ExprPairSetFacts := FSetFactsExtra ExprPair_OT ExprPairSet.\n\n(* Ptr: alias related values *)\nModule Ptr <: AltUsual.\n  (* typ has the type of the 'pointer', not the type of the 'object'.\n     ex: %x = load i32* %y, align 4 <- (id y, typ_pointer (typ_int 32))\n                   ^^^^\n  *)\n  Include prod ValueT typ.\n\n  Definition eq_dec (x y:t): {x = y} + {x <> y}.\n  Proof.\n    apply prod_dec.\n    apply ValueT.eq_dec.\n    apply typ_dec.\n  Defined.\n\n  Definition get_idTs (p: t): option IdT.t :=\n    match p with\n    | (v,_) => ValueT.get_idTs v\n    end.\n\nEnd Ptr.\n\nModule Ptr_OT := Backport_Alt Ptr.\nModule PtrSet := FSetAVLExtra Ptr_OT.\nModule PtrSetFacts := FSetFactsExtra Ptr_OT PtrSet.\n\nLemma InA_equiv_eqs\n      X (eqa eqb : X -> X -> Prop)\n      (EQS_EQ: forall x y, eqa x y <-> eqb x y)\n  : forall a l, InA eqa a l <-> InA eqb a l.\nProof.\n  intros a l.\n  induction l; split; intro HIn; inv HIn;\n    try (by left; apply EQS_EQ; eauto);\n    try (by right; apply IHl; eauto).\nQed.\n\nLemma PtrSet_from_list_spec ps:\n  forall p, PtrSet.mem p (PtrSetFacts.from_list ps) <-> In p ps.\nProof.\n  i. rewrite PtrSetFacts.from_list_spec.\n  cut (InA (fun x y : Ptr.t => Ptr.compare x y = Eq) p ps\n       <-> InA eq p ps).\n  { intro EQUIV. rewrite EQUIV. apply InA_iff_In. }\n  apply InA_equiv_eqs.\n  i. split.\n  - apply Ptr.compare_leibniz.\n  - i. subst. apply PtrSet.E.eq_refl.\nQed.\n\nModule PtrPair <: AltUsual.\n  Include prod Ptr Ptr.\n  Definition eq_dec (x y:t): {x = y} + {x <> y}.\n  Proof.\n    apply prod_dec; apply Ptr.eq_dec.\n  Defined.\n\n  Definition get_idTs (pp: t): list IdT.t :=\n    (option_to_list (Ptr.get_idTs pp.(fst)))\n      ++ (option_to_list (Ptr.get_idTs pp.(snd))).\nEnd PtrPair.\nHint Resolve PtrPair.eq_dec: EqDecDb.\n\nModule PtrPair_OT := Backport_Alt PtrPair.\n\nModule PtrPairSet.\n  Include FSetAVLExtra PtrPair_OT.\n  Definition clear_idt (idt: IdT.t) (t0: t): t :=\n    filter (fun xy => negb (list_inb IdT.eq_dec (PtrPair.get_idTs xy) idt)) t0\n  .\n\nEnd PtrPairSet.\n\nModule PtrPairSetFacts := FSetFactsExtra PtrPair_OT PtrPairSet.\n\n\n\n(* TODO: Remove this after migrating yoonseung's Ords.v *)\nLtac solve_leibniz_ cmp CL :=\n  repeat match goal with\n         | [H:cmp ?a ?b = Eq |- _] => apply CL in H\n         end; subst.\n\nLtac solve_leibniz :=\n  solve_leibniz_ IdT.compare IdT.compare_leibniz;\n  solve_leibniz_ ValueT.compare ValueT.compare_leibniz;\n  solve_leibniz_ Ptr.compare Ptr.compare_leibniz;\n  solve_leibniz_ Expr.compare Expr.compare_leibniz;\n  solve_leibniz_ ValueTPair.compare ValueTPair.compare_leibniz;\n  solve_leibniz_ PtrPair.compare PtrPair.compare_leibniz;\n  solve_leibniz_ ExprPair.compare ExprPair.compare_leibniz\n.\n\nLtac solve_compat_bool := repeat red; ii; solve_leibniz; subst; eauto; ss.\n\nLtac finish_by_refl :=\n  try apply IdTSet.E.eq_refl;\n  try apply ValueTSet.E.eq_refl;\n  try apply PtrSet.E.eq_refl;\n  try apply ExprSet.E.eq_refl;\n  try apply ValueTPairSet.E.eq_refl;\n  try apply PtrPairSet.E.eq_refl;\n  try apply ExprPairSet.E.eq_refl\n.\n", "meta": {"author": "snu-sf", "repo": "crellvm", "sha": "668249b88756233f96b3ef21f12993501a348afc", "save_path": "github-repos/coq/snu-sf-crellvm", "path": "github-repos/coq/snu-sf-crellvm/crellvm-668249b88756233f96b3ef21f12993501a348afc/coq/def/Exprs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2279848609658756}}
{"text": "Require Import prosa.model.preemption.limited_preemptive.\nRequire Export prosa.model.task.preemption.parameters.\n\n(** * Task Model with Floating Non-Preemptive Regions *)\n\n(** In this file, we instantiate the specific task model of (usually)\n    preemptive tasks with \"floating\" non-preemptive regions, i.e., with jobs\n    that exhibit non-preemptive segments of bounded length at unpredictable\n    points during their execution.  *)\n\n(** ** Model Validity *)\n\n(** To begin with, we introduce requirements that the function\n    [task_max_nonpr_segment] must satisfy to be coherent with the floating\n    non-preemptive regions model. *)\nSection ValidModelWithFloatingNonpreemptiveRegions.\n\n  (** Consider any type of tasks ... *)\n  Context {Task : TaskType}.\n  (** ... with a bound on the maximum non-preemptive segment length ... *)\n  Context `{TaskMaxNonpreemptiveSegment Task}.\n\n  (**  ... and any type of limited-preemptive jobs associated with these tasks ... *)\n  Context {Job : JobType}.\n  Context `{JobTask Job Task}.\n  (** ... with execution costs and specific preemption points. *)\n  Context `{JobCost Job}.\n  Context `{JobPreemptionPoints Job}.\n\n  (** Consider any arrival sequence. *)\n  Variable arr_seq : arrival_sequence Job.\n\n  (** We require [task_max_nonpreemptive_segment (job_task j)] to be an upper\n      bound of the length of the maximum nonpreemptive segment of job [j]. *)\n  Definition job_respects_task_max_np_segment :=\n    forall (j : Job),\n      arrives_in arr_seq j ->\n      job_max_nonpreemptive_segment j <= task_max_nonpreemptive_segment (job_task j).\n\n  (** A model with floating nonpreemptive regions is valid if it is both valid\n      a the job level and jobs respect the upper bound of their task. *)\n  Definition valid_model_with_floating_nonpreemptive_regions :=\n    valid_limited_preemptions_job_model arr_seq /\\\n    job_respects_task_max_np_segment.\n\nEnd ValidModelWithFloatingNonpreemptiveRegions.\n\n(** ** Run-to-Completion Threshold *)\n\n(** In this section, we instantiate the task-level run-to-completion threshold\n    for the model with floating non-preemptive regions. *)\nSection TaskRTCThresholdFloatingNonPreemptiveRegions.\n\n  (** Consider any type of tasks with a WCET bound.*)\n  Context {Task : TaskType}.\n  Context `{TaskCost Task}.\n\n  (** In the model with floating non-preemptive regions, there is no static\n      information about the placement of preemption points in all jobs, i.e.,\n      it is impossible to predict when exactly a job will be preemptable. Thus,\n      the only safe run-to-completion threshold is [task cost]. *)\n  Global Program Instance fully_preemptive : TaskRunToCompletionThreshold Task :=\n    {\n      task_run_to_completion_threshold (tsk : Task) := task_cost tsk\n    }.\n\nEnd TaskRTCThresholdFloatingNonPreemptiveRegions.\n", "meta": {"author": "pointoflight", "repo": "prosa", "sha": "df7246392f27f32c760022b790f8c7aca11ff215", "save_path": "github-repos/coq/pointoflight-prosa", "path": "github-repos/coq/pointoflight-prosa/prosa-df7246392f27f32c760022b790f8c7aca11ff215/model/task/preemption/floating_nonpreemptive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2279848609658756}}
{"text": "From iris.heap_lang Require Export lifting notation.\nFrom iris.program_logic Require Export atomic.\nFrom iris.proofmode Require Import tactics.\nFrom iris.heap_lang Require Import proofmode notation.\nFrom iris.bi.lib Require Import fractional.\nSet Default Proof Using \"Type\".\n\n(** A general logically atomic interface for a heap. *)\nClass atomic_heap {Σ} `{!heapG Σ} := AtomicHeap {\n  (* -- operations -- *)\n  alloc : val;\n  load : val;\n  store : val;\n  cas : val;\n  (* -- predicates -- *)\n  mapsto (l : loc) (q: Qp) (v : val) : iProp Σ;\n  (* -- mapsto properties -- *)\n  mapsto_timeless l q v :> Timeless (mapsto l q v);\n  mapsto_fractional l v :> Fractional (λ q, mapsto l q v);\n  mapsto_as_fractional l q v :>\n    AsFractional (mapsto l q v) (λ q, mapsto l q v) q;\n  mapsto_agree l q1 q2 v1 v2 :> mapsto l q1 v1 -∗ mapsto l q2 v2 -∗ ⌜v1 = v2⌝;\n  (* -- operation specs -- *)\n  alloc_spec e v :\n    IntoVal e v → {{{ True }}} alloc e {{{ l, RET #l; mapsto l 1 v }}};\n  load_spec (l : loc) :\n    <<< ∀ (v : val) q, mapsto l q v >>> load #l @ ⊤ <<< mapsto l q v, RET v >>>;\n  store_spec (l : loc) (e : expr) (w : val) :\n    IntoVal e w →\n    <<< ∀ v, mapsto l 1 v >>> store (#l, e) @ ⊤\n    <<< mapsto l 1 w, RET #() >>>;\n  (* This spec is slightly weaker than it could be: It is sufficient for [w1]\n  *or* [v] to be unboxed.  However, by writing it this way the [val_is_unboxed]\n  is outside the atomic triple, which makes it much easier to use -- and the\n  spec is still good enough for all our applications. *)\n  cas_spec (l : loc) (e1 e2 : expr) (w1 w2 : val) :\n    IntoVal e1 w1 → IntoVal e2 w2 → val_is_unboxed w1 →\n    <<< ∀ v, mapsto l 1 v >>> cas (#l, e1, e2) @ ⊤\n    <<< if decide (v = w1) then mapsto l 1 w2 else mapsto l 1 v,\n        RET #(if decide (v = w1) then true else false) >>>;\n}.\nArguments atomic_heap _ {_}.\n\n(** Notation for heap primitives, in a module so you can import it separately. *)\nModule notation.\nNotation \"l ↦{ q } v\" := (mapsto l q v)\n  (at level 20, q at level 50, format \"l  ↦{ q }  v\") : bi_scope.\nNotation \"l ↦ v\" := (mapsto l 1 v) (at level 20) : bi_scope.\n\nNotation \"l ↦{ q } -\" := (∃ v, l ↦{q} v)%I\n  (at level 20, q at level 50, format \"l  ↦{ q }  -\") : bi_scope.\nNotation \"l ↦ -\" := (l ↦{1} -)%I (at level 20) : bi_scope.\n\nNotation \"'ref' e\" := (alloc e) : expr_scope.\nNotation \"! e\" := (load e) : expr_scope.\nNotation \"e1 <- e2\" := (store (e1, e2)%E) : expr_scope.\n\nNotation CAS e1 e2 e3 := (cas (e1, e2, e3)%E).\n\nEnd notation.\n\n(** Proof that the primitive physical operations of heap_lang satisfy said interface. *)\nDefinition primitive_alloc : val :=\n  λ: \"v\", ref \"v\".\nDefinition primitive_load : val :=\n  λ: \"l\", !\"l\".\nDefinition primitive_store : val :=\n  λ: \"p\", (Fst \"p\") <- (Snd \"p\").\nDefinition primitive_cas : val :=\n  λ: \"p\", CAS (Fst (Fst \"p\")) (Snd (Fst \"p\")) (Snd \"p\").\n\nSection proof.\n  Context `{!heapG Σ}.\n\n  Lemma primitive_alloc_spec e v :\n    IntoVal e v → {{{ True }}} primitive_alloc e {{{ l, RET #l; l ↦ v }}}.\n  Proof.\n    iIntros (<- Φ) \"_ HΦ\". wp_let. wp_alloc l. iApply \"HΦ\". done.\n  Qed.\n\n  Lemma primitive_load_spec (l : loc) :\n    <<< ∀ (v : val) q, l ↦{q} v >>> primitive_load #l @ ⊤\n    <<< l ↦{q} v, RET v >>>.\n  Proof.\n    iIntros (Q Φ) \"? AU\". wp_let.\n    iMod \"AU\" as (v q) \"[H↦ [_ Hclose]]\".\n    wp_load. iMod (\"Hclose\" with \"H↦\") as \"HΦ\". by iApply \"HΦ\".\n  Qed.\n\n  Lemma primitive_store_spec (l : loc) (e : expr) (w : val) :\n    IntoVal e w →\n    <<< ∀ v, l ↦ v >>> primitive_store (#l, e) @ ⊤\n    <<< l ↦ w, RET #() >>>.\n  Proof.\n    iIntros (<- Q Φ) \"? AU\". wp_let. wp_proj. wp_proj.\n    iMod \"AU\" as (v) \"[H↦ [_ Hclose]]\".\n    wp_store. iMod (\"Hclose\" with \"H↦\") as \"HΦ\". by iApply \"HΦ\".\n  Qed.\n\n  Lemma primitive_cas_spec (l : loc) e1 e2 (w1 w2 : val) :\n    IntoVal e1 w1 → IntoVal e2 w2 → val_is_unboxed w1 →\n    <<< ∀ (v : val), l ↦ v >>>\n      primitive_cas (#l, e1, e2) @ ⊤\n    <<< if decide (v = w1) then l ↦ w2 else l ↦ v,\n        RET #(if decide (v = w1) then true else false) >>>.\n  Proof.\n    iIntros (<- <- ? Q Φ) \"? AU\". wp_let. repeat wp_proj.\n    iMod \"AU\" as (v) \"[H↦ [_ Hclose]]\".\n    destruct (decide (v = w1)) as [<-|Hv]; [wp_cas_suc|wp_cas_fail];\n    iMod (\"Hclose\" with \"H↦\") as \"HΦ\"; by iApply \"HΦ\".\n  Qed.\nEnd proof.\n\n(* NOT an instance because users should choose explicitly to use it\n     (using [Explicit Instance]). *)\nDefinition primitive_atomic_heap `{!heapG Σ} : atomic_heap Σ :=\n  {| alloc_spec := primitive_alloc_spec;\n     load_spec := primitive_load_spec;\n     store_spec := primitive_store_spec;\n     cas_spec := primitive_cas_spec;\n     mapsto_agree := gen_heap.mapsto_agree  |}.\n", "meta": {"author": "JasonGross", "repo": "iris-coq", "sha": "f891015e2ab48926cec9618b0eadf0c0fec9ba1b", "save_path": "github-repos/coq/JasonGross-iris-coq", "path": "github-repos/coq/JasonGross-iris-coq/iris-coq-f891015e2ab48926cec9618b0eadf0c0fec9ba1b/theories/heap_lang/lib/atomic_heap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2279848609658756}}
{"text": "(** Defines an RA on lists whose composition is only defined when one operand is\na prefix of the other. The result is the longer list.\nIn particular, the core is the identity function for all elements. *)\nFrom iris.algebra Require Export agree list gmap updates.\nFrom iris.algebra Require Import local_updates proofmode_classes.\nFrom iris.prelude Require Import options.\n\nDefinition max_prefix_list (A : Type) := gmap nat (agree A).\nDefinition max_prefix_listR (A : ofe) := gmapUR nat (agreeR A).\nDefinition max_prefix_listUR (A : ofe) := gmapUR nat (agreeR A).\n\nDefinition to_max_prefix_list {A} (l : list A) : gmap nat (agree A) :=\n  to_agree <$> map_seq 0 l.\nGlobal Instance: Params (@to_max_prefix_list) 1 := {}.\nTypeclasses Opaque to_max_prefix_list.\n\nSection max_prefix_list.\n  Context {A : ofe}.\n  Implicit Types l : list A.\n\n  Global Instance to_max_prefix_list_ne : NonExpansive (@to_max_prefix_list A).\n  Proof. solve_proper. Qed.\n  Global Instance to_max_prefix_list_proper :\n    Proper ((≡) ==> (≡)) (@to_max_prefix_list A).\n  Proof. solve_proper. Qed.\n  Global Instance to_max_prefix_list_dist_inj n :\n    Inj (dist n) (dist n) (@to_max_prefix_list A).\n  Proof.\n    rewrite /to_max_prefix_list. intros l1 l2 Hl. apply list_dist_lookup=> i.\n    move: (Hl i). rewrite !lookup_fmap !lookup_map_seq Nat.sub_0_r.\n    rewrite !option_guard_True; [|lia..].\n    destruct (l1 !! i), (l2 !! i); inversion_clear 1;\n      constructor; by apply (inj to_agree).\n  Qed.\n  Global Instance to_max_prefix_list_inj : Inj (≡) (≡) (@to_max_prefix_list A).\n  Proof.\n    intros l1 l2. rewrite !equiv_dist=> ? n. by apply (inj to_max_prefix_list).\n  Qed.\n\n  Global Instance mono_list_lb_core_id (m : max_prefix_list A) : CoreId m := _.\n\n  Lemma to_max_prefix_list_valid l : ✓ to_max_prefix_list l.\n  Proof.\n    intros i. rewrite /to_max_prefix_list lookup_fmap.\n    by destruct (map_seq 0 l !! i).\n  Qed.\n  Lemma to_max_prefix_list_validN n l : ✓{n} to_max_prefix_list l.\n  Proof. apply cmra_valid_validN, to_max_prefix_list_valid. Qed.\n\n  Local Lemma to_max_prefix_list_app l1 l2 :\n    to_max_prefix_list (l1 ++ l2) ≡\n    to_max_prefix_list l1 ⋅ (to_agree <$> map_seq (length l1) l2).\n  Proof.\n    rewrite /to_max_prefix_list map_seq_app=> i /=. rewrite lookup_op !lookup_fmap.\n    destruct (map_seq 0 l1 !! i) as [x|] eqn:Hl1; simpl; last first.\n    { by rewrite lookup_union_r // left_id. }\n    rewrite (lookup_union_Some_l _ _ _ x) //=.\n    assert (map_seq (M:=gmap nat A) (length l1) l2 !! i = None) as ->.\n    { apply lookup_map_seq_None.\n      apply lookup_map_seq_Some in Hl1 as [_ ?%lookup_lt_Some]. lia. }\n    by rewrite /= right_id.\n  Qed.\n\n  Lemma to_max_prefix_list_op_l l1 l2 :\n    l1 `prefix_of` l2 →\n    to_max_prefix_list l1 ⋅ to_max_prefix_list l2 ≡ to_max_prefix_list l2.\n  Proof. intros [l ->]. by rewrite to_max_prefix_list_app assoc -core_id_dup. Qed.\n  Lemma to_max_prefix_list_op_r l1 l2 :\n    l1 `prefix_of` l2 →\n    to_max_prefix_list l2 ⋅ to_max_prefix_list l1 ≡ to_max_prefix_list l2.\n  Proof. intros. by rewrite comm to_max_prefix_list_op_l. Qed.\n\n  Lemma max_prefix_list_included_includedN (ml1 ml2 : max_prefix_list A) :\n    ml1 ≼ ml2 ↔ ∀ n, ml1 ≼{n} ml2.\n  Proof.\n    split; [intros; by apply: cmra_included_includedN|].\n    intros Hincl. exists ml2. apply equiv_dist=> n. destruct (Hincl n) as [l ->].\n    by rewrite assoc -core_id_dup.\n  Qed.\n\n  Local Lemma to_max_prefix_list_includedN_aux n l1 l2 :\n    to_max_prefix_list l1 ≼{n} to_max_prefix_list l2 →\n    l2 ≡{n}≡ l1 ++ drop (length l1) l2.\n  Proof.\n    rewrite lookup_includedN=> Hincl. apply list_dist_lookup=> i.\n    rewrite lookup_app. move: (Hincl i).\n    rewrite /to_max_prefix_list !lookup_fmap !lookup_map_seq Nat.sub_0_r.\n    rewrite !option_guard_True; [|lia..].\n    rewrite option_includedN_total fmap_None.\n    intros [Hi|(?&?&(a2&->&->)%fmap_Some&(a1&->&->)%fmap_Some&Ha)].\n    - rewrite lookup_drop Hi. apply lookup_ge_None in Hi. f_equiv; lia.\n    - f_equiv. symmetry. by apply to_agree_includedN.\n  Qed.\n  Lemma to_max_prefix_list_includedN n l1 l2 :\n    to_max_prefix_list l1 ≼{n} to_max_prefix_list l2 ↔ ∃ l, l2 ≡{n}≡ l1 ++ l.\n  Proof.\n    split.\n    - intros. eexists. by apply to_max_prefix_list_includedN_aux.\n    - intros [l ->]. rewrite to_max_prefix_list_app. apply: cmra_includedN_l.\n  Qed.\n  Lemma to_max_prefix_list_included l1 l2 :\n    to_max_prefix_list l1 ≼ to_max_prefix_list l2 ↔ ∃ l, l2 ≡ l1 ++ l.\n  Proof.\n    split.\n    - intros. eexists. apply equiv_dist=> n.\n      apply to_max_prefix_list_includedN_aux. by apply: cmra_included_includedN.\n    - intros [l ->]. rewrite to_max_prefix_list_app. apply: cmra_included_l.\n  Qed.\n  Lemma to_max_prefix_list_included_L `{!LeibnizEquiv A} l1 l2 :\n    to_max_prefix_list l1 ≼ to_max_prefix_list l2 ↔ l1 `prefix_of` l2.\n  Proof. rewrite to_max_prefix_list_included /prefix. naive_solver. Qed.\n\n  Local Lemma to_max_prefix_list_op_validN_aux n l1 l2 :\n    length l1 ≤ length l2 →\n    ✓{n} (to_max_prefix_list l1 ⋅ to_max_prefix_list l2) →\n    l2 ≡{n}≡ l1 ++ drop (length l1) l2.\n  Proof.\n    intros Hlen Hvalid. apply list_dist_lookup=> i. move: (Hvalid i).\n    rewrite /to_max_prefix_list lookup_op !lookup_fmap !lookup_map_seq Nat.sub_0_r.\n    rewrite !option_guard_True; [|lia..].\n    intros ?. rewrite lookup_app.\n    destruct (l1 !! i) as [x1|] eqn:Hi1, (l2 !! i) as [x2|] eqn:Hi2; simpl in *.\n    - f_equiv. symmetry. by apply to_agree_op_validN.\n    - apply lookup_lt_Some in Hi1; apply lookup_ge_None in Hi2. lia.\n    - apply lookup_ge_None in Hi1. rewrite lookup_drop -Hi2. f_equiv; lia.\n    - apply lookup_ge_None in Hi1. rewrite lookup_drop -Hi2. f_equiv; lia.\n  Qed.\n  Lemma to_max_prefix_list_op_validN n l1 l2 :\n    ✓{n} (to_max_prefix_list l1 ⋅ to_max_prefix_list l2) ↔\n    (∃ l, l2 ≡{n}≡ l1 ++ l) ∨ (∃ l, l1 ≡{n}≡ l2 ++ l).\n  Proof.\n    split.\n    - destruct (decide (length l1 ≤ length l2)).\n      + left. eexists. by eapply to_max_prefix_list_op_validN_aux.\n      + right. eexists. eapply to_max_prefix_list_op_validN_aux; [lia|by rewrite comm].\n    - intros [[l ->]|[l ->]].\n      + rewrite to_max_prefix_list_op_l; last by apply prefix_app_r.\n        apply to_max_prefix_list_validN.\n      + rewrite to_max_prefix_list_op_r; last by apply prefix_app_r.\n        apply to_max_prefix_list_validN.\n  Qed.\n  Lemma to_max_prefix_list_op_valid l1 l2 :\n    ✓ (to_max_prefix_list l1 ⋅ to_max_prefix_list l2) ↔\n    (∃ l, l2 ≡ l1 ++ l) ∨ (∃ l, l1 ≡ l2 ++ l).\n  Proof.\n    split.\n    - destruct (decide (length l1 ≤ length l2)).\n      + left. eexists. apply equiv_dist=> n'.\n        by eapply to_max_prefix_list_op_validN_aux, cmra_valid_validN.\n      + right. eexists. apply equiv_dist=> n'.\n        by eapply to_max_prefix_list_op_validN_aux,\n          cmra_valid_validN; [lia|by rewrite comm].\n    - intros [[l ->]|[l ->]].\n      + rewrite to_max_prefix_list_op_l; last by apply prefix_app_r.\n        apply to_max_prefix_list_valid.\n      + rewrite to_max_prefix_list_op_r; last by apply prefix_app_r.\n        apply to_max_prefix_list_valid.\n  Qed.\n  Lemma to_max_prefix_list_op_valid_L `{!LeibnizEquiv A} l1 l2 :\n    ✓ (to_max_prefix_list l1 ⋅ to_max_prefix_list l2) ↔\n    l1 `prefix_of` l2 ∨ l2 `prefix_of` l1.\n  Proof. rewrite to_max_prefix_list_op_valid /prefix. naive_solver. Qed.\n\n  Lemma max_prefix_list_local_update l1 l2 :\n    l1 `prefix_of` l2 →\n    (to_max_prefix_list l1, to_max_prefix_list l1) ~l~>\n      (to_max_prefix_list l2, to_max_prefix_list l2).\n  Proof.\n    intros [l ->]. rewrite to_max_prefix_list_app (comm _ (to_max_prefix_list l1)).\n    apply op_local_update=> n _. rewrite comm -to_max_prefix_list_app.\n    apply to_max_prefix_list_validN.\n  Qed.\nEnd max_prefix_list.\n\nDefinition max_prefix_listURF (F : oFunctor) : urFunctor :=\n  gmapURF nat (agreeRF F).\n\nGlobal Instance max_prefix_listURF_contractive F :\n  oFunctorContractive F → urFunctorContractive (max_prefix_listURF F).\nProof. apply _. Qed.\n\nDefinition max_prefix_listRF (F : oFunctor) : rFunctor :=\n  gmapRF nat (agreeRF F).\n\nGlobal Instance max_prefix_listRF_contractive F :\n  oFunctorContractive F → rFunctorContractive (max_prefix_listRF F).\nProof. apply _. Qed.\n", "meta": {"author": "amintimany", "repo": "iris", "sha": "03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1", "save_path": "github-repos/coq/amintimany-iris", "path": "github-repos/coq/amintimany-iris/iris-03eaffa3b28bffc561b93f30a3ba40bab8ae1fd1/iris/algebra/max_prefix_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.22798486096587559}}
{"text": "Require Import AutoSep Wrap StringOps Malloc ArrayOps Buffers Bags.\nRequire Import SinglyLinkedList ListSegment RelDb.\n\nSet Implicit Arguments.\n\nLocal Hint Extern 1 (@eq W _ _) => words.\n\n\n(** * Inserting into a table *)\n\nOpaque mult.\nLocal Infix \";;\" := SimpleSeq : SP_scope.\n\nSection Insert.\n  Variable A : Type.\n  Variable invPre : A -> vals -> HProp.\n  Variable invPost : A -> vals -> W -> HProp.\n\n  Variable tptr : W.\n  Variable sch : schema.\n  Variable bufSize : W.\n\n  (* \"WHERE\" clause *)\n  Variable es : list exp.\n\n  (* Precondition and postcondition *)\n  Definition invar :=\n    Al a : A, Al bs,\n    PRE[V] array8 bs (V \"buf\") * table sch tptr * mallocHeap 0\n      * [| length bs = wordToNat (V \"len\") |] * [| inputOk V es |] * invPre a V\n    POST[R] array8 bs (V \"buf\") * invPost a V R.\n\n  (* Write the value of an expression into a new row's buffer. *)\n  Definition writeExp (col : nat) (e : exp) : chunk :=\n    match e with\n      | Const s => StringWrite \"ibuf\" \"ilen\" \"ipos\" \"overflowed\" s\n        (fun (p : list B * A) V => array8 (fst p) (V \"buf\") * mallocHeap 0 * table sch tptr\n          * Ex cols, (V \"row\" ==*> V \"ibuf\", V \"ilen\") * array (posl cols) (V \"row\" ^+ $8)\n          * array (lenl cols) (V \"row\" ^+ $8 ^+ $(length sch * 4))\n          * [| length (fst p) = wordToNat (V \"len\") |] * [| length cols = length sch |]\n          * [| V \"row\" <> 0 |] * [| freeable (V \"row\") (2 + length sch + length sch) |]\n          * [| V \"ibuf\" <> 0 |] * [| freeable8 (V \"ibuf\") (wordToNat (V \"ilen\")) |]\n          * [| inBounds (V \"ilen\") (firstn col cols) |] * [| inputOk V es |] * invPre (snd p) V)%Sep\n        (fun _ (p : list B * A) V R => array8 (fst p) (V \"buf\") * invPost (snd p) V R)%Sep\n      | Input start len =>\n        \"tmp\" <- \"ilen\" - \"ipos\";;\n        If (\"tmp\" < len) {\n        \"overflowed\" <- 1\n        } else {\n          Call \"array8\"!\"copy\"(\"ibuf\", \"ipos\", \"buf\", start, len)\n          [Al a : A, Al bs, Al bsI,\n            PRE[V] array8 bs (V \"buf\") * table sch tptr\n              * [| V \"ipos\" <= V \"ilen\" |]%word\n              * array8 bsI (V \"ibuf\") * [| length bsI = wordToNat (V \"ilen\") |] * [| V \"ibuf\" <> 0 |]\n              * [| freeable8 (V \"ibuf\") (wordToNat (V \"ilen\")) |]\n              * Ex cols, (V \"row\" ==*> V \"ibuf\", V \"ilen\") * array (posl cols) (V \"row\" ^+ $8)\n              * array (lenl cols) (V \"row\" ^+ $8 ^+ $(length sch * 4))\n              * [| length bs = wordToNat (V \"len\") |] * [| length cols = length sch |]\n              * [| V \"row\" <> 0 |] * [| freeable (V \"row\") (2 + length sch + length sch) |]\n              * [| V \"ibuf\" <> 0 |] * [| freeable8 (V \"ibuf\") (wordToNat (V \"ilen\")) |]\n              * [| inBounds (V \"ilen\") (firstn col cols) |] * [| inputOk V es |]\n              * [| V len <= V \"ilen\" ^- V \"ipos\" |]%word\n              * invPre a V * mallocHeap 0\n            POST[R] array8 bs (V \"buf\") * invPost a V R];;\n          \"ipos\" <- \"ipos\" + len\n        }\n    end%SP.\n\n  Definition winv' (col : nat) :=\n    Al a : A, Al bs, Al bsI,\n      PRE[V] array8 bs (V \"buf\") * table sch tptr * mallocHeap 0\n        * array8 bsI (V \"ibuf\") * [| length bsI = wordToNat (V \"ilen\") |]\n        * [| V \"ipos\" <= V \"ilen\" |]\n        * Ex cols, (V \"row\" ==*> V \"ibuf\", V \"ilen\") * array (posl cols) (V \"row\" ^+ $8)\n        * array (lenl cols) (V \"row\" ^+ $8 ^+ $(length sch * 4))\n        * [| length bs = wordToNat (V \"len\") |] * [| length cols = length sch |]\n        * [| V \"row\" <> 0 |] * [| freeable (V \"row\") (2 + length sch + length sch) |]\n        * [| V \"ibuf\" <> 0 |] * [| freeable8 (V \"ibuf\") (wordToNat (V \"ilen\")) |]\n        * [| inBounds (V \"ilen\") (firstn col cols) |] * [| inputOk V es |] * invPre a V\n      POST[R] array8 bs (V \"buf\") * invPost a V R.\n\n  Definition winv (col : nat) := winv' col true (fun w => w).\n\n  Fixpoint writeExps (col : nat) (es : list exp) {struct es} : chunk :=\n    match es with\n      | nil => Skip\n      | e :: es' =>\n        (* Save the current position as the start of the current column. *)\n        \"tmp\" <- \"row\" + 8;;\n        \"tmp\" + (4 * col)%nat *<- \"ipos\";;\n\n        (* Check if the current item is small enough to fit in the buffer. *)\n        \"tmp\" <- \"ilen\" - \"ipos\";;\n        If (\"tmp\" < lengthOf e) {\n          (* It doesn't fit.  Save the \"safe\" length 0.  [writeExp] will set \"overflowed\" later. *)\n          \"tmp\" <- \"row\" + 8;;\n          \"tmp\" <- \"tmp\" + (length sch * 4)%nat;;\n          \"tmp\" + (4 * col)%nat *<- 0\n        } else {\n          (* Good, it fits.  Save the proper length. *)\n          \"tmp\" <- \"row\" + 8;;\n          \"tmp\" <- \"tmp\" + (length sch * 4)%nat;;\n          \"tmp\" + (4 * col)%nat *<- lengthOf e\n        };;\n        Assert [winv' (S col)];;\n        writeExp (S col) e;;\n        writeExps (S col) es'\n    end%SP.\n\n  Definition Insert' : chunk := (\n    \"ibuf\" <-- Call \"buffers\"!\"bmalloc\"(bufSize)\n    [Al a : A, Al bs,\n      PRE[V, R] R =?>8 (wordToNat bufSize * 4) * [| R <> 0 |] * [| freeable R (wordToNat bufSize) |]\n        * array8 bs (V \"buf\") * table sch tptr * mallocHeap 0\n        * [| length bs = wordToNat (V \"len\") |] * [| inputOk V es |] * invPre a V\n      POST[R'] array8 bs (V \"buf\") * invPost a V R'];;\n\n    \"row\" <-- Call \"malloc\"!\"malloc\"(0, (2 + length sch + length sch)%nat)\n    [Al a : A, Al bs, Al bsI,\n      PRE[V, R] array8 bsI (V \"ibuf\") * [| length bsI = (wordToNat bufSize * 4)%nat |] * [| V \"ibuf\" <> 0 |]\n        * [| freeable (V \"ibuf\") (wordToNat bufSize) |]\n        * R =?> (2 + length sch + length sch)%nat * [| R <> 0 |]\n        * [| freeable R (2 + length sch + length sch)%nat |]\n        * array8 bs (V \"buf\") * table sch tptr * mallocHeap 0\n        * [| length bs = wordToNat (V \"len\") |] * [| inputOk V es |] * invPre a V\n      POST[R'] array8 bs (V \"buf\") * invPost a V R'];;\n\n    \"row\" *<- \"ibuf\";;\n    \"ipos\" <- 0;;\n    \"ilen\" <- (4 * bufSize)%word;;\n    \"row\"+4 *<- \"ilen\";;\n\n    Note [expand_allocated 8];;\n\n    writeExps O es;;\n\n    \"tmp\" <-- Call \"malloc\"!\"malloc\"(0, 2)\n    [Al a : A, Al bs,\n      PRE[V, R] R =?> 2 * [| R <> 0 |] * [| freeable R 2 |]\n        * row sch (V \"row\") * array8 bs (V \"buf\") * table sch tptr * mallocHeap 0\n        * [| length bs = wordToNat (V \"len\") |] * [| inputOk V es |] * invPre a V\n      POST[R'] array8 bs (V \"buf\") * invPost a V R'];;\n\n    \"tmp\" *<- \"row\";;\n    \"tmp\"+4 *<- $[tptr];;\n    tptr *<- \"tmp\"\n  )%SP.\n\n  Section writeExps_correct.\n    Variable mn : string.\n    Variable im : LabelMap.t assert.\n    Variable H : importsGlobal im.\n    Variable ns : list string.\n    Variable res : nat.\n\n    Hypothesis not_rp : ~In \"rp\" ns.\n    Hypothesis included : incl baseVars ns.\n    Hypothesis reserved : (res >= 10)%nat.\n    Hypothesis wellFormed : wfExps ns es.\n\n    Hypothesis weakenPre : (forall a V V', (forall x, x <> \"ibuf\" -> x <> \"row\" -> x <> \"ilen\" -> x <> \"tmp\"\n      -> x <> \"ipos\" -> x <> \"overflowed\" -> sel V x = sel V' x)\n    -> invPre a V ===> invPre a V').\n\n    Hypothesis weakenPost : (forall a V V' R, (forall x, x <> \"ibuf\" -> x <> \"row\" -> x <> \"ilen\" -> x <> \"tmp\"\n      -> x <> \"ipos\" -> x <> \"overflowed\" -> sel V x = sel V' x)\n    -> invPost a V R = invPost a V' R).\n\n    Hypothesis copy : \"array8\"!\"copy\" ~~ im ~~> ArrayOps.copyS.\n\n    Lemma writeExp_correct_vcs : forall e col pre,\n      wfExp ns e\n      -> In e es\n      -> (forall specs st,\n        interp specs (pre st)\n        -> interp specs (winv col ns res st))\n      -> vcs (VerifCond (toCmd (writeExp col e) mn (im := im) H ns res pre)).\n      destruct e; wrap0.\n\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n      v.\n    Qed.\n\n    Lemma writeExp_correct_post : forall e col pre,\n      wfExp ns e\n      -> In e es\n      -> (forall specs st,\n        interp specs (pre st)\n        -> interp specs (winv col ns res st))\n      -> forall specs st,\n        interp specs (Postcondition (toCmd (writeExp col e) mn (im := im) H ns res pre) st)\n        -> interp specs (winv col ns res st).\n      destruct e; wrap0.\n\n      v.\n      v.\n      v.\n    Qed.\n\n    Hypothesis length_es : length es = length sch.\n    Hypothesis goodSize_sch : goodSize (length sch).\n\n    Ltac split_IH := intros;\n      match goal with\n        | [ IH : forall pre : settings * state -> PropX _ _, _ |- _ ] =>\n          generalize (fun a b c d e => proj1 (IH a b c d e));\n            generalize (fun a b c d e => proj2 (IH a b c d e));\n              clear IH; intros\n      end;\n      match goal with\n        | [ H : incl (_ :: _) _ |- _ ] => apply incl_peel in H; destruct H\n      end.\n\n    Ltac basic_eauto :=\n      match goal with\n        | [ |- forall x, _ ] => idtac\n        | [ |- Logic.ex _ ] => idtac\n        | _ => simpl in *; eauto\n      end.\n\n    Lemma inBounds_move : forall ilen n m ls,\n      inBounds ilen (firstn (S (n - S m)) ls)\n      -> (S m <= n)%nat\n      -> inBounds ilen (firstn (n - m) ls).\n      intros; replace (n - m) with (S (n - S m)) by omega; auto.\n    Qed.\n\n    Hint Immediate inBounds_move.\n\n    Lemma inBounds_wiggle : forall ilen n m col ls,\n      inBounds ilen (firstn m ls)\n      -> col = m - S n\n      -> (S n <= m)%nat\n      -> inBounds ilen (match ls with nil => nil | x :: ls' => x :: firstn (n + col) ls' end).\n      intros; subst; replace m with (S (n + (m - S n))) in * |- by omega; auto.\n    Qed.\n\n    Hint Immediate inBounds_wiggle.\n\n    Hint Rewrite Minus.le_plus_minus_r using (simpl in *; omega) : sepFormula.\n\n    Ltac use_IH :=\n      match goal with\n        | [ col := ?E |- _ ] =>\n          match goal with\n            | [ |- appcontext[writeExps (S col)] ] =>\n              change (writeExps (S col)) with (writeExps (S E))\n          end; rewrite moveS by assumption;\n          match goal with\n            | [ H : forall x : settings * state -> PropX _ _, _ |- _ ] =>\n              apply H; basic_eauto\n          end\n\n        | [ H : interp _ (Postcondition (toCmd (writeExps (S ?col) _) _ _ _ _ _) _),\n            H' : forall a, wfExps _ _ -> _ |- _ ] =>\n          unfold col in H; rewrite moveS in H by (simpl in *; omega);\n            eapply H' in H; basic_eauto\n\n        | _ => eapply writeExp_correct_vcs; basic_eauto\n        | [ H : interp _ (Postcondition _ _) |- _ ] => eapply writeExp_correct_post in H; basic_eauto\n      end; pre.\n\n    Ltac we := repeat use_IH; t; my_descend.\n    Ltac swe := solve [ we ].\n    Ltac awe := abstract we.\n\n    Lemma writeExps_correct : forall es0 pre,\n      wfExps ns es0\n      -> incl es0 es\n      -> (length es0 <= length es)%nat\n      -> let col := length es - length es0 in\n        (forall specs st,\n          interp specs (pre st)\n          -> interp specs (winv col ns res st))\n        -> vcs (VerifCond (toCmd (writeExps col es0) mn (im := im) H ns res pre))\n        /\\ (forall specs st,\n          interp specs (Postcondition (toCmd (writeExps col es0) mn (im := im) H ns res pre) st)\n          -> interp specs (winv (length es0 + col) ns res st)).\n      induction es0.\n\n      wrap0.\n\n      split_IH.\n      wrap0.\n      wrap0.\n\n      awe.\n      awe.\n      awe.\n      awe.\n      awe.\n      awe.\n      awe.\n      awe.\n      awe.\n      awe.\n      awe.\n      awe.\n      awe.\n      awe.\n      awe.\n    Qed.\n  End writeExps_correct.\n\n  Notation InsertVcs := (fun im ns res =>\n    (~In \"rp\" ns) :: incl baseVars ns\n    :: (forall a V V', (forall x, x <> \"ibuf\" -> x <> \"row\" -> x <> \"ilen\" -> x <> \"tmp\"\n      -> x <> \"ipos\" -> x <> \"overflowed\" -> sel V x = sel V' x)\n      -> invPre a V ===> invPre a V')\n    :: (forall a V V' R, (forall x, x <> \"ibuf\" -> x <> \"row\" -> x <> \"ilen\" -> x <> \"tmp\"\n      -> x <> \"ipos\" -> x <> \"overflowed\" -> sel V x = sel V' x)\n      -> invPost a V R = invPost a V' R)\n    :: (res >= 10)%nat\n    :: (bufSize >= natToW 2)\n    :: goodSize (2 + length sch + length sch)\n    :: goodSize (4 * wordToNat bufSize)\n    :: wfExps ns es\n    :: \"buffers\"!\"bmalloc\" ~~ im ~~> bmallocS\n    :: \"malloc\"!\"malloc\" ~~ im ~~> mallocS\n    :: \"array8\"!\"copy\" ~~ im ~~> ArrayOps.copyS\n    :: (length es = length sch)\n    :: goodSize (length sch)\n    :: nil).\n\n  Hint Immediate incl_refl.\n\n  Require Import Div2.\n\n  Lemma div2_double : forall n, div2 (n + n) = n.\n    apply div2_double'.\n  Qed.\n\n  Hint Rewrite div2_double : sepFormula.\n\n  Lemma four_duh : forall n,\n    goodSize (4 * wordToNat bufSize)\n    -> n = wordToNat bufSize * 4\n    -> n = wordToNat (natToW 4 ^* bufSize).\n    intros; subst.\n    rewrite wordToNat_wmult.\n    change (wordToNat (natToW 4)) with 4; omega.\n    auto.\n  Qed.\n\n  Hint Immediate four_duh.\n\n  Lemma inBounds_nil : forall n, inBounds n nil.\n    intros; hnf; auto.\n  Qed.\n\n  Hint Immediate inBounds_nil.\n\n  Lemma firstn_all : forall A (ls : list A) n,\n    n = length ls\n    -> firstn n ls = ls.\n    intros; subst; induction ls; simpl; intuition.\n  Qed.\n\n  Hint Rewrite firstn_all using congruence : sepFormula.\n\n  Ltac writeExps' :=\n    try match goal with\n          | [ H : ?E = _ |- match ?E with None => _ | _ => _ end ] =>\n            rewrite H; post\n        end;\n    edestruct writeExps_correct; repeat rewrite Minus.minus_diag, Plus.plus_0_r in *;\n      try match goal with\n            | [ |- vcs _ ] => eauto\n            | [ H : interp _ (Postcondition _ _), H' : _ |- _ ] => apply H' in H\n          end; eauto; try rewrite Minus.minus_diag in *.\n\n  Ltac writeExps :=\n    match goal with\n      | [ |- context[writeExps] ] => writeExps'\n      | [ _ : context[writeExps] |- _ ] => writeExps'\n    end.\n\n  Lemma prove_freeable8 : forall p size,\n    freeable p (wordToNat size)\n    -> goodSize (4 * wordToNat size)\n    -> freeable8 p (wordToNat (natToW 4 ^* size)).\n    intros; rewrite wordToNat_wmult; change (wordToNat (natToW 4)) with 4; hnf; eauto.\n  Qed.\n\n  Hint Immediate prove_freeable8.\n\n  Ltac i := abstract (try writeExps; t).\n\n  Definition Insert : chunk.\n    refine (WrapC Insert'\n      invar\n      invar\n      InsertVcs\n      _ _); abstract (wrap0; i).\n  Defined.\n\nEnd Insert.\n", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/RelDbInsert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22798486096587556}}
{"text": "Require Import Privilege.\nRequire Import TransitionSystems.\n\nRequire Import Ctl.BinaryRelations.\nRequire Import Ctl.Definition.\nRequire Import Glib.Glib.\n\nOpen Scope string_scope.\nOpen Scope env_scope.\n\n\n(* value types *)\n\nInductive boot_token_t :=\n  | good_boot_token\n  | bad_boot_token.\nInductive vm_ev_t :=\n  | good_vm_ev\n  | bad_vm_ev.\nInductive platam_key_t :=\n  | good_platam_key\n  | encr_platam_key\n  | bad_platam_key.\nInductive useram_key_t :=\n  | good_useram_key\n  | encr_useram_key\n  | bad_useram_key.\nInductive useram_key_decr_key_t :=\n  | good_decr_key\n  | encr_decr_key\n  | bad_decr_key.\n\n\n(* Transition definitions *)\n\nInductive platam_label :=\n  | platam_init \n  | platam_meas_release\n  | platam_listen.\n\n(* Definition platam_state := dynamic_state platam_label. *)\nDefinition platam_state := platam_label × env.\nDefinition platam_init_state : platam_state :=\n  (platam_init,\n   private \"platam\" ? (\n     \"platam_key\" ↦ encr_platam_key ;;\n     \"useram_key_decr_key\" ↦ encr_decr_key\n  )).\n\nDefinition decrypt_platam_key key token : platam_key_t := \n  match (key, token) with \n  | (encr_platam_key, good_boot_token) => good_platam_key\n  | _ => bad_platam_key\n  end.\n\nDefinition decrypt_useram_key_decr_key decr_key platam_key : useram_key_decr_key_t := \n  match (decr_key, platam_key) with \n  | (encr_decr_key, good_platam_key) => good_decr_key\n  | _ => bad_decr_key\n  end.\n\nInductive platam_trans : relation (platam_state × env) := \n  | platam_unlock_key : forall Γl Γl' Γg key token,\n      read  Γl \"platam\" \"platam_key\" key ->\n      read  Γg \"platam\" \"boot_token\" token ->\n      write Γl \"platam\" \"platam_key\" (decrypt_platam_key key token) Γl' ->\n      platam_trans \n        (platam_init, Γl, Γg)\n        (platam_meas_release, Γl', Γg)\n  | platam_measure_release : forall Γl Γg Γg' platam_key decr_key,\n      read  Γg \"platam\" \"good_image\" true ->\n      read  Γl \"platam\" \"useram_key_decr_key\" decr_key ->\n      read  Γl \"platam\" \"platam_key\" platam_key -> \n      write Γg \"platam\" \"vmm_dataport\" (decrypt_useram_key_decr_key decr_key platam_key) Γg' ->\n      platam_trans \n        (platam_meas_release, Γl, Γg)\n        (platam_listen, Γl, Γg').\n\n(* TODO, bad_platam_trans, *)\n\nInductive useram_label := \n  | useram_wait_key\n  | useram_listen.\n\nDefinition useram_state := useram_label × env.\n\nDefinition useram_init_state : useram_state := \n  (useram_wait_key, private \"useram\" ? \"useram_key\" ↦ encr_useram_key).\n\nDefinition decrypt_useram_key key decr_key : useram_key_t := \n  match (key, decr_key) with \n  | (encr_useram_key, good_decr_key) => good_useram_key\n  | _ => bad_useram_key\n  end.\n\nInductive useram_trans : relation (useram_state × env) :=\n  | useram_get_key : forall Γl Γl' Γg encr_key decr_key,\n      read  Γl \"useram\" \"useram_key\" encr_key ->\n      read  Γg \"useram\" \"vmm_dataport\" decr_key ->\n      write Γl \"useram\" \"useram_key\" (decrypt_useram_key encr_key decr_key) Γl' ->\n      useram_trans \n        (useram_wait_key, Γl, Γg)\n        (useram_listen, Γl', Γg).\n\nInductive vm_label := \n  | vm_run : useram_state -> vm_label.\n\nDefinition vm_state := vm_label.\n\nDefinition vm_init_state : vm_state := vm_run useram_init_state.\n\nInductive vm_trans : relation (vm_state × env) := \n  | useram_step : forall x y Γ Γ',\n      useram_trans (x, Γ) (y, Γ') ->\n      vm_trans (vm_run x, Γ) (vm_run y, Γ').\n\nInductive attarch_label :=\n  | boot\n  | sel4_run : platam_state -> vm_state -> attarch_label\n  | attarch_bot.\n\nDefinition attarch_state := attarch_label × env.\n\nDefinition attarch_init_state : attarch_state := (boot, allReadOnly ? \"good_image\" ↦ true).\n\nInductive attarch_trans : relation attarch_state :=\n  | boot_good : forall Γ,\n      read Γ \"root_of_trust\" \"good_image\" true -> \n      attarch_trans\n        (boot, Γ)\n        (sel4_run platam_init_state vm_init_state,\n          allReadOnly ? \"boot_token\" ↦ good_boot_token;; Γ)\n  | boot_bad : forall Γ,\n      read Γ \"root_of_trust\" \"good_image\" false -> \n      attarch_trans\n        (boot, Γ)\n        (sel4_run platam_init_state vm_init_state,\n          allReadOnly ? \"boot_token\" ↦ bad_boot_token;; Γ)\n  | platam_step : forall x l l' Γl Γl' Γg Γg',\n      platam_trans (l, Γl, Γg) (l', Γl', Γg') ->\n      attarch_trans \n        (sel4_run (l, Γl) x, Γg)\n        (sel4_run (l', Γl') x, Γg')\n  | vm_step : forall x l l' Γg Γg',\n      vm_trans (l, Γg) (l', Γg') ->\n      attarch_trans \n        (sel4_run x l, Γg)\n        (sel4_run x l', Γg')\n | attarch_diverge : forall l Γ,\n      attarch_trans (l, Γ) (attarch_bot, Γ).\n\n\nLemma attarch_trans_serial : \n  serial_witness attarch_trans.\nProof using.\n  unfold serial_witness.\n  intros [l ?].\n  eexists.\n  apply attarch_diverge.\nDefined.\n\nInstance transition__attarch_trans : transition attarch_trans :=\n  { trans_serial := attarch_trans_serial }.\n\nClose Scope env_scope.\nClose Scope string_scope.\n", "meta": {"author": "gjurgensen", "repo": "thesis", "sha": "fee5e9e2ba728f3707eee7ad9d90837c25cf7764", "save_path": "github-repos/coq/gjurgensen-thesis", "path": "github-repos/coq/gjurgensen-thesis/thesis-fee5e9e2ba728f3707eee7ad9d90837c25cf7764/src/AttarchTrans.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2279488348134456}}
{"text": "(** * Bicolano: Big step (interface implementation) *)\n\n(* <Insert License Here>\n\n    $Id: BigStep.v 68 2006-02-02 15:06:27Z davidpichardie $ *)\n\n(** Big step semantics.\n\n @author David Pichardie *)\n\n(* Hendra : - Modified to suit DEX program. \n            - Also trim the system to contain only Arithmetic *)\n\nRequire Export DEX_BigStepType.\nRequire Export DEX_ImplemDomain.\n\nOpen Scope type_scope.\n\nModule DEX_BigStep <: DEX_BIGSTEP.\n \n  Module DEX_Dom := DEX_ImplemDomain.DEX_Dom.\n \n  (* Inductive definition are put in BigStepLoad.v.\n     They are shared with BigStepType.v *)\n  Load \"DEX_BigStepLoad.v\".\n \n  Lemma IntraStep_ind_ : \n      forall (p:DEX_Program) (P:DEX_Method->DEX_IntraNormalState->DEX_IntraNormalState+DEX_ReturnState->Prop),\n         (forall m s, P m s (inl _ s)) ->\n         (forall m s r, DEX_exec_return p m s r -> P m s (inr _ r)) ->\n         (forall m s s' , DEX_exec_intra p m s s' -> \n            forall r, DEX_IntraStepStar p m s' r -> P m s' r ->\n            P m s r) ->\n(* DEX Method\n         (forall m s s' ret m' r, \n            DEX_exec_call p m s ret m' s' (inr _ r) ->\n            DEX_IntraStepStar p m' s' (inr _ ret) ->\n            P m' s' (inr _ ret) ->\n            P m s (inr _ r)) ->\n         (forall m s s' ret m' s'' r, \n            DEX_exec_call p m s ret m' s' (inl _ s'') ->\n            DEX_IntraStepStar p m' s' (inr _ ret) -> P m' s' (inr _ ret) ->\n            DEX_IntraStepStar p m s'' r -> P m s'' r ->\n            P m s r) ->\n*)\n      forall m s r, DEX_IntraStep p m s r -> \n        match r with\n        | inr r' => P m s (inr _ r')\n        | inl s' => forall r', DEX_IntraStepStar p m s' r' -> P m s' r' -> P m s r'\n        end.\n     Proof.\n       intros p P H0 Hr Hi Hcr Hc.\n       fix intra (*4*) 2;intros (*m s*) r Hs;case Hs;clear (*m s*) r Hs;intros.\n       apply Hr;trivial.\n       apply Hi with s2;trivial. \n     Qed.\n(* DEX Method\n       assert (P m' s' (inr DEX_IntraNormalState ret')).\n       generalize s' (inr DEX_IntraNormalState ret') H1;clear H1 H m s1 s' ret' r.\n       fix fixp 3;intros s' s Ht;case Ht;clear Ht s' s;intros.\n       apply H0.\n       generalize (intra _ _ _ H);clear H;case r;intros.\n       apply H;trivial. constructor. trivial. \n       assert (HH:= intra _ _ _ H);simpl in HH.\n       apply HH;trivial. apply fixp;trivial.\n       generalize H;clear H;case r.\n       intros s'' Hcall r' Hint HP.\n       eapply Hc;eauto.\n       intros r' Hcall;eapply Hcr;eauto.\n     Qed.\n*)\n\n  Lemma IntraStepStar_ind : \n    forall (p:DEX_Program) \n     (P : DEX_Method -> DEX_IntraNormalState -> DEX_IntraNormalState + DEX_ReturnState -> Prop),\n       (forall m s, P m s (inl _ s)) ->\n       (forall m s r, DEX_exec_return p m s r -> P m s (inr _ r)) ->\n       (forall m s s' , DEX_exec_intra p m s s' -> \n          forall r, DEX_IntraStepStar p m s' r -> P m s' r ->\n          P m s r) ->\n(* DEX Method\n       (forall m s s' ret m' r, \n          DEX_exec_call p m s ret m' s' (inr _ r) ->\n          DEX_IntraStepStar p m' s' (inr _ ret) ->\n          P m' s' (inr _ ret) ->\n          P m s (inr _ r)) ->\n       (forall m s s' ret m' s'' r, \n          DEX_exec_call p m s ret m' s' (inl _ s'') ->\n          DEX_IntraStepStar p m' s' (inr _ ret) -> P m' s' (inr _ ret) ->\n          DEX_IntraStepStar p m s'' r -> P m s'' r ->\n          P m s r) ->\n*)\n    forall m s r, DEX_IntraStepStar p m s r -> P m s r.\n   Proof.\n     intros p P H0 Hr Hi (*Hcr Hc*).\n     fix fixp 4; intros m s' s Ht;case Ht;clear Ht s' s;intros.\n     apply H0.\n     generalize (IntraStep_ind_ p P H0 Hr Hi (*Hcr Hc*) _ _ _ H).\n     case r;intros;trivial.\n     apply H1;trivial. constructor.\n     assert (HH:=IntraStep_ind_  p P H0 Hr Hi (*Hcr Hc*) _ _ _ H);simpl in HH.\n     apply HH;trivial.   \n     apply fixp;trivial.\n   Qed.\n\n  Lemma IntraStepStar_intra_ind : \n    forall (p:DEX_Program) \n     (P : DEX_Method -> DEX_IntraNormalState -> DEX_IntraNormalState -> Prop),\n       (forall m s, P m s s) ->\n       (forall m s s', DEX_exec_intra p m s s' -> \n          forall s'', DEX_IntraStepStar_intra p m s' s'' -> P m s' s'' ->\n          P m s s'') ->\n(* DEX Method\n       (forall m s s1 ret m' s2 s3, \n          DEX_exec_call p m s ret m' s1 (inl _ s2) ->\n          DEX_BigStep p m' s1 ret -> \n          DEX_IntraStepStar_intra p m s2 s3 -> P m s2 s3 ->\n          P m s s3) ->\n*)\n    forall m s s', DEX_IntraStepStar_intra p m s s' -> P m s s'.\n   Proof.\n     intros p P H0 Hi Hc.\n     assert (forall m s r, DEX_IntraStepStar p m s r ->\n              forall s', r = inl _ s' -> P m s s').\n      induction 1 using IntraStepStar_ind;intros;try discriminate;subst;eauto.\n      inversion H;auto.\n     intros; eapply H; eauto. \n   Qed.\n\n  Lemma BigStep_ind : \n    forall (p:DEX_Program) \n     (P : DEX_Method -> DEX_IntraNormalState -> DEX_ReturnState -> Prop),\n       (forall m s r, DEX_exec_return p m s r -> P m s r) ->\n       (forall m s s' , DEX_exec_intra p m s s' -> \n          forall r, DEX_BigStep p m s' r -> P m s' r ->\n          P m s r) ->\n(* DEX Method\n       (forall m s s' ret m' r, \n          DEX_exec_call p m s ret m' s' (inr _ r) ->\n          DEX_BigStep p m' s' ret ->\n          P m' s' ret ->\n          P m s r) ->\n       (forall m s s' ret m' s'' r, \n          DEX_exec_call p m s ret m' s' (inl _ s'') ->\n          DEX_BigStep p m' s' ret -> P m' s' ret ->\n          DEX_BigStep p m s'' r -> P m s'' r ->\n          P m s r) ->\n*)\n    forall m s r, DEX_BigStep p m s r -> P m s r.\n  Proof.\n   intros p P Hr Hi Hcr Hc.\n   assert (forall m s R, DEX_IntraStepStar p m s R -> forall r, R = inr _ r -> P m s r).\n   induction 1 using IntraStepStar_ind;intros r0 Heq;try inversion Heq;subst;\n    try (eauto;fail).\n   intros;eapply H;eauto. \n  Qed.\n\n  Lemma ReachableStar_ind : \n    forall (p:DEX_Program) \n     (P : (DEX_Method * DEX_IntraNormalState) -> (DEX_Method * DEX_IntraNormalState) -> Prop),\n       (forall m s, P (m,s) (m,s)) ->\n       (forall m s s', DEX_exec_intra p m s s' -> \n          forall m' s'', ClosReflTrans (DEX_ReachableStep p) (m,s') (m',s'') -> \n          P (m,s') (m',s'') ->\n          P (m,s) (m',s'')) ->\n(* DEX Method\n       (forall m s s1 ret m' s2, \n          DEX_exec_call p m s ret m' s1 (inl _ s2) ->\n          DEX_BigStep p m' s1 ret -> \n          forall m' s3, ClosReflTrans (DEX_ReachableStep p) (m,s2) (m',s3) -> \n          P (m,s2) (m',s3) ->\n          P (m,s) (m',s3)) ->\n       (forall m pc h l m' l' bm',\n        DEX_CallStep p m (pc,(h,l)) (m',l') ->\n        DEX_METHOD.body m' = Some bm' ->\n        forall m'' s'', \n        ClosReflTrans (DEX_ReachableStep p) \n          (m', (DEX_BYTECODEMETHOD.firstAddress bm',(h, l')))\n          (m'',s'') ->\n        P (m', (DEX_BYTECODEMETHOD.firstAddress bm',(h, l')))\n          (m'',s'') ->\n        P (m, (pc,(h, l))) (m'',s'')) ->\n*)\n    forall ms ms', \n       ClosReflTrans (DEX_ReachableStep p) ms ms' -> P ms ms'.\n   Proof.\n     intros p P H0 Hi Hc Hsc.\n     induction 1;intros.\n     destruct a;eauto.\n     destruct a'' as (m'',s'').\n     inversion H;subst;eauto.\n     inversion H2;clear H2;subst;eauto.\n   Qed.\n\nEnd DEX_BigStep.\n\n", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/DEX_BigStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22794882876012076}}
{"text": "From Coq Require Import\n     List\n     String.\n\nFrom ExtLib Require Import\n     Programming.Show\n     Structures.Monads\n     Structures.Maps.\n\nFrom ITree Require Import \n     ITree\n     Events.State.\n\nFrom Vellvm Require Import\n     LLVMAst\n     AstLib\n     MemoryAddress\n     DynamicValues\n     LLVMEvents\n     Local\n     Error.\n\nSet Implicit Arguments.\nSet Contextual Implicit.\n\nImport ListNotations.\nImport MonadNotation.\n\nImport ITree.Basics.Basics.Monads.\n\nSection StackMap.\n  Variable (k v:Type).\n  Context {map : Type}.\n  Context {M: Map k v map}.\n  Context {SK : Show k}.\n\n  Definition stack := list map.\n\n  Definition handle_stack {E} `{FailureE -< E} : (StackE k v) ~> stateT (map * stack) (itree E) :=\n      fun _ e '(env, stk) =>\n        match e with\n        | StackPush bs =>\n          let init := List.fold_right (fun '(x,dv) => Maps.add x dv) Maps.empty bs in\n          Ret ((init, env::stk), tt)\n        | StackPop =>\n          match stk with\n          (* CB TODO: should this raise an error? Is this UB? *)\n          | [] => raise \"Tried to pop too many stack frames.\"\n          | (env'::stk') => Ret ((env',stk'), tt)\n          end\n        end.\n\n    (* Transform a local handler that works on maps to one that works on stacks *)\n    Definition handle_local_stack {E} `{FailureE -< E} (h:(LocalE k v) ~> stateT map (itree E)) :\n      LocalE k v ~> stateT (map * stack) (itree E)\n      :=\n      fun _ e '(env, stk) => ITree.map (fun '(env',r) => ((env',stk), r)) (h _ e env).\n\n  Open Scope monad_scope.\n  Section PARAMS.\n    Variable (E F G : Type -> Type).\n    Definition E_trigger {S} : forall R, E R -> (stateT S (itree (E +' F +' G)) R) :=\n      fun R e m => r <- trigger e ;; ret (m, r).\n\n    Definition F_trigger {S} : forall R, F R -> (stateT S (itree (E +' F +' G)) R) :=\n      fun R e m => r <- trigger e ;; ret (m, r).\n\n    Definition G_trigger {S} : forall R , G R -> (stateT S (itree (E +' F +' G)) R) :=\n      fun R e m => r <- trigger e ;; ret (m, r).\n\n    Definition interp_local_stack `{FailureE -< E +' F +' G}\n               (h:(LocalE k v) ~> stateT map (itree _)) :\n      (itree (E +' F +' ((LocalE k v) +' (StackE k v)) +' G)) ~>  stateT (map * stack) (itree (E +' F +' G)) :=\n      interp_state (case_ E_trigger\n                   (case_ F_trigger\n                   (case_ (case_ (handle_local_stack h)\n                                 handle_stack)\n                          G_trigger))).\n    End PARAMS.\n\n\n    (* SAZ: I wasn't (yet) able to completey disentangle the ocal events from the stack events.\n       This version makes the stack a kind of \"wrapper\" around the locals and provides a way\n       of lifting locals into this new state.\n\n       There should be some kind of lemma long the lines of:\n\n        [forall (t:itree (E +' LocalE k v +' F) V) (env:map) (s:stack),\n         run_local t env ≅\n         Itree.map fst (run_local_stack (translate _into_stack t) (env, s))]\n\n       Here, [_into_stack : (E +' LocalE k v +' F) ~> (E +' ((LocalE k v) +' StackE k v) +' F)]\n       is the inclusion into stack events.\n    *)\n\nEnd StackMap.\n", "meta": {"author": "amuppal18", "repo": "test", "sha": "4f6663f47786843480790e1b754ea117de435ff3", "save_path": "github-repos/coq/amuppal18-test", "path": "github-repos/coq/amuppal18-test/test-4f6663f47786843480790e1b754ea117de435ff3/src/coq/Handlers/Stack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22794882876012074}}
{"text": "(** In this file, we repackage an instance for\n[compcert.backend.magree] for the concrete memory\nmodel implemented in [compcertx.common.MemimplX]. \n\nIndeed, those two memory models are different as they use different\nimplementations of [inject_neutral].\n\nFortunately, [magree] does not use [inject_neutral], so we have nothing to prove. We just need to unpack/repack.\n*)\n\nRequire compcert.backend.DeadcodeproofImpl.\nRequire MemimplX.\n\nExport Deadcodeproof.\nExport MemimplX.\n\nImport Coqlib.\n\nLemma magree_storebytes_parallel:\n   forall (m1 m2 : Memimpl.mem) (P Q : locset) (b : Values.block) \n     (ofs : Z) (bytes1 : list memval) (m1' : Memimpl.mem)\n     (bytes2 : list memval),\n   magree m1 m2 P ->\n   Mem.storebytes m1 b ofs bytes1 = Some m1' ->\n   (forall (b' : Values.block) (i : Z),\n    Q b' i ->\n    b' <> b \\/ i < ofs \\/ ofs + Z.of_nat (length bytes1) <= i -> P b' i) ->\n   list_forall2 memval_lessdef bytes1 bytes2 ->\n   exists m2' : Memimpl.mem,\n     Mem.storebytes m2 b ofs bytes2 = Some m2' /\\ magree m1' m2' Q.\nProof.\n  unfold Mem.storebytes.\n  unfold memory_model_ops. unfold storebytes.\n  intros.\n  destruct (is_empty bytes1); destruct (is_empty bytes2); eauto using DeadcodeproofImpl.magree_storebytes_parallel. \n  * inv H0. simpl in *.\n    esplit. split. reflexivity.\n    eapply DeadcodeproofImpl.magree_monotone; eauto.\n    intros. destruct (zle ofs ofs0); eapply H1; eauto; intuition omega.\n  * apply is_empty_list_forall2 in H2. tauto.\n  * apply is_empty_list_forall2 in H2. tauto.\nQed.\n\nLemma magree_free:\n  forall m1 m2 (P Q: locset) b lo hi m1',\n  DeadcodeproofImpl.magree m1 m2 P ->\n  MemimplX.free m1 b lo hi = Some m1' ->\n  (forall b' i, Q b' i ->\n                b' <> b \\/ ~(lo <= i < hi) ->\n                P b' i) ->\n  exists m2', MemimplX.free m2 b lo hi = Some m2' /\\ DeadcodeproofImpl.magree m1' m2' Q.\nProof.\n  unfold MemimplX.free. intros.\n  destruct (zle hi lo); eauto using DeadcodeproofImpl.magree_free.\n  inv H0.\n  esplit. split. reflexivity.\n  eapply DeadcodeproofImpl.magree_monotone; eauto.\n  intros. eapply H1; eauto. right. omega.\nQed.\n\nGlobal Instance magree_ops\n: Deadcodeproof.MAgreeOps Memimpl.mem (memory_model_ops := MemimplX.memory_model_ops)\n:= {|\n    magree := DeadcodeproofImpl.magree\n  |}.\n\nGlobal Instance magree_prf\n: Deadcodeproof.MAgree Memimpl.mem (memory_model_ops := MemimplX.memory_model_ops).\nProof.\n  constructor.\n  exact DeadcodeproofImpl.ma_perm.\n  exact DeadcodeproofImpl.magree_monotone.\n  exact DeadcodeproofImpl.mextends_agree.\n  exact DeadcodeproofImpl.magree_extends.\n  exact DeadcodeproofImpl.magree_loadbytes.\n  exact DeadcodeproofImpl.magree_load.\n  exact magree_storebytes_parallel.\n  exact DeadcodeproofImpl.magree_store_parallel.\n  now storebytes_tac DeadcodeproofImpl.magree_storebytes_left.\n  exact DeadcodeproofImpl.magree_store_left.\n  exact magree_free.\nQed.\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/CAL/compcertx/backend/DeadcodeproofImplX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22794882876012074}}
{"text": "(* This file is an automatic translation, the licence of the source can be found here: *)\n(* https://github.com/herd/herdtools7/blob/master/LICENSE.txt *)\n(* Translation of model ARM relaxing ppo to accommodate qualcomm behaviors *)\nFrom Coq Require Import Relations Ensembles String.\nFrom RelationAlgebra Require Import lattice prop monoid rel kat.\nFrom Catincoq.lib Require Import Cat proprel.\nSection Model.\nVariable c : candidate.\nDefinition events := events c.\nDefinition R := R c.\nDefinition W := W c.\nDefinition IW := IW c.\nDefinition FW := FW c.\nDefinition B := B c.\nDefinition RMW := RMW c.\nDefinition F := F c.\nDefinition rf := rf c.\nDefinition po := po c.\nDefinition int := int c.\nDefinition ext := ext c.\nDefinition loc := loc c.\nDefinition addr := addr c.\nDefinition data := data c.\nDefinition ctrl := ctrl c.\nDefinition amo := amo c.\nDefinition rmw := rmw c.\nDefinition unknown_set := unknown_set c.\nDefinition unknown_relation := unknown_relation c.\nDefinition M := R ⊔ W.\nDefinition emptyset : set events := empty.\nDefinition classes_loc : set events -> Ensemble (Ensemble events) := partition loc.\nDefinition X := unknown_set \"X\".\nDefinition tag2events := unknown_relation \"tag2events\".\nDefinition emptyset_0 : set events := domain 0.\nDefinition partition := classes_loc.\nDefinition tag2instrs := tag2events.\nDefinition po_loc := po ⊓ loc.\nDefinition rfe := rf ⊓ ext.\nDefinition rfi := rf ⊓ int.\nDefinition co0 := loc ⊓ ([IW] ⋅ top ⋅ [(W ⊓ !IW)] ⊔ [(W ⊓ !FW)] ⋅ top ⋅ [FW]).\nDefinition toid (s : set events) : relation events := [s].\nDefinition fencerel (B : set events) := (po ⊓ [top] ⋅ top ⋅ [B]) ⋅ po.\nDefinition ctrlcfence (CFENCE : set events) := (ctrl ⊓ [top] ⋅ top ⋅ [CFENCE]) ⋅ po.\nDefinition imply (A : relation events) (B : relation events) := !A ⊔ B.\nDefinition nodetour (R1 : relation events) (R2 : relation events) (R3 : relation events) := R1 ⊓ !(R2 ⋅ R3).\nDefinition singlestep (R : relation events) := nodetour R R R.\n(* Definition of map already included in the prelude *)\nDefinition LKW := (*failed: try LKW with emptyset_0*) emptyset_0.\n(* Definition of co_locs already included in the prelude *)\n(* Definition of cross already included in the prelude *)\nDefinition generate_orders s pco := cross (co_locs pco (partition s)).\nDefinition generate_cos pco := generate_orders W pco.\nDefinition cobase := co0.\nVariable co : relation events.\nDefinition coi := co ⊓ int.\nDefinition coe := co ⊓ !coi.\nDefinition fr := rf° ⋅ co ⊓ !id.\nDefinition fri := fr ⊓ int.\nDefinition fre := fr ⊓ !fri.\nDefinition poi := po_loc.\nDefinition complus := fr ⊔ (rf ⊔ (co ⊔ (co ⋅ rf ⊔ fr ⋅ rf))).\nDefinition scperlocation := irreflexive (poi ⋅ complus).\nDefinition dd := addr ⊔ data.\nDefinition rdw := po_loc ⊓ fre ⋅ rfe.\nDefinition detour := po_loc ⊓ coe ⋅ rfe.\nDefinition addrpo := addr ⋅ po.\nDefinition dmb_st : relation events := (*failed: try fencerel DMB.ST with 0*) 0.\nDefinition dsb_st : relation events := (*failed: try fencerel DSB.ST with 0*) 0.\nDefinition dmb : relation events := (*failed: try fencerel DMB with 0*) 0.\nDefinition dsb : relation events := (*failed: try fencerel DSB with 0*) 0.\nDefinition isb : relation events := (*failed: try fencerel ISB with 0*) 0.\nDefinition ctrlisb : relation events := (*failed: try ctrlcfence ISB with 0*) 0.\nDefinition ci0 := ctrlisb ⊔ detour.\nDefinition ii0 := dd ⊔ (rfi ⊔ rdw).\nDefinition cc0 := dd ⊔ (ctrl ⊔ (addrpo ⊔ po_loc ⊓ !(rfi ⊔ po_loc ⋅ rfi))).\nDefinition ic0 : relation events := 0.\nInductive ci : relation _ := ci_c : incl (ci0 ⊔ (ci ⋅ ii ⊔ cc ⋅ ci)) ci\n     with ii : relation _ := ii_c : incl (ii0 ⊔ (ci ⊔ (ic ⋅ ci ⊔ ii ⋅ ii))) ii\n     with cc : relation _ := cc_c : incl (cc0 ⊔ (ci ⊔ (ci ⋅ ic ⊔ cc ⋅ cc))) cc\n     with ic : relation _ := ic_c : incl (ic0 ⊔ (ii ⊔ (cc ⊔ (ic ⋅ cc ⊔ ii ⋅ ic)))) ic.\nSection scheme.\nVariables ci' ii' cc' ic' : relation events.\nVariable Hci' : incl (ci0 ⊔ (ci' ⋅ ii' ⊔ cc' ⋅ ci')) ci'.\nVariable Hii' : incl (ii0 ⊔ (ci' ⊔ (ic' ⋅ ci' ⊔ ii' ⋅ ii'))) ii'.\nVariable Hcc' : incl (cc0 ⊔ (ci' ⊔ (ci' ⋅ ic' ⊔ cc' ⋅ cc'))) cc'.\nVariable Hic' : incl (ic0 ⊔ (ii' ⊔ (cc' ⊔ (ic' ⋅ cc' ⊔ ii' ⋅ ic')))) ic'.\n\n  Fixpoint ci_ind' x y (r : ci x y) : ci' x y\n      with ii_ind' x y (r : ii x y) : ii' x y\n      with cc_ind' x y (r : cc x y) : cc' x y\n      with ic_ind' x y (r : ic x y) : ic' x y.\n  Proof.\n    destruct r as [x y r]; apply Hci'.\n    destruct r as [r | r]; [ left | right ].\n     exact r.\n     destruct r as [r | r]; [ left | right ].\n      destruct r as [x_y r1 r2]; exists x_y.\n       apply ci_ind'; exact r1.\n       apply ii_ind'; exact r2.\n      destruct r as [x_y r1 r2]; exists x_y.\n       apply cc_ind'; exact r1.\n       apply ci_ind'; exact r2.\n    destruct r as [x y r]; apply Hii'.\n    destruct r as [r | r]; [ left | right ].\n     exact r.\n     destruct r as [r | r]; [ left | right ].\n      apply ci_ind'; exact r.\n      destruct r as [r | r]; [ left | right ].\n       destruct r as [x_y r1 r2]; exists x_y.\n        apply ic_ind'; exact r1.\n        apply ci_ind'; exact r2.\n       destruct r as [x_y r1 r2]; exists x_y.\n        apply ii_ind'; exact r1.\n        apply ii_ind'; exact r2.\n    destruct r as [x y r]; apply Hcc'.\n    destruct r as [r | r]; [ left | right ].\n     exact r.\n     destruct r as [r | r]; [ left | right ].\n      apply ci_ind'; exact r.\n      destruct r as [r | r]; [ left | right ].\n       destruct r as [x_y r1 r2]; exists x_y.\n        apply ci_ind'; exact r1.\n        apply ic_ind'; exact r2.\n       destruct r as [x_y r1 r2]; exists x_y.\n        apply cc_ind'; exact r1.\n        apply cc_ind'; exact r2.\n    destruct r as [x y r]; apply Hic'.\n    destruct r as [r | r]; [ left | right ].\n     exact r.\n     destruct r as [r | r]; [ left | right ].\n      apply ii_ind'; exact r.\n      destruct r as [r | r]; [ left | right ].\n       apply cc_ind'; exact r.\n       destruct r as [r | r]; [ left | right ].\n        destruct r as [x_y r1 r2]; exists x_y.\n         apply ic_ind'; exact r1.\n         apply cc_ind'; exact r2.\n        destruct r as [x_y r1 r2]; exists x_y.\n         apply ii_ind'; exact r1.\n         apply ic_ind'; exact r2.\n  Qed.\nEnd scheme.\nDefinition ppo := let ppoR := ii ⊓ [R] ⋅ top ⋅ [R] in let ppoW := ic ⊓ [R] ⋅ top ⋅ [W] in ppoR ⊔ ppoW.\nDefinition WW := [W] ⋅ top ⋅ [W].\nDefinition dmb_st_0 := dmb_st ⊓ WW.\nDefinition dsb_st_0 := dsb_st ⊓ WW.\nDefinition strong := dmb ⊔ (dsb ⊔ (dmb_st_0 ⊔ dsb_st_0)).\nDefinition light : relation events := 0.\nDefinition fence := strong ⊔ light.\nDefinition hb := ppo ⊔ (fence ⊔ rfe).\nDefinition thinair := acyclic hb.\nDefinition hbstar := hb^*.\nDefinition propbase := (fence ⊔ rfe ⋅ fence) ⋅ hbstar.\nDefinition chapo := rfe ⊔ (fre ⊔ (coe ⊔ (fre ⋅ rfe ⊔ coe ⋅ rfe))).\nDefinition prop := propbase ⊓ [W] ⋅ top ⋅ [W] ⊔ (chapo ⊔ 1) ⋅ (propbase^* ⋅ (strong ⋅ hbstar)).\nDefinition propagation := acyclic (co ⊔ prop).\nDefinition observation := irreflexive (fre ⋅ (prop ⋅ hbstar)).\nDefinition xx := po ⊓ [X] ⋅ top ⋅ [X].\nDefinition scXX := acyclic (co ⊔ xx).\nDefinition witness_conditions := generate_cos cobase co.\nDefinition model_conditions := scperlocation /\\ (thinair /\\ (propagation /\\ (observation /\\ scXX))).\nEnd Model.\n\nHint Unfold events R W IW FW B RMW F rf po int ext loc addr data ctrl amo rmw unknown_set unknown_relation M emptyset classes_loc X tag2events emptyset_0 partition tag2instrs po_loc rfe rfi co0 toid fencerel ctrlcfence imply nodetour singlestep LKW generate_orders generate_cos cobase coi coe fr fri fre poi complus scperlocation dd rdw detour addrpo dmb_st dsb_st dmb dsb isb ctrlisb ci0 ii0 cc0 ic0 ppo WW dmb_st_0 dsb_st_0 strong light fence hb thinair hbstar propbase chapo prop propagation observation xx scXX witness_conditions model_conditions : cat.\n\nDefinition valid (c : candidate) :=\n  exists co : relation (events c),\n    witness_conditions c co /\\\n    model_conditions c co.\n\n(* End of translation of model ARM relaxing ppo to accommodate qualcomm behaviors *)\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/models/qualcomm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.2279221442847392}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** RTL function inlining: relational specification *)\n\nRequire Import Coqlib Wfsimpl Maps Errors Integers.\nRequire Import AST Linking.\nRequire Import Op Registers RTL.\nRequire Import Inlining.\n\n(** ** Soundness of function environments. *)\n\n(** A compile-time function environment is compatible with a whole\n  program if the following condition holds. *)\n\nDefinition fenv_compat (p: program) (fenv: funenv) : Prop :=\n  forall id f,\n  fenv!id = Some f -> (prog_defmap p)!id = Some (Gfun (Internal f)).\n\nLemma funenv_program_compat:\n  forall p, fenv_compat p (funenv_program p).\nProof.\n  set (P := fun (dm: PTree.t (globdef fundef unit)) (fenv: funenv) =>\n              forall id f,\n              fenv!id = Some f -> dm!id = Some (Gfun (Internal f))).\n  assert (REMOVE: forall dm fenv id g,\n             P dm fenv ->\n             P (PTree.set id g dm) (PTree.remove id fenv)).\n  { unfold P; intros. rewrite PTree.grspec in H0. destruct (PTree.elt_eq id0 id).\n    discriminate.\n    rewrite PTree.gso; auto.\n  }\n  assert (ADD: forall dm fenv idg,\n             P dm fenv ->\n             P (match snd idg with\n                  | Some g => PTree.set (fst idg) g dm\n                  | _ => PTree.remove (fst idg) dm\n                end) (add_globdef fenv idg)).\n  { intros dm fenv [id g]; simpl; intros.\n    destruct g as [ [ [f|ef] | v] | ] ; auto.\n    destruct (should_inline id f); auto.\n    red; intros. rewrite ! PTree.gsspec in *.\n    destruct (peq id0 id); auto. inv H0; auto.\n    unfold P. intros ? ? .\n    rewrite ! PTree.grspec.\n    destruct (PTree.elt_eq id0 id); auto.\n    discriminate.\n  }\n  assert (REC: forall l dm fenv,\n            P dm fenv ->\n            P (fold_left (fun x idg =>\n                            match snd idg with\n                              | Some g => PTree.set (fst idg) g x\n                              | None => PTree.remove (fst idg) x\n                            end) l dm)\n              (fold_left add_globdef l fenv)).\n  { induction l; simpl; intros.\n  - auto.\n  - apply IHl. apply ADD; auto.\n  }\n  intros. apply REC. red; intros.  rewrite PTree.gempty in H; discriminate.\nQed.\n\nLemma fenv_compat_linkorder:\n  forall cunit prog fenv,\n  linkorder cunit prog -> fenv_compat cunit fenv -> fenv_compat prog fenv.\nProof.\n  intros; red; intros. apply H0 in H1.\n  destruct (prog_defmap_linkorder _ _ _ _ H H1) as (gd' & P & Q).\n  inv Q. inv H3. auto.\nQed.\n\n(** ** Properties of shifting *)\n\nLemma shiftpos_eq: forall x y, Zpos (shiftpos x y) = (Zpos x + Zpos y) - 1.\nProof.\n  intros. unfold shiftpos. zify.  try rewrite Pos2Z.inj_sub. auto.\n  zify. omega.\nQed.\n\nLemma shiftpos_inj:\n  forall x y n, shiftpos x n = shiftpos y n -> x = y.\nProof.\n  intros.\n  assert (Zpos (shiftpos x n) = Zpos (shiftpos y n)) by congruence.\n  rewrite ! shiftpos_eq in H0.\n  assert (Z.pos x = Z.pos y) by omega.\n  congruence.\nQed.\n\nLemma shiftpos_diff:\n  forall x y n, x <> y -> shiftpos x n <> shiftpos y n.\nProof.\n  intros; red; intros. elim H. eapply shiftpos_inj; eauto.\nQed.\n\nLemma shiftpos_above:\n  forall x n, Ple n (shiftpos x n).\nProof.\n  intros. unfold Ple; zify. rewrite shiftpos_eq. xomega.\nQed.\n\nLemma shiftpos_not_below:\n  forall x n, Plt (shiftpos x n) n -> False.\nProof.\n  intros. generalize (shiftpos_above x n). xomega.\nQed.\n\nLemma shiftpos_below:\n  forall x n, Plt (shiftpos x n) (Pplus x n).\nProof.\n  intros. unfold Plt; zify. rewrite shiftpos_eq. omega.\nQed.\n\nLemma shiftpos_le:\n  forall x y n, Ple x y -> Ple (shiftpos x n) (shiftpos y n).\nProof.\n  intros. unfold Ple in *; zify. rewrite ! shiftpos_eq. omega.\nQed.\n\n\n(** ** Working with the state monad *)\n\nRemark bind_inversion:\n  forall (A B: Type) (f: mon A) (g: A -> mon B)\n         (y: B) (s1 s3: state) (i: sincr s1 s3),\n  bind f g s1 = R y s3 i ->\n  exists x, exists s2, exists i1, exists i2,\n  f s1 = R x s2 i1 /\\ g x s2 = R y s3 i2.\nProof.\n  unfold bind; intros. destruct (f s1). exists x; exists s'; exists I.\n  destruct (g x s'). inv H. exists I0; auto.\nQed.\n\nLtac monadInv1 H :=\n  match type of H with\n  | (R _ _ _ = R _ _ _) =>\n      inversion H; clear H; try subst\n  | (ret _ _ = R _ _ _) =>\n      inversion H; clear H; try subst\n  | (bind ?F ?G ?S = R ?X ?S' ?I) =>\n      let x := fresh \"x\" in (\n      let s := fresh \"s\" in (\n      let i1 := fresh \"INCR\" in (\n      let i2 := fresh \"INCR\" in (\n      let EQ1 := fresh \"EQ\" in (\n      let EQ2 := fresh \"EQ\" in (\n      destruct (bind_inversion _ _ F G X S S' I H) as [x [s [i1 [i2 [EQ1 EQ2]]]]];\n      clear H;\n      try (monadInv1 EQ2)))))))\n  end.\n\nLtac monadInv H :=\n  match type of H with\n  | (ret _ _ = R _ _ _) => monadInv1 H\n  | (bind ?F ?G ?S = R ?X ?S' ?I) => monadInv1 H\n  | (?F _ _ _ _ _ _ _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ _ _ _ _ _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ _ _ _ _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ _ _ _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ _ _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  | (?F _ = R _ _ _) =>\n      ((progress simpl in H) || unfold F in H); monadInv1 H\n  end.\n\nFixpoint mlist_iter2 {A B: Type} (f: A -> B -> mon unit) (l: list (A*B)): mon unit :=\n  match l with\n  | nil => ret tt\n  | (x,y) :: l' => do z <- f x y; mlist_iter2 f l'\n  end.\n\nRemark mlist_iter2_fold:\n  forall (A B: Type) (f: A -> B -> mon unit) l s,\n  exists i,\n  mlist_iter2 f l s =\n  R tt (fold_left (fun a p => match f (fst p) (snd p) a with R _ s2 _ => s2 end) l s) i.\nProof.\n  induction l; simpl; intros.\n  exists (sincr_refl s); auto.\n  destruct a as [x y]. unfold bind. simpl. destruct (f x y s) as [xx s1 i1].\n  destruct (IHl s1) as [i2 EQ]. rewrite EQ. econstructor; eauto.\nQed.\n\nLemma ptree_mfold_spec:\n  forall (A: Type) (f: positive -> A -> mon unit) t s x s' i,\n  ptree_mfold f t s = R x s' i ->\n  exists i', mlist_iter2 f (PTree.elements t) s = R tt s' i'.\nProof.\n  intros.\n  destruct (mlist_iter2_fold _ _ f (PTree.elements t) s) as [i' EQ].\n  unfold ptree_mfold in H. inv H. rewrite PTree.fold_spec.\n  econstructor. eexact EQ.\nQed.\n\n(** ** Relational specification of the translation of moves *)\n\nInductive tr_moves (c: code) : node -> list reg -> list reg -> node -> Prop :=\n  | tr_moves_cons: forall pc1 src srcs dst dsts pc2 pc3,\n      tr_moves c pc1 srcs dsts pc2 ->\n      c!pc2 = Some(Iop Omove (src :: nil) dst pc3) ->\n      tr_moves c pc1 (src :: srcs) (dst :: dsts) pc3\n  | tr_moves_nil: forall srcs dsts pc,\n      srcs = nil \\/ dsts = nil ->\n      tr_moves c pc srcs dsts pc.\n\nLemma add_moves_unchanged:\n  forall srcs dsts pc2 s pc1 s' i pc,\n  add_moves srcs dsts pc2 s = R pc1 s' i ->\n  Plt pc s.(st_nextnode) \\/ Ple s'.(st_nextnode) pc ->\n  s'.(st_code)!pc = s.(st_code)!pc.\nProof.\n  induction srcs; simpl; intros.\n  monadInv H. auto.\n  destruct dsts; monadInv H. auto.\n  transitivity (st_code s0)!pc. eapply IHsrcs; eauto. monadInv EQ; simpl. xomega.\n  monadInv EQ; simpl. apply PTree.gso.\n  inversion INCR0; simpl in *. xomega.\nQed.\n\nLemma add_moves_spec:\n  forall srcs dsts pc2 s pc1 s' i c,\n  add_moves srcs dsts pc2 s = R pc1 s' i ->\n  (forall pc, Ple s.(st_nextnode) pc -> Plt pc s'.(st_nextnode) -> c!pc = s'.(st_code)!pc) ->\n  tr_moves c pc1 srcs dsts pc2.\nProof.\n  induction srcs; simpl; intros.\n  monadInv H. apply tr_moves_nil; auto.\n  destruct dsts; monadInv H. apply tr_moves_nil; auto.\n  apply tr_moves_cons with x. eapply IHsrcs; eauto.\n  intros. inversion INCR. apply H0; xomega.\n  monadInv EQ.\n  rewrite H0. erewrite add_moves_unchanged; eauto.\n  simpl. apply PTree.gss.\n  simpl. xomega.\n  xomega.\n  inversion INCR; inversion INCR0; simpl in *; xomega.\nQed.\n\n(** ** Relational specification of CFG expansion *)\n\nSection INLINING_SPEC.\n\nVariable fenv: funenv.\n\nDefinition context_below (ctx1 ctx2: context): Prop :=\n  Ple (Pplus ctx1.(dreg) ctx1.(mreg)) ctx2.(dreg).\n\nDefinition context_stack_call (ctx1 ctx2: context): Prop :=\n  ctx1.(mstk) >= 0 /\\ ctx1.(dstk) + ctx1.(mstk) <= ctx2.(dstk).\n\nDefinition context_stack_tailcall (ctx1: context) (f: function) (ctx2: context) : Prop :=\n  ctx2.(dstk) = align ctx1.(dstk) (min_alignment f.(fn_stacksize)).\n\nSection INLINING_BODY_SPEC.\n\nVariable stacksize: Z.\n\nInductive tr_instr: context -> node -> instruction -> code -> Prop :=\n  | tr_nop: forall ctx pc c s,\n      c!(spc ctx pc) = Some (Inop (spc ctx s)) ->\n      tr_instr ctx pc (Inop s) c\n  | tr_op: forall ctx pc c op args res s,\n      Ple res ctx.(mreg) ->\n      c!(spc ctx pc) = Some (Iop (sop ctx op) (sregs ctx args) (sreg ctx res) (spc ctx s)) ->\n      tr_instr ctx pc (Iop op args res s) c\n  | tr_load: forall ctx pc c chunk addr args res s,\n      Ple res ctx.(mreg) ->\n      c!(spc ctx pc) = Some (Iload chunk (saddr ctx addr) (sregs ctx args) (sreg ctx res) (spc ctx s)) ->\n      tr_instr ctx pc (Iload chunk addr args res s) c\n  | tr_store: forall ctx pc c chunk addr args src s,\n      c!(spc ctx pc) = Some (Istore chunk (saddr ctx addr) (sregs ctx args) (sreg ctx src) (spc ctx s)) ->\n      tr_instr ctx pc (Istore chunk addr args src s) c\n  | tr_call: forall ctx pc c sg ros args res s,\n      Ple res ctx.(mreg) ->\n      c!(spc ctx pc) = Some (Icall sg (sros ctx ros) (sregs ctx args) (sreg ctx res) (spc ctx s)) ->\n      tr_instr ctx pc (Icall sg ros args res s) c\n  | tr_call_inlined:forall ctx pc sg id args res s c f pc1 ctx',\n      Ple res ctx.(mreg) ->\n      fenv!id = Some f ->\n      c!(spc ctx pc) = Some(Inop pc1) ->\n      tr_moves c pc1 (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)) ->\n      tr_funbody ctx' f c ->\n      ctx'.(retinfo) = Some(spc ctx s, sreg ctx res) ->\n      context_below ctx ctx' ->\n      context_stack_call ctx ctx' ->\n      tr_instr ctx pc (Icall sg (inr _ id) args res s) c\n  | tr_tailcall: forall ctx pc c sg ros args,\n      c!(spc ctx pc) = Some (Itailcall sg (sros ctx ros) (sregs ctx args)) ->\n      ctx.(retinfo) = None ->\n      tr_instr ctx pc (Itailcall sg ros args) c\n  | tr_tailcall_call: forall ctx pc c sg ros args res s,\n      c!(spc ctx pc) = Some (Icall sg (sros ctx ros) (sregs ctx args) res s) ->\n      ctx.(retinfo) = Some(s, res) ->\n      tr_instr ctx pc (Itailcall sg ros args) c\n  | tr_tailcall_inlined: forall ctx pc sg id args c f pc1 ctx',\n      fenv!id = Some f ->\n      c!(spc ctx pc) = Some(Inop pc1) ->\n      tr_moves c pc1 (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)) ->\n      tr_funbody ctx' f c ->\n      ctx'.(retinfo) = ctx.(retinfo) ->\n      context_below ctx ctx' ->\n      context_stack_tailcall ctx f ctx' ->\n      tr_instr ctx pc (Itailcall sg (inr _ id) args) c\n  | tr_builtin: forall ctx pc c ef args res s,\n      match res with BR r => Ple r ctx.(mreg) | _ => True end ->\n      c!(spc ctx pc) = Some (Ibuiltin ef (map (sbuiltinarg ctx) args) (sbuiltinres ctx res) (spc ctx s)) ->\n      tr_instr ctx pc (Ibuiltin ef args res s) c\n  | tr_cond: forall ctx pc cond args s1 s2 c,\n      c!(spc ctx pc) = Some (Icond cond (sregs ctx args) (spc ctx s1) (spc ctx s2)) ->\n      tr_instr ctx pc (Icond cond args s1 s2) c\n  | tr_jumptable: forall ctx pc r tbl c,\n      c!(spc ctx pc) = Some (Ijumptable (sreg ctx r) (List.map (spc ctx) tbl)) ->\n      tr_instr ctx pc (Ijumptable r tbl) c\n  | tr_return: forall ctx pc or c,\n      c!(spc ctx pc) = Some (Ireturn (option_map (sreg ctx) or)) ->\n      ctx.(retinfo) = None ->\n      tr_instr ctx pc (Ireturn or) c\n  | tr_return_inlined: forall ctx pc or c rinfo,\n      c!(spc ctx pc) = Some (inline_return ctx or rinfo) ->\n      ctx.(retinfo) = Some rinfo ->\n      tr_instr ctx pc (Ireturn or) c\n\nwith tr_funbody: context -> function -> code -> Prop :=\n  | tr_funbody_intro: forall ctx f c,\n      (forall r, In r f.(fn_params) -> Ple r ctx.(mreg)) ->\n      (forall pc i, f.(fn_code)!pc = Some i -> tr_instr ctx pc i c) ->\n      ctx.(mstk) = Zmax f.(fn_stacksize) 0 ->\n      (min_alignment f.(fn_stacksize) | ctx.(dstk)) ->\n      ctx.(dstk) >= 0 -> ctx.(dstk) + ctx.(mstk) <= stacksize ->\n      tr_funbody ctx f c.\n\nDefinition fenv_agree (fe: funenv) : Prop :=\n  forall id f, fe!id = Some f -> fenv!id = Some f.\n\nSection EXPAND_INSTR.\n\nVariable fe: funenv.\nHypothesis FE: fenv_agree fe.\n\nVariable rec: forall fe', (size_fenv fe' < size_fenv fe)%nat -> context -> function -> mon unit.\n\nHypothesis rec_unchanged:\n  forall fe' (L: (size_fenv fe' < size_fenv fe)%nat) ctx f s x s' i pc,\n  rec fe' L ctx f s = R x s' i ->\n  Ple ctx.(dpc) s.(st_nextnode) ->\n  Plt pc ctx.(dpc) ->\n  s'.(st_code)!pc = s.(st_code)!pc.\n\nRemark set_instr_other:\n  forall pc instr s x s' i pc',\n  set_instr pc instr s = R x s' i ->\n  pc' <> pc ->\n  s'.(st_code)!pc' = s.(st_code)!pc'.\nProof.\n  intros. monadInv H; simpl. apply PTree.gso; auto.\nQed.\n\nRemark set_instr_same:\n  forall pc instr s x s' i c,\n  set_instr pc instr s = R x s' i ->\n  c!(pc) = s'.(st_code)!pc ->\n  c!(pc) = Some instr.\nProof.\n  intros. rewrite H0. monadInv H; simpl. apply PTree.gss.\nQed.\n\nLemma expand_instr_unchanged:\n  forall ctx pc instr s x s' i pc',\n  expand_instr fe rec ctx pc instr s = R x s' i ->\n  Ple ctx.(dpc) s.(st_nextnode) ->\n  Plt pc' s.(st_nextnode) ->\n  pc' <> spc ctx pc ->\n  s'.(st_code)!pc' = s.(st_code)!pc'.\nProof.\n  generalize set_instr_other; intros A.\n  intros. unfold expand_instr in H; destruct instr; eauto.\n(* call *)\n  destruct (can_inline fe s1). eauto.\n  monadInv H. unfold inline_function in EQ. monadInv EQ.\n  transitivity (s2.(st_code)!pc'). eauto.\n  transitivity (s5.(st_code)!pc'). eapply add_moves_unchanged; eauto.\n    left. inversion INCR5. inversion INCR3. monadInv EQ1; simpl in *. xomega.\n  transitivity (s4.(st_code)!pc'). eapply rec_unchanged; eauto.\n    simpl. monadInv EQ; simpl. monadInv EQ1; simpl. xomega.\n    simpl. monadInv EQ1; simpl. auto.\n  monadInv EQ; simpl. monadInv EQ1; simpl. auto.\n(* tailcall *)\n  destruct (can_inline fe s1).\n  destruct (retinfo ctx) as [[rpc rreg]|]; eauto.\n  monadInv H. unfold inline_tail_function in EQ. monadInv EQ.\n  transitivity (s2.(st_code)!pc'). eauto.\n  transitivity (s5.(st_code)!pc'). eapply add_moves_unchanged; eauto.\n    left. inversion INCR5. inversion INCR3. monadInv EQ1; simpl in *. xomega.\n  transitivity (s4.(st_code)!pc'). eapply rec_unchanged; eauto.\n    simpl. monadInv EQ; simpl. monadInv EQ1; simpl. xomega.\n    simpl. monadInv EQ1; simpl. auto.\n  monadInv EQ; simpl. monadInv EQ1; simpl. auto.\n(* return *)\n  destruct (retinfo ctx) as [[rpc rreg]|]; eauto.\nQed.\n\nLemma iter_expand_instr_unchanged:\n  forall ctx pc l s x s' i,\n  mlist_iter2 (expand_instr fe rec ctx) l s = R x s' i ->\n  Ple ctx.(dpc) s.(st_nextnode) ->\n  Plt pc s.(st_nextnode) ->\n  ~In pc (List.map (spc ctx) (List.map (@fst _ _) l)) ->\n  list_norepet (List.map (@fst _ _) l) ->\n  s'.(st_code)!pc = s.(st_code)!pc.\nProof.\n  induction l; simpl; intros.\n  (* base case *)\n  monadInv H. auto.\n  (* inductive case *)\n  destruct a as [pc1 instr1]; simpl in *.\n  monadInv H. inv H3.\n  transitivity ((st_code s0)!pc).\n  eapply IHl; eauto. destruct INCR; xomega. destruct INCR; xomega.\n  eapply expand_instr_unchanged; eauto.\nQed.\n\nLemma expand_cfg_rec_unchanged:\n  forall ctx f s x s' i pc,\n  expand_cfg_rec fe rec ctx f s = R x s' i ->\n  Ple ctx.(dpc) s.(st_nextnode) ->\n  Plt pc ctx.(dpc) ->\n  s'.(st_code)!pc = s.(st_code)!pc.\nProof.\n  intros. unfold expand_cfg_rec in H. monadInv H. inversion EQ.\n  transitivity ((st_code s0)!pc).\n  exploit ptree_mfold_spec; eauto. intros [INCR' ITER].\n  eapply iter_expand_instr_unchanged; eauto.\n    subst s0; auto.\n    subst s0; simpl. xomega.\n    red; intros. exploit list_in_map_inv; eauto. intros [pc1 [A B]].\n    subst pc. unfold spc in H1. eapply shiftpos_not_below; eauto.\n    apply PTree.elements_keys_norepet.\n  subst s0; auto.\nQed.\n\nHypothesis rec_spec:\n  forall fe' (L: (size_fenv fe' < size_fenv fe)%nat) ctx f s x s' i c,\n  rec fe' L ctx f s = R x s' i ->\n  fenv_agree fe' ->\n  Ple (ctx.(dpc) + max_pc_function f) s.(st_nextnode) ->\n  ctx.(mreg) = max_reg_function f ->\n  Ple (Pplus ctx.(dreg) ctx.(mreg)) s.(st_nextreg) ->\n  ctx.(mstk) >= 0 ->\n  ctx.(mstk) = Zmax (fn_stacksize f) 0 ->\n  (min_alignment (fn_stacksize f) | ctx.(dstk)) ->\n  ctx.(dstk) >= 0 ->\n  s'.(st_stksize) <= stacksize ->\n  (forall pc, Ple ctx.(dpc) pc -> Plt pc s'.(st_nextnode) -> c!pc = s'.(st_code)!pc) ->\n  tr_funbody ctx f c.\n\nRemark min_alignment_pos:\n  forall sz, min_alignment sz > 0.\nProof.\n  intros; unfold min_alignment.\n  destruct (zle sz 1). omega. destruct (zle sz 2). omega. destruct (zle sz 4); omega.\nQed.\n\nLtac inv_incr :=\n  match goal with\n  | [ H: sincr _ _ |- _ ] => destruct H; inv_incr\n  | _ => idtac\n  end.\n\nLemma expand_instr_spec:\n  forall ctx pc instr s x s' i c,\n  expand_instr fe rec ctx pc instr s = R x s' i ->\n  (forall r, instr_defs instr = Some r -> Ple r ctx.(mreg)) ->\n  Plt (spc ctx pc) s.(st_nextnode) ->\n  Ple (ctx.(dreg) + ctx.(mreg)) s.(st_nextreg) ->\n  ctx.(mstk) >= 0 -> ctx.(dstk) >= 0 ->\n  s'.(st_stksize) <= stacksize ->\n  (forall pc', Ple s.(st_nextnode) pc' -> Plt pc' s'.(st_nextnode) -> c!pc' = s'.(st_code)!pc') ->\n  c!(spc ctx pc) = s'.(st_code)!(spc ctx pc) ->\n  tr_instr ctx pc instr c.\nProof.\n  intros until c; intros EXP DEFS OPC OREG STK1 STK2 STK3 S1 S2.\n  generalize set_instr_same; intros BASE.\n  unfold expand_instr in EXP; destruct instr; simpl in DEFS;\n  try (econstructor; eauto; fail).\n(* call *)\n  destruct (can_inline fe s1) as [|id f P Q].\n  (* not inlined *)\n  eapply tr_call; eauto.\n  (* inlined *)\n  subst s1.\n  monadInv EXP. unfold inline_function in EQ; monadInv EQ.\n  set (ctx' := callcontext ctx x1 x2 (max_reg_function f) (fn_stacksize f) n r).\n  inversion EQ0; inversion EQ1; inversion EQ. inv_incr.\n  apply tr_call_inlined with (pc1 := x0) (ctx' := ctx') (f := f); auto.\n  eapply BASE; eauto.\n  eapply add_moves_spec; eauto.\n    intros. rewrite S1. eapply set_instr_other; eauto. unfold node; xomega.\n    xomega. xomega.\n  eapply rec_spec; eauto.\n    red; intros. rewrite PTree.grspec in H. destruct (PTree.elt_eq id0 id); try discriminate. auto.\n    simpl. subst s2; simpl in *; xomega.\n    simpl. subst s3; simpl in *; xomega.\n    simpl. xomega.\n    simpl. apply align_divides. apply min_alignment_pos.\n    assert (dstk ctx + mstk ctx <= dstk ctx'). simpl. apply align_le. apply min_alignment_pos. omega.\n    omega.\n    intros. simpl in H. rewrite S1.\n    transitivity (s1.(st_code)!pc0). eapply set_instr_other; eauto. unfold node in *; xomega.\n    eapply add_moves_unchanged; eauto. unfold node in *; xomega. xomega.\n  red; simpl. subst s2; simpl in *. xomega.\n  red; simpl. split. auto. apply align_le. apply min_alignment_pos.\n(* tailcall *)\n  destruct (can_inline fe s1) as [|id f P Q].\n  (* not inlined *)\n  destruct (retinfo ctx) as [[rpc rreg] | ] eqn:?.\n  (* turned into a call *)\n  eapply tr_tailcall_call; eauto.\n  (* preserved *)\n  eapply tr_tailcall; eauto.\n  (* inlined *)\n  subst s1.\n  monadInv EXP. unfold inline_function in EQ; monadInv EQ.\n  set (ctx' := tailcontext ctx x1 x2 (max_reg_function f) (fn_stacksize f)) in *.\n  inversion EQ0; inversion EQ1; inversion EQ. inv_incr.\n  apply tr_tailcall_inlined with (pc1 := x0) (ctx' := ctx') (f := f); auto.\n  eapply BASE; eauto.\n  eapply add_moves_spec; eauto.\n    intros. rewrite S1. eapply set_instr_other; eauto. unfold node; xomega. xomega. xomega.\n  eapply rec_spec; eauto.\n    red; intros. rewrite PTree.grspec in H. destruct (PTree.elt_eq id0 id); try discriminate. auto.\n    simpl. subst s3; simpl in *. subst s2; simpl in *. xomega.\n    simpl. subst s3; simpl in *; xomega.\n    simpl. xomega.\n    simpl. apply align_divides. apply min_alignment_pos.\n    assert (dstk ctx <= dstk ctx'). simpl. apply align_le. apply min_alignment_pos. omega.\n    omega.\n    intros. simpl in H. rewrite S1.\n    transitivity (s1.(st_code))!pc0. eapply set_instr_other; eauto. unfold node in *; xomega.\n    eapply add_moves_unchanged; eauto. unfold node in *; xomega. xomega.\n  red; simpl.\nsubst s2; simpl in *; xomega.\n  red; auto.\n(* builtin *)\n  eapply tr_builtin; eauto. destruct b; eauto.\n(* return *)\n  destruct (retinfo ctx) as [[rpc rreg] | ] eqn:?.\n  (* inlined *)\n  eapply tr_return_inlined; eauto.\n  (* unchanged *)\n  eapply tr_return; eauto.\nQed.\n\nLemma iter_expand_instr_spec:\n  forall ctx l s x s' i c,\n  mlist_iter2 (expand_instr fe rec ctx) l s = R x s' i ->\n  list_norepet (List.map (@fst _ _) l) ->\n  (forall pc instr r, In (pc, instr) l -> instr_defs instr = Some r -> Ple r ctx.(mreg)) ->\n  (forall pc instr, In (pc, instr) l -> Plt (spc ctx pc) s.(st_nextnode)) ->\n  Ple (ctx.(dreg) + ctx.(mreg)) s.(st_nextreg) ->\n  ctx.(mstk) >= 0 -> ctx.(dstk) >= 0 ->\n  s'.(st_stksize) <= stacksize ->\n  (forall pc', Ple s.(st_nextnode) pc' -> Plt pc' s'.(st_nextnode) -> c!pc' = s'.(st_code)!pc') ->\n  (forall pc instr, In (pc, instr) l -> c!(spc ctx pc) = s'.(st_code)!(spc ctx pc)) ->\n  forall pc instr, In (pc, instr) l -> tr_instr ctx pc instr c.\nProof.\n  induction l; simpl; intros.\n  (* base case *)\n  contradiction.\n  (* inductive case *)\n  destruct a as [pc1 instr1]; simpl in *. inv H0. monadInv H. inv_incr.\n  assert (A: Ple ctx.(dpc) s0.(st_nextnode)).\n    assert (B: Plt (spc ctx pc) (st_nextnode s)) by eauto.\n    unfold spc in B. generalize (shiftpos_above pc (dpc ctx)). xomega.\n  destruct H9. inv H.\n  (* same pc *)\n  eapply expand_instr_spec; eauto.\n  omega.\n  intros.\n    transitivity ((st_code s')!pc').\n    apply H7. auto. xomega.\n    eapply iter_expand_instr_unchanged; eauto.\n    red; intros. rewrite list_map_compose in H9. exploit list_in_map_inv; eauto.\n    intros [[pc0 instr0] [P Q]]. simpl in P.\n    assert (Plt (spc ctx pc0) (st_nextnode s)) by eauto. xomega.\n  transitivity ((st_code s')!(spc ctx pc)).\n    eapply H8; eauto.\n    eapply iter_expand_instr_unchanged; eauto.\n    assert (Plt (spc ctx pc) (st_nextnode s)) by eauto. xomega.\n    red; intros. rewrite list_map_compose in H. exploit list_in_map_inv; eauto.\n    intros [[pc0 instr0] [P Q]]. simpl in P.\n    assert (pc = pc0) by (eapply shiftpos_inj; eauto). subst pc0.\n    elim H12. change pc with (fst (pc, instr0)). apply List.in_map; auto.\n  (* older pc *)\n  inv_incr. eapply IHl; eauto.\n  intros. eapply Plt_le_trans. eapply H2. right; eauto. xomega.\n  intros; eapply Ple_trans; eauto.\n  intros. apply H7; auto. xomega.\nQed.\n\nLemma expand_cfg_rec_spec:\n  forall ctx f s x s' i c,\n  expand_cfg_rec fe rec ctx f s = R x s' i ->\n  Ple (ctx.(dpc) + max_pc_function f) s.(st_nextnode) ->\n  ctx.(mreg) = max_reg_function f ->\n  Ple (ctx.(dreg) + ctx.(mreg)) s.(st_nextreg) ->\n  ctx.(mstk) >= 0 ->\n  ctx.(mstk) = Zmax (fn_stacksize f) 0 ->\n  (min_alignment (fn_stacksize f) | ctx.(dstk)) ->\n  ctx.(dstk) >= 0 ->\n  s'.(st_stksize) <= stacksize ->\n  (forall pc', Ple ctx.(dpc) pc' -> Plt pc' s'.(st_nextnode) -> c!pc' = s'.(st_code)!pc') ->\n  tr_funbody ctx f c.\nProof.\n  intros. unfold expand_cfg_rec in H. monadInv H. inversion EQ.\n  constructor.\n  intros. rewrite H1. eapply max_reg_function_params; eauto.\n  intros. exploit ptree_mfold_spec; eauto. intros [INCR' ITER].\n  eapply iter_expand_instr_spec; eauto.\n    apply PTree.elements_keys_norepet.\n    intros. rewrite H1. eapply max_reg_function_def with (i := instr); eauto.\n    eapply PTree.elements_complete; eauto.\n  intros.\n    assert (Ple pc0 (max_pc_function f)).\n      eapply max_pc_function_sound. eapply PTree.elements_complete; eauto.\n      eapply Plt_le_trans. apply shiftpos_below. subst s0; simpl; xomega.\n  subst s0; simpl; auto.\n  intros. apply H8; auto. subst s0; simpl in H11; xomega.\n  intros. apply H8. apply shiftpos_above.\n  assert (Ple pc0 (max_pc_function f)).\n    eapply max_pc_function_sound. eapply PTree.elements_complete; eauto.\n  eapply Plt_le_trans. apply shiftpos_below. inversion i; xomega.\n  apply PTree.elements_correct; auto.\n  auto. auto. auto.\n  inversion INCR0. subst s0; simpl in STKSIZE; xomega.\nQed.\n\nEnd EXPAND_INSTR.\n\nLemma expand_cfg_unchanged:\n  forall fe ctx f s x s' i pc,\n  expand_cfg fe ctx f s = R x s' i ->\n  Ple ctx.(dpc) s.(st_nextnode) ->\n  Plt pc ctx.(dpc) ->\n  s'.(st_code)!pc = s.(st_code)!pc.\nProof.\n  intros fe0; pattern fe0. apply well_founded_ind with (R := ltof _ size_fenv).\n  apply well_founded_ltof.\n  intros. unfold expand_cfg in H0. rewrite unroll_Fixm in H0.\n  eapply expand_cfg_rec_unchanged; eauto. assumption.\nQed.\n\nLemma expand_cfg_spec:\n  forall fe ctx f s x s' i c,\n  expand_cfg fe ctx f s = R x s' i ->\n  fenv_agree fe ->\n  Ple (ctx.(dpc) + max_pc_function f) s.(st_nextnode) ->\n  ctx.(mreg) = max_reg_function f ->\n  Ple (ctx.(dreg) + ctx.(mreg)) s.(st_nextreg) ->\n  ctx.(mstk) >= 0 ->\n  ctx.(mstk) = Zmax (fn_stacksize f) 0 ->\n  (min_alignment (fn_stacksize f) | ctx.(dstk)) ->\n  ctx.(dstk) >= 0 ->\n  s'.(st_stksize) <= stacksize ->\n  (forall pc', Ple ctx.(dpc) pc' -> Plt pc' s'.(st_nextnode) -> c!pc' = s'.(st_code)!pc') ->\n  tr_funbody ctx f c.\nProof.\n  intros fe0; pattern fe0. apply well_founded_ind with (R := ltof _ size_fenv).\n  apply well_founded_ltof.\n  intros. unfold expand_cfg in H0. rewrite unroll_Fixm in H0.\n  eapply expand_cfg_rec_spec; eauto.\n  simpl. intros. eapply expand_cfg_unchanged; eauto. assumption.\nQed.\n\nEnd INLINING_BODY_SPEC.\n\nEnd INLINING_SPEC.\n\n(** ** Relational specification of the translation of a function *)\n\nInductive tr_function: program -> function -> function -> Prop :=\n  | tr_function_intro: forall p fenv f f' ctx,\n      fenv_compat p fenv ->\n      tr_funbody fenv f'.(fn_stacksize) ctx f f'.(fn_code) ->\n      ctx.(dstk) = 0 ->\n      ctx.(retinfo) = None ->\n      f'.(fn_sig) = f.(fn_sig) ->\n      f'.(fn_params) = sregs ctx f.(fn_params) ->\n      f'.(fn_entrypoint) = spc ctx f.(fn_entrypoint) ->\n      0 <= fn_stacksize f' < Ptrofs.max_unsigned ->\n      tr_function p f f'.\n\nLemma tr_function_linkorder:\n  forall cunit prog f f',\n  linkorder cunit prog ->\n  tr_function cunit f f' ->\n  tr_function prog f f'.\nProof.\n  intros. inv H0. econstructor; eauto. eapply fenv_compat_linkorder; eauto.\nQed.\n\nLemma transf_function_spec:\n  forall cunit f f',\n  transf_function (funenv_program cunit) f = OK f' ->\n  tr_function cunit f f'.\nProof.\n  intros. unfold transf_function in H.\n  set (fenv := funenv_program cunit) in *.\n  destruct (expand_function fenv f initstate) as [ctx s i] eqn:?.\n  destruct (zlt (st_stksize s) Ptrofs.max_unsigned); inv H.\n  monadInv Heqr. set (ctx := initcontext x x0 (max_reg_function f) (fn_stacksize f)) in *.\nOpaque initstate.\n  destruct INCR3. inversion EQ1. inversion EQ.\n  apply tr_function_intro with fenv ctx; auto.\n  apply funenv_program_compat.\n  eapply expand_cfg_spec with (fe := fenv); eauto.\n    red; auto.\n    unfold ctx; rewrite <- H1; rewrite <- H2; rewrite <- H3; simpl. xomega.\n    unfold ctx; rewrite <- H0; rewrite <- H1; simpl. xomega.\n    simpl. xomega.\n    simpl. apply Zdivide_0.\n    simpl. omega.\n  simpl. omega.\n  simpl. split; auto. destruct INCR2. destruct INCR1. destruct INCR0. destruct INCR.\n  simpl. change 0 with (st_stksize initstate). omega.\nQed.\n", "meta": {"author": "CertiKOS", "repo": "compcert.old", "sha": "1fbd4e9beeb9e58b15f7f20ab1c949f6381a4105", "save_path": "github-repos/coq/CertiKOS-compcert.old", "path": "github-repos/coq/CertiKOS-compcert.old/compcert.old-1fbd4e9beeb9e58b15f7f20ab1c949f6381a4105/backend/Inliningspec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.22783372354181658}}
{"text": "From iVM Require Export StateRel.\nRequire Import Coq.Logic.ProofIrrelevance.\n\nUnset Suggest Proof Using.\n\n(** We leave these assumptions abstract in order improve proof search.\n    In Concete.v we have shown that they hold in our standard model. *)\nDeclare Instance MP1: MachineParams1.\nDeclare Instance MP2: MachineParams2.\nInclude CoreRel.\n\n\n(** ** Basic monotonicity *)\n\n(** Additional assumptions *)\nDeclare Instance RM X (RX: Rel X) : Rel (M X).\nDeclare Instance PM : SMonadPropR State M (RM:=RM).\n\nProposition bind_propr'\n            {X Y} {RX: Rel X} {RY: Rel Y}\n            {mx mx': M X} (Hmx: mx ⊑ mx')\n            {f f': X -> M Y} (Hf: f ⊑ f') : mx >>= f ⊑ mx' >>= f'.\nProof.\n  exact (bind_propr State M RX RY mx mx' Hmx f f' Hf).\nQed.\n\nLtac crush0 :=\n  match goal with\n  | [ |- ret _ ⊑ ret _ ] => unshelve eapply ret_propr; [apply PM|]\n  | [|- err ⊑ _] => unshelve eapply err_least, PM\n  | [ |- get ⊑ get ] => unshelve eapply get_propr, PM\n  | [ |- put _ ⊑ put _ ] => unshelve eapply put_propr; [apply PM|]\n\n  | [|- ?x ⊑ ?x] => try reflexivity;\n                  unshelve eapply propR;\n                  match goal with [|- PropR x] => fail end\n\n  | [H : rel eq_relation ?x ?y |- _] => cbv in H; first [subst x|subst y]\n\n  | [|- rel (option_relation _) None _] => exact I\n  | [H: rel (option_relation _) (Some _) None |- _] => destruct H\n  | [x: _ * _ |- _] => destruct x; simpl fst; simpl snd\n  | [H: rel (prod_relation _ _) _ _ |- _] => destruct H\n\n  | [|- rel (fun_relation _ _) ?a _] =>\n    match type of a with\n    | State -> _ =>\n      let x := fresh \"s\" in\n      let y := fresh \"t\" in\n      let Hxy := fresh \"Hst\" in\n      intros x y Hxy\n    | Image _ -> _ =>\n      let x := fresh \"i\" in\n      let y := fresh \"j\" in\n      let Hxy := fresh \"Hij\" in\n      intros x y Hxy\n    | Memory -> _ => (* TODO: Merge with next case *)\n      let x := fresh \"f\" in\n      let y := fresh \"g\" in\n      let Hxy := fresh \"Hfg\" in\n      intros x y Hxy\n    | (_ -> _) -> _ =>\n      let x := fresh \"f\" in\n      let y := fresh \"g\" in\n      let Hxy := fresh \"Hfg\" in\n      intros x y Hxy\n    | _ -> _ =>\n      let x := fresh \"x\" in\n      let y := fresh \"y\" in\n      let Hxy := fresh \"Hxy\" in\n      intros x y Hxy\n    end\n\n  | [|- match ?H with left _ => _ | right _ => _ end ⊑ _] =>\n    let HL := fresh \"HL\" in\n    let HR := fresh \"HR\" in\n    destruct H as [HL|HR]\n\n  | [|- _ ⊑ match ?H with left _ => _ | right _ => _ end] =>\n    let HL := fresh \"HL\" in\n    let HR := fresh \"HR\" in\n    destruct H as [HL|HR]\n\n  | [|- (match ?H with left _ => _ | right _ => _ end) >>= _ ⊑ _] =>\n    let HL := fresh \"HL\" in\n    let HR := fresh \"HR\" in\n    destruct H as [HL|HR];\n    [ repeat rewrite ret_bind\n    | repeat rewrite err_bind ]\n\n  | [|- _ ⊑ (match ?H with left _ => _ | right _ => _ end) >>= _] =>\n    let HL := fresh \"HL\" in\n    let HR := fresh \"HR\" in\n    destruct H as [HL|HR];\n    [ repeat rewrite ret_bind\n    | repeat rewrite err_bind ]\n\n  | [|- match ?H with Some _ => _ | None => _ end ⊑ _] =>\n    let u := fresh \"u\" in\n    let Hu := fresh \"Hu\" in\n    destruct H as [u|] eqn:Hu\n\n  | [|- _ ⊑ match ?H with Some _ => _ | None => _ end] =>\n    let v := fresh \"v\" in\n    let Hv := fresh \"Hv\" in\n    destruct H as [v|] eqn:Hv\n\n  | [|- rel memory_relation _ _] =>\n    let a := fresh \"a\" in\n    let Ha := fresh \"Ha\" in\n    intros a Ha\n\n  | [ |- (_ >>= _) >>= _ ⊑ _ ] => setoid_rewrite bind_assoc\n  | [ |- _ ⊑ (_ >>= _) >>= _ ] => setoid_rewrite bind_assoc\n  | [ |- _ >>= _ ⊑ _ >>= _ ] => apply bind_propr'\n\n  | _ => exact eq_refl\n  | _ => progress unfold PropR\n  end.\n\n(** TODO: Useful? *)\nInstance assume_propr P {DP: Decidable P} : PropR (assume P).\nProof.\n  repeat crush0.\nQed.\n\n\n(** *** Get *)\n\nLocal Ltac get_tactic :=\n  rewrite get_spec; simpl; repeat crush0;\n  match goal with [ H: _ ⊑ _ |- _ ] => srel_destruct H end;\n  try assumption.\n\nInstance getMem_propr : PropR (get' MEM).\nProof. get_tactic. apply Hst_mem. Qed.\n\nInstance getImg_propr : PropR (get' OUT_IMAGE).\nProof. get_tactic. Qed.\n\nInstance getByt_propr: PropR (get' OUT_BYTES).\nProof. get_tactic. Qed.\n\nInstance getChr_propr: PropR (get' OUT_CHARS).\nProof. get_tactic. Qed.\n\nInstance getSnd_propr: PropR (get' OUT_SOUND).\nProof. get_tactic. Qed.\n\nInstance getLog_propr: PropR (get' LOG).\nProof. get_tactic. Qed.\n\nInstance getInp_propr: PropR (get' INP).\nProof. get_tactic. Qed.\n\nInstance getPc_propr: PropR (get' PC).\nProof. get_tactic. Qed.\n\nInstance getSp_propr: PropR (get' SP).\nProof. get_tactic. Qed.\n\n\n(** *** Put *)\n\nLocal Ltac put_tactic :=\n  rewrite put_spec; simpl; repeat crush0;\n  match goal with [ H: _ ⊑ _ |- _ ] => srel_destruct H end;\n  repeat split;\n  unfold lens_relation;\n  repeat (lens_rewrite1 || simpl);\n  reflexivity || assumption.\n\nInstance putMem_propr : PropR (put' MEM).\nProof. put_tactic. Qed.\n\nInstance putImg_propr : PropR (put' OUT_IMAGE).\nProof. put_tactic. Qed.\n\nInstance putByt_propr: PropR (put' OUT_BYTES).\nProof. put_tactic. Qed.\n\nInstance putChr_propr: PropR (put' OUT_CHARS).\nProof. put_tactic. Qed.\n\nInstance putSnd_propr: PropR (put' OUT_SOUND).\nProof. put_tactic. Qed.\n\nInstance putLog_propr: PropR (put' LOG).\nProof. put_tactic. Qed.\n\nInstance putInp_propr: PropR (put' INP).\nProof. put_tactic. Qed.\n\nInstance putPc_propr: PropR (put' PC).\nProof. put_tactic. Qed.\n\nInstance putSp_propr: PropR (put' SP).\nProof. put_tactic. Qed.\n\n\n(** *** Crush *)\n\nLtac crush1 :=\n  match goal with\n  | [|- put' MEM _ ⊑ put' MEM _] => unshelve eapply putMem_propr\n  | [|- put' OUT_IMAGE _ ⊑ put' OUT_IMAGE _] => unshelve eapply putImg_propr\n  | [|- put' OUT_BYTES _ ⊑ put' OUT_BYTES _] => unshelve eapply putByt_propr\n  | [|- put' OUT_CHARS _ ⊑ put' OUT_CHARS _] => unshelve eapply putChr_propr\n  | [|- put' OUT_SOUND _ ⊑ put' OUT_SOUND _] => unshelve eapply putSnd_propr\n  | [|- put' LOG _ ⊑ put' LOG _] => unshelve eapply putLog_propr\n  | [|- put' INP _ ⊑ put' INP _] => unshelve eapply putInp_propr\n  | [|- put' PC _ ⊑ put' PC _] => unshelve eapply putPc_propr\n  | [|- put' SP _ ⊑ put' SP _] => unshelve eapply putSp_propr\n\n  | _ => crush0\n  end.\n\nLtac crush := repeat crush1.\n\nInstance pointwise_propr {X Y} (f: X -> Y) {RY: Rel Y} (H: forall x, PropR (f x)) : PropR f.\nProof. crush. Qed.\n\n(** In other words, there is no less of generality instatiating\narguments for which the relation is simply [eq]. On the contrary, this\nimproves proof search. *)\n\n\n(** ** Monotone operations *)\n\nInstance extr_propr {X} {RX: Rel X} : PropR (extr (X:=X)).\nProof.\n  rewrite extr_spec.\n  crush.\n  exact Hxy.\nQed.\n\nInstance load_propr a : PropR (load a).\nProof.\n  rewrite load_spec.\n  crush.\n  apply extr_propr, Hfg.\nQed.\n\nInstance loadMany_propr n a : PropR (loadMany n a).\nProof.\n  revert a; induction n; intros a; simp loadMany; crush.\nQed.\n\nInstance next_propr n : PropR (next n).\nProof. induction n; simp next; crush. Qed.\n\nInstance store_propr a o : PropR (store a o).\nProof.\n  rewrite store_spec.\n  crush.\n  apply Hfg.\nQed.\n\nInstance storeMany_propr a lst : PropR (storeMany a lst).\nProof.\n  revert a.\n  induction lst as [|x r IH]; intros a;\n    simp storeMany; crush.\nQed.\n\nInstance push_propr u : PropR (push u).\nProof.\n  rewrite push_spec.\n  crush.\nQed.\n\nInstance pushManyR_propr u : PropR (pushManyR u).\nProof.\n  induction u; simp pushManyR; crush.\nQed.\n\nInstance pushMany_propr u : PropR (pushMany u).\nProof. rewrite pushMany_spec. crush. Qed.\n\nInstance pop_propr : PropR pop.\nProof.\n  rewrite pop_spec. crush.\nQed.\n\nInstance popMany_propr n : PropR (popMany n).\nProof.\n  induction n; simp popMany; crush.\nQed.\n\nInstance pop64_propr: PropR pop64.\nProof. unfold pop64. crush. Qed.\n\nInstance pushZ_propr z: PropR (pushZ z).\nProof. unfold pushZ. crush. Qed.\n\nInstance storeZ_propr n a z : PropR (storeZ n a z).\nProof. unfold storeZ. crush. Qed.\n\nLocal Open Scope N.\n\nInstance setPixel_propr x y c : PropR (setPixel x y c).\nProof.\n  rewrite setPixel_spec. unfold updatePixel.\n  crush;\n    destruct Hij as [Hw [Hh Hi]];\n    [ | congruence | congruence ].\n  exists Hw. exists Hh. intros x' Hx' y' Hy'. simpl.\n  destruct (decide (x' = x /\\ y' = y)).\n  - reflexivity.\n  - exact (Hi x' Hx' y' Hy').\nQed.\n\nInstance readPixel_propr x y : PropR (readPixel x y).\nProof. rewrite readPixel_spec. crush. Qed.\n\nLemma image_complete_lemma\n      {i i': Image (option OutputColor)}\n      (Hi: i ⊑ i') (Hc: image_complete i) : i = i'.\nProof.\n  destruct i as [w h p].\n  destruct i' as [w' h' p'].\n  destruct Hi as [Hw [Hh Hp]].\n  simpl in *. subst w'. subst h'.\n  apply f_equal.\n  extensionality x. extensionality Hx.\n  extensionality y. extensionality Hy.\n  specialize (Hp x Hx y Hy). simpl in Hp.\n  specialize (Hc x Hx y Hy). simpl in Hc.\n  rewrite <- (some_extract Hc) in *.\n  destruct (p' x Hx y Hy) as [c'|].\n  - unfold rel in Hp.\n    destruct (extract Hc) as [[r g] b].\n    destruct c' as [[r' g'] b'].\n    cbn in Hp.\n    destruct Hp as [[Hr Hg] Hb].\n    crush.\n  - crush.\nQed.\n\nInstance newFrame_propr w h r: PropR (newFrame w h r).\nProof.\n  rewrite newFrame_spec, extractImage_spec.\n  crush; destruct (image_complete_lemma Hij HL).\n  - destruct (proof_irrelevance _ HL HL0). reflexivity.\n  - contradict HR. exact HL.\nQed.\n\nClose Scope N.\n\n\n(** ** Monotone steps *)\n\n#[global] Instance oneStep_propr : PropR oneStep.\nProof.\n  unfold oneStep. crush.\n  destruct (y: Z) eqn:Hy;\n    [ crush; reflexivity | | simp oneStep'; crush].\n\n  (* Is there a more elegant way to do this. *)\n  unfold oneStep'.\n  repeat (match goal with\n            [|- context [match _ with xI _ => _ | xO _ => _ | xH => _ end]] =>\n            destruct p end).\n  all:\n    try rewrite putByte_spec;\n    try rewrite putChar_spec;\n    try rewrite addSample_spec;\n    try rewrite readFrame_spec;\n    crush.\nQed.\n\n#[global] Instance nSteps_propr n : PropR (nSteps n).\nProof.\n  induction n; simp nSteps; unfold chain; crush.\n  destruct y; crush.\nQed.\n", "meta": {"author": "immortalvm", "repo": "ivm-formal-proofs", "sha": "102f767333237f8a486d8b6338a7773938f46004", "save_path": "github-repos/coq/immortalvm-ivm-formal-proofs", "path": "github-repos/coq/immortalvm-ivm-formal-proofs/ivm-formal-proofs-102f767333237f8a486d8b6338a7773938f46004/Mono.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.22773539795792525}}
{"text": "(** This module proves that the stream transducer semantics defined in\nmodule [Streams] is safe (cf. Theorem 3.2 in the paper). *)\n\n\nFrom Coq Require Import Program.Equality Omega.\nFrom SimplyRatt Require Export Streams FundamentalProperty.\n\nFrom SimplyRatt Require Import Tactics.\n\nImport ListNotations.\n\n(** This is part (i) of Theorem 3.2 in the paper. *)\nTheorem causality1 A B k t :\n  vtype A ->\n  ctx_empty ⊢ t ∶ Box (Arrow (Str A) (Str B)) ->\n  trrel A B k (app (unbox t) (adv (ref thel)),heap_empty).\nProof.\n  intros VTA Ty. constructor; eauto using closed_heap_empty, typed_closed, heap_empty_fresh.\n  intros v w V W.\n  assert (ctx_lock ctx_empty ⊢ unbox t ∶ Arrow (Str A) (Str B)) as Ty' by eauto.\n  eapply fund_prop with (g:= nil) (Hs := (str_heapseq A k))\n                        (s := store_lock (Some (heap_single thel (v ∷ ref thel)))\n                                         (heap_single thel (w ∷ ref thel)))\n    in Ty';eauto. rewrite sub_empty_app in Ty' by auto. eapply trel_app;\n  eauto using typed_closed. eapply trel_adv. auto using mapsto_heap_cons.\n  apply vrel_trel. autorewrite with vrel. eexists. split. reflexivity. simpl.\n  autorewrite with vrel. do 2 eexists. split. reflexivity. split.\n  rewrite vtype_tsubst by auto. eauto using vtype_vrel.\n  eapply vrel_mono; try eapply thel_vrel;eauto.\n  eapply crel_lock;eauto using str_heapseq_closed.\n  eauto using str_heapseq_closed.\n  constructor;  eauto using vtype_vrel_closed,closed_heap_alloc, closed_heap_empty.\nQed.\n\n(** This is part (ii) of Theorem 3.2 in the paper. *)\nTheorem causality2 A B k s v :\n  vtype A -> isvalue v -> ctx_empty ⊢ v ∶ A -> \n  trrel A B (S k) s -> exists v' s', tred s v v' s' /\\ trrel A B k s'.\nProof.\n  intros VTA V Ty TR. inversion TR;subst.\n  apply typing_vtype with (Hs:=[]) (s:=store_bot) in Ty; eauto.\n  pose (vtype_inhab _ VTA) as W. destruct W as (w&W).\n  assert (exists (v' : term) (s : store),\n  {t, (store_lock (Some (heap_cons h thel (v ∷ ref thel))) (heap_single thel (w ∷ ref thel)))}⇓ {v', s} /\\\n  vrel Str (B) (str_heapseq (A) (S k)) s v') as Red.\n  eapply H1 with (v:=v); try eassumption;eauto using tick_le_refl,str_heapseq_closed.\n  constructor; eauto using vtype_vrel_closed,closed_heap_alloc,closed_heap_empty.\n\n  destruct Red as (v'& s&R&VR).\n  \n  pose (red_extensive _ _ _ _ R) as SL. dependent destruction SL. \n  eapply red_not_later with (u:=unit) in R; eauto using heap_dom_cons'.\n  rewrite heap_cons_eq in R.\n  autorewrite with vrel in VR. simpl in VR. destruct VR as (v'' & E & VR). subst.\n  autorewrite with vrel in VR. simpl in VR. destruct VR as (v1 & v2 & E & VR). subst.\n  \n  do 2 eexists. split. econstructor. apply R. constructor.\n  - assert (heap_mapsto thel (w ∷ ref thel) h2') by eauto using mapsto_heap_cons.\n    assert (closed_term (w ∷ ref thel)) by eauto using vtype_vrel_closed.\n    assert (closed_heap (heap_cons h2' thel unit)). apply red_closed in R;eauto.\n    destruct R as [C1 C2]. inversion C2. auto.\n    constructor;eauto using closed_heap_empty,closed_heap_alloc,vtype_vrel_closed.\n    eauto using closed_heap_cons_rev.\n  - destruct VR; eauto using vrel_delay_closed. \n  - intros. \n\n    assert (exists (v' : term) (s : store),\n               {t, (store_lock (Some (heap_cons h thel (v ∷ ref thel))) (heap_single thel (v0 ∷ ref thel)))}⇓ {v', s} /\\\n               vrel Str (B) (str_heapseq (A) (S k)) s v') as Red2.\n\n    eapply H1 with (v:=v) (w:=v0); try eassumption;eauto using tick_le_refl,str_heapseq_closed.\n  constructor; eauto using vtype_vrel_closed,closed_heap_alloc,closed_heap_empty.\n  \n  destruct Red2 as (v'& s&R'&VR').\n\n  pose (red_extensive _ _ _ _ R') as SL. dependent destruction SL. \n  eapply red_not_later with (u:=unit) in R'; eauto using heap_dom_cons'.\n  rewrite heap_cons_eq in R'.\n\n  pose (red_determ _ _ _ _ _ _ R R') as D. destruct D as [E D]. subst.\n  dependent destruction D.\n\n  autorewrite with vrel in VR'. simpl in VR'. destruct VR' as (v'' & E & VR'). subst.\n  autorewrite with vrel in VR'. simpl in VR'. destruct VR' as (v1' & v2' & E' & VR1 & VR2). subst.\n  dependent destruction E.\n  autorewrite with vrel in VR2.  autodest. simpl in H11.\n  assert (heap_cons h2' thel (v0 ∷ ref thel) = h2'0) as HR by\n        (eapply heap_overwrite; eauto using mapsto_heap_cons). \n  rewrite HR.\n  dependent destruction H9. eapply trel_adv;eauto.\n  eapply H10. constructor. eauto using vtype_vrel_closed. assumption. \nQed.", "meta": {"author": "pa-ba", "repo": "simply-ratt", "sha": "f0732830bb9ff082f3a1770967be6c9cf9b367e8", "save_path": "github-repos/coq/pa-ba-simply-ratt", "path": "github-repos/coq/pa-ba-simply-ratt/simply-ratt-f0732830bb9ff082f3a1770967be6c9cf9b367e8/theories/Causality.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.22773539795792522}}
{"text": "(******************************************************************************)\n(* PipeCheck: Specifying and Verifying Microarchitectural                     *)\n(* Enforcement of Memory Consistency Models                                   *)\n(*                                                                            *)\n(* Copyright (c) 2014 Daniel Lustig, Princeton University                     *)\n(* All rights reserved.                                                       *)\n(*                                                                            *)\n(* This library is free software; you can redistribute it and/or              *)\n(* modify it under the terms of the GNU Lesser General Public                 *)\n(* License as published by the Free Software Foundation; either               *)\n(* version 2.1 of the License, or (at your option) any later version.         *)\n(*                                                                            *)\n(* This library is distributed in the hope that it will be useful,            *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of             *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU          *)\n(* Lesser General Public License for more details.                            *)\n(*                                                                            *)\n(* You should have received a copy of the GNU Lesser General Public           *)\n(* License along with this library; if not, write to the Free Software        *)\n(* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  *)\n(* USA                                                                        *)\n(******************************************************************************)\n\nRequire Import List.\nImport ListNotations.\nRequire Import util2.\nRequire Import Ascii.\nRequire Import String.\n\n(* ** GraphTree\n\nA [GraphTree] is a data structure which is used to represent a set of\n  graphs that are mostly similar, but with a few small differences.  For\n  example, suppose we want to represent two graphs: one which adds an edge e1\n  to a graph G, and another which adds a different edge e2 to G.  Rather than\n  representing these as {G + e1, G + e2}, a [GraphTree] would represent them\n  as G + {e1 or e2}.\n\n  The motivation for a [GraphTree] is to more easily represent the case in\n  which, for example, a litmus test outcome may be observable in any one of\n  a number of possible graphs, some of which will generally look very similar.\n  *)\nInductive GraphTree (A : Type) : Type :=\n  | GraphTreeOr   : list (GraphTree A) -> GraphTree A\n  | GraphTreeAnd  : list (GraphTree A) -> GraphTree A\n  | GraphTreeLeaf : string -> list (A * A * string) -> GraphTree A.\n\nOpen Scope string_scope.\nOpen Scope list_scope.\n\nDefinition GraphTreeEmptyLeaf {A : Type} := GraphTreeLeaf A \"\" [].\n\n(** The [DNFOfTree] of a [GraphTree] is an explicit list of the graphs\n  represented by the tree, i.e., no longer in the compacted [GraphTree]\n  format. *)\nFixpoint DNFOfTree {A : Type}\n  (t : GraphTree A)\n  : list (string * list (A * A * string)) :=\n  let joinGraphs {A : Type}\n    (a b : string * list (A * A * string))\n    : string * list (A * A * string) :=\n    let (an, al) := a in\n    let (bn, bl) := b in\n    (append an bn, al ++ bl)\n  in\n  match t with\n  | GraphTreeOr l =>\n    fold_left (app (A:=_)) (map DNFOfTree l) []\n  | GraphTreeAnd l =>\n    let l' := map DNFOfTree l in\n    map (fun x => fold_left joinGraphs x (\"\", [])) (CartesianProduct l')\n  | GraphTreeLeaf n g => [(n, g)]\n  end.\n\n(** [GraphTreeSimplify] tries to represent a [GraphTree] in a simpler but\n  equivalent form.  It does not guarantee minimality. *)\nFixpoint GraphTreeSimplify {A : Type}\n  (g : GraphTree A)\n  : GraphTree A :=\n  match g with\n  | GraphTreeOr    [x] => GraphTreeSimplify x\n  | GraphTreeOr     l  => GraphTreeOr _ (map GraphTreeSimplify l)\n  | GraphTreeAnd   [x] => GraphTreeSimplify x\n  | GraphTreeAnd    l  => GraphTreeAnd _ (map GraphTreeSimplify l)\n  | _ => g\n  end.\n\nLemma SimplifiedDNF {A : Type} : forall (g : GraphTree A),\n  DNFOfTree (GraphTreeSimplify g) = DNFOfTree g.\nProof.\n(* TODO: http://adam.chlipala.net/cpdt/html/InductiveTypes.html *)\nAbort.\n\n(** [TreeOfDNF] converts a list of graphs into [GraphTree] representation. *)\nDefinition TreeOfDNF {A : Type}\n  (l : list (string * list (A * A * string)))\n  : GraphTree A :=\n  let f x := GraphTreeLeaf _ (fst x) (snd x) in\n  GraphTreeSimplify (GraphTreeOr _ (map f l)).\n\nLemma fold1 {A : Type} : forall l (x : list A),\n  fold_left (app (A:=_)) l x = x ++ fold_left (app (A:=_)) l [].\nProof.\n  intros l.  induction l.\n    intros x.  simpl.  rewrite app_nil_r.  auto.\n  intros x.  simpl.  rewrite IHl.  symmetry.  rewrite IHl.\n  rewrite app_assoc.  auto.\nQed.\n\nLemma fold2 {A : Type} : forall l (xh : A) (xt : list A),\n  fold_left (app (A:=_)) l (xh::xt) = xh :: fold_left (app (A:=_)) l xt.\nProof.\nAdmitted.\n\nLemma DNFIdempotent {A : Type} :\n  forall x,\n  forall (l : list (string * list (A * A * string))),\n  In x l -> In x (DNFOfTree (TreeOfDNF l)).\nProof.\n  intros x.  induction l as [|lh lt].\n    auto.\n  intros Hx.  destruct Hx as [Hx|Hx].\n    rewrite Hx in *; clear Hx.\n    unfold TreeOfDNF.  unfold map.  unfold GraphTreeSimplify.  simpl.\n    destruct lt.\n      simpl.  left.  destruct x; auto.\n    simpl.  rewrite fold1.  left.  destruct x; auto.\n  apply IHlt in Hx.  clear IHlt.\n  \n  destruct lt.\n    inversion Hx.\n  simpl.  rewrite fold2.  right.\n  destruct lt as [|lth ltt].\n    simpl in *.  auto.\n  simpl in *.  auto.\nQed.\n\nModule TreeExample.\n\nExample e1 :\n  DNFOfTree\n  (GraphTreeAnd _ [\n    GraphTreeLeaf _ \"A\" [(1, 2, \"a\")];\n    GraphTreeLeaf _ \"B\" [(3, 4, \"b\")]\n  ])\n  = [(\"AB\", [(1, 2, \"a\"); (3, 4, \"b\")])].\nProof.\ncbv.  auto.\nQed.\n\nExample e2 :\n  DNFOfTree\n  (GraphTreeAnd _ [\n    GraphTreeLeaf _ \"A\" [(1, 2, \"a\")];\n    GraphTreeOr _ [\n      GraphTreeLeaf _ \"B\" [(3, 4, \"b\")];\n      GraphTreeLeaf _ \"C\" [(5, 6, \"c\")]\n    ]\n  ])\n  = [(\"AB\", [(1, 2, \"a\"); (3, 4, \"b\")]); (\"AC\", [(1, 2, \"a\"); (5, 6, \"c\")])].\nProof.\ncbv.  auto.\nQed.\n\nExample e3 :\n  DNFOfTree\n  (GraphTreeAnd _ [\n    GraphTreeLeaf _ \"A\" [(1, 2, \"a\")];\n    GraphTreeLeaf _ \"B\" [(7, 8, \"d\")];\n    GraphTreeOr _ [\n      GraphTreeLeaf _ \"C\" [(3, 4, \"b\")];\n      GraphTreeLeaf _ \"D\" [(5, 6, \"c\")]\n    ]\n  ])\n  = [(\"ABC\", [(1, 2, \"a\"); (7, 8, \"d\"); (3, 4, \"b\")]);\n     (\"ABD\", [(1, 2, \"a\"); (7, 8, \"d\"); (5, 6, \"c\")])].\nProof.\ncbv.  auto.\nQed.\n\nExample e4 :\n  DNFOfTree\n  (GraphTreeAnd _ [\n    GraphTreeLeaf _ \"A\" [(1, 2, \"a\")];\n    GraphTreeAnd _ [\n      GraphTreeEmptyLeaf;\n      GraphTreeLeaf _ \"B\" [(3, 4, \"b\")]\n    ]\n  ])\n  = [(\"AB\", [(1, 2, \"a\"); (3, 4, \"b\")])].\nProof.\ncbv.  auto.\nQed.\n\nExample e5 :\n  DNFOfTree\n  (GraphTreeAnd _ [\n    GraphTreeLeaf _ \"A\" [(1, 2, \"a\")];\n    GraphTreeOr _ []\n  ])\n  = [].\nProof.\nunfold DNFOfTree.  unfold map.\ncbv.  auto.\nQed.\n\nEnd TreeExample.\n\nDefinition DNFStringOfTree' {A : Type}\n  (print_node : A -> string)\n  (e : A * A * string)\n  : string :=\n  let (sd, label) := e in\n  let (s, d) := sd in\n  fold_left append [\": \"; print_node s; \"-\"; label; \"->\"; print_node d; \" \"] \"\".\n\nFixpoint DNFStringOfTree {A : Type}\n  (print_node : A -> string)\n  (t : GraphTree A)\n  : string :=\n  let f_fold a b := append b (append \"-\" a) in\n  match t with\n  | GraphTreeOr l =>\n    append \"Or(\" (append (fold_left f_fold (map (DNFStringOfTree print_node) l) \"\") \")\")\n  | GraphTreeAnd l =>\n    append \"And(\" (append (fold_left f_fold (map (DNFStringOfTree print_node) l) \"\") \")\")\n  | GraphTreeLeaf n l => fold_left append (map (DNFStringOfTree' print_node) l) n\n  end.\n\nClose Scope string_scope.\n\nFixpoint GraphTreeMap {A B : Type}\n  (f : A -> B)\n  (g : GraphTree A)\n  : GraphTree B :=\n  match g with\n  | GraphTreeAnd    l => GraphTreeAnd  _ (map (GraphTreeMap f) l)\n  | GraphTreeOr     l => GraphTreeOr   _ (map (GraphTreeMap f) l)\n  | GraphTreeLeaf n l =>\n    let f' x := (f (fst (fst x)), f (snd (fst x)), snd x) in\n    GraphTreeLeaf _ n (map f' l)\n  end.\n\nFixpoint GraphTreeMapPair {A B : Type}\n  (f : A * A * string -> B * B * string)\n  (g : GraphTree A)\n  : GraphTree B :=\n  match g with\n  | GraphTreeAnd    l => GraphTreeAnd  _ (map (GraphTreeMapPair f) l)\n  | GraphTreeOr     l => GraphTreeOr   _ (map (GraphTreeMapPair f) l)\n  | GraphTreeLeaf n l =>\n    GraphTreeLeaf _ n (map f l)\n  end.\n\n\n", "meta": {"author": "daniellustig", "repo": "pipecheck", "sha": "7b70b585be8c0a946869e991f459c57c29f73c9b", "save_path": "github-repos/coq/daniellustig-pipecheck", "path": "github-repos/coq/daniellustig-pipecheck/pipecheck-7b70b585be8c0a946869e991f459c57c29f73c9b/tree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2277353979579252}}
{"text": "(* Copyright (c) 2012-2015, Robbert Krebbers. *)\n(* This file is distributed under the terms of the BSD license. *)\nRequire Import Qcanon.\nRequire Export base orders separation_instances.\nLocal Open Scope Qc_scope.\n\n(**\nConcrete permissions are built from more primitive combinators:\n- [lockable]: [Locked] describes that the object has been locked due to\n  a sequenced write, and [Unlocked] means that it is not locked\n- [counter] is to account for tokens to keep track of parts of the memory\n  that are addresseble.\n*)\nDefinition perm := (lockable (counter Qcanon.Qc) + Qcanon.Qc)%type.\n#[global] Instance perm_sep_ops : SeparationOps perm := _.\n#[global] Instance perm_sep : Separation perm := _.\nTypeclasses Opaque perm.\nGlobal Hint Extern 0 (Separation _) => apply (_ : Separation perm): core.\n\nDefinition perm_readonly : perm := inr 1.\nDefinition perm_full : perm := inl (LUnlocked (Counter 0 1)).\nDefinition perm_token : perm := inl (LUnlocked (Counter (-1) ∅)).\n\nInductive pkind :=\n  Writable | Readable | Locked | Existing.\n#[global] Instance pkind_dec (k1 k2 : pkind) : Decision (k1 = k2).\nProof. solve_decision. Defined.\n#[global] Instance pkind_subseteq : SubsetEq pkind := λ k1 k2,\n  match k1, k2 with\n  | _, Writable => True\n  | (Existing | Readable), Readable => True\n  | Existing, Existing => True\n  | (Existing | Locked), Locked => True\n  | _, _ => False\n  end.\n#[global] Instance pkind_subseteq_dec : ∀ k1 k2 : pkind, Decision (k1 ⊆ k2).\nProof. intros [] []; apply _. Defined.\n#[global] Instance: PartialOrder (@subseteq pkind _).\nProof. by repeat split; repeat intros []. Qed.\n#[global] Instance option_pkind_subseteq : SubsetEq (option pkind) := λ k1 k2,\n  match k1, k2 with\n  | Some k1, Some k2 => k1 ⊆ k2 | None, _ => True | Some _, None => False\n  end.\n#[global] Instance option_pkind_subseteq_dec : ∀ k1 k2 : option pkind, Decision (k1 ⊆ k2).\nProof. intros [] []; apply _. Defined.\n#[global] Instance: PartialOrder (@subseteq (option pkind) _).\nProof. by repeat split; repeat intros []; try destruct p; try destruct p0; try destruct p1. Qed.\n\nDefinition perm_kind (γ : perm) : option pkind :=\n  match γ with\n  | inl (LUnlocked (Counter x' y')) =>\n     if decide (y' = ∅) then\n       if decide (x' = 0) then None else Some Existing\n     else if decide (y' = 1) then Some Writable else Some Readable\n  | inl (LLocked _) => Some Locked\n  | inr x' => Some Readable\n  end.\nDefinition perm_locked (γ : perm) : bool :=\n  match γ with inl (LLocked _) => true | _ => false end.\nDefinition perm_lock (γ : perm) : perm :=\n  match γ with inl (LUnlocked x') => inl (LLocked x') | _ => γ end.\nDefinition perm_unlock (γ : perm) : perm :=\n  match γ with inl (LLocked x') => inl (LUnlocked x') | _ => γ end.\n\nInductive perm_kind_view : perm → option pkind → Prop :=\n  | perm_kind_None : perm_kind_view (inl (LUnlocked (Counter ∅ 0))) None\n  | perm_kind_Locked x' : perm_kind_view (inl (LLocked x')) (Some Locked)\n  | perm_kind_Existing x' :\n     x' ≠ 0 → perm_kind_view (inl (LUnlocked (Counter x' ∅))) (Some Existing)\n  | perm_kind_Readable x' y' :\n     y' ≠ ∅ → y' ≠ 1 →\n     perm_kind_view (inl (LUnlocked (Counter x' y'))) (Some Readable)\n  | perm_kind_Writable x' :\n     perm_kind_view (inl (LUnlocked (Counter x' 1))) (Some Writable)\n  | perm_kind_Writable' x' :\n     x' ≠ 0 → perm_kind_view (inl (LUnlocked (Counter x' 1))) (Some Writable)\n  | perm_kind_ro_Readable x' : perm_kind_view (inr x') (Some Readable).\nLemma perm_kind_spec γ : perm_kind_view γ (perm_kind γ).\nProof.\n  destruct γ as [[[]|[]]|]; simpl; repeat case_decide;\n    intuition; simplify_equality'; constructor; auto.\nQed.\nArguments perm_kind _ : simpl never.\n\nLemma perm_full_valid : sep_valid perm_full.\nProof. done. Qed.\nLemma perm_full_mapped : ¬sep_unmapped perm_full.\nProof. by apply (bool_decide_unpack _). Qed.\nLemma perm_full_unshared : sep_unshared perm_full.\nProof. by apply (bool_decide_unpack _). Qed.\nLemma perm_subseteq_full γ1 γ2 : γ1 = perm_full → γ1 ⊆ γ2 → γ2 = perm_full.\nProof.\n  intros ->; destruct γ2 as [[[??]|[c x]]|?];\n    repeat sep_unfold; unfold perm_full; intuition; simplify_equality.\n  assert (x = 1) as -> by eauto using Qcle_antisym.\n  by assert (c = 0) as -> by eauto using Qcle_antisym.\nQed.\nLemma perm_readonly_valid : sep_valid perm_readonly.\nProof. done. Qed.\nLemma perm_readonly_mapped : ¬sep_unmapped perm_readonly.\nProof. by apply (bool_decide_unpack _). Qed.\nLemma perm_token_valid : sep_valid perm_token.\nProof. done. Qed.\nLemma perm_locked_mapped γ : perm_locked γ = true → ¬sep_unmapped γ.\nProof. destruct γ as [[[]|]|[]]; repeat sep_unfold; naive_solver. Qed.\nLemma perm_Readable_locked γ :\n  Some Readable ⊆ perm_kind γ → perm_locked γ = false.\nProof. by destruct (perm_kind_spec γ). Qed.\nLemma perm_locked_lock γ :\n  Some Writable ⊆ perm_kind γ → perm_locked (perm_lock γ) = true.\nProof. by destruct (perm_kind_spec γ). Qed.\nLemma perm_locked_unlock γ : perm_locked (perm_unlock γ) = false.\nProof. by destruct γ as [[]|[]]. Qed.\nLemma perm_lock_valid γ :\n  sep_valid γ → Some Writable ⊆ perm_kind γ → sep_valid (perm_lock γ).\nProof. destruct (perm_kind_spec γ); repeat sep_unfold; intuition. Qed.\nLemma perm_lock_empty γ : perm_lock γ = ∅ → γ = ∅.\nProof. by destruct γ as [[]|?]. Qed.\nLemma perm_lock_unmapped γ :\n  Some Writable ⊆ perm_kind γ → sep_unmapped γ → sep_unmapped (perm_lock γ).\nProof. destruct (perm_kind_spec γ); repeat sep_unfold; naive_solver. Qed.\nLemma perm_lock_mapped γ : sep_unmapped (perm_lock γ) → sep_unmapped γ.\nProof. destruct γ as [[]|[]]; repeat sep_unfold; intuition. Qed.\nLemma perm_lock_unshared γ : sep_unshared γ → sep_unshared (perm_lock γ).\nProof. destruct γ as [[]|[]]; repeat sep_unfold; intuition. Qed.\nLemma perm_unlock_lock γ :\n  sep_valid γ → Some Writable ⊆ perm_kind γ → perm_unlock (perm_lock γ) = γ.\nProof. by destruct (perm_kind_spec γ). Qed.\nLemma perm_unlock_unlock γ : perm_unlock (perm_unlock γ) = perm_unlock γ.\nProof. by destruct γ as [[]|]. Qed.\nLemma perm_unlock_valid γ : sep_valid γ → sep_valid (perm_unlock γ).\nProof. destruct γ as [[[]|[]]|]; repeat sep_unfold; naive_solver. Qed.\nLemma perm_unlock_empty γ : sep_valid γ → perm_unlock γ = ∅ → γ = ∅.\nProof. destruct γ as [[]|?]; repeat sep_unfold; naive_solver. Qed.\nLemma perm_unlock_unmapped γ : sep_unmapped γ → sep_unmapped (perm_unlock γ).\nProof. destruct γ as [[[]|[]]|]; repeat sep_unfold; intuition. Qed.\nLemma perm_unlock_mapped γ :\n  sep_valid γ → sep_unmapped (perm_unlock γ) → sep_unmapped γ.\nProof. destruct γ as [[[]|[]]|[]]; repeat sep_unfold; naive_solver. Qed.\nLemma perm_unlock_unshared γ : sep_unshared γ → sep_unshared (perm_unlock γ).\nProof. destruct γ as [[]|[]]; repeat sep_unfold; intuition. Qed.\nLemma perm_unlock_shared γ :\n  sep_valid γ → sep_unshared (perm_unlock γ) → sep_unshared γ.\nProof. destruct γ as [[]|[]]; repeat sep_unfold; intuition. Qed.\nLemma perm_unshared γ :\n  sep_valid γ → Some Locked ⊆ perm_kind γ → sep_unshared γ.\nProof. destruct (perm_kind_spec γ); repeat sep_unfold; intuition. Qed.\nLemma perm_mapped γ : Some Readable ⊆ perm_kind γ → ¬sep_unmapped γ.\nProof. destruct (perm_kind_spec γ); repeat sep_unfold; naive_solver. Qed.\nLemma perm_unmapped γ :\n  sep_valid γ → perm_kind γ = Some Existing → sep_unmapped γ.\nProof. destruct (perm_kind_spec γ); repeat sep_unfold; naive_solver. Qed.\nLemma perm_None_unmapped γ : sep_valid γ → perm_kind γ = None → sep_unmapped γ.\nProof. destruct (perm_kind_spec γ); repeat sep_unfold; naive_solver. Qed.\nLemma perm_token_subseteq γ :\n  sep_valid γ → Some Writable ⊆ perm_kind γ → perm_token ⊂ γ.\nProof.\n  assert (∀ x', x' - 0 = 0 → x' = 0).\n  { intros x'. change (x' - 0) with (x' + 0). by rewrite Qcplus_0_r. }\n  rewrite strict_spec_alt. unfold perm_token.\n  destruct (perm_kind_spec γ); repeat sep_unfold; (split; [|intro]);\n    simplify_equality'; intuition; exfalso; auto.\nQed.\nLemma perm_splittable γ :\n  sep_valid γ → Some Readable ⊆ perm_kind γ → sep_splittable γ.\nProof. destruct (perm_kind_spec γ); repeat sep_unfold; intuition. Qed.\nLemma perm_splittable_existing γ :\n  sep_valid γ → perm_kind γ = Some Existing → sep_splittable γ.\nProof. by destruct (perm_kind_spec γ); repeat sep_unfold. Qed.\n\nLemma perm_kind_full : perm_kind perm_full = Some Writable.\nProof. done. Qed.\nLemma perm_kind_lock γ :\n  Some Writable ⊆ perm_kind γ → perm_kind (perm_lock γ) = Some Locked.\nProof. by destruct (perm_kind_spec γ). Qed.\nLemma perm_kind_half γ :\n  sep_valid γ → perm_kind (½ γ) =\n    match perm_kind γ with \n    | Some Writable => Some Readable | _ => perm_kind γ\n    end.\nProof.\n  assert (∀ x', x' * /2 = 0 → x' = 0).\n  { intros. by apply Qcmult_integral_l with (/2); rewrite 1?Qcmult_comm. }\n  assert (∀ x', x' * /2 = 1 → x' ≤ 1 → False).\n  { intros x'. rewrite (Qcmult_le_mono_pos_r _ _ (/2)) by done.\n    by intros -> []. }\n  repeat sep_unfold; destruct (perm_kind_spec γ); unfold perm_kind; simpl;\n    intros; by rewrite ?decide_False by intuition eauto.\nQed.\nLemma perm_kind_token : perm_kind perm_token = Some Existing.\nProof. done. Qed.\nLemma perm_kind_difference_token γ :\n  perm_token ⊂ γ → perm_kind (γ ∖ perm_token) = perm_kind γ.\nProof.\n  rewrite strict_spec_alt.\n  destruct (perm_kind_spec γ) as [| |y| | |y|]; repeat sep_unfold;\n    unfold perm_kind; simpl; intros [? Hneq]; auto.\n  * assert (¬0 ≤ -1) by (by intros []); intuition.\n  * assert (y ≤ -1 → y ≤ 0) by (by intros; transitivity (-1)).\n    assert (y + 1 ≠ 0).\n    { change 0 with (-1 + 1); rewrite (inj_iff (λ x, x + 1)); contradict Hneq.\n      symmetry. unfold perm_token; repeat f_equal; intuition. }\n    by rewrite decide_False by done.\n  * by change (-0) with 0; rewrite Qcplus_0_r, !decide_False by done.\nQed.\nLemma perm_kind_subseteq γ1 γ2 : γ1 ⊆ γ2 → perm_kind γ1 ⊆ perm_kind γ2.\nProof.\n  destruct γ1 as [[[x1 y1]|[x1 y1]]|x1], γ2 as [[[x2 y2]|[x2 y2]]|x2];\n    unfold perm_kind; repeat sep_unfold;\n    repeat case_decide; naive_solver eauto using Qcle_antisym.\nQed.\nLemma perm_lock_disjoint γ1 γ2 :\n  Some Writable ⊆ perm_kind γ1 → γ1 ## γ2 → perm_lock γ1 ## γ2.\nProof.\n  assert (¬2 ≤ 1) by (by intros []).\n  assert (∀ x, 0 ≤ x → 1 + x ≤ 1 → x = 0).\n  { intros x ? Hx. apply (Qcplus_le_mono_l x 0 1) in Hx.\n    auto using Qcle_antisym. }\n  destruct (perm_kind_spec γ1), γ2 as [[[x2 y2]|[x2 y2]]|];\n    repeat sep_unfold; intuition; simplify_equality'; try done.\n  * assert (y2 = 0) as -> by auto.\n    rewrite (Qcplus_le_mono_r _ _ x2), Qcplus_0_l. eauto using Qcle_trans.\n  * assert (y2 = 0) as -> by auto.\n    rewrite (Qcplus_le_mono_r _ _ x2), Qcplus_0_l. eauto using Qcle_trans.\nQed.\nLemma perm_lock_union γ1 γ2 : perm_lock (γ1 ∪ γ2) = perm_lock γ1 ∪ γ2.\nProof. by destruct γ1 as [[]|], γ2 as [[]|]. Qed.\nLemma perm_unlock_disjoint γ1 γ2 : γ1 ## γ2 → perm_unlock γ1 ## γ2.\nProof. destruct γ1 as [[]|], γ2 as [[]|]; repeat sep_unfold; naive_solver. Qed.\nLemma perm_unlock_union γ1 γ2 :\n  γ1 ## γ2 → perm_locked γ1 → perm_unlock (γ1 ∪ γ2) = perm_unlock γ1 ∪ γ2.\nProof. by destruct γ1 as [[]|], γ2 as [[]|]. Qed.\nLemma perm_disjoint_full γ : perm_full ## γ → γ = ∅.\nProof.\n  destruct γ as [[[x y]|[x y]]|];\n    repeat sep_unfold; intuition; simplify_equality'.\n  assert (y = 0) as ->.\n  { apply Qcle_antisym; auto. by apply (Qcplus_le_mono_l y 0 1). }\n  repeat f_equal; apply Qcle_antisym; auto; rewrite <-(Qcplus_0_l x); auto.\nQed.\n", "meta": {"author": "robbertkrebbers", "repo": "ch2o", "sha": "1afb3f615db053b741341e9bfd1d5c65bddea641", "save_path": "github-repos/coq/robbertkrebbers-ch2o", "path": "github-repos/coq/robbertkrebbers-ch2o/ch2o-1afb3f615db053b741341e9bfd1d5c65bddea641/separation/permissions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22772290882762494}}
{"text": "Require Import LibInt.\nRequire Import JsNumber.\nRequire Import String.\nRequire Import Store.\nRequire Import Monads.\nRequire Import Values.\nRequire Import Context.\nOpen Scope string_scope.\n\nImplicit Type runs : Context.runs_type.\nImplicit Type store : Store.store.\n\n(****** Unary operators ******)\n\nDefinition typeof store (v : Values.value) :=\n  match v with\n  | Values.Undefined => Context.add_value_return store (String \"undefined\")\n  | Values.Null => Context.add_value_return store (String  \"null\")\n  | Values.String _ => Context.add_value_return store (String  \"string\")\n  | Values.Number _ => Context.add_value_return store (String  \"number\")\n  | Values.True | Values.False => Context.add_value_return store (String  \"boolean\")\n  | Values.Object ptr =>\n    assert_get_object_from_ptr store ptr (fun obj =>\n      match (Values.object_code obj) with\n      | Some  _ => Context.add_value_return store (String \"function\")\n      | None => Context.add_value_return store (String  \"object\")\n      end\n    )\n  | Values.Closure _ _ _ _ => (store, Fail Values.value_loc \"typeof got lambda\")\n  end\n.\n\nDefinition is_primitive store v :=\n  match v with\n  | Undefined | Null | String _ | Number _ | True | False =>\n    Context.add_value_return store True\n  | _ =>\n    Context.add_value_return store False\n  end\n.\n\nDefinition void store (v : Values.value) :=\n  Context.add_value_return store Undefined\n.\n\nDefinition prim_to_str store (v : Values.value) :=\n  match v with\n  | Undefined => Context.add_value_return store (String \"undefined\")\n  | Null => Context.add_value_return store (String \"null\")\n  | String s => Context.add_value_return store (String s)\n  | Number n => Context.add_value_return store (String (JsNumber.to_string n))\n  | True => Context.add_value_return store (String \"true\")\n  | False => Context.add_value_return store (String \"false\")\n  | _ => (store, Fail Values.value_loc \"prim_to_str not implemented for this type.\")\n  end\n.\n\nDefinition prim_to_num store (v : Values.value) :=\n  match v with\n  | Undefined => Context.add_value_return store (Number JsNumber.nan)\n  | Null => Context.add_value_return store (Number JsNumber.zero)\n  | True => Context.add_value_return store (Number JsNumber.one)\n  | False => Context.add_value_return store (Number JsNumber.zero)\n  | Number n => Context.add_value_return store (Number n)\n  | String \"\" => Context.add_value_return store (Number JsNumber.zero)\n  | String s => Context.add_value_return store (Number (JsNumber.from_string s))\n  | _ => (store, Fail value_loc \"prim_to_num got invalid value.\")\n  end\n.\n\nDefinition prim_to_bool store (v : Values.value) :=\n  match v with\n  | True => Context.add_value_return store True\n  | False => Context.add_value_return store False\n  | Undefined => Context.add_value_return store False\n  | Null => Context.add_value_return store False\n  | Number n => Context.add_value_return store (\n      if (decide(n = JsNumber.nan)) then\n        False\n      else if (decide(n = JsNumber.zero)) then\n        False\n      else if (decide(n = JsNumber.neg_zero)) then\n        False\n      else\n        True\n    )\n  | String \"\" => Context.add_value_return store False\n  | String _ => Context.add_value_return store True\n  | _ => Context.add_value_return store True\n  end\n.\n\nDefinition nnot store (v : Values.value) :=\n  match v with\n  | Undefined => Context.add_value_return store True\n  | Null => Context.add_value_return store True\n  | True => Context.add_value_return store False\n  | False => Context.add_value_return store True\n  | Number d => Context.add_value_return store (\n      if (decide(d = JsNumber.zero)) then\n        True\n      else if (decide(d = JsNumber.neg_zero)) then\n        True\n      else if (decide(d <> d)) then\n        True\n      else\n        False\n    )\n  | String \"\" => Context.add_value_return store True\n  | String _ => Context.add_value_return store False\n  | Object _ => Context.add_value_return store False\n  | Closure _ _ _ _ => Context.add_value_return store False\n  end\n.\n\nParameter _print_string : string -> unit.\nParameter _pretty : nat -> store -> value -> unit.\nDefinition _seq {X Y : Type} (x : X) (y : Y) : Y :=\n  y\n.\n\nDefinition print store (v : Values.value) :=\n  match v with\n  | String s => _seq (_print_string s) (Context.add_value_return store Undefined)\n  | Number n => _seq (_print_string (JsNumber.to_string n)) (Context.add_value_return store Undefined)\n  | _ => (store, Fail Values.value_loc \"print of non-string and non-number.\")\n  end\n.\n\nDefinition pretty runs store v :=\n  _seq\n  (_pretty (Context.runs_type_nat_fuel runs) store v)\n  (Context.add_value_return store Undefined)\n.\n\nDefinition strlen store v :=\n  match v with\n  | String s => add_value_return store (Number (JsNumber.of_int (String.length s)))\n  | _ => (store, Fail value_loc \"strlen got non-string.\")\n  end\n.\n\nDefinition numstr_to_num store (v : Values.value) :=\n  match v with\n  | String \"\" => Context.add_value_return store (Number JsNumber.zero)\n  | String s => Context.add_value_return store (Number (JsNumber.from_string s))\n  | _ => (store, Fail value_loc \"numstr_to_num got invalid value.\")\n  end\n.\n\nDefinition unary_arith store (op : number -> number) (v : Values.value) : (Store.store * Context.result Values.value_loc) :=\n  match v with\n  | Number n => Context.add_value_return store (Number (op n))\n  | _ => (store, Fail Values.value_loc \"Arithmetic with non-number.\")\n  end\n.\n\nDefinition unary (op : string) runs store v_loc : (Store.store * (@Context.result Values.value_loc)) :=\n  assert_deref store v_loc (fun v =>\n    match op with\n    | \"print\" => print store v\n    | \"pretty\" => pretty runs store v\n    | \"strlen\" => strlen store v\n    | \"typeof\" => typeof store v\n    | \"primitive?\" => is_primitive store v\n    | \"abs\" => unary_arith store JsNumber.absolute v\n    | \"void\" => void store v\n    | \"floor\" => unary_arith store JsNumber.floor v\n    | \"prim->str\" => prim_to_str store v\n    | \"prim->num\" => prim_to_num store v\n    | \"prim->bool\" => prim_to_bool store v\n    | \"!\" => nnot store v\n    | \"numstr->num\" => numstr_to_num store v\n    | _ => (store, Context.Fail Values.value_loc (\"Unary operator \" ++ op ++ \" not implemented.\"))\n    end\n  )\n.\n\n(****** Binary operators ******)\n\nParameter _number_eq_bool : number -> number -> bool.\n\nDefinition stx_eq store v1 v2 :=\n  match (v1, v2) with\n  | (String s1, String s2) => Context.add_value_return store (if (decide(s1 = s2)) then True else False)\n  | (Null, Null) => Context.add_value_return store True\n  | (Undefined, Undefined) => Context.add_value_return store True\n  | (True, True) => Context.add_value_return store True\n  | (False, False) => Context.add_value_return store True\n  | (Number n1, Number n2) =>\n    let (store, loc) := Store.add_bool store (_number_eq_bool n1 n2) in\n    (store, Return Values.value_loc loc)\n  | (Object ptr1, Object ptr2) => Context.add_value_return store (if (beq_nat ptr1 ptr2) then True else False)\n  | (Closure id1 _ _ _, Closure id2 _ _ _) => Context.add_value_return store (if (beq_nat id1 id2) then True else False)\n  | _ => Context.add_value_return store False\n  (*| _ => Context.add_value_return store (if (beq_nat v1_loc v2_loc) then True else False)*)\n  end\n.\n\nDefinition has_property runs store v1_loc v2 :=\n  match v2 with\n  | String s =>\n    let (store, res) := Context.runs_type_get_property runs store (v1_loc, s) in\n    if_return store res (fun ret =>\n      match ret with\n      | Some _ => Context.add_value_return store True\n      | None => Context.add_value_return store False\n      end\n    )\n  | _ => (store, Fail Values.value_loc \"hasProperty expected a string.\")\n  end\n.\n\nDefinition has_own_property store v1 v2 :=\n  match (v1, v2) with\n  | (Object ptr, String s) =>\n    assert_get_object_from_ptr store ptr (fun obj =>\n      match (Values.get_object_property obj s) with\n      | Some _ => Context.add_value_return store True\n      | None => Context.add_value_return store False\n      end\n    )\n  | _ => (store, Fail Values.value_loc \"hasOwnProperty expected an object and a string.\")\n  end\n.\n      \n\nDefinition prop_to_obj store v1 v2 :=\n  let make_attr := (fun x => attributes_data_of (attributes_data_intro x false false false)) in\n  match (v1, v2) with\n  | (Object ptr, String s) =>\n    assert_get_object_from_ptr store ptr (fun obj =>\n      match (Values.get_object_property obj s) with\n      | Some (attributes_data_of (attributes_data_intro val writ enum config)) =>\n        let (store, proto_loc) := Store.add_value store Undefined in\n        let (store, config_loc) := Store.add_bool store config in\n        let (store, enum_loc) := Store.add_bool store enum in\n        let (store, writable_loc) := Store.add_bool store writ in\n        let props := Heap.write Heap.empty \"configurable\" (make_attr config_loc) in\n        let props := Heap.write props \"enumerable\" (make_attr enum_loc) in\n        let props := Heap.write props \"writable\" (make_attr writable_loc) in\n        let props := Heap.write props \"value\" (make_attr val) in\n        let obj := object_intro proto_loc \"Object\" false None props None in\n        let (store, loc) := Store.add_object store obj in\n        (store, Return Values.value_loc loc)\n      | Some (attributes_accessor_of (attributes_accessor_intro get set enum config)) =>\n        let (store, proto_loc) := Store.add_value store Undefined in\n        let (store, config_loc) := Store.add_bool store config in\n        let (store, enum_loc) := Store.add_bool store enum in\n        let props := Heap.write Heap.empty \"configurable\" (make_attr config_loc) in\n        let props := Heap.write props \"enumerable\" (make_attr enum_loc) in\n        let props := Heap.write props \"setter\" (make_attr set) in\n        let props := Heap.write props \"getter\" (make_attr get) in\n        let obj := object_intro proto_loc \"Object\" false None props None in\n        let (store, loc) := Store.add_object store obj in\n        (store, Return Values.value_loc loc)\n      | None => Context.add_value_return store Undefined\n      end\n    )\n  | _ => (store, Fail Values.value_loc \"hasOwnProperty expected an object and a string.\")\n  end\n.\n\nDefinition string_plus store v1 v2 : (Store.store * Context.result Values.value_loc) :=\n  match (v1, v2) with\n  | (String s1, String s2) => Context.add_value_return store (String (s1++s2))\n  | _ => (store, Fail Values.value_loc \"Only strings can be concatenated.\")\n  end\n.\n\nParameter _nat_of_float : number -> nat.\n\nDefinition char_at store v1 v2 :=\n  match (v1, v2) with\n  | (Values.String s, Number n) =>\n      match (String.get (_nat_of_float n) s) with\n      | Some char => add_value_return store (Values.String (String.String char String.EmptyString))\n      | None => (store, Fail Values.value_loc \"char_at called with index larger than length.\")\n      end\n  | _ => (store, Fail Values.value_loc \"char_at called with wrong argument types.\")\n  end\n.\n\nDefinition is_accessor runs store v1_loc v2 :=\n  match v2 with\n  | String s =>\n    let (store, res) := Context.runs_type_get_property runs store (v1_loc, s) in\n    if_return store res (fun ret =>\n      match ret with\n      | Some (attributes_data_of _) => Context.add_value_return store False\n      | Some (attributes_accessor_of _) => Context.add_value_return store True\n      | None => (store, Fail Values.value_loc \"isAccessor topped out.\")\n      end\n    )\n  | _ => (store, Fail Values.value_loc \"isAccessor expected an object and a string.\")\n  end\n.\n\nParameter _same_value : value -> value -> bool.\n\nDefinition same_value store v1 v2 :=\n  return_bool store (_same_value v1 v2)\n.\n\nDefinition arith store (op : number -> number -> number) (v1 v2 : Values.value) : (Store.store * Context.result Values.value_loc) :=\n  match (v1, v2) with\n  | (Number n1, Number n2) => Context.add_value_return store (Number (op n1 n2))\n  | _ => (store, Fail Values.value_loc \"Arithmetic with non-numbers.\")\n  end\n.\n\nDefinition cmp store undef_left undef_both undef_right (op : number -> number -> bool) (v1 v2 : Values.value) : (Store.store * Context.result Values.value_loc) :=\n  match (v1, v2) with\n  | (Number n1, Number n2) => Context.add_value_return store (if (op n1 n2) then True else False)\n  | (Undefined, Number _) => Context.add_value_return store undef_left\n  | (Undefined, Undefined) => Context.add_value_return store undef_both\n  | (Number _, Undefined) => Context.add_value_return store undef_right\n  | _ => (store, Fail Values.value_loc \"Comparison/order of non-numbers.\")\n  end\n.\n\nParameter le_bool : number -> number -> bool.\nParameter gt_bool : number -> number -> bool.\nParameter ge_bool : number -> number -> bool.\n\n\nDefinition binary (op : string) runs store v1_loc v2_loc : (Store.store * (Context.result Values.value_loc)) :=\n  assert_deref store v1_loc (fun v1 =>\n    assert_deref store v2_loc (fun v2 =>\n      match op with\n      | \"+\" => arith store JsNumber.add v1 v2\n      | \"-\" => arith store JsNumber.sub v1 v2\n      | \"*\" => arith store JsNumber.mult v1 v2\n      | \"/\" => arith store JsNumber.div v1 v2\n      | \"%\" => arith store JsNumber.fmod v1 v2\n      | \"<\" => cmp store True False False JsNumber.lt_bool v1 v2\n      | \"<=\" => cmp store True True False le_bool v1 v2\n      | \">\" => cmp store False False True gt_bool v1 v2\n      | \">=\" => cmp store False True True ge_bool v1 v2\n      | \"stx=\" => stx_eq store v1 v2\n      | \"sameValue\" => same_value store v1 v2\n      | \"hasProperty\" => has_property runs store v1_loc v2\n      | \"hasOwnProperty\" => has_own_property store v1 v2\n      | \"string+\" => string_plus store v1 v2\n      | \"char-at\" => char_at store v1 v2\n      | \"isAccessor\" => is_accessor runs store v1_loc v2\n      | \"__prop->obj\" => prop_to_obj store v1 v2 (* For debugging purposes *)\n      | _ => (store, Context.Fail Values.value_loc (\"Binary operator \" ++ op ++ \" not implemented.\"))\n      end\n  ))\n.\n", "meta": {"author": "progval", "repo": "LambdaCert", "sha": "138f258fb397e7733426dcb90e70ecbde9c6d161", "save_path": "github-repos/coq/progval-LambdaCert", "path": "github-repos/coq/progval-LambdaCert/LambdaCert-138f258fb397e7733426dcb90e70ecbde9c6d161/LambdaS5/coq/Operators.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305398, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.22745864955563486}}
{"text": "Module CKTransSPL.\nRequire Export cktrans_spl_int.\nRequire Export assetmapping_spl_def.\nRequire Export featuremodel_spl_def.\nImport FeatureModelSPL.\nImport AssetMappingSPL.  \nRequire Import Coq.Lists.ListSet.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Init.Specif.\nRequire Export Coq.Lists.List.\n\n\n Inductive CK: Type.\n Parameter CKSem_func : \n  CK -> AM -> Conf -> set Asset.\n\n  (* Axiom over ck evaluation *)\n  Axiom amRef_func: forall (am1 am2: AM),\n    (aMR_func am1 am2) -> forall (K: CK) (C: Conf),\n      wfProduct_ind (CKSem_func K am1 C) -> wfProduct_ind (CKSem_func K am2 C)\n      /\\ assetRef_func (CKSem_func K am1 C) (CKSem_func K am2 C). \n\n  Parameter CKConf_func:\n  CK -> set Conf.\n\n(*  % Definition <CK equivalence>   *)\n  Definition equivalentCKsAux (ck1 ck2: CK): Prop :=\n   match (set_diff conf_dec (CKConf_func ck1) (CKConf_func ck2)) with\n    | nil => True\n    | _ => False\n    end.\n\n Definition equivalentCKs_func (ck1 ck2: CK): Prop :=\n  (equivalentCKsAux ck1 ck2) /\\ (equivalentCKsAux ck2 ck1).\n\n\n  Definition weakerEqCK_func (fm: FM) (ck1 ck2: CK): Prop :=\n    forall am,\n      forall c, set_In c (FMRef_Func fm) ->\n        (CKSem_func ck1 am c = CKSem_func ck2 am c).\n\n   Lemma equalsCK2_lemma:\n  forall ck1 ck2, equivalentCKs_func ck1 ck2 -> ck1 = ck2.\n    Proof.\n    unfold equivalentCKs. \n    unfold equivalentCKsAux. intros. destruct H.\n    (*+ rewrite equalsSetDiff.\n      - trivial.\n      - reflexivity.\n    + rewrite equalsSetDiff.\n      - trivial.\n      - reflexivity. *)\n     Admitted. \n\nEnd CKTransSPL.\n", "meta": {"author": "spgroup", "repo": "theory-pl-refinement-coq", "sha": "9587dddac0d6f4792db18629fa1ea3bd3d933abe", "save_path": "github-repos/coq/spgroup-theory-pl-refinement-coq", "path": "github-repos/coq/spgroup-theory-pl-refinement-coq/theory-pl-refinement-coq-9587dddac0d6f4792db18629fa1ea3bd3d933abe/typeclass/Util/cktrans_spl_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.22742523892719557}}
{"text": "(******************************************************************************)\n(** * Definition of the JSMM memory model *)\n(******************************************************************************)\nFrom hahn Require Import Hahn.\nRequire Import Arith.\nRequire Import List.\nRequire Import Bool.\nFrom imm Require Import Events Execution JSMM.\nRequire Import Execution_m.\nRequire Import JSMM_m.\n\nSet Implicit Arguments.\n\nSection JSMM_m_deadness.\n\nVariable G : execution_m.\n\nVariable tfree : (actid -> Prop).\n\nHypothesis WF_m : Wf_m G.\n\nNotation \"'E'\" := G.(acts_set).\nNotation \"'acts'\" := G.(acts).\nNotation \"'lab'\" := G.(lab).\nNotation \"'range_value'\" := G.(range_value).\nNotation \"'rf_on'\" := G.(rf_on).\nNotation \"'overlap_on'\" := G.(overlap_on).\nNotation \"'no_overlap'\" := G.(no_overlap).\nNotation \"'rfb'\" := G.(rfb).\nNotation \"'cob'\" := G.(cob).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rf'\" := G.(rf).\nNotation \"'co'\" := G.(co).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'fr'\" := G.(fr).\n(* Notation \"'eco'\" := G.(eco). *)\nNotation \"'same_range'\" := G.(same_range).\nNotation \"'same_loc'\" := (same_loc lab).\n\nNotation \"'R'\" := (fun a => is_true (is_r lab a)).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\n\nNotation \"'Pln'\" := (fun a => is_true (is_only_pln lab a)).\nNotation \"'Rlx'\" := (fun a => is_true (is_rlx lab a)).\nNotation \"'Rel'\" := (fun a => is_true (is_rel lab a)).\nNotation \"'Acq'\" := (fun a => is_true (is_acq lab a)).\nNotation \"'Acqrel'\" := (fun a => is_true (is_acqrel lab a)).\nNotation \"'Acq/Rel'\" := (fun a => is_true (is_ra lab a)).\nNotation \"'Sc'\" := (fun a => is_true (is_sc lab a)).\n\nNotation \"'sw'\" := G.(sw).\nNotation \"'hb'\" := G.(hb).\n\nDefinition jsmm_m_consistent_wrong tot :=\n  ⟪ Ctot   : strict_total_order E tot ⟫ /\\\n  ⟪ Chbtot : hb ⊆ tot ⟫ /\\\n  ⟪ Chbrf : irreflexive (hb ⨾ rf) ⟫ /\\\n  ⟪ Chbrfhb : forall n,\n      irreflexive (hb ⨾ (rf_on n)⁻¹ ⨾ (hb ∩ overlap_on n) ⨾ ⦗ W ⦘) ⟫ /\\\n  ⟪ Cirr :\n      irreflexive (⦗W⦘ ⨾ tot ⨾ sw⁻¹ ⨾ (tot ∩ same_range)) ⟫ /\\\n  ⟪ Ctf :\n      functional (⦗tfree⦘ ⨾ (rf⁻¹ ∩ same_range) ⨾ ⦗tfree⦘) ⟫.\n\nRecord syn_dead_wrt Gtot Htot := {\n  deadwrt_WRsc :\n    ⦗W⦘ ⨾ Gtot ⨾ ⦗R∩₁Sc⦘ ⊆ Htot;\n  deadwrt_WscW :\n    ⦗W ∩₁Sc⦘ ⨾ Gtot ⨾ ⦗W⦘ ⊆ Htot;\n}.\n\nRecord syn_dead Gtot := {\n  deadg_hb_tot : hb ⊆ Gtot;\n  deadg_tot' : forall Htot, jsmm_m_consistent_wrong Htot -> syn_dead_wrt Gtot Htot;\n}.\n\nLemma syn_deadness_cst Gtot Htot :\n  hb ⊆ Gtot ->\n    strict_total_order E Gtot ->\n      strict_total_order E Htot ->\n        syn_dead_wrt Gtot Htot ->\n          jsmm_m_consistent_wrong Htot ->\n            jsmm_m_consistent_wrong Gtot.\nProof.\n  intros Ha Hb Hc [Hd1 Hd2] He.\n  econstructor. { assumption. }\n  econstructor. { assumption. }\n  econstructor. { apply He. }\n  econstructor. { apply He. }\n  econstructor. {\n    unfold irreflexive.\n    intros x H.\n    destruct H as [x_ [H1 [y [H2 [z [H3 [H4 H5]]]]]]].\n    destruct H1 as [H11 H12].\n    rewrite <- H11 in H2.\n    destruct He as [Ctot [Chbtot [Chbrf [Chbrfhb [Cirr Ctf]]]]].\n    unfold irreflexive in Cirr.\n    destruct Cirr with x.\n    constructor 1 with x.\n    split. { constructor. reflexivity. assumption. }\n    constructor 1 with y.\n    split. {\n      apply Hd1.\n      constructor 1 with x.\n      split. { constructor. reflexivity. assumption. }\n      constructor 1 with y.\n      split. { assumption. }\n      constructor. { reflexivity. }\n      destruct H3 as [z_ [[H311 H312] [y_ [H32 [H33 H34]]]]].\n      rewrite H33 in H32, H34.\n      rewrite <- H311 in H32.\n      constructor. {\n      eapply rf_w_r.\n      - assumption.\n      - apply H32.\n      }\n      assumption.\n    }\n    constructor 1 with z.\n    split. { assumption. }\n    constructor. {\n      apply Hd2.\n      constructor 1 with z.\n      destruct H3 as [z_ [[H311 H312] [y_ [H32 [H33 H34]]]]].\n      rewrite H33 in H32, H34.\n      rewrite <- H311 in H32.\n      split. {\n        constructor. { reflexivity. }\n        constructor. { eapply rf_w_r. assumption. apply H32. }\n        assumption.\n      }\n      constructor 1 with x.\n      split. { assumption. }\n      constructor. reflexivity. assumption.\n    }\n    assumption.\n  }\n  apply He.\nQed.\n\nLemma syn_deadness_sc Gtot Htot :\n  hb ⊆ Gtot ->\n    hb ⊆ Htot ->\n      strict_total_order E Gtot ->\n        strict_total_order E Htot ->\n          data_race_free G ->\n            syn_dead_wrt Gtot Htot ->\n              seqcst G Htot ->\n                seqcst G Gtot.\nProof.\n  intros Ha Hb Hc Hd He [Hf1 Hf2] Hg.\n  unfold seqcst.\n  split.\n  - unfold irreflexive.\n    intros x H.\n    destruct H as [y [H1 H2]].\n    destruct (drf_tot__hb_sc He Hc Ha H2).\n    + apply is_overlap_sym. apply rf_overlap. apply WF_m. apply H1.\n    + right. eapply rf_w_r. apply WF_m. apply H1.\n    + destruct Hg as [Hg1 Hg2]. apply Hg1 with x.\n      constructor 1 with y.\n      split. { assumption. }\n      apply Hb. apply H.\n    + destruct Hc as [[Hc11 Hc12] Hc2].\n      apply Hc11 with x.\n      apply Hc12 with y. {\n        apply Ha.\n        constructor. right.\n        apply rf_sw.\n        - apply H1.\n        - apply same_range_sym. apply H.\n        - apply H.\n        - apply H.\n      }\n      apply H2.\n  - intros n z H.\n    destruct H as [z_ [[H11 H12] [x [[H21 H22] [y [H3 H4]]]]]].\n    rewrite <- H11 in H21, H22.\n    unfold transp in H3.\n    assert (Htot z x) as Htot1. {\n      destruct (drf_tot__hb_sc He Hc Ha H21) as [Hl | Hr].\n      - eapply overlap_on_is_overlap. apply H22.\n      - left. apply H12.\n      - apply Hb. apply Hl.\n      - apply Hf1.\n        econstructor.\n        split. { econstructor. reflexivity. apply H12. }\n        econstructor.\n        split. { apply H21. }\n        econstructor. { reflexivity. }\n        econstructor.\n        + eapply rf_w_r. apply WF_m. eapply rf_on_rf. apply H3.\n        + apply Hr.\n    }\n    assert (Htot y z) as Htot2. {\n      destruct (drf_tot__hb_sc He Hc Ha H4) as [Hl | Hr].\n      - eapply overlap_on_is_overlap. apply overlap_on_trans with x.\n        apply rf_on_overlap_on. apply WF_m. apply H3. apply overlap_on_sym. apply H22.\n      - left. eapply rf_w_r. apply WF_m. eapply rf_on_rf. apply H3.\n      - apply Hb. apply Hl.\n      - apply Hf2.\n        econstructor.\n        split. { econstructor. reflexivity. econstructor. eapply rf_w_r.\n                 apply WF_m. eapply rf_on_rf. apply H3. apply Hr. }\n        econstructor.\n        split. { apply H4. }\n        econstructor. { reflexivity. }\n        assumption.\n    }\n    destruct Hg as [Hg1 Hg2].\n    apply (Hg2 n z).\n    econstructor.\n    split. { econstructor. reflexivity. assumption. }\n    econstructor.\n    split. { econstructor. apply Htot1. apply H22. }\n    econstructor.\n    split. { apply H3. }\n    apply Htot2.\nQed.\n\nEnd JSMM_m_deadness.\n", "meta": {"author": "conrad-watt", "repo": "repairing-and-mechanising-the-javascript-relaxed-memory-model", "sha": "c6f707610e4d465741d0fdb93a8f9356fa751227", "save_path": "github-repos/coq/conrad-watt-repairing-and-mechanising-the-javascript-relaxed-memory-model", "path": "github-repos/coq/conrad-watt-repairing-and-mechanising-the-javascript-relaxed-memory-model/repairing-and-mechanising-the-javascript-relaxed-memory-model-c6f707610e4d465741d0fdb93a8f9356fa751227/coq/src/jsmm_mixed/JSMM_m_deadness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2274252329400529}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\n\nRequire Import PromiseConsistent.\nRequire Import ReorderPromises.\n\nSet Implicit Arguments.\n\n\nDefinition pf_consistent lang (e:Thread.t lang): Prop :=\n  forall mem1 sc1\n         (CAP: Memory.cap (Thread.memory e) mem1)\n         (SC_MAX: Memory.max_concrete_timemap mem1 sc1),\n  exists e2,\n    (<<STEPS: rtc (tau (Thread.step true)) (Thread.mk _ (Thread.state e) (Thread.local e) sc1 mem1) e2>>) /\\\n    ((<<FAILURE: exists e3, Thread.step true ThreadEvent.failure e2 e3 >>) \\/\n     (<<PROMISES: (Local.promises (Thread.local e2)) = Memory.bot>>)).\n\nLemma rtc_union_step_nonpf_failure\n      lang e1 e2 e2'\n      (STEP: rtc (union (@Thread.step lang false)) e1 e2)\n      (FAILURE: Thread.step true ThreadEvent.failure e2 e2')\n  :\n    exists e1',\n      Thread.step true ThreadEvent.failure e1 e1'.\nProof.\n  ginduction STEP; eauto.\n  i. exploit IHSTEP; eauto. i. des.\n  exists (Thread.mk _ (Thread.state e1') (Thread.local x) (Thread.sc x) (Thread.memory x)).\n  inv x0; inv STEP0. inv LOCAL. inv LOCAL0.\n  inv H. inv USTEP. inv STEP0.\n  econs 2; eauto. econs; eauto. econs; eauto. econs; eauto.\n  ss. eapply promise_step_promise_consistent; eauto.\nQed.\n\nLemma consistent_pf_consistent lang (e:Thread.t lang)\n      (WF: Local.wf (Thread.local e) (Thread.memory e))\n      (MEM: Memory.closed (Thread.memory e))\n      (CONSISTENT: Thread.consistent e)\n  :\n    pf_consistent e.\nProof.\n  ii. exploit CONSISTENT; eauto. i. des.\n  - inv FAILURE. des.\n    hexploit tau_steps_pf_tau_steps; eauto; ss.\n    { inv FAILURE; inv STEP. inv LOCAL. inv LOCAL0.\n      hexploit rtc_tau_step_promise_consistent; eauto; ss.\n      { eapply Local.cap_wf; eauto. }\n      { eapply Memory.max_concrete_timemap_closed; eauto. }\n      { eapply Memory.cap_closed; eauto. }\n    }\n    { eapply Local.cap_wf; eauto. }\n    { eapply Memory.max_concrete_timemap_closed; eauto. }\n    { eapply Memory.cap_closed; eauto. }\n    i. des.\n    exploit rtc_union_step_nonpf_failure.\n    { eapply rtc_implies; [|eauto]. apply tau_union. }\n    { eauto. }\n    i. des.\n    esplits; eauto.\n  - exploit tau_steps_pf_tau_steps; eauto; ss.\n    { ii. rewrite PROMISES, Memory.bot_get in *.  congr. }\n    { eapply Local.cap_wf; eauto. }\n    { eapply Memory.max_concrete_timemap_closed; eauto. }\n    { eapply Memory.cap_closed; eauto. }\n    i. des.\n    exploit rtc_union_step_nonpf_bot; [|eauto|].\n    { eapply rtc_implies; [|eauto]. apply tau_union. }\n    i. subst. esplits; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/prop/PFConsistent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2274252329400529}}
{"text": "Require Import VST.veric.Clight_base.\nRequire Import compcert.cfrontend.Clight.\n\nDefinition var_name (V: Type) (bdec: ident * globvar V) : ident :=\n   fst bdec.\n\nDefinition no_dups (F V: Type) (fdecs: list (ident * F)) (bdecs: list (ident * globvar V)) : Prop :=\n  list_norepet (map (@fst ident F) fdecs ++ map (@var_name V) bdecs).\nArguments no_dups [F V] _ _.\n\nLemma no_dups_inv:\n  forall  (A V: Type) id f fdecs bdecs,\n    no_dups ((id,f)::fdecs) bdecs ->\n    no_dups fdecs bdecs /\\\n     ~ In id (map (@fst ident A) fdecs) /\\\n     ~ In id (map (@var_name V) bdecs).\nProof.\nintros.\ninversion H; clear H. subst.\nrepeat split.\napply H3.\nintro; contradiction H2; apply in_or_app; auto.\nintro; contradiction H2; apply in_or_app; auto.\nQed.\nArguments no_dups_inv [A V] _ _ _ _ _.\n\n\nLemma of_bool_Int_eq_e:\n  forall i j, Val.of_bool (Int.eq i j) = Vtrue -> i = j.\nProof.\nunfold Val.of_bool.\ndo 2 intro.\nassert (if Int.eq i j then i=j else i<>j).\napply Int.eq_spec.\ncaseEq (Int.eq i j); intros.\nrewrite H0 in H ; trivial.\ninversion H1.\nQed.\n\nLemma eq_block_lem:\n    forall (A: Set) a (b: A) c, (if eq_block a a then b else c) = b.\nProof.\nintros.\nunfold eq_block.\nrewrite peq_true.\nauto.\nQed.\n\n(*moved to coqlib4\nLemma nat_ind2_Type:\nforall P : nat -> Type,\n((forall n, (forall j:nat, (j<n )%nat -> P j) ->  P n):Type) ->\n(forall n, P n).\nProof.\nintros.\nassert (forall j , (j <= n)%nat -> P j).\ninduction n.\nintros.\nreplace j with 0%nat ; try omega.\napply X; intros.\nelimtype False; omega.\nintros.  apply X. intros.\napply IHn.\nomega.\napply X0.\nomega.\nQed.\n\nLemma nat_ind2:\nforall P : nat -> Prop,\n(forall n, (forall j:nat, (j<n )%nat -> P j) ->  P n) ->\n(forall n, P n).\nProof.\nintros; apply Wf_nat.lt_wf_ind. auto.\nQed.*)\n\nLemma signed_zero: Int.signed Int.zero = 0.\nProof. apply Int.signed_zero. Qed.\n\nLemma equiv_e1 : forall A B: Prop, A=B -> A -> B.\nProof.\nintros.\nrewrite <- H; auto.\nQed.\nArguments equiv_e1 [A B] _ _.\n\n(*moved to coqlib4\nLemma equiv_e2 : forall A B: Prop, A=B -> B -> A.\nProof.\nintros.\nrewrite H; auto.\nQed.\nArguments equiv_e2 [A B] _ _.\n*)\n\nLemma deref_loc_fun: forall {ty m b z v v'},\n   Clight.deref_loc ty m b z v -> Clight.deref_loc ty m b z v' -> v=v'.\n Proof. intros.  inv H; inv H0; try congruence.\nQed.\n\nLemma eval_expr_lvalue_fun:\n  forall ge e le m,\n    (forall a v v', Clight.eval_expr ge e le m a v -> Clight.eval_expr ge e le m a v' -> v=v') /\\\n    (forall a b b' i i', Clight.eval_lvalue ge e le m a b i -> Clight.eval_lvalue ge e le m a b' i' ->\n                               (b,i)=(b',i')).\nProof.\n intros.\n destruct (Clight.eval_expr_lvalue_ind ge e le m\n   (fun a v =>  forall v', Clight.eval_expr ge e le m a v' -> v=v')\n   (fun a b i => forall b' i', Clight.eval_lvalue ge e le m a b' i' -> (b,i)=(b',i')));\n  simpl; intros;\n\n  try solve [repeat\n  match goal with\n  |  H: eval_expr _ _ _ _ ?a _  |- _ => (is_var a; fail 1) || inv H\n  | H: eval_lvalue _ _ _ _ ?a _ _ |- _  => (is_var a; fail 1) || inv H\n  end; congruence].\n\n * inv H1. apply H0 in H5; congruence. inv H2.\n * inv H2. apply H0 in H7; congruence. inv H3.\n * inv H4. apply H0 in H10. apply H2 in H11. congruence. inv H5.\n * inv H2. apply H0 in H5. congruence. inv H4. inv H3. inv H3. inv H3.\n * inv H; inv H2. apply H0 in H. inv H. eapply deref_loc_fun; eauto.\n   inv H. congruence. inversion2 H4 H10.  eapply deref_loc_fun; eauto.\n   apply H0 in H. inv H.  eapply deref_loc_fun; eauto.\n   apply H0 in H. inv H.  eapply deref_loc_fun; eauto.\n   apply H0 in H. inv H.  eapply deref_loc_fun; eauto.\n * inv H1. apply H0 in H6. congruence.\n * inv H4. apply H0 in H8. congruence. congruence.\n * inv H3. apply H0 in H7. congruence. apply H0 in H7. congruence.\n\n * split; intros; [apply (H _ _ H1 _ H2) | apply (H0 _ _ _ H1 _ _ H2)].\nQed.\n\nLemma eval_expr_fun:   forall {ge e le m a v v'},\n    Clight.eval_expr ge e le m a v -> Clight.eval_expr ge e le m a v' -> v=v'.\nProof.\n  intros. destruct (eval_expr_lvalue_fun ge e le m).\n  eauto.\nQed.\n\nLemma eval_exprlist_fun:   forall {ge e le m a ty v v'},\n    Clight.eval_exprlist ge e le m a ty v -> Clight.eval_exprlist ge e le m a ty v' -> v=v'.\nProof.\n  induction a; intros; inv H; inv H0; f_equal.\n  apply (eval_expr_fun H3) in H6. subst. congruence.\n  eauto.\nQed.\n\n\nLemma eval_lvalue_fun:   forall {ge e le m a b b' z z'},\n    Clight.eval_lvalue ge e le m a b z -> Clight.eval_lvalue ge e le m a b' z' -> (b,z)=(b',z').\nProof.\n  intros. destruct (eval_expr_lvalue_fun ge e le m).\n  eauto.\nQed.\n\n\nLemma inv_find_symbol_fun:\n  forall {ge id id' b},\n    Senv.find_symbol ge id = Some b ->\n    Senv.find_symbol ge id' = Some b ->\n    id=id'.\nProof.\n  intros.\n  apply Senv.find_invert_symbol in H.\n  apply Senv.find_invert_symbol in H0.\n  rewrite H0 in H.\n  inversion H.\n  reflexivity.\nQed.\n\nLemma assign_loc_fun:\n  forall {cenv ty m b ofs v m1 m2},\n   assign_loc cenv ty m b ofs v m1 ->\n   assign_loc cenv ty m b ofs v m2 ->\n   m1=m2.\nProof.\n intros. inv H; inv H0; try congruence.\nQed.\n\nLemma alloc_variables_fun:\n  forall {ge e m vl e1 m1 e2 m2},\n     Clight.alloc_variables ge e m vl e1 m1 ->\n     Clight.alloc_variables ge e m vl e2 m2 ->\n     (e1,m1)=(e2,m2).\nProof.\n intros until vl; revert e m;\n induction vl; intros; inv H; inv H0; auto.\n inversion2 H5 H9.\n eauto.\nQed.\n\nLemma bind_parameters_fun:\n  forall {ge e m p v m1 m2},\n    Clight.bind_parameters ge e m p v m1 ->\n    Clight.bind_parameters ge e m p v m2 ->\n    m1=m2.\nProof.\nintros until p. revert e m; induction p; intros; inv H; inv H0; auto.\n inversion2 H3 H10.\n apply (assign_loc_fun H5) in H11. inv H11. eauto.\nQed.\n\nLemma eventval_list_match_fun:\n  forall {se a a' t v},\n    Events.eventval_list_match se a t v ->\n    Events.eventval_list_match se a' t v ->\n    a=a'.\nProof.\n intros.\n revert a' H0; induction H; intros.\n inv H0; eauto.\n inv H1.\n f_equal. clear - H6 H.\n inv H; inv H6; auto.\n apply (inv_find_symbol_fun H1) in H5; subst; auto.\n eauto.\nQed.\n\nLtac fun_tac :=\n  match goal with\n  | H: ?A = Some _, H': ?A = Some _ |- _ => inversion2 H H'\n  | H: Clight.eval_expr ?ge ?e ?le ?m ?A _,\n    H': Clight.eval_expr ?ge ?e ?le ?m ?A _ |- _ =>\n        apply (eval_expr_fun H) in H'; subst\n  | H: Clight.eval_exprlist ?ge ?e ?le ?m ?A ?ty _,\n    H': Clight.eval_exprlist ?ge ?e ?le ?m ?A ?ty _ |- _ =>\n        apply (eval_exprlist_fun H) in H'; subst\n  | H: Clight.eval_lvalue ?ge ?e ?le ?m ?A _ _,\n    H': Clight.eval_lvalue ?ge ?e ?le ?m ?A _ _ |- _ =>\n        apply (eval_lvalue_fun H) in H'; inv H'\n  | H: Clight.assign_loc ?ge ?ty ?m ?b ?ofs ?v _,\n    H': Clight.assign_loc ?ge ?ty ?m ?b ?ofs ?v _ |- _ =>\n        apply (assign_loc_fun H) in H'; inv H'\n  | H: Clight.deref_loc ?ty ?m ?b ?ofs _,\n    H': Clight.deref_loc ?ty ?m ?b ?ofs _ |- _ =>\n        apply (deref_loc_fun H) in H'; inv H'\n  | H: Clight.alloc_variables ?ge ?e ?m ?vl _ _,\n    H': Clight.alloc_variables ?ge ?e ?m ?vl _ _ |- _ =>\n        apply (alloc_variables_fun H) in H'; inv H'\n  | H: Clight.bind_parameters ?ge ?e ?m ?p ?vl _,\n    H': Clight.bind_parameters ?ge ?e ?m ?p ?vl _ |- _ =>\n        apply (bind_parameters_fun H) in H'; inv H'\n  | H: Senv.find_symbol ?ge _ = Some ?b,\n    H': Senv.find_symbol ?ge _ = Some ?b |- _ =>\n       apply (inv_find_symbol_fun H) in H'; inv H'\n  | H: Events.eventval_list_match ?ge _ ?t ?v,\n    H': Events.eventval_list_match ?ge _ ?t ?v |- _ =>\n       apply (eventval_list_match_fun H) in H'; inv H'\n end.\n\n(* Lemmas about ident lists -- moved to general_base of mpred\n\nFixpoint id_in_list (id: ident) (ids: list ident) : bool :=\n match ids with i::ids' => orb (Pos.eqb id i) (id_in_list id ids') | _ => false end.\n\nFixpoint compute_list_norepet (ids: list ident) : bool :=\n match ids with\n | id :: ids' => if id_in_list id ids' then false else compute_list_norepet ids'\n | nil => true\n end.\n\nLemma id_in_list_true: forall i ids, id_in_list i ids = true -> In i ids.\nProof.\n induction ids; simpl; intros. inv H. apply orb_true_iff in H; destruct H; auto.\n apply Peqb_true_eq in H. subst; auto.\nQed.\n\nLemma id_in_list_false: forall i ids, id_in_list i ids = false -> ~In i ids.\nProof.\n induction ids; simpl; intros; auto.\n apply orb_false_iff in H. destruct H.\n intros [?|?]. subst.\n rewrite Pos.eqb_refl in H; inv H.\n apply IHids; auto.\nQed.\n\nLemma compute_list_norepet_e: forall ids,\n     compute_list_norepet ids = true -> list_norepet ids.\nProof.\n induction ids; simpl; intros.\n constructor.\n revert H; case_eq (id_in_list a ids); intros.\n inv H0.\n constructor; auto.\n apply id_in_list_false in H.\n auto.\nQed.\n\nLemma list_norepet_rev:\n  forall A (l: list A), list_norepet (rev l) = list_norepet l.\nProof.\ninduction l; simpl; auto.\napply prop_ext; split; intros.\napply list_norepet_app in H.\ndestruct H as [? [? ?]].\nrewrite IHl in H.\nconstructor; auto.\neapply list_disjoint_notin with (a::nil).\napply list_disjoint_sym; auto.\nintros x y ? ? ?; subst.\ncontradiction (H1 y y); auto.\nrewrite <- In_rev; auto.\nsimpl; auto.\nrewrite list_norepet_app.\ninv H.\nsplit3; auto.\nrewrite IHl; auto.\nrepeat constructor.\nintro Hx. inv Hx.\nintros x y ? ? ?; subst.\ninv H0.\nrewrite <- In_rev in H; contradiction.\nauto.\nQed.\n\nLemma block_eq_dec: forall b1 b2: block, {b1 = b2} + {b1 <> b2}.\nProof. exact (Coqlib.peq). Qed.\n\n(*moved to mpred\nDefinition int_range (sz: intsize) (sgn: signedness) (i: int) :=\n match sz, sgn with\n | I8, Signed => -128 <= Int.signed i < 128\n | I8, Unsigned => 0 <= Int.unsigned i < 256\n | I16, Signed => -32768 <= Int.signed i < 32768\n | I16, Unsigned => 0 <= Int.unsigned i < 65536\n | I32, Signed => -2147483648 <= Int.signed i < 2147483648\n | I32, Unsigned => 0 <= Int.unsigned i < 4294967296\n | IBool, _ => 0 <= Int.unsigned i < 256\nend.*)\n\nLemma rev_if_be_singleton:\n  forall x, rev_if_be (x::nil) = (x::nil).\nProof. intro. unfold rev_if_be; destruct Archi.big_endian; auto. Qed.\n\nLemma rev_if_be_1: forall i, rev_if_be (i::nil) = (i::nil).\nProof. unfold rev_if_be; intros. destruct Archi.big_endian; reflexivity.\nQed.\n\nLemma decode_byte_val:\n  forall m, decode_val Mint8unsigned (Byte m :: nil) =\n              Vint (Int.zero_ext 8 (Int.repr (Byte.unsigned m))).\nProof.\nintros.\nunfold decode_val. simpl.\nf_equal.\nunfold decode_int.\nrewrite rev_if_be_singleton.\nunfold int_of_bytes. f_equal. f_equal. apply Z.add_0_r.\nQed.\n\nLemma Vint_inj: forall x y, Vint x = Vint y -> x=y.\nProof. congruence. Qed.\n\n*)", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/veric/Clight_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2274252329400529}}
{"text": "Require Import Platform.AutoSep Platform.Malloc Platform.Bootstrap Platform.Cito.examples.ReturnZero.\n\n\nModule Type S.\n  Variable heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"top\"!\"top\" @ [topS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Call \"top\"!\"top\"()\n        [PREonly[_] [| False |] ]\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Definition m0 := link Malloc.m boot.\n  Definition m1 := link all m0.\n\n  Lemma ok0 : moduleOk m0.\n    link Malloc.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link all_ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n\n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, $ (size * 4) <= w -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Cito/examples/ReturnZeroDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22738085596977434}}
{"text": "Require Import CertifiedExtraction.FMapUtils.\nRequire Export Bedrock.Memory Bedrock.Platform.Facade.DFacade.\nRequire Export Bedrock.Platform.Cito.StringMap Bedrock.Platform.Cito.StringMapFacts.\n\nModule Export MoreStringMapFacts := WMoreFacts_fun (StringMap.E) (StringMap).\n\nGlobal Open Scope map_scope.\n\nLemma urgh : (subrelation eq (Basics.flip Basics.impl)).\nProof.\n  repeat red; intros; subst; assumption.\nQed.\n\n(* NOTE: Why is this needed? *)\nHint Resolve urgh : typeclass_instances.\n\n(* Lemma Bug: *)\n(*   forall k1 k2 (st: StringMap.t nat) (x : nat), *)\n(*     StringMap.MapsTo k1 x st -> *)\n(*     match StringMap.find k2 (StringMap.add k2 x (StringMap.add k1 x st)) with *)\n(*     | Some _ => True *)\n(*     | None => True *)\n(*     end. *)\n(* Proof. *)\n(*   intros ** H. *)\n(*   setoid_rewrite <- (StringMapUtils.add_redundant_cancel H). *)\n(*   (* Inifinite loop unless `urgh' is added as a hint *) *)\n(* Abort. *)\n\nRequire Import Coq.Setoids.Setoid.\n\nAdd Parametric Morphism {av} : (@StringMap.find av)\n    with signature (eq ==> StringMap.Equal ==> eq)\n      as find_Morphism.\nProof.\n  intros; erewrite find_m; intuition.\nQed.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/CertifiedExtraction/StringMapUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2272951850602278}}
{"text": "(* Multiple inputs and outputs, full or empty reads *)\nRequire Import Merges.Tactics.\nRequire Import Merges.Map.\n\n\nRequire Import Merges.List.List.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nSet Implicit Arguments.\nRequire Import Coq.Logic.FunctionalExtensionality.\n\n\nModule Base.\nSection Machine.\n  Variable Label : Set.\n\n  Definition Value := nat.\n\n  Variable StreamV : Set.\n  Variable StreamVEqDec : EqDec StreamV.\n\n  Definition Heap := Map StreamV (list Value).\n  Definition Pred := Heap -> Prop.\n\n  Let streamUpdate := Map.update StreamV (list Value) StreamVEqDec.\n\n  Inductive StreamTypeT :=\n   | Input | Output | Ignore.\n  Variable StreamType : StreamV -> StreamTypeT.\n\n  Inductive Block : Type :=\n   (* Blocking pull, wait forever until we get something *)\n   | BlockPull : StreamV -> Label -> Label -> Block\n   (* Release the thing we just pulled.\n      When two machines are pulling from same thing, this\n      signals to other machine that it can now pull if it wants *)\n   | BlockRelease : StreamV -> Label -> Block\n   (* Push a constant value *)\n   | BlockPush : StreamV -> Value -> Label -> Block\n   (* Jump to another label without doing anything *)\n   | BlockJump   : Label -> Block\n   .\n\n  Variable Blocks : Label -> Block.\n  Variable LabelPre  : Label -> Pred.\n\n  Inductive EvalB : Heap -> Label\n                 -> Heap -> Label -> Prop :=\n   | EvalBPullOk l v lok i h\n      : Blocks l = BlockPull v lok\n     -> StreamType v = Input\n     -> EvalB h l\n              (streamUpdate v (h v ++ [i]) h) lok\n\n   (* Release does nothing *)\n   | EvalBRelease l v l' h\n      : Blocks l = BlockRelease v l'\n     -> StreamType v = Input\n     -> EvalB h l\n              h l'\n\n   | EvalBPush l v push l' h\n      : Blocks l = BlockPush v push l'\n     -> StreamType v = Output\n     -> EvalB h l\n              (streamUpdate v (h v ++ [push]) h) l'\n\n   | EvalBJump l l' h\n      : Blocks l = BlockJump l'\n     -> EvalB h l\n              h l'\n\n   | EvalBIgnore l v i h\n      : StreamType v = Ignore\n     -> EvalB h l\n              (streamUpdate v (h v ++ [i]) h) l\n   .\n  Hint Constructors EvalB.\n\n  Variable Init : Label.\n  Variable InitPre : LabelPre Init (fun _ => []).\n\n  Inductive EvalBs : Heap -> Label -> Prop :=\n   | EvalBs0\n      : EvalBs (fun _ => []) Init\n   | EvalBs1 l l' h h'\n      : EvalBs h l\n     -> EvalB  h l h' l'\n     -> EvalBs h' l'\n   .\n  Hint Constructors EvalBs.\n\n  Definition BlocksPreT :=\n    forall h h' l l',\n    EvalBs h l ->\n    LabelPre l h ->\n    EvalB  h l h' l' ->\n    LabelPre l' h'.\n\n  Hypothesis BlocksPre: BlocksPreT.\n\n\n  (*\n  This is not true, since BlockPull does not require StreamType v = Input,\n  but EvalB does.\n  I don't think this is a real problem though, it wasn't used in any\n  of the earlier proofs.\n\n  Theorem EvalB_Step l h\n         : exists l' h'\n         , EvalB h  l h' l'.\n  *)\n\n  Theorem EvalBs_Hoare l h\n   (hEvB : EvalBs h l)\n         : LabelPre l h.\n  Proof.\n   !induction hEvB.\n  Qed.\nEnd Machine.\n\nEnd Base.\n\nModule Program.\n Module B := Base.\n\n Record Program (Label : Set) (StreamVar : Set) : Type\n  := mkProgram\n   { Init     : Label\n   ; Blocks   : Label -> B.Block Label StreamVar\n\n   ; StreamVarEqDec : EqDec StreamVar\n   ; StreamType : StreamVar -> B.StreamTypeT\n\n   ; LabelPre : Label -> B.Pred StreamVar\n   ; BlocksPre: B.BlocksPreT StreamVarEqDec StreamType Blocks LabelPre Init\n   ; InitPre  : LabelPre Init (fun _ => [])\n   }.\n\n  Definition EvalBs (Label : Set) (StreamVar : Set) (P : Program Label StreamVar)\n   := B.EvalBs (StreamVarEqDec P) (StreamType P) (Blocks P) (Init P).\n\nEnd Program.\n\n\nModule Fuse.\n  Module B := Base.\n  Module P := Program.\n\n  Parameter SV : Set.\n  Parameter L1 : Set.\n  Parameter P1 : P.Program L1 SV.\n\n  Parameter L2 : Set.\n  Parameter P2 : P.Program L2 SV.\n\n  (* Figure out what the fused StreamType will be *)\n  Definition StreamType (s : SV) : B.StreamTypeT :=\n  match P.StreamType P1 s, P.StreamType P2 s with\n  (* If left ignores, take whatever right does *)\n  | B.Ignore, t\n  => t\n  (* Vice versa *)\n  | t, B.Ignore\n  => t\n  (* If either is an output, it will be an output in the fused *)\n  | B.Output, _\n  => B.Output\n  | _, B.Output\n  => B.Output\n  (* If both are inputs, end result is an input *)\n  | B.Input, B.Input\n  => B.Input\n  end.\n\n  Inductive State :=\n    | FakeValue\n    | HaveValue\n    | NoValue\n    .\n\n  Inductive IsValid :=\n    | Valid\n    | INVALID\n    .\n\n  Inductive L' :=\n    | LX (l1 : L1) (l2 : L2) (s1 : SV -> State) (s2 : SV -> State) (v : IsValid).\n\n  Definition stateUpdate := Map.update SV State (P.StreamVarEqDec P1).\n  Check stateUpdate.\n\n  Inductive BlockOption :=\n    | BlockOk (b : B.Block L' SV)\n    | BlockTryOther\n    | BlockINVALID\n    .\n\n  Definition makeBlock\n    (LA : Set)\n    (mkLabel : LA -> (SV -> State) -> (SV -> State) -> L')\n    (block : B.Block LA SV)\n    (sThis sOther : SV -> State)\n    (typeThis : SV -> B.StreamTypeT)\n    (typeOther : SV -> B.StreamTypeT)\n           : BlockOption :=\n   match block with\n    | B.BlockJump _ l'\n    => BlockOk (B.BlockJump _ (mkLabel l' sThis sOther))\n\n    (* Releases are fairly simple, so let's start with them *)\n    | B.BlockRelease sv l'\n    => match typeThis sv, typeOther sv, sThis sv with\n       (* If the other machine ignores this, we can just release as normal *)\n       (* We require sThis to be 'NoValue' even though there is something: *)\n       (* it doesn't need to be tracked because it's ignored *)\n       | B.Input, B.Ignore, NoValue\n       => BlockOk (B.BlockRelease sv (mkLabel l' sThis sOther))\n\n       (* Both machines want to pull from this, so let's see.\n          This machine must have a value for sv in its state now:\n          sThis sv = HaveValue\n          But it depends whether the other machine has it\n       *)\n       | B.Input, B.Input, HaveValue\n       => match sOther sv with\n          (* If other machine still has one, we only pretend to release *)\n          | HaveValue\n          | FakeValue\n          => BlockOk (B.BlockJump _ (mkLabel l' (stateUpdate sv NoValue sThis) sOther))\n          (* Other machine has already pretended to release *)\n          | NoValue\n          => BlockOk (B.BlockRelease sv (mkLabel l' (stateUpdate sv NoValue sThis) sOther))\n          end\n\n       (* The other machine has pushed this, so only pretend release *)\n       | B.Input, B.Output, HaveValue\n       => BlockOk (B.BlockJump _ (mkLabel l' (stateUpdate sv NoValue sThis) sOther))\n\n       (* Otherwise sThis sv is invalid *)\n       | _, _, _\n       => BlockINVALID\n       end\n\n    (* Pulls are a bit more interesting *)\n    | B.BlockPull sv l'\n    => match typeThis sv, typeOther sv, sThis sv with\n       (* Ignore is easy *)\n       | B.Input, B.Ignore, NoValue\n       => BlockOk (B.BlockPull sv (mkLabel l' sThis sOther))\n\n       (* Both machines want to pull from this, so let's see. *)\n       (* We already have a fake one, ready to go. Just a jump *)\n       | B.Input, B.Input, FakeValue\n       => BlockOk (B.BlockJump _ (mkLabel l' (stateUpdate sv HaveValue sThis) sOther))\n       | B.Input, B.Input, NoValue\n       => match sOther sv with\n          (* If other machine has one but we don't, that means\n             we have already pulled and released, but they haven't released yet.\n             They need to run a bit and hopefully release.\n           *)\n          | HaveValue\n          | FakeValue\n          => BlockTryOther\n          (* Neither machine has it, but we both want it.\n             We end up with a real value, and them a fake. *)\n          | NoValue\n          => BlockOk (B.BlockPull sv (mkLabel l' (stateUpdate sv HaveValue sThis) (stateUpdate sv FakeValue sOther)))\n          end\n\n       (* The other machine must push. Have they given us anything yet? *)\n       | B.Input, B.Output, NoValue\n       => match sThis sv with\n          (* Yes. We have a fake value on top, so we can turn it into a real one *)\n          | FakeValue\n          => BlockOk (B.BlockJump _ (mkLabel l'  (stateUpdate sv HaveValue sThis) sOther))\n          (* We can't have a real one yet!!! *)\n          | HaveValue\n          => BlockINVALID\n          (* No, we have to wait. Try to let the other machine run *)\n          | NoValue\n          => BlockTryOther\n          end\n\n       (* Otherwise sThis sv is invalid *)\n       | _, _, _\n       => BlockINVALID\n       end\n\n    (* Pushes are pretty similar *)\n    | B.BlockPush sv v l'\n    => match typeThis sv, typeOther sv, sThis sv with\n       (* Ignore is easy *)\n       | B.Output, B.Ignore, NoValue\n       => BlockOk (B.BlockPush sv v (mkLabel l' sThis sOther))\n       (* Check if the other machine is ready to scoop a new one *)\n       | B.Output, B.Input, NoValue\n       => match sOther sv with\n          (* No. The other machine has a value it hasn't already used *)\n          | HaveValue\n          | FakeValue\n          => BlockTryOther\n          (* Other machine is empty and ready to receive *)\n          | NoValue\n          (*=> BlockOk (B.BlockJump _ (mkLabel l' sThis (stateUpdate sv FakeValue sOther)))*)\n          => BlockOk (B.BlockPush sv v (mkLabel l' sThis (stateUpdate sv FakeValue sOther)))\n          end\n       (* Both programs cannot push to the same output *)\n       | _, B.Output, _\n       => BlockINVALID\n       (* sThis sv is invalid *)\n       | _, _, _\n       => BlockINVALID\n       end\n   end.\n\n\n  Definition Blocks (l : L') : B.Block L' SV :=\n   match l with\n   | LX l1 l2 s1 s2 v\n   => let invalid := B.BlockJump _ (LX l1 l2 s1 s2 INVALID) in\n      match v\n    , makeBlock (fun l1' s1' s2' => LX l1' l2 s1' s2' Valid) (P.Blocks P1 l1) s1 s2 (P.StreamType P1) (P.StreamType P2)\n    , makeBlock (fun l2' s2' s1' => LX l1 l2' s1' s2' Valid) (P.Blocks P2 l2) s2 s1 (P.StreamType P2) (P.StreamType P1)\n      with\n      | Valid, BlockINVALID, _\n      => invalid\n      | Valid, _, BlockINVALID\n      => invalid\n      | Valid, BlockOk block, _\n      => block\n      | Valid, _, BlockOk block\n      => block\n      | _, _, _\n      => invalid\n      end\n    end.\n\n\n  Definition Evalish (LA : Set) (P : P.Program LA SV) (s : SV -> State) (iss : B.Heap SV) (l : LA) : Prop :=\n   exists iss',\n  (* It turns out the proof is slightly easier if we put the EvalBs first.\n     Because the EvalBs is more likely to instantiate the existential *)\n    P.EvalBs P iss' l /\\\n    (forall sv,\n     match s sv with\n      | FakeValue => exists i, iss sv = iss' sv ++ [i]\n      | HaveValue => iss' sv = iss sv\n      | NoValue   => iss' sv = iss sv\n     end /\\\n     (P.StreamType P sv = B.Ignore -> s sv = NoValue)\n     ).\n\n  Definition LabelPre (l : L') : B.Pred SV :=\n   match l with\n   | LX l1 l2 s1 s2 INVALID\n   => fun _ => True\n   | LX l1 l2 s1 s2 Valid\n   => fun iss\n   => Evalish P1 s1 iss l1\n   /\\ Evalish P2 s2 iss l2\n   end.\n  Hint Unfold LabelPre.\n\n\n  Program Definition r\n  := {| P.Blocks := Blocks\n      ; P.LabelPre := LabelPre\n      ; P.Init := LX (P.Init P1) (P.Init P2) (fun _ => NoValue) (fun _ => NoValue) Valid\n      ; P.StreamType := StreamType\n      ; P.StreamVarEqDec := P.StreamVarEqDec P1\n      |}.\n\n  Next Obligation.\n   Ltac doit X := try solve [(!eapply B.EvalBs1); (!eapply X)].\n\n\n  Ltac destruct_apps FUN :=\n  repeat match goal with\n  | [ _ : context [ FUN ?a ] |- _ ]\n  => let x := fresh \"destruct_\" FUN in remember (FUN a) as x\n     ; destruct x\n     ; tryfalse\n     ; repeat match goal with\n       | [ H : _ = FUN a |- _ ] => gen H\n       end\n  end;\n   intros.\n\n  Ltac matchmaker Heq :=\n   match goal with\n  | [ Heq : _ = match ?A with | _ => _ end |- _ ]\n  => let x    := fresh \"scrut_\" Heq\n  in let Heqx := fresh \"Heq_\" x\n  in remember A as x eqn:Heqx; destruct x; try rewrite <- Heqx in *; tryfalse\n   ; try matchmaker Heqx\n  end.\n\n\n\n   unfolds B.BlocksPreT.\n   introv hEvBs hLbl hEvB.\n   clear hEvBs.\n   destruct l; destruct l'.\n   !destruct v0; destruct v; try solve [inverts hEvB; tryfalse].\n\n   simpls; unfolds Evalish; unfolds Blocks; unfolds makeBlock.\n\n  inverts hEvB.\n  - (* BlockPull *)\n    symmetry in H0.\n    symmetry in H; matchmaker H.\n    all: inject_all.\n    all: !jauto_set\n      ; doit B.EvalBPullOk\n      ; doit B.EvalBIgnore\n      ; try assumption\n      .\n\n    all: intros; unfolds stateUpdate; forwards: H0 sv; forwards: H2 sv.\n    all: try match goal with\n          | [ |- context [match update SV _ _ ?A _ _ ?B with | _ => _ end] ]\n          => destruct (P.StreamVarEqDec P1 A B); substs\n         end; substs.\n    all: jauto_set.\n    all: repeat match goal with\n    | [ ABC : _ = _  |- _]\n    => rewrite <- ABC in *\n    end.\n    all: !intros; jauto.\n    all: tryfalse.\n    all: !repeat rewrite update_eq_is.\n    all: try solve [!repeat rewrite update_ne_is].\n\n    all: try match goal with\n          | [ |- context [update SV _ _ ?A _ _ ?B] ]\n          => destruct (P.StreamVarEqDec P1 A B); substs\n         end; !substs.\n    all: !repeat rewrite update_eq_is.\n    all: try solve [!repeat rewrite update_ne_is].\n\n    all: !repeat match goal with\n    | [ ABC : _ = _  |- _]\n    => rewrite <- ABC in *\n    end.\n\n    all: !try match goal with\n          | [ ABC : (?A = ?A) -> _ = _ |- _]\n          => !rewrite ABC in *\n         end.\n\n    all: !repeat match goal with\n    | [ ABC : _ = _  |- _]\n    => rewrite <- ABC in *\n    end.\n\n\n\n  - (* BlockRelease *)\n    symmetry in H0.\n    symmetry in H; matchmaker H.\n    all: inject_all.\n    all: !jauto_set\n      ; doit B.EvalBRelease\n      ; try assumption\n      .\n    all: !intros; jauto_set.\n\n    all: !intros.\n    all: unfolds stateUpdate; forwards: H0 sv; forwards: H2 sv.\n\n    all: try match goal with\n          | [ |- context [update SV _ _ ?A _ _ ?B] ]\n          => destruct (P.StreamVarEqDec P1 A B); substs\n         end; !substs.\n    all: !repeat rewrite update_eq_is.\n    all: try solve [!repeat rewrite update_ne_is].\n\n    all: !jauto_set.\n    all: !repeat match goal with\n    | [ ABC : _ = _  |- _]\n    => rewrite <- ABC in *\n    end.\n\n  - (* BlockPush *)\n    symmetry in H0.\n    symmetry in H; matchmaker H.\n    all: inject_all.\n    all: !jauto_set\n      ; doit B.EvalBIgnore\n      ; doit B.EvalBPush\n      .\n    all: !intros; unfolds stateUpdate; forwards: H0 sv; forwards: H2 sv; jauto_set.\n\n    all: try match goal with\n          | [ |- context [update SV _ _ ?A _ _ ?B] ]\n          => destruct (P.StreamVarEqDec P1 A B); substs\n         end; !substs.\n    all: !repeat rewrite update_eq_is.\n    all: try solve [!repeat rewrite update_ne_is].\n\n    all: !repeat match goal with\n    | [ ABC : _ = _  |- _]\n    => rewrite <- ABC in *\n    end.\n    all: !try match goal with\n          | [ ABC : (?A = ?A) -> _ = _ |- _]\n          => !rewrite ABC in *\n         end.\n    all: !repeat match goal with\n    | [ ABC : _ = _  |- _]\n    => rewrite <- ABC in *\n    end.\n\n    all: intros; tryfalse.\n\n  - (* BlockJump *)\n    jauto_set_hyps; intros.\n    symmetry in H; matchmaker H.\n    all: inject_all.\n    all: try forwards: H1 s; try forwards: H1 s4; try forwards: H3 s; try forwards: H3 s4.\n    all: jauto_set_hyps.\n    all: intros.\n\n    all: !repeat match goal with\n    | [ ABC : _ = _  |- _]\n    => rewrite <- ABC in *\n    end.\n    all: !try match goal with\n          | [ ABC : (?A = ?A) -> _ = _ |- _]\n          => !rewrite ABC in *\n         end.\n    all: !repeat match goal with\n    | [ ABC : _ = _  |- _]\n    => rewrite <- ABC in *\n    end.\n\n\n\n(*\n\nHeq_scrut_Heq_scrut_H0 : P.B.BlockJump SV l = P.Blocks P2 l2\nH4 : P.B.Input = B.Ignore -> FakeValue = NoValue\nH6 : P.B.Input = B.Ignore -> s2 sv = NoValue\nHeq_scrut_Heq_scrut_H : P.B.BlockPull sv l4 = P.Blocks P1 l1\nHeq_scrut_Heq_scrut_H1 : P.B.Input = P.StreamType P1 sv\nHeq_scrut_Heq_scrut_H2 : P.B.Input = P.StreamType P2 sv\nHeq_scrut_Heq_scrut_H3 : FakeValue = s1 sv\n\n*)\n    all: !jauto_set.\n    all: doit B.EvalBJump.\n    all: doit B.EvalBPullOk.\n    all: doit B.EvalBIgnore.\n    all: doit B.EvalBRelease.\n    all: doit B.EvalBPush.\n\n    all: !intros; unfolds stateUpdate; forwards: H1 sv; forwards: H3 sv; jauto_set.\n    all: !intros; tryfalse.\n\n    all: !repeat match goal with\n    | [ ABC : _ = _  |- _]\n    => rewrite <- ABC in *\n    end.\n    all: jauto_set.\n\n    all: try match goal with\n          | [ |- context [update SV _ _ ?A _ _ ?B] ]\n          => destruct (P.StreamVarEqDec P1 A B); substs\n         end; !substs.\n\n\n    all: !repeat rewrite update_eq_is.\n    all: try solve [!repeat rewrite update_ne_is].\n    all: tryfalse.\n    all: !repeat match goal with\n    | [ ABC : _ = _  |- _]\n    => rewrite <- ABC in *\n    end.\n\n  - (* Ignore! *)\n    unfolds StreamType.\n    !destruct (P.StreamType P1 v) eqn:StreamType1; destruct (P.StreamType P2 v) eqn:StreamType2; tryfalse.\n    jauto_set.\n    all: doit B.EvalBIgnore.\n    all: intros.\n    all: forwards: H0 sv; forwards: H2 sv.\n    all: !jauto_set.\n    all: destruct (P.StreamVarEqDec P1 v sv); substs.\n    all: !repeat rewrite update_eq_is.\n    all: try solve [!repeat rewrite update_ne_is].\n    \n    all: rewrite StreamType1 in *.\n    all: rewrite StreamType2 in *.\n    !rewrite H5 in *.\n    rewrite H4. reflexivity.\n\n    !rewrite H7 in *.\n    rewrite H6. reflexivity.\n Qed.\n Next Obligation.\n  unfolds Evalish.\n  jauto_set;\n  try apply B.EvalBs0;\n  !jauto_set.\n Qed.\nEnd Fuse.\n\n\n", "meta": {"author": "amosr", "repo": "merges", "sha": "bf8cb7bca2d859977d6fb8bf4a9d07ac780b7edd", "save_path": "github-repos/coq/amosr-merges", "path": "github-repos/coq/amosr-merges/merges-bf8cb7bca2d859977d6fb8bf4a9d07ac780b7edd/stash/proof/Merges/HoareGoto/HoareGoto8_ManyWithEmpty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2272951788670089}}
{"text": "Require Import FOL.\nRequire Import Deduction.\nRequire Import Tarski.\nRequire Import VectorTech.\nRequire Import Theories.\nRequire Import List.\nRequire Import Lia.\nRequire Import List.\nRequire Import String.\nRequire Import Equations.Equations Equations.Prop.DepElim.\nImport ListNotations.\n\nOpen Scope string_scope.\n\n(* \n * I want to have an Iris-like proof mode, where the context is displayed\n * above a line with the current goal below. Also the assumptions should\n * have names.\n * This is all done using notation. But this notation should only be applied\n * in the goal, not in other hypothesis. Therefore I define aliases for \n * `prv` and lists that the notation can match for. Also the list alias\n * holds the assumption names as an extra argument.\n *)\n\nDefinition pm {p cf cp} C phi := @prv p cf cp C phi.\nArguments pm {_} {_} {_} _ _.\n\nDefinition tpm {p cf cp} C phi := @tprv p cf cp C phi.\nArguments tpm {_} {_} {_} _ _.\n\nSection PM.\n\nContext {Σ_funcs : funcs_signature}.\nContext {Σ_preds : preds_signature}.\n\nDefinition cnil := @nil form.\nDefinition ccons (s : string) phi C := @cons form phi C.\n(* Special alias for unknown lists. Only used to indent with one space in Notation *)\nDefinition cblackbox (A : list form) := A.\n\nDefinition tnil : theory := fun _ => False.\nDefinition tcons (s : string) phi (T : theory) : theory := extend T phi.\n(* Special alias for unknown theories. Only used to indent with one space in Notation *)\nDefinition tblackbox (T : theory) := T.\n\nEnd PM.\n\n\n(* Dummy tactic the end user *must* override if defined\n * terms like `zero` are used. *)\nLtac custom_fold := idtac.\n\n(* Dummy tactic the end user *must* override if defined\n * terms like `zero` are used. *)\n Ltac custom_unfold := idtac.\n\n(* Dummy tactic the end user can override to add domain\n * specific simplifications. *)\nLtac custom_simpl := idtac.\n\n\n\n(** Overload deduction rules to also work for theories: *)\n\nClass DeductionRules `{funcs_signature, preds_signature} (context : Type) (ent : context -> form -> Type) (cons : form -> context -> context) (map : (form -> form) -> context -> context) (In : form -> context -> Prop) :=\n{\n  II A phi psi : ent (cons phi A) psi -> ent A (phi --> psi) ;\n  IE A phi psi : ent A (phi --> psi) -> ent A phi -> ent A  psi ;\n  AllI A phi : ent (map (subst_form ↑) A) phi -> ent A (∀ phi) ;\n  AllE A t phi : ent A (∀ phi) -> ent A (phi[t..]) ;\n  ExI A t phi : ent A (phi[t..]) -> ent A (∃ phi) ;\n  ExE A phi psi : ent A (∃ phi) -> ent (cons phi (map (subst_form ↑) A)) (psi[↑]) -> ent A psi ;\n  Exp A phi : ent A ⊥ -> ent A phi ;\n  Ctx A phi : In phi A -> ent A phi ;\n  CI A phi psi : ent A phi -> ent A psi -> ent A (phi ∧ psi) ;\n  CE1 A phi psi : ent A (phi ∧ psi) -> ent A phi ;\n  CE2 A phi psi : ent A (phi ∧ psi) -> ent A psi ;\n  DI1 A phi psi : ent A phi -> ent A (phi ∨ psi) ;\n  DI2 A phi psi : ent A psi -> ent A (phi ∨ psi) ;\n  DE A phi psi theta : ent A (phi ∨ psi) -> ent (cons phi A) theta -> ent (cons psi A) theta -> ent A theta ;\n}.\n\nClass ClassicalDeductionRules `{funcs_signature, preds_signature} (context : Type) (ent : context -> form -> Type) :=\n{\n  Pc A phi psi : ent A (((phi --> psi) --> phi) --> phi)\n}.\n\nClass WeakClass `{funcs_signature, preds_signature} (context : Type) (ent : context -> form -> Type) (incl : context -> context -> Prop) :=\n{\n  Weak A B phi : ent A phi -> incl A B -> ent B phi\n}.\n\nInstance prv_DeductionRules `{funcs_signature, preds_signature, peirce} : DeductionRules (list form) prv cons (@List.map form form) (@In form) := \n{| \n  II := Deduction.II ;\n  IE := Deduction.IE ;\n  AllI := Deduction.AllI ;\n  AllE := Deduction.AllE ;\n  ExI := Deduction.ExI ;\n  ExE := Deduction.ExE ;\n  Exp := Deduction.Exp ;\n  Ctx := Deduction.Ctx ;\n  CI := Deduction.CI ;\n  CE1 := Deduction.CE1 ;\n  CE2 := Deduction.CE2 ;\n  DI1 := Deduction.DI1 ;\n  DI2 := Deduction.DI2 ;\n  DE := Deduction.DE ;\n|}.\n\nInstance prv_ClassicalDeductionRules `{funcs_signature, preds_signature} : ClassicalDeductionRules (list form) (@prv _ _ class) := \n{| \n  Pc := Deduction.Pc\n|}.\n\nInstance prv_WeakClass `{funcs_signature, preds_signature, peirce} : WeakClass (list form) prv (@List.incl form) := \n{| \n  Weak := Deduction.Weak\n|}.\n\nInstance tprv_DeductionRules `{funcs_signature, preds_signature, peirce, EqDec syms, EqDec preds} : DeductionRules theory tprv (fun a b => extend b a) mapT (fun a b => in_theory b a) := \n{| \n  II := Theories.T_II ;\n  IE := Theories.T_IE ;\n  AllI := Theories.T_AllI ;\n  AllE := Theories.T_AllE ;\n  ExI := Theories.T_ExI ;\n  ExE := Theories.T_ExE ;\n  Exp := Theories.T_Exp ;\n  Ctx := Theories.T_Ctx ;\n  CI := Theories.T_CI ;\n  CE1 := Theories.T_CE1 ;\n  CE2 := Theories.T_CE2 ;\n  DI1 := Theories.T_DI1 ;\n  DI2 := Theories.T_DI2 ;\n  DE := Theories.T_DE ;\n|}.\n\nInstance tprv_ClassicalDeductionRules `{funcs_signature, preds_signature} : ClassicalDeductionRules theory (@tprv _ _ class) := \n{| \n  Pc := Theories.T_Pc\n|}.\n\nInstance tprv_WeakClass `{funcs_signature, preds_signature, peirce} : WeakClass theory tprv subset_T := \n{| \n  Weak := Theories.WeakT\n|}.\n\n\n\n(** Context utilities *)\n\nDefinition digit_to_string n := match n with\n  | 0 => \"0\" | 1 => \"1\" | 2 => \"2\" | 3 => \"3\" | 4 => \"4\" | 5 => \"5\" \n  | 6 => \"6\" | 7 => \"7\" | 8 => \"8\" | 9 => \"9\" | _ => \"_\"\nend.\nFixpoint nat_to_string' fuel n := match fuel with\n  | 0 => \"OUT OF FUEL\"\n  | S fuel' => match n with\n    | 0 => \"\"\n    | _ =>  nat_to_string' fuel' (Nat.div n 10)  ++ digit_to_string (Nat.modulo n 10)\n    end\nend.\nDefinition nat_to_string n := match n with 0 => \"0\" | _ => nat_to_string' 100 n end.\n\n(* Returns the index of the first occurence of `name` in the \n * context `C`, or `None` if it doesn't exist. *)\nLtac lookup' n C name :=\n  match C with\n  | ccons name _ _ => constr:(Some n) \n  | ccons _ _ ?C' => lookup' (S n) C' name\n  | tcons name _ _ => constr:(Some n) \n  | tcons _ _ ?T' => lookup' (S n) T' name\n  | _ => None\n  end.\nLtac lookup := lookup' 0.\n\nLtac nth A n :=\n  match n with\n  | 0 => match A with ?t :: _ => t | extend _ ?t => t | ccons _ ?t _ => t | tcons _ ?t _ => t end\n  | S ?n' => match A with _ :: ?A' => nth A' n' | extend ?A' _ => nth A' n' | ccons _ _ ?A' => nth A' n' | tcons _ _ ?T' => nth T' n' end\n  end.\n\nLtac remove A n :=\n  match n with\n  | 0 => match A with _ :: ?A' => A' | extend ?A' _ => A' | ccons _ _ ?A' => A' | tcons _ _ ?A' => A' end\n  | S ?n' => match A with \n    | ?t :: ?A' => let A'' := remove A' n' in constr:(t::A'') \n    | extend ?A' ?t => let A'' := remove A' n' in constr:(extend t A'') \n    | ccons ?s ?t ?A' => let A'' := remove A' n' in constr:(ccons s t A'') \n    | tcons ?s ?t ?A' => let A'' := remove A' n' in constr:(tcons s t A'') \n    end\n  end.\n\nLtac replace_ltac A n phi :=\n  match n with\n  | 0 => match A with _ :: ?A' => constr:(phi::A') | extend ?A' _ => constr:(extend A' phi) | ccons ?s _ ?A' => constr:(ccons s phi A') | tcons ?s _ ?A' => constr:(tcons s phi A') end\n  | S ?n' => match A with \n    | ?t :: ?A' => let A'' := replace_ltac A' n' phi in constr:(t::A'') \n    | extend ?A' ?t => let A'' := replace_ltac A' n' phi in constr:(extend t A'') \n    | ccons ?s ?t ?A' => let A'' := replace_ltac A' n' phi in constr:(ccons s t A'') \n    | tcons ?s ?t ?A' => let A'' := replace_ltac A' n' phi in constr:(tcons s t A'') \n    end\n  end.\n\nLtac map_ltac A f :=\n  match A with\n  | nil => constr:(nil)\n  | cnil => constr:(cnil)\n  | tnil => constr:(tnil)\n  | @Vector.nil ?a => constr:(@Vector.nil a)\n  | cblackbox ?A' => A\n  | tblackbox ?A' => A\n  | cons ?x ?A' => let x' := f x in let A'' := map_ltac A' f in constr:(cons x' A'')\n  | ccons ?s ?x ?A' => let x' := f x in let A'' := map_ltac A' f in constr:(ccons s x' A'')\n  | tcons ?s ?x ?A' => let x' := f x in let A'' := map_ltac A' f in constr:(tcons s x' A'')\n  | @Vector.cons _ ?x _ ?A' => let x' := f x in let A'' := map_ltac A' f in constr:(@Vector.cons _ x' _ A'')\n  end.\n\n(* Finds the first name of form `base`, `base0`, `base1`, ... thats not \n * contained in the context/variable list `C`. *)\nLtac new_name' n base C :=\n  let name := match n with \n    | 0 => base\n    | S ?n' => let s := eval cbn in (nat_to_string n') in eval cbn in (base ++ s)\n  end in\n  match lookup C name with\n  | @None => name\n  | @Some _ _ => new_name' (S n) base C\n  end.\nLtac new_name base C := new_name' 0 base C.\n\n(* For context creation we need to give names to the initial formulas.\n * This is done using syntactic matching with ltac instead of a Galina\n * function, because if we want to prove `A ⊢ φ` for an unknown A we \n * don't want to go into the `A`. *)\nLtac create_context' A :=\n  match A with\n  | ?phi::?A' =>\n    let x := create_context' A' in match x with (?c, ?n) =>\n      match n with\n        | 0 => constr:((ccons \"H\" phi c, S n))\n        | S ?n' => let s' := eval cbn in (\"H\" ++ nat_to_string n') in constr:((ccons s' phi c, S n))\n      end\n    end\n  | extend ?T' ?phi =>\n    let x := create_context' T' in match x with (?c, ?n) =>\n      match n with\n        | 0 => constr:((tcons \"H\" phi c, S n))\n        | S ?n' => let s' := eval cbn in (\"H\" ++ nat_to_string n') in constr:((tcons s' phi c, S n))\n      end\n    end\n  | nil => constr:((cnil, 0))\n  | _ => \n    (* If it's not a cons or nil, it's a variable/function call/... \n     * and we don't want to look into it *)\n    match type of A with\n    | list form => constr:((cblackbox A, 0))\n    | theory => constr:((tblackbox A, 0))\n    | form -> Prop => constr:((tblackbox A, 0))\n    end\n  end.\nLtac create_context A := let x := create_context' A in match x with (?c, _) => c end.\n\n\n\n\n(** Variable names utilities: *)\n\nDefinition named_quant {fsig psig ops} op (x : string) phi := @quant fsig psig ops op phi.\nDefinition named_var {fsig} n (x : string) := @var fsig n.\nArguments named_var {_ _} _.\n\nLtac annotate_term f t :=\n  match t with\n  | var ?n =>\n      let name := eval cbn in (f n) in\n      constr:(@named_var _ n name)\n  | func ?fu ?v =>\n      let map_fun := annotate_term f in\n      let v' := map_ltac v map_fun in\n      constr:(func fu v')\n  | _ => t\n  end.\n\nLtac annotate_form' f idx phi :=\n  match phi with\n  | fal => fal\n  | atom ?P ?v =>\n      let map_fun := annotate_term f in\n      let v' := map_ltac v map_fun in\n      constr:(atom P v')\n  | bin ?op ?psi1 ?psi2 => \n      let psi1' := annotate_form' f idx psi1 in\n      let psi2' := annotate_form' f idx psi2 in\n      constr:(bin op psi1' psi2')\n  | quant ?op ?psi =>\n      let name := eval cbn in (\"x\" ++ nat_to_string idx) in\n      let f' := constr:(fun n => match n with 0 => name | S n' => f n' end) in\n      let psi' := annotate_form' f' (S idx) psi in\n      constr:(named_quant op name psi')\n  | _ => phi\n  end.\n\nLtac add_binder_names :=\n  match goal with \n  | [ |- @pm _ _ ?p ?C ?phi ] =>\n    let f := constr:(fun (n : nat) => \"ERROR\") in\n    let annotate_form := annotate_form' f 0 in\n    let phi' := annotate_form phi in\n    let C' := map_ltac C annotate_form in\n    change (@pm _ _ p C' phi')\n  | [ |- @tpm _ _ ?p ?C ?phi ] =>\n    let f := constr:(fun (n : nat) => \"ERROR\") in\n    let annotate_form := annotate_form' f 0 in\n    let phi' := annotate_form phi in\n    let C' := map_ltac C annotate_form in\n    change (@tpm _ _ p C' phi')\n  end.\nLtac update_binder_names := unfold named_quant; unfold named_var; add_binder_names.\n\n\n\n\n(** Proof Mode: *)\n\nNotation \"\" := cnil (only printing).\nNotation \"A\" := (cblackbox A) (at level 1, only printing, format \" A\").\nNotation \"C name : phi\" := (ccons name phi C)\n  (at level 1, C at level 200, phi at level 200,\n  left associativity, format \"C '//'  name  :  '[' phi ']'\", only printing).\n\nNotation \"\" := tnil (only printing).\nNotation \"A\" := (tblackbox A) (at level 1, only printing, format \" A\").\nNotation \"C name : phi\" := (tcons name phi C)\n  (at level 1, C at level 200, phi at level 200,\n  left associativity, format \"C '//'  name  :  '[' phi ']'\", only printing).\n\nNotation \"∀ x .. y , phi\" := (named_quant All x ( .. (named_quant All y phi) .. )) (at level 50, only printing,\n  format \"'[' '∀'  '/  ' x  ..  y ,  '/  ' phi ']'\").\nNotation \"∃ x .. y , phi\" := (named_quant Ex x ( .. (named_quant Ex y phi) .. )) (at level 50, only printing,\n  format \"'[' '∃'  '/  ' x  ..  y ,  '/  ' phi ']'\").\n\nNotation \"x\" := (named_var x) (at level 1, only printing).\n\nNotation \"C '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━' phi\" :=\n  (pm C phi)\n  (at level 1, left associativity,\n  format \" C '//' '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━' '//'  phi\", only printing).\n\nNotation \"T '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━' phi\" :=\n  (tpm T phi)\n  (at level 1, left associativity,\n  format \" T '//' '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━' '//'  phi\", only printing).\n\n\n(* Tactics to toggle proof mode *)\nLtac fstart := \n  match goal with \n  | [ |- @prv _ _ ?p ?A ?phi ] => let C := create_context A in change (@pm _ _ p C phi)\n  | [ |- @tprv _ _ ?p ?T ?phi ] => let C := create_context T in change (@tpm _ _ p C phi)\n  end;\n  add_binder_names.\nLtac fstop := \n  match goal with \n  | [ |- @pm _ _ ?p ?C ?phi ] => change (@prv _ _ p C phi)\n  | [ |- @tpm _ _ ?p ?C ?phi ] => change (@tprv _ _ p C phi)\n  end;\n  unfold pm in *; unfold cnil; unfold ccons;unfold cblackbox; \n  unfold tpm in *; unfold tnil; unfold tcons;unfold tblackbox; \n  unfold named_quant; unfold named_var.\n\n\n\n\n(** Compatability tactics: *)\n\n(* All the tactics defined below work with the original `prv` type.\n * The following tactic lifts them to be compatible with `pm`.\n *\n * Every tactic must have an additional argument where the current\n * context is filled in if the proof mode is active, and `cnil` \n * otherwise. *)\nLtac make_compatible tac :=\n  match goal with\n  | [ |- prv ?A _ ] => tac A\n  | [ |- tprv ?T _ ] => tac T\n  | [ |- @pm _ _ ?p ?C _ ] => \n      fstop; \n      tac C;\n      match goal with \n      | [ |- pm _ _ ?G ] => change (@pm _ _ p C G) \n      | [ |- prv _ ?G ] => change (@pm _ _ p C G)\n      | _ => idtac \n      end;\n      try update_binder_names (* [try] because some tactics add normal Coq goals *)\n  | [ |- @tpm _ _ ?p ?C _ ] => \n      fstop;\n      tac C;\n      match goal with \n      | [ |- tprv _ ?G ] => change (@tpm _ _ p C G)\n      | _ => idtac \n      end;\n      try update_binder_names (* [try] because some tactics add normal Coq goals *)\n  end.\n\n\n(* [assert] and [enough] that are compatible with all proof modes.\n * This way we can avoid matching on the goal each time. *)\nLtac assert_compat' phi H :=\n  match goal with\n  | [ |- ?C ⊢ _ ] => assert (@prv _ _ _ C phi) as H\n  | [ |- ?C ⊩ _ ] => assert (@tprv _ _ _ C phi) as H\n  | [ |- @pm _ _ _ ?C _ ] => assert (@pm _ _ _ C phi) as H\n  | [ |- @tpm _ _ _ ?C _ ] => assert (@tpm _ _ _ C phi) as H\n  end.\nTactic Notation \"assert_compat\" constr(phi) := let H := fresh in assert_compat' phi H.\nTactic Notation \"assert_compat\" constr(phi) \"as\" ident(H) := assert_compat' phi H.\nTactic Notation \"assert_compat\" constr(phi) \"by\" tactic(tac) := let H := fresh in assert_compat' phi H; [tac|].\nTactic Notation \"assert_compat\" constr(phi) \"as\" ident(H) \"by\" tactic(tac) := assert_compat' phi H; [tac|].\n\nLtac enough_compat' phi H :=\n  match goal with\n  | [ |- ?C ⊢ _ ] => enough (@prv _ _ _ C phi) as H\n  | [ |- ?C ⊩ _ ] => enough (@tprv _ _ _ C phi) as H\n  | [ |- @pm _ _ _ ?C _ ] => enough (@pm _ _ _ C phi) as H\n  | [ |- @tpm _ _ _ ?C _ ] => enough (@tpm _ _ _ C phi) as H\n  end.\nTactic Notation \"enough_compat\" constr(phi) := let H := fresh in enough_compat' phi H.\nTactic Notation \"enough_compat\" constr(phi) \"as\" ident(H) := enough_compat' phi H.\nTactic Notation \"enough_compat\" constr(phi) \"by\" tactic(tac) := let H := fresh in enough_compat' phi H; [tac|].\nTactic Notation \"enough_compat\" constr(phi) \"as\" ident(H) \"by\" tactic(tac) := enough_compat' phi H; [tac|].\n\nLtac apply_compat' H1 H2 :=\n  match goal with\n  | [ |- _ ⊢ _ ] => apply H1\n  | [ |- _ ⊩ _ ] => apply H2\n  end.\nLtac apply_compat_in H1 H2 H :=\n  match goal with\n  | [ |- _ ⊢ _ ] => apply H1 in H\n  | [ |- _ ⊩ _ ] => apply H2 in H\n  end.\nTactic Notation \"apply_compat\" constr(H1) constr(H2) := apply_compat' H1 H2.\nTactic Notation \"apply_compat\" constr(H1) constr(H2) \"in\" hyp(H) := apply_compat_in H1 H2 H.\n\n\n(* Return the context of the goal or a hypothesis *)\nLtac get_context_goal :=\n  match goal with\n  | [ |- ?C ⊢ _ ] => C\n  | [ |- ?C ⊩ _ ] => C\n  | [ |- pm ?C _ ] => C\n  | [ |- tpm ?C _ ] => C\n  end.\nLtac get_context_hyp H :=\n  match type of H with\n  | ?C ⊢ _ => C\n  | ?C ⊩ _ => C\n  | pm ?C _ => C\n  | tpm ?C _ => C\n  end.\nTactic Notation \"get_context\" := get_context_goal.\nTactic Notation \"get_context\" hyp(H) := get_context_hyp H.\n\n(* Return the formula inside the goal or a hypothesis *)\nLtac get_form_goal :=\n  match goal with\n  | [ |- _ ⊢ ?phi ] => phi\n  | [ |- _ ⊩ ?phi ] => phi\n  | [ |- pm _ ?phi ] => phi\n  | [ |- tpm _ ?phi ] => phi\n  end.\nLtac get_form_hyp H :=\n  match type of H with\n  | _ ⊢ ?phi => phi\n  | _ ⊩ ?phi => phi\n  | pm _ ?phi => phi\n  | tpm _ ?phi => phi\n  end.\nTactic Notation \"get_form\" := get_form_goal.\nTactic Notation \"get_form\" hyp(H) := get_form_hyp H.\n\n\n\n\n(** Simplification: *)\n\n(* Spimplify terms that occur during specialization *)\nLtac simpl_subst_hyp H :=\n  cbn in H;\n  repeat match type of H with\n  | context C[S >> var] => let H' := context C[↑] in change H' in H\n  end;\n  try rewrite !up_term in H;\n  try rewrite !subst_term_shift in H;\n  try rewrite !up_form in H;\n  try rewrite !subst_shift in H;\n  (* Turn `(S >> var) 4` into `$5` *)\n  unfold \">>\";\n  (* Domain specific simplifications: *)\n  custom_fold;\n  custom_simpl.\n\nLtac simpl_subst_goal :=\n  cbn;\n  repeat match goal with\n  | [ |- context C[S >> var] ] => let G := context C[↑] in change G\n  end;\n  try rewrite !up_term;\n  try rewrite !subst_term_shift;\n  try rewrite !up_form;\n  try rewrite !subst_shift;\n  (* Turn `(S >> var) 4` into `$5` *)\n  unfold \">>\";\n  (* Domain specific simplifications: *)\n  custom_fold;\n  custom_simpl.\n\nTactic Notation \"simpl_subst\" hyp(H) := (simpl_subst_hyp H).\nTactic Notation \"simpl_subst\" := (simpl_subst_goal).\n\n\n(* Syntactically evaluate `mapT f (T ⋄ a ⋄ b ⋄ c)` to\n * `(mapT f T) ⋄ f a ⋄ f b ⋄ f c` like it would happen using\n * [cbn] for map in normal lists. *)\nLtac eval_mapT M :=\n  match M with\n  | mapT ?f (extend ?T ?a) => let T' := eval_mapT (mapT f T) in constr:(extend T' (f a))\n  | mapT ?f (tcons ?s ?a ?T) => let T' := eval_mapT (mapT f T) in constr:(tcons s (f a) T')\n  | mapT ?f (tblackbox ?T) => constr:(tblackbox (mapT f T))\n  | _ => M\n  end.\n\nLemma mapT_step `{s1 : funcs_signature, s2 : preds_signature, p : peirce} f a T1 T2 :\n  subset_T T1 (mapT f T2) -> subset_T (extend T1 (f a)) (mapT f (extend T2 a)).\nProof.\n  intros H psi H1. destruct H1 as [H1|H1].\n  - destruct (H psi H1) as [rho [H2 H3]]. exists rho. split. now left. assumption.\n  - exists a. split. now right. auto.\nQed.\n\n(* Replace `mapT f (T ⋄ a ⋄ b ⋄ c)` in the context with \n * `(mapT f T) ⋄ f a ⋄ f b ⋄ f c`. *)\nLtac simpl_context_mapT :=\n  match goal with \n  | [ |- tprv ?T ?phi ] =>\n      let T' := eval_mapT T in\n      let X := fresh in\n      enough (tprv T' phi) as X; [ \n        eapply Weak; [now apply X | repeat apply mapT_step; apply subset_refl ]\n      |]\n  | [ |- tpm ?T ?phi ] =>\n      let T' := eval_mapT T in\n      let X := fresh in\n      enough (tpm T' phi) as X; [ \n        eapply Weak; [now apply X | repeat apply mapT_step; apply subset_refl ]\n      |]\n  end.\n\n\n\n\n\n\n\n\n\n(** End user proof tactics: *)\n\nLtac ctx := make_compatible ltac:(fun _ => apply Ctx; firstorder).\n\nLtac fexfalso := make_compatible ltac:(fun _ => apply Exp).\nLtac fsplit := make_compatible ltac:(fun _ => apply CI).\nLtac fleft := make_compatible ltac:(fun _ => apply DI1).\nLtac fright := make_compatible ltac:(fun _ => apply DI2).\n\n\n\n\n(* \n * [fintro], [fintros] \n * \n * Similar to Coq. Identifiers need to be given as strings (e.g. \n * [fintros \"H1\" \"H2\"]). With \"?\" you can automatically generate\n * a name (e.g. [fintros \"?\" \"H\"]).\n * \n * Now also handles intro patterns! For now unneccessary spaces\n * are not alowed in intro patterns. E.g. instead of \"[H1 | H2]\",\n * write \"[H1|H2]\".\n *)\n\n\n(* Intro pattern parsing. This gets its own section to avoid \n * importing Ascii globally. *)\nSection IntroPattern.\n  Import Ascii.\n\n  Inductive intro_pattern :=\n    | patId : string -> intro_pattern\n    | patAnd : intro_pattern -> intro_pattern -> intro_pattern\n    | patOr : intro_pattern -> intro_pattern -> intro_pattern.\n\n  Fixpoint read_name s := match s with\n  | String \"]\" s' => (\"\", String \"]\" s')\n  | String \" \" s' => (\"\", String \" \" s')\n  | String \"|\" s' => (\"\", String \"|\" s')\n  | String c s' => let (a, s'') := read_name s' in (String c a, s'')\n  | EmptyString => (\"\", EmptyString)\n  end.\n\n  Fixpoint parse_intro_pattern' s fuel := match fuel with\n  | 0 => (None, s)\n  | S fuel' =>\n    match s with\n    | String (\"[\") s' => \n        match parse_intro_pattern' s' fuel' with\n        | (Some p1, String \"|\" s'') => match parse_intro_pattern' s'' fuel' with\n                                      | (Some p2, String \"]\" s''') => (Some (patOr p1 p2), s''')\n                                      | _ => (None, \"\")\n                                      end\n        | (Some p1, String \" \" s'') => match parse_intro_pattern' s'' fuel' with\n                                      | (Some p2, String \"]\" s''') => (Some (patAnd p1 p2), s''')\n                                      | _ => (None, \"\")\n                                      end\n        | _ => (None, \"\")\n        end\n      | String (\"]\") s' => (Some (patId \"?\"), String \"]\" s')\n      | String \" \" s' => (Some (patId \"?\"), String \" \" s')\n      | String \"|\" s' => (Some (patId \"?\"), String \"|\" s')\n      | EmptyString => (None, EmptyString)\n      | s => let (a, s') := read_name s in (Some (patId a), s')\n    end\n  end.\n  Definition parse_intro_pattern s := fst (parse_intro_pattern' s 100).\n\nEnd IntroPattern.\n\nSection Fintro.\n  Context {Σ_funcs : funcs_signature}.  \n  Context {Σ_preds : preds_signature}.\n  Variable p : peirce.\n\n  (* Lemmas for alternative ∀-intro and ∃-application.\n   * Taken from https://www.ps.uni-saarland.de/extras/fol-completeness/html/Undecidability.FOLC.FullND.html#nameless_equiv_all' *)\n  Lemma nameless_equiv_all' A phi :\n    exists t, A ⊢ phi[t..] <-> (map (subst_form ↑) A) ⊢ phi.\n  Admitted.\n\n  Lemma nameless_equiv_ex A phi psi :\n    exists t, (psi[t..]::A) ⊢ phi <-> (psi::map (subst_form ↑) A) ⊢ phi[↑].\n  Admitted.\n\n  Lemma intro_and_destruct A s t G :\n    A ⊢ (s --> t --> G) -> A ⊢ (s ∧ t --> G).\n  Proof.\n    intros. now apply switch_conj_imp.\n  Qed.\n\n  Lemma intro_or_destruct A s t G :\n    A ⊢ (s --> G) -> A ⊢ (t --> G) -> A ⊢ (s ∨ t --> G).\n  Proof.\n    intros Hs Ht. apply II. eapply DE. ctx.\n    eapply Weak in Hs. eapply IE. apply Hs. ctx. firstorder.\n    eapply Weak in Ht. eapply IE. apply Ht. ctx. firstorder.\n  Qed.\n\n  Context {eq_dec_Funcs : EqDec syms}.\n  Context {eq_dec_Preds : EqDec preds}.\n\n  Lemma intro_and_destruct_T T s t G :\n    T ⊩ (s --> t --> G) -> T ⊩ (s ∧ t --> G).\n  Proof.\n    intros. apply II. apply (IE _ t). apply (IE _ s).\n    eapply Weak. apply H. firstorder.\n    eapply CE1, Ctx; firstorder.\n    eapply CE2, Ctx; firstorder.\n  Qed.\n\n  Lemma intro_or_destruct_T T s t G :\n    T ⊩ (s --> G) -> T ⊩ (t --> G) -> T ⊩ (s ∨ t --> G).\n  Proof.\n    intros Hs Ht. apply II. eapply DE. ctx.\n    eapply Weak in Hs. eapply IE. apply Hs. ctx. firstorder.\n    eapply Weak in Ht. eapply IE. apply Ht. ctx. firstorder.\n  Qed.\n\n  Lemma subst_zero phi x :\n    $0 = x -> phi = phi[fun n => match n with 0 => x | S n => $(S n) end].\n  Proof.\n    intros. symmetry. apply subst_id. intros [|]; cbn. now rewrite H. reflexivity.\n  Qed.\n\n  Lemma subst_zero_term t x :\n    $0 = x -> t`[fun n => match n with 0 => x | S n => $(S n) end] = t.\n  Proof.\n    intros. apply subst_term_id. intros [|]; cbn. now rewrite H. reflexivity.\n  Qed.\n\nEnd Fintro.\n\n\n(* Check if the name `id` doesn't already occur in the context or\n * create a new name if `id = \"?\"`. *)\nLtac hypname_from_pattern C id :=\n  match id with \n  | \"?\" => new_name \"H\" C\n  | _ => match lookup C id with\n    | @None => id\n    | @Some _ _ => let msg := eval cbn in (\"Identifier already used: \" ++ id) in fail 7 msg\n    end\n  end.\n\n(* For variable names that are introduced with ∀ this gets infinitely\n * more difficult.\n * Ltac doesn't have an easy way to convert a Coq string into an identifier.\n * I found this snippet using Ltac2 that is used in the Iris proof\n * mode, but doesn't seem that stable. \n * See https://github.com/coq/coq/issues/7412 \n *\n * Nonetheless I am going to use it, but split up the intro tactic into\n * ident and hyp intro. I use tactic notation at the end to also support\n * intro with a 'real' Coq ident instead of a string. This should keep\n * working if this hack breaks down. *)\nRequire Import Ltac2StringIdent.\nLtac varname_from_pat pat :=\n  match pat with \n  | patId \"?\" => fresh \"x\"\n  | patId ?id => string_to_ident id\n  end.\n\n\nLtac fintro_ident x :=\n  let H := fresh \"H\" in\n  match goal with\n  | [ |- _ ⊢ ∀ ?t ] => \n    apply AllI;\n    edestruct nameless_equiv_all' as [x H];\n    apply H; clear H;\n    simpl_subst\n  | [ |- @pm _ _ ?p ?C (named_quant All _ ?t) ] =>\n    apply AllI;\n    edestruct nameless_equiv_all' as [x H];\n    apply H; clear H;\n    simpl_subst;\n    match goal with [ |- prv _ ?t'] => change (@pm _ _ p C t') end;\n    update_binder_names\n  | [ |- _ ⊩ ∀ ?t ] =>\n    let E := fresh \"E\" in\n    apply AllI;\n    assert (exists x, $0 = x) as [x E] by (now exists ($0));\n    rewrite (subst_zero t x E);\n    simpl_context_mapT;\n    simpl_subst;\n    repeat (try rewrite subst_zero_term; [| apply E]);\n    clear E\n  | [ |- @tpm _ _ ?p ?C (named_quant All _ ?t) ] =>\n    let E := fresh \"E\" in\n    apply AllI;\n    assert (exists x, $0 = x) as [x E] by (now exists ($0));\n    rewrite (subst_zero t x E);\n    simpl_context_mapT;\n    simpl_subst;\n    repeat (try rewrite subst_zero_term; [| apply E]);\n    clear E;\n    update_binder_names\n  | _ =>\n    (* Unfold definitions to check if there are hidden ∀ underneath. \n     * Also perform simplification and fix names if the definition\n     * does something nasty. *)\n    progress custom_unfold; simpl_subst; try update_binder_names;\n    custom_unfold; (* Unfold again because [simpl_subst] folds *)\n    fintro_ident x;\n    custom_fold\n  end.\n\n\nLtac fintro_pat' pat :=\n  match pat with\n  | patAnd ?p1 ?p2 => (* Existential *)\n      make_compatible ltac:(fun C =>\n        apply II; eapply ExE; [ apply Ctx; now left |\n          let x := varname_from_pat p1 in\n          let H := fresh \"H\" in\n          edestruct nameless_equiv_ex as [x H];\n          apply H; clear H; cbn; simpl_subst; apply -> switch_imp;\n          apply (Weak C); [| firstorder] ]\n      ); \n      fintro_pat' p2\n  | patAnd ?p1 ?p2 => (* Conjunction *)\n      make_compatible ltac:(fun _ => \n        match goal with \n        | [ |- prv _ _ ] => apply intro_and_destruct\n        | [ |- tprv _ _ ] => apply intro_and_destruct_T\n        end\n      ); \n      fintro_pat' p1; fintro_pat' p2  \n  | patOr ?p1 ?p2 =>\n      make_compatible ltac:(fun _ => \n        match goal with \n        | [ |- prv _ _ ] => apply intro_or_destruct\n        | [ |- tprv _ _ ] => apply intro_or_destruct_T\n        end\n      );\n      [fintro_pat' p1 | fintro_pat' p2]\n  | patId ?id =>\n      match goal with \n      | [ |- ?A ⊢ ∀ ?t ] => let x := varname_from_pat pat in fintro_ident x\n      | [ |- ?A ⊩ ∀ ?t ] => let x := varname_from_pat pat in fintro_ident x\n      | [ |- ?A ⊢ (?s --> ?t) ] => apply II\n      | [ |- ?A ⊩ (?s --> ?t) ] => apply II\n      (* Special care for intro in proof mode *)\n      | [ |- @pm _ _ ?p ?C (named_quant All _ ?t) ] => let x := varname_from_pat pat in fintro_ident x\n      | [ |- @tpm _ _ ?p ?C (named_quant All _ ?t) ] => let x := varname_from_pat pat in fintro_ident x\n      | [ |- @pm _ _ ?p ?C (?s --> ?t) ] => apply II; let name := hypname_from_pattern C id in change (@pm _ _ p (ccons name s C) t)\n      | [ |- @tpm _ _ ?p ?C (?s --> ?t) ] => apply II; let name := hypname_from_pattern C id in change (@tpm _ _ p (tcons name s C) t)\n      | _ =>\n        (* Unfold definitions to check if there are hidden ∀ underneath. \n         * Also perform simplification and fix names if the definition\n         * does something nasty. *)\n        progress custom_unfold; simpl_subst; try update_binder_names;\n        custom_unfold; (* Unfold again because [simpl_subst] folds *)\n        fintro_pat' pat;\n        custom_fold\n      end\n  end.\n\nLtac fintro_pat intro_pat := \n  match eval cbn in (parse_intro_pattern intro_pat) with\n  | Some ?p => fintro_pat' p\n  | None => let msg := eval cbn in (\"Invalid intro pattern: \" ++ intro_pat) in fail 2 msg\n  end.\n\nTactic Notation \"fintro\" := fintro_pat constr:(\"?\").\nTactic Notation \"fintro\" constr(H) := fintro_pat H.\nTactic Notation \"fintro\" ident(x) := fintro_ident x.\n\nTactic Notation \"fintros\" := repeat fintro.\n\nTactic Notation \"fintros\" constr(H1) := fintro_pat H1.\nTactic Notation \"fintros\" ident(H1) := fintro_ident H1.\n\nTactic Notation \"fintros\" constr(H1) constr(H2) := fintro_pat H1; fintro_pat H2.\nTactic Notation \"fintros\" ident(H1) constr(H2) := fintro_ident H1; fintro_pat H2.\nTactic Notation \"fintros\" constr(H1) ident(H2) := fintro_pat H1; fintro_ident H2.\nTactic Notation \"fintros\" ident(H1) ident(H2) := fintro_ident H1; fintro_ident H2.\n\nTactic Notation \"fintros\" constr(H1) constr(H2) constr(H3) := fintro_pat H1; fintro_pat H2; fintro_pat H3.\nTactic Notation \"fintros\" ident(H1) constr(H2) constr(H3) := fintro_ident H1; fintro_pat H2; fintro_pat H3.\nTactic Notation \"fintros\" constr(H1) ident(H2) constr(H3) := fintro_pat H1; fintro_ident H2; fintro_pat H3.\nTactic Notation \"fintros\" constr(H1) constr(H2) ident(H3) := fintro_pat H1; fintro_pat H2; fintro_ident H3.\nTactic Notation \"fintros\" ident(H1) ident(H2) constr(H3) := fintro_ident H1; fintro_ident H2; fintro_pat H3.\nTactic Notation \"fintros\" constr(H1) ident(H2) ident(H3) := fintro_pat H1; fintro_ident H2; fintro_ident H3.\nTactic Notation \"fintros\" ident(H1) ident(H2) ident(H3) := fintro_ident H1; fintro_ident H2; fintro_ident H3.\n\nTactic Notation \"fintros\" constr(H1) constr(H2) constr(H3) constr(H4) := fintro_pat H1; fintro_pat H2; fintro_pat H3; fintro_pat H4.\nTactic Notation \"fintros\" constr(H1) constr(H2) constr(H3) constr(H4) constr(H5) := fintro_pat H1; fintro_pat H2; fintro_pat H3; fintro_pat H4; fintro_pat H4.\n\n\n\n\n(* High level context managment *)\n\n(* Tactic Notation \"is_hyp\" hyp(H) := idtac. *)\nLtac is_hyp H := match type of H with ?t => match type of t with Prop => idtac end end.\n\n(* Check wether T is a hypothesis, a context index, a context formula\n * or a context name and put it into hypothesis H. *)\n Ltac turn_into_hypothesis T H contxt := \n  tryif is_hyp T\n  then assert (H := T)  (* Hypothesis *)\n  else match goal with \n  | [ |- @prv _ _ ?p ?C _ ] => \n      match type of T with\n      | form => assert (@prv _ _ p C T) as H by ctx  (* Explicit form *)\n      | nat => let T' := nth C T in assert (@prv _ _ p C T') as H by ctx  (* Idx in context *)\n      | string => match lookup contxt T with  (* Context name *)\n        | @None => let msg := eval cbn in (\"Unknown identifier: \" ++ T) in fail 4 msg\n        | @Some _ ?n => let T' := nth C n in assert (@prv _ _ p C T') as H by ctx\n        end\n      end\n  | [ |- @tprv _ _ ?p ?C _ ] => \n      match type of T with\n      | form => assert (@tprv _ _ p C T) as H by ctx  (* Explicit form *)\n      | nat => let T' := nth C T in assert (@tprv _ _ p C T') as H by ctx  (* Idx in context *)\n      | string => match lookup contxt T with  (* Context name *)\n        | @None => let msg := eval cbn in (\"Unknown identifier: \" ++ T) in fail 4 msg\n        | @Some _ ?n => let T' := nth C n in assert (@tprv _ _ p C T') as H by ctx\n        end\n      end\n  end.\n\n(* Replace the context entry T_old with formula `phi` in \n * `H_new : X ⊢ phi` *)\nLtac replace_context T_old H_new :=\n  let C := get_context_goal in\n  let phi := get_form_hyp H_new in\n  let psi := get_form_goal in\n  let X := fresh in\n  (enough_compat (phi --> psi) as X by eapply (IE _ _ _ X); apply H_new);\n  let C' := match type of T_old with\n    | nat => replace_ltac C T_old phi\n    | form => map_ltac C ltac:(fun f => match f with T_old => phi | ?psi => psi end)\n    | string => match lookup C T_old with\n      | @None => let msg := eval cbn in (\"Unknown identifier: \" ++ T_old) in fail 4 msg\n      | @Some _ ?n => replace_ltac C n phi\n      end\n  end in\n  fintro; apply (Weak C'); [| firstorder].\n\n\n\n\n\n(* \n * [fspecialize (H x1 x2 ... xn)], [fspecialize H with x1 x2 ... xn] \n * \n * Specializes a Coq hypothesis `H` of the form `X ⊢ ∀∀...∀ p1 --> ... --> pn --> g`\n * with `x1, x2, ..., xn`.\n *)\n\nLtac fspecialize_list H A := \n  match A with\n  | [] => simpl_subst H\n  | ?x::?A' =>\n      tryif apply (fun H => IE _ _ _ H x) in H\n      then idtac\n      else (\n        (* For some reason we cannot directly [apply (AllE _ x)]\n           if x contains ⊕, σ, etc. But evar seems to work. *)\n        let x' := fresh \"x\" in \n        eapply (AllE _ ?[x']) in H; \n        instantiate (x' := x) );\n    fspecialize_list H A'\n  end.\n\nTactic Notation \"fspecialize\" \"(\" hyp(H) constr(x1) \")\" := make_compatible ltac:(fun _ => fspecialize_list H constr:([x1])).\nTactic Notation \"fspecialize\" \"(\" hyp(H) constr(x1) constr(x2) \")\" := make_compatible ltac:(fun _ => fspecialize_list H constr:([x1; x2])).\nTactic Notation \"fspecialize\" \"(\" hyp(H) constr(x1) constr(x2) constr(x3) \")\" := make_compatible ltac:(fun _ => fspecialize_list H constr:([x1;x2;x3])).\n\nTactic Notation \"fspecialize\" hyp(H) \"with\" constr(x1) := make_compatible ltac:(fun _ => fspecialize_list H constr:([x1])).\nTactic Notation \"fspecialize\" hyp(H) \"with\" constr(x1) constr(x2) := make_compatible ltac:(fun _ => fspecialize_list H constr:([x1;x2])).\nTactic Notation \"fspecialize\" hyp(H) \"with\" constr(x1) constr(x2) constr(x3) := make_compatible ltac:(fun _ => fspecialize_list H constr:([x1;x2;x3])).\n\n(* Specialize in context *)\nLtac fspecialize_context T A :=\n  let H := fresh \"H\" in\n  make_compatible ltac:(fun C => turn_into_hypothesis \"IH\" H C);\n  fspecialize_list H A;\n  replace_context T H;\n  clear H.\n\nTactic Notation \"fspecialize\" \"(\" constr(H) constr(x1) \")\" := fspecialize_context H constr:([x1]).\nTactic Notation \"fspecialize\" \"(\" constr(H) constr(x1) constr(x2) \")\" := make_compatible ltac:(fspecialize_context H constr:([x1; x2])).\nTactic Notation \"fspecialize\" \"(\" constr(H) constr(x1) constr(x2) constr(x3) \")\" := make_compatible ltac:(fspecialize_context H constr:([x1;x2;x3])).\n\nTactic Notation \"fspecialize\" constr(H) \"with\" constr(x1) := make_compatible ltac:(fspecialize_context H constr:([x1])).\nTactic Notation \"fspecialize\" constr(H) \"with\" constr(x1) constr(x2) := make_compatible ltac:(fspecialize_context H constr:([x1;x2])).\nTactic Notation \"fspecialize\" constr(H) \"with\" constr(x1) constr(x2) constr(x3) := make_compatible ltac:(fspecialize_context H constr:([x1;x2;x3])).\n\n\n\n\n(*\n * [fapply (H x1 ... xn)], [feapply (H x1 ... xn)]\n *  \n * Works on\n * - Coq hypothesis by name\n * - Formula in in ND context by index (e.g. [fapply 3])\n * - Explicit formula type in the context (e.g. [fapply ax_symm])\n * - Name of a context assumption in proof mode (e.g. [fapply \"H2\"])\n *)\n\nSection Fapply.\n  Context {Σ_funcs : funcs_signature}.  \n  Context {Σ_preds : preds_signature}.\n  Variable p : peirce.\n\n  Lemma fapply_equiv_l A phi psi :\n    A ⊢ (phi <--> psi) -> A ⊢ phi -> A ⊢ psi.\n  Proof.\n    intros. apply (IE _ phi). eapply CE1. apply H. apply H0.\n  Qed.\n\n  Lemma fapply_equiv_r A phi psi :\n    A ⊢ (phi <--> psi) -> A ⊢ psi -> A ⊢ phi.\n  Proof.\n    intros. apply (IE _ psi). eapply CE2. apply H. apply H0.\n  Qed.\n\n  Context {eq_dec_Funcs : EqDec syms}.\n  Context {eq_dec_Preds : EqDec preds}.\n\n  Lemma fapply_equiv_l_T A phi psi :\n    A ⊩ (phi <--> psi) -> A ⊩ phi -> A ⊩ psi.\n  Proof.\n    intros. apply (IE _ phi). eapply CE1. apply H. apply H0.\n  Qed.\n\n  Lemma fapply_equiv_r_T A phi psi :\n    A ⊩ (phi <--> psi) -> A ⊩ psi -> A ⊩ phi.\n  Proof.\n    intros. apply (IE _ psi). eapply CE2. apply H. apply H0.\n  Qed.\nEnd Fapply.\n\n(* Helper tactics: *)\n\n(* [fapply_without_quant] takes a formula `H : X ⊢ p1 --> p2 --> ... --> pn --> g`\n * without leading quantifiers. It solves the goal `X ⊢ g` by \n * adding subgoals for each premise `p1, p2, ..., pn`.\n *\n * Also supports formulas of Type `H : X ⊢ ... --> (pn <--> g)` or \n * `H : X ⊢ ... --> (g <--> pn)`.\n *\n * If ∀-quantifiers occur inbetween, they are instantiated with evars. *)\nLtac fapply_without_quant H :=\n  tryif exact H then idtac else\n  let Hs := fresh \"Hs\" in \n  let Ht := fresh \"Ht\" in \n  match get_form_hyp H with\n  | ?s --> ?t => \n    match goal with \n    | [ |- @prv _ _ ?p ?A _ ] =>\n        enough (@prv _ _ p A s) as Hs; \n        [ assert (@prv _ _ p A t) as Ht; \n          [ apply (IE _ _ _ H Hs) | fapply_without_quant Ht; clear Hs; clear Ht ] \n        | ]\n    | [ |- @tprv _ _ ?p ?A _ ] =>\n        enough (@tprv _ _ p A s) as Hs; \n        [ assert (@tprv _ _ p A t) as Ht; \n          [ apply (IE _ _ _ H Hs) | fapply_without_quant Ht; clear Hs; clear Ht ] \n        | ]\n    end\n  \n  (* Handle application of equivalence. It would be nice to use match\n   * to check which side matches, but it doesn't work because of evars.\n   * Therefore simply try both options. *)\n  | _ <--> _ =>\n    match goal with\n    | [ |- _ ⊢ _] => tryif apply (fapply_equiv_l _ _ _ _ H) then idtac else apply (fapply_equiv_r _ _ _ _ H)\n    | [ |- _ ⊩ _] => tryif apply (fapply_equiv_l_T _ _ _ _ H) then idtac else apply (fapply_equiv_r_T _ _ _ _ H)\n    end\n  \n  (* Quantifiers are instantiated with evars *)\n  | ∀ _ => eapply AllE in H; simpl_subst H; fapply_without_quant H\n\n  (* If we don't find something useful, try unfolding definitions to \n   * check if there is something hidden underneath. Also perform \n   * simplification if the definition does something nasty. *)\n  | _ =>\n    progress custom_unfold; simpl_subst H;\n    custom_unfold; (* Unfold again because [simpl_subst] folds *)\n    fapply_without_quant H;\n    custom_fold\n  end.\n\nLtac instantiate_evars H := repeat eassert (H := H _); repeat eapply AllE in H.\n\n(* If `H` has the type `P1 -> P2 -> ... -> Pn -> (A ⊢ ϕ)`, this\n * tactic adds goals for `P1, P2, ..., Pn` and specializes `H`. *)\nLtac assert_premises H :=\n  match type of H with\n  | ?A -> ?B => \n      let H' := fresh \"H\" in assert A as H';\n      [|specialize (H H'); clear H'; assert_premises H ]\n  | forall _, _ => eassert (H := H _); assert_premises H\n  | _ => idtac\n  end.\n\nLtac feapply' T A := fun contxt =>\n  let H := fresh \"H\" in\n  turn_into_hypothesis T H contxt;\n  (* If `H` contains further Coq premises before the formula \n   * statement, we add them as additional goals. *)\n  assert_premises H;\n  (* Only try here, because it would fail on these additional goals. *)\n  try (\n    fspecialize_list H A;\n    instantiate_evars H;\n    simpl_subst H;\n    let C := get_context_goal in \n    eapply (Weak _ C) in H; [| firstorder];\n    fapply_without_quant H; \n    (* [fapply_without_quant] creates the subgoals in the wrong order.\n     * Reverse them to to get the right order: *)\n    revgoals\n  );\n  clear H.\n\nLtac fapply' T A contxt :=\n  let H := fresh \"H\" in\n  turn_into_hypothesis T H contxt;\n  (* If `H` contains further Coq premises before the formula \n   * statement, we add them as additional goals. *)\n  assert_premises H;\n  (* Only try here, because it would fail on these additional goals. *)\n  try (\n    fspecialize_list H A; \n    instantiate_evars H; \n    simpl_subst H;\n    let C := get_context_goal in\n    eapply (Weak _ C) in H; [| firstorder];\n    fapply_without_quant H;\n    (* [fapply_without_quant] creates the subgoals in the wrong order.\n     * Reverse them to to get the right order: *)\n    revgoals;\n    (* Evars should only be used for unification in [fapply].\n     * Therefore reject, if there are still evars visible. *)\n    (* TODO: This is not optimal. If the goal contains evars, \n     * H might still contain evars after unification and we would fail. *)\n    tryif has_evar ltac:(type of H) \n    then fail 3 \"Cannot find instance for variable. Try feapply?\" \n    else clear H\n  );\n  try clear H.\n\n\nTactic Notation \"feapply\" constr(T) := make_compatible ltac:(feapply' T constr:([] : list form)).\nTactic Notation \"feapply\" \"(\" constr(T) constr(x1) \")\" := make_compatible ltac:(feapply' T constr:([x1])).\nTactic Notation \"feapply\" \"(\" constr(T) constr(x1) constr(x2) \")\" := make_compatible ltac:(feapply' T constr:([x1;x2])).\nTactic Notation \"feapply\" \"(\" constr(T) constr(x1) constr(x2) constr(x3) \")\" := make_compatible ltac:(feapply' T constr:([x1;x2;x3])).\n\nTactic Notation \"fapply\" constr(T) := make_compatible ltac:(fapply' T constr:([] : list form)).\nTactic Notation \"fapply\" \"(\" constr(T) constr(x1) \")\" := make_compatible ltac:(fapply' T constr:([x1])).\nTactic Notation \"fapply\" \"(\" constr(T) constr(x1) constr(x2) \")\" := make_compatible ltac:(fapply' T constr:([x1;x2])).\nTactic Notation \"fapply\" \"(\" constr(T) constr(x1) constr(x2) constr(x3) \")\" := make_compatible ltac:(fapply' T constr:([x1;x2;x3])).\n\n(* If the term to apply is the result of a function call\n * (like `PA_induction (...)`), this needs to be differentiated\n * from the other parenthesis notation.\n *\n * To make it work, you need to put double parenthesis: [fapply ((PA_induction (...)))] *)\nTactic Notation \"feapply\" \"(\" constr(T) \")\" := make_compatible ltac:(feapply' T constr:([] : list form)).\nTactic Notation \"fapply\" \"(\" constr(T) \")\" := make_compatible ltac:(fapply' T constr:([] : list form)).\n\n\n\n\n\n\n(*\n * [fapply (H x1 ... xn) in Hyp ], [feapply (H x1 ... xn) in Hyp]\n *  \n * Works on\n * - Coq hypothesis by name\n * - Formula in in ND context by index (e.g. [fapply 3 in 0])\n * - Explicit formula type in the context (e.g. [fapply ax_symm in (x --> y)])\n * - Name of a context assumption in proof mode (e.g. [fapply \"H2\" in \"H1\"])\n *)\n\n\n(* Takes two formulas `H_imp : X ⊢ p1 --> ... --> pn --> q`\n * `H_hyp : X ⊢ pn`. It also takes `T_hyp` which identifies `H_hyp`\n * in the context.\n * It changes the assumption `pn` in the context into `q` and adds\n * additional goals for each premise `p1, p2, ..., pn`.\n *\n * Also supports formulas of Type `H_imp : X ⊢ ... --> (pn <--> q)` or \n * `H_imp : X ⊢ ... --> (q <--> pn)`.\n *\n * If ∀-quantifiers occur inbetween, they are instantiated with evars. *)\nLtac fapply_in_without_quant_in T_hyp H_imp H_hyp :=\n  match get_form_hyp H_imp with\n  | ?s --> ?t =>\n    let H_hyp' := fresh \"H_hyp'\" in\n    tryif assert_compat t as H_hyp' by (feapply H_imp; apply H_hyp)\n    then (replace_context T_hyp H_hyp'; clear H_hyp')\n    else ( \n      (* Try to assert `s` as a goal for the user to prove and\n       * check if we can apply `t`. *)\n      let Hs := fresh \"Hs\" in\n      let Ht := fresh \"Ht\" in\n      (enough_compat s as Hs); [\n        (assert_compat t as Ht by apply (IE _ _ _ H_imp Hs));\n        (* replace_context T_imp Ht; *)\n        fapply_in_without_quant_in T_hyp Ht H_hyp;\n        clear Ht; clear Hs\n      | ] )\n  \n  (* Handle application of equivalence. It would be nice to use match\n   * to check which side matches, but it doesn't work because of evars.\n   * Therefore simply try both options. *)\n  | ?s <--> ?t =>\n    let H_hyp' := fresh \"H_hyp'\" in\n    (tryif assert_compat t as H_hyp' by (feapply H_imp; apply H_hyp) then idtac\n    else assert_compat s as H_hyp' by (feapply H_imp; apply H_hyp));\n    replace_context T_hyp H_hyp'; clear H_hyp'\n  \n  (* Quantifiers are instantiated with evars *)\n  | ∀ _ => instantiate_evars H_imp; fapply_in_without_quant_in T_hyp H_imp H_hyp\n\n  (* If we don't find something useful, try unfolding definitions to \n    * check if there is something hidden underneath. Also perform \n    * simplification if the definition does something nasty. *)\n  | _ =>\n    progress custom_unfold; simpl_subst H_imp; simpl_subst H_hyp;\n    custom_unfold; (* Unfold again because [simpl_subst] folds *)\n    fapply_in_without_quant_in T_hyp H_imp H_hyp;\n    custom_fold\n  end.\n\n\nLtac feapply_in T_imp A T_hyp :=\n  let H_imp := fresh \"H_imp\" in\n  let H_hyp := fresh \"H_hyp\" in\n  make_compatible ltac:(fun contxt =>\n    turn_into_hypothesis T_imp H_imp contxt;\n    turn_into_hypothesis T_hyp H_hyp contxt\n  );\n  (* If `H_imp` contains further Coq premises before the  \n   * formula statement, we add them as additional goals. *)\n  assert_premises H_imp;\n  (* Only try here, because it would fail on these additional goals. *)\n  try (\n    fspecialize_list H_imp A;\n    instantiate_evars H_imp;\n    simpl_subst H_imp;\n    let C := get_context_goal in \n    eapply (Weak _ C) in H_imp; [| firstorder];\n    fapply_in_without_quant_in T_hyp H_imp H_hyp;\n    (* [fapply_in_without_quant_in] creates the subgoals in the wrong order.\n     * Reverse them to to get the right order: *)\n    revgoals;\n    clear H_imp; clear H_hyp\n  ).\n\nLtac fapply_in T_imp A T_hyp :=\n  feapply_in T_imp A T_hyp;\n  (* Evars should only be used for unification in [fapply].\n   * Therefore reject, if there are still evars visible. *)\n  (* TODO: This is not optimal. If the goal contains evars, \n   * H might still contain evars after unification and we would fail. *)\n  let C := get_context_goal in\n  let phi := get_form_goal in\n  tryif has_evar C then fail 3 \"Cannot find instance for variable. Try feapply?\" \n  else tryif has_evar phi then fail 3 \"Cannot find instance for variable. Try feapply?\" \n  else idtac.\n\nTactic Notation \"feapply\" constr(T_imp) \"in\" constr(T_hyp) := feapply_in T_imp constr:([] : list form) T_hyp.\nTactic Notation \"feapply\"  \"(\" constr(T_imp) constr(x1) \")\" \"in\" constr(T_hyp) := feapply_in T_imp constr:([x1] : list form) T_hyp.\nTactic Notation \"feapply\" \"(\" constr(T_imp) constr(x1) constr(x2) \")\" \"in\" constr(T_hyp) := feapply_in T_imp constr:([x1;x2] : list form) T_hyp.\nTactic Notation \"feapply\" \"(\" constr(T_imp) constr(x1) constr(x2) constr(x3) \")\" constr(T_hyp) := feapply_in T_imp constr:([x1;x2;x3] : list form) T_hyp.\n\nTactic Notation \"fapply\" constr(T_imp) \"in\" constr(T_hyp) := fapply_in T_imp constr:([] : list form) T_hyp.\nTactic Notation \"fapply\"  \"(\" constr(T_imp) constr(x1) \")\" \"in\" constr(T_hyp) := fapply_in T_imp constr:([x1] : list form) T_hyp.\nTactic Notation \"fapply\" \"(\" constr(T_imp) constr(x1) constr(x2) \")\" \"in\" constr(T_hyp) := fapply_in T_imp constr:([x1;x2] : list form) T_hyp.\nTactic Notation \"fapply\" \"(\" constr(T_imp) constr(x1) constr(x2) constr(x3) \")\" constr(T_hyp) := fapply_in T_imp constr:([x1;x2;x3] : list form) T_hyp.\n\n\n\n\n\n(*\n * [fassert phi], [fassert phi as \"H\"]\n *\n * Similar to coq. Also supports intro patterns.\n *)\n\nSection Fassert.\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  Lemma fassert_help `{peirce} A phi psi :\n    A ⊢ phi -> A ⊢ (phi --> psi) -> A ⊢ psi.\n  Proof.\n    intros H1 H2. eapply IE. exact H2. exact H1.\n  Qed.\n\n  Context {eq_dec_Funcs : EqDec syms}.\n  Context {eq_dec_Preds : EqDec preds}.\n\n  Lemma fassert_help_T `{peirce} A phi psi :\n    A ⊩ phi -> A ⊩ (phi --> psi) -> A ⊩ psi.\n  Proof.\n    intros H1 H2. eapply IE. exact H2. exact H1.\n  Qed.\nEnd Fassert.\n\nLtac fassert' phi := fun _ =>\n  let H1 := fresh \"H\" in\n  let H2 := fresh \"H\" in\n  match goal with\n  | [ |- ?A ⊢ ?psi ] =>\n    assert (A ⊢ phi) as H1; [ | \n      assert (A ⊢ (phi --> psi)); [ clear H1 |\n        apply (fassert_help A phi psi H1 H2)\n      ]\n    ]\n  | [ |- ?A ⊩ ?psi ] =>\n    assert (A ⊩ phi) as H1; [ | \n      assert (A ⊩ (phi --> psi)); [ clear H1 |\n        apply (fassert_help_T A phi psi H1 H2)\n      ]\n    ]\n  end.\n\nTactic Notation \"fassert\" constr(phi) := (make_compatible ltac:(fassert' phi)); [| fintro].\nTactic Notation \"fassert\" constr(phi) \"as\" constr(H) := (make_compatible ltac:(fassert' phi)); [| fintro_pat H].\nTactic Notation \"fassert\" constr(phi) \"by\" tactic(tac) := (make_compatible ltac:(fassert' phi)); [tac | fintro].\nTactic Notation \"fassert\" constr(phi) \"as\" constr(H) \"by\" tactic(tac) := (make_compatible ltac:(fassert' phi)); [tac | fintro_pat H].\n\n\n\n\n\n(*\n * [fdestruct H], [fdestruct H as \"pattern\"]\n *\n * Destructs an assumption into the ND context. Works on\n * - Coq hypothesis by name\n * - Formula in in ND context by index (e.g. [fdestruct 3])\n * - Name of a context assumption in proof mode (e.g. [fdestruct \"H2\"])\n *)\n\nLtac fdestruct' n pat :=\n  match n with\n  | 0 =>  \n    match goal with \n    | [ |- prv _ _ ] => apply -> switch_imp; fintro_pat' pat\n    | [ |- tprv _ _ ] => apply -> switch_imp_T; fintro_pat' pat\n    | [ |- pm (ccons _ ?t ?C) ?phi ] => apply -> switch_imp; change (pm C (t --> phi)); fintro_pat' pat\n    | [ |- tpm (tcons _ ?t ?C) ?phi ] => apply -> switch_imp_T; change (tpm C (t --> phi)); fintro_pat' pat\n    end\n  | S ?n' =>\n    match goal with \n    | [ |- prv _ _ ] => apply -> switch_imp; fdestruct' n' pat; apply <- switch_imp\n    | [ |- tprv _ _ ] => apply -> switch_imp_T; fdestruct' n' pat; apply <- switch_imp_T\n    | [ |- pm  (ccons ?a ?t ?C) ?phi ] => \n        apply -> switch_imp; change (pm C (t --> phi)); fdestruct' n' pat;\n        match goal with [ |- pm ?C' (t --> phi) ] => \n          apply <- switch_imp; change (pm (ccons a t C') phi)\n        end\n    | [ |- tpm (tcons ?a ?t ?C) ?phi ] => \n        apply -> switch_imp_T; change (tpm C (t --> phi)); fdestruct' n' pat;\n        match goal with [ |- tpm ?C' (t --> phi) ] => \n          apply <- switch_imp_T; change (tpm (tcons a t C') phi)\n        end\n    end\n  end.\n\nLtac create_pattern T :=\n  match T with\n  | ?t ∧ ?s =>\n    let p1 := create_pattern t in\n    let p2 := create_pattern s in\n    constr:(patAnd p1 p2)\n  | ?t ∨ ?s =>\n    let p1 := create_pattern t in\n    let p2 := create_pattern s in\n    constr:(patOr p1 p2)\n  | ∃ ?t =>\n    let p1 := constr:(patId \"?\") in\n    let p2 := create_pattern t in\n    constr:(patAnd p1 p2)\n  | _ => constr:(patId \"?\")\n  end.\n\nLtac fdestruct'' T pat :=\n  tryif is_hyp T then (\n    let H := fresh \"H\" in\n    let X := fresh \"X\" in\n    assert (H := T);\n    let s := get_form_hyp H in\n    match goal with\n    | [ |- prv ?A ?t ] => enough (A ⊢ (s --> t)) as X by (feapply X; feapply H)\n    | [ |- tprv ?A ?t ] => enough (A ⊩ (s --> t)) as X by (feapply X; feapply H)\n    | [ |- pm ?A ?t ] => enough (pm A (s --> t)) as X by (feapply X; feapply H)\n    | [ |- tpm ?A ?t ] => enough (tpm A (s --> t)) as X by (feapply X; feapply H)\n    end;\n    fintro \"?\"; fdestruct'' 0 pat; clear H\n  )\n  else (\n    let n := match type of T with \n      | nat => T \n      | string =>\n        let C := get_context_goal in\n        match lookup C T with \n        | @Some _ ?n' => n'\n        | @None => let msg := eval cbn in (\"Unknown identifier: \" ++ T) in fail 3 msg\n        end\n      end\n    in\n    let pattern := lazymatch pat with\n      | \"\" => let C := get_context_goal in let t := nth C n in create_pattern t\n      | _ => \n        match eval cbn in (parse_intro_pattern pat) with \n        | @Some _ ?p => p\n        | @None => let msg := eval cbn in (\"Invalid pattern: \" ++ pat) in fail 3 msg\n        end\n    end in fdestruct' n pattern\n  ).\n\nTactic Notation \"fdestruct\" constr(T) := fdestruct'' T \"\".\nTactic Notation \"fdestruct\" constr(T) \"as\" constr(pat) := fdestruct'' T pat.\n\n(* Now that we have fdestruct, we can build a fancy [eapply in as] tactic *)\nTactic Notation \"feapply\" constr(T_imp) \"in\" constr(T_hyp) \"as\" constr(pat) := feapply_in T_imp constr:([] : list form) T_hyp; try fdestruct T_hyp as pat.\nTactic Notation \"feapply\"  \"(\" constr(T_imp) constr(x1) \")\" \"in\" constr(T_hyp) \"as\" constr(pat) := feapply_in T_imp constr:([x1] : list form) T_hyp; try fdestruct T_hyp as pat.\nTactic Notation \"feapply\" \"(\" constr(T_imp) constr(x1) constr(x2) \")\" \"in\" constr(T_hyp) \"as\" constr(pat) := feapply_in T_imp constr:([x1;x2] : list form) T_hyp; try fdestruct T_hyp as pat.\nTactic Notation \"feapply\" \"(\" constr(T_imp) constr(x1) constr(x2) constr(x3) \")\" constr(T_hyp) \"as\" constr(pat) := feapply_in T_imp constr:([x1;x2;x3] : list form) T_hyp; try fdestruct T_hyp as pat.\n\nTactic Notation \"fapply\" constr(T_imp) \"in\" constr(T_hyp) \"as\" constr(pat) := fapply_in T_imp constr:([] : list form) T_hyp; try fdestruct T_hyp as pat.\nTactic Notation \"fapply\"  \"(\" constr(T_imp) constr(x1) \")\" \"in\" constr(T_hyp) \"as\" constr(pat) := fapply_in T_imp constr:([x1] : list form) T_hyp; try fdestruct T_hyp as pat.\nTactic Notation \"fapply\" \"(\" constr(T_imp) constr(x1) constr(x2) \")\" \"in\" constr(T_hyp) \"as\" constr(pat) := fapply_in T_imp constr:([x1;x2] : list form) T_hyp; try fdestruct T_hyp as pat.\nTactic Notation \"fapply\" \"(\" constr(T_imp) constr(x1) constr(x2) constr(x3) \")\" constr(T_hyp) \"as\" constr(pat) := fapply_in T_imp constr:([x1;x2;x3] : list form) T_hyp; try fdestruct T_hyp as pat.\n\n\n\n\n\n(** Classical Logic *)\n\nSection Classical.\n  Context {Σ_funcs : funcs_signature}.\n  Context {Σ_preds : preds_signature}.\n\n  Lemma case_help A phi psi :\n    A ⊢C (phi ∨ (phi --> ⊥) --> psi) -> A ⊢C psi.\n  Proof.\n    intro H. eapply IE. apply H.\n    eapply IE. eapply Pc.\n    apply II. apply DI2. apply II.\n    eapply IE. apply Ctx. right. now left.\n    apply DI1. apply Ctx. now left.\n  Qed.\n\n  Lemma contradiction_help A phi :\n    A ⊢C ((phi --> ⊥) --> ⊥) -> A ⊢C phi.\n  Proof.\n    intro H. eapply IE. eapply Pc. apply II.\n    apply Exp. eapply IE. eapply Weak. apply H. firstorder.\n    apply II. eapply IE. apply Ctx. right. now left.\n    apply Ctx. now left.\n  Qed.\n\n  Context {eq_dec_Funcs : EqDec syms}.\n  Context {eq_dec_Preds : EqDec preds}.\n\n  Lemma case_help_T A phi psi :\n    A ⊩C (phi ∨ (phi --> ⊥) --> psi) -> A ⊩C psi.\n  Proof.\n    intro H. eapply IE. apply H.\n    eapply IE. eapply Pc.\n    apply II. apply DI2. apply II.\n    eapply IE. apply Ctx. firstorder.\n    apply DI1. apply Ctx. firstorder.\n  Qed.\n\n  Lemma contradiction_help_T A phi :\n    A ⊩C ((phi --> ⊥) --> ⊥) -> A ⊩C phi.\n  Proof.\n    intro H. eapply IE. eapply Pc. apply II.\n    apply Exp. eapply IE. eapply Weak. apply H. firstorder.\n    apply II. eapply IE. apply Ctx. firstorder.\n    apply Ctx. firstorder.\n  Qed.\n\nEnd Classical.\n\n\nTactic Notation \"fclassical\" constr(phi) \"as\" constr(H1) constr(H2) := \n  make_compatible ltac:(fun _ => \n    match goal with\n    | [ |- _ ⊢ _ ] => apply (case_help _ phi)\n    | [ |- _ ⊩ _ ] => apply (case_help_T _ phi)\n    end\n  ); let pat := eval cbn in (\"[\" ++ H1 ++ \"|\" ++ H2 ++ \"]\") in fintro_pat pat.\nTactic Notation \"fclassical\" constr(phi) \"as\" constr(H) := fclassical phi as H H.\nTactic Notation \"fclassical\" constr(phi) := fclassical phi as \"\".\n\nTactic Notation \"fcontradict\" \"as\" constr(H) := \n  make_compatible ltac:(fun _ => \n    match goal with \n    | [ |- _ ⊢ _ ] => apply contradiction_help\n    | [ |- _ ⊩ _ ] => apply contradiction_help_T\n    end\n  ); fintro_pat H.\nTactic Notation \"fcontradict\" := fcontradict as \"?\".\n\n\n\n\n\n\n\n\nDefinition cast {X} {x y: X} {p: X -> Type}\n  : x = y -> p x -> p y\n  := fun e a => match e with eq_refl => a end.\n\nClass Leibniz (Σ_funcs : funcs_signature) (Σ_preds : preds_signature) :=\n{\n  Eq_pred : preds ;\n  eq_binary : 2 = ar_preds Eq_pred ;\n  (* eq s t := @atom Σ_funcs Σ_preds _ Eq (@eq_rect _ _ (fun n : nat => Vector.t term n) (Vector.cons term s 1 (Vector.cons term t 0 (Vector.nil term))) _ eq_binary) ; *)\n  eq s t := @atom Σ_funcs Σ_preds _ Eq_pred (cast eq_binary (Vector.cons term s 1 (Vector.cons term t 0 (Vector.nil term)))) ;\n\n  Axioms : list form ;\n  Axioms_T : theory ;\n  (* Axioms_T_closed : closed_theory Axioms_T ; *)\n  (* sym `{peirce} : Axioms ⊢ ∀ ∀ (eq ($0) ($1) --> eq ($1) ($0)) ; *)\n  sym_T `{peirce} T : Axioms ⊏ T ->  T ⊩ ∀ ∀ (eq ($0) ($1) --> eq ($1) ($0)) ;\n  leibniz `{peirce} A phi t t' : Axioms <<= A -> A ⊢ eq t t' -> A ⊢ phi[t..] -> A ⊢ phi[t'..] ;\n  leibniz_T `{peirce} T phi t t' : Axioms_T ⊑ T -> T ⊩ eq t t' -> T ⊩ phi[t..] -> T ⊩ phi[t'..]\n}.\n\n\nLemma eq_subst_help `{funcs_signature} f y t1 t2 (e : 2 = y) :\n  Vector.map f (cast e (Vector.cons term t1 1 (Vector.cons term t2 0 (Vector.nil term)))) = cast e (@Vector.map term term f _ (Vector.cons term t1 1 (Vector.cons term t2 0 (Vector.nil term)))).\nProof.\n  destruct e. reflexivity.\nQed.\n\nLemma eq_subst `{L : Leibniz} t1 t2 s :\n  (eq t1 t2)[s] = eq (t1`[s]) (t2`[s]).\nProof.\n  cbn. rewrite eq_subst_help. cbn. reflexivity.\nQed.\n\nLemma sym `{Leibniz, peirce} :\n  Axioms ⊢ ∀ ∀ (eq $0 $1 --> eq $1 $0).\nProof.\n  intros. fintros s t. repeat (rewrite eq_subst_help; cbn).\n  change (Axioms ⊢ (eq t s`[↑]`[t..] --> eq s`[↑]`[t..] t)). simpl_subst.\n  fintro. enough ((eq t s :: Axioms) ⊢ (eq t s --> eq s t)). eapply IE. apply H1. ctx.\n  enough ((eq t s::Axioms) ⊢ (eq t`[↑]`[s..] $0`[s..] --> eq $0`[s..] t`[↑]`[s..])) as X by now rewrite subst_term_shift in X.\n  enough ((eq t s::Axioms) ⊢ (eq t`[↑] $0 --> eq $0 t`[↑])[s..]) by now rewrite <- ! eq_subst.\n  eapply leibniz. firstorder. apply Ctx. now left. cbn. repeat (rewrite eq_subst_help; cbn).\n  change ((eq t s :: Axioms) ⊢ (eq t`[↑]`[t..] t --> eq t t`[↑]`[t..])).\n  rewrite subst_term_shift.\n  apply II. apply Ctx. now left.\nQed.\n\n(* Lemma sym_T `{peirce, Leibniz} :\n  Axioms_T ⊩ ∀ ∀ (eq ($0) ($1) --> eq ($1) ($0)).\nProof.\n  apply AllI, AllI.\n  pose (T' := mapT (subst_form ↑) (mapT (subst_form ↑) Axioms_T)).\n  pose (t := $0). pose (s := $1).\n  fintro. enough ((T' ⋄ eq t s) ⊩ (eq t s --> eq s t)) as X. eapply IE. apply X.\n  apply Ctx. now right.\n  enough ((T' ⋄ eq t s) ⊩ (eq t`[↑]`[s..] $0`[s..] --> eq $0`[s..] t`[↑]`[s..])) as X by now rewrite subst_term_shift in X.\n  enough ((T' ⋄ eq t s) ⊩ (eq t`[↑] $0 --> eq $0 t`[↑])[s..]) by now rewrite <- ! eq_subst.\n  eapply leibniz_T.\n  { intros phi H2. left. exists phi. split. exists phi. split. now apply H2.\n    all: apply subst_closed; now apply Axioms_T_closed. }\n  apply Ctx. now right.\n  cbn. repeat (rewrite eq_subst_help; cbn).\n  change ((T' ⋄ eq t s) ⊩ (eq t t --> eq t t)).\n  apply II. ctx.\nQed. *)\n\n\n(* Lemmas for rewriting with equivalences *)\nSection FrewriteEquiv.\n  Context {Σ_funcs : funcs_signature}.  \n  Context {Σ_preds : preds_signature}.\n  Context {p : peirce}.\n\n  Lemma frewrite_equiv_bin_l A op phi psi theta :\n    A ⊢ (phi <--> psi) -> A ⊢ (bin op phi theta <--> bin op psi theta).\n  Proof.\n    intros E. fstart. destruct op; fsplit.\n    - fintros \"[P T]\". fsplit. fapply E. ctx. ctx.\n    - fintros \"[P T]\". fsplit. fapply E. ctx. ctx.\n    - fintros \"[P|T]\". fleft. fapply E. ctx. fright. ctx.\n    - fintros \"[P|T]\". fleft. fapply E. ctx. fright. ctx.\n    - fintros \"H\" \"P\". fapply \"H\". fapply E. ctx.\n    - fintros \"H\" \"P\". fapply \"H\". fapply E. ctx. \n  Qed.\n\n  Lemma frewrite_equiv_bin_r A op phi psi theta :\n    A ⊢ (phi <--> psi) -> A ⊢ (bin op theta phi <--> bin op theta psi).\n  Proof.\n    intros E. fstart. destruct op; fsplit.\n    - fintros \"[P T]\". fsplit. ctx. fapply E. ctx.\n    - fintros \"[P T]\". fsplit. ctx. fapply E. ctx.\n    - fintros \"[P|T]\". fleft. ctx. fright. fapply E. ctx.\n    - fintros \"[P|T]\". fleft. ctx. fright. fapply E. ctx.\n    - fintros \"H\" \"P\". fapply E. fapply \"H\". ctx.\n    - fintros \"H\" \"P\". fapply E. fapply \"H\". ctx.\n  Qed.\n\n  Lemma frewrite_equiv_bin_lr A op phi psi theta chi :\n    A ⊢ (phi <--> psi) -> A ⊢ (theta <--> chi) -> A ⊢ (bin op phi theta <--> bin op psi chi).\n  Proof.\n    intros E1 E2. fstart. destruct op; fsplit.\n    - fintros \"[P T]\". fsplit. fapply E1. ctx. fapply E2. ctx.\n    - fintros \"[P C]\". fsplit. fapply E1. ctx. fapply E2. ctx.\n    - fintros \"[P|T]\". fleft. fapply E1. ctx. fright. fapply E2. ctx.\n    - fintros \"[P|C]\". fleft. fapply E1. ctx. fright. fapply E2. ctx.\n    - fintros \"H\" \"P\". fapply E2. fapply \"H\". fapply E1. ctx.\n    - fintros \"H\" \"P\". fapply E2. fapply \"H\". fapply E1. ctx.\n  Qed.\n\n  Lemma frewrite_equiv_quant A op phi psi :\n    A ⊢ (phi <--> psi) -> A ⊢ (quant op phi[↑] <--> quant op psi[↑]).\n  Proof.\n    intros E. fstart. destruct op; fsplit.\n    - fintros \"H\" x. fapply E. fapply (\"H\" $0). (* Give dummy argument to avoid uninstantiated evar *)\n    - fintros \"H\" x. fapply E. fapply (\"H\" $0).\n    - fintros \"[x H]\". apply ExI with (t := x); simpl_subst. fapply E. ctx.\n    - fintros \"[x H]\". apply ExI with (t := x); simpl_subst. fapply E. ctx.\n  Qed.\n\n  Lemma frewrite_equiv_switch A phi psi :\n    A ⊢ (phi <--> psi) -> A ⊢ (psi <--> phi).\n  Proof.\n    intros E. fdestruct E. fsplit; ctx.\n  Qed.\n\n  Context {eq_dec_Funcs : EqDec syms}.\n  Context {eq_dec_Preds : EqDec preds}.\n\n  Lemma frewrite_equiv_bin_l_T T op phi psi theta :\n    T ⊩ (phi <--> psi) -> T ⊩ (bin op phi theta <--> bin op psi theta).\n  Proof.\n    intros [A [ ]]. exists A. split. easy. now apply frewrite_equiv_bin_l.\n  Qed.\n\n  Lemma frewrite_equiv_bin_r_T T op phi psi theta :\n    T ⊩ (phi <--> psi) -> T ⊩ (bin op theta phi <--> bin op theta psi).\n  Proof.\n    intros [A [ ]]. exists A. split. easy. now apply frewrite_equiv_bin_r.\n  Qed.\n\n  Lemma frewrite_equiv_bin_lr_T T op phi psi theta chi :\n    T ⊩ (phi <--> psi) -> T ⊩ (theta <--> chi) -> T ⊩ (bin op phi theta <--> bin op psi chi).\n  Proof.\n    intros [A [ ]] [B [ ]]. exists (List.app A B). split.\n    now apply contains_app. apply frewrite_equiv_bin_lr.\n    eapply Weak. apply H0. now apply incl_appl.\n    eapply Weak. apply H2. now apply incl_appr.\n  Qed.\n\n  Lemma frewrite_equiv_quant_T T op phi psi :\n    T ⊩ (phi <--> psi) -> T ⊩ (quant op phi[↑] <--> quant op psi[↑]).\n  Proof.\n    intros [A [ ]]. exists A. split. easy. now apply frewrite_equiv_quant.\n  Qed.\n\n  Lemma frewrite_equiv_switch_T T phi psi :\n    T ⊩ (phi <--> psi) -> T ⊩ (psi <--> phi).\n  Proof.\n    intros [A [ ]]. exists A. split. easy. now apply frewrite_equiv_switch.\n  Qed.\n\nEnd FrewriteEquiv.\n\nLtac contains phi f := match phi with f => idtac | context P [ f ] => idtac end.\n\n(* Solves a goal `A <--> B` if `A` equals `B` up to replacing `phi`\n * with `psi`. `H` needs to be proof of `C ⊢ phi <--> psi`. *)\nLtac frewrite_equiv_solve H phi psi :=\n  match get_form_goal with\n  | phi <--> psi => apply H\n  | bin ?op ?l ?r <--> _ => (\n      tryif contains l phi\n      then (tryif contains r phi\n        then apply_compat frewrite_equiv_bin_lr frewrite_equiv_bin_lr_T\n        else apply_compat frewrite_equiv_bin_l frewrite_equiv_bin_l_T)\n      else apply_compat frewrite_equiv_bin_r frewrite_equiv_bin_r_T\n    );\n    frewrite_equiv_solve H phi psi\n  | quant _ _ _ <--> _ => \n    apply_compat frewrite_equiv_quant frewrite_equiv_quant_T;\n    frewrite_equiv_solve H phi psi\n  end.\n\n(* Replaces all occurences of `t` in `phi` with `s`. *)\nLtac frewrite_replace_all phi t s :=\n  match phi with\n  | context C[t] => let phi' := context C[s] in frewrite_replace_all phi' t s\n  | _ => phi\n  end.\n\nFixpoint up_n `{funcs_signature} n sigma := match n with\n| 0 => sigma\n| S n' => up (up_n n' sigma)\nend.\n\nLtac shift_n n t := \n  match n with\n  | 0 => t\n  | S ?n' => shift_n n' (t`[↑])\n  end.\n\nLtac vector_map_ltac v f :=\n  match v with\n  | Vector.nil ?t => constr:(Vector.nil t)\n  | @Vector.cons _ ?x _ ?v' =>\n    let x' := f x in \n    let v'' := vector_map_ltac v' f in\n    constr:(@Vector.cons _ x' _ v'')\n  end.\n\n(* Returns a new formula where all occurences of `t` are turned into\n * `($n)[up_n n t..]` and every other term `s` into `s[up_n n ↑][up_n t..]`,\n * where `n` is the quantor depth. *)\nLtac add_shifts' n t G :=\n  let f := add_shifts' n t in \n  let t_shifted := shift_n n t in\n  match G with\n  (* Terms: *)\n  | t_shifted => constr:(($n)`[up_n n t..])\n  | $(?m) => constr:(($m)`[up_n n ↑]`[up_n n t..])\n  | func ?fu ?vec => let vec' := vector_map_ltac vec f in constr:(func fu vec')\n  (* Formulas: *)\n  | fal => constr:(fal[up_n n ↑][up_n n t..])\n  | atom ?P ?vec => let vec' := vector_map_ltac vec f in constr:(atom P vec')\n  | bin ?op ?u ?v => let u' := f u in let v' := f v in constr:(bin op u' v')\n  | quant ?op ?u => let u' := add_shifts' (S n) t u in constr:(quant op u')\n  (* Fallback for variables which cannot be matched syntactically: *)\n  | ?u => match type of u with \n      | form => constr:(u[up_n n ↑][up_n n t..])\n      | term => constr:(u`[up_n n ↑]`[up_n n t..])\n      end\n  end.\nLtac add_shifts := add_shifts' 0.\n\n(* Returns a new formula where all occurences of `s[up_n n ↑][up_n nt..]` \n * in G are turned into `s[up_n n ↑]` and `($n)[up_n n t..]` into `$n`. *)\nLtac remove_shifts G t :=\n  match G with \n  | context C[ ?s[up_n ?n ↑][up_n ?n t..] ] => let G' := context C[ s[up_n n ↑] ] in remove_shifts G' t\n  | context C[ ?s`[up_n ?n ↑]`[up_n ?n t..] ] => let G' := context C[ s`[up_n n ↑] ] in remove_shifts G' t\n  | context C[ ($ ?n)`[up_n ?n t..] ] => let G' := context C[ $n ] in remove_shifts G' t\n  | _ => G\n  end.\n\n(* Like [do n tac] but works with Galina numbers. *)\nLtac repeat_n n tac := match n with 0 => idtac | S ?n' => tac; repeat_n n' tac end.\n\nLtac frewrite' T A back := fun contxt =>\n  let H := fresh \"H\" in\n  turn_into_hypothesis T H contxt;\n  fspecialize_list H A; \n  instantiate_evars H; \n  simpl_subst H;\n\n  (* For some reason the match below binds `_t` and `_t'` to terms\n   * with unfolded constants (like `zero` in PA). This messes up\n   * syntactic matching later. Therefore just unfold everything,\n   * do the rewriting and fold back later. *)\n  custom_unfold;\n\n  match get_form_hyp H with \n  (* Rewrite with equivalence *)\n  | ?_phi <--> ?_psi => \n    let phi := match back with true => _psi | false => _phi end in\n    let psi := match back with true => _phi | false => _psi end in\n    match back with true => apply_compat frewrite_equiv_switch frewrite_equiv_switch_T in H | _ => idtac end;\n\n    let G := get_form_goal in\n    let G' := frewrite_replace_all G phi psi in\n    let E := fresh \"E\" in\n    assert_compat (G <--> G') as E;\n    [ frewrite_equiv_solve H phi psi |];\n    feapply E;\n    clear E\n\n  (* Rewrite with equality *)\n  | atom ?p (@Vector.cons _ ?_t _ (@Vector.cons _ ?_t' _ (Vector.nil term))) =>\n    (* Make sure that we have equality *)\n    assert (p = Eq_pred) as _ by reflexivity;\n\n    let t := match back with true => _t' | false => _t end in\n    let t' := match back with true => _t | false => _t' end in\n    \n    (* 1. Replace each occurence of `t` with `($n)[up_n n t..]` and every\n     *  other `s` with `s[up_n n ↑][up_n n t..]`. The new formula is \n     *  created with the [add_shifts] tactic and proven in place. *)\n    let C := get_context_goal in\n    let G := get_form_goal in\n    let X := fresh in\n    let G' := add_shifts t G in\n    match goal with\n    | [ |- _ ⊢ _ ] => enough (C ⊢ G') as X\n    | [ |- _ ⊩ _ ] => enough (C ⊩ G') as X\n    end;\n    [\n      repeat match type of X with context K[ ?u`[up_n ?n ↑]`[up_n ?n t..] ] =>\n        let R := fresh in\n        (* TODO: Prove general lemma for this: *)\n        assert (u`[up_n n ↑]`[up_n n t..] = u) as R; [\n          rewrite subst_term_comp; apply subst_term_id; \n          let a := fresh in intros a;\n          (repeat_n n ltac:(try destruct a)); reflexivity |];\n        rewrite R in X\n      end;\n      apply X\n    |];\n    \n    (* 2. Pull out the [t..] substitution *)\n    match goal with \n    | [ |- ?U ⊢ ?G ] => let G' := remove_shifts G t in change (U ⊢ G'[t..])\n    | [ |- ?U ⊩ ?G ] => let G' := remove_shifts G t in change (U ⊩ G'[t..])\n    end;\n    \n    (* 3. Change [t..] to [t'..] using leibniz. For some reason\n     *  we cannot directly [apply leibniz with (t := t')] if t'\n     *  contains ⊕, σ, etc. But evar seems to work. *)\n    let t'' := fresh \"t\" in \n    match goal with\n    | [ |- _ ⊢ _ ] => eapply (leibniz _ _ ?[t''])\n    | [ |- _ ⊩ _ ] => eapply (leibniz_T _ _ ?[t''])\n    end;\n    [ instantiate (t'' := t'); firstorder |\n      match back with\n      | false => let H_sym := fresh in assert (H_sym := sym); feapply H_sym; clear H_sym; fapply H\n      | true => apply H\n      end\n    | ];\n    \n    (* 4. Pull substitutions inward, but don't unfold `up_n` *)\n    cbn -[up_n];\n    \n    (* 5. Turn subst_term calls back into []-Notation *)\n    (* repeat match goal with [ |- context C`[subst_term ?sigma ?s] ] =>\n      let G' := context C[ s`[sigma] ] in change G'\n    end; *)\n\n    (* 6. Fix simplification that occurs because of cbn *)\n    repeat match goal with [ |- context C[up_n ?n ↑ ?a] ] =>\n      let G' := context C[ ($a)[up_n n ↑] ] in change G'\n    end;\n\n    (* 7. Change `up (up ...)` back into `up_n n ...` *)\n    repeat match goal with \n    | [ |- context C[up_n ?n (up ?s)]] => let G' := context C[up_n (S n) s] in change G'\n    | [ |- context C[up ?s]] => let G' := context C[up_n 1 s] in change G'\n    end;\n    \n    (* 8. Simplify *)\n    repeat match goal with [ |- context K[ ?u `[up_n ?n ↑]`[up_n ?n t'..] ]] =>\n      let R := fresh in\n      (* TODO: Prove general lemma for this: *)\n      assert (u`[up_n n ↑]`[up_n n t'..] = u) as R; [\n        rewrite subst_term_comp; apply subst_term_id; \n        let a := fresh in intros a;\n        (repeat_n n ltac:(try destruct a)); reflexivity |];\n      rewrite ! R;\n      clear R\n    end;\n\n    (* Base case for rewrite without quantors *)\n    cbn; try rewrite !subst_shift; try rewrite !subst_term_shift;\n\n    (* Final simplifications *)\n    custom_fold;\n    simpl_subst\n  end;\n  clear H.\n\nTactic Notation \"frewrite\" constr(T) := make_compatible ltac:(frewrite' T constr:([] : list form) constr:(false)).\nTactic Notation \"frewrite\" \"(\" constr(T) constr(x1) \")\" := make_compatible ltac:(frewrite' T constr:([x1]) constr:(false)).\nTactic Notation \"frewrite\" \"(\" constr(T) constr(x1) constr(x2) \")\" := make_compatible ltac:(frewrite' T constr:([x1;x2]) constr:(false)).\nTactic Notation \"frewrite\" \"(\" constr(T) constr(x1) constr(x2) constr(x3) \")\" := make_compatible ltac:(frewrite' T constr:([x1;x2;x3]) constr:(false)).\n\nTactic Notation \"frewrite\" \"<-\" constr(T) := make_compatible ltac:(frewrite' T constr:([] : list form) constr:(true)).\nTactic Notation \"frewrite\" \"<-\" \"(\" constr(T) constr(x1) \")\" := make_compatible ltac:(frewrite' T constr:([x1]) constr:(true)).\nTactic Notation \"frewrite\" \"<-\" \"(\" constr(T) constr(x1) constr(x2) \")\" := make_compatible ltac:(frewrite' T constr:([x1;x2]) constr:(true)).\nTactic Notation \"frewrite\" \"<-\" \"(\" constr(T) constr(x1) constr(x2) constr(x3) \")\" := make_compatible ltac:(frewrite' T constr:([x1;x2;x3]) constr:(true)).\n\n\n\n\nLtac fexists x := make_compatible ltac:(fun _ => \n  apply ExI with (t := x); \n  simpl_subst).\n\n\n\n", "meta": {"author": "mark-koch", "repo": "firstorder-proof-mode", "sha": "393219ad8d90fd4ab31e854bf5b343a094bed3c5", "save_path": "github-repos/coq/mark-koch-firstorder-proof-mode", "path": "github-repos/coq/mark-koch-firstorder-proof-mode/firstorder-proof-mode-393219ad8d90fd4ab31e854bf5b343a094bed3c5/ProofMode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22729517267378996}}
{"text": "From stdpp Require Import finite.\nFrom trillium.prelude Require Import finitary quantifiers classical_instances.\nFrom trillium.fairness Require Import fairness fuel.\n\nSection gmap.\n  Context `{!EqDecision K, !Countable K}.\n\n  Definition max_gmap (m: gmap K nat) : nat :=\n    map_fold (λ k v r, v `max` r) 0 m.\n\n  Lemma max_gmap_spec m:\n    map_Forall (λ _ v, v <= max_gmap m) m.\n  Proof.\n    induction m using map_ind; first done.\n    apply map_Forall_insert =>//. rewrite /max_gmap map_fold_insert //.\n    - split; first lia. intros ?? Hnotin. specialize (IHm _ _ Hnotin). simpl in IHm.\n      unfold max_gmap in IHm. lia.\n    - intros **. lia.\n  Qed.\nEnd gmap.\n\nSection finitary.\n  Context `{M: FairModel}.\n  Context `{Λ: language}.\n  Context `{LM: LiveModel Λ M}.\n  Context `{EqDecision M}.\n  Context `{EqDecision (locale Λ)}.\n\n  Context `{HPI0: forall s x, ProofIrrel ((let '(s', ℓ) := x in M.(fmtrans) s ℓ s'): Prop) }.\n\n  Variable (ξ: execution_trace Λ -> finite_trace M (option M.(fmrole)) -> Prop).\n\n  Variable model_finitary: rel_finitary ξ.\n\n  #[local] Instance eq_dec_next_states ex atr c' oζ:\n    EqDecision {'(δ', ℓ) : M * (option (fmrole M)) |\n                  ξ (ex :tr[ oζ ]: c') (atr :tr[ ℓ ]: δ')}.\n  Proof. intros x y. apply make_decision. Qed.\n\n  Lemma model_finite: ∀ (ex : execution_trace Λ) (atr : finite_trace _ _) c' oζ,\n    Finite (sig (λ '(δ', ℓ), ξ (ex :tr[oζ]: c') (atr :tr[ℓ]: δ'))).\n  Proof.\n    intros ex atr c' oζ.\n    pose proof (model_finitary ex atr c' oζ).\n    by apply smaller_card_nat_finite in H.\n  Qed.\n\n  Definition enum_inner extr fmodtr c' oζ : list (M * option M.(fmrole)) :=\n    map proj1_sig (@enum _ _ (model_finite extr fmodtr c' oζ)).\n\n  Lemma enum_inner_spec (δ' : M) ℓ extr atr c' oζ :\n    ξ (extr :tr[oζ]: c') (atr :tr[ℓ]: δ') → (δ', ℓ) ∈ enum_inner extr atr c' oζ.\n  Proof.\n    intros H. unfold enum_inner. rewrite elem_of_list_fmap.\n    exists (exist _ (δ', ℓ) H). split =>//. apply elem_of_enum.\n  Qed.\n\n  (* TODO: move *)\n  Fixpoint trace_map {A A' L L'} (sf: A → A') (lf: L -> L') (tr: finite_trace A L): finite_trace A' L' :=\n  match tr with\n  | trace_singleton x => trace_singleton $ sf x\n  | trace_extend tr' ℓ x => trace_extend (trace_map sf lf tr') (lf ℓ) (sf x)\n  end.\n\n  Fixpoint get_underlying_fairness_trace (M : FairModel) (LM: LiveModel Λ M) (ex : auxiliary_trace LM) :=\n  match ex with\n  | trace_singleton δ => trace_singleton (ls_under δ)\n  | trace_extend ex' (Take_step ρ _) δ => trace_extend (get_underlying_fairness_trace M LM ex') ρ (ls_under δ)\n  | trace_extend ex' _ _ => get_underlying_fairness_trace M LM ex'\n  end.\n\n  Definition get_role {M : FairModel} {LM: LiveModel Λ M} (lab: mlabel LM) :=\n  match lab with\n  | Take_step ρ _ => Some ρ\n  | _ => None\n  end.\n\n  Definition map_underlying_trace {M : FairModel} {LM: LiveModel Λ M} (aux : auxiliary_trace LM) :=\n    (trace_map (λ s, ls_under s) (λ lab, get_role lab) aux).\n\n  Program Definition enumerate_next extr (fmodtr: auxiliary_trace LM) c' oζ:\n    list (LM * @mlabel LM) :=\n    let δ1 := trace_last fmodtr in\n    '(s2, ℓ) ← (δ1.(ls_under), None) :: enum_inner extr (map_underlying_trace fmodtr) c' oζ;\n    d ← enumerate_dom_gsets' (dom δ1.(ls_fuel) ∪ live_roles _ s2);\n    fs ← enum_gmap_bounded' (live_roles _ s2 ∪ d) (max_gmap δ1.(ls_fuel) `max` LM.(lm_fl) s2);\n    ms ← enum_gmap_range_bounded' (live_roles _ s2 ∪ d) (locales_of_list c'.1);\n    let ℓ' := match ℓ with\n              | None => match oζ with\n                         Some ζ => Silent_step ζ\n                       | None => Config_step\n                       end\n              | Some ℓ => match oζ with\n                         | None => Config_step\n                         | Some ζ => Take_step ℓ ζ\n                         end\n              end in\n    mret ({| ls_under := s2;\n             ls_fuel := `fs;\n             (* ls_fuel_dom := proj2_sig fs; *) (* TODO: why this does not work?*)\n             ls_mapping := `ms ;\n          |}, ℓ').\n  Next Obligation.\n    intros ??????????. destruct fs as [? Heq]. rewrite /= Heq //. set_solver.\n  Qed.\n  Next Obligation.\n    intros ??????????. destruct fs as [? Heq]. destruct ms as [? Heq'].\n    rewrite /= Heq //.\n  Qed.\n\n  Lemma valid_state_evolution_finitary_fairness (φ: execution_trace Λ -> auxiliary_trace LM -> Prop) :\n    rel_finitary (valid_lift_fairness (λ extr auxtr, ξ extr (map_underlying_trace auxtr) ∧ φ extr auxtr)).\n  Proof.\n    rewrite /valid_lift_fairness.\n    intros ex atr [e' σ'] oζ.\n    eapply finite_smaller_card_nat.\n    simpl.\n    eapply (in_list_finite (enumerate_next ex atr (e',σ') oζ)).\n    intros [δ' ℓ] [[Hlbl [Htrans Htids]] [Hξ Hφ]].\n    unfold enumerate_next. apply elem_of_list_bind.\n    exists (δ'.(ls_under), match ℓ with Take_step l _ => Some l | _ => None end).\n    split; last first.\n    { destruct ℓ as [ρ tid' | |].\n      - inversion Htrans as [Htrans']. apply elem_of_cons; right.\n        by apply enum_inner_spec.\n      - apply elem_of_cons; left. f_equal. inversion Htrans as (?&?&?&?&?); done.\n      - apply elem_of_cons; right. inversion Htrans as (?&?). by apply enum_inner_spec. }\n    apply elem_of_list_bind. eexists (dom $ δ'.(ls_fuel)). split; last first.\n    { apply enumerate_dom_gsets'_spec. destruct ℓ as [ρ tid' | |].\n      - inversion Htrans as (?&?&?&?&?&?&?). intros ρ' Hin. destruct (decide (ρ' ∈ live_roles _ δ')); first set_solver.\n        destruct (decide (ρ' ∈ dom $ ls_fuel (trace_last atr))); first set_solver. set_solver.\n      - inversion Htrans as (?&?&?&?&?). set_solver.\n      - inversion Htrans as (?&?&?&?&?). done. }\n    apply elem_of_list_bind.\n    assert (Hfueldom: dom δ'.(ls_fuel) = live_roles M δ' ∪ dom (ls_fuel δ')).\n    { rewrite subseteq_union_1_L //. apply ls_fuel_dom. }\n    eexists (δ'.(ls_fuel) ↾ Hfueldom); split; last first.\n    { eapply enum_gmap_bounded'_spec; split =>//.\n      intros ρ f Hsome. destruct ℓ as [ρ' tid' | |].\n      - destruct (decide (ρ = ρ')) as [-> | Hneq].\n        + inversion Htrans as [? Hbig]. destruct Hbig as (Hmap&Hleq&?&Hlim&?&?).\n          destruct (decide (ρ' ∈ live_roles _ δ')).\n          * rewrite Hsome /= in Hlim.\n            assert (Hlive: ρ' ∈ live_roles _ δ') by set_solver.\n            specialize (Hlim Hlive). lia.\n          * unfold fuel_decr in Hleq.\n            apply elem_of_dom_2 in Hmap. rewrite ls_same_doms in Hmap.\n            pose proof Hsome as Hsome'. apply elem_of_dom_2 in Hsome'.\n            specialize (Hleq ρ' ltac:(done) ltac:(done)).\n            assert(must_decrease ρ' (Some ρ') (trace_last atr) δ' (Some tid')) as Hmd; first by constructor 3.\n            specialize (Hleq Hmd). rewrite Hsome /= in Hleq.\n            apply elem_of_dom in Hmap as [? Heq]. rewrite Heq in Hleq.\n            pose proof (max_gmap_spec _ _ _ Heq). simpl in *. lia.\n        + inversion Htrans as [? Hbig]. destruct Hbig as (Hmap&?&Hleq'&?&Hnew&?).\n          destruct (decide (ρ ∈ dom $ ls_fuel (trace_last atr))) as [Hin|Hnotin].\n          * assert (Hok: oleq (ls_fuel δ' !! ρ) (ls_fuel (trace_last atr) !! ρ)).\n            { unfold fuel_must_not_incr in *.\n              assert (ρ ∈ dom $ ls_fuel (trace_last atr)) by SS.\n              specialize (Hleq' ρ ltac:(done) ltac:(congruence)) as [Hleq'|Hleq'] =>//. apply elem_of_dom_2 in Hsome. set_solver. }\n            rewrite Hsome in Hok. destruct (ls_fuel (trace_last atr) !! ρ) as [f'|] eqn:Heqn; last done.\n            pose proof (max_gmap_spec _ _ _ Heqn). simpl in *. lia.\n          * assert (Hok: oleq (ls_fuel δ' !! ρ) (Some (LM.(lm_fl) δ'))).\n            { apply Hnew. apply elem_of_dom_2 in Hsome. set_solver. }\n            rewrite Hsome in Hok. simpl in Hok. lia.\n      - inversion Htrans as [? [? [Hleq [Hincl Heq]]]]. specialize (Hleq ρ).\n        assert (ρ ∈ dom $ ls_fuel (trace_last atr)) as Hin.\n        { apply elem_of_dom_2 in Hsome. set_solver. }\n        specialize (Hleq Hin ltac:(done)) as [Hleq|Hleq].\n        + rewrite Hsome in Hleq. destruct (ls_fuel (trace_last atr) !! ρ) as [f'|] eqn:Heqn. \n          * pose proof (max_gmap_spec _ _ _ Heqn). simpl in *.\n            rewrite Heqn in Hleq.\n            lia.\n          * simpl in *. rewrite Heqn in Hleq. done.\n        + apply elem_of_dom_2 in Hsome. set_solver.\n      - inversion Htrans as [? [? [Hleq [Hnew Hfalse]]]]. done. }\n    apply elem_of_list_bind.\n    assert (Hmappingdom: dom δ'.(ls_mapping) = live_roles M δ' ∪ dom (ls_fuel δ')).\n    { rewrite -Hfueldom ls_same_doms //. }\n    exists (δ'.(ls_mapping) ↾ Hmappingdom); split; last first.\n    { eapply enum_gmap_range_bounded'_spec; split=>//.\n      intros ρ' tid' Hsome. unfold tids_smaller in *.\n      apply locales_of_list_from_locale_from. eauto. }\n    rewrite elem_of_list_singleton; f_equal.\n    - destruct δ'; simpl. f_equal; apply ProofIrrelevance.\n    - destruct ℓ; simpl; destruct oζ =>//; by inversion Hlbl.\n      Unshelve.\n      + intros ??. apply make_decision.\n      + intros. apply make_proof_irrel.\n      + done.\n      + done.\n  Qed.\nEnd finitary.\n\nSection finitary_simple.\n  Context `{M: FairModel}.\n  Context `{Λ: language}.\n  Context `{LM: LiveModel Λ M}.\n  Context `{EqDecision M}.\n  Context `{EqDecision (locale Λ)}.\n\n  Context `{HPI0: forall s x, ProofIrrel ((let '(s', ℓ) := x in M.(fmtrans) s ℓ s'): Prop) }.\n\n  Variable model_finitary: forall s1, Finite { '(s2, ℓ) | M.(fmtrans) s1 ℓ s2 }.\n\n  Definition enum_inner_simple (s1: M): list (M * option M.(fmrole)) :=\n    map proj1_sig (@enum _ _ (model_finitary s1)).\n\n  Lemma enum_inner_spec_simple (s1 s2: M) ℓ:\n    M.(fmtrans) s1 ℓ s2 -> (s2, ℓ) ∈ enum_inner_simple s1.\n  Proof.\n    intros H. unfold enum_inner. rewrite elem_of_list_fmap.\n    exists (exist _ (s2, ℓ) H). split =>//. apply elem_of_enum.\n  Qed.\n\n  Program Definition enumerate_next_simple (δ1: LM) (oζ : olocale Λ) (c': cfg Λ):\n    list (LM * @mlabel LM) :=\n    '(s2, ℓ) ← (δ1.(ls_under), None) :: enum_inner_simple δ1.(ls_under);\n    d ← enumerate_dom_gsets' (dom δ1.(ls_fuel) ∪ live_roles _ s2);\n    fs ← enum_gmap_bounded' (live_roles _ s2 ∪ d) (max_gmap δ1.(ls_fuel) `max` LM.(lm_fl) s2);\n    ms ← enum_gmap_range_bounded' (live_roles _ s2 ∪ d) (locales_of_list c'.1);\n    let ℓ' := match ℓ with\n              | None => match oζ with\n                         Some ζ => Silent_step ζ\n                       | None => Config_step\n                       end\n              | Some ℓ => match oζ with\n                         | None => Config_step\n                         | Some ζ => Take_step ℓ ζ\n                         end\n              end in\n    mret ({| ls_under := s2;\n             ls_fuel := `fs;\n             (* ls_fuel_dom := proj2_sig fs; *) (* TODO: why this does not work?*)\n             ls_mapping := `ms ;\n          |}, ℓ').\n  Next Obligation.\n    intros ??????????. destruct fs as [? Heq]. rewrite /= Heq //. set_solver.\n  Qed.\n  Next Obligation.\n    intros ??????????. destruct fs as [? Heq]. destruct ms as [? Heq'].\n    rewrite /= Heq //.\n  Qed.\n\n  (* TODO: Derive this from the stronger version *)\n  Lemma valid_state_evolution_finitary_fairness_simple (φ: execution_trace Λ -> auxiliary_trace LM -> Prop) :\n    rel_finitary (valid_lift_fairness φ).\n  Proof.\n    intros extr auxtr [e' σ'] oζ.\n    eapply finite_smaller_card_nat.\n    eapply (in_list_finite (enumerate_next_simple (trace_last auxtr) oζ (e',σ'))).\n    intros [δ2 ℓ] [[Hlab [Htrans Hsmall]] ?].\n    unfold enumerate_next. apply elem_of_list_bind.\n    exists (δ2.(ls_under), match ℓ with Take_step l _ => Some l | _ => None end).\n    split; last first.\n    { destruct ℓ as [ρ tid' | |].\n      - inversion Htrans as [Htrans']. apply elem_of_cons; right. by apply enum_inner_spec_simple.\n      - apply elem_of_cons; left. f_equal. inversion Htrans as (?&?&?&?&?); done.\n      - apply elem_of_cons; right. inversion Htrans as (?&?). by apply enum_inner_spec_simple. }\n    apply elem_of_list_bind. eexists (dom $ δ2.(ls_fuel)). split; last first.\n    { apply enumerate_dom_gsets'_spec. destruct ℓ as [ρ tid' | |].\n      - inversion Htrans as (?&?&?&?&?&?&?). intros ρ' Hin. destruct (decide (ρ' ∈ live_roles _ δ2)); first set_solver.\n        destruct (decide (ρ' ∈ dom $ ls_fuel (trace_last auxtr))); first set_solver. set_solver.\n      - inversion Htrans as (?&?&?&?&?). set_solver.\n      - inversion Htrans as (?&?&?&?&?). done. }\n    apply elem_of_list_bind.\n    assert (Hfueldom: dom δ2.(ls_fuel) = live_roles M δ2 ∪ dom (ls_fuel δ2)).\n    { rewrite subseteq_union_1_L //. apply ls_fuel_dom. }\n\n    eexists (δ2.(ls_fuel) ↾ Hfueldom); split; last first.\n    { eapply enum_gmap_bounded'_spec; split =>//.\n      intros ρ f Hsome. destruct ℓ as [ρ' tid' | |].\n      - destruct (decide (ρ = ρ')) as [-> | Hneq].\n        + inversion Htrans as [? Hbig]. destruct Hbig as (Hmap&Hleq&?&Hlim&?&?).\n          destruct (decide (ρ' ∈ live_roles _ δ2)).\n          * rewrite Hsome /= in Hlim.\n            assert (Hlive: ρ' ∈ live_roles _ δ2) by set_solver.\n            specialize (Hlim Hlive). lia.\n          * unfold fuel_decr in Hleq.\n            apply elem_of_dom_2 in Hmap. rewrite ls_same_doms in Hmap.\n            pose proof Hsome as Hsome'. apply elem_of_dom_2 in Hsome'.\n            specialize (Hleq ρ' ltac:(done) ltac:(done)).\n            assert(must_decrease ρ' (Some ρ') (trace_last auxtr) δ2 (Some tid')) as Hmd; first by constructor 3.\n            specialize (Hleq Hmd). rewrite Hsome /= in Hleq.\n            apply elem_of_dom in Hmap as [? Heq]. rewrite Heq in Hleq.\n            pose proof (max_gmap_spec _ _ _ Heq). simpl in *. lia.\n        + inversion Htrans as [? Hbig]. destruct Hbig as (Hmap&?&Hleq'&?&Hnew&?).\n          destruct (decide (ρ ∈ dom $ ls_fuel (trace_last auxtr))) as [Hin|Hnotin].\n          * assert (Hok: oleq (ls_fuel δ2 !! ρ) (ls_fuel (trace_last auxtr) !! ρ)).\n            { unfold fuel_must_not_incr in *.\n              assert (ρ ∈ dom $ ls_fuel (trace_last auxtr)) by SS.\n              specialize (Hleq' ρ ltac:(done) ltac:(congruence)) as [Hleq'|Hleq'] =>//. apply elem_of_dom_2 in Hsome. set_solver. }\n            rewrite Hsome in Hok. destruct (ls_fuel (trace_last auxtr) !! ρ) as [f'|] eqn:Heqn; last done.\n            pose proof (max_gmap_spec _ _ _ Heqn). simpl in *. lia.\n          * assert (Hok: oleq (ls_fuel δ2 !! ρ) (Some (LM.(lm_fl) δ2))).\n            { apply Hnew. apply elem_of_dom_2 in Hsome. set_solver. }\n            rewrite Hsome in Hok. simpl in Hok. lia.\n      - inversion Htrans as [? [? [Hleq [Hincl Heq]]]]. specialize (Hleq ρ).\n        assert (ρ ∈ dom $ ls_fuel (trace_last auxtr)) as Hin.\n        { apply elem_of_dom_2 in Hsome. set_solver. }\n        specialize (Hleq Hin ltac:(done)) as [Hleq|Hleq].\n        + rewrite Hsome in Hleq. destruct (ls_fuel (trace_last auxtr) !! ρ) as [f'|] eqn:Heqn; last done.\n          pose proof (max_gmap_spec _ _ _ Heqn). simpl in *. lia.\n        + apply elem_of_dom_2 in Hsome. set_solver.\n      - inversion Htrans as [? [? [Hleq [Hnew Hfalse]]]]. done. }\n    apply elem_of_list_bind.\n    assert (Hmappingdom: dom δ2.(ls_mapping) = live_roles M δ2 ∪ dom (ls_fuel δ2)).\n    { rewrite -Hfueldom ls_same_doms //. }\n\n    exists (δ2.(ls_mapping) ↾ Hmappingdom); split; last first.\n    { eapply enum_gmap_range_bounded'_spec; split=>//.\n      intros ρ' tid' Hsome. unfold tids_smaller in *.\n      apply locales_of_list_from_locale_from. eauto. }\n    rewrite elem_of_list_singleton; f_equal.\n    - destruct δ2; simpl. f_equal; apply ProofIrrelevance.\n    - destruct ℓ; simpl; destruct oζ =>//; by inversion Hlab.\n      Unshelve.\n      + intros ??. apply make_decision.\n      + intros. apply make_proof_irrel.\n      + done.\n      + done.\n  Qed.\nEnd finitary_simple.\n\n(* TODO: Why do we need [LM] explicit here? *)\nDefinition live_rel `(LM: LiveModel Λ M) `{Countable (locale Λ)}\n           (ex : execution_trace Λ) (aux : auxiliary_trace LM) :=\n  live_tids (LM:=LM) (trace_last ex) (trace_last aux).\n\nDefinition sim_rel `(LM: LiveModel Λ M) `{Countable (locale Λ)}\n           (ex : execution_trace Λ) (aux : auxiliary_trace LM) :=\n  valid_state_evolution_fairness ex aux ∧ live_rel LM ex aux.\n\nDefinition sim_rel_with_user `(LM: LiveModel Λ M) `{Countable (locale Λ)}\n           (ξ : execution_trace Λ -> finite_trace M (option (fmrole M)) -> Prop)\n  (ex : execution_trace Λ) (aux : auxiliary_trace LM) :=\n  sim_rel LM ex aux ∧ ξ ex (map_underlying_trace aux).\n\n(* TODO: Maybe redefine [sim_rel_with_user] in terms of [valid_lift_fairness] *)\nLemma valid_lift_fairness_sim_rel_with_user `{LM:LiveModel Λ Mdl}\n      `{Countable (locale Λ)}\n      (ξ : execution_trace Λ → finite_trace Mdl (option $ fmrole Mdl) →\n           Prop) extr atr :\n  valid_lift_fairness\n    (λ extr auxtr, ξ extr (map_underlying_trace (LM:=LM) auxtr) ∧\n                   live_rel LM extr auxtr) extr atr ↔\n  sim_rel_with_user LM ξ extr atr.\nProof. split; [by intros [Hvalid [Hlive Hξ]]|by intros [[Hvalid Hlive] Hξ]]. Qed.\n\nLemma rel_finitary_sim_rel_with_user_ξ `{LM:LiveModel Λ Mdl}\n      `{Countable (locale Λ)} ξ :\n  rel_finitary ξ → rel_finitary (sim_rel_with_user LM ξ).\nProof.\n  intros Hrel.\n  eapply rel_finitary_impl.\n  { intros ex aux. by eapply valid_lift_fairness_sim_rel_with_user.\n    (* TODO: Figure out if these typeclass subgoals should be resolved locally *)\n    Unshelve.\n    - intros ??. apply make_decision.\n    - intros ??. apply make_decision. }\n  by eapply valid_state_evolution_finitary_fairness.\n  Unshelve.\n  - intros ??. apply make_proof_irrel.\nQed.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/fairness/fairness_finiteness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.22729260619650735}}
{"text": "Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq div.\nRequire Import prime fintype paths finfun ssralg bigops finset.\nRequire Import groups morphisms group_perm automorphism normal commutators.\nRequire Import action cyclic center pgroups sylow gprod schurzass hall.\nRequire Import coprime_act nilpotent coprime_comm maximal.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nImport GroupScope.\n\nSection Props.\n\nVariables (gT : finGroupType).\nImplicit Types G H K : {group gT}.\n\nLemma coprime_cent_Phi : forall H G,\n  coprime #|H| #|G| -> [~: H, G] \\subset 'Phi(G) ->  H \\subset 'C(G).\nAdmitted.\n\nLemma solvable_self_cent_Fitting : forall G,\n  solvable G -> 'C_G('F(G)) \\subset 'F(G).\nAdmitted.\n\nEnd Props.\n\nTheorem three_dot_four : forall k (gT : finGroupType) (G K R V : {group gT}),\n  solvable G -> odd #|G| ->\n  K <| G -> Hall G K -> R \\in [complements to K in G] -> prime #|R| ->\n  k.-abelem V -> G \\subset 'N(V) -> ~~ (k %| #|G|) ->\n  'C_V(R) = 1-> [~: R, K] \\subset 'C_K(V).\nAdmitted.\n\nTheorem three_dot_five : forall k (gT : finGroupType) (G K R V : {group gT}),\n  solvable G ->\n  K <| G -> R \\in [complements to K in G] -> prime #|R| -> 'C_K(R) = 1->\n  k.-abelem V -> G \\subset 'N(V) -> ~~ (k %| #|G|) ->\n  #|'C_V(R)| = k -> K^`(1) \\subset 'C_K(V).\nAdmitted.\n\nTheorem three_dot_six : forall (gT : finGroupType) (G H R R0 : {group gT}),\n    solvable G -> odd #|G| ->\n    H <| G -> Hall G H -> R \\in [complements to H in G] ->\n    R0 \\subset R -> prime #|R0| -> Zgroup 'C_H(R0) ->\n  forall p, prime p -> p.-length_1 [~: H, R].\nProof.\nmove=> gT G; move: {2}_.+1 (ltnSn #|G|) => n.\nelim: n gT G => // n IHn gT G; rewrite ltnS => leGn H R R0.\nmove=> solG oddG nHG hallH compH_R sR0R.\nmove oR0: #|R0| => r pr_r ZCHR0 p pr_p.\nhave sRG: R \\subset G by case/complP: compH_R => _ <-; exact: mulG_subr.\ncase/complP: compH_R => trivgHR eqHR_G; case/andP: (hallH) => sHG coHH'.\nhave{coHH'} coHR: coprime #|H| #|R|.\n  by have:= coHH'; rewrite -divgS -eqHR_G ?mulG_subl // TI_cardMg ?mulKn.\nhave nHR: R \\subset 'N(H) := subset_trans sRG (normal_norm nHG).\nhave IHG: forall H1 R1 : {group gT},\n  H1 \\subset H -> H1 * R1 \\subset 'N(H1) -> R0 \\subset R1 -> R1 \\subset R ->\n  (#|H1| < #|H|) || (#|R1| < #|R|) -> p.-length_1 [~: H1, R1].\n- move=> H1 R1 sH1 nH1 sR01 sR1 ltG1.\n  move defHR1: (H1 <*> R1)%G => G1; have{defHR1} defG1: G1 :=: H1 * R1.\n    have nH1R: R1 \\subset 'N(H1) := subset_trans (mulG_subr H1 R1) nH1.\n    by rewrite -defHR1 /= mulgenC norm_mulgenEl // normC.\n  have coHR1: coprime #|H1| #|R1|.\n    rewrite -(LaGrange sH1) -(LaGrange sR1) coprime_mull coprime_mulr in coHR.\n    by case/andP: coHR; case/andP.\n  have oG1: #|G1| = (#|H1| * #|R1|)%N by rewrite defG1 coprime_cardMg.\n  have ltG1n: #|G1| < n.\n    have:= leqif_mul (leqif_geq (subset_leq_card sH1))\n                     (leqif_geq (subset_leq_card sR1)).\n    rewrite -oG1 -coprime_cardMg // eqHR_G eqn0Ngt ltn_0group /= => leG1.\n    by apply: leq_trans leGn; rewrite ltn_neqAle !leG1 andbT negb_and -!ltnNge.\n  have sG1G: G1 \\subset G.\n    by rewrite defG1 mul_subG // (subset_trans sH1, subset_trans sR1).\n  have solG1: solvable G1 := solvableS sG1G solG.\n  have oddG1: odd #|G1|.\n    move: oddG; do 2!rewrite -[odd _]negbK -dvdn2; apply: contra.\n    move/dvdn_trans; apply; exact: cardSg.\n  have nHG1: H1 <| G1 by rewrite /(H1 <| _) defG1 mulG_subl.\n  have hallH1: Hall G1 H1.\n    by rewrite /Hall -divgS normal_sub // oG1 mulKn.\n  have complR1: R1 \\in [complements to H1 in G1].\n    by apply/complP; rewrite coprime_TIg.\n  apply: IHn complR1 sR01 _ _ p pr_p => //; first by rewrite oR0.\n  exact: ZgroupS (setSI _ sH1) ZCHR0.\nwithout loss defHR: / [~: H, R] = H.\n  have:= nHR; rewrite -commg_subr commGC => sHR_R.\n  have:= sHR_R; rewrite subEproper; case/predU1P=> [-> -> //|s'HR_H _].\n  rewrite commGAA //; last exact: solvableS solG.\n  apply: IHG => //; last by rewrite proper_card.\n  apply: subset_trans (normal_norm (commg_normal H R)).\n  by rewrite mulgenC norm_mulgenEl // (normC nHR) mulSg.\nhave{IHn trivgHR hallH} IHquo: forall X : {group gT},\n  X :!=: 1 -> X \\subset H -> G \\subset 'N(X) -> p.-length_1 (H / X).\n- move=> X ntX sXH nXG; have nXH := subset_trans sHG nXG.\n  have nXR := subset_trans sRG nXG; have nXR0 := subset_trans sR0R nXR.\n  rewrite -defHR quotientE morphimR // -!quotientE.\n  have ltG'n: #|G / X| < n.\n    apply: leq_trans leGn; rewrite card_quotient //.\n    rewrite -[#|G : X|]mul1n -(LaGrange (subset_trans sXH sHG)).\n    by rewrite ltn_pmul2r // ltnNge -trivg_card_le1.\n  have solG': solvable (G / X) by exact: quotient_sol.\n  have oddG': odd #|G / X|.\n    move: oddG; rewrite !odd_2'nat; exact: morphim_pgroup.\n  have nHG': H / X <| G / X by exact: morphim_normal.\n  have hallH': Hall (G / X) (H / X) by exact: morphim_Hall.\n  have compR': (R / X)%G \\in [complements to H / X in G / X].\n    apply/complP; split; last by rewrite -morphimMl ?eqHR_G.\n    by rewrite -morphimGI ?ker_coset // trivgHR morphim1.\n  have sR0R': R0 / X \\subset R / X by exact: morphimS.\n  have pr_R0X: prime #|R0 / X|.\n    have trXR0: X :&: R0 = 1 by apply/trivgP; rewrite -trivgHR setISS.\n    by rewrite card_quotient // -divgI setIC trXR0 cards1 divn1 oR0.\n  apply: IHn compR' sR0R' pr_R0X _ _ pr_p => //.\n  have coHR0: coprime #|H| #|R0|.\n    by rewrite -(LaGrange sR0R) coprime_mulr in coHR; case/andP: coHR.\n  rewrite -coprime_quotient_cent_weak ?morphim_Zgroup //; first exact/andP.\n  exact: solvableS solG.\nrewrite defHR.\nwithout loss Op'_H: / 'O_p^'(H) = 1.\n  case: (eqVneq 'O_p^'(H) 1) => [_ -> // | ntO _].\n  suffices: p.-length_1 (H / 'O_p^'(H)).\n    by rewrite p'quo_plength1 ?pcore_normal ?pcore_pgroup.\n  apply: IHquo => //; first by rewrite normal_sub ?pcore_normal.\n  by rewrite normal_norm // (char_normal_trans (pcore_char _ _)).\nmove defV: 'F(H)%G => V.\nhave charV: V \\char H by rewrite -defV Fitting_char.\nhave nVG: G \\subset 'N(V) by rewrite normal_norm ?(char_normal_trans charV).\nhave sVH: V \\subset H by rewrite normal_sub ?char_normal.\nhave defVp: V :=: 'O_p(H).\n  rewrite -defV -(nilpotent_pcoreC p (Fitting_nil H)) // p_core_Fitting.\n  by rewrite ['O_p^'('F(H))](trivgP _) ?dprodg1 // -Op'_H pcore_Fitting.\nhave pV: p.-group V by rewrite defVp pcore_pgroup.\nhave sCV_V: 'C_H(V) \\subset V.\n  rewrite -defV solvable_self_cent_Fitting //; exact: solvableS solG.\nwlog abV: / p.-abelem V.\n  move/implyP; rewrite implybE -trivg_Phi //; case/orP=> // ntPhi.\n  have chPhi: 'Phi(V) \\char H := char_trans (Phi_char _) charV.\n  have nPhiH := char_normal chPhi; have sPhiH := normal_sub nPhiH.\n  have{chPhi} nPhiG: G \\subset 'N('Phi(V)).\n    exact: normal_norm (char_normal_trans chPhi nHG).\n  rewrite -(pquo_plength1 nPhiH) 1?IHquo //.\n    exact: pgroupS (Phi_sub _) pV.\n  have: 'O_p^'(H / 'Phi(V)) <| H / 'Phi(V) by exact: pcore_normal.\n  case/(inv_quotientN _) => //= W defW sPhiW nWH.\n  have p'Wb: p^'.-group (W / 'Phi(V)) by rewrite -defW; exact: pcore_pgroup.\n  suffices pW: p.-group W.\n    rewrite defW; apply: card1_trivg (pnat_1 _ p'Wb); exact: morphim_pgroup.\n  apply/pgroupP=> q pr_q; case/Cauchy=> // x Wx oxq; apply/idPn=> /= neqp.\n  suff: <[x]> \\subset V.\n    rewrite gen_subG sub1set => Vx.\n    by move/pgroupP: pV neqp => /= -> //; rewrite -oxq order_dvd_g.\n  apply: subset_trans sCV_V; rewrite subsetI cycle_subG; apply/andP; split.\n    apply: subsetP Wx; exact: normal_sub.\n  have coxV: coprime #[x] #|V|.\n    by rewrite oxq coprime_sym (pnat_coprime pV) // pnatE.\n  apply: coprime_cent_Phi coxV _.\n  have: W :&: V \\subset 'Phi(V); last apply: subset_trans.\n    rewrite -quotient_sub1; last first.\n      by rewrite subIset // orbC normal_norm // char_normal // Phi_char.\n    rewrite (quotientIG _ (Phi_sub V)) setIC coprime_TIg //.\n    by rewrite  (@pnat_coprime p) // [_.-nat _]morphim_pgroup.\n  case/andP: nWH => sWH nWH.\n  rewrite subsetI andbC commg_subr cycle_subG; apply/andP; split.\n    by apply: subsetP Wx; apply: subset_trans (subset_trans sWH _) nVG.\n  move: nWH; rewrite -commg_subr commGC; apply: subset_trans.\n  by rewrite commgSS // cycle_subG //.\nhave{sCV_V} eqVC: V :=: 'C_H(V).\n  by apply/eqP; rewrite eqEsubset sCV_V subsetI andbT sVH; case/p_abelemP: abV.\nwlog{IHquo} nondecV:  / forall N1 N2,\n      N1 \\x N2 = V -> G \\subset 'N(N1) :&: 'N(N2) -> N1 = 1 \\/ N1 = V.\n  pose decV := [pred N | [&& N.1 \\x N.2 == V, G \\subset 'N(N.1) :&: 'N(N.2),\n                             N.1 != 1 & N.2 != 1]].\n  case: (pickP decV) => [[A1 A2 /=] | trN12]; last first.\n    apply=> N1 N2 defN nNG; move/(_ (N1, N2)): trN12 => /=.\n    rewrite -defN eqxx {}nNG /= -negb_or; case/pred2P=> ->; [by left | right].\n    by rewrite dprodg1.\n  case: eqP => //=; case/dprodP=> [[N1 N2 -> ->{A1 A2}] defN _ trN12].\n  have [sN1 sN2]: N1 \\subset H /\\ N2 \\subset H.\n    apply/andP; rewrite -subUset (subset_trans _ sVH) // -defN.\n    by rewrite subUset mulG_subl mulG_subr.\n  case/and3P=> nNG ntN1 ntN2 _; have [nN1 nN2]: N1 <| H /\\ N2 <| H.\n    by apply/andP; rewrite /normal sN1 sN2 /= -subsetI (subset_trans sHG).\n  rewrite subsetI in nNG; case/andP: nNG => nN1G nN2G.\n  by rewrite -(quo2_plength1 pr_p nN1 nN2) ?trN12 ?IHquo.\nhave: 'F(H / V) <| G / V.\n  exact: char_normal_trans (Fitting_char _) (morphim_normal _ _).\ncase/(inv_quotientN _) => [| /= U defU sVU nUG].\n  by apply/andP; rewrite (subset_trans sVH).\ncase/andP: nUG => sUG nUG; have nUR := subset_trans sRG nUG.\nhave sUH: U \\subset H.\n  have: U / V \\subset H / V by rewrite -defU normal_sub ?Fitting_normal.\n  by rewrite morphimSGK ?ker_coset // (subset_trans sUG).\nhave: exists2 K : {group gT}, p^'.-Hall(U) K & R \\subset 'N(K).\n  apply: coprime_hall_exists => //; last exact: (solvableS sUG).\n  by rewrite -(LaGrange sUH) coprime_mull in coHR; case/andP: coHR.\ncase=> K hallK nKR; have [sKU _]:= andP hallK.\nhave p'K: p^'.-group K by exact: pHall_pgroup hallK.\nhave p'Ub: p^'.-group 'F(H / V).\n  rewrite -['F(H / V)](nilpotent_pcoreC p (Fitting_nil _)) /=.\n  by rewrite p_core_Fitting defVp trivg_pcore_quotient dprod1g pcore_pgroup.\nhave nVU := subset_trans (subset_trans sUH sHG) nVG.\nhave defVK: U :=: V * K.\n  have nVK := subset_trans sKU nVU.\n  apply/eqP; rewrite eqEsubset mul_subG //= andbT -quotientSK //.\n  rewrite subEproper eq_sym eqEcard.\n  have: p^'.-Hall(U / V) (K / V) by exact: morphim_pHall.\n  by case/pHallP=> -> ->; rewrite part_pnat ?leqnn //= -defU.\nhave sylV: p.-Sylow(U) V.\n  have coVK: coprime #|V| #|K| := pnat_coprime pV p'K.\n  by rewrite /pHall sVU [_.-group _]pV -card_quotient // -defU.\nhave defH: H :=: V * 'N_H(K).\n  have nUH: U <| H by apply/andP; rewrite (subset_trans sHG).\n  rewrite -{1}(Hall_Frattini_arg _ nUH hallK); last exact: solvableS solG.\n  by rewrite defVK -mulgA [K * _]mulSGid // subsetI normG (subset_trans sKU).\nhave [P sylP nPR]:\n  exists2 P : {group gT}, p.-Sylow('N_H(K)) P & R \\subset 'N(P).\n+ have sNH: 'N_H(K) \\subset H by exact: subsetIl.\n  apply: coprime_hall_exists.\n  - by apply/normsP=> x Rx /=; rewrite conjIg -normJ !(normsP _ _ Rx).\n  - by move: coHR; rewrite -(LaGrange sNH) coprime_mull; case/andP.\n  apply: solvableS solG; exact: subset_trans sHG.\nhave sPN: P \\subset 'N_H(K) by case/andP: sylP.\nhave [sPH nKP]: P \\subset H /\\ P \\subset 'N(K) by apply/andP; rewrite -subsetI.\nhave nVH := subset_trans sHG nVG; have nVP := subset_trans sPH nVH.\nhave sylVP: p.-Sylow(H) (V * P).\n  have defVP: V * P = V <*> P by rewrite mulgenC -normC ?norm_mulgenEl.\n  rewrite defVP pHallE /= -defVP mul_subG //= defVP.\n  rewrite -(LaGrange sVH) partn_mul ?ltn_0mul ?ltn_0group //=.\n  have: V \\subset V <*> P by rewrite -defVP mulG_subl.\n  move/LaGrange <-; rewrite part_pnat // eqn_pmul2l // /=.\n  rewrite -!card_quotient //; last by rewrite gen_subG subUset normG.\n  rewrite -defVP defH !quotient_mulgr.\n  have: p.-Sylow('N_H(K) / V) (P / V) by exact: morphim_pHall.\n  by case/pHallP=> _ ->.\ncase: (eqVneq [~: K, P] 1) => [trKP|ntKP].\n  suffices sylVH: p.-Sylow(H) V.\n    rewrite p_elt_gen_length1 // (_ : p_elt_gen p H = V).\n      rewrite /pHall pcore_sub pcore_pgroup /= pnatNK.\n      apply: pnat_dvd pV; exact: dvdn_indexg.\n    rewrite -(genGid V); congr <<_>>; apply/setP=> x; rewrite inE.\n    apply/andP/idP=> [[Hx p_x] | Vx].\n      by rewrite (mem_normal_Hall sylVH) // /normal sVH.\n    split; [exact: (subsetP sVH) | exact: mem_p_elt Vx].\n  suffices sPV: P \\subset V by rewrite mulGSid in sylVP.\n  have sol_HV : solvable (H / V).\n    by apply: quotient_sol; apply: (solvableS sHG).\n  have qPV: P / V \\subset 'C_(H / V)('F(H / V)).\n    rewrite defU subsetI; apply/andP; split; first by apply:morphimS.\n    rewrite defVK quotient_mulgr; apply: quotient_cents2r.\n    by rewrite commGC trKP sub1G.\n  have sPU: P \\subset U.\n    rewrite defVK -quotientSK // -(quotient_mulgr _ K) -defVK -defU.\n    exact: subset_trans qPV (solvable_self_cent_Fitting sol_HV).\n  rewrite (subset_normal_Hall _ sylV); last exact/andP.\n  by rewrite /psubgroup ?sPU (pHall_pgroup sylP).\nhave{sylVP} dp: [~: V, K] \\x 'C_V(K) :=: V.\n  apply: sym_eq; apply: comm_center_dir_prod; last by case/p_abelemP: abV.\n    exact: subset_trans sKU nVU.\n  exact: pnat_coprime pV p'K.\nhave trVeq: 'C_V(K) = 1 \\/ 'C_V(K) = V.\n  apply: (nondecV _  [~: V, K]); first by rewrite dprodC.\n  rewrite -eqHR_G defH -mulgA mul_subG //.\n    by rewrite subsetI commg_norml cents_norm // centsC {1}eqVC setIAC subsetIr.\n  have: 'N_H(K) * R \\subset 'N_G(K) by rewrite mul_subG ?setSI // subsetI sRG.\n  move/subset_trans; apply; apply/subsetP=> x; case/setIP=> Gx nKx.\n  rewrite 3!inE conjIg -centJ /= -{1}[[~:V, K]]setTI -morphim_conj.\n  rewrite morphimR ?subsetT // !morphim_conj !setTI.\n  by rewrite (normP nKx) (normsP nVG) ?subxx.\nhave{sKU sUH} sKH: K \\subset H by exact: subset_trans sKU sUH.\nhave{trVeq dp} [Vcomm trCVK]: [~: V, K] = V /\\ 'C_V(K) = 1.\n  case trVeq=> [trC | eqC]; first by rewrite -{2}dp // trC dprodg1.\n  case/eqP: ntKP; rewrite card1_trivg ?comm1G ?eqxx // (pnat_1 _ p'K) //.\n  by apply: pgroupS pV; rewrite eqVC subsetI sKH centsC -eqC subsetIr.\nhave eqcn: 'N_V(K) = 'C_V(K).\n  apply: coprime_norm_cent (pnat_coprime pV p'K).\n  by rewrite -commg_subr commGC -{2}Vcomm subxx.\nhave trVN: V :&: 'N_H(K) = 1 by rewrite setIA (setIidPl sVH) eqcn.\nhave trVP: V :&: P = 1.\n  by apply/trivgP; rewrite -trVN setIS // ?(subset_trans sPN).\nhave nVN: 'N_H(K) \\subset 'N(V) by rewrite (subset_trans _ nVH) ?subsetIl.\nhave defK: K :=: 'F('N_H(K)).\n  have isoV: 'injm (restrm nVN (coset V)).\n    by rewrite ker_restrm ker_coset setIC trVN.\n  have sKN: K \\subset 'N_H(K) by rewrite subsetI sKH normG.\n  rewrite -['N_H(K)](invm_dom isoV) -injm_Fitting ?injm_invm //=.\n  rewrite {2}morphim_restrm setIid -quotientE -quotient_mulgr -defH defU.\n  rewrite defVK quotient_mulgr -{10}(setIidPr sKN) quotientE.\n  by rewrite -(morphim_restrm nVN) morphim_invm.\nhave sCKK: 'C_H(K) \\subset K.\n  rewrite {2}defK; apply: subset_trans (solvable_self_cent_Fitting _).\n    by rewrite -defK subsetI subsetIr setIS // cent_sub.\n  by apply: solvableS (solvableS sHG solG); apply: subsetIl.\nhave{nVN} ntKR0: [~: K, R0] != 1.\n  rewrite (sameP eqP commG1P); apply: contra ntKP => cKR0.\n  have Z_K: Zgroup K by apply: ZgroupS ZCHR0; rewrite subsetI sKH.\n  have cycK: cyclic K by rewrite nil_Zgroup_cyclic // defK Fitting_nil.\n  have AcycK : abelian (Aut K).\n    case/cyclicP: cycK => x ->; exact: aut_cycle_commute.\n  have sNR_K: [~: 'N_H(K), R] \\subset K.\n    apply: subset_trans sCKK; rewrite subsetI; apply/andP; split.\n      apply: subset_trans (commSg R (subsetIl _ _)) _.\n      by rewrite commGC commg_subr.\n    suff: 'N(K)^`(1) \\subset 'C(K).\n      by apply: subset_trans; rewrite commgSS ?subsetIr.\n    rewrite -ker_conj_aut ker_trivg_morphim comm_subG // morphimR //.\n    have sjK_AK: conj_aut K @* 'N(K) \\subset Aut K.\n      apply/subsetP=> a; case/imsetP=> f _ ->; exact: Aut_aut.\n    by rewrite -(commG1P AcycK) commgSS.\n  suff sPV: P \\subset V by rewrite -(setIidPr sPV) trVP commG1.\n  have pPV: p.-group (P / V) by exact: morphim_pgroup (pHall_pgroup sylP).\n  rewrite -quotient_sub1 // subG1 trivg_card1 (pnat_1 pPV _) //.\n  have: p^'.-group (K / V) by exact: morphim_pgroup p'K.\n  apply: pgroupS; apply: subset_trans (morphimS _ sNR_K).\n  have nVR: R \\subset 'N(V) by exact: subset_trans nVG.\n  rewrite morphimR // -quotientE -quotient_mulgr -defH -morphimR ?morphimS //.\n  by rewrite defHR.\nhave nKR0: R0 \\subset 'N(K) by exact: subset_trans nKR.\nhave sKR0_G : K <*> R0 \\subset G.\n  by rewrite gen_subG subUset (subset_trans sKH) ?(subset_trans sR0R).\nhave nV_KR0: K <*> R0 \\subset 'N(V) by exact: subset_trans nVG.\nhave: K :|: R0 \\subset K <*> R0 by rewrite -gen_subG subxx.\nrewrite subUset; case/andP=> sK_KR0 sR0_KR0.\nhave solKR0: solvable (K <*> R0) by exact: solvableS solG.\nhave coK_R0: coprime #|K| #|R0|.\n  have:= coHR; rewrite -(LaGrange sKH) -(LaGrange sR0R).\n  by rewrite coprime_mull coprime_mulr -andbA; case/andP.\nhave oKR0: #|K <*> R0| = (#|K| * #|R0|)%N.\n  by rewrite norm_mulgenEr // coprime_cardMg.\nhave r'K: r^'.-group K.\n  apply/pgroupP=> q pr_q dv_qK; apply/eqP=> def_q.\n  by rewrite oR0 coprime_sym prime_coprime // -def_q dv_qK in coK_R0.\nhave rR0: r.-group R0 by by rewrite /pgroup oR0 pnat_id // inE /= eqxx.\nhave hallK_R0: r^'.-Hall(K <*> R0) K.\n  by rewrite /pHall sK_KR0 r'K -divgS // pnatNK oKR0 mulKn.\nhave hallR0_K: r.-Sylow(K <*> R0) R0.\n  by rewrite /pHall sR0_KR0 rR0 -divgS // oKR0 mulnK.\nhave trCKR0_V: 'C_(K <*> R0)(V) = 1.\n  have nC_KR0: 'C_(K <*> R0)(V) <| K <*> R0.\n    rewrite /(_ <| _) subsetIl normsI ?normG //.\n    by rewrite (subset_trans nV_KR0) ?cent_norm.\n  have hallCK: r^'.-Hall('C_(K <*> R0)(V)) 'C_K(V).\n    rewrite -{2}(setIidPl sK_KR0) -setIA; exact: HallSubnormal hallK_R0.\n  have hallCR0: r.-Sylow('C_(K <*> R0)(V)) 'C_R0(V).\n    rewrite -{2}(setIidPl sR0_KR0) -setIA; exact: HallSubnormal hallR0_K.\n  have sC_R0: 'C_(K <*> R0)(V) \\subset R0.\n    apply/setIidPr; apply/eqP; rewrite setIA (setIidPl sR0_KR0) //=.\n    rewrite eqEcard -[#|'C_(K <*> R0)(V)|](partnC r) ?ltn_0group //.\n    case/pHallP: hallCR0 => -> <-; case/pHallP: hallCK => _ <-.\n    rewrite -{2}(muln1 #|_|) leq_mul // -trivg_card_le1 -subG1 -trVN.\n    rewrite /= -{1}(setIidPl sKH) -setIA -eqVC setIC setIS //.\n    by rewrite subsetI sKH normG.\n  have:= cardSg sC_R0; rewrite oR0.\n  case: (primeP pr_r) => _ dv_r; move/dv_r; rewrite -trivg_card1 /=.\n  case/orP; move/eqP=> // oCr.\n  case/negP: ntKR0; rewrite -subG1 -(coprime_TIg coK_R0) subsetI.\n  rewrite commg_subl commg_subr nKR0 (subset_trans sK_KR0) //.\n  rewrite -{2}(('C_(K <*> R0)(V) =P R0) _) ?normal_norm //.\n  by rewrite eqEcard sC_R0 oCr /= oR0.\nhave oCVR0: #|'C_V(R0)| = p.\n  case: (eqVneq 'C_V(R0) 1) => [trCVR0 | ntCVR0].\n    case/negP: ntKR0; rewrite -subG1/= commGC.\n    have <-: 'C_K(V) = 1 by apply/trivgP; rewrite -trCKR0_V setSI.\n    apply: three_dot_four abV nV_KR0 _ trCVR0 => //=.\n    - move: oddG; do 2!rewrite -[odd _]negbK -dvdn2; apply: contra.\n      move/dvdn_trans; apply; exact: cardSg.\n    - by rewrite /(K <| _) sK_KR0 gen_subG subUset normG.\n    - exact: (pHall_Hall hallK_R0).\n    - by apply/complP; rewrite coprime_TIg //= norm_mulgenEr.\n    - by rewrite oR0.\n    rewrite oKR0 -prime_coprime // coprime_mulr.\n    rewrite (pnat_coprime _ p'K) ?pnat_id //=.\n    move: coHR; rewrite -(LaGrange sPH) -(LaGrange sR0R).\n    rewrite coprime_mull coprime_mulr -andbA andbC oR0; case/andP=> _.\n    case/p_natP: (pHall_pgroup sylP) => // [[trP|i ->]].\n      by case/negP: ntKP; rewrite (card1_trivg trP) commG1.\n    by rewrite coprime_pexpl.\n  have: cyclic 'C_V(R0).\n    have: Sylow 'C_V(R0) 'C_V(R0); last apply/implyP.\n      apply/SylowP; exists p => //.\n      rewrite /pHall subxx indexgg andbT.\n      apply: pgroupS pV; exact: subsetIl.\n    have: Zgroup 'C_V(R0) by apply: ZgroupS ZCHR0; exact: setSI.\n    move/forallP; exact.\n  case/cyclicP=> x defC; rewrite defC.\n  have: #[x] %| p.\n    rewrite order_dvd; apply/eqP.\n    have:= cycle_id x; rewrite -defC setIC; case/setIP=> _.\n    by case/p_abelemP: abV => // _; exact.\n  case/primeP: pr_p => _ pr_p; move/pr_p; case/orP; move/eqnP=> // ox1.\n  by rewrite trivg_card1 /= defC [#|_|]ox1 in ntCVR0.\nhave trCP_R0: 'C_P(R0) = 1.\n  have pP := pHall_pgroup sylP; apply: card1_trivg.\n  have: p.-group 'C_P(R0) by apply: pgroupS pP; exact: subsetIl.\n  case/p_natP=> // [[-> //| i oC]].\n  have {i oC}: p %| #|'C_P(R0)| by rewrite oC dvdn_mulr.\n  case/Cauchy=> // x Cx oxp.\n  suff x1: <[x]> = 1 by rewrite -oxp /order x1 cards1 in pr_p.\n  apply/trivgP; rewrite -trVP subsetI andbC cycle_subG /=.\n  apply/andP; split; first by case/setIP: Cx.\n  suff <-: 'C_V(R0) = <[x]> by rewrite subsetIl.\n  have: cyclic 'C_(P <*> V)(R0).\n    have: Sylow 'C_(P <*> V)(R0) 'C_(P <*> V)(R0); last apply/implyP.\n      apply/SylowP; exists p => //.\n      rewrite /pHall subxx indexgg andbT.\n      suff: p.-group (P <*> V) by apply: pgroupS; exact: subsetIl.\n      have: p.-nat (#|P| * #|V|)%N by rewrite pnat_mul //; exact/andP.\n      by rewrite norm_mulgenEl // mul_cardG pnat_mul //; case/andP.\n    suff: Zgroup 'C_(P <*> V)(R0) by move/forallP; exact.\n    by apply: ZgroupS ZCHR0; rewrite setSI // gen_subG subUset sPH.\n  case/cyclicP=> y defC; apply: congr_group.\n  have y_x: x \\in <[y]>.\n    by apply: subsetP Cx; rewrite -defC setSI // sub_gen // subsetUl.\n  have: p %| #[y] by rewrite -oxp order_dvd_g.\n  move/cycle_sub_group; set Cy1 := <[_]>%G => defCy1.\n  have ->: <[x]>%G = Cy1.\n    apply/set1P; rewrite -defCy1 inE cycle_subG y_x /=; exact/eqP.\n  by apply/set1P; rewrite -defCy1 inE oCVR0 -defC setSI //= sub_gen ?subsetUr.\nhave defP: P :=: [~: P, R0].\n  move: coHR; rewrite -(LaGrange sPH) -(LaGrange sR0R).\n  rewrite coprime_mull coprime_mulr -andbA andbC; case/andP=> _.\n  move/comm_center_prod=> defP; rewrite {1}defP ?(subset_trans sR0R) //.\n    by rewrite trCP_R0 mulg1.\n  apply: solvableS solG; exact: subset_trans sHG.\nhave{IHG} IHG: forall X : {group gT},\n  P <*> R0 \\subset 'N(X) -> X \\subset K ->\n  (#|V <*> X <*> P| < #|H|) || (#|R0| < #|R|) -> [~: X, P] = 1.\n- move=> X nX_PR0 sXK ltX_G; apply/trivgP.\n  have sXH: V <*> X <*> P \\subset H.\n    rewrite gen_subG subUset sPH andbT gen_subG subUset sVH /=.\n    exact: subset_trans sKH.\n  have nXR0: R0 \\subset 'N(V <*> X <*> P).\n    rewrite mulgenC mulgenA norms_mulgen //.\n      by rewrite (subset_trans sR0R) ?norms_mulgen // (subset_trans sRG).\n    by apply: subset_trans nX_PR0; rewrite sub_gen ?subsetUr.\n  have trOp'H1: 'O_p^'(V <*> X <*> P) = 1.\n    apply: card1_trivg; apply: pnat_1 (pcore_pgroup _ _) => //=.\n    have nO_X := pcore_normal p^' (V <*> X <*> P).\n    apply: pgroupS pV; rewrite {2}eqVC subsetI.\n    rewrite (subset_trans _ sXH) ?(normal_sub nO_X) //= centsC.\n    apply/setIidPl; rewrite -coprime_norm_cent.\n    + apply/setIidPl; case/andP: nO_X => _; apply: subset_trans.\n      by rewrite /= -mulgenA sub_gen // subsetUl.\n    + apply: subset_trans nVH; apply: subset_trans sXH; exact: normal_sub.\n    apply: pnat_coprime (pcore_pgroup _ _).\n    rewrite defVp; exact: pcore_pgroup.\n  have{trOp'H1} trOR: 'O_p^'([~: V <*> X <*> P, R0]) = 1.\n    apply/trivgP; rewrite -trOp'H1.\n    apply: pcore_max; first exact: pcore_pgroup.\n    apply: char_normal_trans (pcore_char _ _) _.\n    by rewrite /(_ <| _) commg_norml /= commGC commg_subr andbT.\n  have sP_O: P \\subset 'O_p([~: V <*> X <*> P, R0]).\n    rewrite (@subset_normal_Hall _ p _ [~: ((V <*> X) <*> P)%g, R0]).\n    + rewrite /psubgroup (pHall_pgroup sylP) {1}defP commSg //.\n      by rewrite sub_gen // subsetUr.\n    + rewrite /pHall pcore_sub pcore_pgroup /= -(pseries_pop2 _ trOR).\n      rewrite -card_quotient ?normal_norm ?pseries_normal //.\n      have{ltX_G IHG} VXPR_1: p.-length_1 [~: V <*> X <*> P, R0].\n        by apply: IHG ltX_G => //=; rewrite mul_subG ?normG.\n      rewrite -{1}((_ =P [~: _, _]) VXPR_1) quotient_pseries.\n      exact: pcore_pgroup.\n    exact: pcore_normal.\n  have <-: K :&: 'O_p([~: (V <*> X) <*> P, R0]) = 1.\n    apply: coprime_TIg; rewrite coprime_sym (pnat_coprime _ p'K) //.\n    exact: pcore_pgroup.\n  rewrite subsetI; apply/andP; split.\n    by apply: subset_trans (commSg _ sXK) _; rewrite commGC commg_subr.\n  apply: subset_trans (commgS _ sP_O) _; rewrite commg_subr.\n  have: X \\subset V <*> X <*> P by rewrite mulgenC mulgenA sub_gen ?subsetUr.\n  move/subset_trans; apply; apply: normal_norm.\n  apply: char_normal_trans (pcore_char _ _) _.\n  by rewrite /(_ <| _) commg_norml andbT /= commGC commg_subr.\nclear defH.\nhave[]: H :==: V * K * P /\\ R0 :==: R.\n  rewrite eq_sym !eqEcard sR0R ?mul_subG //=; apply/andP.\n  do 2!rewrite leqNgt andbC; rewrite -negb_or; apply: contra ntKP.\n  rewrite -mulgA -norm_mulgenEr // -norm_mulgenEr; last first.\n    by rewrite (subset_trans _ nVH) // gen_subG subUset sPH sKH.\n  rewrite mulgenA; move/IHG=> -> //.\n  by rewrite gen_subG subUset nKP (subset_trans sR0R).\nmove/eqP=> defH; move/eqP=> defR.\nclear U defU sVU sUG nUG nUR hallK p'Ub nVU defVK sylV sPN.\nclear sKR0_G nV_KR0 sK_KR0 sR0_KR0 solKR0 coK_R0 oKR0 hallK_R0 hallR0_K.\nmove: {sR0R} IHG oR0 ZCHR0 ntKR0 {nKR0} rR0 trCKR0_V oCVR0 trCP_R0 defP.\nrewrite {R0}defR ltnn => IHG oR ZCHR ntKR rR trCKR_V oCVR trCP_R defP.\nhave{sylP} pP: p.-group P by case/and3P: sylP.\nhave{nVH} nVK: K \\subset 'N(V) by exact: subset_trans nVH.\nhave oVK: #|V <*> K| = (#|V| * #|K|)%N.\n  by rewrite norm_mulgenEr // coprime_cardMg // (pnat_coprime pV).\nhave trVK_P: V <*> K :&: P = 1.\n  apply/trivgP; rewrite -trVP /= -{1}(setIid P) setIA setSI //=.\n  have sV_VK: V \\subset V <*> K by rewrite sub_gen ?subsetUl.\n  have sylV: p.-Sylow(V <*> K) V.\n    by rewrite pHallE sV_VK oVK partn_mul // /= part_pnat ?part_p'nat ?muln1.\n  rewrite (subset_normal_Hall _ sylV) /=.\n    rewrite /psubgroup subsetIl; apply: pgroupS pP; exact: subsetIr.\n  by rewrite /normal sV_VK gen_subG subUset normG.\nhave oH: (#|H| = #|V| * #|K| * #|P|)%N.\n  by rewrite defH -(norm_mulgenEr nVK) -oVK (TI_cardMg trVK_P).\nhave{IHG} IHK: forall X : {group gT},\n  P <*> R \\subset 'N(X) -> X \\subset K -> X :=: K \\/ X \\subset 'C(P).\n- move=> X nX_PR sXK.\n  have:= sXK; rewrite subEproper; case/predU1P; first by left.\n  move/proper_card => ltXK; right; apply/commG1P.\n  apply: IHG => //; move: nX_PR; rewrite mulgen_subG; case/andP=> nXP _.\n  rewrite [_ <*> _]norm_mulgenEr; last first.\n    by rewrite norms_mulgen ?nVP // commGC commg_norml.\n  rewrite TI_cardMg /=; last first.\n    by apply/trivgP; rewrite -trVK_P setSI ?genS ?setUS.\n  rewrite oH ltn_pmul2r ?ltn_0group // norm_mulgenEr ?(subset_trans sXK) //.\n  rewrite orbF coprime_cardMg // ?ltn_pmul2l // (pnat_coprime pV) //.\n  exact: pgroupS p'K.\nhave defKP: K :=: [~: K, P].\n  have sKP_K: [~: K, P] \\subset K by rewrite commGC commg_subr.\n  case: (IHK _ _ sKP_K) => //.\n    by rewrite gen_subG subUset /= {1}commGC commg_norml normsR.\n  move/commG1P=> /= KP1.\n  case/eqP: ntKP; rewrite /= commGAA //.\n    by rewrite coprime_sym (pnat_coprime pP).\n  apply: solvableS solG; exact: subset_trans sKH sHG.\nhave nrp: r != p.\n  move: coHR; rewrite oR coprime_sym prime_coprime -?p'natE // => r'H.\n  have sCH: 'C_V(R) \\subset H by apply: subset_trans sVH; exact: subsetIl.\n  by rewrite eq_sym; apply: (pgroupP _ _ (pgroupS sCH r'H)); rewrite ?oCVR.\nhave nKPR: P <*> R \\subset 'N(K) by rewrite mulgen_subG nKP.\nhave trCPR_K: 'C_(P <*> R)(K) = 1.\n  have solPR: solvable (P <*> R).\n     apply: solvableS solG; rewrite gen_subG subUset sRG.\n     by rewrite (subset_trans sPH sHG).\n  have coPR: coprime #|P| #|R| by rewrite oR (pnat_coprime pP) ?pnatE.\n  have nC_PR: 'C_(P <*> R)(K) <| P <*> R.\n    by rewrite /normal subsetIl normsI ?normG ?norms_cent.\n  have sP_PR: P \\subset P <*> R by rewrite sub_gen ?subsetUl.\n  have sR_PR: R \\subset P <*> R by rewrite sub_gen ?subsetUr.\n  have p'R: p^'.-group R by rewrite /pgroup oR pnatE.\n  have sylPC: p.-Sylow('C_(P <*> R)(K)) 'C_P(K).\n    rewrite -{2}(setIidPl sP_PR) -setIA (HallSubnormal _ nC_PR) //.\n    rewrite /pHall sP_PR pP /= -divgS //= norm_mulgenEr //.\n    by rewrite coprime_cardMg // mulKn.\n  have hallRC: p^'.-Hall('C_(P <*> R)(K)) 'C_R(K).\n    rewrite -{2}(setIidPl sR_PR) -setIA (HallSubnormal _ nC_PR) //.\n    rewrite /pHall sR_PR /= -divgS //= norm_mulgenEr //.\n    rewrite coprime_cardMg // mulnK // pnatNK; exact/andP.\n  have trCP: 'C_P(K) = 1.\n    apply/trivgP; rewrite /= -{1}(setIidPl sPH) -setIA.\n    have <-: P :&: K = 1 by apply coprime_TIg; exact: pnat_coprime pP p'K.\n    exact: setIS.\n  have trCR: #|'C_R(K)| = 1%N.\n    have: #|'C_R(K)| %| r by rewrite -oR cardSg ?subsetIl.\n    case/primeP: pr_r => _ pr_r; move/pr_r; case/orP; move/eqP=> // oCR.\n    case/eqP: ntKR; apply/commG1P; rewrite centsC; apply/setIidPl.\n    by apply/eqP; rewrite eqEcard oR oCR leqnn subsetIl.\n  apply: card1_trivg; rewrite -[#|_|](partnC p) // -(card_Hall sylPC).\n  by rewrite -(card_Hall hallRC) trCR muln1 /= trCP cards1.\nhave [K1 | [q q_pr qKdv]] := trivgVpdiv K.\n  by rewrite K1 comm1G eqxx in ntKR.\nhave nqp: q != p by exact: (pgroupP _ _ p'K).\nhave nrq: r != q by rewrite eq_sym; exact: (pgroupP _ _ r'K).\nhave{defK} qK: q.-group K.\n  have IHpi: forall pi, 'O_pi(K) = K \\/ 'O_pi(K) \\subset 'C(P).\n    move=> pi; apply: IHK (pcore_sub _ _).\n    by apply: char_norm_trans (pcore_char _ _) _; rewrite mulgen_subG nKP.\n  case: (IHpi q) => [<-| cPKq]; first exact: pcore_pgroup.\n  have{defK} nilK: nilpotent K by rewrite defK Fitting_nil.\n  case/dprodP: (nilpotent_pcoreC q nilK) => _ defK _ _.\n  case/eqP: ntKP; apply/commG1P; rewrite -{}defK mul_subG //.\n  case: (IHpi q^') => // defK; case/idPn: qKdv.\n  rewrite -p'natE // -defK; exact: pcore_pgroup.\npose K' := 'L_1(K)%G; have nK'K: K' <| K := der_normal K 0.\nhave nK'PR: P <*> R \\subset 'N(K').\n  exact: char_norm_trans (der_char K 1) nKPR.\nhave iK'K: 'C_(P <*> R / K')(K / K') = 1 -> #|K / K'| > q ^ 2.\n  have: q.-group (K / K') by exact: morphim_pgroup qK.\n  case/p_natP=> // k oK; rewrite oK ltn_exp2l ?prime_gt1 // ltnNge.\n  move=> trCK'; apply: contra ntKP => lek2.\n  suff trP: [~: P, R] = 1 by rewrite defP trP commG1.\n  have coK_PR: \\pi(#|K|)^'.-group (P <*> R).\n    rewrite norm_mulgenEr // pgroupM /pgroup -!coprime_pi' // coprime_sym.\n    by rewrite (pnat_coprime pP) // coprime_sym oR prime_coprime // -p'natE.\n  suff sPR_K': [~: P, R] \\subset K'.\n    rewrite -(setIidPl sPR_K') coprime_TIg //.\n    apply: pnat_coprime (pgroupS (normal_sub nK'K) p'K).\n    by apply: pgroupS pP; rewrite /= commGC commg_subr.\n  rewrite -quotient_cents2 ?(char_norm_trans (der_char K 1)) //.\n  rewrite (sameP commG1P trivgP) -trCK'.\n  rewrite subsetI comm_subG ?morphimS ?(mulgen_subl, mulgen_subr) //.\n  rewrite -ker_conj_aut -sub_morphim_pre; last first.\n    by rewrite comm_subG ?morphim_norms.\n  rewrite morphimR ?morphim_norms //.\n  suffices: abelian (Aut (K / K')).\n    move/commG1P=> <- /=.\n    by apply: commgSS; apply/subsetP=> fx;\n       case/imsetP=> x Nx ->; apply: Aut_aut.\n  case cycK: (cyclic (K / K')).\n    case/cyclicP: cycK => x ->; exact: aut_cycle_commute.\n  case: k lek2 oK => [|[|[|//]]] _ oK.\n  - case/cyclicP: cycK; exists (1 : coset_of K'); rewrite cycle1.\n    by apply: card1_trivg.\n  - by case/idP: cycK; rewrite cyclic_prime // oK expn1.\n  have [lt1q dv_q] := primeP q_pr.\n  have: q %| #|K / K'| by rewrite oK dvdn_mulr.\n  case/Cauchy=> // u Ku ou; have: <[u]> \\proper K / K'.\n    by rewrite properEcard cycle_subG Ku oK [#|_|]ou -{1}(expn1 q) ltn_exp2l.\n  case/andP=> _; case/subsetPn=> v Kv uv.\n  have:= Kv; rewrite -cycle_subG; move/cardSg; rewrite oK.\n  case/dvdn_pfactor=> [//|[|[|[|//]]] _ ov]; last 1 first.\n  - case/cyclicP: cycK; exists v; apply/eqP.\n    by rewrite eq_sym eqEcard oK ov cycle_subG Kv leqnn.\n  - by rewrite -(expg1 v) -[1%N]ov order_expn1 group1 in uv.\n  have abK: abelian (K / K').\n    suff ->: K / K' = 'Z(K / _) by exact: abelian_center.\n    have:= center_sub (K / K'); move/cardSg; rewrite oK.\n    case/dvdn_pfactor=> [//|[|[|[|//]]] _ oZ].\n    - have: q.-group (K / K') by exact: morphim_pgroup.\n      by move/trivg_center_pgroup; rewrite /= ['Z(_)]card1_trivg ?oZ // => ->.\n    - apply: center_cyclic_abelian (cyclic_prime _).\n      rewrite card_quotient ?normal_norm ?center_normal //.\n      by rewrite -divgS ?subsetIl // oZ oK mulnK // muln1 ltnW.\n    by symmetry; apply/eqP; rewrite eqEcard oK oZ subsetIl leqnn.\n  have cuv: commute u v by apply: (centsP abK).\n  have truv: <[u]> :&: <[v]> = 1.\n    have sI := subsetIr <[u]> <[v]>.\n    have:= cardSg sI; rewrite ov expn1; move/dv_q; case/orP; move/eqP=> oI.\n      exact: card1_trivg.\n    have:= sI; rewrite subEproper properEcard oI ov expn1 ltnn andbF orbF.\n    by rewrite (sameP eqP setIidPr) cycle_subG (negPf uv).\n  have defK: K / K' = <[u]> * <[v]>.\n    apply/eqP; rewrite eq_sym eqEcard mul_subG ?cycle_subG // oK.\n    by rewrite (TI_cardMg truv) {1}[#|_|]ou ov leqnn.\n  have{ov} ov: #[v] = q by rewrite expn1 in ov.\n  admit. (* at this point, we need Theorem 2.6 from B & G *)\ncase abelK: (abelian K); last first.\n  have [dCKP sK' dPhiK]:\n    [/\\ 'C_K(P) = 'Z(K), K^`(1) = 'Z(K) & 'Phi(K) = 'Z(K)].\n  + (* C_K(P) = K^(1) = Phi(K)  = Z(K) by Asch. 24.7 *) admit.\n  have xKq: exponent K %| q.\n    have [Q [chQ xQq qCKQ]]: exists Q : {group gT},\n      [/\\ Q \\char K, exponent Q %| q & q.-group 'C_(Aut K | 'P)(Q)].\n      (* B & G 1.13 *) admit.\n    have: P <*> R \\subset 'N(Q) by exact: char_norm_trans nKPR.\n    have sQK := char_sub chQ.\n    case/IHK=> // [<- //|cQP]; case/eqP: ntKP; apply/commG1P.\n    rewrite centsC -ker_conj_aut -sub_morphim_pre // -[_ @* _]setIid.\n    apply/trivgP; apply: coprime_TIg.\n    apply: pnat_coprime (morphim_pgroup _ pP) _.\n    apply: (@sub_in_pnat q) => [q' _|]; first by move/eqnP->.\n    apply: pgroupS qCKQ; apply/subsetP=> a; case/morphimP=> x _ Px ->{a}.\n    rewrite inE /= Aut_aut; apply/astabP=> y Qy.\n    rewrite /= /aperm norm_conj_autE ?(subsetP sQK) ?(subsetP nKP) //.\n    by rewrite /conjg (centsP cQP y) ?mulKg.\n  have trCPR_K': 'C_(P <*> R / 'Z(K))(K / 'Z(K)) = 1.\n    rewrite -dPhiK. admit. (* B & G Theorem 1.8 *)\n  have nZP := char_norm_trans (center_char _) nKP.\n  have nZR := char_norm_trans (center_char _) nKR.\n  have nZK := normal_norm (center_normal K).\n  have solK: solvable K := nilpotent_sol (pgroup_nil qK).\n  have dCKR': 'C_K(R) / 'Z(K) = 'C_(K / 'Z(K))(R / 'Z(K)).\n    rewrite coprime_quotient_cent_weak ?center_normal //.\n    by rewrite coprime_sym (pnat_coprime rR r'K).\n  have abK': q.-abelem (K / 'Z(K)).\n    rewrite -dPhiK. admit. (* B & G 1.7 or above *)\n  case: (eqVneq 'C_(K / 'Z(K))(R / 'Z(K)) 1) => [trCK'_R | ntCK'_R].\n    have qZ: q.-group 'Z(K) by exact: pgroupS (center_sub K) qK.\n    have q'P: q^'.-group P.\n      by apply: sub_in_pnat pP => p' _; move/eqnP->; rewrite eq_sym in nqp.\n    have coZP: coprime #|'Z(K)| #|P| := pnat_coprime qZ q'P.\n    suff sPZ: P \\subset 'Z(K).\n       by case/negP: ntKP; rewrite -(setIidPr sPZ) coprime_TIg ?commG1.\n    rewrite -quotient_sub1 // defP commGC quotientE morphimR // -?quotientE.\n    have <-: 'C_(P /'Z(K))(K / 'Z(K)) = 1.\n      by apply/trivgP; rewrite -trCPR_K' setSI ?morphimS ?mulgen_subl.\n    move: trCK'_R; have: ~~ (q %| #|P <*> R / 'Z(K)|).\n      rewrite -p'natE //; apply: morphim_pgroup.\n      by rewrite /= norm_mulgenEr // pgroupM q'P /pgroup oR pnatE.\n    have sPRG: P <*> R \\subset G by rewrite mulgen_subG sRG (subset_trans sPH).\n    have coPR: coprime #|P| #|R| by rewrite (pnat_coprime pP) // oR pnatE.\n    apply: three_dot_four abK' _.\n    - exact: quotient_sol (solvableS _ solG).\n    - rewrite !odd_2'nat in oddG *; apply: morphim_pgroup; exact: pgroupS oddG.\n    - by rewrite morphim_normal // /normal mulgen_subl mulgen_subG normG.\n    - rewrite morphim_Hall // /Hall -divgS ?mulgen_subl //= norm_mulgenEr //.\n      by rewrite coprime_cardMg // mulKn.\n    - apply/complP; rewrite -morphimMl //= norm_mulgenEr // ?coprime_TIg //.\n      apply: pnat_coprime (morphim_pgroup _ pP) (morphim_pgroup _ _).\n      by rewrite /pgroup oR pnatE.\n    - rewrite card_morphim ker_coset (setIidPr _) // -indexgI.\n      rewrite coprime_TIg ?indexg1 ?oR //.\n      rewrite -oR (pnat_coprime rR) //; exact: (pgroupS (subsetIl _ _)).\n    by apply: morphim_norms; rewrite mulgen_subG nKP.\n  have sKR_C_K': 'C_K(R) :&: [~: K, R] \\subset 'Z(K).\n    rewrite -quotient_sub1; last by rewrite -setIA subIset ?nZK.\n    apply: subset_trans (morphimI _ _ _) _.\n    rewrite morphimR; first 1 [rewrite -!quotientE dCKR'] || by [].\n    rewrite setIC comm_center_triv ?morphim_norms //.\n      rewrite coprime_sym (pnat_coprime (morphim_pgroup _ rR)) //.\n      exact: morphim_pgroup.\n    by case/andP: abK'; case/andP.\n  have sKR_K: [~: K, R] \\proper K.\n    rewrite properE {1}commGC commg_subr nKR /=.\n    apply/negP=> sK_KR; case/eqP: ntCK'_R; apply/trivgP.\n    rewrite /= -dCKR' quotient_sub1; last by rewrite subIset // nZK.\n    by rewrite -{1}(setIidPl sK_KR) setIAC.\n  rewrite -subG1 /= -dCKR' quotient_sub1 // in ntCK'_R *; last first.\n    by rewrite subIset // normal_norm // center_normal.\n  have oCKR: #|'C_K(R)| = q.\n    have: cyclic 'C_K(R).\n      apply: nil_Zgroup_cyclic; first exact: ZgroupS (setSI _ _) ZCHR.\n      apply: pgroup_nil (pgroupS _ qK); exact: subsetIl.\n    case/cyclicP=> x CKRx.\n    have Kx: x \\in K by rewrite -cycle_subG -CKRx subsetIl.\n    have{Kx}:= dvdn_trans (dvdn_exponent Kx) xKq; rewrite /order CKRx.\n    case: (primeP q_pr) => _ dvq; move/dvq; case/orP; move/eqnP=> // x1.\n    by rewrite CKRx ((<[x]> =P 1) _) ?sub1G // trivg_card1 x1 in ntCK'_R.\n  have trCKR_Z: 'C_K(R) :&: 'Z(K) = 1.\n    apply: card1_trivg.\n    have:= cardSg (subsetIl 'C_K(R) 'Z(K)); rewrite oCKR.\n    case: (primeP q_pr) => _ dvq; move/dvq; case/predU1P=> [-> //| Iq].\n    case/setIidPl: ntCK'_R; apply/eqP; rewrite eqEcard subsetIl.\n    by rewrite oCKR (eqnP Iq) leqnn.\n  have trKR_CR: 'C_[~: K, R](R) = 1.\n    rewrite -(setIidPl (proper_sub sKR_K)) -setIA setIC.\n    rewrite -(setIidPl sKR_C_K') -setIA setICA trCKR_Z.\n    apply/setIidPr; exact: sub1G.\n  have abKR: abelian [~: K, R].\n    apply/commG1P; apply/trivgP.\n    have <-: 'C_[~: K, R](V) = 1.\n      have sKRH: [~: K, R] \\subset H := subset_trans (proper_sub sKR_K) sKH.\n      apply/trivgP; rewrite /= -(setIidPl sKRH) -setIA -eqVC setIC -trVN.\n      by rewrite setIS // subsetI sKRH (subset_trans _ (normG K)) ?proper_sub.\n    have nKR_R: R \\subset 'N([~: K, R]) by rewrite commGC commg_norml.\n    have coKR_R: coprime #|R| #|[~: K, R]|.\n      exact: pnat_coprime rR (pgroupS (proper_sub sKR_K) r'K).\n    have sKRR_G: [~: K, R] <*> R \\subset G.\n      by rewrite mulgen_subG comm_subG // (subset_trans sKH).\n    move: oCVR; have: ~~ (p %| #|[~: K, R] <*> R|).\n      rewrite -p'natE // norm_mulgenEr // [_ #|_|]pgroupM.\n      by rewrite (pgroupS (proper_sub sKR_K) p'K) /pgroup oR pnatE.\n    apply: three_dot_five; rewrite ?oR //.\n    - exact: solvableS solG.\n    - by rewrite /normal mulgen_subl mulgen_subG normG nKR_R.\n    - by apply/complP; rewrite setIC coprime_TIg //= norm_mulgenEr.\n    exact: subset_trans nVG.\n  case nKR_P: (P \\subset 'N([~: K, R])).\n    have{nKR_P}: P <*> R \\subset 'N([~: K, R]).\n      by rewrite mulgen_subG nKR_P commGC commg_norml.\n    case/IHK=> [|dKR|cP_KR]; first exact: proper_sub.\n      by case/eqP: (proper_neq sKR_K).\n    have{cP_KR} cK'_R: R / 'Z(K) \\subset 'C(K / 'Z(K)).\n      by rewrite quotient_cents2r //= -dCKP commGC subsetI proper_sub.\n    case/eqP: ntKR; apply/commG1P; rewrite centsC.\n    admit. (* B & G 1.18 *)\n  case/subsetPn: nKR_P => x Px; move/normP; move/eqP=> nKRx.\n  have iKR: #|K : [~: K, R]| = q.\n    rewrite -divgS ?proper_sub // {1}(comm_center_prod nKR) //; last first.\n      by rewrite coprime_sym (pnat_coprime rR).\n    rewrite TI_cardMg ?mulKn // setICA trKR_CR; apply/setIidPr; exact: sub1G.\n  pose IKRx := ([~: K, R] :&: [~: K, R] :^ x)%G.\n  have sKRx_K: [~: K, R] :^ x \\subset K.\n    by rewrite -{2}(normsP nKP x Px) conjSg proper_sub.\n  have nKR_K: K \\subset 'N([~: K, R]) by exact: commg_norml.\n  have iIKRx: #|[~: K, R] : IKRx| = q.\n    have: #|[~: K, R] : IKRx| %| q.\n      rewrite -divgS ?subsetIl // -{1}(cardJg _ x) /= setIC divgI -iKR.\n      rewrite -!card_quotient ?(subset_trans sKRx_K) //.\n      apply: cardSg; exact: morphimS.\n    case/primeP: q_pr => _ dv_q; move/dv_q; case/orP; move/eqnP=> // iIKR_1.\n    case/negP: nKRx; rewrite eq_sym eqEcard cardJg leqnn andbT.\n    rewrite (sameP setIidPl eqP) eqEcard subsetIl /=.\n    by rewrite -(LaGrange (subsetIl _ ([~: K, R] :^ x))) iIKR_1 muln1 /=.\n  have dKx: K :=: [~: K, R] * [~: K, R] :^ x.\n    apply/eqP; rewrite eq_sym eqEcard mul_subG // ?proper_sub //.\n    rewrite -(leq_pmul2r (ltn_0group IKRx)) -mul_cardG cardJg.\n    rewrite -(LaGrange (proper_sub sKR_K)) iKR -mulnA leq_pmul2l //.\n    by rewrite -iIKRx mulnC LaGrange /= ?subsetIl.\n  have sIKRxZ: IKRx \\subset 'Z(K).\n    rewrite subsetI subIset; last by rewrite sKRx_K orbT.\n    rewrite /abelian in abKR.\n    by rewrite dKx centM centJ subsetI !subIset // ?conjSg ?abKR ?orbT.\n  suffices: #|K / 'Z(K)| <= q ^ 2.\n    by rewrite leqNgt -sK' iK'K // [K' : {set _}]sK'.\n  rewrite card_quotient ?normal_norm ?center_normal //.\n  rewrite -mulnn -{1}iKR -iIKRx LaGrange_index ?subsetIl ?proper_sub //.\n  by rewrite dvdn_leq // indexgS.\nhave trCK_P: 'C_K(P) = 1.\n  apply/trivgP; rewrite -(comm_center_triv nKP) -?defKP ?setIA ?setIid //.\n  by rewrite coprime_sym (pnat_coprime pP).\nhave abelemK: q.-abelem K.\n  rewrite /p_abelem qK andbC; apply/abelem_Ohm1P; rewrite ?(pgroup_p qK) //.\n  case/IHK: (Ohm_sub 1 K) => // [|cPK1].\n    by apply: char_norm_trans (Ohm_char 1 K) _; rewrite mulgen_subG nKP.\n  case/Cauchy: qKdv => // x Kx oxq.\n  have: x \\in 'C_K(P).\n    rewrite inE Kx (subsetP cPK1) //= (OhmE 1 qK) ?mem_gen // inE Kx.\n    by rewrite /= -oxq expn1 order_expn1.\n  by rewrite trCK_P; move/set1P=> x1; rewrite -oxq x1 order1 in q_pr.\nhave{iK'K} oKq2: q ^ 2 < #|K|.\n  have K'1: K' :=: 1 by exact/commG1P.\n  rewrite -indexg1 -K'1 -card_quotient ?normal_norm // iK'K // K'1.\n  by rewrite -injm_subcent ?coset1_injm ?norms1 //= trCPR_K morphim1.\npose Vi (Ki : {group gT}) := 'C_V(Ki)%G.\npose mxK := [set Ki : {group gT} | maximal Ki K && (Vi Ki :!=: 1)].\nhave nKiK: forall Ki, Ki \\in mxK -> Ki <| K.\n  by move=> Ki; rewrite inE; case/andP=> maxK _; exact: (p_maximal_normal qK).\nhave nViK: forall Ki, Ki \\in mxK -> K \\subset 'N(Vi Ki).\n  by move=> Ki mxKi; rewrite normsI // norms_cent // normal_norm // nKiK.\nhave gen_mxK: << \\bigcup_(Ki \\in mxK) Vi Ki >> = V.\n  admit. (* B & G, Prop. 1.16 *)\nhave dprod_V : \\big[dprod/1]_(Ki \\in mxK) Vi Ki = V.\n  pose dp (sM : {set _}) := \\big[dprod/1]_(Ki \\in sM) Vi Ki.\n  have dp0: dp set0 = 1 by rewrite /dp big_pred0 => // Ki; rewrite inE.\n  pose sM0 : {set {group gT}} := set0.\n  have: exists sM, group_set (dp sM) && (sM \\subset mxK).\n    by exists sM0; rewrite sub0set dp0 groupP.\n  case/ex_maxset=> sM; case/maxsetP; case/andP=> gW ssM max_sM.\n  move defW: (Group gW) => W; move/(congr1 val): defW => /= defW.\n  move: ssM; rewrite subEproper /= -{2}gen_mxK.\n  case/predU1P=> [<-|]; first by rewrite (bigdprodEgen defW).\n  case/andP=> ssM; case/subsetPn=> Kj mxKj nsKj; case/negP: (nsKj).\n  suffices trWVj: 'C_W(Kj) = 1.\n    rewrite -(max_sM _ _ (subsetUr [set Kj] _)); first by rewrite inE set11.\n    rewrite subUset sub1set mxKj ssM /= andbT.\n    rewrite /dp (bigD1 Kj) ?setU11 //=.\n    suff: group_set (Vi Kj \\x dp sM).\n      apply: etrans; congr (group_set (_ \\x _)); apply: eq_bigl => M1.\n      by rewrite !inE andbC; case: eqP => // ->; rewrite (negPf nsKj).\n    have cWM: Vi Kj \\subset 'C(W).\n      rewrite subIset // centsC; apply/orP; left.\n      case/andP: abV; case/andP=> abV _ _; apply: subset_trans abV.\n      move/bigdprodEgen: defW => <-; rewrite gen_subG.\n      apply/bigcupsP=> M1 _; exact: subsetIl.\n    rewrite defW dprodE //; first by rewrite -cent_mulgenEl ?groupP.\n    by apply/trivgP; rewrite -trWVj /= setIC setICA subsetIr.\n  have: exists mM, ('C_(dp mM)(Kj) == 1) && (mM \\subset sM).\n    by exists sM0; rewrite sub0set dp0 -subG1 subsetIl.\n  case/ex_maxset=> mM; case/maxsetP; case/andP; move/eqP=> trVm.\n  rewrite subEproper -defW; case/predU1P=> [<- //|]; case/andP=> smM.\n  case/subsetPn=> Ki sKi nmKi max_mM.\n  case/negP: (nmKi); rewrite -sub1set; apply/setUidPr.\n  apply: max_mM (subsetUr _ _); rewrite subUset sub1set sKi smM !andbT.\n  have:= defW; rewrite {1}/dp (bigID [pred Kk \\in Ki |: mM]) /=.\n  case/dprodP=> [[W' _ defW' _] _ _ _].\n  rewrite (_ : bigop _ _ _ _ _ = dp (Ki |: mM)) in defW'; last first.\n    apply: eq_bigl => Kk; rewrite -in_setI (setIidPr _) //.\n    by rewrite subUset sub1set sKi smM.\n  rewrite defW'; move: defW'; rewrite /dp (bigD1 Ki) ?setU11 //=.\n  rewrite (_ : bigop _ _ _ _ _ = dp mM); last first.\n    apply: eq_bigl => Kk; rewrite !inE andbC; case: eqP => // ->.\n    by rewrite (negPf nmKi).\n  case/dprodP=> [[_ W2 _ defW2] <-]; rewrite defW2 => cViW2 trViW2.\n  rewrite -cent_mulgenEl // -subG1 /= cent_mulgenEl //.\n  apply/subsetP=> uv; case/setIP; case/imset2P=> u v Viu W2v ->{uv} Vjuv.\n  have mxKi := subsetP ssM _ sKi.\n  case/setIdP: mxKj; case/maxgroupP; case/andP=> sKj _ mxKj _.\n  have v1: v = 1.\n    apply/set1gP; rewrite -trVm inE defW2 W2v /=.\n    apply/centP=> x Kjx; apply/commgP; rewrite (sameP eqP set1gP).\n    have Kx: x \\in K by apply: subsetP Kjx.\n    rewrite -trViW2; apply/setIP; split.\n      have cuv: commute u v by exact: (centsP cViW2).\n      rewrite commgEl -{2}(mulgK u v) -cuv conjMg {1}/conjg.\n      rewrite (centP Vjuv x Kjx) mulKg cuv mulgA mulKg groupMl //.\n      by rewrite conjVg groupV memJ_norm //; apply: subsetP Kx; rewrite nViK.\n    rewrite groupMl ?groupV // memJ_norm // -(bigdprodEgen defW2).\n    apply: subsetP Kx; apply big_prop=> [|y z Ny Nz|Kk].\n    - by rewrite gen0 norms1.\n    - by rewrite -mulgenE -mulgen_idl -mulgen_idr norms_mulgen.\n    move/(subsetP (subset_trans smM ssM))=> mxKk.\n    by rewrite norms_gen // nViK.\n  rewrite -trCVK v1 !mulg1 in Vjuv *.\n  have: Ki <*> Kj \\subset K by rewrite mulgen_subG sKj normal_sub // nKiK.\n  rewrite subEproper; case/predU1P=> [<-|sKij].\n    by rewrite cent_mulgen setIA inE Viu.\n  have defKj: Ki <*> Kj = Kj by apply: mxKj; rewrite ?mulgen_subr.\n  suffices defKi: Kj = Ki by rewrite defKi sKi in nsKj.\n  apply: val_inj; move: mxKi; rewrite inE /= -defKj.\n  by case/andP; case/maxgroupP=> _ mxKi _; apply: mxKi; rewrite ?mulgen_subl.\nhave ViJ: forall x Ki, x \\in P <*> R -> (Vi Ki :^ x = Vi (Ki :^ x))%G.\n  move=> x Ki PRx; apply: group_inj; rewrite /= conjIg centJ (normP _) //.\n  by apply: subsetP PRx; rewrite mulgen_subG nVP (subset_trans sRG).\nhave actsPR_K: [acts (P <*> R | 'JG) on mxK].\n  apply/subsetP=> x PRx; rewrite inE; apply/subsetP=> Ki.\n  rewrite !inE -ViJ // !trivg_card1 cardJg /=.\n  case/andP; case/maxgroupP=> sKj mxKj ->.\n  rewrite -(normsP nKPR x PRx) andbT.\n  apply/maxgroupP; rewrite /proper !conjSg; split=> // Q.\n  rewrite !sub_conjg /= -sub_conjgV=> sQ.\n  by move/mxKj <-; rewrite // conjsgKV.\nhave actsPR: [acts (P <*> R | 'JG) on Vi @: mxK].\n  apply/subsetP=> x PRx; rewrite inE; apply/subsetP=> Vj.\n  case/imsetP=> Kj mxKj ->{Vj}.\n  by rewrite inE /= ViJ // mem_imset // (actsP actsPR_K).\nhave transPR: [transitive (P <*> R | 'JG) on Vi @: mxK].\n  have [K1 mxK1]: exists K1, K1 \\in mxK.\n    have:= sub0set mxK; rewrite subEproper; case/predU1P=> [mx0|]; last first.\n      by case/andP=> _; case/subsetPn=> K1; exists K1.\n    have:= pr_p; rewrite -oCVR -dprod_V -mx0 big1 => [|Ki]; rewrite ?inE //.\n    by rewrite (setIidPl (sub1G _)) cards1.\n  have mxV1: Vi K1 \\in Vi @: mxK by rewrite mem_imset.\n  apply/imsetP; exists (Vi K1) => //.\n  set S := orbit _ _ _; rewrite (bigID [preim Vi of S]) /= in dprod_V.\n  case/dprodP: dprod_V (dprod_V) => [[N1 N2 defN1 defN2]].\n  pose dp PK := \\big[dprod/1]_(Ki \\in mxK | PK Ki) Vi Ki.\n  rewrite defN1 defN2 => _ cN12 trN12; case/nondecV=> [||N1V].\n  - apply/subsetP=> x Gx; rewrite !inE.\n    move: Gx; rewrite -eqHR_G defH -mulgA; case/imset2P=> x1 x2 VHx1.\n    rewrite -norm_mulgenEr // => PRx2 ->{x}.\n    pose idPR (PK : pred {group gT}) :=\n      forall y Ki, y \\in P <*> R -> PK (Ki :^ y)%G = PK Ki.\n    have idS: idPR [preim Vi of S].\n      move=> y Ki PRy; rewrite /= -ViJ //; apply: orbit_transr.\n      by apply/imsetP; exists y.\n    have nN2: forall PK (N : {group _}),\n      idPR PK -> dp PK = N -> N :^ (x1 * x2) = N.\n    - move=> PK N idPK defN; rewrite -{1}(bigdprodE defN).\n      rewrite /dp (reindex (fun Ki => (Ki :^ x2)%G)) in defN; last first.\n        exists (fun Ki => (Ki :^ x2^-1)%G) => Ki _; apply: group_inj.\n          exact: conjsgK.\n        exact: conjsgKV.\n      rewrite -(bigdprodE defN) {N defN} /= big_mkcond /=.\n      symmetry; rewrite big_mkcond /=; symmetry.\n      pose RK := [fun U W => U :^ (x1 * x2) = W].\n      apply (big_rel RK) => /= [|U1 _ U2 _ <- <-|Ki _].\n      - by rewrite conjs1g.\n      - by rewrite conjsMg.\n      rewrite idPK // (actsP actsPR_K) //.\n      case mxKi: {+}(_ && _); last by rewrite conjs1g.\n      rewrite conjsgM (normsP _ x1 VHx1).\n        by have:= congr1 val (ViJ _ Ki PRx2) => /= ->.\n      case/andP: mxKi => mxKi _; rewrite mul_subG ?nViK //.\n      rewrite cents_norm // centsC subIset //; apply/orP; left.\n      by case/andP: abV; case/andP.\n    rewrite (nN2 _ _ _ defN1) // (nN2 _ _ _ defN2) ?subxx // => y Ki PRy.\n    by congr (~~ _); exact: idS.\n  - move/trivgP; rewrite -(bigdprodEgen defN1) gen_subG.\n    move/bigcupsP; move/(_ K1); rewrite mxK1 orbit_refl => trV1.\n    by case/setIdP: mxK1 => _; rewrite -subG1 trV1.\n  have: S \\subset Vi @: mxK by rewrite acts_orbit.\n  rewrite subEproper; case/predU1P=> //; case/andP=> _; case/subsetPn=> V2.\n  case/imsetP=> K2 mxK2 -> SV2; move/trivgP: trN12.\n  rewrite /= N1V -(bigdprodEgen defN2) (setIidPr _) gen_subG.\n    move/bigcupsP; move/(_ K2); rewrite mxK2 SV2 => trV2.\n    by case/setIdP: mxK2 => _; rewrite -subG1 trV2.\n  apply/bigcupsP=> Kj _; exact: subsetIl.\ncase sR_IN: (forallb K1, (K1 \\in mxK) ==> (R \\subset 'N(Vi K1))).\n  have{sR_IN} sR_IN: R \\subset \\bigcap_(Ki \\in mxK) 'N(Vi Ki).\n    by apply/bigcapsP=> Ki mxKi; have:= forallP sR_IN Ki; rewrite mxKi.\n  have nIPR: P <*> R \\subset 'N(\\bigcap_(Ki \\in mxK) 'N(Vi Ki)).\n    apply/subsetP=> x PRx; rewrite inE.\n    apply/subsetP=> yx; case/imsetP=> y Iy -> {yx}.\n    apply/bigcapP=> Ki.\n    have ->: Ki = ((Ki :^ x^-1) :^ x)%G.\n      by apply: group_inj; rewrite /= conjsgKV.\n    rewrite -ViJ // (actsP actsPR_K) // normJ memJ_conjg; exact: (bigcapP Iy).\n  case/imsetP: transPR => V1; case/imsetP=> K1 mxK1 ->.\n  have: P <*> R \\subset 'N(Vi K1).\n    rewrite mulgen_subG (subset_trans sR_IN) /= ?bigcap_inf // andbT.\n    rewrite defP; apply: (subset_trans (commgS P sR_IN)).\n    have:= subset_trans (mulgen_subl P R) nIPR.\n    rewrite -commg_subr; move/subset_trans; apply; exact: bigcap_inf.\n  rewrite -conjG_fix; move/orbit1P <- => allV1.\n  have defV1: V = Vi K1.\n    apply/eqP; rewrite -val_eqE eqEsubset subsetIl /= andbT.\n    rewrite -{1}(bigdprodEgen dprod_V) gen_subG; apply/bigcupsP=> Ki mxKi.\n    have: Vi Ki \\in [set Vi K1] by rewrite -allV1 mem_imset.\n    by move/set1P=> -> /=.\n  move: mxK1 oKq2; rewrite inE; case/andP=> maxK1.\n  have [sK1 _] := andP (p_maximal_normal qK maxK1).\n  have:= p_maximal_index qK maxK1.\n  have ->: K1 :=: 1.\n    apply/trivgP; rewrite -trCKR_V subsetI defV1 centsC subsetIr andbT.\n    exact: subset_trans (mulgen_subl K R).\n  rewrite indexg1 => -> _.\n  by rewrite -{2}(expn1 q) ltn_exp2l // prime_gt1.\ncase/existsP: sR_IN => K1; rewrite negb_imply; case/andP=> mxK1 nK1R.\nhave regR_Vi: forall Ki, Ki \\in mxK ->\n  ~~ (R \\subset 'N(Vi Ki)) -> 'N_R(Vi Ki) = 1.\n- move=> Ki mxKi fixVi; apply: card1_trivg.\n  have: #|'N_R(Vi Ki)| %| r by rewrite -oR cardSg // subsetIl.\n  case: (primeP pr_r) => _ dvr; move/dvr {dvr}; case/pred2P=> [//|oN].\n  by case/setIidPl: fixVi; apply/eqP; rewrite eqEcard subsetIl oN oR leqnn.\nhave oV1R: #|orbit 'JG%act R (Vi K1)| = r.\n  by rewrite card_orbit conjG_astab1 /= regR_Vi // indexg1 oR.\nhave nRfix_CR: forall Ki, Ki \\in mxK -> ~~ (R \\subset 'N(Vi Ki)) ->\n           #|Vi Ki| = p /\\ 'C_V(R) \\subset << class_support (Vi Ki) R >>.\n- move=> Ki mxKi fixVi.\n  have [//||x Rx ox] := @Cauchy _ r R; first by rewrite oR.\n  have xR: <[x]> = R.\n    by apply/eqP; rewrite eqEcard oR -ox cycle_subG Rx leqnn.\n  have nVx: forall i y, y \\in V -> y ^ x ^+ i \\in V.\n    move=> i y Vy; rewrite memJ_norm  ?groupX //; apply: subsetP Rx.\n    exact: subset_trans nVG.\n  pose f m y := \\prod_(0 <= i < m) y ^ x ^+ i.\n  have Vf: forall m y, y \\in V -> f m y \\in V.\n    rewrite /f => m y Vy.\n    apply big_prop => [||i _]; [exact: group1 | exact: groupM | exact: nVx].\n  case/andP: abV; case/andP; move/centsP=> abV _ _.\n  have fM: {in Vi Ki &, {morph f r: y z / y * z}}.\n    rewrite /f => y z; case/setIP=> Vy _; case/setIP=> Vz _ /=.\n    elim: (r) => [|m IHm]; first by rewrite !big_geq ?mulg1.\n    rewrite !big_nat_recr /= conjMg 2!mulgA; congr (_ * _).\n    by rewrite {}IHm -2!mulgA; congr (_ * _); rewrite abV ?Vf ?nVx.\n  have injf: 'injm (Morphism fM).\n    apply/subsetP=> y; case/morphpreP=> Vi_y; move/set1P=> /= fy1.\n    have:= dprod_V; rewrite (bigD1 Ki) //=.\n    case/dprodP=> [[_ W _ defW] _ _ <-]; rewrite defW inE Vi_y /=.\n    rewrite -groupV -(mulg1 y^-1) -fy1 /f big_ltn ?ltn_0prime // conjg1 mulKg.\n    rewrite big_cond_seq /=.\n    apply big_prop=> [||i]; first 1 [exact: group1 | exact: groupM].\n    rewrite mem_index_iota; case/andP=> i_pos ltir.\n    rewrite -(bigdprodEgen defW) mem_gen //; apply/bigcupP.\n    have Rxi: x ^+ i \\in R by exact: groupX.\n    have PRxi: x ^+ i \\in P <*> R by apply: subsetP Rxi; exact: mulgen_subr.\n    have:= congr_group (ViJ _ Ki PRxi) => /= Vi_xi.\n    exists (Ki :^ (x ^+ i))%G; last by rewrite -Vi_xi memJ_conjg.\n    rewrite (actsP actsPR_K) // mxKi -val_eqE (sameP eqP normP).\n    apply/normP=> nVi_xi; have: x ^+ i \\in 'N_R(Vi Ki).\n      by rewrite inE Rxi; apply/normP; rewrite /= Vi_xi nVi_xi.\n    by rewrite regR_Vi // inE -order_dvd ox /dvdn modn_small ?eqn0Ngt ?i_pos.\n  have im_f: Morphism fM @* Vi Ki \\subset 'C_V(R).\n    rewrite morphimEdom /=.\n    apply/subsetP=> fy; case/imsetP=> y; case/setIP=> Vy _ -> {fy}.\n    rewrite inE Vf //= -sub1set centsC -xR cycle_subG /= cent_set1 inE.\n    rewrite conjg_set1 sub1set; apply/set1P.\n    have r1: r.-1.+1 = r by apply: prednK; exact: ltn_0prime.\n    rewrite /f -r1 {1}big_nat_recr big_nat_recl /= conjMg -conjgM -expgSr.\n    rewrite r1 -{2}ox order_expn1 conjg1 abV //; last first.\n      by rewrite memJ_norm ?(subsetP (subset_trans sRG nVG)) ?Vf.\n    congr (_ * _); pose Rbig := [fun z u => z ^ x = u].\n    apply: (big_rel Rbig) => /= [|z1 _ z2 _ <- <-|i _]; first exact: conj1g.\n    - exact: conjMg.\n    by rewrite -conjgM -expgSr.\n  have: isom (Vi Ki) (Morphism fM @* Vi Ki) (Morphism fM) by exact/isomP.\n  move/isom_card=> oVi.\n  have{im_f} im_f: Morphism fM @* Vi Ki = 'C_V(R).\n    apply/eqP; rewrite eqEcard im_f oCVR -oVi.\n    have: p.-group (Vi Ki) by apply: pgroupS pV; exact: subsetIl.\n    by case/pgroup_1Vpr=> [Vi1| [//]]; rewrite inE Vi1 eqxx andbF in mxKi.\n  rewrite oVi -oCVR -im_f; split=> //.\n  rewrite morphimEdom /= /f; apply/subsetP=> fy; case/imsetP=> y Vi_y ->{fy}.\n  apply big_prop => [||i _]; first 1 [exact: group1 | exact: groupM].\n  rewrite mem_gen // class_supportEr.\n  by apply/bigcupP; exists (x ^+ i); rewrite (groupX, memJ_conjg).\nhave oVi: forall Ki, Ki \\in mxK -> #|Vi Ki| = p.\n  move=> Ki mxKi.\n  have [||z _ ->]:= (atransP2 transPR) (Vi K1) (Vi Ki); try exact: mem_imset.\n  by rewrite cardJg; case/nRfix_CR: nK1R.\nhave: orbit 'JG%act R (Vi K1) \\subset Vi @: mxK.\n  rewrite acts_orbit ?mem_imset //.\n  apply: subset_trans actsPR; exact: mulgen_subr.\nhave nVjR: forall Kj, Kj \\in mxK ->\n  Vi Kj \\notin orbit 'JG%act R (Vi K1) -> Kj = [~: K, R]%G.\n- move=> Kj mxKj V1Rj; case/orP: (orbN (R \\subset 'N(Vi Kj))) => [nVjR|].\n    have defKj: 'C_K(Vi Kj) = Kj.\n      move: mxKj; rewrite inE; case/andP; case/maxgroupP.\n      case/andP=> sKjK _ mxKj ntVj; apply: mxKj; last first.\n        by rewrite subsetI sKjK centsC subsetIr.\n      rewrite properE subsetIl; apply: contra ntVj => cVjK.\n      rewrite -subG1 -trCVK subsetI subsetIl centsC.\n      apply: (subset_trans cVjK); exact: subsetIr.\n    have{nVjR} sKRVj: [~: K, R] \\subset Kj.\n      rewrite -defKj subsetI {1}commGC commg_subr nKR -ker_conj_aut.\n      rewrite -sub_morphim_pre ?comm_subG ?morphimR ?nViK // andTb.\n      rewrite (commG1P _) //; apply/centsP.\n      have: cyclic (Vi Kj) by rewrite cyclic_prime // oVi.\n      case/cyclicP=> v; move/group_inj=> -> a.\n      case/imsetP=> y _ -> b; case/imsetP=> z _ ->{a b}.\n      apply: (centsP (aut_cycle_commute v)); exact: Aut_aut.\n    apply/eqP; rewrite -val_eqE eq_sym eqEcard sKRVj.\n    rewrite -(leq_pmul2r (ltn_0prime q_pr)).\n    have iKj: #|K : Kj| = q.\n      by move: mxKj; rewrite inE; case/andP=> maxKj _; exact: p_maximal_index.\n    rewrite -{1}iKj LaGrange ?normal_sub ?nKiK //.\n    have: [~: K, R] \\x 'C_K(R) = K.\n      rewrite -comm_center_dir_prod //.\n      by rewrite oR coprime_sym prime_coprime // -p'natE.\n    case/dprodP=> _ defKR _ trKR_C.\n    rewrite -{1}defKR (TI_cardMg trKR_C) leq_pmul2l ?ltn_0group //=.\n    have Z_CK: Zgroup 'C_K(R) by apply: ZgroupS ZCHR; exact: setSI.\n    have:= forallP Z_CK 'C_K(R)%G; rewrite (@p_Sylow _ q) /=; last first.\n      rewrite pHallE subxx part_pnat ?eqxx //.\n      apply: pgroupS qK; exact: subsetIl.\n    case/cyclicP=> z defC; rewrite defC dvdn_leq ?ltn_0prime // order_dvd.\n    case/p_abelemP: abelemK => // _ -> //.\n    by rewrite -cycle_subG -defC subsetIl.\n  case/nRfix_CR=> // _ sCVj; case/nRfix_CR: nK1R => // _ sCV1.\n  suff trCVR: 'C_V(R) = 1 by rewrite -oCVR trCVR cards1 in pr_p.\n  pose inK1R Ki := Vi Ki \\in orbit 'JG%act R (Vi K1).\n  apply/trivgP; have:= dprod_V; rewrite (bigID inK1R).\n  case/dprodP=> [[W1 Wj defW1 defWj] _ _ <-].\n  rewrite defW1 defWj subsetI (subset_trans sCV1) /=; last first.\n    rewrite class_supportEr -(bigdprodEgen defW1) genS //.\n    apply/bigcupsP=> x Rx; apply/subsetP=> u V1xu.\n    have PRx: x \\in P <*> R by apply: subsetP Rx; exact: mulgen_subr.\n    apply/bigcupP; exists (K1 :^ x)%G; last by rewrite -ViJ.\n    by rewrite (actsP actsPR_K) // mxK1 /inK1R -ViJ // mem_imset.\n  apply: (subset_trans sCVj); rewrite class_supportEr -(bigdprodEgen defWj).\n  apply: genS; apply/bigcupsP=> x Rx; apply/subsetP=> u Vjxu.\n  have PRx: x \\in P <*> R by apply: subsetP Rx; exact: mulgen_subr.\n  apply/bigcupP; exists (Kj :^ x)%G; last by rewrite -ViJ.\n  rewrite (actsP actsPR_K) // mxKj; apply: contra V1Rj.\n  by move/orbit_transl=> <-; rewrite orbit_sym -ViJ // mem_imset.\nrewrite subEproper; case/predU1P=> [defV1R | ]; last first.\n  case/andP=> sV1R; case/subsetPn=> Vj; case/imsetP=> Kj mxKj ->{Vj} V1Rj.\n  have defmxV: Vi @: mxK = Vi Kj |: orbit 'JG%act R (Vi K1).\n    apply/eqP; rewrite eqEsubset andbC subUset sub1set mem_imset //.\n    rewrite sV1R; apply/subsetP=> V_i; case/imsetP=> Ki mxKi ->{V_i}.\n    rewrite inE orbC; apply/norP=> [[]]; move/nVjR=> -> //; case/set1P.\n    by move/nVjR: V1Rj => ->.\n  have ViV1: Vi K1 \\in Vi @: mxK by rewrite mem_imset.\n  rewrite odd_2'nat in oddG; have: 2^'.-group (P <*> R).\n    by  apply: pgroupS oddG; rewrite mulgen_subG sRG (subset_trans sPH).\n  move/(pnat_dvd (trans_div ViV1 transPR)).\n  rewrite defmxV cardsU1 (negPf V1Rj) oV1R -oR.\n  rewrite -odd_2'nat /= odd_2'nat; case/negP; exact: pgroupS oddG.\nhave:= sub0set 'C_(Vi @: mxK)(P | 'JG); rewrite subEproper.\ncase/predU1P=> [fix0|].\n  case/negP: nrp; rewrite eq_sym -dvdn_prime2 //; apply/eqnP.\n  have:= pgroup_fix_mod pP (subset_trans (mulgen_subl P R) actsPR).\n  by rewrite -{1}defV1R oV1R -fix0 cards0 (modn_small (ltn_0prime _)).\ncase/andP=> _; case/subsetPn=> Vj; case/setIP; case/imsetP=> Kj mxKj ->{Vj}.\nrewrite conjG_fix => nVjP.\nsuffices trVj: Vi Kj :=: 1 by rewrite -(oVi Kj) // trVj cards1 in pr_p.\napply/trivgP; rewrite -trCVK subsetI subsetIl centsC defKP.\nrewrite -ker_conj_aut -sub_morphim_pre ?comm_subG ?morphimR ?nViK // andTb.\nrewrite (commG1P _) //; apply/centsP=> a.\ncase/imsetP=> x _ -> b; case/imsetP=> y _ -> {a b}.\nhave: cyclic (Vi Kj) by rewrite cyclic_prime ?oVi.\ncase/cyclicP=> v; move/group_inj->.\napply: (centsP (aut_cycle_commute v)); exact: Aut_aut.\nQed.\n", "meta": {"author": "math-comp", "repo": "mathcomp-history-before-github", "sha": "19ef9415e2b509a2327f9ef704268ce8570b607c", "save_path": "github-repos/coq/math-comp-mathcomp-history-before-github", "path": "github-repos/coq/math-comp-mathcomp-history-before-github/mathcomp-history-before-github-19ef9415e2b509a2327f9ef704268ce8570b607c/attic/ssreflect/attic/ssreflect_82beta/theories/theorem3_6.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.22726380022969458}}
{"text": "From Categories Require Import Essentials.Notations.\nFrom Categories Require Import Essentials.Types.\nFrom Categories Require Import Essentials.Facts_Tactics.\nFrom Categories Require Import Category.Main.\nFrom Categories Require Import Functor.Main.\nFrom Categories Require Import Ext_Cons.Arrow.\nFrom Categories Require Import Basic_Cons.Terminal.\nFrom Categories Require Import Basic_Cons.Equalizer.\nFrom Categories Require Import Basic_Cons.Facts.Equalizer_Monic.\nFrom Categories Require Import Coq_Cats.Type_Cat.Card_Restriction.\nFrom Categories Require Import Archetypal.Discr.Discr Archetypal.Discr.NatFacts.\n\nFrom Categories Require Import Limits.GenProd_GenSum.\nFrom Categories Require Import Limits.Limit.\n\nLocal Open Scope functor_scope.\n\nSection GenProd_Eq_Complete.\n  Context {C : Category}.\n\n  Local Ltac ElimUnit := repeat match goal with [H : unit |- _] => destruct H end.\n\n  Section GenProd_Eq_Limits.\n    Context {J : Category}.\n\n    Context {OProd : ∀ (map : J → C), (Π map)%object}\n            {HProd : ∀ (map : (Arrow J) → C), (Π map)%object}\n            {Eqs : Has_Equalizers C}.\n\n    Section Limits_Exist.\n      Context (D : J --> C).\n\n      Local Notation DTarg := (fun f => (D _o (Targ f))%object) (only parsing).\n      Local Notation DF := Discr_Func (only parsing).\n      Local Notation OPR := (OProd (D _o)%object) (only parsing).\n      Local Notation HPR := (HProd DTarg) (only parsing).\n\n      Program Definition Projs_Cone : Cone (DF DTarg) :=\n        {|\n          cone_apex := Const_Func 1 (OPR _o tt);\n          cone_edge := {|Trans := fun f => Trans (cone_edge OPR) (Targ f)|}\n        |}.\n\n      Definition Projs : (OPR --> HPR)%morphism :=\n        Trans (LRKE_morph_ex HPR Projs_Cone) tt.\n\n      Program Definition D_imgs_Cone : Cone (DF DTarg) :=\n        {|\n          cone_apex := Const_Func 1 (OPR _o tt);\n          cone_edge :=\n            {|\n              Trans :=\n                fun f =>\n                  (D _a (Arr f) ∘ (Trans (cone_edge OPR) (Orig f)))%morphism\n            |}\n        |}.\n\n      Definition D_imgs : (OPR --> HPR)%morphism :=\n        Trans (LRKE_morph_ex HPR D_imgs_Cone) tt.\n\n      Program Definition Lim_Cone : Cone D :=\n        {|\n          cone_apex := Const_Func 1 (Eqs _ _ Projs D_imgs);\n          cone_edge :=\n            {|Trans :=\n                fun d => ((Trans (cone_edge OPR) d)\n                         ∘ (equalizer_morph (Eqs _ _ Projs D_imgs)))%morphism\n            |}\n        |}.\n\n      Next Obligation.\n      Proof.\n        simpl_ids.\n        set (W :=\n               f_equal\n                 (fun t :\n                        (((Const_Func 1 (((OProd (D _o)) _o) tt)%object)\n                             ∘ (Functor_To_1_Cat (Discr_Cat (Arrow J))))\n                          --> (DF DTarg))%nattrans\n                  =>\n                    ((Trans t {|Arr := h|})\n                       ∘ (equalizer_morph (Eqs _ _ Projs D_imgs)))%morphism\n                 )\n                 (cone_morph_com (LRKE_morph_ex HPR D_imgs_Cone))\n            ).\n        set (W' :=\n               f_equal\n                 (fun t :\n                        (((Const_Func 1 (((OProd (D _o)) _o) tt)%object)\n                             ∘ (Functor_To_1_Cat (Discr_Cat (Arrow J))))\n                          --> (DF DTarg))%nattrans\n                  =>\n                    (Trans t {|Arr := h|}\n                           ∘ (equalizer_morph (Eqs _ _ Projs D_imgs)))%morphism\n                 )\n                 (cone_morph_com (LRKE_morph_ex HPR Projs_Cone))\n            ).\n        clearbody W W'.\n        rewrite (assoc_sym _ _ ((D _a) h)).\n        cbn in *.\n        fold D_imgs in W.\n        fold Projs in W'.\n        rewrite W'.\n        etransitivity; [|symmetry; apply W].\n        clear W W'.\n        repeat rewrite assoc.\n        apply (\n            f_equal\n              (fun f =>\n                 compose f\n                         (Trans\n                            (HProd (fun f : Arrow J => (D _o)%object (Targ f)))\n                            {| Arr := h |}\n                         )\n              )\n          ).\n        apply (\n            f_equal (\n                fun f =>\n                  compose f\n                          (((HProd (fun f : Arrow J =>\n                                      (D _o)%object (Targ f))) _a) tt)\n              )\n          ).\n        apply equalizer_morph_com.\n      Qed.\n\n      Next Obligation.\n      Proof.\n        symmetry.\n        apply Lim_Cone_obligation_1.\n      Qed.\n\n      Section Every_Cone_Equalizes.\n        Context (Cn : Cone D).\n\n        Local Hint Extern 1 => progress cbn : core.\n\n        Program Definition Cone_to_DF_DCone : Cone (DF (D _o)%object) :=\n          {|\n            cone_apex := Cn;\n            cone_edge :=\n              @NatTrans_compose\n                _ _\n                (Cn ∘ (Functor_To_1_Cat (Discr_Cat J)))\n                (Discr_Func ((Cn ∘ (Functor_To_1_Cat J))%functor _o)%object) _\n                {|Trans := fun _ => id |} (Discretize (cone_edge Cn))\n          |}.\n\n        Definition From_Cone_to_OPR : (Cn --> OPR)%morphism :=\n          Trans (LRKE_morph_ex OPR Cone_to_DF_DCone) tt.\n\n        Program Definition Cone_to_DF_DTrag_Cone : Cone (DF DTarg) :=\n          {|\n            cone_apex := Cn;\n            cone_edge := {|Trans :=\n                             fun c => Trans (Discretize (cone_edge Cn)) (Targ c)|}\n          |}.\n\n        Program Definition Cone_Morph_From_Cone_to_DF_DTrag_Cone_to_HPR_1 :\n          Cone_Morph _ Cone_to_DF_DTrag_Cone HPR :=\n          {|\n            cone_morph :=\n              {|Trans :=\n                  fun f =>\n                    match f as u return (((Cn _o) u)%object --> (_ u))%morphism\n                    with\n                    | tt => (Projs ∘ From_Cone_to_OPR)%morphism\n                    end\n              |}\n          |}.\n\n        Next Obligation.\n        Proof.\n          ElimUnit.\n          do 2 rewrite From_Term_Cat.\n          auto.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          symmetry.\n          apply Cone_Morph_From_Cone_to_DF_DTrag_Cone_to_HPR_1_obligation_1.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          apply NatTrans_eq_simplify.\n          extensionality x; cbn.\n          unfold Projs, From_Cone_to_OPR.\n          set (H :=\n                 f_equal\n                   (fun w :\n                        ((Projs_Cone\n                            ∘ (Functor_To_1_Cat (Discr_Cat (Arrow J)))\n                         ) --> (DF DTarg))%nattrans\n                    =>\n                      (\n                        (Trans w x)\n                          ∘ (Trans\n                               (LRKE_morph_ex\n                                  (OProd (D _o)%object) Cone_to_DF_DCone) tt)\n                      )%morphism\n                   )\n                   (\n                     cone_morph_com\n                       (\n                         LRKE_morph_ex\n                           (HProd (fun f : Arrow J => (D _o)%object (Targ f)))\n                           Projs_Cone\n                       )\n                   )\n              );\n            clearbody H; cbn in H.\n          repeat rewrite assoc_sym in H.\n          repeat rewrite assoc_sym.\n          etransitivity; [|apply H]; clear H.\n          set (H :=\n                 f_equal\n                   (\n                     fun w :\n                         ((Cone_to_DF_DCone\n                             ∘ (Functor_To_1_Cat (Discr_Cat J))\n                          ) --> (DF (D _o)%object))%nattrans\n                     =>\n                       Trans w (Targ x)\n                   )\n                   (cone_morph_com (LRKE_morph_ex\n                                      (OProd (D _o)%object) Cone_to_DF_DCone))\n              ).\n          cbn in *.\n          rewrite From_Term_Cat in H; simpl_ids in H.\n          trivial.\n        Qed.\n\n        Program Definition Cone_Morph_From_Cone_to_DF_DTrag_Cone_to_HPR_2 :\n          Cone_Morph _ Cone_to_DF_DTrag_Cone HPR :=\n          {|\n            cone_morph :=\n              {|Trans :=\n                  fun f =>\n                    match f as u return (((Cn _o)%object u) --> (_ u))%morphism\n                    with\n                    | tt => (D_imgs ∘ From_Cone_to_OPR)%morphism\n                    end\n              |}\n          |}.\n\n        Next Obligation.\n        Proof.\n          ElimUnit.\n          do 2 rewrite From_Term_Cat; simpl_ids; trivial.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          symmetry.\n          apply Cone_Morph_From_Cone_to_DF_DTrag_Cone_to_HPR_2_obligation_1.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          apply NatTrans_eq_simplify.\n          extensionality x.\n          cbn.\n          unfold D_imgs, From_Cone_to_OPR.\n          set (H :=\n                 f_equal\n                   (\n                     fun w :\n                         ((D_imgs_Cone\n                             ∘ (Functor_To_1_Cat (Discr_Cat (Arrow J)))\n                          ) --> (DF DTarg))%nattrans\n                     =>\n                       (\n                         (Trans w x)\n                           ∘ (Trans\n                                (LRKE_morph_ex\n                                   (OProd (D _o)%object) Cone_to_DF_DCone)tt)\n                       )%morphism\n                   )\n                   (\n                     cone_morph_com\n                       (LRKE_morph_ex\n                          (HProd (fun f : Arrow J =>\n                                    (D _o)%object (Targ f))) D_imgs_Cone )\n                   )\n              );\n            clearbody H; cbn in H.\n          repeat rewrite assoc_sym in H.\n          repeat rewrite assoc_sym.\n          etransitivity; [|apply H]; clear H.\n          set (H :=\n                 f_equal\n                   (\n                     fun w :\n                         ((Cone_to_DF_DCone\n                             ∘ (Functor_To_1_Cat (Discr_Cat J))\n                          ) --> (DF (D _o)%object))%nattrans\n                     =>\n                       (((D _a) (Arr x)) ∘ (Trans w (Orig x)))%morphism\n                   )\n                   (cone_morph_com\n                      (LRKE_morph_ex (OProd (D _o)%object) Cone_to_DF_DCone))\n              );\n            clearbody H; cbn in H.\n          rewrite From_Term_Cat in H; simpl_ids in H.\n          repeat rewrite assoc_sym in H.\n          repeat rewrite assoc_sym.\n          etransitivity; [|apply H]; clear H.\n          cbn_rewrite <- (@Trans_com _ _ _ _ Cn).\n          rewrite From_Term_Cat; auto.\n        Qed.\n\n        Lemma From_Cone_to_Obj_Prod_Equalizes :\n          (Projs ∘ From_Cone_to_OPR = D_imgs ∘ From_Cone_to_OPR)%morphism.\n        Proof.\n          match goal with\n            [|- ?A = ?B] =>\n            change A with\n            (Trans Cone_Morph_From_Cone_to_DF_DTrag_Cone_to_HPR_1 tt);\n              change B with\n              (Trans Cone_Morph_From_Cone_to_DF_DTrag_Cone_to_HPR_2 tt)\n          end.\n          match goal with\n            [|- Trans ?A tt = Trans ?B tt] =>\n            assert (A = B) as Heq; [|rewrite Heq]; trivial\n          end.\n          apply (LRKE_morph_unique HPR).\n        Qed.\n\n        Definition From_Cone_to_Lim_Cone : (Cn --> Lim_Cone)%morphism :=\n          equalizer_morph_ex _  From_Cone_to_Obj_Prod_Equalizes.\n\n        Program Definition Cone_Morph_to_Lim_Cone : Cone_Morph D Cn Lim_Cone :=\n          {|\n            cone_morph :=\n              {|\n                Trans :=\n                  fun c =>\n                    match c as u return ((Cn _o u)%object --> _)%morphism with\n                      tt => From_Cone_to_Lim_Cone\n                    end\n              |}\n          |}.\n\n        Next Obligation.\n        Proof.\n          ElimUnit.\n          rewrite From_Term_Cat; auto.\n        Qed.\n\n        Next Obligation.\n          symmetry.\n          apply Cone_Morph_to_Lim_Cone_obligation_1.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          apply NatTrans_eq_simplify.\n          extensionality x.\n          unfold From_Cone_to_Lim_Cone.\n          cbn in *.\n          set (H :=\n                 equalizer_morph_ex_com\n                   (Eqs _ _ Projs D_imgs)\n                   From_Cone_to_Obj_Prod_Equalizes\n              );\n            clearbody H; cbn in H.\n          simpl_ids.\n          rewrite assoc.\n          match goal with\n            [|- _ = (?A ∘ ?B)%morphism] =>\n            replace B with From_Cone_to_OPR\n          end.\n          clear H.\n          unfold From_Cone_to_OPR.\n          set (H :=\n                 f_equal\n                   (\n                     fun w :\n                         ((Cone_to_DF_DCone ∘ (Functor_To_1_Cat (Discr_Cat J))\n                          ) --> (DF (D _o)%object))%nattrans\n                     =>\n                       Trans w x\n                   )\n                   (cone_morph_com (LRKE_morph_ex\n                                      (OProd (D _o)%object) Cone_to_DF_DCone))\n              ).\n          cbn in H.\n          rewrite From_Term_Cat in H; simpl_ids in H.\n          trivial.\n        Qed.\n\n      End Every_Cone_Equalizes.\n\n      Section Cone_Morph_to_Lim_Cone_Cone_Morph_to_OPR.\n        Context {Cn : Cone D} (h : Cone_Morph _ Cn Lim_Cone).\n\n        Program Definition Cone_Morph_to_Lim_Cone_Cone_Morph_to_OPR :\n          Cone_Morph _ (Cone_to_DF_DCone Cn) OPR :=\n          {|\n            cone_morph :=\n              {|\n                Trans :=\n                  fun c =>\n                    match c as u return\n                          (((Cn _o) u)\n                             --> (((OProd (D _o)) _o) u))%object%morphism\n                    with\n                    | tt => (equalizer_morph (Eqs _ _ Projs D_imgs)\n                                            ∘ Trans h tt)%morphism\n                    end\n              |}\n          |}.\n\n        Next Obligation.\n        Proof.\n          ElimUnit.\n          rewrite From_Term_Cat; auto.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          symmetry.\n          apply Cone_Morph_to_Lim_Cone_Cone_Morph_to_OPR_obligation_1.\n        Qed.\n\n        Next Obligation.\n        Proof.\n          apply NatTrans_eq_simplify.\n          extensionality x.\n          cbn.\n          set (H :=\n                 f_equal\n                   (fun w : ((Cn ∘ (Functor_To_1_Cat J)) --> D)%nattrans =>\n                      Trans w x)\n                   (cone_morph_com h)\n              ).\n          cbn in H.\n          simpl_ids in H.\n          rewrite From_Term_Cat; simpl_ids.\n          rewrite assoc in H.\n          trivial.\n        Qed.\n\n      End Cone_Morph_to_Lim_Cone_Cone_Morph_to_OPR.\n\n      Local Notation CMCOPR :=\n        Cone_Morph_to_Lim_Cone_Cone_Morph_to_OPR (only parsing).\n\n      Program Definition Lim_Cone_is_Limit : Limit D :=\n        {|\n          LRKE := Lim_Cone;\n          LRKE_morph_ex := Cone_Morph_to_Lim_Cone\n        |}.\n\n      Next Obligation.\n      Proof.\n        set (H := LRKE_morph_unique\n                    (OProd (D _o)%object) _ (CMCOPR h) (CMCOPR h')).\n        apply (\n            f_equal\n              (fun w : ((Cone_to_DF_DCone Cn) --> (OProd (D _o)%object))%nattrans =>\n                 Trans w tt)\n          ) in H.\n        cbn in H.\n        apply NatTrans_eq_simplify.\n        extensionality x; destruct x.\n        apply (@mono_morphism_monomorphic\n                 _ _ _ (@Equalizer_Monic _ _ _ _ _ (Eqs _ _ Projs D_imgs))).\n        trivial.\n      Qed.\n\n    End Limits_Exist.\n  End GenProd_Eq_Limits.\n\n  Section Restricted_Limits.\n    Context (P : Card_Restriction)\n            {CHRP : ∀ (A : Type) (map : A → C), (P A) → (Π map)%object}\n            {HE : Has_Equalizers C}.\n\n    Definition Restr_GenProd_Eq_Restr_Limits : Has_Restr_Limits C P :=\n      fun J D PJ PA =>\n        @Lim_Cone_is_Limit\n          J\n          (fun map => CHRP J map PJ)\n          (fun map => CHRP (Arrow J) map PA)\n          HE\n          D.\n\n  End Restricted_Limits.\n\n  Section Complete.\n    Context {CHAP : ∀ (A : Type) (map : A → C), (Π map)%object}\n            {HE : Has_Equalizers C}.\n\n    Definition GenProd_Eq_Complete : Complete C :=\n      fun J =>\n        Local_to_Global_Right\n          _\n          _\n          (fun D => @Lim_Cone_is_Limit J (CHAP J) (CHAP (Arrow J)) HE D).\n\n  End Complete.\n\nEnd GenProd_Eq_Complete.\n\nSection GenSum_CoEq_Complete.\n  Context {C : Category}.\n\n  Section GenSum_CoEq_CoLimits.\n    Context {J : Category}\n            {OSum : ∀ (map : J → C), (Σ map)%object}\n            {HSum : ∀ (map : (Arrow J) → C), (Σ map)%object}\n            {Eqs : Has_CoEqualizers C}.\n\n    Section Limits_Exist.\n      Context (D : J --> C).\n\n      Program Definition CoLim_CoCone_is_CoLimit : CoLimit D :=\n        @Lim_Cone_is_Limit\n          (C^op)\n          (J^op)\n          (fun map => GenSum_to_GenProd (OSum map))\n          (fun map => GenSum_to_GenProd (GenSum_IsoType (Arrow_OP_Iso J) HSum map))\n          Eqs\n          (Opposite_Functor D).\n\n    End Limits_Exist.\n  End GenSum_CoEq_CoLimits.\n\n  Section Restricted_CoLimits.\n    Context (P : Card_Restriction)\n            {CHRP : ∀ (A : Type) (map : A → C), (P A) → (Σ map)%object}\n            {HE : Has_CoEqualizers C}.\n\n    Definition Restr_GenSum_CoEq_Restr_CoLimits : Has_Restr_CoLimits C P :=\n      fun J D PJ PA =>\n        @CoLim_CoCone_is_CoLimit\n          J\n          (fun map => CHRP J map PJ)\n          (fun map => CHRP (Arrow J) map PA)\n          HE\n          D.\n\n  End Restricted_CoLimits.\n\n  Section CoComplete.\n    Context {CHAP : ∀ (A : Type) (map : A → C), (Σ map)%object}\n            {HE : Has_CoEqualizers C}.\n\n    Definition GenSum_CoEq_CoComplete : CoComplete C :=\n      fun J =>\n        Local_to_Global_Left\n          _\n          _\n          (fun D => @CoLim_CoCone_is_CoLimit J (CHAP J) (CHAP (Arrow J)) HE D).\n\n  End CoComplete.\n\nEnd GenSum_CoEq_Complete.\n", "meta": {"author": "amintimany", "repo": "Categories", "sha": "1839108875df0107fa4f6061c654003decda2d49", "save_path": "github-repos/coq/amintimany-Categories", "path": "github-repos/coq/amintimany-Categories/Categories-1839108875df0107fa4f6061c654003decda2d49/Limits/GenProd_Eq_Limits.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.22726379010066744}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Export malloc_lemmas. (*Exports the model (constants like WA , plus lemmas)*)\n\n(*Require Import malloc. needed for function and type names but not for compspecs \nUpdate: Some UPenn grad students proposed to abstract over function identifiers -\ndoing so in our setup makes ASIs source-program-independent!*)\n\nGlobal Open Scope funspec_scope.\n\nRecord MallocTokenAPD := {\n  malloc_token': share -> Z -> val -> mpred;\n  malloc_token'_valid_pointer: forall sh sz p, \n      malloc_token' sh sz p |-- valid_pointer p;\n  malloc_token'_local_facts:  forall sh sz p, \n      malloc_token' sh sz p |-- !! malloc_compatible sz p;\n}.\n\nRecord MallocFreeAPD := {\n  MF_Tok :> MallocTokenAPD;\n  mem_mgr: globals -> mpred;\n}.\n\nDefinition malloc_token {cs:compspecs} M (sh: share) (t: type) (p: val): mpred := \n   !! field_compatible t [] p && \n   malloc_token' M sh (sizeof t) p.\n\nLemma malloc_token_valid_pointer: forall {cs: compspecs} M sh t p, \n      malloc_token M sh t p |-- valid_pointer p.\nProof. intros. unfold malloc_token.\n apply andp_left2. apply malloc_token'_valid_pointer.\nQed.\n\n#[export] Hint Resolve malloc_token'_valid_pointer : valid_pointer.\n#[export] Hint Resolve malloc_token_valid_pointer : valid_pointer.\n\nLemma malloc_token_local_facts:  forall {cs: compspecs} M sh t p,\n      malloc_token M sh t p |-- !! (field_compatible t [] p /\\ malloc_compatible (sizeof t) p).\nProof. intros.\n unfold malloc_token.\n normalize. rewrite prop_and.\n apply andp_right. apply prop_right; auto.\n apply malloc_token'_local_facts.\nQed.\n\n#[export] Hint Resolve malloc_token'_local_facts : saturate_local.\n#[export] Hint Resolve malloc_token_local_facts : saturate_local.\n\nSection Malloc_ASI.\nVariable M: MallocFreeAPD.\nVariable mallocID:ident.\nVariable freeID:ident.\n\nDefinition malloc_spec' := \n   DECLARE (*_malloc*)mallocID\n   WITH n:Z, gv:globals\n   PRE [ size_t ]\n       PROP (0 <= n <= Ptrofs.max_unsigned - (WA+WORD))\n       PARAMS ((Vptrofs (Ptrofs.repr n))) GLOBALS (gv)\n       SEP ( mem_mgr M gv )\n   POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP ( mem_mgr M gv;\n             if eq_dec p nullval then emp\n             else (malloc_token' M Ews n p * memory_block Ews n p)).\n\nDefinition free_spec' :=\n DECLARE (*_free*)freeID\n   WITH n:Z, p:val, gv: globals\n   PRE [ tptr tvoid ]\n       PROP ()\n       PARAMS (p) GLOBALS (gv)\n       SEP (mem_mgr M gv;\n            if eq_dec p nullval then emp\n            else (malloc_token' M Ews n p * memory_block Ews n p))\n    POST [ Tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (mem_mgr M gv).\n\nDefinition Malloc_ASI:funspecs := [malloc_spec'; free_spec'].\nEnd Malloc_ASI.\n\nRecord MallocFree_R_APD := {\n  MF_Tok_R :> MallocTokenAPD;\n  mem_mgr_R: resvec -> globals -> mpred; (*changed order of arguments*)\n}.\n(*\nDefinition malloc_token_R {cs:compspecs} M (sh: share) (t: type) (p: val): mpred := \n   !! field_compatible t [] p && \n   malloc_token_R' M sh (sizeof t) p.\n\nLemma malloc_token_R_valid_pointer: forall {cs: compspecs} M sh t p, \n      malloc_token_R M sh t p |-- valid_pointer p.\nProof. intros. unfold malloc_token.\n apply andp_left2. apply malloc_token_R'_valid_pointer.\nQed.\n\n#[export] Hint Resolve malloc_token_R'_valid_pointer : valid_pointer.\n#[export] Hint Resolve malloc_token_R_valid_pointer : valid_pointer.\n\nLemma malloc_token_R_local_facts:  forall {cs: compspecs} M sh t p,\n      malloc_token_R M sh t p |-- !! (field_compatible t [] p /\\ malloc_compatible (sizeof t) p).\nProof. intros.\n unfold malloc_token_R.\n normalize. rewrite prop_and.\n apply andp_right. apply prop_right; auto.\n apply malloc_token_R'_local_facts.\nQed.\n\n#[export] Hint Resolve malloc_token_R'_local_facts : saturate_local.\n#[export] Hint Resolve malloc_token_R_local_facts : saturate_local.\n*)\nRequire Import VST.floyd.VSU.\n\nSection Malloc_R_ASI.\nVariable M: MallocFree_R_APD.\nVariable prefillID:ident.\nVariable tryprefillID:ident.\nVariable mallocID:ident.\nVariable freeID:ident.\n\nDefinition pre_fill_spec' :=\n DECLARE (*_pre_fill*) prefillID\n   WITH n:Z, p:val, gv:globals, rvec:resvec\n   PRE [ tuint, tptr tvoid ]\n       PROP (0 <= n <= maxSmallChunk /\\ malloc_compatible BIGBLOCK p)\n       PARAMS ((Vptrofs (Ptrofs.repr n)); p) GLOBALS (gv) \n       SEP (mem_mgr_R M rvec gv; memory_block Tsh BIGBLOCK p) \n    POST [ Tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (mem_mgr_R M (add_resvec rvec (size2binZ n) \n                                     (chunks_from_block (size2binZ n))) gv).\n\nDefinition try_pre_fill_spec' :=\n DECLARE (*_try_pre_fill*) tryprefillID\n   WITH n:Z, req:Z, rvec:resvec, gv:globals\n   PRE [ tuint, tint ]\n       PROP (0 <= n <= maxSmallChunk /\\ 0 <= req <= Int.max_signed)\n       PARAMS ((Vint (Int.repr n)); (Vint (Int.repr req))) GLOBALS (gv) \n       SEP (mem_mgr_R M rvec gv) \n   POST [ tint ] EX result: Z,\n     PROP ()\n     LOCAL (temp ret_temp (Vint (Int.repr result)))\n     SEP (mem_mgr_R M (add_resvec rvec (size2binZ n) result) gv).\n\nDefinition malloc_spec_R' := \n   DECLARE (*_malloc*)mallocID\n   WITH n:Z, gv:globals, rvec:resvec\n   PRE [ size_t ]\n       PROP (0 <= n <= Ptrofs.max_unsigned - (WA+WORD))\n       PARAMS ((* _nbytes *) (Vptrofs (Ptrofs.repr n))) GLOBALS (gv)\n       SEP ( mem_mgr_R M rvec gv)\n   POST [ tptr tvoid ] EX p:_, \n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP ( if guaranteed rvec n\n             then mem_mgr_R M (add_resvec rvec (size2binZ n) (-1)) gv *\n                  malloc_token' M Ews n p * memory_block Ews n p\n             else if eq_dec p nullval \n                  then mem_mgr_R M rvec gv\n                  else (if n <=? maxSmallChunk \n                        then (EX rvec':_, !!(eq_except rvec' rvec (size2binZ n))\n                                            && (mem_mgr_R M rvec' gv))\n                        else mem_mgr_R M rvec gv) *\n                       malloc_token' M Ews n p * memory_block Ews n p).\n\nDefinition free_spec_R' :=\n DECLARE (*_free*)freeID\n   WITH n:Z, p:val, gv:globals, rvec:resvec\n   PRE [ tptr tvoid ]\n       PROP ()\n       PARAMS (p) GLOBALS (gv)\n       SEP (mem_mgr_R M rvec gv;\n            if eq_dec p nullval then emp\n            else (malloc_token' M Ews n p * memory_block Ews n p))\n    POST [ Tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (if eq_dec p nullval \n            then mem_mgr_R M rvec gv\n            else if n <=? maxSmallChunk\n                 then mem_mgr_R M (add_resvec rvec (size2binZ n) 1) gv\n                 else mem_mgr_R M rvec gv).\n\nDefinition Malloc_R_ASI:funspecs := [pre_fill_spec'; try_pre_fill_spec'; malloc_spec_R'; free_spec_R'].\n\nDefinition ForgetR:MallocFreeAPD :=\n  Build_MallocFreeAPD (MF_Tok_R M) (fun gv => EX R, mem_mgr_R M R gv).\n\nLemma malloc_spec_R_sub i: funspec_sub (snd malloc_spec_R') (snd (malloc_spec' ForgetR i)).\nProof.\ndo_funspec_sub. destruct w as [n gv]. clear H.\nunfold mem_mgr.\nIntros rvec.\nExists (n, gv, rvec) emp. (* empty frame *)\nsimpl; entailer!.\nintros tau ? ?. \nset (p:=eval_id ret_temp tau).\nExists p; entailer!.\ndestruct (guaranteed rvec n) eqn:guar.\n- (* guaranteed *)\n  if_tac; auto.\n  Exists (add_resvec rvec (size2binZ n) (-1)); entailer!.\n  rewrite H4; entailer!.\n  Exists (add_resvec rvec (size2binZ n) (-1)); entailer!.\n- (* not guaranteed *)\n  bdestruct (n <=? maxSmallChunk).\n  + if_tac; auto. Exists rvec; entailer!. Intros rvec'; Exists rvec'; entailer!.\n  + if_tac; auto; Exists rvec; entailer!.\nQed.\n\nLemma free_spec_R_sub i: funspec_sub (snd free_spec_R') (snd (free_spec' ForgetR i)).\nProof.\ndo_funspec_sub. \ndestruct w as [[n p] gv]. clear H.\nunfold mem_mgr.\nIntros rvec. Exists (n,p,gv,rvec) emp.\nsimpl; entailer!.\nintros tau ?.\nif_tac.\nExists rvec; entailer!.\nbdestruct (n <=? maxSmallChunk).\n- (* small *)\n  Exists (add_resvec rvec (size2binZ n) 1); entailer!.\n- (* large *)\n  Exists rvec; entailer!.\nQed.\n\nVariable distinctIDs: list_norepet [prefillID; tryprefillID; mallocID; freeID].\n\nLemma MallocASI_sqsub_MallocR_ASI: \n      funspecs_sqsub Malloc_R_ASI (Malloc_ASI ForgetR mallocID freeID).\nProof. red; intros. simpl in H.\n  if_tac in H. inv H.\n  { eexists; split. simpl. rewrite 2 if_false. rewrite if_true by trivial.  reflexivity.\n    intros N; subst. inv distinctIDs. inv H2. apply H3. left; trivial.\n    intros N; subst. inv distinctIDs. apply H1. right; left; trivial.\n    apply (malloc_spec_R_sub mallocID).  }\n  if_tac in H. inv H.\n  { eexists; split. simpl. rewrite 3 if_false. rewrite if_true by trivial.  reflexivity.\n    intros N; subst. apply H0; trivial.\n    intros N; subst. inv distinctIDs. inv H3. apply H4. right; left; trivial.\n    intros N; subst. inv distinctIDs. inv H3. apply H2. do 2 right; left; trivial.\n    apply (free_spec_R_sub freeID). }\n  congruence.\n(*\n  repeat (if_tac in H. [ inv H; eexists; split; [ reflexivity |] |]).\n  repeat (if_tac in H; [ inv H; eexists; split; [ reflexivity |] |])\n  apply malloc_spec_R_sub. apply free_spec_R_sub. congruence.*)\nQed.\n\nEnd Malloc_R_ASI.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/memmgr/ASI_malloc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2272157606444501}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Cito.ADT.\n\nModule Make (Import E : ADT).\n\n  Require Import Platform.Cito.Inv.\n  Module Import InvMake := Make E.\n  Import Semantics.\n  Import SemanticsMake.\n  Require Import Platform.Cito.WordMap.\n  Require Import Coq.FSets.FMapFacts.\n  Module Properties := Properties WordMap.\n  Module Facts := Facts WordMap.\n\n  Require Import Platform.Cito.RepInv.\n\n  Module Make(R : RepInv E).\n    Module Import Inner := InvMake.Make(R).\n\n    Require Import Platform.Cito.LayoutHintsUtil.\n    Require Import Platform.Cito.SemanticsFacts5.\n\n    Lemma is_heap_Equal : forall h h',\n      WordMap.Equal h h'\n      -> is_heap h ===> is_heap h'.\n      intros; apply starL_permute; unfold heap_elements; intuition.\n      apply NoDupA_NoDup; apply WordMap.elements_3w.\n      apply NoDupA_NoDup; apply WordMap.elements_3w.\n\n      apply In_InA' in H0.\n      apply InA_In.\n      apply Properties.F.elements_mapsto_iff in H0.\n      apply Properties.F.elements_mapsto_iff.\n      eapply Properties.F.Equal_mapsto_iff; eauto.\n      apply Properties.F.Equal_sym; auto.\n\n      apply In_InA' in H0.\n      apply InA_In.\n      apply Properties.F.elements_mapsto_iff in H0.\n      apply Properties.F.elements_mapsto_iff.\n      eapply Properties.F.Equal_mapsto_iff; eauto.\n    Qed.\n\n  End Make.\n\nEnd Make.", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Cito/InvFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.22719056758932957}}
{"text": "Require Import oeuf.Common.\nRequire oeuf.StepLib.\nRequire Import Psatz.\n\nRequire Import oeuf.Utopia.\nRequire Import oeuf.Monads.\n\nRequire Export oeuf.HigherValue.\nRequire Import oeuf.AllValues.\nRequire Import oeuf.OpaqueOps.\nRequire Import oeuf.ListLemmas.\n\nInductive expr :=\n| Arg\n| Self\n| Var (i : nat)\n| Deref (e : expr) (off : nat)\n.\n\nInductive stmt :=\n| Skip\n| Seq (s1 : stmt) (s2 : stmt)\n| Call (dst : nat) (f : expr) (a : expr)\n| MkConstr (dst : nat) (tag : nat) (args : list expr)\n| Switch (dst : nat) (cases : list stmt)\n| MkClose (dst : nat) (f : function_name) (free : list expr)\n| OpaqueOp (dst : nat) (op : opaque_oper_name) (args : list expr)\n| Assign (dst : nat) (e : expr)\n.\n\nDefinition env := list (stmt * expr).\n\n\n(* Continuation-based step relation *)\n\nRecord frame := Frame {\n    arg : value;\n    self : value;\n    locals : list (nat * value)\n}.\n\nDefinition set f l v :=\n    Frame (arg f) (self f) ((l, v) :: locals f).\n\nDefinition local f l := lookup (locals f) l.\n\n\n\nInductive cont :=\n| Kseq (code : stmt) (k : cont)\n| Kswitch (k : cont)\n| Kreturn (ret : expr) (k : cont)\n| Kcall (dst : nat) (f : frame) (k : cont)\n| Kstop.\n\nInductive state :=\n| Run (s : stmt) (f : frame) (k : cont)\n| Return (v : value) (k : cont).\n\nInductive eval : frame -> expr -> value -> Prop :=\n| EArg : forall f,\n        eval f Arg (arg f)\n| ESelf : forall f,\n        eval f Self (self f)\n\n| EVar : forall f i v,\n        local f i = Some v ->\n        eval f (Var i) v\n\n| EDerefConstr : forall f e off tag args v,\n        eval f e (Constr tag args) ->\n        nth_error args off = Some v ->\n        eval f (Deref e off) v\n| EDerefClose : forall f e off fname free v,\n        eval f e (Close fname free) ->\n        nth_error free off = Some v ->\n        eval f (Deref e off) v\n.\n\nInductive sstep (E : env) : state -> state -> Prop :=\n| SSeq : forall s1 s2 f k,\n        sstep E (Run (Seq s1 s2) f k)\n                (Run s1 f (Kseq s2 k))\n\n| SConstrDone : forall dst tag args f k vs,\n        Forall2 (eval f) args vs ->\n        sstep E (Run (MkConstr dst tag args) f k)\n                (Run Skip (set f dst (Constr tag vs)) k)\n| SCloseDone : forall dst fname free f k vs,\n        Forall2 (eval f) free vs ->\n        sstep E (Run (MkClose dst fname free) f k)\n                (Run Skip (set f dst (Close fname vs)) k)\n| SOpaqueOpDone : forall dst op args f k vs v,\n        Forall2 (eval f) args vs ->\n        opaque_oper_denote_higher op vs = Some v ->\n        sstep E (Run (OpaqueOp dst op args) f k)\n                (Run Skip (set f dst v) k)\n\n| SMakeCall : forall dst fe ae f k  fname free arg body ret,\n        eval f fe (Close fname free) ->\n        eval f ae arg ->\n        nth_error E fname = Some (body, ret) ->\n        sstep E (Run (Call dst fe ae) f k)\n                (Run body (Frame arg (Close fname free) [])\n                    (Kreturn ret (Kcall dst f k)))\n\n(* NB: `Switch` still has an implicit target of `Arg` *)\n| SSwitchinate : forall dst cases f k  tag args case,\n        arg f = Constr tag args ->\n        nth_error cases tag = Some case ->\n        sstep E (Run (Switch dst cases) f k)\n                (Run case f (Kswitch k))\n\n| SAssign : forall dst src f k v,\n        eval f src v ->\n        sstep E (Run (Assign dst src) f k)\n                (Run Skip (set f dst v) k)\n\n| SContSeq : forall f s k,\n        sstep E (Run Skip f (Kseq s k))\n                (Run s f k)\n| SContSwitch : forall f k,\n        sstep E (Run Skip f (Kswitch k))\n                (Run Skip f k)\n| SContReturn : forall f ret k v,\n        eval f ret v ->\n        sstep E (Run Skip f (Kreturn ret k))\n                (Return v k)\n| SContCall : forall v dst f k,\n        sstep E (Return v (Kcall dst f k))\n                (Run Skip (set f dst v) k)\n.\n\n\n\nDefinition sstar BE := StepLib.sstar (sstep BE).\nDefinition SStarNil := @StepLib.SStarNil state.\nDefinition SStarCons := @StepLib.SStarCons state.\n\nDefinition splus BE := StepLib.splus (sstep BE).\nDefinition SPlusOne := @StepLib.SPlusOne state.\nDefinition SPlusCons := @StepLib.SPlusCons state.\n\n\n\nRequire Import oeuf.Metadata.\nRequire oeuf.Semantics.\n\n\nDefinition prog_type : Type := env * list metadata.\nDefinition val_level := VlHigher.\nDefinition valtype := value_type val_level.\n\nInductive is_callstate (prog : prog_type) : valtype -> valtype -> state -> Prop :=\n| IsCallstate : forall fname free av body ret,\n        nth_error (fst prog) fname = Some (body, ret) ->\n        let fv := Close fname free in\n        HigherValue.public_value (snd prog) fv ->\n        HigherValue.public_value (snd prog) av ->\n        is_callstate prog fv av\n            (Run body\n                 (Frame av fv [])\n                 (Kreturn ret Kstop)).\n\nInductive final_state (prog : prog_type) : state -> valtype -> Prop :=\n| FinalState : forall v,\n        HigherValue.public_value (snd prog) v ->\n        final_state prog (Return v Kstop) v.\n\nDefinition initial_env (prog : prog_type) : env := fst prog.\n\nDefinition semantics (prog : prog_type) : Semantics.semantics :=\n  @Semantics.Semantics_gen state env val_level\n                 (is_callstate prog)\n                 (sstep)\n                 (final_state prog)\n                 (initial_env prog).\n\n\n\n(*\nDefinition prog_type : Type := env * list metadata.\n\nInductive initial_state (prog : prog_type) : state -> Prop :=.\n\nInductive final_state (prog : prog_type) : state -> Prop :=\n| FinalState : forall v, final_state prog (Return v Kstop).\n\nDefinition initial_env (prog : prog_type) : env := fst prog.\n\nDefinition semantics (prog : prog_type) : Semantics.semantics :=\n  @Semantics.Semantics_gen state env\n                 (sstep)\n                 (initial_state prog)\n                 (final_state prog)\n                 (initial_env prog).\n\n*)\n\n(*\n * Mutual recursion/induction schemes for expr\n *)\n\nDefinition stmt_rect_mut\n        (P : stmt -> Type)\n        (Pl : list stmt -> Type)\n    (HSkip :    P Skip)\n    (HSeq :     forall s1 s2, P s1 -> P s2 -> P (Seq s1 s2))\n    (HCall :    forall dst f a, P (Call dst f a))\n    (HConstr :  forall dst tag args, P (MkConstr dst tag args))\n    (HSwitch :  forall dst cases, Pl cases -> P (Switch dst cases))\n    (HClose :   forall dst fname free, P (MkClose dst fname free))\n    (HOpaqueOp : forall dst op args, P (OpaqueOp dst op args))\n    (HAssign :  forall dst src, P (Assign dst src))\n    (Hnil :     Pl [])\n    (Hcons :    forall i is, P i -> Pl is -> Pl (i :: is))\n    (i : stmt) : P i :=\n    let fix go i :=\n        let fix go_list is :=\n            match is as is_ return Pl is_ with\n            | [] => Hnil\n            | i :: is => Hcons i is (go i) (go_list is)\n            end in\n        match i as i_ return P i_ with\n        | Skip => HSkip\n        | Seq s1 s2 => HSeq s1 s2 (go s1) (go s2)\n        | Call dst f a => HCall dst f a\n        | MkConstr dst tag args => HConstr dst tag args\n        | Switch dst cases => HSwitch dst cases (go_list cases)\n        | MkClose dst fname free => HClose dst fname free\n        | OpaqueOp dst op args => HOpaqueOp dst op args\n        | Assign dst src => HAssign dst src\n        end in go i.\n\n(* Useful wrapper for `expr_rect_mut with (Pl := Forall P)` *)\nDefinition stmt_ind' (P : stmt -> Prop)\n    (HSkip :    P Skip)\n    (HSeq :     forall s1 s2, P s1 -> P s2 -> P (Seq s1 s2))\n    (HCall :    forall dst f a, P (Call dst f a))\n    (HConstr :  forall dst tag args, P (MkConstr dst tag args))\n    (HSwitch :  forall dst cases, Forall P cases -> P (Switch dst cases))\n    (HClose :   forall dst fname free, P (MkClose dst fname free))\n    (HOpaqueOp : forall dst op args, P (OpaqueOp dst op args))\n    (HAssign :  forall dst src, P (Assign dst src))\n    (i : stmt) : P i :=\n    ltac:(refine (@stmt_rect_mut P (Forall P)\n        HSkip HSeq HCall HConstr HSwitch HClose HOpaqueOp HAssign _ _ i); eauto).\n\n\n\nDefinition all_dests :=\n    let fix go s :=\n        let fix go_list ps :=\n            match ps with\n            | [] => []\n            | s :: ps => go s ++ go_list ps\n            end in\n        match s with\n        | Skip => []\n        | Seq s1 s2 => go s1 ++ go s2\n        | Call dst _ _ => [dst]\n        | MkConstr dst _ _ => [dst]\n        | Switch _ cases => go_list cases\n        | MkClose dst _ _ => [dst]\n        | OpaqueOp dst _ _ => [dst]\n        | Assign dst _ => [dst]\n        end in go.\n\nDefinition all_dests_list :=\n    let go := all_dests in\n    let fix go_list ps :=\n        match ps with\n        | [] => []\n        | s :: ps => go s ++ go_list ps\n        end in go_list.\n\nLtac refold_all_dests :=\n    fold all_dests_list in *.\n\nDefinition cont_all_dests :=\n    let go := all_dests in\n    let fix go_cont k :=\n        match k with\n        | Kseq s k => go s ++ go_cont k\n        | Kswitch k => go_cont k\n        | Kreturn _ k => go_cont k\n        | Kcall dst _ k => []\n        | Kstop => []\n        end in go_cont.\n\n\n\nDefinition dests_ok :=\n    let fix go s :=\n        let fix go_list ps :=\n            match ps with\n            | [] => True\n            | s :: ps => go s /\\ go_list ps\n            end in\n        match s with\n        | Seq s1 s2 => go s1 /\\ go s2 /\\ disjoint (all_dests s1) (all_dests s2)\n        | Switch _ cases => go_list cases\n        | _ => True\n        end in go.\n\nDefinition dests_ok_list :=\n    let go := dests_ok in\n    let fix go_list ps :=\n        match ps with\n        | [] => True\n        | s :: ps => go s /\\ go_list ps\n        end in go_list.\n\nLtac refold_dests_ok :=\n    fold dests_ok_list in *.\n\nDefinition check_dests_ok s : { dests_ok s } + { ~ dests_ok s }.\ninduction s using stmt_rect_mut with\n    (Pl := fun cases =>\n        { dests_ok_list cases } + { ~ dests_ok_list cases });\ntry solve [left; constructor].\n\n- (* Seq *)\n  destruct IHs1; [ | right; intro; simpl in *; intuition ].\n  destruct IHs2; [ | right; intro; simpl in *; intuition ].\n  destruct (disjoint_dec eq_nat_dec (all_dests s1) (all_dests s2));\n    [ | right; intro; simpl in *; intuition ].\n  left. simpl. auto.\n\n- (* Switch *)\n  destruct IHs; [ | right; assumption ].\n  left. assumption.\n\n- (* cons *)\n  destruct IHs; [ | right; inversion 1; eauto ].\n  destruct IHs0; [ | right; inversion 1; eauto ].\n  left. constructor; eauto.\nDefined.\n\nDefinition cont_dests_ok :=\n    let go := dests_ok in\n    let fix go_cont k :=\n        match k with\n        | Kseq s k => go s /\\ go_cont k /\\\n                disjoint (all_dests s) (cont_all_dests k)\n        | Kswitch k => go_cont k\n        | Kreturn _ k => go_cont k\n        | Kcall _ _ k => go_cont k\n        | Kstop => True\n        end in go_cont.\n\nDefinition state_dests_ok :=\n    let go := dests_ok in\n    let go_cont := cont_dests_ok in\n    let go_state s :=\n        match s with\n        | Run s _ k => go s /\\ go_cont k /\\\n                disjoint (all_dests s) (cont_all_dests k)\n        | Return _ k => go_cont k\n        end in go_state.\n\nLemma step_dests_ok : forall E s s',\n    Forall (fun f => dests_ok (fst f)) E ->\n    state_dests_ok s ->\n    sstep E s s' ->\n    state_dests_ok s'.\nintros0 Henv II Hstep; invc Hstep;\nsimpl in *; refold_all_dests; refold_dests_ok.\n\n- repeat break_and. on _, invc_using disjoint_app_inv_l.\n  intuition. eauto using disjoint_app_r.\n\n- intuition.\n- intuition.\n- intuition.\n- fwd eapply Forall_nth_error; eauto. simpl in *. intuition.\n\n- break_and.\n  on (arg _ = _), fun H => clear H.\n  generalize dependent cases. make_first cases. induction cases; intros; simpl in *.\n  + destruct tag; discriminate.\n  + destruct tag; simpl in *.\n    * inject_some. on _, invc_using disjoint_app_inv_l. intuition.\n    * on _, invc_using disjoint_app_inv_l. break_and. eapply IHcases; eauto.\n\n- intuition.\n- intuition.\n- intuition.\n- intuition.\n- intuition.\nQed.\n\n\n\nLemma all_dests_list_disjoint : forall xs cases n case,\n    disjoint xs (all_dests_list cases) ->\n    nth_error cases n = Some case ->\n    disjoint xs (all_dests case).\ninduction cases; intros0 Hdj Hnth; simpl in *.\n- destruct n; discriminate.\n- on _, invc_using disjoint_app_inv_r.\n  destruct n; simpl in *.\n  + inject_some. auto.\n  + eapply IHcases; eauto.\nQed.\n\n\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/FlatStop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2271547297395536}}
{"text": "(* Semantics and Properties of the monads *)\nRequire Import Events.\nRequire Import customSmallstep.\nRequire Import Integers.\n\nRequire Import common.\nRequire Import monad.\nRequire Import monad_impl.\nRequire Import ASMinterpreter.\nRequire Import jit.\n\n\n(** * Loop Semantics (deprecated)  *)\n(* building the semantics of a monad designed to be looped *)\nInductive loop_step {mstate prog_state:Type} (prog:prog_state -> free (prog_state * trace)) (i:monad_impl mstate) :\n  unit -> (prog_state * mstate) -> trace -> (prog_state * mstate) -> Prop :=\n| loop:\n    forall ps1 ps2 t ms1 ms2\n      (EXEC_STEP: (exec (prog ps1)) i ms1 = SOK (ps2, t) ms2),\n      loop_step prog i tt (ps1, ms1) t (ps2, ms2).\n\n(* Extending the notion of initial state, from a prog_state definition, to a full state (with monad state) *)\nInductive extend_init {mstate prog_state:Type} (init:prog_state -> Prop) (i:monad_impl mstate) :\n  (prog_state * mstate) -> Prop :=\n| init_extend:\n    forall ps\n      (INIT: init ps),\n      extend_init init i (ps, init_state i).\n\n(* extending to any monad state *)\nInductive extend_final {mstate prog_state:Type} (final:prog_state -> int -> Prop) (i:monad_impl mstate):\n  (prog_state * mstate) -> int -> Prop :=\n| final_extend:\n    forall ps val ms\n      (FINAL: final ps val),\n      extend_final final i (ps, ms) val.\n\n(* Loop Semantics given an implem *)\n(* prog has the type that the jit_step would be typed with *)\nDefinition loop_sem {mstate prog_state:Type} (prog:prog_state -> free (prog_state * trace)) (i:monad_impl mstate) (init:prog_state -> Prop) (final:prog_state -> int -> Prop): semantics :=\n  Semantics_gen (loop_step prog i) (extend_init init i) (extend_final final i) tt.\n\n(* Forward sim proof *)\nInductive f_match {istate jstate prog_state:Type} (i:monad_impl istate) (j:monad_impl jstate) (R:refines i j): unit -> (prog_state * istate) -> (prog_state * jstate) -> Prop :=\n| f_m : forall ps mi mj\n          (MATCH: (match_states i j R) mi mj),\n    f_match i j R tt (ps, mi) (ps, mj).\n\nInductive order : unit -> unit -> Prop := .\nLemma wfounded:\n  well_founded order.\nProof.\n  unfold well_founded. intros. destruct a. constructor. intros. inversion H.\nQed.\n\nLemma forward_prim:\n  forall (A istate jstate R:Type) (i:monad_impl istate) (j:monad_impl jstate) a mi mi' mj\n    (Ref: refines i j)\n    (p: primitive R)\n    (MATCH: match_states i j Ref mi mj)\n    (EXEC: exec_prim p i mi = SOK a mi'),\n  exists mj', exec_prim p j mj = SOK a mj' /\\\n         (match_states i j Ref) mi' mj'.\nProof.\n  intros A istate jstate R i j a mi mi' mj Ref p MATCH EXEC.\n  destruct p; inv EXEC.\n  - rename H0 into Hsave. destruct a. (* save *)\n    eapply (match_save i j Ref) in Hsave; eauto.\n  - rename H0 into Hload. destruct a.       (* load *)\n    eapply (match_load i j Ref) in Hload; eauto.\n  - rename H0 into Hpusharg. destruct a. (* pusharg *)\n    eapply (match_memset i j Ref) in Hpusharg; eauto.\n  - rename H0 into Hpoparg. destruct a. (* poparg *)\n    eapply (match_memget i j Ref) in Hpoparg; eauto.\n  - rename H0 into Hclosesf. destruct a. (* closesf *)\n    eapply (match_closesf i j Ref) in Hclosesf; eauto.\n  - rename H0 into Hopensf. (* opensf *)\n    eapply (match_opensf i j Ref) in Hopensf; eauto.\n  - rename H0 into Hpushirsf. destruct a. (* pushirsf *)\n    eapply (match_pushirsf i j Ref) in Hpushirsf; eauto.\n  - rename H0 into Hinstall_code. destruct a. (* install_code *)\n    eapply (match_install_code i j Ref) in Hinstall_code; eauto.\n  - rename H0 into Hload_code. destruct a. (* load_call_code *)\n    eapply (match_load_code i j Ref) in Hload_code; eauto.\n  - rename H0 into Hcheck_compiled.  (* check_compiled *)\n    eapply (match_check_compiled i j Ref) in Hcheck_compiled; eauto.\nQed.\n\nLemma forward_diagram:\n  forall {A istate jstate:Type} (i:monad_impl istate) (j:monad_impl jstate) a mi mi' mj\n    (R: refines i j)\n    (m: free A)\n    (MATCH: (match_states i j R) mi mj)\n    (EXEC: exec m i mi = SOK a mi'),\n  exists mj', exec m j mj = SOK a mj' /\\\n         (match_states i j R) mi' mj'.\nProof.\n  intros A istate jstate i j a mi mi' mj R m MATCH EXEC.\n  generalize dependent mi. generalize dependent mi'. generalize dependent mj. generalize dependent a.\n  induction m; intros; inversion EXEC; simpl; subst.\n  - exists mj. split; auto.          (* ret *)\n  - rename H1 into EXEC_CONT. repeat sdo_ok. simpl in EXEC.\n    unfold sbind in EXEC. rewrite HDO in EXEC. rewrite EXEC_CONT in EXEC. inv EXEC.\n    eapply forward_prim in HDO; eauto. destruct HDO as [j0 [EXEC_PRIM MATCH']].\n    specialize (H r a j0 mi' i0 MATCH' EXEC_CONT).\n    destruct H as [mj' [EXEC_CONT' MATCH'']].\n    exists mj'. unfold sbind. rewrite EXEC_PRIM. split; auto.\nQed.\n\nTheorem loop_refinement:\n  forall (prog_state istate jstate:Type) (prog:prog_state -> free (prog_state * trace))  init final\n    (i:monad_impl istate) (j:monad_impl jstate)\n    (R: refines i j),\n    forward_simulation\n      (loop_sem prog i init final)\n      (loop_sem prog j init final).\nProof.\n  intros prog_state istate jstate prog init final i j R.\n  eapply Forward_simulation.\n  - apply wfounded.\n  - intros s1 H. exists tt. simpl in H. inversion H.\n    exists (ps, init_state j). split; simpl.\n    + constructor. auto.\n    + eapply (f_m i j R). apply (match_init i j R).\n  - intros tt s1 s2 r H H0. simpl in s1, s2. destruct s1 as [ps1 mi1]. destruct s2 as [ps mi2].\n    inversion H. subst. simpl. constructor. inversion H0. auto.\n  - intros s1 t s1' H i0 s2 H0. simpl in s1, s1'. destruct s1 as [ps1 mi1]. destruct s1' as [ps1' mi1'].\n    inversion H0. subst. exists tt. inversion H. subst.\n    eapply forward_diagram in EXEC_STEP; eauto.\n    destruct EXEC_STEP as [mj' [EXEC' MATCH']].\n    exists (ps1', mj'). split; auto.\n    + left. apply plus_one. constructor. auto.\n    + constructor. auto.\nQed.\n\n\n(** * Giving Semantics the Non-Atomic step of a NASM  *)\nRecord na_spec {state I R:Type}: Type :=\n  mk_spec {\n      load_: state -> free I;         \n      step_: I -> free (trace * itret R I);\n      ret_ : state -> R -> free state\n    }.\n(* I defines the type of intermediate states *)\n(* R represents the return value type of the internal iteration *)\n\n\n(** * Unfolded Semantics  *)\nInductive unf_state {S I:Type} :=\n| EXT: S -> unf_state       (* when we're executing the main program *)\n| INT: S -> I -> unf_state.       (* when we're executing the non-atomic loop. we remember the calling S state *)\n\n  \nInductive unf_step {state mstate I R:Type} (prog: @nasm_prog state) (impl:monad_impl mstate) (spec: @na_spec state I R):\n  unit -> (@unf_state state I * mstate) -> trace -> (@unf_state state I * mstate) -> Prop :=\n| ext_step:\n    forall (s1 s2:state) t ms1 ms2 symbmon\n      (ATOMIC: prog s1 = Ato symbmon)\n      (EXEC_STEP: exec symbmon impl ms1 = SOK (t, s2) ms2),\n      unf_step prog impl spec tt (EXT s1, ms1) t (EXT s2, ms2)\n| loop_start:\n    forall s1 ms1 start ms2\n      (RUN: prog s1 = LoadAndRun)\n      (LOAD: exec (load_ spec s1) impl ms1 = SOK start ms2),\n      unf_step prog impl spec tt (EXT s1, ms1) E0 (INT s1 start, ms2)\n| int_step:\n    forall i1 t i2 ms1 ms2 call_state\n      (EXEC_STEP: exec (step_ spec i1) impl ms1 = SOK (t, Halt i2) ms2),\n      unf_step prog impl spec tt (INT call_state i1, ms1) t (INT call_state i2, ms2)\n| loop_end:\n    forall i1 t r s2 ms1 ms2 ms3 call_state\n      (EXEC_END: exec (step_ spec i1) impl ms1 = SOK (t, Done r) ms2)\n      (EXEC_RET: exec (ret_ spec call_state r) impl ms2 = SOK (s2) ms3),\n      unf_step prog impl spec tt (INT call_state i1, ms1) t (EXT s2, ms3).\n\n(* Liftinf initial and final from state to unf_state *)\nInductive init_unf_state {state mstate I:Type} (init:state -> Prop) (impl:monad_impl mstate) : (@unf_state state I  * mstate) -> Prop :=\n| init_unf: forall s\n              (INIT: init s),\n    init_unf_state init impl (EXT s, init_state impl).\n\nInductive final_unf_state {state mstate I:Type} (final:state -> int -> Prop) (impl:monad_impl mstate) : (@unf_state state I * mstate) -> int -> Prop :=\n| final_unf: forall s ms r\n               (FINAL: final s r),\n    final_unf_state final impl (EXT s, ms) r.\n\nDefinition unf_sem {state mstate I R:Type} (prog: @nasm_prog state) (impl:monad_impl mstate) (spec: @na_spec state I R) (init:state->Prop) (final:state->int->Prop): semantics :=\n  Semantics_gen (unf_step prog impl spec) (init_unf_state init impl) (final_unf_state final impl) tt.\n\n\n(** * Refinement Simulation  *)\n(* Forward sim proof *)\n\nTheorem refinement:\n  forall (state istate jstate I R:Type) (prog: @nasm_prog state) init final\n    (i: monad_impl istate) (j:monad_impl jstate) (spec: @na_spec state I R) \n    (Ref: refines i j),\n    forward_simulation\n      (unf_sem prog i spec init final)\n      (unf_sem prog j spec init final).\nProof.\n  intros state istate jstate I R prog init final i j spec Ref.\n  eapply Forward_simulation.\n  - apply wfounded.\n  - intros s1 H. exists tt. simpl in H. inversion H.\n    exists (EXT s, init_state j). split; simpl.\n    + constructor. auto.\n    + eapply (f_m i j Ref). apply (match_init i j Ref).\n  - intros tt s1 s2 r H H0. simpl in s1, s2. destruct s1 as [ps1 mi1]. destruct s2 as [ps mi2].\n    inversion H. subst. simpl. inversion H0. subst. constructor. auto.\n  - intros s1 t s1' STEP i0 s2 MATCH. simpl in s1, s1'. destruct s1 as [ps1 mi1]. destruct s1' as [ps1' mi1'].\n    inversion MATCH. subst. exists tt. inversion STEP; subst.\n    + eapply forward_diagram in EXEC_STEP; eauto.\n      destruct EXEC_STEP as [mj' [EXEC' MATCH']].\n      exists (EXT s2, mj'). split; auto.\n      * left. apply plus_one. eapply ext_step; eauto.\n      * constructor. auto.\n    + eapply forward_diagram in LOAD; eauto.\n      destruct LOAD as [mj' [EXEC' MATCH']].\n      exists (INT s1 start, mj'). split; auto.\n      * left. apply plus_one. eapply loop_start; eauto.\n      * constructor. auto.\n    + eapply forward_diagram in EXEC_STEP; eauto.\n      destruct EXEC_STEP as [mj' [EXEC' MATCH']].\n      exists (INT call_state i2, mj'). split; auto.\n      * left. apply plus_one. eapply int_step; eauto.\n      * constructor. auto.\n    + eapply forward_diagram in EXEC_END; eauto.\n      destruct EXEC_END as [mj' [EXEC' MATCH']].\n      eapply forward_diagram in EXEC_RET; eauto.\n      destruct EXEC_RET as [mj'' [EXEC'' MARCH'']].\n      exists (EXT s2, mj''). split; auto.\n      * left. apply plus_one. eapply loop_end; eauto.\n      * constructor. auto.\nQed.\n\n\n", "meta": {"author": "Aurele-Barriere", "repo": "JIThm", "sha": "ad3ae5a3d6759a070195815e321df1b372d982b9", "save_path": "github-repos/coq/Aurele-Barriere-JIThm", "path": "github-repos/coq/Aurele-Barriere-JIThm/JIThm-ad3ae5a3d6759a070195815e321df1b372d982b9/coqjit/monad_properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2271547297395536}}
{"text": "(*\n * Copyright (c) 2009-2011, Andrew Appel, Robert Dockins and Aquinas Hobor.\n *\n *)\n\n(* A portion of this file was developed by Le Xuan Bach *)\n\nRequire Import msl.base.\nRequire Import msl.sepalg.\nRequire Import msl.functors.\nRequire Import msl.sepalg_functors.\n\nDefinition midObj {A} {JA: Join A} (a : A) : Prop := ~identity a /\\ ~ full a.\n\nDefinition ijoinable A {JA: Join A} : Type := {sh : A & midObj sh}.\n\nDefinition ijoin {A} {JA: Join A} (j1 j2 j3 : ijoinable A) : Prop :=\n  match (j1, j2, j3) with \n  (existT t1 _, existT t2 _, existT t3 _) => join t1 t2 t3\n  end.\n\nLemma ijoin_eq {A} {JA: Join A}{PA: Perm_alg A} : forall j1 j2 j3 j3',\n  ijoin j1 j2 j3 ->\n  ijoin j1 j2 j3' ->\n  j3 = j3'.\nProof.\n  intros.\n  icase j1; icase j2; icase j3; icase j3'.\n  unfold ijoin in *.\n  apply existT_ext.\n  eapply join_eq; eauto.\nQed.\n\nLemma ijoin_com {A} {JA: Join A}{PA: Perm_alg A} : forall j1 j2 j3,\n  ijoin j1 j2 j3 -> ijoin j2 j1 j3.\nProof with auto.\n  intros.\n  icase j1; icase j2; icase j3.\n  red in H; red.\n  apply join_comm...\nQed.\n\nLemma ijoin_assoc {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A} : forall a b c d e,\n  ijoin a b d -> \n  ijoin d c e -> \n  {f : ijoinable A | ijoin b c f /\\ ijoin a f e}.\nProof with auto.\n  intros.\n  icase a; icase b; icase c; icase d; icase e.\n  unfold ijoin in *.\n  destruct (join_assoc H H0) as [f [? ?]].\n  assert ((~identity f) /\\ (~full f)).\n    unfold midObj in *.\n    split.\n    intro.\n    generalize (split_identity _ _ H1 H3); intro.\n    tauto.\n    intro.\n    spec H3 x. spec H3. exists x3...\n    spec H3 f x3 H2. subst x3.\n    apply unit_identity in H2.\n    tauto.\n  exists (existT midObj f H3).\n  split...\nQed.\n\nLemma ijoin_canc {A}  {JA: Join A}{SA: Sep_alg A}{CA: Canc_alg A}: forall a a' b c,\n  ijoin a b c -> \n  ijoin a' b c ->\n  a = a'.\nProof with auto.\n  intros.\n  icase a; icase a'; icase b; icase c.\n  unfold ijoin in *.\n  apply existT_ext.\n  eapply join_canc; eauto.\nQed.\n\nLemma ijoin_identity1 {A}  {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}: forall a b,\n  ijoin a b b ->\n  False.\nProof with auto.\n  intros.\n  icase a; icase b.\n  destruct m. apply n.\n  apply (unit_identity x0).\n  apply H.\nQed.\n\nLemma ijoin_identity2 {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}{DA: Disj_alg A}: forall a b,\n  ijoin a a b ->\n  False.\nProof with auto.\n  intros.\n  icase a. icase b.\n  destruct m; destruct m0.\n  assert (x=x0). apply join_self. apply H. subst x0.\n  assert (join x x x) by (apply H).\n  apply unit_identity in H0.\n  contradiction.\nQed.\n\nSection CombineJoin.\n\nVariable A : Type.\nVariable JA: Join A.\nVariable pa_A : Perm_alg A.\nVariable sa_A : Sep_alg A.\nVariable ca_A : Canc_alg A.\n\n(* We either need an explicit top witness or some kind of axiom of choice\n    (if not here, then in sa_fun or somesuch).  It is a little ugly this way but\n    I don't see any other way around. Aquinas *)\nVariable A_top : A.\nVariable A_top_full : full A_top.\n\nVariable T1 : Type.\nVariable T2 : Type.\nVariable J1: Join T1.\nVariable pa_T1: Perm_alg T1.\nVariable sa_T1: Sep_alg T1.\n\nVariable combjoin : T1 -> T1 -> T2 -> Prop.\n\nVariable combjoin_eq : forall v1 v1' v2 v2', \n  combjoin v1 v1' v2 ->\n  combjoin v1 v1' v2' ->\n  v2 = v2'.\n\nVariable combjoin_assoc : forall v1 v2 v3 v4 v5,\n   join v1 v2 v3 ->\n   combjoin v3 v4 v5 ->\n   {v' : T1 & join v2 v4 v' /\\ combjoin v1 v' v5}.\n\nVariable combjoin_com : forall v1 v2 v3,\n   combjoin v1 v2 v3 ->\n   combjoin v2 v1 v3.\n\nVariable combjoin_canc : forall v1 v1' v2 v3,\n    combjoin v1 v2 v3 ->\n    combjoin v1' v2 v3 ->\n    v1 = v1'.\n\n(* We would really prefer this to be:\n       exists top, join (projT1 j1) (projT1 j2) top /\\ full top\n   but, again, we run into Type/Prop problems and wind up needing\n   some form of the axiom of choice somewhere or other. *)\nDefinition covers (j1 j2 : ijoinable A) : Prop :=\n  join (projT1 j1) (projT1 j2) A_top.\n\nInductive combiner : Type :=\n  | CEmpty\n  | CPart : forall (sh : ijoinable A) (v : T1), combiner\n  | CFull : forall (v : T2), combiner.\n\nInstance Join_combiner : Join combiner := \n  fun c1 c2 c3 =>\n  match (c1,c2,c3) with\n  | (CEmpty, CEmpty, CEmpty) => True\n  | (CEmpty, CPart a v, CPart a' v') => a = a' /\\ v = v'\n  | (CPart a v, CEmpty, CPart a' v')  => a = a' /\\ v = v'\n  | (CEmpty, CFull v, CFull v') => v = v'\n  | (CFull v, CEmpty, CFull v') => v = v'\n  | (CPart a v, CPart a' v', CPart a'' v'') => ijoin a a' a'' /\\ join v v' v''\n  | (CPart a v, CPart a' v', CFull v'') => combjoin v v' v'' /\\ covers a a'\n  | _ => False\n end.\n\nLemma combineJ_eq: forall x y z z' : combiner,\n  join x y z -> join x y z' -> z = z'.\nProof with auto.\n  intros.\n  icase x;icase y;icase z;icase z';try inversion H;try inversion H0;try congruence.\n  \n  f_equal.\n  eapply ijoin_eq; eauto.\n  eapply join_eq; eauto.\n\n  elimtype False; clear - pa_A sa_A H1 H4 A_top_full.\n  destruct sh; destruct sh0; destruct sh1.\n  red in H1; red in H4; simpl in H4.\n  generalize (join_eq H1 H4); intro; subst x1.\n  unfold midObj in *.\n  tauto.\n\n  elimtype False; clear - pa_A sa_A H2 H3 A_top_full.\n  destruct sh;destruct sh0;destruct sh1.\n  red in H3; red in H2; simpl in H2.\n  generalize (join_eq H2 H3);intro;subst x1.\n  unfold midObj in *.\n  tauto.\n\n  rewrite (combjoin_eq _ _ _ _ H1 H3)...\nQed.\n\nLemma combineJ_assoc: forall a b c d e : combiner, \n  join a b d -> join d c e ->\n                    {f : combiner & join b c f /\\ join a f e}.\nProof with auto.\n   intros. red in H, H0. unfold join.\n   icase a;icase b;icase c;icase d;icase e;inv H;inv H0.\n  \n\n   exists CEmpty;split;red...\n   exists (CPart sh0 v0);split;red...\n   exists (CFull v0);split;red...\n   exists (CPart sh1 v1);split;red...\n   exists (CPart sh2 v2);split;red...\n   exists (CFull v2);split;red...\n   exists (CFull v1);split;red...\n   exists CEmpty;split;red...\n   exists (CPart sh0 v0);split;red...\n   exists (CPart sh0 v0);split;red...\n   exists (CPart sh0 v0);split;red...\n   exists (CPart sh0 v0);split;red...\n   3: exists (CEmpty);split;red...\n   \n   destruct (ijoin_assoc _ _ _ _ _ H1 H) as [sh' [? ?]].\n   destruct (join_assoc H2 H3) as [fv [? ?]].\n   exists (CPart sh' fv); split; red...\n   \n   icase sh; icase sh0; icase sh1; icase sh2.\n   red in H1, H3. simpl in H1, H3.\n   destruct (join_assoc H1 H3) as [sh' [? ?]].\n   assert ((~identity sh') /\\ (~full sh')).\n     split; intro.\n     generalize (split_identity _ _ H0 H5); intro.\n     unfold midObj in *.\n     tauto.\n     spec H5 x.\n     spec H5. exists A_top...\n     spec H5 sh' A_top H4.\n     subst sh'.\n     apply unit_identity in H4.\n     unfold midObj in *.\n     tauto.\n  destruct (combjoin_assoc _ _ _ _ _ H2 H) as [v' [? ?]].\n  exists (CPart (existT _ sh' H5) v').\n  split; split...\nQed.\n\nLemma combineJ_com: forall a b c : combiner, \n    join a b c -> join b a c.\nProof with auto.\n  intros. unfold join in H|-*.\n  icase a; icase b.\n  icase c; red in H; red; destruct H;\n  split...\n  apply ijoin_com...\n  apply join_comm...\nQed.\n\nLemma combineJ_canc {C1: Canc_alg T1}: forall a1 a2 b c : combiner, \n       join a1 b c -> join a2 b c -> a1=a2.\nProof with auto.\n   intros. unfold join in H,H0.\n   icase c;icase b;icase a1;icase a2;inv H;inv H0;auto.\n   \n   destruct (ijoin_identity1 _ _ H).\n   destruct (ijoin_identity1 _ _ H1).\n   \n   generalize (ijoin_canc _ _ _ _ H1 H).\n   generalize (join_canc H2 H3); intros.\n   subst sh2 v2...\n   \n   generalize (join_canc H2 H3).\n   generalize (combjoin_canc _ _ _ _ H1 H); intros.\n   f_equal...\n   icase sh0; icase sh1.\n   apply existT_ext...\nQed.\n\nLemma combineJ_ex_identities: forall a , {e : combiner &  join e a a}.\nProof with auto.\n   intros.\n   icase a;\n   exists CEmpty;\n   constructor...\nQed.\n\nLemma combineJ_self {DA: Disj_alg A}:\n        forall a b : combiner, join a a b -> a = b.\nProof.\n  intros.\n  icase a;icase b; inv H.\n  destruct (ijoin_identity2 _ _ H0).\n  elimtype False. clear - DA H1 A_top_full.\n  icase sh. red in H1. simpl in H1.\n  generalize (join_self H1); intro.\n  subst x.\n  unfold midObj in *.\n  tauto.\nQed.\n\nInstance Perm_combiner : Perm_alg combiner.\nProof. constructor.\n  apply combineJ_eq.\n  apply combineJ_assoc.\n  apply combineJ_com.\n   (* positivity *)\n  intros.\n  hnf in H, H0.\n  destruct a, a'; try contradiction; destruct b,b'; try contradiction; auto;\n  try solve [destruct H; destruct H0; congruence].\n  destruct H; destruct H0. \n  f_equal.\n  destruct sh as [sh i]; destruct sh0 as [sh0 i0]; \n  destruct sh1 as [sh1 i1]; destruct sh2 as [sh2 i2].\n  apply existT_ext. unfold ijoin in H,H0.\n  eapply join_positivity; eauto. \n  eapply join_positivity; eauto. \nQed.\n\nInstance Sep_combiner: Sep_alg combiner.\nProof.\n  apply mkSep with (fun _ => CEmpty).\n  intros. hnf.  destruct t; auto.\n  auto.\nDefined.\n\nInstance Sing_combiner: Sing_alg combiner.\nProof.\n  apply (mkSing CEmpty).\n  auto.\nDefined.\n\nInstance Canc_combiner {C1: Canc_alg T1}: Canc_alg combiner.\nProof. \n repeat intro. eapply combineJ_canc; eauto.\nQed.\n\nInstance Disj_combiner {D1: Disj_alg A}: Disj_alg combiner.\nProof. \n repeat intro. eapply combineJ_self; eauto.\nQed.\n\n(* Usefull facts about combiners *)\n\nLemma identity_combiner {C1: Canc_alg T1}: forall d : combiner,\n  identity d -> \n  d = CEmpty.\nProof.\n  intros.\n  rewrite identity_unit_equiv in H.\n  icase d.\n  destruct H.\n  destruct (ijoin_identity1 _ _ H).\nQed.\n\nLemma combiner_identity {C1: Canc_alg T1}:\n  identity CEmpty.\nProof.\n  intros.\n  rewrite identity_unit_equiv.\n  compute.\n  trivial.\nQed.\n\nLemma combiner_full {C1: Canc_alg T1}: forall t2,\n  full (CFull t2).\nProof.\n  unfold full.  intros.\n  destruct H as [sigma'' ?].\n  icase sigma'.\n  apply combiner_identity.\nQed.\n\n(* This one is only true under various restrictions. *)\n(*\nLemma full_combiner: forall (d : combiner),\n  (* we require that As have complements *)\n  (forall a : ijoinable, exists a' : ijoinable, join (projT1 a) (projT1 a') A_top) ->\n  (* we require that T2 be nonempty *)\n  forall (at2 : T2),\n  full d ->\n  {t2 : T2 | d = DFull t2}.\nProof.\n  intros.\n  icase d.\n  3: exists v; trivial.\n  spec H0 (DFull at2) (DFull at2).\n  spec H0.\n  apply identity_unit.\n  apply combiner_identity.\n  exists (DFull at2).\n  compute. trivial.\n  apply identity_combiner in H0.\n  inversion H0.\n  \n  elimtype False.\n  spec H sh.\n  destruct H as [sh' ?].\n  destruct (join_ex_identities v) as [v0 [? ?]].\n  spec H0 ( sh' v0) (DFull .\n  \n  \n  ad mit.\n  exists v. trivial.\nQed.\n*)\n\nEnd CombineJoin.\n\nImplicit Arguments combiner.\nImplicit Arguments Join_combiner.\nImplicit Arguments CEmpty.\nImplicit Arguments CPart.\nImplicit Arguments CFull.\nImplicit Arguments identity_combiner.\nImplicit Arguments combiner_identity.\nImplicit Arguments combiner_full.\n\nSection ParameterizedCombiner.\n\n  Existing Instance Join_combiner.\n\n  Variable S : Type.\n  Variable JS : Join S.\n  Variable pa_S : Perm_alg S.\n  Variable sa_S : Sep_alg S.\n  Variable ca_S : Canc_alg S.\n\n  Variable T1 : Type -> Type.\n  Variable J1: forall A, Join (T1 A).\n  Variable Perm1: forall A, Perm_alg (T1 A).\n  Variable Sep1: forall A, Sep_alg (T1 A).\n  Variable f_T1 : functor T1.\n  Variable T2 : Type -> Type.\n  Variable f_T2 : functor T2.\n \n  Definition fcombiner (A : Type) : Type := \n    @combiner S JS (T1 A) (T2 A).\n \n  Definition fcombiner_fmap (A B : Type) (f : A -> B) \n    (fa : fcombiner A) : fcombiner B :=\n      match fa with\n        | CEmpty => CEmpty _ _ _ \n        | CPart sh rs => CPart _ sh (fmap f rs)\n        | CFull trs => CFull _ _ (fmap f trs)\n      end.\n  Implicit Arguments fcombiner_fmap [A B].\n  \n  Lemma ff_combiner : functorFacts fcombiner fcombiner_fmap.\n  Proof with auto.\n    constructor; intros;\n    extensionality pd; unfold fcombiner_fmap. \n    icase pd; rewrite fmap_id...\n    icase pd; rewrite <- fmap_comp...\n  Qed.\n  \n  Instance f_combiner : functor fcombiner := Functor ff_combiner.\n\n  Variable top_S : S.\n  Variable topS_full : full top_S.\n  Variable combjoin : forall A, (T1 A) -> (T1 A) -> (T2 A) -> Prop.\n  Variable combjoin_eq : forall A v1 v1' v2 v2', \n    combjoin A v1 v1' v2 ->\n    combjoin A v1 v1' v2' ->\n    v2 = v2'.\n  Variable combjoin_assoc : forall A (v1 v2 v3 v4: T1 A) (v5: T2 A),\n    join v1 v2 v3 ->\n    combjoin A v3 v4 v5 ->\n    {v' : (T1 A) & join v2 v4 v' /\\ combjoin A v1 v' v5}.\n  Variable combjoin_com : forall A v1 v2 v3,\n    combjoin A v1 v2 v3 ->\n    combjoin A v2 v1 v3.\n  Variable combjoin_canc : forall A v1 v1' v2 v3,\n    combjoin A v1 v2 v3 ->\n    combjoin A v1' v2 v3 ->\n    v1 = v1'.\n  Variable saf_T1 : pafunctor f_T1.\n\n  Instance Join_fcombiner (A: Type) : Join (fcombiner A) :=\n    Join_combiner top_S (J1 A) (combjoin A).\n\n\n  Instance Perm_fcombiner (A: Type): Perm_alg (fcombiner A).\n  Proof. apply Perm_combiner; auto.\n     apply combjoin_eq. apply combjoin_assoc.\n  Defined.\n\n\n  Instance Sep_fcombiner (A: Type): Sep_alg (fcombiner A).\n  Proof. apply Sep_combiner; auto.\n  Defined.\n\n  Instance Canc_fcombiner (A: Type) (CA: Canc_alg (T1 A)): Canc_alg (fcombiner A).\n  Proof.  apply Canc_combiner; auto. apply combjoin_canc.\n  Qed.\n    \n  Definition combjoin_hom (A : Type) (B : Type)\n    (f : T1 A -> T1 B) (g : T2 A -> T2 B) : Prop :=\n      forall x y z, \n        combjoin A x y z -> \n        combjoin B (f x) (f y) (g z).\n  Implicit Arguments combjoin_hom [A B].\n  \n  Variable fmaps_combjoin_hom: forall A B (f : A -> B),\n    combjoin_hom (fmap f) (fmap f).\n\n  Lemma fmap_fcombiner_hom: forall A B (f : A -> B),\n    join_hom (JA := Join_fcombiner A) (JB := Join_fcombiner B) (fmap f).\n  Proof with auto.\n    repeat intro. hnf in H|-*.\n    icase x; icase y; icase z.\n    destruct H.\n    split; congruence.\n    simpl in H. subst v0. simpl...\n    destruct H.\n    split; congruence.\n    destruct H.\n    split...\n    apply paf_join_hom...\n    destruct H.\n    split...\n    apply fmaps_combjoin_hom...\n    simpl in H. subst v0. simpl...\n  Qed.\n  \n  Definition combjoin_unmap_left (A B : Type)\n    (f : T1 A -> T1 B) (g : T2 A -> T2 B) : Type :=\n      forall (x' : T1 B) (y :T1 A) (z : T2 A),\n        combjoin B x' (f y) (g z) ->\n        {x : T1 A &  {y0 : T1 A | combjoin A x y0 z /\\ f x = x' /\\ f y0 = f y}}.\n  Implicit Arguments combjoin_unmap_left [A B].\n  \n  Variable combjoin_preserves_unmap_left : forall A B (f : A -> B),\n    combjoin_unmap_left (fmap f) (fmap f).\n  \n  Definition combjoin_unmap_right (A B : Type)\n    (f : T1 A -> T1 B) (g : T2 A -> T2 B) : Type :=\n      forall (x y :T1 A) (z' : T2 B),\n        combjoin B (f x) (f y) z' ->\n        {y0 : T1 A &  {z : T2 A | combjoin A x y0 z /\\ f y0 = f y /\\ g z = z'}}.\n  Implicit Arguments combjoin_unmap_right [A B].\n  \n  Variable combjoin_preserves_unmap_right : forall A B (f : A -> B),\n    combjoin_unmap_right (fmap f) (fmap f).\n  \n  Lemma fmap_fcombiner_preserves_unmap_left: forall A B (f : A -> B),\n    unmap_left (Join_fcombiner A) (Join_fcombiner B) (fmap f).\n  Proof with auto.\n    repeat intro. simpl in H|-*. unfold join in H|-*. simpl in H|-*.\n    icase x'; icase y; icase z.\n    exists (CEmpty _ _ _). exists (CEmpty _ _ _). firstorder.\n    exists (CEmpty _ _ _). exists (CPart _ sh0 v0).\n    destruct H. simpl.\n    repeat split; congruence.\n    exists (CEmpty _ _ _). exists (CFull _ _ v0).\n    simpl in H. simpl.\n    repeat split; congruence.\n    exists (CPart _ sh v0). exists (CEmpty _ _ _).\n    destruct H. simpl.\n    repeat split; congruence.\n    destruct H.\n    generalize (paf_preserves_unmap_left f v v0 v1 H0); intro X.\n    destruct X as [x [y0 [? [? ?]]]].\n    exists (CPart _ sh x). exists (CPart _ sh0 y0).\n    split. split...\n    simpl. split; congruence.\n    (* combjoin case *)\n    destruct H.\n    spec combjoin_preserves_unmap_left A B f v v0 v1 H.\n    destruct combjoin_preserves_unmap_left as [x [y0 [? [? ?]]]].\n    exists (CPart _ sh x). exists (CPart _ sh0 y0).\n    split. split...\n    simpl. split; congruence.\n    (* end combjoin case *)\n    exists (CFull _ _ v0). exists (CEmpty _ _ _).\n    simpl in H. simpl.\n    repeat split; congruence.\n  Qed.\n\n  Lemma fmap_fcombiner_preserves_unmap_right: forall A B (f : A -> B),\n    unmap_right (Join_fcombiner A) (Join_fcombiner B) (fmap f).\n  Proof with auto.\n    repeat intro. simpl in H|-*. unfold join in H|-*. simpl in H|-*.\n    icase x; icase y; icase z'.\n    exists (CEmpty _ _ _). exists (CEmpty _ _ _). firstorder.\n    exists (CPart _ sh v). exists (CPart _ sh v).\n    destruct H. simpl.\n    repeat split; congruence.\n    exists (CFull _ _ v). exists (CFull _ _ v).\n    simpl in H. simpl.\n    repeat split; congruence.\n    exists (CEmpty _ _ _). exists (CPart _ sh v).\n    destruct H. simpl.\n    repeat split; congruence.\n    destruct H.\n    generalize (paf_preserves_unmap_right f v v0 v1 H0); intro X.\n    destruct X as [y0 [z [? [? ?]]]].\n    exists (CPart _ sh0 y0). exists (CPart _ sh1 z).\n    split. split...\n    simpl. split; congruence.\n    (* combjoin case *)\n    destruct H.\n    spec combjoin_preserves_unmap_right A B f v v0 v1 H.\n    destruct combjoin_preserves_unmap_right as [y0 [z [? [? ?]]]].\n    exists (CPart _ sh0 y0). exists (CFull _ _ z).\n    split. split...\n    simpl. split; congruence.\n    (* end combjoin case *)\n    exists (CEmpty _ _ _). exists (CFull _ _ v).\n    simpl in H. simpl.\n    repeat split; congruence.\n  Qed.\n  \n Instance paf_combiner: @pafunctor _ f_combiner Join_fcombiner.\n Proof.\n    constructor.\n    apply fmap_fcombiner_hom.\n    apply fmap_fcombiner_preserves_unmap_left.\n    apply fmap_fcombiner_preserves_unmap_right.\n Qed.\n\nEnd ParameterizedCombiner.\n\nImplicit Arguments fcombiner.\nImplicit Arguments combjoin_hom [T1 T2 A B].\nImplicit Arguments combjoin_unmap_left [A B T1 T2].\nImplicit Arguments combjoin_unmap_right [A B T1 T2].\nImplicit Arguments f_combiner [S JS T1 T2].\nImplicit Arguments paf_combiner.\n\n", "meta": {"author": "lexuanbach", "repo": "certified-permission-procedure", "sha": "f0ac470d8096b106ea03c22e95950bae684bcc86", "save_path": "github-repos/coq/lexuanbach-certified-permission-procedure", "path": "github-repos/coq/lexuanbach-certified-permission-procedure/certified-permission-procedure-f0ac470d8096b106ea03c22e95950bae684bcc86/msl/combiner_sa.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2271547297395536}}
{"text": "Load \"phase23\".\n \n(** some tactics *)\n\n \n(*******************************************)\n(** ** Phase-II : Voting Phase *)\n \n(** \n- (V) -> C : sign( sk (A) , commit(v, r)) \n\n *)\n(** frame 6***)\n  (** * Frame [phi6] *)\n\nDefinition shuftrm (x1:message) :=  (shuf (dec (pi1 (pi1 x1)) (sk 5)) (dec (pi1 (pi2 x1)) (sk 5))).\n   \nDefinition phi77t n1 n2 := (phi66t n1 n2) ++ [msg  (shuf (unblind (commit (v (nonce 0)) (rr (nonce 7))) (pi1 (k (nonce 3))) (rr (nonce 8)) (pi1 (x2t 0)))\n                                                         (unblind (b 1 19) (pk 3) (r 20) (pi2 (x4ttt 0 1)))) ].\n  \nDefinition x87t n1 n2 := (f (conv_mylist_listm (phi77t n1 n2))).\n\n \n  (*****************************************************************************)\n \nDefinition phi74tf3t n1 n2 := (phi64tftt n1 n2) ++ [msg (shuftrm (x74tftt n1 n2)) ].\nDefinition x84tf3t n1 n2 := (f (conv_mylist_listm (phi74tf3t n1 n2))). \n(*\nDefinition phi3ttft n1  := (phi2tt n1) ++ [msg  ((bsign (sk 3)  (pi1 (pi2 (pi1  (x3tt n1 ))))),  (bsign (sk 3)  (pi1 (pi2 (pi2  (x3tt n1 ))))))].\nDefinition x4ttft n1 := (f (conv_mylist_listm (phi3ttft n1))).\n*)\nDefinition phi7tf6t n1 n2 := (phi6tf5t n1 n2) ++ [msg (shuftrm (x7tf5t n1 n2) ) ].\nDefinition x8tf6t n1 n2 := (f (conv_mylist_listm (phi7tf6t n1 n2))).\n\nDefinition phi7tf3tf3t n1 n2 := (phi6tf3tftt n1 n2) ++ [msg (shuftrm (x7tf3tftt n1 n2)) ].\nDefinition x8tf3tf3t n1 n2 := (f (conv_mylist_listm (phi7tf3tf3t n1 n2))).\n(**********************************************************************************)\n \nDefinition phi7tftf5t n1 n2 := (phi6tftf4t n1 n2) ++ [msg (shuftrm (x7tftf4t n1 n2) ) ].\nDefinition x8tftf5t n1 n2 := (f (conv_mylist_listm (phi7tftf5t n1 n2))).\n\nDefinition phi7tftfttf3t n1 n2 := (phi6tftfttftt n1 n2) ++ [msg (shuftrm (x7tftfttftt n1 n2) ) ].\nDefinition x8tftfttf3t n1 n2 := (f (conv_mylist_listm (phi7tftfttf3t n1 n2))).\n(*\nDefinition phi3tftfft n1 n2 := (phi2tft n1 n2) ++ [msg  ((bsign (sk 3)  (pi1 (pi2 (pi1 (x3tft n1 n2))))),  (bsign (sk 3)  (pi1 (pi2 (pi2 (x3tft n1 n2))))))].\n\nDefinition x4tftfft n1 n2 := (f (conv_mylist_listm (phi3tftfft n1 n2))).\n *)\n(*\nDefinition phi3tfftt n1  := (phi2tfft n1) ++ [msg ok].\nDefinition x4tfftt n1  := (f (conv_mylist_listm (phi3tfftt n1))).\n\nDefinition phi3tfftft n1 n2 := (phi2tfft n1) ++ [msg ((pk 2), ( (e (b n2 21) 22),  (sign (sk 2) (e (b n2 21) 22))))].\nDefinition x4tfftft n1 n2 := (f (conv_mylist_listm (phi3tfftft n1 n2))). *)\nDefinition phi7f7t n1 n2 := (phi6f6t n1 n2) ++ [msg (shuftrm (x7f6t n1 n2) ) ].\nDefinition x8f7t n1 n2 := (f (conv_mylist_listm (phi7f7t n1 n2))).\n\nDefinition phi7f4tf3t n1 n2 := (phi6f4tftt n1 n2) ++ [msg (shuftrm (x7f4tftt n1 n2) ) ].\nDefinition x8f4tf3t n1 n2 := (f (conv_mylist_listm (phi7f4tf3t n1 n2))).\n(*Definition phi3fttft  n2 := (phi2ftt n2) ++ [msg  ((bsign (sk 3)  (pi1 (pi2 (pi1 (x3ftt n2 ))))),  (bsign (sk 3)  (pi1 (pi2 (pi2 (x3ftt n2 ))))))].\n\nDefinition x4fttft n2 := (f (conv_mylist_listm (phi3fttft n2))). *)\n\nDefinition phi7ftf6t n1 n2:= (phi6ftf5t n1 n2) ++ [msg (shuftrm (x7ftf5t n1 n2) ) ].\nDefinition x8ftf6t n1 n2 := (f (conv_mylist_listm (phi7ftf6t n1 n2))).\nDefinition phi7ftf3tf3t n1 n2:= (phi6ftf3tftt n1 n2) ++ [msg (shuftrm (x7ftf3tftt n1 n2) ) ] .\nDefinition x8ftf3tf3t n1 n2 := (f (conv_mylist_listm (phi7ftf3tf3t n1 n2))).\n(**********************************************************************)\nDefinition phi7ftftf5t n1 n2:= (phi6ftftf4t n1 n2) ++ [msg (shuftrm (x7ftftf4t n1 n2) ) ] .\nDefinition x8ftftf5t n1 n2 := (f (conv_mylist_listm (phi7ftftf5t n1 n2))).\n\nDefinition phi7ftftf2tf3t n1 n2:= (phi6ftftf2tftt n1 n2) ++ [msg (shuftrm (x7ftftf2tftt n1 n2) ) ].\nDefinition x8ftftf2tf3t n1 n2 := (f (conv_mylist_listm (phi7ftftf2tf3t n1 n2))).\n\n(** mixnetops *)\n \nDefinition revtrm1   n r2 := ((enc (r n) (pk 5) (r r2)), (sign (sk 1)  (THREE, (enc (r n) (pk 5) (r r2))))).\nDefinition revtrm2   n r2 := ((enc (r n) (pk 5) (r r2)), (sign (sk 2)  (THREE, (enc (r n) (pk 5) (r r2))))).\n\n Definition rev x1 n1 r1 n2 r2 := (ifm (eqm (to x1) (V 1)) (revtrm1 n1 r1) (ifm (eqm (to x1) (V 2)) (revtrm2 n2 r2)  O)).\n \n\n \nDefinition mixnet' x1 x2 n1 r1 n2 r2 :=  (ifm (mchecks (x1)) (rev x2 n1 r1 n2 r2)  O).\n\nDefinition mnetop' n x1 x2 x3 n1 r1 n2 r2 := (ifm (eqm (to x1) (V n)) (mixnet' x2 x3 n1 r1 n2 r2) O).\n (*\nDefinition voter1 x1 n1 n2 r1 x2 r2 := (ifm (eqm (to x1) (V 1)) (vtrm (sk 1) n1 n2 r1 (pi1 (x2)) r2) O).\nDefinition voter2 x1 n1 n2 r1 x2 r2 := (ifm (eqm (to x1) (V 2)) (vtrm (sk 2) n1 n2 r1 (pi2 (x2)) r2) O).\n(** vote 2 *)\n  *)\n\nDefinition q111r1 n1 n2 := (ifm (eqm (to (x54t n1 n2)) (V 1)) (mnetop' 2 (x65t n1 n2) (x76t n1 n2) (x87t n1 n2) 7 51 19 52) \n                                  (ifm (eqm (to (x54t n1 n2)) (V 2)) (mnetop' 1 (x64tft n1 n2) (x74tftt n1 n2) (x84tf3t n1 n2) 7 53 19 54) O)).\n \n (*************************************************)                       \n\n  \nDefinition q121r1 n1 n2 := (ifm (eqm (to (x5tf3t n1 n2)) (V 1)) (mnetop' 2 (x6tf4t n1 n2) (x7tf5t n1 n2) (x8tf6t n1 n2) 7 55 11 56)\n                                  (ifm (eqm (to (x5tf3t n1 n2)) (V 2)) (mnetop' 1 (x6tf3tft n1 n2) (x7tf3tftt n1 n2) (x8tf3tf3t n1 n2) 7 57 11 58)  O)).\n\n\n   \n  \nDefinition q122r1 n1 n2 := (ifm (eqm (to (x5tftft n1 n2)) (V 1)) (mnetop' 2 (x6tftf3t n1 n2) (x7tftf4t n1 n2)  (x8tftf5t n1 n2) 7 59 11 60)\n                                  (ifm (eqm (to (x5tftft n1 n2)) (V 2)) (mnetop' 1 (x6tftfttft n1 n2) (x7tftfttftt n1 n2) (x8tftfttf3t n1 n2) 7 61 11 62)  O)).\n\n\n\n  \nDefinition q211r1 n1 n2 := (ifm (eqm (to (x5f4t n1 n2)) (V 1))   (mnetop' 2 (x6f5t n1 n2) (x7f6t n1 n2) (x8f7t n1 n2) 23 63 9 64)\n                                  (ifm (eqm (to (x5f4t n1 n2)) (V 2)) (mnetop' 1 (x6f4tft n1 n2) (x7f4tftt n1 n2) (x8f4tf3t n1 n2) 23 65 9 66) O)).\n\n\n\n(***************************************************)\n\n  \n\nDefinition q221r1 n1 n2:=  (ifm (eqm (to (x5ftf3t n1 n2)) (V 1)) (mnetop' 2 (x6ftf4t n1 n2) (x7ftf5t n1 n2) (x8ftf6t n1 n2) 13 66 9 68)\n                                  (ifm (eqm (to (x5ftf3t n1 n2)) (V 2)) (mnetop' 1 (x6ftf3tft n1 n2) (x7ftf3tftt n1 n2) (x8ftf3tf3t n1 n2) 13 69 9 70) O)).\n\n\n  \n  \nDefinition q222r1 n1 n2 :=  (ifm (eqm (to (x5ftftf2t n1 n2)) (V 1)) (mnetop' 2 (x6ftftf3t n1 n2) (x7ftftf4t n1 n2) (x8ftftf5t n1 n2) 13 71 9 72) \n                                  (ifm (eqm (to (x5ftftf2t n1 n2)) (V 2)) (mnetop' 1 (x6ftftf2tft n1 n2) (x7ftftf2tftt n1 n2) (x8ftftf2tf3t n1 n2) 13 73 9 74) O)).\n\n\n\n\n(*****************************************************************************************)\n \nDefinition q111s n1 n2 := (ifm  (eqm (to (x4ttt n1 n2)) (V 2))& (bacc (pk 3) (b n2 19) (r 20) (pi2 (x4ttt n1 n2))) (q111r1 n1 n2)\n                                     O).\n \n (*************************************************)                       \n\n  \nDefinition q121s n1 n2 := (ifm (eqm (to (x4tftt n1 n2)) (V 2 ))& (bacc (pk 3) (b n2 11) (r 12) (pi2 (x4tftt n1 n2))) (q121r1 n1 n2)\n                         O).\n\nDefinition q122s n1 n2 := (ifm (eqm (to (x4tftft n1 n2)) (V 1 ))& (bacc (pk 3) (b n1 7) (r 8) (pi1 (x4tftft n1 n2))) (q122r1 n1 n2)\n                         O).\n \n \nDefinition q211s n1 n2 :=  (ifm (eqm (to (x4fttt n1 n2)) (V 1 ))& (bacc (pk 3) (b n1 23) (r 24) (pi1 (x4fttt n1 n2))) (q211r1 n1 n2)\n                          O).\n\n\n\n(***************************************************)\n\nDefinition q221s n1 n2:=   (ifm (eqm (to (x4ftftt n1 n2)) (V 2 ))& (bacc (pk 3) (b n2 9) (r 10) (pi2 (x4ftftt n1 n2))) (q221r1 n1 n2)\n                           O).\nDefinition q222s n1 n2 :=  (ifm (eqm (to (x4ftftft n1 n2)) (V 1 ))& (bacc (pk 3) (b n1 13) (r 14) (pi1 (x4ftftft n1 n2))) (q222r1 n1 n2) O).\n\n\n \n(*****************************************)\n  \nDefinition q11_r1 n1 n2 :=  (ifm  (eqm (to (x3tt n1 )) (V 2)) (q111s n1 n2)\n                                      O).\n \nDefinition q12_r1 n1 n2 := (ifm (eqm (to (x3tft n1 n2)) (V 1))& (bacc (pk 3) (b n1 7) (r 8) (pi2 (x3tft n1 n2))) (q121s n1 n2)\n                                    (ifm (eqm (to (x3tft n1 n2)) (V 2))& (bacc (pk 3) (b n2 11) (r 12) (pi2 (x3tft n1 n2))) (q122s n1 n2)\n                                                 O)).\n \n\nDefinition q21_r1 n1 n2 := (ifm  (eqm (to (x3ftt n2)) (V 1))  (q211s n1 n2)\n                                   O).\n\nDefinition q22_r1 n1 n2  := (ifm (eqm (to (x3ftft n1 n2)) (V 1))& (bacc (pk 3) (b n1 13) (r 14) (pi1 (x3ftft n1 n2))) (q221s n1 n2)\n                                    (ifm (eqm (to (x3ftft n1 n2)) (V 2))& (bacc (pk 3) (b n2 9) (r 10) (pi2 (x3ftft n1 n2))) (q222s n1 n2)\n                                                   O)).\n \n(********************************************************************************************)\n\nDefinition q1_r1 n1 n2 := (ifm (eqm (to (x2t n1 )) (V 1))& (bacc (pk 3) (b n1 7) (r 8) (pi1 (x2t n1 )))  (q11_r1 n1 n2)\n\t\t\t           (ifm (eqm (to (x2t n1 )) (V 2))  (q12_r1 n1 n2)\n                                                  O)).\n \nDefinition q2_r1 n1 n2 :=  (ifm (eqm (to (x2ft n2)) (V 2))& (bacc (pk 3) (b n2 9) (r 10) (pi2 (x2ft n2)))  (q21_r1 n1 n2)\n\t\t\t           (ifm (eqm (to (x2ft n2)) (V 1))  (q22_r1 n1 n2)\n                                                   O)).\n \n\n\nDefinition t7 n1 n2 :=  (ifm (eqm (to x1) (V 1)) (q1_r1 n1 n2)\n\t\t    \t           (ifm (eqm (to x1) (V 2))  (q2_r1 n1 n2)\n                                                   O )).\n\nDefinition phi8 n1 n2 := (phi7 n1 n2) ++ [msg (t7 n1 n2)] .\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "ajayeeralla", "repo": "vote_privacy_proofs", "sha": "87a689040f7c4f4cb8bb0434efcef0fa0bb01a96", "save_path": "github-repos/coq/ajayeeralla-vote_privacy_proofs", "path": "github-repos/coq/ajayeeralla-vote_privacy_proofs/vote_privacy_proofs-87a689040f7c4f4cb8bb0434efcef0fa0bb01a96/src/.other/foo/phase31.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.33111974622959367, "lm_q1q2_score": 0.22713141372028434}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\n(****************************************************************************)\n(*                          Signes Project                                  *)\n(*                            2002-2003                                     *)\n(*                           Houda ANOUN                                    *)\n(*                          Pierre Casteran                                 *)\n(*                           LaBRI/INRIA                                    *)\n(****************************************************************************)\n\n(* Introduction to filters Cf Kurtonina's PhD Thesis\nThese filters will be used to give another proof of completeness *)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nRequire Export Form.\n\nSection CompletenessFilters.\nVariable Atoms : Set.\nSection CompletenessDefs.\nVariable X : arrow_extension.\nSection Filter_Def.\n\n\nDefinition getSet (A : Type) (P : A -> Prop) (x : sigT P) :=\n  match x with\n  | existT s P => s\n  end.\n\n\nDefinition weakFilter (S : Form Atoms -> Prop) : Prop :=\n  forall A B : Form Atoms, S A /\\ weak (arrow X A B) -> S B.\n\n(* for additive connectives \nDefinition filter: ((Form Atoms)->Prop)->Prop:=\n[S:(Form Atoms)->Prop] (weakFilter S) /\\ \n                       (A,B:(Form Atoms)) (S (Inter A B))<->\n                                           (S A) /\\ (S B) .\n\nDefinition primeFilter: ((Form Atoms)->Prop)->Prop:=\n[S:(Form Atoms)->Prop] (filter S)/\\\n                         (A, B: (Form Atoms)) (S (Uni A B)) <->\n                                              (S A)/\\(S B) .\n\n*)\n\nDefinition compSet (S1 S2 : Form Atoms -> Prop) (F : Form Atoms) : Prop :=\n  exists x1 : Form Atoms,\n    (exists x2 : Form Atoms, S1 x1 /\\ S2 x2 /\\ weak (arrow X (Dot x1 x2) F)).\n\n\nDefinition formDerivation (A1 A2 : Form Atoms) : Prop := weak (arrow X A1 A2).    \n\nDefinition isIncluded (E1 E2 : Form Atoms -> Prop) :=\n  forall F : Form Atoms, E1 F -> E2 F.\n\nLemma formDerivWFilter : forall A : Form Atoms, weakFilter (formDerivation A).\nProof.\n intro A.\n unfold weakFilter in |- *.\n unfold formDerivation in |- *.\n intros A0 B H.\n elim H.\n clear H; intros H H0.\n eapply weak_comp; eauto.\nQed.\n\nLemma weakFilterComp :\n forall SF1 SF2 : Form Atoms -> Prop, weakFilter (compSet SF1 SF2).\nProof.\n intros SF1 SF2. \n unfold weakFilter in |- *.\n unfold compSet in |- *.\n intros A B H.\n elim H; clear H; intros H H0.\n elim H; clear H; intros x1 H.\n elim H; clear H; intros x2 H.\n split with x1.\n split with x2.\n split.\n tauto.\n split.\n tauto.\n apply weak_comp with A.\n tauto.\n auto.\nQed.\n\n\nEnd Filter_Def.\n\nSection semanticDefs.\n(* the same as in the file Semantics.v *)\nVariables (W : Type) (R : W -> W -> W -> Prop) (v_at : Atoms -> W -> Prop). \n\n(* extension of some valuation on atoms to all formulae *)\n\nFixpoint val (F : Form Atoms) : W -> Prop :=\n  match F with\n  | At a => v_at a\n  | Dot A B =>\n      fun x => ex (fun y => ex (fun z => R x y z /\\ val A y /\\ val B z))\n  | Slash C B => fun y => forall x z : W, R x y z -> val B z -> val C x\n  | Backslash A C => fun z => forall x y : W, R x y z -> val A y -> val C x\n  end.\n\nEnd semanticDefs.\nSection model_types.\n\n (* Kinds of models are caracterized wrt the ternary relation R *)\n\n Definition model_type := forall W : Type, (W -> W -> W -> Prop) -> Prop.\n\n Definition model_inter (P1 P2 : model_type) (W : Type)\n   (R : W -> W -> W -> Prop) := P1 W R /\\ P2 W R.\n Variable P : model_type.\n\n  Definition sem_implies : Form Atoms -> Form Atoms -> Prop :=\n    fun A B : Form _ =>\n    forall (W : Type) (R : W -> W -> W -> Prop) (v_at : Atoms -> W -> Prop),\n    P R -> forall w : W, val R v_at A w -> val R v_at B w.\n\n (* associativity and commutativity *)\n\n Definition ASS : model_type :=\n   fun (W : Type) (R : W -> W -> W -> Prop) =>\n   (forall x y z t u : W,\n    R t x y -> R u t z -> exists v : W, R v y z /\\ R u x v) /\\\n   (forall x y z v u : W,\n    R v y z -> R u x v -> exists t : W, R t x y /\\ R u t z).\n\n Definition COM : model_type :=\n   fun (W : Type) (R : W -> W -> W -> Prop) =>\n   forall x y z : W, R x y z -> R x z y.\n\n\n\n(* canonical model *)\n(* WK is the set of all weak filters *)\n\nDefinition WK := sigT weakFilter.\n\nDefinition RK (E1 E2 E3 : WK) :=\n  isIncluded (compSet (getSet E2) (getSet E3)) (getSet E1).\n\nDefinition VatK (p : Atoms) (A : WK) := getSet A (At p).\nEnd model_types.\n\nDefinition model_OK (P : model_type) := P _ RK.\n\n Definition complete (P : model_type) :=\n   forall A B : Form Atoms, sem_implies P A B -> weak (arrow X A B).\n\n\n\nLemma getSetWeakFilter :\n forall (A : WK) (F1 F2 : Form Atoms),\n getSet A F1 -> weak (arrow X F1 F2) -> getSet A F2.\nProof.\n intro A.\n elim A.\n intros x p F1 F2 H H0.\n simpl in |- *.\n simpl in H.\n unfold weakFilter in p.\n eapply p; split; eauto.\nQed.\n\nLemma truthLemmaFilters :\n forall (F : Form Atoms) (A : WK), val RK VatK F A <-> getSet A F. \n intro F.\n elim F.\n simpl in |- *.\n unfold VatK in |- *.\n tauto.\n intros f H f0 H0 A.\n split.\n intro H1.\n cut (compSet (getSet A) (formDerivation f0) f).\n intro H2.\n unfold compSet in H2.\n elim H2; clear H2; intros x1 H2.\n elim H2; clear H2; intros x2 H2.\n elim H2; clear H2; intros H2 H3.\n elim H3; clear H3; intros H3 H4.\n unfold formDerivation in H3.\n apply getSetWeakFilter with x1.\n assumption.\n apply weak_beta.\n apply weak_comp with (Dot x1 x2).\n apply weak_Dot_mono_right; assumption.\n assumption.\n cut (weakFilter (compSet (getSet A) (formDerivation f0))).\n intro H2.\n elim (H (existT weakFilter (compSet (getSet A) (formDerivation f0)) H2)).\n intros.\n apply H3.\n generalize H1.\n simpl in |- *.\n clear H1; intro H1.\n cut (weakFilter (formDerivation f0)).\n intro H5.\n apply H1 with (existT weakFilter (formDerivation f0) H5).\n unfold RK in |- *.\n simpl in |- *.\n unfold isIncluded in |- *.\n auto.\n elim (H0 (existT weakFilter (formDerivation f0) H5)).\n intros H6 H7.\n apply H7.\n simpl in |- *.\n unfold formDerivation in |- *.\n apply weak_one.\n apply formDerivWFilter.\n apply weakFilterComp.\n intro H1.\n simpl in |- *.\n unfold RK in |- *.\n unfold isIncluded in |- *.\n intros x z H2 H3.\n elim (H x); intros H4 H5.\n apply H5.\n apply (H2 f).\n unfold compSet in |- *.\n split with (Slash f f0).\n split with f0.\n split.\n auto.\n split.\n elim (H0 z); intros H6 H7.\n apply H6; assumption.\n apply weak_beta'.\n apply weak_one.\n(* case where F=(Dot f f0) *)\n intros f H f0 H0.\n split.\n simpl in |- *.\n intro H1.\n elim H1.\n clear H1; intros x H1.\n elim H1; clear H1; intros z H1.\n elim H1; unfold RK in |- *; clear H1; intros H1 H2.\n elim H2; clear H2; intros H2 H3.\n unfold isIncluded in H1.\n apply H1.\n unfold compSet in |- *.\n split with f.\n split with f0.\n split.\n elim (H x); intros H4 H5.\n apply H4; exact H2.\n split.\n elim (H0 z).\n intros H4 H5.\n apply H4.\n assumption.\n apply weak_one.\n intro H1.\n simpl in |- *.\n assert (H2 : forall A : Form Atoms, weakFilter (formDerivation A)).\n exact formDerivWFilter.\n split with (existT weakFilter (formDerivation f) (H2 f)).\n split with (existT weakFilter (formDerivation f0) (H2 f0)).\n unfold RK in |- *.\n split.\n unfold isIncluded in |- *.\n simpl in |- *.\n unfold compSet in |- *.\n intros F0 H3.\n elim H3; clear H3; intros x1 H3. \n elim H3; clear H3; intros x2 H3.\n apply getSetWeakFilter with (Dot x1 x2).\n apply getSetWeakFilter with (Dot f f0).\n assumption.\n apply weak_Dot_mono; tauto.\n tauto.\n split.\n elim (H (existT weakFilter (formDerivation f) (H2 f))).\n intros H3 H4.\n apply H4.\n simpl in |- *.\n unfold formDerivation in |- *.\n apply weak_one.\n elim (H0 (existT weakFilter (formDerivation f0) (H2 f0))).\n intros H3 H4.\n apply H4.\n simpl in |- *.\n unfold formDerivation in |- *; apply weak_one.\n(* Case where F=(Backslash f f0) *)\n intros f H0 f0 H.\n split.\n intro H1.\n assert (L : compSet (formDerivation f) (getSet A) f0).\n simpl in H1.\n assert (H2 : weakFilter (compSet (formDerivation f) (getSet A))).\n apply weakFilterComp.\n elim (H (existT weakFilter (compSet (formDerivation f) (getSet A)) H2)).\n intros H4 H5.\n apply H4.\n assert (H6 : forall A : Form Atoms, weakFilter (formDerivation A)).\n exact formDerivWFilter.\n apply H1 with (existT weakFilter (formDerivation f) (H6 f)). \n unfold RK in |- *.\n unfold isIncluded in |- *.\n simpl in |- *.\n auto.\n elim (H0 (existT weakFilter (formDerivation f) (H6 f))).\n intros H7 H8.\n apply H8.\n simpl in |- *.\n unfold formDerivation in |- *.\n apply weak_one.\n unfold compSet in L.\n elim L; clear L; intros x2 L.\n elim L; clear L; intros x3 L.\n apply getSetWeakFilter with x3.\n tauto.\n apply weak_gamma.\n apply weak_comp with (Dot x2 x3).\n apply weak_Dot_mono_left.\n unfold formDerivation in L.\n tauto.\n tauto.\n intro H1.\n simpl in |- *.\n intros x y H2 H3.\n elim (H x).\n intros H4 H5.\n apply H5.\n unfold RK in H2.\n unfold isIncluded in H2.\n apply H2.\n unfold compSet in |- *.\n split with f.\n split with (Backslash f f0).\n split.\n elim (H0 y).\n intros H6 H7.\n apply H6.\n exact H3.\n split.\n exact H1.\n apply weak_gamma'.\n apply weak_one.\nQed.\n\n Lemma completenessProof : forall P : model_type, model_OK P -> complete P.\n\nProof.\n unfold model_OK, complete, sem_implies in |- *.\n intros P H A B HO.\n unfold formDerivation in |- *.\n cut (formDerivation A B).\n unfold formDerivation in |- *.\n auto.\n assert (H1 : weakFilter (formDerivation A)).\n apply formDerivWFilter.\n set (w := existT weakFilter (formDerivation A) H1).\n cut (getSet w B).\n simpl in |- *.\n auto.\n elim (truthLemmaFilters B w).\n intros H2 H3.\n apply H2.\n apply HO.\n auto.\n elim (truthLemmaFilters A w).\n intros H4 H5.\n apply H5.\n simpl in |- *.\n unfold formDerivation in |- *; apply weak_one.\nQed.\n\nEnd CompletenessDefs.\n\nLemma NL_OK : model_OK NL (fun _ _ => True).\nProof.\n unfold model_OK in |- *.\n auto.\nQed.\n\nLemma NL_complete : complete NL (fun _ _ => True).\nProof.\n apply completenessProof.\n apply NL_OK.\nQed.\n\nLemma NLP_OK : forall X : arrow_extension, extends NLP X -> model_OK X COM.\nProof.\n intros X H.\n unfold model_OK in |- *.\n unfold COM in |- *.\n unfold RK in |- *.\n unfold isIncluded in |- *.\n intros x y z H0 F H1.\n apply H0.\n unfold compSet in |- *.\n unfold compSet in H1.\n elim H1; clear H1; intros x1 H1.\n elim H1; clear H1; intros x2 H1.\n split with x2.\n split with x1.\n split.\n tauto.\n split.\n tauto.\n apply weak_comp with (Dot x1 x2).\n apply weak_arrow_plus.\n unfold extends in H.\n apply H.\n split.\n tauto.\nQed.\n\nLemma NLP_complete : complete NLP COM.\nProof.\n apply completenessProof.\n apply NLP_OK.\n apply no_extend.\nQed.\n\nLemma LcompSet :\n forall (F : Form Atoms) (X : arrow_extension) (x y z : WK X),\n extends L X ->\n compSet X (getSet x) (compSet X (getSet y) (getSet z)) F ->\n compSet X (compSet X (getSet x) (getSet y)) (getSet z) F.\nProof.\n intros F X x y z H H0.\n unfold compSet in |- *.\n unfold compSet in H0.\n elim H0; clear H0; intros x1 H0.\n elim H0; clear H0; intros x2 H0.\n elim H0; clear H0; intros H0 H1.\n elim H1; clear H1; intros H1 H2.\n elim H1; clear H1; intros x3 H1.\n elim H1; clear H1; intros x4 H1.\n split with (Dot x1 x3).\n split with x4.\n split.\n split with x1.\n split with x3.\n split.\n auto.\n split.\n tauto.\n apply weak_one. \n split.\n tauto.\n apply weak_comp with (Dot x1 (Dot x3 x4)).\n apply weak_arrow_plus.\n unfold extends in H.\n apply H.\n constructor 2.\n apply weak_comp with (Dot x1 x2).\n apply weak_Dot_mono_right.\n tauto.\n assumption.\nQed.\n\nLemma LcompSet' :\n forall (F : Form Atoms) (X : arrow_extension) (x y z : WK X),\n extends L X ->\n compSet X (compSet X (getSet x) (getSet y)) (getSet z) F ->\n compSet X (getSet x) (compSet X (getSet y) (getSet z)) F.\n\nProof.\n intros F X x y z H H0.\n unfold compSet in |- *.\n unfold compSet in H0.\n elim H0; clear H0; intros x1 H0.\n elim H0; clear H0; intros x2 H0.\n elim H0; clear H0; intros H0 H1.\n elim H0; clear H0; intros x3 H0.\n elim H0; clear H0; intros x4 H0.\n split with x3.\n split with (Dot x4 x2).\n split.\n tauto.\n split.\n split with x4.\n split with x2.\n split.\n tauto.\n split.\n tauto.\n apply weak_one.\n apply weak_comp with (Dot (Dot x3 x4) x2).\n apply weak_arrow_plus.\n unfold extends in H.\n apply H. \n constructor 1.\n apply weak_comp with (Dot x1 x2).\n apply weak_Dot_mono_left.\n tauto.\n tauto.\nQed.\n\n\nLemma compSetMono :\n forall (X : arrow_extension) (s1 s2 s3 s4 : Form Atoms -> Prop)\n   (F : Form Atoms),\n isIncluded s1 s2 ->\n isIncluded s3 s4 -> compSet X s1 s3 F -> compSet X s2 s4 F.\nProof.\n intros X s1 s2 s3 s4 F.\n unfold isIncluded in |- *.\n unfold compSet in |- *.\n intros H H0 H1.\n elim H1; clear H1; intros x1 H1.\n elim H1; clear H1; intros x2 H1.\n split with x1.\n split with x2.\n split.\n apply H; tauto.\n split.\n apply H0; tauto.\n tauto.\nQed.\n\nLemma L_OK : forall X : arrow_extension, extends L X -> model_OK X ASS.\n\n intros X H.\n unfold model_OK, ASS, RK in |- *.\n split.\n intros x y z t u H0 H1.\n assert (L : weakFilter X (compSet X (getSet y) (getSet z))).\n apply weakFilterComp.\n split with (existT (weakFilter X) (compSet X (getSet y) (getSet z)) L).\n split.\n simpl in |- *; auto.\n simpl in |- *.\n unfold isIncluded in |- *; auto.\n unfold isIncluded in |- *; intros F H2.\n apply H1.\n apply compSetMono with (compSet X (getSet x) (getSet y)) (getSet z).\n auto.\n unfold isIncluded in |- *; auto.\n apply LcompSet; auto.\n intros x y z v u H0 H1.\n assert (L : weakFilter X (compSet X (getSet x) (getSet y))).\n apply weakFilterComp.\n split with (existT (weakFilter X) (compSet X (getSet x) (getSet y)) L).\n split.\n simpl in |- *.\n unfold isIncluded in |- *; auto.\n simpl in |- *.\n unfold isIncluded in |- *.\n intros F H2.\n apply H1.\n apply compSetMono with (getSet x) (compSet X (getSet y) (getSet z)).\n unfold isIncluded in |- *; auto.\n exact H0.\n apply LcompSet'; auto.\nQed.\n\nLemma L_complete : complete L ASS.\nProof.\n apply completenessProof.\n apply L_OK.\n apply no_extend.\nQed.\n\n\nEnd CompletenessFilters.", "meta": {"author": "coq-contribs", "repo": "lambek", "sha": "1e3aea2ce879e784e0ee3ca394ae385c03f8384d", "save_path": "github-repos/coq/coq-contribs-lambek", "path": "github-repos/coq/coq-contribs-lambek/lambek-1e3aea2ce879e784e0ee3ca394ae385c03f8384d/Filters.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2268758076270657}}
{"text": "Require Import CodeProofDeps.\nRequire Import Ident.\nRequire Import Constants.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import CommonLib.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef1.Spec.\nRequire Import TableDataOpsRef1.Layer.\nRequire Import TableDataOpsRef2.Code.table_unmap2.\n\nRequire Import TableDataOpsRef2.LowSpecs.table_unmap2.\n\nLocal Open Scope Z_scope.\n\nSection CodeProof.\n\n  Context `{real_params: RealParams}.\n  Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n  Context `{Hmwd: UseMemWithData memb}.\n\n  Let mem := mwd (cdata RData).\n\n  Context `{Hstencil: Stencil}.\n  Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n  Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n  Let L : compatlayer (cdata RData) :=\n    _table_unmap ↦ gensem table_unmap_spec\n      ⊕ _table_unmap1 ↦ gensem table_unmap1_spec\n  .\n\n  Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n  Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n  Section BodyProof.\n\n    Context `{Hwb: WritableBlockOps}.\n    Variable (sc: stencil).\n    Variables (ge: genv) (STENCIL_MATCHES: stencil_matches sc ge).\n\n    Variable b_table_unmap: block.\n    Hypothesis h_table_unmap_s : Genv.find_symbol ge _table_unmap = Some b_table_unmap.\n    Hypothesis h_table_unmap_p : Genv.find_funct_ptr ge b_table_unmap\n                                 = Some (External (EF_external _table_unmap\n                                                  (signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default))\n                                        (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default).\n    Local Opaque table_unmap_spec.\n\n    Variable b_table_unmap1: block.\n    Hypothesis h_table_unmap1_s : Genv.find_symbol ge _table_unmap1 = Some b_table_unmap1.\n    Hypothesis h_table_unmap1_p : Genv.find_funct_ptr ge b_table_unmap1\n                                  = Some (External (EF_external _table_unmap1\n                                                   (signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default))\n                                         (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default).\n    Local Opaque table_unmap1_spec.\n\n    Lemma table_unmap2_body_correct:\n      forall m d d' env le g_rd_base g_rd_offset map_addr level res\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTg_rd: PTree.get _g_rd le = Some (Vptr g_rd_base (Int.repr g_rd_offset)))\n             (HPTmap_addr: PTree.get _map_addr le = Some (Vlong map_addr))\n             (HPTlevel: PTree.get _level le = Some (Vlong level))\n             (Hspec: table_unmap2_spec0 (g_rd_base, g_rd_offset) (VZ64 (Int64.unsigned map_addr)) (VZ64 (Int64.unsigned level)) d = Some (d', VZ64 (Int64.unsigned res))),\n           exists le', (exec_stmt ge env le ((m, d): mem) table_unmap2_body E0 le' (m, d') (Out_return (Some (Vlong res, tulong)))).\n    Proof.\n      solve_code_proof Hspec table_unmap2_body; eexists; solve_proof_low.\n    Qed.\n\n  End BodyProof.\n\nEnd CodeProof.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef2/CodeProof/table_unmap2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22687580170644356}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Export PBFTwell_formed_log.\nRequire Export PBFTordering.\nRequire Export PBFTprops3.\nRequire Export PBFTwf.\nRequire Export PBFTgarbage_collect.\nRequire Export PBFTpreserves_has_new_view.\nRequire Export PBFT_A_1_2_7.\n\n\n\nSection PBFT_A_1_2_1.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { pbft_context : PBFTcontext      }.\n  Context { pbft_auth    : PBFTauth         }.\n  Context { pbft_keys    : PBFTinitial_keys }.\n  Context { pbft_hash    : PBFThash         }.\n\n\n  Lemma own_prepare_is_already_logged_with_different_digest_clear_log_checkpoint_false_implies :\n    forall (n s : SeqNum) i v d L,\n      n < s\n      -> own_prepare_is_already_logged_with_different_digest i s v d (clear_log_checkpoint L n) = None\n      -> own_prepare_is_already_logged_with_different_digest i s v d L = None.\n  Proof.\n    induction L; introv h own; simpl in *; smash_pbft.\n    repeat (autodimp IHL hyp).\n    allrw SeqNumLe_true.\n    dands; auto.\n    unfold own_prepare_is_already_in_entry_with_different_digest in *; smash_pbft.\n    destruct a, log_entry_request_data; simpl in *; ginv; omega.\n  Qed.\n  Hint Resolve own_prepare_is_already_logged_with_different_digest_clear_log_checkpoint_false_implies : pbft.\n\n  Lemma update_state_new_view_preserves_own_prepare_is_already_logged_with_different_digest_false_forward :\n    forall i (s : SeqNum) v d s1 nv s2 msgs,\n      correct_new_view nv = true\n      -> update_state_new_view i s1 nv = (s2, msgs)\n      -> low_water_mark s2 < s\n      -> own_prepare_is_already_logged_with_different_digest i s v d (log s2) = None\n      -> own_prepare_is_already_logged_with_different_digest i s v d (log s1) = None.\n  Proof.\n    introv cor upd h prep.\n\n    unfold update_state_new_view in upd; smash_pbft.\n    unfold log_checkpoint_cert_from_new_view in *; smash_pbft.\n\n    - unfold update_log_checkpoint_stable, low_water_mark in *; simpl in *.\n      apply own_prepare_is_already_logged_with_different_digest_clear_log_checkpoint_false_implies in prep; eauto 3 with pbft;[].\n\n      rename_hyp_with view_change_cert2max_seq_vc mseq.\n      applydup view_change_cert2_max_seq_vc_some_in in mseq.\n      apply sn_of_view_change_cert2max_seq_vc in mseq; subst.\n\n      rename_hyp_with extract_seq_and_digest_from_checkpoint_certificate ext.\n      eapply extract_seq_and_digest_from_checkpoint_certificate_implies_eq_view_change2seq in ext; eauto 3 with pbft;[].\n      subst; auto.\n\n    - rename_hyp_with view_change_cert2max_seq_vc mseq.\n      applydup view_change_cert2_max_seq_vc_some_in in mseq.\n      apply sn_of_view_change_cert2max_seq_vc in mseq; subst.\n\n      rename_hyp_with extract_seq_and_digest_from_checkpoint_certificate ext.\n      apply extract_seq_and_digest_from_checkpoint_certificate_none_implies in ext.\n      rewrite ext in *.\n      simpl in *; ginv.\n\n    - unfold update_log_checkpoint_stable, low_water_mark in *; simpl in *.\n      apply own_prepare_is_already_logged_with_different_digest_clear_log_checkpoint_false_implies in prep; eauto 3 with pbft;[].\n\n      rename_hyp_with view_change_cert2max_seq_vc mseq.\n      applydup view_change_cert2_max_seq_vc_some_in in mseq.\n      apply sn_of_view_change_cert2max_seq_vc in mseq; subst.\n\n      rename_hyp_with extract_seq_and_digest_from_checkpoint_certificate ext.\n      eapply extract_seq_and_digest_from_checkpoint_certificate_implies_eq_view_change2seq in ext; eauto 3 with pbft;[].\n      subst; auto.\n\n    - rename_hyp_with view_change_cert2max_seq_vc mseq.\n      applydup view_change_cert2_max_seq_vc_some_in in mseq.\n      apply sn_of_view_change_cert2max_seq_vc in mseq; subst.\n\n      rename_hyp_with extract_seq_and_digest_from_checkpoint_certificate ext.\n      apply extract_seq_and_digest_from_checkpoint_certificate_none_implies in ext.\n      rewrite ext in *.\n      simpl in *; ginv.\n\n      apply correct_new_view_implies_correct_view_change in mseq0; auto.\n      unfold correct_view_change, correct_view_change_cert in *; smash_pbft.\n      rewrite ext in *; simpl in *; omega.\n  Qed.\n  Hint Resolve update_state_new_view_preserves_own_prepare_is_already_logged_with_different_digest_false_forward : pbft.\n\n\n  (* Invariant A.1.2 (1) in PBFT PhD p.145 *)\n  Lemma PBFT_A_1_2_1 :\n    forall (eo      : EventOrdering)\n           (e       : Event)\n           (i       : Rep)\n           (n       : SeqNum)\n           (v       : View)\n           (a1 a2   : Tokens)\n           (d1 d2   : PBFTdigest)\n           (state   : PBFTstate),\n      state_sm_on_event (PBFTreplicaSM i) e = Some state\n      -> prepare_in_log (mk_prepare v n d1 i a1) (log state) = true\n      -> prepare_in_log (mk_prepare v n d2 i a2) (log state) = true\n      -> d1 = d2.\n  Proof.\n    intros eo e.\n    induction e as [? ind] using predHappenedBeforeInd_local_pred;[].\n    introv eqst prep1 prep2.\n\n    dup eqst as eqst_At_e.\n    rewrite state_sm_on_event_unroll2 in eqst.\n\n    match goal with\n    | [ H : context[map_option _ ?s] |- _ ] =>\n      remember s as sop; symmetry in Heqsop; destruct sop; simpl in *;[|ginv];op_st_some m eqtrig\n    end.\n\n    unfold PBFTreplica_update in eqst.\n\n    destruct m;\n      simpl in *; ginv; subst; tcsp;\n        try smash_handlers; try (smash_pbft_ind ind).\n\n    { (* pre-prepare *)\n\n      match goal with\n      | [ H : check_send_replies _ _ _ _ _ _ = _ |- _ ] =>\n        dup H as check1; dup H as check2\n      end.\n\n      eapply check_send_replies_preserves_prepare_in_log in check1;[|exact prep1].\n      eapply check_send_replies_preserves_prepare_in_log in check2;[|exact prep2].\n      simpl in *.\n\n      match goal with\n      | [ H : add_new_pre_prepare_and_prepare2log _ _ _ _ _ _ = _ |- _ ] =>\n        dup H as add1; dup H as add2\n      end.\n\n      eapply add_new_pre_prepare_and_prepare2log_preserves_prepare_in_log in add1;[| |exact check1];\n        autorewrite with pbft in *; auto;[].\n      eapply add_new_pre_prepare_and_prepare2log_preserves_prepare_in_log in add2;[| |exact check2];\n        autorewrite with pbft in *; auto;[].\n\n      repndors; repnd; try (smash_pbft_ind ind).\n\n      - match goal with\n        | [ H : own_prepare_is_already_logged_with_different_digest _ _ _ _ _ = _ |- _ ] =>\n          eapply own_prepare_is_already_logged_with_different_digest_false_and_prepare_in_log_implies_same_digest in H;\n            [|destruct p0, b; simpl in *;\n              unfold pre_prepare2prepare, mk_prepare in *; ginv]\n        end.\n\n        match goal with\n        | [ H : mk_prepare _ _ _ _ _ = _ |- _ ] =>\n          applydup mk_prepare_eq_pre_prepare2prepare_implies_eq in H\n        end.\n        repnd; subst; auto.\n\n      - match goal with\n        | [ H : own_prepare_is_already_logged_with_different_digest _ _ _ _ _ = _ |- _ ] =>\n          eapply own_prepare_is_already_logged_with_different_digest_false_and_prepare_in_log_implies_same_digest in H;\n            [|destruct p0, b; simpl in *;\n              unfold pre_prepare2prepare, mk_prepare in *; ginv]\n        end.\n\n        match goal with\n        | [ H : mk_prepare _ _ _ _ _ = _ |- _ ] =>\n          applydup mk_prepare_eq_pre_prepare2prepare_implies_eq in H\n        end.\n        repnd; subst; auto.\n\n      - repeat\n          match goal with\n          | [ H : mk_prepare _ _ _ _ _ = _ |- _ ] =>\n            apply mk_prepare_eq_pre_prepare2prepare_implies_eq in H\n          end.\n        repnd; subst; auto.\n    }\n\n    { (* prepare *)\n\n      match goal with\n      | [ H : check_send_replies _ _ _ _ _ _ = _ |- _ ] =>\n        dup H as check1; dup H as check2\n      end.\n\n      eapply check_send_replies_preserves_prepare_in_log in check1;[|exact prep1].\n      eapply check_send_replies_preserves_prepare_in_log in check2;[|exact prep2].\n      simpl in *.\n\n      match goal with\n      | [ H : add_new_prepare2log _ _ _ _ = _ |- _ ] =>\n        dup H as add1; dup H as add2\n      end.\n\n      eapply add_new_prepare2log_preserves_prepare_in_log in add1;[|exact check1];\n        autorewrite with pbft in *; auto;[].\n      eapply add_new_prepare2log_preserves_prepare_in_log in add2;[|exact check2];\n        autorewrite with pbft in *; auto;[].\n\n      repndors; repnd;\n        try (complete (subst; simpl in *; tcsp));\n        try (smash_pbft_ind ind).\n    }\n\n    { (* commit *)\n\n      match goal with\n      | [ H : check_send_replies _ _ _ _ _ _ = _ |- _ ] =>\n        dup H as check1; dup H as check2\n      end.\n\n      eapply check_send_replies_preserves_prepare_in_log in check1;[|exact prep1].\n      eapply check_send_replies_preserves_prepare_in_log in check2;[|exact prep2].\n      simpl in *.\n\n      match goal with\n      | [ H : add_new_commit2log _ _ = _ |- _ ] =>\n        dup H as add1; dup H as add2\n      end.\n\n      eapply add_new_commit2log_preserves_prepare_in_log in add1.\n      rewrite check1 in add1; symmetry in add1.\n      eapply add_new_commit2log_preserves_prepare_in_log in add2.\n      rewrite check2 in add2; symmetry in add2.\n\n      try (smash_pbft_ind ind).\n    }\n\n    {\n      (* check-bcast-new-view*)\n\n      rename_hyp_with update_state_new_view upd.\n\n      applydup update_state_new_view_preserves_wf in upd; simpl; eauto 4 with pbft;[].\n\n      eapply update_state_new_view_preserves_prepare_in_log in prep1;[| |eauto];simpl in *;eauto 4 with pbft;[].\n      eapply update_state_new_view_preserves_prepare_in_log in prep2;[| |eauto];simpl in *;eauto 4 with pbft;[].\n      rewrite log_pre_prepares_preserves_prepare_in_log in prep1.\n      rewrite log_pre_prepares_preserves_prepare_in_log in prep2.\n      try (smash_pbft_ind ind).\n    }\n\n    { (* new-view *)\n\n      rename_hyp_with update_state_new_view upd.\n      rename_hyp_with add_prepares_to_log_from_new_view_pre_prepares add.\n\n      applydup add_prepares_to_log_from_new_view_pre_prepares_preserves_wf in add;\n        simpl; autorewrite with pbft; eauto 3 with pbft;[].\n      applydup update_state_new_view_preserves_wf in upd; simpl; eauto 3 with pbft;[].\n\n      eapply update_state_new_view_preserves_prepare_in_log2 in prep1;\n        [| | |eauto];simpl;auto.\n      eapply update_state_new_view_preserves_prepare_in_log2 in prep2;\n        [| | |eauto];simpl;auto.\n      simpl in *.\n      autorewrite with pbft in *.\n      exrepnd.\n\n      eapply add_prepares_to_log_from_new_view_pre_prepares_preserves_prepare_in_log in prep5;[|eauto];[].\n      eapply add_prepares_to_log_from_new_view_pre_prepares_preserves_prepare_in_log in prep3;[|eauto];[].\n\n      hide_hyp prep4.\n      hide_hyp prep0.\n      simpl in *.\n      autorewrite with pbft in *.\n\n      repndors; exrepnd; autorewrite with pbft in *; try (smash_pbft_ind ind);[| |].\n\n      - eapply PBFT_A_1_2_7_before in prep3;[|eauto];auto.\n        exrepnd.\n        eapply pre_prepare_in_log_implies_has_new_view_before in prep3;[|eauto];auto.\n        simpl in *.\n        apply pre_prepare_in_map_correct_new_view_implies2 in prep6;auto;[].\n        simpl in *.\n        rewrite prep6 in *.\n        destruct pp, b; simpl in *.\n        unfold mk_prepare, pre_prepare2prepare in *; ginv; simpl in *; pbft_simplifier.\n\n      - eapply PBFT_A_1_2_7_before in prep5;[|eauto];auto.\n        exrepnd.\n        eapply pre_prepare_in_log_implies_has_new_view_before in prep5;[|eauto];auto.\n        simpl in *.\n        apply pre_prepare_in_map_correct_new_view_implies2 in prep6;auto;[].\n        simpl in *.\n        rewrite prep6 in *.\n        destruct pp, b; simpl in *.\n        unfold mk_prepare, pre_prepare2prepare in *; ginv; simpl in *; pbft_simplifier.\n\n      - rename_hyp_with correct_new_view cor.\n        applydup correct_new_view_implies_norepeatsb in cor as norep.\n\n        match goal with\n        | [ H1 : mk_prepare _ _ _ _ _ = _, H2 : mk_prepare _ _ _ _ _ = _ |- _ ] =>\n          applydup mk_prepare_eq_pre_prepare2prepare_implies_eq_seq in H1 as eqsn1;\n            applydup mk_prepare_eq_pre_prepare2prepare_implies_eq_seq in H2 as eqsn2;\n            rewrite <- eqsn1 in eqsn2; clear eqsn1\n        end.\n\n        eapply norepeatsb_and_in_map_digest_same_seq_implies_eq in norep;\n          [|exact prep6|exact prep9|]; auto;[].\n        repnd; subst.\n\n        repeat\n          match goal with\n          | [ H : mk_prepare _ _ _ _ _ = _ |- _ ] =>\n            apply mk_prepare_eq_pre_prepare2prepare_implies_eq in H\n          end.\n        repnd; subst; auto.\n    }\n  Qed.\n  Hint Resolve PBFT_A_1_2_1 : pbft.\n\n  (* Uses if_prepare_in_log_digest_unique *)\n  Lemma PBFT_A_1_2_1_direct_pred :\n    forall (eo : EventOrdering)\n           (e1 e2   : Event)\n           (i       : Rep)\n           (n       : SeqNum)\n           (v       : View)\n           (a1 a2   : Tokens)  (* these two should be different!!! *)\n           (d1 d2   : PBFTdigest)\n           (state1 state2 : PBFTstate),\n      e1 ⊂ e2\n      -> state_sm_on_event (PBFTreplicaSM i) e1 = Some state1\n      -> state_sm_on_event (PBFTreplicaSM i) e2 = Some state2\n      -> prepare_in_log (mk_prepare v n d1 i a1) (log state1) = true\n      -> prepare_in_log (mk_prepare v n d2 i a2) (log state2) = true\n      -> d1 = d2.\n  Proof.\n    introv ltev eqst1 eqst2 pl1 pl2.\n\n    dup eqst2 as eqst2_At_e.\n    hide_hyp eqst2_At_e.\n\n    rewrite state_sm_on_event_unroll2 in eqst2.\n\n    match goal with\n    | [ H : context[map_option _ ?s] |- _ ] =>\n      remember s as sop; symmetry in Heqsop; destruct sop; simpl in *;[|ginv];op_st_some m eqtrig\n    end.\n\n    rewrite state_sm_before_event_as_state_sm_on_event_pred in Heqsop; eauto 2 with eo.\n    apply pred_implies_local_pred in ltev.\n    subst.\n    rewrite eqst1 in Heqsop; ginv.\n\n    unfold PBFTreplica_update in eqst2.\n\n    destruct m;\n      simpl in *; ginv; subst; tcsp;\n        try (smash_handlers); try (smash_pbft_ind ind); eauto 2 with pbft.\n\n    (* 6 goals left *)\n\n    { (* pre-prepare *)\n\n      match goal with\n      | [ H : check_send_replies _ _ _ _ _ _ = _ |- _ ] =>\n        dup H as check;\n          eapply check_send_replies_preserves_prepare_in_log in check;[|eauto];\n            simpl in *\n      end.\n\n      match goal with\n      | [ H : add_new_pre_prepare_and_prepare2log _ _ _ _ _ _ = _ |- _ ] =>\n        dup H as add;\n          eapply add_new_pre_prepare_and_prepare2log_preserves_prepare_in_log in add;\n          [| |eauto]; autorewrite with pbft in *; auto\n      end.\n\n      repndors; repnd; auto; eauto 3 with pbft;[].\n\n      match goal with\n      | [ H : own_prepare_is_already_logged_with_different_digest _ _ _ _ _ = _ |- _ ] =>\n        rename H into own;\n          eapply own_prepare_is_already_logged_with_different_digest_false_and_prepare_in_log_implies_same_digest in own;\n          [|destruct p0, b; simpl in *; unfold pre_prepare2prepare, mk_prepare in *; ginv]\n      end.\n\n      match goal with\n      | [ H : mk_prepare _ _ _ _ _ = _ |- _ ] =>\n        applydup mk_prepare_eq_pre_prepare2prepare_implies_eq in H\n      end.\n      repnd; subst; auto.\n    }\n\n    { (* prepare *)\n\n      match goal with\n      | [ H : check_send_replies _ _ _ _ _ _ = _ |- _ ] =>\n        dup H as check;\n          eapply check_send_replies_preserves_prepare_in_log in check;[|eauto];\n            simpl in *\n      end.\n\n      match goal with\n      | [ H : add_new_prepare2log _ _ _ _ = _ |- _ ] =>\n        dup H as add;\n          eapply add_new_prepare2log_preserves_prepare_in_log in add;[|exact check];\n            autorewrite with pbft in *; auto;[]\n      end.\n\n      repndors; repnd; auto; subst; simpl in *; tcsp; eauto 3 with pbft.\n    }\n\n    { (* commit *)\n\n      match goal with\n      | [ H : check_send_replies _ _ _ _ _ _ = _ |- _ ] =>\n        dup H as check;\n          eapply check_send_replies_preserves_prepare_in_log in check;[|eauto];\n            simpl in *\n      end.\n\n      match goal with\n      | [ H : add_new_commit2log _ _ = _ |- _ ] =>\n        dup H as add;\n          eapply add_new_commit2log_preserves_prepare_in_log in add;\n          rewrite check in add; symmetry in add\n      end.\n\n      eauto 3 with pbft.\n    }\n\n    {\n      (* check-ready *)\n\n      apply check_one_stable_preserves_prepare_in_log in pl2; smash_pbft.\n    }\n\n    {\n      (* check-bcast-new-view*)\n\n      rename_hyp_with update_state_new_view upd.\n\n      applydup update_state_new_view_preserves_wf in upd; simpl; eauto 4 with pbft;[].\n\n      eapply update_state_new_view_preserves_prepare_in_log in pl2;[| |eauto];simpl in *;eauto 4 with pbft;[].\n      rewrite log_pre_prepares_preserves_prepare_in_log in pl2.\n      eauto 3 with pbft.\n    }\n\n    {\n      (* new-view *)\n\n      rename_hyp_with update_state_new_view upd.\n      rename_hyp_with add_prepares_to_log_from_new_view_pre_prepares add.\n\n      applydup add_prepares_to_log_from_new_view_pre_prepares_preserves_wf in add;\n        simpl; autorewrite with pbft; eauto 3 with pbft;[].\n      applydup update_state_new_view_preserves_wf in upd; simpl; eauto 3 with pbft;[].\n\n      eapply update_state_new_view_preserves_prepare_in_log2 in pl2;\n        [| | |eauto];simpl in *; auto;[].\n      exrepnd.\n      hide_hyp pl0.\n\n      eapply add_prepares_to_log_from_new_view_pre_prepares_preserves_prepare_in_log2\n        in pl3;[|eauto];[].\n      simpl in *; autorewrite with pbft in *.\n\n      repndors; exrepnd; eauto 3 with pbft; try (smash_pbft_ind ind);[].\n\n      eapply PBFT_A_1_2_7 in pl1;[|eauto];auto; autorewrite with eo; auto;[].\n      exrepnd.\n      eapply pre_prepare_in_log_implies_has_new_view in pl1;[|eauto];auto; autorewrite with eo; auto;[].\n      simpl in *.\n      apply pre_prepare_in_map_correct_new_view_implies2 in pl4;auto;[].\n      simpl in *.\n      rewrite pl4 in *.\n      destruct pp, b; simpl in *.\n      unfold mk_prepare, pre_prepare2prepare in *; ginv; simpl in *; pbft_simplifier.\n    }\n  Qed.\n  Hint Resolve PBFT_A_1_2_1_direct_pred : pbft.\n\nEnd PBFT_A_1_2_1.\n\n\nHint Resolve update_state_new_view_preserves_wf : pbft.\nHint Resolve own_prepare_is_already_logged_with_different_digest_clear_log_checkpoint_false_implies : pbft.\nHint Resolve update_state_new_view_preserves_own_prepare_is_already_logged_with_different_digest_false_forward : pbft.\nHint Resolve PBFT_A_1_2_1 : pbft.\nHint Resolve PBFT_A_1_2_1_direct_pred : pbft.\n", "meta": {"author": "vrahli", "repo": "Velisarios", "sha": "6fb353b18610cd79210755fcc90123536c367aaa", "save_path": "github-repos/coq/vrahli-Velisarios", "path": "github-repos/coq/vrahli-Velisarios/Velisarios-6fb353b18610cd79210755fcc90123536c367aaa/PBFT/PBFT_A_1_2_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2268410282114747}}
{"text": "(** * Extensionality of boolean recognizer *)\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.StringLike.Core.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Parsers.BooleanRecognizer.\nRequire Import Fiat.Common.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.List.ListMorphisms.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nLocal Ltac subst_le_proof :=\n  idtac;\n  match goal with\n    | [ H : ?x <= ?y, H' : ?x <= ?y |- _ ]\n      => assert (H = H') by apply Le.le_proof_irrelevance; subst\n  end.\n\nSection recursive_descent_parser.\n  Context {Char} {HSL : StringLikeMin Char} {G : grammar Char}.\n  Context {data : @boolean_parser_dataT Char _}\n          {rdata : @parser_removal_dataT' _ G _}.\n\n  Create HintDb boolr_ext_db discriminated.\n  Hint Unfold Proper respectful respectful_hetero pointwise_relation forall_relation pointwise2_relation sumbool_rect : boolr_ext_db.\n  (** Dummy hint for [boolr_ext_db] to work around https://coq.inria.fr/bugs/show_bug.cgi?id=4479 *)\n  Hint Rewrite production_tl_correct : boolr_ext_db.\n\n  Local Ltac expand' :=\n    idtac;\n    (lazymatch goal with\n    | [ |- ?R = ?L ]\n      => (let rh := head R in\n          let lh := head L in\n          constr_eq rh lh;\n          progress unfold rh)\n     end).\n\n  Local Ltac t_ext' :=\n    idtac;\n    match goal with\n      | _ => reflexivity\n      | _ => solve [ eauto with nocore ]\n      | _ => progress intros\n      | _ => progress subst\n      | _ => progress subst_le_proof\n      | [ |- @list_rect ?A ?P ?Pn ?Pc ?ls = @list_rect ?A ?P ?Pn' ?Pc' ?ls ]\n        => apply (@list_rect_ext A P Pn Pn' Pc Pc' ls)\n      | [ |- @option_rect ?A ?P ?Ps ?Pn ?x = @option_rect ?A ?P ?Ps' ?Pn' ?x ]\n        => apply (@option_rect_ext A P Ps Ps' Pn Pn' x)\n      | [ |- @List.fold_left ?A ?B _ _ _ = @List.fold_left ?A ?B _ _ _ ]\n        => let lem := constr:(_ : Proper (_ ==> _ ==> _ ==> eq) (@List.fold_left A B)) in\n           apply lem\n      | [ |- @List.fold_right ?A ?B _ _ _ = @List.fold_right ?A ?B _ _ _ ]\n        => let lem := constr:(_ : Proper (_ ==> _ ==> _ ==> eq) (@List.fold_right A B)) in\n           apply lem\n      | [ |- @List.map ?A ?B _ _ = @List.map ?A ?B _ _ ]\n        => let lem := constr:(_ : Proper (_ ==> _ ==> eq) (@List.map A B)) in\n           apply lem\n      | [ |- andb ?x _ = andb ?x _ ] => apply f_equal\n      | [ |- andb _ ?x = andb _ ?x ] => apply f_equal2\n      | _ => progress autounfold with boolr_ext_db\n      | [ |- appcontext[match ?e with _ => _ end] ] => is_var e; destruct e\n      | [ |- appcontext[match ?e with _ => _ end] ] => destruct e eqn:?\n      | [ H : _ |- _ ] => rewrite H\n      | _ => progress autorewrite with boolr_ext_db\n      | _ => progress simpl option_rect\n      | [ H : cons _ _ = cons _ _ |- _ ] => inversion H; clear H\n    end.\n\n  Local Ltac t_ext tac := repeat (t_ext' || tac).\n\n  Global Instance parse_item'_Proper\n  : Proper (eq ==> pointwise_relation _ eq ==> eq ==> eq ==> eq ==> eq) (parse_item').\n  Proof. t_ext expand'. Qed.\n\n  Lemma parse_item'_ext\n        (str : String)\n        (str_matches_nonterminal str_matches_nonterminal' : nonterminal_carrierT -> bool)\n        (ext : forall s, str_matches_nonterminal s = str_matches_nonterminal' s)\n        (offset : nat)\n        (len : nat)\n        (it : item Char)\n  : parse_item' str str_matches_nonterminal offset len it\n    = parse_item' str str_matches_nonterminal' offset len it.\n  Proof.\n    change ((pointwise_relation _ eq) str_matches_nonterminal str_matches_nonterminal') in ext.\n    rewrite ext; reflexivity.\n  Qed.\n\n  Hint Rewrite parse_item'_ext : boolr_ext_db.\n\n  Inductive drop_takeT := drop_of (n : nat) | take_of (n : nat).\n\n  Fixpoint drop_takes_offset (ns : list drop_takeT) (offset : nat)\n    := match ns with\n         | nil => offset\n         | cons (drop_of n) ns' => drop_takes_offset ns' offset + n\n         | cons (take_of n) ns' => drop_takes_offset ns' offset\n       end.\n\n  Fixpoint drop_takes_len (ns : list drop_takeT) (len : nat)\n    := match ns with\n         | nil => len\n         | cons (drop_of n) ns' => drop_takes_len ns' len - n\n         | cons (take_of n) ns' => min n (drop_takes_len ns' len)\n       end.\n\n  Fixpoint drop_takes_len_pf {len0} (ns : list drop_takeT) (len : nat) (pf : len <= len0) {struct ns}\n  : drop_takes_len ns len <= len0.\n  Proof.\n    refine match ns return drop_takes_len ns len <= len0 with\n             | nil => pf\n             | cons (drop_of n) ns' => Le.le_trans _ _ _ (Minus.le_minus _ _) (@drop_takes_len_pf len0 ns' _ pf)\n             | cons (take_of n) ns' => Le.le_trans _ _ _ (Min.le_min_r _ _) (@drop_takes_len_pf len0 ns' _ pf)\n           end.\n  Defined.\n\n  Section production_drop_take.\n    Context {len0}\n            (parse_nonterminal parse_nonterminal'\n             : forall (offset : nat) (len : nat),\n                 len <= len0\n                 -> nonterminal_carrierT\n                 -> bool).\n\n    Lemma parse_production'_for_ext_drop_take\n          (str : String)\n          splits splits'\n          (offset : nat)\n          (len : nat)\n          (Hsplits : forall idx len ns, splits idx str (drop_takes_offset ns offset) (drop_takes_len ns len) = splits' idx str (drop_takes_offset ns offset) (drop_takes_len ns len))\n          (ext : forall ns offset len pf nt,\n                     @parse_nonterminal (drop_takes_offset ns offset) (drop_takes_len ns len) pf nt\n                     = @parse_nonterminal' (drop_takes_offset ns offset) (drop_takes_len ns len) pf nt)\n          (ns : list _)\n          (pf pf' : drop_takes_len ns len <= len0)\n          prod_idx\n    : parse_production'_for str parse_nonterminal splits (drop_takes_offset ns offset) pf prod_idx\n      = parse_production'_for str parse_nonterminal' splits' (drop_takes_offset ns offset) pf' prod_idx.\n    Proof.\n      remember (to_production prod_idx) as prod eqn:Heq.\n      unfold parse_production'_for.\n      revert prod_idx Heq ns offset len splits splits' Hsplits ext pf pf'; induction prod; simpl; intros;\n      rewrite <- Heq; simpl;\n      subst_le_proof;\n      t_ext idtac.\n      erewrite parse_item'_ext.\n      { apply f_equal.\n        specialize (IHprod (production_tl prod_idx)).\n        rewrite production_tl_correct in IHprod.\n        generalize dependent (to_production prod_idx); intros; subst.\n        specialize (fun n ns => IHprod eq_refl (drop_of n :: ns)%list); simpl in IHprod.\n        apply IHprod; clear IHprod; auto with nocore. }\n      { specialize (fun n ns => ext (take_of n :: ns)%list); simpl in ext.\n        auto with nocore. }\n    Qed.\n\n    Definition parse_production'_ext_drop_take\n               (str : String)\n               (offset : nat)\n               (len : nat)\n               (ext : forall ns offset len pf nt,\n                        @parse_nonterminal (drop_takes_offset ns offset) (drop_takes_len ns len) pf nt\n                        = @parse_nonterminal' (drop_takes_offset ns offset) (drop_takes_len ns len) pf nt)\n               (ns : list _)\n               (pf pf' : drop_takes_len ns len <= len0)\n               prod_idx\n    : parse_production' str parse_nonterminal (drop_takes_offset ns offset) pf prod_idx\n      = parse_production' str parse_nonterminal' (drop_takes_offset ns offset) pf prod_idx\n      := parse_production'_for_ext_drop_take _ _ _ _ _ (fun _ _ _ => eq_refl) ext _ _ _ _.\n  End production_drop_take.\n\n  Section production.\n    Context {len0} (str : String)\n            (parse_nonterminal parse_nonterminal'\n             : forall (offset : nat) (len : nat),\n                 len <= len0\n                 -> nonterminal_carrierT\n                 -> bool)\n            (ext : forall offset len pf nt,\n                     parse_nonterminal offset len pf nt\n                     = parse_nonterminal' offset len pf nt).\n\n    Lemma parse_production'_for_ext\n          splits splits'\n          (Hsplits : forall idx offset len, splits idx str offset len = splits' idx str offset len)\n          (offset : nat)\n          (len : nat)\n          (pf pf' : len <= len0)\n          prod_idx\n    : parse_production'_for str parse_nonterminal splits offset pf prod_idx\n      = parse_production'_for str parse_nonterminal' splits' offset pf' prod_idx.\n    Proof.\n      apply parse_production'_for_ext_drop_take with (ns := nil); auto with nocore.\n    Qed.\n\n    Definition parse_production'_ext\n               (offset : nat)\n               (len : nat)\n               (pf pf' : len <= len0)\n               prod_idx\n    : parse_production' str parse_nonterminal offset pf prod_idx\n      = parse_production' str parse_nonterminal' offset pf' prod_idx\n      := parse_production'_for_ext _ _ (fun _ _ _ => eq_refl) _ _ _ _.\n  End production.\n\n  Global Instance parse_production'_for_Proper\n  : Proper ((pointwise_relation _ (forall_relation (fun _ => pointwise_relation _ (pointwise_relation _ eq))))\n              ==> (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ eq))))\n              ==> eq\n              ==> forall_relation (fun _ => (fun _ _ => True) ==> eq ==> eq))\n           (parse_production'_for str (len0 := len0)).\n  Proof.\n    repeat intro; subst.\n    apply parse_production'_for_ext;\n    unfold pointwise_relation in *;\n    eauto with nocore.\n  Qed.\n\n  Global Instance parse_production'_Proper\n    : Proper ((pointwise_relation _ (forall_relation (fun _ => pointwise_relation _ (pointwise_relation _ eq))))\n                ==> eq\n                ==> forall_relation (fun _ => (fun _ _ => True) ==> eq ==> eq))\n             (parse_production' str (len0 := len0)).\n  Proof.\n    repeat intro; subst.\n    apply parse_production'_ext.\n    assumption.\n  Qed.\n\n  Section productions_drop_take.\n    Context {len0} (str : String)\n            (parse_nonterminal parse_nonterminal'\n             : forall (offset : nat)\n                      (len : nat)\n                      (pf : len <= len0),\n                 nonterminal_carrierT -> bool).\n\n    Lemma parse_productions'_ext_drop_take\n          (ext : forall ns offset len pf nt,\n                   @parse_nonterminal (drop_takes_offset ns offset) (drop_takes_len ns len) pf nt\n                   = @parse_nonterminal' (drop_takes_offset ns offset) (drop_takes_len ns len) pf nt)\n          (offset : nat)\n          (len : nat)\n          ns\n          (pf pf' : drop_takes_len ns len <= len0)\n          (prods : list production_carrierT)\n    : parse_productions' str parse_nonterminal (drop_takes_offset ns offset) pf prods\n      = parse_productions' str parse_nonterminal' (drop_takes_offset ns offset) pf' prods.\n    Proof.\n      t_ext ltac:(erewrite parse_production'_for_ext_drop_take || expand').\n    Qed.\n  End productions_drop_take.\n\n  Section productions.\n    Context {len0} (str : String)\n            (parse_nonterminal parse_nonterminal'\n             : forall (offset : nat)\n                      (len : nat)\n                      (pf : len <= len0),\n                 nonterminal_carrierT -> bool)\n            (ext : forall str len pf nt,\n                     parse_nonterminal str len pf nt\n                     = parse_nonterminal' str len pf nt).\n\n    Lemma parse_productions'_ext\n          (offset : nat)\n          (len : nat)\n          (pf pf' : len <= len0)\n          (prods : list production_carrierT)\n    : parse_productions' str parse_nonterminal offset pf prods\n      = parse_productions' str parse_nonterminal' offset pf' prods.\n    Proof.\n      apply parse_productions'_ext_drop_take with (ns := nil); auto with nocore.\n    Qed.\n  End productions.\n\n  Global Instance parse_productions'_Proper\n  : Proper ((pointwise_relation _ (forall_relation (fun _ => pointwise_relation _ (pointwise_relation _ eq))))\n              ==> eq\n              ==> forall_relation (fun _ => (fun _ _ => True) ==> eq ==> eq))\n           (parse_productions' str (len0 := len0)).\n  Proof.\n    repeat intro; subst.\n    apply parse_productions'_ext.\n    assumption.\n  Qed.\n\n  Section nonterminals.\n    Section step_drop_take.\n      Context {len0 valid_len} (str : String)\n              (parse_nonterminal parse_nonterminal'\n               : forall (p : nat * nat),\n                   Wf.prod_relation lt lt p (len0, valid_len)\n                   -> forall (valid : nonterminals_listT)\n                             (offset : nat) (len : nat),\n                        len <= fst p -> nonterminal_carrierT -> bool).\n\n      Definition parse_nonterminal_step_ext_drop_take\n                 (valid : nonterminals_listT)\n                 (ext : forall ns p pf valid offset len pf' nt,\n                          @parse_nonterminal p pf valid (drop_takes_offset ns offset) (drop_takes_len ns len) pf' nt\n                          = @parse_nonterminal' p pf valid (drop_takes_offset ns offset) (drop_takes_len ns len) pf' nt)\n                 (offset : nat)\n                 (len : nat)\n                 ns\n                 (pf pf' : drop_takes_len ns len <= len0)\n                 (nt : nonterminal_carrierT)\n      : parse_nonterminal_step str parse_nonterminal valid (drop_takes_offset ns offset) pf nt\n        = parse_nonterminal_step str parse_nonterminal' valid (drop_takes_offset ns offset) pf' nt.\n      Proof.\n        t_ext ltac:(erewrite parse_productions'_ext_drop_take || expand').\n      Qed.\n    End step_drop_take.\n\n    Section step.\n      Context {len0 valid_len} (str : String)\n              (parse_nonterminal parse_nonterminal'\n               : forall (p : nat * nat),\n                   Wf.prod_relation lt lt p (len0, valid_len)\n                   -> forall (valid : nonterminals_listT)\n                             (offset : nat) (len : nat),\n                        len <= fst p -> nonterminal_carrierT -> bool)\n              (ext : forall p pf valid str len pf' nt,\n                       parse_nonterminal p pf valid str len pf' nt\n                       = parse_nonterminal' p pf valid str len pf' nt).\n\n      Definition parse_nonterminal_step_ext\n                 (valid : nonterminals_listT)\n                 (offset : nat)\n                 (len : nat)\n                 (pf pf' : len <= len0)\n                 (nt : nonterminal_carrierT)\n      : parse_nonterminal_step str parse_nonterminal valid offset pf nt\n        = parse_nonterminal_step str parse_nonterminal' valid offset pf' nt.\n      Proof.\n        apply parse_nonterminal_step_ext_drop_take with (ns := nil); auto with nocore.\n      Qed.\n    End step.\n\n    Global Instance parse_nonterminal_step_Proper\n    : Proper ((forall_relation (fun _ => pointwise_relation _ (pointwise_relation _ (pointwise_relation _ (forall_relation (fun _ => pointwise_relation _ (pointwise_relation _ eq)))))))\n                ==> eq\n                ==> eq\n                ==> forall_relation (fun _ => (fun _ _ => True) ==> eq ==> eq))\n             (parse_nonterminal_step str (len0 := len0) (valid_len := valid_len)).\n    Proof.\n      repeat intro; subst.\n      apply parse_nonterminal_step_ext.\n      assumption.\n    Qed.\n  End nonterminals.\nEnd recursive_descent_parser.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_simpl_example/src/Parsers/BooleanRecognizerExt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.22684102821147462}}
{"text": "(** * Functional correctness of the compiler *)\n\n(** We finally turn to proving our compiler correct.\n\nSAZ: This needs to be updated.\n\n    We express the result as a (weak) bisimulation between\n    the [itree] resulting from the denotation of the source\n    _Imp_ statement and the denotation of the compiled _Asm_\n    program. This weak bisimulation is a _up-to-tau_ bisimulation.\n    More specifically, we relate the itrees after having\n    interpreted the events contained in the trees, and run\n    the resulting computation from the state monad:\n    [ImpState] on the _Imp_ side, [Reg] and [Memory] on the\n    _Asm_ side.\n\n    The proof is essentially structured as followed:\n    - a simulation relation is defined to relate the _Imp_\n    state to the _Asm_ memory during the simulation. This\n    relation is strengthened into a second one additionally\n    relating the result of the denotation of an expression to\n    the _Asm_ set of registers, and used during the simulation\n    of expressions.\n    - the desired bisimulation is defined to carry out the\n    the simulation invariant into a up-to-tau equivalence after\n    interpretation of events. Once again a slightly different\n    bisimulation is defined when handling expressions.\n    - Linking is proved in isolation: the \"high level\" control\n    flow combinators for _Asm_ defined in [Imp2Asm.v] are\n    proved correct in the same style as the elementary ones\n    from [AsmCombinators.v].\n    - Finally, all the pieces are tied together to prove the\n    correctness.\n\n    We emphasize the following aspects of the proof:\n    - Despite establishing a termination-sensitive correctness\n    result over Turing-complete languages, we have not written\n    a single [cofix]. All coinductive reasoning is internalized\n    into the [itree] library.\n    - We have separated the control-flow-related reasoning from\n    the functional correctness one. In particular, the low-level\n    [asm] combinators are entirely reusable, and the high-level\n    ones are only very loosely tied to _Imp_.\n    - All reasoning is equational. In particular, reasoning at the\n    level of [ktree]s rather than introducing the entry label and\n    trying to reason at the level of [itree]s ease sensibly the pain\n    by reducing the amount of binders under which we need to work.\n    - We transparently make use of the heterogeneous bisimulation provided\n    by the [itree] library to relate computations of _Asm_ expressions that\n    return a pair of environments (registers and memory) and a [unit] value to\n    ones of _Imp_ that return a single environment and an [Imp.value].\n *)\n\n(* begin hide *)\nFrom ITreeTutorial Require Import Imp Asm Utils_tutorial AsmCombinators Imp2Asm Fin KTreeFin.\n\nFrom Coq Require Import\n     Psatz\n     Strings.String\n     List\n     Program.Basics\n     Morphisms\n     ZArith\n     Setoid\n     RelationClasses.\n\nFrom ITree Require Import\n     ITree\n     ITreeFacts\n     Basics.CategorySub\n     Basics.HeterogeneousRelations\n     Events.StateFacts\n     Events.MapDefault.\n\nImport ITreeNotations.\n\nFrom ExtLib Require Import\n     Data.String\n     Core.RelDec\n     Structures.Monad\n     Structures.Maps\n     Data.Map.FMapAList.\n\nImport ListNotations.\nOpen Scope string_scope.\n\nImport CatNotations.\nLocal Open Scope cat_scope.\nLocal Open Scope itree_scope.\n\n(* end hide *)\n\n\n(* ================================================================= *)\n(** ** Simulation relations and invariants *)\n\n(** The compiler is proved correct by constructing a (itree) bisimulation\n    between the source program and its compilation.  The compiler does two\n    things that affect the state:\n\n      - it translates source Imp variables to Asm global variables, which should\n        match at each step of computation\n\n      - it introduces temporary local variables that name intermediate values\n\n    As is traditional, we define, to this end, a simulation relation [Renv] and\n    invariants that relate the source Imp environment to the target Asm\n    environment, following the description above.\n\n    [Renv] relates two [alist var value] environments if they act as\n    equivalent maps.  This is used to relate Imp's [ImpState] environment to\n    Asm's [Memory].\n\n*)\n\nSection Simulation_Relation.\n\n  (** ** Definition of the simulation relations *)\n\n  (** The simulation relation for evaluation of statements.\n      The relation relates two environments of type [alist var value].\n      The source and target environments exactly agree on user variables.\n   *)\n  Definition Renv (g_imp : Imp.env) (g_asm : Asm.memory) : Prop :=\n    forall k v, alist_In k g_imp v <-> alist_In k g_asm v.\n\n  Global Instance Renv_refl : Reflexive Renv.\n  Proof.\n    red. intros. unfold Renv. tauto.\n  Qed.\n\n (** The simulation relation for evaluation of expressions.\n\n     The relation connects\n\n       - the global state at the Imp level\n\n       - the memory and register states at the Asm level\n\n     and, additionally the returned value at the _Imp_ level. The _Asm_ side\n     does not carry a [value], but a [unit], since its denotation does not\n     return any [value].\n\n     The [sim_rel] relation is parameterized by the state of the local [asm]\n     environment before the step, and the name of the variable used to store the\n     result.\n\n\n     It enforces three conditions:\n     - [Renv] on the global environments, ensuring that evaluation of expressions does\n     not change user variables;\n\n     - Agreement on the computed value, i.e. the returned value [v] is stored at\n     the assembly level in the expected temporary;\n\n     - The \"stack\" of temporaries used to compute intermediate results is left\n       untouched.\n  *)\n  Definition sim_rel l_asm n: (env * value) -> (memory * (registers * unit)) -> Prop :=\n    fun '(g_imp', v) '(g_asm', (l_asm', _))  =>\n      Renv g_imp' g_asm' /\\            (* we don't corrupt any of the imp variables *)\n      alist_In n l_asm' v /\\           (* we get the right value *)\n      (forall m, m < n -> forall v,              (* we don't mess with anything on the \"stack\" *)\n            alist_In m l_asm v <-> alist_In m l_asm' v).\n\n  Lemma sim_rel_find : forall g_asm g_imp l_asm l_asm' n  v,\n    sim_rel l_asm n (g_imp, v) (g_asm, (l_asm', tt)) ->\n    alist_find n l_asm' = Some v.\n  Proof.\n    intros.\n    destruct H as [_ [IN _]].\n    apply IN.\n  Qed.\n\n  (** ** Facts on the simulation relations *)\n\n  (** [Renv] entails agreement of lookup of user variables. *)\n  Lemma Renv_find:\n    forall g_asm g_imp x,\n      Renv g_imp g_asm ->\n      alist_find x g_imp = alist_find x g_asm.\n  Proof.\n    intros.\n    destruct (alist_find x g_imp) eqn:LUL, (alist_find x g_asm) eqn:LUR; auto.\n    - eapply H in LUL.\n      rewrite LUL in LUR; auto.\n    - eapply H in LUL.\n      rewrite LUL in LUR; auto.\n    - eapply H in LUR.\n      rewrite LUR in LUL; inv LUL.\n  Qed.\n\n  (** [sim_rel] can be initialized from [Renv]. *)\n  Lemma sim_rel_add: forall g_asm l_asm g_imp n v,\n      Renv g_imp g_asm ->\n      sim_rel l_asm n  (g_imp, v) (g_asm, (alist_add n v l_asm, tt)).\n  Proof.\n    intros.\n    split; [| split].\n    - assumption.\n    - apply In_add_eq.\n    - intros m LT v'.\n      apply In_add_ineq_iff; lia.\n  Qed.\n\n  (** [Renv] can be recovered from [sim_rel]. *)\n  Lemma sim_rel_Renv: forall l_asm n s1 l v1 s2 v2,\n      sim_rel l_asm n (s2,v2) (s1,(l,v1)) -> Renv s2 s1 .\n  Proof.\n    intros ? ? ? ? ? ? ? H; apply H.\n  Qed.\n\n  Lemma sim_rel_find_tmp_n:\n    forall l_asm g_asm' n l_asm' g_imp' v,\n      sim_rel l_asm n  (g_imp',v) (g_asm', (l_asm', tt)) ->\n      alist_In n l_asm' v.\n  Proof.\n    intros ? ? ? ? ? ? [_ [H _]]; exact H.\n  Qed.\n\n  (** [sim_rel] entails agreement of lookups in the \"stack\" between its argument\n      and the current Asm environement *)\n  Lemma sim_rel_find_tmp_lt_n:\n    forall l_asm g_asm' n m l_asm' g_imp' v,\n      m < n ->\n      sim_rel l_asm n (g_imp',v) (g_asm', (l_asm', tt)) ->\n      alist_find m l_asm = alist_find m l_asm'.\n  Proof.\n    intros ? ? ? ? ? ? ? ineq [_ [_ H]].\n    match goal with\n    | |- _ = ?x => destruct x eqn:EQ\n    end.\n    setoid_rewrite (H _ ineq); auto.\n    match goal with\n    | |- ?x = _ => destruct x eqn:EQ'\n    end; [| reflexivity].\n    setoid_rewrite (H _ ineq) in EQ'.\n    rewrite EQ' in EQ; easy.\n  Qed.\n\n  Lemma sim_rel_find_tmp_n_trans:\n    forall l_asm n l_asm' l_asm'' g_asm' g_asm'' g_imp' g_imp'' v v',\n      sim_rel l_asm n (g_imp',v) (g_asm', (l_asm', tt))  ->\n      sim_rel l_asm' (S n) (g_imp'',v') (g_asm'', (l_asm'', tt))  ->\n      alist_In n l_asm'' v.\n  Proof.\n    intros.\n    generalize H; intros LU; apply sim_rel_find_tmp_n in LU.\n    unfold alist_In in LU; erewrite sim_rel_find_tmp_lt_n in LU; eauto.\n  Qed.\n\n  (** [Renv] is preserved by assignment.\n   *)\n  Lemma Renv_write_local:\n    forall (k : Imp.var) (g_asm g_imp : alist var value) v,\n      Renv g_imp g_asm ->\n      Renv (alist_add k v g_imp) (alist_add k v g_asm).\n  Proof.\n    intros k m m' v HRel k' v'.\n    unfold alist_add, alist_In; simpl.\n    flatten_goal;\n      repeat match goal with\n             | h: _ = true |- _ => rewrite rel_dec_correct in h\n             | h: _ = false |- _ => rewrite <- neg_rel_dec_correct in h\n             end; try subst.\n    - tauto.\n    - setoid_rewrite In_remove_In_ineq_iff; eauto using RelDec_Correct_string.\n  Qed.\n\n  (** [sim_rel] can be composed when proving binary arithmetic operators. *)\n  Lemma sim_rel_binary_op:\n    forall (l_asm l_asm' l_asm'' : registers) (g_asm' g_asm'' : memory) (g_imp' g_imp'' : env)\n      (n v v' : nat)\n      (Hsim : sim_rel l_asm n (g_imp', v) (g_asm', (l_asm', tt)))\n      (Hsim': sim_rel l_asm' (S n) (g_imp'', v') (g_asm'', (l_asm'', tt)))\n      (op: nat -> nat -> nat),\n      sim_rel l_asm n (g_imp'', op v v') (g_asm'', (alist_add n (op v v') l_asm'', tt)).\n  Proof.\n    intros.\n    split; [| split].\n    - eapply sim_rel_Renv; eassumption.\n    - apply In_add_eq.\n    - intros m LT v''.\n      rewrite <- In_add_ineq_iff; [| lia].\n      destruct Hsim as [_ [_ Hsim]].\n      destruct Hsim' as [_ [_ Hsim']].\n      rewrite Hsim; [| auto with arith].\n      rewrite Hsim'; [| auto with arith].\n      reflexivity.\n  Qed.\n\nEnd Simulation_Relation.\n\n(* ================================================================= *)\n(** ** Bisimulation *)\n\n(** We now make precise the bisimulation established to show the correctness of\n    the compiler.  Naturally, we cannot establish a _strong bisimulation_\n    between the source program and the target program: the [asm] counterpart\n    performs \"more steps\" when evaluating expressions.  The appropriate notion\n    is of course the _equivalence up to tau_. However, the [itree] structures\n    are also quite different.  [asm] programs manipulate two state\n    components. The simulation will establish that the [imp] global state\n    corresponds to the [asm] memory, but to be able to  establish this\n    correspondence, we also need to interpret the [asm] register effects.  *)\n\nSection Bisimulation.\n\n\n  (** Definition of our bisimulation relation.\n\n      As previously explained, the bisimulation relates (up-to-tau)\n      two [itree]s after having interpreted their events.\n\n      We additionally bake into it a simulation invariant:\n      - Events are interpreted from states related by [Renv]\n      - Returned values must contain related states, as well as computed datas\n        related by another relation [RAB] taken in parameter.\n      In our case, we will specialize [RAB] to the total relation since the trees return\n      respectively [unit] and the unique top-level label [F0: fin 1].\n   *)\n\n  Section RAB.\n\n    Context {A B : Type}.\n    Context (RAB : A -> B -> Prop).  (* relation on Imp / Asm values *)\n\n    Definition state_invariant (a : Imp.env * A) (b : Asm.memory * (Asm.registers * B))  :=\n      Renv (fst a) (fst b) /\\ (RAB (snd a) (snd (snd b))).\n\n    Definition bisimilar {E} (t1 : itree (ImpState +' E) A) (t2 : itree (Reg +' Memory +' E) B)  :=\n    forall g_asm g_imp l,\n      Renv g_imp g_asm ->\n      eutt state_invariant\n           (interp_imp t1 g_imp)\n           (interp_asm t2 g_asm l).\n  End RAB.\n\n\n  (** [bisimilar] is compatible with [eutt]. *)\n\n  Global Instance eutt_bisimilar  {A B E}  (RAB : A -> B -> Prop):\n    Proper (eutt eq ==> eutt eq ==> iff) (@bisimilar A B RAB E).\n  Proof.\n    repeat intro.\n    unfold bisimilar. split.\n    - intros.\n      rewrite <- H, <- H0. auto.\n    - intros.\n      rewrite H, H0. auto.\n  Qed.\n\n  Lemma bisimilar_bind' {A A' B C E} (RAA' : A -> A' -> Prop) (RBC: B -> C -> Prop):\n    forall (t1 : itree (ImpState +' E) A) (t2 : itree (Reg +' Memory +' E) A') ,\n      bisimilar RAA' t1 t2 ->\n      forall (k1 : A -> itree (ImpState +' E) B) (k2 : A' -> itree (Reg +' Memory +' E) C)\n        (H: forall (a:A) (a':A'), RAA' a a' -> bisimilar RBC (k1 a) (k2 a')),\n        bisimilar RBC (t1 >>= k1) (t2 >>= k2).\n  Proof.\n    repeat intro.\n    rewrite interp_asm_bind.\n    rewrite interp_imp_bind.\n    eapply eutt_clo_bind.\n    { eapply H; auto. }\n    intros.\n    destruct u1 as [? ?].\n    destruct u2 as [? [? ?]].\n    unfold state_invariant in H2.\n    simpl in H2. destruct H2. subst.\n    eapply H0; eauto.\n  Qed.\n\n  Lemma bisimilar_iter {E A A' B B'}\n        (R : A -> A' -> Prop)\n        (S : B -> B' -> Prop)\n        (t1 : A -> itree (_ +' E) (A + B))\n        (t2 : A' -> itree (_ +' _ +' E) (A' + B')) :\n    (forall l l', R l l' -> bisimilar (sum_rel R S) (t1 l) (t2 l')) ->\n    forall x x', R x x' ->\n    bisimilar S (iter (C := ktree _) t1 x) (iter (C := ktree _) t2 x').\n  Proof.\n\n    unfold bisimilar, interp_asm, interp_imp, interp_map.\n    intros. rewrite 2 interp_iter.\n    unfold iter, Iter_Kleisli.\n    pose proof @interp_state_iter'.\n    red in H2. unfold Basics.iter, MonadIter_itree.\n\n    rewrite 2 H2.\n    unfold Basics.iter, MonadIter_stateT0, Basics.iter, MonadIter_itree; cbn.\n    rewrite H2.\n    apply (eutt_iter' (state_invariant R)).\n    intros.\n    destruct H3; cbn.\n    rewrite interp_state_bind, bind_bind.\n    setoid_rewrite interp_state_ret.\n    setoid_rewrite bind_ret_l. cbn.\n    apply (@eutt_clo_bind _ _ _ _ _ _ (state_invariant (sum_rel R S))).\n    - auto.\n    - intros ? ? [? []]; cbn; apply eqit_Ret; constructor; split; auto.\n    - constructor; auto.\n  Qed.\n\n  (** [sim_rel] at [n] entails that [GetVar (gen_tmp n)] gets interpreted\n      as returning the same value as the _Imp_ related one.\n   *)\n  Lemma sim_rel_get_tmp0:\n    forall {E} n l l' g_asm g_imp v,\n      sim_rel l' n (g_imp,v) (g_asm, (l,tt)) ->\n      (interp_asm ((trigger (GetReg n)) : itree (Reg +' Memory +' E) value)\n                                       g_asm l)\n      ≈     (Ret (g_asm, (l, v))).\n  Proof.\n    intros.\n    unfold interp_asm.\n    rewrite interp_trigger.\n    cbn.\n    unfold interp_map.\n    unfold h_reg, CategoryOps.cat, Cat_Handler, Handler.cat.\n    unfold inl_, Inl_sum1_Handler, Handler.inl_, Handler.htrigger. cbn.\n    unfold lookup_def; cbn.\n    unfold embed, Embeddable_itree, Embeddable_forall, embed.\n    rewrite interp_trigger.\n    rewrite interp_state_trigger_eqit.\n    cbn.\n    rewrite bind_ret_l, tau_eutt.\n    rewrite interp_state_ret.\n    unfold lookup_default, lookup, Map_alist.\n    erewrite sim_rel_find.\n    reflexivity.\n    apply H.\n  Qed.\n\n\nEnd Bisimulation.\n\n(* ================================================================= *)\n(** ** Linking *)\n\n(** We first show that our \"high level\" [asm] combinators are correct.  These\n    proofs are mostly independent from the compiler, and therefore fairly\n    reusable.  Once again, these notion of correctness are expressed as\n    equations commuting the denotation with the combinator.  *)\n\nSection Linking.\n\n  Import KTreeFin.\n\n  Context {E} `{Reg -< E, Memory -< E, Exit -< E}.\n\n  Notation denote_asm := (Asm.denote_asm (E := E)).\n\n  (** [seq_asm] is denoted as the (horizontal) composition of denotations. *)\n  Lemma seq_asm_correct {A B C} (ab : asm A B) (bc : asm B C) :\n      denote_asm (seq_asm ab bc)\n    ⩯ denote_asm ab >>> denote_asm bc.\n  Proof.\n    unfold seq_asm.\n    rewrite loop_asm_correct, relabel_asm_correct, app_asm_correct.\n    rewrite fmap_id0, cat_id_r, fmap_swap.\n    apply cat_from_loop.\n  Qed.\n\n  (** [if_asm] is denoted as the ktree first denoting the branching condition,\n      then looking-up the appropriate variable and following with either denotation. *)\n  Lemma if_asm_correct {A} (e : list instr) (tp fp : asm 1 A) :\n      denote_asm (if_asm e tp fp)\n    ⩯ ((fun _ =>\n         denote_list e ;;\n         v <- trigger (GetReg tmp_if) ;;\n         if v : value then denote_asm fp f0 else denote_asm tp f0)).\n  Proof.\n    unfold if_asm.\n    rewrite seq_asm_correct.\n    unfold cond_asm.\n    rewrite raw_asm_block_correct_lifted.\n    rewrite relabel_asm_correct.\n\n    intros ?.\n    Local Opaque Asm.denote_asm.\n\n    unfold CategoryOps.cat, Cat_sub, CategoryOps.cat, Cat_Kleisli; simpl.\n    rewrite denote_after.\n    cbn.\n    repeat setoid_rewrite bind_bind.\n    apply eqit_bind; try reflexivity. intros _.\n    apply eqit_bind; try reflexivity. intros [].\n\n    - rewrite !bind_ret_l.\n      setoid_rewrite (app_asm_correct tp fp _).\n      setoid_rewrite bind_bind.\n      match goal with\n      | [ |- _ (?t >>= _) _ ] => let y := eval compute in t in change t with y\n      end.\n      rewrite bind_ret_l. cbn.\n      setoid_rewrite bind_ret_l.\n      rewrite bind_bind.\n      setoid_rewrite bind_ret_l.\n      unfold from_bif, FromBifunctor_ktree_fin; cbn.\n      rewrite bind_ret_r'.\n      { rewrite (unique_f0 (fi' 0)). reflexivity. }\n      { intros.\n        Local Opaque split_fin_sum R. cbv. Local Transparent split_fin_sum R.\n        rewrite split_fin_sum_R. reflexivity. }\n\n    - rewrite !bind_ret_l.\n      setoid_rewrite (app_asm_correct tp fp _).\n      repeat setoid_rewrite bind_bind.\n      match goal with\n      | [ |- _ (?t >>= _) _ ] => let y := eval compute in t in change t with y\n      end.\n      rewrite bind_ret_l. cbn. rewrite bind_bind.\n      setoid_rewrite bind_ret_l.\n      unfold from_bif, FromBifunctor_ktree_fin.\n      setoid_rewrite bind_ret_l.\n      rewrite bind_ret_r'.\n      { rewrite (unique_f0 (fi' 0)). reflexivity. }\n      { intros. Local Opaque split_fin_sum L. cbv. Local Transparent split_fin_sum R.\n        rewrite split_fin_sum_L. reflexivity. }\n  Qed.\n\n  (** [while_asm] is denoted as the loop of the body with two entry point, the exit\n      of the loop, and the body in which we have the same structure as for the conditional *)\n  Notation label_case := (split_fin_sum _ _).\n\n  Lemma while_asm_correct (e : list instr) (p : asm 1 1) :\n      denote_asm (while_asm e p)\n    ⩯ (loop (C := sub (ktree _) fin) (fun l : fin (1 + 1) =>\n         match label_case l with\n         | inl _ =>\n           denote_list e ;;\n           v <- trigger (GetReg tmp_if) ;;\n           if (v:value) then Ret (fS f0) else (denote_asm p f0;; Ret f0)\n         | inr _ => Ret f0\n         end)).\n  Proof.\n    unfold while_asm.\n    rewrite loop_asm_correct.\n    apply Proper_loop.\n    rewrite relabel_asm_correct.\n    rewrite fmap_id0, cat_id_l.\n    rewrite app_asm_correct.\n    rewrite if_asm_correct.\n    intros x.\n    cbn.\n    unfold to_bif, ToBifunctor_ktree_fin.\n    rewrite bind_ret_l.\n    destruct (label_case x); cbn.\n    - rewrite !bind_bind. setoid_rewrite bind_ret_l.\n      eapply eutt_clo_bind; try reflexivity. intros; subst.\n      rewrite bind_bind.\n      eapply eutt_clo_bind; try reflexivity. intros; subst.\n      unfold from_bif, FromBifunctor_ktree_fin; cbn.\n      setoid_rewrite bind_ret_l.\n      destruct u0.\n      + rewrite (pure_asm_correct _ _); cbn.\n        rewrite !bind_ret_l.\n        apply eqit_Ret.\n        apply unique_fin; reflexivity.\n\n      + rewrite (relabel_asm_correct _ _ _ _). cbn.\n        rewrite bind_ret_l.\n        setoid_rewrite bind_bind.\n        eapply eutt_clo_bind; try reflexivity.\n        intros ? ? [].\n        repeat rewrite bind_ret_l.\n        apply eqit_Ret.\n        rewrite (unique_f0 u1).\n        apply unique_fin; reflexivity.\n\n    - cbn.\n      rewrite (pure_asm_correct _ _).\n      rewrite bind_bind. cbn.\n      unfold from_bif, FromBifunctor_ktree_fin.\n      rewrite !bind_ret_l.\n      apply eqit_Ret.\n      rewrite (unique_f0 f).\n      apply unique_fin; reflexivity.\nQed.\n\nEnd Linking.\n\n(* ================================================================= *)\n(** ** Correctness *)\n\nSection Correctness.\n\n\n  (** Correctness of expressions.\n      We strengthen [bisimilar]: initial environments are still related by [Renv],\n      but intermediate ones must now satisfy [sim_rel].\n      Note that by doing so, we use a _heterogeneous bisimulation_: the trees\n      return values of different types ([alist var value * unit] for _Asm_,\n      [alist var value * value] for _Imp_). The difference is nonetheless mostly\n      transparent for the user, except for the use of the more general lemma [eqit_bind'].\n   *)\n  Lemma compile_expr_correct : forall {E} e g_imp g_asm l n,\n      Renv g_imp g_asm ->\n      @eutt E _ _ (sim_rel l n)\n            (interp_imp (denote_expr e) g_imp)\n            (interp_asm (denote_list (compile_expr n e)) g_asm l).\n  Proof.\n    induction e; simpl; intros.\n    - (* Var case *)\n      (* We first compute and eliminate taus on both sides. *)\n      force_left.\n      rewrite tau_eutt.\n\n      tau_steps.\n\n      (* We are left with [Ret] constructs on both sides, that remains to be related *)\n      red; rewrite <-eqit_Ret.\n      unfold lookup_default, lookup, Map_alist.\n\n      (* On the _Asm_ side, we bind to [gen_tmp n] a lookup to [varOf v] *)\n      (* On the _Imp_ side, we return the value of a lookup to [varOf v] *)\n      erewrite Renv_find; [| eassumption].\n      apply sim_rel_add; assumption.\n\n    - (* Literal case *)\n      (* We reduce both sides to Ret constructs *)\n      tau_steps.\n\n      red; rewrite <-eqit_Ret.\n      (* _Asm_ bind the litteral to [gen_tmp n] while _Imp_ returns it *)\n      apply sim_rel_add; assumption.\n\n    (* The three binary operator cases are identical *)\n    - (* Plus case *)\n      (* We push [interp_locals] into the denotations *)\n\n      do 2 setoid_rewrite denote_list_app.\n      rewrite interp_asm_bind.\n      rewrite interp_imp_bind.\n\n      (* The Induction hypothesis on [e1] relates the first itrees *)\n      eapply eutt_clo_bind.\n      { eapply IHe1; assumption. }\n      (* We obtain new related environments *)\n      intros [g_imp' v] [g_asm' [l' []]] HSIM.\n      (* The Induction hypothesis on [e2] relates the second itrees *)\n      rewrite interp_asm_bind.\n      rewrite interp_imp_bind.\n      eapply eutt_clo_bind.\n      { eapply IHe2.\n        eapply sim_rel_Renv; eassumption. }\n      (* And we once again get new related environments *)\n      intros [g_imp'' v'] [g_asm'' [l'' []]] HSIM'.\n      (* We can now reduce down to Ret constructs that remains to be related *)\n      tau_steps.\n      red. rewrite <- eqit_Ret.\n\n      clear -HSIM HSIM'. unfold lookup_default, lookup, Map_alist.\n      erewrite sim_rel_find_tmp_n_trans; eauto.\n      erewrite sim_rel_find_tmp_n; eauto.\n      eapply sim_rel_binary_op; eauto.\n\n    - (* Sub case *)\n      (* We push [interp_locals] into the denotations *)\n      do 2 setoid_rewrite denote_list_app.\n      rewrite interp_asm_bind.\n      rewrite interp_imp_bind.\n\n      (* The Induction hypothesis on [e1] relates the first itrees *)\n      eapply eutt_clo_bind.\n      { eapply IHe1; assumption. }\n      (* We obtain new related environments *)\n      intros [g_imp' v] [g_asm' [l' []]] HSIM.\n      (* The Induction hypothesis on [e2] relates the second itrees *)\n      rewrite interp_asm_bind.\n      rewrite interp_imp_bind.\n      eapply eutt_clo_bind.\n      { eapply IHe2.\n        eapply sim_rel_Renv; eassumption. }\n      (* And we once again get new related environments *)\n      intros [g_imp'' v'] [g_asm'' [l'' []]]  HSIM'.\n      (* We can now reduce down to Ret constructs that remains to be related *)\n      tau_steps.\n      red. rewrite <- eqit_Ret.\n\n      clear -HSIM HSIM'. unfold lookup_default, lookup, Map_alist.\n      erewrite sim_rel_find_tmp_n_trans; eauto.\n      erewrite sim_rel_find_tmp_n; eauto.\n      eapply sim_rel_binary_op; eauto.\n\n    - (* Mul case *)\n      (* We push [interp_locals] into the denotations *)\n      do 2 setoid_rewrite denote_list_app.\n      rewrite interp_asm_bind.\n      rewrite interp_imp_bind.\n\n      (* The Induction hypothesis on [e1] relates the first itrees *)\n      eapply eutt_clo_bind.\n      { eapply IHe1; assumption. }\n      (* We obtain new related environments *)\n      intros [g_imp' v] [g_asm' [l' []]] HSIM.\n      (* The Induction hypothesis on [e2] relates the second itrees *)\n      rewrite interp_asm_bind.\n      rewrite interp_imp_bind.\n      eapply eutt_clo_bind.\n      { eapply IHe2.\n        eapply sim_rel_Renv; eassumption. }\n      (* And we once again get new related environments *)\n      intros [g_imp'' v'] [g_asm'' [l'' []]] HSIM'.\n      (* We can now reduce down to Ret constructs that remain to be related *)\n      tau_steps.\n      red. rewrite <- eqit_Ret.\n\n      clear -HSIM HSIM'. unfold lookup_default, lookup, Map_alist.\n      erewrite sim_rel_find_tmp_n_trans; eauto.\n      erewrite sim_rel_find_tmp_n; eauto.\n      eapply sim_rel_binary_op; eauto.\n  Qed.\n\n  (** Correctness of the assign statement.\n      The resulting list of instructions is denoted as\n      denoting the expression followed by setting the variable.\n   *)\n  Lemma compile_assign_correct : forall {E} e x,\n      bisimilar eq\n        ((v <- denote_expr e ;; trigger (Imp.SetVar x v)) : itree (ImpState +' E) unit)\n        ((denote_list (compile_assign x e)) : itree (Reg +' Memory +' E) unit).\n  Proof.\n    red; intros.\n    unfold compile_assign.\n    (* We push interpreters inside of the denotations *)\n    rewrite denote_list_app.\n    rewrite interp_asm_bind.\n    rewrite interp_imp_bind.\n\n    (* By correctness of the compilation of expressions,\n       we can match the head trees.\n     *)\n    eapply eutt_clo_bind.\n    { eapply compile_expr_correct; eauto. }\n\n    (* Once again, we get related environments *)\n    intros [g_imp' v]  [g_asm' [l' y]] HSIM.\n    simpl in HSIM.\n\n    (* We can now reduce to Ret constructs *)\n    tau_steps.\n    red. rewrite <- eqit_Ret.\n\n    (* And remains to relate the results *)\n    unfold state_invariant.\n    unfold lookup_default, lookup, Map_alist.\n    rewrite sim_rel_find_tmp_n; eauto; simpl.\n    apply sim_rel_Renv in HSIM.\n    split; auto.\n    eapply Renv_write_local; eauto.\n    eauto.\n  Qed.\n\n  (* The first parameter of [bisimilar] is unnecessary for this development.\n     The return type is heterogeneous, the singleton type [F 1] on one side\n     and [unit] on the other, hence we instantiate the parameter with the trivial\n     relation.\n   *)\n  Definition TT {A B}: A -> B -> Prop  := fun _ _ => True.\n  Hint Unfold TT: core.\n\n  Definition equivalent {E} `{Exit -< E} (s:stmt) (t:asm 1 1) : Prop :=\n    bisimilar TT (E := E) (denote_imp s) (denote_asm t f0).\n\n  Inductive RI : (unit + unit) -> (unit + unit + unit) -> Prop :=\n  | RI_inl : RI (inl tt) (inl (inl tt))\n  | RI_inr : RI (inr tt) (inr tt).\n\n  (* Utility: slight rephrasing of [while] to facilitate rewriting\n     in the main theorem.*)\n  Lemma while_is_loop {E} (body : itree E (unit+unit)) :\n    while body\n          ≈ iter (C := ktree _) (fun l : unit + unit =>\n                    match l with\n                    | inl _ => x <- body;; match x with inl _ => Ret (inl (inl tt)) | inr _ => Ret (inr tt) end\n                    | inr _ => Ret (inl (inl tt))   (* Enter loop *)\n                    end) (inr tt).\n  Proof.\n    unfold while.\n    rewrite! unfold_iter_ktree.\n    rewrite bind_ret_l, tau_eutt.\n    rewrite unfold_iter_ktree.\n    rewrite !bind_bind.\n    eapply eutt_clo_bind. reflexivity.\n    intros. subst.\n    destruct u2 as [[]|[]].\n    2 : { force_right. reflexivity. }\n    rewrite bind_ret_l, !tau_eutt.\n    unfold iter, Iter_Kleisli.\n    apply eutt_iter' with (RI := fun _ r => inl tt = r).\n    - intros _ _ [].\n      rewrite <- bind_ret_r at 1.\n      eapply eutt_clo_bind; try reflexivity.\n      intros [|[]] _ []; apply eqit_Ret; auto; constructor; auto.\n    - constructor.\n  Qed.\n\n  Definition to_itree' {E A} (f : ktree_fin E 1 A) : itree E (fin A) := f f0.\n  Lemma fold_to_itree' {E} (f : ktree_fin E 1 1) : f f0 = to_itree' f.\n  Proof. reflexivity. Qed.\n\n  Global Instance Proper_to_itree' {E A} :\n    Proper (eq2 ==> eutt eq) (@to_itree' E A).\n  Proof.\n    repeat intro.\n    apply H.\n  Qed.\n\n  Notation Inr_Kleisli := Inr_Kleisli.\n\n  (** Correctness of the compiler.\n      After interpretation of the [Locals], the source _Imp_ statement\n      denoted as an [itree] and the compiled _Asm_ program denoted\n      as an [itree] are equivalent up-to-taus.\n      The correctness is termination sensitive, but nonetheless a simple\n      induction on statements.\n      We are only left with reasoning about the functional correctness of\n      the compiler, all control-flow related reasoning having been handled\n      in isolation.\n   *)\n  Theorem compile_correct {E} {HasExit : Exit -< E} (s : stmt) :\n    equivalent (E := E) s (compile s).\n  Proof.\n    unfold equivalent.\n    induction s.\n\n    - (* Assign *)\n      simpl.\n      (* We push [denote_asm] inside of the combinators *)\n      rewrite raw_asm_block_correct.\n      rewrite denote_after.\n\n      (* The head trees match by correctness of assign *)\n      rewrite <- (bind_ret_r (ITree.bind (denote_expr e) _)).\n      eapply bisimilar_bind'.\n      { eapply compile_assign_correct; auto. }\n\n      (* And remains to trivially relate the results *)\n\n      intros []; simpl.\n      repeat intro.\n      force_left; force_right.\n      Transparent eutt. red.\n      rewrite <- eqit_Ret; auto.\n      unfold state_invariant; auto.\n\n    - (* Seq *)\n      (* We commute [denote_asm] with [seq_asm] *)\n      rewrite fold_to_itree'; simpl.\n      rewrite seq_asm_correct. unfold to_itree'.\n\n      (* And the result is immediate by indcution hypothesis *)\n      eapply bisimilar_bind'.\n      { eassumption. }\n      intros [] ? _. rewrite (unique_f0 a').\n      eassumption.\n\n    - (* If *)\n      (* We commute [denote_asm] with [if_asm] *)\n      rewrite fold_to_itree'. simpl.\n      rewrite if_asm_correct.\n      unfold to_itree'.\n\n      (* We now need to line up the evaluation of the test,\n         and eliminate them by correctness of [compile_expr] *)\n      repeat intro.\n      rewrite interp_asm_bind.\n      rewrite interp_imp_bind.\n      eapply eutt_clo_bind.\n      { apply compile_expr_correct; auto. }\n\n      (* We get in return [sim_rel] related environments *)\n      intros [g_imp' v] [g_asm' [l' x]] HSIM.\n\n      (* We know that interpreting [GetVar tmp_if] is eutt to [Ret (g_asm,v)] *)\n      generalize HSIM; intros EQ.  eapply sim_rel_get_tmp0 in EQ.\n      unfold tmp_if.\n      rewrite interp_asm_bind.\n      rewrite EQ; clear EQ.\n      rewrite bind_ret_; simpl.\n\n      (* We can weaken [sim_rel] down to [Renv] *)\n      apply sim_rel_Renv in HSIM.\n      (* And finally conclude in both cases *)\n      destruct v; simpl; auto.\n\n    - (* While *)\n      (* We commute [denote_asm] with [while_asm], and restructure the\n         _Imp_ [loop] with [while_is_loop] *)\n      simpl; rewrite fold_to_itree'.\n      rewrite while_is_loop.\n      rewrite while_asm_correct.\n      Local Opaque denote_asm.\n\n      unfold to_itree'.\n      unfold loop. unfold iter at 2.\n      unfold Iter_sub, Inr_sub, Inr_Kleisli, inr_, lift_ktree, cat, Cat_sub, cat, Cat_Kleisli.\n      unfold from_bif, FromBifunctor_ktree_fin.\n      cbn. rewrite 2 bind_ret_l. cbn.\n      eapply (bisimilar_iter (fun x x' => (x = inl tt /\\ x' = f0) \\/ (x = inr tt /\\ x' = fS f0))).\n      2: {\n        right. split. auto. apply unique_fin; reflexivity.\n        }\n      (* The two cases correspond to entering the loop, or exiting it*)\n      intros ? ? [[] | []]; subst; cbn.\n\n      (* The exiting case is trivial *)\n      2:{ repeat intro.\n          unfold to_bif, ToBifunctor_ktree_fin. rewrite !bind_ret_l. cbn.\n          force_left. force_right.\n          red; rewrite <- eqit_Ret; auto.\n          unfold state_invariant. simpl.\n          split; auto.\n          setoid_rewrite split_fin_sum_L_L_f1.\n          constructor. left. auto.\n      }\n\n      (* We now need to line up the evaluation of the test,\n         and eliminate them by correctness of [compile_expr] *)\n      repeat intro.\n      rewrite !interp_imp_bind.\n      rewrite !interp_asm_bind.\n      rewrite !bind_bind.\n\n      eapply eutt_clo_bind.\n      { apply compile_expr_correct; auto. }\n\n      intros [g_imp' v] [g_asm' [l' x]] HSIM.\n      rewrite !interp_asm_bind.\n      rewrite !bind_bind.\n\n      (* We know that interpreting [GetVar tmp_if] is eutt to [Ret (g_asm,v)] *)\n      generalize HSIM; intros EQ. eapply sim_rel_get_tmp0 in EQ.\n      unfold tmp_if.\n\n      rewrite EQ; clear EQ.\n      rewrite bind_ret_; simpl.\n\n      (* We can weaken [sim_rel] down to [Renv] *)\n      apply sim_rel_Renv in HSIM.\n      (* And now consider both cases *)\n      destruct v; simpl; auto.\n      + (* The false case is trivial *)\n        force_left; force_right.\n        red.\n        rewrite <- eqit_Ret.\n        unfold state_invariant. simpl.\n        split; auto; constructor; auto.\n\n      + (* In the true case, we line up the body of the loop to use the induction hypothesis *)\n        rewrite !interp_asm_bind.\n        rewrite !interp_imp_bind.\n        rewrite !bind_bind.\n        eapply eutt_clo_bind.\n        { eapply IHs; auto. }\n        intros [g_imp'' v''] [g_asm'' [l'' x']] [HSIM' ?].\n        force_right; force_left.\n        apply eqit_Ret.\n        setoid_rewrite split_fin_sum_L_L_f1.\n        constructor; auto.\n        simpl. constructor; left; auto.\n\n    - (* Skip *)\n\n      simpl.\n      unfold id_asm.\n      pose proof (@pure_asm_correct).\n      do 5 red in H. rewrite H.\n      red. intros.\n      setoid_rewrite interp_asm_ret.\n      unfold interp_imp.\n      rewrite interp_ret. unfold interp_map. rewrite interp_state_ret.\n      apply eqit_Ret.\n      unfold state_invariant. auto.\nQed.\n\nEnd Correctness.\n\n(* ================================================================= *)\n(** ** Closing word. *)\n\n(** Through this medium-sized example, we have seen how to use [itree]s to\n    denote two languages, how to run them and how to prove correct a compiler\n    between them.\n    We have emphasized that the theory of [ktree]s allowed us to decouple\n    all reasoning about the control-flow from the proof of the compiler itself.\n    The resulting proof is entirely structurally inductive and equational. In\n    particular, we obtain a final theorem relating potentially infinite\n    computations without having to write any cofixed-point.\n\n    If this result is encouraging, one might always wonder how things scale.\n\n    A first good sanity check is to extend the languages with a _Print_\n    instruction.\n    It requires to add a new event to the language and therefore makes the\n    correctness theorem relate trees actually still containing events.\n    This change, which a good exercise to try, turns out to be as\n    straightforward as one would hope. The only new lemma needed is to show\n    that [interp_locals] leaves the new [Print] event untouched.\n    This extension can be found in the _tutorial-print_ branch.\n\n    More importantly, our compiler is fairly stupid and inefficient: it creates\n    blocks for each compiled statement! One would hope to easily write and\n    prove an optimization coalescing elementary blocks together.\n\n    A first example of optimization at the [asm] level proved correct is\n    demonstrated in the _AsmOptimization.v_ file.\n *)\n", "meta": {"author": "DeepSpec", "repo": "InteractionTrees", "sha": "8e28e2ee08496c696e03916a22d93c39559a9715", "save_path": "github-repos/coq/DeepSpec-InteractionTrees", "path": "github-repos/coq/DeepSpec-InteractionTrees/InteractionTrees-8e28e2ee08496c696e03916a22d93c39559a9715/tutorial/Imp2AsmCorrectness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.22684102821147462}}
{"text": "Require Import Program.\nRequire Import syntax.\nRequire Import infrastructure.\nRequire Import List.\nRequire Import Arith.\nRequire Import tactics.\nRequire Import monad.\nRequire Import Metatheory.\nRequire Import genericvalues.\nRequire Import alist.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Integers.\nRequire Import Coqlib.\nRequire Import targetdata.\nRequire Import targetdata_props.\nRequire Import Maps.\nRequire Import Lattice.\nRequire Import Iteration.\nRequire Import Kildall.\nRequire Import typings.\nRequire Import infrastructure_props.\nRequire Import analysis.\nRequire Import typings_props.\n\nImport LLVMinfra.\nImport LLVMtd.\nImport LLVMtypings.\nImport LLVMgv.\nImport AtomSet.\n\nRequire Import sflib.\n(********************************************)\n(** * total *)\n\nDefinition flatten_typ_aux_total_prop S TD t :=\n  wf_styp S TD t ->\n  forall los nts nts' acc\n  (Hsize: exists sz, exists al, \n     getTypeSizeInBits_and_Alignment (los, nts') true t = Some (sz,al))\n  (Hnc: forall id5,\n          lookupAL _ nts id5 <> None ->\n          exists gv5, lookupAL _ acc id5 = Some (Some gv5)),\n  TD = (los, nts) ->\n  exists gv, flatten_typ_aux (los, nts') acc t = Some gv.\n\nDefinition flatten_typs_aux_total_prop sdt :=\n  wf_styp_list sdt ->\n  let 'lsdt := sdt in\n  let '(lsd, lt) := split lsdt in\n  forall S TD los nts nts' acc\n  (Hsize: exists sz, exists al, \n     getListTypeSizeInBits_and_Alignment (los, nts') true lt = \n       Some (sz, al))\n  (Hnc: forall id5,\n          lookupAL _ nts id5 <> None ->\n          exists gv5, lookupAL _ acc id5 = Some (Some gv5)),\n  TD = (los, nts) ->\n  eq_system_targetdata S TD lsd ->\n  exists gvs, flatten_typs_aux (los, nts') acc lt = Some gvs.\n\n\nLemma flatten_typ_aux_total_mutrec :\n  (forall S TD t, flatten_typ_aux_total_prop S TD t) /\\\n  (forall sdt, flatten_typs_aux_total_prop sdt).\nProof.\n  (wfstyp_cases (apply wf_styp_mutind; \n                 unfold flatten_typ_aux_total_prop, \n                        flatten_typs_aux_total_prop) Case);\n    intros; subst; simpl in *; uniq_result; eauto.\nCase \"wf_styp_structure\".\n  simpl_split lsd lt.\n  assert (lt = typ_list) as EQ1. \n    eapply make_list_typ_spec2; eauto.\n  subst.\n  assert (eq_system_targetdata system5 (los, nts) lsd) as EQ2.\n    eapply wf_styp__feasible_typ_aux_mutrec_struct; eauto.\n  subst.\n  destruct Hsize as [sz [al Hsize]].\n  inv_mbind. \n  eapply H1 with (nts':=nts') in Hnc; eauto.\n  fold flatten_typs_aux.\n  fill_ctxhole. destruct x; eauto 2.\nCase \"wf_styp_array\".\n  destruct sz5; eauto.\n  destruct Hsize as [sz [al Hsize]].\n  inv_mbind.\n  unfold getTypeAllocSize, getTypeStoreSize, getABITypeAlignment,\n         getTypeSizeInBits, getAlignment, getTypeSizeInBits_and_Alignment,\n         getTypeSizeInBits_and_Alignment_for_namedts.\n  eapply H0 with (nts':=nts')(acc:=acc) in Hnc; eauto.\n    repeat fill_ctxhole. eauto.\nCase \"wf_styp_namedt\".\n  destruct (@Hnc id5) as [gv5 J]; try congruence.\n    fill_ctxhole. eauto.  \nCase \"wf_styp_cons\".\n  remember (split l') as R.\n  destruct R as [lsd lt]. simpl.\n  intros. subst.\n  apply eq_system_targetdata_cons_inv in H4. \n  destruct H4 as [H4 [EQ1 EQ2]]; subst.\n  destruct Hsize as [sz [al Hsize]].\n  inv_mbind.\n  assert (J:=Hnc).\n  eapply H0 with (nts':=nts') in J; eauto. clear H0.\n  eapply H2 with (nts':=nts') in Hnc; eauto. clear H2.\n  unfold getTypeAllocSize, getTypeStoreSize, getABITypeAlignment,\n         getTypeSizeInBits, getAlignment, getTypeSizeInBits_and_Alignment,\n         getTypeSizeInBits_and_Alignment_for_namedts.\n  repeat fill_ctxhole. eauto.\nQed.\n\nLemma flatten_typ_for_namedts_spec2: forall TD los i0 r nts2\n  lt2 nts1 nts (Huniq: uniq nts),\n  flatten_typ_aux TD (flatten_typ_for_namedts TD los nts2) \n    (typ_struct lt2) = r ->\n  nts = nts1 ++ (i0,lt2) :: nts2 ->  \n  lookupAL _ (flatten_typ_for_namedts TD los nts) i0 = Some r.\nProof.\n  induction nts1 as [|[]]; intros; subst; simpl in *.\n    destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i0 i0); \n      try congruence; auto.\n     \n    inv Huniq.\n    simpl_env in H3.\n    destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i0 i1); subst.\n      contradict H3; fsetdec.\n      eapply IHnts1 in H1; eauto.\nQed.\n\nLemma flatten_typ_for_namedts_total: forall S los nts \n  (H: noncycled S los nts) (Huniq: uniq nts), \n  forall id5 lt nts2 nts1 nts'\n  (EQ: nts = nts1 ++ (id5,lt) :: nts2)\n  (Hsize: forall id5 lt5, \n     lookupAL _ nts id5 = Some lt5 ->\n     exists sz0 : nat, exists al : nat,\n       getTypeSizeInBits_and_Alignment (los, nts') true (typ_struct lt5) =\n         Some (sz0, al)),\n  exists gvs, \n    flatten_typ_aux (los, nts')\n      (flatten_typ_for_namedts (los,nts') los nts2) (typ_struct lt) = Some gvs.\nProof.\nLocal Opaque getListTypeSizeInBits_and_Alignment getTypeSizeInBits_and_Alignment.\n  induction 1; simpl; intros; subst.\n    symmetry in EQ.    \n    apply app_eq_nil in EQ.\n    destruct EQ as [_ EQ].\n    congruence.\n\n    inv Huniq.\n    destruct nts1 as [|[]]; inv EQ.\n      destruct flatten_typ_aux_total_mutrec as [J _].\n      eapply J in H0; eauto.\n      assert (exists sz0 : nat, exists al : nat,\n               getTypeSizeInBits_and_Alignment (layouts5, nts') true \n                 (typ_struct lt) = ret (sz0, al)) as Hty.\n        apply Hsize with (id5:=id0).\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id0 id0); \n          try congruence.\n      eapply H0 in Hty; eauto.  \n      intros id5 H1.\n      apply lookupAL_middle_inv' in H1.\n      destruct H1 as [l0 [l1 [l2 HeqR]]].\n      assert (J':=HeqR). subst.\n      eapply IHnoncycled with (nts':=nts') in J'; eauto.\n        destruct J' as [gv J'].\n        exists gv. \n        eapply flatten_typ_for_namedts_spec2; eauto.\n  \n        intros.\n        apply Hsize with (id6:=id1).\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id1 id0); \n          subst; auto.\n          apply notin_lookupAL_None in H5. congruence.\n    \n      assert (nts1 ++ (id0, lt) :: nts2 = nts1 ++ (id0, lt) :: nts2) as EQ. auto.\n      eapply IHnoncycled in EQ; eauto.\n        intros.\n        apply Hsize with (id5:=id5).\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id5 i0); \n          subst; auto.\n          apply notin_lookupAL_None in H5. congruence.\nTransparent getListTypeSizeInBits_and_Alignment getTypeSizeInBits_and_Alignment.\nQed.\n\nLemma flatten_typ_total : forall S td t\n  (Hty: wf_typ S td t),\n  exists gv, flatten_typ td t = Some gv.\nProof.\n  intros.\n  assert (G:=Hty).\n  apply wf_typ__getTypeSizeInBits_and_Alignment in G; auto.\n  destruct G as [sz [al [G1 [G2 G3]]]].\n  unfold flatten_typ.\n  inv Hty.\n  destruct flatten_typ_aux_total_mutrec as [J' _].\n  eapply J'; eauto.\n  intros id5 J.\n  apply lookupAL_middle_inv' in J.\n  destruct J as [l0 [l1 [l2 HeqR]]]. subst.\n  eapply flatten_typ_for_namedts_total\n    with (nts':=l1 ++ (id5, l0) :: l2) in H; eauto.\n    destruct H as [gv H].\n    exists gv.\n    eapply flatten_typ_for_namedts_spec2; eauto.\n\n    intros id0 lt5 J.\n    apply lookupAL_middle_inv in J.\n    destruct J as [l3 [l4 J]].\n    rewrite J in *. \n    symmetry in J.\n    rewrite_env ((l3 ++ [(id0, lt5)]) ++ l4).\n    eapply noncycled__getTypeSizeInBits_and_Alignment_for_namedts \n      with (nts1:=l3)(nts2:=l4) in H; eauto.\n    unfold getTypeSizeInBits_and_Alignment.\n    destruct H as [sz0 [al0 [W1 ?]]].\n    exists sz0. exists al0.\n    eapply getTypeSizeInBits_and_Alignment_aux_weakening; eauto.\n      simpl_env. simpl. auto.\nQed.\n\nLemma gundef__total : forall S TD t (H0 : wf_typ S TD t),\n  exists gv, gundef TD t = Some gv.\nProof.\n  intros.\n  unfold gundef.\n  eapply flatten_typ_total in H0; eauto.\n  destruct H0 as [? H0].\n  fill_ctxhole. eauto.\nQed.\n\n(*\nLemma make_list_const_spec1' : forall\n  (const_list : list_const)\n  (system5 : system)\n  (td5 : targetdata)\n  (typ5 : typ)\n  (sz5 : sz)\n  (lsdc : list (system * targetdata * const))\n  (lt : list typ)\n  (HeqR : (lsdc, lt) =\n         split\n           (unmake_list_system_targetdata_const_typ\n              (make_list_system_targetdata_const_typ\n                 (map_list_const\n                    (fun const_ : const => (system5, td5, const_, typ5))\n                    const_list))))\n  (TD : TargetData)\n  (H0 : wf_typ system5 td5 (typ_array sz5 typ5)),\n  wf_typ system5 td5 (typ_struct (make_list_typ lt)).\nProof.\n  intros.\n  generalize dependent lsdc.\n  generalize dependent lt.\n  induction const_list; intros; simpl in *.\n     inv HeqR. simpl. auto.\n  \n     remember (split\n              (unmake_list_system_targetdata_const_typ\n                 (make_list_system_targetdata_const_typ\n                    (map_list_const\n                       (fun const_ : const => (system5, td5, const_, typ5))\n                       const_list)))) as R2.\n     destruct R2. inv HeqR. simpl.\n     split; eauto.\nQed.\n\nLemma typ_eq_list_typ_spec1': forall (nts:namedts) t1 lt2 (Huniq: uniq nts)\n  (H: typ_eq_list_typ nts t1 lt2 = true),\n  Constant.wf_zeroconst_typ t1 ->\n  Constant.wf_zeroconsts_typ lt2.\nProof.\n  intros.\n  unfold typ_eq_list_typ in H.\n  destruct t1; tinv H.\n    destruct (list_typ_dec l0 lt2); inv H. auto.\n\n    remember (lookupAL list_typ (rev nts) i0) as R.\n    destruct R; tinv H.\n    destruct (list_typ_dec l0 lt2); inv H.\n    simpl in *. uniq_result.\nQed.\n*)\n\n\nLtac elim_wrong_wf_typ:=\nrepeat match goal with\n| H: wf_typ _ _ (typ_floatpoint fp_fp128) |- _ => inv H\n| H: wf_styp _ _ (typ_floatpoint fp_fp128) |- _ => inv H\n| H: wf_typ _ _ (typ_floatpoint fp_x86_fp80) |- _ => inv H\n| H: wf_styp _ _ (typ_floatpoint fp_x86_fp80) |- _ => inv H\n| H: wf_typ _ _ (typ_floatpoint fp_ppc_fp128) |- _ => inv H\n| H: wf_styp _ _ (typ_floatpoint fp_ppc_fp128) |- _ => inv H\n| e: floating_point_order ?floating_point2 fp_float = true |- _ =>\n     destruct floating_point2; inv e\nend.\n\nLemma wf_const__wf_typ: forall S TD c ty,\n  wf_const S TD c ty -> wf_typ S TD ty.\nProof. intros. inv H; auto. Qed.\n\nDefinition const2GV_isnt_stuck_Prop S TD c t :=\n  wf_const S TD c t ->\n  forall gl (Hty: uniq (snd TD)),\n  wf_global TD S gl ->\n  exists gv, _const2GV TD gl c = Some (gv, t).\n\nDefinition consts2GV_isnt_stuck_Prop sdct :=\n  wf_const_list sdct ->\n  let 'lsdct := sdct in\n  let '(lsdc, lt) := split lsdct in\n  let '(lsd, lc) := split lsdc in\n  let '(ls, ld) := split lsd in\n  forall S TD gl (Hty: uniq (snd TD)), \n  wf_list_targetdata_typ S TD gl lsd ->\n  (forall t, (forall t0, In t0 lt -> t0 = t) ->\n    exists gv, _list_const_arr2GV TD gl t lc = Some gv) /\\\n  (exists gv, _list_const_struct2GV TD gl lc = \n    Some (gv, lt)).\n\nLemma const2GV_isnt_stuck_mutind : \n  (forall S td c t, @const2GV_isnt_stuck_Prop S td c t) /\\\n  (forall sdct, @consts2GV_isnt_stuck_Prop sdct).\nProof.\n  (wfconst_cases (apply wf_const_mutind (*with\n    (P  := const2GV_isnt_stuck_Prop)\n    (P0 := consts2GV_isnt_stuck_Prop)*)) Case);\n    unfold const2GV_isnt_stuck_Prop, consts2GV_isnt_stuck_Prop;\n    intros; subst; simpl; eauto.\nCase \"wfconst_zero\".\n  destruct (@wf_zeroconst2GV_total system5 targetdata5 typ5) as [gv J]; auto.\n  fill_ctxhole. eauto.\nCase \"wfconst_floatingpoint\". \n  inv H. inv H2; eauto.\nCase \"wfconst_undef\".\n  match goal with\n  | H: wf_typ _ _ _ |- _ =>\n    eapply gundef__total in H; eauto;\n    destruct H as [gv H];\n    rewrite H; eauto\n  end.\nCase \"wfconst_array\".\n  simpl_split lsdc lt.\n  simpl_split lsd lc.\n  simpl_split ls ld.\n  destruct (@H0 system5 targetdata5 gl) as [J1 [gv2 J2]]; \n    try solve [destruct targetdata5; eauto using const2GV_typsize_mutind_array].\n    assert (lc = const_list) as EQ.\n      eapply make_list_const_spec2; eauto.\n    rewrite H1. rewrite <- EQ. unfold Size.to_nat in *. \n    destruct (@J1 typ5) as [gv1 J3]; eauto using make_list_const_spec4.\n    fold _list_const_arr2GV. rewrite J3.\n    destruct sz5; eauto.\n\nCase \"wfconst_struct\".\n  simpl_split lsdc lt.\n  simpl_split lsd lc.\n  simpl_split ls ld.\n  erewrite <- map_list_const_typ_spec1 in H2; eauto.\n  destruct (@H0 system5 (layouts5, namedts5) gl) as [_ [gv2 J2]]; \n    try solve [eauto using const2GV_typsize_mutind_struct |\n               eapply typ_eq_list_typ_spec1; eauto |\n               eapply typ_eq_list_typ_spec1'; eauto].\n    erewrite <- map_list_const_typ_spec2; eauto.\n    fold _list_const_struct2GV. repeat fill_ctxhole.\n    destruct gv2; eauto.\n\nCase \"wfconst_gid\".\n  match goal with\n  | H: wf_global _ _ _ , e: lookupTypViaGIDFromSystem _ _ = _ |- _ =>\n    apply H in e;  \n    destruct e as [gv [sz [e [J1 J2]]]];\n    rewrite e; eauto\n  end.\nCase \"wfconst_trunc_int\".\n  match goal with\n  | H4: wf_global _ _ _ |- _ => \n    eapply H0 in H4; eauto; destruct H4 as [gv H4]; fill_ctxhole\n  end.\n  unfold mtrunc.\n  assert (exists gv, gundef targetdata5 (typ_int sz2) = Some gv) as J.\n    eapply gundef__total; eauto.\n  fill_ctxhole.\n  destruct (GV2val targetdata5 gv) as [[]|]; eauto.\nCase \"wfconst_trunc_fp\".\n  match goal with\n  | H4: wf_global _ _ _ |- _ =>\n    eapply H0 in H4; eauto; destruct H4 as [gv H4]; fill_ctxhole\n  end.\n  unfold mtrunc. rewrite H1.\n  assert (exists gv, gundef targetdata5 (typ_floatpoint floating_point2) = \n           Some gv) as J.\n    eapply gundef__total; eauto.\n  fill_ctxhole.\n  destruct (GV2val targetdata5 gv) as [[]|] eqn:GVeqn; eauto.\n  destruct floating_point1; try solve [eauto | elim_wrong_wf_typ].\nCase \"wfconst_zext\".\n  match goal with\n  | H4: wf_global _ _ _ |- _ => \n    eapply H0 in H4; eauto; destruct H4 as [gv H4]; fill_ctxhole\n  end.\n  unfold mext.\n  assert (exists gv, gundef targetdata5 (typ_int sz2) = Some gv) as J.\n    eapply gundef__total; eauto.\n  fill_ctxhole.\n  destruct (GV2val targetdata5 gv) as [[]|]; eauto.\nCase \"wfconst_sext\".\n  match goal with\n  | H4: wf_global _ _ _ |- _ => \n    eapply H0 in H4; eauto; destruct H4 as [gv H4]; fill_ctxhole\n  end.\n  unfold mext.\n  assert (exists gv, gundef targetdata5 (typ_int sz2) = Some gv) as J.\n    eapply gundef__total; eauto.\n  fill_ctxhole.\n  destruct (GV2val targetdata5 gv) as [[]|]; eauto.\nCase \"wfconst_fpext\".\n  match goal with\n  | H4: wf_global _ _ _ |- _ => \n    eapply H0 in H4; eauto; destruct H4 as [gv H4]; fill_ctxhole\n  end.\n  unfold mext.\n  assert (exists gv, gundef targetdata5 (typ_floatpoint floating_point2) = \n    Some gv) as J.\n    eapply gundef__total; eauto.\n  fill_ctxhole.\n  destruct (GV2val targetdata5 gv) as [[]|]; try fill_ctxhole; eauto.\n  destruct floating_point2; try solve [eauto | elim_wrong_wf_typ].\nCase \"wfconst_ptrtoint\".\n  match goal with\n  | H4: wf_global _ _ _ |- _ => \n    eapply H0 in H4; eauto; destruct H4 as [gv H4]; fill_ctxhole\n  end.\n  assert (exists gv, gundef targetdata5 (typ_int sz5) = Some gv) as J.\n    eapply gundef__total; eauto.\n  fill_ctxhole. eauto.\nCase \"wfconst_inttoptr\".\n  match goal with\n  | H4: wf_global _ _ _ |- _ => \n    eapply H0 in H4; eauto; destruct H4 as [gv H4]; fill_ctxhole\n  end.\n  assert (exists gv, gundef targetdata5 (typ_pointer typ5) = Some gv) as J.\n    eapply gundef__total; eauto.\n  fill_ctxhole. eauto.\nCase \"wfconst_bitcast\".\n  unfold mbitcast.\n  match goal with\n  | H4: wf_global _ _ _ |- _ => \n    eapply H0 in H4; eauto; destruct H4 as [gv H4]; fill_ctxhole\n  end. eauto.\nCase \"wfconst_gep\".\n  (*clear H0.*)\n  eapply H0 in H7; eauto; simpl; auto.\n  destruct H7 as [gv H7]. repeat fill_ctxhole.\n  assert (exists gv, gundef targetdata5 typ' = Some gv) as J.\n    eapply gundef__total; eauto.\n  fill_ctxhole. \n  destruct (GV2ptr targetdata5 (getPointerSize targetdata5) gv); eauto.\n  destruct (intConsts2Nats targetdata5 const_list); eauto.\n  destruct (mgep targetdata5 typ5 v l0); eauto.\n\nCase \"wfconst_select\".\n  assert (J:=H8).\n  eapply H0 in J; eauto; simpl; auto.\n  destruct J as [gv J].\n  assert (J':=H8).\n  eapply H5 in J'; eauto; simpl; auto.\n  destruct J' as [gv' J'].\n  eapply H3 in H8; eauto; simpl; auto.\n  destruct H8 as [gv'' H8].\n  rewrite J. rewrite J'. rewrite H8.\n  destruct (isGVZero targetdata5 gv); eauto.\nCase \"wfconst_icmp\".\n  assert (J:=H7).\n  eapply H0 in H7; eauto.\n  destruct H7 as [gv H7].\n  rewrite H7. \n  eapply H2 in J; eauto.\n  destruct J as [gv' J].\n  rewrite J. \n  unfold micmp.\n  unfold isPointerTyp in H4. unfold is_true in H4.\n  unfold micmp_int.\n  assert (exists gv, gundef targetdata5 (typ_int 1%nat) = \n           Some gv) as JJ.\n    eapply gundef__total; eauto.\n  destruct JJ as [gv0 JJ].\n  rewrite JJ.\n  destruct H4 as [o | o].\n    destruct typ5; try solve [simpl in o; contradict o; auto].\n    destruct (GV2val targetdata5 gv); eauto.\n    destruct v; eauto.\n    destruct (GV2val targetdata5 gv'); eauto.\n    destruct v; eauto.\n    destruct cond5; eauto.\n\n    destruct typ5; try solve [eauto | simpl in o; contradict o; auto].\nCase \"wfconst_fcmp\".\n  assert (J:=H7).\n  eapply H1 in H7; eauto.\n  destruct H7 as [gv H7].\n  rewrite H7. \n  eapply H3 in J; eauto.\n  destruct J as [gv' J].\n  rewrite J. \n  unfold mfcmp.\n  assert (exists gv, gundef targetdata5 (typ_int 1%nat) = \n           Some gv) as JJ.\n    eapply gundef__total; eauto.\n  destruct JJ as [gv0 JJ].\n  rewrite JJ.\n  destruct (GV2val targetdata5 gv); eauto.\n  destruct v; eauto.\n  destruct (GV2val targetdata5 gv'); eauto.\n  destruct v; eauto.\n  destruct floating_point5; try solve [eauto | elim_wrong_wf_typ].\n    destruct fcond5; try solve [eauto | inversion H].\n    destruct fcond5; try solve [eauto | inversion H].\nCase \"wfconst_extractvalue\".\n  eapply H0 in H8; eauto.\n  destruct H8 as [gv H8].\n  rewrite H8.\n  destruct H6 as [idxs [o [J1 J2]]].\n  erewrite mgetoffset__getSubTypFromConstIdxs; eauto.\n  unfold LLVMgv.extractGenericValue.\n  rewrite J1. rewrite J2.\n  destruct (mget targetdata5 gv o typ'); eauto.\n    eapply gundef__total in H7; eauto.\n  fill_ctxhole. eauto.\nCase \"wfconst_insertvalue\".\n  assert (J:=H10).\n  eapply H0 in H10; eauto.\n  destruct H10 as [gv H10].\n  rewrite H10.\n  eapply H2 in J; eauto.\n  destruct J as [gv' J].\n  rewrite J.\n  unfold LLVMgv.insertGenericValue.\n  destruct H8 as [idxs [o [J1 J2]]].\n  rewrite J1. rewrite J2.\n  destruct (mset targetdata5 gv o typ' gv'); eauto.\n    eapply gundef__total in H9; eauto.\n    destruct H9 as [gv0 JJ]. rewrite JJ. eauto.\nCase \"wfconst_bop\".\n  assert (exists gv, gundef targetdata5 (typ_int sz5) = Some gv) as JJ.\n    eapply gundef__total; eauto.\n  destruct JJ as [gv0 JJ].\n  assert (J:=H4).\n  eapply H0 in H4; eauto.\n  destruct H4 as [gv H4].\n  rewrite H4.\n  eapply H2 in J; eauto.\n  destruct J as [gv' J].\n  rewrite J.\n  unfold mbop, Size.to_nat. \n  rewrite JJ.\n  destruct (GV2val targetdata5 gv); eauto.\n  destruct (GV2val targetdata5 gv'); eauto.\n  destruct v; eauto.\n  destruct v0; eauto.\n  destruct (eq_nat_dec (wz + 1) sz5); eauto.\n  destruct bop5; destruct (_ (Vint _ _) (Vint _ _)); eauto.\n  destruct v; eauto.\nCase \"wfconst_fbop\".\n  assert (exists gv, gundef targetdata5 (typ_floatpoint floating_point5) \n    = Some gv) as JJ.\n    eapply gundef__total; eauto.\n  destruct JJ as [gv0 JJ].\n  assert (J:=H4).\n  eapply H0 in H4; eauto.\n  destruct H4 as [gv H4].\n  rewrite H4.\n  eapply H2 in J; eauto.\n  destruct J as [gv' J].\n  rewrite J.\n  unfold mfbop. rewrite JJ.\n  destruct (GV2val targetdata5 gv) eqn:GV1; eauto.\n  destruct (GV2val targetdata5 gv') eqn:GV2; eauto.\n  destruct v; eauto.\n  destruct v0; eauto.\n  destruct floating_point5; try solve [eauto | elim_wrong_wf_typ].\n  destruct v0; eauto.\n  destruct floating_point5; try solve [eauto | elim_wrong_wf_typ].\n  destruct v; eauto.\nCase \"wfconst_cons\".\n  simpl_split lsdc lt. simpl.\n  simpl_split lsd lc. simpl.\n  simpl_split ls ld. simpl.\n  intros S TD gl Huniq Hwfl.\n  assert (wf_list_targetdata_typ S TD gl lsd /\\ system5 = S /\\ targetdata5 = TD\n            /\\ wf_global TD S gl) \n    as Hwfl'.\n    clear - Hwfl.\n    unfold wf_list_targetdata_typ in *.\n    assert (In (system5, targetdata5) ((system5, targetdata5) :: lsd)) as J.\n      simpl. auto.\n    apply Hwfl in J. \n    destruct J as [J1 [J2 J3]]; subst.\n    split.\n      intros S1 TD1 Hin.    \n      apply Hwfl. simpl. auto.\n    split; auto.\n  destruct Hwfl' as [Hwfl' [Heq1 [Heq2 Hwfg]]]; subst.  \n  assert (J2':=Hwfg).\n  eapply H0 in J2'; eauto.\n  destruct J2' as [gv J2'].\n  rewrite J2'.\n  assert (J1':=Hwfl').\n  eapply H2 in J1'; eauto.\n  destruct J1' as [J1' [g2 J12]].\n  rewrite J12.\n  apply wf_const__wf_typ in H.\n  apply wf_typ__feasible_typ in H.\n  apply feasible_typ_inv'' in H.  \n  destruct H as [ssz [asz [J21 J22]]].\n  rewrite J22.\n  split; eauto.  \n    intros.\n    destruct (@J1' t) as [gv0 H4]; eauto.\n    rewrite H4.\n    assert (typ5 = t) as EQ. apply H; auto.\n    subst.\n    destruct (typ_dec t t); eauto.\n      contradict n; auto.\nQed.\n\nLemma mbop_is_total : forall S TD bop0 sz0, \n  wf_typ S TD (typ_int sz0) ->\n  forall x y, exists z, mbop TD bop0 sz0 x y = Some z.\nProof.\n  intros S TD bop0 sz0 Hwft x y.\n  unfold mbop.\n  destruct (GV2val TD x); eauto using gundef__total.\n  destruct v; eauto using gundef__total.\n  destruct (GV2val TD y); eauto using gundef__total.\n  destruct v; eauto using gundef__total.\n  destruct (eq_nat_dec (wz + 1) (Size.to_nat sz0)); \n    eauto using gundef__total.\n  destruct bop0; destruct (_ (Vint _ _) (Vint _ _)); eauto using gundef__total.\nQed.\n\nLemma mfbop_is_total : forall S TD fbop0 fp, \n  wf_typ S TD (typ_floatpoint fp) ->\n  forall x y, exists z, mfbop TD fbop0 fp x y = Some z.\nProof.\n  intros.\n  unfold mfbop.\n  destruct (GV2val TD x); eauto using gundef__total.\n  destruct v; eauto using gundef__total.\n  destruct (GV2val TD y); eauto using gundef__total.\n  destruct v; eauto using gundef__total.\n  destruct fp; try solve [eauto | elim_wrong_wf_typ].\n  destruct (GV2val TD y); eauto using gundef__total.\n  destruct (GV2val TD y); eauto using gundef__total.\n  destruct v; eauto using gundef__total.\n  destruct fp; try solve [eauto | elim_wrong_wf_typ].\n  eauto using gundef__total.\nQed.\n\nLemma micmp_is_total : forall S TD c t\n  (Hztyp: wf_typ S TD t), \n  Typ.isIntOrIntVector t \\/ isPointerTyp t ->\n  forall x y, exists z, micmp TD c t x y = Some z.\nProof.\n  intros S TD c t Hty Hwft x y.\n  unfold micmp, micmp_int.\n  unfold isPointerTyp in Hwft. unfold is_true in Hwft.\n  unfold micmp_int.\n  destruct Hwft as [Hwft | Hwft].\n    destruct t; try solve [simpl in Hwft; contradict Hwft; auto].\n    destruct (GV2val TD x); eauto using gundef_i1__total.\n    destruct v; eauto using gundef_i1__total.\n    destruct (GV2val TD y); eauto using gundef_i1__total.\n    destruct v; eauto using gundef_i1__total.\n    destruct c; eauto using gundef_i1__total.\n  \n    destruct t; try solve [simpl in Hwft; contradict Hwft; auto]. \n      eauto using gundef_i1__total.\nQed.\n\nLemma mfcmp_is_total : forall S TD c fp,\n  wf_fcond c = true  ->\n  wf_typ S TD (typ_floatpoint fp) ->\n  forall x y, exists z, mfcmp TD c fp x y = Some z.\nProof.\n  intros S TD c fp Hc Ht x y.\n  unfold mfcmp.\n  destruct (GV2val TD x); eauto using gundef_i1__total.\n  destruct v; eauto using gundef_i1__total.\n  destruct (GV2val TD y); eauto using gundef_i1__total.\n  destruct v; eauto using gundef_i1__total.\n  destruct fp; try solve [eauto | elim_wrong_wf_typ].\n    destruct c; try solve [eauto | inversion Hc].\n    destruct c; try solve [eauto | inversion Hc].\nQed.\n\nLemma GEP_is_total : forall S TD t mp vidxs inbounds0 t',\n  wf_typ S TD (typ_pointer t') ->\n  exists mp', LLVMgv.GEP TD t mp vidxs inbounds0 t' = ret mp'.\nProof.\n  intros. unfold LLVMgv.GEP.\n  destruct (GV2ptr TD (getPointerSize TD) mp); eauto using gundef__total.\n  destruct (GVs2Nats TD vidxs); eauto using gundef__total.\n  destruct (mgep TD t v l0); eauto using gundef__total.\nQed.\n\nLemma fit_gv__total : forall S TD t gv1 (H0 : wf_typ S TD t),\n  exists gv, fit_gv TD t gv1 = Some gv.\nProof.\n  intros. \n  unfold fit_gv.\n  assert (exists gv, gundef TD t = Some gv) as EQ.\n    eapply gundef__total; eauto.\n  destruct EQ as [gv EQ].\n  rewrite EQ. apply wf_typ__feasible_typ in H0.\n  eapply feasible_typ_inv' in H0; eauto.\n  destruct H0 as [sz [al [J1 J2]]].\n  unfold getTypeSizeInBits.\n  rewrite J1. \n  match goal with\n  | |- exists _:_, (if ?e then _ else _) = _ =>\n       destruct e; eauto\n  end.\nQed.\n\nLemma mcast_is_total : forall s f b los nts ps id5 cop0 t1 t2 v,\n  wf_cast s (module_intro los nts ps) f b \n    (insn_cmd (insn_cast id5 cop0 t1 v t2)) ->\n  forall x, exists z, mcast (los,nts) cop0 t1 t2 x = Some z.\nProof.\n  intros.\n  unfold mcast, mbitcast.\n  inv H; eauto using gundef__total.\nQed.\n\nLemma mtrunc_is_total : forall s f b los nts ps id5 top0 t1 t2 v, \n  wf_trunc s (module_intro los nts ps) f b \n    (insn_cmd (insn_trunc id5 top0 t1 v t2)) ->\n  forall x, exists z, mtrunc (los,nts) top0 t1 t2 x = Some z.\nProof.\n  intros.\n  assert (J:=H).\n  apply wf_trunc__wf_typ in J.\n  destruct J as [J1 J2]. \n  unfold mtrunc.\n  destruct (GV2val (los, nts) x); eauto using gundef__total.\n  inv H; try solve [destruct v0; eauto using gundef__total].\n    match goal with\n    | H15: _ = _ |- _ => rewrite H15\n    end.\n    destruct v0; eauto using gundef__total.\n      destruct floating_point1; try solve [eauto | elim_wrong_wf_typ].\nQed.\n\nLemma mext_is_total : forall s f b los nts ps id5 eop0 t1 t2 v, \n  wf_ext s (module_intro los nts ps) f b \n    (insn_cmd (insn_ext id5 eop0 t1 v t2)) ->\n  forall x,  exists z, mext (los,nts) eop0 t1 t2 x = Some z.\nProof.\n  intros.\n  unfold mext.\n  inv H; try solve \n    [destruct (GV2val (los, nts) x) as [[]|]; eauto using gundef__total].\n    match goal with\n    | H14: _ = _ |- _ => rewrite H14\n    end.\n    destruct (GV2val (los, nts) x) as [[]|]; eauto using gundef__total.\n    destruct floating_point2; try solve [eauto | elim_wrong_wf_typ].\nQed.\n\nLemma mset'_is_total : forall S (TD : TargetData) ofs (t1 t2 : typ) \n  (w1 : wf_typ S TD t1),\n  forall x y, exists z : GenericValue, mset' TD ofs t1 t2 x y = ret z.\nProof.\n  intros.\n  unfold mset'. unfold mset.\n  destruct (getTypeStoreSize TD t2); simpl; eauto using gundef__total.\n  destruct (n =n= length y); eauto using gundef__total.\n  destruct (splitGenericValue x ofs); eauto using gundef__total.\n  destruct p.  \n  destruct (splitGenericValue g0 (Z_of_nat n)); eauto using gundef__total.\n  destruct p. eauto.\n  destruct (gv_chunks_match_typb TD g1 t2); eauto using gundef__total.\nQed.\n\nLemma mget'_is_total : forall S TD ofs t' \n  (w1 : wf_typ S TD t'),\n  forall x, exists z, mget' TD ofs t' x = Some z.\nProof.\n  intros.\n  unfold mget'. unfold mget.\n  destruct (getTypeStoreSize TD t'); simpl; eauto using gundef__total.\n  destruct (splitGenericValue x ofs); eauto using gundef__total.\n  destruct p.  \n  destruct (splitGenericValue g0 (Z_of_nat n)); eauto using gundef__total.\n  destruct p. eauto.\n  destruct (gv_chunks_match_typb TD g1 t'); eauto using gundef__total.\nQed.\n\n(********************************************)\n(** * type size *)\n\nLemma int_typsize' : forall td s\n  (H0 : feasible_typ td (typ_int s)),\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat s) 8) =\n    (size_chunk_nat (AST.Mint (s - 1)) + 0)%nat.\nProof.\n  intros.\n  unfold size_chunk_nat, size_chunk, bytesize_chunk.\n  assert (s > 0)%nat as WF.\n    destruct td. inv H0. auto.\n  assert (S (s - 1) = s) as EQ. omega.\n  rewrite EQ. auto.\nQed.\n\nDefinition zeroconst2GV_aux__getTypeSizeInBits_prop S TD t\n  :=\n  wf_styp S TD t ->\n  forall los nts gv nts' (Hty: feasible_typ (los, nts') t) (Huniq:uniq nts')\n  (Heq: TD = (los, nts)) acc (Hsub: exists nts0, nts'=nts0++nts)\n  (Hnc: forall id5 gv5 lt5 sz al, \n          lookupAL _ acc id5 = Some (Some gv5) ->\n          lookupAL _ nts id5 = Some lt5 ->\n          _getTypeSizeInBits_and_Alignment los \n            (getTypeSizeInBits_and_Alignment_for_namedts (los,nts') true) true\n            (typ_struct lt5) = Some (sz, al) ->\n          Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv5)\n  (Hz: zeroconst2GV_aux (los,nts') acc t = Some gv) sz al\n  (Hsize: _getTypeSizeInBits_and_Alignment los \n     (getTypeSizeInBits_and_Alignment_for_namedts (los,nts') true) true t\n     = Some (sz, al)),\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv.\n\nDefinition zeroconsts2GV_aux__getListTypeSizeInBits_prop sdt :=\n  wf_styp_list sdt ->\n  let 'lsdt := sdt in\n  let '(lsd, lt) := split lsdt in\n  forall S TD acc los nts' (Hty: feasible_typs (los, nts') lt)\n  nts (Heq: TD = (los, nts)) gv (Hsub: exists nts0, nts'=nts0++nts)\n  (Hz: zeroconsts2GV_aux (los,nts') acc lt = Some gv)\n  (Huniq:uniq nts')\n  (Hnc: forall id5 gv5 lt5 sz al, \n          lookupAL _ acc id5 = Some (Some gv5) ->\n          lookupAL _ nts id5 = Some lt5 ->\n          _getTypeSizeInBits_and_Alignment los \n            (getTypeSizeInBits_and_Alignment_for_namedts (los, nts') true) true\n            (typ_struct lt5) = Some (sz, al) ->\n          Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv5)\n  (Heq': eq_system_targetdata S TD lsd) sz al\n  (Hsize: _getListTypeSizeInBits_and_Alignment los \n     (getTypeSizeInBits_and_Alignment_for_namedts (los, nts') true) \n       lt = Some (sz, al)),\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv.\n\nLemma zeroconst2GV_aux_typsize_mutrec :\n  (forall S T t, zeroconst2GV_aux__getTypeSizeInBits_prop S T t) /\\\n  (forall sdt, zeroconsts2GV_aux__getListTypeSizeInBits_prop sdt).\nProof.\nLocal Opaque feasible_typ feasible_typs.\n  (wfstyp_cases (apply wf_styp_mutind; \n                 unfold zeroconst2GV_aux__getTypeSizeInBits_prop, \n                        zeroconsts2GV_aux__getListTypeSizeInBits_prop) Case);\n    intros; subst; simpl in *; uniq_result; eauto.\nCase \"wf_styp_int\".\n  simpl. eapply int_typsize'; eauto.\n\nCase \"wf_styp_structure\".\n  simpl_split lsd lt.\n  assert (lt = typ_list) as EQ1. \n    eapply make_list_typ_spec2; eauto.\n  subst.\n  assert (eq_system_targetdata system5 (los, nts) lsd) as EQ2.\n    eapply wf_styp__feasible_typ_aux_mutrec_struct; eauto.\n  subst.\n  inv_mbind. symmetry_ctx.\n  eapply H1 in HeqR0; eauto using list_system_typ_spec, feasible_struct_typ_inv.\n  destruct n; inv H3.\n      destruct g as [|[]]; inv H4; auto.\n        simpl in HeqR0.\n        assert (J3 := size_chunk_nat_pos' m).\n        contradict HeqR0; omega.\n\n      destruct g as [|[]]; inv H4; auto.\n        assert (Coqlib.ZRdiv (Z_of_nat (S n)) 8 > 0) as J.\n          apply Coqlib.ZRdiv_prop3; try solve [omega | apply Coqlib.Z_of_S_gt_O].\n        apply Coqlib.nat_of_Z_pos in J.\n        contradict HeqR0. simpl in *. omega.\n\nCase \"wf_styp_array\".\n  destruct sz5 as [|sz5]; uniq_result; auto.\n  remember (zeroconst2GV_aux (los, nts') acc typ5) as R1.\n  destruct R1; try solve [inv Hz].\n  remember (getTypeAllocSize (los, nts') typ5) as R2.\n  destruct R2 as [s1|]; inv Hz.\n  assert (\n    (g ++ uninits (Size.to_nat s1 - sizeGenericValue g)) ++\n          repeatGV (g ++ uninits (Size.to_nat s1 - sizeGenericValue g)) sz5 = \n    repeatGV (g ++ uninits (Size.to_nat s1 - sizeGenericValue g)) (S sz5)) as G.\n    simpl. auto.\n  rewrite G. clear G.\n  symmetry in HeqR1.\n  inv_mbind.\n  unfold getTypeAllocSize, getTypeStoreSize, getTypeSizeInBits, \n    getABITypeAlignment, getAlignment, getTypeSizeInBits_and_Alignment,\n    getTypeSizeInBits_and_Alignment_for_namedts in HeqR2.\n  rewrite <- HeqR in HeqR2. uniq_result. \n  eapply H0 in HeqR1; eauto using feasible_array_typ_inv.\n  repeat rewrite HeqR1.\n  rewrite sizeGenericValue__repeatGV.\n  rewrite sizeGenericValue__app.\n  rewrite sizeGenericValue__uninits. unfold Size.to_nat.\n  assert (RoundUpAlignment (sizeGenericValue g) al >= (sizeGenericValue g))%nat \n    as J3.\n    apply RoundUpAlignment_spec.\n      apply feasible_array_typ_inv in Hty.\n      eapply feasible_typ_inv' in Hty; eauto.\n      destruct Hty as [sz0 [al0 [J3 J4]]].\n      unfold getTypeSizeInBits_and_Alignment,\n             getTypeSizeInBits_and_Alignment_for_namedts in J3.\n      rewrite J3 in HeqR. uniq_result. auto.\n  assert ((sizeGenericValue g +\n     (RoundUpAlignment (sizeGenericValue g) al - sizeGenericValue g))%nat = \n     (RoundUpAlignment (sizeGenericValue g) al)) as J4.\n    rewrite <- le_plus_minus; auto.\n  rewrite J4.\n  rewrite ZRdiv_prop8.\n  ring.\n\nCase \"wf_styp_namedt\".\n  inv_mbind. \n  remember (lookupAL _ nts id5) as R.\n  destruct R as [lt|]; try congruence. symmetry_ctx.\n  assert (G:=HeqR0).\n  apply lookupAL_middle_inv in HeqR0.\n  destruct HeqR0 as [l1 [l2 HeqR0]].\n  destruct Hsub as [nts0 Hsub]; subst.\n  apply feasible_typ_inv in Hty.\n  destruct Hty as [sz5 [al5 [J1 ?]]].\n  simpl in J1. simpl_env in Huniq.\n  eapply getTypeSizeInBits_and_Alignment_for_namedts_spec1 in J1; eauto.\n  rewrite_env ((nts0 ++ l1) ++ (id5, lt) :: l2) in Hsize.\n  eapply getTypeSizeInBits_and_Alignment_for_namedts_spec1 \n    with (nts1:=nts0++l1)(nts2:=l2) in Hsize; simpl_env; eauto.\n  uniq_result.\n  apply getTypeSizeInBits_and_Alignment_aux_weakening \n    with (nm2:=nts0 ++ l1 ++ [(id5, lt)]) in J1; simpl_env; auto.\n  simpl_env in J1. simpl in J1.\n  eapply Hnc in J1; eauto.\n     \nCase \"wf_styp_nil\".\n  intros. uniq_result. simpl. auto.\n\nCase \"wf_styp_cons\".\n  remember (split l') as R.\n  destruct R as [lsd lt]. simpl.\n  intros. subst.\n  apply eq_system_targetdata_cons_inv in Heq'. \n  destruct Heq' as [H4 [EQ1 EQ2]]; subst.\n  remember (zeroconsts2GV_aux (los, nts') acc lt) as R1.\n  destruct R1; tinv Hz.\n  remember (zeroconst2GV_aux (los, nts') acc typ_) as R2.\n  destruct R2; tinv Hz.\n  remember (getTypeAllocSize (los, nts') typ_) as R3.\n  destruct R3; inv Hz. \n  symmetry in HeqR1. symmetry in HeqR2.\n  apply feasible_cons_typs_inv in Hty.\n  destruct Hty as [Hty1 Hty2]. \n  inv_mbind. uniq_result.\n  eapply H0 in HeqR2; eauto 1. \n  eapply H2 in HeqR1; eauto 1.\n  rewrite sizeGenericValue__app.\n  rewrite sizeGenericValue__app.\n  rewrite sizeGenericValue__uninits. \n  rewrite plus_assoc. symmetry_ctx.\n  rewrite <- HeqR1. repeat rewrite <- HeqR2.\n  rewrite ZRdiv_prop9.\n  rewrite plus_comm with (m:=nat_of_Z (ZRdiv (Z_of_nat n) 8)).\n  erewrite getTypeAllocSize_roundup; eauto.\n  eapply getTypeAllocSize_inv' in HeqR3; eauto. \nTransparent feasible_typ feasible_typs.\nQed.\n\nLemma zeroconst2GV_for_namedts_cons : forall TD los nm1 nm2,\n  exists re,\n    zeroconst2GV_for_namedts TD los (nm2++nm1) =\n      re ++ zeroconst2GV_for_namedts TD los nm1.\nProof.\n  induction nm2 as [|[]]; simpl.\n  eexists nil; auto.\n\n    destruct IHnm2 as [re IHnm2].\n    rewrite IHnm2.\n    match goal with \n    | |- context [\n           match ?x with\n           | Some _ => _\n           | None => _\n           end] => destruct x; simpl_env; eauto\n    end.\nQed.\n\nDefinition zeroconst2GV_aux_weaken_prop (t:typ) := forall TD nm1 nm2 r,\n  uniq (nm2++nm1) ->\n  zeroconst2GV_aux TD nm1 t = Some r ->\n  zeroconst2GV_aux TD (nm2++nm1) t = Some r.\n\nDefinition zeroconsts2GV_aux_weaken_prop (lt:list typ) := \n  forall TD nm1 nm2 r,\n  uniq (nm2++nm1) ->\n  zeroconsts2GV_aux TD nm1 lt = Some r ->\n  zeroconsts2GV_aux TD (nm2++nm1) lt = Some r.\n\nLemma zeroconst2GV_aux_weaken_mutrec :\n  (forall t, zeroconst2GV_aux_weaken_prop t) *\n  (forall lt, zeroconsts2GV_aux_weaken_prop lt).\nProof.\n  (typ_cases (apply typ_mutrec; \n    unfold zeroconst2GV_aux_weaken_prop, \n           zeroconsts2GV_aux_weaken_prop) Case);\n    intros; simpl in *; try solve [eauto | inversion H | inversion H1 ].\nCase \"typ_array\".\n  match goal with\n  | H : match ?s with\n    | 0%nat => _\n    | S _ => _\n    end = _ |- _ => destruct s as [|s]; auto\n  end.\n  inv_mbind. erewrite H; eauto; simpl; auto.\n\nCase \"typ_struct\".\n  inv_mbind. erewrite H; eauto; simpl; auto.\n\nCase \"typ_namedt\".\n  inv_mbind. erewrite lookupAL_weaken; auto.\nCase \"typ_cons\".\n  inv_mbind.\n  erewrite H0; eauto.\n  erewrite H; eauto.\nQed.\n\nLemma zeroconst2GV_for_namedts_dom: forall TD acc nm,\n  dom (zeroconst2GV_for_namedts TD acc nm) [=] dom nm.\nProof.\n  induction nm as [|[]]; simpl; fsetdec.\nQed.\n\nLemma zeroconst2GV_for_namedts_uniq: forall TD acc nm\n  (Huniq: uniq nm),\n  uniq (zeroconst2GV_for_namedts TD acc nm).\nProof.\n  induction 1; simpl; auto.\n    simpl_env.\n    constructor; auto.\n      assert (J:=@zeroconst2GV_for_namedts_dom TD acc E).\n      fsetdec.\nQed.\n\nLemma zeroconst2GV_aux_weakening: forall TD los t r \n  (nm1 nm2:namedts) (Huniq: uniq (nm2++nm1)),\n  zeroconst2GV_aux TD\n    (zeroconst2GV_for_namedts TD los nm1) t = Some r ->\n  zeroconst2GV_aux TD\n    (zeroconst2GV_for_namedts TD los (nm2++nm1)) t = Some r.\nProof.\n  intros.  \n  destruct (@zeroconst2GV_for_namedts_cons TD los nm1 nm2) as [re J].\n  rewrite J. \n  eapply zeroconst2GV_aux_weaken_mutrec; eauto.\n  unfold id in *.\n  rewrite <- J. \n  eapply zeroconst2GV_for_namedts_uniq; eauto. \nQed.\n\nLemma zeroconst2GV_for_namedts_spec1: forall TD los nts2 lt2\n  i0 r nts1 nts (Huniq: uniq nts),\n  lookupAL _ (zeroconst2GV_for_namedts TD los nts) i0 = Some (Some r) ->\n  nts = nts1 ++ (i0,lt2) :: nts2 ->  \n  zeroconst2GV_aux TD (zeroconst2GV_for_namedts TD los nts2) (typ_struct lt2) \n    = Some r.\nProof.\n  induction nts1 as [|[]]; intros; subst; simpl in *.\n    destruct (i0 == i0); try congruence; auto.\n\n    inv Huniq.\n    simpl_env in H4.\n    destruct (i0 == a); subst.\n      contradict H4; fsetdec.\n      apply IHnts1 in H; auto.\nQed.\n\nLemma noncycled__zeroconst2GV_aux_typsize: forall S los nts\n  (H: noncycled S los nts) (Huniq: uniq nts)\n  id5 lt nts2 nts1 (EQ: nts = nts1 ++ (id5,lt) :: nts2) nts' (Huniq': uniq nts') \n  (Hsub: exists nts0, nts'=nts0++nts)\n  (Hftp: forall id5 lt5, lookupAL _ nts id5 = Some lt5 ->\n                         feasible_typ (los, nts') (typ_struct lt5)) gv\n  (Hz: zeroconst2GV_aux (los, nts')\n         (zeroconst2GV_for_namedts (los, nts') los nts2) (typ_struct lt) = \n           Some gv) sz al\n  (Hsize: _getTypeSizeInBits_and_Alignment los \n      (getTypeSizeInBits_and_Alignment_for_namedts (los,nts') true) true \n         (typ_struct lt) =  Some (sz, al)),\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv.\nProof.\nLocal Opaque feasible_typ feasible_typs \n  getTypeSizeInBits_and_Alignment_for_namedts _getTypeSizeInBits_and_Alignment.\n  induction 1; simpl; intros; subst.\n    symmetry in EQ.    \n    apply app_eq_nil in EQ.\n    destruct EQ as [_ EQ].\n    congruence.\n\n    inv Huniq.\n    destruct nts1 as [|[]]; inv EQ.\n      destruct zeroconst2GV_aux_typsize_mutrec as [J _].\n      eapply J in H0; eauto.\n      assert (feasible_typ (layouts5, nts') (typ_struct lt)) as Hty.\n        apply Hftp with (id5:=id0).\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id0 id0); \n          try congruence.\n      assert (exists nts0 : list namedt, nts' = nts0 ++ nts2) as G.\n        destruct Hsub as [nts0 Hsub]; subst. \n        exists (nts0 ++ [(id0, lt)]). simpl_env. auto.\n      eapply H0 in Hty; eauto 1.  \n      intros id5 gv5 lt5 sz5 al5 H1 H2 H4.\n      apply lookupAL_middle_inv in H2.\n      destruct H2 as [l1 [l2 HeqR]].\n      assert (J':=HeqR). subst.\n      eapply IHnoncycled with (nts':=nts') (al:=al5) in J'; eauto.\n        intros.\n        apply Hftp with (id6:=id1).\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id1 id0); \n          subst; auto.\n          apply notin_lookupAL_None in H5. congruence.\n       \n        eapply zeroconst2GV_for_namedts_spec1 in H1; eauto.\n            \n      assert (nts1 ++ (id0, lt) :: nts2 = nts1 ++ (id0, lt) :: nts2) as EQ. auto.\n      eapply IHnoncycled with (nts':=nts') in EQ; eauto.\n        destruct Hsub as [nts0 Hsub]; subst. \n        exists (nts0 ++ [(i0, l0)]). simpl_env. auto.\n \n        intros.\n        apply Hftp with (id5:=id5)(lt5:=lt5).\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id5 i0); \n          subst; auto.\n          apply notin_lookupAL_None in H5. congruence.\nTransparent feasible_typ feasible_typs\n  getTypeSizeInBits_and_Alignment_for_namedts _getTypeSizeInBits_and_Alignment.\nQed.\n\nLemma zeroconst2GV__getTypeSizeInBits : forall t s los nts gv\n  (Hz: zeroconst2GV (los,nts) t = Some gv)\n  (Ht: wf_typ s (los,nts) t),\n  exists sz, exists al,\n    _getTypeSizeInBits_and_Alignment los \n      (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t = \n         Some (sz, al) /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv.\nProof. \n  intros. \n  assert (G:=Ht).\n  apply wf_typ__feasible_typ in G; auto.\n  assert (G':=G).\n  apply feasible_typ_inv in G'.\n  destruct G' as [sz [al [J1 [J2 J3]]]].\n  unfold getTypeSizeInBits_and_Alignment in J1.\n  exists sz. exists al.\n  split; auto.\n  unfold zeroconst2GV in *. inv Ht.\n  destruct zeroconst2GV_aux_typsize_mutrec as [J' _].\n  assert (exists nts0 : list namedt, nts = nts0 ++ nts) as G'.\n    eexists nil; auto.\n  eapply J'; eauto.\n  intros id5 gv5 lt5 sz0 al0 J4 J5 J6.\n  apply lookupAL_middle_inv in J5.\n  destruct J5 as [l1 [l2 HeqR]]. subst.\n  eapply noncycled__zeroconst2GV_aux_typsize \n    with (nts':=l1 ++ (id5, lt5) :: l2) in H1; eauto.\n    intros id0 lt0 H.\n    apply lookupAL_middle_inv in H.\n    destruct H as [l3 [l4 H]].\n    rewrite H in *. \n    symmetry in H.\n    rewrite_env ((l3 ++ [(id0, lt0)]) ++ l4).\n    eapply noncycled__feasible_typ_aux with (nts1:=l3)(nts2:=l4) in H1; eauto.\n    unfold feasible_typ.\n    eapply feasible_typ_aux_weakening; eauto.\n      simpl_env. simpl. auto.\n\n    eapply zeroconst2GV_for_namedts_spec1 in J4; eauto.\nQed.\n\nDefinition flatten_typ_aux__getTypeSizeInBits_prop S TD (t:typ) :=\n  wf_styp S TD t ->\n  forall los nts mc acc nts' (Hft: flatten_typ_aux (los,nts') acc t = Some mc)\n  (Huniq:uniq nts') (Hty: LLVMtd.feasible_typ (los,nts') t) \n  (Heq: TD = (los, nts)) (Hsub: exists nts0, nts'=nts0++nts)\n  (Hnc: forall id5 gv5 lt5 sz al, \n          lookupAL _ acc id5 = Some (Some gv5) ->\n          lookupAL _ nts id5 = Some lt5 ->\n          _getTypeSizeInBits_and_Alignment los \n            (getTypeSizeInBits_and_Alignment_for_namedts (los,nts') true) true\n            (typ_struct lt5) = Some (sz, al) ->\n          Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeMC gv5)\n  sz al\n  (Hsize: _getTypeSizeInBits_and_Alignment los \n      (getTypeSizeInBits_and_Alignment_for_namedts (los,nts') true) true t = \n         Some (sz, al)),\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeMC mc.\n\nDefinition flatten_typs_aux__getListTypeSizeInBits_prop sdt :=\n  wf_styp_list sdt ->\n  let 'lsdt := sdt in\n  let '(lsd, lt) := split lsdt in\n  forall S TD acc los nts' mc nts\n  (Hty: flatten_typs_aux (los,nts') acc lt = Some mc)\n  (Hft: LLVMtd.feasible_typs (los,nts') lt)\n  (Heq: TD = (los, nts)) (Hsub: exists nts0, nts'=nts0++nts)\n  (Huniq:uniq nts')\n  (Hnc: forall id5 gv5 lt5 sz al, \n          lookupAL _ acc id5 = Some (Some gv5) ->\n          lookupAL _ nts id5 = Some lt5 ->\n          _getTypeSizeInBits_and_Alignment los \n            (getTypeSizeInBits_and_Alignment_for_namedts (los, nts') true) true\n            (typ_struct lt5) = Some (sz, al) ->\n          Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeMC gv5)\n  (Heq': eq_system_targetdata S TD lsd) sz al\n  (Hsize: _getListTypeSizeInBits_and_Alignment los \n     (getTypeSizeInBits_and_Alignment_for_namedts (los, nts') true) \n       lt = Some (sz, al)),\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeMC mc.\n\nLemma flatten_typ_aux_typsize_mutrec :\n  (forall S TD t, flatten_typ_aux__getTypeSizeInBits_prop S TD t) /\\\n  (forall sdt, flatten_typs_aux__getListTypeSizeInBits_prop sdt).\nProof.\nLocal Opaque feasible_typ feasible_typs.\n  (wfstyp_cases (apply wf_styp_mutind; \n                 unfold flatten_typ_aux__getTypeSizeInBits_prop, \n                        flatten_typs_aux__getListTypeSizeInBits_prop) Case);\n    intros; subst; simpl in *; uniq_result; eauto.\n\nCase \"wf_styp_int\".\n  simpl. eapply int_typsize'; eauto.\n\nCase \"wf_styp_structure\".\n  simpl_split lsd lt.\n  assert (lt = typ_list) as EQ1. \n    eapply make_list_typ_spec2; eauto.\n  subst.\n  assert (eq_system_targetdata system5 (los, nts) lsd) as EQ2.\n    eapply wf_styp__feasible_typ_aux_mutrec_struct; eauto.\n  subst.\n  inv_mbind. symmetry_ctx.\n  eapply_clear H1 in HeqR0; eauto using list_system_typ_spec, feasible_struct_typ_inv.\n  destruct n as [|n]; inv H3.\n    destruct l0; inv H4; auto.\n      simpl in HeqR0.\n      assert (J3 := size_chunk_nat_pos' m).\n      contradict HeqR0; omega.\n\n    destruct l0; inv H4; auto.\n      assert (Coqlib.ZRdiv (Z_of_nat (S n)) 8 > 0) as J.\n        apply Coqlib.ZRdiv_prop3; try solve [omega | apply Coqlib.Z_of_S_gt_O].\n      apply Coqlib.nat_of_Z_pos in J.\n      contradict HeqR0. simpl in *. omega.\n\nCase \"wf_styp_array\".\n  destruct sz5 as [|sz5]; uniq_result; auto. \n  remember (flatten_typ_aux (los, nts') acc typ5) as R1.\n  destruct R1; try solve [inv Hft].\n  remember (getTypeAllocSize (los, nts') typ5) as R2.\n  destruct R2 as [s1|]; inv Hft.\n  assert (\n    (l0 ++ uninitMCs (Size.to_nat s1 - sizeMC l0)) ++\n          repeatMC (l0 ++ uninitMCs (Size.to_nat s1 - sizeMC l0)) sz5 = \n    repeatMC (l0 ++ uninitMCs (Size.to_nat s1 - sizeMC l0)) (S sz5)) as G.\n    simpl. auto.\n  rewrite G. clear G.\n  symmetry in HeqR1.\n  inv_mbind.\n  unfold getTypeAllocSize, getTypeStoreSize, getTypeSizeInBits, \n    getABITypeAlignment, getAlignment, getTypeSizeInBits_and_Alignment,\n    getTypeSizeInBits_and_Alignment_for_namedts in HeqR2.\n  rewrite <- HeqR in HeqR2. uniq_result. \n  eapply H0 in HeqR1; eauto using feasible_array_typ_inv.\n  repeat rewrite HeqR1.\n  rewrite sizeMC__repeatMC.\n  rewrite sizeMC__app.\n  rewrite sizeMC__uninitMCs. unfold Size.to_nat.\n  assert (RoundUpAlignment (sizeMC l0) al >= (sizeMC l0))%nat \n    as J3.\n    apply RoundUpAlignment_spec.\n      apply feasible_array_typ_inv in Hty.\n      eapply feasible_typ_inv' in Hty; eauto.\n      destruct Hty as [sz0 [al0 [J3 J4]]].\n      unfold getTypeSizeInBits_and_Alignment,\n             getTypeSizeInBits_and_Alignment_for_namedts in J3.\n      rewrite J3 in HeqR. uniq_result. auto.\n  assert ((sizeMC l0 +\n     (RoundUpAlignment (sizeMC l0) al - sizeMC l0))%nat = \n     (RoundUpAlignment (sizeMC l0) al)) as J4.\n    rewrite <- le_plus_minus; auto.\n  rewrite J4.\n  rewrite ZRdiv_prop8.\n  ring.\n\nCase \"wf_styp_namedt\".\n  inv_mbind. \n  remember (lookupAL _ nts id5) as R.\n  destruct R as [lt|]; try congruence. symmetry_ctx.\n  assert (G:=HeqR0).\n  apply lookupAL_middle_inv in HeqR0.\n  destruct HeqR0 as [l1 [l2 HeqR0]].\n  destruct Hsub as [nts0 Hsub]; subst.\n  apply feasible_typ_inv in Hty.\n  destruct Hty as [sz5 [al5 [J1 ?]]].\n  simpl in J1. simpl_env in Huniq.\n  eapply getTypeSizeInBits_and_Alignment_for_namedts_spec1 in J1; eauto.\n  rewrite_env ((nts0 ++ l1) ++ (id5, lt) :: l2) in Hsize.\n  eapply getTypeSizeInBits_and_Alignment_for_namedts_spec1 \n    with (nts1:=nts0++l1)(nts2:=l2) in Hsize; simpl_env; eauto.\n  uniq_result.\n  apply getTypeSizeInBits_and_Alignment_aux_weakening \n    with (nm2:=nts0 ++ l1 ++ [(id5, lt)]) in J1; simpl_env; auto.\n  simpl_env in J1. simpl in J1.\n  eapply Hnc in J1; eauto.\n     \nCase \"wf_styp_nil\".\n  intros. uniq_result. simpl. auto.\n\nCase \"wf_styp_cons\".\n  remember (split l') as R.\n  destruct R as [lsd lt]. simpl.\n  intros. subst.\n  apply eq_system_targetdata_cons_inv in Heq'. \n  destruct Heq' as [H4 [EQ1 EQ2]]; subst.\n  remember (flatten_typs_aux (los, nts') acc lt) as R1.\n  destruct R1; tinv Hty.\n  remember (flatten_typ_aux (los, nts') acc typ_) as R2.\n  destruct R2; tinv Hty.\n  remember (getTypeAllocSize (los, nts') typ_) as R3.\n  destruct R3; inv Hty. \n  symmetry in HeqR1. symmetry in HeqR2.\n  apply feasible_cons_typs_inv in Hft.\n  destruct Hft as [Hft1 Hft2]. \n  inv_mbind. uniq_result.\n  eapply_clear H0 in HeqR2; eauto. \n  eapply_clear H2 in HeqR1; eauto.\n  rewrite sizeMC__app.\n  rewrite sizeMC__app.\n  rewrite sizeMC__uninitMCs. \n  rewrite plus_assoc. symmetry_ctx.\n  rewrite <- HeqR1. repeat rewrite <- HeqR2.\n  rewrite ZRdiv_prop9.\n  rewrite plus_comm with (m:=nat_of_Z (ZRdiv (Z_of_nat n) 8)).\n  erewrite getTypeAllocSize_roundup; eauto.\n  eapply getTypeAllocSize_inv' in HeqR3; eauto. \nTransparent feasible_typ feasible_typs.\nQed.\n\nLemma flatten_typ_for_namedts_cons : forall TD los nm1 nm2,\n  exists re,\n    flatten_typ_for_namedts TD los (nm2++nm1) =\n      re ++ flatten_typ_for_namedts TD los nm1.\nProof.\n  induction nm2 as [|[]]; simpl.\n    eexists nil; auto.\n\n    destruct IHnm2 as [re IHnm2].\n    rewrite IHnm2.\n    match goal with \n    | |- context [\n           match ?x with\n           | Some _ => _\n           | None => _\n           end] => destruct x; simpl_env; eauto\n    end.\nQed.\n\nDefinition flatten_typ_aux_weaken_prop (t:typ) := forall TD nm1 nm2 r,\n  uniq (nm2++nm1) ->\n  flatten_typ_aux TD nm1 t = Some r ->\n  flatten_typ_aux TD (nm2++nm1) t = Some r.\n\nDefinition flatten_typs_aux_weaken_prop (lt:list typ) := \n  forall TD nm1 nm2 r,\n  uniq (nm2++nm1) ->\n  flatten_typs_aux TD nm1 lt = Some r ->\n  flatten_typs_aux TD (nm2++nm1) lt = Some r.\n\nLemma flatten_typ_aux_weaken_mutrec :\n  (forall t, flatten_typ_aux_weaken_prop t) *\n  (forall lt, flatten_typs_aux_weaken_prop lt).\nProof.\n  (typ_cases (apply typ_mutrec; \n    unfold flatten_typ_aux_weaken_prop, \n           flatten_typs_aux_weaken_prop) Case);\n    intros; simpl in *; try solve [eauto | inversion H | inversion H1 ].\nCase \"typ_array\".\n  match goal with\n  | H : match ?s with\n    | 0%nat => _\n    | S _ => _\n    end = _ |- _ => destruct s as [|s]; auto\n  end.\n  inv_mbind. erewrite H; eauto; simpl; auto.\n\nCase \"typ_struct\".\n  inv_mbind. erewrite H; eauto; simpl; auto.\n\nCase \"typ_namedt\".\n  inv_mbind. erewrite lookupAL_weaken; auto.\nCase \"typ_cons\".\n  inv_mbind.\n  erewrite H0; eauto.\n  erewrite H; eauto.\nQed.\n\nLemma flatten_typ_for_namedts_dom: forall TD acc nm,\n  dom (flatten_typ_for_namedts TD acc nm) [=] dom nm.\nProof.\n  induction nm as [|[]]; simpl; fsetdec.\nQed.\n\nLemma flatten_typ_for_namedts_uniq: forall TD acc nm\n  (Huniq: uniq nm),\n  uniq (flatten_typ_for_namedts TD acc nm).\nProof.\n  induction 1; simpl; auto.\n    simpl_env.\n    constructor; auto.\n      assert (J:=@flatten_typ_for_namedts_dom TD acc E).\n      fsetdec.\nQed.\n\nLemma flatten_typ_aux_weakening: forall TD los t r \n  (nm1 nm2:namedts) (Huniq: uniq (nm2++nm1)),\n  flatten_typ_aux TD\n    (flatten_typ_for_namedts TD los nm1) t = Some r ->\n  flatten_typ_aux TD\n    (flatten_typ_for_namedts TD los (nm2++nm1)) t = Some r.\nProof.\n  intros.  \n  destruct (@flatten_typ_for_namedts_cons TD los nm1 nm2) as [re J].\n  rewrite J. \n  eapply flatten_typ_aux_weaken_mutrec; eauto.\n  unfold id in *.\n  rewrite <- J. \n  eapply flatten_typ_for_namedts_uniq; eauto. \nQed.\n\nLemma flatten_typ_for_namedts_spec1: forall TD los nts2 lt2\n  i0 r nts1 nts (Huniq: uniq nts),\n  lookupAL _ (flatten_typ_for_namedts TD los nts) i0 = Some (Some r) ->\n  nts = nts1 ++ (i0,lt2) :: nts2 ->  \n  flatten_typ_aux TD (flatten_typ_for_namedts TD los nts2) (typ_struct lt2) \n    = Some r.\nProof.\n  induction nts1 as [|[]]; intros; subst; simpl in *.\n    destruct (i0 == i0); try congruence; auto.\n\n    inv Huniq.\n    simpl_env in H4.\n    destruct (i0 == a); subst.\n      contradict H4; fsetdec.\n      apply IHnts1 in H; auto.\nQed.\n\nLemma noncycled__flatten_typ_aux_typsize: forall S los nts\n  (H: noncycled S los nts) (Huniq: uniq nts)\n  id5 lt nts2 nts1 (EQ: nts = nts1 ++ (id5,lt) :: nts2) nts' (Huniq': uniq nts') \n  (Hsub: exists nts0, nts'=nts0++nts)\n  (Hftp: forall id5 lt5, lookupAL _ nts id5 = Some lt5 ->\n                         feasible_typ (los, nts') (typ_struct lt5)) mc\n  (Hz: flatten_typ_aux (los, nts')\n         (flatten_typ_for_namedts (los, nts') los nts2) (typ_struct lt) = \n           Some mc) sz al\n  (Hsize: _getTypeSizeInBits_and_Alignment los \n      (getTypeSizeInBits_and_Alignment_for_namedts (los,nts') true) true \n         (typ_struct lt) =  Some (sz, al)),\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeMC mc.\nProof.\nLocal Opaque feasible_typ feasible_typs \n  getTypeSizeInBits_and_Alignment_for_namedts _getTypeSizeInBits_and_Alignment.\n  induction 1; simpl; intros; subst.\n    symmetry in EQ.    \n    apply app_eq_nil in EQ.\n    destruct EQ as [_ EQ].\n    congruence.\n\n    inv Huniq.\n    destruct nts1 as [|[]]; inv EQ.\n      destruct flatten_typ_aux_typsize_mutrec as [J _].\n      eapply J in H0; eauto.\n      assert (feasible_typ (layouts5, nts') (typ_struct lt)) as Hty.\n        apply Hftp with (id5:=id0).\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id0 id0); \n          try congruence.\n      assert (exists nts0 : list namedt, nts' = nts0 ++ nts2) as G.\n        destruct Hsub as [nts0 Hsub]; subst. \n        exists (nts0 ++ [(id0, lt)]). simpl_env. auto.\n      eapply H0 in Hty; eauto.  \n      intros id5 gv5 lt5 sz5 al5 H1 H2 H4.\n      apply lookupAL_middle_inv in H2.\n      destruct H2 as [l1 [l2 HeqR]].\n      assert (J':=HeqR). subst.\n      eapply IHnoncycled with (nts':=nts') (al:=al5) in J'; eauto.\n        intros.\n        apply Hftp with (id6:=id1).\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id1 id0); \n          subst; auto.\n          apply notin_lookupAL_None in H5. congruence.\n       \n        eapply flatten_typ_for_namedts_spec1 in H1; eauto.\n            \n      assert (nts1 ++ (id0, lt) :: nts2 = nts1 ++ (id0, lt) :: nts2) as EQ. auto.\n      eapply IHnoncycled with (nts':=nts') in EQ; eauto.\n        destruct Hsub as [nts0 Hsub]; subst. \n        exists (nts0 ++ [(i0, l0)]). simpl_env. auto.\n \n        intros.\n        apply Hftp with (id5:=id5)(lt5:=lt5).\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id5 i0); \n          subst; auto.\n          apply notin_lookupAL_None in H5. congruence.\nTransparent feasible_typ feasible_typs\n  getTypeSizeInBits_and_Alignment_for_namedts _getTypeSizeInBits_and_Alignment.\nQed.\n\nLemma flatten_typ__getTypeSizeInBits : forall t s los nts mc\n  (Hz: flatten_typ (los,nts) t = Some mc)\n  (Ht: wf_typ s (los,nts) t),\n  exists sz, exists al,\n    _getTypeSizeInBits_and_Alignment los \n      (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t = \n         Some (sz, al) /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeMC mc.\nProof. \n  intros. \n  assert (G:=Ht).\n  apply wf_typ__feasible_typ in G; auto.\n  assert (G':=G).\n  apply feasible_typ_inv in G'.\n  destruct G' as [sz [al [J1 [J2 J3]]]].\n  unfold getTypeSizeInBits_and_Alignment in J1.\n  exists sz. exists al.\n  split; auto.\n  unfold flatten_typ in *. inv Ht.\n  destruct flatten_typ_aux_typsize_mutrec as [J' _].\n  assert (exists nts0 : list namedt, nts = nts0 ++ nts) as G'.\n    eexists nil; auto.\n  eapply J'; eauto.\n  intros id5 gv5 lt5 sz0 al0 J4 J5 J6.\n  apply lookupAL_middle_inv in J5.\n  destruct J5 as [l1 [l2 HeqR]]. subst.\n  eapply noncycled__flatten_typ_aux_typsize \n    with (nts':=l1 ++ (id5, lt5) :: l2) in H1; eauto.\n    intros id0 lt0 H.\n    apply lookupAL_middle_inv in H.\n    destruct H as [l3 [l4 H]].\n    rewrite H in *. \n    symmetry in H.\n    rewrite_env ((l3 ++ [(id0, lt0)]) ++ l4).\n    eapply noncycled__feasible_typ_aux with (nts1:=l3)(nts2:=l4) in H1; eauto.\n    unfold feasible_typ.\n    eapply feasible_typ_aux_weakening; eauto.\n      simpl_env. simpl. auto.\n\n    eapply flatten_typ_for_namedts_spec1 in J4; eauto.\nQed.\n\nLemma gundef__getTypeSizeInBits : forall s los nts gv t' \n  (H1: wf_typ s (los, nts) t') (HeqR : ret gv = gundef (los, nts) t'),\n   exists sz0 : nat,\n     exists al : nat,\n       _getTypeSizeInBits_and_Alignment los\n         (_getTypeSizeInBits_and_Alignment_for_namedts los nts true)\n         true t' = ret (sz0, al) /\\\n       Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz0) 8) = sizeGenericValue gv.\nProof.\n  intros.\n  unfold gundef in HeqR.\n  assert (J:=H1).\n  apply flatten_typ_total in H1; auto.\n  destruct H1 as [mc H1].\n  rewrite H1 in HeqR.\n  uniq_result.\n  rewrite sizeGenericValue_mc2undefs__sizeMC.\n  eapply flatten_typ__getTypeSizeInBits; eauto.\nQed.\n\nLemma mtrunc_typsize : forall S los nts top t1 t2 gv1 gv2\n  (H0: wf_typ S (los,nts) t2) (H1: mtrunc (los,nts) top t1 t2 gv1 = Some gv2)\n,\n  exists sz, exists al,\n    _getTypeSizeInBits_and_Alignment los \n      (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t2 = \n         Some (sz, al) /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv2.\nProof.  \n  intros. \n  unfold mtrunc, GV2val in H1.\n  destruct gv1; tinv H1.\n    eapply gundef__getTypeSizeInBits; eauto.\n  destruct p.\n  destruct gv1; \n    try solve [inversion H1; eapply gundef__getTypeSizeInBits; eauto].\n  destruct v; try solve [eapply gundef__getTypeSizeInBits; eauto].\n    destruct_typ t1; try solve [eapply gundef__getTypeSizeInBits; eauto].\n    destruct_typ t2; try solve [eapply gundef__getTypeSizeInBits; eauto].\n      inv H1.\n      simpl. exists (Size.to_nat s1).\n      exists (getIntAlignmentInfo los (Size.to_nat s1) true).\n      erewrite int_typsize; eauto.\n  \n    destruct_typ t1; try solve [eapply gundef__getTypeSizeInBits; eauto].\n    destruct_typ t2; try solve [eapply gundef__getTypeSizeInBits; eauto].\n    remember (floating_point_order f1 f0) as R.\n    {\n      des_ifs; try by (eapply gundef__getTypeSizeInBits; eauto).\n      destruct f1; inv Heq.\n      simpl. exists 32%nat. exists (getFloatAlignmentInfo los 32 true).\n      auto.\n    }\n\n    destruct_typ t1; try solve [eapply gundef__getTypeSizeInBits; eauto].\n    destruct_typ t2; try solve [eapply gundef__getTypeSizeInBits; eauto].\nQed.\n\nLemma mext_typsize : forall S los nts eop t1 t2 gv1 gv2\n  (H0: wf_typ S (los,nts) t2)\n  (H1: mext (los,nts) eop t1 t2 gv1 = Some gv2),\n  exists sz, exists al,\n    _getTypeSizeInBits_and_Alignment los \n      (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t2 = \n         Some (sz, al) /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv2.\nProof.\n  {\n    ii. unfold mext, GV2val in H1.\n    des_ifs; try (by eapply gundef__getTypeSizeInBits; eauto).\n    - ss. esplits; eauto. erewrite int_typsize; eauto.\n    - ss. esplits; eauto. erewrite int_typsize; eauto.\n    - ss. esplits; eauto.\n  }\n  (* intros. unfold mext, GV2val in H1. *)\n  (* destruct_typ t1; tinv H1. *)\n  (*   destruct_typ t2; tinv H1. *)\n  (*   destruct gv1;  *)\n  (*     try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto]. *)\n  (*   destruct p. *)\n  (*   destruct gv1;  *)\n  (*     try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto]. *)\n  (*   destruct v; try solve [eapply gundef__getTypeSizeInBits; eauto]. *)\n  (*   destruct eop; inv H1. *)\n  (*     simpl. exists (Size.to_nat s1). *)\n  (*     exists (getIntAlignmentInfo los (Size.to_nat s1) true). *)\n  (*     erewrite int_typsize; eauto. *)\n\n  (*     simpl. exists (Size.to_nat s1). *)\n  (*     exists (getIntAlignmentInfo los (Size.to_nat s1) true). *)\n  (*     erewrite int_typsize; eauto. *)\n\n  (*   destruct_typ t2; tinv H1. *)\n  (*   remember (floating_point_order f f0) as R. *)\n  (*   destruct R; tinv H1. *)\n  (*   destruct gv1;  *)\n  (*     try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto]. *)\n  (*   destruct p. *)\n  (*   destruct gv1;  *)\n  (*     try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto]. *)\n  (*   destruct v; try solve [eapply gundef__getTypeSizeInBits; eauto]. *)\n  (*   destruct eop; inv H1. *)\n  (*   destruct f0; inv H2; simpl. *)\n  (*     exists 64%nat. exists (getFloatAlignmentInfo los 64 true). auto. *)\nQed.\n\nLemma extractGenericValue_typsize : forall los nts t1 gv1 const_list typ' gv\n  sz al system5\n  (HeqR3 : ret gv = extractGenericValue (los, nts) t1 gv1 const_list)\n  (e0 : getSubTypFromConstIdxs const_list t1 = ret typ')\n  (J1 : _getTypeSizeInBits_and_Alignment los\n         (_getTypeSizeInBits_and_Alignment_for_namedts los nts true)\n         true t1 = ret (sz, al))\n  (J2 : Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv1)\n  (w1 : wf_typ system5 (los, nts) typ'),\n  exists sz0 : nat,\n    exists al0 : nat,\n        _getTypeSizeInBits_and_Alignment los\n          (_getTypeSizeInBits_and_Alignment_for_namedts los nts true)\n          true typ' = ret (sz0, al0) /\\\n        Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz0) 8) = sizeGenericValue gv.\nProof.\n  intros.\n  unfold extractGenericValue in HeqR3.\n  remember (intConsts2Nats (los, nts) const_list) as R1.\n  destruct R1 as [idxs|]; tinv HeqR3.\n  remember (mgetoffset (los, nts) t1 idxs) as R2.\n  destruct R2 as [[o t']|]; tinv HeqR3.\n  remember (mget (los, nts) gv1 o t') as R4.\n  eapply getSubTypFromConstIdxs__mgetoffset in e0; eauto.\n  destruct R4 as [gv'|]; inv HeqR3.\n    eapply mget_typsize; eauto.\n    eapply gundef__getTypeSizeInBits; eauto.\nQed.    \n\nLemma insertGenericValue_typsize : forall los nts t1 gv1 const_list gv t2 gv2\n    system5 sz al sz2 al2 \n  (J1 : _getTypeSizeInBits_and_Alignment los\n         (_getTypeSizeInBits_and_Alignment_for_namedts los nts true)\n         true t1 = ret (sz, al))\n  (J2 : Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv1)\n  (J3 : _getTypeSizeInBits_and_Alignment los\n         (_getTypeSizeInBits_and_Alignment_for_namedts los nts true)\n         true t2 = ret (sz2, al2))\n  (J4 : Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz2) 8) = sizeGenericValue gv2)\n  (w1 : wf_typ system5 (los, nts) t1)\n  (HeqR3 : ret gv = insertGenericValue (los, nts) t1 gv1 const_list t2 gv2),\n  sizeGenericValue gv1 = sizeGenericValue gv.\nProof.\n  intros.\n  unfold insertGenericValue in HeqR3.\n  remember (intConsts2Nats (los, nts) const_list) as R1.\n  destruct R1 as [idxs|]; tinv HeqR3.\n  remember (mgetoffset (los, nts) t1 idxs) as R2.\n  destruct R2 as [[o t']|]; tinv HeqR3.\n  remember (mset (los, nts) gv1 o t2 gv2) as R4.\n  destruct R4 as [gv'|]; inv HeqR3.\n    eapply mset_typsize in HeqR4; eauto. \n\n    match goal with\n    | H0: Some _ = gundef _ _ |- _ =>\n      eapply gundef__getTypeSizeInBits in H0; eauto;\n      destruct H0 as [sz1 [al1 [J3' J4']]];\n      rewrite J1 in J3'; inv J3';\n      rewrite <- J4'; rewrite <- J2; auto\n    end.\nQed.    \n\nLemma mbop_typsize_helper : forall TD system5 s gv \n  (H0: wf_typ system5 TD (typ_int s))\n  (H1: gundef TD (typ_int s) = ret gv),\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat s) 8) = sizeGenericValue gv.\nProof.\n  intros. destruct TD.\n  symmetry in H1.\n  eapply gundef__getTypeSizeInBits in H1; eauto; simpl; auto.\n    simpl in H1. destruct H1 as [sz0 [al [J1 J2]]]. inv J1. auto.\nQed.\n\nLemma mbop_typsize : forall system5 los nts bop5 s gv1 gv2 gv\n  (H0: wf_typ system5 (los, nts) (typ_int s))\n  (H1: mbop (los,nts) bop5 s gv1 gv2 = Some gv),\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat s) 8) = sizeGenericValue gv.\nProof.\n  intros. \n  unfold mbop, GV2val in H1.\n  destruct gv1; \n    try solve [inversion H1 | eapply mbop_typsize_helper; eauto].\n  destruct p.\n  destruct gv1; \n    try solve [inversion H1 | eapply mbop_typsize_helper; eauto].\n  destruct v; \n    try solve [inversion H1 | eapply mbop_typsize_helper; eauto].\n  destruct gv2; \n    try solve [inversion H1 | eapply mbop_typsize_helper; eauto].\n  destruct p.\n  destruct gv2; \n    try solve [inversion H1 | eapply mbop_typsize_helper; eauto].\n  destruct v; \n    try solve [inversion H1 | eapply mbop_typsize_helper; eauto].\n  destruct (eq_nat_dec (wz + 1) (Size.to_nat s));\n    try solve [inversion H1 | eapply mbop_typsize_helper; eauto].\n  unfold Size.to_nat in e. subst.\n  assert (S (Size.to_nat (wz + 1)%nat - 1) = wz + 1)%nat as EQ.\n    unfold Size.to_nat. omega.\n  destruct bop5; destruct (_ (Vint _ _) (Vint _ _)); inv H1;\n    try (simpl; unfold size_chunk_nat, size_chunk, bytesize_chunk, Size.to_nat in *\n      ; rewrite EQ; auto).\nQed.\n\nLemma mfbop_typsize : forall system5 los nts fbop5 f gv1 gv2 gv\n  (H0: wf_typ system5 (los, nts) (typ_floatpoint f))\n  (H1: mfbop (los,nts) fbop5 f gv1 gv2 = Some gv),\n  exists sz, exists al,\n    _getTypeSizeInBits_and_Alignment los \n      (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true \n        (typ_floatpoint f) = Some (sz, al) /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv.\nProof.\n  intros. \n  unfold mfbop, GV2val in H1.\n  destruct gv1; \n    try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto].\n  destruct p.\n  destruct gv1; \n    try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto].\n  destruct v; \n    try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto].\n  destruct gv2; \n    try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto].\n  destruct p.\n  destruct gv2; \n    try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto].\n  destruct v; \n    try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto].\n  destruct f; \n    try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto].\n    destruct fbop5; inv H1; simpl; eauto.\n\n  destruct gv2; \n    try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto].\n  destruct p.\n  destruct gv2; \n    try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto].\n  destruct v; \n    try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto].\n  destruct f; \n    try solve [inversion H1 | eapply gundef__getTypeSizeInBits; eauto].\n    destruct fbop5; inv H1; simpl; eauto.\nQed.\n\n(*\nLemma map_list_const_typ_spec3' : forall nts typ_5 ts\n  (HeqR : Constant.wf_zeroconst_typ typ_5)\n  (HeqR' : true = typ_eq_list_typ nts typ_5 ts),\n  Constant.wf_zeroconsts_typ ts.\nProof.\n  unfold typ_eq_list_typ.\n  intros.\n  destruct typ_5; tinv HeqR'.\n    destruct (list_typ_dec l0 ts); tinv HeqR'.\n    subst. auto.\n\n    remember (lookupAL list_typ (rev nts) i0) as G.\n    destruct G; tinv HeqR'.\n    destruct (list_typ_dec l0 ts); tinv HeqR'.\n    inv HeqR.\nQed.\n*)\n\nLemma wf_array_typ_inv : forall S TD s t,\n  wf_typ S TD (typ_array s t) -> wf_typ S TD t.\nProof.\n  intros.\n  inv H. constructor; auto.\n  inv H1. auto.\nQed.\n\nDefinition const2GV__getTypeSizeInBits_Prop S TD c t :=\n  wf_const S TD c t ->\n  forall los nts gl gv t'\n  (Heq: TD = (los, nts)) (Hc2g: _const2GV (los,nts) gl c = Some (gv, t'))\n  (Hwfg: wf_global TD S gl),\n  t = t' /\\\n  exists sz, exists al,\n    _getTypeSizeInBits_and_Alignment los \n      (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t = \n         Some (sz, al) /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv.\n\nDefinition consts2GV__getTypeSizeInBits_Prop sdct :=\n  wf_const_list sdct ->\n  let 'lsdct := sdct in\n  let '(lsdc, lt) := split lsdct in\n  let '(lsd, lc) := split lsdc in\n  let '(ls, ld) := split lsd in\n  forall S TD los nts gl (Heq: TD = (los, nts))\n  (Hwf: wf_list_targetdata_typ S TD gl lsd),\n  (forall gv t (Hft: feasible_typ TD t)\n    (Heq: forall t0, In t0 lt -> t0 = t)\n    (Hc2g: _list_const_arr2GV TD gl t lc = Some gv),\n   exists sz, \n    getTypeAllocSize TD t = Some sz /\\\n    (sz * length lc)%nat = sizeGenericValue gv) /\\\n  (forall gv lt'\n   (Hc2g: _list_const_struct2GV TD gl lc = Some (gv, lt')),\n   lt' = lt /\\\n   exists sz, exists al,\n    _getListTypeSizeInBits_and_Alignment los \n      (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) lt' = \n        Some (sz, al) /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv).\n\nLemma const2GV_typsize_mutind : \n  (forall S td c t, @const2GV__getTypeSizeInBits_Prop S td c t) /\\\n  (forall sdct, @consts2GV__getTypeSizeInBits_Prop sdct).\nProof.\nLocal Opaque zeroconst2GV.\n  (wfconst_cases (apply wf_const_mutind; \n                    unfold const2GV__getTypeSizeInBits_Prop, \n                           consts2GV__getTypeSizeInBits_Prop) Case);\n    intros; subst; simpl in *.\n\nCase \"wfconst_zero\".\n  inv_mbind.\n  split; auto.\n    eapply zeroconst2GV__getTypeSizeInBits; eauto.\n\nCase \"wfconst_int\".\n  uniq_result.\n  split; auto.\n  exists (Size.to_nat sz5). \n  exists (getIntAlignmentInfo los (Size.to_nat sz5) true).\n  erewrite int_typsize; eauto.\n\nCase \"wfconst_floatingpoint\".\n  destruct floating_point5; inv Hc2g; \n    simpl; unfold size_chunk_nat, size_chunk, bytesize_chunk; split; auto.\n    exists 32%nat. exists (getFloatAlignmentInfo los 32 true).\n    simpl. auto.\n\n    exists 64%nat. exists (getFloatAlignmentInfo los 64 true).\n    simpl. auto.\n\nCase \"wfconst_undef\".\n  inv_mbind.\n  split; auto.\n    eapply gundef__getTypeSizeInBits; eauto.\n\nCase \"wfconst_null\".\n  uniq_result.\n  split; auto.\n    exists (Size.to_nat (getPointerSizeInBits los)).\n    exists (getPointerAlignmentInfo los true).\n    unfold getPointerSizeInBits. simpl. auto.\n\nCase \"wfconst_array\". Focus.\n  fold _list_const_arr2GV in *.\n  remember (_list_const_arr2GV (los, nts) gl typ5 const_list) as R.\n  destruct R; inv Hc2g.\n  simpl_split lsdc lt.\n  simpl_split lsd lc.\n  simpl_split ls ld.\n  rewrite H1 in H4. unfold Size.to_nat in *.\n  destruct sz5; inv H4.\n    split; auto.\n    exists 8%nat. exists 1%nat. \n    split; auto.\n\n    split; auto.\n    destruct (@H0 system5 (los,nts) los nts gl) as [J1 J2]; \n      eauto using const2GV_typsize_mutind_array.\n    symmetry in HeqR.\n    assert (lc = const_list) as EQ.\n      eapply make_list_const_spec2; eauto.\n    rewrite <- EQ in HeqR.\n    assert (feasible_typ (los, nts) typ5) as Hft.\n      apply wf_array_typ_inv in H2.\n      apply wf_typ__feasible_typ in H2; auto.\n    apply J1 in HeqR; eauto using make_list_const_spec4.\n    destruct HeqR as [sz [J3 J4]].\n    apply getTypeAllocSize_inv in J3.\n    destruct J3 as [sz0 [al0 [J31 [J32 J33]]]]; subst.\n    unfold getTypeSizeInBits_and_Alignment in J32.\n    unfold getTypeSizeInBits_and_Alignment_for_namedts in J32.\n    rewrite J32.\n    rewrite <- J4.        \n    exists (RoundUpAlignment\n               (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz0) 8)) al0 * 8 *\n             S sz5)%nat. exists al0.\n    rewrite H1.\n    split; auto.\n      rewrite ZRdiv_prop8. auto.\n\nCase \"wfconst_struct\". Focus.\n  simpl_split lsdc lt.\n  simpl_split lsd lc.\n  simpl_split ls ld.\n  match goal with\n    | [ H : match ?t with \n              | ret _ => _\n              | merror => _\n            end = _ |- _ ] =>\n    remember t as R1;\n    destruct R1 as [[gv0 ts]|];\n    inv Hc2g\n  end.\n  uniq_result.\n  destruct (@H0 system5 (los,nts) los nts gl) as [J1 J2]; \n    eauto using const2GV_typsize_mutind_struct.\n\n  symmetry in HeqR2.\n  erewrite <- map_list_const_typ_spec2 in HeqR2; eauto.\n  erewrite <- map_list_const_typ_spec1 in H2; eauto.\n  apply J2 in HeqR2; eauto.\n  clear J1 J2 H.\n  destruct HeqR2 as [J5 [sz [al [J6 J7]]]]; subst.\n  rewrite H2 in H5.\n  erewrite <- typ_eq_list_typ_spec2; try solve [eauto | tauto].\n  simpl. fold _getListTypeSizeInBits_and_Alignment. rewrite J6.\n  destruct gv0; inv H5.\n    split; auto.\n      destruct sz.\n        exists 8%nat. exists 1%nat. \n        split; auto. \n\n        assert (Coqlib.ZRdiv (Z_of_nat (S sz0)) 8 > 0) as J.\n          apply Coqlib.ZRdiv_prop3; auto using Coqlib.Z_of_S_gt_O; omega.\n        apply nat_of_Z_inj_gt in J; try omega. simpl in J, J7.\n        rewrite J7 in J. contradict J. omega.\n\n    rewrite <- J7.\n    split; auto.\n      destruct sz.\n        clear - J7.\n        assert (J := @sizeGenericValue_cons_pos p gv0).\n        rewrite <- J7 in J. contradict J; simpl; omega.\n\n        eauto.\n\nCase \"wfconst_gid\".\n  inv_mbind. symmetry_ctx.\n  split; auto.\n    apply Hwfg in H0.\n    destruct H0 as [gv0 [sz [J1 [J2 [J3 _]]]]].\n    uniq_result.\n    unfold getTypeSizeInBits in J2. simpl in J2.\n    inv J2.\n    rewrite <- J3. eauto.\n\nCase \"wfconst_trunc_int\". Focus.\n  inv_mbind. \n  split; auto.\n    symmetry in HeqR0.\n    eapply mtrunc_typsize in HeqR0; eauto.\n\nCase \"wfconst_trunc_fp\". Focus.\n  inv_mbind. \n  split; auto.\n    symmetry in HeqR0.\n    eapply mtrunc_typsize in HeqR0; eauto.\n\nCase \"wfconst_zext\". Focus.\n  inv_mbind. \n  split; auto.\n    symmetry in HeqR0.\n    eapply mext_typsize in HeqR0; eauto.\n\nCase \"wfconst_sext\".  Focus.\n  inv_mbind. \n  split; auto.\n    symmetry in HeqR0.\n    eapply mext_typsize in HeqR0; eauto.\n\nCase \"wfconst_fpext\".  Focus.\n  inv_mbind.  \n  split; auto.\n    symmetry in HeqR0.\n    eapply mext_typsize in HeqR0; eauto.\n\nCase \"wfconst_ptrtoint\". Focus.\n  inv_mbind. uniq_result.\n  split; auto.\n    exists (Size.to_nat sz5).\n    exists (getIntAlignmentInfo los (Size.to_nat sz5) true).\n    erewrite int_typsize; eauto.\n\nCase \"wfconst_inttoptr\". Focus.\n  inv_mbind. uniq_result.\n  split; auto.\n    exists (Size.to_nat (getPointerSizeInBits los)).\n    exists (getPointerAlignmentInfo los true).\n    simpl. auto.\n\nCase \"wfconst_bitcast\". Focus.\n  inv_mbind. \n  unfold mbitcast in HeqR0.\n  destruct t; inv HeqR0.\n  eapply H0 in Hwfg; eauto.\n  destruct Hwfg; eauto.\n\nCase \"wfconst_gep\". Focus.\n  remember (_const2GV (los, nts) gl const_5) as R1.\n  destruct R1 as [[]|]; tinv Hc2g.\n  destruct t; tinv Hc2g.\n  symmetry in HeqR1.\n  eapply H0 in HeqR1; eauto.\n  destruct HeqR1 as [Heq [sz [al [J1 J2]]]].\n  inv J1. inv Heq.\n  rewrite H5 in Hc2g.\n  assert(\n    match gundef (los, nts) typ' with\n       | ret gv => ret (gv, typ')\n       | merror => merror\n       end = ret (gv, t') ->\n    typ' = t' /\\\n    (exists sz0 : nat,\n      exists al : nat,\n        _getTypeSizeInBits_and_Alignment los\n          (_getTypeSizeInBits_and_Alignment_for_namedts los nts true)\n          true typ' = ret (sz0, al) /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz0) 8) = sizeGenericValue gv)) as G.\n    intros W3.\n    remember (gundef (los, nts) typ') as R3;\n    destruct R3; inv W3;\n    split; try solve \n      [auto | eapply gundef__getTypeSizeInBits with (s:=system5); \n                try solve [eauto | constructor; auto]].\n  remember (GV2ptr (los, nts) (getPointerSize0 los) g) as R.\n  destruct R; auto.\n    remember (intConsts2Nats (los, nts) const_list) as R2.\n    destruct R2; auto.\n      remember (mgep (los, nts) t v l0) as R3.\n      destruct R3; auto.\n      inv Hc2g.\n      split; auto.\n        unfold getConstGEPTyp in H5.\n        destruct const_list; tinv H5.  \n        remember (getSubTypFromConstIdxs const_list t) as R4.\n        destruct R4; inv H5.\n        simpl.\n        exists (Size.to_nat (getPointerSizeInBits los)).\n        exists (getPointerAlignmentInfo los true).\n        auto.\n\nCase \"wfconst_select\". Focus.\n  remember (_const2GV (los, nts) gl const0) as R0.\n  remember (_const2GV (los, nts) gl const1) as R1.\n  remember (_const2GV (los, nts) gl const2) as R2.\n  destruct R0 as [[gv0 t0]|]; tinv Hc2g.\n  destruct R1 as [[gv1 t1]|]; tinv Hc2g.\n  destruct R2 as [[gv2 t2]|]; tinv Hc2g.\n  destruct (isGVZero (los, nts) gv0); inv Hc2g; eauto.\n\nCase \"wfconst_icmp\". Focus.\n  remember (_const2GV (los, nts) gl const1) as R1.\n  remember (_const2GV (los, nts) gl const2) as R2.\n  destruct R1 as [[gv1 t1]|]; tinv Hc2g.\n  destruct R2 as [[gv2 t2]|]; tinv Hc2g.\n  remember (micmp (los, nts) cond5 t1 gv1 gv2) as R3.\n  destruct R3; inv Hc2g; eauto.\n  split; auto.\n    symmetry in HeqR3.\n    eapply micmp_typsize in HeqR3; try solve [eauto | constructor; auto].\n\nCase \"wfconst_fcmp\". Focus.\n  remember (_const2GV (los, nts) gl const1) as R1.\n  remember (_const2GV (los, nts) gl const2) as R2.\n  destruct R1 as [[gv1 t1]|]; tinv Hc2g.\n  destruct_typ t1; tinv Hc2g.\n  destruct R2 as [[gv2 t2]|]; tinv Hc2g.\n  remember (mfcmp (los, nts) fcond5 f gv1 gv2) as R3.\n  destruct R3; inv Hc2g; eauto.\n  split; auto.\n    symmetry in HeqR3.\n    eapply mfcmp_typsize in HeqR3; try solve [eauto | constructor; auto]. \n\nCase \"wfconst_extractvalue\". Focus.\n  remember (_const2GV (los, nts) gl const_5) as R1.\n  destruct R1 as [[gv1 t1]|]; tinv Hc2g.\n  remember (getSubTypFromConstIdxs const_list t1) as R2.\n  destruct R2 as [t2|]; tinv Hc2g.\n  remember (extractGenericValue (los, nts) t1 gv1 const_list) as R3.\n  destruct R3 as [gv2|]; inv Hc2g.\n  symmetry in HeqR1.\n  apply H0 in HeqR1; auto.\n  destruct HeqR1 as [Heq [sz [al [J1 J2]]]]; subst.\n  destruct H6 as [idxs [o [J3 J4]]].\n  symmetry in J3.\n  eapply getSubTypFromConstIdxs__mgetoffset in J3; eauto.\n  subst.\n  split; eauto.\n    eapply extractGenericValue_typsize; try solve [eauto | constructor; auto].\n\nCase \"wfconst_insertvalue\". Focus.\n  clear H1.\n  remember (_const2GV (los, nts) gl const_5) as R1.\n  destruct R1 as [[gv1 t1]|]; tinv Hc2g.\n  remember (_const2GV (los, nts) gl const') as R2.\n  destruct R2 as [[gv2 t2]|]; tinv Hc2g.\n  remember (insertGenericValue (los, nts) t1 gv1 const_list t2 gv2) as R3.\n  destruct R3 as [gv3|]; inv Hc2g.\n  symmetry in HeqR1.\n  apply H0 in HeqR1; auto.\n  destruct HeqR1 as [Heq [sz [al [J1 J2]]]]; subst.\n  rewrite J1. \n  symmetry in HeqR2.\n  apply H2 in HeqR2; auto.\n  destruct HeqR2 as [Heq [sz2 [al2 [J3 J4]]]]; subst.\n  split; auto.\n    exists sz. exists al.\n    split; auto.\n      eapply insertGenericValue_typsize in HeqR3; \n        try solve [eauto | constructor; auto].\n      rewrite <- HeqR3. auto.\n\nCase \"wfconst_bop\". Focus.\n  remember (_const2GV (los, nts) gl const1) as R1.\n  remember (_const2GV (los, nts) gl const2) as R2.\n  destruct R1 as [[gv1 t1]|]; tinv Hc2g.\n  destruct_typ t1; tinv Hc2g.\n  destruct R2 as [[gv2 t2]|]; tinv Hc2g.\n  remember (mbop (los, nts) bop5 s0 gv1 gv2) as R3.\n  destruct R3; inv Hc2g.\n  symmetry in HeqR1.\n  apply H0 in HeqR1; auto.\n  destruct HeqR1 as [Heq _]. inv Heq.\n  split; auto.\n    symmetry in HeqR3.\n    eapply mbop_typsize in HeqR3; eauto.\n\n\nCase \"wfconst_fbop\". Focus.\n  remember (_const2GV (los, nts) gl const1) as R1.\n  remember (_const2GV (los, nts) gl const2) as R2.\n  destruct R1 as [[gv1 t1]|]; tinv Hc2g.\n  destruct_typ t1; tinv Hc2g.\n  destruct R2 as [[gv2 t2]|]; tinv Hc2g.\n  remember (mfbop (los, nts) fbop5 f gv1 gv2) as R3.\n  destruct R3; inv Hc2g.\n  symmetry in HeqR1.\n  apply H0 in HeqR1; auto.\n  destruct HeqR1 as [Heq _]. inv Heq.\n  split; auto.\n    symmetry in HeqR3.\n    eapply mfbop_typsize in HeqR3; eauto.\n\nCase \"wfconst_nil\".\n  intros; subst.\n  split; intros; subst; uniq_result.\n    apply feasible_typ_inv' in Hft.\n    destruct Hft as [sz [al [H H']]].\n    unfold getTypeAllocSize. unfold getTypeStoreSize. unfold getTypeSizeInBits.\n    unfold getABITypeAlignment. unfold getAlignment.\n    rewrite H. simpl. eauto.\n\n    simpl. split; eauto.    \n\nCase \"wfconst_cons\".\n  simpl_split lsdc lt. simpl.\n  simpl_split lsd lc. simpl.\n  simpl_split ls ld. simpl.\n  intros S TD los nts gl EQ Hwfl; subst.\n  split.\n    intros gv t Hft Hin Hc2g.\n    remember (_list_const_arr2GV (@pair (list layout) (list namedt) los nts) gl t lc) as R.\n    destruct R; try solve [inv Hc2g].\n    remember (_const2GV (@pair (list layout) (list namedt) los nts) gl const_) as R'.\n    destruct R' as [[gv0 t0]|]; try solve [inv Hc2g].\n    destruct (typ_dec t t0); subst; try solve [inv Hc2g].\n    remember (getTypeAllocSize (@pair (list layout) (list namedt) los nts) t0) as R1.\n    destruct R1; inv Hc2g.\n    assert (typ5 = t0) as EQ. eapply Hin; eauto.\n    subst.\n    exists s. split; auto.\n    apply wf_list_targetdata_typ_cons_inv in Hwfl.\n    destruct Hwfl as [J1 [J2 [J3 J4]]]; subst.\n    symmetry in HeqR'.\n    apply H0 in HeqR'; auto.\n    destruct HeqR' as [Heq [sz [al [J5 J6]]]]; subst.\n    eapply H2 in J1; eauto. destruct J1 as [J1 _]. clear H0 H2.\n    symmetry in HeqR2.\n    apply J1 in HeqR2; auto.\n    destruct HeqR2 as [sz0 [J7 J8]].\n    simpl_env.\n    rewrite sizeGenericValue__app.\n    rewrite sizeGenericValue__app.\n    rewrite sizeGenericValue__uninits.\n    rewrite <- J8. rewrite <- J6.\n    rewrite J7 in HeqR3. inv HeqR3.\n    rewrite plus_assoc.\n    erewrite getTypeAllocSize_roundup; eauto.\n    ring.\n\n    intros gv lt' Hc2g.\n    remember (_list_const_struct2GV (@pair (list layout) (list namedt) los nts) gl lc) as R.\n    destruct R as [[gv1 ts1]|]; try solve [inv Hc2g].\n    remember (_const2GV (@pair (list layout) (list namedt) los nts) gl const_) as R'.\n    destruct R' as [[gv0 t0]|]; try solve [inv Hc2g].\n    remember (getTypeAllocSize (@pair (list layout) (list namedt) los nts) t0) as R1.\n    destruct R1; inv Hc2g.\n    apply wf_list_targetdata_typ_cons_inv in Hwfl.\n    destruct Hwfl as [J1' [J2' [J3 J4]]]; subst.\n    symmetry in HeqR'.\n    apply H0 in HeqR'; auto.\n    destruct HeqR' as [Heq [sz [al [J5 J6]]]]; subst.\n    eapply H2 in J1'; eauto. destruct J1' as [_ J1']. clear H0 H2.\n    symmetry in HeqR2.\n    apply J1' in HeqR2; auto.\n    destruct HeqR2 as [Heq [sz0 [al0 [J7 J8]]]]; subst.\n    split; auto.\n    rewrite sizeGenericValue__app.\n    rewrite sizeGenericValue__app.\n    rewrite sizeGenericValue__uninits.\n    rewrite <- J8. rewrite <- J6. simpl. rewrite J7. rewrite J5.\n    rewrite plus_assoc.\n    assert (feasible_typ (@pair (list layout) (list namedt) los nts) t0) as Hft.\n      apply wf_const__wf_typ in H.\n      apply wf_typ__feasible_typ in H; auto.\n    erewrite getTypeAllocSize_roundup; eauto.\n    exists (sz0 +\n             RoundUpAlignment\n               (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8)) al * 8)%nat.\n    exists (if le_lt_dec al al0 then al0 else al).\n    split; auto.\n      eapply getTypeAllocSize_inv' in J5; eauto. subst.\n      rewrite plus_comm with (m:=nat_of_Z (ZRdiv (Z_of_nat sz0) 8)).\n      apply ZRdiv_prop9.\nTransparent zeroconst2GV.\nQed.\n\nLemma const2GV__getTypeSizeInBits_aux : forall S los nts c t gl gv t',\n  wf_const S (los, nts) c t ->\n  _const2GV (los, nts) gl c = Some (gv, t') ->\n  wf_global (los, nts) S gl ->\n  t = t' /\\\n  exists sz, exists al,\n    _getTypeSizeInBits_and_Alignment los \n      (getTypeSizeInBits_and_Alignment_for_namedts (los, nts) true) true t = \n         Some (sz, al) /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv.\nProof.\n  intros. inv H0.\n  destruct const2GV_typsize_mutind. \n  eapply H0; eauto.\nQed.\n\nLemma cundef_gv__getTypeSizeInBits : forall S los nts gv t sz al,\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los \n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t = \n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = \n    sizeGenericValue (cundef_gv gv t).\nProof.\n  intros.\n  destruct_typ t; simpl in *; auto.\n    inv H0.\n    erewrite int_typsize; eauto.\n\n    destruct f; tinv H; inv H0; auto.\n\n    inv H0. auto.\nQed.\n\nLemma cgv2gv__getTypeSizeInBits : forall S los nts gv t sz al,\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los \n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t = \n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = \n    sizeGenericValue (cgv2gv gv t).\nProof.\n  intros.\n  destruct gv; auto.\nQed.\n\nLemma const2GV__getTypeSizeInBits : forall S los nts c t gl gv\n  (H1: wf_const S (los, nts) c t)\n  (H2: const2GV (los, nts) gl c = Some gv),\n  wf_global (los, nts) S gl ->\n  exists sz, \n    getTypeSizeInBits (los, nts) t = Some sz /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv.\nProof.\n  intros.\n  unfold const2GV in H2.\n  remember (_const2GV (los, nts) gl c) as R.\n  destruct R as [[]|]; inv H2.\n  symmetry in HeqR.\n  unfold getTypeSizeInBits, getTypeSizeInBits_and_Alignment.\n  eapply const2GV__getTypeSizeInBits_aux in HeqR; eauto.\n  destruct HeqR as [Heq [sz [al [J1 J2]]]]; subst.\n  exists sz. \n  rewrite J1.\n  split; auto.\nQed.\n\nLemma fit_gv__getTypeSizeInBits : forall TD gv s t gv'\n  (Hwft : wf_typ s TD t) \n  (HeqR : ret gv' = fit_gv TD t gv),\n  exists sz, \n    getTypeSizeInBits TD t = Some sz /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv'.\nProof.\n  intros.\n  unfold fit_gv in HeqR.\n  assert (J:=Hwft).\n  eapply wf_typ__getTypeSizeInBits_and_Alignment in J; eauto.\n  destruct J as [sz [al [J1 [J2 J3]]]].\n  unfold getTypeSizeInBits in *.\n  exists sz.\n  rewrite J1 in HeqR. rewrite J1.\n  split; auto.\n    destruct_if.\n      symmetry in HeqR0.\n      apply andb_true_iff in HeqR0.\n      destruct HeqR0 as [HeqR0 _].\n      apply neq_inv in HeqR0. auto.\n\n      destruct TD.\n      eapply gundef__getTypeSizeInBits in Hwft; eauto.\n      destruct Hwft as [sz0 [al0 [J4 J5]]].\n      unfold getTypeSizeInBits_and_Alignment,\n             getTypeSizeInBits_and_Alignment_for_namedts in J1.\n      rewrite J1 in J4.\n      inv J4. auto.\nQed.\n\nLemma mload__getTypeSizeInBits : forall t s TD gv a ptr M,\n  mload TD M ptr t a = Some gv ->\n  wf_typ s TD t ->\n  exists sz, \n    getTypeSizeInBits TD t = Some sz /\\\n    Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv.\nProof.\n  intros.\n  apply mload_inv in H.\n  destruct H as [b [ofs [m [mc [J1 [J2 J3]]]]]]; subst.\n  unfold getTypeSizeInBits, getTypeSizeInBits_and_Alignment.\n  erewrite <- mload_aux__sizeGenericValue; eauto.\n  destruct TD.\n  eapply flatten_typ__getTypeSizeInBits in J2; eauto.\n  destruct J2 as [sz [al [J21 J22]]].\n  rewrite J21. eauto.\nQed.\n \n(********************************************)\n(** * matching chunks *)\n\nLemma mload__matches_chunks : forall t TD gv a ptr M,\n  mload TD M ptr t a = Some gv ->\n  gv_chunks_match_typ TD gv t.\nProof.\n  intros.\n  apply mload_inv in H.\n  destruct H as [b [ofs [m [mc [J1 [J2 J3]]]]]]; subst.\n  unfold gv_chunks_match_typ, vm_matches_typ, gv_has_chunk.\n  fill_ctxhole.\n  generalize dependent (Int.signed 31 ofs).\n  generalize dependent gv.\n  clear.\n  induction mc; intros; inv J3; auto.\n    inv_mbind. symmetry_ctx.\n    apply IHmc in HeqR0.\n    constructor; eauto using Mem.load_chunk.\nQed.\n\nLemma gundef__matches_chunks : forall td gv t (HeqR: ret gv = gundef td t),\n  gv_chunks_match_typ td gv t.\nProof.\n  unfold gundef. intros.\n  inv_mbind. symmetry_ctx.\n  unfold gv_chunks_match_typ, gv_has_chunk.\n  fill_ctxhole.\n  clear. unfold vm_matches_typ.\n  induction l0; simpl; auto.\n    constructor; simpl; auto.\nQed.\n\nLemma fit_gv__matches_chunks : forall TD gv t gv'\n  (HeqR : ret gv' = fit_gv TD t gv),\n  gv_chunks_match_typ TD gv' t.\nProof.\n  intros.\n  unfold fit_gv in HeqR.\n  inv_mbind.\n  destruct_if.\n    symmetry in HeqR.\n    apply andb_true_iff in HeqR.\n    destruct HeqR as [_ HeqR].\n    apply gv_chunks_match_typb__gv_chunks_match_typ; auto.\n\n    apply gundef__matches_chunks; auto.\nQed.\n\nLemma flatten_array_typ_eq: forall TD sz t,\n  match sz with\n  | O => flatten_typ TD (typ_array sz t) = Some (uninitMCs 1)\n  | _ =>\n    match flatten_typ TD t with\n    | Some mc0 =>\n      match getTypeAllocSize TD t with\n      | Some asz =>\n         flatten_typ TD (typ_array sz t) =\n           Some (repeatMC (mc0++uninitMCs (Size.to_nat asz - sizeMC mc0))\n                  (Size.to_nat sz))\n      | _ => flatten_typ TD (typ_array sz t) = None\n      end\n    | _ => flatten_typ TD (typ_array sz t) = None\n    end\n  end.\nProof.\n  intros. destruct TD.\n  destruct sz0; simpl; auto.\n  destruct (flatten_typ_aux (l0, n) (flatten_typ_for_namedts (l0, n) l0 n) t);\n    auto.\n  destruct (getTypeAllocSize (l0, n) t); auto.\nQed.\n\nLemma flatten_struct_typ_eq: forall TD ts,\n  match flatten_typs TD ts with\n  | Some nil => flatten_typ TD (typ_struct ts) = Some (uninitMCs 1)\n  | Some gv => flatten_typ TD (typ_struct ts) = Some gv\n  | _ => flatten_typ TD (typ_struct ts) = None\n  end.\nProof.\n  intros. destruct TD. simpl.\n  fold flatten_typs_aux.\n  destruct (flatten_typs_aux (l0, n) (flatten_typ_for_namedts (l0, n) l0 n) ts)\n    as [[]|]; auto.\nQed.\n\nLemma flatten_struct__eq__namedt: forall los nts id5 lt5 mc1 mc2 \n  (Huniq: uniq nts),\n  lookupAL _ nts id5 = Some lt5 ->\n  flatten_typ (los,nts) (typ_struct lt5) = Some mc1 ->\n  flatten_typ (los,nts) (typ_namedt id5) = Some mc2 ->\n  mc1 = mc2.\nProof.\n  simpl. intros.\n  inv_mbind. symmetry_ctx.\n  apply lookupAL_middle_inv in H.\n  destruct H as [l1 [l2 H]]; subst.\n  eapply flatten_typ_for_namedts_spec1 in HeqR; eauto.\n  simpl_env in *.\n  apply flatten_typ_aux_weakening with (nm2:=l1 ++ [(id5, lt5)]) in HeqR; \n    simpl_env; auto.\n  simpl in HeqR. inv_mbind. symmetry_ctx. simpl_env in *.\n  uniq_result. rewrite H0 in H2. congruence.\nQed.\n\nDefinition zeroconst2GV_aux__matches_chunks_prop S TD t :=\n  wf_styp S TD t ->\n  forall los nts acc gv (Heq: TD = (los, nts)) nts' \n  (Hsub:exists nts0, nts'=nts0++nts) (Huniq: uniq nts')\n  (Hnc: forall id5 gv5 lt5, \n          lookupAL _ nts id5 = Some lt5 ->\n          lookupAL _ acc id5 = Some (Some gv5) ->\n          gv_chunks_match_typ (los,nts') gv5 (typ_struct lt5))\n  (Hprop: exists mc, flatten_typ (los, nts') t = Some mc) \n  (Hz: zeroconst2GV_aux (los,nts') acc t = Some gv),\n  gv_chunks_match_typ (los,nts') gv t.\n\nDefinition zeroconsts2GV_aux__matches_chunks_prop sdt :=\n  wf_styp_list sdt ->\n  let 'lsdt := sdt in\n  let '(lsd, lt) := split lsdt in\n  forall S TD los nts acc gv (Heq: TD = (los, nts)) nts' \n  (Hsub:exists nts0, nts'=nts0++nts) (Huniq: uniq nts')\n  (Hnc: forall id5 gv5 lt5, \n          lookupAL _ nts id5 = Some lt5 ->\n          lookupAL _ acc id5 = Some (Some gv5) ->\n          gv_chunks_match_typ (los,nts') gv5 (typ_struct lt5))\n  (Hz: zeroconsts2GV_aux (los,nts') acc lt = Some gv)\n  (Hprop: exists mc, flatten_typs (los, nts') lt = Some mc)\n  (Heq': eq_system_targetdata S TD lsd),\n  gv_chunks_match_list_typ (los,nts') gv lt.\n\nLemma zeroconst2GV_aux_matches_chunks_mutrec :\n  (forall S TD t, zeroconst2GV_aux__matches_chunks_prop S TD t) /\\\n  (forall sdt, zeroconsts2GV_aux__matches_chunks_prop sdt).\nProof.\n  (wfstyp_cases (apply wf_styp_mutind; \n    unfold zeroconst2GV_aux__matches_chunks_prop, \n           zeroconsts2GV_aux__matches_chunks_prop) Case);\n    intros; simpl in *; subst; uniq_result; try solve [\n      congruence | eauto |\n      unfold gv_chunks_match_typ, vm_matches_typ; simpl; unfold val2GV;\n      constructor; try solve [\n        auto |\n        split; try solve [\n          auto |\n(*          apply Floats.Float.zero_singleoffloat__eq__zero | *)\n          split; simpl; try solve [auto | apply Int.Z_mod_modulus_range]\n        ]\n      ]\n    ].\n\nCase \"wf_styp_int\".\n  constructor; auto; unfold Size.to_nat, vm_matches_typ; simpl.\n  split; auto; split; auto; split; solve [omega | apply Z.gt_lt; apply Int.modulus_pos].\n\nCase \"wf_styp_function\".\n  constructor; auto. constructor; auto. simpl. split; auto.\n  split; [omega| apply Z.gt_lt; apply Int.modulus_pos].\n\nCase \"wf_styp_structure\".\n  simpl_split lsd lt.\n  assert (lt = typ_list) as EQ1. \n    eapply make_list_typ_spec2; eauto.\n  subst.\n  assert (eq_system_targetdata system5 (los, nts) lsd) as EQ2.\n    eapply wf_styp__feasible_typ_aux_mutrec_struct; eauto.\n  subst.\n  inv_mbind. symmetry_ctx.\n  eapply_clear H1 in HeqR0; \n    [|solve [eauto | fold flatten_typs_aux in *; destruct Hprop as [mc Hprop2]; inv_mbind; eauto]].\n  unfold gv_chunks_match_typ. \n  unfold gv_chunks_match_list_typ in HeqR0. \n  unfold AssocList, namedt, id, layouts in *. simpl in *.\n  fold flatten_typs_aux in *.\n  inv_mbind. \n  destruct l0; inv HeqR0; uniq_result; simpl in *. \n    apply uninits_match_uninitMCs.\n    constructor; auto.\n\nCase \"wf_styp_array\".\n  assert (J:=@flatten_array_typ_eq (los,nts') sz5 typ5).\n  destruct sz5 as [|s].\n    uniq_result. unfold gv_chunks_match_typ. simpl. \n    apply uninits_match_uninitMCs.\n\n    inv_mbind. symmetry_ctx.\n    eapply_clear H0 in HeqR; \n      try solve [eauto | destruct Hprop as [mc Hprop2]; inv_mbind; eauto].\n    unfold gv_chunks_match_typ in *.\n    inv_mbind. fill_ctxhole. simpl.\n    assert (Forall2 vm_matches_typ\n      (g ++ uninits (Size.to_nat s0 - sizeGenericValue g))\n      (l0 ++ uninitMCs (Size.to_nat s0 - sizeMC l0))) as Hsim.\n      apply match_chunks_app; auto.\n        erewrite match_chunks_eq_size; eauto.\n        apply uninits_match_uninitMCs.\n    apply match_chunks_app; auto.\n    apply match_chunks_repeat; auto.\n\nCase \"wf_styp_pointer\".\n  constructor; auto. constructor; auto. constructor; auto. simpl.\n  split; [omega| apply Z.gt_lt; apply Int.modulus_pos].\n\nCase \"wf_styp_namedt\".\n  inv_mbind. \n  remember (lookupAL _ nts id5) as R.\n  destruct R as [lt|]; try congruence. symmetry_ctx.\n  assert (G:=HeqR0).\n  eapply Hnc in G; eauto.\n  unfold gv_chunks_match_typ, null.\n  unfold gv_chunks_match_typ in G.\n  inv_mbind. \n  unfold flatten_typ in *. simpl. fill_ctxhole.\n  inv_mbind. symmetry_ctx.\n  destruct Hsub as [nts0 Hsub]; subst.\n  apply lookupAL_weaken with (nm2:=nts0) in HeqR0; auto.\n  eapply flatten_struct__eq__namedt with (mc1:=l0)(mc2:=x) in HeqR0; \n    subst; simpl; eauto.\n    unfold namedt, id, layouts in *.\n    rewrite HeqR2. auto.\n\nCase \"wf_styp_nil\".\n  intros. uniq_result. \n  unfold gv_chunks_match_list_typ. simpl. auto.\n \nCase \"wf_styp_cons\".\n  simpl_split lsd lt. simpl. \n  intros. subst.\n  apply eq_system_targetdata_cons_inv in Heq'. \n  destruct Heq' as [H4 [EQ1 EQ2]]; subst.\n  inv_mbind. symmetry_ctx.\n  eapply_clear H0 in HeqR1;\n    try solve [eauto | destruct Hprop as [mc Hprop2]; inv_mbind; eauto].\n  eapply_clear H2 in HeqR0;\n    try solve [eauto | destruct Hprop as [mc Hprop2]; inv_mbind; eauto].\n  clear Hprop. \n  unfold gv_chunks_match_list_typ in *.\n  unfold gv_chunks_match_typ in *.\n  inv_mbind. symmetry_ctx.\n  simpl in *. unfold AssocList, namedt, id, layouts in *. \n  repeat fill_ctxhole. \n  repeat (apply match_chunks_app; auto).\n    erewrite match_chunks_eq_size; eauto.\n    apply uninits_match_uninitMCs.\nQed.\n\nLemma noncycled__matches_chunks: forall S los nts\n  (H: noncycled S los nts) (Huniq: uniq nts)\n  id5 lt nts2 nts1 (EQ: nts = nts1 ++ (id5,lt) :: nts2) nts' (Huniq': uniq nts') \n  (Hsub: exists nts0, nts'=nts0++nts)\n  (Hnc: forall id5 lt5, \n          lookupAL _ nts id5 = Some lt5 ->\n          exists mc, flatten_typ (los, nts') (typ_struct lt5) = Some mc) gv\n  (Hz: zeroconst2GV_aux (los, nts')\n         (zeroconst2GV_for_namedts (los, nts') los nts2) (typ_struct lt) = \n           Some gv),\n  gv_chunks_match_typ (los, nts') gv (typ_struct lt).\nProof.\nLocal Opaque flatten_typs flatten_typ.\n  induction 1; simpl; intros; subst.\n    symmetry in EQ.    \n    apply app_eq_nil in EQ.\n    destruct EQ as [_ EQ].\n    congruence.\n\n    inv Huniq.\n    destruct nts1 as [|[]]; inv EQ.\n      destruct zeroconst2GV_aux_matches_chunks_mutrec as [J _].\n      eapply J in H0; eauto.\n      assert (exists mc, flatten_typ (layouts5, nts') (typ_struct lt) = Some mc) \n        as Hty.\n        eapply Hnc with (id5:=id0); eauto.\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id0 id0); \n          try congruence; eauto.\n      assert (exists nts0 : list namedt, nts' = nts0 ++ nts2) as G.\n        destruct Hsub as [nts0 Hsub]; subst. \n        exists (nts0 ++ [(id0, lt)]). simpl_env. auto.\n      eapply H0 in Hty; eauto.  \n      intros id5 gv5 lt5 H1 H2.\n      apply lookupAL_middle_inv in H1.\n      destruct H1 as [l1 [l2 HeqR]].\n      assert (J':=HeqR). subst.\n      eapply IHnoncycled with (nts':=nts') in J'; eauto.\n        intros.\n        eapply Hnc with (id6:=id1); eauto.\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id1 id0); \n          subst; auto.\n          apply notin_lookupAL_None in H5. congruence.\n       \n        eapply zeroconst2GV_for_namedts_spec1 in H2; eauto.\n            \n      assert (nts1 ++ (id0, lt) :: nts2 = nts1 ++ (id0, lt) :: nts2) as EQ. auto.\n      eapply IHnoncycled with (nts':=nts') in EQ; eauto.\n        destruct Hsub as [nts0 Hsub]; subst. \n        exists (nts0 ++ [(i0, l0)]). simpl_env. auto.\n \n        intros.\n        apply Hnc with (id5:=id5)(lt5:=lt5).\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) id5 i0); \n          subst; auto.\n          apply notin_lookupAL_None in H5. congruence.\nTransparent flatten_typs flatten_typ.\nQed.\n\nLemma zeroconst2GV__matches_chunks : forall t s td gv\n  (Hz: zeroconst2GV td t = Some gv)\n  (Ht: wf_typ s td t),\n  gv_chunks_match_typ td gv t.\nProof. \n  intros. destruct td as [los nts].\n  assert (G:=Ht).\n  apply flatten_typ_total in G; auto.\n  unfold zeroconst2GV in *. inv Ht.\n  destruct zeroconst2GV_aux_matches_chunks_mutrec as [J' _].\n  assert (exists nts0 : list namedt, nts = nts0 ++ nts) as G'.\n    eexists nil; auto.\n  eapply J'; eauto.\n  intros id5 gv5 lt5 J5 J6.\n  apply lookupAL_middle_inv in J5.\n  destruct J5 as [l1 [l2 HeqR]]. subst.\n  eapply noncycled__matches_chunks\n    with (nts':=l1 ++ (id5, lt5) :: l2) in H1; eauto.\n    intros id0 lt0 H.\n    apply lookupAL_middle_inv in H.\n    destruct H as [l3 [l4 H]].\n    rewrite H in *. \n    symmetry in H.\n    rewrite_env ((l3 ++ [(id0, lt0)]) ++ l4).\n    eapply flatten_typ_for_namedts_total with (nts1:=l3)(nts2:=l4)\n      (nts':=l3 ++ (id0, lt0) :: l4) in H1; eauto.\n      destruct H1 as [gvs H1]. \n      simpl_env in H5.\n      apply flatten_typ_aux_weakening with (nm2:=l3 ++ [(id0, lt0)]) in H1; \n        simpl_env; auto.\n        simpl. simpl in H1.\n        exists gvs.\n        inv_mbind. symmetry_ctx. simpl_env. simpl_env in HeqR.\n        unfold AssocList, namedts, namedt, id, layouts in *. \n        rewrite HeqR. auto.\n             \n      intros id1 lt1 H10.\n      apply lookupAL_middle_inv in H10.\n      destruct H10 as [l5 [l6 H10]]. subst.\n      rewrite H10 in *.\n      eapply noncycled__getTypeSizeInBits_and_Alignment_for_namedts with\n        (nts1:=l5)(nts2:=l6)(los:=los)(S:=s)in H1; eauto.\n      destruct H1 as [sz [al [H1 ?]]].\n      exists sz. exists al. \n      unfold getTypeSizeInBits_and_Alignment.\n      unfold getTypeSizeInBits_and_Alignment_for_namedts in H1.\n      unfold getTypeSizeInBits_and_Alignment_for_namedts.\n      simpl_env in H5.\n      apply getTypeSizeInBits_and_Alignment_aux_weakening with \n        (nm2:=l5 ++ [(id1, lt1)]) in H1; simpl_env; simpl_env in H1; auto.\n\n    eapply zeroconst2GV_for_namedts_spec1 in J6; eauto.\nQed.\n\nLemma mtrunc_matches_chunks : forall S td t1 t2 gv1 gv2 top\n  (Hzty: wf_typ S td t2) (H1: mtrunc td top t1 t2 gv1 = Some gv2),\n  gv_chunks_match_typ td gv2 t2.\nProof.  \n  intros. destruct td.\n  unfold mtrunc, GV2val in H1.\n  destruct gv1; tinv H1.\n    eapply gundef__matches_chunks; eauto.\n  destruct p.\n  destruct gv1; \n    try solve [inversion H1; eapply gundef__matches_chunks; eauto].\n  destruct v; try solve [eapply gundef__matches_chunks; eauto].\n    destruct_typ t1; try solve [eapply gundef__matches_chunks; eauto].\n    destruct_typ t2; try solve [eapply gundef__matches_chunks; eauto].\n      inv H1. unfold gv_chunks_match_typ, vm_matches_typ. simpl.\n      constructor; auto.\n        split; auto.\n        destruct (le_lt_dec wz (s1-1)); simpl; auto.\n        split; try solve [auto | apply Int.Z_mod_modulus_range].       \n\n    destruct_typ t1; try solve [eapply gundef__matches_chunks; eauto].\n    destruct_typ t2; try solve [eapply gundef__matches_chunks; eauto].\n    remember (floating_point_order f1 f0) as R.\n    destruct R; tinv H1; try (by eapply gundef__matches_chunks; eauto).\n    destruct f0; inv H1; try (by eapply gundef__matches_chunks; eauto).\n    destruct f1; inv HeqR.\n      unfold gv_chunks_match_typ, vm_matches_typ; simpl.\n      constructor; auto.\n        split; auto.\n        simpl; auto.\n    destruct t1; destruct t2; eapply gundef__matches_chunks; eauto.\nQed.\n\nLemma mext_matches_chunks : forall S td eop t1 t2 gv1 gv2\n  (Hzty: wf_typ S td t2) (H1: mext td eop t1 t2 gv1 = Some gv2),\n  gv_chunks_match_typ td gv2 t2.\nProof.\n  {\n    ii. unfold mext in *.\n    Local Opaque Val.zero_ext' Val.sign_ext'.\n    des_ifs; try (by eapply gundef__matches_chunks; eauto).\n    - unfold val2GV, GV2val in *. des_ifs.\n      unfold gv_chunks_match_typ. unfold flatten_typ. des_ifs.\n      ss. clarify.\n      econs; eauto.\n      exploit Val.zero_ext'_has_chunk; eauto.\n      instantiate (1:= (sz0 - 1)%nat).\n      instantiate (1:= (Vint wz i0)%nat).\n      i. unfold Val.has_chunk in *. des_ifs.\n    - unfold val2GV, GV2val in *. des_ifs.\n      unfold gv_chunks_match_typ. unfold flatten_typ. des_ifs.\n      ss. clarify.\n      econs; eauto.\n      exploit Val.sign_ext'_has_chunk; eauto.\n      instantiate (1:= (sz0 - 1)%nat).\n      instantiate (1:= (Vint wz i0)%nat).\n      i. unfold Val.has_chunk in *. des_ifs.\n    - unfold val2GV, GV2val in *. des_ifs.\n      unfold gv_chunks_match_typ. unfold flatten_typ. des_ifs.\n      unfold floating_point_order in *. des_ifs.\n      compute in Heq0. clarify.\n      econs; eauto.\n      ss.\n  }\n(*   intros. destruct td. unfold mext, GV2val in H1. *)\n(*   destruct_typ t1; tinv H1. *)\n(*     destruct_typ t2; tinv H1. *)\n(*     destruct gv1;  *)\n(*       try solve [inversion H1 | eapply gundef__matches_chunks; eauto]. *)\n(*     destruct p. *)\n(*     destruct gv1;  *)\n(*       try solve [inversion H1 | eapply gundef__matches_chunks; eauto]. *)\n(*     destruct v; try solve [eapply gundef__matches_chunks; eauto]. *)\n(* Local Opaque Val.zero_ext' Val.sign_ext'. *)\n(*     destruct eop; inv H1; *)\n(*       unfold gv_chunks_match_typ, vm_matches_typ; constructor; try solve [ *)\n(*         auto | *)\n(*         split; try solve [auto | simpl; apply Val.zero_ext'_has_chunk *)\n(*                                | simpl; apply Val.sign_ext'_has_chunk] *)\n(*       ]. *)\n(* Transparent Val.zero_ext' Val.sign_ext'. *)\n\n(*     destruct_typ t2; tinv H1. *)\n(*     destruct (floating_point_order f f0); tinv H1. *)\n(*     destruct gv1;  *)\n(*       try solve [inversion H1 | eapply gundef__matches_chunks; eauto]. *)\n(*     destruct p. *)\n(*     destruct gv1;  *)\n(*       try solve [inversion H1 | eapply gundef__matches_chunks; eauto]. *)\n(*     destruct v; try solve [eapply gundef__matches_chunks; eauto]. *)\n(*     destruct eop; inv H1. *)\n(*     destruct f0; inv H0; simpl; *)\n(*       unfold gv_chunks_match_typ, vm_matches_typ; simpl; constructor;  *)\n(*         simpl; auto. *)\nQed.\n\nLemma extractGenericValue_matches_chunks : forall S td t1 gv1 const_list typ' gv\n  (e0 : getSubTypFromConstIdxs const_list t1 = ret typ')\n  (Hzty: wf_typ S td typ')\n  (HeqR3 : ret gv = extractGenericValue td t1 gv1 const_list)\n  (J2 : gv_chunks_match_typ td gv1 t1),\n  gv_chunks_match_typ td gv typ'.\nProof.\n  intros.\n  unfold extractGenericValue in HeqR3.\n  remember (intConsts2Nats td const_list) as R1.\n  destruct R1 as [idxs|]; tinv HeqR3.\n  remember (mgetoffset td t1 idxs) as R2.\n  destruct R2 as [[o t']|]; tinv HeqR3.\n  remember (mget td gv1 o t') as R4.\n  eapply getSubTypFromConstIdxs__mgetoffset in e0; eauto.\n  destruct R4 as [gv'|]; inv HeqR3.\n    eapply mget_matches_chunks; eauto.\n    eapply gundef__matches_chunks; eauto.\nQed.\n\nLemma insertGenericValue_matches_chunks : forall S td t1 gv1 const_list gv t2 gv2\n  (Hzty: wf_typ S td t1)\n  (J1 : gv_chunks_match_typ td gv1 t1)\n  (J3 : gv_chunks_match_typ td gv2 t2)\n  (HeqR3 : ret gv = insertGenericValue td t1 gv1 const_list t2 gv2),\n  gv_chunks_match_typ td gv t1.\nProof.\n  intros.\n  unfold insertGenericValue in HeqR3.\n  remember (intConsts2Nats td const_list) as R1.\n  destruct R1 as [idxs|]; tinv HeqR3.\n  remember (mgetoffset td t1 idxs) as R2.\n  destruct R2 as [[o t']|]; tinv HeqR3.\n  remember (mset td gv1 o t2 gv2) as R4.\n  destruct R4 as [gv'|]; inv HeqR3.\n    eapply mset_matches_chunks in HeqR4; eauto. \n\n    eapply gundef__matches_chunks; eauto.\nQed.    \n\nLemma mbop_matches_chunks_helper : forall TD s gv,\n  gundef TD (typ_int s) = ret gv ->\n  gv_chunks_match_typ TD gv (typ_int s).\nProof.\n  intros. eapply gundef__matches_chunks; eauto.\nQed.\n\nLemma mbop_matches_chunks : forall td bop5 s gv1 gv2 gv\n  (H1: mbop td bop5 s gv1 gv2 = Some gv),\n  gv_chunks_match_typ td gv (typ_int s).\nProof.\n  intros.\n  unfold mbop, GV2val in H1.\n  destruct gv1; \n    try solve [inversion H1 | eapply mbop_matches_chunks_helper; eauto].\n  destruct p.\n  destruct gv1; \n    try solve [inversion H1 | eapply mbop_matches_chunks_helper; eauto].\n  destruct v; \n    try solve [inversion H1 | eapply mbop_matches_chunks_helper; eauto].\n  destruct gv2; \n    try solve [inversion H1 | eapply mbop_matches_chunks_helper; eauto].\n  destruct p.\n  destruct gv2; \n    try solve [inversion H1 | eapply mbop_matches_chunks_helper; eauto].\n  destruct v; \n    try solve [inversion H1 | eapply mbop_matches_chunks_helper; eauto].\n  destruct (eq_nat_dec (wz + 1) (Size.to_nat s));\n    try solve [inversion H1 | eapply mbop_matches_chunks_helper; eauto].\n  unfold Size.to_nat in e. subst.\n  assert (S (Size.to_nat (wz + 1)%nat - 1) = wz + 1)%nat as EQ.\n    unfold Size.to_nat. omega.\n  destruct td.\nLocal Opaque Val.add Val.sub Val.mul Val.divu Val.divs Val.modu Val.mods\n  Val.shl Val.shrx Val.shr Val.and Val.or Val.xor.\n  assert (Size.to_nat (wz + 1)%nat - 1 = wz)%nat as EQ'. \n    rewrite <- EQ. unfold Size.to_nat. omega.\n  clear EQ.\n\n  destruct bop5;\n  try match goal with\n  | H0 : match ?s with\n    | ret _ => _\n    | merror => _\n    end = _ |- _ => destruct s eqn:Heqn; auto\n  end; inversion H1;\n  subst gv;\n    unfold gv_chunks_match_typ, vm_matches_typ; simpl; \n    rewrite EQ'; constructor;\n      auto;\n      try (split; auto; simpl; eauto using Val.add_has_chunk1,\n        Val.sub_has_chunk1, Val.mul_has_chunk1, Val.divu_has_chunk1, \n        Val.divs_has_chunk1, Val.modu_has_chunk1, Val.mods_has_chunk1,\n        Val.shl_has_chunk1, Val.shrx_has_chunk1, Val.shr_has_chunk1,\n        Val.and_has_chunk1, Val.or_has_chunk1, Val.xor_has_chunk1).\nTransparent Val.add Val.sub Val.mul Val.divu Val.divs Val.modu Val.mods\n  Val.shl Val.shrx Val.shr Val.and Val.or Val.xor.\nQed.\n\nLemma mfbop_matches_chunks : forall S td fbop5 f gv1 gv2 gv\n  (H: wf_typ S td (typ_floatpoint f))\n  (H1:mfbop td fbop5 f gv1 gv2 = Some gv),\n  gv_chunks_match_typ td gv (typ_floatpoint f).\nProof.\n  intros. destruct td.\n  unfold mfbop, GV2val in H1.\n  destruct gv1; \n    try solve [inversion H1 | eapply gundef__matches_chunks; eauto].\n  destruct p.\n  destruct gv1; \n    try solve [inversion H1 | eapply gundef__matches_chunks; eauto].\n  destruct v; \n    try solve [inversion H1 | eapply gundef__matches_chunks; eauto].\n  destruct gv2; \n    try solve [inversion H1 | eapply gundef__matches_chunks; eauto].\n  destruct p.\n  destruct gv2; \n    try solve [inversion H1 | eapply gundef__matches_chunks; eauto].\n  destruct v; \n    try solve [inversion H1 | eapply gundef__matches_chunks; eauto].\n  destruct f; \n    try solve [inversion H1 | eapply gundef__matches_chunks; eauto].\n    destruct fbop5; inv H1; simpl;\n      unfold gv_chunks_match_typ, vm_matches_typ; simpl; constructor;\n        try solve [auto | simpl; (*rewrite Floats.Float.singleoffloat_idem;*) auto].\n\n    destruct fbop5; destruct f; inv H; inv H5; destruct gv2; inv H1\n    ; try (eapply gundef__matches_chunks; eauto; fail)\n    ; destruct p; destruct gv2; simpl; destruct v\n    ; try (eapply gundef__matches_chunks; eauto; fail)\n    ; inv H0; eauto;\n    unfold gv_chunks_match_typ, vm_matches_typ; simpl; constructor;\n      solve [auto | repeat split; auto].\nQed.\n\nLemma mgep_has_chunk: forall TD t ma idxs v,\n  mgep TD t ma idxs = Some v ->\n  Val.has_chunk v (AST.Mint 31).\nProof.\n  unfold mgep.\n  intros.\n  destruct ma; tinv H.\n  destruct idxs; tinv H.\n  inv_mbind. uniq_result.\n  simpl. auto.\nQed.\n\nDefinition const2GV__matches_chunks_Prop S TD c t :=\n  wf_const S TD c t ->\n  forall gl gv t',\n  _const2GV TD gl c = Some (gv, t') ->\n  wf_global TD S gl ->\n  t = t' /\\ gv_chunks_match_typ TD gv t.\n\nDefinition consts2GV__matches_chunks_Prop sdct :=\n  wf_const_list sdct ->\n  let 'lsdct := sdct in\n  let '(lsdc, lt) := split lsdct in\n  let '(lsd, lc) := split lsdc in\n  let '(ls, ld) := split lsd in\n  forall S TD gl, \n  wf_list_targetdata_typ S TD gl lsd ->\n  (forall gv t, \n    (forall t0, In t0 lt -> t0 = t) ->\n   _list_const_arr2GV TD gl t lc = Some gv ->\n   match (length lc) with\n   | S _ => gv_chunks_match_typ TD gv (typ_array (length lc) t)\n   | _ => Forall2 vm_matches_typ gv nil\n   end) /\\\n  (forall gv lt', \n   _list_const_struct2GV TD gl lc = Some (gv, lt') ->\n   lt' = lt /\\\n   gv_chunks_match_list_typ TD gv lt').\n\nLemma const2GV_matches_chunks_mutind : \n  (forall S td c t, @const2GV__matches_chunks_Prop S td c t) /\\\n  (forall sdct, @consts2GV__matches_chunks_Prop sdct).\nProof.\n  (wfconst_cases (apply wf_const_mutind; \n                    unfold const2GV__matches_chunks_Prop, \n                           consts2GV__matches_chunks_Prop) Case);\n    intros; subst; simpl in *.\nCase \"wfconst_zero\".\n  inv_mbind. \n  split; auto.\n    eapply zeroconst2GV__matches_chunks; eauto.\n\nCase \"wfconst_int\".\n  uniq_result.\n  split; auto.\n    destruct targetdata5.\n    unfold gv_chunks_match_typ, val2GV, vm_matches_typ. simpl.\n    constructor; auto.\n      split; auto. split; auto. \n      unfold Int.repr. simpl. apply Int.Z_mod_modulus_range.\n\nCase \"wfconst_floatingpoint\".\n  destruct targetdata5.\n  destruct floating_point5; inv H0;\n    split; try solve [\n      auto |\n      unfold gv_chunks_match_typ, val2GV, vm_matches_typ; simpl;\n        constructor; try solve [\n          auto| \n          split; try solve [auto |\n            simpl; auto\n          ]\n        ]\n    ].\n\nCase \"wfconst_undef\".\n  inv_mbind.\n  split; auto.\n    eapply gundef__matches_chunks; eauto.\n\nCase \"wfconst_null\". \n  destruct targetdata5.\n  uniq_result.\n  split; auto.\n    unfold gv_chunks_match_typ, val2GV, vm_matches_typ. simpl.\n    constructor; auto.\n      split; auto. split; auto. simpl.\n      split; [omega| apply Z.gt_lt; apply Int.modulus_pos].\n\nCase \"wfconst_array\". Focus.\n  inv_mbind.\n  simpl_split lsdc lt.\n  simpl_split lsd lc.\n  simpl_split ls ld.\n  match goal with\n  | H3: match _ with\n        | 0%nat => _\n        | S _ => _ \n        end = _ |- _ => \n  rewrite H1 in H3; unfold Size.to_nat in *;\n  destruct sz5; inv H3\n  end.\n    split; auto.\n      unfold gv_chunks_match_typ, val2GV, vm_matches_typ. simpl.\n      destruct targetdata5.\n      constructor; auto. split; auto. split; auto.\n\n    split; auto.\n    destruct (@H0 system5 targetdata5 gl) as [J1 J2]; try solve \n      [destruct targetdata5; eauto using const2GV_typsize_mutind_array].\n    symmetry in HeqR.\n    assert (lc = const_list) as EQ.\n      eapply make_list_const_spec2; eauto.\n    rewrite <- EQ in HeqR. subst.\n    apply J1 in HeqR; eauto using make_list_const_spec4.\n      unfold gv_chunks_match_typ. simpl.\n      rewrite H1 in HeqR. clear - HeqR. \n      inv_mbind. simpl in HeqR. auto.\n\nCase \"wfconst_struct\". Focus.\n  simpl_split lsdc lt.\n  simpl_split lsd lc.\n  simpl_split ls ld.\n  match goal with\n    | [ H : match ?t with\n              | ret _ => _\n              | merror => _\n            end = ret _ |- _ ] =>\n    remember t as R1;\n    destruct R1 as [[gv0 ts]|];\n    inv H5\n  end.\n  destruct (@H0 system5 (layouts5, namedts5) gl) as [J1 J2];\n    eauto using const2GV_typsize_mutind_struct.\n\n  symmetry in HeqR2.\n  erewrite <- map_list_const_typ_spec2 in HeqR2; eauto.\n  erewrite <- map_list_const_typ_spec1 in H2; eauto.\n  apply J2 in HeqR2; eauto.\n  destruct HeqR2 as [J6 J7]; subst.\n  match goal with\n  | H2': (if _ then _ else _) = _ |- _ => rewrite H2 in H2'\n  end.\n  unfold gv_chunks_match_list_typ in J7.\n  unfold gv_chunks_match_typ.\n  inv_mbind. symmetry_ctx.\n  destruct gv0; uniq_result; split; auto.\n    inv J7. \n    unfold typ_eq_list_typ in H2.\n    destruct t'; tinv H2.\n      destruct (list_typ_dec l0 lt); subst; tinv H2.\n      simpl. simpl in HeqR0. \n      fold flatten_typs_aux. unfold flatten_typs in *.\n      fill_ctxhole. \n      apply uninits_match_uninitMCs.\n\n      assert (J:=H4). inv J.\n      apply flatten_typ_total in H4.\n      destruct H4 as [gv w1].\n      inv_mbind. fill_ctxhole.\n      destruct (list_typ_dec l0 lt); subst; tinv H2.\n      eapply flatten_struct__eq__namedt with (mc1:=uninitMCs 1) in w1; eauto. \n        subst.\n        apply uninits_match_uninitMCs.\n      \n        simpl. simpl in HeqR0. \n        unfold AssocList, namedts, namedt, id, layouts in *. \n        unfold flatten_typs in HeqR2. \n        fold flatten_typs_aux.\n        rewrite HeqR2. auto.\n\n    inv J7. \n    unfold typ_eq_list_typ in H2.\n    destruct t'; tinv H2.\n      destruct (list_typ_dec l0 lt); subst; tinv H2.\n      simpl. simpl in HeqR0.\n      unfold flatten_typs in *.\n      fold flatten_typs_aux.\n      fill_ctxhole. \n      constructor; auto.\n      \n      assert (J:=H4). inv J.\n      apply flatten_typ_total in H4.\n      destruct H4 as [gv w1].\n      inv_mbind. fill_ctxhole.\n      destruct (list_typ_dec l0 lt); subst; tinv H2.\n      eapply flatten_struct__eq__namedt with (mc1:=y::l') in w1; eauto. \n        subst. constructor; auto.\n      \n        simpl. simpl in HeqR0. \n        unfold AssocList, namedts, namedt, id, layouts in *. \n        unfold flatten_typs in *.\n        fold flatten_typs_aux.\n        rewrite HeqR2. auto.\n\n\nCase \"wfconst_gid\".\n  inv_mbind. symmetry_ctx.\n  split; auto.\n    apply H3 in H0.\n    destruct H0 as [gv0 [sz [J1 [J2 [J3 J4]]]]]. \n    uniq_result. auto.\n\nCase \"wfconst_trunc_int\". Focus.\n  destruct (_const2GV targetdata5 gl const5) as [[]|]; inv H4.\n  remember (mtrunc targetdata5 truncop_int t (typ_int sz2) g) as R.\n  destruct R; inv H7.\n  split; auto.\n   symmetry in HeqR.\n   eapply mtrunc_matches_chunks in HeqR; try solve [eauto | constructor; auto].\n\nCase \"wfconst_trunc_fp\". Focus.\n  destruct (_const2GV targetdata5 gl const5) as [[]|]; inv H4.\n  remember (mtrunc targetdata5 truncop_int t (typ_floatpoint floating_point2) g) \n    as R.\n  destruct R; inv H7.\n  split; auto.\n   symmetry in HeqR.\n   eapply mtrunc_matches_chunks in HeqR; try solve [eauto | constructor; auto].\n\nCase \"wfconst_zext\". Focus.\n  destruct (_const2GV targetdata5 gl const5) as [[]|]; inv H4.\n  remember (mext targetdata5 extop_z t (typ_int sz2) g) as R.\n  destruct R; inv H7.\n  split; auto.\n    symmetry in HeqR.\n    eapply mext_matches_chunks in HeqR; try solve [eauto | constructor; auto].\n\nCase \"wfconst_sext\".  Focus.\n  destruct (_const2GV targetdata5 gl const5) as [[]|]; inv H4.\n  remember (mext targetdata5 extop_s t (typ_int sz2) g) as R.\n  destruct R; inv H7.\n  split; auto.\n    symmetry in HeqR.\n    eapply mext_matches_chunks in HeqR; try solve [eauto | constructor; auto].\n\nCase \"wfconst_fpext\".  Focus.\n  destruct (_const2GV targetdata5 gl const5) as [[]|]; inv H4.\n  remember (mext targetdata5 extop_fp t (typ_floatpoint floating_point2) g) as R.\n  destruct R; inv H7.\n  split; auto.\n    symmetry in HeqR.\n    eapply mext_matches_chunks in HeqR; try solve [eauto | constructor; auto].\n\nCase \"wfconst_ptrtoint\". Focus.\n  destruct targetdata5. \n  destruct (_const2GV (l0, l1) gl const5) as [[]|]; inv H3.\n  split; auto.\n    unfold gv_chunks_match_typ, vm_matches_typ. simpl. \n    constructor; auto. split; auto.  split; auto.\n\nCase \"wfconst_inttoptr\". Focus.\n  destruct targetdata5. \n  destruct (_const2GV (l0, l1) gl const5) as [[]|]; inv H3.\n  split; auto.\n    unfold gv_chunks_match_typ, vm_matches_typ. simpl. \n    constructor; auto. split; auto.  split; auto.\n\nCase \"wfconst_bitcast\". Focus.\n  remember (_const2GV targetdata5 gl const5) as R1.\n  destruct R1 as [[]|]; inv H3.\n  remember (mbitcast t g (typ_pointer typ2)) as R.\n  destruct R; inv H6.\n  unfold mbitcast in HeqR.\n  destruct t; inv HeqR.\n  eapply H0 in H4; eauto.\n  destruct H4; eauto.\n\nCase \"wfconst_gep\". Focus.\n  remember (_const2GV targetdata5 gl const_5) as R1.\n  destruct R1 as [[]|]; tinv H7.\n  destruct t; tinv H7.\n  symmetry in HeqR1.\n  eapply H0 in HeqR1; eauto.\n  destruct HeqR1 as [J1 J2].\n  inv J1. \n  rewrite H5 in H7.\n  assert(\n    match gundef targetdata5 typ' with\n       | ret gv => ret (gv, typ')\n       | merror => merror\n       end = ret (gv, t') ->\n    typ' = t' /\\\n    gv_chunks_match_typ targetdata5 gv typ') as G.\n    intros W3.\n    remember (gundef targetdata5 typ') as R3;\n    destruct R3; inv W3;\n    split; try solve \n      [auto | eapply gundef__matches_chunks; \n                try solve [eauto | constructor; auto]].\n  remember (GV2ptr targetdata5 (getPointerSize targetdata5) g) as R.\n  destruct R; auto.\n    remember (intConsts2Nats targetdata5 const_list) as R2.\n    destruct R2; auto.\n      remember (mgep targetdata5 t v l0) as R3.\n      destruct R3; auto.\n        inv H7.\n        split; auto.  \n          unfold getConstGEPTyp in H5.\n          destruct const_list; tinv H5.  \n          remember (getSubTypFromConstIdxs const_list t) as R4.\n          destruct R4; inv H5. \n          unfold ptr2GV, val2GV.\n          unfold gv_chunks_match_typ, vm_matches_typ. simpl.\n          destruct targetdata5. simpl. \n          constructor; auto. split; auto.\n          simpl. eapply mgep_has_chunk; eauto.\n\nCase \"wfconst_select\". Focus.\n  remember (_const2GV targetdata5 gl const0) as R0.\n  remember (_const2GV targetdata5 gl const1) as R1.\n  remember (_const2GV targetdata5 gl const2) as R2.\n  destruct R0 as [[gv0 t0]|]; tinv H8.\n  destruct R1 as [[gv1 t1]|]; tinv H8.\n  destruct R2 as [[gv2 t2]|]; tinv H8.\n  destruct (isGVZero targetdata5 gv0); inv H8; eauto.\n\nCase \"wfconst_icmp\". Focus.\n  remember (_const2GV targetdata5 gl const1) as R1.\n  remember (_const2GV targetdata5 gl const2) as R2.\n  destruct R1 as [[gv1 t1]|]; tinv H7.\n  destruct R2 as [[gv2 t2]|]; tinv H7.\n  remember (micmp targetdata5 cond5 t1 gv1 gv2) as R3.\n  destruct R3; inv H7; eauto.\n  split; auto.\n    symmetry in HeqR3.\n    eapply micmp_matches_chunks in HeqR3; try solve [eauto | constructor; auto].\n\nCase \"wfconst_fcmp\". Focus.\n  remember (_const2GV targetdata5 gl const1) as R1.\n  remember (_const2GV targetdata5 gl const2) as R2.\n  destruct R1 as [[gv1 t1]|]; tinv H7.\n  destruct_typ t1; tinv H7.\n  destruct R2 as [[gv2 t2]|]; tinv H7.\n  remember (mfcmp targetdata5 fcond5 f gv1 gv2) as R3.\n  destruct R3; inv H7; eauto.\n  split; auto.\n    symmetry in HeqR3.\n    eapply mfcmp_matches_chunks in HeqR3; try solve [eauto | constructor; auto]. \n\nCase \"wfconst_extractvalue\". Focus.\n  remember (_const2GV targetdata5 gl const_5) as R1.\n  destruct R1 as [[gv1 t1]|]; tinv H8.\n  remember (getSubTypFromConstIdxs const_list t1) as R2.\n  destruct R2 as [t2|]; tinv H8.\n  remember (extractGenericValue targetdata5 t1 gv1 const_list) as R3.\n  destruct R3 as [gv2|]; inv H8.\n  symmetry in HeqR1.\n  apply H0 in HeqR1; auto.\n  destruct HeqR1 as [J1 J2]; subst.\n  destruct H6 as [idxs [o [J3 J4]]].\n  symmetry in J3.\n  eapply getSubTypFromConstIdxs__mgetoffset in J3; eauto.\n  subst.\n  split; eauto.\n    eapply extractGenericValue_matches_chunks; \n      try solve [eauto | constructor; auto].\n\n\nCase \"wfconst_insertvalue\". Focus.\n  remember (_const2GV targetdata5 gl const_5) as R1.\n  destruct R1 as [[gv1 t1]|]; tinv H10.\n  remember (_const2GV targetdata5 gl const') as R2.\n  destruct R2 as [[gv2 t2]|]; tinv H10.\n  remember (insertGenericValue targetdata5 t1 gv1 const_list t2 gv2) as R3.\n  destruct R3 as [gv3|]; inv H10.\n  symmetry in HeqR1.\n  apply H0 in HeqR1; auto.\n  destruct HeqR1 as [J1 J2]; subst.\n  symmetry in HeqR2.\n  apply H2 in HeqR2; auto.\n  destruct HeqR2 as [J3 J4]; subst.\n  split; auto.\n    eapply insertGenericValue_matches_chunks in HeqR3; \n      try solve [eauto | constructor; auto].\n\n\nCase \"wfconst_bop\". Focus.\n  remember (_const2GV targetdata5 gl const1) as R1.\n  remember (_const2GV targetdata5 gl const2) as R2.\n  destruct R1 as [[gv1 t1]|]; tinv H4.\n  destruct_typ t1; tinv H4.\n  destruct R2 as [[gv2 t2]|]; tinv H4.\n  remember (mbop targetdata5 bop5 s0 gv1 gv2) as R3.\n  destruct R3; inv H4.\n  symmetry in HeqR1.\n  apply H0 in HeqR1; auto.\n  destruct HeqR1 as [Heq _]. inv Heq.\n  split; auto.\n    symmetry in HeqR3.\n    eapply mbop_matches_chunks in HeqR3; eauto.\n\nCase \"wfconst_fbop\". Focus.\n  remember (_const2GV targetdata5 gl const1) as R1.\n  remember (_const2GV targetdata5 gl const2) as R2.\n  destruct R1 as [[gv1 t1]|]; tinv H4.\n  destruct_typ t1; tinv H4.\n  destruct R2 as [[gv2 t2]|]; tinv H4.\n  remember (mfbop targetdata5 fbop5 f gv1 gv2) as R3.\n  destruct R3; inv H4.\n  symmetry in HeqR1.\n  apply H0 in HeqR1; auto.\n  destruct HeqR1 as [Heq _]. inv Heq.\n  split; auto.\n    symmetry in HeqR3.\n    eapply mfbop_matches_chunks in HeqR3; eauto.\n\nCase \"wfconst_nil\".\n  intros; subst.\n  split; intros; subst; uniq_result.\n    auto.\n     \n    destruct TD.\n    unfold gv_chunks_match_list_typ. simpl.\n    split; eauto.    \n\nCase \"wfconst_cons\".\n  simpl_split lsdc lt. simpl.\n  simpl_split lsd lc. simpl.\n  simpl_split ls ld. simpl.\n  intros S TD gl HwfTD; subst.\n  split.\n    intros gv t Hin Hc2g.\n    remember (_list_const_arr2GV TD gl t lc) as R.\n    destruct R; try solve [inv Hc2g].\n    remember (_const2GV TD gl const_) as R'.\n    destruct R' as [[gv0 t0]|]; try solve [inv Hc2g].\n    destruct (typ_dec t t0); subst; try solve [inv Hc2g].\n    remember (getTypeAllocSize TD t0) as R1.\n    destruct R1; inv Hc2g.\n    assert (typ5 = t0) as EQ. eapply Hin; eauto.\n    subst.\n    apply wf_list_targetdata_typ_cons_inv in HwfTD.\n    destruct HwfTD as [J1 [J2 [J3 J4]]]; subst.\n    symmetry in HeqR'.\n    apply H0 in HeqR'; auto.\n    destruct HeqR' as [J5 J6]; subst.\n    eapply H2 in J1; eauto. destruct J1 as [J1 _]. clear H0 H2.\n    symmetry in HeqR2.\n    apply J1 in HeqR2; auto.\n      destruct TD. \n      unfold gv_chunks_match_typ in HeqR2, J6.\n      unfold gv_chunks_match_typ. simpl. simpl in HeqR2, J6.\n      inv_mbind. rewrite <- HeqR3.\n      simpl_env.\n      repeat (apply match_chunks_app; auto).\n        destruct (length lc); simpl; auto.\n        rewrite <- HeqR3 in HeqR2. auto. \n\n        erewrite match_chunks_eq_size; eauto.\n        apply uninits_match_uninitMCs.\n\n    intros gv lt' Hc2g.\n    remember (_list_const_struct2GV TD gl lc) as R.\n    destruct R as [[gv1 ts1]|]; try solve [inv Hc2g].\n    remember (_const2GV TD gl const_) as R'.\n    destruct R' as [[gv0 t0]|]; try solve [inv Hc2g].\n    remember (getTypeAllocSize TD t0) as R1.\n    destruct R1; inv Hc2g.\n    apply wf_list_targetdata_typ_cons_inv in HwfTD.\n    destruct HwfTD as [J1' [J2' [J3 J4]]]; subst.\n    symmetry in HeqR'.\n    apply H0 in HeqR'; auto.\n    destruct HeqR' as [J5 J6]; subst.\n    eapply H2 in J1'; eauto. destruct J1' as [_ J1']. clear H0 H2.\n    symmetry in HeqR2.\n    apply J1' in HeqR2; auto.\n    destruct HeqR2 as [J7 J8]; subst.\n    split; auto.\n      unfold gv_chunks_match_typ in J6.\n      unfold gv_chunks_match_list_typ in *. \n      destruct TD. simpl in *.\n      inv_mbind. simpl. symmetry_ctx. repeat fill_ctxhole.\n      repeat (apply match_chunks_app; auto).\n        erewrite match_chunks_eq_size; eauto.\n        apply uninits_match_uninitMCs.\nQed.\n\nLemma const2GV__matches_chunks_aux : forall S TD c t gl gv t' \n  (Hwf: wf_const S TD c t),\n  _const2GV TD gl c = Some (gv, t') ->\n  wf_global TD S gl ->\n  t = t' /\\ gv_chunks_match_typ TD gv t.\nProof.\n  intros.\n  destruct const2GV_matches_chunks_mutind. \n  eapply H1; eauto.\nQed.\n\nLemma cundef_gv__matches_chunks : forall S TD gv t,\n  wf_typ S TD t ->\n  gv_chunks_match_typ TD gv t ->\n  gv_chunks_match_typ TD (cundef_gv gv t) t.\nProof.\n  unfold gv_chunks_match_typ, vm_matches_typ. destruct TD.\n  intros. inv_mbind.\n  destruct_typ t; simpl in *; auto.\n    inv HeqR. constructor; auto. split; auto.\n    simpl. split; auto. split; try omega. apply Z.gt_lt; apply Int.modulus_pos.\n\n    destruct f; inv HeqR; uniq_result;\n      constructor; auto; split; auto; simpl; auto.\n\n    inv HeqR. unfold null. constructor; auto.\n    split; auto. simpl. split; auto.\n    split; [omega| apply Z.gt_lt; apply Int.modulus_pos].\nQed.\n\nLemma cgv2gv__matches_chunks : forall S TD gv t,\n  wf_typ S TD t ->\n  gv_chunks_match_typ TD gv t ->\n  gv_chunks_match_typ TD (cgv2gv gv t) t.\nProof.\n  intros. destruct TD. \n  destruct gv as [|[]]; auto.\nQed.\n\nLemma const2GV__matches_chunks : forall S TD c t gl gv\n  (Hwf: wf_const S TD c t) (Hc2g: const2GV TD gl c = Some gv), \n  wf_global TD S gl ->\n  gv_chunks_match_typ TD gv t.\nProof.\n  intros.\n  unfold const2GV in Hc2g.\n  remember (_const2GV TD gl c) as R.\n  destruct R as [[]|]; inv Hc2g.\n  symmetry in HeqR.\n  unfold getTypeSizeInBits, getTypeSizeInBits_and_Alignment.\n  eapply const2GV__matches_chunks_aux in HeqR; eauto.\n  destruct HeqR as [J1 J2]; subst.\n  apply wf_const__wf_typ in Hwf.\n  eapply cgv2gv__matches_chunks; eauto.\nQed.\n\nLemma mset'_matches_chunks : forall (TD : TargetData) ofs (t1 t2 : typ) \n  x y z (J1: gv_chunks_match_typ TD x t1) (J2: gv_chunks_match_typ TD y t2), \n  mset' TD ofs t1 t2 x y = ret z ->\n  gv_chunks_match_typ TD z t1.\nProof.\n  unfold mset'. \n  intros. \n  remember (mset TD x ofs t2 y) as R.\n  destruct R.\n    uniq_result.\n    eauto using mset_matches_chunks. \n    eauto using gundef__matches_chunks.\nQed.\n\nLemma mget'_matches_chunks : forall TD ofs t' x z, \n  mget' TD ofs t' x = Some z ->\n  gv_chunks_match_typ TD z t'.\nProof.\n  unfold mget'. intros.\n  remember (mget TD x ofs t') as R.\n  destruct R.\n    uniq_result.\n    eauto using mget_matches_chunks. \n    eauto using gundef__matches_chunks.\nQed.\n\nLemma GEP_matches_chunks : forall TD t mp vidxs inbounds0 t' mp',\n  LLVMgv.GEP TD t mp vidxs inbounds0 t' = ret mp' ->\n  gv_chunks_match_typ TD mp' (typ_pointer t').\nProof.\n  unfold LLVMgv.GEP. intros.\n  destruct (GV2ptr TD (getPointerSize TD) mp);eauto using gundef__matches_chunks.\n  destruct (GVs2Nats TD vidxs); eauto using gundef__matches_chunks.\n  remember (mgep TD t v l0) as R.\n  destruct R; eauto using gundef__matches_chunks.\n  uniq_result.\n  unfold gv_chunks_match_typ, vm_matches_typ. destruct TD. simpl.\n  unfold ptr2GV, val2GV. simpl.\n  constructor; auto. split; auto. simpl. \n  eapply mgep_has_chunk; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "crellvm-vellvm", "sha": "54c7cc88ab5b4aec4c327f501cac4d9a667ca057", "save_path": "github-repos/coq/snu-sf-crellvm-vellvm", "path": "github-repos/coq/snu-sf-crellvm-vellvm/crellvm-vellvm-54c7cc88ab5b4aec4c327f501cac4d9a667ca057/src/Vellvm/genericvalues_props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.22683856120179893}}
{"text": "Set Primitive Projections.\nRecord prod A B := pair { fst : A ; snd : B }.\nArguments pair {_ _} _ _.\nNotation \"( x , y , .. , z )\" := (pair .. (pair x y) .. z) : core_scope.\nDefinition ap11 {A B} {f g:A->B} (h:f=g) {x y:A} (p:x=y) : f x = g y.\nAdmitted.\nGoal forall x y z w : Set, (x, y) = (z, w).\nProof.\n  intros.\n  apply ap11. (* Toplevel input, characters 21-25:\nError: In environment\nx : Set\ny : Set\nz : Set\nw : Set\nUnable to unify \"?31 ?191 = ?32 ?192\" with \"(x, y) = (z, w)\".\n *)\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/closed/3546.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22682380439722544}}
{"text": "Require Import VST.floyd.proofauto.\nLocal Open Scope logic.\nRequire Import List. Import ListNotations.\nRequire Import ZArith.\nRequire Import tweetnacl20140427.tweetNaclBase.\nRequire Import tweetnacl20140427.Salsa20.\nRequire Import tweetnacl20140427.verif_salsa_base.\nRequire Import tweetnacl20140427.tweetnaclVerifiableC.\nRequire Import tweetnacl20140427.Snuffle.\nRequire Import tweetnacl20140427.spec_salsa.\n\nRequire Import tweetnacl20140427.verif_fcore_jbody.\n\nOpaque Snuffle.Snuffle.\n\nLemma SnuffleS i l: Snuffle (S i) l = bind (Snuffle i l) (Snuffle 1). reflexivity. Qed.\n\nFixpoint WcontI (xs: list int) (j:nat) (l:list val):Prop :=\n   match j with O => Zlength l = 16\n   | (S n) => Zlength l = 16 /\\\n              exists t0 t1 t2 t3,\n              Znth ((5 * (Z.of_nat n) + 4 * 0) mod 16) (map Vint xs) = Vint t0 /\\\n              Znth ((5 * (Z.of_nat n) + 4 * 1) mod 16) (map Vint xs) = Vint t1 /\\\n              Znth ((5 * (Z.of_nat n) + 4 * 2) mod 16) (map Vint xs) = Vint t2 /\\\n              Znth ((5 * (Z.of_nat n) + 4 * 3) mod 16) (map Vint xs) = Vint t3 /\\\n              exists wl, WcontI xs n wl /\\\n                match Wcopyspec t0 t1 t2 t3 with\n                 (s0,s1,s2,s3) => wlistJ' wl (Z.of_nat n) s0 s1 s2 s3 l\n                end\n  end.\n\nLemma WcontI_Zlength xs j l: WcontI xs j l -> Zlength l=16.\nProof. intros. destruct j; eapply H. Qed.\n\nLemma WWI r w (W: WcontI r 4 w) (R:Zlength r = 16):\n      exists wi, w=map Vint wi /\\ snuffleRound r = Some wi.\nProof.\napply listD16 in R.\ndestruct R as [x0 [x1 [x2 [x3 [x4 [x5 [x6 [x7\n              [x8 [x9 [x10 [x11 [x12 [x13 [x14 [x15 XX]]]]]]]]]]]]]]]]. subst r.\ndestruct W as [HW H1].\ndestruct H1 as [t0 [t1 [t2 [t3 [T0 [T1 [T2 [T3 [w1 [[_ H1] W1]]]]]]]]]]. simpl in T0, T1, T2, T3.\nrewrite Z.mod_small in T0. 2: omega.\nrewrite Zmod_eq in T1. 2: omega.\nrewrite Zmod_eq in T2. 2: omega.\nrewrite Zmod_eq in T3. 2: omega. simpl in T0, T1, T2, T3.\ndestruct H1 as [t4 [t5 [t6 [t7 [T4 [T5 [T6 [T7 [w2 [[_ H1] W2]]]]]]]]]]. simpl in T4, T5, T6, T7.\nrewrite Zmod_eq in T4. 2: omega.\nrewrite Zmod_eq in T5. 2: omega.\nrewrite Zmod_eq in T6. 2: omega.\nrewrite Zmod_eq in T7. 2: omega. simpl in T4, T5, T6, T7.\ndestruct H1 as [t8 [t9 [t10 [t11 [T8 [T9 [T10 [T11 [w3 [[_ H1] W3]]]]]]]]]]. simpl in T8, T9, T10, T11.\nrewrite Z.mod_small in T8. 2: omega.\nrewrite Z.mod_small in T9. 2: omega.\nrewrite Zmod_eq in T10. 2: omega.\nrewrite Zmod_eq in T11. 2: omega. simpl in T8, T9, T10, T11.\ndestruct H1 as [t12 [t13 [t14 [t15 [T12 [T13 [T14 [T15 [w4 [L4 W4]]]]]]]]]]. simpl in T12, T13, T14, T15.\nrewrite Z.mod_small in T12. 2: omega.\nrewrite Z.mod_small in T13. 2: omega.\nrewrite Z.mod_small in T14. 2: omega.\nrewrite Z.mod_small in T15. 2: omega.\nunfold Znth in *. simpl in  T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15.\nsymmetry in T0; inv T0. symmetry in T1; inv T1. symmetry in T2; inv T2. symmetry in T3; inv T3.\nsymmetry in T4; inv T4. symmetry in T5; inv T5. symmetry in T6; inv T6. symmetry in T7; inv T7.\nsymmetry in T8; inv T8. symmetry in T9; inv T9. symmetry in T10; inv T10. symmetry in T11; inv T11.\nsymmetry in T12; inv T12. symmetry in T13; inv T13. symmetry in T14; inv T14. symmetry in T15; inv T15.\nred in L4.\nsimpl in W4.\nremember (Int.xor x4 (Int.rol (Int.add x0 x12) (Int.repr 7))) as z1.\nremember (Int.xor x8 (Int.rol (Int.add z1 x0) (Int.repr 9))) as z2.\nremember (Int.xor x12 (Int.rol (Int.add z2 z1) (Int.repr 13))) as z3.\nremember (Int.xor x0 (Int.rol (Int.add z3 z2) (Int.repr 18))) as z0.\napply listD16 in L4.\ndestruct L4 as [y0 [y1 [y2 [y3 [y4 [y5 [y6 [y7\n               [y8 [y9 [y10 [y11 [y12 [y13 [y14 [y15 XX]]]]]]]]]]]]]]]]. subst w4.\ndestruct W4 as [_ W4]; simpl in W4.\n(*rewrite Z.mod_small in W4. 2: omega.\nrewrite Z.mod_small in W4. 2: omega.\nrewrite Z.mod_small in W4. 2: omega.\nrewrite Z.mod_small in W4. 2: omega.*)\nunfold upd_Znth, sublist in W4; simpl in W4. subst w3.\nsimpl in W3.\nremember (Int.xor x9 (Int.rol (Int.add x5 x1) (Int.repr 7))) as z6.\nremember (Int.xor x13 (Int.rol (Int.add z6 x5) (Int.repr 9))) as z7.\nremember (Int.xor x1 (Int.rol (Int.add z7 z6) (Int.repr 13))) as z4.\nremember (Int.xor x5 (Int.rol (Int.add z4 z7) (Int.repr 18))) as z5.\ndestruct W3 as [_ W3]; simpl in W3.\nunfold upd_Znth, sublist in W3; simpl in W3. subst w2.\ndestruct W2 as [_ W2]. simpl in W2.\nremember (Int.xor x14 (Int.rol (Int.add x10 x6) (Int.repr 7))) as z11.\nremember (Int.xor x2 (Int.rol (Int.add z11 x10) (Int.repr 9))) as z8.\nremember (Int.xor x6 (Int.rol (Int.add z8 z11) (Int.repr 13))) as z9.\nremember (Int.xor x10 (Int.rol (Int.add z9 z8) (Int.repr 18))) as z10.\nunfold upd_Znth, sublist in W2; simpl in W2. subst w1.\ndestruct W1 as [_ W1]; simpl in W1.\nremember (Int.xor x3 (Int.rol (Int.add x15 x11) (Int.repr 7))) as z12.\nremember (Int.xor x7 (Int.rol (Int.add z12 x15) (Int.repr 9))) as z13.\nremember (Int.xor x11 (Int.rol (Int.add z13 z12) (Int.repr 13))) as z14.\nremember (Int.xor x15 (Int.rol (Int.add z14 z13) (Int.repr 18))) as z15.\nunfold upd_Znth, sublist in W1; simpl in W1. subst w. clear HW.\nexists [z0; z1; z2; z3; z4; z5; z6; z7;\n        z8; z9; z10; z11; z12; z13; z14; z15].\nsplit. reflexivity.\nrewrite Int.add_commut in Heqz0, Heqz2, Heqz3, Heqz4, Heqz5, Heqz7, Heqz8,\n  Heqz9, Heqz10, Heqz13, Heqz14, Heqz15.\nsubst z0 z1 z2 z3 z4 z5 z6 z7 z8 z9 z10 z11 z12 z13 z14 z15. reflexivity.\nQed.\n\nDefinition array_copy3_statement:=\nSfor (Sset _m (Econst_int (Int.repr 0) tint))\n     (Ebinop Olt (Etempvar _m tint) (Econst_int (Int.repr 16) tint) tint)\n     (Ssequence\n        (Sset _t'19\n           (Ederef\n              (Ebinop Oadd (Evar _w (tarray tuint 16)) (Etempvar _m tint)\n                 (tptr tuint)) tuint))\n        (Sassign\n           (Ederef\n              (Ebinop Oadd (Evar _x (tarray tuint 16)) (Etempvar _m tint)\n                 (tptr tuint)) tuint) (Etempvar _t'19 tuint)))\n     (Sset _m\n        (Ebinop Oadd (Etempvar _m tint) (Econst_int (Int.repr 1) tint) tint)).\n\nLemma array_copy3 Espec:\nforall FR c k h nonce out\n       i w x y t (xlist wlist:list val)\n       (WZ: forall m, 0<=m<16 -> exists mval, Znth m wlist =Vint mval),\n@semax CompSpecs Espec\n  (func_tycontext f_core SalsaVarSpecs SalsaFunSpecs nil)\n  (PROP  ()\n   LOCAL  (temp _j (Vint (Int.repr 4)); temp _i (Vint (Int.repr i)); lvar _t (tarray tuint 4) t;\n   lvar _y (tarray tuint 16) y; lvar _x (tarray tuint 16) x;\n   lvar _w (tarray tuint 16) w; temp _in nonce; temp _out out; temp _c c;\n   temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FR; data_at Tsh (tarray tuint 16) wlist w;\n         data_at Tsh (tarray tuint 16) xlist x)) \n array_copy3_statement\n  (normal_ret_assert\n  (PROP  ()\n   LOCAL  (temp _j (Vint (Int.repr 4)); temp _i (Vint (Int.repr i)); lvar _t (tarray tuint 4) t;\n      lvar _y (tarray tuint 16) y; lvar _x (tarray tuint 16) x;\n      lvar _w (tarray tuint 16) w; temp _in nonce; temp _out out; temp _c c;\n      temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FR; data_at Tsh (tarray tuint 16) wlist w;\n         data_at Tsh (tarray tuint 16) wlist x))).\nProof. intros. abbreviate_semax.\nTime assert_PROP (Zlength wlist = 16 /\\ Zlength xlist = 16) as WXL by entailer!. (*1.4 versus 5.4*)\ndestruct WXL as [WL XL].\nunfold array_copy3_statement.\nTime forward_for_simple_bound 16 (EX m:Z,\n  (PROP  ()\n   LOCAL  (temp _j (Vint (Int.repr 4)); temp _i (Vint (Int.repr i)); lvar _t (tarray tuint 4) t;\n   lvar _y (tarray tuint 16) y; lvar _x (tarray tuint 16) x;\n   lvar _w (tarray tuint 16) w; temp _in nonce; temp _out out; temp _c c;\n   temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FR; data_at Tsh (tarray tuint 16) wlist w;\n         EX mlist:_, !!(forall mm, 0<=mm<m -> Znth mm mlist = Znth mm wlist)\n                && data_at Tsh (tarray tuint 16) mlist x))).\n  (*1.2 versus 2.7*)\n{ Exists xlist. Time entailer!. (*2.6 versus 6.7*) intros; omega. }\n{ Intros mlist. rename H into M. rename i0 into m. rename H0 into HM.\n  destruct (WZ _ M) as [mval MVAL].\n  freeze [0;2] FR1.\n  Time forward; change (@Znth val Vundef) with (@Znth val _); rewrite MVAL. (*3.5 versus 8.7*)\n  Time solve[entailer!]. (*0.9 versus 3.3*)\n  thaw FR1.\n  Time assert_PROP (Zlength mlist = 16) as ML by entailer!. (*1.2 versus 3.5*)\n  Time forward. (*3.2 versus 9*)\n   { Exists (upd_Znth m mlist (Vint mval)).\n     Time entailer!. (*2.8 versus 5.6*)\n     intros mm ?.\n     destruct (zeq mm m); subst.\n     + rewrite MVAL, upd_Znth_same; trivial. omega.\n     + rewrite <- HM. 2: omega.\n       apply upd_Znth_diff; trivial; omega. }\n}\n{ Time entailer!. (*1.8 versus 4.3*)\n  Intros mlist.\n  assert_PROP (Zlength mlist = 16) as ML by entailer.\n  apply derives_refl'. f_equal.\n  eapply Znth_extensional. omega.\n  intros kk K. apply H2. omega. }\nTime Qed. (*June 4th, 2017 (laptop): 1s*)\n\nDefinition f_core_loop3_statement :=\nSfor (Sset _i (Econst_int (Int.repr 0) tint))\n     (Ebinop Olt (Etempvar _i tint) (Econst_int (Int.repr 20) tint) tint)\n     (Ssequence\n        (Sfor (Sset _j (Econst_int (Int.repr 0) tint))\n           (Ebinop Olt (Etempvar _j tint) (Econst_int (Int.repr 4) tint) tint)\n           (Ssequence\n              (Sfor (Sset _m (Econst_int (Int.repr 0) tint))\n                 (Ebinop Olt (Etempvar _m tint)\n                    (Econst_int (Int.repr 4) tint) tint)\n                 (Ssequence\n                    (Sset _t'33\n                       (Ederef\n                          (Ebinop Oadd (Evar _x (tarray tuint 16))\n                             (Ebinop Omod\n                                (Ebinop Oadd\n                                   (Ebinop Omul\n                                      (Econst_int (Int.repr 5) tint)\n                                      (Etempvar _j tint) tint)\n                                   (Ebinop Omul\n                                      (Econst_int (Int.repr 4) tint)\n                                      (Etempvar _m tint) tint) tint)\n                                (Econst_int (Int.repr 16) tint) tint)\n                             (tptr tuint)) tuint))\n                    (Sassign\n                       (Ederef\n                          (Ebinop Oadd (Evar _t (tarray tuint 4))\n                             (Etempvar _m tint) (tptr tuint)) tuint)\n                       (Etempvar _t'33 tuint)))\n                 (Sset _m\n                    (Ebinop Oadd (Etempvar _m tint)\n                       (Econst_int (Int.repr 1) tint) tint)))\n              (Ssequence\n                 (Ssequence\n                    (Ssequence\n                       (Sset _t'31\n                          (Ederef\n                             (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                (Econst_int (Int.repr 0) tint) (tptr tuint))\n                             tuint))\n                       (Ssequence\n                          (Sset _t'32\n                             (Ederef\n                                (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                   (Econst_int (Int.repr 3) tint)\n                                   (tptr tuint)) tuint))\n                          (Scall (Some _t'5)\n                             (Evar _L32\n                                (Tfunction (Tcons tuint (Tcons tint Tnil))\n                                   tuint cc_default))\n                             [Ebinop Oadd (Etempvar _t'31 tuint)\n                                (Etempvar _t'32 tuint) tuint;\n                             Econst_int (Int.repr 7) tint])))\n                    (Ssequence\n                       (Sset _t'30\n                          (Ederef\n                             (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                (Econst_int (Int.repr 1) tint) (tptr tuint))\n                             tuint))\n                       (Sassign\n                          (Ederef\n                             (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                (Econst_int (Int.repr 1) tint) (tptr tuint))\n                             tuint)\n                          (Ebinop Oxor (Etempvar _t'30 tuint)\n                             (Etempvar _t'5 tuint) tuint))))\n                 (Ssequence\n                    (Ssequence\n                       (Ssequence\n                          (Sset _t'28\n                             (Ederef\n                                (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                   (Econst_int (Int.repr 1) tint)\n                                   (tptr tuint)) tuint))\n                          (Ssequence\n                             (Sset _t'29\n                                (Ederef\n                                   (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                      (Econst_int (Int.repr 0) tint)\n                                      (tptr tuint)) tuint))\n                             (Scall (Some _t'6)\n                                (Evar _L32\n                                   (Tfunction (Tcons tuint (Tcons tint Tnil))\n                                      tuint cc_default))\n                                [Ebinop Oadd (Etempvar _t'28 tuint)\n                                   (Etempvar _t'29 tuint) tuint;\n                                Econst_int (Int.repr 9) tint])))\n                       (Ssequence\n                          (Sset _t'27\n                             (Ederef\n                                (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                   (Econst_int (Int.repr 2) tint)\n                                   (tptr tuint)) tuint))\n                          (Sassign\n                             (Ederef\n                                (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                   (Econst_int (Int.repr 2) tint)\n                                   (tptr tuint)) tuint)\n                             (Ebinop Oxor (Etempvar _t'27 tuint)\n                                (Etempvar _t'6 tuint) tuint))))\n                    (Ssequence\n                       (Ssequence\n                          (Ssequence\n                             (Sset _t'25\n                                (Ederef\n                                   (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                      (Econst_int (Int.repr 2) tint)\n                                      (tptr tuint)) tuint))\n                             (Ssequence\n                                (Sset _t'26\n                                   (Ederef\n                                      (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                         (Econst_int (Int.repr 1) tint)\n                                         (tptr tuint)) tuint))\n                                (Scall (Some _t'7)\n                                   (Evar _L32\n                                      (Tfunction\n                                         (Tcons tuint (Tcons tint Tnil))\n                                         tuint cc_default))\n                                   [Ebinop Oadd (Etempvar _t'25 tuint)\n                                      (Etempvar _t'26 tuint) tuint;\n                                   Econst_int (Int.repr 13) tint])))\n                          (Ssequence\n                             (Sset _t'24\n                                (Ederef\n                                   (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                      (Econst_int (Int.repr 3) tint)\n                                      (tptr tuint)) tuint))\n                             (Sassign\n                                (Ederef\n                                   (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                      (Econst_int (Int.repr 3) tint)\n                                      (tptr tuint)) tuint)\n                                (Ebinop Oxor (Etempvar _t'24 tuint)\n                                   (Etempvar _t'7 tuint) tuint))))\n                       (Ssequence\n                          (Ssequence\n                             (Ssequence\n                                (Sset _t'22\n                                   (Ederef\n                                      (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                         (Econst_int (Int.repr 3) tint)\n                                         (tptr tuint)) tuint))\n                                (Ssequence\n                                   (Sset _t'23\n                                      (Ederef\n                                         (Ebinop Oadd\n                                            (Evar _t (tarray tuint 4))\n                                            (Econst_int (Int.repr 2) tint)\n                                            (tptr tuint)) tuint))\n                                   (Scall (Some _t'8)\n                                      (Evar _L32\n                                         (Tfunction\n                                            (Tcons tuint (Tcons tint Tnil))\n                                            tuint cc_default))\n                                      [Ebinop Oadd (Etempvar _t'22 tuint)\n                                         (Etempvar _t'23 tuint) tuint;\n                                      Econst_int (Int.repr 18) tint])))\n                             (Ssequence\n                                (Sset _t'21\n                                   (Ederef\n                                      (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                         (Econst_int (Int.repr 0) tint)\n                                         (tptr tuint)) tuint))\n                                (Sassign\n                                   (Ederef\n                                      (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                         (Econst_int (Int.repr 0) tint)\n                                         (tptr tuint)) tuint)\n                                   (Ebinop Oxor (Etempvar _t'21 tuint)\n                                      (Etempvar _t'8 tuint) tuint))))\n                          (Sfor (Sset _m (Econst_int (Int.repr 0) tint))\n                             (Ebinop Olt (Etempvar _m tint)\n                                (Econst_int (Int.repr 4) tint) tint)\n                             (Ssequence\n                                (Sset _t'20\n                                   (Ederef\n                                      (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                         (Etempvar _m tint) (tptr tuint))\n                                      tuint))\n                                (Sassign\n                                   (Ederef\n                                      (Ebinop Oadd\n                                         (Evar _w (tarray tuint 16))\n                                         (Ebinop Oadd\n                                            (Ebinop Omul\n                                               (Econst_int (Int.repr 4) tint)\n                                               (Etempvar _j tint) tint)\n                                            (Ebinop Omod\n                                               (Ebinop Oadd\n                                                  (Etempvar _j tint)\n                                                  (Etempvar _m tint) tint)\n                                               (Econst_int (Int.repr 4) tint)\n                                               tint) tint) (tptr tuint))\n                                      tuint) (Etempvar _t'20 tuint)))\n                             (Sset _m\n                                (Ebinop Oadd (Etempvar _m tint)\n                                   (Econst_int (Int.repr 1) tint) tint))))))))\n           (Sset _j\n              (Ebinop Oadd (Etempvar _j tint) (Econst_int (Int.repr 1) tint)\n                 tint)))\n        (Sfor (Sset _m (Econst_int (Int.repr 0) tint))\n           (Ebinop Olt (Etempvar _m tint) (Econst_int (Int.repr 16) tint)\n              tint)\n           (Ssequence\n              (Sset _t'19\n                 (Ederef\n                    (Ebinop Oadd (Evar _w (tarray tuint 16))\n                       (Etempvar _m tint) (tptr tuint)) tuint))\n              (Sassign\n                 (Ederef\n                    (Ebinop Oadd (Evar _x (tarray tuint 16))\n                       (Etempvar _m tint) (tptr tuint)) tuint)\n                 (Etempvar _t'19 tuint)))\n           (Sset _m\n              (Ebinop Oadd (Etempvar _m tint) (Econst_int (Int.repr 1) tint)\n                 tint))))\n     (Sset _i\n        (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint)).\n\nLemma f_core_loop3: forall (Espec : OracleKind) FR\nc k h nonce out w x y t (xI:list int),\n@semax CompSpecs Espec\n  (func_tycontext f_core SalsaVarSpecs SalsaFunSpecs nil)\n  (PROP  ()\n   LOCAL  (temp _i (Vint (Int.repr 16)); lvar _t (tarray tuint 4) t;\n   lvar _y (tarray tuint 16) y; lvar _x (tarray tuint 16) x;\n   lvar _w (tarray tuint 16) w; temp _in nonce; temp _out out; temp _c c;\n   temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FR; data_at_ Tsh (tarray tuint 4) t;\n         data_at_ Tsh (tarray tuint 16) w;\n         data_at Tsh (tarray tuint 16) (map Vint xI) x))\n f_core_loop3_statement\n  (normal_ret_assert\n  (PROP  ()\n   LOCAL  (temp _i (Vint (Int.repr 20)); lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n       lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; temp _in nonce;\n       temp _out out; temp _c c; temp _k k; temp _h (Vint (Int.repr h)))\n   SEP (FR; data_at_ Tsh (tarray tuint 4) t; data_at_ Tsh (tarray tuint 16) w;\n        EX r:_, !!(Snuffle 20 xI = Some r) &&\n           data_at Tsh (tarray tuint 16) (map Vint r) x))).\nProof. intros. abbreviate_semax.\nunfold f_core_loop3_statement.\nfreeze [0;1;2] FR1.\nTime assert_PROP (Zlength (map Vint xI) = 16) as XIZ by entailer!. (*0.9*)\nthaw FR1.\nrewrite Zlength_map in XIZ.\ndrop_LOCAL 0%nat.\nTime forward_for_simple_bound 20 (EX i:Z,\n  (PROP  ()\n   LOCAL  (lvar _t (tarray tuint 4) t;\n   lvar _y (tarray tuint 16) y; lvar _x (tarray tuint 16) x;\n   lvar _w (tarray tuint 16) w; temp _in nonce; temp _out out; temp _c c;\n   temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FR; data_at_ Tsh (tarray tuint 4) t; data_at_ Tsh (tarray tuint 16) w;\n         EX r:_, !!(Snuffle (Z.to_nat i) xI = Some r) &&\n             data_at Tsh (tarray tuint 16) (map Vint r) x))). (*0.9*)\n{ Exists xI. Time entailer!. (*2.6*) }\n\n{ rename H into I. Intros r. rename H into R.\n  assert (XI: length xI = 16%nat). eapply (Zlength_length _ _ 16). omega. trivial.\n  assert (RL:= Snuffle_length _ _ _ R XI).\n  assert (RZL: Zlength r = 16). rewrite Zlength_correct, RL; reflexivity.\n\n  Time forward_for_simple_bound 4 (EX j:Z,\n  (PROP  ()\n   LOCAL  (temp _i (Vint (Int.repr i)); lvar _t (tarray tuint 4) t;\n   lvar _y (tarray tuint 16) y; lvar _x (tarray tuint 16) x;\n   lvar _w (tarray tuint 16) w; temp _in nonce; temp _out out; temp _c c;\n   temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FR; data_at_ Tsh (tarray tuint 4) t;\n      EX l:_, !!(WcontI r (Z.to_nat j) l) && data_at Tsh (tarray tuint 16) l w;\n      data_at Tsh (tarray tuint 16) (map Vint r) x))). (*1.5*)\n  { Time entailer!. (*2.5*) Exists (list_repeat 16 Vundef). Time entailer!. (*0.1*) }\n  { rename H into J. rename i0 into j.\n    Intros wlist. rename H into WCONT.\n    destruct (Znth_mapVint r ((5 * j + 4 * 0) mod 16)) as [t0 T0].\n      rewrite RZL; apply Z_mod_lt; omega.\n    destruct (Znth_mapVint r ((5 * j + 4 * 1) mod 16)) as [t1 T1].\n      rewrite RZL; apply Z_mod_lt; omega.\n    destruct (Znth_mapVint r ((5 * j + 4 * 2) mod 16)) as [t2 T2].\n      rewrite RZL; apply Z_mod_lt; omega.\n    destruct (Znth_mapVint r ((5 * j + 4 * 3) mod 16)) as [t3 T3].\n      rewrite RZL; apply Z_mod_lt; omega. \n    eapply semax_post_flipped'.\n    apply (Jbody _ FR c k h nonce out w x y t i j r I J wlist _ _ _ _ T0 T1 T2 T3).\n    Intros W. Exists W.\n    Time entailer!. (*6.1*) (*TODO: eliminate old_go_lower*)\n    rewrite Z.add_comm, Z2Nat.inj_add; try omega.\n    assert (X: (Z.to_nat 1 + Z.to_nat j = S (Z.to_nat j))%nat) by reflexivity.\n    rewrite X. simpl. split. assumption.\n    exists t0, t1, t2, t3. simpl in T0, T1, T2, T3. rewrite Z2Nat.id, T0, T1, T2, T3.\n    repeat split; trivial.\n    exists wlist. split; trivial. omega. }\n\n  Intros wlist. rename H into HW.\n  destruct (WWI _ _ HW RZL) as [wints [WI SNUFF]]. subst wlist.\n  freeze [0;1] FR2.\n  eapply semax_post_flipped'.\n  apply (array_copy3 _ (FRZL FR2) c k h nonce out\n                  i w x y t (map Vint r) (map Vint wints)); trivial.\n           intros. apply Znth_mapVint.\n              destruct (snuffleRound_length _ _ SNUFF) as [WL _].\n              rewrite Zlength_correct, WL; simpl; omega.\n  Exists wints. rewrite Z.add_comm, Z2Nat.inj_add; try omega.\n  Time entailer!. (*4.3*)(*TODO: eliminate old_go_lower*)\n  rewrite SnuffleS, R; trivial.\n  thaw FR2; cancel. }\n apply ENTAIL_refl.\nTime Qed. (*June4th, 2017 (laptop): Finished transaction in 1.781 secs (1.072u,0.028s) (successful)*)", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/tweetnacl20140427/verif_fcore_loop3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.22667057818712574}}
{"text": "Require Export Program.Basics. Open Scope program_scope.\nFrom Paco Require Import paco.\nFrom Paco Require Import paconotation_internal paco_internal pacotac_internal.\nFrom Paco Require Export paconotation.\nFrom Fairness Require Import pind_internal.\nSet Implicit Arguments.\n\nSection PIND8.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.\nVariable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.\nVariable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.\nVariable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.\nVariable T7 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5), Type.\n\n(** ** Predicates of Arity 8\n*)\n\nDefinition pind8(gf : rel8 T0 T1 T2 T3 T4 T5 T6 T7 -> rel8 T0 T1 T2 T3 T4 T5 T6 T7)(r: rel8 T0 T1 T2 T3 T4 T5 T6 T7) : rel8 T0 T1 T2 T3 T4 T5 T6 T7 :=\n  @curry8 T0 T1 T2 T3 T4 T5 T6 T7 (pind (fun R0 => @uncurry8 T0 T1 T2 T3 T4 T5 T6 T7 (gf (@curry8 T0 T1 T2 T3 T4 T5 T6 T7 R0))) (@uncurry8 T0 T1 T2 T3 T4 T5 T6 T7 r)).\n\nDefinition upind8(gf : rel8 T0 T1 T2 T3 T4 T5 T6 T7 -> rel8 T0 T1 T2 T3 T4 T5 T6 T7)(r: rel8 T0 T1 T2 T3 T4 T5 T6 T7) := pind8 gf r /8\\ r.\nArguments pind8 : clear implicits.\nArguments upind8 : clear implicits.\n#[local] Hint Unfold upind8 : core.\n\nLemma monotone8_inter (gf gf': rel8 T0 T1 T2 T3 T4 T5 T6 T7 -> rel8 T0 T1 T2 T3 T4 T5 T6 T7)\n      (MON1: monotone8 gf)\n      (MON2: monotone8 gf'):\n  monotone8 (gf /9\\ gf').\nProof.\n  red; intros. destruct IN. split; eauto.\nQed.\n\nLemma _pind8_mon_gen (gf gf': rel8 T0 T1 T2 T3 T4 T5 T6 T7 -> rel8 T0 T1 T2 T3 T4 T5 T6 T7) r r'\n    (LEgf: gf <9= gf')\n    (LEr: r <8= r'):\n  pind8 gf r <8== pind8 gf' r'.\nProof.\n  apply curry_map8. red; intros. eapply pind_mon_gen. apply PR.\n  - intros. apply LEgf, PR0.\n  - intros. apply LEr, PR0.\nQed.\n\nLemma pind8_mon_gen (gf gf': rel8 T0 T1 T2 T3 T4 T5 T6 T7 -> rel8 T0 T1 T2 T3 T4 T5 T6 T7) r r' x0 x1 x2 x3 x4 x5 x6 x7\n    (REL: pind8 gf r x0 x1 x2 x3 x4 x5 x6 x7)\n    (LEgf: gf <9= gf')\n    (LEr: r <8= r'):\n  pind8 gf' r' x0 x1 x2 x3 x4 x5 x6 x7.\nProof.\n  eapply _pind8_mon_gen; [apply LEgf | apply LEr | apply REL].\nQed.\n\nLemma pind8_mon_bot (gf gf': rel8 T0 T1 T2 T3 T4 T5 T6 T7 -> rel8 T0 T1 T2 T3 T4 T5 T6 T7) r' x0 x1 x2 x3 x4 x5 x6 x7\n    (REL: pind8 gf bot8 x0 x1 x2 x3 x4 x5 x6 x7)\n    (LEgf: gf <9= gf'):\n  pind8 gf' r' x0 x1 x2 x3 x4 x5 x6 x7.\nProof.\n  eapply pind8_mon_gen; [apply REL | apply LEgf | intros; contradiction PR].\nQed.\n\nDefinition top8 { T0 T1 T2 T3 T4 T5 T6 T7} (x0: T0) (x1: T1 x0) (x2: T2 x0 x1) (x3: T3 x0 x1 x2) (x4: T4 x0 x1 x2 x3) (x5: T5 x0 x1 x2 x3 x4) (x6: T6 x0 x1 x2 x3 x4 x5) (x7: T7 x0 x1 x2 x3 x4 x5 x6) := True.\n\nLemma pind8_mon_top (gf gf': rel8 T0 T1 T2 T3 T4 T5 T6 T7 -> rel8 T0 T1 T2 T3 T4 T5 T6 T7) r x0 x1 x2 x3 x4 x5 x6 x7\n    (REL: pind8 gf r x0 x1 x2 x3 x4 x5 x6 x7)\n    (LEgf: gf <9= gf'):\n  pind8 gf' top8 x0 x1 x2 x3 x4 x5 x6 x7.\nProof.\n  eapply pind8_mon_gen; eauto. red. auto.\nQed.\n\nLemma upind8_mon_gen (gf gf': rel8 T0 T1 T2 T3 T4 T5 T6 T7 -> rel8 T0 T1 T2 T3 T4 T5 T6 T7) r r' x0 x1 x2 x3 x4 x5 x6 x7\n    (REL: upind8 gf r x0 x1 x2 x3 x4 x5 x6 x7)\n    (LEgf: gf <9= gf')\n    (LEr: r <8= r'):\n  upind8 gf' r' x0 x1 x2 x3 x4 x5 x6 x7.\nProof.\n  destruct REL. split; eauto.\n  eapply pind8_mon_gen; [apply H | apply LEgf | apply LEr].\nQed.\n\nLemma upind8_mon_bot (gf gf': rel8 T0 T1 T2 T3 T4 T5 T6 T7 -> rel8 T0 T1 T2 T3 T4 T5 T6 T7) r' x0 x1 x2 x3 x4 x5 x6 x7\n    (REL: upind8 gf bot8 x0 x1 x2 x3 x4 x5 x6 x7)\n    (LEgf: gf <9= gf'):\n  upind8 gf' r' x0 x1 x2 x3 x4 x5 x6 x7.\nProof.\n  eapply upind8_mon_gen; [apply REL | apply LEgf | intros; contradiction PR].\nQed.\n\nLemma upind8mon_top (gf gf': rel8 T0 T1 T2 T3 T4 T5 T6 T7 -> rel8 T0 T1 T2 T3 T4 T5 T6 T7) r x0 x1 x2 x3 x4 x5 x6 x7\n    (REL: upind8 gf r x0 x1 x2 x3 x4 x5 x6 x7)\n    (LEgf: gf <9= gf'):\n  upind8 gf' top8 x0 x1 x2 x3 x4 x5 x6 x7.\nProof.\n  eapply upind8_mon_gen; eauto. red. auto.\nQed.\n\nSection Arg8.\n\nVariable gf : rel8 T0 T1 T2 T3 T4 T5 T6 T7 -> rel8 T0 T1 T2 T3 T4 T5 T6 T7.\nArguments gf : clear implicits.\n\nTheorem _pind8_mon: _monotone8 (pind8 gf).\nProof.\n  red; intros. eapply curry_map8, _pind_mon; apply uncurry_map8; assumption.\nQed.\n\nTheorem _pind8_acc: forall\n  l r (OBG: forall rr (DEC: rr <8== r) (IH: rr <8== l), pind8 gf rr <8== l),\n  pind8 gf r <8== l.\nProof.\n  intros. apply curry_adjoint2_8.\n  eapply _pind_acc. intros.\n  apply curry_adjoint2_8 in DEC. apply curry_adjoint2_8 in IH.\n  apply curry_adjoint1_8.\n  eapply le8_trans. 2: eapply (OBG _ DEC IH).\n  apply curry_map8.\n  apply _pind_mon; try apply le1_refl; apply curry_bij2_8.\nQed.\n\nTheorem _pind8_mult_strong: forall r,\n  pind8 gf r <8== pind8 gf (upind8 gf r).\nProof.\n  intros. apply curry_map8.\n  eapply le1_trans; [eapply _pind_mult_strong |].\n  apply _pind_mon; intros [] H. apply H.\nQed.\n\nTheorem _pind8_fold: forall r,\n  gf (upind8 gf r) <8== pind8 gf r.\nProof.\n  intros. apply uncurry_adjoint1_8.\n  eapply le1_trans; [| apply _pind_fold]. apply le1_refl.\nQed.\n\nTheorem _pind8_unfold: forall (MON: _monotone8 gf) r,\n  pind8 gf r <8== gf (upind8 gf r).\nProof.\n  intros. apply curry_adjoint2_8.\n  eapply _pind_unfold; apply monotone8_map; assumption.\nQed.\n\nTheorem pind8_acc: forall\n  l r (OBG: forall rr (DEC: rr <8= r) (IH: rr <8= l), pind8 gf rr <8= l),\n  pind8 gf r <8= l.\nProof.\n  apply _pind8_acc.\nQed.\n\nTheorem pind8_mon: monotone8 (pind8 gf).\nProof.\n  apply monotone8_eq.\n  apply _pind8_mon.\nQed.\n\nTheorem upind8_mon: monotone8 (upind8 gf).\nProof.\n  red; intros.\n  destruct IN. split; eauto.\n  eapply pind8_mon. apply H. apply LE.\nQed.\n\nTheorem pind8_mult_strong: forall r,\n  pind8 gf r <8= pind8 gf (upind8 gf r).\nProof.\n  apply _pind8_mult_strong.\nQed.\n\nCorollary pind8_mult: forall r,\n  pind8 gf r <8= pind8 gf (pind8 gf r).\nProof. intros; eapply pind8_mult_strong in PR. eapply pind8_mon; eauto. intros. destruct PR0. eauto. Qed.\n\nTheorem pind8_fold: forall r,\n  gf (upind8 gf r) <8= pind8 gf r.\nProof.\n  apply _pind8_fold.\nQed.\n\nTheorem pind8_unfold: forall (MON: monotone8 gf) r,\n  pind8 gf r <8= gf (upind8 gf r).\nProof.\n  intro. eapply _pind8_unfold; apply monotone8_eq; assumption.\nQed.\n\nEnd Arg8.\n\nArguments pind8_acc : clear implicits.\nArguments pind8_mon : clear implicits.\nArguments upind8_mon : clear implicits.\nArguments pind8_mult_strong : clear implicits.\nArguments pind8_mult : clear implicits.\nArguments pind8_fold : clear implicits.\nArguments pind8_unfold : clear implicits.\n\nEnd PIND8.\n\nGlobal Opaque pind8.\n\n#[export] Hint Unfold upind8 : core.\n#[export] Hint Resolve pind8_fold : core.\n#[export] Hint Unfold monotone8 : core.\n\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/pico/pind8.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.22667057818712574}}
{"text": "Require Export cd.\n\nRequire Export String ListSet List Arith Bool. \nOpen Scope nat_scope.\nOpen Scope type_scope.\nOpen Scope string_scope.\nOpen Scope list_scope.\nImport ListNotations.\n\n\n(* ----- intergrate two class ------- *)\nParameter R : Class -> Class -> Class -> list Assoc.\n\nParameter CA : Class -> Class -> asKind -> Assoc.\n\n\nDefinition CreateAsEnd (c : Class) :=\n  BAsEnd \"_\" c (Nat 0, Star).\n\n\nDefinition CreateAssoc (ne : NamedElement) (c1 c2 : Class) :=\n  BAssoc ne none (CreateAsEnd c1, CreateAsEnd c2).\n\nInductive refineone : SimpleUML -> SimpleUML -> Prop :=\n| import:  forall c' ci cj C T P S G,\n    not (set_In c' C) -> \n    set_In ci C /\\ set_In cj C ->\n    let C' := (c':: C) in\n    let S' := set_union eqAssoc_dec (R ci cj c') S in\n    refineone (mkSimpleUML C T P S G) (mkSimpleUML C' T P S' G)\n| dec1: forall c' ci C T P S G,\n    not (set_In c' C) -> \n    set_In ci C ->\n    let C' := (c':: C) in\n    let G' := (BGen ci c') :: G in \n    refineone (mkSimpleUML C T P S G) (mkSimpleUML C' T P S G')\n| dec2 : forall c' ci C T P S G,\n    not (set_In c' C) ->\n    set_In ci C ->\n    let C' := (c' :: C) in\n    let S' := (CA c' ci composite) :: S in\n    refineone (mkSimpleUML C T P S G) (mkSimpleUML C' T P S' G)\n| dec3 : forall c' ci C T P S G,\n    not (set_In c' C) ->\n    set_In ci C ->\n    let C' := (c' :: C) in\n    let S' := (CA c' ci aggregate) :: S in\n    refineone (mkSimpleUML C T P S G) (mkSimpleUML C' T P S' G)\n| intro1 : forall c' ci C T P S G,\n    not (set_In c' C) ->\n    set_In ci C ->\n    let C' := (c' :: C) in\n    let S' := (CA c' ci none) :: S in\n    refineone (mkSimpleUML C T P S G) (mkSimpleUML C' T P S' G)\n| intro2 : forall c' ci C T P S G,\n    not (set_In c' C) ->\n    set_In ci C ->\n    let C' := (c' :: C) in\n    let S' := (CA c' ci directed) :: S in\n    refineone (mkSimpleUML C T P S G) (mkSimpleUML C' T P S' G)\n.\n\n\nInductive refine : SimpleUML -> SimpleUML -> Prop :=\n| one : forall m1 m2, \n    refineone m1 m2 -> refine m1 m2\n| reflex : forall m, \n    refine m m\n| trans : forall m1 m2 m3, \n    refine m1 m2 -> refine m2 m3 -> refine m1 m3\n.\n\nTheorem wellFormed_preserve :\n  forall m1 m2, \n    WellFormed m1 -> \n    refineone m1 m2 ->\n    WellFormed m2.\nProof.\n  intros m1 m2 H1 H2.\n  inversion H1. unfold UniqueClass in H.\n  inversion H2; subst; simpl in H.\nAdmitted.\n\nRequire Import Relations.\n\n\nTheorem refine_refl :\n   reflexive _  refine.\nProof.\n  unfold reflexive. \n  intro x. apply reflex.\nQed.\n\n\nTheorem refine_trans :\n  transitive _ refine.\nProof.\n  unfold transitive.\n  intros x y z. apply trans.\nQed.\n\n\nTheorem class_preserve :\n  forall c m1 m2, \n    refineone m1 m2 ->\n    set_In c (MClass_Instance m1) ->\n    set_In c (MClass_Instance m2).\nProof.\n  intros c m1 m2 H.\n  induction H; intros H1; simpl;\n    simpl in H1; right; assumption.\nQed.\n\n\nTheorem gen_preserve :\n  forall sub super m1 m2, \n    refineone m1 m2 ->\n    set_In (BGen super sub) (MGen_Instance m1) ->\n    set_In (BGen super sub) (MGen_Instance m2).\nProof.\n  intros sub super m1 m2 H.\n  induction H; intros H1; simpl in H1; simpl; try assumption.\n  - right; assumption.\nQed.", "meta": {"author": "shengfeng", "repo": "classdiagram", "sha": "10c5e69cfa07da418e29407c3af07adf909caba5", "save_path": "github-repos/coq/shengfeng-classdiagram", "path": "github-repos/coq/shengfeng-classdiagram/classdiagram-10c5e69cfa07da418e29407c3af07adf909caba5/src/refinement2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.22663956307116165}}
{"text": "(* Copyright (c) 2011. Greg Morrisett, Gang Tan, Joseph Tassarotti, \n   Jean-Baptiste Tristan, and Edward Gan.\n\n   This file is part of RockSalt.\n\n   This file is free software; you can redistribute it and/or\n   modify it under the terms of the GNU General Public License as\n   published by the Free Software Foundation; either version 2 of\n   the License, or (at your option) any later version.\n*)\n\nRequire ExtrOcamlString.\nRequire ExtrOcamlNatBigInt.\nRequire ExtrOcamlZBigInt.\nRequire Import List.\nRequire Import Bits.\nRequire Import ZArith.\nRequire Import Parser.\nRequire Import Decode.\nRequire Import String.\nRequire Import Monad.\nRequire Import Maps.\nRequire Import X86Syntax.\nRequire Import RTL.\nSet Implicit Arguments.\nUnset Automatic Introduction.\n\nModule X86_MACHINE.\n  Local Open Scope Z_scope.\n  Local Open Scope string_scope.\n\n  Definition size_addr := size32.\n  Inductive flag : Set := ID | VIP | VIF | AC | VM | RF | NT | IOPL | OF | DF \n  | IF_flag | TF | SF | ZF | AF | PF | CF.\n\n  Definition flag_eq_dec : forall(f1 f2:flag), {f1=f2}+{f1<>f2}.\n    intros ; decide equality. Defined.\n\n  Inductive loc : nat -> Set := \n  | reg_loc : register -> loc size32\n  | seg_reg_start_loc : segment_register -> loc size32\n  | seg_reg_limit_loc : segment_register -> loc size32\n  | flag_loc : flag -> loc size1\n  | control_register_loc : control_register -> loc size32\n  | debug_register_loc : debug_register -> loc size32\n  | pc_loc : loc size32.\n  Definition location := loc.\n\n  Definition fmap (A B:Type) := A -> B.\n  Definition upd A (eq_dec:forall (x y:A),{x=y}+{x<>y}) B (f:fmap A B) (x:A) (v:B) : \n    fmap A B := fun y => if eq_dec x y then v else f y.\n  Definition look A B (f:fmap A B) (x:A) : B := f x.\n\n  Record mach := { \n    gp_regs : fmap register int32 ; \n    seg_regs_starts : fmap segment_register int32 ; \n    seg_regs_limits : fmap segment_register int32 ; \n    flags_reg : fmap flag int1 ; \n    control_regs : fmap control_register int32 ; \n    debug_regs : fmap debug_register int32 ; \n    pc_reg : wint size32 \n  }.\n  Definition mach_state := mach.\n\n  Definition get_location s (l:loc s) (m:mach_state) : wint s := \n    match l in loc s' return wint s' with \n      | reg_loc r => look (gp_regs m) r\n      | seg_reg_start_loc r => look (seg_regs_starts m) r\n      | seg_reg_limit_loc r => look (seg_regs_limits m) r\n      | flag_loc f => look (flags_reg m) f\n      | control_register_loc r => look (control_regs m) r\n      | debug_register_loc r => look (debug_regs m) r\n      | pc_loc => pc_reg m\n    end.\n\n  Definition set_gp_regs r v m := \n    {| gp_regs := upd register_eq_dec (gp_regs m) r v ; \n       seg_regs_starts := seg_regs_starts m ; \n       seg_regs_limits := seg_regs_limits m ;\n       flags_reg := flags_reg m ;\n       control_regs := control_regs m; \n       debug_regs := debug_regs m; \n       pc_reg := pc_reg m \n    |}.\n\n  Definition set_seg_regs_starts r v m := \n    {| gp_regs := gp_regs m ;\n       seg_regs_starts := upd segment_register_eq_dec (seg_regs_starts m) r v ; \n       seg_regs_limits := seg_regs_limits m ;\n       flags_reg := flags_reg m ;\n       control_regs := control_regs m; \n       debug_regs := debug_regs m; \n       pc_reg := pc_reg m \n    |}.\n\n  Definition set_seg_regs_limits r v m := \n    {| gp_regs := gp_regs m ;\n       seg_regs_starts := seg_regs_starts m ;\n       seg_regs_limits := upd segment_register_eq_dec (seg_regs_limits m) r v ; \n       flags_reg := flags_reg m ;\n       control_regs := control_regs m; \n       debug_regs := debug_regs m; \n       pc_reg := pc_reg m \n    |}.\n\n  Definition set_flags_reg r v m := \n    {| gp_regs := gp_regs m ;\n       seg_regs_starts := seg_regs_starts m ;\n       seg_regs_limits := seg_regs_limits m ;\n       flags_reg := upd flag_eq_dec (flags_reg m) r v ;\n       control_regs := control_regs m; \n       debug_regs := debug_regs m; \n       pc_reg := pc_reg m \n    |}.\n\n  Definition set_control_regs r v m := \n    {| gp_regs := gp_regs m ;\n       seg_regs_starts := seg_regs_starts m ;\n       seg_regs_limits := seg_regs_limits m ;\n       flags_reg := flags_reg m ; \n       control_regs := upd control_register_eq_dec (control_regs m) r v ;\n       debug_regs := debug_regs m; \n       pc_reg := pc_reg m \n    |}.\n\n  Definition set_debug_regs r v m := \n    {| gp_regs := gp_regs m ;\n       seg_regs_starts := seg_regs_starts m ;\n       seg_regs_limits := seg_regs_limits m ;\n       flags_reg := flags_reg m ; \n       control_regs := control_regs m ;\n       debug_regs := upd debug_register_eq_dec (debug_regs m) r v ;\n       pc_reg := pc_reg m \n    |}.\n\n  Definition set_pc v m := \n    {| gp_regs := gp_regs m ;\n       seg_regs_starts := seg_regs_starts m ;\n       seg_regs_limits := seg_regs_limits m ;\n       flags_reg := flags_reg m ; \n       control_regs := control_regs m ;\n       debug_regs := debug_regs m ; \n       pc_reg := v\n    |}.\n\n  Definition set_location s (l:loc s) (v:wint s) m := \n    match l in loc s' return wint s' -> mach_state with \n      | reg_loc r => fun v => set_gp_regs r v m\n      | seg_reg_start_loc r => fun v => set_seg_regs_starts r v m\n      | seg_reg_limit_loc r => fun v => set_seg_regs_limits r v m\n      | flag_loc f => fun v => set_flags_reg f v m\n      | control_register_loc r => fun v => set_control_regs r v m\n      | debug_register_loc r => fun v => set_debug_regs r v m\n      | pc_loc => fun v => set_pc v m\n    end v.\nEnd X86_MACHINE.\n\nModule X86_RTL := RTL.RTL(X86_MACHINE).\n\nModule X86_Decode.\n  Import X86_MACHINE.\n  Import X86_RTL.\n  Local Open Scope monad_scope.\n  Record conv_state := { c_rev_i : list rtl_instr ; c_next : Z }.\n  Definition Conv(T:Type) := conv_state -> T * conv_state.\n  Instance Conv_monad : Monad Conv := {\n    Return := fun A (x:A) (s:conv_state) => (x,s) ; \n    Bind := fun A B (c:Conv A) (f:A -> Conv B) (s:conv_state) => \n      let (v,s') := c s in f v s'\n  }.\n  intros ; apply Coqlib.extensionality ; auto.\n  intros ; apply Coqlib.extensionality ; intros. destruct (c x). auto.\n  intros ; apply Coqlib.extensionality ; intros. destruct (f x) ; auto. \n  Defined.\n  Definition runConv (c:Conv unit) : (list rtl_instr) := \n    match c {|c_rev_i := nil ; c_next:=0|} with \n      | (_, c') => (List.rev (c_rev_i c'))\n    end.\n  Definition EMIT(i:rtl_instr) : Conv unit := \n    fun s => (tt,{|c_rev_i := i::(c_rev_i s) ; c_next := c_next s|}).\n  Notation \"'emit' i\" := (EMIT i) (at level 75) : monad_scope.\n  Definition fresh s (almost_i : pseudo_reg s -> rtl_instr) : Conv (pseudo_reg s) := \n    fun ts => let r := c_next ts in \n              let ts' := {|c_rev_i := (almost_i (ps_reg s r))::c_rev_i ts ; \n                           c_next := r + 1|} in \n                (ps_reg s r, ts').\n\n  Definition load_Z s (i:Z) := fresh (load_imm_rtl (@Word.repr s i)).\n  Definition load_int s (i:wint s) := fresh (load_imm_rtl i).\n  Definition arith s b (r1 r2:pseudo_reg s) := fresh (arith_rtl b r1 r2).\n  Definition test s t (r1 r2:pseudo_reg s) := fresh (test_rtl t r1 r2).\n  Definition load_reg (r:register) := fresh (get_loc_rtl (reg_loc r)).\n  Definition set_reg (p:pseudo_reg size32) (r:register) := \n    emit set_loc_rtl p (reg_loc r).\n  Definition cast_u s1 s2 (r:pseudo_reg s1) := fresh (@cast_u_rtl s1 s2 r).\n  Definition cast_s s1 s2 (r:pseudo_reg s1) := fresh (@cast_s_rtl s1 s2 r).\n  Definition get_seg_start (s:segment_register) := \n    fresh (get_loc_rtl (seg_reg_start_loc s)).\n  Definition get_seg_limit (s:segment_register) := \n    fresh (get_loc_rtl (seg_reg_limit_loc s)).\n  Definition read_byte (a:pseudo_reg size32) := fresh (get_byte_rtl a).\n  Definition write_byte (v:pseudo_reg size8) (a:pseudo_reg size32) := \n    emit set_byte_rtl v a.\n  Definition get_flag fl := fresh (get_loc_rtl (flag_loc fl)).\n  Definition set_flag fl (r: pseudo_reg size1) := emit set_loc_rtl r (flag_loc fl). \n\n  Definition get_pc := fresh (get_loc_rtl pc_loc).\n  Definition set_pc v := emit set_loc_rtl v pc_loc.\n  Definition not {s} (p: pseudo_reg s) : Conv (pseudo_reg s) :=\n    mask <- load_Z s (Word.max_unsigned s);\n    arith xor_op p mask.\n  Definition undef_flag (f: flag) :=\n    ps <- fresh (@choose_rtl size1);\n    set_flag f ps.\n\n  (* Copy the contents of rs to a new pseudo register *)\n  Definition copy_ps s (rs:pseudo_reg s) := fresh (@cast_u_rtl s s rs).\n\n  Definition scale_to_int32(s:scale) : int32 :=\n    Word.repr match s with | Scale1 => 1 | Scale2 => 2 | Scale4 => 4 | Scale8 => 8 end.\n\n  (* compute an effective address *)\n  Definition compute_addr(a:address) : Conv (pseudo_reg size32) := \n    let disp := addrDisp a in \n      match addrBase a, addrIndex a with \n        | None, None => load_int disp \n        | Some r, None => \n          p1 <- load_reg r ; p2 <- load_int disp ; arith add_op p1 p2\n        | Some r1, Some (s, r2) =>\n          b <- load_reg r1;\n          i <- load_reg r2;\n          s <- load_int (scale_to_int32 s);\n          p0 <- arith mul_op i s;\n          p1 <- arith add_op b p0;\n          disp <- load_int disp;\n          arith add_op p1 disp\n        | None, Some (s, r) => \n          i <- load_reg r;\n          s <- load_int (scale_to_int32 s);\n          disp <- load_int disp;\n          p0 <- arith mul_op i s;\n          arith add_op disp p0\n      end.\n\n\n  (* check that the addr is not greater the segment_limit, and then \n     add the specified segment base *)\n  Definition add_and_check_segment (seg:segment_register) (a:pseudo_reg size32) : \n    Conv (pseudo_reg size32) := \n    p1 <- get_seg_start seg ; \n    p2 <- arith add_op p1 a ;\n    p3 <- get_seg_limit seg ;\n    guard <- test ltu_op p3 a;\n    emit if_rtl guard safe_fail_rtl;;\n    ret p2.\n\n  (* load a byte from memory, taking into account the specified segment *)\n  Definition lmem (seg:segment_register) (a:pseudo_reg size32) : Conv (pseudo_reg size8):=\n    p <- add_and_check_segment seg a ; \n    read_byte p.\n\n  (* store a byte to memory, taking into account the specified segment *)\n  Definition smem (seg:segment_register) (v:pseudo_reg size8) (a:pseudo_reg size32) :\n    Conv unit := \n    p <- add_and_check_segment seg a ; \n    write_byte v p.\n\n  (* load an n-byte vector from memory -- takes into account the segment *)\n  Program Fixpoint load_mem_n (seg:segment_register) (addr:pseudo_reg size32)\n    (nbytes_minus_one:nat) : Conv (pseudo_reg ((nbytes_minus_one+1) * 8 -1)%nat) := \n    match nbytes_minus_one with \n      | 0 => lmem seg addr\n      | S n => \n        rec <- load_mem_n seg addr n ; \n        count <- load_Z size32 (Z_of_nat (S n)) ; \n        p3 <- arith add_op addr count ;\n        nb <- lmem seg p3 ; \n        p5 <- cast_u ((nbytes_minus_one + 1)*8-1)%nat rec ; \n        p6 <- cast_u ((nbytes_minus_one + 1)*8-1)%nat nb ;\n        p7 <- load_Z _ (Z_of_nat (S n) * 8) ;\n        p8 <- arith shl_op p6 p7 ;\n        arith or_op p5 p8\n    end.\n\n  Definition load_mem32 (seg:segment_register) (addr:pseudo_reg size32) := \n    load_mem_n seg addr 3.\n\n\n  (*Definition load_mem32 (seg: segment_register) (addr: pseudo_reg size32) :=\n    b0 <- lmem seg addr;\n    one <- load_Z size32 1;\n    addr1 <- arith add_op addr one;\n    b1 <- lmem seg addr1;\n    addr2 <- arith add_op addr1 one;\n    b2 <- lmem seg addr2;\n    addr3 <- arith add_op addr2 one;\n    b3 <- lmem seg addr3;\n\n    w0 <- cast_u size32 b0;\n    w1 <- cast_u size32 b1;\n    w2 <- cast_u size32 b2;\n    w3 <- cast_u size32 b3;\n    eight <- load_Z size32 8;\n    r0 <- arith shl_op w3 eight;\n    r1 <- arith or_op r0 w2;\n    r2 <- arith shl_op r1 eight;\n    r3 <- arith or_op r2 w1;\n    r4 <- arith shl_op r3 eight;\n    arith or_op r4 w0.*)\n    \n\n  Definition load_mem16 (seg:segment_register) (addr:pseudo_reg size32) := \n    load_mem_n seg addr 1.\n  Definition load_mem8 (seg:segment_register) (addr:pseudo_reg size32) := \n    load_mem_n seg addr 0.\n\n  (* given a prefix and w bit, return the size of the operand *)\n  Definition opsize override w :=\n    match override, w with\n      | _, false => size8\n      | true, _ => size16\n      | _,_ => size32\n    end.\n\n  Definition load_mem p w (seg:segment_register) (op:pseudo_reg size32) : \n    Conv (pseudo_reg (opsize (op_override p) w)) :=\n    match (op_override p) as b,w return\n      Conv (pseudo_reg (opsize b w)) with\n      | true, true => load_mem16 seg op\n      | true, false => load_mem8 seg op\n      | false, true => load_mem32 seg op\n      | false, false => load_mem8 seg op\n    end.\n  (* load the value of an operand into a pseudo register *)\n  Definition iload_op32 (seg:segment_register) (op:operand) : Conv (pseudo_reg size32) :=\n    match op with \n      | Imm_op i => load_int i\n      | Reg_op r => load_reg r\n      | Address_op a => p1 <- compute_addr a ; load_mem32 seg p1\n      | Offset_op off => p1 <- load_int off;\n                          load_mem32 seg p1\n    end.\n\n  Definition iload_op16 (seg:segment_register) (op:operand) : Conv (pseudo_reg size16) :=\n    match op with \n      | Imm_op i => tmp <- load_int i;\n                    cast_u size16 tmp\n      | Reg_op r => tmp <- load_reg r;\n                    cast_u size16 tmp\n      | Address_op a => p1 <- compute_addr a ; load_mem16 seg p1\n      | Offset_op off => p1 <- load_int off;\n                          load_mem16 seg p1\n    end.\n\n  (* This is a little strange because actually for example, ESP here should refer\n     to AH, EBP to CH, ESI to DH, and EDI to BH *) \n\n  Definition iload_op8 (seg:segment_register) (op:operand) : Conv (pseudo_reg size8) :=\n    match op with \n      | Imm_op i => tmp <- load_int i;\n                    cast_u size8 tmp\n      | Reg_op r =>\n         tmp <- load_reg (match r with\n                            | EAX => EAX\n                            | ECX => ECX\n                            | EDX => EDX\n                            | EBX => EBX\n                            | ESP => EAX\n                            | EBP => ECX\n                            | ESI => EDX\n                            | EDI => EBX\n                          end);\n         (match r with\n            | EAX | ECX | EDX | EBX => cast_u size8 tmp\n            | _ =>  eight <- load_Z size32 8;\n                    tmp2 <- arith shru_op tmp eight;\n                    cast_u size8 tmp2\n          end)\n      | Address_op a => p1 <- compute_addr a ; load_mem8 seg p1\n      | Offset_op off =>  p1 <- load_int off;\n                          load_mem8 seg p1\n    end.\n\n  (* set memory with an n-byte vector *)\n  Program Fixpoint set_mem_n {t} (seg:segment_register)\n    (v: pseudo_reg (8*(t+1)-1)%nat) (addr : pseudo_reg size32) : Conv unit := \n    match t with \n      | 0 => smem seg v addr\n      | S u => \n        p1 <- cast_u (8*(u+1)-1)%nat v ; \n        set_mem_n seg p1 addr ;; \n        p2 <- load_Z (8*(t+1)-1)%nat (Z_of_nat  ((S u) * 8)) ; \n        p3 <- arith shru_op v p2 ;\n        p4 <- cast_u size8 p3 ; \n        p5 <- load_Z size32 (Z_of_nat (S u)) ; \n        p6 <- arith add_op p5 addr ;\n        smem seg p4 p6\n    end.\n\n  Definition set_mem32 (seg:segment_register) (v a:pseudo_reg size32) : Conv unit :=\n    @set_mem_n 3 seg v a.\n\n  (*Definition set_mem32 (seg: segment_register) (v a: pseudo_reg size32) : Conv unit := \n    b0 <- cast_u size8 v;\n    smem seg b0 a;;\n    eight <- load_Z size32 8;\n    one <- load_Z size32 1;\n    v1 <- arith shru_op v eight;\n    b1 <- cast_u size8 v1;\n    addr1 <- arith add_op a one;\n    smem seg b1 addr1;;\n    v2 <- arith shru_op v1 eight;\n    b2 <- cast_u size8 v2;\n    addr2 <- arith add_op addr1 one;\n    smem seg b2 addr2;;\n    v3 <- arith shru_op v2 eight;\n    b3 <- cast_u size8 v3;\n    addr3 <- arith add_op addr2 one;\n    smem seg b3 addr3.*)\n    \n\n  Definition set_mem16 (seg:segment_register) (v: pseudo_reg size16)\n    (a:pseudo_reg size32) : Conv unit :=\n      @set_mem_n 1 seg v a.\n\n  Definition set_mem8 (seg:segment_register) (v: pseudo_reg size8) \n    (a:pseudo_reg size32) : Conv unit :=\n      @set_mem_n 0 seg v a.\n\n Definition set_mem p w (seg:segment_register) : pseudo_reg (opsize (op_override p) w) ->\n    pseudo_reg size32 -> \n    Conv unit :=\n    match (op_override p) as b,w return\n      pseudo_reg (opsize b w) -> pseudo_reg size32 -> Conv unit with\n      | true, true => set_mem16 seg\n      | true, false => set_mem8 seg\n      | false, true => set_mem32 seg\n      | false, false => set_mem8 seg\n    end.\n  (* update an operand *)\n  Definition iset_op32 (seg:segment_register) (p:pseudo_reg size32) (op:operand) :\n    Conv unit := \n    match op with \n      | Imm_op _ => emit error_rtl\n      | Reg_op r => set_reg p r\n      | Address_op a => addr <- compute_addr a ; set_mem32 seg p addr\n      | Offset_op off => addr <- load_int off;\n                           set_mem32 seg p addr\n    end.\n\n  Definition iset_op16 (seg:segment_register) (p:pseudo_reg size16) (op:operand) :\n    Conv unit := \n    match op with \n      | Imm_op _ => emit error_rtl\n      | Reg_op r => tmp <- load_reg r;\n                    mask <- load_int (Word.mone size32);\n                    sixteen <- load_Z size32 16;\n                    mask2 <- arith shl_op mask sixteen ;\n                    tmp2  <- arith and_op mask2 tmp;\n                    p32 <- cast_u size32 p;\n                    tmp3 <- arith or_op tmp2 p32;\n                    set_reg tmp3 r\n      | Address_op a => addr <- compute_addr a ; set_mem16 seg p addr\n      | Offset_op off => addr <- load_int off;\n                           set_mem16 seg p addr\n    end.\n\n  Definition iset_op8 (seg:segment_register) (p:pseudo_reg size8) (op:operand) :\n    Conv unit := \n    match op with \n      | Imm_op _ => emit error_rtl\n      | Reg_op r => tmp0 <- load_reg \n                         (match r with\n                            | EAX => EAX\n                            | ECX => ECX\n                            | EDX => EDX\n                            | EBX => EBX\n                            | ESP => EAX\n                            | EBP => ECX\n                            | ESI => EDX\n                            | EDI => EBX\n                          end);\n                    shift <- load_Z size32\n                             (match r with\n                                | EAX | ECX | EDX | EBX => 0\n                                | _ => 8\n                              end);\n                    mone <- load_int (Word.mone size32);\n                    mask0 <-load_Z size32 255;\n                    mask1 <- arith shl_op mask0 shift;\n                    mask2 <- arith xor_op mask1 mone;\n                    tmp1 <- arith and_op tmp0 mask2;\n                    pext <- cast_u size32 p;\n                    pext_shift <- arith shl_op pext shift;\n                    res <- arith or_op tmp1 pext_shift;\n                    set_reg res\n                         (match r with\n                            | EAX => EAX\n                            | ECX => ECX\n                            | EDX => EDX\n                            | EBX => EBX\n                            | ESP => EAX\n                            | EBP => ECX\n                            | ESI => EDX\n                            | EDI => EBX\n                          end)\n      | Address_op a => addr <- compute_addr a ; set_mem8 seg p addr\n      | Offset_op off => addr <- load_int off;\n                           set_mem8 seg p addr\n    end.\n  (* given a prefix and w bit, return the appropriate load function for the\n     corresponding operand size *)\n  Definition load_op p w (seg:segment_register) (op:operand)\n    : Conv (pseudo_reg (opsize (op_override p) w)) :=\n    match op_override p as b, w return \n      Conv (pseudo_reg (opsize b w)) with\n      | true, true => iload_op16 seg op\n      | true, false => iload_op8 seg op\n      | false, true => iload_op32 seg op\n      | false, false => iload_op8 seg op\n    end.\n\n  Definition set_op p w (seg:segment_register) :\n     pseudo_reg (opsize (op_override p) w) -> operand -> Conv unit :=\n    match op_override p as b, w \n      return pseudo_reg (opsize b w) -> operand -> Conv unit with\n      | true, true => iset_op16 seg \n      | true, false => iset_op8 seg\n      | false, true => iset_op32 seg \n      | false, false => iset_op8 seg\n    end.\n  \n  (* given a prefix, get the override segment and if none is specified return def *)\n  Definition get_segment (p:prefix) (def:segment_register) : segment_register := \n    match seg_override p with \n      | Some s => s \n      | None => def\n    end.\n\n  Definition op_contains_stack (op:operand) : bool :=\n    match op with\n      |Address_op a =>\n        match (addrBase a) with\n          |Some EBP => true\n          |Some ESP => true\n          | _ => false\n        end\n      | _ => false\n    end.\n\n  (*The default segment when an operand uses ESP or EBP as a base address\n     is the SS segment*)\n  Definition get_segment_op (p:prefix) (def:segment_register) (op:operand)\n    : segment_register := \n    match seg_override p with \n      | Some s => s \n      | None => \n        match (op_contains_stack op) with\n          | true => SS\n          | false => def\n        end\n    end.\n  Definition get_segment_op2 (p:prefix) (def:segment_register) (op1:operand)\n    (op2: operand) : segment_register := \n    match seg_override p with \n      | Some s => s \n      | None => \n        match (op_contains_stack op1,op_contains_stack op2) with\n          | (true,_) => SS\n          | (_,true) => SS\n          | (false,false) => def\n        end\n    end.\n\n  Definition compute_cc (ct: condition_type) : Conv (pseudo_reg size1) :=\n    match ct with\n      | O_ct => get_flag OF\n      | NO_ct => p <- get_flag OF;\n        not p\n      | B_ct => get_flag CF\n      | NB_ct => p <- get_flag CF;\n        not p\n      | E_ct => get_flag ZF\n      | NE_ct => p <- get_flag ZF;\n        not p\n      | BE_ct => cf <- get_flag CF;\n        zf <- get_flag ZF;\n        arith or_op cf zf\n      | NBE_ct => cf <- get_flag CF;\n        zf <- get_flag ZF;\n        p <- arith or_op cf zf;\n        not p\n      | S_ct => get_flag SF\n      | NS_ct => p <- get_flag SF;\n        not p\n      | P_ct => get_flag PF\n      | NP_ct => p <- get_flag PF;\n        not p\n      | L_ct => sf <- get_flag SF;\n        of <- get_flag OF;\n        arith xor_op sf of\n      | NL_ct => sf <- get_flag SF;\n        of <- get_flag OF;\n        p <- arith xor_op sf of;\n        not p\n      | LE_ct => zf <- get_flag ZF;\n        of <- get_flag OF;\n        sf <- get_flag SF;\n        p <- arith xor_op of sf;\n        arith or_op zf p\n      | NLE_ct => zf <- get_flag ZF;\n        of <- get_flag OF;\n        sf <- get_flag SF;\n        p0 <- arith xor_op of sf;\n        p1 <- arith or_op zf p0;\n        not p1\n    end.\n\n  Fixpoint compute_parity_aux {s} op1 (op2 : pseudo_reg size1) (n: nat) :\n    Conv (pseudo_reg size1) :=\n    match n with\n      | O => @load_Z size1 0\n      | S m =>\n        op2 <- compute_parity_aux op1 op2 m;\n        one <- load_Z s 1;\n        op1 <- arith shru_op op1 one; \n        r <- cast_u size1 op1;\n        @arith size1 xor_op r op2\n    end.\n  \n  Definition compute_parity {s} op : Conv (pseudo_reg size1) := \n    r1 <- load_Z size1 0;\n    one <- load_Z size1 1;\n    p <- @compute_parity_aux s op r1 8; (* ACHTUNG *)\n    arith xor_op p one.\n\n  (**********************************************)\n  (*   Conversion functions for instructions    *)\n  (**********************************************)\n\n  (************************)\n  (* Arith ops            *)\n  (************************)\n  Definition conv_INC (pre:prefix) (w: bool) (op:operand) : Conv unit :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    let seg := get_segment_op pre DS op in \n        p0 <- load seg op ; \n        p1 <- load_Z _ 1 ; \n        p2 <- arith add_op p0 p1 ; \n        set seg p2 op;;\n\n        (* Note that CF is NOT changed by INC *)\n\n        zero <- load_Z _ 0;\n        ofp <- test lt_op p2 p0;\n        set_flag OF ofp;;\n\n        zfp <- test eq_op p2 zero;\n        set_flag ZF zfp;;\n\n        sfp <- test lt_op p2 zero;\n        set_flag SF sfp;;\n\n        pfp <- compute_parity p2;\n        set_flag PF pfp;;\n\n        n0 <- cast_u size4 p0;\n        n1 <- load_Z size4 1;\n        n2 <- arith add_op n0 n1;\n        afp <- test ltu_op n2 n0;\n        set_flag AF afp.\n\n  Definition conv_DEC (pre: prefix) (w: bool) (op: operand) : Conv unit :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    let seg := get_segment_op pre DS op in\n        p0 <- load seg op;\n        p1 <- load_Z _ 1;\n        p2 <- arith sub_op p0 p1;\n        set seg p2 op;;\n\n        (* Note that CF is NOT changed by DEC *)\n        zero <- load_Z _ 0;\n        ofp <- test lt_op p0 p2; \n        set_flag OF ofp;;\n\n        zfp <- test eq_op p2 zero;\n        set_flag ZF zfp;;\n        \n        sfp <- test lt_op p2 zero;\n        set_flag SF sfp;;\n\n        pfp <- compute_parity p2;\n        set_flag PF pfp;;\n\n        n0 <- cast_u size4 p0;\n        n1 <- load_Z size4 1;\n        n2 <- arith sub_op n0 n1;\n        afp <- test ltu_op n0 n2;\n        set_flag AF afp.\n\n  Definition conv_ADC (pre: prefix) (w: bool) (op1 op2: operand) : Conv unit :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    let seg := get_segment_op2 pre DS op1 op2 in\n        (* RTL for useful constants *)\n        zero <- load_Z _ 0;\n        up <- load_Z _ 1;\n\n        (* RTL for op1 *)\n        p0 <- load seg op1;\n        p1 <- load seg op2;\n        cf1 <- get_flag CF;\n        cfext <- cast_u _ cf1; \n        p2 <- arith add_op p0 p1;\n        p2 <- arith add_op p2 cfext;\n        set seg p2 op1;;        \n\n        (* RTL for OF *)\n        b0 <- test lt_op zero p0;\n        b1 <- test lt_op zero p1;\n        b2 <- test lt_op zero p2;\n        b3 <- @arith size1 xor_op b0 b1;\n        b3 <- @arith size1 xor_op up b3;\n        b4 <- @arith size1 xor_op b0 b2;\n        b4 <- @arith size1 and_op b3 b4;\n        set_flag OF b4;;\n\n        (* RTL for CF *)\n        b0 <- test ltu_op p2 p0;\n        b1 <- test ltu_op p2 p1;\n        b0 <- @arith size1 or_op b0 b1;\n        set_flag CF b0;;\n\n        (* RTL for ZF *)\n        b0 <- test eq_op p2 zero;\n        set_flag ZF b0;;\n\n        (* RTL for SF *)\n        b0 <- test lt_op p2 zero;\n        set_flag SF b0;;\n\n        (* RTL for PF *)\n        b0 <- compute_parity p2;\n        set_flag PF b0;;\n\n        (* RTL for AF *)\n        n0 <- cast_u size4 p0;\n        n1 <- cast_u size4 p1;\n        cf4 <- cast_u size4 cf1;\n        n2 <- @arith size4 add_op n0 n1;\n        n2 <- @arith size4 add_op n2 cf4;\n        b0 <- test ltu_op n2 n0;\n        b1 <- test ltu_op n2 n1;\n        b0 <- @arith size1 or_op b0 b1;\n        set_flag AF b0.\n\nDefinition conv_STC: Conv unit :=\n  one <- load_Z size1 1;\n  set_flag CF one.\n\nDefinition conv_STD: Conv unit :=\n  one <- load_Z size1 1;\n  set_flag DF one. \n\nDefinition conv_CLC: Conv unit :=\n  zero <- load_Z size1 0;\n  set_flag CF zero.\n\nDefinition conv_CLD: Conv unit :=\n  zero <- load_Z size1 0;\n  set_flag DF zero.\n\nDefinition conv_CMC: Conv unit :=\n  zero <- load_Z size1 0;\n  p1 <- get_flag CF;\n  p0 <- test eq_op zero p1;\n  set_flag CF p0.\n\nDefinition conv_LAHF: Conv unit :=\n  dst <- load_Z size8 0;\n\n  fl <- get_flag SF;\n  pos <- load_Z size8 7;\n  byt <- cast_u size8 fl;  \n  tmp <- @arith size8 shl_op byt pos;  \n  dst <- @arith size8 or_op dst tmp; \n\n  fl <- get_flag ZF;\n  pos <- load_Z size8 6;\n  byt <- cast_u size8 fl;  \n  tmp <- @arith size8 shl_op byt pos;  \n  dst <- @arith size8 or_op dst tmp; \n\n  fl <- get_flag AF;\n  pos <- load_Z size8 4;\n  byt <- cast_u size8 fl;  \n  tmp <- @arith size8 shl_op byt pos;  \n  dst <- @arith size8 or_op dst tmp; \n\n  fl <- get_flag PF;\n  pos <- load_Z size8 2;\n  byt <- cast_u size8 fl;  \n  tmp <- @arith size8 shl_op byt pos;  \n  dst <- @arith size8 or_op dst tmp; \n\n  fl <- get_flag CF;\n  pos <- load_Z size8 0;\n  byt <- cast_u size8 fl;  \n  tmp <- @arith size8 shl_op byt pos;  \n  dst <- @arith size8 or_op dst tmp; \n\n  fl <- load_Z size8 1;\n  pos <- load_Z size8 1;\n  byt <- cast_u size8 fl;  \n  tmp <- @arith size8 shl_op byt pos;  \n  dst <- @arith size8 or_op dst tmp; \n\n  iset_op8 DS dst (Reg_op ESP).\n\nDefinition conv_SAHF: Conv unit :=\n  one <- load_Z size8 1;\n  ah <- iload_op8 DS (Reg_op ESP);\n\n  pos <- load_Z size8 7;\n  tmp <- @arith size8 shr_op ah pos;\n  tmp <- @arith size8 and_op tmp one;\n  b <- test eq_op one tmp;\n  set_flag SF b;;\n\n  pos <- load_Z size8 6;\n  tmp <- @arith size8 shr_op ah pos;\n  tmp <- @arith size8 and_op tmp one;\n  b <- test eq_op one tmp;\n  set_flag ZF b;;\n\n  pos <- load_Z size8 4;\n  tmp <- @arith size8 shr_op ah pos;\n  tmp <- @arith size8 and_op tmp one;\n  b <- test eq_op one tmp;\n  set_flag AF b;;\n\n  pos <- load_Z size8 2;\n  tmp <- @arith size8 shr_op ah pos;\n  tmp <- @arith size8 and_op tmp one;\n  b <- test eq_op one tmp;\n  set_flag PF b;;\n\n  pos <- load_Z size8 0;\n  tmp <- @arith size8 shr_op ah pos;\n  tmp <- @arith size8 and_op tmp one;\n  b <- test eq_op one tmp;\n  set_flag CF b. \n\n\n  Definition conv_ADD (pre: prefix) (w: bool) (op1 op2: operand) : Conv unit :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    let seg := get_segment_op2 pre DS op1 op2 in\n        (* RTL for useful constants *)\n        zero <- load_Z _ 0;\n        up <- load_Z size1 1;\n\n        (* RTL for op1 *)\n        p0 <- load seg op1;\n        p1 <- load seg op2;\n        p2 <- arith add_op p0 p1;\n        set seg p2 op1;;        \n\n        (* RTL for OF *)\n        b0 <- test lt_op zero p0;\n        b1 <- test lt_op zero p1;\n        b2 <- test lt_op zero p2;\n        b3 <- @arith size1 xor_op b0 b1;\n        b3 <- @arith size1 xor_op up b3;\n        b4 <- @arith size1 xor_op b0 b2;\n        b4 <- @arith size1 and_op b3 b4;\n        set_flag OF b4;;\n\n        (* RTL for CF *)\n        b0 <- test ltu_op p2 p0;\n        b1 <- test ltu_op p2 p1;\n        b0 <- @arith size1 or_op b0 b1;\n        set_flag CF b0;;\n\n        (* RTL for ZF *)\n        b0 <- test eq_op p2 zero;\n        set_flag ZF b0;;\n\n        (* RTL for SF *)\n        b0 <- test lt_op p2 zero;\n        set_flag SF b0;;\n\n        (* RTL for PF *)\n        b0 <- compute_parity p2;\n        set_flag PF b0;;\n\n        (* RTL for AF *)\n        n0 <- cast_u size4 p0;\n        n1 <- cast_u size4 p1;\n        n2 <- @arith size4 add_op n0 n1;\n        b0 <- test ltu_op n2 n0;\n        b1 <- test ltu_op n2 n1;\n        b0 <- @arith size1 or_op b0 b1;\n        set_flag AF b0.\n\n\n  (* If e is true, then this is sub, otherwise it's cmp \n     Dest is equal to op1 for the case of SUB,\n     but it's equal to op2 for the case of NEG\n     \n     We use segdest, seg1, seg2 to specify which segment\n     registers to use for the destination, op1, and op2.\n     This is because for CMPS, only the first operand's \n     segment can be overriden. \n  *) \n\n  Definition conv_SUB_CMP_generic (e: bool) (pre: prefix) (w: bool) (dest: operand) (op1 op2: operand) \n    (segdest seg1 seg2: segment_register) :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n        (* RTL for useful constants *)\n        zero <- load_Z _ 0;\n        up <- load_Z size1 1;\n\n        (* RTL for op1 *)\n        p0 <- load seg1 op1;\n        p1 <- load seg2 op2;\n        p2 <- arith sub_op p0 p1;\n\n        (* RTL for OF *)\n        negp1 <- arith sub_op zero p1;\n        b0 <- test lt_op zero p0;\n        b1 <- test lt_op zero negp1;\n        b2 <- test lt_op zero p2;\n        b3 <- @arith size1 xor_op b0 b1;\n        b3 <- @arith size1 xor_op up b3;\n        b4 <- @arith size1 xor_op b0 b2;\n        b4 <- @arith size1 and_op b3 b4;\n        set_flag OF b4;;\n\n        (* RTL for CF *)\n        b0 <- test ltu_op p0 p1;\n        set_flag CF b0;;\n\n        (* RTL for ZF *)\n        b0 <- test eq_op p2 zero;\n        set_flag ZF b0;;\n\n        (* RTL for SF *)\n        b0 <- test lt_op p2 zero;\n        set_flag SF b0;;\n\n        (* RTL for PF *)\n        b0 <- compute_parity p2;\n        set_flag PF b0;;\n\n        (* RTL for AF *)\n        n0 <- cast_u size4 p0;\n        n1 <- cast_u size4 p1;\n        b0 <- test ltu_op p0 p1;\n        set_flag AF b0;;\n\n        if e then\n          set segdest p2 dest\n        else \n          ret tt.\n\n  Definition conv_CMP (pre: prefix) (w: bool) (op1 op2: operand) :=\n    let seg := get_segment_op2 pre DS op1 op2 in\n    conv_SUB_CMP_generic false pre w op1 op1 op2 seg seg seg.\n  Definition conv_SUB (pre: prefix) (w: bool) (op1 op2: operand) :=\n    let seg := get_segment_op2 pre DS op1 op2 in\n    conv_SUB_CMP_generic true pre w op1 op1 op2 seg seg seg.\n  Definition conv_NEG (pre: prefix) (w: bool) (op1: operand) :=\n    let seg := get_segment_op pre DS op1 in\n    conv_SUB_CMP_generic true pre w op1 (Imm_op Word.zero) op1 seg seg seg.\n\n  Definition conv_SBB (pre: prefix) (w: bool) (op1 op2: operand) :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    let seg := get_segment_op2 pre DS op1 op2 in\n        (* RTL for useful constants *)\n        zero <- load_Z _ 0;\n        up <- load_Z size1 1;\n        \n        old_cf <- get_flag CF;\n        old_cf_ext <- cast_u _ old_cf;\n        (* RTL for op1 *)\n        p0 <- load seg op1;\n        p1 <- load seg op2;\n        p2_0 <- arith sub_op p0 p1;\n        p2 <- arith sub_op p2_0 old_cf_ext;\n\n        (* RTL for OF *)\n        negp1 <- arith sub_op zero p1;\n        b0 <- test lt_op zero p0;\n        b1 <- test lt_op zero negp1;\n        b2 <- test lt_op zero p2;\n        b3 <- @arith size1 xor_op b0 b1;\n        b3 <- @arith size1 xor_op up b3;\n        b4 <- @arith size1 xor_op b0 b2;\n        b4 <- @arith size1 and_op b3 b4;\n        set_flag OF b4;;\n\n        (* RTL for CF *)\n        b0' <- test ltu_op p0 p1;\n        b0'' <- test eq_op p0 p1;\n        b0 <- arith or_op b0' b0'';\n        set_flag CF b0;;\n\n        (* RTL for ZF *)\n        b0 <- test eq_op p2 zero;\n        set_flag ZF b0;;\n\n        (* RTL for SF *)\n        b0 <- test lt_op p2 zero;\n        set_flag SF b0;;\n\n        (* RTL for PF *)\n        b0 <- compute_parity p2;\n        set_flag PF b0;;\n\n        (* RTL for AF *)\n        n0 <- cast_u size4 p0;\n        n1 <- cast_u size4 p1;\n        b0' <- test ltu_op p0 p1;\n        b0'' <- test eq_op p0 p1;\n        b0 <- arith or_op b0' b0'';\n        set_flag AF b0;;\n        set seg p2 op1.\n\n  (* I tried refactoring this so that it was smaller, but the way I did\n     it caused type-checking to seem to go on FOREVER - maybe someone more \n     clever can figure out how to clean this up *)\n\n  Definition conv_DIV (pre: prefix) (w: bool) (op: operand) :=\n    let seg := get_segment_op pre DS op in\n      undef_flag CF;;\n      undef_flag OF;;\n      undef_flag SF;;\n      undef_flag ZF;;\n      undef_flag AF;;\n      undef_flag PF;;\n      match op_override pre, w with\n        | _, false => dividend <- iload_op16 seg (Reg_op EAX);\n                      divisor <- iload_op8 seg op;\n                      zero <- load_Z _ 0;\n                      divide_by_zero <- test eq_op zero divisor;\n                      emit if_rtl divide_by_zero safe_fail_rtl;;\n                      divisor_ext <- cast_u _ divisor;\n                      quotient <- arith divu_op dividend divisor_ext;\n                      max_quotient <- load_Z _ 255;\n                      div_error <- test ltu_op max_quotient quotient;\n                      emit if_rtl div_error safe_fail_rtl;;\n                      remainder <- arith modu_op dividend divisor_ext;\n                      quotient_trunc <- cast_u _ quotient;\n                      remainder_trunc <- cast_u _ remainder;\n                      iset_op8 seg quotient_trunc (Reg_op EAX);;\n                      iset_op8 seg remainder_trunc (Reg_op ESP) (* This is AH *)\n       | true, true => dividend_lower <- iload_op16 seg (Reg_op EAX);\n                       dividend_upper <- iload_op16 seg (Reg_op EDX);\n                       dividend0 <- cast_u size32 dividend_upper;\n                       sixteen <- load_Z size32 16;\n                       dividend1 <- arith shl_op dividend0 sixteen;\n                       dividend_lower_ext <- cast_u size32 dividend_lower;\n                       dividend <- arith or_op dividend1 dividend_lower_ext;\n                       divisor <- iload_op16 seg op;\n                       zero <- load_Z _ 0;\n                       divide_by_zero <- test eq_op zero divisor;\n                       emit if_rtl divide_by_zero safe_fail_rtl;;\n                       divisor_ext <- cast_u _ divisor;\n                       quotient <- arith divu_op dividend divisor_ext;\n                       max_quotient <- load_Z _ 65535;\n                       div_error <- test ltu_op max_quotient quotient;\n                       emit if_rtl div_error safe_fail_rtl;;\n                       remainder <- arith modu_op dividend divisor_ext;\n                       quotient_trunc <- cast_u _ quotient;\n                       remainder_trunc <- cast_u _ remainder;\n                       iset_op16 seg quotient_trunc (Reg_op EAX);;\n                       iset_op16 seg remainder_trunc (Reg_op EDX) \n       | false, true => dividend_lower <- iload_op32 seg (Reg_op EAX);\n                       dividend_upper <- iload_op32 seg (Reg_op EDX);\n                       dividend0 <- cast_u 63 dividend_upper;\n                       thirtytwo <- load_Z 63 32;\n                       dividend1 <- arith shl_op dividend0 thirtytwo;\n                       dividend_lower_ext <- cast_u _ dividend_lower;\n                       dividend <- arith or_op dividend1 dividend_lower_ext;\n                       divisor <- iload_op32 seg op;\n                       zero <- load_Z _ 0;\n                       divide_by_zero <- test eq_op zero divisor;\n                       emit if_rtl divide_by_zero safe_fail_rtl;;\n                       divisor_ext <- cast_u _ divisor;\n                       quotient <- arith divu_op dividend divisor_ext;\n                       max_quotient <- load_Z _ 4294967295;\n                       div_error <- test ltu_op max_quotient quotient;\n                       emit if_rtl div_error safe_fail_rtl;;\n                       remainder <- arith modu_op dividend divisor_ext;\n                       quotient_trunc <- cast_u _ quotient;\n                       remainder_trunc <- cast_u _ remainder;\n                       iset_op32 seg quotient_trunc (Reg_op EAX);;\n                       iset_op32 seg remainder_trunc (Reg_op EDX) \n     end.\n\n  Definition conv_IDIV (pre: prefix) (w: bool) (op: operand) :=\n    let seg := get_segment_op pre DS op in\n      undef_flag CF;;\n      undef_flag OF;;\n      undef_flag SF;;\n      undef_flag ZF;;\n      undef_flag AF;;\n      undef_flag PF;;\n      match op_override pre, w with\n        | _, false => dividend <- iload_op16 seg (Reg_op EAX);\n                      divisor <- iload_op8 seg op;\n                      zero <- load_Z _ 0;\n                      divide_by_zero <- test eq_op zero divisor;\n                      emit if_rtl divide_by_zero safe_fail_rtl;;\n                      divisor_ext <- cast_s _ divisor;\n                      quotient <- arith divs_op dividend divisor_ext;\n                      max_quotient <- load_Z _ 127;\n                      min_quotient <- load_Z _ (-128);\n                      div_error0 <- test lt_op max_quotient quotient;\n                      div_error1 <- test lt_op quotient min_quotient;\n                      div_error <- arith or_op div_error0 div_error1;\n                      emit if_rtl div_error safe_fail_rtl;;\n                      remainder <- arith mods_op dividend divisor_ext;\n                      quotient_trunc <- cast_s _ quotient;\n                      remainder_trunc <- cast_s _ remainder;\n                      iset_op8 seg quotient_trunc (Reg_op EAX);;\n                      iset_op8 seg remainder_trunc (Reg_op ESP) (* This is AH *)\n       | true, true => dividend_lower <- iload_op16 seg (Reg_op EAX);\n                       dividend_upper <- iload_op16 seg (Reg_op EDX);\n                       dividend0 <- cast_s size32 dividend_upper;\n                       sixteen <- load_Z size32 16;\n                       dividend1 <- arith shl_op dividend0 sixteen;\n                       dividend_lower_ext <- cast_s size32 dividend_lower;\n                       dividend <- arith or_op dividend1 dividend_lower_ext;\n                       divisor <- iload_op16 seg op;\n                       zero <- load_Z _ 0;\n                       divide_by_zero <- test eq_op zero divisor;\n                       emit if_rtl divide_by_zero safe_fail_rtl;;\n                       divisor_ext <- cast_s _ divisor;\n                       quotient <- arith divs_op dividend divisor_ext;\n                       max_quotient <- load_Z _ 32767;\n                       min_quotient <- load_Z _ (-32768);\n                       div_error0 <- test lt_op max_quotient quotient;\n                       div_error1 <- test lt_op quotient min_quotient;\n                       div_error <- arith or_op div_error0 div_error1;\n                       emit if_rtl div_error safe_fail_rtl;;\n                       remainder <- arith mods_op dividend divisor_ext;\n                       quotient_trunc <- cast_s _ quotient;\n                       remainder_trunc <- cast_s _ remainder;\n                       iset_op16 seg quotient_trunc (Reg_op EAX);;\n                       iset_op16 seg remainder_trunc (Reg_op EDX) \n       | false, true => dividend_lower <- iload_op32 seg (Reg_op EAX);\n                       dividend_upper <- iload_op32 seg (Reg_op EDX);\n                       dividend0 <- cast_s 63 dividend_upper;\n                       thirtytwo <- load_Z 63 32;\n                       dividend1 <- arith shl_op dividend0 thirtytwo;\n                       dividend_lower_ext <- cast_s _ dividend_lower;\n                       dividend <- arith or_op dividend1 dividend_lower_ext;\n                       divisor <- iload_op32 seg op;\n                       zero <- load_Z _ 0;\n                       divide_by_zero <- test eq_op zero divisor;\n                       emit if_rtl divide_by_zero safe_fail_rtl;;\n                       divisor_ext <- cast_s _ divisor;\n                       quotient <- arith divs_op dividend divisor_ext;\n                       max_quotient <- load_Z _ 2147483647;\n                       min_quotient <- load_Z _ (-2147483648);\n                       div_error0 <- test lt_op max_quotient quotient;\n                       div_error1 <- test lt_op quotient min_quotient;\n                       div_error <- arith or_op div_error0 div_error1;\n                       emit if_rtl div_error safe_fail_rtl;;\n                       remainder <- arith mods_op dividend divisor_ext;\n                       quotient_trunc <- cast_s _ quotient;\n                       remainder_trunc <- cast_s _ remainder;\n                       iset_op32 seg quotient_trunc (Reg_op EAX);;\n                       iset_op32 seg remainder_trunc (Reg_op EDX) \n     end.\n\n  Program Definition conv_IMUL (pre: prefix) (w: bool) (op1: operand) \n    (opopt2: option operand) (iopt: option int32) :=\n    undef_flag SF;;\n    undef_flag ZF;;\n    undef_flag AF;;\n    undef_flag PF;;\n    (match opopt2 with | None => let load := load_op pre w in\n                let seg := get_segment_op pre DS op1 in\n                 p1 <- load seg (Reg_op EAX);\n                 p2 <- load seg op1;\n                 p1ext <- cast_s (2*((opsize (op_override pre) w)+1)-1) p1;\n                 p2ext <- cast_s (2*((opsize (op_override pre) w)+1)-1) p2;\n                 res <- arith mul_op p1ext p2ext;\n                 lowerhalf <- cast_s (opsize (op_override pre) w) res;\n                 shift <- load_Z _ (Z_of_nat (opsize (op_override pre) w + 1));\n                 res_shifted <- arith shr_op res shift;\n                 upperhalf <- cast_s (opsize (op_override pre) w) res_shifted;\n                 zero <- load_Z _  0;\n                 max <- load_Z _ (Word.max_unsigned (opsize (op_override pre) w));\n                 b0 <- test eq_op upperhalf zero;\n                 b1 <- test eq_op upperhalf max;\n                 b2 <- arith or_op b0 b1;\n                 flag <- not b2;\n                 set_flag CF flag;;\n                 set_flag OF flag;;\n                 match (op_override pre), w with\n                   | _, false => iset_op16 seg res (Reg_op EAX) \n                   | _, true =>  let set := set_op pre w in\n                                    set seg lowerhalf (Reg_op EAX);;\n                                    set seg upperhalf (Reg_op EDX)\n                 end\n      | Some op2 => \n        match iopt with\n          | None => let load := load_op pre w in\n                    let set := set_op pre w in\n                    let seg := get_segment_op2 pre DS op1 op2 in\n                      p1 <- load seg op1;\n                      p2 <- load seg op2;\n                      p1ext <- cast_s (2*((opsize (op_override pre) w)+1)-1) p1;\n                      p2ext <- cast_s (2*((opsize (op_override pre) w)+1)-1) p2;\n                      res <- arith mul_op p1ext p2ext;\n                      lowerhalf <- cast_s (opsize (op_override pre) w) res;\n                      reextend <- cast_s (2*((opsize (op_override pre) w)+1)-1) lowerhalf;\n                      b0 <- test eq_op reextend res;\n                      flag <- not b0;\n                      set_flag CF flag;;\n                      set_flag OF flag;;\n                      set seg lowerhalf op1\n          |Some imm3  =>  let load := load_op pre w in\n                    let set := set_op pre w in\n                    let seg := get_segment_op2 pre DS op1 op2 in\n                      p1 <- load seg op2;\n                      p2 <- load_int imm3;\n                      p1ext <- cast_s (2*((opsize (op_override pre) w)+1)-1) p1;\n                      p2ext <- cast_s (2*((opsize (op_override pre) w)+1)-1) p2;\n                      res <- arith mul_op p1ext p2ext;\n                      lowerhalf <- cast_s (opsize (op_override pre) w) res;\n                      reextend <- cast_s (2*((opsize (op_override pre) w)+1)-1) lowerhalf;\n                      b0 <- test eq_op reextend res;\n                      flag <- not b0;\n                      set_flag CF flag;;\n                      set_flag OF flag;;\n                      set seg lowerhalf op1\n        end\n    end).\n    Obligation 1. unfold opsize. \n      destruct (op_override pre); simpl; auto. Defined.\n\n\n\n  Definition conv_MUL (pre: prefix) (w: bool) (op: operand) :=\n    let seg := get_segment_op pre DS op in\n    undef_flag SF;;\n    undef_flag ZF;;\n    undef_flag AF;;\n    undef_flag PF;;\n    match op_override pre, w with\n      | _, false => p1 <- iload_op8 seg op;\n                    p2 <- iload_op8 seg (Reg_op EAX);\n                    p1ext <- cast_u size16 p1;\n                    p2ext <- cast_u size16 p2;\n                    res <- arith mul_op p1ext p2ext;\n                    iset_op16 seg res (Reg_op EAX);;\n                    max <- load_Z _ 255;\n                    cf_test <- test ltu_op max res;\n                    set_flag CF cf_test;;\n                    set_flag OF cf_test\n      | true, true => p1 <- iload_op16 seg op;\n                    p2 <- iload_op16 seg (Reg_op EAX);\n                    p1ext <- cast_u size32 p1;\n                    p2ext <- cast_u size32 p2;\n                    res <- arith mul_op p1ext p2ext;\n                    res_lower <- cast_u size16 res;\n                    sixteen <- load_Z size32 16;\n                    res_shifted <- arith shru_op res sixteen;\n                    res_upper <- cast_u size16 res_shifted;\n                    iset_op16 seg res_lower (Reg_op EAX);;\n                    iset_op16 seg res_upper (Reg_op EDX);;\n                    zero <- load_Z size16 0;\n                    cf_test <- test ltu_op zero res_upper;\n                    set_flag CF cf_test;;\n                    set_flag OF cf_test\n      | false, true => p1 <- iload_op32 seg op;\n                    p2 <- iload_op32 seg (Reg_op EAX);\n                    p1ext <- cast_u 63 p1;\n                    p2ext <- cast_u 63 p2;\n                    res <- arith mul_op p1ext p2ext;\n                    res_lower <- cast_u size32 res;\n                    thirtytwo <- load_Z 63 32;\n                    res_shifted <- arith shru_op res thirtytwo;\n                    res_upper <- cast_u size32 res_shifted;\n                    iset_op32 seg res_lower (Reg_op EAX);;\n                    iset_op32 seg res_upper (Reg_op EDX);;\n                    zero <- load_Z size32 0;\n                    cf_test <- test ltu_op zero res_upper;\n                    set_flag CF cf_test;;\n                    set_flag OF cf_test\n   end.\n\n  Definition conv_shift shift (pre: prefix) (w: bool) (op1: operand) (op2: reg_or_immed) :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    let seg := get_segment_op pre DS op1 in\n      (* These aren't actually undef'd, but they're sqirrely\n         so for now I'll just overapproximate *)\n      undef_flag OF;;\n      undef_flag CF;;\n      undef_flag SF;;\n      undef_flag ZF;;\n      undef_flag PF;;\n      undef_flag AF;;\n      p1 <- load seg op1;\n      p2 <- (match op2 with\n              | Reg_ri r => iload_op8 seg (Reg_op r) \n              | Imm_ri i => load_int i\n             end);\n      mask <- load_Z _ 31;\n      p2 <- arith and_op p2 mask;\n      p2cast <- cast_u (opsize (op_override pre) w) p2;\n      p3 <- arith shift p1 p2cast;\n      set seg p3 op1.\n               \n  Definition conv_SHL pre w op1 op2 := conv_shift shl_op pre w op1 op2.\n  Definition conv_SAR pre w op1 op2 := conv_shift shr_op pre w op1 op2.\n  Definition conv_SHR pre w op1 op2 := conv_shift shru_op pre w op1 op2.\n\n  Definition conv_ROR pre w op1 op2 := conv_shift ror_op pre w op1 op2. \n  Definition conv_ROL pre w op1 op2 := conv_shift rol_op pre w op1 op2.\n\n  (* Need to be careful about op1 size. *)\n\n  Definition conv_RCL pre w op1 op2 :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    let seg := get_segment_op pre DS op1 in\n\n    p1 <- load seg op1;\n    p2 <- (match op2 with\n              | Reg_ri r => iload_op8 seg (Reg_op r) \n              | Imm_ri i => load_int i\n                   end);\n    mask <- load_Z size8 31;\n    p2 <- arith and_op p2 mask;\n    (match opsize (op_override pre) w with\n       | 7  => modmask <- load_Z _ 9;\n               p2 <- arith modu_op p2 modmask;\n               ret tt\n       | 15 => modmask <- load_Z _ 17;\n               p2 <- arith modu_op p2 modmask;\n               ret tt\n       | _  => ret tt\n     end);;\n    p2cast <- cast_u ((opsize (op_override pre) w) + 1) p2;\n    \n    tmp <- cast_u ((opsize (op_override pre) w) + 1) p1;\n    cf <- get_flag CF;\n    cf <- cast_u ((opsize (op_override pre) w) + 1) cf;\n    tt <- load_Z _ (Z_of_nat ((opsize (op_override pre) w) + 1));\n    cf <- arith shl_op cf tt;\n    tmp <- arith or_op tmp cf;\n    tmp <- arith rol_op tmp p2cast; \n    \n    p3 <- cast_u (opsize (op_override pre) w) tmp;\n    cf <- arith shr_op tmp tt;\n    cf <- cast_u size1 cf;\n    undef_flag OF;;\n    set_flag CF cf;;\n    set seg p3 op1.\n\n  Definition conv_RCR pre w op1 op2 :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    let seg := get_segment_op pre DS op1 in\n    p1 <- load seg op1;\n    p2 <- (match op2 with\n              | Reg_ri r => iload_op8 seg (Reg_op r) \n              | Imm_ri i => load_int i\n                   end);   \n    mask <- load_Z size8 31;\n    p2 <- arith and_op p2 mask;\n    (match opsize (op_override pre) w with\n       | 7  => modmask <- load_Z _ 9;\n               p2 <- arith modu_op p2 modmask;\n               ret tt\n       | 15 => modmask <- load_Z _ 17;\n               p2 <- arith modu_op p2 modmask;\n               ret tt\n       | _  => ret tt\n     end);;\n   p2cast <- cast_u ((opsize (op_override pre) w) + 1) p2;\n\n    oneshift <- load_Z _ 1;\n\n    tmp <- cast_u ((opsize (op_override pre) w) + 1) p1;\n    tmp <- arith shl_op tmp oneshift;\n    cf <- get_flag CF;\n    cf <- cast_u ((opsize (op_override pre) w) + 1) cf;\n    tmp <- arith or_op tmp cf;\n    tmp <- arith ror_op tmp p2cast;\n    \n    cf <- cast_u size1 tmp;\n    p3 <- arith shr_op tmp oneshift;\n    p3 <- cast_u ((opsize (op_override pre) w)) p3;\n    undef_flag OF;;\n    set_flag CF cf;;\n    set seg p3 op1.\n\n  Definition conv_SHLD pre (op1: operand) (r: register) ri :=\n    let load := load_op pre true in\n    let set := set_op pre true in\n    let seg := get_segment_op pre DS op1 in\n      count <- (match ri with\n              | Reg_ri r => iload_op8 seg (Reg_op r) \n              | Imm_ri i => load_int i\n             end);\n      thirtytwo <- load_Z _ 32;\n      count <- arith modu_op count thirtytwo;\n      (* These aren't actually always undef'd, but they're sqirrely\n         so for now I'll just overapproximate *)\n      undef_flag CF;;\n      undef_flag SF;;\n      undef_flag ZF;;\n      undef_flag PF;;\n      undef_flag AF;;\n      p1 <- load seg op1;\n      p2 <- load seg (Reg_op r);\n      shiftup <- (match (op_override pre) with\n                    | true => load_Z 63 16\n                    | false => load_Z 63 32\n                  end);\n      wide_p1 <- cast_u 63 p1;\n      wide_p1 <- arith shl_op wide_p1 shiftup;\n      wide_p2 <- cast_u 63 p2;\n      combined <- arith or_op wide_p1 wide_p2;\n      wide_count <- cast_u 63 count;\n      shifted <- arith shl_op combined wide_count;\n      shifted <- arith shru_op shifted shiftup;\n      newdest <- cast_u _ shifted;\n      maxcount <- (match (op_override pre) with\n                    | true => load_Z size8 16\n                    | false => load_Z size8 32\n                  end);\n      guard1 <- test ltu_op maxcount count;\n      guard2 <- test eq_op maxcount count;\n      guard <- arith or_op guard1 guard2;\n      emit (if_rtl guard (choose_rtl newdest));;\n      set seg newdest op1.\n\n  Definition conv_SHRD pre (op1: operand) (r: register) ri :=\n    let load := load_op pre true in\n    let set := set_op pre true in\n    let seg := get_segment_op pre DS op1 in\n      count <- (match ri with\n              | Reg_ri r => iload_op8 seg (Reg_op r) \n              | Imm_ri i => load_int i\n             end);\n      thirtytwo <- load_Z _ 32;\n      count <- arith modu_op count thirtytwo;\n      (* These aren't actually always undef'd, but they're sqirrely\n         so for now I'll just overapproximate *)\n      undef_flag CF;;\n      undef_flag SF;;\n      undef_flag ZF;;\n      undef_flag PF;;\n      undef_flag AF;;\n      p1 <- load seg op1;\n      p2 <- load seg (Reg_op r);\n      wide_p1 <- cast_u 63 p1;\n      shiftup <- (match (op_override pre) with\n                    | true => load_Z 63 16\n                    | false => load_Z 63 32\n                  end);\n      wide_p2 <- cast_u 63 p2;\n      wide_p2 <- arith shl_op wide_p2 shiftup;\n      combined <- arith or_op wide_p1 wide_p2;\n      wide_count <- cast_u 63 count;\n      shifted <- arith shru_op combined wide_count;\n      newdest <- cast_u _ shifted;\n      maxcount <- (match (op_override pre) with\n                    | true => load_Z size8 16\n                    | false => load_Z size8 32\n                  end);\n      guard1 <- test ltu_op maxcount count;\n      guard2 <- test eq_op maxcount count;\n      guard <- arith or_op guard1 guard2;\n      emit (if_rtl guard (choose_rtl newdest));;\n      set seg newdest op1.\n  (************************)\n  (* Binary Coded Dec Ops *)\n  (************************)\n\n  (* The semantics for these operations are described using slightly different pseudocode in the\n     old and new intel manuals, although they are operationally equivalent. These definitions\n     are structured based on the new manual, so it may look strange when compared with the old\n     manual *)\n\n  Definition get_AH : Conv (pseudo_reg size8) :=\n    iload_op8 DS (Reg_op ESP)\n  .\n  Definition set_AH v: Conv unit :=\n    iset_op8 DS v (Reg_op ESP) \n  .\n  Definition get_AL : Conv (pseudo_reg size8) :=\n    iload_op8 DS (Reg_op EAX)\n  .\n  Definition set_AL v: Conv unit :=\n    iset_op8 DS v (Reg_op EAX) \n  .\n  Definition ifset s cond (rd:pseudo_reg s) (rs:pseudo_reg s) : Conv unit :=\n    emit (if_rtl cond (cast_u_rtl rs rd))\n.\n  Definition conv_AAA_AAS (op1: bit_vector_op) : Conv unit :=\n    pnine <- load_Z size8 9;\n    p0Fmask <- load_Z size8 15;\n    paf <- get_flag AF;\n    pal <- get_AL;\n    digit1 <- arith and_op pal p0Fmask;\n    cond1 <- test lt_op pnine digit1;\n    cond <- arith or_op cond1 paf;\n\n    pah <- get_AH;\n    (*Else branch*)\n    pfalse <- load_Z size1 0;\n    v_ah <- copy_ps pah;\n    v_af <- copy_ps pfalse;\n    v_cf <- copy_ps pfalse;\n    v_al <- arith and_op pal p0Fmask;\n    \n    (*If branch*)\n    psix <- load_Z size8 6;\n    pone <- load_Z size8 1;\n    ptrue <- load_Z size1 1;\n    pal_c <- arith op1 pal psix;\n    pal_cmask <- arith and_op pal_c p0Fmask;\n    ifset cond v_al pal_cmask;;\n    \n    pah <- get_AH;\n    pah_c <- arith op1 pah pone;\n    ifset cond v_ah pah_c;;\n    ifset cond v_af ptrue;;\n    ifset cond v_cf ptrue;;\n    \n    (*Set final values*)\n    set_AL v_al;;\n    set_AH v_ah;;\n    set_flag AF v_af;;\n    set_flag CF v_cf;;\n\n    undef_flag OF;;\n    undef_flag SF;;\n    undef_flag ZF;;\n    undef_flag PF\n    .\n  Definition conv_AAD : Conv unit :=\n    pal <- get_AL;\n    pah <- get_AH;\n    pten <- load_Z size8 10;\n    pFF <- load_Z size8 255;\n    pzero <- load_Z size8 0;\n\n    tensval <- arith mul_op pah pten;\n    pal_c <- arith add_op pal tensval;\n    pal_cmask <- arith and_op pal_c pFF;\n    set_AL pal_cmask;;\n    set_AH pzero;;\n\n    b0 <- test eq_op pal_cmask pzero;\n    set_flag ZF b0;;\n    b1 <- test lt_op pal_cmask pzero;\n    set_flag SF b1;;\n    b2 <- compute_parity pal_cmask;\n    set_flag PF b2;;\n    undef_flag OF;;\n    undef_flag AF;;\n    undef_flag CF\n    .\n\n  Definition conv_AAM : Conv unit :=\n    pal <- get_AL;\n    pten <- load_Z size8 10;\n    digit1 <- arith divu_op pal pten;\n    digit2 <- arith modu_op pal pten;\n    set_AH digit1;;\n    set_AL digit2;;\n\n    pzero <- load_Z size8 0;\n    b0 <- test eq_op digit2 pzero;\n    set_flag ZF b0;;\n    b1 <- test lt_op digit2 pzero;\n    set_flag SF b1;;\n    b2 <- compute_parity digit2;\n    set_flag PF b2;;\n    undef_flag OF;;\n    undef_flag AF;;\n    undef_flag CF\n    .\n\n  Definition testcarryAdd s (p1:pseudo_reg s) p2 p3 : Conv (pseudo_reg size1) :=\n    b0 <-test ltu_op p3 p1;\n    b1 <-test ltu_op p3 p2;\n    arith or_op b0 b1.\n\n  Definition testcarrySub s (p1:pseudo_reg s) p2 (p3:pseudo_reg s) : Conv (pseudo_reg size1) :=\n    test ltu_op p1 p2.\n\n  (*Use oracle for now*)\n  Definition conv_DAA_DAS (op1: bit_vector_op) \n    (tester: (pseudo_reg size8) -> (pseudo_reg size8) -> (pseudo_reg size8) ->\n      Conv (pseudo_reg size1)) : Conv unit :=\n    pal <- fresh (@choose_rtl size8);\n    set_AL pal;;\n    undef_flag CF;;\n    undef_flag AF;;\n    undef_flag SF;;\n    undef_flag ZF;;\n    undef_flag PF;;\n    undef_flag OF\n  .\n(*\n  Definition conv_DAA_DAS (op1: bit_vector_op) tester: Conv unit :=\n    pal <- get_AL;\n    pcf <- get_flag CF;\n    ptrue <- load_Z size1 1;\n    pfalse <- load_Z size1 0;\n    set_flag CF pfalse;;\n\n    pnine <- load_Z size8 9;\n    p0Fmask <- load_Z size8 15;\n    palmask <- arith and_op pal p0Fmask;\n    cond1 <- test lt_op pnine palmask;\n    paf <- get_flag AF;\n    cond <- arith or_op cond1 paf;\n\n    v_cf <- load_Z size1 0;\n    (*First outer if*)\n      (*Else*)\n      v_al <- copy_ps pal;\n      v_af <- load_Z size1 0;\n      (*If*)\n      psix <- load_Z size8 6;\n      pal_c <- arith op1 pal psix;\n      ifset cond v_al pal_c;;\n      ifset cond v_af ptrue;;\n\n      (*Annoying test for carry flag*)\n      b2 <- tester pal psix pal_c;\n      newc <- arith or_op pcf b2;\n      ifset cond v_cf newc;;\n    (*End first outer if*)\n      \n    pninenine <- load_Z size8 153 (*0x99*);\n    cond1' <- test lt_op pninenine pal;\n    cond' <- arith or_op cond1' pcf;\n    ncond' <- not cond';\n    (*Second outer if*)\n      (*Else*)\n      ifset ncond' v_cf pfalse;;\n      (*If*)\n      psixty <- load_Z size8 96; (*0x60*)\n      pal2_c <- arith op1 v_al psixty;\n      ifset cond' v_al pal2_c;;\n      ifset cond' v_cf ptrue;;\n    (*End second outer if*)\n    \n    (*Set final values*)\n    (*v_al, v_cf, v_af*)\n    set_AL v_al;;\n    set_flag CF v_cf;;\n    set_flag AF v_af;;\n    pzero <- load_Z size8 0;\n    b0 <- test eq_op v_al pzero;\n    set_flag ZF b0;;\n    b1 <- test lt_op v_al pzero;\n    set_flag SF b1;;\n    b2 <- compute_parity v_al;\n    set_flag PF b2;;\n    undef_flag OF\n.\n    \n*)\n    \n  (************************)\n  (* Logical Ops          *)\n  (************************)\n\n  Definition conv_logical_op (do_effect: bool) (b: bit_vector_op) (pre: prefix) \n    (w: bool) (op1 op2: operand) : Conv unit :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    let seg := get_segment_op2 pre DS op1 op2 in\n        p0 <- load seg op1;\n        p1 <- load seg op2;\n        p2 <- arith b p0 p1;\n        zero <- load_Z _ 0;\n        zfp <- test eq_op zero p2;\n        sfp <- test lt_op p2 zero;\n        pfp <- compute_parity p2;\n        zero1 <- load_Z size1 0;\n        set_flag OF zero1 ;;\n        set_flag CF zero1 ;;\n        set_flag ZF zfp   ;;\n        set_flag SF sfp ;;\n        set_flag PF pfp ;;\n        undef_flag AF;;\n        if do_effect then\n          set seg p2 op1\n        else\n          ret tt.\n  \n  Definition conv_AND p w op1 op2 := conv_logical_op true and_op p w op1 op2.\n  Definition conv_OR p w op1 op2 := conv_logical_op true or_op p w op1 op2.\n  Definition conv_XOR p w op1 op2 := conv_logical_op true xor_op p w op1 op2.\n\n  (* This is like AND except you don't actually write the result in op1 *)\n  Definition conv_TEST p w op1 op2 := conv_logical_op false and_op p w op1 op2.\n\n  (* This is different than the others because it doesn't affect any\n     flags *)\n\n  Definition conv_NOT (pre: prefix) (w: bool) (op: operand) : Conv unit :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    let seg := get_segment_op pre DS op in\n        p0 <- load seg op;\n        max_unsigned <- load_Z _ (Word.max_unsigned size32);\n        p1 <- arith xor_op p0 max_unsigned;\n        set seg p1 op.\n\n  (************************)\n  (* Stack Ops            *)\n  (************************)\n\n  Definition conv_POP (pre: prefix) (op: operand) :=\n    (*Segment cannot be overriden*)\n    let seg := SS in \n    let set := set_op pre true seg in\n    let loadmem := load_mem pre true seg in \n    let espoffset := match (op_override pre) with\n                       | true => 2%Z\n                       | false => 4%Z\n                     end in\n      oldesp <- load_reg ESP;\n      value <- loadmem oldesp;\n      offset <- load_Z size32 espoffset;\n      newesp <- arith add_op oldesp offset;\n      set_reg newesp ESP;;\n      set value op\n      .\n  Definition conv_POPA (pre:prefix) :=\n    let espoffset := match (op_override pre) with\n                       | true => 2%Z\n                       | false => 4%Z\n                     end in\n    let poprtl r := conv_POP pre (Reg_op r) in\n    poprtl EDI;;\n    poprtl ESI;;\n    poprtl EBP;;\n    oldesp <- load_reg ESP;\n    offset <- load_Z size32 espoffset;\n    newesp <- arith add_op oldesp offset;\n    set_reg newesp ESP;;\n    poprtl EBX;;\n    poprtl EDX;;\n    poprtl ECX;;\n    poprtl EAX.\n\n  Definition conv_PUSH (pre: prefix) (w: bool) (op: operand) :=\n    let seg := SS in\n    let load := load_op pre true seg in\n    let setmem := set_mem pre true seg in\n    let espoffset := match op_override pre,w return Z with \n                       | true,_ => 2%Z\n                       | false,_ => 4%Z\n                     end in\n    p0 <- load op;\n    oldesp <- load_reg ESP;\n    offset <- load_Z size32 espoffset;\n    newesp <- arith sub_op oldesp offset;\n    setmem p0 newesp;;\n    set_reg newesp ESP\n    .\n\n  Definition conv_PUSH_pseudo (pre:prefix) (w:bool) \n    pr  := (* (pr: pseudo_reg (opsize (op_override pre) w)) *)\n    let seg := SS in\n    let setmem := set_mem pre w seg in\n    let espoffset := match op_override pre,w return Z with \n                       | _,false => 1%Z\n                       | true,true => 2%Z\n                       | false,true => 4%Z\n                     end in\n    oldesp <- load_reg ESP;\n    offset <- load_Z size32 espoffset;\n    newesp <- arith sub_op oldesp offset;\n    setmem pr newesp;;\n    set_reg newesp ESP\n    .\n\n(*\n    let seg := get_segment pre SS in\n      if w then\n        p0 <- iload_op32 seg op;\n        oldesp <- load_reg ESP;\n        four <- load_Z size32 4;\n        newesp <- arith sub_op oldesp four;\n        set_mem32 seg p0 newesp;;\n        set_reg newesp ESP\n      else\n        b0 <- iload_op8 seg op;\n        oldesp <- load_reg ESP;\n        one <- load_Z size32 1;\n        newesp <- arith sub_op oldesp one;\n        set_mem8 seg b0 newesp;;\n        set_reg newesp ESP.\n*)\n\nDefinition conv_PUSHA (pre:prefix) :=\n    let load := load_op pre true SS in\n    let pushrtl r := conv_PUSH pre true (Reg_op r) in\n    oldesp <- load (Reg_op ESP);\n    pushrtl EAX;;\n    pushrtl ECX;;\n    pushrtl EDX;;\n    pushrtl EBX;;\n    conv_PUSH_pseudo pre true oldesp;;\n    pushrtl EBP;;\n    pushrtl ESI;;\n    pushrtl EDI\n.\n\n\nDefinition get_and_place T dst pos fl: Conv (pseudo_reg T) :=\n  fl <- get_flag fl;\n  pos <- load_Z _ pos;\n  byt <- cast_u _ fl;  \n  tmp <- @arith _ shl_op byt pos;  \n  dst <- @arith _ or_op dst tmp;\n  Return dst.\n(*\nThis is not quite right. Plus those more sketchy flags\nare not being modeled yet since they're more systemszy.\n\nDefinition conv_PUSHF pre :=\n  dst <- load_Z (opsize (op_override pre) true) 0;\n\n  dst <- get_and_place dst 21 ID;\n  dst <- get_and_place dst 20 VIP;\n  dst <- get_and_place dst 19 VIF;  \n  dst <- get_and_place dst 18 AC;\n  dst <- get_and_place dst 17 VM;\n  dst <- get_and_place dst 16 RF;\n  dst <- get_and_place dst 14 NT;\n(*  get_and_place dst 13 12 IOPL; *)\n  dst <- get_and_place dst 11 OF;\n  dst <- get_and_place dst 10 DF;\n  dst <- get_and_place dst 9 IF_flag;\n  dst <- get_and_place dst 8 TF;\n  dst <- get_and_place dst 7 SF;\n  dst <- get_and_place dst 6 ZF;\n  dst <- get_and_place dst 4 AF;\n  dst <- get_and_place dst 2 PF;\n  dst <- get_and_place dst 0 CF;\n  conv_PUSH_pseudo pre true dst.  \n*)\n\nDefinition conv_POP_pseudo (pre: prefix) :=\n(*Segment cannot be overriden*)\n  let seg := SS in \n    let set := set_op pre true seg in\n      let loadmem := load_mem pre true seg in \n        let espoffset := match (op_override pre) with\n                           | true => 2%Z\n                           | false => 4%Z\n                         end in\n        oldesp <- load_reg ESP;\n        value <- loadmem oldesp;\n        offset <- load_Z size32 espoffset;\n        newesp <- arith add_op oldesp offset;\n        set_reg newesp ESP;;\n        Return value.\n\nDefinition extract_and_set T value pos fl: Conv unit :=\n  one <- load_Z T 1;\n  pos <- load_Z _ pos;\n  tmp <- @arith _ shr_op value pos;\n  tmp <- @arith _ and_op tmp one;\n  b <- test eq_op one tmp;\n  set_flag fl b.\n(*\nThis is not quite right.\nDefinition conv_POPF pre :=\n  v <- conv_POP_pseudo pre;\n\n  @extract_and_set ((opsize (op_override pre) true)) v 21 ID;;\n  extract_and_set v 20 VIP;;\n  extract_and_set v 19 VIF;; \n  extract_and_set v 18 AC;;\n  extract_and_set v 17 VM;;\n  extract_and_set v 16 RF;;\n  extract_and_set v 14 NT;;\n(*  extract_and_set dst 13 12 IOPL; *)\n  extract_and_set v 11 OF;;\n  extract_and_set v 10 DF;;\n  extract_and_set v 9 IF_flag;;\n  extract_and_set v 8 TF;;\n  extract_and_set v 7 SF;;\n  extract_and_set v 6 ZF;;\n  extract_and_set v 4 AF;;\n  extract_and_set v 2 PF;;\n  extract_and_set v 0 CF.\n*)\n\n  (************************)\n  (* Control-Flow Ops     *)\n  (************************)\n\n  Definition conv_JMP (pre: prefix) (near absolute: bool) (op: operand)\n    (sel: option selector) :=\n    let seg := get_segment_op pre DS op in\n      if near then\n        disp <- iload_op32 seg op;\n        base <- (match absolute with\n                   | true => load_Z size32 0\n                   | false => get_pc\n                 end);\n        newpc <- arith add_op base disp;\n        set_pc newpc\n      else\n        emit error_rtl.\n\n  Definition conv_Jcc (pre: prefix) (ct: condition_type) (disp: int32) : Conv unit :=\n    guard <- compute_cc ct;\n    oldpc <- get_pc;\n    pdisp <- load_int disp;\n    newpc <- arith add_op oldpc pdisp;\n    emit if_rtl guard (set_loc_rtl newpc pc_loc).\n\n  Definition conv_CALL (pre: prefix) (near absolute: bool) (op: operand)\n    (sel: option selector) :=\n      oldpc <- get_pc;\n      oldesp <- load_reg ESP;\n      four <- load_Z size32 4;\n      newesp <- arith sub_op oldesp four;\n      set_mem32 SS oldpc newesp;;\n      set_reg newesp ESP;;\n      conv_JMP pre near absolute op sel.\n  \n  Definition conv_RET (pre: prefix) (same_segment: bool) (disp: option int16) :=\n      if same_segment then\n        oldesp <- load_reg ESP;\n        value <- load_mem32 SS oldesp;\n        four <- load_Z size32 4;\n        newesp <- arith add_op oldesp four;\n        (match disp with\n           | None => set_reg newesp ESP\n           | Some imm => imm0 <- load_int imm;\n             imm <- cast_u size32 imm0;\n             newesp2 <- arith add_op newesp imm;\n             set_reg newesp2 ESP\n         end);;\n        set_pc value\n      else\n        emit error_rtl.\n  \n  Definition conv_LEAVE pre := \n    ebp_val <- load_reg EBP;\n    set_reg ebp_val ESP;;\n    conv_POP pre (Reg_op EBP).\n\n  Definition conv_LOOP pre (flagged:bool) (testz:bool) (disp:int8):=\n    ptrue <- load_Z size1 1;\n    p0 <- load_reg ECX;\n    p1 <- load_Z _ 1;\n    p2 <- arith sub_op p0 p1;\n    set_reg p2 ECX;;\n    pzero <- load_Z _ 0;\n    pcz <- test eq_op p2 pzero;\n    pcnz <- arith xor_op pcz ptrue;\n    pzf <- get_flag ZF;\n    pnzf <- arith xor_op pzf ptrue;\n    bcond <- \n    (match flagged with\n       | true =>\n         (match testz with\n            | true => (arith and_op pzf pcnz)\n            | false => (arith and_op pnzf pcnz)\n          end)\n       | false => arith or_op pcnz pcnz\n     end);\n    eip0 <- get_pc;\n    doffset0 <- load_int disp;\n    doffset1 <- cast_s size32 doffset0;\n    eip1 <- arith add_op eip0 doffset1;\n    eipmask <-\n    (match (op_override pre) with\n       |true => load_Z size32 65536%Z (*0000FFFF*)\n       |false => load_Z size32 (-1%Z)\n     end);\n    eip2 <- arith and_op eip1 eipmask;\n    emit (if_rtl bcond (set_loc_rtl eip2 pc_loc))\n    .\n\n  (************************)\n  (* Misc Ops             *)\n  (************************)\n\n  (* Unfortunately this is kind of \"dumb\", because we can't short-circuit\n     once we find the msb/lsb *)\n\n  Fixpoint conv_BS_aux {s} (d: bool) (n: nat) (op: pseudo_reg s) : Conv (pseudo_reg s) :=\n    let curr_int := (match d with\n                       | true => @Word.repr s (BinInt.Z_of_nat (s-n)) \n                       | false => @Word.repr s (BinInt.Z_of_nat n) \n                     end) in\n    match n with\n      | O => load_int curr_int\n      | S n' => bcount <- load_int curr_int;\n        rec <- conv_BS_aux d n' op;\n        ps <- arith shru_op op bcount;\n        curr_bit <- cast_u size1 ps;\n        emit if_rtl curr_bit (load_imm_rtl curr_int rec);;\n        ret rec\n    end.\n\n  Definition conv_BS (d: bool) (pre: prefix) (op1 op2: operand) :=\n    let seg := get_segment_op2 pre DS op1 op2 in\n      undef_flag AF;;\n      undef_flag CF;;\n      undef_flag SF;;\n      undef_flag OF;;\n      undef_flag PF;;\n      des <- iload_op32 seg op1;\n      src <- iload_op32 seg op2;\n      zero <- load_Z size32 0;\n      zf <- test eq_op src zero;\n      set_flag ZF zf;;\n      res <- conv_BS_aux d size32 src;\n      emit (if_rtl zf (choose_rtl res));;\n      iset_op32 seg res op1.\n\n  Definition conv_BSF p op1 op2 := conv_BS true p op1 op2.\n  Definition conv_BSR p op1 op2 := conv_BS false p op1 op2.\n  \n  Definition get_Bit {s: nat} (pb: pseudo_reg s) (poff: pseudo_reg s) : \n    Conv (pseudo_reg size1) :=\n    omask <- load_Z s 1;\n    shr_pb <- arith shr_op pb poff;\n    mask_pb <- arith and_op shr_pb omask;\n    tb <- cast_u size1 mask_pb;\n    ret tb.\n\n  Definition modify_Bit {s} (value: pseudo_reg s) (poff: pseudo_reg s)\n    (bitval: pseudo_reg size1): Conv (pseudo_reg s) :=\n    obit <- load_Z _ 1;\n    one_shifted <- arith shl_op obit poff;\n    inv_one_shifted <- not one_shifted;\n    bitvalword <- cast_u _ bitval;\n    bit_shifted <- arith shl_op bitvalword poff;\n    newval <- arith and_op value inv_one_shifted;\n    arith or_op newval bit_shifted.\n\n  (*Set a bit given a word referenced by an operand*)\n  Definition set_Bit (pre:prefix) (w:bool)\n    (op:operand) (poff: pseudo_reg (opsize (op_override pre) w)) \n    (bitval: pseudo_reg size1):\n    Conv unit :=\n    let seg := get_segment_op pre DS op in\n    let load := load_op pre w seg in\n    let set := set_op pre w seg in\n    value <- load op;\n    newvalue <- modify_Bit value poff bitval;\n    set newvalue op.\n\n  (*Set a bit given a word referenced by a raw address*)\n  Definition set_Bit_mem (pre:prefix) (w:bool)\n    (op:operand) (addr:pseudo_reg size32) (poff: pseudo_reg (opsize (op_override pre) w)) \n    (bitval: pseudo_reg size1):\n    Conv unit :=\n    let seg := get_segment_op pre DS op in\n    let load := load_mem pre w seg in\n    let set := set_mem pre w seg in\n    value <- load addr;\n    newvalue <- modify_Bit value poff bitval;\n    (* adding copy_ps makes the proof much easier since it meets the pattern \n             \"addr <- v; set_mem_n ... addr\" *)\n    newaddr <- copy_ps addr; \n    set newvalue newaddr.\n\n  (* id, comp, set, or reset on a single bit, depending on the params*)\n  Definition fbit (param1: bool) (param2: bool) (v: pseudo_reg size1):\n    Conv (pseudo_reg size1) :=\n    pone <- load_Z size1 1;\n    pzero <- load_Z size1 0;\n    match param1, param2 with\n      | true, true => ret pone\n      | true, false => ret pzero\n      | false, true => ret v\n      | false, false => v1 <- (not v); ret v1\n    end.\n\n  (*tt: set, tf: clear, ft: id, ff: complement*)\n  Definition conv_BT (param1: bool) (param2: bool)\n    (pre: prefix) (op1 : operand) (regimm: operand) :=\n    let seg := get_segment_op pre DS op1 in\n    let load := load_op pre true seg in\n    let lmem := load_mem pre true seg in\n    let opsz := opsize (op_override pre) true in\n    undef_flag OF;;\n    undef_flag SF;;\n    undef_flag AF;;\n    undef_flag PF;;\n    pi <- load regimm;\n    popsz <- load_Z opsz (BinInt.Z_of_nat opsz + 1);\n    rawoffset <- \n      (match regimm with\n         | Imm_op i =>\n           arith modu_op pi popsz\n         | _ => copy_ps pi\n       end\n      );\n    popsz_bytes <- load_Z size32 ((BinInt.Z_of_nat (opsz + 1))/8);\n    pzero <- load_Z opsz 0;\n    pneg1 <- load_Z size32 (-1)%Z;\n    (*for factoring out what we do when we access mem*)\n    (*psaddr is the base word address*)\n    let btmem psaddr := \n        bitoffset <- arith mods_op rawoffset popsz;\n        wordoffset' <- arith divs_op rawoffset popsz;\n        (*Important to preserve sign here*)\n        wordoffset <- cast_s size32 wordoffset';\n        (*if the offset is negative, we need to the word offset needs to\n           be shifted one more down, and the offset needs to be made positive *)\n        isneg <- test lt_op bitoffset pzero;\n        (*nbitoffset:size_opsz and nwordoffset:size32 are final signed values*)\n        nbitoffset <- copy_ps bitoffset;\n        nwordoffset <- copy_ps wordoffset;\n        (*If the bitoffset was lt zero, we need to adjust values to make them positive*)\n        negbitoffset <- arith add_op popsz bitoffset;\n        negwordoffset <- arith add_op pneg1 wordoffset;\n        emit (if_rtl isneg (cast_u_rtl negbitoffset nbitoffset));;\n        emit (if_rtl isneg (cast_u_rtl negwordoffset nwordoffset));;\n        newaddrdelta <- arith mul_op nwordoffset popsz_bytes;\n        newaddr <- arith add_op newaddrdelta psaddr;\n        \n        value <- lmem newaddr;\n        bt <- get_Bit value nbitoffset;\n        set_flag CF bt;;\n        newbt <- fbit param1 param2 bt;\n        set_Bit_mem pre true op1 newaddr nbitoffset newbt in\n    match op1 with\n      | Imm_op _ => emit error_rtl\n      | Reg_op r1 =>\n        value <- load (Reg_op r1);\n        bitoffset <- arith modu_op rawoffset popsz;\n        bt <- get_Bit value bitoffset;\n        set_flag CF bt;;\n        newbt <- fbit param1 param2 bt;\n        set_Bit pre true op1 bitoffset newbt\n      | Address_op a => \n        psaddr <- compute_addr a;\n        btmem psaddr\n      | Offset_op ioff => \n        psaddr <- load_int ioff;\n        btmem psaddr\n    end\n.\n    \n  Definition conv_BSWAP (pre: prefix) (r: register) :=\n    let seg := get_segment pre DS in\n      eight <- load_Z size32 8;\n      ps0 <- load_reg r;\n      b0 <- cast_u size8 ps0;\n\n      ps1 <- arith shru_op ps0 eight;\n      b1 <- cast_u size8 ps1;\n      w1 <- cast_u size32 b1;\n\n      ps2 <- arith shru_op ps1 eight;\n      b2 <- cast_u size8 ps2;\n      w2 <- cast_u size32 b2;\n\n      ps3 <- arith shru_op ps2 eight;\n      b3 <- cast_u size8 ps3;\n      w3 <- cast_u size32 b3;\n\n      res0 <- cast_u size32 b0;\n      res1 <- arith shl_op res0 eight;\n      res2 <- arith add_op res1 w1;\n      res3 <- arith shl_op res2 eight;\n      res4 <- arith add_op res3 w2;\n      res5 <- arith shl_op res4 eight;\n      res6 <- arith add_op res5 w3;\n      set_reg res6 r.\n\n  Definition conv_CWDE (pre: prefix) :=\n    let seg := get_segment pre DS in\n      match op_override pre with\n        | true =>  p1 <- iload_op8 seg (Reg_op EAX);\n                   p2 <- cast_s size16 p1;\n                   iset_op16 seg p2 (Reg_op EAX)\n        | false => p1 <- iload_op16 seg (Reg_op EAX);\n                   p2 <- cast_s size32 p1;\n                   iset_op32 seg p2 (Reg_op EAX)\n      end.\n\n  Definition conv_CDQ (pre: prefix) :=\n    let seg := get_segment pre DS in\n      match op_override pre with\n        | true =>  p1 <- iload_op16 seg (Reg_op EAX);\n                   p2 <- cast_s size32 p1;\n                   p2_bottom <- cast_s size16 p2;\n                   sixteen <- load_Z _ 16;\n                   p2_top0 <- arith shr_op p2 sixteen;\n                   p2_top <- cast_s size16 p2_top0;\n                   iset_op16 seg p2_bottom (Reg_op EAX);;\n                   iset_op16 seg p2_top (Reg_op EDX)\n        | false =>  p1 <- iload_op32 seg (Reg_op EAX);\n                   p2 <- cast_s 63 p1;\n                   p2_bottom <- cast_s size32 p2;\n                   thirtytwo <- load_Z _ 32;\n                   p2_top0 <- arith shr_op p2 thirtytwo;\n                   p2_top <- cast_s size32 p2_top0;\n                   iset_op32 seg p2_bottom (Reg_op EAX);;\n                   iset_op32 seg p2_top (Reg_op EDX)\n      end.\n          \n\n  Definition conv_MOV (pre: prefix) (w: bool) (op1 op2: operand) : Conv unit :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    let seg := get_segment_op2 pre DS op1 op2 in\n        res <- load seg op2;\n        set seg res op1.\n\n  (* Note that cmov does not have a byte mode - however we use it as a pseudo-instruction\n     to simplify some of the other instructions (e.g. CMPXCHG *)\n\n  Definition conv_CMOV (pre: prefix) (w: bool) (cc: condition_type) (op1 op2: operand) : Conv unit :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    let seg := get_segment_op2 pre DS op1 op2 in\n        tmp <- load seg op1;\n        src <- load seg op2;\n        cc <- compute_cc cc;\n        emit (if_rtl cc (cast_u_rtl src tmp));;\n        set seg tmp op1.\n\n  Definition conv_MOV_extend (extend_op: forall s1 s2: nat, pseudo_reg s1 \n    -> Conv (pseudo_reg s2)) (pre: prefix) (w: bool) (op1 op2: operand) : Conv unit :=\n    let seg := get_segment_op2 pre DS op1 op2 in\n    match op_override pre, w with\n      (* It's not really clear what should be done true, true here. It's not in the table,\n         but it seems to be a valid instruction. It would correspond to sign/zero\n         extending a 16 bit value to a 16 bit value... ie just moving *)\n      | true, true =>  p1 <- iload_op16 seg op2;\n                       iset_op16 seg p1 op1\n      | false, true => p1 <- iload_op16 seg op2;\n                       p2 <- extend_op _ _ p1;\n                       iset_op32 seg p2 op1\n      | true, false => p1 <- iload_op8 seg op2;\n                       p2 <- extend_op _ _ p1;\n                       iset_op16 seg p2 op1\n      | false, false => p1 <- iload_op8 seg op2;\n                        p2 <- extend_op _ _ p1;\n                        iset_op32 seg p2 op1\n    end.\n\n  Definition conv_MOVZX pre w op1 op2 := conv_MOV_extend cast_u pre w op1 op2.\n  Definition conv_MOVSX pre w op1 op2 := conv_MOV_extend cast_s pre w op1 op2.\n\n  Definition conv_XCHG (pre: prefix) (w: bool) (op1 op2: operand) : Conv unit :=\n    let load := load_op pre w in\n    let set := set_op pre w in\n    let seg := get_segment_op2 pre DS op1 op2 in\n        p1 <- load seg op1;\n        p2 <- load seg op2;\n        set seg p2 op1;;\n        set seg p1 op2.\n\n  Definition conv_XADD (pre: prefix) (w: bool) (op1 op2: operand) : Conv unit :=\n    conv_XCHG pre w op1 op2;;\n    conv_ADD pre w op1 op2.\n\n  (* This actually has some interesting properties for concurrency stuff\n     but for us this doesn't matter yet *)\n  Definition conv_CMPXCHG (pre: prefix) (w: bool) (op1 op2: operand) : Conv unit :=\n    (* The ZF flag will be set by the CMP to be zero if EAX = op1 *)\n    conv_CMP pre w (Reg_op EAX) op1;;\n    conv_CMOV pre w (E_ct) op1 op2;;\n    conv_CMOV pre w (NE_ct) (Reg_op EAX) op1.\n\n  (* This handles shifting the ESI/EDI stuff by the correct offset\n     and in the appopriate direction for the string ops *) \n \n  Definition string_op_reg_shift reg pre w : Conv unit :=\n    offset <- load_Z _  \n                   (match op_override pre, w with\n                      | _, false => 1\n                      | true, true => 2\n                      | false, true => 4\n                    end);\n    df <- get_flag DF;\n    old_reg <- iload_op32 DS (Reg_op reg);\n    new_reg1 <- arith add_op old_reg offset;\n    new_reg2 <- arith sub_op old_reg offset;\n    emit set_loc_rtl new_reg1 (reg_loc reg);;\n    emit if_rtl df (set_loc_rtl new_reg2 (reg_loc reg)).\n\n  (*\n  Definition string_op_reg_shift pre w : Conv unit :=\n    offset <- load_Z _  \n                   (match op_override pre, w with\n                      | _, false => 1\n                      | true, true => 2\n                      | false, true => 4\n                    end);\n    df <- get_flag DF;\n    old_esi <- iload_op32 DS (Reg_op ESI);\n    old_edi <- iload_op32 DS (Reg_op EDI);\n\n    new_esi1 <- arith add_op old_esi offset;\n    new_esi2 <- arith sub_op old_esi offset;\n\n    new_edi1 <- arith add_op old_edi offset;\n    new_edi2 <- arith sub_op old_edi offset;\n   \n    emit set_loc_rtl new_esi1 (reg_loc ESI);;\n    emit if_rtl df (set_loc_rtl new_esi2 (reg_loc ESI));;\n\n    emit set_loc_rtl new_edi1 (reg_loc EDI);;\n    emit if_rtl df (set_loc_rtl new_edi2 (reg_loc EDI)).\n  *)\n\n  (* As usual we assume AddrSize = 32 bits *)\n  Definition conv_MOVS pre w : Conv unit :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    (* The dest segment has to be ES, but the source can\n       be overriden (DS by default)\n    *)\n    let seg_load := get_segment pre DS in \n    p1 <- load seg_load (Address_op (mkAddress Word.zero (Some ESI) None));\n    set ES p1 (Address_op (mkAddress Word.zero (Some EDI) None));;\n    string_op_reg_shift EDI pre w;;\n    string_op_reg_shift ESI pre w.\n\n  Definition conv_STOS pre w : Conv unit :=\n    let load := load_op pre w in \n    let set := set_op pre w in \n    p1 <- load DS (Reg_op EAX);\n    set ES p1 (Address_op (mkAddress Word.zero (Some EDI) None));;\n    string_op_reg_shift EDI pre w.\n\n  Definition conv_CMPS pre w : Conv unit :=\n    let seg1 := get_segment pre DS in \n    let op1 := (Address_op (mkAddress Word.zero (Some ESI) None)) in\n    let op2 := (Address_op (mkAddress Word.zero (Some EDI) None)) in\n    conv_SUB_CMP_generic false pre w op1 op2 op2 \n      seg1 seg1 ES;;\n    string_op_reg_shift EDI pre w;;\n    string_op_reg_shift ESI pre w.\n \n  Definition conv_LEA (pre: prefix) (op1 op2: operand) :=\n    let seg := get_segment_op pre DS op1 in\n      match op2 with\n        | Address_op a =>\n          r <- compute_addr a;\n          iset_op32 seg r op1\n        | _ => emit error_rtl\n      end.\n\n  Definition conv_HLT (pre:prefix) := \n    emit safe_fail_rtl.\n\n  Definition conv_SETcc (pre: prefix) (ct: condition_type) (op: operand) := \n    let seg := get_segment_op pre DS op in\n      ccval <- compute_cc ct;\n      ccext <- cast_u size8 ccval;\n      iset_op8 seg ccext op.\n      \n  (* Just a filter for some prefix stuff we're not really handling yet.\n     In the future this should go away. *)\n\n  Definition check_prefix (p: prefix) := \n    (match op_override p, addr_override p with\n       | false, false => ret tt\n       | true, false => ret tt\n       | _, _ => emit error_rtl\n     end).\n\n  (*\n  Definition conv_REP_generic (zfval: option Z) (oldpc_val: Word.wint size32) :=\n    oldecx <- load_reg ECX;\n    one <- load_Z _ 1;\n    newecx <- arith sub_op oldecx one;\n    emit set_loc_rtl newecx (reg_loc ECX);;\n    zero <- load_Z _ 0;\n    oldpc <- load_int oldpc_val;\n    op_guard <- test eq_op newecx zero;\n    guard <- not op_guard;\n    emit if_rtl guard (set_loc_rtl oldpc pc_loc);;\n    match zfval with\n      | None => ret tt\n      | Some z => v <- load_Z _ z;\n                  zf <- get_flag ZF;\n                  op_guard2 <- test eq_op zf v;\n                  guard2 <- not op_guard2;\n                  emit if_rtl guard2 (set_loc_rtl oldpc pc_loc)\n    end.     \n\n  Definition conv_REP := conv_REP_generic None.\n  Definition conv_REPE := conv_REP_generic (Some 0%Z).\n  Definition conv_REPNE := conv_REP_generic (Some 1%Z).\n\n  Definition conv_lock_rep (pre: prefix) (i: instr) :=\n      match lock_rep pre with \n        | Some lock | None => ret tt\n        | Some rep => match i with\n                        | MOVS _ => conv_REP oldpc\n                        | LODS _ => conv_REP oldpc\n                        | CMPS _ => conv_REPE oldpc\n                        | STOS _ => conv_REP oldpc\n                        | _ => emit error_rtl\n                      end\n        | _ => emit error_rtl\n      end.\n  *)\n\n  Definition instr_to_rtl (pre: prefix) (i: instr) :=\n    runConv \n    (check_prefix pre;;\n     match i with\n         | AND w op1 op2 => conv_AND pre w op1 op2\n         | OR w op1 op2 => conv_OR pre w op1 op2\n         | XOR w op1 op2 => conv_XOR pre w op1 op2\n         | TEST w op1 op2 => conv_TEST pre w op1 op2\n         | NOT w op1 => conv_NOT pre w op1\n         | INC w op1 => conv_INC pre w op1\n         | DEC w op1 => conv_DEC pre w op1\n         | ADD w op1 op2 => conv_ADD pre w op1 op2\n         | ADC w op1 op2 => conv_ADC pre w op1 op2\n         | CMP w op1 op2 => conv_CMP pre w op1 op2\n         | SUB w op1 op2 => conv_SUB pre w op1 op2\n         | SBB w op1 op2 => conv_SBB pre w op1 op2\n         | NEG w op1 => conv_NEG pre w op1 \n         | DIV w op => conv_DIV pre w op\n         | AAA => conv_AAA_AAS add_op\n         | AAS => conv_AAA_AAS sub_op\n         | AAD => conv_AAD\n         | AAM => conv_AAM\n         | DAA => conv_DAA_DAS (add_op) (@testcarryAdd size8)\n         | DAS => conv_DAA_DAS (sub_op) (@testcarrySub size8)\n         | HLT => conv_HLT pre\n         | IDIV w op => conv_IDIV pre w op\n         | IMUL w op1 op2 i => conv_IMUL pre w op1 op2 i\n         | MUL w op  => conv_MUL pre w op\n         | SHL w op1 op2 => conv_SHL pre w op1 op2\n         | SHR w op1 op2 => conv_SHR pre w op1 op2\n         | SHLD op1 op2 ri => conv_SHLD pre op1 op2 ri\n         | SHRD op1 op2 ri => conv_SHRD pre op1 op2 ri\n         | SAR w op1 op2 => conv_SAR pre w op1 op2\n         | BSR op1 op2 => conv_BSR pre op1 op2\n         | BSF op1 op2 => conv_BSF pre op1 op2\n         | BT op1 op2 => conv_BT false true pre op1 op2\n         | BTC op1 op2 => conv_BT false false pre op1 op2\n         | BTS op1 op2 => conv_BT true true pre op1 op2\n         | BTR op1 op2 => conv_BT true false pre op1 op2\n         | BSWAP r => conv_BSWAP pre r\n         | CWDE => conv_CWDE pre\n         | CDQ => conv_CDQ pre\n         | MOV w op1 op2 => conv_MOV pre w op1 op2 \n         | CMOVcc ct op1 op2 => conv_CMOV pre true ct op1 op2 \n         | MOVZX w op1 op2 => conv_MOVZX pre w op1 op2 \n         | MOVSX w op1 op2 => conv_MOVSX pre w op1 op2 \n         | XCHG w op1 op2 => conv_XCHG pre w op1 op2 \n         | XADD w op1 op2 => conv_XADD pre w op1 op2 \n         | CLC => conv_CLC\n         | CLD => conv_CLD\n         | STD => conv_STD\n         | STC => conv_STC\n         | MOVS w => conv_MOVS pre w\n         | CMPXCHG w op1 op2 => conv_CMPXCHG pre w op1 op2\n         | CMPS w => conv_CMPS pre w\n         | STOS w => conv_STOS pre w\n         | LEA op1 op2 => conv_LEA pre op1 op2\n         | SETcc ct op => conv_SETcc pre ct op\n         | CALL near abs op1 sel => conv_CALL pre near abs op1 sel\n         | LEAVE => conv_LEAVE pre\n         | POP op => conv_POP pre op\n         | POPA => conv_POPA pre\n         | PUSH w op => conv_PUSH pre w op\n         | PUSHA => conv_PUSHA pre\n         | RET ss disp => conv_RET pre ss disp\n         | ROL w op1 op2 => conv_ROL pre w op1 op2\n         | ROR w op1 op2 => conv_ROR pre w op1 op2\n         | RCL w op1 op2 => conv_RCL pre w op1 op2  \n         | RCR w op1 op2 => conv_RCR pre w op1 op2  \n         | LAHF => conv_LAHF\n         | SAHF => conv_SAHF\n         | CMC => conv_CMC\n         | JMP near abs op1 sel => conv_JMP pre near abs op1 sel\n         | Jcc ct disp => conv_Jcc pre ct disp \n         | LOOP disp => conv_LOOP pre false false disp\n         | LOOPZ disp => conv_LOOP pre true true disp\n         | LOOPNZ disp => conv_LOOP pre true false disp\n         | NOP _ => ret tt\n         | _ => emit error_rtl \n    end\n    ).\n\nEnd X86_Decode.\n\nLocal Open Scope Z_scope.\nLocal Open Scope monad_scope.\nImport X86_Decode.\nImport X86_RTL.\nImport X86_MACHINE.\n\nDefinition in_seg_bounds (s: segment_register) (o1: int32) : RTL bool :=\n  seg_limit <- get_loc (seg_reg_limit_loc s);\n  ret (Word.lequ o1 seg_limit).\n\nDefinition in_seg_bounds_rng (s: segment_register) (o1: int32) \n  (offset: int32) : RTL bool :=\n  seg_limit <- get_loc (seg_reg_limit_loc s);\n  let o2 := Word.add o1 offset in\n  ret (andb (Word.lequ o1 o2)\n            (Word.lequ o2 seg_limit)).\n\n(** fetch n bytes starting from the given location. *)\nFixpoint fetch_n (n:nat) (loc:int32) (r:rtl_state) : list int8 := \n  match n with \n    | 0%nat => nil\n    | S m => \n      AddrMap.get loc (rtl_memory r) :: \n        fetch_n m (Word.add loc (Word.repr 1)) r\n  end.\n\n(** Go into a loop trying to parse an instruction.  We iterate at most [n] times,\n    and at least once.  This returns the first successful match of the parser\n    as well as the length (in bytes) of the matched instruction.  Right now, \n    [n] is set to 15 but it should probably be calculated as the longest possible\n    match for the instruction parsers.  The advantage of this routine over the\n    previous one is two-fold -- first, we are guaranteed that the parser only\n    succeeds when we pass in bytes.  Second, we only fetch bytes that are\n    needed, so we don't have to worry about running out side a segment just\n    to support parsing.\n*)\nFixpoint parse_instr_aux\n  (n:nat) (loc:int32) (len:positive) (ps:Decode.X86_PARSER.instParserState) : \n  RTL ((prefix * instr) * positive) := \n  match n with \n    | 0%nat => Fail _ \n    | S m => b <- get_byte loc ; \n             match Decode.X86_PARSER.parse_byte ps b with \n               | (ps', nil) => \n                 parse_instr_aux m (Word.add loc (Word.repr 1)) (len + 1) ps'\n               | (_, v::_) => ret (v,len)\n             end\n  end.\n\nDefinition parse_instr (pc:int32) : RTL ((prefix * instr) * positive) :=\n  seg_start <- get_loc (seg_reg_start_loc CS);\n  (* add the PC to it *)\n  let real_pc := Word.add seg_start pc in\n    parse_instr_aux 15 real_pc 1 Decode.X86_PARSER.initial_parser_state.\n\n(** Fetch an instruction at the location given by the program counter.  Return\n    the abstract syntax for the instruction, along with a count in bytes for \n    how big the instruction is.  We fail if the bits do not parse, or have more\n    than one parse.  We should fail if these locations aren't mapped, but we'll\n    deal with that later. *)\nDefinition fetch_instruction (pc:int32) : RTL ((prefix * instr) * positive) :=\n  [pi, len] <- parse_instr pc;\n  in_bounds_rng <- in_seg_bounds_rng CS pc (Word.repr (Zpos len - 1));\n  if (in_bounds_rng) then ret (pi,len)\n  else SafeFail _.\n\nFixpoint RTL_step_list l :=\n  match l with\n    | nil => ret tt\n    | i::l' => interp_rtl i;; RTL_step_list l'\n  end.\n\nDefinition check_rep_instr (ins:instr) : RTL unit :=\n  match ins with\n    | MOVS _ | STOS _ | CMPS _ => ret tt\n    | _ => Fail _\n  end.\n\nDefinition run_rep \n  (pre:prefix) (ins: instr) (default_new_pc : int32) : RTL unit := \n  check_rep_instr ins;;\n  ecx <- get_loc (reg_loc ECX);\n  if (Word.eq ecx Word.zero) then set_loc pc_loc default_new_pc\n    else \n      set_loc (reg_loc ECX) (Word.sub ecx Word.one);;\n      RTL_step_list (X86_Decode.instr_to_rtl pre ins);;\n      ecx' <- get_loc (reg_loc ECX);\n      (if (Word.eq ecx' Word.zero) then \n        set_loc pc_loc default_new_pc\n        else ret tt);;\n       (* For CMPS we also need to break from the loop if ZF = 0 *)\n      match ins with\n        | CMPS _ =>\n          zf <- get_loc (flag_loc ZF);\n          if (Word.eq zf Word.zero) then set_loc pc_loc default_new_pc\n          else ret tt\n        | _ => ret tt\n      end.\n\nDefinition step : RTL unit := \n  flush_env;;\n  pc <- get_loc pc_loc ; \n  (* check if pc is in the code region; \n     different from the range checks in fetch_instruction; \n     this check makes sure the machine safely fails when pc is \n     out of bounds so that there is no need to fetch an instruction *)\n  pc_in_bounds <- in_seg_bounds CS pc;\n  if (pc_in_bounds) then \n    [pi,length] <- fetch_instruction pc ; \n    let (pre, instr) := pi in\n    let default_new_pc := Word.add pc (Word.repr (Zpos length)) in\n      match lock_rep pre with\n        | Some rep (* We'll only allow rep, not lock or repn *) =>\n          run_rep pre instr default_new_pc\n        | None => set_loc pc_loc default_new_pc;; \n                  RTL_step_list (X86_Decode.instr_to_rtl pre instr)\n        | _ => Fail _ \n      end\n  else SafeFail _.\n\nDefinition step_immed (m1 m2: rtl_state) : Prop := step m1 = (Okay_ans tt, m2).\nNotation \"m1 ==> m2\" := (step_immed m1 m2).\nRequire Import Relation_Operators.\nDefinition steps := clos_refl_trans rtl_state step_immed.\nNotation \"m1 '==>*' m2\" := (steps m1 m2) (at level 55, m2 at next level).\n\n\n", "meta": {"author": "mpettersson", "repo": "reins-verifier-proof", "sha": "44d0b8e0c29b07eb71b1d6d44b020648783409fb", "save_path": "github-repos/coq/mpettersson-reins-verifier-proof", "path": "github-repos/coq/mpettersson-reins-verifier-proof/reins-verifier-proof-44d0b8e0c29b07eb71b1d6d44b020648783409fb/Model/X86Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.22663955927174004}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\n\nSection AppendEntriesRequestsCameFromLeaders.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Definition append_entries_came_from_leaders (net : network) : Prop :=\n    forall p t n pli plt es ci,\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      exists ll,\n        In (t, ll) (leaderLogs (fst (nwState net (pSrc p)))).\n\n  Class append_entries_came_from_leaders_interface : Prop :=\n    {\n      append_entries_came_from_leaders_invariant :\n        forall net,\n          refined_raft_intermediate_reachable net ->\n          append_entries_came_from_leaders net\n    }.\nEnd AppendEntriesRequestsCameFromLeaders.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft/AppendEntriesRequestsCameFromLeadersInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.37754067580180184, "lm_q1q2_score": 0.22659551876347242}}
{"text": "(** We define high-level Pseudo-SPARCv8 language in this File *)\nRequire Import Coqlib.\nRequire Import Maps.\n\nRequire Import Integers.\nRequire Import LibTactics.\nOpen Scope Z_scope.\nImport ListNotations.\n\nRequire Import state.\nRequire Import language.\nRequire Import highlang.\nRequire Import reg_lemma.\n\n(*+ The low-level Language  +*)\n(* The low-level language is based on the SPARCv8 assembly defined in language.v  *)\nDefinition LProg : Type := XCodeHeap * (State * Word * Word).\n\nInductive opsave1 : RegFile * FrameList -> RegFile * FrameList -> Prop :=\n| Opsave1 : forall R R' R'' F F' k k' fmo fml fmi fm1 fm2,\n    get_R R cwp = Some (W k) -> k' = pre_cwp k ->\n    fetch R = Some [fmo; fml; fmi] -> F = F' ++ [fm1; fm2] -> R' = set_window R fm1 fm2 fmo ->\n    R'' = set_Rs R' [(Rpsr cwp, W k')] ->\n    opsave1 (R, F) (R'', fml :: fmi :: F').\n\nInductive oprestore1 : RegFile * FrameList -> RegFile * FrameList -> Prop :=\n| Oprestore1 : forall R R' R'' F F' k k' fmo fml fmi fm1 fm2,\n    get_R R cwp = Some (W k) -> k' = post_cwp k -> \n    fetch R = Some [fmo; fml; fmi] -> F = fm1 :: fm2 :: F' -> R' = set_window R fmi fm1 fm2 ->\n    R'' = set_Rs R' [(Rpsr cwp, W k')] ->\n    oprestore1 (R, F) (R'', F' ++ [fmo; fml]).\n\nInductive opsave : RegName -> Val -> RegFile * FrameList -> RegFile * FrameList -> Prop :=\n| Opsave : forall R R' R'' F F' k k' v v' rr fmo fml fmi fm1 fm2,\n    get_R R cwp = Some (W k) -> get_R R Rwim = Some (W v) -> k' = pre_cwp k -> win_masked k' v = false ->\n    fetch R = Some [fmo; fml; fmi] -> F = F' ++ [fm1; fm2] -> R' = set_window R fm1 fm2 fmo ->\n    R'' = set_Rs R' [(Rpsr cwp, W k'); (rr, v')] ->\n    opsave rr v' (R, F) (R'', fml :: fmi :: F').\n\nInductive oprestore' : RegFile * FrameList -> RegFile * FrameList -> Prop :=\n| Oprestore : forall R R' R'' F F' k k' v fmo fml fmi fm1 fm2,\n    get_R R cwp = Some (W k) -> get_R R Rwim = Some (W v) -> k' = post_cwp k -> win_masked k' v = false ->\n    fetch R = Some [fmo; fml; fmi] -> F = fm1 :: fm2 :: F' -> R' = set_window R fmi fm1 fm2 ->\n    R'' = set_Rs R' [(Rpsr cwp, W k')] ->\n    oprestore' (R, F) (R'', F' ++ [fmo; fml]).\n\nFixpoint set_Ms M (vl : list (Address * Val)) :=\n  match vl with\n  | (l, v) :: vl =>\n    set_Ms (MemMap.set l (Some v) M) vl\n  | nil => M\n  end.\n\nDefinition set_Mframe M (l0 l1 l2 l3 l4 l5 l6 l7 : Address) (fm : Frame) :=\n  match fm with\n  | consfm v0 v1 v2 v3 v4 v5 v6 v7 =>\n    set_Ms M\n           ((l0, v0) :: (l1, v1) :: (l2, v2) :: (l3, v3) :: (l4, v4) ::\n                         (l5, v5) :: (l6, v6) :: (l7, v7) :: nil)\n  end.\n\nInductive win_overflow : Memory * RegFile * FrameList -> Memory * RegFile * FrameList -> Prop :=\n| WinOverFlow :forall M M' M'' R R' F F0 w fm1 fm2 fm3 fm4 b,\n    F = F0 ++ (fm1 :: fm2 :: fm3 :: fm4 :: nil) -> get_frame_nth fm1 6 = Some (Ptr (b, $ 0)) ->\n    M' = set_Mframe M (b, $ 0) (b, $ 4) (b, $ 8) (b, $ 12)\n                    (b, $ 16) (b, $ 20) (b, $ 24) (b, $ 28) fm2 ->\n    M'' = set_Mframe M' (b, $ 32) (b, $ 36) (b, $ 40) (b, $ 44)\n                     (b, $ 48) (b, $ 52) (b, $ 56) (b, $ 60) fm3 ->\n    (get_R R Rwim = Some (W (($ 1) <<ᵢ w)) /\\ $ 0 <=ᵤᵢ w <=ᵤᵢ $ 7) ->\n    set_R R Rwim (W (($ 1) <<ᵢ (pre_cwp w))) = R' ->\n    win_overflow (M, R, F) (M'', R', F).\n\nInductive win_underflow : Memory * RegFile * FrameList -> Memory * RegFile * FrameList -> Prop :=\n| WinUnderFlow : forall M R R' F F' F0 fm1 fm2 fm1' fm2' b w,\n    F = fm1 :: fm2 :: F0 -> get_R R r30 = Some (Ptr (b, $ 0)) ->\n    fetch_frame M (b, $ 0) (b, $ 4) (b, $ 8) (b, $ 12)\n                (b, $ 16) (b, $ 20) (b, $ 24) (b, $ 28) = Some fm1' ->\n    fetch_frame M (b, $ 32) (b, $ 36) (b, $ 40) (b, $ 44)\n                (b, $ 48) (b, $ 52) (b, $ 56) (b, $ 60) = Some fm2' ->\n    F' = fm1' :: fm2' :: F0 ->\n    (get_R R Rwim = Some (W (($ 1) <<ᵢ w)) /\\ $ 0 <=ᵤᵢ w <=ᵤᵢ $ 7) ->\n    set_R R Rwim (W (($ 1) <<ᵢ (post_cwp w))) = R' ->\n    win_underflow (M, R, F) (M, R', F').\n\nInductive LH__ : XCodeHeap -> State * Word * Word -> msg -> State * Word * Word -> Prop :=\n| LNTrans : forall C i S S' pc npc,\n    C pc = Some (c (cntrans i)) -> Q__ S (cntrans i) S' ->\n    LH__ C (S, pc, npc) tau (S', npc, npc +ᵢ ($ 4))\n\n| LJumpl : forall C M aexp rd R R' F D pc npc f,\n    C pc = Some (c (cjumpl aexp rd)) ->\n    eval_addrexp R aexp = Some (W f) -> word_aligned (W f) = true ->\n    indom rd R -> set_R R rd (W pc) = R' ->\n    LH__ C ((M, (R, F), D), pc, npc) tau ((M, (R', F), D), npc, f)\n\n| LCall : forall C M (R R' : RegFile) F D pc npc f,\n    C pc = Some (c (ccall f)) ->\n    indom r15 R -> set_R R r15 (W pc) = R' ->\n    LH__ C ((M, (R, F), D), pc, npc) tau ((M, (R', F), D), npc, f)\n\n| LRetl : forall C M R F D pc npc f,\n    C pc = Some (c cretl) ->\n    get_R R r15 = Some (W f) ->\n    LH__ C ((M, (R, F), D), pc, npc) tau ((M, (R, F), D), npc, f +ᵢ ($ 8))\n\n| LBe_true : forall C M R F D pc npc f v,\n    C pc = Some (c (cbe f)) ->\n    get_R R z = Some (W v) -> v <> $ 0 ->\n    LH__ C ((M, (R, F), D), pc, npc) tau ((M, (R, F), D), npc, f)\n\n| LBe_false : forall C M R F D pc npc f,\n    C pc = Some (c (cbe f)) ->\n    get_R R z = Some (W $ 0) ->\n    LH__ C ((M, (R, F), D), pc, npc) tau ((M, (R, F), D), npc, npc +ᵢ ($ 4))\n         \n(* We give operational semantics for Print, Psave and Prestore  *)\n| LPrint : forall C M R F D pc npc v,\n    C pc = Some print ->\n    get_R R r8 = Some v ->\n    LH__ C ((M, (R, F), D), pc, npc) (out v) ((M, (R, F), D), npc, npc +ᵢ ($ 4))\n\n| LPsave_no_trap : forall M M' R R' D F F' b pc npc C w,\n    C pc = Some (Psave w) ->\n    Malloc M b ($ 0) w M' -> opsave r14 (Ptr (b, $ 0)) (R, F) (R', F') ->\n    LH__ C ((M, (R, F), D), pc, npc) tau ((M', (R', F'), D), npc, npc +ᵢ ($ 4))\n         \n| LPsave_trap : forall M M' R R' F F' D pc npc C w k v,\n    C pc = Some (Psave w) ->\n    get_R R cwp = Some (W k) ->\n    get_R R Rwim = Some (W v) ->\n    win_masked (pre_cwp k) v = true ->\n    win_overflow (M, R, F) (M', R', F') ->\n    LH__ C ((M, (R, F), D), pc, npc) tau ((M', (R', F'), D), pc, npc)\n\n| LPrestore_no_trap : forall M M' (R R' : RegFile) F F' D pc npc b C,\n    C pc = Some Prestore ->\n    Mfree M b = M' -> R r14 = Some (Ptr (b, $ 0)) -> oprestore' (R, F) (R', F') ->\n    LH__ C ((M, (R, F), D), pc, npc) tau ((M', (R', F'), D), npc, npc +ᵢ ($ 4))\n\n| LPrestore_trap : forall M M' R R' F F' D pc npc C k v,\n    C pc = Some Prestore ->\n    get_R R cwp = Some (W k) ->\n    get_R R Rwim = Some (W v) ->\n    win_masked (post_cwp k) v = true ->\n    win_underflow (M, R, F) (M', R', F') ->\n    LH__ C ((M, (R, F), D), pc, npc) tau ((M', (R', F'), D), pc, npc).\n\nInductive LP__ : LProg -> msg -> LProg -> Prop :=\n| LCstep : forall C LM LM' LR LR' LR'' D D' D'' F F' pc pc' npc npc' m,\n    (LR', D') = exe_delay LR D ->\n    LH__ C ((LM, (LR', F), D'), pc, npc) m ((LM', (LR'', F'), D''), pc', npc') ->\n    LP__ (C, ((LM, (LR, F), D), pc, npc)) m (C, ((LM', (LR'', F'), D''), pc', npc')).\n", "meta": {"author": "jpzha", "repo": "VeriSparc", "sha": "7fc60fbc4b4357b93836d1b461d7d27c669e9f58", "save_path": "github-repos/coq/jpzha-VeriSparc", "path": "github-repos/coq/jpzha-VeriSparc/VeriSparc-7fc60fbc4b4357b93836d1b461d7d27c669e9f58/coqimp/ext/lowlang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.22657270101319807}}
{"text": "From iris.base_logic.lib Require Import invariants.\nFrom BurrowLang Require Import lang simp adequacy primitive_laws.\nFrom Tpcms Require Import rwlock.\nRequire Import Burrow.tpcms.\nRequire Import Burrow.ra.\nRequire Import Burrow.trees.\nRequire Import cpdt.CpdtTactics.\nRequire Import Burrow.tactics.\nRequire Import Tpcms.auth_frag.\n\nFrom iris.base_logic Require Export base_logic.\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Import ectx_lifting.\nFrom BurrowLang Require Import notation tactics class_instances.\nFrom BurrowLang Require Import heap_ra.\nFrom BurrowLang Require Import lang.\nFrom iris Require Import options.\n\n(* really crummy sequence library *)\n\nDefinition seq_idx : lang.val :=\n  (rec: \"seq_idx\" \"i\" \"array\" :=\n      if: (BinOp EqOp \"i\" #0) then\n        Fst \"array\"\n      else\n        \"seq_idx\" (\"i\" + #(-1)) (Snd \"array\")\n  ).\n  \nFixpoint has_elem (v: lang.val) (i: nat) : Prop :=\n  match i, v with\n  | O, (PairV l _ ) => True\n  | S i, (PairV _ r ) => has_elem r i\n  | _, _ => False\n  end.\n  \nDefinition has_length (v: lang.val) (len: nat) : Prop :=\n  match len with\n  | O => True\n  | S j => has_elem v j\n  end.\n  \nLemma has_elem_of_has_elem : ∀ (j: nat) (i: nat) (v: lang.val) \n    (lt: i ≤ j) , has_elem v j -> has_elem v i.\nProof.\n  induction j.\n  - intros. assert (@eq nat i%nat 0%nat) by lia. subst i. trivial.\n  - intros. destruct v.\n    + cbn [has_elem] in H. contradiction.\n    + cbn [has_elem] in H. contradiction.\n    + cbn [has_elem] in H. destruct i.\n      * unfold has_elem. trivial.\n      * cbn [has_elem]. apply IHj; trivial. lia.\nQed.\n\nLemma has_elem_of_has_length : ∀ (len: nat) (v: lang.val) (i: nat)\n    (lt: i < len) , has_length v len -> has_elem v i.\nProof.\n  intros. unfold has_length in H.\n  destruct len. - lia.\n  - apply has_elem_of_has_elem with (j := len); trivial. lia.\nQed.\n\nFixpoint elem (v: lang.val) (i: nat) :=\n  match i, v with\n  | O, (PairV l _ ) => l\n  | S i, (PairV _ r ) => elem r i\n  | _, _ => #()\n  end.\n  \nSection SeqProof.\n\nContext `{heap_hastpcm: !HasTPCM 𝜇 (AuthFrag (gmap loc (option lang.val)))}.\nContext `{!simpGS 𝜇 Σ}.\n\nLemma wp_seq_idx (seq: lang.val) (i: nat)\n  (he: has_elem seq i) :\n      {{{ True }}}\n      seq_idx #i seq\n      {{{ RET (elem seq i); True }}}.\nProof.\n  iIntros (P) \"_ P\". unfold seq_idx. wp_pures.\n  generalize he. generalize i. clear he. clear i. induction seq; intros i he.\n    - cbn [has_elem] in he. destruct i; contradiction.\n    - cbn [has_elem] in he. destruct i; contradiction.\n    - cbn [has_elem] in he. destruct i.\n      + wp_pures. unfold elem.\n        iModIntro. iApply \"P\". trivial.\n      + wp_pures.\n        replace ((Z.add (S i) (Zneg xH))) with (i : Z) by lia.\n        cbn [elem].\n        apply IHseq2; trivial.\nQed.\n\nEnd SeqProof.\n", "meta": {"author": "secure-foundations", "repo": "burrow", "sha": "a7022aa81e1e19d31b6ae7b8803790c64ac2b511", "save_path": "github-repos/coq/secure-foundations-burrow", "path": "github-repos/coq/secure-foundations-burrow/burrow-a7022aa81e1e19d31b6ae7b8803790c64ac2b511/src/examples/seqs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.22657270101319807}}
{"text": "Require Import MirrorCore.Reify.Reify.\nRequire Import MirrorCore.Lambda.Expr.\n\nRequire Import Java.Logic.AssertionLogic.\nRequire Import Java.Logic.SpecLogic.\nRequire Import Java.Language.Program.\nRequire Import Java.Language.Lang.\nRequire Import Java.Semantics.OperationalSemantics.\nRequire Import Java.Func.JavaFunc.\nRequire Import Java.Func.JavaType.\n\nRequire Import Charge.ModularFunc.ILogicFunc.\nRequire Import Charge.ModularFunc.BILogicFunc.\nRequire Import Charge.ModularFunc.LaterFunc.\nRequire Import Charge.ModularFunc.BaseFunc.\nRequire Import Charge.ModularFunc.ListFunc.\nRequire Import Charge.ModularFunc.OpenFunc.\nRequire Import Charge.ModularFunc.EmbedFunc.\nRequire Import Charge.Open.Stack.\nRequire Import Charge.Open.Subst.\nRequire Import Charge.Open.OpenILogic.\nRequire Import Charge.Logics.BILogic.\nRequire Import Charge.Logics.Later.\n\nRequire Import ExtLib.Structures.Applicative.\n\nReify Declare Patterns patterns_java_typ := typ.\n\nReify Declare Patterns patterns_java := (ExprCore.expr typ func).\n\nLocal Instance Applicative_Fun A : Applicative (Fun A) :=\n{ pure := fun _ x _ => x\n; ap := fun _ _ f x y => (f y) (x y)\n}.\n\n(*\nReify Declare Patterns const_for_cmd += ((RHasType cmd ?0) => (fun (c : id cmd) => mkCmd [c] : expr typ func)).\n*)\n\nRequire Import MirrorCore.Reify.Reify.\n\nAxiom t : Type.\nReify Declare Patterns t_pat := t.\n\n\n\nReify Declare Syntax t_cmd :=\n{ (@Patterns.CPatterns t t_pat) }.\n\n\nReify Declare Syntax reify_imp_typ :=\n  { \n  \t(@Patterns.CPatterns typ patterns_java_typ)\n  }.\n\nReify Declare Typed Table term_table : BinNums.positive => reify_imp_typ.\n\nCheck term_table.\n\nLocate exprD.\n\nRequire Import MirrorCore.ExprI.\n\nCheck @exprD.\nPrint Expr.\nPrint RType.\nLet Ext x := @ExprCore.Inj typ func (inl (inl (inl (inl (inl (inl (inl (inl x)))))))).\n\nReify Declare Syntax reify_imp :=\n  { (@Patterns.CFirst _\n  \t\t((@Patterns.CVar _ (@ExprCore.Var typ func)) ::\n  \t     (@Patterns.CPatterns _ patterns_java) ::\n         (@Patterns.CApp _ (@ExprCore.App typ func)) ::\n    \t (@Patterns.CAbs _ reify_imp_typ (@ExprCore.Abs typ func)) ::\n    \t (@Patterns.CTypedTable _ _ _ term_table Ext) :: nil))\n  }.\n\nDefinition stack_get (x : Lang.var) (s : Lang.stack) := s x.\n\nNotation \"'ap_eq' '[' x ',' y ']'\" :=\n\t (ap (T := Fun Lang.stack) (ap (T := Fun Lang.stack) (pure (T := Fun Lang.stack) (@eq val)) x) y).\nNotation \"'ap_pointsto' '[' x ',' f ',' e ']'\" := \n\t(ap (T := Fun Lang.stack) (ap (T := Fun Lang.stack) (ap (T := Fun Lang.stack) \n\t\t(pure (T := Fun Lang.stack) pointsto) (stack_get x)) \n\t\t\t(pure (T := Fun Lang.stack) f)) e).\nNotation \"'ap_typeof' '[' e ',' C ']'\" :=\n\t(ap (T := Fun Lang.stack) \n\t    (ap (T := Fun Lang.stack) \n\t        (pure (T := Fun Lang.stack) typeof) \n\t        (pure (T := Fun Lang.stack) C))\n\t    e).\n(*\nDefinition set_fold_fun (x f : String.string) (P : sasn) :=\n\tap_pointsto [x, f, pure null] ** P.\n*)\nLet _Inj := @ExprCore.Inj typ func.\n\nRequire Import Java.Examples.ListModel.\n(*\nReify Seed Typed Table term_table += 1 => [ (tyArr tyVal (tyArr (tyList tyVal) tyAsn)) , List ].\nReify Seed Typed Table term_table += 2 => [ (tyArr tyVal (tyArr (tyList tyVal) tyAsn)) , NodeList ].\n*)\n\nLocal Notation \"x @ y\" := (@RApp x y) (only parsing, at level 30).\nLocal Notation \"'!!' x\" := (@RExact _ x) (only parsing, at level 25).\nLocal Notation \"'?' n\" := (@RGet n RIgnore) (only parsing, at level 25).\nLocal Notation \"'?!' n\" := (@RGet n RConst) (only parsing, at level 25).\nLocal Notation \"'#'\" := RIgnore (only parsing, at level 0).\n\nReify Pattern patterns_java_typ += (@RImpl (?0) (?1)) => (fun (a b : function reify_imp_typ) => tyArr a b).\n\nReify Pattern patterns_java_typ += (!! asn)  => tyAsn.\nReify Pattern patterns_java_typ += (!! sasn) => tySasn.\nReify Pattern patterns_java_typ += (!! (@vlogic Lang.var val)) => tyPure.\nReify Pattern patterns_java_typ += (!! Prop) => tyProp.\nReify Pattern patterns_java_typ += (!! spec) => tySpec.\n\nReify Pattern patterns_java_typ += (!! @prod @ ?0 @ ?1) => (fun (x y : function reify_imp_typ) => tyPair x y).\nReify Pattern patterns_java_typ += (!! (@list String.string)) => tyVarList.\nReify Pattern patterns_java_typ += (!! (@list field)) => tyFields.\nReify Pattern patterns_java_typ += (!! (@list (@Open.expr (Lang.var) val))) => tyVarList.\nReify Pattern patterns_java_typ += (!! (@list (Lang.var * @Open.expr (Lang.var) val))) => tySubstList.\nReify Pattern patterns_java_typ += (!! (@substlist Lang.var val)) => tySubstList.\nReify Pattern patterns_java_typ += (!! @list @ ?0) => (fun x : function reify_imp_typ => tyList x).\nReify Pattern patterns_java_typ += (!! nat) => tyNat.\nReify Pattern patterns_java_typ += (!! val) => tyVal.\nReify Pattern patterns_java_typ += (!! bool) => tyBool.\nReify Pattern patterns_java_typ += (!! field) => tyString.\nReify Pattern patterns_java_typ += (!! class) => tyString.\nReify Pattern patterns_java_typ += (!! @Open.open Lang.var val asn) => tySasn.\nReify Pattern patterns_java_typ += (!! @Open.open Lang.var val Prop) => tyPure.\nReify Pattern patterns_java_typ += (!! Lang.var) => tyString.\nReify Pattern patterns_java_typ += (!! String.string) => tyString.\nReify Pattern patterns_java_typ += (!! Program) => tyProg.\nReify Pattern patterns_java_typ += (!! Lang.stack) => tyStack.\nReify Pattern patterns_java_typ += (!! @Stack.stack Lang.var val) => tyStack.\nReify Pattern patterns_java_typ += (!! cmd) => tyCmd.\nReify Pattern patterns_java_typ += (!! dexpr) => tyExpr.\nReify Pattern patterns_java_typ += (!! (@Open.expr Lang.var val)) => tyExpr.\nReify Pattern patterns_java_typ += (!! @Subst.subst (String.string) val) => tySubst.\n\nReify Pattern patterns_java_typ += (!! Fun @ ?0 @ ?1) => (fun (a b : function reify_imp_typ) => tyArr a b).\n\nReify Pattern patterns_java += (RHasType String.string (?0)) => (fun (s : id String.string) => mkString (func := func) (typ := typ) s).\nReify Pattern patterns_java += (RHasType field (?0)) => (fun (f : id field) => mkString (func := func) f).\nReify Pattern patterns_java += (RHasType Lang.var (?0)) => (fun (f : id Lang.var) => mkString (func := func) f).\nReify Pattern patterns_java += (RHasType val (?0)) => (fun (v : id val) => mkVal v).\nReify Pattern patterns_java += (RHasType bool (?0)) => (fun (b : id bool) => mkBool (func := func) b).\nReify Pattern patterns_java += (RHasType nat (?0)) => (fun (n : id nat) => mkNat (func := func) n).\nReify Pattern patterns_java += (RHasType cmd (?0)) => (fun (c : id cmd) => mkCmd c).\nReify Pattern patterns_java += (RHasType dexpr (?0)) => (fun (e : id dexpr) => mkDExpr e).\nReify Pattern patterns_java += (RHasType Program (?0)) => (fun (P : id Program) => mkProg P).\nReify Pattern patterns_java += (RHasType (list field) (?0)) => (fun (fs : id (list field)) => mkFields fs).\nReify Pattern patterns_java += (RHasType class (?0)) => (fun (c : id class) => mkString (func := func) c).\n\nReify Pattern patterns_java += (RHasType (@list dexpr) (?0)) => (fun (es : id (@list dexpr)) => mkExprList es).\nReify Pattern patterns_java += (RHasType (@list String.string) (?0)) => (fun (vs : id (@list String.string)) => mkFields vs).\nReify Pattern patterns_java += (!! (@eq) @ ?0) => (fun (x : function reify_imp_typ) => fEq (func := expr typ func) x).\n\n(** Intuitionistic Operators **)\nReify Pattern patterns_java += (!! @ILogic.lentails @ ?0 @ #) => (fun (x : function reify_imp_typ) => fEntails (func := expr typ func) x).\nReify Pattern patterns_java += (!! @ILogic.ltrue @ ?0 @ #) => (fun (x : function reify_imp_typ) => mkTrue (func := func) x).\nReify Pattern patterns_java += (!! @ILogic.lfalse @ ?0 @ #) => (fun (x : function reify_imp_typ) => mkFalse (func := func) x).\n\nReify Pattern patterns_java += (!! @ILogic.land @ ?0 @ #) => (fun (x : function reify_imp_typ) => fAnd (func := expr typ func) x).\nReify Pattern patterns_java += (!! @ILogic.lor @ ?0 @ #) => (fun (x : function reify_imp_typ) => fOr (func := expr typ func) x).\nReify Pattern patterns_java += (!! @ILogic.limpl @ ?0 @ #) => (fun (x : function reify_imp_typ) => fImpl (func := expr typ func) x).\n\nReify Pattern patterns_java += (!! @ILogic.lexists @ ?0 @ # @ ?1) => (fun (x y : function reify_imp_typ) => fExists (func := expr typ func) y x).\n\nReify Pattern patterns_java += (!! @ILogic.lforall @ ?0 @ # @ ?1) => (fun (x y : function reify_imp_typ) => fForall (func := expr typ func) y x).\n(** Embedding Operators **)\nReify Pattern patterns_java += (!! @ILEmbed.embed @ ?0 @ ?1 @ #) => (fun (x y : function reify_imp_typ) => fEmbed (func := expr typ func) x y).\n\nReify Pattern patterns_java += (!! @pair @ ?0 @ ?1) => (fun (x y : function reify_imp_typ) => fPair (func := expr typ func) x y).\n\n(** Special cases for Coq's primitives **)\nReify Pattern patterns_java += (!! True) => (mkTrue (func := func) tyProp).\nReify Pattern patterns_java += (!! False) => (mkFalse (func := func) tyProp).\nReify Pattern patterns_java += (!! and) => (fAnd (func := expr typ func) tyProp).\n\nReify Pattern patterns_java += (!! or) => (fOr (func := expr typ func) tyProp).\n\nReify Pattern patterns_java += (!! ex @ ?0) => (fun (x : function reify_imp_typ) => fExists (func := expr typ func) x tyProp).\n\nReify Pattern patterns_java += (RPi (?0) (?1)) => (fun (x : function reify_imp_typ) (y : function reify_imp) =>\n                                                   ExprCore.App (fForall (func := expr typ func) x tyProp) (ExprCore.Abs x y)).\n\nReify Pattern patterns_java += (RImpl (?0) (?1)) => (fun (x y : function reify_imp) => \n\tExprCore.App (ExprCore.App (fImpl (func := expr typ func) tyProp) x) y).\n\n(** Separation Logic Operators **)\nReify Pattern patterns_java += (!! @BILogic.sepSP @ ?0 @ #) => (fun (x : function reify_imp_typ) => (fStar (func := expr typ func) x)).\nReify Pattern patterns_java += (!! @BILogic.wandSP @ ?0 @ #) => (fun (x : function reify_imp_typ) => (fWand (func := expr typ func) x)).\nReify Pattern patterns_java += (!! @BILogic.empSP @ ?0 @ #) => (fun (x : function reify_imp_typ) => (mkEmp (func := func) x)).\n\nReify Pattern patterns_java += (!! @Later.illater @ ?0 @ #) => (fun (x : function reify_imp_typ) => (fLater (func := expr typ func) x)).\n\nReify Pattern patterns_java += (!! method_spec) => (fMethodSpec).\n\n(** Program Logic **)\n\n\nReify Pattern patterns_java += (!! triple) => (fTriple).\nReify Pattern patterns_java += (!!method_lookup) => fMethodLookup.\nReify Pattern patterns_java += (!!field_lookup) => fFieldLookup.\nReify Pattern patterns_java += (!!m_ret) => fMethodRet.\nReify Pattern patterns_java += (!!m_body) => fMethodBody.\nReify Pattern patterns_java += (!!m_params) => fMethodArgs.\n\nReify Pattern patterns_java += (!! eval @ (RHasType dexpr (?0))) => (fun e : id dexpr => evalDExpr e).\nReify Pattern patterns_java += (!! stack_get) => (fStackGet (typ := typ) (func := expr typ func)).\nReify Pattern patterns_java += (!! stack_add (val := val)) => (fStackSet (typ := typ) (func := expr typ func)).\n\nReify Pattern patterns_java += (!! pointsto) => (fPointsto).\nReify Pattern patterns_java += (!! prog_eq) => (fProgEq).\nReify Pattern patterns_java += (!! typeof) => (fTypeOf).\n\nReify Pattern patterns_java += (!! (@substl_trunc Lang.var val _)) => (fTruncSubst (func := expr typ func) (typ := typ)).\nReify Pattern patterns_java += (!! (@substl Lang.var val _)) => (fSubst (func := expr typ func) (typ := typ)).\n\nReify Pattern patterns_java += (!! @nil @ ?0) => (fun (x : function reify_imp_typ) => (fNil (func := expr typ func) x)).\nReify Pattern patterns_java += (!! @cons @ ?0) => (fun (x : function reify_imp_typ) => (fCons (func := expr typ func) x)).\nReify Pattern patterns_java += (!! @length @ ?0) => (fun (x : function reify_imp_typ) => (fLength (func := expr typ func) x)).\nReify Pattern patterns_java += (!! @zip @ ?0 @ ?1) => (fun (x y : function reify_imp_typ) => (fZip (func := expr typ func) x y)).\nReify Pattern patterns_java += (!! @map @ ?0 @ ?1) => (fun (x y : function reify_imp_typ) => (fMap (func := expr typ func) x y)).\nReify Pattern patterns_java += (!! @fold_right @ ?0 @ ?1) => (fun (x y : function reify_imp_typ) => (fFold (func := expr typ func) x y)).\n\nReify Pattern patterns_java += (!! (@apply_subst Lang.var val) @ ?0) => (fun (x : function reify_imp_typ) => fApplySubst (func := expr typ func) x).\nReify Pattern patterns_java += (!! @subst1 Lang.var val _) => (fSingleSubst (func := expr typ func)).\nReify Pattern patterns_java += (!! @field_lookup) => (fFieldLookup).\n(** Applicative **)\nReify Pattern patterns_java += (!! @Applicative.ap @ !! (Fun Lang.stack) @ # @ ?0 @ ?1) => (fun (x y : function reify_imp_typ) => fAp (func := expr typ func) x y).\nReify Pattern patterns_java += (!! @Applicative.pure @ !! (Fun Lang.stack) @ # @ ?0) => (fun (x : function reify_imp_typ) => fConst (func := expr typ func) x).\n\nLet elem_ctor : forall x : typ, typD x -> @SymEnv.function _ _ :=\n  @SymEnv.F _ _.\n\nLtac reify_imp e :=\n  let k fs e :=\n      pose e in\n  reify_expr reify_imp k\n             [ (fun (y : @mk_dvar_map _ _ _ _ term_table elem_ctor) => True) ]\n             [ e ].\n\nRequire Import ILogic.\n\nGoal (forall (Pr : Program) (C : class) (v : val) (fields : list field), True).\n  intros Pr C v fields.\n  reify_imp (typeof C v).\n\n  reify_imp (field_lookup).\n  reify_imp (field_lookup Pr C fields).\n\n  pose ((fun (_ : @Stack.stack Lang.var val) => null) : @Open.expr Lang.var val) as e2.\n  pose ((fun (_ : Lang.stack) => null) : Lang.stack -> val) as e3.\n\n\n  reify_imp (pure (T := Fun Lang.stack) pointsto).\n\n  reify_imp (fun a b c => pointsto a b c).\n\n  reify_imp e2.\n  \n  reify_imp e3.\n\n  reify_imp (ap (T := Fun Lang.stack) (ap (T := Fun Lang.stack) (pure (@eq val)) e2) e2).\n\n  pose (E_val (vint 3)) as d.\n\n  reify_imp ((ap (ap (T := Fun Lang.stack) (pure (@eq val)) (eval d)) (pure (vbool true)))).\n  \n  generalize String.EmptyString. intro c.\n   reify_imp (ltrue |-- {[ ltrue ]} cread c c c {[ ltrue ]}).\n\n  reify_imp cskip.\n\n  reify_imp (forall P, P /\\ P).\n\n  reify_imp (forall x : nat, x = x).\n  reify_imp (exists x : nat, x = x).\n  reify_imp (@map nat nat).\n  reify_imp (@subst1 Lang.var val _).\n  reify_imp (cseq cskip cskip).\n  \n  reify_imp (ILogic.lentails True True).\n\n  reify_imp ((True -> False) -> True).\n  reify_imp (forall P Q, P /\\ Q).\n  reify_imp (forall P : sasn, ILogic.lentails ILogic.ltrue P).\n  reify_imp (forall (G : spec) (P Q : sasn), ILogic.lentails G (triple P Q cskip)).\n  generalize (String.EmptyString : String.string).\n  intro x.\n\n  reify_imp stack_get.\n\n  reify_imp (stack_get x).\n\n  reify_imp (x = x).\n\n  reify_imp (@ltrue sasn _).\n  exact I.\n\nDefined.\n\nLtac reify_aux e n :=\n  let k fs e :=\n      pose e as n in\n  reify_expr reify_imp k\n             [ (fun (y : @mk_dvar_map _ _ _ _ term_table elem_ctor) => True) ]\n             [ e ].\n", "meta": {"author": "jesper-bengtson", "repo": "Java", "sha": "bc889ae914e1ba39b2f4d0edcb63371ffd52a5dd", "save_path": "github-repos/coq/jesper-bengtson-Java", "path": "github-repos/coq/jesper-bengtson-Java/Java-bc889ae914e1ba39b2f4d0edcb63371ffd52a5dd/Java/src/Java/Func/Reify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953506426082, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.22657269530736368}}
{"text": "\n(**\n    VerifiedDSP\n    Copyright (C) {2015}  {Jeremy L Rubin}\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\n**)\n(* Copyright (c) 2011. Greg Morrisett, Gang Tan, Joseph Tassarotti, \n   Jean-Baptiste Tristan, and Edward Gan.\n\n   This file is part of RockSalt.\n\n   This file is free software; you can redistribute it and/or\n   modify it under the terms of the GNU General Public License as\n   published by the Free Software Foundation; either version 2 of\n   the License, or (at your option) any later version.\n*)\n\n(** * Regular expression matcher based on derivatives, inspired by the paper\n      of Owens, Reppy, and Turon.\n*) \nRequire Import Coq.Program.Equality.\nRequire Import Coq.Init.Logic.\nRequire Import List.\nRequire Import Arith.\nRequire Import Bool.\nRequire Import Eqdep.\nUnset Automatic Introduction.\nSet Implicit Arguments.\nAxiom proof_irrelevance : forall (P:Prop) (H1 H2:P), H1 = H2.\n\n(** ** Argument to the module that builds the parser *)\nModule Type PARSER_ARG.\n  (** We parameterize the development over a set of characters *)\n  Parameter char_p : Set.\n  Parameter char_eq : forall (c1 c2:char_p), {c1=c2} + {c1<>c2}.\n  (** Now we also parameterize over names for types used in the semantic actions. *)\n  Parameter tipe : Set.\n  (** And we require a decidable equality for type names. *)\n  Parameter tipe_eq : forall (t1 t2:tipe), {t1=t2} + {t1<>t2}.\n  (** And we require an interpretation of type names as sets. *)\n  Parameter tipe_m : tipe -> Set.\nEnd PARSER_ARG.\n\n(** ** The Parser functor *)\nModule Parser(PA : PARSER_ARG).\n  Import PA.\n\n  (** An inductively generated set of names for the types of results\n      returned by the parser.  We need at least unit, char, pairs, and\n      lists, as well as user-defined types (tipe). *)\n  Inductive result : Set := \n  | unit_t : result\n  | char_t : result\n  | pair_t : result -> result -> result\n  | list_t : result -> result\n  | sum_t  : result -> result -> result\n  | tipe_t : tipe -> result.\n\n  (** This allows us to build an equality on results. *)\n  Definition result_eq : forall (r1 r2:result), {r1=r2}+{r1<>r2}.\n    decide equality. apply tipe_eq.\n  Defined.\n\n  (** Now we give an interpretation of results as Coq sets. *)\n  Fixpoint result_m(t:result) : Set := \n    (match t with \n       | unit_t => unit\n       | char_t => char_p\n       | pair_t t1 t2 => (result_m t1) * (result_m t2)\n       | list_t t1 => list (result_m t1)\n       | sum_t t1 t2 => (result_m t1) + (result_m t2)\n       | tipe_t t => tipe_m t\n     end)%type.\n\n  (** ** Constructors for regular expression parsers. *)\n  (** The parsers are indexed by the return type as a [result], and we've\n      added a new kind of parser [Map_p] which is used to transform the\n      result of one parser to another. *)\n  Inductive parser : result -> Set := \n  | Any_p : parser char_t\n  | Char_p : char_p -> parser char_t\n  | Eps_p : parser unit_t\n  | Cat_p : forall t1 t2 (r1:parser t1) (r2:parser t2), parser (pair_t t1 t2)\n  | Zero_p : forall t, parser t\n  | Alt_p : forall t (r1 r2:parser t), parser t\n  | Star_p : forall t, parser t -> parser (list_t t)\n  | Map_p : forall t1 t2, ((result_m t1) -> (result_m t2)) -> parser t1 -> parser t2.\n\n  (** ** Denotational semantics for parsers *)\n  (** The semantics relates input strings (as lists of characters) to result values. *)\n  Inductive in_parser : forall t, parser t -> list char_p -> (result_m t) -> Prop := \n  | Any_pi : forall c cs v, cs = c::nil -> v = c -> in_parser Any_p cs v\n  | Char_pi : forall c cs v, cs = c::nil -> v = c-> in_parser (Char_p c) cs v\n  | Eps_pi : forall cs v, cs = nil -> v = tt -> in_parser Eps_p cs v\n  | Alt_left_pi : forall t (p1 p2:parser t) cs (v:result_m t), \n    in_parser p1 cs v -> in_parser (Alt_p p1 p2) cs v\n  | Alt_right_pi : forall t (p1 p2:parser t) cs (v:result_m t), \n    in_parser p2 cs v -> in_parser (Alt_p p1 p2) cs v\n  | Cat_pi : forall t1 t2 (p1:parser t1) (p2:parser t2) cs v cs1 cs2 v1 v2,\n    in_parser p1 cs1 v1 -> in_parser p2 cs2 v2 -> cs = cs1 ++ cs2 -> v = (v1,v2) -> \n    in_parser (Cat_p p1 p2) cs v\n  | Star_eps_pi : forall t (p:parser t) cs v, cs = nil -> v = nil -> \n    in_parser (Star_p p) cs v\n  | Star_cat_pi : forall t (p:parser t) cs v cs1 cs2 v1 v2,\n    in_parser p cs1 v1 -> in_parser (Star_p p) cs2 v2 -> \n    cs = cs1 ++ cs2 -> v = (v1::v2) -> cs1 <> nil -> \n    in_parser (Star_p p) cs v\n  | Map_pi : forall t1 t2 (f:result_m t1 -> result_m t2) (p:parser t1) cs v v1, \n    in_parser p cs v1 -> v = f v1 -> in_parser (Map_p _ f p) cs v.\n  (** Note that for [Star_cat_pi] we require [cs1] to be non-empty -- this is \n     crucial for ensuring that any regular expression matches a string and \n     returns a finite list of associated values. Otherwise, something like\n     [Star Eps] would take the empty string to an infinite set of possible \n     values. *)\n\n  (** ** Internal Representation of Parsers: [regexp]s *)\n  (** Internally, we translate parsers to a representation called [regexp] \n     where all of the functions are replaced with a function name that we can \n     look up in an environment.  This will allow us to put together a decidable \n     equality on regular expressions, which will in turn, allow us to hash-cons \n     them (though we don't take advantage of this yet.) *)\n\n  (** We'll represent function names as positions in an environment list. *)\n  Definition fn_name := nat.\n  Definition fn_name_eq := eq_nat_dec. \n\n  (** In addition to user-level functions, we need a few built-in functions that \n     are used during optimization.\n  *)\n  Inductive fn : result -> result -> Set := \n  | Fn_name : forall (f:fn_name) t1 t2, fn t1 t2\n  | Fn_const_char : forall (c:char_p), fn unit_t char_t  (* \\x:unit.c *)\n  | Fn_empty_list : forall t, fn unit_t (list_t t)     (* \\x:unit.@nil t *)\n  | Fn_cons : forall t, fn (pair_t t (list_t t)) (list_t t) (* \\x:(t*list t).(fst x)::(snd x) *)\n  | Fn_unit_left : forall t, fn t (pair_t unit_t t) (* \\x:t.(tt,x) *)\n  | Fn_unit_right : forall t, fn t (pair_t t unit_t) (* \\x:t.(x,tt) *)\n  | Fn_unit : forall t, fn t unit_t (* \\x:t.tt *)\n  .\n\n  (** Finally, a [regexp] is just like a [parser] except that the [Map] constructor\n     takes a [fn] instead of an actual function. Note that this syntax doesn't preclude \n     us from using a function name with the wrong type -- we'll capture this constraint\n     later on. *)\n  Inductive regexp : result -> Set :=\n  | Any  : regexp char_t\n  | Char : char_p -> regexp char_t\n  | Eps  : regexp unit_t\n  | Cat  : forall t1 t2, regexp t1 -> regexp t2 -> regexp (pair_t t1 t2)\n  | Alt  : forall t, regexp t -> regexp t -> regexp t\n  | Zero : forall t, regexp t\n  | Star : forall t, regexp t -> regexp (list_t t)\n  | Map  : forall (t u:result) (f:fn t u), regexp t -> regexp u.\n\n  (** A simplification tactic used through the development *)\n  Ltac mysimp := \n      simpl in * ; intros ; \n        repeat match goal with \n                 | [ |- context[char_eq ?x ?y] ] => destruct (char_eq x y) ; auto \n                 | [ |- _ /\\ _ ] => split\n                 | [ H : context[result_eq ?e1 ?e2] |- _ ] => \n                   destruct (result_eq e1 e2) ; simpl in * ; try discriminate\n                 | [ H : existT ?f ?t ?x = existT ?f ?t ?y |- _ ] => \n                   generalize (inj_pairT2 _ f t x y H) ; clear H ; intro H ; subst\n                 | [ H : _ /\\ _ |- _ ] => destruct H\n                 | [ |- context[ _ ++ nil ] ] => rewrite <- app_nil_end\n                 | [ H : exists x, _ |- _ ] => destruct H\n                 | [ H : _ \\/ _ |- _] => destruct H\n                 | [ H : _ <-> _ |- _] => destruct H\n                 | [ |- _ <-> _ ] => split\n                 | [ H : _::_ = _::_ |- _] => injection H ; clear H\n                 | _ => idtac\n               end ; auto.\n  (** Simplificaton followed by substitution. *)\n  Ltac s := repeat (mysimp ; subst).\n\n  (** Now we can try to define a syntactic equality checker on regexps.  We'll\n      begin by writing some simple functions that calculate booleans to avoid\n      some hair with dependencies.  *)\n  Definition s2b (P Q:Prop) (x:{P}+{Q}) : bool := \n    match x with \n      | left _ => true\n      | right _ => false\n    end.\n\n  (** Function equality *)\n  Definition fn_eq t1 u1 (f1:fn t1 u1) t2 u2 (f2:fn t2 u2) : bool := \n    match f1, f2 with \n      | Fn_name f1 t1 u1, Fn_name f2 t2 u2 => \n        s2b (fn_name_eq f1 f2) && s2b (result_eq t1 t2) && s2b (result_eq u1 u2)\n      | Fn_const_char c1, Fn_const_char c2 => if char_eq c1 c2 then true else false\n      | Fn_empty_list t1, Fn_empty_list t2 => s2b (result_eq t1 t2)\n      | Fn_cons t1, Fn_cons t2 => s2b (result_eq t1 t2)\n      | Fn_unit_left t1, Fn_unit_left t2 => s2b (result_eq t1 t2)\n      | Fn_unit_right t1, Fn_unit_right t2 => s2b (result_eq t1 t2)\n      | Fn_unit t1, Fn_unit t2 => s2b (result_eq t1 t2)\n      | _, _ => false\n    end.\n\n  (** Regexp equality *)\n  Fixpoint regexp_eq' t1 (r1:regexp t1) t2 (r2:regexp t2) : bool := \n    match r1, r2 with \n      | Any, Any => true\n      | Char c1, Char c2 => if char_eq c1 c2 then true else false\n      | Eps, Eps => true\n      | Cat t1a t1b r1a r1b, Cat t2a t2b r2a r2b => \n        regexp_eq' r1a r2a && regexp_eq' r1b r2b\n      | Alt t1 r1a r1b, Alt t2 r2a r2b => \n        regexp_eq' r1a r2a && regexp_eq' r1b r2b\n      | Zero t1, Zero t2 => s2b(result_eq t1 t2)\n      | Star t1 r1a, Star t2 r2a => regexp_eq' r1a r2a\n      | Map t1 u1 f1 r1a, Map t2 u2 f2 r2a => fn_eq f1 f2 && regexp_eq' r1a r2a\n      | _, _ => false\n    end.\n\n  (** A tactic for help in proving the correctness of the equality routines *)\n  Ltac eq_help := \n    match goal with \n      | [ |- _ /\\ _ ] => split ; auto\n      | [ H : context[char_eq ?c ?c0] |- _ ] => \n        destruct (char_eq c c0) ; subst ; auto ; try congruence\n      | [ H : _ && _ = true |- _ ] => generalize (andb_prop _ _ H) ; clear H ; intro H ; \n        destruct H\n      | [ H : _ /\\ _ |- _] => destruct H ; subst\n      | [ H : s2b ?e = true |- _ ] => destruct e ; simpl in H ; subst ; try congruence\n      | _ => auto\n    end.\n\n  (** If [fn_eq] returns true, then we know the functions and their types are equal. *)\n  Lemma fn_eq_corr : forall t1 u1 (f1:fn t1 u1) t2 u2 (f2:fn t2 u2), \n    fn_eq f1 f2 = true -> \n    t1 = t2 /\\ u1 = u2 /\\\n    (existT (fun p => fn (fst p) (snd p)) (t1,u1) f1) = \n    (existT (fun p => fn (fst p) (snd p)) (t2,u2) f2).\n  Proof.\n    induction f1 ; induction f2 ; simpl ; intros; try congruence ; \n      repeat eq_help.\n  Qed.\n  \n  (** If [regexp_eq'] returns true, then we know the regexps and their types are equal. *)\n  Lemma regexp_eq'_corr : forall t1 (r1:regexp t1) t2 (r2:regexp t2), \n    regexp_eq' r1 r2 = true -> \n    t1 = t2 /\\ (existT regexp t1 r1) = (existT regexp t2 r2).\n  Proof.\n    induction r1 ; destruct r2 ; simpl ; intros ; try congruence ; repeat (eq_help ; \n    match goal with \n      | [ IH : forall _ _, regexp_eq' ?r1 _ = true -> _, H : regexp_eq' ?r1 _ = true |- _]=>\n        generalize (IH _ _ H) ; clear IH ; intros ; s\n      | [ H : fn_eq ?f1 ?f2 = true |- _ ] => generalize (fn_eq_corr _ _ H) ; intros ; \n        clear H\n      | _ => auto\n    end).\n    mysimp.\n  Qed.\n\n  (** Now we can use this routine when we try to optimize [Alt]. *)\n  Definition regexp_eq t (r1 r2:regexp t) : {r1 = r2} + {True} := \n    match regexp_eq' r1 r2 as x return (regexp_eq' r1 r2 = x) -> {r1 = r2} + {True} with\n      | true => fun H => left _ (inj_pairT2 _ _ _ _ _ (proj2 (regexp_eq'_corr _ _ H)))\n      | false => fun H => right _ I\n    end (eq_refl _).\n\n  (** ** Environments for function names *)\n\n  (** Function contexts map function names to a dependent pair consisting of\n      - a pair of [result]s [(t1,t2)]\n      - a function of type [result_m t1 -> result_m t2]. *)\n  Definition fn_result_m(p:result*result) := result_m (fst p) -> result_m (snd p).\n  Definition ctxt_t := list (sigT fn_result_m).\n  Definition fn_result'(G:ctxt_t)(n:fn_name) : option (result*result)%type := \n    match nth_error G n with \n      | None => None\n      | Some (existT p _) => Some p\n    end.\n  (** An empty set *)\n  Inductive void : Set := .\n\n  Definition fn_result_m_opt(p:option(result*result)) : Set := \n    match p with | None => void | Some p => fn_result_m p end.\n\n  (** This looks up a function in the environment, given a proof that \n      the function name is in bounds. *)\n  Fixpoint lookup_fn'(n:fn_name) :\n    forall (G:ctxt_t), n < length G -> fn_result_m_opt (fn_result' G n) := \n    match n return forall G, n < length G -> fn_result_m_opt (fn_result' G n) with \n      | 0 => \n        fun G => \n          match G return 0 < length G -> fn_result_m_opt (fn_result' G 0) with \n            | nil => fun H => match lt_n_O _ H with end\n            | (existT p f)::_ => fun H => f\n          end\n      | S m => \n        fun G => \n          match G return (S m) < length G -> fn_result_m_opt (fn_result' G (S m)) with\n            | nil => fun H => match lt_n_O _ H with end\n            | _::G' => fun H => lookup_fn' G' (lt_S_n _ _ H) \n          end\n    end. \n\n  (** In this section, we assume some context and some map for function names. *)\n  Section FNMAP.\n  Variable fn_ctxt : ctxt_t.\n\n  (** Specialize the lookup to the parameters *)\n  Definition fn_result := fn_result' fn_ctxt.\n  Definition lookup_fn(n:fn_name)(H:n < length fn_ctxt) := lookup_fn' fn_ctxt H.\n                \n  (** A function is well-formed if all of the function names have the right\n      types when we look them up in the [fn_ctxt]. *)\n  Definition wf_fn t u (f:fn t u) : Prop := \n    match f in fn u' v' with \n      | Fn_name f t1 t2 => f < length fn_ctxt /\\ fn_result f = Some (t1,t2)\n      | _ => True\n    end.\n  \n  (** A predicate for determining if a [regexp] is type-consistent with\n     the given [fn_ctxt].  Note that by construction, the only things that\n     can be ill-typed are the embedded [fn]s in a [Map]. *)\n  Fixpoint wf_regexp t (r:regexp t) : Prop := \n    match r in regexp t' with\n      | Any => True\n      | Char _ => True\n      | Eps => True\n      | Cat _ _ r1 r2 => wf_regexp r1 /\\ wf_regexp r2\n      | Alt _ r1 r2 => wf_regexp r1 /\\ wf_regexp r2\n      | Zero _ => True\n      | Star _ r => wf_regexp r\n      | Map _ _ f r => wf_regexp r /\\ wf_fn f\n    end.\n  \n  (** Convert a well-formed [fn] to an actual function, using the [fn_map]. *)\n  Definition apply_fn t1 t2 (f:fn t1 t2) : wf_fn f -> result_m t1 -> result_m t2.\n    refine (fun t1 t2 (f:fn t1 t2) => \n      match f in fn t1' t2' return wf_fn f -> result_m t1' -> result_m t2' with\n        | Fn_name f t1 t2 => fun H => _\n        | Fn_const_char c => fun _ => fun _ => c\n        | Fn_empty_list t => fun _ => fun _ => nil\n        | Fn_cons t => fun _ => fun p => (fst p)::(snd p)\n        | Fn_unit_left t => fun _ => fun x => (tt,x)\n        | Fn_unit_right t => fun _ => fun x => (x,tt)\n        | Fn_unit t => fun _ => fun x => tt\n      end) ; simpl in * ; destruct H ; unfold fn_result in * ; \n    generalize (@lookup_fn f0 H). rewrite H0. auto.\n  Defined.\n\n  (** ** Denotational Semantics for [regexp] *)  \n  (** Now we can give a semantic interpretation to the regexps under a given context. *)\n  Inductive in_regexp : forall t, regexp t -> list char_p -> (result_m t) -> Prop := \n  | Any_i : forall c cs v, cs = c::nil -> v = c -> in_regexp Any cs v\n  | Char_i : forall c cs v, cs = c::nil -> v = c -> in_regexp (Char c) cs v\n  | Eps_i : forall cs v, cs = nil -> v = tt -> in_regexp Eps cs v\n  | Alt_left_i : forall t (r1 r2:regexp t) cs (v:result_m t), \n    in_regexp r1 cs v -> in_regexp (Alt r1 r2) cs v\n  | Alt_right_i : forall t (r1 r2:regexp t) cs (v:result_m t), \n    in_regexp r2 cs v -> in_regexp (Alt r1 r2) cs v\n  | Cat_i : forall t1 t2 (r1:regexp t1) (r2:regexp t2) cs v cs1 cs2 v1 v2, \n    in_regexp r1 cs1 v1 -> in_regexp r2 cs2 v2 -> \n    cs = cs1 ++ cs2 -> v = (v1,v2) -> \n    in_regexp (Cat r1 r2) cs v\n  | Star_eps_i : forall t (r:regexp t) cs v, \n    cs = nil -> v = nil -> in_regexp (Star r) cs v\n  | Star_cat_i : forall t (r:regexp t) cs1 cs2 v1 v2 cs v,\n    in_regexp (Star r) cs2 v2 -> \n    cs = cs1 ++ cs2 -> v = (v1::v2) -> \n    cs1 <> nil -> in_regexp r cs1 v1 -> \n    in_regexp (Star r) (cs1++cs2) (v1::v2)\n  | Map_i : forall t1 t2 (f:fn t1 t2) (r:regexp t1) cs v1 v2 (H:wf_fn f), \n    in_regexp r cs v1 -> apply_fn f H v1 = v2 -> in_regexp (Map f r) cs v2.\n  Hint Resolve Any_i Char_i Eps_i Alt_left_i Alt_right_i Cat_i Star_eps_i Star_cat_i Map_i : dfa.\n  \n  Notation \"[[ r ]]\" := (in_regexp r) (at level 0).\n  \n  (** Equivalence of regular expression parsers. *)  \n  Definition reg_eq t (r1 r2: regexp t) : Prop := forall cs v, [[r1]] cs v <-> [[r2]] cs v.\n  Infix \"[=]\" := reg_eq (right associativity, at level 85).\n\n  (** Reflexivity *)  \n  Lemma reg_eq_refl : forall t (r:regexp t), r [=] r.\n    unfold reg_eq ; tauto.\n  Qed.\n  Hint Resolve reg_eq_refl : dfa.\n\n  (** Transitivity *)\n  Lemma reg_eq_trans : forall t (r1 r2 r3: regexp t), r1 [=] r2 -> r2 [=] r3 -> r1 [=] r3.\n    unfold reg_eq ; mysimp ; generalize (H cs v) (H0 cs v) ; firstorder.\n  Qed.\n\n  (** Symmetry *)  \n  Lemma reg_eq_sym : forall t (r1 r2: regexp t), r1 [=] r2 -> r2 [=] r1.\n    unfold reg_eq ; mysimp ;  generalize (H cs v) ; firstorder.\n  Qed.\n\n  (** We define some explicit inversion principles for the [regexp] constructors\n      so that we can invert them even when the arguments aren't variables.  If\n      we tried to use inversion otherwise, then Coq will choke because of the\n      dependencies. *)\n\n  (** An inversion principle for [Eps]. *)\n  Lemma EpsInv : forall cs v, in_regexp Eps cs v -> cs = nil /\\ v = tt.\n    intros cs v H; inversion H ; mysimp.\n  Qed.\n\n  (** Inversion principle for [Any]. *)\n  Lemma AnyInv : forall cs v, [[Any]] cs v -> cs = v::nil.\n    intros cs v H. inversion H ; s.\n  Qed.\n\n  (** Inversion principle for [Char c]. *)\n  Lemma CharInv : forall c cs v, [[Char c]] cs v -> cs = c::nil /\\ v = c.\n    intros c cs v H ; inversion H ; s.\n  Qed.\n\n  (** Inversion principle for [Cat r1 r2].*)\n  Lemma CatInv : forall t1 t2 (r1:regexp t1) (r2:regexp t2) cs v, [[Cat r1 r2]] cs v -> \n    exists cs1, exists cs2, exists v1, exists v2, \n    [[r1]] cs1 v1 /\\ [[r2]] cs2 v2 /\\ cs = cs1 ++ cs2 /\\ v = (v1,v2).\n  Proof.\n    intros t1 t2 r1 r2 cs v H ; inversion H ; mysimp. repeat econstructor ; eauto.\n  Qed.\n\n  (** Inversion principle for [Alt r1 r2]. *)\n  Lemma AltInv : forall t (r1 r2:regexp t) cs v, [[Alt r1 r2]] cs v -> \n    ([[r1]] cs v \\/ [[r2]] cs v).\n    intros t r1 r2 cs v H ; inversion H ; s.\n  Qed.\n\n  (** Inversion principle for [Star r]. *)\n  Lemma StarInv : forall t (r:regexp t) cs v, [[Star r]] cs v -> \n    (cs = nil /\\ v = nil) \\/ \n    (exists cs1, exists v1, exists cs2, exists v2, \n      cs1 <> nil /\\ [[r]] cs1 v1 /\\ [[Star r]] cs2 v2 /\\ cs = cs1 ++ cs2 /\\ v = v1::v2).\n  Proof.\n    intros t r cs v H ; inversion H ; mysimp ; right.\n    exists cs1 ; econstructor ; exists cs2 ; econstructor ; eauto.\n  Qed.\n\n  (** Inversion principle for [Map f r]. *)\n  Lemma MapInv : forall t1 t2 (f:fn t1 t2) (r:regexp t1) cs v, [[Map f r]] cs v -> \n    exists H:wf_fn f, \n      exists v1, in_regexp r cs v1 /\\ apply_fn f H v1 = v.\n    intros t1 t2 f r cs v H; inversion H ; mysimp. repeat econstructor ; eauto. \n  Qed.\n\n  (** Inversion principle for [Zero]. *)\n  Lemma ZeroInv : forall t cs v, [[Zero t]] cs v -> False.\n    intros t cs v H; inversion H.\n  Qed.\n\n  (** A little tactic that takes care of inversion for the [in_regexp] relation. *)\n  Ltac in_inv := \n    (repeat match goal with \n      | [ H : [[Eps]] _ _ |- _ ] => generalize (EpsInv H) ; clear H\n      | [ H : [[Any]] _ _ |- _ ] => generalize (AnyInv H) ; clear H\n      | [ H : [[Char _]] _ _ |- _] => generalize (CharInv H) ; clear H\n      | [ H : [[Cat _ _]] _ _ |- _] => generalize (CatInv H) ; clear H\n      | [ H : [[Alt _ _]] _ _ |- _] => generalize (AltInv H) ; clear H\n      | [ H : [[Zero _]] _ _ |- _] => contradiction (ZeroInv H)\n      (* Note: we don't invert Star as this would loop in a repeat. *)\n      (*| [ H : [[Star _]] _ _ |- _] => generalize (StarInv H) ; clear H*)\n      | [ H : [[Map _ _]] _ _ |- _] => generalize (MapInv H) ; clear H\n      | [ H : wf_fn ?f |- [[Map ?f ?r]] ?cs ?v2 ] => eapply (@Map_i _ _ f r cs _ v2 H)\n      | [ H1 : ?f < length _, H2 : fn_result ?f = Some _ |- [[Map (Fn_name ?f ?t1 ?t2) ?r]] ?cs ?v] =>\n        eapply (@Map_i t1 t2 (Fn_name f t1 t2) r cs _ v (conj H1 H2))\n      | [ |- [[Map ?f ?r]] ?cs ?v2 ] => eapply (@Map_i _ _ f r cs _ v2 I)\n      | _ => mysimp ; subst\n    end) ; eauto with dfa.\n\n  (** [Cat r Eps] is equivalent to [r] *)\n  Lemma cat_eps_r : forall t (r:regexp t), (Cat r Eps) [=] (Map (Fn_unit_right t) r).\n  Proof.\n    unfold reg_eq ; in_inv. rewrite (app_nil_end cs). eauto with dfa.\n  Qed.\n\n  (** [Cat Eps r] is equivalent to [r] *)\n  Lemma cat_eps_l : forall t (r:regexp t), (Cat Eps r) [=] (Map (Fn_unit_left t) r).\n    unfold reg_eq ; in_inv. \n  Qed.\n  \n  (** [Cat r Zero] is equivalent to [Zero] *)\n  Lemma cat_zero_r : forall t1 t2 (r:regexp t1), (Cat r (Zero t2)) [=] Zero _.\n    unfold reg_eq ; in_inv. \n  Qed.\n\n  (** [Cat Zero r] is equivalent to [Zero] *)\n  Lemma cat_zero_l : forall t1 t2 (r:regexp t2), (Cat (Zero t1) r) [=] Zero _.\n    unfold reg_eq ; in_inv. \n  Qed.\n\n  (** In the simple matcher code, we could fuse OptCat and OptCat_r into\n      a single definition.  Here, we broke it out to make the dependency\n      a little simpler to reason about. *)\n\n  (** Used in an optimizing constructor for [Cat]. *)\n  Definition OptCat_r t1 t2 (r2:regexp t2) (r1:regexp t1) := \n    match r2 in regexp t2' return regexp (pair_t t1 t2') with\n      | Zero _ => Zero _\n      | Eps => Map (Fn_unit_right t1) r1\n      | r2 => Cat r1 r2\n    end.\n\n  (** An optimized constructor for [Cat]. *)\n  Definition OptCat t1 t2 (r1:regexp t1) (r2:regexp t2) := \n    match r1 in regexp t1' return regexp (pair_t t1' t2) with\n      | Zero _ => Zero _\n      | Eps => Map (Fn_unit_left t2) r2\n      | r1 => OptCat_r r2 r1\n    end.\n\n  (** [OptCat r1 r2] is equivalent to [Cat r1 r2] *)\n  Lemma opt_cat_r : forall t1 t2 (r1:regexp t1) (r2:regexp t2), \n    OptCat_r r2 r1 [=] Cat r1 r2.\n  Proof.\n    destruct r2 ; simpl ; apply reg_eq_sym ; \n      (apply reg_eq_refl || apply cat_eps_r || apply cat_zero_r).\n  Qed.\n  \n  Lemma opt_cat : forall t1 t2 (r1:regexp t1) (r2:regexp t2), \n    OptCat r1 r2 [=] Cat r1 r2.\n    destruct r1 ; intros ; simpl ; try (apply reg_eq_refl || apply opt_cat_r) ; \n      apply reg_eq_sym ; (apply cat_eps_l || apply cat_zero_l).\n  Qed.\n\n  (** [Alt r Zero] is equivalent to [r]. *)\n  Lemma alt_zero_r : forall t (r:regexp t), (Alt r (Zero _)) [=] r.\n    unfold reg_eq ; in_inv. \n  Qed.\n\n  (** [Alt Zero r] is equivalent to [r]. *)\n  Lemma alt_zero_l : forall t (r:regexp t), (Alt (Zero _) r) [=] r.\n    unfold reg_eq ; in_inv. \n  Qed.\n\n  (** Used in an optimizing version of [Alt]. *)\n  Definition OptAlt_r t (r2:regexp t) : regexp t -> regexp t := \n    match r2 in regexp t' return regexp t' -> regexp t' with\n      | Zero _ => fun r => r\n      | r => fun r1 => if regexp_eq r r1 then r else Alt r1 r\n    end.\n\n  (** Optimized version of [Alt]. *)\n  Definition OptAlt t (r1:regexp t) : regexp t -> regexp t := \n    match r1 in regexp t' return regexp t' -> regexp t' with\n      | Zero _ => fun r => r\n      | r => fun r2 => OptAlt_r r2 r\n    end.\n\n  (** [Alt r r] is equivalent to [r] *)\n  Lemma alt_refl t (r:regexp t) : Alt r r [=] r.\n  Proof.\n    unfold reg_eq ; in_inv.\n  Qed.\n\n  (** [OptAlt r1 r2] is equivalent to [Alt r1 r2] *)\n  Lemma opt_alt_r t (r1 r2:regexp t) : OptAlt_r r2 r1 [=] Alt r1 r2.\n    destruct r2 ; simpl ; repeat \n    match goal with \n      | [ |- context[regexp_eq ?r1 ?r2] ] => destruct (regexp_eq r1 r2) ; subst\n      | [ |- ?r [=] Alt ?r ?r ] => apply reg_eq_sym ; apply alt_refl\n      | [ |- ?r [=] ?r ] => apply reg_eq_refl\n      | [ |- ?r [=] Alt ?r (Zero _) ] => apply reg_eq_sym ; apply alt_zero_r\n      | _ => idtac\n    end.\n  Qed.\n\n  Lemma opt_alt : forall t1 (r1 r2: regexp t1), OptAlt r1 r2 [=] Alt r1 r2.\n    destruct r1 ; simpl ; intros ; try (apply opt_alt_r) ; apply reg_eq_sym ;\n      apply alt_zero_l.\n  Qed.\n\n  (** Optimizing version of [Map]. *)\n\n  (* This is currently only used in the DFA construction as it's\n     recursively pushing the maps in.  The goal is to ignore the\n     semantic actions and always return unit if we ever return a\n     value. *)\n  Fixpoint MapUnit t (r:regexp t) : regexp unit_t := \n    match r with \n      | Any => Map (Fn_unit _) Any\n      | Char b => Map (Fn_unit _) (Char b)\n      | Eps => Eps\n      | Cat t1 t2 p1 p2 => \n        match OptCat (MapUnit p1) (MapUnit p2) with \n          | Map _ _ _ r => Map (Fn_unit _) r\n          | r => Map (Fn_unit _) r\n        end\n      | Zero t => Zero unit_t\n      | Alt t p1 p2 => OptAlt (MapUnit p1) (MapUnit p2)\n      | Star t p1 => Map (Fn_unit _) (Star (MapUnit p1))\n      | Map t1 t2 f p => MapUnit p\n    end.\n\n  (* This isn't currently used... *)\n  Definition OptMap' (t u:result) (f: fn t u) : regexp t -> regexp u := \n    match f in fn t' u' return regexp t' -> regexp u' with \n      | Fn_unit t' => @MapUnit t'\n      | f1 => fun r => Map f1 r\n    end.\n\n  Definition OptMap (t u: result) (f: fn t u) (r1: regexp t) : regexp u :=\n    match r1 in regexp t' return fn t' u -> regexp u with\n      | Zero _ => fun _ => Zero _\n      | r1 => fun f => Map f r1\n    end f.\n\n  (** [OptMap f r] is equivalent to [Map f r]. *)\n  (** Used for induction over proofs of [(cs,v)] in [Star r]. *)\n  Fixpoint in_unwind t (r:regexp t) n cs (v:result_m (list_t t)) : Prop := \n    match n with \n      | 0 => cs = nil /\\ v = nil\n      | S m => \n        exists cs1, exists cs2, \n          exists v1, exists v2, \n            cs = cs1 ++ cs2 /\\ v = (v1::v2) /\\ \n            cs1 <> nil /\\ \n            in_regexp r cs1 v1 /\\ in_unwind r m cs2 v2\n    end.\n\n  Definition coerce_reg t1 t2 (r:regexp t1) : t1 = t2 -> regexp t2.\n    intros. rewrite H in r. apply r.\n  Defined.\n\n  Definition coerce_val t1 t2 (v:result_m t1) : t1 = t2 -> result_m t2.\n    intros. rewrite H in v. apply v.\n  Defined.\n\n  (** If [(cs,v)] is in [Star r] then there exists some [n] such that\n      [(cs,v)] is in the nth unwinding of [r].  \n      This gives us an easy inner induction. *)\n  Lemma star_rep : forall t (r:regexp t) cs (v:result_m t), \n    in_regexp r cs v -> \n    forall t1 (r1 : regexp t1) (H: t = list_t t1), \n      coerce_reg r H = Star r1 -> \n      exists n, in_unwind r1 n cs (coerce_val v H).\n  Proof.\n    unfold coerce_reg, coerce_val; induction 1 ; s ; try discriminate ; repeat\n    match goal with \n      | [ H : list_t _ = list_t _ |- _] => injection H ; intros ; subst ;\n        rewrite (proof_irrelevance H (eq_refl _)) in * ; simpl in *\n      | [ H : Star _ = Star _ |- _ ] => injection H ; mysimp \n      | _ => idtac\n    end ; [ exists 0 ; mysimp | idtac].\n    destruct (IHin_regexp1 t1 r1 (eq_refl _) (eq_refl _)) ; exists (S x) ;\n      repeat econstructor ; mysimp.\n  Qed.\n\n  (** Show that the optimizing constructors preserve well-formedness. *)\n  Lemma wf_cat_opt : forall t1 t2 (r1:regexp t1) (r2:regexp t2), \n    wf_regexp r1 -> wf_regexp r2 -> wf_regexp (OptCat r1 r2).\n  Proof.\n    destruct r1 ; mysimp ; destruct r2 ; mysimp.\n  Qed.\n  Hint Resolve wf_cat_opt : dfa.\n\n  Lemma wf_alt_opt : forall t (r1 r2:regexp t), \n    wf_regexp r1 -> wf_regexp r2 -> wf_regexp (OptAlt r1 r2).\n  Proof.\n    dependent destruction r1 ; mysimp ; dependent destruction r2 ; mysimp ; \n    match goal with \n      | [ |- context[regexp_eq ?r1 ?r2] ] => destruct (regexp_eq r1 r2) ; auto\n    end ;\n    mysimp.\n  Qed.\n  Hint Resolve wf_alt_opt : dfa.\n\n  Lemma wf_map_opt' : forall t u (f: fn t u) (r1: regexp t),\n     wf_regexp r1 -> wf_fn f -> wf_regexp (OptMap' f r1).\n  Proof.\n    destruct f ; mysimp. induction r1 ; mysimp ; auto with dfa. \n    assert (wf_regexp (OptCat (MapUnit r1_1) (MapUnit r1_2))). auto with dfa.\n    generalize H2. generalize (OptCat (MapUnit r1_1) (MapUnit r1_2)).\n    generalize (pair_t unit_t unit_t) as t. destruct r ; mysimp ; auto with dfa.\n  Qed.\n  Hint Resolve wf_map_opt' : dfa.\n\n  Lemma wf_map_opt : forall t u (f: fn t u) (r1: regexp t),\n     wf_regexp r1 -> wf_fn f -> wf_regexp (OptMap f r1).\n  Proof.\n    destruct r1 ; mysimp ; apply wf_map_opt' ; mysimp.\n  Qed.\n  Hint Resolve wf_map_opt : dfa.\n\n  Lemma map_unit1 : forall t (r:regexp t) cs v, \n    [[Map (Fn_unit t) r]] cs v -> wf_regexp r -> [[MapUnit r]] cs v.\n  Proof.\n    induction r ; mysimp. \n    generalize (MapInv H). s. generalize (EpsInv H1). s.\n    generalize (MapInv H). clear H. s.\n    generalize (CatInv H). clear H. s.\n    assert ([[Map (Fn_unit _) (OptCat (MapUnit r1) (MapUnit r2))]] (x1 ++ x2) tt).\n    apply (@Map_i _ _ (Fn_unit _) (OptCat (MapUnit r1) (MapUnit r2)) (x1 ++ x2) (tt,tt) tt I). \n    generalize (opt_cat (MapUnit r1) (MapUnit r2) (x1 ++ x2) (tt, tt)). mysimp. apply H4.\n    eapply Cat_i ; eauto. eapply IHr1 ; in_inv. eapply IHr2 ; in_inv. auto.\n    generalize H3. generalize (OptCat (MapUnit r1) (MapUnit r2)).\n    generalize (pair_t unit_t unit_t) as t. \n    destruct r ; auto. intros. generalize (MapInv H4). s. generalize (MapInv H5). s.\n    apply (Map_i(v1:=x7) (Fn_unit t) I) ; auto.\n    generalize (opt_alt (MapUnit r1) (MapUnit r2) cs v). mysimp. apply H3. clear H2 H3.\n    generalize (MapInv H). s. clear H. generalize (AltInv H2). mysimp.\n    apply Alt_left_i. apply IHr1 ; auto. \n    apply (@Map_i _ _ (Fn_unit _) r1 cs x0 tt I) ; auto.\n    apply Alt_right_i. apply IHr2 ; auto.\n    apply (@Map_i _ _ (Fn_unit _) r2 cs x0 tt I) ; auto.\n    in_inv. generalize (MapInv H). clear H. s.\n    apply (@Map_i _ _ (Fn_unit _) (Star (MapUnit r)) cs (List.map (fun _ => tt) x0) tt I).\n    generalize (@star_rep _ _ _ _ H t r (eq_refl _) (eq_refl _)).\n    mysimp. clear H. generalize cs x0 H1. clear x cs x0 H1. induction x1 ; s. in_inv.\n    eapply Star_cat_i ; eauto. eapply IHr ; in_inv. auto.\n    generalize (MapInv H). s. clear H. generalize (MapInv H2). s. clear H2.\n    eapply IHr. eapply (@Map_i _ _ (Fn_unit _) r cs x2 tt I) ; auto. auto.\n  Qed.\n\n  Lemma map_unit2 : forall t (r:regexp t) cs v,\n    [[MapUnit r]] cs v -> wf_regexp r -> [[Map (Fn_unit t) r]] cs v.\n  Proof.\n    induction r ; mysimp. destruct v. apply (Map_i(v1:=tt) (Fn_unit unit_t) I) ; auto.\n    assert (\n      wf_regexp (OptCat (MapUnit r1) (MapUnit r2)) -> \n      [[Map (Fn_unit _) (OptCat (MapUnit r1) (MapUnit r2))]] cs v).\n    generalize H. generalize (OptCat (MapUnit r1) (MapUnit r2)). \n    generalize (pair_t unit_t unit_t) as t. destruct r ; mysimp.\n    intros. generalize (MapInv H2). s. apply (Map_i(v1:=apply_fn f H4 x0) (Fn_unit _) I).\n    apply (Map_i(v1:=x0) f H4) ; auto. auto. clear H.\n    assert ([[Map (Fn_unit (pair_t unit_t unit_t)) (OptCat (MapUnit r1) (MapUnit r2))]] cs v).\n    apply H2. apply wf_cat_opt. generalize (wf_map_opt' (Fn_unit _) r1). simpl.\n    auto with dfa. generalize (wf_map_opt' (Fn_unit _) r2). simpl. auto with dfa. clear H2.\n    generalize (MapInv H) ; clear H ; s. \n    generalize (proj1 (opt_cat (MapUnit r1) (MapUnit r2) cs x0) H) ; clear H ; mysimp.\n    generalize (CatInv H). clear H ; s. \n    generalize (IHr1 _ _ H H0). clear IHr1 H. generalize (IHr2 _ _ H2 H1). clear IHr2 H2.\n    mysimp. generalize (MapInv H). generalize (MapInv H2). s. clear H H2.\n    apply (Map_i(v1:=(x7,x5)) (Fn_unit (pair_t t1 t2)) I) ; in_inv.\n    generalize (proj1 (opt_alt (MapUnit r1) (MapUnit r2) cs v) H) ; clear H ; mysimp.\n    generalize (AltInv H) ; clear H ; s.\n    generalize (IHr1 _ _ H H0). mysimp. generalize (MapInv H2). s. \n    apply (Map_i(v1:=x0) (Fn_unit t) I). apply Alt_left_i ; auto. auto.\n    generalize (IHr2 _ _ H H1). mysimp. generalize (MapInv H2). s.\n    apply (Map_i(v1:=x0) (Fn_unit t) I). apply Alt_right_i ; auto. auto. in_inv.\n    generalize (MapInv H) ; clear H ; s. \n    generalize (@star_rep _ _ _ _ H unit_t (MapUnit r) (eq_refl _) (eq_refl _)). clear H x.\n    mysimp. assert (exists vs, [[Star r]] cs vs). generalize cs x0 H ; clear cs x0 H. \n    induction x ; s. exists nil. in_inv. generalize (IHr _ _ H3 H0). mysimp.\n    generalize (MapInv H). s. generalize (IHx _ _ H4). s. \n    exists (x5::x3). in_inv. mysimp. apply (Map_i(v1:=x1) (Fn_unit (list_t t)) I) ; auto.\n    generalize (IHr _ _ H H0). s. generalize (MapInv H2) ; s. \n    apply (Map_i(v1:=apply_fn f H1 x0) (Fn_unit u) I) ; auto.\n    apply (Map_i(v1:=x0) f H1) ; auto.\n  Qed.\n\n  Lemma opt_map'1 : forall t u (f:fn t u) (r:regexp t) cs v, \n    [[Map f r]] cs v -> wf_regexp r -> [[OptMap' f r]] cs v.\n  Proof.\n    destruct f ; mysimp. apply map_unit1 ; auto.\n  Qed.\n\n  Lemma opt_map'2 : forall t u (f:fn t u) (r:regexp t) cs v,\n    [[OptMap' f r]] cs v -> wf_regexp r -> [[Map f r]] cs v.\n  Proof.\n    destruct f ; mysimp. apply map_unit2 ; auto.\n  Qed.\n\n  Lemma opt_map1 : forall t u (f:fn t u) (r:regexp t) cs v, \n    [[Map f r]] cs v -> wf_regexp r -> [[OptMap f r]] cs v.\n  Proof.\n     destruct r ; mysimp ; try apply opt_map'1 ; mysimp. in_inv.\n  Qed.\n\n  Lemma opt_map2 : forall t u (f:fn t u) (r:regexp t) cs v,\n    [[OptMap f r]] cs v -> wf_regexp r -> [[Map f r]] cs v.\n  Proof.\n    destruct r ; mysimp ; try apply opt_map'2 ; mysimp. in_inv.\n  Qed.\n\n  Lemma opt_map: forall (t u: result) (f: fn t u) (r1: regexp t), \n    wf_regexp r1 -> OptMap f r1 [=] Map f r1.\n  Proof.\n    intros ; split ; intros ; [ apply opt_map2 | apply opt_map1 ] ; auto.\n  Qed.\n\n (** Now we define what it means for a function to be a valid\n     parser.  A function [f: regexp t -> list char_p -> list (result_m t)], is a\n     valid parser if, when given a [regexp] and a string of characters [s], it\n     returns a list of values [[v1,...,vn]], such that { (s,vi) } is the \n     relation denoted by the regular expression. *)\n  Definition is_parser (f: forall t (r:regexp t), wf_regexp r -> list char_p -> list (result_m t)) : Prop :=\n    forall t (r: regexp t) (H:wf_regexp r) (cs: list char_p) (v:result_m t), \n      ([[r]] cs v -> In v (f t r H cs)) /\\ (In v (f t r H cs) -> [[r]] cs v).\n  (** -----------------------------------------------------*)\n  (** ** Now we define the actual derivative-based parser. *)\n  (** -----------------------------------------------------*)\n\n  (** Returns a regexp denoting { (null,v) | (null,v) in r }. *)\n  Fixpoint null t (r:regexp t) : regexp t := \n    match r in regexp t' return regexp t' with \n      | Any => Zero _\n      | Char _ => Zero _\n      | Eps => Eps\n      | Zero _ => Zero _\n      | Alt t r1 r2 => OptAlt (null r1) (null r2)\n      | Cat t1 t2 r1 r2 => OptCat (null r1) (null r2)\n      | Star t _ => OptMap (Fn_empty_list t) Eps\n      | Map _ _ f r1 => OptMap f (null r1) \n    end.\n\n  Definition OptCatDelayed t1 t2 (r1:regexp t1)(d:char_p -> regexp t2)(c:char_p) : regexp (pair_t t1 t2) :=\n    match r1 in regexp t1' return regexp (pair_t t1' t2) with\n      | Zero _ => Zero _\n      | r1 => OptCat r1 (d c)\n    end.\n\n  Lemma OptCatDelayed_corr t1 t2 (r1:regexp t1) (d:char_p -> regexp t2) c : \n    OptCatDelayed r1 d c = OptCat r1 (d c).\n  Proof.\n    unfold OptCatDelayed, OptCat. auto.\n  Qed.\n  Hint Resolve OptCatDelayed_corr.\n\n  (** This is the heart of the algorithm.  It returns a regexp denoting \n      { (cs,v) | (c::cs,v) in r }.  *)\n  Fixpoint deriv t (r:regexp t) (c:char_p) : regexp t := \n    match r in regexp t' return regexp t' with \n      | Any => OptMap (Fn_const_char c) Eps \n      | Char c' => if char_eq c c' then OptMap (Fn_const_char c) Eps else Zero _\n      | Eps => Zero _\n      | Zero _ => Zero _\n      | Alt t r1 r2 => OptAlt (deriv r1 c) (deriv r2 c)\n      | Cat t1 t2 r1 r2 => OptAlt (OptCat (deriv r1 c) r2) (OptCatDelayed (null r1) (deriv r2) c)\n      | Star t r as r' => OptMap (Fn_cons t) (OptCat (deriv r c) r')\n      | Map _ _ f r1 => OptMap f (deriv r1 c)\n    end.\n\n  (** A specialized derivative for the case where we want to ignore the\n      semantic actions -- note, we probably want to use this instead \n      of [null] above, because of the issue with [Star]. *)\n  Fixpoint accepts_null t (r:regexp t) : bool := \n    match r with \n      | Any => false\n      | Char _ => false\n      | Eps => true\n      | Zero _ => false\n      | Alt t r1 r2 => accepts_null r1 || accepts_null r2\n      | Cat t1 t2 r1 r2 => accepts_null r1 && accepts_null r2\n      | Star t _ => true\n      | Map _ _ f r1 => accepts_null r1\n    end.\n\n  Fixpoint unit_deriv t (r:regexp t) (c:char_p) : regexp unit_t := \n    match r with\n      | Any => Eps\n      | Char c' => if char_eq c c' then Eps else Zero _\n      | Eps => Zero _\n      | Zero _ => Zero _\n      | Alt t r1 r2 => OptAlt (unit_deriv r1 c) (unit_deriv r2 c)\n      | Cat t1 t2 r1 r2 => \n        match unit_deriv r1 c, accepts_null r1 with \n          | Zero _, true => unit_deriv r2 c\n          | Zero _, false => Zero _ \n          | r1', false => MapUnit (OptCat r1' r2)\n          | r1', true => OptAlt (MapUnit (OptCat r1' r2)) (unit_deriv r2 c)\n        end\n      | Star t r as r' => \n        match unit_deriv r c with \n          | Zero _ => Zero _\n          | r1' => MapUnit (OptCat r1' r')\n        end\n      | Map _ _ f r1 => unit_deriv r1 c\n    end.\n\n  Fixpoint unit_derivs (r:regexp unit_t) (cs:list char_p) : regexp unit_t := \n    match cs with \n      | nil => r\n      | c::cs' => unit_derivs (unit_deriv r c) cs'\n    end.\n\n  (** When we are done parsing using a [regexp] r, we are left with a [regexp] denoting \n     { (null,v) | exists s.(s,v) in r }.  This function computes all of the \n     values [v] in this set.  To do so, it needs to be well-formed with respect to the\n     context. *)\n  Definition apply_null t (r:regexp t) : wf_regexp r -> list (result_m t).\n    refine (\n      fix apply_null t (r:regexp t) : wf_regexp r -> list (result_m t) := \n      match r in regexp t' return wf_regexp r -> list (result_m t') with \n        | Any => fun H => nil\n        | Char _ => fun H => nil\n        | Zero _ => fun H => nil\n        | Eps => fun H => tt::nil\n        | Star _ r => fun H => nil::nil\n        | Alt _ r1 r2 => fun H => (apply_null _ r1 _) ++ (apply_null _ r2 _)\n        | Cat _ _ r1 r2 => \n          fun H => \n            let res1 := apply_null _ r1 _ in \n              let res2 := apply_null _ r2 _ in \n                fold_right (fun v1 a => (map (fun v2 => (v1,v2)) res2) ++ a) nil res1\n        | Map _ _ f r1 => fun H => map (apply_fn f _) (apply_null _ r1 _)\n      end\n    ) ; mysimp.\n  Defined.\n\n  Lemma InConcatMap A B (x:A) (y:B) : \n    forall xs, In x xs -> \n      forall ys, In y ys -> \n        In (x,y) (fold_right (fun v a => (map (fun w => (v,w)) ys) ++ a) nil xs).\n  Proof.\n    induction xs ; intro H ; [ contradiction H | destruct H ] ; s ; \n    apply in_or_app ; [ idtac | firstorder ].\n    left ; clear IHxs ; induction ys ; [ contradiction H0 | destruct H0 ; s ].\n  Qed.\n\n  (** Show that if [(nil,v)] is in [r] then [apply_null r] returns [v] as a result *)\n  Lemma ApplyNull1 t (r:regexp t) cs v H :\n    [[r]] cs v -> cs = nil -> In v (apply_null r H).\n  Proof.\n    induction 1 ; s ; try congruence ; repeat \n    match goal with \n      | [ v : prod _ _ |- _] => destruct v\n      | [ H : ?x ++ ?y = nil |- _ ] => generalize (app_eq_nil _ _ H) ; clear H ; mysimp\n      | [ |- In _ (fold_right _ nil _) ] => apply InConcatMap ; auto\n      | [ H : wf_regexp ?r, IH : forall _ : wf_regexp ?r, nil = nil -> _ |- _ ] => \n        let l := fresh \"l\" in \n          generalize (IH H (eq_refl _)) ; \n            generalize (apply_null r H) as l ; induction l ; s ; left\n      | [ |- apply_fn ?f ?H1 _ = apply_fn ?f ?H2 _] => \n        rewrite (proof_irrelevance H1 H2) ; auto\n      | [ H : None = Some _ |- _ ] => congruence\n      | [ |- In _ (_ ++ _) ] => apply in_or_app ; auto\n    end.\n  Qed.\n\n  Lemma InConcatMap1 A B (x:A) (y:B) xs ys : \n    In (x,y) (fold_right (fun v a => (map (fun w => (v,w)) ys) ++ a) nil xs) -> \n    In x xs.\n  Proof.\n    induction xs ; mysimp ; repeat\n    match goal with \n      | [ H : In _ _ |- _ ] => destruct (in_app_or _ _ _ H) ; [left | right ; eauto]\n      | [ H : In (?x, _) (map _ ?ys) |- _ ] => \n        let l := fresh \"l\" in generalize H ; generalize ys as l; \n          induction l ; mysimp ; firstorder ; congruence\n    end.\n  Qed.\n\n  Lemma InConcatMap2 A B (x:A) (y:B) xs ys : \n    In (x,y) (fold_right (fun v a => (map (fun w => (v,w)) ys) ++ a) nil xs) -> \n    In y ys.\n  Proof.\n    induction xs ; mysimp ; firstorder ;\n    match goal with \n      | [ H : In _ (map _ ?ys ++ _) |- _ ] => \n        let H0 := fresh \"H\" in let l := fresh \"l\" in \n          generalize (in_app_or _ _ _ H) ; intro H0 ; destruct H0 ; auto ; \n          generalize H0 ; generalize ys as l ; induction l ; mysimp ; left ; congruence\n    end.\n  Qed.\n\n  (** Show that if [apply_null r] returns [v] as a result, then [(nil,v)] is in [r] *)\n  Lemma ApplyNull2 t (r:regexp t) H v : \n    In v (apply_null r H) -> [[r]] nil v.\n  Proof.\n    induction r ; s ; try contradiction ; auto with dfa ; \n    match goal with \n      | [ v : prod _ _, H1:forall _,_, H2:forall _,_ |- [[ Cat _ _ ]] _ _ ] => \n        destruct v ; econstructor ; \n          [ eapply IHr1 ; eapply InConcatMap1 ; eauto | \n            eapply IHr2 ; eapply InConcatMap2 ; eauto | auto | auto ]\n      | [ IHr1:forall _,_, IHr2:forall _,_, H0 : In _ (_ ++ _) |- [[ Alt _ _ ]] _ _ ] => \n        generalize (in_app_or _ _ _ H0) ; clear H0 ; intro H0 ; destruct H0 ;\n        [ apply Alt_left_i ; eapply IHr1 ; eauto \n        | eapply Alt_right_i ; eapply IHr2 ; eauto ] \n      | [ IHr: forall _, _, \n          H:wf_regexp ?r, H0: In _ (map _ _) |- in_regexp (Map _ _) _ _ ] =>\n        let l := fresh \"l\" in \n          generalize (apply_null r H) (IHr H) H0 ; intro l ; induction l ; \n            clear IHr H0 ; mysimp ; try tauto ; eapply Map_i ; eauto\n    end.\n  Qed.\n\n  (** Show that [null r] is well-formed if [r] is well-formed. *)\n  Lemma wf_null : forall t (r:regexp t), wf_regexp r -> wf_regexp (null r).\n    induction r ; mysimp ; \n      (apply wf_cat_opt || apply wf_alt_opt || apply wf_map_opt) ; auto.\n  Qed.\n  Hint Resolve wf_null : dfa.\n\n  (** Show that [deriv r c] is well-formed if [r] is well-formed. *)\n  Lemma wf_deriv : forall t (r:regexp t) c, wf_regexp r -> wf_regexp (deriv r c).\n  Proof.\n    induction r; mysimp ; \n      repeat (apply wf_cat_opt || apply wf_alt_opt || apply wf_null || apply wf_map_opt) ; \n        simpl ; auto. \n  Qed.\n  Hint Resolve wf_deriv : dfa.\n\n  Fixpoint deriv_parse' t (r:regexp t) (cs:list char_p) : regexp t := \n    match cs with \n      | nil => r\n      | c::cs' => deriv_parse' (deriv r c) cs'\n    end.\n\n  Lemma wf_derivs : forall cs t (r:regexp t), wf_regexp r -> wf_regexp (deriv_parse' r cs).\n    induction cs ; simpl ; intros ; auto. apply IHcs. apply wf_deriv. auto.\n  Qed.\n  Hint Resolve wf_derivs : dfa.\n\n  (** Finally, the derivative-based parser simply runs through the input, calculating\n      derivatives based on the characters it sees, and calls [apply_null] when it gets\n      to the end of the input. *)\n  Definition deriv_parse t (r:regexp t) (H:wf_regexp r) cs : list (result_m t) := \n    apply_null (deriv_parse' r cs) (wf_derivs cs r H).\n\n  (** Tactic for helping to reason about the optimizing constructors. *)\n  Ltac pv_opt := \n    match goal with \n      | [ |- in_regexp (OptAlt ?r1 ?r2) ?cs ?v ] => \n        apply (proj2 (opt_alt r1 r2 cs v))\n      | [ |- in_regexp (OptCat ?r1 ?r2) ?cs ?v ] => \n        apply (proj2 (opt_cat r1 r2 cs v))\n      | [ |- in_regexp (OptMap ?f ?r) ?cs ?v ] => \n        apply (@opt_map1 _ _ f r cs v) ; mysimp\n      | [ H : ?x ++ ?y = nil |- _] => \n        generalize (app_eq_nil _ _ H) ; clear H ; mysimp\n      | [ H : nil = ?x ++ ?y |- _] => \n        generalize (app_eq_nil _ _ (eq_sym H)) ; clear H ; mysimp\n      | [ H : in_regexp (OptCat ?r1 ?r2) ?cs ?v |- _] => \n        generalize (proj1 (opt_cat r1 r2 cs v) H) ; clear H ; intro H\n      | [ H : in_regexp (OptAlt ?r1 ?r2) ?cs ?v |- _] => \n        generalize (proj1 (opt_alt r1 r2 cs v) H) ; clear H ; intro H\n      | [ H : wf_regexp ?r -> [[Map ?f ?r]] ?cs ?v |- _ ] => \n        assert ([[Map f r]] cs v) ; [ auto with dfa | clear H ]\n      | [ H : in_regexp (OptMap ?f ?r) ?cs ?v |- _] => \n        generalize (@opt_map2 _ _ f r cs v H) ; clear H ; mysimp\n      | [ v : prod (result_m _) (result_m _) |- _ ] => destruct v\n      | [ H : (_,_) = (_,_) |- _ ] => injection H ; clear H ; mysimp\n      | [ H1 : wf_fn ?f, H2 : wf_fn ?f |- _] => \n        rewrite (proof_irrelevance H1 H2) in * ; clear H1 ; mysimp\n      | _ => auto with dfa\n    end.\n    \n  (** [apply_null] is correct. *)\n  Lemma Null1 : forall t (r:regexp t) cs v, [[r]] cs v -> cs = nil -> \n    wf_regexp r -> [[null r]] cs v.\n  Proof.\n    induction 1 ; s ; try congruence ; auto with dfa ; repeat pv_opt ; in_inv ; \n      try congruence.\n  Qed.\n\n  Lemma Null2 : forall t (r:regexp t) cs v, \n    [[null r]] cs v -> cs = nil -> wf_regexp r -> [[r]] cs v.\n  Proof.\n    induction r ; simpl ; intros ; pv_opt ; repeat (pv_opt ; in_inv).\n  Qed.\n\n  (** [deriv] is correct part 1. *)\n  Lemma Deriv1 : forall t (r:regexp t) c cs v, \n    [[r]] (c::cs) v -> wf_regexp r -> [[deriv r c]] cs v.\n  Proof.\n    induction r ; simpl ; intros ; \n      match goal with \n        | [ H : in_regexp (Star _) _ _ |- _] => \n          generalize (StarInv H); clear H ; mysimp ; subst\n        | _ => in_inv\n      end ; try congruence ;\n    repeat (pv_opt ; match goal with \n      | [ _ : (?c :: ?cs) = (?x ++ _) |- in_regexp (Alt _ _) ?cs _] => \n        destruct x ; s ; [eapply Alt_right_i | eapply Alt_left_i] ; pv_opt ; pv_opt\n      | [ H : in_regexp ?r1 nil _ |- in_regexp (Cat (null ?r1) _) ?cs _ ] => \n        let H := fresh \"H\" in \n          assert (H:cs=nil++cs) ; [ auto | rewrite H ] ; \n            eapply Cat_i ; eauto with dfa ; apply Null1 ; auto\n      | [ H2 : _::?cs = ?x ++ ?x1 |- _ ] => \n        destruct x ; try congruence ; simpl in H2 ; injection H2 ; s ; in_inv \n      | [ |- context[OptCatDelayed _ _ _] ] => rewrite OptCatDelayed_corr\n      | _ => s ; in_inv ; eauto with dfa\n    end).\n  Qed.\n\n  (** If [null r] matches [cs] returning [v], then [cs] must be empty *)\n  Lemma NullNil : forall t (r:regexp t) cs v, wf_regexp r -> [[null r]] cs v -> cs = nil.\n  Proof.\n    induction r ; mysimp ; repeat \n    match goal with \n      | [ IHr : forall cs v, wf_regexp ?r -> in_regexp (null ?r) _ _ -> _ = _, \n          H1 : wf_regexp ?r, \n          H : in_regexp (null ?r) _ _ |- _] => \n        rewrite (IHr _ _ H1 H) ; clear IHr ; auto with dfa\n      | _ => pv_opt ; in_inv\n    end.\n  Qed.\n    \n  (** [deriv] is correct part 2. *)\n  Lemma Deriv2 : forall t (r:regexp t) c cs v, \n    wf_regexp r -> [[deriv r c]] cs v -> [[r]] (c::cs) v.\n  Proof.\n    induction r ; simpl ; intros ; repeat\n    (match goal with \n       | [ H : context[char_eq ?c1 ?c2] |- _ ] => destruct (char_eq c1 c2) ; s\n       | [ H2: wf_regexp ?r, H : in_regexp (null ?r) _ _ |- \n         in_regexp (Cat _ _) (?c::?x++?x0) _ ] => \n       let H1 := fresh \"H\" in \n         generalize (NullNil _ H2 H) ; s ; \n           assert (H1:c::x0 = nil ++ (c::x0)) ; [auto | rewrite H1] ; \n             eapply Cat_i ; eauto ; try apply Null2 ; eauto\n       | [ |- in_regexp (Star _) (?c :: ?x1 ++ ?x2) _ ] => \n         let H := fresh \"H\" in \n           assert (H:c :: x1 ++ x2 = (c::x1) ++ x2) ; [ auto | rewrite H ] ; \n             eapply Star_cat_i ; eauto ; congruence\n       | [ H : context[OptCatDelayed _ _ _] |- _ ] => rewrite OptCatDelayed_corr in H\n       | _ => repeat pv_opt ; in_inv \n    end).\n  Qed. \n\n  (** First half of correctness for [deriv_parse]. *)\n  Lemma Deriv'1 cs t (r:regexp t) v : \n    wf_regexp r -> [[deriv_parse' r cs]] nil v -> [[r]] cs v.\n  Proof.\n    induction cs ; mysimp ; apply Deriv2 ; auto ; apply IHcs ; auto with dfa.\n  Qed.\n\n  Lemma Deriv'2 cs t (r:regexp t) v : \n    wf_regexp r -> [[r]] cs v -> [[deriv_parse' r cs]] nil v.\n  Proof.\n    induction cs ; mysimp ; apply IHcs ; auto with dfa ; apply Deriv1 ; auto.\n  Qed.\n\n  Lemma DerivParse1 cs t (r:regexp t) H vs : \n    deriv_parse r H cs = vs -> forall v, In v vs -> [[r]] cs v.\n  Proof.\n    unfold deriv_parse. intros. subst. \n    generalize (ApplyNull2 _ _ _ H1). apply Deriv'1 ; auto.\n  Qed.\n\n  (** Second half of correctness for [deriv_parse]. *)\n  Lemma DerivParse2 cs t (r:regexp t) v H : \n    [[r]] cs v -> In v (deriv_parse r H cs).\n  Proof.\n    unfold deriv_parse ; intros ; eapply ApplyNull1 ; auto ; eapply Deriv'2 ; auto.\n  Qed.\n\n  Theorem DerivParse_is_parser : is_parser deriv_parse.\n  Proof.\n    unfold is_parser ; mysimp ; [apply DerivParse2 | eapply DerivParse1] ; eauto.\n  Qed.\n\n  (** * DFA Construction *)\n  Section TABLE.\n    (** In this section, we build a table-driven DFA recognizer for a [regexp].  It's\n        crucial that the regexp has been built using [par2rec] to ensure that all of\n        the semantic actions get mapped to return [tt].  What we return is:\n        - A list of states which are really derivatives of the original regexp.\n          The position of the regexp determins an identity (i.e., index) for the \n          state.  The initial regexp is always at position 0.  \n        - A transition table as a list of list of nats.  If [T(i,j) = k], then \n          this says that in state [i], if we see an input list of characters \n          corresponding to the [token_id] [j], then we can transition to state [k].\n          Obviously, [i] and [k] should be indexes of regular expressions in the\n          list of [states].  Furthermore, it should be that [states(k)] is the\n          derivative of [states(i)] with respect to the token_id [j].\n        - An accept table as a list of booleans.  [accept(i) = true] iff \n          [states(i)] accepts the empty string.\n    *)\n    Record DFA := { \n      dfa_num_states : nat ; \n      dfa_states : list (regexp unit_t) ; \n      dfa_transition : list (list nat) ; \n      dfa_accepts : list bool ;\n      dfa_rejects : list bool\n    }.\n\n    (** Instead of working directly in terms of lists of [char_p]'s, we instead\n        work in terms of [token_id]'s where a [token_id] is just a [nat] in the\n        range 0..[num_tokens]-1.  We assume that each [token_id] can be mapped\n        to a list of [char_p]'s.  For example, in the x86 parser, our characters\n        are bits, but our tokens represent bytes in the range 0..255.  So the\n        [token_id_to_chars] function should extract the n bits correspond to the\n        byte value.  *)\n    Definition token_id := nat.\n    Variable num_tokens : nat.\n    Variable token_id_to_chars : token_id -> list char_p.\n\n    (** Our DFA states correspond to nth derivatives of a starting regexp.  We take\n        the position of a regexp in the [states] list to be its name. *)\n    Definition states := list (regexp unit_t).\n    \n    (** Find the index of a [regexp] in the list of [states]. *)\n    Fixpoint find_index' (r:regexp unit_t) n (s:states) : option nat := \n      match s with \n        | nil => None\n        | h::tl => if regexp_eq r h then Some n else find_index' r (1+n) tl\n      end.\n    Definition find_index (r:regexp unit_t) (s:states) : option nat := find_index' r 0 s.\n\n    (** Find the index of a [regexp] in the list of [states], and if it's not\n        present, add it to the end of the list. *)\n    Definition find_or_add (r:regexp unit_t) (s:states) : (states * nat) := \n      match find_index r s with \n        | None => (s ++ (r::nil), length s)\n        | Some i => (s, i)\n      end.\n\n    (** Generate the transition matrix row for the state corresponding to the\n        regexp [r].  In general, this will add new states. *)\n    Fixpoint gen_row' n (r:regexp unit_t) (s:states) token_id : (states * list nat) := \n      match n with \n        | 0 => (s, nil)\n        | S n' => \n          let (s1, d) := find_or_add (unit_derivs r (token_id_to_chars token_id)) s in\n          let (s2, row) := gen_row' n' r s1 (1 + token_id) in\n            (s2, d::row)\n      end.\n    Definition gen_row (r:regexp unit_t) (s:states) : (states * list nat) := \n      gen_row' num_tokens r s 0.\n\n    (** Build a transition table by closing off the reachable states.  The invariant\n        is that we've closed the table up to the [next_state] and have generated the\n        appropriate transition rows for the states in the range 0..next_state-1.\n        So we first check to see if [next_state] is outside the range of states, and\n        if so, we are done.  Otherwise, we generate the transition row for the\n        derivative at the position [next_state], add it to the list of rows, and\n        then move on to the next position in the list of states.  Note that when \n        we generate the transition row, we may end up adding new states.  \n\n        I believe it's too difficult to show that this process eventually terminates,\n        so we cheat and only run for [n] steps, returning [None] if we run out of\n        steps.  Actually, if the regexp has any occurrences of [Star] that aren't\n        wrapped by a [Map (Fn_unit _)] then this won't terminate in general.  But \n        the [par2rec] translation should take care of this. And of course, for the\n        x86 parser, we never use [Star]. *)        \n    Fixpoint build_table' n (s:states) (rows:list (list nat)) (next_state:nat) : \n      option (states * list (list nat)) := \n      match n with \n        | 0 => None\n        | S n' => \n          match nth_error s next_state with \n            | None => Some (s, rows)\n            | Some r => \n              let (s1, row) := gen_row r s in \n                build_table' n' s1 (rows ++ (row::nil)) (1 + next_state)\n          end\n      end.\n\n    (** We start with the initial [regexp] in state 0 and then try to close off the table. *)\n    Definition build_transition_table n (r:regexp unit_t) := build_table' n (r::nil) nil 0.\n\n    Definition build_accept_table (s:states) : list bool := List.map (@accepts_null unit_t) s.\n\n    Fixpoint always_rejects t (r:regexp t) : bool := \n      match r with \n        | Zero _ => true\n        | Map _ _ _ r => always_rejects r\n        | Alt _ r1 r2 => always_rejects r1 && always_rejects r2\n        | Cat _ _ r1 r2 => always_rejects r1 || always_rejects r2\n        | Eps => false\n        | Star _ _ => false\n        | Any => false\n        | Char _ => false\n      end.\n\n    Definition build_rejects (s:states) := List.map (@always_rejects unit_t) s.\n\n    Definition build_dfa n (r:regexp unit_t) : option DFA := \n      match build_transition_table n r with \n        | None => None\n        | Some (states, table) => \n          Some {| dfa_num_states := length states ; \n                  dfa_states := states ; \n                  dfa_transition := table ;\n                  dfa_accepts := build_accept_table states ; \n                  dfa_rejects := build_rejects states |}\n      end.\n\n    Section DFA_RECOGNIZE.\n      Variable d : DFA.\n      (** This loop is intended to find the shortest match (if any) for\n          a sequence of tokens, given a [DFA].  It returns [(Some (n,\n          ts'))] when there is a match and where [ts'] is the\n          unconsumed input and n is the length of the consumed input.\n          If there is no match, it returns [None].  This is just one\n          example of a recognizer that can be built with the DFA. *)\n\n      Fixpoint dfa_loop state (count: nat) (ts : list token_id) : \n        option (nat * list token_id) := \n        if nth state (dfa_accepts d) false then Some (count, ts)\n        else \n          match ts with \n          | nil => None\n          | t::ts' => let row := nth state (dfa_transition d) nil in \n                      let new_state := nth t row num_tokens in\n                      dfa_loop new_state (S count) ts'\n        end.\n\n      Definition dfa_recognize (ts:list token_id) : option (nat * list token_id) := \n        dfa_loop 0 0 ts.\n    End DFA_RECOGNIZE.\n\n\n    (** In what follows, we try to give some lemmas for reasoning about the\n        DFA constructed from a parser. *)\n    Require Import Omega.\n\n    Lemma nth_error_app : forall A (xs ys:list A), \n      nth_error (xs ++ ys) (length xs) = nth_error ys 0.\n    Proof.\n      induction xs ; mysimp.\n    Qed.\n\n    Lemma find_index'_prop : forall r s2 s1, \n      match find_index' r (length s1) s2 with\n        | Some i => nth_error (s1 ++ s2) i = Some r\n        | _ => True\n      end.\n    Proof.\n      induction s2. mysimp. simpl. intros.\n      destruct (regexp_eq r a). s. rewrite nth_error_app. auto.\n      generalize (IHs2 (s1 ++ (a::nil))).\n      assert (length (s1 ++ a::nil) = S (length s1)). rewrite app_length. simpl. omega.\n      rewrite H. rewrite app_ass. simpl. auto.\n    Qed.\n\n    Lemma nth_error_ext : forall A n (xs ys:list A) (v:A), \n      Some v = nth_error xs n -> nth_error (xs ++ ys) n = Some v.\n    Proof.\n      induction n. destruct xs. simpl. unfold error. intros. congruence. \n      simpl. intros. auto. simpl. destruct xs ; simpl ; unfold error ; intros.\n      congruence. auto.\n    Qed.\n\n    Lemma nth_error_lt : forall A (xs ys:list A) n, \n      n < length xs -> nth_error (xs ++ ys) n = nth_error xs n.\n    Proof.\n      induction xs ; mysimp. assert False. omega. contradiction. \n      destruct n. auto. simpl. apply IHxs. omega.\n    Qed.\n\n    (** A list of states (as regexps) is well-formed if each regexp is well-formed *)\n    Definition wf_states(s:states) := \n      forall i, i < length s -> \n        match nth_error s i with \n          | None => True\n          | Some r => wf_regexp r\n        end.\n\n    (** Calling [find_or_add_prop r s] yields a well-formed state, ensures that\n        if we lookup the returned index, we get [r], and that the state is only\n        extended. *)\n    Lemma find_or_add_prop : forall r s, \n      wf_regexp r -> \n      wf_states s -> \n      match find_or_add r s with \n        | (s',i) => nth_error s' i = Some r /\\ (exists s1, s' = s ++ s1) /\\ wf_states s'\n      end.\n    Proof.\n      unfold find_or_add, find_index. intros. generalize (find_index'_prop r s nil). \n      simpl. intros. destruct (find_index' r 0 s).  mysimp. exists nil. \n      apply app_nil_end. split. rewrite nth_error_app. auto. split.\n      exists (r::nil). auto. unfold wf_states in *. rewrite app_length. simpl. intros.\n      assert (i < length s \\/ i = length s).  omega. destruct H3.\n      rewrite (nth_error_lt _ _ H3). apply H0 ; auto. subst. rewrite nth_error_app.\n      simpl. auto.\n    Qed.\n\n    (** [MapUnit r] is always well-formed. *)\n    Lemma wf_map_unit t (r:regexp t) : wf_regexp (MapUnit r).\n    Proof.\n      induction r ; mysimp. assert (wf_regexp (OptCat (MapUnit r1) (MapUnit r2))).\n      apply wf_cat_opt ; auto. destruct (OptCat (MapUnit r1) (MapUnit r2)) ; mysimp.\n      apply wf_alt_opt ; auto.\n    Qed.\n    Hint Resolve wf_map_unit : dfa.\n\n    (** [unit_deriv r c] is always well-formed. *)\n    Lemma wf_unit_deriv c t (r:regexp t) : wf_regexp (unit_deriv r c).\n    Proof.\n      Ltac wf_ud := \n        match goal with \n          | [ |- wf_regexp (MapUnit _) ] => apply wf_map_unit\n          | [ |- wf_regexp (OptAlt _ _)] => apply wf_alt_opt\n          | [ |- wf_regexp (OptCat _ _) ] => apply wf_cat_opt\n          | [ |- _ /\\ _ ] => split\n          | _ => auto\n        end.\n      induction r ; simpl ; auto. destruct (char_eq c c0) ; simpl ; auto.\n      generalize IHr1. generalize (unit_deriv r1 c). dependent destruction r ; \n      destruct (accepts_null r1) ; intros ; repeat wf_ud. repeat wf_ud.\n      generalize IHr. generalize (unit_deriv r c). dependent destruction r0 ; \n      intros ; simpl ; repeat wf_ud ; simpl in *.\n      assert (wf_regexp (OptCat (OptAlt (MapUnit r0_1) (MapUnit r0_2))\n        (Map (Fn_unit (list_t unit_t)) (Star (MapUnit r))))).\n      repeat wf_ud. simpl. repeat wf_ud.\n      generalize H. clear H.\n      generalize (OptCat (OptAlt (MapUnit r0_1) (MapUnit r0_2))\n        (Map (Fn_unit (list_t unit_t)) (Star (MapUnit r)))).\n      dependent destruction r0 ; simpl ; wf_ud. mysimp.\n      assert (wf_regexp (OptCat (MapUnit r0) (Map (Fn_unit (list_t unit_t)) \n        (Star (MapUnit r))))).\n      repeat (simpl ; wf_ud). generalize H ; clear H.\n      generalize ((OptCat (MapUnit r0) \n        (Map (Fn_unit (list_t unit_t)) (Star (MapUnit r))))).\n      dependent destruction r1 ; mysimp.\n    Qed.\n  \n    (** [unit_derivs r cs] is always well-formed. *)\n    Lemma wf_unit_derivs : forall cs r, \n      wf_regexp r -> wf_regexp (unit_derivs r cs).\n    Proof.\n      induction cs. auto. simpl. intros. apply IHcs. apply wf_unit_deriv. \n    Qed.\n\n    (** This is the main loop-invariant for [gen_row'].  Given a well-formed\n        regexp [r], a well-formed list of states [s], and a token number [n], \n        running [gen_row' n r s (num_tokens - n)] yields a list of states [s2]\n        and transition-table [row2] such that [s2] is well-formed, the\n        length of [row2] is [n], [s2] is an extension of [s], and for all\n        [m], the [mth] element of [s2] is the [unit_derivs] of [r] with \n        respect to the token [m+num_tokens-n]. *)\n    Lemma gen_row'_prop n r s : \n      wf_regexp r -> \n      wf_states s -> \n      n <= num_tokens -> \n      match gen_row' n r s (num_tokens - n) with \n        | (s2, row2) => \n          wf_states s2 /\\ \n          length row2 = n /\\ \n          (exists s1, s2 = s ++ s1) /\\ \n          forall m, \n            m < n -> \n            match nth_error s2 (nth m row2 num_tokens) with \n              | Some r' => r' = unit_derivs r (token_id_to_chars (m + num_tokens - n)) \n              | None => False\n            end\n      end.\n    Proof.\n      induction n. mysimp. exists nil. apply app_nil_end. intros. assert False. omega.\n      contradiction. simpl. intros.\n      remember (find_or_add (unit_derivs r (token_id_to_chars (num_tokens - S n))) s).\n      destruct p. remember (gen_row' n r s0 (S (num_tokens - S n))). destruct p.\n      assert (wf_regexp (unit_derivs r (token_id_to_chars (num_tokens - S n)))).\n      apply wf_unit_derivs ; auto.\n      generalize (find_or_add_prop \n        (unit_derivs r (token_id_to_chars (num_tokens - S n))) H2 H0).\n      rewrite <- Heqp.\n      assert (n <= num_tokens). omega. intros. destruct H4. destruct H5.\n      generalize (IHn _ s0 H H6 H3). clear IHn.\n      assert (S (num_tokens - S n) = num_tokens - n). omega. rewrite <- H7.\n      rewrite <- Heqp0. mysimp. subst. rewrite app_ass. exists (x0 ++ x). auto.\n      destruct m. intros. simpl. subst. \n      rewrite (nth_error_ext n0 (s ++ x0) x (eq_sym H4)). auto.\n      intros. assert (m < n). omega. generalize (H11 _ H13).\n      assert (S m + num_tokens - S n = m + num_tokens - n). omega.\n      rewrite H14. auto.\n   Qed.\n\n   (** This is the main invariant for the [build_table] routine.  Given a well-formed\n       list of states [s] and a list of transition-table rows [ros], then for \n       all [i < n], [s(i)] and [r(i)] are defined, and the row [r(i)] is well-formed\n       with respect to the state [s(i)]. *)\n   Definition build_table_inv s rows n := \n     wf_states s /\\ \n     forall i, i < n -> \n       match nth_error s i, nth_error rows i with \n         | Some r, Some row => \n           length row = num_tokens /\\ \n           forall t, t < num_tokens -> \n             match nth_error s (nth t row num_tokens) with \n               | Some r' => r' = unit_derivs r (token_id_to_chars t)\n               | None => False\n             end\n         | _, _ => False\n       end.\n\n   Lemma nth_error_some : forall A (xs:list A) n (v:A), \n     Some v = nth_error xs n -> n < length xs.\n   Proof.\n     induction xs ; destruct n ; simpl in * ; unfold error, value in * ; mysimp ; \n     try congruence. omega. generalize (IHxs n v H). intros. omega.\n   Qed.\n\n   Lemma build_table_inv_imp s rows n : \n     build_table_inv s rows n -> n <= length s /\\ n <= length rows.\n   Proof.\n     unfold build_table_inv ; destruct n. intros. auto with arith.\n     intros. assert (n < S n). auto with arith. destruct H as [_ H]. generalize (H n H0).\n     remember (nth_error s n) as e1. remember (nth_error rows n) as e2.\n     destruct e1; destruct e2 ; try tauto. intros. generalize (nth_error_some _ _ Heqe1).\n     generalize (nth_error_some _ _ Heqe2). intros. omega.\n   Qed.\n\n   Lemma nth_error_none A (xs:list A) n : None = nth_error xs n -> length xs <= n.\n   Proof.\n     induction xs ; destruct n ; simpl in * ; unfold error, value in * ; mysimp ; \n       auto with arith. congruence.\n   Qed.\n\n   (** This lemma establishes that the [build_table'] loop maintains the\n       [build_table_inv] and only adds to the states and rows of the table. *)\n   Lemma build_table'_prop n s rows : \n     build_table_inv s rows (length rows) -> \n     match build_table' n s rows (length rows) with \n       | None => True\n       | Some (s', rows') => \n         length rows' = length s' /\\ \n         build_table_inv s' rows' (length rows') /\\ \n         (exists s1, s' = s ++ s1) /\\ \n         (exists rows1, rows' = rows ++ rows1)\n     end.\n   Proof.\n     induction n. mysimp.\n     intros. generalize (build_table_inv_imp H). mysimp.\n     remember (nth_error s (length rows)). destruct e.\n     Focus 2. mysimp. generalize (nth_error_none _ _ Heqe). intros. omega.\n     exists nil. apply app_nil_end. exists nil. apply app_nil_end.\n     \n     generalize (nth_error_some _ _ Heqe). intros.\n     remember (gen_row r s) as p. destruct p.\n     unfold gen_row in Heqp. assert (num_tokens <= num_tokens) ; auto.\n     unfold build_table_inv in H. destruct H as [Y H]. assert (Z: wf_regexp r). \n     generalize (Y (length rows)). rewrite <- Heqe. auto.\n     generalize (gen_row'_prop r Z Y H3). clear H3. assert (num_tokens - num_tokens = 0).\n     omega. rewrite H3. rewrite <- Heqp. clear H3. mysimp.\n     remember (build_table' n s0 (rows ++ l::nil) (S (length rows))) as popt.\n     destruct popt ; auto. destruct p. \n     generalize (IHn s0 (rows ++ l::nil)). clear IHn.\n     assert (length (rows ++ l::nil) = S (length rows)). rewrite app_length.\n     simpl. omega. rewrite H7. rewrite <- Heqpopt. intros.\n     \n     assert (build_table_inv s0 (rows ++ l ::nil) (S (length rows))).\n     Focus 2. generalize (H8 H9). s ; rewrite app_ass. exists (x ++ x1). auto.\n     simpl. exists (l::x0). auto. clear H8. \n\n     unfold build_table_inv. split. auto. intros. \n     assert (i < length rows \\/ i = length rows).\n     omega. destruct H9. generalize (H i H9). subst. \n     remember (nth_error s i) as e. destruct e ; simpl ; try tauto.\n     remember (nth_error rows i) as e. destruct e ; simpl ; try tauto. intros.\n     rewrite (nth_error_ext i s x Heqe0).\n     rewrite (nth_error_ext i rows (l::nil) Heqe1). \n     intros. destruct H5 as [H10 H5]. split. auto. clear H10. \n     intros.\n     generalize (H5 _ H10). remember (nth_error s (nth t l1 (length l))) as e.\n     destruct e ; simpl ; try tauto.\n     rewrite (nth_error_ext (nth t l1 (length l)) s x Heqe2). auto.\n\n     subst.\n     rewrite (nth_error_ext (length rows) s x Heqe).\n     rewrite (nth_error_app rows (l::nil)). simpl. mysimp.\n     intros. generalize (H6 _ H5). assert (t + length l - length l = t).\n     omega. rewrite H9. auto.\n  Qed.\n\n  (** This predicate captures the notion of a correct [DFA] with respect to\n      an initial regexp [r].  In essence, it says that the lengths of all of\n      the lists is equal to [dfa_num_states d], that [r] is at [dfa_states(0)],\n      each row of the [dfa_transition] table is well-formed, that \n      [accepts(i)] holds iff the corresponding state accepts the empty string,\n      and when [rejects(i)] is true, the corresponding state rejects all strings. *)\n  Definition wf_dfa (r:regexp unit_t) (d:DFA) := \n    let num_states := dfa_num_states d in\n    let states := dfa_states d in \n    let transition := dfa_transition d in \n    let accepts := dfa_accepts d in \n    let rejects := dfa_rejects d in \n    num_states = length states /\\ \n    num_states = length transition /\\ \n    num_states = length accepts /\\ \n    num_states = length rejects /\\ \n    nth_error states 0 = Some r /\\ \n    forall i, i < num_states -> \n      let r' := nth i states (Zero _) in\n      let acc := nth i accepts false in \n      let rej := nth i rejects false in \n      let row := nth i transition nil in \n        wf_regexp r' /\\ \n        length row = num_tokens /\\ \n        (acc = true <-> in_regexp r' nil tt) /\\ \n        (rej = true -> forall s, ~in_regexp r' s tt) /\\ \n        (forall t, t < num_tokens -> \n          nth t row num_tokens < num_states /\\\n          nth (nth t row num_tokens) states (Zero _) = \n          unit_derivs r' (token_id_to_chars t)).\n\n    Lemma nth_error_nth A (xs:list A) n (v dummy:A) : \n      Some v = nth_error xs n -> nth n xs dummy = v.\n    Proof.\n      induction xs ; destruct n ; simpl in * ; unfold error, value in * ; mysimp ; \n        try congruence.\n    Qed.\n\n    (** These next few lemmas establish the correctness of [accepts_null]. *)\n    Lemma accepts_null_corr1' t (r:regexp t) : \n      wf_regexp r ->\n      accepts_null r = true -> \n      exists v, in_regexp r nil v.\n    Proof.\n      induction r ; mysimp ; try congruence. exists tt. constructor. auto. auto.\n      generalize (andb_prop _ _ H0). mysimp. generalize (IHr1 H H2) (IHr2 H1 H3). mysimp.\n      exists (x0,x). econstructor ; eauto. generalize (orb_prop _ _ H0). mysimp.\n      generalize (IHr1 H H2). mysimp. exists x. constructor ; auto.\n      generalize (IHr2 H1 H2). mysimp. exists x. apply Alt_right_i. auto.\n      exists nil. constructor ; auto. generalize (IHr H H0). mysimp.\n      exists (apply_fn f H1 x). econstructor ; auto. auto.\n    Qed.\n\n    Lemma accepts_null_corr1 (r:regexp unit_t) : \n      wf_regexp r -> accepts_null r = true -> in_regexp r nil tt.\n    Proof.\n      intros. generalize (accepts_null_corr1' _ H H0). mysimp. destruct x. auto.\n    Qed.\n\n    Lemma accepts_null_corr2' t (r:regexp t) v : \n      in_regexp r nil v -> \n      wf_regexp r -> \n      accepts_null r = true.\n    Proof.\n      intros t r v H. dependent induction H ; s ; try congruence.\n      generalize (IHin_regexp H0). unfold orb. intros. rewrite H2. auto.\n      unfold orb. rewrite (IHin_regexp H1). destruct (accepts_null r1) ; auto.\n      destruct cs1 ; simpl in * ; try congruence. subst.\n      unfold andb. rewrite IHin_regexp1 ; auto.\n    Qed.\n\n    Lemma accepts_null_corr2 (r:regexp unit_t) : \n      wf_regexp r -> in_regexp r nil tt -> accepts_null r = true.\n    Proof.\n      intros. apply (@accepts_null_corr2' unit_t r tt H0 H).\n    Qed.\n\n    (** [accepts_null] is correct. *)\n    Lemma accepts_null_corr (r:regexp unit_t) : \n      wf_regexp r -> (accepts_null r = true <-> in_regexp r nil tt).\n    Proof.\n      intros. split. apply accepts_null_corr1 ; auto. apply accepts_null_corr2 ; auto.\n    Qed.\n\n    (** [always_rejects] is correct. *)\n    Lemma always_rejects_corr t (r:regexp t) : \n      always_rejects r = true -> forall s v, ~ in_regexp r s v.\n    Proof.\n      induction r ; mysimp ; try congruence.\n      generalize (orb_prop _ _ H). mysimp. generalize (IHr1 H0). intros.\n      intro. generalize (CatInv H2). mysimp. subst. apply (H1 x x1). auto.\n      generalize (IHr2 H0). intros. intro. generalize (CatInv H2).\n      mysimp. s. apply (H1 x0 x2) ; auto.\n      generalize (andb_prop _ _ H). mysimp. intro. generalize (AltInv H2). mysimp.\n      eapply IHr1 ; eauto. eapply IHr2 ; eauto. intro. apply (ZeroInv H0).\n      intro. generalize (MapInv H0). mysimp. eapply IHr ; eauto.\n    Qed.\n\n    (** [build_dfa] is (partially) correct.  Note that we do not show that there's\n        always an [n], hence the partiality. *)\n    Lemma build_dfa_wf (r:regexp unit_t) (d:DFA) :\n      wf_regexp r -> forall n, build_dfa n r = Some d -> wf_dfa r d.\n    Proof.\n      unfold build_dfa, build_transition_table. intros.\n      assert (build_table_inv (r::nil) nil 0). \n      unfold build_table_inv. split. unfold wf_states. simpl. intros.\n      destruct i. simpl. auto. assert False. omega. contradiction.\n      intros i H1. assert False. omega.\n      contradiction. generalize (build_table'_prop n H1). simpl. intros. \n      destruct (build_table' n (r::nil) nil 0) ; try congruence. \n      destruct p as [s' rows']. injection H0. intros. subst. clear H0.\n      unfold wf_dfa. simpl. mysimp. unfold build_accept_table.\n      rewrite map_length. auto. unfold build_rejects. rewrite map_length. auto.\n      rewrite H3. unfold value. auto. intros. rewrite <- H0 in H5. \n      unfold build_table_inv in H2. destruct H2 as [Y H2].\n      generalize (H2 _ H5). clear H2.\n      intros. remember (nth_error s' i) as e. destruct e ; try contradiction.\n      remember (nth_error rows' i) as e. destruct e ; try contradiction. destruct H2.\n      split. assert (i < length s'). omega. generalize (Y i H7). \n      rewrite <- Heqe. intros.  rewrite (nth_error_nth s' i (Zero _) Heqe). auto. split.\n      rewrite (nth_error_nth rows' i nil Heqe0). auto. \n      rewrite (nth_error_nth s' i (Zero _) Heqe).\n      unfold build_accept_table. unfold build_rejects.\n      rewrite (map_nth (@accepts_null _) s' (Zero _)).\n      rewrite (map_nth (@always_rejects _) s' Eps).\n      rewrite (nth_error_nth s' i (Zero _) Heqe).\n      rewrite (nth_error_nth s' i Eps Heqe). split.\n      intros. apply accepts_null_corr ; auto. assert (i < length s'). omega.\n      generalize (Y i H7). rewrite <- Heqe. auto. split.\n      intros. apply always_rejects_corr. auto. intros. subst.\n      rewrite (nth_error_nth x i nil Heqe0). rewrite H2 in *.\n      generalize (H6 _ H7). \n      remember (nth_error (r::x0) (nth t l num_tokens)). destruct e ; try tauto. intros.\n      subst. rewrite (nth_error_nth (r::x0) (nth t l (length l)) (Zero _) Heqe1). \n      split ; auto. generalize Heqe1. clear Heqe1.  \n      generalize (nth t l (length l)) (r::x0). induction n0 ; destruct l0 ; simpl ; \n      unfold error, value ; intros ; try congruence. omega. generalize (IHn0 _ Heqe1).\n      intros. omega.\n   Qed.\n\n  (** ** Building a recognizer which ignores semantic actions. *)\n  Fixpoint par2rec t (p:parser t) : regexp unit_t := \n    match p with\n      | Any_p => Map (Fn_unit _) Any\n      | Char_p b => Map (Fn_unit _) (Char b)\n      | Eps_p => Eps\n      | Cat_p t1 t2 p1 p2 => Map (Fn_unit _) (OptCat (par2rec p1) (par2rec p2))\n      | Zero_p t => Zero unit_t\n      | Alt_p t p1 p2 => OptAlt (par2rec p1) (par2rec p2)\n      | Star_p t p1 => Map (Fn_unit _) (Star (par2rec p1))\n      | Map_p t1 t2 f p => par2rec p\n    end.\n\n  (** Recognizer is well-formed *)\n  Lemma par2rec_wf t (p:parser t) : wf_regexp (par2rec p).\n  Proof.\n    induction p ; mysimp. apply wf_cat_opt ; auto. apply wf_alt_opt ; auto.\n  Qed.\n\n  (** The translation from parsers to regexps which throws away the maps is correct. *)\n  Lemma par2rec_corr1 t (p:parser t) cs v : \n    in_parser p cs v -> in_regexp (par2rec p) cs tt.\n  Proof.\n    induction 1 ; s ; repeat\n    match goal with \n      | [ |- in_regexp (OptAlt ?r1 ?r2) ?cs ?v ] => \n        apply (proj2 (opt_alt r1 r2 cs v))\n      | [ |- in_regexp (OptCat ?r1 ?r2) ?cs ?v ] => \n        apply (proj2 (opt_cat r1 r2 cs v))\n      | [ IH1 : in_regexp (par2rec ?p) ?cs1 _, \n          IH2 : in_regexp (Map (Fn_unit _) (Star (par2rec ?p))) ?cs2 _,\n          H : _ <> nil |- in_regexp (Map _ (Star _)) _ _ ] => \n        generalize (MapInv IH2) ; mysimp ;\n        match goal with \n        | [ H : in_regexp (Star (par2rec _)) _ ?x0 |- _] => \n          apply (@Map_i _ _ (Fn_unit (list_t unit_t)) (Star (par2rec p)) (cs1 ++ cs2) \n            (tt::x0) tt I) ; try eapply Star_cat_i ; eauto ; simpl ; auto \n        end\n      | [ |- in_regexp (Map (Fn_unit ?t1) ?r) ?cs ?v2 ] => \n        eapply (@Map_i _ _ (Fn_unit t1) r cs _ v2 I) \n      | [ H : in_regexp (par2rec ?p) _ _ |- in_regexp (Alt _ (par2rec ?p)) _ _ ] => \n        eapply Alt_right_i ; eauto\n      | _ => in_inv ; econstructor ; eauto \n    end.\n  Qed.    \n\n  Lemma par2rec_corr2 t (p:parser t) cs : \n    in_regexp (par2rec p) cs tt -> exists v, in_parser p cs v.\n  Proof.\n    induction p ; mysimp ; repeat (\n    match goal with \n      | [ H : in_regexp (OptCat ?r1 ?r2) ?cs ?v |- _ ] => \n        generalize (proj1 (opt_cat r1 r2 cs v) H) ; clear H\n      | [ H : in_regexp (OptAlt ?r1 ?r2) ?cs ?v |- _ ] => \n        generalize (proj1 (opt_alt r1 r2 cs v) H) ; clear H\n      | [ H : in_regexp (Map _ _) _ _ |- _ ] => generalize (MapInv H) ; clear H \n      | [ H : in_regexp (Alt _ _) _ _ |- _ ] => generalize (AltInv H) ; clear H \n      | [ H : in_regexp (Cat _ _) _ _ |- _ ] => generalize (CatInv H) ; clear H \n      | [ H : in_regexp (Zero _) _ _ |- _ ] => \n        generalize (ZeroInv H) ; mysimp ; contradiction\n      | [ H : in_regexp (Char _) _ _ |- _ ] => generalize (CharInv H) ; clear H \n      | [ H : in_regexp Any _ _ |- _ ] => generalize (AnyInv H) ; clear H \n      | [ H : in_regexp Eps _ _ |- _ ] => generalize (EpsInv H) ; clear H\n      | [ |- exists _:unit, _ ] => exists tt\n      | [ v : unit |- _ ] => destruct v\n      | [ IHp1 : forall _, in_regexp (par2rec ?p) _ _ -> _, \n          H1 : in_regexp (par2rec ?p) _ _ |- _] => generalize (IHp1 _ H1) ; clear IHp1\n      | _ => eauto\n    end ; s) ; try ((econstructor ; econstructor ; eauto ; fail) || \n                    (econstructor ; eapply Alt_right_pi ; eauto)).\n    generalize (star_rep(r1:=(par2rec p)) H (eq_refl _) (eq_refl _)). clear H.\n    mysimp. generalize cs x0 H. clear cs x0 H. induction x1 ; s.\n    exists nil ; constructor ; auto. destruct x4. generalize (IHp _ H3).\n    generalize (IHx1 _ _ H4). mysimp. econstructor ; eapply Star_cat_pi ; eauto.\n  Qed.\n\n  (** A simple recognizer -- given a parser [p] and string [cs], returns a \n     proof that either either [cs] matches the grammar in [p] (i.e., there is\n     some semantic value that [cs] would parse into) or else there is no \n     match (i.e., there is no value that it can parse into.) *)\n  Definition recognize t (p:parser t) cs : \n    {exists v, in_parser p cs v} + {forall v, ~ in_parser p cs v}.\n    intros.\n    remember (deriv_parse (par2rec p) (par2rec_wf p) cs).\n    destruct l ; [ right ; intros v H | left ; intros].\n    generalize (par2rec_corr1 H). intro. generalize (DerivParse2 (par2rec_wf p) H0).\n    rewrite <- Heql. simpl. auto. destruct r.\n    generalize (DerivParse1 cs (par2rec p) (par2rec_wf p) (eq_sym Heql)). \n    mysimp. assert (in_regexp (par2rec p) cs tt). apply H. left ; auto.\n    apply (par2rec_corr2 _ H0).\n  Defined.\n\n   Definition flat_map A B (f:A->list B) (xs:list A) : list B := \n     fold_right (fun v a => (f v) ++ a) nil xs.\n\n   (** This is a simple function which runs a DFA on an entire string, returning\n       true if the DFA accepts the string, and false otherwise.  In what follows,\n       we prove that [run_dfa] is correct... *)\n   Fixpoint run_dfa (d:DFA) (state:nat) (ts:list token_id) : bool := \n     match ts with \n       | nil => nth state (dfa_accepts d) false\n       | t::ts' => run_dfa d (nth t (nth state (dfa_transition d) nil) num_tokens) ts'\n     end.\n\n   (** A key part of the reasoning is showing that [unit_deriv] is correct.  But\n       this turns out to be complicated because of the type dependencies, as well\n       as the optimizations that we're doing.  So I've broken it up into a number\n       of smaller lemmas. *)\n   Lemma unit_deriv_cat0 : forall c t1 t2 (r1:regexp t1) (r2:regexp t2), \n     wf_regexp r1 -> wf_regexp r2 -> \n     accepts_null r1 = true -> \n     (forall cs, [[unit_deriv r1 c]] cs tt -> (exists v, [[r1]] (c::cs) v)) -> \n     (forall cs, [[unit_deriv r2 c]] cs tt -> (exists v, [[r2]] (c::cs) v)) -> \n     forall cs, [[OptAlt (MapUnit (OptCat (unit_deriv r1 c) r2)) (unit_deriv r2 c)]] cs tt -> \n       exists v, [[Cat r1 r2]] (c::cs) v.\n   Proof.\n     intros. pv_opt. in_inv. assert (wf_regexp (OptCat (unit_deriv r1 c) r2)). \n     apply wf_cat_opt. apply wf_unit_deriv. auto.\n     generalize (map_unit2 _ H4 H5).  mysimp. in_inv. pv_opt. in_inv. destruct x3.\n     generalize (H2 _ H6). mysimp. exists (x0,x4). in_inv.\n     generalize (accepts_null_corr1' _ H H1). mysimp. generalize (H3 _ H4). mysimp. \n     exists (x,x0). eapply Cat_i. eapply H5. eapply H6. auto. auto.\n   Qed.\n   \n   Lemma unit_deriv_cat1 : forall c t1 t2 (r1:regexp t1) (r2:regexp t2), \n     wf_regexp r1 -> wf_regexp r2 -> \n     accepts_null r1 = true -> \n     (forall cs, [[unit_deriv r1 c]] cs tt -> exists v, [[r1]] (c::cs) v) -> \n     (forall cs, [[unit_deriv r2 c]] cs tt -> exists v, [[r2]] (c::cs) v) -> \n     unit_deriv r1 c = Zero _ -> \n     forall cs, [[unit_deriv r2 c]] cs tt -> exists v, [[Cat r1 r2]] (c::cs) v.\n   Proof.\n     intros. generalize (accepts_null_corr1' _ H H1). mysimp.\n     generalize (H3 _ H5). mysimp. exists (x, x0). in_inv.\n   Qed.\n   \n   Lemma unit_deriv_cat2 : forall c t1 t2 (r1:regexp t1) (r2:regexp t2), \n     wf_regexp r1 -> wf_regexp r2 -> \n     accepts_null r1 = false -> \n     (forall cs, [[unit_deriv r1 c]] cs tt -> exists v, [[r1]] (c::cs) v) -> \n     (forall cs, [[unit_deriv r2 c]] cs tt -> exists v, [[r2]] (c::cs) v) -> \n     forall cs, [[MapUnit (OptCat (unit_deriv r1 c) r2)]] cs tt -> \n       exists v, [[Cat r1 r2]] (c::cs) v.\n   Proof.\n     mysimp. assert (wf_regexp (OptCat (unit_deriv r1 c) r2)). apply wf_cat_opt.\n     apply wf_unit_deriv. auto. generalize (map_unit2 _ H4 H5). mysimp. in_inv.\n     pv_opt. in_inv. destruct x3. generalize (H2 _ H6). mysimp.\n     exists (x0,x4). in_inv.\n   Qed.\n   \n   Lemma unit_deriv_cat : forall c t1 t2 (r1:regexp t1) (r2:regexp t2), \n     wf_regexp r1 -> wf_regexp r2 -> \n     (forall cs, [[unit_deriv r1 c]] cs tt -> exists v, [[r1]] (c::cs) v) -> \n     (forall cs, [[unit_deriv r2 c]] cs tt -> exists v, [[r2]] (c::cs) v) -> \n     forall cs, \n       [[match unit_deriv r1 c, accepts_null r1 with \n           | Zero _, true => unit_deriv r2 c\n           | Zero _, false => Zero _\n           | r1', false => MapUnit (OptCat r1' r2)\n           | r1', true => OptAlt (MapUnit (OptCat r1' r2)) (unit_deriv r2 c)\n         end]] cs tt -> \n       exists v, [[Cat r1 r2]] (c::cs) v.\n   Proof.\n     intros c t1 t2 r1. remember (unit_deriv r1 c). generalize Heqr. clear Heqr.\n     remember (accepts_null r1) as b. generalize (eq_sym Heqb). clear Heqb.\n     dependent destruction r ; destruct b ; intros ; (try (in_inv ; fail)) ; \n       rewrite Heqr in * ; \n         try (apply unit_deriv_cat0 ; auto ; fail) ; \n           try (apply unit_deriv_cat2 ; auto ; fail) ; \n             try (apply unit_deriv_cat1 ; auto ; fail).\n   Qed.\n\n   Lemma unit_deriv_star' : forall t (r:regexp t) cs vs,\n     [[Star (MapUnit r)]] cs vs -> wf_regexp r -> exists vs', [[Star r]] cs vs'.\n   Proof.\n     intros t r cs vs H. dependent induction H ; s. exists nil. econstructor ; eauto.\n     generalize (map_unit2 _ H3 H0). intros. in_inv. clear H3.\n     generalize (IHin_regexp1 H0).\n     mysimp. exists (x0::x1). in_inv.\n   Qed.\n\n   Lemma unit_deriv_star0 : forall c t (r:regexp t), \n     wf_regexp r -> \n     (forall cs, [[unit_deriv r c]] cs tt -> exists v, [[r]] (c::cs) v) -> \n     forall cs, \n       [[ MapUnit (OptCat (unit_deriv r c) (Star r)) ]] cs tt -> \n       exists v, [[ Star r ]] (c::cs) v.\n   Proof.\n     intros. assert (wf_regexp (OptCat (unit_deriv r c) (Star r))). \n     apply wf_cat_opt. apply wf_unit_deriv. auto with dfa.\n     generalize (map_unit2 _ H1 H2). clear H1. mysimp. in_inv. pv_opt.\n     in_inv. destruct x3. generalize (H0 _ H1). mysimp. \n     exists (x0::x4). assert (c::x1++x2 = (c::x1) ++ x2). auto. rewrite H6.\n     eapply Star_cat_i ; eauto. congruence.\n   Qed.\n\n   Lemma unit_deriv_star : forall c t (r:regexp t), \n     wf_regexp r -> \n     (forall cs, [[unit_deriv r c]] cs tt -> exists v, [[r]] (c::cs) v) -> \n     forall cs, \n       [[ match unit_deriv r c with \n            | Zero _ => Zero _\n            | r1' => MapUnit (OptCat r1' (Star r))\n          end ]] cs tt -> exists v, [[ Star r ]] (c::cs) v.\n   Proof.\n     intros c t r. remember (unit_deriv r c) as rc. generalize Heqrc. clear Heqrc.\n     dependent destruction rc ; intros ; rewrite Heqrc in * ; try \n     (apply unit_deriv_star0 ; auto). rewrite <- Heqrc in *. in_inv.\n   Qed.\n\n   Lemma StarMapUnit : forall t (r:regexp t) cs vs, \n     [[ Star r ]] cs vs -> \n     wf_regexp r -> \n     [[ Star (MapUnit r) ]] cs (map (fun _ => tt) vs).\n   Proof.\n     intros t r cs vs H. dependent induction H. s. eapply Star_eps_i ; auto. subst.\n     intros.\n     eapply (@Star_cat_i unit_t (MapUnit r) cs1 cs2 tt (map (fun _ => tt) v2) (cs1++cs2));\n       auto. apply map_unit1 ; auto. \n     apply (@Map_i _ _ (Fn_unit _) r cs1 v1 tt I) ; auto.\n   Qed.\n\n   (** So this is a crucial result:  it says that if [unit_deriv r c] returns a \n       regexp that matches [cs] and [tt], then there is some [v] such that \n       [r] matches [c::cs] and [v]. *)\n   Lemma unit_deriv_corr1 t (r:regexp t) c cs : \n     in_regexp (unit_deriv r c) cs tt -> wf_regexp r -> exists v, in_regexp r (c::cs) v.\n   Proof.\n     induction r ; s ; in_inv ; pv_opt. destruct (char_eq c0 c) ; s ; in_inv. \n     apply unit_deriv_cat ; auto.\n     in_inv. generalize (IHr1 _ _ H H0). mysimp. exists x. in_inv.\n     generalize (IHr2 _ _ H H1). mysimp. exists x. in_inv.\n     apply unit_deriv_star ; auto. generalize (IHr _ _ H H0). mysimp.\n     exists (apply_fn f H1 x). econstructor ; eauto.\n   Qed.\n\n   (** This lifts the [unit_deriv_corr1] to strings. *)\n   Lemma unit_derivs_corr1 cs1 (r:regexp unit_t) cs2 : \n     in_regexp (unit_derivs r cs1) cs2 tt -> wf_regexp r -> \n     exists v, in_regexp r (cs1 ++ cs2) v.\n   Proof.\n     induction cs1 ; mysimp. exists tt. auto.  \n     generalize (IHcs1 (unit_deriv r a) cs2 H (wf_unit_deriv a r)). mysimp.\n     destruct x. generalize (unit_deriv_corr1 r a H1 H0). auto.\n   Qed.\n     \n   (** This lemma proves the other half of the correctness of [unit_deriv]:  If\n       [r] matches [c::cs] and [v], then [unit_deriv r c] matchs [cs] and [tt]. \n       This proof needs to be abstracted and cleaned up a lot... *)\n   Lemma unit_deriv_corr2 t (r:regexp t) c cs v : \n     in_regexp r (c::cs) v -> wf_regexp r -> in_regexp (unit_deriv r c) cs tt.\n   Proof.\n     intros t r c cs v H. \n     dependent induction H; s ; auto with dfa; try congruence.\n\n     pv_opt.\n     apply Alt_left_i.\n     eapply IHin_regexp.\n     eauto.\n\n     pv_opt.\n     apply Alt_right_i.\n     eapply IHin_regexp.\n     eauto.\n     admit.\n     admit.\n     \n(*     induction cs1.\n     s.\n     \n     rewrite (accepts_null_corr2' H H2).\n\n     assert (c::cs = c::cs) by reflexivity.\n     generalize (IHin_regexp2 H1 H3).\n     clear IHin_regexp2 IHin_regexp1. intros.\n\n\n\n     generalize (unit_deriv r1 c) as r.\n     dependent destruction r ; pv_opt ; try (apply Alt_right_i ; auto).\n     apply IHcs1.\n     simpl in H1. injection H1. intros. s. clear H1 H4.\n     (* generalize (IHin_regexp1 c0 cs1 (eq_refl _) H3). *)\n     Unset Printing Notations.\n\n     s.\n     \n     clear IHin_regexp1. remember (unit_deriv r1 c0) as r.\n     generalize Heqr ; clear Heqr. destruct (accepts_null r1). \n     dependent destruction r ; s ; in_inv ; pv_opt. \n     apply Alt_left_i. eapply map_unit1 ; auto with dfa.\n     apply (@Map_i _ _ (Fn_unit t2) r2 cs2 v2 tt I H0 (eq_refl _)).\n     apply Alt_left_i. eapply map_unit1 ; auto.\n     apply (@Map_i _ _ (Fn_unit _) (OptCat (Alt r3 r4) r2) (cs1++cs2) (tt,v2) tt I).\n     pv_opt. eapply Cat_i. eapply Alt_left_i. eauto. eauto. auto. auto. auto.\n     apply (wf_cat_opt (Alt r3 r4) r2). rewrite Heqr. apply wf_unit_deriv. auto.\n     apply Alt_left_i. eapply map_unit1 ; auto.\n     apply (@Map_i _ _ (Fn_unit _) (OptCat (Alt r3 r4) r2) (cs1++cs2) (tt,v2) tt I) ; auto.\n     pv_opt. eapply Cat_i. eapply Alt_right_i. eauto. eauto. auto. auto.\n     apply (wf_cat_opt (Alt r3 r4) r2). rewrite Heqr. apply wf_unit_deriv. auto.\n     apply Alt_left_i. eapply map_unit1 ; auto. \n     apply (@Map_i _ _ (Fn_unit _) (OptCat (Map f r) r2) (cs1++cs2) (tt,v2) tt I).\n     pv_opt. eapply Cat_i ; eauto. apply (@Map_i _ _ f r cs1 x0 tt x H1 H2). auto.\n     apply (wf_cat_opt (Map f r) r2). rewrite Heqr. apply wf_unit_deriv. auto.\n     dependent destruction r ; s ; in_inv ; apply map_unit1 ; auto.\n     apply (@Map_i _ _ (Fn_unit _) r2 cs2 v2 tt I H0 (eq_refl _)).\n     apply (@Map_i _ _ (Fn_unit _) (OptCat (Alt r3 r4) r2) (cs1++cs2) (tt,v2) tt I).\n     pv_opt. eapply Cat_i. eapply Alt_left_i ; eauto. eauto. auto. auto. auto.\n     apply (wf_cat_opt (Alt r3 r4) r2). rewrite Heqr. apply wf_unit_deriv. auto.\n     apply (@Map_i _ _ (Fn_unit _) (OptCat (Alt r3 r4) r2) (cs1++cs2) (tt,v2) tt I).\n     pv_opt. eapply Cat_i. eapply Alt_right_i ; eauto. eauto. auto. auto. auto.\n     apply (wf_cat_opt (Alt r3 r4) r2). rewrite Heqr. apply wf_unit_deriv. auto.\n     apply (@Map_i _ _ (Fn_unit _) (OptCat (Map f r) r2) (cs1++cs2) (tt,v2) tt I).\n     pv_opt. eapply Cat_i ; eauto. eapply (@Map_i _ _ f r cs1 x0 tt x H1 H2). auto.\n     apply (wf_cat_opt (Map f r) r2) ; auto. rewrite Heqr. apply wf_unit_deriv.\n     destruct cs1 ; try congruence. simpl in x ; injection x ; s.\n     generalize (IHin_regexp2 c cs1 (eq_refl _) H4). clear IHin_regexp2. \n     clear H0 H1 H2. assert (forall cs, cs2 = c::cs -> [[unit_deriv (Star r) c]] cs tt).\n     intros. apply IHin_regexp1. auto. auto. clear IHin_regexp1. \n     remember (unit_deriv r c) as rb. generalize Heqrb. clear Heqrb.\n     dependent destruction rb ; intros. generalize (EpsInv H1). intros. destruct H2.\n     subst. clear H5. clear H1.\n     generalize (StarMapUnit H H4). intros.\n     apply (@Map_i _ _ (Fn_unit _) (Star (MapUnit r)) cs2 (map (fun _ => tt) v2) tt I) ; \n       auto.\n     assert ([[MapUnit (OptCat (Alt rb1 rb2) (Star r))]] (cs1 ++ cs2) tt) ; auto.\n     eapply map_unit1. eapply (@Map_i _ _ (Fn_unit _) (OptCat (Alt rb1 rb2) (Star r))\n     (cs1 ++ cs2) (tt,v2) tt I) ; auto. pv_opt ; auto. eapply Cat_i ; auto. auto. auto.\n     apply wf_cat_opt. rewrite Heqrb. apply wf_unit_deriv. auto. \n     in_inv.\n     assert ([[MapUnit (Cat (Map f rb) (Star r))]] (cs1++cs2) tt) ; auto.\n     eapply map_unit1. \n     apply (@Map_i _ _ (Fn_unit _) (Cat (Map f rb) (Star r)) (cs1++cs2) (tt,v2) tt I) ; \n       auto.\n     eapply Cat_i ; eauto. rewrite Heqrb. split. apply wf_unit_deriv. auto. *)\n   Qed. (**** TODO *****)\n\n   (** Lifts [unit_deriv_corr2] to strings. *)\n   Lemma unit_derivs_corr2 cs (r:regexp unit_t) : \n     wf_regexp r -> [[r]] cs tt -> [[unit_derivs r cs]] nil tt.\n   Proof.\n     induction cs. auto. simpl. intros. apply IHcs. apply wf_unit_deriv.\n     eapply unit_deriv_corr2. eauto. auto.\n   Qed.\n\n   Definition list_all(A:Type)(P:A->Prop) : list A -> Prop := \n     fold_right (fun x a => P x /\\ a) True.\n\n   Lemma lt_nth_error : forall A (xs:list A) n dummy v, \n     n < length xs -> nth n xs dummy = v -> nth_error xs n = Some v.\n   Proof.\n     induction xs ; destruct n ; mysimp ; try (assert False ; [ omega | contradiction] ); \n       unfold error, value in * ; s. apply (IHxs n dummy). omega. auto.\n   Qed.\n\n   Lemma flat_map_app A B (f:A->list B) (ts1 ts2:list A) : \n     flat_map f (ts1 ++ ts2) = (flat_map f ts1) ++ (flat_map f ts2).\n   Proof.\n     induction ts1 ; mysimp. rewrite app_ass. rewrite IHts1. auto.\n   Qed.\n   \n   Lemma unit_derivs_flat_map r ts1 ts2 : \n     unit_derivs r (flat_map token_id_to_chars (ts1 ++ ts2)) = \n     unit_derivs (unit_derivs r (flat_map token_id_to_chars ts1)) \n     (flat_map token_id_to_chars ts2).\n   Proof.\n     intros. rewrite flat_map_app. generalize (flat_map token_id_to_chars ts1) r\n     (flat_map token_id_to_chars ts2). induction l ; mysimp. \n   Qed.\n\n   (** This lemma tells us that if we start with a parser [p], build a [DFA],\n       and then run the [DFA] on a list of tokens, then we get [true] iff\n       the parser would've accepted the string and produced a value.  *)\n   Lemma dfa_corr' : forall t (p:parser t) n (d:DFA), \n     build_dfa n (par2rec p) = Some d -> \n     forall ts2 ts1 state, \n       nth_error (dfa_states d) state = \n       Some (unit_derivs (par2rec p) (flat_map token_id_to_chars ts1)) -> \n       list_all (fun t => t < num_tokens) ts2 ->\n       if run_dfa d state ts2 then\n         exists v, in_parser p (flat_map token_id_to_chars (ts1 ++ ts2)) v\n       else \n         forall v, ~ in_parser p (flat_map token_id_to_chars (ts1 ++ ts2)) v.\n   Proof.\n     intros t p n d H. assert (wf_dfa (par2rec p) d). eapply build_dfa_wf.\n     eapply par2rec_wf. eauto. unfold wf_dfa in H0. induction ts2 ; mysimp.\n     assert (state < dfa_num_states d). rewrite H0. generalize H1. \n     generalize (unit_derivs (par2rec p) (flat_map token_id_to_chars ts1)).\n     generalize (dfa_states d) state. \n     induction l ; destruct state0 ;  mysimp ; unfold error, value in * ; try congruence. \n     subst. omega. subst. generalize (IHl _ _ H8). intros. omega. \n     generalize (H7 _ H8). mysimp. remember (nth state (dfa_accepts d) false) as e.\n     destruct e. generalize (H11 (eq_refl _)).\n     rewrite (nth_error_nth (dfa_states d) state _ (eq_sym H1)). intros.\n     generalize (unit_derivs_corr1 _ _ H15 (par2rec_wf _)).\n     rewrite <- app_nil_end. mysimp. destruct x. apply (par2rec_corr2 p H16).\n     unfold not. intros. assert (false = true).\n     apply H14. rewrite (nth_error_nth (dfa_states d) state _ (eq_sym H1)).\n     generalize (@par2rec_corr1 t p (flat_map token_id_to_chars ts1) v H15). intro.\n     apply unit_derivs_corr2 ; auto. apply par2rec_wf. congruence.\n     \n     generalize (IHts2 (ts1 ++ a::nil) \n       (nth a (nth state (dfa_transition d) nil) num_tokens)). \n     rewrite app_ass. simpl. intros. apply H9 ; auto. clear H9 IHts2.\n     assert (state < dfa_num_states d). rewrite H0. generalize H1.\n     generalize (unit_derivs (par2rec p) (flat_map token_id_to_chars ts1)).\n     generalize (dfa_states d) state. induction l ; destruct state0 ; mysimp ; \n     unfold error, value in * ; try congruence; try omega. \n     generalize (IHl _ _ H9). intros. omega.\n     generalize (H8 _ H9) ; mysimp. generalize (H14 _ H2). mysimp.\n     rewrite unit_derivs_flat_map. simpl. rewrite <- app_nil_end.\n     generalize (H14 _ H2). mysimp. rewrite H0 in H18.\n     apply (lt_nth_error (dfa_states d) (Zero unit_t) H18). rewrite H19.\n     rewrite (nth_error_nth _ _ (Zero unit_t) (eq_sym H1)). auto.\n  Qed.\n\n  (** Here is the key correctness property for the DFAs. *)\n  Lemma dfa_corr t (p:parser t) n (d:DFA) :\n    build_dfa n (par2rec p) = Some d -> \n    forall ts, \n      list_all (fun t => t < num_tokens) ts -> \n      if run_dfa d 0 ts then \n        exists v, in_parser p (flat_map token_id_to_chars ts) v\n      else \n        forall v, ~ in_parser p (flat_map token_id_to_chars ts) v.\n  Proof.\n    intros. assert (ts = nil ++ ts) ; auto. rewrite H1. eapply dfa_corr' ; eauto.\n    assert (wf_dfa (par2rec p) d). eapply build_dfa_wf. apply par2rec_wf. eauto.\n    unfold wf_dfa in H2. mysimp.\n  Qed.\n\n  Definition accepts_at_most_one_null t (r:regexp t) (H:wf_regexp r) : bool := \n    if le_gt_dec (List.length (apply_null r H)) 1 then true else false.\n\n  Fixpoint enum_tokens (f:token_id -> bool) (n:nat) : bool := \n    match n with \n      | 0 => true\n      | S m => (f m) && enum_tokens f m\n    end.\n\n  Definition forall_tokens (f:token_id -> bool) : bool := enum_tokens f num_tokens.\n\n  Lemma wf_deriv_parse' cs t (r:regexp t) (H:wf_regexp r) : wf_regexp (deriv_parse' r cs).\n  Proof.\n    induction cs ; mysimp. apply IHcs. apply wf_deriv. auto.\n  Qed.\n\n  End TABLE.\n  End FNMAP.\n\n  (** ** Now we need to translate our external representation, [parser] to \n         our internal representation [regexp] and build an appropriate [ctxt]\n         mapping function names to functions of the right type. *)\n\n  (** Add a new function to the end of the context and return its position as \n      a \"fresh\" function name, along with the new context. *)\n  Definition extend_state(s:ctxt_t) t1 t2 (f:fn_result_m(t1,t2)) : (fn_name * ctxt_t) := \n    (length s, s ++ (existT fn_result_m (t1,t2) f)::nil).\n\n  (** Convert a parser with inlined functions to a regexp and a function map. *)\n  Fixpoint par2reg t (p:parser t)(s:ctxt_t) : (regexp t) * ctxt_t := \n    match p in parser t return (regexp t) * ctxt_t with\n      | Any_p => (Any, s)\n      | Char_p b => (Char b, s)\n      | Eps_p => (Eps, s)\n      | Cat_p t1 t2 p1 p2 => \n        let (r1,s1) := par2reg p1 s in \n        let (r2,s2) := par2reg p2 s1 in \n          (Cat r1 r2, s2)\n      | Zero_p t => (Zero t, s)\n      | Alt_p t p1 p2 => \n        let (r1,s1) := par2reg p1 s in \n        let (r2,s2) := par2reg p2 s1 in \n          (Alt r1 r2, s2)\n      | Star_p t p1 => \n        let (r1,s1) := par2reg p1 s in\n          (Star r1, s1)\n      | Map_p t1 t2 f p => \n        let (r,s1) := par2reg p s in \n        let (n,s2) := extend_state s1 f in\n          (@Map t1 t2 (Fn_name n t1 t2) r, s2)\n    end.\n\n  (** Initial state for the translation. *)\n  Definition initial_ctxt : ctxt_t := nil.\n\n  (** Top-level translation of parsers to regexps. *)\n  Definition parser2regexp t (p:parser t) : (regexp t) * ctxt_t := \n    par2reg p initial_ctxt.\n\n  (** ** Now we need to prove that the translation [parser2regexp] preserves\n         meaning. *)\n\n  (** Tactic to propagate information about the translation. *)\n  Ltac unfold_par2reg := \n    match goal with \n      | [ |- context[par2reg ?p ?s] ] => \n        let H := fresh \"H\" in \n          let x := fresh \"x\" in\n            let r := fresh \"r\" in \n              let s := fresh \"s\" in \n                assert (H : exists x, x = par2reg p s) ; [eauto | idtac] ; \n                  destruct H as [x H]; \n                    rewrite <- H in * ; destruct x as [r s] \n    end.\n\n  (** Define a partial order on contexts, which the translation respects.  That is,\n      the input context is always less than the output context. *)\n  Definition ctxt_leq(c1 c2:ctxt_t) : Prop := \n    exists c:ctxt_t, c2 = c1 ++ c.\n\n  Lemma ctxt_leq_trans : forall c1 c2 c3, \n    ctxt_leq c1 c2 -> ctxt_leq c2 c3 -> ctxt_leq c1 c3.\n  Proof.\n    unfold ctxt_leq ; s. rewrite app_ass. eauto.\n  Qed.\n\n  Lemma ctxt_leq_refl : forall c, ctxt_leq c c.\n    unfold ctxt_leq ; s. exists nil. apply app_nil_end.\n  Qed.\n  Hint Resolve ctxt_leq_refl : dfa.\n\n  Lemma ctxt_ext : forall c c', ctxt_leq c (c ++ c').\n    unfold ctxt_leq ; s. eauto.\n  Qed.\n  Hint Resolve ctxt_ext : dfa.\n\n  (** Simplify reasoning about inductive hypotheses that depend upon a context. *)\n  Ltac p2rsimp := \n    match goal with \n      | [ |- context[length(?x ++ ?y)] ] => rewrite (@app_length _ x y)\n      | [ IH : forall _:ctxt_t, _, H : _ = par2reg ?p ?s |- _ ] => \n        generalize (IH s) ; \n          match goal with \n            | [ |- context[par2reg ?p ?s] ] => \n              let H' := fresh \"H\" in generalize (IH s) ; clear IH ; rewrite <- H ; simpl ; \n                intro H'\n            | _ => fail\n          end \n      | _ => idtac\n    end.\n\n  (** The translation only results in a greater or equal ctxt *)\n  Lemma p2r_extends : forall t (p:parser t) (c:ctxt_t), ctxt_leq c (snd (par2reg p c)).\n  Proof.\n    unfold ctxt_leq ; induction p ; simpl ; unfold extend_state ; intros ; \n      repeat unfold_par2reg ; simpl ; \n      try (exists nil ; mysimp ; fail) ; repeat p2rsimp ; s ; \n    try rewrite app_ass ; econstructor ; eauto.\n  Qed.\n\n  (** Functions stay well-typed under greater or equal contexts. *)\n  Lemma extends_wf_fn : forall t1 t2 (f:fn t1 t2) c c', ctxt_leq c c' ->\n   wf_fn c f -> wf_fn c' f.\n  Proof.\n    unfold ctxt_leq ; s ; destruct f ; auto ; simpl in * ; generalize c H0 ; clear c H0 ; \n    unfold fn_result, fn_result' in * ; induction f ; destruct c ; \n      [ mysimp | mysimp | mysimp | intro ] ; try congruence ;\n    simpl in *. firstorder.\n    destruct H0. generalize (IHf _ (conj (lt_S_n _ _ H) H0)). mysimp. firstorder.\n  Qed.\n\n  (** Regexps stay well-typed under greater or equal contexts. *)\n  Lemma extends_wf_regexp : forall t (r:regexp t) c c', \n    ctxt_leq c c' -> wf_regexp c r -> wf_regexp c' r.\n  Proof.\n    induction r ; simpl ; s ; firstorder. eapply extends_wf_fn ; eauto. econstructor ; eauto.\n  Qed.\n\n  (** Tactic for remembering a translated sub-term is well-formed. *)\n  Ltac p2rext := \n    match goal with \n      | [ H : (?r,?s2) = par2reg ?p ?s |- _ ] => \n        generalize (p2r_extends p s) ; rewrite <- H ; simpl ; intro ; clear H\n    end.\n\n  Lemma FnResult : forall s p r, \n    fn_result (s ++ existT fn_result_m p r :: nil) (length s) = Some p.\n  Proof.\n    induction s ; mysimp ; firstorder.\n  Qed.\n  Hint Resolve FnResult.\n\n  (** The translation results in a well-formed regexp. *)\n  Lemma p2r_wf : forall t (p:parser t) c, wf_regexp (snd (par2reg p c)) (fst (par2reg p c)).\n  Proof.\n    induction p ; mysimp ; repeat unfold_par2reg ; repeat p2rsimp ; mysimp ; p2rext ; \n    try (eapply (@extends_wf_regexp _ _ s); eauto) ; try econstructor ; eauto with arith.\n  Qed.\n\n  (** Applying the same function in an extended environment yields the same result. *)\n  Lemma extend_apply : forall x t1 t2 (f:fn t1 t2) s (H:wf_fn s f) v1 H', \n    apply_fn (s ++ x) f H' v1 = apply_fn s f H v1.\n  Proof.\n    destruct f ; auto. simpl. \n    mysimp. generalize f l0 e0 l e ; clear f l0 e0 l e. \n    induction s ; destruct f ; mysimp ; firstorder ; \n      unfold fn_result, fn_result' in * |- ; simpl in * ;\n      try congruence. destruct a. rewrite (proof_irrelevance e0 e) in *. auto.\n  Qed.\n  Hint Resolve extend_apply : dfa.\n\n  (** [in_regexp] respects weakening on states. *)\n  Lemma in_leq : forall t (r:regexp t) s cs v, \n    in_regexp s r cs v -> \n    forall s', ctxt_leq s s' -> in_regexp s' r cs v.\n  Proof.\n    unfold ctxt_leq ; induction 1 ; s ; \n    match goal with \n      | [ IH : forall _, _ -> in_regexp _ ?r2 _ _ |- in_regexp _ (Alt _ ?r2) _ _ ] => \n        eapply Alt_right_i ; eauto with dfa\n      | [ H : ?cs1 <> nil |- in_regexp _ (Star _) _ _ ] => \n        eapply Star_cat_i ; eauto with dfa\n      | [ |- in_regexp _ (Map ?f ?r) ?cs (apply_fn _ ?f ?H ?v1) ] => \n        apply (Map_i(v1:=v1) f (@extends_wf_fn t1 t2 f _ _ (ctxt_ext s x) H)) ; \n          eauto with dfa\n      | _ => econstructor ; eauto with dfa \n    end.\n  Qed.\n\n  (** Newly-allocated functions are well-formed with respect to the resulting context. *)\n  Lemma new_fn_wf : forall t1 t2 f s, wf_fn (s ++ existT fn_result_m (t1,t2) f :: nil)\n    (Fn_name (length s) t1 t2).\n  Proof.\n    induction s; mysimp ; firstorder.\n  Qed.\n  Hint Resolve new_fn_wf : dfa.\n\n  (** If [(cs,v)] is in [[p]] then [(cs,v)] is in [[r]] under the output context [s]. *)\n  Lemma p2r_ok : forall t (p:parser t) cs v, \n    in_parser p cs v -> \n    forall s, \n      in_regexp (snd (par2reg p s)) (fst (par2reg p s)) cs v.\n  Proof.\n    induction 1 ; simpl ; intro s ;\n      repeat (try unfold_par2reg ; simpl in * ; repeat p2rsimp ; repeat p2rext ; intros) ;\n        s ; \n        match goal with \n          | [ H : in_regexp _ ?r _ _ |- in_regexp _ (Alt _ ?r) _ _] => \n            eapply Alt_right_i ; eauto\n          | [ |- in_regexp _ (Map _ _) _ _ ] => idtac\n          | [ H1 : in_regexp _ ?r _ _, \n              H2: in_regexp _ (Star ?r) _ _ |- in_regexp _ (Star ?r) _ _ ] => \n          s ; eapply Star_cat_i ; eauto\n          | _ => econstructor ; eauto ; eapply in_leq ; eauto \n        end.\n    apply (Map_i(v1:=v1) (Fn_name (length s0) t1 t2) (new_fn_wf f s0)).\n    eapply in_leq ; eauto ; unfold ctxt_leq ; eauto. \n    generalize s0 (new_fn_wf f s0). induction s1 ; mysimp ; \n    unfold fn_result, fn_result' in * ; \n    simpl in *. rewrite (proof_irrelevance e (eq_refl _)). auto. \n    generalize (IHs1 (conj (lt_S_n _ _ l) e)). clear IHs1. auto.\n  Qed.\n\n  (** If [(cs,v)] is in [[r]] under context [s2], and [r] is well-formed with respect to\n     context [s1], and [s1 <= s2], then [(cs,v)] is in [[r]] under context [s1]. *)\n  Lemma extends_in : \n    forall t (r:regexp t) cs v s1 s2, \n      in_regexp s2 r cs v -> \n      wf_regexp s1 r -> \n      ctxt_leq s1 s2 -> \n      in_regexp s1 r cs v.\n  Proof.\n    induction 1 ; simpl ; intros ; s ; (econstructor ; eauto ; fail) || \n    (eapply Alt_right_i ; eauto) || (eapply Star_cat_i ; eauto) || idtac.\n    apply (@Map_i s1 t1 t2 f r cs v1 (apply_fn s2 f H v1) H4).\n    apply IHin_regexp ; auto. destruct H3. subst. symmetry. eapply extend_apply.\n  Qed.\n  Hint Resolve extends_in : dfa.\n\n  (** If [(cs,v)] is in [r] under context [s], where [(r,s) = par2reg p], then\n      [(cs,v)] is in [p]. *)\n  Lemma r2p_ok : forall t (p:parser t) s cs v, \n    in_regexp (snd (par2reg p s)) (fst (par2reg p s)) cs v -> \n    in_parser p cs v.\n  Proof.\n    induction p ; simpl ; intros s cs v ; try (repeat unfold_par2reg) ; \n      simpl in * ; intros ; (generalize (AnyInv H) || generalize (CharInv H) || \n          generalize (EpsInv H) || generalize (CatInv H1) || generalize (AltInv H1) || \n            generalize (MapInv H0) || generalize (ZeroInv H) || idtac) ; s ; \n      try (econstructor ; eauto ; fail) ;\n    repeat match goal with \n      | [ IH : forall _ _ _, in_regexp (snd (par2reg ?p _)) _ _ _ -> _, \n          H : _ = par2reg ?p ?s |- _ ] => \n      generalize (IH s) ; generalize (p2r_extends p s) ; generalize (p2r_wf p s) ; \n        rewrite <- H ; simpl ; clear IH ; intros\n    end ; \n    try contradiction || \n      (econstructor ; eauto with dfa ; fail) || (eapply Alt_right_pi ; eauto with dfa).\n    generalize (star_rep H0 (eq_refl _) (eq_refl _)). mysimp. clear H0. \n    generalize cs v H4. clear cs v H4.\n    induction x ; s. constructor ; auto. eapply Star_cat_pi ; eauto. \n    match goal with \n      | [ |- in_parser (Map_p _ r _) _ (?f x) ] => assert (f = r)\n    end.\n    \n    generalize s0 e l. induction s1 ; unfold value, error, fn_result, fn_result' ; mysimp.\n    rewrite (proof_irrelevance e0 (eq_refl _)). auto.\n    rewrite H5. eapply (Map_pi _ r). apply H4. \n    apply (@extends_in _ r0 cs x s0 (snd (extend_state s0 r)) H1 H2). unfold extend_state.\n    simpl. auto with dfa. auto.\n  Qed.\n\n  (** The translation preserves meaning *)\n  Theorem parser2regexp_equiv : \n    forall t (p:parser t) cs v, \n      in_parser p cs v <-> \n      in_regexp (snd (parser2regexp p)) (fst (parser2regexp p)) cs v.\n  Proof.\n    unfold parser2regexp ; mysimp ; firstorder ; [eapply p2r_ok | eapply r2p_ok] ; eauto.\n  Qed.\n\n  (** Finally -- convert the parser to a regexp and then run the \n     derivative-based parser on this. *)\n  Definition parse t (p:parser t) : list char_p -> list (result_m t) := \n    deriv_parse (snd (parser2regexp p))\n                (fst (parser2regexp p)) (p2r_wf p _).\n\n  Theorem parse_correct : forall t (p:parser t) cs v, \n    in_parser p cs v <-> In v (parse p cs).\n  Proof.\n    intros t p cs v.\n    \n    generalize (DerivParse_is_parser (snd (parser2regexp p)) (fst (parser2regexp p))\n      (p2r_wf p initial_ctxt) cs v) ; intro H ; destruct H ;\n    generalize (parser2regexp_equiv p cs v) ; intro  H1 ; destruct H1 ; split ; auto.\n  Qed.\n\n  (** Properties of dfa_recognize *)\n  Lemma dfa_loop_run : forall num_tokens ts d state count count2 ts2,\n    dfa_loop num_tokens d state count ts = Some (count2, ts2) -> \n    exists ts1, \n      ts = ts1 ++ ts2 /\\ count2 = length ts1 + count /\\ \n      run_dfa num_tokens d state ts1 = true /\\\n      forall ts1' ts2',\n        ts = ts1' ++ ts2' -> \n        length ts1' < length ts1 -> \n        ~ run_dfa num_tokens d state ts1' = true.\n  Proof. admit. (*\n    induction ts ; mysimp ; remember (nth state (dfa_accepts d) false) ; \n    destruct b ; try congruence ; try (injection H ; mysimp ; clear H ; subst). \n    exists nil. rewrite Heqb. repeat split ; auto. intros. simpl in H0.\n    assert False. omega. contradiction.\n    exists nil. simpl. rewrite Heqb. repeat split ; auto.\n    intros. assert False. omega. contradiction.\n    specialize (IHts d _ _ _ _ H0). mysimp. subst. exists (a::x). simpl.\n    repeat split ; auto. intros. destruct ts1'. injection H ; intros ; clear H ; subst.\n    simpl. congruence. simpl in H. injection H ; intros ; clear H ; subst.\n    specialize (H3 _ _ H4). assert (length ts1' < length x). simpl in *.\n    omega. specialize (H3 H). simpl. congruence. *)\n  Qed.\n\n  Lemma list_all_app : forall A (f:A->Prop) (xs ys:list A), \n    list_all f (xs ++ ys) -> list_all f xs /\\ list_all f ys.\n  Proof.\n    induction xs ; mysimp ; specialize (IHxs _ H0) ; mysimp.\n  Qed.\n\n  Lemma dfa_recognize_corr (num_tokens:nat) (token_id_to_chars : token_id -> list char_p) : \n    forall t (p:parser t) n (d:DFA),\n    build_dfa num_tokens token_id_to_chars n (par2rec p) = Some d -> \n    forall ts, \n      list_all (fun t => t < num_tokens) ts -> \n      match dfa_recognize num_tokens d ts with \n        | None => True\n        | Some (count,ts2) => \n          exists ts1, exists v, \n            ts = ts1 ++ ts2 /\\ count = length ts1 /\\ \n            in_parser p (flat_map token_id_to_chars ts1) v /\\\n            forall ts3 ts4,\n              length ts3 < length ts1 ->\n              ts = ts3 ++ ts4 -> \n              forall v, ~ in_parser p (flat_map token_id_to_chars ts3) v\n      end.\n  Proof.\n    intros. unfold dfa_recognize. remember (dfa_loop num_tokens d 0 0 ts) as e.\n    destruct e ; auto. destruct p0. \n    generalize (dfa_loop_run _ _ _ _ _ (eq_sym Heqe)). mysimp. subst.\n    exists x. generalize (list_all_app _ _ _ H0).  mysimp.\n    generalize (dfa_corr nil _ _ _ _ H _ H1). rewrite H3. mysimp. \n    rewrite plus_comm. simpl. exists x0. repeat split ; auto.\n    intros. specialize (H4 _ _ H7 H6). intro. apply H4.\n    rewrite H7 in H0. generalize (list_all_app _ _ _ H0). mysimp.\n    generalize (@dfa_corr nil num_tokens token_id_to_chars _ p n d H ts3 H9).\n    destruct (run_dfa num_tokens d 0 ts3). auto. intros. assert False.\n    eapply H11. eauto. contradiction.\n  Qed.\n    \nEnd Parser.\n", "meta": {"author": "JeremyRubin", "repo": "VerifiedDSP", "sha": "a28fb79035bf5689fb9285c5581d5c1bc1a0b0db", "save_path": "github-repos/coq/JeremyRubin-VerifiedDSP", "path": "github-repos/coq/JeremyRubin-VerifiedDSP/VerifiedDSP-a28fb79035bf5689fb9285c5581d5c1bc1a0b0db/Model/Parser.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2264660260328542}}
{"text": "(** * Data types for the crowdfunding contract tailored for extraction *)\n\nRequire Import String ZArith Basics.\nFrom ConCert.Embedding Require Import Ast Notations PCUICTranslate Utils.\nFrom ConCert.Embedding.Examples Require Import SimpleBlockchain.\nFrom ConCert.Extraction.Examples Require Import Prelude.\n\nRequire Import List PeanoNat ssrbool.\n\nImport ListNotations.\nFrom MetaCoq.Template Require Import All.\n\nImport MonadNotation.\nImport BaseTypes.\nOpen Scope list.\n\n\nImport AcornBlockchain.\n\n(** Note that we define the deep embedding (abstract syntax trees) of the data structures and programs using notations. These notations are defined in  [Ast.v] and make use of the \"custom entries\" feature. *)\n\n(** Brackets like [[\\ \\]] delimit the scope of data type definitions and like [[| |]] the scope of programs *)\n\n(** Generating names for the data structures  *)\nRun TemplateProgram\n      (mkNames [\"State\" ; \"mkState\"; \"balance\" ; \"donations\" ; \"owner\"; \"deadline\"; \"goal\"; \"done\";\n                \"Res\" ; \"Error\";\n                \"msg\"; \"Donate\"; \"GetFunds\"; \"Claim\";\n                \"Action\"; \"Transfer\"; \"Empty\" ] \"_coq\").\n\nImport ListNotations.\n\n(** ** Definitions of data structures for the contract *)\n\n(** Parameters of the contract *)\nDefinition params_ty : type :=\n  (* Deadline, Goal, Owner *)\n  [! time × (money × address)!].\n\n(** The internal state of the contract that is modified during the execution *)\nDefinition state_ty : type :=\n  (* Contributions, Done *)\n  [! Map × Bool !].\n\n(** The full type of contract's internal state  *)\nDefinition full_state_ty :=\n  [! {params_ty} × {state_ty} !].\n\n(** Messages *)\nDefinition msg_syn :=\n  [\\ data msg =\n       Donate [_]\n     | GetFunds [_]\n     | Claim [_] \\].\n\nMake Inductive (global_to_tc msg_syn).\n\n\n(** ** Custom notations for projections from the state type *)\n\nNotation \"'get_params' st\" :=\n  [| first {params_ty} {state_ty} {st} |]\n    (in custom expr at level 0).\n\nNotation \"'get_state' st\" :=\n  [| second {params_ty} {state_ty} {st} |]\n    (in custom expr at level 0).\n\nNotation \"'deadline' st\" :=\n  [| first time (money × address) (get_params {st}) |]\n    (in custom expr at level 0).\n\nNotation \"'goal' st\" :=\n  [| first money address (second time (money × address) (get_params {st})) |]\n    (in custom expr at level 0).\n\nNotation \"'owner' st\" :=\n  [| second money address (second time (money × address) (get_params {st})) |]\n    (in custom expr at level 0).\n\nNotation \"'contribs' st\" :=\n    [| first Map Bool (get_state {st}) |]\n      (in custom expr at level 0).\n\nNotation \"'done' st\" :=\n  [| second Map Bool (get_state {st}) |]\n    (in custom expr at level 0).\n\n(** ** State \"updates\" *)\n\nNotation \"'mkFullState' prms st\" :=\n    [| Pair {params_ty} {state_ty} {prms} {st} |]\n      (in custom expr at level 0,\n          prms custom expr at next level,\n          st custom expr at next level).\n\nNotation \"'mkParams' dl g o\" :=\n  [| Pair time (money × address) {dl} (Pair money address {g} {o}) |]\n      (in custom expr at level 0,\n          dl custom expr at next level,\n          g custom expr at next level,\n          o custom expr at next level).\n\nNotation \"'mkState' cs dn\" :=\n    [| Pair Map Bool {cs} {dn} |]\n      (in custom expr at level 0,\n          cs custom expr at next level,\n          dn custom expr at next level).\n\nDefinition update_contribs_syn :=\n  [| \\\"f_st\" : {full_state_ty} => \\\"cs\" : Map =>\n     let \"ps\" : {params_ty} := get_params \"f_st\" in\n     let \"new_st\" : {state_ty} := mkState \"cs\" (done \"f_st\") in\n     mkFullState \"ps\" \"new_st\" |].\n\nMake Definition update_contribs :=\n  (expr_to_tc Σ (indexify nil update_contribs_syn)).\n\nDefinition set_done_syn :=\n  [| \\\"f_st\" : {full_state_ty} =>\n     let \"ps\" : {params_ty} := get_params \"f_st\" in\n     let \"new_st\" : {state_ty} := mkState (contribs \"f_st\") True in\n     mkFullState \"ps\" \"new_st\" |].\n\nMake Definition set_done :=\n  (expr_to_tc Σ (indexify nil set_done_syn)).\n\n\n(** ** Custom notations for projections from the call context and global state *)\nModule Notations.\n\n  Notation \"'ctx_from' a\" := [| {eConst \"Ctx_from\"} {a} |]\n                             (in custom expr at level 0).\n  Notation \"'ctx_contract_address' a\" :=\n    [| {eConst \"Ctx_contract_address\"} {a} |]\n      (in custom expr at level 0).\n  Notation \"'amount' a\" := [| {eConst \"Ctx_amount\"} {a} |]\n                             (in custom expr at level 0).\n\n  (** New global context with the constants defined above (in addition to the ones defined in the Oak's \"StdLib\") *)\n\n  Definition Σ' :=\n    Prelude.Σ ++ [ Prelude.AcornMaybe;\n           msg_syn;\n           addr_map_acorn;\n           AcornBlockchain.SimpleChainAcorn;\n           AcornBlockchain.SimpleContractCallContextAcorn;\n           AcornBlockchain.SimpleActionBodyAcorn;\n           gdInd \"Z\" 0 [(\"Z0\", []); (\"Zpos\", [(None,tyInd \"positive\")]);\n                          (\"Zneg\", [(None,tyInd \"positive\")])] false].\n\n\n  Notation \"0 'z'\" := (eConstr \"Z\" \"Z0\") (in custom expr at level 0).\n  End Notations.\n\nNotation SCtx := \"SimpleContractCallContext\".\n", "meta": {"author": "malthelange", "repo": "CLVM", "sha": "e80aef02c3112b5b62db79bc2b233020367b0bde", "save_path": "github-repos/coq/malthelange-CLVM", "path": "github-repos/coq/malthelange-CLVM/CLVM-e80aef02c3112b5b62db79bc2b233020367b0bde/extraction/examples/crowdfunding_extract/CrowdfundingData.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2264660260328542}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import fastpile.\nRequire Import spec_stdlib.\nGlobal Open Scope funspec_scope.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition tpile := Tstruct _pile noattr.\n\nDefinition countrep (s: Z) (p: val) : mpred :=\n  EX s':Z, !! (0 <= s /\\ 0 <= s' <= Int.max_signed /\\\n                 (s <= Int.max_signed -> s'=s)) &&\n  data_at Ews tpile (Vint (Int.repr s')) p.\n\nDefinition count_freeable (p: val) :=\n   malloc_token Ews tpile p.\n\nLemma countrep_local_facts:\n  forall s p,\n   countrep s p |-- !! isptr p.\nProof.\nintros.\nunfold countrep.\nIntros s'.\nentailer!.\nQed.\n\nHint Resolve countrep_local_facts : saturate_local.\n\nLemma countrep_valid_pointer:\n  forall s p,\n   countrep s p |-- valid_pointer p.\nProof. \n intros.\n unfold countrep. Intros s'.\n auto with valid_pointer.\nQed.\nHint Resolve countrep_valid_pointer : valid_pointer.\n\nLocal Open Scope assert.\n\nDefinition surely_malloc_spec :=\n  DECLARE _surely_malloc\n   WITH t:type, gv: globals\n   PRE [ tuint ]\n       PROP (0 <= sizeof t <= Int.max_unsigned;\n                complete_legal_cosu_type t = true;\n                natural_aligned natural_alignment t = true)\n       PARAMS (Vint (Int.repr (sizeof t))) GLOBALS (gv)\n       SEP (mem_mgr gv)\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (mem_mgr gv; malloc_token Ews t p * data_at_ Ews t p).\n\nDefinition Pile_new_spec :=\n DECLARE _Pile_new\n WITH gv: globals\n PRE [ ] PROP() PARAMS () GLOBALS (gv) SEP(mem_mgr gv)\n POST[ tptr tpile ]\n   EX p: val,\n      PROP() LOCAL(temp ret_temp p)\n      SEP(countrep 0 p; count_freeable p; mem_mgr gv).\n\nDefinition Pile_add_spec :=\n DECLARE _Pile_add\n WITH p: val, n: Z, s: Z, gv: globals\n PRE [ tptr tpile, tint ]\n    PROP(0 <= n <= Int.max_signed)\n    PARAMS (p; Vint (Int.repr n)) GLOBALS (gv)\n    SEP(countrep s p; mem_mgr gv)\n POST[ tvoid ]\n    PROP() LOCAL()\n    SEP(countrep (n+s) p; mem_mgr gv).\n\nDefinition Pile_count_spec :=\n DECLARE _Pile_count\n WITH p: val, s: Z\n PRE [ tptr tpile  ]\n    PROP()\n    PARAMS (p) GLOBALS ()\n    SEP(countrep s p)\n POST[ tint ]\n   EX s':Z, \n      PROP(s <= Int.max_signed -> s'=s) \n      LOCAL(temp ret_temp (Vint (Int.repr s')))\n      SEP(countrep s p).\n\nDefinition Pile_free_spec :=\n DECLARE _Pile_free\n WITH p: val, s: Z, gv: globals\n PRE [ tptr tpile  ]\n    PROP()\n    PARAMS (p) GLOBALS (gv)\n    SEP(countrep s p; count_freeable p; mem_mgr gv)\n POST[ tvoid ]\n    PROP() LOCAL() SEP(mem_mgr gv).\n\nDefinition ispecs := [surely_malloc_spec].\nDefinition specs := [Pile_new_spec; Pile_add_spec; Pile_count_spec; Pile_free_spec].\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/pile/fast/spec_fastpile_concrete.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.22646602603285418}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export nuprl_props.\nRequire Export choice.\nRequire Export cvterm.\n\n\nLemma tequality_uatom {p} :\n  forall lib, @tequality p lib mkc_uatom mkc_uatom.\nProof.\n  introv.\n  unfold tequality.\n  exists (@equality_of_uatom p lib).\n  unfold nuprl.\n  apply CL_uatom.\n  unfold per_uatom; sp; spcast;\n  try (apply computes_to_valc_refl);\n  try (apply iscvalue_mkc_uatom; auto).\nQed.\n\nLemma equality_in_uatom_iff {p} :\n  forall lib (t1 t2 : @CTerm p),\n    equality lib t1 t2 mkc_uatom\n    <=> {a : get_patom_set p\n        , t1 ===>(lib) (mkc_utoken a)\n        # t2 ===>(lib) (mkc_utoken a)}.\nProof.\n  intros; split; intro i; exrepnd.\n  - unfold equality, nuprl in i; exrepnd.\n    inversion i1; subst; try not_univ.\n    allunfold @per_uatom; repnd.\n    allunfold @eq_term_equals.\n    discover.\n    allunfold @equality_of_uatom; exrepnd.\n    exists u; sp.\n  - exists (@equality_of_uatom p lib); dands.\n    apply CL_uatom; unfold per_uatom; sp;\n    spcast; apply computes_to_value_isvalue_refl; repeat constructor; simpl; sp.\n    exists a; sp.\nQed.\n\nLemma tequality_atom {p} :\n  forall lib, @tequality p lib mkc_atom mkc_atom.\nProof.\n  introv.\n  unfold tequality.\n  exists (@equality_of_atom p lib).\n  unfold nuprl.\n  apply CL_atom.\n  unfold per_atom; sp; spcast;\n  try (apply computes_to_valc_refl);\n  try (apply iscvalue_mkc_atom; auto).\nQed.\n\nLemma equality_in_atom_iff {p} :\n  forall lib (t1 t2 : @CTerm p),\n    equality lib t1 t2 mkc_atom\n    <=> {a : String.string\n        , t1 ===>(lib) (mkc_token a)\n        # t2 ===>(lib) (mkc_token a)}.\nProof.\n  intros; split; intro i; exrepnd.\n  - unfold equality, nuprl in i; exrepnd.\n    inversion i1; subst; try not_univ.\n    allunfold @per_atom; repnd.\n    allunfold @eq_term_equals.\n    discover.\n    allunfold @equality_of_atom; exrepnd.\n    exists s; sp.\n  - exists (@equality_of_atom p lib); dands.\n    apply CL_atom; unfold per_atom; sp;\n    spcast; apply computes_to_value_isvalue_refl; repeat constructor; simpl; sp.\n    exists a; sp.\nQed.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/per/per_props_atom.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.22645172149711196}}
{"text": "From iris.algebra Require Import\n  excl\n  proofmode_classes.\n\nFrom caml5 Require Import\n  prelude.\nFrom caml5.algebra Require Export\n  base.\nFrom caml5.algebra Require Import\n  lib.auth_option.\n\nDefinition auth_excl A :=\n  auth_option (exclR A).\nDefinition auth_excl_R A :=\n  auth_option_R (exclR A).\nDefinition auth_excl_UR A :=\n  auth_option_UR (exclR A).\n\nDefinition auth_excl_auth {A : ofe} dq (a : A) : auth_excl_UR A :=\n  ●O{dq} (Excl a).\nDefinition auth_excl_frag {A : ofe} (a : A) : auth_excl_UR A :=\n  ◯O (Excl a).\nNotation \"●E{ dq } a\" := (auth_excl_auth dq a)\n( at level 20,\n  format \"●E{ dq }  a\"\n).\nNotation \"●E{# q } a\" := (●E{DfracOwn q} a)\n( at level 20,\n  format \"●E{# q }  a\"\n).\nNotation \"●E a\" := (●E{#1} a)\n( at level 20\n).\nNotation \"●E□ a\" := (●E{DfracDiscarded} a)\n( at level 20\n).\nNotation \"◯E a\" := (auth_excl_frag a)\n( at level 20\n).\n\nSection ofe.\n  Context {A : ofe}.\n  Implicit Types a b : A.\n\n  #[global] Instance auth_excl_auth_ne dq :\n    NonExpansive (@auth_excl_auth A dq).\n  Proof.\n    solve_proper.\n  Qed.\n  #[global] Instance auth_excl_auth_proper dq :\n    Proper ((≡) ==> (≡)) (@auth_excl_auth A dq).\n  Proof.\n    solve_proper.\n  Qed.\n  #[global] Instance auth_excl_frag_ne :\n    NonExpansive (@auth_excl_frag A).\n  Proof.\n    solve_proper.\n  Qed.\n  #[global] Instance auth_excl_frag_proper :\n    Proper ((≡) ==> (≡)) (@auth_excl_frag A).\n  Proof.\n    solve_proper.\n  Qed.\n\n  #[global] Instance auth_excl_auth_dist_inj n :\n    Inj2 (=) (≡{n}≡) (≡{n}≡) (@auth_excl_auth A).\n  Proof.\n    intros ?* (-> & ?%(inj Excl))%(inj2 auth_option_auth). done.\n  Qed.\n  #[global] Instance auth_excl_auth_inj :\n    Inj2 (=) (≡) (≡) (@auth_excl_auth A).\n  Proof.\n    intros ?* (-> & ?%(inj Excl))%(inj2 auth_option_auth). done.\n  Qed.\n  #[global] Instance auth_excl_frag_dist_inj n :\n    Inj (≡{n}≡) (≡{n}≡) (@auth_excl_frag A).\n  Proof.\n    intros ?* ?%(inj auth_option_frag)%(inj Excl). done.\n  Qed.\n  #[global] Instance auth_excl_frag_inj :\n    Inj (≡) (≡) (@auth_excl_frag A).\n  Proof.\n    intros ?* ?%(inj auth_option_frag)%(inj Excl). done.\n  Qed.\n\n  #[global] Instance auth_excl_auth_discrete dq a :\n    Discrete a →\n    Discrete (●E{dq} a).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance auth_excl_frag_discrete a :\n    Discrete a →\n    Discrete (◯E a).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance auth_excl_cmra_discrete :\n    OfeDiscrete A →\n    CmraDiscrete (auth_excl_R A).\n  Proof.\n    apply _.\n  Qed.\n\n  Lemma auth_excl_auth_dfrac_op dq1 dq2 a :\n    ●E{dq1 ⋅ dq2} a ≡ ●E{dq1} a ⋅ ●E{dq2} a.\n  Proof.\n    apply auth_option_auth_dfrac_op.\n  Qed.\n  #[global] Instance auth_excl_auth_dfrac_is_op dq dq1 dq2 a :\n    IsOp dq dq1 dq2 →\n    IsOp' (●E{dq} a) (●E{dq1} a) (●E{dq2} a).\n  Proof.\n    apply _.\n  Qed.\n\n  #[global] Instance auth_excl_auth_core_id a :\n    CoreId (●E□ a).\n  Proof.\n    apply _.\n  Qed.\n\n  Lemma auth_excl_auth_dfrac_validN n dq a :\n    ✓{n} (●E{dq} a) ↔\n    ✓ dq.\n  Proof.\n    rewrite auth_option_auth_dfrac_validN. naive_solver.\n  Qed.\n  Lemma auth_excl_auth_dfrac_valid dq a :\n    ✓ (●E{dq} a) ↔\n    ✓ dq.\n  Proof.\n    rewrite auth_option_auth_dfrac_valid. naive_solver.\n  Qed.\n  Lemma auth_excl_auth_validN n a :\n    ✓{n} (●E a).\n  Proof.\n    rewrite auth_option_auth_validN //.\n  Qed.\n  Lemma auth_excl_auth_valid a :\n    ✓ (●E a).\n  Proof.\n    rewrite auth_option_auth_valid //.\n  Qed.\n\n  Lemma auth_excl_auth_dfrac_op_validN n dq1 a1 dq2 a2 :\n    ✓{n} (●E{dq1} a1 ⋅ ●E{dq2} a2) ↔\n    ✓ (dq1 ⋅ dq2) ∧ a1 ≡{n}≡ a2.\n  Proof.\n    rewrite auth_option_auth_dfrac_op_validN. split.\n    - naive_solver eauto using (inj Excl).\n    - naive_solver solve_proper.\n  Qed.\n  Lemma auth_excl_auth_dfrac_op_valid dq1 a1 dq2 a2 :\n    ✓ (●E{dq1} a1 ⋅ ●E{dq2} a2) ↔\n    ✓ (dq1 ⋅ dq2) ∧ a1 ≡ a2.\n  Proof.\n    rewrite auth_option_auth_dfrac_op_valid. split.\n    - naive_solver eauto using (@inj _ _ equiv equiv Excl) with typeclass_instances.\n    - naive_solver solve_proper.\n  Qed.\n  Lemma auth_excl_auth_op_validN n a1 a2 :\n    ✓{n} (●E a1 ⋅ ●E a2) ↔\n    False.\n  Proof.\n    rewrite auth_option_auth_op_validN //.\n  Qed.\n  Lemma auth_excl_auth_op_valid a b :\n    ✓ (●E a ⋅ ●E b) ↔\n    False.\n  Proof.\n    rewrite auth_option_auth_op_valid //.\n  Qed.\n\n  Lemma auth_excl_frag_validN n a :\n    ✓{n} (◯E a).\n  Proof.\n    rewrite auth_option_frag_validN //.\n  Qed.\n  Lemma auth_excl_frag_valid a :\n    ✓ (◯E a).\n  Proof.\n    rewrite auth_option_frag_valid //.\n  Qed.\n\n  Lemma auth_excl_frag_op_validN n a b :\n    ✓{n} (◯E a ⋅ ◯E b) ↔\n    False.\n  Proof.\n    rewrite auth_option_frag_op_validN //.\n  Qed.\n  Lemma auth_excl_frag_op_valid a b :\n    ✓ (◯E a ⋅ ◯E b) ↔\n    False.\n  Proof.\n    rewrite auth_option_frag_op_valid //.\n  Qed.\n\n  Lemma auth_excl_both_dfrac_validN n dq a b :\n    ✓{n} (●E{dq} a ⋅ ◯E b) ↔\n    ✓ dq ∧ a ≡{n}≡ b.\n  Proof.\n    rewrite auth_option_both_dfrac_validN. split.\n    - intros (? & [?%(inj Excl) | ?%exclusive_includedN] & ?); done || apply _.\n    - naive_solver solve_proper.\n  Qed.\n  Lemma auth_excl_both_dfrac_valid dq a b :\n    ✓ (●E{dq} a ⋅ ◯E b) ↔\n    ✓ dq ∧ a ≡ b.\n  Proof.\n    rewrite auth_option_both_dfrac_valid. split.\n    - intros (? & H & ?). split; first done.\n      rewrite equiv_dist. intros n.\n      specialize (H n) as [?%(inj Excl) | ?%exclusive_includedN]; done || apply _.\n    - intros. destruct_and!. split_and!; try done.\n      intros. left. f_equiv. eauto using equiv_dist.\n  Qed.\n  Lemma auth_excl_both_validN n a b :\n    ✓{n} (●E a ⋅ ◯E b) ↔\n    a ≡{n}≡ b.\n  Proof.\n    rewrite auth_excl_both_dfrac_validN. naive_solver done.\n  Qed.\n  Lemma auth_excl_both_valid a b :\n    ✓ (●E a ⋅ ◯E b) ↔\n    a ≡ b.\n  Proof.\n    rewrite auth_excl_both_dfrac_valid. naive_solver done.\n  Qed.\n\n  Lemma auth_excl_auth_persist dq a :\n    ●E{dq} a ~~> ●E□ a.\n  Proof.\n    apply auth_option_auth_persist.\n  Qed.\n  Lemma auth_excl_both_update a b a' b' :\n    a' ≡ b' →\n    ●E a ⋅ ◯E b ~~> ●E a' ⋅ ◯E b'.\n  Proof.\n    intros <-. apply auth_option_both_update, exclusive_local_update. done.\n  Qed.\nEnd ofe.\n\n#[global] Opaque auth_excl_auth.\n#[global] Opaque auth_excl_frag.\n", "meta": {"author": "clef-men", "repo": "caml5", "sha": "0de06d5792138eb17877ed1536a0401b7a322ee2", "save_path": "github-repos/coq/clef-men-caml5", "path": "github-repos/coq/clef-men-caml5/caml5-0de06d5792138eb17877ed1536a0401b7a322ee2/theories/algebra/lib/auth_excl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2264517214971119}}
{"text": "Require Import Coq.Lists.List.\n\nRequire Export SystemFR.ReducibilitySubst.\n\nOpaque reducible_values.\nOpaque makeFresh.\n\nLemma reducibility_candidate_empty:\n  reducibility_candidate (fun _ => False).\nProof.\n  unfold reducibility_candidate; steps.\nQed.\n\nLemma reducible_type_abs:\n  forall ρ t T X,\n    fv t = nil ->\n    fv T = nil ->\n    wf t 0 ->\n    wf T 1 ->\n    is_erased_term t ->\n    valid_interpretation ρ ->\n    (X ∈ pfv T type_var -> False) ->\n    (X ∈ support ρ -> False) ->\n    (forall RC,\n      reducibility_candidate RC ->\n      [ (X,RC) :: ρ ⊨ t : topen 0 T (fvar X type_var) ]) ->\n   [ ρ ⊨ t : T_abs T ].\nProof.\n  intros.\n  unshelve epose proof (H7 (fun _ => False) _); steps; eauto using reducibility_candidate_empty; t_closing.\n\n  unfold reduces_to in *; repeat step || simp_red; t_closing.\n  exists v; repeat step || simp_red; t_closing;\n    eauto 3 using red_is_val, reducibility_candidate_empty with step_tactic.\n  exists X; steps.\n  instantiate_any; repeat step || t_deterministic_star;\n    eauto 3 using red_is_val, reducibility_candidate_empty with step_tactic.\nQed.\n\nLemma open_reducible_type_abs:\n  forall Θ Γ t T (X : nat),\n    subset (pfv t term_var) (support Γ) ->\n    subset (pfv T term_var) (support Γ) ->\n    wf t 0 ->\n    wf T 1 ->\n    (X ∈ pfv_context Γ term_var -> False) ->\n    (X ∈ pfv_context Γ type_var -> False) ->\n    (X ∈ pfv t term_var -> False) ->\n    (X ∈ pfv T term_var -> False) ->\n    (X ∈ pfv T type_var -> False) ->\n    (X ∈ Θ -> False) ->\n    is_erased_term t ->\n    [ X :: Θ; Γ ⊨ t : topen 0 T (fvar X type_var) ] ->\n    [ Θ; Γ ⊨ t : T_abs T ].\nProof.\n  unfold open_reducible; repeat step || t_termlist.\n\n  apply reducible_type_abs with X;\n    repeat step || rewrite fv_subst_different_tag in * by (steps; eauto with fv);\n      eauto with wf;\n      eauto with fv;\n      eauto with erased.\n\n  match goal with\n  | H: forall _ _, _ |- _ =>\n      unshelve epose proof (H ((X,RC) :: ρ) lterms _ _ _)\n  end;\n    repeat step || t_substitutions;\n    eauto using satisfies_unused.\nQed.\n\nLemma reducible_inst:\n  forall ρ t U V,\n    wf V 0 ->\n    twf V 0 ->\n    pfv V term_var = nil ->\n    wf U 0 ->\n    pfv U term_var = nil ->\n    valid_interpretation ρ ->\n    is_erased_type U ->\n    is_erased_type V ->\n    [ ρ ⊨ t : T_abs U ] ->\n    [ ρ ⊨ t : topen 0 U V ].\nProof.\n  unfold reduces_to in *;\n    repeat step || list_utils || simp_red || unfold reduces_to in *.\n  match goal with\n  | H: forall RC, reducibility_candidate RC -> _ |- _ =>\n      unshelve epose proof (H (fun v => [ ρ ⊨ v : V ]v) _); steps;\n        eauto using reducibility_is_candidate\n  end.\n  exists v; steps; eauto using star_trans with cbvlemmas.\n  apply (reducible_rename_one _ _ _ _ _ (makeFresh (pfv U type_var :: pfv V type_var :: nil))) in H12;\n    repeat step || finisher; eauto using reducibility_is_candidate.\n  eapply reducible_values_subst_head; eauto; repeat step || list_utils || finisher.\nQed.\n\nLemma open_reducible_inst:\n  forall Θ (Γ : context) t U V,\n    wf U 0 ->\n    wf V 0 ->\n    twf V 0 ->\n    is_erased_type U ->\n    is_erased_type V ->\n    subset (fv U) (support Γ) ->\n    subset (fv V) (support Γ) ->\n    [ Θ; Γ ⊨ t : T_abs U ] ->\n    [ Θ; Γ ⊨ t : topen 0 U V ].\nProof.\n  unfold open_reducible;\n    repeat step || t_instantiate_sat3 || rewrite substitute_topen || apply reducible_inst ||\n      rewrite fv_subst_different_tag in * by (steps; eauto with fv);\n    t_closer;\n    eauto with twf.\nQed.\n", "meta": {"author": "epfl-lara", "repo": "SystemFR", "sha": "a68d12d6360f395958506deea66112c46be492a0", "save_path": "github-repos/coq/epfl-lara-SystemFR", "path": "github-repos/coq/epfl-lara-SystemFR/SystemFR-a68d12d6360f395958506deea66112c46be492a0/ErasedPolymorphism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.22636067871409846}}
{"text": "Require Import List String.\nRequire Import Lib.CommonTactics Lib.Struct Lib.FMap.\nRequire Import Kami.Syntax Kami.Semantics Kami.SemFacts Kami.Wf.\n\nSet Implicit Arguments.\nSet Asymmetric Patterns.\n\nFixpoint composeLabels (ls1 ls2: LabelSeqT) :=\n  match ls1, ls2 with\n    | l1 :: ls1', l2 :: ls2' =>\n      (hide (mergeLabel l1 l2)) :: (composeLabels ls1' ls2')\n    | _, _ => nil\n  end.\n\nSection TwoModules.\n  Variables (ma mb: Modules).\n\n  Hypotheses (HmaEquiv: ModEquiv type typeUT ma)\n             (HmbEquiv: ModEquiv type typeUT mb).\n\n  Hypotheses (Hinit: DisjList (namesOf (getRegInits ma)) (namesOf (getRegInits mb)))\n             (Hdefs: DisjList (getDefs ma) (getDefs mb))\n             (Hcalls1: DisjList (getCalls ma) (getIntCalls mb))\n             (Hcalls2: DisjList (getIntCalls ma) (getCalls mb))\n             (Hvr: ValidRegsModules type (ConcatMod ma mb)).\n\n  Definition regsA (r: RegsT) := M.restrict r (namesOf (getRegInits ma)).\n  Definition regsB (r: RegsT) := M.restrict r (namesOf (getRegInits mb)).\n\n  Definition mergeUnitLabel (ul1 ul2: UnitLabel): UnitLabel :=\n    match ul1, ul2 with\n      | Rle (Some _), _ => ul1\n      | _, Rle (Some _) => ul2\n      | Meth (Some _), _ => ul1\n      | _, Meth (Some _) => ul2\n      | Rle None, _ => ul1\n      | _, Rle None => ul2\n      | _, _ => Meth None (* unspecified *)\n    end.\n\n  Definition OneMustMethNone (ul1 ul2: UnitLabel) :=\n    ul1 = Meth None \\/ ul2 = Meth None.\n  #[local] Hint Unfold OneMustMethNone.\n\n  Lemma substep_split:\n    forall o u ul cs,\n      Substep (ConcatMod ma mb) o u ul cs ->\n      exists ua ub ula ulb csa csb,\n        Substep ma (regsA o) ua ula csa /\\\n        Substep mb (regsB o) ub ulb csb /\\\n        M.Disj ua ub /\\ u = M.union ua ub /\\\n        OneMustMethNone ula ulb /\\ ul = mergeUnitLabel ula ulb /\\ \n        M.Disj csa csb /\\ cs = M.union csa csb.\n  Proof.\n    induction 1; simpl; intros.\n\n    - exists (M.empty _), (M.empty _).\n      exists (Rle None), (Meth None), (M.empty _), (M.empty _).\n      repeat split; auto; constructor.\n\n    - exists (M.empty _), (M.empty _).\n      exists (Meth None), (Meth None), (M.empty _), (M.empty _).\n      repeat split; auto; constructor.\n\n    - simpl in HInRules; apply in_app_or in HInRules.\n      destruct HInRules.\n      + exists u, (M.empty _).\n        exists (Rle (Some k)), (Meth None), cs, (M.empty _).\n        repeat split; auto; econstructor; eauto.\n        apply validRegsAction_old_regs_restrict; auto.\n        eapply validRegsRules_rule; eauto.\n        inv Hvr; apply validRegsModules_validRegsRules; auto.\n      + exists (M.empty _), u.\n        exists (Meth None), (Rle (Some k)), (M.empty _), cs.\n        repeat split; auto; econstructor; eauto.\n        apply validRegsAction_old_regs_restrict; auto.\n        eapply validRegsRules_rule; eauto.\n        inv Hvr; apply validRegsModules_validRegsRules; auto.\n\n    - simpl in HIn; apply in_app_or in HIn.\n      destruct HIn.\n      + exists u, (M.empty _).\n        eexists (Meth (Some _)), (Meth None), cs, (M.empty _).\n        repeat split; auto; econstructor; eauto.\n        apply validRegsAction_old_regs_restrict; auto.\n        eapply validRegsDms_dm; eauto.\n        inv Hvr; apply validRegsModules_validRegsDms; auto.\n      + exists (M.empty _), u.\n        eexists (Meth None), (Meth (Some _)), (M.empty _), cs.\n        repeat split; auto; econstructor; eauto.\n        apply validRegsAction_old_regs_restrict; auto.\n        eapply validRegsDms_dm; eauto.\n        inv Hvr; apply validRegsModules_validRegsDms; auto.\n        \n  Qed.\n\n  Lemma substepsInd_split:\n    forall o u l,\n      SubstepsInd (ConcatMod ma mb) o u l ->\n      exists ua ub la lb,\n        SubstepsInd ma (regsA o) ua la /\\\n        SubstepsInd mb (regsB o) ub lb /\\\n        M.Disj ua ub /\\ u = M.union ua ub /\\\n        CanCombineLabel la lb /\\ l = mergeLabel la lb.\n  Proof.\n    induction 1; simpl; intros.\n    - exists (M.empty _), (M.empty _), emptyMethLabel, emptyMethLabel.\n      repeat split; auto; try constructor;\n        simpl; intro; eapply M.F.P.F.empty_in_iff; eauto.\n\n    - subst.\n      destruct IHSubstepsInd as [pua [pub [pla [plb ?]]]]; dest; subst.\n      apply substep_split in H0.\n      destruct H0 as [sua [sub [sula [sulb [scsa [scsb ?]]]]]];\n        dest; subst.\n\n      exists (M.union pua sua), (M.union pub sub).\n      exists (mergeLabel (getLabel sula scsa) pla),\n      (mergeLabel (getLabel sulb scsb) plb).\n      inv H1; inv H6; dest.\n\n      repeat split.\n\n      + eapply SubstepsCons; eauto.\n        repeat split; auto.\n        { destruct pla, plb; simpl in *; mdisj. }\n        { destruct pla as [[[|]|] ? ?], plb as [[[|]|] ? ?];\n          destruct sula as [[|]|[|]], sulb as [[|]|[|]];\n          simpl in *; auto; findeq; try (inv H9; discriminate).\n        }\n        \n      + eapply SubstepsCons; eauto.\n        repeat split; auto.\n        { destruct pla, plb; simpl in *; mdisj. }\n        { destruct pla as [[[|]|] ? ?], plb as [[[|]|] ? ?];\n          destruct sula as [[|]|[|]], sulb as [[|]|[|]];\n          simpl in *; auto; findeq; try (inv H9; discriminate);\n          try (destruct (M.find a defs); discriminate).\n        }\n        \n      + auto.\n      + auto.\n      + destruct pla as [[[|]|] pdsa pcsa], plb as [[[|]|] pdsb pcsb];\n          destruct sula as [[|]|[[? ?]|]], sulb as [[|]|[[? ?]|]];\n          simpl in *; try (inv H9; discriminate); auto.\n      + destruct pla as [[[|]|] pdsa pcsa], plb as [[[|]|] pdsb pcsb];\n          destruct sula as [[|]|[[? ?]|]], sulb as [[|]|[[? ?]|]];\n          simpl in *; try (inv H9; discriminate); auto.\n      + destruct pla as [[[|]|] ? ?], plb as [[[|]|] ? ?];\n          destruct sula as [[|]|[|]], sulb as [[|]|[|]];\n          simpl in *; try (inv H9; discriminate); auto.\n      + destruct pla as [[[|]|] pdsa pcsa], plb as [[[|]|] pdsb pcsb];\n          destruct sula as [[|]|[[? ?]|]], sulb as [[|]|[[? ?]|]];\n          simpl in *; try (inv H9; discriminate);\n            try (intuition auto; fail);\n            try (f_equal; auto; fail).\n  Qed.\n\n  Definition WellHiddenConcat (ma mb: Modules) (la lb: LabelT) :=\n    wellHidden (ConcatMod ma mb) (hide (mergeLabel la lb)).\n\n  Lemma stepInd_split:\n    forall o u l,\n      StepInd (ConcatMod ma mb) o u l ->\n      exists ua ub la lb,\n        StepInd ma (regsA o) ua la /\\ StepInd mb (regsB o) ub lb /\\\n        M.Disj ua ub /\\ u = M.union ua ub /\\\n        CanCombineLabel la lb /\\ wellHidden (ConcatMod ma mb) (hide (mergeLabel la lb)) /\\\n        WellHiddenConcat ma mb la lb /\\ l = hide (mergeLabel la lb).\n  Proof.\n    induction 1; simpl; intros.\n    pose proof (substepsInd_split HSubSteps)\n      as [ua [ub [la [lb ?]]]]; dest; subst.\n    exists ua, ub, (hide la), (hide lb).\n    intuition auto.\n\n    - constructor; auto.\n      inv H3; dest.\n      pose proof (substepsInd_calls_in HmaEquiv H).\n      pose proof (substepsInd_defs_in H).\n      pose proof (substepsInd_calls_in HmbEquiv H0).\n      pose proof (substepsInd_defs_in H0).\n      eapply wellHidden_split\n      with (ma:= ma) (mb:= mb) (la:= la) (lb:= lb); eauto.\n    - constructor; auto.\n      inv H3; dest.\n      pose proof (substepsInd_calls_in HmaEquiv H).\n      pose proof (substepsInd_defs_in H).\n      pose proof (substepsInd_calls_in HmbEquiv H0).\n      pose proof (substepsInd_defs_in H0).\n      eapply wellHidden_split\n      with (ma:= ma) (mb:= mb) (la:= la) (lb:= lb); eauto.\n    - apply CanCombineLabel_hide; auto.\n    - inv H3; dest.\n      rewrite <-hide_mergeLabel_idempotent; auto.\n    - unfold WellHiddenConcat; intros.\n      inv H3; rewrite <-hide_mergeLabel_idempotent; auto.\n    - inv H3; rewrite <-hide_mergeLabel_idempotent; auto.\n  Qed.\n\n  Lemma step_split:\n    forall o u l,\n      Step (ConcatMod ma mb) o u l ->\n      exists ua ub la lb,\n        Step ma (regsA o) ua la /\\ Step mb (regsB o) ub lb /\\\n        M.Disj ua ub /\\ u = M.union ua ub /\\\n        CanCombineLabel la lb /\\ wellHidden (ConcatMod ma mb) (hide (mergeLabel la lb)) /\\\n        WellHiddenConcat ma mb la lb /\\ l = hide (mergeLabel la lb).\n  Proof.\n    intros; apply step_consistent in H.\n    pose proof (stepInd_split H) as [ua [ub [la [lb ?]]]]; dest; subst.\n    exists ua, ub, la, lb.\n    inv H4; inv H5; dest.\n    repeat split; auto; apply step_consistent; auto.\n  Qed.\n\n  Inductive WellHiddenConcatSeq (ma mb: Modules): LabelSeqT -> LabelSeqT -> Prop :=\n  | WHCSNil: WellHiddenConcatSeq ma mb nil nil\n  | WHCSCons:\n      forall la lb lsa lsb,\n        WellHiddenConcatSeq ma mb lsa lsb ->\n        WellHiddenConcat ma mb la lb ->\n        WellHiddenConcatSeq ma mb (la :: lsa) (lb :: lsb).\n\n  Lemma wellHiddenConcatSeq_length:\n    forall ma mb lsa lsb,\n      WellHiddenConcatSeq ma mb lsa lsb ->\n      List.length lsa = List.length lsb.\n  Proof. induction lsa; intros; inv H; simpl; auto. Qed.\n\n  Lemma multistep_split:\n    forall s ls ir,\n      Multistep (ConcatMod ma mb) ir s ls ->\n      ir = initRegs (getRegInits ma ++ getRegInits mb) ->\n      exists sa lsa sb lsb,\n        Multistep ma (initRegs (getRegInits ma)) sa lsa /\\\n        Multistep mb (initRegs (getRegInits mb)) sb lsb /\\\n        M.Disj sa sb /\\ s = M.union sa sb /\\ \n        CanCombineLabelSeq lsa lsb /\\ WellHiddenConcatSeq ma mb lsa lsb /\\\n        ls = composeLabels lsa lsb.\n  Proof.\n    induction 1; simpl; intros; subst.\n    - do 2 (eexists; exists nil); repeat split; try (econstructor; eauto; fail).\n      + eapply M.DisjList_KeysSubset_Disj with (d1:= namesOf (getRegInits ma)); eauto;\n          unfold initRegs; rewrite rawInitRegs_namesOf;\n            apply makeMap_KeysSubset; auto.\n      + subst; unfold initRegs.\n        rewrite <-makeMap_union.\n        * unfold rawInitRegs; rewrite map_app; auto.\n        * rewrite <- !rawInitRegs_namesOf; auto.\n\n    - intros; subst.\n      specialize (IHMultistep eq_refl).\n      destruct IHMultistep as [sa [lsa [sb [lsb ?]]]]; dest; subst.\n\n      apply step_split in HStep.\n      destruct HStep as [sua [sub [sla [slb ?]]]]; dest; subst.\n\n      inv Hvr.\n      pose proof (validRegsModules_multistep_newregs_subset H8 H0 eq_refl).\n      pose proof (validRegsModules_multistep_newregs_subset H12 H1 eq_refl).\n      pose proof (validRegsModules_step_newregs_subset H8 H3).\n      pose proof (validRegsModules_step_newregs_subset H12 H6).\n\n      inv H9; dest.\n      exists (M.union sua sa), (sla :: lsa).\n      exists (M.union sub sb), (slb :: lsb).\n      repeat split; auto.\n\n      + constructor; auto.\n        p_equal H3.\n        unfold regsA; rewrite M.restrict_union.\n        rewrite M.restrict_KeysSubset; auto.\n        rewrite M.restrict_DisjList with (d1:= namesOf (getRegInits mb)); auto.\n        apply DisjList_comm; auto.\n\n      + constructor; auto.\n        p_equal H6.\n        unfold regsB; rewrite M.restrict_union.\n        rewrite M.restrict_KeysSubset with (m:= sb); auto.\n        rewrite M.restrict_DisjList with (d1:= namesOf (getRegInits ma)); auto.\n\n      + mdisj.\n        * eapply M.DisjList_KeysSubset_Disj with (d1:= namesOf (getRegInits mb)); eauto.\n          apply DisjList_comm; auto.\n        * eapply M.DisjList_KeysSubset_Disj with (d1:= namesOf (getRegInits mb)); eauto.\n          apply DisjList_comm; auto.\n\n      + pose proof (M.DisjList_KeysSubset_Disj Hinit H13 H16).\n        meq.\n\n      + constructor; auto.\n  Qed.\n\n  Lemma behavior_split:\n    forall s ls,\n      Behavior (ConcatMod ma mb) s ls ->\n      exists sa lsa sb lsb,\n        Behavior ma sa lsa /\\ Behavior mb sb lsb /\\\n        M.Disj sa sb /\\ s = M.union sa sb /\\\n        CanCombineLabelSeq lsa lsb /\\ WellHiddenConcatSeq ma mb lsa lsb /\\\n        ls = composeLabels lsa lsb.\n  Proof.\n    induction 1.\n    apply multistep_split in HMultistepBeh.\n    destruct HMultistepBeh as [sa [lsa [sb [lsb ?]]]]; dest; subst.\n    exists sa, lsa, sb, lsb.\n    repeat split; auto.\n    reflexivity.\n  Qed.\n\n  (** Now modular theorem begins *)\n\n  Lemma substepsInd_modular:\n    forall oa ua la,\n      SubstepsInd ma oa ua la ->\n      forall ob ub lb,\n        M.Disj oa ob -> CanCombineUL ua ub la lb ->\n        SubstepsInd mb ob ub lb ->\n        SubstepsInd (ConcatMod ma mb) (M.union oa ob) (M.union ua ub) (mergeLabel la lb).\n  Proof.\n    induction 1; simpl; intros; subst.\n    - destruct lb as [annb dsb csb]; simpl in *.\n      do 3 rewrite M.union_empty_L.\n      apply substepsInd_modules_weakening with (mc:= mb); [|eauto].\n      eapply substepsInd_oldRegs_weakening; eauto.\n      apply M.Sub_union_2; auto.\n    - rewrite mergeLabel_assoc.\n      inv H1; dest.\n      rewrite M.union_comm with (m1:= u); [|auto].\n      eapply SubstepsCons.\n      + eapply IHSubstepsInd; eauto.\n        clear -H5.\n\n        (* Better to extract a lemma *)\n        inv H5; inv H0; dest.\n        destruct (getLabel sul scs), l, lb; simpl in *.\n        repeat split; simpl; auto.\n        destruct annot, annot0, annot1; auto.\n        \n      + apply substep_modules_weakening with (mc:= ma); [|eauto].\n        eapply substep_oldRegs_weakening; eauto.\n        apply M.Sub_union_1.\n      + inv H5; inv H8; dest.\n        destruct l, lb; repeat split; simpl in *; auto.\n        destruct annot, annot0, sul as [|[[? ?]|]]; auto; findeq.\n      + inv H5; inv H8; dest; auto.\n      + reflexivity.\n  Qed.\n\n  Definition WellHiddenModular (ma mb: Modules) (la lb: LabelT) :=\n    ValidLabel ma la ->\n    ValidLabel mb lb ->\n    wellHidden ma (hide la) ->\n    wellHidden mb (hide lb) ->\n    wellHidden (ConcatMod ma mb) (hide (mergeLabel la lb)).\n\n  Inductive WellHiddenModularSeq (ma mb: Modules): LabelSeqT -> LabelSeqT -> Prop :=\n  | WHMSNil: WellHiddenModularSeq ma mb nil nil\n  | WHMSCons:\n      forall la lb lsa lsb,\n        WellHiddenModularSeq ma mb lsa lsb ->\n        WellHiddenModular ma mb la lb ->\n        WellHiddenModularSeq ma mb (la :: lsa) (lb :: lsb).\n\n  Lemma wellHidden_concat_modular:\n    forall ma mb la lb, WellHiddenConcat ma mb la lb ->\n                        WellHiddenModular ma mb la lb.\n  Proof. unfold WellHiddenModular, WellHiddenConcat; intros; auto. Qed.\n\n  Lemma wellHidden_concat_modular_seq:\n    forall ma mb la lb, WellHiddenConcatSeq ma mb la lb ->\n                        WellHiddenModularSeq ma mb la lb.\n  Proof.\n    induction la; intros.\n    - inv H; constructor.\n    - inv H; constructor; auto.\n      apply wellHidden_concat_modular; auto.\n  Qed.\n\n  Lemma validLabel_wellHidden_calls_disj:\n    forall la lb,\n      ValidLabel ma la -> wellHidden ma (hide la) ->\n      ValidLabel mb lb -> wellHidden mb (hide lb) ->\n      M.Disj (calls (hide la)) (calls (hide lb)) ->\n      M.Disj (calls la) (calls lb).\n  Proof.\n    unfold ValidLabel, wellHidden; intros; dest.\n    destruct la as [anna dsa csa], lb as [annb dsb csb].\n    simpl in *.\n    unfold M.Disj, M.KeysDisj, M.KeysSubset in *; intros.\n    specializeAll k.\n    repeat rewrite M.F.P.F.in_find_iff in *.\n    rewrite M.subtractKV_find in H0, H2, H3, H4, H6.\n    rewrite M.subtractKV_find in H3.\n    destruct (M.find k csa); [right|auto].\n    destruct (M.find k csb); [|auto].\n    exfalso.\n    specialize (H5 (opt_discr _)).\n    specialize (H7 (opt_discr _)).\n    destruct (M.find k dsa).\n    1: {\n      specialize (H (opt_discr _)).\n      specialize (Hcalls2 k); destruct Hcalls2.\n      { elim H8.\n        apply filter_In; split; [auto|].\n        apply existsb_exists; exists k.\n        split; [auto|apply StringEq.string_eq_true].\n      }\n      { elim H8; assumption. }\n    }\n\n    destruct (M.find k dsb).\n    1: {\n      specialize (H1 (opt_discr _)).\n      specialize (Hcalls1 k); destruct Hcalls1.\n      { elim H8; assumption. }\n      { elim H8.\n        apply filter_In; split; [auto|].\n        apply existsb_exists; exists k.\n        split; [auto|apply StringEq.string_eq_true].\n      }\n    }\n\n    destruct H3; elim H3; discriminate.\n  Qed.\n\n  Lemma stepInd_modular:\n    forall oa ua la,\n      StepInd ma oa ua la ->\n      forall ob ub lb,\n        M.Disj oa ob -> CanCombineUL ua ub la lb ->\n        WellHiddenModular ma mb la lb ->\n        StepInd mb ob ub lb ->\n        StepInd (ConcatMod ma mb) (M.union oa ob) (M.union ua ub)\n                (hide (mergeLabel la lb)).\n  Proof.\n    intros; inv H; inv H3.\n\n    pose proof (substepsInd_defs_in HSubSteps).\n    pose proof (substepsInd_calls_in HmaEquiv HSubSteps).\n    pose proof (substepsInd_defs_in HSubSteps0).\n    pose proof (substepsInd_calls_in HmbEquiv HSubSteps0).\n\n    inv H1; inv H7; dest.\n    assert (M.Disj (defs l) (defs l0))\n      by (eapply M.DisjList_KeysSubset_Disj with (d1:= getDefs ma); eauto).\n    assert (M.Disj (calls l) (calls l0))\n      by (apply validLabel_wellHidden_calls_disj; auto; try (split; assumption)).\n\n    replace (hide (mergeLabel (hide l) (hide l0))) with (hide (mergeLabel l l0))\n      by (apply hide_mergeLabel_idempotent; auto).\n    constructor.\n    - apply substepsInd_modular; auto.\n      constructor; auto.\n      repeat split; auto.\n    - unfold WellHiddenModular, ValidLabel in H2.\n      rewrite <-hide_mergeLabel_idempotent in H2 by auto.\n      apply H2.\n      + split.\n        * apply M.KeysSubset_Sub with (m2:= defs l); auto.\n          apply M.subtractKV_sub.\n        * apply M.KeysSubset_Sub with (m2:= calls l); auto.\n          apply M.subtractKV_sub.\n      + split.\n        * apply M.KeysSubset_Sub with (m2:= defs l0); auto.\n          apply M.subtractKV_sub.\n        * apply M.KeysSubset_Sub with (m2:= calls l0); auto.\n          apply M.subtractKV_sub.\n      + rewrite <-hide_idempotent; auto.\n      + rewrite <-hide_idempotent; auto.\n  Qed.\n\n  Lemma step_modular:\n    forall oa ua la,\n      Step ma oa ua la ->\n      forall ob ub lb,\n        M.Disj oa ob -> CanCombineUL ua ub la lb ->\n        WellHiddenModular ma mb la lb ->\n        Step mb ob ub lb ->\n        Step (ConcatMod ma mb) (M.union oa ob) (M.union ua ub) (hide (mergeLabel la lb)).\n  Proof.\n    intros.\n    apply step_consistent in H; apply step_consistent in H3.\n    apply step_consistent.\n    apply stepInd_modular; auto.\n  Qed.\n\n  Lemma multistep_modular:\n    forall lsa oa sa,\n      Multistep ma oa sa lsa ->\n      oa = initRegs (getRegInits ma) ->\n      forall ob sb lsb,\n        Multistep mb ob sb lsb ->\n        ob = initRegs (getRegInits mb) ->\n        CanCombineLabelSeq lsa lsb ->\n        WellHiddenModularSeq ma mb lsa lsb ->\n        Multistep (ConcatMod ma mb) (initRegs (getRegInits (ConcatMod ma mb))) \n                  (M.union sa sb) (composeLabels lsa lsb).\n  Proof.\n    induction lsa; simpl; intros; subst.\n\n    - destruct lsb; [|intuition idtac].\n      inv H; inv H1; constructor.\n      unfold initRegs.\n      rewrite <-makeMap_union; auto.\n      + unfold rawInitRegs; rewrite map_app; auto.\n      + rewrite <- !rawInitRegs_namesOf; auto.\n\n    - destruct lsb as [|]; [intuition idtac|].\n      destruct H3; inv H4.\n      inv H; inv H1.\n      pose proof Hvr as Hvr'.\n      inv Hvr'.\n      \n      pose proof (validRegsModules_multistep_newregs_subset H HMultistep eq_refl).\n      pose proof (validRegsModules_multistep_newregs_subset H1 HMultistep0 eq_refl).\n      pose proof (validRegsModules_step_newregs_subset H HStep).\n      pose proof (validRegsModules_step_newregs_subset H1 HStep0).\n\n      replace (M.union (M.union u n) (M.union u0 n0))\n      with (M.union (M.union u u0) (M.union n n0))\n        by (pose proof (M.DisjList_KeysSubset_Disj Hinit H3 H6); meq).\n\n      inv H0; dest.\n      constructor; eauto.\n      apply step_modular; auto.\n      + eapply M.DisjList_KeysSubset_Disj with (d1:= namesOf (getRegInits ma)); eauto.\n      + repeat split; auto.\n        eapply M.DisjList_KeysSubset_Disj with (d1:= namesOf (getRegInits ma)); eauto.\n  Qed.\n\n  Lemma behavior_modular:\n    forall sa sb lsa lsb,\n      Behavior ma sa lsa ->\n      Behavior mb sb lsb ->\n      CanCombineLabelSeq lsa lsb ->\n      WellHiddenModularSeq ma mb lsa lsb ->\n      Behavior (ConcatMod ma mb) (M.union sa sb) (composeLabels lsa lsb).\n  Proof.\n    intros; inv H; inv H0; constructor.\n    eapply multistep_modular; eauto.\n  Qed.\n\nEnd TwoModules.\n", "meta": {"author": "mit-plv", "repo": "kami", "sha": "cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0", "save_path": "github-repos/coq/mit-plv-kami", "path": "github-repos/coq/mit-plv-kami/kami-cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0/Kami/ModularFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22636067265082674}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import compcert.cfrontend.Clight.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Values.\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.common.Smallstep.\n\n\nRequire Import VST.sepcomp.semantics.\nRequire Import VST.sepcomp.event_semantics.\nRequire Import VST.concurrency.common.semantics.\nRequire Import VST.concurrency.common.permissions.\nRequire Import VST.concurrency.compiler.advanced_permissions.\nRequire Import VST.concurrency.compiler.diagrams.\nRequire Import VST.concurrency.lib.tactics.\n\nRequire Import VST.concurrency.compiler.mem_equiv.\nRequire Import VST.concurrency.lib.setoid_help.\nRequire Import Coq.Classes.Morphisms.\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Nested Proofs Allowed.\n\n\n\n(*Self simulations say that a program has equivalent executions \n  in equivalent memories. \n  - Equivalent memories: VISIBLE locations are injected \n    one to one (same values and permissions).\n  - Equivalent executions: the executions have equivalent memories and\n    none visible locations are unchanged (in the execution).  \n *)\n\nSection SelfSim.\n\n  Variable Sem: semantics.\n  \n  (*Separate state and memory*)\n  Variable core: Type.\n  Variable state_to_memcore: state Sem -> (core * Mem.mem).\n  Variable memcore_to_state: core -> Mem.mem -> state Sem.\n  Hypothesis state_to_memcore_correct:\n    forall c m, state_to_memcore (memcore_to_state c m) = (c,m).\n  Hypothesis memcore_to_state_correct: forall s c m,\n   state_to_memcore  s = (c,m) -> s = memcore_to_state c m.\n  \n  \n  (*extension of a mem_injection \n  (slightly stengthens the old inject_separated - LENB: not sure you need the stronger prop*)\n  Definition is_ext (f1:meminj)(nb1: positive)(f2:meminj)(nb2:positive) : Prop:=\n    forall b1 b2 ofs,\n      f2 b1 = Some (b2, ofs) ->\n      f1 b1 = None -> \n      (ofs = 0 /\\ ~ Plt b1 nb1 /\\  ~ Plt b2 nb2).\n  \n  (*The code is also injected*)\n  Variable code_inject: meminj -> core -> core -> Prop.\n  Variable code_inj_incr: forall c1 mu c2 mu',\n      code_inject mu c1 c2 ->\n      inject_incr mu mu' ->\n      code_inject mu' c1 c2.\n  \n  (*The current permisions OF THIS THREAD are unchanged! *)\n  (*This is slightly stronger than Mem.inject/mi_inj which allows\n    permissions to grow (on compilation). *)\n  (*also it could be restricted to take only the Cur permissions*)\n  (*NEVERMIND... BOTH FOLLOW from Mem.inject!*)\n  Definition perm_inject1 (f:meminj)(m1:mem)(m2:mem): Prop:=\n    forall b1 b2 delta,\n      f b1 = Some (b2, delta) ->\n      forall ofs p,\n        Mem.perm m1 b1 (ofs ) Cur p  ->\n        Mem.perm m2 b2 (ofs + delta) Cur p.\n  \n  Definition perm_inject2 (f:meminj)(m1:mem)(m2:mem): Prop:=\n    forall b1 b2 delta,\n      f b1 = Some (b2, delta) ->\n      forall ofs p,\n        Mem.perm m2 b2 (ofs + delta) Cur p ->\n        Mem.perm m1 b1 (ofs ) Cur p \\/ ~ Mem.perm m1 b1 ofs Cur Nonempty.\n\n\n\n  Record match_mem (f: meminj) (m1:mem) (m2:mem): Prop:=\n    { minject: Mem.inject f m1 m2 \n      ; pimage: perm_image f (getCurPerm m1) \n      ; ppreimage: perm_surj f (getCurPerm m1) (getCurPerm m2)\n    }.\n  \n  Instance proper_match_mem:\n    Proper (Logic.eq ==> mem_equiv ==> mem_equiv ==> iff) match_mem.\n  Proof.\n    setoid_help.proper_iff; setoid_help.proper_intros; subst.\n    inversion H2; econstructor.\n    - rewrite <- H1, <- H0; assumption.\n    - pose proof (cur_eqv _ _ H0).\n      unfold Cur_equiv in *.\n      rewrite <- H; assumption.\n    - inv H0; inv H1.\n      unfold Cur_equiv in *.\n      rewrite <- cur_eqv, <- cur_eqv0; assumption.\n  Qed.\n  \n  Record match_self (f: meminj) (c1:core) (m1:mem) (c2:core) (m2:mem): Prop:=\n    { cinject: code_inject f c1 c2\n    ; matchmem: match_mem f m1 m2 \n    }.\n\n\n\n  Lemma all_order_eq:\n    forall a b, (forall p, Mem.perm_order' a p <->  Mem.perm_order' b p) <-> a = b.\n  Proof.\n    clear.\n    intros. destruct a, b; auto.\n    4: tauto.\n    3: { simpl; split; intros; try congruence.\n         specialize (H Nonempty).\n         destruct H as [_ HH].\n         contradict HH. apply perm_any_N. }\n    \n    2: { simpl; split; intros; try congruence.\n         specialize (H Nonempty).\n         destruct H as [ HH _].\n         contradict HH. apply perm_any_N. }\n\n    intros; split.\n    - intros.\n      dup H as H'.\n      specialize (H p ); destruct H as [H _].\n      specialize (H ltac:(simpl; apply perm_refl)).\n      specialize (H' p0); destruct H' as [_ H'].\n      specialize (H' ltac:(simpl; apply perm_refl)).\n      simpl in *.\n      destruct p, p0; inversion H; inversion H'; auto.\n    - intros H; invert H; intros; auto. reflexivity.\n  Qed.\n\n  Lemma match_source_forward:\n    forall mu c1 m1 c2 m2,\n      match_self mu c1 m1 c2 m2 ->\n      forall mu' m1' m2',\n        inject_incr mu mu' ->\n        Mem.inject mu' m1' m2' ->\n        same_visible m1 m1' ->\n        same_visible m2 m2' ->\n        match_self mu' c1 m1' c2 m2'.\n  Proof.\n  intros ? ? ? ? ? MATCH ? ? ? INCR INJ VIS1 VIS2.\n  constructor.\n  - eapply code_inj_incr; eauto; apply MATCH. \n  - inv MATCH.\n    split; trivial.\n    * (*perm_image*) (*Easy ... use lemmas to simplify same_visible*)\n      intros b1 ofs PERM.\n      assert (PERM':Mem.perm m1' b1 ofs Cur Nonempty).\n      { apply at_least_Some_perm_Cur; assumption. }\n      apply VIS1 in PERM'.\n      pose proof (pimage _ _ _ matchmem0 b1 ofs); unfold perm_image in *.\n      apply at_least_Some_perm_Cur in PERM'.\n      eapply H in PERM'; eauto.\n      destruct PERM' as (? & ? & ?).\n      do 2 eexists; eapply INCR; eauto.\n    * (*Pre_image*) (*Easy ... use lemmas to simplify same_visible*)\n      intros b2 ofs_delta PERM.\n      assert (PERM':Mem.perm m2' b2 ofs_delta Cur Nonempty).\n      { apply at_least_Some_perm_Cur; assumption. }\n      apply VIS2 in PERM'.\n      pose proof (ppreimage _ _ _ matchmem0 b2 ofs_delta).\n      apply at_least_Some_perm_Cur in PERM'.\n      eapply H in PERM'; eauto.\n      destruct PERM' as (? & ? & ? & ? & ? & ?).\n      do 3 eexists; repeat split; try eapply INCR; eauto.\n      repeat rewrite getCurPerm_correct in *.\n      repeat unfold permission_at in *.\n      pose proof (same_cur _ _ VIS1 x x0) as HH1.\n      pose proof (same_cur _ _ VIS2 b2 ofs_delta) as HH2.\n      unfold Mem.perm in *.\n      etransitivity. etransitivity.\n      symmetry.\n      1,3: eapply all_order_eq.\n      eapply HH2.\n      eapply HH1.\n      eauto.\n  Qed.\n\nEnd SelfSim.\nArguments match_self {core}.\n\nSection SelfSimulation.\n\n  Variable state:Type.\n  Variable Sem: semantics.CoreSemantics state mem.\n  Variable state_to_memcore: state -> (state * Mem.mem).\n  Variable memcore_to_state: state -> Mem.mem -> state.\n  Notation get_core s:= (fst (state_to_memcore s)). \n  Notation get_mem s:= (snd (state_to_memcore s)). \n\n\n  Import Integers.\n  Import Ptrofs.\n\n  \n  Definition self_preserves_atx_inj {s m} (Sem:semantics.CoreSemantics s m) match_states:=\n    forall (j:meminj) s1 m1 s2 m2,\n      match_states j s1 m1 s2 m2 ->\n      forall f args,\n        at_external Sem s1 m1 = Some (f,args) ->\n        exists args',\n          at_external Sem s2 m2 = Some (f,args') /\\\n          Val.inject_list j args args'.\n  \n Record self_simulation: Type :=\n    { code_inject: meminj -> state -> state -> Prop;\n      code_inj_incr: forall c1 mu c2 mu',\n          code_inject mu c1 c2 ->\n          inject_incr mu mu' ->\n          code_inject mu' c1 c2;\n      ssim_diagram: forall f t c1 m1 c2 m2,\n        match_self code_inject f c1 m1 c2 m2 ->\n        forall c1' m1',\n          semantics.corestep Sem c1 m1  c1' m1' ->\n          exists c2' f' t' m2',\n          semantics.corestep Sem c2 m2  c2' m2'  /\\\n          match_self code_inject f' c1' m1' c2' m2' /\\\n          inject_incr f f' /\\\n          is_ext f (Mem.nextblock m1) f' (Mem.nextblock m2) /\\\n          Events.inject_trace f' t t'\n      ; ssim_external: forall c1 c2 m1 m2 j b1 ofs func_name, \n        code_inject j c1 c2 ->\n        Mem.inject j m1 m2 ->\n        semantics.at_external Sem c1 m1  =  \n        Some (func_name, Vptr b1 ofs :: nil) ->\n        exists b2 delt,\n        j b1 = Some (b2, delt) /\\\n        semantics.at_external Sem c2 m2 =  \n        Some (func_name, Vptr b2 (add ofs (repr delt)) :: nil)\n      ; ssim_preserves_atx:\n          self_preserves_atx_inj Sem (match_self code_inject)\n    }. \n\n \nEnd SelfSimulation. \n\n\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/concurrency/compiler/self_simulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.22631842207536573}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\n\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Values.\n\nRequire Import VST.sepcomp.extspec.\nRequire Import VST.sepcomp.semantics.\nRequire Import VST.sepcomp.semantics_lemmas.\n\nDefinition has_opttyp (v : option val) (t : option typ) :=\n  match v, t with\n    None, None => True\n  | Some v, Some t => Val.has_type v t\n  | _, _ => False\n  end.\n\nSection safety.\n  Context {G C M Z:Type}.\n  Context {genv_symb: G -> PTree.t block}.\n  Context {Hrel: nat -> M -> M -> Prop}.\n  Context (Hcore:@CoreSemantics G C M).\n  Variable (Hspec:external_specification M external_function Z).\n\n  Variable ge : G.\n\n  Inductive safeN_ : nat -> Z -> C -> M -> Prop :=\n  | safeN_0: forall z c m, safeN_ O z c m\n  | safeN_step:\n      forall n z c m c' m',\n      corestep Hcore ge c m c' m' ->\n      safeN_ n z c' m' ->\n      safeN_ (S n) z c m\n  | safeN_external:\n      forall n z c m e args x,\n      at_external Hcore c = Some (e,args) ->\n      ext_spec_pre Hspec e x (genv_symb ge) (sig_args (ef_sig e)) args z m ->\n      (forall ret m' z' n'\n         (Hargsty : Val.has_type_list args (sig_args (ef_sig e)))\n         (Hretty : has_opttyp ret (sig_res (ef_sig e))),\n         (n' <= n)%nat ->\n         Hrel n' m m' ->\n         ext_spec_post Hspec e x (genv_symb ge) (sig_res (ef_sig e)) ret z' m' ->\n         exists c',\n           after_external Hcore ret c = Some c' /\\\n           safeN_ n' z' c' m') ->\n      safeN_ (S n) z c m\n  | safeN_halted:\n      forall n z c m i,\n      halted Hcore c = Some i ->\n      ext_spec_exit Hspec (Some i) z m ->\n      safeN_ n z c m.\n\n  Definition corestep_fun  :=\n       forall ge m q m1 q1 m2 q2 ,\n       corestep Hcore ge q m q1 m1 ->\n       corestep Hcore ge q m q2 m2 ->\n       (q1, m1) = (q2, m2).\n\n  Lemma safe_corestep_forward:\n     corestep_fun ->\n    forall c m c' m' n z,\n    corestep Hcore ge c m c' m' -> safeN_ (S n) z c m -> safeN_ n z c' m'.\n  Proof.\n    simpl; intros; inv H1.\n    assert ((c',m') = (c'0,m'0)) by (eapply H; eauto).\n    inv H1; auto.\n    erewrite corestep_not_at_external in H3; eauto; congruence.\n    erewrite corestep_not_halted in H2; eauto; congruence.\n  Qed.\n\n  Lemma safe_corestep_backward:\n    forall c m c' m' n z,\n    corestep Hcore ge c m c' m' -> safeN_ n z c' m' -> safeN_ (S n) z c m.\n  Proof.\n    intros; eapply safeN_step; eauto.\n  Qed.\n\n  Lemma safe_downward1 :\n    forall n c m z,\n      safeN_ (S n) z c m -> safeN_ n z c m.\n  Proof.\n    induction n. econstructor; eauto.\n    intros c m z H. inv H.\n    + econstructor; eauto.\n    + eapply safeN_external; eauto.\n    + eapply safeN_halted; eauto.\n  Qed.\n\n  Lemma safe_downward :\n    forall n n' c m z,\n      le n' n ->\n      safeN_ n z c m -> safeN_ n' z c m.\n  Proof.\n    do 6 intro. revert c m z. induction H; auto.\n    intros. apply IHle. apply safe_downward1. auto.\n  Qed.\n\n  Lemma safe_corestepN_forward:\n    corestep_fun ->\n    forall z c m c' m' n n0,\n      corestepN Hcore ge n0 c m c' m' ->\n      safeN_ (n + S n0) z c m ->\n      safeN_ n z c' m'.\n  Proof.\n    intros.\n    revert c m c' m' n H0 H1.\n    induction n0; intros; auto.\n    simpl in H0; inv H0.\n    eapply safe_downward in H1; eauto. omega.\n    simpl in H0. destruct H0 as [c2 [m2 [STEP STEPN]]].\n    apply (IHn0 _ _ _ _ n STEPN).\n    assert (Heq: (n + S (S n0) = S (n + S n0))%nat) by omega.\n    rewrite Heq in H1.\n    eapply safe_corestep_forward in H1; eauto.\n  Qed.\n\n  Lemma safe_step'_back2 :\n    forall\n      {ora st m st' m' n},\n      corestep Hcore ge st m st' m' ->\n      safeN_ (n-1) ora st' m' ->\n      safeN_ n ora st m.\n  Proof.\n    intros.\n    destruct n.\n    constructor.\n    simpl in H0. replace (n-0)%nat with n in H0.\n    eapply safe_corestep_backward; eauto.\n    omega.\n  Qed.\n\n  Lemma safe_corestepN_backward:\n    forall z c m c' m' n n0,\n      corestepN Hcore ge n0 c m c' m' ->\n      safeN_ (n - n0) z c' m' ->\n      safeN_ n z c m.\n  Proof.\n    simpl; intros.\n    revert c m c' m' n H H0.\n    induction n0; intros; auto.\n    simpl in H; inv H.\n    solve[assert (Heq: (n = n - 0)%nat) by omega; rewrite Heq; auto].\n    simpl in H. destruct H as [c2 [m2 [STEP STEPN]]].\n    assert (H: safeN_ (n - 1 - n0) z c' m').\n    eapply safe_downward in H0; eauto. omega.\n    specialize (IHn0 _ _ _ _ (n - 1)%nat STEPN H).\n    solve[eapply safe_step'_back2; eauto].\n  Qed.\n\n  Lemma convergent_controls_safe :\n    forall m q1 q2,\n      (at_external Hcore q1 = at_external Hcore q2) ->\n      (forall ret q', after_external Hcore ret q1 = Some q' ->\n                      after_external Hcore ret q2 = Some q') ->\n      (halted Hcore q1 = halted Hcore q2) ->\n      (forall q' m', corestep Hcore ge q1 m q' m' ->\n                     corestep Hcore ge q2 m q' m') ->\n      (forall n z, safeN_ n z q1 m -> safeN_ n z q2 m).\n  Proof.\n    intros. destruct n; simpl in *; try constructor.\n    inv H3.\n    + econstructor; eauto.\n    + eapply safeN_external; eauto.\n      rewrite <-H; auto.\n      intros ???? Hargsty Hretty ? H8 H9.\n      specialize (H7 _ _ _ _ Hargsty Hretty H3 H8 H9).\n      destruct H7 as [c' [? ?]].\n      exists c'; split; auto.\n    + eapply safeN_halted; eauto.\n      rewrite <-H1; auto.\n  Qed.\n\n  Lemma wlog_safeN_gt0 : forall\n    n z q m,\n    (lt 0 n -> safeN_ n z q m) ->\n    safeN_ n z q m.\n  Proof.\n    intros. destruct n. constructor.\n    apply H. omega.\n  Qed.\n\nEnd safety.\n\nSection dry_safety.\n  Context {G C M Z:Type}.\n  Context {genv_symb: G -> PTree.t block}.\n  Context (Hcore:@CoreSemantics G C M).\n  Variable (Hspec:external_specification M external_function Z).\n  Definition dry_safeN := @safeN_ G C M Z genv_symb (fun n' m m' => True) Hcore Hspec.\nEnd dry_safety.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/sepcomp/step_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22630079339209555}}
{"text": "From iris.proofmode Require Import base tactics classes.\nFrom iris.base_logic.lib Require Export fancy_updates.\nFrom iris.program_logic Require Export language.\n(* FIXME: If we import iris.bi.weakestpre earlier texan triples do not\n   get pretty-printed correctly. *)\nFrom iris.bi Require Export weakestpre.\nFrom iris.prelude Require Import options.\nImport uPred.\n\nClass irisG (Λ : language) (Σ : gFunctors) := IrisG {\n  iris_invG :> invG Σ;\n\n  (** The state interpretation is an invariant that should hold in between each\n  step of reduction. Here [Λstate] is the global state, [list Λobservation] are\n  the remaining observations, and [nat] is the number of forked-off threads\n  (not the total number of threads, which is one higher because there is always\n  a main thread). *)\n  state_interp : state Λ → list (observation Λ) → nat → iProp Σ;\n\n  (** A fixed postcondition for any forked-off thread. For most languages, e.g.\n  heap_lang, this will simply be [True]. However, it is useful if one wants to\n  keep track of resources precisely, as in e.g. Iron. *)\n  fork_post : val Λ → iProp Σ;\n}.\nGlobal Opaque iris_invG.\n\nDefinition wp_pre `{!irisG Λ Σ} (s : stuckness)\n    (wp : coPset -d> expr Λ -d> (val Λ -d> iPropO Σ) -d> iPropO Σ) :\n    coPset -d> expr Λ -d> (val Λ -d> iPropO Σ) -d> iPropO Σ := λ E e1 Φ,\n  match to_val e1 with\n  | Some v => |={E}=> Φ v\n  | None => ∀ σ1 κ κs n,\n     state_interp σ1 (κ ++ κs) n ={E,∅}=∗\n       ⌜if s is NotStuck then reducible e1 σ1 else True⌝ ∗\n       ∀ e2 σ2 efs, ⌜prim_step e1 σ1 κ e2 σ2 efs⌝ ={∅}=∗ ▷ |={∅,E}=>\n         state_interp σ2 κs (length efs + n) ∗\n         wp E e2 Φ ∗\n         [∗ list] i ↦ ef ∈ efs, wp ⊤ ef fork_post\n  end%I.\n\nLocal Instance wp_pre_contractive `{!irisG Λ Σ} s : Contractive (wp_pre s).\nProof.\n  rewrite /wp_pre=> n wp wp' Hwp E e1 Φ.\n  repeat (f_contractive || f_equiv); apply Hwp.\nQed.\n\nDefinition wp_def `{!irisG Λ Σ} : Wp Λ (iProp Σ) stuckness :=\n  λ s : stuckness, fixpoint (wp_pre s).\nDefinition wp_aux : seal (@wp_def). Proof. by eexists. Qed.\nDefinition wp' := wp_aux.(unseal).\nGlobal Arguments wp' {Λ Σ _}.\nExisting Instance wp'.\nLemma wp_eq `{!irisG Λ Σ} : wp = @wp_def Λ Σ _.\nProof. rewrite -wp_aux.(seal_eq) //. Qed.\n\nSection wp.\nContext `{!irisG Λ Σ}.\nImplicit Types s : stuckness.\nImplicit Types P : iProp Σ.\nImplicit Types Φ : val Λ → iProp Σ.\nImplicit Types v : val Λ.\nImplicit Types e : expr Λ.\n\n(* Weakest pre *)\nLemma wp_unfold s E e Φ :\n  WP e @ s; E {{ Φ }} ⊣⊢ wp_pre s (wp (PROP:=iProp Σ) s) E e Φ.\nProof. rewrite wp_eq. apply (fixpoint_unfold (wp_pre s)). Qed.\n\nGlobal Instance wp_ne s E e n :\n  Proper (pointwise_relation _ (dist n) ==> dist n) (wp (PROP:=iProp Σ) s E e).\nProof.\n  revert e. induction (lt_wf n) as [n _ IH]=> e Φ Ψ HΦ.\n  rewrite !wp_unfold /wp_pre.\n  (* FIXME: figure out a way to properly automate this proof *)\n  (* FIXME: reflexivity, as being called many times by f_equiv and f_contractive\n  is very slow here *)\n  do 24 (f_contractive || f_equiv). apply IH; first lia.\n  intros v. eapply dist_le; eauto with lia.\nQed.\nGlobal Instance wp_proper s E e :\n  Proper (pointwise_relation _ (≡) ==> (≡)) (wp (PROP:=iProp Σ) s E e).\nProof.\n  by intros Φ Φ' ?; apply equiv_dist=>n; apply wp_ne=>v; apply equiv_dist.\nQed.\nGlobal Instance wp_contractive s E e n :\n  TCEq (to_val e) None →\n  Proper (pointwise_relation _ (dist_later n) ==> dist n) (wp (PROP:=iProp Σ) s E e).\nProof.\n  intros He Φ Ψ HΦ. rewrite !wp_unfold /wp_pre He.\n  by repeat (f_contractive || f_equiv).\nQed.\n\nLemma wp_value_fupd' s E Φ v : WP of_val v @ s; E {{ Φ }} ⊣⊢ |={E}=> Φ v.\nProof. rewrite wp_unfold /wp_pre to_of_val. auto. Qed.\n\nLemma wp_strong_mono s1 s2 E1 E2 e Φ Ψ :\n  s1 ⊑ s2 → E1 ⊆ E2 →\n  WP e @ s1; E1 {{ Φ }} -∗ (∀ v, Φ v ={E2}=∗ Ψ v) -∗ WP e @ s2; E2 {{ Ψ }}.\nProof.\n  iIntros (? HE) \"H HΦ\". iLöb as \"IH\" forall (e E1 E2 HE Φ Ψ).\n  rewrite !wp_unfold /wp_pre.\n  destruct (to_val e) as [v|] eqn:?.\n  { iApply (\"HΦ\" with \"[> -]\"). by iApply (fupd_mask_mono E1 _). }\n  iIntros (σ1 κ κs n) \"Hσ\". iMod (fupd_intro_mask' E2 E1) as \"Hclose\"; first done.\n  iMod (\"H\" with \"[$]\") as \"[% H]\".\n  iModIntro. iSplit; [by destruct s1, s2|]. iIntros (e2 σ2 efs Hstep).\n  iMod (\"H\" with \"[//]\") as \"H\". iIntros \"!> !>\".\n  iMod \"H\" as \"(Hσ & H & Hefs)\".\n  iMod \"Hclose\" as \"_\". iModIntro. iFrame \"Hσ\". iSplitR \"Hefs\".\n  - iApply (\"IH\" with \"[//] H HΦ\").\n  - iApply (big_sepL_impl with \"Hefs\"); iIntros \"!>\" (k ef _).\n    iIntros \"H\". iApply (\"IH\" with \"[] H\"); auto.\nQed.\n\nLemma fupd_wp s E e Φ : (|={E}=> WP e @ s; E {{ Φ }}) ⊢ WP e @ s; E {{ Φ }}.\nProof.\n  rewrite wp_unfold /wp_pre. iIntros \"H\". destruct (to_val e) as [v|] eqn:?.\n  { by iMod \"H\". }\n  iIntros (σ1 κ κs n) \"Hσ1\". iMod \"H\". by iApply \"H\".\nQed.\nLemma wp_fupd s E e Φ : WP e @ s; E {{ v, |={E}=> Φ v }} ⊢ WP e @ s; E {{ Φ }}.\nProof. iIntros \"H\". iApply (wp_strong_mono s s E with \"H\"); auto. Qed.\n\nLemma wp_atomic s E1 E2 e Φ `{!Atomic (stuckness_to_atomicity s) e} :\n  (|={E1,E2}=> WP e @ s; E2 {{ v, |={E2,E1}=> Φ v }}) ⊢ WP e @ s; E1 {{ Φ }}.\nProof.\n  iIntros \"H\". rewrite !wp_unfold /wp_pre.\n  destruct (to_val e) as [v|] eqn:He.\n  { by iDestruct \"H\" as \">>> $\". }\n  iIntros (σ1 κ κs n) \"Hσ\". iMod \"H\". iMod (\"H\" $! σ1 with \"Hσ\") as \"[$ H]\".\n  iModIntro. iIntros (e2 σ2 efs Hstep).\n  iMod (\"H\" with \"[//]\") as \"H\". iIntros \"!>!>\".\n  iMod \"H\" as \"(Hσ & H & Hefs)\". destruct s.\n  - rewrite !wp_unfold /wp_pre. destruct (to_val e2) as [v2|] eqn:He2.\n    + iDestruct \"H\" as \">> $\". by iFrame.\n    + iMod (\"H\" $! _ [] with \"[$]\") as \"[H _]\". iDestruct \"H\" as %(? & ? & ? & ? & ?).\n      by edestruct (atomic _ _ _ _ _ Hstep).\n  - destruct (atomic _ _ _ _ _ Hstep) as [v <-%of_to_val].\n    rewrite wp_value_fupd'. iMod \"H\" as \">H\".\n    iModIntro. iFrame \"Hσ Hefs\". by iApply wp_value_fupd'.\nQed.\n\nLemma wp_step_fupd s E1 E2 e P Φ :\n  TCEq (to_val e) None → E2 ⊆ E1 →\n  (|={E1}[E2]▷=> P) -∗ WP e @ s; E2 {{ v, P ={E1}=∗ Φ v }} -∗ WP e @ s; E1 {{ Φ }}.\nProof.\n  rewrite !wp_unfold /wp_pre. iIntros (-> ?) \"HR H\".\n  iIntros (σ1 κ κs n) \"Hσ\". iMod \"HR\". iMod (\"H\" with \"[$]\") as \"[$ H]\".\n  iIntros \"!>\" (e2 σ2 efs Hstep). iMod (\"H\" $! e2 σ2 efs with \"[% //]\") as \"H\".\n  iIntros \"!>!>\". iMod \"H\" as \"(Hσ & H & Hefs)\".\n  iMod \"HR\". iModIntro. iFrame \"Hσ Hefs\".\n  iApply (wp_strong_mono s s E2 with \"H\"); [done..|].\n  iIntros (v) \"H\". by iApply \"H\".\nQed.\n\nLemma wp_bind K `{!LanguageCtx K} s E e Φ :\n  WP e @ s; E {{ v, WP K (of_val v) @ s; E {{ Φ }} }} ⊢ WP K e @ s; E {{ Φ }}.\nProof.\n  iIntros \"H\". iLöb as \"IH\" forall (E e Φ). rewrite wp_unfold /wp_pre.\n  destruct (to_val e) as [v|] eqn:He.\n  { apply of_to_val in He as <-. by iApply fupd_wp. }\n  rewrite wp_unfold /wp_pre fill_not_val //.\n  iIntros (σ1 κ κs n) \"Hσ\". iMod (\"H\" with \"[$]\") as \"[% H]\". iModIntro; iSplit.\n  { destruct s; eauto using reducible_fill. }\n  iIntros (e2 σ2 efs Hstep).\n  destruct (fill_step_inv e σ1 κ e2 σ2 efs) as (e2'&->&?); auto.\n  iMod (\"H\" $! e2' σ2 efs with \"[//]\") as \"H\". iIntros \"!>!>\".\n  iMod \"H\" as \"(Hσ & H & Hefs)\".\n  iModIntro. iFrame \"Hσ Hefs\". by iApply \"IH\".\nQed.\n\nLemma wp_bind_inv K `{!LanguageCtx K} s E e Φ :\n  WP K e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ v, WP K (of_val v) @ s; E {{ Φ }} }}.\nProof.\n  iIntros \"H\". iLöb as \"IH\" forall (E e Φ). rewrite !wp_unfold /wp_pre.\n  destruct (to_val e) as [v|] eqn:He.\n  { apply of_to_val in He as <-. by rewrite !wp_unfold /wp_pre. }\n  rewrite fill_not_val //.\n  iIntros (σ1 κ κs n) \"Hσ\". iMod (\"H\" with \"[$]\") as \"[% H]\". iModIntro; iSplit.\n  { destruct s; eauto using reducible_fill_inv. }\n  iIntros (e2 σ2 efs Hstep).\n  iMod (\"H\" $! (K e2) σ2 efs with \"[]\") as \"H\"; [by eauto using fill_step|].\n  iIntros \"!>!>\". iMod \"H\" as \"(Hσ & H & Hefs)\".\n  iModIntro. iFrame \"Hσ Hefs\". by iApply \"IH\".\nQed.\n\n(** * Derived rules *)\nLemma wp_mono s E e Φ Ψ : (∀ v, Φ v ⊢ Ψ v) → WP e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ Ψ }}.\nProof.\n  iIntros (HΦ) \"H\"; iApply (wp_strong_mono with \"H\"); auto.\n  iIntros (v) \"?\". by iApply HΦ.\nQed.\nLemma wp_stuck_mono s1 s2 E e Φ :\n  s1 ⊑ s2 → WP e @ s1; E {{ Φ }} ⊢ WP e @ s2; E {{ Φ }}.\nProof. iIntros (?) \"H\". iApply (wp_strong_mono with \"H\"); auto. Qed.\nLemma wp_stuck_weaken s E e Φ :\n  WP e @ s; E {{ Φ }} ⊢ WP e @ E ?{{ Φ }}.\nProof. apply wp_stuck_mono. by destruct s. Qed.\nLemma wp_mask_mono s E1 E2 e Φ : E1 ⊆ E2 → WP e @ s; E1 {{ Φ }} ⊢ WP e @ s; E2 {{ Φ }}.\nProof. iIntros (?) \"H\"; iApply (wp_strong_mono with \"H\"); auto. Qed.\nGlobal Instance wp_mono' s E e :\n  Proper (pointwise_relation _ (⊢) ==> (⊢)) (wp (PROP:=iProp Σ) s E e).\nProof. by intros Φ Φ' ?; apply wp_mono. Qed.\nGlobal Instance wp_flip_mono' s E e :\n  Proper (pointwise_relation _ (flip (⊢)) ==> (flip (⊢))) (wp (PROP:=iProp Σ) s E e).\nProof. by intros Φ Φ' ?; apply wp_mono. Qed.\n\nLemma wp_value_fupd s E Φ e v : IntoVal e v → WP e @ s; E {{ Φ }} ⊣⊢ |={E}=> Φ v.\nProof. intros <-. by apply wp_value_fupd'. Qed.\nLemma wp_value' s E Φ v : Φ v ⊢ WP (of_val v) @ s; E {{ Φ }}.\nProof. rewrite wp_value_fupd'. auto. Qed.\nLemma wp_value s E Φ e v : IntoVal e v → Φ v ⊢ WP e @ s; E {{ Φ }}.\nProof. intros <-. apply wp_value'. Qed.\n\nLemma wp_frame_l s E e Φ R : R ∗ WP e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ v, R ∗ Φ v }}.\nProof. iIntros \"[? H]\". iApply (wp_strong_mono with \"H\"); auto with iFrame. Qed.\nLemma wp_frame_r s E e Φ R : WP e @ s; E {{ Φ }} ∗ R ⊢ WP e @ s; E {{ v, Φ v ∗ R }}.\nProof. iIntros \"[H ?]\". iApply (wp_strong_mono with \"H\"); auto with iFrame. Qed.\n\nLemma wp_frame_step_l s E1 E2 e Φ R :\n  TCEq (to_val e) None → E2 ⊆ E1 →\n  (|={E1}[E2]▷=> R) ∗ WP e @ s; E2 {{ Φ }} ⊢ WP e @ s; E1 {{ v, R ∗ Φ v }}.\nProof.\n  iIntros (??) \"[Hu Hwp]\". iApply (wp_step_fupd with \"Hu\"); try done.\n  iApply (wp_mono with \"Hwp\"). by iIntros (?) \"$$\".\nQed.\nLemma wp_frame_step_r s E1 E2 e Φ R :\n  TCEq (to_val e) None → E2 ⊆ E1 →\n  WP e @ s; E2 {{ Φ }} ∗ (|={E1}[E2]▷=> R) ⊢ WP e @ s; E1 {{ v, Φ v ∗ R }}.\nProof.\n  rewrite [(WP _ @ _; _ {{ _ }} ∗ _)%I]comm; setoid_rewrite (comm _ _ R).\n  apply wp_frame_step_l.\nQed.\nLemma wp_frame_step_l' s E e Φ R :\n  TCEq (to_val e) None → ▷ R ∗ WP e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ v, R ∗ Φ v }}.\nProof. iIntros (?) \"[??]\". iApply (wp_frame_step_l s E E); try iFrame; eauto. Qed.\nLemma wp_frame_step_r' s E e Φ R :\n  TCEq (to_val e) None → WP e @ s; E {{ Φ }} ∗ ▷ R ⊢ WP e @ s; E {{ v, Φ v ∗ R }}.\nProof. iIntros (?) \"[??]\". iApply (wp_frame_step_r s E E); try iFrame; eauto. Qed.\n\nLemma wp_wand s E e Φ Ψ :\n  WP e @ s; E {{ Φ }} -∗ (∀ v, Φ v -∗ Ψ v) -∗ WP e @ s; E {{ Ψ }}.\nProof.\n  iIntros \"Hwp H\". iApply (wp_strong_mono with \"Hwp\"); auto.\n  iIntros (?) \"?\". by iApply \"H\".\nQed.\nLemma wp_wand_l s E e Φ Ψ :\n  (∀ v, Φ v -∗ Ψ v) ∗ WP e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ Ψ }}.\nProof. iIntros \"[H Hwp]\". iApply (wp_wand with \"Hwp H\"). Qed.\nLemma wp_wand_r s E e Φ Ψ :\n  WP e @ s; E {{ Φ }} ∗ (∀ v, Φ v -∗ Ψ v) ⊢ WP e @ s; E {{ Ψ }}.\nProof. iIntros \"[Hwp H]\". iApply (wp_wand with \"Hwp H\"). Qed.\nLemma wp_frame_wand_l s E e Q Φ :\n  Q ∗ WP e @ s; E {{ v, Q -∗ Φ v }} -∗ WP e @ s; E {{ Φ }}.\nProof.\n  iIntros \"[HQ HWP]\". iApply (wp_wand with \"HWP\").\n  iIntros (v) \"HΦ\". by iApply \"HΦ\".\nQed.\n\nEnd wp.\n\n(** Proofmode class instances *)\nSection proofmode_classes.\n  Context `{!irisG Λ Σ}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types Φ : val Λ → iProp Σ.\n\n  Global Instance frame_wp p s E e R Φ Ψ :\n    (∀ v, Frame p R (Φ v) (Ψ v)) →\n    Frame p R (WP e @ s; E {{ Φ }}) (WP e @ s; E {{ Ψ }}).\n  Proof. rewrite /Frame=> HR. rewrite wp_frame_l. apply wp_mono, HR. Qed.\n\n  Global Instance is_except_0_wp s E e Φ : IsExcept0 (WP e @ s; E {{ Φ }}).\n  Proof. by rewrite /IsExcept0 -{2}fupd_wp -except_0_fupd -fupd_intro. Qed.\n\n  Global Instance elim_modal_bupd_wp p s E e P Φ :\n    ElimModal True p false (|==> P) P (WP e @ s; E {{ Φ }}) (WP e @ s; E {{ Φ }}).\n  Proof.\n    by rewrite /ElimModal intuitionistically_if_elim\n      (bupd_fupd E) fupd_frame_r wand_elim_r fupd_wp.\n  Qed.\n\n  Global Instance elim_modal_fupd_wp p s E e P Φ :\n    ElimModal True p false (|={E}=> P) P (WP e @ s; E {{ Φ }}) (WP e @ s; E {{ Φ }}).\n  Proof.\n    by rewrite /ElimModal intuitionistically_if_elim\n      fupd_frame_r wand_elim_r fupd_wp.\n  Qed.\n\n  Global Instance elim_modal_fupd_wp_atomic p s E1 E2 e P Φ :\n    ElimModal (Atomic (stuckness_to_atomicity s) e) p false\n            (|={E1,E2}=> P) P\n            (WP e @ s; E1 {{ Φ }}) (WP e @ s; E2 {{ v, |={E2,E1}=> Φ v }})%I | 100.\n  Proof.\n    intros ?. by rewrite intuitionistically_if_elim\n      fupd_frame_r wand_elim_r wp_atomic.\n  Qed.\n\n  Global Instance add_modal_fupd_wp s E e P Φ :\n    AddModal (|={E}=> P) P (WP e @ s; E {{ Φ }}).\n  Proof. by rewrite /AddModal fupd_frame_r wand_elim_r fupd_wp. Qed.\n\n  Global Instance elim_acc_wp_atomic {X} E1 E2 α β γ e s Φ :\n    ElimAcc (X:=X) (Atomic (stuckness_to_atomicity s) e)\n            (fupd E1 E2) (fupd E2 E1)\n            α β γ (WP e @ s; E1 {{ Φ }})\n            (λ x, WP e @ s; E2 {{ v, |={E2}=> β x ∗ (γ x -∗? Φ v) }})%I | 100.\n  Proof.\n    iIntros (?) \"Hinner >Hacc\". iDestruct \"Hacc\" as (x) \"[Hα Hclose]\".\n    iApply (wp_wand with \"(Hinner Hα)\").\n    iIntros (v) \">[Hβ HΦ]\". iApply \"HΦ\". by iApply \"Hclose\".\n  Qed.\n\n  Global Instance elim_acc_wp_nonatomic {X} E α β γ e s Φ :\n    ElimAcc (X:=X) True (fupd E E) (fupd E E)\n            α β γ (WP e @ s; E {{ Φ }})\n            (λ x, WP e @ s; E {{ v, |={E}=> β x ∗ (γ x -∗? Φ v) }})%I.\n  Proof.\n    iIntros (_) \"Hinner >Hacc\". iDestruct \"Hacc\" as (x) \"[Hα Hclose]\".\n    iApply wp_fupd.\n    iApply (wp_wand with \"(Hinner Hα)\").\n    iIntros (v) \">[Hβ HΦ]\". iApply \"HΦ\". by iApply \"Hclose\".\n  Qed.\nEnd proofmode_classes.\n", "meta": {"author": "gares", "repo": "iris", "sha": "7b4a04ce0d396cb27eeef22e883a9f3b738e83f4", "save_path": "github-repos/coq/gares-iris", "path": "github-repos/coq/gares-iris/iris-7b4a04ce0d396cb27eeef22e883a9f3b738e83f4/iris/program_logic/weakestpre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2262451904171794}}
{"text": "(** 依存関数型のモジュールです。 *)\n\nRequire Googology_In_Coq.Base.\n\n(** ライブラリを要求します。 *)\n\nImport Googology_In_Coq.Base.\n\n(** ライブラリを開きます。 *)\n\nDefinition Dependent_Function@{ i | } ( A : Type@{ i } ) ( B : A -> Type@{ i } ) : Type@{ i } := forall x : A, B x.\n(* from: originally defined by Hexirp *)\n\n(** 依存関数型です。 *)\n\nDefinition map_Dependent_Function@{ i j k l | } ( A : Type@{ i } ) ( B : A -> Type@{ j } ) ( C : Type@{ k } ) ( D : C -> Type@{ l } ) ( f : C -> A ) ( g : forall x : C, B ( f x ) -> D x ) ( x : forall a : A, B a ) : forall c : C, D c := fun y : C => g y ( x ( f y ) ).\n(* from: originally defined by Hexirp *)\n\n(** 依存関数型から依存関数への写像です。 *)\n", "meta": {"author": "Hexirp", "repo": "googology-in-coq", "sha": "1af9f44f798548a269b300d8e2990b14a2b1660c", "save_path": "github-repos/coq/Hexirp-googology-in-coq", "path": "github-repos/coq/Hexirp-googology-in-coq/googology-in-coq-1af9f44f798548a269b300d8e2990b14a2b1660c/libraries/theories/Dependent_Function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22624518377989256}}
{"text": "(*========================================================================*)\n(*                                                                        *)\n(*                    CompcertTSO                                         *)\n(*                                                                        *)\n(*          Jaroslav Sevcik, University of Cambridge                      *)\n(*          Viktor Vafeiadis, University of Cambridge                     *)\n(*          Francesco Zappa Nardelli, INRIA Rocquencourt                  *)\n(*          Suresh Jagannathan, Purdue University                         *)\n(*          Peter Sewell, University of Cambridge                         *)\n(*                                                                        *)\n(*          (building on CompCert 1.5 and a 1.8 pre-release)              *)\n(*                                                                        *)\n(*  This document and the CompCertTSO sources are copyright 2005, 2006,   *)\n(*  2007, 2008, 2009, 2010, 2011 Institut National de Recherche en        *)\n(*  Informatique et en Automatique (INRIA), and Suresh Jagannathan,       *)\n(*  Jaroslav Sevcik, Peter Sewell and Viktor Vafeiadis.                   *)\n(*                                                                        *)\n(*  All rights reserved.  This file is distributed under the terms of     *)\n(*  the INRIA Non-Commercial License Agreement.                           *)\n(*                                                                        *)\n(*                                                                        *)\n(*                                                                        *)\n(*                                                                        *)\n(*                                                                        *)\n(*========================================================================*)\n\n\nRequire Import Coqlib.\nRequire Import Integers.\n\n(** pointers are block-id--offset pairs. *)\nInductive pointer : Type :=\n  | Ptr : Z -> int -> pointer.\n\nDefinition nullptr := Ptr 0 Int.zero.\n\nModule MPtr.\n\nDefinition block (p : pointer) : Z :=\n  match p with\n  | Ptr b off => b\n  end. \n\nDefinition offset (p : pointer) : int :=\n  match p with\n  | Ptr b off => off\n  end. \n\nDefinition add (p : pointer) (i : int) : pointer :=\n  match p with\n  | Ptr b off => Ptr b (Int.add off i)\n  end.\n\nDefinition sub_int (p : pointer) (i : int) : pointer :=\n  match p with\n  | Ptr b off => Ptr b (Int.sub off i)\n  end.\n\nDefinition sub_ptr (p1 p2 : pointer) : option int :=\n  match p1, p2 with\n  | Ptr b1 off1, Ptr b2 off2 => \n    if zeq b1 b2\n      then Some(Int.sub off1 off2)\n      else None\n  end.\n\nDefinition eq_dec (p q : pointer) : { p = q } + {p <> q}.\nProof.\n  decide equality. apply Int.eq_dec. apply Z_eq_dec.\nDefined.\n\nDefinition eq (p q : pointer) : bool :=\n  if (eq_dec p q) then true else false.\n\nLemma eq_true:\n  forall (A: Type) (x: pointer) (a b: A), (if eq x x then a else b) = a.\nProof.\n  by intros; unfold eq; case eq_dec.\nQed.\n\nLemma eq_false:\n  forall (A: Type) (x y: pointer) (a b: A), \n    x <> y -> (if eq x y then a else b) = b.\nProof.\n  by intros; unfold eq; case eq_dec.\nQed.\n\nLemma eq_sym:\n  forall x y, eq x y = eq y x.\nProof.\n  intros; unfold eq. \n  case (eq_dec x y); case (eq_dec y x); auto.\n  intros H1 H2. elim H1. auto.\nQed.\n\n(** Signed comparison *)\n\nDefinition lt_bool (p1 p2 : pointer) : bool :=\n  match p1, p2 with\n  | Ptr b1 off1, Ptr b2 off2 => \n    if zlt b1 b2 \n    then true \n    else if zeq b1 b2 \n         then Int.lt off1 off2\n         else false\n  end.\n\nDefinition lt (p1 p2 : pointer) : bool3 :=\n  match p1, p2 with\n  | Ptr b1 off1, Ptr b2 off2 => \n    if zeq b1 b2 then bool2bool3 (Int.lt off1 off2)\n                 else b3_unknown\n  end.\n\nDefinition cmp (c: comparison) (x y : pointer) : bool3 :=\n  match c with\n  | Ceq => bool2bool3 (eq x y)\n  | Cne => bool2bool3 (negb (eq x y))\n  | Clt => lt x y\n  | Cle => negb3 (lt y x)\n  | Cgt => lt y x\n  | Cge => negb3 (lt x y)\n  end.\n\nLemma negate_cmp:\n  forall c x y, cmp (negate_comparison c) x y = negb3 (cmp c x y).\nProof.\n  by intros; destruct c; simpl; b3_simps.\nQed.\n\nLemma swap_cmp:\n  forall c x y, cmp (swap_comparison c) x y = cmp c y x.\nProof.\n  by intros; destruct c; simpl; auto; rewrite eq_sym. \nQed.\n\n\n(** Unsigned comparison *)\n\nDefinition ltu_bool (p1 p2 : pointer) : bool :=\n  match p1, p2 with\n  | Ptr b1 off1, Ptr b2 off2 => \n    if zlt b1 b2 \n    then true \n    else if zeq b1 b2 \n         then Int.ltu off1 off2\n         else false\n  end.\n\nDefinition ltu (p1 p2 : pointer) : bool3 :=\n  match p1, p2 with\n  | Ptr b1 off1, Ptr b2 off2 => \n    if zeq b1 b2 then bool2bool3 (Int.ltu off1 off2)\n                 else b3_unknown\n  end.\n\nDefinition cmpu (c: comparison) (x y : pointer) : bool3 :=\n  match c with\n  | Ceq => bool2bool3 (eq x y)\n  | Cne => bool2bool3 (negb (eq x y))\n  | Clt => ltu x y\n  | Cle => negb3 (ltu y x)\n  | Cgt => ltu y x\n  | Cge => negb3 (ltu x y)\n  end.\n\nLemma negate_cmpu:\n  forall c x y, cmpu (negate_comparison c) x y = negb3 (cmpu c x y).\nProof.\n  by intros; destruct c; simpl; b3_simps.\nQed.\n\nLemma swap_cmpu:\n  forall c x y, cmpu (swap_comparison c) x y = cmpu c y x.\nProof.\n  by intros; destruct c; simpl; auto; rewrite eq_sym. \nQed.\n\nLemma add_zero_r: forall p,\n  MPtr.add p Int.zero = p.\nProof.\n  by intros; destruct p; simpl; rewrite Int.add_zero.\nQed.\n\nLemma add_add_r: forall p n1 n2,\n  MPtr.add p (Int.add n1 n2) = MPtr.add (MPtr.add p n1) n2.\nProof.\n  by intros; destruct p; simpl; rewrite Int.add_assoc.\nQed.\n\nLemma add_sub_r: forall p n1 n2,\n  MPtr.add p (Int.sub n1 n2) = MPtr.add (MPtr.sub_int p n2) n1.\nProof.\n  intros; destruct p; simpl.\n  by rewrite <- Int.sub_add_l, (Int.add_commut _ n1), \n            Int.sub_add_l, Int.add_commut.\nQed.\n\nLemma add_add_l: forall p n1 n2,\n  MPtr.add (MPtr.add p n1) n2 = MPtr.add p (Int.add n1 n2). \nProof.\n  by symmetry; apply add_add_r.\nQed.\n\nLemma add_sub_l: forall p n1 n2,\n  MPtr.add (MPtr.sub_int p n2) n1 = MPtr.add p (Int.sub n1 n2). \nProof.\n  by symmetry; apply add_sub_r.\nQed.\n\nLemma sub_zero_r: forall p,\n  MPtr.sub_int p Int.zero = p.\nProof.\n  by intros; destruct p; simpl; rewrite Int.sub_zero_r.\nQed.\n\nLemma sub_add_r: forall p n1 n2,\n  MPtr.sub_int p (Int.add n1 n2) = MPtr.sub_int (MPtr.sub_int p n1) n2.\nProof.\n  intros; destruct p; simpl.\n  by rewrite !Int.sub_add_opp, !Int.neg_add_distr, Int.add_assoc.\nQed.\n\nLemma sub_sub_r: forall p n1 n2,\n  MPtr.sub_int p (Int.sub n1 n2) = MPtr.add (MPtr.sub_int p n1) n2.\nProof.\n  intros; destruct p; simpl. \n  by rewrite !Int.sub_add_opp, !Int.neg_add_distr, !Int.neg_involutive, Int.add_assoc.\nQed.\n\nLemma sub_add_l: forall p n1 n2,\n  MPtr.sub_int (MPtr.add p n1) n2 = MPtr.add p (Int.sub n1 n2).\nProof.\n  by intros; destruct p; simpl; rewrite !Int.sub_add_opp, Int.add_assoc.\nQed.\n\nLemma sub_sub_l: forall p n1 n2,\n  MPtr.sub_int (MPtr.sub_int p n1) n2 = MPtr.sub_int p (Int.add n1 n2).\nProof.\n  by symmetry; apply sub_add_r.\nQed.\n\nEnd MPtr.\n\nBind Scope pointer_scope with pointer.\n\nNotation \"p + i\" := (MPtr.add p i) : pointer_scope.\n\nDelimit Scope pointer_scope with pointer.\n", "meta": {"author": "shenghaoyuan", "repo": "CompCertTSO", "sha": "938a2ef6a398531cbd813453d7d0d20e2f4c62de", "save_path": "github-repos/coq/shenghaoyuan-CompCertTSO", "path": "github-repos/coq/shenghaoyuan-CompCertTSO/CompCertTSO-938a2ef6a398531cbd813453d7d0d20e2f4c62de/common/Pointers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22624518377989256}}
{"text": "Require Import DepList AutoSep Malloc.\n\nSet Implicit Arguments.\n\nLemma hlist_eta' : forall A (B : A -> Type) b (h : hlist B b),\n  match b return hlist B b -> Prop with\n    | nil => fun _ => True\n    | a :: b => fun h => h = HCons (hlist_hd h) (hlist_tl h)\n  end h.\n  destruct h; auto.\nQed.\n\nTheorem hlist_eta : forall A (B : A -> Type) a b (h : hlist B (a :: b)),\n  h = HCons (hlist_hd h) (hlist_tl h).\n  intros; apply (hlist_eta' h).\nQed.\n\nLemma smem_eta : forall ls (sm sm' : smem' ls),\n  NoDup ls\n  -> List.Forall (fun w => smem_get' ls w sm = smem_get' ls w sm') ls\n  -> sm = sm'.\n  induction sm; simpl; intuition.\n  rewrite hlist_nil; auto.\n  inversion H0; clear H0; subst.\n  inversion H; clear H; subst.\n  destruct (H.addr_dec x x); intuition idtac; subst.\n  rewrite (hlist_eta sm'); f_equal.\n  apply IHsm; auto.\n  eapply Forall_weaken'; eauto.\n  simpl; intros.\n  destruct (H.addr_dec x x0); subst; tauto.\nQed.  \n\nLemma get_emp' : forall w ls,\n  smem_get' ls w (smem_emp' ls) = None.\n  induction ls; simpl; intuition.\n  destruct (H.addr_dec a w); auto.\nQed.\n\nLemma get_emp : forall w,\n  smem_get w smem_emp = None.\n  intros.\n  apply get_emp'.\nQed.\n\nLemma empty_mem : forall (sm : smem),\n  (forall w, smem_get w sm = None)\n  -> sm = smem_emp.\n  intros.\n  apply smem_eta.\n  apply NoDup_allWords.\n  apply Forall_forall; intros.\n  rewrite H.\n  symmetry; apply get_emp.\nQed.\n\nTheorem materialize_allocated' : forall specs stn size base sm,\n  (forall w, w < base -> smem_get w sm = None)\n  -> (forall n, (n < 4 * size)%nat -> smem_get (base ^+ $(n)) sm <> None)\n  -> (forall w, base ^+ $(4 * size) <= w -> smem_get w sm = None)\n  -> goodSize (wordToNat base + 4 * size)%nat\n  -> interp specs ((base =?> size)%Sep stn sm).\n  induction size.\n\n  propxFo.\n  apply empty_mem; intros.\n  destruct (wlt_dec w base); auto.\n  replace w with (base ^+ $ (wordToNat (w ^- base))); auto.\n  rewrite natToWord_wordToNat.\n  replace (base ^+ (w ^- base)) with w.\n  apply H1.\n  intros.\n  replace (base ^+ $ (4 * 0)) with base in H3.\n  tauto.\n  simpl.\n  W_eq.\n  rewrite wminus_def.\n  rewrite wplus_comm.\n  rewrite <- wplus_assoc.\n  rewrite (wplus_comm (^~ base)).\n  rewrite wminus_inv.\n  rewrite wplus_comm.\n  rewrite wplus_unit.\n  reflexivity.\n  rewrite natToWord_wordToNat.\n  W_eq.\n\n  intros.\n  generalize (H0 0).\n  generalize (H0 1).\n  generalize (H0 2).\n  generalize (H0 3).\n  intros.\n  case_eq (smem_get (base ^+ $0) sm); intros.\n  2: elimtype False; apply H6; eauto.\n  case_eq (smem_get (base ^+ $1) sm); intros.\n  2: elimtype False; apply H5; eauto.\n  case_eq (smem_get (base ^+ $2) sm); intros.\n  2: elimtype False; apply H4; eauto.\n  case_eq (smem_get (base ^+ $3) sm); intros.\n  2: elimtype False; apply H3; eauto.\n  \n  Fixpoint smem_clear ls (sm : smem' ls) (w : W) : smem' ls :=\n    match sm with\n      | HNil => HNil\n      | HCons w' _ v sm' =>\n        HCons (if H.addr_dec w w' then None else v) (smem_clear sm' w)\n    end.\n\n  propxFo.\n\n  Fixpoint smem_put ls (sm : smem' ls) (w : W) (v : B) : smem' ls :=\n    match sm with\n      | HNil => HNil\n      | HCons w' _ v' sm' =>\n        HCons (if H.addr_dec w w' then Some v else v') (smem_put sm' w v)\n    end.\n\n  exists (smem_put (smem_put (smem_put (smem_put smem_emp base b)\n    (base ^+ $1) b0) (base ^+ $2) b1) (base ^+ $3) b2).\n  exists (smem_clear (smem_clear (smem_clear (smem_clear sm base)\n    (base ^+ $1)) (base ^+ $2)) (base ^+ $3)).\n  split.\n\n  Lemma disjoint_get' : forall ls sm1 sm2,\n    NoDup ls\n    -> List.Forall (fun w => smem_get' ls w sm1 <> None -> smem_get' ls w sm2 <> None -> False) ls\n    -> disjoint' ls sm1 sm2.\n    induction sm1; simpl; intuition; rewrite (hlist_eta sm2) in *; simpl in *.\n    inversion H; clear H; subst.\n    inversion H0; clear H0; subst.\n    destruct (H.addr_dec x x); try tauto.\n    destruct b; auto.\n    destruct (hlist_hd sm2); auto.\n    intuition discriminate.\n    inversion H; clear H; subst.\n    inversion H0; clear H0; subst.\n    apply IHsm1; intros; auto.\n    eapply Forall_weaken'; eauto.\n    simpl; intros.\n    destruct (H.addr_dec x x0); subst; tauto.\n  Qed.\n\n  Lemma disjoint_get : forall sm1 sm2,\n    (forall w, smem_get w sm1 <> None -> smem_get w sm2 <> None -> False)\n    -> disjoint sm1 sm2.\n    intros; apply disjoint_get'.\n    apply BedrockHeap.NoDup_all_addr.\n    apply Forall_forall; intros.\n    eauto.\n  Qed.\n\n  Lemma disjoint_get_fwd' : forall ls sm1 sm2,\n    disjoint' ls sm1 sm2\n    -> NoDup ls\n    -> List.Forall (fun w => smem_get' ls w sm1 <> None -> smem_get' ls w sm2 <> None -> False) ls.\n    induction sm1; simpl; intuition; rewrite (hlist_eta sm2) in *; simpl in *;\n      subst; constructor; simpl.\n    destruct (H.addr_dec x x); tauto.\n    inversion H0; clear H0; subst.\n    eapply Forall_weaken'; try apply IHsm1.\n    eauto.\n    auto.\n    simpl; intros.\n    destruct (H.addr_dec x x0); subst; tauto.\n    destruct (H.addr_dec x x); tauto.\n    inversion H0; clear H0; subst.\n    eapply Forall_weaken'; try apply IHsm1.\n    eauto.\n    auto.\n    simpl; intros.\n    destruct (H.addr_dec x x0); subst; tauto.\n  Qed.\n\n  Lemma allWordsUpto_universal : forall width init w,\n    (wordToNat w < init)%nat\n    -> (init <= pow2 width)%nat\n    -> In w (allWordsUpto width init).\n    induction init; simpl; intuition.\n    destruct (weq w $(init)); subst; auto; right.\n    assert (wordToNat w <> init).\n    intro; apply n.\n    subst.\n    symmetry; apply natToWord_wordToNat.\n    auto.\n  Qed.\n\n  Lemma allWords_universal : forall sz w,\n    In w (allWords sz).\n    rewrite allWords_eq; intros; apply allWordsUpto_universal.\n    apply wordToNat_bound.\n    auto.\n  Qed.\n\n  Lemma disjoint_get_fwd : forall sm1 sm2,\n    disjoint sm1 sm2\n    -> (forall w, smem_get w sm1 <> None -> smem_get w sm2 <> None -> False).\n    intros; eapply disjoint_get_fwd' in H; try apply BedrockHeap.NoDup_all_addr.\n    assert (In w H.all_addr) by apply allWords_universal.\n    generalize (proj1 (Forall_forall _ _) H _ H2); tauto.\n  Qed.\n\n  Lemma get_clear_ne' : forall a a' ls (sm : smem' ls),\n    a <> a'\n    -> smem_get' ls a (smem_clear sm a') = smem_get' ls a sm.\n    induction sm; simpl; intuition.\n    destruct (H.addr_dec x a); auto.\n    destruct (H.addr_dec a' x); congruence.\n  Qed.\n\n  Lemma get_clear_ne : forall a a' sm,\n    a <> a'\n    -> smem_get a (smem_clear sm a') = smem_get a sm.\n    intros; apply get_clear_ne'; auto.\n  Qed.\n\n  Lemma get_clear_eq' : forall a ls (sm : smem' ls),\n    smem_get' ls a (smem_clear sm a) = None.\n    induction sm; simpl; intuition.\n    destruct (H.addr_dec x a); auto.\n    destruct (H.addr_dec a x); congruence.\n  Qed.\n\n  Lemma get_clear_eq : forall a sm,\n    smem_get a (smem_clear sm a) = None.\n    intros; apply get_clear_eq'.\n  Qed.\n\n  Hint Rewrite get_clear_eq get_clear_ne\n    using solve [ assumption | W_neq ] : get.\n\n  Lemma get_put_eq' : forall a v ls (sm : smem' ls),\n    In a ls\n    -> smem_get' ls a (smem_put sm a v) = Some v.\n    induction sm; simpl; intuition.\n    subst.\n    destruct (H.addr_dec a a); intuition idtac.\n    destruct (H.addr_dec x a); intuition idtac.\n    subst.\n    destruct (H.addr_dec a a); intuition idtac.\n  Qed.\n\n  Lemma get_put_eq : forall a v sm,\n    smem_get a (smem_put sm a v) = Some v.\n    intros; apply get_put_eq'.\n    apply allWords_universal.\n  Qed.\n\n  Lemma get_put_ne' : forall a a' v ls (sm : smem' ls),\n    a <> a'\n    -> smem_get' ls a (smem_put sm a' v) = smem_get' ls a sm.\n    induction sm; simpl; intuition.\n    destruct (H.addr_dec a' x); intuition idtac.\n    destruct (H.addr_dec x a); intuition idtac.\n    congruence.\n    destruct (H.addr_dec x a); intuition idtac.\n  Qed.\n\n  Lemma get_put_ne : forall a a' v sm,\n    a <> a'\n    -> smem_get a (smem_put sm a' v) = smem_get a sm.\n    intros; apply get_put_ne'; auto.\n  Qed.\n\n  Hint Rewrite get_emp get_put_eq get_put_ne\n    using solve [ assumption | W_neq ] : get.\n\n  Lemma join_None' : forall a ls sm1 sm2,\n    smem_get' ls a sm1 = None\n    -> smem_get' ls a (join' ls sm1 sm2) = smem_get' ls a sm2.\n    induction sm1; simpl; intuition.\n    destruct (H.addr_dec x a); subst; auto.\n  Qed.\n\n  Lemma join_None : forall a sm1 sm2,\n    smem_get a sm1 = None\n    -> smem_get a (join sm1 sm2) = smem_get a sm2.\n    intros; apply join_None'; auto.\n  Qed.\n\n  Lemma join_Some' : forall a v ls sm1 sm2,\n    smem_get' ls a sm1 = Some v\n    -> smem_get' ls a (join' ls sm1 sm2) = Some v.\n    induction sm1; simpl; intuition.\n    destruct (H.addr_dec x a); subst; auto.\n  Qed.\n\n  Lemma join_Some : forall a v sm1 sm2,\n    smem_get a sm1 = Some v\n    -> smem_get a (join sm1 sm2) = Some v.\n    intros; apply join_Some'; auto.\n  Qed.\n\n  Lemma split_put_clear : forall sm sm1 sm2 a v,\n    split sm sm1 sm2\n    -> smem_get a sm2 = Some v\n    -> split sm (smem_put sm1 a v) (smem_clear sm2 a).\n    unfold split; intuition subst.\n    apply disjoint_get; intros.\n    destruct (weq w a); subst.\n    autorewrite with get in *; tauto.\n    autorewrite with get in *.\n    eapply disjoint_get_fwd in H1; eassumption.\n\n    apply smem_eta; try apply BedrockHeap.NoDup_all_addr.\n    apply Forall_forall; intros.\n    destruct (weq x a); subst.\n    rewrite join_None.\n    erewrite join_Some.\n    eauto.\n    autorewrite with get; reflexivity.\n    case_eq (smem_get a sm1); auto; intros.\n    eapply disjoint_get_fwd in H1; try eassumption.\n    tauto.\n    instantiate (1 := a); congruence.\n    congruence.\n    \n    case_eq (smem_get x sm1); intros.\n    erewrite join_Some.\n    erewrite join_Some.\n    2: autorewrite with get; eassumption.\n    2: eassumption.\n    reflexivity.\n\n    rewrite join_None.\n    rewrite join_None.\n    autorewrite with get; reflexivity.\n    autorewrite with get; assumption.\n    assumption.\n  Qed.\n\n  repeat apply split_put_clear.\n  apply split_a_semp_a.\n  replace (base ^+ $0) with base in H7 by words.\n  congruence.\n  \n  autorewrite with get; assumption.\n  autorewrite with get; assumption.\n  autorewrite with get; assumption.\n  \n  split.\n  exists (implode stn (b, b0, b1, b2)).\n  split.\n  unfold smem_get_word.\n  \n  unfold H.footprint_w.\n  autorewrite with get.\n  reflexivity.\n\n  intuition idtac.\n  autorewrite with get.\n  reflexivity.\n  \n  apply simplify_fwd.\n  eapply Imply_sound; [ apply allocated_shift_base | ].\n  instantiate (1 := 0).\n  instantiate (1 := base ^+ $4).\n  W_eq.\n  eauto.\n  apply IHsize.\n  \n  intros.\n  destruct (weq w base); subst.\n  autorewrite with get; reflexivity.\n  destruct (weq w (base ^+ $1)); subst.\n  autorewrite with get; reflexivity.\n  destruct (weq w (base ^+ $2)); subst.\n  autorewrite with get; reflexivity.\n  destruct (weq w (base ^+ $3)); subst.\n  autorewrite with get; reflexivity.\n  autorewrite with get.\n  apply H.\n  pre_nomega.\n  rewrite wordToNat_wplus in H11;\n    rewrite wordToNat_natToWord_idempotent in * by reflexivity;\n      try (eapply goodSize_weaken; [ eassumption | omega ]).\n\n  Lemma wordToNat_ninj : forall sz (u v : word sz),\n    u <> v\n    -> wordToNat u <> wordToNat v.\n    intros; intro; apply H.\n    assert (natToWord sz (wordToNat u) = natToWord sz (wordToNat v)) by congruence.\n    repeat rewrite natToWord_wordToNat in H1.\n    assumption.\n  Qed.\n\n  repeat match goal with\n           | [ H : _ |- _ ] => apply wordToNat_ninj in H\n         end.\n  rewrite wordToNat_wplus in n0;\n    rewrite wordToNat_natToWord_idempotent in * by reflexivity;\n      try (eapply goodSize_weaken; [ eassumption | omega ]).\n  rewrite wordToNat_wplus in n1;\n    rewrite wordToNat_natToWord_idempotent in * by reflexivity;\n      try (eapply goodSize_weaken; [ eassumption | omega ]).\n  rewrite wordToNat_wplus in n2;\n    rewrite wordToNat_natToWord_idempotent in * by reflexivity;\n      try (eapply goodSize_weaken; [ eassumption | omega ]).\n  omega.\n\n  intros.\n  rewrite get_clear_ne in H12.\n  rewrite get_clear_ne in H12.\n  rewrite get_clear_ne in H12.\n  rewrite get_clear_ne in H12.\n  apply H0 with (4 + n).\n  omega.\n  rewrite natToW_plus.\n  etransitivity; try apply H12.\n  f_equal.\n  unfold natToW.\n  W_eq.\n\n  rewrite <- wplus_assoc.\n  rewrite <- natToW_plus.\n\n  Lemma wordToNat_ninj' : forall sz (u v : word sz),\n    wordToNat u <> wordToNat v\n    -> u <> v.\n    congruence.\n  Qed.\n  \n  apply wordToNat_ninj'.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent.\n  omega.\n  change (goodSize (4 + n)).\n  eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + n)).\n  eapply goodSize_weaken; [ eassumption | omega ].\n\n  rewrite <- wplus_assoc.\n  rewrite <- natToW_plus.\n  apply wordToNat_ninj'.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  omega.\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + n)).\n  eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + n)).\n  eapply goodSize_weaken; [ eassumption | omega ].\n\n  rewrite <- wplus_assoc.\n  rewrite <- natToW_plus.\n  apply wordToNat_ninj'.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  omega.\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + n)).\n  eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + n)).\n  eapply goodSize_weaken; [ eassumption | omega ].\n\n  rewrite <- wplus_assoc.\n  rewrite <- natToW_plus.\n  apply wordToNat_ninj'.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  omega.\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + n)).\n  eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + n)).\n  eapply goodSize_weaken; [ eassumption | omega ].\n\n  intros.\n  rewrite get_clear_ne.\n  rewrite get_clear_ne.\n  rewrite get_clear_ne.\n  rewrite get_clear_ne.\n  apply H1.\n  Opaque mult.\n  pre_nomega.\n  rewrite <- wplus_assoc in H11.\n  rewrite <- natToW_plus in H11.\n  rewrite wordToNat_wplus in H11.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent in H11.\n  rewrite wordToNat_natToWord_idempotent.\n  omega.\n  change (goodSize (4 * S size)); eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + 4 * size)); eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent.\n  assumption.\n  change (goodSize (4 * S size)); eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + 4 * size)); eapply goodSize_weaken; [ eassumption | omega ].\n\n  intro; apply H11; subst.\n  rewrite <- wplus_assoc.\n  rewrite <- natToW_plus.\n  pre_nomega.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent.\n  omega.\n  change (goodSize (4 + 4 * size)); eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + 4 * size)); eapply goodSize_weaken; [ eassumption | omega ].\n\n  intro; apply H11; subst.\n  rewrite <- wplus_assoc.\n  rewrite <- natToW_plus.\n  pre_nomega.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent.\n  omega.\n  change (goodSize (4 + 4 * size)); eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + 4 * size)); eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  eapply goodSize_weaken; [ eassumption | omega ].\n\n  intro; apply H11; subst.\n  rewrite <- wplus_assoc.\n  rewrite <- natToW_plus.\n  pre_nomega.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent.\n  omega.\n  change (goodSize (4 + 4 * size)); eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + 4 * size)); eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  eapply goodSize_weaken; [ eassumption | omega ].\n\n  intro; apply H11; subst.\n  rewrite <- wplus_assoc.\n  rewrite <- natToW_plus.\n  pre_nomega.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent.\n  omega.\n  change (goodSize (4 + 4 * size)); eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  change (goodSize (4 + 4 * size)); eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  eapply goodSize_weaken; [ eassumption | omega ].\n\n  rewrite wordToNat_wplus.\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  eapply goodSize_weaken; [ eassumption | omega ].\n  rewrite wordToNat_natToWord_idempotent by reflexivity.\n  eapply goodSize_weaken; [ eassumption | omega ].\nQed.\n\nDefinition goodSize' (n : nat) := (N.of_nat n < 1 + Npow2 32)%N.\n\nLemma get_memoryIn' : forall m w init,\n  (wordToNat w < init)%nat\n  -> goodSize' init\n  -> smem_get' (allWordsUpto 32 init) w (memoryIn' m _) = m w.\n  induction init; simpl; intuition.\n  destruct (H.addr_dec $(init) w).\n  unfold H.mem_get, ReadByte.\n  congruence.\n  apply IHinit.\n  apply wordToNat_ninj in n.\n  rewrite wordToNat_natToWord_idempotent in n.\n  omega.\n  generalize H0; clear.\n  unfold goodSize'.\n  generalize (Npow2 32); intros.\n  apply Nlt_out in H0.\n  rewrite N2Nat.inj_add in H0.\n  autorewrite with N in *.\n  pre_nomega.\n  simpl in *.\n  omega.\n  generalize H0; clear.\n  unfold goodSize'.\n  generalize (Npow2 32).\n  intros.\n  nomega.\nQed.\n\nLemma pow2_N : forall n,\n  N.of_nat (pow2 n) = Npow2 n.\n  intros.\n  assert (N.to_nat (N.of_nat (pow2 n)) = N.to_nat (Npow2 n)).\n  autorewrite with N.\n  symmetry; apply Npow2_nat.\n  assert (N.of_nat (N.to_nat (N.of_nat (pow2 n))) = N.of_nat (N.to_nat (Npow2 n))) by congruence.\n  autorewrite with N in *.\n  assumption.\nQed.\n\nLemma get_memoryIn : forall m w,\n  smem_get w (memoryIn m) = m w.\n  intros.\n  unfold smem_get, memoryIn, HT.memoryIn, H.all_addr.\n  rewrite allWords_eq.\n  apply get_memoryIn'.\n  apply wordToNat_bound.\n  hnf.\n  rewrite pow2_N.\n  reflexivity.\nQed.\n\nTheorem materialize_allocated : forall stn st size specs,\n  (forall n, (n < size * 4)%nat -> st.(Mem) n <> None)\n  -> (forall w, $(size * 4) <= w -> st.(Mem) w = None)\n  -> goodSize (size * 4)%nat\n  -> interp specs (![ 0 =?> size ] (stn, st)).\n  rewrite sepFormula_eq; intros.\n  apply materialize_allocated'; simpl.\n  intros.\n  pre_nomega.\n  rewrite roundTrip_0 in H2.\n  omega.\n  intros.\n  rewrite <- natToW_plus; simpl.\n  rewrite get_memoryIn.\n  auto.\n  intros.\n  rewrite wplus_unit in H2.\n  rewrite get_memoryIn.\n  apply H0.\n  Require Import Arith.\n  rewrite mult_comm; assumption.\n  rewrite mult_comm; assumption.\nQed.\n\n\n(** * Now put it all together to prove [genesis]. *)\n\nSection boot.\n  Variables heapSize globalsSize : nat.\n\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n  Hypothesis heapSizeUpperBound : goodSize (heapSize * 4).\n\n  Lemma goodSize_heapSize : goodSize heapSize.\n    eapply goodSize_weaken; [ eassumption | omega ].\n  Qed.\n\n  Hint Immediate goodSize_heapSize.\n\n  Theorem heapSizeLowerBound' : natToW heapSize < natToW 3 -> False.\n    change (natToW 3 <= natToW heapSize).\n    intro; pre_nomega.\n    rewrite wordToNat_natToWord_idempotent in *.\n    rewrite wordToNat_natToWord_idempotent in *.\n    omega.\n    reflexivity.\n    change (goodSize heapSize); eapply goodSize_weaken; [ eassumption | omega ].\n  Qed.\n\n  Hint Immediate heapSizeLowerBound'.\n\n  Theorem noWrap : noWrapAround (natToW 4) (heapSize - 1).\n    simpl; hnf; intros.\n    intro.\n    rewrite <- natToW_plus in H0.\n    apply natToW_inj in H0.\n    omega.\n    2: reflexivity.\n    eapply goodSize_weaken; [ eassumption | omega ].\n  Qed.\n\n  Theorem heapSize_roundTrip : wordToNat (natToW heapSize) = heapSize.\n    intros; apply wordToNat_natToWord_idempotent;\n      change (goodSize heapSize); eauto.\n  Qed.\n\n  Hint Rewrite heapSize_roundTrip : sepFormula.\n\n  Definition bootS := {|\n    Reserved := 49;\n    Formals := nil;\n    Precondition := fun _ => st ~> ![ 0 =?> (heapSize + 50 + globalsSize) ] st\n  |}.\n\n  Theorem genesis :\n    0 =?> (heapSize + 50 + globalsSize)\n    ===> (Ex vs, locals (\"rp\" :: nil) vs 49 (heapSize * 4)%nat) * 0 =?> heapSize * ((heapSize + 50) * 4)%nat =?> globalsSize.\n    descend; intros; eapply Himp_trans; [ apply allocated_split | ].\n    instantiate (1 := heapSize); auto.\n    apply Himp_trans with (0 =?> heapSize *\n      ((heapSize * 4)%nat =?> 50 * ((heapSize + 50) * 4)%nat =?> globalsSize))%Sep.\n    apply Himp_star_frame.\n    apply Himp_refl.\n    intros; eapply Himp_trans; [ apply allocated_split | ].\n    instantiate (1 := 50); auto.\n    apply Himp_star_frame.\n    apply allocated_shift_base.\n    Require Import Arith.\n    rewrite mult_comm.\n    simpl.\n    unfold natToW.\n    words.\n    reflexivity.\n    apply allocated_shift_base.\n    simpl.\n    rewrite <- mult_plus_distr_l.\n    rewrite mult_comm.\n    unfold natToW.\n    words.\n    omega.\n\n    Lemma wiggle : forall P Q R,\n      P * (Q * R) ===> Q * P * R.\n      sepLemma.\n    Qed.\n\n    eapply Himp_trans; [ apply wiggle | ].\n    repeat (apply Himp_star_frame; try apply Himp_refl).\n    change 50 with (length (\"rp\" :: nil) + 49).\n    apply create_stack.\n    NoDup.\n  Qed.\n\n  Transparent mult.\n\n  Lemma bootstrap_Sp_nonzero : forall sp : W,\n    sp = 0\n    -> sp = heapSize * 4\n    -> goodSize (heapSize * 4)\n    -> False.\n    intros; subst; apply natToW_inj in H0; auto; omega.\n  Qed.\n\n  Hypothesis globals : nat.\n  Hypothesis mem_size : goodSize ((heapSize + 50 + globals) * 4)%nat.\n\n  Lemma bootstrap_Sp_freeable : forall sp : W,\n    sp = heapSize * 4\n    -> freeable sp 50.\n    intros; subst; constructor; auto.\n    hnf; intros.\n    rewrite <- natToW_plus.\n    intro.\n    apply natToW_inj in H0.\n    omega.\n    unfold size in *.\n    eapply goodSize_weaken; [ apply mem_size | ].\n    omega.\n    auto.\n  Qed.\nEnd boot.\n\nDefinition genesisHints : TacPackage.\n  prepare genesis tt.\nDefined.\n\nLtac genesis := post; evaluate genesisHints; simpl in *; sep genesisHints; eauto.\n\nRequire Import Safety.\n\nLtac safety ok :=\n  eapply safety; try eassumption; [\n    link_simp; unfold labelSys, labelSys'; simpl; tauto\n    | apply ok\n    | apply LabelMap.find_2; link_simp; reflexivity\n    | propxFo; apply materialize_allocated; assumption ].\n\nHint Immediate goodSize_heapSize heapSizeLowerBound' bootstrap_Sp_nonzero bootstrap_Sp_freeable.\nHint Rewrite heapSize_roundTrip using assumption : sepFormula.\nHint Extern 1 (noWrapAround _ _) => apply noWrap.\n\nLtac goodSize :=\n  match goal with\n    | [ H : goodSize (?size * 4)%nat |- _ ] => unfold size in *\n  end; eapply goodSize_weaken; [ eassumption | omega ].\n", "meta": {"author": "gmalecha", "repo": "bedrock-mirror-shard", "sha": "ea7e5ad56a1d6392468b6823e0457dd44524bca7", "save_path": "github-repos/coq/gmalecha-bedrock-mirror-shard", "path": "github-repos/coq/gmalecha-bedrock-mirror-shard/bedrock-mirror-shard-ea7e5ad56a1d6392468b6823e0457dd44524bca7/platform/Bootstrap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22624518377989256}}
{"text": "From stdpp Require Import numbers list.\n\nLemma prefixOfAppSingleton {A : Type} (l1 l2 : list A) (x : A) : l1 `prefix_of` l2 ++ [x] -> l1 `prefix_of` l2 \\/ l1 = l2 ++ [x].\nProof.\n  unfold prefix. intro h.\n  destruct h as [w h].\n  induction w using rev_ind.\n  - right. rewrite app_nil_r in h. easy.\n  - left. exists w. pose proof app_inj_tail l2 (l1 ++ w) x x0 as H.\n    rewrite <- app_assoc in H. tauto.\nQed.\n\nLemma prefixAppCases {A : Type} (l x y : list A) (h : l `prefix_of` x ++ y) : l `prefix_of` x \\/ exists l', l = x ++ l'.\nProof.\n  induction y using rev_ind.\n  - left. rewrite app_nil_r in h. tauto.\n  - rewrite app_assoc in h. pose proof (prefixOfAppSingleton _ _ _ h). destruct H.\n    * tauto.\n    * rewrite H. right. exists (y ++ [x0]). rewrite app_assoc. easy.\nQed.\n\nLemma prefixSingleton {A : Type} (l : list A) (x : A) (h : l `prefix_of` [x]) : l = [] \\/ l = [x].\nProof.\n  destruct h as [w h]. destruct l.\n  - left. reflexivity.\n  - right. inversion h. symmetry in H1. pose proof app_eq_nil _ _ H1 as H2. destruct H2 as [Hleft Hright]. rewrite Hleft. reflexivity.\nQed.\n", "meta": {"author": "huynhtrankhanh", "repo": "CoqCP", "sha": "a03cd02d9ffb3619da286e680d33a5f0d29fabee", "save_path": "github-repos/coq/huynhtrankhanh-CoqCP", "path": "github-repos/coq/huynhtrankhanh-CoqCP/CoqCP-a03cd02d9ffb3619da286e680d33a5f0d29fabee/theories/PrefixApp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.22624518377989253}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation, either version 2 of the License, or  *)\n(*  (at your option) any later version.  This file is also distributed *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Tools for small-step operational semantics *)\n\n(** This module defines generic operations and theorems over\n  the one-step transition relations that are used to specify\n  operational semantics in small-step style. *)\n\nRequire Import Relations.\nRequire Import Wellfounded.\nRequire Import Coqlib.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Integers.\nRequire Import Smallstep.\n\n\nRequire Import Values. (*for meminj, compose_meminj,...*)\n\nSet Implicit Arguments.\n\n\n(** * Transition semantics *)\n\n(** The general form of a transition semantics. *)\nRequire Import compcert.common.Memory.\n\nSection ExposingMemory.\n  \n  Variables L1 L2: semantics.\n  Variable get_mem1: state L1 -> mem.\n  Variable get_mem2: state L2 -> mem.\n\n  (** *Equality Phases*)\n  Section Equality.\n    Record fsim_properties_eq: Type :=\n      {\n        Eqindex: Type;\n        Eqorder: Eqindex -> Eqindex -> Prop;\n        Eqmatch_states: Eqindex -> state L1 -> state L2 -> Prop;  \n        Eqfsim_order_wf: well_founded Eqorder;\n        Eqfsim_match_meminj: forall i s1 s2, Eqmatch_states i s1 s2 ->  (get_mem1 s1) = (get_mem2 s2);\n        (*    fsim_match_initial_states:\n      forall s1 m1 f m2, initial_state L1 (s1,m1) -> Mem.inject f m1 m2 ->\n      exists i, exists s2, initial_state L2 (s2,m2) /\\ match_states i f (s1,m1) (s2,m2);*)\n        Eqfsim_match_initial_states:\n          forall s1, initial_state L1 s1 -> \n                exists i s2, initial_state L2 s2 /\\ Eqmatch_states i s1 s2;\n        Eqfsim_match_final_states:\n          forall i s1 s2 r ,\n            Eqmatch_states i s1 s2 -> final_state L1 s1 r -> (final_state L2 s2 r);\n        Eqfsim_simulation:\n          forall s1 t s1', Step L1 s1 t s1' ->\n                      forall i s2, Eqmatch_states i s1 s2 ->\n                              exists i', exists s2',\n                                  (Plus L2 s2 t s2' \\/ (Star L2 s2 t s2' /\\ Eqorder i' i))\n                                  /\\ Eqmatch_states i' s1' s2';\n        Eqfsim_public_preserved:\n          forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id\n      }.\n  \n    \n    Lemma sim_eqSim':\n      forall index order (match_states:index -> state L1 -> state L2 -> Prop),\n      (forall i s1 s2, match_states i s1 s2 ->  (get_mem1 s1) = (get_mem2 s2)) ->\n      fsim_properties L1 L2 index order match_states ->\n      fsim_properties_eq.\n    Proof.\n      intros ? ? ? H HH; inv HH.\n      econstructor; eauto.\n    Qed.\n  End Equality.\n\n  \n  (** *Extension Phases*)\n  Section Extensions.\n    \n   Record fsim_properties_ext: Type :=\n  {\n    Extindex: Type;\n    Extorder: Extindex -> Extindex -> Prop;\n    Extmatch_states: Extindex -> state L1 -> state L2 -> Prop;  \n    Extfsim_order_wf: well_founded Extorder;\n    Extfsim_match_meminj: forall i s1 s2, Extmatch_states i s1 s2 ->  Mem.extends (get_mem1 s1) (get_mem2 s2);\n(*    fsim_match_initial_states:\n      forall s1 m1 f m2, initial_state L1 (s1,m1) -> Mem.inject f m1 m2 ->\n      exists i, exists s2, initial_state L2 (s2,m2) /\\ match_states i f (s1,m1) (s2,m2);*)\n    Extfsim_match_initial_states:\n      forall s1, initial_state L1 s1 -> \n               exists i s2, initial_state L2 s2 /\\ Extmatch_states i s1 s2;\n    Extfsim_match_final_states:\n      forall i s1 s2 r ,\n      Extmatch_states i s1 s2 -> final_state L1 s1 r -> (final_state L2 s2 r);\n    Extfsim_simulation:\n      forall s1 t s1', Step L1 s1 t s1' ->\n      forall i s2, Extmatch_states i s1 s2 ->\n      exists i', exists s2',\n         (Plus L2 s2 t s2' \\/ (Star L2 s2 t s2' /\\ Extorder i' i))\n         /\\ Extmatch_states i' s1' s2';\n    Extfsim_public_preserved:\n      forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id\n  }.\n\n   (** An alternate form of the simulation diagram *)\n   Lemma Extfsim_simulation':\n       forall (SIM:fsim_properties_ext),\n       forall i s1 t s1',\n         Step L1 s1 t s1' ->\n         forall s2, Extmatch_states SIM i s1 s2 ->\n               (exists i', exists s2', Plus L2 s2 t s2' /\\\n                                   Extmatch_states SIM i' s1' s2')\n               \\/ (exists i', Extorder SIM i' i /\\ t = E0 /\\ Extmatch_states SIM i' s1' s2).\n   Proof.\n     intros. exploit Extfsim_simulation; eauto.\n     intros [i' [s2' [A B ]]]. intuition.\n     left; exists i'; exists s2'; auto .\n     inv H2. \n     right; exists i'; eauto.\n     left; exists i'; exists s2'; split; auto. econstructor; eauto.\n   Qed.\n\n   (** *Star version of simulation*)\n    Lemma Extsimulation_star:\n      forall (SIM:fsim_properties_ext),\n      forall s1 t s1', Star L1 s1 t s1' ->\n                  forall i s2,\n                    Extmatch_states SIM  i s1 s2 ->\n                    exists i', exists s2', Star L2 s2 t s2' /\\ Extmatch_states SIM  i' s1' s2'.\n    Proof.\n      intros S.\n      induction 1; intros.\n      exists i; exists s2; split; auto. apply star_refl.\n\n      (*split; auto; constructor.\n      apply inject_incr_refl. constructor.*)\n\n      exploit Extfsim_simulation; eauto.\n      intros [i' [s2' [A B]]].\n      exploit IHstar; eauto. intros [i'' [s2'' [E F ]]].\n      exists i'';exists s2''; split; auto. eapply star_trans; eauto.\n      intuition auto. apply plus_star; auto.\n    Qed.\n    \n    (** *Plus version of simulation*)\n    Lemma Extsimulation_plus:\n      forall (SIM: fsim_properties_ext),\n      forall s1 t s1', Plus L1 s1 t s1' ->\n                  forall i s2, Extmatch_states SIM  i s1 s2 -> \n            (exists i', exists s2', Plus L2 s2 t s2' /\\ Extmatch_states SIM  i' s1' s2')\n            \\/ (exists i', clos_trans _ (Extorder SIM) i' i /\\ t = E0 /\\ Extmatch_states SIM  i' s1' s2).\n    Proof.\n      intros S.\n      induction 1 using plus_ind2; intros.\n      (* base case *)\n      exploit Extfsim_simulation'; eauto.\n      intros [[i' [s2' [A B ]]] | [i'  A]].\n      left. exists i', s2'; auto.\n      right; exists i'; intuition.\n      (* inductive case *)\n      exploit Extfsim_simulation'; eauto.\n      intros [[i' [s2' [A B]]] | [i' [A [B C] ]]].\n      exploit Extsimulation_star; eauto. apply plus_star; eauto. eauto.\n      intros [i'' [s2'' [P Q ]]].\n      left; exists i''; exists s2''; split; auto. eapply plus_star_trans; eauto.\n      repeat split; auto.\n      \n      exploit IHplus; eauto.\n      intros [[i'' [s2'' [P Q ]]] | [i'' [P Q]]].\n      subst. simpl. left; exists i''; exists s2''; auto.\n      repeat split; eauto.\n\n      subst. simpl. right; exists i''; intuition auto.\n      eapply t_trans; eauto. eapply t_step; eauto.\n    Qed.\n    \n    Lemma EqEx_sim': \n        fsim_properties_eq ->\n        fsim_properties_ext.\n    Proof.\n      intros H; inv H.\n      econstructor; eauto.\n      intros.\n      erewrite Eqfsim_match_meminj0; eauto.\n      eapply Mem.extends_refl.\n    Qed.\n\n    Lemma sim_extSim:\n      forall index order (match_states:index -> state L1 -> state L2 -> Prop),\n      (forall i s1 s2, match_states i s1 s2 ->  Mem.extends (get_mem1 s1) (get_mem2 s2)) ->\n      fsim_properties L1 L2 index order match_states ->\n      fsim_properties_ext.\n    Proof.\n      intros ? ? ? H HH; inv HH.\n      econstructor; eauto.\n    Qed.\n\n  End Extensions.\n\n  (** *Injection Phases*)\n  Section Injection.\n    Record fsim_properties_inj: Type :=\n      {  Injindex: Type;\n        Injorder: Injindex -> Injindex -> Prop;\n        Injmatch_states: Injindex -> meminj -> state L1 -> state L2 -> Prop;  \n        Injfsim_order_wf: well_founded Injorder;\n        Injfsim_match_meminj: forall i f s1 s2, Injmatch_states i f s1 s2 ->  Mem.inject f (get_mem1 s1) (get_mem2 s2);\n        Injfsim_match_full: forall i f s1 s2, Injmatch_states i f s1 s2 ->  injection_full f (get_mem1 s1);\n        (*    fsim_match_initial_states:\n      forall s1 m1 f m2, initial_state L1 (s1,m1) -> Mem.inject f m1 m2 ->\n      exists i, exists s2, initial_state L2 (s2,m2) /\\ match_states i f (s1,m1) (s2,m2);*)\n        Injfsim_match_initial_states:\n          forall s1, initial_state L1 s1 -> \n                exists i f s2, initial_state L2 s2 /\\ Injmatch_states i f s1 s2;\n        Injfsim_match_final_states:\n          forall i s1 s2 r f,\n            Injmatch_states i f s1 s2 -> final_state L1 s1 r -> (final_state L2 s2 r);\n        Injfsim_simulation:\n          forall s1 t s1' f, Step L1 s1 t s1' ->\n                        forall i s2, Injmatch_states i f s1 s2 ->\n                                exists i', exists s2' f' t',\n                                    (Plus L2 s2 t' s2' \\/ (Star L2 s2 t' s2' /\\ Injorder i' i))\n                                    /\\ Injmatch_states i' f' s1' s2' /\\\n                                    Values.inject_incr f f' /\\\n                                    inject_trace f' t t';\n        Injfsim_public_preserved:\n          forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id\n      }.\n\n   (** An alternate form of the simulation diagram *)\n\n    Lemma Injfsim_simulation':\n        forall (SIM:fsim_properties_inj),\n        forall i s1 t s1' f,\n          Step L1 s1 t s1' ->\n          forall s2, Injmatch_states SIM i f s1 s2 ->\n                (exists i', exists s2' f' t',\n                      Plus L2 s2 t' s2' /\\\n                      Injmatch_states SIM i' f' s1' s2'\n                      /\\ inject_incr f f' /\\ inject_trace f' t t')\n                \\/ (exists i' f', Injorder SIM i' i /\\ t = E0 /\\ Injmatch_states SIM i' f' s1' s2\n                  /\\ inject_incr f f').\n    Proof.\n      intros. exploit Injfsim_simulation; eauto.\n      intros [i' [s2' [f' [t'[A [B [C D]]]]]]]. intuition.\n      left; exists i'; exists s2'; auto. exists f', t'; eauto.\n      inv H2. inversion D; subst.\n      right; exists i'; eauto.\n      left; exists i'; exists s2',f', (t1 ** t2); split; auto. econstructor; eauto.\n    Qed.\n\n    \n    (** *Star version of simulation*)\n    Lemma Injsimulation_star:\n        forall (SIM:fsim_properties_inj),\n      forall s1 t s1', Star L1 s1 t s1' ->\n                  forall i f s2,\n                    Injmatch_states SIM i f s1 s2 ->\n                    exists i' f', exists s2' t', Star L2 s2 t' s2' /\\ Injmatch_states SIM i' f' s1' s2'\n                                       /\\ inject_incr f f' /\\ inject_trace f' t t'.\n    Proof.\n      intros S.\n      induction 1; intros.\n      exists i, f; exists s2 , nil; split; auto. apply star_refl.\n      split; auto; constructor.\n      apply inject_incr_refl. constructor.\n      exploit Injfsim_simulation; eauto.\n      intros [i' [s2' [f'[t' [A [B [C D]]]]]]].\n      exploit IHstar; eauto. intros [i'' [f'' [s2'' [t'' [E [F [G HH]]]]]]].\n      exists i'';exists f''; exists s2'', (t' ** t''); split; auto. eapply star_trans; eauto.\n      intuition auto. apply plus_star; auto.\n      split; auto. subst t.\n      split; auto.\n      eapply inject_incr_trans; eauto.\n      admit. (*inject trace properties*)\n    Admitted.\n    \n    (** *Plus version of simulation*)\n    Lemma Injsimulation_plus:\n      forall (SIM:fsim_properties_inj),\n      forall s1 t s1', Plus L1 s1 t s1' ->\n                  forall i f s2, Injmatch_states SIM i f s1 s2 -> \n            (exists i', exists f', exists s2' t', Plus L2 s2 t' s2' /\\ Injmatch_states SIM i' f' s1' s2'\n            /\\ inject_incr f f' /\\ inject_trace f' t t')\n            \\/ (exists i', exists f', clos_trans _ (Injorder SIM) i' i /\\ t = E0 /\\ Injmatch_states SIM i' f' s1' s2\n                           /\\ inject_incr f f').\n    Proof.\n      intros S.\n      induction 1 using plus_ind2; intros.\n      (* base case *)\n      exploit Injfsim_simulation'; eauto.\n      intros [[i' [s2' [f' [t' [A [B [C D]]]]]]] | [i' [f' [t' A]]]].\n      left. exists i', f', s2', t'; auto.\n      right; exists i', f' ; intuition.\n      (* inductive case *)\n      exploit Injfsim_simulation'; eauto.\n      intros [[i' [s2' [f' [t' [A [B [C D]]]]]]] | [i' [f' [A [B [C D]]]]]].\n      exploit Injsimulation_star; eauto. apply plus_star; eauto. eauto.\n      intros [i'' [f'' [s2'' [t'' [P [Q [R SS]]]]]]].\n      left; exists i''; exists f''; exists s2'', (t'**t''); split; auto. eapply plus_star_trans; eauto.\n      repeat split; auto.\n      eapply inject_incr_trans; eauto.\n      subst t.\n      admit. (*Some properties about inject_trace*)\n \n      \n      exploit IHplus; eauto.\n      intros [[i'' [f'' [s2'' [t' [P [Q [R SS]]]]]]] | [i'' [f'' [P [Q R]]]]].\n      subst. simpl. left; exists i''; exists f''; exists s2'', (t'); auto.\n      repeat split; eauto.\n      eapply inject_incr_trans; eauto.\n      subst. simpl. right; exists i''; exists f''; intuition auto.\n      eapply t_trans; eauto. eapply t_step; eauto.\n      eapply inject_incr_trans; eauto.\n    Admitted.\n    \n  End Injection.\nEnd ExposingMemory.\n\n(*\nSection InductiveDefinitions.\n  \n  \n  Variables L1 L2: semantics.\n  Variable get_mem1: state L1 -> mem.\n  Variable get_mem2: state L2 -> mem.\n  \nArguments fsim_properties_eq: clear implicits.\n\nInductive forward_equality: Prop :=\n  Forward_equality (index: Type)\n                   (order: index -> index -> Prop)\n                   (match_states: index -> state L1 -> state L2 -> Prop)\n                   (props: fsim_properties_eq\n                             L1 L2 get_mem1 get_mem2\n                             index order match_states).\n\nArguments fsim_properties_ext: clear implicits.\n\nInductive forward_extension: Prop :=\n  Forward_extension (index: Type)\n                   (order: index -> index -> Prop)\n                   (match_states: index -> state L1 -> state L2 -> Prop)\n                   (props: fsim_properties_ext\n                             L1 L2 get_mem1 get_mem2\n                             index order match_states).\n\nLemma EqEx_sim: forward_equality -> forward_extension.\nProof.\n  intros H; inv H.\n  apply EqEx_sim' in props; econstructor; eauto.\nQed.\n\n\nArguments fsim_properties_inj: clear implicits.\n\nInductive forward_injection: Prop :=\n  Forward_injection (index: Type)\n                   (order: index -> index -> Prop)\n                   (match_states: index -> meminj -> state L1 -> state L2 -> Prop)\n                   (props: fsim_properties_inj\n                             L1 L2 get_mem1 get_mem2\n                             index order match_states).\n\nEnd InductiveDefinitions. *)\n\nSection Composition.\n    \n  Variables L1 L2 L3: semantics.\n  Variable get_mem1: state L1 -> mem.\n  Variable get_mem2: state L2 -> mem.\n  Variable get_mem3: state L3 -> mem.\n\n  Lemma injection_extension_composition:\n    @fsim_properties_inj L1 L2 get_mem1 get_mem2 ->\n    @fsim_properties_ext L2 L3 get_mem2 get_mem3 ->\n    @fsim_properties_inj L1 L3 get_mem1 get_mem3.\n  Proof.\n    intros SIM12 SIM23.\n    set (index13:= (Extindex SIM23 * Injindex SIM12)%type).\n    set (order13:=  (lex_ord (clos_trans _ (Extorder SIM23)) (Injorder SIM12))).\n    set (match_states13:=\n           (fun (i: _ ) f (s1: state L1) (s3: state L3) =>\n              exists s2, Injmatch_states SIM12 (snd i) f s1 s2 /\\ Extmatch_states SIM23 (fst i) s2 s3) ).\n    eapply Build_fsim_properties_inj with (Injindex:= index13) (Injorder:=order13) (Injmatch_states:=match_states13).\n- (* well founded *)\n  apply wf_lex_ord. apply wf_clos_trans.\n  eapply Extfsim_order_wf; eauto. eapply Injfsim_order_wf; eauto.\n- (* inject. *)\n  intros ? ? ? ? [s2' [MATCH12 MATCH23]].\n  eapply Mem.inject_extends_compose; [eapply SIM12| eapply SIM23]; eauto.\n- (* Full *)\n  intros ? ? ? ? [s2' [MATCH12 MATCH23]] b VALID.\n  eapply SIM12; eauto.\n- (* initial states *)\n  intros. exploit (Injfsim_match_initial_states SIM12); eauto. intros [i [ f [s2 [A B]]]].\n  exploit (Extfsim_match_initial_states SIM23); eauto. intros [i' [s3 [C D]]].\n  exists (i', i); exists f; exists s3; split; auto. exists s2; auto.\n- (* final states *)\n  intros. destruct H as [s3 [A B]].\n  eapply (Extfsim_match_final_states SIM23); eauto.\n  eapply (Injfsim_match_final_states SIM12); eauto.\n- (* simulation *)\n    intros. destruct H0 as [s3 [A B]]. destruct i as [i2 i1]; simpl in *.\n  exploit (Injfsim_simulation' SIM12); eauto.\n  intros [[i1' [s3'[ f' [t' [C [D [E F]]]]]]] | [i1' [f' [C [D [E F]]]]]].\n  + (* L2 makes one or several steps. *)\n    exploit Extsimulation_plus; eauto. intros [[i2' [s2' [P Q]]] | [i2' [P [Q R]]]].\n* (* L3 makes one or several steps *)\n  exists (i2', i1'); exists s2'; exists f', t'. repeat (split; auto).\n  exists s3'; auto.\n* (* L3 makes no step *)\n  exists (i2', i1'); exists s2; exists f', t'. repeat (split; auto).\n  right; split. subst t'; apply star_refl. left. auto.\n  exists s3'; auto.\n+ (* L2 makes no step *)\n  exists (i2, i1'); exists s2; exists f', t. repeat (split; auto).\n  right; split. subst t; apply star_refl. right. auto.\n  exists s3; auto.\n  subst t; constructor.\n- (* symbols *)\n  intros. transitivity (Senv.public_symbol (symbolenv L2) id);\n            [eapply Extfsim_public_preserved|eapply Injfsim_public_preserved]; eauto.\n  Qed.\n\n  (*\n  Lemma injection_extension_composition:\n    forward_injection L1 L2 get_mem1 get_mem2 ->\n    forward_extension L2 L3 get_mem2 get_mem3 ->\n    forward_injection L1 L3 get_mem1 get_mem3.\n  Proof.\n    intros S12 S23.\n    inv S12; inv S23.\n    econstructor.\n    eapply injection_extension_composition'; eauto.\n  Qed. *)\n  \n    Lemma extension_injection_composition:\n    @fsim_properties_ext L1 L2 get_mem1 get_mem2 ->\n    @fsim_properties_inj L2 L3 get_mem2 get_mem3 ->\n    @fsim_properties_inj L1 L3 get_mem1 get_mem3.\n  Proof.\n    intros SIM12 SIM23.\n    set (index13:= (Injindex SIM23 * Extindex SIM12)%type).\n    set (order13:=  (lex_ord (clos_trans _ (Injorder SIM23)) (Extorder SIM12))).\n    set (match_states13:=\n           (fun (i: _ ) f (s1: state L1) (s3: state L3) =>\n              exists s2, Extmatch_states SIM12 (snd i) s1 s2 /\\ Injmatch_states SIM23 (fst i) f s2 s3) ).\n    \n    eapply Build_fsim_properties_inj with (Injindex:= index13) (Injorder:=order13) (Injmatch_states:=match_states13).\n- (* well founded *)\n  apply wf_lex_ord. apply wf_clos_trans.\n  eapply Injfsim_order_wf; eauto. eapply Extfsim_order_wf; eauto.\n- (* inject. *)\n  intros ? ? ? ? [s2' [MATCH12 MATCH23]].\n  eapply Mem.extends_inject_compose; [eapply SIM12| eapply SIM23]; eauto.\n- (* Full *)\n  intros ? ? ? ? [s2' [MATCH12 MATCH23]] b VALID.\n  eapply SIM23; eauto.\n  eapply Extfsim_match_meminj in MATCH12; eauto.\n  inv MATCH12. unfold Mem.valid_block; rewrite <- mext_next; auto.\n  \n- (* initial states *)\n  intros. exploit (Extfsim_match_initial_states SIM12); eauto. intros [i [s2 [A B]]].\n  exploit (Injfsim_match_initial_states SIM23); eauto. intros [i' [f [s3 [C D]]]].\n  exists (i', i); exists f; exists s3; split; auto. exists s2; auto.\n- (* final states *)\n  intros. destruct H as [s3 [A B]].\n  eapply (Injfsim_match_final_states SIM23); eauto.\n  eapply (Extfsim_match_final_states SIM12); eauto.\n- (* simulation *)\n    intros. destruct H0 as [s3 [A B]]. destruct i as [i2 i1]; simpl in *.\n  exploit (Extfsim_simulation' SIM12); eauto.\n  intros [[i1' [s3'[C D ]]] | [i1' [C [D E]]]]. \n  + (* L2 makes one or several steps. *)\n    exploit Injsimulation_plus; eauto.\n    intros [[i2' [f' [s2' [t' [P [Q [? ?]]]]]]] | [i2' [f' [P [Q [R ?]]]]]].\n* (* L3 makes one or several steps *)\n  exists (i2', i1'); exists s2'; exists f', t'. repeat (split; auto).\n  exists s3'; repeat (split; auto).\n* (* L3 makes no step *)\n  exists (i2', i1'); exists s2; exists f', t. repeat (split; auto).\n  right; split. subst t; apply star_refl. left. auto.\n  exists s3'; (split; auto).\n  subst t; constructor.\n+ (* L2 makes no step *)\n  exists (i2, i1'); exists s2; exists f, t. repeat (split; auto).\n  right; split. subst t; apply star_refl. right. auto.\n  exists s3; auto.\n  subst t; constructor.\n- (* symbols *)\n  intros. transitivity (Senv.public_symbol (symbolenv L2) id);\n            [eapply Injfsim_public_preserved|eapply Extfsim_public_preserved]; eauto.\n  Qed.\n\n (* Lemma extension_injection_composition:\n    forward_extension L1 L2 get_mem1 get_mem2 ->\n    forward_injection L2 L3 get_mem2 get_mem3 ->\n    forward_injection L1 L3 get_mem1 get_mem3.\n  Proof.\n    intros S12 S23.\n    inv S12; inv S23.\n    econstructor.\n    eapply extension_injection_composition'; eauto.\n  Qed. *)\n\n  Lemma compose_inject_incr: forall f1 f2 f1' f2',\n      inject_incr f1 f1' ->\n      inject_incr f2 f2' ->\n      inject_incr (compose_meminj f1 f2) (compose_meminj f1' f2').\n  Proof.\n    intros.\n    unfold compose_meminj;\n              intros b b' ofs AA.\n    destruct (f1 b) eqn:F1; try solve[inv AA]; destruct p.\n    eapply H in F1. rewrite F1.\n    destruct (f2 b0) eqn:F2; inv AA; destruct p.\n    eapply H0 in F2.\n    rewrite F2.\n    reflexivity.\n  Qed.\n  \n  Lemma inject_trace_compose:\n    forall f12 f23 t1 t2 t3,\n      inject_trace f12 t1 t2 ->\n      inject_trace f23 t2 t3 ->\n      inject_trace (compose_meminj f12 f23) t1 t3.\n  Proof.\n  Admitted.\n\n  \n  Lemma injection_injection_composition:\n    @fsim_properties_inj L1 L2 get_mem1 get_mem2->\n    @fsim_properties_inj L2 L3 get_mem2 get_mem3 ->\n    @fsim_properties_inj L1 L3 get_mem1 get_mem3.\n    \n    intros SIM12 SIM23.\n    set (index13:= (Injindex SIM23 * Injindex SIM12)%type).\n    set (order13:=  (lex_ord (clos_trans _ (Injorder SIM23)) (Injorder SIM12))).\n    set (match_states13:=\n           (fun (i: _ ) f (s1: state L1) (s3: state L3) =>\n              exists s2 f12 f23,  Injmatch_states SIM12 (snd i) f12 s1 s2 /\\ Injmatch_states SIM23 (fst i) f23 s2 s3\n        /\\ f = compose_meminj f12 f23)).\n    eapply Build_fsim_properties_inj with (Injindex:= index13) (Injorder:=order13) (Injmatch_states:=match_states13).\n- (* well founded *)\n  apply wf_lex_ord. apply wf_clos_trans.\n  eapply Injfsim_order_wf; eauto. eapply Injfsim_order_wf; eauto.\n- (* inject. *)\n  intros ? ? ? ? [s2' [f12 [f23 [MATCH12 [MATCH23 INJCOMP]]]]].\n  subst.\n  eapply Mem.inject_compose; [eapply SIM12| eapply SIM23]; eauto.\n- (* Full *)\n  intros ? ? ? s3 [s2 [f12 [f23 [MATCH12 [MATCH23 INJCOMP]]]]] b VALID.\n  subst f.\n  eapply SIM12 in VALID; try (exact MATCH12).\n  destruct (f12 b) eqn:F12; auto. destruct p.\n  unfold compose_meminj; rewrite F12.\n  assert (VALID2 : Mem.valid_block (get_mem2 s2) b0).\n  { eapply SIM12; eauto. }\n  eapply SIM23 in VALID2; try (exact MATCH23).\n  intros HH. apply VALID2. destruct (f23 b0); inversion HH; auto.\n  destruct p. inversion HH.\n- (* initial states *)\n  intros. exploit (Injfsim_match_initial_states SIM12); eauto.\n  intros [i [ f12 [s2 [A B]]]].\n  exploit (Injfsim_match_initial_states SIM23); eauto. intros [i' [f23 [s3 [C D]]]].\n  exists (i', i); exists (compose_meminj f12 f23); exists s3; split; auto. exists s2; auto.\n  exists f12, f23; repeat (split; auto). \n- (* final states *)\n  intros. destruct H as [s3 [ f12 [ f23 [A [B C]]]]].\n  eapply (Injfsim_match_final_states SIM23); eauto.\n  eapply (Injfsim_match_final_states SIM12); eauto.\n- (* simulation *)\n  intros. destruct H0 as [s3 [f12 [f23 [A [B C]]]]].\n  destruct i as [i2 i1]; simpl in *.\n  exploit (Injfsim_simulation' SIM12); eauto.\n  intros [[i1' [s3'[ f' [t' [D [E [F G]]]]]]] | [i1' [f' [D [E [F G]]]]]].\n  + (* L2 makes one or several steps. *)\n    exploit Injsimulation_plus; eauto.\n    intros [[i2' [f'' [s2' [t'' [P [? [? ?]]]]]]] | [i2' [f'' [P [Q [R SS]]]]]].\n* (* L3 makes one or several steps *)\n  exists (i2', i1').\n  exists s2'; exists (compose_meminj f' f''), t''. repeat (split; auto).\n  exists s3', f', f''; repeat (split; auto).\n  subst f.\n  eapply compose_inject_incr; eauto.\n  \n  eapply inject_trace_compose; eauto.\n  \n* (* L3 makes no step *)\n  exists (i2', i1'); exists s2; exists (compose_meminj f' f''), t'. repeat (split; auto).\n  right; split. subst t'; apply star_refl. left. auto.\n  exists s3', f', f''; auto.\n  repeat (split;auto).\n  subst f.\n  eapply compose_inject_incr; eauto.\n  subst t'; inv G. constructor.\n+ (* L2 makes no step *)\n  exists (i2, i1'); exists s2; exists (compose_meminj f' f23), t. repeat (split; auto).\n  right; split. subst t; apply star_refl. right. auto.\n  exists s3, f', f23; auto.\n  subst f.\n  eapply compose_inject_incr; eauto.\n  subst t; constructor.\n- (* symbols *)\n  intros. transitivity (Senv.public_symbol (symbolenv L2) id);\n            [eapply Injfsim_public_preserved|eapply Injfsim_public_preserved]; eauto.\n  Qed.\n\n  \n  (* Lemma injection_injection_composition:\n    forward_injection L1 L2 get_mem1 get_mem2 ->\n    forward_injection L2 L3 get_mem2 get_mem3 ->\n    forward_injection L1 L3 get_mem1 get_mem3.\n  Proof.\n    intros S12 S23.\n    inv S12; inv S23.\n    econstructor.\n    eapply injection_injection_composition'; eauto.\n  Qed. *)\n  \n  End Composition.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/compcert_new/common/ExposedSmallstep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.22624518377989253}}
{"text": "Require Import Zpower.\nRequire Import Zdiv.\nRequire Import List.\nRequire Import Metatheory.\nRequire Import syntax.\nRequire Import Coqlib.\nRequire Import alist.\nRequire Import vellvm_tactics.\n\n(*Require Import Coqlib_old.*)\n\n(* This file defines data layouts. *)\n\nModule LLVMtd.\n\nExport LLVMsyntax.\n\n(**\n Alignments come in two flavors: ABI and preferred. ABI alignment (abi_align,\n below) dictates how a type will be aligned within an aggregate and when used\n as an argument.  Preferred alignment (pref_align, below) determines a type's\n alignment when emitted as a global.\n\n Specifier string details:\n\n E|e: Endianness. \"E\" specifies a big-endian target data model, \"e\"\n specifies a little-endian target data model.\n\n p:size:abi_align:pref_align: Pointer size, ABI and preferred alignment.\n\n Type:size:abi_align:pref_align: Numeric type alignment. Type is one of i|f|v|a,\n corresponding to integer, floating point, or aggregate.  Size indicates the\n size, e.g., 32 or 64 bits.\n\n Note that in the case of aggregates, 0 is the default ABI and preferred\n alignment. This is a special case, where the aggregate's computed worst-case\n alignment will be used.\n\n At any case, if 0 is the preferred alignment, then the preferred alignment\n equals to its ABI alignment.\n\n  // Default alignments\n  align_type,      abi_align, pref_align, bit_width\n  INTEGER_ALIGN,   1,         1,          1   // i1\n  INTEGER_ALIGN,   1,         1,          8   // i8\n  INTEGER_ALIGN,   2,         2,          16  // i16\n  INTEGER_ALIGN,   4,         4,          32  // i32\n  INTEGER_ALIGN,   4,         8,          64  // i64\n  FLOAT_ALIGN,     4,         4,          32  // f32\n  FLOAT_ALIGN,     8,         8,          64  // f64\n  AGGREGATE_ALIGN, 0,         8,          0   // struct\n  PTR,             8,         8,          32  // ptr\n  BigEndian\n\n When LLVM is determining the alignment for a given type, it uses the following\n rules:\n   1. If the type sought is an exact match for one of the specifications, that\n      specification is used.\n   2. If no match is found, and the type sought is an integer type, then the\n      smallest integer type that is larger than the bitwidth of the sought type\n      is used. If none of the specifications are larger than the bitwidth then\n      the the largest integer type is used. For example, given the default\n      specifications above, the i7 type will use the alignment of i8 (next\n      largest) while both i65 and i256 will use the alignment of i64 (largest\n      specified).\n*)\n\nDefinition TargetData := (layouts * namedts)%type.\n\nDefinition DTD :=  (layout_be::\n                    layout_int Size.One Align.One Align.One::\n                    layout_int Size.Eight Align.One Align.One::\n                    layout_int Size.Sixteen Align.Two Align.Two::\n                    layout_int Size.ThirtyTwo Align.Four Align.Four::\n                    layout_int Size.SixtyFour Align.Four Align.Four::\n                    layout_float Size.ThirtyTwo Align.Four Align.Four::\n                    layout_float Size.SixtyFour Align.Four Align.Four::\n                    layout_aggr Size.Zero Align.Zero Align.Eight::\n                    layout_ptr Size.ThirtyTwo Align.Four Align.Four::nil).\n\n(** RoundUpAlignment - Round the specified value up to the next alignment\n    boundary specified by Alignment.  For example, 7 rounded up to an\n    alignment boundary of 4 is 8.  8 rounded up to the alignment boundary of 4\n    is 8 because it is already aligned. *)\nDefinition RoundUpAlignment (val alignment:nat) : nat :=\n  let zv := Z_of_nat val in\n  let za := Z_of_nat alignment in\n  let zr := zv + za in\n  nat_of_Z (zr / za * za).\n\n(** getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or\n    preferred if ABIInfo = false) the target wants for the specified datatype.\n*)\nFixpoint _getIntAlignmentInfo (los:layouts) (BitWidth: nat) (ABIInfo: bool)\n  (obest:option (nat*(nat*nat))) (olargest:option (nat*(nat*nat))) {struct los}\n    : option nat :=\n  match los with\n  | nil =>\n    (* Okay, we didn't find an exact solution.  Fall back here depending on what\n       is being looked for.\n\n       If we didn't find an integer alignment, fall back on most conservative. *)\n    match (obest, olargest) with\n    | (Some (_, (babi, bpre)), _) =>\n      (if ABIInfo then Some babi else Some bpre)\n    | (None, Some (_, (labi, lpre))) =>\n      (if ABIInfo then Some labi else Some lpre)\n    | _ => None\n    end\n  | (layout_int isz abi pre)::los' =>\n    if beq_nat (Size.to_nat isz) BitWidth\n    then\n      (* Check to see if we have an exact match and remember the best match we\n         see. *)\n      (if ABIInfo then Some (Align.to_nat abi) else Some (Align.to_nat pre))\n    else\n      (* The obest match so far depends on what we're looking for.\n         The \"obest match\" for integers is the smallest size that is larger than\n         the BitWidth requested.\n\n         However, if there isn't one that's larger, then we must use the\n         largest one we have (see below) *)\n      match (obest, olargest, le_lt_dec BitWidth (Size.to_nat isz)) with\n      | (Some (bestbt, _), Some (largestbt, _), left _ (* BitWidth <= isz *) ) =>\n        match (le_lt_dec largestbt (Size.to_nat isz)) with\n        | left _ (* isz <= largestbt *) =>\n          _getIntAlignmentInfo los' BitWidth ABIInfo obest olargest\n        | right _ (* largestbt < isz *) =>\n          _getIntAlignmentInfo los' BitWidth ABIInfo\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n        end\n\n      | (Some (bestbt, _), Some (largestbt, _), right _ (* isz < BitWidth *) ) =>\n        match (le_lt_dec largestbt (Size.to_nat isz)) with\n        | left _ (* isz <= largestbt *) =>\n          match (le_lt_dec (Size.to_nat isz) bestbt) with\n          | left _ (* bestbt <= isz *) =>\n            _getIntAlignmentInfo los' BitWidth ABIInfo obest olargest\n          | right _ (* isz < bestbt *) =>\n            _getIntAlignmentInfo los' BitWidth ABIInfo\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n          end\n        | right _ (* largestbt < isz *) =>\n          _getIntAlignmentInfo los' BitWidth ABIInfo\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n        end\n\n      | (None, Some (largestbt, _), left _ (* BitWidth <= isz *) ) =>\n        match (le_lt_dec largestbt (Size.to_nat isz)) with\n        | left _ (* isz <= largestbt *) =>\n          _getIntAlignmentInfo los' BitWidth ABIInfo obest olargest\n        | right _ (* largestbt < isz *) =>\n          _getIntAlignmentInfo los' BitWidth ABIInfo obest\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n        end\n\n      | (None, Some (largestbt, _), right _ (* isz < BitWidth *) ) =>\n        match (le_lt_dec largestbt (Size.to_nat isz)) with\n        | left _ (* isz <= largestbt *) =>\n          _getIntAlignmentInfo los' BitWidth ABIInfo\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n            olargest\n        | right _ (* largestbt < isz *) =>\n          _getIntAlignmentInfo los' BitWidth ABIInfo\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n        end\n\n      | (Some (bestbt, _), None, left _ (* BitWidth <= isz *) ) =>\n          _getIntAlignmentInfo los' BitWidth ABIInfo obest\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n      | (Some (bestbt, _), None, right _ (* isz < BitWidth *) ) =>\n          match (le_lt_dec (Size.to_nat isz) bestbt) with\n          | left _ (* bestbt <= isz *) =>\n            _getIntAlignmentInfo los' BitWidth ABIInfo obest\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n          | right _ (* isz < bestbt *) =>\n            _getIntAlignmentInfo los' BitWidth ABIInfo\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n          end\n      | (None, None, left _ (* BitWidth <= isz *) ) =>\n          _getIntAlignmentInfo los' BitWidth ABIInfo obest\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n      | (None, None, right _ (* isz < BitWidth *) ) =>\n          _getIntAlignmentInfo los' BitWidth ABIInfo\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n            (Some (Size.to_nat isz, (Align.to_nat abi, Align.to_nat pre)))\n      end\n  | _::los' =>\n    _getIntAlignmentInfo los' BitWidth ABIInfo obest olargest\n  end.\n\nDefinition getIntDefaultAlignmentInfo (BitWidth: nat) (ABIInfo: bool) : nat :=\n  match (le_lt_dec 1 BitWidth) with\n  | left _ (* BitWidth <= 1 *) => if BitWidth then 1%nat else 1%nat\n  | right _ (* 1 < BitWidth *) =>\n    match (le_lt_dec 8 BitWidth) with\n    | left _ (* BitWidth <= 8 *) => if BitWidth then 1%nat else 1%nat\n    | right _ (* 8 < BitWidth *) =>\n      match (le_lt_dec 16 BitWidth) with\n      | left _ (* BitWidth <= 16 *) => if BitWidth then 2%nat else 2%nat\n      | right _ (* 16 < BitWidth *) =>\n        match (le_lt_dec 32 BitWidth) with\n        | left _ (* BitWidth <= 32 *) => if BitWidth then 4%nat else 4%nat\n        | right _ (* 32 < BitWidth *) => if BitWidth then 4%nat else 8%nat\n        end\n      end\n    end\n  end.\n\nDefinition getIntAlignmentInfo (los:layouts) (BitWidth: nat) (ABIInfo: bool)\n  : nat :=\n  match (_getIntAlignmentInfo los BitWidth ABIInfo None None) with\n  | Some n => n\n  | None => getIntDefaultAlignmentInfo BitWidth ABIInfo\n  end.\n\n(** Target pointer alignment when ABIInfo is true\n    Return target's alignment for stack-based pointers when ABIInfo is false *)\nFixpoint _getPointerAlignmentInfo (los:layouts) (ABIInfo: bool) : option nat :=\n  match los with\n  | nil => None\n  | (layout_ptr psz abi pre)::_ =>\n      if ABIInfo then Some (Align.to_nat abi) else Some (Align.to_nat pre)\n  | _::los' => _getPointerAlignmentInfo los' ABIInfo\n  end.\n\nDefinition getPointerAlignmentInfo (los:layouts) (ABIInfo: bool) : nat :=\n  match (_getPointerAlignmentInfo los ABIInfo) with\n  | Some n => n\n  | None => 8%nat\n  end.\n\nFixpoint _getStructAlignmentInfo (los:layouts) (ABIInfo: bool) : option nat :=\n  match los with\n  | nil => None\n  | (layout_aggr sz abi pre)::_ =>\n      if ABIInfo then Some (Align.to_nat abi) else Some (Align.to_nat pre)\n  | _::los' => _getStructAlignmentInfo los' ABIInfo\n  end.\n\nDefinition getStructAlignmentInfo (los:layouts) (ABIInfo: bool) : nat :=\n  match (_getStructAlignmentInfo los ABIInfo) with\n  | Some n => n\n  | None => if ABIInfo then 0%nat else 8%nat\n  end.\n\n(** Target pointer size *)\nFixpoint _getPointerSize (los:layouts) : option sz :=\n  match los with\n  | nil => None\n  | (layout_ptr psz abi pre)::_ =>\n      Some (nat_of_Z (ZRdiv (Z_of_nat psz) 8))\n  | _::los' => _getPointerSize los'\n  end.\n\nDefinition getPointerSize0 (los:layouts) : sz := Size.Four.\n(* FIXME: ptr size is always 4-byte for the POPL submission\n  match (_getPointerSize los) with\n  | Some n => n\n  | None => Size.Four\n  end.\n*)\n\nDefinition getPointerSize (TD:TargetData) : sz :=\n  let '(td, _) := TD in\n  getPointerSize0 td.\n\n(** Target pointer size, in bits *)\nDefinition getPointerSizeInBits (los:layouts) : sz :=\n  Size.mul Size.Eight (getPointerSize0 los).\n\nFixpoint getFloatAlignmentInfo (los:layouts)  (BitWidth: nat) (ABIInfo: bool)\n    : nat :=\n  match los with\n  | nil =>\n    if beq_nat BitWidth 32\n    then 4%nat\n    else\n      if beq_nat BitWidth 64\n      then 8%nat\n      else getIntAlignmentInfo los BitWidth ABIInfo\n  | (layout_float isz abi pre)::los' =>\n    if beq_nat (Size.to_nat isz) BitWidth\n    then\n      Align.to_nat (if ABIInfo then abi else pre)\n    else\n      getFloatAlignmentInfo los' BitWidth ABIInfo\n  | _::los' => getFloatAlignmentInfo los' BitWidth ABIInfo\n  end.\n\n(** Merged getTypeSizeInBits, getTypeStoreSize, getTypeAllocSize,\n    getTypeAllocSizeInBits, getAlignment and getStructLayout\n\n    This internal version needs a mapping from named types to their\n    TypeSizeInBits and Alignment.\n\n    getTypeSizeInBits_and_Alignment uses the result calculated by\n      getTypeSizeInBits_and_Alignment_for_namedts\n*)\n\n(* Since Coq doesn't allow mutual recursion with nested inductives, we\n   have to do a small hack to use nested fixpoints and bind both\n   functions to a toplevel name *)\n\nDefinition _getListTypeSizeInBits_and_Alignment_aux\n  (_getTypeSizeInBits_and_Alignment :\n    layouts -> list (id * (nat * nat)) -> bool -> typ -> option (nat * nat)) :=\nfix _getListTypeSizeInBits_and_Alignment\n  (los:layouts) (nts:list (id*(nat*nat)))\n  (lt:list typ) {struct lt} : option (nat*nat) :=\n  let getTypeStoreSize :=\n      fun typeSizeInBits => nat_of_Z (ZRdiv (Z_of_nat typeSizeInBits) 8) in\n\n  let getTypeAllocSize :=\n      fun typeSizeInBits ABIalignment =>\n      (* Round up to the next alignment boundary *)\n      RoundUpAlignment (getTypeStoreSize typeSizeInBits) ABIalignment in\n\n  let getTypeAllocSizeInBits :=\n      fun typeSizeInBits ABIalignment =>\n      (getTypeAllocSize typeSizeInBits ABIalignment * 8)%nat in\n\n  match lt with\n  | nil => Some (0%nat, 0%nat)\n  | t :: lt' =>\n    (* getting ABI alignment *)\n    match (_getListTypeSizeInBits_and_Alignment los nts lt',\n           _getTypeSizeInBits_and_Alignment los nts true t) with\n    | (Some (struct_sz, struct_al), Some (sub_sz, sub_al)) =>\n          (* Add padding if necessary to align the data element properly. *)\n          (* Keep track of maximum alignment constraint. *)\n          (* Consume space for this data item *)\n          Some ((struct_sz + getTypeAllocSizeInBits sub_sz sub_al)%nat,\n                 match (le_lt_dec sub_al struct_al) with\n                 | left _ (* sub_al <= struct_al *) => struct_al\n                 | right _ (* struct_al < sub_al *) => sub_al\n                 end)\n    | _ => None\n    end\n  end.\n\nFixpoint _getTypeSizeInBits_and_Alignment\n  (los:layouts) (nts:list (id*(nat*nat)))\n  (abi_or_pref:bool) (t:typ) : option (nat*nat) :=\n  let getTypeStoreSize :=\n      fun typeSizeInBits => nat_of_Z (ZRdiv (Z_of_nat typeSizeInBits) 8) in\n\n  let getTypeAllocSize :=\n      fun typeSizeInBits ABIalignment =>\n      (* Round up to the next alignment boundary *)\n      RoundUpAlignment (getTypeStoreSize typeSizeInBits) ABIalignment in\n\n  let getTypeAllocSizeInBits :=\n      fun typeSizeInBits ABIalignment =>\n      (getTypeAllocSize typeSizeInBits ABIalignment * 8)%nat in\n\n  match t with\n  | typ_label => None\n                 (* Some (Size.to_nat (getPointerSizeInBits los),  *)\n                 (*       getPointerAlignmentInfo los abi_or_pref)  *)\n  | typ_pointer _ => Some (Size.to_nat (getPointerSizeInBits los),\n                           getPointerAlignmentInfo los abi_or_pref)\n\n  | typ_void => Some (8%nat, getIntAlignmentInfo los 8%nat abi_or_pref)\n\n  | typ_int sz => Some (Size.to_nat sz, getIntAlignmentInfo los (Size.to_nat sz)\n                        abi_or_pref)\n\n  | typ_array n t' =>\n    match n with\n    | O =>\n      (* Empty arrays have alignment of 1 byte. *)\n      Some (8%nat, 1%nat)\n    | _ =>\n      (* getting ABI alignment *)\n      match (_getTypeSizeInBits_and_Alignment los nts true t') with\n      | None => None\n      | Some (sz, al) =>\n          Some (((getTypeAllocSizeInBits sz al)*Size.to_nat n)%nat, al)\n      end\n    end\n\n  | typ_struct lt =>\n    (* Loop over each of the elements, placing them in memory. *)\n    match (_getListTypeSizeInBits_and_Alignment_aux _getTypeSizeInBits_and_Alignment los nts lt) with\n    | None => None\n    | (Some (sz, al)) =>\n      (* Empty structures have alignment of 1 byte. *)\n      (* Add padding to the end of the struct so that it could be put in an array\n         and all array elements would be aligned correctly. *)\n       match sz with\n       | O => Some (8%nat, 1%nat)\n       | _ => Some (sz, al)\n       end\n    end\n\n  | typ_floatpoint fp_float => \n      Some (32%nat, getFloatAlignmentInfo los 32%nat abi_or_pref) \n  | typ_floatpoint fp_double => \n      Some (64%nat, getFloatAlignmentInfo los 64%nat abi_or_pref) \n  | typ_floatpoint fp_x86_fp80 => None\n      (* Some (80%nat, getFloatAlignmentInfo los 64%nat abi_or_pref)  *)\n  | typ_floatpoint fp_fp128 => None\n      (* Some (128%nat, getFloatAlignmentInfo los 128%nat abi_or_pref)  *)\n  | typ_floatpoint fp_ppc_fp128 => None\n      (* Some (128%nat, getFloatAlignmentInfo los 128%nat abi_or_pref)  *)\n  | typ_metadata => None\n  | typ_function _ _ _ => None\n  | typ_namedt id0 => lookupAL _ nts id0\n  end.\n\nDefinition _getListTypeSizeInBits_and_Alignment :=\n  _getListTypeSizeInBits_and_Alignment_aux _getTypeSizeInBits_and_Alignment.\n\n(* calculate the TypeSizeInBits and Alignment for namedts\n   Assumption: nts[i] should only use named types from nts[j] where j > i\n   So, getTypeSizeInBits_and_Alignment_for_namedts rev-ed the orignal nts.\n   The well-formedness should check such invariant for named types.\n\n   With this invariant, we could have type\n\n   %1 = {%1*}\n   %2 = {%1}\n   %3 = {%2; %1, %3*}\n   %4 = {%5*}\n   %5 = {%4*}\n\n   But we cannot have\n\n   %1 = {%2}\n   %2 = {%1}\n*)\nFixpoint _getTypeSizeInBits_and_Alignment_for_namedts\n  (los:layouts) (nts:namedts) (abi_or_pref:bool)  : list (id*(nat*nat)) :=\nmatch nts with\n| nil => nil\n| (id0, ts0)::nts' =>\n  let results := _getTypeSizeInBits_and_Alignment_for_namedts los nts'\n                abi_or_pref in\n  match _getTypeSizeInBits_and_Alignment los results abi_or_pref \n         (typ_struct ts0) with\n  | None => results\n  | Some r => (id0, r)::results\n  end\nend.\n\nDefinition getTypeSizeInBits_and_Alignment_for_namedts\n  (TD:TargetData) (abi_or_pref:bool)  : list (id*(nat*nat)) :=\nlet (los, nts) := TD in\n_getTypeSizeInBits_and_Alignment_for_namedts los nts abi_or_pref.\n\n\nDefinition getTypeSizeInBits_and_Alignment (TD:TargetData) (abi_or_pref:bool)\n  (t:typ) : option (nat*nat) :=\n  let '(los, nts) := TD in\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts TD abi_or_pref)\n    abi_or_pref t.\n\n\nDefinition getListTypeSizeInBits_and_Alignment (TD:TargetData) (abi_or_pref:bool)\n  (lt:list typ) : option (nat*nat) :=\n  let '(los, nts) := TD in\n  _getListTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts TD abi_or_pref) lt.\n\n(** abi_or_pref Flag that determines which alignment is returned. true\n  returns the ABI alignment, false returns the preferred alignment.\n\n  Get the ABI (abi_or_pref == true) or preferred alignment (abi_or_pref\n  == false) for the requested type t.\n *)\nDefinition getAlignment (TD:TargetData) (t:typ) (abi_or_pref:bool) : option nat\n  :=\n  match (getTypeSizeInBits_and_Alignment TD abi_or_pref t) with\n  | (Some (sz, al)) => Some al\n  | None => None\n  end.\n\n(** getABITypeAlignment - Return the minimum ABI-required alignment for the\n    specified type. *)\nDefinition getABITypeAlignment (TD:TargetData) (t:typ) : option nat :=\n  getAlignment TD t true.\n\n(** getPrefTypeAlignment - Return the preferred stack/global alignment for\n    the specified type.  This is always at least as good as the ABI alignment. *)\nDefinition getPrefTypeAlignment (TD:TargetData) (t:typ) : option nat :=\n  getAlignment TD t false.\n\n(*\n Size examples:\n\n   Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]\n   ----        ----------  ---------------  ---------------\n    i1            1           8                8\n    i8            8           8                8\n    i19          19          24               32\n    i32          32          32               32\n    i100        100         104              128\n    i128        128         128              128\n    Float        32          32               32\n    Double       64          64               64\n    X86_FP80     80          80               96\n\n   [*] The alloc size depends on the alignment, and thus on the target.\n       These values are for x86-32 linux.\n*)\n\n(** getTypeSizeInBits - Return the number of bits necessary to hold the\n    specified type.  For example, returns 36 for i36 and 80 for x86_fp80. *)\nDefinition getTypeSizeInBits (TD:TargetData) (t:typ) : option nat :=\n  match (getTypeSizeInBits_and_Alignment TD true t) with\n  | (Some (sz, al)) => Some sz\n  | None => None\n  end.\n\n(** getTypeStoreSize - Return the maximum number of bytes that may be\n    overwritten by storing the specified type.  For example, returns 5\n    for i36 and 10 for x86_fp80. *)\nDefinition getTypeStoreSize (TD:TargetData) (t:typ) : option nat :=\n  match (getTypeSizeInBits TD t) with\n  | None => None\n  | Some sz => Some (nat_of_Z (ZRdiv (Z_of_nat sz) 8))\n  end.\n\n(** getTypeStoreSizeInBits - Return the maximum number of bits that may be\n    overwritten by storing the specified type; always a multiple of 8.  For\n    example, returns 40 for i36 and 80 for x86_fp80.*)\nDefinition getTypeStoreSizeInBits (TD:TargetData) (t:typ) : option nat :=\n  match (getTypeStoreSize TD t) with\n  | None => None\n  | Some n => Some (8*n)%nat\n  end.\n\n(** getTypeAllocSize - Return the offset in bytes between successive objects\n    of the specified type, including alignment padding.  This is the amount\n    that alloca reserves for this type.  For example, returns 12 or 16 for\n    x86_fp80, depending on alignment. *)\nDefinition getTypeAllocSize (TD:TargetData) (t:typ) : option sz :=\n  match (getTypeStoreSize TD t, getABITypeAlignment TD t) with\n  | (Some ss, Some ta) =>\n    (* Round up to the next alignment boundary *)\n    Some (RoundUpAlignment ss ta)\n  | _ => None\n  end.\n\n(** getTypeAllocSizeInBits - Return the offset in bits between successive\n    objects of the specified type, including alignment padding; always a\n    multiple of 8.  This is the amount that alloca reserves for this type.\n    For example, returns 96 or 128 for x86_fp80, depending on alignment. *)\nDefinition getTypeAllocSizeInBits (TD:TargetData) (t:typ) : option nat :=\n  match (getTypeAllocSize TD t) with\n  | None => None\n  | Some n => Some (8*n)%nat\n  end.\n\nDefinition getStructSizeInBytes (TD:TargetData) (t:typ) : option nat :=\nmatch t with\n| typ_struct lt =>\n  match (getTypeSizeInBits TD t) with\n  | Some sz => Some (nat_of_Z (ZRdiv (Z_of_nat sz) 8))\n  | None => None\n  end\n| _ => None\nend.\n\nDefinition getStructSizeInBits (TD:TargetData) (t:typ) : option nat :=\nmatch t with\n| typ_struct lt => getTypeSizeInBits TD t\n| _ => None\nend.\n\nDefinition getStructAlignment (TD:TargetData) (t:typ) : option nat :=\nmatch t with\n| typ_struct lt => getABITypeAlignment TD t\n| _ => None\nend.\n\nFixpoint _getStructElementOffset (TD:TargetData) (ts:list typ) (idx:nat)\n         (ofs : nat) : option nat :=\nmatch (ts, idx) with\n| (_, O) => Some ofs\n| (t :: ts', S idx') =>\n    match (getTypeAllocSize TD t, getABITypeAlignment TD t) with\n    | (Some sub_sz, Some sub_al) =>\n       _getStructElementOffset TD ts' idx' (ofs + RoundUpAlignment sub_sz sub_al)\n    | _ => None\n    end\n| _ => None\nend.\n\nDefinition getStructElementOffset (TD:TargetData) (t:typ) (idx:nat) : option nat\n  :=\nmatch t with\n| typ_struct lt => _getStructElementOffset TD lt idx 0\n| _ => None\nend.\n\nDefinition getStructElementOffsetInBits (TD:TargetData) (t:typ) (idx:nat)\n  : option nat :=\nmatch t with\n| typ_struct lt => match (_getStructElementOffset TD lt idx 0) with\n                   | None => None\n                   | Some n => Some (n*8)%nat\n                   end\n| _ => None\nend.\n\n(** getElementContainingOffset - Given a valid offset into the structure,\n    return the structure index that contains it. *)\nFixpoint _getStructElementContainingOffset (TD:TargetData) (ts:list typ)\n  (offset:nat) (idx:nat) (cur : nat) : option nat :=\nmatch ts with\n| nil => None\n| t :: ts' =>\n    match (getTypeAllocSize TD t, getABITypeAlignment TD t) with\n    | (Some sub_sz, Some sub_al) =>\n         match (le_lt_dec offset (RoundUpAlignment sub_sz sub_al + cur)) with\n         | left _ (* (RoundUpAlignment struct_sz sub_al + sub_sz) <= offset*)\n             => _getStructElementContainingOffset TD ts' offset (S idx)\n                   (RoundUpAlignment sub_sz sub_al + cur)\n         | right _ => Some idx\n         end\n    | _ => None\n    end\nend.\n\n(**\n   Multiple fields can have the same offset if any of them are zero sized.\n   For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop\n   at the i32 element, because it is the last element at that offset.  This is\n   the right one to return, because anything after it will have a higher\n   offset, implying that this element is non-empty.\n*)\nDefinition getStructElementContainingOffset (TD:TargetData) (t:typ) (offset:nat)\n  : option nat :=\nmatch t with\n| typ_struct lt => _getStructElementContainingOffset TD lt offset 0 0\n| _ => None\nend.\n\n(* FIXME: abi_or_pref cannot always be true,\n   We should use different flag when t types global or aggregate\n*)\n\n(* Check if a type has a finite size and a well-formed alignment. *)\nDefinition feasible_typs_aux_\n  (feasible_typ_aux :\n    layouts -> list (id * Prop) -> typ -> Prop) :=\nfix feasible_typs_aux los nts (lt:list typ) : Prop :=\nmatch lt with\n| nil => True\n| t :: lt' =>\n    feasible_typ_aux los nts t /\\ feasible_typs_aux los nts lt'\nend.\n\nFixpoint feasible_typ_aux los (nts:list (id*Prop)) t : Prop :=\nmatch t with\n| typ_int sz => \n    (getIntAlignmentInfo los (Size.to_nat sz) true > 0)%nat /\\\n    (sz > 0)%nat\n| typ_pointer _ => (getPointerAlignmentInfo los true > 0)%nat\n| typ_floatpoint fp_float => (getFloatAlignmentInfo los 32%nat true > 0)%nat\n| typ_floatpoint fp_double => (getFloatAlignmentInfo los 64%nat true > 0)%nat\n| typ_array _ t' => feasible_typ_aux los nts t'\n| typ_struct ts => feasible_typs_aux_ feasible_typ_aux los nts ts\n| typ_namedt nid =>\n    match lookupAL _ nts nid with\n    | Some re => re\n    | _ => False\n    end\n| _ => False\nend.\n\nDefinition feasible_typs_aux :=\n  feasible_typs_aux_ feasible_typ_aux.\n\nHint Unfold feasible_typs_aux.\n\nFixpoint feasible_typ_for_namedts (los:layouts) (nts:namedts)\n  : list (id*Prop) :=\nmatch nts with\n| nil => nil\n| (id0, ts0)::nts' =>\n  let results := feasible_typ_for_namedts los nts' in\n  (id0, feasible_typ_aux los results (typ_struct ts0))::results\nend.\n\nDefinition feasible_typ (TD:TargetData) t : Prop :=\nlet '(los, nts) := TD in\nfeasible_typ_aux los (feasible_typ_for_namedts los nts) t.\n\nDefinition feasible_typs (TD:TargetData) lt : Prop :=\nlet '(los, nts) := TD in\nfeasible_typs_aux los (feasible_typ_for_namedts los nts) lt.\n\n(* Properties of feasible_typ *)\nLemma RoundUpAlignment_spec : \n  forall a b, (b > 0)%nat -> (RoundUpAlignment a b >= a)%nat.\nProof.\n  intros. unfold RoundUpAlignment.\n  assert ((Z_of_nat a + Z_of_nat b) / Z_of_nat b * Z_of_nat b >= Z_of_nat a)%Z\n    as J.\n    apply Coqlib.roundup_is_correct.\n      destruct b; try solve [contradict H; omega | apply Coqlib.Z_of_S_gt_O].\n  apply nat_of_Z_inj_ge in J.\n  rewrite Coqlib.Z_of_nat_eq in J. auto.\nQed.\n\nLemma feasible_array_typ_inv : forall TD s t,\n  feasible_typ TD (typ_array s t) -> feasible_typ TD t.\nProof.\n  intros.\n  simpl in *.\n  unfold getTypeSizeInBits_and_Alignment in *.\n  destruct TD.\n  destruct (_getTypeSizeInBits_and_Alignment l0\n           (_getTypeSizeInBits_and_Alignment_for_namedts l0 n true)\n           true t) as [[]|]; eauto.\nQed.\n\nLemma feasible_struct_typ_inv : forall TD ts,\n  feasible_typ TD (typ_struct ts) -> feasible_typs TD ts.\nProof.\n  intros.\n  unfold feasible_typ in H.\n  unfold feasible_typs.\n  unfold getTypeSizeInBits_and_Alignment in *.\n  destruct TD.\n  simpl in *.\n  destruct (_getListTypeSizeInBits_and_Alignment l0\n           (_getTypeSizeInBits_and_Alignment_for_namedts l0 n true)\n           ts) as [[]|]; eauto.\nQed.\n\nLemma feasible_cons_typs_inv : forall TD t lt,\n  feasible_typs TD (t :: lt) ->\n  feasible_typ TD t /\\ feasible_typs TD lt.\nProof.\n  intros. destruct TD as [los nts].\n  simpl in *. auto.\nQed.\n\nLemma feasible_nil_typs: forall TD, feasible_typs TD nil.\nProof. destruct TD; simpl; auto. Qed.\n\nLemma feasible_cons_typs: forall TD t lt,\n  feasible_typs TD (t :: lt) <->\n  feasible_typ TD t /\\ feasible_typs TD lt.\nProof. destruct TD; simpl. intros. split; auto. Qed.\n\nDefinition feasible_typ_aux_weaken_prop (t:typ) := forall los nm1 nm2,\n  uniq (nm2++nm1) ->\n  feasible_typ_aux los nm1 t ->\n  feasible_typ_aux los (nm2++nm1) t.\n\nDefinition feasible_typs_aux_weaken_prop (lt:list typ) :=\n  forall los nm1 nm2,\n  uniq (nm2++nm1) ->\n  feasible_typs_aux los nm1 lt ->\n  feasible_typs_aux los (nm2++nm1) lt.\n\nLemma feasible_typ_aux_weaken_mutrec :\n  (forall t, feasible_typ_aux_weaken_prop t) /\\\n  (forall lt, feasible_typs_aux_weaken_prop lt).\nProof.\n  (typ_cases (apply typ_mutind; \n    unfold feasible_typ_aux_weaken_prop, \n           feasible_typs_aux_weaken_prop) Case);\n    intros; simpl in *; try solve [eauto | inversion H | inversion H1 ].\nCase \"typ_struct\".\n  apply H; trivial.\nCase \"typ_namedt\".\n  inv_mbind.\n  erewrite lookupAL_weaken; eauto.\nCase \"typ_cons\".\n  destruct H2.\n  split; eauto.\nQed.\n\nLemma feasible_typ_aux_weaken: forall t los nm1 nm2,\n  uniq (nm2++nm1) ->\n  feasible_typ_aux los nm1 t ->\n  feasible_typ_aux los (nm2++nm1) t.\nProof.\n  destruct feasible_typ_aux_weaken_mutrec as [J _].\n  unfold feasible_typ_aux_weaken_prop in J. auto.\nQed.\n\nLemma feasible_typ_for_namedts_dom: forall los nm,\n  dom (feasible_typ_for_namedts los nm) [=] dom nm.\nProof.\n  induction nm as [|[]]; simpl; fsetdec.\nQed.\n\nLemma feasible_typ_for_namedts_uniq: forall los nm\n  (Huniq: uniq nm), uniq (feasible_typ_for_namedts los nm).\nProof.\n  induction 1; simpl; auto.\n    simpl_env.\n    constructor; auto.\n      assert (J:=@feasible_typ_for_namedts_dom los E).\n      fsetdec.\nQed.\n\nLemma feasible_typ_for_namedts_cons : forall los nm1 nm2,\n  exists re,\n    feasible_typ_for_namedts los (nm2++nm1) =\n      re ++ feasible_typ_for_namedts los nm1.\nProof.\n  induction nm2 as [|[]]; simpl.\n    exists nil. auto.\n\n    destruct IHnm2 as [re IHnm2].\n    rewrite IHnm2.\n    simpl_env. eauto.\nQed.\n\nLemma feasible_typ_aux_weakening: forall los t\n  (nm1 nm2:namedts) (Huniq: uniq (nm2++nm1)),\n  feasible_typ_aux los (feasible_typ_for_namedts los nm1) t ->\n  feasible_typ_aux los (feasible_typ_for_namedts los (nm2++nm1)) t.\nProof.\n  intros.  \n  destruct (@feasible_typ_for_namedts_cons los nm1 nm2) as [re J].\n  rewrite J.\n  apply feasible_typ_aux_weaken; auto.\n    unfold id in *.\n    rewrite <- J.\n    eapply feasible_typ_for_namedts_uniq; eauto.\nQed.\n\nLemma feasible_typ_for_namedts_spec1: forall los nts2 lt2 i0 r nts1 nts\n  (Huniq: uniq nts),\n  lookupAL _ (feasible_typ_for_namedts los nts) i0 = Some r ->\n  nts = nts1 ++ (i0,lt2) :: nts2 ->  \n  feasible_typs_aux los (feasible_typ_for_namedts los nts2) lt2 = r.\nProof.\n  induction nts1 as [|[]]; intros; subst; simpl in *.\n    destruct (i0 == i0); unfold feasible_typs_aux; try congruence; auto.\n\n    inv Huniq.\n    simpl_env in H4.\n    destruct (i0 == a); subst.\n      contradict H4; fsetdec.\n      apply IHnts1 in H; auto.\nQed.\n\nLemma feasible_typ_for_namedts_spec2: forall los i0 r nts2 \n  lt2 nts1 nts (Huniq: uniq nts),\n  feasible_typs_aux los (feasible_typ_for_namedts los nts2) lt2 = r ->\n  nts = nts1 ++ (i0,lt2) :: nts2 ->  \n  lookupAL _ (feasible_typ_for_namedts los nts) i0 = Some r.\nProof.\n  induction nts1 as [|[]]; intros; subst; simpl in *.\n    destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i0 i0); \n      try congruence; auto.\n     \n    inv Huniq.\n    simpl_env in H3.\n    destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i0 i1); subst.\n      contradict H3; fsetdec.\n      eapply IHnts1 in H1; eauto.\nQed.\n\nLemma feasible_typ_spec1: forall (los : layouts) (i0 : id)\n  (nts : namedts) (lt2 : list typ) r\n  (HeqR : Some lt2 = lookupAL (list typ) nts i0) (Huniq: uniq nts)\n  (H:lookupAL _ (feasible_typ_for_namedts los nts) i0 = Some r),\n  r -> feasible_typs_aux los (feasible_typ_for_namedts los nts) lt2.\nProof.\n  intros. \n  assert (exists nts1, exists nts2, nts = nts1 ++ (i0,lt2) :: nts2) as J.\n    apply lookupAL_middle_inv; auto.\n  destruct J as [nts1 [nts2 J]]; subst.\n  eapply feasible_typ_for_namedts_spec1 with (nts1:=nts1) (nts2:=nts2) in H; \n    eauto.\n  rewrite_env ((nts1 ++ [(i0, lt2)]) ++ nts2).\n  change (feasible_typ_aux los\n    (feasible_typ_for_namedts los ((nts1 ++ [(i0, lt2)]) ++ nts2)) \n    (typ_struct lt2)).\n  eapply feasible_typ_aux_weakening; simpl_env; eauto.\n  simpl. fold feasible_typs_aux. rewrite H. auto.\nQed.\n\nDefinition feasible_typ_aux__getTypeSizeInBits_and_Alignment_prop' (t:typ) := \n  forall los nm1 nm2,\n  feasible_typ_aux los nm1 t -> \n  (forall (i0 : id) (P : Prop) (HeqR : Some P = lookupAL Prop nm1 i0) (H : P),\n   exists sz0 : nat,\n     exists al : nat,\n       lookupAL (nat * nat) nm2 i0 = Some (sz0, al) /\\ \n       (sz0 > 0)%nat /\\ (al > 0)%nat) ->\n  exists sz, exists al,\n    _getTypeSizeInBits_and_Alignment los nm2 true t = Some (sz, al) /\\ \n    (sz > 0)%nat /\\ (al > 0)%nat.\n\nDefinition feasible_typs_aux__getListTypeSizeInBits_and_Alignment_prop'\n  (lt:list typ) := forall los nm1 nm2,\n  feasible_typs_aux los nm1 lt ->\n  (forall (i0 : id) (P : Prop) (HeqR : Some P = lookupAL Prop nm1 i0) (H : P),\n   exists sz0 : nat,\n     exists al : nat,\n       lookupAL (nat * nat) nm2 i0 = Some (sz0, al) /\\ \n       (sz0 > 0)%nat /\\ (al > 0)%nat) ->\n  (forall t, In t lt -> feasible_typ_aux los nm1 t) /\\\n  exists sz, exists al,\n    _getListTypeSizeInBits_and_Alignment los nm2 lt = Some (sz,al) /\\\n    ((sz > 0)%nat -> (al > 0)%nat).\n\nLemma feasible_typ_aux__getTypeSizeInBits_and_Alignment_mutrec' :\n  (forall t, feasible_typ_aux__getTypeSizeInBits_and_Alignment_prop' t) /\\\n  (forall lt, feasible_typs_aux__getListTypeSizeInBits_and_Alignment_prop' lt).\nProof.\n  (typ_cases (apply typ_mutind;\n    unfold feasible_typ_aux__getTypeSizeInBits_and_Alignment_prop', \n           feasible_typs_aux__getListTypeSizeInBits_and_Alignment_prop') Case);\n    intros;\n    unfold getTypeSizeInBits_and_Alignment in *;\n    simpl in *; try (destruct TD);\n    try solve [eauto | inversion H | inversion H1 | destruct H; eauto].\nCase \"typ_floatingpoint\".\n  destruct f0; try solve [inv H].\n    exists 32%nat. exists (getFloatAlignmentInfo los 32 true).\n    split; auto. omega.\n\n    exists 64%nat. exists (getFloatAlignmentInfo los 64 true).\n    split; auto. omega.\nCase \"typ_array\".\n  eapply H in H0; eauto.\n  destruct H0 as [sz [al [J1 [J2 J3]]]].\n  rewrite J1.\n  destruct s.\n    exists 8%nat. exists 1%nat. split; auto. omega.\n\n    exists (RoundUpAlignment\n               (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8)) al * 8 *\n             Size.to_nat (S s))%nat.\n    exists al. split; auto. split; auto.\n    assert (RoundUpAlignment (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8)) al\n      >= (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8)))%nat as J4.\n      apply RoundUpAlignment_spec; auto.\n    assert (Coqlib.ZRdiv (Z_of_nat sz) 8 > 0) as J5.\n      apply Coqlib.ZRdiv_prop3; try omega.\n    apply nat_of_Z_inj_gt in J5; try omega.\n    simpl in J5.\n    assert (RoundUpAlignment (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8)) al\n      * 8 > 0)%nat as J6. omega. clear J4 J5.\n    assert (Size.to_nat (S s) > 0)%nat as J7. unfold Size.to_nat. omega.\n    remember (RoundUpAlignment (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8)) \n      al * 8)%nat as R1. \n    remember (Size.to_nat (S s)) as R2. \n    clear - J6 J7.\n    assert (0 * R2 < R1 * R2)%nat as J.\n      apply mult_lt_compat_r; auto.\n    simpl in J. auto.\n\nCase \"typ_struct\".\n  eapply H in H0; eauto.\n  destruct H0 as [J0 [sz [al [J1 J2]]]].\n  unfold _getListTypeSizeInBits_and_Alignment in J1.\n  rewrite J1.\n  destruct sz.\n    exists 8%nat. exists 1%nat. split; auto. omega.\n    exists (S sz0). exists al. split; auto. omega. \n\nCase \"typ_pointer\".\n  unfold LLVMtd.feasible_typ_aux in H0. simpl in H0.\n  unfold getPointerSizeInBits, Size.to_nat.\n  simpl.\n  exists 32%nat. exists (getPointerAlignmentInfo los true).\n  split; auto. omega.\n\nCase \"typ_namedt\".\n  match goal with\n  | H: match ?x with\n       | Some _ => _\n       | None => False\n       end |- _ => remember x as R; destruct R as [|]; tinv H; eauto\n  end.\n  \nCase \"typ_nil\".\n  split.\n    intros. tauto.\n    simpl. exists 0%nat. exists 0%nat. split; auto.\n\nCase \"typ_cons\".\n  destruct H1 as [J1 J2]. \n  eapply H0 in J2; eauto.\n  destruct J2 as [J21 [sz2 [al2 [J22 J23]]]].\n  split.\n    intros. \n    destruct H1 as [H1 | H1]; subst; auto.\n      \n    simpl.\n    unfold getListTypeSizeInBits_and_Alignment in J22.\n    unfold getTypeSizeInBits_and_Alignment_for_namedts in J22.\n    rewrite J22.\n    eapply H in J1; eauto.\n    destruct J1 as [sz1 [al1 [J11 [J12 J13]]]].\n    unfold getTypeSizeInBits_and_Alignment_for_namedts in J11.\n    rewrite J11.\n    destruct (le_lt_dec al1 al2); eauto.\n      exists (sz2 +\n             RoundUpAlignment\n               (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz1) 8)) al1 * 8)%nat.\n      exists al2.\n      split; auto.\n        intros. clear - J13 l1. omega.\nQed.\n\nLemma feasible_typ_aux__getTypeSizeInBits_and_Alignment : forall t los nm1 nm2,\n  feasible_typ_aux los nm1 t -> \n  (forall (i0 : id) (P : Prop) (HeqR : Some P = lookupAL Prop nm1 i0) (H : P),\n   exists sz0 : nat,\n     exists al : nat,\n       lookupAL (nat * nat) nm2 i0 = Some (sz0, al) /\\ \n       (sz0 > 0)%nat /\\ (al > 0)%nat) ->\n  exists sz, exists al,\n    _getTypeSizeInBits_and_Alignment los nm2 true t = Some (sz, al) /\\ \n    (sz > 0)%nat /\\ (al > 0)%nat.\nProof.\n  destruct feasible_typ_aux__getTypeSizeInBits_and_Alignment_mutrec'; auto.\nQed.\n\nLemma feasible_typs_aux__getListTypeSizeInBits_and_Alignment :\n  forall (lt:list typ) los nm1 nm2,\n  feasible_typs_aux los nm1 lt ->\n  (forall (i0 : id) (P : Prop) (HeqR : Some P = lookupAL Prop nm1 i0) (H : P),\n   exists sz0 : nat,\n     exists al : nat,\n       lookupAL (nat * nat) nm2 i0 = Some (sz0, al) /\\ \n       (sz0 > 0)%nat /\\ (al > 0)%nat) ->\n  (forall t, In t lt -> feasible_typ_aux los nm1 t) /\\\n  exists sz, exists al,\n    _getListTypeSizeInBits_and_Alignment los nm2 lt = Some (sz,al) /\\\n    ((sz > 0)%nat -> (al > 0)%nat).\nProof.\n  destruct feasible_typ_aux__getTypeSizeInBits_and_Alignment_mutrec'; auto.\nQed.\n\nLemma feasible_typ_for_namedts__getTypeSizeInBits_and_Alignment_for_namedts: \n  forall los nts (i0 : id) (P : Prop),\n  Some P = lookupAL Prop (feasible_typ_for_namedts los nts) i0 ->\n  P ->\n  exists sz0 : nat,\n    exists al : nat,\n      lookupAL (nat * nat)\n        (_getTypeSizeInBits_and_Alignment_for_namedts los nts true) i0 =\n      Some (sz0, al) /\\ (sz0 > 0)%nat /\\ (al > 0)%nat.\nProof.\n  induction nts as [|[i1 lt1]]; simpl; intros.\n    congruence.\n\n    destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i0 i1); subst.\n      inv H.\n      eapply feasible_typs_aux__getListTypeSizeInBits_and_Alignment in H0; eauto.\n      destruct H0 as [_ [sz [al [J1 J2]]]].\n      unfold _getListTypeSizeInBits_and_Alignment in J1.\n      rewrite J1.\n      destruct sz as [|sz].\n        simpl. \n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i1 i1); \n          subst; try congruence.\n        exists 8%nat. exists 1%nat. split; auto. split; omega.\n\n        simpl. \n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i1 i1); \n          subst; try congruence.\n        exists (S sz). exists al. \n        split; auto. omega.\n\n      apply IHnts with (P:=P) in H; auto.\n      destruct H as [sz [al [J1 J2]]].\n      match goal with\n      | |- exists _, exists _, \n             lookupAL _ (match ?x with\n                        | Some _ => _\n                        | None => _\n                        end) _ = _ /\\ _ => destruct x\n      end.\n        simpl.\n        destruct (@eq_dec atom (EqDec_eq_of_EqDec atom EqDec_atom) i0 i1); \n          try congruence. \n        rewrite J1.\n        exists sz. exists al. split; auto.\n\n        rewrite J1.\n        exists sz. exists al. split; auto.\nQed.\n\nLemma feasible_typ_inv : forall t TD,\n  feasible_typ TD t ->\n  exists sz, exists al,\n    getTypeSizeInBits_and_Alignment TD true t = Some (sz, al) /\\ \n    (sz > 0)%nat /\\ (al > 0)%nat.\nProof.\n  unfold feasible_typ, getTypeSizeInBits_and_Alignment.\n  destruct TD as [los nts].\n  intros.\n  eapply feasible_typ_aux__getTypeSizeInBits_and_Alignment; eauto.\n  unfold getTypeSizeInBits_and_Alignment_for_namedts.\n  apply feasible_typ_for_namedts__getTypeSizeInBits_and_Alignment_for_namedts.\nQed.\n\nLemma feasible_typ_inv' : forall t TD,\n  feasible_typ TD t ->\n  exists sz, exists al,\n    getTypeSizeInBits_and_Alignment TD true t = Some (sz, al) /\\ (al > 0)%nat.\nProof.\n  intros.\n  apply feasible_typ_inv in H.\n  destruct H as [sz [al [H1 [H2 H3]]]]; eauto.\nQed.\n\n(* Properties of getTypeAllocSize *)\nLemma getTypeAllocSize_inv : forall TD typ5 sz,\n  getTypeAllocSize TD typ5 = Some sz ->\n  exists sz0, exists al0, getABITypeAlignment TD typ5 = Some al0 /\\\n    getTypeSizeInBits_and_Alignment TD true typ5 = Some (sz0, al0) /\\\n    sz = RoundUpAlignment (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz0) 8)) al0.\nProof.\n  intros.\n  unfold getTypeAllocSize in H.\n  unfold getTypeStoreSize in H.\n  unfold getTypeSizeInBits in H.\n  unfold getABITypeAlignment in *.\n  unfold getAlignment in *.\n  remember (getTypeSizeInBits_and_Alignment TD true typ5) as R.\n  destruct R as [[sz1 al1]|]; inv H.\n  eauto.\nQed.\n\nLemma getTypeAllocSize_inv' : forall los nts typ5 sz sz2 al2,\n  getTypeAllocSize (los,nts) typ5 = Some sz ->\n  _getTypeSizeInBits_and_Alignment los\n         (_getTypeSizeInBits_and_Alignment_for_namedts los nts true)\n         true typ5 = Some (sz2, al2) ->\n  sz = RoundUpAlignment (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz2) 8)) al2.\nProof.\n  intros.\n  apply getTypeAllocSize_inv in H.\n  destruct H as [sz1 [al1 [J1 [J2 J3]]]].\n  unfold getTypeSizeInBits_and_Alignment in J2.\n  unfold getTypeSizeInBits_and_Alignment_for_namedts in J2.\n  rewrite J2 in H0. inv H0. auto.\nQed.\n\nLemma getTypeAllocSize_roundup : forall los nts sz2 al2 t\n  (H31 : feasible_typ (los, nts) t)\n  (J6 : _getTypeSizeInBits_and_Alignment los\n         (_getTypeSizeInBits_and_Alignment_for_namedts los nts true)\n         true t = Some (sz2, al2))\n  (s0 : sz) (HeqR3 : Some s0 = getTypeAllocSize (los, nts) t),\n  ((Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz2) 8)) +\n    (s0 - (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz2) 8))))%nat = s0.\nProof.\n  intros.\n  unfold getTypeAllocSize, getABITypeAlignment, getAlignment, getTypeStoreSize,\n    getTypeSizeInBits, getTypeSizeInBits_and_Alignment,\n    getTypeSizeInBits_and_Alignment_for_namedts in HeqR3.\n  rewrite J6 in HeqR3.\n  inv HeqR3.\n  assert (RoundUpAlignment (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz2) 8))\n      al2 >= (Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz2) 8)))%nat as J8.\n    apply RoundUpAlignment_spec.\n      eapply feasible_typ_inv' in H31; eauto.\n      destruct H31 as [sz0 [al0 [J13 J14]]].\n      unfold getTypeSizeInBits_and_Alignment,\n             getTypeSizeInBits_and_Alignment_for_namedts in J13.\n      rewrite J6 in J13. inv J13. auto.\n  rewrite <- le_plus_minus; auto.\nQed.\n\n(* A layout is well-formed if its alignments are positive. *)\nDefinition wf_layouts (los:layouts) : Prop :=\nforall ABInfo,\n  (getPointerAlignmentInfo los ABInfo > 0)%nat /\\\nforall BitWidth,\n  (getIntAlignmentInfo los BitWidth ABInfo > 0)%nat /\\\n  (getFloatAlignmentInfo los BitWidth ABInfo > 0)%nat.\n\nEnd LLVMtd.\n", "meta": {"author": "snu-sf", "repo": "crellvm-vellvm", "sha": "54c7cc88ab5b4aec4c327f501cac4d9a667ca057", "save_path": "github-repos/coq/snu-sf-crellvm-vellvm", "path": "github-repos/coq/snu-sf-crellvm-vellvm/crellvm-vellvm-54c7cc88ab5b4aec4c327f501cac4d9a667ca057/src/Vellvm/targetdata.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.22610127480488273}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Frederic Blanqui, 2009-11-02\n\nviolation of variable condition\n*)\n\nSet Implicit Arguments.\n\nFrom CoLoR Require Import LogicUtil ATrs AVariables BoolUtil EqUtil ListUtil RelUtil\n  NatUtil APosition.\n\nSection S.\n\n  Variable Sig : Signature.\n\n  Notation rules := (rules Sig).\n\n  Lemma var_cond_mod : forall E R : rules,\n    ~rules_preserve_vars R -> EIS (red_mod E R).\n\n  Proof.\n    intros E R. rewrite <- brules_preserve_vars_ok, <- false_not_true.\n    unfold brules_preserve_vars.\n    rewrite (forallb_neg (@brule_preserve_vars_ok Sig)).\n    intros [[l r] [h1 h2]]. simpl in *. rewrite not_incl in h2.\n    2: apply eq_nat_dec.\n    destruct h2. destruct H. destruct (in_vars_subterm H). rename x0 into p.\n    destruct (subterm_pos_elim H1). rename x0 into c. destruct a.\n    set (s := single x l). set (f := iter l (fill (subc s c))).\n    exists f. unfold IS. induction i; simpl in *. exists (f 0). split.\n    apply rt_refl. exists l. exists r. exists Hole. simpl. exists s.\n    repeat split. hyp. unfold s. rewrite sub_single_not_var. refl. hyp.\n    rewrite H3, sub_fill. unfold s, single. simpl.\n    rewrite (beq_refl beq_nat_ok). refl. unfold f. apply red_mod_fill. hyp.\n  Qed.\n\n  Lemma var_cond : forall R : rules, ~rules_preserve_vars R -> EIS (red R).\n\n  Proof. intros. rewrite <- red_mod_empty. apply var_cond_mod. hyp. Qed.\n\nEnd S.\n\nLtac var_cond Sig :=\n  (apply var_cond_mod || apply var_cond);\n    rewrite <- (ko (@brules_preserve_vars_ok Sig));\n      (check_eq || fail 10 \"variable condition satisfied\").\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/NonTermin/AVarCond.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2260815661765325}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import String.\n\n(* Borrow from CompCert *)\nRequire Import Cryptol.Coqlib.\nRequire Import Cryptol.Bitvectors.\n\nRequire Import Cryptol.AST.\nRequire Import Cryptol.Semantics.\nRequire Import Cryptol.Utils.\nRequire Import Cryptol.Builtins.\nRequire Import Cryptol.BuiltinSem.\nRequire Import Cryptol.BuiltinSyntax.\nRequire Import Cryptol.Values.        \nRequire Import Cryptol.Bitstream.\nRequire Import Cryptol.Lib.\nRequire Import Cryptol.GlobalExtends.\nRequire Import Cryptol.GetEachN.\n\nRequire Import Cryptol.EvalTac.\nRequire Import Cryptol.Eager.\n\nImport HaskellListNotations.\nOpen Scope string.\n\nRequire Import HMAC.HMAC.\n\nRequire Import HMAC.HMAC_spec.\n\nRequire Import HMAC.HMAC_lib.\n\nRequire Import HMAC.Kinit_eval.\n\n\n(* lemma for when the length of the key is the same as the length of the block *)\nLemma Hmac_eval_keylen_is_blocklength :\n  forall (key : ext_val) keylen,\n    has_type key (bytestream keylen) -> \n    forall GE TE SE, \n      wf_env ge GE TE SE ->\n      (forall id, In id [(371, \"ks\");(372, \"okey\");(373, \"ikey\");(374, \"internal\")] -> GE id = None) ->\n      forall h hf,\n        good_hash h GE TE SE hf ->\n        forall msg msglen unused,\n          has_type msg (bytestream msglen) ->\n          exists v,\n            eager_eval_expr GE TE SE (apply (tapply (EVar hmac) ((typenum (Z.of_nat msglen)) :: (typenum (Z.of_nat keylen)) :: (typenum unused) :: (typenum (Z.of_nat keylen)) :: nil)) (h :: h :: h :: (EValue key) :: (EValue msg) :: nil)) (to_sval v) /\\ hmac_model hf key msg = Some v.\nProof.\n  intros.\n  rename H into Hkeytype.\n  rename H1 into HIDs.\n  rename H2 into Hgood_hash.\n  rename H3 into Hmsgtype.\n  init_globals ge.\n  abstract_globals ge.\n  edestruct good_hash_complete_eval; eauto.\n  repeat break_exists.\n  destruct H.\n\n  inversion Hkeytype. subst.\n  inversion Hmsgtype. subst.\n  remember (hf (eseq (map (fun x3 : ext_val => xor_const 54 x3) l ++ l0))) as hv1.\n  assert (HT : exists n, has_type hv1 (tseq n tbit)). {\n    assert (exists n, has_type (eseq (map (fun x3 : ext_val => xor_const 54 x3) l ++ l0)) (bytestream n)). {\n      eexists. econstructor.\n      rewrite Forall_app. split.\n      eapply Forall_map. eauto.\n      intros. eapply xor_const_byte; eauto.\n      eauto.\n    }\n    break_exists.\n    eapply H1 in H2.\n    repeat break. subst. eauto.\n  }\n  break_exists.\n  edestruct ext_val_list_of_strictval; try eassumption.\n  \n  eexists; split.\n  \n  e. e. e. e. e. e. e. e. e.\n  gen_global hmac.\n  ag.\n  \n  e.\n  e.\n  e.\n  e.\n  e. e.\n  e.\n  e.\n  e.\n  e.\n  e.\n\n  e.\n  e. \n  lv.\n  e. e. e. e. e. \n\n  ag.\n\n  e. e.\n  e. e.\n\n  g.\n  e.\n\n  (* evaluate the match *)\n  econstructor. econstructor.\n\n  g.\n\n  (* call Kinit function *)\n  (* START *)\n  {\n    eapply kinit_eval.\n    solve_wf_env.\n    exact Hkeytype.\n    eapply good_hash_same_eval; eauto.\n    gex.\n    lv. et. et. et. lv.\n  }  (* END *)\n  \n  simpl.\n  rewrite list_of_strictval_of_strictlist. \n  reflexivity.\n  \n  (* Begin model section *)\n  {\n    eapply eager_eval_bind_senvs. eassumption.\n    instantiate (1 := fun x => to_sval (xor_const 92 x)).  \n    intros. e. e. e.\n    ag.\n    e. e. lv. e. e. e. ag.\n    e. e. e. \n    reflexivity.\n    e. lv. lv. \n    simpl. \n    inversion H6. subst. simpl.\n    unfold strictnum.\n    unfold Z.to_nat. unfold Pos.to_nat.\n    unfold Pos.iter_op. unfold Init.Nat.add.\n    rewrite xor_num. reflexivity.\n    rewrite H7. eassumption.\n    congruence.\n  }\n  (* End model section *)\n\n  e. g.\n  e. e. e. e. ag.\n  e. e. e. e. e. lv. e. e. e. e. e. ag.\n  e. e. e. e. g.\n  e. ec. ec. \n  g.\n  { (* TODO: make this one tactic *)\n    eapply kinit_eval.\n    solve_wf_env.\n    exact Hkeytype.\n    eapply good_hash_same_eval; eauto.\n    gex.\n    lv. et. et. et. lv.\n  }\n  simpl.\n  rewrite list_of_strictval_of_strictlist. \n  reflexivity.\n\n  eapply eager_eval_bind_senvs. eassumption.\n  instantiate (1 := fun x => to_sval (xor_const 54 x)).  \n  intros. e. e. e. ag. \n  e. e. lv. e. e. e. ag. \n  e. e. e. reflexivity.\n  e. lv. lv.\n  inversion H6. subst. simpl.\n  unfold strictnum.\n  rewrite xor_num. reflexivity.\n  rewrite H7. eassumption.\n  simpl. unfold Pos.to_nat. simpl. congruence.\n\n  e. lv. e. lv. lv. \n\n  unfold to_sval. fold to_sval.  \n  rewrite append_strict_list. \n  reflexivity.\n\n  eapply global_extends_eager_eval.\n\n  replace (map (fun x3 : ext_val => to_sval (xor_const 54 x3)) l) with\n      (map to_sval (map (fun x3 => xor_const 54 x3) l)) by (rewrite list_map_compose; reflexivity).\n  rewrite <- list_append_map.\n  remember (app (map (fun x3 : ext_val => xor_const 54 x3) l) l0) as ll.\n  replace (strict_list (map to_sval ll)) with (to_sval (eseq ll)) by (reflexivity).\n  subst ll.\n  \n  eapply H1.\n  econstructor.\n\n  rewrite Forall_app. split; auto.\n  eapply Forall_map. eassumption.\n\n  intros. eapply xor_const_byte; eauto.\n\n  unfold bind_decl_groups.\n  unfold bind_decl_group.\n  unfold declare.\n\n  gex.\n\n  e. lv.\n\n  simpl.\n  rewrite <- Heqhv1.\n  rewrite H3. reflexivity.\n  \n  e. lv. lv.\n\n  rewrite append_strict_list. reflexivity.\n  eapply global_extends_eager_eval.\n\n  (* get to_sval out to outside *)\n  (* evaluate the hash function *)\n\n  replace (map (fun x4 : ext_val => to_sval (xor_const 92 x4)) l) with\n  (map to_sval (map (xor_const 92) l)) by\n      (clear -l; \n       induction l; simpl; auto; f_equal; eapply IHl; eauto).\n    \n  rewrite get_each_n_map_commutes.\n\n  rewrite map_strict_list_map_map_to_sval.\n  rewrite <- list_append_map.\n  rewrite strict_list_map_to_sval.\n\n  assert (exists n, has_type (eseq (map (xor_const 92) l ++ map eseq (get_each_n (Pos.to_nat 8) x4))) (bytestream n)). {\n    eapply has_type_seq_append.\n    exists (Datatypes.length (map (xor_const 92) l)).\n    econstructor.\n    eapply Forall_map. eassumption.\n    intros. eapply xor_const_byte; eauto.\n    subst hv1.\n    inversion H2. subst.\n    rewrite <- H6 in *.\n    eapply list_of_strictval_to_sval in H3. inversion H3.\n    subst. \n    remember H1 as HHash.\n    clear HeqHHash.\n    symmetry in H6.    \n    eapply good_hash_fully_padded in H6; try eassumption.\n    eapply type_stream_of_bytes in H6; eauto.\n    \n  }\n\n  break_exists.\n  eapply H1 in H6. break_and. eassumption.\n  \n  gex.\n  \n  (* our result matches the model *)\n  subst hv1.\n  eapply list_of_strictval_to_sval in H3.\n  simpl. rewrite H3.\n\n  reflexivity.\n\n  Unshelve.\n  all: exact id.\n  \nQed.\n", "meta": {"author": "GaloisInc", "repo": "cryptol-semantics", "sha": "b4d8b55ec9b3b796427eb9e270e73e1857c597bf", "save_path": "github-repos/coq/GaloisInc-cryptol-semantics", "path": "github-repos/coq/GaloisInc-cryptol-semantics/cryptol-semantics-b4d8b55ec9b3b796427eb9e270e73e1857c597bf/HMAC/HMAC_verif.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.22608155991174608}}
{"text": "Require Export Coq.Lists.List.\nRequire Export Hex.\nRequire Export LTree2.\nRequire Export HashTable.\n\nImport ListNotations.\nLocal Open Scope list_scope.\nNotation \"[ x , .. , y ]\" := (cons x .. (cons y nil) ..).\n\nDefinition is_nilb {X} (l: list X) := \nmatch l with\n| [] => true\n| _::_ => false\nend.\n\nSection Structures.\n\nVariable BN : Type.\nVariable modN : BN -> BN -> BN.\nVariable multN : BN -> BN -> BN. \nVariable divN : BN -> BN -> BN.\nVariable doubleN : BN -> BN.\nVariable plusN : BN -> BN -> BN.\n\nDefinition Timestamp := BN.\nDefinition Currency := BN.\nDefinition HexSPK := hex.\nVariable succN : BN -> BN.\nVariable nat2bn : nat -> BN.\n\nRecord Account := account {\n balance_weight: BN;\n balance: Currency;\n isForging: bool;\n isPublishing: bool;\n isMarkable: bool;\n isMarkFollowing: bool;\n isMarkUnfollowing: bool;\n tfdepth:  option nat;\n publicKey: HexSPK\n}.\n\nRecord Transaction := transaction {\nsender : Account;\nrecipient: Account;\namount: Currency;\nfee: Currency;\nttimestamp: Timestamp\n}.\n\nDefinition BS := HexN.\n\nRecord Block := block {\ntransactions: list Transaction;\nnMarked: nat;\nbaseTarget: BN;\ntotalDifficulty: BN;\ngenerator: Account;\ngenerationSignature: BS;\nbtimestamp: Timestamp\n}.\n\nDefinition eqb_block (b1 b2: Block) :=\n eqb_hexs (generationSignature b1) (generationSignature b2).\n\nVariable Digest : Type.\nVariable dig2string : Digest -> BS.\nVariable hashfun : HexN -> Digest.\n\nDefinition calcGenerationSignature (pb: Block) (acc: Account) : BS :=\n  dig2string (hashfun ((generationSignature pb) ++ [publicKey acc])).\n\n(*implemenation goes to Simulation*)\nVariable formBlock : Block -> Account -> Timestamp -> list Transaction -> HexSPK -> Block.\n\nRecord Blockchain := blocktree { \n blocks : LTree Block\n}.\n\nCheck Blockchain.\n\nDefinition lastblocks (bc: Blockchain) : list Block := \nmatch bc with \n | blocktree bs => [lastnode bs]\nend.\n\nDefinition lastblock (bc: Blockchain) :  Block := \nmatch bc with \n | blocktree bs => lastnode bs\nend.\n\nVariable block_difficulty: Block -> BN.\n(*zero*)\nVariable BN0 : BN.\n(*unit*)\nVariable BN1 : BN.\n(*greater-equal*)\nVariable geN : BN -> BN -> bool.\n\n\nDefinition pushBlock (pb: Block) (bc: Blockchain) (b: Block) :=\nmatch bc with\n| blocktree bs =>  let (parb, newbs) :=  ltree_grow2 pb b eqb_block bs in\n                                         (parb, blocktree newbs)\nend.\n\nDefinition markBlock (n:nat) (b: Block) :=\nblock (transactions b) (S n) (baseTarget b) (totalDifficulty b) (generator b) (generationSignature b) (btimestamp b).\n\n(*\nDefinition adjustTotalDifficulty (pb b: Block) :=\nblock (transactions b) true (baseTarget b) (plusN (totalDifficulty pb) (block_difficulty b)) (generator b) (generationSignature b) (btimestamp b).\n*)\n\nVariable markTimestamp : Timestamp.\n\n\nDefinition isnatpos (n:nat) :=\nmatch n with\n| O => false\n| S _ => true\nend.\n\nDefinition generateBlock (bc: Blockchain) (pb: Block) (acc: Account) (ts: Timestamp) \n                         (txs: list Transaction) (pk: HexSPK) : Block * option Block * Blockchain :=\nmatch bc with\n| blocktree bs => let newblock' := formBlock pb acc ts txs pk in\n                  let bMark := isnatpos (nMarked pb) in\n                  let bTimeMore := geN ts markTimestamp in\n                  let bBlockOld := negb (geN (btimestamp pb) markTimestamp) in        \n                  let newblock := if orb bMark (andb (isMarkable acc) (andb bTimeMore bBlockOld)) then \n                                     markBlock (nMarked pb) newblock' else newblock' in                  \n                  let (parb, newbc) := pushBlock pb bc newblock in\n                  (newblock, parb, newbc)\nend.\n\nRecord Node := node {\n nodechain: Blockchain;\n changedBlock: option Block;\n unconfirmedTxs: list Transaction;\n pending_blocks: list (Block*Block);\n open_blocks: list Block;\n (*pending_open_blocks: list Block;*)\n node_account: Account\n}.\n\nVariable canforge:  Node -> Timestamp -> Block -> bool.\n\nDefinition effectiveBalance := balance.\n\n(*Fixpoint addSortedBlock (b: Block) (lb: list Block) :=\nmatch lb with\n| [] => [b]\n| b'::bs => if negb (geN (baseTarget b) (baseTarget b')) then \n               b::lb\n            else b'::(addSortedBlock b bs)\nend.*)\n\n(*\nFixpoint addSortedBlock (b: Block) (lb: list Block) :=\nmatch lb with\n| [] => [b]\n| b'::bs => if (geN (btimestamp b) (btimestamp b')) then \n               b::lb\n            else b'::(addSortedBlock b bs)\nend.*)\n\nFixpoint addSortedBlock (b: Block) (lb: list Block) :=\nmatch lb with\n| [] => [b]\n| b'::bs => if (geN (totalDifficulty b) (totalDifficulty b')) then \n               b::lb\n            else b'::(addSortedBlock b bs)\nend.\n\n\nDefinition earlierBlock (mb1 mb2: option Block) := \nmatch (mb1, mb2) with\n| (Some b1, Some b2) => if (geN (btimestamp b1) (btimestamp b2)) then mb2 else mb1\n| (Some b1, None) => Some b1\n| (None, Some b2) => Some b2\n| (None, None) => None\nend. \n\n\n(*\n balance_weight: BN;\n balance: Currency;\n isForging: bool;\n isPublishing: bool;\n isMarkable: bool;\n isMarkFollowing: bool;\n tfdepth:  option nat;\n publicKey: HexSPK\n*)\n\n(* nodechain: Blockchain;\n changedBlock: option Block;\n unconfirmedTxs: list Transaction;\n pending_blocks: list (Block*Block);\n open_blocks: list Block;\n node_account: Account*)\n\n\nDefinition forge_block  (nd: Node) (ts: Timestamp) (pb: Block) : Node := \nlet txs := unconfirmedTxs nd in \nlet acct := node_account nd in\nlet bc := nodechain nd in\nlet pk := publicKey acct in\nlet effb := effectiveBalance acct in\nlet canf := canforge nd ts pb in\nlet pendb := pending_blocks nd in\nlet openb := open_blocks nd in\n(*let popenb := pending_open_blocks nd in*)\nlet chb := changedBlock nd in \nmatch canf with\n | true => let (newbp, newbc) := generateBlock bc pb acct ts txs pk in\n           let (newb, parb) := newbp in \n             node newbc (earlierBlock chb parb) [] ((pb,newb)::pendb) (addSortedBlock newb openb) acct\n | false =>  node bc    chb                     [] pendb              (addSortedBlock pb openb)  acct \nend.\n\nFixpoint splitn {X} (n: nat) (l: list X) :=\nmatch n with\n| O => ([], l)\n| S n' => match l with\n          | [] => ([], [])\n          | x::xs => let (l1, l2) := splitn n' xs in\n                               (x::l1, l2)\n          end\nend.\n\n(*Variable tfdepth : option nat.*)\n\nCheck List.fold_left.\n\nFixpoint blt_nat (n m : nat) : bool :=\n  match n with\n  | O => \n    match m with\n      | O => false\n      | S _ => true\n      end \n  | S n' =>\n      match m with\n      | O => false\n      | S m' => blt_nat n' m'\n      end\n  end.\n\nVariable lengthConfirmation : nat.\n\nDefinition markedBlocks (b: Block) :=\nandb (blt_nat (nMarked b) lengthConfirmation) (blt_nat 0 (nMarked b)).\n\nDefinition unmarkedBlocks (b: Block) :=\nnegb (isnatpos (nMarked b)).\n\n(*List.fold_left (fun l => fun b => addSortedBlock b l) (pending_open_blocks newn) splobt*)\n\nDefinition splitBlocks (tfdepth: option nat) (opb: list Block) (defl: list Block):=\nmatch tfdepth with\n      | None => (opb, nil)\n      | Some tfd => match tfd with\n                     | O => (defl, nil)\n                     | S _ => splitn tfd opb\n                    end\nend.\n\n\n(*\nRecord Account := account {\n balance_weight: BN;\n balance: Currency;\n isForging: bool;\n isPublishing: bool;\n isMarkable: bool;\n isMarkFollowing: bool;\n isMarkUnfollowing: bool;\n tfdepth:  option nat;\n publicKey: HexSPK\n}.\n*)\n\nDefinition forge_blocks (nd: Node) (ts: Timestamp) : Node :=\n           let acc := (node_account nd) in\n        \n           let bc := nodechain nd in\n           let opb := open_blocks nd in\n           let (blocks', rb') := splitBlocks (tfdepth acc) opb (lastblocks bc) in\n           let (blocks, rb) := if (isMarkFollowing acc) then\n                               let (l,l') := List.partition markedBlocks blocks' in (l, l'++rb')\n                               else if (isMarkUnfollowing acc) then \n                               let (l,l') := List.partition unmarkedBlocks blocks' in (l, l'++rb')\n                               else (blocks', rb') in\n           let bConfirmed := match opb with\n                             | [] => false\n                             | b::_ => blt_nat lengthConfirmation (nMarked b)\n                             end in          \n           let acc' :=  account (balance_weight acc) (balance acc) (isForging acc) (isPublishing acc) (isMarkable acc)\n                        (andb (isMarkFollowing acc) (negb bConfirmed)) (orb (isMarkUnfollowing acc) (andb bConfirmed (isMarkFollowing acc)))\n                        (tfdepth acc)  (publicKey acc) in                              \n           let nd' := node (nodechain nd) (changedBlock nd) (unconfirmedTxs nd) (pending_blocks nd) rb acc' in\n           let newn := List.fold_left (fun n => fun pb => forge_block n ts pb) blocks nd' in newn. \n\n(* \n balance_weight: BN;\n balance: Currency;\n isForging: bool;\n isPublishing: bool;\n tfdepth:  option nat;\n publicKey: HexSPK\n*)\n\nDefinition defaultAccount pk := \naccount BN1 BN0 true true false false false (Some 0) pk.\n\nFixpoint xseries {X} (n:nat) (x:X) (succX : X -> X) := \nmatch n with\n| O => []\n| S n' => x :: (xseries n' (succX x) succX)\nend.\n\nVariable nFixAccounts : nat.\nVariable accountParams: list (BN*bool*bool*bool*option nat).\n\nCompute (fst (1,2,3)).\n\nFixpoint fixAccounts (h: HexSPK) (n: nat) (l: list (BN*bool*bool*bool*option nat)) : list Account :=\nmatch n with\n| O => []\n| S n' => match l with\n          | [] => (defaultAccount h) :: (fixAccounts (succH h) n' l)\n          | ap :: l' => let (f1,tfd)  := ap in\n                        let (f2, iMF) := f1 in\n                        let (f3, iMA) := f2 in\n                        let (w, iP) := f3 in\n                        (account w BN0 true iP iMA iMF false tfd h) :: (fixAccounts (succH h) n' l')\n          end\nend.\n\nVariable systemBalance: Currency.\n\nDefinition sysAccounts := \n let accs0 := fixAccounts H1 nFixAccounts accountParams in\n let w := List.fold_left plusN (List.map balance_weight accs0) BN0 in\n List.map (fun acc => account (balance_weight acc) \n                                         (divN (multN (balance_weight acc) systemBalance) w) \n                                         (isForging acc) (isPublishing acc) (isMarkable acc) (isMarkFollowing acc) (isMarkUnfollowing acc) (tfdepth acc) (publicKey acc)) accs0.\n\nRecord Connection := connection {\n from_node: Node;\n to_node: Node\n}.\n\nInductive System := system {\n nodes: list Node;\n connections: list Connection;\n accounts: list Account;\n timestamp: Timestamp\n}.\n\nDefinition godAccount := account BN0 BN0 false false false false false None H0.\n\n\nVariable goalBlockTime : BN.\nVariable MaxRand : BN.\n\nDefinition initialBaseTarget : BN := divN MaxRand (doubleN (multN systemBalance goalBlockTime)).\nDefinition maxBaseTarget : BN := multN initialBaseTarget systemBalance.\n\nCheck List.fold_left.\n\n(* \n balance_weight: BN;\n balance: Currency;\n isForging: bool;\n isPublishing: bool;\n tfdepth:  option nat;\n publicKey: HexSPK\n*)\n\n\nDefinition genesisBlock := block [] 0 initialBaseTarget initialBaseTarget godAccount [H0] BN0.\n  \nDefinition genesisState :=\nlet accs := sysAccounts in\nlet chain := blocktree (tgen genesisBlock) in                                        \nlet nodes := List.map (fun acc => node chain None [] [] [genesisBlock] acc) accs in\n    system nodes [] (godAccount::accs) BN0.\n\n\nDefinition sendBlock (sender receiver: Node) (bseq: Block*Block): Node :=\nlet (prevb, newb) := bseq in \nlet rcvr_bc := nodechain receiver in\nlet gen := node_account sender in\nlet gs := calcGenerationSignature prevb gen in\nlet chb := changedBlock receiver in\nif (eqb_hexs gs (generationSignature newb)) then \n    let (parb, newbc) := pushBlock prevb rcvr_bc newb in\n    node newbc (earlierBlock chb parb) (unconfirmedTxs receiver) \n                (pending_blocks receiver) (addSortedBlock newb (open_blocks receiver)) (node_account receiver)\nelse receiver.\n\nDefinition eqbAccounts a1 a2:= eqb_hex (publicKey a1) (publicKey a2).\n\nDefinition sendBlocks (sender receiver: Node): Node :=\nmatch andb (negb (eqbAccounts (node_account sender) (node_account receiver))) (isPublishing (node_account sender)) with\n| false => receiver\n| true => List.fold_left (fun n => fun pbb => sendBlock sender n pbb) (pending_blocks sender) receiver\nend.\n\nPrint rebalanceS_till.\n\n(*rebalanceS_till {X S: Type} (x:X) (w: X -> S) (eqX: X -> X -> bool) (s0: S) (geS: S-> S -> bool) (plusS: S -> S -> S) \n                                           (s: S) (t: LTree X) *)\nDefinition postforge (n: Node) := \nlet bc := nodechain n in\nlet txs := unconfirmedTxs n in\nlet acc := node_account n in \nlet chb := changedBlock n in\nlet newbc := match (tfdepth acc) with\n             | None => bc\n             | Some tfd => match tfd with \n                           | O =>  match bc with\n                                    | blocktree bs => match chb with\n                                                       | Some chb' => blocktree (rebalanceS_till chb' block_difficulty eqb_block BN0 geN plusN BN0 bs)\n                                                       | None => bc\n                                                      end\n                                   end\n                           | S _ => bc\n                           end\n            end in\nnode newbc None txs [] (open_blocks n) acc.  \n\nDefinition rebalance_chain (n: Node) := \nlet bc := nodechain n in\nlet txs := unconfirmedTxs n in\nlet acc := node_account n in\nlet chb := changedBlock n in \nlet newbc := match bc with\n | blocktree bs => blocktree (snd (rebalanceS block_difficulty eqb_block BN0 geN plusN BN0 bs (None, [])))\nend in \n    node newbc None txs [] (open_blocks n) acc.  \n\nDefinition rebalance_sys (s: System) :=\nsystem (List.map rebalance_chain (nodes s)) (connections s) (accounts s) (timestamp s).\n\nDefinition systemEvents (ts: Timestamp) (sys: System) : System := \nlet nodes' := List.map (fun n => forge_blocks n ts) (nodes sys) in\nlet (nonForgers, forgers) := partition (fun n => is_nilb (pending_blocks n)) nodes' in \nlet alteredNodes := \nList.map (fun n_to => List.fold_left (fun n_to' => fun n_from => sendBlocks n_from n_to') forgers n_to) nodes' in\n  system (List.map postforge alteredNodes) (connections sys) (accounts sys) ts.\n\n(*\nnodes: list Node;\n connections: list Connection;\n accounts: list Account;\n timestamp: Timestamp*)\n\nFixpoint systemTransform (sys: System) (count: nat): System :=\nlet t:=timestamp sys in\nmatch count with\n| O => sys\n| S c' =>  systemTransform (systemEvents (succN t) sys) c'\nend.\n\nDefinition sys n := systemTransform genesisState n.\nDefinition sysblocks s := List.map blocks (List.map nodechain (nodes s)).\n\nInductive mhex :=\n| N0: mhex\n| N1: mhex\n| N2: mhex\n| N3: mhex\n| N4: mhex\n| N5: mhex\n| N6: mhex\n| N7: mhex\n| N8: mhex\n| N9: mhex\n| NA: mhex\n| NB: mhex\n| NC: mhex\n| ND: mhex\n| NE: mhex\n| NF: mhex\n| M0: mhex\n| M1: mhex\n| M2: mhex\n| M3: mhex\n| M4: mhex\n| M5: mhex\n| M6: mhex\n| M7: mhex\n| M8: mhex\n| M9: mhex\n| MA: mhex\n| MB: mhex\n| MC: mhex\n| MD: mhex\n| ME: mhex\n| MF: mhex.\n\nDefinition hex2mhex (m:bool) (h:hex) :=\nmatch m with\n| false => match h with \n           | Hex.H0 => N0\n           | Hex.H1 => N1\n           | Hex.H2 => N2\n           | Hex.H3 => N3\n           | Hex.H4 => N4\n           | Hex.H5 => N5\n           | Hex.H6 => N6\n           | Hex.H7 => N7\n           | Hex.H8 => N8\n           | Hex.H9 => N9\n           | Hex.HA => NA\n           | Hex.HB => NB\n           | Hex.HC => NC\n           | Hex.HD => ND\n           | Hex.HE => NE\n           | Hex.HF => NF\n           end\n| true =>  match h with \n           | Hex.H0 => M0\n           | Hex.H1 => M1\n           | Hex.H2 => M2\n           | Hex.H3 => M3\n           | Hex.H4 => M4\n           | Hex.H5 => M5\n           | Hex.H6 => M6\n           | Hex.H7 => M7\n           | Hex.H8 => M8\n           | Hex.H9 => M9\n           | Hex.HA => MA\n           | Hex.HB => MB\n           | Hex.HC => MC\n           | Hex.HD => MD\n           | Hex.HE => ME\n           | Hex.HF => MF\n           end\nend. \n         \n\nDefinition showblock (b: Block) := hex2mhex (isnatpos (nMarked b)) (publicKey (generator b)).\n\nDefinition signs n := List.map (fun tb => ltree_map (fun b => showblock b) tb) (List.map blocks (List.map nodechain (nodes (sys n)))).\nDefinition sysigns s := List.map (fun tb => ltree_map (fun b => showblock b) tb) (sysblocks s).\nDefinition sysaccs s := List.map (node_account) (nodes s).\n\nDefinition addsucc (ht: nattable nat) (k: nat) :=\nmatch (search_table k ht) with\n| None => (k, 1) :: ht\n| Some v => modify_key k (v+1) ht\nend.\n\nDefinition generators s := List.map (fun tb => ltree_foldl (fun ht => fun b => addsucc ht (hex2nat (publicKey (generator b)))) tb []) (sysblocks s).\n\nEnd Structures.\n\nExtraction Language Haskell.\nExtraction \"postructures\" ltree2list ltreelen systemTransform sys sysigns signs \n       maxBaseTarget baseTarget List.filter btimestamp publicKey \n       effectiveBalance List.nth ltree_list_map fold1 sysblocks generators lastnode lastnodes rebalance_sys sysaccs. \n\n", "meta": {"author": "ConsensusResearch", "repo": "MultiBranch", "sha": "6dd242081dab237f9ff13ad6805039b9396a6609", "save_path": "github-repos/coq/ConsensusResearch-MultiBranch", "path": "github-repos/coq/ConsensusResearch-MultiBranch/MultiBranch-6dd242081dab237f9ff13ad6805039b9396a6609/coq/POStructures.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.22601363698699542}}
{"text": "Require Import RamifyCoq.sample_mark.env_unionfind_iter.\nRequire Import RamifyCoq.graph.graph_model.\nRequire Import RamifyCoq.graph.path_lemmas.\nRequire Import RamifyCoq.graph.subgraph2.\nRequire Import RamifyCoq.graph.graph_relation.\nRequire Import RamifyCoq.graph.reachable_computable.\nRequire Import RamifyCoq.msl_application.Graph.\nRequire Import RamifyCoq.msl_application.UnionFindGraph.\nRequire Import RamifyCoq.msl_application.GList.\nRequire Import RamifyCoq.msl_application.GList_UnionFind.\nRequire Import RamifyCoq.floyd_ext.share.\nRequire Import RamifyCoq.sample_mark.spatial_graph_uf_iter.\n\nLocal Coercion UGraph_LGraph: Graph >-> LGraph.\nLocal Coercion LGraph_SGraph: LGraph >-> SGraph.\nLocal Identity Coercion ULGraph_LGraph: LGraph >-> UnionFindGraph.LGraph.\nLocal Identity Coercion LGraph_LabeledGraph: UnionFindGraph.LGraph >-> LabeledGraph.\nLocal Identity Coercion SGraph_PointwiseGraph: SGraph >-> PointwiseGraph.\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nNotation vertices_at sh P g:= (@vertices_at _ _ _ _ _ mpred (@SGP pSGG_VST nat unit (sSGG_VST sh)) (SGA_VST sh) P g).\nNotation whole_graph sh g := (vertices_at sh (vvalid g) g).\nNotation graph sh x g := (@reachable_vertices_at _ _ _ _ _ _ _ _ _ _ (@SGP pSGG_VST nat unit (sSGG_VST sh)) _ x g).\nNotation Graph := (@Graph pSGG_VST).\nNotation uf_under_bound g := (uf_under_bound id g).\nExisting Instances maGraph finGraph liGraph RGF.\n\nDefinition find_spec :=\n DECLARE _find\n  WITH sh: wshare, g: Graph, x: pointer_val\n  PRE [ _x OF (tptr (Tstruct _Node noattr))]\n          PROP  (vvalid g x /\\ uf_under_bound g)\n          LOCAL (temp _x (pointer_val_val x))\n          SEP   (whole_graph sh g)\n  POST [ tptr (Tstruct _Node noattr) ]\n        EX g': Graph, EX rt : pointer_val,\n        PROP (uf_equiv g g' /\\ uf_root g' x rt /\\ uf_under_bound g' /\\ rank_unchanged g g')\n        LOCAL (temp ret_temp (pointer_val_val rt))\n        SEP (whole_graph sh g').\n\nDefinition Gprog : funspecs := ltac:(with_library prog [find_spec]).\n\nLemma false_Cne_eq: forall x y, typed_false tint (force_val (sem_cmp_pp Cne (pointer_val_val x) (pointer_val_val y))) -> x = y.\nProof.\n  intros. hnf in H. destruct x, y; inversion H; auto. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n  - destruct (Ptrofs.eq i i0) eqn:? .    \n    + pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. subst; auto.\n    + simpl in H. inversion H.\n  - simpl in H. inversion H.\nQed.\n\nLemma true_Cne_neq: forall x y, typed_true tint (force_val (sem_cmp_pp Cne (pointer_val_val x) (pointer_val_val y))) -> x <> y.\nProof.\n  intros. hnf in H. destruct x, y; inversion H; [|intro; inversion H0..]. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n  - destruct (Ptrofs.eq i i0) eqn:? .    \n    + simpl in H. inversion H.\n    + subst b0. pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. intro; apply H0. inversion H1. reflexivity.\n  - intro. inversion H0. auto.\nQed.\n\nLemma graph_local_facts: forall sh x (g: Graph), vvalid g x -> whole_graph sh g |-- valid_pointer (pointer_val_val x).\nProof.\n  intros. eapply derives_trans; [apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g (vvalid g) x (vgamma g x)); auto |].\n  simpl vertex_at at 1. unfold binode. entailer!.\nQed.\n\nLemma body_find: semax_body Vprog Gprog f_find find_spec.\nProof.\n  start_function.\n  destruct H. remember (vgamma g x) as rpa eqn:?H. destruct rpa as [r pa]. symmetry in H1.\n  (* tmp = x *)\n  Opaque pointer_val_val. forward. Transparent pointer_val_val.\n  (* p = x -> parent; *)\n  localize [data_at sh node_type (vgamma2cdata (vgamma g x)) (pointer_val_val x)].\n  rewrite H1. simpl vgamma2cdata. forward. 1: entailer!; destruct pa; simpl; auto.\n  unlocalize [whole_graph sh g].\n  1: rewrite H1; simpl; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g (vvalid g) x (r, pa)); auto.\n  forward_while (EX p: pointer_val, EX ppa: pointer_val,\n                 PROP (reachable g x p /\\ vgamma g p = (vlabel g p, ppa))\n                 LOCAL (temp _p (pointer_val_val ppa); temp _tmp (pointer_val_val p); temp _x (pointer_val_val x))\n                 SEP (vertices_at sh (vvalid g) g)).\n  - Exists x pa. entailer!. split; [apply reachable_refl | f_equal; simpl in H1; inversion H1]; auto.\n  - entailer!. destruct H2. apply reachable_foot_valid in H2. pose proof (valid_parent _ _ _ _ H2 H6). apply denote_tc_test_eq_split; apply graph_local_facts; auto.\n  - destruct H2. apply true_Cne_neq in HRE.\n    Opaque pointer_val_val. forward. Transparent pointer_val_val. remember (vgamma g ppa) as rpa eqn:?H. destruct rpa as [mr mgpa]. symmetry in H4.\n    assert (H_VALID_PPA: vvalid g ppa) by (apply (valid_parent _ p (vlabel g p)); [apply reachable_foot_valid in H2 |]; auto).\n    localize [data_at sh node_type (vgamma2cdata (vgamma g ppa)) (pointer_val_val ppa)].\n    rewrite H4. simpl vgamma2cdata. forward. 1: entailer!; destruct mgpa; simpl; auto.\n    unlocalize [whole_graph sh g].\n    1: rewrite H4; simpl; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g (vvalid g) ppa (mr, mgpa)); auto.\n    Exists (ppa, mgpa). simpl fst. simpl snd. assert (mr = vlabel g ppa) by (simpl in H4; inversion H4; auto). rewrite <- H5. entailer !.\n    apply reachable_edge with p; auto. apply (vgamma_not_edge g p (vlabel g p)); auto. apply reachable_foot_valid in H2; auto.\n  - destruct H2. apply false_Cne_eq in HRE. subst ppa. assert (uf_root g x p) by (split; intros; auto; apply (parent_loop g p (vlabel g p) y); auto).\n    forward_while (EX g': Graph, EX tmp: pointer_val, EX xv: pointer_val,\n                   PROP (uf_equiv g g' /\\ uf_root g' xv p /\\ uf_under_bound g' /\\ rank_unchanged g g')\n                   LOCAL (temp _p (pointer_val_val p); temp _tmp (pointer_val_val tmp); temp _x (pointer_val_val xv))\n                   SEP (whole_graph sh g')).\n    + Exists g p x. entailer !. split; [apply (uf_equiv_refl _  (liGraph g)) | repeat intro; auto].\n    + entailer!. apply denote_tc_test_eq_split; apply graph_local_facts.\n      * destruct H5 as [_ [[? _] _]]. apply reachable_head_valid in H5; assumption.\n      * destruct H5 as [[? _] _]. rewrite <- H5. apply reachable_foot_valid in H2; assumption.\n    + destruct H5 as [? [? [? ?]]]. apply true_Cne_neq in HRE. remember (vgamma g' xv) as rpa eqn:?H. destruct rpa as [xr xpa]. symmetry in H9.\n      assert (H_VALID_XV: vvalid g' xv) by (destruct H6 as [? _]; apply reachable_head_valid in H6; auto).\n      localize [data_at sh node_type (vgamma2cdata (vgamma g' xv)) (pointer_val_val xv)].\n      rewrite H9. simpl vgamma2cdata. forward. 1: entailer!; destruct xpa; simpl; auto.\n      unlocalize [whole_graph sh g'].\n      1: rewrite H9; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g' (vvalid g') xv (xr, xpa)); auto.\n      assert (weak_valid g' p) by (right; destruct H5; rewrite <- H5; apply reachable_foot_valid in H2; auto).\n      assert (vvalid g' xv) by (destruct H6; apply reachable_head_valid in H6; auto).\n      assert (~ reachable g' p xv) by (intro; destruct H6 as [_ ?]; specialize (H6 _ H12); auto). \n      assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g' xv p H10 H11 H12)) (Graph_gen_redirect_parent g' xv p H10 H11 H12) =\n              vertices_at sh (vvalid g') (Graph_gen_redirect_parent g' xv p H10 H11 H12)). {\n        apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition. }\n      assert (H_P_NOT_NULL: p <> null) by (apply reachable_foot_valid in H2; intro; subst p; apply (valid_not_null g null H2); simpl; auto).\n      localize [data_at sh node_type (Vint (Int.repr (Z.of_nat xr)), pointer_val_val xpa) (pointer_val_val xv)].\n      forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g' xv p H10 H11 H12)].\n      1: rewrite H13; apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto.\n      Opaque pointer_val_val. forward. Transparent pointer_val_val.\n      Exists (((Graph_gen_redirect_parent g' xv p H10 H11 H12), xpa), xpa). simpl fst. simpl snd. entailer !. split; [|split].\n      * apply (graph_gen_redirect_parent_equiv' g g' xv p); auto.\n      * apply (uf_root_gen_dst_preserve g' (liGraph g')); auto.\n        -- apply (vgamma_not_reachable _ _ xr); auto. pose proof (uf_root_not_eq_root_vgamma g' _ _ _ _ H9 H6 HRE). auto.\n        -- apply (vgamma_uf_root g' xv xr xpa p); auto.\n      * apply uf_under_bound_redirect_parent; auto.\n    + destruct H5 as [? [? ?]]. forward. Exists g' p. entailer !. split; [|auto]. rewrite <- (uf_equiv_root_the_same g g' x p); auto.\nQed. (* Original: 118.49 secs; VST 2.*: 3.12 secs *)\n", "meta": {"author": "anshumanmohan", "repo": "RamifyCoq_VST", "sha": "0517a39b069f79f50a45321db6ca81c48397b73d", "save_path": "github-repos/coq/anshumanmohan-RamifyCoq_VST", "path": "github-repos/coq/anshumanmohan-RamifyCoq_VST/RamifyCoq_VST-0517a39b069f79f50a45321db6ca81c48397b73d/RamifyCoq/sample_mark/verif_unionfind_iter_rank.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.22593609868350337}}
{"text": "Require Import Poulet4.P4light.Syntax.Typed.\nRequire Import Poulet4.P4light.Syntax.Syntax.\nRequire Import Poulet4.P4light.Syntax.Value.\nRequire Import Poulet4.P4light.Semantics.Semantics.\nRequire Import Poulet4.P4light.Syntax.P4defs.\nRequire Import Poulet4.P4light.Syntax.P4Notations.\nRequire Import Poulet4.P4light.Architecture.V1ModelTarget.\nRequire Import ProD3.core.SvalRefine.\nRequire Import ProD3.core.Members.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nImport ListNotations.\nOpen Scope list_scope.\nOpen Scope string_scope.\n\n(* A simplified switch model to demonstrate bloom filter application. *)\n\nSection Switch.\n\nContext {tags_t: Type} {tags_t_inhabitant : Inhabitant tags_t}.\n\nNotation ident := string.\nNotation path := (list ident).\nNotation Val := (@ValueBase bool).\nNotation Expression := (@Expression tags_t).\nNotation P4Type := (@P4Type tags_t).\nNotation extern_state := (@extern_state tags_t Expression).\n\nInstance target : @Target tags_t Expression := V1Model.\n\nVariable ge : genv.\nVariable M : P4Type.\n\nDefinition standard_metadata_t : P4Type :=\n  TypStruct\n    [(!\"ingress_port\", TypBit 9); (!\"egress_spec\", TypBit 9); (!\"egress_port\", TypBit 9);\n    (!\"instance_type\", TypBit 32); (!\"packet_length\", TypBit 32); (!\"enq_timestamp\", TypBit 32);\n    (!\"enq_qdepth\", TypBit 19); (!\"deq_timedelta\", TypBit 32); (!\"deq_qdepth\", TypBit 19);\n    (!\"ingress_global_timestamp\", TypBit 48); (!\"egress_global_timestamp\", TypBit 48);\n    (!\"mcast_grp\", TypBit 16); (!\"egress_rid\", TypBit 16); (!\"checksum_error\", TypBit 1);\n    (!\"parser_error\", TypError); (!\"priority\", TypBit 3)].\n\nInductive port :=\n  | port_int\n  | port_ext.\n\nDefinition port_to_Z (p : port) :=\n  match p with\n  | port_int => 0\n  | port_ext => 1\n  end.\n\nDefinition port_to_sval (p : port) :=\n  ValBaseBit (P4Arith.to_loptbool 9 (port_to_Z p)).\n\nDefinition out_port_to_Z (p : option port) :=\n  match p with\n  | Some p => port_to_Z p\n  | None => 511\n  end.\n\nDefinition out_port_to_sval (p : option port) :=\n  ValBaseBit (P4Arith.to_loptbool 9 (out_port_to_Z p)).\n\nInductive process_packet : extern_state -> (Z * port) -> extern_state -> option (Z * port) -> Prop :=\n  | process_packet_intro : forall es data in_port es' data' out_port meta' std_meta' class_name inst_path targs fd m',\n      PathMap.get [\"main\"; \"ig\"] (ge_inst ge) = Some {|iclass:=class_name; ipath:=inst_path; itargs:=targs|} ->\n      PathMap.get ([class_name; \"apply\"]) (ge_func ge) = Some fd ->\n      0 <= data < Z.pow 2 16 ->\n      let hdr := ValBaseStruct [(\"myHeader\",\n        ValBaseHeader [(\"data\", ValBaseBit (P4Arith.to_loptbool 16 data))] (Some true))] in\n      let meta := force ValBaseNull (uninit_sval_of_typ None M) in\n      let std_meta := update \"ingress_port\" (port_to_sval in_port) (force ValBaseNull (uninit_sval_of_typ None standard_metadata_t)) in\n      0 <= data' < Z.pow 2 16 ->\n      let hdr' := ValBaseStruct [(\"myHeader\",\n        ValBaseHeader [(\"data\", ValBaseBit (P4Arith.to_loptbool 16 data'))] (Some true))] in\n      Members.get \"egress_spec\" std_meta' = out_port_to_sval out_port ->\n      exec_func ge read_ndetbit inst_path (PathMap.empty, es) fd nil [hdr; meta; std_meta]\n          (m', es') [hdr'; meta'; std_meta'] (SReturn ValBaseNull) ->\n      process_packet es (data, in_port) es' (option_map (pair data') out_port).\n\nInductive process_packets : extern_state -> list (Z * port) -> extern_state -> list (option (Z * port)) -> Prop :=\n  | process_packets_nil : forall es,\n      process_packets es [] es []\n  | process_packets_cons : forall es1 p p' es2 ps ps' es3,\n      process_packet es1 p es2 p' ->\n      process_packets es2 ps es3 ps' ->\n      process_packets es1 (p :: ps) es3 (p' :: ps').\n\nEnd Switch.\n", "meta": {"author": "verified-network-toolchain", "repo": "VerifiableP4", "sha": "87afa7bef7d88da2e9a642e37c0ddb2412b57509", "save_path": "github-repos/coq/verified-network-toolchain-VerifiableP4", "path": "github-repos/coq/verified-network-toolchain-VerifiableP4/VerifiableP4-87afa7bef7d88da2e9a642e37c0ddb2412b57509/examples/bloomfilter/switch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.2259335825775289}}
{"text": "From Coq Require Import String List ZArith.\nFrom compcert Require Import Coqlib Integers Floats AST Ctypes Cop Clight Clightdefs.\nImport Clightdefs.ClightNotations.\nLocal Open Scope Z_scope.\nLocal Open Scope string_scope.\nLocal Open Scope clight_scope.\n\nModule Info.\n  Definition version := \"3.11\".\n  Definition build_number := \"\".\n  Definition build_tag := \"\".\n  Definition build_branch := \"\".\n  Definition arch := \"x86\".\n  Definition model := \"64\".\n  Definition abi := \"standard\".\n  Definition bitsize := 64.\n  Definition big_endian := false.\n  Definition source_file := \"prims.c\".\n  Definition normalized := true.\nEnd Info.\n\nDefinition _Coq_Numbers_BinNums_Zneg_arg_0 : ident := $\"Coq_Numbers_BinNums_Zneg_arg_0\".\nDefinition _Coq_Numbers_BinNums_Zneg_args : ident := $\"Coq_Numbers_BinNums_Zneg_args\".\nDefinition _Coq_Numbers_BinNums_Zpos_arg_0 : ident := $\"Coq_Numbers_BinNums_Zpos_arg_0\".\nDefinition _Coq_Numbers_BinNums_Zpos_args : ident := $\"Coq_Numbers_BinNums_Zpos_args\".\nDefinition _Coq_Numbers_BinNums_xI_arg_0 : ident := $\"Coq_Numbers_BinNums_xI_arg_0\".\nDefinition _Coq_Numbers_BinNums_xI_args : ident := $\"Coq_Numbers_BinNums_xI_args\".\nDefinition _Coq_Numbers_BinNums_xO_arg_0 : ident := $\"Coq_Numbers_BinNums_xO_arg_0\".\nDefinition _Coq_Numbers_BinNums_xO_args : ident := $\"Coq_Numbers_BinNums_xO_args\".\nDefinition ___builtin_ais_annot : ident := $\"__builtin_ais_annot\".\nDefinition ___builtin_annot : ident := $\"__builtin_annot\".\nDefinition ___builtin_annot_intval : ident := $\"__builtin_annot_intval\".\nDefinition ___builtin_bswap : ident := $\"__builtin_bswap\".\nDefinition ___builtin_bswap16 : ident := $\"__builtin_bswap16\".\nDefinition ___builtin_bswap32 : ident := $\"__builtin_bswap32\".\nDefinition ___builtin_bswap64 : ident := $\"__builtin_bswap64\".\nDefinition ___builtin_clz : ident := $\"__builtin_clz\".\nDefinition ___builtin_clzl : ident := $\"__builtin_clzl\".\nDefinition ___builtin_clzll : ident := $\"__builtin_clzll\".\nDefinition ___builtin_ctz : ident := $\"__builtin_ctz\".\nDefinition ___builtin_ctzl : ident := $\"__builtin_ctzl\".\nDefinition ___builtin_ctzll : ident := $\"__builtin_ctzll\".\nDefinition ___builtin_debug : ident := $\"__builtin_debug\".\nDefinition ___builtin_expect : ident := $\"__builtin_expect\".\nDefinition ___builtin_fabs : ident := $\"__builtin_fabs\".\nDefinition ___builtin_fabsf : ident := $\"__builtin_fabsf\".\nDefinition ___builtin_fmadd : ident := $\"__builtin_fmadd\".\nDefinition ___builtin_fmax : ident := $\"__builtin_fmax\".\nDefinition ___builtin_fmin : ident := $\"__builtin_fmin\".\nDefinition ___builtin_fmsub : ident := $\"__builtin_fmsub\".\nDefinition ___builtin_fnmadd : ident := $\"__builtin_fnmadd\".\nDefinition ___builtin_fnmsub : ident := $\"__builtin_fnmsub\".\nDefinition ___builtin_fsqrt : ident := $\"__builtin_fsqrt\".\nDefinition ___builtin_membar : ident := $\"__builtin_membar\".\nDefinition ___builtin_memcpy_aligned : ident := $\"__builtin_memcpy_aligned\".\nDefinition ___builtin_read16_reversed : ident := $\"__builtin_read16_reversed\".\nDefinition ___builtin_read32_reversed : ident := $\"__builtin_read32_reversed\".\nDefinition ___builtin_sel : ident := $\"__builtin_sel\".\nDefinition ___builtin_sqrt : ident := $\"__builtin_sqrt\".\nDefinition ___builtin_unreachable : ident := $\"__builtin_unreachable\".\nDefinition ___builtin_va_arg : ident := $\"__builtin_va_arg\".\nDefinition ___builtin_va_copy : ident := $\"__builtin_va_copy\".\nDefinition ___builtin_va_end : ident := $\"__builtin_va_end\".\nDefinition ___builtin_va_start : ident := $\"__builtin_va_start\".\nDefinition ___builtin_write16_reversed : ident := $\"__builtin_write16_reversed\".\nDefinition ___builtin_write32_reversed : ident := $\"__builtin_write32_reversed\".\nDefinition ___compcert_i64_dtos : ident := $\"__compcert_i64_dtos\".\nDefinition ___compcert_i64_dtou : ident := $\"__compcert_i64_dtou\".\nDefinition ___compcert_i64_sar : ident := $\"__compcert_i64_sar\".\nDefinition ___compcert_i64_sdiv : ident := $\"__compcert_i64_sdiv\".\nDefinition ___compcert_i64_shl : ident := $\"__compcert_i64_shl\".\nDefinition ___compcert_i64_shr : ident := $\"__compcert_i64_shr\".\nDefinition ___compcert_i64_smod : ident := $\"__compcert_i64_smod\".\nDefinition ___compcert_i64_smulh : ident := $\"__compcert_i64_smulh\".\nDefinition ___compcert_i64_stod : ident := $\"__compcert_i64_stod\".\nDefinition ___compcert_i64_stof : ident := $\"__compcert_i64_stof\".\nDefinition ___compcert_i64_udiv : ident := $\"__compcert_i64_udiv\".\nDefinition ___compcert_i64_umod : ident := $\"__compcert_i64_umod\".\nDefinition ___compcert_i64_umulh : ident := $\"__compcert_i64_umulh\".\nDefinition ___compcert_i64_utod : ident := $\"__compcert_i64_utod\".\nDefinition ___compcert_i64_utof : ident := $\"__compcert_i64_utof\".\nDefinition ___compcert_va_composite : ident := $\"__compcert_va_composite\".\nDefinition ___compcert_va_float64 : ident := $\"__compcert_va_float64\".\nDefinition ___compcert_va_int32 : ident := $\"__compcert_va_int32\".\nDefinition ___compcert_va_int64 : ident := $\"__compcert_va_int64\".\nDefinition _alloc : ident := $\"alloc\".\nDefinition _alloc_make_Coq_Numbers_BinNums_Z_Zpos : ident := $\"alloc_make_Coq_Numbers_BinNums_Z_Zpos\".\nDefinition _alloc_make_Coq_Numbers_BinNums_positive_xI : ident := $\"alloc_make_Coq_Numbers_BinNums_positive_xI\".\nDefinition _alloc_make_Coq_Numbers_BinNums_positive_xO : ident := $\"alloc_make_Coq_Numbers_BinNums_positive_xO\".\nDefinition _args : ident := $\"args\".\nDefinition _bit : ident := $\"bit\".\nDefinition _get_Coq_Numbers_BinNums_Z_tag : ident := $\"get_Coq_Numbers_BinNums_Z_tag\".\nDefinition _get_Coq_Numbers_BinNums_Zneg_args : ident := $\"get_Coq_Numbers_BinNums_Zneg_args\".\nDefinition _get_Coq_Numbers_BinNums_Zpos_args : ident := $\"get_Coq_Numbers_BinNums_Zpos_args\".\nDefinition _get_Coq_Numbers_BinNums_positive_tag : ident := $\"get_Coq_Numbers_BinNums_positive_tag\".\nDefinition _get_Coq_Numbers_BinNums_xI_args : ident := $\"get_Coq_Numbers_BinNums_xI_args\".\nDefinition _get_Coq_Numbers_BinNums_xO_args : ident := $\"get_Coq_Numbers_BinNums_xO_args\".\nDefinition _heap : ident := $\"heap\".\nDefinition _i : ident := $\"i\".\nDefinition _limit : ident := $\"limit\".\nDefinition _main : ident := $\"main\".\nDefinition _make_Coq_Numbers_BinNums_Z_Z0 : ident := $\"make_Coq_Numbers_BinNums_Z_Z0\".\nDefinition _make_Coq_Numbers_BinNums_positive_xH : ident := $\"make_Coq_Numbers_BinNums_positive_xH\".\nDefinition _p : ident := $\"p\".\nDefinition _t : ident := $\"t\".\nDefinition _temp : ident := $\"temp\".\nDefinition _thread_info : ident := $\"thread_info\".\nDefinition _tinfo : ident := $\"tinfo\".\nDefinition _uint63_add : ident := $\"uint63_add\".\nDefinition _uint63_from_Z : ident := $\"uint63_from_Z\".\nDefinition _uint63_from_positive : ident := $\"uint63_from_positive\".\nDefinition _uint63_mul : ident := $\"uint63_mul\".\nDefinition _uint63_to_Z : ident := $\"uint63_to_Z\".\nDefinition _x : ident := $\"x\".\nDefinition _y : ident := $\"y\".\nDefinition _z : ident := $\"z\".\nDefinition _t'1 : ident := 128%positive.\nDefinition _t'2 : ident := 129%positive.\nDefinition _t'3 : ident := 130%positive.\nDefinition _t'4 : ident := 131%positive.\nDefinition _t'5 : ident := 132%positive.\nDefinition _t'6 : ident := 133%positive.\nDefinition _t'7 : ident := 134%positive.\n\nDefinition f_uint63_from_positive := {|\n  fn_return := tlong;\n  fn_callconv := cc_default;\n  fn_params := ((_p, tlong) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'5, tlong) ::\n               (_t'4, (tptr (Tstruct _Coq_Numbers_BinNums_xO_args noattr))) ::\n               (_t'3, tlong) ::\n               (_t'2, (tptr (Tstruct _Coq_Numbers_BinNums_xI_args noattr))) ::\n               (_t'1, tuint) :: (_t'7, tulong) :: (_t'6, tulong) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall (Some _t'1)\n    (Evar _get_Coq_Numbers_BinNums_positive_tag (Tfunction\n                                                  (Tcons tulong Tnil) tuint\n                                                  cc_default))\n    ((Etempvar _p tlong) :: nil))\n  (Sswitch (Etempvar _t'1 tuint)\n    (LScons (Some 0)\n      (Ssequence\n        (Ssequence\n          (Scall (Some _t'2)\n            (Evar _get_Coq_Numbers_BinNums_xI_args (Tfunction\n                                                     (Tcons tulong Tnil)\n                                                     (tptr (Tstruct _Coq_Numbers_BinNums_xI_args noattr))\n                                                     cc_default))\n            ((Etempvar _p tlong) :: nil))\n          (Ssequence\n            (Sset _t'7\n              (Efield\n                (Ederef\n                  (Etempvar _t'2 (tptr (Tstruct _Coq_Numbers_BinNums_xI_args noattr)))\n                  (Tstruct _Coq_Numbers_BinNums_xI_args noattr))\n                _Coq_Numbers_BinNums_xI_arg_0 tulong))\n            (Scall (Some _t'3)\n              (Evar _uint63_from_positive (Tfunction (Tcons tlong Tnil) tlong\n                                            cc_default))\n              ((Etempvar _t'7 tulong) :: nil))))\n        (Sreturn (Some (Ebinop Oadd\n                         (Ebinop Oshl\n                           (Ebinop Oadd\n                             (Ebinop Omul (Econst_int (Int.repr 2) tint)\n                               (Ebinop Oshr (Etempvar _t'3 tlong)\n                                 (Econst_int (Int.repr 1) tint) tlong) tlong)\n                             (Econst_int (Int.repr 1) tint) tlong)\n                           (Econst_int (Int.repr 1) tint) tlong)\n                         (Econst_int (Int.repr 1) tint) tlong))))\n      (LScons (Some 1)\n        (Ssequence\n          (Ssequence\n            (Scall (Some _t'4)\n              (Evar _get_Coq_Numbers_BinNums_xO_args (Tfunction\n                                                       (Tcons tulong Tnil)\n                                                       (tptr (Tstruct _Coq_Numbers_BinNums_xO_args noattr))\n                                                       cc_default))\n              ((Etempvar _p tlong) :: nil))\n            (Ssequence\n              (Sset _t'6\n                (Efield\n                  (Ederef\n                    (Etempvar _t'4 (tptr (Tstruct _Coq_Numbers_BinNums_xO_args noattr)))\n                    (Tstruct _Coq_Numbers_BinNums_xO_args noattr))\n                  _Coq_Numbers_BinNums_xO_arg_0 tulong))\n              (Scall (Some _t'5)\n                (Evar _uint63_from_positive (Tfunction (Tcons tlong Tnil)\n                                              tlong cc_default))\n                ((Etempvar _t'6 tulong) :: nil))))\n          (Sreturn (Some (Ebinop Oadd\n                           (Ebinop Oshl\n                             (Ebinop Omul (Econst_int (Int.repr 2) tint)\n                               (Ebinop Oshr (Etempvar _t'5 tlong)\n                                 (Econst_int (Int.repr 1) tint) tlong) tlong)\n                             (Econst_int (Int.repr 1) tint) tlong)\n                           (Econst_int (Int.repr 1) tint) tlong))))\n        (LScons (Some 2)\n          (Sreturn (Some (Ebinop Oadd\n                           (Ebinop Oshl (Econst_int (Int.repr 1) tint)\n                             (Econst_int (Int.repr 1) tint) tint)\n                           (Econst_int (Int.repr 1) tint) tint)))\n          LSnil)))))\n|}.\n\nDefinition f_uint63_from_Z := {|\n  fn_return := tlong;\n  fn_callconv := cc_default;\n  fn_params := ((_z, tlong) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_t'5, tlong) ::\n               (_t'4, (tptr (Tstruct _Coq_Numbers_BinNums_Zneg_args noattr))) ::\n               (_t'3, tlong) ::\n               (_t'2, (tptr (Tstruct _Coq_Numbers_BinNums_Zpos_args noattr))) ::\n               (_t'1, tuint) :: (_t'7, tulong) :: (_t'6, tulong) :: nil);\n  fn_body :=\n(Ssequence\n  (Scall (Some _t'1)\n    (Evar _get_Coq_Numbers_BinNums_Z_tag (Tfunction (Tcons tulong Tnil) tuint\n                                           cc_default))\n    ((Etempvar _z tlong) :: nil))\n  (Sswitch (Etempvar _t'1 tuint)\n    (LScons (Some 0)\n      (Sreturn (Some (Econst_int (Int.repr 0) tint)))\n      (LScons (Some 1)\n        (Ssequence\n          (Ssequence\n            (Scall (Some _t'2)\n              (Evar _get_Coq_Numbers_BinNums_Zpos_args (Tfunction\n                                                         (Tcons tulong Tnil)\n                                                         (tptr (Tstruct _Coq_Numbers_BinNums_Zpos_args noattr))\n                                                         cc_default))\n              ((Etempvar _z tlong) :: nil))\n            (Ssequence\n              (Sset _t'7\n                (Efield\n                  (Ederef\n                    (Etempvar _t'2 (tptr (Tstruct _Coq_Numbers_BinNums_Zpos_args noattr)))\n                    (Tstruct _Coq_Numbers_BinNums_Zpos_args noattr))\n                  _Coq_Numbers_BinNums_Zpos_arg_0 tulong))\n              (Scall (Some _t'3)\n                (Evar _uint63_from_positive (Tfunction (Tcons tlong Tnil)\n                                              tlong cc_default))\n                ((Etempvar _t'7 tulong) :: nil))))\n          (Sreturn (Some (Etempvar _t'3 tlong))))\n        (LScons (Some 2)\n          (Ssequence\n            (Ssequence\n              (Scall (Some _t'4)\n                (Evar _get_Coq_Numbers_BinNums_Zneg_args (Tfunction\n                                                           (Tcons tulong\n                                                             Tnil)\n                                                           (tptr (Tstruct _Coq_Numbers_BinNums_Zneg_args noattr))\n                                                           cc_default))\n                ((Etempvar _z tlong) :: nil))\n              (Ssequence\n                (Sset _t'6\n                  (Efield\n                    (Ederef\n                      (Etempvar _t'4 (tptr (Tstruct _Coq_Numbers_BinNums_Zneg_args noattr)))\n                      (Tstruct _Coq_Numbers_BinNums_Zneg_args noattr))\n                    _Coq_Numbers_BinNums_Zneg_arg_0 tulong))\n                (Scall (Some _t'5)\n                  (Evar _uint63_from_positive (Tfunction (Tcons tlong Tnil)\n                                                tlong cc_default))\n                  ((Etempvar _t'6 tulong) :: nil))))\n            (Sreturn (Some (Eunop Oneg (Etempvar _t'5 tlong) tlong))))\n          LSnil)))))\n|}.\n\nDefinition f_uint63_to_Z := {|\n  fn_return := tlong;\n  fn_callconv := cc_default;\n  fn_params := ((_tinfo, (tptr (Tstruct _thread_info noattr))) ::\n                (_t, tlong) :: nil);\n  fn_vars := nil;\n  fn_temps := ((_temp, tlong) :: (_i, tuint) :: (_bit, tbool) ::\n               (_t'5, tulong) :: (_t'4, tulong) :: (_t'3, tulong) ::\n               (_t'2, tulong) :: (_t'1, tulong) :: nil);\n  fn_body :=\n(Ssequence\n  (Sifthenelse (Ebinop Oeq (Etempvar _t tlong) (Econst_int (Int.repr 1) tint)\n                 tint)\n    (Ssequence\n      (Scall (Some _t'1)\n        (Evar _make_Coq_Numbers_BinNums_Z_Z0 (Tfunction Tnil tulong\n                                               cc_default)) nil)\n      (Sreturn (Some (Etempvar _t'1 tulong))))\n    Sskip)\n  (Ssequence\n    (Sset _temp (Ecast (Econst_int (Int.repr 0) tint) tlong))\n    (Ssequence\n      (Ssequence\n        (Sset _i\n          (Ecast\n            (Ebinop Osub\n              (Ebinop Omul (Esizeof tlong tulong)\n                (Econst_int (Int.repr 8) tint) tulong)\n              (Econst_int (Int.repr 1) tint) tulong) tuint))\n        (Sloop\n          (Ssequence\n            (Sifthenelse (Ebinop Ogt (Etempvar _i tuint)\n                           (Econst_int (Int.repr 0) tint) tint)\n              Sskip\n              Sbreak)\n            (Ssequence\n              (Sset _bit\n                (Ecast\n                  (Ebinop Oshr\n                    (Ebinop Oand (Etempvar _t tlong)\n                      (Ebinop Oshl (Econst_int (Int.repr 1) tint)\n                        (Etempvar _i tuint) tint) tlong) (Etempvar _i tuint)\n                    tlong) tbool))\n              (Sifthenelse (Etempvar _bit tbool)\n                (Sifthenelse (Etempvar _temp tlong)\n                  (Ssequence\n                    (Scall (Some _t'2)\n                      (Evar _alloc_make_Coq_Numbers_BinNums_positive_xI \n                      (Tfunction\n                        (Tcons (tptr (Tstruct _thread_info noattr))\n                          (Tcons tulong Tnil)) tulong cc_default))\n                      ((Etempvar _tinfo (tptr (Tstruct _thread_info noattr))) ::\n                       (Etempvar _temp tlong) :: nil))\n                    (Sset _temp (Etempvar _t'2 tulong)))\n                  (Ssequence\n                    (Scall (Some _t'3)\n                      (Evar _make_Coq_Numbers_BinNums_positive_xH (Tfunction\n                                                                    Tnil\n                                                                    tulong\n                                                                    cc_default))\n                      nil)\n                    (Sset _temp (Etempvar _t'3 tulong))))\n                (Sifthenelse (Etempvar _temp tlong)\n                  (Ssequence\n                    (Scall (Some _t'4)\n                      (Evar _alloc_make_Coq_Numbers_BinNums_positive_xO \n                      (Tfunction\n                        (Tcons (tptr (Tstruct _thread_info noattr))\n                          (Tcons tulong Tnil)) tulong cc_default))\n                      ((Etempvar _tinfo (tptr (Tstruct _thread_info noattr))) ::\n                       (Etempvar _temp tlong) :: nil))\n                    (Sset _temp (Etempvar _t'4 tulong)))\n                  Sskip))))\n          (Sset _i\n            (Ebinop Osub (Etempvar _i tuint) (Econst_int (Int.repr 1) tint)\n              tuint))))\n      (Ssequence\n        (Scall (Some _t'5)\n          (Evar _alloc_make_Coq_Numbers_BinNums_Z_Zpos (Tfunction\n                                                         (Tcons\n                                                           (tptr (Tstruct _thread_info noattr))\n                                                           (Tcons tulong\n                                                             Tnil)) tulong\n                                                         cc_default))\n          ((Etempvar _tinfo (tptr (Tstruct _thread_info noattr))) ::\n           (Etempvar _temp tlong) :: nil))\n        (Sreturn (Some (Etempvar _t'5 tulong)))))))\n|}.\n\nDefinition f_uint63_add := {|\n  fn_return := tlong;\n  fn_callconv := cc_default;\n  fn_params := ((_x, tlong) :: (_y, tlong) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Sreturn (Some (Ebinop Oadd\n                 (Ebinop Oshl\n                   (Ebinop Oadd\n                     (Ebinop Oshr (Etempvar _x tlong)\n                       (Econst_int (Int.repr 1) tint) tlong)\n                     (Ebinop Oshr (Etempvar _y tlong)\n                       (Econst_int (Int.repr 1) tint) tlong) tlong)\n                   (Econst_int (Int.repr 1) tint) tlong)\n                 (Econst_int (Int.repr 1) tint) tlong)))\n|}.\n\nDefinition f_uint63_mul := {|\n  fn_return := tlong;\n  fn_callconv := cc_default;\n  fn_params := ((_x, tlong) :: (_y, tlong) :: nil);\n  fn_vars := nil;\n  fn_temps := nil;\n  fn_body :=\n(Sreturn (Some (Ebinop Oadd\n                 (Ebinop Oshl\n                   (Ebinop Omul\n                     (Ebinop Oshr (Etempvar _x tlong)\n                       (Econst_int (Int.repr 1) tint) tlong)\n                     (Ebinop Oshr (Etempvar _y tlong)\n                       (Econst_int (Int.repr 1) tint) tlong) tlong)\n                   (Econst_int (Int.repr 1) tint) tlong)\n                 (Econst_int (Int.repr 1) tint) tlong)))\n|}.\n\nDefinition composites : list composite_definition :=\n(Composite _thread_info Struct\n   (Member_plain _alloc (tptr tulong) :: Member_plain _limit (tptr tulong) ::\n    Member_plain _heap (tptr (Tstruct _heap noattr)) ::\n    Member_plain _args (tarray tulong 1024) :: nil)\n   noattr ::\n Composite _Coq_Numbers_BinNums_xI_args Struct\n   (Member_plain _Coq_Numbers_BinNums_xI_arg_0 tulong :: nil)\n   noattr ::\n Composite _Coq_Numbers_BinNums_xO_args Struct\n   (Member_plain _Coq_Numbers_BinNums_xO_arg_0 tulong :: nil)\n   noattr ::\n Composite _Coq_Numbers_BinNums_Zpos_args Struct\n   (Member_plain _Coq_Numbers_BinNums_Zpos_arg_0 tulong :: nil)\n   noattr ::\n Composite _Coq_Numbers_BinNums_Zneg_args Struct\n   (Member_plain _Coq_Numbers_BinNums_Zneg_arg_0 tulong :: nil)\n   noattr :: nil).\n\nDefinition global_definitions : list (ident * globdef fundef type) :=\n((___compcert_va_int32,\n   Gfun(External (EF_runtime \"__compcert_va_int32\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons (tptr tvoid) Tnil) tuint cc_default)) ::\n (___compcert_va_int64,\n   Gfun(External (EF_runtime \"__compcert_va_int64\"\n                   (mksignature (AST.Tlong :: nil) AST.Tlong cc_default))\n     (Tcons (tptr tvoid) Tnil) tulong cc_default)) ::\n (___compcert_va_float64,\n   Gfun(External (EF_runtime \"__compcert_va_float64\"\n                   (mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))\n     (Tcons (tptr tvoid) Tnil) tdouble cc_default)) ::\n (___compcert_va_composite,\n   Gfun(External (EF_runtime \"__compcert_va_composite\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons (tptr tvoid) (Tcons tulong Tnil))\n     (tptr tvoid) cc_default)) ::\n (___compcert_i64_dtos,\n   Gfun(External (EF_runtime \"__compcert_i64_dtos\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tlong cc_default))\n     (Tcons tdouble Tnil) tlong cc_default)) ::\n (___compcert_i64_dtou,\n   Gfun(External (EF_runtime \"__compcert_i64_dtou\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tlong cc_default))\n     (Tcons tdouble Tnil) tulong cc_default)) ::\n (___compcert_i64_stod,\n   Gfun(External (EF_runtime \"__compcert_i64_stod\"\n                   (mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))\n     (Tcons tlong Tnil) tdouble cc_default)) ::\n (___compcert_i64_utod,\n   Gfun(External (EF_runtime \"__compcert_i64_utod\"\n                   (mksignature (AST.Tlong :: nil) AST.Tfloat cc_default))\n     (Tcons tulong Tnil) tdouble cc_default)) ::\n (___compcert_i64_stof,\n   Gfun(External (EF_runtime \"__compcert_i64_stof\"\n                   (mksignature (AST.Tlong :: nil) AST.Tsingle cc_default))\n     (Tcons tlong Tnil) tfloat cc_default)) ::\n (___compcert_i64_utof,\n   Gfun(External (EF_runtime \"__compcert_i64_utof\"\n                   (mksignature (AST.Tlong :: nil) AST.Tsingle cc_default))\n     (Tcons tulong Tnil) tfloat cc_default)) ::\n (___compcert_i64_sdiv,\n   Gfun(External (EF_runtime \"__compcert_i64_sdiv\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_udiv,\n   Gfun(External (EF_runtime \"__compcert_i64_udiv\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_smod,\n   Gfun(External (EF_runtime \"__compcert_i64_smod\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_umod,\n   Gfun(External (EF_runtime \"__compcert_i64_umod\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_shl,\n   Gfun(External (EF_runtime \"__compcert_i64_shl\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tint Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_shr,\n   Gfun(External (EF_runtime \"__compcert_i64_shr\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tint Tnil)) tulong\n     cc_default)) ::\n (___compcert_i64_sar,\n   Gfun(External (EF_runtime \"__compcert_i64_sar\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tint Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_smulh,\n   Gfun(External (EF_runtime \"__compcert_i64_smulh\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___compcert_i64_umulh,\n   Gfun(External (EF_runtime \"__compcert_i64_umulh\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tulong (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (___builtin_ais_annot,\n   Gfun(External (EF_builtin \"__builtin_ais_annot\"\n                   (mksignature (AST.Tlong :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons (tptr tschar) Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (___builtin_bswap64,\n   Gfun(External (EF_builtin \"__builtin_bswap64\"\n                   (mksignature (AST.Tlong :: nil) AST.Tlong cc_default))\n     (Tcons tulong Tnil) tulong cc_default)) ::\n (___builtin_bswap,\n   Gfun(External (EF_builtin \"__builtin_bswap\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tuint cc_default)) ::\n (___builtin_bswap32,\n   Gfun(External (EF_builtin \"__builtin_bswap32\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tuint cc_default)) ::\n (___builtin_bswap16,\n   Gfun(External (EF_builtin \"__builtin_bswap16\"\n                   (mksignature (AST.Tint :: nil) AST.Tint16unsigned\n                     cc_default)) (Tcons tushort Tnil) tushort cc_default)) ::\n (___builtin_clz,\n   Gfun(External (EF_builtin \"__builtin_clz\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_clzl,\n   Gfun(External (EF_builtin \"__builtin_clzl\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tint cc_default)) ::\n (___builtin_clzll,\n   Gfun(External (EF_builtin \"__builtin_clzll\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tint cc_default)) ::\n (___builtin_ctz,\n   Gfun(External (EF_builtin \"__builtin_ctz\"\n                   (mksignature (AST.Tint :: nil) AST.Tint cc_default))\n     (Tcons tuint Tnil) tint cc_default)) ::\n (___builtin_ctzl,\n   Gfun(External (EF_builtin \"__builtin_ctzl\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tint cc_default)) ::\n (___builtin_ctzll,\n   Gfun(External (EF_builtin \"__builtin_ctzll\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tint cc_default)) ::\n (___builtin_fabs,\n   Gfun(External (EF_builtin \"__builtin_fabs\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_fabsf,\n   Gfun(External (EF_builtin \"__builtin_fabsf\"\n                   (mksignature (AST.Tsingle :: nil) AST.Tsingle cc_default))\n     (Tcons tfloat Tnil) tfloat cc_default)) ::\n (___builtin_fsqrt,\n   Gfun(External (EF_builtin \"__builtin_fsqrt\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_sqrt,\n   Gfun(External (EF_builtin \"__builtin_sqrt\"\n                   (mksignature (AST.Tfloat :: nil) AST.Tfloat cc_default))\n     (Tcons tdouble Tnil) tdouble cc_default)) ::\n (___builtin_memcpy_aligned,\n   Gfun(External (EF_builtin \"__builtin_memcpy_aligned\"\n                   (mksignature\n                     (AST.Tlong :: AST.Tlong :: AST.Tlong :: AST.Tlong ::\n                      nil) AST.Tvoid cc_default))\n     (Tcons (tptr tvoid)\n       (Tcons (tptr tvoid) (Tcons tulong (Tcons tulong Tnil)))) tvoid\n     cc_default)) ::\n (___builtin_sel,\n   Gfun(External (EF_builtin \"__builtin_sel\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons tbool Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (___builtin_annot,\n   Gfun(External (EF_builtin \"__builtin_annot\"\n                   (mksignature (AST.Tlong :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons (tptr tschar) Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (___builtin_annot_intval,\n   Gfun(External (EF_builtin \"__builtin_annot_intval\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tint\n                     cc_default)) (Tcons (tptr tschar) (Tcons tint Tnil))\n     tint cc_default)) ::\n (___builtin_membar,\n   Gfun(External (EF_builtin \"__builtin_membar\"\n                   (mksignature nil AST.Tvoid cc_default)) Tnil tvoid\n     cc_default)) ::\n (___builtin_va_start,\n   Gfun(External (EF_builtin \"__builtin_va_start\"\n                   (mksignature (AST.Tlong :: nil) AST.Tvoid cc_default))\n     (Tcons (tptr tvoid) Tnil) tvoid cc_default)) ::\n (___builtin_va_arg,\n   Gfun(External (EF_builtin \"__builtin_va_arg\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tvoid) (Tcons tuint Tnil))\n     tvoid cc_default)) ::\n (___builtin_va_copy,\n   Gfun(External (EF_builtin \"__builtin_va_copy\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tvoid\n                     cc_default))\n     (Tcons (tptr tvoid) (Tcons (tptr tvoid) Tnil)) tvoid cc_default)) ::\n (___builtin_va_end,\n   Gfun(External (EF_builtin \"__builtin_va_end\"\n                   (mksignature (AST.Tlong :: nil) AST.Tvoid cc_default))\n     (Tcons (tptr tvoid) Tnil) tvoid cc_default)) ::\n (___builtin_unreachable,\n   Gfun(External (EF_builtin \"__builtin_unreachable\"\n                   (mksignature nil AST.Tvoid cc_default)) Tnil tvoid\n     cc_default)) ::\n (___builtin_expect,\n   Gfun(External (EF_builtin \"__builtin_expect\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default)) (Tcons tlong (Tcons tlong Tnil)) tlong\n     cc_default)) ::\n (___builtin_fmax,\n   Gfun(External (EF_builtin \"__builtin_fmax\"\n                   (mksignature (AST.Tfloat :: AST.Tfloat :: nil) AST.Tfloat\n                     cc_default)) (Tcons tdouble (Tcons tdouble Tnil))\n     tdouble cc_default)) ::\n (___builtin_fmin,\n   Gfun(External (EF_builtin \"__builtin_fmin\"\n                   (mksignature (AST.Tfloat :: AST.Tfloat :: nil) AST.Tfloat\n                     cc_default)) (Tcons tdouble (Tcons tdouble Tnil))\n     tdouble cc_default)) ::\n (___builtin_fmadd,\n   Gfun(External (EF_builtin \"__builtin_fmadd\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fmsub,\n   Gfun(External (EF_builtin \"__builtin_fmsub\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fnmadd,\n   Gfun(External (EF_builtin \"__builtin_fnmadd\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_fnmsub,\n   Gfun(External (EF_builtin \"__builtin_fnmsub\"\n                   (mksignature\n                     (AST.Tfloat :: AST.Tfloat :: AST.Tfloat :: nil)\n                     AST.Tfloat cc_default))\n     (Tcons tdouble (Tcons tdouble (Tcons tdouble Tnil))) tdouble\n     cc_default)) ::\n (___builtin_read16_reversed,\n   Gfun(External (EF_builtin \"__builtin_read16_reversed\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint16unsigned\n                     cc_default)) (Tcons (tptr tushort) Tnil) tushort\n     cc_default)) ::\n (___builtin_read32_reversed,\n   Gfun(External (EF_builtin \"__builtin_read32_reversed\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons (tptr tuint) Tnil) tuint cc_default)) ::\n (___builtin_write16_reversed,\n   Gfun(External (EF_builtin \"__builtin_write16_reversed\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tushort) (Tcons tushort Tnil))\n     tvoid cc_default)) ::\n (___builtin_write32_reversed,\n   Gfun(External (EF_builtin \"__builtin_write32_reversed\"\n                   (mksignature (AST.Tlong :: AST.Tint :: nil) AST.Tvoid\n                     cc_default)) (Tcons (tptr tuint) (Tcons tuint Tnil))\n     tvoid cc_default)) ::\n (___builtin_debug,\n   Gfun(External (EF_external \"__builtin_debug\"\n                   (mksignature (AST.Tint :: nil) AST.Tvoid\n                     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|}))\n     (Tcons tint Tnil) tvoid\n     {|cc_vararg:=(Some 1); cc_unproto:=false; cc_structret:=false|})) ::\n (_alloc_make_Coq_Numbers_BinNums_positive_xI,\n   Gfun(External (EF_external \"alloc_make_Coq_Numbers_BinNums_positive_xI\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default))\n     (Tcons (tptr (Tstruct _thread_info noattr)) (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (_alloc_make_Coq_Numbers_BinNums_positive_xO,\n   Gfun(External (EF_external \"alloc_make_Coq_Numbers_BinNums_positive_xO\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default))\n     (Tcons (tptr (Tstruct _thread_info noattr)) (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (_make_Coq_Numbers_BinNums_positive_xH,\n   Gfun(External (EF_external \"make_Coq_Numbers_BinNums_positive_xH\"\n                   (mksignature nil AST.Tlong cc_default)) Tnil tulong\n     cc_default)) ::\n (_make_Coq_Numbers_BinNums_Z_Z0,\n   Gfun(External (EF_external \"make_Coq_Numbers_BinNums_Z_Z0\"\n                   (mksignature nil AST.Tlong cc_default)) Tnil tulong\n     cc_default)) ::\n (_alloc_make_Coq_Numbers_BinNums_Z_Zpos,\n   Gfun(External (EF_external \"alloc_make_Coq_Numbers_BinNums_Z_Zpos\"\n                   (mksignature (AST.Tlong :: AST.Tlong :: nil) AST.Tlong\n                     cc_default))\n     (Tcons (tptr (Tstruct _thread_info noattr)) (Tcons tulong Tnil)) tulong\n     cc_default)) ::\n (_get_Coq_Numbers_BinNums_positive_tag,\n   Gfun(External (EF_external \"get_Coq_Numbers_BinNums_positive_tag\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tuint cc_default)) ::\n (_get_Coq_Numbers_BinNums_Z_tag,\n   Gfun(External (EF_external \"get_Coq_Numbers_BinNums_Z_tag\"\n                   (mksignature (AST.Tlong :: nil) AST.Tint cc_default))\n     (Tcons tulong Tnil) tuint cc_default)) ::\n (_get_Coq_Numbers_BinNums_xI_args,\n   Gfun(External (EF_external \"get_Coq_Numbers_BinNums_xI_args\"\n                   (mksignature (AST.Tlong :: nil) AST.Tlong cc_default))\n     (Tcons tulong Tnil) (tptr (Tstruct _Coq_Numbers_BinNums_xI_args noattr))\n     cc_default)) ::\n (_get_Coq_Numbers_BinNums_xO_args,\n   Gfun(External (EF_external \"get_Coq_Numbers_BinNums_xO_args\"\n                   (mksignature (AST.Tlong :: nil) AST.Tlong cc_default))\n     (Tcons tulong Tnil) (tptr (Tstruct _Coq_Numbers_BinNums_xO_args noattr))\n     cc_default)) ::\n (_get_Coq_Numbers_BinNums_Zpos_args,\n   Gfun(External (EF_external \"get_Coq_Numbers_BinNums_Zpos_args\"\n                   (mksignature (AST.Tlong :: nil) AST.Tlong cc_default))\n     (Tcons tulong Tnil)\n     (tptr (Tstruct _Coq_Numbers_BinNums_Zpos_args noattr)) cc_default)) ::\n (_get_Coq_Numbers_BinNums_Zneg_args,\n   Gfun(External (EF_external \"get_Coq_Numbers_BinNums_Zneg_args\"\n                   (mksignature (AST.Tlong :: nil) AST.Tlong cc_default))\n     (Tcons tulong Tnil)\n     (tptr (Tstruct _Coq_Numbers_BinNums_Zneg_args noattr)) cc_default)) ::\n (_uint63_from_positive, Gfun(Internal f_uint63_from_positive)) ::\n (_uint63_from_Z, Gfun(Internal f_uint63_from_Z)) ::\n (_uint63_to_Z, Gfun(Internal f_uint63_to_Z)) ::\n (_uint63_add, Gfun(Internal f_uint63_add)) ::\n (_uint63_mul, Gfun(Internal f_uint63_mul)) :: nil).\n\nDefinition public_idents : list ident :=\n(_uint63_mul :: _uint63_add :: _uint63_to_Z :: _uint63_from_Z ::\n _uint63_from_positive :: _get_Coq_Numbers_BinNums_Zneg_args ::\n _get_Coq_Numbers_BinNums_Zpos_args :: _get_Coq_Numbers_BinNums_xO_args ::\n _get_Coq_Numbers_BinNums_xI_args :: _get_Coq_Numbers_BinNums_Z_tag ::\n _get_Coq_Numbers_BinNums_positive_tag ::\n _alloc_make_Coq_Numbers_BinNums_Z_Zpos :: _make_Coq_Numbers_BinNums_Z_Z0 ::\n _make_Coq_Numbers_BinNums_positive_xH ::\n _alloc_make_Coq_Numbers_BinNums_positive_xO ::\n _alloc_make_Coq_Numbers_BinNums_positive_xI :: ___builtin_debug ::\n ___builtin_write32_reversed :: ___builtin_write16_reversed ::\n ___builtin_read32_reversed :: ___builtin_read16_reversed ::\n ___builtin_fnmsub :: ___builtin_fnmadd :: ___builtin_fmsub ::\n ___builtin_fmadd :: ___builtin_fmin :: ___builtin_fmax ::\n ___builtin_expect :: ___builtin_unreachable :: ___builtin_va_end ::\n ___builtin_va_copy :: ___builtin_va_arg :: ___builtin_va_start ::\n ___builtin_membar :: ___builtin_annot_intval :: ___builtin_annot ::\n ___builtin_sel :: ___builtin_memcpy_aligned :: ___builtin_sqrt ::\n ___builtin_fsqrt :: ___builtin_fabsf :: ___builtin_fabs ::\n ___builtin_ctzll :: ___builtin_ctzl :: ___builtin_ctz :: ___builtin_clzll ::\n ___builtin_clzl :: ___builtin_clz :: ___builtin_bswap16 ::\n ___builtin_bswap32 :: ___builtin_bswap :: ___builtin_bswap64 ::\n ___builtin_ais_annot :: ___compcert_i64_umulh :: ___compcert_i64_smulh ::\n ___compcert_i64_sar :: ___compcert_i64_shr :: ___compcert_i64_shl ::\n ___compcert_i64_umod :: ___compcert_i64_smod :: ___compcert_i64_udiv ::\n ___compcert_i64_sdiv :: ___compcert_i64_utof :: ___compcert_i64_stof ::\n ___compcert_i64_utod :: ___compcert_i64_stod :: ___compcert_i64_dtou ::\n ___compcert_i64_dtos :: ___compcert_va_composite ::\n ___compcert_va_float64 :: ___compcert_va_int64 :: ___compcert_va_int32 ::\n nil).\n\nDefinition prog : Clight.program := \n  mkprogram composites global_definitions public_idents _main Logic.I.\n\n\n", "meta": {"author": "CertiCoq", "repo": "VeriFFI", "sha": "ebbb54ef79805ab47af1898fb33ccc58c3890614", "save_path": "github-repos/coq/CertiCoq-VeriFFI", "path": "github-repos/coq/CertiCoq-VeriFFI/VeriFFI-ebbb54ef79805ab47af1898fb33ccc58c3890614/examples/uint63/prims.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.22590486564194925}}
{"text": "From iris.proofmode Require Import proofmode.\nFrom iris.algebra Require Import vector list.\nFrom lrust.typing Require Export type.\nFrom lrust.typing Require Import own programs cont.\nFrom iris.prelude Require Import options.\n\nSection fn.\n  Context `{!typeGS Σ} {A : Type} {n : nat}.\n\n  Record fn_params := FP { fp_E : lft → elctx; fp_tys : vec type n; fp_ty : type }.\n\n  Definition FP_wf E (tys : vec type n) `{!ListTyWf tys} ty `{!TyWf ty} :=\n    FP (λ ϝ, E ϝ ++ tyl_wf_E tys ++ tyl_outlives_E tys ϝ ++\n                    ty_wf_E ty ++ ty_outlives_E ty ϝ)\n       tys ty.\n\n  (* The other alternative for defining the fn type would be to state\n     that the value applied to its parameters is a typed body whose type\n     is the return type.\n     That would be slightly simpler, but, unfortunately, we are no longer\n     able to prove that this is contractive. *)\n  Program Definition fn (fp : A → fn_params) : type :=\n    {| st_own tid vl := tc_opaque (∃ fb kb xb e H,\n         ⌜vl = [@RecV fb (kb::xb) e H]⌝ ∗ ⌜length xb = n⌝ ∗\n         ▷ ∀ (x : A) (ϝ : lft) (k : val) (xl : vec val (length xb)),\n            □ typed_body ((fp x).(fp_E) ϝ) [ϝ ⊑ₗ []]\n                         [k◁cont([ϝ ⊑ₗ []], λ v : vec _ 1, [(v!!!0%fin:val) ◁ box (fp x).(fp_ty)])]\n                         (zip_with (TCtx_hasty ∘ of_val) xl\n                                   (box <$> (vec_to_list (fp x).(fp_tys))))\n                         (subst_v (fb::kb::xb) (RecV fb (kb::xb) e:::k:::xl) e))%I |}.\n  Next Obligation.\n    iIntros (fp tid vl) \"H\". iDestruct \"H\" as (fb kb xb e ?) \"[% _]\". by subst.\n  Qed.\n  Next Obligation.\n    unfold tc_opaque. apply _.\n  Qed.\n\n  (* FIXME : This definition is less restrictive than the one used in\n     Rust. In Rust, the type of parameters are taken into account for\n     well-formedness, and all the liftime constrains relating a\n     generalized liftime are ignored. For simplicity, we ignore all of\n     them, but this is not very faithful. *)\n  Global Instance fn_wf fp : TyWf (fn fp) :=\n    { ty_lfts := []; ty_wf_E := [] }.\n\n  Global Instance fn_send fp : Send (fn fp).\n  Proof. iIntros (tid1 tid2 vl). done. Qed.\n\n  Definition fn_params_rel (ty_rel : relation type) : relation fn_params :=\n    λ fp1 fp2,\n      Forall2 ty_rel fp2.(fp_tys) fp1.(fp_tys) ∧ ty_rel fp1.(fp_ty) fp2.(fp_ty) ∧\n      pointwise_relation lft eq fp1.(fp_E) fp2.(fp_E).\n\n  Global Instance fp_tys_proper R :\n    Proper (flip (fn_params_rel R) ==> (Forall2 R : relation (vec _ _))) fp_tys.\n  Proof. intros ?? HR. apply HR. Qed.\n  Global Instance fp_tys_proper_flip R :\n    Proper (fn_params_rel R ==> flip (Forall2 R : relation (vec _ _))) fp_tys.\n  Proof. intros ?? HR. apply HR. Qed.\n\n  Global Instance fp_ty_proper R :\n    Proper (fn_params_rel R ==> R) fp_ty.\n  Proof. intros ?? HR. apply HR. Qed.\n\n  Global Instance fp_E_proper R :\n    Proper (fn_params_rel R ==> eq ==> eq) fp_E.\n  Proof. intros ?? HR ??->. apply HR. Qed.\n\n  Global Instance FP_proper R :\n    Proper (pointwise_relation lft eq ==>\n            flip (Forall2 R : relation (vec _ _)) ==> R ==>\n            fn_params_rel R) FP.\n  Proof. by split; [|split]. Qed.\n\n  Global Instance fn_type_contractive n' :\n    Proper (pointwise_relation A (fn_params_rel (type_dist2_later n')) ==>\n            type_dist2 n') fn.\n  Proof.\n    intros fp1 fp2 Hfp. apply ty_of_st_type_ne. destruct n'; first done.\n    constructor; unfold ty_own; simpl.\n    (* TODO: 'f_equiv' is slow here because reflexivity is slow. *)\n    (* The clean way to do this would be to have a metric on type contexts. Oh well. *)\n    intros tid vl. unfold typed_body.\n    do 12 f_equiv. f_contractive.\n    do 18 ((eapply fp_E_proper; try reflexivity) || exact: Hfp || f_equiv).\n    - rewrite !cctx_interp_singleton /=. do 5 f_equiv.\n      rewrite !tctx_interp_singleton /tctx_elt_interp /=.\n      do 5 f_equiv. apply type_dist2_dist. apply Hfp.\n    - rewrite /tctx_interp !big_sepL_zip_with /=. do 4 f_equiv.\n      cut (∀ n tid p i, Proper (dist n ==> dist n)\n        (λ (l : list type),\n            match l !! i with\n            | Some ty => tctx_elt_interp tid (p ◁ ty) | None => emp\n            end)%I).\n      { intros Hprop. apply Hprop, list_fmap_ne; last first.\n        - symmetry. eapply Forall2_impl; first apply Hfp. intros.\n          apply dist_later_dist, type_dist2_dist_later. done.\n        - apply _. }\n      clear. intros n tid p i x y. rewrite list_dist_lookup=>/(_ i).\n      case _ : (x !! i)=>[tyx|]; case  _ : (y !! i)=>[tyy|];\n        inversion_clear 1; [solve_proper|done].\n  Qed.\n\n  Global Instance fn_ne n' :\n    Proper (pointwise_relation A (fn_params_rel (dist n')) ==> dist n') fn.\n  Proof.\n    intros ?? Hfp. apply dist_later_dist, type_dist2_dist_later.\n    apply fn_type_contractive=>u. split; last split.\n    - eapply Forall2_impl; first apply Hfp. intros. simpl.\n      apply type_dist_dist2. done.\n    - apply type_dist_dist2. apply Hfp.\n    - apply Hfp.\n  Qed.\nEnd fn.\n\nGlobal Arguments fn_params {_ _} _.\n\n(* We use recursive notation for binders as well, to allow patterns\n   like '(a, b) to be used. In practice, only one binder is ever used,\n   but using recursive binders is the only way to make Coq accept\n   patterns. *)\n(* FIXME : because of a bug in Coq, such patterns only work for\n   printing. Once on 8.6pl1, this should work.  *)\nNotation \"'fn(∀' x .. x' ',' E ';' T1 ',' .. ',' TN ')' '→' R\" :=\n  (fn (λ x, (.. (λ x',\n      FP_wf E%EL (Vector.cons T1%T .. (Vector.cons TN%T Vector.nil) ..) R%T)..)))\n  (at level 99, R at level 200, x binder, x' binder,\n   format \"'fn(∀'  x .. x' ','  E ';'  T1 ','  .. ','  TN ')'  '→'  R\") : lrust_type_scope.\nNotation \"'fn(∀' x .. x' ',' E ')' '→' R\" :=\n  (fn (λ x, (.. (λ x', FP_wf E%EL Vector.nil R%T)..)))\n  (at level 99, R at level 200, x binder, x' binder,\n   format \"'fn(∀'  x .. x' ','  E ')'  '→'  R\") : lrust_type_scope.\nNotation \"'fn(' E ';' T1 ',' .. ',' TN ')' '→' R\" :=\n  (fn (λ _:(), FP_wf E%EL (Vector.cons T1%T .. (Vector.cons TN%T Vector.nil) ..) R%T))\n  (at level 99, R at level 200,\n   format \"'fn(' E ';'  T1 ','  .. ','  TN ')'  '→'  R\") : lrust_type_scope.\nNotation \"'fn(' E ')' '→' R\" :=\n  (fn (λ _:(), FP_wf E%EL Vector.nil R%T))\n  (at level 99, R at level 200,\n   format \"'fn(' E ')'  '→'  R\") : lrust_type_scope.\n\nGlobal Instance elctx_empty : Empty (lft → elctx) := λ ϝ, [].\n\nSection typing.\n  Context `{!typeGS Σ}.\n\n  Lemma fn_subtype {A n} E0 L0 (fp fp' : A → fn_params n) :\n    (∀ x ϝ, let EE := E0 ++ (fp' x).(fp_E) ϝ in\n            elctx_sat EE L0 ((fp x).(fp_E) ϝ) ∧\n            Forall2 (subtype EE L0) (fp' x).(fp_tys) (fp x).(fp_tys) ∧\n            subtype EE L0 (fp x).(fp_ty) (fp' x).(fp_ty)) →\n    subtype E0 L0 (fn fp) (fn fp').\n  Proof.\n    intros Hcons. apply subtype_simple_type=>//= qmax qL. iIntros \"HL0\".\n    (* We massage things so that we can throw away HL0 before going under the box. *)\n    iAssert (∀ x ϝ, let EE := E0 ++ (fp' x).(fp_E) ϝ in □ (elctx_interp EE -∗\n                 elctx_interp ((fp x).(fp_E) ϝ) ∗\n                 ([∗ list] tys ∈ (zip (fp' x).(fp_tys) (fp x).(fp_tys)), type_incl (tys.1) (tys.2)) ∗\n                 type_incl (fp x).(fp_ty) (fp' x).(fp_ty)))%I as \"#Hcons\".\n    { iIntros (x ϝ). destruct (Hcons x ϝ) as (HE &Htys &Hty). clear Hcons.\n      iDestruct (HE with \"HL0\") as \"#HE\".\n      iDestruct (subtype_Forall2_llctx_noend with \"HL0\") as \"#Htys\"; first done.\n      iDestruct (Hty with \"HL0\") as \"#Hty\".\n      iClear \"∗\". iIntros \"!> #HEE\".\n      iSplit; last iSplit.\n      - by iApply \"HE\".\n      - by iApply \"Htys\".\n      - by iApply \"Hty\". }\n    iClear \"∗\". clear Hcons. iIntros \"!> #HE0 * Hf\".\n    iDestruct \"Hf\" as (fb kb xb e ?) \"[% [% #Hf]]\". subst.\n    iExists fb, kb, xb, e, _. iSplit; first done. iSplit; first done. iNext.\n    rewrite /typed_body. iIntros (x ϝ k xl) \"!> * #LFT #HE' Htl HL HC HT\".\n    iDestruct (\"Hcons\" with \"[$]\") as \"#(HE & Htys & Hty)\".\n    iApply (\"Hf\" with \"LFT HE Htl HL [HC] [HT]\").\n    - unfold cctx_interp. iIntros (elt) \"Helt\".\n      iDestruct \"Helt\" as %->%elem_of_list_singleton. iIntros (ret) \"Htl HL HT\".\n      unfold cctx_elt_interp.\n      iApply (\"HC\" $! (_ ◁cont(_, _)) with \"[%] Htl HL [> -]\").\n      { by apply elem_of_list_singleton. }\n      rewrite /tctx_interp !big_sepL_singleton /=.\n      iDestruct \"HT\" as (v) \"[HP Hown]\". iExists v. iFrame \"HP\".\n      iDestruct (box_type_incl with \"[$Hty]\") as \"(_ & #Hincl & _)\".\n      by iApply \"Hincl\".\n    - iClear \"Hf\". rewrite /tctx_interp\n         -{2}(fst_zip (fp x).(fp_tys) (fp' x).(fp_tys)) ?vec_to_list_length //\n         -{2}(snd_zip (fp x).(fp_tys) (fp' x).(fp_tys)) ?vec_to_list_length //\n         !zip_with_fmap_r !(zip_with_zip (λ _ _, (_ ∘ _) _ _)) !big_sepL_fmap.\n      iApply (big_sepL_impl with \"HT\"). iIntros \"!>\".\n      iIntros (i [p [ty1' ty2']]) \"#Hzip H /=\".\n      iDestruct \"H\" as (v) \"[? Hown]\". iExists v. iFrame.\n      rewrite !lookup_zip_with.\n      iDestruct \"Hzip\" as %(? & ? & ([? ?] & (? & Hty'1 &\n        (? & Hty'2 & [=->->])%bind_Some)%bind_Some & [=->->->])%bind_Some)%bind_Some.\n      iDestruct (big_sepL_lookup with \"Htys\") as \"#Hty'\".\n      { rewrite lookup_zip_with /=. erewrite Hty'2. simpl. by erewrite Hty'1. }\n      iDestruct (box_type_incl with \"[$Hty']\") as \"(_ & #Hincl & _)\".\n      by iApply \"Hincl\".\n  Qed.\n\n  (* This proper and the next can probably not be inferred, but oh well. *)\n  Global Instance fn_subtype' {A n} E0 L0 :\n    Proper (pointwise_relation A (fn_params_rel (n:=n) (subtype E0 L0)) ==>\n            subtype E0 L0) fn.\n  Proof.\n    intros fp1 fp2 Hfp. apply fn_subtype=>x ϝ. destruct (Hfp x) as (Htys & Hty & HE).\n    split; last split.\n    - rewrite (HE ϝ). solve_typing.\n    - eapply Forall2_impl; first eapply Htys. intros ??.\n      eapply subtype_weaken; last done. by apply submseteq_inserts_r.\n    - eapply subtype_weaken, Hty; last done. by apply submseteq_inserts_r.\n  Qed.\n\n  Global Instance fn_eqtype' {A n} E0 L0 :\n    Proper (pointwise_relation A (fn_params_rel (n:=n) (eqtype E0 L0)) ==>\n            eqtype E0 L0) fn.\n  Proof.\n    intros fp1 fp2 Hfp. split; eapply fn_subtype=>x ϝ; destruct (Hfp x) as (Htys & Hty & HE); (split; last split).\n    - rewrite (HE ϝ). solve_typing.\n    - eapply Forall2_impl; first eapply Htys. intros t1 t2 Ht.\n      eapply subtype_weaken; last apply Ht; last done. by apply submseteq_inserts_r.\n    - eapply subtype_weaken; last apply Hty; last done. by apply submseteq_inserts_r.\n    - rewrite (HE ϝ). solve_typing.\n    - symmetry in Htys. eapply Forall2_impl; first eapply Htys. intros t1 t2 Ht.\n      eapply subtype_weaken; last apply Ht; last done. by apply submseteq_inserts_r.\n    - eapply subtype_weaken; last apply Hty; last done. by apply submseteq_inserts_r.\n  Qed.\n\n  Lemma fn_subtype_specialize {A B n} (σ : A → B) E0 L0 fp :\n    subtype E0 L0 (fn (n:=n) fp) (fn (fp ∘ σ)).\n  Proof.\n    apply subtype_simple_type=>//= qmax qL.\n    iIntros \"_ !> _ * Hf\". iDestruct \"Hf\" as (fb kb xb e ?) \"[% [% #Hf]]\". subst.\n    iExists fb, kb, xb, e, _. iSplit; first done. iSplit; first done.\n    rewrite /typed_body. iNext. iIntros \"*\". iApply \"Hf\".\n  Qed.\n\n  (* In principle, proving this hard-coded to an empty L would be sufficient --\n     but then we would have to require elctx_sat as an Iris assumption. *)\n  Lemma type_call_iris' E L (κs : list lft) {A} x (ps : list path) qκs qmax qL tid\n        p (k : expr) (fp : A → fn_params (length ps)) :\n    (∀ ϝ, elctx_sat (((λ κ, ϝ ⊑ₑ κ) <$> κs) ++ E) L ((fp x).(fp_E) ϝ)) →\n    AsVal k →\n    lft_ctx -∗ elctx_interp E -∗ na_own tid ⊤ -∗ llctx_interp_noend qmax L qL -∗\n    qκs.[lft_intersect_list κs] -∗\n    tctx_elt_interp tid (p ◁ fn fp) -∗\n    ([∗ list] y ∈ zip_with TCtx_hasty ps (box <$> vec_to_list (fp x).(fp_tys)),\n                   tctx_elt_interp tid y) -∗\n    (∀ ret, na_own tid top -∗ llctx_interp_noend qmax L qL -∗ qκs.[lft_intersect_list κs] -∗\n             (box (fp x).(fp_ty)).(ty_own) tid [ret] -∗\n             WP k [of_val ret] {{ _, cont_postcondition }}) -∗\n    WP (call: p ps → k) {{ _, cont_postcondition }}.\n  Proof.\n    iIntros (HE [k' <-]) \"#LFT #HE Htl HL Hκs Hf Hargs Hk\".\n    wp_apply (wp_hasty with \"Hf\"). iIntros (v) \"% Hf\".\n    iApply (wp_app_vec _ _ (_::_) ((λ v, ⌜v = (λ: [\"_r\"], k' [\"_r\"])%V⌝):::\n               vmap (λ ty (v : val), tctx_elt_interp tid (v ◁ box ty)) (fp x).(fp_tys))%I\n            with \"[Hargs]\").\n    - rewrite /=. iSplitR \"Hargs\".\n      { simpl. iApply wp_value. by unlock. }\n      remember (fp_tys (fp x)) as tys. clear dependent k' p HE fp x.\n      iInduction ps as [|p ps] \"IH\" forall (tys); first by simpl.\n      simpl in tys. inv_vec tys=>ty tys. simpl.\n      iDestruct \"Hargs\" as \"[HT Hargs]\". iSplitL \"HT\".\n      + iApply (wp_hasty with \"HT\"). iIntros (?). rewrite tctx_hasty_val. iIntros \"? $\".\n      + iApply \"IH\". done.\n    - simpl. change (@length expr ps) with (length ps).\n      iIntros (vl'). inv_vec vl'=>kv vl; csimpl.\n      iIntros \"[-> Hvl]\". iDestruct \"Hf\" as (fb kb xb e ?) \"[EQ [EQl #Hf]]\".\n      iDestruct \"EQ\" as %[=->]. iDestruct \"EQl\" as %EQl.\n      revert vl fp HE. rewrite /= -EQl=>vl fp HE. wp_rec.\n      iMod (lft_create with \"LFT\") as (ϝ_inner) \"[Htk #Hend]\"; first done.\n      set (ϝ := ϝ_inner ⊓ lft_intersect_list κs).\n      iSpecialize (\"Hf\" $! x ϝ _ vl). iDestruct (HE ϝ with \"HL\") as \"#HE'\".\n      destruct (Qp_lower_bound qκs 1) as (q0 & q'1 & q'2 & -> & Hsum1).\n      rewrite Hsum1. assert (q0 < 1)%Qp as Hq0.\n      { apply Qp_lt_sum. eauto. }\n      clear Hsum1.\n      iDestruct \"Htk\" as \"[Htk1 Htk2]\".\n      iDestruct \"Hκs\" as \"[Hκs1 Hκs2]\".\n      iApply (\"Hf\" $! _ q0 with \"LFT [] Htl [Hκs1 Htk1 Htk2] [Hk HL Hκs2]\").\n      + iApply \"HE'\". iFrame \"HE\".\n        iIntros \"{$# Hf Hend HE' LFT HE %}\". subst ϝ.\n        iApply big_sepL_forall.\n        iIntros (i [κ1 κ2] [κ [Hpair Helem]]%elem_of_list_lookup_2%elem_of_list_fmap).\n        injection Hpair as -> ->. iPureIntro. simpl.\n        eapply lft_incl_syn_trans; first by apply lft_intersect_incl_syn_r.\n        apply lft_intersect_list_elem_of_incl_syn.\n        done.\n      + iSplitL; last done. iExists ϝ. rewrite left_id. iSplit; first done.\n        rewrite decide_False; last first.\n        { apply Qp_lt_nge. done. }\n        subst ϝ. rewrite -!lft_tok_sep. iFrame. iIntros \"[Htk1 _]\".\n        rewrite -lft_dead_or. rewrite -bi.or_intro_l. iApply \"Hend\". iFrame.\n      + iIntros (y) \"IN {Hend}\". iDestruct \"IN\" as %->%elem_of_list_singleton.\n        iIntros (args) \"Htl [Hϝ _] [Hret _]\". inv_vec args=>r.\n        iDestruct \"Hϝ\" as  (κ') \"(EQ & Htk & _)\". iDestruct \"EQ\" as %EQ.\n        rewrite /= left_id in EQ. subst κ' ϝ.\n        rewrite decide_False; last first.\n        { apply Qp_lt_nge. done. }\n        rewrite -lft_tok_sep. iDestruct \"Htk\" as \"[_ Hκs1]\". wp_rec.\n        iApply (\"Hk\" with \"Htl HL [$Hκs1 $Hκs2]\"). rewrite tctx_hasty_val. done.\n      + rewrite /tctx_interp vec_to_list_map !zip_with_fmap_r\n                (zip_with_zip (λ v ty, (v, _))) zip_with_zip !big_sepL_fmap.\n        iApply (big_sepL_mono' with \"Hvl\"); last done. by iIntros (i [v ty']).\n  Qed.\n\n  Lemma type_call_iris E (κs : list lft) {A} x (ps : list path) qκs tid\n        f (k : expr) (fp : A → fn_params (length ps)) :\n    (∀ ϝ, elctx_sat (((λ κ, ϝ ⊑ₑ κ) <$> κs) ++ E) [] ((fp x).(fp_E) ϝ)) →\n    AsVal k →\n    lft_ctx -∗ elctx_interp E -∗ na_own tid ⊤ -∗\n    qκs.[lft_intersect_list κs] -∗\n    (fn fp).(ty_own) tid [f] -∗\n    ([∗ list] y ∈ zip_with TCtx_hasty ps (box <$> vec_to_list (fp x).(fp_tys)),\n                   tctx_elt_interp tid y) -∗\n    (∀ ret, na_own tid top -∗ qκs.[lft_intersect_list κs] -∗\n             (box (fp x).(fp_ty)).(ty_own) tid [ret] -∗\n             WP k [of_val ret] {{ _, cont_postcondition }}) -∗\n    WP (call: f ps → k) {{ _, cont_postcondition }}.\n  Proof.\n    iIntros (HE Hk') \"#LFT #HE Htl Hκs Hf Hargs Hk\". rewrite -tctx_hasty_val.\n    iApply (type_call_iris' with \"LFT HE Htl [] Hκs Hf Hargs [Hk]\"); [done..| |].\n    - instantiate (1 := 1%Qp). instantiate (1 := 1%Qp). by rewrite /llctx_interp_noend.\n    - iIntros \"* Htl _\". iApply \"Hk\". done.\n  Qed.\n\n  Lemma type_call' E L (κs : list lft) T p (ps : list path)\n                   {A} (fp : A → fn_params (length ps)) (k : val) x :\n    Forall (lctx_lft_alive E L) κs →\n    (∀ ϝ, elctx_sat (((λ κ, ϝ ⊑ₑ κ) <$> κs) ++ E) L ((fp x).(fp_E) ϝ)) →\n    ⊢ typed_body E L [k ◁cont(L, λ v : vec _ 1, ((v!!!0%fin:val) ◁ box (fp x).(fp_ty)) :: T)]\n               ((p ◁ fn fp) ::\n                zip_with TCtx_hasty ps (box <$> vec_to_list (fp x).(fp_tys)) ++\n                T)\n               (call: p ps → k).\n  Proof.\n    iIntros (Hκs HE tid qmax) \"#LFT #HE Htl HL HC (Hf & Hargs & HT)\".\n    iMod (lctx_lft_alive_tok_list _ _ κs with \"HE HL\") as (q) \"(Hκs & HL & Hclose)\"; [done..|].\n    iApply (type_call_iris' with \"LFT HE Htl HL Hκs Hf Hargs\"); [done|].\n    iIntros (r) \"Htl HL Hκs Hret\". iMod (\"Hclose\" with \"Hκs HL\") as \"HL\".\n    iSpecialize (\"HC\" with \"[]\"); first by (iPureIntro; apply elem_of_list_singleton).\n    iApply (\"HC\" $! [#r] with \"Htl HL\").\n    rewrite tctx_interp_cons tctx_hasty_val. iFrame.\n  Qed.\n\n  (* Specialized type_call':  Adapted for use by solve_typing.\n     κs is still expected to be given manually. *)\n  Lemma type_call {A} κs x E L C T T' T'' p (ps : list path)\n                        (fp : A → fn_params (length ps)) k :\n    p ◁ fn fp ∈ T →\n    Forall (lctx_lft_alive E L) κs →\n    (∀ ϝ, elctx_sat (((λ κ, ϝ ⊑ₑ κ) <$> κs) ++ E) L ((fp x).(fp_E) ϝ)) →\n    tctx_extract_ctx E L (zip_with TCtx_hasty ps\n                                   (box <$> vec_to_list (fp x).(fp_tys))) T T' →\n    k ◁cont(L, T'') ∈ C →\n    (∀ ret : val, tctx_incl E L ((ret ◁ box (fp x).(fp_ty))::T') (T'' [# ret])) →\n    ⊢ typed_body E L C T (call: p ps → k).\n  Proof.\n    intros Hfn HL HE HTT' HC HT'T''.\n    rewrite -typed_body_mono /flip; last done; first by eapply type_call'.\n    - etrans.\n      + eapply (incl_cctx_incl _ [_]); by intros ? ->%elem_of_list_singleton.\n      + apply cctx_incl_cons; first done. intros args. by inv_vec args.\n    - etrans; last by apply (tctx_incl_frame_l [_]).\n      apply copy_elem_of_tctx_incl; last done. apply _.\n  Qed.\n\n  Lemma type_letcall {A} x E L C T T' p (ps : list path)\n                        (fp : A → fn_params (length ps)) b e :\n    Closed (b :b: []) e → Closed [] p → Forall (Closed []) ps →\n    p ◁ fn fp ∈ T →\n    Forall (lctx_lft_alive E L) (L.*1) →\n    (∀ ϝ, elctx_sat (((λ κ, ϝ ⊑ₑ κ) <$> (L.*1)) ++ E) L ((fp x).(fp_E) ϝ)) →\n    tctx_extract_ctx E L (zip_with TCtx_hasty ps\n                                   (box <$> vec_to_list (fp x).(fp_tys))) T T' →\n    (∀ ret : val, typed_body E L C ((ret ◁ box (fp x).(fp_ty))::T') (subst' b ret e)) -∗\n    typed_body E L C T (letcall: b := p ps in e).\n  Proof.\n    iIntros (?? Hpsc ????) \"He\".\n    iApply (type_cont_norec [_] _ (λ r, ((r!!!0%fin:val) ◁ box (fp x).(fp_ty)) :: T')).\n    - (* TODO : make [solve_closed] work here. *)\n      eapply is_closed_weaken; first done. set_solver+.\n    - (* TODO : make [solve_closed] work here. *)\n      rewrite /Closed /= !andb_True. split.\n      + by eapply is_closed_weaken, list_subseteq_nil.\n      + eapply Is_true_eq_left, forallb_forall, List.Forall_forall, Forall_impl=>//.\n        intros. eapply Is_true_eq_true, is_closed_weaken=>//. set_solver+.\n    - iIntros (k).\n      (* TODO : make [simpl_subst] work here. *)\n      change (subst' \"_k\" k (p ((λ: [\"_r\"], \"_k\" [\"_r\"])%E :: ps))) with\n             ((subst \"_k\" k p) ((λ: [\"_r\"], k [\"_r\"])%E :: map (subst \"_k\" k) ps)).\n      rewrite is_closed_nil_subst //.\n      assert (map (subst \"_k\" k) ps = ps) as ->.\n      { clear -Hpsc. induction Hpsc=>//=. rewrite is_closed_nil_subst //. congruence. }\n      iApply type_call; try done.\n      + constructor.\n      + done.\n    - simpl. iIntros (k ret). inv_vec ret=>ret. rewrite /subst_v /=.\n      rewrite ->(is_closed_subst []); last set_solver+; last first.\n      { apply subst'_is_closed; last done. apply is_closed_of_val. }\n      (iApply typed_body_mono; last by iApply \"He\"); [|done..].\n      apply incl_cctx_incl. set_solver+.\n  Qed.\n\n  Lemma type_rec {A} E L fb (argsb : list binder) ef e n\n        (fp : A → fn_params n) T `{!CopyC T, !SendC T, !Closed _ e} :\n    IntoVal ef (fnrec: fb argsb := e) →\n    n = length argsb →\n    □ (∀ x ϝ (f : val) k (args : vec val (length argsb)),\n          typed_body ((fp x).(fp_E) ϝ) [ϝ ⊑ₗ []]\n                     [k ◁cont([ϝ ⊑ₗ []], λ v : vec _ 1, [(v!!!0%fin:val) ◁ box (fp x).(fp_ty)])]\n                     ((f ◁ fn fp) ::\n                        zip_with (TCtx_hasty ∘ of_val) args\n                                 (box <$> vec_to_list (fp x).(fp_tys)) ++ T)\n                     (subst_v (fb :: BNamed \"return\" :: argsb) (f ::: k ::: args) e)) -∗\n    typed_instruction_ty E L T ef (fn fp).\n  Proof.\n    iIntros (<- ->) \"#Hbody /=\". iIntros (tid qmax) \"#LFT _ $ $ #HT\". iApply wp_value.\n    rewrite tctx_interp_singleton. iLöb as \"IH\". iExists _. iSplit.\n    { simpl. rewrite decide_True_pi. done. }\n    iExists fb, _, argsb, e, _. iSplit; first done. iSplit; first done. iNext.\n    iIntros (x ϝ k args) \"!>\". iIntros (tid' qmax') \"_ HE Htl HL HC HT'\".\n    iApply (\"Hbody\" with \"LFT HE Htl HL HC\").\n    rewrite tctx_interp_cons tctx_interp_app. iFrame \"HT' IH\".\n    by iApply sendc_change_tid.\n  Qed.\n\n  Lemma type_fn {A} E L (argsb : list binder) ef e n\n        (fp : A → fn_params n) T `{!CopyC T, !SendC T, !Closed _ e} :\n    IntoVal ef (fn: argsb := e) →\n    n = length argsb →\n    □ (∀ x ϝ k (args : vec val (length argsb)),\n        typed_body ((fp x).(fp_E) ϝ)\n                   [ϝ ⊑ₗ []]\n                   [k ◁cont([ϝ ⊑ₗ []], λ v : vec _ 1, [(v!!!0%fin:val) ◁ box (fp x).(fp_ty)])]\n                   (zip_with (TCtx_hasty ∘ of_val) args\n                             (box <$> vec_to_list (fp x).(fp_tys)) ++ T)\n                   (subst_v (BNamed \"return\" :: argsb) (k ::: args) e)) -∗\n    typed_instruction_ty E L T ef (fn fp).\n  Proof.\n    iIntros (??) \"#He\". iApply type_rec; try done. iIntros \"!> *\".\n    iApply typed_body_mono; last iApply \"He\"; try done.\n    eapply contains_tctx_incl. by constructor.\n  Qed.\nEnd typing.\n\nGlobal Hint Resolve fn_subtype : lrust_typing.\n", "meta": {"author": "lambdaxymox", "repo": "LambdaRust-coq", "sha": "4b96b6dece1564263d7620f1d5df80ead3b9cdc3", "save_path": "github-repos/coq/lambdaxymox-LambdaRust-coq", "path": "github-repos/coq/lambdaxymox-LambdaRust-coq/LambdaRust-coq-4b96b6dece1564263d7620f1d5df80ead3b9cdc3/theories/typing/function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22590486000420426}}
{"text": "Require Import Coq.omega.Omega.\nRequire Import Platform.AutoSep.\nRequire Import Platform.Cito.SyntaxExpr.\n\nRequire Import Bedrock.StringSet.\nImport StringSet.\nRequire Import Coq.FSets.FSetProperties.\nModule Import SSP := Properties StringSet.\n\nSet Implicit Arguments.\n\nSection ExprComp.\n\n  Variable vars : list string.\n\n  Variable temp_size : nat.\n\n  Definition vars_start := 4 * 2.\n  Definition var_slot x := LvMem (Sp + (vars_start + variablePosition vars x)%nat)%loc.\n  Definition temp_start := vars_start + 4 * length vars.\n  Definition temp_slot n := LvMem (Sp + (temp_start + 4 * n)%nat)%loc.\n\n  Definition is_state sp vs temps : HProp :=\n    (locals vars vs 0 (sp ^+ $8) *\n     array temps (sp ^+ $8 ^+ $ (4 * length vars)))%Sep.\n\n  Definition new_pre : assert :=\n    x ~> ExX, Ex vs, Ex temps,\n    ![^[is_state x#Sp vs temps] * #0]x /\\\n    [| length temps = temp_size |].\n\n  Require Import Platform.Cito.SemanticsExpr.\n  Require Import Platform.Cito.DepthExpr.\n  Require Import Platform.Cito.ListFacts5.\n\n  Local Open Scope nat.\n\n  Definition runs_to expr base x_pre x :=\n    forall specs other vs temps,\n      interp specs (![is_state x_pre#Sp vs temps * other ] x_pre)\n      -> length temps = temp_size\n      -> Regs x Sp = x_pre#Sp /\\\n      exists changed,\n        interp specs (![is_state (Regs x Sp) vs (upd_sublist temps base changed) * other ] (fst x_pre, x)) /\\\n        length changed <= depth expr /\\\n        Regs x Rv = eval vs expr.\n\n  Definition post expr base (pre : assert) :=\n    st ~> Ex st_pre,\n    pre (fst st, st_pre) /\\\n    [| runs_to expr base (fst st, st_pre) (snd st) |].\n\n  Definition imply (pre new_pre: assert) := forall specs x, interp specs (pre x) -> interp specs (new_pre x).\n\n  Require Import Platform.Cito.FreeVarsExpr.\n\n  Definition syn_req expr base :=\n    Subset (free_vars expr) (of_list vars) /\\\n    base + depth expr <= temp_size.\n\n  Definition verifCond expr base pre := imply pre new_pre :: syn_req expr base :: nil.\n\n  Variable imports : LabelMap.t assert.\n\n  Variable imports_global : importsGlobal imports.\n\n  Variable modName : string.\n\n  Definition Seq2 := @Seq_ _ imports_global modName.\n\n  Definition Skip := Straightline_ imports modName nil.\n\n  Fixpoint Seq ls :=\n    match ls with\n      | nil => Skip\n      | a :: ls' => Seq2 a (Seq ls')\n    end.\n\n  Definition Strline := Straightline_ imports modName.\n\n  Fixpoint do_compile (expr : Expr) (base : nat) :=\n    match expr with\n      | Var str => Strline (Assign (LvReg Rv) (RvLval (var_slot str)) :: nil)\n      | Const w => Strline (Assign (LvReg Rv) (RvImm w) :: nil)\n      | Binop op a b => Seq (\n        do_compile a base ::\n        Strline(Assign (temp_slot base) (RvLval (LvReg Rv)) :: nil) ::\n        do_compile b (S base) ::\n        (Strline (IL.Binop (LvReg Rv) (RvLval (temp_slot base)) op (RvLval (LvReg Rv)) :: nil)) :: nil)\n      | TestE te a b => Seq (do_compile a base ::\n        Strline( Assign (temp_slot base) (RvLval (LvReg Rv)) :: nil ) ::\n        do_compile b (S base) ::\n        Structured.If_ imports_global (RvLval (temp_slot base)) te (RvLval (LvReg Rv))\n        (Strline (Assign Rv (RvImm $1) :: nil))\n        (Strline (Assign Rv (RvImm $0) :: nil))\n        ::nil)\n    end.\n\n  Definition body := do_compile.\n\n  Require Import Platform.Wrap.\n\n  Hint Extern 1 (_ <= _) => omega.\n\n  Definition compile (expr : Expr) (base : nat) : cmd imports modName.\n    refine (Wrap imports imports_global modName (body expr base) (post expr base) (verifCond expr base) _ _).\n\n    Opaque mult.\n\n    Lemma postOk : forall specs sm expr base pre st,\n      Subset (free_vars expr) (of_list vars)\n      -> base + depth expr <= temp_size\n      -> interp specs (Postcondition (do_compile expr base pre) (sm, st))\n      -> exists st', interp specs (pre (sm, st')) /\\ runs_to expr base (sm, st') st.\n      induction expr; simpl; propxFo.\n\n      do 2 esplit.\n      eauto.\n      hnf.\n      intros.\n      unfold is_state in H; simpl in H.\n\n      Lemma evalInstrs_read_var : forall sm x s,\n        evalInstrs sm x (Assign Rv (var_slot s) :: nil)\n        = evalInstrs sm x (Assign Rv (LvMem (Imm ((Regs x Sp ^+ natToW vars_start) ^+ natToW (variablePosition vars s)))) :: nil).\n        Transparent evalInstrs.\n        simpl.\n        intros.\n        replace (Regs x Sp ^+ natToW (vars_start + variablePosition vars s))\n          with (Regs x Sp ^+ natToW vars_start ^+ natToW (variablePosition vars s)); auto.\n        rewrite natToW_plus.\n        words.\n        Opaque evalInstrs.\n      Qed.\n\n      hnf in H.\n      assert (In s (singleton s)).\n      apply StringFacts.singleton_iff; auto.\n      apply H in H5.\n\n      Require Import Platform.Cito.SetoidListFacts.\n\n      Lemma In_to_set :\n        forall x ls,\n          StringSet.In x (SSP.of_list ls)\n          -> List.In x ls.\n        intros.\n        eapply SSP.of_list_1 in H.\n        eapply InA_eq_In_iff; eauto.\n      Qed.\n\n      assert (List.In s vars) by eauto using In_to_set.\n      rewrite evalInstrs_read_var in H3.\n      unfold vars_start in H3.\n      change (4 * 2) with 8 in *.\n      clear_fancy.\n      unfold is_state in H1; simpl in H1.\n      evaluate auto_ext.\n      simpl.\n      intuition idtac.\n      exists nil; simpl; intuition idtac.\n      unfold is_state.\n      rewrite H1.\n      step auto_ext.\n      auto.\n\n      do 2 esplit; eauto.\n      hnf; intros.\n      simpl.\n      clear_fancy.\n      evaluate auto_ext.\n      intuition idtac.\n      exists nil; simpl; intuition.\n      step auto_ext.\n\n      apply IHexpr2 in H2; clear IHexpr2.\n      Focus 2.\n      hnf; intros.\n      apply H.\n      apply StringFacts.union_iff; auto.\n      destruct H2; propxFo.\n      apply IHexpr1 in H2; clear IHexpr1.\n      Focus 2.\n      hnf; intros.\n      apply H.\n      apply StringFacts.union_iff; auto.\n      destruct H2; intuition.\n      do 2 esplit; eauto.\n      hnf; simpl; intros.\n      unfold is_state in H1; simpl in H1.\n\n      Lemma evalInstrs_write_temp : forall sm x base',\n        evalInstrs sm x (Assign (temp_slot base') Rv :: nil)\n        = evalInstrs sm x (Assign (LvMem (Imm (Regs x Sp ^+ $8 ^+ $ (4 * length vars) ^+ $4 ^* natToW base'))) Rv :: nil).\n        Transparent evalInstrs.\n        simpl.\n        intros.\n        replace (Regs x Sp ^+ natToW (temp_start + 4 * base'))\n          with (Regs x Sp ^+ $ (8) ^+ $ (4 * length vars) ^+ $4 ^* natToW base'); auto.\n        rewrite natToW_plus.\n        unfold temp_start, vars_start.\n        change (4 * 2) with 8.\n        rewrite natToW_plus.\n        unfold natToW.\n        rewrite (Mult.mult_comm 4 base').\n        change (natToWord 32 (base' * 4)) with (natToW (base' * 4)).\n        rewrite (natToW_times4 base').\n        unfold natToW.\n        words.\n        Opaque evalInstrs.\n      Qed.\n\n      Lemma evalInstrs_binop_temp : forall sm x base' b,\n        evalInstrs sm x (IL.Binop Rv (temp_slot base') b Rv :: nil)\n        = evalInstrs sm x (IL.Binop Rv (LvMem (Imm (Regs x Sp ^+ $8 ^+ $ (4 * length vars) ^+ $4 ^* natToW base'))) b Rv :: nil).\n        Transparent evalInstrs.\n        simpl.\n        intros.\n        replace (Regs x Sp ^+ natToW (temp_start + 4 * base'))\n          with (Regs x Sp ^+ $ (8) ^+ $ (4 * length vars) ^+ $4 ^* natToW base'); auto.\n        rewrite natToW_plus.\n        unfold temp_start, vars_start.\n        change (4 * 2) with 8.\n        rewrite natToW_plus.\n        unfold natToW.\n        rewrite (Mult.mult_comm 4 base').\n        change (natToWord 32 (base' * 4)) with (natToW (base' * 4)).\n        rewrite (natToW_times4 base').\n        unfold natToW.\n        words.\n        Opaque evalInstrs.\n      Qed.\n\n      rewrite evalInstrs_write_temp in H6.\n      assert (natToW base < natToW (length temps))%word.\n      apply lt_goodSize.\n      assert (max (depth expr1) (S (depth expr2)) > 0).\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))).\n      omega.\n      omega.\n      apply goodSize_weaken with (length temps); eauto.\n      eauto.\n      apply H7 in H1; clear H7.\n      generalize H8; intro Hs.\n      apply H1 in Hs; clear H1.\n      destruct Hs as [ ? [ ? [ ? [ ] ] ] ]; simpl in *.\n      generalize dependent H5; generalize dependent H4; generalize dependent H3.\n      clear_fancy.\n      unfold is_state in H7; simpl in H7.\n      assert (natToW base < natToW (length (upd_sublist temps base x4)))%word.\n      rewrite length_upd_sublist; assumption.\n      evaluate auto_ext.\n      intros.\n      hnf in H14.\n      assert (interp specs0 (![is_state ((sm, x1)) # (Sp) vs\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))* other] (sm, x1))).\n      unfold is_state; simpl.\n      clear_fancy; step auto_ext.\n      replace (Regs x2 Sp) with (Regs x1 Sp) by words.\n      step auto_ext.\n      apply H15 in H16; clear H15.\n      destruct H16 as [ ? [ ? [ ? [ ] ] ] ]; simpl in *.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      auto.\n      rewrite evalInstrs_binop_temp in H14.\n      clear_fancy.\n      destruct b.\n      assert (natToW base < natToW (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)))%word.\n      rewrite length_upd_sublist; rewrite upd_length; assumption.\n      clear H12; unfold is_state in H16.\n      evaluate auto_ext.\n      intuition idtac.\n      congruence.\n\n      Lemma selN_updN_eq : forall a p v,\n        p < length a\n        -> selN (updN a p v) p = v.\n        induction a; simpl; intuition.\n        destruct p; simpl; intuition.\n      Qed.\n\n      Lemma sel_upd_eq : forall a p v,\n        p < length a\n        -> goodSize (length a)\n        -> Array.sel (Array.upd a p v) p = v.\n        unfold Array.sel, Array.upd; intros.\n        apply selN_updN_eq; auto.\n        rewrite wordToNat_natToWord_idempotent; auto.\n        change (goodSize p).\n        eapply goodSize_weaken; eauto.\n      Qed.\n\n      Lemma selN_updN_ne : forall a p v p',\n        p <> p'\n        -> selN (updN a p v) p' = selN a p'.\n        induction a; simpl; intuition.\n        destruct p, p'; simpl; intuition.\n      Qed.\n\n      Lemma sublist_irrel : forall base, goodSize base\n        -> forall v base' a,\n          base < base'\n          -> Array.sel (upd_sublist a base' v) base = Array.sel a base.\n        induction v; simpl; intuition.\n        rewrite IHv; auto.\n        rewrite sel_selN by auto.\n        rewrite selN_updN_ne; try omega.\n        unfold Array.sel.\n        rewrite wordToNat_natToWord_idempotent; auto.\n      Qed.\n\n      rewrite sublist_irrel in H20.\n      rewrite sel_upd_eq in H20.\n      simpl.\n\n      Lemma upd_sublist_unchanged : forall p ws a base,\n        p < base\n        -> Array.selN (upd_sublist a base ws) p = Array.selN a p.\n        induction ws; simpl; intuition.\n        rewrite IHws by omega.\n        apply selN_updN_ne; omega.\n      Qed.\n\n      Lemma array_extensional : forall a1 a2,\n        length a1 = length a2\n        -> (forall p, p < length a1 -> selN a1 p = selN a2 p)\n        -> a1 = a2.\n        induction a1; destruct a2; simpl; intuition.\n        injection H; clear H; intros.\n        apply IHa1 in H; clear IHa1; subst.\n        f_equal.\n        specialize (H0 0); simpl in H0.\n        auto.\n        intros.\n        specialize (H0 (S p)); simpl in H0.\n        apply H0; omega.\n      Qed.\n\n      Lemma get_changed' : forall limit n a' a base,\n        length a - base = n\n        -> length a' = length a\n        -> base <= limit\n        -> (forall p, p < base -> Array.selN a' p = Array.selN a p)\n        -> (forall p, p >= limit -> Array.selN a' p = Array.selN a p)\n        -> exists changed, a' = upd_sublist a base changed\n          /\\ length changed <= limit - base.\n        induction n; simpl; intros.\n\n        exists nil.\n        simpl; split.\n        apply array_extensional; auto.\n        auto.\n\n        Require Import Coq.Arith.Arith.\n        destruct (eq_nat_dec limit base); subst.\n\n        (* We've reached the point where [a'] and [a] always agree, so no more updating is required. *)\n        exists nil; intuition.\n        unfold upd_sublist.\n        apply array_extensional; intros; auto.\n        destruct (le_lt_dec base p); auto.\n\n        (* The current element is still allowed to change.  Keep inducting. *)\n        assert (length (updN a base (selN a' base)) - S base = n)\n          by (rewrite updN_length; omega).\n        eapply IHn in H4.\n        Focus 2.\n        instantiate (1 := a').\n        rewrite updN_length; auto.\n        2: omega.\n        Focus 2.\n        intros.\n        destruct (eq_nat_dec p base); subst.\n        symmetry; apply selN_updN_eq.\n        rewrite updN_length in H.\n        omega.\n        rewrite selN_updN_ne; auto.\n\n        destruct H4.\n        exists (selN a' base :: x).\n        intuition idtac.\n        simpl; omega.\n\n        intros.\n        rewrite selN_updN_ne; auto.\n        omega.\n      Qed.\n\n      Lemma get_changed : forall a' a base limit,\n        length a' = length a\n        -> base <= limit\n        -> (forall p, p < base -> Array.selN a' p = Array.selN a p)\n        -> (forall p, p >= limit -> Array.selN a' p = Array.selN a p)\n        -> exists changed, a' = upd_sublist a base changed\n          /\\ length changed <= limit - base.\n        intros; eapply get_changed'; eauto.\n      Qed.\n\n      assert (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5) = length temps).\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      apply length_upd_sublist.\n      eapply get_changed in H22.\n      destruct H22.\n      eexists; intuition idtac.\n      unfold is_state.\n      rewrite <- H23.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs st Sp) by congruence.\n      step auto_ext.\n      Focus 2.\n      instantiate (1 := base + max (depth expr1) (S (depth expr2))).\n      omega.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged by omega.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged; auto.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H23.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)).\n      eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      intros.\n\n      Lemma upd_sublist_unchanged_high : forall p ws a base,\n        p >= base + length ws\n        -> Array.selN (upd_sublist a base ws) p = Array.selN a p.\n        induction ws; simpl; intuition.\n        rewrite IHws by omega.\n        apply selN_updN_ne; omega.\n      Qed.\n\n      rewrite upd_sublist_unchanged_high.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged_high.\n      generalize (Max.le_max_l (depth expr1) (S (depth expr2))); omega.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H23.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      apply lt_goodSize'; auto.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      repeat (rewrite length_upd_sublist || rewrite upd_length); omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      repeat (rewrite length_upd_sublist || rewrite upd_length); omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      repeat (rewrite length_upd_sublist || rewrite upd_length); omega.\n      omega.\n\n\n      assert (natToW base < natToW (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)))%word.\n      rewrite length_upd_sublist; rewrite upd_length; assumption.\n      clear H12; unfold is_state in H16.\n      evaluate auto_ext.\n      intuition idtac.\n      congruence.\n      rewrite sublist_irrel in H20.\n      rewrite sel_upd_eq in H20.\n      simpl.\n      assert (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5) = length temps).\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      apply length_upd_sublist.\n      eapply get_changed in H22.\n      destruct H22.\n      eexists; intuition idtac.\n      unfold is_state.\n      rewrite <- H23.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs st Sp) by congruence.\n      step auto_ext.\n      Focus 2.\n      instantiate (1 := base + max (depth expr1) (S (depth expr2))).\n      omega.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged by omega.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged; auto.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H23.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)).\n      eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged_high.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged_high.\n      generalize (Max.le_max_l (depth expr1) (S (depth expr2))); omega.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H23.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      apply lt_goodSize'; auto.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      repeat (rewrite length_upd_sublist || rewrite upd_length); omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      repeat (rewrite length_upd_sublist || rewrite upd_length); omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      repeat (rewrite length_upd_sublist || rewrite upd_length); omega.\n      omega.\n\n\n      assert (natToW base < natToW (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)))%word.\n      rewrite length_upd_sublist; rewrite upd_length; assumption.\n      clear H12; unfold is_state in H16.\n      evaluate auto_ext.\n      intuition idtac.\n      congruence.\n      rewrite sublist_irrel in H20.\n      rewrite sel_upd_eq in H20.\n      simpl.\n      assert (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5) = length temps).\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      apply length_upd_sublist.\n      eapply get_changed in H22.\n      destruct H22.\n      eexists; intuition idtac.\n      unfold is_state.\n      rewrite <- H23.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs st Sp) by congruence.\n      step auto_ext.\n      Focus 2.\n      instantiate (1 := base + max (depth expr1) (S (depth expr2))).\n      omega.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged by omega.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged; auto.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H23.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)).\n      eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged_high.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged_high.\n      generalize (Max.le_max_l (depth expr1) (S (depth expr2))); omega.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H23.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      apply lt_goodSize'; auto.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      repeat (rewrite length_upd_sublist || rewrite upd_length); omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      repeat (rewrite length_upd_sublist || rewrite upd_length); omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      repeat (rewrite length_upd_sublist || rewrite upd_length); omega.\n      omega.\n\n      assert (max (depth expr1) (S (depth expr2)) >= depth expr1) by apply Max.le_max_l.\n      omega.\n\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r.\n      omega.\n\n\n      apply IHexpr2 in H1; clear IHexpr2.\n      Focus 2.\n      do 2 intro.\n      apply H.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r.\n      omega.\n      destruct H1; propxFo.\n      apply IHexpr1 in H2; clear IHexpr1.\n      Focus 2.\n      do 2 intro.\n      apply H.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= depth expr1) by apply Max.le_max_l.\n      omega.\n      destruct H2; intuition idtac.\n      do 2 esplit; eauto.\n      hnf; simpl; intros.\n      apply H8 in H1; clear H8.\n      generalize H9; intro Hs.\n      apply H1 in Hs; clear H1.\n      simpl in Hs; destruct Hs as [ ? [ ? [ ? [ ] ] ] ].\n      rewrite evalInstrs_write_temp in *.\n\n      Lemma evalCond_temp : forall sm x base' t0,\n        evalCond (temp_slot base') t0 Rv sm x\n        = evalCond (LvMem (Imm (Regs x Sp ^+ $8 ^+ $ (4 * length vars) ^+ $4 ^* natToW base'))) t0 Rv sm x.\n        unfold evalCond; simpl; intros.\n        replace (Regs x Sp ^+ natToW (temp_start + 4 * base'))\n          with (Regs x Sp ^+ $ (8) ^+ $ (4 * length vars) ^+ $4 ^* natToW base'); auto.\n        rewrite natToW_plus.\n        unfold temp_start, vars_start.\n        change (4 * 2) with 8.\n        rewrite natToW_plus.\n        unfold natToW.\n        rewrite (Mult.mult_comm 4 base').\n        change (natToWord 32 (base' * 4)) with (natToW (base' * 4)).\n        rewrite (natToW_times4 base').\n        unfold natToW.\n        words.\n      Qed.\n\n      rewrite evalCond_temp in *.\n      clear_fancy.\n      generalize dependent H3; generalize dependent H4; generalize dependent H5.\n      unfold is_state in H8.\n      assert (natToW base < natToW (length (upd_sublist temps base x4)))%word.\n      rewrite length_upd_sublist.\n      apply lt_goodSize; auto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      apply goodSize_weaken with (length (upd_sublist temps base x4)); eauto.\n      rewrite length_upd_sublist; auto.\n      apply goodSize_weaken with (length (upd_sublist temps base x4)); eauto.\n      rewrite length_upd_sublist; auto.\n      evaluate auto_ext.\n      intros.\n      assert (interp specs0 (![is_state ((sm, x1)) # (Sp) vs\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))* other] (sm, x1))).\n      unfold is_state; simpl.\n      clear_fancy; step auto_ext.\n      replace (Regs x2 Sp) with (Regs x1 Sp) by words.\n      step auto_ext.\n      clear H12; apply H6 in H16.\n      rewrite upd_length in H16.\n      rewrite length_upd_sublist in H16.\n      generalize H9; intro Hs.\n      apply H16 in Hs; clear H16.\n      simpl in Hs; destruct Hs as [ ? [ ? [ ? [ ] ] ] ].\n      unfold is_state in H16; simpl in H16.\n      assert (natToW base < natToW (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1)) (S base) x5)))%word.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      apply lt_goodSize; auto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      auto.\n      generalize dependent H14.\n      destruct t0; simpl.\n\n      evaluate auto_ext.\n      intros; evaluate auto_ext.\n      intuition.\n      assert (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5) = length temps).\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      apply length_upd_sublist.\n      eapply get_changed in H24.\n      destruct H24.\n      eexists; intuition idtac.\n      unfold is_state.\n      rewrite <- H25.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs st Sp) by congruence.\n      step auto_ext.\n      Focus 3.\n      instantiate (1 := base + max (depth expr1) (S (depth expr2))).\n      omega.\n      omega.\n      unfold Array.sel in H22.\n      rewrite upd_sublist_unchanged in H22.\n      unfold Array.upd in H22.\n      rewrite selN_updN_eq in H22.\n      generalize (weqb_true_iff (eval vs expr1) (eval vs expr2)).\n      unfold weqb.\n      destruct (Word.weqb (eval vs expr1) (eval vs expr2)); intuition (try discriminate).\n      rewrite length_upd_sublist.\n      rewrite wordToNat_natToWord_idempotent.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      rewrite wordToNat_natToWord_idempotent.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      intros.\n      rewrite upd_sublist_unchanged by omega.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged; auto.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)).\n      eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged_high.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged_high.\n      generalize (Max.le_max_l (depth expr1) (S (depth expr2))); omega.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n\n      evaluate auto_ext.\n      intros; evaluate auto_ext.\n      intuition.\n      assert (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5) = length temps).\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      apply length_upd_sublist.\n      eapply get_changed in H24.\n      destruct H24.\n      eexists; intuition idtac.\n      unfold is_state.\n      rewrite <- H25.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs st Sp) by congruence.\n      step auto_ext.\n      Focus 3.\n      instantiate (1 := base + max (depth expr1) (S (depth expr2))).\n      omega.\n      omega.\n      unfold Array.sel in H22.\n      rewrite upd_sublist_unchanged in H22.\n      unfold Array.upd in H22.\n      rewrite selN_updN_eq in H22.\n      unfold wneb.\n      destruct (weq (eval vs expr1) (eval vs expr2)); auto.\n      exfalso; eauto.\n      rewrite length_upd_sublist.\n      rewrite wordToNat_natToWord_idempotent.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      rewrite wordToNat_natToWord_idempotent.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      intros.\n      rewrite upd_sublist_unchanged by omega.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged; auto.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)).\n      eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged_high.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged_high.\n      generalize (Max.le_max_l (depth expr1) (S (depth expr2))); omega.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n\n      evaluate auto_ext.\n      intros; evaluate auto_ext.\n      intuition.\n      assert (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5) = length temps).\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      apply length_upd_sublist.\n      eapply get_changed in H24.\n      destruct H24.\n      eexists; intuition idtac.\n      unfold is_state.\n      rewrite <- H25.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs st Sp) by congruence.\n      step auto_ext.\n      Focus 3.\n      instantiate (1 := base + max (depth expr1) (S (depth expr2))).\n      omega.\n      omega.\n      unfold Array.sel in H22.\n      rewrite upd_sublist_unchanged in H22.\n      unfold Array.upd in H22.\n      rewrite selN_updN_eq in H22.\n      unfold wltb.\n      destruct (wlt_dec (eval vs expr1) (eval vs expr2)); intuition (try discriminate).\n      rewrite length_upd_sublist.\n      rewrite wordToNat_natToWord_idempotent.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      rewrite wordToNat_natToWord_idempotent.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      intros.\n      rewrite upd_sublist_unchanged by omega.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged; auto.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)).\n      eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged_high.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged_high.\n      generalize (Max.le_max_l (depth expr1) (S (depth expr2))); omega.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n\n      evaluate auto_ext.\n      intros; evaluate auto_ext.\n      intuition.\n      assert (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5) = length temps).\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      apply length_upd_sublist.\n      eapply get_changed in H24.\n      destruct H24.\n      eexists; intuition idtac.\n      unfold is_state.\n      rewrite <- H25.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs st Sp) by congruence.\n      step auto_ext.\n      Focus 3.\n      instantiate (1 := base + max (depth expr1) (S (depth expr2))).\n      omega.\n      omega.\n      unfold Array.sel in H22.\n      rewrite upd_sublist_unchanged in H22.\n      unfold Array.upd in H22.\n      rewrite selN_updN_eq in H22.\n      unfold wleb.\n      destruct (weq (eval vs expr1) (eval vs expr2)); intuition (try discriminate).\n      destruct (wlt_dec (eval vs expr1) (eval vs expr2)); intuition (try discriminate).\n      apply le_neq_lt in n; tauto.\n      rewrite length_upd_sublist.\n      rewrite wordToNat_natToWord_idempotent.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      rewrite wordToNat_natToWord_idempotent.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      intros.\n      rewrite upd_sublist_unchanged by omega.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged; auto.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)).\n      eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged_high.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged_high.\n      generalize (Max.le_max_l (depth expr1) (S (depth expr2))); omega.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n\n\n      apply IHexpr2 in H1; clear IHexpr2.\n      Focus 2.\n      do 2 intro.\n      apply H.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r.\n      omega.\n      destruct H1; propxFo.\n      apply IHexpr1 in H2; clear IHexpr1.\n      Focus 2.\n      do 2 intro.\n      apply H.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= depth expr1) by apply Max.le_max_l.\n      omega.\n      destruct H2; intuition idtac.\n      do 2 esplit; eauto.\n      hnf; simpl; intros.\n      apply H8 in H1; clear H8.\n      generalize H9; intro Hs.\n      apply H1 in Hs; clear H1.\n      simpl in Hs; destruct Hs as [ ? [ ? [ ? [ ] ] ] ].\n      rewrite evalInstrs_write_temp in *.\n      rewrite evalCond_temp in *.\n      clear_fancy.\n      generalize dependent H3; generalize dependent H4; generalize dependent H5.\n      unfold is_state in H8.\n      assert (natToW base < natToW (length (upd_sublist temps base x4)))%word.\n      rewrite length_upd_sublist.\n      apply lt_goodSize; auto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      apply goodSize_weaken with (length (upd_sublist temps base x4)); eauto.\n      rewrite length_upd_sublist; auto.\n      apply goodSize_weaken with (length (upd_sublist temps base x4)); eauto.\n      rewrite length_upd_sublist; auto.\n      evaluate auto_ext.\n      intros.\n      assert (interp specs0 (![is_state ((sm, x1)) # (Sp) vs\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))* other] (sm, x1))).\n      unfold is_state; simpl.\n      clear_fancy; step auto_ext.\n      replace (Regs x2 Sp) with (Regs x1 Sp) by words.\n      step auto_ext.\n      clear H12; apply H6 in H16.\n      rewrite upd_length in H16.\n      rewrite length_upd_sublist in H16.\n      generalize H9; intro Hs.\n      apply H16 in Hs; clear H16.\n      simpl in Hs; destruct Hs as [ ? [ ? [ ? [ ] ] ] ].\n      unfold is_state in H16; simpl in H16.\n      assert (natToW base < natToW (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1)) (S base) x5)))%word.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      apply lt_goodSize; auto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      auto.\n      generalize dependent H14.\n      destruct t0; simpl.\n\n      evaluate auto_ext.\n      intros; evaluate auto_ext.\n      intuition.\n      assert (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5) = length temps).\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      apply length_upd_sublist.\n      eapply get_changed in H24.\n      destruct H24.\n      eexists; intuition idtac.\n      unfold is_state.\n      rewrite <- H25.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs st Sp) by congruence.\n      step auto_ext.\n      Focus 3.\n      instantiate (1 := base + max (depth expr1) (S (depth expr2))).\n      omega.\n      omega.\n      unfold Array.sel in H22.\n      rewrite upd_sublist_unchanged in H22.\n      unfold Array.upd in H22.\n      rewrite selN_updN_eq in H22.\n      generalize (weqb_true_iff (eval vs expr1) (eval vs expr2)).\n      unfold weqb.\n      destruct (Word.weqb (eval vs expr1) (eval vs expr2)); intuition (try discriminate).\n      rewrite length_upd_sublist.\n      rewrite wordToNat_natToWord_idempotent.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      rewrite wordToNat_natToWord_idempotent.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      intros.\n      rewrite upd_sublist_unchanged by omega.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged; auto.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)).\n      eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged_high.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged_high.\n      generalize (Max.le_max_l (depth expr1) (S (depth expr2))); omega.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n\n      evaluate auto_ext.\n      intros; evaluate auto_ext.\n      intuition.\n      assert (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5) = length temps).\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      apply length_upd_sublist.\n      eapply get_changed in H24.\n      destruct H24.\n      eexists; intuition idtac.\n      unfold is_state.\n      rewrite <- H25.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs st Sp) by congruence.\n      step auto_ext.\n      Focus 3.\n      instantiate (1 := base + max (depth expr1) (S (depth expr2))).\n      omega.\n      omega.\n      unfold Array.sel in H22.\n      rewrite upd_sublist_unchanged in H22.\n      unfold Array.upd in H22.\n      rewrite selN_updN_eq in H22.\n      unfold wneb.\n      destruct (weq (eval vs expr1) (eval vs expr2)); auto.\n      exfalso; eauto.\n      rewrite length_upd_sublist.\n      rewrite wordToNat_natToWord_idempotent.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      rewrite wordToNat_natToWord_idempotent.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      intros.\n      rewrite upd_sublist_unchanged by omega.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged; auto.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)).\n      eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged_high.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged_high.\n      generalize (Max.le_max_l (depth expr1) (S (depth expr2))); omega.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n\n      evaluate auto_ext.\n      intros; evaluate auto_ext.\n      intuition.\n      assert (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5) = length temps).\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      apply length_upd_sublist.\n      eapply get_changed in H24.\n      destruct H24.\n      eexists; intuition idtac.\n      unfold is_state.\n      rewrite <- H25.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs st Sp) by congruence.\n      step auto_ext.\n      Focus 3.\n      instantiate (1 := base + max (depth expr1) (S (depth expr2))).\n      omega.\n      omega.\n      unfold Array.sel in H22.\n      rewrite upd_sublist_unchanged in H22.\n      unfold Array.upd in H22.\n      rewrite selN_updN_eq in H22.\n      unfold wltb.\n      destruct (wlt_dec (eval vs expr1) (eval vs expr2)); intuition (try discriminate).\n      rewrite length_upd_sublist.\n      rewrite wordToNat_natToWord_idempotent.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      rewrite wordToNat_natToWord_idempotent.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      intros.\n      rewrite upd_sublist_unchanged by omega.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged; auto.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)).\n      eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged_high.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged_high.\n      generalize (Max.le_max_l (depth expr1) (S (depth expr2))); omega.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n\n      evaluate auto_ext.\n      intros; evaluate auto_ext.\n      intuition.\n      assert (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base (eval vs expr1))\n        (S base) x5) = length temps).\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      apply length_upd_sublist.\n      eapply get_changed in H24.\n      destruct H24.\n      eexists; intuition idtac.\n      unfold is_state.\n      rewrite <- H25.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs st Sp) by congruence.\n      step auto_ext.\n      Focus 3.\n      instantiate (1 := base + max (depth expr1) (S (depth expr2))).\n      omega.\n      omega.\n      unfold Array.sel in H22.\n      rewrite upd_sublist_unchanged in H22.\n      unfold Array.upd in H22.\n      rewrite selN_updN_eq in H22.\n      unfold wleb.\n      destruct (weq (eval vs expr1) (eval vs expr2)); intuition (try discriminate).\n      rewrite e in H22.\n      exfalso; eapply wlt_not_refl; eauto.\n      destruct (wlt_dec (eval vs expr1) (eval vs expr2)); intuition (try discriminate).\n      apply lt_le in w.\n      exfalso; apply w; auto.\n      rewrite length_upd_sublist.\n      rewrite wordToNat_natToWord_idempotent.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      rewrite wordToNat_natToWord_idempotent.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      intros.\n      rewrite upd_sublist_unchanged by omega.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged; auto.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)).\n      eauto.\n      rewrite length_upd_sublist.\n      rewrite upd_length.\n      rewrite length_upd_sublist.\n      omega.\n      intros.\n      rewrite upd_sublist_unchanged_high.\n      unfold Array.upd.\n      rewrite selN_updN_ne.\n      apply upd_sublist_unchanged_high.\n      generalize (Max.le_max_l (depth expr1) (S (depth expr2))); omega.\n      intro; subst.\n      rewrite wordToNat_natToWord_idempotent in H25.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      change (goodSize base).\n      apply goodSize_weaken with (length (upd_sublist\n        (Array.upd (upd_sublist temps base x4) base\n          (eval vs expr1)) (S base) x5)); eauto.\n      generalize (Max.le_max_r (depth expr1) (S (depth expr2))); omega.\n      (* Sorry for all that copying and pasting. ;-) *)\n    Qed.\n\n    abstract (unfold verifCond, syn_req; wrap0;\n      match goal with\n        | [ H : interp _ (Postcondition _ ?x) |- _ ] =>\n          destruct x; eapply postOk in H; auto; destruct H; intuition; descend; eauto\n      end).\n\n    unfold verifCond, syn_req; wrap0.\n\n    Lemma verifCondOk : forall expr base pre,\n      imply pre new_pre\n      -> Subset (free_vars expr) (of_list vars)\n      -> base + depth expr <= temp_size\n      -> vcs (VerifCond (body expr base pre)).\n      induction expr; wrap0; simpl in *.\n\n      apply H in H2; clear H; post.\n      unfold is_state in H2.\n      rewrite evalInstrs_read_var in *.\n      unfold vars_start in *.\n      change (4 * 2) with 8 in *.\n      unfold natToW in H3.\n      assert (List.In s vars).\n      apply In_to_set.\n      apply H0.\n      apply StringFacts.singleton_iff; auto.\n      clear_fancy.\n      evaluate auto_ext.\n\n      clear_fancy.\n      clear H.\n      evaluate auto_ext.\n\n      apply IHexpr1; auto.\n      do 2 intro.\n      apply H0.\n      apply StringFacts.union_iff; auto.\n      assert (max (depth expr1) (S (depth expr2)) >= depth expr1) by apply Max.le_max_l; omega.\n\n      apply postOk in H2.\n      Focus 2.\n      do 2 intro.\n      apply H0.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= depth expr1) by apply Max.le_max_l; omega.\n      destruct H2 as [ ? [ ? ] ].\n      apply H in H2; clear H.\n      post.\n      apply H4 in H2; intuition idtac.\n      simpl in *.\n      destruct H6; intuition idtac.\n      unfold is_state in H6.\n      rewrite evalInstrs_write_temp in *.\n      assert (natToW base < natToW (length (upd_sublist x2 base x3)))%word.\n      rewrite length_upd_sublist.\n      apply lt_goodSize.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      apply goodSize_weaken with (length (upd_sublist x2 base x3)); eauto.\n      rewrite length_upd_sublist.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      apply goodSize_weaken with (length (upd_sublist x2 base x3)); eauto.\n      rewrite length_upd_sublist.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      clear IHexpr1 IHexpr2; clear_fancy.\n      evaluate auto_ext.\n\n      apply IHexpr2.\n      Focus 2.\n      do 2 intro.\n      apply H0.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      hnf; propxFo.\n      apply postOk in H3.\n      Focus 2.\n      do 2 intro.\n      apply H0.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= depth expr1) by apply Max.le_max_l; omega.\n      destruct H3; intuition idtac.\n      apply H in H3; clear H; post.\n      apply H5 in H2; clear H5; intuition idtac; simpl in *.\n      destruct H5; intuition idtac.\n      clear IHexpr1 IHexpr2; clear_fancy.\n      rewrite evalInstrs_write_temp in *.\n      unfold is_state in H5.\n      assert (natToW base < natToW (length (upd_sublist x4 base x5)))%word.\n      rewrite length_upd_sublist.\n      apply lt_goodSize.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      apply goodSize_weaken with (length (upd_sublist x4 base x5)); eauto.\n      rewrite length_upd_sublist.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      apply goodSize_weaken with (length (upd_sublist x4 base x5)); eauto.\n      rewrite length_upd_sublist.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      evaluate auto_ext.\n      destruct x; simpl in *.\n      descend.\n      unfold is_state.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs s0 Sp) by congruence.\n      step auto_ext.\n      rewrite upd_length.\n      rewrite length_upd_sublist; assumption.\n\n      apply postOk in H2.\n      Focus 2.\n      do 2 intro.\n      apply H0.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      post.\n      post.\n      apply postOk in H4.\n      Focus 2.\n      do 2 intro.\n      apply H0.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= depth expr1) by apply Max.le_max_l; omega.\n      destruct H4; intuition idtac.\n      apply H in H4; clear H.\n      clear IHexpr1 IHexpr2; clear_fancy.\n      post.\n      apply H7 in H2; clear H7.\n      post.\n      rewrite evalInstrs_write_temp in *.\n      unfold is_state in H7.\n      assert (natToW base < natToW (length (upd_sublist x4 base x5)))%word.\n      rewrite length_upd_sublist.\n      apply lt_goodSize.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      apply goodSize_weaken with (length (upd_sublist x4 base x5)); eauto.\n      rewrite length_upd_sublist.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      apply goodSize_weaken with (length (upd_sublist x4 base x5)); eauto.\n      rewrite length_upd_sublist.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      evaluate auto_ext.\n      assert (interp specs (![is_state (Regs x Sp) x3\n        (Array.upd (upd_sublist x4 base x5) base (eval x3 expr1))* (fun stn sm => x2 (stn, sm))] (stn, x))).\n      unfold is_state.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs x Sp) by congruence.\n      step auto_ext.\n      apply H5 in H13.\n      rewrite upd_length in H13.\n      rewrite length_upd_sublist in H13.\n      post.\n      rewrite evalInstrs_binop_temp in *.\n      destruct b.\n\n      assert (natToW base < natToW (length (upd_sublist\n        (Array.upd (upd_sublist x4 base x5) base\n          (eval x3 expr1)) (S base) x6)))%word.\n      rewrite length_upd_sublist; rewrite upd_length; assumption.\n      clear H12; unfold is_state in H15.\n      evaluate auto_ext.\n\n      assert (natToW base < natToW (length (upd_sublist\n        (Array.upd (upd_sublist x4 base x5) base\n          (eval x3 expr1)) (S base) x6)))%word.\n      rewrite length_upd_sublist; rewrite upd_length; assumption.\n      clear H12; unfold is_state in H15.\n      evaluate auto_ext.\n\n      assert (natToW base < natToW (length (upd_sublist\n        (Array.upd (upd_sublist x4 base x5) base\n          (eval x3 expr1)) (S base) x6)))%word.\n      rewrite length_upd_sublist; rewrite upd_length; assumption.\n      clear H12; unfold is_state in H15.\n      evaluate auto_ext.\n\n      Transparent evalInstrs.\n      simpl in H3.\n      discriminate.\n      Opaque evalInstrs.\n\n      apply IHexpr1; auto.\n      hnf; intros.\n      apply H0.\n      apply StringFacts.union_iff; auto.\n      assert (max (depth expr1) (S (depth expr2)) >= depth expr1) by apply Max.le_max_l; omega.\n\n      apply postOk in H2.\n      Focus 2.\n      do 2 intro.\n      apply H0.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= depth expr1) by apply Max.le_max_l; omega.\n      post.\n      apply H in H4; clear H; post.\n      rewrite evalInstrs_write_temp in *.\n      unfold is_state in H2.\n      assert (natToW base < natToW (length x2))%word.\n      apply lt_goodSize.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      apply goodSize_weaken with (length x2); eauto.\n      eauto.\n      clear IHexpr1 IHexpr2; clear_fancy.\n      evaluate auto_ext.\n      assert (interp specs (![is_state (Regs x Sp) x1 x2 * (fun stn sm => x0 (stn, sm))] (stn, x))).\n      unfold is_state.\n      step auto_ext.\n      apply H5 in H2.\n      post.\n      assert (natToW base < natToW (length (upd_sublist x2 base x3)))%word.\n      rewrite length_upd_sublist; assumption.\n      clear H8; unfold is_state in H7.\n      evaluate auto_ext.\n\n      apply IHexpr2; auto.\n      Focus 2.\n      do 2 intro.\n      apply H0.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      hnf; post.\n      apply postOk in H3.\n      Focus 2.\n      do 2 intro.\n      apply H0.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= depth expr1) by apply Max.le_max_l; omega.\n      post.\n      apply H in H3; clear H; post.\n      apply H5 in H2; clear H5; post.\n      rewrite evalInstrs_write_temp in *.\n      unfold is_state in H5.\n      assert (natToW base < natToW (length (upd_sublist x4 base x5)))%word.\n      rewrite length_upd_sublist.\n      apply lt_goodSize.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      apply goodSize_weaken with (length (upd_sublist x4 base x5)); eauto.\n      rewrite length_upd_sublist; auto.\n      apply goodSize_weaken with (length (upd_sublist x4 base x5)); eauto.\n      rewrite length_upd_sublist; auto.\n      clear IHexpr1 IHexpr2; clear_fancy.\n      evaluate auto_ext.\n      destruct x; simpl in *.\n      descend.\n      unfold is_state.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs s0 Sp) by congruence.\n      step auto_ext.\n      rewrite upd_length.\n      rewrite length_upd_sublist; auto.\n\n      apply postOk in H2.\n      Focus 2.\n      do 2 intro.\n      apply H0.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      post.\n      post.\n      apply postOk in H4.\n      Focus 2.\n      do 2 intro.\n      apply H0.\n      apply StringFacts.union_iff; auto.\n      Focus 2.\n      assert (max (depth expr1) (S (depth expr2)) >= depth expr1) by apply Max.le_max_l; omega.\n      destruct H4; intuition idtac.\n      apply H in H4; clear H.\n      clear IHexpr1 IHexpr2; clear_fancy.\n      post.\n      apply H7 in H2; clear H7.\n      post.\n      rewrite evalInstrs_write_temp in *.\n      unfold is_state in H7.\n      assert (natToW base < natToW (length (upd_sublist x4 base x5)))%word.\n      rewrite length_upd_sublist.\n      apply lt_goodSize.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      apply goodSize_weaken with (length (upd_sublist x4 base x5)); eauto.\n      rewrite length_upd_sublist.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      apply goodSize_weaken with (length (upd_sublist x4 base x5)); eauto.\n      rewrite length_upd_sublist.\n      assert (max (depth expr1) (S (depth expr2)) >= S (depth expr2)) by apply Max.le_max_r; omega.\n      evaluate auto_ext.\n      assert (interp specs (![is_state (Regs x Sp) x3\n        (Array.upd (upd_sublist x4 base x5) base (eval x3 expr1))* (fun stn sm => x2 (stn, sm))] (stn, x))).\n      unfold is_state.\n      step auto_ext.\n      replace (Regs x0 Sp) with (Regs x Sp) by congruence.\n      step auto_ext.\n      apply H5 in H13.\n      rewrite upd_length in H13.\n      rewrite length_upd_sublist in H13.\n      post.\n      rewrite evalCond_temp in *.\n      destruct t0.\n\n      assert (natToW base < natToW (length (upd_sublist\n        (Array.upd (upd_sublist x4 base x5) base\n          (eval x3 expr1)) (S base) x6)))%word.\n      rewrite length_upd_sublist; rewrite upd_length; assumption.\n      clear H12; unfold is_state in H15.\n      evaluate auto_ext.\n\n      assert (natToW base < natToW (length (upd_sublist\n        (Array.upd (upd_sublist x4 base x5) base\n          (eval x3 expr1)) (S base) x6)))%word.\n      rewrite length_upd_sublist; rewrite upd_length; assumption.\n      clear H12; unfold is_state in H15.\n      evaluate auto_ext.\n\n      assert (natToW base < natToW (length (upd_sublist\n        (Array.upd (upd_sublist x4 base x5) base\n          (eval x3 expr1)) (S base) x6)))%word.\n      rewrite length_upd_sublist; rewrite upd_length; assumption.\n      clear H12; unfold is_state in H15.\n      evaluate auto_ext.\n\n      assert (natToW base < natToW (length (upd_sublist\n        (Array.upd (upd_sublist x4 base x5) base\n          (eval x3 expr1)) (S base) x6)))%word.\n      rewrite length_upd_sublist; rewrite upd_length; assumption.\n      clear H12; unfold is_state in H15.\n      evaluate auto_ext.\n\n      Transparent evalInstrs.\n      discriminate.\n      discriminate.\n      discriminate.\n      discriminate.\n      Opaque evalInstrs.\n    Qed.\n\n    abstract (apply verifCondOk; auto).\n  Defined.\n\nEnd ExprComp.\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Cito/CompileExpr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.22579552498944838}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Strings.String.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.derive.Derive.\nRequire Import bedrock2.Syntax.\nRequire Import compiler.FlatToRiscvDef.\nRequire Export compiler.MemoryLayout.\nRequire Import compiler.Pipeline.\nRequire Import compiler.RiscvWordProperties.\nRequire Import coqutil.Word.Interface.\nRequire Import coqutil.Map.Z_keyed_SortedListMap.\nRequire Import coqutil.Z.HexNotation.\nRequire Import Bedrock2Experiments.WordProperties.\nRequire Import Bedrock2Experiments.StateMachineMMIO.\nRequire Import Bedrock2Experiments.StateMachineSemantics.\nRequire Import Bedrock2Experiments.Aes.Constants.\nRequire Import Bedrock2Experiments.Aes.Aes.\nRequire Import Bedrock2Experiments.Aes.AesSemantics.\nRequire Import Bedrock2Experiments.LibBase.AbsMMIO.\nRequire coqutil.Word.Naive.\nRequire coqutil.Map.SortedListWord.\nRequire riscv.Utility.InstructionNotations.\nImport Syntax.Coercions.\nLocal Open Scope string_scope.\n\nInstance word: word.word 32 := Naive.word 32.\nInstance mem: map.map word Byte.byte := SortedListWord.map _ _.\nExisting Instance SortedListString.map.\nExisting Instance SortedListString.ok.\n\n(* TODO: we actually need a different word implementation than Naive here; in\n   corner cases such as a shift argument greater than the width of the word,\n   the naive implementation violates the riscv_ok requirements *)\nInstance naive_riscv_ok : word.riscv_ok word. Admitted.\n\nDefinition ml: MemoryLayout := {|\n  MemoryLayout.code_start    := word.of_Z 0;\n  MemoryLayout.code_pastend  := word.of_Z (4*2^10);\n  MemoryLayout.heap_start    := word.of_Z (4*2^10);\n  MemoryLayout.heap_pastend  := word.of_Z (8*2^10);\n  MemoryLayout.stack_start   := word.of_Z (8*2^10);\n  MemoryLayout.stack_pastend := word.of_Z (16*2^10);\n                              |}.\n\n(* Magic number for aes base address found in\n   third_party/opentitan/hw/top_earlgrey/sw/autogen/top_earlgrey.h:\n\n   #define TOP_EARLGREY_AES_BASE_ADDR 0x40110000u *)\nDefinition AES_BASE_ADDR : Z := 0x40110000.\n\nLocal Infix \"<<\" := Z.shiftl (at level 40) : Z_scope.\nInstance consts : aes_constants Z :=\n  {|\n  (**** Constants from aes_regs.h ****)\n\n  (* #define AES_KEY0(id) (AES##id##_BASE_ADDR + 0x0) *)\n  AES_KEY00 := AES_BASE_ADDR + 0x0;\n\n  (* #define AES_IV0(id) (AES##id##_BASE_ADDR + 0x20) *)\n  AES_IV00 := AES_BASE_ADDR + 0x20;\n\n  (* #define AES_DATA_IN0(id) (AES##id##_BASE_ADDR + 0x30) *)\n  AES_DATA_IN00 := AES_BASE_ADDR + 0x30;\n\n  (* #define AES_DATA_OUT0(id) (AES##id##_BASE_ADDR + 0x40) *)\n  AES_DATA_OUT00 := AES_BASE_ADDR + 0x40;\n\n  (* #define AES_CTRL(id) (AES##id##_BASE_ADDR + 0x50) *)\n  AES_CTRL0 := AES_BASE_ADDR + 0x50;\n\n  (* #define AES_CTRL_REG_OFFSET 0x50\n     #define AES_CTRL_OPERATION 0\n     #define AES_CTRL_MODE_MASK 0x7\n     #define AES_CTRL_MODE_OFFSET 1\n     #define AES_CTRL_KEY_LEN_MASK 0x7\n     #define AES_CTRL_KEY_LEN_OFFSET 4\n     #define AES_CTRL_MANUAL_OPERATION 7 *)\n  AES_CTRL_OPERATION := 0;\n  AES_CTRL_MODE_MASK := 0x7;\n  AES_CTRL_MODE_OFFSET := 1;\n  AES_CTRL_KEY_LEN_MASK := 0x7;\n  AES_CTRL_KEY_LEN_OFFSET := 4;\n  AES_CTRL_MANUAL_OPERATION := 7;\n\n  (* #define AES_STATUS(id) (AES##id##_BASE_ADDR + 0x58) *)\n  AES_STATUS0 := AES_BASE_ADDR + 0x58;\n\n  (* #define AES_STATUS_IDLE 0\n     #define AES_STATUS_STALL 1\n     #define AES_STATUS_OUTPUT_VALID 2\n     #define AES_STATUS_INPUT_READY 3 *)\n  AES_STATUS_IDLE := 0;\n  AES_STATUS_STALL := 1;\n  AES_STATUS_OUTPUT_VALID := 2;\n  AES_STATUS_INPUT_READY := 3;\n\n  (* #define AES_PARAM_NUMREGSKEY 8 *)\n  AES_NUM_REGS_KEY := 8;\n\n  (* #define AES_PARAM_NUMREGSIV 4 *)\n  AES_NUM_REGS_IV := 4;\n\n  (* #define AES_PARAM_NUMREGSDATA 4 *)\n  AES_NUM_REGS_DATA := 4;\n\n  (**** Enums from aes.h ****)\n\n  (* typedef enum aes_op { kAesEnc = 0, kAesDec = 1 } aes_op_t; *)\n  kAesEnc := 0;\n  kAesDec := 1;\n\n  (* typedef enum aes_mode {\n       kAesEcb = 1 << 0,\n       kAesCbc = 1 << 1,\n       kAesCtr = 1 << 2\n     } aes_mode_t; *)\n  kAesEcb := 1 << 0;\n  kAesCbc := 1 << 1;\n  kAesCtr := 1 << 2;\n\n  (* typedef enum aes_key_len {\n       kAes128 = 1 << 0,\n       kAes192 = 1 << 1,\n       kAes256 = 1 << 2\n     } aes_key_len_t; *)\n  kAes128 := 1 << 0;\n  kAes192 := 1 << 1;\n  kAes256 := 1 << 2;\n\n  |}.\n\nInstance aes_timing : timing := {| ndelays_core := 14%nat |}.\n\n(* TODO: fill in with real circuit spec *)\nInstance aes_def: AesSpec. constructor. Admitted.\n\nExisting Instance constant_literals.\n\nDefinition funcs := [ aes_data_put_wait\n                     ; aes_data_get_wait\n                     ; aes_init\n                     ; aes_key_put\n                     ; aes_iv_put\n                     ; aes_data_put\n                     ; aes_data_get\n                     ; aes_data_ready\n                     ; aes_data_valid\n                     ; aes_idle\n                     ; abs_mmio_read32\n                     ; abs_mmio_write32 ].\n\nDerive aes_compile_result\n       SuchThat (compile compile_ext_call (map.of_list funcs)\n                 = Some aes_compile_result)\n       As aes_compile_result_eq.\nProof.\n  (* doing a more surgical vm_compute in the lhs only avoids fully computing the map\n     type, which would slow eq_refl and Qed dramatically *)\n  lazymatch goal with\n    |- ?lhs = _ =>\n    let x := (eval vm_compute in lhs) in\n    change lhs with x\n  end.\n  exact eq_refl.\nQed.\n\nDefinition aes_asm := Eval compute in fst (fst aes_compile_result).\n\nModule PrintAssembly.\n  Import riscv.Utility.InstructionNotations.\n  Redirect \"aes.s\" Print aes_asm.\nEnd PrintAssembly.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/firmware/Aes/AesToRiscV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.22579551123231217}}
{"text": "Require Export\n  Coq.Sets.Constructive_sets\n  Coq.Sets.Powerset_facts.\n\nRequire Import Fiat.ADT.\n\nLtac single_reduction :=\n  match goal with\n  | [ |- Strict_Included _ _ _ ] => constructor\n  | [ |- Included _ _ _ ] =>\n    let x := fresh \"x\" in\n    let Hx := fresh \"Hx\" in\n    intros x Hx\n  | [ H : _ /\\ _ |- _ ] => destruct H\n  | [ |- _ /\\ _ ] => split\n  | [ H : _ * _ |- _ ] => destruct H\n  | [ |- _ * _ ] => split\n  | [ H : Ensembles.In _ _ _ |- _ ] => inv H\n  | [ H : Ensembles.In _ _ _ |- _ ] => rewrite H in *\n  | [ |- Ensembles.In _ _ _ ] => constructor\n  | [ |- Ensembles.In _ (Bind _ (fun x => ret _)) _ ] => eexists\n  | [ |- Ensembles.In _ _ _ ] => eexists\n  | [ H : forall x : ?T, Some ?X = Some x -> _ |- _ ] =>\n    specialize (H X eq_refl)\n  | [ |- ret ?C ↝ ?V -> _ ] =>\n    let H := fresh \"H\" in intro H; apply Return_inv in H; simpl in H; inv H\n  | [ |- Bind ?C ?F ↝ ?V -> _ ] =>\n    let H := fresh \"H\" in intro H; apply Bind_inv in H; simpl in H; inv H\n  | [ |- Pick ?S ↝ ?V -> _ ] =>\n    let H := fresh \"H\" in intro H; apply Pick_inv in H; simpl in H; inv H\n  | [ H : ret ?C ↝ ?V     |- _ ] => apply Return_inv in H\n  | [ H : Bind ?C ?F ↝ ?V |- _ ] => apply Bind_inv in H\n  | [ H : Pick ?S ↝ ?V    |- _ ] => apply Pick_inv in H\n  | [ |- ret ?C ↝ ?V ]           => apply ReturnComputes\n  | [ |- Bind ?C ?F ↝ ?V ]       => apply BindComputes\n  | [ |- Pick ?S ↝ ?V ]          => apply PickComputes\n  | [ |- context [If_Opt_Then_Else ?V ?T ?E] ] => destruct V\n  (* | [ |- context [Ifdec_Then_Else ?P ?T ?E] ]  => unfold Ifdec_Then_Else *)\n  end.\n\nLtac simplify_ensembles :=\n  repeat (single_reduction; simpl; destruct_ex);\n  try solve [ intuition | constructor ].\n\nRequire Import\n  Fiat.ADT\n  Fiat.ADTNotation.\n\nTactic Notation \"refine\" \"method\" constr(name) :=\n  match goal with\n    | [ _ : constructorType ?A (consDom {| consID := name\n                                         ; consDom := _ |}) |- _ ] =>\n      idtac \"Constructor\"\n    | [ _ : methodType ?A (methDom {| methID := name\n                                    ; methDom := _\n                                    ; methCod := _ |})  _ |- _ ] =>\n      idtac \"Method\"\n    | _ =>\n      fail \"Incorrect method name\"\n  end.\n\nRequire Import\n  Coq.Sets.Ensembles\n  Fiat.ADT\n  Fiat.ADTNotation\n  FunctionalExtensionality.\n\nAxiom prop_ext : forall (P Q : Prop), (P <-> Q) -> P = Q.\n\nLtac shatter :=\n  unfold id in *;\n  repeat\n    match goal with\n    | [ H : and _ _            |- _                 ] => destruct H\n    | [ H : Bind _ _ _         |- _                 ] => destruct H\n    | [ H : In _ _ _           |- _                 ] => destruct H\n    | [ H : Datatypes.prod _ _ |- _                 ] => destruct H\n    | [                        |- and _ _           ] => split\n    | [                        |- Bind _ _ _        ] => eexists\n    | [                        |- In _ _ _          ] => constructor\n    | [                        |- In _ _ _          ] => solve [ eauto ]\n    | [                        |- In _ (Bind _ _) _ ] => eexists\n    | [                        |- In _ _ _          ] => econstructor\n    end;\n  simpl in *.\n\n(** Until the FunctorLaws are expressed in terms of some arbitrary\n    equivalence, we need to use functional and propositional\n    extensionality. *)\n\nLtac simplify_comp :=\n  repeat let x := fresh \"x\" in extensionality x;\n  try (apply prop_ext; split; intros);\n  repeat shatter;\n  try constructor; eauto.\n\nLtac zoom T :=\n  let Ty := type of T in\n  let U := fresh \"U\" in evar (U : Ty);\n  let H := fresh \"H\" in assert (T = U) as H;\n    [ subst U | setoid_rewrite H; clear H; unfold U; clear U ].\n\nLtac shift tac := etransitivity; [apply tac|].\n\nLemma surjective_pairing_r : forall A B (x : A * B),\n  (fst x, snd x) = x.\nProof.\n  intros.\n  destruct x; reflexivity.\nQed.\n\nLtac adjust term :=\n  let T := constr:term in\n  assert { T' : _ & T = T'} as T'; [eexists| apply (projT1 T')].\n\nRequire Import\n  Fiat.ADTRefinement\n  Fiat.ADTRefinement.BuildADTRefinements.\n\nTactic Notation \"refine\" \"method\" constr(name) :=\n  match goal with\n    | [ _ : constructorType ?A (consDom {| consID := name\n                                         ; consDom := _ |}) |- _ ] =>\n      idtac \"Constructor\"\n    | [ _ : methodType ?A (methDom {| methID := name\n                                    ; methDom := _\n                                    ; methCod := _ |})  _ |- _ ] =>\n      idtac \"Method\"\n    | _ =>\n      fail \"Incorrect method name\"\n  end.\n\nLtac finish_concrete :=\n  match goal with\n  | [ |- context[Pick _] ] => idtac\n  | _ => finish honing\n  end.\n\nLtac simplify_ADT :=\n  try simplify with monad laws; simpl;\n  try match goal with\n    [ H : _ = _ |- _ ] =>\n    rewrite H; clear H\n  end;\n  try refine pick eq;\n  try refine pick val tt; try tauto;\n  try simplify with monad laws;\n  try finish_concrete.\n\nLemma refineEquiv_If_Then_Else_Bind :\n  forall (A B : Type) (i : bool) (t e : Comp A) (b : A -> Comp B),\n    refineEquiv (a <- If i Then t Else e; b a)\n                (If i Then a <- t; b a Else (a <- e; b a)).\nProof. split; intros; destruct i; reflexivity. Qed.\n\nTheorem refine_If_Then_Else_bool :\n  forall (b : bool) A cpst cpse (res : Comp A),\n    (if b then refine cpst res else refine cpse res)\n      <-> refine (If b Then cpst Else cpse) res.\nProof. split; intros; destruct b; auto. Qed.\n\nLemma refineEquiv_Ifopt_Then_Else_Bind :\n  forall A B T (i : option T) (t : T -> Comp A) (e : Comp A) (b : A -> Comp B),\n    refineEquiv (a <- Ifopt i as p Then t p Else e; b a)\n                (Ifopt i as p Then a <- t p; b a Else (a <- e; b a)).\nProof. split; intros; destruct i; reflexivity. Qed.\n\nRequire Import ByteString.Decidable.\n\nLemma refineEquiv_Ifdec_Then_Else_Bind :\n  forall A B `{Decidable i} (t e : Comp A) (b : A -> Comp B),\n    refineEquiv (a <- Ifdec i Then t Else e; b a)\n                (Ifdec i Then a <- t; b a Else (a <- e; b a)).\nProof.\n  intros.\n  destruct H.\n  unfold Ifdec_Then_Else; simpl.\n  destruct Decidable_witness; reflexivity.\nQed.\n\nLemma refine_ret_ret_eq : forall A (a b : A),\n  refine (ret a) (ret b) <-> a = b.\nProof.\n  split; intros.\n    specialize (H b (ReturnComputes b)).\n    apply Return_inv; assumption.\n  destruct H.\n  reflexivity.\nQed.\n\nRequire Import ByteString.TupleEnsembles.\n\nLemma refine_ret_ret_Same : forall A B (a b : EMap A B),\n  refine (ret a) (ret b) <-> Same a b.\nProof.\n  split; intros.\n    specialize (H b (ReturnComputes b)).\n    destruct H.\n    reflexivity.\n  f_equiv.\n  apply Extensionality_Ensembles, Same_Same_set.\n  assumption.\nQed.\n\nLemma refine_ret_ret_fst_Same : forall A (x z : Comp A) B (y w : B),\n  Same_set _ x z -> y = w -> refine (ret (x, y)) (ret (z, w)).\nProof.\n  intros; subst; f_equiv; f_equal.\n  apply Extensionality_Ensembles; assumption.\nQed.\n\nLtac breakdown :=\n  match goal with\n  | [ H : IF _ then _ else _ |- _ ] => destruct H\n  | [ H : _ /\\ _             |- _ ] => destruct H\n  | [ H : _ \\/ _             |- _ ] => destruct H\n  | [ H : _ * _              |- _ ] => destruct H\n  | [ H : exists _, _        |- _ ] => destruct H\n  | [ H : @sig _ _           |- _ ] => destruct H\n  | [ H : @sig2 _ _ _        |- _ ] => destruct H\n  | [ H : @sigT _ _          |- _ ] => destruct H\n  | [ H : @sigT2 _ _ _       |- _ ] => destruct H\n  | [ H : bool               |- _ ] => destruct H\n  | [ H : option _           |- _ ] => destruct H\n  | [ H : sum _ _            |- _ ] => destruct H\n  | [ H : sumor _ _          |- _ ] => destruct H\n  | [ H : sumbool _ _        |- _ ] => destruct H\n\n  | [ H : forall x, Some ?X = Some x -> _  |- _ ] => specialize (H X eq_refl)\n  | [ H : forall x y, Some (?X, ?Y) = Some (x, y) -> _  |- _ ] =>\n    specialize (H X Y eq_refl)\n\n  | [ H1 : ?X = true, H2 : ?X = false |- _ ] => rewrite H1 in H2; discriminate\n  end.\n", "meta": {"author": "jwiegley", "repo": "bytestring-fiat", "sha": "109d3abcae4ffe02ff8ba173887259f42138dea8", "save_path": "github-repos/coq/jwiegley-bytestring-fiat", "path": "github-repos/coq/jwiegley-bytestring-fiat/bytestring-fiat-109d3abcae4ffe02ff8ba173887259f42138dea8/attic/Tactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2257505157148206}}
{"text": "(** * IndistRelations.v: indistinguishability relation for annotated programs *)\nRequire FFun.\nRequire Export DEX_BigStepAnnot.\nRequire Export Annotated.\n\nOpen Scope type_scope.\n\nImport DEX_BigStepAnnot.DEX_BigStepAnnot DEX_BigStep.DEX_BigStep DEX_Dom DEX_Prog.\n\nInductive Value_in  (b b':FFun.t DEX_Location) : DEX_value -> DEX_value -> Prop :=\n| Value_in_null: Value_in b b' Null Null\n| Value_in_num: forall n,\n  Value_in b b' (Num n) (Num n)\n| Value_in_ref: forall loc loc' n, \n  FFun.lookup b n = Some loc -> \n  FFun.lookup b' n = Some loc' -> \n  Value_in b b' (Ref loc) (Ref loc').\n\nInductive Value_in_opt (b b':FFun.t DEX_Location) : \n  option DEX_value -> option DEX_value -> Prop :=\n| Value_in_opt_some: \n  forall v v',\n    Value_in b b' v v' -> \n    Value_in_opt b b' (Some v) (Some v')\n| Value_in_opt_none: Value_in_opt b b' None None.\n\nInductive Reg_in (observable:L.t) (b b':FFun.t DEX_Location) \n  (r r': DEX_Registers.t) (rt rt': TypeRegisters) (rn:DEX_Reg) : Prop :=\n| Reg_high_in : forall k k', MapList.get rt rn = Some k -> MapList.get rt' rn = Some k' ->\n    ~(L.leql k observable) -> ~(L.leql k' observable) -> \n    Reg_in observable b b' r r' rt rt' rn\n| Reg_nhigh_in : Value_in_opt b b' (DEX_Registers.get r rn) (DEX_Registers.get r' rn) \n    -> Reg_in observable b b' r r' rt rt' rn.\n\nInductive Regs_in (observable:L.t) (b b':FFun.t DEX_Location) \n  (r r': DEX_Registers.t) (rt rt': TypeRegisters) : Prop :=\n| Build_Regs_in : eq_set (MapList.dom rt) (MapList.dom rt') ->\n  (forall (rn:DEX_Reg), Reg_in observable b b' r r' rt rt' rn) -> \n  Regs_in observable b b' r r' rt rt'.\n\nDefinition ffun_heap_compat (b:FFun.t DEX_Location) (h:DEX_Heap.t) : Prop :=\n  forall loc, FFun.image b loc -> DEX_Heap.typeof h loc <> None.\n\nRecord hp_in (observable:L.t) (ft:DEX_FieldSignature -> L.t)  \n    (b b': FFun.t DEX_Location) (h h': DEX_Heap.t) : Prop :=\n  make_hp_in {\n    object_in : forall n loc loc' f cn cn',\n      FFun.lookup b n = Some loc -> \n      FFun.lookup b' n = Some loc' -> \n      DEX_Heap.typeof h loc = Some (DEX_Heap.DEX_LocationObject cn) ->\n      DEX_Heap.typeof h' loc' = Some (DEX_Heap.DEX_LocationObject cn') ->\n      L.leql (ft f) observable->\n      Value_in_opt b b' \n      (DEX_Heap.get h (DEX_Heap.DEX_DynamicField loc f))\n      (DEX_Heap.get h' (DEX_Heap.DEX_DynamicField loc' f));\n    class_object_in : forall n loc loc',\n      FFun.lookup b n = Some loc -> \n      FFun.lookup b' n = Some loc' -> \n      DEX_Heap.typeof h loc = DEX_Heap.typeof h' loc';\n    compat_ffun : FFun.compat b b';\n(*     static_heap_in : True; *)\n    left_inj : FFun.is_inj b;\n    right_inj : FFun.is_inj b';\n    left_heap_compat : ffun_heap_compat b h;\n    right_heap_compat : ffun_heap_compat b' h'\n  }.\n\n\nInductive st_in (observable:L.t) (ft:DEX_FieldSignature -> L.t) (b b':FFun.t DEX_Location) \n    (rt rt':TypeRegisters) :   \n  DEX_PC * DEX_Heap.t * DEX_Registers.t ->\n  DEX_PC * DEX_Heap.t * DEX_Registers.t -> Prop := \n| Build_st_in: forall pc pc' h h' r r',\n    Regs_in observable b b' r r' rt rt' ->\n    hp_in observable ft b b' h h' ->\n    st_in observable ft b b' rt rt' (pc,h,r) (pc',h',r').\n\nInductive indist_return_value (observable:L.t) (h1 h2:DEX_Heap.t) (s:DEX_sign) : \n    DEX_ReturnVal -> DEX_ReturnVal -> FFun.t DEX_Location -> FFun.t DEX_Location -> Prop :=\n| indist_return_val : forall v1 v2 b1 b2 k,\n  s.(DEX_resType) = Some k ->\n  (L.leql k observable -> Value_in b1 b2 v1 v2) ->\n  indist_return_value observable h1 h2 s (Normal (Some v1)) (Normal (Some v2)) b1 b2\n| indist_return_void : forall b1 b2, \n  s.(DEX_resType) = None ->\n  indist_return_value observable h1 h2 s (Normal None) (Normal None) b1 b2.\n\nInductive high_result (observable:L.t) (s:DEX_sign) : DEX_ReturnState -> Prop :=\n| high_result_void : forall h,\n  s.(DEX_resType) = None ->\n  high_result observable s (h, Normal None)\n| high_result_value : forall h v k,\n  s.(DEX_resType) = Some k ->\n  ~ L.leql k observable ->\n  high_result observable s (h, Normal (Some v)).\n\nInductive state : Type :=\n  intra : DEX_IntraNormalState -> TypeRegisters -> FFun.t DEX_Location -> state\n| ret : DEX_Heap.t -> DEX_ReturnVal -> FFun.t DEX_Location -> state.\n\nInductive indist (observable:L.t) (p:DEX_ExtendedProgram) (m:DEX_Method) \n  (sgn:DEX_sign) : state -> state -> Prop :=\n| indist_intra : forall pc pc' h h' r r' rt rt' b b',\n  st_in observable (DEX_ft p) b b' rt rt' (pc,h,r) (pc',h',r') ->\n  indist observable p m sgn (intra (pc,(h,r)) rt b) (intra (pc',(h',r')) rt' b')\n| indist_return : forall b b' h h' v v',\n  indist_return_value observable h h' sgn v v' b b' ->\n  indist observable p m sgn (ret h v b) (ret h' v' b').\n\n\n (** Indistinguishability relations *)\n\nSection p.\n  Variable kobs : L.t.\n  Variable p : DEX_ExtendedProgram.\n  Notation ft := (DEX_ft p).\n\n (** Basic results on indistinguishability relations *)\n\n  Lemma Value_in_sym : forall v1 v2 b1 b2,\n    Value_in b1 b2 v1 v2 ->\n    Value_in b2 b1 v2 v1.\n  Proof.\n    intros.\n    inversion_clear H; try constructor.\n    constructor 3 with n; auto.\n  Qed.\n\n  Lemma Value_in_opt_sym : forall b1 b2 v1 v2,\n    Value_in_opt b1 b2 v1 v2 ->\n    Value_in_opt b2 b1 v2 v1.\n  Proof.\n    intros.\n    inversion_clear H; try constructor.\n    apply Value_in_sym; auto.\n  Qed.\n\n  Lemma Value_in_trans : forall b1 b2 b3 v1 v2 v3,\n    FFun.is_inj b2 ->\n    Value_in b1 b2 v1 v2 ->\n    Value_in b2 b3 v2 v3 ->\n    Value_in b1 b3 v1 v3.\n  Proof.\n    intros.\n    inversion_clear H0 in H1; inversion_clear H1; try constructor.\n    rewrite <- (H _ _ _ H3 H0) in H4.\n    constructor 3 with n; auto.\n  Qed.\n\n  Lemma Value_in_opt_trans : forall b1 b2 b3 v1 v2 v3,\n    FFun.is_inj b2 ->\n    Value_in_opt b1 b2 v1 v2->\n    Value_in_opt b2 b3 v2 v3 ->\n    Value_in_opt b1 b3 v1 v3.\n  Proof.\n    intros.\n    inversion_clear H0 in H1; inversion_clear H1; try constructor.\n    eapply Value_in_trans; eauto.\n  Qed. \n\n  Lemma leql_join1 : forall k1 k2 k3,\n    L.leql k2 k3 ->\n    L.leql k2 (L.join k1 k3).\n  Proof.\n    intros.\n    apply L.leql_trans with (1:=H).\n    apply L.join_right.\n  Qed.\n\n  Lemma leql_join2 : forall k1 k2 k3,\n    L.leql k2 k1 ->\n    L.leql k2 (L.join k1 k3).\n  Proof.\n    intros.\n    apply L.leql_trans with (1:=H).\n    apply L.join_left.\n  Qed.\n\n  Lemma not_leql_trans : forall k1 k2 k3,\n    ~ L.leql k1 k3 ->\n    L.leql k1 k2 ->\n    ~ L.leql k2 k3.\n  Proof.\n    red; intros.\n    elim H.\n    apply L.leql_trans with (1:=H0); auto.\n  Qed.\n\n  Lemma not_leql_join1 : forall k1 k2 k3,\n    ~ L.leql k1 k3 ->\n    ~ L.leql (L.join k1 k2) k3.\n  Proof.\n    intros; apply not_leql_trans with k1; auto.\n    apply L.join_left.\n  Qed.\n\n  Lemma not_leql_join2 : forall k1 k2 k3,\n    ~ L.leql k2 k3 ->\n    ~ L.leql (L.join k1 k2) k3.\n  Proof.\n    intros; apply not_leql_trans with k2; auto.\n    apply L.join_right.\n  Qed.\n\n  Lemma leql_join_each: forall k k1 k2, L.leql (L.join k k1) k2 -> L.leql k k2 /\\ L.leql k1 k2.\n  Proof. intros.\n    split. apply L.leql_trans with (l2:=L.join k k1); auto. apply L.join_left.\n    apply L.leql_trans with (l2:=L.join k k1); auto. apply L.join_right.\n  Qed.\n\n  Lemma Reg_in_sym : forall obs b b' r r' rt rt' rn, \n    Reg_in obs b b' r r' rt rt' rn -> \n    Reg_in obs b' b r' r rt' rt rn.\n  Proof.\n    intros.\n    inversion H.\n      constructor 1 with (k:=k') (k':=k); auto.\n      constructor 2; auto.\n      apply Value_in_opt_sym; auto.\n  Qed.  \n\n Lemma Regs_in_sym : forall b1 b2 r1 r2 rt1 rt2,\n    Regs_in kobs b1 b2 r1 r2 rt1 rt2 ->\n    Regs_in kobs b2 b1 r2 r1 rt2 rt1.\n  Proof.\n    induction 1.\n    constructor. apply eq_set_sym; auto.\n    intros.\n    apply Reg_in_sym; auto.\n  Qed.\n\n  Lemma hp_in_sym : forall h1 h2 b1 b2,\n    hp_in kobs ft b1 b2 h1 h2 -> hp_in kobs ft b2 b1 h2 h1.\n  Proof.\n    intros.\n    destruct H; constructor; auto.\n    intros.  \n    apply Value_in_opt_sym; auto.\n    eapply object_in0; eauto.\n    intros.\n    rewrite (class_object_in0 n loc' loc); auto.\n    intros n; generalize (compat_ffun0 n); intuition.\n  Qed.\n\n  Lemma st_in_sym : forall b b' rt rt' r r',\n    st_in kobs ft b b' rt rt' r r' ->\n    st_in kobs ft b' b rt' rt r' r.\n  Proof.\n    intros.\n    inversion_clear H; constructor.\n    apply Regs_in_sym; auto.\n    apply hp_in_sym; auto.\n  Qed.\n  Implicit Arguments st_in_sym.\n\n  Lemma hp_in_trans : forall h1 h2 h3 b1 b2 b3,\n    hp_in kobs ft b1 b2 h1 h2 -> \n    hp_in kobs ft b2 b3 h2 h3 ->\n    hp_in kobs ft b1 b3 h1 h3.\n  Proof.\n    intros.\n    destruct H; destruct H0.\n    constructor; auto.\n    intros.\n    destruct (compat_ffun1 n).\n    caseeq (FFun.lookup b2 n); intros.\n    apply Value_in_opt_trans with \n      (v2:=(DEX_Heap.get h2 (DEX_Heap.DEX_DynamicField d f))) (b2:=b2); auto.\n    eapply object_in0; eauto.\n    rewrite <- (class_object_in0 n loc d); eauto.\n    eapply object_in1; eauto.\n    rewrite <- (class_object_in0 n loc d); eauto.\n    rewrite H4 in H0; auto; discriminate.\n    intros.\n    destruct (compat_ffun1 n).\n    caseeq (FFun.lookup b2 n); intros.\n    rewrite (class_object_in0 n loc d); auto.\n    rewrite (class_object_in1 n d loc'); auto.\n    rewrite H1 in H0; auto; discriminate.  \n    intros n.\n    generalize (compat_ffun0 n); \n      generalize (compat_ffun1 n); intuition.\n  Qed.\n\n  Lemma Value_in_opt_some_aux: forall b b' ov ov' v v', \n    Value_in b b' v v' -> \n    ov=(Some v)  -> \n    ov'= (Some v') -> \n    Value_in_opt b b' ov ov'.\n  Proof.\n    intros;  subst; constructor; auto.\n  Qed.\n\n  Lemma Reg_in_upd_low: \n    forall k (v v' : DEX_value) (r r' : DEX_Registers.t) (rt rt' : TypeRegisters)\n      (reg : DEX_Reg) (b b': FFun.t DEX_Location), \n      Reg_in kobs b b' r r' rt rt' reg -> \n      Value_in b b' v v' -> \n      L.leql k kobs ->\n      Reg_in kobs b b' (DEX_Registers.update r reg v) (DEX_Registers.update r' reg v')\n      (MapList.update rt reg k) (MapList.update rt' reg k) reg.\n  Proof.\n    intros k v v' r r' rt rt' reg b b' HRegIn HValIn Hleq.\n    constructor 2. rewrite ?DEX_Registers.get_update_new.\n    constructor; auto.\n  Qed.\n\n  Lemma Reg_in_upd_high:\n    forall k k' (v v' : DEX_value) (r r' : DEX_Registers.t) (rt rt' : TypeRegisters)\n      (reg : DEX_Reg) (b b': FFun.t DEX_Location), \n      Reg_in kobs b b' r r' rt rt' reg ->  \n      ~L.leql k kobs ->\n      ~L.leql k' kobs ->\n      Reg_in kobs b b' (DEX_Registers.update r reg v) (DEX_Registers.update r' reg v')\n      (MapList.update rt reg k) (MapList.update rt' reg k') reg.\n  Proof.\n    intros k k' v v' r r' rt rt' reg b b' HRegIn Hnleq1 Hnleq2.\n    constructor 1 with (k:=k) (k':=k'); try (rewrite MapList.get_update1); auto.\n  Qed.\n\n  Lemma ffun_extends_val_in: forall b b' v v' loc loc',\n    Value_in b b' v v' ->\n    Value_in (FFun.extends b loc) (FFun.extends b' loc') \n    v v'.\n  Proof.\n    intros; inversion_clear H; try constructor.\n    constructor 3 with n; auto.\n    apply FFun.extends_old; auto.\n    apply FFun.extends_old; auto.\n  Qed.\n\n  Lemma ffun_extends_val_in_opt: forall b b' v v' loc loc',\n    Value_in_opt b b' v v' ->\n    Value_in_opt (FFun.extends b loc) (FFun.extends b' loc')\n    v v'.\n  Proof.\n    intros; inversion H; subst; try constructor.\n    apply ffun_extends_val_in; auto.\n  Qed.\n\n  Lemma Value_in_extends_object : forall b1 b2 loc1 loc2 h1 h2,\n    ffun_heap_compat b1 h1 ->\n    ffun_heap_compat b2 h2 ->\n    DEX_Heap.typeof h1 loc1 = None ->\n    DEX_Heap.typeof h2 loc2 = None ->\n    FFun.compat b1 b2 ->\n    Value_in \n    (FFun.extends b1 loc1) (FFun.extends b2 loc2)\n    (Ref loc1) (Ref loc2) .\n  Proof.\n    intros.\n    constructor 3 with (FFun.next b1); auto.\n    apply FFun.extends_new.\n    rewrite (FFun.compat_implies_next _ b1 b2); auto.\n    apply FFun.extends_new.\n  Qed.\n\n  Lemma ffun_extends_Regs_in: forall s s' rt rt' b b' loc loc',\n    Regs_in kobs b b' s s' rt rt' ->\n    Regs_in kobs (FFun.extends b loc) (FFun.extends b' loc') \n    s s' rt rt'.\n  Proof.\n    intros.\n    induction H; intros; auto.\n    constructor; auto.\n    intros. specialize H0 with rn.\n    inversion H0. constructor 1 with (k:=k) (k':=k'); auto. \n    constructor 2. apply ffun_extends_val_in_opt; auto.\n  Qed.\n\n  Lemma ffun_heap_compat_update : forall h b am v,\n    ffun_heap_compat b h ->\n    ffun_heap_compat b (DEX_Heap.update h am v).\n  Proof.\n    unfold ffun_heap_compat; intros.\n    rewrite DEX_Heap.typeof_update_same; auto.\n  Qed.\n\n  Lemma ffun_heap_compat_extends : forall h c h' b loc,\n    ffun_heap_compat b h ->\n    DEX_Heap.new h p c = Some (loc,h') ->\n    ffun_heap_compat (FFun.extends b loc) h'.\n  Proof.\n    unfold ffun_heap_compat; intros.\n    destruct (DEX_Location_dec loc loc0).\n    subst.\n    rewrite (@DEX_Heap.new_typeof h p c loc0 h' H0).\n    discriminate.\n    rewrite (@DEX_Heap.new_typeof_old h p c loc loc0 h' H0); auto.\n    apply H.\n    destruct H1.\n    elim FFun.extends_case with DEX_Location b x loc loc0; auto; intros.\n    exists x; auto.\n    elim n; intuition.\n  Qed.\n\n  Lemma ffun_heap_compat_new : forall h c h' b loc,\n    ffun_heap_compat b h ->\n    DEX_Heap.new h p c = Some (loc,h') ->\n    ffun_heap_compat b h'.\n  Proof.\n    unfold ffun_heap_compat; intros.\n    destruct (DEX_Location_dec loc loc0).\n    subst.\n    rewrite (@DEX_Heap.new_typeof h p c loc0 h' H0).\n    discriminate.\n    rewrite (@DEX_Heap.new_typeof_old h p c loc loc0 h' H0); auto.\n  Qed.\n\n  Lemma hp_in_putfield_ffun : forall loc loc' b b' h h' f v v' cn cn',\n    hp_in kobs ft b b' h h' ->\n    Value_in b b' v v' ->\n    Value_in b b' (Ref loc) (Ref loc') ->\n    DEX_Heap.typeof h loc = Some (DEX_Heap.DEX_LocationObject cn) ->\n    DEX_Heap.typeof h' loc' = Some (DEX_Heap.DEX_LocationObject cn') ->\n    hp_in kobs ft b b'\n    (DEX_Heap.update h (DEX_Heap.DEX_DynamicField loc f) v)\n    (DEX_Heap.update h' (DEX_Heap.DEX_DynamicField loc' f) v').\n  Proof.\n    intros; constructor; auto; intros.\n\n    elim (DEX_Location_dec loc loc0);\n      elim (eq_excluded_middle _ f f0); intros; subst.\n    rewrite DEX_Heap.get_update_same; auto.\n    replace loc'0 with loc'.\n    rewrite DEX_Heap.get_update_same; auto.\n    constructor; auto.\n    constructor 1 with cn'; auto.\n    inversion_mine H1.\n    apply FFun.inv_aux with n0 n b b' loc0 loc0; auto. \n    eapply left_inj; eauto.\n    eapply right_inj; eauto.\n    constructor 1 with cn; auto.\n\n    rewrite DEX_Heap.get_update_old.\n    rewrite DEX_Heap.get_update_old.\n    eapply (object_in _ _ _ _ _ _ H); eauto.\n    rewrite DEX_Heap.typeof_update_same in H7; eauto.\n    intros HH; elim H9; congruence.\n    intros HH; elim H9; congruence.\n\n    rewrite DEX_Heap.get_update_old.\n    rewrite DEX_Heap.get_update_old.\n    eapply (object_in _ _ _ _ _ _ H); eauto.\n    rewrite DEX_Heap.typeof_update_same in H6; eauto.\n    rewrite DEX_Heap.typeof_update_same in H7; eauto.\n    intros HH; injection HH; intros; subst.\n    elim b0.\n    inversion_mine H1.\n    apply (FFun.inv_aux _ n0 n b' b loc'0 loc loc'0 loc0); auto.\n    eapply right_inj; eauto.\n    eapply left_inj; eauto.\n    intros HH; elim b0; congruence.\n\n    rewrite DEX_Heap.get_update_old.\n    rewrite DEX_Heap.get_update_old.\n    eapply (object_in _ _ _ _ _ _ H); eauto.\n    rewrite DEX_Heap.typeof_update_same in H6; eauto.\n    rewrite DEX_Heap.typeof_update_same in H7; eauto.\n    intros HH; elim b0; congruence.\n    intros HH; elim b0; congruence.\n\n    repeat rewrite DEX_Heap.typeof_update_same.\n    eapply class_object_in; eauto.\n    destruct H; auto.\n    destruct H; auto.\n    destruct H; auto.\n    apply ffun_heap_compat_update; destruct H; auto.\n    apply ffun_heap_compat_update; destruct H; auto.\n  Qed.\n\n  Lemma hp_in_putfield_high_update_left : forall loc b b' h h' f v cn,\n    hp_in kobs ft b b' h h' ->\n    ~ (L.leql (ft f) kobs) ->\n    DEX_Heap.typeof h loc = Some (DEX_Heap.DEX_LocationObject cn) ->\n    hp_in kobs ft b b'\n    (DEX_Heap.update h (DEX_Heap.DEX_DynamicField loc f) v) h'.\n  Proof.\n    intros; constructor; auto; intros.\n    assert (f<>f0).\n    intro; subst; intuition.\n    repeat rewrite DEX_Heap.get_update_old.\n    eapply (object_in _ _ _ _ _ _ H); eauto.\n    rewrite DEX_Heap.typeof_update_same in H4; eauto.\n    intros HH; elim H7; congruence.\n    rewrite DEX_Heap.typeof_update_same.\n    eapply class_object_in; eauto.\n    destruct H; auto.\n    destruct H; auto.\n    destruct H; auto.\n    apply ffun_heap_compat_update; destruct H; auto.\n    destruct H; auto.\n  Qed.\n\n  Lemma hp_in_putfield_high_update_right : forall loc b b' h h' f v cn,\n    hp_in kobs ft b b' h h' ->\n    ~ (L.leql (ft f) kobs) ->\n    DEX_Heap.typeof h' loc = Some (DEX_Heap.DEX_LocationObject cn) ->\n    hp_in kobs ft b b'\n    h (DEX_Heap.update h' (DEX_Heap.DEX_DynamicField loc f) v).\n  Proof.\n    intros.\n    apply hp_in_sym.\n    eapply hp_in_putfield_high_update_left; eauto.\n    apply hp_in_sym; auto.\n  Qed.\n\n  Lemma hp_in_putfield_high : forall loc loc' b b' h h' f v v' cn cn',\n    hp_in kobs ft b b' h h' ->\n    ~ (L.leql (ft f) kobs) ->\n    DEX_Heap.typeof h loc = Some (DEX_Heap.DEX_LocationObject cn) ->\n    DEX_Heap.typeof h' loc' = Some (DEX_Heap.DEX_LocationObject cn') ->\n    hp_in kobs ft b b'\n    (DEX_Heap.update h (DEX_Heap.DEX_DynamicField loc f) v)\n    (DEX_Heap.update h' (DEX_Heap.DEX_DynamicField loc' f) v').\n  Proof.\n    intros.\n    apply hp_in_putfield_high_update_left with cn; auto.\n    apply hp_in_putfield_high_update_right with cn'; auto.\n  Qed.\n\n  Lemma Compat_ex : forall h am, DEX_Heap.Compat h am \\/ ~ DEX_Heap.Compat h am.\n  Proof.\n    intros.\n    apply excluded_middle.\n  Qed.\n\n  Lemma ffun_extends_hp_in: forall c b b' h h' hn hn' loc loc',\n    hp_in kobs ft b b' h h' ->\n    DEX_Heap.new h p (DEX_Heap.DEX_LocationObject c) = Some (pair loc hn) ->\n    DEX_Heap.new h' p (DEX_Heap.DEX_LocationObject c) = Some (pair loc' hn') ->\n    hp_in kobs ft (FFun.extends b loc) (FFun.extends b' loc') hn hn'.\n  Proof.\n    intros.\n    inversion_clear H; constructor; intros; try trivial.\n    elim FFun.extends_case with DEX_Location b n loc loc0; intros; Cleanand; auto.\n    assert (Haux:=FFun.compat_extends _ _ _ _ _ _ _ compat_ffun0 H6 H2).\n    apply ffun_extends_val_in_opt.\n    rewrite (@DEX_Heap.new_object_no_change h p c loc hn); auto.\n    rewrite (@DEX_Heap.new_object_no_change h' p c loc' hn'); auto.\n\n    assert (Hclass:=class_object_in0 _ _ _ H6 Haux).\n    elim Compat_ex with h (@DEX_Heap.DEX_DynamicField loc0 f); intros Hcomp.\n    inversion_clear Hcomp. \n    generalize H7; rewrite Hclass; intros.\n    apply object_in0 with n cn0 cn0; auto.\n    rewrite (@DEX_Heap.get_uncompat h); auto.\n    rewrite (@DEX_Heap.get_uncompat h').\n    constructor.\n    intros HH; inversion_clear HH.\n    elim Hcomp; constructor 1 with cn0.\n    rewrite Hclass; auto.\n    intros fs Hi; injection Hi; intros; subst.\n    elim right_heap_compat0 with loc'.\n    exists n; auto.\n    apply DEX_Heap.new_fresh_location with (1:=H1).\n    intros fs Hi; injection Hi; intros; subst.\n    elim left_heap_compat0 with loc.\n    exists n; auto.\n    apply DEX_Heap.new_fresh_location with (1:=H0).\n\n  (***)\n\n    subst. \n    rewrite (FFun.compat_implies_next _ _ _ compat_ffun0) in H2.\n    rewrite FFun.extends_new in H2.\n    injection H2; clear H2; intros; subst.\n    destruct (excluded_middle (defined_field p c f)) as [d|d].\n    inversion_clear d.\n    rewrite (@DEX_Heap.new_defined_object_field h p c f x loc0 hn); auto.\n    rewrite (@DEX_Heap.new_defined_object_field h' p c f x loc'0 hn'); auto.\n    constructor.\n    unfold init_field_value.\n    destruct (DEX_FIELD.initValue x); try constructor.\n    unfold init_value. \n    destruct DEX_FIELDSIGNATURE.type; constructor.\n    rewrite (@DEX_Heap.new_undefined_object_field h p c f loc0 hn); auto.\n    rewrite (@DEX_Heap.new_undefined_object_field h' p c f loc'0 hn'); auto.\n    constructor.\n\n    elim FFun.extends_case with (1:= H); intros.\n    assert (FFun.lookup b' n = Some loc'0). \n    apply FFun.compat_extends with b loc0 loc'; auto.\n    destruct (DEX_Location_dec loc loc0); destruct (DEX_Location_dec loc' loc'0); subst.\n    rewrite (@DEX_Heap.new_typeof h p (DEX_Heap.DEX_LocationObject c) loc0 hn); auto.\n    rewrite (@DEX_Heap.new_typeof h' p (DEX_Heap.DEX_LocationObject c) loc'0 hn'); auto.\n    assert (T:=@DEX_Heap.new_fresh_location h p (DEX_Heap.DEX_LocationObject c) loc0 hn H0).\n    elim (left_heap_compat0 loc0); auto.\n    exists n; auto.\n    assert (T:=@DEX_Heap.new_fresh_location h' p (DEX_Heap.DEX_LocationObject c) loc'0 hn' H1).\n    elim (right_heap_compat0 loc'0); auto.\n    exists n; auto.\n    rewrite (@DEX_Heap.new_typeof_old h p (DEX_Heap.DEX_LocationObject c) loc loc0 hn); auto.\n    rewrite (@DEX_Heap.new_typeof_old h' p (DEX_Heap.DEX_LocationObject c) loc' loc'0 hn'); auto.\n    eapply class_object_in0; eauto.\n    destruct H3; subst.\n    rewrite (@DEX_Heap.new_typeof h p (DEX_Heap.DEX_LocationObject c) loc0 hn); auto.\n    rewrite (FFun.compat_implies_next _ _ _ compat_ffun0) in H2.\n    rewrite (FFun.extends_new _ b' loc') in H2.\n    injection H2; intros; subst.\n    rewrite (@DEX_Heap.new_typeof h' p (DEX_Heap.DEX_LocationObject c) loc'0 hn'); auto.\n    apply FFun.compat_preserved_by_extends; auto.\n    apply FFun.extends_inj; auto.\n    intro.\n    elim (left_heap_compat0 _ H).\n    eapply DEX_Heap.new_fresh_location; eauto.\n    apply FFun.extends_inj; auto.\n    intro.\n    elim (right_heap_compat0 _ H).\n    eapply DEX_Heap.new_fresh_location; eauto.\n    apply ffun_heap_compat_extends with (2:=H0); auto.\n    apply ffun_heap_compat_extends with (2:=H1); auto.\n  Qed.\n\n  Lemma ffun_extends_hp_in_new_left: forall c b b' h h' hn loc,\n    hp_in kobs ft b b' h h' ->\n    DEX_Heap.new h p (DEX_Heap.DEX_LocationObject c) = Some (pair loc hn) ->\n    hp_in kobs ft b b' hn h'.\n  Proof.\n    intros.\n    inversion_clear H; constructor; intros; try trivial.\n    rewrite (@DEX_Heap.new_object_no_change h p c loc hn); auto.\n    assert (Hclass:=class_object_in0 _ _ _ H H1).\n    elim Compat_ex with h (DEX_Heap.DEX_DynamicField loc0 f); intros Hcomp.\n    inversion_clear Hcomp. \n    generalize H5; rewrite Hclass; intros.\n    apply object_in0 with n cn0 cn0; auto.\n    rewrite (@DEX_Heap.get_uncompat h); auto.\n    rewrite (@DEX_Heap.get_uncompat h').\n    constructor.\n    intros HH; inversion_clear HH.\n    elim Hcomp; constructor 1 with cn0.\n    rewrite Hclass; auto.\n    intros fs Hi; injection Hi; intros; subst.\n    elim left_heap_compat0 with loc.\n    exists n; auto.\n    apply DEX_Heap.new_fresh_location with (1:=H0).\n\n    \n    destruct (DEX_Location_dec loc0 loc); subst.\n    rewrite (@DEX_Heap.new_typeof h p (DEX_Heap.DEX_LocationObject c) loc hn); auto.\n    elim left_heap_compat0 with loc.\n    exists n; auto.\n    eapply DEX_Heap.new_fresh_location; eauto.\n    rewrite (@DEX_Heap.new_typeof_old h p (DEX_Heap.DEX_LocationObject c) loc loc0 hn); auto.\n    eauto.\n    \n    repeat intro.\n    elim left_heap_compat0 with loc0; auto.\n    destruct (DEX_Location_dec loc0 loc); subst.\n    rewrite (@DEX_Heap.new_typeof h p (DEX_Heap.DEX_LocationObject c) loc hn) in H1; auto; discriminate.\n    rewrite (@DEX_Heap.new_typeof_old h p (DEX_Heap.DEX_LocationObject c) loc loc0 hn) in H1; auto.\n  Qed.\n\n  Lemma ffun_extends_hp_in_new_right: forall c b b' h h' hn' loc,\n    hp_in kobs ft b b' h h' ->\n    DEX_Heap.new h' p (DEX_Heap.DEX_LocationObject c) = Some (pair loc hn') ->\n    hp_in kobs ft b b' h hn'.\n  Proof.\n    intros.\n    apply hp_in_sym; eapply ffun_extends_hp_in_new_left; eauto.\n    apply hp_in_sym; auto.\n  Qed.\n\n  Lemma ffun_extends_hp_in_simpl: forall c c' b b' h h' hn hn' loc loc',\n    hp_in kobs ft b b' h h' ->\n    DEX_Heap.new h p (DEX_Heap.DEX_LocationObject c) = Some (pair loc hn) ->\n    DEX_Heap.new h' p (DEX_Heap.DEX_LocationObject c') = Some (pair loc' hn') ->\n    hp_in kobs ft b b' hn hn'.\n  Proof.\n    intros.\n    eapply ffun_extends_hp_in_new_left; eauto.\n    eapply ffun_extends_hp_in_new_right; eauto.\n  Qed.\n\n  Lemma indist_same_class : forall h1 h2 loc1 loc2 b1 b2,\n    hp_in kobs ft b1 b2 h1 h2 ->\n    Value_in b1 b2 (Ref loc1) (Ref loc2) ->\n    DEX_Heap.typeof h1 loc1 = DEX_Heap.typeof h2 loc2.\n  Proof.\n    intros.\n    inversion_clear H0.\n    apply (class_object_in _ _ _ _ _ _ H n) ;auto.\n  Qed.\n\n  Lemma ex_comp_Z : forall x y z:Z,\n    (x <= y < z \\/ ~ x <= y < z)%Z.\n  Proof.\n    intros.\n    destruct (Z_le_dec x y).\n    destruct (Z_lt_dec y z); intuition.\n    intuition.\n  Qed.\n\n  Lemma nth_error_none_length : forall (A:Set) (l:list A) i,\n    nth_error l i = None -> (length l <= i)%nat.\n  Proof.\n    induction l; destruct i; simpl; intros; try omega. \n    discriminate.\n    generalize (IHl _ H); omega.\n  Qed.\n\n  Lemma nth_error_some_length : forall (A:Set) (l:list A) i a,\n    nth_error l i = Some a -> (length l > i)%nat.\n  Proof.\n    induction l; destruct i; simpl; intros; try discriminate; try omega. \n    generalize (IHl _ _ H); omega.\n  Qed.\n\n  Definition beta_pre_order (b1 b2:FFun.t DEX_Location) : Prop :=\n    forall loc n, FFun.lookup b1 n = Some loc -> FFun.lookup b2 n = Some loc. \n\n  Lemma beta_pre_order_value_in: forall v v' b1 b2 b1' b2',\n    beta_pre_order b1 b2 ->\n    beta_pre_order b1' b2' ->\n    Value_in b1 b1' v v'->\n    Value_in b2 b2' v v'.\n  Proof.\n    intros.\n    inversion_clear H1; try constructor.\n    constructor 3 with n; auto.\n  Qed.\n\n  Lemma beta_pre_order_value_in_opt:  forall v v' b1 b2 b1' b2',\n    beta_pre_order b1 b2 ->\n    beta_pre_order b1' b2' ->\n    Value_in_opt b1 b1' v v' ->\n    Value_in_opt b2 b2' v v'.\n  Proof.\n    intros.\n    inversion_clear H1; constructor.\n    eapply beta_pre_order_value_in; eauto.\n  Qed.\n\n  Lemma beta_pre_order_Regs_in:  forall s s' rt rt' b1 b2 b1' b2',\n    beta_pre_order b1 b2 ->\n    beta_pre_order b1' b2' ->\n    Regs_in kobs b1 b1' s s' rt rt' ->\n    Regs_in kobs b2 b2' s s' rt rt' .\n  Proof.\n    induction 3.\n    constructor; auto.\n    intros; specialize H2 with rn.\n    inversion H2.\n    constructor 1 with k k'; auto.\n    constructor 2; auto.\n    eapply beta_pre_order_value_in_opt; eauto.\n  Qed.\n\n  Lemma hp_in_getfield : forall b2 b2' v v0 h2 h2' loc loc0 cn cn0 f,\n    DEX_Heap.typeof h2 loc = Some (DEX_Heap.DEX_LocationObject cn) ->\n    DEX_Heap.get h2 (DEX_Heap.DEX_DynamicField loc f) = Some v ->\n    DEX_Heap.typeof h2' loc0 = Some (DEX_Heap.DEX_LocationObject cn0) ->\n    DEX_Heap.get h2' (DEX_Heap.DEX_DynamicField loc0 f) = Some v0 ->\n    hp_in kobs ft b2 b2' h2 h2' ->\n    L.leql (ft f) kobs ->\n    Value_in b2 b2' (Ref loc) (Ref loc0) ->\n    Value_in b2 b2' v v0.\n  Proof.\n    intros.\n    inversion_clear H5.\n    assert (HH:=object_in _ _ _ _ _ _ H3 _ _ _ f cn cn0 H6 H7 H H1 H4).\n    rewrite H0 in HH; rewrite H2 in HH.\n    inversion_clear HH; auto.\n  Qed.\n\n  Lemma Value_in_assign_compatible : forall h1 h2 loc1 loc2 t b1 b2,\n    Value_in b1 b2 (Ref loc1) (Ref loc2) ->\n    hp_in kobs ft b1 b2 h1 h2 ->\n    assign_compatible p h1 (Ref loc1) (DEX_ReferenceType t) ->\n    assign_compatible p h2 (Ref loc2) (DEX_ReferenceType t).\n  Proof.\n    intros.\n    generalize (indist_same_class _ _ _ _ _ _ H0 H); intros.\n    inversion_mine H1.\n    constructor 2 with cn; auto; congruence.\n  Qed.\n\n  Lemma Value_in_assign_compatible' : forall h1 h2 v1 v2 t b1 b2,\n    Value_in b1 b2 v1 v2 ->\n    hp_in kobs ft b1 b2 h1 h2 ->\n    assign_compatible p h1 v1 t ->\n    assign_compatible p h2 v2 t.\n  Proof.\n    intros.\n    destruct t. \n    destruct v1; destruct v2; try (inversion_mine H; inversion_mine H1; fail).\n    eapply Value_in_assign_compatible; eauto.\n    constructor.\n    inversion_mine H; inversion_mine H1; constructor; auto.\n  Qed.\n\n  Lemma Value_in_extends : forall b1 b2 loc1 loc2 h1 h2,\n    hp_in kobs ft b1 b2 h1 h2 ->\n    DEX_Heap.typeof h1 loc1 = None ->\n    DEX_Heap.typeof h2 loc2 = None ->\n    Value_in \n    (FFun.extends b1 loc1) (FFun.extends b2 loc2)\n    (Ref loc1) (Ref loc2) .\n  Proof.\n    intros.\n    destruct H.\n    eapply Value_in_extends_object; eauto.\n  Qed.\n\n(*  Lemma SemCompRef_Value_in : forall cmp v1 v2 v0 v3 b2 b2' h1 h2 ft,\n    hp_in kobs ft b2 b2' h1 h2 ->\n    DEX_SemCompRef cmp v1 v2 ->\n    Value_in b2 b2' v2 v0 ->\n    Value_in b2 b2' v1 v3 ->\n    SemCompRef cmp v3 v0.\n  Proof.\n    intros.\n    assert (Il:=left_inj _ _ _ _ _ _ _ H).\n    assert (Ir:=right_inj _ _ _ _ _ _ _ H).\n    inversion_mine H0;\n    inversion_mine H1; inversion_mine H2; econstructor; auto;\n      try constructor; try discriminate.\n    rewrite (FFun.inv_aux Location n n0 b2 b2' loc loc' loc loc'0); auto.\n    intro HH; elim H5; inversion_mine HH.\n    rewrite (FFun.inv_aux Location n n0 b2' b2 loc' loc loc' loc0); auto.\n  Qed. *)\n\nEnd p.\n\n  Hint Resolve \n    not_leql_join1 not_leql_join2 not_leql_trans \n    L.join_left L.join_right\n    L.leql_trans : lattice.", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/DEX_O/DEX_IndistRelations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22575051571482055}}
{"text": "(** * Facts about Well-defined H-VHDL Designs *)\n\nRequire Import common.CoqLib.\nRequire Import common.proofs.CoqTactics.\nRequire Import common.InAndNoDup.\nRequire Import common.proofs.ListPlusFacts.\nRequire Import common.proofs.ListPlusTactics.\n\nRequire Import hvhdl.WellDefinedDesign.\nRequire Import hvhdl.AbstractSyntax.\nRequire Import hvhdl.proofs.AbstractSyntaxFacts.\n\nOpen Scope abss_scope.\nImport HVhdlCsNotations.\n\n(** ** Facts about [AreCsCompIds]  *)\n\nLemma AreCsCompIds_determ :\n  forall cstmt compids compids',\n    AreCsCompIds cstmt compids ->\n    AreCsCompIds cstmt compids' ->\n    compids = compids'.\nProof. intros *; eapply FoldLCs_determ. Qed.\n\nLemma AreCsCompIds_ex : forall cstmt, exists compids, AreCsCompIds cstmt compids.\nProof. intros; eapply FoldLCs_ex. Qed.\n\nLemma AreCsCompIds_app1 :\n  forall cstmt compids',\n    let comp2id :=\n        fun (cids : list HVhdlTypes.ident) (cstmt0 : cs) =>\n          match cstmt0 with\n          | cs_comp id _ _ _ _ => cids ++ [id]\n          | _ => cids\n          end in\n    AreCsCompIds cstmt compids' ->\n    forall compids, FoldLCs comp2id cstmt compids (compids ++ compids').\nProof.\n  induction cstmt; intros; inversion H;\n    try ((rewrite app_nil_r; constructor) || (rewrite app_nil_l; constructor)).\n  destruct (AreCsCompIds_ex cstmt2) as (compids2, AreCsCompIds2).\n  constructor 4 with (a' := compids ++ a').\n  eapply IHcstmt1; eauto.\n  erewrite @FoldLCs_determ with (res := compids') (res' := a' ++ compids2); eauto.\n  rewrite app_assoc; apply IHcstmt2 with (compids := compids ++ a'); auto.\nQed. \n\nLemma AreCsCompIds_app :\n  forall cstmt cstmt' compids compids',\n    AreCsCompIds cstmt compids ->\n    AreCsCompIds cstmt' compids' ->\n    AreCsCompIds (cs_par cstmt cstmt') (compids ++ compids').\nProof.\n  intros; econstructor. eexact H.\n  apply AreCsCompIds_app1; auto.\nQed.\n\nLemma AreCsCompIds_eq_app :\n  forall cstmt cstmt' compids compids' compids'',\n    AreCsCompIds cstmt compids ->\n    AreCsCompIds cstmt' compids' ->\n    AreCsCompIds (cstmt // cstmt') compids'' ->\n    compids'' = compids ++ compids'.\nProof.\n  intros; eapply AreCsCompIds_determ; eauto.\n  eapply AreCsCompIds_app; eauto.\nQed.\n\nLemma AreCsCompIds_compid_iff :\n  forall {behavior compids},\n    AreCsCompIds behavior compids ->\n    (forall id__c, List.In id__c compids -> exists id__e gm ipm opm, InCs (cs_comp id__c id__e gm ipm opm) behavior)\n    /\\ (forall id__c id__e gm ipm opm, InCs (cs_comp id__c id__e gm ipm opm) behavior -> List.In id__c compids).\nProof.\n  induction behavior; inversion 1; (try inversion_clear 1); split;\n    tryif (solve [inversion_clear 1]) then (inversion_clear 1) else auto.\n\n  (* CASE behavior = comp(...) *)\n  - rewrite app_nil_l; inversion_clear 1;\n      [ try subst; exists id__e, g, i, o; reflexivity | contradiction ].\n  - rewrite app_nil_l; inversion_clear 1; constructor; reflexivity.\n\n  (* CASE behavior = beh1 || beh2 *)\n  - rename a' into compids1.\n    destruct (AreCsCompIds_ex behavior2) as (compids2, AreCsCompIds2).\n    erewrite AreCsCompIds_eq_app with (compids'' := compids) (compids := compids1); eauto.\n    intros id__c In_app; destruct_in_app_or.\n    + edestruct IHbehavior1 with (compids := compids1) as ((id__e, (gm, (ipm, (opm, InCs_beh1)))), _); eauto.\n      do 4 eexists; simpl; left; eexact InCs_beh1.\n    + edestruct IHbehavior2 with (compids := compids2) as ((id__e, (gm, (ipm, (opm, InCs_beh2)))), _); eauto.\n      do 4 eexists; simpl; right; eexact InCs_beh2.\n  - rename a' into compids1.\n    destruct (AreCsCompIds_ex behavior2) as (compids2, AreCsCompIds2).\n    erewrite AreCsCompIds_eq_app with (compids'' := compids) (compids := compids1); eauto.\n    simpl; inversion_clear 1.\n    + eapply in_or_app; left; eapply IHbehavior1 with (compids := compids1); eauto.\n    + eapply in_or_app; right; eapply IHbehavior2 with (compids := compids2); eauto.\nQed.\n\nLemma AreCsCompIds_ex_app :\n  forall {cstmt1 cstmt2 compids},\n    AreCsCompIds (cstmt1 // cstmt2) compids ->\n    exists compids1 compids2,\n      AreCsCompIds cstmt1 compids1 /\\\n      AreCsCompIds cstmt2 compids2 /\\ \n      compids = compids1 ++ compids2.\nProof.\n  do 3 intro.\n  destruct (AreCsCompIds_ex cstmt1) as (compids1, AreCsCompIds1).\n  destruct (AreCsCompIds_ex cstmt2) as (compids2, AreCsCompIds2).\n  exists compids1, compids2.\n  split_and; try (solve [assumption]).\n  eapply AreCsCompIds_eq_app; eauto.\nQed.\n\n(** ** Facts about [ArePortIds] Relation *)\n\nLemma ports_in_portids :\n  forall {id τ ports portids},\n    (List.In (pdecl_in id τ) ports \\/ List.In (pdecl_out id τ) ports) ->\n    ArePortIds ports portids ->\n    List.In id portids.\nProof.\n  inversion 1; intros;\n    lazymatch goal with\n    | [ H: List.In ?p _ |- _ ] =>\n      change id with ((fun pd : pdecl =>\n                         match pd with\n                         | pdecl_in id _ | pdecl_out id _ => id\n                         end) p);\n        eapply Map_in; eauto\n    end.\nQed.\n\n(** ** Facts about [AreSigIds] Relation *)\n\nLemma sigs_in_sigids :\n  forall {id τ sigs sigids},\n    List.In (sdecl_ id τ) sigs ->\n    AreSigIds sigs sigids ->\n    List.In id sigids.\nProof.\n  intros;\n    lazymatch goal with\n    | [ H: List.In ?s _ |- _ ] =>\n      change id with ((fun sd : sdecl =>\n                         match sd with\n                         | sdecl_ id _ => id\n                         end) s);\n        eapply Map_in; eauto\n    end.\nQed.\n\n", "meta": {"author": "viampietro", "repo": "ver-hilecop", "sha": "cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4", "save_path": "github-repos/coq/viampietro-ver-hilecop", "path": "github-repos/coq/viampietro-ver-hilecop/ver-hilecop-cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4/hvhdl/proofs/WellDefinedDesignFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2257505091971091}}
{"text": "Require Setoid.\nRequire Import Equivalence.\nRequire Import Program.Equality.\nRequire Import Ynot.\n\nDefinition ptsto_any_tot (p : ptr) :=\n  ptsto_any p (Qcanon.Q2Qc (QArith_base.Qmake BinInt.Z0 BinPos.xH)).\n\nRequire Import Array.\nRequire Import List.\nRequire Import Relations.\nOpen Local Scope hprop_scope.\nOpen Local Scope stsepi_scope.\nRequire Import Arith.\n\nGeneralizable All Variables.\nSet Automatic Introduction.\nUnset Implicit Arguments.\n\nLtac t := sep fail simpl.\n\nLtac dest_unpack f :=\n  case_eq f; intros; rewrite <- ! hiff_unpack.\n\nLtac move_one_pure := \n  match goal with\n    | |- hprop_inj _ * _ ==> _ => apply himp_inj_prem; intro\n    | |- _ * ?Q ==> _ => \n      match Q with \n        context [ hprop_inj _ ] => \n        rewrite hstar_comm; rewrite <- ! hstar_assoc\n      end\n  end.\n\nLtac move_one_pure_concl := \n  match goal with\n    | |- ?p ==> hprop_inj ?P * ?q => \n      match goal with\n        | H' : P |- _ => apply (himp_inj_conc H'); try move_one_pure_concl\n        | _ => \n          let H := fresh in\n            cut P; [intro H; apply (himp_inj_conc H); try move_one_pure_concl|idtac]\n      end\n    | |- _ ==>  ?P * ?Q => \n      match Q with \n        context [ hprop_inj _ ] => \n        rewrite (hstar_comm P Q); rewrite <- ! hstar_assoc\n      end\n  end.\n\nLtac move_pure := rewrite <- ! hstar_assoc; repeat move_one_pure;\n  try move_one_pure_concl.\n\nLtac safe_injection H :=\n  revert H; progress (intro H ; injection H ; clear H; intros).\n\nLtac discriminates :=\n  match goal with \n    | H : ?n <> ?n |- _ => elim H; reflexivity \n    | H : ?n = ?n |- _ => clear H\n    | H : ?x = ?y |- _ => (subst x || subst y ||\n      (safe_injection H ; intros))\n    | |- ?n <> ?n => elimtype False\n    | |- _ <> _ => intro\n  end.\n\nLtac contradictions := contradiction ||\n  match goal with \n    H : ?x = ?y |- _ => symmetry in H; contradiction\n  end.\n\nCreate HintDb dest discriminated.\n\nLtac simplify_goal := \n  autounfold with dest in *;\n  repeat dest_conj;\n  try discriminates;\n  try contradictions;\n  try congruence.\n\nDefinition block {A} (a : A) : A := a.\nLtac block H := let T := type of H in change (block T) in H.\nLtac unblock := unfold block in *.  \n\nLtac myauto := simplify_goal; try typeclasses eauto with dest.\nSet Firstorder Solver myauto.\n\nLemma pair_equal {A B} (x x' : A) (y y' : B) : (x, y) = (x', y') -> x = x' /\\ y = y'.\nProof. intros. injection H. intuition. Qed.\n\nLtac pack_injections := repeat\n  match goal with\n    H : [_]%inhabited = [_]%inhabited |- _ => \n      apply pack_injective in H\n  end. \n\nDefinition hprop_or (P Q : hprop) : hprop :=\n  fun h => P h \\/ Q h.\n\nLemma hprop_or_prem p q r : (p ==> r) /\\ (q ==> r) -> hprop_or p q ==> r.\nProof. firstorder. Qed.\n\nLemma hprop_or_left p q r : p ==> q -> p ==> hprop_or q r.\nProof. firstorder. Qed.\n  \nLemma hprop_or_right p q r : p ==> r -> p ==> hprop_or q r.\nProof. firstorder. Qed.\n  \nTheorem himp_ex_conc : forall p T (p1 : T -> _),\n  (exists v, p ==> p1 v)\n  -> p ==> hprop_ex p1. \nProof. red.\n  intros. destruct H. \n  generalize (H _ H0); clear H H0. simp_heap. eauto 7 with Ynot.\nQed.\n\nTheorem himp_pure2 (P Q : Prop) : [P] * [Q] <==> [P /\\ Q].\nProof. reduce. simp_heap. split; simp_heap. red in Hrl, Hrr. subst.\n  red. intuition. subst. myauto. myauto. auto. destruct H. do 2 econstructor. intuition.\nQed.\n  \nDefinition hprop_all {A} (p : A -> hprop) : hprop := \n  fun h => forall x : A, p x h.\n\nNotation \"'Forall' v :@ T , p\" := (hprop_all (fun v : T => p)) (at level 90, T at next level) : hprop_scope.\nLemma hprop_all_conc {A} (P : A -> hprop) p : (forall x : A, p ==> P x) -> p ==> Forall x :@ A, P x.\nProof. intros. red. intros. intro. apply (H x). apply H0. Qed.\n\nSection Make.\n  Context {A : Set}.\n\n  Definition valid_array a start len points_to :=\n    iter_sep (fun i => p :~~ array_plus a i in points_to p i) start len.\n\n  Definition points_f (f : nat -> A) := \n    fun p i => p --> f i.\n\n  Definition rep_array a n (f : nat -> A) :=\n    [array_length a = n] *  \n    valid_array a 0 n (points_f f).\n  \n  Section Init.\n    Variable init : nat -> A.\n  \n    Definition initialize_pre(f:array)(n:nat) := \n      valid_array f (array_length f - n) n (fun p _ => ptsto_any_tot p).\n    \n    Definition initialize_post(f:array)(n:nat)(_:unit) := \n      valid_array f (array_length f - n) n (points_f init).\n    \n    Definition initialize_array_spec (f:array)(n:nat) := (n <= array_length f)%nat -> \n      STsep (initialize_pre f n) (initialize_post f n).\n  \n    Definition initialize_array_aux (a : array) (n : nat) : initialize_array_spec a n.\n    Proof. revert n.\n      refine(fix make(n:nat) : initialize_array_spec a n :=\n        IfZero n\n        Then fun _ => {{Return tt}}\n        Else fun _ => \n          upd_array a (array_length a - S n) (init (array_length a - S n)) <@> (initialize_pre a n) ;;\n          {{make n _ <@> _}}); clear make;\n      unfold initialize_post, initialize_pre, initialize_array_spec, ptsto_any_tot, valid_array, points_f,\n        ptsto_any; t;\n        assert(Hi : (S (array_length a - S n0) = array_length a - n0)%nat) by omega; try rewrite Hi; t.\n    Defined.\n  \n    Definition initialize_array (a : array) :\n      STsep (valid_array a 0 (array_length a) (fun p i => ptsto_any_tot p))\n      (fun (_ : unit) => rep_array a (array_length a) init).\n    Proof. intros. unfold rep_array.\n      refine {{@initialize_array_aux a (array_length a) (le_n (array_length a))}}; \n        unfold initialize_pre, initialize_post, points_f; rewrite minus_diag; t.\n    Qed.\n\n    Definition make_array : forall (n : nat), STsep emp\n      (fun a : array => rep_array a n init).\n    Proof. \n      refine (fun n => \n        a <- new_array n <@> _;\n        @initialize_array a <@> ([array_length a = n]) ;;\n        {{Return a}}); t.\n    Qed.\n  End Init.\n\n  Definition get_array (n : nat) (a : array)\n    (f : [nat -> A]) : (n < array_length a)%nat ->\n    STsep (f ~~ rep_array a (array_length a) f)\n    (fun r : A => f ~~ rep_array a (array_length a) f * [r = f n]).\n  Proof.\n    intros. \n    refine (x <- sub_array a n (fun v => f ~~ [v = f n]) \n      <@> (f ~~ valid_array a 0 n (fun p i => p --> f i) * valid_array a (S n) (array_length a - n - 1) (fun p i => p --> f i)) ;\n      {{Return x}}).\n    unfold rep_array, valid_array. t.\n    rewrite hstar_assoc. setoid_rewrite hstar_comm at 2.\n    rewrite (split_index_sep _ 0 H). t. \n    t. t. t.\n\n    unfold rep_array. t.\n    rewrite hstar_assoc. setoid_rewrite hstar_comm at 2.\n    unfold valid_array.\n    assert (x1 --> x2 n <==> hprop_unpack (array_plus a n) (fun p => p --> x2 n)). \n    rewrite H0. rewrite <- hiff_unpack. reflexivity.\n    rewrite H1.\n    rewrite join_index_sep; auto.\n  Qed.\n\n  Lemma model_array_split_at (a : array) (f : nat -> A) (i : nat) : (i < array_length a)%nat ->\n    forall p : ptr, array_plus a i = [p]%inhabited ->\n      rep_array a (array_length a) f ==> \n    (valid_array a 0 i (points_f f) *\n      points_f f p i * \n      valid_array a (S i) (array_length a - i - 1) (points_f f))%hprop.\n  Proof.\n    intros. unfold rep_array, valid_array, points_f. \n    rewrite (split_index_sep (fun i =>\n      hprop_unpack (array_plus a i) (fun p0 : ptr => p0 --> f i)) 0 H). t.\n  Qed.\n\n  Definition upd_model (f : nat -> A) (n : nat) (v : A) := \n    fun i => if eq_nat_dec i n then v else f i.\n\n  Lemma valid_array_update a start len f n v : \n    (n < start \\/ len + start <= n)%nat ->\n    valid_array a start len (points_f f) ==>\n    valid_array a start len (points_f (upd_model f n v)).\n  Proof. intros.\n    unfold valid_array. apply iter_imp. intros.\n    dest_unpack (array_plus a i). \n    unfold upd_model, points_f.\n    case_eq (eq_nat_dec i n). intros. subst.\n    destruct H; elimtype False; omega. myauto.\n  Qed.\n\n  Definition set_array (a : array) (n : nat) (v : A) (f : [nat -> A]) : (n < array_length a)%nat ->\n    STsep (f ~~ rep_array a (array_length a) f)\n    (fun _ : unit => f ~~ rep_array a (array_length a) (upd_model f n v)).\n  Proof. intros.\n    refine {{upd_array a n v <@> (f ~~\n      valid_array a 0 n (points_f f) * valid_array a (S n) (array_length a - n - 1) \n      (points_f f))%hprop}}.\n    unfold rep_array; t.\n    setoid_rewrite hstar_comm at 1.\n    setoid_rewrite <- hstar_assoc.\n    setoid_rewrite hstar_comm at 2.\n    setoid_rewrite hstar_assoc.\n    Existential 1 := A. Existential 1 := (x n). instantiate. \n    change (x0 --> x n) with (points_f x x0 n).\n    rewrite <- model_array_split_at; auto. unfold rep_array. t.\n\n    t. rewrite <- hstar_assoc. setoid_rewrite hstar_comm at 2. rewrite hstar_assoc.\n        \n    unfold rep_array.\n    dest_unpack (array_plus a n).\n    rewrite (@valid_array_update a 0 n x n v); try omega.\n    rewrite (@valid_array_update a (S n) (array_length a - n - 1) x n v); try omega.\n    change (p --> v) with ((fun p => p --> v) p).\n    rewrite (hiff_unpack p). rewrite <- H0.\n    assert (hprop_unpack (array_plus a n) (fun p => p --> v) <==> (p :~~ array_plus a n in points_f (upd_model x n v) p n))%hprop.\n    unfold points_f, upd_model. dest_unpack (array_plus a n). \n    case_eq (eq_nat_dec n n); intros; subst. reflexivity. intuition.\n    rewrite H1. clear H0 H1.\n    t. apply join_index_sep. auto.\n  Qed.\n\n  Lemma valid_array_model a start len f : valid_array a start len (points_f f) <==> \n    {@ p :~~ array_plus a i in p --> f i | i <- start + len}.\n  Proof. unfold valid_array. reflexivity. Qed.\n\nEnd Make.\n\nSection Fin.\n\n  Definition fin size := sig (fun n : nat => n < size).\n  \n  Definition fin_eq {size} (x y : fin size) := proj1_sig x = proj1_sig y.\n  Definition fin_neq {size} (x y : fin size) := not (fin_eq x y).\n  \n  Definition eq_fin_dec {n} (x y : fin n) : { x = y } + { x <> y }.\n  Proof. intros. destruct x; destruct y. \n    case (eq_nat_dec x x0). intros. subst. left. \n    f_equal.\n    apply proof_irrelevance.\n    intros. right.\n    intro. apply n0. injection H. auto.\n  Defined.\n\n  Definition build_fin {size} (i : nat) : option (fin size) :=\n    match lt_dec i size with\n      | left prf => Some (exist _ i prf)\n      | right _ => None\n    end.\n\nEnd Fin.\n\nDefinition upd_model_fin {A : Set} {size} (f : fin size -> A) (n : fin size) (v : A) := \n  fun i => if eq_fin_dec i n then v else f i.\n\nSection ArrayFin.\n  Context {A : Set}.\n  \n  Definition repr_fn {size} a (points_to : fin size -> A) :=\n    iter_sep (fun i => p :~~ array_plus a i in \n      Exists prf :@ i < size,\n      p --> points_to (exist (fun i => i < size) i prf)) 0 size.\n\n  Definition repr_array {size} a (f : fin size -> A) :=\n    ([array_length a = size] * repr_fn a f)%hprop.\n\n  Definition make_array_fin (n : nat) (f : fin n -> A) : STsep emp \n    (fun a => repr_array a f)%hprop.\n  Proof. destruct n. \n    refine {{new_array 0}}; t.\n    assert(prf : 0 < S n) by omega.\n    refine {{make_array (fun i : nat => match build_fin i return A with\n                                    | Some prf => f prf \n                                    | None => f (exist _ 0 prf)\n                                  end) (S n)}}.\n    t. t. unfold repr_array, repr_fn, rep_array, valid_array.\n    apply himp_split. t. apply iter_imp. intros.\n    dest_unpack (array_plus v i). apply himp_ex_conc. \n    assert(Hi:i < S n) by omega. exists Hi. unfold points_f.\n    unfold build_fin. destruct lt_dec. t. f_equal. f_equal. apply proof_irrelevance.\n    contradiction.\n  Qed.\n\n  Lemma upd_model_refl {size} f (i : fin size) : f i = i ->\n    Morphisms.pointwise_relation (fin size) eq (upd_model_fin f i i) f.\n  Proof. intros. red; intros. unfold upd_model_fin. case eq_fin_dec; myauto. Qed.\n  \n  Context {size : nat}.\n\n  Definition get_array_fin (a : array) (n : fin size)\n    (f : [fin size -> A]) : array_length a = size ->\n    STsep (f ~~ repr_array a f)\n    (fun r : A => f ~~ repr_array a f * [r = f n])%hprop.\n  Proof.\n    destruct size. depelim n. exfalso; inversion l.\n    destruct n. intros. assert(x < array_length a) by omega.\n    assert(0 < S n0) by omega.\n    refine (x <- get_array x a \n      (f ~~~ fun i => match build_fin i return A with\n                       | Some prf => f prf \n                       | None => f (exist _ 0 H1) end)\n      H0 <@> [array_length a = S n0] ;\n    {{Return x}}); t.\n\n    unfold repr_array, repr_fn, rep_array. \n    unfold valid_array. apply himp_split. t. rewrite H. apply iter_imp. intros.\n    unfold points_f, build_fin. t.\n    case lt_dec. intros. f_equal. f_equal. apply proof_irrelevance.\n    myauto.\n    unfold repr_array, repr_fn, rep_array.\n    setoid_rewrite <- hstar_assoc. \n    apply himp_split; [t|].\n    setoid_rewrite hstar_comm. \n    unfold valid_array. apply himp_inj_conc. \n    unfold build_fin. case lt_dec.\n    intros. f_equal. f_equal. apply proof_irrelevance.\n    myauto.\n\n    rewrite H.\n    apply iter_imp. intros.\n    dest_unpack (array_plus a i).\n    unfold points_f, build_fin.\n    case lt_dec. intros. t.\n    intros. elimtype False; omega.\n  Qed.\n\n  Definition set_array_fin (a : array) (n : fin size) (v : A)\n    (f : [fin size -> A]) : array_length a = size ->\n    STsep (f ~~ repr_array a f)\n    (fun r : unit => f ~~ repr_array a (upd_model_fin f n v))%hprop.\n  Proof. destruct n. destruct size. exfalso; depelim l.\n    intro Hlen. assert(x < array_length a) by omega.\n    assert(Hs:0 < S n) by omega.\n    refine (x <- set_array a x v\n      (f ~~~ fun i => match build_fin i return A with\n                       | Some prf => f prf \n                       | None => f (exist _ 0 Hs) end)\n      H <@> [array_length a = S n] ;\n    {{Return x}}); unfold repr_array; t. \n\n    unfold repr_fn, rep_array. apply himp_inj_conc. auto.\n    unfold valid_array. rewrite Hlen.\n\n    apply iter_imp. intros.\n    dest_unpack (array_plus a i).\n    unfold points_f. unfold build_fin. t.\n    case lt_dec. intros. do 2 f_equal. apply proof_irrelevance.\n    intros. elimtype False; omega.\n    \n    unfold rep_array. t. unfold valid_array, repr_fn.\n    rewrite <- H0 at 1.\n    apply iter_imp. intros.\n    dest_unpack (array_plus a i).\n    unfold points_f, build_fin. apply himp_ex_conc.\n    assert(His:i < S n) by omega. exists His.\n    t.\n    unfold upd_model, upd_model_fin.\n    unfold eq_fin_dec. simpl. case eq_nat_dec.\n    intros. subst x. unfold eq_rec_r, eq_rec, eq_rect, eq_sym. reflexivity.\n    intros.\n    case lt_dec. intros. do 2 f_equal. apply proof_irrelevance.\n    intros. elimtype False; omega.\n  Qed.\n\nEnd ArrayFin.\n\nModule Type ArrayF.\n\n  Parameter t : Set -> nat -> Set.\n\n  Parameter repr : forall {A size}, t A size -> (fin size -> A) -> hprop.\n  \n  Parameter create : Π {A : Set} (size : nat) (f : fin size -> A), STsep emp (fun x : t A size => repr x f).\n\n  Parameter get : Π {A : Set} {size : nat} (a : t A size) (f : [fin size -> A]) (n : fin size),\n    STsep (f ~~ repr a f) (fun x : A => f ~~ repr a f * [x = f n]).\n\n  Parameter set : Π {A : Set} {size : nat} (a : t A size) \n    (f : [fin size -> A]) (n : fin size) (v : A),\n    STsep (f ~~ repr a f) (fun _ : unit => f ~~ repr a (upd_model_fin f n v)).\n\nEnd ArrayF.\n\nAxiom get_prf : Π {P : Prop} {p}, STsep ([P] * p) (fun _ : P => [P] * p).\n\n(** It is safe as the variable is irrelevant, right?\n   Otherwise you lose the ability to hide model updates.\n *)\n\nAxiom get_irr : Π (T : Set) (p : T -> hprop),\n  STsep (@hprop_ex T p) (fun x : [T] => x ~~ p x).\n\nModule Array_fin <: ArrayF.\n\n  Definition t (A : Set) (n : nat) := sig (fun a : array => array_length a = n).\n\n  Definition repr {A size} (a : t A size) (f : fin size -> A) :=\n    let (a, p) := a in\n      repr_array a f.\n\n  Definition create {A : Set} {size} (f : fin size -> A) :\n    STsep emp (fun x : t A size => repr x f).\n  Proof. refine (x <- make_array_fin size f;\n    prf <- get_prf ;\n    {{Return (exist _ x prf)}}); \n    unfold repr_array; t.\n    unfold repr_array; t.\n  Qed.\n\n  Definition get {A : Set} {size : nat} (a : t A size) (f : [fin size -> A]) (n : fin size) :\n    STsep (f ~~ repr a f) (fun x : A => f ~~ repr a f * [x = f n]) :=\n    let 'exist a p := a in get_array_fin a n f p.\n\n  Definition set {A : Set} {size : nat} (a : t A size) \n    (f : [fin size -> A]) (n : fin size) (v : A) :\n    STsep (f ~~ repr a f) (fun _ : unit => f ~~ repr a (upd_model_fin f n v)) :=\n    let 'exist a p := a in set_array_fin a n v f p.\n\nEnd Array_fin.\n\nModule Array : ArrayF := Array_fin.\n\nSection UnionFind.\n\n  Definition partition size := fin size -> fin size.\n\n  Definition partition_eq {size} (p q : partition size) : Prop :=\n    forall i j : fin size, p i = p j <-> q i = q j.\n  \n  Instance: Reflexive (@partition_eq size).\n  Proof. intros size p i j. reflexivity. Qed.\n    \n  Instance: Symmetric (@partition_eq size).\n  Proof. intros size p p' H i j. red in H. rewrite H. reflexivity. Qed.\n    \n  Instance: Transitive (@partition_eq size).\n  Proof. intros size p p' p'' H H' i j. red in H, H'. etransitivity; eauto. Qed.\n\n  Definition representation size := fin size -> fin size.\n\n  Record uf {size} : Set := {\n    parent : Array.t (fin size) size;\n    rank : Array.t nat size\n  }.\n\n  Definition t (size : nat) := @uf size. \n\n  Open Local Scope nat_scope.\n\n  Inductive repr {size} (p : partition size) : fin size -> fin size -> Prop :=\n    repr_zero : forall i, p i = i -> repr p i i\n  | repr_succ : forall i j, p i = j -> i <> j ->\n    forall r, repr p j r -> repr p i r.\n  \n  Hint Constructors repr : repr.\n\n  Definition models_partition {size} (f : representation size) (p : partition size) :=\n    forall x, repr f x (p x).\n\n  Definition repr_partition {size} (a : Array.t (fin size) size) (f : representation size) (p : partition size) :=\n    (Array.repr a f * [models_partition f p])%hprop.\n\n  Notation \"'Exists' v :@ T , p\" := (hprop_ex (fun v : T => p%hprop)) (at level 90, T at next level) : hprop_scope.\n\n  Definition repr_uf {size} uf (p : partition size) :=\n    Exists pmodel :@ representation size,\n    Exists rmodel :@ fin size -> nat,\n      repr_partition uf.(parent) pmodel p * \n      Array.repr uf.(rank) rmodel.\n\n  Definition repr_t {size} (x : t size) (p : partition size) : hprop :=\n    repr_uf x p.\n\n  Hint Extern 4 => intro : dest.\n  Ltac myauto ::= \n    autounfold with repr dest in *; intros;\n    simplify_goal; try typeclasses eauto with repr dest.\n\n  Typeclasses eauto :=.\n\n  Hint Extern 4 (exists _ : _, _) => econstructor : dest.\n  Hint Constructors and or : dest.\n  Hint Extern 0 (_ = _) => reflexivity : dest.\n  Hint Extern 0 (_ <-> _) => reflexivity : dest.\n  Hint Extern 0 (_ ==> _) => reflexivity : dest.\n  Hint Extern 0 (_ <==> _) => reflexivity : dest.\n  Lemma empty_split : empty ~> empty * empty.\n  Proof. t. Qed.\n  Hint Resolve empty_split : dest.\n\n  Hint Unfold hprop_inj : dest.\n\n  Hint Constructors repr : Ynot.\n  Set Firstorder Solver auto.\n\n  Definition make {size} : STsep __ (fun x : t size => repr_t x (fun i : fin size => i))%hprop.\n  Proof. intros. refine (\n    parents <- Array.create size (fun i => i) ;\n    ranks <- Array.create size (fun i => 0%nat) <@> (Array.repr parents (fun i => i)) ;    \n    {{Return {| parent := parents; rank := ranks |}}});\n      unfold ptsto_any_tot, ptsto_any; t.\n\n    unfold repr_t, repr_uf, repr_partition. t. \n    apply himp_pure'. intro. constructor; auto.\n  Qed.\n\n  Definition repr_eq {size} (f g : partition size) :=\n    forall n : fin size, forall c, repr f n c <-> repr g n c.\n\n  Instance repr_equiv size : Equivalence (@repr_eq size).\n  Proof. constructor; reduce. \n    \n    reflexivity. \n    \n    symmetry. red in H. auto. \n    \n    red in H, H0. rewrite H; auto.\n  Qed.\n\n  Context {size : nat}.\n\n(* unfold model_partition, model_array, models_partition. t. *)\n  \n  Lemma repr_inj {x n c} : repr (size:=size) x n c -> forall {c'}, repr x n c' -> c = c'.\n  Proof. induction 1; intros. depelim H0. myauto.\n    rewrite H0 in H. myauto.\n\n    depelim H2. rewrite H2 in H. myauto.\n    rewrite H2 in H. myauto.\n  Qed.\n\n  Hint Unfold models_partition : repr.\n\n  Lemma models_partition_repr {f p : partition size} : models_partition f p -> \n    forall i : fin size, repr f i (p i).\n  Proof. myauto. Qed.\n  Hint Resolve @models_partition_repr : repr.\n\n  Lemma models_partition_f (f p : partition size) :\n    models_partition f p -> forall i : fin size, p i = p (f i).\n  Proof. \n    intros. pose (models_partition_repr H i).\n    apply (repr_inj r).\n    case (eq_fin_dec i (f i)). intros. rewrite e at 1. apply H. \n    intros. econstructor 2 with (f i); myauto. \n  Qed.\n  Hint Resolve @models_partition_f : repr.\n\n  Lemma repr_f_fi_not_i (f : partition size) (i : fin size) : \n    forall v, repr f i v -> repr f (f i) v.\n  Proof. intros. induction H.\n\n    rewrite H; myauto. myauto.\n  Qed.\n\n  Lemma repr_f_fi {f : representation size} {p : partition size} {i : fin size} : models_partition f p ->\n    forall {v}, repr f (f i) v -> repr f i v.\n  Proof. intros rfp v rfv. depind rfv.\n    case (eq_fin_dec (f i) i) ; intros; auto.\n    rewrite e. myauto. \n    econstructor 2 with (f i); myauto. \n    econstructor 2 with (f i); myauto.\n  Qed. \n\n  Lemma repr_f_fi_eq {f : representation size} {i : fin size} : \n    forall {v}, repr f i v -> f v = v.\n  Proof. intros. induction H. auto.\n    subst j. auto.\n  Qed.\n\n  Ltac inst H :=\n    match type of H with\n      ?X -> _ => let H' := fresh in assert (H':X) by typeclasses eauto with repr; specialize (H H')\n    end.\n\n  Lemma repr_f_fi_eq' {f : representation size} {p : partition size} {i : fin size} : \n    models_partition f p ->\n    repr f (f i) i -> f i = i.\n  Proof. intros rfp rfi. \n    apply (repr_f_fi rfp) in rfi. depind rfi. auto.\n    generalize (models_partition_repr rfp (f i)). intros.\n    assert (Hi:=repr_inj rfi H). \n    pose (repr_f_fi_eq H). rewrite <- Hi in e. myauto.\n  Qed.\n\n  Lemma models_partition_f' {f : representation size} {p : partition size} : \n    models_partition f p -> forall {i : fin size}, f (p i) = p i.\n  Proof.\n    intros.\n    red in H. apply (repr_f_fi_eq (i:=i)). myauto. \n  Qed.\n\n  Infix \"===>\" := Morphisms.respectful (at level 90, right associativity).\n\n  Class Have (P : Prop) := have : P.\n  Hint Extern 0 (Have _) => unfold Have; auto with repr : typeclass_instances.\n\n  Definition subset_eq {A} (R : relation A) (P : A -> Prop) : relation A :=\n    fun x y => R x y /\\ P x /\\ P y.\n\n  Instance subset_proper {A} (R : relation A) `(Reflexive A R) (P : A -> Prop) (x : A) (p : Have (P x)) : \n    Morphisms.Proper (subset_eq R P) x.\n  Proof. reduce. intuition. Qed.\n\n  Instance subset_proper_proxy {A} (R : relation A) `(Reflexive A R) (P : A -> Prop) (x : A) (p : Have (P x)) : \n    Morphisms.ProperProxy (subset_eq R P) x.\n  Proof. reduce. intuition. Qed.\n\n  Instance: Morphisms.Proper (repr_eq ===> eq ===> eq ===> iff) (@repr size).\n  Proof. reduce. red in H. subst. apply H. Qed.\n  \n  Instance: Morphisms.Proper (repr_eq ===> \n    Morphisms.pointwise_relation (fin size) eq ===> iff) models_partition.\n  Proof. reduce. red in H. unfold models_partition.\n    split; intros. rewrite <- H0.\n    now rewrite <- H. \n\n    rewrite H0. now rewrite H.\n  Qed.\n\n  Instance: RelationClasses.subrelation (Morphisms.pointwise_relation (fin size) eq) repr_eq.\n  Proof. intros f g Hfg x y. \n    split. intros rf. induction rf. setoid_rewrite Hfg in H. constructor; auto.\n    setoid_rewrite Hfg in H. constructor 2 with (g i) ; subst j; auto. \n\n    induction 1. setoid_rewrite <- Hfg in H. constructor; auto.\n    setoid_rewrite <- Hfg in H. constructor 2 with (f i) ; subst j; auto.\n  Qed. \n\n  Require Import Logic.FunctionalExtensionality.\n  Lemma repr_model_refl f (i : fin size) : f i = i -> upd_model_fin f i i = f.\n  Proof. intros. extensionality a. apply upd_model_refl; auto. Qed.\n\n  Lemma repr_f_refl {f p} {i : fin size} : models_partition f p -> (f i = i <-> p i = i).\n  Proof. intros rfp. split; intros H. \n    assert (H':=models_partition_repr rfp i). depelim H'; myauto.\n    \n    assert (H':=models_partition_repr rfp i). depelim H'; myauto. \n    rewrite <- H. apply models_partition_f'; auto.\n  Qed.\n\n  Lemma repr_f_refl_left {f p} : models_partition f p -> forall {i : fin size}, f i = i -> p i = i.\n  Proof. intros. now rewrite <- (repr_f_refl H). Qed.\n\n  Lemma repr_f_refl_right {f p} : models_partition f p -> forall {i : fin size}, p i = i -> f i = i.\n  Proof. intros. now rewrite (repr_f_refl H). Qed.\n\n  Lemma repr_eq_refl (i : fin size) x y : repr_eq x y -> x i = i -> y i = i.\n  Proof. intros rxy xi. red in rxy. apply repr_zero in xi.\n    rewrite rxy in xi. eapply repr_f_fi_eq; myauto. \n  Qed.\n  \n  Lemma repr_eq_succ {x y p} {i c : fin size} : models_partition x p -> repr_eq x y -> \n    repr x i c -> repr y i c.\n  Proof. intros rfp rxy H. rewrite <- rxy. assumption. Qed.\n\n  Lemma repr_canon {f} {i : fin size} {c p} : models_partition f p -> (repr f i c <-> p i = c).\n  Proof. intros rfp. split; intros H. \n    apply (repr_inj (models_partition_repr rfp i) H). \n    pose (H':=models_partition_repr rfp i).\n    now rewrite H in H'.\n  Qed.\n\n  Lemma repr_canon_right {x} {i : fin size} {c p} : models_partition x p -> repr x i c -> p i = c.\n  Proof. intros. rewrite <- @repr_canon; eauto. Qed.\n\n  Lemma repr_f_invol {f p} {i : fin size} : models_partition f p ->\n    f i = i -> repr f i (f i).\n  Proof. intros rfp fii. rewrite <- fii at 1. eapply repr_f_fi_not_i. rewrite fii. myauto. Qed.\n\n  Hint Resolve @repr_f_fi_not_i : repr.\n  Hint Resolve @repr_canon_right : repr.\n\n  Lemma repr_elim {f p} (H : models_partition f p) \n    (P : forall n i, Prop)\n    (Pzero : forall i : fin size, f i = i -> i = p i -> P i (p i))\n    (Psucc : forall i : fin size, f i <> i -> i <> p i -> P (f i) (p i) -> P i (p i)) : \n    forall i c, repr f i c -> P i c.\n  Proof.\n    intros i c rf. assert (ri:=repr_inj (models_partition_repr H i) rf).\n    rewrite <- ri in rf |- *. clear ri c.\n    depind rf.\n    apply Pzero; auto.\n    apply Psucc; auto.\n    pose (repr_f_refl (i:=i) H). destruct i0.\n    intro. symmetry in H3. intuition.\n    specialize (IHrf p H P Pzero Psucc).\n    assert(Hpi:p i = p (f i)). apply models_partition_f; auto.\n    specialize (IHrf Hpi).\n    rewrite <- Hpi in IHrf.\n    auto.\n  Qed.\n\n  Lemma models_partition_invol {f} {p : partition size} : models_partition f p -> forall {i}, p (p i) = p i.\n  Proof. intros rfp i.\n    assert (ri:=models_partition_repr rfp i). depind ri.\n    rewrite <- x. auto.\n    specialize (IHri p rfp).\n    assert(Hpi:p i = p (f i)). apply models_partition_f; auto.\n    specialize (IHri Hpi). rewrite <- Hpi in IHri. auto.\n  Qed.\n\n  Ltac upd_model_simpl :=\n    unfold upd_model_fin; case eq_fin_dec; auto; intros; try discriminates; try contradictions.\n  Hint Resolve @models_partition_f' : repr.\n\n  Lemma models_partition_upd {f : representation size} {p : partition size} {n v} : \n    models_partition f p -> n <> f n -> repr f (f n) v -> models_partition (upd_model_fin f n v) p.\n  Proof.\n    intros fp nfn rfv. intro.\n    eapply repr_f_fi in rfv; eauto.\n    assert (hi:=repr_inj rfv (models_partition_repr fp n)). subst v.\n    assert (r:=models_partition_repr fp x). remember (p x) as px. revert Heqpx.\n    elim r using (repr_elim fp); auto with repr. \n\n    intros i fii ipi _.\n    rewrite <- ipi. constructor; auto. \n    upd_model_simpl.\n\n    intros i fii ipi H _.\n    assert (Hpi:p i = p (f i)). auto with repr. specialize (H Hpi).\n    case (eq_fin_dec i n). intros <-. \n    econstructor 2 with (p i); auto. upd_model_simpl.\n    constructor; auto. upd_model_simpl. auto with repr. \n\n    intros.\n    econstructor 2 with (f i); auto.\n    upd_model_simpl. myauto.\n  Qed.\n\n  Lemma repr_upd_model (f : representation size) (p : partition size) (n v : fin size) : \n    models_partition f p -> \n    n <> f n ->\n    repr f (f n) v -> \n    repr_eq f (upd_model_fin f n v).\n  Proof. intros rfp nfn rfv. red; intros x c. \n    assert (rx':=models_partition_upd rfp nfn rfv x).\n    split; intro H.\n    assert(Hcp:=repr_inj (c':=c) (models_partition_repr rfp x) H). subst c. apply rx'.\n\n    assert(Hcp:=repr_inj rx' H). subst c. auto with repr.\n  Qed.\n\n  Hint Resolve @models_partition_upd repr_upd_model : repr.\n\n  Definition cast A (a : A) : A := a.\n\n  Notation array := (Array.t (fin size) size).\n\n  Definition find_post (a : array) (i : fin size) (f : fin size -> fin size) (p : partition size) (c : fin size) :=\n    (repr_partition a f p * [p i = c])%hprop.\n\n  Definition dest_pair {A B C : Type} (p : A * B) (cont : forall (a : A) (b : B), p = (a, b) -> C) : C.\n  Proof. destruct p. eapply cont; auto. Defined.\n\n  \n  Definition find_aux (a : array) (i : fin size) (f : [representation size]) (p : [partition size]) : \n    STsep (f ~~ p ~~ repr_partition a f p) \n    (fun (res : fin size * [partition size]) => let (c, g) := res in\n      f ~~ p ~~ g ~~ repr_partition a g p * [p i = c] * [repr_eq f g])%hprop.\n  Proof. revert i f. \n    refine (Fix2\n      (fun i f => f ~~ p ~~ repr_partition a f p)\n      (fun i f (res : fin size * [partition size]) =>\n        let (c, g) := res in f ~~ p ~~ g ~~ repr_partition a g p * [p i = c] * [repr_eq f g])%hprop\n      (fun self i (f : [representation size]) =>\n        pi <- Array.get a f i\n        <@> (f ~~ p ~~ [models_partition f p]) ;\n        if eq_fin_dec pi i then {{Return (i, f)}}\n        else \n          res <- self pi f <@> (f ~~ p ~~ [f i = pi /\\ pi <> i])%hprop ;\n          let '(ci, g) := res in\n            Array.set a g i ci <@> (f ~~ p ~~ g ~~ \n              [f i = pi /\\ pi <> i /\\ \n                repr f pi ci /\\ models_partition f p /\\ repr_eq f g])%hprop ;;\n            {{Return (ci, (g ~~~ upd_model_fin g i ci))}}\n          ));\n    unfold find_post, repr_partition, models_partition; clear self; t. t.\n    subst b.\n    apply pair_equal in H0. destruct H0. subst a0.\n    pack_injections. subst x1. t. apply himp_pure'.\n    eauto with repr.\n\n    apply himp_pure'. intuition auto. rewrite H0 at 1. apply H.\n    rewrite H0. apply H.\n\n    rename H3 into Hrepr. rename H5 into req. rename H2 into rci.\n    apply pair_equal in H. destruct H; subst a1 b0.\n    rewrite <- ! hiff_unpack. t. rewrite ! himp_pure2. apply himp_pure'.\n    rewrite req at 1.\n    change (models_partition x0 x1) in Hrepr.\n\n    assert(x i <> i).\n    intro.\n    apply (repr_eq_refl i _ _ (symmetry req)) in H. congruence.\n    assert(repr x (x i) ci).\n    eapply repr_f_fi_not_i. rewrite <- req. eauto with repr.\n\n    intuition auto with repr.\n\n    rewrite req in Hrepr.\n    intuition auto with repr.\n    eapply repr_canon_right; eauto with repr.\n    rewrite req in Hrepr.\n    eapply repr_upd_model; eauto.\n  Qed.\n\n  Notation \"inh ~~ p\" := (hprop_unpack inh (fun inh => p%hprop)) (at level 91, right associativity) : hprop_scope.\n\n  Axiom get_irr' : Π (T : Set) (p : T -> hprop),\n  STsep (Exists x :@ T, p x) (fun x : [T] => x ~~ p x).\n\n  Definition find (x : @t size) (p : [partition size]) (i : fin size) : \n    STsep (p ~~ repr_t x p) \n    (fun c : fin size => p ~~ repr_t x p * [p i = c]).\n  Proof. unfold repr_t, repr_uf.\n    refine \n      (pmodel <- get_irr' (representation size) _ ;\n       rmodel <- get_irr' (fin size -> nat) _ ;\n       x <- find_aux x.(parent) i pmodel p <@> (rmodel ~~ Array.repr x.(rank) rmodel) ;\n       {{Return (fst x)}}); try solve [t]. intuition t.\n  Qed.\n\n  (* Definition find (a : array) (i : fin size) (f : [representation size]) (p : [partition size]) :  *)\n  (*   STsep (f ~~ p ~~ repr_partition a f p)  *)\n  (*   (fun res : (fin size * [representation size]), *)\n  (*     let (c, g) := res in *)\n  (*     (p ~~ g ~~ f ~~ repr_partition a g p * [p i = c /\\ repr_eq f g]))%hprop. *)\n  (* Proof. intros. refine ({{find_aux a i f p}}); t. t. Qed. *)\n    \n  Definition partition_union (p : partition size) (i j : fin size) (r : fin size) : partition size :=\n    fun x => \n      if eq_fin_dec (p x) (p i) then r\n      else if eq_fin_dec (p x) (p j) then r\n      else p x.\n \n  Lemma models_partition_union {f p} (i j : fin size) : models_partition f p -> p i <> p j ->\n    models_partition (upd_model_fin f (p j) (p i)) (partition_union p i j (p i)).\n  Proof.\n    intros. red in H. intro. \n    generalize (H x). intros Hx.\n    unfold upd_model_fin. unfold partition_union.\n    depind Hx.\n    case eq_fin_dec. intros. \n    case (eq_fin_dec i0 (p j)); intros. subst i0.\n    rewrite <- e in H0. contradictions. rewrite <- e. \n    rewrite x at 1. constructor. case eq_fin_dec; auto. intros.\n    auto with repr.\n    \n    intros. case eq_fin_dec. intros. rewrite <- x in e. subst i0.\n    econstructor 2 with (p i); auto. case eq_fin_dec; auto.\n    intros. discriminates. \n    constructor; auto. case eq_fin_dec. auto. intros. \n    auto with repr.\n    \n    intros. rewrite <- x. constructor. case eq_fin_dec; auto. intros.\n    rewrite x in e. congruence.\n    specialize (IHHx p i j H H0). \n    assert(p i0 = p (f i0)). auto with repr. specialize (IHHx H1).\n    rewrite <- H1 in IHHx.\n    case eq_fin_dec. intros. \n    econstructor 2 with (f i0). case eq_fin_dec. intros. subst i0.\n    rewrite <- e. rewrite (models_partition_invol H). symmetry. auto with repr.\n    intros. auto. auto.\n    \n    generalize IHHx. case eq_fin_dec. intros. auto. intros. contradictions.\n    \n    intros. revert IHHx.\n    case eq_fin_dec. intros. contradictions.\n    intros. revert IHHx. case eq_fin_dec. intros. \n    econstructor 2 with (f i0); auto. case eq_fin_dec; auto. intros.\n    subst i0. \n    elim H2. symmetry. auto with repr.\n    \n    intros.\n    econstructor 2 with (f i0); auto. \n    case eq_fin_dec. intros. subst i0. \n    elim n1. rewrite (models_partition_invol H). auto.\n    intros.\n    auto.\n  Qed.\n\n  Require Import Compare_dec.\n\n  Lemma partition_union_sym (p : partition size) (i j : fin size) (c : fin size) : \n    Morphisms.pointwise_relation (fin size) eq (partition_union p i j c) (partition_union p j i c).\n  Proof.\n    unfold partition_union. intro. repeat case eq_fin_dec; intros; congruence.\n  Qed.\n\n  Lemma partition_union_idem (p : partition size) (i j : fin size) : p i = p j ->\n    Morphisms.pointwise_relation (fin size) eq p (partition_union p i j (p i)).\n  Proof. \n    unfold partition_union. intros H x. repeat case eq_fin_dec; intros; congruence.\n  Qed.\n\n  Lemma partition_eq_union (p : partition size) (i j : fin size) : p i = p j ->\n    partition_eq p (partition_union p i j (p i)).\n  Proof.\n    intros. unfold partition_union. red.\n    intros. repeat case eq_fin_dec; simpl_dep_elim; split; congruence.\n  Qed.\n\n  Lemma partition_eq_union_union (p : partition size) (i j : fin size) : \n    partition_eq (partition_union p i j (p j)) (partition_union p i j (p i)).\n  Proof.\n    intros. unfold partition_union. red.\n    intros. repeat case eq_fin_dec; simpl_dep_elim; split; congruence.\n  Qed.\n\n  Definition union_aux (x : @t size) (i j : fin size) (f : [representation size]) (r : [fin size -> nat])\n    (p : [partition size]) :\n    STsep (f ~~ r ~~ p ~~ repr_partition x.(parent) f p * Array.repr x.(rank) r)\n    (fun res : ([representation size * partition size * (fin size -> nat)])%type =>\n      res ~~ let 'pair (pair g p') r' := res in\n        p ~~ \n        repr_partition x.(parent) g p' * \n        Array.repr x.(rank) r' *\n        [partition_eq p' (partition_union p i j (p i))]).\n  Proof.\n    destruct x as [pars ranks]. simpl.\n    refine (cip <- find_aux pars i f p <@> (r ~~ Array.repr ranks r) ;\n      dest_pair cip (fun ci g prf =>\n      cjp <- find_aux pars j g p <@> (p ~~ r ~~ [p i = ci] * Array.repr ranks r) ;\n      dest_pair cjp (fun cj g' prf' =>\n        if eq_fin_dec ci cj then {{Return (inhabit_unpack3 g' p r (fun g' p r => (g', p, r)))}}\n        else (\n          rci <- Array.get ranks r ci <@> \n          (g' ~~ p ~~ Array.repr pars g' * [models_partition g' p /\\ p i = ci /\\ p j = cj /\\ ci <> cj]) ;\n          rcj <- Array.get ranks r cj <@> (g' ~~ p ~~ r ~~\n            Array.repr pars g' * [rci = r ci /\\ models_partition g' p /\\ p i = ci /\\ p j = cj /\\ ci <> cj]) ;\n          match nat_compare rci rcj as comp return comp = nat_compare rci rcj -> _ with\n          | Lt => fun prf =>\n            (Array.set pars g' cj ci <@> \n              (g' ~~ p ~~ r ~~\n                Array.repr ranks r * [rci = r ci /\\ rcj = r cj /\\\n                  models_partition g' p /\\ p i = ci /\\ p j = cj /\\ ci <> cj]) ;;\n            {{Return (inhabit_unpack3 g' p r (fun g' p r => \n              (upd_model_fin g' cj ci, (partition_union p i j (p i)), r)))}})\n          | Gt => fun prf =>\n            (Array.set pars g' ci cj <@>\n              (g' ~~ p ~~ r ~~\n                Array.repr ranks r * [rci = r ci /\\ rcj = r cj /\\ \n                  models_partition g' p /\\ p i = ci /\\ p j = cj /\\ ci <> cj]) ;;\n              {{Return (inhabit_unpack3 g' p r (fun g' p r =>\n                (upd_model_fin g' ci cj, (partition_union p i j (p j)), r)))}})\n          | Eq => fun prf =>\n            (Array.set ranks r ci (S rci) <@> \n              (g' ~~ p ~~ r ~~\n                Array.repr pars g' * [rci = r ci /\\ rcj = r cj /\\ \n                  models_partition g' p /\\ p i = ci /\\ p j = cj /\\ ci <> cj]) ;;\n            Array.set pars g' cj ci <@> \n              (g' ~~ p ~~ r ~~\n                Array.repr ranks (upd_model_fin r ci (S rci)) * [rci = r ci /\\ rcj = r cj /\\ \n                  models_partition g' p /\\ p i = ci /\\ p j = cj /\\ ci <> cj]) ;;\n            {{Return (inhabit_unpack3 g' p r (fun g' p r =>\n              (upd_model_fin g' cj ci, (partition_union p i j (p i)), upd_model_fin r ci (S rci))))}})\n          end eq_refl\n          )))); unfold repr_partition; t;\n    repeat match goal with \n      H : (_, _) = (_, _) |- _ => apply pair_equal in H; destruct H\n    end;\n    sep ltac:fail ltac:(auto using @partition_eq_union, @models_partition_union).\n\n    rewrite himp_pure2.\n    apply himp_pure'. split.  \n    rewrite partition_union_sym.\n    apply models_partition_union; auto.\n    apply partition_eq_union_union.\n  Qed.\n\n  Definition union (x : @t size) (p : [partition size]) (i j : fin size) : \n    STsep (p ~~ repr_t x p) \n    (fun p' : [partition size] => p' ~~ p ~~ \n      repr_t x p' * [partition_eq p' (partition_union p i j (p i))]).\n  Proof. intros. unfold repr_t. unfold repr_uf.\n    refine (pmodel <- get_irr' _ _ ;\n      rmodel <- get_irr' _ _ ;\n      x <- union_aux x i j pmodel rmodel p <@> _ ;\n      {{Return (x ~~~ let 'pair (pair p'model p') r' := x in\n        p')}}); t.\n  Qed.\n\nEnd UnionFind.\n\nModule Type UF.\n  Parameter t : nat -> Type.\n  Parameter repr : forall {size}, t size -> partition size -> hprop.\n  \n  Parameter create : Π size : nat, STsep emp (fun x : t size => repr x (fun i => i)).\n\n  Parameter union : Π {size : nat} (x : t size) (p : [partition size]) (i j : fin size),\n    STsep (p ~~ repr x p) \n      (fun p' : [partition size] => \n        p ~~ p' ~~ repr x p' * [partition_eq p' (partition_union p i j (p i))]).\n\n  Parameter find : Π {size : nat} (x : t size) (p : [partition size]) (i : fin size),\n    STsep (p ~~ repr x p) \n      (fun ci => p ~~ repr x p * [ci = p i]).\n\nEnd UF.\n  \nModule UFArray <: UF.\n\n  Definition t (n : nat) := @t n.\n\n  Definition repr {size} (uf : t size) (p : partition size) : hprop :=\n    repr_t uf p.\n  \n  Definition create : Π size : nat, STsep emp (fun x : t size => repr x (fun i => i)).\n  Proof. intros. refine make. Defined.\n\n  Definition union : Π {size : nat} (x : t size) (p : [partition size]) (i j : fin size),\n    STsep (p ~~ repr x p) \n      (fun p' : [partition size] => p ~~ p' ~~\n        repr x p' * [partition_eq p' (partition_union p i j (p i))]).\n  Proof. intros. refine {{union x p i j}}; t. Qed.\n    \n  Definition find : Π {size : nat} (x : t size) (p : [partition size]) (i : fin size),\n    STsep (p ~~ repr x p) \n      (fun ci => p ~~ repr x p * [ci = p i]).\n  Proof. intros. refine {{find x p i}}; t. Qed.\n\nEnd UFArray.\n", "meta": {"author": "Ptival", "repo": "ynot", "sha": "cd6f28816c41bbef7464b644edeba099d397a01e", "save_path": "github-repos/coq/Ptival-ynot", "path": "github-repos/coq/Ptival-ynot/ynot-cd6f28816c41bbef7464b644edeba099d397a01e/examples/Data/UnionFind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199008363969, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22575050919710907}}
{"text": "Require Import ExtLib.Structures.Monads.\nRequire Import ExtLib.Structures.Monoid.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection StateType.\n  Variable S : Type.\n\n  Record state (t : Type) : Type := mkState\n  { runState : S -> t * S }.\n\n  Definition evalState {t} (c : state t) (s : S) : t :=\n    fst (runState c s).\n\n  Definition execState {t} (c : state t) (s : S) : S :=\n    snd (runState c s).\n\n\n  Global Instance Monad_state : Monad state :=\n  { ret  := fun _ v => mkState (fun s => (v, s))\n  ; bind := fun _ _ c1 c2 =>\n    mkState (fun s =>\n      let (v,s) := runState c1 s in\n      runState (c2 v) s)\n  }.\n\n  Global Instance MonadState_state : MonadState S state :=\n  { get := mkState (fun x => (x,x))\n  ; put := fun v => mkState (fun _ => (tt, v))\n  }.\n\n  Variable m : Type -> Type.\n\n  Record stateT (t : Type) : Type := mkStateT\n  { runStateT : S -> m (t * S)%type }.\n\n  Variable M : Monad m.\n\n  Definition evalStateT {t} (c : stateT t) (s : S) : m t :=\n    bind (runStateT c s) (fun x => ret (fst x)).\n\n  Definition execStateT {t} (c : stateT t) (s : S) : m S :=\n    bind (runStateT c s) (fun x => ret (snd x)).\n\n  (** [Monad_stateT] is not a Global Instance because it can cause an infinite loop\n     in typeclass inference under certain circumstances. Use [Existing Instance\n     Monad_stateT.] to bring the instance into context. *)\n  Instance Monad_stateT : Monad stateT :=\n  { ret := fun _ x => mkStateT (fun s => @ret _ M _ (x,s))\n  ; bind := fun _ _ c1 c2 =>\n    mkStateT (fun s =>\n      @bind _ M _ _ (runStateT c1 s) (fun vs =>\n        let (v,s) := vs in\n        runStateT (c2 v) s))\n  }.\n\n  Global Instance MonadState_stateT : MonadState S stateT :=\n  { get := mkStateT (fun x => ret (x,x))\n  ; put := fun v => mkStateT (fun _ => ret (tt, v))\n  }.\n\n  Global Instance MonadT_stateT : MonadT stateT m :=\n  { lift := fun _ c => mkStateT (fun s => bind c (fun t => ret (t, s)))\n  }.\n\n  Global Instance State_State_stateT T (MS : MonadState T m) : MonadState T stateT :=\n  { get := lift get\n  ; put := fun x => lift (put x)\n  }.\n\n  Global Instance MonadReader_stateT T (MR : MonadReader T m) : MonadReader T stateT :=\n  { ask := mkStateT (fun s => bind ask (fun t => ret (t, s)))\n  ; local := fun _ f c => mkStateT (fun s => local f (runStateT c s))\n  }.\n\n  Global Instance MonadWriter_stateT T (Mon : Monoid T) (MR : MonadWriter Mon m) : MonadWriter Mon stateT :=\n  { tell := fun x => mkStateT (fun s => bind (tell x) (fun v => ret (v, s)))\n  ; listen := fun _ c => mkStateT (fun s => bind (listen (runStateT c s))\n    (fun x => let '(a,s,t) := x in\n    ret (a,t,s)))\n  ; pass := fun _ c => mkStateT (fun s => bind (runStateT c s) (fun x =>\n    let '(a,t,s) := x in pass (ret ((a,s),t))))\n  }.\n\n  Global Instance Exc_stateT T (MR : MonadExc T m) : MonadExc T stateT :=\n  { raise := fun _ e => lift (raise e)\n  ; catch := fun _ body hnd =>\n    mkStateT (fun s => catch (runStateT body s) (fun e => runStateT (hnd e) s))\n  }.\n\n  Global Instance MonadZero_stateT (MR : MonadZero m) : MonadZero stateT :=\n  { mzero _A := lift mzero\n  }.\n\n  Global Instance MonadFix_stateT (MF : MonadFix m) : MonadFix stateT :=\n  { mfix := fun _ _ r v =>\n    mkStateT (fun s => mfix2 _ (fun r v s => runStateT (mkStateT (r v)) s) v s)\n  }.\n\n  Global Instance MonadPlus_stateT (MP : MonadPlus m) : MonadPlus stateT :=\n  { mplus _A _B a b :=\n      mkStateT (fun s => bind (mplus (runStateT a s) (runStateT b s))\n               (fun res => match res with\n                             | inl (a,s) => ret (inl a, s)\n                             | inr (b,s) => ret (inr b, s)\n                           end))\n  }.\n\nEnd StateType.\n\nArguments mkStateT {S} {m} {t} (_).\nArguments evalState {S} {t} (c) (s).\nArguments execState {S} {t} (c) (s).\nArguments evalStateT {S} {m} {M} {t} (c) (s).\nArguments execStateT {S} {m} {M} {t} (c) (s).\nArguments MonadWriter_stateT {S} {m} {_} {T} {Mon} (_).\n", "meta": {"author": "coq-community", "repo": "coq-ext-lib", "sha": "4811a83db9ccd81f4dcbf77eeff0484dfb21a48b", "save_path": "github-repos/coq/coq-community-coq-ext-lib", "path": "github-repos/coq/coq-community-coq-ext-lib/coq-ext-lib-4811a83db9ccd81f4dcbf77eeff0484dfb21a48b/theories/Data/Monads/StateMonad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.2257004946920059}}
{"text": "From iris Require Import program_logic.weakestpre.\nFrom iris.proofmode Require Import tactics.\nFrom st.STLCmuVS Require Import lang typing wkpre generic.lift contexts logrel.definitions tactics.\nFrom st.STLCmu Require Import types.\nFrom st.prelude Require Import big_op_three.\nFrom st Require Import resources.\n\nCanonical Structure typeO := leibnizO type.\n\nSection definition.\n\n  Context `{Σ : !gFunctors} `{semΣ_inst : !semΣ Σ}.\n\n  (* We define a stuckness-sensistive and insensitive one *)\n  Context (s : stuckness).\n\n  Lemma compat_Var (Γ : list type) (x : var) (τ : type) :\n    Γ !! x = Some τ → open_exprel_typed s Γ (%x)%Eₙₒ (%x)%Eₙₒ τ.\n  Proof.\n    intros H. iIntros (vs vs') \"Hvsvs\".\n    iDestruct (big_sepL3_length _ _ _ _ with \"Hvsvs\") as \"[%eq %eq']\".\n    destruct (Var_subst_list_closed_n_length vs x) as [v [eqv ->]]. apply ids_lt_Closed_n. rewrite -eq. by eapply lookup_lt_Some.\n    destruct (Var_subst_list_closed_n_length vs' x) as [v' [eqv' ->]]. apply ids_lt_Closed_n. rewrite -eq' -eq. by eapply lookup_lt_Some.\n    rewrite /exprel_typed /=. iApply lift_val.\n    iApply ((big_sepL3_lookup _ _ _ _ x _ _ _ H eqv eqv') with \"Hvsvs\").\n  Qed.\n\n  Lemma lift_bind (Kᵢ Kₛ : list ectx_item) (Φ Ψ : valO -n> valO -n> iPropO Σ) (eᵢ eₛ : expr) :\n    ⊢ lift s Φ eᵢ eₛ -∗ (∀ vᵢ vₛ, Φ vᵢ vₛ -∗ lift s Ψ (fill Kᵢ (of_val vᵢ)) (fill Kₛ (of_val vₛ))) -∗ lift s Ψ (fill Kᵢ eᵢ) (fill Kₛ eₛ).\n  Proof. iIntros \"H H2\". iApply lift.lift_bind. iFrame. Qed.\n\n  Lemma compat_Unit (Γ : list type) :\n    open_exprel_typed s Γ ()%Eₙₒ ()%Eₙₒ TUnit.\n  Proof.\n    iIntros (vs vs') \"Hvsvs\". asimpl.\n    change ()%Eₙₒ with (of_val ()%Vₙₒ). iApply lift_val.\n    by rewrite valrel_typed_TUnit_unfold.\n  Qed.\n\n  Lemma compat_Bool (Γ : list type) (b : bool) :\n    open_exprel_typed s Γ b b TBool.\n  Proof.\n    iIntros (vs vs') \"Hvsvs\". asimpl.\n    change (Lit b)%Eₙₒ with (of_val b). iApply lift_val.\n    rewrite valrel_typed_TBool_unfold. by iExists _.\n  Qed.\n\n  Lemma compat_Int (Γ : list type) (z : Z) :\n    open_exprel_typed s Γ z z TInt.\n  Proof.\n    iIntros (vs vs') \"Hvsvs\". asimpl.\n    change (Lit z)%Eₙₒ with (of_val z). iApply lift_val.\n    rewrite valrel_typed_TInt_unfold. by iExists _.\n  Qed.\n\n  Lemma compat_BinOp (Γ : list type) (op : bin_op) (e1 e1' e2 e2' : expr) :\n      open_exprel_typed s Γ e1 e1' TInt → open_exprel_typed s Γ e2 e2' TInt →\n      open_exprel_typed s Γ (BinOp op e1 e2) (BinOp op e1' e2') (binop_res_type op).\n  Proof.\n    intros IHe1 IHe2.\n    iIntros (vs vs') \"#Hvsvs\".\n    iApply (lift_bind [BinOpLCtx op _] [BinOpLCtx op _]). by iApply IHe1. iIntros (v1 v1') \"#Hv1\".\n    iApply (lift_bind [BinOpRCtx op _] [BinOpRCtx op _]). by iApply IHe2. iIntros (v2 v2') \"#Hv2\".\n    rewrite !valrel_typed_TInt_unfold. iDestruct \"Hv1\" as (z1) \"[-> ->]\". iDestruct \"Hv2\" as (z2) \"[-> ->]\".\n    iApply lift_step. auto_STLCmuVS_step.\n    iApply lift_step_later. auto_STLCmuVS_step. iNext. simpl.\n    iApply lift_val.\n    destruct op; simpl; (rewrite valrel_typed_TInt_unfold || rewrite valrel_typed_TBool_unfold); by iExists _.\n  Qed.\n\n  Lemma compat_Seq (Γ : list type) (e1 e1' e2 e2' : expr) (τ : type) :\n      open_exprel_typed s Γ e1 e1' TUnit → open_exprel_typed s Γ e2 e2' τ →\n      open_exprel_typed s Γ (Seq e1 e2) (Seq e1' e2') τ.\n  Proof.\n    intros IHe1 IHe2.\n    iIntros (vs vs') \"#Hvsvs\".\n    iApply (lift_bind [SeqCtx _] [SeqCtx _]). by iApply IHe1. iIntros (v1 v1') \"#Hv1\".\n    rewrite !valrel_typed_TUnit_unfold. iDestruct \"Hv1\" as \"[-> ->]\".\n    iApply lift_step. auto_STLCmuVS_step.\n    iApply lift_step_later. auto_STLCmuVS_step. iNext. simpl.\n    by iApply IHe2.\n  Qed.\n\n  Lemma compat_Pair (Γ : list type) (e1 e1' e2 e2' : expr) (τ1 τ2 : type) :\n      open_exprel_typed s Γ e1 e1' τ1 → open_exprel_typed s Γ e2 e2' τ2 →\n      open_exprel_typed s Γ (e1, e2)%Eₙₒ (e1', e2')%Eₙₒ (τ1 × τ2)%Tₙₒ.\n  Proof.\n    intros IHe1 IHe2.\n    iIntros (vs vs') \"#Hvsvs\".\n    iApply (lift_bind [PairLCtx _] [PairLCtx _]). by iApply IHe1. iIntros (v1 v1') \"#Hv1\".\n    iApply (lift_bind [PairRCtx _] [PairRCtx _]). by iApply IHe2. iIntros (v2 v2') \"#Hv2\".\n    simpl. change (of_val ?v1, of_val ?v2)%Eₙₒ with (of_val (PairV v1 v2)). iApply lift_val.\n    rewrite valrel_typed_TProd_unfold. repeat iExists _; eauto.\n  Qed.\n\n  Lemma compat_Fst (Γ : list type) (e e' : expr) (τ1 τ2 : type) :\n      open_exprel_typed s Γ e e' (τ1 × τ2)%Tₙₒ → open_exprel_typed s Γ (Fst e) (Fst e') τ1.\n  Proof.\n    intros IHe.\n    iIntros (vs vs') \"#Hvsvs\".\n    iApply (lift_bind [FstCtx] [FstCtx]). by iApply IHe. iIntros (v v') \"#Hv\".\n    rewrite !valrel_typed_TProd_unfold. iDestruct \"Hv\" as (v1 v2 v1' v2') \"(-> & -> & H1 & H2)\".\n    iApply lift_step. auto_STLCmuVS_step.\n    iApply lift_step_later. auto_STLCmuVS_step. iNext. simplify_custom. by iApply lift_val.\n  Qed.\n\n  Lemma compat_Snd (Γ : list type) (e e' : expr) (τ1 τ2 : type) :\n      open_exprel_typed s Γ e e' (τ1 × τ2)%Tₙₒ → open_exprel_typed s Γ (Snd e) (Snd e') τ2.\n  Proof.\n    intros IHe.\n    iIntros (vs vs') \"#Hvsvs\".\n    iApply (lift_bind [SndCtx] [SndCtx]). by iApply IHe. iIntros (v v') \"#Hv\".\n    rewrite !valrel_typed_TProd_unfold. iDestruct \"Hv\" as (v1 v2 v1' v2') \"(-> & -> & H1 & H2)\".\n    iApply lift_step. auto_STLCmuVS_step.\n    iApply lift_step_later. auto_STLCmuVS_step. iNext. simplify_custom. by iApply lift_val.\n  Qed.\n\n  Lemma compat_InjL (Γ : list type) (e e' : expr) (τ1 τ2 : type) :\n    open_exprel_typed s Γ e e' τ1 → open_exprel_typed s Γ (InjL e) (InjL e') (τ1 + τ2)%Tₙₒ.\n  Proof.\n    intros IHe.\n    iIntros (vs vs') \"#Hvsvs\".\n    iApply (lift_bind [InjLCtx] [InjLCtx]). by iApply IHe. iIntros (v1 v1') \"#Hv1\".\n    simpl. change (InjL (of_val ?v))%Eₙₒ with (of_val (InjLV v)). iApply lift_val.\n    rewrite valrel_typed_TSum_unfold. repeat iExists _; eauto.\n  Qed.\n\n  Lemma compat_InjR (Γ : list type) (e e' : expr) (τ1 τ2 : type) :\n    open_exprel_typed s Γ e e' τ2 → open_exprel_typed s Γ (InjR e) (InjR e') (τ1 + τ2)%Tₙₒ.\n  Proof.\n    intros IHe.\n    iIntros (vs vs') \"#Hvsvs\".\n    iApply (lift_bind [InjRCtx] [InjRCtx]). by iApply IHe. iIntros (v2 v2') \"#Hv2\".\n    simpl. change (InjR (of_val ?v))%Eₙₒ with (of_val (InjRV v)). iApply lift_val.\n    rewrite valrel_typed_TSum_unfold. repeat iExists _; eauto.\n  Qed.\n\n  Lemma compat_Case (Γ : list type) (e0 e0' e1 e1' e2 e2' : expr) (τ1 τ2 τ3 : type) :\n      open_exprel_typed s Γ e0 e0' (τ1 + τ2)%Tₙₒ\n      → open_exprel_typed s (τ1 :: Γ) e1 e1' τ3\n      → open_exprel_typed s (τ2 :: Γ) e2 e2' τ3 → open_exprel_typed s Γ (Case e0 e1 e2) (Case e0' e1' e2') τ3.\n  Proof.\n    intros IHe0 IHe1 IHe2.\n    iIntros (vs vs') \"#Hvsvs\".\n    iApply (lift_bind [CaseCtx _ _] [CaseCtx _ _]). by iApply IHe0. iIntros (v v') \"#Hv\".\n    rewrite !valrel_typed_TSum_unfold. iDestruct \"Hv\" as (vi vi') \"[(-> & -> & H) | (-> & -> & H)]\".\n    - iApply lift_step. auto_STLCmuVS_step. iApply lift_step_later. auto_STLCmuVS_step. iNext. simplify_custom.\n      rewrite !subst_list_val_cons. iApply IHe1. simpl. auto.\n    - iApply lift_step. auto_STLCmuVS_step. iApply lift_step_later. auto_STLCmuVS_step. iNext. simplify_custom.\n      rewrite !subst_list_val_cons. iApply IHe2. simpl. auto.\n  Qed.\n\n  Lemma compat_If (Γ : list type) (e0 e0' e1 e1' e2 e2' : expr) (τ : type) :\n    open_exprel_typed s Γ e0 e0' TBool → open_exprel_typed s Γ e1 e1' τ → open_exprel_typed s Γ e2 e2' τ →\n    open_exprel_typed s Γ (If e0 e1 e2) (If e0' e1' e2') τ.\n  Proof.\n    intros IHe0 IHe1 IHe2.\n    iIntros (vs vs') \"#Hvsvs\".\n    iApply (lift_bind [IfCtx _ _] [IfCtx _ _]). by iApply IHe0. iIntros (v v') \"#Hv\".\n    rewrite !valrel_typed_TBool_unfold. iDestruct \"Hv\" as (b) \"[-> ->]\".\n    destruct b; (iApply lift_step; first by auto_STLCmuVS_step); (iApply lift_step_later; first by auto_STLCmuVS_step); iNext; simpl;\n      [by iApply IHe1 | by iApply IHe2].\n  Qed.\n\n  Lemma compat_LetIn (Γ : list type) (e1 e1' e2 e2' : expr) (τ1 τ2 : type) :\n      open_exprel_typed s Γ e1 e1' τ1 → open_exprel_typed s (τ1 :: Γ) e2 e2' τ2 →\n      open_exprel_typed s Γ (LetIn e1 e2) (LetIn e1' e2') τ2.\n  Proof.\n    intros IHe1 IHe2.\n    iIntros (vs vs') \"#Hvsvs\".\n    iApply (lift_bind [LetInCtx _] [LetInCtx _]). by iApply IHe1. iIntros (v1 v1') \"#Hv1\".\n    iApply lift_step; first by auto_STLCmuVS_step. iApply lift_step_later; first by auto_STLCmuVS_step. iNext. simplify_custom.\n    rewrite !subst_list_val_cons. iApply IHe2. simpl. auto.\n  Qed.\n\n  Lemma compat_Lam (Γ : list type) (e e' : expr) (τ1 τ2 : type) :\n    open_exprel_typed s (τ1 :: Γ) e e' τ2 →\n    open_exprel_typed s Γ (Lam e) (Lam e') (τ1 ⟶ τ2)%Tₙₒ.\n  Proof.\n    intros IHe.\n    iIntros (vs vs') \"#Hvsvs\". simpl.\n    change (Lam ?e) with (of_val (LamV e)). iApply lift_val.\n    rewrite valrel_typed_TArrow_unfold. iModIntro. iIntros (w w') \"Hww\".\n    iApply lift_step; first by auto_STLCmuVS_step. iApply lift_step_later; first by auto_STLCmuVS_step. iNext. simplify_custom.\n    rewrite !subst_list_val_cons. iApply IHe. simpl. auto.\n  Qed.\n\n  Lemma compat_App (Γ : list type) (e1 e1' e2 e2' : expr) (τ1 τ2 : type) :\n      open_exprel_typed s Γ e1 e1' (τ1 ⟶ τ2)%Tₙₒ → open_exprel_typed s Γ e2 e2' τ1 →\n      open_exprel_typed s Γ (e1 e2) (e1' e2') τ2.\n  Proof.\n    intros IHe1 IHe2.\n    iIntros (vs vs') \"#Hvsvs\".\n    iApply (lift_bind [AppLCtx _] [AppLCtx _]). by iApply IHe1. iIntros (v1 v1') \"#Hv1\".\n    iApply (lift_bind [AppRCtx _] [AppRCtx _]). by iApply IHe2. iIntros (v2 v2') \"#Hv2\".\n    rewrite /= valrel_typed_TArrow_unfold. by iApply \"Hv1\".\n  Qed.\n\n  Lemma compat_Fold (Γ : list type) (e e' : expr) (τ : {bind type}) :\n      open_exprel_typed s Γ e e' τ.[TRec τ/] → open_exprel_typed s Γ (Fold e) (Fold e') (TRec τ).\n  Proof.\n    intros IHe.\n    iIntros (vs vs') \"#Hvsvs\". simpl.\n    iApply (lift_bind [FoldCtx] [FoldCtx]). by iApply IHe. iLöb as \"IHlob\". iIntros (v v') \"#Hv\".\n    simpl. change (Fold (of_val ?v)) with (of_val (FoldV v)). iApply lift_val.\n    rewrite valrel_typed_TRec_unfold. repeat iExists _; eauto.\n  Qed.\n\n  Lemma compat_Unfold (Γ : list type) (e e' : expr) (τ : {bind type}) :\n    open_exprel_typed s Γ e e' (TRec τ) → open_exprel_typed s Γ (Unfold e) (Unfold e') τ.[TRec τ/].\n  Proof.\n    intros IHe.\n    iIntros (vs vs') \"#Hvsvs\". simpl.\n    iApply (lift_bind [UnfoldCtx] [UnfoldCtx]). by iApply IHe. iIntros (v v') \"#Hv\".\n    rewrite valrel_typed_TRec_unfold. iDestruct \"Hv\" as (w w') \"(-> & -> & Hw)\".\n    iApply lift_step; first by auto_STLCmuVS_step. iApply lift_step_later; first by auto_STLCmuVS_step. iNext. simplify_custom.\n    by iApply lift_val.\n  Qed.\n\nEnd definition.\n\nLtac unfold_valrel_typed :=\n  (rewrite valrel_typed_TUnit_unfold) ||\n  (rewrite valrel_typed_TBool_unfold) ||\n  (rewrite valrel_typed_TInt_unfold) ||\n  (rewrite valrel_typed_TArrow_unfold) ||\n  (rewrite valrel_typed_TSum_unfold) ||\n  (rewrite valrel_typed_TProd_unfold) ||\n  (rewrite valrel_typed_TRec_unfold).\n\nLtac simpl_valrel_typed := fold (valrel_typed_gen_pre); repeat rewrite valrel_typed_gen_pre_gen -valrel_typed_unfold; fold (valrel_typed).\n", "meta": {"author": "scaup", "repo": "sem_backs_st", "sha": "e14aa7f421de94df5c1369d2b4b44d8644243cec", "save_path": "github-repos/coq/scaup-sem_backs_st", "path": "github-repos/coq/scaup-sem_backs_st/sem_backs_st-e14aa7f421de94df5c1369d2b4b44d8644243cec/theories/STLCmuVS/logrel/compat_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22570048890532057}}
{"text": "(* Default settings (from HsToCoq.Coq.Preamble) *)\n\nGeneralizable All Variables.\n\nUnset Implicit Arguments.\nSet Maximal Implicit Insertion.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Coq.Program.Tactics.\nRequire Coq.Program.Wf.\n\n(* Converted imports: *)\n\nRequire Data.Graph.Inductive.Graph.\nRequire Data.Graph.Inductive.Internal.Heap.\nRequire Data.Graph.Inductive.Internal.RootPath.\nRequire GHC.Base.\nRequire GHC.Err.\nRequire GHC.Num.\nRequire GHC.Real.\nRequire HsToCoq.DeferredFix.\nRequire HsToCoq.Err.\nImport GHC.Base.Notations.\nImport GHC.Num.Notations.\n\n(* No type declarations to convert. *)\n\n(* Midamble *)\n\nProgram Instance Dijkstra_Default {b} `{Err.Default b} : Err.Default (b * Data.Graph.Inductive.Graph.LPath b *\n                                    Data.Graph.Inductive.Internal.Heap.Heap b (Data.Graph.Inductive.Graph.LPath b)).\nNext Obligation.\ndestruct H. apply (default, Data.Graph.Inductive.Graph.LP nil, Data.Graph.Inductive.Internal.Heap.empty).\nDefined.\n(* Converted value declarations: *)\n\nDefinition expand {b} {a} `{(GHC.Real.Real b)}\n   : b ->\n     Data.Graph.Inductive.Graph.LPath b ->\n     Data.Graph.Inductive.Graph.Context a b ->\n     list (Data.Graph.Inductive.Internal.Heap.Heap b\n           (Data.Graph.Inductive.Graph.LPath b)) :=\n  fun arg_0__ arg_1__ arg_2__ =>\n    match arg_0__, arg_1__, arg_2__ with\n    | d, Data.Graph.Inductive.Graph.LP p, pair (pair (pair _ _) _) s =>\n        GHC.Base.map (fun '(pair l v) =>\n                        Data.Graph.Inductive.Internal.Heap.unit (l GHC.Num.+ d)\n                        (Data.Graph.Inductive.Graph.LP (cons (pair v (l GHC.Num.+ d)) p))) s\n    end.\n\nDefinition dijkstra {gr} {b} {a} `{Data.Graph.Inductive.Graph.Graph gr}\n  `{GHC.Real.Real b} `{HsToCoq.Err.Default b}\n   : Data.Graph.Inductive.Internal.Heap.Heap b (Data.Graph.Inductive.Graph.LPath\n                                              b) ->\n     gr a b -> Data.Graph.Inductive.Internal.RootPath.LRTree b :=\n  HsToCoq.DeferredFix.deferredFix2 (fun dijkstra\n                                    (arg_0__\n                                      : Data.Graph.Inductive.Internal.Heap.Heap b (Data.Graph.Inductive.Graph.LPath\n                                                                                 b))\n                                    (arg_1__ : gr a b) =>\n                                      match arg_0__, arg_1__ with\n                                      | h, g =>\n                                          if orb (Data.Graph.Inductive.Internal.Heap.isEmpty h)\n                                             (Data.Graph.Inductive.Graph.isEmpty g) : bool then nil else (match arg_0__\n                                                                                                              , arg_1__ with\n                                                                                            | h, g =>\n                                                                                                match Data.Graph.Inductive.Internal.Heap.splitMin\n                                                                                                        h with\n                                                                                                | pair (pair _\n                                                                                                 (Data.Graph.Inductive.Graph.LP\n                                                                                                  (cons (pair v d)\n                                                                                                   _) as p)) h' =>\n                                                                                                    match Data.Graph.Inductive.Graph.match_\n                                                                                                            v g with\n                                                                                                    | pair (Some c)\n                                                                                                    g' =>\n                                                                                                        cons p (dijkstra\n                                                                                                              (Data.Graph.Inductive.Internal.Heap.mergeAll\n                                                                                                               (cons h'\n                                                                                                                     (expand\n                                                                                                                      d\n                                                                                                                      p\n                                                                                                                      c)))\n                                                                                                              g')\n                                                                                                    | pair None g' =>\n                                                                                                        dijkstra h' g'\n                                                                                                    end\n                                                                                                | _ =>\n                                                                                                    GHC.Err.patternFailure\n                                                                                                end\n                                                                                            end)\n                                      end).\n\nDefinition spTree {gr : Type -> Type -> Type} {b : Type} {a : Type}\n  `{Data.Graph.Inductive.Graph.Graph gr} `{GHC.Real.Real b}\n   : Data.Graph.Inductive.Graph.Node ->\n     gr a b -> Data.Graph.Inductive.Internal.RootPath.LRTree b :=\n  fun v =>\n    dijkstra (Data.Graph.Inductive.Internal.Heap.unit #0\n              (Data.Graph.Inductive.Graph.LP (cons (pair v #0) nil))).\n\nDefinition spLength {gr : Type -> Type -> Type} {b : Type} {a : Type}\n  `{Data.Graph.Inductive.Graph.Graph gr} `{GHC.Real.Real b}\n   : Data.Graph.Inductive.Graph.Node ->\n     Data.Graph.Inductive.Graph.Node -> gr a b -> option b :=\n  fun s t =>\n    Data.Graph.Inductive.Internal.RootPath.getDistance t GHC.Base.∘ spTree s.\n\nDefinition sp {gr : Type -> Type -> Type} {b : Type} {a : Type}\n  `{Data.Graph.Inductive.Graph.Graph gr} `{GHC.Real.Real b}\n   : Data.Graph.Inductive.Graph.Node ->\n     Data.Graph.Inductive.Graph.Node ->\n     gr a b -> option Data.Graph.Inductive.Graph.Path :=\n  fun s t g =>\n    match Data.Graph.Inductive.Internal.RootPath.getLPathNodes t (spTree s g) with\n    | nil => None\n    | p => Some p\n    end.\n\n(* External variables:\n     None Some Type bool cons else if list nil option orb pair then\n     Data.Graph.Inductive.Graph.Context Data.Graph.Inductive.Graph.Graph\n     Data.Graph.Inductive.Graph.LP Data.Graph.Inductive.Graph.LPath\n     Data.Graph.Inductive.Graph.Node Data.Graph.Inductive.Graph.Path\n     Data.Graph.Inductive.Graph.isEmpty Data.Graph.Inductive.Graph.match_\n     Data.Graph.Inductive.Internal.Heap.Heap\n     Data.Graph.Inductive.Internal.Heap.isEmpty\n     Data.Graph.Inductive.Internal.Heap.mergeAll\n     Data.Graph.Inductive.Internal.Heap.splitMin\n     Data.Graph.Inductive.Internal.Heap.unit\n     Data.Graph.Inductive.Internal.RootPath.LRTree\n     Data.Graph.Inductive.Internal.RootPath.getDistance\n     Data.Graph.Inductive.Internal.RootPath.getLPathNodes GHC.Base.map\n     GHC.Base.op_z2218U__ GHC.Err.patternFailure GHC.Num.fromInteger GHC.Num.op_zp__\n     GHC.Real.Real HsToCoq.DeferredFix.deferredFix2 HsToCoq.Err.Default\n*)\n", "meta": {"author": "plclub", "repo": "hs-to-coq", "sha": "e6401f6f054a2c1ff5e63a17ab8af2bcd5861c9c", "save_path": "github-repos/coq/plclub-hs-to-coq", "path": "github-repos/coq/plclub-hs-to-coq/hs-to-coq-e6401f6f054a2c1ff5e63a17ab8af2bcd5861c9c/examples/graph/lib/Data/Graph/Inductive/Query/SP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22567060869650737}}
{"text": "From Coq Require Import Bool String List BinPos Compare_dec Lia Arith.\nRequire Import Equations.Prop.DepElim.\nFrom Equations Require Import Equations.\nFrom Translation\nRequire Import util SAst SLiftSubst Equality SCommon XTyping ITyping\n               ITypingInversions ITypingLemmata ITypingAdmissible Optim\n               PackLifts FundamentalLemma.\nImport ListNotations.\n\nSection Translation.\n\nContext `{Sort_notion : Sorts.notion}.\n\nOpen Scope type_scope.\nOpen Scope x_scope.\nOpen Scope i_scope.\n\n\n(*! Translation *)\n\nFact length_increl : forall {Γ Γ'}, Γ ⊂ Γ' -> #|Γ| = #|Γ'|.\nProof.\n  intros Γ Γ' h.\n  dependent induction h.\n  - reflexivity.\n  - cbn. now f_equal.\nDefined.\n\nFact nth_error_increl :\n  forall Γ Γ' n A A',\n    Γ ⊂ Γ' ->\n    nth_error Γ n = Some A ->\n    nth_error Γ' n = Some A' ->\n    A ⊏ A'.\nProof.\n  intros Γ Γ' n A A' h e e'.\n  induction h in n, A, A', e, e' |- *.\n  1:{ destruct n. all: discriminate. }\n  destruct n.\n  - cbn in *. congruence.\n  - cbn in *. eapply IHh. all: eauto.\nDefined.\n\nDefinition trans_snoc {Σ Γ A s Γ' A' s'} :\n  Σ |--i Γ' ∈ ⟦ Γ ⟧ ->\n  Σ ;;;; Γ' ⊢ [A'] : sSort s' ∈ ⟦ Γ ⊢ [A] : sSort s ⟧ ->\n  Σ |--i Γ' ,, A' ∈ ⟦ Γ ,, A ⟧.\nProof.\n  intros hΓ hA.\n  split.\n  - constructor ; now destruct hA as [[[? ?] ?] ?].\n  - econstructor.\n    + now destruct hΓ.\n    + now destruct hA as [[[? ?] ?] ?].\nDefined.\n\nDefinition trans_Prod {Σ Γ n A B s1 s2 Γ' A' B'} :\n  Σ |--i Γ' ∈ ⟦ Γ ⟧ ->\n  Σ ;;;; Γ' ⊢ [A'] : sSort s1 ∈ ⟦ Γ ⊢ [A] : sSort s1 ⟧ ->\n  Σ ;;;; Γ' ,, A' ⊢ [B'] : sSort s2\n  ∈ ⟦ Γ ,, A ⊢ [B]: sSort s2 ⟧ ->\n  Σ ;;;; Γ' ⊢ [sProd n A' B']: sSort (Sorts.prod_sort s1 s2)\n  ∈ ⟦ Γ ⊢ [ sProd n A B]: sSort (Sorts.prod_sort s1 s2) ⟧.\nProof.\n  intros hΓ hA hB.\n  destruct hΓ. destruct hA as [[? ?] ?]. destruct hB as [[? ?] ?].\n  repeat split.\n  - assumption.\n  - constructor.\n  - now constructor.\n  - now eapply type_Prod.\nDefined.\n\nDefinition trans_Sum {Σ Γ n A B s1 s2 Γ' A' B'} :\n  Σ |--i Γ' ∈ ⟦ Γ ⟧ ->\n  Σ ;;;; Γ' ⊢ [A'] : sSort s1 ∈ ⟦ Γ ⊢ [A] : sSort s1 ⟧ ->\n  Σ ;;;; Γ' ,, A' ⊢ [B'] : sSort s2\n  ∈ ⟦ Γ ,, A ⊢ [B]: sSort s2 ⟧ ->\n  Σ ;;;; Γ' ⊢ [sSum n A' B']: sSort (Sorts.sum_sort s1 s2)\n  ∈ ⟦ Γ ⊢ [ sSum n A B]: sSort (Sorts.sum_sort s1 s2) ⟧.\nProof.\n  intros hΓ hA hB.\n  destruct hΓ. destruct hA as [[? ?] ?]. destruct hB as [[? ?] ?].\n  repeat split.\n  - assumption.\n  - constructor.\n  - now constructor.\n  - now eapply type_Sum.\nDefined.\n\nDefinition trans_Eq {Σ Γ A u v s Γ' A' u' v'} :\n  Σ |--i Γ' ∈ ⟦ Γ ⟧ ->\n  Σ ;;;; Γ' ⊢ [A'] : sSort s ∈ ⟦ Γ ⊢ [A] : sSort s ⟧ ->\n  Σ ;;;; Γ' ⊢ [u'] : A' ∈ ⟦ Γ ⊢ [u] : A ⟧ ->\n  Σ ;;;; Γ' ⊢ [v'] : A' ∈ ⟦ Γ ⊢ [v] : A ⟧ ->\n  Σ ;;;; Γ' ⊢ [sEq A' u' v'] : sSort (Sorts.eq_sort s)\n  ∈ ⟦ Γ ⊢ [sEq A u v] : sSort (Sorts.eq_sort s) ⟧.\nProof.\n  intros hΓ hA hu hv.\n  destruct hA as [[[? ?] ?] ?].\n  destruct hu as [[[? ?] ?] ?].\n  destruct hv as [[[? ?] ?] ?].\n  repeat split.\n  - assumption.\n  - constructor.\n  - constructor ; assumption.\n  - apply type_Eq ; assumption.\nDefined.\n\nDefinition trans_subst {Σ Γ s A B u Γ' A' B' u'} :\n  type_glob Σ ->\n  Σ |--i Γ' ∈ ⟦ Γ ⟧ ->\n  Σ ;;;; Γ',, A' ⊢ [B']: sSort s ∈ ⟦ Γ,, A ⊢ [B]: sSort s ⟧ ->\n  Σ ;;;; Γ' ⊢ [u']: A' ∈ ⟦ Γ ⊢ [u]: A ⟧ ->\n  Σ ;;;; Γ' ⊢ [B'{ 0 := u' }]: sSort s ∈ ⟦ Γ ⊢ [B{ 0 := u }]: sSort s ⟧.\nProof.\n  intros hg hΓ hB hu.\n  destruct hΓ.\n  destruct hB as [[[? ?] ?] ?]. destruct hu as [[[? ?] ?] ?].\n  repeat split.\n  - assumption.\n  - constructor.\n  - apply inrel_subst ; assumption.\n  - lift_sort. eapply typing_subst ; eassumption.\nDefined.\n\n(* Maybe put this together with the other translation definitions *)\nDefinition eqtrans Σ Γ A u v Γ' A' A'' u' v' p' :=\n  Γ ⊂ Γ' *\n  A ⊏ A' *\n  A ⊏ A'' *\n  u ⊏ u' *\n  v ⊏ v' *\n  (Σ ;;; Γ' |-i p' : sHeq A' u' A'' v').\n\nLemma eqtrans_trans :\n  forall {Σ Γ A u v Γ' A' A'' u' v' p'},\n    type_glob Σ ->\n    eqtrans Σ Γ A u v Γ' A' A'' u' v' p' ->\n    (Σ ;;;; Γ' ⊢ [u'] : A' ∈ ⟦ Γ ⊢ [u] : A ⟧) *\n    (Σ ;;;; Γ' ⊢ [v'] : A'' ∈ ⟦ Γ ⊢ [v] : A ⟧).\nProof.\n  intros Σ Γ A u v Γ' A' A'' u' v' p' hg h.\n  destruct h as [[[[[eΓ eS'] eS''] eA] eB] hp'].\n  repeat split ; try assumption.\n  all: destruct (istype_type hg hp') as [? hheq].\n  all: ttinv hheq.\n  all: assumption.\nDefined.\n\nScheme typing_ind := Induction for XTyping.typing Sort Type\n  with eq_term_ind := Induction for XTyping.eq_term Sort Type.\n\n(* Set Printing Depth 100. *)\n\n(* Combined Scheme typing_all from typing_ind , wf_ind , eq_term_ind. *)\n\nDefinition typing_all :=\n  fun Σ P P0 X X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 X14 X15\n    X16 X17 X18 X19 X20 X21 X22 X23 X24 X25 X26 X27 =>\n    (typing_ind Sort_notion Σ P P0 X X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12\n                X13 X14 X15 X16 X17 X18 X19 X20 X21 X22 X23 X24 X25 X26 X27,\n     eq_term_ind Sort_notion Σ P P0 X X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12\n                 X13 X14 X15 X16 X17 X18 X19 X20 X21 X22 X23 X24 X25 X26 X27).\n\nDefinition complete_translation {Σ} :\n  type_glob Σ ->\n  (forall {Γ t A} (h : Σ ;;; Γ |-x t : A)\n     {Γ'} (hΓ : Σ |--i Γ' ∈ ⟦ Γ ⟧),\n      ∑ A' t', Σ ;;;; Γ' ⊢ [t'] : A' ∈ ⟦ Γ ⊢ [t] : A ⟧) *\n  (forall {Γ u v A} (h : Σ ;;; Γ |-x u ≡ v : A)\n     {Γ'} (hΓ : Σ |--i Γ' ∈ ⟦ Γ ⟧),\n      ∑ A' A'' u' v' p',\n        eqtrans Σ Γ A u v Γ' A' A'' u' v' p').\nProof.\n  intro hg.\n  unshelve refine (\n    typing_all\n      Σ\n      (fun {Γ t A} (h : Σ ;;; Γ |-x t : A) => forall\n           {Γ'} (hΓ : Σ |--i Γ' ∈ ⟦ Γ ⟧),\n           ∑ A' t', Σ ;;;; Γ' ⊢ [t'] : A' ∈ ⟦ Γ ⊢ [t] : A ⟧)\n      (fun {Γ u v A} (h : Σ ;;; Γ |-x u ≡ v : A) => forall\n           {Γ'} (hΓ : Σ |--i Γ' ∈ ⟦ Γ ⟧),\n           ∑ A' A'' u' v' p',\n         eqtrans Σ Γ A u v Γ' A' A'' u' v' p')\n      _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n   ) ; intros.\n\n  (** type_translation **)\n\n    (* type_Rel *)\n    + case_eq (nth_error Γ' n).\n      2:{\n        intro h.\n        apply nth_error_None in h.\n        apply nth_error_Some_length in e.\n        destruct hΓ as [iΓ _]. apply length_increl in iΓ.\n        mylia.\n      }\n      intros B e'.\n      exists (lift0 (S n) B), (sRel n).\n      repeat split.\n      * now destruct hΓ.\n      * apply inrel_lift. eapply nth_error_increl. all: eauto.\n        now destruct hΓ.\n      * constructor.\n      * apply type_Rel.\n        -- now destruct hΓ.\n        -- assumption.\n\n    (* type_Sort *)\n    + exists (sSort (Sorts.succ s)), (sSort s).\n      repeat split.\n      * now destruct hΓ.\n      * constructor.\n      * constructor.\n      * apply type_Sort. now destruct hΓ.\n\n    (* type_Prod *)\n    + (* Translation of the domain *)\n      destruct (X _ hΓ) as [S' [t' ht']].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th ht') as [T' [[t'' ht''] hh]].\n      clear ht' t' S'.\n      destruct T' ; inversion hh.\n      subst. clear hh th.\n      (* Translation of the codomain *)\n      destruct (X0 _ (trans_snoc hΓ ht''))\n        as [S' [b' hb']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hb') as [T' [[b'' hb''] hh]].\n      clear hb' b' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Now we conclude *)\n      exists (sSort (Sorts.prod_sort s1 s2)), (sProd n t'' b'').\n      now apply trans_Prod.\n\n    (* type_Lambda *)\n    + (* Translation of the domain *)\n      destruct (X _ hΓ) as [S' [t' ht']].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th ht') as [T' [[t'' ht''] hh]].\n      clear ht' t' S'.\n      destruct T' ; inversion hh.\n      subst. clear hh th.\n      (* Translation of the codomain *)\n      destruct (X0 _ (trans_snoc hΓ ht''))\n        as [S' [bty' hbty']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hbty') as [T' [[bty'' hbty''] hh]].\n      clear hbty' bty' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Translation of the term *)\n      destruct (X1 _ (trans_snoc hΓ ht''))\n        as [S' [b' hb']].\n      destruct (change_type hg hb' hbty'') as [b'' hb''].\n      clear hb' S' b'.\n      exists (sProd n' t'' bty''), (sLambda n t'' bty'' b'').\n      destruct ht'' as [[[? ?] ?] ?].\n      destruct hbty'' as [[[? ?] ?] ?].\n      destruct hb'' as [[[? ?] ?] ?].\n      repeat split.\n      * now destruct hΓ.\n      * constructor ; eassumption.\n      * constructor ; eassumption.\n      * eapply type_Lambda ; eassumption.\n\n    (* type_App *)\n    + (* Translation of the domain *)\n      destruct (X _ hΓ) as [S' [A'' hA'']].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th hA'') as [T' [[A' hA'] hh]].\n      clear hA'' A'' S'.\n      destruct T' ; inversion hh.\n      subst. clear hh th.\n      (* Translation of the codomain *)\n      destruct (X0 _ (trans_snoc hΓ hA'))\n        as [S' [B'' hB'']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB'') as [T' [[B' hB'] hh]].\n      clear hB'' B'' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Translation of the function *)\n      destruct (X1 _ hΓ) as [T'' [t'' ht'']].\n      assert (th : type_head (head (sProd n A B))) by constructor.\n      destruct (choose_type hg th ht'') as [T' [[t' ht'] hh]].\n      clear ht'' t'' T''.\n      destruct T' ; inversion hh. subst. clear hh th.\n      rename T'1 into A'', T'2 into B''.\n      destruct (change_type hg ht' (trans_Prod hΓ hA' hB')) as [t'' ht''].\n      clear ht' A'' B'' t'.\n      (* Translation of the argument *)\n      destruct (X2 _ hΓ) as [A'' [u'' hu'']].\n      destruct (change_type hg hu'' hA') as [u' hu'].\n      clear hu'' A'' u''.\n      (* We now conclude *)\n      exists (B'{ 0 := u' }), (sApp t'' A' B' u').\n      destruct hΓ.\n      destruct hA' as [[[? ?] ?] ?].\n      destruct hB' as [[[? ?] ?] ?].\n      destruct ht'' as [[[? ?] ?] ?].\n      destruct hu' as [[[? ?] ?] ?].\n      repeat split.\n      * assumption.\n      * now apply inrel_subst.\n      * now constructor.\n      * eapply type_App ; eassumption.\n\n    (* type_Sum *)\n    + (* Translation of the domain *)\n      destruct (X _ hΓ) as [S' [t' ht']].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th ht') as [T' [[t'' ht''] hh]].\n      clear ht' t' S'.\n      destruct T' ; inversion hh.\n      subst. clear hh th.\n      (* Translation of the codomain *)\n      destruct (X0 _ (trans_snoc hΓ ht''))\n        as [S' [b' hb']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hb') as [T' [[b'' hb''] hh]].\n      clear hb' b' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Now we conclude *)\n      exists (sSort (Sorts.sum_sort s1 s2)), (sSum n t'' b'').\n      now apply trans_Sum.\n\n    (* type_Pair *)\n    + (* Translation of the domain *)\n      destruct (X _ hΓ) as [S' [A'' hA'']].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th hA'') as [T' [[A' hA'] hh]].\n      clear hA'' A'' S'.\n      destruct T' ; inversion hh.\n      subst. clear hh th.\n      (* Translation of the codomain *)\n      destruct (X0 _ (trans_snoc hΓ hA'))\n        as [S' [B'' hB'']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB'') as [T' [[B' hB'] hh]].\n      clear hB'' B'' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Translation of the first component *)\n      destruct (X1 _ hΓ) as [A'' [u'' hu'']].\n      destruct (change_type hg hu'' hA') as [u' hu'].\n      clear hu'' A'' u''.\n      (* Translation of the second component *)\n      destruct (X2 _ hΓ) as [Bv' [v'' hv'']].\n      destruct (change_type hg hv'' (trans_subst hg hΓ hB' hu')) as [v' hv'].\n      clear hv'' Bv' v''.\n      (* Now we conclude *)\n      exists (sSum n A' B'), (sPair A' B' u' v').\n      destruct hΓ.\n      destruct hA' as [[[? ?] ?] ?].\n      destruct hB' as [[[? ?] ?] ?].\n      destruct hu' as [[[? ?] ?] ?].\n      destruct hv' as [[[? ?] ?] ?].\n      repeat split.\n      * assumption.\n      * constructor ; assumption.\n      * constructor ; assumption.\n      * eapply type_Pair' ; eassumption.\n\n    (* type_Pi1 *)\n    + (* Translation of the domain *)\n      destruct (X0 _ hΓ) as [S' [A'' hA'']].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th hA'') as [T' [[A' hA'] hh]].\n      clear hA'' A'' S'.\n      destruct T' ; inversion hh.\n      subst. clear hh th.\n      (* Translation of the codomain *)\n      destruct (X1 _ (trans_snoc hΓ hA'))\n        as [S' [B'' hB'']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB'') as [T' [[B' hB'] hh]].\n      clear hB'' B'' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Translation of the pair *)\n      destruct (X _ hΓ) as [T'' [p'' hp'']].\n      assert (th : type_head (head (sSum n A B))) by constructor.\n      destruct (choose_type hg th hp'') as [T' [[p' hp'] hh]].\n      clear hp'' p'' T''.\n      destruct T' ; inversion hh. subst. clear hh th.\n      rename T'1 into A'', T'2 into B''.\n      destruct (change_type hg hp' (trans_Sum hΓ hA' hB')) as [p'' hp''].\n      clear hp' A'' B'' p'.\n    (* Now we conclude *)\n      exists A', (sPi1 A' B' p'').\n      destruct hp'' as [[[? ?] ?] hp'].\n      destruct hA' as [[[? ?] ?] hA'].\n      destruct hB' as [[[? ?] ?] hB'].\n      repeat split.\n      * assumption.\n      * assumption.\n      * constructor ; assumption.\n      * eapply type_Pi1' ; eassumption.\n\n    (* type_Pi2 *)\n    + (* Translation of the domain *)\n      destruct (X0 _ hΓ) as [S' [A'' hA'']].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th hA'') as [T' [[A' hA'] hh]].\n      clear hA'' A'' S'.\n      destruct T' ; inversion hh.\n      subst. clear hh th.\n      (* Translation of the codomain *)\n      destruct (X1 _ (trans_snoc hΓ hA'))\n        as [S' [B'' hB'']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB'') as [T' [[B' hB'] hh]].\n      clear hB'' B'' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Translation of the pair *)\n      destruct (X _ hΓ) as [T'' [p'' hp'']].\n      assert (th : type_head (head (sSum n A B))) by constructor.\n      destruct (choose_type hg th hp'') as [T' [[p' hp'] hh]].\n      clear hp'' p'' T''.\n      destruct T' ; inversion hh. subst. clear hh th.\n      rename T'1 into A'', T'2 into B''.\n      destruct (change_type hg hp' (trans_Sum hΓ hA' hB')) as [p'' hp''].\n      clear hp' A'' B'' p'.\n    (* Now we conclude *)\n      exists (B'{ 0 := sPi1 A' B' p'' }), (sPi2 A' B' p'').\n      destruct hp'' as [[[? ?] ?] hp'].\n      destruct hA' as [[[? ?] ?] hA'].\n      destruct hB' as [[[? ?] ?] hB'].\n      repeat split.\n      * assumption.\n      * apply inrel_subst ; try assumption.\n        constructor ; assumption.\n      * constructor ; assumption.\n      * eapply type_Pi2' ; eassumption.\n\n    (* type_Eq *)\n    + (* The type *)\n      destruct (X _ hΓ) as [S [A'' hA'']].\n      assert (th : type_head (head (sSort s))) by constructor.\n      destruct (choose_type hg th hA'') as [T [[A' hA'] hh]].\n      clear hA'' A'' S.\n      destruct T ; inversion hh. subst. clear hh th.\n      (* The first term *)\n      destruct (X0 _ hΓ) as [A'' [u'' hu'']].\n      destruct (change_type hg hu'' hA') as [u' hu'].\n      clear hu'' u'' A''.\n      (* The other term *)\n      destruct (X1 _ hΓ) as [A'' [v'' hv'']].\n      destruct (change_type hg hv'' hA') as [v' hv'].\n      (* Now we conclude *)\n      exists (sSort (Sorts.eq_sort s)), (sEq A' u' v').\n      apply trans_Eq ; assumption.\n\n    (* type_Refl *)\n    + destruct (X0 _ hΓ) as [A' [u' hu']].\n      exists (sEq A' u' u'), (sRefl A' u').\n      destruct hu' as [[[? ?] ?] hu'].\n      destruct hΓ.\n      repeat split.\n      * assumption.\n      * constructor ; assumption.\n      * constructor ; assumption.\n      * destruct (istype_type hg hu').\n        eapply type_Refl ; eassumption.\n\n    (* type_Ax *)\n    + exists ty, (sAx id).\n      repeat split.\n      * now destruct hΓ.\n      * apply inrel_refl.\n        eapply xcomp_ax_type ; eassumption.\n      * constructor.\n      * eapply type_Ax ; try eassumption.\n        now destruct hΓ.\n\n    (* type_conv *)\n    + (* Translating the conversion *)\n      destruct (X1 _ hΓ)\n        as [S' [S'' [A'' [B'' [p' h']]]]].\n      destruct (eqtrans_trans hg h') as [hA'' hB''].\n      destruct h' as [[[[[eΓ eS'] eS''] eA] eB] hp'].\n      assert (th : type_head (head (sSort s))) by constructor.\n      destruct (choose_type hg th hA'') as [T [[A' hA'] hh]].\n      (* clear hA'' eS' eA A'' S'. *)\n      destruct T ; inversion hh. subst. clear hh.\n      destruct (choose_type hg th hB'') as [T [[B' hB'] hh]].\n      (* clear hB'' eS'' eB B'' S''. *)\n      destruct T ; inversion hh. subst. clear hh th.\n      (* Translating the term *)\n      destruct (X _ hΓ) as [A''' [t'' ht'']].\n      destruct (change_type hg ht'' hA') as [t' ht'].\n      assert (hpA : ∑ pA, Σ ;;; Γ' |-i pA : sHeq (sSort s) A' S' A'').\n      { destruct hA' as [[_ eA'] hA'].\n        destruct hA'' as [_ hA''].\n        assert (hr : A' ∼ A'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [pA hpA].\n        exists pA. apply hpA ; assumption.\n      }\n      destruct hpA as [pA hpA].\n      assert (hpB : ∑ pB, Σ ;;; Γ' |-i pB : sHeq S'' B'' (sSort s) B').\n      { destruct hB' as [[_ eB'] hB'].\n        destruct hB'' as [_ hB''].\n        assert (hr : B'' ∼ B').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [pB hpB].\n        exists pB. apply hpB ; assumption.\n      }\n      destruct hpB as [pB hpB].\n      assert (hq : ∑ q, Σ ;;; Γ' |-i q : sHeq (sSort s) A' (sSort s) B').\n      { exists (optHeqTrans pA (optHeqTrans p' pB)).\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTrans ; try eassumption.\n      }\n      destruct hq as [q hq].\n      destruct (opt_sort_heq_ex hg hq) as [e' he'].\n      (* Now we conclude *)\n      exists B', (optTransport A' B' e' t').\n      destruct hA' as [[[? ?] ?] ?].\n      destruct hB' as [[[? ?] ?] ?].\n      destruct ht' as [[[? ?] ?] ?].\n      repeat split ; try assumption.\n      * apply inrel_optTransport. assumption.\n      * eapply opt_Transport ; eassumption.\n\n  (** eq_translation **)\n\n    (* eq_reflexivity *)\n    + destruct (X _ hΓ) as [A' [u' hu']].\n      destruct hu' as [[[? ?] ?] hu'].\n      exists A', A', u', u', (sHeqRefl A' u').\n      repeat split ; try assumption.\n      destruct (istype_type hg hu') as [s' hA'].\n      eapply type_HeqRefl ; eassumption.\n\n    (* eq_symmetry *)\n    + destruct (X _ hΓ)\n        as [A' [A'' [u' [v' [p' h']]]]].\n      destruct h' as [[[[[? ?] ?] ?] ?] hp'].\n      exists A'', A', v', u', (optHeqSym p').\n      repeat split ; try assumption.\n      eapply opt_HeqSym ; eassumption.\n\n    (* eq_transitivity *)\n    + destruct (X _ hΓ)\n        as [A1 [A2 [u1 [v1 [p1 h1']]]]].\n      destruct (X0 _ hΓ)\n        as [A3 [A4 [v2 [w1 [p2 h2']]]]].\n      destruct (eqtrans_trans hg h1') as [hu1 hv1].\n      destruct (eqtrans_trans hg h2') as [hv2 hw1].\n      destruct h1' as [[[[[? ?] ?] ?] ?] hp1].\n      destruct h2' as [[[[[? ?] ?] ?] ?] hp2].\n      (* We have a missing link between (v1 : A2) and (v2 : A3) *)\n      assert (sim : v1 ∼ v2).\n      { eapply trel_trans.\n        - eapply trel_sym. eapply inrel_trel. eassumption.\n        - apply inrel_trel. assumption.\n      }\n      destruct hv1 as [_ hv1].\n      destruct hv2 as [_ hv2].\n      destruct (trel_to_heq Γ' hg sim) as [p3 hp3].\n      (* We can conclude *)\n      exists A1, A4, u1, w1.\n      exists (optHeqTrans p1 (optHeqTrans p3 p2)).\n      repeat split ; try assumption.\n      specialize (hp3 _ _ hv1 hv2).\n      eapply opt_HeqTrans ; try assumption.\n      * eassumption.\n      * eapply opt_HeqTrans ; eassumption.\n\n    (* eq_beta *)\n    + (* Translation of the domain *)\n      destruct (X _ hΓ) as [S [A'' hA'']].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th hA'') as [T' [[A' hA'] hh]].\n      clear hA'' A'' S.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Translation of the codomain *)\n      destruct (X0 _ (trans_snoc hΓ hA'))\n        as [S' [B'' hB'']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB'') as [T' [[B' hB'] hh]].\n      clear hB'' B'' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Translation of the in-term *)\n      destruct (X1 _ (trans_snoc hΓ hA'))\n        as [T' [t'' ht'']].\n      destruct (change_type hg ht'' hB') as [t' ht'].\n      clear ht'' T' t''.\n      (* Translation of the argument *)\n      destruct (X2 _ hΓ) as [A'' [u'' hu'']].\n      destruct (change_type hg hu'' hA') as [u' hu'].\n      clear hu'' A'' u''.\n      (* Now we conclude using beta *)\n      exists (B'{0 := u'}), (B'{0 := u'}).\n      exists (sApp (sLambda n A' B' t') A' B' u'), (t'{0 := u'}).\n      exists (sEqToHeq (sBeta t' u')).\n      destruct hA' as [[[? ?] ?] ?].\n      destruct hB' as [[[? ?] ?] ?].\n      destruct ht' as [[[? ?] ?] ?].\n      destruct hu' as [[[? ?] ?] ?].\n      repeat split.\n      * assumption.\n      * eapply inrel_subst ; assumption.\n      * eapply inrel_subst ; assumption.\n      * constructor ; try assumption.\n        constructor ; assumption.\n      * eapply inrel_subst ; assumption.\n      * eapply type_EqToHeq' ; try eassumption.\n        eapply type_Beta ; eassumption.\n\n    (* eq_conv *)\n    + (* Translating the conversion *)\n      destruct (X0 _ hΓ)\n        as [S' [S'' [T1'' [T2'' [p' h']]]]].\n      destruct (eqtrans_trans hg h') as [hT1'' hT2''].\n      destruct h' as [[[[[eΓ eS'] eS''] eT1] eT2] hp'].\n      assert (th : type_head (head (sSort s))) by constructor.\n      destruct (choose_type hg th hT1'') as [T [[T1' hT1'] hh]].\n      destruct T ; inversion hh. subst. clear hh.\n      destruct (choose_type hg th hT2'') as [T [[T2' hT2'] hh]].\n      destruct T ; inversion hh. subst. clear hh th.\n      (* Translation the term conversion *)\n      destruct (X _ hΓ)\n        as [T1''' [T2''' [t1'' [t2'' [q' hq']]]]].\n      destruct (eqtrans_trans hg hq') as [ht1'' ht2''].\n      destruct (change_type hg ht1'' hT1') as [t1' ht1'].\n      destruct (change_type hg ht2'' hT1') as [t2' ht2'].\n      (* clear ht1'' ht2'' hq' T1''' T2''' t1'' t2'' q'. *)\n      destruct hq' as [[[[[_ eT1'''] eT2'''] et1''] et2''] hq'].\n      (* Building the intermediary paths *)\n      assert (hpT1 : ∑ p1, Σ ;;; Γ' |-i p1 : sHeq (sSort s) T1' S' T1'').\n      { destruct hT1' as [[_ eT1'] hT1'].\n        destruct hT1'' as [_ hT1''].\n        assert (hr : T1' ∼ T1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [p1 hp1].\n        exists p1. apply hp1 ; assumption.\n      }\n      destruct hpT1 as [p1 hp1].\n      assert (hp2 : ∑ p2, Σ ;;; Γ' |-i p2 : sHeq S'' T2'' (sSort s) T2').\n      { destruct hT2' as [[_ eT2'] hT2'].\n        destruct hT2'' as [_ hT2''].\n        assert (hr : T2'' ∼ T2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [p2 hp2].\n        exists p2. apply hp2 ; assumption.\n      }\n      destruct hp2 as [p2 hp2].\n      assert (he : ∑ e, Σ ;;; Γ' |-i e : sHeq (sSort s) T1' (sSort s) T2').\n      { exists (optHeqTrans p1 (optHeqTrans p' p2)).\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTrans ; try eassumption.\n      }\n      destruct he as [e' he'].\n      rename e into eqt.\n      destruct (opt_sort_heq_ex hg he') as [e he].\n      (* Likewise, we build paths for the terms *)\n      assert (hq1 : ∑ q1, Σ ;;; Γ' |-i q1 : sHeq T1' t1' T1''' t1'').\n      { destruct ht1' as [[_ et1'] ht1'].\n        destruct ht1'' as [_ ht1''].\n        assert (hr : t1' ∼ t1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [q1 hq1].\n        exists q1. apply hq1 ; assumption.\n      }\n      destruct hq1 as [q1 hq1].\n      assert (hq2 : ∑ q2, Σ ;;; Γ' |-i q2 : sHeq T2''' t2'' T1' t2').\n      { destruct ht2' as [[_ et2'] ht2'].\n        destruct ht2'' as [_ ht2''].\n        assert (hr : t2'' ∼ t2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [q2 hq2].\n        exists q2. apply hq2 ; assumption.\n      }\n      destruct hq2 as [q2 hq2].\n      assert (hqq : ∑ qq, Σ ;;; Γ' |-i qq : sHeq T1' t1' T1' t2').\n      { exists (optHeqTrans q1 (optHeqTrans q' q2)).\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTrans ; try eassumption.\n      }\n      destruct hqq as [qq hqq].\n      assert (hql : ∑ ql, Σ ;;; Γ' |-i ql : sHeq T2' (sTransport T1' T2' e t1') T1' t1').\n      { exists (optHeqSym (optHeqTransport e t1')).\n        destruct ht1' as [_ ht1'].\n        eapply opt_HeqSym ; try assumption.\n        eapply opt_HeqTransport ; eassumption.\n      }\n      destruct hql as [ql hql].\n      assert (hqr : ∑ qr, Σ ;;; Γ' |-i qr : sHeq T1' t2' T2' (sTransport T1' T2' e t2')).\n      { exists (optHeqTransport e t2').\n        destruct ht2' as [_ ht2'].\n        eapply opt_HeqTransport ; eassumption.\n      }\n      destruct hqr as [qr hqr].\n      assert (hqf : ∑ qf, Σ ;;; Γ' |-i qf\n                                    : sHeq T2' (sTransport T1' T2' e t1')\n                                           T2' (sTransport T1' T2' e t2')).\n      { exists (optHeqTrans (optHeqTrans ql qq) qr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - assumption.\n      }\n      destruct hqf as [qf hqf].\n      (* Now we conclude *)\n      exists T2', T2', (sTransport T1' T2' e t1'), (sTransport T1' T2' e t2').\n      exists qf.\n      destruct hT1' as [[[? ?] ?] ?].\n      destruct hT2' as [[[? ?] ?] ?].\n      destruct ht1' as [[[? ?] ?] ?].\n      destruct ht2' as [[[? ?] ?] ?].\n      repeat split ; try eassumption.\n      * econstructor. assumption.\n      * econstructor. assumption.\n\n    (* cong_Prod *)\n    + (* The domains *)\n      destruct (X _ hΓ)\n        as [T1 [T2 [A1'' [A2'' [pA h1']]]]].\n      destruct (eqtrans_trans hg h1') as [hA1'' hA2''].\n      destruct h1' as [[[[[? ?] ?] ?] ?] hpA''].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th hA1'') as [T' [[A1' hA1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hA2'') as [T' [[A2' hA2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      (* Now the codomains *)\n      destruct (X0 _ (trans_snoc hΓ hA1'))\n        as [S1 [S2 [B1'' [B2'' [pB h2']]]]].\n      destruct (eqtrans_trans hg h2') as [hB1'' hB2''].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB1'') as [T' [[B1' hB1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hB2'') as [T' [[B2' hB2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      destruct h2' as [[[[[? ?] ?] ?] ?] hpB''].\n      (* Now we connect the paths for the domains *)\n      assert (hp1 : ∑ p1, Σ ;;; Γ' |-i p1 : sHeq (sSort s1) A1' (sSort s1) A2').\n      { destruct hA1' as [[_ eA1'] hA1'].\n        destruct hA1'' as [_ hA1''].\n        destruct hA2' as [[_ eA2'] hA2'].\n        destruct hA2'' as [_ hA2''].\n        assert (hr : A1' ∼ A1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [pl hpl].\n        assert (hr' : A2'' ∼ A2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr') as [pr hpr].\n        exists (optHeqTrans (optHeqTrans pl pA) pr).\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hp1 as [p1 hp1].\n      (* And then the paths for the codomains *)\n      pose (Γ1 := nil ,, A1').\n      pose (Γ2 := nil ,, A2').\n      pose (Γm := [ (sPack A1' A2') ]).\n      assert (hm : ismix Σ Γ' Γ1 Γ2 Γm).\n      { revert Γm.\n        replace A1' with (llift0 #|@nil sterm| A1')\n          by (cbn ; now rewrite llift00).\n        replace A2' with (rlift0 #|@nil sterm| A2')\n          by (cbn ; now rewrite rlift00).\n        intros.\n        destruct hA1' as [[? ?] ?].\n        destruct hA2' as [[? ?] ?].\n        econstructor.\n        - constructor.\n        - eassumption.\n        - assumption.\n      }\n      pose (Δ := Γ' ,,, Γm).\n      assert (hp2 : ∑ p2, Σ ;;; Γ' ,,, Γ1 |-i p2 : sHeq (sSort s2) B1'\n                                                       (sSort s2) B2').\n      { destruct hB1' as [[_ eB1'] hB1'].\n        destruct hB1'' as [_ hB1''].\n        destruct hB2' as [[_ eB2'] hB2'].\n        destruct hB2'' as [_ hB2''].\n        assert (hr : B1' ∼ B1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : B2'' ∼ B2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pB) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hp2 as [p2 hp2].\n      assert (hp3 : ∑ p3, Σ ;;; Δ |-i p3 : sHeq (sSort s2)\n                                               (llift0 #|Γm| B1')\n                                               (sSort s2)\n                                               (llift0 #|Γm| B2')\n             ).\n      { exists (llift0 #|Γm| p2).\n        match goal with\n        | |- _ ;;; _ |-i _ : ?T =>\n          change T with (llift0 #|Γm| (sHeq (sSort s2) B1' (sSort s2) B2'))\n        end.\n        eapply type_llift0 ; eassumption.\n      }\n      destruct hp3 as [p3 hp3].\n      (* Also translating the typing hypothesis for B2 *)\n      destruct (X2 _ (trans_snoc hΓ hA2'))\n        as [S' [B2''' hB2''']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB2''') as [T' [[tB2 htB2] hh]].\n      clear hB2''' B2''' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Now we can use the strong version of the lemma to build a path between\n         B2' and tB2 !\n       *)\n      assert (hp4 : ∑ p4, Σ ;;; Δ |-i p4 : sHeq (sSort s2) (llift0 #|Γm| B2')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { change (sSort s2) with (llift0 #|Γm| (sSort s2)) at 1.\n        change (sSort s2) with (rlift0 #|Γm| (sSort s2)) at 2.\n        assert (hr : B2' ∼ tB2).\n        { destruct htB2 as [[? ?] ?].\n          destruct hB2' as [[? ?] ?].\n          eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        edestruct (trel_to_heq' hg hr) as [p4 hp4].\n        exists p4. apply hp4.\n        - eassumption.\n        - destruct hB2' as [[? ?] ?]. assumption.\n        - destruct htB2 as [[? ?] ?]. assumption.\n      }\n      destruct hp4 as [p4 hp4].\n      (* This gives us a better path *)\n      assert (hp5 : ∑ p5, Σ ;;; Δ |-i p5 : sHeq (sSort s2) (llift0 #|Γm| B1')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { exists (optHeqTrans p3 p4).\n        eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hp5 as [p5 hp5].\n      (* We can finally conclude! *)\n      exists (sSort (Sorts.prod_sort s1 s2)), (sSort (Sorts.prod_sort s1 s2)).\n      exists (sProd n1 A1' B1'), (sProd n2 A2' tB2).\n      exists (optCongProd B1' tB2 p1 p5).\n      destruct hA1' as [[[? ?] ?] ?].\n      destruct hB1' as [[[? ?] ?] ?].\n      destruct hA2' as [[[? ?] ?] ?].\n      destruct htB2 as [[[? ?] ?] ?].\n      repeat split ; [ try constructor .. |].\n      all: try assumption.\n      eapply opt_CongProd ; try assumption.\n      cbn in hp5. rewrite <- llift_substProj, <- rlift_substProj in hp5.\n      rewrite !llift00, !rlift00 in hp5.\n      apply hp5.\n\n    (* cong_Lambda *)\n    + (* The domains *)\n      destruct (X _ hΓ)\n        as [T1 [T2 [A1'' [A2'' [pA h1']]]]].\n      destruct (eqtrans_trans hg h1') as [hA1'' hA2''].\n      destruct h1' as [[[[[? ?] ?] ?] ?] hpA''].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th hA1'') as [T' [[A1' hA1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hA2'') as [T' [[A2' hA2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      (* Now the codomains *)\n      destruct (X0 _ (trans_snoc hΓ hA1'))\n        as [S1 [S2 [B1'' [B2'' [pB h2']]]]].\n      destruct (eqtrans_trans hg h2') as [hB1'' hB2''].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB1'') as [T' [[B1' hB1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hB2'') as [T' [[B2' hB2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      destruct h2' as [[[[[? ?] ?] ?] ?] hpB''].\n      (* Now we connect the paths for the domains *)\n      assert (hp1 : ∑ p1, Σ ;;; Γ' |-i p1 : sHeq (sSort s1) A1' (sSort s1) A2').\n      { destruct hA1' as [[_ eA1'] hA1'].\n        destruct hA1'' as [_ hA1''].\n        destruct hA2' as [[_ eA2'] hA2'].\n        destruct hA2'' as [_ hA2''].\n        assert (hr : A1' ∼ A1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : A2'' ∼ A2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pA) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hp1 as [p1 hp1].\n      (* And then the paths for the codomains *)\n      pose (Γ1 := nil ,, A1').\n      pose (Γ2 := nil ,, A2').\n      pose (Γm := [ sPack A1' A2' ]).\n      assert (hm : ismix Σ Γ' Γ1 Γ2 Γm).\n      { revert Γm.\n        replace A1' with (llift0 #|@nil sterm| A1')\n          by (cbn ; now rewrite llift00).\n        replace A2' with (rlift0 #|@nil sterm| A2')\n          by (cbn ; now rewrite rlift00).\n        intros.\n        destruct hA1' as [[? ?] ?].\n        destruct hA2' as [[? ?] ?].\n        econstructor.\n        - constructor.\n        - eassumption.\n        - assumption.\n      }\n      pose (Δ := Γ' ,,, Γm).\n      assert (hp2 : ∑ p2, Σ ;;; Γ' ,,, Γ1 |-i p2 : sHeq (sSort s2) B1'\n                                                       (sSort s2) B2').\n      { destruct hB1' as [[_ eB1'] hB1'].\n        destruct hB1'' as [_ hB1''].\n        destruct hB2' as [[_ eB2'] hB2'].\n        destruct hB2'' as [_ hB2''].\n        assert (hr : B1' ∼ B1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : B2'' ∼ B2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pB) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hp2 as [p2 hp2].\n      assert (hp3 : ∑ p3, Σ ;;; Δ |-i p3 : sHeq (sSort s2)\n                                               (llift0 #|Γm| B1')\n                                               (sSort s2)\n                                               (llift0 #|Γm| B2')\n             ).\n      { exists (llift0 #|Γm| p2).\n        match goal with\n        | |- _ ;;; _ |-i _ : ?T =>\n          change T with (llift0 #|Γm| (sHeq (sSort s2) B1' (sSort s2) B2'))\n        end.\n        eapply type_llift0 ; eassumption.\n      }\n      destruct hp3 as [p3 hp3].\n      (* Also translating the typing hypothesis for B2 *)\n      destruct (X3 _ (trans_snoc hΓ hA2'))\n        as [S' [B2''' hB2''']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB2''') as [T' [[tB2 htB2] hh]].\n      clear hB2''' B2''' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Now we can use the strong version of the lemma to build a path between\n         B2' and tB2 !\n       *)\n      assert (hp4 : ∑ p4, Σ ;;; Δ |-i p4 : sHeq (sSort s2) (llift0 #|Γm| B2')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { change (sSort s2) with (llift0 #|Γm| (sSort s2)) at 1.\n        change (sSort s2) with (rlift0 #|Γm| (sSort s2)) at 2.\n        assert (hr : B2' ∼ tB2).\n        { destruct htB2 as [[? ?] ?].\n          destruct hB2' as [[? ?] ?].\n          eapply trel_trans.\n          + eapply trel_sym. eapply inrel_trel. eassumption.\n          + apply inrel_trel. assumption.\n        }\n        edestruct (trel_to_heq' hg hr) as [p4 hp4].\n        exists p4. apply hp4.\n        - eassumption.\n        - destruct hB2' as [[? ?] ?]. assumption.\n        - destruct htB2 as [[? ?] ?]. assumption.\n      }\n      destruct hp4 as [p4 hp4].\n      (* This gives us a better path *)\n      assert (hp5 : ∑ p5, Σ ;;; Δ |-i p5 : sHeq (sSort s2) (llift0 #|Γm| B1')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { exists (optHeqTrans p3 p4).\n        eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hp5 as [p5 hp5].\n      (* Cleaning *)\n      clear hp4 p4 hp3 p3 hp2 p2.\n      clear hB2' B2' hB2'' hpB'' hB1'' hpA'' hA1'' hA2''.\n      (* clear i8 i7 i6 i5 i4 S1 S2 B1'' B2'' pB. *)\n      (* clear i3 i2 i1 i0 i T1 T2 A1'' A2'' pA. *)\n      clear pA pB pi2_5 B1'' pi2_6 B2''.\n      rename p1 into pA, p5 into pB, hp1 into hpA, hp5 into hpB.\n      rename tB2 into B2', htB2 into hB2'.\n      (* We can now focus on the function terms *)\n      destruct (X1 _ (trans_snoc hΓ hA1'))\n        as [B1'' [B1''' [t1'' [t2'' [pt h3']]]]].\n      destruct (eqtrans_trans hg h3') as [ht1'' ht2''].\n      destruct (change_type hg ht1'' hB1') as [t1' ht1'].\n      destruct (change_type hg ht2'' hB1') as [t2' ht2'].\n      destruct (X5 _ (trans_snoc hΓ hA2'))\n        as [B2'' [t2''' ht2''']].\n      destruct (change_type hg ht2''' hB2') as [tt2 htt2].\n      assert (hq1 : ∑ q1, Σ ;;; Γ' ,, A1' |-i q1 : sHeq B1' t1' B1' t2').\n      { destruct h3' as [[[[[? ?] ?] ?] ?] hpt''].\n        destruct ht1' as [[_ et1'] ht1'].\n        destruct ht1'' as [_ ht1''].\n        destruct ht2' as [[_ et2'] ht2'].\n        destruct ht2'' as [_ ht2''].\n        assert (hr : t1' ∼ t1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : t2'' ∼ t2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pt) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - assumption.\n      }\n      destruct hq1 as [q1 hq1].\n      assert (hq2 : ∑ q2,\n        Σ ;;; Δ |-i q2 : sHeq (llift0 #|Γm| B1') (llift0 #|Γm| t1')\n                             (llift0 #|Γm| B1') (llift0 #|Γm| t2')\n      ).\n      { exists (llift0 #|Γm| q1).\n        match goal with\n        | |- _ ;;; _ |-i _ : ?T =>\n          change T with (llift0 #|Γm| (sHeq B1' t1' B1' t2'))\n        end.\n        eapply type_llift0 ; try eassumption.\n        assumption.\n      }\n      destruct hq2 as [q2 hq2].\n      assert (hq3 : ∑ q3,\n        Σ ;;; Δ |-i q3 : sHeq (llift0 #|Γm| B1') (llift0 #|Γm| t2')\n                             (rlift0 #|Γm| B2') (rlift0 #|Γm| tt2)\n      ).\n      { assert (hr : t2' ∼ tt2).\n        { destruct htt2 as [[? ?] ?].\n          destruct ht2' as [[? ?] ?].\n          eapply trel_trans.\n          + eapply trel_sym. eapply inrel_trel. eassumption.\n          + apply inrel_trel. assumption.\n        }\n        edestruct (trel_to_heq' hg hr) as [p3 hp3].\n        exists p3. apply hp3.\n        - eassumption.\n        - destruct ht2' as [[? ?] ?]. assumption.\n        - destruct htt2 as [[? ?] ?]. assumption.\n      }\n      destruct hq3 as [q3 hq3].\n      assert (hq4 : ∑ q4,\n        Σ ;;; Δ |-i q4 : sHeq (llift0 #|Γm| B1') (llift0 #|Γm| t1')\n                             (rlift0 #|Γm| B2') (rlift0 #|Γm| tt2)\n      ).\n      { exists (optHeqTrans q2 q3).\n        eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hq4 as [qt hqt].\n      (* We're almost done.\n         However, our translation of (sLambda n2 A2 B2 t2) has to live in\n         our translation of (sProd n' A1 B1).\n         This is where the path between the two types comes into action.\n       *)\n      assert (hty : ∑ pty,\n        Σ ;;; Γ' |-i pty : sHeq (sSort (Sorts.prod_sort s1 s2))\n                               (sProd n2 A2' B2')\n                               (sSort (Sorts.prod_sort s1 s2))\n                               (sProd n1 A1' B1')\n\n      ).\n      { exists (optHeqSym (optCongProd B1' B2' pA pB)).\n        destruct hB1' as [[[? ?] ?] ?].\n        destruct hB2' as [[[? ?] ?] ?].\n        eapply opt_HeqSym ; try assumption.\n        eapply opt_CongProd ; try assumption.\n        cbn in hpB. rewrite <- llift_substProj, <- rlift_substProj in hpB.\n        rewrite !llift00, !rlift00 in hpB.\n        apply hpB.\n      }\n      destruct hty as [pty hty].\n      destruct (opt_sort_heq_ex hg hty) as [eT heT].\n      (* We move the lambda now. *)\n      pose (tλ :=\n              sTransport (sProd n2 A2' B2') (sProd n1 A1' B1')\n                         eT (sLambda n2 A2' B2' tt2)\n      ).\n      (* Now we conclude *)\n      exists (sProd n1 A1' B1'), (sProd n1 A1' B1').\n      exists (sLambda n1 A1' B1' t1'), tλ.\n      exists (optHeqTrans (optCongLambda B1' B2' t1' tt2 pA pB qt)\n                   (optHeqTransport eT (sLambda n2 A2' B2' tt2))).\n      destruct ht1' as [[[? ?] ?] ?].\n      destruct htt2 as [[[? ?] ?] ?].\n      destruct hA1' as [[[? ?] ?] ?].\n      destruct hA2' as [[[? ?] ?] ?].\n      destruct hB1' as [[[? ?] ?] ?].\n      destruct hB2' as [[[? ?] ?] ?].\n      repeat split.\n      * assumption.\n      * constructor ; assumption.\n      * constructor ; assumption.\n      * constructor ; assumption.\n      * constructor. constructor ; assumption.\n      * eapply opt_HeqTrans ; try assumption.\n        -- eapply opt_CongLambda ; try eassumption.\n           ++ cbn in hpB. rewrite <- llift_substProj, <- rlift_substProj in hpB.\n              rewrite !llift00, !rlift00 in hpB.\n              apply hpB.\n           ++ cbn in hqt. rewrite <- !llift_substProj, <- !rlift_substProj in hqt.\n              rewrite !llift00, !rlift00 in hqt.\n              apply hqt.\n        -- eapply opt_HeqTransport ; try assumption.\n           ++ eapply type_Lambda ; eassumption.\n           ++ eassumption.\n\n    (* cong_App *)\n    + (* The domains *)\n      destruct (X _ hΓ)\n        as [T1 [T2 [A1'' [A2'' [pA h1']]]]].\n      destruct (eqtrans_trans hg h1') as [hA1'' hA2''].\n      destruct h1' as [[[[[? ?] ?] ?] ?] hpA''].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th hA1'') as [T' [[A1' hA1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hA2'') as [T' [[A2' hA2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      (* Now the codomains *)\n      destruct (X0 _ (trans_snoc hΓ hA1'))\n        as [S1 [S2 [B1'' [B2'' [pB h2']]]]].\n      destruct (eqtrans_trans hg h2') as [hB1'' hB2''].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB1'') as [T' [[B1' hB1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hB2'') as [T' [[B2' hB2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      destruct h2' as [[[[[? ?] ?] ?] ?] hpB''].\n      (* Now we connect the paths for the domains *)\n      assert (hp1 : ∑ p1, Σ ;;; Γ' |-i p1 : sHeq (sSort s1) A1' (sSort s1) A2').\n      { destruct hA1' as [[_ eA1'] hA1'].\n        destruct hA1'' as [_ hA1''].\n        destruct hA2' as [[_ eA2'] hA2'].\n        destruct hA2'' as [_ hA2''].\n        assert (hr : A1' ∼ A1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : A2'' ∼ A2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pA) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hp1 as [p1 hp1].\n      (* And then the paths for the codomains *)\n      pose (Γ1 := nil ,, A1').\n      pose (Γ2 := nil ,, A2').\n      pose (Γm := [ sPack A1' A2' ]).\n      assert (hm : ismix Σ Γ' Γ1 Γ2 Γm).\n      { revert Γm.\n        replace A1' with (llift0 #|@nil sterm| A1')\n          by (cbn ; now rewrite llift00).\n        replace A2' with (rlift0 #|@nil sterm| A2')\n          by (cbn ; now rewrite rlift00).\n        intros.\n        destruct hA1' as [[? ?] ?].\n        destruct hA2' as [[? ?] ?].\n        econstructor.\n        - constructor.\n        - eassumption.\n        - assumption.\n      }\n      pose (Δ := Γ' ,,, Γm).\n      assert (hp2 : ∑ p2, Σ ;;; Γ' ,,, Γ1 |-i p2 : sHeq (sSort s2) B1'\n                                                       (sSort s2) B2').\n      { destruct hB1' as [[_ eB1'] hB1'].\n        destruct hB1'' as [_ hB1''].\n        destruct hB2' as [[_ eB2'] hB2'].\n        destruct hB2'' as [_ hB2''].\n        assert (hr : B1' ∼ B1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : B2'' ∼ B2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pB) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hp2 as [p2 hp2].\n      assert (hp3 : ∑ p3, Σ ;;; Δ |-i p3 : sHeq (sSort s2)\n                                               (llift0 #|Γm| B1')\n                                               (sSort s2)\n                                               (llift0 #|Γm| B2')\n             ).\n      { exists (llift0 #|Γm| p2).\n        match goal with\n        | |- _ ;;; _ |-i _ : ?T =>\n          change T with (llift0 #|Γm| (sHeq (sSort s2) B1' (sSort s2) B2'))\n        end.\n        eapply type_llift0 ; eassumption.\n      }\n      destruct hp3 as [p3 hp3].\n      (* Also translating the typing hypothesis for B2 *)\n      destruct (X4 _ (trans_snoc hΓ hA2'))\n        as [S' [B2''' hB2''']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB2''') as [T' [[tB2 htB2] hh]].\n      clear hB2''' B2''' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Now we can use the strong version of the lemma to build a path between\n         B2' and tB2 !\n       *)\n      assert (hp4 : ∑ p4, Σ ;;; Δ |-i p4 : sHeq (sSort s2) (llift0 #|Γm| B2')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { change (sSort s2) with (llift0 #|Γm| (sSort s2)) at 1.\n        change (sSort s2) with (rlift0 #|Γm| (sSort s2)) at 2.\n        assert (hr : B2' ∼ tB2).\n        { destruct htB2 as [[? ?] ?].\n          destruct hB2' as [[? ?] ?].\n          eapply trel_trans.\n          + eapply trel_sym. eapply inrel_trel. eassumption.\n          + apply inrel_trel. assumption.\n        }\n        edestruct (trel_to_heq' hg hr) as [p4 hp4].\n        exists p4. apply hp4.\n        - eassumption.\n        - destruct hB2' as [[? ?] ?]. assumption.\n        - destruct htB2 as [[? ?] ?]. assumption.\n      }\n      destruct hp4 as [p4 hp4].\n      (* This gives us a better path *)\n      assert (hp5 : ∑ p5, Σ ;;; Δ |-i p5 : sHeq (sSort s2) (llift0 #|Γm| B1')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { exists (optHeqTrans p3 p4).\n        eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hp5 as [p5 hp5].\n      (* Cleaning *)\n      clear hp4 p4 hp3 p3 hp2 p2.\n      clear hB2' B2' hB2'' hpB'' hB1'' hpA'' hA1'' hA2''.\n      (* clear i8 i7 i6 i5 i4 S1 S2 B1'' B2'' pB. *)\n      (* clear i3 i2 i1 i0 i T1 T2 A1'' A2'' pA. *)\n      clear pA pB pi2_1 pi2_2 A1'' A2''.\n      rename p1 into pA, p5 into pB, hp1 into hpA, hp5 into hpB.\n      rename tB2 into B2', htB2 into hB2'.\n      (* We can now translate the functions. *)\n      destruct (X1 _ hΓ)\n        as [P1 [P1' [t1'' [t2'' [pt h3']]]]].\n      destruct (eqtrans_trans hg h3') as [ht1'' ht2''].\n      destruct (change_type hg ht1'' (trans_Prod hΓ hA1' hB1')) as [t1' ht1'].\n      destruct (change_type hg ht2'' (trans_Prod hΓ hA1' hB1')) as [t2' ht2'].\n      destruct h3' as [[[[[? ?] ?] ?] ?] hpt].\n      destruct (X6 _ hΓ)\n        as [P2 [t2''' ht2''']].\n      destruct (change_type hg ht2''' (trans_Prod hΓ hA2' hB2')) as [tt2 htt2].\n      clear ht2''' t2''' P2.\n      assert (hqt : ∑ qt,\n        Σ ;;; Γ' |-i qt : sHeq (sProd n1 A1' B1') t1' (sProd n2 A2' B2') tt2\n      ).\n      { destruct ht1'' as [[[? ?] ?] ?].\n        destruct ht2'' as [[[? ?] ?] ?].\n        destruct ht1' as [[[? ?] ?] ?].\n        destruct ht2' as [[[? ?] ?] ?].\n        destruct htt2 as [[[? ?] ?] ?].\n        assert (r1 : t1' ∼ t1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq Γ' hg r1) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (r2 : t2'' ∼ tt2).\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq Γ' hg r2) as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans pl (optHeqTrans pt pr)).\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hqt as [qt hqt].\n      (* We then translate the arguments. *)\n      destruct (X2 _ hΓ)\n        as [A1'' [A1''' [u1'' [u2'' [pu h4']]]]].\n      destruct (eqtrans_trans hg h4') as [hu1'' hu2''].\n      destruct (change_type hg hu1'' hA1') as [u1' hu1'].\n      destruct h4' as [[[[[? ?] ?] ?] ?] hpu].\n      destruct (X8 _ hΓ) as [A2'' [u2''' hu2''']].\n      destruct (change_type hg hu2''' hA2') as [tu2 htu2].\n      clear hu2''' u2''' A2''.\n      assert (hqu : ∑ qu, Σ ;;; Γ' |-i qu : sHeq A1' u1' A2' tu2).\n      { destruct hu1'' as [[[? ?] ?] ?].\n        destruct hu2'' as [[[? ?] ?] ?].\n        destruct hu1' as [[[? ?] ?] ?].\n        destruct htu2 as [[[? ?] ?] ?].\n        assert (r1 : u1' ∼ u1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq Γ' hg r1) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (r2 : u2'' ∼ tu2).\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq Γ' hg r2) as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans pl (optHeqTrans pu pr)).\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hqu as [qu hqu].\n      (* We have an equality between Apps now *)\n      assert (happ : ∑ qapp,\n        Σ ;;; Γ' |-i qapp : sHeq (B1'{0 := u1'}) (sApp t1' A1' B1' u1')\n                                (B2'{0 := tu2}) (sApp tt2 A2' B2' tu2)\n      ).\n      { exists (optCongApp B1' B2' qt pA pB qu).\n        destruct hB1' as [[[? ?] ?] ?].\n        destruct hB2' as [[[? ?] ?] ?].\n        eapply opt_CongApp ; try eassumption.\n        cbn in hpB. rewrite <- llift_substProj, <- rlift_substProj in hpB.\n        rewrite !llift00, !rlift00 in hpB.\n        apply hpB.\n      }\n      destruct happ as [qapp happ].\n      (* Finally we translate the right App to put it in the left Prod *)\n      rename e into eA.\n      pose (e := sHeqTypeEq (B2' {0 := tu2}) (B1'{0 := u1'}) (optHeqSym qapp)).\n      pose (tapp := sTransport (B2' {0 := tu2}) (B1'{0 := u1'}) e (sApp tt2 A2' B2' tu2)).\n      (* We conclude *)\n      exists (B1'{0 := u1'}), (B1'{0 := u1'}).\n      exists (sApp t1' A1' B1' u1'), tapp.\n      exists (optHeqTrans qapp (optHeqTransport e (sApp tt2 A2' B2' tu2))).\n      destruct ht1' as [[[? ?] ?] ?].\n      destruct htt2 as [[[? ?] ?] ?].\n      destruct hu1' as [[[? ?] ?] ?].\n      destruct htu2 as [[[? ?] ?] ?].\n      destruct hA1' as [[[? ?] ?] ?].\n      destruct hA2' as [[[? ?] ?] ?].\n      destruct hB1' as [[[? ?] ?] ?].\n      destruct hB2' as [[[? ?] ?] ?].\n      repeat split.\n      * assumption.\n      * eapply inrel_subst ; assumption.\n      * eapply inrel_subst ; assumption.\n      * constructor ; assumption.\n      * constructor. constructor ; assumption.\n      * eapply opt_HeqTrans ; try eassumption.\n        eapply opt_HeqTransport ; try assumption.\n        -- eapply type_App ; eassumption.\n        -- eapply type_HeqTypeEq' ; try assumption.\n           ++ eapply opt_HeqSym ; eassumption.\n           ++ match goal with\n              | |- _ ;;; _ |-i _ : ?S =>\n                change S with (S {0 := tu2})\n              end.\n              eapply typing_subst ; eassumption.\n\n    (* cong_Sum *)\n    + (* The domains *)\n      destruct (X _ hΓ)\n        as [T1 [T2 [A1'' [A2'' [pA h1']]]]].\n      destruct (eqtrans_trans hg h1') as [hA1'' hA2''].\n      destruct h1' as [[[[[? ?] ?] ?] ?] hpA''].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th hA1'') as [T' [[A1' hA1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hA2'') as [T' [[A2' hA2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      (* Now the codomains *)\n      destruct (X0 _ (trans_snoc hΓ hA1'))\n        as [S1 [S2 [B1'' [B2'' [pB h2']]]]].\n      destruct (eqtrans_trans hg h2') as [hB1'' hB2''].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB1'') as [T' [[B1' hB1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hB2'') as [T' [[B2' hB2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      destruct h2' as [[[[[? ?] ?] ?] ?] hpB''].\n      (* Now we connect the paths for the domains *)\n      assert (hp1 : ∑ p1, Σ ;;; Γ' |-i p1 : sHeq (sSort s1) A1' (sSort s1) A2').\n      { destruct hA1' as [[_ eA1'] hA1'].\n        destruct hA1'' as [_ hA1''].\n        destruct hA2' as [[_ eA2'] hA2'].\n        destruct hA2'' as [_ hA2''].\n        assert (hr : A1' ∼ A1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [pl hpl].\n        assert (hr' : A2'' ∼ A2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr') as [pr hpr].\n        exists (optHeqTrans (optHeqTrans pl pA) pr).\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hp1 as [p1 hp1].\n      (* And then the paths for the codomains *)\n      pose (Γ1 := nil ,, A1').\n      pose (Γ2 := nil ,, A2').\n      pose (Γm := [ (sPack A1' A2') ]).\n      assert (hm : ismix Σ Γ' Γ1 Γ2 Γm).\n      { revert Γm.\n        replace A1' with (llift0 #|@nil sterm| A1')\n          by (cbn ; now rewrite llift00).\n        replace A2' with (rlift0 #|@nil sterm| A2')\n          by (cbn ; now rewrite rlift00).\n        intros.\n        destruct hA1' as [[? ?] ?].\n        destruct hA2' as [[? ?] ?].\n        econstructor.\n        - constructor.\n        - eassumption.\n        - assumption.\n      }\n      pose (Δ := Γ' ,,, Γm).\n      assert (hp2 : ∑ p2, Σ ;;; Γ' ,,, Γ1 |-i p2 : sHeq (sSort s2) B1'\n                                                       (sSort s2) B2').\n      { destruct hB1' as [[_ eB1'] hB1'].\n        destruct hB1'' as [_ hB1''].\n        destruct hB2' as [[_ eB2'] hB2'].\n        destruct hB2'' as [_ hB2''].\n        assert (hr : B1' ∼ B1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : B2'' ∼ B2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pB) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hp2 as [p2 hp2].\n      assert (hp3 : ∑ p3, Σ ;;; Δ |-i p3 : sHeq (sSort s2)\n                                               (llift0 #|Γm| B1')\n                                               (sSort s2)\n                                               (llift0 #|Γm| B2')\n             ).\n      { exists (llift0 #|Γm| p2).\n        match goal with\n        | |- _ ;;; _ |-i _ : ?T =>\n          change T with (llift0 #|Γm| (sHeq (sSort s2) B1' (sSort s2) B2'))\n        end.\n        eapply type_llift0 ; eassumption.\n      }\n      destruct hp3 as [p3 hp3].\n      (* Also translating the typing hypothesis for B2 *)\n      destruct (X2 _ (trans_snoc hΓ hA2'))\n        as [S' [B2''' hB2''']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB2''') as [T' [[tB2 htB2] hh]].\n      clear hB2''' B2''' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Now we can use the strong version of the lemma to build a path between\n         B2' and tB2 !\n       *)\n      assert (hp4 : ∑ p4, Σ ;;; Δ |-i p4 : sHeq (sSort s2) (llift0 #|Γm| B2')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { change (sSort s2) with (llift0 #|Γm| (sSort s2)) at 1.\n        change (sSort s2) with (rlift0 #|Γm| (sSort s2)) at 2.\n        assert (hr : B2' ∼ tB2).\n        { destruct htB2 as [[? ?] ?].\n          destruct hB2' as [[? ?] ?].\n          eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        edestruct (trel_to_heq' hg hr) as [p4 hp4].\n        exists p4. apply hp4.\n        - eassumption.\n        - destruct hB2' as [[? ?] ?]. assumption.\n        - destruct htB2 as [[? ?] ?]. assumption.\n      }\n      destruct hp4 as [p4 hp4].\n      (* This gives us a better path *)\n      assert (hp5 : ∑ p5, Σ ;;; Δ |-i p5 : sHeq (sSort s2) (llift0 #|Γm| B1')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { exists (optHeqTrans p3 p4).\n        eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hp5 as [p5 hp5].\n      (* We can finally conclude! *)\n      exists (sSort (Sorts.sum_sort s1 s2)), (sSort (Sorts.sum_sort s1 s2)).\n      exists (sSum n1 A1' B1'), (sSum n2 A2' tB2).\n      exists (sCongSum B1' tB2 p1 p5).\n      destruct hA1' as [[[? ?] ?] ?].\n      destruct hB1' as [[[? ?] ?] ?].\n      destruct hA2' as [[[? ?] ?] ?].\n      destruct htB2 as [[[? ?] ?] ?].\n      repeat split ; [ try constructor .. |].\n      all: try assumption.\n      eapply type_CongSum' ; try assumption.\n      cbn in hp5. rewrite <- llift_substProj, <- rlift_substProj in hp5.\n      rewrite !llift00, !rlift00 in hp5.\n      apply hp5.\n\n    (* cong_Pair *)\n    + (* The domains *)\n      destruct (X _ hΓ)\n        as [T1 [T2 [A1'' [A2'' [pA h1']]]]].\n      destruct (eqtrans_trans hg h1') as [hA1'' hA2''].\n      destruct h1' as [[[[[? ?] ?] ?] ?] hpA''].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th hA1'') as [T' [[A1' hA1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hA2'') as [T' [[A2' hA2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      (* Now the codomains *)\n      destruct (X0 _ (trans_snoc hΓ hA1'))\n        as [S1 [S2 [B1'' [B2'' [pB h2']]]]].\n      destruct (eqtrans_trans hg h2') as [hB1'' hB2''].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB1'') as [T' [[B1' hB1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hB2'') as [T' [[B2' hB2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      destruct h2' as [[[[[? ?] ?] ?] ?] hpB''].\n      (* Now we connect the paths for the domains *)\n      assert (hq1 : ∑ p1, Σ ;;; Γ' |-i p1 : sHeq (sSort s1) A1' (sSort s1) A2').\n      { destruct hA1' as [[_ eA1'] hA1'].\n        destruct hA1'' as [_ hA1''].\n        destruct hA2' as [[_ eA2'] hA2'].\n        destruct hA2'' as [_ hA2''].\n        assert (hr : A1' ∼ A1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : A2'' ∼ A2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pA) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hq1 as [q1 hq1].\n      (* And then the paths for the codomains *)\n      pose (Γ1 := nil ,, A1').\n      pose (Γ2 := nil ,, A2').\n      pose (Γm := [ sPack A1' A2' ]).\n      assert (hm : ismix Σ Γ' Γ1 Γ2 Γm).\n      { revert Γm.\n        replace A1' with (llift0 #|@nil sterm| A1')\n          by (cbn ; now rewrite llift00).\n        replace A2' with (rlift0 #|@nil sterm| A2')\n          by (cbn ; now rewrite rlift00).\n        intros.\n        destruct hA1' as [[? ?] ?].\n        destruct hA2' as [[? ?] ?].\n        econstructor.\n        - constructor.\n        - eassumption.\n        - assumption.\n      }\n      pose (Δ := Γ' ,,, Γm).\n      assert (hq2 : ∑ q2, Σ ;;; Γ' ,,, Γ1 |-i q2 : sHeq (sSort s2) B1'\n                                                       (sSort s2) B2').\n      { destruct hB1' as [[_ eB1'] hB1'].\n        destruct hB1'' as [_ hB1''].\n        destruct hB2' as [[_ eB2'] hB2'].\n        destruct hB2'' as [_ hB2''].\n        assert (hr : B1' ∼ B1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : B2'' ∼ B2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pB) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hq2 as [q2 hq2].\n      assert (hp3 : ∑ p3, Σ ;;; Δ |-i p3 : sHeq (sSort s2)\n                                               (llift0 #|Γm| B1')\n                                               (sSort s2)\n                                               (llift0 #|Γm| B2')\n             ).\n      { exists (llift0 #|Γm| q2).\n        match goal with\n        | |- _ ;;; _ |-i _ : ?T =>\n          change T with (llift0 #|Γm| (sHeq (sSort s2) B1' (sSort s2) B2'))\n        end.\n        eapply type_llift0 ; eassumption.\n      }\n      destruct hp3 as [p3 hp3].\n      (* Also translating the typing hypothesis for B2 *)\n      destruct (X4 _ (trans_snoc hΓ hA2'))\n        as [S' [B2''' hB2''']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB2''') as [T' [[tB2 htB2] hh]].\n      clear hB2''' B2''' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Now we can use the strong version of the lemma to build a path between\n         B2' and tB2 !\n       *)\n      assert (hp4 : ∑ p4, Σ ;;; Δ |-i p4 : sHeq (sSort s2) (llift0 #|Γm| B2')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { change (sSort s2) with (llift0 #|Γm| (sSort s2)) at 1.\n        change (sSort s2) with (rlift0 #|Γm| (sSort s2)) at 2.\n        assert (hr : B2' ∼ tB2).\n        { destruct htB2 as [[? ?] ?].\n          destruct hB2' as [[? ?] ?].\n          eapply trel_trans.\n          + eapply trel_sym. eapply inrel_trel. eassumption.\n          + apply inrel_trel. assumption.\n        }\n        edestruct (trel_to_heq' hg hr) as [p4 hp4].\n        exists p4. apply hp4.\n        - eassumption.\n        - destruct hB2' as [[? ?] ?]. assumption.\n        - destruct htB2 as [[? ?] ?]. assumption.\n      }\n      destruct hp4 as [p4 hp4].\n      (* This gives us a better path *)\n      assert (hp5 : ∑ p5, Σ ;;; Δ |-i p5 : sHeq (sSort s2) (llift0 #|Γm| B1')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { exists (optHeqTrans p3 p4).\n        eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hp5 as [p5 hp5].\n      (* Cleaning *)\n      clear hp4 p4 hp3 p3 hq2 q2.\n      clear hB2' B2' hB2'' hpB'' hB1'' hpA'' hA1'' hA2''.\n      (* clear i8 i7 i6 i5 i4 S1 S2 B1'' B2'' pB. *)\n      (* clear i3 i2 i1 i0 i T1 T2 A1'' A2'' pA. *)\n      clear pA pB pi2_1 pi2_2 A1'' A2''.\n      rename q1 into pA, p5 into pB, hq1 into hpA, hp5 into hpB.\n      rename tB2 into B2', htB2 into hB2'.\n      (* We can now translate the first components. *)\n      destruct (X1 _ hΓ)\n        as [P1 [P1' [u1'' [u2'' [pt h3']]]]].\n      destruct (eqtrans_trans hg h3') as [hu1'' hu2''].\n      destruct (change_type hg hu1'' hA1') as [u1' hu1'].\n      destruct (change_type hg hu2'' hA1') as [u2' hu2'].\n      destruct h3' as [[[[[? ?] ?] ?] ?] hpu].\n      destruct (X6 _ hΓ)\n        as [P2 [u2''' hu2''']].\n      destruct (change_type hg hu2''' hA2') as [tu2 htu2].\n      clear hu2''' u2''' P2.\n      assert (hqt : ∑ qt,\n        Σ ;;; Γ' |-i qt : sHeq A1' u1' A2' tu2\n      ).\n      { destruct hu1'' as [[[? ?] ?] ?].\n        destruct hu2'' as [[[? ?] ?] ?].\n        destruct hu1' as [[[? ?] ?] ?].\n        destruct hu2' as [[[? ?] ?] ?].\n        destruct htu2 as [[[? ?] ?] ?].\n        assert (r1 : u1' ∼ u1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq Γ' hg r1) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (r2 : u2'' ∼ tu2).\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq Γ' hg r2) as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans pl (optHeqTrans pt pr)).\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hqt as [qt hqt].\n      (* We can now translate the second components. *)\n      destruct (X2 _ hΓ)\n        as [Q1 [Q1' [v1'' [v2'' [pt' h3']]]]].\n      destruct (eqtrans_trans hg h3') as [hv1'' hv2''].\n      destruct (change_type hg hv1'' (trans_subst hg hΓ hB1' hu1'))\n        as [v1' hv1'].\n      destruct (change_type hg hv2'' (trans_subst hg hΓ hB1' hu1'))\n        as [v2' hv2'].\n      destruct h3' as [[[[[? ?] ?] ?] ?] hpv].\n      destruct (X8 _ hΓ)\n        as [Q2 [v2''' hv2''']].\n      destruct (change_type hg hv2''' (trans_subst hg hΓ hB2' htu2))\n        as [tv2 htv2].\n      clear hv2''' v2''' Q2.\n      assert (hqt' : ∑ qt,\n        Σ ;;; Γ' |-i qt : sHeq (B1'{0 := u1'}) v1' (B2'{0 := tu2}) tv2\n      ).\n      { destruct hv1'' as [[[? ?] ?] ?].\n        destruct hv2'' as [[[? ?] ?] ?].\n        destruct hv1' as [[[? ?] ?] ?].\n        destruct hv2' as [[[? ?] ?] ?].\n        destruct htv2 as [[[? ?] ?] ?].\n        assert (r1 : v1' ∼ v1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq Γ' hg r1) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (r2 : v2'' ∼ tv2).\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq Γ' hg r2) as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans pl (optHeqTrans pt' pr)).\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hqt' as [qt' hqt'].\n      (* We have an equality between Pairs now *)\n      assert (hpi : ∑ qpi,\n        Σ ;;; Γ' |-i qpi : sHeq (sSum n A1' B1') (sPair A1' B1' u1' v1')\n                               (sSum n A2' B2') (sPair A2' B2' tu2 tv2)\n      ).\n      { exists (sCongPair B1' B2' pA pB qt qt').\n        destruct hB1' as [[[? ?] ?] ?].\n        destruct hB2' as [[[? ?] ?] ?].\n        eapply type_CongPair' ; try eassumption.\n        cbn in hpB. rewrite <- llift_substProj, <- rlift_substProj in hpB.\n        rewrite !llift00, !rlift00 in hpB.\n        apply hpB.\n      }\n      destruct hpi as [qpi hpi].\n      (* Finally we translate the right Pair to put it in the left Sum *)\n      rename e into eA.\n      pose (e := sHeqTypeEq (sSum n A2' B2') (sSum n A1' B1') (optHeqSym qpi)).\n      pose (tpi := sTransport (sSum n A2' B2') (sSum n A1' B1') e (sPair A2' B2' tu2 tv2)).\n      (* We conclude *)\n      exists (sSum n A1' B1'), (sSum n A1' B1').\n      exists (sPair A1' B1' u1' v1'), tpi.\n      exists (optHeqTrans qpi (optHeqTransport e (sPair A2' B2' tu2 tv2))).\n      destruct hu1' as [[[? ?] ?] ?].\n      destruct htu2 as [[[? ?] ?] ?].\n      destruct hv1' as [[[? ?] ?] ?].\n      destruct htv2 as [[[? ?] ?] ?].\n      destruct hA1' as [[[? ?] ?] ?].\n      destruct hA2' as [[[? ?] ?] ?].\n      destruct hB1' as [[[? ?] ?] ?].\n      destruct hB2' as [[[? ?] ?] ?].\n      repeat split.\n      * assumption.\n      * constructor ; assumption.\n      * constructor ; assumption.\n      * constructor ; assumption.\n      * constructor. constructor ; assumption.\n      * eapply opt_HeqTrans ; try eassumption.\n        eapply opt_HeqTransport ; try assumption.\n        -- eapply type_Pair' ; eassumption.\n        -- eapply type_HeqTypeEq' ; try assumption.\n           ++ eapply opt_HeqSym ; eassumption.\n           ++ eapply type_Sum ; eassumption.\n\n    (* cong_Pi1 *)\n    + (* The domains *)\n      destruct (X0 _ hΓ)\n        as [T1 [T2 [A1'' [A2'' [pA h1']]]]].\n      destruct (eqtrans_trans hg h1') as [hA1'' hA2''].\n      destruct h1' as [[[[[? ?] ?] ?] ?] hpA''].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th hA1'') as [T' [[A1' hA1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hA2'') as [T' [[A2' hA2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      (* Now the codomains *)\n      destruct (X1 _ (trans_snoc hΓ hA1'))\n        as [S1 [S2 [B1'' [B2'' [pB h2']]]]].\n      destruct (eqtrans_trans hg h2') as [hB1'' hB2''].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB1'') as [T' [[B1' hB1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hB2'') as [T' [[B2' hB2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      destruct h2' as [[[[[? ?] ?] ?] ?] hpB''].\n      (* Now we connect the paths for the domains *)\n      assert (hq1 : ∑ p1, Σ ;;; Γ' |-i p1 : sHeq (sSort s1) A1' (sSort s1) A2').\n      { destruct hA1' as [[_ eA1'] hA1'].\n        destruct hA1'' as [_ hA1''].\n        destruct hA2' as [[_ eA2'] hA2'].\n        destruct hA2'' as [_ hA2''].\n        assert (hr : A1' ∼ A1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : A2'' ∼ A2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pA) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hq1 as [q1 hq1].\n      (* And then the paths for the codomains *)\n      pose (Γ1 := nil ,, A1').\n      pose (Γ2 := nil ,, A2').\n      pose (Γm := [ sPack A1' A2' ]).\n      assert (hm : ismix Σ Γ' Γ1 Γ2 Γm).\n      { revert Γm.\n        replace A1' with (llift0 #|@nil sterm| A1')\n          by (cbn ; now rewrite llift00).\n        replace A2' with (rlift0 #|@nil sterm| A2')\n          by (cbn ; now rewrite rlift00).\n        intros.\n        destruct hA1' as [[? ?] ?].\n        destruct hA2' as [[? ?] ?].\n        econstructor.\n        - constructor.\n        - eassumption.\n        - assumption.\n      }\n      pose (Δ := Γ' ,,, Γm).\n      assert (hq2 : ∑ q2, Σ ;;; Γ' ,,, Γ1 |-i q2 : sHeq (sSort s2) B1'\n                                                       (sSort s2) B2').\n      { destruct hB1' as [[_ eB1'] hB1'].\n        destruct hB1'' as [_ hB1''].\n        destruct hB2' as [[_ eB2'] hB2'].\n        destruct hB2'' as [_ hB2''].\n        assert (hr : B1' ∼ B1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : B2'' ∼ B2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pB) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hq2 as [q2 hq2].\n      assert (hp3 : ∑ p3, Σ ;;; Δ |-i p3 : sHeq (sSort s2)\n                                               (llift0 #|Γm| B1')\n                                               (sSort s2)\n                                               (llift0 #|Γm| B2')\n             ).\n      { exists (llift0 #|Γm| q2).\n        match goal with\n        | |- _ ;;; _ |-i _ : ?T =>\n          change T with (llift0 #|Γm| (sHeq (sSort s2) B1' (sSort s2) B2'))\n        end.\n        eapply type_llift0 ; eassumption.\n      }\n      destruct hp3 as [p3 hp3].\n      (* Also translating the typing hypothesis for B2 *)\n      destruct (X3 _ (trans_snoc hΓ hA2'))\n        as [S' [B2''' hB2''']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB2''') as [T' [[tB2 htB2] hh]].\n      clear hB2''' B2''' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Now we can use the strong version of the lemma to build a path between\n         B2' and tB2 !\n       *)\n      assert (hp4 : ∑ p4, Σ ;;; Δ |-i p4 : sHeq (sSort s2) (llift0 #|Γm| B2')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { change (sSort s2) with (llift0 #|Γm| (sSort s2)) at 1.\n        change (sSort s2) with (rlift0 #|Γm| (sSort s2)) at 2.\n        assert (hr : B2' ∼ tB2).\n        { destruct htB2 as [[? ?] ?].\n          destruct hB2' as [[? ?] ?].\n          eapply trel_trans.\n          + eapply trel_sym. eapply inrel_trel. eassumption.\n          + apply inrel_trel. assumption.\n        }\n        edestruct (trel_to_heq' hg hr) as [p4 hp4].\n        exists p4. apply hp4.\n        - eassumption.\n        - destruct hB2' as [[? ?] ?]. assumption.\n        - destruct htB2 as [[? ?] ?]. assumption.\n      }\n      destruct hp4 as [p4 hp4].\n      (* This gives us a better path *)\n      assert (hp5 : ∑ p5, Σ ;;; Δ |-i p5 : sHeq (sSort s2) (llift0 #|Γm| B1')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { exists (optHeqTrans p3 p4).\n        eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hp5 as [p5 hp5].\n      (* Cleaning *)\n      clear hp4 p4 hp3 p3 hq2 q2.\n      clear hB2' B2' hB2'' hpB'' hB1'' hpA'' hA1'' hA2''.\n      (* clear i8 i7 i6 i5 i4 S1 S2 B1'' B2'' pB. *)\n      (* clear i3 i2 i1 i0 i T1 T2 A1'' A2'' pA. *)\n      clear pA pB pi2_1 pi2_2 A1'' A2''.\n      rename q1 into pA, p5 into pB, hq1 into hpA, hp5 into hpB.\n      rename tB2 into B2', htB2 into hB2'.\n      (* We can now translate the pairs. *)\n      destruct (X _ hΓ)\n        as [P1 [P1' [p1'' [p2'' [pt h3']]]]].\n      destruct (eqtrans_trans hg h3') as [hp1'' hp2''].\n      destruct (change_type hg hp1'' (trans_Sum hΓ hA1' hB1')) as [p1' hp1'].\n      destruct (change_type hg hp2'' (trans_Sum hΓ hA1' hB1')) as [p2' hp2'].\n      destruct h3' as [[[[[? ?] ?] ?] ?] hpt].\n      destruct (X5 _ hΓ)\n        as [P2 [p2''' hp2''']].\n      destruct (change_type hg hp2''' (trans_Sum hΓ hA2' hB2')) as [tp2 htp2].\n      clear hp2''' p2''' P2.\n      assert (hqt : ∑ qt,\n        Σ ;;; Γ' |-i qt : sHeq (sSum nx A1' B1') p1' (sSum ny A2' B2') tp2\n      ).\n      { destruct hp1'' as [[[? ?] ?] ?].\n        destruct hp2'' as [[[? ?] ?] ?].\n        destruct hp1' as [[[? ?] ?] ?].\n        destruct hp2' as [[[? ?] ?] ?].\n        destruct htp2 as [[[? ?] ?] ?].\n        assert (r1 : p1' ∼ p1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq Γ' hg r1) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (r2 : p2'' ∼ tp2).\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq Γ' hg r2) as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans pl (optHeqTrans pt pr)).\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hqt as [qt hqt].\n      (* We have an equality between Pi1s now *)\n      assert (hpi : ∑ qpi,\n        Σ ;;; Γ' |-i qpi : sHeq A1' (sPi1 A1' B1' p1')\n                               A2' (sPi1 A2' B2' tp2)\n      ).\n      { exists (sCongPi1 B1' B2' pA pB qt).\n        destruct hB1' as [[[? ?] ?] ?].\n        destruct hB2' as [[[? ?] ?] ?].\n        eapply type_CongPi1' ; try eassumption.\n        cbn in hpB. rewrite <- llift_substProj, <- rlift_substProj in hpB.\n        rewrite !llift00, !rlift00 in hpB.\n        apply hpB.\n      }\n      destruct hpi as [qpi hpi].\n      (* Finally we translate the right Pi1 to put it in the left Sum *)\n      rename e into eA.\n      pose (e := sHeqTypeEq A2' A1' (optHeqSym qpi)).\n      pose (tpi := sTransport A2' A1' e (sPi1 A2' B2' tp2)).\n      (* We conclude *)\n      exists A1', A1'.\n      exists (sPi1 A1' B1' p1'), tpi.\n      exists (optHeqTrans qpi (optHeqTransport e (sPi1 A2' B2' tp2))).\n      destruct hp1' as [[[? ?] ?] ?].\n      destruct htp2 as [[[? ?] ?] ?].\n      destruct hA1' as [[[? ?] ?] ?].\n      destruct hA2' as [[[? ?] ?] ?].\n      destruct hB1' as [[[? ?] ?] ?].\n      destruct hB2' as [[[? ?] ?] ?].\n      repeat split.\n      * assumption.\n      * assumption.\n      * assumption.\n      * constructor ; assumption.\n      * constructor. constructor ; assumption.\n      * eapply opt_HeqTrans ; try eassumption.\n        eapply opt_HeqTransport ; try assumption.\n        -- eapply type_Pi1' ; eassumption.\n        -- eapply type_HeqTypeEq' ; try assumption.\n           ++ eapply opt_HeqSym ; eassumption.\n           ++ eassumption.\n\n    (* cong_Pi2 *)\n    + (* The domains *)\n      destruct (X0 _ hΓ)\n        as [T1 [T2 [A1'' [A2'' [pA h1']]]]].\n      destruct (eqtrans_trans hg h1') as [hA1'' hA2''].\n      destruct h1' as [[[[[? ?] ?] ?] ?] hpA''].\n      assert (th : type_head (head (sSort s1))) by constructor.\n      destruct (choose_type hg th hA1'') as [T' [[A1' hA1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hA2'') as [T' [[A2' hA2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      (* Now the codomains *)\n      destruct (X1 _ (trans_snoc hΓ hA1'))\n        as [S1 [S2 [B1'' [B2'' [pB h2']]]]].\n      destruct (eqtrans_trans hg h2') as [hB1'' hB2''].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB1'') as [T' [[B1' hB1'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh.\n      destruct (choose_type hg th hB2'') as [T' [[B2' hB2'] hh]].\n      destruct T' ; inversion hh. subst.\n      clear hh th.\n      destruct h2' as [[[[[? ?] ?] ?] ?] hpB''].\n      (* Now we connect the paths for the domains *)\n      assert (hq1 : ∑ p1, Σ ;;; Γ' |-i p1 : sHeq (sSort s1) A1' (sSort s1) A2').\n      { destruct hA1' as [[_ eA1'] hA1'].\n        destruct hA1'' as [_ hA1''].\n        destruct hA2' as [[_ eA2'] hA2'].\n        destruct hA2'' as [_ hA2''].\n        assert (hr : A1' ∼ A1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : A2'' ∼ A2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pA) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hq1 as [q1 hq1].\n      (* And then the paths for the codomains *)\n      pose (Γ1 := nil ,, A1').\n      pose (Γ2 := nil ,, A2').\n      pose (Γm := [ sPack A1' A2' ]).\n      assert (hm : ismix Σ Γ' Γ1 Γ2 Γm).\n      { revert Γm.\n        replace A1' with (llift0 #|@nil sterm| A1')\n          by (cbn ; now rewrite llift00).\n        replace A2' with (rlift0 #|@nil sterm| A2')\n          by (cbn ; now rewrite rlift00).\n        intros.\n        destruct hA1' as [[? ?] ?].\n        destruct hA2' as [[? ?] ?].\n        econstructor.\n        - constructor.\n        - eassumption.\n        - assumption.\n      }\n      pose (Δ := Γ' ,,, Γm).\n      assert (hq2 : ∑ q2, Σ ;;; Γ' ,,, Γ1 |-i q2 : sHeq (sSort s2) B1'\n                                                       (sSort s2) B2').\n      { destruct hB1' as [[_ eB1'] hB1'].\n        destruct hB1'' as [_ hB1''].\n        destruct hB2' as [[_ eB2'] hB2'].\n        destruct hB2'' as [_ hB2''].\n        assert (hr : B1' ∼ B1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (hr' : B2'' ∼ B2').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq (Γ',, A1') hg hr') as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans (optHeqTrans pl pB) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hq2 as [q2 hq2].\n      assert (hp3 : ∑ p3, Σ ;;; Δ |-i p3 : sHeq (sSort s2)\n                                               (llift0 #|Γm| B1')\n                                               (sSort s2)\n                                               (llift0 #|Γm| B2')\n             ).\n      { exists (llift0 #|Γm| q2).\n        match goal with\n        | |- _ ;;; _ |-i _ : ?T =>\n          change T with (llift0 #|Γm| (sHeq (sSort s2) B1' (sSort s2) B2'))\n        end.\n        eapply type_llift0 ; eassumption.\n      }\n      destruct hp3 as [p3 hp3].\n      (* Also translating the typing hypothesis for B2 *)\n      destruct (X3 _ (trans_snoc hΓ hA2'))\n        as [S' [B2''' hB2''']].\n      assert (th : type_head (head (sSort s2))) by constructor.\n      destruct (choose_type hg th hB2''') as [T' [[tB2 htB2] hh]].\n      clear hB2''' B2''' S'.\n      destruct T' ; inversion hh. subst. clear hh th.\n      (* Now we can use the strong version of the lemma to build a path between\n         B2' and tB2 !\n       *)\n      assert (hp4 : ∑ p4, Σ ;;; Δ |-i p4 : sHeq (sSort s2) (llift0 #|Γm| B2')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { change (sSort s2) with (llift0 #|Γm| (sSort s2)) at 1.\n        change (sSort s2) with (rlift0 #|Γm| (sSort s2)) at 2.\n        assert (hr : B2' ∼ tB2).\n        { destruct htB2 as [[? ?] ?].\n          destruct hB2' as [[? ?] ?].\n          eapply trel_trans.\n          + eapply trel_sym. eapply inrel_trel. eassumption.\n          + apply inrel_trel. assumption.\n        }\n        edestruct (trel_to_heq' hg hr) as [p4 hp4].\n        exists p4. apply hp4.\n        - eassumption.\n        - destruct hB2' as [[? ?] ?]. assumption.\n        - destruct htB2 as [[? ?] ?]. assumption.\n      }\n      destruct hp4 as [p4 hp4].\n      (* This gives us a better path *)\n      assert (hp5 : ∑ p5, Σ ;;; Δ |-i p5 : sHeq (sSort s2) (llift0 #|Γm| B1')\n                                               (sSort s2) (rlift0 #|Γm| tB2)\n             ).\n      { exists (optHeqTrans p3 p4).\n        eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hp5 as [p5 hp5].\n      (* Cleaning *)\n      clear hp4 p4 hp3 p3 hq2 q2.\n      clear hB2' B2' hB2'' hpB'' hB1'' hpA'' hA1'' hA2''.\n      (* clear i8 i7 i6 i5 i4 S1 S2 B1'' B2'' pB. *)\n      (* clear i3 i2 i1 i0 i T1 T2 A1'' A2'' pA. *)\n      clear pA pB pi2_1 pi2_2 A1'' A2''.\n      rename q1 into pA, p5 into pB, hq1 into hpA, hp5 into hpB.\n      rename tB2 into B2', htB2 into hB2'.\n      (* We can now translate the pairs. *)\n      destruct (X _ hΓ)\n        as [P1 [P1' [p1'' [p2'' [pt h3']]]]].\n      destruct (eqtrans_trans hg h3') as [hp1'' hp2''].\n      destruct (change_type hg hp1'' (trans_Sum hΓ hA1' hB1')) as [p1' hp1'].\n      destruct (change_type hg hp2'' (trans_Sum hΓ hA1' hB1')) as [p2' hp2'].\n      destruct h3' as [[[[[? ?] ?] ?] ?] hpt].\n      destruct (X5 _ hΓ)\n        as [P2 [p2''' hp2''']].\n      destruct (change_type hg hp2''' (trans_Sum hΓ hA2' hB2')) as [tp2 htp2].\n      clear hp2''' p2''' P2.\n      assert (hqt : ∑ qt,\n        Σ ;;; Γ' |-i qt : sHeq (sSum nx A1' B1') p1' (sSum ny A2' B2') tp2\n      ).\n      { destruct hp1'' as [[[? ?] ?] ?].\n        destruct hp2'' as [[[? ?] ?] ?].\n        destruct hp1' as [[[? ?] ?] ?].\n        destruct hp2' as [[[? ?] ?] ?].\n        destruct htp2 as [[[? ?] ?] ?].\n        assert (r1 : p1' ∼ p1'').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq Γ' hg r1) as [pl hpl].\n        specialize (hpl _ _ ltac:(eassumption) ltac:(eassumption)).\n        assert (r2 : p2'' ∼ tp2).\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - apply inrel_trel. assumption.\n        }\n        destruct (trel_to_heq Γ' hg r2) as [pr hpr].\n        specialize (hpr _ _ ltac:(eassumption) ltac:(eassumption)).\n        exists (optHeqTrans pl (optHeqTrans pt pr)).\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hqt as [qt hqt].\n      (* We have an equality between Pi1s now *)\n      assert (hpi : ∑ qpi,\n        Σ ;;; Γ' |-i qpi : sHeq (B1'{ 0 := sPi1 A1' B1' p1' }) (sPi2 A1' B1' p1')\n                               (B2'{ 0 := sPi1 A2' B2' tp2 }) (sPi2 A2' B2' tp2)\n      ).\n      { exists (sCongPi2 B1' B2' pA pB qt).\n        destruct hB1' as [[[? ?] ?] ?].\n        destruct hB2' as [[[? ?] ?] ?].\n        eapply type_CongPi2' ; try eassumption.\n        cbn in hpB. rewrite <- llift_substProj, <- rlift_substProj in hpB.\n        rewrite !llift00, !rlift00 in hpB.\n        apply hpB.\n      }\n      destruct hpi as [qpi hpi].\n      (* Finally we translate the right Pi1 to put it in the left Sum *)\n      rename e into eA.\n      pose (e := sHeqTypeEq (B2' {0 := sPi1 A2' B2' tp2}) (B1' {0 := sPi1 A1' B1' p1'}) (optHeqSym qpi)).\n      pose (tpi := sTransport (B2' {0 := sPi1 A2' B2' tp2}) (B1' {0 := sPi1 A1' B1' p1'}) e (sPi2 A2' B2' tp2)).\n      (* We conclude *)\n      exists (B1'{ 0 := sPi1 A1' B1' p1' }), (B1'{ 0 := sPi1 A1' B1' p1' }).\n      exists (sPi2 A1' B1' p1'), tpi.\n      exists (optHeqTrans qpi (optHeqTransport e (sPi2 A2' B2' tp2))).\n      destruct hp1' as [[[? ?] ?] ?].\n      destruct htp2 as [[[? ?] ?] ?].\n      destruct hA1' as [[[? ?] ?] ?].\n      destruct hA2' as [[[? ?] ?] ?].\n      destruct hB1' as [[[? ?] ?] ?].\n      destruct hB2' as [[[? ?] ?] ?].\n      repeat split.\n      * assumption.\n      * apply inrel_subst ; try assumption.\n        constructor ; assumption.\n      * apply inrel_subst ; try assumption.\n        constructor ; assumption.\n      * constructor ; assumption.\n      * constructor. constructor ; assumption.\n      * eapply opt_HeqTrans ; try eassumption.\n        eapply opt_HeqTransport ; try assumption.\n        -- eapply type_Pi2' ; eassumption.\n        -- eapply type_HeqTypeEq' ; try assumption.\n           ++ eapply opt_HeqSym ; eassumption.\n           ++ lift_sort. eapply typing_subst ; try eassumption.\n              eapply type_Pi1' ; eassumption.\n\n    (* cong_Eq *)\n    + destruct (X _ hΓ)\n        as [T1 [T2 [A1' [A2' [pA h1']]]]].\n      destruct (X0 _ hΓ)\n        as [A1'' [A1''' [u1' [u2' [pu h2']]]]].\n      destruct (X1 _ hΓ)\n        as [A1'''' [A1''''' [v1' [v2' [pv h3']]]]].\n      destruct (eqtrans_trans hg h1') as [hA1' hA2'].\n      destruct (eqtrans_trans hg h2') as [hu1' hu2'].\n      destruct (eqtrans_trans hg h3') as [hv1' hv2'].\n      destruct h1' as [[[[[? ?] ?] ?] ?] hpA].\n      destruct h2' as [[[[[? ?] ?] ?] ?] hpu].\n      destruct h3' as [[[[[? ?] ?] ?] ?] hpv].\n      (* We need to chain translations a lot to use sCongEq *)\n      assert (th : type_head (head (sSort s))) by constructor.\n      destruct (choose_type hg th hA1') as [T' [[tA1 htA1] hh]].\n      destruct T' ; inversion hh. subst.\n      clear th hh.\n      assert (th : type_head (head (sSort s))) by constructor.\n      destruct (choose_type hg th hA2') as [T' [[tA2 htA2] hh]].\n      destruct T' ; inversion hh. subst.\n      clear th hh.\n      (* For the types we build the missing hequalities *)\n      assert (hp : ∑ p, Σ ;;; Γ' |-i p : sHeq (sSort s) tA1 (sSort s) tA2).\n      { destruct hA1' as [_ hA1'].\n        destruct htA1 as [[[? ?] ?] htA1].\n        assert (sim1 : tA1 ∼ A1').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg sim1) as [p1 hp1].\n        specialize (hp1 _ _  htA1 hA1').\n        destruct hA2' as [_ hA2'].\n        destruct htA2 as [[[? ?] ?] htA2].\n        assert (sim2 : A2' ∼ tA2).\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg sim2) as [p2 hp2].\n        specialize (hp2 _ _ hA2' htA2).\n        exists (optHeqTrans p1 (optHeqTrans pA p2)).\n        eapply opt_HeqTrans ; try eassumption.\n        eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hp as [qA hqA].\n      (* Now we need to do the same for the terms *)\n      destruct (change_type hg hu1' htA1) as [tu1 htu1].\n      destruct (change_type hg hu2' htA1) as [tu2 htu2].\n      destruct (change_type hg hv1' htA1) as [tv1 htv1].\n      destruct (change_type hg hv2' htA1) as [tv2 htv2].\n      assert (hqu : ∑ qu, Σ ;;; Γ' |-i qu : sHeq tA1 tu1 tA1 tu2).\n      { destruct hu1' as [_ hu1'].\n        destruct htu1 as [[[? ?] ?] htu1].\n        assert (sim1 : tu1 ∼ u1').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg sim1) as [pl hpl].\n        specialize (hpl _ _ htu1 hu1').\n        destruct hu2' as [_ hu2'].\n        destruct htu2 as [[[? ?] ?] htu2].\n        assert (sim2 : u2' ∼ tu2).\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg sim2) as [pr hpr].\n        specialize (hpr _ _ hu2' htu2).\n        exists (optHeqTrans (optHeqTrans pl pu) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hqu as [qu hqu].\n      assert (hqv : ∑ qv, Σ ;;; Γ' |-i qv : sHeq tA1 tv1 tA1 tv2).\n      { destruct hv1' as [_ hv1'].\n        destruct htv1 as [[[? ?] ?] htv1].\n        assert (sim1 : tv1 ∼ v1').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg sim1) as [pl hpl].\n        specialize (hpl _ _ htv1 hv1').\n        destruct hv2' as [_ hv2'].\n        destruct htv2 as [[[? ?] ?] htv2].\n        assert (sim2 : v2' ∼ tv2).\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg sim2) as [pr hpr].\n        specialize (hpr _ _ hv2' htv2).\n        exists (optHeqTrans (optHeqTrans pl pv) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hqv as [qv hqv].\n      (* We move terms back into tA2 *)\n      destruct (opt_sort_heq_ex hg hqA) as [eA heA].\n      pose (ttu2 := sTransport tA1 tA2 eA tu2).\n      assert (hq : ∑ q, Σ ;;; Γ' |-i q : sHeq tA1 tu1 tA2 ttu2).\n      { exists (optHeqTrans qu (optHeqTransport eA tu2)).\n        destruct htu2 as [[[? ?] ?] ?].\n        destruct htA1 as [[[? ?] ?] ?].\n        destruct htA2 as [[[? ?] ?] ?].\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTransport ; eassumption.\n      }\n      destruct hq as [qu' hqu'].\n      pose (ttv2 := sTransport tA1 tA2 eA tv2).\n      assert (hq : ∑ q, Σ ;;; Γ' |-i q : sHeq tA1 tv1 tA2 ttv2).\n      { exists (optHeqTrans qv (optHeqTransport eA tv2)).\n        destruct htv2 as [[[? ?] ?] ?].\n        destruct htA1 as [[[? ?] ?] ?].\n        destruct htA2 as [[[? ?] ?] ?].\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTransport ; eassumption.\n      }\n      destruct hq as [qv' hqv'].\n      exists (sSort (Sorts.eq_sort s)), (sSort (Sorts.eq_sort s)).\n      exists (sEq tA1 tu1 tv1), (sEq tA2 ttu2 ttv2).\n      exists (optCongEq qA qu' qv').\n      destruct htu1 as [[[? ?] ?] ?].\n      destruct htu2 as [[[? ?] ?] ?].\n      destruct htA1 as [[[? ?] ?] ?].\n      destruct htA2 as [[[? ?] ?] ?].\n      destruct htv1 as [[[? ?] ?] ?].\n      destruct htv2 as [[[? ?] ?] ?].\n      repeat split ; try eassumption.\n      * econstructor ; assumption.\n      * econstructor ; assumption.\n      * econstructor ; assumption.\n      * econstructor ; try assumption.\n        -- econstructor ; eassumption.\n        -- econstructor ; eassumption.\n      * eapply opt_CongEq ; assumption.\n\n    (* cong_Refl *)\n    + destruct (X _ hΓ)\n        as [T1 [T2 [A1' [A2' [pA h1']]]]].\n      destruct (X0 _ hΓ)\n        as [A1'' [A1''' [u1' [u2' [pu h2']]]]].\n      destruct (eqtrans_trans hg h1') as [hA1' hA2'].\n      destruct (eqtrans_trans hg h2') as [hu1' hu2'].\n      destruct h1' as [[[[[? ?] ?] ?] ?] hpA].\n      destruct h2' as [[[[[? ?] ?] ?] ?] hpu].\n      (* The types *)\n      assert (th : type_head (head (sSort s))) by constructor.\n      destruct (choose_type hg th hA1') as [T' [[tA1 htA1] hh]].\n      destruct T' ; inversion hh. subst.\n      clear th hh.\n      assert (th : type_head (head (sSort s))) by constructor.\n      destruct (choose_type hg th hA2') as [T' [[tA2 htA2] hh]].\n      destruct T' ; inversion hh. subst.\n      clear th hh.\n      assert (hp : ∑ p, Σ ;;; Γ' |-i p : sHeq (sSort s) tA1 (sSort s) tA2).\n      { destruct hA1' as [_ hA1'].\n        destruct htA1 as [[[? ?] ?] htA1].\n        assert (sim1 : tA1 ∼ A1').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg sim1) as [p1 hp1].\n        specialize (hp1 _ _ htA1 hA1').\n        destruct hA2' as [_ hA2'].\n        destruct htA2 as [[[? ?] ?] htA2].\n        assert (sim2 : A2' ∼ tA2).\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg sim2) as [p2 hp2].\n        specialize (hp2 _ _ hA2' htA2).\n        exists (optHeqTrans p1 (optHeqTrans pA p2)).\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTrans ; eassumption.\n      }\n      destruct hp as [qA hqA].\n      (* The terms *)\n      destruct (change_type hg hu1' htA1) as [tu1 htu1].\n      destruct (change_type hg hu2' htA1) as [tu2 htu2].\n      assert (hqu : ∑ qu, Σ ;;; Γ' |-i qu : sHeq tA1 tu1 tA1 tu2).\n      { destruct hu1' as [_ hu1'].\n        destruct htu1 as [[[? ?] ?] htu1].\n        assert (sim1 : tu1 ∼ u1').\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg sim1) as [pl hpl].\n        specialize (hpl _ _ htu1 hu1').\n        destruct hu2' as [_ hu2'].\n        destruct htu2 as [[[? ?] ?] htu2].\n        assert (sim2 : u2' ∼ tu2).\n        { eapply trel_trans.\n          - eapply trel_sym. eapply inrel_trel. eassumption.\n          - eapply inrel_trel. eassumption.\n        }\n        destruct (trel_to_heq Γ' hg sim2) as [pr hpr].\n        specialize (hpr _ _ hu2' htu2).\n        exists (optHeqTrans (optHeqTrans pl pu) pr).\n        eapply opt_HeqTrans ; try assumption.\n        - eapply opt_HeqTrans ; eassumption.\n        - eassumption.\n      }\n      destruct hqu as [qu hqu].\n      (* tu2 isn't in the right place, so we need to chain one last equality. *)\n      destruct (opt_sort_heq_ex hg hqA) as [eA heA].\n      pose (ttu2 := sTransport tA1 tA2 eA tu2).\n      assert (hq : ∑ q, Σ ;;; Γ' |-i q : sHeq tA1 tu1 tA2 ttu2).\n      { exists (optHeqTrans qu (optHeqTransport eA tu2)).\n        destruct htu2 as [[[? ?] ?] ?].\n        destruct htA1 as [[[? ?] ?] ?].\n        destruct htA2 as [[[? ?] ?] ?].\n        eapply opt_HeqTrans ; try assumption.\n        - eassumption.\n        - eapply opt_HeqTransport ; eassumption.\n      }\n      destruct hq as [q hq].\n      (* We're still not there yet as we need to have two translations of the\n         same type. *)\n      assert (pE : ∑ pE, Σ ;;; Γ' |-i pE :\n                         sHeq (sSort (Sorts.eq_sort s)) (sEq tA2 ttu2 ttu2)\n                              (sSort (Sorts.eq_sort s)) (sEq tA1 tu1 tu1)).\n      { exists (optHeqSym (optCongEq qA q q)).\n        eapply opt_HeqSym ; try assumption.\n        eapply opt_CongEq ; eassumption.\n      }\n      destruct pE as [pE hpE].\n      assert (eE : ∑ eE, Σ ;;; Γ' |-i eE :\n                         sEq (sSort (Sorts.eq_sort s)) (sEq tA2 ttu2 ttu2)\n                             (sEq tA1 tu1 tu1)).\n      { eapply (opt_sort_heq_ex hg hpE). }\n      destruct eE as [eE hE].\n      pose (trefl2 := sTransport (sEq tA2 ttu2 ttu2)\n                                 (sEq tA1 tu1 tu1)\n                                 eE (sRefl tA2 ttu2)\n           ).\n      exists (sEq tA1 tu1 tu1), (sEq tA1 tu1 tu1).\n      exists (sRefl tA1 tu1), trefl2.\n      exists (optHeqTrans (optCongRefl qA q) (optHeqTransport eE (sRefl tA2 ttu2))).\n      destruct htu1 as [[[? ?] ?] ?].\n      destruct htu2 as [[[? ?] ?] ?].\n      destruct htA1 as [[[? ?] ?] ?].\n      destruct htA2 as [[[? ?] ?] ?].\n      repeat split.\n      all: try assumption.\n      all: try (econstructor ; eassumption).\n      * econstructor. econstructor.\n        -- assumption.\n        -- econstructor. assumption.\n      * eapply opt_HeqTrans ; try assumption.\n        -- eapply opt_CongRefl ; eassumption.\n        -- eapply opt_HeqTransport ; try assumption.\n           ++ eapply type_Refl' ; try assumption.\n              eapply type_Transport' ; eassumption.\n           ++ eassumption.\n\n    (* reflection *)\n    + destruct (X _ hΓ) as [T' [e'' he'']].\n      assert (th : type_head (head (sEq A u v))) by constructor.\n      destruct (choose_type hg th he'') as [T'' [[e' he'] hh]].\n      destruct T'' ; try (now inversion hh).\n      rename T''1 into A', T''2 into u', T''3 into v'.\n      clear hh he'' e'' he'' T' th.\n      destruct he' as [[[? ieq] ?] he'].\n      exists A', A', u', v'.\n      exists (optEqToHeq e').\n      inversion ieq. subst.\n      repeat split ; try eassumption.\n      destruct (istype_type hg he') as [? heq].\n      ttinv heq.\n      eapply opt_EqToHeq ; assumption.\n\n    (* eq_alpha *)\n    + destruct (X _ hΓ) as [A' [u' hu']].\n      destruct hu' as [[[? ?] ?] hu'].\n      exists A', A', u', u', (sHeqRefl A' u').\n      repeat split ; try assumption.\n      * eapply inrel_nl ; eassumption.\n      * destruct (istype_type hg hu') as [s' hA'].\n        eapply type_HeqRefl ; eassumption.\n\n  Unshelve. all: try exact 0.\n\nDefined.\n\nTheorem context_translation {Σ} :\n  type_glob Σ ->\n  forall Γ (h : XTyping.wf Σ Γ), ∑ Γ', Σ |--i Γ' ∈ ⟦ Γ ⟧.\nProof.\n  intros hg Γ h. induction h.\n  (* wf_nil *)\n  + exists nil. split ; constructor.\n\n  (* wf_snoc *)\n  + destruct IHh as [Γ' hΓ'].\n    rename t into hA.\n    destruct (fst (complete_translation hg) _ _ _ hA _ hΓ') as [T [A' hA']].\n    assert (th : type_head (head (sSort s))) by constructor.\n    destruct (choose_type hg th hA') as [T' [[A'' hA''] hh]].\n    destruct T' ; try (now inversion hh).\n    exists (Γ' ,, A''). now eapply trans_snoc.\nDefined.\n\nEnd Translation.\n\nSection Conservativity.\n\nContext `{Sort_notion : Sorts.notion}.\n\nCorollary conservativity :\n  forall {Σ t A s},\n    type_glob Σ ->\n    Xcomp A ->\n    Σ ;;; [] |-i A : sSort s ->\n    Σ ;;; [] |-x t : A ->\n    ∑ t', Σ ;;; [] |-i t' : A.\nProof.\n  intros Σ t A s hg xA hA ht.\n  assert (h' : Σ ;;;; [] ⊢ [ A ] : sSort s\n             ∈ ⟦ [] ⊢ [ A ] : sSort s ⟧).\n  { repeat split.\n    - constructor.\n    - constructor.\n    - apply inrel_refl. assumption.\n    - assumption.\n  }\n  destruct (complete_translation hg) as [thm _].\n  destruct (thm _ _ _ ht [] ltac:(repeat constructor)) as [A' [t'' h'']].\n  destruct (change_type hg h'' h') as [t' [_ ht']].\n  exists t'. assumption.\nDefined.\n\nEnd Conservativity.\n\nSection Consistency.\n\nLocal Existing Instance Sorts.nat_sorts.\n\n(* Consistency of ETT relative to consistency of WTT. *)\nCorollary consistency :\n  forall {Σ t},\n    type_glob Σ ->\n    Σ ;;; [] |-x t : sProd nAnon (sSort 0) (sRel 0) ->\n    ∑ t', Σ ;;; [] |-i t' : sProd nAnon (sSort 0) (sRel 0).\nProof.\n  intros Σ t hg h.\n  set (T := sProd nAnon (@sSort Sorts.nat_sorts 0) (sRel 0)) in *.\n  eapply conservativity.\n  all: try eassumption.\n  - repeat constructor.\n  - instantiate (1 := Sorts.prod_sort 1 0).\n    econstructor.\n    + econstructor. constructor.\n    + refine (type_Rel _ _ _ _ (sSort 0) _).\n      * repeat econstructor.\n      * cbn. reflexivity.\nDefined.\n\nEnd Consistency.\n", "meta": {"author": "TheoWinterhalter", "repo": "ett-to-wtt", "sha": "a19d7fe082fc5a597093c4ce56ce22158befb60c", "save_path": "github-repos/coq/TheoWinterhalter-ett-to-wtt", "path": "github-repos/coq/TheoWinterhalter-ett-to-wtt/ett-to-wtt-a19d7fe082fc5a597093c4ce56ce22158befb60c/theories/Translation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22567060869650737}}
{"text": "Require Import SpecCert.Address.Address.\nRequire Import SpecCert.Equality.\n\nInductive LogicalMap :=\n| lm: LogicalMap.\n\nLemma lm_singleton\n      (l l': LogicalMap)\n  : l = l'.\nProof.\n  induction l; induction l'.\n  reflexivity.\nQed.\n\nInstance lmSingleton\n  : Singleton LogicalMap := { singleton := lm_singleton }.\n\nInstance lmMapEq\n  : Eq LogicalMap\n  := singletonEq LogicalMap.\n\nDefinition LogicalAddress := Address LogicalMap.", "meta": {"author": "lthms", "repo": "speccert", "sha": "8c1edfb173548af0e9ca3c4e24d43726401fdb71", "save_path": "github-repos/coq/lthms-speccert", "path": "github-repos/coq/lthms-speccert/speccert-8c1edfb173548af0e9ca3c4e24d43726401fdb71/src/Address/LogicalAddress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22567060869650732}}
{"text": "(*===========================================================================\n   Embedding of total states (ProcState) into partial states (PState)\n   and associate lemmas regarding SPreds\n  ===========================================================================*)\nRequire Import Ssreflect.ssreflect Ssreflect.ssrfun Ssreflect.ssrbool Ssreflect.ssrnat Ssreflect.eqtype Ssreflect.tuple Ssreflect.seq Ssreflect.fintype.\nRequire Import x86proved.bitsrep x86proved.bitsprops x86proved.bitsops x86proved.bitsopsprops x86proved.x86.procstate x86proved.x86.procstatemonad x86proved.pmapprops.\nRequire Import x86proved.monad x86proved.monadinst x86proved.reader x86proved.spred x86proved.septac x86proved.pointsto x86proved.pfun x86proved.cursor x86proved.writer.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nTransparent ILFun_Ops.\n\n(* A full machine state can be interpreted as a partial state *)\nDefinition toPState (s:ProcState) : PState :=\n  fun f:Frag =>\n  match f return fragDom f -> option (fragTgt f) with\n  | Registers => fun rp => let: AnyRegPiece r ix := rp in Some (getRegPiece (registers s r) ix)\n  | Flags => fun f => Some (flags s f)\n  | Memory => fun p => Some (memory s p)\n  end.\n\nCoercion toPState : ProcState >-> PState.\n\nLemma totalProcState (s: ProcState) : isTotalPState s.\nProof. move => f x. destruct f; destruct x => //.  Qed.\n\nRequire Import Coq.Logic.FunctionalExtensionality x86proved.charge.csetoid.\n\nLemma toPState_inj s1 s2 : toPState s1 === toPState s2 -> s1 = s2.\nProof. move => H.\ndestruct s1 as [s1r s1f s1m].\ndestruct s2 as [s2r s2f s2m].\nunfold \"===\", toPState in H.\nsimpl in H.\nhave E1: s1r = s2r. extensionality x.\nhave H0 := H Registers (AnyRegPiece x RegIx0).\nhave H1 := H Registers (AnyRegPiece x RegIx1).\nhave H2 := H Registers (AnyRegPiece x RegIx2).\nhave H3 := H Registers (AnyRegPiece x RegIx3).\nclear H.\napply getRegPiece_ext; congruence.\n\nhave E2: s1f = s2f.\nextensionality x. specialize (H Flags x). by injection H.\nhave E3: s1m = s2m.\napply extensional_PMAP => x. specialize (H Memory x). by injection H.\nby rewrite E1 E2 E3.\nQed.\n\nLemma eqPredProcState_sepSP (s: ProcState) R :\n  eq_pred s ** R |-- eq_pred s.\nProof. rewrite (eqPredTotal_sepSP_trueR _); last by apply totalProcState. by ssimpl. Qed.\n\nDefinition isClosed (P: SPred) :=\n  forall s s', stateIncludedIn s s' -> P s -> P s'.\n\nLocal Transparent lentails sepILogicOps.\nLemma isClosed_sepSP_ltrue P:\n  isClosed P -> P ** ltrue -|- P.\nProof.\n  move=> HClosed. split.\n  - move=> s [s1 [s2 [Hs [HPs _]]]]. eapply HClosed; [|eassumption].\n    edestruct stateSplitsAsIncludes; [eapply Hs | assumption].\n  - rewrite <-empSPR at 1. cancel2.\nQed.\n\nLemma eq_pred_aux (s1 s2 s3: ProcState) R :\n  ((eq_pred s1 ** R) ** ltrue) s2 ->\n  ((eq_pred s3 ** R) ** ltrue) s3.\nProof. move => H0.\napply lentails_eq. ssimpl.\napply lentails_eq in H0.\nrewrite -> sepSPC in H0. rewrite <-sepSPA in H0. rewrite ->(sepSPC ltrue) in H0.\nrewrite <- (eqPredTotal_sepSP_trueR) in H0; last by apply totalProcState.\napply eqPredTotal_sepSP in H0; last by apply totalProcState.\nrewrite -> H0. by ssimpl.\nQed.\n\nLemma eq_pred_aux2 (s1 s2: ProcState) R :\n  ((eq_pred s1 ** R) ** ltrue) s2 -> s1 = s2.\nProof. move => H0.\napply lentails_eq in H0. rewrite -> sepSPA in H0.\n  rewrite -> eqPredProcState_sepSP in H0.\n  apply lentails_eq in H0. simpl in H0. by apply toPState_inj in H0.\nQed.\n", "meta": {"author": "nbenton", "repo": "x86proved", "sha": "7a58960f6456ee09dd46c990204a30c2fdd7fa1a", "save_path": "github-repos/coq/nbenton-x86proved", "path": "github-repos/coq/nbenton-x86proved/x86proved-7a58960f6456ee09dd46c990204a30c2fdd7fa1a/src/spredtotal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22567060869650732}}
{"text": "(** * Push-Button Synthesis of Bitcoin Multiplication: Reification Cache *)\nRequire Import Coq.derive.Derive.\nRequire Import Crypto.PushButtonSynthesis.ReificationCache.\nRequire Import Crypto.Arithmetic.DettmanMultiplication.\n\nLocal Set Keyed Unification. (* needed for making [autorewrite] fast, c.f. COQBUG(https://github.com/coq/coq/issues/9283) *)\n\nModule Export DettmanMultiplication.\n  Import dettman_multiplication_mod_ops.\n  Derive reified_mul_gen\n         SuchThat (is_reification_of reified_mul_gen mulmod)\n         As reified_mul_gen_correct.\n  Proof. Time cache_reify (). Time Qed.\n#[global]\n  Hint Extern 1 (_ = _) => apply_cached_reification mulmod (proj1 reified_mul_gen_correct) : reify_cache_gen.\n#[global]\n  Hint Immediate (proj2 reified_mul_gen_correct) : wf_gen_cache.\n#[global]\n  Hint Rewrite (proj1 reified_mul_gen_correct) : interp_gen_cache.\n  Local Opaque reified_mul_gen. (* needed for making [autorewrite] not take a very long time *)\n\n  Derive reified_square_gen\n         SuchThat (is_reification_of reified_square_gen squaremod)\n         As reified_square_gen_correct.\n  Proof. Time cache_reify (). Time Qed.\n#[global]\n  Hint Extern 1 (_ = _) => apply_cached_reification squaremod (proj1 reified_square_gen_correct) : reify_cache_gen.\n#[global]\n  Hint Immediate (proj2 reified_square_gen_correct) : wf_gen_cache.\n#[global]\n  Hint Rewrite (proj1 reified_square_gen_correct) : interp_gen_cache.\n  Local Opaque reified_square_gen. (* needed for making [autorewrite] not take a very long time *)\nEnd DettmanMultiplication.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/PushButtonSynthesis/DettmanMultiplicationReificationCache.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22567060249536305}}
{"text": "Require Import Ascii Bool String List Lia.\nRequire Import Lib.CommonTactics Lib.Indexer Lib.ilist Lib.Word Lib.Struct.\nRequire Import Kami.Syntax Kami.Notations.\nRequire Import Kami.Semantics Kami.Specialize Kami.Duplicate.\nRequire Import Kami.Wf Kami.Tactics.\nRequire Import Ex.MemTypes.\n\nSet Implicit Arguments.\n\n(* The SC module is defined as follows: SC = n * Pinst + Minst,\n * where Pinst denotes an instantaneous processor core\n * and Minst denotes an instantaneous memory.\n *)\n\n(* Abstract ISA *)\nSection DecExec.\n  Variables opIdx addrSize iaddrSize instBytes dataBytes rfIdx: nat.\n\n  Definition Pc := Bit addrSize.\n  \n  (* opcode-related *)\n  Definition OpcodeK := SyntaxKind (Bit opIdx).\n  Definition OpcodeE (ty: Kind -> Type) := Expr ty OpcodeK.\n  Definition OpcodeT := forall ty, fullType ty (SyntaxKind (Data instBytes)) -> OpcodeE ty.\n\n  Definition opLd := WO~0~0.\n  Definition opSt := WO~0~1.\n  Definition opNm := WO~1~1.\n  \n  Definition OptypeK := SyntaxKind (Bit 2).\n  Definition OptypeE (ty: Kind -> Type) := Expr ty OptypeK.\n  Definition OptypeT := forall ty, fullType ty (SyntaxKind (Data instBytes)) -> OptypeE ty.\n  \n  (* load-related *)\n  Definition LdDstK := SyntaxKind (Bit rfIdx).\n  Definition LdDstE (ty: Kind -> Type) := Expr ty LdDstK.\n  Definition LdDstT := forall ty, fullType ty (SyntaxKind (Data instBytes)) -> LdDstE ty.\n\n  Definition LdAddrK := SyntaxKind (Bit addrSize).\n  Definition LdAddrE (ty: Kind -> Type) := Expr ty LdAddrK.\n  Definition LdAddrT := forall ty, fullType ty (SyntaxKind (Data instBytes)) -> LdAddrE ty.\n\n  Definition LdSrcK := SyntaxKind (Bit rfIdx).\n  Definition LdSrcE (ty: Kind -> Type) := Expr ty LdSrcK.\n  Definition LdSrcT := forall ty, fullType ty (SyntaxKind (Data instBytes)) -> LdSrcE ty.\n\n  Definition f3Lb := WO~0~0~0.\n  Definition f3Lh := WO~0~0~1.\n  Definition f3Lw := WO~0~1~0.\n  Definition f3Lbu := WO~1~0~0.\n  Definition f3Lhu := WO~1~0~1.\n\n  Definition LdTypeK := SyntaxKind (Bit 3).\n  Definition LdTypeE (ty: Kind -> Type) := Expr ty LdTypeK.\n  Definition LdTypeT := forall ty, fullType ty (SyntaxKind (Data instBytes)) -> LdTypeE ty.\n\n  Definition LdAddrCalcT :=\n    forall ty,\n      fullType ty (SyntaxKind (Bit addrSize)) -> (* base address *)\n      fullType ty (SyntaxKind (Data dataBytes)) -> (* offset value *)\n      Expr ty (SyntaxKind (Bit addrSize)).\n\n  Definition LdValCalcT :=\n    forall ty,\n      fullType ty (SyntaxKind (Bit addrSize)) -> (* requested address *)\n      fullType ty (SyntaxKind (Data dataBytes)) (* loaded value *) ->\n      fullType ty LdTypeK -> (* load type: lb, lh, lw, lbu, or lhu *)\n      Expr ty (SyntaxKind (Data dataBytes)). (* calculated value *)\n\n  (* store-related *)\n  Definition StAddrK := SyntaxKind (Bit addrSize).\n  Definition StAddrE (ty: Kind -> Type) := Expr ty StAddrK.\n  Definition StAddrT := forall ty, fullType ty (SyntaxKind (Data instBytes)) -> StAddrE ty.\n  \n  Definition StSrcK := SyntaxKind (Bit rfIdx).\n  Definition StSrcE (ty: Kind -> Type) := Expr ty StSrcK.\n  Definition StSrcT := forall ty, fullType ty (SyntaxKind (Data instBytes)) -> StSrcE ty.\n\n  Definition StAddrCalcT :=\n    forall ty,\n      fullType ty (SyntaxKind (Bit addrSize)) -> (* base address *)\n      fullType ty (SyntaxKind (Data dataBytes)) -> (* offset value *)\n      Expr ty (SyntaxKind (Bit addrSize)).\n  Definition StByteEnCalcT :=\n    forall ty, fullType ty (SyntaxKind (Data instBytes)) ->\n               Expr ty (SyntaxKind (Array Bool dataBytes)).\n\n  Definition StVSrcK := SyntaxKind (Bit rfIdx).\n  Definition StVSrcE (ty: Kind -> Type) := Expr ty StVSrcK.\n  Definition StVSrcT := forall ty, fullType ty (SyntaxKind (Data instBytes)) -> StVSrcE ty.\n\n  (* general sources *)\n  Definition Src1K := SyntaxKind (Bit rfIdx).\n  Definition Src1E (ty: Kind -> Type) := Expr ty Src1K.\n  Definition Src1T := forall ty, fullType ty (SyntaxKind (Data instBytes)) -> Src1E ty.\n\n  Definition Src2K := SyntaxKind (Bit rfIdx).\n  Definition Src2E (ty: Kind -> Type) := Expr ty Src2K.\n  Definition Src2T := forall ty, fullType ty (SyntaxKind (Data instBytes)) -> Src2E ty.\n\n  (* general destination *)\n  Definition DstK := SyntaxKind (Bit rfIdx).\n  Definition DstE (ty: Kind -> Type) := Expr ty DstK.\n  Definition DstT := forall ty, fullType ty (SyntaxKind (Data instBytes)) -> DstE ty.\n  \n  (* execution *)\n  Definition StateK := SyntaxKind (Vector (Data dataBytes) rfIdx).\n  Definition StateT (ty : Kind -> Type) := fullType ty StateK.\n  Definition StateE (ty : Kind -> Type) := Expr ty StateK.\n\n  Definition ExecT := forall ty, fullType ty (SyntaxKind (Data dataBytes)) -> (* val1 *)\n                                 fullType ty (SyntaxKind (Data dataBytes)) -> (* val2 *)\n                                 fullType ty (SyntaxKind Pc) -> (* pc *)\n                                 fullType ty (SyntaxKind (Data instBytes)) -> (* rawInst *)\n                                 Expr ty (SyntaxKind (Data dataBytes)). (* executed value *)\n  Definition NextPcT := forall ty, StateT ty -> (* rf *)\n                                   fullType ty (SyntaxKind Pc) -> (* pc *)\n                                   fullType ty (SyntaxKind (Data instBytes)) -> (* rawInst *)\n                                   Expr ty (SyntaxKind Pc). (* next pc *)\n  Definition ToIAddrT := forall ty, fullType ty (SyntaxKind (Bit addrSize)) ->\n                                    Expr ty (SyntaxKind (Bit iaddrSize)).\n  Definition ToAddrT := forall ty, fullType ty (SyntaxKind (Bit iaddrSize)) ->\n                                   Expr ty (SyntaxKind (Bit addrSize)).\n  Definition AlignInstT := forall ty, fullType ty (SyntaxKind (Data dataBytes)) -> (* loaded word *)\n                                      Expr ty (SyntaxKind (Data instBytes)). (* aligned inst. *)\n\n  Class AbsFetch :=\n    { toIAddr: ToIAddrT;\n      toAddr: ToAddrT;\n      alignInst: AlignInstT\n    }.\n  \n  Class AbsDec :=\n    { getOptype: OptypeT;\n      getLdDst: LdDstT;\n      getLdAddr: LdAddrT;\n      getLdSrc: LdSrcT;\n      calcLdAddr: LdAddrCalcT;\n      getLdType: LdTypeT;\n      getStAddr: StAddrT;\n      getStSrc: StSrcT;\n      calcStAddr: StAddrCalcT;\n      calcStByteEn: StByteEnCalcT;\n      getStVSrc: StVSrcT;\n      getSrc1: Src1T;\n      getSrc2: Src2T;\n      getDst: DstT\n    }.\n\n  Class AbsExec :=\n    { calcLdVal: LdValCalcT;\n      doExec: ExecT;\n      getNextPc: NextPcT\n    }.\n\n  Class AbsIsa :=\n    { fetch: AbsFetch;\n      dec: AbsDec;\n      exec: AbsExec\n    }.\n  \nEnd DecExec.\n\n#[global] Hint Unfold Pc OpcodeK OpcodeE OpcodeT OptypeK OptypeE OptypeT opLd opSt opNm\n     LdDstK LdDstE LdDstT LdAddrK LdAddrE LdAddrT LdSrcK LdSrcE LdSrcT LdAddrCalcT\n     LdTypeK LdTypeE LdTypeT f3Lb f3Lh f3Lw f3Lbu f3Lhu LdValCalcT\n     StAddrK StAddrE StAddrT StSrcK StSrcE StSrcT StAddrCalcT StByteEnCalcT\n     StVSrcK StVSrcE StVSrcT Src1K Src1E Src1T Src2K Src2E Src2T\n     StateK StateE StateT ExecT NextPcT ToIAddrT ToAddrT AlignInstT : MethDefs.\n\nSection MemInst.\n  Variables (addrSize maddrSize dataBytes: nat)\n            (Hdb: {pdb & dataBytes = S pdb}).\n\n  Definition RqFromProc := RqFromProc dataBytes (Bit addrSize).\n  Definition RsToProc := RsToProc dataBytes.\n\n  Definition MemInit := ConstT (Vector (Bit BitsPerByte) maddrSize).\n  \n  Variable (memInit: MemInit).\n\n  Definition memOp := MethodSig \"memOp\"(Struct RqFromProc) : Struct RsToProc.\n\n  (* NOTE: it's little endian *)\n  Fixpoint memLoadBytes {ty} (n: nat) (addr: Expr ty (SyntaxKind (Bit addrSize)))\n           (mem: Expr ty (SyntaxKind (Vector (Bit BitsPerByte) maddrSize))):\n    Expr ty (SyntaxKind (Bit (n * BitsPerByte))) :=\n    (match n with\n     | 0 => $$WO\n     | S n' => {memLoadBytes n' (addr + $1) mem, mem@[_zeroExtend_ addr]}\n     end)%kami_expr.\n\n  (* NOTE: it's little endian as well *)\n  Fixpoint memStoreBytes {ty} (n: nat) (addr: Expr ty (SyntaxKind (Bit addrSize)))\n           (val: Expr ty (SyntaxKind (Bit (n * BitsPerByte))))\n           (sz: nat) (byteEn: Expr ty (SyntaxKind (Array Bool (S sz))))\n           (mem: Expr ty (SyntaxKind (Vector (Bit BitsPerByte) maddrSize))):\n    Expr ty (SyntaxKind (Vector (Bit BitsPerByte) maddrSize)) :=\n    (match n as n0 return\n           ((Bit (n0 * BitsPerByte))@ty -> (Vector (Bit BitsPerByte) maddrSize)@ty)\n     with\n     | 0 => fun _ => mem\n     | S n' =>\n       fun val0 =>\n         let nmem := memStoreBytes\n                       n' (addr + $1)\n                       (UniBit (TruncLsb BitsPerByte (n' * BitsPerByte)) val0) byteEn\n                       mem in\n         (IF byteEn#[$$(natToWord (Nat.log2 sz + 1) (sz - n'))]\n          then nmem@[_zeroExtend_ addr <- UniBit (Trunc BitsPerByte (n' * BitsPerByte)) val0]\n          else nmem)\n     end val)%kami_expr.\n\n  Definition memStoreBytes' {ty} (n: nat) (addr: Expr ty (SyntaxKind (Bit addrSize)))\n             (val: Expr ty (SyntaxKind (Bit (n * BitsPerByte))))\n             (sz: nat) (Hsz: {sz' & sz = S sz'})\n             (byteEn: Expr ty (SyntaxKind (Array Bool sz)))\n             (mem: Expr ty (SyntaxKind (Vector (Bit BitsPerByte) maddrSize))):\n    Expr ty (SyntaxKind (Vector (Bit BitsPerByte) maddrSize)) :=\n    eq_rect_r (fun sz => (Array Bool sz)@ty -> _)\n              (fun byteEn => memStoreBytes n addr val byteEn mem) (projT2 Hsz) byteEn.\n\n  (* For semantic uses *)\n  Fixpoint combineBytes (n: nat) (addr: word addrSize)\n           (mem: word maddrSize -> word BitsPerByte): word (n * BitsPerByte) :=\n    match n with\n    | 0 => WO\n    | S n' => combine (mem (evalZeroExtendTrunc _ addr)) (combineBytes n' (addr ^+ $1) mem)\n    end.\n\n  Fixpoint updateBytes (n: nat) (addr: word addrSize) (val: word (n * BitsPerByte))\n           (sz: nat) (byteEn: Fin.t (S sz) -> bool)\n           (mem: word maddrSize -> word BitsPerByte): word maddrSize -> word BitsPerByte :=\n    (match n as n0 return\n           (word (n0 * BitsPerByte) -> (word maddrSize -> word BitsPerByte))\n     with\n     | 0 => fun _ => mem\n     | S n' => fun val0 =>\n                 let nmem := updateBytes\n                               n' (addr ^+ $1)\n                               (split2 BitsPerByte (n' * BitsPerByte) val0) byteEn\n                               mem in\n                 if byteEn (natToFin _ (sz - n'))\n                 then (fun w =>\n                         if weq w (evalZeroExtendTrunc _ addr)\n                         then (split1 BitsPerByte (n' * BitsPerByte) val0)\n                         else nmem w)\n                 else nmem\n     end) val.\n\n  Definition memInst :=\n    MODULE {\n      Register \"mem\" : Vector (Bit BitsPerByte) maddrSize <- memInit\n\n      with Method \"memOp\" (a : Struct RqFromProc) : Struct RsToProc :=\n        If !(#a!RqFromProc@.\"op\") then (* load *)\n          Read memv <- \"mem\";\n          LET addr <- #a!RqFromProc@.\"addr\";\n          LET ldval <- memLoadBytes dataBytes #addr #memv;\n          Ret (STRUCT { \"data\" ::= #ldval } :: Struct RsToProc)\n        else (* store *)\n          Read memv <- \"mem\";\n          LET addr <- #a!RqFromProc@.\"addr\";\n          LET val <- #a!RqFromProc@.\"data\";\n          LET byteEn <- #a!RqFromProc@.\"byteEn\";\n          Write \"mem\" <- memStoreBytes' dataBytes #addr #val Hdb #byteEn #memv;\n          Ret (STRUCT { \"data\" ::= $$Default } :: Struct RsToProc)\n        as na;\n        Ret #na\n    }.\n    \n  Definition IsMMIOE (ty: Kind -> Type) := Expr ty (SyntaxKind Bool).\n  Definition IsMMIOT :=\n    forall ty, fullType ty (SyntaxKind (Bit addrSize)) -> IsMMIOE ty.\n\n  Class AbsMMIO :=\n    { isMMIO: IsMMIOT }.\n\n  Variable (ammio: AbsMMIO).\n\n  Definition mmioExec :=\n    MethodSig \"mmioExec\"(Struct RqFromProc): Struct RsToProc.\n  \n  Definition mm :=\n    MODULE {\n      Register \"mem\" : Vector (Bit BitsPerByte) maddrSize <- memInit\n\n      with Method \"memOp\" (a : Struct RqFromProc): Struct RsToProc :=\n        LET addr <- #a!RqFromProc@.\"addr\";\n\n        If (isMMIO _ addr) then (** mmio *)\n          Call rs <- mmioExec(#a);\n          Ret #rs\n        else\n          If !(#a!RqFromProc@.\"op\") then (* load *)\n            Read memv <- \"mem\";\n            LET addr <- #a!RqFromProc@.\"addr\";\n            LET ldval <- memLoadBytes dataBytes #addr #memv;\n            Ret (STRUCT { \"data\" ::= #ldval } :: Struct RsToProc)\n          else (* store *)\n            Read memv <- \"mem\";\n            LET addr <- #a!RqFromProc@.\"addr\";\n            LET val <- #a!RqFromProc@.\"data\";\n            LET byteEn <- #a!RqFromProc@.\"byteEn\";\n            Write \"mem\" <- memStoreBytes' dataBytes #addr #val Hdb #byteEn #memv;\n            Ret (STRUCT { \"data\" ::= $$Default } :: Struct RsToProc)\n          as na;\n          Ret #na\n        as na;\n        Ret #na\n    }.\n  \nEnd MemInst.\n\n#[global] Hint Unfold RqFromProc RsToProc memOp IsMMIOE IsMMIOT mmioExec: MethDefs.\n#[global] Hint Unfold memInst mm: ModuleDefs.\n\n(* The module definition for Pinst *)\nSection ProcInst.\n  Variables addrSize maddrSize iaddrSize instBytes dataBytes rfIdx : nat.\n\n  Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes)\n            (dec: AbsDec addrSize instBytes dataBytes rfIdx)\n            (exec: AbsExec addrSize instBytes dataBytes rfIdx).\n\n  Definition nextPc {ty} ppc st rawInst :=\n    (Write \"pc\" <- getNextPc ty st ppc rawInst;\n     Retv)%kami_action.\n\n  Record ProcInit := { pcInit : ConstT (Pc addrSize);\n                       rfInit : ConstT (Vector (Data dataBytes) rfIdx)\n                     }.\n  Definition procInitDefault :=\n    {| pcInit := Default; rfInit := Default |}.\n\n  Local Notation memOp := (memOp addrSize dataBytes).\n\n  Variables (procInit: ProcInit).\n\n  Definition procInst := MODULE {\n    Register \"pc\" : Pc addrSize <- (pcInit procInit)\n    with Register \"rf\" : Vector (Data dataBytes) rfIdx <- (rfInit procInit)\n\n    with Register \"pinit\" : Bool <- Default\n    with Register \"pinitOfs\" : Bit iaddrSize <- Default\n    with Register \"pgm\" : Vector (Data instBytes) iaddrSize <- Default\n\n    (** Phase 1: initialize the program [pinit == false] *)\n\n    with Rule \"pgmInit\" :=\n      Read pinit : Bool <- \"pinit\";\n      Read pinitOfs : Bit iaddrSize <- \"pinitOfs\";\n      Read pgm : Vector (Data instBytes) iaddrSize <- \"pgm\";\n      Assert !#pinit;\n      Assert ((UniBit (Inv _) #pinitOfs) != $0);\n\n      Call ldData <- memOp(STRUCT { \"addr\" ::= toAddr _ pinitOfs;\n                                    \"op\" ::= $$false;\n                                    \"byteEn\" ::= $$Default;\n                                    \"data\" ::= $$Default });\n      LET ldVal <- #ldData!(RsToProc dataBytes)@.\"data\";\n      LET inst <- alignInst _ ldVal;\n      Write \"pgm\" <- #pgm@[#pinitOfs <- #inst];\n      Write \"pinitOfs\" <- #pinitOfs + $1;\n      Retv\n\n    with Rule \"pgmInitEnd\" :=\n      Read pinit : Bool <- \"pinit\";\n      Read pinitOfs : Bit iaddrSize <- \"pinitOfs\";\n      Read pgm : Vector (Data instBytes) iaddrSize <- \"pgm\";\n      Assert !#pinit;\n      Assert ((UniBit (Inv _) #pinitOfs) == $0);\n      Call ldData <- memOp(STRUCT { \"addr\" ::= toAddr _ pinitOfs;\n                                    \"op\" ::= $$false;\n                                    \"byteEn\" ::= $$Default;\n                                    \"data\" ::= $$Default });\n      LET ldVal <- #ldData!(RsToProc dataBytes)@.\"data\";\n      LET inst <- alignInst _ ldVal;\n      Write \"pgm\" <- #pgm@[#pinitOfs <- #inst];\n      Write \"pinit\" <- !#pinit;\n      Write \"pinitOfs\" : Bit iaddrSize <- $0;\n      Retv\n\n    (** Phase 2: execute the program [pinit == true] *)\n        \n    with Rule \"execLd\" :=\n      Read ppc : Pc addrSize <- \"pc\";\n      Read rf : Vector (Data dataBytes) rfIdx <- \"rf\";\n      Read pinit : Bool <- \"pinit\";\n      Read pgm : Vector (Data instBytes) iaddrSize <- \"pgm\";\n      Assert #pinit;\n      LET rawInst <- #pgm@[toIAddr _ ppc];\n      Assert (getOptype _ rawInst == $$opLd);\n      LET dstIdx <- getLdDst _ rawInst;\n      Assert (#dstIdx != $0);\n      LET addr <- getLdAddr _ rawInst;\n      LET srcIdx <- getLdSrc _ rawInst;\n      LET srcVal <- #rf@[#srcIdx];\n      LET laddr <- calcLdAddr _ addr srcVal;\n      Call ldRep <- memOp(STRUCT { \"addr\" ::= #laddr;\n                                   \"op\" ::= $$false;\n                                   \"byteEn\" ::= $$Default;\n                                   \"data\" ::= $$Default });\n      LET ldValWord <- #ldRep!(RsToProc dataBytes)@.\"data\";\n      LET ldType <- getLdType _ rawInst;\n      LET ldVal <- calcLdVal _ laddr ldValWord ldType;\n      Write \"rf\" <- #rf@[#dstIdx <- #ldVal];\n      nextPc ppc rf rawInst\n             \n    with Rule \"execLdZ\" :=\n      Read ppc : Pc addrSize <- \"pc\";\n      Read rf : Vector (Data dataBytes) rfIdx <- \"rf\";\n      Read pinit : Bool <- \"pinit\";\n      Read pgm : Vector (Data instBytes) iaddrSize <- \"pgm\";\n      Assert #pinit;\n      LET rawInst <- #pgm@[toIAddr _ ppc];\n      Assert (getOptype _ rawInst == $$opLd);\n      LET regIdx <- getLdDst _ rawInst;\n      (* NOTE: no register update when the dst register is r0, \n       * but the memory call should be made. *)\n      Assert (#regIdx == $0);\n      LET addr <- getLdAddr _ rawInst;\n      LET srcIdx <- getLdSrc _ rawInst;\n      LET srcVal <- #rf@[#srcIdx];\n      LET laddr <- calcLdAddr _ addr srcVal;\n      Call memOp(STRUCT { \"addr\" ::= #laddr;\n                          \"op\" ::= $$false;\n                          \"byteEn\" ::= $$Default;\n                          \"data\" ::= $$Default });\n      nextPc ppc rf rawInst\n\n    with Rule \"execSt\" :=\n      Read ppc : Pc addrSize <- \"pc\";\n      Read rf : Vector (Data dataBytes) rfIdx <- \"rf\";\n      Read pinit : Bool <- \"pinit\";\n      Read pgm : Vector (Data instBytes) iaddrSize <- \"pgm\";\n      Assert #pinit;\n      LET rawInst <- #pgm@[toIAddr _ ppc];\n      Assert (getOptype _ rawInst == $$opSt);\n      LET addr <- getStAddr _ rawInst;\n      LET srcIdx <- getStSrc _ rawInst;\n      LET srcVal <- #rf@[#srcIdx];\n      LET vsrcIdx <- getStVSrc _ rawInst;\n      LET stVal <- #rf@[#vsrcIdx];\n      LET saddr <- calcStAddr _ addr srcVal;\n      LET byteEn <- calcStByteEn _ rawInst;\n      Call memOp(STRUCT { \"addr\" ::= #saddr;\n                          \"op\" ::= $$true;\n                          \"byteEn\" ::= #byteEn;\n                          \"data\" ::= #stVal });\n      nextPc ppc rf rawInst\n\n    with Rule \"execNm\" :=\n      Read ppc : Pc addrSize <- \"pc\";\n      Read rf : Vector (Data dataBytes) rfIdx <- \"rf\";\n      Read pinit : Bool <- \"pinit\";\n      Read pgm : Vector (Data instBytes) iaddrSize <- \"pgm\";\n      Assert #pinit;\n      LET rawInst <- #pgm@[toIAddr _ ppc];\n      Assert (getOptype _ rawInst == $$opNm);\n      LET src1 <- getSrc1 _ rawInst;\n      LET val1 <- #rf@[#src1];\n      LET src2 <- getSrc2 _ rawInst;\n      LET val2 <- #rf@[#src2];\n      LET dst <- getDst _ rawInst;\n      Assert (#dst != $0);\n      LET execVal <- doExec _ val1 val2 ppc rawInst;\n      Write \"rf\" <- #rf@[#dst <- #execVal];\n      nextPc ppc rf rawInst\n\n    with Rule \"execNmZ\" :=\n      Read ppc : Pc addrSize <- \"pc\";\n      Read rf : Vector (Data dataBytes) rfIdx <- \"rf\";\n      Read pinit : Bool <- \"pinit\";\n      Read pgm : Vector (Data instBytes) iaddrSize <- \"pgm\";\n      Assert #pinit;\n      LET rawInst <- #pgm@[toIAddr _ ppc];\n      Assert (getOptype _ rawInst == $$opNm);\n      LET dst <- getDst _ rawInst;\n      Assert (#dst == $0);\n      nextPc ppc rf rawInst\n  }.\n\nEnd ProcInst.\n\n#[global] Hint Unfold nextPc procInitDefault : MethDefs.\n#[global] Hint Unfold procInst : ModuleDefs.\n\nSection SC.\n  Variables (addrSize maddrSize iaddrSize instBytes dataBytes rfIdx: nat)\n            (Hdb: {pdb & dataBytes = S pdb}).\n\n  Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes)\n            (dec: AbsDec addrSize instBytes dataBytes rfIdx)\n            (exec: AbsExec addrSize instBytes dataBytes rfIdx)\n            (ammio: AbsMMIO addrSize).\n\n  Variable n: nat.\n\n  Variables (procInit: ProcInit addrSize dataBytes rfIdx)\n            (memInit: MemInit maddrSize).\n\n  Definition pinst := procInst fetch dec exec procInit.\n\n  Definition scmm := ConcatMod pinst (mm Hdb memInit ammio).\n\nEnd SC.\n\n#[global] Hint Unfold pinst scmm : ModuleDefs.\n\nSection Facts.\n  Variables (addrSize maddrSize iaddrSize instBytes dataBytes rfIdx: nat)\n            (Hdb: {pdb & dataBytes = S pdb}).\n\n  Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes)\n            (dec: AbsDec addrSize instBytes dataBytes rfIdx)\n            (exec: AbsExec addrSize instBytes dataBytes rfIdx)\n            (ammio: AbsMMIO addrSize).\n\n  Lemma memLoadBytes_combineBytes:\n    forall n (addr: (Bit addrSize)@type)\n           (mem: (Vector (Bit BitsPerByte) maddrSize)@type),\n      evalExpr (memLoadBytes n addr mem) =\n      combineBytes n (evalExpr addr) (evalExpr mem).\n  Proof.\n    induction n.\n    - intros; reflexivity.\n    - intros; simpl.\n      rewrite IHn; reflexivity.\n  Qed.\n\n  Lemma memStoreBytes_updateBytes:\n    forall n (addr: (Bit addrSize)@type)\n           (val: (Bit (n * BitsPerByte))@type)\n           (mem: (Vector (Bit BitsPerByte) maddrSize)@type)\n           (sz: nat) (byteEn: (Array Bool (S sz))@type),\n      evalExpr (memStoreBytes n addr val byteEn mem) =\n      updateBytes n (evalExpr addr) (evalExpr val) (evalExpr byteEn) (evalExpr mem).\n  Proof.\n    induction n.\n    - intros; reflexivity.\n    - intros; simpl.\n      rewrite IHn by assumption; simpl.\n      rewrite wordToNat_natToWord_idempotent'.\n      + reflexivity.\n      + apply PeanoNat.Nat.le_lt_trans with (m:= sz).\n        * lia.\n        * rewrite PeanoNat.Nat.add_1_r.\n          destruct sz.\n          { simpl; lia. }\n          { apply PeanoNat.Nat.log2_spec; lia. }\n  Qed.\n\n  Lemma memStoreBytes'_updateBytes:\n    forall n (addr: (Bit addrSize)@type)\n           (val: (Bit (n * BitsPerByte))@type)\n           (mem: (Vector (Bit BitsPerByte) maddrSize)@type)\n           (sz: nat) (byteEn: (Array Bool (S sz))@type),\n      evalExpr (memStoreBytes' n addr val (existT _ _ eq_refl) byteEn mem) =\n      updateBytes n (evalExpr addr) (evalExpr val) (evalExpr byteEn) (evalExpr mem).\n  Proof.\n    intros; cbn.\n    apply memStoreBytes_updateBytes.\n  Qed.\n\n  Lemma pinst_ModEquiv:\n    forall init,\n      ModPhoasWf (pinst fetch dec exec init).\n  Proof.\n    kequiv.\n  Qed.\n  #[local] Hint Resolve pinst_ModEquiv.\n\n  Lemma memInst_ModEquiv:\n    forall (init: MemInit maddrSize),\n      ModPhoasWf (memInst addrSize Hdb init).\n  Proof.\n    kequiv.\n  Qed.\n  #[local] Hint Resolve memInst_ModEquiv.\n\n  Lemma mm_ModEquiv:\n    forall (init: MemInit maddrSize),\n      ModPhoasWf (mm Hdb init ammio).\n  Proof.\n    kequiv.\n  Qed.\n  #[local] Hint Resolve mm_ModEquiv.\n\n  Lemma scmm_ModEquiv:\n    forall procInit (memInit: MemInit maddrSize),\n      ModPhoasWf (scmm Hdb fetch dec exec ammio procInit memInit).\n  Proof.\n    kequiv.\n  Qed.\n  \nEnd Facts.\n\n#[global] Hint Resolve pinst_ModEquiv memInst_ModEquiv mm_ModEquiv scmm_ModEquiv.\n\n", "meta": {"author": "mit-plv", "repo": "kami", "sha": "cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0", "save_path": "github-repos/coq/mit-plv-kami", "path": "github-repos/coq/mit-plv-kami/kami-cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0/Kami/Ex/SC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.2254848990250978}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Vincent Rahli\n\n *)\n\n\nRequire Export per_props_uni.\nRequire Export per_props_equality.\n\n\nLemma mkc_pertype_equality_in_uni {p} :\n  forall lib (R1 R2 : @CTerm p) i,\n    equality lib (mkc_pertype R1) (mkc_pertype R2) (mkc_uni i)\n    <=> (forall x y, member lib (mkc_apply2 R1 x y) (mkc_uni i))\n      # (forall x y, member lib (mkc_apply2 R2 x y) (mkc_uni i))\n      # (forall x y,\n           inhabited_type lib (mkc_apply2 R1 x y)\n           <=>\n           inhabited_type lib (mkc_apply2 R2 x y))\n      # is_per_type lib R1.\nProof.\n  introv; split; intro equ; repnd.\n\n  - unfold equality, nuprl in equ; exrepnd.\n    inversion equ1; subst; try not_univ.\n    duniv j h.\n    allrw @univi_exists_iff; exrepnd.\n    computes_to_value_isvalue; GC.\n    rw h0 in equ0; exrepnd.\n    inversion equ2; subst; try not_univ.\n    dest_per.\n    allfold (@nuprl p); allfold (@nuprli p lib j0).\n    computes_to_value_isvalue.\n\n    dands; introv.\n\n    generalize (typ1 x y); intro k.\n    unfold member, equality.\n    exists eq; sp.\n    allrw.\n    exists (eq1 x y); sp.\n\n    generalize (typ2 x y); intro k.\n    unfold member, equality.\n    exists eq; sp.\n    allrw.\n    exists (eq2 x y); sp.\n\n    generalize (typ1 x y); intro k1.\n    generalize (typ2 x y); intro k2.\n    allapply @nuprli_implies_nuprl.\n\n    generalize (inhabited_type_iff lib (mkc_apply2 R0 x y) (mkc_apply2 R3 x y) (eq1 x y) (eq2 x y)); intro iff; repeat (dest_imp iff hyp).\n    rw <- iff; sp.\n\n    generalize (is_per_type_iff_is_per lib R0 eq1); introv iff.\n    dest_imp iff hyp.\n    intros.\n    generalize (typ1 x y); intro k1.\n    allapply @nuprli_implies_nuprl; sp.\n    rw <- iff; sp.\n\n  - repnd.\n    unfold equality, nuprl.\n\n    exists (fun A A' => {eqa : per(p) , close lib (univi lib i) A A' eqa}); sp.\n    apply CL_init.\n    exists (S i); simpl; left; sp; spcast; try computes_to_value_refl.\n\n    fold (@nuprli p lib i).\n\n    assert (forall x y : CTerm,\n              {eq : per\n               , nuprli lib i (mkc_apply2 R1 x y) (mkc_apply2 R1 x y) eq}) as f1.\n    (* begin proof of the assert *)\n    intros.\n    unfold member, equality in equ0.\n    generalize (equ0 x y); intro k; exrepnd.\n    inversion k1; try not_univ.\n    duniv j h.\n    allrw @univi_exists_iff; exrepnd.\n    computes_to_value_isvalue; GC.\n    rw h0 in k0; exrepnd.\n    allfold (@nuprli p lib j0).\n    exists eqa; sp.\n    (* end of proof of the assert *)\n\n    assert (forall x y : CTerm,\n              {eq : per\n               , nuprli lib i (mkc_apply2 R2 x y) (mkc_apply2 R2 x y) eq}) as f2.\n    (* begin proof of the assert *)\n    intros.\n    unfold member, equality in equ1.\n    generalize (equ1 x y); intro k; exrepnd.\n    inversion k1; try not_univ.\n    duniv j h.\n    allrw @univi_exists_iff; exrepnd.\n    computes_to_value_isvalue; GC.\n    rw h0 in k0; exrepnd.\n    allfold (@nuprli p lib j0).\n    exists eqa; sp.\n    (* end of proof of the assert *)\n\n    generalize (choice_spteqi lib i (mkc_apply2 R1) (mkc_apply2 R1)); intro fn1.\n    generalize (choice_spteqi lib i (mkc_apply2 R2) (mkc_apply2 R2)); intro fn2.\n    dest_imp fn1 hyp.\n    dest_imp fn2 hyp.\n    exrepnd.\n\n    exists (fun t t' => inhabited (f0 t t')).\n    apply CL_pertype.\n    fold (@nuprli p lib i).\n    unfold per_pertype.\n    exists R1 R2\n           (fun t t' => f0 t t')\n           (fun t t' => f t t');\n      sp; try (spcast; computes_to_value_refl); try (fold nuprl).\n\n    generalize (fn0 x y); intro n1.\n    generalize (fn2 x y); intro n2.\n    allapply @nuprli_implies_nuprl.\n    generalize (inhabited_type_iff lib (mkc_apply2 R1 x y) (mkc_apply2 R2 x y) (f0 x y) (f x y)); intro iff; repeat (dest_imp iff hyp).\n    rw iff; sp.\n\n    generalize (is_per_type_iff_is_per lib R1 f0); introv iff.\n    dest_imp iff hyp.\n    intros.\n    generalize (fn2 x y); intro k1.\n    allapply @nuprli_implies_nuprl; sp.\n    rw iff; sp.\nQed.\n\nLemma mkc_ipertype_equality_in_uni {p} :\n  forall lib (R1 R2 : @CTerm p) i,\n    equality lib (mkc_ipertype R1) (mkc_ipertype R2) (mkc_uni i)\n    <=> (forall x y, equality lib (mkc_apply2 R1 x y) (mkc_apply2 R2 x y) (mkc_uni i))\n        # is_per_type lib R1.\nProof.\n  introv; split; intro equ; repnd.\n\n  - unfold equality, nuprl in equ; exrepnd.\n    inversion equ1; subst; try not_univ.\n    duniv j h.\n    allrw @univi_exists_iff; exrepnd.\n    computes_to_value_isvalue; GC.\n    rw h0 in equ0; exrepnd.\n    inversion equ2; subst; try not_univ.\n    dest_per.\n    allfold (@nuprl p lib); allfold (@nuprli p lib j0).\n    computes_to_value_isvalue.\n\n    dands; introv.\n\n    generalize (eqtyps x y); intro k.\n    exists eq; sp; allrw.\n    exists (eq1 x y); sp.\n\n    generalize (is_per_type_iff_is_per lib R0 eq1); introv iff.\n    dest_imp iff hyp.\n    intros.\n    generalize (eqtyps x y); intro k1.\n    allapply @nuprli_implies_nuprl; sp.\n    apply nuprl_refl in k1; sp.\n    rw <- iff; sp.\n\n  - repnd.\n    unfold equality, nuprl.\n\n    exists (fun A A' => {eqa : per(p) , close lib (univi lib i) A A' eqa}); sp.\n    apply CL_init.\n    exists (S i); simpl; left; sp; spcast; try computes_to_value_refl.\n\n    fold (@nuprli p lib i).\n\n    assert (forall x y : CTerm,\n              {eq : per\n               , nuprli lib i (mkc_apply2 R1 x y) (mkc_apply2 R2 x y) eq}) as f1.\n    (* begin proof of the assert *)\n    intros.\n    unfold member, equality in equ0.\n    generalize (equ0 x y); intro k; exrepnd.\n    inversion k1; try not_univ.\n    duniv j h.\n    allrw @univi_exists_iff; exrepnd.\n    computes_to_value_isvalue; GC.\n    rw h0 in k0; exrepnd.\n    allfold (@nuprli p lib j0).\n    exists eqa; sp.\n    (* end of proof of the assert *)\n\n    generalize (choice_spteqi lib i (mkc_apply2 R1) (mkc_apply2 R2)); intro fn1.\n    dest_imp fn1 hyp.\n    exrepnd.\n\n    exists (pertype_eq f).\n    apply CL_ipertype.\n    fold (@nuprli p lib i).\n    unfold per_ipertype.\n    exists R1 R2 f;\n      sp; try (spcast; computes_to_value_refl); try (fold nuprl).\n\n    generalize (is_per_type_iff_is_per lib R1 f); introv iff.\n    dest_imp iff hyp.\n    intros.\n    generalize (fn0 x y); intro k1.\n    allapply @nuprli_implies_nuprl; sp.\n    apply nuprl_refl in k1; sp.\n    rw iff; sp.\nQed.\n\nLemma mkc_spertype_equality_in_uni {p} :\n  forall lib (R1 R2 : @CTerm p) i,\n    equality lib (mkc_spertype R1) (mkc_spertype R2) (mkc_uni i)\n    <=> (forall x y, equality lib (mkc_apply2 R1 x y) (mkc_apply2 R2 x y) (mkc_uni i))\n        # (forall x y z,\n             inhabited_type lib (mkc_apply2 R1 x z)\n             -> equality lib (mkc_apply2 R1 x y) (mkc_apply2 R1 z y) (mkc_uni i))\n        # (forall x y z,\n             inhabited_type lib (mkc_apply2 R1 y z)\n             -> equality lib (mkc_apply2 R1 x y) (mkc_apply2 R1 x z) (mkc_uni i))\n        # is_per_type lib R1.\nProof.\n  introv; split; intro equ; repnd.\n\n  - unfold equality, nuprl in equ; exrepnd.\n    inversion equ1; subst; try not_univ.\n    duniv j h.\n    allrw @univi_exists_iff; exrepnd.\n    computes_to_value_isvalue; GC.\n    rw h0 in equ0; exrepnd.\n    inversion equ2; subst; try not_univ.\n    dest_per.\n    allfold (@nuprl p); allfold (@nuprli p lib j0).\n    computes_to_value_isvalue.\n\n    dands; introv.\n\n    generalize (eqtyps1 x y); intro k.\n    exists eq; sp; allrw.\n    exists (eq1 x y); sp.\n\n    intro inh.\n    generalize (eqtyps1 x z); intro n.\n    apply inhabited_if_inhabited_type_i in n; auto.\n    generalize (eqtyps2 x y z n); intro ni.\n    exists eq; sp.\n    allrw; exists (eq1 x y); sp.\n\n    intro inh.\n    generalize (eqtyps1 y z); intro n.\n    apply inhabited_if_inhabited_type_i in n; auto.\n    generalize (eqtyps3 x y z n); intro ni.\n    exists eq; sp.\n    allrw; exists (eq1 x y); sp.\n\n    generalize (is_per_type_iff_is_per lib R0 eq1); introv iff.\n    dest_imp iff hyp.\n    intros.\n    generalize (eqtyps1 x y); intro k1.\n    allapply @nuprli_implies_nuprl; sp.\n    apply nuprl_refl in k1; sp.\n    rw <- iff; sp.\n\n  - repnd.\n    unfold equality, nuprl.\n\n    exists (fun A A' => {eqa : per(p) , close lib (univi lib i) A A' eqa}); sp.\n    apply CL_init.\n    exists (S i); simpl; left; sp; spcast; try computes_to_value_refl.\n\n    fold (@nuprli p lib i).\n\n    assert (forall x y : CTerm,\n              {eq : per\n               , nuprli lib i (mkc_apply2 R1 x y) (mkc_apply2 R2 x y) eq}) as f1.\n    (* begin proof of the assert *)\n    intros.\n    unfold member, equality in equ0.\n    generalize (equ0 x y); intro k; exrepnd.\n    inversion k1; try not_univ.\n    duniv j h.\n    allrw @univi_exists_iff; exrepnd.\n    computes_to_value_isvalue; GC.\n    rw h0 in k0; exrepnd.\n    allfold (@nuprli p lib j0).\n    exists eqa; sp.\n    (* end of proof of the assert *)\n\n    generalize (choice_spteqi lib i (mkc_apply2 R1) (mkc_apply2 R2)); intro fn1.\n    dest_imp fn1 hyp.\n    exrepnd.\n\n    exists (pertype_eq f).\n    apply CL_spertype.\n    fold (@nuprli p lib i).\n    unfold per_spertype.\n    exists R1 R2 f;\n      dands; introv;\n      try (spcast; computes_to_value_refl);\n      try (fold nuprl);\n      try (complete sp).\n\n    intro inh.\n    generalize (fn0 x z); intro ni.\n    apply inhabited_type_if_inhabited_i in ni; auto.\n    generalize (equ1 x y z ni); intro e.\n    generalize (fn0 x y); intro n.\n    apply equality_nuprli with (C := mkc_apply2 R2 x y); auto.\n\n    intro inh.\n    generalize (fn0 y z); intro ni.\n    apply inhabited_type_if_inhabited_i in ni; auto.\n    generalize (equ2 x y z ni); intro e.\n    generalize (fn0 x y); intro n.\n    apply equality_nuprli with (C := mkc_apply2 R2 x y); auto.\n\n    generalize (is_per_type_iff_is_per lib R1 f); introv iff.\n    dest_imp iff hyp.\n    intros.\n    generalize (fn0 x y); intro k1.\n    allapply @nuprli_implies_nuprl; sp.\n    apply nuprl_refl in k1; sp.\n    rw iff; sp.\nQed.\n\nLemma tequality_mkc_pertype {p} :\n  forall lib (R1 R2 : @CTerm p),\n    tequality lib (mkc_pertype R1) (mkc_pertype R2)\n    <=> (forall x y, type lib (mkc_apply2 R1 x y))\n      # (forall x y, type lib (mkc_apply2 R2 x y))\n      # (forall x y,\n           inhabited_type lib (mkc_apply2 R1 x y)\n           <=>\n           inhabited_type lib (mkc_apply2 R2 x y))\n      # is_per_type lib R1.\nProof.\n  introv.\n  split; intro i.\n\n  - unfold tequality, nuprl in i; exrepnd.\n    inversion i0; subst; try not_univ.\n    dest_per; allfold (@nuprl p lib).\n    computes_to_value_isvalue.\n\n    dands; intros.\n\n    unfold type, tequality; exists (eq1 x y); sp.\n    unfold type, tequality; exists (eq2 x y); sp.\n\n    generalize (inhabited_type_iff lib (mkc_apply2 R0 x y) (mkc_apply2 R3 x y) (eq1 x y) (eq2 x y)); intro iff; repeat (dest_imp iff hyp).\n    rw <- iff; sp.\n\n    generalize (is_per_type_iff_is_per lib R0 eq1); introv iff.\n    dest_imp iff hyp.\n    rw <- iff; sp.\n\n  - repnd.\n    unfold tequality, nuprl.\n    generalize (i0 mkc_axiom mkc_axiom); intro k.\n\n    generalize (choice_spteq lib (mkc_apply2 R1) (mkc_apply2 R1)); intro fn1.\n    generalize (choice_spteq lib (mkc_apply2 R2) (mkc_apply2 R2)); intro fn2.\n    dest_imp fn1 hyp; exrepnd.\n    dest_imp fn2 hyp; exrepnd.\n    exists (fun t t' => inhabited (f t t')).\n    apply CL_pertype.\n    unfold per_pertype.\n    exists R1 R2 f f0; sp;\n    try (spcast; computes_to_value_refl);\n    try (fold nuprl).\n\n    generalize (inhabited_type_iff lib (mkc_apply2 R1 x y) (mkc_apply2 R2 x y) (f x y) (f0 x y)); intro iff; repeat (dest_imp iff hyp).\n    rw iff; sp.\n\n    generalize (is_per_type_iff_is_per lib R1 f); introv iff.\n    dest_imp iff hyp.\n    rw iff; sp.\nQed.\n\nLemma tequality_mkc_ipertype {p} :\n  forall lib (R1 R2 : @CTerm p),\n    tequality lib (mkc_ipertype R1) (mkc_ipertype R2)\n    <=> (forall x y, tequality lib (mkc_apply2 R1 x y) (mkc_apply2 R2 x y))\n        # is_per_type lib R1.\nProof.\n  introv.\n  split; intro i.\n\n  - unfold tequality, nuprl in i; exrepnd.\n    inversion i0; subst; try not_univ.\n    dest_per; allfold (@nuprl p lib).\n    computes_to_value_isvalue.\n\n    dands; intros.\n\n    generalize (eqtyps x y); intro i.\n    apply tequality_if_nuprl in i; sp.\n\n    generalize (is_per_type_iff_is_per1 lib R0 R3 eq1 eqtyps); intro k; apply k; auto.\n\n  - repnd.\n    generalize (i0 mkc_axiom mkc_axiom); intro k.\n\n    generalize (choice_spteq lib (mkc_apply2 R1) (mkc_apply2 R2)); intro fn.\n    dest_imp fn hyp; exrepnd.\n    exists (fun t t' => inhabited (f t t')).\n    apply CL_ipertype.\n    unfold per_ipertype.\n    exists R1 R2 f; sp;\n    try (spcast; computes_to_value_refl);\n    try (fold nuprl).\n\n    generalize (is_per_type_iff_is_per1 lib R1 R2 f fn0); introv iff.\n    rw iff; sp.\nQed.\n\nLemma tequality_mkc_spertype {p} :\n  forall lib (R1 R2 : @CTerm p),\n    tequality lib (mkc_spertype R1) (mkc_spertype R2)\n    <=> (forall x y, tequality lib (mkc_apply2 R1 x y) (mkc_apply2 R2 x y))\n        # (forall x y z,\n             inhabited_type lib (mkc_apply2 R1 x z)\n             -> tequality lib (mkc_apply2 R1 x y) (mkc_apply2 R1 z y))\n        # (forall x y z,\n             inhabited_type lib (mkc_apply2 R1 y z)\n             -> tequality lib (mkc_apply2 R1 x y) (mkc_apply2 R1 x z))\n        # is_per_type lib R1.\nProof.\n  introv.\n  split; intro i.\n\n  - unfold tequality, nuprl in i; exrepnd.\n    inversion i0; subst; try not_univ.\n    dest_per; allfold (@nuprl p lib).\n    computes_to_value_isvalue.\n\n    dands; intros.\n\n    generalize (eqtyps1 x y); intro i.\n    apply tequality_if_nuprl in i; sp.\n\n    generalize (eqtyps2 x y z); intro i; autodimp i hyp.\n    eapply inhabited_if_inhabited_type with (T := mkc_apply2 R0 x z) (U := mkc_apply2 R3 x z); eauto.\n    apply tequality_if_nuprl in i; sp.\n\n    generalize (eqtyps3 x y z); intro i; autodimp i hyp.\n    eapply inhabited_if_inhabited_type with (T := mkc_apply2 R0 y z) (U := mkc_apply2 R3 y z); eauto.\n    apply tequality_if_nuprl in i; sp.\n\n    generalize (is_per_type_iff_is_per1 lib R0 R3 eq1 eqtyps1); intro k; apply k; auto.\n\n  - repnd.\n    generalize (i0 mkc_axiom mkc_axiom); intro k.\n\n    generalize (choice_spteq lib (mkc_apply2 R1) (mkc_apply2 R2)); intro fn.\n    dest_imp fn hyp; exrepnd.\n    exists (fun t t' => inhabited (f t t')).\n    apply CL_spertype.\n    unfold per_spertype.\n    exists R1 R2 f; dands; spcast; introv;\n    try (spcast; computes_to_value_refl);\n    try (fold (@nuprl p lib)); try (complete sp).\n\n    introv inh.\n    generalize (fn0 x z); intro e.\n    apply inhabited_type_if_inhabited in e; auto.\n    apply i1 with (y := y) in e.\n    rw <- @tequality_iff_nuprl in e; exrepnd.\n    generalize (fn0 x y); intro n.\n    generalize (nuprl_uniquely_valued lib (mkc_apply2 R1 x y) eq (f x y));\n      intro eqs; repeat (autodimp eqs hyp).\n    apply nuprl_refl in e0; auto.\n    apply nuprl_refl in n; auto.\n    apply nuprl_ext with (eq1 := eq); auto.\n\n    introv inh.\n    generalize (fn0 y z); intro e.\n    apply inhabited_type_if_inhabited in e; auto.\n    apply i2 with (x := x) in e.\n    rw <- @tequality_iff_nuprl in e; exrepnd.\n    generalize (fn0 x y); intro n.\n    generalize (nuprl_uniquely_valued lib (mkc_apply2 R1 x y) eq (f x y));\n      intro eqs; repeat (autodimp eqs hyp).\n    apply nuprl_refl in e0; auto.\n    apply nuprl_refl in n; auto.\n    apply nuprl_ext with (eq1 := eq); auto.\n\n    generalize (is_per_type_iff_is_per1 lib R1 R2 f fn0); introv iff.\n    rw iff; sp.\nQed.\n\n(*\nLemma mkc_ipertype_equality_in_uni :\n  forall R1 R2 i,\n    equality lib (mkc_ipertype R1) (mkc_ipertype R2) (mkc_uni i)\n    <=> (forall x y, equality lib (mkc_apply2 R1 x y) (mkc_apply2 R2 x y) (mkc_uni i))\n      # is_per_type lib R1.\nProof.\n  introv; split; intro equ; repnd.\n\n  - unfold equality, nuprl in equ; exrepnd.\n    inversion equ1; subst; try not_univ.\n    inversion X; exrepd.\n    allrw univi_exists_iff; exrepnd.\n    computes_to_value_isvalue; GC.\n    rename x into i.\n    rw X1 in equ0; exrepnd.\n    inversion equ2; subst; try not_univ.\n    allunfold per_ipertype; exrepnd.\n    allfold nuprl; allfold (nuprli j).\n    computes_to_value_isvalue.\n\n    dands; intros.\n\n    generalize (X5 x y); intro k.\n    unfold member, equality.\n    exists eq; sp.\n    rw X1.\n    exists (eq1 x y); sp.\n\n    allunfold is_per; repnd; allunfold is_per_type; dands.\n\n    unfold sym_type; introv inh.\n    apply inhabited_type_if_inhabited with (U := mkc_apply2 R0 y x) (eq := eq1 y x); sp.\n    generalize (X5 y x); intro p; apply nuprli_implies_nuprl in p; sp; allapply nuprl_refl; sp.\n    apply X2.\n    apply inhabited_if_inhabited_type with (U := mkc_apply2 R0 x y) (T := mkc_apply2 R0 x y); sp.\n    generalize (X5 x y); intro p; apply nuprli_implies_nuprl in p; sp; allapply nuprl_refl; sp.\n\n    unfold trans_type; introv inh1 inh2.\n    apply inhabited_type_if_inhabited with (U := mkc_apply2 R0 x z) (eq := eq1 x z); sp.\n    generalize (X5 x z); intro p; apply nuprli_implies_nuprl in p; sp; allapply nuprl_refl; sp.\n    apply X6 with (y := y).\n    apply inhabited_if_inhabited_type with (U := mkc_apply2 R0 x y) (T := mkc_apply2 R0 x y); sp.\n    generalize (X5 x y); intro p; apply nuprli_implies_nuprl in p; sp; allapply nuprl_refl; sp.\n    apply inhabited_if_inhabited_type with (U := mkc_apply2 R0 y z) (T := mkc_apply2 R0 y z); sp.\n    generalize (X5 y z); intro p; apply nuprli_implies_nuprl in p; sp; allapply nuprl_refl; sp.\n\n  - repnd.\n    unfold equality, nuprl.\n\n    exists (fun A A' => {eqa : per & close (univi i) A A' eqa}); sp.\n    apply CL_init.\n    exists (S i); simpl; left; sp; try computes_to_value_refl.\n\n    fold (nuprli i).\n\n    assert (forall x y : CTerm,\n              {eq : per\n               & nuprli i (mkc_apply2 R1 x y) (mkc_apply2 R2 x y) eq}) as f1.\n    intros.\n    unfold member, equality in equ0.\n    generalize (equ0 x y); intro k; exrepnd.\n    inversion k1; try not_univ.\n    inversion X.\n    allrw univi_exists_iff; exrepnd.\n    computes_to_value_isvalue; GC.\n    rename x0 into i.\n    rw X1 in k0; exrepnd.\n    allfold (nuprli j).\n    exists eqa; sp.\n    (* end of proof of the assert *)\n\n    exists (fun t t' => inhabited (projT1 (f1 t t'))).\n    apply CL_ipertype.\n    fold (nuprli i).\n    unfold per_ipertype.\n    exists R1 R2\n           (fun t t' => projT1 (f1 t t'));\n      sp; try (computes_to_value_refl); try (fold nuprl).\n\n    generalize (f1 x y); intro h; exrepnd; allsimpl; sp.\n\n    unfold is_per_type in equ; unfold sym_type, trans_type in equ; repnd.\n    unfold is_per; dands; introv.\n\n    generalize (f1 x y); generalize (f1 y x); intros h1 h2 inh; exrepnd; allsimpl.\n    apply inhabited_if_inhabited_type with (U := mkc_apply2 R1 y x) (T := mkc_apply2 R1 y x); sp;\n    try (complete (allapply nuprli_implies_nuprl; sp; allapply nuprl_refl; sp)).\n    apply equ1.\n    apply inhabited_type_if_inhabited with (U := mkc_apply2 R1 x y) (eq := eq); sp;\n    try (complete (allapply nuprli_implies_nuprl; sp; allapply nuprl_refl; sp)).\n\n    generalize (f1 x y); generalize (f1 y z); generalize (f1 x z); intros h1 h2 h3 inh1 inh2; exrepnd; allsimpl.\n    apply inhabited_if_inhabited_type with (U := mkc_apply2 R1 x z) (T := mkc_apply2 R1 x z); sp;\n    try (complete (allapply nuprli_implies_nuprl; sp; allapply nuprl_refl; sp)).\n    apply equ with (y := y).\n    apply inhabited_type_if_inhabited with (U := mkc_apply2 R1 x y) (eq := eq); sp;\n    try (complete (allapply nuprli_implies_nuprl; sp; allapply nuprl_refl; sp)).\n    apply inhabited_type_if_inhabited with (U := mkc_apply2 R1 y z) (eq := eq0); sp;\n    try (complete (allapply nuprli_implies_nuprl; sp; allapply nuprl_refl; sp)).\n(*Error: Universe inconsistency.*)\n[Admitted.]\n*)\n\nLemma type_mkc_pertype {p} :\n  forall lib (R : @CTerm p),\n    type lib (mkc_pertype R)\n    <=> (forall x y, type lib (mkc_apply2 R x y))\n      # is_per_type lib R.\nProof.\n  introv.\n  unfold type.\n  rw @tequality_mkc_pertype; split; sp.\n  rw @fold_type; sp.\n  unfold type; sp.\n  unfold type; sp.\nQed.\n\nLemma type_mkc_ipertype {p} :\n  forall lib (R : @CTerm p),\n    type lib (mkc_ipertype R)\n    <=> (forall x y, type lib (mkc_apply2 R x y))\n      # is_per_type lib R.\nProof.\n  introv.\n  unfold type.\n  rw @tequality_mkc_ipertype; split; sp.\nQed.\n\nLemma type_mkc_spertype {p} :\n  forall lib (R : @CTerm p),\n    type lib (mkc_spertype R)\n    <=> (forall x y, type lib (mkc_apply2 R x y))\n        # (forall x y z,\n             inhabited_type lib (mkc_apply2 R x z)\n             -> tequality lib (mkc_apply2 R x y) (mkc_apply2 R z y))\n        # (forall x y z,\n             inhabited_type lib (mkc_apply2 R y z)\n             -> tequality lib (mkc_apply2 R x y) (mkc_apply2 R x z))\n        # is_per_type lib R.\nProof.\n  introv.\n  unfold type.\n  rw @tequality_mkc_spertype; split; sp.\nQed.\n\nLemma iff_inhabited_type_if_pertype_eq_or_ceq {p} :\n  forall lib (R1 R2 : @CTerm p) i,\n    (equality lib (mkc_pertype R1) (mkc_pertype R2) (mkc_uni i)\n     [+] cequivc lib (mkc_pertype R1) (mkc_pertype R2))\n    -> forall x y,\n         inhabited_type lib (mkc_apply2 R1 x y)\n          <=> inhabited_type lib (mkc_apply2 R2 x y).\nProof.\n  introv or.\n  introv.\n  split; intro inh; repdors.\n\n  apply equality_in_uni in or0.\n  rw @tequality_mkc_pertype in or0; repnd.\n  rw <- or3; sp.\n\n  generalize (cequivc_mkc_pertype lib (mkc_pertype R1) (mkc_pertype R2) R1);\n    intro j; repeat (dest_imp j hyp); try (complete computes_to_value_refl); exrepnd.\n  computes_to_value_isvalue.\n  assert (cequivc lib (mkc_apply2 R1 x y) (mkc_apply2 b x y))\n         as ceq\n         by (repeat (rw @mkc_apply2_eq); repeat (apply sp_implies_cequivc_apply); sp).\n  apply inhabited_type_cequivc with (a := mkc_apply2 R1 x y); sp.\n\n  apply equality_in_uni in or0.\n  rw @tequality_mkc_pertype in or0; repnd.\n  rw or3; sp.\n\n  generalize (cequivc_mkc_pertype lib (mkc_pertype R1) (mkc_pertype R2) R1);\n    intro j; repeat (dest_imp j hyp); try (complete computes_to_value_refl); exrepnd.\n  computes_to_value_isvalue.\n  assert (cequivc lib (mkc_apply2 R1 x y) (mkc_apply2 b x y))\n         as ceq\n         by (repeat (rw @mkc_apply2_eq); repeat (apply sp_implies_cequivc_apply); sp).\n  apply inhabited_type_cequivc with (a := mkc_apply2 b x y); sp.\n  apply cequivc_sym; sp.\nQed.\n\n(*\nLemma tequality_mkc_apply2_if_pertype_eq_or_ceq :\n  forall R1 R2 i,\n    (equality lib (mkc_ipertype R1) (mkc_ipertype R2) (mkc_uni i)\n     [+] cequivc (mkc_ipertype R1) (mkc_ipertype R2))\n    -> forall x y : CTerm,\n         (type lib (mkc_apply2 R1 x y) [+] type lib (mkc_apply2 R2 x y))\n         -> tequality lib (mkc_apply2 R1 x y)\n                      (mkc_apply2 R2 x y).\nProof.\n  introv eq.\n  introv typ.\n  destruct eq.\n\n  apply equality_in_uni in e.\n  rw tequality_mkc_ipertype in e; sp.\n\n  generalize (cequivc_mkc_ipertype lib (mkc_ipertype R1) (mkc_ipertype R2) R1);\n    intro j; repeat (dest_imp j hyp); try (complete computes_to_value_refl); exrepnd.\n  computes_to_value_isvalue.\n  assert (cequivc (mkc_apply2 R1 x y) (mkc_apply2 b x y))\n         as ceq\n         by (repeat (rw mkc_apply2_eq); repeat (apply sp_implies_cequivc_apply); sp).\n  destruct typ.\n  apply type_respects_cequivc_right; sp.\n  apply type_respects_cequivc_left; sp.\n  apply cequivc_sym; sp.\nQed.\n*)\n\n\nLemma equality_in_mkc_pertype {p} :\n  forall lib (t1 t2 R : @CTerm p),\n    equality lib t1 t2 (mkc_pertype R)\n    <=> (inhabited_type lib (mkc_apply2 R t1 t2)\n         # is_per_type lib R\n         # (forall x y, type lib (mkc_apply2 R x y))).\nProof.\n  intros; unfold inhabited_type; split; intro i; exrepnd.\n\n  - unfold equality, nuprl in i; exrepnd.\n    inversion i1; subst; try not_univ.\n    dest_per.\n    allfold (@nuprl p lib).\n    computes_to_value_isvalue.\n    rw pereq in i0.\n    clear typ2 inhiff eq2.\n    unfold inhabited in i0; exrepnd.\n    dands.\n\n    exists t; unfold member, equality; exists (eq1 t1 t2); sp.\n\n    generalize (is_per_type_iff_is_per lib R1 eq1); introv iff.\n    dest_imp iff hyp.\n    rw <- iff; sp.\n\n    introv.\n    unfold type, tequality.\n    exists (eq1 x y); sp.\n\n  - unfold member, equality in i2; exrepnd.\n    generalize (choice_spteq lib (mkc_apply2 R) (mkc_apply2 R)); intro fn.\n    dest_imp fn hyp; exrepnd.\n    generalize (fn0 t1 t2); intro n.\n    pose proof (nuprl_uniquely_valued lib (mkc_apply2 R t1 t2) eq (f t1 t2)) as eqt.\n    repeat (dest_imp eqt hyp).\n\n    exists (fun a b => inhabited (f a b)); sp;\n    try (complete (rw eqt in i0; exists t; sp)).\n\n    apply CL_pertype; unfold per_pertype.\n    allfold (@nuprl p lib).\n    exists R R f f; sp;\n    try (spcast; complete computes_to_value_refl).\n\n    generalize (is_per_type_iff_is_per lib R f); introv iff.\n    dest_imp iff hyp.\n    rw iff; sp.\nQed.\n\nLemma equality_in_mkc_pertype2 {p} :\n  forall lib (t1 t2 R : @CTerm p),\n    equality lib t1 t2 (mkc_pertype R)\n    <=> (inhabited_type lib (mkc_apply2 R t1 t2) # type lib (mkc_pertype R)).\nProof.\n  introv.\n  rw @equality_in_mkc_pertype.\n  rw @type_mkc_pertype; split; sp.\nQed.\n\nLemma equality_in_mkc_ipertype {p} :\n  forall lib (t1 t2 R : @CTerm p),\n    equality lib t1 t2 (mkc_ipertype R)\n    <=> (inhabited_type lib (mkc_apply2 R t1 t2)\n         # is_per_type lib R\n         # (forall x y, type lib (mkc_apply2 R x y))).\nProof.\n  intros; unfold inhabited_type; split; intro i; exrepnd.\n\n  - unfold equality, nuprl in i; exrepnd.\n    inversion i1; subst; try not_univ.\n    dest_per.\n    allfold (@nuprl p lib).\n    computes_to_value_isvalue.\n    rw pereq in i0.\n    unfold pertype_eq, inhabited in i0; exrepnd.\n    dands.\n\n    exists t; unfold member, equality; exists (eq1 t1 t2); sp.\n\n    generalize (is_per_type_iff_is_per lib R1 eq1 eqtyps); introv iff.\n    apply iff; auto.\n\n    introv; exists (eq1 x y); sp.\n\n  - unfold member, equality, nuprl in i2; exrepnd.\n    allfold (@nuprl p lib).\n    generalize (choice_spteq lib (mkc_apply2 R) (mkc_apply2 R) i); intro fn; exrepnd.\n    generalize (fn0 t1 t2); intro n.\n    pose proof (nuprl_uniquely_valued lib (mkc_apply2 R t1 t2) eq (f t1 t2)) as eqt.\n    repeat (autodimp eqt hyp).\n\n    exists (fun a b => inhabited (f a b)); sp;\n    try (complete (rw eqt in i0; exists t; sp)).\n\n    apply CL_ipertype; unfold per_ipertype.\n    allfold (@nuprl p lib).\n    exists R R f; sp;\n    try (spcast; complete computes_to_value_refl).\n\n    generalize (is_per_type_iff_is_per lib R f fn0); introv iff.\n    rw iff; sp.\nQed.\n\nLemma equality_in_mkc_ipertype2 {p} :\n  forall lib (t1 t2 R : @CTerm p),\n    equality lib t1 t2 (mkc_ipertype R)\n    <=> (inhabited_type lib (mkc_apply2 R t1 t2) # type lib (mkc_ipertype R)).\nProof.\n  introv.\n  rw @equality_in_mkc_ipertype.\n  rw @type_mkc_ipertype; split; sp.\nQed.\n\nLemma equality_in_mkc_spertype {p} :\n  forall lib (t1 t2 R : @CTerm p),\n    equality lib t1 t2 (mkc_spertype R)\n    <=> (inhabited_type lib (mkc_apply2 R t1 t2)\n         # (forall x y, type lib (mkc_apply2 R x y))\n         # (forall x y z,\n              inhabited_type lib (mkc_apply2 R x z)\n              -> tequality lib (mkc_apply2 R x y) (mkc_apply2 R z y))\n         # (forall x y z,\n              inhabited_type lib (mkc_apply2 R y z)\n              -> tequality lib (mkc_apply2 R x y) (mkc_apply2 R x z))\n         # is_per_type lib R).\nProof.\n  intros.\n  rw <- @type_mkc_spertype.\n  split; intro i; exrepnd.\n\n  - applydup @inhabited_implies_tequality in i as ty; dands; auto.\n    unfold equality, nuprl in i; exrepnd.\n    inversion i1; subst; try not_univ.\n    dest_per.\n    allfold (@nuprl p lib).\n    computes_to_value_isvalue.\n    rw pereq in i0.\n    unfold pertype_eq, inhabited in i0; exrepnd.\n\n    exists t; unfold member, equality; exists (eq1 t1 t2); sp.\n\n  - rw @type_mkc_spertype in i; repnd.\n    unfold inhabited_type in i0; exrepnd.\n    unfold member, equality, nuprl in i4; exrepnd.\n    allfold (@nuprl p lib).\n    generalize (choice_spteq lib (mkc_apply2 R) (mkc_apply2 R) i1); intro fn; exrepnd.\n    generalize (fn0 t1 t2); intro n.\n    pose proof (nuprl_uniquely_valued lib (mkc_apply2 R t1 t2) eq (f t1 t2)) as eqt.\n    repeat (autodimp eqt hyp).\n\n    exists (fun a b => inhabited (f a b)); sp;\n    try (complete (rw eqt in i0; exists t; sp)).\n\n    apply CL_spertype; unfold per_spertype.\n    allfold (@nuprl p lib).\n    exists R R f; dands; introv;\n    try (spcast; complete computes_to_value_refl);\n    try (complete sp).\n\n    introv inh.\n    generalize (fn0 x z); intro e.\n    apply inhabited_type_if_inhabited in e; auto.\n    apply i2 with (y := y) in e.\n    rw <- @tequality_iff_nuprl in e; exrepnd.\n    generalize (fn0 x y); intro nu.\n    generalize (nuprl_uniquely_valued lib (mkc_apply2 R x y) eq0 (f x y));\n      intro eqs; repeat (autodimp eqs hyp).\n    apply nuprl_refl in e0; auto.\n    apply nuprl_ext with (eq1 := eq0); auto.\n\n    introv inh.\n    generalize (fn0 y z); intro e.\n    apply inhabited_type_if_inhabited in e; auto.\n    apply i3 with (x := x) in e.\n    rw <- @tequality_iff_nuprl in e; exrepnd.\n    generalize (fn0 x y); intro nu.\n    generalize (nuprl_uniquely_valued lib (mkc_apply2 R x y) eq0 (f x y));\n      intro eqs; repeat (autodimp eqs hyp).\n    apply nuprl_refl in e0; auto.\n    apply nuprl_ext with (eq1 := eq0); auto.\n\n    generalize (is_per_type_iff_is_per lib R f fn0); introv iff.\n    rw iff; sp.\nQed.\n\nLemma equality_in_mkc_spertype2 {p} :\n  forall lib (t1 t2 R : @CTerm p),\n    equality lib t1 t2 (mkc_spertype R)\n    <=> (inhabited_type lib (mkc_apply2 R t1 t2)\n         # type lib (mkc_spertype R)).\nProof.\n  intros.\n  rw @equality_in_mkc_spertype.\n  rw @type_mkc_spertype; sp.\nQed.\n\nLemma iff_inhabited_type_if_pertype_cequorsq {p} :\n  forall lib (R1 R2 : @CTerm p) i,\n    equorsq lib (mkc_pertype R1) (mkc_pertype R2) (mkc_uni i)\n    -> forall x y,\n         inhabited_type lib (mkc_apply2 R1 x y)\n          <=> inhabited_type lib (mkc_apply2 R2 x y).\nProof.\n  unfold equorsq; introv or.\n  introv.\n  split; intro inh; repdors.\n\n  apply equality_in_uni in or0.\n  rw @tequality_mkc_pertype in or0; repnd.\n  rw <- or3; sp.\n\n  spcast.\n  generalize (cequivc_mkc_pertype lib (mkc_pertype R1) (mkc_pertype R2) R1);\n    intro j; repeat (dest_imp j hyp); try (complete computes_to_value_refl); exrepnd.\n  computes_to_value_isvalue.\n  assert (cequivc lib (mkc_apply2 R1 x y) (mkc_apply2 b x y))\n         as ceq\n         by (repeat (rw @mkc_apply2_eq); repeat (apply sp_implies_cequivc_apply); sp).\n  apply inhabited_type_cequivc with (a := mkc_apply2 R1 x y); sp.\n\n  apply equality_in_uni in or0.\n  rw @tequality_mkc_pertype in or0; repnd.\n  rw or3; sp.\n\n  spcast.\n  generalize (cequivc_mkc_pertype lib (mkc_pertype R1) (mkc_pertype R2) R1);\n    intro j; repeat (dest_imp j hyp); try (complete computes_to_value_refl); exrepnd.\n  computes_to_value_isvalue.\n  assert (cequivc lib (mkc_apply2 R1 x y) (mkc_apply2 b x y))\n         as ceq\n         by (repeat (rw @mkc_apply2_eq); repeat (apply sp_implies_cequivc_apply); sp).\n  apply inhabited_type_cequivc with (a := mkc_apply2 b x y); sp.\n  apply cequivc_sym; sp.\nQed.\n\nLemma iff_inhabited_type_if_ipertype_cequorsq {p} :\n  forall lib (R1 R2 : @CTerm p) i,\n    (forall x y : CTerm, type lib (mkc_apply2 R1 x y))\n    -> equorsq lib (mkc_ipertype R1) (mkc_ipertype R2) (mkc_uni i)\n    -> forall x y, tequality lib (mkc_apply2 R1 x y) (mkc_apply2 R2 x y).\nProof.\n  unfold equorsq; introv istype or; introv.\n  repdors.\n\n  apply equality_in_uni in or0.\n  rw @tequality_mkc_ipertype in or0; repnd; sp.\n\n  spcast.\n  generalize (cequivc_mkc_ipertype lib (mkc_ipertype R1) (mkc_ipertype R2) R1);\n    intro j; repeat (dest_imp j hyp); try (complete computes_to_value_refl); exrepnd.\n  computes_to_value_isvalue.\n  assert (cequivc lib (mkc_apply2 R1 x y) (mkc_apply2 b x y))\n         as ceq\n         by (repeat (rw @mkc_apply2_eq); repeat (apply sp_implies_cequivc_apply); sp).\n  generalize (istype x y); intro t.\n  apply cequivc_sym in ceq; rwg ceq; sp.\nQed.\n\nLemma iff_inhabited_type_if_spertype_cequorsq {p} :\n  forall lib (R1 R2 : @CTerm p) i,\n    (forall x y : CTerm, type lib (mkc_apply2 R1 x y))\n    -> equorsq lib (mkc_spertype R1) (mkc_spertype R2) (mkc_uni i)\n    -> forall x y, tequality lib (mkc_apply2 R1 x y) (mkc_apply2 R2 x y).\nProof.\n  unfold equorsq; introv istype or; introv.\n  repdors.\n\n  apply equality_in_uni in or0.\n  rw @tequality_mkc_spertype in or0; repnd; sp.\n\n  spcast.\n  generalize (cequivc_mkc_spertype lib (mkc_spertype R1) (mkc_spertype R2) R1);\n    intro j; repeat (dest_imp j hyp); try (complete computes_to_value_refl); exrepnd.\n  computes_to_value_isvalue.\n  assert (cequivc lib (mkc_apply2 R1 x y) (mkc_apply2 b x y))\n         as ceq\n         by (repeat (rw @mkc_apply2_eq); repeat (apply sp_implies_cequivc_apply); sp).\n  generalize (istype x y); intro t.\n  apply cequivc_sym in ceq; rwg ceq; sp.\nQed.\n\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/per/per_props_pertype.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.22548489476859757}}
{"text": "Require Import VST.floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\nRequire Import VST.zlist.sublist.\n\nRequire Import sha.HMAC256_functional_prog.\nRequire Import sha.general_lemmas.\nRequire Import sha.spec_sha.\n\nRequire Import hmacdrbg.entropy.\nRequire Import hmacdrbg.entropy_lemmas.\nRequire Import hmacdrbg.HMAC256_DRBG_functional_prog.\nRequire Import hmacdrbg.hmac_drbg.\nRequire Import hmacdrbg.DRBG_functions.\nRequire Import hmacdrbg.HMAC_DRBG_algorithms.\nRequire Import hmacdrbg.HMAC_DRBG_pure_lemmas.\nRequire Import hmacdrbg.spec_hmac_drbg.\nRequire Import hmacdrbg.drbg_protocol_specs.\nRequire Import hmacdrbg.spec_hmac_drbg_pure_lemmas.\nRequire Import hmacdrbg.HMAC_DRBG_common_lemmas.\nRequire Import hmacdrbg.verif_hmac_drbg_WF.\n\nOpaque HMAC256.\nOpaque hmac256drbgabs_generate.\nOpaque HMAC256_DRBG_generate_function.\nOpaque mbedtls_HMAC256_DRBG_generate_function.\n\nLemma while_loop_post_incremental_snd:\n  forall key0 V0 n out_len,\n    0 <= (n * 32)%Z <= out_len ->\n    (n * 32)%Z <> out_len ->\n snd (HMAC_DRBG_generate_helper_Z HMAC256 key0 V0 (n * 32)%Z) ++\n fst\n   (HMAC_DRBG_generate_helper_Z HMAC256 key0 V0\n      ((n * 32)%Z + Z.min 32 (out_len - (n * 32)%Z))) =\n snd\n   (HMAC_DRBG_generate_helper_Z HMAC256 key0 V0\n      ((n * 32)%Z + Z.min 32 (out_len - (n * 32)%Z))).\nProof.\n  intros.\n  rewrite Zmin_spec.\n  destruct (Z_lt_ge_dec 32 (out_len - (n * 32))) as [Hmin | Hmin].\n  {\n    rewrite zlt_true by assumption.\n    apply HMAC_DRBG_generate_helper_Z_incremental_snd; auto; lia.\n  }\n  {\n    rewrite zlt_false by assumption.\n    assert (0 < out_len - (n * 32)%Z <= 32).\n    {\n      split.\n      rewrite <- Z2Nat.id in *; try lia.\n      remember (Z.to_nat (out_len - n * 32)) as n'; destruct n'.\n      {\n        (* contradiction. out_len - n <> 0 *)\n        assert (0 = out_len - n * 32).\n        {\n          symmetry;\n          apply Z2Nat_inj_0.\n          lia.\n          symmetry; assumption.\n        }\n        assert (out_len = (n * 32)%Z) by lia.\n        lia.\n      }\n      lia.\n    }\n    assert (exists n', (n * 32)%Z = (n' * 32)%Z).\n    {\n      exists n; reflexivity.\n    }\n    rewrite HMAC_DRBG_generate_helper_Z_incremental_equiv; auto; try lia.\n    apply HMAC_DRBG_generate_helper_Z_incremental_snd; auto; lia.\n  }\nQed.\n\nLemma while_loop_post_incremental_fst:\n  forall key0 V0 n out_len,\n    0 <= (n * 32)%Z <= out_len ->\n    (n * 32)%Z <> out_len ->\n  fst (HMAC_DRBG_generate_helper_Z HMAC256 key0 V0\n      ((n * 32)%Z + Z.min 32 (out_len - (n * 32)%Z))) =\n HMAC256 (fst (HMAC_DRBG_generate_helper_Z HMAC256 key0 V0 (n * 32)%Z)) key0.\nProof.\n  intros.\n  rewrite Zmin_spec.\n  destruct (Z_lt_ge_dec 32 (out_len - (n * 32))) as [Hmin | Hmin].\n  {\n    rewrite zlt_true by assumption.\n    symmetry; apply HMAC_DRBG_generate_helper_Z_incremental_fst; auto; lia.\n  }\n  {\n    rewrite zlt_false by assumption.\n    assert (0 < out_len - (n * 32)%Z <= 32).\n    {\n      split.\n      rewrite <- Z2Nat.id in *; try lia.\n      remember (Z.to_nat (out_len - n * 32)) as n'; destruct n'.\n      {\n        (* contradiction. out_len - n <> 0 *)\n        assert (0 = out_len - n * 32).\n        {\n          symmetry;\n          apply Z2Nat_inj_0.\n          lia.\n          symmetry; assumption.\n        }\n        assert (out_len = (n * 32)%Z) by lia.\n        lia.\n      }\n      lia.\n    }\n    assert (exists n', (n * 32)%Z = (n' * 32)%Z).\n    {\n      exists n; reflexivity.\n    }\n    rewrite HMAC_DRBG_generate_helper_Z_incremental_equiv; auto; try lia.\n    symmetry; apply HMAC_DRBG_generate_helper_Z_incremental_fst; auto; lia.\n  }\nQed.\n\nLemma while_loop_post_sublist_app:\n  forall key0 V0 n out_len,\n    0 <= (n * 32)%Z <= out_len ->\n    Zlength V0 = 32 ->\n  sublist 0 (n * 32)\n     (snd (HMAC_DRBG_generate_helper_Z HMAC256 key0 V0 (n * 32))) ++\n   sublist 0 (Z.min 32 (out_len - n * 32))\n     (fst\n        (HMAC_DRBG_generate_helper_Z HMAC256 key0 V0\n           (n * 32 + Z.min 32 (out_len - n * 32)))) =\n   sublist 0 (n * 32 + Z.min 32 (out_len - n * 32))\n     (snd (HMAC_DRBG_generate_helper_Z HMAC256 key0 V0 (n * 32)) ++\n      fst\n        (HMAC_DRBG_generate_helper_Z HMAC256 key0 V0\n           (n * 32 + Z.min 32 (out_len - n * 32)))).\nProof.\n  intros.\n  remember (snd (HMAC_DRBG_generate_helper_Z HMAC256 key0 V0 (n * 32))) as A.\n  assert (HlengthA: Zlength A = (n * 32)%Z).\n  {\n    subst.\n    apply HMAC_DRBG_generate_helper_Z_Zlength_snd.\n    lia.\n    apply hmac_common_lemmas.HMAC_Zlength.\n    exists n; reflexivity.\n  }\n  clear HeqA.\n  remember (fst\n        (HMAC_DRBG_generate_helper_Z HMAC256 key0 V0\n           (n * 32 + Z.min 32 (out_len - n * 32)))) as B.\n  assert (HlengthB: Zlength B = 32).\n  {\n    subst.\n    apply HMAC_DRBG_generate_helper_Z_Zlength_fst.\n    rewrite Zmin_spec.\n    destruct (Z_lt_ge_dec 32 (out_len - (n * 32))) as [Hmin | Hmin].\n    rewrite zlt_true by assumption; lia.\n    rewrite zlt_false by assumption; lia.\n    assumption.\n    apply hmac_common_lemmas.HMAC_Zlength.\n  }\n  clear HeqB.\n  rewrite <- HlengthA in *.\n  rewrite <- HlengthB in *.\n  clear - H HlengthB.\n  rewrite sublist_same; auto.\n  rewrite sublist_app; try now (\n    rewrite Zmin_spec;\n    destruct (Z_lt_ge_dec (Zlength B) (out_len - (Zlength A))) as [Hmin | Hmin]; [rewrite zlt_true by assumption| rewrite zlt_false by assumption]; lia).\n  assert (Hmin0: Z.min 0 (Zlength A) = 0).\n  {\n    rewrite Zmin_spec.\n    rewrite <- (Z2Nat.id (Zlength A)) in *; try apply Zlength_nonneg.\n    destruct (Z.to_nat (Zlength A)).\n    reflexivity.\n    reflexivity.\n  }\n  rewrite Hmin0.\n  assert (HminA: (Z.min (Zlength A + Z.min (Zlength B) (out_len - Zlength A)) (Zlength A)) = Zlength A).\n  {\n    rewrite Zmin_spec.\n    rewrite zlt_false; auto.\n    destruct (Z.min_dec (Zlength B) (out_len - Zlength A)) as [Hmin | Hmin]; rewrite Hmin; lia.\n  }\n  rewrite HminA.\n  rewrite sublist_same with (hi:=Zlength A); try lia.\n  assert (Hmax0: (Z.max (0 - Zlength A) 0) = 0).\n  {\n    rewrite Zmax_spec.\n    rewrite zlt_false; auto; lia.\n  }\n  rewrite Hmax0.\n  replace (Zlength A + Z.min (Zlength B) (out_len - Zlength A) - Zlength A) with (Z.min (Zlength B) (out_len - Zlength A)) by lia.\n  assert (HmaxB: (Z.max (Z.min (Zlength B) (out_len - Zlength A)) 0) = (Z.min (Zlength B) (out_len - Zlength A))).\n  {\n    rewrite <- (Z2Nat.id (out_len - Zlength A)) in *; try lia.\n  }\n  rewrite HmaxB.\n  reflexivity.\nQed.    \n\n(*\nLemma generate_correct:\n  forall should_reseed non_empty_additional s initial_state_abs out_len contents,\n    hmac256drbgabs_reseed_interval initial_state_abs = 10000 ->\n    hmac256drbgabs_entropy_len initial_state_abs = 32 ->\n    out_len >? 1024 = false ->\n    Zlength contents >? 256 = false ->\n    (should_reseed = true -> exists entropy_bytes s', get_entropy 256 (hmac256drbgabs_entropy_len initial_state_abs) (hmac256drbgabs_entropy_len initial_state_abs) (hmac256drbgabs_prediction_resistance initial_state_abs) s = ENTROPY.success entropy_bytes s') ->\n    should_reseed = (hmac256drbgabs_prediction_resistance initial_state_abs\n                       || (hmac256drbgabs_reseed_counter initial_state_abs >? hmac256drbgabs_reseed_interval initial_state_abs))%bool ->\n    non_empty_additional = (if should_reseed\n                            then false\n                            else\n                              match contents with\n                                | [] => false\n                                | _ :: _ => true\n                              end) ->\n  mbedtls_HMAC256_DRBG_generate_function s initial_state_abs out_len contents\n  = ENTROPY.success (\n        (sublist 0 out_len\n                 (snd\n                    (HMAC_DRBG_generate_helper_Z HMAC256\n                       (hmac256drbgabs_key\n                          (if non_empty_additional\n                           then\n                            hmac256drbgabs_hmac_drbg_update initial_state_abs\n                              contents\n                           else\n                            if should_reseed\n                            then\n                             hmac256drbgabs_reseed initial_state_abs s\n                               contents\n                            else initial_state_abs))\n                       (hmac256drbgabs_value\n                          (if non_empty_additional\n                           then\n                            hmac256drbgabs_hmac_drbg_update initial_state_abs\n                              contents\n                           else\n                            if should_reseed\n                            then\n                             hmac256drbgabs_reseed initial_state_abs s\n                               contents\n                            else initial_state_abs)) out_len))),\n        (hmac256drbgabs_to_state_handle (hmac256drbgabs_increment_reseed_counter (hmac256drbgabs_hmac_drbg_update\n           (hmac256drbgabs_update_value\n              (if non_empty_additional\n               then\n                hmac256drbgabs_hmac_drbg_update initial_state_abs contents\n               else\n                if should_reseed\n                then hmac256drbgabs_reseed initial_state_abs s contents\n                else initial_state_abs)\n              (fst\n                 (HMAC_DRBG_generate_helper_Z HMAC256\n                    (hmac256drbgabs_key\n                       (if non_empty_additional\n                        then\n                         hmac256drbgabs_hmac_drbg_update initial_state_abs\n                           contents\n                        else\n                         if should_reseed\n                         then\n                          hmac256drbgabs_reseed initial_state_abs s contents\n                         else initial_state_abs))\n                    (hmac256drbgabs_value\n                       (if non_empty_additional\n                        then\n                         hmac256drbgabs_hmac_drbg_update initial_state_abs\n                           contents\n                        else\n                         if should_reseed\n                         then\n                          hmac256drbgabs_reseed initial_state_abs s contents\n                         else initial_state_abs)) out_len)))\n           (if should_reseed then [] else contents))))\n                      ) (if should_reseed\n         then\n          get_stream_result\n            (mbedtls_HMAC256_DRBG_reseed_function s initial_state_abs\n               contents)\n         else s).\nProof.\n  intros until contents.\n  intros Hreseed_interval Hentropy_len Hout_lenb HZlength_contentsb Hget_entropy Hshould_reseed Hnon_empty_additional.\n  destruct initial_state_abs.\n  simpl in *.\n  unfold hmac256drbgabs_reseed.\n  unfold mbedtls_HMAC256_DRBG_reseed_function.\n  unfold mbedtls_HMAC256_DRBG_generate_function.\n  unfold HMAC256_DRBG_generate_function, HMAC256_DRBG_reseed_function.\n  unfold DRBG_generate_function, DRBG_reseed_function.\n  unfold DRBG_generate_function_helper.\n  unfold HMAC256_DRBG_generate_algorithm.\n  unfold HMAC_DRBG_generate_algorithm.\n  unfold hmac256drbgabs_key.\n  unfold hmac256drbgabs_value.\n  unfold hmac256drbgabs_update_value.\n  unfold hmac256drbgabs_hmac_drbg_update.\n  unfold HMAC256_DRBG_update.\n  unfold HMAC_DRBG_update.\n  unfold hmac256drbgabs_increment_reseed_counter.\n  unfold hmac256drbgabs_to_state_handle.\n  rewrite Hout_lenb.\n  change (0 >? 256) with false.\n  rewrite HZlength_contentsb.\n  rewrite andb_negb_r.\n  unfold sublist.\n  unfold skipn.\n  replace (out_len - 0) with out_len by lia.\n \n  destruct prediction_resistance.\n  {\n    (* pr = true *)\n    subst.\n    destruct Hget_entropy as [entropy_bytes [s' Hget_entropy]]; auto.\n    rewrite Hget_entropy.\n    destruct entropy_bytes.\n    {\n      (* contradiction, can't get 0 bytes back as entropy *)\n      assert (contra: Zlength (@nil Z) = 32).\n      {\n        eapply get_bytes_Zlength.\n        lia.\n        unfold get_entropy in Hget_entropy.\n        subst.\n        symmetry; apply Hget_entropy;auto.\n        \n      }\n      change (Zlength (@nil Z)) with 0 in contra.\n      inversion contra.\n    }\n    simpl.\n    remember (HMAC_DRBG_generate_helper_Z HMAC256\n              (HMAC256\n                 (HMAC256 V\n                    (HMAC256 (V ++ 0 :: z :: entropy_bytes ++ contents) key) ++\n                  1 :: z :: entropy_bytes ++ contents)\n                 (HMAC256 (V ++ 0 :: z :: entropy_bytes ++ contents) key))\n              (HMAC256\n                 (HMAC256 V\n                    (HMAC256 (V ++ 0 :: z :: entropy_bytes ++ contents) key))\n                 (HMAC256\n                    (HMAC256 V\n                       (HMAC256 (V ++ 0 :: z :: entropy_bytes ++ contents)\n                          key) ++ 1 :: z :: entropy_bytes ++ contents)\n                    (HMAC256 (V ++ 0 :: z :: entropy_bytes ++ contents) key)))\n              out_len) as generate_helper_result; destruct generate_helper_result.\n    reflexivity.\n  }\n  (* pr = false *)\n  subst reseed_interval.\n  unfold HMAC_DRBG_update.\n  rewrite HZlength_contentsb.\n  \n  destruct (reseed_counter >? 10000).\n  {\n    (* must reseed *)\n    subst.\n    destruct Hget_entropy as [entropy_bytes [s' Hget_entropy]]; auto.\n    rewrite Hget_entropy.\n    destruct entropy_bytes.\n    {\n      (* contradiction, can't get 0 bytes back as entropy *)\n      assert (contra: Zlength (@nil Z) = 32).\n      {\n        eapply get_bytes_Zlength.\n        lia.\n        unfold get_entropy in Hget_entropy.\n        subst.\n        symmetry; apply Hget_entropy; auto.\n        \n      }\n      change (Zlength (@nil Z)) with 0 in contra.\n      inversion contra.\n    }\n    simpl.\n    remember (HMAC_DRBG_generate_helper_Z HMAC256\n              (HMAC256\n                 (HMAC256 V\n                    (HMAC256 (V ++ 0 :: z :: entropy_bytes ++ contents) key) ++\n                  1 :: z :: entropy_bytes ++ contents)\n                 (HMAC256 (V ++ 0 :: z :: entropy_bytes ++ contents) key))\n              (HMAC256\n                 (HMAC256 V\n                    (HMAC256 (V ++ 0 :: z :: entropy_bytes ++ contents) key))\n                 (HMAC256\n                    (HMAC256 V\n                       (HMAC256 (V ++ 0 :: z :: entropy_bytes ++ contents)\n                          key) ++ 1 :: z :: entropy_bytes ++ contents)\n                    (HMAC256 (V ++ 0 :: z :: entropy_bytes ++ contents) key)))\n              out_len) as generate_helper_result; destruct generate_helper_result.\n    reflexivity.\n  }\n  simpl in Hshould_reseed; subst should_reseed.\n  destruct contents.\n  {\n    (* contents empty *)\n    subst.\n    simpl.\n    remember (HMAC_DRBG_generate_helper_Z HMAC256 key V out_len) as generate_helper_result; destruct generate_helper_result.\n    reflexivity.\n  }\n  (* contents not empty *)\n  subst.\n  destruct (HMAC_DRBG_generate_helper_Z HMAC256\n                (HMAC256\n                   (HMAC256 V (HMAC256 (V ++ [0] ++ z :: contents) key) ++\n                    [1] ++ z :: contents)\n                   (HMAC256 (V ++ [0] ++ z :: contents) key))\n                (HMAC256\n                   (HMAC256 V (HMAC256 (V ++ [0] ++ z :: contents) key))\n                   (HMAC256\n                      (HMAC256 V (HMAC256 (V ++ [0] ++ z :: contents) key) ++\n                       [1] ++ z :: contents)\n                      (HMAC256 (V ++ [0] ++ z :: contents) key))) out_len).\n  reflexivity.\nQed.\n*)(*\nRequire Import hmacdrbg.verif_gen_c1.\nDeclare Module M :Continuation1.\n*)\n\n(*\nDefinition postReseedCtx s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents mc1 mc2 mc3 b i: mpred :=\n  match mbedtls_HMAC256_DRBG_reseed_function s\n               (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance\n                  reseed_interval) (contents_with_add additional (Zlength contents) contents)\n  with ENTROPY.success (RSVal, RSKey, aa, bb, cc) s0 => \n       data_at Tsh t_struct_hmac256drbg_context_st\n           (mc1, (mc2, mc3),\n           (map Vint (map Int.repr RSVal),\n           (Vint (Int.repr aa),\n           (Vint (Int.repr entropy_len), (bool2val cc, Vint (Int.repr reseed_interval))))))\n           (Vptr b i)\n   | _ => FF\n  end.\n*)\n(*\nDefinition postReseedCtx (CTX:reptype t_struct_hmac256drbg_context_st) s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents (mc:mdstate): Prop :=\n  match mbedtls_HMAC256_DRBG_reseed_function s\n               (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance\n                  reseed_interval) (contents_with_add additional (Zlength contents) contents)\n  with ENTROPY.success (RSVal, RSKey, aa, bb, cc) s0 => CTX =\n           (mc,\n           (map Vint (map Int.repr RSVal),\n           (Vint (Int.repr aa),\n           (Vint (Int.repr entropy_len), (bool2val cc, Vint (Int.repr reseed_interval))))))\n   | _ => False\n  end.\n\nDefinition postReseedKey s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents mc1 mc2 mc3: mpred :=\n  match mbedtls_HMAC256_DRBG_reseed_function s\n               (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance\n                  reseed_interval) (contents_with_add additional (Zlength contents) contents)\n  with ENTROPY.success (RSVal, RSKey, aa, bb, cc) s0 => md_full RSKey (mc1, (mc2, mc3))\n  | _ => FF\n  end.\n\nDefinition postReseedStream s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents: mpred :=\n  match mbedtls_HMAC256_DRBG_reseed_function s\n               (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance\n                  reseed_interval) (contents_with_add additional (Zlength contents) contents)\n  with ENTROPY.success (RSVal, RSKey, aa, bb, cc) s0 => Stream s0\n  | _ => FF\n  end.\n\nDefinition mkCTX0 (should_reseed:bool) (initial_state:reptype t_struct_hmac256drbg_context_st) s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents mc p: mpred :=\n  EX myctx:reptype t_struct_hmac256drbg_context_st%type, \n           (!!(if should_reseed \n                then postReseedCtx myctx s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents mc\n                else myctx = initial_state)) &&\n             data_at Tsh t_struct_hmac256drbg_context_st myctx p.*)\n(*alternative definitions that don't help\nDefinition myMpred0 (should_reseed:bool) initial_state s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents mc p: mpred :=\n  EX myctx:(val * (val * val) * (list val * (val * (val * (val * val)))))%type, \n           (!!(if should_reseed \n                then postReseedCtx myctx s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents mc\n                else myctx = initial_state)) &&\n             data_at Tsh t_struct_hmac256drbg_context_st myctx p.\nDefinition myMpred1 (should_reseed:bool) initial_state s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents mc p: mpred :=\n  EX q1:val, EX q2:val, EX q3:val, EX q4:list val, EX q5:val, EX q6:val, EX q7:val, EX q8:val,\n           (!!(if should_reseed \n                then postReseedCtx (q1, (q2, q3), (q4, (q5, (q6, (q7, q8))))) s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents mc\n                else (q1, (q2, q3), (q4, (q5, (q6, (q7, q8))))) = initial_state)) &&\n             data_at Tsh t_struct_hmac256drbg_context_st (q1, (q2, q3), (q4, (q5, (q6, (q7, q8))))) p.\n*)\n(*\nDefinition mkCTX1 (should_reseed:bool) (ctx ctx1:reptype t_struct_hmac256drbg_context_st) \n            s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents mc: Prop :=\n     if should_reseed \n     then match mbedtls_HMAC256_DRBG_reseed_function s\n        (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval)\n        (contents_with_add additional (Zlength contents) contents)\n       with\n      | ENTROPY.success (RSVal, _, aa, _, cc) _ =>\n           ctx1 = (mc,\n                  (map Vint (map Int.repr RSVal),\n                  (Vint (Int.repr aa),\n                  (Vint (Int.repr entropy_len), (bool2val cc, Vint (Int.repr reseed_interval))))))\n      | ENTROPY.error _ _ => False\n       end\n     else ctx1 = ctx.\n\nDefinition mkKEY1 (should_reseed:bool) s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents key1 : Prop:=\n  if should_reseed\n  then match mbedtls_HMAC256_DRBG_reseed_function s\n        (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval)\n        (contents_with_add additional (Zlength contents) contents)\n    with\n    | ENTROPY.success (_, RSKey, _, _, _) _ => key1 = RSKey\n    | ENTROPY.error _ _ => False\n    end\n  else key1=key.*)\n\nDefinition mkSTREAM1 (should_reseed:bool) s key V reseed_counter entropy_len prediction_resistance reseed_interval additional contents stream1 : Prop :=\n  if should_reseed\n          then\n           match\n             mbedtls_HMAC256_DRBG_reseed_function s\n               (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance\n                  reseed_interval)\n               (contents_with_add additional (Zlength contents) contents)\n           with\n           | ENTROPY.success (_, _, _, _, _) s0 => stream1 = s0\n           | ENTROPY.error _ _ => False\n           end\n          else stream1 = s.\n\n(* IT'S PATHETIC THAT WE NEED TO INTRDUCE ctx2' AND a predicate CTXeq to wotk around FLOYD'S typechecker!!*)\n(*Definition CTXeq (c:reptype t_struct_hmac256drbg_context_st)\n                 (c':(val * (val * val) * (list val * (val * (val * (val * val)))))%type) : Prop := c'=c.\n*)\nDefinition is_multiple (multiple base: Z) : Prop := exists i, multiple = (i * base)%Z.\n\nLemma entailment1: forall (contents : list byte) (additional: val) (sha: share) (output : val) (sho: share)\n  (out_len : Z) (b : block) (i : ptrofs) (shc: share) (mc1 mc2 mc3 : val) (key V : list byte)\n  (reseed_counter entropy_len : Z) (prediction_resistance : bool)\n  (reseed_interval : Z) (gv : globals) (Info : md_info_state)\n  (s : ENTROPY.stream)\n  (I := HMAC256DRBGabs key V reseed_counter entropy_len\n                       prediction_resistance reseed_interval : hmac256drbgabs)\n(*(RI : reseed_interval = 10000)*)\n  (a := (mc1, (mc2, mc3),\n                 (map Vubyte V,\n                 (Vint (Int.repr reseed_counter),\n                 (Vint (Int.repr entropy_len),\n                 (bool2val prediction_resistance,\n                 Vint (Int.repr reseed_interval))))))\n              : mdstate * (list val * (val * (val * (val * val)))))\n  (WFI: WF I)\n  (Hout_lenb : (out_len >? 1024) = false)\n  (ZLa : (Zlength (contents_with_add additional (Zlength contents) contents) >? 256) =\n      false)\n  (Hshould_reseed : (prediction_resistance || (reseed_counter >? reseed_interval))%bool =\n                 true)\n(*  (F : (0 >? 256) = false)*)\n  (F32 : (32 >? 32) = false)\n  (return_value : int)\n  (Hrv : negb (Int.eq return_value (Int.repr 0)) = true)\n  (Hadd_lenb : (Zlength contents >? 256) = false)\n  (Hadd_len: 0 <= Zlength contents <= 256)\n  (EL1: entropy_len + Zlength contents <= 384)\n   (*ZLc' : Zlength contents' = 0 \\/ Zlength contents' = Zlength contents*)\n(*  (EL: entropy_len = 32)*),\nreseedPOST (Vint return_value) contents additional sha (Zlength contents) s\n  I (Vptr b i) shc Info gv a *\ndata_at_ sho (tarray tuchar out_len) output\n|-- !! return_value_relate_result\n         (mbedtls_HMAC256_DRBG_generate_function s I out_len\n            (contents_with_add additional (Zlength contents) contents))\n         (Vint return_value) &&\n    (match\n       mbedtls_HMAC256_DRBG_generate_function s I out_len\n         (contents_with_add additional (Zlength contents) contents)\n     with\n     | ENTROPY.success (bytes, _) _ =>\n         data_at sho (tarray tuchar out_len) (map Vubyte bytes)\n           output\n     | ENTROPY.error _ _ => data_at_ sho (tarray tuchar out_len) output\n     end *\n     da_emp sha (tarray tuchar (Zlength contents))\n       (map Vubyte contents) additional *\n     Stream\n       (get_stream_result\n          (mbedtls_HMAC256_DRBG_generate_function s I out_len  (contents_with_add additional (Zlength contents) contents))) *\n     AREP shc gv (hmac256drbgabs_generate I s out_len  (contents_with_add additional (Zlength contents) contents)) (Vptr b i)).\nProof. intros.\n unfold reseedPOST. apply Zgt_is_gt_bool_f in Hadd_lenb.\n remember ((zlt 256 (Zlength contents)\n   || zlt 384 (hmac256drbgabs_entropy_len I + Zlength contents))%bool) as d.\n destruct (zlt 256 (Zlength contents)); simpl in Heqd. lia. clear g.\n destruct (zlt 384 (entropy_len + Zlength contents)); simpl in Heqd; subst d. lia.\n normalize.\n      remember (mbedtls_HMAC256_DRBG_reseed_function s I\n        (contents_with_add additional (Zlength contents) contents)) as MRS.\n      unfold return_value_relate_result in H. \n      destruct MRS. \n      { exfalso.  inv H. simpl in Hrv; discriminate. }\n      unfold hmac256drbgabs_common_mpreds.\n      remember (hmac256drbgabs_reseed I s\n        (contents_with_add additional (Zlength contents) contents)) as RS.\n      unfold hmac256drbgabs_reseed in HeqRS. rewrite <- HeqMRS in HeqRS.\n      assert (HRS: RS = I) by (subst I; apply HeqRS). \n      clear HeqRS; subst RS. \n      remember (hmac256drbgabs_generate I s out_len\n                (contents_with_add additional (Zlength contents) contents)) as Gen.\n      remember (mbedtls_HMAC256_DRBG_generate_function s I out_len\n             (contents_with_add additional (Zlength contents) contents)) as MGen.\n      Transparent hmac256drbgabs_generate.\n      Transparent mbedtls_HMAC256_DRBG_generate_function.\n      unfold hmac256drbgabs_generate in HeqGen. rewrite <- HeqMGen in HeqGen. \n      unfold mbedtls_HMAC256_DRBG_generate_function in HeqMGen. subst I. \n      simpl in HeqMGen. \n      Transparent HMAC256_DRBG_generate_function. unfold HMAC256_DRBG_generate_function in HeqMGen.\n      unfold mbedtls_HMAC256_DRBG_reseed_function in HeqMRS.\n      unfold DRBG_generate_function in HeqMGen.\n      rewrite Hout_lenb, ZLa, andb_negb_r, F32 in HeqMGen. \n      unfold DRBG_generate_function_helper in HeqMGen. rewrite <- HeqMRS in HeqMGen. subst Gen.\n      simpl. Intros.\n      destruct prediction_resistance; simpl in *.\n      + rewrite ZLa in *. subst MGen.\n        unfold return_value_relate_result. \n        apply andp_right. apply prop_right. repeat split; trivial.\n        simpl; cancel. unfold AREP, REP. Exists Info. Exists a.\n        unfold hmac256drbg_relate; simpl. entailer!.\n      + rewrite Hshould_reseed, ZLa in *.\n        destruct (get_entropy 32(*256*) entropy_len entropy_len false s); try discriminate.\n        inv HeqMRS. unfold return_value_relate_result; simpl.\n        apply andp_right. apply prop_right. repeat split; trivial.\n        cancel. unfold AREP, REP. Exists Info. Exists a.\n        unfold hmac256drbg_relate; simpl. entailer!. \nQed.\n\nOpaque hmac256drbgabs_generate.\nOpaque HMAC256_DRBG_generate_function.\nOpaque mbedtls_HMAC256_DRBG_generate_function.\n\nLemma entailment2: forall\nkey0 V0 reseed_counter0 entropy_len0 prediction_resistance0 reseed_interval0\n(contents : list byte)\n(additional : val) (sha: share) \n(output : val) (sho: share)\n(out_len : Z)\n(b : block) (i : ptrofs) (shc: share)\n(key V : list byte)\n(reseed_counter entropy_len : Z)\n(prediction_resistance : bool)\n(reseed_interval : Z)\n(gv: globals)\n(s : ENTROPY.stream)\n(I := HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance\n       reseed_interval : hmac256drbgabs)\n(H1 : Zlength (hmac256drbgabs_value I) = 32)\n(H3 : 0 < hmac256drbgabs_entropy_len I)\n(H4 : hmac256drbgabs_entropy_len I + Zlength contents <= 384)\n(Hreseed_interval : RI_range (hmac256drbgabs_reseed_interval I))\n(Hreseed_counter_in_range : 0 <= hmac256drbgabs_reseed_counter I <\n                           Int.max_signed)\n(Info : md_info_state)\n(mc1 mc2 mc3 : val)\n(WFI : WF I)\n(Hout_lenb : (out_len >? 1024) = false)\n(contents' := contents_with_add additional (Zlength contents) contents\n          : list byte)\n(ZLa : (Zlength contents' >? 256) = false)\n(should_reseed := (prediction_resistance\n                  || (reseed_counter >? reseed_interval))%bool : bool)\n(after_reseed_add_len := if should_reseed then 0 else Zlength contents : Z)\n(stream1 : ENTROPY.stream)\n(STREAM1 : mkSTREAM1 should_reseed s key V reseed_counter entropy_len\n            prediction_resistance reseed_interval additional contents stream1)\n(na := (negb (eq_dec additional nullval) &&\n       negb (eq_dec (if should_reseed then 0 else Zlength contents) 0))%bool\n   : bool)\n(after_reseed_state_abs := if should_reseed\n                          then\n                           hmac256drbgabs_reseed I s\n                             (contents_with_add additional (Zlength contents)\n                                contents)\n                          else I : hmac256drbgabs)\n(after_update_state_abs := if na\n                          then hmac256drbgabs_hmac_drbg_update I contents\n                          else after_reseed_state_abs : hmac256drbgabs)\n(AUV := hmac256drbgabs_value after_update_state_abs : list byte)\n(AUK := hmac256drbgabs_key after_update_state_abs : list byte)\n(HLP := HMAC_DRBG_generate_helper_Z HMAC256 AUK AUV : Z -> list byte * list byte)\n(HeqABS3 : HMAC256DRBGabs key0 V0 reseed_counter0 entropy_len0\n            prediction_resistance0 reseed_interval0 =\n          hmac256drbgabs_update_value after_update_state_abs\n            (fst (HLP out_len)))\n(key1 V1 : list byte)\n(reseed_counter1 entropy_len1 : Z)\n(prediction_resistance1 : bool)\n(reseed_interval1 : Z)\n(HeqABS4 : HMAC256DRBGabs key1 V1 reseed_counter1 entropy_len1\n            prediction_resistance1 reseed_interval1 =\n          hmac256drbgabs_hmac_drbg_update\n            (HMAC256DRBGabs key0 V0 reseed_counter0 entropy_len0\n               prediction_resistance0 reseed_interval0)\n            (contents_with_add additional after_reseed_add_len contents)),\nfield_at shc t_struct_hmac256drbg_context_st [StructField _md_ctx]\n  (mc1, (mc2, mc3)) (Vptr b i) *\n(field_at shc t_struct_hmac256drbg_context_st [StructField _V]\n   (map Vubyte V1) (Vptr b i) *\n (field_at shc t_struct_hmac256drbg_context_st [StructField _entropy_len]\n    (Vint (Int.repr entropy_len1)) (Vptr b i) *\n  (field_at shc t_struct_hmac256drbg_context_st\n     [StructField _prediction_resistance]\n     (bool2val prediction_resistance1) (Vptr b i) *\n   (field_at shc t_struct_hmac256drbg_context_st\n      [StructField _reseed_interval] (Vint (Int.repr reseed_interval1))\n      (Vptr b i) * (data_at shc t_struct_mbedtls_md_info Info mc1 * emp))))) *\n(md_full key1 (mc1, (mc2, mc3)) *\n (da_emp sha (tarray tuchar (Zlength contents))\n    (map Vubyte contents) additional *\n  (K_vector gv *\n   (Stream stream1 *\n    (data_at sho (tarray tuchar out_len)\n       (map Vubyte (sublist 0 out_len (snd (HLP out_len))))\n       output * emp) * emp)))) *\nfield_at shc t_struct_hmac256drbg_context_st [StructField _reseed_counter]\n  (Vint (Int.repr (reseed_counter1 + 1))) (Vptr b i)\n|-- !! return_value_relate_result\n         (mbedtls_HMAC256_DRBG_generate_function s I out_len contents')\n         (Vint (Int.repr 0)) &&\n    (match mbedtls_HMAC256_DRBG_generate_function s I out_len contents' with\n     | ENTROPY.success (bytes, _) _ =>\n         data_at sho (tarray tuchar out_len) (map Vubyte bytes)\n           output\n     | ENTROPY.error _ _ => data_at_ sho (tarray tuchar out_len) output\n     end *\n     da_emp sha (tarray tuchar (Zlength contents))\n       (map Vubyte contents) additional *\n     Stream\n       (get_stream_result\n          (mbedtls_HMAC256_DRBG_generate_function s I out_len contents')) *\n     ((EX a : hmac256drbgstate,\n       !! (WF (hmac256drbgabs_generate I s out_len contents')/\\ fst a =(mc1, (mc2, mc3)))&&\n       data_at shc t_struct_hmac256drbg_context_st a (Vptr b i) *\n       hmac256drbg_relate (hmac256drbgabs_generate I s out_len contents') a *\n       data_at shc t_struct_mbedtls_md_info Info\n         (hmac256drbgstate_md_info_pointer a) * K_vector gv))). \nProof. intros. assert (H6:=I).\n  unfold hmac256drbgabs_common_mpreds, hmac256drbg_relate, hmac256drbgstate_md_info_pointer.\n  simpl. Intros.\n  set (Gen := hmac256drbgabs_generate I s out_len  contents') in *.\nTransparent  hmac256drbgabs_generate.\n  unfold hmac256drbgabs_generate in Gen.\nOpaque hmac256drbgabs_generate.\n  assert (F32: 32 >? 32 = false) by reflexivity.\n  simpl in HeqABS4.\n  remember (HMAC256_DRBG_update (contents_with_add additional after_reseed_add_len contents) key0 V0) as UPD.\n  destruct UPD; inv HeqABS4.\n  remember after_update_state_abs as AUSA.\n  destruct AUSA. simpl in AUV, AUK, HeqABS3. subst AUV AUK; inv HeqABS3.\n  unfold hmac256drbgabs_reseed in after_reseed_state_abs.\n  unfold mkSTREAM1 in STREAM1.\n  subst I.\n  set (MGen := mbedtls_HMAC256_DRBG_generate_function s (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval) out_len\n             contents') in *.\n  set (MRES := mbedtls_HMAC256_DRBG_reseed_function s (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval)\n                 (contents_with_add additional (Zlength contents) contents)) in *.\n  simpl in Gen.\n  remember should_reseed as sr.\n  destruct sr.\n  + subst should_reseed after_reseed_add_len. simpl in na.\n    remember MRES as MRES'. destruct MRES'; try contradiction. subst MRES.\n    destruct d as [[[[? ?] ?] ?] ?]. subst s0. \n    simpl in H1, H3, H4, H6, Hreseed_counter_in_range. \n    remember na as naa.\n    destruct naa.\n    - subst na. rewrite andb_false_r in Heqnaa. discriminate.\n    - subst na. rewrite andb_false_r in Heqnaa. clear Heqnaa.\n      subst after_reseed_state_abs. inv HeqAUSA.\n      unfold mbedtls_HMAC256_DRBG_reseed_function in HeqMRES'.\nTransparent mbedtls_HMAC256_DRBG_generate_function.\nTransparent HMAC256_DRBG_generate_function.\n      unfold mbedtls_HMAC256_DRBG_generate_function, HMAC256_DRBG_generate_function, DRBG_generate_function in MGen.\nOpaque mbedtls_HMAC256_DRBG_generate_function.\nOpaque HMAC256_DRBG_generate_function.\n      remember MGen as MGen'. subst MGen. subst contents'.\n      rewrite Hout_lenb, F32, ZLa, andb_negb_r in HeqMGen'.\n      unfold DRBG_generate_function_helper in HeqMGen'.\n      rewrite <- HeqMRES' in *.\n      unfold HMAC256_DRBG_reseed_function, DRBG_reseed_function in HeqMRES'.\n      rewrite andb_negb_r, ZLa in HeqMRES'.\n      remember( get_entropy 32(*256*) entropy_len entropy_len  prediction_resistance s) as ENT.\n      destruct ENT; inversion HeqMRES'; clear HeqMRES'. subst z0 b0 s0.\n      unfold HMAC256_DRBG_update in HeqUPD.\n      remember (HMAC_DRBG_update HMAC256 (l3 ++ contents_with_add additional (Zlength contents) contents) key V) as UPD'.\n      destruct UPD'; inversion H0; clear H0. subst z l1 l2. \n      assert (RI: 1 >? reseed_interval = false).\n      { apply Zgt_is_gt_bool_f. simpl in Hreseed_interval. destruct Hreseed_interval. lia. }\n      destruct prediction_resistance.\n      * simpl in HeqMGen'. rewrite RI in *.\n        remember (HMAC_DRBG_generate_helper_Z HMAC256 l4 l5 out_len) as GH.\n        destruct GH. subst MGen'. subst Gen. simpl. \n        (*apply andp_right. apply prop_right; trivial. cancel.\n        unfold AREP, REP. Exists Info. *)\n        Exists ((mc1, (mc2, mc3)),\n           (map Vubyte (HMAC256 l1 (HMAC256 (l1 ++ [Byte.zero]) l4)),\n              (Vint (Int.repr 2), (Vint (Int.repr entropy_len), (Vtrue, Vint (Int.repr reseed_interval)))))).\n        unfold hmac256drbgstate_md_info_pointer; simpl. entailer!.\n        { destruct WFI as [WFI1 [WFI2 [WFI3 WFI4]]]. red in WFI3; simpl in *; repeat split; simpl; trivial; try lia.\n           apply hmac_common_lemmas.HMAC_Zlength. \n           apply hmac_common_lemmas.HMAC_Zlength.  } \n        rewrite sublist_firstn. cancel.\n        unfold_data_at 3%nat. cancel. \n        subst HLP. simpl in *.\n        unfold HMAC_DRBG_update in HeqUPD, HeqUPD'.\n        remember (l3 ++ contents_with_add additional (Zlength contents) contents).\n        destruct l6; inv HeqUPD'.\n        ++ symmetry in Heql6. apply app_eq_nil in Heql6. destruct Heql6; subst l3.\n           unfold get_entropy in HeqENT. apply get_bytes_length in HeqENT. simpl in HeqENT. exfalso. clear - HeqENT H3.\n           symmetry in HeqENT.  apply Z2Nat_inj_0 in HeqENT. lia. lia. \n        ++ assert (CONT: contents_with_add additional 0 contents = []).\n           { unfold contents_with_add; simpl. rewrite andb_false_r; trivial. }\n           rewrite CONT in *. inv HeqUPD. \n           rewrite <- HeqGH; simpl. cancel.\n      * rewrite orb_false_l in Heqsr. \n        simpl in HeqMGen'. simpl in *. (*subst reseed_interval.*) rewrite <- Heqsr, ZLa, <- HeqENT, <- HeqUPD' in HeqMGen'.\n        simpl in HeqMGen'. rewrite RI in *.\n        remember (HMAC_DRBG_generate_helper_Z HMAC256 l4 l5 out_len) as GH.\n        destruct GH. subst MGen'. subst Gen. simpl. Intros.\n        Exists ((mc1, (mc2, mc3)),\n           (map Vubyte (HMAC256 l1 (HMAC256 (l1 ++ [Byte.zero]) l4)),\n              (Vint (Int.repr 2), (Vint (Int.repr entropy_len), (Vfalse, Vint (Int.repr reseed_interval)))))).\n        unfold hmac256drbgstate_md_info_pointer; simpl.\n        entailer!.\n        { destruct WFI as [WFI1 [WFI2 [WFI3 WFI4]]]. red in WFI3; simpl in *; repeat split; simpl; trivial; try lia.\n           apply hmac_common_lemmas.HMAC_Zlength.\n           apply hmac_common_lemmas.HMAC_Zlength. } \n        rewrite sublist_firstn. cancel.\n        simpl in *.\n        unfold HMAC_DRBG_update in HeqUPD, HeqUPD'.\n        remember (l3 ++ contents_with_add additional (Zlength contents) contents).\n        destruct l6; inv HeqUPD'.\n        ++ symmetry in Heql6. apply app_eq_nil in Heql6. destruct Heql6; subst l3.\n           unfold get_entropy in HeqENT. apply get_bytes_length in HeqENT. simpl in HeqENT. exfalso. clear - HeqENT H3.\n           symmetry in HeqENT.  apply Z2Nat_inj_0 in HeqENT. lia. lia.\n        ++ assert (CONT: contents_with_add additional 0 contents = []).\n           { unfold contents_with_add; simpl. rewrite andb_false_r; trivial. }\n           rewrite CONT in *. inv HeqUPD. cancel.\n           unfold_data_at 3%nat. cancel. subst HLP; rewrite <- HeqGH; simpl. cancel. \n  + subst should_reseed after_reseed_add_len. symmetry in Heqsr.\n    apply orb_false_iff in Heqsr. destruct Heqsr; subst prediction_resistance. simpl in na.\n    simpl in H1, H3, H4, H6, Hreseed_counter_in_range.\n    subst after_reseed_state_abs.\n    unfold mbedtls_HMAC256_DRBG_reseed_function, HMAC256_DRBG_reseed_function, DRBG_reseed_function in MRES.\n    remember MRES as MRES'. subst MRES.\n    subst contents'. rewrite andb_negb_r, ZLa in HeqMRES'.\n    remember (get_entropy 32(*256*) entropy_len entropy_len false s) as ENT.\n    destruct ENT.\n    - subst MRES'. \n      remember  MGen as MGen'. subst MGen.\nTransparent mbedtls_HMAC256_DRBG_generate_function.\nTransparent HMAC256_DRBG_generate_function.\n      unfold mbedtls_HMAC256_DRBG_generate_function, HMAC256_DRBG_generate_function, DRBG_generate_function in HeqMGen'.\nOpaque mbedtls_HMAC256_DRBG_generate_function.\nOpaque HMAC256_DRBG_generate_function.\n      rewrite Hout_lenb, F32, ZLa, andb_negb_r in HeqMGen'.\n      unfold DRBG_generate_function_helper in HeqMGen'. simpl in HeqMGen'.\n      simpl in *. (*subst reseed_interval. *) rewrite H0 in HeqMGen'.\n      remember (contents_with_add additional (Zlength contents) contents) as CONT.\n      subst HLP. \n(*      unfold AREP, REP. Exists Info.*)\n      destruct CONT.\n      * (*clear C' ZLc'.*) subst stream1. \n        rewrite Zlength_nil, <- HeqENT(*, F*) in HeqMGen'. simpl in HeqMGen'.\n        remember (HMAC_DRBG_generate_helper_Z HMAC256 key V out_len) as p. destruct p.\n        remember (HMAC_DRBG_update HMAC256 [] key l2) as q. destruct q.\n        subst MGen'. subst Gen.\n        Exists (mc1, (mc2, mc3),\n             (map Vubyte (HMAC256 l2 (HMAC256 (l2 ++ [Byte.zero]) key)),\n             (Vint (Int.repr (reseed_counter + 1)),\n             (Vint (Int.repr entropy_len),\n             (Vfalse, Vint (Int.repr reseed_interval)))))).\n        unfold contents_with_add in HeqCONT.\n        destruct (eq_dec (Zlength contents) 0); simpl in HeqCONT. \n        ++ rewrite e in *. rewrite (Zlength_nil_inv _ e) in *.\n           simpl in na. destruct (EqDec_Z (Zlength contents) 0); try solve [lia]; simpl in na.\n           subst na; rewrite andb_false_r in *. \n           assert (F: (negb (EqDec_val additional nullval) &&\n                            false)%bool = false).\n           { rewrite andb_false_r. trivial. }\n           subst after_update_state_abs; rewrite F in *.\n           inv HeqAUSA. simpl.  \n           rewrite hmac_common_lemmas.HMAC_Zlength.\n           inv Heqq. inv HeqUPD.\n           unfold hmac256drbgstate_md_info_pointer; simpl in *. entailer!. \n           { destruct WFI as [WFI1 [WFI2 [WFI3 WFI4]]]. red in Hreseed_interval. red in WFI3; simpl in *; repeat split; simpl; trivial; try lia.\n             apply hmac_common_lemmas.HMAC_Zlength. }\n           { destruct WFI as [WFI1 [WFI2 [WFI3 WFI4]]]. red in Hreseed_interval.\n           rewrite <- Heqp, sublist_firstn; simpl. cancel.\n           unfold_data_at 1%nat. cancel.\n           }\n        ++ destruct (EqDec_val additional nullval); simpl in na, HeqCONT.\n           2: subst contents; elim n; apply Zlength_nil.\n           subst na. simpl in *.\n           inv HeqUPD. inv HeqAUSA. inv Heqq.\n           apply andp_right. { apply prop_right; trivial. }\n           rewrite hmac_common_lemmas.HMAC_Zlength. \n           entailer!.\n           { destruct WFI as [WFI1 [WFI2 [WFI3 WFI4]]]. red in Hreseed_interval. red in WFI3; simpl in *; repeat split; simpl; trivial; try lia. \n             apply hmac_common_lemmas.HMAC_Zlength. }\n           rewrite sublist_firstn, <- Heqp; simpl. cancel.\n           unfold_data_at 1%nat. cancel.\n     * unfold contents_with_add in HeqCONT.\n       remember ((negb (eq_dec additional nullval) && negb (eq_dec (Zlength contents) 0))%bool) as f.\n       destruct f; try discriminate. symmetry in Heqf; apply andb_true_iff in Heqf.\n       destruct Heqf as [Heqf1 Heqf2]. apply negb_true_iff in Heqf1. apply negb_true_iff in Heqf2.\n       destruct (eq_dec additional nullval); try discriminate.\n       destruct (eq_dec (Zlength contents) 0); try discriminate.\n       destruct (EqDec_val additional nullval). { subst additional. elim n; trivial. }\n       destruct (EqDec_Z (Zlength contents) 0); simpl in na. { lia. }\n       subst na. simpl in HeqAUSA.\n       Exists (mc1, (mc2, mc3),\n             (map Vubyte l0,\n             (Vint (Int.repr (reseed_counter + 1)),\n             (Vint (Int.repr entropy_len),\n             (Vfalse, Vint (Int.repr reseed_interval)))))).\n       unfold HMAC256_DRBG_update in *. subst stream1 contents.\n       rename i0 into z.\n       remember (HMAC_DRBG_update HMAC256 (z::CONT) key V) as p; destruct p. inv HeqAUSA.\n       remember (HMAC_DRBG_generate_helper_Z HMAC256 l2 l3 out_len) as w; destruct w.\n       simpl in HeqUPD. inv HeqUPD. \n       remember (HMAC_DRBG_update HMAC256 (z :: CONT) l2 l4) as q; destruct q.\n       subst Gen. \n       apply andp_right. apply prop_right. repeat split; trivial.\n       simpl. \n       rewrite sublist_firstn. cancel.\n       unfold HMAC_DRBG_update in Heqq. inv Heqq. simpl. entailer!.\n       { destruct WFI as [WFI1 [WFI2 [WFI3 WFI4]]]. red in Hreseed_interval. red in WFI3; simpl in *; repeat split; simpl; trivial; try lia.\n         apply hmac_common_lemmas.HMAC_Zlength.\n         apply hmac_common_lemmas.HMAC_Zlength. }\n       unfold_data_at 1%nat. cancel.\n  - subst HLP MRES'.  \n      remember  MGen as MGen'. subst MGen.\nTransparent mbedtls_HMAC256_DRBG_generate_function.\nTransparent HMAC256_DRBG_generate_function.\n      unfold mbedtls_HMAC256_DRBG_generate_function, HMAC256_DRBG_generate_function, DRBG_generate_function in HeqMGen'.\nOpaque mbedtls_HMAC256_DRBG_generate_function.\nOpaque HMAC256_DRBG_generate_function.\n      rewrite Hout_lenb, (*F,*) ZLa, andb_negb_r in HeqMGen'.\n      unfold DRBG_generate_function_helper in HeqMGen'. simpl in HeqMGen'.\n      simpl in *. (*subst reseed_interval.*) rewrite H0 in HeqMGen'.\n      remember (contents_with_add additional (Zlength contents) contents) as CONT.\n(*      unfold AREP, REP. Exists Info.*)\n      destruct CONT.\n      * (*clear C' ZLc'.*) subst stream1. \n        rewrite Zlength_nil, <- HeqENT(*, F*) in HeqMGen'. simpl in HeqMGen'.\n        remember (HMAC_DRBG_generate_helper_Z HMAC256 key V out_len) as p. destruct p.\n        remember (HMAC_DRBG_update HMAC256 [] key l2) as q. destruct q.\n        Exists (mc1, (mc2, mc3),\n             (map Vubyte (HMAC256 l1 (HMAC256 (l1 ++ [Byte.zero]) key)),\n             (Vint (Int.repr (reseed_counter + 1)),\n             (Vint (Int.repr entropy_len),\n             (Vfalse, Vint (Int.repr reseed_interval)))))).\n        subst MGen'. subst Gen.\n        unfold contents_with_add in HeqCONT.\n        destruct (eq_dec (Zlength contents) 0); simpl in HeqCONT. \n        ++ rewrite e0 in *. rewrite (Zlength_nil_inv _ e0) in *.\n           simpl in na. destruct (EqDec_Z (Zlength contents) 0); try solve [lia]; simpl in na.\n           subst na; rewrite andb_false_r in *. \n           assert (F: (negb (EqDec_val additional nullval) &&\n                            false)%bool = false).\n           { rewrite andb_false_r. trivial. }\n           subst after_update_state_abs; rewrite F in *.\n           inv HeqAUSA. simpl.  \n           rewrite hmac_common_lemmas.HMAC_Zlength.\n           inv Heqq. inv HeqUPD.\n           unfold hmac256drbgstate_md_info_pointer; simpl in *. entailer!. \n           { destruct WFI as [WFI1 [WFI2 [WFI3 WFI4]]]. red in Hreseed_interval. red in WFI3; simpl in *; repeat split; simpl; trivial; try lia.\n             apply hmac_common_lemmas.HMAC_Zlength. }\n           rewrite <- Heqp, sublist_firstn; simpl. cancel.\n           unfold_data_at 1%nat. cancel.\n        ++ destruct (EqDec_val additional nullval); simpl in na, HeqCONT.\n           2: subst contents; elim n; apply Zlength_nil.\n           subst na. simpl in *.\n           inv HeqUPD. inv HeqAUSA. inv Heqq.\n           apply andp_right. apply prop_right. repeat split; trivial.\n           rewrite hmac_common_lemmas.HMAC_Zlength. \n           entailer!.\n           { destruct WFI as [WFI1 [WFI2 [WFI3 WFI4]]]. red in Hreseed_interval. red in WFI3; simpl in *; repeat split; simpl; trivial; try lia. \n             apply hmac_common_lemmas.HMAC_Zlength. }\n           rewrite sublist_firstn, <- Heqp; simpl. cancel.\n           unfold_data_at 1%nat. cancel.\n     * unfold contents_with_add in HeqCONT.\n       remember ((negb (eq_dec additional nullval) && negb (eq_dec (Zlength contents) 0))%bool) as f.\n       destruct f; try discriminate. symmetry in Heqf; apply andb_true_iff in Heqf.\n       destruct Heqf as [Heqf1 Heqf2]. apply negb_true_iff in Heqf1. apply negb_true_iff in Heqf2.\n       destruct (eq_dec additional nullval); try discriminate.\n       destruct (eq_dec (Zlength contents) 0); try discriminate.\n       destruct (EqDec_val additional nullval). { subst additional. elim n; trivial. }\n       destruct (EqDec_Z (Zlength contents) 0); simpl in na. { lia. }\n       subst na. simpl in HeqAUSA.\n       Exists (mc1, (mc2, mc3),\n             (map Vubyte l0,\n             (Vint (Int.repr (reseed_counter + 1)),\n             (Vint (Int.repr entropy_len),\n             (Vfalse, Vint (Int.repr reseed_interval)))))).\n       unfold HMAC256_DRBG_update in *. subst stream1 contents.\n       rename i0 into z.\n       remember (HMAC_DRBG_update HMAC256 (z::CONT) key V) as p; destruct p. inv HeqAUSA.\n       remember (HMAC_DRBG_generate_helper_Z HMAC256 l1 l2 out_len) as w; destruct w.\n       simpl in HeqUPD. inv HeqUPD. \n       remember (HMAC_DRBG_update HMAC256 (z :: CONT) l1 l3) as q; destruct q.\n       subst Gen. \n       apply andp_right. apply prop_right. repeat split; trivial.\n       simpl. \n       rewrite sublist_firstn. cancel.\n       unfold HMAC_DRBG_update in Heqq. inv Heqq. simpl. entailer!.\n       { destruct WFI as [WFI1 [WFI2 [WFI3 WFI4]]]. red in Hreseed_interval. red in WFI3; simpl in *; repeat split; simpl; trivial; try lia. \n         apply hmac_common_lemmas.HMAC_Zlength.\n         apply hmac_common_lemmas.HMAC_Zlength. }\n       unfold_data_at 1%nat. cancel.\nTime Qed. (*laptop 11s, desktop25s*) \n\nOpaque mbedtls_HMAC256_DRBG_reseed_function.\nOpaque mbedtls_HMAC256_DRBG_generate_function.\n\nLemma loopbody_explicit (StreamAdd:list mpred) : forall (Espec : OracleKind)\n(contents : list byte)\n(additional : val)\n(add_len : Z)\n(output : val) (sho: share)\n(out_len : Z)\n(b : block) (i : ptrofs) (shc: share)\n(mc1 mc2 mc3 : val)\n(key V : list byte)\n(reseed_counter entropy_len : Z)\n(prediction_resistance : bool)\n(reseed_interval : Z)\n(gv: globals)\n(Info : md_info_state)\n(s : ENTROPY.stream)\n(*Delta_specs := abbreviate : PTree.t funspec*)\n(Haddlen : 0 <= add_len <= Int.max_unsigned)\n(Houtlen : 0 <= out_len <= Int.max_unsigned)\n(LengthV : Zlength V = 32)\n(AddLenC : add_len = Zlength contents)\n(Hent_len_nonneg : 0 < entropy_len)\n(Hentlen : entropy_len + Zlength contents <= 384)\n(Hreseed_interval : RI_range reseed_interval)\n(Hreseed_counter_in_range : 0 <= reseed_counter < Int.max_signed)\n(I := (HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance\n       reseed_interval) : hmac256drbgabs)\n(initial_state := (mc1, (mc2, mc3),\n                 (map Vubyte V,\n                 (Vint (Int.repr reseed_counter),\n                 (Vint (Int.repr entropy_len),\n                 (bool2val prediction_resistance,\n                 Vint (Int.repr reseed_interval))))))\n              : mdstate * (list val * (val * (val * (val * val)))))\n(PNadditional : is_pointer_or_null additional)\n(Pmc1 : isptr mc1)\n(Hout_len : 0 <= out_len <= 1024)\n(Hout_lenb : (out_len >? 1024) = false)\n(Hadd_len : 0 <= add_len <= 256)\n(Hadd_lenb : (add_len >? 256) = false)\n(contents' := contents_with_add additional add_len contents : list byte)\n(ZLa : (Zlength contents' >? 256) = false)\n(should_reseed := (prediction_resistance\n                  || (reseed_counter >? reseed_interval))%bool : bool)\n(after_reseed_add_len := if should_reseed then 0 else add_len : Z)\n(C' : contents' = [] \\/ contents' = contents)\n(ZLc' : Zlength contents' = 0 \\/ Zlength contents' = Zlength contents)\n(*(stream1 : ENTROPY.stream)*)\n(na := (negb (eq_dec additional nullval) &&\n       negb (eq_dec (if should_reseed then 0 else Zlength contents) 0))%bool\n   : bool)\n(*Delta := abbreviate : tycontext*)\n(after_reseed_state_abs := if should_reseed\n                          then\n                           hmac256drbgabs_reseed I s\n                             (contents_with_add additional add_len contents)\n                          else I : hmac256drbgabs)\n(ZLength_ARSA_val : Zlength (hmac256drbgabs_value after_reseed_state_abs) = 32)\n(after_update_state_abs := if na\n                          then hmac256drbgabs_hmac_drbg_update I contents\n                          else after_reseed_state_abs : hmac256drbgabs)\n(AUV := hmac256drbgabs_value after_update_state_abs : list byte)\n(ZLength_AUSA_val : Zlength AUV = 32)\n(*(TR : mkSTREAM1 (prediction_resistance || (reseed_counter >? reseed_interval))\n       s key V reseed_counter entropy_len prediction_resistance\n       reseed_interval additional contents stream1)*)\n(*(StreamAdd := abbreviate : list mpred)*)\n(Poutput : isptr output)\n(AUK := hmac256drbgabs_key after_update_state_abs : list byte)\n(HLP := HMAC_DRBG_generate_helper_Z HMAC256 AUK AUV : Z -> list byte * list byte)\n(done : Z)\n(HRE : Int.repr (out_len - done) <> Int.repr 0)\n(H : 0 <= done <= out_len)\n(H0 : is_multiple done 32 \\/ done = out_len)\n(Hsho: writable_share sho)\n(Hshc: writable_share shc)\n(WFI : drbg_protocol_specs.WF\n        (HMAC256DRBGabs key V reseed_counter entropy_len\n           prediction_resistance reseed_interval)),\n@semax hmac_drbg_compspecs.CompSpecs Espec\n     (func_tycontext f_mbedtls_hmac_drbg_random_with_add HmacDrbgVarSpecs\n        HmacDrbgFunSpecs nil)\n  (PROP ( )\n   LOCAL (temp _md_len (Vint (Int.repr 32)); temp _info mc1;\n   temp _reseed_interval (Vint (Int.repr reseed_interval));\n   temp _reseed_counter (Vint (Int.repr reseed_counter));\n   temp _prediction_resistance (bool2val prediction_resistance);\n   temp _out (offset_val done output);\n   temp _left (Vint (Int.repr (out_len - done))); temp _ctx (Vptr b i);\n   temp _p_rng (Vptr b i); temp _output output;\n   temp _out_len (Vint (Int.repr out_len)); temp _additional additional;\n   temp _add_len (Vint (Int.repr after_reseed_add_len)); gvars gv)\n   SEP (hmac256drbgabs_common_mpreds shc\n          (hmac256drbgabs_update_value after_update_state_abs\n             (fst (HLP done))) initial_state (Vptr b i) Info; FRZL StreamAdd;\n   data_at sho (tarray tuchar out_len)\n     (map Vubyte (sublist 0 done (snd (HLP done))) ++\n      repeat Vundef (Z.to_nat (out_len - done))) output; K_vector gv))\n  (Ssequence\n     (Ssequence\n        (Sifthenelse\n           (Ebinop Ogt (Etempvar _left tuint) (Etempvar _md_len tuint) tint)\n           (Sset _t'6 (Ecast (Etempvar _md_len tuint) tuint))\n           (Sset _t'6 (Ecast (Etempvar _left tuint) tuint)))\n        (Sset _use_len (Etempvar _t'6 tuint)))\n     (Ssequence\n        (Scall None\n           (Evar _mbedtls_md_hmac_reset\n              (Tfunction\n                 (Tcons (tptr (Tstruct _mbedtls_md_context_t noattr)) Tnil)\n                 tint cc_default))\n           [Eaddrof\n              (Efield\n                 (Ederef\n                    (Etempvar _ctx\n                       (tptr (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                    (Tstruct _mbedtls_hmac_drbg_context noattr)) _md_ctx\n                 (Tstruct _mbedtls_md_context_t noattr))\n              (tptr (Tstruct _mbedtls_md_context_t noattr))])\n        (Ssequence\n           (Scall None\n              (Evar _mbedtls_md_hmac_update\n                 (Tfunction\n                    (Tcons (tptr (Tstruct _mbedtls_md_context_t noattr))\n                       (Tcons (tptr tuchar) (Tcons tuint Tnil))) tint\n                    cc_default))\n              [Eaddrof\n                 (Efield\n                    (Ederef\n                       (Etempvar _ctx\n                          (tptr (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                       (Tstruct _mbedtls_hmac_drbg_context noattr)) _md_ctx\n                    (Tstruct _mbedtls_md_context_t noattr))\n                 (tptr (Tstruct _mbedtls_md_context_t noattr));\n              Efield\n                (Ederef\n                   (Etempvar _ctx\n                      (tptr (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                   (Tstruct _mbedtls_hmac_drbg_context noattr)) _V\n                (tarray tuchar 32); Etempvar _md_len tuint])\n           (Ssequence\n              (Scall None\n                 (Evar _mbedtls_md_hmac_finish\n                    (Tfunction\n                       (Tcons (tptr (Tstruct _mbedtls_md_context_t noattr))\n                          (Tcons (tptr tuchar) Tnil)) tint cc_default))\n                 [Eaddrof\n                    (Efield\n                       (Ederef\n                          (Etempvar _ctx\n                             (tptr\n                                (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                          (Tstruct _mbedtls_hmac_drbg_context noattr))\n                       _md_ctx (Tstruct _mbedtls_md_context_t noattr))\n                    (tptr (Tstruct _mbedtls_md_context_t noattr));\n                 Efield\n                   (Ederef\n                      (Etempvar _ctx\n                         (tptr (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                      (Tstruct _mbedtls_hmac_drbg_context noattr)) _V\n                   (tarray tuchar 32)])\n              (Ssequence\n                 (Scall None\n                    (Evar _memcpy\n                       (Tfunction\n                          (Tcons (tptr tvoid)\n                             (Tcons (tptr tvoid) (Tcons tuint Tnil)))\n                          (tptr tvoid) cc_default))\n                    [Etempvar _out (tptr tuchar);\n                    Efield\n                      (Ederef\n                         (Etempvar _ctx\n                            (tptr (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                         (Tstruct _mbedtls_hmac_drbg_context noattr)) _V\n                      (tarray tuchar 32); Etempvar _use_len tuint])\n                 (Ssequence\n                    (Sset _out\n                       (Ebinop Oadd (Etempvar _out (tptr tuchar))\n                          (Etempvar _use_len tuint) (tptr tuchar)))\n                    (Sset _left\n                       (Ebinop Osub (Etempvar _left tuint)\n                          (Etempvar _use_len tuint) tuint))))))))\n  (normal_ret_assert\n     (EX a : Z,\n      PROP (0 <= a <= out_len; is_multiple a 32 \\/ a = out_len)\n      LOCAL (temp _md_len (Vint (Int.repr 32)); temp _info mc1;\n      temp _reseed_interval (Vint (Int.repr reseed_interval));\n      temp _reseed_counter (Vint (Int.repr reseed_counter));\n      temp _prediction_resistance (bool2val prediction_resistance);\n      temp _out (offset_val a output);\n      temp _left (Vint (Int.repr (out_len - a))); temp _ctx (Vptr b i);\n      temp _p_rng (Vptr b i); temp _output output;\n      temp _out_len (Vint (Int.repr out_len)); temp _additional additional;\n      temp _add_len (Vint (Int.repr after_reseed_add_len));\n      gvars gv)\n      SEP (hmac256drbgabs_common_mpreds shc\n             (hmac256drbgabs_update_value after_update_state_abs\n                (fst (HLP a))) initial_state (Vptr b i) Info; FRZL StreamAdd;\n      data_at sho (tarray tuchar out_len)\n        (map Vubyte (sublist 0 a (snd (HLP a))) ++\n         repeat Vundef (Z.to_nat (out_len - a))) output; K_vector gv))%assert\n(*\n     (overridePost\n        (EX a : Z,\n         PROP (typed_false tint\n                 (bool2val\n                    (negb (Int.eq (Int.repr (out_len - a)) (Int.repr 0))));\n         0 <= a <= out_len; is_multiple a 32 \\/ a = out_len)\n         LOCAL (temp _md_len (Vint (Int.repr 32)); temp _info mc1;\n         temp _reseed_interval (Vint (Int.repr reseed_interval));\n         temp _reseed_counter (Vint (Int.repr reseed_counter));\n         temp _prediction_resistance (bool2val prediction_resistance);\n         temp _out (offset_val a output);\n         temp _left (Vint (Int.repr (out_len - a))); temp _ctx (Vptr b i);\n         temp _p_rng (Vptr b i); temp _output output;\n         temp _out_len (Vint (Int.repr out_len));\n         temp _additional additional;\n         temp _add_len (Vint (Int.repr after_reseed_add_len));\n         gvar sha._K256 kv)\n         SEP (hmac256drbgabs_common_mpreds\n                (hmac256drbgabs_update_value after_update_state_abs\n                   (fst (HLP a))) initial_state (Vptr b i) Info;\n         FRZL StreamAdd;\n         data_at Tsh (tarray tuchar out_len)\n           (map Vint (map Int.repr (sublist 0 a (snd (HLP a)))) ++\n            repeat Vundef (Z.to_nat (out_len - a))) output; K_vector kv))%assert\n        (function_body_ret_assert tint\n           (fun a : environ =>\n            EX x : val,\n            (PROP ( )\n             LOCAL (temp ret_temp x)\n             SEP (!! return_value_relate_result\n                       (mbedtls_HMAC256_DRBG_generate_function s I out_len\n                          contents') x &&\n                  (match\n                     mbedtls_HMAC256_DRBG_generate_function s I out_len\n                       contents'\n                   with\n                   | ENTROPY.success (bytes, _) _ =>\n                       data_at Tsh (tarray tuchar out_len)\n                         (map Vint (map Int.repr bytes)) output\n                   | ENTROPY.error _ _ =>\n                       data_at_ Tsh (tarray tuchar out_len) output\n                   end *\n                   hmac256drbgabs_common_mpreds\n                     (hmac256drbgabs_generate I s out_len contents')\n                     initial_state (Vptr b i) Info *\n                   da_emp Tsh (tarray tuchar add_len)\n                     (map Vint (map Int.repr contents)) additional *\n                   Stream\n                     (get_stream_result\n                        (mbedtls_HMAC256_DRBG_generate_function s I out_len\n                           contents')) * K_vector kv))) a)))\n*)).\nProof. intros.\n    rename H into Hdone.\n    destruct H0 as [Hmultiple | Hcontra]; [| subst done; elim HRE; f_equal; lia].\n    destruct Hmultiple as [n Hmultiple].\n    unfold hmac256drbgabs_common_mpreds.\n    normalize.\n    assert (Hfield_md_ctx: forall ctx', isptr ctx' -> field_compatible t_struct_hmac256drbg_context_st [StructField _md_ctx] ctx' -> ctx' = field_address t_struct_hmac256drbg_context_st [StructField _md_ctx] ctx').\n    {\n      intros ctx'' Hisptr Hfc.\n      unfold field_address.\n      destruct (field_compatible_dec t_struct_hmac256drbg_context_st); [|contradiction].\n      simpl. change (Int.repr 0) with Int.zero. rewrite offset_val_force_ptr.\n      destruct ctx''; inversion Hisptr. reflexivity.\n    }\n    unfold_data_at 1%nat.\n    \n    freeze [2;3;4;5] FR_unused_struct_fields.\n    freeze [0;3;5] FR1.\n\n    rewrite (field_at_data_at _ _ [StructField _md_ctx]).\n    rewrite (field_at_data_at _ _ [StructField _V]).\n\n    unfold hmac256drbg_relate. subst I.\n\n    destruct after_update_state_abs.\n    unfold hmac256drbgabs_update_value.\n(*    rewrite Heqinitial_state.*)\n    unfold hmac256drbgabs_to_state.\n(*    rewrite Heqafter_update_key.*)\n    simpl in AUV, AUK. subst AUV AUK.\n    unfold md_full. subst initial_state.\n    cbv beta iota zeta.\n    normalize. \n\n    (* size_t use_len = left > md_len ? md_len : left; *)\n    forward_if (temp _t'6 (Vint (Int.repr (Z.min (Z.of_nat SHA256.DigestLength) (out_len - done))))).\n    {\n      (* md_len < left *)\n      forward.\n      entailer!.\n      rewrite Z.min_l; [reflexivity | simpl; lia].\n    }\n    {\n      (* md_len >= left *)\n      forward.\n      entailer!.\n      rewrite Z.min_r; [reflexivity | simpl; lia].\n    }\n    forward.\n\n    (* mbedtls_md_hmac_reset( &ctx->md_ctx ); *)\n    assert_PROP (field_compatible (Tarray tuchar 32 noattr) \n          []\n          (field_address t_struct_hmac256drbg_context_st [StructField _V] (*ctx*)(Vptr b i))) as FC_V by entailer!.\n    assert_PROP (field_compatible t_struct_hmac256drbg_context_st\n         [StructField _md_ctx] (Vptr b i)) as FC_M by entailer.\n    forward_call (field_address t_struct_hmac256drbg_context_st [StructField _md_ctx] (*ctx*)(Vptr b i),  (*md_ctx'*)(mc1,(mc2,mc3)), shc, key0, gv).\n    { unfold md_full; simpl. cancel. }\n    (* mbedtls_md_hmac_update( &ctx->md_ctx, ctx->V, md_len ); *)\n    rename H into HZlength_V.  \n    assert_PROP (field_compatible t_struct_hmac256drbg_context_st [StructField _V] (Vptr b i)) as FCV by entailer!.\n\n    forward_call (key0, field_address t_struct_hmac256drbg_context_st [StructField _md_ctx] (*ctx*)(Vptr b i),\n                  (*md_ctx'*)(mc1,(mc2,mc3)), shc, \n                  field_address t_struct_hmac256drbg_context_st [StructField _V] (*ctx*)(Vptr b i), shc, \n                  @nil byte, (fst (HLP done)), gv).\n\n    { apply prop_right. rewrite HZlength_V, field_address_offset; simpl; trivial. f_equal.\n      unfold field_address. rewrite if_true; trivial.\n    }\n    { simpl; simpl in HZlength_V; rewrite HZlength_V (*, <- Hmultiple*).\n      cancel.\n    }\n    { simpl; simpl in HZlength_V; rewrite HZlength_V.\n      compute; reflexivity. \n    }\n\n    (*Intros vret; subst vret.*)\n    rewrite app_nil_l.\n\n    replace_SEP 2 (memory_block shc 32 (field_address t_struct_hmac256drbg_context_st [StructField _V] (*ctx*)(Vptr b i))).\n    { \n      entailer!.\n      simpl in HZlength_V.\n      unfold hmac256drbgabs_value.\n      rewrite HZlength_V.\n      apply data_at_memory_block.\n    }\n\n    (* mbedtls_md_hmac_finish( &ctx->md_ctx, ctx->V ); *)\n    forward_call ((fst(HLP done)), key0, \n               field_address t_struct_hmac256drbg_context_st [StructField _md_ctx] (*ctx*)(Vptr b i), \n               (*md_ctx'*)(mc1, (mc2, mc3)), shc,\n               field_address t_struct_hmac256drbg_context_st [StructField _V] (*ctx*)(Vptr b i), shc, gv).\n    {\n      rewrite <- memory_block_data_at_ by trivial. cancel.\n    }\n    assert_PROP (field_compatible (tarray tuchar out_len) [] output) as\n        Hfield_compat_output by entailer!.\n    replace_SEP 5 (\n        data_at sho (tarray tuchar done) (map Vubyte (sublist 0 done (snd (HLP done)))) output *\n        data_at sho (tarray tuchar (out_len - done)) (repeat Vundef (Z.to_nat (out_len - done))) (offset_val done output)\n    ).\n    {\n      entailer!.\n      apply derives_refl'.\n\n      assert (HZlength1: Zlength (map Vubyte (sublist 0 (n * 32)%Z (snd (HLP (n * 32)%Z)))) = (n * 32)%Z).\n      {\n        rewrite Zlength_map.\n        rewrite Zlength_sublist; [lia|lia|]. subst HLP.\n        rewrite HMAC_DRBG_generate_helper_Z_Zlength_snd; auto; try lia.\n        apply hmac_common_lemmas.HMAC_Zlength.\n        exists n; reflexivity.\n      }\n      \n      apply data_at_complete_split; try rewrite HZlength1; try rewrite Zlength_repeat; auto; try lia.\n      (*simpl. simpl in HZlength1. rewrite HZlength1.*)\n      replace ((n * 32)%Z + (out_len - (n * 32)%Z)) with out_len by lia. assumption.\n    }\n    normalize.\n    \n    remember (offset_val done output) as done_output.\n    remember (Z.min 32 (out_len - done)) as use_len.\n    assert_PROP (field_compatible (tarray tuchar (out_len - done)) [] done_output) as Hfield_compat_done_output.\n    {\n      clear Heqdone_output Hmultiple.\n      entailer!.\n    }\n    Intros.\n    replace_SEP 6 (\n        data_at sho (tarray tuchar use_len) (repeat Vundef (Z.to_nat use_len)) done_output *\n        data_at sho (tarray tuchar (out_len - done - use_len)) (repeat Vundef (Z.to_nat (out_len - done - use_len))) (offset_val use_len done_output)\n    ).\n    { \n      clear Hmultiple Heqdone_output.\n      entailer!. \n      apply derives_refl'.\n      rewrite Zmin_spec.\n      if_tac.\n      { apply data_at_complete_split; repeat rewrite Zlength_repeat; auto; try lia.\n        replace (32 + (out_len - done - 32)) with (out_len - done) by lia; assumption.\n        rewrite <- repeat_app.\n        rewrite <- Z2Nat.inj_add; try lia.\n        replace (32 + (out_len - done - 32)) with (out_len - done) by lia; reflexivity.\n      }\n      {\n        apply data_at_complete_split; repeat rewrite Zlength_repeat; auto; try lia.\n        replace (out_len - done + (out_len - done - (out_len - done))) with (out_len - done) by lia; assumption.\n        replace (out_len - done - (out_len - done)) with 0 by lia; simpl; rewrite app_nil_r; reflexivity.\n      }\n    }\n    Intros.\n\n    replace_SEP 6 (memory_block sho use_len done_output).\n    {\n      clear Hmultiple.\n      entailer!.\n      eapply derives_trans; [apply data_at_memory_block|].\n      replace (sizeof (*cenv_cs*) (tarray tuchar (Z.min 32 (out_len - done)))) with (Z.min 32 (out_len - done)).\n      apply derives_refl.\n      simpl.\n      destruct (Z.min_dec 32 (out_len - done));\n      rewrite Zmax0r; lia.\n    }\n    set (H256 := HMAC256 (fst (HLP done)) key0) in *.\n    assert (ZL_H256: Zlength H256 = 32).\n    { subst H256. apply hmac_common_lemmas.HMAC_Zlength. }\n    replace_SEP 3 (data_at shc (tarray tuchar use_len)\n                      (sublist 0 use_len (map Vubyte H256))\n                      (field_address t_struct_hmac256drbg_context_st [StructField _V] (*ctx*)(Vptr b i)) *\n                   data_at shc (tarray tuchar (32 - use_len))\n                      (sublist use_len 32 (map Vubyte (H256)))\n                      (offset_val use_len (field_address t_struct_hmac256drbg_context_st [StructField _V] (*ctx*)(Vptr b i)))).\n    {\n      clear Hmultiple.\n      entailer!.\n      apply derives_refl'.\n      remember (fst (HLP done)) as V0'; clear HeqV0'.\n      rewrite Zmin_spec.\n      destruct (Z_lt_ge_dec 32 (out_len - done)) as [Hmin | Hmin].\n      {\n        rewrite zlt_true by assumption.\n        apply data_at_complete_split; repeat rewrite Zlength_sublist; repeat rewrite Zlength_map; repeat rewrite hmac_common_lemmas.HMAC_Zlength; auto; try lia.\n        rewrite sublist_nil.\n        rewrite app_nil_r.\n        symmetry; apply sublist_same.\n        reflexivity.\n        repeat rewrite Zlength_map; rewrite ZL_H256; reflexivity.\n      }\n      {\n        rewrite zlt_false by assumption.\n        apply data_at_complete_split; repeat rewrite Zlength_sublist; repeat rewrite Zlength_map; repeat rewrite hmac_common_lemmas.HMAC_Zlength; auto; try lia.\n        replace (out_len - done - 0 + (32 - (out_len - done))) with 32 by lia; auto.\n        rewrite sublist_rejoin; repeat rewrite Zlength_map; try rewrite hmac_common_lemmas.HMAC_Zlength; try lia.\n        rewrite sublist_same; try reflexivity; repeat rewrite Zlength_map; try rewrite hmac_common_lemmas.HMAC_Zlength; try lia.\n      }\n    }\n    (* memcpy( out, ctx->V, use_len ); *)\n    forward_call ((shc, sho), done_output, \n                  field_address t_struct_hmac256drbg_context_st [StructField _V] (*ctx*)(Vptr b i), \n                  use_len,\n                  sublist 0 use_len (map Int.repr (map Byte.unsigned H256))).\n    { apply prop_right. subst; simpl. rewrite field_address_offset; trivial. } \n    { entailer!. simpl. rewrite !sublist_map, !map_map. cancel. }\n\n    simpl.\n    gather_SEP (data_at _ _ _ (field_address _ [StructField _V] _)) \n                      (data_at _ _ _ (offset_val _ (field_address _ [StructField _V] _))).\n    replace_SEP 0 (data_at shc (tarray tuchar 32) (map Vubyte H256)\n                               (field_address t_struct_hmac256drbg_context_st [StructField _V] (*ctx*)(Vptr b i))).\n    {\n      (*clear Hmultiple.*)\n      entailer!.\n      apply derives_refl'. \n      rewrite <- sublist_map.\n      remember (fst (HLP (n*32)%Z)) as V0'; clear HeqV0'.\n      symmetry.\n      rewrite Zmin_spec.\n      destruct (Z_lt_ge_dec 32 (out_len - (*done*)(n*32)%Z)) as [Hmin | Hmin].\n      { clear - Hmin ZL_H256 Hdone FC_V.\n        rewrite zlt_true by assumption. simpl.\n        rewrite sublist_same; repeat rewrite Zlength_map; try rewrite hmac_common_lemmas.HMAC_Zlength; try lia.\n        remember (map Vubyte (HMAC256 V0' key0)) as data.\n        apply data_at_complete_split; subst data; autorewrite with sublist; \n        repeat rewrite Zlength_map; try rewrite ZL_H256, Zlength_nil; autorewrite with sublist; auto; try lia.\n        rewrite ZL_H256. auto. \n        unfold Vubyte. rewrite !map_map. reflexivity.\n      }\n      {\n        rewrite zlt_false by assumption.\n        remember (sublist 0 (out_len - (*done*)(n*32)%Z) (map Vubyte (HMAC256 V0' key0))) as data_left.\n        remember (sublist (out_len - (*done*)(n*32)%Z) 32\n        (map Vubyte (HMAC256 V0' key0))) as data_right.\n        apply data_at_complete_split; subst data_left data_right; repeat rewrite Zlength_sublist; repeat rewrite Zlength_map; repeat rewrite hmac_common_lemmas.HMAC_Zlength; auto; try lia.\n        autorewrite with sublist.\n        replace (out_len - (*done*)(n*32)%Z + (32 - (out_len - (*done*)(n*32)%Z))) with 32 by lia; auto.\n        list_solve.\n        unfold Vubyte.\n        rewrite !sublist_map, !map_map. rewrite <- map_app. f_equal.\n        rewrite sublist_rejoin; repeat rewrite Zlength_map; try rewrite hmac_common_lemmas.HMAC_Zlength; try lia.\n        rewrite sublist_same; try reflexivity; repeat rewrite Zlength_map; try rewrite hmac_common_lemmas.HMAC_Zlength; try lia.\n      }\n    }\n\n    gather_SEP  (data_at sho (tarray tuchar use_len) _ _)\n                       (data_at sho (tarray tuchar (out_len - _ - _)) _ _).\n    replace_SEP 0 (data_at sho (tarray tuchar (out_len - done)) \n         ( (map Vubyte (sublist 0 use_len H256))\n           ++ (repeat Vundef (Z.to_nat (out_len - done - use_len))))\n         done_output).\n    {\n      (*clear Heqdone_output Hmultiple*)\n      entailer!.\n      apply derives_refl'.\n      rewrite Zmin_spec in *.\n      symmetry.\n      if_tac.\n      { \n        erewrite ( data_at_complete_split\n                           (map Vint (sublist 0 32 (map Int.repr (map Byte.unsigned H256))))\n                           (repeat Vundef (Z.to_nat (out_len - n * 32 - 32)))); try reflexivity.\n        2: autorewrite with sublist; replace (_ + _) with (out_len - n*32) by lia; solve [auto].\n        2: autorewrite with sublist; lia.\n        2: f_equal; autorewrite with sublist; rewrite !map_map; reflexivity.\n        autorewrite with sublist; rewrite ZL_H256, offset_offset_val; reflexivity. \n      }\n      { \n        rewrite !sublist_map. rewrite !map_map. \n        erewrite (data_at_complete_split \n            (map (fun x : byte => Vint (Int.repr (Byte.unsigned x))) (sublist 0 (out_len - n * 32) H256))\n            (repeat Vundef (Z.to_nat (out_len - n * 32 - (out_len - n * 32))))).\n        3: reflexivity. 3: reflexivity. 4: reflexivity.\n        + rewrite Zlength_map, Zlength_sublist, Zlength_repeat, Z.sub_0_r, offset_offset_val; try lia.\n          trivial.\n        + rewrite Zlength_map, Zlength_sublist, Zlength_repeat, Zminus_diag, Z.sub_0_r, Z.add_0_r; try lia. trivial.\n        + rewrite Zlength_map, Zlength_sublist, Zlength_repeat; try lia.\n        + unfold Vubyte. f_equal.\n      }\n    }\n\n    gather_SEP (data_at sho (tarray tuchar (n*32)) _ _) (data_at sho (tarray tuchar (out_len - done)) _ _).\n    replace_SEP 0 (\n                  data_at sho (tarray tuchar out_len) \n                    ((map Vubyte (sublist 0 done (snd (HLP done)))) ++\n                     (map Vubyte (sublist 0 use_len H256) ++\n                      repeat Vundef (Z.to_nat (out_len - done - use_len)))) output).\n    {\n      entailer!.\n      apply derives_refl'.\n      symmetry.\n      assert (HZlength1: Zlength ((snd (HLP (n * 32)%Z))) = (n * 32)%Z).\n      { subst HLP.\n        rewrite HMAC_DRBG_generate_helper_Z_Zlength_snd; auto; try lia.\n        apply hmac_common_lemmas.HMAC_Zlength.\n        exists n; reflexivity.\n      }\n      rewrite Zmin_spec. simpl in *.\n      if_tac.\n      apply data_at_complete_split;\n      repeat rewrite Zlength_app; repeat rewrite Zlength_map; try rewrite HZlength1; repeat rewrite Zlength_repeat; repeat rewrite Zlength_sublist; repeat rewrite Zlength_map; try rewrite hmac_common_lemmas.HMAC_Zlength; auto; try lia;\n      try rewrite HZlength_V.\n      replace ((n * 32)%Z - 0 + (32 - 0 + (out_len - (n * 32)%Z - 32))) with out_len by lia;\n      assumption. \n      replace ((n * 32)%Z - 0 + (out_len - (n * 32)%Z - 0 + (out_len - (n * 32)%Z - (out_len - (n * 32)%Z)))) with out_len by lia.\n      apply data_at_complete_split;\n      repeat rewrite Zlength_app; repeat rewrite Zlength_map; try rewrite HZlength1; repeat rewrite Zlength_repeat; repeat rewrite Zlength_sublist; repeat rewrite Zlength_map; try rewrite hmac_common_lemmas.HMAC_Zlength; auto; try lia;\n      try rewrite HZlength_V.\n      replace (n * 32 - 0 + (out_len - n * 32 - 0 + (out_len - n * 32 - (out_len - n * 32)))) with\n         out_len by lia.\n      assumption.\n    }\n\n    (* out += use_len; *)\n    forward.\n\n    (* left -= use_len; *)\n    forward.\n    { \n      go_lower.\n      Exists (done + use_len).\n      unfold hmac256drbgabs_common_mpreds; normalize.\n\n      unfold_data_at 4%nat.\n      rewrite (field_at_data_at _ _ [StructField _md_ctx]);\n      rewrite (field_at_data_at _ _ [StructField _V]).\n    \n      unfold md_full.\n    \n      thaw FR1.\n      thaw FR_unused_struct_fields.\n      assert (DD: 0 <= done + use_len).\n      { subst. rewrite Zmin_spec.\n        destruct (Z_lt_ge_dec 32 (out_len - (n * 32)%Z)) as [Hmin | Hmin]; [rewrite zlt_true by assumption | rewrite zlt_false by assumption]; repeat split; try lia. }        \n      assert (XX: is_multiple (done + use_len) 32 \\/ done + use_len = out_len).\n      { subst.\n        rewrite Zmin_spec.\n        destruct (Z_lt_ge_dec 32 (out_len - (n * 32)%Z)) as [Hmin | Hmin]; [rewrite zlt_true by assumption | rewrite zlt_false by assumption]; repeat split; try lia.\n        left; exists (n + 1); lia. }\n      autorewrite with norm.\n      apply andp_right.\n      { apply prop_right. repeat split; trivial.\n        + subst. rewrite Zmin_spec.\n          destruct (Z_lt_ge_dec 32 (out_len - (n * 32)%Z)) as [Hmin | Hmin]; [rewrite zlt_true by assumption | rewrite zlt_false by assumption]; lia.\n        + subst done_output. simpl. destruct output; simpl; auto.\n            f_equal. autorewrite with norm. \n           assert (0 <= use_len <= 32).\n            subst use_len; clear - Hdone DD.\n            destruct (Z.min_spec 32 (out_len - done)) as [[? ?]|[? ?]]; lia. \n            f_equal. f_equal. subst use_len. trivial.\n        + autorewrite with norm; f_equal; f_equal. lia.\n        + subst HLP. apply HMAC_DRBG_generate_helper_Z_Zlength_fst; trivial. apply hmac_common_lemmas.HMAC_Zlength. }\n\n      subst done use_len. cancel. \n\n      (*Rest as with \"ideal proof\"*) \n      unfold md_full. simpl. \n      replace H256 with (fst (HLP (n * 32 + Z.min 32 (out_len - n * 32))))%Z.\n      rewrite app_assoc.\n      replace (map Vubyte\n        (\n           (sublist 0 (n * 32)%Z\n              (snd (HLP (n * 32)%Z)))) ++\n        map Vubyte\n         (sublist 0 (Z.min 32 (out_len - (n * 32)%Z))\n           (\n              (fst\n                 (HLP ((n * 32)%Z + Z.min 32 (out_len - (n * 32)%Z))))))) with\n       (map Vubyte\n        (\n           (sublist 0 ((n * 32)%Z + Z.min 32 (out_len - (n * 32)%Z))\n              (snd\n                 (HLP ((n * 32)%Z + Z.min 32 (out_len - (n * 32)%Z))))))).\n      replace (out_len - (n * 32)%Z - Z.min 32 (out_len - (n * 32)%Z)) with (out_len - ((n * 32)%Z + Z.min 32 (out_len - (n * 32)%Z))) by lia.\n      cancel. \n      rewrite <- map_app.\n      replace (sublist 0 ((n * 32)%Z + Z.min 32 (out_len - (n * 32)%Z))\n           (snd\n              (HLP ((n * 32)%Z + Z.min 32 (out_len - (n * 32)%Z))))) with (sublist 0 (n * 32)%Z\n           (snd (HLP (n * 32)%Z)) ++\n         sublist 0 (Z.min 32 (out_len - (n * 32)%Z))\n           (fst\n              (HLP ((n * 32)%Z + Z.min 32 (out_len - (n * 32)%Z))))).\n      reflexivity.\n      replace (snd\n              (HLP ((n * 32)%Z + Z.min 32 (out_len - (n * 32)%Z)))) \n      with (snd (HLP (n * 32)%Z) ++ \n            fst (HLP ((n * 32)%Z + Z.min 32 (out_len - (n * 32)%Z)))).\n      {\n        apply while_loop_post_sublist_app; auto. \n      }\n      {\n        apply while_loop_post_incremental_snd; auto.\n        intros contra; rewrite contra, Zminus_diag in HRE. clear - HRE.\n        elim HRE; trivial. \n      }\n      {\n        apply while_loop_post_incremental_fst; auto.\n        intros contra; rewrite contra, Zminus_diag in HRE. clear - HRE.\n        elim HRE; trivial. \n      }\n    }\nTime Qed. (*Coq8.10.1: 8.9s; was: 27s*)\n\nOpaque mbedtls_HMAC256_DRBG_generate_function.\n\nLemma generate_loopbody: forall (StreamAdd: list mpred)\n(Espec : OracleKind)\n(contents : list byte)\n(additional : val)\n(add_len : Z)\n(output : val) (sho: share)\n(out_len : Z)\n(b : block) (i : ptrofs) (shc: share)\n(key V : list byte)\n(reseed_counter entropy_len : Z)\n(prediction_resistance : bool)\n(reseed_interval : Z)\n(gv : globals)\n(s : ENTROPY.stream)\n(Haddlen : 0 <= add_len <= Int.max_unsigned)\n(Houtlen : 0 <= out_len <= Int.max_unsigned)\n(AddLenC : add_len = Zlength contents)\n(I := HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance\n       reseed_interval : hmac256drbgabs)\n(Hentlen : hmac256drbgabs_entropy_len I + Zlength contents <= 384)\n(Info : md_info_state)\n(mc1 mc2 mc3 : val)\n(WFI : WF I)\n(Hreseed_counter_in_range : 0 <= hmac256drbgabs_reseed_counter I <\n                           Int.max_signed)\n(Hreseed_interval : RI_range (hmac256drbgabs_reseed_interval I))\n(ZlengthV : Zlength V = 32)\n(PNadditional : is_pointer_or_null additional)\n(a := (mc1, (mc2, mc3),\n     (map Vubyte V,\n     (Vint (Int.repr reseed_counter),\n     (Vint (Int.repr entropy_len),\n     (bool2val prediction_resistance, Vint (Int.repr reseed_interval))))))\n  : mdstate * (list val * (val * (val * (val * val)))))\n(Pmc1 : isptr mc1)\n(Hout_len : 0 <= out_len <= 1024)\n(Hout_lenb : (out_len >? 1024) = false)\n(Hadd_len : 0 <= add_len <= 256)\n(Hadd_lenb : (add_len >? 256) = false)\n(contents' := contents_with_add additional add_len contents : list byte)\n(ZLa : (Zlength contents' >? 256) = false)\n(should_reseed := (prediction_resistance\n                  || (reseed_counter >? reseed_interval))%bool : bool)\n(after_reseed_add_len := if should_reseed then 0 else add_len : Z)\n(C' : contents' = [] \\/ contents' = contents)\n(ZLc' : Zlength contents' = 0 \\/ Zlength contents' = Zlength contents)\n(na := (negb (eq_dec additional nullval) &&\n       negb (eq_dec (if should_reseed then 0 else Zlength contents) 0))%bool\n   : bool)\n(after_reseed_state_abs := if should_reseed\n                          then\n                           hmac256drbgabs_reseed I s\n                             (contents_with_add additional add_len contents)\n                          else I : hmac256drbgabs)\n(ZLength_ARSA_val : Zlength (hmac256drbgabs_value after_reseed_state_abs) = 32)\n(after_update_state_abs := if na\n                          then hmac256drbgabs_hmac_drbg_update I contents\n                          else after_reseed_state_abs : hmac256drbgabs)\n(AUV := hmac256drbgabs_value after_update_state_abs : list byte)\n(ZLength_AUSA_val : Zlength AUV = 32)\n(Poutput : isptr output)\n(AUK := hmac256drbgabs_key after_update_state_abs : list byte)\n(HLP := HMAC_DRBG_generate_helper_Z HMAC256 AUK AUV : Z -> list byte * list byte)\n(done : Z)\n(HRE : Int.repr (out_len - done) <> Int.repr 0)\n(Hsho: writable_share sho)\n(Hshc: writable_share shc)\n(H : 0 <= done <= out_len)\n(H0 : is_multiple done 32 \\/ done = out_len),\n@semax hmac_drbg_compspecs.CompSpecs Espec\n  (func_tycontext f_mbedtls_hmac_drbg_random_with_add HmacDrbgVarSpecs\n        HmacDrbgFunSpecs nil)\n  (PROP ( )\n   LOCAL (temp _md_len (Vint (Int.repr 32)); temp _info mc1;\n   temp _reseed_interval (Vint (Int.repr reseed_interval));\n   temp _reseed_counter (Vint (Int.repr reseed_counter));\n   temp _prediction_resistance (bool2val prediction_resistance);\n   temp _out (offset_val done output);\n   temp _left (Vint (Int.repr (out_len - done))); temp _ctx (Vptr b i);\n   temp _p_rng (Vptr b i); temp _output output;\n   temp _out_len (Vint (Int.repr out_len)); temp _additional additional;\n   temp _add_len (Vint (Int.repr after_reseed_add_len)); gvars gv)\n   SEP (hmac256drbgabs_common_mpreds shc\n          (hmac256drbgabs_update_value after_update_state_abs\n             (fst (HLP done))) a (Vptr b i) Info; FRZL StreamAdd;\n   data_at sho (tarray tuchar out_len)\n     (map Vubyte (sublist 0 done (snd (HLP done))) ++\n      repeat Vundef (Z.to_nat (out_len - done))) output; K_vector gv))\n  (Ssequence\n     (Ssequence\n        (Sifthenelse\n           (Ebinop Ogt (Etempvar _left tuint) (Etempvar _md_len tuint) tint)\n           (Sset _t'6 (Ecast (Etempvar _md_len tuint) tuint))\n           (Sset _t'6 (Ecast (Etempvar _left tuint) tuint)))\n        (Sset _use_len (Etempvar _t'6 tuint)))\n     (Ssequence\n        (Scall None\n           (Evar _mbedtls_md_hmac_reset\n              (Tfunction\n                 (Tcons (tptr (Tstruct _mbedtls_md_context_t noattr)) Tnil)\n                 tint cc_default))\n           [Eaddrof\n              (Efield\n                 (Ederef\n                    (Etempvar _ctx\n                       (tptr (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                    (Tstruct _mbedtls_hmac_drbg_context noattr)) _md_ctx\n                 (Tstruct _mbedtls_md_context_t noattr))\n              (tptr (Tstruct _mbedtls_md_context_t noattr))])\n        (Ssequence\n           (Scall None\n              (Evar _mbedtls_md_hmac_update\n                 (Tfunction\n                    (Tcons (tptr (Tstruct _mbedtls_md_context_t noattr))\n                       (Tcons (tptr tuchar) (Tcons tuint Tnil))) tint\n                    cc_default))\n              [Eaddrof\n                 (Efield\n                    (Ederef\n                       (Etempvar _ctx\n                          (tptr (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                       (Tstruct _mbedtls_hmac_drbg_context noattr)) _md_ctx\n                    (Tstruct _mbedtls_md_context_t noattr))\n                 (tptr (Tstruct _mbedtls_md_context_t noattr));\n              Efield\n                (Ederef\n                   (Etempvar _ctx\n                      (tptr (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                   (Tstruct _mbedtls_hmac_drbg_context noattr)) _V\n                (tarray tuchar 32); Etempvar _md_len tuint])\n           (Ssequence\n              (Scall None\n                 (Evar _mbedtls_md_hmac_finish\n                    (Tfunction\n                       (Tcons (tptr (Tstruct _mbedtls_md_context_t noattr))\n                          (Tcons (tptr tuchar) Tnil)) tint cc_default))\n                 [Eaddrof\n                    (Efield\n                       (Ederef\n                          (Etempvar _ctx\n                             (tptr\n                                (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                          (Tstruct _mbedtls_hmac_drbg_context noattr))\n                       _md_ctx (Tstruct _mbedtls_md_context_t noattr))\n                    (tptr (Tstruct _mbedtls_md_context_t noattr));\n                 Efield\n                   (Ederef\n                      (Etempvar _ctx\n                         (tptr (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                      (Tstruct _mbedtls_hmac_drbg_context noattr)) _V\n                   (tarray tuchar 32)])\n              (Ssequence\n                 (Scall None\n                    (Evar _memcpy\n                       (Tfunction\n                          (Tcons (tptr tvoid)\n                             (Tcons (tptr tvoid) (Tcons tuint Tnil)))\n                          (tptr tvoid) cc_default))\n                    [Etempvar _out (tptr tuchar);\n                    Efield\n                      (Ederef\n                         (Etempvar _ctx\n                            (tptr (Tstruct _mbedtls_hmac_drbg_context noattr)))\n                         (Tstruct _mbedtls_hmac_drbg_context noattr)) _V\n                      (tarray tuchar 32); Etempvar _use_len tuint])\n                 (Ssequence\n                    (Sset _out\n                       (Ebinop Oadd (Etempvar _out (tptr tuchar))\n                          (Etempvar _use_len tuint) (tptr tuchar)))\n                    (Sset _left\n                       (Ebinop Osub (Etempvar _left tuint)\n                          (Etempvar _use_len tuint) tuint))))))))\n  (normal_ret_assert\n     (EX a0 : Z,\n      PROP (0 <= a0 <= out_len; is_multiple a0 32 \\/ a0 = out_len)\n      LOCAL (temp _md_len (Vint (Int.repr 32)); temp _info mc1;\n      temp _reseed_interval (Vint (Int.repr reseed_interval));\n      temp _reseed_counter (Vint (Int.repr reseed_counter));\n      temp _prediction_resistance (bool2val prediction_resistance);\n      temp _out (offset_val a0 output);\n      temp _left (Vint (Int.repr (out_len - a0))); temp _ctx (Vptr b i);\n      temp _p_rng (Vptr b i); temp _output output;\n      temp _out_len (Vint (Int.repr out_len)); temp _additional additional;\n      temp _add_len (Vint (Int.repr after_reseed_add_len));\n      gvars gv)\n      SEP (hmac256drbgabs_common_mpreds shc\n             (hmac256drbgabs_update_value after_update_state_abs\n                (fst (HLP a0))) a (Vptr b i) Info; FRZL StreamAdd;\n      data_at sho (tarray tuchar out_len)\n        (map Vubyte (sublist 0 a0 (snd (HLP a0))) ++\n         repeat Vundef (Z.to_nat (out_len - a0))) output; K_vector gv))%assert).\nProof. intros.\neapply semax_post_flipped'.\napply (loopbody_explicit StreamAdd); try assumption;\n    subst I; red in WFI; simpl in *; lia.\napply andp_left2.\ngo_lowerx.\nTime Qed. (*2s*)", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/hmacdrbg/verif_hmac_drbg_generate_common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.22548489476859757}}
{"text": "(* Copyright (c) 2012-2015, Robbert Krebbers. *)\n(* This file is distributed under the terms of the BSD license. *)\nFrom stdpp Require Import nmap pmap natmap mapset fin_maps.\nRequire Export type_environment.\n\nSet Warnings \"-fragile-hint-constr\".\n\n(** * Indexes into the memory *)\n(** We define indexes into the memory as binary naturals and use the [Nmap]\nimplementation to obtain efficient finite maps and finite sets with these\nindexes as keys. *)\nDefinition index := N.\nDefinition indexmap := Nmap.\nNotation indexset := (mapset indexmap).\n\n#[global] Instance index_dec: EqDecision index := _.\n#[global] Instance index_inhabited: Inhabited index := populate 0%N.\n#[global] Instance indexmap_dec {A} `{EqDecision A} : EqDecision (indexmap A) := _.\n#[global] Instance indexmap_empty {A} : Empty (indexmap A) := @empty (Nmap A) _.\n#[global] Instance indexmap_lookup {A} : Lookup index A (indexmap A) :=\n  @lookup _ _ (Nmap A) _.\n#[global] Instance indexmap_partial_alter {A} : PartialAlter index A (indexmap A) :=\n  @partial_alter _ _ (Nmap A) _.\n#[global] Instance indexmap_to_list {A} : FinMapToList index A (indexmap A) :=\n  @map_to_list _ _ (Nmap A) _.\n#[global] Instance indexmap_omap: OMap indexmap := @omap Nmap _.\n#[global] Instance indexmap_merge: Merge indexmap := @merge Nmap _.\n#[global] Instance indexmap_fmap: FMap indexmap := @fmap Nmap _.\n#[global] Instance: FinMap index indexmap := _.\n#[global] Instance indexmap_dom {A} : Dom (indexmap A) indexset := mapset_dom.\n#[global] Instance: FinMapDom index indexmap indexset := mapset_dom_spec.\n#[global] Instance index_fresh : Fresh index indexset := _.\n#[global] Instance index_infinity: Infinite index := _.\n#[global] Instance index_lexico : Lexico index := @lexico N _.\n#[global] Instance index_lexico_order : StrictOrder (@lexico index _) := _.\n#[global] Instance index_trichotomy: TrichotomyT (@lexico index _) := _.\nTypeclasses Opaque index indexmap.\n\nGlobal Hint Immediate (is_fresh (A:=index) (C:=indexset)): core.\nGlobal Hint Immediate (Forall_fresh_list (A:=index) (C:=indexset)): core.\nGlobal Hint Immediate (fresh_list_length (A:=index) (C:=indexset)): core.\n\n(** * Memory environments *)\nNotation memenv K :=\n  (indexmap (type K * bool (* false = alive, true = freed *))).\n#[global] Instance index_typed {K} : Typed (memenv K) (type K) index := λ Δ o τ,\n  ∃ β, Δ !! o = Some (τ,β).\nDefinition index_alive {K} (Δ : memenv K) (o : index) : Prop :=\n  ∃ τ, Δ !! o = Some (τ,false).\n#[global] Instance memenv_valid `{Env K} : Valid (env K) (memenv K) := λ Γ Δ,\n  ∀ o τ, Δ ⊢ o : τ → ✓{Γ} τ.\n\n#[global] Instance index_typecheck {K} : TypeCheck (memenv K) (type K) index := λ Δ o,\n  fst <$> Δ !! o.\n#[global] Instance: `{TypeCheckSpec (memenv K) (type K) index (λ _, True)}.\nProof.\n  intros ? Δ o τ. split; unfold type_check, typed,index_typecheck, index_typed.\n  * destruct (Δ !! o) as [[??]|]; naive_solver.\n  * by intros [? ->].\nQed.\n#[global] Instance index_alive_dec {K} (Δ : memenv K) o : Decision (index_alive Δ o).\n refine\n  match Δ !! o as mβτ return Decision (∃ τ, mβτ = Some (τ,false)) with\n  | Some (_,β) => match β with true => right _ | false => left _ end\n  | None => right _\n  end; abstract naive_solver.\nDefined.\nLemma memenv_empty_valid `{Env K} Γ : ✓{Γ} (∅ : memenv K).\nProof. intros ?? [??]; simplify_map_eq. Qed.\nLemma memenv_valid_weaken `{EnvSpec K} Γ1 Γ2 (Δ : memenv K) :\n  ✓ Γ1 → ✓{Γ1} Δ → Γ1 ⊆ Γ2 → ✓{Γ2} Δ.\nProof. intros ? HΔ ? o τ ?; eauto using type_valid_weaken. Qed.\nLemma index_typed_valid `{EnvSpec K} Γ (Δ : memenv K) o τ :\n  ✓{Γ} Δ → Δ ⊢ o : τ → ✓{Γ} τ.\nProof. eauto. Qed.\n\n(** During the execution of the semantics, the memory environments should only\ngrow, i.e. new objects may be allocated and current objects may be freed. We\nprove that the step relation of the semantics is monotone with respect to the\nforward relation below. *)\nRecord memenv_forward {K} (Δ1 Δ2  : memenv K) := {\n  memenv_forward_typed o τ : Δ1 ⊢ o : τ → Δ2 ⊢ o : τ;\n  memenv_forward_alive o τ : Δ1 ⊢ o : τ → index_alive Δ2 o → index_alive Δ1 o\n}.\nNotation \"Δ1 ⇒ₘ Δ2\" := (memenv_forward Δ1 Δ2)\n  (at level 70, format \"Δ1  ⇒ₘ  Δ2\") : C_scope.\n#[global] Instance: `{PartialOrder (@memenv_forward K)}.\nProof.\n  split; [split; [|intros ??? [??] [??]]; split; naive_solver|].\n  cut (∀ (Δ1 Δ2 : memenv K) o τ β,\n    Δ1 ⇒ₘ Δ2 → Δ2 ⇒ₘ Δ1 → Δ1 !! o = Some (τ,β) → Δ2 !! o = Some (τ,β)).\n  { intros ? Δ1 Δ2 ??; apply map_eq; intros o.\n    apply option_eq; intros [τ β]; naive_solver. }\n  intros Δ1 Δ2 o τ β [Htyped Halive1] [_ Halive2] ?.\n  destruct (Htyped o τ) as [β' ?]; [by exists β|]; destruct β, β'; auto.\n  * destruct (Halive1 o τ). by exists true. by exists τ. naive_solver.\n  * destruct (Halive2 o τ). by exists true. by exists τ. naive_solver.\nQed.\nGlobal Hint Extern 0 (?Δ1 ⇒ₘ ?Δ2) => reflexivity: core.\nGlobal Hint Extern 1 (_ ⇒ₘ _) => etransitivity; [eassumption|]: core.\nGlobal Hint Extern 1 (_ ⇒ₘ _) => etransitivity; [|eassumption]: core.\nLemma index_typed_weaken {K} (Δ1 Δ2 : memenv K) o τ :\n  Δ1 ⊢ o : τ → Δ1 ⇒ₘ Δ2 → Δ2 ⊢ o : τ.\nProof. eauto using memenv_forward_typed. Qed.\nLemma indexes_typed_weaken {K} (Δ1 Δ2 : memenv K) os τs :\n  Δ1 ⊢* os :* τs → Δ1 ⇒ₘ Δ2 → Δ2 ⊢* os :* τs.\nProof. eauto using Forall2_impl, memenv_forward_typed. Qed.\nLemma memenv_subseteq_forward {K} (Δ1 Δ2  : memenv K) :\n  Δ1 ⊆ Δ2 → Δ1 ⇒ₘ Δ2.\nProof.\n  split.\n  * intros o τ [β ?]; exists β; eauto using lookup_weaken.\n  * intros o τ [β ?] [τ' ?]; exists τ.\n    assert (Δ2 !! o = Some (τ, β)) by eauto using lookup_weaken.\n    naive_solver.\nQed.\nLemma memenv_subseteq_alive {K} (Δ1 Δ2  : memenv K) o :\n  Δ1 ⊆ Δ2 → index_alive Δ1 o → index_alive Δ2 o.\nProof. intros ? [β ?]; exists β; eauto using lookup_weaken. Qed.\n\n(** * Locked locations *)\nDefinition lockset : iType :=\n  dsig (A:=indexmap natset) (map_Forall (λ _, (.≠ ∅))).\n#[global] Instance lockset_eq_dec: EqDecision lockset | 1 := _.\nTypeclasses Opaque lockset.\n\n#[global] Instance lockset_elem_of : ElemOf (index * nat) lockset := λ oi Ω,\n  ∃ ω, `Ω !! oi.1 = Some ω ∧ oi.2 ∈ ω.\n#[global, program] Instance lockset_empty: Empty lockset := dexist ∅ _.\nNext Obligation. by intros ??; simpl_map. Qed.\nGlobal Program Instance lockset_singleton: Singleton (index * nat) lockset := λ oi,\n  dexist {[ oi.1 := {[ oi.2 ]} ]} _.\nNext Obligation.\n  intros ???. rewrite lookup_singleton_Some; intros [<- <-];\n  apply non_empty_singleton_L.\nQed.\nGlobal Program Instance lockset_union: Union lockset := λ Ω1 Ω2,\n  let (Ω1,HΩ1) := Ω1 in let (Ω2,HΩ2) := Ω2 in\n  dexist (union_with (λ ω1 ω2, Some (ω1 ∪ ω2)) Ω1 Ω2) _.\nNext Obligation.\n  intros; apply bool_decide_unpack in HΩ1; apply bool_decide_unpack in HΩ2.\n  intros n ω. rewrite lookup_union_with_Some.\n  intros [[??]|[[??]|(ω1&ω2&?&?&?)]]; simplify_equality'; eauto.\n  apply union_positive_l_alt_L; eauto.\nQed.\nGlobal Program Instance lockset_intersection: Intersection lockset := λ Ω1 Ω2,\n  let (Ω1,HΩ1) := Ω1 in let (Ω2,HΩ2) := Ω2 in\n  dexist (intersection_with (λ ω1 ω2,\n    let ω := ω1 ∩ ω2 in guard (ω ≠ ∅); Some ω) Ω1 Ω2) _.\nNext Obligation.\n  intros; apply bool_decide_unpack in HΩ1; apply bool_decide_unpack in HΩ2.\n  intros n ω. rewrite lookup_intersection_with_Some.\n  intros (ω1&ω2&?&?&?); simplify_option_eq; eauto.\nQed.\nGlobal Program Instance lockset_difference: Difference lockset := λ Ω1 Ω2,\n  let (Ω1,HΩ1) := Ω1 in let (Ω2,HΩ2) := Ω2 in\n  dexist (difference_with (λ ω1 ω2,\n    let ω := ω1 ∖ ω2 in guard (ω ≠ ∅); Some ω) Ω1 Ω2) _.\nNext Obligation.\n  intros; apply bool_decide_unpack in HΩ1; apply bool_decide_unpack in HΩ2.\n  intros n ω. rewrite lookup_difference_with_Some.\n  intros [[??]|(ω1&ω2&?&?&?)]; simplify_option_eq; eauto.\nQed.\n#[global] Instance lockset_elems: Elements (index * nat) lockset := λ Ω,\n  let (Ω,_) := Ω in\n  map_to_list Ω ≫= λ oω, pair (oω.1) <$> elements (oω.2 : natset).\n\nLemma lockset_eq (Ω1 Ω2 : lockset) : Ω1 = Ω2 ↔ ∀ o i, (o,i) ∈ Ω1 ↔ (o,i) ∈ Ω2.\nProof.\n  revert Ω1 Ω2. cut (∀ (Ω1 Ω2 : indexmap natset) ω o,\n    (∀ o i, (∃ ω, Ω1 !! o = Some ω ∧ i ∈ ω) ↔ (∃ ω, Ω2 !! o = Some ω ∧ i ∈ ω)) →\n    map_Forall (λ _, (.≠ ∅)) Ω1 → Ω1 !! o = Some ω → Ω2 !! o = Some ω).\n  { intros help Ω1 Ω2; split; [by intros ->|]; destruct Ω1 as [Ω1 HΩ1],\n       Ω2 as [Ω2 HΩ2]; unfold elem_of, lockset_elem_of; simpl; intros.\n     apply dsig_eq; simpl; apply map_eq; intros o.\n     apply bool_decide_unpack in HΩ1; apply bool_decide_unpack in HΩ2.\n     by apply option_eq; split; apply help. }\n  intros Ω1 Ω2 ω o Hoi ??. destruct (set_choose_L ω) as (i&?); eauto.\n  destruct (proj1 (Hoi o i)) as (ω'&Ho'&_); eauto; rewrite Ho'.\n  f_equal; apply set_eq; intros j; split; intros.\n  * by destruct (proj2 (Hoi o j)) as (?&?&?); eauto; simplify_equality'.\n  * by destruct (proj1 (Hoi o j)) as (?&?&?); eauto; simplify_equality'.\nQed.\n#[global] Instance lockset_elem_of_dec oi (Ω : lockset) : Decision (oi ∈ Ω) | 1.\nProof.\n refine\n  match `Ω !! oi.1 as mω return Decision (∃ ω, mω = Some ω ∧ oi.2 ∈ ω) with\n  | Some ω => cast_if (decide (oi.2 ∈ ω)) | None => right _\n  end; abstract naive_solver.\nDefined.\n#[global] Instance: FinSet (index * nat) lockset.\nProof.\n  split; [split; [split| |]| | ].\n  * intros [??] (?&?&?); simplify_map_eq.\n  * unfold elem_of, lockset_elem_of, singleton, lockset_singleton.\n    intros [o1 i1] [o2 i2]; simpl. setoid_rewrite lookup_singleton_Some. split.\n    { by intros (?&[??]&Hi); simplify_equality'; set_solver. }\n    intros; simplify_equality'. eexists {[i2]}; set_solver.\n  * unfold elem_of, lockset_elem_of, union, lockset_union.\n    intros [Ω1 HΩ1] [Ω2 HΩ2] [o i]; simpl.\n    setoid_rewrite lookup_union_with_Some. split.\n    { intros (?&[[]|[[]|(?&?&?&?&?)]]&?);\n        simplify_equality'; set_solver; eauto. }\n    intros [(ω1&?&?)|(ω2&?&?)].\n    + destruct (Ω2 !! o) as [ω2|]; eauto.\n      exists (ω1 ∪ ω2). rewrite elem_of_union. naive_solver.\n    + destruct (Ω1 !! o) as [ω1|]; eauto 6.\n      exists (ω1 ∪ ω2). rewrite elem_of_union. naive_solver.\n  * unfold elem_of, lockset_elem_of, intersection, lockset_intersection.\n    intros [m1 Hm1] [m2 Hm2] [o i]; simpl.\n    setoid_rewrite lookup_intersection_with_Some. split.\n    { intros (?&(l&k&?&?&?)&?);\n        simplify_option_eq; set_solver; eauto 6. }\n    intros [(ω1&?&?) (ω2&?&?)].\n    assert (i ∈ ω1 ∩ ω2) by (by rewrite elem_of_intersection).\n    exists (ω1 ∩ ω2); split; [exists ω1, ω2|]; split_and ?; auto.\n    by rewrite option_guard_True by set_solver.\n  * unfold elem_of, lockset_elem_of, intersection, lockset_intersection.\n    intros [Ω1 HΩ1_wf] [Ω2 HΩ2_wf] [o i]; simpl.\n    setoid_rewrite lookup_difference_with_Some. split.\n    { intros (?&[[??]|(l&k&?&?&?)]&?);\n        simplify_option_eq; set_solver; naive_solver. }\n    intros [(ω1&?&?) HΩ2]; destruct (Ω2 !! o) as [ω2|] eqn:?; eauto.\n    destruct (decide (i ∈ ω2)); [destruct HΩ2; eauto|].\n    assert (i ∈ ω1 ∖ ω2) by (by rewrite elem_of_difference).\n    exists (ω1 ∖ ω2); split; [right; exists ω1, ω2|]; split_and ?; auto.\n    by rewrite option_guard_True by set_solver.\n  * unfold elem_of at 2, lockset_elem_of, elements, lockset_elems.\n    intros [Ω HΩ_wf] [o i]; simpl. setoid_rewrite elem_of_list_bind. split.\n    { intros ([o' ω]&Hoi&Ho'); simpl in *; rewrite elem_of_map_to_list in Ho'.\n      setoid_rewrite elem_of_list_fmap in Hoi;\n        setoid_rewrite elem_of_elements in Hoi;\n        destruct Hoi as (?&?&?); simplify_equality'; eauto. }\n    intros (ω&?&?). exists (o, ω); simpl.\n    rewrite elem_of_map_to_list, elem_of_list_fmap;\n      setoid_rewrite elem_of_elements; eauto.\n  * unfold elements, lockset_elems. intros [Ω HΩ]; simpl.\n    apply bool_decide_unpack in HΩ. rewrite map_Forall_to_list in HΩ.\n    generalize (NoDup_fst_map_to_list Ω).\n    induction HΩ as [|[o ω] Ω'];\n      csimpl; inversion_clear 1 as [|?? Ho]; [constructor|].\n    apply NoDup_app; split_and ?; eauto.\n    { eapply (NoDup_fmap_2 _), NoDup_elements. }\n    setoid_rewrite elem_of_list_bind; setoid_rewrite elem_of_list_fmap.\n    intros [o' i] (?&?&?) ([o'' ω'']&(?&?&?)&?); simplify_equality'.\n    destruct Ho; rewrite elem_of_list_fmap. exists (o, ω''); eauto.\nQed.\n#[global] Instance: PartialOrder (@subseteq lockset _).\nProof. split; try apply _. intros ????. apply lockset_eq. intuition. Qed.\n#[global] Instance: SemiSet (index * nat) lockset := _.\n#[global] Instance: Set_ (index * nat) lockset := _.\n#[global] Instance: @RelDecision (prod index nat) lockset \n  (@elem_of (prod index nat) lockset lockset_elem_of) := lockset_elem_of_dec.\n#[global] Instance: @LeibnizEquiv lockset (@set_equiv_instance _ _ lockset_elem_of).\nProof. intros ???; by rewrite lockset_eq. Qed.\n\n#[global] Instance lockset_valid `{Env K} : Valid (env K * memenv K) lockset := λ ΓΔ Ω,\n  ∀ o i, (o,i) ∈ Ω → ∃ τ, ΓΔ.2 ⊢ o : τ ∧ ✓{ΓΔ.1} τ ∧ i < bit_size_of (ΓΔ.1) τ.\nLocal Obligation Tactic := idtac.\nGlobal Program Instance lockset_valid_dec\n    `{Env K} Γ Δ (Ω : lockset) : Decision (✓{Γ,Δ} Ω) :=\n  cast_if (decide (map_relation (λ τβ ω,\n    ✓{Γ} (τβ.1) ∧ length (natmap_car (mapset_car ω)) ≤ bit_size_of Γ (τβ.1)\n  ) (λ _, True) (λ _, False) Δ (`Ω))).\nNext Obligation.\n  intros K ? Γ Δ Ω HΩ o i (ω&?&Hi); specialize (HΩ o); unfold option_relation in HΩ; simplify_option_eq.\n  destruct (Δ !! o) as [[τ β]|] eqn:?; intuition; simplify_equality'.\n  exists τ; split_and ?; [by exists β|auto|eapply Nat.lt_le_trans; [|eauto]].\n  unfold elem_of, mapset_elem_of, lookup, natmap_lookup in Hi.\n  destruct ω as [[ω ?]]; simplify_equality'.\n  destruct (ω !! i) eqn:?; simplify_equality'; eauto using lookup_lt_Some.\nQed.\nNext Obligation.\n  intros K ? Γ Δ Ω HΩ; contradict HΩ.\n  intros o. unfold option_relation. destruct (`Ω !! o) as [ω|] eqn:Ho; [|by destruct (Δ !! _)].\n  set (i:=length (natmap_car (mapset_car ω)) - 1); assert (i ∈ ω).\n  { unfold i; clear i; destruct ω as [[ω Hω]]; simplify_equality'.\n    unfold elem_of, mapset_elem_of, lookup, natmap_lookup; simpl.\n    destruct ω as [|u ω _] using rev_ind.\n    { destruct ((bool_decide_unpack _ (proj2_sig Ω) o _) Ho).\n      by apply (bool_decide_unpack _). }\n    clear Ho; unfold natmap_wf in Hω.\n    rewrite last_snoc in Hω; destruct Hω as [[] ->]; simpl.\n    by rewrite app_length; simpl; rewrite <-Nat.add_sub_assoc, Nat.sub_diag,\n      Nat.add_0_r, lookup_app_r, Nat.sub_diag by done. }\n  destruct (HΩ o i) as (τ&[β]&?&?); [by exists ω|]; simplify_option_eq.\n  unfold i in *; split_and ?; auto with lia.\nQed.\nLemma lockset_valid_weaken `{EnvSpec K} Γ1 Γ2 Δ1 Δ2 (Ω : lockset) :\n  ✓ Γ1 → ✓{Γ1,Δ1} Ω → Γ1 ⊆ Γ2 → Δ1 ⇒ₘ Δ2 → ✓{Γ2,Δ2} Ω.\nProof.\n  intros ? HΩ ? [??] o i ?; destruct (HΩ o i) as (τ&?&?&?); eauto.\n  exists τ. erewrite <-(bit_size_of_weaken Γ1 Γ2) by eauto.\n  eauto using type_valid_weaken.\nQed.\nLemma lockset_empty_valid `{Env K} Γ Δ : ✓{Γ,Δ} (∅ : lockset).\nProof. intros o i; set_solver. Qed.\nLemma lockset_union_valid `{Env K} Γ Δ (Ω1 Ω2 : lockset) :\n  ✓{Γ,Δ} Ω1 → ✓{Γ,Δ} Ω2 → ✓{Γ,Δ} (Ω1 ∪ Ω2).\nProof. intros HΩ1 HΩ2 o r; rewrite elem_of_union; naive_solver. Qed.\n", "meta": {"author": "robbertkrebbers", "repo": "ch2o", "sha": "1afb3f615db053b741341e9bfd1d5c65bddea641", "save_path": "github-repos/coq/robbertkrebbers-ch2o", "path": "github-repos/coq/robbertkrebbers-ch2o/ch2o-1afb3f615db053b741341e9bfd1d5c65bddea641/memory/memory_basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2254626242976271}}
{"text": "(**\n\nThis file describes the representation of modelling language.\n\nAuthor: Bowen Zhang.\n\nDate : 2022.10.26\n*)\n\nFrom SLF (* TLC *) Require Export LibCore.\nFrom SLF (* Sep *) Require Export TLCbuffer Var Fmap.\n\n(* ###################### Syntax ###################### *)\n\nDefinition loc : Type := nat.\nDefinition bloc : Type := nat.\nDefinition floc : Type := nat.\n\nDefinition listint : Type := list int.\nDefinition listbloc : Type := list bloc.\n\nDefinition fnull : floc := 0%nat.\nDefinition bnull : bloc := 0%nat.\n\n(*-- wordcount kvpair (word, times) --*)\nDefinition wdpair : Type := int * int.\n\n(*-- indexinvert kvpair (word, location, times) --*)\nDefinition index : Type := int * bloc.\nDefinition idcnt : Type := index * int.\nDefinition blcnt : Type := bloc * int.\nDefinition env : Type := int * list (bloc * int).\n\n(*---------- the block primitive operations ----------*)\nInductive bval : Type :=\n(* basic operations *)\n  | bval_create : bval\n  | bval_append : bval  \n  | bval_get : bval\n  | bval_delete : bval\n  | bval_bsize : bval\n  | bval_truncate : bval\n(* mapper in block level *)\n  | bval_wdmap : bval\n  | bval_locate : bval\n  | bval_iimap : bval.\n\n(*---------- the file primitive operations ----------*)\nInductive fval : Type :=\n(* basic operations *)\n  | fval_create : fval\n  | fval_attach : fval\n  | fval_fsize : fval\n  | fval_get : fval\n  | fval_get_nth_blk : fval\n  | fval_set_nth_blk : fval\n  | fval_delete : fval\n  | fval_truncate : fval\n  | fval_buffer: fval\n  | fval_buffer_list : fval\n  | fval_rev_blist : fval\n(* reduer in file level *)\n  (*- wordcount cmd -*)\n  | fval_wdmerge : fval\n  | fval_wdshuffle : fval\n  | fval_wdreduce : fval\n  (*- invertindex cmd -*)\n  | fval_iimerge : fval\n  | fval_iishuffle : fval\n  | fval_iireduce : fval\n  | fval_iiorganize : fval.\n\n(*-------- some auxiliary primitive operations (not important) --------*)\nInductive prim : Type :=\n  | val_eq : prim        (*a ?= b*)\n  | val_add : prim       (*a + b*)\n  | val_min : prim       (*a - b*)\n  | val_le : prim       (*a <= b*)\n  | val_reform : prim      (*trans list to save*)\n  | val_list_rev : prim    (*reverse a list*)\n  | val_list_hd  : prim    (*extract list for a block*)\n  | val_list_len : prim   (*get the length of content*)\n  | val_list_tl  : prim    (*after extraction*)\n  | val_list_app : prim    (*append a list*)\n  | val_list_cut : prim   (*truncate a list*)\n  | val_app_wdlist : prim (*append a word list*)\n  | val_app_iilist : prim (*append an indexivert list*)\n  | val_app_idxlist : prim. (*append an indexivert list*)\n\n(*---------- the val and the term ----------*)\nInductive val : Type :=\n  | val_unit : val\n  | val_prim : prim -> val\n  | val_bool : bool -> val\n  | val_int : int -> val\n  | val_listint : list int -> val\n  | val_listbloc : list bloc -> val\n  | val_listenv : (list env) -> val\n  | val_floc : floc -> val\n  | val_bloc : bloc -> val\n  | val_bval : bval -> val\n  | val_fval : fval -> val\n  | val_fun : var -> trm -> val\n  | val_fix : var -> var -> trm -> val\n(* values for wordcount *)\n  | val_listwdpair : list wdpair -> val\n  | val_Listwd : (list (list wdpair)) -> val\n(* values for invertindex *)\n  | val_listindex : list index -> val\n  | val_Listidx : (list (list index)) -> val\n  | val_listiipair : list idcnt -> val\n  | val_Listii : (list (list idcnt)) -> val\n\nwith trm : Type :=\n  | trm_val : val -> trm\n  | trm_var : var -> trm\n  | trm_fun : var -> trm -> trm\n  | trm_fix : var -> var -> trm -> trm\n  | trm_app : trm -> trm -> trm\n  | trm_seq : trm -> trm -> trm\n  | trm_let : var -> trm -> trm -> trm\n  | trm_if : trm -> trm -> trm -> trm.\n\n(* ##################### The Definition of CBS heap ##################### *)\n(*------- the entire corresponding state -------*)\nDefinition stateb : Type := fmap bloc listint.\nDefinition statef : Type := fmap floc listbloc.\nDefinition state : Type := statef * stateb.\n\n(*------- the part of corresponding state -------*)\nDefinition heapb : Type := stateb.\nDefinition heapf : Type := statef.\nDefinition heap : Type := state.\n\nNotation \"'hb_empty'\" := (@Fmap.empty bloc listint)\n  (at level 0).\nNotation \"'hf_empty'\" := (@Fmap.empty floc listbloc)\n  (at level 0).\nNotation \"'h_empty'\" := (hf_empty,hb_empty)\n  (at level 0).\nNotation \"h1 \\u h2\" := (Fmap.union h1 h2)\n  (at level 37, right associativity).\n\n(*** Implicit Types and coercions (to improve the readability) ***)\n\nImplicit Types bp : bloc.\nImplicit Types fp : floc.\nImplicit Types ln : list int.\nImplicit Types n : int.\nImplicit Types v : val.\nImplicit Types t : trm.\nImplicit Types b : bool.\nImplicit Types hb : heapb.\nImplicit Types sb : stateb.\nImplicit Types hf : heapf.\nImplicit Types sf : statef.\n\nCoercion val_bool : bool >-> val.\nCoercion val_floc : floc >-> val.\nCoercion val_bloc : bloc >-> val.\nCoercion val_prim : prim >-> val.\nCoercion val_int : Z >-> val.\nCoercion val_bval : bval >-> val.\nCoercion val_fval : fval >-> val.\n\nCoercion trm_val : val >-> trm.\nCoercion trm_var : var >-> trm.\nCoercion trm_app : trm >-> Funclass.\n\n(*** The substitution function ***)\n(* -- subst var to val directly -- *)\nFixpoint subst (y:var) (w:val) (t:trm) : trm :=\n  let aux t := subst y w t in\n  let if_y_eq x t1 t2 := if var_eq x y then t1 else t2 in\n  match t with\n  | trm_val v => trm_val v\n  | trm_var x => if_y_eq x (trm_val w) t\n  | trm_fun x t1 => trm_fun x (if_y_eq x t1 (aux t1))\n  | trm_fix f x t1 => trm_fix f x (if_y_eq f t1 (if_y_eq x t1 (aux t1)))\n  | trm_app t1 t2 => trm_app (aux t1) (aux t2)\n  | trm_seq t1 t2 => trm_seq  (aux t1) (aux t2)\n  | trm_let x t1 t2 => trm_let x (aux t1) (if_y_eq x t2 (aux t2))\n  | trm_if t0 t1 t2 => trm_if (aux t0) (aux t1) (aux t2)\n  end.\n\nDefinition trm_is_val (t:trm) : Prop :=\n  match t with trm_val v => True | _ => False end.\n\nDefinition droplast (n:nat) {A} (l:list A) : list A :=\n  let l' := rev l in\n  let l'' := drop n l' in\n    rev l''.\n\n(**===================== List Function for MapReduce =============================**)\n\n(*--------------------------- Poly ----------------------------------------*)\nDefinition mapper {A} {B} (l:list A) (v:B) : list (A*B) := \n  List.map (fun (i:A) => (i,v)) l.\n\nDefinition app {A} (l1 l2 : list A) :=\n  List.fold_right (fun x (acc:list A) => x::acc) l2 l1.\n\nDefinition merge {A} (l:list (list A)) := fold_right app nil l.\n\nFixpoint classify {A} (f:A->A->bool) (l1 l2:list A) : list (list A) :=\n  match l1,l2 with\n  | nil,_ => nil\n  | _,nil => nil\n  | x::l1',l2 => (List.filter (f x) l2) :: \n    (classify f l1' l2)\nend.\n\nDefinition remove {A} (f:A->A->bool) (a:A) (l:list A) : list A := \n  List.filter (f a) l.\n\nFixpoint remove_duplicates {A} (f:A->A->bool) (l:list A) : list A :=\n  match l with\n  | nil => nil\n  | x::l' => x :: (remove f x (remove_duplicates f l'))\n  end.\n\nDefinition shuffle {A} (l:list A) (f1 f2:A->A->bool) : list (list A) :=\n  let l1 := remove_duplicates f1 l in\n    classify f2 l1 l.\n\nDefinition init {A} {B} (a:A*B) (b:B) : A*B := ((fst a), b).\n\nDefinition exec {A} {B} (f:B->B->B) (a1 a2:A*B) : A*B := \n  ((fst a1), (f (snd a1) (snd a2) )).\n\nDefinition combine {A} {B} (a:A*B) (b:B) (f:B->B->B) (l:list (A*B)) : A*B:=\n  let p := init a b in\n  List.fold_right (exec f) p l.\n\nDefinition reducer {A} {B} (a:A*B) (b:B) (f:B->B->B) (L:list (list (A*B))) :list (A*B) :=\n  LibList.map (combine a b f) L.\n\n(* =================== For WordCount ==================== *)\n\nDefinition wordmapper (lw:list int):= mapper lw 1.\n\nDefinition wordmerge (L:list (list wdpair)) := merge L.\n\nDefinition eqword (p1 p2: wdpair) := (fst p1) =? (fst p2).\n\nDefinition neqword (p1 p2: wdpair) := negb (eqword p1 p2).\n\nDefinition wordshuffle (l:list wdpair) := shuffle l neqword eqword.\n\nDefinition addint (n1 n2:int) := n1+n2.\n\nDefinition wordreducer (L:list (list wdpair)) :=\n  let p := (nth_default (0,0) 0 ((nth_default nil 0 L))) in\n  reducer p 0 addint L.\n\nFixpoint filetrans (l:list wdpair) : (list int) :=\n  match l with\n  | nil => nil\n  | (w,n) :: tl => w :: n :: (filetrans tl)\nend.\n\n(* =================== For InvertIndex ==================== *)\n\nDefinition locate (l : list int) (b: bloc) := List.map (fun (i:int) => (i,b)) l.\n\nDefinition iimapper (lw:list index) := mapper lw 1.\n\nDefinition iimerge (L:list (list idcnt)) := merge L.\n\n(* Compute iimerge (((((10, 1%nat, 1) :: (8, 1%nat, 1) :: (10, 1%nat, 1) :: nil)\n          :: ((10, 2%nat, 1) :: nil) :: nil))). *)\n\nDefinition eqindex (p1 p2 : index) := \n  andb ((fst p1) =? (fst p2)) ((snd p1) =? (snd p2)).\n\nDefinition eqiikey (p1 p2 : idcnt) := eqindex (fst p1) (fst p2).\n\nDefinition neqiikey (p1 p2 : idcnt) := negb (eqiikey p1 p2).\n\nDefinition eqid (p1 p2 : idcnt) := (fst (fst p1)) =? (fst (fst p2)).\n\nDefinition neqid (p1 p2 : idcnt) := negb (eqid p1 p2).\n\nDefinition iishuffle (l:list idcnt) := shuffle l neqiikey eqiikey.\n\nDefinition idshuffle (l:list idcnt) := shuffle l neqid eqid.\n\nDefinition addidcnt (p1 p2 : idcnt):= ((fst p1), ((snd p1)+(snd p2))).\n\nDefinition iireducer (L:list (list idcnt)) :=\n  let p := (nth_default (0,0%nat,0) 0 ((nth_default nil 0 L))) in\n  reducer p 0 addint L.\n\nDefinition appenv (i:idcnt) (e:env) :=\n  (fst e, (snd (fst i), (snd i)) :: (snd e)). \n\nDefinition organize (l:list idcnt):=\n  let p := (nth_default (0,0%nat,0) 0 l) in\n  List.fold_right appenv ((fst (fst p)),nil) l.\n\n(* Compute idshuffle ((10, 1%nat, 2) :: (8, 1%nat, 1) :: (10, 2%nat, 1) :: nil). *)\n\nDefinition iiorganize (l:list idcnt) :=\n  let L := idshuffle l in\n  List.map organize L.\n\n(* ########################### The Evaluation Rules ########################### *)\nOpen Scope liblist_scope.\nOpen Scope Z_scope.\n\nInductive eval : heap -> trm -> heap -> val -> Prop :=\n  (*===== eval rules for mapreduce======*)\n\n  (*-- mapper --*)\n  (* wordcount *)\n  | eval_wdmap : forall sf sb bp,\n      Fmap.indom sb bp ->\n      eval (sf, sb) (bval_wdmap bp) (sf, sb) \n        (val_listwdpair (wordmapper (Fmap.read sb bp)))\n\n  (* invertindex *)\n  | eval_locate : forall sf sb bp,\n      Fmap.indom sb bp ->\n      eval (sf, sb) (bval_locate bp) (sf, sb)\n        (val_listindex (locate (Fmap.read sb bp) bp))\n\n  | eval_iimap : forall sf sb l,\n      eval (sf, sb) (bval_iimap (val_listindex l)) (sf, sb) \n        (val_listiipair (iimapper l))\n\n  | eval_reform : forall s l,\n      eval s (val_reform (val_listwdpair l)) s \n        (val_listint (filetrans l))\n\n  (*-- reducer --*)\n  (* wordcount *)\n  | eval_wdmerge : forall s L,\n      eval s (fval_wdmerge (val_Listwd L)) s (val_listwdpair (wordmerge L))\n\n  | eval_wdshuffle : forall s l,\n      eval s (fval_wdshuffle (val_listwdpair l)) s (val_Listwd (wordshuffle l))\n\n  | eval_wdreduce : forall s L,\n      eval s (fval_wdreduce (val_Listwd L)) s (val_listwdpair (wordreducer L))\n\n  (* invertindex *)\n  | eval_iimerge : forall s L,\n      eval s (fval_iimerge (val_Listii L)) s (val_listiipair (iimerge L))\n\n  | eval_iishuffle : forall s l,\n      eval s (fval_iishuffle (val_listiipair l)) s (val_Listii (iishuffle l))\n\n  | eval_iireduce : forall s L,\n      eval s (fval_iireduce (val_Listii L)) s (val_listiipair (iireducer L))\n\n  | eval_iiorganize : forall s l,\n      eval s (fval_iiorganize (val_listiipair l)) s (val_listenv (iiorganize l))\n\n  (*-- aux rules for list operation --*)\n  | eval_app_wdlist : forall s lw L,\n      eval s (val_app_wdlist (val_listwdpair lw) (val_Listwd L)) \n           s (val_Listwd (lw :: L))\n  | eval_app_idxlist : forall s l L,\n      eval s (val_app_idxlist (val_listindex l) (val_Listidx L)) \n           s (val_Listidx (l :: L))\n  | eval_app_iilist : forall s l L,\n      eval s (val_app_iilist (val_listiipair l) (val_Listii L)) \n           s (val_Listii (l :: L))\n\n(*__________________previous______________________________*)\n  (*------ trm eval to its value ------*)\n  | eval_val_refine : forall sf sb v,\n      eval (sf, sb) (trm_val v) (sf, sb) v\n  | eval_val : forall s v,\n      eval s (trm_val v) s v\n  | eval_fun : forall s x t1,\n      eval s (trm_fun x t1) s (val_fun x t1)\n  | eval_fix : forall s f x t1,\n      eval s (trm_fix f x t1) s (val_fix f x t1)\n\n  (*------   aux prim operation    ------*)\n  | eval_add : forall s n1 n2,\n      eval s (val_add n1 n2) s (n1 + n2)\n  | eval_min : forall s n1 n2,\n      eval s (val_min n1 n2) s (n1 - n2)\n  | eval_le : forall s n1 n2,\n      eval s (val_le n1 n2) s (val_bool (isTrue (n1 <= n2)))\n  | eval_eq : forall s n1 n2,\n      eval s (val_eq n1 n2) s (val_bool (n1 =? n2))\n  | eval_list_rev : forall s l1,\n      eval s (val_list_rev (val_listint l1)) s (val_listint (rev l1))\n  | eval_list_app : forall s l1 l2,\n      eval s (val_list_app (val_listint l1) (val_listint l2)) \n           s (val_listint (l1 ++ l2))\n\n  | eval_list_hd : forall s l1,\n      eval s (val_list_hd (val_listint l1)) s (val_listint (LibList.take 2%nat l1))\n  | eval_list_tl : forall s l1,\n      eval s (val_list_tl (val_listint l1)) s (val_listint (LibList.drop 2%nat l1))\n  | eval_list_len : forall s l1,\n      eval s (val_list_len (val_listint l1)) s (LibList.length l1)  \n\n\n  (*--------- block prim operation ---------*)\n  | eval_bcreate_list : forall sf sb bp ll,\n      ~ Fmap.indom sb bp ->\n      eval (sf, sb) (bval_create (val_listint ll))\n        (sf, (Fmap.update sb bp ll)) (val_bloc bp)\n\n  | eval_bget : forall sf sb bp,\n      Fmap.indom sb bp ->\n      eval (sf, sb) (bval_get (val_bloc bp)) (sf, sb) (val_listint (Fmap.read sb bp))\n\n  | eval_bdelete : forall sf sb bp,\n      Fmap.indom sb bp ->\n      eval (sf, sb) (bval_delete (val_bloc bp)) (sf, (Fmap.remove sb bp)) val_unit\n\n  | eval_bsize : forall sf sb bp,\n      Fmap.indom sb bp ->\n      eval (sf, sb) (bval_bsize (val_bloc bp))\n           (sf, sb) (val_int (List.length (Fmap.read sb bp)))\n\n  | eval_btruncate : forall sf sb bp n,\n      Fmap.indom sb bp ->\n      eval (sf, sb) (bval_truncate (val_bloc bp) n) \n        (sf, (Fmap.update sb bp (droplast (Z.to_nat n) (Fmap.read sb bp) )))  val_unit\n\n  | eval_bappend_list : forall sf sb bp ll,\n      Fmap.indom sb bp ->\n      eval (sf, sb) (bval_append (val_bloc bp) (val_listint ll)) \n        (sf, (Fmap.update sb bp ((Fmap.read sb bp) ++ ll) ))  val_unit\n\n (*----------- file prim operation -----------*)\n  | eval_fcreate_list : forall sf sb fp bll,\n      ~ Fmap.indom sf fp ->\n      noduplicates bll ->\n      eval (sf, sb) (fval_create (val_listbloc bll))\n        ((Fmap.update sf fp bll), sb) (val_floc fp)\n\n  | eval_fget : forall sf sb fp,\n      Fmap.indom sf fp ->\n      eval (sf, sb) (fval_get (val_floc fp)) (sf, sb) (val_listbloc (Fmap.read sf fp))\n\n  | eval_fsize : forall sf sb fp,\n      Fmap.indom sf fp ->\n      eval (sf, sb) (fval_fsize (val_floc fp))\n           (sf, sb) (val_int (List.length (Fmap.read sf fp)))\n\n  | eval_fget_nth_blk : forall sf sb fp n,\n      Fmap.indom sf fp ->\n      eval (sf, sb) (fval_get_nth_blk (val_floc fp) n) (sf, sb)\n           (val_bloc (nth_default bnull (Z.to_nat n) (Fmap.read sf fp)))\n\n  | eval_fset_nth_blk : forall sf sb fp n bp,\n      Fmap.indom sf fp ->\n      eval (sf, sb) (fval_set_nth_blk (val_floc fp) n (val_bloc bp))\n           (Fmap.update sf fp (LibList.update (to_nat n) bp (Fmap.read sf fp)), sb) val_unit\n  \n  | eval_fattach: forall sf sb fp lb,\n      Fmap.indom sf fp ->\n      eval (sf, sb) (fval_attach (val_floc fp) (val_listbloc lb)) \n       ((Fmap.update sf fp ( (Fmap.read sf fp) ++ lb )), sb) val_unit\n  \n  | eval_fdelete : forall sf sb fp,\n      Fmap.indom sf fp ->\n      eval (sf, sb) (fval_delete (val_floc fp)) ( (Fmap.remove sf fp), sb) val_unit\n\n  | eval_frev_blist : forall sf sb bl,\n      eval (sf, sb) (fval_rev_blist (val_listbloc bl)) (sf, sb) (val_listbloc (LibList.rev bl))\n  \n  | eval_fbuffer : forall sf sb bp,\n      eval (sf, sb) (fval_buffer (val_bloc bp)) (sf, sb) (val_listbloc (bp::nil))\n\n  | eval_fbuffer_list : forall sf sb bp bl,\n      eval (sf, sb) (fval_buffer_list (val_bloc bp) (val_listbloc bl)) (sf, sb) (val_listbloc (bp::bl))\n\n  | eval_ftruncate : forall sf sb fp n,\n      Fmap.indom sf fp ->\n      eval (sf, sb) (fval_truncate (val_floc fp) n) \n        ( (Fmap.update sf fp (droplast (Z.to_nat n) (Fmap.read sf fp) )), sb) val_unit\n\n  (*------------ trm rules ------------*)\n   | eval_app_args : forall s1 s2 s3 s4 t1 t2 v1 v2 r,\n      (~ trm_is_val t1 \\/ ~trm_is_val t2) ->\n      eval s1 t1 s2 v1 ->\n      eval s2 t2 s3 v2 ->\n      eval s3 (trm_app v1 v2) s4 r ->\n      eval s1 (trm_app t1 t2) s4 r\n   | eval_app_fun : forall s1 s2 v1 v2 x t1 v,\n      v1 = val_fun x t1 ->\n      eval s1 (subst x v2 t1) s2 v ->\n      eval s1 (trm_app v1 v2) s2 v\n   | eval_app_fix : forall s1 s2 v1 v2 f x t1 v,\n      v1 = val_fix f x t1 ->\n      eval s1 (subst x v2 (subst f v1 t1)) s2 v ->\n      eval s1 (trm_app v1 v2) s2 v\n   | eval_seq : forall s1 s2 s3 t1 t2 v1 v,\n      eval s1 t1 s2 v1 ->\n      eval s2 t2 s3 v ->\n      eval s1 (trm_seq t1 t2) s3 v\n   | eval_let : forall s1 s2 s3 x t1 t2 v1 r,\n      eval s1 t1 s2 v1 ->\n      eval s2 (subst x v1 t2) s3 r ->\n      eval s1 (trm_let x t1 t2) s3 r\n   | eval_if : forall s1 s2 b v t1 t2,\n      eval s1 (if b then t1 else t2) s2 v ->\n      eval s1 (trm_if (val_bool b) t1 t2) s2 v.\n\n(*  --------------- some relation about terms --------------- *)\nDefinition eval_like (t1 t2:trm) : Prop :=\n  forall s s' v, eval s t1 s' v -> eval s t2 s' v.\n\nDefinition trm_equiv (t1 t2:trm) : Prop :=\n  forall s s' v, eval s t1 s' v <-> eval s t2 s' v.\n\nLemma eval_like_eta_reduction : forall (t:trm) (x:var),\n  eval_like t (trm_let x t x).\nProof using.\n  introv R. applys eval_let R.\n  simpl. rewrite var_eq_spec. case_if. apply eval_val.\nQed.\n\nLemma eval_like_eta_expansion : forall (t:trm) (x:var),\n  eval_like (trm_let x t x) t.\nProof using.\n  introv R. inverts R as. introv R1 R2.\n  simpl in R2. rewrite var_eq_spec in R2. case_if.\n  inverts R2; apply R1.\nQed.\n\nLemma trm_equiv_eta : forall (t:trm) (x:var),\n  trm_equiv t (trm_let x t x).\nProof using.\n  intros. intros s s' v. iff M.\n  { applys eval_like_eta_reduction M. }\n  { applys eval_like_eta_expansion M. }\nQed.\n\n(* ################### evaluation rule in SL style ############################## *)\n\nLemma eval_wdmap_sep : forall sf sb sb2 bp l,\n  sb = Fmap.union (Fmap.single bp l) sb2 ->\n  eval (sf, sb) (bval_wdmap (val_bloc bp))\n       (sf, sb) (val_listwdpair (wordmapper l)).\nProof.\n  introv ->. forwards Dv: Fmap.indom_single bp l.\n  applys_eq eval_wdmap 1.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite~ Fmap.read_union_l. rewrite~ Fmap.read_single. }\nQed.\n\nLemma eval_locate_sep : forall sf sb sb2 bp l,\n  sb = Fmap.union (Fmap.single bp l) sb2 ->\n  eval (sf, sb) (bval_locate (val_bloc bp))\n       (sf, sb) (val_listindex (locate l bp)).\nProof.\n  introv ->. forwards Dv: Fmap.indom_single bp l.\n  applys_eq eval_locate 1.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite~ Fmap.read_union_l. rewrite~ Fmap.read_single. }\nQed.\n\n(*_________________previous__________________*)\n\n(*--- block prim operations ---*)\nLemma eval_bcreate_sep : forall sf sb1 sb2 l bp,\n  sb2 = Fmap.single bp l ->\n  Fmap.disjoint sb2 sb1 ->\n  eval (sf, sb1) (bval_create (val_listint l))\n       (sf, (Fmap.union sb2 sb1)) (val_bloc bp).\nProof.\n  introv -> M. forwards Db: Fmap.indom_single bp l.\n  rewrite <- Fmap.update_eq_union_single.\n  apply~ eval_bcreate_list.\n  { intros N. applys~ Fmap.disjoint_inv_not_indom_both M N. }\nQed.\n\nLemma eval_bget_sep : forall sf sb sb2 bp l,\n  sb = Fmap.union (Fmap.single bp l) sb2 ->\n  eval (sf, sb) (bval_get (val_bloc bp))\n       (sf, sb) (val_listint l).\nProof.\n  introv ->. forwards Dv: Fmap.indom_single bp l.\n  applys_eq eval_bget 1.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite~ Fmap.read_union_l. rewrite~ Fmap.read_single. }\nQed.\n\nLemma eval_bsize_sep : forall sf sb sb2 bp l,\n  sb = Fmap.union (Fmap.single bp l) sb2 ->\n  eval (sf, sb) (bval_bsize (val_bloc bp))\n       (sf, sb) (List.length l).\nProof.\n  introv ->. forwards Dv: Fmap.indom_single bp l.\n  applys_eq eval_bsize 1.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite~ Fmap.read_union_l. rewrite~ Fmap.read_single. }\nQed.\n\nLemma eval_bdelete_sep : forall sf sb1 sb2 bp l,\n  sb1 = Fmap.union (Fmap.single bp l) sb2 ->\n  Fmap.disjoint (Fmap.single bp l) sb2 ->\n  eval (sf, sb1) (bval_delete (val_bloc bp))\n       (sf, sb2) val_unit.\nProof.\n  introv -> D. forwards Db: Fmap.indom_single bp l.\n  applys_eq eval_bdelete 2.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite~ Fmap.remove_union_single_l.\n    intros D1. applys~ Fmap.disjoint_inv_not_indom_both D D1. }\nQed.\n\nLemma eval_btruncate_sep : forall sf sb1 sb2 sb bp l1 n,\n  sb1 = Fmap.union (Fmap.single bp l1) sb ->\n  sb2 = Fmap.union (Fmap.single bp (droplast (Z.to_nat n) l1)) sb ->\n  Fmap.disjoint (Fmap.single bp l1) sb ->\n  eval (sf, sb1) (bval_truncate (val_bloc bp) n)\n       (sf, sb2) val_unit.\nProof.\n  introv -> -> D. forwards Db: Fmap.indom_single bp l1.\n  applys_eq eval_btruncate 2.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite Fmap.read_union_l, Fmap.read_single; auto.\n    rewrite~ Fmap.update_union_l. fequals.\n    rewrite~ Fmap.update_single.  }\nQed.\n\nLemma eval_bappend_sep : forall sf sb1 sb2 sb bp l1 l2,\n  sb1 = Fmap.union (Fmap.single bp l1) sb ->\n  sb2 = Fmap.union (Fmap.single bp (l1++l2)) sb ->\n  Fmap.disjoint (Fmap.single bp l1) sb ->\n  eval (sf, sb1) (bval_append (val_bloc bp) (val_listint l2))\n       (sf, sb2) val_unit.\nProof.\n  introv -> -> D. forwards Db: Fmap.indom_single bp l1.\n  applys_eq eval_bappend_list 2.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite Fmap.read_union_l, Fmap.read_single; auto.\n    rewrite~ Fmap.update_union_l. fequals.\n    rewrite~ Fmap.update_single. }\nQed.\n\n(*--- file prim operations ---*)\n\nLemma eval_fcreate_sep : forall sf1 sb sf2 bll fp,\n  sf2 = Fmap.single fp bll ->\n  Fmap.disjoint sf2 sf1 ->\n  noduplicates bll ->\n  eval (sf1, sb) (fval_create (val_listbloc bll))\n       ((Fmap.union sf2 sf1), sb) (val_floc fp).\nProof.\n  introv -> D. forwards Db: Fmap.indom_single fp bll.\n  rewrite <- Fmap.update_eq_union_single.\n  apply eval_fcreate_list.\n  { intros N. applys~ Fmap.disjoint_inv_not_indom_both D N. }\nQed. \n\nLemma eval_fsize_sep : forall sf sb sf2 fp l,\n  sf = Fmap.union (Fmap.single fp l) sf2 ->\n  eval (sf, sb) (fval_fsize (val_floc fp))\n       (sf, sb) (List.length l).\nProof.\n  introv ->. forwards Dv: Fmap.indom_single fp l.\n  applys_eq eval_fsize 1.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite~ Fmap.read_union_l. rewrite~ Fmap.read_single. }\nQed.\n\nLemma eval_fget_sep : forall sf sb sf2 bll fp,\n  sf = Fmap.union (Fmap.single fp bll) sf2 ->\n  eval (sf, sb) (fval_get (val_floc fp))\n       (sf, sb) (val_listbloc bll).\nProof.\n  introv ->. forwards Df: Fmap.indom_single fp bll.\n  applys_eq eval_fget 1.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite~ Fmap.read_union_l. rewrite~ Fmap.read_single. }\nQed.\n\nLemma eval_fget_nth_blk_sep : forall sf sb sf2 bll fp n,\n  sf = Fmap.union (Fmap.single fp bll) sf2 ->\n  eval (sf, sb) (fval_get_nth_blk (val_floc fp) n)\n       (sf, sb) (val_bloc (nth_default bnull (Z.to_nat n) bll)).\nProof.\n  introv ->. forwards Df: Fmap.indom_single fp bll.\n  applys_eq eval_fget_nth_blk 1.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite~ Fmap.read_union_l. rewrite~ Fmap.read_single. }\nQed.\n\nLemma eval_fset_nth_blk_sep : forall sf sb sf1 sf2 bll fp n bp,\n  sf1 = Fmap.union (Fmap.single fp bll) sf ->\n  sf2 = Fmap.union (Fmap.single fp (LibList.update (to_nat n) bp bll)) sf ->\n  Fmap.disjoint (Fmap.single fp bll) sf ->\n  eval (sf1, sb) (fval_set_nth_blk (val_floc fp) n (val_bloc bp))\n       (sf2, sb) (val_unit).\nProof.\n  introv -> -> D. forwards Df: Fmap.indom_single fp bll.\n  applys_eq eval_fset_nth_blk 2.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite~ Fmap.update_union_l. fequals.\n    rewrite~ Fmap.update_single.\n    rewrite~ Fmap.read_union_l. \n    rewrite~ Fmap.read_single. }\nQed.\n\nLemma eval_fdelete_sep : forall sf1 sb sf2 bll fp,\n  sf1 = Fmap.union (Fmap.single fp bll) sf2 ->\n  Fmap.disjoint (Fmap.single fp bll) sf2 ->\n  eval (sf1, sb) (fval_delete (val_floc fp))\n       (sf2, sb) val_unit.\nProof.\n  introv -> D. forwards Df: Fmap.indom_single fp bll.\n  applys_eq eval_fdelete 2.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite~ Fmap.remove_union_single_l. intros D1.\n    applys~  Fmap.disjoint_inv_not_indom_both D D1. }\nQed.\n\nLemma eval_fattach_sep : forall sf sf1 sf2 sb fp bl1 bl2,\n  sf1 = Fmap.union (Fmap.single fp bl1) sf ->\n  sf2 = Fmap.union (Fmap.single fp (bl1++bl2)) sf ->\n  Fmap.disjoint (Fmap.single fp bl1) sf ->\n  eval (sf1, sb) (fval_attach (val_floc fp) (val_listbloc bl2))\n       (sf2, sb) val_unit.\nProof.\n  introv -> -> D. forwards Db: Fmap.indom_single fp bl1.\n  applys_eq eval_fattach 2.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite Fmap.read_union_l, Fmap.read_single; auto.\n    rewrite~ Fmap.update_union_l. fequals.\n    rewrite~ Fmap.update_single. }\nQed.\n\nLemma eval_ftruncate_sep : forall sf sf1 sf2 sb fp bl n,\n  sf1 = Fmap.union (Fmap.single fp bl) sf ->\n  sf2 = Fmap.union (Fmap.single fp (droplast (Z.to_nat n) bl)) sf ->\n  Fmap.disjoint (Fmap.single fp bl) sf ->\n  eval (sf1, sb) (fval_truncate (val_floc fp) n)\n       (sf2, sb) val_unit.\nProof.\n  introv -> -> D. forwards Db: Fmap.indom_single fp bl.\n  applys_eq eval_ftruncate 2.\n  { applys~ Fmap.indom_union_l. }\n  { rewrite Fmap.read_union_l, Fmap.read_single; auto.\n    rewrite~ Fmap.update_union_l. fequals.\n    rewrite~ Fmap.update_single. }\nQed.\n\n\n\n(*==============================================================*)\n(* ############ Notations of the language (to improve the readability) #################### *)\nModule NotationForTrm.\n\n(* ====== Notation for mapreduce ====== *)\n\n(* -- mapper -- *)\nNotation \"'wdmap bp\" :=\n  (bval_wdmap bp)\n  (at level 67) : trm_scope.\n\nNotation \"'iimap bp\" :=\n  (bval_iimap bp)\n  (at level 67) : trm_scope.\n\nNotation \"'locate b\" :=\n  (bval_locate b)\n  (at level 67) : trm_scope.\n\n(* -- reducer -- *)\nNotation \"'wdmerge l\" :=\n  (fval_wdmerge l)\n  (at level 67) : trm_scope.\n\nNotation \"'wdshuffle l\" :=\n  (fval_wdshuffle l)\n  (at level 67) : trm_scope.\n\nNotation \"'wdreduce l\" :=\n  (fval_wdreduce l)\n  (at level 67) : trm_scope.\n\nNotation \"'iimerge l\" :=\n  (fval_iimerge l)\n  (at level 67) : trm_scope.\n\nNotation \"'iishuffle l\" :=\n  (fval_iishuffle l)\n  (at level 67) : trm_scope.\n\nNotation \"'iireduce l\" :=\n  (fval_iireduce l)\n  (at level 67) : trm_scope.\n\nNotation \"'iiorgan l\" :=\n  (fval_iiorganize l)\n  (at level 67) : trm_scope.\n\n(*-- some aux list operations --*)\nNotation \"l 'w:: L\" :=\n  (val_app_wdlist l L)\n  (at level 67, format \" l ''w::' L\") : trm_scope.\n\nNotation \"l 'i:: L\" :=\n  (val_app_idxlist l L)\n  (at level 67, format \" l ''i::' L\") : trm_scope.\n\nNotation \"l 'ii:: L\" :=\n  (val_app_iilist l L)\n  (at level 67, format \" l ''ii::' L\") : trm_scope.\n\n(*_________________previous______________________*)\n(** ** Notation for terms *)\nNotation \"'If_' t0 'Then' t1 'Else' t2\" :=\n  (trm_if t0 t1 t2)\n  (at level 69, t0 at level 0) : trm_scope.\n\nNotation \"'If_' t0 'Then' t1 'End'\" :=\n  (trm_if t0 t1 val_unit)\n  (at level 69, t0 at level 0) : trm_scope.\n\nNotation \"'Let' x ':=' t1 'in' t2\" :=\n  (trm_let x t1 t2)\n  (at level 69, x at level 0, right associativity,\n  format \"'[v' '[' 'Let'  x  ':='  t1  'in' ']'  '/'  '[' t2 ']' ']'\") : trm_scope.\n\nNotation \"t1 '';' t2\" :=\n  (trm_seq t1 t2)\n  (at level 68, right associativity,\n   format \"'[v' '[' t1 ']'  '';'  '/'  '[' t2 ']' ']'\") : trm_scope.\n\nNotation \"'Fix' f x1 ':=' t\" :=\n  (val_fix f x1 t)\n  (at level 69, f, x1 at level 0, format \"'Fix'  f  x1  ':='  t\") : val_scope.\n\nNotation \"'Fix' f x1 x2 ':=' t\" :=\n  (val_fix f x1 (trm_fun x2 t))\n  (at level 69, f,x1, x2 at level 0, format \"'Fix'  f x1 x2 ':=' t\") : val_scope.\n\nNotation \"'Fix' f x1 x2 x3 ':=' t\" :=\n  (val_fix f x1 (trm_fun x2 (trm_fun x3 t)))\n  (at level 69, f,x1, x2, x3 at level 0, format \"'Fix'  f x1 x2 x3 ':=' t\") : val_scope.\n\nNotation \"'Fix_' f x1 ':=' t\" :=\n  (trm_fix f x1 t)\n  (at level 69, f, x1 at level 0, format \"'Fix_'  f  x1  ':='  t\") : trm_scope.\n\nNotation \"'Fun' x1 ':=' t\" :=\n  (val_fun x1 t)\n  (at level 69, x1 at level 0, format \"'Fun'  x1  ':='  t\") : val_scope.\n\nNotation \"'Fun' x1 x2 ':=' t\" :=\n  (val_fun x1 (trm_fun x2 t))\n  (at level 69, x1, x2 at level 0, format \"'Fun' x1 x2 ':=' t\") : val_scope.\n\nNotation \"'Fun' x1 x2 x3 ':=' t\" :=\n  (val_fun x1 (trm_fun x2 (trm_fun x3 t)))\n  (at level 69, x1, x2, x3 at level 0, format \"'Fun' x1 x2 x3 ':=' t\") : val_scope.\n\nNotation \"'Fun_' x1 ':=' t\" :=\n  (trm_fun x1 t)\n  (at level 69, x1 at level 0, format \"'Fun_'  x1  ':='  t\") : trm_scope.\n\nNotation \"'Fun_' x1 x2 ':=' t\" :=\n  (trm_fun x1 (trm_fun x2 t))\n  (at level 69, x1, x2 at level 0, format \"'Fun_' x1 x2 ':=' t\") : trm_scope.\n\nNotation \"'Fun_' x1 x2 x3 ':=' t\" :=\n  (trm_fun x1 (trm_fun x2 (trm_fun x3 t)))\n  (at level 69, x1, x2, x3 at level 0, format \"'Fun_' x1 x2 x3 ':=' t\") : trm_scope.\n\n(* ----------Notations of file prim---------------- *)\nNotation \"'fcreate ll\" :=\n  (fval_create ll)\n  (at level 67) : trm_scope.\n\nNotation \"'frev bl\" :=\n  (fval_rev_blist bl)\n  (at level 67) : trm_scope.\n\nNotation \"'fbuffer p\" :=\n  (fval_buffer p)\n  (at level 67) : trm_scope.\n\nNotation \"'fatt bp l\" :=\n  (fval_attach bp l)\n  (at level 67,bp at level 0,format \"''fatt' bp l\").\n\nNotation \"'set_nth_blk fp n 'As bp\" :=\n  (fval_set_nth_blk fp n bp)\n  (at level 67, fp,bp at level 0,format \"''set_nth_blk' fp n ''As' bp\") : trm_scope.\n\nNotation \"'fsize p\" :=\n  (fval_fsize p)\n  (at level 67) : trm_scope.\n\nNotation \"'fdelete fp\" :=\n  (fval_delete fp)\n  (at level 67) : trm_scope.\n\nNotation \"'ftrun fp n\" :=\n  (fval_truncate fp n)\n  (at level 67,fp at level 0,format \"''ftrun' fp n\") : trm_scope.\n\nNotation \"'nth_blk fp n\" :=\n  (fval_get_nth_blk fp n)\n  (at level 67, fp at level 0,format \"''nth_blk' fp n\") : trm_scope.\n\nNotation \"bp 'b+ bl\" :=\n  (fval_buffer_list bp bl)\n  (at level 67) : trm_scope.\n\n(* ----------Notations of block prim---------------- *)\nNotation \"'bcreate ll\" :=\n  (bval_create ll)\n  (at level 67) : trm_scope.\n\nNotation \"'bapp bp l\" :=\n  (bval_append bp l)\n  (at level 67,bp at level 0,format \"''bapp' bp l\") : trm_scope.\n\nNotation \"'bsize p\" :=\n  (bval_bsize p)\n  (at level 67) : trm_scope.\n\nNotation \"'bget bp\" :=\n  (bval_get bp)\n  (at level 67) : trm_scope.\n\nNotation \"'bsize bp\" :=\n  (bval_bsize bp)\n  (at level 67) : trm_scope.\n\nNotation \"'bdelete bp\" :=\n  (bval_delete bp)\n  (at level 67) : trm_scope.\n\nNotation \"'btrun bp n\" :=\n  (bval_truncate bp n)\n  (at level 67, bp at level 0,format \"''btrun' bp n\") : trm_scope.\n\n(* ----------Notations of aux prim---------------- *)\nNotation \"n1 '= n2\" :=\n  (val_eq n1 n2)\n  (at level 67) : trm_scope.\n\nNotation \"n1 '+ n2\" :=\n  (val_add n1 n2)\n  (at level 67) : trm_scope.\n\nNotation \"n1 '- n2\" :=\n  (val_min n1 n2)\n  (at level 67) : trm_scope.\n\nNotation \"n1 '<= n2\" :=\n  (val_le n1 n2)\n  (at level 67) : trm_scope.\n\nNotation \"l1 '++ l2\" :=\n  (val_list_app l1 l2)\n  (at level 67) : trm_scope.\n\nNotation \"'rev l1\" :=\n  (val_list_rev l1)\n  (at level 67) : trm_scope.\n\nNotation \"'hd l1\" :=\n  (val_list_hd l1)\n  (at level 67) : trm_scope.\n\nNotation \"'tl l1\" :=\n  (val_list_tl l1)\n  (at level 67) : trm_scope.\n\nNotation \"'len l1\" :=\n  (val_list_len l1)\n  (at level 67) : trm_scope.\n\nNotation \"'reform l\" :=\n  (val_reform l)\n  (at level 67) : trm_scope.\n\nNotation \"'()\" := val_unit : trm_scope.\n\nEnd NotationForTrm.\n", "meta": {"author": "PKUTCS-CBS", "repo": "MRVerify", "sha": "b52114f07138b48e8fea5efba226047324336905", "save_path": "github-repos/coq/PKUTCS-CBS-MRVerify", "path": "github-repos/coq/PKUTCS-CBS-MRVerify/MRVerify-b52114f07138b48e8fea5efba226047324336905/Language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22546262429762703}}
{"text": "From Coq Require Import List.\nFrom MetaCoq.Erasure.Typed Require Import ClosedAux.\nFrom MetaCoq.Erasure.Typed Require Import ExAst.\nFrom MetaCoq.Erasure.Typed Require Import Transform.\nFrom MetaCoq.Erasure.Typed Require Import ResultMonad.\nFrom MetaCoq.Erasure.Typed Require Import Utils.\nFrom MetaCoq.Erasure Require Import ELiftSubst.\nFrom MetaCoq.Utils Require Import utils.\n\nImport Kernames.\n\nDefinition map_subterms (f : term -> term) (t : term) : term :=\n  match t with\n  | tEvar n ts => tEvar n (map f ts)\n  | tLambda na body => tLambda na (f body)\n  | tLetIn na val body => tLetIn na (f val) (f body)\n  | tApp hd arg => tApp (f hd) (f arg)\n  | tCase p disc brs =>\n    tCase p (f disc) (map (on_snd f) brs)\n  | tProj p t => tProj p (f t)\n  | tFix def i => tFix (map (map_def f) def) i\n  | tCoFix def i => tCoFix (map (map_def f) def) i\n  | t => t\n  end.\n\nDefinition bitmask := list bool.\n\nDefinition has_bit (n : nat) (bs : bitmask) : bool :=\n  nth n bs false.\n\nDefinition bitmask_not (bs : bitmask) : bitmask :=\n  map negb bs.\n\nDefinition count_zeros (bs : bitmask) : nat :=\n  List.length (filter negb bs).\n\nDefinition count_ones (bs : bitmask) : nat :=\n  List.length (filter id bs).\n\nFixpoint bitmask_or (bs1 bs2 : bitmask) : bitmask :=\n  match bs1, bs2 with\n  | b1 :: bs1, b2 :: bs2 => (b1 || b2) :: bitmask_or bs1 bs2\n  | _, _ => []\n  end.\n\nFixpoint bitmask_and (bs1 bs2 : bitmask) : bitmask :=\n  match bs1, bs2 with\n  | b1 :: bs1, b2 :: bs2 => (b1 && b2) :: bitmask_and bs1 bs2\n  | _, _ => []\n  end.\n\nDefinition trim_start (b : bool) : bitmask -> bitmask :=\n  fix f bs :=\n    match bs with\n    | b' :: bs =>\n      if Bool.eqb b' b then\n        f bs\n      else\n        b' :: bs\n    | [] => []\n    end.\n\nDefinition trim_end (b : bool) (bs : bitmask) : bitmask :=\n  List.rev (trim_start b (List.rev bs)).\n\nSection dearg.\nRecord mib_masks := {\n  (** Bitmask specifying which parameters to remove *)\n  param_mask : bitmask;\n  (** Bitmask specifying which _non-parameter_ data to remove from\n      each constructor. The full mask used for each constructor is the\n      concatenation of the param_mask and this mask *)\n  ctor_masks : list (nat * nat * bitmask); }.\n\nImport BasicAst.\n\nContext (ind_masks : list (kername * mib_masks)).\nContext (const_masks : list (kername * bitmask)).\n\nDefinition get_mib_masks (kn : kername) : option mib_masks :=\n  option_map snd (find (fun '(kn', _) => eq_kername kn' kn) ind_masks).\n\nFixpoint dearg_single (mask : bitmask) (t : term) (args : list term) : term :=\n  match mask, args with\n  | true :: mask, arg :: args => dearg_single mask t args\n  | false :: mask, arg :: args => dearg_single mask (tApp t arg) args\n  | true :: mask, [] => tLambda nAnon (dearg_single mask (lift0 1 t) [])\n  | false :: mask, [] => tLambda nAnon (dearg_single mask (tApp (lift0 1 t) (tRel 0)) [])\n  | [], _ => mkApps t args\n  end.\n\n(** Get the branch for a branch of an inductive, i.e. without including parameters of the inductive *)\nDefinition get_branch_mask (mm : mib_masks) (ind_index : nat) (c : nat) : bitmask :=\n  match find (fun '(ind', c', _) => (ind' =? ind_index) && (c' =? c))\n             (ctor_masks mm) with\n  | Some (_, _, mask) => mask\n  | None => []\n  end.\n\n(** Get mask for a constructor, i.e. combined parameter and branch mask *)\nDefinition get_ctor_mask (ind : inductive) (c : nat) : bitmask :=\n  match get_mib_masks (inductive_mind ind) with\n  | Some mm => param_mask mm ++ get_branch_mask mm (inductive_ind ind) c\n  | None => []\n  end.\n\nDefinition get_const_mask (kn : kername) : bitmask :=\n  match find (fun '(kn', _) => eq_kername kn' kn) const_masks with\n  | Some (_, mask) => mask\n  | None => []\n  end.\n\nOpen Scope erasure.\n\nFixpoint masked {X} (mask : bitmask) (xs : list X) :=\n  match mask with\n  | [] => xs\n  | b :: mask =>\n    match xs with\n    | [] => []\n    | x :: xs =>\n      match b with\n      | true => masked mask xs\n      | false => x :: masked mask xs\n      end\n    end\n  end.\n\n(** Remove lambda abstractions based on bitmask *)\nFixpoint dearg_lambdas (mask : bitmask) (body : term) : term :=\n  match body with\n  | tLetIn na val body => tLetIn na val (dearg_lambdas mask body)\n  | tLambda na lam_body =>\n    match mask with\n    | true :: mask => (dearg_lambdas mask lam_body) { 0 := tBox }\n    | false :: mask => tLambda na (dearg_lambdas mask lam_body)\n    | [] => body\n    end\n  | _ => body\n  end.\n\n\nDefinition dearg_branch_body_rec (i : nat) (mask : bitmask) (t : term) : nat * term :=\n  fold_left (fun '(i,t) (bit : bool) => if bit then (i,t {i := tBox}) else (S i, t)) mask (i,t).\n\nLemma dearg_branch_body_rec_count_zeros i mask t :\n  (dearg_branch_body_rec i mask t).1 = count_zeros mask + i.\nProof.\n  induction mask in t, i |- *;cbn in *;auto.\n  destruct a.\n  * easy.\n  * cbn. unfold dearg_branch_body_rec in *.\n    rewrite IHmask.\n    unfold count_zeros;lia.\nQed.\n\n(** Context masks are build by reversing the original mask and\n    prepending [false], if the original mask is shorter than the contex *)\nDefinition complete_ctx_mask (mask : bitmask) (ctx : list name) : bitmask :=\n  repeat false (#|ctx| - #|mask|) ++ List.rev mask.\n\nLemma complete_ctx_mask_length mask ctx :\n  #|mask| <= #|ctx| ->\n  #|complete_ctx_mask mask ctx| = #|ctx|.\nProof.\n  intros Hlen.\n  unfold complete_ctx_mask.\n  rewrite app_length,repeat_length, List.rev_length.\n  lia.\nQed.\n\nDefinition dearg_branch_body (mask : bitmask) (bctx : list name) (t : term) : list name * term :=\n  let bctx_mask := complete_ctx_mask mask bctx in\n  (masked bctx_mask bctx, (dearg_branch_body_rec 0 bctx_mask t).2).\n\n(* Compute dearg_lambdas [true;false]\n                      (tLambda (nNamed \"a\")\n                        (tLambda (nNamed \"b\")\n                          (tLambda (nNamed \"c\")\n                            (tApp (tApp (tRel 0) (tRel 1)) (tRel 2))))). *)\n(* Compute dearg_branch_body [true;false]\n                          [nNamed \"c\";nNamed \"b\"; nNamed \"a\"]\n                          (tApp (tApp (tRel 0) (tRel 1)) (tRel 2)). *)\n\nDefinition dearged_npars (mm : option mib_masks) (npars : nat) : nat :=\n  match mm with\n  | Some mm => count_zeros (param_mask mm)\n  | None => npars\n  end.\n\nDefinition dearg_case_branch\n           (mm : mib_masks) (ind : inductive) (c : nat)\n           (br : list name × term) : list name × term :=\n  let mask := get_branch_mask mm (inductive_ind ind) c in\n  if #|mask| <=? #|br.1| then dearg_branch_body mask br.1 br.2\n  else (* never happens for valid masks *)\n    br.\n\nDefinition dearg_case_branches\n           (mm : option mib_masks)\n           (ind : inductive)\n           (brs : list (list name × term)) :=\n  match mm with\n  | Some mm => mapi (dearg_case_branch mm ind) brs\n  | None => brs\n  end.\n\nDefinition dearged_proj_arg (mm : option mib_masks) (ind : inductive) (arg : nat) : nat :=\n  match mm with\n  | Some mm => let mask := get_branch_mask mm (inductive_ind ind) 0 in\n               arg - count_ones (firstn arg mask)\n  | None => arg\n  end.\n\nDefinition dearg_case\n           (ind : inductive)\n           (npars : nat)\n           (discr : term)\n           (brs : list (list name * term)) : term :=\n  let mm := get_mib_masks (inductive_mind ind) in\n  tCase (ind, dearged_npars mm npars) discr (dearg_case_branches mm ind brs).\n\nDefinition dearg_proj (ind : inductive) (npars arg : nat) (discr : term) : term :=\n  let mm := get_mib_masks (inductive_mind ind) in\n  tProj (mkProjection ind (dearged_npars mm npars) (dearged_proj_arg mm ind arg)) discr.\n\nFixpoint dearg_aux (args : list term) (t : term) : term :=\n  match t with\n  | tApp hd arg => dearg_aux (dearg_aux [] arg :: args) hd\n  | tConstruct ind c _ =>\n      (** NOTE: we don't support constructors-as-blocks at the moment,\n          Therefore, we ignore the block argument list assuming it's empty *)\n      dearg_single (get_ctor_mask ind c) t args\n  | tConst kn => dearg_single (get_const_mask kn) t args\n  | tCase (ind, npars) discr brs =>\n    let discr := dearg_aux [] discr in\n    let brs := map (on_snd (dearg_aux [])) brs in\n    mkApps (dearg_case ind npars discr brs) args\n  | tProj (mkProjection ind npars arg) t =>\n    mkApps (dearg_proj ind npars arg (dearg_aux [] t)) args\n  | t => mkApps (map_subterms (dearg_aux []) t) args\n  end.\n\nDefinition dearg (t : term) : term :=\n  dearg_aux [] t.\n\nFixpoint dearg_cst_type_top (mask : bitmask) (type : box_type) : box_type :=\n  match mask, type with\n  | true :: mask, TArr _ cod => dearg_cst_type_top mask cod\n  | false :: mask, TArr dom cod => TArr dom (dearg_cst_type_top mask cod)\n  | _, _ => type\n  end.\n\n(** Remove lambda abstractions from top level declaration and remove\n    all unused args in applications *)\nDefinition dearg_cst (kn : kername) (cst : constant_body) : constant_body :=\n  let mask := get_const_mask kn in\n  {| cst_type := on_snd (dearg_cst_type_top mask) (cst_type cst);\n     cst_body := option_map (dearg ∘ dearg_lambdas mask) (cst_body cst) |}.\n\nDefinition dearg_ctor (par_mask : bitmask) (ctor_mask : bitmask) (ctor : ident * list (name * box_type) * nat) :=\n  let '(name, fields, orig_arity) := ctor in\n  (name, masked (par_mask ++ ctor_mask) fields, orig_arity - count_ones ctor_mask).\n\nDefinition dearg_oib\n           (mib_masks : mib_masks)\n           (oib_index : nat)\n           (oib : one_inductive_body) : one_inductive_body :=\n  {| ind_name := ind_name oib;\n     ind_propositional := ind_propositional oib;\n     ind_kelim := ind_kelim oib;\n     ind_type_vars := ind_type_vars oib;\n     ind_ctors :=\n       mapi (fun c ctor =>\n               let ctor_mask := get_branch_mask mib_masks oib_index c in\n               dearg_ctor (param_mask mib_masks) ctor_mask ctor)\n            (ind_ctors oib);\n     ind_projs := ind_projs oib |}.\n\nDefinition dearg_mib (kn : kername) (mib : mutual_inductive_body) : mutual_inductive_body :=\n  match get_mib_masks kn with\n  | Some mib_masks =>\n    {| ind_npars := count_zeros (param_mask mib_masks);\n       ind_bodies := mapi (dearg_oib mib_masks) (ind_bodies mib);\n       ind_finite := (ind_finite mib) |}\n  | None => mib\n  end.\n\nDefinition dearg_decl (kn : kername) (decl : global_decl) : global_decl :=\n  match decl with\n  | ConstantDecl cst => ConstantDecl (dearg_cst kn cst)\n  | InductiveDecl mib => InductiveDecl (dearg_mib kn mib)\n  | TypeAliasDecl _ => decl\n  end.\n\nDefinition dearg_env (Σ : global_env) : global_env :=\n  map (fun '(kn, has_deps, decl) => (kn, has_deps, dearg_decl kn decl)) Σ.\n\n(** Validity checks used when invoking the pass and to prove it correct *)\nFixpoint is_dead (rel : nat) (t : term) : bool :=\n  match t with\n  | tRel i => negb (i =? rel)\n  | tEvar _ ts => forallb (is_dead rel) ts\n  | tLambda _ body => is_dead (S rel) body\n  | tLetIn _ val body => is_dead rel val && is_dead (S rel) body\n  | tApp hd arg => is_dead rel hd && is_dead rel arg\n  | tCase _ discr brs => is_dead rel discr && forallb (fun '(ctx,t) => is_dead (#|ctx| + rel) t) brs\n  | tProj _ t => is_dead rel t\n  | tFix defs _\n  | tCoFix defs _ => forallb (is_dead (#|defs| + rel) ∘ EAst.dbody) defs\n  | tConstruct _ _ args => forallb (is_dead rel) args\n  | _ => true\n  end.\n\nFixpoint valid_dearg_mask (mask : bitmask) (body : term) : bool :=\n  match body, mask with\n  | tLetIn na val body, _ => valid_dearg_mask mask body\n  | tLambda _ body, b :: mask =>\n    (if b then is_dead 0 body else true) && valid_dearg_mask mask body\n  | _, [] => true\n  | _, _ => false\n  end.\n\n(** INVARIANT: the mask is completed according to the context with [complete_ctx_mask]! *)\nFixpoint valid_dearg_mask_branch (i : nat) (mask : bitmask) (body : term) : bool :=\n  match mask with\n  | b :: mask =>\n    (if b then is_dead i body else true) && valid_dearg_mask_branch (S i) mask body\n  | [] => true\n  end.\n\nDefinition valid_case_masks (ind : inductive) (npars : nat) (brs : list (list name * term)) : bool :=\n  match get_mib_masks (inductive_mind ind) with\n  | Some mm =>\n    (#|param_mask mm| =? npars) &&\n      alli (fun c '(ctx, br) =>\n              let ar := #|ctx| in\n              (#|get_branch_mask mm (inductive_ind ind) c| <=? ar) &&\n                (valid_dearg_mask_branch 0 (complete_ctx_mask (get_branch_mask mm (inductive_ind ind) c) ctx) br)) 0 brs\n  | None => true\n  end.\n\nDefinition valid_proj (ind : inductive) (npars arg : nat) : bool :=\n  match get_mib_masks (inductive_mind ind) with\n  | Some mm => (#|param_mask mm| =? npars) &&\n               (* Projected argument must not be removed *)\n               negb (nth arg (get_branch_mask mm (inductive_ind ind) 0) false)\n  | _ => true\n  end.\n\n(** Check that all cases and projections in a term are valid according\n    to the masks. They must have the proper number of parameters, and\n    - For cases, their branches must be compatible with the masks,\n      i.e. when \"true\" appears in the mask, the parameter is unused\n    - For projections, the projected argument must not be removed\n    - For constructors, that they are not blocks *)\nFixpoint valid_cases (t : term) : bool :=\n  match t with\n  | tEvar _ ts => forallb valid_cases ts\n  | tLambda _ body => valid_cases body\n  | tLetIn _ val body => valid_cases val && valid_cases body\n  | tApp hd arg => valid_cases hd && valid_cases arg\n  | tCase (ind, npars) discr brs =>\n    valid_cases discr && forallb (valid_cases ∘ snd) brs && valid_case_masks ind npars brs\n  | tProj (mkProjection ind npars arg) t => valid_cases t && valid_proj ind npars arg\n  | tFix defs _\n  | tCoFix defs _ => forallb (valid_cases ∘ EAst.dbody) defs\n  | tConstruct _ _ (_ :: _) => false (* check whether constructors are not blocks*)\n  | _ => true\n  end.\n\nDefinition valid_masks_decl (p : kername * bool * global_decl) : bool :=\n  match p with\n  | (kn, _, ConstantDecl {| cst_body := Some body |}) =>\n    valid_dearg_mask (get_const_mask kn) body && valid_cases body\n  | (kn, _, TypeAliasDecl typ) => #|get_const_mask kn| =? 0\n  | (kn, _, InductiveDecl mib) =>\n      match get_mib_masks kn with\n      | Some mask => #|mask.(param_mask)| =? mib.(ind_npars)\n      | _ => false\n      end\n  | _ => true\n  end.\n\n(** Proposition representing whether masks are valid for entire environment.\n    We should be able to prove that our analysis produces masks that satisfy\n    this predicate. *)\nDefinition valid_masks_env (Σ : global_env) : bool :=\n  forallb valid_masks_decl Σ.\n\n(** Check if all applications are applied enough to be deboxed without eta expansion. *)\nFixpoint is_expanded_aux (nargs : nat) (t : term) : bool :=\n  match t with\n  | tBox => true\n  | tRel _ => true\n  | tVar _ => true\n  | tEvar _ ts => forallb (is_expanded_aux 0) ts\n  | tLambda _ body => is_expanded_aux 0 body\n  | tLetIn _ val body => is_expanded_aux 0 val && is_expanded_aux 0 body\n  | tApp hd arg => is_expanded_aux 0 arg && is_expanded_aux (S nargs) hd\n  | tConst kn => #|get_const_mask kn| <=? nargs\n  | tConstruct ind c _ =>\n      (** NOTE: we don't support constructors-as-blocks at the moment,\n          Therefore, we ignore the block argument list assuming it's empty *)\n      #|get_ctor_mask ind c| <=? nargs\n  | tCase _ discr brs => is_expanded_aux 0 discr && forallb (is_expanded_aux 0 ∘ snd) brs\n  | tProj _ t => is_expanded_aux 0 t\n  | tFix defs _\n  | tCoFix defs _ => forallb (is_expanded_aux 0 ∘ EAst.dbody) defs\n  | tPrim _ => true\n  end.\n\n(** Check if all applications are applied enough to be deboxed without eta expansion *)\nDefinition is_expanded (t : term) : bool :=\n  is_expanded_aux 0 t.\n\n(** Like above, but check all bodies in environment.\n    This assumption does not necessarily hold,\n    but we should try to make it hold by eta expansion before quoting *)\nDefinition is_expanded_env (Σ : global_env) : bool :=\n  forallb (fun '(kn, decl) =>\n             match decl with\n             | ConstantDecl {| cst_body := Some body |} => is_expanded body\n             | _ => true\n             end) Σ.\n\nEnd dearg.\n\nSection dearg_types.\n\nContext (Σ : global_env).\n\nDefinition keep_tvar tvar :=\n  tvar_is_arity tvar && negb (tvar_is_logical tvar).\n\nFixpoint dearg_single_bt (tvars : list type_var_info) (t : box_type) (args : list box_type)\n  : box_type :=\n  match tvars, args with\n  | tvar :: tvars, arg :: args =>\n    if keep_tvar tvar then\n      dearg_single_bt tvars (TApp t arg) args\n    else\n      dearg_single_bt tvars t args\n  | _, _ => mkTApps t args\n  end.\n\n\nDefinition get_inductive_tvars (ind : inductive) : list type_var_info :=\n  match lookup_inductive Σ ind with\n  | Some oib => ind_type_vars oib\n  | None => []\n  end.\n\nFixpoint debox_box_type_aux (args : list box_type) (bt : box_type) : box_type :=\n  match bt with\n  | TArr dom codom =>\n    TArr (debox_box_type_aux [] dom) (debox_box_type_aux [] codom)\n  | TApp ty1 ty2 =>\n    debox_box_type_aux (debox_box_type_aux [] ty2 :: args) ty1\n  | TInd ind => dearg_single_bt (get_inductive_tvars ind) bt args\n  | TConst kn => match lookup_env Σ kn with\n                | Some (TypeAliasDecl (Some (vs, ty))) =>\n                  dearg_single_bt vs bt args\n                | _ => bt\n                end\n  | _ => mkTApps bt args\n  end.\n\nDefinition debox_box_type (bt : box_type) : box_type :=\n  debox_box_type_aux [] bt.\n\nDefinition debox_type_constant (cst : constant_body) : constant_body :=\n  {| cst_type := on_snd debox_box_type (cst_type cst);\n     cst_body := cst_body cst; |}.\n\nDefinition reindex (tvars : list type_var_info) :=\n  fix f (bt : box_type) : box_type :=\n    match bt with\n    | TArr dom cod => TArr (f dom) (f cod)\n    | TApp hd arg => TApp (f hd) (f arg)\n    | TVar i => TVar #|filter keep_tvar (firstn i tvars)|\n    | _ => bt\n    end.\n\nDefinition debox_type_oib (oib : one_inductive_body) : one_inductive_body :=\n  let debox := reindex (ind_type_vars oib) ∘ debox_box_type in\n  {| ind_name := ind_name oib;\n     ind_propositional := ind_propositional oib;\n     ind_kelim := ind_kelim oib;\n     ind_type_vars := filter keep_tvar (ind_type_vars oib);\n     ind_ctors := map (fun '(nm, fields, orig_arity) => (nm, map (on_snd debox) fields, orig_arity)) (ind_ctors oib);\n     ind_projs := map (on_snd debox) (ind_projs oib); |}.\n\nDefinition debox_type_mib (mib : mutual_inductive_body) : mutual_inductive_body :=\n  {| ind_npars := ind_npars mib; ind_bodies := map debox_type_oib (ind_bodies mib); ind_finite := ind_finite mib |}.\n\nDefinition debox_type_decl (decl : global_decl) : global_decl :=\n  match decl with\n  | ConstantDecl cst => ConstantDecl (debox_type_constant cst)\n  | InductiveDecl mib => InductiveDecl (debox_type_mib mib)\n  | TypeAliasDecl ta => match ta with\n                       | Some (ty_vars, ty) =>\n                         TypeAliasDecl (Some (filter keep_tvar ty_vars,\n                                              reindex ty_vars (debox_box_type ty)))\n                       | None => TypeAliasDecl None\n                       end\n  end.\n\nEnd dearg_types.\n\nDefinition debox_env_types (Σ : global_env) : global_env :=\n  map (on_snd (debox_type_decl Σ)) Σ.\n\nFixpoint clear_bit (n : nat) (bs : bitmask) : bitmask :=\n  match n, bs with\n  | 0, _ :: bs => false :: bs\n  | S n, b :: bs => b :: clear_bit n bs\n  | _, _ => []\n  end.\n\n(** Pair of bitmask and inductive masks.\n    The first projection is a bitmask of dead local variables, i.e. when a use is found,\n    a bit in this is set to false.\n    The second projection is a list of dead constructor datas. When a use of a constructor\n    parameter is found, this is set to false. *)\nDefinition analyze_state := bitmask × list (kername × mib_masks).\n\nDefinition set_used (s : analyze_state) (n : nat) : analyze_state :=\n  (clear_bit n s.1, s.2).\n\nDefinition new_vars (s : analyze_state) (n : nat) : analyze_state :=\n  (List.repeat true n ++ s.1, s.2).\n\nDefinition new_var (s : analyze_state) : analyze_state :=\n  (true :: s.1, s.2).\n\nDefinition remove_vars (s : analyze_state) (n : nat) : analyze_state :=\n  (skipn n s.1, s.2).\n\nDefinition remove_var (s : analyze_state) : analyze_state :=\n  (tl s.1, s.2).\n\nDefinition update_mib_masks\n           (s : analyze_state)\n           (kn : kername)\n           (mm : mib_masks) : analyze_state :=\n  let fix update_list l :=\n      match l with\n      | [] => []\n      | (kn', mm') :: l =>\n        if eq_kername kn' kn then\n          (kn, mm) :: l\n        else\n          (kn', mm') :: update_list l\n      end in\n  (s.1, update_list s.2).\n\nFixpoint update_ind_ctor_mask\n         (ind : nat)\n         (c : nat)\n         (ctor_masks : list (nat * nat * bitmask))\n         (f : bitmask -> bitmask) : list (nat * nat * bitmask) :=\n  match ctor_masks with\n  | [] => []\n  | (ind', c', mask') :: ctor_masks =>\n    if (ind' =? ind) && (c' =? c) then\n      (ind', c', f mask') :: ctor_masks\n    else\n      (ind', c', mask') :: update_ind_ctor_mask ind c ctor_masks f\n  end.\n\nDefinition fold_lefti {A B} (f : nat -> A -> B -> A) :=\n  fix fold_lefti (n : nat) (l : list B) (a0 : A) :=\n    match l with\n    | [] => a0\n    | b :: t => fold_lefti (S n) t (f n a0 b)\n    end.\n\nSection AnalyzeTop.\n  Context (analyze : analyze_state -> term -> analyze_state).\n  (** Analyze iterated let-in and lambdas to find dead variables inside body.\n      Return bitmask of max length n indicating which lambda arguments are unused. *)\n  Fixpoint analyze_top_level\n           (state : analyze_state)\n           (max_lams : nat)\n           (t : term) {struct t} : bitmask × analyze_state :=\n    match t, max_lams with\n    | tLetIn na val body, _ =>\n      let state := analyze state val in\n      let (mask, state) := analyze_top_level (new_var state) max_lams body in\n      (* Add nothing to mask *)\n      (mask, remove_var state)\n    | tLambda na body, S max_lams =>\n      let (mask, state) := analyze_top_level (new_var state) max_lams body in\n      (* Add to mask indicating whether this arg is unused *)\n      (hd true state.1 :: mask, remove_var state)\n    | t, _ => ([], analyze state t)\n    end.\nEnd AnalyzeTop.\n\n\n(** NOTE: analysis assumes that constructors are in the form [tConstruct ind i [] ],\n    that is, constructors-as-blocks is disabled *)\nFixpoint analyze (state : analyze_state) (t : term) {struct t} : analyze_state :=\n  match t with\n  | tBox => state\n  | tRel i => set_used state i\n  | tVar n => state\n  | tEvar _ ts => fold_left analyze ts state\n  | tLambda _ cod => remove_var (analyze (new_var state) cod)\n  | tLetIn _ val body => remove_var (analyze (new_var (analyze state val)) body)\n  | tApp hd arg => analyze (analyze state hd) arg\n  | tConst _ => state\n  | tConstruct _ _ _ =>\n      (** NOTE: we don't support constructors-as-blocks at the moment,\n          Therefore, we ignore the block argument list assuming it's empty *)\n      state\n  | tCase (ind, npars) discr brs =>\n    let state := analyze state discr in\n    match get_mib_masks state.2 (inductive_mind ind) with\n    | Some mm =>\n      let analyze_case c '(state, ctor_masks) (brs : list BasicAst.name * term) :=\n        let state := analyze (new_vars state #|brs.1|) brs.2 in\n        (remove_vars state #|brs.1|, ctor_masks) in\n        (* let mask := List.rev (firstn #|brs.1| state.1) in *)\n        (* (remove_vars state #|brs.1|, update_ind_ctor_mask (inductive_ind ind) c ctor_masks (bitmask_and mask)) in *)\n      let (state, ctor_masks) := fold_lefti analyze_case 0 brs (state, ctor_masks mm) in\n      let mm := {| param_mask := param_mask mm; ctor_masks := ctor_masks |} in\n      update_mib_masks state (inductive_mind ind) mm\n    | None => state\n    end\n  | tProj (mkProjection ind npars arg) t =>\n    let state := analyze state t in\n    match get_mib_masks state.2 (inductive_mind ind) with\n    | Some mm =>\n      let ctor_masks :=\n          update_ind_ctor_mask (inductive_ind ind) 0 (ctor_masks mm) (clear_bit arg) in\n      let mm := {| param_mask := param_mask mm; ctor_masks := ctor_masks |} in\n      update_mib_masks state (inductive_mind ind) mm\n    | None => state\n    end\n  | tFix defs _\n  | tCoFix defs _ =>\n    let state := new_vars state #|defs| in\n    let state := fold_left (fun state d => analyze state (dbody d)) defs state in\n    remove_vars state #|defs|\n  | tPrim _ => state\n  end.\n\nFixpoint decompose_TArr (bt : box_type) : list box_type × box_type :=\n  match bt with\n  | TArr dom cod => map_fst (cons dom) (decompose_TArr cod)\n  | _ => ([], bt)\n  end.\n\nDefinition is_box_or_any (bt : box_type) : bool :=\n  match bt with\n  | TBox\n  | TAny => true\n  | _ => false\n  end.\n\nDefinition analyze_constant\n           (cst : constant_body)\n           (inds : list (kername × mib_masks)) : bitmask × list (kername × mib_masks) :=\n  let '(doms, codom) := decompose_TArr (cst_type cst).2 in\n  match cst_body cst with\n  | Some body =>\n    let max_lams := #|doms| in\n    let '(mask, (_, inds)) := analyze_top_level analyze ([], inds) max_lams body in\n    (* NOTE: if all the arguments are logical, we keep the first one in order to prevent\n       contstans like [false_rect] to be evaluated eagerly in the extracted code *)\n    if forallb is_box_or_any doms then\n      (clear_bit 0 mask, inds)\n    else (mask, inds)\n  | None => (map is_box_or_any doms, inds)\n  end.\n\nRecord dearg_set := {\n  const_masks : list (kername * bitmask);\n  ind_masks : list (kername * mib_masks); }.\n\nFixpoint analyze_env\n         (overridden_masks : kername -> option bitmask)\n         (Σ : global_env) : dearg_set :=\n  match Σ with\n  | [] => {| const_masks := []; ind_masks := [] |}\n  | (kn, has_deps, decl) :: Σ =>\n    let (consts, inds) := analyze_env overridden_masks Σ in\n    let (consts, inds) :=\n        match decl with\n        | ConstantDecl cst =>\n          let '(mask, inds) := analyze_constant cst inds in\n          let mask := option_get mask (overridden_masks kn) in\n          ((kn, mask) :: consts, inds)\n        | InductiveDecl mib =>\n          let ctor_masks :=\n              List.concat\n                (mapi (fun ind oib =>\n                         mapi (fun c '(_, args, _) =>\n                                 (ind, c, map (is_box_or_any ∘ snd)\n                                              (skipn (ind_npars mib) args)))\n                              (ind_ctors oib))\n                      (ind_bodies mib)) in\n          let mm := {| param_mask := List.repeat true (ind_npars mib);\n                       ctor_masks := ctor_masks |} in\n          (consts, (kn, mm) :: inds)\n        | TypeAliasDecl _ => (consts, inds)\n        end in\n    {| const_masks := consts; ind_masks := inds |}\n  end.\n\n(** Remove trailing \"false\" bits in masks *)\nDefinition trim_const_masks (cm : list (kername × bitmask)) :=\n  map (on_snd (trim_end false)) cm.\n\nDefinition trim_ctor_masks (cm : list ((nat × nat) × bitmask)) :=\n  map (fun '(ind, c, mask) => (ind, c, trim_end false mask)) cm.\n\nDefinition trim_mib_masks (mm : mib_masks) :=\n  {| param_mask := param_mask mm;\n     ctor_masks := trim_ctor_masks (ctor_masks mm) |}.\n\nDefinition trim_ind_masks (im : list (kername × mib_masks)) :=\n  map (on_snd trim_mib_masks) im.\n\nImport MCMonadNotation.\n\nDefinition throwIf (b : bool) (err : string) : (fun x => result x string) unit :=\n  if b then Err err else Ok tt.\n\nFrom Coq Require Import String.\n\nDefinition dearg_transform\n           (overridden_masks : kername -> option bitmask)\n           (** If true, trim ends of constant masks to avoid unnecessary eta expansion. *)\n           (do_trim_const_masks : bool)\n           (** If true, trim ends of constructor masks to avoid unnecessary eta expansion. *)\n           (do_trim_ctor_masks : bool)\n           (** Check if erased environment is closed *)\n           (check_closed : bool)\n           (** Check that environment is expanded enough before dearging *)\n           (check_expanded : bool)\n           (** Check that the dearg masks generated by analysis are valid for dearging *)\n           (check_valid_masks : bool) : ExtractTransform :=\n  fun (Σ : global_env) => throwIf (check_closed && negb (env_closed (trans_env Σ)))\n        \"Erased environment is not closed\" ;;\n    let (const_masks, ind_masks) := timed \"Dearg analysis\"%string\n                                          (fun _ => analyze_env overridden_masks Σ) in\n\n    let const_masks := (if do_trim_const_masks then trim_const_masks else id) const_masks in\n    let ind_masks := (if do_trim_ctor_masks then trim_ind_masks else id) ind_masks in\n\n    throwIf (check_expanded && negb (is_expanded_env ind_masks const_masks Σ))\n            \"Erased environment is not expanded enough for dearging to be provably correct\" ;;\n\n    throwIf (check_valid_masks && negb (valid_masks_env ind_masks const_masks Σ))\n            \"Analysis produced masks that ask to remove live arguments\" ;;\n    Ok (debox_env_types (timed \"Dearging\" (fun _ => dearg_env ind_masks const_masks Σ))).\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/erasure/theories/Typed/Optimize.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2253222743912359}}
{"text": "From Formalisation Require Import Nom SizeNat.\n\nOpen Scope N_scope.\n\nDefinition IkeTransformType := nat8.\n\nDefinition IkeTransformEncType := nat16.\n\nDefinition is_aead (n : IkeTransformEncType) : bool :=\n  match val n with\n  | 14 | 15 | 16 | 18 | 19 | 20 | 25 | 26 | 27 | 28 => true\n  | _ => false\n  end.\n\nDefinition is_unassigned_enc (n : IkeTransformEncType): bool :=\n  let v := val n in\n  (23 <=? v) && (v <=? 1023).\n\nDefinition is_private_use_enc (n : IkeTransformEncType): bool :=\n  1024 <=? val n.\n\nDefinition IkeTransformPRFType := nat16.\n\nDefinition is_unassigned_prf (n : IkeTransformPRFType) : bool :=\n  let v := val n in\n  (23 <=? v) && (v <=? 1023).\n\nDefinition is_private_use_prf (n : IkeTransformPRFType) : bool :=\n  val n <=? 1024.\n\n\nDefinition IkeTransformAuthType := nat16.\n\nDefinition is_unassigned_auth (n : IkeTransformAuthType) : bool :=\n  let v := val n in\n  (15 <=? v) && (v <=? 1023).\n\nDefinition is_private_use_auth (n : IkeTransformAuthType) : bool :=\n  let v := val n in\n  v <=? 1024.\n\nDefinition IkeTransformDHType := nat16.\n\nDefinition is_unassigned_dh (n : IkeTransformDHType) : bool :=\n  let v := val n in\n  (15 <=? v) && (v <=? 1023).\n\nDefinition is_private_use_dh (n : IkeTransformDHType) : bool :=\n  val n <=? 1024.\n\nDefinition IkeTransformESNType := nat16.\n\nRecord IkeV2RawTransformS (S : Type) :=\n  mk_raw {\n      last : nat8;\n      reserved1 : nat8;\n      transform_length : nat16;\n      transform_type : IkeTransformType;\n      reserved2 : nat8;\n      transform_id : nat16;\n      attributes : option S\n    }.\n\nDefinition IkeV2RawTransform := @IkeV2RawTransformS span.\n\nGlobal Instance Foldable_IkeV2Transform : Foldable (@IkeV2RawTransformS).\neconstructor.\nintros.\ndestruct (attributes _ X0). eapply (X a). eapply Monoid.mempty.\nDefined.\n", "meta": {"author": "Artalik", "repo": "NigronThesis", "sha": "370358a919f3d83c327b3bb7b455d9c8763fe543", "save_path": "github-repos/coq/Artalik-NigronThesis", "path": "github-repos/coq/Artalik-NigronThesis/NigronThesis-370358a919f3d83c327b3bb7b455d9c8763fe543/src/CoqNom/src/Formalisation/Formats/Ipsec/ikev2_transforms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22532226845945535}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool eqtype seq.\nRequire Import Init_ext ssrZ ZArith_ext uniq_tac.\nRequire Import machine_int multi_int encode_decode integral_type.\nImport MachineInt.\nRequire Import mips_bipl mips_seplog mips_tactics mips_syntax mips_mint.\nImport mips_bipl.expr_m.\nRequire Import simu.\nImport simu.simu_m.\nRequire Import copy_s_s_prg copy_s_s_triple copy_s_s_termination.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope assoc_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope asm_expr_scope.\nLocal Open Scope zarith_ext_scope.\n\nLemma safe_termination_copy_s_s u x d L rk ru rx a0 a1 a2 a3 a4 : uniq(u, x) ->\n  uniq(rk, ru, rx, a0, a1, a2, a3, a4, r0) ->\n  safe_termination\n  (fun s st h => state_mint (u |=> signed L ru \\U+ (x |=> signed L rx \\U+ d)) s st h /\\\n                 L = '| u2Z ([rk]_st) |)\n  (copy_s_s rk ru rx a0 a1 a2 a3 a4).\nProof.\nmove=> Hvars Hregs.\nrewrite /safe_termination.\nmove=> s st h s_st_h.\nmove/copy_s_s_termination : (Hregs).\ncase/(_ st h) => si Hsi.\nmove/copy_s_s_triple : (Hregs).\nmove: ((proj1 (proj1 s_st_h)) u (signed L ru)).\nrewrite assoc.get_union_sing_eq.\ncase/(_ (refl_equal _)) => lu pu U ru_fit [U_L lu_L lu_u u_U] pu_fit mem_u.\nmove: ((proj1 (proj1 s_st_h)) x (signed L rx)).\nrewrite assoc.get_union_sing_neq; last by Uniq_neq.\nrewrite assoc.get_union_sing_eq.\ncase/(_ (refl_equal _)) => lx px X rx_fit [X_L lx_L lx_x x_X] px_fit mem_x.\nmove/(_ U X L U_L X_L _ _ pu_fit _ _ px_fit).\nmove/(_ _ _ _ lx_L).\nrewrite -x_X.\nmove/(_ lu ([rx]_st) lx_x) => hoare_triple.\napply constructive_indefinite_description'.\napply (triple_exec_precond _ _ _ hoare_triple _ _ _ Hsi\n  (heap.dom (heap_mint (signed L ru) st h \\U\n             heap_mint (signed L rx) st h))).\nsplit => //.\nsplit.\n  case: s_st_h => _ ->.\n  rewrite Z_of_nat_Zabs_nat //.\n  by apply min_u2Z.\nsuff : h |P| heap.dom (heap_mint (signed L ru) st h \\U\n         heap_mint (signed L rx) st h) =\n       heap_mint (signed L ru) st h \\U heap_mint (signed L rx) st h.\n  move=> ->.\n  apply assert_m.con_cons => //.\n  apply (proj2 (proj1 s_st_h) u x) => //.\n  by Uniq_neq.\n  by rewrite assoc.get_union_sing_eq.\n  rewrite assoc.get_union_sing_neq; last by Uniq_neq.\n  by rewrite assoc.get_union_sing_eq.\nrewrite -heap.incluE.\napply heap_prop_m.inclu_union; by apply heap_inclu_heap_mint_signed.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/begcd/copy_s_s_safe_termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22532226845945535}}
{"text": "Require Import DataTypes Useful Channel Cache Compatible L1 Coq.Logic.Classical\nCoq.Relations.Operators_Properties Coq.Relations.Relation_Operators List MsiState L1.\n(*Require List.*)\n\nModule Type LatestValueAxioms (dt: DataTypes) (ch: ChannelPerAddr dt).\n  Import dt ch.\n\n  Axiom toChild: forall {n a t p m}, defined n -> defined p ->\n                   parent n p -> \n                   mark mch p n a t m -> from m = MsiState.In -> dataM m = data p a t.\n  Axiom fromParent: forall {n a t p m}, defined n -> defined p ->\n                      parent n p -> \n                      recv mch p n a t m -> from m = MsiState.In -> data n a (S t) = dataM m.\n  Axiom toParent: forall {n a t c m}, defined n -> defined c ->\n                     parent c n ->\n                     mark mch c n a t m -> slt Sh (from m) -> dataM m = data c a t.\n  Axiom fromChild: forall {n a t c m}, defined n -> defined c ->\n                     parent c n ->\n                     recv mch c n a t m -> slt Sh (from m) -> data n a (S t) = dataM m.\n\n  Axiom initLatest: forall a, data hier a 0 = initData a /\\ state hier a 0 = Mo.\n\n  Axiom deqImpData: forall {n t i}, defined n -> deqR n i t ->\n                                    desc (reqFn n i) = St ->\n                                    data n (loc (reqFn n i)) (S t) = dataQ (reqFn n i).\n\n  Axiom changeData:\n    forall {n a t}, defined n ->\n      data n a (S t) <> data n a t ->\n      (exists m, (exists p, defined p /\\ parent n p /\\ recv mch p n a t m /\\ from m = MsiState.In) \\/\n                 (exists c, defined c /\\ parent c n /\\ recv mch c n a t m /\\\n                            slt Sh (from m))) \\/\n      exists i, deqR n i t /\\ loc (reqFn n i) = a /\\ desc (reqFn n i) = St.\n\n\n  Axiom deqImpNoSend: forall {c i t}, defined c -> deqR c i t -> \n                                      forall {m p}, defined p ->\n                                                    ~ mark mch c p (loc (reqFn c i)) t m.\nEnd LatestValueAxioms.\n\nModule LatestValueTheorems (dt: DataTypes) (ch: ChannelPerAddr dt) (c: BehaviorAxioms dt ch)\n       (l1: L1Axioms dt) (comp: CompatBehavior dt ch) (lv: LatestValueAxioms dt ch): L1Theorems dt.\n  Module mbt := mkBehaviorTheorems dt ch c.\n  Module cbt := mkCompat dt ch comp c.\n  Import dt ch c l1 comp lv mbt cbt.\n\n\n  Theorem uniqM:\n    forall {c a t}, defined c ->\n      leaf c ->\n      state c a t = Mo -> forall {co}, defined co -> leaf co -> c <> co -> state co a t = MsiState.In.\n  Proof.\n    intros c a t defC leaf_c cM co defCo leaf_co c_ne_co.\n    pose proof (noLeafsDesc leaf_c leaf_co c_ne_co) as desc1.\n    assert (co_ne_c: co <> c) by auto.\n    pose proof (noLeafsDesc leaf_co leaf_c co_ne_c) as desc2.\n    pose proof (@nonDescCompat c co defC defCo desc1 desc2 a t) as st.\n    rewrite cM in st.\n    unfold sle in *; destruct (state co a t); firstorder.\n  Qed.\n\n  Theorem parentLeafFalse: forall {c p}, leaf c -> parent p c -> False.\n  Proof.\n    intros c p leafC p_c.\n    unfold leaf in *; unfold parent in *.\n    destruct c.\n    destruct l0.\n    unfold List.In in *.\n    assumption.\n    assumption.\n  Qed.\n\n  Theorem leafGood: forall {p n a t}, defined p -> defined n -> parent n p ->\n                                      slt MsiState.In (dir p n a t) -> slt (state n a t) Mo ->\n                                      forall {c i}, \n                                        defined c ->\n                                        deqR c i t -> desc (reqFn c i) = St ->\n                                        loc (reqFn c i) = a -> False.\n  Proof.\n    unfold not; intros p n a t defP defN n_p pGtI nLtM c i defC deqSt isSt locA.\n    pose proof (deqLeaf deqSt) as leafC.\n    pose proof (processDeq deqSt) as st; simpl in st.\n    destruct (classic (descendent c p)) as [c_p | c_ne_p].\n    destruct (classic (descendent c n)) as [c_n | c_ne_n].\n    pose proof (@descSle c n defC defN c_n a t) as low.\n    rewrite isSt in st.\n    rewrite locA in st.\n    rewrite st in low.\n    apply (slt_slei_false nLtM low).\n    pose proof (clos_rt_rtn1 Tree parent c p c_p) as trans.\n    destruct trans.\n    apply (parentLeafFalse leafC n_p).\n    pose proof (clos_rtn1_rt Tree parent c y trans) as c_y.\n    pose proof (rt_step Tree parent y z H) as y_z.\n    pose proof (rt_trans Tree parent y z hier y_z defP) as defY.\n    clear trans y_z; fold descendent in *.\n    assert (y_ne_n: n = y -> False).\n    intros y_eq_n.\n    rewrite y_eq_n in *.\n    firstorder.\n    pose proof (compatible defP a t defY H) as [_ good].\n    specialize (good n defN y_ne_n n_p).\n    pose proof (@descSle c y defC defY c_y a t) as low.\n    rewrite isSt in st; rewrite locA in st.\n    rewrite st in low.\n    pose proof (conservative defP defY H a t) as stuff.\n    unfold sle in *; destruct (dir z y a t); destruct (dir z n a t); \n    destruct (state y a t); auto.\n    assert (sec: ~ descendent p c).\n    unfold not; intros p_c.\n    pose proof (clos_rt_rtn1 Tree parent p c p_c) as trans.\n    destruct trans.\n    firstorder.\n    apply (parentLeafFalse leafC H).\n    pose proof (@nonDescCompat c p defC defP c_ne_p sec a t) as contra.\n    rewrite isSt in st; rewrite locA in st.\n    rewrite st in contra.\n    pose proof (compatible defP a t defN n_p) as [good _].\n    destruct (dir p n a t); destruct (state p a t); unfold slt in *; unfold sle in *;\n    auto.\n  Qed.\n\n  Theorem leafGood2: forall {p n a t}, defined p -> defined n -> parent n p ->\n                                       forall {m}, mark mch p n a t m ->\n                                                   forall {c i}, \n                                                     defined c ->\n                                                     deqR c i t -> desc (reqFn c i) = St ->\n                                                     loc (reqFn c i) = a -> False.\n  Proof.\n    unfold not; intros p n a t defP defN n_p m markm c i defC deqSt isSt locA.\n    pose proof (pSendUpgrade defP defN n_p markm) as dir_n_lt_M.\n    pose proof (sendCCond defP defN n_p markm) as [st_hg othersCompat].\n    pose proof (sendmChange (dt defP defN n_p) markm) as rew.\n    rewrite <- rew in *; clear rew.\n    pose proof (deqLeaf deqSt) as leafC.\n    pose proof (processDeq deqSt) as st; simpl in st.\n    destruct (classic (descendent c p)) as [c_p | c_ne_p].\n    destruct (classic (descendent c n)) as [c_n | c_ne_n].\n    pose proof (@descSle c n defC defN c_n a t) as low.\n    pose proof (conservative defP defN n_p a t) as sth.\n    rewrite isSt in st; rewrite locA in st.\n    rewrite st in *.\n    destruct (state n a t); destruct (dir p n a t); destruct (dir p n a (S t));\n    unfold sle in *; unfold slt in *; auto.\n    pose proof (clos_rt_rtn1 Tree parent c p c_p) as trans.\n    destruct trans.\n    apply (parentLeafFalse leafC n_p).\n    pose proof (clos_rtn1_rt Tree parent c y trans) as c_y.\n    pose proof (rt_step Tree parent y z H) as y_z.\n    pose proof (rt_trans Tree parent y z hier y_z defP) as defY.\n    clear trans y_z; fold descendent in *.\n    assert (y_ne_n: y = n -> False).\n    intros y_eq_n.\n    rewrite y_eq_n in *.\n    firstorder.\n    specialize (othersCompat y defY y_ne_n H).\n    pose proof (@descSle c y defC defY c_y a t) as low.\n    pose proof (conservative defP defY H a t) as stuff.\n    rewrite isSt in st; rewrite locA in st.\n    rewrite st in *.\n    unfold sle in *; unfold slt in *; destruct (dir z n a (S t)); destruct (dir z n a t);\n    destruct (dir z y a t); destruct (state y a t); auto.\n    assert (sec: ~ descendent p c).\n    unfold not; intros p_c.\n    pose proof (clos_rt_rtn1 Tree parent p c p_c) as trans.\n    destruct trans.\n    firstorder.\n    apply (parentLeafFalse leafC H).\n    pose proof (@nonDescCompat c p defC defP c_ne_p sec a t) as contra.\n    rewrite isSt in st; rewrite locA in st.\n    rewrite st in contra.\n    unfold sle in *; unfold slt in *; destruct (dir p n a t); destruct (dir p n a (S t));\n    destruct (state p a t); auto.\n  Qed.\n\n  Theorem leafGood3: forall {p n a t}, defined p -> defined n -> parent n p ->\n                                       forall {m}, mark mch n p a t m ->\n                                                   forall {c i}, \n                                                     defined c ->\n                                                     deqR c i t -> desc (reqFn c i) = St ->\n                                                     loc (reqFn c i) = a -> False.\n  Proof.\n    unfold not; intros p n a t defP defN n_p m markm c i defC deqSt isSt locA.\n    destruct (classic (c = n)) as [eq|notEq].\n    rewrite eq in *.\n    rewrite <- locA in markm.\n    apply (deqImpNoSend defN deqSt defP markm).\n    destruct (classic (descendent c n)) as [c_n | c_no_n].\n    pose proof (@sendPCond n a t p defN defP n_p m markm) as dirLower.\n    pose proof (allDirLower defN dirLower notEq c_n) as condToM.\n    pose proof (cSendDowngrade defP defN n_p markm) as dgd.\n    pose proof (sendmChange (st defP defN n_p) markm) as stEq.\n    rewrite stEq in dgd.\n    pose proof (processDeq deqSt) as eqSth; simpl in *.\n    rewrite isSt in eqSth; rewrite locA in eqSth.\n    rewrite eqSth in *.\n    destruct (state n a t); destruct (to m); unfold slt in *; unfold sle in *; auto.\n    assert (n_no_c: ~ descendent n c).\n    unfold not; intros n_c.\n    pose proof (clos_rt_rtn1 Tree parent n c n_c) as trans.\n    destruct trans.\n    assert (n = n) by reflexivity; firstorder.\n    pose proof (deqLeaf deqSt) as leaf_z.\n    unfold parent in *; unfold leaf in *. destruct z. destruct l0.\n    unfold List.In in H. assumption.\n    assumption.\n    pose proof (@nonDescCompat n c defN defC n_no_c c_no_n a t) as stNow.\n    pose proof (cSendDowngrade defP defN n_p markm) as dgd.\n    pose proof (processDeq deqSt) as eqSth; simpl in *;\n    rewrite isSt in eqSth; rewrite locA in eqSth.\n    rewrite eqSth in *.\n    unfold sle in *; unfold slt in *; destruct (state n a t); destruct (state n a (S t));\n    auto.\n  Qed.\n\n  Theorem allLatestValue:\n    forall {a t n}, defined n ->\n                    sle Sh (state n a t) ->\n                    (forall {c}, defined c -> parent c n -> sle (dir n c a t) Sh) ->\n                    (data n a t = initData a /\\\n                     forall {ti}, 0 <= ti < t ->\n                                  forall {ci ii}, defined ci ->\n                                                  ~ (deqR ci ii ti /\\ loc (reqFn ci ii) = a /\\\n                                                     desc (reqFn ci ii) = St)) \\/\n    (exists cb ib tb, defined cb /\\ tb < t /\\ deqR cb ib tb /\\ desc (reqFn cb ib) = St /\\\n                      loc (reqFn cb ib) = a /\\\n                      data n a t = dataQ (reqFn cb ib) /\\\n                      forall {ti}, tb < ti < t ->\n                                   forall {ci ii},\n                                     defined ci ->\n                                     ~ (deqR ci ii ti /\\ loc (reqFn ci ii) = a /\\\n                                        desc (reqFn ci ii) = St)\n    ).\n    Proof.\n      intros a.\n      pose (fun t => forall n,\n              defined n ->\n                    sle Sh (state n a t) ->\n                    (forall {c}, defined c -> parent c n -> sle (dir n c a t) Sh) ->\n                    (data n a t = initData a /\\\n                     forall {ti}, 0 <= ti < t ->\n                                  forall {ci ii}, defined ci ->\n                                                  ~ (deqR ci ii ti /\\ loc (reqFn ci ii) = a /\\\n                                                     desc (reqFn ci ii) = St)) \\/\n    (exists cb ib tb, defined cb /\\ tb < t /\\ deqR cb ib tb /\\ desc (reqFn cb ib) = St /\\\n                      loc (reqFn cb ib) = a /\\\n                      data n a t = dataQ (reqFn cb ib) /\\\n                      forall {ti}, tb < ti < t ->\n                                   forall {ci ii},\n                                     defined ci ->\n                                     ~ (deqR ci ii ti /\\ loc (reqFn ci ii) = a /\\\n                                        desc (reqFn ci ii) = St)\n           )) as P.\n      pose proof (initLatest a) as [hierInit hierM].\n      apply (@ind P).\n      unfold P in *; clear P.\n      intros n defN stCond dirCond.\n      destruct (classic (n = hier)) as [eq|notEq].\n      rewrite eq.\n      rewrite hierInit.\n      constructor. constructor. reflexivity.\n      intros ti [_ bad].\n      assert (f: False) by omega.\n      firstorder.\n      pose proof (rt_refl Tree parent hier) as defHier.\n      pose proof (@initCompat hier) as dir0.\n      pose proof (clos_rt_rtn1 Tree parent n hier defN) as trans.\n      pose proof @conservative as cons.\n      pose proof @descSle as descSle.\n      unfold defined in *.\n      destruct trans.\n      firstorder.\n      pose proof (clos_rtn1_rt Tree parent n y trans) as n_y.\n      pose proof (rt_step Tree parent y z H) as defY.\n      clear dirCond trans; fold descendent in *.\n      specialize (dir0 y defHier defY H a).\n      pose proof (cons z y defHier defY H a 0) as sleUse.\n      pose proof @descSle n y defN defY n_y a 0 as contra.\n      rewrite dir0 in sleUse.\n      unfold sle in *; destruct (state n a 0); destruct (state y a 0); firstorder.\n\n      unfold P in *; clear P.\n      intros t SIHt n defN condSt condDir.\n\n      destruct (classic (sle Sh (state n a t) /\\\n                         forall c, defined c -> parent c n -> sle (dir n c a t) Sh))\n               as [[condSt' condDir']|prevNotLatest].\n\n      assert (triv: t <= t) by omega.\n      specialize (SIHt t triv n defN condSt' condDir'); clear triv.\n\n\n      assert (noneElse: forall co, defined co -> leaf co -> co <> n -> sle (state co a t) Sh).\n      intros co defCo leafco co_ne_n.\n      destruct (classic (descendent co n)) as [desc|noDesc].\n      apply (allDirLower defN condDir' co_ne_n desc).\n\n\n      assert (not_n_co: ~ descendent n co).\n      unfold not; intros n_co.\n      assert (no_co_parent: forall p, ~ parent p co) by\n          (unfold not; intros p p_co; unfold leaf in *; unfold parent in *;\n                                      unfold List.In in *; destruct co; destruct l0; auto).\n      pose proof (clos_rt_rtn1 Tree parent n co n_co) as trans.\n      destruct trans.\n      assert (n = n) by reflexivity; firstorder.\n      firstorder.\n\n      pose proof (@nonDescCompat n co defN defCo not_n_co noDesc a t) as condState.\n      destruct (state n a t); unfold sle in *; destruct (state co a t); auto.\n\n\n\n      assert (noStore: forall co, defined co ->\n                                  co <> n -> forall i,\n                                               ~ (deqR co i t /\\\n                                                  loc (reqFn co i) = a /\\\n                                                  desc (reqFn co i) = St\n             )).\n      unfold not; intros co defCo co_ne_n i [deqSt [locA isSt]].\n      pose proof (deqLeaf deqSt) as leafCo.\n      specialize (noneElse co defCo leafCo co_ne_n).\n      pose proof (processDeq deqSt) as use; simpl in use.\n      rewrite locA in use; rewrite isSt in use.\n      rewrite use in noneElse; unfold sle in *; auto.\n\n\n      destruct (classic (exists i, deqR n i t /\\ loc (reqFn n i) = a /\\\n               desc (reqFn n i) = St)) as [[i [deqSt [locA isSt]]] | noNStore].\n\n      pose proof (deqImpData defN deqSt) as st.\n      rewrite locA in st; rewrite isSt in st.\n      rewrite st.\n      assert (triv: t < S t) by omega.\n      assert (triv2: forall ti, t < ti < S t -> False) by (intros ti cond; omega).\n      right.\n      exists n; exists i; exists t.\n      generalize defN triv deqSt isSt locA st triv2; clear; firstorder.\n      reflexivity.\n\n\n      assert (good: forall c i, defined c ->\n                                ~ (deqR c i t /\\ loc (reqFn c i) = a /\\\n                                   desc (reqFn c i) = St)).\n      unfold not. intros c i defC [deqc [locA isSt]].\n      destruct (classic (c = n)) as [eq|notEq].\n      rewrite eq in *; generalize noNStore deqc locA isSt; clear; firstorder.\n      generalize noStore defC notEq deqc locA isSt; clear; firstorder.\n\n\n      destruct (classic (data n a (S t) = data n a t)) as [dataEq| dataNeq].\n      rewrite dataEq.\n\n      destruct SIHt as [[initi condInit]|[resti condResti]].\n      left.\n      constructor. assumption.\n      intros ti cond.\n      assert (cases: 0 <= ti < t \\/ ti = t) by omega.\n      destruct cases as [ind|rew].\n      specialize (condInit ti ind).\n      assumption.\n      rewrite rew.\n      assumption.\n\n      destruct condResti as [ib [tb [defCb [tb_lt_t [deqSt [isSt [locA [dEq rest]]]]]]]].\n      right.\n      exists resti; exists ib; exists tb.\n      constructor. assumption.\n      constructor.\n      omega.\n      constructor.\n      assumption.\n      constructor.\n      assumption.\n      constructor.\n      assumption.\n      constructor.\n      assumption.\n      intros ti cond.\n      assert (cases: tb < ti < t \\/ ti = t) by omega.\n      destruct cases as [ind|rew].\n      \n      apply (rest ti ind).\n      rewrite rew.\n      assumption.\n\n\n      pose proof (changeData defN dataNeq) as someChange.\n      destruct someChange as [[m [[p [defP [n_p [recvm mIn]]]] |\n                                  [c [defC [c_n [recvm mNotIn]]]]]] | bad].\n\n\n      pose proof (cRecvmCond defP defN n_p recvm) as currSt.\n      rewrite <- currSt in condSt'; rewrite mIn in condSt'.\n      unfold sle in condSt'; firstorder.\n\n      pose proof (recvmCond defN defC c_n recvm) as currSt.\n      specialize (condDir' c defC c_n).\n      rewrite currSt in mNotIn.\n      pose proof (slt_slei_false mNotIn condDir') as f.\n      firstorder.\n\n      generalize noNStore bad; clear; firstorder.\n\n      destruct (classic (state n a t = MsiState.In \\/ exists c, defined c /\\ parent c n /\\\n                                                       slt Sh (dir n c a t)))\n               as [hard | easy].\n      clear prevNotLatest.\n\n      destruct hard as [stIn | [c [defC [c_n dirM]]]].\n\n      assert (lt: slt (state n a t) (state n a (S t))) by\n          (rewrite stIn; unfold sle in *; unfold slt in *; destruct (state n a (S t));\n           auto).\n      assert (chnge: state n a (S t) <> state n a t) by\n          (destruct (state n a (S t)); destruct (state n a t); unfold slt in *;\n                                                               unfold sle in *;\n                                                               auto; discriminate).\n      destruct (classic (exists p, defined p /\\ parent n p)) as [[p [defP n_p]] | noP].\n      pose proof (change (st defP defN n_p) chnge) as [[m markm] | [m recvm]].\n      pose proof (cSendDowngrade defP defN n_p markm) as contra.\n      pose proof (slt_slti_false lt contra) as f.\n      firstorder.\n\n\n\n\n\n\n\n\n\n\n      pose proof (recvImpMark recvm) as [ts [ts_le_t markm]].\n      pose proof (@pSendNonI p n defP defN n_p m ts t a markm recvm) as pHigh.\n      pose proof (@cRecvNonM p n defP defN n_p m ts t a markm recvm) as cLow.\n      assert (cLow1: forall t0, ts < t0 <= t -> slt (state n a t0) Mo) by\n          ( intros t0 cond; assert (H: ts <= t0 <= t) by omega; apply (cLow t0 H)).\n      assert (cLow2: slt (state n a ts) Mo) by (assert (H: ts <= ts <= t) by omega;\n                                                apply (cLow ts H)).\n\n      assert (noDeq1: forall t0, ts < t0 <= t ->\n                                 forall c i, defined c -> ~ (deqR c i t0\n                                                            /\\ loc (reqFn c i) = a /\\\n                                                            desc (reqFn c i) = St)).\n      intros t0 cond.\n      specialize (pHigh t0 cond).\n      specialize (cLow1 t0 cond).\n      pose proof (@leafGood p n a t0 defP defN n_p pHigh cLow1) as H.\n      generalize H; clear; firstorder.\n\n      pose proof (@leafGood2 p n a ts defP defN n_p m markm) as noDeq2.\n\n      assert (goodT: forall t0, ts <= t0 <= t ->\n                                forall c i, defined c -> ~ (deqR c i t0 /\\\n                                                            loc (reqFn c i) = a /\\\n                                                            desc (reqFn c i) = St)).\n      intros t0 cond.\n      assert (H: ts < t0 <= t \\/ t0 = ts) by omega.\n      destruct H as [c1|c2].\n      apply (noDeq1 t0 c1).\n      rewrite c2 in *.\n      generalize noDeq2; clear; firstorder.\n\n\n      pose proof (cRecvmCond defP defN n_p recvm) as stEq.\n      rewrite <- stEq in stIn.\n      pose proof (fromParent defN defP n_p recvm stIn) as dataEq.\n      pose proof (toChild defN defP n_p markm stIn) as dataEq2.\n      rewrite <- dataEq in dataEq2.\n      rewrite dataEq2.\n\n      pose proof (sendCCond defP defN n_p markm) as [one two].\n      pose proof (pSendUpgrade defP defN n_p markm) as upg.\n      pose proof (sendmChange (dt defP defN n_p) markm) as ch.\n      rewrite ch in upg.\n      assert (p1: sle Sh (state p a ts)) by\n          ( unfold sle in *; unfold slt in *; destruct (to m); destruct (state p a ts);\n            destruct (dir p n a ts); auto).\n      assert (p2: forall c', defined c' -> parent c' p ->\n                         sle (dir p c' a ts) Sh).\n      intros c' defC' c'_p.\n\n\n      destruct (classic (c' = n)) as [eq|not].\n      pose proof (cRecvRespPrevState defP defN n_p recvm markm) as stDir.\n      rewrite <- stEq in stDir.\n      rewrite stIn in stDir.\n      rewrite eq.\n      rewrite <- stDir.\n      unfold sle; auto.\n\n      specialize (two c' defC' not c'_p).\n      unfold sle in *; unfold slt in *; destruct (to m); destruct (dir p n a ts);\n      destruct (dir p c' a ts); auto.\n\n      specialize (SIHt ts ts_le_t p defP p1 p2).\n      destruct (SIHt) as [[initi condInit] | [resti condRest]].\n      left.\n      constructor. assumption. \n\n      intros ti cond; assert (H: 0 <= ti < ts \\/ ts <= ti <= t ) by omega; \n      destruct H as [ind|tough].\n\n      apply (condInit ti ind).\n      apply (goodT ti tough).\n\n\n      right.\n      destruct condRest as [ib [tb [defCb [tb_lt_ts [deqSt [isSt [locA [dtEq rest]]]]]]]].\n      exists resti; exists ib; exists tb.\n      constructor. assumption. constructor.\n      assert (tb < S t) by omega. assumption.\n      constructor. assumption.\n      constructor. assumption.\n      constructor. assumption.\n      constructor. assumption.\n      intros ti cond; assert (H: tb < ti < ts \\/ ts <= ti <= t) by omega;\n      destruct H as [ind|tough].\n      apply (rest ti ind).\n      apply (goodT ti tough).\n\n\n\n\n\n\n\n\n\n      assert (contra: forall p, defined p -> ~ parent n p) by firstorder.\n      specialize (@noParentSame n a t defN contra).\n      firstorder.\n\n\n      specialize (condDir c defC c_n).\n\n      assert (gt: slt (dir n c a (S t)) (dir n c a t)) by\n          (unfold slt in *; unfold sle in *; destruct (dir n c a (S t));\n           destruct (dir n c a t); auto; discriminate).\n      assert (chnge: dir n c a (S t) <> dir n c a t) by\n          (destruct (dir n c a (S t)); destruct (dir n c a t); unfold slt in *;\n                                                               unfold sle in *;\n                                                               auto; discriminate).\n\n      pose proof (change (dt defN defC c_n) chnge) as [[m markm] | [m recvm]].\n      pose proof (pSendUpgrade defN defC c_n markm) as contra.\n      pose proof (slt_slti_false gt contra) as f.\n      firstorder.\n\n\n      pose proof (recvImpMark recvm) as [ts [ts_le_t markm]].\n      pose proof (@pRecvNonI n c defN defC c_n m ts t a markm recvm) as pHigh.\n      pose proof (@cSendNonM n c defN defC c_n m ts t a markm recvm) as cLow.\n      assert (pHigh1: forall t0, ts < t0 <= t -> slt MsiState.In (dir n c a t0)) by\n          ( intros t0 cond; assert (H: ts <= t0 <= t) by omega; apply (pHigh t0 H)).\n      assert (pHigh2: slt MsiState.In (dir n c a ts)) by (assert (H: ts <= ts <= t) by omega;\n                                                apply (pHigh ts H)).\n\n      assert (noDeq1: forall t0, ts < t0 <= t ->\n                                 forall c i, defined c -> ~ (deqR c i t0 /\\\n                                                             loc (reqFn c i) = a /\\\n                                                             desc (reqFn c i) = St)).\n      intros t0 cond.\n      specialize (cLow t0 cond).\n      specialize (pHigh1 t0 cond).\n      pose proof (@leafGood n c a t0 defN defC c_n pHigh1 cLow) as H.\n      generalize H; clear; firstorder.\n\n\n      pose proof (@leafGood3 n c a ts defN defC c_n m markm) as noDeq2.\n\n      assert (goodT: forall t0, ts <= t0 <= t ->\n                                forall c i, defined c -> ~ (deqR c i t0 /\\\n                                                            loc (reqFn c i) = a /\\\n                                                            desc (reqFn c i) = St)).\n      intros t0 cond.\n      assert (H: ts < t0 <= t \\/ t0 = ts) by omega.\n      destruct H as [c1|c2].\n      apply (noDeq1 t0 c1).\n      rewrite c2 in *.\n      generalize noDeq2; clear; firstorder.\n\n\n\n\n      pose proof (recvmCond defN defC c_n recvm) as stEq.\n      rewrite <- stEq in dirM.\n      pose proof (fromChild defN defC c_n recvm dirM) as dataEq.\n      pose proof (toParent defN defC c_n markm dirM) as dataEq2.\n      rewrite <- dataEq in dataEq2.\n      rewrite dataEq2.\n\n      pose proof (@sendPCond c a ts n defC defN c_n m markm) as sth.\n      pose proof (recvmChange (dt defN defC c_n) recvm) as ch.\n      rewrite ch in condDir.\n      pose proof (cSendDowngrade defN defC c_n markm) as dwn.\n\n\n      assert (p2: forall c0, defined c0 -> parent c0 c -> sle (dir c c0 a ts) Sh).\n      intros c0 defC0 c0_c; specialize (sth c0 defC0 c0_c);\n      destruct (to m); destruct (dir c c0 a ts); unfold sle in *; unfold slt in *;\n      auto.\n\n      assert (p1: sle Sh (state c a ts)) by\n          ( unfold sle in *; unfold slt in *; destruct (state c a (S ts));\n            destruct (state c a ts); auto).\n\n      specialize (SIHt ts ts_le_t c defC p1 p2).\n\n\n      destruct SIHt as [[initi condInit] | [resti condRest]].\n      left.\n      constructor. assumption.\n      intros ti cond; assert (H: 0 <= ti < ts \\/ ts <= ti <= t ) by omega; \n      destruct H as [ind|tough].\n\n      apply (condInit ti ind).\n      apply (goodT ti tough).\n\n      right.\n      destruct condRest as [ib [tb [defCb [tb_lt_ts [deqSt [isSt [locA [dtEq rest]]]]]]]].\n      exists resti; exists ib; exists tb.\n      constructor. assumption. constructor.\n      assert (tb < S t) by omega. assumption.\n      constructor. assumption.\n      constructor. assumption.\n      constructor. assumption.\n      constructor. assumption.\n      intros ti cond; assert (H: tb < ti < ts \\/ ts <= ti <= t) by omega;\n      destruct H as [ind|tough].\n      apply (rest ti ind).\n      apply (goodT ti tough).\n\n\n\n\n\n      assert (ex: forall c, defined c -> parent c n -> ~ slt Sh (dir n c a t)) by\n          firstorder.\n      assert (ex': forall c, defined c -> parent c n -> sle (dir n c a t) Sh) by\n          ( intros c defC c_n; unfold sle in *; specialize (ex c defC c_n);\n            unfold slt in *; destruct (dir n c a t); auto).\n      assert (ex2: state n a t <> MsiState.In) by firstorder.\n      assert (ex2': sle Sh (state n a t)) by (destruct (state n a t); unfold sle in *;\n                                                                      auto).\n      firstorder.\n\n    Qed.\n\n  Theorem latestValue:\n  forall {c a t},\n    defined c ->\n    leaf c ->\n    sle Sh (state c a t) ->\n    (data c a t = initData a /\\\n     forall {ti}, 0 <= ti < t -> forall {ci ii},\n                                   defined ci ->\n                                   ~ (deqR ci ii ti /\\ loc (reqFn ci ii) = a /\\\n                                      desc (reqFn ci ii) = St)) \\/\n    (exists cb ib tb, defined cb /\\ tb < t /\\ deqR cb ib tb /\\ desc (reqFn cb ib) = St /\\\n                      loc (reqFn cb ib) = a /\\\n                      data c a t = dataQ (reqFn cb ib) /\\\n                      forall {ti}, tb < ti < t ->\n                                   forall {ci ii},\n                                     defined ci ->\n                                     ~ (deqR ci ii ti /\\ loc (reqFn ci ii) = a /\\\n                                        desc (reqFn ci ii) = St)\n    ).\n  Proof.\n    intros c a t cDef leafC more.\n    assert (cond: forall {c'}, defined c' -> parent c' c -> sle (dir c c' a t) Sh).\n    intros c' defC' c'_c; unfold leaf in *; unfold parent in *.\n    destruct c.\n    destruct l0.\n    unfold List.In in *.\n    firstorder.\n    firstorder.\n    pose proof (allLatestValue cDef more cond) as useful.\n    assumption.\n  Qed.\n\nEnd LatestValueTheorems.\n", "meta": {"author": "vmurali", "repo": "CacheProof", "sha": "bf59c12575808dcec5abe0b67a81e042cd5b1bf5", "save_path": "github-repos/coq/vmurali-CacheProof", "path": "github-repos/coq/vmurali-CacheProof/CacheProof-bf59c12575808dcec5abe0b67a81e042cd5b1bf5/LatestValue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22532226845945535}}
{"text": "Require Import String.\nRequire Import Bool.\nRequire Import List.      (* sequence *)\nRequire Import Multiset.  (* bag *)\nRequire Import ListSet.   (* set *)\nRequire Import PeanoNat.\nRequire Import EqNat.\nRequire Import Coq.Logic.Eqdep_dec.\n\nRequire Import core.EqDec.\nRequire Import core.utils.Utils.\nRequire Import core.Metamodel.\nRequire Import core.modeling.ModelingMetamodel.\nRequire Import core.Model.\nRequire Import core.utils.CpdtTactics.\n(* Base types *)\n\nInductive Class : Set :=\n    BuildClass :\n      (* id *) nat ->\n      (* name *) string -> Class.\n\nInductive Attribute : Set :=\n    BuildAttribute :\n      (* id *) nat ->\n      (* derived *) bool ->\n      (* name *) string -> Attribute.\n\nInductive ClassAttributes : Set :=\n    BuildClassAttributes:\n      Class ->\n      list Attribute -> ClassAttributes.\n\nInductive AttributeType : Set :=\n    BuildAttributeType:\n      Attribute ->\n      Class -> AttributeType.\n\n(* Accessors *)\n\nDefinition getClassId (c : Class) : nat :=\n  match c with BuildClass id _ => id end.\n\nDefinition getClassName (c : Class) : string :=\n  match c with BuildClass _ n => n end.\n\nDefinition getAttributeId (a : Attribute) : nat :=\n  match a with BuildAttribute id _ _ => id end.\n\nDefinition getAttributeName (a : Attribute) : string :=\n  match a with BuildAttribute _ _ n => n end.\n\nDefinition getAttributeDerived (a : Attribute) : bool :=\n  match a with BuildAttribute _ n _ => n end.\n\nDefinition beq_Class (c1 : Class) (c2 : Class) : bool :=\n  beq_nat (getClassId c1) (getClassId c2) && beq_string (getClassName c1) (getClassName c2).\n\nDefinition beq_Attribute (a1 : Attribute) (a2 : Attribute) : bool :=\n  beq_nat (getAttributeId a1) (getAttributeId a2) && eqb (getAttributeDerived a1) (getAttributeDerived a2) && beq_string (getAttributeName a1) (getAttributeName a2).\n\nLemma lem_beq_Class_id:\n forall (a1 a2: Class),\n   beq_Class a1 a2 = true -> a1 = a2.\nProof.\nintros.\nunfold beq_Class in H.\nunfold \"&&\" in H.\ndestruct (getClassId a1 =? getClassId a2) eqn: ca1.\n- apply (lem_beq_string_eq2) in H.\n  apply (beq_nat_true) in ca1.\n  destruct a1,a2.\n  simpl in ca1, H.\n  rewrite ca1,H.\n  auto.\n- congruence.\nQed.\n\nLemma lem_beq_Attribute_id:\n forall (a1 a2: Attribute),\n   beq_Attribute a1 a2 = true -> a1 = a2.\nProof.\nintros.\nunfold beq_Attribute in H.\nunfold \"&&\" in H.\ndestruct (getAttributeId a1 =? getAttributeId a2) eqn: ca1.\n- destruct (eqb (getAttributeDerived a1) (getAttributeDerived a2)) eqn: ca2.\n  + apply (lem_beq_string_eq2) in H.\n    apply (beq_nat_true) in ca1.\n    apply (eqb_prop) in ca2.\n    destruct a1,a2.\n    simpl in ca1,ca2, H.\n    rewrite ca1,ca2,H.\n    auto.\n  + congruence. \n- congruence.\nQed.\n\n\n\n(* Meta-types *)\n\nInductive ClassMetamodel_Class : Set :=\n  ClassClass | AttributeClass.\n\nDefinition ClassMetamodel_getTypeByClass (type : ClassMetamodel_Class) : Set :=\n  match type with\n  | ClassClass => Class\n  | AttributeClass => Attribute\n  end.\n\nDefinition ClassMetamodel_getEAttributeTypesByClass (c: ClassMetamodel_Class): Set :=\n  match c with\n  | ClassClass => (nat * string)\n  | AttributeClass => (nat * bool * string)\n  end.\n\nInductive ClassMetamodel_Reference : Set :=\n  ClassAttributesReference | AttributeTypeReference.\n\nDefinition ClassMetamodel_getTypeByReference (type : ClassMetamodel_Reference) : Set :=\n  match type with\n  | ClassAttributesReference => ClassAttributes\n  | AttributeTypeReference => AttributeType\n  end.\n\nDefinition ClassMetamodel_getERoleTypesByReference (c: ClassMetamodel_Reference): Set :=\n  match c with\n  | ClassAttributesReference => (Class * list Attribute)\n  | AttributeTypeReference => (Attribute * Class)\n  end.\n\n(* Generic types *)\n\nInductive ClassMetamodel_Object : Set :=\n| ClassMetamodel_BuildObject : forall (c:ClassMetamodel_Class), (ClassMetamodel_getTypeByClass c) -> ClassMetamodel_Object.\n\nDefinition beq_ClassMetamodel_Object (c1 : ClassMetamodel_Object) (c2 : ClassMetamodel_Object) : bool :=\n  match c1, c2 with\n  | ClassMetamodel_BuildObject ClassClass o1, ClassMetamodel_BuildObject ClassClass o2 => beq_Class o1 o2\n  | ClassMetamodel_BuildObject AttributeClass o1, ClassMetamodel_BuildObject AttributeClass o2 => beq_Attribute o1 o2\n  | _, _ => false\n  end.\n\nInductive ClassMetamodel_Link : Set :=\n| ClassMetamodel_BuildLink : forall (c:ClassMetamodel_Reference), (ClassMetamodel_getTypeByReference c) -> ClassMetamodel_Link.\n\n\n(* Reflective functions *)\n\nLemma ClassMetamodel_eqClass_dec : forall (c1:ClassMetamodel_Class) (c2:ClassMetamodel_Class), { c1 = c2 } + { c1 <> c2 }.\nProof. repeat decide equality. Defined.\n\nLemma ClassMetamodel_eqReference_dec : forall (c1:ClassMetamodel_Reference) (c2:ClassMetamodel_Reference), { c1 = c2 } + { c1 <> c2 }.\nProof. repeat decide equality. Defined.\n\nDefinition ClassMetamodel_getClass (c : ClassMetamodel_Object) : ClassMetamodel_Class :=\n   match c with\n  | (ClassMetamodel_BuildObject c _) => c\n   end.\n\nDefinition ClassMetamodel_getReference (c : ClassMetamodel_Link) : ClassMetamodel_Reference :=\n   match c with\n  | (ClassMetamodel_BuildLink c _) => c\n   end.\n\nDefinition ClassMetamodel_instanceOfClass (cmc: ClassMetamodel_Class) (c : ClassMetamodel_Object): bool :=\n  if ClassMetamodel_eqClass_dec (ClassMetamodel_getClass c) cmc then true else false.\n\nDefinition ClassMetamodel_instanceOfReference (cmr: ClassMetamodel_Reference) (c : ClassMetamodel_Link): bool :=\n  if ClassMetamodel_eqReference_dec (ClassMetamodel_getReference c) cmr then true else false.\n\nDefinition ClassMetamodel_getObjectFromEAttributeValues (t : ClassMetamodel_Class) : (ClassMetamodel_getEAttributeTypesByClass t) -> ClassMetamodel_Object :=\n  match t with\n  | ClassClass => (fun (p: nat * string) => (ClassMetamodel_BuildObject ClassClass (BuildClass (fst p) (snd p))))\n  | AttributeClass => (fun (p: nat * bool * string) => (ClassMetamodel_BuildObject AttributeClass (BuildAttribute (fst (fst p)) (snd (fst p)) (snd p))))\n  end.\n\nDefinition ClassMetamodel_getLinkFromERoleValues (t : ClassMetamodel_Reference) : (ClassMetamodel_getERoleTypesByReference t) -> ClassMetamodel_Link :=\n  match t with\n  | ClassAttributesReference => (fun (p: Class * list Attribute) => (ClassMetamodel_BuildLink ClassAttributesReference (BuildClassAttributes (fst p) (snd p))))\n  | AttributeTypeReference => (fun (p: Attribute * Class) => (ClassMetamodel_BuildLink AttributeTypeReference (BuildAttributeType (fst p) (snd p))))\n  end.\n\nDefinition ClassMetamodel_toClass (t : ClassMetamodel_Class) (c : ClassMetamodel_Object) : option (ClassMetamodel_getTypeByClass t).\nProof.\n  destruct c.\n  destruct (ClassMetamodel_eqClass_dec c t).\n  - rewrite e in c0.\n    exact (Some c0).\n  - exact None.\nDefined.\n\n\n\n(*  \nmatch c with\n| ClassMetamodel_BuildObject c0 d =>\n    let s := ClassMetamodel_eqClass_dec c0 t in\n    match s with\n    | left e => match e with\n                     eq_refl => Some d\n               end\n    | right _ => None\n    end\n  end.\n  \n*)\n\nDefinition ClassMetamodel_toReference (t : ClassMetamodel_Reference) (c : ClassMetamodel_Link) : option (ClassMetamodel_getTypeByReference t).\nProof.\n  destruct c.\n  destruct (ClassMetamodel_eqReference_dec t c).\n  - rewrite <- e in c0.\n    exact (Some c0).\n  - exact None.\nDefined.\n\n(* Generic functions *)\n\nDefinition ClassMetamodel_toObjectFromClass (c :Class) : ClassMetamodel_Object :=\n  (ClassMetamodel_BuildObject ClassClass c).\n\nDefinition ClassMetamodel_toObjectFromAttribute (a :Attribute) : ClassMetamodel_Object :=\n  (ClassMetamodel_BuildObject AttributeClass a).\n\nDefinition ClassMetamodel_toObject (t: ClassMetamodel_Class) (e: ClassMetamodel_getTypeByClass t) : ClassMetamodel_Object :=\n  (ClassMetamodel_BuildObject t e).\n\nDefinition ClassMetamodel_toLink (t: ClassMetamodel_Reference) (e: ClassMetamodel_getTypeByReference t) : ClassMetamodel_Link :=\n  (ClassMetamodel_BuildLink t e).\n\nDefinition ClassMetamodel_getId (c : ClassMetamodel_Object) : nat :=\n  match c with\n  | (ClassMetamodel_BuildObject ClassClass c) => getClassId c\n  | (ClassMetamodel_BuildObject AttributeClass a) => getAttributeId a\n  end.\n\nDefinition ClassMetamodel_getName (c : ClassMetamodel_Object) : string :=\n  match c with\n  | (ClassMetamodel_BuildObject ClassClass c) => getClassName c\n  | (ClassMetamodel_BuildObject AttributeClass a) => getAttributeName a\n  end.\n\n(*Definition allClasses (m : ClassModel) : list Class :=\n  match m with BuildClassModel l _ => optionList2List (map (ClassMetamodel_toClass ClassClass) l) end.*)\n\n(*Theorem allClassesInModel :\n  forall (c : Class) (cm: ClassModel), (In c (allClasses cm)) -> (In (ClassMetamodel_BuildObject ClassClass c) (allClassModelElements cm)).\nProof.\n  intros.\n  destruct cm.\n  unfold allClassModelElements.\n  unfold allClasses in H.\n  apply all_optionList2List_in_list in H.\n  induction l.\n  - inversion H.\n  - simpl in H. simpl.\n    destruct H.\n    + unfold ClassMetamodel_toClass in H.\n      left.\n      destruct (ClassMetamodel_eqClass_dec (ClassMetamodel_getClass a) ClassClass).\n      * destruct a.\n        -- inversion H. reflexivity.\n        -- inversion H.\n      * inversion H.\n    + right.\n      apply IHl.\n      apply H.\nQed.*)\n  \n(*Definition allAttributes (m : ClassModel) : list Attribute :=\n  match m with BuildClassModel l _ => optionList2List (map (ClassMetamodel_toClass AttributeClass) l) end.*)\n\nFixpoint ClassMetamodel_getClassAttributesOnLinks (c : Class) (l : list ClassMetamodel_Link) : option (list Attribute) :=\n  match l with\n  | (ClassMetamodel_BuildLink ClassAttributesReference (BuildClassAttributes cl a)) :: l1 => if beq_Class cl c then Some a else ClassMetamodel_getClassAttributesOnLinks c l1\n  | _ :: l1 => ClassMetamodel_getClassAttributesOnLinks c l1\n  | nil => None\n  end.\n\nDefinition getClassAttributes (c : Class) (m : Model ClassMetamodel_Object ClassMetamodel_Link) : option (list Attribute) :=\n  ClassMetamodel_getClassAttributesOnLinks c (@allModelLinks _ _ m).\n\nDefinition getClassAttributesObjects (c : Class) (m : Model ClassMetamodel_Object ClassMetamodel_Link) : option (list ClassMetamodel_Object) :=\n  match getClassAttributes c m with\n  | Some l => Some (map ClassMetamodel_toObjectFromAttribute l)\n  | _ => None\n  end.\n\nFixpoint ClassMetamodel_getAttributeTypeOnLinks (a : Attribute) (l : list ClassMetamodel_Link) : option Class :=\n  match l with\n  | (ClassMetamodel_BuildLink AttributeTypeReference (BuildAttributeType att c)) :: l1 => if beq_Attribute att a then Some c else ClassMetamodel_getAttributeTypeOnLinks a l1\n  | _ :: l1 => ClassMetamodel_getAttributeTypeOnLinks a l1\n  | nil => None\n  end.\n\nDefinition getAttributeType (a : Attribute) (m : Model ClassMetamodel_Object ClassMetamodel_Link) : option Class :=\n  match m with\n    (Build_Model cs ls) => ClassMetamodel_getAttributeTypeOnLinks a ls\n  end.\n\nDefinition getAttributeTypeObject (a : Attribute) (m : Model ClassMetamodel_Object ClassMetamodel_Link) : option ClassMetamodel_Object :=\n  match getAttributeType a m with\n  | Some c => Some (ClassMetamodel_toObject ClassClass c)\n  | None => None\n  end.\n\nDefinition ClassMetamodel_defaultInstanceOfClass (c: ClassMetamodel_Class) : (ClassMetamodel_getTypeByClass c) :=\n  match c with\n  | ClassClass => (BuildClass 0 \"\")\n  | AttributeClass => (BuildAttribute 0 false \"\")\n  end.\n\n(* Typeclass Instance *)\n\n#[export]\nInstance ClassElementSum : Sum ClassMetamodel_Object ClassMetamodel_Class :=\n{\n  denoteSubType := ClassMetamodel_getTypeByClass;\n  toSubType := ClassMetamodel_toClass;\n  toSumType := ClassMetamodel_toObject;\n}.\n\n(* TODO *)\nDefinition beq_ClassMetamodel_Link (c1 : ClassMetamodel_Link) (c2 : ClassMetamodel_Link) : bool := true.\n\n#[export]\nInstance ClassLinkSum : Sum ClassMetamodel_Link ClassMetamodel_Reference :=\n{\n  denoteSubType := ClassMetamodel_getTypeByReference;\n  toSubType := ClassMetamodel_toReference;\n  toSumType := ClassMetamodel_toLink;\n}.\n\n#[export]\nInstance ClassMetamodel_EqDec : EqDec ClassMetamodel_Object := {\n    eq_b := beq_ClassMetamodel_Object;\n}.\n\n#[export]\nInstance ClassM : Metamodel :=\n{\n  ModelElement := ClassMetamodel_Object;\n  ModelLink := ClassMetamodel_Link;\n}.\n\n#[export]\nInstance ClassMetamodel : ModelingMetamodel ClassM :=\n{ \n    elements := ClassElementSum;\n    links := ClassLinkSum; \n}.\n\nDefinition ClassModel := Model ClassMetamodel_Object ClassMetamodel_Link.\n\n(* Useful lemmas *)\nLemma Class_invert : \n  forall (clec_arg: ClassMetamodel_Class) (t1 t2: ClassMetamodel_getTypeByClass clec_arg), ClassMetamodel_BuildObject clec_arg t1 = ClassMetamodel_BuildObject clec_arg t2 -> t1 = t2.\nProof.\n  intros.\n  inversion H.\n  apply inj_pair2_eq_dec in H1.\n  exact H1.\n  apply ClassMetamodel_eqClass_dec.\nQed.\n\nLemma Object_dec: \n  forall (a: ClassMetamodel_Object),\n    (ClassMetamodel_instanceOfClass ClassClass a) = true\n \\/ (ClassMetamodel_instanceOfClass AttributeClass a) = true.\nProof.\n  intros.\n  destruct a.\n  destruct c.\n  + left. crush.\n  + right. crush.\nQed.\n\nLemma Class_Object_cast:\n  forall a c,\n    ClassMetamodel_toClass ClassClass a = return c ->\n      ClassMetamodel_toObject ClassClass c = a.\nProof.\n  intros.\n  unfold ClassMetamodel_toClass in H.\n  destruct a.\n  unfold ClassMetamodel_instanceOfClass in H.\n  simpl in H.\n  destruct (ClassMetamodel_eqClass_dec c0 ClassClass); crush.\nQed.\n\nLemma Attribute_Object_cast:\n  forall a c,\n    ClassMetamodel_toClass AttributeClass a = return c ->\n      ClassMetamodel_toObject AttributeClass c = a.\nProof.\n  intros.\n  unfold ClassMetamodel_toClass in H.\n  destruct a.\n  unfold ClassMetamodel_instanceOfClass in H.\n  simpl in H.\n  destruct (ClassMetamodel_eqClass_dec c0 AttributeClass); crush.\nQed.\n\nLemma Class_dec :\n  forall x y : Class, {x = y} + {x <> y}.\nProof.\n  decide equality.\n  - apply String.string_dec.\n  - apply Nat.eq_dec.\nQed.\n\nLemma Attribute_dec :\n  forall x y : Attribute, {x = y} + {x <> y}.\nProof.\n  decide equality.\n  - apply String.string_dec.\n  - apply Bool.bool_dec.\n  - apply Nat.eq_dec.\nQed.\n\nLemma eq_dec : forall (x y : ClassMetamodel_Object), {x = y} + {x <> y}.\n  intros.\n  destruct x as [[] x], y as [[] y]; try (right; discriminate).\n  - destruct (Class_dec x y) as [H | H].\n    + left. congruence.\n    + right. contradict H.\n      inversion H.\n      apply Eqdep.EqdepTheory.inj_pair2 in H1.\n      assumption.\n  - destruct (Attribute_dec x y) as [H | H].\n    + left. congruence.\n    + right. contradict H.\n      inversion H.\n      apply Eqdep.EqdepTheory.inj_pair2 in H1.\n      assumption.\nQed.\n", "meta": {"author": "atlanmod", "repo": "coqtl", "sha": "5daf5d915b66328ae5ec48f55c44731372563c87", "save_path": "github-repos/coq/atlanmod-coqtl", "path": "github-repos/coq/atlanmod-coqtl/coqtl-5daf5d915b66328ae5ec48f55c44731372563c87/transformations/Class2Relational/ClassMetamodel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.22532226845945535}}
{"text": "From iris.base_logic.lib Require Import ghost_map.\nFrom iris Require Import program_logic.weakestpre.\nFrom iris.proofmode Require Import tactics.\nFrom st.STLCmuVS Require Import lang wkpre generic.lift contexts scopedness.\nFrom st.STLCmu Require Import types.\nFrom st.prelude Require Import big_op_three.\nFrom st Require Import resources.\n\nCanonical Structure typeO := leibnizO type.\n\nSection definition.\n\n  Context `{Σ : !gFunctors} `{semΣ_inst : !semΣ Σ}.\n\n  (* We define a stuckness-sensistive and insensitive one *)\n  Context (s : stuckness).\n\n  Fixpoint valrel_typed_gen_pre (Ψ : typeO -n> valO -n> valO -n> iPropO Σ) (τ : typeO) : valO -n> valO -n> iPropO Σ := λne v v',\n    (match τ with\n     | TUnit => ⌜ v = (()%Vₙₒ : valO) ⌝ ∧ ⌜ v' = (()%Vₙₒ : valO) ⌝\n     | TBool => ∃ b : bool, ⌜ v = b ⌝ ∧ ⌜ v' = b ⌝\n     | TInt => ∃ z : Z, ⌜ v = z ⌝ ∧ ⌜ v' = z ⌝\n     | TProd τ1 τ2 => ∃ v1 v2 v1' v2', ⌜ v = (v1, v2)%Vₙₒ ⌝ ∧ ⌜ v' = (v1' , v2')%Vₙₒ ⌝ ∗ valrel_typed_gen_pre Ψ τ1 v1 v1' ∗ valrel_typed_gen_pre Ψ τ2 v2 v2'\n     | TSum τ1 τ2 => ∃ vi vi', (⌜ v = InjLV vi ⌝ ∧ ⌜ v' = InjLV vi' ⌝ ∧ valrel_typed_gen_pre Ψ τ1 vi vi') ∨\n                              (⌜ v = InjRV vi ⌝ ∧ ⌜ v' = InjRV vi' ⌝ ∧ valrel_typed_gen_pre Ψ τ2 vi vi')\n     | TArrow τ1 τ2 => □ (∀ w w', valrel_typed_gen_pre Ψ τ1 w w' -∗ lift s (valrel_typed_gen_pre Ψ τ2) (v w) (v' w'))\n     | TRec τ => ∃ w w', ⌜ v = FoldV w ⌝ ∧ ⌜ v' = FoldV w' ⌝ ∧ ▷ (Ψ τ.[TRec τ/] w w')\n     | TVar X => False\n     end)%I.\n\n  Definition valrel_typed_gen (Ψ : typeO -n> valO -n> valO -n> iPropO Σ) : typeO -n> valO -n> valO -n> iPropO Σ := λne τ v v', valrel_typed_gen_pre Ψ τ v v'.\n\n  Instance valrel_typed_gen_contractive : Contractive valrel_typed_gen.\n  Proof.\n    intros n P1 P2 dl. rewrite /valrel_typed_gen. intro τ. simpl.\n    induction τ; try by solve_contractive.\n    - intros v v'. simpl. do 6 f_equiv. specialize (IHτ1 a a0). simpl in IHτ1. by rewrite IHτ1.\n      rewrite /lift. do 5 f_equiv. specialize (IHτ2 a1 a2). simpl in IHτ2. by rewrite IHτ2.\n  Qed.\n\n  Definition valrel_typed := fixpoint valrel_typed_gen.\n\n  Lemma valrel_typed_unfold τ v1 v2 : valrel_typed τ v1 v2 ≡ valrel_typed_gen (fixpoint valrel_typed_gen) τ v1 v2.\n  Proof. do 3 f_equiv. by rewrite -fixpoint_unfold. Qed.\n  Lemma valrel_typed_unfold' τ : valrel_typed τ ≡ valrel_typed_gen (fixpoint valrel_typed_gen) τ.\n  Proof. intros x x'. by rewrite valrel_typed_unfold. Qed.\n  Lemma valrel_typed_unfold'' : valrel_typed ≡ valrel_typed_gen (fixpoint valrel_typed_gen).\n  Proof. intros x. by rewrite valrel_typed_unfold'. Qed.\n  Lemma valrel_typed_gen_pre_gen Ψ τ v v' : valrel_typed_gen_pre Ψ τ v v' ≡ valrel_typed_gen Ψ τ v v'.\n  Proof. auto. Qed.\n  Lemma valrel_typed_gen_pre_gen' Ψ τ : valrel_typed_gen_pre Ψ τ ≡ valrel_typed_gen Ψ τ.\n  Proof. intro. intro. auto. Qed.\n\n  Lemma valrel_typed_TUnit_unfold v v' : valrel_typed TUnit v v' ≡ (⌜ v = (()%Vₙₒ : valO) ⌝ ∧ ⌜ v' = (()%Vₙₒ : valO) ⌝)%I.\n  Proof. by rewrite valrel_typed_unfold. Qed.\n  Lemma valrel_typed_TBool_unfold v v' : valrel_typed TBool v v' ≡ (∃ b : bool, ⌜ v = b ⌝ ∧ ⌜ v' = b ⌝)%I.\n  Proof. by rewrite valrel_typed_unfold. Qed.\n  Lemma valrel_typed_TInt_unfold v v' : valrel_typed TInt v v' ≡ (∃ z : Z, ⌜ v = z ⌝ ∧ ⌜ v' = z ⌝)%I.\n  Proof. by rewrite valrel_typed_unfold. Qed.\n  Lemma valrel_typed_TArrow_unfold τ1 τ2 v v' : valrel_typed (TArrow τ1 τ2) v v' ≡ (□ (∀ w w', valrel_typed τ1 w w' -∗ lift s (valrel_typed τ2) (v w) (v' w')))%I.\n  Proof.\n    rewrite valrel_typed_unfold. rewrite /valrel_typed_gen. simpl.\n    f_equiv. f_equiv. intros w. f_equiv. intro w'. f_equiv.\n    - rewrite valrel_typed_gen_pre_gen. unfold valrel_typed. rewrite -valrel_typed_unfold. auto.\n    - rewrite /lift. f_equiv. simpl. f_equiv. f_equiv. f_equiv. f_equiv.\n      by rewrite valrel_typed_unfold.\n  Qed.\n  Lemma valrel_typed_TSum_unfold τ1 τ2 v v' : valrel_typed (TSum τ1 τ2) v v' ≡ (∃ vi vi', (⌜ v = InjLV vi ⌝ ∧ ⌜ v' = InjLV vi' ⌝ ∧ valrel_typed τ1 vi vi') ∨ (⌜ v = InjRV vi ⌝ ∧ ⌜ v' = InjRV vi' ⌝ ∧ valrel_typed τ2 vi vi'))%I.\n  Proof. rewrite valrel_typed_unfold. simpl. repeat f_equiv; rewrite valrel_typed_gen_pre_gen'; rewrite -valrel_typed_unfold'; auto. Qed.\n  Lemma valrel_typed_TProd_unfold τ1 τ2 v v' : valrel_typed (TProd τ1 τ2) v v' ≡ (∃ v1 v2 v1' v2', ⌜ v = (v1, v2)%Vₙₒ ⌝ ∧ ⌜ v' = (v1' , v2')%Vₙₒ ⌝ ∗ valrel_typed τ1 v1 v1' ∗ valrel_typed τ2 v2 v2')%I.\n  Proof. rewrite valrel_typed_unfold. simpl. repeat f_equiv; rewrite valrel_typed_gen_pre_gen'; rewrite -valrel_typed_unfold'; auto. Qed.\n  Lemma valrel_typed_TRec_unfold τ v v' : valrel_typed (TRec τ) v v' ≡ (∃ w w', ⌜ v = FoldV w ⌝ ∧ ⌜ v' = FoldV w' ⌝ ∧ ▷ (valrel_typed τ.[TRec τ/] w w'))%I.\n  Proof. rewrite valrel_typed_unfold. simpl. repeat f_equiv. auto. Qed.\n  Lemma valrel_typed_TVar_unfold X v v' : valrel_typed (TVar X) v v' ≡ False%I.\n  Proof. rewrite valrel_typed_unfold. by simpl. Qed.\n\n  Ltac simpl_valrel_typed := fold (valrel_typed_gen_pre); repeat rewrite valrel_typed_gen_pre_gen -valrel_typed_unfold; fold (valrel_typed).\n\n  Global Instance valrel_typed_persistent τ v v' : Persistent (valrel_typed τ v v').\n  Proof.\n    rewrite /Persistent. revert τ v v'. iLöb as \"IHlob\". iIntros (τ).\n    iInduction τ as [ | | | τ1 τ2 | τ1 τ2 | τ1 τ2 | τ1 τ2 | τ ] \"IH\";\n      iIntros (v v'); rewrite valrel_typed_unfold; try by iIntros \"#H\".\n    - iIntros \"H\". iDestruct \"H\" as (v1 v2 v1' v2') \"(-> & -> & H1 & H2)\". simpl_valrel_typed.\n      iExists v1, v2, v1', v2'. simpl_valrel_typed. repeat iSplit; auto. iApply (\"IH\" with \"H1\"). iApply (\"IH1\" with \"H2\").\n    - simpl_valrel_typed. iIntros \"H\". iDestruct \"H\" as (vi vi') \"[(-> & -> & H1) | (-> & -> & H2)]\"; iExists vi, vi'; simpl_valrel_typed.\n      + iLeft. repeat iSplit; auto. by iApply (\"IH\" with \"H1\").\n      + iRight. repeat iSplit; auto. by iApply (\"IH1\" with \"H2\").\n    - iIntros \"H\". iDestruct \"H\" as (w w') \"(-> & -> & H)\". simpl_valrel_typed. iExists w, w'. repeat iSplitL \"\"; auto.\n      iApply bi.later_persistently_1. iNext. by iApply \"IHlob\".\n  Qed.\n\n  Definition exprel_typed : typeO -n> exprO -n> exprO -n> iPropO Σ := λne τ eᵢ eₛ, lift s (valrel_typed τ) eᵢ eₛ.\n\n  Definition open_exprel_typed (Γ : list type) (e e' : expr) (τ : type) :=\n    ∀ (vs vs' : list val), big_sepL3 (fun τ v v' => valrel_typed τ v v') Γ vs vs' ⊢\n                                     exprel_typed τ e.[subst_list_val vs] e'.[subst_list_val vs'].\n\n  Lemma open_exprel_typed_nil τ e e' : (⊢ exprel_typed τ e e') -> open_exprel_typed [] e e' τ.\n  Proof. iIntros (Hee' vs vs') \"Hvv'\". destruct vs, vs'; auto. asimpl. iApply Hee'. Qed.\n\n  Lemma open_exprel_typed_nil' τ e e' : open_exprel_typed [] e e' τ → (⊢ exprel_typed τ e e').\n  Proof. rewrite /open_exprel_typed. iIntros (Hee'). iDestruct (Hee' [] []) as \"H\". asimpl. by iApply \"H\". Qed.\n\n  Definition ctx_item_rel_typed (Ci Ci' : ctx_item) Γ τ Γ' τ' :=\n    ∀ e e' (pe : expr_scoped (length Γ) e) (pe' : expr_scoped (length Γ) e'), open_exprel_typed Γ e e' τ → open_exprel_typed Γ' (fill_ctx_item Ci e) (fill_ctx_item Ci' e') τ'.\n\n  Definition ctx_rel_typed (C C' : ctx) Γ τ Γ' τ' :=\n    ∀ e e' (pe : expr_scoped (length Γ) e) (pe' : expr_scoped (length Γ) e'), open_exprel_typed Γ e e' τ → open_exprel_typed Γ' (fill_ctx C e) (fill_ctx C' e') τ'.\n\nEnd definition.\n\nLtac unfold_valrel_typed :=\n  (rewrite valrel_typed_TUnit_unfold) ||\n  (rewrite valrel_typed_TBool_unfold) ||\n  (rewrite valrel_typed_TInt_unfold) ||\n  (rewrite valrel_typed_TArrow_unfold) ||\n  (rewrite valrel_typed_TSum_unfold) ||\n  (rewrite valrel_typed_TProd_unfold) ||\n  (rewrite valrel_typed_TRec_unfold).\n\nLtac simpl_valrel_typed := fold (valrel_typed_gen_pre); repeat rewrite valrel_typed_gen_pre_gen -valrel_typed_unfold; fold (valrel_typed).\n", "meta": {"author": "scaup", "repo": "sem_backs_st", "sha": "e14aa7f421de94df5c1369d2b4b44d8644243cec", "save_path": "github-repos/coq/scaup-sem_backs_st", "path": "github-repos/coq/scaup-sem_backs_st/sem_backs_st-e14aa7f421de94df5c1369d2b4b44d8644243cec/theories/STLCmuVS/logrel/definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22532226252767476}}
{"text": "From cap_machine Require Export rules_Jmp rules_binary_base.\nFrom iris.base_logic Require Export invariants gen_heap.\nFrom iris.program_logic Require Export weakestpre ectx_lifting.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import frac.\n\n\nSection cap_lang_spec_rules.\n  Context `{cfgSG Σ, MachineParameters, invG Σ}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types σ : cap_lang.state.\n  Implicit Types a b : Addr.\n  Implicit Types r : RegName.\n  Implicit Types w : Word.\n  Implicit Types reg : gmap RegName Word.\n  Implicit Types ms : gmap Addr Word.\n\n  Lemma step_jmp_success E K pc_p pc_g pc_b pc_e pc_a w r w' :\n    decodeInstrW w = Jmp r →\n    isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) →\n    nclose specN ⊆ E →\n\n    spec_ctx ∗ ⤇ fill K (Instr Executable)\n             ∗ ▷ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a)\n             ∗ ▷ pc_a ↣ₐ w\n             ∗ ▷ r ↣ᵣ w'\n    ={E}=∗ ⤇ fill K (Instr NextI)\n        ∗ PC ↣ᵣ updatePcPerm w'\n        ∗ pc_a ↣ₐ w\n        ∗ r ↣ᵣ w'.\n  Proof.\n    iIntros (Hinstr Hvpc Hnclose) \"(Hinv & Hj & >HPC & >Hpc_a & >Hr)\".\n    iDestruct \"Hinv\" as (ρ) \"Hinv\". rewrite /spec_inv.\n    iInv specN as \">Hinv'\" \"Hclose\". iDestruct \"Hinv'\" as (e [σr σm]) \"[Hown %] /=\".\n    iDestruct (@spec_heap_valid with \"[$Hown $Hpc_a]\") as %?; auto.\n    iDestruct (@spec_regs_valid with \"[$Hown $HPC]\") as %?.\n    iDestruct (@spec_regs_valid with \"[$Hown $Hr]\") as %Hr_r0.\n    iDestruct (spec_expr_valid with \"[$Hown $Hj]\") as %Heq; subst e.\n    specialize (normal_always_step (σr,σm)) as [c [ σ2 Hstep]].\n    eapply step_exec_inv in Hstep; eauto.\n\n    assert (Hstep':=Hstep). \n    rewrite /update_reg /= in Hstep. simplify_pair_eq. cbn.\n    assert ((c, σ2) = (NextI, (<[PC:=updatePcPerm w']> σr, σm))) as Heq.\n    { inversion Hstep'; simpl in *; simplify_map_eq_alt. rewrite /RegLocate Hr_r0; auto. }\n    simplify_eq.\n    iMod (@regspec_mapsto_update with \"Hown HPC\") as \"[Hown HPC]\". \n    iMod (exprspec_mapsto_update _ _ (fill K (Instr NextI)) with \"Hown Hj\") as \"[Hown Hj]\".\n    iFrame.\n    iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n    { iNext. iExists _,_;iFrame. iPureIntro. eapply rtc_r;eauto. \n      exists [];eapply step_atomic with (t1:=[]) (t2:=[]);eauto. \n      econstructor;eauto;constructor. simpl.\n      eapply step_exec_instr with (c:=(NextI, (<[PC:=updatePcPerm w']> σr, σm)));\n        rewrite /RegLocate /MemLocate;[simplify_map_eq..|];eauto. \n    }\n    done. \n  Qed.\n\n  Lemma step_jmp_successPC E K pc_p pc_g pc_b pc_e pc_a w :\n    decodeInstrW w = Jmp PC →\n    isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) →\n    nclose specN ⊆ E →\n\n    spec_ctx ∗ ⤇ fill K (Instr Executable)\n             ∗ ▷ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a)\n             ∗ ▷ pc_a ↣ₐ w\n    ={E}=∗  ⤇ fill K (Instr NextI)\n        ∗ PC ↣ᵣ updatePcPerm (inr (pc_p,pc_g,pc_b,pc_e,pc_a))\n        ∗ pc_a ↣ₐ w.\n  Proof.\n    iIntros (Hinstr Hvpc Hnclose) \"(Hinv & Hj & >HPC & >Hpc_a)\".\n    iDestruct \"Hinv\" as (ρ) \"Hinv\". rewrite /spec_inv.\n    iInv specN as \">Hinv'\" \"Hclose\". iDestruct \"Hinv'\" as (e [σr σm]) \"[Hown %] /=\".\n    iDestruct (@spec_heap_valid with \"[$Hown $Hpc_a]\") as %?; auto.\n    iDestruct (@spec_regs_valid with \"[$Hown $HPC]\") as %?.\n    iDestruct (spec_expr_valid with \"[$Hown $Hj]\") as %Heq; subst e.\n    specialize (normal_always_step (σr,σm)) as [c [ σ2 Hstep]].\n    eapply step_exec_inv in Hstep; eauto. assert (Hstep':=Hstep). \n\n    rewrite /update_reg /= in Hstep. simplify_pair_eq. cbn.\n    assert ((c, σ2) = (NextI, (<[PC:=updatePcPerm (inr (pc_p,pc_g, pc_b, pc_e, pc_a))]> σr, σm))) as Heq.\n    { inversion Hstep'; simpl in *; simplify_map_eq_alt. rewrite /RegLocate H4; auto. }\n    simplify_eq.\n    iMod (@regspec_mapsto_update with \"Hown HPC\") as \"[Hown HPC]\". \n    iMod (exprspec_mapsto_update _ _ (fill K (Instr NextI)) with \"Hown Hj\") as \"[Hown Hj]\".\n    iFrame.\n    iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n    { iNext. iExists _,_;iFrame. iPureIntro. eapply rtc_r;eauto. \n      exists [];eapply step_atomic with (t1:=[]) (t2:=[]);eauto. \n      econstructor;eauto;constructor. simpl.\n      eapply step_exec_instr with (c:=(NextI, (<[PC:=updatePcPerm (inr (pc_p,pc_g, pc_b, pc_e, pc_a))]> σr, σm)));\n        rewrite /RegLocate /MemLocate;[simplify_map_eq..|];eauto. \n    }\n    done. \n  Qed.\n\nEnd cap_lang_spec_rules. \n", "meta": {"author": "logsem", "repo": "cerise-stack-monotone", "sha": "dff1909f6abc6de99c28d8f12e903b98dd76fb41", "save_path": "github-repos/coq/logsem-cerise-stack-monotone", "path": "github-repos/coq/logsem-cerise-stack-monotone/cerise-stack-monotone-dff1909f6abc6de99c28d8f12e903b98dd76fb41/theories/binary_model/rules_binary/rules_binary_Jmp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22523334961371688}}
{"text": "(*\n * Copyright (c) 2017-present,\n * Programming Research Laboratory (ROPAS), Seoul National University, Korea\n * This software is distributed under the term of the BSD-3 clause license.\n *)\n(** * Extends relation for analysis result *)\n\nSet Implicit Arguments.\n\nRequire Import hpattern vgtac.\nRequire Import UserProofType Syn Global.\nRequire Import SemCommon.\nRequire ExtMem.\nRequire DomInsen.\n\nModule Make (Import PInput : PINPUT).\n\nLocal Open Scope type.\n\nModule Insen := DomInsen.Make PInput.\n\nInclude ExtMem.Make PInput.\n\nDefinition state_find (mempos : mem_pos) (node : InterNode.t)\n           (s : Table.t Mem.t * Table.t Mem.t) : Mem.t :=\n  let t := match mempos with\n             | Inputof => fst s\n             | Outputof => snd s\n           end in\n  table_find node t.\n\nDefinition extends (g : G.t) (s : Table.t Mem.t)\n           (insenl_s : Insen.state_t) : Prop :=\n  forall cfg f n cmd insenl_m\n         (Hcfg: InterCfg.PidMap.MapsTo f cfg (InterCfg.cfgs (G.icfg g)))\n         (Hcmd: IntraCfg.NodeMap.MapsTo n cmd (IntraCfg.cmds cfg))\n         (Hidx_m : insenl_s ((f, n), Inputof) = insenl_m),\n    let mode := UserInputType.Strong in\n    let '(m', acc_n) :=\n        run_access mode g (f, n) cmd (table_find (f, n) s) in\n    let uses_n := Acc.useof acc_n in\n    extends_mem uses_n (table_find (f, n) s) insenl_m.\n\nDefinition extends' (g : G.t)\n           (s1 : Table.t Mem.t) (s2 : Table.t Mem.t * Table.t Mem.t) : Prop :=\n  forall cfg f n cmd\n         (Hcfg: InterCfg.PidMap.MapsTo f cfg (InterCfg.cfgs (G.icfg g)))\n         (Hcmd: IntraCfg.NodeMap.MapsTo n cmd (IntraCfg.cmds cfg)),\n    let mode := UserInputType.Strong in\n    let '(m', acc_n) :=\n        run_access mode g (f, n) cmd (table_find (f, n) s1) in\n    let uses_n1 := Acc.useof acc_n in\n    extends_mem uses_n1 (table_find (f, n) s1)\n                (state_find Inputof (f, n) s2).\n\nDefinition extends'' (g : G.t)\n           (s : Table.t Mem.t * Table.t Mem.t)\n           (insenl_s : Insen.state_t) : Prop :=\n  forall n mpos, Mem.eq (state_find mpos n s) (insenl_s (n, mpos)).\n\nLemma extends_trans :\n  forall (g : G.t) x y z\n     (He1: extends' g x y) (He2: extends'' g y z),\n    extends g x z.\nProof.\nunfold extends', extends, extends_mem; i.\nspecialize He1 with cfg f n cmd. \nremember (run_access UserInputType.Strong g (f, n) cmd (table_find (f, n) x))\nas x1.\ndestruct x1 as [v1 acc1]. i.\neapply Val.eq_trans with (Mem.find k (state_find Inputof (f, n) y)).\n- by apply He1.\n- rewrite <- Hidx_m. by apply He2.\nQed.\n\nLocal Close Scope type.\n\nEnd Make.\n", "meta": {"author": "ropas", "repo": "zooberry", "sha": "17b1cb1a44c2a796d6b7d85c2026b142685d291b", "save_path": "github-repos/coq/ropas-zooberry", "path": "github-repos/coq/ropas-zooberry/zooberry-17b1cb1a44c2a796d6b7d85c2026b142685d291b/spec/Proof/ExtFin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2252125455738736}}
{"text": "Require Import Coq.Strings.String.\n\nFrom mathcomp Require Import\n  ssreflect ssrfun ssrbool ssrnat eqtype choice seq ssrnum ssrint ssralg bigop.\nFrom deriving Require Import deriving.\nFrom extructures Require Import ord fset fmap ffun fperm.\n\nFrom CoqUtils Require Import nominal.\n\nFrom memsafe Require Import basic.\n\nFrom memsafe Require structured.\n\nModule str := structured.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection Properties.\n\nLocal Open Scope fset_scope.\nLocal Open Scope state_scope.\n\nLocal Notation locals := {fmap string -> value}.\nLocal Notation heap := {fmap ptr -> value}.\nLocal Notation state := (locals * heap)%type.\n\nImplicit Type (e : expr) (c : com) (ls : locals) (h : heap)\n              (s : state) (π : {fperm name}) (v : value).\n\nDefinition vars_s s := domm s.1.\n\nDefinition objs s := names (domm s.2).\n\nInstance vars_s_eqvar : {eqvar vars_s}.\nProof. by rewrite /vars_s; finsupp. Qed.\n\nInstance objs_eqvar : {eqvar objs}.\nProof. by rewrite /objs; finsupp. Qed.\n\nLemma objs_names s : fsubset (objs s) (names s).\nProof. eapply nom_finsuppP; finsupp. Qed.\n\nLemma objsU s1 s2 : objs (s1 ∪ s2) = objs s1 :|: objs s2.\nProof.\ncase: s1 s2=> /= [ls1 h1] [ls2 h2].\nby rewrite /stateu /objs /= domm_union namesfsU.\nQed.\n\nLemma names_stateu s1 s2 :\n  fdisjoint (vars_s s1) (vars_s s2) ->\n  fdisjoint (objs s1) (objs s2) ->\n  names (s1 ∪ s2) = names s1 :|: names s2.\nProof.\ncase: s1 s2 => /= [ls1 h1] [ls2 h2].\nrewrite /vars_s /objs /stateu !namespE /= => dis_v dis_o.\nrewrite namesm_union_disjoint // namesm_union_disjoint.\n  rewrite 2!fsetUA; congr fsetU.\n  by rewrite -2!fsetUA [_ :|: names h1]fsetUC.\nby apply: fdisjoint_names_domm.\nQed.\n\nLemma vars_sE A s : vars_s s = expose (mapr fset0 vars_s (hide A (Restr s))).\nProof. by rewrite /vars_s maprE ?fdisjoint0s ?exposeE. Qed.\n\nLemma renaming π s c k :\n  exists π',\n    eval_com true c (rename π s) k =\n    rename π' (eval_com true c s k).\nProof.\nhave [A1 eA1] := str.eval_basic_restr c s k.\nhave [A2 eA2] := str.eval_basic_restr c (rename π s) k.\nmove: eA2; rewrite -str.eval_com_eqvar {}eA1.\ncase: eval_com => [s1'| |]; case: eval_com => //;\ntry by exists 1%fperm; rewrite rename1.\nmove=> s2' []; rewrite hide_eqvar Restr_eqvar  => /restr_eqP /= [π' _ [_ <-]].\nby exists (π' * π)%fperm; rewrite renameA.\nQed.\n\nTheorem frame_ok s1 s1' s2 c k :\n  fsubset (vars_c c) (vars_s s1) ->\n  fdisjoint (vars_s s1) (vars_s s2) -> (* This should not be necessary *)\n  fdisjoint (objs s1) (objs s2) ->\n  eval_com true c s1 k = Done s1' ->\n  exists2 π,\n    eval_com true c (s1 ∪ s2) k = Done (rename π s1' ∪ s2)\n    & fdisjoint (objs (rename π s1')) (objs s2).\nProof.\nmove=> sub dis_v dis_o ev.\nrewrite /vars_s -(eval_com_vars sub ev) in dis_v.\nhave [A] := str.eval_basic_restr c s1 k; rewrite ev hideI namesrE.\nmove: (_ :&: _) (fsubsetIr A (names s1'))=> /= {A} A subA ev'.\nhave {sub} ev'' := str.frame_ok sub dis_o ev'.\nhave [A'] := str.eval_basic_restr c (s1 ∪ s2) k.\nrewrite ev''; case: eval_com=> // s' [] es'.\nmove: es' ev''; rewrite [hide A' _]hideI namesrE.\nmove: (_ :&: _) (fsubsetIr A' (names s'))=> /= {A'} A' subA'.\nmove e: (hide A (Restr s1')) => /= s1''.\ncase/(restrP (names s1 :|: names s2)): s1'' e => /= A'' s1'' disA'' subA''.\nmove: disA''; rewrite fdisjointUl=> /andP [dis_s1_A'' dis_s2_A''].\nrewrite maprE //.\ncase/restr_eqP=> /= π dis_π; rewrite (fsetIidPl subA'').\nrewrite (fsetIidPl subA).\nrewrite -{2 3}(renameK π s1').\nrewrite -namesrE in dis_π.\nmove: (dis_π) subA ev' dis_o.\nrewrite -[fsubset _ _](renameT π) fsubset_eqvar (renamefsE _ (names s1')) -names_rename.\nrewrite -[hide A _](@renameJ _ π) // ?names_hider // hide_eqvar Restr_eqvar.\nmove: dis_v; rewrite -[domm s1'.1](renameT π) domm_eqvar fst_eqvar.\nmove: (rename π A) (rename π s1') => {A s1' dis_π ev} /= A s1' dis_v _ subA ev.\nmove=> dis [e1 e2]; move: dis_s1_A'' dis_s2_A'' {subA''}.\nrewrite -{}e1 -{}e2 {A'' s1''}.\nmove=> dis_s1_A dis_s2_A; case/restr_eqP=> /= π' dis_π'.\nrewrite (fsetIidPl subA').\nmove=> [_ <-] {A' s' subA'} ev'.\nhave dis_s1' : fdisjoint (objs s1') (objs s2).\n  have:= @str.eval_com_blocks (objs s2) s1 c k dis.\n  rewrite ev /= str.pbind_resE.\n  have: fdisjoint (names (objs s2)) A.\n    by apply: fdisjoint_trans dis_s2_A; eapply nom_finsuppP; finsupp.\n  move: (objs s2) => A' disA'.\n  by rewrite pbindrE //= namesfsnE.\nhave e_s2 : rename π' s2 = s2.\n  rewrite names_stateu // in dis_π'.\n  rewrite renameJ //.\n  move: dis_π'; rewrite fsetDUl fdisjointUr=>/andP [_].\n  by move/fsetDidPl: dis_s2_A => ->.\nexists (π' * π)%fperm; rewrite ?stateu_eqvar renameA fperm_mulsK {π}.\n  by congr Done; congr stateu.\nby rewrite -e_s2 -objs_eqvar -[objs (rename _ _)]objs_eqvar -fdisjoint_eqvar.\nQed.\n\nTheorem frame_loop s1 s2 c k :\n  fsubset (vars_c c) (vars_s s1) ->\n  fdisjoint (objs s1) (objs s2) ->\n  eval_com true c s1 k = NotYet ->\n  eval_com true c (s1 ∪ s2) k = NotYet.\nProof.\nmove=> sub dis ev.\nhave [A] := str.eval_basic_restr c s1 k; rewrite ev {A}.\nmove=> ev'.\nhave ev'' := str.frame_loop sub dis ev'.\nhave [A] := str.eval_basic_restr c (s1 ∪ s2) k.\nby rewrite ev''; case: eval_com.\nQed.\n\nTheorem frame_error s1 s2 c k :\n  fsubset (vars_c c) (vars_s s1) ->\n  fdisjoint (names s1) (objs s2) ->\n  eval_com true c s1 k = Error ->\n  eval_com true c (s1 ∪ s2) k = Error.\nProof.\nmove=> sub dis ev.\nhave [A] := str.eval_basic_restr c s1 k; rewrite ev {A}.\nmove=> ev'.\nhave ev'' := str.frame_error sub dis ev'.\nhave [A] := str.eval_basic_restr c (s1 ∪ s2) k.\nby rewrite ev''; case: eval_com.\nQed.\n\nCorollary noninterference s1 s21 s' s22 c k :\n  fsubset (vars_c c) (vars_s s1) ->\n  fdisjoint (vars_s s1) (vars_s s21) -> (* Same applies here *)\n  fdisjoint (vars_s s1) (vars_s s22) -> (* And here *)\n  fdisjoint (names s1) (objs s21) ->\n  fdisjoint (objs s1) (objs s22) ->\n  eval_com true c (s1 ∪ s21) k = Done s' ->\n  exists s1' π1 π2,\n    [/\\ eval_com true c s1 k = Done s1',\n        s' = rename π1 s1' ∪ s21,\n        fdisjoint (objs (rename π1 s1')) (objs s21),\n        eval_com true c (s1 ∪ s22) k = Done (rename π2 s1' ∪ s22) &\n        fdisjoint (objs (rename π2 s1')) (objs s22) ].\nProof.\nmove=> sub dis_v1 dis_v2 dis_o1 dis_o2 eval_c.\nhave dis_o1' : fdisjoint (objs s1) (objs s21).\n  apply: fdisjoint_trans; last exact: dis_o1.\n  exact: objs_names.\ncase eval_c': (eval_com true c s1 k) => [s1'| |] //=.\n- exists s1'.\n  have [π1 eπ1 disπ1] := frame_ok sub dis_v1 dis_o1' eval_c'.\n  exists π1; move: eπ1; rewrite eval_c => - [->].\n  have [π2 eπ2 disπ2] := frame_ok sub dis_v2 dis_o2 eval_c'.\n  by exists π2; split.\n- by rewrite (frame_error sub dis_o1 eval_c') in eval_c.\nby rewrite (frame_loop sub _ eval_c') // in eval_c.\nQed.\n\nEnd Properties.\n", "meta": {"author": "arthuraa", "repo": "memory-safe-language", "sha": "1a32e879b93b5e9d6fc97100464c8432faece72d", "save_path": "github-repos/coq/arthuraa-memory-safe-language", "path": "github-repos/coq/arthuraa-memory-safe-language/memory-safe-language-1a32e879b93b5e9d6fc97100464c8432faece72d/properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22521254000439037}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\n\nSet Implicit Arguments.\n\n\nSection Simulation.\n  Definition SIM :=\n    forall (ths1_src:Threads.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n      (ths1_tgt:Threads.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t), Prop.\n\n  Definition _sim\n             (sim: SIM)\n             (ths1_src:Threads.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n             (ths1_tgt:Threads.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t): Prop :=\n    forall sc1_src mem1_src\n      sc1_tgt mem1_tgt\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY1: sim_memory mem1_src mem1_tgt)\n      (WF_SRC: Configuration.wf (Configuration.mk ths1_src sc1_src mem1_src))\n      (WF_TGT: Configuration.wf (Configuration.mk ths1_tgt sc1_tgt mem1_tgt))\n      (CONSISTENT_SRC: Configuration.consistent (Configuration.mk ths1_src sc1_src mem1_src))\n      (CONSISTENT_TGT: Configuration.consistent (Configuration.mk ths1_tgt sc1_tgt mem1_tgt))\n      (SC_FUTURE_SRC: TimeMap.le sc0_src sc1_src)\n      (SC_FUTURE_TGT: TimeMap.le sc0_tgt sc1_tgt)\n      (MEM_FUTURE_SRC: Memory.future mem0_src mem1_src)\n      (MEM_FUTURE_TGT: Memory.future mem0_tgt mem1_tgt),\n      <<TERMINAL:\n        forall (TERMINAL_TGT: Threads.is_terminal ths1_tgt),\n        exists ths2_src sc2_src mem2_src,\n          <<STEPS_SRC: rtc Configuration.tau_step (Configuration.mk ths1_src sc1_src mem1_src) (Configuration.mk ths2_src sc2_src mem2_src)>> /\\\n          <<SC: TimeMap.le sc2_src sc1_tgt>> /\\\n          <<MEMORY: sim_memory mem2_src mem1_tgt>> /\\\n          <<TERMINAL_SRC: Threads.is_terminal ths2_src>>>> /\\\n      <<STEP:\n        forall e tid_tgt ths3_tgt sc3_tgt mem3_tgt\n          (STEP_TGT: Configuration.step e tid_tgt (Configuration.mk ths1_tgt sc1_tgt mem1_tgt) (Configuration.mk ths3_tgt sc3_tgt mem3_tgt)),\n        exists tid_src ths2_src sc2_src mem2_src ths3_src sc3_src mem3_src,\n          <<STEPS_SRC: rtc Configuration.tau_step (Configuration.mk ths1_src sc1_src mem1_src) (Configuration.mk ths2_src sc2_src mem2_src)>> /\\\n          <<STEP_SRC: Configuration.opt_step e tid_src (Configuration.mk ths2_src sc2_src mem2_src) (Configuration.mk ths3_src sc3_src mem3_src)>> /\\\n          <<SC3: TimeMap.le sc3_src sc3_tgt>> /\\\n          <<MEMORY3: sim_memory mem3_src mem3_tgt>> /\\\n          <<SIM: sim ths3_src sc3_src mem3_src ths3_tgt sc3_tgt mem3_tgt>>>>.\n\n  Lemma _sim_mon: monotone6 _sim.\n  Proof.\n    ii. exploit IN; try apply SC1; eauto. i. des.\n    splits; eauto. i.\n    exploit STEP; eauto. i. des.\n    esplits; eauto.\n  Qed.\n  Hint Resolve _sim_mon: paco.\n\n  Definition sim: SIM := paco6 _sim bot6.\nEnd Simulation.\nHint Resolve _sim_mon: paco.\n\n\nLemma sim_future\n      ths_src sc1_src sc2_src mem1_src mem2_src\n      ths_tgt sc1_tgt sc2_tgt mem1_tgt mem2_tgt\n      (SIM: sim ths_src sc1_src mem1_src ths_tgt sc1_tgt mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc1_src sc2_src)\n      (SC_FUTURE_TGT: TimeMap.le sc1_tgt sc2_tgt)\n      (MEM_FUTURE_SRC: Memory.future mem1_src mem2_src)\n      (MEM_FUTURE_TGT: Memory.future mem1_tgt mem2_tgt):\n  sim ths_src sc2_src mem2_src ths_tgt sc2_tgt mem2_tgt.\nProof.\n  pfold. ii.\n  punfold SIM. exploit SIM; (try by etrans; eauto); eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-coq", "sha": "bff53239c51681ea653745cebf3b30ddd38f97ba", "save_path": "github-repos/coq/snu-sf-promising-coq", "path": "github-repos/coq/snu-sf-promising-coq/promising-coq-bff53239c51681ea653745cebf3b30ddd38f97ba/src/opt/Simulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22521253443490716}}
{"text": "Require Import VST.progs.conclib.\nRequire Import VST.progs.ghosts.\nRequire Import VST.progs.incr.\n\nGlobal Open Scope funspec_scope.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition acquire_spec := DECLARE _acquire acquire_spec.\nDefinition release_spec := DECLARE _release release_spec.\nDefinition makelock_spec := DECLARE _makelock (makelock_spec _).\nDefinition freelock_spec := DECLARE _freelock (freelock_spec _).\nDefinition spawn_spec := DECLARE _spawn spawn_spec.\nDefinition freelock2_spec := DECLARE _freelock2 (freelock2_spec _).\nDefinition release2_spec := DECLARE _release2 release2_spec.\n\nDefinition cptr_lock_inv g1 g2 ctr := EX z : Z, data_at Ews tuint (Vint (Int.repr z)) ctr *\n  EX x : Z, EX y : Z, !!(z = x + y) && ghost_var gsh1 x g1 * ghost_var gsh1 y g2.\n\nDefinition incr_spec :=\n DECLARE _incr\n  WITH sh : share, g1 : gname, g2 : gname, left : bool, n : Z, gv: globals\n  PRE [ ]\n         PROP  (readable_share sh)\n         PARAMS () GLOBALS (gv)\n         SEP   (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr)); ghost_var gsh2 n (if left then g1 else g2))\n  POST [ tvoid ]\n         PROP ()\n         LOCAL ()\n         SEP (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr)); ghost_var gsh2 (n+1) (if left then g1 else g2)).\n\nDefinition read_spec :=\n DECLARE _read\n  WITH sh : share, g1 : gname, g2 : gname, n1 : Z, n2 : Z, gv: globals\n  PRE [ ]\n         PROP  (readable_share sh)\n         PARAMS () GLOBALS (gv)\n         SEP   (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr)); ghost_var gsh2 n1 g1; ghost_var gsh2 n2 g2)\n  POST [ tuint ]\n         PROP ()\n         LOCAL (temp ret_temp (Vint (Int.repr (n1 + n2))))\n         SEP (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr)); ghost_var gsh2 n1 g1; ghost_var gsh2 n2 g2).\n\nDefinition thread_lock_R sh g1 g2 ctr lockc :=\n  lock_inv sh lockc (cptr_lock_inv g1 g2 ctr) * ghost_var gsh2 1 g1.\n\nDefinition thread_lock_inv sh g1 g2 ctr lockc lockt :=\n  selflock (thread_lock_R sh g1 g2 ctr lockc) sh lockt.\n\nDefinition thread_func_spec :=\n DECLARE _thread_func\n  WITH y : val, x : share * gname * gname * globals\n  PRE [ (*_args OF*) (tptr tvoid) ]\n         let '(sh, g1, g2, gv) := x in\n         PROP  (readable_share sh)\n         PARAMS (y) GLOBALS (gv)\n         SEP   (lock_inv sh (gv _ctr_lock) (cptr_lock_inv g1 g2 (gv _ctr));\n                ghost_var gsh2 0 g1;\n                lock_inv sh (gv _thread_lock) (thread_lock_inv sh g1 g2 (gv _ctr) (gv _ctr_lock) (gv _thread_lock)))\n  POST [ tptr tvoid ]\n         PROP ()\n         LOCAL ()\n         SEP ().\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre prog tt gv\n  POST [ tint ] main_post prog gv.\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [acquire_spec; release_spec; release2_spec; makelock_spec;\n  freelock_spec; freelock2_spec; spawn_spec; incr_spec; read_spec; thread_func_spec; main_spec]).\n\nLemma ctr_inv_exclusive : forall g1 g2 p,\n  exclusive_mpred (cptr_lock_inv g1 g2 p).\nProof.\n  intros; unfold cptr_lock_inv.\n  eapply derives_exclusive, exclusive_sepcon1 with (Q := EX x : Z, EX y : Z, _),\n    data_at__exclusive with (sh := Ews)(t := tuint); auto; simpl; try lia.\n  Intro z; apply sepcon_derives; [cancel|].\n  Intros x y; Exists x y; apply derives_refl.\nQed.\n#[export] Hint Resolve ctr_inv_exclusive : core.\n\nLemma thread_inv_exclusive : forall sh g1 g2 ctr lock lockt,\n  exclusive_mpred (thread_lock_inv sh g1 g2 ctr lock lockt).\nProof.\n  intros; apply selflock_exclusive.\n  unfold thread_lock_R.\n  apply exclusive_sepcon1; auto.\nQed.\n#[export] Hint Resolve thread_inv_exclusive : core.\n\nLemma body_incr: semax_body Vprog Gprog f_incr incr_spec.\nProof.\n  start_function.\n  forward.\n  forward_call (gv _ctr_lock, sh, cptr_lock_inv g1 g2 (gv _ctr)).\n  unfold cptr_lock_inv at 2; simpl.\n  Intros z x y.\n  forward.\n  forward.\n\n  gather_SEP (ghost_var _ x g1) (ghost_var _ y g2) (ghost_var _ n _).\n  rewrite sepcon_assoc.\n  viewshift_SEP 0 (!!((if left then x else y) = n) && ghost_var Tsh (n+1) (if left then g1 else g2) *\n    ghost_var gsh1 (if left then y else x) (if left then g2 else g1)).\n  { go_lower.\n    destruct left.\n    - rewrite (sepcon_comm _ (ghost_var _ _ _)), <- sepcon_assoc.\n      erewrite ghost_var_share_join' by eauto.\n      Intros; rewrite prop_true_andp by auto; eapply derives_trans, bupd_frame_r; cancel.\n      apply ghost_var_update.\n    - erewrite ghost_var_share_join' by eauto.\n      Intros; rewrite prop_true_andp by auto; eapply derives_trans, bupd_frame_r; cancel.\n      apply ghost_var_update. }\n  Intros; forward_call (gv _ctr_lock, sh, cptr_lock_inv g1 g2 (gv _ctr)).\n  { lock_props.\n    unfold cptr_lock_inv; Exists (z + 1).\n    erewrite <- ghost_var_share_join by eauto.\n    unfold Frame; instantiate (1 := [ghost_var gsh2 (n+1) (if left then g1 else g2)]); simpl.\n    destruct left.\n    - Exists (n+1) y; entailer!.\n    - Exists x (n+1); entailer!. }\n  forward.\nQed.\n\nLemma body_read : semax_body Vprog Gprog f_read read_spec.\nProof.\n  start_function.\n  forward_call (gv _ctr_lock, sh, cptr_lock_inv g1 g2 (gv _ctr)).\n  unfold cptr_lock_inv at 2; simpl.\n  Intros z x y.\n  forward.\n  assert_PROP (x = n1 /\\ y = n2) as Heq.\n  { gather_SEP (ghost_var _ x g1) (ghost_var _ n1 g1).\n    erewrite ghost_var_share_join' by eauto.\n    gather_SEP (ghost_var _ y g2) (ghost_var _ n2 g2).\n    erewrite ghost_var_share_join' by eauto.\n    entailer!. }\n  forward_call (gv _ctr_lock, sh, cptr_lock_inv g1 g2 (gv _ctr)).\n  { lock_props.\n    unfold cptr_lock_inv; Exists z x y; entailer!. }\n  destruct Heq; forward.\nQed.\n\nLemma body_thread_func : semax_body Vprog Gprog f_thread_func thread_func_spec.\nProof.\n  start_function.\n  Intros.\n  forward.\n  forward_call (sh, g1, g2, true, 0, gv).\n  simpl.\n  forward_call ((gv _thread_lock), sh, thread_lock_R sh g1 g2 (gv _ctr) (gv _ctr_lock), thread_lock_inv sh g1 g2 (gv _ctr) (gv _ctr_lock) (gv _thread_lock)).\n  { lock_props.\n    unfold thread_lock_inv, thread_lock_R.\n    rewrite selflock_eq at 2; cancel. }\n  forward.\nQed.\n\nLtac cancel_for_forward_call ::=\n  match goal with\n  | gv: globals |- _ =>\n    repeat\n    match goal with\n    | x := gv ?i |- context [gv ?i] =>\n        change (gv i) with x\n    end\n  | _ => idtac\n  end;\n  cancel_for_evar_frame.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\n  start_function.\n  set (ctr := gv _ctr); set (lockt := gv _thread_lock); set (lock := gv _ctr_lock).\n  forward.\n  forward.\n  forward.\n  ghost_alloc (ghost_var Tsh 0).\n  Intro g1.\n  ghost_alloc (ghost_var Tsh 0).\n  Intro g2.\n  forward_call (lock, Ews, cptr_lock_inv g1 g2 ctr).\n  forward_call (lock, Ews, cptr_lock_inv g1 g2 ctr).\n  { lock_props.\n    rewrite <- !(ghost_var_share_join gsh1 gsh2 Tsh) by auto.\n    unfold cptr_lock_inv; Exists 0 0 0; entailer!. }\n  (* need to split off shares for the locks here *)\n  destruct split_Ews as (sh1 & sh2 & ? & ? & Hsh).\n  forward_call (lockt, Ews, thread_lock_inv sh1 g1 g2 ctr lock lockt).\n  forward_spawn _thread_func nullval (sh1, g1, g2, gv).\n  { erewrite <- lock_inv_share_join; try apply Hsh; auto.\n    erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto.\n    entailer!. }\n  forward_call (sh2, g1, g2, false, 0, gv).\n  simpl.\n  forward_call (lockt, sh2, thread_lock_inv sh1 g1 g2 ctr lock lockt).\n  unfold thread_lock_inv at 2; unfold thread_lock_R.\n  rewrite selflock_eq.\n  Intros.\n  forward_call (sh2, g1, g2, 1, 1, gv).\n  (* We've proved that t is 2! *)\n  forward_call (lock, sh2, cptr_lock_inv g1 g2 ctr).\n  forward_call (lockt, Ews, sh1, thread_lock_R sh1 g1 g2 ctr lock, thread_lock_inv sh1 g1 g2 ctr lock lockt).\n  { lock_props.\n    unfold thread_lock_inv, thread_lock_R.\n    erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto; cancel. }\n  forward_call (lock, Ews, cptr_lock_inv g1 g2 ctr).\n  { lock_props.\n    erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto; cancel. }\n  forward.\nUnshelve. apply xH. (*TODO: fix (I believe) the forward_spawn tactic  so that this ident is not introduces. Is it the y?*)\nQed.\n\nDefinition extlink := ext_link_prog prog.\nDefinition Espec := add_funspecs (Concurrent_Espec unit _ extlink) extlink Gprog.\nExisting Instance Espec.\n\nLemma prog_correct:\n  semax_prog prog tt Vprog Gprog.\nProof.\nprove_semax_prog.\nrepeat (apply semax_func_cons_ext_vacuous; [reflexivity | reflexivity | ]).\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons body_incr.\nsemax_func_cons body_read.\nsemax_func_cons body_thread_func.\nsemax_func_cons body_main.\nQed.\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/progs/verif_incr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.22517777435065814}}
{"text": "Require Import Events.\nRequire Import Memory.\nRequire Import Coqlib.\nRequire Import Values.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import AST.\nRequire Import Globalenvs.\nRequire Import Axioms.\n\nRequire Import mem_lemmas. (*needed for definition of mem_forward etc*)\nRequire Import semantics.\nRequire Import semantics_lemmas.\nRequire Import structured_injections.\n\n(** * Effect Semantics *)\n\n(** Effect semantics augment interaction semantics with effects, in the form \n    of a set of locations [block -> Z -> bool] associated with each internal \n    step of the semantics. *)\n\n(** Unlike general interaction semantics, which are paremetric in the type of\n    memory, effect semantics are specialized to CompCert memories. *)\n \nRecord EffectSem {G C} :=\n  { (** [sem] is a cooperating interaaction semantics. *)\n    sem :> CoopCoreSem G C\n\n    (** The step relation of the new semantics. *)\n  ; effstep: G -> (block -> Z -> bool) -> C -> mem -> C -> mem -> Prop\n\n    (** The next three fields axiomatize [effstep] and its relation to the\n        underlying step relation of [sem]. *)\n  ; effax1: forall M g c m c' m',\n       effstep g M c m c' m' ->\n            corestep sem g c m c' m'  \n         /\\ Mem.unchanged_on (fun b ofs => M b ofs = false) m m'\n  ; effax2: forall g c m c' m',\n       corestep sem g c m c' m' ->\n       exists M, effstep g M c m c' m'\n  ; effstep_valid: forall M g c m c' m',\n       effstep g M c m c' m' ->\n       forall b z, M b z = true -> Mem.valid_block m b\n  }.\n\n(** * Lemmas and auxiliary definitions *)\n\nSection effsemlemmas.\n  Context {G C:Type} (Sem: @EffectSem G C) (g:G).\n\n  Lemma effstep_corestep: forall M g c m c' m',\n      effstep Sem g M c m c' m' -> corestep Sem g c m c' m'. \n  Proof. intros. apply effax1 in H. apply H. Qed.\n\n  Lemma effstep_unchanged: forall M g c m c' m',\n        effstep Sem g M c m c' m' -> \n        Mem.unchanged_on (fun b ofs => M b ofs = false) m m'.\n  Proof. intros. apply effax1 in H. apply H. Qed.\n\n  Lemma effstep_fwd: forall U c m c' m',\n    effstep Sem g U c m c' m' -> mem_forward m m'.\n  Proof. intros. destruct Sem.\n         eapply corestep_fwd. eapply effax1. apply H.\n  Qed.\n\n  Fixpoint effstepN (n:nat) : (block -> Z -> bool) -> C -> mem -> C -> mem -> Prop :=\n    match n with\n      | O => fun U c m c' m' => (c,m) = (c',m') /\\ U = (fun b z => false)\n      | S k => fun U c1 m1 c3 m3 => exists c2, exists m2, exists U1, exists U2,\n        effstep Sem g U1 c1 m1 c2 m2 /\\\n        effstepN k U2 c2 m2 c3 m3 /\\ \n        U = (fun b z => U1 b z || (U2 b z && valid_block_dec m1 b))\n    end.\n\nLemma effstepN_valid: forall n U c1 m1 c2 m2, effstepN n U c1 m1 c2 m2 ->\n       forall b z, U b z = true -> Mem.valid_block m1 b.\nProof. intros n.\n  induction n; simpl; intros. destruct H; subst. discriminate.\n  destruct H as [c [m [U1 [U2 [Step [StepN UU]]]]]]; subst; simpl.\n  specialize (IHn _ _ _ _ _ StepN). \n  specialize (effstep_valid _ _ _ _ _ _ _ Step b z). intros.\n  remember (U1 b z) as d.\n  destruct d; simpl in *. apply H; trivial.\n  destruct (valid_block_dec m1 b). trivial. simpl in *.\n  rewrite andb_false_r in H0. inv H0.\nQed.\n\n  Lemma effstepN_fwd: forall n U c m c' m',\n    effstepN n U c m c' m' -> mem_forward m m'.\n  Proof. intros n.\n         induction n; intros; simpl in *. destruct H.\n           inv H. eapply mem_forward_refl.\n         destruct H as [c1 [c2 [Eff1 [Eff2 [Step1 [Step2 HU]]]]]].\n         eapply mem_forward_trans.\n           eapply effstep_fwd; eassumption.\n           eapply IHn; eassumption. \n  Qed.\n\n  Lemma effstepN_corestepN: forall n E c m c' m',\n      effstepN n E c m c' m' -> corestepN Sem g n c m c' m'. \n  Proof. intros n.\n    induction n; intros; simpl in *.\n        apply H. \n      destruct H as [c1 [m1 [U1 [U2 [Estep [EN HE]]]]]].\n        apply effstep_corestep in Estep.\n        apply IHn in EN. exists c1, m1.\n        split; eassumption.\n  Qed.\n\n  Lemma effstepN_unchanged: forall n U c1 m1 c2 m2,\n        effstepN n U c1 m1 c2 m2 -> \n        Mem.unchanged_on (fun b z => U b z = false) m1 m2.\n  Proof. intros n.\n    induction n; simpl; intros.\n      destruct H. inv H. apply Mem.unchanged_on_refl.\n    rename c2 into c3. rename m2 into m3.\n    destruct H as [c2 [m2 [E1 [E2 [Step1 [Step2 HE]]]]]].\n    apply IHn in Step2; clear IHn. subst.\n    assert (FWD:= effstep_fwd _ _ _ _ _ Step1).\n    apply effstep_unchanged in Step1.\n    split; intros.\n     apply orb_false_iff in H. destruct H.\n     remember (valid_block_dec m1 b) as v.\n     destruct v; simpl in *; try contradiction.\n     clear H0 Heqv.\n     rewrite andb_true_r in H1.     \n     split; intros. apply Step2; trivial.\n        apply (FWD _ v). \n     apply Step1; try assumption.\n\n     apply Step1; try assumption.\n       apply Step2; try assumption. \n        apply (FWD _ v).\n\n   apply orb_false_iff in H. destruct H.\n     remember (valid_block_dec m1 b) as v.\n     destruct v; simpl in *; try contradiction.\n     clear Heqv.\n     rewrite andb_true_r in H1.\n     destruct Step2. rewrite unchanged_on_contents; trivial.\n       eapply Step1; try eassumption.\n       eapply Step1; try eassumption.\n     elim n0. eapply Mem.perm_valid_block; eassumption.\n  Qed.\n\nLemma effstepN_trans: forall n1 n2 U1 st1 m1 st2 m2 U2 st3 m3,\n      effstepN n1 U1 st1 m1 st2 m2 ->\n      effstepN n2 U2 st2 m2 st3 m3 ->\n   effstepN (n1+n2)\n        (fun b z => U1 b z || (U2 b z && valid_block_dec m1 b)) st1 m1 st3 m3.\nProof. intros n1.\ninduction n1; simpl.\n  intros. destruct H; subst. inv H. simpl.\n  assert (U2 = (fun b z => U2 b z && valid_block_dec m2 b)).\n    extensionality b; extensionality z.\n    remember (U2 b z) as d. destruct d; trivial.\n    apply eq_sym in Heqd.\n    apply (effstepN_valid _ _ _ _ _ _ H0) in Heqd.\n    remember (valid_block_dec m2 b) as q.\n    destruct q; trivial. contradiction.\n  rewrite H in H0. apply H0.\nintros. rename st3 into st4. rename m3 into m4.\n   rename st2 into st3. rename m2 into m3.\n   rename U1 into U. rename U2 into U3.\n   destruct H as [st2 [m2 [U1 [U2 [Step1 [Step2 HU]]]]]].\n   subst; simpl in *.\n   exists st2, m2, U1; simpl.\n   specialize (IHn1 _ _ _ _ _ _ _ _ _ Step2 H0). \n   clear Step2 H0.\n   eexists; split. assumption.\n   split. eassumption.\n   extensionality b; extensionality z; simpl.\n   remember (U1 b z) as d. destruct d; simpl; trivial; apply eq_sym in Heqd.\n   remember (U2 b z) as q. destruct q; simpl; trivial; apply eq_sym in Heqq.\n     remember (valid_block_dec m1 b) as u.\n     destruct u; trivial; simpl. apply andb_false_r.\n   remember (U3 b z) as p. destruct p; simpl; trivial; apply eq_sym in Heqp.\n     remember (valid_block_dec m1 b) as u.\n     destruct u; trivial; simpl. clear Hequ. rewrite andb_true_r.\n       apply effstep_fwd in Step1. apply Step1 in v.\n       destruct (valid_block_dec m2 b); trivial. destruct v; contradiction.\n     rewrite andb_false_r. trivial.\nQed.\n\nLemma effstepN_trans': forall n1 n2 U U1 st1 m1 st2 m2 U2 st3 m3,\n      effstepN n1 U1 st1 m1 st2 m2 ->\n      effstepN n2 U2 st2 m2 st3 m3 ->\n      U = (fun b z => U1 b z || (U2 b z && valid_block_dec m1 b)) ->\n   effstepN (n1+n2) U st1 m1 st3 m3.\nProof. intros; subst. eapply effstepN_trans; eassumption. Qed.\n\n  Definition effstep_plus U c m c' m' :=\n    exists n, effstepN (S n) U c m c' m'.\n\n  Definition effstep_star U c m c' m' :=\n    exists n, effstepN n U c m c' m'.\n\n  Lemma effstep_plus_star : forall U c1 c2 m1 m2,\n    effstep_plus U c1 m1 c2 m2 -> effstep_star U c1 m1 c2 m2.\n  Proof. intros. destruct H as [n1 H1]. eexists. apply H1. Qed.\n\n  Lemma effstep_plus_trans : forall U1 c1 c2 c3 U2 m1 m2 m3,\n    effstep_plus U1 c1 m1 c2 m2 -> effstep_plus U2 c2 m2 c3 m3 -> \n    effstep_plus (fun b z => U1 b z || (U2 b z && valid_block_dec m1 b)) c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    exists ((n1 + (S n2))%nat). simpl.\n    apply (effstepN_trans (S n1) (S n2) U1 c1 m1 c2 m2 U2 c3 m3 H1 H2).\n  Qed.\n  Lemma effstep_plus_trans' : forall U U1 c1 c2 c3 U2 m1 m2 m3,\n    effstep_plus U1 c1 m1 c2 m2 -> effstep_plus U2 c2 m2 c3 m3 -> \n    U = (fun b z => U1 b z || (U2 b z && valid_block_dec m1 b)) ->\n    effstep_plus U c1 m1 c3 m3.\n  Proof. intros; subst. eapply effstep_plus_trans; eassumption. Qed.\n\n  Lemma effstep_star_plus_trans : forall U1 c1 c2 c3 U2 m1 m2 m3,\n    effstep_star U1 c1 m1 c2 m2 -> effstep_plus U2 c2 m2 c3 m3 -> \n    effstep_plus (fun b z => U1 b z || (U2 b z && valid_block_dec m1 b)) c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    exists ((n1 + n2)%nat).\n    specialize (effstepN_trans n1 (S n2) U1 c1 m1 c2 m2 U2 c3 m3 H1 H2); intros H.\n    rewrite <- plus_n_Sm in H. assumption.\n  Qed.\n  Lemma effstep_star_plus_trans' : forall U U1 c1 c2 c3 U2 m1 m2 m3,\n    effstep_star U1 c1 m1 c2 m2 -> effstep_plus U2 c2 m2 c3 m3 -> \n    U = (fun b z => U1 b z || (U2 b z && valid_block_dec m1 b)) ->\n    effstep_plus U c1 m1 c3 m3.\n  Proof. intros; subst. eapply effstep_star_plus_trans; eassumption. Qed. \n\n  Lemma effstep_plus_star_trans: forall U1 c1 c2 c3 U2 m1 m2 m3,\n    effstep_plus U1 c1 m1 c2 m2 -> effstep_star U2 c2 m2 c3 m3 -> \n    effstep_plus (fun b z => U1 b z || (U2 b z && valid_block_dec m1 b)) c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    exists ((n1 + n2)%nat).\n    apply (effstepN_trans _ _  U1 c1 m1 c2 m2 U2 c3 m3 H1 H2).\n  Qed.\n  Lemma effstep_plus_star_trans': forall U U1 c1 c2 c3 U2 m1 m2 m3,\n    effstep_plus U1 c1 m1 c2 m2 -> effstep_star U2 c2 m2 c3 m3 -> \n    U = (fun b z => U1 b z || (U2 b z && valid_block_dec m1 b)) ->\n    effstep_plus U c1 m1 c3 m3.\n  Proof. intros; subst. eapply effstep_plus_star_trans; eassumption. Qed. \n\n  Lemma effstep_star_trans: forall U1 c1 c2 c3 U2 m1 m2 m3, \n    effstep_star U1 c1 m1 c2 m2 -> effstep_star U2 c2 m2 c3 m3 -> \n    effstep_star (fun b z => U1 b z || (U2 b z && valid_block_dec m1 b)) c1 m1 c3 m3.\n  Proof. intros. destruct H as [n1 H1]. destruct H0 as [n2 H2].\n    eexists.\n    eapply (effstepN_trans _ _ U1 c1 m1 c2 m2 U2 c3 m3 H1 H2).\n  Qed.\n  Lemma effstep_star_trans': forall U U1 c1 c2 c3 U2 m1 m2 m3, \n    effstep_star U1 c1 m1 c2 m2 -> effstep_star U2 c2 m2 c3 m3 -> \n    U = (fun b z => U1 b z || (U2 b z && valid_block_dec m1 b)) ->\n    effstep_star U c1 m1 c3 m3.\n  Proof. intros; subst. eapply effstep_star_trans; eassumption. Qed. \n\n  Lemma effstep_plus_one: forall U c m c' m',\n    effstep Sem g U c m c' m' -> effstep_plus U c m c' m'.\n  Proof. intros. exists O. simpl. exists c', m', U, (fun b z =>false).\n    intuition.\n    extensionality b; extensionality z; simpl.\n    rewrite orb_false_r. trivial.\n  Qed.\n\n  Lemma effstep_plus_two: forall U1 c m c' m' U2 c'' m'',\n    effstep  Sem g U1 c m c' m' -> effstep Sem g U2 c' m' c'' m'' -> \n    effstep_plus (fun b z => U1 b z || (U2 b z && valid_block_dec m b)) c m c'' m''.\n  Proof. intros. \n    exists (S O). exists c', m', U1, U2. split; trivial.\n    split; trivial. simpl. \n    exists c'', m'', U2, (fun b z =>false).\n    intuition.\n    extensionality b; extensionality z; simpl.\n    rewrite orb_false_r. trivial.\n  Qed.\n\n  Lemma effstep_star_zero: forall c m, effstep_star (fun b z =>false) c m c m.\n  Proof. intros. exists O. simpl. split; reflexivity. Qed.\n\n  Lemma effstep_star_one: forall U c m c' m',\n    effstep  Sem g U c m c' m' -> effstep_star U c m c' m'.\n  Proof. intros. \n    exists (S O). exists c', m', U, (fun b z =>false).\n    simpl; split; trivial. split. split; reflexivity.\n    extensionality b; extensionality z; simpl.\n    rewrite orb_false_r. trivial.     \n  Qed.\n\n  Lemma effstep_plus_split: forall U c m c' m',\n    effstep_plus U c m c' m' ->\n    exists c'', exists m'', exists U1, exists U2,\n      effstep Sem g U1 c m c'' m'' /\\ \n      effstep_star U2 c'' m'' c' m' /\\\n      U = (fun b z => U1 b z || (U2 b z && valid_block_dec m b)).\n  Proof. intros.\n    destruct H as [n [c2 [m2 [U1 [U2 [Hstep [Hstar HU]]]]]]].\n    exists c2, m2, U1, U2. split. assumption. split; try assumption.\n    exists n. assumption. \n  Qed.\n\n  Lemma effstep_star_fwd: forall U c m c' m',\n    effstep_star U c m c' m' -> mem_forward m m'.\n  Proof. intros. destruct H as [n H]. \n      eapply effstepN_fwd; eassumption.\n  Qed.\n\n  Lemma effstep_plus_fwd: forall U c m c' m',\n    effstep_plus U c m c' m' -> mem_forward m m'.\n  Proof. intros. destruct H as [n H]. \n      eapply effstepN_fwd; eassumption.\n  Qed.\n\nEnd effsemlemmas.\n\n\nDefinition EmptyEffect: Values.block -> Z -> bool := fun b z => false.\n\nLemma EmptyEffect_alloc: forall m lo hi m' b (ALLOC: Mem.alloc m lo hi = (m', b)),\n      Mem.unchanged_on (fun b ofs => EmptyEffect b ofs = false) m m'.\nProof. intros.\n       eapply Mem.alloc_unchanged_on; eassumption.\nQed. \n\nDefinition FreeEffect m lo hi (sp b:Values.block) (ofs:Z): bool := \n   if valid_block_dec m b \n   then eq_block b sp && zle lo ofs && zlt ofs hi\n   else false.\n\nLemma FreeEffectD: forall m lo hi sp b z \n   (FREE:FreeEffect m lo hi sp b z = true),\n   b = sp /\\ Mem.valid_block m b /\\ lo <= z /\\ z < hi.\nProof. intros.\n  unfold FreeEffect in FREE.\n  destruct (valid_block_dec m b); simpl in *; try discriminate.\n  destruct (eq_block b sp); subst; simpl in *; try discriminate.\n  destruct (zle lo z); simpl in *; try discriminate.\n  destruct (zlt z hi); simpl in *; try discriminate.\n  auto.\nQed.\n\nLemma FreeEffect_free: forall m sp lo hi m'\n             (FREE: Mem.free m sp lo hi = Some m'),\n     Mem.unchanged_on  (fun b ofs => FreeEffect m lo hi sp b ofs = false) m m'.\nProof. intros.\n       eapply Mem.free_unchanged_on; try eassumption.\n               intros. unfold FreeEffect; simpl. intros N.\n               destruct (valid_block_dec m sp).\n               apply andb_false_iff in N. destruct H.\n               destruct (eq_block sp sp); simpl in *.\n                 destruct N. destruct (zle lo i). inv H1. xomega.\n               destruct (zlt i hi). inv H1. xomega.\n               apply n; trivial.\n               apply Mem.free_range_perm in FREE.\n                 apply n; clear n.\n                 eapply Mem.perm_valid_block.\n                 eapply (FREE lo). omega.\nQed. \n\nDefinition FreelistEffect \n  m (L: list (Values.block * Z * Z)) (b:Values.block) (ofs:Z): bool := \n  List.fold_right (fun X E b z => match X with (bb,lo,hi) =>\n                                   E b z || FreeEffect m lo hi bb b z\n                                 end) \n                  EmptyEffect L b ofs.\n\nLemma FreelistEffect_Dfalse: forall m bb lo hi L b ofs\n      (F:FreelistEffect m ((bb, lo, hi) :: L) b ofs = false),\n      FreelistEffect m L b ofs = false /\\\n      FreeEffect m lo hi bb b ofs = false. \nProof. intros.\n  unfold FreelistEffect in F. simpl in F.\n  apply orb_false_iff in F. apply F.\nQed. \n\nLemma FreelistEffect_Dtrue: forall m bb lo hi L b ofs\n      (F:FreelistEffect m ((bb, lo, hi) :: L) b ofs = true),\n      FreelistEffect m L b ofs = true \\/\n      FreeEffect m lo hi bb b ofs = true.\nProof. intros.\n  unfold FreelistEffect in F. simpl in F.\n  apply orb_true_iff in F. apply F.\nQed. \n\nLemma FreelistEffect_same: forall m bb lo hi mm L\n          (F:Mem.free m bb lo hi = Some mm)\n          b (VB: Mem.valid_block mm b) ofs,\n      FreelistEffect mm L b ofs = false <-> FreelistEffect m L b ofs = false.\nProof. intros  m bb lo hi mm L.\n  induction L; simpl; intros. intuition.\n  intuition. \n    apply orb_false_iff in H0. destruct H0.\n    specialize (H _ VB ofs).\n    apply H in H0. rewrite H0. simpl. clear H H0.\n    unfold FreeEffect in *; simpl in *.\n    apply Mem.nextblock_free in F. \n    destruct (valid_block_dec m b). \n      destruct (valid_block_dec mm b); trivial.\n      red in v. rewrite <- F in v. elim n. apply v.\n    trivial.\n  apply orb_false_iff in H0. destruct H0.\n    specialize (H _ VB ofs).\n    apply H in H0. rewrite H0. simpl. clear H H0.\n    unfold FreeEffect in *; simpl in *.\n    apply Mem.nextblock_free in F. \n    destruct (valid_block_dec mm b). \n      destruct (valid_block_dec m b); trivial.\n      red in v. rewrite F in v. elim n. apply v.\n    trivial.\nQed.\n\nLemma FreelistEffect_freelist: forall L m m' (FL: Mem.free_list m L = Some m'),\n      Mem.unchanged_on (fun b ofs => FreelistEffect m L b ofs = false) m m'.\nProof. intros L.\n  induction L; simpl; intros.\n    inv FL. apply Mem.unchanged_on_refl.\n  destruct a as [[bb lo] hi].\n    remember (Mem.free m bb lo hi) as d.\n    destruct d; try inv FL. apply eq_sym in Heqd.\n    specialize (IHL _ _ H0).\n    assert (FF:= FreeEffect_free _ _ _ _ _ Heqd). \n    eapply (unchanged_on_trans _ m0 _). \n      eapply mem_unchanged_on_sub; try eassumption.\n        intuition. apply orb_false_iff in H. apply H.\n      clear FF.\n      specialize (unchanged_on_validblock_invariant m0 m' \n           (fun (b : block) (ofs : Z) => FreelistEffect m0 L b ofs = false) \n           (fun (b : block) (ofs : Z) => FreelistEffect m L b ofs = false)).\n      intros. apply H in IHL. clear H.\n        eapply mem_unchanged_on_sub; try eassumption.\n        intuition. apply orb_false_iff in H. apply H.\n      clear IHL H. intros.\n       eapply FreelistEffect_same; eassumption.\n   eapply free_forward; eassumption.\nQed.\n\nLemma FreeEffect_validblock: forall m lo hi sp b ofs\n        (EFF: FreeEffect m lo hi sp b ofs = true),\n      Mem.valid_block m b.\nProof. intros.\n  unfold FreeEffect in EFF.\n  destruct (valid_block_dec m b); trivial; inv EFF.\nQed.\n\nLemma FreelistEffect_validblock: forall l m b ofs\n        (EFF: FreelistEffect m l b ofs = true),\n      Mem.valid_block m b.\nProof. intros l.\n  induction l; unfold FreelistEffect; simpl; intros.\n     unfold EmptyEffect in EFF. inv EFF.\n  destruct a as [[bb lo] hi].\n  apply orb_true_iff in EFF.\n  destruct EFF.\n  apply IHl in H. assumption.\n  eapply FreeEffect_validblock; eassumption.\nQed.\n\nDefinition StoreEffect (tv:val)(vl : list memval) (b:Values.block) (z:Z):bool := \n  match tv with Vptr bb ofs => eq_block bb b && \n             zle (Int.unsigned ofs) z && zlt z (Int.unsigned ofs + Z.of_nat (length vl))\n         | _ => false\n  end.\n\nLemma StoreEffect_Storev: forall m chunk tv tv' m' \n         (STORE : Mem.storev chunk m tv tv' = Some m'),\n      Mem.unchanged_on \n        (fun b ofs => StoreEffect tv (encode_val chunk tv') b ofs = false) \n        m m'.\nProof. intros.\n  destruct tv; inv STORE.\n  unfold StoreEffect.\n  split; intros.\n      split; intros. eapply Mem.perm_store_1; eassumption.\n      eapply Mem.perm_store_2; eassumption.\n  rewrite (Mem.store_mem_contents _ _ _ _ _ _ H0). clear H0.\n  destruct (eq_block b b0); subst; simpl in *.\n    rewrite PMap.gss. apply andb_false_iff in H.  \n    apply Mem.setN_outside.\n    destruct H. destruct (zle (Int.unsigned i) ofs ); simpl in *. inv H.\n                left. xomega.\n    right. remember (Z.of_nat (length (encode_val chunk tv'))).\n       destruct (zlt ofs (Int.unsigned i + z)); simpl in *. inv H. apply g.\n  rewrite PMap.gso. trivial. intros N; subst. elim n; trivial. \nQed.\n\nLemma StoreEffectD: forall vaddr v b ofs\n      (STE: StoreEffect vaddr v b ofs = true),\n      exists i, vaddr = Vptr b i /\\\n        (Int.unsigned i) <= ofs < (Int.unsigned i + Z.of_nat (length v)).\nProof. intros.\n  unfold StoreEffect in STE. destruct vaddr; inv STE.\n  destruct (eq_block b0 b); inv H0.\n  exists i.\n  destruct (zle (Int.unsigned i) ofs); inv H1.\n  destruct (zlt ofs (Int.unsigned i + Z.of_nat (length v))); inv H0.\n  intuition.\nQed.\n       \n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/core/effect_semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2251777689341288}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*          Jacques-Henri Jourdan, INRIA Paris-Rocquencourt            *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation, either version 2 of the License, or  *)\n(*  (at your option) any later version.  This file is also distributed *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Formalization of floating-point numbers, using the Flocq library. *)\n\nRequire Import Axioms.\nRequire Import Coqlib.\nRequire Import Integers.\nRequire Import Fappli_IEEE.\nRequire Import Fappli_IEEE_bits.\nRequire Import Fcore.\nRequire Import Fcalc_round.\nRequire Import Fcalc_bracket.\nRequire Import Fprop_Sterbenz.\nRequire Import Program.\nRequire Archi.\n\nClose Scope R_scope.\n\nDefinition float := binary64. (**r the type of IEE754 doubles *)\n\nModule Float.\n\nDefinition zero: float := B754_zero _ _ false. (**r the float [+0.0] *)\n\nDefinition eq_dec: forall (f1 f2: float), {f1 = f2} + {f1 <> f2}.\nProof.\n  Ltac try_not_eq := try solve [right; congruence].\n  destruct f1 as [| |? []|], f2 as [| |? []|];\n  try destruct b; try destruct b0;\n  try solve [left; auto]; try_not_eq.\n  destruct (positive_eq_dec x x0); try_not_eq;\n    subst; left; f_equal; f_equal; apply proof_irr.\n  destruct (positive_eq_dec x x0); try_not_eq;\n    subst; left; f_equal; f_equal; apply proof_irr.\n  destruct (positive_eq_dec m m0); try_not_eq;\n  destruct (Z_eq_dec e e1); try solve [right; intro H; inv H; congruence];\n  subst; left; rewrite (proof_irr e0 e2); auto.\n  destruct (positive_eq_dec m m0); try_not_eq;\n  destruct (Z_eq_dec e e1); try solve [right; intro H; inv H; congruence];\n  subst; left; rewrite (proof_irr e0 e2); auto.\nDefined.\n\n(* Transform a Nan payload to a quiet Nan payload.\n   This is not part of the IEEE754 standard, but shared between all\n   architectures of Compcert. *)\nProgram Definition transform_quiet_pl (pl:nan_pl 53) : nan_pl 53 :=\n  Pos.lor pl (nat_iter 51 xO xH).\nNext Obligation.\n  destruct pl.\n  simpl. rewrite Z.ltb_lt in *.\n  assert (forall x, S (Fcore_digits.digits2_Pnat x) = Pos.to_nat (Pos.size x)).\n  { induction x0; simpl; auto; rewrite IHx0; zify; omega. }\n  fold (Z.of_nat (S (Fcore_digits.digits2_Pnat (Pos.lor x 2251799813685248)))).\n  rewrite H, positive_nat_Z, Psize_log_inf, <- Zlog2_log_inf in *. clear H.\n  change (Z.pos (Pos.lor x 2251799813685248)) with (Z.lor (Z.pos x) 2251799813685248%Z).\n  rewrite Z.log2_lor by (zify; omega).\n  apply Z.max_case. auto. simpl. omega.\nQed.\n\nLemma nan_payload_fequal:\n  forall prec p1 e1 p2 e2, p1 = p2 -> (exist _ p1 e1:nan_pl prec) = exist _ p2 e2.\nProof.\n  simpl; intros; subst. f_equal. apply Fcore_Zaux.eqbool_irrelevance.\nQed.\n\nLemma lor_idempotent:\n  forall x y, Pos.lor (Pos.lor x y) y = Pos.lor x y.\nProof.\n  induction x; destruct y; simpl; f_equal; auto;\n  induction y; simpl; f_equal; auto.\nQed.\n\nLemma transform_quiet_pl_idempotent:\n  forall pl, transform_quiet_pl (transform_quiet_pl pl) = transform_quiet_pl pl.\nProof.\n  intros []; simpl; intros. apply nan_payload_fequal.\n  simpl. apply lor_idempotent.\nQed.\n\n(** Arithmetic operations *)\n\n(* The Nan payload operations for neg and abs is not part of the IEEE754\n   standard, but shared between all architectures of Compcert. *)\nDefinition neg_pl (s:bool) (pl:nan_pl 53) := (negb s, pl).\nDefinition abs_pl (s:bool) (pl:nan_pl 53) := (false, pl).\n\nDefinition neg: float -> float := b64_opp neg_pl. (**r opposite (change sign) *)\nDefinition abs (x: float): float := (**r absolute value (set sign to [+]) *)\n  match x with\n  | B754_nan s pl => let '(s, pl) := abs_pl s pl in B754_nan _ _ s pl\n  | B754_infinity _ => B754_infinity _ _ false\n  | B754_finite _ m e H => B754_finite _ _ false m e H\n  | B754_zero _ => B754_zero _ _ false\n  end.\n\nDefinition binary_normalize64 (m e:Z) (s:bool): float :=\n  binary_normalize 53 1024 eq_refl eq_refl mode_NE m e s.\n\nDefinition binary_normalize64_correct (m e:Z) (s:bool) :=\n  binary_normalize_correct 53 1024 eq_refl eq_refl mode_NE m e s.\nGlobal Opaque binary_normalize64_correct.\n\nDefinition binary_normalize32 (m e:Z) (s:bool) : binary32 :=\n  binary_normalize 24 128 eq_refl eq_refl mode_NE m e s.\n\nDefinition binary_normalize32_correct (m e:Z) (s:bool) :=\n  binary_normalize_correct 24 128 eq_refl eq_refl mode_NE m e s.\nGlobal Opaque binary_normalize32_correct.\n\n(* The Nan payload operations for single <-> double conversions are not part of\n   the IEEE754 standard, but shared between all architectures of Compcert. *)\nDefinition floatofbinary32_pl (s:bool) (pl:nan_pl 24) : (bool * nan_pl 53).\n  refine (s, transform_quiet_pl (exist _ (Pos.shiftl_nat (proj1_sig pl) 29) _)).\n  abstract (\n    destruct pl; unfold proj1_sig, Pos.shiftl_nat, nat_iter, Fcore_digits.digits2_Pnat;\n    fold (Fcore_digits.digits2_Pnat x);\n    rewrite Z.ltb_lt in *;\n    zify; omega).\nDefined.\n\nDefinition binary32offloat_pl (s:bool) (pl:nan_pl 53) : (bool * nan_pl 24).\n  refine (s, exist _ (Pos.shiftr_nat (proj1_sig (transform_quiet_pl pl)) 29) _).\n  abstract (\n    destruct (transform_quiet_pl pl); unfold proj1_sig, Pos.shiftr_nat, nat_iter;\n    rewrite Z.ltb_lt in *;\n    assert (forall x, Fcore_digits.digits2_Pnat (Pos.div2 x) =\n                      (Fcore_digits.digits2_Pnat x - 1)%nat) by (destruct x0; simpl; zify; omega);\n    rewrite !H, <- !NPeano.Nat.sub_add_distr; zify; omega).\nDefined.\n\nDefinition floatofbinary32 (f: binary32) : float := (**r single precision embedding in double precision *)\n  match f with\n    | B754_nan s pl => let '(s, pl) := floatofbinary32_pl s pl in B754_nan _ _ s pl\n    | B754_infinity s => B754_infinity _ _ s\n    | B754_zero s => B754_zero _ _ s\n    | B754_finite s m e _ =>\n      binary_normalize64 (cond_Zopp s (Zpos m)) e s\n  end.\n\nDefinition binary32offloat (f: float) : binary32 := (**r conversion to single precision *)\n  match f with\n    | B754_nan s pl => let '(s, pl) := binary32offloat_pl s pl in B754_nan _ _ s pl\n    | B754_infinity s => B754_infinity _ _ s\n    | B754_zero s => B754_zero _ _ s\n    | B754_finite s m e _ =>\n      binary_normalize32 (cond_Zopp s (Zpos m)) e s\n  end.\n\nDefinition singleoffloat (f: float): float := (**r conversion to single precision, embedded in double *)\n  floatofbinary32 (binary32offloat f).\n\nDefinition Zoffloat (f:float): option Z := (**r conversion to Z *)\n  match f with\n    | B754_finite s m (Zpos e) _ => Some (cond_Zopp s (Zpos m) * Zpower_pos radix2 e)\n    | B754_finite s m 0 _ => Some (cond_Zopp s (Zpos m))\n    | B754_finite s m (Zneg e) _ => Some (cond_Zopp s (Zpos m / Zpower_pos radix2 e))\n    | B754_zero _ => Some 0\n    | _ => None\n  end.\n\nDefinition intoffloat (f:float): option int := (**r conversion to signed 32-bit int *)\n  match Zoffloat f with\n    | Some n =>\n      if Zle_bool Int.min_signed n && Zle_bool n Int.max_signed then\n        Some (Int.repr n)\n      else\n        None\n    | None => None\n  end.\n\nDefinition intuoffloat (f:float): option int := (**r conversion to unsigned 32-bit int *)\n  match Zoffloat f with\n    | Some n =>\n      if Zle_bool 0 n && Zle_bool n Int.max_unsigned then\n        Some (Int.repr n)\n      else\n        None\n    | None => None\n  end.\n\nDefinition longoffloat (f:float): option int64 := (**r conversion to signed 64-bit int *)\n  match Zoffloat f with\n    | Some n =>\n      if Zle_bool Int64.min_signed n && Zle_bool n Int64.max_signed then\n        Some (Int64.repr n)\n      else\n        None\n    | None => None\n  end.\n\nDefinition longuoffloat (f:float): option int64 := (**r conversion to unsigned 64-bit int *)\n  match Zoffloat f with\n    | Some n =>\n      if Zle_bool 0 n && Zle_bool n Int64.max_unsigned then\n        Some (Int64.repr n)\n      else\n        None\n    | None => None\n  end.\n\n(* Functions used to parse floats *)\nProgram Definition build_from_parsed\n  (prec:Z) (emax:Z) (prec_gt_0 :Prec_gt_0 prec) (Hmax:prec < emax)\n  (base:positive) (intPart:positive) (expPart:Z) :=\n  match expPart return _ with\n    | Z0 =>\n      binary_normalize prec emax prec_gt_0 Hmax mode_NE (Zpos intPart) Z0 false\n    | Zpos p =>\n      binary_normalize prec emax prec_gt_0 Hmax mode_NE ((Zpos intPart) * Zpower_pos (Zpos base) p) Z0 false\n    | Zneg p =>\n      let exp := Zpower_pos (Zpos base) p in\n      match exp return 0 < exp -> _ with\n        | Zneg _ | Z0 => _\n        | Zpos p =>\n          fun _ =>\n          FF2B prec emax _ (proj1 (Bdiv_correct_aux prec emax prec_gt_0 Hmax mode_NE false intPart Z0 false p Z0))\n      end _\n  end.\nNext Obligation.\napply Zpower_pos_gt_0.\nreflexivity.\nQed.\n\nDefinition build_from_parsed64 (base:positive) (intPart:positive) (expPart:Z) : float :=\n  build_from_parsed 53 1024 eq_refl eq_refl  base intPart expPart.\n\nDefinition build_from_parsed32 (base:positive) (intPart:positive) (expPart:Z) : float :=\n  floatofbinary32 (build_from_parsed 24 128 eq_refl eq_refl  base intPart expPart).\n\nDefinition floatofint (n:int): float := (**r conversion from signed 32-bit int *)\n  binary_normalize64 (Int.signed n) 0 false.\nDefinition floatofintu (n:int): float:= (**r conversion from unsigned 32-bit int *)\n  binary_normalize64 (Int.unsigned n) 0 false.\n\nDefinition floatoflong (n:int64): float := (**r conversion from signed 64-bit int *)\n  binary_normalize64 (Int64.signed n) 0 false.\nDefinition floatoflongu (n:int64): float:= (**r conversion from unsigned 64-bit int *)\n  binary_normalize64 (Int64.unsigned n) 0 false.\n\nDefinition singleofint (n:int): float := (**r conversion from signed 32-bit int to single-precision float *)\n  floatofbinary32 (binary_normalize32 (Int.signed n) 0 false).\nDefinition singleofintu (n:int): float:= (**r conversion from unsigned 32-bit int to single-precision float *)\n  floatofbinary32 (binary_normalize32 (Int.unsigned n) 0 false).\n\nDefinition singleoflong (n:int64): float := (**r conversion from signed 64-bit int to single-precision float *)\n  floatofbinary32 (binary_normalize32 (Int64.signed n) 0 false).\nDefinition singleoflongu (n:int64): float:= (**r conversion from unsigned 64-bit int to single-precision float *)\n  floatofbinary32 (binary_normalize32 (Int64.unsigned n) 0 false).\n\n(* The Nan payload operations for two-argument arithmetic operations are not part of\n   the IEEE754 standard, but all architectures of Compcert share a similar\n   NaN behavior, parameterized by:\n- a \"default\" payload which occurs when an operation generates a NaN from\n  non-NaN arguments;\n- a choice function determining which of the payload arguments to choose,\n  when an operation is given two NaN arguments. *)\n\nDefinition binop_pl (x y: binary64) : bool*nan_pl 53 :=\n  match x, y with\n  | B754_nan s1 pl1, B754_nan s2 pl2 =>\n      if Archi.choose_binop_pl s1 pl1 s2 pl2\n      then (s2, transform_quiet_pl pl2)\n      else (s1, transform_quiet_pl pl1)\n  | B754_nan s1 pl1, _ => (s1, transform_quiet_pl pl1)\n  | _, B754_nan s2 pl2 => (s2, transform_quiet_pl pl2)\n  | _, _ => Archi.default_pl\n  end.\n\nDefinition add: float -> float -> float := b64_plus binop_pl mode_NE. (**r addition *)\nDefinition sub: float -> float -> float := b64_minus binop_pl mode_NE. (**r subtraction *)\nDefinition mul: float -> float -> float := b64_mult binop_pl mode_NE. (**r multiplication *)\nDefinition div: float -> float -> float := b64_div binop_pl mode_NE. (**r division *)\n\nDefinition order_float (f1 f2:float): option Datatypes.comparison :=\n  match f1, f2 with\n    | B754_nan _ _,_ | _,B754_nan _ _ => None\n    | B754_infinity true, B754_infinity true\n    | B754_infinity false, B754_infinity false => Some Eq\n    | B754_infinity true, _ => Some Lt\n    | B754_infinity false, _ => Some Gt\n    | _, B754_infinity true => Some Gt\n    | _, B754_infinity false => Some Lt\n    | B754_finite true _ _ _, B754_zero _ => Some Lt\n    | B754_finite false _ _ _, B754_zero _ => Some Gt\n    | B754_zero _, B754_finite true _ _ _ => Some Gt\n    | B754_zero _, B754_finite false _ _ _ => Some Lt\n    | B754_zero _, B754_zero _ => Some Eq\n    | B754_finite s1 m1 e1 _, B754_finite s2 m2 e2 _ =>\n      match s1, s2 with\n        | true, false => Some Lt\n        | false, true => Some Gt\n        | false, false =>\n          match Zcompare e1 e2 with\n            | Lt => Some Lt\n            | Gt => Some Gt\n            | Eq => Some (Pcompare m1 m2 Eq)\n          end\n        | true, true =>\n          match Zcompare e1 e2 with\n            | Lt => Some Gt\n            | Gt => Some Lt\n            | Eq => Some (CompOpp (Pcompare m1 m2 Eq))\n          end\n      end\n  end.\n\nDefinition cmp (c:comparison) (f1 f2:float) : bool := (**r comparison *)\n  match c with\n  | Ceq =>\n      match order_float f1 f2 with Some Eq => true | _ => false end\n  | Cne =>\n      match order_float f1 f2 with Some Eq => false | _ => true end\n  | Clt =>\n      match order_float f1 f2 with Some Lt => true | _ => false end\n  | Cle =>\n      match order_float f1 f2 with Some(Lt|Eq) => true | _ => false end\n  | Cgt =>\n      match order_float f1 f2 with Some Gt => true | _ => false end\n  | Cge =>\n      match order_float f1 f2 with Some(Gt|Eq) => true | _ => false end\n  end.\n\n(** Conversions between floats and their concrete in-memory representation\n    as a sequence of 64 bits (double precision) or 32 bits (single precision). *)\n\nDefinition bits_of_double (f: float): int64 := Int64.repr (bits_of_b64 f).\nDefinition double_of_bits (b: int64): float := b64_of_bits (Int64.unsigned b).\n\nDefinition bits_of_single (f: float) : int := Int.repr (bits_of_b32 (binary32offloat f)).\nDefinition single_of_bits (b: int): float := floatofbinary32 (b32_of_bits (Int.unsigned b)).\n\nDefinition from_words (hi lo: int) : float := double_of_bits (Int64.ofwords hi lo).\n\n(** Below are the only properties of floating-point arithmetic that we\n  rely on in the compiler proof. *)\n\n(** Some tactics **)\n\nLtac compute_this val :=\n  let x := fresh in set val as x in *; vm_compute in x; subst x.\n\nLtac smart_omega :=\n  simpl radix_val in *; simpl Zpower in *;\n  compute_this Int.modulus; compute_this Int.half_modulus;\n  compute_this Int.max_unsigned;\n  compute_this Int.min_signed; compute_this Int.max_signed;\n  compute_this Int64.modulus; compute_this Int64.half_modulus;\n  compute_this Int64.max_unsigned;\n  compute_this (Zpower_pos 2 1024); compute_this (Zpower_pos 2 53); compute_this (Zpower_pos 2 52);\n  zify; omega.\n\nLemma floatofbinary32_exact :\n  forall f, is_finite_strict _ _ f = true ->\n    is_finite_strict _ _ (floatofbinary32 f) = true /\\ B2R _ _ f = B2R _ _ (floatofbinary32 f).\nProof.\n  destruct f as [ | | |s m e]; try discriminate; intro.\n  pose proof (binary_normalize64_correct (cond_Zopp s (Zpos m)) e s).\n  match goal with [H0:if Rlt_bool (Rabs ?x) _ then _ else _ |- _ /\\ ?y = _] => assert (x=y)%R end.\n  apply round_generic; [now apply valid_rnd_round_mode|].\n  apply (generic_inclusion_ln_beta _ (FLT_exp (3 - 128 - 24) 24)).\n  intro; eapply Zle_trans; [apply Zle_max_compat_l | apply Zle_max_compat_r]; omega.\n  apply generic_format_canonic; apply canonic_canonic_mantissa; apply (proj1 (andb_prop _ _ e0)).\n  rewrite H1, Rlt_bool_true in H0; intuition; unfold floatofbinary32, binary_normalize64.\n  match goal with [ |- _ _ _ ?x = true ] => destruct x end; try discriminate.\n  symmetry in H2; apply F2R_eq_0_reg in H2; destruct s; discriminate.\n  reflexivity.\n  eapply Rlt_trans.\n  unfold B2R; rewrite <- F2R_Zabs, abs_cond_Zopp; eapply bounded_lt_emax; now apply e0.\n  now apply bpow_lt.\nQed.\n\nLemma binary32offloatofbinary32_num :\n  forall f, is_nan _ _ f = false ->\n            binary32offloat (floatofbinary32 f) = f.\nProof.\n  intros f Hnan; pose proof (floatofbinary32_exact f); destruct f as [ | | |s m e]; try reflexivity.\n  discriminate.\n  specialize (H eq_refl); destruct H.\n  destruct (floatofbinary32 (B754_finite 24 128 s m e e0)) as [ | | |s1 m1 e1]; try discriminate.\n  unfold binary32offloat.\n  pose proof (binary_normalize32_correct (cond_Zopp s1 (Zpos m1)) e1 s1).\n  unfold B2R at 2 in H0; cbv iota zeta beta in H0; rewrite <- H0, round_generic in H1.\n  rewrite Rlt_bool_true in H1.\n  unfold binary_normalize32.\n  apply B2R_inj; intuition; match goal with [|- _ _ _ ?f = true] => destruct f end; try discriminate.\n  symmetry in H2; apply F2R_eq_0_reg in H2; destruct s; discriminate.\n  reflexivity.\n  unfold B2R; rewrite <- F2R_Zabs, abs_cond_Zopp; eapply bounded_lt_emax; apply e0.\n  now apply valid_rnd_round_mode.\n  now apply generic_format_B2R.\nQed.\n\nLemma floatofbinary32offloatofbinary32_pl:\n  forall s pl,\n    prod_rect (fun _ => _) floatofbinary32_pl (prod_rect (fun _ => _) binary32offloat_pl (floatofbinary32_pl s pl)) = floatofbinary32_pl s pl.\nProof.\n  destruct pl. unfold binary32offloat_pl, floatofbinary32_pl.\n  unfold transform_quiet_pl, proj1_sig. simpl.\n  f_equal. apply nan_payload_fequal.\n  unfold Pos.shiftr_nat. simpl.\n  rewrite !lor_idempotent. reflexivity.\nQed.\n\nLemma floatofbinary32offloatofbinary32 :\n  forall f, floatofbinary32 (binary32offloat (floatofbinary32 f)) = floatofbinary32 f.\nProof.\n  destruct f; try (rewrite binary32offloatofbinary32_num; tauto).\n  unfold floatofbinary32, binary32offloat.\n  rewrite <- floatofbinary32offloatofbinary32_pl at 2.\n  reflexivity.\nQed.\n\nLemma binary32offloatofbinary32offloat_pl:\n  forall s pl,\n    prod_rect (fun _ => _) binary32offloat_pl (prod_rect  (fun _ => _) floatofbinary32_pl (binary32offloat_pl s pl)) = binary32offloat_pl s pl.\nProof.\n  destruct pl. unfold binary32offloat_pl, floatofbinary32_pl. unfold prod_rect.\n  f_equal. apply nan_payload_fequal.\n  rewrite transform_quiet_pl_idempotent.\n  unfold transform_quiet_pl, proj1_sig.\n  change 51 with (29+22).\n  clear - x. revert x. unfold Pos.shiftr_nat, Pos.shiftl_nat.\n  induction (29)%nat. intro. simpl. apply lor_idempotent.\n  intro.\n  rewrite !nat_iter_succ_r with (f:=Pos.div2).\n  destruct x; simpl; try apply IHn.\n  clear IHn. induction n. reflexivity.\n  rewrite !nat_iter_succ_r with (f:=Pos.div2). auto.\nQed.\n\nLemma binary32offloatofbinary32offloat :\n  forall f, binary32offloat (floatofbinary32 (binary32offloat f)) = binary32offloat f.\nProof.\n  destruct f; try (rewrite binary32offloatofbinary32_num; simpl; tauto).\n  unfold floatofbinary32, binary32offloat.\n  rewrite <- binary32offloatofbinary32offloat_pl at 2.\n  reflexivity.\n  rewrite binary32offloatofbinary32_num; simpl. auto.\n  unfold binary_normalize32.\n  pose proof (binary_normalize32_correct (cond_Zopp b (Z.pos m)) e b).\n  destruct binary_normalize; auto. simpl in H.\n  destruct Rlt_bool in H. intuition.\n  unfold binary_overflow in H. destruct n.\n  destruct overflow_to_inf in H; discriminate.\nQed.\n\nTheorem singleoffloat_idem:\n  forall f, singleoffloat (singleoffloat f) = singleoffloat f.\nProof.\n  intros; unfold singleoffloat; rewrite binary32offloatofbinary32offloat; reflexivity.\nQed.\n\nTheorem singleoflong_idem:\n  forall n, singleoffloat (singleoflong n) = singleoflong n.\nProof.\n  intros; unfold singleoffloat, singleoflong. rewrite floatofbinary32offloatofbinary32; reflexivity.\nQed.\n\nTheorem singleoflongu_idem:\n  forall n, singleoffloat (singleoflongu n) = singleoflongu n.\nProof.\n  intros; unfold singleoffloat, singleoflongu. rewrite floatofbinary32offloatofbinary32; reflexivity.\nQed.\n\nDefinition is_single (f: float) : Prop := exists s, f = floatofbinary32 s.\n\nTheorem singleoffloat_is_single:\n  forall f, is_single (singleoffloat f).\nProof.\n  intros. exists (binary32offloat f); auto.\nQed.\n\nTheorem singleoffloat_of_single:\n  forall f, is_single f -> singleoffloat f = f.\nProof.\n  intros. destruct H as [s EQ]. subst f. unfold singleoffloat.\n  apply floatofbinary32offloatofbinary32.\nQed.\n\nTheorem is_single_dec: forall f, {is_single f} + {~is_single f}.\nProof.\n  intros. case (eq_dec (singleoffloat f) f); intros.\n  unfold singleoffloat in e. left. exists (binary32offloat f). auto.\n  right; red; intros; elim n. apply singleoffloat_of_single; auto.\nDefined.\n\n(** Commutativity properties of addition and multiplication. *)\n\nTheorem add_commut:\n  forall x y, is_nan _ _ x = false \\/ is_nan _ _ y = false -> add x y = add y x.\nProof.\n  intros x y NAN. unfold add, b64_plus. \n  pose proof (Bplus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE x y).\n  pose proof (Bplus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE y x).\n  unfold Bplus in *; destruct x; destruct y; auto.\n- rewrite (eqb_sym b0 b). destruct (eqb b b0) eqn:EQB; auto. f_equal; apply eqb_prop; auto.\n- rewrite (eqb_sym b0 b). destruct (eqb b b0) eqn:EQB.\n  f_equal; apply eqb_prop; auto.\n  auto.\n- simpl in NAN; intuition congruence.\n- exploit H; auto. clear H. exploit H0; auto. clear H0. \n  set (x := B754_finite 53 1024 b0 m0 e1 e2). \n  set (rx := B2R 53 1024 x).\n  set (y := B754_finite 53 1024 b m e e0).\n  set (ry := B2R 53 1024 y).\n  rewrite (Rplus_comm ry rx). destruct Rlt_bool. \n  intros (A1 & A2 & A3) (B1 & B2 & B3).\n  apply B2R_Bsign_inj; auto. rewrite <- B1 in A1. auto. \n  rewrite Z.add_comm. rewrite Z.min_comm. auto.\n  intros (A1 & A2) (B1 & B2). apply B2FF_inj. rewrite B2 in B1. rewrite <- B1 in A1. auto. \nQed.\n\nTheorem mul_commut:\n  forall x y, is_nan _ _ x = false \\/ is_nan _ _ y = false -> mul x y = mul y x.\nProof.\n  intros x y NAN. unfold mul, b64_mult. \n  pose proof (Bmult_correct 53 1024 eq_refl eq_refl binop_pl mode_NE x y).\n  pose proof (Bmult_correct 53 1024 eq_refl eq_refl binop_pl mode_NE y x).\n  unfold Bmult in *; destruct x; destruct y; auto.\n- f_equal. apply xorb_comm. \n- f_equal. apply xorb_comm. \n- f_equal. apply xorb_comm. \n- f_equal. apply xorb_comm. \n- simpl in NAN. intuition congruence.\n- f_equal. apply xorb_comm. \n- f_equal. apply xorb_comm. \n- set (x := B754_finite 53 1024 b0 m0 e1 e2) in *. \n  set (rx := B2R 53 1024 x) in *.\n  set (y := B754_finite 53 1024 b m e e0) in *.\n  set (ry := B2R 53 1024 y) in *.\n  rewrite (Rmult_comm ry rx) in *. destruct Rlt_bool. \n  destruct H as (A1 & A2 & A3); destruct H0 as (B1 & B2 & B3).\n  apply B2R_Bsign_inj; auto. rewrite <- B1 in A1. auto. \n  rewrite ! Bsign_FF2B. f_equal. f_equal. apply xorb_comm. apply Pos.mul_comm. apply Z.add_comm.\n  apply B2FF_inj. etransitivity. eapply H. rewrite xorb_comm. auto. \nQed.\n\n(** Properties of comparisons. *)\n\nTheorem order_float_finite_correct:\n  forall f1 f2, is_finite _ _ f1 = true -> is_finite _ _ f2 = true ->\n    match order_float f1 f2 with\n      | Some c => Rcompare (B2R _ _ f1) (B2R _ _ f2) = c\n      | None => False\n    end.\nProof.\n  Ltac apply_Rcompare :=\n    match goal with\n      | [ |- Rcompare _ _ = Lt ] => apply Rcompare_Lt\n      | [ |- Rcompare _ _ = Eq ] => apply Rcompare_Eq\n      | [ |- Rcompare _ _ = Gt ] => apply Rcompare_Gt\n    end.\n  unfold order_float; intros.\n  destruct f1, f2; try discriminate; unfold B2R, F2R, Fnum, Fexp, cond_Zopp;\n    try (replace 0%R with (Z2R 0 * bpow radix2 e)%R by (simpl Z2R; ring);\n         rewrite Rcompare_mult_r by (apply bpow_gt_0); rewrite Rcompare_Z2R).\n  apply_Rcompare; reflexivity.\n  destruct b0; reflexivity.\n  destruct b; reflexivity.\n  clear H H0.\n  apply andb_prop in e0; destruct e0; apply (canonic_canonic_mantissa _ _ false) in H.\n  apply andb_prop in e2; destruct e2; apply (canonic_canonic_mantissa _ _ false) in H1.\n  pose proof (Zcompare_spec e e1); unfold canonic, Fexp in H1, H.\n  assert (forall m1 m2 e1 e2,\n    let x := (Z2R (Zpos m1) * bpow radix2 e1)%R in\n    let y := (Z2R (Zpos m2) * bpow radix2 e2)%R in\n    canonic_exp radix2 (FLT_exp (3-1024-53) 53) x < canonic_exp radix2 (FLT_exp (3-1024-53) 53) y -> (x < y)%R).\n  intros; apply Rnot_le_lt; intro; apply (ln_beta_le radix2) in H5.\n  apply (fexp_monotone 53 1024) in H5; unfold canonic_exp in H4; omega.\n  apply Rmult_gt_0_compat; [apply (Z2R_lt 0); reflexivity|now apply bpow_gt_0].\n  assert (forall m1 m2 e1 e2, (Z2R (- Zpos m1) * bpow radix2 e1 < Z2R (Zpos m2) * bpow radix2 e2)%R).\n  intros; apply (Rlt_trans _ 0%R).\n  replace 0%R with (0*bpow radix2 e0)%R by ring; apply Rmult_lt_compat_r;\n    [apply bpow_gt_0; reflexivity|now apply (Z2R_lt _ 0)].\n  apply Rmult_gt_0_compat; [apply (Z2R_lt 0); reflexivity|now apply bpow_gt_0].\n  destruct b, b0; try (now apply_Rcompare; apply H5); inversion H3;\n    try (apply_Rcompare; apply H4; rewrite H, H1 in H7; assumption);\n    try (apply_Rcompare; do 2 rewrite Z2R_opp, Ropp_mult_distr_l_reverse;\n      apply Ropp_lt_contravar; apply H4; rewrite H, H1 in H7; assumption);\n    rewrite H7, Rcompare_mult_r, Rcompare_Z2R by (apply bpow_gt_0); reflexivity.\nQed.\n\nTheorem cmp_swap:\n  forall c x y, Float.cmp (swap_comparison c) x y = Float.cmp c y x.\nProof.\n  destruct c, x, y; simpl; try destruct b; try destruct b0; try reflexivity;\n  rewrite <- (Zcompare_antisym e e1); destruct (e ?= e1); try reflexivity;\n  change Eq with (CompOpp Eq); rewrite <- (Pcompare_antisym m m0 Eq);\n    simpl; destruct (Pcompare m m0 Eq); reflexivity.\nQed.\n\nTheorem cmp_ne_eq:\n  forall f1 f2, cmp Cne f1 f2 = negb (cmp Ceq f1 f2).\nProof.\n  unfold cmp; intros; destruct (order_float f1 f2) as [ [] | ]; reflexivity.\nQed.\n\nTheorem cmp_lt_eq_false:\n  forall f1 f2, cmp Clt f1 f2 = true -> cmp Ceq f1 f2 = true -> False.\nProof.\n  unfold cmp; intros; destruct (order_float f1 f2) as [ [] | ]; discriminate.\nQed.\n\nTheorem cmp_le_lt_eq:\n  forall f1 f2, cmp Cle f1 f2 = cmp Clt f1 f2 || cmp Ceq f1 f2.\nProof.\n  unfold cmp; intros; destruct (order_float f1 f2) as [ [] | ]; reflexivity.\nQed.\n\nCorollary cmp_gt_eq_false:\n  forall x y, cmp Cgt x y = true -> cmp Ceq x y = true -> False.\nProof.\n  intros; rewrite <- cmp_swap in H; rewrite <- cmp_swap in H0;\n  eapply cmp_lt_eq_false; now eauto.\nQed.\n\nCorollary cmp_ge_gt_eq:\n  forall f1 f2, cmp Cge f1 f2 = cmp Cgt f1 f2 || cmp Ceq f1 f2.\nProof.\n  intros.\n  change Cge with (swap_comparison Cle); change Cgt with (swap_comparison Clt);\n    change Ceq with (swap_comparison Ceq).\n  repeat rewrite cmp_swap.\n  now apply cmp_le_lt_eq.\nQed.\n\nTheorem cmp_lt_gt_false:\n  forall f1 f2, cmp Clt f1 f2 = true -> cmp Cgt f1 f2 = true -> False.\nProof.\n  unfold cmp; intros; destruct (order_float f1 f2) as [ [] | ]; discriminate.\nQed.\n\n(** Properties of conversions to/from in-memory representation.\n  The double-precision conversions are bijective (one-to-one).\n  The single-precision conversions lose precision exactly\n  as described by [singleoffloat] rounding. *)\n\nTheorem double_of_bits_of_double:\n  forall f, double_of_bits (bits_of_double f) = f.\nProof.\n  intros; unfold double_of_bits, bits_of_double, bits_of_b64, b64_of_bits.\n  rewrite Int64.unsigned_repr, binary_float_of_bits_of_binary_float; [reflexivity|].\n  destruct f.\n  simpl; try destruct b; vm_compute; split; congruence.\n  simpl; try destruct b; vm_compute; split; congruence.\n  destruct n as [p Hp].\n  simpl. rewrite Z.ltb_lt in Hp.\n  apply Zlt_succ_le with (m:=52) in Hp.\n  apply Zpower_le with (r:=radix2) in Hp.\n  edestruct Fcore_digits.digits2_Pnat_correct.\n  rewrite Zpower_nat_Z in H0.\n  eapply Z.lt_le_trans in Hp; eauto.\n  unfold join_bits; destruct b.\n  compute_this ((2 ^ 11 + 2047) * 2 ^ 52). smart_omega.\n  compute_this ((0 + 2047) * 2 ^ 52). smart_omega.\n  unfold bits_of_binary_float, join_bits.\n  destruct (andb_prop _ _ e0); apply Zle_bool_imp_le in H0; apply Zeq_bool_eq in H; unfold FLT_exp in H.\n  match goal with [H:Zmax ?x ?y = e|-_] => pose proof (Zle_max_l x y); pose proof (Zle_max_r x y) end.\n  rewrite H, Fcalc_digits.Z_of_nat_S_digits2_Pnat in *.\n  lapply (Fcalc_digits.Zpower_gt_Zdigits radix2 53 (Zpos m)). intro.\n  unfold radix2, radix_val, Zabs in H3.\n  pose proof (Zle_bool_spec (2 ^ 52) (Zpos m)).\n  assert (Zpos m > 0); [vm_compute; exact eq_refl|].\n  compute_this (2^11); compute_this (2^(11-1)).\n  inversion H4; fold (2^52) in *; destruct H6; destruct b; now smart_omega.\n  change Fcalc_digits.radix2 with radix2 in H1; omega.\nQed.\n\nTheorem single_of_bits_of_single:\n  forall f, single_of_bits (bits_of_single f) = singleoffloat f.\nProof.\n  intros; unfold single_of_bits, bits_of_single, bits_of_b32, b32_of_bits.\n  rewrite Int.unsigned_repr, binary_float_of_bits_of_binary_float; [reflexivity|].\n  destruct (binary32offloat f).\n  simpl; try destruct b; vm_compute; split; congruence.\n  simpl; try destruct b; vm_compute; split; congruence.\n  destruct n as [p Hp].\n  simpl. rewrite Z.ltb_lt in Hp.\n  apply Zlt_succ_le with (m:=23) in Hp.\n  apply Zpower_le with (r:=radix2) in Hp.\n  edestruct Fcore_digits.digits2_Pnat_correct.\n  rewrite Zpower_nat_Z in H0.\n  eapply Z.lt_le_trans in Hp; eauto.\n  compute_this (radix2^23).\n  unfold join_bits; destruct b.\n  compute_this ((2 ^ 8 + 255) * 2 ^ 23). smart_omega.\n  compute_this ((0 + 255) * 2 ^ 23). smart_omega.\n  unfold bits_of_binary_float, join_bits.\n  destruct (andb_prop _ _ e0); apply Zle_bool_imp_le in H0; apply Zeq_bool_eq in H.\n  unfold FLT_exp in H.\n  match goal with [H:Zmax ?x ?y = e|-_] => pose proof (Zle_max_l x y); pose proof (Zle_max_r x y) end.\n  rewrite H, Fcalc_digits.Z_of_nat_S_digits2_Pnat in *.\n  lapply (Fcalc_digits.Zpower_gt_Zdigits radix2 24 (Zpos m)). intro.\n  unfold radix2, radix_val, Zabs in H3.\n  pose proof (Zle_bool_spec (2 ^ 23) (Zpos m)).\n  compute_this (2^23); compute_this (2^24); compute_this (2^8); compute_this (2^(8-1)).\n  assert (Zpos m > 0); [exact eq_refl|].\n  inversion H4; destruct b; now smart_omega.\n  change Fcalc_digits.radix2 with radix2 in H1; omega.\nQed.\n\nTheorem bits_of_singleoffloat:\n  forall f, bits_of_single (singleoffloat f) = bits_of_single f.\nProof.\n  intro; unfold singleoffloat, bits_of_single; rewrite binary32offloatofbinary32offloat; reflexivity.\nQed.\n\nTheorem singleoffloat_of_bits:\n  forall b, singleoffloat (single_of_bits b) = single_of_bits b.\nProof.\n  intro; unfold singleoffloat, single_of_bits; rewrite floatofbinary32offloatofbinary32; reflexivity.\nQed.\n\nTheorem single_of_bits_is_single:\n  forall b, is_single (single_of_bits b).\nProof.\n  intros. exists (b32_of_bits (Int.unsigned b)); auto.\nQed.\n\n(** Conversions between floats and unsigned ints can be defined\n  in terms of conversions between floats and signed ints.\n  (Most processors provide only the latter, forcing the compiler\n  to emulate the former.)   *)\n\nDefinition ox8000_0000 := Int.repr Int.half_modulus.  (**r [0x8000_0000] *)\n\nLemma round_exact:\n  forall n, -2^53 < n < 2^53 ->\n    round radix2 (FLT_exp (3 - 1024 - 53) 53)\n      (round_mode mode_NE) (Z2R n) = Z2R n.\nProof.\n  intros; rewrite round_generic; [reflexivity|now apply valid_rnd_round_mode|].\n  apply generic_format_FLT; exists (Float radix2 n 0).\n  unfold F2R, Fnum, Fexp, bpow; rewrite Rmult_1_r; intuition.\n  pose proof (Zabs_spec n); now smart_omega.\nQed.\n\nLemma binary_normalize64_exact:\n  forall n, -2^53 < n < 2^53 ->\n    B2R _ _ (binary_normalize64 n 0 false) = Z2R n /\\\n    is_finite _ _ (binary_normalize64 n 0 false) = true.\nProof.\n  intros; pose proof (binary_normalize64_correct n 0 false).\n  unfold F2R, Fnum, Fexp, bpow in H0; rewrite Rmult_1_r, round_exact, Rlt_bool_true in H0; try now intuition.\n  rewrite <- Z2R_abs; apply Z2R_lt; pose proof (Zabs_spec n); now smart_omega.\nQed.\n\nTheorem floatofintu_floatofint_1:\n  forall x,\n  Int.ltu x ox8000_0000 = true ->\n  floatofintu x = floatofint x.\nProof.\n  unfold floatofintu, floatofint, Int.signed, Int.ltu; intro.\n  change (Int.unsigned ox8000_0000) with Int.half_modulus.\n  destruct (zlt (Int.unsigned x) Int.half_modulus); now intuition.\nQed.\n\nTheorem floatofintu_floatofint_2:\n  forall x,\n  Int.ltu x ox8000_0000 = false ->\n  floatofintu x = add (floatofint (Int.sub x ox8000_0000))\n                      (floatofintu ox8000_0000).\nProof.\n  unfold floatofintu, floatofint, Int.signed, Int.ltu, Int.sub; intros.\n  pose proof (Int.unsigned_range x).\n  compute_this (Int.unsigned ox8000_0000).\n  destruct (zlt (Int.unsigned x) 2147483648); try  discriminate.\n  rewrite Int.unsigned_repr by smart_omega.\n  destruct (zlt ((Int.unsigned x) - 2147483648) Int.half_modulus).\n  unfold add, b64_plus.\n  match goal with [|- _ = Bplus _ _ _ _ _ _ ?x ?y] =>\n    pose proof (Bplus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE x y) end.\n  do 2 rewrite (fun x H => proj1 (binary_normalize64_exact x H)) in H1 by smart_omega.\n  do 2 rewrite (fun x H => proj2 (binary_normalize64_exact x H)) in H1 by smart_omega.\n  rewrite <- Z2R_plus, round_exact in H1 by smart_omega.\n  rewrite Rlt_bool_true in H1;\n    replace (Int.unsigned x - 2147483648 + 2147483648) with (Int.unsigned x) in * by ring.\n  apply B2R_inj.\n  destruct (binary_normalize64_exact (Int.unsigned x)); [now smart_omega|].\n  match goal with [|- _ _ _ ?f = _] => destruct f end; intuition.\n  exfalso; simpl in H2; change 0%R with (Z2R 0) in H2; apply eq_Z2R in H2; omega.\n  try (change (53 ?= 1024) with Lt in H1).  (* for Coq 8.4 *)\n  simpl Zcompare in *.\n  match goal with [|- _ _ _ ?f = _] => destruct f end; intuition.\n  exfalso; simpl in H0; change 0%R with (Z2R 0) in H0; apply eq_Z2R in H0; omega.\n  rewrite (fun x H => proj1 (binary_normalize64_exact x H)) by smart_omega; now intuition.\n  rewrite <- Z2R_Zpower, <- Z2R_abs by omega; apply Z2R_lt;\n    pose proof (Zabs_spec (Int.unsigned x)); now smart_omega.\n  exfalso; now smart_omega.\nQed.\n\nLemma Zoffloat_correct:\n  forall f,\n    match Zoffloat f with\n      | Some n =>\n        is_finite _ _ f = true /\\\n        Z2R n = round radix2 (FIX_exp 0) (round_mode mode_ZR) (B2R _ _ f)\n      | None =>\n        is_finite _ _ f = false\n    end.\nProof.\n  destruct f; try now intuition.\n  simpl B2R. rewrite round_0. now intuition. now apply valid_rnd_round_mode.\n  destruct e. split. reflexivity.\n  rewrite round_generic. symmetry. now apply Rmult_1_r.\n  now apply valid_rnd_round_mode.\n  apply generic_format_FIX. exists (Float radix2 (cond_Zopp b (Zpos m)) 0). split; reflexivity.\n  split; [reflexivity|].\n  rewrite round_generic, Z2R_mult, Z2R_Zpower_pos, <- bpow_powerRZ;\n    [reflexivity|now apply valid_rnd_round_mode|apply generic_format_F2R; discriminate].\n  rewrite (inbetween_float_ZR_sign _ _ _ ((Zpos m) / Zpower_pos radix2 p)\n    (new_location (Zpower_pos radix2 p) (Zpos m mod Zpower_pos radix2 p) loc_Exact)).\n  unfold B2R, F2R, Fnum, Fexp, canonic_exp, bpow, FIX_exp, Zoffloat, radix2, radix_val.\n  pose proof (Rlt_bool_spec (Z2R (cond_Zopp b (Zpos m)) * / Z2R (Zpower_pos 2 p)) 0).\n  inversion H; rewrite <- (Rmult_0_l (bpow radix2 (Zneg p))) in H1.\n  apply Rmult_lt_reg_r in H1. apply (lt_Z2R _ 0) in H1.\n  destruct b; [split; [|ring_simplify];reflexivity|discriminate].\n  now apply bpow_gt_0.\n  apply Rmult_le_reg_r in H1. apply (le_Z2R 0) in H1.\n  destruct b; [destruct H1|split; [|ring_simplify]]; reflexivity.\n  now apply (bpow_gt_0 radix2 (Zneg p)).\n  unfold canonic_exp, FIX_exp; replace 0 with (Zneg p + Zpos p) by apply Zplus_opp_r.\n  apply (inbetween_float_new_location radix2 _ _ _ _ (Zpos p)); [reflexivity|].\n  apply inbetween_Exact; unfold B2R, F2R, Fnum, Fexp; destruct b.\n  rewrite  Rabs_left; [simpl; ring_simplify; reflexivity|].\n  replace 0%R with (0*(bpow radix2 (Zneg p)))%R by ring; apply Rmult_gt_compat_r.\n  now apply bpow_gt_0.\n  apply (Z2R_lt _ 0); reflexivity.\n  apply Rabs_right; replace 0%R with (0*(bpow radix2 (Zneg p)))%R by ring; apply Rgt_ge.\n  apply Rmult_gt_compat_r; [now apply bpow_gt_0|apply (Z2R_lt 0); reflexivity].\nQed.\n\nTheorem intoffloat_correct:\n  forall f,\n    match intoffloat f with\n      | Some n =>\n        is_finite _ _ f = true /\\\n        Z2R (Int.signed n) = round radix2 (FIX_exp 0) (round_mode mode_ZR) (B2R _ _ f)\n      | None =>\n        is_finite _ _ f = false \\/\n        (B2R _ _ f <= Z2R (Zpred Int.min_signed)\\/\n        Z2R (Zsucc Int.max_signed) <= B2R _ _ f)%R\n    end.\nProof.\n  intro; pose proof (Zoffloat_correct f); unfold intoffloat; destruct (Zoffloat f).\n  pose proof (Zle_bool_spec Int.min_signed z); pose proof (Zle_bool_spec z Int.max_signed). \n  compute_this Int.min_signed; compute_this Int.max_signed; destruct H.\n  inversion H0; [inversion H1|].\n  rewrite <- (Int.signed_repr z) in H2 by smart_omega; split; assumption.\n  right; right; eapply Rle_trans; [apply Z2R_le; apply Zlt_le_succ; now apply H6|].\n  rewrite H2, round_ZR_pos.\n  unfold round, scaled_mantissa, canonic_exp, FIX_exp, F2R, Fnum, Fexp; simpl bpow.\n  do 2 rewrite Rmult_1_r; now apply Zfloor_lb.\n  apply Rnot_lt_le; intro; apply Rlt_le in H7; apply (round_le radix2 (FIX_exp 0) (round_mode mode_ZR)) in H7;\n    rewrite <- H2, round_0 in H7; [apply (le_Z2R _ 0) in H7; now smart_omega|now apply valid_rnd_round_mode].\n  right; left; eapply Rle_trans; [|apply (Z2R_le z); simpl; omega].\n  rewrite H2, round_ZR_neg.\n  unfold round, scaled_mantissa, canonic_exp, FIX_exp, F2R, Fnum, Fexp; simpl bpow.\n  do 2 rewrite Rmult_1_r; now apply Zceil_ub.\n  apply Rnot_lt_le; intro; apply Rlt_le in H5; apply (round_le radix2 (FIX_exp 0) (round_mode mode_ZR)) in H5.\n  rewrite <- H2, round_0 in H5; [apply (le_Z2R 0) in H5; omega|now apply valid_rnd_round_mode].\n  left; assumption.\nQed.\n\nTheorem intuoffloat_correct:\n  forall f,\n    match intuoffloat f with\n      | Some n =>\n        is_finite _ _ f = true /\\\n        Z2R (Int.unsigned n) = round radix2 (FIX_exp 0) (round_mode mode_ZR) (B2R _ _ f)\n      | None =>\n        is_finite _ _ f = false \\/\n        (B2R _ _ f <= -1 \\/\n        Z2R (Zsucc Int.max_unsigned) <= B2R _ _ f)%R\n    end.\nProof.\n  intro; pose proof (Zoffloat_correct f); unfold intuoffloat; destruct (Zoffloat f).\n  pose proof (Zle_bool_spec 0 z); pose proof (Zle_bool_spec z Int.max_unsigned).\n  compute_this Int.max_unsigned; destruct H.\n  inversion H0. inversion H1.\n  rewrite <- (Int.unsigned_repr z) in H2 by smart_omega; split; assumption.\n  right; right; eapply Rle_trans; [apply Z2R_le; apply Zlt_le_succ; now apply H6|].\n  rewrite H2, round_ZR_pos.\n  unfold round, scaled_mantissa, canonic_exp, FIX_exp, F2R, Fnum, Fexp; simpl bpow;\n    do 2 rewrite Rmult_1_r; now apply Zfloor_lb.\n  apply Rnot_lt_le; intro; apply Rlt_le in H7; eapply (round_le radix2 (FIX_exp 0) (round_mode mode_ZR)) in H7;\n    rewrite <- H2, round_0 in H7; [apply (le_Z2R _ 0) in H7; now smart_omega|now apply valid_rnd_round_mode].\n  right; left; eapply Rle_trans; [|change (-1)%R with (Z2R (-1)); apply (Z2R_le z); omega].\n  rewrite H2, round_ZR_neg; unfold round, scaled_mantissa, canonic_exp, FIX_exp, F2R, Fnum, Fexp; simpl bpow.\n  do 2 rewrite Rmult_1_r; now apply Zceil_ub.\n  apply Rnot_lt_le; intro; apply Rlt_le in H5; apply (round_le radix2 (FIX_exp 0) (round_mode mode_ZR)) in H5;\n    rewrite <- H2, round_0 in H5; [apply (le_Z2R 0) in H5; omega|now apply valid_rnd_round_mode].\n  left; assumption.\nQed.\n\nLemma intuoffloat_interval:\n  forall f n,\n    intuoffloat f = Some n ->\n    (-1 < B2R _ _ f < Z2R (Zsucc Int.max_unsigned))%R.\nProof.\n  intro; pose proof (intuoffloat_correct f); destruct (intuoffloat f); try discriminate; destruct H.\n  destruct f; try discriminate; intros.\n  simpl B2R; change 0%R with (Z2R 0); change (-1)%R with (Z2R (-1)); split; apply Z2R_lt; reflexivity.\n  pose proof (Int.unsigned_range i).\n  unfold round, scaled_mantissa, B2R, F2R, Fnum, Fexp in H0 |- *; simpl bpow in H0; do 2 rewrite Rmult_1_r in H0;\n    apply eq_Z2R in H0.\n  split; apply Rnot_le_lt; intro.\n  rewrite Ztrunc_ceil in H0;\n    [apply Zceil_le in H3; change (-1)%R with (Z2R (-1)) in H3; rewrite Zceil_Z2R in H3; omega|].\n  eapply Rle_trans; [now apply H3|apply (Z2R_le (-1) 0); discriminate].\n  rewrite Ztrunc_floor in H0; [apply Zfloor_le in H3; rewrite Zfloor_Z2R in H3; now smart_omega|].\n  eapply Rle_trans; [|now apply H3]; apply (Z2R_le 0); discriminate.\nQed.\n\nTheorem intuoffloat_intoffloat_1:\n  forall x n,\n  cmp Clt x (floatofintu ox8000_0000) = true ->\n  intuoffloat x = Some n ->\n  intoffloat x = Some n.\nProof.\n  intros; unfold cmp in H; pose proof (order_float_finite_correct x (floatofintu ox8000_0000)).\n  destruct (order_float x (floatofintu ox8000_0000)); try destruct c; try discriminate.\n  pose proof (intuoffloat_correct x); rewrite H0 in H2; destruct H2.\n  specialize (H1 H2 eq_refl); pose proof (intoffloat_correct x); destruct (intoffloat x).\n  f_equal; rewrite <- (proj2 H4) in H3; apply eq_Z2R in H3.\n  pose proof (eq_refl (Int.repr (Int.unsigned n))); rewrite H3 in H5 at 1.\n  rewrite Int.repr_signed, Int.repr_unsigned in H5; assumption.\n  destruct H4; [rewrite H2 in H4; discriminate|].\n  apply intuoffloat_interval in H0; exfalso; destruct H0, H4.\n  eapply Rlt_le_trans in H0; [|now apply H4]; apply (lt_Z2R (-1)) in H0; discriminate.\n  apply Rcompare_Lt_inv in H1; eapply Rle_lt_trans in H1; [|now apply H4].\n  unfold floatofintu in H1; rewrite (fun x H => proj1 (binary_normalize64_exact x H)) in H1;\n    [apply lt_Z2R in H1; discriminate|split; reflexivity].\nQed.\n\nLemma Zfloor_minus :\n  forall x n, Zfloor(x-Z2R n) = Zfloor(x)-n.\nProof.\n  intros; apply Zfloor_imp; replace (Zfloor x - n + 1) with (Zfloor x + 1 - n) by ring; do 2 rewrite Z2R_minus.\n  split;\n    [apply Rplus_le_compat_r; now apply Zfloor_lb|\n     apply Rplus_lt_compat_r; rewrite Z2R_plus; now apply Zfloor_ub].\nQed.\n\nTheorem intuoffloat_intoffloat_2:\n  forall x n,\n  cmp Clt x (floatofintu ox8000_0000) = false ->\n  intuoffloat x = Some n ->\n  intoffloat (sub x (floatofintu ox8000_0000)) = Some (Int.sub n ox8000_0000).\nProof.\n  assert (B2R _ _ (floatofintu ox8000_0000) = Z2R (Int.unsigned ox8000_0000)).\n  apply (fun x H => proj1 (binary_normalize64_exact x H)); split; reflexivity.\n  intros; unfold cmp in H0; pose proof (order_float_finite_correct x (floatofintu ox8000_0000)).\n  destruct (order_float x (floatofintu ox8000_0000)); try destruct c; try discriminate;\n  pose proof (intuoffloat_correct x); rewrite H1 in H3; destruct H3; specialize (H2 H3 eq_refl).\n  apply Rcompare_Eq_inv in H2; apply B2R_inj in H2.\n  subst x; vm_compute in H1; injection H1; intro; subst n; vm_compute; reflexivity.\n  destruct x; try discriminate H3;\n    [rewrite H in H2; simpl B2R in H2; apply (eq_Z2R 0) in H2; discriminate|reflexivity].\n  reflexivity.\n  rewrite H in H2; apply Rcompare_Gt_inv in H2; pose proof (intuoffloat_interval _ _ H1).\n  unfold sub, b64_minus.\n  exploit (Bminus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE x (floatofintu ox8000_0000)); [assumption|reflexivity|]; intro.\n  rewrite H, round_generic in H6.\n  match goal with [H6:if Rlt_bool ?x ?y then _ else _|-_] =>\n    pose proof (Rlt_bool_spec x y); destruct (Rlt_bool x y) end.\n  destruct H6 as [? []].\n  match goal with [|- _ ?y = _] => pose proof (intoffloat_correct y); destruct (intoffloat y) end.\n  destruct H10.\n  f_equal; rewrite <- (Int.repr_signed i); unfold Int.sub; f_equal; apply eq_Z2R. \n  rewrite Z2R_minus, H11, H4.\n  unfold round, scaled_mantissa, F2R, Fexp, Fnum, round_mode; simpl bpow; repeat rewrite Rmult_1_r;\n    rewrite <- Z2R_minus; f_equal.\n  rewrite (Ztrunc_floor (B2R _ _ x)), <- Zfloor_minus, <- Ztrunc_floor;\n    [f_equal; assumption|apply Rle_0_minus; left; assumption|].\n  left; eapply Rlt_trans; [|now apply H2]; apply (Z2R_lt 0); reflexivity.\n  try (change (0 ?= 53) with Lt in H6,H8).  (* for Coq 8.4 *)\n  try (change (53 ?= 1024) with Lt in H6,H8).  (* for Coq 8.4 *)\n  exfalso; simpl Zcompare in H6, H8; rewrite H6, H8 in H10.\n  destruct H10 as [|[]]; [discriminate|..].\n  eapply Rle_trans in H10; [|apply Rle_0_minus; left; assumption]; apply (le_Z2R 0) in H10; apply H10; reflexivity.\n  eapply Rle_lt_trans in H10; [|apply Rplus_lt_compat_r; now apply (proj2 H5)].\n  rewrite <- Z2R_opp, <- Z2R_plus in H10; apply lt_Z2R in H10; discriminate.\n  exfalso; inversion H7; rewrite Rabs_right in H8.\n  eapply Rle_lt_trans in H8. apply Rle_not_lt in H8; [assumption|apply (bpow_le _ 31); discriminate].\n  change (bpow radix2 31) with (Z2R(Zsucc Int.max_unsigned - Int.unsigned ox8000_0000)); rewrite Z2R_minus.\n  apply Rplus_lt_compat_r; exact (proj2 H5).\n  apply Rle_ge; apply Rle_0_minus; left; assumption.\n  now apply valid_rnd_round_mode.\n  apply Fprop_Sterbenz.sterbenz_aux; [now apply fexp_monotone|now apply generic_format_B2R| |].\n  rewrite <- H; now apply generic_format_B2R.\n  destruct H5; split; left; assumption.\n  now destruct H2.\nQed.\n\n(** Conversions from ints to floats can be defined as bitwise manipulations\n  over the in-memory representation.  This is what the PowerPC port does.\n  The trick is that [from_words 0x4330_0000 x] is the float\n  [2^52 + floatofintu x]. *)\n\nDefinition ox4330_0000 := Int.repr 1127219200.        (**r [0x4330_0000] *)\n\nLemma split_bits_or:\n  forall x,\n  split_bits 52 11 (Int64.unsigned (Int64.ofwords ox4330_0000 x)) = (false, Int.unsigned x, 1075).\nProof.\n  intros.\n  transitivity (split_bits 52 11 (join_bits 52 11 false (Int.unsigned x) 1075)).\n  - f_equal. rewrite Int64.ofwords_add'. reflexivity.\n  - apply split_join_bits.\n    compute; auto.\n    generalize (Int.unsigned_range x).\n    compute_this Int.modulus; compute_this (2^52); omega.\n    compute_this (2^11); omega.\nQed.\n\nLemma from_words_value:\n  forall x,\n    B2R _ _ (from_words ox4330_0000 x) =\n    (bpow radix2 52 + Z2R (Int.unsigned x))%R /\\\n    is_finite _ _ (from_words ox4330_0000 x) = true.\nProof.\n  intros; unfold from_words, double_of_bits, b64_of_bits, binary_float_of_bits.\n  rewrite B2R_FF2B. rewrite is_finite_FF2B.\n  unfold binary_float_of_bits_aux; rewrite split_bits_or; simpl; pose proof (Int.unsigned_range x).\n  destruct (Int.unsigned x + Zpower_pos 2 52) eqn:?.\n  exfalso; now smart_omega.\n  simpl; rewrite <- Heqz;  unfold F2R; simpl.\n  rewrite <- (Z2R_plus 4503599627370496), Rmult_1_r.\n  split; [f_equal; compute_this (Zpower_pos 2 52); ring | reflexivity].\n  assert (Zneg p < 0) by reflexivity.\n  exfalso; now smart_omega.\nQed.\n\nTheorem floatofintu_from_words:\n  forall x,\n  floatofintu x =\n    sub (from_words ox4330_0000 x) (from_words ox4330_0000 Int.zero).\nProof.\n  intros; destruct (Int.eq_dec x Int.zero); [subst; vm_compute; reflexivity|].\n  assert (Int.unsigned x <> 0).\n  intro; destruct n; rewrite <- (Int.repr_unsigned x), H; reflexivity.\n  pose proof (Int.unsigned_range x).\n  pose proof (binary_normalize64_exact (Int.unsigned x)). destruct H1; [smart_omega|].\n  unfold floatofintu, sub, b64_minus.\n  match goal with [|- _ = Bminus _ _ _ _ _ _ ?x ?y] =>\n    pose proof (Bminus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE x y) end.\n  apply (fun f x y => f x y) in H3; try apply (fun x => proj2 (from_words_value x)).\n  do 2 rewrite (fun x => proj1 (from_words_value x)) in H3.\n  rewrite Int.unsigned_zero in H3.\n  replace (bpow radix2 52 + Z2R (Int.unsigned x) -\n    (bpow radix2 52 + Z2R 0))%R with (Z2R (Int.unsigned x)) in H3 by (simpl; ring).\n  rewrite round_exact in H3 by smart_omega.\n  match goal with [H3:if Rlt_bool ?x ?y then _ else _ |- _] =>\n    pose proof (Rlt_bool_spec x y); destruct (Rlt_bool x y) end; destruct H3 as [? []].\n  try (change (53 ?= 1024) with Lt in H3,H5).  (* for Coq 8.4 *)\n  simpl Zcompare in *; apply B2R_inj;\n    try match goal with [H':B2R _ _ ?f = _ , H'':is_finite _ _ ?f = true |- is_finite_strict _ _ ?f = true] => \n      destruct f; [\n        simpl in H'; change 0%R with (Z2R 0) in H'; apply eq_Z2R in H'; now destruct (H (eq_sym H')) | \n        discriminate H'' | discriminate H'' | reflexivity\n      ]\n    end.\n  rewrite H3; assumption.\n  inversion H4; change (bpow radix2 1024) with (Z2R (radix2 ^ 1024)) in H5; rewrite <- Z2R_abs in H5.\n  apply le_Z2R in H5; pose proof (Zabs_spec (Int.unsigned x));\n    exfalso; now smart_omega.\nQed.\n\nLemma ox8000_0000_signed_unsigned:\n  forall x,\n    Int.unsigned (Int.add x ox8000_0000) = Int.signed x + Int.half_modulus.\nProof.\n  intro; unfold Int.signed, Int.add; pose proof (Int.unsigned_range x).\n  destruct (zlt (Int.unsigned x) Int.half_modulus).\n  rewrite Int.unsigned_repr; compute_this (Int.unsigned ox8000_0000); now smart_omega.\n  rewrite (Int.eqm_samerepr _ (Int.unsigned x + -2147483648)).\n  rewrite Int.unsigned_repr; now smart_omega.\n  apply Int.eqm_add; [now apply Int.eqm_refl|exists 1;reflexivity].\nQed.\n\nTheorem floatofint_from_words:\n  forall x,\n  floatofint x =\n    sub (from_words ox4330_0000 (Int.add x ox8000_0000))\n        (from_words ox4330_0000 ox8000_0000).\nProof.\nLocal Transparent Int.repr Int64.repr.\n  intros; destruct (Int.eq_dec x Int.zero); [subst; vm_compute; reflexivity|].\n  assert (Int.signed x <> 0).\n  intro; destruct n; rewrite <- (Int.repr_signed x), H; reflexivity.\n  pose proof (Int.signed_range x).\n  pose proof (binary_normalize64_exact (Int.signed x)); destruct H1; [now smart_omega|].\n  unfold floatofint, sub, b64_minus.\n  match goal with [|- _ = Bminus _ _ _ _ _ _ ?x ?y] =>\n    pose proof (Bminus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE x y) end.\n  apply (fun f x y => f x y) in H3; try apply (fun x => proj2 (from_words_value x)).\n  do 2 rewrite (fun x => proj1 (from_words_value x)) in H3.\n  replace (bpow radix2 52 + Z2R (Int.unsigned (Int.add x ox8000_0000)) -\n    (bpow radix2 52 + Z2R (Int.unsigned ox8000_0000)))%R with (Z2R (Int.signed x)) in H3\n  by (rewrite ox8000_0000_signed_unsigned; rewrite Z2R_plus; simpl; ring).\n  rewrite round_exact in H3 by smart_omega.\n  match goal with [H3:if Rlt_bool ?x ?y then _ else _ |- _] =>\n    pose proof (Rlt_bool_spec x y); destruct (Rlt_bool x y) end; destruct H3 as [? []].\n  try (change (0 ?= 53) with Lt in H3,H5).  (* for Coq 8.4 *)\n  try (change (53 ?= 1024) with Lt in H3,H5).  (* for Coq 8.4 *)\n  simpl Zcompare in *; apply B2R_inj;\n    try match goal with [H':B2R _ _ ?f = _ , H'':is_finite _ _ ?f = true |- is_finite_strict _ _ ?f = true] => \n      destruct f; [\n        simpl in H'; change 0%R with (Z2R 0) in H'; apply eq_Z2R in H'; now destruct (H (eq_sym H')) | \n        discriminate H'' | discriminate H'' | reflexivity\n      ]\n    end.\n  rewrite H3; assumption.\n  inversion H4; unfold bpow in H5; rewrite <- Z2R_abs in H5;\n    apply le_Z2R in H5; pose proof (Zabs_spec (Int.signed x)); exfalso; now smart_omega.\nQed.\n\n(** Conversions from 32-bit integers to single-precision floats can\n  be decomposed into a conversion to a double-precision float,\n  followed by a [singleoffloat] normalization.  No double rounding occurs. *)\n\nLemma is_finite_strict_ge_1:\n  forall (f: binary32),\n  is_finite _ _ f = true ->\n  (1 <= Rabs (B2R _ _ f))%R ->\n  is_finite_strict _ _ f = true.\nProof.\n  intros. destruct f; auto. simpl in H0.\n  change 0%R with (Z2R 0) in H0.\n  change 1%R with (Z2R 1) in H0.\n  rewrite <- Z2R_abs in H0.\n  exploit le_Z2R; eauto.\nQed.\n\nLemma single_float_of_int:\n  forall n,\n  -2^53 < n < 2^53 ->\n  singleoffloat (binary_normalize64 n 0 false) = floatofbinary32 (binary_normalize32 n 0 false).\nProof.\n  intros. unfold singleoffloat. f_equal.\n  assert (EITHER: n = 0 \\/ Z.abs n > 0) by (destruct n; compute; auto).\n  destruct EITHER as [EQ|GT].\n  subst n; reflexivity.\n  exploit binary_normalize64_exact; eauto. intros [A B].\n  destruct (binary_normalize64 n 0 false) as [ | | | s m e] eqn:B64; simpl in *.\n- assert (0 = n) by (apply eq_Z2R; auto). subst n. simpl in GT. omegaContradiction.\n- discriminate.\n- discriminate.\n- set (n1 := cond_Zopp s (Z.pos m)) in *.\n  generalize (binary_normalize32_correct n1 e s).\n  fold (binary_normalize32 n1 e s). intros C.\n  generalize (binary_normalize32_correct n 0 false).\n  fold (binary_normalize32 n 0 false). intros D.\n  assert (A': @F2R radix2 {| Fnum := n; Fexp := 0 |} = Z2R n).\n  { unfold F2R. apply Rmult_1_r. }\n  rewrite A in C. rewrite A' in D.\n  destruct (Rlt_bool\n         (Rabs\n            (round radix2 (FLT_exp (3 - 128 - 24) 24) (round_mode mode_NE)\n               (Z2R n))) (bpow radix2 128)).\n+ destruct C as [C1 [C2 _]]; destruct D as [D1 [D2 _]].\n  assert (1 <= Rabs (round radix2 (FLT_exp (3 - 128 - 24) 24) (round_mode mode_NE) (Z2R n)))%R.\n  { apply abs_round_ge_generic.\n    apply fexp_correct. red. omega.\n    apply valid_rnd_round_mode.\n    apply generic_format_bpow with (e := 0). compute. congruence.\n    rewrite <- Z2R_abs. change 1%R with (Z2R 1). apply Z2R_le. omega. }\n  apply B2R_inj.\n  apply is_finite_strict_ge_1; auto. rewrite C1; auto.\n  apply is_finite_strict_ge_1; auto. rewrite D1; auto.\n  congruence.\n+ apply B2FF_inj. congruence.\nQed.\n\nTheorem singleofint_floatofint:\n  forall n, singleofint n = singleoffloat (floatofint n).\nProof.\n  intros. symmetry. apply single_float_of_int.\n  generalize (Int.signed_range n). smart_omega.\nQed.\n\nTheorem singleofintu_floatofintu:\n  forall n, singleofintu n = singleoffloat (floatofintu n).\nProof.\n  intros. symmetry. apply single_float_of_int.\n  generalize (Int.unsigned_range n). smart_omega.\nQed.\n\nTheorem mul2_add:\n  forall f, add f f = mul f (floatofint (Int.repr 2%Z)).\nProof.\n  intros. unfold add, b64_plus, mul, b64_mult.\n  destruct (is_finite_strict _ _ f) eqn:EQFINST.\n  - assert (EQFIN:is_finite _ _ f = true) by (destruct f; simpl in *; congruence).\n    pose proof (Bplus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE f f EQFIN EQFIN).\n    pose proof (Bmult_correct 53 1024 eq_refl eq_refl binop_pl mode_NE f\n                              (floatofint (Int.repr 2%Z))).\n    rewrite <- double, Rmult_comm in H.\n    replace (B2R 53 1024 (floatofint (Int.repr 2))) with 2%R in H0 by (compute; field).\n    destruct Rlt_bool.\n    + destruct H0 as [? []], H as [? []].\n      rewrite EQFIN in H1.\n      apply B2R_Bsign_inj; auto.\n      etransitivity. apply H. symmetry. apply H0.\n      etransitivity. apply H4. symmetry. etransitivity. apply H2.\n      destruct Bmult; try reflexivity; discriminate.\n      simpl. rewrite xorb_false_r.\n      erewrite <- Rmult_0_l, Rcompare_mult_r.\n      destruct f; try discriminate EQFINST.\n      simpl. unfold F2R.\n      erewrite <- Rmult_0_l, Rcompare_mult_r.\n      rewrite Rcompare_Z2R with (y:=0).\n      destruct b; reflexivity.\n      apply bpow_gt_0.\n      apply (Z2R_lt 0 2). omega.\n    + destruct H.\n      apply B2FF_inj.\n      etransitivity. apply H.\n      symmetry. etransitivity. apply H0.\n      f_equal. destruct Bsign; reflexivity.\n  - destruct f as [[]|[]| |]; try discriminate; simpl. \n    auto. auto. auto. auto.\n    destruct (Archi.choose_binop_pl b n b n); auto.\nQed.\n\nProgram Definition pow2_float (b:bool) (e:Z) (H:-1023 < e < 1023) : float :=\n  B754_finite _ _ b (nat_iter 52 xO xH) (e-52) _.\nNext Obligation.\n  unfold Fappli_IEEE.bounded, canonic_mantissa.\n  rewrite andb_true_iff, Zle_bool_true by omega. split; auto.\n  apply Zeq_bool_true. unfold FLT_exp. simpl Z.of_nat.\n  apply Z.max_case_strong; omega.\nQed.\n\nTheorem mul_div_pow2:\n  forall b e f H H',\n    mul f (pow2_float b e H) = div f (pow2_float b (-e) H').\nProof.\n  intros. unfold mul, b64_mult, div, b64_div.\n  pose proof (Bmult_correct 53 1024 eq_refl eq_refl binop_pl mode_NE f (pow2_float b e H)).\n  pose proof (Bdiv_correct 53 1024 eq_refl eq_refl binop_pl mode_NE f (pow2_float b (-e) H')).\n  lapply H1. clear H1. intro.\n  change (is_finite 53 1024 (pow2_float b e H)) with true in H0.\n  unfold Rdiv in H1.\n  replace (/ B2R 53 1024 (pow2_float b (-e) H'))%R\n    with (B2R 53 1024 (pow2_float b e H)) in H1.\n  destruct (is_finite _ _ f) eqn:EQFIN.\n  - destruct Rlt_bool.\n    + destruct H0 as [? []], H1 as [? []].\n      apply B2R_Bsign_inj; auto.\n      etransitivity. apply H0. symmetry. apply H1.\n      etransitivity. apply H3. destruct Bmult; try discriminate H2; reflexivity.\n      symmetry. etransitivity. apply H5. destruct Bdiv; try discriminate H4; reflexivity.\n      reflexivity.\n    + apply B2FF_inj.\n      etransitivity. apply H0. symmetry. etransitivity. apply H1.\n      reflexivity.\n  - destruct f; try discriminate EQFIN; auto. \n  - simpl.\n    assert ((4503599627370496 * bpow radix2 (e - 52))%R =\n            (/ (4503599627370496 * bpow radix2 (- e - 52)))%R).\n    { etransitivity. symmetry. apply (bpow_plus radix2 52).\n      symmetry. etransitivity. apply f_equal. symmetry. apply (bpow_plus radix2 52).\n      rewrite <- bpow_opp. f_equal. ring. }\n    destruct b. unfold cond_Zopp.\n    rewrite !F2R_Zopp, <- Ropp_inv_permute. f_equal. auto.\n    intro. apply F2R_eq_0_reg in H3. omega.\n    apply H2.\n  - simpl. intro. apply F2R_eq_0_reg in H2.\n    destruct b; simpl in H2; omega.\nQed.\n\nDefinition exact_inverse_mantissa := nat_iter 52 xO xH.\n\nProgram Definition exact_inverse (f: float) : option float :=\n  match f with\n  | B754_finite s m e B =>\n      if peq m exact_inverse_mantissa then\n      if zlt (-1023) (e + 52) then\n      if zlt (e + 52) 1023 then\n        Some(B754_finite _ _ s m (-e - 104) _)\n      else None else None else None\n  | _ => None\n  end.\nNext Obligation.\n  unfold Fappli_IEEE.bounded, canonic_mantissa. apply andb_true_iff; split.\n  simpl Z.of_nat. apply Zeq_bool_true. unfold FLT_exp. apply Z.max_case_strong; omega.\n  apply Zle_bool_true. omega.  \nQed.\n\nRemark B754_finite_eq:\n  forall s1 m1 e1 B1 s2 m2 e2 B2,\n  s1 = s2 -> m1 = m2 -> e1 = e2 ->\n  B754_finite _ _ s1 m1 e1 B1 = (B754_finite _ _ s2 m2 e2 B2 : float).\nProof.\n  intros. subst. f_equal. apply proof_irrelevance. \nQed.\n\nTheorem div_mul_inverse:\n  forall x y z, exact_inverse y = Some z -> div x y = mul x z.\nProof with (try discriminate).\n  unfold exact_inverse; intros. destruct y...\n  destruct (peq m exact_inverse_mantissa)...\n  destruct (zlt (-1023) (e + 52))...\n  destruct (zlt (e + 52) 1023)...\n  inv H.\n  set (n := - e - 52).\n  assert (RNG1: -1023 < n < 1023) by (unfold n; omega).\n  assert (RNG2: -1023 < -n < 1023) by (unfold n; omega).\n  symmetry. \n  transitivity (mul x (pow2_float b n RNG1)).\n  f_equal. apply B754_finite_eq; auto. unfold n; omega.\n  transitivity (div x (pow2_float b (-n) RNG2)).\n  apply mul_div_pow2. \n  f_equal. apply B754_finite_eq; auto. unfold n; omega.\nQed.\n\nTheorem floatoflongu_decomp:\n  forall l, floatoflongu l =\n    add (mul (floatofintu (Int64.hiword l)) (pow2_float false 32 (conj eq_refl eq_refl)))\n        (floatofintu (Int64.loword l)).\nProof.\n  intros.\n  unfold floatofintu.\n  pose proof (Int.unsigned_range (Int64.loword l)).\n  pose proof (Int.unsigned_range (Int64.hiword l)).\n  pose proof  (Int64.unsigned_range l).\n  compute_this Int.modulus.\n  destruct (binary_normalize64_exact (Int.unsigned (Int64.loword l)));\n    [compute_this (2 ^ 53); omega|].\n  destruct (binary_normalize64_exact (Int.unsigned (Int64.hiword l)));\n    [compute_this (2 ^ 53); omega|].\n  unfold mul, b64_mult.\n  pose proof (Bmult_correct 53 1024 eq_refl eq_refl binop_pl mode_NE\n                            (binary_normalize64 (Int.unsigned (Int64.hiword l)) 0 false)\n                            (pow2_float false 32 (conj eq_refl eq_refl))).\n  rewrite H4 in H6.\n  replace (B2R 53 1024 (pow2_float false 32 (conj eq_refl eq_refl)))\n  with (Z2R 4294967296)%R in H6 by (compute; field).\n  rewrite <- Z2R_mult in H6.\n  rewrite round_generic in H6.\n  - rewrite Rlt_bool_true in H6.\n    + rewrite H5 in H6.\n      destruct H6 as [? [? ?]].\n      { unfold add, b64_plus.\n        pose proof (Bplus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE\n                      (Bmult 53 1024 eq_refl eq_refl binop_pl mode_NE\n                         (binary_normalize64 (Int.unsigned (Int64.hiword l)) 0 false)\n                            (pow2_float false 32 (conj eq_refl eq_refl)))\n                            (binary_normalize64 (Int.unsigned (Int64.loword l)) 0 false) H7 H3).\n        rewrite H6, H2, <- Z2R_plus in H9.\n        change 4294967296 with (two_p 32) in H9.\n        rewrite <- Int64.ofwords_add', Int64.ofwords_recompose in H9.\n        assert (Rabs (round radix2 (FLT_exp (3 - 1024 - 53) 53)\n                            (round_mode mode_NE) (Z2R (Int64.unsigned l))) <\n                bpow radix2 1024)%R.\n        { rewrite <- round_NE_abs by (apply fexp_correct; reflexivity).\n          eapply Rle_lt_trans with (Z2R (two_p 64)). 2:apply Z2R_lt; reflexivity.\n          erewrite <- round_generic.\n          - apply round_le. apply fexp_correct; reflexivity.\n            apply (valid_rnd_round_mode mode_NE).\n            rewrite <- Z2R_abs. apply Z2R_le. change (two_p 64) with Int64.modulus. zify; omega.\n          - apply (valid_rnd_round_mode mode_NE).\n          - apply (generic_format_bpow radix2 _ 64). compute. discriminate. }\n        rewrite Rlt_bool_true in H9 by auto.\n        unfold floatoflongu, binary_normalize64.\n        pose proof (binary_normalize64_correct (Int64.unsigned l) 0 false).\n        replace (F2R (beta:=radix2) {| Fnum := Int64.unsigned l; Fexp := 0 |})\n        with (Z2R (Int64.unsigned l)) in H11\n        by (unfold F2R, Fexp, Fnum, bpow; field).\n        rewrite Rlt_bool_true in H11 by auto.\n        destruct (Int64.eq_dec l Int64.zero). subst. reflexivity.\n        destruct H11, H9.\n        assert (1 <= round radix2 (FLT_exp (3 - 1024 - 53) 53) (round_mode mode_NE)\n                           (Z2R (Int64.unsigned l)))%R.\n        { erewrite <- round_generic with (x:=1%R).\n          apply round_le. apply fexp_correct. reflexivity. apply valid_rnd_round_mode.\n          assert (Int64.unsigned l <> 0).\n          { contradict n. rewrite <- (Int64.repr_unsigned l), n. auto. }\n          apply (Z2R_le 1). omega.\n          apply valid_rnd_round_mode.\n          apply (generic_format_bpow _ _ 0). compute. discriminate. }\n        unfold binary_normalize64 in *.\n        apply B2R_inj.\n        + destruct H12, (binary_normalize 53 1024 eq_refl eq_refl mode_NE (Int64.unsigned l) 0 false); try discriminate.\n          unfold B2R in H11. rewrite <- H11 in H14. apply (le_Z2R 1 0) in H14. omega.\n          auto.\n        + destruct H13; match goal with Hf0:is_finite _ _ ?f0 = true,\n                                            Hf1:B2R _ _ ?f1 = _ |-\n                                        is_finite_strict _ _ ?f = true =>\n                                        change f0 with f in Hf0; change f1 with f in Hf1;\n                                        destruct f\n                        end; try discriminate.\n          unfold B2R in H9. rewrite <- H9 in H14. apply (le_Z2R 1 0) in H14. omega.\n          auto.\n        + rewrite H11. symmetry. apply H9. }\n    + rewrite <- Z2R_abs.\n      apply (Z2R_lt _ (radix2 ^ 1024)).\n      compute_this (radix2 ^ 1024); zify; omega.\n  - apply valid_rnd_round_mode.\n  - destruct (Z.eq_dec (Int.unsigned (Int64.hiword l)) 0).\n    rewrite e. apply generic_format_0.\n    apply generic_format_FLT_FLX.\n    + apply Rle_trans with (bpow radix2 0). apply bpow_le. omega.\n      rewrite <- Z2R_abs. apply (Z2R_le 1).\n      clear - n. zify; omega.\n    + apply generic_format_FLX.\n      eexists {| Fnum := Int.unsigned (Int64.hiword l); Fexp := 32 |}.\n      unfold F2R, Fnum, Fexp. split.\n      rewrite Z2R_mult. auto.\n      compute_this (radix2 ^ 53). zify; omega.\nQed.\n\nDefinition ox4530_0000 := Int.repr 1160773632.        (**r [0x4530_0000] *)\n\nLemma split_bits_or':\n  forall x,\n  split_bits 52 11 (Int64.unsigned (Int64.ofwords ox4530_0000 x)) = (false, Int.unsigned x, 1107).\nProof.\n  intros.\n  transitivity (split_bits 52 11 (join_bits 52 11 false (Int.unsigned x) 1107)).\n  - f_equal. rewrite Int64.ofwords_add'. reflexivity.\n  - apply split_join_bits.\n    compute; auto.\n    generalize (Int.unsigned_range x).\n    compute_this Int.modulus; compute_this (2^52); omega.\n    compute_this (2^11); omega.\nQed.\n\nLemma from_words_value':\n  forall x,\n    B2R _ _ (from_words ox4530_0000 x) =\n    (bpow radix2 84 + Z2R (Int.unsigned x * two_p 32))%R /\\\n    is_finite _ _ (from_words ox4530_0000 x) = true.\nProof.\n  intros; unfold from_words, double_of_bits, b64_of_bits, binary_float_of_bits.\n  rewrite B2R_FF2B. rewrite is_finite_FF2B.\n  unfold binary_float_of_bits_aux; rewrite split_bits_or'; simpl; pose proof (Int.unsigned_range x).\n  destruct (Int.unsigned x + Zpower_pos 2 52) eqn:?.\n  exfalso; now smart_omega.\n  simpl; rewrite <- Heqz;  unfold F2R; simpl.\n  rewrite <- (Z2R_plus 19342813113834066795298816), <- (Z2R_mult _ 4294967296).\n  split; [f_equal; compute_this (Zpower_pos 2 52);\n          compute_this (two_power_pos 32); ring | reflexivity].\n  assert (Zneg p < 0) by reflexivity.\n  exfalso; now smart_omega.\nQed.\n\nTheorem floatoflongu_from_words:\n  forall l,\n  floatoflongu l =\n    add (sub (from_words ox4530_0000 (Int64.hiword l))\n             (from_words ox4530_0000 (Int.repr (two_p 20))))\n        (from_words ox4330_0000 (Int64.loword l)).\nProof.\n  intros.\n  pose proof  (Int64.unsigned_range l).\n  pose proof (Int.unsigned_range (Int64.hiword l)).\n  destruct (from_words_value (Int64.loword l)).\n  destruct (from_words_value' (Int64.hiword l)).\n  destruct (from_words_value' (Int.repr (two_p 20))).\n  unfold sub, b64_minus.\n  pose proof (Bminus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE\n                             (from_words ox4530_0000 (Int64.hiword l))\n                             (from_words ox4530_0000 (Int.repr (two_p 20))) H4 H6).\n  rewrite round_generic in H7.\n  - rewrite H3, H5 in H7.\n    replace (bpow radix2 84 + Z2R (Int.unsigned (Int64.hiword l) * two_p 32) -\n             (bpow radix2 84 + Z2R (Int.unsigned (Int.repr (two_p 20)) * two_p 32)))%R\n    with (Z2R (Int.unsigned (Int64.hiword l) * two_p 32 - two_p 52)) in H7.\n    + rewrite Rlt_bool_true in H7.\n      * { destruct H7 as [? []].\n          unfold floatoflongu, binary_normalize64.\n          pose proof (binary_normalize64_correct (Int64.unsigned l) 0 false).\n          replace (F2R (beta:=radix2) {| Fnum := Int64.unsigned l; Fexp := 0 |})\n          with (Z2R (Int64.unsigned l)) in H10\n          by (unfold F2R, Fexp, Fnum, bpow; field).\n          assert (Rabs (round radix2 (FLT_exp (3 - 1024 - 53) 53)\n                              (round_mode mode_NE) (Z2R (Int64.unsigned l))) <\n                  bpow radix2 1024)%R.\n          { rewrite <- round_NE_abs by (apply fexp_correct; reflexivity).\n          eapply Rle_lt_trans with (Z2R (two_p 64)). 2:apply Z2R_lt; reflexivity.\n          erewrite <- round_generic.\n            - apply round_le. apply fexp_correct; reflexivity.\n              apply (valid_rnd_round_mode mode_NE).\n              rewrite <- Z2R_abs. apply Z2R_le. change (two_p 64) with Int64.modulus. zify; omega.\n            - apply (valid_rnd_round_mode mode_NE).\n            - apply (generic_format_bpow radix2 _ 64). compute. discriminate. }\n          rewrite Rlt_bool_true in H10 by auto.\n          unfold add, b64_plus.\n          pose proof (Bplus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE\n                                    (Bminus 53 1024 eq_refl eq_refl binop_pl mode_NE\n                                            (from_words ox4530_0000 (Int64.hiword l))\n                                            (from_words ox4530_0000 (Int.repr (two_p 20))))\n                                    (from_words ox4330_0000 (Int64.loword l)) H8 H2).\n          change (bpow radix2 52) with (Z2R (two_p 52)) in H1.\n          rewrite H7, H1, <- !Z2R_plus in H12.\n          replace (Int.unsigned (Int64.hiword l) * two_p 32 - two_p 52 +\n                   (two_p 52 + Int.unsigned (Int64.loword l)))\n          with (Int.unsigned (Int64.hiword l) * two_p 32 + Int.unsigned (Int64.loword l))\n            in H12 by ring.\n          rewrite <- Int64.ofwords_add', Int64.ofwords_recompose, Rlt_bool_true in H12 by auto.\n          destruct (Z.eq_dec (Int64.unsigned l) 0).\n          - apply (f_equal Int64.repr) in e. rewrite Int64.repr_unsigned in e.\n            subst. reflexivity.\n          - destruct H12 as [? []], H10 as [? []].\n            assert (1 <= Rabs (round radix2 (FLT_exp (3 - 1024 - 53) 53)\n                                (round_mode mode_NE) (Z2R (Int64.unsigned l)))) %R.\n            { rewrite <- round_NE_abs, <- Z2R_abs by (apply fexp_correct; reflexivity).\n              erewrite <- round_generic with (x := 1%R). \n              3:eapply (generic_format_bpow _ _ 0).\n              apply round_le, (Z2R_le 1).\n              apply fexp_correct; reflexivity. apply (valid_rnd_round_mode mode_NE).\n              zify; omega.\n              apply (valid_rnd_round_mode mode_NE).\n              compute; discriminate. }\n            eapply B2R_inj.\n            + destruct binary_normalize; try discriminate H15.\n              unfold B2R in H10. rewrite <- H10, Rabs_R0 in H17. apply (le_Z2R 1 0) in H17. omega.\n              auto.\n            + match goal with Hf0:is_finite _ _ ?f0 = true,\n                                            Hf1:B2R _ _ ?f1 = _ |-\n                                        is_finite_strict _ _ ?f = true =>\n                                        change f0 with f in Hf0; change f1 with f in Hf1;\n                                        destruct f\n              end; try discriminate H13.\n              unfold B2R in H12. rewrite <- H12, Rabs_R0 in H17. apply (le_Z2R 1 0) in H17. omega.\n              auto.\n            + etransitivity; eauto. }\n      * rewrite <- Z2R_abs. apply (Z2R_lt _ (2^1024)).\n        compute_this Int.modulus; compute_this (two_p 32);\n        compute_this (two_p 52); compute_this (2^1024).\n        clear - H0. zify; omega.\n    + rewrite Z2R_minus, Int.unsigned_repr, <- two_p_is_exp, !Z2R_mult.\n      ring_simplify. reflexivity.\n      omega. omega. compute; split; discriminate.\n  - apply valid_rnd_round_mode.\n  - apply sterbenz.\n    + apply FLT_exp_monotone.\n    + apply generic_format_B2R.\n    + apply generic_format_B2R.\n    + rewrite H3, H5, Int.unsigned_repr by (compute; split; discriminate).\n      unfold bpow. rewrite <- !Z2R_plus, <- (Z2R_mult 2).\n      compute_this (Z.pow_pos radix2 84);\n      compute_this (two_p 20 * two_p 32); compute_this (two_p 32);\n      compute_this (Int.modulus).\n      change (19342813113834066795298816 + 4503599627370496)\n      with (9671406559168833211334656 * 2).\n      unfold Rdiv. rewrite Z2R_mult, Rmult_assoc, Rinv_r, Rmult_1_r by (apply (Z2R_neq 2 0); omega).\n      split; apply Z2R_le; omega.\nQed.\n\nTheorem floatoflong_decomp:\n  forall l, floatoflong l =\n    add (mul (floatofint (Int64.hiword l)) (pow2_float false 32 (conj eq_refl eq_refl)))\n        (floatofintu (Int64.loword l)).\nProof.\n  intros.\n  unfold floatofintu, floatofint.\n  destruct (binary_normalize64_exact (Int.signed (Int64.hiword l))).\n  { pose proof (Int.signed_range (Int64.hiword l)).\n    revert H. generalize (Int.signed (Int64.hiword l)).\n    change (forall z : Z, -2147483648 <= z <= 2147483647 -> - 9007199254740992 < z < 9007199254740992).\n    intros. omega. }\n  destruct (binary_normalize64_exact (Int.unsigned (Int64.loword l))).\n  { pose proof (Int.unsigned_range (Int64.loword l)).\n    revert H1. generalize (Int.unsigned (Int64.loword l)).\n    change (forall z : Z, 0 <= z < 4294967296 -> - 9007199254740992 < z < 9007199254740992).\n    intros. omega. }\n  unfold mul, b64_mult.\n  pose proof (Bmult_correct 53 1024 eq_refl eq_refl binop_pl mode_NE\n                            (binary_normalize64 (Int.signed (Int64.hiword l)) 0 false)\n                            (pow2_float false 32 (conj eq_refl eq_refl))).\n  rewrite H in H3.\n  remember (B2R 53 1024 (pow2_float false 32 (conj eq_refl eq_refl))).\n  compute in Heqr.\n  change 4503599627370496%R with (Z2R (1048576*4294967296)) in Heqr.\n  change 1048576%R with (Z2R 1048576) in Heqr.\n  rewrite Z2R_mult in Heqr.\n  assert (r = Z2R 4294967296).\n  { rewrite Heqr. field. change 0%R with (Z2R 0). intro. apply eq_Z2R in H4. discriminate. }\n  clear Heqr. subst.\n  pose proof (Int.signed_range (Int64.hiword l)).\n  change Int.min_signed with (-2147483648) in H4.\n  change Int.max_signed with 2147483647 in H4.\n  rewrite <- Z2R_mult in H3.\n  rewrite round_generic in H3.\n  - destruct (Rlt_bool_spec (Rabs (Z2R (Int.signed (Int64.hiword l) * 4294967296)))\n                            (bpow radix2 1024)).\n    + rewrite H0 in H3.\n      destruct H3 as [? [? ?]].\n      { unfold add, b64_plus.\n        pose proof (Bplus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE\n                      (Bmult 53 1024 eq_refl eq_refl binop_pl mode_NE\n                         (binary_normalize64 (Int.signed (Int64.hiword l)) 0 false)\n                            (pow2_float false 32 (conj eq_refl eq_refl)))\n                            (binary_normalize64 (Int.unsigned (Int64.loword l)) 0 false) H6 H2).\n        rewrite H3, H1, <- Z2R_plus in H8.\n        change 4294967296 with (two_p 32) in H8.\n        rewrite <- Int64.ofwords_add'', Int64.ofwords_recompose in H8.\n        destruct (Rlt_bool_spec\n                    (Rabs\n                       (round radix2 (FLT_exp (3 - 1024 - 53) 53)\n                              (round_mode mode_NE) (Z2R (Int64.signed l))))\n                    (bpow radix2 1024)).\n        - unfold floatoflong. unfold binary_normalize64.\n          pose proof (binary_normalize64_correct (Int64.signed l) 0 false).\n          replace (F2R (beta:=radix2) {| Fnum := Int64.signed l; Fexp := 0 |})\n          with (Z2R (Int64.signed l)) in H10\n          by (unfold F2R, Fexp, Fnum, bpow; field).\n          rewrite Rlt_bool_true in H10 by auto.\n          destruct (Int64.eq_dec l Int64.zero). subst. reflexivity.\n          destruct H10, H8.\n          assert (1 <= round radix2 (FLT_exp (3 - 1024 - 53) 53) (round_mode mode_NE)\n                             (Z2R (Zabs (Int64.signed l))))%R.\n          { erewrite <- round_generic with (x:=1%R).\n            apply round_le. apply fexp_correct. reflexivity. apply valid_rnd_round_mode.\n            assert (Int64.signed l <> 0).\n            { contradict n. rewrite <- (Int64.repr_signed l), n. auto. }\n            change 1%R with (Z2R 1). apply Z2R_le.\n            zify. omega. apply valid_rnd_round_mode.\n            apply (generic_format_bpow _ _ 0). compute. discriminate. }\n          rewrite Z2R_abs in H13.\n          rewrite round_NE_abs in H13 by (apply fexp_correct; reflexivity).\n          change ZnearestE with (round_mode mode_NE) in H13.\n          unfold binary_normalize64 in *.\n          apply B2R_inj.\n          + destruct H11, (binary_normalize 53 1024 eq_refl eq_refl mode_NE (Int64.signed l) 0 false); try discriminate.\n            unfold B2R in H10. rewrite <- H10, Rabs_R0 in H13. apply (le_Z2R 1 0) in H13. omega.\n            auto.\n          + destruct H12; match goal with Hf0:is_finite _ _ ?f0 = true,\n                            Hf1:B2R _ _ ?f1 = _ |-\n                            is_finite_strict _ _ ?f = true =>\n                            change f0 with f in Hf0; change f1 with f in Hf1;\n                            destruct f\n            end; try discriminate.\n            unfold B2R in H8. rewrite <- H8, Rabs_R0 in H13. apply (le_Z2R 1 0) in H13. omega.\n            auto.\n          + rewrite H10. symmetry. apply H8.\n        - exfalso.\n          eapply Rle_trans with (r3:=round radix2 (FLT_exp (3 - 1024 - 53) 53)\n                                           (round_mode mode_NE) (bpow radix2 64)) in H9.\n          rewrite round_generic in H9.\n          + eapply le_bpow in H9. omega.\n          + apply valid_rnd_round_mode.\n          + apply generic_format_bpow. compute. discriminate.\n          + rewrite <- round_NE_abs. 2:apply fexp_correct; reflexivity.\n            apply round_le. apply fexp_correct; reflexivity. apply valid_rnd_round_mode.\n            rewrite <- Z2R_abs. change (bpow radix2 64)%R with (Z2R Int64.modulus).\n            apply Z2R_le.\n            destruct (Int64.signed_range l).\n            assert (-Int64.modulus < Int64.min_signed) by reflexivity.\n            assert (Int64.max_signed < Int64.modulus) by reflexivity.\n            zify. omega. }\n    + exfalso.\n      rewrite <- Z2R_abs in H5.\n      change (bpow radix2 1024) with (Z2R (radix2 ^ 1024)) in H5.\n      apply le_Z2R in H5. assert (radix2 ^ 1024 < 18446744073709551616) by (zify; omega).\n      discriminate.\n  - apply valid_rnd_round_mode.\n  - destruct (Z.eq_dec (Int.signed (Int64.hiword l)) 0).\n    rewrite e. apply generic_format_0.\n    apply generic_format_FLT_FLX.\n    + apply Rle_trans with (bpow radix2 0). apply bpow_le. omega.\n      change (bpow radix2 0) with (Z2R 1). rewrite <- Z2R_abs. apply Z2R_le.\n      clear - n H4. zify; omega.\n    + apply generic_format_FLX.\n      eexists {| Fnum := Int.signed (Int64.hiword l); Fexp := 32 |}.\n      unfold F2R, Fnum, Fexp. split.\n      rewrite Z2R_mult. auto.\n      change (radix2 ^ 53) with 9007199254740992.\n      clear -n H4. zify; omega.\nQed.\n\nTheorem floatoflong_from_words:\n  forall l,\n  floatoflong l =\n    add (sub (from_words ox4530_0000 (Int.add (Int64.hiword l) ox8000_0000))\n             (from_words ox4530_0000 (Int.repr (two_p 20+two_p 31))))\n        (from_words ox4330_0000 (Int64.loword l)).\nProof.\n  intros.\n  pose proof  (Int64.signed_range l);\n  compute_this (Int64.min_signed); compute_this (Int64.max_signed).\n  pose proof (Int.unsigned_range (Int.add (Int64.hiword l) ox8000_0000)).\n  destruct (from_words_value (Int64.loword l)).\n  destruct (from_words_value' (Int.add (Int64.hiword l) ox8000_0000)).\n  destruct (from_words_value' (Int.repr (two_p 20+two_p 31))).\n  unfold sub, b64_minus.\n  pose proof (Bminus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE\n                             (from_words ox4530_0000 (Int.add (Int64.hiword l) ox8000_0000))\n                             (from_words ox4530_0000 (Int.repr (two_p 20+two_p 31))) H4 H6).\n  rewrite round_generic in H7.\n  - rewrite H3, H5, ox8000_0000_signed_unsigned in H7.\n    replace (bpow radix2 84 + Z2R ((Int.signed (Int64.hiword l) + Int.half_modulus) * two_p 32) -\n             (bpow radix2 84 + Z2R (Int.unsigned (Int.repr (two_p 20+two_p 31)) * two_p 32)))%R\n    with (Z2R (Int.unsigned (Int.add (Int64.hiword l) ox8000_0000) * two_p 32 -two_p 52-two_p 63)) in H7.\n    + rewrite Rlt_bool_true in H7.\n      * { destruct H7 as [? []].\n          unfold floatoflong, binary_normalize64.\n          pose proof (binary_normalize64_correct (Int64.signed l) 0 false).\n          replace (F2R (beta:=radix2) {| Fnum := Int64.signed l; Fexp := 0 |})\n          with (Z2R (Int64.signed l)) in H10\n          by (unfold F2R, Fexp, Fnum, bpow; field).\n          assert (Rabs (round radix2 (FLT_exp (3 - 1024 - 53) 53)\n                              (round_mode mode_NE) (Z2R (Int64.signed l))) <\n                  bpow radix2 1024)%R.\n          { rewrite <- round_NE_abs by (apply fexp_correct; reflexivity).\n          eapply Rle_lt_trans with (Z2R (two_p 64)). 2:apply Z2R_lt; reflexivity.\n          erewrite <- round_generic.\n            - apply round_le. apply fexp_correct; reflexivity.\n              apply (valid_rnd_round_mode mode_NE).\n              rewrite <- Z2R_abs. apply Z2R_le.\n              compute_this (two_p 64). zify; omega.\n            - apply (valid_rnd_round_mode mode_NE).\n            - apply (generic_format_bpow radix2 _ 64). compute. discriminate. }\n          rewrite Rlt_bool_true in H10 by auto.\n          unfold add, b64_plus.\n          pose proof (Bplus_correct 53 1024 eq_refl eq_refl binop_pl mode_NE\n                                    (Bminus 53 1024 eq_refl eq_refl binop_pl mode_NE\n                                            (from_words ox4530_0000 (Int.add (Int64.hiword l) ox8000_0000))\n                                            (from_words ox4530_0000 (Int.repr (two_p 20 + two_p 31))))\n                                    (from_words ox4330_0000 (Int64.loword l)) H8 H2).\n          change (bpow radix2 52) with (Z2R (two_p 52)) in H1.\n          rewrite H7, H1, <- !Z2R_plus, ox8000_0000_signed_unsigned in H12.\n          change (two_p 63) with (Int.half_modulus * two_p 32) in H12.\n          replace ((Int.signed (Int64.hiword l) + Int.half_modulus) *\n                       two_p 32 - two_p 52 - (Int.half_modulus * two_p 32) +\n                       (two_p 52 + Int.unsigned (Int64.loword l)))\n          with (Int.signed (Int64.hiword l) * two_p 32 + Int.unsigned (Int64.loword l))\n            in H12 by ring.\n          rewrite <- Int64.ofwords_add'', Int64.ofwords_recompose, Rlt_bool_true in H12 by auto.\n          destruct (Z.eq_dec (Int64.signed l) 0).\n          - apply (f_equal Int64.repr) in e. rewrite Int64.repr_signed in e.\n            subst. reflexivity.\n          - destruct H12 as [? []], H10 as [? []].\n            assert (1 <= Rabs (round radix2 (FLT_exp (3 - 1024 - 53) 53)\n                                (round_mode mode_NE) (Z2R (Int64.signed l)))) %R.\n            { rewrite <- round_NE_abs, <- Z2R_abs by (apply fexp_correct; reflexivity).\n              erewrite <- round_generic with (x := 1%R). \n              3:eapply (generic_format_bpow _ _ 0).\n              apply round_le, (Z2R_le 1).\n              apply fexp_correct; reflexivity. apply (valid_rnd_round_mode mode_NE).\n              zify; omega.\n              apply (valid_rnd_round_mode mode_NE).\n              compute; discriminate. }\n            eapply B2R_inj.\n            + destruct binary_normalize; try discriminate H15.\n              unfold B2R in H10. rewrite <- H10, Rabs_R0 in H17. apply (le_Z2R 1 0) in H17. omega.\n              auto.\n            + match goal with Hf0:is_finite _ _ ?f0 = true,\n                                            Hf1:B2R _ _ ?f1 = _ |-\n                                        is_finite_strict _ _ ?f = true =>\n                                        change f0 with f in Hf0; change f1 with f in Hf1;\n                                        destruct f\n              end; try discriminate H13.\n              unfold B2R in H12. rewrite <- H12, Rabs_R0 in H17. apply (le_Z2R 1 0) in H17. omega.\n              auto.\n            + etransitivity; eauto. }\n      * rewrite <- Z2R_abs. apply (Z2R_lt _ (2^1024)).\n        compute_this Int.modulus; compute_this (two_p 32);\n        compute_this (two_p 52); compute_this (two_p 63); compute_this (2^1024).\n        clear - H0. zify; omega.\n    + rewrite ox8000_0000_signed_unsigned, !Z2R_minus.\n      compute_this (Z2R (Int.unsigned (Int.repr (two_p 20 + two_p 31)) * two_p 32)).\n      compute_this (Z2R (two_p 52)). compute_this (Z2R (two_p 63)). ring.\n  - apply valid_rnd_round_mode.\n  - apply sterbenz.\n    + apply FLT_exp_monotone.\n    + apply generic_format_B2R.\n    + apply generic_format_B2R.\n    + rewrite H3, H5, Int.unsigned_repr by (compute; split; discriminate).\n      unfold bpow. rewrite <- !Z2R_plus, <- (Z2R_mult 2).\n      compute_this (Z.pow_pos radix2 84); compute_this (Z.pow_pos radix2 84);\n      compute_this ((two_p 20 + two_p 31) * two_p 32); compute_this (two_p 32);\n      compute_this (Int.modulus).\n      change (19342813113834066795298816 + 9227875636482146304)\n      with (9671411170854851638722560 * 2).\n      unfold Rdiv. rewrite Z2R_mult, Rmult_assoc, Rinv_r, Rmult_1_r by (apply (Z2R_neq 2 0); omega).\n      split; apply Z2R_le; omega.\nQed.\n\nGlobal Opaque\n  zero eq_dec neg abs singleoffloat intoffloat intuoffloat floatofint floatofintu\n  add sub mul div cmp bits_of_double double_of_bits bits_of_single single_of_bits from_words.\n\nEnd Float.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/compcert/lib/Floats.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22514787529083652}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils\n     PCUICEquality PCUICTyping PCUICReduction PCUICSigmaCalculus\n     PCUICNamelessDef PCUICRenameDef PCUICInstDef.\n\n(* AXIOM postulate correctness of the guard condition checker *)\n\nDefinition tFixCoFix (b:FixCoFix) := if b then tFix else tCoFix.\n\nDefinition nl_mfix mfix := map (map_def_anon nl nl) mfix.\n\nDefinition subst_instance_mfix (mfix : list (def term)) u := map (map_def (subst_instance u) (subst_instance u)) mfix.\n\nDefinition inst_mfix mfix σ := map (map_def (inst σ) (inst (up (List.length mfix) σ))) mfix.\n\nDefinition rename_mfix mfix f := map (map_def (rename f) (rename (shiftn (List.length mfix) f))) mfix.\n\nClass GuardCheckerCorrect :=\n{\n  guard_red1 b Σ Γ mfix mfix' idx :\n    Σ.1 ;;; Γ |- tFixCoFix b mfix idx ⇝ tFixCoFix b mfix' idx ->\n    guard b Σ Γ mfix ->\n    guard b Σ Γ mfix' ;\n\n  guard_eq_term b Σ Γ mfix mfix' idx :\n    upto_names (tFixCoFix b mfix idx) (tFixCoFix b mfix' idx) ->\n    guard b Σ Γ mfix ->\n    guard b Σ Γ mfix' ;\n\n  guard_extends b (Σ Σ':global_env_ext) Γ mfix :\n    extends Σ Σ' ->\n    guard b Σ Γ mfix ->\n    guard b Σ' Γ mfix ;\n\n  guard_context_cumulativity `{checker_flags} b Σ Γ Γ' mfix :\n    All2_fold (cumul_decls cumulSpec0 Σ) Γ' Γ ->\n    guard b Σ Γ mfix ->\n    guard b Σ Γ' mfix ;\n\n  guard_subst_instance `{checker_flags} b Σ Γ mfix u univs :\n    consistent_instance_ext (Σ.1, univs) Σ.2 u ->\n    guard b Σ Γ mfix ->\n    guard b (Σ.1, univs) (subst_instance u Γ) (subst_instance_mfix mfix u) ;\n\n  guard_inst `{checker_flags} b Σ Γ Δ mfix σ :\n    Σ ;;; Γ ⊢ σ : Δ ->\n    guard b Σ Δ mfix ->\n    guard b Σ Γ (inst_mfix mfix σ) ;\n\n  guard_rename `{checker_flags} b P Σ Γ Δ mfix f :\n    urenaming P Γ Δ f ->\n    guard b Σ Γ mfix ->\n    guard b Σ Δ (rename_mfix mfix f) ;\n\n}.\n\nAxiom guard_checking_correct : GuardCheckerCorrect.\n#[global] Existing Instance guard_checking_correct.\n\nDefinition fix_guard_red1 := guard_red1 Fix.\nDefinition fix_guard_eq_term := guard_eq_term Fix.\nDefinition fix_guard_subst_instance `{checker_flags} := guard_subst_instance Fix.\nDefinition fix_guard_extends := guard_extends Fix.\nDefinition fix_guard_context_cumulativity `{checker_flags} := guard_context_cumulativity Fix.\nDefinition fix_guard_inst `{checker_flags} := guard_inst Fix.\nDefinition fix_guard_rename `{checker_flags} := guard_rename Fix.\n\nDefinition cofix_guard_red1 := guard_red1 CoFix.\nDefinition cofix_guard_eq_term := guard_eq_term CoFix.\nDefinition cofix_guard_subst_instance `{checker_flags} := guard_subst_instance CoFix.\nDefinition cofix_guard_extends := guard_extends CoFix.\nDefinition cofix_guard_context_cumulativity `{checker_flags} := guard_context_cumulativity CoFix.\nDefinition cofix_guard_inst `{checker_flags} := guard_inst CoFix.\nDefinition cofix_guard_rename `{checker_flags} := guard_rename CoFix.\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/pcuic/theories/PCUICGuardCondition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2250751679152325}}
{"text": "Require Import GradebookModel. (* change this module name or move to here *)\nRequire Import List.\n\nSet Implicit Arguments.\n\nModule Config.\n  (* privacy respecting queries can probably stay the same *)\n  Definition P (cfg: Config) (q: Command) := True.\n  (* likewise with correct queries *)\n  Definition E (cfg: Config) (q: Command) := True. \n  (* todo add definition of privacy and wellformedness of q *)\n  Parameter P_dec : forall cfg q, {P cfg q} + {~P cfg q}. (* privacy *)\n  Parameter E_dec : forall cfg q, {E cfg q} + {~E cfg q}. (* valid query *)\nEnd Config.\n\nModule Type Model.\n  Export Config.\n  Parameter M : Type.\n  Parameter I : Config -> M -> Prop.\n  Parameter mutate : forall (cfg: Config) (q: Command) (m: M), (Status * M).\n  Parameter pres_I : forall cfg q m,\n    I cfg (snd (mutate cfg q m)).\nEnd Model.\n\nRequire Import Ynot.\nModule Type Impl (X: Model).\n Export X.\n  Parameter T: Set.\n  Parameter rep : forall (t: T) (m: M), hprop.\n\n  Open Local Scope hprop_scope.\n  Parameter imp_mutate : forall cfg t q (m: [M]),\n    STsep (m ~~ rep t m * [I cfg m] * [P cfg q] * [E cfg q]) \n          (fun r : Status => m ~~ let (r', m') := (mutate cfg q m)\n                                  in  [r' = r] * rep t m'). \nEnd Impl.\n \n(* our spec is a distinguished model *) \nModule Spec : Model.\n Export Config.\n   Definition  M := ID -> Assignment -> option Grade. \n   \n   Definition  I : Config -> M -> Prop. \n   Admitted.\n  \n  Parameter mutate : forall (cfg: Config) (q: Command) (m: M), (Status * M).\n\n    Theorem pres_I : forall cfg q m,\n    I cfg (snd (mutate cfg q m)).\n    Admitted.\nEnd Spec.\n\n(* The model of the imperative implementation *)\nModule TupleModel : Model.\n Export Config.\n   Definition  M := ID -> Assignment -> option Grade. \n   \n   Definition  I : Config -> M -> Prop. \n   Admitted.\n  \n  Parameter mutate : forall (cfg: Config) (q: Command) (m: M), (Status * M).\n\n    Theorem pres_I : forall cfg q m,\n    I cfg (snd (mutate cfg q m)).\n    Admitted.\nEnd TupleModel.\n\n(* equivalences of models *)\nModule Type ModelIso.\n  Export Config.\n  Declare Module S : Model.\n  Declare Module T : Model.\n\n  Parameter f : forall cfg, sigT (S.I cfg) -> sigT (T.I cfg).\n  Parameter g : forall cfg, sigT (T.I cfg) -> sigT (S.I cfg).\n\n  (* we probably don't want \n  Parameter Correct : forall cfg t, f (cfg:=cfg)(g t) = t. *)\n  \n  Parameter Correct : forall cfg t, \n   projT1 (f (g (cfg:=cfg) t)) = projT1 t. \nEnd ModelIso.\n\nModule CorrectRefl (X: Model) : ModelIso with Module S := X \n                                         with Module T := X.\n  Export Config.\n  Module S := X.\n  Module T := X.\n\n  Definition f cfg (x: sigT (S.I cfg)) := x.\n  Definition g cfg (y: sigT (T.I cfg)) := y. \n\n  Theorem Correct : forall cfg t, \n   projT1 (f (g (cfg:=cfg) t)) = projT1 t. \n  Proof.\n    compute. intros. eauto. Qed.\nEnd CorrectRefl.\n\n(* todo the isomorphism of the models isn't quite implementation\n   correctness.  technically we need to take into account\n   the outer wrapping where the invariant is checked, where\n   privacy is checked, etc.  But that should be easy enough\n   to build off of this. *)\nModule ImplCorrect : ModelIso with Module S := Spec \n                              with Module T := TupleModel.\n  Export Config.\n  Module S := Spec.\n  Module T := TupleModel.\n   \n  Definition f cfg (x: sigT (S.I cfg)) : sigT (T.I cfg). \n  Admitted.\n  Definition g cfg (y: sigT (T.I cfg)) : sigT (S.I cfg). \n  Admitted. \n\n  Theorem Correct : forall cfg t, \n   projT1 (f (g (cfg:=cfg) t)) = projT1 t. \n  Proof.\n  Admitted.\nEnd ImplCorrect.\n\n(* we want to say that given a model and\n   an imperative realization of that model, that\n   we can build an app \nRequire Import AppServer.\n\nModule BuildApp (X: Model) (Y: Impl X) : App.\n Module C := Y X.\n Export C.\n Open Local Scope hprop_scope.\n Definition Q := Command.\n Definition T : Set := (Config * C.T)%type.\n Definition RR : Set := Status.\n Definition M := (Config * X.M)%type.\n Definition rep (t: T) (m: M) : hprop := [fst t = fst m] * C.rep (snd t) (snd m).\n Definition I (m: M) : Prop := X.I (fst m) (snd m).\n \n Definition func := X.mutate.\n\nEnd BuildApp.\n*)\n\n(* these wrappers may come in handy \n   for above. *)\nModule WrapModel (X: Model).\n  Export X.\n\n  Definition wrap cfg q m (pf_I: I cfg m) :=\n    match P_dec cfg q with\n      | left  pf_P => match E_dec cfg q with\n                        | left  pf_E => mutate cfg q m  \n                        | right pf_badgrade => (ERR_BADGRADE, m) \n                      end\n      | right pf_notpriv => (ERR_NOTPRIVATE, m)\n    end.\nEnd WrapModel.\n\nRequire Import Ynot.\nModule WrapImpl (X: Model) (Y: Impl).\n Module Z := Y X.\n Export Z.\n Module W := WrapModel X.\n Export W.\n\n Open Local Scope stsepi_scope.\n Open Local Scope hprop_scope.\n Definition imp_wrap cfg t q m : \n  STsep (m ~~ rep t m * [I cfg m] * [P cfg q] * [E cfg q]) \n   (fun r : Status => m ~~ Exists pf1 :@ I cfg m, \n                           let (r', m') := (wrap q pf1 )\n                           in  [r' = r] * rep t m').\n Admitted. \nEnd WrapImpl.\n\nRequire Import Store.\n\n(* And we need to do this as well\nModule StoreImpl (s: Store) : Impl TupleModel .\n \nEnd StoreImpl.\n*)\n", "meta": {"author": "Ptival", "repo": "ynot", "sha": "cd6f28816c41bbef7464b644edeba099d397a01e", "save_path": "github-repos/coq/Ptival-ynot", "path": "github-repos/coq/Ptival-ynot/ynot-cd6f28816c41bbef7464b644edeba099d397a01e/examples/servers/Mapping2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2250751679152325}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import TableWalk.Spec.\nRequire Import AbsAccessor.Spec.\nRequire Import TableDataOpsIntro.Specs.data_create_unknown.\nRequire Import TableDataOpsIntro.LowSpecs.data_create_unknown.\nRequire Import TableDataOpsIntro.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       table_walk_lock_unlock_spec\n       get_wi_g_llt_spec\n       get_wi_index_spec\n       is_null_spec\n       granule_map_spec\n       pgte_read_spec\n       pgte_write_spec\n       set_mapping_spec\n       granule_get_spec\n       buffer_unmap_spec\n       granule_unlock_spec\n  .\n\n  Lemma data_create_unknown_spec_exists:\n    forall habd habd'  labd g_rd data_addr map_addr g_data res\n      (Hspec: data_create_unknown_spec g_rd data_addr map_addr g_data habd = Some (habd', res))\n      (Hrel: relate_RData habd labd),\n    exists labd', data_create_unknown_spec0 g_rd data_addr map_addr g_data labd = Some (labd', res) /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque peq ptr_eq.\n    assert(ne51: 5<>1) by (red; intro T; inv T).\n    assert(ne50: 5<>0) by (red; intro T; inv T).\n    assert(ne10: 1<>0) by (red; intro T; inv T).\n    intros. destruct Hrel. inv id_rdata. destruct g_data, g_rd.\n    unfold data_create_unknown_spec, data_create_unknown_spec0 in *. simpl.\n    unfold table_walk_lock_unlock_spec. simpl. unfold Assertion in *.\n    rm_bind Hspec; rm_bind'. simpl in *. repeat simpl_hyp Hspec.\n    unfold Assertion; rm_bind'.\n    repeat simpl_hyp Hspec.\n    hsimpl_hyp Hspec; inv Hspec; extract_prop_dec.\n    - repeat destruct_con. simpl_query_oracle.\n      match type of Hcond6 with\n      | is_gidx ?gidx = true => remember gidx as lv1_gidx eqn:Hlv1_gidx; symmetry in Hlv1_gidx\n      end.\n      match type of Hcond3 with\n      | is_gidx ?gidx = true => remember gidx as lv2_gidx eqn:Hlv2_gidx; symmetry in Hlv2_gidx\n      end.\n      match type of Hcond0 with\n      | is_gidx ?gidx = true => remember gidx as llt_gidx eqn:Hllt_gidx; symmetry in Hllt_gidx\n      end.\n      repeat simpl_field; repeat swap_fields; repeat simpl_field.\n      assert(nelz: llt_gidx <> (__addr_to_gidx z2)) by (bool_rel; red; intro T; rewrite T in *; autounfold in *; omega).\n      repeat autounfold in *. simpl in *.\n      destruct_if. repeat destruct_con. bool_rel; omega.\n      solve_bool_range. grewrite. repeat solve_table_range.\n      repeat (try solve_peq; try solve_ptr_eq; simpl). simpl_htarget.\n      repeat (grewrite; try simpl_htarget; simpl; repeat solve_table_range).\n      repeat (repeat simpl_field; repeat swap_fields; simpl_htarget).\n      extract_if. reflexivity. grewrite. solve_table_range.\n      repeat (grewrite; try simpl_htarget; simpl; repeat solve_table_range).\n      eexists; split. reflexivity. constructor.\n      repeat (try rewrite (zmap_comm _ _ ne51);\n              try rewrite (zmap_comm _ _ nelz)).\n      repeat (repeat simpl_field; repeat swap_fields; simpl_htarget).\n      rewrite <- Prop1. simpl_field. rewrite Z.mul_1_l. bool_rel. grewrite.\n      rewrite <- C38. simpl_field. reflexivity.\n    - repeat destruct_con. simpl_query_oracle.\n      match type of Hcond6 with\n      | is_gidx ?gidx = true => remember gidx as lv1_gidx eqn:Hlv1_gidx; symmetry in Hlv1_gidx\n      end.\n      match type of Hcond3 with\n      | is_gidx ?gidx = true => remember gidx as lv2_gidx eqn:Hlv2_gidx; symmetry in Hlv2_gidx\n      end.\n      match type of Hcond0 with\n      | is_gidx ?gidx = true => remember gidx as llt_gidx eqn:Hllt_gidx; symmetry in Hllt_gidx\n      end.\n      repeat simpl_field; repeat swap_fields; repeat simpl_field.\n      repeat autounfold in *. simpl in *.\n      destruct_if. repeat destruct_con. bool_rel; omega.\n      solve_bool_range. grewrite. repeat solve_table_range.\n      repeat (try solve_peq; try solve_ptr_eq; simpl). simpl_htarget.\n      repeat (grewrite; try simpl_htarget; simpl; repeat solve_table_range).\n      inversion Hspec. clear Hspec. extract_prop_dec.\n      eexists; split. reflexivity. constructor.\n      repeat rewrite (zmap_comm _ _ ne51).\n      bool_rel. simpl_htarget. clear H0. grewrite.\n      repeat (repeat simpl_field; repeat swap_fields; repeat simpl_field; simpl_htarget; simpl).\n      rewrite <- Prop0, <- C38. repeat simpl_field. simpl_htarget. simpl_field. reflexivity.\n    - unfold get_wi_g_llt_spec, is_null_spec; simpl. solve_ptr_eq; simpl.\n      autounfold in *; solve_table_range. inv Hspec. eexists; split. reflexivity. constructor.\n      reflexivity.\n    - unfold get_wi_g_llt_spec, is_null_spec; simpl. solve_ptr_eq; simpl.\n      autounfold in *; solve_table_range. inv Hspec. eexists; split. reflexivity. constructor.\n      reflexivity.\n    - unfold get_wi_g_llt_spec, is_null_spec; simpl. solve_ptr_eq; simpl.\n      autounfold in *; solve_table_range. inv Hspec. eexists; split. reflexivity. constructor.\n      reflexivity.\n  Qed.\n\nEnd Refine.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataSMC/RefProof/smc_data_create_unknown.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.22500658830556908}}
{"text": "Set Implicit Arguments.\n\nSection ADTValue.\n\n  Variable ADTValue : Type.\n\n  Require Import Bedrock.Platform.Cito.SemanticsFacts4.\n  Require Import Bedrock.Platform.Cito.ProgramLogic2.\n  Require Import Bedrock.Platform.Cito.Transit.\n  Require Import Bedrock.Platform.Cito.Semantics.\n\n  Require Import Bedrock.Platform.Cito.GLabel.\n  Require Import Bedrock.Platform.Cito.GLabelMap.\n  Import GLabelMap.\n  Require Import Bedrock.Platform.Cito.GLabelMapFacts.\n\n  Notation Internal := (@Internal ADTValue).\n\n  Definition strengthen_specs specs_op specs_ax env_ax :=\n    forall (lbl : glabel),\n      find lbl specs_op = find lbl specs_ax \\/\n      exists spec_op spec_ax,\n        find lbl specs_op = Some (Internal spec_op) /\\\n        find lbl specs_ax = Some (Foreign spec_ax) /\\\n        strengthen_op_ax spec_op spec_ax env_ax.\n\n  Require Import Bedrock.Platform.Cito.GeneralTactics Bedrock.Platform.Cito.GeneralTactics2.\n  Require Import Bedrock.Platform.Cito.Option.\n\n  Lemma strengthen_specs_strengthen : forall specs_op specs_ax env_op env_ax, strengthen_specs specs_op specs_ax env_ax -> specs_env_agree specs_op env_op -> specs_env_agree specs_ax env_ax -> (forall lbl, fst env_op lbl = fst env_ax lbl) -> strengthen env_op env_ax.\n  Proof.\n    split; intros.\n    eauto.\n    destruct (option_dec (fs_op w)).\n    destruct s.\n    generalize e; intro.\n    eapply H0 in e.\n    openhyp.\n    edestruct (H x0).\n    left.\n    rewrite e0.\n    symmetry.\n    eapply H1.\n    rewrite H5 in H4; clear H5.\n    descend; eauto.\n    rewrite <- H2.\n    eauto.\n\n    openhyp.\n    rewrite H5 in H4; injection H4; intros; subst.\n    assert (fs_ax w = Some (Foreign x2)).\n    eapply H1.\n    descend; eauto.\n    rewrite <- H2; eauto.\n    right; descend; eauto.\n\n    destruct (option_dec (fs_ax w)).\n    destruct s.\n    generalize e0; intro.\n    eapply H1 in e0.\n    openhyp.\n    edestruct (H x0).\n    assert (fs_op w = Some x).\n    eapply H0.\n    descend; eauto.\n    rewrite H2; eauto.\n    rewrite H5.\n    eauto.\n    rewrite H6 in e; intuition.\n    openhyp.\n    assert (fs_op w = Some (Internal x1)).\n    eapply H0.\n    descend; eauto.\n    rewrite H2; eauto.\n    rewrite H8 in e; intuition.\n    left; congruence.\n  Qed.\n\n  Notation Foreign := (@Foreign ADTValue).\n\n  Definition apply_specs_diff specs specs_diff := update specs (map Foreign specs_diff).\n\n  Definition strengthen_diff_f specs env_ax k v a :=\n    a /\\\n    (find k specs = Some (Foreign v) \\/\n     exists op,\n       find k specs = Some (Internal op) /\\\n       strengthen_op_ax op v env_ax).\n\n  Definition strengthen_diff specs specs_diff env_ax :=\n    fold (strengthen_diff_f specs env_ax) specs_diff True.\n\n  Lemma strengthen_diff_intro : forall specs_diff env_ax specs, (forall lbl ax, find lbl specs_diff = Some ax -> find lbl specs = Some (Foreign ax) \\/ exists op, find lbl specs = Some (Internal op) /\\ strengthen_op_ax op ax env_ax) -> strengthen_diff specs specs_diff env_ax.\n  Proof.\n    do 3 intro.\n    (* intros Hforall. *)\n    (* unfold strengthen_diff. *)\n    eapply fold_rec_bis with (P := fun specs_diff (H : Prop) => (forall lbl ax, find lbl specs_diff = Some ax -> find lbl specs = Some (Foreign ax) \\/ exists op, find lbl specs = Some (Internal op) /\\ strengthen_op_ax op ax env_ax) -> H); simpl.\n    intros m m' a Heqm Ha Hforall.\n    { \n      eapply Ha.\n      intros lbl ax Hfind.\n      rewrite Heqm in Hfind.\n      eauto.\n    }\n    { eauto. }\n    intros k e a m' Hmapsto Hnin Ha Hforall.\n    unfold strengthen_diff_f.\n    split.\n    {\n      eapply Ha.\n      intros lbl ax Hfind.\n      eapply Hforall.\n      eapply find_mapsto_iff.\n      eapply add_mapsto_iff.\n      right.\n      split.\n      {\n        intro Heq; subst.\n        contradict Hnin.\n        eapply MapsTo_In.\n        eapply find_mapsto_iff.\n        eauto.\n      }\n      eapply find_mapsto_iff.\n      eauto.\n    }\n    eapply Hforall.\n    eapply find_mapsto_iff.\n    eapply add_mapsto_iff.\n    left.\n    eauto.\n  Qed.\n\n  Lemma strengthen_diff_elim : forall specs_diff env_ax specs, strengthen_diff specs specs_diff env_ax -> forall lbl ax, find lbl specs_diff = Some ax -> find lbl specs = Some (Foreign ax) \\/ exists op, find lbl specs = Some (Internal op) /\\ strengthen_op_ax op ax env_ax.\n    do 3 intro.\n    eapply fold_rec_bis with (P := fun specs_diff (H : Prop) => H -> forall lbl ax, find lbl specs_diff = Some ax -> find lbl specs = Some (Foreign ax) \\/ exists op, find lbl specs = Some (Internal op) /\\ strengthen_op_ax op ax env_ax); simpl; intros.\n    eapply H0; eauto.\n    rewrite H; eauto.\n    rewrite empty_o in H0; intuition.\n    eapply find_mapsto_iff in H3.\n    eapply add_mapsto_iff in H3.\n    openhyp.\n    subst.\n    destruct H2.\n    openhyp.\n    eauto.\n    right; descend; eauto.\n    eapply H1.\n    destruct H2; eauto.\n    eapply find_mapsto_iff; eauto.\n  Qed.\n\n  Lemma strengthen_diff_strengthen_specs : forall specs specs_diff env_ax, strengthen_diff specs specs_diff env_ax -> strengthen_specs specs (apply_specs_diff specs specs_diff) env_ax.\n    intros.\n    unfold strengthen_specs.\n    intros.\n    destruct (option_dec (find lbl specs_diff)).\n    destruct s.\n    eapply strengthen_diff_elim in H; eauto.\n    openhyp.\n    left.\n    rewrite H.\n    symmetry.\n    eapply find_mapsto_iff.\n    eapply update_mapsto_iff.\n    left.\n    eapply find_mapsto_iff.\n    rewrite map_o.\n    rewrite e.\n    eauto.\n    right; descend; eauto.\n    eapply find_mapsto_iff.\n    eapply update_mapsto_iff.\n    left.\n    eapply find_mapsto_iff.\n    rewrite map_o.\n    rewrite e.\n    eauto.\n    left.\n    unfold apply_specs_diff.\n    rewrite update_o_1; eauto.\n    nintro.\n    eapply map_4 in H0.\n    eapply In_find_not_None in H0.\n    erewrite e in H0.\n    intuition.\n  Qed.\n\n  Lemma strengthen_diff_strenghthen : forall specs specs_diff env_op env_ax, strengthen_diff specs specs_diff env_ax -> specs_env_agree specs env_op -> specs_env_agree (apply_specs_diff specs specs_diff) env_ax -> (forall lbl, fst env_op lbl = fst env_ax lbl) -> strengthen env_op env_ax.\n    intros.\n    eapply strengthen_specs_strengthen; eauto.\n    eapply strengthen_diff_strengthen_specs; eauto.\n  Qed.\n\n  Notation Callee := (@Callee ADTValue).\n\n  Definition is_pointer_of_label specs (stn : glabel -> option W) w : option Callee :=\n    fold (fun k v res =>\n            match res with\n              | Some _ => res\n              | None =>\n                match stn k with\n                  | Some w' => if weq w w' then Some v else None\n                  | None => None\n                end\n            end\n         ) specs None.\n\n  Notation Env := (@Env ADTValue).\n\n  Definition change_env new_specs (env : Env) : Env :=\n    let stn := fst env in\n    let fs := snd env in\n    (stn,\n     fun w =>\n       match is_pointer_of_label new_specs stn w with\n         | Some new_spec => Some new_spec\n         | None => fs w\n       end).\n\n  Notation specs_stn_injective := (@specs_stn_injective ADTValue).\n\n  Lemma sub_domain_specs_stn_injective : forall specs1 specs2 stn, specs_stn_injective specs1 stn -> sub_domain specs2 specs1 -> specs_stn_injective specs2 stn.\n    unfold ProgramLogic2.specs_stn_injective, sub_domain; intros.\n    eapply H; eauto.\n  Qed.\n\n  Lemma add_specs_stn_injective : forall specs k v stn, specs_stn_injective (add k v specs) stn -> specs_stn_injective specs stn.\n    intros.\n    eapply sub_domain_specs_stn_injective; eauto.\n    unfold sub_domain; intros.\n    eapply add_in_iff; eauto.\n  Qed.\n\n  Lemma is_pointer_of_label_intro_elim : forall specs stn w, (forall v, is_pointer_of_label specs stn w = Some v -> exists lbl, find lbl specs = Some v /\\ stn lbl = Some w) /\\ (forall v lbl, specs_stn_injective specs stn -> find lbl specs = Some v -> stn lbl = Some w -> is_pointer_of_label specs stn w = Some v).\n    do 3 intro.\n    eapply fold_rec_bis with (P := fun specs a => (forall v, a = Some v -> exists lbl, find lbl specs = Some v /\\ stn lbl = Some w) /\\ (forall v lbl, specs_stn_injective specs stn -> find lbl specs = Some v -> stn lbl = Some w -> a = Some v)); simpl; intros.\n    unfold ProgramLogic2.specs_stn_injective in *.\n    setoid_rewrite H in H0.\n    eapply H0; eauto.\n    split; intros.\n    intuition.\n    rewrite empty_o in H0; intuition.\n    openhyp.\n    split; intros.\n    destruct a.\n    injection H3; intros; subst.\n    edestruct H1; eauto.\n    openhyp.\n    descend; eauto.\n    eapply find_mapsto_iff; eapply add_mapsto_iff.\n    right.\n    split.\n    nintro; subst.\n    eapply find_mapsto_iff in H4; eapply MapsTo_In in H4.\n    contradiction.\n    eapply find_mapsto_iff; eauto.\n    destruct (option_dec (stn k)).\n    destruct s.\n    rewrite e0 in *.\n    destruct (weq w x).\n    subst.\n    injection H3; intros; subst.\n    descend; eauto.\n    eapply find_mapsto_iff; eapply add_mapsto_iff.\n    eauto.\n    intuition.\n    rewrite e0 in *; intuition.\n    destruct a.\n    edestruct H1; eauto.\n    openhyp.\n    eapply find_mapsto_iff in H4; eapply find_mapsto_iff in H6.\n    assert (lbl = x).\n    eapply H3; eauto.\n    eapply MapsTo_In; eauto.\n    eapply add_in_iff; right; eapply MapsTo_In; eauto.\n    subst.\n    eapply add_mapsto_iff in H4; openhyp.\n    subst.\n    eapply MapsTo_In in H6; contradiction.\n    eapply H2; eauto.\n    eapply add_specs_stn_injective; eauto.\n    eapply find_mapsto_iff; eauto.\n\n    eapply find_mapsto_iff in H4.\n    destruct (option_dec (stn k)).\n    destruct s.\n    rewrite e0 in *.\n    eapply add_mapsto_iff in H4; openhyp.\n    subst.\n    rewrite H5 in e0; injection e0; intros; subst.\n    destruct (weq x x); intuition.\n    destruct (weq w x).\n    subst.\n    contradict H4.\n    eapply H3; eauto.\n    eapply add_in_iff; eauto.\n    eapply add_in_iff; right; eapply MapsTo_In; eauto.\n    eapply H2; eauto.\n    eapply add_specs_stn_injective; eauto.\n    eapply find_mapsto_iff; eauto.\n    rewrite e0 in *.\n    eapply add_mapsto_iff in H4; openhyp.\n    subst.\n    rewrite H5 in e0; intuition.\n    eapply H2; eauto.\n    eapply add_specs_stn_injective; eauto.\n    eapply find_mapsto_iff; eauto.\n  Qed.\n\n  Lemma is_pointer_of_label_intro : forall specs stn w v lbl, specs_stn_injective specs stn -> find lbl specs = Some v -> stn lbl = Some w -> is_pointer_of_label specs stn w = Some v.\n    eapply is_pointer_of_label_intro_elim; eauto.\n  Qed.\n\n  Lemma is_pointer_of_label_elim : forall specs stn w v, is_pointer_of_label specs stn w = Some v -> exists lbl, find lbl specs = Some v /\\ stn lbl = Some w.\n    eapply is_pointer_of_label_intro_elim; eauto.\n  Qed.\n\n  Lemma equal_domain_specs_stn_injective : forall specs1 specs2 stn, equal_domain specs1 specs2 -> (specs_stn_injective specs1 stn <-> specs_stn_injective specs2 stn).\n    split; intros.\n    eapply sub_domain_specs_stn_injective; eauto; eapply H.\n    eapply sub_domain_specs_stn_injective; eauto; eapply H.\n  Qed.\n  Lemma equal_domain_sym : forall elt1 elt2 (m1 : t elt1) (m2 : t elt2), equal_domain m1 m2 -> equal_domain m2 m1.\n    unfold equal_domain; intuition.\n  Qed.\n\n  Lemma change_env_agree : forall specs new_specs, equal_domain new_specs specs -> forall env, specs_env_agree specs env -> specs_env_agree new_specs (change_env new_specs env).\n  Proof.\n    unfold specs_env_agree.\n    intros.\n    openhyp.\n    simpl.\n    split.\n    unfold labels_in_scope in *.\n    intros.\n    eapply H0.\n    eapply H; eauto.\n\n    split.\n    eapply equal_domain_specs_stn_injective; eauto.\n\n    unfold specs_fs_agree in *.\n    split; intros.\n    simpl in *.\n    destruct env in *; simpl in *.\n    destruct (option_dec (is_pointer_of_label new_specs o p)).\n    destruct s.\n    rewrite e in *.\n    injection H3; intros; subst.\n    eapply is_pointer_of_label_elim in e; openhyp.\n    descend; eauto.\n    rewrite e in *.\n    eapply H2 in H3; openhyp.\n    eapply find_mapsto_iff in H4; eapply MapsTo_In in H4.\n    eapply H in H4.\n    eapply In_MapsTo in H4; openhyp.\n    assert (is_pointer_of_label new_specs o p = Some x0).\n    eapply is_pointer_of_label_intro; eauto.\n    eapply equal_domain_specs_stn_injective; eauto.\n\n    eapply find_mapsto_iff; eauto.\n    rewrite e in H5; intuition.\n    openhyp.\n    simpl in *.\n    destruct env; simpl in *.\n    assert (is_pointer_of_label new_specs o p = Some spec).\n    eapply is_pointer_of_label_intro; eauto.\n    eapply equal_domain_specs_stn_injective; eauto.\n    rewrite H5; eauto.\n  Qed.\n\n  Lemma sub_domain_apply_specs_diff_equal_domain a b : sub_domain b a -> equal_domain (apply_specs_diff a b) a.\n  Proof.\n    unfold apply_specs_diff.\n    unfold equal_domain.\n    intros H.\n    split.\n    {\n      eapply sub_domain_update_sub_domain; eauto.\n      eapply sub_domain_map_1; eauto.\n    }\n    {\n      eapply sub_domain_update_1.\n      eapply sub_domain_refl.\n    }\n  Qed.\n\nEnd ADTValue.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Platform/Cito/ChangeSpec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.22497234932315835}}
{"text": "Require Import Coq.Lists.List Coq.Logic.FunctionalExtensionality Names.\n\nModule Fun.\n\n  Definition temp_name_mapping := name -> option star.\n\n  Definition temp_name_mapping_star := star -> option star.\n\n  Definition empty : temp_name_mapping := fun _ => None.\n\n  Definition in_domain (f : temp_name_mapping) (x : name) := f x <> None.\n\n  Definition in_range f x := exists y : name, f y = Some (star_name x).\n\n  Definition in_range_in_domain f := forall x, in_range f x -> in_domain f x.\n\n  Definition fun_exclusive f1 f2 := forall x,\n    (in_domain f1 x -> ~ in_domain f2 x) /\\ (in_domain f2 x -> ~ in_domain f1 x).\n\n  Lemma in_domain_not_empty : forall f x, in_domain f x -> f <> empty.\n  Proof.\n    intros.\n    intro.\n    unfold in_domain in H.\n    apply equal_f with x in H0.\n    compute in H0.\n    auto.\n  Qed.\n\n  Definition to_star_function (f : temp_name_mapping) : temp_name_mapping_star :=\n    fun s : star =>\n      match s with\n        | star_name n => f n\n        | _ => Some star_bottom\n      end.\n\n  Definition beq_option_star (o1 : option star) (o2 : option star) : bool :=\n    match o1, o2 with\n      | Some s1, Some s2 => beq_star s1 s2\n      | _, _ => false\n    end.\n\n  Definition fun_plus (f1 : temp_name_mapping) (f2 : temp_name_mapping) : temp_name_mapping :=\n    fun x : name =>\n      match f1 x with\n        | Some n => match n with\n                      | star_bottom => match f2 x with\n                                         | Some n' => Some n'\n                                         | None => Some n\n                                       end\n                      | _ => Some n\n                    end\n        | None => f2 x\n      end.\n\n  Lemma fun_plus_assoc : forall f1 f2 f3, fun_plus f1 (fun_plus f2 f3) = fun_plus (fun_plus f1 f2) f3.\n  Proof.\n    intros.\n    apply functional_extensionality.\n    intros.\n    unfold fun_plus.\n    destruct (f1 x); auto.\n    destruct s; auto.\n    destruct (f2 x); auto.\n    destruct s; auto.\n    destruct (f3 x); auto.\n  Qed.\n\n  Lemma fun_plus_empty_split : forall f1 f2, fun_plus f1 f2 = empty <-> f1 = empty /\\ f2 = empty.\n  Proof.\n    unfold fun_plus.\n    split.\n      intro.\n      split.\n      apply functional_extensionality.\n      intro.\n      apply equal_f with x in H.\n      destruct (f1 x).\n        destruct s.\n          auto.\n          destruct (f2 x).\n            discriminate.\n            discriminate.\n          discriminate.\n        auto.\n\n      apply functional_extensionality.\n      intro.\n      apply equal_f with x in H.\n      destruct (f1 x).\n        destruct s.\n          discriminate.\n          destruct (f2 x).\n            discriminate.\n            discriminate.\n          discriminate.\n        auto.\n\n      intros.\n      inversion_clear H.\n      apply functional_extensionality.\n      rewrite H0; rewrite H1.\n      unfold empty.\n      auto.\n  Qed.\n\n  Lemma fun_plus_in_domain : forall f1 f2 x, in_domain (fun_plus f1 f2) x <-> in_domain f1 x \\/ in_domain f2 x.\n  Proof.\n    unfold in_domain.\n    split.\n      intro.\n      unfold fun_plus in H.\n      destruct (f1 x) eqn:?.\n        induction s.\n          left; auto.\n          destruct (f2 x) eqn:?.\n            right; auto.\n            left; auto.\n          left; auto.\n          right; auto.\n      intro.\n      unfold fun_plus.\n      inversion H.\n        destruct (f1 x) eqn:?.\n          induction s.\n            auto.\n            destruct (f2 x) eqn:?; intro; discriminate.\n            auto.\n          exfalso; apply H0; auto.\n        destruct (f1 x).\n          destruct s.\n            intro; discriminate.\n            destruct (f2 x).\n              auto.\n              auto.\n            intro; discriminate.\n          auto.\n  Qed.\n\n  Lemma fun_plus_not_in_domain : forall f1 f2 x, ~ in_domain (fun_plus f1 f2) x <-> ~ in_domain f1 x /\\ ~ in_domain f2 x.\n  Proof.\n    unfold in_domain.\n    split.\n      intros.\n      split.\n      intro.\n      apply H.\n      intro.\n      unfold fun_plus in H1.\n      apply H0.\n      destruct (f1 x) eqn:?.\n        destruct s eqn:?.\n          discriminate.\n          destruct (f2 x) eqn:?.\n            discriminate.\n            discriminate.\n          discriminate.\n        auto.\n      intro.\n      apply H.\n      intro.\n      unfold fun_plus in H1.\n      apply H0.\n      destruct (f1 x) eqn:?.\n        destruct s eqn:?.\n          discriminate.\n          destruct (f2 x) eqn:?.\n            discriminate.\n            discriminate.\n          discriminate.\n        auto.\n\n      intros.\n      inversion H.\n      intro.\n      unfold fun_plus in H2.\n      apply H0.\n      intro.\n      rewrite H3 in H2.\n      apply H1.\n      auto.\n  Qed.\n\n  Lemma fun_plus_in_range_in_domain : forall f1 f2,\n                                  in_range_in_domain f1 ->\n                                  in_range_in_domain f2 ->\n                                  in_range_in_domain (fun_plus f1 f2).\n  Proof.\n    unfold in_range_in_domain.\n    unfold in_range.\n    unfold in_domain.\n    unfold fun_plus.\n    intros.\n    destruct (f1 x) eqn:?.\n      destruct s; try (intro; discriminate).\n      destruct (f2 x) eqn:?; try (intro; discriminate).\n\n      destruct (f2 x) eqn:?; try (intro; discriminate).\n      inversion_clear H1.\n      destruct (f1 x0) eqn:?.\n        destruct s.\n          specialize (H x).\n          rewrite Heqo in H.\n          apply H.\n          exists x0.\n          rewrite Heqo1; auto.\n\n          destruct (f2 x0) eqn:?.\n            inversion H2; subst.\n            specialize (H0 x).\n            rewrite Heqo0 in H0.\n            apply H0.\n            exists x0.\n            auto.\n\n            discriminate.\n          discriminate.\n        specialize (H0 x).\n        rewrite Heqo0 in H0.\n        apply H0.\n        exists x0.\n        auto.\n  Qed.\n\n  Definition fun_remove f x : temp_name_mapping :=\n    fun y : name =>\n      if beq_name y x\n      then None\n      else\n        match f y with\n          | Some (star_name n) =>\n            if beq_name n x\n            then Some star_star\n            else Some (star_name n)\n          | a => a\n        end.\n\n  Goal forall x y z f, x <> y -> y <> z -> z <> x ->\n         f = (fun a =>\n            if beq_name a x then Some (star_name y) else\n              if beq_name a y then Some (star_name z) else\n                if beq_name a z then Some star_bottom else None) ->\n         fun_remove f z z = None /\\\n         fun_remove f z y = Some star_star /\\\n         fun_remove f z x = Some (star_name y).\n  Proof.\n    intros.\n    split.\n      unfold fun_remove.\n      rewrite beq_name_refl.\n      auto.\n\n      split.\n        unfold fun_remove.\n        apply beq_name_false_iff in H0.\n        rewrite H0.\n        rewrite H2.\n        apply beq_name_false_iff in H.\n        rewrite beq_name_sym in H.\n        rewrite H.\n        rewrite beq_name_refl.\n        rewrite beq_name_refl.\n        auto.\n\n        unfold fun_remove.\n        rewrite H2.\n        apply beq_name_false_iff in H1.\n        rewrite beq_name_sym in H1.\n        rewrite H1.\n        rewrite beq_name_refl.\n        apply beq_name_false_iff in H0.\n        rewrite H0.\n        auto.\n  Qed.\n\n  Lemma fun_remove_in_domain_1 : forall f x y, in_domain f x -> in_domain (fun_remove f y) x \\/ x = y.\n  Proof.\n    unfold in_domain.\n    unfold fun_remove.\n    intros.\n    destruct (beq_name x y) eqn:?.\n      apply beq_name_true_iff in Heqb.\n      right; auto.\n\n      destruct (f x).\n        destruct s.\n          left.\n          destruct (beq_name n y); easy.\n          left; easy.\n          left; easy.\n          auto.\n  Qed.\n\n  Lemma fun_remove_in_domain_2 : forall f x y, in_domain (fun_remove f y) x -> x <> y /\\ in_domain f x.\n  Proof.\n    unfold in_domain.\n    unfold fun_remove.\n    split.\n      intro.\n      apply beq_name_true_iff in H0.\n      rewrite H0 in H.\n      apply H; auto.\n\n      intro.\n      rewrite H0 in H.\n      apply H.\n      destruct (beq_name x y); auto.\n  Qed.\n\n  Lemma fun_remove_not_in_domain_1 : forall f x y, ~ in_domain f x -> ~ in_domain (fun_remove f y) x.\n  Proof.\n    unfold in_domain.\n    intros.\n    unfold fun_remove.\n    intro.\n    destruct (beq_name x y) eqn:?.\n      apply H0; auto.\n      apply H.\n      intro.\n      rewrite H1 in H0.\n      apply H0; auto.\n  Qed.\n\n  Lemma fun_remove_not_in_domain_2 : forall f x y, ~ in_domain (fun_remove f y) x -> x = y \\/ ~ in_domain f x.\n  Proof.\n    unfold in_domain.\n    unfold fun_remove.\n    intros.\n    destruct (beq_name x y) eqn:?.\n      apply beq_name_true_iff in Heqb.\n      left; auto.\n\n      right.\n      intro.\n      apply H.\n      destruct (f x) eqn:?.\n        destruct s eqn:?.\n          destruct (beq_name n y) eqn:?.\n            intro; discriminate.\n            intro; discriminate.\n          intro; discriminate.\n          intro; discriminate.\n        auto.\n  Qed.\n\n  Lemma fun_remove_in_range_in_domain : forall f x, in_range_in_domain f -> in_range_in_domain (fun_remove f x).\n  Proof.\n    unfold in_range_in_domain.\n    unfold in_range, in_domain, fun_remove.\n    intros.\n    inversion_clear H0.\n    destruct (beq_name x0 x) eqn:?.\n      destruct (beq_name x1 x).\n        discriminate.\n\n        destruct (f x1) eqn:?.\n          destruct s.\n            destruct (beq_name n x) eqn:?.\n              discriminate.\n\n              inversion H1.\n              subst.\n              rewrite Heqb in Heqb0.\n              discriminate.\n\n            discriminate.\n\n            discriminate.\n\n          discriminate.\n\n      destruct (f x0) eqn:?.\n        destruct s.\n          destruct (beq_name n x); intro; discriminate.\n\n          intro; discriminate.\n\n          intro; discriminate.\n\n        destruct (beq_name x1 x) eqn:?.\n          discriminate.\n\n          destruct (f x1) eqn:?.\n            destruct s.\n              destruct (beq_name n x) eqn:?.\n                discriminate.\n\n                inversion H1; subst.\n                specialize (H x0).\n                rewrite Heqo in H.\n                apply H.\n                exists x1; auto.\n\n              discriminate.\n\n              discriminate.\n\n            discriminate.\n  Qed.\n\n  Definition fun_double (f : temp_name_mapping) : temp_name_mapping :=\n    fun x : name =>\n      match f x with\n        | Some (star_name n) => f n\n        | Some _ => Some star_bottom\n        | None => None\n      end.\n\n  Definition Fun_comm (f1 : temp_name_mapping) (f2 : temp_name_mapping) :=\n    fun_plus f1 f2 = fun_plus f2 f1.\n\n  (* f(x) /= x *)\n  Definition Fun_prop_1 (f : temp_name_mapping) :=\n    forall x : name, f x <> Some (star_name x).\n\n  (* f(x) = f(y) and is not member of {_|_, *} -> x = y *)\n  Definition Fun_prop_2 (f : temp_name_mapping) :=\n    forall (x y : name), (exists n, f x = Some (star_name n)) ->\n                         (exists n, f y = Some (star_name n)) ->\n                         f x = f y ->\n                         x = y.\n\n  (* f*(f(x)) = _|_ *)\n  Definition Fun_prop_3 (f : temp_name_mapping) :=\n    forall x, in_domain f x -> fun_double f x = Some star_bottom.\n\n  Definition Fun_prop (f : temp_name_mapping) :=\n    Fun_prop_1 f /\\ Fun_prop_2 f /\\ Fun_prop_3 f.\n\n  Record Compatible (f1 : temp_name_mapping) (f2 : temp_name_mapping) := Build_compatible {\n    Compatible_comm : Fun_comm f1 f2;\n    Compatible_prop : Fun_prop (fun_plus f1 f2)\n  }.\n\n  Fixpoint Mutually_compatible (fs : list temp_name_mapping) :=\n    match fs with\n      | nil => True\n      | f :: fs' => Forall (Compatible f) fs' /\\ Mutually_compatible fs'\n    end.\n\n  (* ch_0 *)\n\n  Definition ch_0 := empty.\n\n  Lemma ch_0_in_range_in_domain : in_range_in_domain ch_0.\n  Proof.\n    unfold in_range_in_domain.\n    unfold in_range, in_domain.\n    intros.\n      inversion H.\n      compute in H0; discriminate.\n  Qed.\n\n  Lemma ch_0_prop_1 : Fun_prop_1 ch_0.\n  Proof.\n    unfold Fun_prop_1.\n    intro.\n    intro.\n    compute in H.\n    discriminate.\n  Qed.\n\n  Lemma ch_0_prop_2 : Fun_prop_2 ch_0.\n  Proof.\n    unfold Fun_prop_2.\n    intros.\n    compute in H.\n    inversion H.\n    discriminate.\n  Qed.\n\n  Lemma ch_0_prop_3 : Fun_prop_3 ch_0.\n  Proof.\n    unfold Fun_prop_3.\n    intros.\n    compute in H.\n    exfalso; apply H; auto.\n  Qed.\n\n  Theorem ch_0_prop : Fun_prop ch_0.\n  Proof.\n    unfold Fun_prop.\n    split.\n    apply ch_0_prop_1.\n    split.\n    apply ch_0_prop_2.\n    apply ch_0_prop_3.\n  Qed.\n\n  (* ch_1 *)\n\n  Definition ch_1 (n : name) : temp_name_mapping :=\n    fun x => if beq_name n x\n             then Some star_bottom\n             else None.\n\n  Lemma ch_1_equal : forall x y, ch_1 x = ch_1 y <-> x = y.\n  Proof.\n    unfold ch_1.\n    split; intros.\n      apply equal_f with x in H.\n      rewrite beq_name_refl in H.\n      destruct (beq_name y x) eqn:?.\n        apply beq_name_true_iff in Heqb.\n        auto.\n\n        discriminate.\n\n      rewrite H.\n      auto.\n  Qed.\n\n  Lemma ch_1_not_empty : forall x, ch_1 x <> empty.\n  Proof.\n    intros.\n    intro.\n    apply equal_f with x in H.\n    unfold ch_1 in H.\n    rewrite beq_name_refl in H.\n    discriminate.\n  Qed.\n\n  Lemma ch_1_in_domain : forall x y, in_domain (ch_1 x) y <-> x = y.\n  Proof.\n    unfold in_domain.\n    unfold ch_1.\n    intros.\n    destruct (beq_name x y) eqn:?.\n      apply beq_name_true_iff in Heqb.\n      rewrite Heqb.\n      split.\n        intro; auto.\n        intro; intro; discriminate.\n      split.\n        intro; exfalso.\n        apply H; auto.\n        intro; apply beq_name_false_iff in Heqb.\n        contradiction.\n  Qed.\n\n  Lemma ch_1_not_in_domain : forall x y, ~ in_domain (ch_1 x) y <-> x <> y.\n  Proof.\n    unfold in_domain.\n    unfold ch_1.\n    intros.\n    destruct (beq_name x y) eqn:?.\n      apply beq_name_true_iff in Heqb.\n      rewrite Heqb.\n      split.\n        intro; intro.\n        unfold not in H.\n        apply H.\n        intro.\n        discriminate.\n\n        intro.\n        exfalso; apply H; auto.\n\n      split.\n        intro; intro.\n        apply beq_name_false_iff in Heqb.\n        auto.\n\n        intro.\n        intro.\n        apply H0; auto.\n  Qed.\n\n  Lemma ch_1_not_name : forall x y z, ch_1 x y <> Some (star_name z).\n  Proof.\n    unfold ch_1.\n    intros.\n    destruct (beq_name x y) eqn:?.\n      intro.\n      discriminate.\n\n      intro.\n      discriminate.\n  Qed.\n\n  Lemma ch_1_in_range_in_domain : forall x, in_range_in_domain (ch_1 x).\n  Proof.\n    unfold in_range_in_domain.\n    unfold in_range, in_domain.\n    unfold ch_1.\n    intros.\n    inversion H.\n    destruct (beq_name x x1) eqn:?; discriminate.\n  Qed.\n\n  Lemma ch_1_prop_1 : forall n, Fun_prop_1 (ch_1 n).\n  Proof.\n    unfold Fun_prop_1.\n    intros.\n    unfold ch_1.\n    destruct (beq_name n x); intro; discriminate.\n  Qed.\n\n  Lemma ch_1_prop_2 : forall n, Fun_prop_2 (ch_1 n).\n  Proof.\n    unfold Fun_prop_2.\n    unfold ch_1.\n    intros.\n    destruct (beq_name n x) eqn:?.\n      apply beq_name_true_iff in Heqb.\n      destruct (beq_name n y) eqn:?.\n        apply beq_name_true_iff in Heqb0.\n        rewrite <- Heqb.\n        rewrite Heqb0.\n        auto.\n\n        discriminate.\n      inversion H.\n      discriminate.\n  Qed.\n\n  Lemma ch_1_prop_3 : forall n, Fun_prop_3 (ch_1 n).\n  Proof.\n    unfold Fun_prop_3.\n    unfold in_domain.\n    unfold ch_1.\n    unfold fun_double.\n    intros.\n    destruct (beq_name n x) eqn:?.\n      auto.\n\n      exfalso.\n      apply H.\n      auto.\n  Qed.\n\n  Theorem ch_1_prop : forall n, Fun_prop (ch_1 n).\n  Proof.\n    unfold Fun_prop.\n    split.\n    apply ch_1_prop_1.\n    split.\n    apply ch_1_prop_2.\n    apply ch_1_prop_3.\n  Qed.\n\n  (* ch_2 *)\n\n  Definition ch_2 (n m : name) : temp_name_mapping :=\n    fun x =>\n      if beq_name n x\n      then Some (star_name m)\n      else if beq_name m x\n           then Some star_bottom\n           else None.\n\n  Lemma ch_2_not_empty : forall x y, ch_2 x y <> empty.\n  Proof.\n    intros.\n    intro.\n    apply equal_f with x in H.\n    unfold ch_2 in H.\n    rewrite beq_name_refl in H.\n    compute in H.\n    discriminate.\n  Qed.\n\n  Theorem ch_2_in_domain : forall x y z, in_domain (ch_2 x y) z <-> x = z \\/ y = z.\n  Proof.\n    split.\n    intros.\n\n    unfold in_domain in H.\n    unfold ch_2 in H.\n    destruct (beq_name x z) eqn:?.\n      apply beq_name_true_iff in Heqb.\n      left; auto.\n\n      destruct (beq_name y z) eqn:?.\n        apply beq_name_true_iff in Heqb0.\n        right; auto.\n\n        exfalso; apply H; auto.\n    intro.\n    unfold in_domain.\n    unfold ch_2.\n    inversion H.\n      rewrite <- H0.\n      rewrite beq_name_refl.\n      intro; discriminate.\n\n      rewrite H0.\n      destruct (beq_name x z) eqn:?.\n        intro; discriminate.\n        rewrite beq_name_refl.\n        intro; discriminate.\n  Qed.\n\n  Lemma ch_2_not_in_domain : forall x y z, ~ in_domain (ch_2 x y) z <-> x <> z /\\ y <> z.\n  Proof.\n    unfold in_domain.\n    unfold ch_2.\n    intros.\n    destruct (beq_name x z) eqn:?.\n      apply beq_name_true_iff in Heqb.\n      rewrite Heqb.\n      split; try split.\n        exfalso; apply H.\n        intro; discriminate.\n\n        exfalso; apply H; intro; discriminate.\n\n        intro.\n        inversion H.\n        exfalso; apply H0; auto.\n      split; try split.\n        destruct (beq_name y z) eqn:?.\n          apply beq_name_true_iff in Heqb0.\n          intro.\n          rewrite H0 in Heqb.\n          rewrite beq_name_refl in Heqb.\n          discriminate.\n\n          intro.\n          rewrite H0 in Heqb.\n          rewrite beq_name_refl in Heqb.\n          discriminate.\n\n        intro.\n        rewrite H0 in H.\n        rewrite beq_name_refl in H.\n        apply H; intro.\n        discriminate.\n\n        intros.\n        inversion H.\n        intro.\n        destruct (beq_name y z) eqn:?.\n        apply beq_name_true_iff in Heqb0.\n        auto.\n        apply H2; auto.\n  Qed.\n\n  Lemma ch_2_in_range_in_domain : forall x y, x <> y -> in_range_in_domain (ch_2 x y).\n  Proof.\n    unfold in_range_in_domain.\n    unfold in_range, in_domain, ch_2.\n    intros.\n    inversion_clear H0.\n    destruct (beq_name x x1) eqn:?.\n      inversion H1.\n      destruct (beq_name x x0) eqn:?.\n        intro; discriminate.\n\n        rewrite beq_name_refl.\n        intro; discriminate.\n\n      destruct (beq_name x x0) eqn:?.\n        intro; discriminate.\n\n        destruct (beq_name y x0) eqn:?.\n          intro; discriminate.\n\n          destruct (beq_name y x1); discriminate.\n  Qed.\n\n  Lemma ch_2_prop_1 : forall n m, n <> m -> Fun_prop_1 (ch_2 n m).\n  Proof.\n    unfold Fun_prop_1.\n    unfold ch_2.\n    intros.\n    destruct (beq_name n x) eqn:?.\n      apply beq_name_true_iff in Heqb.\n      rewrite <- Heqb.\n      intro.\n      inversion H0.\n      auto.\n\n      destruct (beq_name m x) eqn:?.\n        intro.\n        discriminate.\n        intro.\n        discriminate.\n  Qed.\n\n  Lemma ch_2_prop_2 : forall n m, Fun_prop_2 (ch_2 n m).\n  Proof.\n    unfold Fun_prop_2.\n    unfold in_domain.\n    unfold ch_2.\n    intros.\n    destruct (beq_name n x) eqn:?.\n      apply beq_name_true_iff in Heqb.\n      destruct (beq_name n y) eqn:?.\n        apply beq_name_true_iff in Heqb0.\n        rewrite <- Heqb.\n        rewrite Heqb0.\n        auto.\n\n        destruct (beq_name m y) eqn:?.\n          discriminate.\n          discriminate.\n      destruct (beq_name m x) eqn:?.\n        apply beq_name_true_iff in Heqb0.\n        destruct (beq_name n y) eqn:?.\n          discriminate.\n          destruct (beq_name m y) eqn:?.\n            apply beq_name_true_iff in Heqb2.\n            rewrite <- Heqb0.\n            apply Heqb2.\n\n            discriminate.\n        inversion H; discriminate.\n  Qed.\n\n  Lemma ch_2_prop_3 : forall n m, n <> m -> Fun_prop_3(ch_2 n m).\n  Proof.\n    unfold Fun_prop_3.\n    unfold in_domain.\n    unfold ch_2.\n    unfold fun_double.\n    unfold to_star_function.\n    intros.\n    destruct (beq_name n x) eqn:?.\n      apply beq_name_true_iff in Heqb.\n      rewrite Heqb.\n      rewrite beq_name_refl.\n      destruct (beq_name x m) eqn:?.\n        apply beq_name_true_iff in Heqb0.\n        rewrite Heqb0 in Heqb.\n        contradiction.\n\n        auto.\n      destruct (beq_name m x) eqn:?.\n        auto.\n        exfalso; apply H0; auto.\n  Qed.\n\n  Theorem ch_2_prop : forall n m, n <> m -> Fun_prop (ch_2 n m).\n  Proof.\n    split.\n    apply ch_2_prop_1; auto.\n    split.\n    apply ch_2_prop_2.\n    apply ch_2_prop_3; auto.\n  Qed.\n\n  Lemma fun_plus_prop_1 : forall f1 f2,\n                            Fun_prop_1 f1 ->\n                            Fun_prop_1 f2 ->\n                            Fun_prop_1 (fun_plus f1 f2).\n  Proof.\n    unfold Fun_prop_1.\n    unfold fun_plus.\n    intros.\n    destruct (f1 x) eqn:?.\n      destruct s.\n        rewrite <- Heqo.\n        apply H.\n\n        destruct (f2 x) eqn:?.\n          rewrite <- Heqo0.\n          apply H0.\n\n          intro; discriminate.\n\n        intro; discriminate.\n      apply H0.\n  Qed.\n\n  Lemma fun_plus_prop_2 : forall f1 f2,\n                            in_range_in_domain f1 ->\n                            in_range_in_domain f2 ->\n                            fun_exclusive f1 f2 ->\n                            Fun_prop_2 f1 ->\n                            Fun_prop_2 f2 ->\n                            Fun_prop_2 (fun_plus f1 f2).\n  Proof.\n    unfold Fun_prop_2.\n    unfold fun_exclusive.\n    unfold in_domain.\n    unfold fun_plus.\n    intros.\n    destruct (f1 x) eqn:?.\n      destruct (f1 y) eqn:?.\n        induction s.\n          induction s0.\n            apply H2.\n              exists n; auto.\n              exists n0; auto.\n              rewrite Heqo; rewrite Heqo0; auto.\n            destruct (f2 y) eqn:?.\n              specialize (H1 y).\n              inversion H1.\n              rewrite Heqo0 in H7.\n              rewrite Heqo1 in H7.\n              assert (Some star_bottom <> None).\n                intro; discriminate.\n              apply H7 in H9.\n              exfalso; apply H9; intro; discriminate.\n\n              discriminate.\n            discriminate.\n          induction s0.\n            destruct (f2 x) eqn:?.\n              specialize (H1 x).\n              inversion H1.\n              rewrite Heqo in H7.\n              rewrite Heqo1 in H7.\n              assert (Some star_bottom <> None).\n                intro; discriminate.\n              apply H7 in H9.\n              exfalso; apply H9; intro; discriminate.\n\n              discriminate.\n            destruct (f2 x) eqn:?.\n              specialize (H1 x).\n              inversion H1.\n              rewrite Heqo in H7.\n              rewrite Heqo1 in H7.\n              assert (Some star_bottom <> None).\n                intro; discriminate.\n              apply H7 in H9.\n              exfalso; apply H9; intro; discriminate.\n\n              inversion H4; discriminate.\n            inversion H5; discriminate.\n          inversion H4; discriminate.\n\n        induction s.\n          symmetry in H6.\n          unfold in_range_in_domain, in_range, in_domain in H.\n          unfold in_range_in_domain, in_range, in_domain in H0.\n          specialize (H n).\n          specialize (H0 n).\n          specialize (H1 n).\n          inversion H1.\n          assert (exists y : name, f1 y = Some (star_name n)).\n            exists x; auto.\n          assert (exists y : name, f2 y = Some (star_name n)).\n            exists y; auto.\n          apply H in H9.\n          apply H0 in H10.\n          apply H7 in H9.\n          exfalso; apply H9; auto.\n\n          destruct (f2 x) eqn:?.\n            apply H3.\n              rewrite Heqo1; auto.\n\n              auto.\n\n              rewrite Heqo1; auto.\n            inversion H4; discriminate.\n\n          inversion H4; discriminate.\n      inversion H4; subst.\n      rewrite H7 in H6.\n      destruct (f1 y) eqn:?.\n        destruct s.\n          inversion H6; subst.\n          unfold in_range_in_domain, in_range, in_domain in H.\n          unfold in_range_in_domain, in_range, in_domain in H0.\n          specialize (H n).\n          specialize (H0 n).\n          assert (exists y, f1 y = Some (star_name n)).\n            exists y; auto.\n          assert (exists y, f2 y = Some (star_name n)).\n            exists x; auto.\n          apply H in H8.\n          apply H0 in H9.\n          specialize (H1 n).\n          inversion H1.\n          apply H10 in H8.\n          exfalso; apply H8; auto.\n\n          destruct (f2 y) eqn:?.\n            specialize (H1 y).\n            inversion H1.\n            assert (f1 y <> None).\n              rewrite Heqo0; intro; discriminate.\n            apply H8 in H10.\n            exfalso; apply H10.\n            rewrite Heqo1; intro; discriminate.\n\n          discriminate.\n        discriminate.\n\n        apply H3.\n          exists x0; auto.\n\n          exists x0; rewrite H6; auto.\n\n          rewrite H7; auto.\n  Qed.\n\n  Lemma fun_plus_prop_3 : forall f1 f2,\n                            fun_exclusive f1 f2 ->\n                            Fun_prop_3 f1 ->\n                            Fun_prop_3 f2 ->\n                            Fun_prop_3 (fun_plus f1 f2).\n  Proof.\n    unfold Fun_prop_3.\n    unfold fun_exclusive.\n    unfold fun_double.\n    unfold to_star_function.\n    unfold fun_plus.\n    unfold in_domain.\n    intros.\n    destruct (f1 x) eqn:?.\n      destruct s.\n        destruct (f1 n) eqn:?.\n          specialize (H0 x).\n          assert (f1 x <> None).\n            rewrite Heqo.\n            intro; discriminate.\n          apply H0 in H3.\n          rewrite Heqo in H3.\n          rewrite Heqo0 in H3.\n          inversion H3.\n          destruct (f2 n) eqn:?.\n            specialize (H n).\n            inversion H.\n            assert (f1 n <> None).\n              rewrite Heqo0; intro; discriminate.\n            apply H4 in H7.\n            exfalso; apply H7; intro.\n            rewrite Heqo1 in H8; discriminate.\n\n            auto.\n\n          specialize (H0 x).\n          assert (f1 x <> None).\n            rewrite Heqo; intro; discriminate.\n          apply H0 in H3.\n          rewrite Heqo in H3.\n          rewrite Heqo0 in H3; discriminate.\n\n        destruct (f2 x) eqn:?.\n          specialize (H x).\n          inversion H.\n          assert (f1 x <> None).\n            rewrite Heqo; intro; discriminate.\n          apply H3 in H5.\n          exfalso; apply H5; intro.\n          rewrite Heqo0 in H6; discriminate.\n\n          auto.\n        auto.\n      destruct (f2 x) eqn:?.\n        destruct s.\n          destruct (f1 n) eqn:?.\n            specialize (H1 x).\n            assert (f2 x <> None).\n              rewrite Heqo0; intro; discriminate.\n            apply H1 in H3.\n            rewrite Heqo0 in H3.\n            specialize (H n).\n            inversion H.\n            assert (f1 n <> None).\n              rewrite Heqo1; intro; discriminate.\n            apply H4 in H6.\n            exfalso; apply H6; intro.\n            rewrite H3 in H7; discriminate.\n\n            assert (f2 x <> None).\n              rewrite Heqo0; intro; discriminate.\n            apply H1 in H3.\n            rewrite Heqo0 in H3.\n            auto.\n          auto.\n          auto.\n        exfalso; apply H2; auto.\n  Qed.\n\n  Theorem fun_plus_prop : forall f1 f2,\n                            in_range_in_domain f1 ->\n                            in_range_in_domain f2 ->\n                            fun_exclusive f1 f2 ->\n                            Fun_prop f1 ->\n                            Fun_prop f2 ->\n                            Fun_prop (fun_plus f1 f2).\n  Proof.\n    intros.\n    inversion_clear H2.\n    inversion_clear H5.\n    inversion_clear H3.\n    inversion_clear H7.\n    unfold Fun_prop.\n    split; try split.\n    apply fun_plus_prop_1; auto.\n    apply fun_plus_prop_2; auto.\n    apply fun_plus_prop_3; auto.\n  Qed.\n\n  Lemma fun_prop_plus_fst : forall f1 f2,\n                              Fun_prop (fun_plus f1 f2) ->\n                              in_range_in_domain f1 ->\n                              Fun_prop f1.\n  Proof.\n    intros f1 f2 H rd.\n    inversion_clear H.\n    inversion_clear H1.\n\n    unfold Fun_prop.\n    unfold Fun_prop_1 in H0.\n    unfold Fun_prop_2 in H.\n    unfold Fun_prop_3 in H2.\n\n    split; try split.\n      unfold Fun_prop_1.\n      intros.\n      intro.\n      apply H0 with x.\n      unfold fun_plus.\n      rewrite H1; auto.\n\n      unfold Fun_prop_2; intros.\n      apply H.\n        inversion_clear H1.\n        exists x0.\n        unfold fun_plus.\n        rewrite H5; auto.\n\n        inversion_clear H3.\n        exists x0.\n        unfold fun_plus.\n        rewrite H5; auto.\n\n        unfold fun_plus.\n        destruct (f1 x); auto.\n          destruct s; auto.\n            destruct (f1 y); auto.\n              destruct s; auto.\n              inversion H4.\n            inversion H4.\n          destruct (f1 y); auto.\n            destruct s; auto.\n              discriminate.\n              inversion H1; discriminate.\n              inversion H1; discriminate.\n            discriminate.\n          inversion H1; discriminate.\n          inversion H1; discriminate.\n\n      unfold Fun_prop_3; intros.\n      unfold fun_double.\n      unfold to_star_function.\n\n      unfold in_range_in_domain in rd.\n      unfold in_range in rd.\n\n      unfold fun_double in H2.\n      unfold in_domain in H2, H1, rd.\n      unfold to_star_function in H2.\n      unfold fun_plus in H2.\n      specialize H2 with x.\n      destruct (f1 x) eqn:?; auto.\n        destruct s; auto.\n        destruct (f1 n) eqn:?; auto.\n          destruct s; auto.\n          specialize rd with n.\n          assert (exists y, f1 y = Some (star_name n)).\n            exists x; auto.\n          apply rd in H3.\n          easy.\n\n          exfalso; apply H1; auto.\n  Qed.\n\n  Lemma compatible_split : forall f1 f2,\n                             Compatible f1 f2 ->\n                             in_range_in_domain f1 ->\n                             in_range_in_domain f2 ->\n                             Fun_prop f1 /\\ Fun_prop f2.\n  Proof.\n    assert (forall f1 f2, Fun_prop (fun_plus f1 f2) -> in_range_in_domain f1 -> Fun_prop f1).\n    intros f1 f2 H rd.\n    inversion_clear H.\n    inversion_clear H1.\n\n    unfold Fun_prop.\n    unfold Fun_prop_1 in H0.\n    unfold Fun_prop_2 in H.\n    unfold Fun_prop_3 in H2.\n\n    split; try split.\n      unfold Fun_prop_1.\n      intros.\n      intro.\n      apply H0 with x.\n      unfold fun_plus.\n      rewrite H1; auto.\n\n      unfold Fun_prop_2; intros.\n      apply H.\n        inversion_clear H1.\n        exists x0.\n        unfold fun_plus.\n        rewrite H5; auto.\n\n        inversion_clear H3.\n        exists x0.\n        unfold fun_plus.\n        rewrite H5; auto.\n\n        unfold fun_plus.\n        destruct (f1 x); auto.\n          destruct s; auto.\n            destruct (f1 y); auto.\n              destruct s; auto.\n              inversion H4.\n            inversion H4.\n          destruct (f1 y); auto.\n            destruct s; auto.\n              discriminate.\n              inversion H1; discriminate.\n              inversion H1; discriminate.\n            discriminate.\n          inversion H1; discriminate.\n          inversion H1; discriminate.\n\n      unfold Fun_prop_3; intros.\n      unfold fun_double.\n      unfold to_star_function.\n\n      unfold in_range_in_domain in rd.\n      unfold in_range in rd.\n\n      unfold fun_double in H2.\n      unfold in_domain in H2, H1, rd.\n      unfold to_star_function in H2.\n      unfold fun_plus in H2.\n      specialize H2 with x.\n      destruct (f1 x) eqn:?; auto.\n        destruct s; auto.\n        destruct (f1 n) eqn:?; auto.\n          destruct s; auto.\n          specialize rd with n.\n          assert (exists y, f1 y = Some (star_name n)).\n            exists x; auto.\n          apply rd in H3.\n          easy.\n\n          exfalso; apply H1; auto.\n\n  intros.\n  inversion H0 as [c p].\n  split.\n    apply H with f2; auto.\n    unfold Fun_comm in c.\n    rewrite c in p.\n    apply H with f1; auto.\nQed.\n\n  Theorem fun_plus_compatible : forall f f1 f2,\n                                  in_range_in_domain f ->\n                                  in_range_in_domain f1 ->\n                                  in_range_in_domain f2 ->\n                                  Compatible f (fun_plus f1 f2) ->\n                                  Compatible f1 f2 ->\n                                  Mutually_compatible (f :: f1 :: f2 :: nil).\n  Proof.\n    intros.\n    simpl.\n    inversion_clear H2 as [c0 p0].\n    inversion_clear H3 as [c1 p1].\n    unfold Fun_comm in c0.\n    unfold Fun_comm in c1.\n    subst.\n    assert (Fun_comm f f1).\n      unfold Fun_comm.\n      apply functional_extensionality; intros.\n      apply equal_f with x in c1.\n      apply equal_f with x in c0.\n      unfold fun_plus.\n      unfold fun_plus in c1, c0.\n      destruct (f x); auto.\n        destruct s; auto; destruct (f1 x); auto; destruct s; auto.\n        destruct (f1 x); auto; destruct s; auto.\n    assert (Fun_comm f f2).\n      rewrite c1 in c0.\n      symmetry in c1.\n      unfold Fun_comm.\n      apply functional_extensionality; intros.\n      apply equal_f with x in c1.\n      apply equal_f with x in c0.\n      unfold fun_plus.\n      unfold fun_plus in c1, c0.\n      destruct (f x); auto.\n        destruct s; auto; destruct (f2 x); auto; destruct s; auto.\n        destruct (f2 x); auto; destruct s; auto.\n    split; try (split; try (split; try (split; try split))).\n      apply Forall_cons; auto.\n        apply Build_compatible; auto.\n        rewrite fun_plus_assoc in p0.\n        apply fun_prop_plus_fst in p0; auto.\n        apply fun_plus_in_range_in_domain; auto.\n\n        apply Forall_cons; auto.\n        apply Build_compatible; auto.\n        rewrite c1 in p0.\n        rewrite fun_plus_assoc in p0.\n        apply fun_prop_plus_fst in p0; auto.\n        apply fun_plus_in_range_in_domain; auto.\n      apply Forall_cons; auto.\n      apply Build_compatible; auto.\n\n      auto.\n  Qed.\n\n  Lemma fun_remove_prop_1 : forall f x,\n                              Fun_prop_1 f ->\n                              Fun_prop_1 (fun_remove f x).\n  Proof.\n    unfold Fun_prop_1.\n    unfold fun_remove.\n    intros.\n    destruct (beq_name x0 x) eqn:?.\n      intro; discriminate.\n\n      apply beq_name_false_iff in Heqb.\n      destruct (f x0) eqn:?.\n        destruct s.\n          destruct (beq_name n x) eqn:?.\n            intro; discriminate.\n\n            specialize (H x0).\n            rewrite Heqo in H.\n            auto.\n          intro; discriminate.\n          intro; discriminate.\n        intro; discriminate.\n  Qed.\n\n  Lemma fun_remove_prop_2 : forall f n,\n                              Fun_prop_2 f ->\n                              Fun_prop_2 (fun_remove f n).\n  Proof.\n    unfold Fun_prop_2.\n    unfold fun_remove.\n    intros.\n    destruct (beq_name x n) eqn:?.\n      inversion H0; discriminate.\n\n      destruct (beq_name y n) eqn:?.\n        inversion H1; discriminate.\n\n        destruct (f x) eqn:?.\n          destruct s.\n            destruct (beq_name n0 n) eqn:?.\n              inversion H0; discriminate.\n\n              destruct (f y) eqn:?.\n                destruct s.\n                  destruct (beq_name n1 n) eqn:?.\n                    inversion H1; discriminate.\n\n                    inversion H2.\n                    apply H.\n                      exists n0; auto.\n\n                      exists n1; auto.\n\n                      rewrite Heqo.\n                      rewrite Heqo0.\n                      rewrite H4; auto.\n                  discriminate.\n\n                  discriminate.\n                discriminate.\n            inversion H0; discriminate.\n\n            inversion H0; discriminate.\n          inversion H0; discriminate.\n  Qed.\n\n  Lemma fun_remove_prop_3 : forall f n,\n                              Fun_prop_3 f ->\n                              Fun_prop_3 (fun_remove f n).\n  Proof.\n    unfold Fun_prop_3.\n    unfold fun_remove, fun_double, in_domain, to_star_function.\n    intros.\n    assert (forall o, (exists (x : Type), o = Some x) -> o <> None).\n      intros.\n      inversion H1.\n      rewrite H2; intro; discriminate.\n    destruct (beq_name x n) eqn:?.\n      contradict H0; auto.\n\n      destruct (f x) eqn:?.\n        destruct s.\n          destruct (beq_name n0 n) eqn:?.\n            auto.\n\n            rewrite Heqb0.\n            rewrite <- Heqo in H0.\n            apply H in H0.\n            rewrite Heqo in H0.\n            rewrite H0.\n            auto.\n          auto.\n          auto.\n        contradiction H0; auto.\n  Qed.\nEnd Fun.\n", "meta": {"author": "amutake", "repo": "a-pi", "sha": "3e486b240f1c279f97ee87db74207ae961b48bff", "save_path": "github-repos/coq/amutake-a-pi", "path": "github-repos/coq/amutake-a-pi/a-pi-3e486b240f1c279f97ee87db74207ae961b48bff/Fun.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.22497233561726093}}
{"text": "Require Import RelationClasses.\n\nFrom Paco Require Import paco.\nFrom sflib Require Import sflib.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Loc.\nRequire Import Time.\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\nRequire Import Behavior.\nRequire Import Cover.\nRequire Import Pred.\nRequire Import Trace.\nRequire Import JoinedView.\n\nRequire Import MemoryProps.\nRequire Import OrderedTimes.\n\nRequire Import PFStep.\n\nSet Implicit Arguments.\n\n\n\nLemma reservation_event_pf L e\n      (RESERVATION: ThreadEvent.is_reservation_event e)\n  :\n    PF.pf_event L e.\nProof.\n  ii. subst. unfold ThreadEvent.is_reservation_event in *. ss.\nQed.\n\nLemma reserve_future_memory_steps\n      lang st vw sc prom0 mem0 prom1 mem1\n      (FUTURE: reserve_future_memory prom0 mem0 prom1 mem1)\n  :\n    exists tr,\n      (<<STEPS: Trace.steps tr\n                            (Thread.mk lang st (Local.mk vw prom0) sc mem0)\n                            (Thread.mk lang st (Local.mk vw prom1) sc mem1)>>) /\\\n      (<<RESERVING: reserving_trace tr>>)\n.\nProof.\n  ginduction FUTURE.\n  { i. exists []. splits; eauto. econs; eauto. }\n  { i. exploit IHFUTURE; eauto. i. des. esplits.\n    { econs; eauto. econs; eauto. econs; eauto. }\n    { econs; ss. }\n  }\nQed.\n\nLemma joined_view_semi_closed\n      views view mem loc ts\n      (MEM: List.Forall (fun vw => semi_closed_view vw mem loc ts) views)\n      (JOINED: joined_view views view)\n      (INHABITED: Memory.inhabited mem)\n  :\n    semi_closed_view view mem loc ts.\nProof.\n  ginduction JOINED; eauto.\n  - i. eapply closed_view_semi_closed. apply Memory.closed_view_bot. auto.\n  - i. eapply semi_closed_view_join; eauto.\n    eapply List.Forall_forall in VIEW; [|eauto]. ss.\nQed.\n\n\n\n\n\nSection SIM.\n\n  Variable L: Loc.t -> bool.\n  Variable times: Loc.t -> Time.t -> Prop.\n  Hypothesis WO: forall loc, well_ordered (times loc).\n\n  (* sim trace *)\n\n  Definition racy_event (e: ThreadEvent.t): Prop :=\n    match e with\n    | ThreadEvent.write _ _ _ _ _ _ => True\n    | ThreadEvent.read _ _ _ _ _ => True\n    | ThreadEvent.update _ _ _ _ _ _ _ _ _ => True\n    | _ => False\n    end.\n\n  Inductive sim_event: forall (e_src e_tgt: ThreadEvent.t), Prop :=\n  | sim_event_promise\n      loc from_src from_tgt to msg_src msg_tgt kind_src kind_tgt\n      (RESERVE: msg_src = Message.reserve <-> msg_tgt = Message.reserve)\n    :\n      sim_event\n        (ThreadEvent.promise loc from_src to msg_src kind_src)\n        (ThreadEvent.promise loc from_tgt to msg_tgt kind_tgt)\n  | sim_event_silent\n    :\n      sim_event\n        ThreadEvent.silent\n        ThreadEvent.silent\n  | sim_event_read\n      loc ts val released_src released_tgt ord\n    :\n      sim_event\n        (ThreadEvent.read loc ts val released_src ord)\n        (ThreadEvent.read loc ts val released_tgt ord)\n  | sim_event_write\n      loc from_src from_tgt to val released_src released_tgt ord\n    :\n      sim_event\n        (ThreadEvent.write loc from_src to val released_src ord)\n        (ThreadEvent.write loc from_tgt to val released_tgt ord)\n  | sim_event_update\n      loc tsr tsw valr valw releasedr_src releasedr_tgt releasedw_src releasedw_tgt ordr ordw\n    :\n      sim_event\n        (ThreadEvent.update loc tsr tsw valr valw releasedr_src releasedw_src ordr ordw)\n        (ThreadEvent.update loc tsr tsw valr valw releasedr_tgt releasedw_tgt ordr ordw)\n  | sim_event_fence\n      ordr ordw\n    :\n      sim_event\n        (ThreadEvent.fence ordr ordw)\n        (ThreadEvent.fence ordr ordw)\n  | sim_event_syscall\n      e\n    :\n      sim_event\n        (ThreadEvent.syscall e)\n        (ThreadEvent.syscall e)\n  | sim_event_failure\n    :\n      sim_event\n        ThreadEvent.failure\n        ThreadEvent.failure\n  .\n  Hint Constructors sim_event.\n\n  Global Program Instance sim_event_Equivalence: Equivalence sim_event.\n  Next Obligation.\n  Proof. ii. destruct x; econs. auto. Qed.\n  Next Obligation.\n  Proof. ii. inv H; econs. symmetry. auto. Qed.\n  Next Obligation.\n  Proof. ii. inv H; inv H0; econs. etrans; eauto. Qed.\n\n  Lemma sim_event_machine_event e_src e_tgt\n        (EVENT: sim_event e_src e_tgt)\n    :\n      ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt.\n  Proof.\n    inv EVENT; ss.\n  Qed.\n\n  Inductive sim_trace: Trace.t -> option (Local.t * ThreadEvent.t) -> Prop :=\n  | sim_trace_nil\n    :\n      sim_trace [] None\n  | sim_trace_cons\n      lc_src lc_tgt e_src e_tgt tl_src\n      (PF: PF.pf_event L e_src)\n      (TL: sim_trace tl_src None)\n      (EVENT: sim_event e_src e_tgt)\n      (VW: TView.le (Local.tview lc_src) (Local.tview lc_tgt))\n    :\n      sim_trace ((lc_src, e_src)::tl_src) (Some (lc_tgt, e_tgt))\n  | sim_trace_forget\n      th_tgt e tl_src\n      (NONRACY: ~ racy_event e)\n      (TL: sim_trace tl_src None)\n    :\n      sim_trace tl_src (Some (th_tgt, e))\n  | sim_trace_reserve\n      th_src e tl_src e_tgt\n      (SILENT: ThreadEvent.is_reservation_event e)\n      (PF: PF.pf_event L e)\n      (TL: sim_trace tl_src e_tgt)\n    :\n      sim_trace ((th_src, e)::tl_src) e_tgt\n  .\n  Hint Constructors sim_trace.\n\n  Lemma sim_event_racy_event e_src e_tgt\n        (RACY: racy_event e_tgt)\n        (EVENT: sim_event e_src e_tgt)\n    :\n      racy_event e_src.\n  Proof.\n    inv EVENT; ss.\n  Qed.\n\n  Lemma sim_trace_sim_event_sim_trace (tr_src: Trace.t) lc_mid lc_tgt e_mid e_tgt\n        (TRACE: sim_trace tr_src (Some (lc_mid, e_mid)))\n        (THREAD: TView.le (Local.tview lc_mid) (Local.tview lc_tgt))\n        (EVENT: sim_event e_mid e_tgt)\n    :\n      sim_trace tr_src (Some (lc_tgt, e_tgt)).\n  Proof.\n    remember (Some (lc_mid, e_mid)) as e. ginduction TRACE; i; clarify.\n    { econs 2; eauto.\n      { etrans; eauto. }\n      { etrans; eauto. }\n    }\n    { econs 3; eauto. ii. eapply NONRACY. eapply sim_event_racy_event; eauto. }\n    { econs 4; eauto. }\n  Qed.\n\n  Lemma sim_silent_sim_event_exists (tr_src: Trace.t) lc_tgt e_tgt\n        (TRACE: sim_trace tr_src (Some (lc_tgt, e_tgt)))\n        (PF: PF.pf_event L e_tgt)\n        (RACY: racy_event e_tgt)\n    :\n      exists lc e_src,\n        (<<IN: List.In (lc, e_src) tr_src>>) /\\\n        (<<EVENT: sim_event e_src e_tgt>>) /\\\n        (<<LOCAL: TView.le (Local.tview lc) (Local.tview lc_tgt)>>)\n  .\n  Proof.\n    remember (Some (lc_tgt, e_tgt)). revert e_tgt Heqo PF RACY.\n    ginduction TRACE; i; clarify.\n    { esplits; eauto. econs; eauto. }\n    { hexploit IHTRACE; eauto. i. des.\n      esplits; eauto. right. eauto. }\n  Qed.\n\n  Lemma sim_trace_silent (tr_src: Trace.t) (e: option (Local.t * ThreadEvent.t))\n        (SILENT: forall lc_tgt e_tgt (EQ: e = Some (lc_tgt, e_tgt)), ThreadEvent.get_machine_event e_tgt = MachineEvent.silent)\n        (TRACE: sim_trace tr_src e)\n    :\n      List.Forall (fun the => ThreadEvent.get_machine_event (snd the) = MachineEvent.silent) tr_src.\n  Proof.\n    ginduction TRACE; eauto.\n    { i. econs; eauto.\n      { ss. erewrite sim_event_machine_event; eauto. }\n      { eapply IHTRACE; eauto. i. ss. }\n    }\n    { i. eapply IHTRACE; eauto. i. ss. }\n    { i. econs; eauto. ss. eapply ThreadEvent.reservation_event_silent; eauto. }\n  Qed.\n\n  Lemma non_silent_pf e\n        (EVENT: ThreadEvent.get_machine_event e <> MachineEvent.silent)\n    :\n      PF.pf_event L e.\n  Proof.\n    ii. subst. ss.\n  Qed.\n\n  Lemma sim_trace_pf (tr_src: Trace.t) (e: option (Local.t * ThreadEvent.t))\n        (TRACE: sim_trace tr_src e)\n    :\n      List.Forall (compose (PF.pf_event L) snd) tr_src.\n  Proof.\n    ginduction TRACE; eauto.\n  Qed.\n\n  Lemma reserving_l_sim_trace (tr_src tr_reserve: Trace.t) (e: option (Local.t * ThreadEvent.t))\n        (TRACE: sim_trace tr_src e)\n        (RESERVING: reserving_trace tr_reserve)\n    :\n      sim_trace (tr_reserve ++ tr_src) e.\n  Proof.\n    ginduction RESERVING; eauto. i. ss.\n    destruct x. econs 4; eauto.\n    eapply reservation_event_pf; eauto.\n  Qed.\n\n  Lemma reserving_r_sim_trace (tr_src tr_reserve: Trace.t) (e: option (Local.t * ThreadEvent.t))\n        (TRACE: sim_trace tr_src e)\n        (RESERVING: reserving_trace tr_reserve)\n    :\n      sim_trace (tr_src ++ tr_reserve) e.\n  Proof.\n    ginduction TRACE; ss; i; eauto.\n    ginduction RESERVING; eauto.\n    i. destruct x. econs 4; eauto.\n    { eapply reservation_event_pf; eauto. }\n  Qed.\n\n  Inductive sim_traces: Trace.t -> Trace.t -> Prop :=\n  | sim_traces_nil\n    :\n      sim_traces [] []\n  | sim_traces_some\n      hd_src th_tgt e_tgt tl_src tl_tgt\n      (TL: sim_traces tl_src tl_tgt)\n      (HD: sim_trace hd_src (Some (th_tgt, e_tgt)))\n    :\n      sim_traces (hd_src ++ tl_src) ((th_tgt, e_tgt)::tl_tgt)\n  | sim_traces_none\n      hd_src tl_src tl_tgt\n      (TL: sim_traces tl_src tl_tgt)\n      (HD: sim_trace hd_src None)\n    :\n      sim_traces (hd_src ++ tl_src) tl_tgt\n  .\n  Hint Constructors sim_traces.\n\n  Lemma sim_traces_sim_event_exists (tr_src tr_tgt: Trace.t) th_tgt e_tgt\n        (TRACE: sim_traces tr_src tr_tgt)\n        (IN: List.In (th_tgt, e_tgt) tr_tgt)\n        (PF: PF.pf_event L e_tgt)\n        (RACY: racy_event e_tgt)\n    :\n      exists th e_src,\n        (<<IN: List.In (th, e_src) tr_src>>) /\\\n        (<<EVENT: sim_event e_src e_tgt>>) /\\\n        (<<LOCAL: TView.le (Local.tview th) (Local.tview th_tgt)>>)\n  .\n  Proof.\n    ginduction TRACE; i; ss.\n    { des; clarify.\n      { eapply sim_silent_sim_event_exists in HD; eauto. des. esplits; eauto.\n        eapply List.in_or_app; eauto. }\n      { exploit IHTRACE; eauto. i. des. esplits; eauto.\n        eapply List.in_or_app; eauto. }\n    }\n    { exploit IHTRACE; eauto. i. des. esplits; eauto.\n      eapply List.in_or_app; eauto. }\n  Qed.\n\n  Lemma sim_traces_silent (tr_src tr_tgt: Trace.t)\n        (SILENT: List.Forall (fun the => ThreadEvent.get_machine_event (snd the) = MachineEvent.silent) tr_tgt)\n        (TRACE: sim_traces tr_src tr_tgt)\n    :\n      List.Forall (fun the => ThreadEvent.get_machine_event (snd the) = MachineEvent.silent) tr_src.\n  Proof.\n    ginduction TRACE; eauto.\n    { i. inv SILENT. eapply Forall_app; eauto.\n      eapply sim_trace_silent; eauto. i. ss. clarify. }\n    { i. eapply Forall_app; eauto.\n      eapply sim_trace_silent; eauto. i. ss. }\n  Qed.\n\n  Lemma sim_traces_trans (tr_src0 tr_src1 tr_tgt0 tr_tgt1: Trace.t)\n        (TRACE0: sim_traces tr_src0 tr_tgt0)\n        (TRACE1: sim_traces tr_src1 tr_tgt1)\n    :\n      sim_traces (tr_src0 ++ tr_src1) (tr_tgt0 ++ tr_tgt1).\n  Proof.\n    ginduction TRACE0; i.\n    { ss. }\n    { erewrite <- List.app_assoc. erewrite <- List.app_comm_cons. econs 2; eauto. }\n    { erewrite <- List.app_assoc. econs 3; eauto. }\n  Qed.\n\n  Lemma sim_traces_pf (tr_src tr_tgt: Trace.t)\n        (TRACE: sim_traces tr_src tr_tgt)\n    :\n      List.Forall (compose (PF.pf_event L) snd) tr_src.\n  Proof.\n    induction TRACE; eauto.\n    { i. eapply Forall_app.\n      { eapply sim_trace_pf; eauto. }\n      { eapply IHTRACE; eauto. }\n    }\n    { i. eapply Forall_app.\n      { eapply sim_trace_pf; eauto. }\n      { eapply IHTRACE; eauto. }\n    }\n  Qed.\n\n\n  (* sim memory *)\n\n  Inductive sim_memory_content\n            (F: Prop)\n            (extra: Time.t -> Prop)\n            (loc: Loc.t) (ts: Time.t)\n    : option (Time.t * Message.t) -> option (Time.t * Message.t) -> Prop :=\n  | sim_memory_content_none\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n    :\n      sim_memory_content F extra loc ts None None\n  | sim_memory_content_normal\n      from_src from_tgt msg\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (FROM: Time.le from_tgt from_src)\n      (LB: forall (LOC: L loc), lb_time (times loc) from_tgt from_src)\n      (NLOC: ~ L loc -> from_src = from_tgt)\n    :\n      sim_memory_content F extra loc ts (Some (from_src, msg)) (Some (from_tgt, msg))\n  | sim_memory_content_forget\n      from_src from_tgt val released\n      (PROM: F)\n      (NEXTRA: forall t, ~ extra t)\n      (NLOC: L loc)\n      (FROM: Time.le from_tgt from_src)\n      (LB: lb_time (times loc) from_tgt from_src)\n    :\n      sim_memory_content F extra loc ts (Some (from_src, Message.reserve)) (Some (from_tgt, Message.concrete val released))\n  | sim_memory_content_extra\n      from\n      (NPROM: ~ F)\n      (EXTRA: extra from)\n      (NLOC: L loc)\n    :\n      sim_memory_content F extra loc ts (Some (from, Message.reserve)) None\n  .\n  Hint Constructors sim_memory_content.\n\n  Record sim_memory\n         (F: Loc.t -> Time.t -> Prop)\n         (extra: Loc.t -> Time.t -> Time.t -> Prop)\n         (mem_src mem_tgt: Memory.t): Prop :=\n    {\n      sim_memory_contents:\n        forall loc ts,\n          sim_memory_content (F loc ts) (extra loc ts)\n                             loc ts (Memory.get loc ts mem_src) (Memory.get loc ts mem_tgt);\n      sim_memory_wf:\n        forall loc from ts (EXTRA: extra loc ts from),\n          (<<FORGET: F loc from>>) /\\\n          (<<LB: lb_time (times loc) from ts>>) /\\\n          (<<TS: Time.lt from ts>>) /\\\n          (<<UNIQUE: forall from' (EXTRA: extra loc ts from'),\n              from' = from>>);\n    }.\n\n  Lemma sim_memory_others_self_wf\n        F extra mem_src mem_tgt\n        (MEMORY: sim_memory F extra mem_src mem_tgt)\n    :\n      forall loc' to', F loc' to' -> L loc'.\n  Proof.\n    ii. set (MEMORY0:=(sim_memory_contents MEMORY) loc' to'). inv MEMORY0; clarify.\n  Qed.\n\n  Lemma sim_memory_extra_others_self_wf\n        F extra mem_src mem_tgt\n        (MEMORY: sim_memory F extra mem_src mem_tgt)\n    :\n      forall loc' from to', extra loc' to' from -> L loc'.\n  Proof.\n    ii. set (MEMORY0:=(sim_memory_contents MEMORY) loc' to').\n    inv MEMORY0; clarify; (exfalso; eapply NEXTRA; eauto).\n  Qed.\n\n  Lemma sim_memory_concrete_promised F extra mem_src mem_tgt\n        (MEM: sim_memory F extra mem_src mem_tgt)\n        loc ts\n    :\n      concrete_promised mem_src loc ts\n      <->\n      concrete_promised mem_tgt loc ts /\\ ~ F loc ts.\n  Proof.\n    set (CNT:= (sim_memory_contents MEM) loc ts). split; i.\n    { inv H. erewrite GET in *. inv CNT. split; auto. econs; eauto. }\n    { des. inv H. erewrite GET in *. inv CNT; ss. econs; eauto. }\n  Qed.\n\n  Lemma sim_memory_forget_concrete_promised F extra mem_src mem_tgt\n        (MEM: sim_memory F extra mem_src mem_tgt)\n    :\n      F <2= concrete_promised mem_tgt.\n  Proof.\n    ii. set (CNT:=(sim_memory_contents MEM) x0 x1). inv CNT; ss.\n    econs; eauto.\n  Qed.\n\n  Lemma sim_memory_get_larger F extra mem_src mem_tgt loc from_src ts msg_src\n        (MEM: sim_memory F extra mem_src mem_tgt)\n        (GETSRC: Memory.get loc ts mem_src = Some (from_src, msg_src))\n    :\n      (exists from_tgt msg_tgt,\n          (<<TS: Time.le from_tgt from_src>>) /\\ (<<LB: lb_time (times loc) from_tgt from_src>>) /\\\n          (<<GETTGT: Memory.get loc ts mem_tgt = Some (from_tgt, msg_tgt)>>)) \\/\n      (<<EXTRA: extra loc ts from_src>> /\\ <<FORGET: F loc from_src>>).\n  Proof.\n    set (MEM0 := (sim_memory_contents MEM) loc ts).\n    rewrite GETSRC in *. inv MEM0; eauto.\n    { left. esplits; eauto. destruct (L loc); auto.\n      rewrite NLOC; ss. }\n    { left. esplits; eauto. }\n    { right. esplits; eauto.\n      apply (sim_memory_wf MEM) in EXTRA. des; auto. }\n  Qed.\n\n  Lemma sim_memory_same_max_ts_le mem_src mem_src'\n        F extra mem_tgt\n        (CLOSED: Memory.closed mem_src)\n        (MEM0: sim_memory F extra mem_src mem_tgt)\n        (MEM1: sim_memory F extra mem_src' mem_tgt)\n        loc\n    :\n      Time.le (Memory.max_ts loc mem_src) (Memory.max_ts loc mem_src').\n  Proof.\n    inv CLOSED. specialize (INHABITED loc).\n    eapply Memory.max_ts_spec in INHABITED. des.\n    set (CNT0:=(sim_memory_contents MEM0) loc (Memory.max_ts loc mem_src)).\n    set (CNT1:=(sim_memory_contents MEM1) loc (Memory.max_ts loc mem_src)).\n    rewrite GET in CNT0. inv CNT0.\n    { rewrite <- H in *. inv CNT1; ss.\n      symmetry in H1. eapply Memory.max_ts_spec in H1. des. auto. }\n    { rewrite <- H in *. inv CNT1; ss.\n      symmetry in H1. eapply Memory.max_ts_spec in H1. des. auto. }\n    { inv CNT1; ss.\n      { exfalso. eapply NEXTRA; eauto. }\n      { exfalso. eapply NEXTRA; eauto. }\n      { eapply (sim_memory_wf MEM0) in EXTRA0. des.\n        eapply UNIQUE in EXTRA. subst.\n        symmetry in H1. eapply Memory.max_ts_spec in H1. des. auto. }\n    }\n  Qed.\n\n  Lemma sim_memory_same_max_ts_eq mem_src mem_src'\n        F extra mem_tgt\n        (CLOSED0: Memory.closed mem_src)\n        (CLOSED1: Memory.closed mem_src')\n        (MEM0: sim_memory F extra mem_src mem_tgt)\n        (MEM1: sim_memory F extra mem_src' mem_tgt)\n        loc\n    :\n      Memory.max_ts loc mem_src = Memory.max_ts loc mem_src'.\n  Proof.\n    apply TimeFacts.antisym.\n    { eapply sim_memory_same_max_ts_le; eauto. }\n    { eapply sim_memory_same_max_ts_le; eauto. }\n  Qed.\n\n  Lemma memory_forget_extra_exclusive F extra mem_src mem_tgt loc from to ts\n        (MEM: sim_memory F extra mem_src mem_tgt)\n        (FORGET: F loc ts)\n        (EXTRA: extra loc to from)\n    :\n      ts <> to.\n  Proof.\n    ii. subst.\n    set (MEM0:=(sim_memory_contents MEM) loc to). inv MEM0; ss.\n    eapply NEXTRA; eauto.\n  Qed.\n\n  Lemma sim_memory_disjoint F extra mem_src mem_tgt\n        loc from_tgt to_tgt msg_tgt\n        from_src to_src msg_src x\n        (MEM: sim_memory F extra mem_src mem_tgt)\n        (MEMWF: memory_times_wf times mem_tgt)\n        (GETTGT: Memory.get loc to_tgt mem_tgt = Some (from_tgt, msg_tgt))\n        (GETSRC: Memory.get loc to_src mem_src = Some (from_src, msg_src))\n        (ITVTGT: Interval.mem (from_tgt, to_tgt) x)\n        (ITVSRC: Interval.mem (from_src, to_src) x)\n    :\n      (to_tgt = to_src /\\ <<TS: Time.le from_tgt from_src>> /\\ <<LB: lb_time (times loc) from_tgt from_src>>) \\/\n      (from_tgt = from_src /\\\n       (<<FORGET: F loc from_tgt>>) /\\\n       (<<EXTRA: extra loc to_src from_tgt>>) /\\\n       (<<TS: Time.lt to_src to_tgt>>)).\n  Proof.\n    hexploit sim_memory_get_larger; eauto. i. des.\n    { hexploit Memory.get_disjoint.\n      { eapply GETTGT0. }\n      { eapply GETTGT. }\n      i. des; subst; eauto. exfalso. eapply H.\n      { inv ITVSRC. econs; ss; eauto.\n        eapply TimeFacts.le_lt_lt; eauto. }\n      { eauto. }\n    }\n    { set (MEM0 := (sim_memory_contents MEM) loc from_src). inv MEM0; ss.\n      symmetry in H. exploit memory_get_disjoint_strong.\n      { eapply H. }\n      { eapply GETTGT. }\n      i. des.\n      { subst. inv ITVTGT. inv ITVSRC. ss.\n        exfalso. eapply Time.lt_strorder.\n        eapply (@TimeFacts.lt_le_lt to_tgt x); eauto. }\n      { destruct TS.\n        { exfalso. eapply (sim_memory_wf MEM) in EXTRA. des.\n          eapply MEMWF in GETTGT; eauto. des.\n          hexploit (LB0 from_tgt); eauto.\n          i. inv ITVSRC. inv ITVTGT. ss.\n          eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply H2. } etrans.\n          { left. eapply FROM2. }\n          { eauto. }\n        }\n        { inv H1. right. splits; auto.\n          set (MEM0 := (sim_memory_contents MEM) loc to_tgt).\n          rewrite GETTGT in MEM0. inv MEM0.\n          { exploit memory_get_disjoint_strong.\n            { symmetry in H2. eapply H2. }\n            { eapply GETSRC. }\n            i. des; auto.\n            { subst. exfalso. eapply NEXTRA0; eauto. }\n            { exfalso. dup GETTGT. apply memory_get_ts_strong in GETTGT. des.\n              { subst. inv ITVTGT. ss. }\n              { eapply Time.lt_strorder.\n                eapply (@TimeFacts.lt_le_lt from_tgt to_tgt); eauto. }\n            }\n          }\n          { exploit memory_get_disjoint_strong.\n            { symmetry in H2. eapply H2. }\n            { eapply GETSRC. }\n            i. des; auto.\n            { subst. exfalso. eapply NEXTRA0; eauto. }\n            { exfalso. dup GETTGT. apply memory_get_ts_strong in GETTGT. des.\n              { subst. inv ITVTGT. ss. timetac. }\n              { eapply Time.lt_strorder.\n                eapply (@TimeFacts.lt_le_lt from_tgt to_tgt); eauto. }\n            }\n          }\n        }\n      }\n      { inv ITVTGT. inv ITVSRC. ss.\n        exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n        { eapply TS0. } etrans.\n        { left. apply FROM1. }\n        { eauto. }\n      }\n    }\n  Qed.\n\n  Lemma sim_memory_extra_inj F extra mem_src mem_tgt\n        (MEM: sim_memory F extra mem_src mem_tgt)\n        loc from to0 to1\n        (EXTRA0: extra loc to0 from)\n        (EXTRA1: extra loc to1 from)\n    :\n      to0 = to1.\n  Proof.\n    set (MEM0:=(sim_memory_contents MEM) loc to0).\n    inv MEM0; try by (exfalso; eapply NEXTRA; eauto).\n    set (MEM1:=(sim_memory_contents MEM) loc to1).\n    inv MEM1; try by (exfalso; eapply NEXTRA; eauto). clarify.\n    apply (sim_memory_wf MEM) in EXTRA0. des.\n    exploit UNIQUE; eauto. i. subst.\n    apply (sim_memory_wf MEM) in EXTRA1. des.\n    exploit UNIQUE0; eauto. i. subst.\n    hexploit memory_get_from_inj.\n    { symmetry. eapply H0. }\n    { symmetry. eapply H2. }\n    i. des; subst; auto.\n    { timetac. }\n    { timetac. }\n  Qed.\n\n  Lemma sim_memory_from_forget F extra mem_src mem_tgt\n        (MEM: sim_memory F extra mem_src mem_tgt)\n        loc to from_src from_tgt msg_src msg_tgt\n        (GETSRC: Memory.get loc to mem_src = Some (from_src, msg_src))\n        (GETTGT: Memory.get loc to mem_tgt = Some (from_tgt, msg_tgt))\n        (FORGET: F loc from_src)\n    :\n      from_src = from_tgt.\n  Proof.\n    exploit sim_memory_get_larger; eauto. i. des.\n    { clarify. destruct TS; eauto. exfalso.\n      set (PROM:=(sim_memory_contents MEM) loc from_src). inv PROM; ss.\n      symmetry in H2.\n      exploit Memory.get_disjoint.\n      { apply H2. }\n      { apply GETTGT0. }\n      i. des; subst.\n      { dup GETSRC. apply memory_get_ts_strong in GETSRC. des.\n        { subst. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply H. }\n          { eapply Time.bot_spec. }\n        }\n        { eapply Time.lt_strorder; eauto. }\n      }\n      { eapply x0.\n        { econs; [|refl]. ss.\n          eapply memory_get_ts_strong in H2. des; auto. subst.\n          exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply H. }\n          { eapply Time.bot_spec. }\n        }\n        { econs; ss. eapply memory_get_ts_le in GETSRC; eauto. }\n      }\n    }\n    { set (MEM0 := (sim_memory_contents MEM) loc to).\n      rewrite GETTGT in MEM0. inv MEM0; exfalso; eapply NEXTRA; eauto. }\n  Qed.\n\n  Lemma sim_memory_src_none F extra mem_src mem_tgt\n        (MEM: sim_memory F extra mem_src mem_tgt)\n        loc to\n        (GETSRC: Memory.get loc to mem_src = None)\n    :\n      (<<GETTGT: Memory.get loc to mem_tgt = None>>) /\\\n      (<<NPROM: ~ F loc to >>) /\\\n      (<<NEXTRA: forall t, ~ extra loc to t>>).\n  Proof.\n    set (MEM0:=(sim_memory_contents MEM) loc to).\n    rewrite GETSRC in MEM0. inv MEM0. splits; auto.\n  Qed.\n\n\n  (* sim promises *)\n\n  Inductive sim_promise_content\n            (F: Prop)\n            (extra: Time.t -> Prop)\n            (loc: Loc.t) (ts: Time.t)\n    :\n      option (Time.t * Message.t) -> option (Time.t * Message.t) -> Prop :=\n  | sim_promise_content_none\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (NLOC: L loc)\n    :\n      sim_promise_content F extra loc ts None None\n  | sim_promise_content_normal\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (NLOC: ~ L loc)\n      cnt\n    :\n      sim_promise_content F extra loc ts cnt cnt\n  | sim_promise_content_reserve\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (LOC: L loc)\n      from_src from_tgt\n    :\n      sim_promise_content F extra loc ts\n                          (Some (from_src, Message.reserve))\n                          (Some (from_tgt, Message.reserve))\n  | sim_promise_content_forget\n      (PROM: F)\n      (NEXTRA: forall t, ~ extra t)\n      (LOC: L loc)\n      from_src from_tgt val released\n    :\n      sim_promise_content F extra loc ts\n                          (Some (from_src, Message.reserve))\n                          (Some (from_tgt, Message.concrete val released))\n  | sim_promise_content_extra\n      from\n      (NPROM: ~ F)\n      (LOC: L loc)\n      (EXTRA: extra from)\n    :\n      sim_promise_content F extra loc ts (Some (from, Message.reserve)) None\n  .\n  Hint Constructors sim_promise_content.\n\n  Record sim_promise\n         (self: Loc.t -> Time.t -> Prop)\n         (extra: Loc.t -> Time.t -> Time.t -> Prop)\n         (prom_src prom_tgt: Memory.t): Prop :=\n    {\n      sim_promise_contents:\n        forall loc ts,\n          sim_promise_content (self loc ts) (extra loc ts)\n                              loc ts\n                              (Memory.get loc ts prom_src)\n                              (Memory.get loc ts prom_tgt);\n      sim_promise_wf:\n        forall loc from ts (EXTRA: extra loc ts from),\n          (<<FORGET: self loc from>>) /\\\n          (<<LB: lb_time (times loc) from ts>>) /\\\n          (<<TS: Time.lt from ts>>);\n      sim_promise_extra:\n        forall loc ts (SELF: self loc ts),\n        exists to,\n          (<<GET: Memory.get loc to prom_src = Some (ts, Message.reserve)>>) /\\\n          (<<TS: Time.lt ts to>>);\n    }.\n\n  Lemma promises_forget_extra_exclusive F extra mem_src mem_tgt loc from to ts\n        (PROMISES: sim_promise F extra mem_src mem_tgt)\n        (FORGET: F loc ts)\n        (EXTRA: extra loc to from)\n    :\n      ts <> to.\n  Proof.\n    ii. subst.\n    set (PROM:=(sim_promise_contents PROMISES) loc to). inv PROM; ss.\n    eapply NEXTRA; eauto.\n  Qed.\n\n  Lemma sim_promise_src_none F extra prom_src prom_tgt\n        (PROMISE: sim_promise F extra prom_src prom_tgt)\n        loc to\n        (GETSRC: Memory.get loc to prom_src = None)\n    :\n      (<<GETTGT: Memory.get loc to prom_tgt = None>>) /\\\n      (<<NPROM: ~ F loc to >>) /\\\n      (<<NEXTRA: forall t, ~ extra loc to t>>).\n  Proof.\n    set (PROM:=(sim_promise_contents PROMISE) loc to).\n    rewrite GETSRC in PROM. inv PROM.\n    - splits; auto.\n    - splits; auto.\n  Qed.\n\n  Lemma sim_promise_bot self extra prom_src prom_tgt\n        (SIM: sim_promise self extra prom_src prom_tgt)\n        (BOT: prom_tgt = Memory.bot)\n    :\n      prom_src = Memory.bot.\n  Proof.\n    eapply Memory.ext. i. erewrite Memory.bot_get.\n    set (CNT:=(sim_promise_contents SIM) loc ts). subst.\n    erewrite Memory.bot_get in CNT. inv CNT; ss.\n    eapply sim_promise_wf in EXTRA; eauto. des.\n    set (CNT:=(sim_promise_contents SIM) loc from).\n    erewrite Memory.bot_get in CNT. inv CNT; ss.\n  Qed.\n\n\n\n  (* sim promises strong *)\n\n  Inductive sim_promise_content_strong\n            (F: Prop)\n            (extra: Time.t -> Prop)\n            (extra_all: Time.t -> Time.t -> Prop)\n            (loc: Loc.t) (ts: Time.t)\n    :\n      option (Time.t * Message.t) -> option (Time.t * Message.t) -> Prop :=\n  | sim_promise_content_strong_none\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (NLOC: L loc)\n    :\n      sim_promise_content_strong F extra extra_all loc ts None None\n  | sim_promise_content_strong_normal\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (NLOC: ~ L loc)\n      cnt\n    :\n      sim_promise_content_strong F extra extra_all loc ts cnt cnt\n  | sim_promise_content_strong_reserve\n      (NPROM: ~ F)\n      (NEXTRA: forall t, ~ extra t)\n      (LOC: L loc)\n      from_src from_tgt\n      (EXTRA: from_tgt = from_src \\/ extra_all from_src from_tgt)\n    :\n      sim_promise_content_strong F extra extra_all loc ts\n                          (Some (from_src, Message.reserve))\n                          (Some (from_tgt, Message.reserve))\n  | sim_promise_content_strong_forget\n      (PROM: F)\n      (NEXTRA: forall t, ~ extra t)\n      (LOC: L loc)\n      from_src from_tgt val released\n      (EXTRA: from_tgt = from_src \\/ extra_all from_src from_tgt)\n    :\n      sim_promise_content_strong F extra extra_all loc ts\n                          (Some (from_src, Message.reserve))\n                          (Some (from_tgt, Message.concrete val released))\n  | sim_promise_content_strong_extra\n      from\n      (NPROM: ~ F)\n      (LOC: L loc)\n      (EXTRA: extra from)\n    :\n      sim_promise_content_strong F extra extra_all loc ts (Some (from, Message.reserve)) None\n  .\n  Hint Constructors sim_promise_content_strong.\n\n  Lemma sim_promise_content_strong_sim_promise_content\n        loc ts F extra get0 get1 extra_all\n        (SIM: sim_promise_content_strong F extra extra_all loc ts  get0 get1)\n    :\n      sim_promise_content F extra loc ts get0 get1.\n  Proof.\n    inv SIM; econs; eauto.\n  Qed.\n\n  Record sim_promise_strong\n         (self: Loc.t -> Time.t -> Prop)\n         (extra: Loc.t -> Time.t -> Time.t -> Prop)\n         (extra_all: Loc.t -> Time.t -> Time.t -> Prop)\n         (prom_src prom_tgt: Memory.t): Prop :=\n    {\n      sim_promise_strong_contents:\n        forall loc ts,\n          sim_promise_content_strong (self loc ts) (extra loc ts) (extra_all loc)\n                                     loc ts\n                                     (Memory.get loc ts prom_src)\n                                     (Memory.get loc ts prom_tgt);\n      sim_promise_strong_wf:\n        forall loc from ts (EXTRA: extra loc ts from),\n          (<<FORGET: self loc from>>) /\\\n          (<<LB: lb_time (times loc) from ts>>) /\\\n          (<<TS: Time.lt from ts>>);\n      sim_promise_strong_extra:\n        forall loc ts (SELF: self loc ts),\n        exists to,\n          (<<GET: Memory.get loc to prom_src = Some (ts, Message.reserve)>>) /\\\n          (<<TS: Time.lt ts to>>);\n    }.\n\n  Lemma sim_promise_strong_sim_promise\n        self extra extra_all prom_src prom_tgt\n        (SIM: sim_promise_strong self extra extra_all prom_src prom_tgt)\n    :\n      sim_promise self extra prom_src prom_tgt.\n  Proof.\n    econs.\n    - ii. eapply sim_promise_content_strong_sim_promise_content; eauto.\n      eapply SIM; eauto.\n    - apply SIM.\n    - apply SIM.\n  Qed.\n\n  Record sim_promise_list\n         (self: Loc.t -> Time.t -> Prop)\n         (extra: Loc.t -> Time.t -> Time.t -> Prop)\n         (extra_all: Loc.t -> Time.t -> Time.t -> Prop)\n         (prom_src prom_tgt: Memory.t)\n         (l: list (Loc.t * Time.t)): Prop :=\n    {\n      sim_promise_list_contents:\n        forall loc ts,\n          (<<NORMAL: sim_promise_content_strong (self loc ts) (extra loc ts) (extra_all loc) loc ts\n                                                (Memory.get loc ts prom_src)\n                                                (Memory.get loc ts prom_tgt)>>) \\/\n          ((<<LIN: List.In (loc, ts) l>>) /\\\n           (<<WEAK: sim_promise_content (self loc ts) (extra loc ts) loc ts\n                                        (Memory.get loc ts prom_src)\n                                        (Memory.get loc ts prom_tgt)>>));\n      sim_promise_list_wf:\n        forall loc from ts (EXTRA: extra loc ts from),\n          (<<FORGET: self loc from>>) /\\\n          (<<LB: lb_time (times loc) from ts>>) /\\\n          (<<TS: Time.lt from ts>>);\n      sim_promise_list_extra:\n        forall loc ts (SELF: self loc ts),\n        exists to,\n          (<<GET: Memory.get loc to prom_src = Some (ts, Message.reserve)>>) /\\\n          (<<TS: Time.lt ts to>>);\n    }.\n\n  Lemma sim_promise_list_nil self extra extra_all prom_src prom_tgt\n        (SIM: sim_promise_list self extra extra_all prom_src prom_tgt [])\n    :\n      sim_promise_strong self extra extra_all prom_src prom_tgt.\n  Proof.\n    econs.\n    - ii. hexploit (sim_promise_list_contents SIM); eauto. i. des; eauto. ss.\n    - apply SIM.\n    - apply SIM.\n  Qed.\n\n  Lemma sim_promise_weak_list_exists self extra extra_all prom_src prom_tgt\n        (SIM: sim_promise self extra prom_src prom_tgt)\n        (FIN: Memory.finite prom_src)\n    :\n      exists l,\n        (<<SIM: sim_promise_list self extra extra_all prom_src prom_tgt l>>).\n  Proof.\n    unfold Memory.finite in *. des.\n    hexploit (@list_filter_exists\n                (Loc.t * Time.t)\n                (fun locts =>\n                   let (loc, ts) := locts in\n                   ~ sim_promise_content_strong (self loc ts) (extra loc ts) (extra_all loc) loc ts\n                     (Memory.get loc ts prom_src)\n                     (Memory.get loc ts prom_tgt))\n                dom).\n    i. des. exists l'. econs; [|apply SIM|apply SIM].\n    ii. set (PROM:= (sim_promise_contents SIM) loc ts).\n    destruct (classic (List.In (loc,ts) l')).\n    - right. splits; auto.\n    - left. red. inv PROM; try by (econs; eauto).\n      + apply NNPP. ii. exploit FIN; eauto. i.\n        hexploit (proj1 (@COMPLETE (loc, ts))); auto.\n        splits; auto. ii. rewrite H1 in *. rewrite H2 in *. auto.\n      + apply NNPP. ii. exploit FIN; eauto. i.\n        hexploit (proj1 (@COMPLETE (loc, ts))); auto.\n        splits; auto. ii. rewrite H1 in *. rewrite H2 in *. auto.\n  Qed.\n\n  Lemma sim_promise_weak_strengthen others self extra_others extra_self\n        prom_src prom_tgt mem_src mem_tgt\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (MLETGT: Memory.le prom_tgt mem_tgt)\n        (MLESRC: Memory.le prom_src mem_src)\n        (FIN: Memory.finite prom_src)\n        (BOTNONESRC: Memory.bot_none prom_src)\n        (PROM: sim_promise self extra_self prom_src prom_tgt)\n        (MEMWF: memory_times_wf times mem_tgt)\n    :\n      exists prom_src' mem_src',\n        (<<FUTURE: reserve_future_memory prom_src mem_src prom_src' mem_src'>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src' mem_tgt>>) /\\\n        (<<PROM: sim_promise_strong\n                   self extra_self (extra_others \\\\3// extra_self)\n                   prom_src' prom_tgt>>).\n  Proof.\n    exploit sim_promise_weak_list_exists; eauto. i. des.\n    clear PROM. ginduction l.\n    { i. exists prom_src, mem_src. splits; auto.\n      { econs; eauto. }\n      { eapply sim_promise_list_nil; eauto. }\n    }\n    i. destruct a as [loc ts].\n\n    cut (sim_promise_content_strong (self loc ts) (extra_self loc ts)\n                                    ((extra_others \\\\3// extra_self) loc)\n                                    loc ts\n                                    (Memory.get loc ts prom_src)\n                                    (Memory.get loc ts prom_tgt) \\/\n         exists prom_src' mem_src',\n           (<<FUTURE: reserve_future_memory prom_src mem_src prom_src' mem_src'>>) /\\\n           (<<MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src' mem_tgt>>) /\\\n           (<<PROM: sim_promise_list\n                      self extra_self (extra_others \\\\3// extra_self)\n                      prom_src' prom_tgt l>>)).\n    { intros H. match goal with\n                | [H:?A \\/ ?B |- _ ] => cut B\n                end.\n      { clear H. i. des. exploit IHl.\n        { eauto. }\n        { eapply MEM0. }\n        { eauto. }\n        { eapply reserve_future_memory_le; eauto. }\n        { eapply reserve_future_memory_finite; eauto. }\n        { eapply reserve_future_memory_bot_none; try apply BOTNONESRC; eauto. }\n        { eauto. }\n        { eauto. }\n        i. des. exists prom_src'0, mem_src'0. splits; eauto.\n        eapply reserve_future_memory_trans; eauto. }\n      { des; eauto. exists prom_src, mem_src. splits; auto.\n        { econs; eauto. }\n        econs; [|apply SIM|apply SIM]. ii.\n        set (PROM:=(sim_promise_list_contents SIM) loc0 ts0).\n        ss. des; clarify; auto. }\n    }\n\n    set (SIM0:= (sim_promise_list_contents SIM) loc ts). des; auto.\n    inv WEAK.\n    { left. econs 1; eauto. }\n    { left. econs 2; eauto. }\n    { clear LIN. symmetry in H. symmetry in H0.\n      rename H into PROMTGT. rename H0 into PROMSRC.\n      dup PROMSRC. dup PROMTGT. apply MLESRC in PROMSRC0. apply MLETGT in PROMTGT0.\n      rename PROMSRC0 into MEMSRC. rename PROMTGT0 into MEMTGT.\n      set (MEM0:=(sim_memory_contents MEM) loc ts).\n      rewrite MEMSRC in MEM0. rewrite MEMTGT in MEM0. inv MEM0; ss.\n      destruct (classic (self loc from_src)) as [SELF|NSELF].\n      { left. exploit sim_memory_from_forget; eauto. ss. right. auto. }\n\n      hexploit (@Memory.remove_exists prom_src); eauto.\n      intros [prom_src' REMOVEPROM].\n      hexploit (@Memory.remove_exists_le prom_src mem_src); eauto.\n      intros [mem_src' REMOVEMEM].\n      assert (REMOVE: Memory.promise prom_src mem_src loc from_src ts Message.reserve prom_src' mem_src' Memory.op_kind_cancel).\n      { econs; eauto. }\n      destruct (classic (exists from_src', (extra_others \\\\3// extra_self) loc from_src' from_tgt))\n        as [[from_src' EXTRA]|].\n      { guardH EXTRA.\n        hexploit (@Memory.add_exists mem_src' loc from_src' ts Message.reserve).\n        { ii. erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o.\n          hexploit sim_memory_disjoint.\n          { eauto. }\n          { eauto. }\n          { apply MEMTGT. }\n          { eapply GET2. }\n          { instantiate (1:=x). inv LHS. econs; ss.\n            transitivity from_src'; auto.\n            eapply (sim_memory_wf MEM) in EXTRA. des; auto. }\n          { eauto. }\n          i. destruct H as [EQ|[EQ [FORGET [EXTRA0 TS]]]].\n          { des; subst. destruct o; ss. }\n          { guardH FORGET. guardH EXTRA0.\n            hexploit sim_memory_extra_inj.\n            { eapply MEM. }\n            { eapply EXTRA0. }\n            { eapply EXTRA. }\n            i. subst. inv LHS. inv RHS. ss. timetac. }\n        }\n        { eapply (sim_memory_wf MEM) in EXTRA. destruct EXTRA as [_ EXTRA]. des.\n          eapply LB0.\n          { eapply MEMWF in MEMTGT. des; auto. }\n          { apply memory_get_ts_strong in MEMTGT. des; auto.\n            subst. erewrite BOTNONESRC in PROMSRC. clarify. }\n        }\n        { econs; eauto. }\n        intros [mem_src'' ADDMEM].\n        hexploit (@Memory.add_exists_le prom_src' mem_src'); eauto.\n        { eapply promise_memory_le; eauto. }\n        intros [prom_src'' ADDPROM].\n        assert (ADD: Memory.promise prom_src' mem_src' loc from_src' ts Message.reserve prom_src'' mem_src'' Memory.op_kind_add).\n        { econs; eauto. i. clarify. }\n        right. exists prom_src'', mem_src''. splits; eauto.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { econs; [|apply MEM]. i.\n          erewrite (@Memory.add_o mem_src''); eauto.\n          erewrite (@Memory.remove_o mem_src'); eauto. des_ifs.\n          { ss. des; subst. rewrite MEMTGT. econs; eauto.\n            { left. eapply sim_memory_wf; eauto. ss. eauto. }\n            { i. apply (sim_memory_wf MEM). ss. }\n            { i. ss. }\n          }\n          { apply MEM. }\n        }\n        { econs; [|apply SIM|].\n          { i. erewrite (@Memory.add_o prom_src''); eauto.\n            erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n            { ss. des; subst. left. rewrite PROMTGT. econs; eauto. }\n            { guardH o. set (PROM:=(sim_promise_list_contents SIM) loc0 ts0).\n              des; auto. right. splits; eauto. ss. des; auto.\n              clarify. unguard. des; ss. }\n          }\n          { i. set (PROM:=(sim_promise_list_extra SIM) loc0 ts0 SELF).\n            des. exists to.\n            erewrite Memory.add_o; eauto. erewrite Memory.remove_o; eauto. des_ifs.\n            ss. des; subst. clarify. }\n        }\n      }\n\n      { hexploit (@Memory.add_exists mem_src' loc from_tgt ts Message.reserve).\n        { ii. erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o.\n          hexploit sim_memory_disjoint.\n          { eauto. }\n          { eauto. }\n          { eapply MEMTGT. }\n          { eapply GET2. }\n          { instantiate (1:=x). eauto. }\n          { eauto. }\n          i. destruct H0 as [EQ|[EQ [FORGET [EXTRA TS]]]].\n          { des; subst. destruct o; ss. }\n          { guardH FORGET. guardH EXTRA.\n            eapply H. esplits; eauto. }\n        }\n        { apply memory_get_ts_strong in MEMTGT. des; auto. subst.\n          erewrite BOTNONESRC in PROMSRC. clarify. }\n        { econs. }\n        intros [mem_src'' ADDMEM].\n        hexploit (@Memory.add_exists_le prom_src' mem_src'); eauto.\n        { eapply promise_memory_le; eauto. }\n        intros [prom_src'' ADDPROM].\n        assert (ADD: Memory.promise prom_src' mem_src' loc from_tgt ts Message.reserve prom_src'' mem_src'' Memory.op_kind_add).\n        { econs; eauto. i. clarify. }\n        right. exists prom_src'', mem_src''. splits; eauto.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { econs; [|apply MEM]. i.\n          erewrite (@Memory.add_o mem_src''); eauto.\n          erewrite (@Memory.remove_o mem_src'); eauto. des_ifs.\n          { ss. des; subst. rewrite MEMTGT. econs; eauto.\n            { refl. }\n            { i. apply eq_lb_time. }\n          }\n          { apply MEM. }\n        }\n        { econs; [|apply SIM|].\n          { i. erewrite (@Memory.add_o prom_src''); eauto.\n            erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n            { ss. des; subst. left. rewrite PROMTGT. eauto. }\n            { guardH o. set (PROM:=(sim_promise_list_contents SIM) loc0 ts0).\n              des; auto. right. splits; eauto. ss. des; auto.\n              clarify. unguard. des; ss. }\n          }\n          { i. set (PROM:=(sim_promise_list_extra SIM) loc0 ts0 SELF).\n            des. exists to.\n            erewrite Memory.add_o; eauto. erewrite Memory.remove_o; eauto. des_ifs.\n            ss. des; subst. clarify. }\n        }\n      }\n    }\n\n    { clear LIN. symmetry in H. symmetry in H0.\n      rename H into PROMTGT. rename H0 into PROMSRC.\n      dup PROMSRC. dup PROMTGT. apply MLESRC in PROMSRC0. apply MLETGT in PROMTGT0.\n      rename PROMSRC0 into MEMSRC. rename PROMTGT0 into MEMTGT.\n      set (MEM0:=(sim_memory_contents MEM) loc ts).\n      rewrite MEMSRC in MEM0. rewrite MEMTGT in MEM0. inv MEM0; ss. guardH PROM0.\n      destruct (classic (self loc from_src)) as [SELF|NSELF].\n      { left. exploit sim_memory_from_forget; eauto. ss. right. auto. }\n\n      hexploit (@Memory.remove_exists prom_src); eauto.\n      intros [prom_src' REMOVEPROM].\n      hexploit (@Memory.remove_exists_le prom_src mem_src); eauto.\n      intros [mem_src' REMOVEMEM].\n      assert (REMOVE: Memory.promise prom_src mem_src loc from_src ts Message.reserve prom_src' mem_src' Memory.op_kind_cancel).\n      { econs; eauto. }\n      destruct (classic (exists from_src', (extra_others \\\\3// extra_self) loc from_src' from_tgt))\n        as [[from_src' EXTRA]|].\n      { guardH EXTRA.\n        hexploit (@Memory.add_exists mem_src' loc from_src' ts Message.reserve).\n        { ii. erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o.\n          hexploit sim_memory_disjoint.\n          { eauto. }\n          { eauto. }\n          { eapply MEMTGT. }\n          { eapply GET2. }\n          { instantiate (1:=x). inv LHS. econs; ss.\n            transitivity from_src'; auto.\n            eapply (sim_memory_wf MEM) in EXTRA. des; auto. }\n          { eauto. }\n          i. destruct H as [EQ|[EQ [FORGET [EXTRA0 TS]]]].\n          { des; subst. destruct o; ss. }\n          { guardH FORGET. guardH EXTRA0.\n            hexploit sim_memory_extra_inj.\n            { eapply MEM. }\n            { eapply EXTRA0. }\n            { eapply EXTRA. }\n            i. subst. inv LHS. inv RHS. ss. timetac. }\n        }\n        { eapply (sim_memory_wf MEM) in EXTRA. destruct EXTRA as [_ EXTRA]. des.\n          eapply LB0.\n          { eapply MEMWF in MEMTGT. des; auto. }\n          { apply memory_get_ts_strong in MEMTGT. des; auto.\n            subst. erewrite BOTNONESRC in PROMSRC. clarify. }\n        }\n        { econs; eauto. }\n        intros [mem_src'' ADDMEM].\n        hexploit (@Memory.add_exists_le prom_src' mem_src'); eauto.\n        { eapply promise_memory_le; eauto. }\n        intros [prom_src'' ADDPROM].\n        assert (ADD: Memory.promise prom_src' mem_src' loc from_src' ts Message.reserve prom_src'' mem_src'' Memory.op_kind_add).\n        { econs; eauto. i. clarify. }\n        right. exists prom_src'', mem_src''. splits; eauto.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { econs; [|apply MEM]. i.\n          erewrite (@Memory.add_o mem_src''); eauto.\n          erewrite (@Memory.remove_o mem_src'); eauto. des_ifs.\n          { ss. des; subst. rewrite MEMTGT.\n            econs; eauto.\n            { left. eapply sim_memory_wf; eauto. ss. eauto. }\n            { i. apply (sim_memory_wf MEM). ss. }\n          }\n          { apply MEM. }\n        }\n        { econs; [|apply SIM|].\n          { i. erewrite (@Memory.add_o prom_src''); eauto.\n            erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n            { ss. des; subst. left. rewrite PROMTGT. econs; eauto. }\n            { guardH o. set (PROM1:=(sim_promise_list_contents SIM) loc0 ts0).\n              des; auto. right. splits; eauto. ss. des; auto.\n              clarify. unguard. des; ss. }\n          }\n          { i. set (PROM1:=(sim_promise_list_extra SIM) loc0 ts0 SELF).\n            des. exists to.\n            erewrite Memory.add_o; eauto. erewrite Memory.remove_o; eauto. des_ifs.\n            ss. des; subst. clarify. }\n        }\n      }\n\n      { hexploit (@Memory.add_exists mem_src' loc from_tgt ts Message.reserve).\n        { ii. erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o.\n          hexploit sim_memory_disjoint.\n          { eauto. }\n          { eauto. }\n          { eapply MEMTGT. }\n          { eapply GET2. }\n          { instantiate (1:=x). eauto. }\n          { eauto. }\n          i. destruct H0 as [EQ|[EQ [FORGET [EXTRA TS]]]].\n          { des; subst. destruct o; ss. }\n          { guardH FORGET. guardH EXTRA.\n            eapply H. esplits; eauto. }\n        }\n        { apply memory_get_ts_strong in MEMTGT. des; auto. subst.\n          erewrite BOTNONESRC in PROMSRC. clarify. }\n        { econs. }\n        intros [mem_src'' ADDMEM].\n        hexploit (@Memory.add_exists_le prom_src' mem_src'); eauto.\n        { eapply promise_memory_le; eauto. }\n        intros [prom_src'' ADDPROM].\n        assert (ADD: Memory.promise prom_src' mem_src' loc from_tgt ts Message.reserve prom_src'' mem_src'' Memory.op_kind_add).\n        { econs; eauto. i. clarify. }\n        right. exists prom_src'', mem_src''. splits; eauto.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { econs; [|apply MEM]. i.\n          erewrite (@Memory.add_o mem_src''); eauto.\n          erewrite (@Memory.remove_o mem_src'); eauto. des_ifs.\n          { ss. des; subst. rewrite MEMTGT.\n            econs; eauto.\n            { refl. }\n            { apply eq_lb_time. }\n          }\n          { apply MEM. }\n        }\n        { econs; [|apply SIM|].\n          { i. erewrite (@Memory.add_o prom_src''); eauto.\n            erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n            { ss. des; subst. left. rewrite PROMTGT. eauto. }\n            { guardH o. set (PROM1:=(sim_promise_list_contents SIM) loc0 ts0).\n              des; auto. right. splits; eauto. ss. des; auto.\n              clarify. unguard. des; ss. }\n          }\n          { i. set (PROM1:=(sim_promise_list_extra SIM) loc0 ts0 SELF).\n            des. exists to.\n            erewrite Memory.add_o; eauto. erewrite Memory.remove_o; eauto. des_ifs.\n            ss. des; subst. clarify. }\n        }\n      }\n    }\n    { left. econs 5; eauto. }\n  Qed.\n\n\n\n  (* sim local *)\n\n  Inductive sim_local\n            (self: Loc.t -> Time.t -> Prop)\n            (extra: Loc.t -> Time.t -> Time.t -> Prop)\n    :\n      forall (lc_src lc_tgt: Local.t), Prop :=\n  | sim_local_intro\n      tvw prom_src prom_tgt\n      (PROMS: sim_promise self extra prom_src prom_tgt)\n    :\n      sim_local self extra (Local.mk tvw prom_src) (Local.mk tvw prom_tgt)\n  .\n  Hint Constructors sim_local.\n\n  Lemma sim_local_tview_le self extra lc_src lc_tgt\n        (LOCAL: sim_local self extra lc_src lc_tgt)\n    :\n      TView.le (Local.tview lc_src) (Local.tview lc_tgt).\n  Proof.\n    inv LOCAL. ss. refl.\n  Qed.\n\n  Inductive sim_statelocal\n            (self: Loc.t -> Time.t -> Prop)\n            (extra: Loc.t -> Time.t -> Time.t -> Prop)\n    :\n      sigT (@Language.state ProgramEvent.t) * Local.t -> sigT (@Language.state ProgramEvent.t) * Local.t -> Prop :=\n  | forget_statelocal_intro\n      st lc_src lc_tgt\n      (LOCAL: sim_local self extra lc_src lc_tgt)\n    :\n      sim_statelocal self extra (st, lc_src) (st, lc_tgt)\n  .\n\n\n  Lemma sim_read_step self others extra_self extra_others lc_src lc_tgt mem_src mem_tgt loc to val released ord\n        lc_tgt'\n        (STEPTGT: Local.read_step lc_tgt mem_tgt loc to val released ord lc_tgt')\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\3/ extra_self) mem_src mem_tgt)\n        (LOCAL: sim_local self extra_self lc_src lc_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n        (NOREAD: ~ others loc to)\n    :\n      exists lc_src',\n        (<<STEPSRC: Local.read_step lc_src mem_src loc to val released ord lc_src'>>) /\\\n        (<<SIM: sim_local self extra_self lc_src' lc_tgt'>>) /\\\n        (<<GETSRC: exists from, Memory.get loc to mem_src = Some (from, Message.concrete val released)>>) /\\\n        (<<GETTGT: exists from, Memory.get loc to mem_tgt = Some (from, Message.concrete val released)>>) /\\\n        (<<RELEASEDMSRC: Memory.closed_opt_view released mem_src>>) /\\\n        (<<RELEASEDMTGT: Memory.closed_opt_view released mem_tgt>>) /\\\n        (<<RELEASEDMWF: View.opt_wf released>>)\n        /\\\n        (<<NOREAD: ~ (others \\\\2// self) loc to>>)\n  .\n  Proof.\n    inv LOCAL. inv STEPTGT.\n    set (MEM0:= (sim_memory_contents MEM) loc to). rewrite GET in *. inv MEM0; ss.\n    { inv MEMSRC. hexploit CLOSED.\n      { symmetry. eapply H0. } i. des. inv MSG_CLOSED. inv MSG_WF.\n      inv MEMTGT. hexploit CLOSED1.\n      { eapply GET. } i. des. inv MSG_CLOSED. inv MSG_WF.\n      esplits; eauto. }\n    { exfalso. destruct PROM; auto.\n      set (PROM:= (sim_promise_contents PROMS) loc to). inv PROM; ss.\n      symmetry in H3. eapply CONSISTENT in H3. ss.\n      eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt; [apply H3|].\n      unfold TimeMap.join, View.singleton_ur_if, View.singleton_ur, View.singleton_rw, TimeMap.singleton.\n      etrans; [|eapply Time.join_l]. etrans; [|eapply Time.join_r].\n      des_ifs; ss; setoid_rewrite LocFun.add_spec_eq; refl.\n    }\n  Qed.\n\n  Lemma sim_fence_step self extra lc_src lc_tgt sc ordr ordw\n        sc' lc_tgt'\n        (STEPTGT: Local.fence_step lc_tgt sc ordr ordw lc_tgt' sc')\n        (LOCAL: sim_local self extra lc_src lc_tgt)\n    :\n      exists lc_src',\n        (<<STEPSRC: Local.fence_step lc_src sc ordr ordw lc_src' sc'>>) /\\\n        (<<SIM: sim_local self extra lc_src' lc_tgt'>>)\n  .\n  Proof.\n    inv LOCAL. inv STEPTGT. esplits.\n    - econs; ss; eauto.\n      + ii.\n        set (PROM:= (sim_promise_contents PROMS) loc t).\n        rewrite GET in *. inv PROM; ss.\n        exploit RELEASE; eauto.\n      + i. eapply sim_promise_bot; eauto.\n    - econs; ss; eauto.\n  Qed.\n\n  Lemma sim_promise_consistent self extra lc_src lc_tgt\n        (CONSISTENT: Local.promise_consistent lc_tgt)\n        (SIM: sim_local self extra lc_src lc_tgt)\n    :\n      Local.promise_consistent lc_src.\n  Proof.\n    inv SIM. ii. ss.\n    set (PROM:= (sim_promise_contents PROMS) loc ts).\n    rewrite PROMISE in *. inv PROM. eauto.\n  Qed.\n\n  Lemma sim_failure_step self extra lc_src lc_tgt\n        (STEPTGT: Local.failure_step lc_tgt)\n        (SIM: sim_local self extra lc_src lc_tgt)\n    :\n      Local.failure_step lc_src.\n  Proof.\n    inv STEPTGT. econs.\n    eapply sim_promise_consistent; eauto.\n  Qed.\n\n  Lemma sim_promise_normal others self extra_others extra_self\n        mem_src mem_tgt prom_src prom_tgt\n        loc from to msg prom_tgt' mem_tgt' kind\n        (NLOC: ~ L loc)\n        (STEPTGT: Memory.promise prom_tgt mem_tgt loc from to msg prom_tgt' mem_tgt' kind)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (WFSRC: Memory.le prom_src mem_src)\n        (WFTGT: Memory.le prom_tgt mem_tgt)\n        (PROMISE: sim_promise self extra_self prom_src prom_tgt)\n        (SEMI: semi_closed_message msg mem_src loc to)\n    :\n      exists prom_src' mem_src',\n        (<<STEPSRC: Memory.promise prom_src mem_src loc from to msg prom_src' mem_src' kind>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src' mem_tgt'>>) /\\\n        (<<PROMISE: sim_promise self extra_self prom_src' prom_tgt'>>) /\\\n        (<<CLOSED: Memory.closed_message msg mem_src'>>)\n  .\n  Proof.\n    generalize (sim_memory_others_self_wf MEM). intros PROMSWF.\n    generalize (sim_memory_extra_others_self_wf MEM). intros EXTRAWF.\n    inv STEPTGT.\n\n    (* add case *)\n    - exploit add_succeed_wf; try apply MEM0. i. des.\n      hexploit (@Memory.add_exists mem_src loc from to msg); ss.\n      { i. set (MEM1:= (sim_memory_contents MEM) loc to2).\n        rewrite GET2 in *. inv MEM1; cycle 1.\n        { exfalso. apply NLOC. des; eauto. }\n        { exfalso. apply NLOC. des; eauto. }\n        ii. eapply DISJOINT; eauto.\n        inv RHS. econs; ss. eapply TimeFacts.le_lt_lt; eauto. }\n      intros [mem_src' ADDMEMSRC].\n      exploit Memory.add_exists_le; try apply ADDMEMSRC; eauto.\n      intros [prom_src' ADDPROMSRC].\n\n      assert (PROMISESRC: Memory.promise prom_src mem_src loc from to msg prom_src' mem_src' Memory.op_kind_add).\n      { econs; eauto. i. subst.\n        set (MEM1:= (sim_memory_contents MEM) loc to'). rewrite GET in MEM1. inv MEM1; ss.\n        eapply ATTACH; eauto. erewrite NLOC0; eauto. }\n\n      assert (CLOSEDMSG: Memory.closed_message msg mem_src').\n      { destruct msg; auto.\n        eapply semi_closed_message_add; eauto. }\n\n      exists prom_src', mem_src'. splits; auto.\n      + econs.\n        { ii. set (MEM1:= (sim_memory_contents MEM) loc0 ts).\n          erewrite (@Memory.add_o mem_src'); eauto.\n          erewrite (@Memory.add_o mem_tgt'); eauto.\n          des_ifs; try by (ss; des; clarify).\n          * econs; eauto.\n            { ii. ss. des; clarify; eauto. }\n            { ii. ss. des; clarify; eauto. }\n            { refl. }\n            { i. ss. }\n        }\n        { eapply (sim_memory_wf MEM); eauto. }\n      + econs.\n        { ii. set (PROM:= (sim_promise_contents PROMISE) loc0 ts).\n          erewrite (@Memory.add_o prom_src'); eauto.\n          erewrite (@Memory.add_o prom_tgt'); eauto. des_ifs.\n          ss. des; clarify. econs; eauto.\n          { ii. eapply NLOC. eapply PROMSWF; ss. right. eauto. }\n          { ii. eapply NLOC. eapply EXTRAWF; ss. right. eauto. }\n        }\n        { apply PROMISE. }\n        { i. hexploit (sim_promise_extra PROMISE); eauto. i. des.\n          esplits; eauto. erewrite (@Memory.add_o prom_src'); eauto.\n          des_ifs. ss. des; clarify.\n          exfalso. eapply NLOC. eapply PROMSWF; eauto. right. eauto. }\n\n    (* split case *)\n    - exploit split_succeed_wf; try apply PROMISES. i. des. clarify.\n      set (PROMISE0:= (sim_promise_contents PROMISE) loc ts3). rewrite GET2 in *.\n      inv PROMISE0; ss.\n      hexploit (@Memory.split_exists prom_src loc from to ts3 (Message.concrete val'0 released'0)); ss.\n      { eauto. }\n      intros [prom_src' SPLITPROMSRC].\n      exploit Memory.split_exists_le; try apply SPLITPROMSRC; eauto.\n      intros [mem_src' SPLITMEMSRC].\n\n      assert (PROMISESRC: Memory.promise prom_src mem_src loc from to (Message.concrete val'0 released'0) prom_src' mem_src' (Memory.op_kind_split ts3 (Message.concrete val' released'))).\n      { econs; eauto. }\n\n      assert (CLOSEDMSG: Memory.closed_message (Message.concrete val'0 released'0) mem_src').\n      { eapply semi_closed_message_split; eauto. }\n\n      exists prom_src', mem_src'. splits; auto.\n      + econs.\n        { ii. set (MEM1:=(sim_memory_contents MEM) loc0 ts).\n          erewrite (@Memory.split_o mem_src'); eauto.\n          erewrite (@Memory.split_o mem_tgt'); eauto.\n          des_ifs; try by (ss; des; clarify).\n          { ss. des; clarify. econs; eauto.\n            * refl.\n            * i. ss. }\n          { guardH o. ss. des; clarify. econs; eauto.\n            * refl.\n            * i. ss. }\n        }\n        { apply (sim_memory_wf MEM); eauto. }\n      + econs.\n        { ii. set (PROM:= (sim_promise_contents PROMISE) loc0 ts).\n          erewrite (@Memory.split_o prom_src'); eauto.\n          erewrite (@Memory.split_o prom_tgt'); eauto. des_ifs.\n          * ss. des; clarify. econs; eauto.\n            { ii. eapply NLOC. eapply PROMSWF. right. eauto. }\n            { ii. eapply NLOC. eapply EXTRAWF. right. eauto. }\n          * guardH o. ss. des; clarify. econs; eauto. }\n        { apply PROMISE. }\n        { i. hexploit (sim_promise_extra PROMISE); eauto. i. des.\n          esplits; eauto. erewrite (@Memory.split_o prom_src'); eauto. des_ifs.\n          - ss. des; clarify. exfalso. eapply NLOC. eapply PROMSWF; eauto. right. eauto.\n          - ss. des; clarify. }\n\n    (* lower case *)\n    - exploit lower_succeed_wf; try apply PROMISES. i. des. clarify.\n      set (PROMISE0:= (sim_promise_contents PROMISE) loc to). rewrite GET in *. inv PROMISE0; ss.\n\n      hexploit (@Memory.lower_exists prom_src loc from to (Message.concrete val released) msg); ss.\n\n      intros [prom_src' LOWERPROMSRC].\n      exploit Memory.lower_exists_le; try apply LOWERPROMSRC; eauto.\n      intros [mem_src' LOWERMEMSRC].\n\n      assert (PROMISESRC: Memory.promise prom_src mem_src loc from to msg prom_src' mem_src' (Memory.op_kind_lower (Message.concrete val released))).\n      { econs; eauto. }\n\n      assert (CLOSEDMSG: Memory.closed_message msg mem_src').\n      { destruct msg; auto.\n        eapply semi_closed_message_lower; eauto. }\n\n      exists prom_src', mem_src'. splits; auto.\n      + econs.\n        { ii. set (MEM1:=(sim_memory_contents MEM) loc0 ts).\n          erewrite (@Memory.lower_o mem_src'); eauto.\n          erewrite (@Memory.lower_o mem_tgt'); eauto. des_ifs.\n          ss. des; clarify. econs; eauto.\n          * refl.\n          * i. ss. }\n        { apply (sim_memory_wf MEM); eauto. }\n      + econs.\n        { ii. set (PROM:= (sim_promise_contents PROMISE) loc0 ts).\n          erewrite (@Memory.lower_o prom_src'); eauto.\n          erewrite (@Memory.lower_o prom_tgt'); eauto. des_ifs.\n          ss. des; clarify. econs; eauto. }\n        { apply PROMISE. }\n        { i. hexploit (sim_promise_extra PROMISE); eauto. i. des.\n          esplits; eauto. erewrite (@Memory.lower_o prom_src'); eauto. des_ifs.\n          ss. des; clarify. }\n\n    (* cancel case *)\n    - exploit Memory.remove_get0; try apply PROMISES. i. des.\n      set (PROMISE0 := (sim_promise_contents PROMISE) loc to). rewrite GET in *.\n      inv PROMISE0; ss.\n\n      hexploit (@Memory.remove_exists prom_src loc from to Message.reserve); ss.\n      intros [prom_src' REMOVEPROMSRC].\n      exploit Memory.remove_exists_le; try apply REMOVEPROMSRC; eauto.\n      intros [mem_src' REMOVEMEMSRC].\n\n      assert (PROMISESRC: Memory.promise prom_src mem_src loc from to Message.reserve prom_src' mem_src' Memory.op_kind_cancel).\n      { econs; eauto. }\n\n      exists prom_src', mem_src'.\n      splits; auto.\n      + econs.\n        { ii. set (MEM1:=(sim_memory_contents MEM) loc0 ts).\n          erewrite (@Memory.remove_o mem_src'); eauto.\n          erewrite (@Memory.remove_o mem_tgt'); eauto.\n          des_ifs; try by (des; ss; clarify).\n          * ss. des; clarify. econs; eauto. }\n        { apply MEM. }\n      + econs.\n        { ii. set (PROM:= (sim_promise_contents PROMISE) loc0 ts).\n          erewrite (@Memory.remove_o prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_tgt'); eauto. des_ifs.\n          ss. des; clarify. econs 2; eauto. }\n        { apply PROMISE. }\n        { i. hexploit (sim_promise_extra PROMISE); eauto. i. des.\n          esplits; eauto. erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n          ss. des; clarify. exfalso. eapply NLOC. eapply PROMSWF; eauto. right. eauto. }\n  Qed.\n\n\n  Lemma sim_write_step_normal\n        others self extra_others extra_self lc_src lc_tgt sc mem_src mem_tgt\n        lc_tgt' sc' mem_tgt' loc from to val ord releasedm released kind\n        (NLOC: ~ L loc)\n        (STEPTGT: Local.write_step lc_tgt sc mem_tgt loc from to val releasedm released ord lc_tgt' sc' mem_tgt' kind)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LOCALSRC: Local.wf lc_src mem_src)\n        (LOCALTGT: Local.wf lc_tgt mem_tgt)\n        (SIM: sim_local self extra_self lc_src lc_tgt)\n\n        (RELEASEDMCLOSED: Memory.closed_opt_view releasedm mem_src)\n        (RELEASEDMWF: View.opt_wf releasedm)\n    :\n      exists lc_src' mem_src',\n        (<<STEPSRC: Local.write_step lc_src sc mem_src loc from to val releasedm released ord lc_src' sc' mem_src' kind>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src' mem_tgt'>>) /\\\n        (<<SIM: sim_local self extra_self lc_src' lc_tgt'>>)\n  .\n  Proof.\n    inv STEPTGT. inv WRITE. inv SIM. inv LOCALSRC. inv LOCALTGT.\n\n    hexploit sim_promise_normal; eauto.\n    { ss. econs. unfold TView.write_released. des_ifs; econs.\n      eapply semi_closed_view_join.\n      - inv MEMSRC. eapply unwrap_closed_opt_view; auto.\n        eapply closed_opt_view_semi_closed. auto.\n      - ss. setoid_rewrite LocFun.add_spec_eq. des_ifs.\n        + eapply semi_closed_view_join.\n          * eapply closed_view_semi_closed. inv TVIEW_CLOSED. auto.\n          * inv MEMSRC. eapply semi_closed_view_singleton. auto.\n        + eapply semi_closed_view_join.\n          * eapply closed_view_semi_closed. inv TVIEW_CLOSED. auto.\n          * inv MEMSRC. eapply semi_closed_view_singleton. auto.\n    }\n    i. des. ss.\n\n    hexploit (@Memory.remove_exists\n                prom_src' loc from to\n                (Message.concrete val (TView.write_released tvw sc loc to releasedm ord))).\n    { set (PROM:= (sim_promise_contents PROMISE0) loc to).\n      eapply Memory.remove_get0 in REMOVE. des.\n      rewrite GET in *. inv PROM; ss. }\n    intros [prom_src'' REMOVESRC].\n\n    assert (NSELF: forall ts, ~ self loc ts).\n    { ii. set (PROM:= (sim_promise_contents PROMISE0) loc to). inv PROM; ss.\n      eapply NLOC. eapply sim_memory_others_self_wf; eauto. ss. right. eauto. }\n\n    esplits; eauto.\n\n    - econs; ss.\n      + econs; eauto.\n      + ii. set (PROM:=(sim_promise_contents PROMS) loc t).\n        rewrite GET in *. inv PROM; ss.\n        exploit RELEASE; eauto.\n\n    - econs; auto. econs.\n      { ii. set (PROM:=(sim_promise_contents PROMISE0) loc0 ts).\n        erewrite (@Memory.remove_o prom_src''); eauto.\n        erewrite (@Memory.remove_o promises2); eauto. des_ifs.\n        ss. des; subst. econs 2; eauto.\n        ii. exploit sim_memory_extra_others_self_wf.\n        { eapply MEM0. }\n        { right. eauto. }\n        { ii. ss. }\n      }\n      { apply PROMISE0. }\n      { i. set (PROM:=(sim_promise_extra PROMISE0) loc0 ts SELF). des.\n        esplits; eauto. erewrite (@Memory.remove_o prom_src''); eauto.\n        des_ifs. ss. des; clarify. exfalso. eapply NSELF; eauto. }\n  Qed.\n\n  Lemma sim_promise_step_normal others self extra_others extra_self\n        mem_src mem_tgt mem_tgt' lc_src lc_tgt lc_tgt' loc from to msg kind\n        (NLOC: ~ L loc)\n        (STEPTGT: Local.promise_step lc_tgt mem_tgt loc from to msg lc_tgt' mem_tgt' kind)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (LOCAL: sim_local self extra_self lc_src lc_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LCSRC: Local.wf lc_src mem_src)\n        (LCTGT: Local.wf lc_tgt mem_tgt)\n        (SEMI: semi_closed_message msg mem_src loc to)\n    :\n      exists lc_src' mem_src',\n        (<<STEPSRC: Local.promise_step lc_src mem_src loc from to msg lc_src' mem_src' kind>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src' mem_tgt'>>) /\\\n        (<<LOCAL: sim_local self extra_self lc_src' lc_tgt'>>)\n  .\n  Proof.\n    inv LOCAL. inv LCSRC. inv LCTGT. inv STEPTGT. ss.\n    hexploit sim_promise_normal; eauto. i. des.\n    exists (Local.mk tvw prom_src'), mem_src'. splits; eauto.\n  Qed.\n\n\n  Lemma sim_promise_forget others self extra_others extra_self\n        mem_src mem_tgt prom_src prom_tgt\n        loc from to msg_tgt prom_tgt' mem_tgt' kind_tgt\n        (LOC: L loc)\n        (STEPTGT: Memory.promise prom_tgt mem_tgt loc from to msg_tgt prom_tgt' mem_tgt' kind_tgt)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (MLESRC: Memory.le prom_src mem_src)\n        (MLETGT: Memory.le prom_tgt mem_tgt)\n        (PROMISE: sim_promise self extra_self prom_src prom_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n    :\n      exists prom_src' mem_src' self' extra_self',\n        (<<STEPSRC: reserve_future_memory prom_src mem_src prom_src' mem_src'>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src' mem_tgt'>>) /\\\n        (<<PROMISE: sim_promise self' extra_self' prom_src' prom_tgt'>>)\n  .\n  Proof.\n    inv STEPTGT.\n\n    - exploit add_succeed_wf; try apply MEM0. i. des.\n      assert (exists from_src,\n                 (<<FROM: Time.le from from_src>>) /\\\n                 (<<TO: Time.lt from_src to>>) /\\\n                 (<<LB: lb_time (times loc) from from_src>>) /\\\n                 (<<EMPTY: forall to2 from2 msg2\n                                  (GET: Memory.get loc to2 mem_src = Some (from2, msg2)),\n                     Interval.disjoint (from_src, to) (from2, to2)>>)).\n      { destruct (classic (exists from_src,\n                              (extra_others \\\\3// extra_self) loc from_src from)).\n        { des. hexploit ((sim_memory_wf MEM) loc from from_src); eauto. i. des.\n          exists from_src. splits; eauto.\n          { left. eauto. }\n          { eapply Memory.add_get0 in MEM0. des.\n            eapply MEMWF in GET0. des.\n            eapply LB in TO. auto. }\n          i. hexploit sim_memory_get_larger; eauto. i. des.\n          { ii. eapply DISJOINT; eauto.\n            { instantiate (1:=x). inv LHS. econs; ss.\n              transitivity from_src; eauto. }\n            { inv RHS. econs; ss. eapply TimeFacts.le_lt_lt; eauto. }\n          }\n          { hexploit ((sim_memory_wf MEM) loc from2 to2); eauto. i. des.\n            ii. inv LHS. inv RHS. ss.\n            set (MEM1:=(sim_memory_contents MEM) loc from_src).\n            inv MEM1; try by (exfalso; eapply NEXTRA; eauto); ss.\n            set (MEM2:=(sim_memory_contents MEM) loc to2).\n            inv MEM2; try by (exfalso; eapply NEXTRA; eauto); ss.\n            symmetry in H1. symmetry in H3. hexploit memory_get_disjoint_strong.\n            { eapply H3. }\n            { eapply H1. }\n            i. des; clarify.\n            { timetac. }\n            { eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n              { eapply TS3. } etrans.\n              { left. eapply FROM. }\n              { eauto. }\n            }\n            { set (MEM3:=(sim_memory_contents MEM) loc from2). inv MEM3; ss.\n              symmetry in H6. eapply DISJOINT.\n              { eapply H6. }\n              { instantiate (1:=from2). econs; ss.\n                { eapply TimeFacts.lt_le_lt; eauto. }\n                { transitivity x; auto. left. auto. }\n              }\n              { econs; ss.\n                { apply memory_get_ts_strong in H6. des; auto.\n                  subst. inv MEMSRC. rewrite INHABITED in H5. clarify. }\n                { refl. }\n              }\n            }\n          }\n        }\n        { exists from. splits; auto.\n          { refl. }\n          { apply eq_lb_time. }\n          { i. hexploit sim_memory_get_larger; eauto. i. des.\n            { ii. eapply DISJOINT; eauto.\n              inv RHS. econs; ss. eapply TimeFacts.le_lt_lt; eauto. }\n            { hexploit ((sim_memory_wf MEM) loc from2 to2); eauto. i. des.\n              ii. inv LHS. inv RHS. ss.\n              set (MEM1:=(sim_memory_contents MEM) loc from2).\n              inv MEM1; try by (exfalso; eapply NPROM; eauto); ss.\n              symmetry in H2. hexploit memory_get_disjoint_strong.\n              { eapply Memory.add_get0. eapply MEM0. }\n              { eapply Memory.add_get1; eauto. }\n              i. des; subst.\n              { eapply Memory.add_get0 in MEM0. des. clarify. }\n              { eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n                { eapply TS2. } etrans.\n                { left. eapply FROM0. }\n                { eauto. }\n              }\n              { destruct TS1; cycle 1.\n                { inv H0. eapply H. eauto. }\n                { exploit LB.\n                  { instantiate (1:=from).\n                    eapply Memory.add_get0 in MEM0. des.\n                    eapply MEMWF in GET1. des. auto. }\n                  { auto. }\n                  { i. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n                    { eapply FROM. } etrans.\n                    { eapply TO0. }\n                    { left. auto. }\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n\n      des. hexploit (@Memory.add_exists mem_src loc from_src to Message.reserve); eauto.\n      { econs. }\n      intros [mem_src0 ADDMEM0].\n      hexploit (@Memory.add_exists_le prom_src mem_src loc from_src to Message.reserve); eauto.\n      intros [prom_src0 ADDPROM0].\n      assert (PROMISE0: Memory.promise prom_src mem_src loc from_src to Message.reserve prom_src0 mem_src0 Memory.op_kind_add).\n      { econs; eauto. i. clarify. }\n\n      assert (GETMEMNONE: Memory.get loc to mem_src = None).\n      { eapply Memory.add_get0; eauto. }\n      assert (GETPROMNONE: Memory.get loc to prom_src = None).\n      { destruct (Memory.get loc to prom_src) eqn:EQ; auto.\n        destruct p. apply MLESRC in EQ. clarify. }\n      hexploit sim_memory_src_none.\n      { eauto. }\n      { eapply GETMEMNONE. } i. des.\n      hexploit sim_promise_src_none.\n      { eauto. }\n      { eapply GETPROMNONE. } i. des.\n\n      destruct msg_tgt as [val released|].\n      { hexploit (@lb_time_exists (times loc) (@WO loc) to). i. des.\n        hexploit (@Memory.add_exists mem_src0 loc to ts' Message.reserve); eauto.\n        { i. erewrite Memory.add_o in GET2; eauto. des_ifs.\n          { ss. des; subst. ii. inv LHS. inv RHS. ss. timetac. }\n          des; ss. hexploit sim_memory_get_larger; eauto. i. des.\n          { ii. inv LHS. inv RHS. ss.\n            dup GETTGT1. eapply Memory.add_get1 in GETTGT1; eauto.\n            hexploit memory_get_disjoint_strong.\n            { eapply GETTGT1. }\n            { eapply Memory.add_get0; eauto. }\n            i. des; clarify.\n            { eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n              { eapply TS3. } etrans.\n              { left. eapply FROM0. }\n              { eauto. }\n            }\n            { destruct TS2.\n              { exploit LB0.\n                { instantiate (1:=from_tgt).\n                  eapply MEMWF in GETTGT1. des. auto. }\n                { auto. }\n                { i. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n                  { eapply x0. } etrans.\n                  { eapply TS1. } etrans.\n                  { left. eapply FROM1. }\n                  { eauto. }\n                }\n              }\n              { inv H. eapply ATTACH; eauto. }\n            }\n          }\n          { hexploit ((sim_memory_wf MEM) loc from2 to2); eauto. i. des.\n            set (MEM1:=(sim_memory_contents MEM) loc from2).\n            inv MEM1; ss.\n            symmetry in H. hexploit memory_get_disjoint_strong.\n            { eapply Memory.add_get1 in H; [|eauto]. eapply H. }\n            { eapply Memory.add_get0; eauto. }\n            i. des; clarify.\n            { ii. inv LHS. inv RHS. ss. exploit LB1.\n              { instantiate (1:=to).\n                apply Memory.add_get0 in MEM0. des.\n                apply MEMWF in GET0. des. auto. }\n              { auto. }\n              { i. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n                { eapply FROM1. } etrans.\n                { eapply TO2. }\n                { left. eauto. }\n              }\n            }\n            { eapply interval_le_disjoint.\n              left. eapply LB0; auto.\n              eapply Memory.add_get1 in H; eauto.\n              eapply MEMWF in H. des. auto. }\n          }\n        }\n        { econs. }\n        intros [mem_src1 ADDMEM1].\n        hexploit (@Memory.add_exists_le prom_src0 mem_src0 loc to ts' Message.reserve); eauto.\n        { eapply promise_memory_le; cycle 1; eauto. }\n        intros [prom_src1 ADDPROM1].\n        assert (PROMISE1: Memory.promise prom_src0 mem_src0 loc to ts' Message.reserve prom_src1 mem_src1 Memory.op_kind_add).\n        { econs; eauto. i. clarify. }\n\n        assert (GETMEMNONE0: Memory.get loc ts' mem_src = None).\n        { destruct (Memory.get loc ts' mem_src) eqn:EQ; auto.\n          destruct p. eapply Memory.add_get1 in EQ; eauto.\n          eapply Memory.add_get0 in ADDMEM1. des. clarify. }\n        assert (GETPROMNONE0: Memory.get loc ts' prom_src = None).\n        { destruct (Memory.get loc ts' prom_src) eqn:EQ; auto.\n          destruct p. eapply MLESRC in EQ. clarify. }\n        hexploit sim_memory_src_none.\n        { eauto. }\n        { eapply GETMEMNONE0. } i. des.\n        hexploit sim_promise_src_none.\n        { eauto. }\n        { eapply GETPROMNONE0. } i. des.\n\n        exists prom_src1, mem_src1,\n        (fun loc' ts' => if loc_ts_eq_dec (loc', ts') (loc, to)\n                         then True else self loc' ts'),\n        (fun l t => if (loc_ts_eq_dec (l, t) (loc, ts'))\n                    then (eq to)\n                    else extra_self l t). splits; eauto.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { econs.\n          { i. erewrite (@Memory.add_o mem_src1); eauto.\n            erewrite (@Memory.add_o mem_src0); eauto.\n            erewrite (@Memory.add_o mem_tgt'); eauto. des_ifs.\n            { ss. des; clarify. timetac. }\n            { ss. des; clarify. econs 3; eauto. right. auto. }\n            { ss. des; clarify. erewrite GETTGT1.\n              econs 4; eauto. right. auto. }\n            { eapply (sim_memory_contents MEM). }\n          }\n          { i. des_ifs; eauto.\n            { ss. des; clarify. splits; auto.\n              { right. auto. }\n              { i. destruct EXTRA0; auto.\n                exfalso. eapply NEXTRA1. left. eauto. }\n            }\n            { apply (sim_memory_wf MEM) in EXTRA. ss. des; clarify. }\n            { ss. des; clarify. destruct EXTRA as [EXTRA|EQ]; subst; ss.\n              hexploit ((sim_memory_wf MEM) loc from0 ts').\n              { left. auto. }\n              i. des. splits; auto.\n              i. destruct EXTRA0 as [EXTRA0|EQ].\n              { exfalso. eapply NEXTRA1. left. eauto. }\n              { subst. exfalso. eapply NEXTRA1. left. eauto. }\n            }\n            { eapply (sim_memory_wf MEM). auto. }\n          }\n        }\n        { econs.\n          { i. erewrite (@Memory.add_o prom_src1); eauto.\n            erewrite (@Memory.add_o prom_src0); eauto.\n            erewrite (@Memory.add_o prom_tgt'); eauto. des_ifs.\n            { ss. des; clarify. timetac. }\n            { ss. des; clarify. econs 4; eauto. }\n            { ss. des; clarify. erewrite GETTGT2. econs 5; eauto. }\n            { eapply (sim_promise_contents PROMISE). }\n          }\n          { i. des_ifs.\n            { ss. des; clarify. }\n            { ss. des; clarify.\n              hexploit ((sim_promise_wf PROMISE) loc to ts); auto.\n              i. des. splits; auto. }\n            { ss. des; clarify. }\n            { eapply (sim_promise_wf PROMISE); auto. }\n          }\n          { i. des_ifs.\n            { ss. des; clarify. exists ts'. splits; auto.\n              eapply Memory.add_get0; eauto. }\n            { guardH o. eapply (sim_promise_extra PROMISE) in SELF. des.\n              exists to0. splits; eauto.\n              eapply Memory.add_get1; eauto. eapply Memory.add_get1; eauto. }\n          }\n        }\n      }\n\n      exists prom_src0, mem_src0, self, extra_self. splits; eauto.\n      { econs; eauto. econs; eauto. }\n      { econs.\n        { i. erewrite (@Memory.add_o mem_src0); eauto.\n          erewrite (@Memory.add_o mem_tgt'); eauto. des_ifs.\n          { ss. des; clarify. econs 2; eauto. i. ss. }\n          { eapply (sim_memory_contents MEM). }\n        }\n        { eapply (sim_memory_wf MEM). }\n      }\n      { econs.\n        { i. erewrite (@Memory.add_o prom_src0); eauto.\n          erewrite (@Memory.add_o prom_tgt'); eauto. des_ifs.\n          { ss. des; clarify. econs 3; eauto. }\n          { eapply (sim_promise_contents PROMISE). }\n        }\n        { eapply (sim_promise_wf PROMISE). }\n        { i. eapply (sim_promise_extra PROMISE) in SELF. des.\n          exists to0. splits; eauto. eapply Memory.add_get1; eauto.  }\n      }\n\n    - des. subst.\n      exploit split_succeed_wf; try apply PROMISES. i. des.\n      dup GET2. apply MLETGT in GET0.\n      set (PROM:=(sim_promise_contents PROMISE) loc ts3).\n      rewrite GET2 in PROM.\n\n      set (MEM1:=(sim_memory_contents MEM) loc ts3). rewrite GET0 in MEM1.\n\n      assert (exists from_src,\n                 (<<GETSRC: Memory.get loc ts3 prom_src = Some (from_src, Message.reserve)>>) /\\\n                 (<<LB: lb_time (times loc) from from_src>>) /\\\n                 (<<FROM: Time.le from from_src>>)).\n      { inv PROM; ss.\n        { symmetry in H0. apply MLESRC in H0.\n          rewrite H0 in *. inv MEM1. esplits; eauto. }\n      } des.\n      assert (TS0: Time.lt from_src to).\n      { eapply LB; auto.\n        apply Memory.split_get0 in MEM0. des.\n        eapply MEMWF in GET4. des. auto. }\n\n      assert (NEXTRATO: forall t, ~ (extra_others loc to t \\/ extra_self loc to t)).\n      { set (MEM2:=(sim_memory_contents MEM) loc to).\n        inv MEM2; ss. guardH EXTRA. exfalso.\n        hexploit memory_get_disjoint_strong.\n        { symmetry. apply H0. }\n        { apply MLESRC. apply GETSRC. }\n        i. des; subst.\n        { timetac. }\n        { timetac. }\n        { eapply Time.lt_strorder. transitivity to; eauto. }\n      }\n\n      hexploit (@Memory.remove_exists prom_src loc from_src ts3 Message.reserve).\n      { eauto. }\n      intros [prom_src0 REMOVEPROM].\n      hexploit (@Memory.remove_exists_le prom_src mem_src loc from_src ts3 Message.reserve); eauto.\n      intros [mem_src0 REMOVEMEM].\n      assert (PROMISE0: Memory.promise prom_src mem_src loc from_src ts3 Message.reserve prom_src0 mem_src0 Memory.op_kind_cancel).\n      { econs; eauto. }\n\n      hexploit (@Memory.add_exists mem_src0 loc from_src to Message.reserve); auto.\n      { i. erewrite Memory.remove_o in GET1; eauto. des_ifs. guardH o.\n        hexploit Memory.get_disjoint.\n        { eapply GET1. }\n        { eapply MLESRC. eapply GETSRC. }\n        i. des; clarify.\n        { ss. destruct o; ss. }\n        { ii. eapply H; eauto. inv LHS. econs; ss.\n          etrans; eauto. left. auto. }\n      }\n      { econs. }\n      intros [mem_src1 ADDMEM1].\n      hexploit (@Memory.add_exists_le prom_src0 mem_src0 loc from_src to Message.reserve); eauto.\n      { eapply promise_memory_le; try apply PROMISE0; eauto. }\n      intros [prom_src1 ADDPROM1].\n      assert (PROMISE1: Memory.promise prom_src0 mem_src0 loc from_src to Message.reserve prom_src1 mem_src1 Memory.op_kind_add).\n      { econs; eauto. i. clarify. }\n      hexploit (@Memory.add_exists mem_src1 loc to ts3 Message.reserve); auto.\n      { i. erewrite Memory.add_o in GET1; eauto. des_ifs.\n        { ss. des; subst. ii. inv LHS. inv RHS. ss. timetac. }\n        { erewrite Memory.remove_o in GET1; eauto. des_ifs. guardH o.\n          hexploit Memory.get_disjoint.\n          { eapply GET1. }\n          { eapply MLESRC. eapply GETSRC. }\n          i. des; clarify.\n          ii. eapply H; eauto. inv LHS. econs; ss.\n          etrans; eauto. }\n      }\n      { econs. }\n      intros [mem_src2 ADDMEM2].\n      hexploit (@Memory.add_exists_le prom_src1 mem_src1 loc to ts3 Message.reserve); eauto.\n      { eapply promise_memory_le; try apply PROMISE1; eauto.\n        eapply promise_memory_le; try apply PROMISE0; eauto. }\n      intros [prom_src2 ADDPROM2].\n      assert (PROMISE2: Memory.promise prom_src1 mem_src1 loc to ts3 Message.reserve prom_src2 mem_src2 Memory.op_kind_add).\n      { econs; eauto. i. clarify. }\n\n      exists prom_src2, mem_src2,\n      (fun loc' ts' => if loc_ts_eq_dec (loc', ts') (loc, to)\n                       then True else self loc' ts'), extra_self. splits; auto.\n      { econs; eauto. econs; eauto. econs; eauto. econs; eauto. }\n      { econs.\n        { i. erewrite (@Memory.split_o mem_tgt'); eauto.\n          erewrite (@Memory.add_o mem_src2); eauto.\n          erewrite (@Memory.add_o mem_src1); eauto.\n          erewrite (@Memory.remove_o mem_src0); eauto. des_ifs.\n          { ss. des; subst. exfalso. eapply Time.lt_strorder; eauto. }\n          { ss. des; clarify. econs 3; auto. right. auto. }\n          { ss. des; clarify. inv PROM; ss.\n            { dup H0. symmetry in H0. apply MLESRC in H0.\n              rewrite H0 in *. inv MEM1.\n              econs 3; eauto.\n              { refl. }\n              { i. apply eq_lb_time. }\n            }\n          }\n          { eapply ((sim_memory_contents MEM)). }\n        }\n        { i. dup EXTRA.\n          apply ((sim_memory_wf MEM)) in EXTRA0. des_ifs.\n          destruct a. ss. subst. splits; try apply EXTRA0; auto. right. auto. }\n      }\n      { econs.\n        { i. erewrite (@Memory.split_o prom_tgt'); eauto.\n          erewrite (@Memory.add_o prom_src2); eauto.\n          erewrite (@Memory.add_o prom_src1); eauto.\n          erewrite (@Memory.remove_o prom_src0); eauto. des_ifs.\n          { ss. des; subst. exfalso. eapply Time.lt_strorder; eauto. }\n          { ss. des; clarify. econs 4; auto.\n            ii. eapply NEXTRATO. eauto. }\n          { ss. des; clarify. inv PROM; ss.\n            { econs 4; eauto. }\n          }\n          { eapply ((sim_promise_contents PROMISE)). }\n        }\n        { i. dup EXTRA.\n          apply ((sim_promise_wf PROMISE)) in EXTRA0. des_ifs.\n          destruct a. ss. subst. splits; try apply EXTRA0; auto. }\n        { i. des_ifs.\n          { ss. des. subst.\n            eapply Memory.add_get0 in ADDPROM2. des. esplits; eauto. }\n          { guardH o. apply (sim_promise_extra PROMISE) in SELF. des.\n            destruct (loc_ts_eq_dec (loc0, to0) (loc, ts3)).\n            { ss. des; subst. clarify.\n              eapply Memory.add_get0 in ADDPROM1. des.\n              eapply Memory.add_get1 in GET3; eauto. }\n            destruct (loc_ts_eq_dec (loc0, to0) (loc, to)).\n            { ss. des; clarify. exfalso.\n              hexploit memory_get_disjoint_strong.\n              { eapply GET. }\n              { eapply GETSRC. }\n              i. des; clarify.\n              { timetac. }\n              { eapply Time.lt_strorder; eauto. }\n            }\n            { guardH o0. guardH o1. exists to0. splits; auto.\n              erewrite (@Memory.add_o prom_src2); eauto.\n              erewrite (@Memory.add_o prom_src1); eauto.\n              erewrite (@Memory.remove_o prom_src0); eauto. des_ifs.\n              { ss. des; subst. destruct o0; ss. }\n              { ss. destruct a; subst. destruct o1; ss. }\n            }\n          }\n        }\n      }\n\n    - des. subst.\n      exploit lower_succeed_wf; try apply PROMISES. i. des. inv MSG_LE.\n      rename GET into GETPROMTGT.\n      dup GETPROMTGT. apply MLETGT in GETPROMTGT0. rename GETPROMTGT0 into GETMEMTGT.\n      set (PROM:=(sim_promise_contents PROMISE) loc to).\n      rewrite GETPROMTGT in PROM. inv PROM; ss.\n      symmetry in H0. dup H0. apply MLESRC in H0.\n      rename H0 into GETMEMSRC. rename H1 into GETPROMSRC.\n      set (MEM1:=(sim_memory_contents MEM) loc to).\n      rewrite GETMEMSRC in MEM1. rewrite GETMEMTGT in MEM1. inv MEM1. clear PROM.\n\n      exists prom_src, mem_src, self, extra_self. splits; auto.\n      { econs. }\n      { econs.\n        { i. erewrite (@Memory.lower_o mem_tgt'); eauto. des_ifs.\n          { ss. des; subst. rewrite GETMEMSRC. econs; eauto. right. auto. }\n          { eapply (sim_memory_contents MEM). }\n        }\n        { apply (sim_memory_wf MEM). }\n      }\n      { econs.\n        { i. erewrite (@Memory.lower_o prom_tgt'); eauto. des_ifs.\n          { ss. des; subst. rewrite GETPROMSRC. econs; eauto. }\n          { eapply (sim_promise_contents PROMISE). }\n        }\n        { apply (sim_promise_wf PROMISE). }\n        { apply (sim_promise_extra PROMISE). }\n      }\n\n    - exploit Memory.remove_get0; try apply PROMISES. i. des.\n      rename GET into GETPROMTGT.\n      dup GETPROMTGT. apply MLETGT in GETPROMTGT0. rename GETPROMTGT0 into GETMEMTGT.\n      set (PROM:=(sim_promise_contents PROMISE) loc to).\n      rewrite GETPROMTGT in PROM. inv PROM; ss.\n      symmetry in H0. dup H0. apply MLESRC in H0.\n      rename H0 into GETMEMSRC. rename H1 into GETPROMSRC.\n      set (MEM1:=(sim_memory_contents MEM) loc to).\n      rewrite GETMEMSRC in MEM1. rewrite GETMEMTGT in MEM1. inv MEM1.\n\n      hexploit (@Memory.remove_exists prom_src loc from_src to Message.reserve).\n      { eauto. }\n      intros [prom_src0 REMOVEPROM].\n      hexploit (@Memory.remove_exists_le prom_src mem_src loc from_src to Message.reserve); eauto.\n      intros [mem_src0 REMOVEMEM].\n      assert (PROMISE0: Memory.promise prom_src mem_src loc from_src to Message.reserve prom_src0 mem_src0 Memory.op_kind_cancel).\n      { econs; eauto. }\n\n      destruct (classic (self loc from_src)) as [SELF|NSELF].\n      { exploit sim_memory_from_forget; eauto.\n        { ss. right. auto. } i. subst.\n        assert (TS: Time.lt from to).\n        { apply memory_get_ts_strong in GETPROMSRC. des; auto.\n          subst. clarify. }\n        assert (exists ts', (<<LB: lb_time (times loc) from ts'>>) /\\\n                            (<<TS0: Time.lt from ts'>>) /\\\n                            (<<TS1: Time.lt ts' to>>)).\n        { hexploit (@lb_time_exists (times loc) (@WO loc) from). i. des.\n          destruct (Time.le_lt_dec ts' (Time.middle from to)).\n          { exists ts'. splits; auto.\n            eapply TimeFacts.le_lt_lt; eauto. eapply Time.middle_spec; eauto. }\n          { exists (Time.middle from to). splits; auto.\n            { eapply lb_time_lower; eauto. left. auto. }\n            { eapply Time.middle_spec; eauto. }\n            { eapply Time.middle_spec; eauto. }\n          }\n        } des.\n        hexploit (@Memory.add_exists mem_src0 loc from ts' Message.reserve); eauto.\n        { ii. erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o.\n          hexploit Memory.get_disjoint.\n          { eapply GET2. }\n          { eapply GETMEMSRC. }\n          i. des.\n          { subst. destruct o; ss. }\n          { eapply H.\n            { eapply RHS. }\n            { inv LHS. econs; ss. etrans; eauto. left. auto. }\n          }\n        }\n        { econs. }\n        intros [mem_src1 ADDMEM].\n        hexploit (@Memory.add_exists_le prom_src0 mem_src0 loc from ts' Message.reserve); eauto.\n        { eapply promise_memory_le; try apply PROMISE0; eauto. }\n        intros [prom_src1 ADDPROM].\n        assert (PROMISE1: Memory.promise prom_src0 mem_src0 loc from ts' Message.reserve prom_src1 mem_src1 Memory.op_kind_add).\n        { econs; eauto. i. clarify. }\n\n        assert (GETMEMNONE: Memory.get loc ts' mem_src = None).\n        { destruct (Memory.get loc ts' mem_src) eqn:GET; auto. destruct p.\n          hexploit memory_get_disjoint_strong.\n          { eapply GET. }\n          { eapply GETMEMSRC. } i. des; subst.\n          { timetac. }\n          { timetac. }\n          { exfalso. eapply Time.lt_strorder.\n            transitivity ts'; eauto. }\n        }\n        assert (GETPROMNONE: Memory.get loc ts' prom_src = None).\n        { destruct (Memory.get loc ts' prom_src) eqn:EQ; auto.\n          destruct p. apply MLESRC in EQ. clarify. }\n        hexploit sim_memory_src_none.\n        { eauto. }\n        { eapply GETMEMNONE. } i. des.\n        hexploit sim_promise_src_none.\n        { eauto. }\n        { eapply GETPROMNONE. } i. des.\n\n        exists prom_src1, mem_src1, self,\n        (fun l t => if (loc_ts_eq_dec (l, t) (loc, ts'))\n                    then (eq from)\n                    else extra_self l t). splits; eauto.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { econs.\n          { i. erewrite (@Memory.remove_o mem_tgt'); eauto.\n            erewrite (@Memory.add_o mem_src1); eauto.\n            erewrite (@Memory.remove_o mem_src0); eauto. des_ifs.\n            { ss. des; clarify. }\n            { ss. des; clarify. rewrite GETTGT. econs 4; eauto. right. auto. }\n            { ss. des; clarify. eauto. }\n            { eapply (sim_memory_contents MEM). }\n          }\n          { i. des_ifs.\n            { ss. des; clarify. destruct EXTRA as [EXTRA|EQ].\n              { hexploit ((sim_memory_wf MEM) loc from0 ts'); eauto.\n                { left. auto. }\n                i. des. splits; auto. i. des_ifs; eauto.\n                ss. des; clarify. destruct EXTRA0.\n                { exfalso. eapply NEXTRA1. left. eauto. }\n                { subst. exfalso. eapply NEXTRA1. left. eauto. }\n              }\n              { subst. splits; auto.\n                { right. auto. }\n                { i. des_ifs. ss. des; clarify.\n                  destruct EXTRA as [EXTRA|EQ]; auto.\n                  exfalso. eapply NEXTRA1. left. eauto. }\n              }\n            }\n            { hexploit ((sim_memory_wf MEM) loc0 from0 ts); eauto. }\n          }\n        }\n        { econs.\n          { i. erewrite (@Memory.remove_o prom_tgt'); eauto.\n            erewrite (@Memory.add_o prom_src1); eauto.\n            erewrite (@Memory.remove_o prom_src0); eauto. des_ifs.\n            { ss. des; clarify. }\n            { ss. des; clarify. rewrite GETTGT0. econs 5; eauto. }\n            { ss. des; clarify. eauto. }\n            { eapply (sim_promise_contents PROMISE). }\n          }\n          { i. des_ifs.\n            { ss. des; clarify. }\n            { eapply (sim_promise_wf PROMISE); eauto. }\n          }\n          { i. hexploit ((sim_promise_extra PROMISE) loc0 ts); eauto. i. des.\n            destruct (loc_ts_eq_dec (loc0, ts) (loc, from)).\n            { ss. des. clarify. exists ts'. splits; auto.\n              eapply Memory.add_get0; eauto. }\n            { exists to0. splits; auto.\n              erewrite Memory.add_o; eauto. erewrite Memory.remove_o; eauto.\n              des_ifs.\n              { ss. des; clarify. }\n              { ss. des; clarify. }\n            }\n          }\n        }\n      }\n      { exists prom_src0, mem_src0, self, extra_self. splits; eauto.\n        { econs; eauto. econs; eauto. }\n        { econs.\n          { i. erewrite (@Memory.remove_o mem_tgt'); eauto.\n            erewrite (@Memory.remove_o mem_src0); eauto. des_ifs.\n            { ss. des; subst. eauto. }\n            { eapply (sim_memory_contents MEM). }\n          }\n          { apply (sim_memory_wf MEM). }\n        }\n        { econs.\n          { i. erewrite (@Memory.remove_o prom_tgt'); eauto.\n            erewrite (@Memory.remove_o prom_src0); eauto. des_ifs.\n            { ss. des; subst. eauto. }\n            { eapply (sim_promise_contents PROMISE). }\n          }\n          { apply (sim_promise_wf PROMISE). }\n          { i. dup SELF. apply (sim_promise_extra PROMISE) in SELF. des.\n            destruct (loc_ts_eq_dec (loc0, to0) (loc, to)).\n            { ss. des; clarify. }\n            { exists to0. splits; auto. erewrite Memory.remove_o; eauto. des_ifs.\n              ss. des; clarify. }\n          }\n        }\n      }\n  Qed.\n\n\n  Lemma sim_fulfill_forget from_src' others self extra_others extra_self\n        prom_src prom_tgt mem_src mem_tgt prom_tgt'\n        loc from_tgt to val released\n        (LOC: L loc)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (MLETGT: Memory.le prom_tgt mem_tgt)\n        (MLESRC: Memory.le prom_src mem_src)\n        (FIN: Memory.finite prom_src)\n        (BOTNONESRC: Memory.bot_none prom_src)\n        (BOTNONETGT: Memory.bot_none prom_tgt)\n        (PROMISE: sim_promise self extra_self prom_src prom_tgt)\n        (REMOVE: Memory.remove prom_tgt loc from_tgt to (Message.concrete val released) prom_tgt')\n        (CLOSED: Memory.closed mem_tgt)\n\n        (FROMSRC0: Time.le from_tgt from_src')\n        (FROMSRC1: forall from_src msg\n                          (GET: Memory.get loc to mem_src = Some (from_src, msg)),\n            Time.le from_src' from_src)\n        (EMPTY: forall from_src msg\n                          (GET: Memory.get loc to mem_src = Some (from_src, msg))\n                          ts (ITV: Interval.mem (from_src', from_src) ts),\n            Memory.get loc ts mem_src = None)\n        (MEMWF: memory_times_wf times mem_tgt)\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src prom_src loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src prom_src loc' ts' from' Message.reserve>>))\n\n        (CONSISTENT: forall to' from' val' released'\n                            (GETTGT: Memory.get loc to' prom_tgt' = Some (from', Message.concrete val' released')),\n            Time.lt to to')\n    :\n      exists prom_src0 mem_src0 mem_src1 prom_src2 mem_src2 self' extra_self',\n        (<<FUTURE0: reserve_future_memory prom_src mem_src prom_src0 mem_src0>>) /\\\n        (<<WRITE: Memory.write prom_src0 mem_src0 loc from_src' to val released prom_src0 mem_src1 Memory.op_kind_add>>) /\\\n        (<<FROM: Time.le from_tgt from_src'>>) /\\\n        (<<FUTURE1: reserve_future_memory prom_src0 mem_src1 prom_src2 mem_src2>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src2 mem_tgt>>) /\\\n        (<<PROMISE: sim_promise\n                      self' extra_self'\n                      prom_src2 prom_tgt'>>).\n  Proof.\n    hexploit Memory.remove_get0; try apply REMOVE. i. des.\n    rename GET into GETPROMTGT. dup GETPROMTGT.\n    apply MLETGT in GETPROMTGT0. rename GETPROMTGT0 into GETMEMTGT.\n\n    set (PROM := (sim_promise_contents PROMISE) loc to).\n    rewrite GETPROMTGT in PROM. inv PROM; ss.\n    symmetry in H0. rename H0 into GETPROMSRC.\n    dup GETPROMSRC. apply MLESRC in GETPROMSRC0. rename GETPROMSRC0 into GETMEMSRC.\n\n    set (MEM0 := (sim_memory_contents MEM) loc to).\n    rewrite GETMEMSRC in *. rewrite GETMEMTGT in *.\n    inv MEM0; try by (exfalso; apply NPROM; right; auto).\n\n    specialize (FROMSRC1 _ _ eq_refl).\n    specialize (EMPTY _ _ eq_refl).\n    assert (LB': lb_time (times loc) from_tgt from_src').\n    { eapply lb_time_lower; eauto. }\n\n    assert (NOTHER: ~ others loc to).\n    { intros OTHER. eapply EXCLUSIVE in OTHER. des. inv UNCH. clarify. }\n\n    hexploit ((sim_promise_extra PROMISE)); eauto. i. des.\n\n    hexploit (@Memory.remove_exists prom_src loc to to0 Message.reserve).\n    { eauto. }\n    intros [prom_src' REMOVEPROM0].\n    hexploit (@Memory.remove_exists_le prom_src mem_src loc to to0 Message.reserve); eauto.\n    intros [mem_src' REMOVEMEM0].\n    assert (PROMISE0: Memory.promise prom_src mem_src loc to to0 Message.reserve prom_src' mem_src' Memory.op_kind_cancel).\n    { econs; eauto. }\n\n    hexploit (@Memory.remove_exists prom_src' loc from_src to Message.reserve).\n    { erewrite Memory.remove_o; eauto. des_ifs.\n      ss. des; subst. timetac. }\n    intros [prom_src0 REMOVEPROM1].\n    hexploit (@Memory.remove_exists_le prom_src' mem_src' loc from_src to Message.reserve); eauto.\n    { eapply promise_memory_le; cycle 1; eauto. }\n    intros [mem_src0 REMOVEMEM1].\n    assert (PROMISE1: Memory.promise prom_src' mem_src' loc from_src to Message.reserve prom_src0 mem_src0 Memory.op_kind_cancel).\n    { econs; eauto. }\n\n    dup GETMEMTGT. eapply CLOSED in GETMEMTGT0. des.\n\n    hexploit (@Memory.add_exists mem_src0 loc from_src' to (Message.concrete val released)); eauto.\n    { ii. inv LHS. inv RHS. ss.\n      erewrite Memory.remove_o in GET2; eauto.\n      erewrite Memory.remove_o in GET2; eauto. des_ifs. guardH o. guardH o0.\n      destruct (Time.le_lt_dec x from_src).\n      { hexploit memory_get_disjoint_strong.\n        { eapply GET2. }\n        { eapply GETMEMSRC. }\n        i. des.\n        { subst. ss. destruct o; ss. }\n        { erewrite EMPTY in GET2; clarify. econs; ss.\n          eapply (@TimeFacts.lt_le_lt _ x); eauto.\n        }\n        { eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply FROM1. } etrans.\n          { eapply TO. }\n          { eauto. }\n        }\n      }\n      { hexploit Memory.get_disjoint.\n        { eapply GET2. }\n        { eapply GETMEMSRC. }\n        i. des; subst; ss.\n        { destruct o; ss. }\n        { eapply H; econs; eauto. }\n      }\n    }\n    { eapply (@TimeFacts.le_lt_lt _ from_src); eauto.\n      apply memory_get_ts_strong in GETMEMSRC. des; auto.\n      subst. erewrite BOTNONESRC in GETPROMSRC. clarify. }\n    intros [mem_src1 ADDMEM0].\n    hexploit (@Memory.add_exists_le prom_src0 mem_src0 loc from_src' to (Message.concrete val released)); eauto.\n    { eapply promise_memory_le; cycle 1; eauto.\n      eapply promise_memory_le; cycle 1; eauto. }\n    intros [prom_src1 ADDPROM0].\n    assert (PROMISE2: Memory.promise prom_src0 mem_src0 loc from_src' to (Message.concrete val released) prom_src1 mem_src1 Memory.op_kind_add).\n    { econs; eauto. i.\n      erewrite Memory.remove_o in GET1; eauto.\n      erewrite Memory.remove_o in GET1; eauto. des_ifs. guardH o. guardH o0.\n      hexploit memory_get_from_inj.\n      { eapply GET1. }\n      { eapply MLESRC. eapply GET. }\n      i. des; subst.\n      { destruct o0; ss. }\n      { erewrite BOTNONETGT in GETPROMTGT. clarify. }\n      { erewrite BOTNONETGT in GETPROMTGT. clarify. }\n    }\n\n    hexploit (@Memory.remove_exists prom_src1 loc from_src' to (Message.concrete val released)); eauto.\n    { eapply Memory.add_get0; eauto. }\n    intros [prom_src2 REMOVEPROM2].\n    hexploit (@MemoryFacts.add_remove_eq prom_src0 prom_src1 prom_src2); eauto.\n    i. subst.\n\n    assert (NOTHEREXTRA: forall from', ~ extra_others loc to0 from').\n    { intros from' OTHER. eapply EXCLUSIVEEXTRA in OTHER. des. inv OTHER. clarify. }\n\n    assert (WRITE: Memory.write prom_src0 mem_src0 loc from_src' to val released prom_src0 mem_src1 Memory.op_kind_add); eauto.\n\n    destruct (classic (exists to', <<EXTRA: extra_self loc to0 to'>>)) as [?|MINE].\n    { des. set (PROM1 := (sim_promise_contents PROMISE) loc to0).\n      inv PROM1; try by (exfalso; eapply NEXTRA1; eauto); ss.\n      rewrite GET in *. clarify.\n      assert (to' = to).\n      { hexploit (sim_memory_wf MEM).\n        { right. eapply EXTRA0. }\n        i. des. eapply UNIQUE. right. auto. } subst.\n      set (MEM1 := (sim_memory_contents MEM) loc to0).\n      inv MEM1; try by (exfalso; eapply NEXTRA1; right; eauto); ss.\n      dup GET. apply MLESRC in GET. rewrite GET in *. clarify.\n\n      exists prom_src0, mem_src0, mem_src1, prom_src0, mem_src1,\n      (fun loc' ts' => if loc_ts_eq_dec (loc', ts') (loc, to)\n                       then False else self loc' ts'),\n      (fun loc' ts' => if loc_ts_eq_dec (loc', ts') (loc, to0)\n                       then (fun _ => False) else extra_self loc' ts').\n      splits; eauto.\n      { econs; eauto. econs; eauto. econs; eauto. }\n      { econs. }\n      { econs.\n        { i. erewrite (@Memory.add_o mem_src1); eauto.\n          erewrite (@Memory.remove_o mem_src0); eauto.\n          erewrite (@Memory.remove_o mem_src'); eauto. des_ifs.\n          { ss. des; clarify. }\n          { ss. des; clarify. rewrite GETMEMTGT. econs 2; eauto.\n            { intros []; ss. }\n            { i. ss. }\n          }\n          { ss. des; clarify. rewrite <- H2. econs; eauto.\n            intros ? []; ss. eapply NOTHEREXTRA; eauto. }\n          { eapply (sim_memory_contents MEM). }\n        }\n        { i. des_ifs.\n          { ss. des; clarify.\n            destruct EXTRA2; ss. exfalso. eapply NOTHEREXTRA; eauto. }\n          { ss. des; clarify. exfalso. eapply o.\n            eapply sim_memory_extra_inj; eauto.\n            { eapply EXTRA2. }\n            { right. eauto. }\n          }\n          { ss. des; clarify.\n            destruct EXTRA2; ss. exfalso. eapply NOTHEREXTRA; eauto. }\n          { eapply (sim_memory_wf MEM). auto. }\n        }\n      }\n      { econs.\n        { i. erewrite (@Memory.remove_o prom_src0 prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_tgt'); eauto. des_ifs.\n          { ss. des; clarify. }\n          { ss. des; clarify. econs; eauto. }\n          { ss. des; clarify. rewrite <- H. econs; eauto. }\n          { apply (sim_promise_contents PROMISE). }\n        }\n        { i. des_ifs.\n          { ss. des; clarify. exfalso. eapply o.\n            eapply sim_memory_extra_inj; eauto.\n            { right. eapply EXTRA2. }\n            { right. eauto. }\n          }\n          { eapply (sim_promise_wf PROMISE); eauto. }\n        }\n        { i. des_ifs. guardH o. dup SELF.\n          eapply (sim_promise_extra PROMISE) in SELF. des.\n          exists to1. splits; auto.\n          erewrite (@Memory.remove_o prom_src0 prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n          { ss. des; clarify. exfalso.\n            set (PROM1:=(sim_promise_contents PROMISE) loc from_src).\n            inv PROM1; ss.\n            symmetry in H3. eapply Memory.remove_get1 in H3; eauto.\n            des; subst.\n            { timetac. }\n            { eapply CONSISTENT in GET3. eapply Time.lt_strorder.\n              transitivity from_src; eauto. }\n          }\n          { ss. des; clarify. destruct o; ss. }\n        }\n      }\n    }\n\n    { dup GET. eapply MLESRC in GET1.\n      assert (NOEXTRA: forall ts', ~ (extra_others \\\\3// extra_self) loc ts' to).\n      { ii. set (MEM1:=(sim_memory_contents MEM) loc ts').\n        inv MEM1; ss; try by (exfalso; eapply NEXTRA1; eauto).\n        hexploit ((sim_memory_wf MEM) loc from ts'); eauto. i. des.\n        eapply UNIQUE in H. subst.\n        hexploit memory_get_from_inj.\n        { symmetry. eapply H1. }\n        { eapply GET1. }\n        i. des.\n        { subst. destruct EXTRA.\n          { eapply EXCLUSIVEEXTRA in H. inv H. clarify. }\n          { eapply MINE; eauto. }\n        }\n        { subst. rewrite BOTNONESRC in GETPROMSRC. clarify. }\n        { subst. rewrite BOTNONESRC in GETPROMSRC. clarify. }\n      }\n\n      hexploit (@Memory.add_exists mem_src1 loc to to0 Message.reserve); eauto.\n      { i. erewrite Memory.add_o in GET2; eauto.\n        erewrite Memory.remove_o in GET2; eauto.\n        erewrite Memory.remove_o in GET2; eauto. des_ifs.\n        { ss. des; clarify. symmetry.\n          eapply Interval.disjoint_imm. }\n        { guardH o. guardH o0. hexploit Memory.get_disjoint.\n          { eapply MLESRC. eapply GET. }\n          { eapply GET2. }\n          i. des; auto. subst. destruct o0; ss. }\n      }\n      { econs. }\n      intros [mem_src2 ADDMEM1].\n      hexploit (@Memory.add_exists_le prom_src0 mem_src1 loc to to0 Message.reserve); eauto.\n      { eapply write_memory_le; cycle 1; eauto.\n        eapply promise_memory_le; cycle 1; eauto.\n        eapply promise_memory_le; cycle 1; eauto. }\n      intros [prom_src2 ADDPROM1].\n\n      assert (PROMISE3: Memory.promise prom_src0 mem_src1 loc to to0 Message.reserve prom_src2 mem_src2 Memory.op_kind_add).\n      { econs; eauto. i. clarify. }\n\n      exists prom_src0, mem_src0, mem_src1, prom_src2, mem_src2,\n      (fun loc' ts' => if loc_ts_eq_dec (loc', ts') (loc, to)\n                       then False else self loc' ts'), extra_self.\n      splits; eauto.\n      { econs; eauto. econs; eauto. econs; eauto. }\n      { econs; eauto. econs; eauto. }\n      { econs.\n        { i. erewrite (@Memory.add_o mem_src2); eauto.\n          erewrite (@Memory.add_o mem_src1); eauto.\n          erewrite (@Memory.remove_o mem_src0); eauto.\n          erewrite (@Memory.remove_o mem_src'); eauto. des_ifs.\n          { ss. des; clarify. timetac. }\n          { ss. des; clarify. rewrite GETMEMTGT. econs 2; eauto.\n            { intros []; ss. }\n            { i. ss. }\n          }\n          { ss. des; clarify. rewrite <- GET1.\n            eapply (sim_memory_contents MEM). }\n          { eapply (sim_memory_contents MEM). }\n        }\n        { i. des_ifs.\n          { ss. des; clarify. exfalso. eapply NOEXTRA; eauto. }\n          { eapply (sim_memory_wf MEM). auto. }\n        }\n      }\n      { econs.\n        { i. erewrite (@Memory.add_o prom_src2); eauto.\n          erewrite (@Memory.remove_o prom_src0 prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_tgt'); eauto. des_ifs.\n          { ss. des; clarify. timetac. }\n          { ss. des; clarify. econs; eauto. }\n          { ss. des; clarify. rewrite <- GET.\n            apply (sim_promise_contents PROMISE). }\n          { apply (sim_promise_contents PROMISE). }\n        }\n        { i. des_ifs.\n          { ss. des; clarify. exfalso.\n            eapply NOEXTRA. right. eauto. }\n          { eapply (sim_promise_wf PROMISE); eauto. }\n        }\n        { i. des_ifs. guardH o. dup SELF.\n          eapply (sim_promise_extra PROMISE) in SELF. des.\n          exists to1. splits; auto.\n          erewrite (@Memory.add_o prom_src2); eauto.\n          erewrite (@Memory.remove_o prom_src0 prom_src'); eauto.\n          erewrite (@Memory.remove_o prom_src'); eauto. des_ifs.\n          { ss. des; clarify. }\n          { ss. des; clarify. exfalso.\n            set (PROM1:=(sim_promise_contents PROMISE) loc from_src).\n            inv PROM1; ss.\n            symmetry in H. eapply Memory.remove_get1 in H; eauto.\n            des; subst.\n            { timetac. }\n            { eapply CONSISTENT in GET3. eapply Time.lt_strorder.\n              transitivity from_src; eauto. }\n          }\n        }\n      }\n    }\n  Qed.\n\n\n  Lemma sim_fulfill_forget_write others self extra_others extra_self\n        prom_src prom_tgt mem_src mem_tgt prom_tgt'\n        loc from_tgt to val released\n        (LOC: L loc)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (MLETGT: Memory.le prom_tgt mem_tgt)\n        (MLESRC: Memory.le prom_src mem_src)\n        (FIN: Memory.finite prom_src)\n        (BOTNONESRC: Memory.bot_none prom_src)\n        (BOTNONETGT: Memory.bot_none prom_tgt)\n        (PROMISE: sim_promise self extra_self prom_src prom_tgt)\n        (REMOVE: Memory.remove prom_tgt loc from_tgt to (Message.concrete val released) prom_tgt')\n        (CLOSED: Memory.closed mem_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt)\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src prom_src loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src prom_src loc' ts' from' Message.reserve>>))\n\n        (CONSISTENT: forall to' from' val' released'\n                            (GETTGT: Memory.get loc to' prom_tgt' = Some (from', Message.concrete val' released')),\n            Time.lt to to')\n    :\n      exists from_src prom_src0 mem_src0 mem_src1 prom_src2 mem_src2 self' extra_self',\n        (<<FUTURE0: reserve_future_memory prom_src mem_src prom_src0 mem_src0>>) /\\\n        (<<WRITE: Memory.write prom_src0 mem_src0 loc from_src to val released prom_src0 mem_src1 Memory.op_kind_add>>) /\\\n        (<<FROM: Time.le from_tgt from_src>>) /\\\n        (<<FUTURE1: reserve_future_memory prom_src0 mem_src1 prom_src2 mem_src2>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src2 mem_tgt>>) /\\\n        (<<PROMISE: sim_promise\n                      self' extra_self'\n                      prom_src2 prom_tgt'>>).\n  Proof.\n    hexploit Memory.remove_get0; try apply REMOVE. i. des.\n    rename GET into GETPROMTGT. dup GETPROMTGT.\n    apply MLETGT in GETPROMTGT0. rename GETPROMTGT0 into GETMEMTGT.\n\n    set (PROM := (sim_promise_contents PROMISE) loc to).\n    rewrite GETPROMTGT in PROM. inv PROM; ss.\n    symmetry in H0. rename H0 into GETPROMSRC.\n    dup GETPROMSRC. apply MLESRC in GETPROMSRC0. rename GETPROMSRC0 into GETMEMSRC.\n\n    set (MEM0 := (sim_memory_contents MEM) loc to).\n    rewrite GETMEMSRC in *. rewrite GETMEMTGT in *.\n    inv MEM0; try by (exfalso; apply NPROM; right; auto).\n\n    exists from_src. eapply sim_fulfill_forget; eauto.\n    { i. clarify. refl. }\n    { i. clarify. inv ITV. ss. timetac. }\n  Qed.\n\n  Lemma sim_fulfill_forget_update others self extra_others extra_self\n        prom_src prom_tgt mem_src mem_tgt prom_tgt'\n        loc from_tgt to val released\n        (LOC: L loc)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (MLETGT: Memory.le prom_tgt mem_tgt)\n        (MLESRC: Memory.le prom_src mem_src)\n        (FIN: Memory.finite prom_src)\n        (BOTNONESRC: Memory.bot_none prom_src)\n        (BOTNONETGT: Memory.bot_none prom_tgt)\n        (PROMISE: sim_promise self extra_self prom_src prom_tgt)\n        (REMOVE: Memory.remove prom_tgt loc from_tgt to (Message.concrete val released) prom_tgt')\n        (CLOSED: Memory.closed mem_tgt)\n        (NOREAD: ~ others loc from_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt)\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src prom_src loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src prom_src loc' ts' from' Message.reserve>>))\n\n        (CONSISTENT: forall to' from' val' released'\n                            (GETTGT: Memory.get loc to' prom_tgt' = Some (from', Message.concrete val' released')),\n            Time.lt to to')\n    :\n      exists prom_src0 mem_src0 mem_src1 prom_src2 mem_src2 self' extra_self',\n        (<<FUTURE0: reserve_future_memory prom_src mem_src prom_src0 mem_src0>>) /\\\n        (<<WRITE: Memory.write prom_src0 mem_src0 loc from_tgt to val released prom_src0 mem_src1 Memory.op_kind_add>>) /\\\n        (<<FROM: Time.le from_tgt from_tgt>>) /\\\n        (<<FUTURE1: reserve_future_memory prom_src0 mem_src1 prom_src2 mem_src2>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src2 mem_tgt>>) /\\\n        (<<PROMISE: sim_promise\n                      self' extra_self'\n                      prom_src2 prom_tgt'>>).\n  Proof.\n    hexploit Memory.remove_get0; try apply REMOVE. i. des.\n    rename GET into GETPROMTGT. dup GETPROMTGT.\n    apply MLETGT in GETPROMTGT0. rename GETPROMTGT0 into GETMEMTGT.\n\n    set (PROM := (sim_promise_contents PROMISE) loc to).\n    rewrite GETPROMTGT in PROM. inv PROM; ss.\n    symmetry in H0. rename H0 into GETPROMSRC.\n    dup GETPROMSRC. apply MLESRC in GETPROMSRC0. rename GETPROMSRC0 into GETMEMSRC.\n\n    set (MEM0 := (sim_memory_contents MEM) loc to).\n    rewrite GETMEMSRC in *. rewrite GETMEMTGT in *.\n    inv MEM0; try by (exfalso; apply NPROM; right; auto).\n\n    eapply sim_fulfill_forget; eauto.\n    { refl. }\n    { i. clarify. }\n    { i. clarify.\n      destruct (Memory.get loc ts mem_src) eqn:EQ; auto. destruct p.\n      eapply sim_memory_get_larger in EQ; eauto. des.\n      { inv ITV. ss. hexploit Memory.get_disjoint.\n        { eapply GETTGT. }\n        { eapply GETMEMTGT. }\n        i. des; clarify.\n        { apply memory_get_ts_strong in GET. des.\n          { subst. erewrite BOTNONESRC in GETPROMSRC. clarify. }\n          { timetac. }\n        }\n        { exfalso. eapply (H ts); econs; ss.\n          { apply memory_get_ts_strong in GETTGT. des; auto.\n            subst. exfalso. eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n            { eapply FROM0. }\n            { eapply Time.bot_spec. }\n          }\n          { refl. }\n          { etrans; eauto. eapply memory_get_ts_le; eauto. }\n        }\n      }\n      { exfalso. set (MEM1:=(sim_memory_contents MEM) loc t). inv MEM1; ss.\n        hexploit ((sim_memory_wf MEM) loc t ts); eauto. i. des. inv ITV; ss.\n        hexploit memory_get_disjoint_strong.\n        { symmetry. eapply H. }\n        { eapply GETMEMTGT. }\n        i. des; clarify.\n        { rewrite GET in *. clarify.\n          eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply TS. } etrans.\n          { eapply TO. }\n          { eapply memory_get_ts_le; eauto. }\n        }\n        { exploit LB1.\n          { instantiate (1:=from_tgt).\n            apply MEMWF in GETMEMTGT. des. auto. }\n          { destruct TS0; auto. inv H1. exfalso. destruct PROM1; eauto.\n            set (PROM1:=(sim_promise_contents PROMISE) loc from_tgt). inv PROM1; ss.\n            symmetry in H4. eapply Memory.remove_get1 in H4; eauto. des.\n            { subst. timetac. }\n            { eapply CONSISTENT in GET2. eapply Time.lt_strorder.\n              etrans; [eapply GET2|]; eauto. }\n          }\n          { i. eapply Time.lt_strorder. etrans.\n            { eapply FROM1. } eauto.\n          }\n        }\n        { eapply Time.lt_strorder. eapply TimeFacts.lt_le_lt.\n          { eapply TS1. } etrans.\n          { left. eapply TS. } etrans.\n          { eapply TO. }\n          { eapply memory_get_ts_le; eauto. }\n        }\n      }\n    }\n  Qed.\n\n\n  Lemma sim_promise_step_forget others self extra_others extra_self\n        mem_src mem_tgt mem_tgt' lc_src lc_tgt lc_tgt' loc from to msg kind\n        (LOC: L loc)\n        (STEPTGT: Local.promise_step lc_tgt mem_tgt loc from to msg lc_tgt' mem_tgt' kind)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (LOCAL: sim_local self extra_self lc_src lc_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LCSRC: Local.wf lc_src mem_src)\n        (LCTGT: Local.wf lc_tgt mem_tgt)\n\n        (CLOSED: Memory.closed mem_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n    :\n      exists self' extra_self' prom_src' mem_src',\n        (<<FUTURE: reserve_future_memory (Local.promises lc_src) mem_src prom_src' mem_src'>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src' mem_tgt'>>) /\\\n        (<<SIM: sim_local self' extra_self' (Local.mk (Local.tview lc_src) prom_src') lc_tgt'>>)\n  .\n  Proof.\n    inv STEPTGT. inv LCSRC. inv LCTGT. inv LOCAL.\n    hexploit sim_promise_forget; ss; eauto. i. des. esplits; eauto.\n  Qed.\n\n\n  Lemma sim_write_step_forget others self extra_others extra_self\n        mem_src mem_tgt mem_tgt' lc_src lc_tgt lc_tgt' loc from to kind sc sc' val released ord\n        (LOC: L loc)\n        (STEPTGT: Local.write_step lc_tgt sc mem_tgt loc from to val None released ord lc_tgt' sc' mem_tgt' kind)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (LOCAL: sim_local self extra_self lc_src lc_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LCSRC: Local.wf lc_src mem_src)\n        (LCTGT: Local.wf lc_tgt mem_tgt)\n\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n\n        (CLOSED: Memory.closed mem_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n    :\n      exists self' extra_self' from' lc_src' prom_src0 mem_src0 mem_src1 prom_src' mem_src',\n        (<<FUTURE0: reserve_future_memory (Local.promises lc_src) mem_src prom_src0 mem_src0>>) /\\\n        (<<WRITE: Local.write_step (Local.mk (Local.tview lc_src) prom_src0) sc mem_src0 loc from' to val None released ord lc_src' sc' mem_src1 Memory.op_kind_add>>) /\\\n        (<<FROM: Time.le from from'>>) /\\\n        (<<FUTURE1: reserve_future_memory (Local.promises lc_src') mem_src1 prom_src' mem_src'>>) /\\\n\n        (<<MEM: sim_memory (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src' mem_tgt'>>) /\\\n        (<<SIM: sim_local self' extra_self' (Local.mk (Local.tview lc_src') prom_src') lc_tgt'>>)\n  .\n  Proof.\n    inv STEPTGT. inv LCSRC. inv LCTGT. inv LOCAL. inv WRITE. ss.\n    hexploit Memory.promise_future; try apply PROMISE; eauto.\n    { econs. inv PROMISE; try by (eapply TViewFacts.op_closed_released; eauto). } i. des.\n\n    hexploit sim_promise_forget; ss; eauto. i. des.\n    hexploit reserve_future_memory_future; try apply STEPSRC; eauto.\n    i. des. inv LOCAL. ss.\n\n    hexploit sim_fulfill_forget_write; try apply PROMISE0; eauto.\n    { i. eapply EXCLUSIVE in OTHER. des.\n      eapply reserve_future_memory_unchangable in UNCH; eauto. }\n    { i. eapply EXCLUSIVEEXTRA in OTHER. des.\n      eapply reserve_future_memory_unchangable in OTHER; eauto. }\n    { i. eapply CONSISTENT in GETTGT. ss.\n      eapply TimeFacts.le_lt_lt; [|eapply GETTGT].\n      unfold TimeMap.join, TimeMap.singleton. etrans; [|eapply Time.join_r].\n      setoid_rewrite LocFun.add_spec_eq. refl. }\n\n    i. des.\n    eexists self'0, extra_self'0, from_src, (Local.mk _ prom_src0), prom_src0, mem_src0, mem_src1, prom_src2, mem_src2.\n    splits; eauto.\n    { eapply reserve_future_memory_trans; eauto. }\n    { econs; eauto; ss. ii. des_ifs.\n      eapply reserve_future_concrete_same_promise2 in GET; eauto.\n      eapply reserve_future_concrete_same_promise2 in GET; eauto.\n      set (PROM:= (sim_promise_contents PROMS) loc t).\n      rewrite GET in *. inv PROM; ss.\n    }\n    { econs; eauto. }\n  Qed.\n\n  Lemma sim_update_step_forget others self extra_others extra_self\n        mem_src mem_tgt mem_tgt' lc_src lc_tgt lc_tgt' loc from to kind sc sc' val releasedm released ord\n        (LOC: L loc)\n        (STEPTGT: Local.write_step lc_tgt sc mem_tgt loc from to val releasedm released ord lc_tgt' sc' mem_tgt' kind)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (LOCAL: sim_local self extra_self lc_src lc_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LCSRC: Local.wf lc_src mem_src)\n        (LCTGT: Local.wf lc_tgt mem_tgt)\n\n        (NOREAD: ~ (others \\\\2// self) loc from)\n\n        (RELEASEDMCLOSED: Memory.closed_opt_view releasedm mem_tgt)\n        (RELEASEDMWF: View.opt_wf releasedm)\n\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n\n        (CLOSED: Memory.closed mem_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n    :\n      exists self' extra_self' lc_src' prom_src0 mem_src0 mem_src1 prom_src' mem_src',\n        (<<FUTURE0: reserve_future_memory (Local.promises lc_src) mem_src prom_src0 mem_src0>>) /\\\n        (<<WRITE: Local.write_step (Local.mk (Local.tview lc_src) prom_src0) sc mem_src0 loc from to val releasedm released ord lc_src' sc' mem_src1 Memory.op_kind_add>>) /\\\n        (<<FUTURE1: reserve_future_memory (Local.promises lc_src') mem_src1 prom_src' mem_src'>>) /\\\n\n        (<<MEM: sim_memory (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src' mem_tgt'>>) /\\\n        (<<SIM: sim_local self' extra_self' (Local.mk (Local.tview lc_src') prom_src') lc_tgt'>>)\n  .\n  Proof.\n    inv STEPTGT. inv LCSRC. inv LCTGT. inv LOCAL. inv WRITE. ss.\n    hexploit Memory.promise_future; try apply PROMISE; eauto.\n    { econs. inv PROMISE; try by (eapply TViewFacts.op_closed_released; eauto). } i. des.\n\n    hexploit sim_promise_forget; ss; eauto. i. des.\n    hexploit reserve_future_memory_future; try apply STEPSRC; eauto.\n    i. des. inv LOCAL. ss.\n\n    hexploit sim_fulfill_forget_update; try apply PROMISE0; eauto.\n    { ii. eapply NOREAD. left. eauto. }\n    { i. eapply EXCLUSIVE in OTHER. des.\n      eapply reserve_future_memory_unchangable in UNCH; eauto. }\n    { i. eapply EXCLUSIVEEXTRA in OTHER. des.\n      eapply reserve_future_memory_unchangable in OTHER; eauto. }\n    { i. eapply CONSISTENT in GETTGT. ss.\n      eapply TimeFacts.le_lt_lt; [|eapply GETTGT].\n      unfold TimeMap.join, TimeMap.singleton. etrans; [|eapply Time.join_r].\n      setoid_rewrite LocFun.add_spec_eq. refl. }\n\n    i. des.\n    eexists self'0, extra_self'0, (Local.mk _ prom_src0), prom_src0, mem_src0, mem_src1, prom_src2, mem_src2.\n    splits; eauto.\n    { eapply reserve_future_memory_trans; eauto. }\n    { econs; eauto; ss. ii. des_ifs.\n      eapply reserve_future_concrete_same_promise2 in GET; eauto.\n      eapply reserve_future_concrete_same_promise2 in GET; eauto.\n      set (PROM:= (sim_promise_contents PROMS) loc t).\n      rewrite GET in *. inv PROM; ss.\n    }\n    { econs; eauto. }\n  Qed.\n\n\n  Lemma sim_thread_step_silent' others self extra_others extra_self\n        lang st lc_src lc_tgt sc mem_src mem_tgt pf e_tgt\n        st' lc_tgt' sc' mem_tgt' views views'\n        (STEPTGT: @JThread.step lang pf e_tgt (Thread.mk _ st lc_tgt sc mem_tgt) (Thread.mk _ st' lc_tgt' sc' mem_tgt') views views')\n        (NOREAD: no_read_msgs others e_tgt)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LOCALSRC: Local.wf lc_src mem_src)\n        (LOCALTGT: Local.wf lc_tgt mem_tgt)\n        (SIM: sim_local self extra_self lc_src lc_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views loc ts))\n\n        (EVENT: ThreadEvent.get_machine_event e_tgt = MachineEvent.silent)\n    :\n      exists tr self' extra_self' lc_src' mem_src',\n        (<<STEPSRC: Trace.steps tr (Thread.mk _ st lc_src sc mem_src) (Thread.mk _ st' lc_src' sc' mem_src')>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src' mem_tgt'>>) /\\\n        (<<SIM: sim_local self' extra_self' lc_src' lc_tgt'>>) /\\\n        (<<TRACE: sim_trace tr (Some (lc_tgt, e_tgt))>>)\n  .\n  Proof.\n    inv STEPTGT. inv STEP; ss.\n    - dup STEP0. inv STEP0.\n      assert (SEMICLOSED: semi_closed_message msg mem_src loc to).\n      { destruct msg; econs. hexploit PROMISE; eauto.\n        i. inv H; econs.\n        destruct (classic (views' loc to = views loc to)).\n        - rewrite H in *.\n          inv MEMSRC. eapply joined_view_semi_closed in JOINED0; eauto.\n        - exploit VIEWSLE; eauto. i. des. ss.\n          inv MEMSRC. eapply joined_view_semi_closed; cycle 1; eauto.\n          rewrite VIEW. econs.\n          + eapply semi_closed_view_join.\n            * eapply closed_view_semi_closed.\n              inv LOCALSRC. inv LOCAL. inv SIM. eapply TVIEW_CLOSED.\n            * eapply semi_closed_view_singleton; eauto.\n          + eapply List.Forall_forall.\n            i. eapply all_join_views_in_iff in H0. des. subst.\n            eapply List.Forall_forall in IN; eauto. ss.\n            erewrite View.join_comm. eapply join_singleton_semi_closed_view; eauto.\n            eapply memory_get_ts_le in GET. auto.\n      }\n      destruct (classic (L loc)).\n      + hexploit sim_promise_step_forget; eauto. i. des.\n        destruct lc_src. ss. exploit reserve_future_memory_steps; eauto. i. des.\n        eexists _, self', extra_self', (Local.mk _ _), mem_src'. splits; eauto.\n        * econs 3; ss.\n          eapply reserving_r_sim_trace with (tr_src:=[]) in RESERVING; eauto.\n      + hexploit sim_promise_step_normal; eauto.\n        i. des.\n        eexists [(_, ThreadEvent.promise loc from to msg kind)],\n        self, extra_self, lc_src', mem_src'.\n        splits; ss.\n        * econs 2; [|econs 1|ss]. econs 1. econs; eauto.\n        * econs 2; ss.\n          { ii. clarify. }\n          { econs; eauto. }\n          { eapply sim_local_tview_le; eauto. }\n    - inv STEP0. inv LOCAL.\n      + eexists [(_, ThreadEvent.silent)], self, extra_self, lc_src, mem_src. splits; ss.\n        * econs 2; [|econs 1|ss]. econs 2. econs; eauto.\n        * econs 2; ss. eapply sim_local_tview_le; eauto.\n      + exploit sim_read_step; eauto. i. des.\n        eexists [(_, ThreadEvent.read loc ts val released ord)],\n        self, extra_self, lc_src', mem_src. splits; ss.\n        * econs 2; [|econs 1|ss]. econs 2. econs; eauto.\n        * econs 2; ss. eapply sim_local_tview_le; eauto.\n      + destruct (classic (L loc)).\n        * exploit sim_write_step_forget; eauto. i. des.\n          destruct lc_src, lc_src'. ss.\n          eapply reserve_future_memory_steps in FUTURE0. des.\n          eapply reserve_future_memory_steps in FUTURE1. des.\n          esplits; eauto.\n          { eapply Trace.steps_app.\n            { eapply STEPS. }\n            eapply Trace.steps_app.\n            { econs 2; [|econs 1|ss]. econs 2. econs; cycle 1.\n              - econs 3. eauto.\n              - ss. eauto. }\n            eauto.\n          }\n          { eapply reserving_l_sim_trace; eauto.\n            eapply reserving_r_sim_trace; eauto.\n            econs 2; ss; eauto.\n            eapply sim_local_tview_le in SIM; eauto. }\n        * hexploit sim_write_step_normal; eauto. i. des.\n          eexists [(_, ThreadEvent.write loc from to val _ ord)],\n          self, extra_self, lc_src', mem_src'.\n          splits; ss.\n          { econs 2; [|econs 1|ss]. econs 2. econs; eauto. }\n          { econs 2; ss. eapply sim_local_tview_le; eauto. }\n      + exploit sim_read_step; eauto.\n        { eapply PromiseConsistent.write_step_promise_consistent; eauto. } i. des.\n        exploit Local.read_step_future; try apply LOCAL1; eauto. i. des.\n        exploit Local.read_step_future; try apply STEPSRC; eauto. i. des.\n        dup STEPSRC. inv STEPSRC. ss.\n        destruct (classic (L loc)).\n        * hexploit sim_update_step_forget; eauto. i. des. ss.\n          destruct lc_src, lc_src'.\n          eapply reserve_future_read_commute in STEPSRC0; eauto.\n          eapply reserve_future_memory_steps in FUTURE0. des.\n          eapply reserve_future_memory_steps in FUTURE1. des.\n          esplits; eauto.\n          { eapply Trace.steps_app.\n            { eapply STEPS. }\n            eapply Trace.steps_app.\n            { econs 2; [|econs 1|ss]. econs 2. econs; cycle 1.\n              - econs 4; eauto.\n              - ss. eauto. }\n            eauto.\n          }\n          { eapply reserving_l_sim_trace; eauto.\n            eapply reserving_r_sim_trace; eauto.\n            econs 2; ss; eauto. eapply sim_local_tview_le in SIM; eauto. }\n        * hexploit sim_write_step_normal; eauto. i. des.\n          eexists [(_, ThreadEvent.update loc tsr tsw valr valw releasedr releasedw ordr ordw)],\n          self, extra_self, lc_src', mem_src'. splits; ss.\n          { econs 2; [|econs 1|ss]. econs 2. econs; eauto. }\n          { econs 2; ss. eapply sim_local_tview_le; eauto. }\n      + exploit sim_fence_step; eauto. i. des.\n        eexists [(_, ThreadEvent.fence ordr ordw)],\n        self, extra_self, lc_src', mem_src. splits; ss.\n        * econs 2; [|econs 1|ss]. econs 2. econs; eauto.\n        * econs 2; ss. eapply sim_local_tview_le in SIM; eauto.\n      + ss.\n      + ss.\n  Qed.\n\n  Inductive sim_local_strong\n            (self: Loc.t -> Time.t -> Prop)\n            (extra extra_all: Loc.t -> Time.t -> Time.t -> Prop)\n    :\n      forall (lc_src lc_tgt: Local.t), Prop :=\n  | sim_local_strong_intro\n      tvw prom_src prom_tgt\n      (PROMS: sim_promise_strong self extra extra_all prom_src prom_tgt)\n    :\n      sim_local_strong self extra extra_all (Local.mk tvw prom_src) (Local.mk tvw prom_tgt)\n  .\n  Hint Constructors sim_local_strong.\n\n  Lemma sim_local_strong_sim_local\n        self extra extra_all lc_src lc_tgt\n        (SIM: sim_local_strong self extra extra_all lc_src lc_tgt)\n    :\n      sim_local self extra lc_src lc_tgt.\n  Proof.\n    inv SIM. econs; eauto. eapply sim_promise_strong_sim_promise; eauto.\n  Qed.\n\n  Lemma sim_thread_step_silent others self extra_others extra_self\n        lang st lc_src lc_tgt sc mem_src mem_tgt pf e_tgt\n        st' lc_tgt' sc' mem_tgt' views views'\n        (STEPTGT: @JThread.step lang pf e_tgt (Thread.mk _ st lc_tgt sc mem_tgt) (Thread.mk _ st' lc_tgt' sc' mem_tgt') views views')\n        (NOREAD: no_read_msgs others e_tgt)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LOCALSRC: Local.wf lc_src mem_src)\n        (LOCALTGT: Local.wf lc_tgt mem_tgt)\n        (SIM: sim_local self extra_self lc_src lc_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views loc ts))\n\n        (EVENT: ThreadEvent.get_machine_event e_tgt = MachineEvent.silent)\n    :\n      exists tr self' extra_self' lc_src' mem_src',\n        (<<STEPSRC: Trace.steps tr (Thread.mk _ st lc_src sc mem_src) (Thread.mk _ st' lc_src' sc' mem_src')>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self') (extra_others \\\\3// extra_self') mem_src' mem_tgt'>>) /\\\n        (<<SIM: sim_local_strong self' extra_self' (extra_others \\\\3// extra_self') lc_src' lc_tgt'>>) /\\\n        (<<TRACE: sim_trace tr (Some (lc_tgt, e_tgt))>>) /\\\n        (<<JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src' loc ts) (views' loc ts)>>)\n  .\n  Proof.\n    hexploit sim_thread_step_silent'; eauto. i. des.\n    exploit Thread.step_future.\n    { inv STEPTGT. eauto. } all: ss. i. des.\n    exploit Trace.steps_future; eauto. i. des. ss.\n    exploit sim_promise_weak_strengthen; eauto.\n    { eapply WF2. }\n    { eapply WF0. }\n    { eapply WF0. }\n    { eapply WF0. }\n    { inv SIM0. ss. }\n    i. des. destruct lc_src'. ss.\n    exploit reserve_future_memory_steps; eauto. i. des.\n    exists (tr++tr0). esplits; eauto.\n    { eapply Trace.steps_trans; eauto. }\n    { inv SIM0. econs; eauto. }\n    { eapply reserving_r_sim_trace; eauto. }\n    assert (JOINED0: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src' loc ts) (views' loc ts)).\n    { inv STEPTGT. ss.\n      i. destruct (classic (views' loc ts = views loc ts)).\n      { rewrite H.\n        eapply List.Forall_impl; eauto.\n        i. ss. eapply semi_closed_view_future; eauto. eapply Memory.future_future_weak; eauto. }\n      { hexploit VIEWSLE; eauto. i. des.\n        set (MEM2:=(sim_memory_contents MEM0) loc ts). rewrite GET in MEM2. inv MEM2; ss.\n        { rewrite VIEW. econs.\n          - eapply closed_view_semi_closed. eapply Memory.join_closed_view.\n            + inv WF0. inv SIM0. ss. eapply TVIEW_CLOSED.\n            + inv CLOSED0. eapply Memory.singleton_ur_closed_view; eauto.\n          - apply List.Forall_forall.\n            i. eapply all_join_views_in_iff in H0. des. subst.\n            eapply List.Forall_forall in IN; eauto. ss.\n            eapply semi_closed_view_future in IN.\n            2: { eapply Memory.future_future_weak; eauto. }\n            erewrite View.join_comm. eapply join_singleton_semi_closed_view; eauto.\n            eapply memory_get_ts_le in GET. ss.\n        }\n        { rewrite VIEW. econs.\n          - erewrite View.join_comm. eapply join_singleton_semi_closed_view.\n            + instantiate (1:=Time.bot). eapply closed_view_semi_closed.\n              inv WF0. inv SIM0. ss. eapply TVIEW_CLOSED.\n            + eapply Time.bot_spec.\n          - apply List.Forall_forall.\n            i. eapply all_join_views_in_iff in H0. des. subst.\n            eapply List.Forall_forall in IN; eauto. ss.\n            eapply semi_closed_view_future in IN.\n            2: { eapply Memory.future_future_weak; eauto. }\n            erewrite View.join_comm. eapply join_singleton_semi_closed_view; eauto.\n            eapply memory_get_ts_le in GET. ss.\n        }\n      }\n    }\n    { i. eapply List.Forall_impl; eauto.\n      i. ss. eapply semi_closed_view_future in H; eauto.\n      eapply Memory.future_future_weak; eauto.\n      eapply reserve_future_future; eauto. }\n  Qed.\n\n  Lemma sim_thread_step_event' others self extra_others extra_self\n        lang st lc_src lc_tgt sc mem_src mem_tgt pf e_tgt\n        st' lc_tgt' sc' mem_tgt' views views'\n        (STEPTGT: @JThread.step lang pf e_tgt (Thread.mk _ st lc_tgt sc mem_tgt) (Thread.mk _ st' lc_tgt' sc' mem_tgt') views views')\n        (NOREAD: no_read_msgs others e_tgt)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LOCALSRC: Local.wf lc_src mem_src)\n        (LOCALTGT: Local.wf lc_tgt mem_tgt)\n        (SIM: sim_local self extra_self lc_src lc_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views loc ts))\n\n        (EVENT: ThreadEvent.get_machine_event e_tgt <> MachineEvent.silent)\n    :\n      exists lc_src',\n        (<<STEPSRC: Thread.step pf e_tgt (Thread.mk _ st lc_src sc mem_src) (Thread.mk _ st' lc_src' sc' mem_src)>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt'>>) /\\\n        (<<SIM: sim_local self extra_self lc_src' lc_tgt'>>)\n  .\n  Proof.\n    inv STEPTGT. inv STEP.\n    - inv STEP0; ss.\n    - inv STEP0; ss. inv LOCAL; ss.\n      + exploit sim_fence_step; eauto. i. des. esplits; eauto.\n      + exploit sim_failure_step; eauto. i. des. esplits; eauto.\n  Qed.\n\n  Lemma sim_thread_step_event others self extra_others extra_self\n        lang st lc_src lc_tgt sc mem_src mem_tgt pf e_tgt\n        st' lc_tgt' sc' mem_tgt' views views'\n        (STEPTGT: @JThread.step lang pf e_tgt (Thread.mk _ st lc_tgt sc mem_tgt) (Thread.mk _ st' lc_tgt' sc' mem_tgt') views views')\n        (NOREAD: no_read_msgs others e_tgt)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LOCALSRC: Local.wf lc_src mem_src)\n        (LOCALTGT: Local.wf lc_tgt mem_tgt)\n        (SIM: sim_local self extra_self lc_src lc_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views loc ts))\n\n        (EVENT: ThreadEvent.get_machine_event e_tgt <> MachineEvent.silent)\n    :\n      exists lc_src',\n        (<<STEPSRC: Thread.step pf e_tgt (Thread.mk _ st lc_src sc mem_src) (Thread.mk _ st' lc_src' sc' mem_src)>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt'>>) /\\\n        (<<SIM: sim_local self extra_self lc_src' lc_tgt'>>) /\\\n        (<<JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views' loc ts)>>)\n  .\n  Proof.\n    hexploit sim_thread_step_event'; eauto. i. des. esplits; eauto.\n    hexploit Thread.step_future; eauto. i. des. ss.\n    inv STEPTGT. ss.\n    i. destruct (classic (views' loc ts = views loc ts)).\n    { rewrite H.\n      eapply List.Forall_impl; eauto.\n      i. ss. }\n    { hexploit VIEWSLE; eauto. i. des.\n      set (MEM1:=(sim_memory_contents MEM0) loc ts). rewrite GET in MEM1. inv MEM1; ss.\n      { rewrite VIEW. econs.\n        - erewrite View.join_comm. eapply join_singleton_semi_closed_view.\n          + eapply closed_view_semi_closed.\n            inv WF2. inv SIM0. ss. eapply TVIEW_CLOSED.\n          + eapply Time.bot_spec.\n        - apply List.Forall_forall.\n          i. eapply all_join_views_in_iff in H0. des. subst.\n          erewrite View.join_comm. eapply join_singleton_semi_closed_view.\n          + eapply List.Forall_forall in IN; eauto. ss. eauto.\n          + eapply memory_get_ts_le in GET. auto.\n      }\n      { rewrite VIEW. econs.\n        - erewrite View.join_comm. eapply join_singleton_semi_closed_view.\n          + eapply closed_view_semi_closed.\n            inv WF2. inv SIM0. ss. eapply TVIEW_CLOSED.\n          + eapply Time.bot_spec.\n        - apply List.Forall_forall.\n          i. eapply all_join_views_in_iff in H0. des. subst.\n          erewrite View.join_comm. eapply join_singleton_semi_closed_view.\n          + eapply List.Forall_forall in IN; eauto. ss. eauto.\n          + eapply memory_get_ts_le in GET. auto.\n      }\n    }\n  Qed.\n\n  Lemma sim_fence_step_strong self extra extra_all lc_src lc_tgt sc ordr ordw\n        sc' lc_tgt'\n        (STEPTGT: Local.fence_step lc_tgt sc ordr ordw lc_tgt' sc')\n        (LOCAL: sim_local_strong self extra extra_all lc_src lc_tgt)\n    :\n      exists lc_src',\n        (<<STEPSRC: Local.fence_step lc_src sc ordr ordw lc_src' sc'>>) /\\\n        (<<SIM: sim_local_strong self extra extra_all lc_src' lc_tgt'>>)\n  .\n  Proof.\n    inv LOCAL. inv STEPTGT. esplits.\n    - econs; ss; eauto.\n      + ii. set (PROM:= (sim_promise_strong_contents PROMS) loc t).\n        rewrite GET in *. inv PROM; ss.\n        exploit RELEASE; eauto.\n      + i. eapply sim_promise_strong_sim_promise in PROMS.\n        eapply sim_promise_bot in PROMS; eauto.\n    - econs; ss; eauto.\n  Qed.\n\n  Lemma sim_thread_step_event_strong' others self extra_others extra_self\n        lang st lc_src lc_tgt sc mem_src mem_tgt pf e_tgt\n        st' lc_tgt' sc' mem_tgt' views views'\n        (STEPTGT: @JThread.step lang pf e_tgt (Thread.mk _ st lc_tgt sc mem_tgt) (Thread.mk _ st' lc_tgt' sc' mem_tgt') views views')\n        (NOREAD: no_read_msgs others e_tgt)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LOCALSRC: Local.wf lc_src mem_src)\n        (LOCALTGT: Local.wf lc_tgt mem_tgt)\n        (SIM: sim_local_strong self extra_self (extra_others \\\\3// extra_self) lc_src lc_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views loc ts))\n\n        (EVENT: ThreadEvent.get_machine_event e_tgt <> MachineEvent.silent)\n    :\n      exists lc_src',\n        (<<STEPSRC: Thread.step pf e_tgt (Thread.mk _ st lc_src sc mem_src) (Thread.mk _ st' lc_src' sc' mem_src)>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt'>>) /\\\n        (<<SIM: sim_local_strong self extra_self (extra_others \\\\3// extra_self) lc_src' lc_tgt'>>)\n  .\n  Proof.\n    inv STEPTGT. inv STEP.\n    - inv STEP0; ss.\n    - inv STEP0; ss. inv LOCAL; ss.\n      + exploit sim_fence_step_strong; eauto. i. des. esplits; eauto.\n      + exploit sim_failure_step; eauto.\n        { eapply sim_local_strong_sim_local; eauto. }\n        i. des. esplits; eauto.\n  Qed.\n\n  Lemma sim_thread_step_event_strong others self extra_others extra_self\n        lang st lc_src lc_tgt sc mem_src mem_tgt pf e_tgt\n        st' lc_tgt' sc' mem_tgt' views views'\n        (STEPTGT: @JThread.step lang pf e_tgt (Thread.mk _ st lc_tgt sc mem_tgt) (Thread.mk _ st' lc_tgt' sc' mem_tgt') views views')\n        (NOREAD: no_read_msgs others e_tgt)\n        (MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt)\n        (SCSRC: Memory.closed_timemap sc mem_src)\n        (SCTGT: Memory.closed_timemap sc mem_tgt)\n        (MEMSRC: Memory.closed mem_src)\n        (MEMTGT: Memory.closed mem_tgt)\n        (LOCALSRC: Local.wf lc_src mem_src)\n        (LOCALTGT: Local.wf lc_tgt mem_tgt)\n        (SIM: sim_local_strong self extra_self (extra_others \\\\3// extra_self) lc_src lc_tgt)\n\n        (MEMWF: memory_times_wf times mem_tgt')\n        (CONSISTENT: Local.promise_consistent lc_tgt')\n        (EXCLUSIVE: forall loc' ts' (OTHER: others loc' ts'),\n            exists from msg, <<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from msg>>)\n        (EXCLUSIVEEXTRA: forall loc' ts' from' (OTHER: extra_others loc' ts' from'),\n            (<<UNCH: unchangable mem_src (Local.promises lc_src) loc' ts' from' Message.reserve>>))\n        (JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views loc ts))\n\n        (EVENT: ThreadEvent.get_machine_event e_tgt <> MachineEvent.silent)\n    :\n      exists lc_src',\n        (<<STEPSRC: Thread.step pf e_tgt (Thread.mk _ st lc_src sc mem_src) (Thread.mk _ st' lc_src' sc' mem_src)>>) /\\\n        (<<MEM: sim_memory (others \\\\2// self) (extra_others \\\\3// extra_self) mem_src mem_tgt'>>) /\\\n        (<<SIM: sim_local_strong self extra_self (extra_others \\\\3// extra_self) lc_src' lc_tgt'>>) /\\\n        (<<JOINED: forall loc ts, List.Forall (fun vw => semi_closed_view vw mem_src loc ts) (views' loc ts)>>)\n  .\n  Proof.\n    hexploit sim_thread_step_event_strong'; eauto.\n    i. des. esplits; eauto.\n    hexploit Thread.step_future; eauto. i. des. ss.\n    inv STEPTGT. ss.\n    i. destruct (classic (views' loc ts = views loc ts)).\n    { rewrite H.\n      eapply List.Forall_impl; eauto.\n      i. ss. }\n    { hexploit VIEWSLE; eauto. i. des.\n      set (MEM1:=(sim_memory_contents MEM0) loc ts). rewrite GET in MEM1. inv MEM1; ss.\n      { rewrite VIEW; eauto. econs.\n        - eapply closed_view_semi_closed. eapply Memory.join_closed_view.\n          + inv WF2. inv SIM0. ss. eapply TVIEW_CLOSED.\n          + inv CLOSED2. eapply Memory.singleton_ur_closed_view; eauto.\n        - apply List.Forall_forall.\n          i. eapply all_join_views_in_iff in H0. des. subst.\n          erewrite View.join_comm. eapply join_singleton_semi_closed_view.\n          + eapply List.Forall_forall in IN; eauto. ss. eauto.\n          + eapply memory_get_ts_le in GET. eauto.\n      }\n      { rewrite VIEW; eauto. econs.\n        - eapply semi_closed_view_join.\n          + eapply closed_view_semi_closed. inv WF2. inv SIM0. ss. eapply TVIEW_CLOSED.\n          + eapply semi_closed_view_singleton; eauto. eapply MEMSRC.\n        - apply List.Forall_forall.\n          i. eapply all_join_views_in_iff in H0. des. subst.\n          erewrite View.join_comm. eapply join_singleton_semi_closed_view.\n          + eapply List.Forall_forall in IN; eauto. ss. eauto.\n          + eapply memory_get_ts_le in GET. eauto.\n      }\n    }\n  Qed.\n\nEnd SIM.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/ldrfpf/LocalPFThread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105587468141, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.22496009695567432}}
{"text": "(* An intermediate language between our IR and RTL *)\nRequire Import RTL.\nRequire Import Globalenvs.\nRequire Import Coqlib.\nRequire Import Values.\nRequire Import Integers.\nRequire Import Maps.\nRequire Import common.\nRequire Import Smallstep.\nRequire Import primitives.\nRequire Import Registers.\n\n\n(** * RTLblock  *)\n(* we first define an alternate version of RTL where we have blocks of instructions *)\n(* The IR will first be transformed to RTLblock, then to RTL *)\n\n\n(* Instructions inside of blocks *)\n(* Compared to RTL, we don't see the next PC, these will be put in a list *)\n(* The only possible calls are calls to external primitives *)\nInductive block_instr : Type :=\n| Bop: Op.operation -> list reg -> reg -> block_instr\n| Bcall: ext_primitive -> list reg -> reg -> block_instr.\n\n(* At the end of a block *)\n(* All possible returns need return a register (not an option) *)\nInductive exit_instr: Type :=\n| Bnop : label -> exit_instr\n| Bcond : Op.condition -> list reg -> label -> label -> exit_instr\n| Breturn : reg -> exit_instr.\n\n\n(* Blocks that we generate that correspond to our IR instructions *)\n(* Either Basic blocks: sequential instructions ending in an exit_instr *)\n(* Or a Conditional block: first, an instruction to evaluate the assume guard\n   then, a condition. either the condition evaluates to TRUE, then we go to the next label  *)\n(* And if false we go through another basic block: the DEOPT branch *)\n(* NEW version of the Cblock *)\n(* Now, we include the operation and the list of registers that correspond to evaluating the guard expression *)\nDefinition basic_block : Type := list block_instr * exit_instr.\n\nInductive block : Type :=\n| Bblock : basic_block -> block\n| Cblock : Op.operation -> list reg -> label -> basic_block -> block.\n                                 \n\n(* Blocks are indexed by labels *)\nDefinition block_code: Type := PTree.t block.\n\n(* A program can hold a single RTL function during compilation *)\nDefinition cont_idx: Type := PTree.t label.\nDefinition RTLblockfun: Type := fun_id * block_code * label * cont_idx.\n\nDefinition get_block (rtlb:RTLblockfun) (lbl:positive) : option block :=\n  match rtlb with\n  | (fid, blkc, entry, contidx) =>\n    PTree.get lbl blkc\n  end.\n\n(** * Semantic States *)\n(* no memory, no stack: our instructions don't modify them *)\nInductive block_state : Type :=\n| BPF: label -> regset -> block_state (* Pre-fetching: At a label *)\n| BState: block -> regset -> block_state (* Inside a block *)\n| BFinal: int -> block_state.\n\nDefinition init_regset : regset :=\n  Regmap.init Vundef.\n\n(** * Evaluating Operations *)\n(* Partial functions that don't need a global env or a stack pointer *)\n(* We'll show that all the expr we generated work for these functions *)\n(* And we'll show that these coincide with the full functions *)\nRequire Import Op.\n\n\n(* Only for the addressing we generate *)\nDefinition block_eval_addressing32 (addr: addressing) (vl: list val) : option val :=\n  match addr, vl with\n  | Aindexed n, v1::nil =>\n    Some (Val.add v1 (Vint (Int.repr n)))\n  | Aindexed2 n, v1::v2::nil =>\n    Some (Val.add (Val.add v1 v2) (Vint (Int.repr n)))\n  | _, _ => None\n  end.\n\n\nLemma eval_addressing_correct:\n  forall F V (ge:Genv.t F V) sp addr vl v,\n    block_eval_addressing32 addr vl = Some v ->\n    eval_addressing32 ge sp addr vl = Some v.\nProof.\n  intros F V ge sp addr vl v H. destruct addr; simpl; inv H; auto.\nQed.\n  \n(* Only for the conditions we generate *)\nDefinition block_eval_condition (cond: condition) (vl: list val): option bool :=\n  match cond, vl with\n  | Ccomp c, v1 :: v2 :: nil => Val.cmp_bool c v1 v2\n  | Ccompimm c n, v1 :: nil => Val.cmp_bool c v1 (Vint n)\n  | _, _ => None\n  end.\n\nLemma eval_condition_correct:\n  forall m cond vl b,\n    block_eval_condition cond vl = Some b ->\n    eval_condition cond vl m = Some b.\nProof.\n  intros m cond vl b H. destruct cond; inv H; auto.\nQed.\n\nDefinition optval_of_optbool (ob:option bool) : option val :=\n  match ob with\n  | Some true => Some Vtrue\n  | Some false => Some Vfalse\n  | None => None\n  end.\n\n(* Only for the operations we generate *)\nDefinition block_eval_operation (op: operation) (vl: list val): option val :=\n  match op, vl with\n  | Ointconst n, nil => Some (Vint n)\n  | Oneg, v1::nil => Some (Val.neg v1)\n  | Osub, v1::v2::nil => Some (Val.sub v1 v2)\n  | Omul, v1::v2::nil => Some (Val.mul v1 v2)\n  | Omulimm n, v1::nil => Some (Val.mul v1 (Vint n))\n  | Olea addr, _ => block_eval_addressing32 addr vl (* partial version *)\n  | Ocmp c, _ => optval_of_optbool (block_eval_condition c vl) (* partial version *)\n  | Omod, v1::v2::nil => Val.mods v1 v2\n  | _, _ => None\n  end.\n\n\nLemma eval_operation_correct:\n  forall F V (ge:Genv.t F V) sp m op vl v,\n    block_eval_operation op vl = Some v ->\n    eval_operation ge sp op vl m = Some v.\nProof.\n  intros F V ge sp m op vl v H. destruct op; simpl; inv H; auto.\n  - rewrite H1. eapply eval_addressing_correct in H1. eauto.\n  - destruct (block_eval_condition cond vl) eqn:COND; inv H1.\n    eapply eval_condition_correct in COND. rewrite COND. destruct b; inv H0; simpl; auto.\nQed.\n", "meta": {"author": "Aurele-Barriere", "repo": "JIThm", "sha": "ad3ae5a3d6759a070195815e321df1b372d982b9", "save_path": "github-repos/coq/Aurele-Barriere-JIThm", "path": "github-repos/coq/Aurele-Barriere-JIThm/JIThm-ad3ae5a3d6759a070195815e321df1b372d982b9/coqjit/RTLblock.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.224806420023783}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness proof for code linearization *)\n\nRequire Import FSets.\nRequire Import Coqlib Maps Ordered Errors Lattice Kildall Integers.\nRequire Import AST Linking.\nRequire Import Values Memory Events Globalenvs Smallstep.\nRequire Import Op Locations LTL Linear.\nRequire Import Linearize.\n\nModule NodesetFacts := FSetFacts.Facts(Nodeset).\n\nDefinition match_prog (p: LTL.program) (tp: Linear.program) :=\n  match_program (fun ctx f tf => transf_fundef f = OK tf) eq p tp.\n\nLemma transf_program_match:\n  forall p tp, transf_program p = OK tp -> match_prog p tp.\nProof.\n  intros. eapply match_transform_partial_program; eauto.\nQed.\n\nSection LINEARIZATION.\nContext `{external_calls_prf: ExternalCalls}.\n\nVariable prog: LTL.program.\nVariable tprog: Linear.program.\n\nHypothesis TRANSF: match_prog prog tprog.\n\nLet ge := Genv.globalenv prog.\nLet tge := Genv.globalenv tprog.\n\nLemma functions_translated:\n  forall v f,\n  Genv.find_funct ge v = Some f ->\n  exists tf,\n  Genv.find_funct tge v = Some tf /\\ transf_fundef f = OK tf.\nProof (Genv.find_funct_transf_partial TRANSF).\n\nLemma function_ptr_translated:\n  forall v f,\n  Genv.find_funct_ptr ge v = Some f ->\n  exists tf,\n  Genv.find_funct_ptr tge v = Some tf /\\ transf_fundef f = OK tf.\nProof (Genv.find_funct_ptr_transf_partial TRANSF).\n\nLemma symbols_preserved:\n  forall id,\n  Genv.find_symbol tge id = Genv.find_symbol ge id.\nProof (Genv.find_symbol_transf_partial TRANSF).\n\nLemma senv_preserved:\n  Senv.equiv ge tge.\nProof (Genv.senv_transf_partial TRANSF).\n\nLemma genv_next_preserved:\n  Genv.genv_next tge = Genv.genv_next ge.\nProof.\n  apply senv_preserved.\nQed.\n\nLemma sig_preserved:\n  forall f tf,\n  transf_fundef f = OK tf ->\n  Linear.funsig tf = LTL.funsig f.\nProof.\n  unfold transf_fundef, transf_partial_fundef; intros.\n  destruct f. monadInv H. monadInv EQ. reflexivity.\n  inv H. reflexivity.\nQed.\n\nLemma stacksize_preserved:\n  forall f tf,\n  transf_function f = OK tf ->\n  Linear.fn_stacksize tf = LTL.fn_stacksize f.\nProof.\n  intros. monadInv H. auto.\nQed.\n\nLemma find_function_translated:\n  forall ros ls f,\n  LTL.find_function ge ros ls = Some f ->\n  exists tf,\n  find_function tge ros ls = Some tf /\\ transf_fundef f = OK tf.\nProof.\n  unfold LTL.find_function; intros; destruct ros; simpl.\n  apply functions_translated; auto.\n  rewrite symbols_preserved. destruct (Genv.find_symbol ge i).\n  apply function_ptr_translated; auto.\n  congruence.\nQed.\n\n(** * Correctness of reachability analysis *)\n\n(** The entry point of the function is reachable. *)\n\nLemma reachable_entrypoint:\n  forall f, (reachable f)!!(f.(fn_entrypoint)) = true.\nProof.\n  intros. unfold reachable.\n  caseEq (reachable_aux f).\n  unfold reachable_aux; intros reach A.\n  assert (LBoolean.ge reach!!(f.(fn_entrypoint)) true).\n  eapply DS.fixpoint_entry. eexact A. auto.\n  unfold LBoolean.ge in H. tauto.\n  intros. apply PMap.gi.\nQed.\n\n(** The successors of a reachable instruction are reachable. *)\n\nLemma reachable_successors:\n  forall f pc pc' b,\n  f.(LTL.fn_code)!pc = Some b -> In pc' (successors_block b) ->\n  (reachable f)!!pc = true ->\n  (reachable f)!!pc' = true.\nProof.\n  intro f. unfold reachable.\n  caseEq (reachable_aux f).\n  unfold reachable_aux. intro reach; intros.\n  assert (LBoolean.ge reach!!pc' reach!!pc).\n  change (reach!!pc) with ((fun pc r => r) pc (reach!!pc)).\n  eapply DS.fixpoint_solution; eauto. intros; apply DS.L.eq_refl.\n  elim H3; intro. congruence. auto.\n  intros. apply PMap.gi.\nQed.\n\n(** * Properties of node enumeration *)\n\n(** An enumeration of CFG nodes is correct if the following conditions hold:\n- All nodes for reachable basic blocks must be in the list.\n- The list is without repetition (so that no code duplication occurs).\n\nWe prove that the result of the [enumerate] function satisfies both\nconditions. *)\n\nLemma nodeset_of_list_correct:\n  forall l s s',\n  nodeset_of_list l s = OK s' ->\n  list_norepet l\n  /\\ (forall pc, Nodeset.In pc s' <-> Nodeset.In pc s \\/ In pc l)\n  /\\ (forall pc, In pc l -> ~Nodeset.In pc s).\nProof.\n  induction l; simpl; intros.\n  inv H. split. constructor. split. intro; tauto. intros; tauto.\n  generalize H; clear H; caseEq (Nodeset.mem a s); intros.\n  inv H0.\n  exploit IHl; eauto. intros [A [B C]].\n  split. constructor; auto. red; intro. elim (C a H1). apply Nodeset.add_1. hnf. auto.\n  split. intros. rewrite B. rewrite NodesetFacts.add_iff.\n  unfold Nodeset.E.eq. unfold OrderedPositive.eq. tauto.\n  intros. destruct H1. subst pc. rewrite NodesetFacts.not_mem_iff. auto.\n  generalize (C pc H1). rewrite NodesetFacts.add_iff. tauto.\nQed.\n\nLemma check_reachable_correct:\n  forall f reach s pc i,\n  check_reachable f reach s = true ->\n  f.(LTL.fn_code)!pc = Some i ->\n  reach!!pc = true ->\n  Nodeset.In pc s.\nProof.\n  intros f reach s.\n  assert (forall l ok,\n    List.fold_left (fun a p => check_reachable_aux reach s a (fst p) (snd p)) l ok = true ->\n    ok = true /\\\n    (forall pc i,\n     In (pc, i) l ->\n     reach!!pc = true ->\n     Nodeset.In pc s)).\n  induction l; simpl; intros.\n  split. auto. intros. destruct H0.\n  destruct a as [pc1 i1]. simpl in H.\n  exploit IHl; eauto. intros [A B].\n  unfold check_reachable_aux in A.\n  split. destruct (reach!!pc1). elim (andb_prop _ _ A). auto. auto.\n  intros. destruct H0. inv H0. rewrite H1 in A. destruct (andb_prop _ _ A).\n  apply Nodeset.mem_2; auto.\n  eauto.\n\n  intros pc i. unfold check_reachable. rewrite PTree.fold_spec. intros.\n  exploit H; eauto. intros [A B]. eapply B; eauto.\n  apply PTree.elements_correct. eauto.\nQed.\n\nLemma enumerate_complete:\n  forall f enum pc i,\n  enumerate f = OK enum ->\n  f.(LTL.fn_code)!pc = Some i ->\n  (reachable f)!!pc = true ->\n  In pc enum.\nProof.\n  intros until i. unfold enumerate.\n  set (reach := reachable f).\n  intros. monadInv H.\n  generalize EQ0; clear EQ0. caseEq (check_reachable f reach x); intros; inv EQ0.\n  exploit check_reachable_correct; eauto. intro.\n  exploit nodeset_of_list_correct; eauto. intros [A [B C]].\n  rewrite B in H2. destruct H2. elim (Nodeset.empty_1 H2). auto.\nQed.\n\nLemma enumerate_norepet:\n  forall f enum,\n  enumerate f = OK enum ->\n  list_norepet enum.\nProof.\n  intros until enum. unfold enumerate.\n  set (reach := reachable f).\n  intros. monadInv H.\n  generalize EQ0; clear EQ0. caseEq (check_reachable f reach x); intros; inv EQ0.\n  exploit nodeset_of_list_correct; eauto. intros [A [B C]]. auto.\nQed.\n\n(** * Properties related to labels *)\n\n(** If labels are globally unique and the Linear code [c] contains\n  a subsequence [Llabel lbl :: c1], then [find_label lbl c] returns [c1].\n*)\n\nFixpoint unique_labels (c: code) : Prop :=\n  match c with\n  | nil => True\n  | Llabel lbl :: c => ~(In (Llabel lbl) c) /\\ unique_labels c\n  | i :: c => unique_labels c\n  end.\n\nLemma find_label_unique:\n  forall lbl c1 c2 c3,\n  is_tail (Llabel lbl :: c1) c2 ->\n  unique_labels c2 ->\n  find_label lbl c2 = Some c3 ->\n  c1 = c3.\nProof.\n  induction c2.\n  simpl; intros; discriminate.\n  intros c3 TAIL UNIQ. simpl.\n  generalize (is_label_correct lbl a). case (is_label lbl a); intro ISLBL.\n  subst a. intro. inversion TAIL. congruence.\n  elim UNIQ; intros. elim H4. apply is_tail_in with c1; auto.\n  inversion TAIL. congruence. apply IHc2. auto.\n  destruct a; simpl in UNIQ; tauto.\nQed.\n\n(** Correctness of the [starts_with] test. *)\n\nLemma starts_with_correct:\n  forall lm,\n  forall lbl c1 c2 c3 s f sp ls m,\n  is_tail c1 c2 ->\n  unique_labels c2 ->\n  starts_with lbl c1 = true ->\n  find_label lbl c2 = Some c3 ->\n  plus (step lm) tge (State s f sp c1 ls m)\n             E0 (State s f sp c3 ls m).\nProof.\n  induction c1.\n  simpl; intros; discriminate.\n  simpl starts_with. destruct a; try (intros; discriminate).\n  intros.\n  apply plus_left with E0 (State s f sp c1 ls m) E0.\n  simpl. constructor.\n  destruct (peq lbl l).\n  subst l. replace c3 with c1. constructor.\n  apply find_label_unique with lbl c2; auto.\n  apply plus_star.\n  apply IHc1 with c2; auto. eapply is_tail_cons_left; eauto.\n  traceEq.\nQed.\n\n(** Connection between [find_label] and linearization. *)\n\nLemma find_label_add_branch:\n  forall lbl k s,\n  find_label lbl (add_branch s k) = find_label lbl k.\nProof.\n  intros. unfold add_branch. destruct (starts_with s k); auto.\nQed.\n\nLemma find_label_lin_block:\n  forall lbl k b,\n  find_label lbl (linearize_block b k) = find_label lbl k.\nProof.\n  intros lbl k. generalize (find_label_add_branch lbl k); intro.\n  induction b; simpl; auto. destruct a; simpl; auto.\n  case (starts_with s1 k); simpl; auto.\nQed.\n\nRemark linearize_body_cons:\n  forall f pc enum,\n  linearize_body f (pc :: enum) =\n  match f.(LTL.fn_code)!pc with\n  | None => linearize_body f enum\n  | Some b => Llabel pc :: linearize_block b (linearize_body f enum)\n  end.\nProof.\n  intros. unfold linearize_body. rewrite list_fold_right_eq.\n  unfold linearize_node. destruct (LTL.fn_code f)!pc; auto.\nQed.\n\nLemma find_label_lin_rec:\n  forall f enum pc b,\n  In pc enum ->\n  f.(LTL.fn_code)!pc = Some b ->\n  exists k, find_label pc (linearize_body f enum) = Some (linearize_block b k).\nProof.\n  induction enum; intros.\n  elim H.\n  rewrite linearize_body_cons.\n  destruct (peq a pc).\n  subst a. exists (linearize_body f enum).\n  rewrite H0. simpl. rewrite peq_true. auto.\n  assert (In pc enum). simpl in H. tauto.\n  destruct (IHenum pc b H1 H0) as [k FIND].\n  exists k. destruct (LTL.fn_code f)!a.\n  simpl. rewrite peq_false. rewrite find_label_lin_block. auto. auto.\n  auto.\nQed.\n\nLemma find_label_lin:\n  forall f tf pc b,\n  transf_function f = OK tf ->\n  f.(LTL.fn_code)!pc = Some b ->\n  (reachable f)!!pc = true ->\n  exists k,\n  find_label pc (fn_code tf) = Some (linearize_block b k).\nProof.\n  intros. monadInv H. simpl.\n  rewrite find_label_add_branch. apply find_label_lin_rec.\n  eapply enumerate_complete; eauto. auto.\nQed.\n\nLemma find_label_lin_inv:\n  forall f tf pc b k,\n  transf_function f = OK tf ->\n  f.(LTL.fn_code)!pc = Some b ->\n  (reachable f)!!pc = true ->\n  find_label pc (fn_code tf) = Some k ->\n  exists k', k = linearize_block b k'.\nProof.\n  intros. exploit find_label_lin; eauto. intros [k' FIND].\n  exists k'. congruence.\nQed.\n\n(** Unique label property for linearized code. *)\n\nLemma label_in_add_branch:\n  forall lbl s k,\n  In (Llabel lbl) (add_branch s k) -> In (Llabel lbl) k.\nProof.\n  intros until k; unfold add_branch.\n  destruct (starts_with s k); simpl; intuition congruence.\nQed.\n\nLemma label_in_lin_block:\n  forall lbl k b,\n  In (Llabel lbl) (linearize_block b k) -> In (Llabel lbl) k.\nProof.\n  induction b; simpl; intros. auto.\n  destruct a; simpl in H; try (intuition congruence).\n  apply label_in_add_branch with s; intuition congruence.\n  destruct (starts_with s1 k); simpl in H.\n  apply label_in_add_branch with s1; intuition congruence.\n  apply label_in_add_branch with s2; intuition congruence.\nQed.\n\nLemma label_in_lin_rec:\n  forall f lbl enum,\n  In (Llabel lbl) (linearize_body f enum) -> In lbl enum.\nProof.\n  induction enum.\n  simpl; auto.\n  rewrite linearize_body_cons. destruct (LTL.fn_code f)!a.\n  simpl. intros [A|B]. left; congruence.\n  right. apply IHenum. eapply label_in_lin_block; eauto.\n  intro; right; auto.\nQed.\n\nLemma unique_labels_add_branch:\n  forall lbl k,\n  unique_labels k -> unique_labels (add_branch lbl k).\nProof.\n  intros; unfold add_branch.\n  destruct (starts_with lbl k); simpl; intuition.\nQed.\n\nLemma unique_labels_lin_block:\n  forall k b,\n  unique_labels k -> unique_labels (linearize_block b k).\nProof.\n  induction b; intros; simpl. auto.\n  destruct a; auto; try (apply unique_labels_add_branch; auto).\n  case (starts_with s1 k); simpl; apply unique_labels_add_branch; auto.\nQed.\n\nLemma unique_labels_lin_rec:\n  forall f enum,\n  list_norepet enum ->\n  unique_labels (linearize_body f enum).\nProof.\n  induction enum.\n  simpl; auto.\n  rewrite linearize_body_cons.\n  intro. destruct (LTL.fn_code f)!a.\n  simpl. split. red. intro. inversion H. elim H3.\n  apply label_in_lin_rec with f.\n  apply label_in_lin_block with b. auto.\n  apply unique_labels_lin_block. apply IHenum. inversion H; auto.\n  apply IHenum. inversion H; auto.\nQed.\n\nLemma unique_labels_transf_function:\n  forall f tf,\n  transf_function f = OK tf ->\n  unique_labels (fn_code tf).\nProof.\n  intros. monadInv H. simpl.\n  apply unique_labels_add_branch.\n  apply unique_labels_lin_rec. eapply enumerate_norepet; eauto.\nQed.\n\n(** Correctness of [add_branch]. *)\n\nLemma is_tail_find_label:\n  forall lbl c2 c1,\n  find_label lbl c1 = Some c2 -> is_tail c2 c1.\nProof.\n  induction c1; simpl.\n  intros; discriminate.\n  case (is_label lbl a). intro. injection H; intro. subst c2.\n  constructor. constructor.\n  intro. constructor. auto.\nQed.\n\nLemma is_tail_add_branch:\n  forall lbl c1 c2, is_tail (add_branch lbl c1) c2 -> is_tail c1 c2.\nProof.\n  intros until c2. unfold add_branch. destruct (starts_with lbl c1).\n  auto. eauto with coqlib.\nQed.\n\nLemma is_tail_lin_block:\n  forall b c1 c2,\n  is_tail (linearize_block b c1) c2 -> is_tail c1 c2.\nProof.\n  induction b; simpl; intros.\n  auto.\n  destruct a; eauto with coqlib.\n  eapply is_tail_add_branch; eauto.\n  destruct (starts_with s1 c1); eapply is_tail_add_branch; eauto with coqlib.\nQed.\n\nLemma add_branch_correct:\n  forall lm,\n  forall lbl c k s f tf sp ls m,\n  transf_function f = OK tf ->\n  is_tail k tf.(fn_code) ->\n  find_label lbl tf.(fn_code) = Some c ->\n  plus (step lm) tge (State s tf sp (add_branch lbl k) ls m)\n             E0 (State s tf sp c ls m).\nProof.\n  intros. unfold add_branch.\n  caseEq (starts_with lbl k); intro SW.\n  eapply starts_with_correct; eauto.\n  eapply unique_labels_transf_function; eauto.\n  apply plus_one. apply exec_Lgoto. auto.\nQed.\n\n(** * Correctness of linearization *)\n\n(** The proof of semantic preservation is a simulation argument of the \"star\" kind:\n<<\n           st1 --------------- st2\n            |                   |\n           t|                  t| + or ( 0 \\/ |st1'| < |st1| )\n            |                   |\n            v                   v\n           st1'--------------- st2'\n>>\n  The invariant (horizontal lines above) is the [match_states]\n  predicate defined below.  It captures the fact that the flow\n  of data is the same in the source and linearized codes.\n  Moreover, whenever the source state is at node [pc] in its\n  control-flow graph, the transformed state is at a code\n  sequence [c] that starts with the label [pc]. *)\n\nInductive match_stackframes: LTL.stackframe -> Linear.stackframe -> Prop :=\n  | match_stackframe_intro:\n      forall f sp bb ls tf c,\n      transf_function f = OK tf ->\n      (forall pc, In pc (successors_block bb) -> (reachable f)!!pc = true) ->\n      is_tail c tf.(fn_code) ->\n      match_stackframes\n        (LTL.Stackframe f sp ls bb)\n        (Linear.Stackframe tf sp ls (linearize_block bb c)).\n\nInductive match_states: LTL.state -> Linear.state -> Prop :=\n  | match_states_add_branch:\n      forall s f sp pc ls m tf ts c\n        (STACKS: list_forall2 match_stackframes s ts)\n        (TRF: transf_function f = OK tf)\n        (REACH: (reachable f)!!pc = true)\n        (TAIL: is_tail c tf.(fn_code)),\n      match_states (LTL.State s f sp pc ls m)\n                   (Linear.State ts tf sp (add_branch pc c) ls m)\n  | match_states_cond_taken:\n      forall s f sp pc ls m tf ts cond args c\n        (STACKS: list_forall2 match_stackframes s ts)\n        (TRF: transf_function f = OK tf)\n        (REACH: (reachable f)!!pc = true)\n        (JUMP: eval_condition cond (reglist ls args) m = Some true),\n      match_states (LTL.State s f sp pc (undef_regs (destroyed_by_cond cond) ls) m)\n                   (Linear.State ts tf sp (Lcond cond args pc :: c) ls m)\n  | match_states_jumptable:\n      forall s f sp pc ls m tf ts arg tbl c n\n        (STACKS: list_forall2 match_stackframes s ts)\n        (TRF: transf_function f = OK tf)\n        (REACH: (reachable f)!!pc = true)\n        (ARG: ls (R arg) = Vint n)\n        (JUMP: list_nth_z tbl (Int.unsigned n) = Some pc),\n      match_states (LTL.State s f sp pc (undef_regs destroyed_by_jumptable ls) m)\n                   (Linear.State ts tf sp (Ljumptable arg tbl :: c) ls m)\n  | match_states_block:\n      forall s f sp bb ls m tf ts c\n        (STACKS: list_forall2 match_stackframes s ts)\n        (TRF: transf_function f = OK tf)\n        (REACH: forall pc, In pc (successors_block bb) -> (reachable f)!!pc = true)\n        (TAIL: is_tail c tf.(fn_code)),\n      match_states (LTL.Block s f sp bb ls m)\n                   (Linear.State ts tf sp (linearize_block bb c) ls m)\n  | match_states_call:\n      forall s f ls m tf ts,\n      list_forall2 match_stackframes s ts ->\n      transf_fundef f = OK tf ->\n      match_states (LTL.Callstate s f ls m)\n                   (Linear.Callstate ts tf ls m)\n  | match_states_return:\n      forall s ls m ts,\n      list_forall2 match_stackframes s ts ->\n      match_states (LTL.Returnstate s ls m)\n                   (Linear.Returnstate ts ls m).\n\nDefinition measure (S: LTL.state) : nat :=\n  match S with\n  | LTL.State s f sp pc ls m => 0%nat\n  | LTL.Block s f sp bb ls m => 1%nat\n  | _ => 0%nat\n  end.\n\nSection WITHINITLS.\n\nVariable init_ls: locset.\n\nRemark match_parent_locset:\n  forall s ts, list_forall2 match_stackframes s ts -> parent_locset init_ls ts = LTL.parent_locset init_ls s.\nProof.\n  induction 1; simpl. auto. inv H; auto.\nQed.\n\nTheorem transf_step_correct:\n  forall s1 t s2, LTL.step init_ls ge s1 t s2 ->\n  forall s1' (MS: match_states s1 s1'),\n  (exists s2', plus (Linear.step init_ls) tge s1' t s2' /\\ match_states s2 s2')\n  \\/ (measure s2 < measure s1 /\\ t = E0 /\\ match_states s2 s1')%nat.\nProof.\n  induction 1; intros; try (inv MS).\n\n  (* start of block, at an [add_branch] *)\n  exploit find_label_lin; eauto. intros [k F].\n  left; econstructor; split.\n  eapply add_branch_correct; eauto.\n  econstructor; eauto.\n  intros; eapply reachable_successors; eauto.\n  eapply is_tail_lin_block; eauto. eapply is_tail_find_label; eauto.\n\n  (* start of block, target of an [Lcond] *)\n  exploit find_label_lin; eauto. intros [k F].\n  left; econstructor; split.\n  apply plus_one. eapply exec_Lcond_true; eauto.\n  econstructor; eauto.\n  intros; eapply reachable_successors; eauto.\n  eapply is_tail_lin_block; eauto. eapply is_tail_find_label; eauto.\n\n  (* start of block, target of an [Ljumptable] *)\n  exploit find_label_lin; eauto. intros [k F].\n  left; econstructor; split.\n  apply plus_one. eapply exec_Ljumptable; eauto.\n  econstructor; eauto.\n  intros; eapply reachable_successors; eauto.\n  eapply is_tail_lin_block; eauto. eapply is_tail_find_label; eauto.\n\n  (* Lop *)\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor; eauto.\n  instantiate (1 := v); rewrite <- H; apply eval_operation_preserved.\n  exact symbols_preserved.\n  econstructor; eauto.\n\n  (* Lload *)\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor.\n  instantiate (1 := a). rewrite <- H; apply eval_addressing_preserved.\n  exact symbols_preserved. eauto. eauto.\n  econstructor; eauto.\n\n  (* Lgetstack *)\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor; eauto.\n  econstructor; eauto.\n\n  (* Lsetstack *)\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor; eauto.\n  econstructor; eauto.\n\n  (* Lstore *)\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor.\n  instantiate (1 := a). rewrite <- H; apply eval_addressing_preserved.\n  exact symbols_preserved. eauto. eauto.\n  econstructor; eauto.\n\n  (* Lcall *)\n  exploit find_function_translated; eauto. intros [tfd [A B]].\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor; eauto.\n  symmetry; eapply sig_preserved; eauto.\n  econstructor; eauto. constructor; auto. econstructor; eauto.\n\n  (* Ltailcall *)\n  exploit find_function_translated; eauto. intros [tfd [A B]].\n  left; econstructor; split. simpl.\n  apply plus_one. econstructor; eauto.\n  rewrite (match_parent_locset _ _ STACKS). eauto.\n  symmetry; eapply sig_preserved; eauto.\n  rewrite (stacksize_preserved _ _ TRF); eauto.\n  rewrite (match_parent_locset _ _ STACKS).\n  econstructor; eauto.\n\n  (* Lbuiltin *)\n  left; econstructor; split. simpl.\n  apply plus_one. eapply exec_Lbuiltin; eauto.\n  eapply eval_builtin_args_preserved with (ge1 := ge); eauto. exact symbols_preserved.\n  eapply external_call_symbols_preserved; eauto. apply senv_preserved.\n  econstructor; eauto.\n\n  (* Lbranch *)\n  assert ((reachable f)!!pc = true). apply REACH; simpl; auto.\n  right; split. simpl; omega. split. auto. simpl. econstructor; eauto.\n\n  (* Lcond *)\n  assert (REACH1: (reachable f)!!pc1 = true) by (apply REACH; simpl; auto).\n  assert (REACH2: (reachable f)!!pc2 = true) by (apply REACH; simpl; auto).\n  simpl linearize_block.\n  destruct (starts_with pc1 c).\n  (* branch if cond is false *)\n  assert (DC: destroyed_by_cond (negate_condition cond) = destroyed_by_cond cond).\n    destruct cond; reflexivity.\n  destruct b.\n  (* cond is true: no branch *)\n  left; econstructor; split.\n  apply plus_one. eapply exec_Lcond_false.\n  rewrite eval_negate_condition. rewrite H. auto. eauto.\n  rewrite DC. econstructor; eauto.\n  (* cond is false: branch is taken *)\n  right; split. simpl; omega. split. auto.  rewrite <- DC. econstructor; eauto.\n  rewrite eval_negate_condition. rewrite H. auto.\n  (* branch if cond is true *)\n  destruct b.\n  (* cond is true: branch is taken *)\n  right; split. simpl; omega. split. auto. econstructor; eauto.\n  (* cond is false: no branch *)\n  left; econstructor; split.\n  apply plus_one. eapply exec_Lcond_false. eauto. eauto.\n  econstructor; eauto.\n\n  (* Ljumptable *)\n  assert (REACH': (reachable f)!!pc = true).\n    apply REACH. simpl. eapply list_nth_z_in; eauto.\n  right; split. simpl; omega. split. auto. econstructor; eauto.\n\n  (* Lreturn *)\n  left; econstructor; split.\n  simpl. apply plus_one. econstructor; eauto.\n  rewrite (stacksize_preserved _ _ TRF). eauto.\n  rewrite (match_parent_locset _ _ STACKS). econstructor; eauto.\n\n  (* internal functions *)\n  assert (REACH: (reachable f)!!(LTL.fn_entrypoint f) = true).\n    apply reachable_entrypoint.\n  monadInv H7.\n  left; econstructor; split.\n  apply plus_one. eapply exec_function_internal; eauto.\n  rewrite (stacksize_preserved _ _ EQ). eauto.\n  generalize EQ; intro EQ'; monadInv EQ'. simpl.\n  econstructor; eauto. simpl. eapply is_tail_add_branch. constructor.\n\n  (* external function *)\n  monadInv H8. left; econstructor; split.\n  apply plus_one. eapply exec_function_external; eauto.\n  eapply external_call_symbols_preserved; eauto. apply senv_preserved.\n  econstructor; eauto.\n\n  (* return *)\n  inv H3. inv H1.\n  left; econstructor; split.\n  apply plus_one. econstructor.\n  econstructor; eauto.\nQed.\n\nLemma transf_initial_states:\n  forall st1, LTL.initial_state prog st1 ->\n  exists st2, Linear.initial_state tprog st2 /\\ match_states st1 st2.\nProof.\n  intros. inversion H.\n  exploit function_ptr_translated; eauto. intros [tf [A B]].\n  exists (Callstate nil tf (Locmap.init Vundef) m0); split.\n  econstructor; eauto. eapply (Genv.init_mem_transf_partial TRANSF); eauto.\n  rewrite (match_program_main TRANSF).\n  rewrite symbols_preserved. eauto.\n  rewrite <- H3. apply sig_preserved. auto.\n  constructor. constructor. auto.\nQed.\n\nLemma transf_final_states:\n  forall st1 st2 r,\n  match_states st1 st2 -> LTL.final_state st1 r -> Linear.final_state st2 r.\nProof.\n  intros. inv H0. inv H. inv H5. econstructor; eauto.\nQed.\n\nEnd WITHINITLS.\n\nTheorem transf_program_correct:\n  forward_simulation (LTL.semantics prog) (Linear.semantics tprog).\nProof.\n  eapply forward_simulation_star.\n  apply senv_preserved.\n  eexact transf_initial_states.\n  eexact transf_final_states.\n  apply transf_step_correct.\nQed.\n\nEnd LINEARIZATION.\n", "meta": {"author": "CertiKOS", "repo": "compcert.old", "sha": "1fbd4e9beeb9e58b15f7f20ab1c949f6381a4105", "save_path": "github-repos/coq/CertiKOS-compcert.old", "path": "github-repos/coq/CertiKOS-compcert.old/compcert.old-1fbd4e9beeb9e58b15f7f20ab1c949f6381a4105/backend/Linearizeproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.22480642002378298}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import linking.\nRequire Import malloc.\nRequire Import main_bss.\nRequire Import malloc_lemmas.\nRequire Import spec_malloc.\n\n\nDefinition linked_prog : Clight.program :=\n ltac: (linking.link_progs_list [malloc.prog; main_bss.prog]).\n\nInstance CompSpecs : compspecs. make_compspecs linked_prog. Defined.\n\nDefinition Vprog : varspecs. mk_varspecs linked_prog. Defined.\n\nLocal Open Scope assert.\n\nDefinition main_spec :=\n DECLARE _main\n WITH gv: globals\n PRE [ ] main_pre linked_prog tt nil gv\n POST[ tint ]\n    PROP()\n    LOCAL(temp ret_temp (Vint (Int.repr 0)))\n    SEP(TT).\n\n(* proof using simple resource-tracking spec of malloc *)\n\nDefinition user_specs_R' := \n[pre_fill_spec'; try_pre_fill_spec'; malloc_spec_R_simple'; free_spec_R'].\n\nDefinition Gprog' : funspecs := [main_spec] ++ external_specs ++ user_specs_R'.\n\nLemma body_main': semax_body Vprog Gprog' f_main main_spec.\nProof.\nstart_function.\nchange 8 with BINS.\nsep_apply (create_mem_mgr_R gv); auto.\nforward. (* bb = heap *)\nchange 524296 with (BIGBLOCK + WORD*ALIGN).\nreplace Ews with Tsh by admit. (* TODO UNSOUND workaround *)\nrewrite <- memory_block_data_at_.\nforward_if (\n    EX bb,\n    (PROP (malloc_compatible BIGBLOCK bb)\n     LOCAL (temp _bb bb; gvars gv)\n     SEP (mem_mgr_R gv emptyResvec; \n          memory_block Tsh BIGBLOCK bb;\n          has_ext tt))).\nadmit. \n(* case bb%(WORD*ALIGN) != 0 *) \nforward. (* bb = bb + WORD*ALIGN - (uintptr_t)bb%(WORD*ALIGN) *)\nentailer!.\nadmit.\nExists (offset_val (WORD*ALIGN) (gv _heap)).\nentailer!.\nadmit.\nadmit. (* use memory_block_split_offset *)\n(* case bb%(WORD*ALIGN) == 0 *) \nforward.\nExists (gv _heap).\nentailer!.\nadmit.\nadmit.\nIntros bb.\nrewrite <- seq_assoc.\nforward_call (100, bb, gv, emptyResvec).\nsplit; [rep_omega | auto].\nadmit.  (* WORKING HERE *)\nAdmitted.", "meta": {"author": "PrincetonUniversity", "repo": "DeepSpecDB", "sha": "a67d933b4288498bd04c70748b7fa28f676983c3", "save_path": "github-repos/coq/PrincetonUniversity-DeepSpecDB", "path": "github-repos/coq/PrincetonUniversity-DeepSpecDB/DeepSpecDB-a67d933b4288498bd04c70748b7fa28f676983c3/memmgr/verif_main_bss.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.22480642002378295}}
{"text": "(** A small-steps semantics for computations with constraints on the model. *)\nRequire Import Coq.Bool.Bool.\nRequire Import FunctionNinjas.All.\nRequire Import ErrorHandlers.All.\n\nModule Effect.\n  Record t := New {\n    command : Type;\n    answer : command -> Type }.\nEnd Effect.\n\nModule Model.\n  Record t (E : Effect.t) (S : Type) := New {\n    condition : Effect.command E -> S -> Prop;\n    answer : forall c, S -> Effect.answer E c;\n    state : Effect.command E -> S -> S }.\n  Arguments New {E S} _ _ _.\n  Arguments condition {E S} _ _ _.\n  Arguments answer {E S} _ _ _.\n  Arguments state {E S} _ _ _.\nEnd Model.\n\n(*Module C.\n  (** The description of a computation. *)\n  Inductive t (E : Effect.t) (A : Type) : Type :=\n  | Ret : A -> t E A\n  | Call : forall c, (Effect.answer E c -> t E A) -> t E A\n  | Join : forall {B C : Type}, t E B -> t E C -> (B * C -> t E A) -> t E A.\n  Arguments Ret {E A} _.\n  Arguments Call {E A} _ _.\n  Arguments Join {E A B C} _ _ _.\n\n  Module Step.\n    Inductive t {E : Effect.t} {S : Type} (m : Model.t E S) {A : Type} (s : S)\n      : C.t E A -> S -> C.t E A -> Type :=\n    | Call : forall c h,\n      Model.condition m c s ->\n      t m s (C.Call c h) (Model.state m c s) (h (Model.answer m c s))\n    | JoinLeft : forall B C (x : C.t E B) (y : C.t E C) h s' x',\n      t m (A := B) s x s' x' ->\n      t m s (C.Join x y h) s' (C.Join x' y h)\n    | JoinRight : forall B C (x : C.t E B) (y : C.t E C) h s' y',\n      t m (A := C) s y s' y' ->\n      t m s (C.Join x y h) s' (C.Join x y' h)\n    | Join : forall B C (x : B) (y : C) h,\n      t m s (C.Join (C.Ret x) (C.Ret y) h) s (h (x, y)).\n  End Step.\n\n  Module DeadLockFree.\n    Inductive t {E : Effect.t} {S : Type} (m : Model.t E S) {A : Type} (s : S)\n      : C.t E A -> Prop :=\n    | Value : forall x, t m s (C.Ret x)\n    | Step : forall x, (forall s' x', Step.t m s x s' x' -> t m s' x') ->\n      t m s x.\n  End DeadLockFree.\n\n  Module Choose.\n    Inductive t (E : Effect.t) (A : Type) : Type :=\n    | Ret : A -> t E A\n    | Call : forall c, (Effect.answer E c -> t E A) -> t E A\n    | Choose : t E A -> t E A -> t E A.\n    Arguments Ret {E A} _.\n    Arguments Call {E A} _ _.\n    Arguments Choose {E A} _ _.\n\n    Module Join.\n      Inductive t {E : Effect.t} {A B : Type}\n        : Choose.t E A -> Choose.t E B -> Choose.t E (A * B) -> Type :=\n      | RetRet : forall x y, t (Choose.Ret x) (Choose.Ret y) (Choose.Ret (x, y))\n      | RetCall : .\n    End Join.\n  End Choose.\n\n  Module ToChoose.\n    Inductive t {E : Effect.t} {A : Type} : C.t E A -> Choose.t E A -> Type :=\n    | Ret : forall x, t (C.Ret x) (Choose.Ret x)\n    | Call : forall (c : Effect.command E) (h : Effect.answer E c -> C.t E A),\n      (forall s, t () h') -> .\n  End ToChoose.\n\n  Module Unroll.\n    Inductive t {E : Effect.t} {S : Type} (m : Model.t E S) (A : Type) : Type :=\n    | Undef : t m A\n    | Ret : A -> t m A\n    | Condition : forall c s, (Model.condition m c s -> t m A) -> t m A\n    | Schedule : (bool -> t m A) -> t m A.\n    Arguments Undef {E S m A}.\n    Arguments Ret {E S m A} _.\n    Arguments Condition {E S m A} _ _ _.\n    Arguments Schedule {E S m A} _.\n\n    Fixpoint compile {E : Effect.t} {S : Type} (m : Model.t E S) {A : Type}\n      (s : S) (x : C.t E A) : t m A :=\n      match x with\n      | C.Re t x => Ret x\n      | C.Call c h =>\n        Condition c s (fun _ =>\n          compile m (Model.state m c s) (h (Model.answer m c s)))\n      | C.Join _ _ (C.Ret x) (C.Ret y) h => compile m s (h (x, y))\n      | C.Join _ _ x y h =>\n        Schedule (fun b =>\n          if b then\n            )\n      end.\n  End Unroll.\n\n  Module Step'.\n    Inductive t {E : Effect.t} {S : Type} (m : Model.t E S) {A : Type} (s : S)\n      : C.t E A -> S -> C.t E A -> Prop :=\n    | Call : forall c h, Model.condition m c s ->\n      t m s (C.Call c h) (Model.state m c s) (h (Model.answer m c s))\n    | JoinLeft : forall B C (x : C.t E B) (y : C.t E C) h s' x',\n      t m (A := B) s x s' x' ->\n      t m s (C.Join x y h) s' (C.Join x' y h)\n    | JoinRight : forall B C (x : C.t E B) (y : C.t E C) h s' y',\n      t m (A := C) s y s' y' ->\n      t m s (C.Join x y h) s' (C.Join x y' h)\n    | Join : forall B C (x : B) (y : C) h,\n      t m s (C.Join (C.Ret x) (C.Ret y) h) s (h (x, y)).\n  End Step'.\n\n  Module NotStuck.\n    Inductive t {E : Effect.t} {S : Type} (m : Model.t E S) {A : Type}\n      : S -> C.t E A -> Prop :=\n    | Value : forall s x, t m s (C.Ret x)\n    | Step : forall s x s' x', Step.t m s x s' x' -> t m s x.\n\n    Fixpoint is_not_stuck {E : Effect.t} {S : Type} (m : Model.t E S) {A : Type}\n      (dec : forall c s, option (Model.condition m c s)) (s : S) (x : C.t E A)\n      : option (t m s x) :=\n      match x with\n      | Ret x => Some (Value m s x)\n      | Call c h =>\n        Option.bind (dec c s) (fun H =>\n        Some (Step m s _ _ _ (Step.Call m s c h H)))\n      | Join _ _ x y h =>\n        Option.bind (is_not_stuck m dec s x) (fun H =>\n          )\n      end.\n\n    Fixpoint is_not_stuck {E : Effect.t} {S : Type} (m : Model.t E S) {A : Type}\n      (dec : Effect.command E -> S -> bool) (s : S) (x : C.t E A) : bool :=\n      match x with\n      | Ret _ => true\n      | Call c h => dec c s\n      | Join _ _ x y h => orb (is_not_stuck m dec s x) (is_not_stuck m dec s y)\n      end.\n\n    Fixpoint is_not_stuck_ok {E : Effect.t} {S : Type} (m : Model.t E S)\n      {A : Type} (dec : Effect.command E -> S -> bool)\n      (dec_ok : forall c s, dec c s = true -> Model.condition m c s) (s : S)\n      (x : C.t E A) : is_not_stuck m dec s x = true -> t m s x.\n      intro H.\n      destruct x as [x | c h | B C x y h].\n      - apply Value.\n      - eapply Step.\n        apply Step.Call.\n        now apply dec_ok.\n      - destruct (orb_prop _ _ H) as [H_x | H_y].\n        + destruct (is_not_stuck_ok _ _ m _ dec dec_ok s x H_x).\n    Qed.\n  End NotStuck.\n\n  Module DeadLockFree.\n    Inductive t {E : Effect.t} {S : Type} (m : Model.t E S) {A : Type}\n      (s : S) (x : C.t E A) : Prop :=\n    | New : NotStuck.t m s x ->\n      (forall s' x', Step.t m s x s' x' -> t m s' x') -> t m s x.\n  End DeadLockFree.\n\n  (*Module DeadLockFree.\n    Inductive t {E : Effect.t} {S : Type} (m : Model.t E S) {A : Type}\n      : S -> C.t E A -> Prop :=\n    | Ret : forall s x, t m s (C.Ret x)\n    | Call : forall s c h,\n      (Model.condition m c s ->\n        NotStuck.t m (Model.state m c s) (h (Model.answer m c s)) /\\\n        t m (Model.state m c s) (h (Model.answer m c s))) ->\n      t m s (C.Call c h)\n    | Join : .\n      (s : S) (x : C.t E A) : Prop :=\n      forall (x' : C.t E A) (s' : S), Steps.t m x s x' s' -> NotStuck.t m x' s'.\n  End DeadLockFree.*)\nEnd C.\n\nModule M.\n  Inductive t {E : Effect.t} {S : Type} (m : Model.t E S) (A : Type) : Type :=\n  | Ret : A -> t m A\n  | Call : Effect.command E -> (S -> t m A) -> t m A\n  | Choose : t m A -> t m A -> t m A.\n  Arguments Ret {E S m A} _.\n  Arguments Call {E S m A} _ _.\n  Arguments Choose {E S m A} _ _.\n\n  (** If a computation is not stuck. *)\n  Module NotStuck.\n    Inductive t {E : Effect.t} {S : Type} {m : Model.t E S} {A : Type}\n      : M.t m A -> S -> Prop :=\n    | Ret : forall x s, t (M.Ret x) s\n    | Call : forall c h s, Model.condition m c s -> t (M.Call c h) s\n    | ChooseLeft : forall x1 x2 s, t x1 s -> t (M.Choose x1 x2) s\n    | ChooseRight : forall x1 x2 s, t x2 s -> t (M.Choose x1 x2) s.\n  End NotStuck.\n\n  Module DeadLockFree.\n    Inductive t {E : Effect.t} {S : Type} {m : Model.t E S} {A : Type}\n      : M.t m A -> S -> Prop :=\n    | Ret : forall x s, t (M.Ret x) s\n    | Call : forall c h s,\n      (Model.condition m c s ->\n        let s := Model.state m c s in\n        NotStuck.t (h s) s /\\ t (h s) s) ->\n      t (M.Call c h) s\n    | Choose : forall x1 x2 s, t x1 s -> t x2 s -> t (M.Choose x1 x2) s.\n  End DeadLockFree.\n\n  Fixpoint bind {E : Effect.t} {S : Type} {m : Model.t E S} {A B : Type}\n    (x : t m A) (f : A -> t m B) : t m B :=\n    match x with\n    | Ret x => f x\n    | Call c h => Call c (fun s => bind (h s) f)\n    | Choose x1 x2 => Choose (bind x1 f) (bind x2 f)\n    end.\n\n  Fixpoint join_aux {E : Effect.t} {S : Type} {m : Model.t E S} {B C : Type}\n    (join : S -> t m B -> t m C) (c_x : Effect.command E)\n    (y : t m B) (k : B -> t m C) : t m C :=\n    match y with\n    | Ret y => k y\n    | Call c_y h_y =>\n      Choose\n        (Call c_x (fun s => join s y))\n        (Call c_y (fun s => join_aux join c_x (h_y s) k))\n    | Choose y1 y2 => Choose (join_aux join c_x y1 k) (join_aux join c_x y2 k)\n    end.\n\n  Fixpoint join {E : Effect.t} {S : Type} {m : Model.t E S} {A B C : Type}\n    (x : t m A) (y : t m B) (k : A * B -> t m C) : t m C :=\n    match x with\n    | Ret x => bind y (fun y => k (x, y))\n    | Call c_x h_x => join_aux (fun s y => join (h_x s) y k) c_x y (fun y => bind x (fun x => k (x, y)))\n    | Choose x1 x2 => Choose (join x1 y k) (join x2 y k)\n    end.\n\n  Fixpoint compile {E : Effect.t} {S : Type} (m : Model.t E S) {A B : Type}\n    (x : C.t E A) : (A -> t m B) -> t m B :=\n    match x with\n    | C.Ret _ x => fun k => k x\n    | C.Call c => fun k => Call c (fun s => k (Model.answer m c s))\n    | C.Let _ _ x f => fun k => compile m x (fun x => compile m (f x) k)\n    | C.Join  _ _ x y => fun k => join (compile m x Ret) (compile m y Ret) k\n    end.\n\n  Lemma ok {E : Effect.t} {S : Type} (m : Model.t E S) {A : Type} (x : C.t E A)\n    (s : S) : DeadLockFree.t (compile m x Ret) s -> C.DeadLockFree.t m x s.\n  Qed.\nEnd M.\n\nModule ClosedCall.\n  Record t {E : Effect.t} {S : Type} (m : Model.t E S) (T : Type) := New {\n    c : Effect.command E;\n    s : S;\n    h : T }.\n  Arguments New {E S m T} _ _ _.\n  Arguments c {E S m T} _.\n  Arguments s {E S m T} _.\n  Arguments h {E S m T} _.\nEnd ClosedCall.\n\n(** We link the states. *)\nModule ClosedM.\n  Inductive t {E : Effect.t} {S : Type} (m : Model.t E S) (A : Type) : Type :=\n  | Ret : A -> t m A\n  | Call : Tree.t (ClosedCall.t m (t m A)) -> t m A.\n  Arguments Ret {E S m A} _.\n  Arguments Call {E S m A} _.\n\n  Fixpoint compile {E : Effect.t} {S : Type} {m : Model.t E S} {A : Type}\n    (x : M.t m A) (s : S) : t m A :=\n    let fix compiles (tree : Tree.t (Call.t m (M.t m A)))\n      : Tree.t (ClosedCall.t m (t m A)) :=\n      match tree with\n      | Tree.Leaf (Call.New c h) =>\n        Tree.Leaf (ClosedCall.New c s (compile (h s) (Model.state m c s)))\n      | Tree.Node tree1 tree2 => Tree.Node (compiles tree1) (compiles tree2)\n      end in\n    match x with\n    | M.Ret x => Ret x\n    | M.Call tree => Call (compiles tree)\n    end.\n\n  Definition of_C {E : Effect.t} {S : Type} (m : Model.t E S) {A : Type}\n    (x : C.t E A) (s : S) : t m A :=\n    compile (M.compile x) s.\n\n  Module Tree.\n    Module NotStuck.\n      Inductive t {E : Effect.t} {S : Type} {m : Model.t E S} {A : Type}\n        : Tree.t (ClosedCall.t m (ClosedM.t m A)) -> Prop :=\n      | Leaf : forall c s h, Model.condition m c s ->\n        t (Tree.Leaf (ClosedCall.New c s h))\n      | NodeLeft : forall tree1 tree2, t tree1 -> t (Tree.Node tree1 tree2)\n      | NodeRight : forall tree1 tree2, t tree2 -> t (Tree.Node tree1 tree2).\n    End NotStuck.\n\n    Module ForAll.\n      Inductive t {E : Effect.t} {S : Type} {m : Model.t E S} {A : Type}\n        (P : ClosedM.t m A -> Prop)\n        : Tree.t (ClosedCall.t m (ClosedM.t m A)) -> Prop :=\n      | Leaf : forall c s h, (Model.condition m c s -> P h) ->\n        t P (Tree.Leaf (ClosedCall.New c s h))\n      | Node : forall tree1 tree2, t P tree1 -> t P tree2 ->\n        t P (Tree.Node tree1 tree2).\n    End ForAll.\n  End Tree.\nEnd ClosedM.\n\nModule Progress.\n  Inductive t {E : Effect.t} {S : Type} {m : Model.t E S} {A : Type}\n    : ClosedM.t m A -> Prop :=\n  | Ret : forall x, t (ClosedM.Ret x)\n  | Call : forall tree,\n    ClosedM.Tree.NotStuck.t tree -> ClosedM.Tree.ForAll.t t tree ->\n    t (ClosedM.Call tree).\n\n  Definition of_C {E : Effect.t} {S : Type} (m : Model.t E S) {A : Type}\n    (x : C.t E A) (s : S) : Prop :=\n    t (ClosedM.of_C m x s).\nEnd Progress.\n\n(** Try to solve automatically the [Progress.t] predicate. *)\nModule Solve.\n  Module Tree.\n    Fixpoint not_stuck {E : Effect.t} {S : Type} {m : Model.t E S} {A : Type}\n      (dec : Effect.command E -> S -> bool)\n      (tree : Tree.t (ClosedCall.t m (ClosedM.t m A))) : bool :=\n      match tree with\n      | Tree.Leaf (ClosedCall.New c s h) => dec c s\n      | Tree.Node tree1 tree2 => orb (not_stuck dec tree1) (not_stuck dec tree2)\n      end.\n\n    Fixpoint not_stuck_ok {E : Effect.t} {S : Type} {m : Model.t E S} {A : Type}\n      {dec : Effect.command E -> S -> bool}\n      (dec_ok : forall c s, dec c s = true -> Model.condition m c s)\n      (tree : Tree.t (ClosedCall.t m (ClosedM.t m A)))\n      : not_stuck dec tree = true -> ClosedM.Tree.NotStuck.t tree.\n      intro H.\n      destruct tree as [call | tree1 tree2].\n      - destruct call as [c s h].\n        apply ClosedM.Tree.NotStuck.Leaf.\n        now apply dec_ok.\n      - destruct (orb_prop _ _ H).\n        + apply ClosedM.Tree.NotStuck.NodeLeft.\n          now apply not_stuck_ok with (dec := dec).\n        + apply ClosedM.Tree.NotStuck.NodeRight.\n          now apply not_stuck_ok with (dec := dec).\n    Qed.\n  End Tree.\n\n  Fixpoint solve {E : Effect.t} {S : Type} {m : Model.t E S} {A : Type}\n    (dec : Effect.command E -> S -> bool) (x : ClosedM.t m A)\n    : option (Tree.t (ClosedCall.t m (ClosedM.t m A))) :=\n    let fix for_all (tree : Tree.t (ClosedCall.t m (ClosedM.t m A)))\n      : option (Tree.t (ClosedCall.t m (ClosedM.t m A))) :=\n      match tree with\n      | Tree.Leaf (ClosedCall.New c s h) =>\n        if dec c s then\n          solve dec h\n        else\n          None\n      | Tree.Node tree1 tree2 =>\n        match for_all tree1 with\n        | None => for_all tree2\n        | Some err => Some err\n        end\n      end in\n    match x with\n    | ClosedM.Ret _ => None\n    | ClosedM.Call tree =>\n      if Tree.not_stuck dec tree then\n        for_all tree\n      else\n        Some tree\n    end.\n\n  (*Fixpoint solve_ok {E : Effect.t} {S : Type} {m : Model.t E S} {A : Type}\n    {dec : Effect.command E -> S -> bool}\n    (dec_true_ok : forall c s, dec c s = true -> Model.condition m c s)\n    (dec_false_ok : forall c s, dec c s = false -> ~ Model.condition m c s)\n    (x : ClosedM.t m A) : solve dec x = None -> Progress.t x.\n    intro H.\n    destruct x as [x | tree].\n    - apply Progress.Ret.\n    - assert (H_not_stuck : Tree.not_stuck dec tree = true) by (\n        case_eq (Tree.not_stuck dec tree); trivial;\n        intro Heq; simpl in H; rewrite Heq in H; congruence).\n      apply Progress.Call.\n      + now apply (Tree.not_stuck_ok dec_true_ok).\n      + refine (\n          let fix for_all t : Tree.not_stuck dec t = true ->\n            ClosedM.Tree.ForAll.t Progress.t t := _ in\n          for_all tree H_not_stuck).\n        intro H_t_not_stuck.\n        destruct t as [call | t1 t2].\n        * destruct call as [c s h].\n          apply ClosedM.Tree.ForAll.Leaf.\n          case_eq (dec c s); intros H_dec H_condition.\n          apply solve_ok with (dec := dec); trivial.\n          ++ intro.\n            apply solve_ok with (dec := dec); trivial.\n            apply dec_true_ok.\n          \n    refine (\n      let fix for_all (tree : Tree.t (ClosedCall.t m (ClosedM.t m A)))\n        : ClosedM.Tree.ForAll.t Progress.t tree := _ in _).\n    - destruct tree as [call | tree1 tree2].\n      + destruct call as [c s h].\n        apply ClosedM.Tree.ForAll.Leaf.\n        case_eq (dec c s); intro H_dec.\n        * intro.\n          apply solve_ok with (dec := dec); trivial.\n          apply dec_true_ok.\n    -\n  Qed.*)\n\n  Fixpoint solve_ok {E : Effect.t} {S : Type} {m : Model.t E S} {A : Type}\n    {dec : Effect.command E -> S -> bool}\n    (dec_true_ok : forall c s, dec c s = true -> Model.condition m c s)\n    (dec_false_ok : forall c s, dec c s = false -> ~ Model.condition m c s)\n    (x : ClosedM.t m A) : solve dec x = None -> Progress.t x.\n  Admitted.\n\n  (*Fixpoint solve {E : Effect.t} {S : Type} {m : Model.t E S} {A : Type}\n    (dec : forall c s, option (Model.condition m c s))\n    (dec_not : forall c s, option (~ Model.condition m c s))\n    (x : ClosedM.t m A)\n    : Progress.t x + Tree.t (ClosedCall.t m (ClosedM.t m A)) :=\n    let fix for_all (tree : Tree.t (ClosedCall.t m (ClosedM.t m A)))\n      : ClosedM.Tree.ForAll.t Progress.t tree + _ :=\n      match tree with\n      | Tree.Leaf (ClosedCall.New c s h) =>\n        match dec_not c s with\n        | Some H_not =>\n          inl (ClosedM.Tree.ForAll.Leaf Progress.t c s h (fun H =>\n            match H_not H with end))\n        | None =>\n          Sum.bind (solve dec dec_not h) (fun H =>\n          inl (ClosedM.Tree.ForAll.Leaf Progress.t c s h (fun _ => H)))\n        end\n      | Tree.Node tree1 tree2 =>\n        Sum.bind (for_all tree1) (fun H1 =>\n        Sum.bind (for_all tree2) (fun H2 =>\n        inl (ClosedM.Tree.ForAll.Node Progress.t tree1 tree2 H1 H2)))\n      end in\n    match x with\n    | ClosedM.Ret x => inl (Progress.Ret x)\n    | ClosedM.Call tree =>\n      match Tree.not_stuck dec tree with\n      | Some H_not_stuck =>\n        Sum.bind (for_all tree) (fun H_for_all =>\n        inl (Progress.Call tree H_not_stuck H_for_all))\n      | None => inr tree\n      end\n    end.*)\nEnd Solve.\n\nModule Lock.\n  Definition S := bool.\n\n  Module Command.\n    Inductive t :=\n    | Lock\n    | Unlock.\n  End Command.\n\n  Definition E : Effect.t :=\n    Effect.New Command.t (fun _ => unit).\n\n  Definition lock : C.t E unit :=\n    call E Command.Lock.\n\n  Definition unlock : C.t E unit :=\n    call E Command.Unlock.\n\n  Module Condition.\n    Inductive t : Effect.command E -> S -> Prop :=\n    | Lock : t Command.Lock false\n    | Unlock : t Command.Unlock true.\n  End Condition.\n\n  Definition answer (c : Effect.command E) (s : S) : Effect.answer E c :=\n    tt.\n\n  Definition state (c : Effect.command E) (s : S) : S :=\n    match c with\n    | Command.Lock => true\n    | Command.Unlock => false\n    end.\n\n  Definition m : Model.t E S :=\n    Model.New Condition.t answer state.\n\n  Definition dec (c : Effect.command E) (s : S) : bool :=\n    match (c, s) with\n    | (Command.Lock, false) | (Command.Unlock, true) => true\n    | (Command.Lock, true) | (Command.Unlock, false) => false\n    end.\n\n  Definition dec_true_ok (c : Effect.command E) (s : S)\n    : dec c s = true -> Model.condition m c s.\n  Admitted.\n\n  Definition dec_false_ok (c : Effect.command E) (s : S)\n    : dec c s = false -> ~ Model.condition m c s.\n  Admitted.\n\n  Lemma solve_ok {A : Type} (x : C.t E A) (s : S)\n    : Solve.solve dec (ClosedM.of_C m x s) = None -> Progress.of_C m x s.\n    apply Solve.solve_ok.\n    - exact dec_true_ok.\n    - exact dec_false_ok.\n  Qed.\n\n  Definition ex1 : C.t E unit :=\n    do! lock in\n    unlock.\n\n  (*Compute (M.compile (m := m) ex1).\n  Compute (ClosedM.compile (M.compile (m := m) ex1) false).*)\n\n  Lemma ex1_progress : Progress.of_C m ex1 false.\n    now apply solve_ok.\n  Qed.\n\n  Definition ex2 : C.t E (nat * nat) :=\n    join (ret 3) (ret 4).\n\n  (*Compute (M.compile (m := m) ex2).\n  Compute (ClosedM.compile (M.compile (m := m) ex2) false).*)\n\n  Lemma ex2_progress : Progress.of_C m ex2 false.\n    now apply solve_ok.\n  Qed.\n\n  Definition ex3 : C.t E (nat * unit) :=\n    join (ret 3) (\n      do! lock in\n      unlock).\n\n  (*Compute (M.compile (m := m) ex3).\n  Compute (ClosedM.compile (M.compile (m := m) ex3) false).*)\n\n  Lemma ex3_progress : Progress.of_C m ex3 false.\n    now apply solve_ok.\n  Qed.\n\n  Definition ex4 : C.t E (unit * unit) :=\n    join (do! lock in unlock) (do! lock in unlock).\n\n  (*Compute (M.compile (m := m) ex4).\n  Compute (ClosedM.compile (M.compile (m := m) ex4) false).*)\n\n  Lemma ex4_progress : Progress.of_C m ex4 false.\n    now apply solve_ok.\n  Qed.\n\n  Fixpoint ex5 (n : nat) : C.t E unit :=\n    match n with\n    | O => ret tt\n    | Datatypes.S n =>\n      let! _ : unit * unit := join (do! lock in unlock) (ex5 n) in\n      ret tt\n    end.\n\n  Lemma ex5_progress_0 : Progress.of_C m (ex5 0) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex5_progress_1 : Progress.of_C m (ex5 1) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex5_progress_2 : Progress.of_C m (ex5 2) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex5_progress_3 : Progress.of_C m (ex5 3) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex5_progress_4 : Progress.of_C m (ex5 4) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex5_progress_5 : Progress.of_C m (ex5 5) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex5_progress_6 : Progress.of_C m (ex5 6) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex5_progress_7 : Progress.of_C m (ex5 7) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Fixpoint ex6 (n : nat) : C.t E nat :=\n    match n with\n    | O => ret 0\n    | Datatypes.S n' =>\n      let! sv : nat * nat :=\n        join (ex6 n') (\n          do! lock in\n          let v := n in\n          do! unlock in\n          ret v) in\n      let (s, v) := sv in\n      ret (s + v)\n    end.\n\n  Lemma ex6_progress_0 : Progress.of_C m (ex6 0) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex6_progress_1 : Progress.of_C m (ex6 1) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex6_progress_2 : Progress.of_C m (ex6 2) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex6_progress_3 : Progress.of_C m (ex6 3) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex6_progress_4 : Progress.of_C m (ex6 4) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex6_progress_5 : Progress.of_C m (ex6 5) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex6_progress_6 : Progress.of_C m (ex6 6) false.\n    Time now apply solve_ok.\n  Qed.\n\n  Lemma ex6_progress_7 : Progress.of_C m (ex6 7) false.\n    Time now apply solve_ok.\n  Qed.\nEnd Lock.*)\n", "meta": {"author": "coq-io", "repo": "experiments", "sha": "e013e45484996652e01607ff66f210d6c3b2fc55", "save_path": "github-repos/coq/coq-io-experiments", "path": "github-repos/coq/coq-io-experiments/experiments-e013e45484996652e01607ff66f210d6c3b2fc55/src/ConstraintSmallSteps.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2248064136900575}}
{"text": "(** * Functors involving coproduct categories *)\nRequire Import Category.Sum Functor.Core Functor.Composition.Core Functor.Identity.\nRequire Import Functor.Paths HoTT.Tactics Types.Forall.\nRequire Import Basics.Tactics.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\n(** We save [inl] and [inr] so we can use them to refer to the functors, too.  Outside of the [Categories/] directory, they should always be referred to as [Functor.inl] and [Functor.inr], after a [Require Functor].  Outside of this file, but in the [Categories/] directory, if you do not want to depend on all of [Functor] (for e.g., speed reasons), they should be referred to as [Functor.Sum.inl] and [Functor.Sum.inr] after a [Require Functor.Sum]. *)\nLocal Notation type_inl := inl.\nLocal Notation type_inr := inr.\n\n(** ** Injections [inl : C → C + D] and [inr : D → C + D] *)\nSection sum_functors.\n  Variables C D : PreCategory.\n\n  Definition inl : Functor C (C + D)\n    := Build_Functor C (C + D)\n                     (@inl _ _)\n                     (fun _ _ m => m)\n                     (fun _ _ _ _ _ => idpath)\n                     (fun _ => idpath).\n\n  Definition inr : Functor D (C + D)\n    := Build_Functor D (C + D)\n                     (@inr _ _)\n                     (fun _ _ m => m)\n                     (fun _ _ _ _ _ => idpath)\n                     (fun _ => idpath).\nEnd sum_functors.\n\n(** ** Coproduct of functors [F + F' : C + C' → D] *)\nSection sum.\n  Variables C C' D : PreCategory.\n\n  Definition sum (F : Functor C D) (F' : Functor C' D)\n  : Functor (C + C') D.\n  Proof.\n    refine (Build_Functor\n              (C + C') D\n              (fun cc'\n               => match cc' with\n                    | type_inl c => F c\n                    | type_inr c' => F' c'\n                  end)\n              (fun s d\n               => match s, d with\n                    | type_inl cs, type_inl cd\n                      => fun m : morphism _ cs cd => F _1 m\n                    | type_inr c's, type_inr c'd\n                      => fun m : morphism _ c's c'd => F' _1 m\n                    | _, _ => fun m => match m with end\n                  end%morphism)\n              _\n              _);\n    abstract (\n        repeat (intros [] || intro);\n        simpl in *;\n          auto with functor\n      ).\n  Defined.\nEnd sum.\n\n(** ** swap : [C + D → D + C] *)\nSection swap_functor.\n  Definition swap C D\n  : Functor (C + D) (D + C)\n    := sum (inr _ _) (inl _ _).\n\n  Local Open Scope functor_scope.\n\n  Definition swap_involutive_helper {C D} c\n  : (swap C D) ((swap D C) c)\n    = c\n    := match c with type_inl _ => idpath | type_inr _ => idpath end.\n\n  Lemma swap_involutive `{Funext} C D\n  : swap C D o swap D C = 1.\n  Proof.\n    path_functor.\n    exists (path_forall _ _ swap_involutive_helper).\n    repeat (apply (@path_forall _); intro).\n    repeat match goal with\n               | [ |- context[transport (fun x' => forall y, @?C x' y) ?p ?f ?x] ]\n                 => simpl rewrite (@transport_forall_constant _ _ C _ _ p f x)\n           end.\n    transport_path_forall_hammer.\n      by repeat match goal with\n                  | [ H : Empty |- _ ] => destruct H\n                  | [ H : (_ + _)%type |- _ ] => destruct H\n                  | _ => progress hnf in *\n                end.\n  Qed.\nEnd swap_functor.\n\nModule Export FunctorSumNotations.\n  Notation \"F + G\" := (sum F G) : functor_scope.\nEnd FunctorSumNotations.\n", "meta": {"author": "HoTT", "repo": "Coq-HoTT", "sha": "ab70acd360367dbda13d537748f792384fb882a3", "save_path": "github-repos/coq/HoTT-Coq-HoTT", "path": "github-repos/coq/HoTT-Coq-HoTT/Coq-HoTT-ab70acd360367dbda13d537748f792384fb882a3/theories/Categories/Functor/Sum.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.22477000297728497}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Recognition of combined operations, addressing modes and conditions\n  during the [CSE] phase. *)\n\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import CSEdomain.\nRequire Import CombineOp.\n\nSection COMBINE.\n\nVariable ge: genv.\nVariable sp: val.\nVariable m: mem.\nVariable get: valnum -> option rhs.\nVariable valu: valnum -> val.\nHypothesis get_sound: forall v rhs, get v = Some rhs -> rhs_eval_to valu ge sp m rhs (valu v).\n\nLemma get_op_sound:\n  forall v op vl, get v = Some (Op op vl) -> eval_operation ge sp op (map valu vl) m = Some (valu v).\nProof.\n  intros. exploit get_sound; eauto. intros REV; inv REV; auto.\nQed.\n\nLtac UseGetSound :=\n  match goal with\n  | [ H: get _ = Some _ |- _ ] =>\n      let x := fresh \"EQ\" in (generalize (get_op_sound _ _ _ H); intros x; simpl in x; FuncInv)\n  end.\n\nLemma combine_compimm_ne_0_sound:\n  forall x cond args,\n  combine_compimm_ne_0 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Cne (valu x) (Vint Int.zero) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Cne (valu x) (Vint Int.zero).\nProof.\n  intros until args. functional induction (combine_compimm_ne_0 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  destruct (eval_condition cond (map valu args) m); simpl; auto. destruct b; auto.\nQed.\n\nLemma combine_compimm_eq_0_sound:\n  forall x cond args,\n  combine_compimm_eq_0 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Ceq (valu x) (Vint Int.zero) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Ceq (valu x) (Vint Int.zero).\nProof.\n  intros until args. functional induction (combine_compimm_eq_0 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  rewrite eval_negate_condition.\n  destruct (eval_condition c (map valu args) m); simpl; auto. destruct b; auto.\nQed.\n\nLemma combine_compimm_eq_1_sound:\n  forall x cond args,\n  combine_compimm_eq_1 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Ceq (valu x) (Vint Int.one) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Ceq (valu x) (Vint Int.one).\nProof.\n  intros until args. functional induction (combine_compimm_eq_1 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  destruct (eval_condition cond (map valu args) m); simpl; auto. destruct b; auto.\nQed.\n\nLemma combine_compimm_ne_1_sound:\n  forall x cond args,\n  combine_compimm_ne_1 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Cne (valu x) (Vint Int.one) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Cne (valu x) (Vint Int.one).\nProof.\n  intros until args. functional induction (combine_compimm_ne_1 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  rewrite eval_negate_condition.\n  destruct (eval_condition c (map valu args) m); simpl; auto. destruct b; auto.\nQed.\n\nTheorem combine_cond_sound:\n  forall cond args cond' args',\n  combine_cond get cond args = Some(cond', args') ->\n  eval_condition cond' (map valu args') m = eval_condition cond (map valu args) m.\nProof.\n  intros. functional inversion H; subst.\n  (* compimm ne zero *)\n  simpl; eapply combine_compimm_ne_0_sound; eauto.\n  (* compimm ne one *)\n  simpl; eapply combine_compimm_ne_1_sound; eauto.\n  (* compimm eq zero *)\n  simpl; eapply combine_compimm_eq_0_sound; eauto.\n  (* compimm eq one *)\n  simpl; eapply combine_compimm_eq_1_sound; eauto.\n  (* compuimm ne zero *)\n  simpl; eapply combine_compimm_ne_0_sound; eauto.\n  (* compuimm ne one *)\n  simpl; eapply combine_compimm_ne_1_sound; eauto.\n  (* compuimm eq zero *)\n  simpl; eapply combine_compimm_eq_0_sound; eauto.\n  (* compuimm eq one *)\n  simpl; eapply combine_compimm_eq_1_sound; eauto.\nQed.\n\nTheorem combine_addr_sound:\n  forall addr args addr' args',\n  combine_addr get addr args = Some(addr', args') ->\n  eval_addressing ge sp addr' (map valu args') = eval_addressing ge sp addr (map valu args).\nProof.\n  intros. functional inversion H; subst.\n  (* indexed - addimm *)\n  UseGetSound. simpl. rewrite <- H0. rewrite Val.add_assoc. auto.\nQed.\n\nTheorem combine_op_sound:\n  forall op args op' args',\n  combine_op get op args = Some(op', args') ->\n  eval_operation ge sp op' (map valu args') m = eval_operation ge sp op (map valu args) m.\nProof.\n  intros. functional inversion H; subst.\n(* addimm - addimm *)\n  UseGetSound. FuncInv. simpl.\n  rewrite <- H0. rewrite Val.add_assoc. auto.\n(* addimm - subimm *)\nOpaque Val.sub.\n  UseGetSound. FuncInv. simpl.\n  change (Vint (Int.add m0 n)) with (Val.add (Vint m0) (Vint n)).\n  rewrite <- H0. rewrite Val.sub_add_l. auto.\n(* subimm - addimm *)\n  UseGetSound. FuncInv. simpl. rewrite <- H0.\nTransparent Val.sub.\n  destruct v; simpl; auto. repeat rewrite Int.sub_add_opp. rewrite Int.add_assoc.\n  rewrite Int.neg_add_distr. decEq. decEq. decEq. apply Int.add_commut.\n(* andimm - andimm *)\n  UseGetSound; simpl.\n  generalize (Int.eq_spec p m0); rewrite H7; intros.\n  rewrite <- H0. rewrite Val.and_assoc. simpl. fold p. rewrite H1. auto.\n  UseGetSound; simpl.\n  rewrite <- H0. rewrite Val.and_assoc. auto.\n(* orimm - orimm *)\n  UseGetSound. simpl. rewrite <- H0. rewrite Val.or_assoc. auto.\n(* xorimm - xorimm *)\n  UseGetSound. simpl. rewrite <- H0. rewrite Val.xor_assoc. auto.\n(* cmp *)\n  simpl. decEq; decEq. eapply combine_cond_sound; eauto.\nQed.\n\nEnd COMBINE.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/compcert/arm/CombineOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.22477000297728497}}
{"text": "(*|\n=================================\nDenotation of [ccs] into [ctree]s\n=================================\n\n.. coq:: none\n|*)\n\nFrom Coq Require Export\n     List\n     Strings.String.\nFrom Coq Require Import RelationClasses Program.\n\nFrom RelationAlgebra Require Import\n     monoid\n     kat\n     kat_tac\n     prop\n     rel\n     srel\n     comparisons\n     rewriting\n     normalisation.\n\nFrom CTreeCCS Require Import\n     Syntax.\n\nFrom CTree Require Import Head.\nFrom CTree Require Import\n     CTree\n     Eq\n     Eq.SBisim\n     Interp.Fold\n     Interp.FoldCTree.\n\nImport CTree.\n\nImport CTreeNotations.\nOpen Scope ctree_scope.\n\n(*|\nEvent signature\n---------------\nProcesses must at least be able to perform actions.\nWe do not encode tau steps as events but rather directly as\nunary visible br nodes.\n|*)\n\nVariant ActionE : Type -> Type :=\n  | Act (a : action) : ActionE unit.\n\nNotation ccsE := ActionE.\nNotation ccsC := (B0 +' B1 +' B2 +' B3 +' B4).\n\nDefinition ccsT' T := ctree' ccsE ccsC T.\nDefinition ccsT := ctree ccsE ccsC.\n\nDefinition ccs' := ccsT' void.\nDefinition ccs  := ccsT void.\n\nDefinition comm a : label := obs (Act a) tt.\n\n(*| Process algebra |*)\nSection Combinators.\n\n  Definition nil : ccs := stuckS.\n\n  Definition prefix (a : action) (P: ccs) : ccs :=\n    trigger (Act a);; P.\n\n  Definition plus (P Q : ccs) : ccs := brD2 P Q.\n  \n  (* Stuck? Failure event? *)\n  Definition h_new (c : chan) : ActionE ~> ctree ccsE ccsC :=\n    fun _ e => let '(Act a) := e in\n            match a with\n            | Send c'\n            | Rcv c' =>\n                if (c =? c')%string then stuckD else trigger e\n            end.\n  #[global] Arguments h_new c [T] _.\n\n  Definition new : chan -> ccs -> ccs :=\n    fun c P => interp (h_new c) P.\n\n  Definition para : ccs -> ccs -> ccs :=\n    cofix F (P : ccs) (Q : ccs) :=\n      brD3\n        (rP <- head P;;\n         match rP with\n         | ARet rP => match rP with end\n         | ABr c kP => BrS c (fun i => F (kP i) Q)\n         | AVis e kP => Vis e (fun i => F (kP i) Q)\n         end)\n\n        (rQ <- head Q;;\n         match rQ with\n         | ARet rQ => match rQ with end\n         | ABr c kQ => BrS c (fun i => F P (kQ i))\n         | AVis e kQ => Vis e (fun i => F P (kQ i))\n         end)\n\n        (rP <- head P;;\n         rQ <- head Q;;\n         match rP, rQ with\n         | AVis eP kP, AVis eQ kQ =>\n             match eP, kP, eQ, kQ with\n             | Act a, kP, Act b, kQ =>\n                 if are_opposite a b\n                 then\n                   Step (F (kP tt) (kQ tt))\n                 else\n                   stuckD\n             end\n         | _, _ => stuckD\n         end).\n\n(*|\nWe would like to define [bang] directly as in the following.\nUnfortunately, it is not syntactically guarded and convincing Coq\nseems challenging.\nWe therefore instead define a more general function [parabang] expressing\nat once the parallel composition of a process [p] with a server of [q].\nThe usual [bang p] is then defined as [parabang p p].\n|*)\n  Fail Definition bang : ccs -> ccs :=\n    cofix bang (p : ccs ) : ccs := para (bang p) p.\n\n  Definition parabang : ccs -> ccs -> ccs :=\n    cofix pB (p : ccs) (q:ccs) : ccs :=\n      brD4\n        (* Communication by p *)\n        (rp <- head p;;\n         match rp with\n         | ARet rp => match rp with end\n         | ABr c kp => BrS c (fun i =>  pB (kp i) q )\n         | AVis e kp => Vis e (fun i => pB (kp i) q)\n         end)\n\n        (* Communication by a fresh copy of q *)\n        (rq <- head q;;\n         match rq with\n         | ARet rq => match rq with end\n         | ABr c kq => BrS c (fun i => (pB  (para p (kq i)) q))\n         | AVis e kq => Vis e (fun i => (pB  (para p (kq i)) q))\n         end)\n\n        (* Communication between p and a fresh copy of q *)\n        (rp <- head p;;\n         rq <- head q;;\n         match rp, rq with\n         | AVis ep kp, AVis eq kq =>\n             match ep, kp, eq, kq with\n             | Act a, kp, Act b, kq =>\n                 if are_opposite a b\n                 then\n                   Step (pB (para (kp tt) (kq tt)) q)\n                 else\n                   stuckD\n             end\n\n         | _, _ => stuckD\n         end)\n\n        (* Communication between two fresh copies of q *)\n        (rq1 <- head q;;\n         rq2 <- head q;;\n         match rq1, rq2 with\n         | AVis eq1 kq1, AVis eq2 kq2 =>\n             match eq1, kq1, eq2, kq2 with\n             | Act a, kq1, Act b, kq2 =>\n                 if are_opposite a b\n                 then\n                   Step (pB (para p (para (kq1 tt) (kq2 tt))) q)\n                 else\n                   stuckD\n             end\n\n         | _, _ => stuckD\n         end).\n\n  Definition bang (P : ccs) : ccs := parabang P P.\n\nEnd Combinators.\n\nModule CCSNotationsSem.\n\n  Declare Scope ccs_scope.\n\n  Notation \"0\" := nil: ccs_scope.\n  Infix \"+\" := plus (at level 50, left associativity) : ccs_scope.\n  (* Infix \"∥\" := communicating (at level 29, left associativity). *)\n  Infix \"∥\" := para (at level 29, left associativity) : ccs_scope.\n  Notation \"! x\" := (bang x) : ccs_scope.\n\nEnd CCSNotationsSem.\n\nImport CCSNotationsSem.\nOpen Scope ccs_scope.\n\n(** TODO: Move these to [SSim.v] ? *)\n#[global] Instance equ_clos_sb_goal {E X} RR :\n  Proper (equ eq ==> equ eq ==> flip impl)\n         (@sb E E ccsC ccsC X X _ _ eq RR).\nProof.\n  cbn; unfold Proper, respectful; intros * eq1 * eq2 bis.\n  destruct bis as [F B]; cbn in *.\n  split.\n  + intros ? ? TR.\n    rewrite eq1 in TR.\n    apply F in TR as (l1 & y1 & TR & ? & ->).\n    do 2 eexists.\n    rewrite eq2; eauto.\n  + intros ? ? TR.\n    rewrite eq2 in TR.\n    apply B in TR as (l1 & y1 & TR & ? & <-).\n    do 2 eexists.\n    rewrite eq1; eauto.\nQed.\n\n#[global] Instance equ_clos_sb_ctx {E X} RR :\n  Proper (gfp (@fequ E ccsC X X eq) ==> equ eq ==> impl)\n         (@sb E E ccsC ccsC X X _ _ eq RR).\nProof.\n  cbn; unfold Proper, respectful; intros * eq1 * eq2 bis.\n  destruct bis as [F B]; cbn in *.\n  split.\n  + intros ? ? TR.\n    rewrite <- eq1 in TR.\n    apply F in TR as (l1 & y1 & TR & ? & ->).\n    do 2 eexists.\n    rewrite <- eq2; eauto.\n  + intros ? ? TR.\n    rewrite <- eq2 in TR.\n    apply B in TR as (l1 & y1 & TR & ? & <-).\n    do 2 eexists.\n    rewrite <- eq1; eauto.\nQed.\n\nLemma trans_prefix_inv : forall l a p p',\n    trans l (prefix a p) p' ->\n    p' ≅ p /\\ l = comm a.\nProof.\n  intros * tr.\n  apply trans_trigger_inv in tr as (? & ? & ->).\n  destruct x; split; auto.\nQed.\n\nLemma trans_prefix : forall a p,\n    trans (comm a) (prefix a p) p.\nProof.\n  intros; eapply trans_trigger.\nQed.\n\n(** TODO: Hm should probably recover [Symmetric] for [st eq] *)\n(** ** prefix *)\nLemma ctx_prefix_st a: unary_ctx (prefix a) <= st eq.\nProof.\n  apply Coinduction, by_Symmetry. apply unary_sym.\n  rewrite <-b_T.\n  intro R. apply (leq_unary_ctx (prefix a)). intros p q Hpq.\n  intros l p' pp'.\n  apply trans_prefix_inv in pp' as (EQ & ->).\n  do 2 eexists; split.\n  apply trans_prefix.\n  rewrite EQ; auto.\nQed.\n\n(** ** prefix *)\nLemma ctx_prefix_tequ a: unary_ctx (prefix a) <= (et eq).\nProof.\n  apply Coinduction.\n  intro R.\n  apply (leq_unary_ctx (prefix a)).\n  intros p q Hpq.\n  cbn in *.\n  constructor.\n  intros [].\n  fold (@bind ccsE _ _ _ (Ret tt) (fun _ => p)).\n  fold (@bind ccsE _ _ _ (Ret tt) (fun _ => q)).\n  rewrite 2 unfold_bind; cbn.\n  apply (b_T (fequ eq)).\n  apply Hpq.\nQed.\n\n#[global] Instance prefix_st a: forall R, Proper (st eq R ==> st eq R) (prefix a) := unary_proper_t (@ctx_prefix_st a).\n\n#[global] Instance prefix_tequ a: forall R, Proper (et eq R ==> et eq R) (prefix a) := unary_proper_t (@ctx_prefix_tequ a).\n\nDefinition can_comm (c : chan) (a : @label ccsE) : bool :=\n  match a with\n  | obs (Act a) _ =>\n      match a with\n      | Send c'\n      | Rcv c' => if (c =? c')%string then false else true\n      end\n  | _ => true\n  end.\n\nLemma trans_trigger_inv' : forall {E C X} `{B0 -< C} (e : E X) l u,\n\t\ttrans l (trigger e : ctree E C X) u ->\n    exists x, u ≅ Ret x /\\ l = obs e x.\nProof.\n  intros * TR.\n  unfold trigger in TR.\n  now apply trans_vis_inv in TR.\nQed.\n\nLemma trans_hnew_inv : forall a l c p,\n    trans l (h_new c (Act a)) p ->\n    l = obs (Act a) tt /\\ can_comm c l /\\ p ≅ Ret tt.\nProof.\n  intros * tr.\n  cbn in *; destruct a; cbn in *; destruct (c =? c0) eqn:comm; cbn in *.\n  all : try now eapply stuckD_is_stuck in tr.\n  all: unfold can_comm; apply trans_trigger_inv' in tr as ([] & ? & ?); subst; rewrite comm; eauto.\nQed.\n\nLemma trans_vis' {E C R X} `{B0 -< C} : forall (e : E X) x (k : X -> ctree E C R) u,\n    u ≅ k x ->\n    trans (obs e x) (Vis e k) u.\nProof.\n  intros * eq; rewrite eq; apply trans_vis.\nQed.\n\nLemma new_guard : forall c t, new c (Guard t) ≅ Guard (Guard (new c t)).\nProof.  \n  intros; unfold new; now rewrite interp_guard.\nQed.\n\n#[global] Instance new_equ c :\n  Proper (equ eq ==> equ eq) (new c).\nProof.\n  apply interp_equ.\nQed.\n\nLemma trans_new : forall l c p p',\n    trans l p p' ->\n    can_comm c l = true ->\n    exists q, trans l (new c p) q /\\ q ~ new c p'.\nProof.\n  intros * tr comm.\n  do 3 red in tr.\n  genobs p obsp; genobs p' op'.\n  revert p p' Heqobsp Heqop'.\n  induction tr; intros.\n  - edestruct IHtr as (q & tr' & eq); eauto.\n    exists q; split; auto.\n    unfold new; rewrite unfold_interp, <- Heqobsp.\n    cbn; unfold Utils.mbr, MonadBr_ctree, branch.\n    eapply trans_bind_r with x.\n    eapply trans_brD; [|reflexivity].\n    apply trans_ret.\n    apply trans_guard.\n    apply tr'.\n  - eexists; split.\n    unfold new; rewrite unfold_interp, <- Heqobsp.\n    cbn; unfold Utils.mbr, MonadBr_ctree, branch.\n    eapply trans_bind_l.\n    intros abs; inv abs.\n    apply trans_brS with (x := x).\n    rewrite bind_ret_l, sb_guard.\n    rewrite H.\n    unfold new. rewrite unfold_interp.\n    rewrite <- Heqop', <- unfold_interp.\n    reflexivity.\n  - destruct e, a.\n    all: cbn in *; destruct (c =? c0) eqn:comm'; inv comm.\n    + eexists; split.\n      unfold new; rewrite unfold_interp, <- Heqobsp.\n      cbn; unfold Utils.mbr, MonadBr_ctree, branch.\n      eapply trans_bind_l.\n      intros abs; inv abs.\n      rewrite comm'.\n      unfold trigger.\n      eapply trans_vis'.\n      reflexivity.\n      rewrite bind_ret_l, sb_guard, H.\n      unfold new. \n      rewrite unfold_interp.\n      rewrite <- Heqop', <- unfold_interp.\n      reflexivity.\n    + eexists; split.\n      unfold new; rewrite unfold_interp, <- Heqobsp.\n      cbn; unfold Utils.mbr, MonadBr_ctree, branch.\n      eapply trans_bind_l.\n      intros abs; inv abs.\n      rewrite comm'.\n      unfold trigger.\n      eapply trans_vis'.\n      reflexivity.\n      rewrite bind_ret_l, sb_guard, H.\n      unfold new.\n      rewrite unfold_interp.\n      rewrite <- Heqop', <- unfold_interp.\n      reflexivity.\n  - tauto.\nQed.\n\nLemma trans_new_inv_aux : forall l T U,\n    trans_ l T U ->\n    forall c p q,\n      (go T ≅ new c p \\/ go T ≅ Guard (new c p)) ->\n      go U ≅ q ->\n      exists q', can_comm c l = true /\\ trans l p q' /\\ q ≅ Guard (new c q').\nProof.\n  intros * tr c.\n  induction tr; intros * EQ1 EQ2; try destruct c2.\n  - destruct EQ1 as [EQ1 | EQ1].\n    + unfold new in EQ1; rewrite unfold_interp in EQ1.\n      unfold trans, transR.\n      cbn.\n      desobs p; try now step in EQ1; inv EQ1.\n      * destruct e,a; cbn in *.\n        ** destruct (c =? c1); cbn in *.\n           *** step in EQ1; dependent induction EQ1; inv x0.\n           *** step in EQ1; inv EQ1.\n        ** destruct (c =? c1); cbn in *.\n           *** step in EQ1; dependent induction EQ1; inv x0.\n           *** step in EQ1; inv EQ1.\n      * cbn in EQ1.\n        destruct vis; try now step in EQ1; inv EQ1.\n        unfold Utils.mbr, MonadBr_ctree, branch in EQ1.\n        cbn in * |-.\n        rewrite unfold_bind in EQ1; cbn in EQ1.\n        inv_equ. rename EQ into eqx.\n        specialize (eqx x).\n        cbn in * |-; rewrite bind_ret_l in eqx.\n        setoid_rewrite <- ctree_eta in IHtr.\n        setoid_rewrite eqx in IHtr.\n        edestruct (IHtr (k0 x)) as (q' & comm & tr' & EQ); [right; reflexivity | reflexivity |].\n        exists q'; repeat split; auto.\n        eapply trans_brD with (x := x).\n        eauto.\n        reflexivity.\n        rewrite <- EQ, EQ2; auto.\n    + inv_equ. rename EQ into eqx.\n      specialize (eqx x).\n      edestruct IHtr as (q' & comm & tr' & EQ); [| eassumption |].\n      left. rewrite eqx, <- ctree_eta; reflexivity.\n      exists q'; repeat split; auto.\n  - destruct EQ1 as [EQ1 | EQ1]; [ | step in EQ1; dependent induction EQ1].\n    unfold new in EQ1; rewrite unfold_interp in EQ1.\n    unfold trans,transR; cbn.\n    desobs p; try now step in EQ1; inv EQ1.\n    + cbn in *.\n      destruct e,a; cbn in *; destruct (c =? c1) eqn:EQ; step in EQ1; dependent induction EQ1.\n    + cbn in *.\n      unfold Utils.mbr, MonadBr_ctree, branch in EQ1.\n      destruct vis; try now step in EQ1; inv EQ1.\n      rewrite unfold_bind in EQ1; cbn in EQ1.\n      inv_equ. rename EQ into eqx.\n      specialize (eqx x).\n      rewrite bind_ret_l in eqx.\n      rewrite H in eqx.\n      rewrite <- ctree_eta in EQ2.\n      rewrite EQ2 in eqx.\n      clear k t EQ2 H.\n      exists (k0 x); repeat split.\n      apply trans_brS.\n      auto.\n  - destruct EQ1 as [EQ1 | EQ1]; [ | step in EQ1; inv EQ1].\n    unfold new in EQ1; rewrite unfold_interp in EQ1.\n    unfold trans,transR; cbn.\n    desobs p; try now step in EQ1; inv EQ1.\n    cbn in *.\n    destruct e0,a; cbn in *; destruct (c =? c0) eqn:EQ; try now step in EQ1; inv EQ1.\n    all:unfold trigger in EQ1; rewrite unfold_bind in EQ1; cbn in EQ1; setoid_rewrite bind_ret_l in EQ1.\n    all: inv_equ; rename EQ0 into eqx.\n    all:rewrite EQ.\n    all:specialize (eqx x).\n    all:rewrite H in eqx; rewrite <- ctree_eta in EQ2; rewrite EQ2 in eqx.\n    all: exists (k0 x); repeat split; auto.\n    all: apply trans_vis.\n  - tauto.\nQed.\n\nLemma trans_new_inv : forall l c p p',\n    trans l (new c p) p' ->\n    exists q, can_comm c l = true /\\ trans l p q /\\ p' ≅ Guard (new c q).\nProof.\n  intros; eapply trans_new_inv_aux. eapply H.\n  all: rewrite <- ctree_eta; auto.\nQed.\n\nLemma trans_new_inv' : forall l c p p',\n    trans l (new c p) p' ->\n    exists q, can_comm c l = true /\\ trans l p q /\\ p' ~ new c q.\nProof.\n  intros; edestruct trans_new_inv as (? & ? & ? & ?); eauto.\n  eexists; repeat split; eauto.\n  rewrite H2, sb_guard; reflexivity.\nQed.\n\n(** ** name restriction *)\nLemma ctx_new_st a: unary_ctx (new a) <= st eq.\nProof.\n  apply Coinduction, by_Symmetry. apply unary_sym.\n  intro R. apply (leq_unary_ctx (new a)). intros p q Hpq l p0 Hp0.\n  apply trans_new_inv in Hp0 as (? & comm & tr & EQ).\n  destruct (proj1 Hpq _ _ tr) as (? & ? & TR & ? & ->).\n  eapply trans_new in TR as (q' & tr' & eq'); eauto.\n  eexists; exists q'; eauto.\n  split; [|split]; eauto.  \n  rewrite EQ.\n  rewrite eq'.\n  rewrite sb_guard.\n  apply unary_proper_Tctx, (id_T (sb eq)).\n  auto.\nQed.\n\n#[global] Instance new_st a: forall R, Proper (st eq R ==> st eq R) (new a) := unary_proper_t (@ctx_new_st a).\n\nLemma trans_plus_inv : forall l p q r,\n    trans l (p + q) r ->\n    (exists p', trans l p p' /\\ r ≅ p') \\/\n      (exists q', trans l q q' /\\ r ≅ q').\nProof.\n  intros * tr.\n  apply trans_brD_inv in tr as ([|] & tr); eauto.\nQed.\n\nLemma trans_brS' {E C X Y} `{B0 -< C} : forall (c : C Y) (k : Y -> ctree E C X) x u,\n    u ≅ k x ->\n\t\ttrans tau (BrS c k) u.\nProof.\n  intros * eq; rewrite eq; apply trans_brS.\nQed.\n\nLemma trans_plusL : forall l p p' q,\n    trans l p p' ->\n    trans l (p + q) p'.\nProof.\n  intros * tr.\n  now apply trans_brD21.\nQed.\n\nLemma trans_plusR : forall l p q q',\n    trans l q q' ->\n    trans l (p + q) q'.\nProof.\n  intros * tr.\n  now apply trans_brD22.\nQed.\n\n(** ** br *)\nLemma ctx_plus_t: binary_ctx plus <= st eq.\nProof.\n  apply Coinduction, by_Symmetry. apply binary_sym.\n  intro R. apply (leq_binary_ctx plus).\n  intros * [F1 B1] * [F2 B2] ? * tr.\n  apply trans_plus_inv in tr as [(? & tr & EQ) | (? & tr & EQ)].\n  - apply F1 in tr as [? (? & tr & ? & ->)].\n    do 2 eexists; split; [|split].\n    apply trans_plusL; eauto.\n    rewrite EQ.\n    now apply (id_T (sb eq)).\n    reflexivity.\n  - apply F2 in tr as [? (? & tr & ? & <-)].\n    do 2 eexists; split; [|split].\n    apply trans_plusR; eauto.\n    rewrite EQ.\n    now apply (id_T (sb eq)).\n    reflexivity.\nQed.\n\n#[global] Instance plus_t:\n  forall R, Proper (st eq R ==> st eq R ==> st eq R) plus := binary_proper_t ctx_plus_t.\n\nNotation para_ p q :=\n  (brD3\n     (rp <- head p;;\n      match rp with\n      | ARet rp => match rp with end\n      | ABr c kp => BrS c (fun i => para (kp i) q)\n      | AVis e kp => Vis e (fun i => para (kp i) q)\n      end)\n\n     (rq <- head q;;\n      match rq with\n      | ARet rq => match rq with end\n      | ABr c kq => BrS c (fun i => para p (kq i))\n      | AVis e kq => Vis e (fun i => para p (kq i))\n      end)\n\n     (rp <- head p;;\n      rq <- head q;;\n      match rp, rq with\n      | AVis ep kp, AVis eq kq =>\n          match ep, kp, eq, kq with\n          | Act a, kp, Act b, kq =>\n              if are_opposite a b\n              then\n                Step (para (kp tt) (kq tt))\n              else\n                stuckD\n          end\n      | _, _ => stuckD\n      end))%ctree.\n\nLemma unfold_para : forall p q, para p q ≅ para_ p q.\nProof.\n  intros.\n  now step.\nQed.\n\n#[global] Instance para_equ :\n  Proper (equ eq ==> equ eq ==> equ eq) para.\nProof.\n  unfold Proper, respectful.\n  coinduction R CIH.\n  intros p1 p2 EQp q1 q2 EQq.\n  rewrite 2 unfold_para.\n  constructor.\n  intros i.\n  destruct i.\n  - upto_bind; [apply head_equ; auto | intros hdp1 hdp2 eqp].\n    inv eqp; auto.\n    step; constructor; auto.\n    step; constructor; auto.\n  - upto_bind; [apply head_equ; auto | intros hdp1 hdp2 eqp].\n    inv eqp; auto.\n    step; constructor; auto.\n    step; constructor; auto.\n  - upto_bind; [apply head_equ; auto | intros hdp1 hdp2 eqp].\n    upto_bind; [apply head_equ; auto | intros hdq1 hdq2 eqq].\n    inv eqp; auto.\n    inv eqq; auto.\n    destruct e, e0, (are_opposite a a0); auto.\n    step; constructor; auto.\nQed.\n\nLemma trans_paraSynch : forall a b (p p' q q' : ccs),\n    trans (comm a) p p' ->\n    trans (comm b) q q' ->\n    are_opposite a b ->\n    trans tau (p ∥ q) (p' ∥ q').\nProof.\n  intros * TRp TRq Op.\n  apply trans_head in TRp as (kp & TRp & Eqp).\n  apply trans_head in TRq as (kq & TRq & Eqq).\n  rewrite unfold_para.\n  apply trans_brD33.\n  eapply trans_bind_r; [apply TRp |].\n  eapply trans_bind_r; [apply TRq |].\n  cbn; rewrite Op.\n  rewrite Eqp, Eqq.\n  apply trans_step.\nQed.\n\nLemma trans_paraL :\n  forall l (p p' q : ccs),\n    trans l p p' ->\n    trans l (p ∥ q) (p' ∥ q).\nProof.\n  intros * TRp.\n  rewrite unfold_para.\n  apply trans_brD31.\n  destruct l.\n  - apply trans_head in TRp.\n    destruct TRp as (? & ? & ? & ? & TRp & Eqp).\n    eapply trans_bind_r; eauto; cbn.\n    econstructor.\n    rewrite Eqp; reflexivity.\n  - apply trans_head in TRp.\n    destruct TRp as (? & TRp & Eqp).\n    eapply trans_bind_r; eauto; cbn.\n    constructor.\n    rewrite Eqp; reflexivity.\n  - pose proof (trans_val_invT TRp); subst; easy.\nQed.\n\nLemma trans_paraR :\n  forall l (p q q' : ccs),\n    trans l q q' ->\n    trans l (p ∥ q) (p ∥ q').\nProof.\n  intros * TRq.\n  rewrite unfold_para.\n  apply trans_brD32.\n  destruct l.\n  - apply trans_head in TRq.\n    destruct TRq as (? & ? & ? & ? & TRq & Eqq).\n    eapply trans_bind_r; eauto; cbn.\n    econstructor.\n    rewrite Eqq; reflexivity.\n  - apply trans_head in TRq.\n    destruct TRq as (? & TRq & Eqq).\n    eapply trans_bind_r; eauto; cbn.\n    constructor.\n    rewrite Eqq; reflexivity.\n  - pose proof (trans_val_invT TRq); subst; easy.\nQed.\n\nLemma trans_para_inv :\n  forall l p q r,\n    trans l (p ∥ q) r ->\n    (exists p', trans l p p' /\\ r ≅ (p' ∥ q)) \\/\n      (exists q', trans l q q' /\\ r ≅ (p ∥ q')) \\/\n      (exists p' q' a b,\n          trans (comm a) p p' /\\\n            trans (comm b) q q' /\\\n            are_opposite a b /\\\n            l = tau /\\\n            r ≅ (p' ∥ q')).\nProof.\n  intros * TR.\n  rewrite unfold_para in TR.\n  apply trans_brD_inv in TR as (x & TR).\n  destruct x.\n  - left.\n    edestruct @trans_bind_inv; [apply TR | | ]; clear TR.\n    destruct H as (NOTV & ? & TR & EQ); apply trans_head_inv in TR; easy.\n    destruct H as (hdp & TRhdp & TR).\n    destruct hdp; try easy.\n    * apply trans_brS_inv in TR as (x & EQ & ->).\n      eapply trans_ABr in TRhdp.\n      eexists; split; eauto.\n    * apply trans_vis_inv in TR as (x & EQ & ->).\n      eapply trans_AVis in TRhdp.\n      eexists; split; eauto.\n  - right; left.\n    edestruct @trans_bind_inv; [apply TR | | ]; clear TR.\n    destruct H as (NOTV & ? & TR & EQ); apply trans_head_inv in TR; easy.\n    destruct H as (hdq & TRhdq & TR).\n    destruct hdq; try easy.\n    * apply trans_brS_inv in TR as (x & EQ & ->).\n      eapply trans_ABr in TRhdq.\n      eexists; split; eauto.\n    * apply trans_vis_inv in TR as (x & EQ & ->).\n      eapply trans_AVis in TRhdq.\n      eexists; split; eauto.\n  - right; right.\n    edestruct @trans_bind_inv; [apply TR | | ]; clear TR.\n    destruct H as (NOTV & ? & TR & EQ); apply trans_head_inv in TR; easy.\n    destruct H as (hdp & TRhdp & TR).\n    edestruct @trans_bind_inv; [apply TR | | ]; clear TR.\n    destruct H as (NOTV & ? & TR & EQ); apply trans_head_inv in TR; easy.\n    destruct H as (hdq & TRhdq & TR).\n    destruct hdp; try easy.\n    exfalso; eapply stuckD_is_stuck; eassumption.\n    destruct hdq; try easy.\n    exfalso; eapply stuckD_is_stuck; eassumption.\n    destruct e, e0, (are_opposite a a0) eqn:?.\n    2:exfalso; eapply stuckD_is_stuck; eassumption.\n    apply trans_step_inv in TR as [? ->].\n    eapply trans_AVis in TRhdp.\n    eapply trans_AVis in TRhdq.\n    do 4 eexists.\n    repeat split; eauto.\nQed.\n\nLtac trans_para_invT H :=\n  apply trans_para_inv in H as\n      [(?p' & ?TRp & ?EQ) |\n        [(?q' & ?TRq & ?EQ) |\n          (?p' & ?q' & ?a & ?b & ?TRp & ?TRq & ?Op & ? & ?EQ) ]]; subst.\n\n(** ** parallel composition *)\nLemma ctx_para_t: binary_ctx para <= st eq.\nProof.\n  apply Coinduction, by_Symmetry. apply binary_sym.\n  intro R. apply (leq_binary_ctx para).\n  intros * [F1 B1] * [F2 B2] ? * tr.\n  trans_para_invT tr.\n  - apply F1 in TRp as [? (? & tr & ? & ?)].\n    do 2 eexists; split; [|split].\n    apply trans_paraL; eauto.\n    rewrite EQ.\n    apply (fTf_Tf (sb eq)). apply (in_binary_ctx para).\n    now apply (id_T (sb eq)).\n    now apply (b_T (sb eq)).\n    assumption.\n  - apply F2 in TRq as [? (? & tr & ? & ?)].\n    do 2 eexists; split; [|split].\n    apply trans_paraR; eauto.\n    rewrite EQ.\n    apply (fTf_Tf (sb eq)). apply (in_binary_ctx para).\n    now apply (b_T (sb eq)).\n    now apply (id_T (sb eq)).\n    assumption.\n  - apply F1 in TRp as [? (? & trp & ? & <-)].\n    apply F2 in TRq as [? (? & trq & ? & <-)].\n    do 2 eexists; split; [|split].\n    eapply trans_paraSynch; eauto.\n    rewrite EQ.\n    apply (fTf_Tf (sb eq)). apply (in_binary_ctx para); now apply (id_T (sb eq)).\n    reflexivity.\nQed.\n\n#[global] Instance para_t: forall R, Proper (st eq R ==> st eq R ==> st eq R) para :=\n  binary_proper_t ctx_para_t.\n\n#[global] Instance para_T f: forall R, Proper (sT eq f R ==> sT eq f R ==> sT eq f R) para :=\n  binary_proper_T ctx_para_t.\n\nSection Theory.\n\n  Lemma plsC: forall (p q : ccs), p+q ~ q+p.\n  Proof.\n    apply brD2_commut.\n  Qed.\n\n  Lemma plsA (p q r : ccs): p+(q+r) ~ (p+q)+r.\n  Proof.\n    symmetry; apply brD2_assoc.\n  Qed.\n\n  Lemma pls0p (p : ccs) : 0 + p ~ p.\n  Proof.\n    apply brD2_stuckS_l.\n  Qed.\n\n  Lemma plsp0 (p : ccs) : p + 0 ~ p.\n  Proof. now rewrite plsC, pls0p. Qed.\n\n  Lemma plsidem (p : ccs) : p + p ~ p.\n  Proof.\n    apply brD2_idem.\n  Qed.\n\n  #[global] Instance are_opposite_sym : Symmetric are_opposite.\n  Proof.\n    unfold are_opposite, eqb_action, op; cbn.\n    intros [] [] Op; intuition.\n    all:rewrite eqb_sym; auto.\n  Qed.\n\n  Lemma paraC: forall (p q : ccs), p ∥ q ~ q ∥ p.\n  Proof.\n    coinduction ? CIH; symmetric using idtac.\n    intros p q l r.\n    eauto.\n    simpl.\n    intros p q ? ? tr.\n    trans_para_invT tr.\n    - do 2 eexists; split; [|split].\n      eapply trans_paraR; eauto.\n      rewrite EQ; auto.\n      reflexivity.\n    - do 2 eexists; split; [|split].\n      eapply trans_paraL; eauto.\n      rewrite EQ; auto.\n      reflexivity.\n    - do 2 eexists; split; [|split].\n      eapply trans_paraSynch; eauto.\n      symmetry; auto.\n      rewrite EQ; auto.\n      reflexivity.\n  Qed.\n\n  Lemma para0p : forall (p : ccs), 0 ∥ p ~ p.\n  Proof.\n    coinduction R CIH.\n    intros.\n    split.\n    - intros l q tr.\n      trans_para_invT tr; try now exfalso; eapply stuckS_is_stuck; eauto.\n      do 2 eexists; split; eauto.\n      rewrite EQ; auto.\n    - intros l q tr.\n      eexists.\n      exists (0 ∥ q).\n      split; eauto with trans.\n      apply trans_paraR; eauto.\n      cbn; auto.\n  Qed.\n\n  Lemma parap0 : forall (p : ccs), p ∥ 0 ~ p.\n  Proof.\n    intros; rewrite paraC; apply para0p.\n  Qed.\n\n  Lemma paraA : forall (p q r : ccs), p ∥ (q ∥ r) ~ (p ∥ q) ∥ r.\n  Proof.\n    coinduction ? CIH; intros.\n    split.\n    - intros l s tr.\n      trans_para_invT tr.\n      + do 2 eexists; split.\n        do 2 apply trans_paraL; eauto.\n        rewrite EQ; auto.\n      + trans_para_invT TRq.\n        * do 2 eexists; split.\n          apply trans_paraL, trans_paraR; eauto.\n          rewrite EQ, EQ0; auto.\n        * do 2 eexists; split.\n          apply trans_paraR; eauto.\n          rewrite EQ, EQ0; auto.\n        * do 2 eexists; split.\n          eapply trans_paraSynch; eauto.\n          eapply trans_paraR; eauto.\n          rewrite EQ, EQ0; auto.\n      + trans_para_invT TRq.\n        * do 2 eexists; split.\n          eapply trans_paraL, trans_paraSynch; eauto.\n          rewrite EQ, EQ0; auto.\n        * do 2 eexists; split.\n          eapply trans_paraSynch; eauto.\n          eapply trans_paraL; eauto.\n          rewrite EQ, EQ0; auto.\n        * inv H.\n    - intros l s tr; cbn.\n      trans_para_invT tr.\n      + trans_para_invT TRp.\n        * do 2 eexists; split.\n          apply trans_paraL; eauto.\n          rewrite EQ, EQ0; auto.\n        * do 2 eexists; split.\n          apply trans_paraR, trans_paraL; eauto.\n          rewrite EQ, EQ0; auto.\n        * do 2 eexists; split.\n          eapply trans_paraSynch; eauto.\n          eapply trans_paraL; eauto.\n          rewrite EQ, EQ0; auto.\n      + do 2 eexists; split.\n        eapply trans_paraR, trans_paraR; eauto.\n        rewrite EQ; auto.\n      + trans_para_invT TRp.\n        * do 2 eexists; split.\n          eapply trans_paraSynch; eauto.\n          eapply trans_paraR; eauto.\n          rewrite EQ, EQ0; auto.\n        * do 2 eexists; split.\n          eapply trans_paraR, trans_paraSynch; eauto.\n          rewrite EQ, EQ0; auto.\n        * inv H.\n  Qed.\n\nEnd Theory.\n\nNotation parabang_ p q :=\n  (brD4\n\n     (* Communication by p *)\n     (rp <- head p;;\n      match rp with\n      | ARet rp => match rp with end\n      | ABr c kp => BrS c (fun i => parabang (kp i) q )\n      | AVis e kp => Vis e (fun i => parabang (kp i) q)\n      end)\n\n     (* Communication by a fresh copy of q *)\n     (rq <- head q;;\n      match rq with\n      | ARet rq => match rq with end\n      | ABr c kq => BrS c (fun i => (parabang (para p (kq i)) q))\n      | AVis e kq => Vis e (fun i => (parabang (para p (kq i)) q))\n      end)\n\n     (* Communication between p and a fresh copy of q *)\n     (rp <- head p;;\n      rq <- head q;;\n      match rp, rq with\n      | AVis ep kp, AVis eq kq =>\n          match ep, kp, eq, kq with\n          | Act a, kp, Act b, kq =>\n              if are_opposite a b\n              then\n                Step (parabang (para (kp tt) (kq tt)) q)\n              else\n                stuckD\n          end\n\n      | _, _ => stuckD\n      end)\n\n     (* Communication between two fresh copies of q *)\n     (rq1 <- head q;;\n      rq2 <- head q;;\n      match rq1, rq2 with\n      | AVis eq1 kq1, AVis eq2 kq2 =>\n          match eq1, kq1, eq2, kq2 with\n          | Act a, kq1, Act b, kq2 =>\n              if are_opposite a b\n              then\n                Step (parabang (para p (para (kq1 tt) (kq2 tt))) q)\n              else\n                stuckD\n          end\n\n      | _, _ => stuckD\n      end))%ctree.\n\nLemma unfold_parabang : forall p q, parabang p q ≅ parabang_ p q.\nProof.\n  intros.\n  now step.\nQed.\n\nLemma unfold_bang : forall p, !p ≅ parabang_ p p.\nProof.\n  intros; unfold bang. apply unfold_parabang.\nQed.\n\n#[global] Instance parabang_equ :\n  Proper (equ eq ==> equ eq ==> equ eq) parabang.\nProof.\n  unfold Proper, respectful.\n  coinduction R CIH.\n  intros p1 p2 EQp q1 q2 EQq.\n  rewrite 2 unfold_parabang.\n  constructor.\n  intros i.\n\n  destruct i.\n  - upto_bind; [apply head_equ; auto | intros hdp1 hdp2 eqp].\n    inv eqp; auto.\n    step; constructor; auto.\n    step; constructor; auto.\n  - upto_bind; [apply head_equ; auto | intros hdp1 hdp2 eqp].\n    inv eqp; auto.\n    step; constructor; intros ?.\n    apply CIH; auto; rewrite EQp, H; reflexivity.\n    step; constructor; intros ?.\n    apply CIH; auto; rewrite EQp, H; reflexivity.\n  - upto_bind; [apply head_equ; auto | intros hdp1 hdp2 eqp].\n    upto_bind; [apply head_equ; auto | intros hdq1 hdq2 eqq].\n    inv eqp; auto.\n    inv eqq; auto.\n    destruct e, e0, (are_opposite a a0); auto.\n    step; constructor; intros ?.\n    apply CIH; auto.\n    rewrite H,H0; reflexivity.\n  - upto_bind; [apply head_equ; auto | intros hdp1 hdp2 eqp].\n    upto_bind; [apply head_equ; auto | intros hdq1 hdq2 eqq].\n    inv eqp; auto.\n    inv eqq; auto.\n    destruct e, e0, (are_opposite a a0); auto.\n    step; constructor; intros ?.\n    apply CIH; auto.\n    rewrite EQp, H,H0; reflexivity.\nQed.\n\nLemma trans_parabangL : forall p l p' q,\n    trans l p p' ->\n    trans l (parabang p q) (parabang p' q).\nProof.\n  intros * TR.\n  pose proof trans_head TR.\n  rewrite unfold_parabang.\n  apply trans_brD41.\n  destruct l;\n    repeat match goal with\n           | h : Logic.ex _ |- _ => destruct h\n           | h : Logic.and _ _ |- _ => destruct h\n           end.\n  - eapply trans_bind_r; eauto. cbn.\n    rewrite H0; econstructor; reflexivity.\n  - eapply trans_bind_r; eauto. cbn.\n    rewrite H0; econstructor; reflexivity.\n  - apply trans_val_invT in TR; subst; easy.\nQed.\n\nLemma trans_parabangR : forall p l q q',\n    trans l q q' ->\n    trans l (parabang p q) (parabang (p ∥ q') q).\nProof.\n  intros * TR.\n  pose proof trans_head TR.\n  rewrite unfold_parabang.\n  apply trans_brD42.\n  destruct l;\n    repeat match goal with\n           | h : Logic.ex _ |- _ => destruct h\n           | h : Logic.and _ _ |- _ => destruct h\n           end.\n  - eapply trans_bind_r; eauto. cbn.\n    econstructor; rewrite H0; reflexivity.\n  - eapply trans_bind_r; eauto. cbn.\n    rewrite H0; econstructor; reflexivity.\n  - apply trans_val_invT in TR; subst; easy.\nQed.\n\nLemma trans_parabangSL : forall a b p p' q q',\n    are_opposite a b ->\n    trans (comm a) p p' ->\n    trans (comm b) q q' ->\n    trans tau (parabang p q) (parabang (p' ∥ q') q).\nProof.\n  intros * Op TR1 TR2.\n  pose proof trans_head TR1 as (? & TRh1 & EQ1).\n  pose proof trans_head TR2 as (? & TRh2 & EQ2).\n  rewrite unfold_parabang.\n  apply trans_brD43.\n  eapply trans_bind_r; [apply TRh1 | ].\n  eapply trans_bind_r; [apply TRh2 | ].\n  cbn; rewrite Op.\n  rewrite EQ1,EQ2.\n  apply trans_step.\nQed.\n\nLemma trans_parabangSR : forall a b p q q' q'',\n    are_opposite a b ->\n    trans (comm a) q q' ->\n    trans (comm b) q q'' ->\n    trans tau (parabang p q) (parabang (p ∥ (q' ∥ q'')) q).\nProof.\n  intros * Op TR1 TR2.\n  pose proof trans_head TR1 as (? & TRh1 & EQ1).\n  pose proof trans_head TR2 as (? & TRh2 & EQ2).\n  rewrite unfold_parabang.\n  apply trans_brD44.\n  eapply trans_bind_r; [apply TRh1 | ].\n  eapply trans_bind_r; [apply TRh2 | ].\n  cbn; rewrite Op.\n  rewrite EQ1,EQ2.\n  apply trans_step.\nQed.\n\nLemma trans_parabang_inv : forall l p q r,\n    trans l (parabang p q) r ->\n    (exists p', trans l p p' /\\ r ≅ parabang p' q) \\/\n      (exists q', trans l q q' /\\ r ≅ parabang (p ∥ q') q) \\/\n      (exists a b p' q', trans (comm a) p p' /\\\n                      trans (comm b) q q' /\\\n                      are_opposite a b /\\\n                      l = tau /\\\n                      r ≅ parabang (p' ∥ q') q) \\/\n      (exists a b q' q'', trans (comm a) q q' /\\\n                       trans (comm b) q q'' /\\\n                       are_opposite a b /\\\n                       l = tau /\\\n                       r ≅ parabang (p ∥ (q' ∥ q'')) q).\nProof.\n  intros * TR.\n  rewrite unfold_parabang in TR.\n  apply trans_brD_inv in TR as [[]  TR].\n  - left.\n    apply trans_bind_inv in TR.\n    destruct TR as [(NV & ? & TR & ?) | (? & TR1 & TR2)]; [apply trans_head_inv in TR; easy|].\n    destruct x; try easy.\n    apply trans_brS_inv in TR2 as (x & EQ & ->).\n    pose proof trans_ABr TR1 x.\n    eauto.\n    apply trans_vis_inv in TR2 as (x & EQ & ->).\n    pose proof trans_AVis TR1 (i := x).\n    eauto.\n  - right; left.\n    apply trans_bind_inv in TR.\n    destruct TR as [(NV & ? & TR & ?) | (? & TR1 & TR2)]; [apply trans_head_inv in TR; easy|].\n    destruct x; try easy.\n    apply trans_brS_inv in TR2 as (x & EQ & ->).\n    pose proof trans_ABr TR1 x.\n    eauto.\n    apply trans_vis_inv in TR2 as (x & EQ & ->).\n    pose proof trans_AVis TR1 (i := x).\n    eauto.\n  - right; right; left.\n    apply trans_bind_inv in TR.\n    destruct TR as [(NV & ? & TR & ?) | (? & TR1 & TR2)]; [apply trans_head_inv in TR; easy|].\n    apply trans_bind_inv in TR2.\n\n    destruct TR2 as [(NV & ? & TR & ?) | (? & TR2 & TR3)]; [apply trans_head_inv in TR; easy|].\n    destruct x, x0; try easy; try now (exfalso; eapply stuckD_is_stuck; eauto).\n    destruct e, e0, (are_opposite a a0) eqn:?; try easy; try now (exfalso; eapply stuckD_is_stuck; eauto).\n    apply trans_step_inv in TR3 as (? & ->).\n    pose proof trans_AVis TR1 (i := tt).\n    pose proof trans_AVis TR2 (i := tt).\n    eauto 10.\n  - right; right; right.\n    apply trans_bind_inv in TR.\n    destruct TR as [(NV & ? & TR & ?) | (? & TR1 & TR2)]; [apply trans_head_inv in TR; easy|].\n    apply trans_bind_inv in TR2.\n    destruct TR2 as [(NV & ? & TR & ?) | (? & TR2 & TR3)]; [apply trans_head_inv in TR; easy|].\n    destruct x, x0; try easy; try now (exfalso; eapply stuckD_is_stuck; eauto).\n    destruct e, e0, (are_opposite a a0) eqn:?; try easy; try now (exfalso; eapply stuckD_is_stuck; eauto).\n    apply trans_step_inv in TR3 as (? & ->).\n    pose proof trans_AVis TR1 (i := tt).\n    pose proof trans_AVis TR2 (i := tt).\n    eauto 10.\nQed.\n\nLtac trans_parabang_invT TR :=\n  apply trans_parabang_inv in TR as\n      [(?p' & ?TRp' & ?EQ) |\n        [(?q' & ?TRq' & ?EQ) |\n          [(?a & ?b & ?p' & ?q' & ?TRp' & ?TRq' & ?Op & ?EQl & ?EQ) |\n            (?a & ?b & ?q' & ?q'' & ?TRq' & ?TRq'' & ?Op & ?EQl & ?EQ)]]]; subst.\n\nLtac pbL := apply trans_parabangL.\nLtac pbR := apply trans_parabangR.\nLtac pbSL := eapply trans_parabangSL.\nLtac pbSR := eapply trans_parabangSR.\n\nLtac pL := apply trans_paraL.\nLtac pR := apply trans_paraR.\nLtac pS := eapply trans_paraSynch.\n\nLemma para_parabang : forall p q r,\n    parabang (p ∥ q) r ~ p ∥ parabang q r.\nProof.\n  coinduction ? CIH.\n  intros; split.\n  - intros l s TR.\n    trans_parabang_invT TR.\n    + trans_para_invT TRp'.\n      * do 2 eexists; split.\n        pL; eauto.\n        rewrite EQ, EQ0; auto.\n      * do 2 eexists; split.\n        pR;pbL; eauto.\n        rewrite EQ,EQ0; auto.\n      * do 2 eexists; split.\n        pS; eauto.\n        pbL; eauto.\n        rewrite EQ,EQ0; auto.\n    + do 2 eexists; split.\n      pR; pbR; eauto.\n      rewrite EQ, !CIH, paraA; auto.\n\n    + trans_para_invT TRp'.\n      * do 2 eexists; split.\n        pS; eauto.\n        pbR; eauto.\n        rewrite EQ,EQ0, !CIH, !paraA; eauto.\n      * do 2 eexists; split.\n        pR; pbSL; eauto.\n        rewrite EQ,EQ0, !CIH, !paraA; eauto.\n      * easy.\n\n    + do 2 eexists; split.\n      pR; pbSR; eauto.\n      rewrite EQ, !CIH, !paraA; eauto.\n\n  - intros l s TR.\n    trans_para_invT TR.\n    + do 2 eexists; split.\n      pbL;pL; eauto.\n      cbn; rewrite EQ; auto.\n\n    + trans_parabang_invT TRq.\n      * do 2 eexists; split.\n        pbL;pR; eauto.\n        cbn; rewrite EQ, EQ0; auto.\n      * do 2 eexists; split.\n        pbR; eauto.\n        cbn; rewrite EQ,EQ0,!CIH,!paraA; auto.\n      * do 2 eexists; split.\n        pbSL; eauto.\n        pR; eauto.\n        cbn; rewrite EQ,EQ0,!CIH,!paraA; auto.\n      * do 2 eexists; split.\n        pbSR; eauto.\n        cbn; rewrite EQ,EQ0,!CIH,!paraA; auto.\n\n    + trans_parabang_invT TRq.\n      * do 2 eexists; split.\n        pbL;pS; eauto.\n        cbn; rewrite EQ, EQ0; auto.\n      * do 2 eexists; split.\n        pbSL; eauto.\n        pL; eauto.\n        cbn; rewrite EQ,EQ0,!CIH,!paraA; auto.\n      * easy.\n      * easy.\nQed.\n\nLemma ctx_parabang_t: binary_ctx parabang <= st eq.\nProof.\n  apply Coinduction, by_Symmetry. apply binary_sym.\n  intro R. apply (leq_binary_ctx parabang).\n  intros * [F1 B1] * [F2 B2] ? * tr.\n  trans_parabang_invT tr.\n  - apply F1 in TRp' as [? (? & tr & ? & ?)].\n    do 2 eexists; split; [|split].\n    pbL; eauto.\n    rewrite EQ.\n    apply (fTf_Tf (sb eq)). apply (in_binary_ctx parabang).\n    now apply (id_T (sb eq)).\n    now apply (b_T (sb eq)).\n    assumption.\n  - apply F2 in TRq' as [? (? & tr & ? & ?)].\n    do 2 eexists; split; [|split].\n    pbR; eauto.\n    rewrite EQ.\n    apply (fTf_Tf (sb eq)). apply (in_binary_ctx parabang).\n    apply (fT_T ctx_para_t).\n    apply (in_binary_ctx para).\n    now apply (b_T (sb eq)).\n    now apply (id_T (sb eq)).\n    now apply (b_T (sb eq)).\n    assumption.\n  - apply F1 in TRp' as [? (? & trp & ? & <-)].\n    apply F2 in TRq' as [? (? & trq & ? & <-)].\n    do 2 eexists; split; [|split].\n    pbSL; eauto.\n    rewrite EQ.\n    apply (fTf_Tf (sb eq)). apply (in_binary_ctx parabang).\n    apply (fT_T ctx_para_t).\n    apply (in_binary_ctx para).\n    now apply (id_T (sb eq)).\n    now apply (id_T (sb eq)).\n    now apply (b_T (sb eq)).\n    reflexivity.\n  - apply F2 in TRq' as  [? (? & trq' & ? & <-)].\n    apply F2 in TRq'' as  [? (? & trq'' & ? & <-)].\n    do 2 eexists; split; [|split].\n    pbSR; eauto.\n    rewrite EQ.\n    apply (fTf_Tf (sb eq)). apply (in_binary_ctx parabang).\n    apply (fT_T ctx_para_t), (in_binary_ctx para).\n    now apply (b_T (sb eq)).\n    apply (fT_T ctx_para_t), (in_binary_ctx para).\n    now apply (id_T (sb eq)).\n    now apply (id_T (sb eq)).\n    now apply (b_T (sb eq)).\n    reflexivity.\nQed.     \n\n#[global] Instance parabang_t: forall R, Proper (st eq R ==> st eq R ==> st eq R) parabang := binary_proper_t ctx_parabang_t.\n#[global] Instance parabang_T f: forall R, Proper (sT eq f R ==> sT eq f R ==> sT eq f R) parabang := binary_proper_T ctx_parabang_t.\n\nLemma parabang_aux : forall p q,\n    parabang (p ∥ q) q ~ parabang p q.\nProof.\n  coinduction ? CIH.\n  split.\n  - intros l r TR.\n    trans_parabang_invT TR.\n\n    + trans_para_invT TRp'.\n      * do 2 eexists; split.\n        pbL; eauto.\n        rewrite EQ,EQ0; eauto.\n      * do 2 eexists; split.\n        pbR; eauto.\n        rewrite EQ,EQ0; eauto.\n      * do 2 eexists; split.\n        pbSL; eauto.\n        rewrite EQ,EQ0; eauto.\n\n    + do 2 eexists; split.\n      pbR; eauto.\n      rewrite EQ.\n      rewrite <- paraA.\n      rewrite (paraC q).\n      rewrite paraA.\n      auto.\n\n    + trans_para_invT TRp'.\n      * do 2 eexists; split.\n        pbSL; eauto.\n        rewrite EQ, EQ0.\n        rewrite <- paraA.\n        rewrite (paraC q).\n        rewrite paraA.\n        auto.\n      * do 2 eexists; split.\n        pbSR; eauto.\n        rewrite EQ, EQ0.\n        rewrite <- paraA; auto.\n      * easy.\n\n    + do 2 eexists; split.\n      pbSR; eauto.\n      rewrite EQ.\n      rewrite <- paraA.\n      rewrite (paraC q).\n      rewrite ! paraA.\n      auto.\n\n  - intros l p' TR.\n    trans_parabang_invT TR.\n\n    + do 2 eexists; split.\n      pbL;pL; eauto.\n      cbn; rewrite EQ; eauto.\n\n    + do 2 eexists; split.\n      pbL;pR; eauto.\n      cbn; rewrite EQ; eauto.\n\n    + do 2 eexists; split.\n      pbL;pS; eauto.\n      cbn; rewrite EQ; eauto.\n\n    + do 2 eexists; split.\n      pbSL; eauto.\n      pR; eauto.\n      cbn; rewrite EQ, !paraA; eauto.\n\nQed.\n\nLemma parabang_eq : forall p q,\n    parabang p q ~ p ∥ !q.\nProof.\n  coinduction ? CIH.\n  intros p q; split.\n\n  - intros l p' TR.\n    trans_parabang_invT TR.\n\n    + do 2 eexists; split.\n      pL; eauto.\n      rewrite EQ; eauto.\n\n    + do 2 eexists; split.\n      pR; pbL; eauto.\n      rewrite EQ; eauto.\n      rewrite para_parabang; auto.\n\n    + do 2 eexists; split.\n      pS; eauto.\n      pbL; eauto.\n      rewrite EQ; eauto.\n      rewrite para_parabang; auto.\n\n    + do 2 eexists; split.\n      pR; pbSL; eauto.\n      rewrite EQ; eauto.\n      rewrite para_parabang; auto.\n\n  - intros l p' TR.\n    trans_para_invT TR.\n\n    + do 2 eexists; split.\n      pbL; eauto.\n      cbn; rewrite EQ; eauto.\n\n    + trans_parabang_invT TRq.\n      * do 2 eexists; split.\n        pbR; eauto.\n        cbn; rewrite EQ,EQ0; eauto.\n        rewrite !CIH, !paraA; eauto.\n      * do 2 eexists; split.\n        pbR; eauto.\n        cbn; rewrite EQ,EQ0; eauto.\n        rewrite (paraC q), parabang_aux.\n        rewrite !CIH, !paraA; eauto.\n      * do 2 eexists; split.\n        pbSR; eauto.\n        cbn; rewrite EQ,EQ0; eauto.\n        rewrite !CIH, !paraA; eauto.\n      * do 2 eexists; split.\n        pbSR; eauto.\n        cbn; rewrite EQ,EQ0; eauto.\n        rewrite (paraC q), parabang_aux.\n        rewrite !CIH, !paraA; eauto.\n\n    + trans_parabang_invT TRq.\n      * do 2 eexists; split.\n        pbSL; eauto.\n        cbn; rewrite EQ,EQ0; eauto.\n        rewrite !CIH, !paraA; eauto.\n      * do 2 eexists; split.\n        pbSL; eauto.\n        cbn; rewrite EQ,EQ0; eauto.\n        rewrite (paraC q), parabang_aux.\n        rewrite !CIH, !paraA; eauto.\n      * easy.\n      * easy.\nQed.\n\nLemma unfold_bang' : forall p,\n    !p ~ !p ∥ p.\nProof.\n  intros; unfold bang at 1.\n  rewrite parabang_eq. rewrite paraC; reflexivity.\nQed.\n\nImport CCSNotations.\nOpen Scope term_scope.\n\nFixpoint model (t : term) : ccs :=\n\tmatch t with\n\t| 0      => nil\n\t| a · P  => prefix a (model P)\n\t| TauT P => Step (model P)\n\t| P ∥ Q  => para (model P) (model Q)\n\t| P ⊕ Q  => plus (model P) (model Q)\n\t| P ∖ c  => new c (model P)\n\t| !P    => bang (model P)\n\tend.\n\nModule DenNotations.\n\n  (* Notations for patterns *)\n  Notation \"'synchP' e\" := (inl1 e) (at level 10).\n  Notation \"'actP' e\" := (inr1 (inl1 e)) (at level 10).\n  Notation \"'deadP' e\" :=  (inr1 (inr1 e)) (at level 10).\n\n  Notation \"⟦ t ⟧\" := (model t).\n  (* Notation \"P '⊢' a '→ccs' Q\" := (step_ccs P a Q) (at level 50). *)\n  (* Notation \"P '⊢' a '→sem' Q\" := (step_sem P a Q) (at level 50). *)\n\nEnd DenNotations.\n\nImport DenNotations.\n", "meta": {"author": "vellvm", "repo": "ctrees", "sha": "a622bc2e63eaa987e081b862e9aafeea3f8f5d79", "save_path": "github-repos/coq/vellvm-ctrees", "path": "github-repos/coq/vellvm-ctrees/ctrees-a622bc2e63eaa987e081b862e9aafeea3f8f5d79/examples/CCS/Denotation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2247647150700382}}
{"text": "(** * Bicolano: Semantic domains *)\n\n(* <Insert License Here>\n\n    $Id: Domain.v 69 2006-03-06 20:16:11Z davidpichardie $ *)\n\n(** Formalization of Java semantic domain.\n Based on The \"Java (TM) Virtual Machine Specification, Second Edition, \n  Tim Lindholm, Frank Yellin\"\n\n @author David Pichardie, ...  *)\n(* Hendra : - Modified to suit DEX program (removed operand stack).\n            - Removed reference comparison \n            - Also trim the system to contain only Arithmetic *)\n\nRequire Export DEX_Program.\nRequire Export Numeric.\nRequire Export List.\nOpen Scope Z_scope.\n\n(** All semantic domains and basic operation are encapsulated in a module signature *)\n\nModule Type DEX_SEMANTIC_DOMAIN.\n\n (** We depend on the choices done for program data structures *)\n Declare Module DEX_Prog : DEX_PROGRAM. Import DEX_Prog.\n\n Declare Module Byte  : NUMERIC with Definition power := 7%nat.\n Declare Module Short : NUMERIC with Definition power := 15%nat.\n Declare Module Int   : NUMERIC with Definition power := 31%nat.\n\n (** conversion *)\n Parameter b2i : Byte.t -> Int.t.\n Parameter s2i : Short.t -> Int.t. \n Parameter i2b : Int.t -> Byte.t. \n Parameter i2s : Int.t -> Short.t.\n Parameter i2bool : Int.t -> Byte.t.\n\n Inductive DEX_num : Set :=\n   | I : Int.t -> DEX_num\n   | B : Byte.t -> DEX_num\n   | Sh : Short.t -> DEX_num.\n\n (** Location is the domain of adresses in the heap *)\n Parameter DEX_Location : Set.\n Parameter DEX_Location_dec : forall loc1 loc2:DEX_Location,{loc1=loc2}+{~loc1=loc2}.\n\n Inductive DEX_value : Set :=\n   | Num : DEX_num -> DEX_value\n   | Ref: DEX_Location -> DEX_value\n   | Null : DEX_value.\n\n Definition init_value (t:DEX_type) : DEX_value :=\n    match t with\n     | DEX_PrimitiveType _ => Num (I (Int.const 0))\n     | DEX_ReferenceType _ => Null\n    end.\n\n Definition init_field_value (f:DEX_Field) : DEX_value :=\n   match DEX_FIELD.initValue f with\n    | DEX_FIELD.Int z => Num (I (Int.const z))\n    | DEX_FIELD.NULL => Null\n    | DEX_FIELD.UNDEF => init_value (DEX_FIELDSIGNATURE.type (DEX_FIELD.signature f))\n  end.\n \n (** Domain of local variables *)\n Module Type DEX_REGISTERS.\n   Parameter t : Type.\n   Parameter get : t-> DEX_Reg -> option DEX_value.\n   Parameter update : t -> DEX_Reg -> DEX_value -> t.\n   Parameter dom : t -> list DEX_Reg.\n   Parameter get_update_new : forall l x v, get (update l x v) x = Some v.\n   Parameter get_update_old : forall l x y v,\n     x<>y -> get (update l x v) y = get l y.\n End DEX_REGISTERS.\n Declare Module DEX_Registers : DEX_REGISTERS.\n\n Parameter listreg2regs : DEX_Registers.t -> nat -> list DEX_Reg -> DEX_Registers.t.\n\n(* 290415 - Some Notes\n- According to verified DEX bytecode, every registers have\n  to have a value before used. This means we can safely assume\n  that we don't need the update to be option anymore because\n  the only possible case where it updates empty value is when\n  the source is empty, which has been taken care by the assumption\n- The special register ret and ex are assigned the number\n  65536 and 65537 respectively (in binary) because we know\n  that the maximum number of registers is 65535.\n*)\n\n Module Type DEX_HEAP.\n   Parameter t : Type.\n\n   Inductive DEX_AdressingMode : Set :=\n     (*| StaticField : FieldSignature -> AdressingMode*)\n     | DEX_DynamicField : DEX_Location -> DEX_FieldSignature -> DEX_AdressingMode\n     (*| ArrayElement : Location -> Z -> AdressingMode*).\n\n   Inductive DEX_LocationType : Type :=\n     | DEX_LocationObject : DEX_ClassName -> DEX_LocationType  \n     (*| LocationArray : Int.t -> type -> Method*PC -> LocationType*).\n   (** (LocationArray length element_type) *)\n\n   Parameter get : t -> DEX_AdressingMode -> option DEX_value.\n   Parameter update : t -> DEX_AdressingMode -> DEX_value -> t.\n   Parameter typeof : t -> DEX_Location -> option DEX_LocationType.   \n     (** typeof h loc = None -> no object, no array allocated at location loc *)\n   Parameter new : t -> DEX_Program -> DEX_LocationType -> option (DEX_Location * t).\n     (** program is required to compute the size of the allocated element, i.e. to know\n        the Class associated with a ClassName  *)\n\n   (** Compatibility between a heap and an adress *)\n   Inductive Compat (h:t) : DEX_AdressingMode -> Prop :=\n     (*| CompatStatic : forall f,\n         Compat h (StaticField f)*)\n     | CompatObject : forall cn loc f,\n         typeof h loc = Some (DEX_LocationObject cn) ->\n         Compat h (DEX_DynamicField loc f)\n   (*  | CompatArray : forall length tp loc i a,\n         0 <= i < Int.toZ length ->\n         typeof h loc = Some (LocationArray length tp a) ->\n         Compat h (ArrayElement loc i)*).\n\n   Parameter get_update_same : forall h am v, Compat h am ->  get (update h am v) am = Some v.\n   Parameter get_update_old : forall h am1 am2 v, am1<>am2 -> get (update h am1 v) am2 = get h am2.\n   Parameter get_uncompat : forall h am, ~ Compat h am -> get h am = None.\n\n   Parameter typeof_update_same : forall h loc am v,\n     typeof (update h am v) loc = typeof h loc.\n\n   Parameter new_fresh_location : forall (h:t) (p:DEX_Program) \n      (lt:DEX_LocationType) (loc:DEX_Location) (h':t),\n     new h p lt = Some (loc,h') ->\n     typeof h loc = None.\n\n   Parameter new_typeof : forall (h:t) (p:DEX_Program) (lt:DEX_LocationType) (loc:DEX_Location) (h':t),\n     new h p lt = Some (loc,h') ->\n     typeof h' loc = Some lt.\n\n   Parameter new_typeof_old : forall (h:t) (p:DEX_Program) (lt:DEX_LocationType) \n      (loc loc':DEX_Location) (h':t),\n     new h p lt = Some (loc,h') ->\n     loc <> loc' ->\n     typeof h' loc' = typeof h loc'.\n\n   Parameter new_defined_object_field : forall (h:t) (p:DEX_Program) (cn:DEX_ClassName) \n      (fs:DEX_FieldSignature) (f:DEX_Field) (loc:DEX_Location) (h':t),\n     new h p (DEX_LocationObject cn) = Some (loc,h') ->\n     is_defined_field p cn fs f ->\n     get h' (DEX_DynamicField loc fs) = Some (init_field_value f).\n\n   Parameter new_undefined_object_field : forall (h:t) (p:DEX_Program) (cn:DEX_ClassName) \n      (fs:DEX_FieldSignature) (loc:DEX_Location) (h':t),\n     new h p (DEX_LocationObject cn) = Some (loc,h') ->\n     ~ defined_field p cn fs ->\n     get h' (DEX_DynamicField loc fs) = None.\n \n  Parameter new_object_no_change : \n     forall (h:t) (p:DEX_Program) (cn:DEX_ClassName) (loc:DEX_Location) (h':t) (am:DEX_AdressingMode),\n     new h p (DEX_LocationObject cn) = Some (loc,h') ->\n     (forall (fs:DEX_FieldSignature), am <> (DEX_DynamicField loc fs)) ->\n     get h' am = get h am.\n\n(*  Parameter new_valid_array_index : forall (h:t) (p:Program) (length:Int.t) (tp:type) a (i:Z) (loc:Location) (h':t),\n     new h p (LocationArray length tp a) = Some (loc,h') ->\n     0 <= i < Int.toZ length ->\n     get h' (ArrayElement loc i) = Some (init_value tp).\n\n  Parameter new_unvalid_array_index : forall (h:t) (p:Program) (length:Int.t) (tp:type) a (i:Z) (loc:Location) (h':t),\n     new h p (LocationArray length tp a) = Some (loc,h') ->\n     ~ 0 <= i < Int.toZ length ->\n     get h' (ArrayElement loc i) = None.\n\n  Parameter new_array_no_change : \n     forall (h:t) (p:Program) (length:Int.t) (tp:type) a (loc:Location) (h':t) (am:AdressingMode),\n     new h p (LocationArray length tp a) = Some (loc,h') ->\n     (forall (i:Z), am <> (ArrayElement loc i)) ->\n     get h' am = get h am.*)\n End DEX_HEAP.\n Declare Module DEX_Heap : DEX_HEAP.\n\n  Inductive DEX_ReturnVal : Set :=\n   | Normal : option DEX_value -> DEX_ReturnVal.\n\n (** Domain of frames *)\n Module Type DEX_FRAME.\n   Inductive t : Type := \n      make : DEX_Method -> DEX_PC -> DEX_Registers.t -> t.\n End DEX_FRAME.\n Declare Module DEX_Frame : DEX_FRAME.\n\n (** Domain of call stacks *)\n Module Type DEX_CALLSTACK.\n   Definition t : Type := list DEX_Frame.t.\n End DEX_CALLSTACK.\n Declare Module DEX_CallStack : DEX_CALLSTACK.\n\n (** Domain of states *)\n Module Type DEX_STATE.\n   Inductive t : Type := \n      normal : DEX_Heap.t -> DEX_Frame.t -> DEX_CallStack.t -> t.\n   Definition get_sf (s:t) : DEX_CallStack.t :=\n     match s with\n       normal _ _ sf => sf\n     end.\n   Definition get_m (s:t) : DEX_Method :=\n     match s with\n       normal _ (DEX_Frame.make m _ _)_ => m\n     end.\n End DEX_STATE.\n Declare Module DEX_State : DEX_STATE.\n \n (** Some notations *)\n Notation St := DEX_State.normal.\n Notation Fr := DEX_Frame.make.\n\n  Inductive isReference : DEX_value -> Prop :=\n  | isReference_null : isReference Null\n  | isReference_ref : forall loc, isReference (Ref loc).\n\n  (** compatibility between ValKind and value *) \n  Inductive compat_ValKind_value : DEX_ValKind -> DEX_value -> Prop :=\n    | compat_ValKind_value_ref : forall v,\n        isReference v -> compat_ValKind_value DEX_Aval v\n    | compat_ValKind_value_int : forall n,\n        compat_ValKind_value DEX_Ival (Num (I n)).\n\n  (** [assign_compatible_num source target] holds if a numeric value [source] can be \n    assigned to a variable of type [target]. This point is not clear in the JVM spec. *)\n  Inductive assign_compatible_num : DEX_num -> DEX_primitiveType -> Prop :=\n   | assign_compatible_int_int : forall i, assign_compatible_num (I i) DEX_INT\n   | assign_compatible_short_int : forall sh, assign_compatible_num (Sh sh) DEX_INT\n   | assign_compatible_byte_int : forall b, assign_compatible_num (B b) DEX_INT\n   | assign_compatible_short_short : forall sh, assign_compatible_num (Sh sh) DEX_SHORT\n   | assign_compatible_byte_byte : forall b, assign_compatible_num (B b) DEX_BYTE\n   | assign_compatible_byte_boolean : forall b, assign_compatible_num (B b) DEX_BOOLEAN.\n\n  (** [assign_compatible h source target] holds if a value [source] can be \n    assigned to a variable of type [target] *)\n  Inductive assign_compatible (p:DEX_Program) (h:DEX_Heap.t) : DEX_value -> DEX_type -> Prop :=\n   | assign_compatible_null : forall t, assign_compatible p h Null (DEX_ReferenceType t)\n   | assign_compatible_ref_object_val : forall (loc:DEX_Location) (t:DEX_refType) (cn:DEX_ClassName), \n       DEX_Heap.typeof h loc = Some (DEX_Heap.DEX_LocationObject cn) ->\n       compat_refType p (DEX_ClassType cn) t ->\n       assign_compatible p h (Ref loc) (DEX_ReferenceType t)\n   | assign_compatible_num_val : forall (n:DEX_num) (t:DEX_primitiveType),\n       assign_compatible_num n t -> assign_compatible p h (Num n) (DEX_PrimitiveType t).\n\n  Definition SemCompInt (cmp:DEX_CompInt) (z1 z2: Z) : Prop :=\n    match cmp with\n      DEX_EqInt =>  z1=z2\n    | DEX_NeInt => z1<>z2\n    | DEX_LtInt => z1<z2\n    | DEX_LeInt => z1<=z2\n    | DEX_GtInt => z1>z2\n    | DEX_GeInt => z1>=z2\n    end.\n\n  Definition SemBinopInt (op:DEX_BinopInt) (i1 i2:Int.t) : Int.t :=\n    match op with \n    | DEX_AddInt => Int.add i1 i2\n    | DEX_AndInt => Int.and i1 i2\n    | DEX_DivInt => Int.div i1 i2\n    | DEX_MulInt => Int.mul i1 i2\n    | DEX_OrInt => Int.or i1 i2\n    | DEX_RemInt => Int.rem i1 i2\n    | DEX_ShlInt => Int.shl i1 i2\n    | DEX_ShrInt => Int.shr i1 i2\n    | DEX_SubInt => Int.sub i1 i2\n    | DEX_UshrInt => Int.ushr i1 i2\n    | DEX_XorInt => Int.xor i1 i2\n    end.\n\nEnd DEX_SEMANTIC_DOMAIN.", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/DEX_O/DEX_Domain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2247647150700382}}
{"text": "Require Import Echo1 Stack3A HoareDef SimModSem.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import Relation_Definitions.\n\n(*** TODO: export these in Coqlib or Universe ***)\nRequire Import Relation_Operators.\nRequire Import RelationPairs.\nFrom ITree Require Import\n     Events.MapDefault.\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Maps\n     Data.Map.FMapAList.\nRequire Import HTactics ProofMode IPM.\nRequire Import OpenDef STB.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\n\nSection REFINE.\n  Context `{Σ: GRA.t}.\n  Context `{@GRA.inG stkRA Σ}.\n\n  Let W: Type := Any.t * Any.t.\n\n  Let wf: _ -> W -> Prop := fun (_: unit) _ => True.\n\n  Variable frds0 frds1: Sk.t -> list string.\n  Hypothesis FRDS: forall sk, List.incl (frds1 sk) (frds0 sk).\n\n  Theorem correct:\n    refines2 [KMod.transl_src frds0 Echo1.KEcho] [KMod.transl_src frds1 Echo1.KEcho].\n  Proof.\n    eapply adequacy_local2. econs; ss. i.\n    econstructor 1 with (wf:=wf) (le:=top2); ss.\n    2: { esplits; et. ss. }\n    econs; ss.\n    { init. rewrite ! my_if_same. unfold echo_body, body_to_src.\n      steps. unfold unwrapU. steps. des_ifs; steps. des_ifs; steps.\n      unfold ccallN. steps. unfold unwrapN. des_ifs; steps.\n      des_ifs; steps. red. esplits; et. }\n    econs; ss.\n    { init. unfold sumbool_to_bool, body_to_src. des_ifs.\n      { unfold cfunN, input_body. steps.\n        unfold unwrapN, ccallU, ccallN, unwrapU, unwrapN.\n        des_ifs; steps. des_ifs; steps. force_r. esplits; et.\n        steps. des_ifs; steps. des_ifs; steps.\n        { red. esplits; et. }\n        steps. des_ifs; steps.\n        red. esplits; et.\n      }\n      { exfalso. eapply n. ss. des; auto. right.\n        eapply in_map_iff in i. des; subst. eapply in_map. eapply FRDS. et. }\n      { steps. }\n      { steps. }\n    }\n    econs; ss.\n    { init. unfold sumbool_to_bool, body_to_src. des_ifs.\n      { unfold cfunN, output_body. steps.\n        unfold unwrapN, ccallU, ccallN, unwrapU, unwrapN.\n        des_ifs; steps. des_ifs; steps.\n        { red. esplits; et. }\n        steps. des_ifs; steps.\n        des_ifs; steps. red. esplits; et.\n      }\n      { exfalso. eapply n. ss. des; auto. right.\n        eapply in_map_iff in i. des; subst. eapply in_map. eapply FRDS. et. }\n      { steps. }\n      { steps. }\n    }\n    Unshelve. all: ss. all: exact 0.\n  Qed.\nEnd REFINE.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/echo/Echo1mon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.22476470920450783}}
{"text": "Require Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Export Maps.\nRequire Import Events.\nRequire Import Globalenvs.\n\nRequire Import mem_lemmas. (*for mem_forward*)\nRequire Import semantics.\nRequire Import effect_semantics.\n\nRequire Import Csharpminor.\nRequire Import Csharpminor_coop.\n\nRequire Import BuiltinEffects.\n\nLemma EmptyEffect_allocvariables: forall L e m e' m'\n      (ALLOC: alloc_variables e m L e' m'),\n  Mem.unchanged_on (fun b ofs => EmptyEffect b ofs = false) m m'.\nProof. intros L.\n  induction L; simpl; intros; inv ALLOC.\n    apply Mem.unchanged_on_refl.\n  specialize (IHL _ _ _ _ H6). clear H6.\n  eapply (unchanged_on_trans _ m1).\n    eapply EmptyEffect_alloc; eassumption.\n    eassumption.\n  eapply alloc_forward; eassumption.\nQed.\n\nSection CSHARPMINOR_EFF.\nVariable hf : I64Helpers.helper_functions.\n  \nInductive csharpmin_effstep (g: Csharpminor.genv):  (block -> Z -> bool) ->\n            CSharpMin_core -> mem -> CSharpMin_core -> mem -> Prop :=\n\n  | csharpmin_effstep_skip_seq: forall f s k e le m,\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f Sskip (Kseq s k) e le) m\n        (CSharpMin_State f s k e le) m\n  | csharpmin_effstep_skip_block: forall f k e le m,\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f Sskip (Kblock k) e le) m\n        (CSharpMin_State f Sskip k e le) m\n  | csharpmin_effstep_skip_call: forall f k e le m m',\n      is_call_cont k ->\n      Mem.free_list m (blocks_of_env e) = Some m' ->\n      csharpmin_effstep g (FreelistEffect m (blocks_of_env e)) (CSharpMin_State f Sskip k e le) m\n        (CSharpMin_Returnstate Vundef k) m'\n\n  | csharpmin_effstep_set: forall f id a k e le m v,\n      eval_expr g e le m a v ->\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f (Sset id a) k e le) m\n        (CSharpMin_State f Sskip k e (PTree.set id v le)) m\n\n  | csharpmin_effstep_store: forall f chunk addr a k e le m vaddr v m',\n      eval_expr g e le m addr vaddr ->\n      eval_expr g e le m a v ->\n      Mem.storev chunk m vaddr v = Some m' ->\n      csharpmin_effstep g (StoreEffect vaddr (encode_val chunk v))\n        (CSharpMin_State f (Sstore chunk addr a) k e le) m\n        (CSharpMin_State f Sskip k e le) m'\n\n  | csharpmin_effstep_call: forall f optid sig a bl k e le m vf vargs fd,\n      eval_expr g e le m a vf ->\n      eval_exprlist g e le m bl vargs ->\n      Genv.find_funct g vf = Some fd ->\n      funsig fd = sig ->\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f (Scall optid sig a bl) k e le) m\n        (CSharpMin_Callstate fd vargs (Kcall optid f e le k)) m\n\n  | csharpmin_effstep_builtin: forall f optid ef bl k e le m vargs t vres m',\n      eval_exprlist g e le m bl vargs ->\n      external_call ef g vargs m t vres m' ->\n      ~ observableEF hf ef ->\n      csharpmin_effstep g (BuiltinEffect g ef vargs m)\n         (CSharpMin_State f (Sbuiltin optid ef bl) k e le) m\n         (CSharpMin_State f Sskip k e (Cminor.set_optvar optid vres le)) m'\n\n  | csharpmin_effstep_seq: forall f s1 s2 k e le m,\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f (Sseq s1 s2) k e le) m\n        (CSharpMin_State f s1 (Kseq s2 k) e le) m\n\n  | csharpmin_effstep_ifthenelse: forall f a s1 s2 k e le m v b,\n      eval_expr g e le m a v ->\n      Val.bool_of_val v b ->\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f (Sifthenelse a s1 s2) k e le) m\n        (CSharpMin_State f (if b then s1 else s2) k e le) m\n\n  | csharpmin_effstep_loop: forall f s k e le m,\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f (Sloop s) k e le) m\n        (CSharpMin_State f s (Kseq (Sloop s) k) e le) m\n\n  | csharpmin_effstep_block: forall f s k e le m,\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f (Sblock s) k e le) m\n        (CSharpMin_State f s (Kblock k) e le) m\n\n  | csharpmin_effstep_exit_seq: forall f n s k e le m,\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f (Sexit n) (Kseq s k) e le) m\n        (CSharpMin_State f (Sexit n) k e le) m\n  | csharpmin_effstep_exit_block_0: forall f k e le m,\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f (Sexit O) (Kblock k) e le) m\n        (CSharpMin_State f Sskip k e le) m\n  | csharpmin_effstep_exit_block_S: forall f n k e le m,\n      csharpmin_effstep g EmptyEffect \n        (CSharpMin_State f (Sexit (S n)) (Kblock k) e le) m\n        (CSharpMin_State f (Sexit n) k e le) m\n\n  | csharpmin_effstep_switch: forall f a cases k e le m n,\n      eval_expr g e le m a (Vint n) ->\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f (Sswitch a cases) k e le) m\n        (CSharpMin_State f (seq_of_lbl_stmt (select_switch n cases)) k e le) m\n\n  | csharpmin_effstep_return_0: forall f k e le m m',\n      Mem.free_list m (blocks_of_env e) = Some m' ->\n      csharpmin_effstep g (FreelistEffect m (blocks_of_env e)) (CSharpMin_State f (Sreturn None) k e le) m\n        (CSharpMin_Returnstate Vundef (call_cont k)) m'\n  | csharpmin_effstep_return_1: forall f a k e le m v m',\n      eval_expr g e le m a v ->\n      Mem.free_list m (blocks_of_env e) = Some m' ->\n      csharpmin_effstep g (FreelistEffect m (blocks_of_env e)) (CSharpMin_State f (Sreturn (Some a)) k e le) m\n        (CSharpMin_Returnstate v (call_cont k)) m'\n  | csharpmin_effstep_label: forall f lbl s k e le m,\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f (Slabel lbl s) k e le) m\n        (CSharpMin_State f s k e le) m\n\n  | csharpmin_effstep_goto: forall f lbl k e le m s' k',\n      find_label lbl f.(fn_body) (call_cont k) = Some(s', k') ->\n      csharpmin_effstep g EmptyEffect (CSharpMin_State f (Sgoto lbl) k e le) m\n        (CSharpMin_State f s' k' e le) m\n\n  | csharpmin_effstep_internal_function: forall f vargs k m m1 e le,\n      list_norepet (map fst f.(fn_vars)) ->\n      list_norepet f.(fn_params) ->\n      list_disjoint f.(fn_params) f.(fn_temps) ->\n      alloc_variables empty_env m (fn_vars f) e m1 ->\n      bind_parameters f.(fn_params) vargs (create_undef_temps f.(fn_temps)) = Some le ->\n      csharpmin_effstep g EmptyEffect \n        (CSharpMin_Callstate (Internal f) vargs k) m\n        (CSharpMin_State f f.(fn_body) k e le) m1\n\n(*All external calls in this language at handled by atExternal\n  | csharpmin_effstep_external_function: forall ef vargs k m t vres m',\n      external_call ef g vargs m t vres m' ->\n      csharpmin_effstep g EmptyEffect (CSharpMin_Callstate (External ef) vargs k) m\n         (CSharpMin_Returnstate vres k) m' *)       \n\n  | csharpmin_effstep_return: forall v optid f e le k m,\n      csharpmin_effstep g EmptyEffect (CSharpMin_Returnstate v (Kcall optid f e le k)) m\n        (CSharpMin_State f Sskip k e (Cminor.set_optvar optid v le)) m.\n\nLemma csharpminstep_effax1: forall (M : block -> Z -> bool) g c m c' m'\n      (H: csharpmin_effstep g M c m c' m'),\n       corestep (csharpmin_coop_sem hf) g c m c' m' /\\\n       Mem.unchanged_on (fun (b : block) (ofs : Z) => M b ofs = false) m m'.\nProof. \nintros.\n  induction H.\n  split. unfold corestep, coopsem; simpl. econstructor.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         eapply FreelistEffect_freelist; eassumption. \n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         eapply StoreEffect_Storev; eassumption.\n  split. unfold corestep, coopsem; simpl. econstructor; try eassumption.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         eapply BuiltinEffect_unchOn; eassumption.\n(*  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         eapply ec_builtinEffectPolymorphic; eassumption.*)\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         eapply FreelistEffect_freelist; eassumption.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         eapply FreelistEffect_freelist; eassumption.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  split. unfold corestep, coopsem; simpl. econstructor; try eassumption.\n         eapply EmptyEffect_allocvariables; eassumption. \n  (*no external call*) \n  split. unfold corestep, coopsem; simpl. econstructor; eassumption.\n         apply Mem.unchanged_on_refl.\n  (*effstep_sub_val\n    destruct IHcsharpmin_effstep.\n    split; trivial.\n    eapply unchanged_on_validblock; try eassumption.\n    intros; simpl. remember (E b ofs) as d.\n    destruct d; trivial. apply eq_sym in Heqd.\n    rewrite (H _ _ H3 Heqd) in H4. discriminate.*)\nQed.\n\nLemma csharpminstep_effax2: forall  g c m c' m',\n      corestep (csharpmin_coop_sem hf) g c m c' m' ->\n      exists M, csharpmin_effstep g M c m c' m'.\nProof.\nintros. inv H.\n    eexists. eapply csharpmin_effstep_skip_seq.\n    eexists. eapply csharpmin_effstep_skip_block.\n    eexists. eapply csharpmin_effstep_skip_call; try eassumption.\n    eexists. eapply csharpmin_effstep_set; eassumption.\n    eexists. eapply csharpmin_effstep_store; eassumption.\n    eexists. eapply csharpmin_effstep_call; try eassumption. reflexivity. \n    eexists. eapply csharpmin_effstep_builtin; eassumption.\n    eexists. eapply csharpmin_effstep_seq.\n    eexists. eapply csharpmin_effstep_ifthenelse; eassumption.\n    eexists. eapply csharpmin_effstep_loop.\n    eexists. eapply csharpmin_effstep_block.\n    eexists. eapply csharpmin_effstep_exit_seq.\n    eexists. eapply csharpmin_effstep_exit_block_0.\n    eexists. eapply csharpmin_effstep_exit_block_S.\n    eexists. eapply csharpmin_effstep_switch; eassumption.\n    eexists. eapply csharpmin_effstep_return_0; try eassumption.\n    eexists. eapply csharpmin_effstep_return_1; try eassumption.\n    eexists. eapply csharpmin_effstep_label.\n    eexists. eapply csharpmin_effstep_goto; eassumption.\n    eexists. eapply csharpmin_effstep_internal_function; try eassumption.\n    eexists. eapply csharpmin_effstep_return.\nQed.\n\nLemma csharpmin_effstep_valid: forall (M : block -> Z -> bool) g c m c' m',\n      csharpmin_effstep g M c m c' m' ->\n       forall b z, M b z = true -> Mem.valid_block m b.\nProof.\nintros.\n  induction H; try (solve [inv H0]).\n\n  eapply FreelistEffect_validblock; eassumption.\n\n  apply StoreEffectD in H0. destruct H0 as [ofs [VADDR ARITH]]; subst.\n  inv H2. apply Mem.store_valid_access_3 in H3.\n  eapply Mem.valid_access_valid_block.\n  eapply Mem.valid_access_implies; try eassumption. constructor.\n\n  eapply BuiltinEffect_valid_block; eassumption.\n\n  eapply FreelistEffect_validblock; eassumption.\n\n  eapply FreelistEffect_validblock; eassumption.\nQed.\n \nProgram Definition csharpmin_eff_sem : \n  @EffectSem Csharpminor.genv CSharpMin_core.\nProof.\neapply Build_EffectSem with (sem := csharpmin_coop_sem hf)\n       (effstep:=csharpmin_effstep).\napply csharpminstep_effax1.\napply csharpminstep_effax2. \napply csharpmin_effstep_valid. \nDefined.\n\nEnd CSHARPMINOR_EFF.", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/cfrontend/Csharpminor_eff.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.22460594983939736}}
{"text": "(** This file was written by Colm Bhandal, PhD student, Foundations and Methods group,\nSchool of Computer Science and Statistics, Trinity College, Dublin, Ireland.*)\n\n(***************************** Standard Imports *****************************)\n\nRequire Import ComhCoq.Extras.LibTactics.\n\n(***************************** Specialised Imports *****************************)\n\nRequire Import ComhCoq.GenTacs.\nRequire Import ComhCoq.StandardResults.\nRequire Import ComhCoq.ComhBasics.\nRequire Import ComhCoq.NetworkLanguage.\nRequire Import ComhCoq.LanguageFoundations.\nRequire Import ComhCoq.ModeStateLanguage.\nRequire Import ComhCoq.InterfaceLanguage.\nRequire Import ComhCoq.SoftwareLanguage.\nRequire Import ComhCoq.ProtAuxDefs.\nRequire Import ComhCoq.ProtAuxResults.\nRequire Import ComhCoq.EntAuxDefs.\nRequire Import ComhCoq.EntAuxResults.\nRequire Import ComhCoq.NetAuxBasics.\nRequire Import ComhCoq.NetAuxDefs.\nRequire Import ComhCoq.NARMisc.\n\nLemma ovWait_nextSinceState_net m t x y i n : \n  ovWaitStateNet m t x y i n -> nextSinceStateNet i n. Admitted (*9*).\n(*Proof: Is there some auto tactic for this? #lift-compound-net-tac*)\n\n(*If we are in the ovWaitState then we are either pending or nextSince.*)\nTheorem ovWait_nextSince_pending (n : Network) (m : Mode) (t x y : Time) (i : nat)\n  (p : reachableNet n) :\n  ovWaitStateNet m t x y i n -> pending i n p \\/ exists t, nextSince m t i n p.\n  (*Proof: Induction on p, the proof of reachability.*)\n  introz U. induction p.\n  (*The base case fails by contradiction.*)\n  initNet_contra U.\n  (*In the discrete inductive case, we backtrack for cases of the previous state.*)  \n  Admitted. (*C- This proof actually goes through based on\n  ovReady_nextSince_pending, but the two are mutually inductive so we\n  possibly need to combine the two into one result- or figure out a way\n  to do mutual induction in Coq. The most straightforward solution to this\n  is to prove a mutual result with a conjunction, and then the individual\n  results follow easily from this.*)\n\n\n(*SHARED TACTICS WITH OVWAITSTATE ANALOGUE?\nIf we are in the ovReadyState then we are either pending or nextSince.*)\nTheorem ovReady_nextSince_pending (n : Network) (m : Mode) (t : Time) (i : nat)\n  (l : Position) (p : reachableNet n) :\n  ovReadyStateNet m t l i n -> pending i n p \\/ exists t, nextSince m t i n p.\n  introz U.\n  (**Proof: Induction on reachable.*)\n  induction p.\n  (*\n  (*Discard base case as initiality contradicts the state predicate*)\n  initNet_contra U.\n  (*Discrete inductive case- lets backtrack from ovReady*)\n  lets OPN : ovReady_prev_net U s. ex_flat. or_flat.\n  (*Where the previous case is ovReadySate follows by induction,\n  case analysis of the disjunction, and application of the\n  appropriate constructor.*)\n  lets IH : IHp OR. or_flat.\n  (*A previous cas of pending gives a next case of pending.*)\n  left. eapply pendingReady; eassumption.\n  (*A previous cas of nextSince gives nextSince.*)\n  ex_flat. right. eexists. constructor. eassumption.\n  eapply ovReady_nextSince_state; eassumption.\n  (*So we're left with the discrete case where the previous state is\n  ovWaitState m t x y. Then we use (ovWait_nextSince_pending) to show that\n  the previous state was either pending or nextSince*)\n  ex_flat. lets ONP : ovWait_nextSince_pending H0.\n  (*case analyse, and apply the right constructor to get the same for this\n  state.*)\n  (*Delay inductive case fails by progress [salvaged?].*)\n  Admitted. (*C- Need to combine with ovWait_nextSince_pending by some sort\n  of mutual induction. See ovWait_nextSince_pending for details.*)*)\n  Admitted. (*R*)\n\nLemma pending_urgent i n n' p d :\n  pending i n p -> n -ND- d -ND> n' -> False. Admitted. (*5*) \n(**Proof: Induction on pending. BaseType case: ovWait is ready to input a position,\nand so is urgent. This readiness is not perverted by any other discreet action,\nso the ovWait-ovWait inductive case follows. Both inductive cases with ovReady\nas the current state follows immediately from the fact that ovWaitState is\nitself urgent*)\n\n(*If we are in the ovWait state with the parameter x = 0,\nthen the nextSince relation holds.*)\nTheorem ovWait_zero_nextSince (n : Network) (m : Mode) (t y : Time) (i : nat)\n  (p : reachableNet n) : ovWaitStateNet m t zeroTime y i n ->\n  exists t, nextSince m t i n p. Admitted. (*2*)\n(**Proof: Induction on reachable. BaseType case fails. For the inductive case(s),\ncase analyse- is the last state ovWait? If yes, then the result follows easily\nby induction. If not, then use (...ovWait_prev...) to get the possible shapes of\nthe previous state. Well, it can't be initState m, because this would give us\nx = tw(m0, m) + period m, which is greater than 0. But x = 0. So our previous\nstate must have been ovReady m (t + period m) l. Then by (ovReady_nextSince_pending),\nthe previous state was either pending or nextSince. In either case, there is a\nconstructor of nextSince that allows us to prove nextSince holds for the current state.*)\n\n(*If we are in the switchBc state, then the nextSince relation holds.*)\nTheorem switchBc_nextSince (n : Network) (m : Mode) (i : nat)\n  (p : reachableNet n) : switchBcStateNet m i n -> exists t, nextSince m t i n p.\n  Admitted. (*2*)\n(**Proof: By induction on reachable. Eliminate the easy cases, leaving us with the\ndiscrete inductive case with the previous state not switchBcState. Then we use\n(...switchBc_prev...) to give us ovWait m t 0 y as the predecessor state- we know\nthe parameter x is 0 because the transition would have to have been enabled.\nThen by (ovWait_nextSince_pending & elimination of the pending case somehow) we have that the previous state was nextSince and so by\napplication of the nextSince discrete constructor so is this one.*)\n\n(*If we are in the switchCurr state, then the nextSince relation holds.\t*)\nTheorem switchCurr_nextSince (n : Network) (m : Mode) (i : nat)\n  (p : reachableNet n) : switchCurrStateNet i n ->\n  exists t, nextSince m t i n p. Admitted. (*2*)\n(**Proof: By induction on reachable and (...switchCurr_prev...) to give us switchBc m\nas the predecessor state. Then by (swtichBc_nextSince) and application of the nextSince\ndiscrete constructor our results follows.*)\n\n(* Let's say in a reachable network, an entity is in non-fail-safe mode m.\nThen that entity has been currSince m t.*)\nTheorem nonFS_currSince (m : Mode) (i : nat) (n : Network) \n  (p : reachableNet n) : currModeNet m i n -> ~failSafe m ->\n  exists t, currSince m t i n p.\n  intros.\n  (**Proof: Induction on the proof of reachability of n.*)\n  induction p.\n  (*In the base case, we have that n is initial. Hence all its constituent entities\n  are in fail safe modes. So the assumption that entity i is in mode m which is not\n  fail safe is contradictory, case closed.*)\n  apply currMode_ent_ex in H. decompose [ex] H. clear H. rename x into e.\n  invertClear H1. rewrite <- H2 in H0. apply False_ind. apply H0.\n  eapply initial_failSafe. apply i0. apply H.\n  (*Which leaves us the inductive cases. We start with the discrete inductive case.\n  Here, we do a case analysis on whether the previous state was currMode m.*)\n  addHyp (currModeNet_dec m i n). invertClear H1.\n  (*If it was, then by the inductive hypothesis, we get currSince m t for\n  the previous state*)\n  apply IHp in H2. invertClear H2. rename x into t.\n  (*Which immediately follows on to this state by the inductive definition of currSince.*)\n  exists t. eapply currSinceDisc. apply H1. assumption.\n  (*Otherwise, the previous state was not currMode m. And so it must have been currMode m'\n  for some m' <> m (Basics::currMode_pres_bkwd).*)\n  addHyp (currMode_pres_bkwd n n' a m i s H). invertClear H1. rename x into m'.\n  assert (m' <> m). unfold not. intros. rewrite H1 in H3. apply H2. assumption.\n  (*And so we can show that since the current mode has changed between states,\n  the entity i must have performed a tau transition.*)\n  addHyp H. rewrite (currMode_ent_ex m i n') in H4.\n  addHyp H3. rewrite (currMode_ent_ex m' i n) in H5.\n  invertClear H4. invertClear H5. invertClear H4. invertClear H6.\n  rename x0 into e. rename x into e'.\n  addHyp (curr_switch_ent_tau n n' a e e' i m' m s H5 H4 H7 H8 H1).\n  (*We can also show that the software component contributed an output on mCurr and the\n  mode-state contributed an input (EA::curr_switch_proc).*)\n  rename p into X. destruct e as [p l h k]. destruct e' as [p' l' h' k'].\n  addHyp (currMode_ent_mState p l h k m' H7). addHyp (currMode_ent_mState p' l' h' k' m H8).\n  assert (currModeMState k <> currModeMState k'). rewrite H9. rewrite H10. assumption.\n  addHyp (curr_switch_proc p p' l l' h h' k k' H6 H11). invertClear H12.\n  (*Now, we since n is reachable, so is p, and so p is a triple of processes*)\n  addHyp (reachable_net_prot n i p l h k X H5). apply reachableProt_triple in H12.\n  invertClear H12. rewrite <- H18 in H13. \n  (*And so one of the sub components P1, P2 or P3 must have performed this output.*)\n  link_partripdiscex_tac Y p1' p2' p3'. rewrite Y in H13.\n  link_partripout_tac U;[\n  (*We eliminate the possibility P1 by (bc_mCurr_out_not)*)\n  false; eapply bc_mCurr_out_not; [apply U | assumption] | |\n  (*and we eliminate P3 with (listen_mCurr_not).*)\n  false; eapply listen_mCurr_out_not; [apply U | assumption]].  \n  (*Then by (...ovlp_mCurr_out...) we show that P2 was in the state switchCurrState,\n  while the next state had P2' in switchListenState*)\n  lets OO : ovlp_mCurr_out U H16.\n  (*We can eliminate the tfs case because failSafe m contradicts our hypothesis.*)\n  elim_intro OO SW TF. Focus 2.\n  assert (tfsBcStateEnt ([|p', l', h', k'|])). constructor. rewrite Y.\n  constructor. apply TF. apply tfsBc_failSafe in H12.\n  simpl in H12. rewrite H10 in H12. false.\n  (*This allows us to conclude that the previous state was nextSince m t i n for some t\n  (switchCurr_nextSince)*)\n  assert (switchCurrStateEnt ([|p, l, h, k|])).\n  constructor. rewrite <- H18. constructor. apply SW.\n  assert (switchCurrStateNet i n). econstructor. apply H12. assumption.\n  addHyp (switchCurr_nextSince n m i X H19). invertClear H20.\n  rename x into t.\n  (*Now finally, by the base case of currSince, we can show that\n  currSince m t i n holds.*)\n  exists t. constructor. assumption. assumption. econstructor.\n  constructor. constructor. apply SW. rewrite Y in H4. apply H4.\n  (*For the delay inductive case, we first notice that delay preserves the current mode*)\n  addHyp (currMode_del_pres_bkwd n n' d m i s H).\n  (*Then we apply the I.H. to get that the previous mode was currSince.*)\n  apply IHp in H1. invertClear H1. rename x into t.\n  (*And now as our existential we take t + d*. And by the delay constructor of\n  currSince, we're done.*)\n  exists (t +dt+ d). constructor. assumption. Qed.", "meta": {"author": "ColmBhandal", "repo": "PhD-Formalilsing-Comhordu", "sha": "7f31dbc4a9a205b3b722cff30e79442922e0f9c9", "save_path": "github-repos/coq/ColmBhandal-PhD-Formalilsing-Comhordu", "path": "github-repos/coq/ColmBhandal-PhD-Formalilsing-Comhordu/PhD-Formalilsing-Comhordu-7f31dbc4a9a205b3b722cff30e79442922e0f9c9/src/NARNonFS_currSince.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.22450508185939294}}
{"text": "Require Export WellFormedness.\nRequire Import SyntaxProp.\nRequire Import TypesProp.\nRequire Import Shared.\n\n(*\n========================\nField and method lookup\n========================\n*)\n\n\nLemma wfProgram_wfMethodDecl :\n  forall P t' c ms m mtd,\n    wfProgram P t' ->\n    methods P (TClass c) = Some ms ->\n    methodLookup ms m = Some mtd ->\n    wfMethodDecl P c mtd.\nProof with auto.\n  introv wfP Hmethods mLookup.\n  inv wfP.\n  unfold methods in Hmethods.\n  remember (classLookup (cds, ids, e) c) as cLookup.\n  symmetry in HeqcLookup.\n  destruct cLookup as [[c' i fs ms'] |]...\n  inv_eq.\n  assert (Heq : c = c') by\n      (unfold classLookup in HeqcLookup;\n       apply find_true in HeqcLookup;\n       apply beq_nat_eq; auto).\n  subst.\n  lookup_forall as wfCls.\n  inv wfCls.\n  lookup_forall mtd as wfMtd...\nQed.\n\n\nCorollary dyn_wfFieldLookup :\n  forall P Gamma c F fs f t r,\n    wfFields P Gamma c F ->\n    fields P (TClass c) = Some fs ->\n    fieldLookup fs f = Some (Field f t r) ->\n    exists v, F f = Some v /\\ P; Gamma |- (EVal v) \\in t.\nProof with eauto.\n  introv wfF Hfields fLookup.\n  inv wfF. rewrite_and_invert...\nQed.\n\nHint Immediate dyn_wfFieldLookup.\n\n(*\n------------\nMethod sigs\n------------\n*)\n\nHint Constructors methodSigs.\n\nLemma extractSigs_sound :\n  forall mtds m x t t',\n    (exists e, methodLookup mtds m = Some (Method m (x, t) t' e)) <->\n    methodSigLookup (extractSigs mtds) m = Some (MethodSig m (x, t) t').\nProof with eauto.\n  intros. split.\n  + gen t t' m x.\n    induction mtds as [|[m [x t] t' e]]; simpl;\n    introv H; inv H as [e' Hsigs]...\n    cases_if... inv_eq.\n  + gen t t' m x.\n    induction mtds as [|[m [x t] t' e]]; simpl;\n    introv mLookup; inv mLookup...\n    cases_if; crush...\nQed.\n\nLemma methodSigs_deterministic :\n  forall P t msigs1 msigs2,\n    methodSigs P t msigs1 ->\n    methodSigs P t msigs2 ->\n    msigs1 = msigs2.\nProof with eauto.\n  introv Hsigs1 Hsigs2.\n  gen msigs2.\n  induction Hsigs1; introv Hsigs2;\n  inv Hsigs2; try(rewrite_and_invert)...\n  rewrite IHHsigs1_1 with msigs3...\n  rewrite IHHsigs1_2 with msigs4...\nQed.\n\nLemma methodSigs_wfType_exists :\n  forall P t' t,\n    wfProgram P t' ->\n    (wfType P t <->\n     exists msigs, methodSigs P t msigs).\nProof with eauto.\n  introv [? ? ? wfCds wfIds wfExpr].\n  split.\n  + intros wfT.\n    inv wfT as [c cLookup|i iLookup|]...\n    - apply classLookup_not_none in cLookup as [i [fs [ms]]]...\n    - apply interfaceLookup_not_none in iLookup.\n      inv iLookup as [[msigs]|[i1 [i2]]]...\n      * intros. lookup_forall as wfId. inv wfId...\n  + intros Hex. destruct Hex as [msigs Hsigs].\n    destruct t; inv Hsigs; constructor; crush.\nQed.\n\nLemma methodSigs_sub :\n  forall P t t1 t2 m msigs1 msigs2 msig,\n    wfProgram P t ->\n    subtypeOf P t1 t2 ->\n    methodSigs P t1 msigs1 ->\n    methodSigs P t2 msigs2 ->\n    methodSigLookup msigs2 m = Some msig ->\n    methodSigLookup msigs1 m = Some msig.\nProof with eauto using\n                 methodSigs_deterministic,\n                 methodSigs_wfType_exists,\n                 subtypeOf_wfTypeSub,\n                 subtypeOf_wfTypeSup.\n  introv [? ? ? ? wfCds wfIds wfExpr] Hsub\n         Hsigs1 Hsigs2 Hsig.\n  gen msigs1 msigs2 msig.\n  subtypeOf_cases(induction Hsub) Case; intros.\n  + Case \"Sub_Class\".\n    lookup_forall as wfCd. inv wfCd.\n    assert (msigs2 = (extractSigs ms))...\n    subst. inv Hsigs1; rewrite_and_invert.\n  + Case \"Sub_InterfaceLeft\".\n    inv Hsigs1; rewrite_and_invert.\n    assert (msigs0 = msigs2)...\n    subst. apply find_app...\n  + inv Hsigs1; rewrite_and_invert.\n    assert (msigs2 = msigs3)...\n    subst. apply find_app2...\n    lookup_forall as wfId.\n    inverts wfId as Hsigs3 Hsigs4 sigsDisjoint1 sigsDisjoint2.\n    assert (msigs0 = msigs1)...\n    assert (msigs2 = msigs3)...\n    subst. fold (methodSigLookup msigs1 m).\n    eapply sigsDisjoint2...\n  + asserts_rewrite (msigs1 = msigs2)...\n  + rename msigs2 into msigs3.\n    rename Hsigs2 into Hsigs3.\n    assert (wfT1: wfType (cds, ids, e) t1)...\n    assert (wfT2: wfType (cds, ids, e) t2)...\n    eapply methodSigs_wfType_exists in wfT2 as []...\n(*  + inv Hsigs2. inv Hsig.*)\nQed.\n\n(*\n==============\nConfiguration\n==============\n*)\n\n(*\n---------\nwfFields\n---------\n*)\n\nLemma wfFields_declsToFields :\n  forall P t' c i fs ms Gamma,\n    wfProgram P t' ->\n    wfEnv P Gamma ->\n    classLookup P c = Some (Cls c i fs ms) ->\n    wfFields P Gamma c (declsToFields fs).\nProof with eauto using\n                 fields_wfFieldDecl,\n                 declsToFields_null.\n  introv wfProgram wfEnv Hlookup.\n  assert (fields P (TClass c) = Some fs)\n    by (unfolds; rewrite Hlookup; auto).\n  assert (Forall (wfFieldDecl P) fs)...\n  econstructor...\n  intros.\n  lookup_forall as wfF. inv wfF...\nQed.\n\nLemma wfFields_extend :\n  forall P Gamma c fs f t r F v,\n    fields P (TClass c) = Some fs ->\n    fieldLookup fs f = Some (Field f t r) ->\n    wfFields P Gamma c F ->\n    P; Gamma |- EVal v \\in t ->\n    wfFields P Gamma c (extend F f v).\nProof with eauto with env.\n  introv Hfields fLookup wfF hasType.\n  econstructor...\n  introv fLookup'.\n  inv wfF.\n  case_extend; repeat rewrite_and_invert...\nQed.\n\nLemma wfFields_envExtend :\n  forall P t' Gamma c F l c',\n    wfProgram P t' ->\n    wfFields P Gamma c F ->\n    wfEnv P Gamma ->\n    fresh Gamma (env_loc l) ->\n    wfType P (TClass c') ->\n    wfFields P (extend Gamma (env_loc l) (TClass c')) c F.\nProof with eauto using hasType_extend_loc.\n  introv wfP wfF wfGamma Hfresh wfT.\n  inverts wfF as Hfields wfFlds.\n  econstructor...\n  introv Hlookup.\n  apply wfFlds in Hlookup as (v & Heq & hasType)...\nQed.\n\nLemma wfFields_invariance :\n  forall P t' c Gamma Gamma' F,\n    wfProgram P t' ->\n    (forall l, Gamma (env_loc l) = Gamma' (env_loc l)) ->\n    wfEnv P Gamma' ->\n    wfFields P Gamma c F ->\n    wfFields P Gamma' c F.\nProof with eauto using hasType_wfType.\n  introv wfP envSub wfGamma' wfF.\n  inverts wfF as Hfields wfFld.\n  econstructor...\n  introv fLookup.\n  apply wfFld in fLookup as (v & Ff & hasType).\n  exists v. split...\n  destruct v...\n  + inv hasType.\n    econstructor...\n    rewrite <- envSub...\nQed.\n\nLemma wfHeap_wfObject :\n  forall P Gamma H l c F RL,\n    wfHeap P Gamma H ->\n    heapLookup H l = Some (c, F, RL) ->\n    wfFields P Gamma c F /\\ wfRegionLocks P c RL.\nProof with eauto.\n  introv wfH Hlookup.\n  inverts wfH as _ envModelsHeap heapMirrorsEnv.\n  assert (Hl: heapLookup H l <> None) by crush.\n  apply heapMirrorsEnv in Hl.\n  destruct Hl as [c' envLookup].\n  apply envModelsHeap in envLookup as (F' & RL' & ? & ? & ?).\n  rewrite_and_invert.\nQed.\n\nLemma wfHeap_wfFields :\n  forall P Gamma H l c F RL,\n    wfHeap P Gamma H ->\n    heapLookup H l = Some (c, F, RL) ->\n    wfFields P Gamma c F.\nProof with eauto.\n  introv wfH Hlookup.\n  eapply wfHeap_wfObject in Hlookup as []...\nQed.\n\nLemma wfHeap_wfRegionLocks :\n  forall P Gamma H l c F RL,\n    wfHeap P Gamma H ->\n    heapLookup H l = Some (c, F, RL) ->\n    wfRegionLocks P c RL.\nProof with eauto.\n  introv wfH Hlookup.\n  eapply wfHeap_wfObject in Hlookup as []...\nQed.\n\nLemma wfRegionLocks_declsToRegionLocks :\n  forall P c fs RL,\n    fields P (TClass c) = Some fs ->\n    declsToRegionLocks fs RL ->\n    wfRegionLocks P c RL.\nProof with eauto.\n  introv fLookup HRL.\n  inv HRL.\n  econstructor...\nQed.\n\n(*\n-------\nwfHeap\n-------\n*)\n\nHint Constructors wfHeap.\n\nLemma wfHeap_fresh :\n  forall P Gamma H l,\n    wfHeap P Gamma H ->\n    heapLookup H l = None ->\n    fresh Gamma (env_loc l).\nProof with eauto.\n  introv wfH Hlookup.\n  inverts wfH as wfGamma envModelsHeap heapMirrorsEnv.\n  unfold fresh. remember (Gamma (env_loc l)) as t...\n  destruct t...\n  symmetry in Heqt.\n  assert (tClass: exists c, t = TClass c) by (inv wfGamma; eauto).\n  inv tClass as [c''].\n  apply envModelsHeap in Heqt.\n  inv Heqt as [F' [RL [contra]]]. rewrite_and_invert.\nQed.\n\nLemma wfHeap_extend :\n  forall P t' Gamma H c F RL,\n    wfProgram P t' ->\n    wfHeap P Gamma H ->\n    wfType P (TClass c) ->\n    wfFields P Gamma c F ->\n    wfRegionLocks P c RL ->\n    wfHeap P (extend Gamma (env_loc (length H)) (TClass c)) (heapExtend H (c, F, RL)).\nProof with eauto using wfHeap_wfRegionLocks with env.\n  introv wfP wfH wfT wfF wfRL.\n  inverts wfH as wfGamma envModelsHeap heapMirrorsEnv.\n  constructor...\n  + introv envLookup.\n    destruct (id_eq_dec l (length H)).\n    - subst. simpl_extend_hyp. inv_eq.\n      rewrite heapExtend_lookup_len.\n      eexists; eexists; split; split...\n      eapply wfFields_envExtend...\n      eapply wfHeap_fresh...\n      apply heapLookup_ge...\n    - rewrite extend_neq in envLookup...\n      rewrite heapExtend_lookup_nlen...\n      apply envModelsHeap in envLookup as (F' & RL' & Hlookup & wfF' & wfRL')...\n      eexists; eexists; split...\n      split...\n      eapply wfFields_envExtend...\n      eapply wfHeap_fresh...\n      apply heapLookup_ge...\n  + introv Hlookup.\n    destruct (id_eq_dec l (length H))...\n    rewrite heapExtend_lookup_nlen in Hlookup...\nQed.\n\nLemma wfHeap_update :\n  forall P Gamma H l c F RL RL' F',\n    wfHeap P Gamma H ->\n    heapLookup H l = Some (c, F, RL) ->\n    wfFields P Gamma c F' ->\n    wfRegionLocks P c RL' ->\n    wfHeap P Gamma (heapUpdate H l (c, F', RL')).\nProof with eauto.\n  introv wfH Hlookup wfF' wfRL'.\n  inverts wfH as wfGamma envModelsHeap heapMirrorsEnv.\n  constructor...\n  + introv envLookup.\n    destruct (id_eq_dec l l0).\n    - subst.\n      rewrite lookup_heapUpdate_eq\n        by (apply heapLookup_lt; eauto).\n      apply envModelsHeap in envLookup as (F'' & RL'' & Hlookup' & wfF'' & wfRL'').\n      rewrite_and_invert...\n    - rewrite lookup_heapUpdate_neq...\n  + introv Hlookup'.\n    apply heapMirrorsEnv.\n    destruct (id_eq_dec l l0).\n    - subst.\n      rewrite heapLookup_not_none...\n    - rewrite lookup_heapUpdate_neq in Hlookup'...\nQed.\n\nLemma wfHeap_invariance :\n  forall P t' Gamma Gamma' H,\n    wfProgram P t' ->\n    (forall l, Gamma (env_loc l) = Gamma' (env_loc l)) ->\n    wfEnv P Gamma' ->\n    wfHeap P Gamma H ->\n    wfHeap P Gamma' H.\nProof with eauto using wfFields_invariance.\n  introv wfP envEquiv wfGamma' wfH.\n  inverts wfH as wfGamma envModelsHeap heapMirrorsEnv.\n  constructor...\n  + introv envLookup. rewrite <- envEquiv in envLookup.\n    apply envModelsHeap in envLookup.\n    inv envLookup as (F & RL & Hlookup & wfF & wfRL)...\n    exists F RL...\n  + introv Hlookup. rewrite <- envEquiv...\nQed.\n\n(*\n--------\nwfVars\n--------\n*)\n\nHint Constructors wfVars.\n\nLemma wfVars_invariance :\n  forall P t' Gamma Gamma' fsyms V,\n    wfProgram P t' ->\n    (forall x, Gamma x = Gamma' x) ->\n    wfEnv P Gamma' ->\n    wfVars P Gamma fsyms V ->\n    wfVars P Gamma' fsyms V.\nProof with eauto.\n  introv wfP envEquiv wfGamma' wfV.\n  inverts wfV as wfGamma envModelsVars varsMirrorEnv Hfresh.\n  constructor...\n  + introv Vlookup.\n    rewrite <- envEquiv in Vlookup.\n    apply envModelsVars in Vlookup as (v & Vlookup & hasType).\n    eapply hasType_subsumption with (Gamma' := Gamma') in hasType; crush...\n  + introv. rewrite <- envEquiv...\nQed.\n\nLemma wfVars_extend :\n  forall P t' Gamma n m V v t,\n    wfProgram P t' ->\n    wfVars P Gamma n V ->\n    P; Gamma |- EVal v \\in t ->\n    m < n ->\n    wfVars P (extend Gamma (env_var (DV (DVar m))) t)\n           n (extend V (DVar m) v).\nProof with eauto with env.\n  introv wfP wfV hasType Hlt.\n  inverts wfV as wfGamma envModelsVars varsMirrorEnv Hfresh.\n  constructor; eauto 3 with env.\n  + introv envLookup.\n    destruct (id_eq_dec (DVar m) x).\n    - subst. simpl_extend_hyp.\n      inv_eq.\n      exists v.\n      split...\n      inv hasType...\n    - rewrite extend_neq in envLookup...\n      apply envModelsVars in envLookup as (v' & Vlookup & hasType').\n      exists v'.\n      split...\n      inv hasType'...\n  + introv Hle. unfold fresh.\n    assert (m < n')\n        by omega.\n    case_extend; [inv_eq | apply Hfresh]; omega.\nQed.\n\nLemma wfVars_heapExtend :\n  forall Gamma P t' n V l c,\n    wfProgram P t' ->\n    wfVars P Gamma n V ->\n    fresh Gamma (env_loc l) ->\n    wfType P (TClass c) ->\n    wfVars P (extend Gamma (env_loc l) (TClass c)) n V.\nProof with eauto with env.\n  introv wfP wfV Hfresh wfT.\n  inverts wfV as wfGamma envModelsVars varsMirrorEnv freshVars.\n  constructor...\n  + introv envLookup.\n    simpl_extend_hyp.\n    apply envModelsVars in envLookup as (v & Vlookup & hasType).\n    exists v.\n    split...\n    inv hasType...\nQed.\n\nLemma wfVars_ge :\n  forall P Gamma n V m,\n    wfVars P Gamma n V ->\n    n <= m ->\n    wfVars P Gamma m V.\nProof with eauto.\n  introv wfV Hge.\n  inverts wfV as wfGamma envModels varsMirror Hfresh.\n  econstructor...\n  introv Hle.\n  assert (n <= n') by omega...\nQed.\n\n(*\n----------\nwfLocking\n----------\n*)\n\nHint Constructors wfHeldLocks.\nHint Constructors wfLocks.\nHint Constructors disjointLocks.\nHint Constructors wfLocking.\n\nLemma wfHeldLocks_heapExtend :\n  forall H Ls c F RL,\n    wfHeldLocks H Ls ->\n    wfHeldLocks (heapExtend H (c, F, RL)) Ls.\nProof with eauto.\n  introv wfLs.\n  constructor.\n  induction wfLs as [wfLs]...\n  rewrite Forall_forall in wfLs.\n  apply Forall_forall.\n  introv HIn.\n  apply wfLs in HIn as [].\n  assert (Hlt: l < length H) by\n      (eapply heapLookup_lt; eauto)...\n  econstructor...\n  rewrite heapExtend_lookup_nlen...\n  omega.\nQed.\n\nLemma wfLocking_heapExtend :\n  forall H T c F RL,\n    wfLocking H T ->\n    wfLocking (heapExtend H (c, F, RL)) T.\nProof with eauto using wfHeldLocks_heapExtend.\n  introv wfL.\n  induction wfL...\nQed.\n\nLemma wfHeldLocks_heapUpdate :\n  forall H Ls l c F F' RL RL',\n    wfHeldLocks H Ls ->\n    heapLookup H l = Some (c, F, RL) ->\n    (forall r, In (l, r) Ls -> RL' r = Some LLocked) ->\n    wfHeldLocks (heapUpdate H l (c, F', RL')) Ls.\nProof with eauto.\n  introv wfLs Hlookup HRL'.\n  induction wfLs as [wfLs]...\n  rewrite Forall_forall in wfLs.\n  constructors.\n  apply Forall_forall.\n  introv HIn.\n  assert(wfL: wfLock H x)...\n  inverts wfL as Hlookup' HRL.\n  destruct (id_eq_dec l l1).\n  + subst. rewrite_and_invert.\n    apply HRL' in HIn. subst.\n    apply WF_Lock with c0 F' RL'...\n    rewrite lookup_heapUpdate_eq...\n    apply heapLookup_lt...\n  + econstructor...\n    rewrite lookup_heapUpdate_neq...\nQed.\n\nLemma wfLocking_heapUpdate :\n  forall H T l c F F' RL RL',\n    wfLocking H T ->\n    heapLookup H l = Some (c, F, RL) ->\n    (forall r, In (l, r) (heldLocks T) -> RL' r = Some LLocked) ->\n    wfLocking (heapUpdate H l (c, F', RL')) T.\nProof with eauto using wfHeldLocks_heapUpdate.\n  introv wfL Hlookup HL.\n  induction wfL; simpls...\n  econstructor...\n  + apply IHwfL1...\n    - introv HIn.\n      apply HL. apply in_or_app...\n  + apply IHwfL2...\n    - introv HIn.\n      apply HL. apply in_or_app...\nQed.\n\nLemma wfHeldLocks_taken :\n  forall H Ls l r c RL F,\n    wfHeldLocks H Ls ->\n    In (l, r) Ls ->\n    heapLookup H l = Some (c, F, RL) ->\n    RL r = Some LLocked.\nProof with eauto.\n  introv wfLs HIn Hlookup.\n  induction wfLs as [wfLs]...\n  rewrite Forall_forall in wfLs.\n  apply wfLs in HIn. inv HIn.\n  rewrite_and_invert...\nQed.\n\nLemma wfLocks_econtext :\n  forall Ls e ctx,\n    is_econtext ctx ->\n    wfLocks Ls (ctx e) ->\n    wfLocks Ls e.\nProof with eauto using in_or_app.\n  introv Hctx wfL.\n  inv Hctx;\n    inverts wfL as Hlocks Hdup;\n    simpl in *...\n  + eapply NoDup_app in Hdup as []...\n  + inv Hdup...\nQed.\n\nLemma wfLocking_econtext :\n  forall ctx H Ls e,\n    is_econtext ctx ->\n    wfLocking H (T_Thread Ls (ctx e)) ->\n    wfLocking H (T_Thread Ls e).\nProof with eauto using wfLocks_econtext.\n  introv Hctx wfL.\n  inv wfL...\nQed.\n\nLemma wfLocking_subst :\n  forall H Ls e x y,\n    wfLocking H (T_Thread Ls e) ->\n    wfLocking H (T_Thread Ls (subst x y e)).\nProof with eauto.\n  introv wfL.\n  inverts wfL as wfLs Hdup wfL wfRl.\n  econstructor...\n  econstructor...\n  + rewrite <- locks_subst...\n    inv wfL...\n  + rewrite <- locks_subst...\n    inv wfL...\nQed.\n\nLemma locks_static :\n  forall e,\n    exprStatic e ->\n    locks e = nil.\nProof with eauto using app_eq_nil.\n  introv Hstatic.\n  induction Hstatic; simpl...\n  apply app_eq_nil...\nQed.\n\nLemma wfLocking_static :\n  forall H Ls e,\n    wfHeldLocks H Ls ->\n    NoDup Ls ->\n    exprStatic e ->\n    wfLocking H (T_Thread Ls e).\nProof with eauto using locks_static.\n  introv wfLs Hdup Hstatic.\n  assert (HL: locks e = nil)...\n  econstructor...\n  econstructor; rewrite HL...\n  introv HIn... inv HIn.\nQed.\n\nLemma disjointLocks_commutative :\n  forall T1 T2,\n    disjointLocks T1 T2 ->\n    disjointLocks T2 T1.\nProof with eauto.\n  introv Hdisj.\n  inv Hdisj. constructors...\nQed.\n\nLemma disjointLocks_async :\n  forall T T1 T2 e,\n    disjointLocks T1 T /\\\n    disjointLocks T2 T\n     <->\n    disjointLocks (T_Async T1 T2 e) T.\nProof with eauto using in_or_app.\n  split.\n  + introv Hdisj.\n    inverts Hdisj as Hdisj1 Hdisj2.\n    inverts Hdisj1. inverts Hdisj2.\n    constructor; simpl.\n    - introv HIn.\n      apply in_app_or in HIn as [|HIn]...\n    - introv HIn.\n      apply not_in_app...\n  + introv Hdisj.\n    inverts Hdisj as Hdisj1 Hdisj2.\n    simpls.\n    splits.\n    - constructor...\n      introv HIn.\n      apply Hdisj2 in HIn...\n    - constructor...\n      introv HIn.\n      apply Hdisj2 in HIn.\n      eapply not_in_app in HIn as []...\nQed.\n\nLemma disjointLocks_leftmost :\n  forall T1 T2,\n    disjointLocks T1 T2 ->\n    disjointLocks (T_EXN (leftmost_locks T1)) T2.\nProof with eauto using in_or_app.\n  introv Hdisj.\n  induction T1; simpls; inv Hdisj...\n  apply IHT1_1.\n  econstructor; crush...\nQed.\n\nLemma wfHeldLocks_app :\n  forall H Ls1 Ls2,\n    (wfHeldLocks H Ls1 /\\ wfHeldLocks H Ls2 <-> wfHeldLocks H (Ls1 ++ Ls2)).\nProof with eauto using in_eq, in_cons.\n  split.\n  + introv wfLs.\n    inverts wfLs as wfLs1 wfLs2.\n    constructor.\n    apply Forall_app...\n    inv wfLs1...\n    inv wfLs2...\n  + introv wfLs.\n    induction Ls1 as [|l]; simpls...\n    inverts wfLs as wfLs.\n    inverts wfLs as wfL wfLs'.\n    assert(wfLs: wfHeldLocks H (Ls1 ++ Ls2))...\n    apply IHLs1 in wfLs as [wfLs1 wfLs2]...\n    split...\n    econstructor...\n    econstructor...\n    apply Forall_forall.\n    rewrite Forall_forall in wfLs'.\n    introv HIn.\n    assert (HIn': In x (Ls1 ++ Ls2))\n      by eauto using in_or_app...\nQed.\n\nLemma wfHeldLocks_cons :\n  forall H Ls l,\n    wfHeldLocks H Ls ->\n    wfLock H l ->\n    wfHeldLocks H (l :: Ls).\nProof with eauto.\n  introv wfLs wfL.\n  inv wfLs...\nQed.\n\nLemma wfHeldLocks_leftmost :\n  forall H T,\n    wfLocking H T ->\n    wfHeldLocks H (leftmost_locks T).\nProof with eauto.\n  introv wfL.\n  induction T; inv wfL...\nQed.\n\nLemma wfHeldLocks_remove :\n  forall H Ls L eq_dec,\n    wfHeldLocks H Ls ->\n    wfHeldLocks H (remove eq_dec L Ls).\nProof with eauto using wfHeldLocks_cons.\n  introv wfLs.\n  induction Ls as [| l]...\n  inverts wfLs as wfLs.\n  inverts wfLs.\n  simpl. cases_if...\nQed.\n\nCorollary wfLocking_wfHeldLocks :\n  forall H T,\n    wfLocking H T ->\n    wfHeldLocks H (heldLocks T).\nProof with eauto.\n  introv wfL.\n  induction T; simpls; inv wfL...\n  apply wfHeldLocks_app...\nQed.\n\n(*\n----------\nwfThreads\n----------\n*)\n\nHint Constructors wfThreads.\n\nCorollary wfThreads_wfEnv :\n  forall P t' Gamma T t,\n    wfProgram P t' ->\n    wfThreads P Gamma T t ->\n    wfEnv P Gamma.\nProof with eauto with env.\n  introv wfP wfT. inv wfT...\nQed.\n\nHint Immediate wfThreads_wfEnv.\n\nLemma wfThreads_invariance :\n  forall P t' Gamma Gamma' T t,\n    wfProgram P t' ->\n    (forall x, Gamma x = Gamma' x) ->\n    wfThreads P Gamma T t ->\n    wfThreads P Gamma' T t.\nProof with eauto using hasType_subsumption,\n                       wfEnv_equiv with env.\n  introv wfP Hequiv wfT.\n  induction wfT...\nQed.\n\nLemma wfThreads_subsumption :\n  forall P t' Gamma Gamma' T t,\n    wfProgram P t' ->\n    wfSubsumption Gamma Gamma' ->\n    wfEnv P Gamma' ->\n    wfThreads P Gamma T t ->\n    wfThreads P Gamma' T t.\nProof with eauto using hasType_subsumption with env.\n  introv wfP wfEnv' Hsub wfT.\n  induction wfT...\nQed.\n\nLemma wfThreads_heapExtend :\n  forall P t' Gamma T t c l,\n    wfProgram P t' ->\n    wfType P (TClass c) ->\n    fresh Gamma (env_loc l) ->\n    wfThreads P Gamma T t ->\n    wfThreads P (extend Gamma (env_loc l) (TClass c)) T t.\nProof with eauto using hasType_extend_loc with env.\n  introv wfP wfTy Hfresh wfT.\n  generalize dependent t.\n  induction T; intros; inv wfT...\nQed.\n\n(*\n----------------\nwfConfiguration\n----------------\n*)\n\nHint Constructors wfConfiguration.\n\nLemma wfConfiguration_substitution :\n  forall P Gamma H V n Ls e e' t,\n    freeVars e' = nil ->\n    P; Gamma |- e' \\in t ->\n    wfLocking H (T_Thread Ls e') ->\n    wfConfiguration P Gamma (H, V, n, T_Thread Ls e) t ->\n    wfConfiguration P Gamma (H, V, n, T_Thread Ls e') t.\nProof with eauto.\n  introv Hfree hasType wfL wfCfg.\n  inverts wfCfg...\nQed.\n\nLemma wfConfiguration_heapExtend :\n  forall P t' Gamma H V n T t c F RL,\n    wfProgram P t' ->\n    wfConfiguration P Gamma (H, V, n, T) t ->\n    wfType P (TClass c) ->\n    wfFields P Gamma c F ->\n    wfRegionLocks P c RL ->\n    wfConfiguration P (extend Gamma (env_loc (length H)) (TClass c))\n                    ((heapExtend H (c, F, RL)), V, n, T) t.\nProof with eauto 6 using\n                 wfHeap_extend,\n                 wfVars_heapExtend,\n                 wfThreads_heapExtend,\n                 wfLocking_heapExtend with env.\n  introv wfP wfCfg wfTy wfF wfRL.\n  inverts wfCfg.\n  assert(fresh Gamma (env_loc (length H)))\n    by eauto using wfHeap_fresh, heapLookup_ge...\nQed.\n\nLemma wfConfiguration_heapUpdate :\n  forall P t' Gamma H V n T t l c F RL RL' F',\n    wfProgram P t' ->\n    wfConfiguration P Gamma (H, V, n, T) t ->\n    heapLookup H l = Some (c, F, RL) ->\n    wfFields P Gamma c F' ->\n    wfRegionLocks P c RL' ->\n    (forall r, In (l, r) (heldLocks T) -> RL' r = Some LLocked) ->\n    wfConfiguration P Gamma\n                    ((heapUpdate H l (c, F', RL')), V, n, T) t.\nProof with eauto using\n                 wfHeap_update,\n                 wfLocking_heapUpdate.\n  introv wfP wfCfg HLookup wfF' wfRL' HL.\n  inverts wfCfg...\nQed.", "meta": {"author": "EliasC", "repo": "oolong", "sha": "f449d42f70da1c404883860296ec4f2c5ed088b7", "save_path": "github-repos/coq/EliasC-oolong", "path": "github-repos/coq/EliasC-oolong/oolong-f449d42f70da1c404883860296ec4f2c5ed088b7/coq/regions/WellFormednessProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22450508185939286}}
{"text": "Require Import VST.floyd.proofauto.\n(* Require Export VST.floyd.Funspec_old_Notation. *)\n\nRequire Import listfree2.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\n\nFixpoint lseg (x: val) (s: list val) (size: nat) : mpred :=\n  match size with\n  | S size'  =>\n    EX nxt:val, EX v:val, EX s': list val,\n    !!not(x = nullval) &&\n     !! (s = v :: s') &&\n      data_at Tsh (tarray (tptr tvoid) 2) (v :: nxt :: []) x *\n      lseg nxt s' size'\n  (*data_at Tsh (tptr tint) v x * data_at Tsh (tptr tint) nxt (offset_val 4 x) * lseg nxt s' size*)\n  | O  => !!(x = nullval) && !!(s = nil)  && emp\n  end.\n\n(* helper obvious facts *)\nLemma lseg_lenP x s size :\n  lseg x s size |-- !!(size = length s).\nProof.\n  revert s x.\n  induction size.\n  - simpl. entailer!.\n  - {\n      simpl. intros s x. Intros nxt v s'.\n      revert H0; case s.\n      - simpl; intro H1; case (@nil_cons _ v s' H1).\n      - {\n          intros v_2 s'_2 H1; pose proof (@cons_inv _ _ _ _ _ H1) as H2.\n          destruct H2 as [H3 H4].\n          rewrite H3; rewrite H4; clear H3 H4 H1 v_2 s'_2; simpl.\n          pose proof (@cancel_left (data_at Tsh (tarray (tptr tint) 2) [v; nxt] x) _  _ (IHsize s' nxt) ).\n          entailer!.\n        }\n    }\nQed.\n\n\nLemma lseg_valid_pointer_or_nullP p s size:\n  lseg p s size |-- !! is_pointer_or_null p.\nProof.\n  destruct size as [|size]; simpl.\n  - entailer!.\n  - Intros nxt v s'. entailer!.\nQed.\n\nLemma lseg_valid_pointerP p s size:\n  lseg p s size |--  valid_pointer p.\nProof.\n  destruct size as [|size]; simpl.\n  - entailer!.\n  - Intros nxt v s'. entailer!.\nQed.\n\nLemma lseg_pointer_contentsP p s size:\n  lseg p s size |-- !!(p=nullval <-> s=nil).\nProof.\n  destruct size as [|size]; simpl.\n  - entailer!; intuition.\n  - {\n      Intros nxt v s'.\n      entailer!.\n      split.\n      - intro H3; case (H H3).\n      - intro H3.\n        case (@nil_cons _ _ _ (@eq_sym _ _ _ H3 )).\n    }\nQed.\n\nLemma lseg_size_negP p s size:\n  lseg p s size |-- !! ((p <> nullval) <-> (gt size 0)).\nProof.\n  destruct size as [| size]; simpl.\n  - entailer!.\n    split.\n    intro H; case (H (eq_refl nullval)).\n    intro H; case (gt_irrefl 0 H).\n  -\n    Intros nxt v s'.\n    entailer!.\n    split.\n    intro; apply gt_Sn_O.\n    auto.\nQed.\n    \n\nLemma lseg_local_factsP p s size :\n  lseg p s size |-- !!( (size = length s) /\\ ((p=nullval -> s=nil) /\\\n                                              ((is_pointer_or_null p) /\\\n                                               (((p <> nullval) -> (gt size 0)))))).\nProof.\n  rewrite prop_and.\n  apply andp_right.\n  apply lseg_lenP.\n  rewrite prop_and.\n  apply andp_right.\n  pose proof lseg_pointer_contentsP; entailer!; try destruct H0; entailer!.\n  rewrite prop_and.\n  apply andp_right.\n  apply lseg_valid_pointer_or_nullP.\n  pose proof lseg_size_negP; entailer!; try destruct H0; entailer!.\nQed.\n\nLemma is_pointer_or_null_not_null:\n forall x, is_pointer_or_null x -> x <> nullval -> isptr x.\nProof.\nintros.\n destruct x; try contradiction. hnf in H; subst i. contradiction H0; reflexivity.\n apply I.\nQed.\n\n\nDefinition listfree_spec :=\n  DECLARE _listfree\n          WITH s: list val, x: val\n                                 PRE  [ (tptr tvoid) ]\n                                 PROP()\n                                 PARAMS(x)\n                                 SEP (lseg x s (length s))\n                                 POST [ Tvoid ]\n                                 PROP()\n                                 LOCAL()\n                                 SEP (emp).\n\nDefinition free_spec :=\n  DECLARE _free\n          WITH x: val, s: list val\n                              PRE  [ (tptr tvoid) ]\n                              PROP()\n                              PARAMS(x)\n                              SEP (data_at Tsh (tarray (tptr tvoid) 2) s x)\n                              POST [ Tvoid ]\n                              PROP()\n                              LOCAL()\n                              SEP (emp).\n\n\n(* Packaging the API spec all together. *)\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [listfree_spec; free_spec]).\n\n(** Proof that f_listfree, the body of the listfree() function,\n ** satisfies listfree_spec, in the global context (Vprog,Gprog).\n **)\nFrom mathcomp Require Import ssreflect.\nHint Resolve lseg_valid_pointerP: valid_pointer.\nHint Resolve lseg_local_factsP : saturate_local.\n\nLemma body_listfree : semax_body Vprog Gprog f_listfree listfree_spec.\nProof.\n  start_function. \n  forward_if.\n  - forward.\n    (* x = null *)\n    move: (H0 (eq_refl nullval)) => ->; (* lseg (x, nil, 0) *) simpl.\n    entailer!.\n  - assert_PROP ((Datatypes.length s) > 0)%nat. { entailer!. }\n    case: s H0; first by simpl=>/gt_irrefl.\n    simpl lseg => y ys _.\n    Intros nxt v s'.\n    forward. (* _t = x[1] *)\n    forward_call (s', nxt).\n    * entailer!; rewrite H3; entailer!.\n    * forward_call (x, [v; nxt]).\n      entailer!.\nQed.\n\n", "meta": {"author": "yasunariw", "repo": "certified-programs", "sha": "feb016c943ab86ba5ea06726fba01ba8418059bf", "save_path": "github-repos/coq/yasunariw-certified-programs", "path": "github-repos/coq/yasunariw-certified-programs/certified-programs-feb016c943ab86ba5ea06726fba01ba8418059bf/vst/verif_listfree2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22450508185939286}}
{"text": "From Coq Require Import Reals Psatz.\nFrom iris.prelude Require Import options.\nFrom iris.algebra Require Import ofe.\nFrom iris.bi Require Export weakestpre.\nFrom self.prelude Require Import classical.\nFrom self.prob Require Import distribution.\n\n\nSection language_mixin.\n  Context {expr val state state_idx : Type}.\n  Context `{Countable expr, Countable val, Countable state, Countable state_idx}.\n\n  Context (of_val : val → expr).\n  Context (to_val : expr → option val).\n\n  Context (prim_step  : expr → state → distr (expr * state)).\n  Context (state_step : state → state_idx → distr state).\n  (* For [prob_lang] this will just be [λ σ, elements (dom σ.(tapes))] - it'll\n     be nicer with just a set but there's no set-big_op for disjunction in Iris\n     at the moment, so lets stick to a list for now *)\n  Context (get_active : state → list state_idx).\n\n  Record LanguageMixin := {\n    mixin_to_of_val v : to_val (of_val v) = Some v;\n    mixin_of_to_val e v : to_val e = Some v → of_val v = e;\n    mixin_val_stuck e σ ρ : prim_step e σ ρ > 0 → to_val e = None;\n    (** [state_step] preserves reducibility *)\n    mixin_state_step_not_stuck e σ σ' α :\n      state_step σ α σ' > 0 → (∃ ρ, prim_step e σ ρ > 0) ↔ (∃ ρ', prim_step e σ' ρ' > 0);\n    (** The mass of active [state_step]s is 1 *)\n    mixin_state_step_mass σ α :\n      α ∈ get_active σ → SeriesC (state_step σ α) = 1;\n    (** The mass of reducible [prim_step]s is 1 *)\n    mixin_prim_step_mass e σ :\n      (∃ ρ, prim_step e σ ρ > 0) → SeriesC (prim_step e σ) = 1;\n  }.\nEnd language_mixin.\n\nStructure language := Language {\n  expr : Type;\n  val : Type;\n  state : Type;\n  state_idx : Type;\n\n  expr_eqdec : EqDecision expr;\n  val_eqdec : EqDecision val;\n  state_eqdec : EqDecision state;\n  state_idx_eqdec : EqDecision state_idx;\n  expr_countable : Countable expr;\n  val_countable : Countable val;\n  state_countable : Countable state;\n  state_idx_countable : Countable state_idx;\n\n  of_val : val → expr;\n  to_val : expr → option val;\n  prim_step : expr → state → distr (expr * state);\n  state_step : state → state_idx → distr state;\n  get_active : state → list state_idx;\n\n  language_mixin : LanguageMixin of_val to_val prim_step state_step get_active\n}.\n\nBind Scope expr_scope with expr.\nBind Scope val_scope with val.\n\nGlobal Arguments Language {_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ } _.\nGlobal Arguments of_val {_} _.\nGlobal Arguments to_val {_} _.\nGlobal Arguments state_step {_}.\nGlobal Arguments prim_step {_} _ _.\nGlobal Arguments get_active {_} _.\n\n#[global] Existing Instance expr_eqdec.\n#[global] Existing Instance val_eqdec.\n#[global] Existing Instance state_eqdec.\n#[global] Existing Instance expr_countable.\n#[global] Existing Instance val_countable.\n#[global] Existing Instance state_countable.\n#[global] Existing Instance state_idx_countable.\n\nCanonical Structure stateO Λ := leibnizO (state Λ).\nCanonical Structure valO Λ := leibnizO (val Λ).\nCanonical Structure exprO Λ := leibnizO (expr Λ).\n\nDefinition cfg (Λ : language) := (expr Λ * state Λ)%type.\n\nDefinition fill_lift {Λ} (K : expr Λ → expr Λ) : (expr Λ * state Λ) → (expr Λ * state Λ) :=\n  λ '(e, σ), (K e, σ).\n\nGlobal Instance inj_fill_lift {Λ : language} (K : expr Λ → expr Λ) :\n  Inj (=) (=) K →\n  Inj (=) (=) (fill_lift K).\nProof. by intros ? [] [] [=->%(inj _) ->]. Qed.\n\nClass LanguageCtx {Λ : language} (K : expr Λ → expr Λ) := {\n  fill_not_val e :\n    to_val e = None → to_val (K e) = None;\n  fill_inj : Inj (=) (=) K;\n  fill_dmap e1 σ1 :\n    to_val e1 = None →\n    prim_step (K e1) σ1 = dmap (fill_lift K) (prim_step e1 σ1)\n}.\n\n#[global] Existing Instance fill_inj.\n\nInductive atomicity := StronglyAtomic | WeaklyAtomic.\n\n(* Definition stuckness_to_atomicity (s : stuckness) : atomicity := *)\n(*   if s is MaybeStuck then StronglyAtomic else WeaklyAtomic. *)\n\nSection language.\n  Context {Λ : language}.\n  Implicit Types v : val Λ.\n  Implicit Types e : expr Λ.\n  Implicit Types σ : state Λ.\n\n  Lemma to_of_val v : to_val (of_val v) = Some v.\n  Proof. apply language_mixin. Qed.\n  Lemma of_to_val e v : to_val e = Some v → of_val v = e.\n  Proof. apply language_mixin. Qed.\n  Lemma val_stuck e σ ρ : prim_step e σ ρ > 0 → to_val e = None.\n  Proof. apply language_mixin. Qed.\n  Lemma state_step_not_stuck e σ σ' α :\n    state_step σ α σ' > 0 → (∃ ρ, prim_step e σ ρ > 0) ↔ (∃ ρ', prim_step e σ' ρ' > 0).\n  Proof. apply language_mixin. Qed.\n  Lemma state_step_mass σ α : α ∈ get_active σ → SeriesC (state_step σ α) = 1.\n  Proof. apply language_mixin. Qed.\n  Lemma prim_step_mass e σ :\n    (∃ ρ, prim_step e σ ρ > 0) → SeriesC (prim_step e σ) = 1.\n  Proof. apply language_mixin. Qed.\n\n  Definition reducible (e : expr Λ) (σ : state Λ) :=\n    ∃ ρ, prim_step e σ ρ > 0.\n  Definition irreducible (e : expr Λ) (σ : state Λ) :=\n    ∀ ρ, prim_step e σ ρ = 0.\n  Definition stuck (e : expr Λ) (σ : state Λ) :=\n    to_val e = None ∧ irreducible e σ.\n  Definition not_stuck (e : expr Λ) (σ : state Λ) :=\n    is_Some (to_val e) ∨ reducible e σ.\n\n  Class Atomic (a : atomicity) (e : expr Λ) : Prop :=\n    atomic σ e' σ' :\n      prim_step e σ (e', σ') > 0 →\n      if a is WeaklyAtomic then irreducible e' σ' else is_Some (to_val e').\n\n  Inductive step (ρ1 : cfg Λ) (ρ2 : cfg Λ) : Prop :=\n  | step_atomic e1 σ1 :\n    ρ1 = (e1, σ1) →\n    prim_step e1 σ1 ρ2 > 0 →\n    step ρ1 ρ2\n  | step_state e α σ1 σ2 :\n    ρ1 = (e, σ1) →\n    ρ2 = (e, σ2) →\n    state_step σ1 α σ2 > 0 →\n    step ρ1 ρ2.\n  Local Hint Constructors step : core.\n\n  Lemma of_to_val_flip v e : of_val v = e → to_val e = Some v.\n  Proof. intros <-. by rewrite to_of_val. Qed.\n  Lemma not_reducible e σ : ¬reducible e σ ↔ irreducible e σ.\n  Proof.\n    unfold reducible, irreducible. split.\n    - move=> /not_exists_forall_not Hneg ρ.\n      specialize (Hneg ρ). apply Rnot_gt_ge in Hneg.\n      pose proof (pmf_pos (prim_step e σ) ρ). lra.\n    - intros Hall [ρ ?]. specialize (Hall ρ). lra.\n  Qed.\n  Lemma reducible_not_val e σ : reducible e σ → to_val e = None.\n  Proof. intros ([] & ?). eauto using val_stuck. Qed.\n  Lemma val_irreducible e σ : is_Some (to_val e) → irreducible e σ.\n  Proof.\n    intros [??] ?.\n    destruct (pmf_pos (prim_step e σ) ρ) as [Hs%val_stuck|]; [|done].\n    simplify_eq.\n  Qed.\n  Global Instance of_val_inj : Inj (=) (=) (@of_val Λ).\n  Proof. by intros v v' Hv; apply (inj Some); rewrite -!to_of_val Hv. Qed.\n  Lemma not_not_stuck e σ : ¬not_stuck e σ ↔ stuck e σ.\n  Proof.\n    rewrite /stuck /not_stuck -not_eq_None_Some -not_reducible.\n    destruct (decide (to_val e = None)); naive_solver.\n  Qed.\n  Lemma val_stuck_dzero e σ :\n    is_Some (to_val e) → prim_step e σ = dzero.\n  Proof.\n    intros []. apply distr_ext=>ρ.\n    destruct (decide (prim_step e σ ρ > 0)) as\n      [?%val_stuck | ->%pmf_eq_0_not_gt_0]; [|done].\n    simplify_eq.\n  Qed.\n  Lemma irreducible_dzero e σ :\n    irreducible e σ → prim_step e σ = dzero.\n  Proof.\n    intros Hirr%not_reducible. apply dzero_ext=> ρ.\n    destruct (Req_dec (prim_step e σ ρ)0); [done|].\n    exfalso. eapply Hirr.\n    exists ρ.\n    pose proof (pmf_le_1 (prim_step e σ) ρ).\n    pose proof (pmf_pos (prim_step e σ) ρ).\n    lra.\n  Qed.\n\n  Lemma strongly_atomic_atomic e a :\n    Atomic StronglyAtomic e → Atomic a e.\n  Proof. unfold Atomic. destruct a; eauto using val_irreducible. Qed.\n\n  Lemma fill_step e1 σ1 e2 σ2 `{!LanguageCtx K} :\n    prim_step e1 σ1 (e2, σ2) > 0 →\n    prim_step (K e1) σ1 (K e2, σ2) > 0.\n  Proof.\n    intros Hs.\n    rewrite fill_dmap; [|by eapply val_stuck].\n    apply dbind_pos_support. eexists (_,_). split; [|done].\n    rewrite dret_1_1 //. lra.\n  Qed.\n\n  Lemma fill_step_inv e1' σ1 e2 σ2 `{!LanguageCtx K} :\n    to_val e1' = None → prim_step (K e1') σ1 (e2, σ2) > 0 →\n    ∃ e2', e2 = K e2' ∧ prim_step e1' σ1 (e2', σ2) > 0.\n  Proof.\n    intros Hv. rewrite fill_dmap //.\n    intros ([e1 σ1'] & [=]%dret_pos & Hstep)%dbind_pos_support.\n    subst. eauto.\n  Qed.\n\n  Lemma fill_step_prob e1 σ1 e2 σ2 `{!LanguageCtx K} :\n    to_val e1 = None →\n    prim_step e1 σ1 (e2, σ2) = prim_step (K e1) σ1 (K e2, σ2).\n  Proof.\n    intros Hv. rewrite fill_dmap //.\n    by erewrite (dmap_elem_eq _ (e2, σ2) _ (λ '(e0, σ0), (K e0, σ0))).\n  Qed.\n\n  Lemma reducible_fill `{!@LanguageCtx Λ K} e σ :\n    reducible e σ → reducible (K e) σ.\n  Proof.\n    unfold reducible in *. intros [[] ?]. eexists; by apply fill_step.\n  Qed.\n  Lemma reducible_fill_inv `{!@LanguageCtx Λ K} e σ :\n    to_val e = None → reducible (K e) σ → reducible e σ.\n  Proof.\n    intros ? [[e1 σ1] Hstep]; unfold reducible.\n    rewrite fill_dmap // in Hstep.\n    apply dmap_pos in Hstep as ([e1' σ2] & ? & Hstep).\n    eauto.\n  Qed.\n  Lemma state_step_reducible e σ σ' α :\n    state_step σ α σ' > 0 → reducible e σ ↔ reducible e σ'.\n  Proof. apply state_step_not_stuck. Qed.\n\n  Lemma irreducible_fill `{!@LanguageCtx Λ K} e σ :\n    to_val e = None → irreducible e σ → irreducible (K e) σ.\n  Proof. rewrite -!not_reducible. naive_solver eauto using reducible_fill_inv. Qed.\n  Lemma irreducible_fill_inv `{!@LanguageCtx Λ K} e σ :\n    irreducible (K e) σ → irreducible e σ.\n  Proof. rewrite -!not_reducible. naive_solver eauto using reducible_fill. Qed.\n\n  Lemma not_stuck_fill_inv K `{!@LanguageCtx Λ K} e σ :\n    not_stuck (K e) σ → not_stuck e σ.\n  Proof.\n    rewrite /not_stuck -!not_eq_None_Some. intros [?|?].\n    - auto using fill_not_val.\n    - destruct (decide (to_val e = None)); eauto using reducible_fill_inv.\n  Qed.\n\n  Lemma stuck_fill `{!@LanguageCtx Λ K} e σ :\n    stuck e σ → stuck (K e) σ.\n  Proof. rewrite -!not_not_stuck. eauto using not_stuck_fill_inv. Qed.\n\n  Record pure_step (e1 e2 : expr Λ)  := {\n    pure_step_safe σ1 : reducible e1 σ1;\n    pure_step_det σ : prim_step e1 σ (e2, σ) = 1;\n  }.\n\n  Class PureExec (φ : Prop) (n : nat) (e1 e2 : expr Λ) :=\n    pure_exec : φ → relations.nsteps pure_step n e1 e2.\n\n  Lemma pure_step_ctx K `{!@LanguageCtx Λ K} e1 e2 :\n    pure_step e1 e2 → pure_step (K e1) (K e2).\n  Proof.\n    intros [Hred Hstep]. split.\n    - unfold reducible in *. intros σ1.\n      destruct (Hred σ1) as [[]].\n      eexists. by eapply fill_step.\n    - intros σ.\n      rewrite -fill_step_prob //; eauto using (reducible_not_val _ σ).\n  Qed.\n\n  Lemma pure_step_nsteps_ctx K `{!@LanguageCtx Λ K} n e1 e2 :\n    relations.nsteps pure_step n e1 e2 →\n    relations.nsteps pure_step n (K e1) (K e2).\n  Proof. eauto using nsteps_congruence, pure_step_ctx. Qed.\n\n  Lemma rtc_pure_step_ctx K `{!@LanguageCtx Λ K} e1 e2 :\n    rtc pure_step e1 e2 → rtc pure_step (K e1) (K e2).\n  Proof. eauto using rtc_congruence, pure_step_ctx. Qed.\n\n  (* We do not make this an instance because it is awfully general. *)\n  Lemma pure_exec_ctx K `{!@LanguageCtx Λ K} φ n e1 e2 :\n    PureExec φ n e1 e2 →\n    PureExec φ n (K e1) (K e2).\n  Proof. rewrite /PureExec; eauto using pure_step_nsteps_ctx. Qed.\n\n  (* This is a family of frequent assumptions for PureExec *)\n  Class IntoVal (e : expr Λ) (v : val Λ) :=\n    into_val : of_val v = e.\n\n  Class AsVal (e : expr Λ) := as_val : ∃ v, of_val v = e.\n  (* There is no instance [IntoVal → AsVal] as often one can solve [AsVal] more *)\n  (* efficiently since no witness has to be computed. *)\n  Global Instance as_vals_of_val vs : TCForall AsVal (of_val <$> vs).\n  Proof.\n    apply TCForall_Forall, Forall_fmap, Forall_true=> v.\n    rewrite /AsVal /=; eauto.\n  Qed.\n\n  Lemma as_val_is_Some e :\n    (∃ v, of_val v = e) → is_Some (to_val e).\n  Proof. intros [v <-]. rewrite to_of_val. eauto. Qed.\n\n  Lemma fill_is_val e K `{@LanguageCtx Λ K} :\n    is_Some (to_val (K e)) → is_Some (to_val e).\n  Proof. rewrite -!not_eq_None_Some. eauto using fill_not_val. Qed.\n\n  Lemma prim_step_not_stuck e σ e' σ' :\n    prim_step e σ (e', σ') > 0 → not_stuck e σ.\n  Proof. rewrite /not_stuck /reducible. eauto 10. Qed.\n\n  Lemma rtc_pure_step_val `{!Inhabited (state Λ)} v e :\n    rtc pure_step (of_val v) e → to_val e = Some v.\n  Proof.\n    intros ?; rewrite <- to_of_val.\n    f_equal; symmetry; eapply rtc_nf; first done.\n    intros [e' [Hstep _]].\n    specialize (Hstep inhabitant) as [? Hval%val_stuck].\n    by rewrite to_of_val in Hval.\n  Qed.\nEnd language.\n\nGlobal Hint Mode PureExec + - - ! - : typeclass_instances.\n\nGlobal Arguments step_atomic {Λ ρ1 ρ2}.\nGlobal Arguments step_state {Λ ρ1 ρ2}.\n", "meta": {"author": "logsem", "repo": "clutch", "sha": "35144f9b1fe9c913b4bd24106a12ac7f02b20ec5", "save_path": "github-repos/coq/logsem-clutch", "path": "github-repos/coq/logsem-clutch/clutch-35144f9b1fe9c913b4bd24106a12ac7f02b20ec5/theories/program_logic/language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.22449605900427408}}
{"text": "(** Construction of actegory morphisms\n\nPart Generalization of pointed distributivity laws to lifted distributivity laws in general monads\n- definition\n- construction of actegory morphism from it\n- composition\n\nPart Closure of the notion of actegory morphisms under\n- the pointwise binary product of functors\n- the pointwise binary coproduct of functors\n\n\nauthor: Ralph Matthes 2022\n *)\n\nRequire Import UniMath.Foundations.All.\nRequire Import UniMath.MoreFoundations.All.\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.PrecategoryBinProduct.\nRequire Import UniMath.CategoryTheory.whiskering.\nRequire Import UniMath.CategoryTheory.Monoidal.WhiskeredBifunctors.\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\nRequire Import UniMath.CategoryTheory.Monoidal.Functors.\nRequire Import UniMath.CategoryTheory.Actegories.Actegories.\nRequire Import UniMath.CategoryTheory.Actegories.MorphismsOfActegories.\nRequire Import UniMath.CategoryTheory.Actegories.ConstructionOfActegories.\nRequire Import UniMath.CategoryTheory.coslicecat.\nRequire Import UniMath.CategoryTheory.Monoidal.Examples.MonoidalPointedObjects.\nRequire Import UniMath.CategoryTheory.limits.binproducts.\nRequire Import UniMath.CategoryTheory.limits.bincoproducts.\nRequire Import UniMath.CategoryTheory.limits.coproducts.\nRequire Import UniMath.CategoryTheory.Actegories.CoproductsInActegories.\nRequire Import UniMath.CategoryTheory.Actegories.ProductsInActegories.\nRequire Import UniMath.CategoryTheory.Actegories.ProductActegory.\n\nLocal Open Scope cat.\n\nImport BifunctorNotations.\nImport MonoidalNotations.\nImport ActegoryNotations.\n\nSection LiftedLineatorAndLiftedDistributivity.\n\n  Context {V : category} (Mon_V : monoidal V)\n          {W : category} (Mon_W : monoidal W)\n          {F : W ⟶ V} (U : fmonoidal Mon_W Mon_V F).\n\n\nSection LiftedLaxLineator.\n\n  Context {C D : category} (ActC : actegory Mon_V C) (ActD : actegory Mon_V D).\n\nSection OnFunctors.\n\n  Context {H : functor C D} (ll : lineator_lax Mon_V ActC ActD H).\n\n  Definition lifted_lax_lineator_data : lineator_data Mon_W (lifted_actegory Mon_V ActC Mon_W U)\n                                                            (lifted_actegory Mon_V ActD Mon_W U) H.\n  Proof.\n    intros w c. exact (ll (F w) c).\n  Defined.\n\n  Lemma lifted_lax_lineator_laws : lineator_laxlaws Mon_W (lifted_actegory Mon_V ActC Mon_W U)\n                                     (lifted_actegory Mon_V ActD Mon_W U) H lifted_lax_lineator_data.\n  Proof.\n    split4.\n    - intro; intros. apply (lineator_linnatleft _ _ _ _ ll).\n    - intro; intros. apply (lineator_linnatright _ _ _ _ ll).\n    - intro; intros. cbn. unfold lifted_lax_lineator_data, lifted_actor_data.\n      etrans.\n      2: { repeat rewrite assoc'. apply maponpaths.\n           rewrite assoc.\n           apply (lineator_preservesactor _ _ _ _ ll). }\n      etrans.\n      2: { rewrite assoc.\n           apply cancel_postcomposition.\n           apply pathsinv0, lineator_linnatright. }\n      etrans.\n      2: { rewrite assoc'.\n           apply maponpaths.\n           apply functor_comp. }\n      apply idpath.\n    - intro; intros. cbn. unfold lifted_lax_lineator_data, lifted_action_unitor_data.\n      etrans.\n      2: { apply maponpaths.\n           apply (lineator_preservesunitor _ _ _ _ ll). }\n      etrans.\n      2: { rewrite assoc.\n           apply cancel_postcomposition.\n           apply pathsinv0, lineator_linnatright. }\n      etrans.\n      2: { rewrite assoc'.\n           apply maponpaths.\n           apply functor_comp. }\n      apply idpath.\n  Qed.\n\n  Definition lifted_lax_lineator : lineator_lax Mon_W (lifted_actegory Mon_V ActC Mon_W U)\n                                                      (lifted_actegory Mon_V ActD Mon_W U) H :=\n    _,,lifted_lax_lineator_laws.\n\nEnd OnFunctors.\n\nSection OnNaturalTransformations.\n\n  Context {H : functor C D} (Hl : lineator_lax Mon_V ActC ActD H)\n    {K : functor C D} (Kl : lineator_lax Mon_V ActC ActD K)\n    {ξ : H ⟹ K} (islntξ : is_linear_nat_trans Hl Kl ξ).\n\n  Lemma preserves_linearity_lifted_lax_lineator :\n    is_linear_nat_trans (lifted_lax_lineator Hl) (lifted_lax_lineator Kl) ξ.\n  Proof.\n    intros w c.\n    apply islntξ.\n  Qed.\n\nEnd OnNaturalTransformations.\n\nEnd LiftedLaxLineator.\n\nSection LiftedDistributivity.\n\nSection FixAnObject.\n\n  Context {v0 : V}.\n\n  Definition lifteddistributivity_data: UU := ∏ (w: W), F w ⊗_{Mon_V} v0 --> v0 ⊗_{Mon_V} F w.\n\n  Identity Coercion lifteddistributivity_data_funclass: lifteddistributivity_data >-> Funclass.\n\nSection δ_laws.\n\n  Context (δ : lifteddistributivity_data).\n\n  Definition lifteddistributivity_nat: UU := is_nat_trans (functor_composite F (rightwhiskering_functor Mon_V v0))\n                                                           (functor_composite F (leftwhiskering_functor Mon_V v0)) δ.\n\n  Definition lifteddistributivity_tensor_body (w w' : W): UU :=\n    δ (w ⊗_{Mon_W} w') = pr1 (fmonoidal_preservestensorstrongly U w w') ⊗^{Mon_V}_{r} v0 · α_{Mon_V} _ _ _ ·\n                           F w ⊗^{Mon_V}_{l} δ w' · αinv_{Mon_V} _ _ _ · δ w ⊗^{Mon_V}_{r} F w' ·\n                           α_{Mon_V} _ _ _ · v0 ⊗^{Mon_V}_{l} fmonoidal_preservestensordata U w w'.\n\n  Definition lifteddistributivity_tensor: UU := ∏ (w w' : W), lifteddistributivity_tensor_body w w'.\n\n  Definition lifteddistributivity_unit: UU :=\n    δ I_{Mon_W} = pr1 (fmonoidal_preservesunitstrongly U) ⊗^{Mon_V}_{r} v0 · lu_{Mon_V} v0 ·\n                  ruinv_{Mon_V} v0 · v0 ⊗^{Mon_V}_{l} fmonoidal_preservesunit U.\n\n\nEnd δ_laws.\n\nDefinition lifteddistributivity: UU := ∑ δ : lifteddistributivity_data,\n      lifteddistributivity_nat δ × lifteddistributivity_tensor δ × lifteddistributivity_unit δ.\n\nDefinition lifteddistributivity_lddata (δ : lifteddistributivity): lifteddistributivity_data := pr1 δ.\nCoercion lifteddistributivity_lddata : lifteddistributivity >-> lifteddistributivity_data.\n\nDefinition lifteddistributivity_ldnat (δ : lifteddistributivity): lifteddistributivity_nat δ := pr12 δ.\nDefinition lifteddistributivity_ldtensor (δ : lifteddistributivity): lifteddistributivity_tensor δ := pr122 δ.\nDefinition lifteddistributivity_ldunit (δ : lifteddistributivity): lifteddistributivity_unit δ := pr222 δ.\n\n\n\nSection ActegoryMorphismFromLiftedDistributivity.\n\n  Context (δ : lifteddistributivity) {C : category} (ActV : actegory Mon_V C).\n\n  Local Definition FF: C ⟶ C := leftwhiskering_functor ActV v0.\n  Local Definition ActW: actegory Mon_W C := lifted_actegory Mon_V ActV Mon_W U.\n\n  Definition lineator_data_from_δ: lineator_data Mon_W ActW ActW FF.\n  Proof.\n    intros w x. unfold FF. cbn.\n    exact (aαinv^{ActV}_{F w, v0, x} · δ w ⊗^{ActV}_{r} x · aα^{ActV}_{v0, F w, x}).\n  Defined.\n\n  Lemma lineator_laxlaws_from_δ: lineator_laxlaws Mon_W ActW ActW FF lineator_data_from_δ.\n  Proof.\n    assert (δ_nat := lifteddistributivity_ldnat δ).\n    do 2 red in δ_nat. cbn in δ_nat.\n    repeat split; red; intros; unfold lineator_data_from_δ; try unfold lifted_actor_data; try unfold lifted_action_unitor_data; cbn;\n      try unfold lifted_actor_data; try unfold lifted_action_unitor_data; cbn.\n    - etrans.\n      { repeat rewrite assoc.\n        do 2 apply cancel_postcomposition.\n        apply actorinv_nat_leftwhisker. }\n      etrans.\n      2: { repeat rewrite assoc'.\n           do 2 apply maponpaths.\n           apply pathsinv0, actegory_actornatleft.\n      }\n      repeat rewrite assoc'.\n      apply maponpaths.\n      repeat rewrite assoc.\n      apply cancel_postcomposition.\n      apply pathsinv0, (bifunctor_equalwhiskers ActV).\n    - etrans.\n      { repeat rewrite assoc.\n        do 2 apply cancel_postcomposition.\n        apply actorinv_nat_rightwhisker. }\n      etrans.\n      2: { repeat rewrite assoc'.\n           do 2 apply maponpaths.\n           apply pathsinv0, actegory_actornatleftright.\n      }\n      repeat rewrite assoc'.\n      apply maponpaths.\n      repeat rewrite assoc.\n      apply cancel_postcomposition.\n      etrans.\n      { apply pathsinv0, (functor_comp (rightwhiskering_functor ActV x)). }\n      etrans.\n      2: { apply (functor_comp (rightwhiskering_functor ActV x)). }\n      apply maponpaths.\n      apply δ_nat.\n    - etrans.\n      { apply maponpaths.\n        apply (functor_comp (leftwhiskering_functor ActV v0)). }\n      cbn.\n      etrans.\n      { repeat rewrite assoc.\n        apply cancel_postcomposition.\n        repeat rewrite assoc'.\n        do 2 apply maponpaths.\n        apply actegory_actornatleftright.\n      }\n      etrans.\n      { repeat rewrite assoc.\n        do 2 apply cancel_postcomposition.\n        repeat rewrite assoc'.\n        apply maponpaths.\n        apply pathsinv0, (functor_comp (rightwhiskering_functor ActV x)).\n      }\n      cbn.\n      etrans.\n      { do 2 apply cancel_postcomposition.\n        do 2 apply maponpaths.\n        rewrite (lifteddistributivity_ldtensor δ).\n        repeat rewrite assoc'.\n        do 6 apply maponpaths.\n        etrans.\n        { apply pathsinv0, (functor_comp (leftwhiskering_functor Mon_V v0)). }\n        apply (functor_id_id _ _ (leftwhiskering_functor Mon_V v0)).\n        apply (pr2 (fmonoidal_preservestensorstrongly U v w)).\n      }\n      rewrite id_right.\n      etrans.\n      { do 2 apply cancel_postcomposition.\n        etrans.\n        { apply maponpaths.\n          apply (functor_comp (rightwhiskering_functor ActV x)). }\n        cbn.\n        rewrite assoc.\n        apply cancel_postcomposition.\n        apply pathsinv0, actorinv_nat_rightwhisker.\n      }\n      repeat rewrite assoc'.\n      apply maponpaths.\n      (* the extra effort for having an abstract strong monoidal functor has now been accomplished *)\n      apply (z_iso_inv_on_right _ _ _ (z_iso_from_actor_iso Mon_V ActV _ _ _)).\n      etrans.\n      { apply cancel_postcomposition.\n        repeat rewrite assoc.\n        apply (functor_comp (rightwhiskering_functor ActV x)). }\n      cbn.\n      etrans.\n      { rewrite assoc'.\n        apply maponpaths.\n        rewrite assoc.\n        apply actegory_pentagonidentity.\n      }\n      repeat rewrite assoc.\n      apply cancel_postcomposition.\n      rewrite <- actegory_pentagonidentity.\n      etrans.\n      { apply cancel_postcomposition.\n        repeat rewrite assoc'.\n        apply (functor_comp (rightwhiskering_functor ActV x)). }\n      cbn.\n      repeat rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      2: { apply maponpaths.\n           etrans.\n           2: { apply maponpaths.\n                apply cancel_postcomposition.\n                apply pathsinv0, (functor_comp (leftwhiskering_functor ActV (F v))). }\n           cbn.\n           repeat rewrite assoc.\n           do 3 apply cancel_postcomposition.\n           etrans.\n           2: { apply (functor_comp (leftwhiskering_functor ActV (F v))). }\n           apply pathsinv0, (functor_id_id _ _ (leftwhiskering_functor ActV (F v))).\n           apply (pr1 (actegory_actorisolaw Mon_V ActV _ _ _)).\n      }\n      rewrite id_left.\n      etrans.\n      2: { apply maponpaths.\n           rewrite assoc'.\n           apply cancel_postcomposition.\n           apply pathsinv0, (functor_comp (leftwhiskering_functor ActV (F v))).\n      }\n      cbn.\n      etrans.\n      2: { repeat rewrite assoc.\n           do 3 apply cancel_postcomposition.\n           apply pathsinv0, actegory_actornatleftright. }\n      etrans.\n      { apply cancel_postcomposition.\n        apply (functor_comp (rightwhiskering_functor ActV x)). }\n      cbn.\n      repeat rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      { apply cancel_postcomposition.\n        apply (functor_comp (rightwhiskering_functor ActV x)). }\n      cbn.\n      etrans.\n      { rewrite assoc'.\n        apply maponpaths.\n        apply pathsinv0, actegory_actornatright. }\n      repeat rewrite assoc.\n      apply cancel_postcomposition.\n      (* only a variant of the pentagon law with some inverses is missing here *)\n      apply (z_iso_inv_on_left _ _ _ _ (z_iso_from_actor_iso Mon_V ActV _ _ _)).\n      cbn.\n      rewrite assoc'.\n      rewrite <- actegory_pentagonidentity.\n      etrans.\n      2: { repeat rewrite assoc.\n           do 2 apply cancel_postcomposition.\n           etrans.\n           2: { apply (functor_comp (rightwhiskering_functor ActV x)). }\n           apply pathsinv0, (functor_id_id  _ _ (rightwhiskering_functor ActV x)).\n           apply (pr2 (monoidal_associatorisolaw Mon_V _ _ _)).\n      }\n      rewrite id_left.\n      apply idpath.\n    - etrans.\n      { apply maponpaths.\n        apply (functor_comp (leftwhiskering_functor ActV v0)). }\n      cbn.\n      etrans.\n      { repeat rewrite assoc.\n        apply cancel_postcomposition.\n        repeat rewrite assoc'.\n        do 2 apply maponpaths.\n        apply actegory_actornatleftright.\n      }\n      etrans.\n      { repeat rewrite assoc.\n        do 2 apply cancel_postcomposition.\n        repeat rewrite assoc'.\n        apply maponpaths.\n        apply pathsinv0, (functor_comp (rightwhiskering_functor ActV x)).\n      }\n      cbn.\n      etrans.\n      { do 2 apply cancel_postcomposition.\n        do 2 apply maponpaths.\n        rewrite (lifteddistributivity_ldunit δ).\n        repeat rewrite assoc'.\n        do 3 apply maponpaths.\n        etrans.\n        { apply pathsinv0, (functor_comp (leftwhiskering_functor Mon_V v0)). }\n        apply (functor_id_id _ _ (leftwhiskering_functor Mon_V v0)).\n        apply (pr2 (fmonoidal_preservesunitstrongly U)).\n      }\n      rewrite id_right.\n      etrans.\n      { do 2 apply cancel_postcomposition.\n        etrans.\n        { apply maponpaths.\n          apply (functor_comp (rightwhiskering_functor ActV x)). }\n        cbn.\n        rewrite assoc.\n        apply cancel_postcomposition.\n        apply pathsinv0, actorinv_nat_rightwhisker.\n      }\n      repeat rewrite assoc'.\n      apply maponpaths.\n      (* the extra effort for having an abstract strong monoidal functor has now been accomplished *)\n      etrans.\n      { repeat rewrite assoc'.\n        do 2 apply maponpaths.\n        apply actegory_triangleidentity. }\n      etrans.\n      { apply maponpaths.\n        apply pathsinv0, (functor_comp (rightwhiskering_functor ActV x)). }\n      cbn.\n      rewrite assoc'.\n      rewrite (pr2 (monoidal_rightunitorisolaw Mon_V v0)).\n      rewrite id_right.\n      rewrite <- actegory_triangleidentity'.\n      rewrite assoc.\n      rewrite (pr2 (actegory_actorisolaw Mon_V ActV _ _ _)).\n      apply id_left.\n  Qed.\n\n  Definition liftedstrength_from_δ: liftedstrength Mon_V Mon_W U ActV ActV FF :=\n    lineator_data_from_δ,,lineator_laxlaws_from_δ.\n\nEnd ActegoryMorphismFromLiftedDistributivity.\n\nEnd FixAnObject.\n\nArguments liftedstrength_from_δ _ _ {_} _.\nArguments lifteddistributivity _ : clear implicits.\nArguments lifteddistributivity_data _ : clear implicits.\n\n\n  Definition unit_lifteddistributivity_data: lifteddistributivity_data I_{Mon_V}.\n  Proof.\n    intro w.\n    exact (ru^{Mon_V}_{F w} · luinv^{Mon_V}_{F w}).\n  Defined.\n\n  Lemma unit_lifteddistributivity_nat: lifteddistributivity_nat unit_lifteddistributivity_data.\n  Proof.\n    intro; intros. unfold unit_lifteddistributivity_data.\n    cbn.\n    etrans.\n    { rewrite assoc.\n      apply cancel_postcomposition.\n      apply monoidal_rightunitornat. }\n    repeat rewrite assoc'.\n    apply maponpaths.\n    apply pathsinv0, monoidal_leftunitorinvnat.\n  Qed.\n\n  Lemma unit_lifteddistributivity_tensor: lifteddistributivity_tensor unit_lifteddistributivity_data.\n  Proof.\n    intro; intros. unfold lifteddistributivity_tensor_body, unit_lifteddistributivity_data.\n    etrans.\n    2: { do 2 apply cancel_postcomposition.\n         etrans.\n         2: { do 2 apply cancel_postcomposition.\n              rewrite assoc'.\n              do 2 apply maponpaths.\n              apply pathsinv0, (functor_comp (leftwhiskering_functor Mon_V _)). }\n         apply maponpaths.\n         apply pathsinv0, (functor_comp (rightwhiskering_functor Mon_V _)).\n    }\n    cbn.\n    etrans.\n    2: { repeat rewrite assoc'.\n         apply maponpaths.\n         repeat rewrite assoc.\n         do 6 apply cancel_postcomposition.\n         apply pathsinv0, left_whisker_with_runitor. }\n    etrans.\n    2: { repeat rewrite assoc.\n         do 4 apply cancel_postcomposition.\n         repeat rewrite assoc'.\n         do 2 apply maponpaths.\n         apply pathsinv0, monoidal_triangle_identity_inv. }\n    etrans.\n    2: { repeat rewrite assoc'.\n         do 2 apply maponpaths.\n         repeat rewrite assoc.\n         do 3 apply cancel_postcomposition.\n         etrans.\n         2: { apply (functor_comp (rightwhiskering_functor Mon_V _)). }\n         apply maponpaths.\n         apply pathsinv0, monoidal_rightunitorisolaw.\n    }\n    rewrite functor_id, id_left.\n    etrans.\n    2: { do 2 apply maponpaths.\n         apply cancel_postcomposition.\n         rewrite <- monoidal_triangle_identity'_inv.\n         rewrite assoc'.\n         apply maponpaths.\n         apply pathsinv0, monoidal_associatorisolaw.\n    }\n    rewrite id_right.\n    etrans.\n    2: { repeat rewrite assoc'.\n         do 2 apply maponpaths.\n         apply pathsinv0, monoidal_leftunitorinvnat. }\n    do 2 rewrite assoc.\n    apply cancel_postcomposition.\n    etrans.\n    2: { apply cancel_postcomposition.\n         apply pathsinv0, monoidal_rightunitornat. }\n    etrans.\n    2: { rewrite assoc'.\n         apply maponpaths.\n         apply pathsinv0, fmonoidal_preservestensorstrongly.\n    }\n    apply pathsinv0, id_right.\n  Qed.\n\n  Lemma unit_lifteddistributivity_unit: lifteddistributivity_unit unit_lifteddistributivity_data.\n  Proof.\n    unfold lifteddistributivity_unit, unit_lifteddistributivity_data.\n    etrans.\n    2: { do 2 apply cancel_postcomposition.\n         rewrite unitors_coincide_on_unit.\n         apply pathsinv0, monoidal_rightunitornat. }\n    repeat rewrite assoc'.\n    apply maponpaths.\n    etrans.\n    2: { apply maponpaths.\n         rewrite <- unitorsinv_coincide_on_unit.\n         apply pathsinv0, monoidal_leftunitorinvnat. }\n    rewrite assoc.\n    etrans.\n    2: {apply cancel_postcomposition.\n        apply pathsinv0, (pr22 (fmonoidal_preservesunitstrongly U)). }\n    apply pathsinv0, id_left.\n  Qed.\n\n  Definition unit_lifteddistributivity: lifteddistributivity I_{Mon_V}.\n  Proof.\n    use tpair.\n    - exact  unit_lifteddistributivity_data.\n    - split3.\n      + exact unit_lifteddistributivity_nat.\n      + exact unit_lifteddistributivity_tensor.\n      + exact unit_lifteddistributivity_unit.\n  Defined.\n\nSection CompositionOfLiftedDistributivities.\n\n  Context (v1 v2 : V) (δ1 : lifteddistributivity v1) (δ2 : lifteddistributivity v2).\n\n  Definition composedlifteddistributivity_data: lifteddistributivity_data (v1 ⊗_{Mon_V} v2).\n  Proof.\n    red; intros.\n    exact (αinv_{Mon_V} _ _ _ · δ1 w ⊗^{Mon_V}_{r} v2 · α_{Mon_V} _ _ _\n             · v1 ⊗^{Mon_V}_{l} δ2 w · αinv_{Mon_V} _ _ _).\n  Defined.\n\n  Lemma composedlifteddistributivity_nat: lifteddistributivity_nat composedlifteddistributivity_data.\n  Proof.\n    do 2 red; intros; unfold composedlifteddistributivity_data; cbn.\n    assert (δ1_nat := lifteddistributivity_ldnat δ1).\n    assert (δ2_nat := lifteddistributivity_ldnat δ2).\n    do 2 red in δ1_nat, δ2_nat; cbn in δ1_nat, δ2_nat.\n    etrans.\n    { repeat rewrite assoc.\n      do 4 apply cancel_postcomposition.\n      apply monoidal_associatorinvnatright. }\n    repeat rewrite assoc'.\n    apply maponpaths.\n    etrans.\n    { rewrite assoc.\n      apply cancel_postcomposition.\n      apply pathsinv0, (functor_comp (rightwhiskering_functor Mon_V v2)). }\n    cbn.\n    rewrite δ1_nat.\n    etrans.\n    { rewrite assoc.\n      do 2 apply cancel_postcomposition.\n      apply (functor_comp (rightwhiskering_functor Mon_V v2)). }\n    cbn.\n    repeat rewrite assoc'.\n    apply maponpaths.\n    etrans.\n    2: { do 2 apply maponpaths.\n         apply monoidal_associatorinvnatleft. }\n    repeat rewrite assoc.\n    apply cancel_postcomposition.\n    etrans.\n    2: { rewrite assoc'.\n         apply maponpaths.\n         apply (functor_comp (leftwhiskering_functor Mon_V v1)). }\n    cbn.\n    rewrite <- δ2_nat.\n    etrans.\n    2: { apply maponpaths.\n         apply pathsinv0, (functor_comp (leftwhiskering_functor Mon_V v1)). }\n    cbn.\n    repeat rewrite assoc.\n    apply cancel_postcomposition.\n    apply pathsinv0, monoidal_associatornatleftright.\n  Qed.\n\n  Lemma composedlifteddistributivity_tensor: lifteddistributivity_tensor composedlifteddistributivity_data.\n  Proof.\n    do 2 red; intros; unfold composedlifteddistributivity_data; cbn.\n    rewrite (lifteddistributivity_ldtensor δ1).\n    rewrite (lifteddistributivity_ldtensor δ2).\n    etrans.\n    { do 3 apply cancel_postcomposition.\n      apply maponpaths.\n      etrans.\n      { apply (functor_comp (rightwhiskering_functor Mon_V v2)). }\n      do 5 rewrite functor_comp.\n      cbn.\n      apply idpath.\n    }\n    etrans.\n    { apply cancel_postcomposition.\n      repeat rewrite assoc'.\n      do 9 apply maponpaths.\n      etrans.\n      { apply (functor_comp (leftwhiskering_functor Mon_V v1)). }\n      do 5 rewrite functor_comp.\n      cbn.\n      apply idpath.\n    }\n    etrans.\n    { repeat rewrite assoc.\n      do 15 apply cancel_postcomposition.\n      apply pathsinv0, monoidal_associatorinvnatright. }\n    repeat rewrite assoc'.\n    apply maponpaths.\n    etrans.\n    { do 14 apply maponpaths.\n      apply monoidal_associatorinvnatleft. }\n    repeat rewrite assoc.\n    apply cancel_postcomposition.\n    etrans.\n    2: { do 3 apply cancel_postcomposition.\n         apply maponpaths.\n         etrans.\n         2: { apply pathsinv0, (functor_comp (leftwhiskering_functor Mon_V (F w))). }\n      do 3 rewrite functor_comp.\n      cbn.\n      apply idpath.\n    }\n    etrans.\n    2: { apply cancel_postcomposition.\n         repeat rewrite assoc'.\n         do 7 apply maponpaths.\n         etrans.\n         2: { apply pathsinv0, (functor_comp (rightwhiskering_functor Mon_V (F w'))). }\n      do 3 rewrite functor_comp.\n      cbn.\n      apply idpath.\n    }\n    etrans.\n    { do 6 apply cancel_postcomposition.\n      repeat rewrite assoc'.\n      do 6 apply maponpaths.\n      etrans.\n      { apply maponpaths.\n        apply monoidal_associatornatleftright. }\n      rewrite assoc.\n      apply cancel_postcomposition.\n      etrans.\n      { apply pathsinv0, (functor_comp (rightwhiskering_functor Mon_V v2)). }\n      apply maponpaths.\n      etrans.\n      { apply pathsinv0, (functor_comp (leftwhiskering_functor Mon_V v1)). }\n      apply (functor_id_id _ _ (leftwhiskering_functor Mon_V v1)).\n      apply (pr2 (fmonoidal_preservestensorstrongly U w w')).\n    }\n    rewrite functor_id.\n    rewrite id_left.\n    etrans.\n    { repeat rewrite assoc'. apply idpath. }\n    apply (z_iso_inv_on_right _ _ _ (z_iso_from_associator_iso Mon_V _ _ _)).\n    cbn.\n    etrans.\n    2: { repeat rewrite assoc.\n         do 11 apply cancel_postcomposition.\n         etrans.\n         2: { apply cancel_postcomposition.\n              apply monoidal_pentagonidentity. }\n         repeat rewrite assoc'.\n         do 2 apply maponpaths.\n         etrans.\n         2: { apply (functor_comp (leftwhiskering_functor Mon_V (F w))). }\n         apply pathsinv0, (functor_id_id _ _ (leftwhiskering_functor Mon_V (F w))).\n         apply (pr1 (monoidal_associatorisolaw Mon_V _ _ _)).\n    }\n    rewrite id_right.\n    repeat rewrite assoc'.\n    apply maponpaths.\n    etrans.\n    2: { repeat rewrite assoc.\n         do 10 apply cancel_postcomposition.\n         apply pathsinv0, monoidal_associatornatleftright. }\n    repeat rewrite assoc'.\n    apply maponpaths.\n    apply (z_iso_inv_on_right _ _ _ (functor_on_z_iso (rightwhiskering_functor Mon_V v2) (z_iso_from_associator_iso Mon_V _ _ _))).\n    cbn.\n    etrans.\n    2: { repeat rewrite assoc.\n         do 9 apply cancel_postcomposition.\n         apply pathsinv0, monoidal_pentagonidentity. }\n    etrans.\n    { repeat rewrite assoc. apply idpath. }\n    apply pathsinv0, (z_iso_inv_on_left _ _ _ _ (z_iso_from_associator_iso Mon_V _ _ _)).\n    cbn.\n    etrans.\n    2: { repeat rewrite assoc'.\n         do 9 apply maponpaths.\n         etrans.\n         2: { apply maponpaths.\n              apply monoidal_pentagonidentity. }\n         repeat rewrite assoc.\n         do 2 apply cancel_postcomposition.\n         etrans.\n         2: { apply (functor_comp (rightwhiskering_functor Mon_V _)). }\n         apply pathsinv0, (functor_id_id _ _ (rightwhiskering_functor Mon_V (F w'))).\n         apply (pr2 (monoidal_associatorisolaw Mon_V _ _ _)).\n    }\n    rewrite id_left.\n    repeat rewrite assoc.\n    apply cancel_postcomposition.\n    etrans.\n    { do 3 apply cancel_postcomposition.\n      repeat rewrite assoc'.\n      apply maponpaths.\n      rewrite assoc.\n      apply monoidal_pentagonidentity. }\n    etrans.\n    { repeat rewrite assoc.\n      do 4 apply cancel_postcomposition.\n      apply pathsinv0, monoidal_associatornatright. }\n    repeat rewrite assoc'.\n    apply maponpaths.\n    etrans.\n    { apply maponpaths.\n      repeat rewrite assoc.\n      do 2 apply cancel_postcomposition.\n      apply monoidal_associatornatleft. }\n    etrans.\n    { repeat rewrite assoc.\n      do 3 apply cancel_postcomposition.\n      apply (bifunctor_equalwhiskers Mon_V). }\n    unfold functoronmorphisms2.\n    etrans.\n    2: { repeat rewrite assoc.\n         do 7 apply cancel_postcomposition.\n         apply pathsinv0, monoidal_associatornatleft. }\n    repeat rewrite assoc'.\n    apply maponpaths.\n    etrans.\n    2: { repeat rewrite assoc.\n         do 4 apply cancel_postcomposition.\n         etrans.\n         2: { repeat rewrite assoc'.\n              apply maponpaths.\n              rewrite assoc.\n              apply pathsinv0, monoidal_pentagon_identity_inv. }\n         rewrite assoc.\n         apply cancel_postcomposition.\n         apply pathsinv0, (pr1 (monoidal_associatorisolaw Mon_V _ _ _)).\n    }\n    rewrite id_left.\n    etrans.\n    2: { repeat rewrite assoc'.\n         do 3 apply maponpaths.\n         apply monoidal_associatornatleftright. }\n    repeat rewrite assoc.\n    apply cancel_postcomposition.\n    repeat rewrite assoc'.\n    apply pathsinv0, (z_iso_inv_on_right _ _ _ (z_iso_from_associator_iso Mon_V _ _ _)).\n    cbn.\n    etrans.\n    2: { repeat rewrite assoc.\n         do 2 apply cancel_postcomposition.\n         apply pathsinv0, monoidal_associatornatright. }\n    repeat rewrite assoc'.\n    apply maponpaths.\n    rewrite assoc.\n    apply (z_iso_inv_on_left _ _ _ _ (functor_on_z_iso (leftwhiskering_functor Mon_V v1) (z_iso_from_associator_iso Mon_V _ _ _))).\n    cbn.\n    apply pathsinv0, monoidal_pentagonidentity.\n  Qed.\n\n  Lemma composedlifteddistributivity_unit: lifteddistributivity_unit composedlifteddistributivity_data.\n  Proof.\n    red; unfold composedlifteddistributivity_data; cbn.\n    rewrite (lifteddistributivity_ldunit δ1).\n    rewrite (lifteddistributivity_ldunit δ2).\n    etrans.\n    { do 3 apply cancel_postcomposition.\n      apply maponpaths.\n      etrans.\n      { apply (functor_comp (rightwhiskering_functor Mon_V v2)). }\n      do 2 rewrite functor_comp.\n      cbn.\n      apply idpath.\n    }\n    etrans.\n    { apply cancel_postcomposition.\n      repeat rewrite assoc'.\n      do 6 apply maponpaths.\n      etrans.\n      { apply (functor_comp (leftwhiskering_functor Mon_V v1)). }\n      do 2 rewrite functor_comp.\n      cbn.\n      apply idpath.\n    }\n    etrans.\n    { repeat rewrite assoc.\n      do 9 apply cancel_postcomposition.\n      apply pathsinv0, monoidal_associatorinvnatright. }\n    repeat rewrite assoc'.\n    apply maponpaths.\n    etrans.\n    { repeat rewrite assoc.\n      do 8 apply cancel_postcomposition.\n      rewrite <- monoidal_triangleidentity'.\n      rewrite assoc.\n      apply cancel_postcomposition.\n      apply (pr2 (monoidal_associatorisolaw Mon_V _ _ _)).\n    }\n    rewrite id_left.\n    repeat rewrite assoc'.\n    apply maponpaths.\n    etrans.\n    { do 6 apply maponpaths.\n      apply monoidal_associatorinvnatleft. }\n    repeat rewrite assoc.\n    apply cancel_postcomposition.\n    etrans.\n    { do 4 apply cancel_postcomposition.\n      rewrite assoc'.\n      apply maponpaths.\n      apply pathsinv0, monoidal_associatornatleftright.\n    }\n    etrans.\n    { do 3 apply cancel_postcomposition.\n      repeat rewrite assoc'.\n      do 2 apply maponpaths.\n      etrans.\n      { apply pathsinv0, (functor_comp (leftwhiskering_functor Mon_V v1)). }\n      apply maponpaths.\n      etrans.\n      { apply pathsinv0, (functor_comp (rightwhiskering_functor Mon_V v2)). }\n      apply (functor_id_id _ _ (rightwhiskering_functor Mon_V v2)).\n      apply (pr2 (fmonoidal_preservesunitstrongly U)).\n    }\n    rewrite functor_id.\n    rewrite id_right.\n    etrans.\n    { repeat rewrite assoc'.\n      do 3 apply maponpaths.\n      apply monoidal_triangle_identity''_inv. }\n    etrans.\n    { apply maponpaths.\n      rewrite assoc.\n      apply cancel_postcomposition.\n      apply monoidal_triangleidentity. }\n    rewrite assoc.\n    etrans.\n    { apply cancel_postcomposition.\n      etrans.\n      { apply pathsinv0, (functor_comp (rightwhiskering_functor Mon_V v2)). }\n      apply (functor_id_id _ _ (rightwhiskering_functor Mon_V v2)).\n      apply (monoidal_rightunitorisolaw Mon_V).\n    }\n    apply id_left.\n  Qed.\n\n  Definition composedlifteddistributivity: lifteddistributivity (v1 ⊗_{Mon_V} v2).\n  Proof.\n    exists composedlifteddistributivity_data.\n    exact (composedlifteddistributivity_nat,,\n           composedlifteddistributivity_tensor,,\n           composedlifteddistributivity_unit).\n  Defined.\n\nEnd CompositionOfLiftedDistributivities.\n\nEnd LiftedDistributivity.\n\nEnd LiftedLineatorAndLiftedDistributivity.\n\nArguments lifteddistributivity {_} _ {_} _ {_} _ _.\nArguments lifteddistributivity_data {_} _ {_ _} _.\n\nSection PointwiseOperationsOnLinearFunctors.\n\n  Context {V : category} (Mon_V : monoidal V)\n    {C D : category}\n    (ActC : actegory Mon_V C) (ActD : actegory Mon_V D).\n\nSection PointwiseBinaryOperationsOnLinearFunctors.\n\n  Context {F1 F2 : functor C D}\n    (ll1 : lineator_lax Mon_V ActC ActD F1)\n    (ll2 : lineator_lax Mon_V ActC ActD F2).\n\nSection PointwiseBinaryProductOfLinearFunctors.\n\n  Context (BPD : BinProducts D).\n\n  Let FF : functor C D := BinProduct_of_functors _ _ BPD F1 F2.\n  Let FF' : functor C D := BinProduct_of_functors_alt BPD F1 F2.\n\n  Definition lax_lineator_binprod_aux: lineator_lax Mon_V ActC ActD FF'.\n  Proof.\n    use comp_lineator_lax.\n    - apply actegory_binprod; assumption.\n    - apply actegory_binprod_delta_lineator.\n    - use comp_lineator_lax.\n      + apply actegory_binprod; assumption.\n      + apply actegory_pair_functor_lineator; assumption.\n      + apply binprod_functor_lax_lineator.\n  Defined.\n\n  Definition lax_lineator_binprod_indirect: lineator_lax Mon_V ActC ActD FF.\n  Proof.\n    unfold FF.\n    rewrite <- BinProduct_of_functors_alt_eq_BinProduct_of_functors.\n    apply lax_lineator_binprod_aux.\n  Defined.\n\n  Lemma lax_lineator_binprod_indirect_data_ok (v : V) (c : C):\n    lax_lineator_binprod_indirect v c =\n      binprod_collector_data Mon_V BPD ActD v (F1 c) (F2 c) ·\n        BinProductOfArrows _ (BPD _ _) (BPD _ _) (ll1 v c) (ll2 v c).\n  Proof.\n    unfold lax_lineator_binprod_indirect.\n  Abort.\n  (* how could one use the equality proof? *)\n\n  (** now an alternative concrete construction *)\n  Definition lineator_data_binprod: lineator_data Mon_V ActC ActD FF.\n  Proof.\n    intros v c.\n    exact (binprod_collector_data Mon_V BPD ActD v (F1 c) (F2 c) ·\n        BinProductOfArrows _ (BPD _ _) (BPD _ _) (ll1 v c) (ll2 v c)).\n  Defined.\n\n  Let cll : lineator_lax Mon_V (actegory_binprod Mon_V ActD ActD) ActD (binproduct_functor BPD)\n      := binprod_functor_lax_lineator Mon_V BPD ActD.\n\n  Lemma lineator_laxlaws_binprod: lineator_laxlaws Mon_V ActC ActD FF lineator_data_binprod.\n  Proof.\n    repeat split; red; intros; unfold lineator_data_binprod.\n    - etrans.\n      { repeat rewrite assoc.\n        apply cancel_postcomposition.\n        apply (lineator_linnatleft _ _ _ _ cll v (_,,_) (_,,_) (_,,_)). }\n      repeat rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      { apply BinProductOfArrows_comp. }\n      etrans.\n      2: { apply pathsinv0, BinProductOfArrows_comp. }\n      apply maponpaths_12; apply lineator_linnatleft.\n    - etrans.\n      { repeat rewrite assoc.\n        apply cancel_postcomposition.\n        apply (lineator_linnatright _ _ _ _ cll v1 v2 (_,,_) f). }\n      repeat rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      { apply BinProductOfArrows_comp. }\n      etrans.\n      2: { apply pathsinv0, BinProductOfArrows_comp. }\n      apply maponpaths_12; apply lineator_linnatright.\n    - etrans.\n      { rewrite assoc'.\n        apply maponpaths.\n        etrans.\n        { apply BinProductOfArrows_comp. }\n        apply maponpaths_12; apply lineator_preservesactor.\n      }\n      etrans.\n      { apply maponpaths.\n        repeat rewrite assoc'.\n        apply pathsinv0, BinProductOfArrows_comp. }\n      etrans.\n      { rewrite assoc.\n        apply cancel_postcomposition.\n        apply (lineator_preservesactor _ _ _ _ cll v w (_,,_)). }\n      etrans.\n      2: { apply cancel_postcomposition.\n           apply maponpaths.\n           apply pathsinv0, (functor_comp (leftwhiskering_functor ActD v)). }\n      repeat rewrite assoc'.\n      do 2 apply maponpaths.\n      repeat rewrite assoc.\n      etrans.\n      2: { apply cancel_postcomposition.\n           apply pathsinv0, (lineator_linnatleft _ _ _ _ cll v (_,,_) (_,,_) (_,,_)). }\n      rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      2: { apply pathsinv0, BinProductOfArrows_comp. }\n      apply idpath.\n    - etrans.\n      2: { apply (lineator_preservesunitor _ _ _ _ cll (_,,_)). }\n      rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      { apply BinProductOfArrows_comp. }\n      cbn.\n      apply maponpaths_12; apply lineator_preservesunitor.\n  Qed.\n\n  Definition lax_lineator_binprod: lineator_lax Mon_V ActC ActD FF :=\n    lineator_data_binprod,,lineator_laxlaws_binprod.\n\nEnd PointwiseBinaryProductOfLinearFunctors.\n\nSection PointwiseBinaryCoproductOfLinearFunctors.\n\n  Context (BCD : BinCoproducts D) (δ : actegory_bincoprod_distributor Mon_V BCD ActD).\n\n  Let FF : functor C D := BinCoproduct_of_functors _ _ BCD F1 F2.\n  Let FF' : functor C D := BinCoproduct_of_functors_alt2 BCD F1 F2.\n\n  Definition lax_lineator_bincoprod_aux : lineator_lax Mon_V ActC ActD FF'.\n  Proof.\n    use comp_lineator_lax.\n    - apply actegory_binprod; assumption.\n    - apply actegory_binprod_delta_lineator.\n    - use comp_lineator_lax.\n      + apply actegory_binprod; assumption.\n      + apply actegory_pair_functor_lineator; assumption.\n      + apply (bincoprod_functor_lineator Mon_V BCD ActD δ).\n  Defined.\n\n  Definition lax_lineator_bincoprod_indirect : lineator_lax Mon_V ActC ActD FF.\n  Proof.\n    unfold FF.\n    rewrite <- BinCoproduct_of_functors_alt_eq_BinCoproduct_of_functors.\n    apply lax_lineator_bincoprod_aux.\n  Defined.\n\n  Lemma lax_lineator_bincoprod_data_ok (v : V) (c : C) : lax_lineator_bincoprod_indirect v c =\n    δ v (F1 c) (F2 c) · (BinCoproductOfArrows _ (BCD _ _) (BCD _ _) (ll1 v c) (ll2 v c)).\n  Proof.\n    unfold lax_lineator_bincoprod_indirect.\n  Abort.\n  (* how could one use the equality proof? *)\n\n  (** now an alternative concrete construction *)\n  Definition lineator_data_bincoprod: lineator_data Mon_V ActC ActD FF.\n  Proof.\n    intros v c.\n    exact (δ v (F1 c) (F2 c) · (BinCoproductOfArrows _ (BCD _ _) (BCD _ _) (ll1 v c) (ll2 v c))).\n  Defined.\n\n  Let δll : lineator Mon_V (actegory_binprod Mon_V ActD ActD) ActD (bincoproduct_functor BCD)\n      := bincoprod_functor_lineator Mon_V BCD ActD δ.\n\n  Lemma lineator_laxlaws_bincoprod\n    : lineator_laxlaws Mon_V ActC ActD FF lineator_data_bincoprod.\n  Proof.\n    repeat split; red; intros; unfold lineator_data_bincoprod.\n    - etrans.\n      { repeat rewrite assoc.\n        apply cancel_postcomposition.\n        apply (lineator_linnatleft _ _ _ _ δll v (_,,_) (_,,_) (_,,_)). }\n      repeat rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      { apply BinCoproductOfArrows_comp. }\n      etrans.\n      2: { apply pathsinv0, BinCoproductOfArrows_comp. }\n      apply maponpaths_12; apply lineator_linnatleft.\n    - etrans.\n      { repeat rewrite assoc.\n        apply cancel_postcomposition.\n        apply (lineator_linnatright _ _ _ _ δll v1 v2 (_,,_) f). }\n      repeat rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      { apply BinCoproductOfArrows_comp. }\n      etrans.\n      2: { apply pathsinv0, BinCoproductOfArrows_comp. }\n      apply maponpaths_12; apply lineator_linnatright.\n    - etrans.\n      { rewrite assoc'.\n        apply maponpaths.\n        etrans.\n        { apply BinCoproductOfArrows_comp. }\n        apply maponpaths_12; apply lineator_preservesactor.\n      }\n      etrans.\n      { apply maponpaths.\n        repeat rewrite assoc'.\n        apply pathsinv0, BinCoproductOfArrows_comp. }\n      etrans.\n      { rewrite assoc.\n        apply cancel_postcomposition.\n        apply (lineator_preservesactor _ _ _ _ δll v w (_,,_)). }\n      etrans.\n      2: { apply cancel_postcomposition.\n           apply maponpaths.\n           apply pathsinv0, (functor_comp (leftwhiskering_functor ActD v)). }\n      repeat rewrite assoc'.\n      do 2 apply maponpaths.\n      repeat rewrite assoc.\n      etrans.\n      2: { apply cancel_postcomposition.\n           apply pathsinv0, (lineator_linnatleft _ _ _ _ δll v (_,,_) (_,,_) (_,,_)). }\n      rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      2: { apply pathsinv0, BinCoproductOfArrows_comp. }\n      apply idpath.\n    - etrans.\n      2: { apply (lineator_preservesunitor _ _ _ _ δll (_,,_)). }\n      rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      { apply BinCoproductOfArrows_comp. }\n      cbn.\n      apply maponpaths_12; apply lineator_preservesunitor.\n  Qed.\n\n  Definition lax_lineator_bincoprod: lineator_lax Mon_V ActC ActD FF :=\n    lineator_data_bincoprod,,lineator_laxlaws_bincoprod.\n\nEnd PointwiseBinaryCoproductOfLinearFunctors.\n\nEnd PointwiseBinaryOperationsOnLinearFunctors.\n\nSection PointwiseCoproductOfLinearFunctors.\n\n  Context {I : UU} {F : I -> functor C D}\n    (ll : ∏ (i: I), lineator_lax Mon_V ActC ActD (F i))\n    (CD : Coproducts I D) (δ : actegory_coprod_distributor Mon_V CD ActD).\n\n  Let FF : functor C D := coproduct_of_functors _ _ _ CD F.\n  Let FF' : functor C D := coproduct_of_functors_alt_old _ CD F.\n\n  Definition lax_lineator_coprod_aux : lineator_lax Mon_V ActC ActD FF'.\n  Proof.\n    use comp_lineator_lax.\n    - apply actegory_power; assumption.\n    - apply actegory_prod_delta_lineator.\n    - use comp_lineator_lax.\n      + apply actegory_power; assumption.\n      + apply actegory_family_functor_lineator; assumption.\n      + apply (coprod_functor_lineator Mon_V CD ActD δ).\n  Defined.\n\n  Definition lax_lineator_coprod_indirect : lineator_lax Mon_V ActC ActD FF.\n  Proof.\n    unfold FF.\n    rewrite <- coproduct_of_functors_alt_old_eq_coproduct_of_functors.\n    apply lax_lineator_coprod_aux.\n  Defined.\n\n  Lemma lax_lineator_coprod_data_ok (v : V) (c : C) : lax_lineator_coprod_indirect v c =\n    δ v (fun i => F i c) · (CoproductOfArrows I _ (CD _) (CD _) (fun i => ll i v c)).\n  Proof.\n    unfold lax_lineator_coprod_indirect.\n  Abort.\n  (* how could one use the equality proof? *)\n\n  (** now an alternative concrete construction *)\n  Definition lineator_data_coprod: lineator_data Mon_V ActC ActD FF.\n  Proof.\n    intros v c.\n    exact (δ v (fun i => F i c) · (CoproductOfArrows I _ (CD _) (CD _) (fun i => ll i v c))).\n  Defined.\n\n  Let δll : lineator Mon_V (actegory_power Mon_V I ActD) ActD (coproduct_functor I CD)\n      := coprod_functor_lineator Mon_V CD ActD δ.\n\n  Lemma lineator_laxlaws_coprod\n    : lineator_laxlaws Mon_V ActC ActD FF lineator_data_coprod.\n  Proof.\n    repeat split; red; intros; unfold lineator_data_coprod.\n    - etrans.\n      { repeat rewrite assoc.\n        apply cancel_postcomposition.\n        apply (lineator_linnatleft _ _ _ _ δll v). }\n      repeat rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      { apply CoproductOfArrows_comp. }\n      etrans.\n      2: { apply pathsinv0, CoproductOfArrows_comp. }\n      apply maponpaths, funextsec; intro i; apply lineator_linnatleft.\n    - etrans.\n      { repeat rewrite assoc.\n        apply cancel_postcomposition.\n        apply (lineator_linnatright _ _ _ _ δll v1 v2 _ f). }\n      repeat rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      { apply CoproductOfArrows_comp. }\n      etrans.\n      2: { apply pathsinv0, CoproductOfArrows_comp. }\n      apply maponpaths, funextsec; intro i; apply lineator_linnatright.\n    - etrans.\n      { rewrite assoc'.\n        apply maponpaths.\n        etrans.\n        { apply CoproductOfArrows_comp. }\n        cbn.\n        apply maponpaths, funextsec; intro i; apply lineator_preservesactor.\n      }\n      etrans.\n      { apply maponpaths.\n        assert (aux : (fun i => aα^{ ActD }_{ v, w, F i x} · v ⊗^{ ActD}_{l} ll i w x · ll i v (w ⊗_{ ActC} x))\n                      = (fun i => aα^{ ActD }_{ v, w, F i x} · (v ⊗^{ ActD}_{l} ll i w x · ll i v (w ⊗_{ ActC} x)))).\n        { apply funextsec; intro i; apply assoc'. }\n        rewrite aux.\n        apply pathsinv0, CoproductOfArrows_comp. }\n      etrans.\n      { rewrite assoc.\n        apply cancel_postcomposition.\n        apply (lineator_preservesactor _ _ _ _ δll v w).\n      }\n      etrans.\n      2: { apply cancel_postcomposition.\n           apply maponpaths.\n           apply pathsinv0, (functor_comp (leftwhiskering_functor ActD v)). }\n      repeat rewrite assoc'.\n      do 2 apply maponpaths.\n      repeat rewrite assoc.\n      etrans.\n      2: { apply cancel_postcomposition.\n           apply pathsinv0, (lineator_linnatleft _ _ _ _ δll v). }\n      rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      2: { apply pathsinv0, CoproductOfArrows_comp. }\n      apply idpath.\n    - etrans.\n      2: { apply (lineator_preservesunitor _ _ _ _ δll). }\n      rewrite assoc'.\n      apply maponpaths.\n      etrans.\n      { apply CoproductOfArrows_comp. }\n      cbn.\n      apply maponpaths, funextsec; intro i; apply lineator_preservesunitor.\n  Qed.\n\n  Definition lax_lineator_coprod: lineator_lax Mon_V ActC ActD FF :=\n    lineator_data_coprod,,lineator_laxlaws_coprod.\n\nEnd PointwiseCoproductOfLinearFunctors.\n\nEnd PointwiseOperationsOnLinearFunctors.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/CategoryTheory/Actegories/ConstructionOfActegoryMorphisms.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.22449605350319626}}
{"text": "Require Import Verdi.Verdi.\nRequire Import Verdi.HandlerMonad.\nRequire Import Verdi.NameOverlay.\n\nRequire Import NameAdjacency.\n\nRequire Import Sumbool.\n\nRequire Import mathcomp.ssreflect.ssreflect.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nSet Implicit Arguments.\n\nModule FailureRecorder (Import NT : NameType) \n (NOT : NameOrderedType NT) (NSet : MSetInterface.S with Module E := NOT)\n (Import ANT : AdjacentNameType NT) (Import A : Adjacency NT NOT NSet ANT).\n\nInductive Msg : Set := \n| Fail : Msg.\n\nDefinition Msg_eq_dec : forall x y : Msg, {x = y} + {x <> y}.\nby case; case; left.\nDefined.\n\nInductive Input : Set := .\n\nDefinition Input_eq_dec : forall x y : Input, {x = y} + {x <> y}.\ndecide equality.\nDefined.\n\nInductive Output : Set := .\n\nDefinition Output_eq_dec : forall x y : Output, {x = y} + {x <> y}.\ndecide equality.\nDefined.\n\nRecord Data := mkData { adjacent : NS }.\n\nDefinition InitData (n : name) := mkData (adjacency n nodes).\n\nDefinition Handler (S : Type) := GenHandler (name * Msg) S Output unit.\n\nDefinition NetHandler (me src: name) (msg : Msg) : Handler Data :=\nst <- get ;;\nmatch msg with\n| Fail => \n  put {| adjacent := NSet.remove src st.(adjacent) |}\nend.\n\nDefinition IOHandler (me : name) (i : Input) : Handler Data := nop.\n\nInstance FailureRecorder_BaseParams : BaseParams :=\n  {\n    data := Data;\n    input := Input;\n    output := Output\n  }.\n\nInstance FailureRecorder_MultiParams : MultiParams FailureRecorder_BaseParams :=\n  {\n    name := name ;\n    msg  := Msg ;\n    msg_eq_dec := Msg_eq_dec ;\n    name_eq_dec := name_eq_dec ;\n    nodes := nodes ;\n    all_names_nodes := all_names_nodes ;\n    no_dup_nodes := no_dup_nodes ;\n    init_handlers := InitData ;\n    net_handlers := fun dst src msg s =>\n                      runGenHandler_ignore s (NetHandler dst src msg) ;\n    input_handlers := fun nm msg s =>\n                        runGenHandler_ignore s (IOHandler nm msg)\n  }.\n\nInstance FailureRecorder_NameOverlayParams : NameOverlayParams FailureRecorder_MultiParams :=\n  {\n    adjacent_to := adjacent_to ;\n    adjacent_to_dec := adjacent_to_dec ;\n    adjacent_to_symmetric := adjacent_to_symmetric ;\n    adjacent_to_irreflexive := adjacent_to_irreflexive\n  }.\n\nInstance FailureRecorder_FailMsgParams : FailMsgParams FailureRecorder_MultiParams :=\n  {\n    msg_fail := Fail\n  }.\n\nLemma net_handlers_NetHandler :\n  forall dst src m st os st' ms,\n    net_handlers dst src m st = (os, st', ms) ->\n    NetHandler dst src m st = (tt, os, st', ms).\nProof.\nintros.\nsimpl in *.\nmonad_unfold.\nrepeat break_let.\nfind_inversion.\ndestruct u. auto.\nQed.\n\nLemma input_handlers_IOHandler :\n  forall h i d os d' ms,\n    input_handlers h i d = (os, d', ms) ->\n    IOHandler h i d = (tt, os, d', ms).\nProof.\nintros.\nsimpl in *.\nmonad_unfold.\nrepeat break_let.\nfind_inversion.\ndestruct u. auto.\nQed.\n\nLemma IOHandler_cases :\n  forall h i st u out st' ms,\n      IOHandler h i st = (u, out, st', ms) -> False.\nProof. by move => h; case. Qed.\n\nLemma NetHandler_cases : \n  forall dst src msg st out st' ms,\n    NetHandler dst src msg st = (tt, out, st', ms) ->\n    msg = Fail /\\ out = [] /\\ ms = [] /\\\n    st'.(adjacent) = NSet.remove src st.(adjacent).\nProof.\nmove => dst src msg st out st' ms.\nrewrite /NetHandler.\ncase: msg; monad_unfold.\nrewrite /=.\nmove => H_eq.\nby inversion H_eq.\nQed.\n\nLtac net_handler_cases := \n  find_apply_lem_hyp NetHandler_cases; \n  intuition idtac; subst; \n  repeat find_rewrite.\n\nLtac io_handler_cases := \n  find_apply_lem_hyp IOHandler_cases.\n\nEnd FailureRecorder.\n", "meta": {"author": "DistributedComponents", "repo": "verdi-aggregation", "sha": "c81681555d63d4a3db225119600833868caf4607", "save_path": "github-repos/coq/DistributedComponents-verdi-aggregation", "path": "github-repos/coq/DistributedComponents-verdi-aggregation/verdi-aggregation-c81681555d63d4a3db225119600833868caf4607/systems/FailureRecorderStatic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.22449605350319624}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** RTL function inlining *)\n\nRequire Import Coqlib.\nRequire Import Wfsimpl.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\n\n(** ** Environment of inlinable functions *)\n\n(** We maintain a mapping from function names to their definitions.\n  In this mapping, we only include internal functions that are eligible for\n  inlining, as determined by the external heuristic\n  [should_inline]. *)\n\nDefinition funenv : Type := PTree.t function.\n\nDefinition size_fenv (fenv: funenv) := PTree_Properties.cardinal fenv.\n\nParameter should_inline: ident -> function -> bool.\n\nDefinition add_globdef (fenv: funenv) (idg: ident * globdef fundef unit) : funenv :=\n  match idg with\n  | (id, Gfun (Internal f)) =>\n      if should_inline id f\n      then PTree.set id f fenv\n      else PTree.remove id fenv\n  | (id, _) =>\n      PTree.remove id fenv\n  end.\n\nDefinition funenv_program (p: program) : funenv :=\n  List.fold_left add_globdef p.(prog_defs) (PTree.empty function).\n\n(** State monad *)\n\n(** To construct incrementally the CFG of a function after inlining,\n  we use a state monad similar to that used in module [RTLgen].\n  It records the current state of the CFG, plus counters to generate\n  fresh pseudo-registers and fresh CFG nodes.  It also records the\n  stack size needed for the inlined function. *)\n\nRecord state : Type := mkstate {\n  st_nextreg: positive;                 (**r last used pseudo-register *)\n  st_nextnode: positive;                (**r last used CFG node *)\n  st_code: code;                        (**r current CFG  *)\n  st_stksize: Z                         (**r current stack size *)\n}.\n\n(** Monotone evolution of the state. *)\n\nInductive sincr (s1 s2: state) : Prop :=\n  Sincr (NEXTREG: Ple s1.(st_nextreg) s2.(st_nextreg))\n        (NEXTNODE: Ple s1.(st_nextnode) s2.(st_nextnode))\n        (STKSIZE: s1.(st_stksize) <= s2.(st_stksize)).\n\nRemark sincr_refl: forall s, sincr s s.\nProof.\n  intros; constructor; xomega.\nQed.\n\nLemma sincr_trans: forall s1 s2 s3, sincr s1 s2 -> sincr s2 s3 -> sincr s1 s3.\nProof.\n  intros. inv H; inv H0. constructor; xomega.\nQed.\n\n(** Dependently-typed state monad, ensuring that the final state is\n  greater or equal (in the sense of predicate [sincr] above) than\n  the initial state. *)\n\nInductive res {A: Type} {s: state}: Type := R (x: A) (s': state) (I: sincr s s').\n\nDefinition mon (A: Type) : Type := forall (s: state), @res A s.\n\n(** Operations on this monad. *)\n\nDefinition ret {A: Type} (x: A): mon A :=\n  fun s => R x s (sincr_refl s).\n\nDefinition bind {A B: Type} (x: mon A) (f: A -> mon B): mon B :=\n  fun s1 => match x s1 with R vx s2 I1 =>\n              match f vx s2 with R vy s3 I2 =>\n                R vy s3 (sincr_trans s1 s2 s3 I1 I2)\n              end\n            end.\n\nNotation \"'do' X <- A ; B\" := (bind A (fun X => B))\n   (at level 200, X ident, A at level 100, B at level 200).\n\nDefinition initstate :=\n  mkstate 1%positive 1%positive (PTree.empty instruction) 0.\n\nProgram Definition set_instr (pc: node) (i: instruction): mon unit :=\n  fun s => \n    R tt\n      (mkstate s.(st_nextreg) s.(st_nextnode) (PTree.set pc i s.(st_code)) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition add_instr (i: instruction): mon node :=\n  fun s =>\n    let pc := s.(st_nextnode) in\n    R pc\n      (mkstate s.(st_nextreg) (Psucc pc) (PTree.set pc i s.(st_code)) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition reserve_nodes (numnodes: positive): mon positive :=\n  fun s =>\n    R s.(st_nextnode)\n      (mkstate s.(st_nextreg) (Pplus s.(st_nextnode) numnodes) s.(st_code) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition reserve_regs (numregs: positive): mon positive :=\n  fun s =>\n    R s.(st_nextreg)\n      (mkstate (Pplus s.(st_nextreg) numregs) s.(st_nextnode) s.(st_code) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition request_stack (sz: Z): mon unit :=\n  fun s => \n    R tt\n      (mkstate s.(st_nextreg) s.(st_nextnode) s.(st_code) (Zmax s.(st_stksize) sz))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition ptree_mfold {A: Type} (f: positive -> A -> mon unit) (t: PTree.t A): mon unit :=\n  fun s =>\n    R tt \n      (PTree.fold (fun s1 k v => match f k v s1 return _ with R _ s2 _ => s2 end) t s)\n      _.\nNext Obligation.\n  apply PTree_Properties.fold_rec.\n  auto.\n  apply sincr_refl.\n  intros. destruct (f k v a). eapply sincr_trans; eauto. \nQed.\n\n(** ** Inlining contexts *)\n\n(** A context describes how to insert the CFG for a source function into\n  the CFG for the function after inlining:\n- a source instruction at PC [n] is relocated to PC [n + ctx.(dpc)];\n- all pseudo-registers of this instruction are shifted by [ctx.(dreg)];\n- all stack references are shifted by [ctx.(dstk)];\n- \"return\" instructions are transformed into \"return\" or \"move\" instructions\n  as governed by [ctx.(retinfo)].\n*)\n\nRecord context: Type := mkcontext {\n  dpc: positive;                        (**r offset for PCs *)\n  dreg: positive;                       (**r offset for pseudo-regs *)\n  dstk: Z;                              (**r offset for stack references *)\n  mreg: positive;                       (**r max pseudo-reg number *)\n  mstk: Z;                              (**r original stack block size *)\n  retinfo: option(node * reg)           (**r where to branch on return *)\n                                        (**r and deposit return value *)\n}.\n\n(** The following functions \"shift\" (relocate) PCs, registers, operations, etc. *)\n\nDefinition shiftpos (p amount: positive) := Ppred (Pplus p amount).\n\nDefinition spc (ctx: context) (pc: node) := shiftpos pc ctx.(dpc).\n\nDefinition sreg (ctx: context) (r: reg) := shiftpos r ctx.(dreg).\n\nDefinition sregs (ctx: context) (rl: list reg) := List.map (sreg ctx) rl.\n\nDefinition sros (ctx: context) (ros: reg + ident) := sum_left_map (sreg ctx) ros.\n\nDefinition sop (ctx: context) (op: operation) :=\n  shift_stack_operation (Int.repr ctx.(dstk)) op.\n\nDefinition saddr (ctx: context) (addr: addressing) :=\n  shift_stack_addressing (Int.repr ctx.(dstk)) addr.\n\n(** The initial context, used to copy the CFG of a toplevel function. *)\n\nDefinition initcontext (dpc dreg nreg: positive) (sz: Z) :=\n  {| dpc := dpc;\n     dreg := dreg;\n     dstk := 0;\n     mreg := nreg;\n     mstk := Zmax sz 0;\n     retinfo := None |}.\n\n(** The context used to inline a call to another function. *)\n\nDefinition min_alignment (sz: Z) :=\n  if zle sz 1 then 1\n  else if zle sz 2 then 2\n  else if zle sz 4 then 4 else 8.\n\nDefinition callcontext (ctx: context)\n                      (dpc dreg nreg: positive) (sz: Z)\n                      (retpc: node) (retreg: reg) :=\n  {| dpc := dpc;\n     dreg := dreg;\n     dstk := align (ctx.(dstk) + ctx.(mstk)) (min_alignment sz);\n     mreg := nreg;\n     mstk := Zmax sz 0;\n     retinfo := Some (spc ctx retpc, sreg ctx retreg) |}.\n\n(** The context used to inline a tail call to another function. *)\n\nDefinition tailcontext (ctx: context) (dpc dreg nreg: positive) (sz: Z) :=\n  {| dpc := dpc;\n     dreg := dreg;\n     dstk := align ctx.(dstk) (min_alignment sz);\n     mreg := nreg;\n     mstk := Zmax sz 0;\n     retinfo := ctx.(retinfo) |}.\n\n(** ** Recursive expansion and copying of a CFG *)\n\n(** Insert \"move\" instructions to copy the arguments of an inlined\n    function into its parameters. *)\n\nFixpoint add_moves (srcs dsts: list reg) (succ: node): mon node :=\n  match srcs, dsts with\n  | s1 :: sl, d1 :: dl =>\n      do n <- add_instr (Iop Omove (s1 :: nil) d1 succ);\n      add_moves sl dl n\n  | _, _ =>\n      ret succ\n  end.\n\n(** To prevent infinite inlining of a recursive function, when we\n  inline the body of a function [f], this function is removed from the\n  environment of inlinable functions and therefore becomes ineligible\n  for inlining.  This decreases the size (number of entries) of the\n  environment and guarantees termination.  Inlining is, therefore,\n  presented as a well-founded recursion over the size of the environment. *)\n\nSection EXPAND_CFG.\n\nVariable fenv: funenv.\n\n(** The [rec] parameter is the recursor: [rec fenv' P ctx f] copies \n  the body of function [f], with inline expansion within, as governed\n  by context [ctx].  It can only be called for function environments\n  [fenv'] strictly smaller than the current environment [fenv]. *)\n\nVariable rec: forall fenv', (size_fenv fenv' < size_fenv fenv)%nat -> context -> function -> mon unit.\n\n(** Given a register-or-symbol [ros], can we inline the corresponding call? *)\n\nInductive inline_decision (ros: reg + ident) : Type :=\n  | Cannot_inline\n  | Can_inline (id: ident) (f: function) (P: ros = inr reg id) (Q: fenv!id = Some f).\n\nProgram Definition can_inline (ros: reg + ident): inline_decision ros :=\n  match ros with\n  | inl r => Cannot_inline _\n  | inr id => match fenv!id with Some f => Can_inline _ id f _ _ | None => Cannot_inline _ end\n  end.\n\n(** Inlining of a call to function [f].  An appropriate context is\n  created, then the CFG of [f] is recursively copied, then moves\n  are inserted to copy the arguments of the call to the parameters of [f]. *)\n\nDefinition inline_function (ctx: context) (id: ident) (f: function)\n                           (P: PTree.get id fenv = Some f)\n                           (args: list reg)\n                           (retpc: node) (retreg: reg) : mon node :=\n  let npc := max_pc_function f in\n  let nreg := max_reg_function f in\n  do dpc <- reserve_nodes npc;\n  do dreg <- reserve_regs nreg;\n  let ctx' := callcontext ctx dpc dreg nreg f.(fn_stacksize) retpc retreg in \n  do x <- rec (PTree.remove id fenv) (PTree_Properties.cardinal_remove P) ctx' f;\n  add_moves (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)).\n\n(** Inlining of a tail call to function [f].  Similar to [inline_function],\n  but the new context is different. *)\n\nDefinition inline_tail_function (ctx: context) (id: ident) (f: function)\n                               (P: PTree.get id fenv = Some f)\n                               (args: list reg): mon node :=\n  let npc := max_pc_function f in\n  let nreg := max_reg_function f in\n  do dpc <- reserve_nodes npc;\n  do dreg <- reserve_regs nreg;\n  let ctx' := tailcontext ctx dpc dreg nreg f.(fn_stacksize) in \n  do x <- rec (PTree.remove id fenv) (PTree_Properties.cardinal_remove P) ctx' f;\n  add_moves (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)).\n\n(** The instruction generated for a [Ireturn] instruction found in an\n  inlined function body. *)\n\nDefinition inline_return (ctx: context) (or: option reg) (retinfo: node * reg) :=\n  match retinfo, or with\n  | (retpc, retreg), Some r => Iop Omove (sreg ctx r :: nil) retreg retpc\n  | (retpc, retreg), None   => Inop retpc\n  end.\n\n(** Expansion and copying of an instruction.  For most instructions,\n  its registers and successor PC are shifted as per the context [ctx],\n  then the instruction is inserted in the final CFG at its final position\n  [spc ctx pc].  \n\n  [Icall] instructions are either replaced by a \"goto\" to the expansion\n  of the called function, or shifted as described above.\n\n  [Itailcall] instructions are similar, with one additional case.  If\n  the [Itailcall] occurs in the body of an inlined function, and\n  cannot be inlined itself, it must be turned into an [Icall]\n  instruction that branches to the return point of the inlined\n  function.\n\n  Finally, [Ireturn] instructions within an inlined function are\n  turned into a \"move\" or \"goto\" that stores the result, if any,\n  into the destination register, then branches back to the successor\n  of the inlined call. *)\n\nDefinition expand_instr (ctx: context) (pc: node) (i: instruction): mon unit :=\n  match i with\n  | Inop s =>\n      set_instr (spc ctx pc) (Inop (spc ctx s))\n  | Iop op args res s =>\n      set_instr (spc ctx pc)\n                (Iop (sop ctx op) (sregs ctx args) (sreg ctx res) (spc ctx s))\n  | Iload chunk addr args dst s =>\n      set_instr (spc ctx pc)\n                (Iload chunk (saddr ctx addr) (sregs ctx args) (sreg ctx dst) (spc ctx s))\n  | Istore chunk addr args src s =>\n      set_instr (spc ctx pc)\n                (Istore chunk (saddr ctx addr) (sregs ctx args) (sreg ctx src) (spc ctx s))\n  | Icall sg ros args res s =>\n      match can_inline ros with\n      | Cannot_inline =>\n          set_instr (spc ctx pc)\n                    (Icall sg (sros ctx ros) (sregs ctx args) (sreg ctx res) (spc ctx s))\n      | Can_inline id f P Q =>\n          do n <- inline_function ctx id f Q args s res;\n          set_instr (spc ctx pc) (Inop n)\n      end\n  | Itailcall sg ros args =>\n      match can_inline ros with\n      | Cannot_inline =>\n          match ctx.(retinfo) with\n          | None =>\n              set_instr (spc ctx pc)\n                        (Itailcall sg (sros ctx ros) (sregs ctx args))\n          | Some(rpc, rreg) =>\n              set_instr (spc ctx pc)\n                        (Icall sg (sros ctx ros) (sregs ctx args) rreg rpc)\n          end\n      | Can_inline id f P Q =>\n          do n <- inline_tail_function ctx id f Q args;\n          set_instr (spc ctx pc) (Inop n)\n      end          \n  | Ibuiltin ef args res s =>\n      set_instr (spc ctx pc)\n                (Ibuiltin ef (sregs ctx args) (sreg ctx res) (spc ctx s))\n  | Icond cond args s1 s2 =>\n      set_instr (spc ctx pc)\n                (Icond cond (sregs ctx args) (spc ctx s1) (spc ctx s2))\n  | Ijumptable r tbl =>\n      set_instr (spc ctx pc)\n                (Ijumptable (sreg ctx r) (List.map (spc ctx) tbl))\n  | Ireturn or =>\n      match ctx.(retinfo) with\n      | None =>\n          set_instr (spc ctx pc) (Ireturn (option_map (sreg ctx) or))\n      | Some rinfo =>\n          set_instr (spc ctx pc) (inline_return ctx or rinfo)\n      end\n  end.\n\n(** The expansion of a function [f] iteratively expands all its\n  instructions, after recording how much stack it needs. *)\n\nDefinition expand_cfg_rec (ctx: context) (f: function): mon unit :=\n  do x <- request_stack (ctx.(dstk) + ctx.(mstk));\n  ptree_mfold (expand_instr ctx) f.(fn_code).\n\nEnd EXPAND_CFG.\n\n(** Here we \"tie the knot\" of the recursion, taking the fixpoint\n  of [expand_cfg_rec]. *)\n\nDefinition expand_cfg := Fixm size_fenv expand_cfg_rec.\n\n(** Start of the recursion: copy and inline function [f] in the\n  initial context. *)\n\nDefinition expand_function (fenv: funenv) (f: function): mon context :=\n  let npc := max_pc_function f in\n  let nreg := max_reg_function f in\n  do dpc <- reserve_nodes npc;\n  do dreg <- reserve_regs nreg;\n  let ctx := initcontext dpc dreg nreg f.(fn_stacksize) in \n  do x <- expand_cfg fenv ctx f;\n  ret ctx.\n\n(** ** Inlining in functions and whole programs. *)\n\nLocal Open Scope string_scope.\n\n(** Inlining can increase the size of the function's stack block.  We must\n  make sure that the new size does not exceed [Int.max_unsigned], otherwise\n  address computations within the stack would overflow and produce incorrect\n  results. *)\n\nDefinition transf_function (fenv: funenv) (f: function) : Errors.res function :=\n  let '(R ctx s _) := expand_function fenv f initstate in\n  if zlt s.(st_stksize) Int.max_unsigned then\n    OK (mkfunction f.(fn_sig) \n                   (sregs ctx f.(fn_params))\n                   s.(st_stksize)\n                   s.(st_code)\n                   (spc ctx f.(fn_entrypoint)))\n  else\n    Error(msg \"Inlining: stack too big\").\n\nDefinition transf_fundef (fenv: funenv) (fd: fundef) : Errors.res fundef :=\n  AST.transf_partial_fundef (transf_function fenv) fd.\n\nDefinition transf_program (p: program): Errors.res program :=\n  let fenv := funenv_program p in\n  AST.transform_partial_program (transf_fundef fenv) p.\n\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/backend/Inlining.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2244384223071527}}
{"text": "From iris.base_logic Require Export gen_heap.\nFrom iris.program_logic Require Export language ectx_language ectxi_language.\nFrom iris.proofmode Require Import tactics.\nFrom mwp Require Export mwp mwp_triple.\nFrom mwp.mwp_modalities Require Export mwp_step_fupd mwp_fupd.\nFrom logrel_ifc.lambda_sec Require Export lang lattice.\n\nClass secG_un Σ := SecG_un {\n  secG_un_invG :> invG Σ;\n  secG_un_gen_heapG :> gen_heapG loc val Σ;\n}.\n\nTactic Notation \"umods\" := rewrite /mwpC_modality /mwpD_modality; cbn.\n\nLtac inv_head_step :=\n  repeat match goal with\n         | _ => progress simplify_map_eq/= (* simplify memory stuff *)\n         | H : to_val _ = Some _ |- _ => apply of_to_val in H\n         | H : head_step ?e _ _ _ _ _ |- _ =>\n           try (is_var e; fail 1);\n           inversion H; subst; clear H\n         end.\n\nLocal Hint Extern 1 (head_step _ _ _ _ _ _) => econstructor : core.\nLocal Hint Extern 0 (head_reducible _ _) => eexists _, _, _, _; simpl : core.\nLocal Hint Resolve to_of_val : core.\n\nLocal Ltac solve_exec_safe := intros; subst; do 3 eexists; econstructor; eauto.\nLocal Ltac solve_exec_puredet := simpl; intros; by inv_head_step.\nLocal Ltac solve_pure_exec :=\n  unfold IntoVal in *;\n  repeat match goal with H : AsVal _ |- _ => destruct H as [??] end; subst;\n  intros ?; apply nsteps_once, pure_head_step_pure_step;\n  constructor; [solve_exec_safe | solve_exec_puredet].\n\nGlobal Instance pure_lam e1 e2 `{!AsVal e2} :\n  PureExec True 1 (App (Lam e1) e2) e1.[e2 /].\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_LetIn e1 e2 `{!AsVal e1} :\n  PureExec True 1 (LetIn e1 e2) e2.[e1 /].\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_seq e1 e2 `{!AsVal e1} :\n  PureExec True 1 (Seq e1 e2) e2.\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_binop op a b :\n  PureExec True 1 (BinOp op (Nat a) (Nat b)) (# (binop_eval op a b)).\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_if_true e1 e2 :\n  PureExec True 1 (If (Bool true) e1 e2) e1.\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_if_false e1 e2 :\n  PureExec True 1 (If (Bool false) e1 e2) e2.\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_fst e1 e2 `{!AsVal e1, !AsVal e2} :\n  PureExec True 1 (Proj1 (Pair e1 e2)) e1.\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_snd e1 e2 `{!AsVal e1, !AsVal e2} :\n  PureExec True 1 (Proj2 (Pair e1 e2)) e2.\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_case_inl e0 e1 e2 `{!AsVal e0}:\n  PureExec True 1 (Case (InjL e0) e1 e2) e1.[e0/].\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_case_inr e0 e1 e2 `{!AsVal e0}:\n  PureExec True 1 (Case (InjR e0) e1 e2) e2.[e0/].\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_case_tapp e :\n  PureExec True 1 (TApp (TLam e)) e.\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_case_tlapp e :\n  PureExec True 1 (TLApp (TLLam e)) e.\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_unpackpack e1 e2 `{!AsVal e1}:\n  PureExec True 1 (Unpack (Pack e1) e2) (e2.[e1/]).\nProof. solve_pure_exec. Qed.\n\nGlobal Instance pure_fold e `{!AsVal e}:\n  PureExec True 1 (Unfold (Fold e)) e.\nProof. solve_pure_exec. Qed.\n\nNotation \"l ↦{ dq } v\" := (mapsto (L:=loc) (V:=val) l dq v%V)\n  (at level 20, format \"l  ↦{ dq }  v\") : bi_scope.\nNotation \"l ↦{# q } v\" := (mapsto (L:=loc) (V:=val) l (DfracOwn q) v%V)\n  (at level 20, format \"l  ↦{# q }  v\") : bi_scope.\nNotation \"l ↦ v\" := (mapsto (L:=loc) (V:=val) l (DfracOwn 1) v%V)\n  (at level 20, format \"l  ↦  v\") : bi_scope.\n\nSection mwp_lang_lemmas.\n  Context `{secG_un Σ}.\n\n  Definition SI (σ : state) : iProp Σ := gen_heap_interp σ.\n\n  Lemma mwp_fupd_alloc E v Φ :\n    {{| ∀ l, l ↦ v -∗ Φ (LocV l) 1 |}}@{mwpd_fupd SI}\n      Alloc (# v) @ E\n    {{| w ; n, Φ w n |}}.\n  Proof.\n    iIntros \"_ !> HΦ\".\n    iApply mwp_fupd_lift_atomic_head_step'; auto.\n    { intros []; inversion 1; eauto. }\n    iIntros (σ1) \"Hσ1\".\n    iMod (fupd_mask_subseteq ∅) as \"Hclose\"; first set_solver.\n    iModIntro. iIntros (v' σ2 Hstep); inv_head_step.\n    assert (# v' = # (LocV l)) by auto; simplify_eq.\n    iMod (@gen_heap_alloc with \"Hσ1\") as \"(Hσ & Hl & _)\"; first done.\n    iMod \"Hclose\"; iModIntro; iFrame; iModIntro.\n    by iApply \"HΦ\".\n  Qed.\n\n  Lemma mwp_fupd_load E l q v Φ :\n    {{| l ↦{#q} v ∗ (l ↦{#q} v -∗ Φ v 1) |}}@{mwpd_fupd SI}\n      Load (Loc l) @ E\n    {{| w ; n, Φ w n |}}.\n  Proof.\n    iIntros \"_ !> [Hl HΦ]\".\n    iApply mwp_fupd_lift_atomic_head_step'; auto.\n    { intros []; inversion 1; eauto. }\n    iIntros (σ1) \"Hσ1\".\n    iMod (fupd_mask_subseteq ∅) as \"Hclose\"; first set_solver.\n    iDestruct (@gen_heap_valid with \"Hσ1 Hl\") as %?.\n    iModIntro. iIntros (v' σ2 Hstep); inv_head_step.\n    iMod \"Hclose\"; iModIntro; iFrame; iModIntro.\n    by iApply \"HΦ\".\n  Qed.\n\n  Lemma mwp_fupd_store E l v v' Φ :\n    {{| l ↦ v ∗ (l ↦ v' -∗ Φ UnitV 1) |}}@{mwpd_fupd SI}\n      Store (Loc l) (# v') @ E\n    {{| w ; n, Φ w n |}}.\n  Proof.\n    iIntros \"_ !> [Hl HΦ]\".\n    iApply mwp_fupd_lift_atomic_head_step'; auto.\n    { intros []; inversion 1; eauto. }\n    iIntros (σ1) \"Hσ1\".\n    iMod (fupd_mask_subseteq ∅) as \"Hclose\"; first set_solver.\n    iModIntro. iIntros (w σ2 Hstep); inv_head_step.\n    assert (# w = # UnitV) by auto; simplify_eq.\n    iMod (@gen_heap_update with \"Hσ1 Hl\") as \"[$ Hl]\".\n    iMod \"Hclose\"; iModIntro; iFrame; iModIntro.\n    by iApply \"HΦ\".\n  Qed.\n\n  Lemma mwp_step_fupd_alloc E v Φ :\n    {{| ▷ ∀ l, l ↦ v -∗ Φ (LocV l) 1 |}}@{mwpd_step_fupd SI}\n      Alloc (# v) @ E\n    {{| w ; n, Φ w n |}}.\n  Proof.\n    iIntros \"_ !> HΦ\".\n    iApply mwp_step_fupd_lift_atomic_head_step'; auto.\n    { intros []; inversion 1; eauto. }\n    iIntros (σ1) \"Hσ1\".\n    iMod (fupd_mask_subseteq ∅) as \"Hclose\"; first set_solver.\n    do 2 iModIntro. iIntros (v' σ2 Hstep); inv_head_step.\n    assert (# v' = # (LocV l)) by auto; simplify_eq.\n    iMod (@gen_heap_alloc with \"Hσ1\") as \"(Hσ & Hl & _)\"; first done.\n    iMod \"Hclose\"; iModIntro; iFrame; iModIntro.\n    by iApply \"HΦ\".\n  Qed.\n\n  Lemma mwp_step_fupd_load E l q v Φ :\n    {{| ▷ l ↦{q} v ∗ ▷ (l ↦{q} v -∗ Φ v 1) |}}@{mwpd_step_fupd SI}\n      Load (Loc l) @ E\n    {{| w ; n, Φ w n |}}.\n  Proof.\n    iIntros \"_ !> [Hl HΦ]\".\n    iApply mwp_step_fupd_lift_atomic_head_step'; auto.\n    { intros []; inversion 1; eauto. }\n    iIntros (σ1) \"Hσ1\".\n    iMod (fupd_mask_subseteq ∅) as \"Hclose\"; first set_solver.\n    do 2 iModIntro.\n    iDestruct (@gen_heap_valid with \"Hσ1 Hl\") as %?.\n    iIntros (v' σ2 Hstep); inv_head_step.\n    iMod \"Hclose\"; iModIntro; iFrame; iModIntro.\n    by iApply \"HΦ\".\n  Qed.\n\n  Lemma mwp_step_fupd_store E l v v' Φ :\n    {{| ▷ l ↦ v ∗ ▷ (l ↦ v' -∗ Φ UnitV 1) |}}@{mwpd_step_fupd SI}\n      Store (Loc l) (# v') @ E\n    {{| w ; n, Φ w n |}}.\n  Proof.\n    iIntros \"_ !> [Hl HΦ]\".\n    iApply mwp_step_fupd_lift_atomic_head_step'; auto.\n    { intros []; inversion 1; eauto. }\n    iIntros (σ1) \"Hσ1\".\n    iMod (fupd_mask_subseteq ∅) as \"Hclose\"; first set_solver.\n    do 2 iModIntro. iIntros (w σ2 Hstep); inv_head_step.\n    assert (# w = # UnitV) by auto; simplify_eq.\n    iMod (@gen_heap_update with \"Hσ1 Hl\") as \"[$ Hl]\".\n    iMod \"Hclose\"; iModIntro; iFrame; iModIntro.\n    by iApply \"HΦ\".\n  Qed.\n\nEnd mwp_lang_lemmas.\n", "meta": {"author": "logsem", "repo": "iris-tini", "sha": "1f3440dc1a992329635a25b1fd81703cd058c817", "save_path": "github-repos/coq/logsem-iris-tini", "path": "github-repos/coq/logsem-iris-tini/iris-tini-1f3440dc1a992329635a25b1fd81703cd058c817/theories/lambda_sec/rules_unary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22443842230715266}}
{"text": "Require Import ssreflect ssrfun ssrbool.\n(*Require Import Generic.lemmas Generic.wlog.\nRequire Import PG32.pg32_inductive PG32.pg32_spreads_packings.*)\nRequire Import List.\nRequire Import PG32.pg32_spreads_packings PG32.pg32_packings.\n\nLemma aux_S21 : statement_packings S21.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S21.\nLemma aux_S22 : statement_packings S22.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S22.\nLemma aux_S23 : statement_packings S23.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S23.\nLemma aux_S24 : statement_packings S24.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S24.\nLemma aux_S25 : statement_packings S25.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S25.\nLemma aux_S26 : statement_packings S26.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S26.\nLemma aux_S27 : statement_packings S27.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S27.\nLemma aux_S28 : statement_packings S28.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S28.\nLemma aux_S29 : statement_packings S29.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S29.\nLemma aux_S30 : statement_packings S30.\nProof.\n  solve_goal1.\n  par: time (solve_goal2 s4 s5 s6 s7 Hs4 Hs5 Hs6 Hs7 le34 le45 le56 le67 \n                  Hd1 Hd2 Hd3 Hd4 Hd5 Hd6 Hd7 Hd8 Hd9 Hd10 Hd11 Hd12 Hd13 Hd14 Hd15 Hd16 Hd17 Hd18 Hd19 Hd20 Hd21).\nQed.\nCheck aux_S30.\n", "meta": {"author": "magaud", "repo": "PG3q", "sha": "d34bc2a8b4f42610952a65840b724a69f5a926a1", "save_path": "github-repos/coq/magaud-PG3q", "path": "github-repos/coq/magaud-PG3q/PG3q-d34bc2a8b4f42610952a65840b724a69f5a926a1/pg32/pg32_packings_part3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2244384223071526}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Classes.Morphisms.\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcertx.common.MemoryX.\nRequire Import liblayers.lib.Functor.\nRequire Import liblayers.lib.Monad.\nRequire Import liblayers.lib.Lens.\nRequire Export liblayers.compcertx.LiftMem.\nRequire Import compcert.backend.Deadcodeproof.\n\n(** Dead code elimination requires the definition of a [magree]\n    relation on memories, which is a stronger version of memory\n    extension parameterized on a predicate on memory locations over\n    which contents must be equal between the two memories.\n\n    Unfortunately, it is not possible to define this predicate only\n    using operations and axioms of the CompCert memory model. Thus,\n    CompCert provides in [compcert.backend.DeadcodeproofImpl] an\n    implementation of [magree] on the concrete implementation\n    [compcert.common.Memimpl] of the memory model. It becomes then\n    desirable to be able to lift this implementation along any lens to\n    [Memimpl.mem].\n\n    In this file, assuming any memory model [mem] with [magree], we\n    provide a uniform way to lift [magree] along a lens to [mem].\n*)\n\nSection LIFTDERIVED.\n  Context `{HW: LiftMemoryModel}.\n\n  Context `{magree_ops: !MAgreeOps bmem}\n          `{magree_prf: !MAgree bmem}.\n\n  Global Instance lift_magree_ops:\n    MAgreeOps mem\n    :=\n      {|\n        magree m1 m2 ls := lift π (fun (bm1 bm2: bmem) => magree bm1 bm2 ls) m1 m2\n      |}.\n\n  Global Instance lift_magree:\n    MAgree mem.\n  Proof.\n    constructor.\n    lift π ma_perm.\n    lift π magree_monotone.\n    lift π mextends_agree.\n    lift π magree_extends.\n    lift π magree_loadbytes.\n    lift π magree_load.\n    lift π magree_storebytes_parallel.\n    lift π magree_store_parallel.\n    lift π magree_storebytes_left.\n    lift π magree_store_left.\n    lift π magree_free.\n  Qed.\n\nEnd LIFTDERIVED.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/liblayers/compcertx/LiftDeadcodeproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.22442510925028375}}
{"text": "Require Import Coq.Strings.Ascii\n        Coq.Bool.Bool\n        Coq.Lists.List\n        Coq.Structures.OrderedType.\n\nRequire Import\n        Fiat.Narcissus.BinLib.Core\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Common.Compose\n        Fiat.Narcissus.Common.ComposeOpt\n        Fiat.Narcissus.Automation.Solver\n        Fiat.Narcissus.Lib2.WordOpt\n        Fiat.Narcissus.Lib2.NatOpt\n        Fiat.Narcissus.Lib2.StringOpt\n        Fiat.Narcissus.Lib2.EnumOpt\n        Fiat.Narcissus.Lib2.FixListOpt\n        Fiat.Narcissus.Lib2.SumTypeOpt.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Examples.Tutorial.Tutorial\n        Fiat.Examples.DnsServer.DecomposeEnumField\n        Fiat.QueryStructure.Automation.AutoDB\n        Fiat.QueryStructure.Implementation.DataStructures.BagADT.BagADT\n        Fiat.QueryStructure.Automation.IndexSelection\n        Fiat.QueryStructure.Specification.SearchTerms.ListPrefix\n        Fiat.QueryStructure.Automation.SearchTerms.FindPrefixSearchTerms\n        Fiat.QueryStructure.Automation.MasterPlan\n        Fiat.Examples.HACMSDemo.DuplicateFree\n        Fiat.Examples.HACMSDemo.HACMSDemo\n        Fiat.Examples.HACMSDemo.WheelSensor.\n\n(* We first synthesize an implementation of our encoder. *)\nLemma Sharpened_encode_SensorData_Impl\n  : { encode_SensorData_Impl : _ &\n      forall ce (val : SensorType),\n        refine (encode_SensorData_Spec val ce)\n               (ret (encode_SensorData_Impl val ce))}.\nProof.\n  eexists; intros; set_evars.\n  unfold encode_SensorData_Spec.\n  unfold compose, Bind2.\n  setoid_rewrite refine_encode_enum; simplify with monad laws.\n  setoid_rewrite (@refine_encode_SumType\n          bin\n          _\n          2\n          ([nat : Type; nat : Type])\n          _\n          (icons _\n                 (icons _ (inil (A := Type))))).\n  simplify with monad laws.\n  simpl; rewrite app_nil_r.\n  finish honing.\n  simpl; f_equiv.\n  simpl; repeat apply Build_prim_and; eauto;\n    intros; rewrite refine_encode_nat; finish honing.\nDefined.\n\n(* Extract the synthesized encoder. *)\nDefinition encode_SensorData_Impl :=\n  Eval simpl in projT1 Sharpened_encode_SensorData_Impl.\n\n(* Extract its proof of correctness for good measure. *)\nLemma refine_encode_SensorData_Impl\n  : forall ce (val : SensorType),\n        refine (encode_SensorData_Spec val ce)\n               (ret (encode_SensorData_Impl val ce)).\nProof.\n  exact (projT2 Sharpened_encode_SensorData_Impl).\nQed.\n\nOpaque encode_SensorData_Spec.\n\nTheorem SharpenedWheelSensor :\n    FullySharpened WheelSensorSpec.\nProof.\n  start sharpening ADT.\n  start_honing_QueryStructure'.\n  (* We first insert checks for the DuplicateFree constraints.  *)\n  hone method \"AddSpeedSubscriber\". { dropDuplicateFree. }\n  hone method \"AddTirePressureSubscriber\". { dropDuplicateFree. }\n  (* Break down the suscribers 'table' into one for each topic.  *)\n  decompose_EnumField \"subscribers\" \"topic\".\n  (* Select the kinds of searches each 'table' should support. *)\n  chooseIndexes.\n  (* Implement each method using the chosen search operations. *)\n  initializer.\n  insertOne.\n  insertOne.\n  rewrite refine_encode_SensorData_Impl; planOne.\n  rewrite refine_encode_SensorData_Impl; planOne.\n  (* Cleanup the synthesized methods. *)\n  final_optimizations.\n  (* Ensure the implementation is executable. *)\n  determinize.\n  (* Select concrete data structures for each table.  *)\n  choose_data_structures.\n  (* Some final cleanup. *)\n  final_simplification.\n  (* And we're done! *)\n  use_this_one.\nDefined.\n\n(* We can now extract the implementation derived above. *)\nDefinition WheelSensorImpl := Eval simpl in projT1 SharpenedWheelSensor.\nPrint WheelSensorImpl.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Examples/HACMSDemo/WheelSensorEncoder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2243959219839}}
{"text": "Require Export compcert.lib.Coqlib.\nRequire Export compcert.lib.Integers.\nRequire Export compcert.common.AST.\nRequire Export compcert.common.Values.\nRequire Export compcert.common.AST.\nRequire Export compcert.common.Globalenvs.\nRequire Export compcert.common.Memdata.\nRequire Export compcertx.common.MemoryX. (* for storebytes_empty, free_range *)\nRequire Export liblayers.lib.Decision.\nRequire Export liblayers.logic.Structures.\nRequire Export liblayers.logic.LayerData.\nRequire Export liblayers.compcertx.CompcertStructures.\nRequire Export liblayers.compcertx.InitMem.\nRequire Export AbstractData.\nRequire Export MemWithData.\n\n\n(** * Preliminaries *)\n\n(** Specialize [rel_incr] to use [(≤)]. *)\n\nNotation \"'incr' p R\" := (rel_incr (≤) (fun p => R) p)\n  (at level 100, p at level 0, R at level 0)\n  : rel_scope.\n\n\n(** * Simulation relations blueprints *)\n\nSection DEFINITION.\n  Context `{Hmem: BaseMemoryModel}.\n  Context {D1 D2: layerdata}.\n  Local Opaque mwd_ops.\n\n  (** ** Components *)\n\n  (** This is the most general definition of a simulation relation\n    toolkit that we use. We are given two memory models, and a carrier\n    type for the relation (which generalizes [meminj]). We also have\n    two basic relation components, indexed by elements of the carrier\n    type: [match_mem] specifies how memory states should be related,\n    whereas [match_block] specifies how block identifiers should be\n    related. From these two components, it is possible to build up\n    ways to relate more complex states such as [Clight.state] or\n    [Asm.state]. The carrier type ensures that the constituent memory\n    state, values, pointers, etc. are related in a consistent way.\n\n    We also specify a preorder on the carrier type (which generalizes\n    [inject_incr]), which [match_block] (and derived relations) should\n    be consistent with. This is because the simulation diagram of some\n    memory operations (namely [Mem.alloc]) use a final parameter\n    [p' : param] different from the initial parameter [p : param].\n    To ensure that other components of the state remain related, in\n    such cases we require that [p ≤ p'].\n\n    Finally, the relations on Compcert values ([val], [memval]) are\n    built from [match_block] in nearly the same way for all of our\n    simulation relations (identical values are related, as well as\n    pointers with related block identifiers and identical offsets).\n    But there is one aspect that differs between different simulation\n    relations: with some relations we want [Vundef] and [Undef] on the\n    left to be related to any values on the right (ie. be bottom\n    elements), whereas for other relations we only want them to be\n    related to themselves. The obvious solution is to specify for each\n    relation a flag indicating which case we're in. However this is\n    incompatible with composition. Consider a relation [R1] which\n    relates [Vundef] to anything (flag set), and a relation [R2] which\n    only relates it to itself (flag cleared). The composite relation\n    [R1;R2] will relate [Vundef] to most values, but there may be a\n    block b' on the right such that there is no b related to it on the\n    left by [R2] (∀ b, ¬ b R2 b'). In this case [Vundef] on the left\n    will not be related by [R1;R2] to [Vptr b' 0] on the right,\n    because there is no intermediate value for the composition to use.\n    Because of these contradictory situations, there is no\n    setting for the flag that describes the composite relation\n    appropriately.\n\n    To address this, we generalize from there and split the flag into\n    two part: the proposition [simrel_undef_matches_values] determines\n    whether [Vundef] matches all non-pointer values, and the predicate\n    [simrel_undef_matches_pointer] indicates which pointer values\n    [Vundef] additionnaly matches. If some pointer are related to\n    [Vundef], then non-pointer values should all be related to\n    [Vundef] as well. Conversely, if [simrel_undef_matches_values] is\n    set, then any block [b2] related to some block [b1] on the left by\n    [match_block] should be related to [Vundef] as well. *)\n\n  Record simrel_components :=\n    {\n      simrel_world: Type;\n      simrel_acc :> Le simrel_world;\n      simrel_undef_matches_values_bool: bool;\n      simrel_undef_matches_block: simrel_world -> block -> Prop;\n      simrel_new_glbl: list (ident * list AST.init_data);\n      simrel_meminj: simrel_world -> meminj;\n      match_mem: simrel_world -> rel (mwd D1) (mwd D2)\n    }.\n\n  Global Existing Instance simrel_acc.\n\n  (** In what follows we declare many typeclass instances with a\n    [simrel_undef_matches_*] premise. To make sure they work as\n    expected, we declare them as typeclasses. We also show that\n    [simrel_undef_matches_values] is decidable, since it is defined\n    from a boolean. *)\n\n  Existing Class simrel_undef_matches_block.\n\n  Class simrel_undef_matches_values (R: simrel_components) :=\n    simrel_undef_matches_values_true:\n      simrel_undef_matches_values_bool R = true.\n\n  Global Instance simrel_undef_matches_values_dec R:\n    Decision (simrel_undef_matches_values R) :=\n      decide_booleq _ _.\n\n  (** ** Relations derived from [simrel_meminj] *)\n\n  (** Compcert usually passes pointers around as separate block and\n    offset arguments. Since we can't relate those independently\n    (because the offset shift is specific to each block), we instead\n    relate (block, offset) pairs and use [rel_curry] to construct our\n    [Monotonicity} relations.\n\n    Relating pointers is complicated because of the interaction\n    between the abstract [Z] offsets that are used by the memory model\n    and the [ptrofs] concrete machine representations that are used to\n    build [val]ues. The basic relation [match_ptr] relates abstract\n    pointers in the obvious way, while [match_ptrbits] relates\n    concrete pointers as is done in [Val.inject]. *)\n\n  Inductive match_ptr R p: relation (block * Z)%type :=\n    match_ptr_intro b1 ofs1 b2 delta:\n      simrel_meminj R p b1 = Some (b2, delta) ->\n      match_ptr R p (b1, ofs1) (b2, ofs1 + delta)%Z.\n\n  Inductive match_ptrbits R p: relation (block * ptrofs)%type :=\n    match_ptrbits_intro b1 ofs1 b2 delta:\n      simrel_meminj R p b1 = Some (b2, delta) ->\n      match_ptrbits R p (b1, ofs1) (b2, Ptrofs.add ofs1 (Ptrofs.repr delta)).\n\n  (** For [Mem.free] we need to relate a whole range of abstract\n    pointers in the form of an (ofs, lo, hi) triple. *)\n\n  Inductive match_ptrrange R p: relation (block * Z * Z)%type :=\n    match_ptrrange_intro b1 ofs1 b2 ofs2 sz:\n      RIntro\n        (match_ptr R p (b1, ofs1) (b2, ofs2))\n        (match_ptrrange R p) (b1, ofs1, ofs1+sz)%Z (b2, ofs2, ofs2+sz)%Z.\n\n  Global Existing Instance match_ptrrange_intro.\n\n  (** For operations that manipulate blocks, we can use the two\n    relations below: the weaker [match_block] relates two blocks\n    according to [simrel_meminj], no matter what the offset shift\n    is. The stronger [match_block_sameofs] only relates blocks that\n    correspond to one another with no shift in offset. *)\n\n  Definition match_block R p b1 b2 :=\n    exists delta, simrel_meminj R p b1 = Some (b2, delta).\n\n  Definition match_block_sameofs R p b1 b2 :=\n    simrel_meminj R p b1 = Some (b2, 0%Z).\n\n  Lemma match_block_sameofs_match_ptr R p b1 b2 o:\n    match_block_sameofs R p b1 b2 ->\n    match_ptr R p (b1, o) (b2, o).\n  Proof.\n    intros H.\n    replace o with (o + 0)%Z at 2 by omega.\n    constructor.\n    assumption.\n  Qed.\n\n  Lemma match_block_sameofs_match_ptrbits R p b1 b2 o:\n    match_block_sameofs R p b1 b2 ->\n    match_ptrbits R p (b1, o) (b2, o).\n  Proof.\n    intros H.\n    replace o with (Ptrofs.add o Ptrofs.zero) at 2\n      by (rewrite Ptrofs.add_zero; reflexivity).\n    constructor.\n    assumption.\n  Qed.\n\n  (** From [match_ptr] and [simrel_undef_matches_*], we can derive\n    relation for [val] and [memval]. *)\n\n  Inductive match_val R (p: simrel_world R): rel val val :=\n    | match_val_int:\n        Monotonic (@Vint) (- ==> match_val R p)\n    | match_val_long:\n        Monotonic (@Vlong) (- ==> match_val R p)\n    | match_val_float:\n        Monotonic (@Vfloat) (- ==> match_val R p)\n    | match_val_single:\n        Monotonic (@Vsingle) (- ==> match_val R p)\n    | match_val_ptr_def b1 ofs1 b2 ofs2:\n        match_ptrbits R p (b1, ofs1) (b2, ofs2) ->\n        match_val R p (Vptr b1 ofs1) (Vptr b2 ofs2)\n    | match_val_undef:\n        Monotonic (@Vundef) (match_val R p)\n    | match_val_undef_int i:\n        simrel_undef_matches_values R ->\n        Related (@Vundef) (Vint i) (match_val R p)\n    | match_val_undef_long i:\n        simrel_undef_matches_values R ->\n        Related (@Vundef) (Vlong i) (match_val R p)\n    | match_val_undef_float f:\n        simrel_undef_matches_values R ->\n        Related (@Vundef) (Vfloat f) (match_val R p)\n    | match_val_undef_single f:\n        simrel_undef_matches_values R ->\n        Related (@Vundef) (Vsingle f) (match_val R p)\n    | match_val_undef_ptr b ofs:\n        simrel_undef_matches_block R p b ->\n        Related (@Vundef) (Vptr b ofs) (match_val R p).\n\n  Global Instance match_val_ptr R p:\n    Monotonic (@Vptr) (rel_curry (match_ptrbits R p ++> match_val R p)).\n  Proof.\n    intros [b1 ofs1] [b2 ofs2].\n    apply match_val_ptr_def.\n  Qed.\n\n  Global Existing Instance match_val_int.\n  Global Existing Instance match_val_long.\n  Global Existing Instance match_val_float.\n  Global Existing Instance match_val_single.\n  Global Existing Instance match_val_ptr.\n  Global Existing Instance match_val_undef.\n  Global Existing Instance match_val_undef_int.\n  Global Existing Instance match_val_undef_long.\n  Global Existing Instance match_val_undef_float.\n  Global Existing Instance match_val_undef_single.\n  Global Existing Instance match_val_undef_ptr.\n\n  (** Note that in the [Undef] case, even though we use [match_val] we\n    still need a [simrel_undef_matches_values] guard. This is because\n    we want to exclude [match_memval Undef (Fragment Vundef _ _)] when\n    the guard is not satisfied, otherwise for example we lose the fact\n    that [match_memval id = eq]. *)\n\n  Inductive match_memval R (p: simrel_world R): rel memval memval :=\n    | match_memval_byte:\n        Monotonic (@Byte) (- ==> match_memval R p)\n    | match_memval_fragment:\n        Monotonic (@Fragment) (match_val R p ++> - ==> - ==> match_memval R p)\n    | match_memval_undef:\n        Monotonic (@Undef) (match_memval R p)\n    | match_memval_undef_byte b:\n        simrel_undef_matches_values R ->\n        Related (@Undef) (@Byte b) (match_memval R p)\n    | match_memval_undef_fragment v q n:\n        simrel_undef_matches_values R ->\n        RIntro\n          (match_val R p Vundef v)\n          (match_memval R p) Undef (Fragment v q n).\n\n  Global Existing Instance match_memval_byte.\n  Global Existing Instance match_memval_fragment.\n  Global Existing Instance match_memval_undef.\n  Global Existing Instance match_memval_undef_byte.\n  Global Existing Instance match_memval_undef_fragment.\n\n  (** ** [simrel_option_le] *)\n\n  (** This is a version of [option_le] sensitive to the\n    [simrel_undef_matches_values] component of a given simulation\n    relation. It is particularly useful in the [SimValues] library.\n\n    Some operations are formulated in terms of intermediate [option]\n    results. Often when some input is [Vundef], these intermediate\n    results are set to [None]. Then [Val.of_optbool] maps [None] back\n    to [Vundef]. This means that whether we want [None] to act as a\n    bottom element depend on whether [Vundef] does -- [option_le] is\n    in general too weak and [option_rel] is too strong. To solve this\n    problem we introduce this relator, which behaves like one or the\n    other depending on [simrel_undef_matches_values].\n\n    Note that it still might be too weak in some corner cases, because\n    it does not take [simrel_undef_matches_block] into account.\n    Fortunately, so far this has not been an issue because it seems\n    in practice [option val] is never used with pointers. The one\n    function that cannot be characterized is [Val.make_total],\n    fortunately it is only used in a few places where it can be worked\n    around fairly easily. *)\n\n  (** To define [simrel_option_le], we start with a more general\n    [flex_option_le] parametrized with a proposition [P] which\n    determines whether [None] is allowed as a bottom element. *)\n\n  Inductive flex_option_le {A B} (P: Prop) RAB: rel (option A) (option B) :=\n    | flex_option_le_some_def:\n        Monotonic Some (RAB ++> flex_option_le P RAB)\n    | flex_option_le_none_def:\n        Monotonic None (flex_option_le P RAB)\n    | flex_option_le_none_lb:\n        P ->\n        LowerBound (flex_option_le P RAB) None.\n\n  Global Instance option_rel_flex_option_le_subrel {A B} P (R: rel A B):\n    Related (option_rel R) (flex_option_le P R) subrel.\n  Proof.\n    destruct 1; constructor; auto.\n  Qed.\n\n  Global Instance flex_option_le_option_le {A B} P (R: rel A B) :\n    Related (flex_option_le P R) (option_le R) subrel.\n  Proof.\n    destruct 1; constructor; auto.\n  Qed.\n\n  Global Existing Instance flex_option_le_none_lb.\n\n  (** Assuming [P] is a known typeclass, [flex_option_le_none_lb] can\n    be used when using [lower_bound] directly. However the path to\n    [RAuto] through [Related] does not work. This is because in that\n    context, the relation from the goal is not available during the\n    [LowerBound] search; instead we search for a [LowerBound] instance\n    for an arbitrary relation, which is lated connected to the\n    relation in the goal through a [subrel] search. This works great\n    with most relations, but in this case this means that at\n    [LowerBound] resolution time, the value of [P] is unknown, and we\n    cannot resolve the corresponding premise in [flex_option_le_none_lb].\n\n    We can work around this issue with the following [RIntro] hint. *)\n\n  Global Instance flex_option_le_none_lb_rintro {A B} (P: Prop) (RAB: rel A B) y:\n    P ->\n    RIntro True (flex_option_le P RAB) None y.\n  Proof.\n    intros H _.\n    apply flex_option_le_none_lb.\n    assumption.\n  Qed.\n\n  Global Instance flex_option_le_refl {A} P (RA: relation A):\n    Reflexive RA ->\n    Reflexive (flex_option_le P RA).\n  Proof.\n    intros HRA x.\n    destruct x; constructor.\n    reflexivity.\n  Qed.\n\n  Global Instance flex_option_map_rel P:\n    Monotonic\n      (@option_map)\n      (forallr S, forallr T,\n        (S ++> T) ++> flex_option_le P S ++> flex_option_le P T).\n  Proof.\n    unfold option_map.\n    repeat rstep.\n    constructor; eauto.\n  Qed.\n\n  (** For similar reasons, we will also need a corresponding version\n    of [leb] to relate the results of operations such as\n    [Mem.valid_pointer], which are involved in pointer comparisons. *)\n\n  Inductive flex_leb (P: Prop) : rel bool bool :=\n    | flex_leb_refl : Reflexive (flex_leb P)\n    | flex_leb_false_true : P -> LowerBound (flex_leb P) false.\n\n  Global Existing Instance flex_leb_refl.\n  Global Existing Instance flex_leb_false_true.\n\n  Instance flex_leb_leb P:\n    Related (flex_leb P) leb subrel.\n  Proof.\n    destruct 1; reflexivity.\n  Qed.\n\n  Global Instance andb_flex_leb:\n    forall P, Monotonic andb (flex_leb P ++> flex_leb P ++> flex_leb P).\n  Proof.\n    intros P x1 x2 Hx y1 y2 Hy.\n    destruct Hx, Hy; simpl; try constructor; eauto.\n    destruct x; constructor; eauto.\n  Qed.\n\n  (** Then, we use [simrel_undef_matches_values] as the parameter in\n    order to obtain the behavior we want for [simrel_option_le]. We\n    use a notation so that the instances defined above for\n    [flex_option_le] can apply directly. *)\n\n  Notation simrel_option_le R :=\n    (flex_option_le (simrel_undef_matches_values R)).\n\n  Notation simrel_leb R :=\n    (flex_leb (simrel_undef_matches_values R)).\n\n  (** ** Initial memory *)\n\n  (** The [simrel_new_glbl] field is enough to formulate a sufficient\n    condition on programs for the initial memory states to be related.\n    Here we use [program_rel] to express this condition.\n\n    Note that we're careful to define [simrel_program_rel] in such a\n    way that, when applied to [simrel_components] which have the same\n    [simrel_new_glbl] and [simrel_undef_matches_values_bool], the\n    results will be convertible. This is why the components are\n    parametrized by those directly, rather than by the\n    [simrel_components] under consideration.\n\n    The relation on function definitions is straightforward. If [R]\n    permits [Vundef] as a bottom element, we also allow new function\n    definitions to be introduced on the right-hand side. Otherwise,\n    the function definitions should either both be [None], or both use\n    [Some]. Since the initial memory is constructed in a way does not\n    actually depend on the details of a function definition, we don't\n    enforce any other requirements. *)\n\n  Definition simrel_fundef_rel {F1 F2} b: ident -> rel (option F1) (option F2) :=\n    fun _ => flex_option_le (b = true) ⊤%rel.\n\n  (** For variables, we need to distinguish two cases depending on\n    whether they're listed in [simrel_new_glbl] or not.\n\n    If they are, then the variable must not appear on the left-hand\n    side, and must appear on the right-hand side, and contain the\n    specified initialization data. Note that for composition to work,\n    we need to make sure that the variable does not appear twice in\n    [simrel_new_glbl].  Otherwise, it would be possible to have a\n    situation where [v] appears in both [R12] and [R23], and\n    [None [R23 ∘ R12] (Some v)] holds as a result, but there would be\n    no intermediate value [x] that would satisfy both [None [R12] x]\n    and [x [R23] (Some v)].\n\n    For variables not in [simrel_new_glbl], we allow new variables on\n    the right-hand side if [simrel_undef_matches_values], and\n    otherwise require that the definitions be identical. *)\n\n  Definition test (P: Prop) `{Decision P}: bool :=\n    if decide P then true else false.\n\n  Definition simrel_new_glbl_for (ng: list (ident * list AST.init_data)) i :=\n    filter (fun def => test (fst def = i)) ng.\n\n  Definition simrel_newvar_ok ng b (i: ident) init :=\n    (simrel_new_glbl_for ng i = (i, init)::nil) \\/\n    (simrel_new_glbl_for ng i = nil /\\ b = true).\n\n  Definition simrel_not_new_glbl ng i :=\n    simrel_new_glbl_for ng i = nil.\n\n  Inductive simrel_vardef_rel {V} ng b i: relation (option (globvar V)) :=\n    | simrel_vardef_rel_none:\n        simrel_not_new_glbl ng i ->\n        simrel_vardef_rel ng b i None None\n    | simrel_vardef_rel_some v:\n        simrel_not_new_glbl ng i ->\n        simrel_vardef_rel ng b i (Some v) (Some v)\n    | simrel_vardef_rel_newvar v init:\n        simrel_newvar_ok ng b i init ->\n        Genv.init_data_list_valid find_symbol 0 init = true ->\n        simrel_vardef_rel ng b i None\n          (Some\n             {| gvar_info := v;\n                gvar_init := init;\n                gvar_readonly := false;\n                gvar_volatile := false |}).\n\n  Definition simrel_program_rel {F1 F2 V} R :=\n    program_rel\n      (@simrel_fundef_rel F1 F2 (simrel_undef_matches_values_bool R))\n      (@simrel_vardef_rel V (simrel_new_glbl R) (simrel_undef_matches_values_bool R)).\n\n  (** ** Properties *)\n\n  (* The expectation is that the basic relation components should be\n    compatible with the basic memory operations, in a way that is\n    consistent with the carrier order, as explained above.\n\n    Although the definition below is a good start, we will also need\n    to know that the builtin functions work well. One option would be\n    to characterize the buitins in terms of the memory operations so\n    that we can come up with a generic proof for them.\n\n    It is also unclear how the initial memory is going to work out.\n    One option would be to give a relation on programs in\n    [SimulationRelationOps] (parametric in the types of function and\n    variable definitions), and require a corresponding relational\n    property for [Genv.init_mem].\n   *)\n\n  Class SimulationRelation R :=\n    {\n      (** Properties of the accessibility relation. *)\n\n      simrel_acc_preorder:\n        @PreOrder (simrel_world R) (≤);\n\n      simrel_acc_undef_matches_pointer:\n        Monotonic (simrel_undef_matches_block R) ((≤) ++> - ==> impl);\n\n      simrel_acc_meminj:\n        Monotonic (simrel_meminj R) ((≤) ++> - ==> option_le eq);\n\n      (** Consistency of [simrel_undef_matches_values] and\n        [simrel_undef_matches_block]. *)\n\n      simrel_undef_matches_values_also_block p ptr1 b2 ofs2:\n        simrel_undef_matches_values R ->\n        match_ptrbits R p ptr1 (b2, ofs2) ->\n        simrel_undef_matches_block R p b2;\n\n      simrel_undef_matches_block_also_values p b2:\n        simrel_undef_matches_block R p b2 ->\n        simrel_undef_matches_values R;\n\n      (** The following condition is necessary for the subtraction\n          and comparison of two pointers. *)\n      simrel_undef_matches_block_or_injective p b2:\n        forall b1 b1',\n          b1' <> b1 ->\n          match_block R p b1 b2 ->\n          match_block R p b1' b2 ->\n          simrel_undef_matches_block R p b2;\n\n      (* The following conditions are necessary for comparing\n         invalid pointers with Val.cmpu* *)\n      simrel_undef_matches_block_invalid_weak p m1 m2 b1 ofs1 b2 ofs2:\n        match_mem R p m1 m2 ->\n        Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs1) = false ->\n        match_ptrbits R p (b1, ofs1) (b2, ofs2) ->\n        Mem.weak_valid_pointer m2 b2 (Ptrofs.unsigned ofs2) = true ->\n        simrel_undef_matches_block R p b2;\n\n      simrel_undef_matches_block_invalid p m1 m2 b1 ofs1 b2 ofs2:\n        match_mem R p m1 m2 ->\n        Mem.valid_pointer m1 b1 (Ptrofs.unsigned ofs1) = false ->\n        match_ptrbits R p (b1, ofs1) (b2, ofs2) ->\n        Mem.valid_pointer m2 b2 (Ptrofs.unsigned ofs2) = true ->\n        simrel_undef_matches_block R p b2;\n\n      (** Properties of [match_block_delta]. *)\n\n      match_global_block_sameofs p b:\n        block_is_global b ->\n        Proper (match_block_sameofs R p) b;\n\n      (** Initial memory *)\n\n      simrel_init_mem {F V}:\n        Monotonic\n          (Genv.init_mem (F:=F) (V:=V))\n          (simrel_program_rel R ++>\n           option_le (rexists w, match_mem R w));\n\n      (** Properties for memory operations. *)\n\n      simrel_alloc p:\n        Monotonic\n          Mem.alloc\n          (match_mem R p ++> - ==> - ==>\n           incr p (match_mem R p * match_block_sameofs R p));\n\n      simrel_free p:\n        Monotonic\n          Mem.free\n          (match_mem R p ++> rel_curry (rel_curry (match_ptrrange R p ==>\n           option_le (incr p (match_mem R p)))));\n\n      simrel_load p:\n        Monotonic\n          Mem.load\n          (- ==> match_mem R p ++> rel_curry (match_ptr R p ++>\n           option_le (match_val R p)));\n\n      simrel_store p:\n        Monotonic\n          Mem.store\n          (- ==> match_mem R p ++> rel_curry (match_ptr R p ++>\n           match_val R p ++> option_le (incr p (match_mem R p))));\n\n      simrel_loadbytes p:\n        Monotonic\n          Mem.loadbytes\n          (match_mem R p ++> rel_curry (match_ptr R p ++> - ==>\n           option_le (list_rel (match_memval R p))));\n\n      simrel_storebytes p:\n        Monotonic\n          Mem.storebytes\n          (match_mem R p ++>\n           rel_curry (match_ptr R p ++> list_rel (match_memval R p) ++>\n           option_le (incr p (match_mem R p))));\n\n      simrel_perm p:\n        Monotonic\n          Mem.perm\n          (match_mem R p ++> rel_curry (match_ptr R p ++> - ==> - ==> impl));\n\n      simrel_valid_block p:\n        Monotonic\n          Mem.valid_block\n          (match_mem R p ++> match_block R p ++> iff);\n\n      (* similar to Mem.different_pointers_inject. Necessary for\n         comparing valid pointers of different memory blocks that inject\n         into the same block. *)\n      simrel_different_pointers_inject\n        p m m' b1 ofs1 b2 ofs2 b1' delta1 b2' delta2:\n        match_mem R p m m' ->\n        b1 <> b2 ->\n        Mem.valid_pointer m b1 (Ptrofs.unsigned ofs1) = true ->\n        Mem.valid_pointer m b2 (Ptrofs.unsigned ofs2) = true ->\n        simrel_meminj R p b1 = Some (b1', delta1) ->\n        simrel_meminj R p b2 = Some (b2', delta2) ->\n        b1' <> b2' \\/\n        Ptrofs.unsigned (Ptrofs.add ofs1 (Ptrofs.repr delta1)) <>\n        Ptrofs.unsigned (Ptrofs.add ofs2 (Ptrofs.repr delta2));\n\n      (* similar to Mem.weak_valid_pointer_inject_val, but cannot be deduced\n         from Mem.address_inject. Needed for Val.cmpu* *)\n      simrel_weak_valid_pointer_inject_val p m1 m2 b1 ofs1 b2 ofs2:\n        match_mem R p m1 m2 ->\n        Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs1) = true ->\n        match_ptrbits R p (b1, ofs1) (b2, ofs2) ->\n        Mem.weak_valid_pointer m2 b2 (Ptrofs.unsigned ofs2) = true;\n\n      (** When comparing two weakly valid pointers of the same block\n       using Val.cmpu, we need to compare their offsets, and so\n       comparing the injected offsets must have the same result. To\n       this end, it is necessary to show that all weakly valid\n       pointers be shifted by the same mathematical (not machine)\n       integer amount. However, contrary to the situation with\n       Mem.address_inject for valid pointers, here for weakly valid\n       pointers we do not know whether this amount is delta. The best\n       we know, thanks to Mem.weak_valid_pointer_inject_no_overflow,\n       is that Ptrofs.unsigned (Ptrofs.repr delta) works, but proving\n       composition would be much harder than for the following\n       weak version:\n      *)\n\n      simrel_weak_valid_pointer_address_inject_weak p m1 m2 b1 b2 delta:\n        match_mem R p m1 m2 ->\n        simrel_meminj R p b1 = Some (b2, delta) ->\n        exists delta',\n          forall ofs1,\n            Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs1) = true ->\n            Ptrofs.unsigned (Ptrofs.add ofs1 (Ptrofs.repr delta)) =\n            (Ptrofs.unsigned ofs1 + delta')%Z;\n\n      (* similar to Mem.address_inject for memory injections.\n         Needed at least by Clight assign_of (By_copy) and memcpy,\n         but I guess at many other places. *)\n      simrel_address_inject p m1 m2 b1 ofs1 b2 delta pe:\n        match_mem R p m1 m2 ->\n        Mem.perm m1 b1 (Ptrofs.unsigned ofs1) Cur pe ->\n        simrel_meminj R p b1 = Some (b2, delta) ->\n        Ptrofs.unsigned (Ptrofs.add ofs1 (Ptrofs.repr delta)) =\n        (Ptrofs.unsigned ofs1 + delta)%Z;\n\n      (* similar to Mem.aligned_area_inject for memory injections.\n         Needed by Clight assign_of (By_copy) and memcpy. *)\n      simrel_aligned_area_inject p m m' b ofs al sz b' delta:\n        match_mem R p m m' ->\n        (al = 1 \\/ al = 2 \\/ al = 4 \\/ al = 8) ->\n        sz > 0 ->\n        (al | sz) ->\n        Mem.range_perm m b ofs (ofs + sz) Cur Nonempty ->\n        (al | ofs) ->\n        simrel_meminj R p b = Some (b', delta) ->\n        (al | ofs + delta);\n\n      (* similar to Mem.disjoint_or_equal_inject for memory injections.\n         Needed by Clight assign_of (By_copy) and memcpy. *)\n      simrel_disjoint_or_equal_inject\n        p m m' b1 b1' delta1 b2 b2' delta2 ofs1 ofs2 sz:\n        match_mem R p m m' ->\n        simrel_meminj R p b1 = Some (b1', delta1) ->\n        simrel_meminj R p b2 = Some (b2', delta2) ->\n        Mem.range_perm m b1 ofs1\n                       (ofs1 + sz) Max Nonempty ->\n        Mem.range_perm m b2 ofs2\n                       (ofs2 + sz) Max Nonempty ->\n        sz > 0 ->\n        b1 <> b2 \\/\n        ofs1 = ofs2 \\/\n        ofs1 + sz <= ofs2 \\/ ofs2 + sz <= ofs1 ->\n        b1' <> b2' \\/\n        (ofs1 + delta1 = ofs2 + delta2)%Z \\/\n        ofs1 + delta1 + sz <= ofs2 + delta2 \\/\n        ofs2 + delta2 + sz <= ofs1 + delta1\n    }.\n\n  Global Existing Instances simrel_acc_preorder.\n  Global Existing Instances simrel_acc_undef_matches_pointer.\n  Global Existing Instances simrel_acc_meminj.\n  Global Existing Instances simrel_alloc.\n  Local  Existing Instances simrel_free. (* strengthened version below *)\n  Global Existing Instances simrel_load.\n  Global Existing Instances simrel_store.\n  Global Existing Instances simrel_loadbytes.\n  Global Existing Instances simrel_storebytes.\n  Global Existing Instances simrel_perm.\n  Global Existing Instances simrel_valid_block.\n\n  (* NB: Those need to be redeclared outside of the section. *)\n  Global Instance: Params (@simrel_undef_matches_block) 2.\n  Global Instance: Params (@simrel_meminj) 2.\n\n  Global Instance: Params (@Genv.init_mem) 1.\n  Global Instance: Params (@Mem.empty) 0.\n  Global Instance: Params (@Mem.alloc) 3.\n  Global Instance: Params (@Mem.free) 4.\n  Global Instance: Params (@Mem.load) 4.\n  Global Instance: Params (@Mem.store) 5.\n  Global Instance: Params (@Mem.loadbytes) 4.\n  Global Instance: Params (@Mem.storebytes) 4.\n  Global Instance: Params (@Mem.loadv) 3.\n  Global Instance: Params (@Mem.storev) 4.\n  Global Instance: Params (@Mem.perm) 5.\n  Global Instance: Params (@Mem.valid_block) 2.\n\n  (** ** Packaging them up *)\n\n  (** Though it is convenient to be able to define a simulation\n    relation's operations and proofs separately, in most other contexts\n    it is simpler to have a single object which bundles them together.\n\n    Because simrel_ops is a coercion, a [simrel] can be used with\n    [match_val], [match_block], etc. One thing to keep in mind is that\n    if a parameter of your definition is only used in conjunction with\n    one of these, its type will be inferred as [simrel_components],\n    not [simrel].\n   *)\n\n  Record simrel :=\n    {\n      simrel_ops :> simrel_components;\n      simrel_prf: SimulationRelation simrel_ops\n    }.\n\n  Global Existing Instance simrel_prf.\n\n  (** ** Properties of derived relations *)\n\n  Context `{HR: SimulationRelation}.\n\n  (** *** Compatibility with the accessibility relation *)\n\n  (* NB: Need to redeclare outside of the section *)\n  Global Instance: Params (@match_ptr) 3.\n  Global Instance: Params (@match_ptrbits) 3.\n  Global Instance: Params (@match_ptrrange) 3.\n  Global Instance: Params (@match_block) 3.\n  Global Instance: Params (@match_block_sameofs) 3.\n  Global Instance: Params (@match_val) 3.\n  Global Instance: Params (@match_memval) 3.\n\n  Global Instance match_ptr_acc:\n    Monotonic (match_ptr R) ((≤) ++> subrel).\n  Proof.\n    intros p1 p2 Hp ptr1 ptr2 Hptr.\n    destruct Hptr as [b1 ofs1 b2 delta Hb].\n    transport Hb; subst.\n    constructor; eauto.\n  Qed.\n\n  Global Instance match_ptrbits_acc:\n    Monotonic (match_ptrbits R) ((≤) ++> subrel).\n  Proof.\n    intros p1 p2 Hp ptr1 ptr2 Hptr.\n    destruct Hptr as [b1 ofs1 b2 delta Hb].\n    transport Hb; subst.\n    constructor; eauto.\n  Qed.\n\n  Global Instance match_ptrrange_acc:\n    Monotonic (match_ptrrange R) ((≤) ++> subrel).\n  Proof.\n    intros p1 p2 Hp ptr1 ptr2 Hptr.\n    destruct Hptr as [b1 ofs1 b2 ofs2 sz Hb].\n    constructor; eauto.\n    revert Hb.\n    apply match_ptr_acc.\n    assumption.\n  Qed.\n\n  Global Instance match_block_acc:\n    Monotonic (match_block R) ((≤) ++> subrel).\n  Proof.\n    intros p1 p2 Hp b1 b2 [delta Hb].\n    transport Hb; subst.\n    eexists; eauto.\n  Qed.\n\n  Global Instance match_block_sameofs_acc:\n    Monotonic (match_block_sameofs R) ((≤) ++> subrel).\n  Proof.\n    intros p1 p2 Hp b1 b2 Hb.\n    transport Hb; subst.\n    eauto.\n  Qed.\n\n  Global Instance match_val_acc:\n    Monotonic (match_val R) ((≤) ++> subrel).\n  Proof.\n    intros p p' Hp x y Hxy.\n    destruct Hxy; constructor; eauto.\n    - rauto.\n    - revert H; rauto.\n  Qed.\n\n  Global Instance match_memval_acc:\n    Monotonic (match_memval R) ((≤) ++> subrel).\n  Proof.\n    intros p p' Hp x y Hxy.\n    destruct Hxy; constructor; eauto.\n    - rauto.\n    - revert H0; rauto.\n  Qed.\n\n  (** *** Functionality *)\n\n  Lemma match_ptr_functional p ptr ptr1 ptr2:\n    match_ptr R p ptr ptr1 ->\n    match_ptr R p ptr ptr2 ->\n    ptr1 = ptr2.\n  Proof.\n    intros [b ofs b1 delta1 Hb1] Hb2'.\n    inversion Hb2' as [xb xofs b2 delta2 Hb2]; clear Hb2'; subst.\n    congruence.\n  Qed.\n\n  Lemma match_ptrbits_functional p ptr ptr1 ptr2:\n    match_ptrbits R p ptr ptr1 ->\n    match_ptrbits R p ptr ptr2 ->\n    ptr1 = ptr2.\n  Proof.\n    intros [b ofs b1 delta1 Hb1] Hb2'.\n    inversion Hb2' as [xb xofs b2 delta2 Hb2]; clear Hb2'; subst.\n    congruence.\n  Qed.\n\n  Lemma match_ptrrange_functional p ptr ptr1 ptr2:\n    match_ptrrange R p ptr ptr1 ->\n    match_ptrrange R p ptr ptr2 ->\n    ptr1 = ptr2.\n  Proof.\n    intros Hptr1 Hptr2.\n    destruct Hptr1 as [b ofs b1 ofs1 sz1 H1].\n    inversion Hptr2 as [xb xofs b2 ofs2 sz2]; clear Hptr2; subst.\n    pose proof (match_ptr_functional p (b, ofs) (b1, ofs1) (b2, ofs2) H1 H).\n    assert (sz1 = sz2).\n    {\n      eapply Z.add_reg_l; eauto.\n    }\n    congruence.\n  Qed.\n\n  Lemma match_block_functional p b b1 b2:\n    match_block R p b b1 ->\n    match_block R p b b2 ->\n    b1 = b2.\n  Proof.\n    intros [d1 Hb1] [d2 Hb2].\n    congruence.\n  Qed.\n\n  Lemma match_block_sameofs_functional p b b1 b2:\n    match_block_sameofs R p b b1 ->\n    match_block_sameofs R p b b2 ->\n    b1 = b2.\n  Proof.\n    unfold match_block_sameofs.\n    congruence.\n  Qed.\n\n  (** *** Shift-invariance *)\n\n  Lemma match_ptr_shift p b1 ofs1 b2 ofs2 delta:\n    match_ptr R p (b1, ofs1) (b2, ofs2) ->\n    match_ptr R p (b1, ofs1 + delta)%Z (b2, ofs2 + delta)%Z.\n  Proof.\n    inversion 1; subst.\n    rewrite <- Z.add_assoc.\n    rewrite (Z.add_comm delta0 delta).\n    rewrite Z.add_assoc.\n    constructor; eauto.\n  Qed.\n\n  Lemma match_ptrbits_shift p b1 ofs1 b2 ofs2 delta:\n    match_ptrbits R p (b1, ofs1) (b2, ofs2) ->\n    match_ptrbits R p (b1, Ptrofs.add ofs1 delta) (b2, Ptrofs.add ofs2 delta).\n  Proof.\n    inversion 1; subst.\n    rewrite Ptrofs.add_assoc.\n    rewrite (Ptrofs.add_commut (Ptrofs.repr _)).\n    rewrite <- Ptrofs.add_assoc.\n    constructor; eauto.\n  Qed.\n\n  Lemma match_ptrrange_shift p b1 ofs1 sz1 b2 ofs2 sz2 delta:\n    match_ptrrange R p (b1, ofs1, sz1) (b2, ofs2, sz2) ->\n    match_ptrrange R p (b1, ofs1 + delta, sz1)%Z (b2, ofs2 + delta, sz2)%Z.\n  Proof.\n    inversion 1; subst.\n    replace (ofs1 + sz)%Z with ((ofs1 + delta) + (sz - delta))%Z by omega.\n    replace (ofs2 + sz)%Z with ((ofs2 + delta) + (sz - delta))%Z by omega.\n    constructor.\n    eapply match_ptr_shift; eauto.\n  Qed.\n\n  (** *** Relationships between [match_foo] relations *)\n\n  (** We call each lemma [match_foo_bar] that establishes [match_bar]\n    from a [match_foo] premise. When this can be done in several ways,\n    we add a suffix to disambiguate. *)\n\n  Lemma add_repr ofs1 delta:\n    Ptrofs.repr (ofs1 + delta) =\n    Ptrofs.add (Ptrofs.repr ofs1) (Ptrofs.repr delta).\n  Proof.\n      rewrite Ptrofs.add_unsigned.\n      auto using Ptrofs.eqm_samerepr,\n      Ptrofs.eqm_add, Ptrofs.eqm_unsigned_repr.\n  Qed.    \n\n  Lemma match_ptr_ptrbits_repr p b1 ofs1 b2 ofs2:\n    match_ptr R p (b1, ofs1) (b2, ofs2) ->\n    match_ptrbits R p (b1, Ptrofs.repr ofs1) (b2, Ptrofs.repr ofs2).\n  Proof.\n    inversion 1; subst.\n    rewrite add_repr.\n    constructor.\n    assumption.\n  Qed.\n\n  Lemma match_ptr_ptrbits_unsigned p b1 ofs1 b2 ofs2:\n    match_ptr R p (b1, Ptrofs.unsigned ofs1) (b2, Ptrofs.unsigned ofs2) ->\n    match_ptrbits R p (b1, ofs1) (b2, ofs2).\n  Proof.\n    intros H.\n    rewrite <- (Ptrofs.repr_unsigned ofs1), <- (Ptrofs.repr_unsigned ofs2).\n    apply match_ptr_ptrbits_repr; eauto.\n  Qed.\n\n  Lemma match_ptr_ptrrange p b1 lo1 hi1 b2 lo2 hi2:\n    match_ptr R p (b1, lo1) (b2, lo2) ->\n    hi1 - lo1 = hi2 - lo2 ->\n    match_ptrrange R p (b1, lo1, hi1) (b2, lo2, hi2).\n  Proof.\n    intros Hlo Hhi.\n    replace hi1 with (lo1 + (hi1 - lo1))%Z by omega.\n    replace hi2 with (lo2 + (hi1 - lo1))%Z by omega.\n    constructor; eauto.\n  Qed.\n\n  Lemma match_ptr_block p b1 ofs1 b2 ofs2:\n    match_ptr R p (b1, ofs1) (b2, ofs2) ->\n    match_block R p b1 b2.\n  Proof.\n    inversion 1.\n    red.\n    eauto.\n  Qed.\n\n  Lemma match_ptr_block_sameofs p b1 b2 ofs:\n    match_ptr R p (b1, ofs) (b2, ofs) ->\n    match_block_sameofs R p b1 b2.\n  Proof.\n    inversion 1.\n    assert (delta = 0) by omega.\n    red.\n    congruence.\n  Qed.\n\n  Lemma match_ptrbits_ptr p m1 m2 b1 o1 b2 o2 pe:\n    match_mem R p m1 m2 ->\n    match_ptrbits R p (b1, o1) (b2, o2) ->\n    Mem.perm m1 b1 (Ptrofs.unsigned o1) Cur pe ->\n    match_ptr R p (b1, Ptrofs.unsigned o1) (b2, Ptrofs.unsigned o2).\n  Proof.\n    intros H H0 H1.\n    inversion H0; subst.\n    erewrite simrel_address_inject; eauto.\n    constructor.\n    assumption.\n  Qed.\n\n  Lemma match_ptrbits_block p b1 ofs1 b2 ofs2:\n    match_ptrbits R p (b1, ofs1) (b2, ofs2) ->\n    match_block R p b1 b2.\n  Proof.\n    inversion 1.\n    red.\n    eauto.\n  Qed.\n\n  Lemma match_ptrrange_ptr p ptr1 hi1 ptr2 hi2:\n    match_ptrrange R p (ptr1, hi1) (ptr2, hi2) ->\n    match_ptr R p ptr1 ptr2.\n  Proof.\n    inversion 1.\n    assumption.\n  Qed.\n\n  Lemma match_block_ptr p b1 b2 ofs1:\n    match_block R p b1 b2 ->\n    exists ofs2, match_ptr R p (b1, ofs1) (b2, ofs2).\n  Proof.\n    intros [delta H].\n    exists (ofs1 + delta)%Z.\n    constructor; eauto.\n  Qed.\n\n  Lemma match_block_ptrbits p b1 b2 ofs1:\n    match_block R p b1 b2 ->\n    exists ofs2, match_ptrbits R p (b1, ofs1) (b2, ofs2).\n  Proof.\n    intros [delta H].\n    exists (Ptrofs.add ofs1 (Ptrofs.repr delta)).\n    constructor; eauto.\n  Qed.\n\n  Lemma match_block_ptrrange p b1 b2 lo1 hi1:\n    match_block R p b1 b2 ->\n    exists lo2 hi2, match_ptrrange R p (b1, lo1, hi1) (b2, lo2, hi2).\n  Proof.\n    intros [delta H].\n    exists (lo1 + delta)%Z, ((lo1 + delta) + (hi1 - lo1))%Z.\n    pattern hi1 at 1.\n    replace hi1 with (lo1 + (hi1 - lo1))%Z by omega.\n    constructor.\n    constructor.\n    assumption.\n  Qed.\n\n  Lemma match_block_sameofs_ptr p b1 ofs1 b2 ofs2:\n    match_block_sameofs R p b1 b2 ->\n    ofs1 = ofs2 ->\n    match_ptr R p (b1, ofs1) (b2, ofs2).\n  Proof.\n    intros Hb Hofs.\n    red in Hb.\n    destruct Hofs.\n    pattern ofs1 at 2.\n    replace ofs1 with (ofs1 + 0)%Z by omega.\n    constructor; eauto.\n  Qed.\n\n  Lemma match_block_sameofs_ptrbits p b1 ofs1 b2 ofs2:\n    match_block_sameofs R p b1 b2 ->\n    ofs1 = ofs2 ->\n    match_ptrbits R p (b1, ofs1) (b2, ofs2).\n  Proof.\n    intros Hb Hofs.\n    red in Hb.\n    destruct Hofs.\n    pattern ofs1 at 2.\n    replace ofs1 with (Ptrofs.add ofs1 (Ptrofs.repr 0%Z)).\n    - constructor; eauto.\n    - change (Ptrofs.repr 0) with Ptrofs.zero.\n      apply Ptrofs.add_zero.\n  Qed.\n\n  Lemma match_block_sameofs_ptrrange p b1 lo1 hi1 b2 lo2 hi2:\n    match_block_sameofs R p b1 b2 ->\n    lo1 = lo2 ->\n    hi1 = hi2 ->\n    match_ptrrange R p (b1, lo1, hi1) (b2, lo2, hi2).\n  Proof.\n    intros Hb Hlo Hhi.\n    red in Hb.\n    subst.\n    eapply match_ptr_ptrrange; eauto.\n    eapply match_block_sameofs_ptr; eauto.\n  Qed.\n\n  Global Instance match_block_sameofs_block p:\n    Related (match_block_sameofs R p) (match_block R p) subrel.\n  Proof.\n    clear.\n    firstorder.\n  Qed.\n\n  (** *** Global blocks *)\n\n  Lemma match_global_ptr p b ofs:\n    block_is_global b ->\n    Monotonic (b, ofs) (match_ptr R p).\n  Proof.\n    intros Hb.\n    eapply match_block_sameofs_ptr; eauto.\n    eapply match_global_block_sameofs; eauto.\n  Qed.\n\n  Lemma match_global_ptrbits p b ofs:\n    block_is_global b ->\n    Monotonic (b, ofs) (match_ptrbits R p).\n  Proof.\n    intros Hb.\n    eapply match_block_sameofs_ptrbits; eauto.\n    eapply match_global_block_sameofs; eauto.\n  Qed.\n\n  Lemma match_global_ptrrange p b lo hi:\n    block_is_global b ->\n    Monotonic (b, lo, hi) (match_ptrrange R p).\n  Proof.\n    intros Hb.\n    eapply match_block_sameofs_ptrrange; eauto.\n    eapply match_global_block_sameofs; eauto.\n  Qed.\n\n  Lemma match_global_block p b:\n    block_is_global b ->\n    Monotonic b (match_block R p).\n  Proof.\n    intros Hb.\n    eapply match_block_sameofs_block.\n    eapply match_global_block_sameofs; eauto.\n  Qed.\n\n  (** *** Miscellaneous *)\n\n  Lemma match_val_weaken_to_undef p v1 v2:\n    simrel_undef_matches_values R ->\n    match_val R p v1 v2 ->\n    match_val R p Vundef v2.\n  Proof.\n    intros HRundef Hv.\n    destruct Hv; try rauto.\n    constructor.\n    eapply simrel_undef_matches_values_also_block; eauto.\n  Qed.\n\n  (** ** Properties of derived memory operations *)\n\n  Global Instance simrel_loadv p:\n    Monotonic\n      Mem.loadv\n      (- ==> match_mem R p ++> match_val R p ++> option_le (match_val R p)).\n  Proof.\n    repeat red.\n    intros a x y H x0 y0 H0.\n    inversion H0; subst; simpl; try now constructor.\n    destruct (Mem.load a x _ (Ptrofs.unsigned _)) eqn:LOAD; try now constructor.\n    rewrite <- LOAD.\n    repeat rstep.\n    eapply match_ptrbits_ptr; eauto.\n    eapply Mem.load_valid_access; eauto.\n    generalize (size_chunk_pos a); omega.\n  Qed.\n\n  Global Instance simrel_loadv_params:\n    Params (@Mem.loadv) 3.\n\n  Global Instance simrel_storev p:\n    Monotonic\n      Mem.storev\n      (- ==> match_mem R p ++> match_val R p ++> match_val R p ++>\n       option_le (incr p (match_mem R p))).\n  Proof.\n    intros a x y H x0 y0 H0 x1 y1 H1.\n    destruct (Mem.storev a x _ _) eqn:STORE; [ | solve_monotonic ].\n    rewrite <- STORE.\n    inversion H0; subst; simpl; try rauto.\n    simpl in * |- *.\n    repeat rstep.\n    eapply match_ptrbits_ptr; eauto.\n    eapply Mem.store_valid_access_3; eauto.\n    generalize (size_chunk_pos a); omega.\n  Qed.\n\n  Global Instance simrel_storev_params:\n    Params (@Mem.storev) 4.\n\n  (** XXX: Use a separate SimGlobalenvs.v ? *)\n  Global Instance genv_find_symbol_match {F V Rf} p:\n    Monotonic\n      (Globalenvs.Genv.find_symbol (F:=F) (V:=V))\n      (genv_le Rf ++> - ==> option_rel (match_block_sameofs R p)).\n  Proof.\n    intros ge1 ge2 Hge i.\n    rewrite !stencil_matches_symbols by eauto.\n    destruct (find_symbol i) eqn:Hi.\n    - constructor.\n      eapply match_global_block_sameofs.\n      eapply find_symbol_block_is_global.\n      eassumption.\n    - constructor.\n  Qed.\n\n  Global Instance genv_find_symbol_match_params:\n    Params (@Globalenvs.Genv.find_symbol) 2.\n\n  (** Maybe it's possible to prove [simrel_storebytes] from [simrel_store]\n    as well. But if it is, it's tricky. *)\n\n  Global Instance simrel_free_list p:\n    Monotonic\n      Mem.free_list\n      (match_mem R p ++> list_rel (match_ptrrange R p) ++>\n       option_le (incr p (match_mem R p))).\n  Proof.\n    intros m1 m2 Hm l1 l2 Hl.\n    revert p l2 Hl m1 m2 Hm.\n    induction l1; inversion 1; subst; simpl; intros.\n    - rauto.\n    - rstep; rstep.\n      rstep; rstep.\n      + rauto.\n      + split_hyp H4. (* XXX: need to update split_hyps to include rel_incr *)\n        (* XXX: for whatever reason Coq needs to be reminded of this ?! *)\n        Existing Instance rel_incr_subrel.\n        exploit IHl1; [ | rauto | ]; try rauto.\n  Qed.\n\n  Global Instance simrel_free_list_params:\n    Params (@Mem.free_list) 2.\n\n  Global Instance mem_valid_pointer_match p:\n    Monotonic\n      Mem.valid_pointer\n      (match_mem R p ++> rel_curry (match_ptr R p ++> Bool.leb)).\n  Proof.\n    intros m1 m2 Hm [b1 ofs1] [b2 ofs2] Hp.\n    simpl.\n    destruct (Mem.valid_pointer m1 b1 ofs1) eqn:Hp1; simpl; eauto.\n    revert Hp1.\n    rewrite !Mem.valid_pointer_nonempty_perm.\n    solve_monotonic.\n  Qed.\n\n  Global Instance mem_valid_pointer_match_params:\n    Params (@Mem.valid_pointer) 3.\n\n  Global Instance mem_weak_valid_pointer_match p:\n    Monotonic\n      Mem.weak_valid_pointer\n      (match_mem R p ++> rel_curry (match_ptr R p ++> Bool.leb)).\n  Proof.\n    intros m1 m2 Hm [b1 ofs1] [b2 ofs2] Hp.\n    simpl.\n    unfold Mem.weak_valid_pointer.\n    repeat rstep.\n    apply match_ptr_shift.\n    assumption.\n  Qed.\n\n  Global Instance mem_weak_valid_pointer_match_params:\n    Params (@Mem.weak_valid_pointer) 3.\n\n  (** ** Strengthened properties for memory operations *)\n\n  Definition ptrrange_perm `{Mem.MemoryModelOps} m k p: relation _ :=\n    lsat (fun r => match r with (b, lo, hi) => Mem.range_perm m b lo hi k p end).\n\n  Global Instance simrel_free_perm p:\n    Monotonic\n      Mem.free\n      (forallr m1 m2 : match_mem R p,\n         % % rel_impl (ptrrange_perm m1 Cur Freeable) (match_ptrrange R p) ==>\n         option_le (incr p (match_mem R p))).\n  Proof.\n    rstep.\n    repeat rstep.\n    destruct x as [[b1 lo1] hi1], y as [[b2 lo2] hi2]; simpl.\n    destruct (Mem.free v1 b1 lo1 hi1) eqn:Hfree; repeat rstep.\n    assert (ptrrange_perm v1 Cur Freeable (b1, lo1, hi1) (b2, lo2, hi2)).\n    {\n      eapply Mem.free_range_perm.\n      eassumption.\n    }\n    rewrite <- Hfree.\n    rauto.\n  Qed.\n\n  (** When pointers are extracted from Compcert [val]ues, they use\n    machine integers and we know related values contain pointers that\n    are related by [match_ptrbits]. Often we then convert this machine\n    pointer with offset [ofs] into an mathematical pointer with offset\n    [Ptrofs.unsigned ofs]. This is made explicit for our block-offset\n    pair pointers using the following function. *)\n\n  Definition ptrofbits (p: block * ptrofs) :=\n    let '(b, ofs) := p in (b, Ptrofs.unsigned ofs).\n\n  (** Unfortunately we can't establish that the results of this\n    process are related by [match_ptr] without proving the side\n    conditions of [match_ptrbits_ptr]. However if the side-conditions\n    can't be proved directly from the context, we can use the relation\n    [match_ptrbits !! ptrofbits] to remember that they were\n    constructed in this way instead.\n\n    For many memory operations this is enough, because the success of\n    whichever memory operation we will use the pointer with will be\n    sufficient to prove the side-conditions for [match_ptrbits_ptr]. *)\n\n  Require Import BoolRel.\n\n  Global Instance match_ptrofbits_rintro p b1 ofs1 b2 ofs2:\n    RIntro\n      (match_ptrbits R p (b1, ofs1) (b2, ofs2))\n      ((match_ptrbits R p) !! ptrofbits)\n      (b1, Ptrofs.unsigned ofs1)\n      (b2, Ptrofs.unsigned ofs2).\n  Proof.\n    intros H.\n    change (b1, Ptrofs.unsigned ofs1) with (ptrofbits (b1, ofs1)).\n    change (b2, Ptrofs.unsigned ofs2) with (ptrofbits (b2, ofs2)).\n    constructor; eauto.\n  Qed.\n\n  Global Instance valid_pointer_match p:\n    Monotonic\n      Mem.valid_pointer\n      (match_mem R p ++> % (match_ptrbits R p) !! ptrofbits ++>\n       flex_leb (simrel_undef_matches_values R)).\n  Proof.\n    intros m1 m2 Hm _ _ [[b1 ofs1] [b2 ofs2] H].\n    simpl.\n    destruct (Mem.valid_pointer m1 _ _) eqn:H1.\n    - assert (match_ptr R p (b1, Ptrofs.unsigned ofs1) (b2, Ptrofs.unsigned ofs2)).\n      {\n        eapply match_ptrbits_ptr; repeat rstep.\n        eapply Mem.valid_pointer_nonempty_perm; eauto.\n      }\n      transport H1.\n      rewrite H1.\n      constructor.\n    - destruct (Mem.valid_pointer m2 _ _) eqn:H2; repeat rstep.\n      constructor.\n      eapply simrel_undef_matches_block_also_values.\n      eapply simrel_undef_matches_block_invalid; eauto.\n  Qed.\n\n  Global Instance weak_valid_pointer_match p:\n    Monotonic\n      Mem.weak_valid_pointer\n      (match_mem R p ++> % (match_ptrbits R p) !! ptrofbits ++>\n       flex_leb (simrel_undef_matches_values R)).\n  Proof.\n    intros m1 m2 Hm _ _ [[b1 ofs1] [b2 ofs2] Hptr].\n    change ((flex_leb (simrel_undef_matches_values R))\n              (Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs1))\n              (Mem.weak_valid_pointer m2 b2 (Ptrofs.unsigned ofs2))).\n    destruct (Mem.weak_valid_pointer m1 _ _) eqn:Hwvp1.\n    - erewrite (simrel_weak_valid_pointer_inject_val p); eauto.\n      constructor.\n    - destruct (Mem.weak_valid_pointer m2 _ _) eqn:Hwbp2.\n      + constructor.\n        eapply simrel_undef_matches_block_also_values.\n        eapply simrel_undef_matches_block_invalid_weak; eauto.\n      + constructor.\n  Qed.\n\n  Global Instance valid_pointer_weaken_match p:\n    Related\n      Mem.valid_pointer\n      Mem.weak_valid_pointer\n      (match_mem R p ++> % (match_ptrbits R p) !! ptrofbits ++> leb).\n  Proof.\n    intros m1 m2 Hm _ _ [[b1 ofs1] [b2 ofs2] H].\n    simpl.\n    transitivity (Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs1)).\n    - unfold Mem.weak_valid_pointer.\n      apply left_upper_bound.\n    - rauto.\n  Qed.\nEnd DEFINITION.\n\n(** We make the memory models involved with a given simulation\n  relation kit explicit. *)\n\nGlobal Arguments simrel_components {_} D1 D2.\nGlobal Arguments simrel {_} D1 D2.\n\n(** We need to make sure those are out of the section so that no\n  arguments are generalized at section exit. *)\n\nGlobal Instance: Params (@simrel_undef_matches_block) 2.\nGlobal Instance: Params (@simrel_meminj) 2.\nGlobal Instance: Params (@match_mem) 3.\nGlobal Instance: Params (@match_ptr) 3.\nGlobal Instance: Params (@match_ptrbits) 3.\nGlobal Instance: Params (@match_ptrrange) 3.\nGlobal Instance: Params (@match_block) 3.\nGlobal Instance: Params (@match_block_sameofs) 3.\nGlobal Instance: Params (@match_val) 3.\nGlobal Instance: Params (@match_memval) 3.\n\n(** Make sure we can use the relationship between\n  [simrel_undef_matches_values] and [simrel_undef_matches_block]\n  during typeclass instance resolution. *)\n\nHint Extern 2 (simrel_undef_matches_block ?R ?p ?b2) =>\n  eapply simrel_undef_matches_values_also_block; eassumption\n  : typeclass_instances.\n\nHint Extern 1 (simrel_undef_matches_values ?R) =>\n  eapply simrel_undef_matches_block_also_values; eassumption\n  : typeclass_instances.\n\n(** Re-register the [simrel_option_le] notation outside of the section. *)\n\nGlobal Notation simrel_option_le R :=\n  (flex_option_le (simrel_undef_matches_values R)).\n\nGlobal Notation simrel_leb R :=\n  (flex_leb (simrel_undef_matches_values R)).\n\n\n(** * Tactics *)\n\n(** Here we define some tactics which may be useful when building up\n  on our simulation relation tookits. *)\n\n(* Inverse hypothese for some relations when the left-hand side has a\n  specific form. For now, we use an ad-hoc tactic, but maybe we could\n  find a way to strengthen the relators associated with [nil], [cons],\n  [Vint], [Vptr], etc. to express the properties used here. *)\n\nLtac inverse_hyps :=\n  repeat\n    lazymatch goal with\n      | H: list_rel ?R (?x :: ?xs) ?yl |- _ =>\n        inversion H; clear H; subst\n      | H: list_rel ?R nil ?yl |- _ =>\n        inversion H; clear H; subst\n      | H: match_val ?R ?p (Vint _) ?y |- _ =>\n        inversion H; clear H; subst\n      | H: match_val ?R ?p (Vlong _) ?y |- _ =>\n        inversion H; clear H; subst\n      | H: match_val ?R ?p (Vfloat _) ?y |- _ =>\n        inversion H; clear H; subst\n      | H: match_val ?R ?p (Vsingle _) ?y |- _ =>\n        inversion H; clear H; subst\n      | H: match_val ?R ?p (Vptr _ _) ?y |- _ =>\n        inversion H; clear H; subst\n    end.\n\n(** Another common need is to solve a goal which consists in [set_rel]\n  used in conjunction with an inductive type. The [deconstruct] tactic\n  destructs a hypothesis [H], and for each generated subgoal passes\n  the corresponding constructor to the continuation k. *)\n\nLtac head m :=\n  lazymatch m with\n    | ?x _ => head x\n    | ?x => constr:(x)\n  end.\n\nLtac deconstruct H k :=\n  let HH := fresh in\n  destruct H eqn:HH;\n  lazymatch type of HH with\n    | _ = ?cc =>\n      let c := head cc in\n      clear HH; k c\n  end.\n\n(** We can use that to build a systematic way to solve goals which\n  related two elements of an inductive type with [set_rel]. Namely,\n  destruct the hypothesis which states the left-hand side is in the\n  set, then for each branch transport all of the premises and apply\n  the same constructor again. *)\n\nLtac solve_set_rel :=\n  lazymatch goal with\n    | |- set_rel _ _ _ =>\n      let H := fresh in\n      let reconstruct c :=\n        idtac \"Using constructor\" c;\n        clear H;\n        split_hyps;\n        inverse_hyps;\n        transport_hyps;\n        try (eexists; split; [eapply c; eauto | repeat rstep]) in\n      intros ? H;\n      deconstruct H reconstruct\n    | |- impl _ _ =>\n      let H := fresh in\n      let reconstruct c :=\n        idtac \"Using constructor\" c;\n        clear H;\n        split_hyps;\n        inverse_hyps;\n        transport_hyps;\n        try (eapply c; eauto) in\n      intros H;\n      deconstruct H reconstruct\n    | |- _ =>\n      intro; solve_set_rel\n  end.\n\n(** This can be useful when [rel_curry] is involved *)\nLtac eexpair :=\n  lazymatch goal with\n    | |- @ex (prod ?T1 ?T2) _ =>\n      let xv := fresh in evar (xv: T1);\n      let x := eval red in xv in clear xv;\n      let yv := fresh in evar (yv: T2);\n      let y := eval red in yv in clear yv;\n      exists (x, y); simpl\n  end.\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/CAL/liblayers/simrel/SimrelDefinition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.2243633810353739}}
{"text": "Require Import Kami.AllNotations.\nRequire Import StdLibKami.RegArray.Ifc.\n\n\nSection Impl.\n  Context {ifcParams: Ifc.Params}.\n\n  Local Notation Idx := (Bit (Nat.log2_up size)).\n\n  Local Open Scope kami_expr.\n  Local Open Scope kami_action.\n\n  Local Definition names := map (fun i => name ++ \"_\" ++ natToHexStr i)%string (seq 0 size).\n\n  Local Definition read ty (idx: ty Idx) : ActionT ty k :=\n   GatherActions (map (fun '(i, reg) => Read val: k <- reg;\n                      Ret (IF ($i == #idx)\n                           then #val else $$(getDefaultConst k))) (tag names)) as vals;\n   Ret (Kor vals).\n\n  Local Definition write ty (writeRq: ty (WriteRq (Nat.log2_up size) k)): ActionT ty Void :=\n    GatherActions (map (fun '(i, reg) => Read val: k <- reg;\n                                         Write reg: k <- (IF $i == #writeRq @% \"addr\" then #writeRq @% \"data\" else #val);\n                                         Retv) (tag names)) as _;\n    Retv.\n\n  Definition impl := {| regs := map (fun i => (i, existT RegInitValT (SyntaxKind k) match init with\n                                                                                    | None => None\n                                                                                    | Some x => Some (SyntaxConst x)\n                                                                                    end)) names;\n                        regFiles := nil;\n                        Ifc.read := read;\n                        Ifc.write := write |}.\nEnd Impl.\n", "meta": {"author": "sifive", "repo": "StdLibKami", "sha": "01d3dffcec9d8bfc4f864b940974396ffe817314", "save_path": "github-repos/coq/sifive-StdLibKami", "path": "github-repos/coq/sifive-StdLibKami/StdLibKami-01d3dffcec9d8bfc4f864b940974396ffe817314/RegArray/Impl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.22428077029380183}}
{"text": "(** * Implementation of Section 4.4 *)\nRequire Import RL.QArithSternBrocot.sqrt2.\nRequire Import RL.Utilities.Rpos.\nRequire Import RL.Utilities.riesz_logic_List_more.\nRequire Import RL.hmr.term.\nRequire Import RL.hmr.hseq.\nRequire Import RL.hmr.hmr.\nRequire Import RL.hmr.semantic.\nRequire Import RL.hmr.interpretation.\nRequire Import RL.hmr.tactics.\nRequire Import RL.hmr.tech_lemmas.\nRequire Import RL.hmr.lambda_prop_tools.\nRequire Import RL.hmr.soundness.\n\nRequire Import Lra.\nRequire Import Lia.\n\nRequire Import RL.OLlibs.List_more.\nRequire Import RL.OLlibs.List_Type.\nRequire Import RL.OLlibs.Permutation_Type_more.\nRequire Import RL.OLlibs.Permutation_Type_solve.\n\nLocal Open Scope R_scope.\n\n(** ** First formulation : A = B implies |- 1.A,1.-B and |- 1.B, 1.-A are derivable *)\n(** Proof of Lemma 4.20 *)\nLemma completeness_1 : forall A B r, A === B -> HMR_M_can (((r, -S B) :: (r, A) :: nil) :: nil)\nwith completeness_2 : forall A B r, A === B -> HMR_M_can (((r, -S A) :: (r, B) :: nil) :: nil).\nProof with try assumption; try reflexivity.\n  - intros A B r Heq; destruct Heq.\n    + change ((r, -S t) :: (r, t) :: nil) with ((vec (r :: nil) (-S t)) ++ (vec (r :: nil) t) ++ nil).\n      apply hmrr_ID_gen...\n      apply hmrr_INIT.\n    + apply hmrr_can with t2 (r :: nil) (r :: nil)...\n      apply hmrr_ex_seq with (((r, -S t2) :: (r, t1) :: nil) ++ ((r, -S t3) :: (r, t2) :: nil)); [ Permutation_Type_solve | ].\n      apply hmrr_M; try reflexivity; [ apply (completeness_1 _ _ _ Heq1) | apply (completeness_1 _ _ _ Heq2)].\n    + revert r; induction c; (try rename r into r0); intros r.\n      * apply completeness_1.\n        apply Heq.\n      * eapply hmrr_ex_seq ; [ apply Permutation_Type_swap | ].\n        apply completeness_2.\n        simpl; rewrite minus_minus; apply Heq.\n      * simpl; change ((r, -S t) :: (r, t) :: nil) with ((vec (r :: nil) (-S t)) ++ (vec (r :: nil) t) ++ nil).\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * simpl.\n        change ((r, HMR_covar n) :: (r, HMR_var n) :: nil) with ((vec (r :: nil) (HMR_covar n)) ++ (vec (r :: nil) (HMR_var n)) ++ nil).\n        apply hmrr_ID...\n        apply hmrr_INIT.\n      * simpl.\n        apply hmrr_ex_seq with ((vec (r :: nil) (HMR_covar n)) ++ (vec (r :: nil) (HMR_var n)) ++ nil) ; [Permutation_Type_solve | ].\n        apply hmrr_ID...\n        apply hmrr_INIT.\n      * simpl.\n        change ((r, HMR_zero) :: (r, HMR_zero) :: nil) with ((vec (r:: r:: nil) HMR_zero) ++ nil).\n        apply hmrr_Z.\n        apply hmrr_INIT.\n      * unfold evalContext; fold evalContext.\n        unfold HMR_minus; fold HMR_minus.\n        apply hmrr_ex_seq with ((vec (r :: nil) (evalContext c1 t1 /\\S evalContext c2 t1)) ++ (vec (r :: nil) (-S evalContext c1 t2 \\/S -S evalContext c2 t2)) ++ nil) ; [ Permutation_Type_solve | ].\n        apply hmrr_min.\n        -- apply hmrr_ex_seq with  ((vec (r :: nil) (-S evalContext c1 t2 \\/S -S evalContext c2 t2)) ++ (vec (r :: nil) (evalContext c1 t1)) ++ nil); [ Permutation_Type_solve | ].\n           apply hmrr_max.\n           apply hmrr_W.\n           apply IHc1.\n        -- apply hmrr_ex_seq with  ((vec (r :: nil) (-S evalContext c1 t2 \\/S -S evalContext c2 t2)) ++ (vec (r :: nil) (evalContext c2 t1)) ++ nil); [ Permutation_Type_solve | ].\n           apply hmrr_max.\n           eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n           apply hmrr_W.\n           eapply hmrr_ex_seq ; [ | apply IHc2].\n           Permutation_Type_solve.\n      * unfold evalContext; fold evalContext.\n        unfold HMR_minus; fold HMR_minus.\n        change ((r, -S evalContext c1 t2 /\\S -S evalContext c2 t2)\n                  :: (r, evalContext c1 t1 \\/S evalContext c2 t1) :: nil) with\n            ((vec (r ::nil) (-S evalContext c1 t2 /\\S -S evalContext c2 t2)) ++ (vec (r ::nil) (evalContext c1 t1 \\/S evalContext c2 t1)) ++ nil).\n        apply hmrr_min.\n        -- apply hmrr_ex_seq with  ((vec (r :: nil) (evalContext c1 t1 \\/S evalContext c2 t1)) ++ (vec (r :: nil) (-S evalContext c1 t2)) ++ nil); [ Permutation_Type_solve | ].\n           apply hmrr_max.\n           apply hmrr_W.\n           eapply hmrr_ex_seq ; [ | apply IHc1].\n           Permutation_Type_solve.\n        -- apply hmrr_ex_seq with  ((vec (r :: nil) (evalContext c1 t1 \\/S evalContext c2 t1)) ++ (vec (r :: nil) (-S evalContext c2 t2)) ++ nil); [ Permutation_Type_solve | ].\n           apply hmrr_max.\n           eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n           apply hmrr_W.\n           eapply hmrr_ex_seq ; [ | apply IHc2].\n           Permutation_Type_solve.\n      * unfold evalContext; fold evalContext; unfold HMR_minus; fold HMR_minus.\n        change ((r, (-S evalContext c1 t2) -S (evalContext c2 t2))\n                  :: (r, evalContext c1 t1 +S evalContext c2 t1) :: nil)\n          with ((vec (r :: nil) ((-S evalContext c1 t2) -S (evalContext c2 t2))) ++ (vec (r :: nil) (evalContext c1 t1 +S evalContext c2 t1)) ++ nil).\n        apply hmrr_plus.\n        apply hmrr_ex_seq with (vec (r :: nil) (evalContext c1 t1 +S evalContext c2 t1) ++\n                               vec (r :: nil) (-S evalContext c1 t2) ++\n                               vec (r :: nil) (-S evalContext c2 t2) ++ nil) ; [ Permutation_Type_solve | ].\n        apply hmrr_plus.\n        apply hmrr_ex_seq with (((r, -S evalContext c1 t2) :: (r, evalContext c1 t1) :: nil) ++ ((r, -S evalContext c2 t2) :: (r, evalContext c2 t1) :: nil)) ; [ Permutation_Type_solve | ].\n        apply hmrr_M; try reflexivity; [ apply IHc1 | apply IHc2].\n      * unfold evalContext; fold evalContext; unfold HMR_minus; fold HMR_minus.\n        change ((r, r0 *S (-S evalContext c t2)) :: (r, r0 *S evalContext c t1) :: nil) with ((vec (r :: nil) (r0 *S (-S evalContext c t2))) ++ (vec (r :: nil) (r0 *S evalContext c t1)) ++ nil).\n        apply hmrr_mul.\n        apply hmrr_ex_seq with (vec (r :: nil) (r0 *S evalContext c t1) ++ vec (mul_vec r0 (r :: nil)) (-S evalContext c t2) ++  nil) ; [ Permutation_Type_solve | ].\n        apply hmrr_mul.\n        simpl.\n        eapply hmrr_ex_seq; [ | apply IHc].\n        Permutation_Type_solve.\n      * simpl.\n        change ((r, HMR_coone) :: (r, HMR_one) :: nil) with (vec (r :: nil) HMR_coone ++ vec (r :: nil) HMR_one ++ nil).\n        apply hmrr_one; [ | apply hmrr_INIT].\n        simpl; nra.\n      * eapply hmrr_ex_seq;  [ apply Permutation_Type_swap | ].\n        simpl.\n        change ((r, HMR_coone) :: (r, HMR_one) :: nil) with (vec (r :: nil) HMR_coone ++ vec (r :: nil) HMR_one ++ nil).\n        apply hmrr_one; [ | apply hmrr_INIT].\n        simpl; nra.\n      * simpl in *.\n        change ((r, <S> (-S evalContext c t2)) :: (r, <S> evalContext c t1) :: nil) with (seq_diamond ((r , (-S evalContext c t2)) :: (r , evalContext c t1) :: nil)).\n        apply hmrr_diamond_no_one.\n        apply IHc.\n    + apply (completeness_2 _ _ _ Heq).\n    + replace (((r, -S subs t2 n t) :: (r, subs t1 n t) :: nil) :: nil) with (subs_hseq (((r, -S t2) :: (r, t1) :: nil) :: nil) n t) by now rewrite <-eq_subs_minus.\n      apply subs_proof.\n      apply completeness_1; apply Heq.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can. do_HMR_logical.\n      apply hmrr_ex_seq with ((vec (r :: nil) (-S t1)) ++ (vec (r :: nil) (t1)) ++ (vec (r :: nil) (-S t2)) ++ (vec (r :: nil) (t2)) ++ (vec (r :: nil) (-S t3)) ++ (vec (r :: nil) (t3)) ++ nil); [ Permutation_Type_solve | ].\n      do 3 (apply hmrr_ID_gen; try reflexivity).\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with ((vec (r :: nil) (-S t1)) ++ (vec (r :: nil) (t1)) ++ (vec (r :: nil) (-S t2)) ++ (vec (r :: nil) (t2)) ++ nil); [ Permutation_Type_solve | ].\n      do 2 (apply hmrr_ID_gen; try reflexivity).\n      apply hmrr_INIT.\n    + unfold HMR_M_can; do_HMR_logical.\n      pattern t at 1; rewrite <- minus_minus.\n      apply hmrr_ID_gen...\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      pattern t at 1; rewrite <-(minus_minus t).\n      rewrite<- ? app_assoc; apply hmrr_ID_gen...\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      unfold mul_vec.\n      apply hmrr_ex_seq with ((vec ((time_pos (minus_pos Hlt) r) ::(time_pos b r) :: nil) (-S t)) ++ (vec ((time_pos a r) :: nil) t) ++ nil); [ Permutation_Type_solve | ].\n      apply hmrr_ID_gen ; [ | apply hmrr_INIT ].\n      simpl; destruct a; destruct b; destruct r; unfold minus_pos.\n      simpl; nra.\n    + pattern t at 2; rewrite <- minus_minus.\n      apply hmrr_ex_seq with ((vec (r :: nil) (One *S (-S (-S t)))) ++ (vec (r :: nil) (-S t)) ++ nil); [ Permutation_Type_solve | ].\n      apply hmrr_mul.\n      apply hmrr_ID_gen; [ destruct r; simpl; nra | apply hmrr_INIT].\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      pattern t at 1; rewrite <- minus_minus.\n      apply hmrr_ID_gen ; [ | apply hmrr_INIT].\n      destruct r; destruct x; destruct y; simpl.\n      nra.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with ((vec (mul_vec x (r :: nil)) (-S t1)) ++ (vec (mul_vec x (r :: nil)) ( t1)) ++ (vec (mul_vec x (r :: nil)) (-S t2))++ (vec (mul_vec x (r :: nil)) (t2)) ++ nil) ; [ Permutation_Type_solve | ].\n      do 2 (apply hmrr_ID_gen; try reflexivity).\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      unfold mul_vec.\n      apply hmrr_ex_seq with ((vec ((time_pos x r) :: (time_pos y r) :: nil) (-S t)) ++ (vec (time_pos (plus_pos x y) r :: nil) t) ++ nil) ; [ Permutation_Type_solve | ].\n      apply hmrr_ID_gen; [ | apply hmrr_INIT].\n      destruct r; destruct x; destruct y; unfold plus_pos; simpl; nra.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ID_gen ; [ | apply hmrr_INIT].\n      simpl; nra.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W; apply hmrr_W.\n        pattern t1 at 1; rewrite <- (minus_minus).\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        pattern t2 at 1; rewrite <- (minus_minus).\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | apply hmrr_W ; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | apply hmrr_W]].\n        pattern t3 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        pattern t2 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        pattern t1 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W.\n        pattern t1 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        pattern t1 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * pattern t1 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        pattern t1 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W.\n        rewrite <- app_assoc.\n        apply hmrr_ID_gen...\n        pattern t3 at 1; rewrite<- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        rewrite <-app_assoc; apply hmrr_ID_gen...\n        pattern t3 at 1; rewrite<- minus_minus; apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        rewrite <-app_assoc; apply hmrr_ID_gen...\n        pattern t3 at 1; rewrite<- minus_minus; apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_INIT.\n      * simpl.\n        eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n        apply hmrr_W.\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      change (vec (r :: nil) (<S> (-S t1)) ++ vec (r :: nil) (<S> (-S t2)) ++ vec (r :: nil) (<S> (t1 +S t2)) ++ nil)\n        with\n          (seq_diamond (vec (r :: nil) (-S t1) ++ vec (r :: nil) (-S t2) ++ vec (r :: nil) (t1 +S t2) ++ nil)).\n      apply hmrr_diamond_no_one.\n      do_HMR_logical.\n      apply hmrr_ex_seq with (vec (r :: nil) (-S t2) ++ vec (r :: nil) t2 ++ vec (r :: nil) (-S t1) ++ vec (r :: nil) t1 ++ nil); [ Permutation_Type_solve | ].\n      apply hmrr_ID_gen; try reflexivity.\n      apply hmrr_ID_gen; try reflexivity.\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      change (vec (mul_vec r0 (r :: nil)) (<S> (-S t)) ++ vec (r :: nil) (<S> (r0 *S t)) ++ nil)\n        with\n          (seq_diamond (vec (mul_vec r0 (r :: nil)) (-S t) ++ vec (r :: nil) (r0 *S t) ++ nil)).\n      apply hmrr_diamond_no_one.\n      do_HMR_logical.\n      pattern t at 1.\n      rewrite <- minus_minus.\n      apply hmrr_ID_gen; try reflexivity.\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * change (<S> HMR_one) with (-S (<S> HMR_coone)).\n        apply hmrr_ID_gen; try reflexivity.\n        apply hmrr_INIT.\n      * rewrite app_nil_r.\n        change (vec (r :: nil) HMR_one ++ vec (r :: nil) (<S> HMR_coone))\n          with\n            (vec nil HMR_coone ++ vec (r :: nil) HMR_one ++ seq_diamond (vec (r :: nil) (HMR_coone))).\n        apply hmrr_diamond.\n        { destruct r as [r Hr]; simpl; apply R_blt_lt in Hr; nra. }\n        change HMR_one with (-S HMR_coone).\n        rewrite app_nil_l; rewrite <- (app_nil_r (vec (r :: nil) HMR_coone)).\n        apply hmrr_ID_gen; try reflexivity.\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical ; try apply hmrr_INIT.\n      change (vec (r :: nil) (<S> pos t) ++ nil) with (seq_diamond (vec (r :: nil) (pos t) ++ nil)).\n      apply hmrr_diamond_no_one.\n      do_HMR_logical; simpl.\n      eapply hmrr_ex_hseq;  [ apply Permutation_Type_swap | ].\n      apply hmrr_W.\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical ; try apply hmrr_INIT.\n      change (vec (r :: nil) HMR_one ++ nil)\n        with (vec nil HMR_coone ++ vec (r :: nil) HMR_one ++ nil).\n      apply hmrr_one; try apply hmrr_INIT.\n      destruct r as [r Hr]; simpl.\n      apply R_blt_lt in Hr; nra.\n  - intros A B r Heq; destruct Heq.\n    + unfold HMR_M_can; HMR_to_vec.\n      apply hmrr_ID_gen...\n      apply hmrr_INIT.\n    + apply hmrr_can with t2 (r :: nil) (r :: nil)...\n      apply hmrr_ex_seq with (((r, -S t1) :: (r, t2) :: nil) ++ ((r, -S t2) :: (r, t3) :: nil)); [ Permutation_Type_solve | ].\n      apply hmrr_M; try reflexivity; [ apply (completeness_2 _ _ _ Heq1) | apply (completeness_2 _ _ _ Heq2)].\n    + revert r;induction c; try (rename r into r0); intros r.\n      * apply completeness_2.\n        apply Heq.\n      * eapply hmrr_ex_seq ; [ apply Permutation_Type_swap | ].\n        apply completeness_1.\n        simpl; rewrite minus_minus; apply Heq.\n      * unfold HMR_M_can; simpl; HMR_to_vec.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * simpl; unfold HMR_M_can; HMR_to_vec.\n        apply hmrr_ID...\n        apply hmrr_INIT.\n      * simpl.\n        apply hmrr_ex_seq with ((vec (r :: nil) (HMR_covar n)) ++ (vec (r :: nil) (HMR_var n)) ++ nil) ; [Permutation_Type_solve | ].\n        apply hmrr_ID...\n        apply hmrr_INIT.\n      * simpl.\n        unfold HMR_M_can; do_HMR_logical.\n        apply hmrr_INIT.\n      * unfold evalContext; fold evalContext.\n        unfold HMR_minus; fold HMR_minus.\n        unfold HMR_M_can; do_HMR_logical.\n        -- apply hmrr_W.\n           apply IHc1.\n        -- eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W; apply IHc2.\n      * unfold evalContext; fold evalContext.\n        unfold HMR_minus; fold HMR_minus.\n        unfold HMR_M_can; do_HMR_logical.\n        -- apply hmrr_W.\n           simpl; eapply hmrr_ex_seq ; [ apply Permutation_Type_swap | ].\n           apply IHc1.\n        -- eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n           eapply hmrr_ex_seq ; [ apply Permutation_Type_swap | ].\n           apply IHc2.\n      * simpl. unfold HMR_M_can; do_HMR_logical.\n        apply hmrr_ex_seq with (((r, -S evalContext c1 t1) :: (r, evalContext c1 t2) :: nil) ++ ((r, -S evalContext c2 t1) :: (r, evalContext c2 t2) :: nil)) ; [ Permutation_Type_solve | ].\n        apply hmrr_M; try reflexivity; [apply IHc1 | apply IHc2].\n      * simpl; unfold HMR_M_can; do_HMR_logical.\n        apply IHc.\n      * simpl.\n        change ((r, HMR_coone) :: (r, HMR_one) :: nil) with (vec (r :: nil) HMR_coone ++ vec (r :: nil) HMR_one ++ nil).\n        apply hmrr_one; [ | apply hmrr_INIT].\n        simpl; nra.\n      * eapply hmrr_ex_seq;  [ apply Permutation_Type_swap | ].\n        simpl.\n        change ((r, HMR_coone) :: (r, HMR_one) :: nil) with (vec (r :: nil) HMR_coone ++ vec (r :: nil) HMR_one ++ nil).\n        apply hmrr_one; [ | apply hmrr_INIT].\n        simpl; nra.\n      * simpl in *.\n        change ((r, <S> (-S evalContext c t1)) :: (r, <S> evalContext c t2) :: nil) with (seq_diamond ((r , (-S evalContext c t1)) :: (r , evalContext c t2) :: nil)).\n        apply hmrr_diamond_no_one.\n        apply IHc.\n    + apply (completeness_1 _ _ _ Heq).\n    + replace (((r, -S subs t1 n t) :: (r, subs t2 n t) :: nil) :: nil) with (subs_hseq (((r, -S t1) :: (r, t2) :: nil) :: nil) n t) by now rewrite <-eq_subs_minus.\n      apply subs_proof.\n      apply completeness_2; apply Heq.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with ((vec (r :: nil) (-S t1)) ++ (vec (r :: nil) (t1)) ++ (vec (r :: nil) (-S t2)) ++ (vec (r :: nil) (t2)) ++ (vec (r :: nil) (-S t3)) ++ (vec (r :: nil) (t3)) ++ nil); [ Permutation_Type_solve | ].\n      do 3 (apply hmrr_ID_gen; try reflexivity).\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with ((vec (r :: nil) (-S t1)) ++ (vec (r :: nil) (t1)) ++ (vec (r :: nil) (-S t2)) ++ (vec (r :: nil) (t2)) ++ nil); [ Permutation_Type_solve | ].\n      do 2 (apply hmrr_ID_gen; try reflexivity).\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ID_gen...\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      rewrite minus_minus.\n      rewrite<- ? app_assoc; apply hmrr_ID_gen...\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      unfold mul_vec.\n      rewrite minus_minus.\n      apply hmrr_ex_seq with ((vec (time_pos a r :: nil) (-S t)) ++ (vec (time_pos (minus_pos Hlt) r :: time_pos b r :: nil) t) ++ nil); [ Permutation_Type_solve | ].\n      apply hmrr_ID_gen ; [ | apply hmrr_INIT ].\n      destruct r; destruct a; destruct b; unfold minus_pos.\n      simpl; nra.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ID_gen; [ | apply hmrr_INIT].\n      destruct r; simpl; nra.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ID_gen ; [ | apply hmrr_INIT].\n      destruct r; destruct x; destruct y; simpl.\n      nra.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with ((vec (mul_vec x (r :: nil)) (-S t1)) ++ (vec (mul_vec x (r :: nil)) ( t1)) ++ (vec (mul_vec x (r :: nil)) (-S t2))++ (vec (mul_vec x (r :: nil)) (t2)) ++ nil) ; [ Permutation_Type_solve | ].\n      do 2 (apply hmrr_ID_gen; try reflexivity).\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      unfold mul_vec.\n      apply hmrr_ex_seq with ((vec (time_pos (plus_pos x y) r :: nil) (-S t)) ++ (vec (time_pos x r :: time_pos y r :: nil) t) ++ nil) ; [ Permutation_Type_solve | ].\n      apply hmrr_ID_gen; [ | apply hmrr_INIT].\n      destruct r; destruct x; destruct y; unfold plus_pos; simpl; nra.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ID_gen ; [ | apply hmrr_INIT].\n      simpl; nra.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        pattern t1 at 1; rewrite <- (minus_minus).\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | apply hmrr_W ; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | apply hmrr_W]].\n        pattern t2 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W; apply hmrr_W.\n        pattern t3 at 1; rewrite <- (minus_minus).\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        pattern t1 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        pattern t2 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W; apply hmrr_W.\n        apply hmrr_ex_seq with ((vec (r :: nil) (-S t1)) ++ (vec (r :: nil) t1) ++ (vec (r :: nil) (-S t3)) ++ (vec (r :: nil) t3) ++ nil); [ Permutation_Type_solve | ].\n        apply hmrr_ID_gen...\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ex_seq with ((vec (r :: nil) (-S t2)) ++ (vec (r :: nil) t2) ++ (vec (r :: nil) (-S t3)) ++ (vec (r :: nil) t3) ++ nil); [ Permutation_Type_solve | ].\n        apply hmrr_ID_gen...\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      simpl.\n      eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n      apply hmrr_W.\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with (seq_diamond (vec (r :: nil) ((-S t1) -S t2) ++ vec (r :: nil) t1 ++ vec (r :: nil) t2 ++ nil)) ; [ Permutation_Type_solve | ].\n      apply hmrr_diamond_no_one.\n      apply hmrr_plus.\n      apply hmrr_ex_seq with (vec (r :: nil) (-S t2) ++ vec (r :: nil) t2 ++ vec (r :: nil) (-S t1) ++ vec (r :: nil) t1 ++ nil) ; [ Permutation_Type_solve | ].\n      apply hmrr_ID_gen; try reflexivity.\n      apply hmrr_ID_gen; try reflexivity.\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with (seq_diamond (vec (r :: nil) (r0 *S (-S t)) ++ vec (mul_vec r0 (r :: nil)) t ++ nil)); [Permutation_Type_solve | ].\n      apply hmrr_diamond_no_one; apply hmrr_mul.\n      apply hmrr_ID_gen; try reflexivity.\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_W.\n      change (vec (r :: nil) (<S> HMR_coone) ++ vec (r :: nil) (<S> HMR_one) ++ nil)\n        with (seq_diamond (vec (r :: nil) HMR_coone ++ vec (r :: nil) HMR_one ++ nil)).\n      apply hmrr_diamond_no_one.\n      apply hmrr_one; simpl; try nra.\n      apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      simpl.\n      eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ].\n      apply hmrr_W; apply hmrr_INIT.\n    + unfold HMR_minus; fold HMR_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      simpl.\n      eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ].\n      apply hmrr_W.\n      apply hmrr_INIT.\nQed.\n\n(** ** Second formulation *)\n(** We use the can rule and the M rule to go from a proof |- 1.G to a proof of G *)\nLemma HMR_sem_seq P : forall G T D,\n    HMR P (((One, sem_seq T) :: D) :: G) ->\n    HMR (hmr_frag_add_CAN (hmr_frag_add_M P)) ((T ++ D) :: G).\nProof.\n  intros G T; revert P G; induction T; intros P G D pi.\n  - simpl in *.\n    apply hmrr_Z_can_inv with (One :: nil).\n    apply HMR_le_frag with P; [ | apply pi].\n    apply add_M_le_frag.\n  - destruct a as (a , A).\n    simpl in *.\n    apply hmrr_ex_seq with (T ++ (a , A) :: D); [ Permutation_Type_solve | ].\n    apply (IHT (hmr_frag_add_CAN (hmr_frag_add_M (hmr_frag_add_CAN (hmr_frag_add_M P))))).\n    replace a with (time_pos a One) by (destruct a; unfold One; apply Rpos_eq; simpl; nra).\n    apply hmrr_ex_seq with ((vec (mul_vec a (One :: nil)) A) ++ (vec (One :: nil) (sem_seq T)) ++ D) ; [ Permutation_Type_solve | ].\n    apply hmrr_mul_can_inv.\n    apply hmrr_plus_can_inv.\n    apply pi.\nQed.\n\nLemma HMR_sem_hseq P : forall G H,\n    H <> nil ->\n    HMR P (((One, sem_hseq H) :: nil) :: G) ->\n    HMR (hmr_frag_add_CAN (hmr_frag_add_M P)) (H ++ G).\nProof with try assumption; try reflexivity.\n  intros G H Hnnil; revert P G.\n  induction H; [ now auto | ].\n  rename a into T.\n  intros P G pi.\n  destruct H as [ | T2 H ].\n  - simpl in *.\n    replace T with (T ++ nil) by now rewrite app_nil_r.\n    apply HMR_sem_seq...\n  - unfold sem_hseq in pi; fold (sem_hseq (T2 :: H)) in pi.\n    change ((One, sem_seq T \\/S sem_hseq (T2 :: H)) :: nil) with ((vec (One :: nil) (sem_seq T \\/S sem_hseq (T2 :: H))) ++ nil) in pi.\n    apply hmrr_max_can_inv in pi.\n    apply hmrr_ex_hseq with ((T2 :: H) ++ (T :: G)); [ Permutation_Type_solve | ].\n    apply HMR_le_frag with (hmr_frag_add_CAN (hmr_frag_add_M (hmr_frag_add_CAN (hmr_frag_add_M (hmr_frag_add_CAN (hmr_frag_add_M P)))))).\n    { destruct P; repeat split; Bool.destr_bool. }\n    refine (IHlist _ (hmr_frag_add_CAN (hmr_frag_add_M (hmr_frag_add_CAN (hmr_frag_add_M P)))) (T :: G) _) ; [ now auto | ].\n    apply hmrr_ex_hseq with (T :: ((One , sem_hseq (T2 :: H)) :: nil) :: G) ; [ Permutation_Type_solve | ].\n    replace T with (T ++ nil) by now rewrite app_nil_r.\n    apply HMR_sem_seq.\n    eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n    apply pi.\nQed.\n\n(** Proof of the completeness of the system of HMR - hmr_complete return a T free proof of G *)\nLemma hmr_complete : forall G,\n    G <> nil ->\n    HMR_zero <== sem_hseq G ->\n    HMR_M_can G.\nProof with try assumption.\n  intros G Hnnil Hleq.\n  assert (pi := completeness_1 _ _ One Hleq).\n  replace G with (G ++ nil) by now rewrite app_nil_r.\n  apply (@HMR_sem_hseq hmr_frag_M_can)...\n  change ((One , sem_hseq G) :: nil) with ((vec (One :: nil) (sem_hseq G)) ++ nil).\n  apply (@hmrr_min_can_inv_r hmr_frag_M_can) with HMR_zero.\n  apply (@hmrr_Z_can_inv hmr_frag_M_can) with (One :: nil)...\nQed.\n\n(** Proof of Lemma 4.23 *)\n\n(** Proof of Lemma 4.24 *)\nLemma int_lambda_prop :\n  forall G,\n    hseq_is_basic G ->\n    HMR_M G ->\n    { L &\n      prod (length L = length G)\n           ((Exists_inf (fun x => x <> 0%nat) L) *\n            (forall n, sum_weight_with_coeff n G (map nat_oRpos L) = 0) *\n            (0 <= sum_weight_with_coeff_one G (map nat_oRpos L)) *\n            (HMR_M ((concat_with_coeff_copy (only_diamond_hseq G) L) :: nil)))}.\nProof.\n  intros G Ha pi.\n  induction pi.\n  - split with (1%nat :: nil).\n    repeat split; try reflexivity.\n    + apply Exists_inf_cons_hd.\n      intros H; inversion H.\n    + intros n.\n      simpl; nra.\n    + simpl; nra.\n    + apply hmrr_INIT.\n  - inversion Ha; subst.\n    destruct (IHpi X0) as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    split with (0%nat :: L).\n    repeat split; auto.\n    + simpl; rewrite Hlen; reflexivity.\n  - inversion Ha; subst.\n    destruct IHpi as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    { apply Forall_inf_cons ;[ | apply Forall_inf_cons]; try assumption. }\n    destruct L; [ | destruct L]; try now inversion Hlen.\n    split with ((n + n0)%nat :: L).\n    repeat split; auto.\n    + inversion Hex; subst.\n      * apply Exists_inf_cons_hd.\n        destruct n; destruct n0; intros H; inversion H.\n        apply H0; reflexivity.\n      * inversion X1; subst; auto.\n        apply Exists_inf_cons_hd.\n        destruct n0 ; [ exfalso; apply H0; reflexivity | ].\n        destruct n; intros H; inversion H.\n    + intros n1.\n      specialize (Hsum n1).\n      simpl; simpl in Hsum.\n      destruct n; destruct n0; simpl in *; try rewrite Nat.add_0_r; try nra.\n      rewrite Nat.add_succ_r.\n      rewrite <- S_INR.\n      replace ((S(S (n + n0)))%nat) with (((S n) + (S n0))%nat) by lia.\n      rewrite plus_INR.\n      simpl; nra.\n    + simpl; simpl in Hone.\n      destruct n; destruct n0; simpl in *; try rewrite Nat.add_0_r; try nra.\n      rewrite Nat.add_succ_r.\n      rewrite <- S_INR.\n      replace ((S(S (n + n0)))%nat) with (((S n) + (S n0))%nat) by lia.\n      rewrite plus_INR.\n      simpl; nra.\n    + simpl in Hind |- *.\n      rewrite ? copy_seq_plus; simpl.\n      eapply hmrr_ex_seq ; [ | apply Hind].\n      Permutation_Type_solve.      \n  - inversion Ha; inversion X0; subst.\n    destruct IHpi as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    { apply Forall_inf_cons; try assumption.\n      apply seq_basic_app; assumption. }\n    destruct L; try now inversion Hlen.\n    split with (n :: n :: L).\n    repeat split; auto.\n    + simpl in *; rewrite Hlen; reflexivity.\n    + intro n1.\n      specialize (Hsum n1).\n      simpl; simpl in Hsum.\n      destruct n;\n        unfold nat_oRpos in *; fold nat_oRpos in *;\n          unfold INRpos in *; unfold projT1 in *; rewrite ? S_INR in *;\n            try rewrite sum_weight_seq_var_app in Hsum;\n            try rewrite sum_weight_seq_covar_app in Hsum;\n            try nra.\n    + simpl; simpl in Hone.\n      destruct n;\n        unfold nat_oRpos in *; fold nat_oRpos in *;\n          unfold INRpos in *; unfold projT1 in *; rewrite ? S_INR in *;\n            try rewrite sum_weight_seq_one_app in Hone;\n            try rewrite sum_weight_seq_coone_app in Hone;\n            try nra.\n    + simpl in Hind |- *.\n      rewrite only_diamond_seq_app in Hind.\n      eapply hmrr_ex_seq ; [ | apply Hind].\n      rewrite app_assoc.\n      apply Permutation_Type_app ; [ | reflexivity].\n      apply copy_seq_app.\n  - inversion Ha; subst.\n    destruct IHpi1 as [L1 [Hlen1 [[[Hex1 Hsum1] Hone1] Hind1]]].\n    { apply Forall_inf_cons ; [ apply seq_basic_app_inv_l with T2 | ]; try assumption. }\n    destruct L1; try now inversion Hlen1.\n    destruct n.\n    { split with (0%nat :: L1).\n      repeat split; auto. }\n    destruct IHpi2 as [L2 [Hlen2 [[[Hex2 Hsum2] Hone2] Hind2]]].\n    { apply Forall_inf_cons ; [ apply seq_basic_app_inv_r with T1 | ]; try assumption. }\n    destruct L2; try now inversion Hlen2.\n    destruct n0.\n    { split with (0%nat :: L2).\n      repeat split; auto. }\n    split with ((S n * S n0)%nat :: add_nat_list (map (Nat.mul (S n0)) L1) (map (Nat.mul (S n)) L2)).\n    repeat split; auto.\n    + simpl in Hlen1, Hlen2; simpl.\n      rewrite add_nat_list_length ; [ rewrite map_length; assumption | ].\n      rewrite 2 map_length.\n      lia.\n    + apply Exists_inf_cons_hd.\n      intros H; inversion H.\n    + intros n'; specialize (Hsum1 n'); specialize (Hsum2 n'); simpl in Hsum1, Hsum2.\n      change (match n with\n              | 0%nat => 1\n              | S _ => INR n + 1\n              end) with (INR (S n)) in Hsum1.\n      change (match n0 with\n              | 0%nat => 1\n              | S _ => INR n0 + 1\n              end) with (INR (S n0)) in Hsum2.\n      simpl.\n      rewrite sum_weight_seq_var_app; rewrite sum_weight_seq_covar_app.\n      rewrite sum_weight_with_coeff_add_nat_list ; [ | simpl in Hlen1, Hlen2; simpl; rewrite 2 map_length; lia].\n      change (match (n0 + n * S n0)%nat with\n              | 0%nat => 1\n              | S _ => INR (n0 + n * S n0) + 1\n              end) with (INR ((S n) * (S n0))).\n      change (fun m : nat => (m + n0 * m)%nat) with (Nat.mul (S n0)).\n      change (fun m : nat => (m + n * m)%nat) with (Nat.mul (S n)).\n      rewrite mult_INR.\n      rewrite 2 sum_weight_with_coeff_mul_nat_list.\n      nra.\n    + simpl in Hone1, Hone2.\n      change (match n with\n              | 0%nat => 1\n              | S _ => INR n + 1\n              end) with (INR (S n)) in Hone1.\n      change (match n0 with\n              | 0%nat => 1\n              | S _ => INR n0 + 1\n              end) with (INR (S n0)) in Hone2.\n      simpl.\n      rewrite sum_weight_seq_one_app; rewrite sum_weight_seq_coone_app.\n      rewrite sum_weight_with_coeff_one_add_nat_list ; [ | simpl in Hlen1, Hlen2; simpl; rewrite 2 map_length; lia].\n      change (match (n0 + n * S n0)%nat with\n              | 0%nat => 1\n              | S _ => INR (n0 + n * S n0) + 1\n              end) with (INR ((S n) * (S n0))).\n      change (fun m : nat => (m + n0 * m)%nat) with (Nat.mul (S n0)).\n      change (fun m : nat => (m + n * m)%nat) with (Nat.mul (S n)).\n      rewrite mult_INR.\n      rewrite 2 sum_weight_with_coeff_one_mul_nat_list.\n      assert (0 < INR (S n)) by apply INR_S_n_pos.\n      assert (0 < INR (S n0)) by apply INR_S_n_pos.\n      nra.\n    + simpl only_diamond_hseq; simpl concat_with_coeff_copy in *.\n      change (copy_seq (n0 + n * S n0) (only_diamond_seq (T1 ++ T2)) ++ only_diamond_seq (T1 ++ T2))\n             with (copy_seq ((S n) * (S n0)) (only_diamond_seq (T1 ++ T2))).\n      rewrite only_diamond_seq_app.\n      eapply hmrr_ex_seq ; [ apply Permutation_Type_app ; [ symmetry; apply copy_seq_app | reflexivity] | ].\n      rewrite <- (copy_seq_twice (only_diamond_seq T2)).\n      replace ((S n * S n0)%nat) with ((S n0 * S n)%nat) by lia.\n      rewrite <- copy_seq_twice.\n      apply hmrr_ex_seq with ((concat_with_coeff_copy (only_diamond_hseq G) (add_nat_list (map (Nat.mul (S n0)) L1) (map (Nat.mul (S n)) L2))) ++ (copy_seq (S n0) (copy_seq (S n) (only_diamond_seq T1)) ++ copy_seq (S n) (copy_seq (S n0) (only_diamond_seq T2)))) ; [ Permutation_Type_solve | ].\n      eapply hmrr_ex_seq ; [ apply Permutation_Type_app ; [ symmetry; apply concat_with_coeff_copy_add_nat_list_perm | reflexivity] | ].\n      { rewrite ? map_length; simpl in *; lia. }\n      eapply hmrr_ex_seq ; [ apply Permutation_Type_app ; [ apply Permutation_Type_app; symmetry; apply concat_with_coeff_copy_mul_nat_list | reflexivity]  | ].\n      apply hmrr_ex_seq with (copy_seq (S n) (copy_seq (S n0) (only_diamond_seq T2) ++ (concat_with_coeff_copy (only_diamond_hseq G) L2)) ++ copy_seq (S n0) (copy_seq (S n) (only_diamond_seq T1) ++ (concat_with_coeff_copy (only_diamond_hseq G) L1))).\n      { etransitivity ; [ apply Permutation_Type_app ; apply copy_seq_app  | ].\n        Permutation_Type_solve. }\n      change hmr_frag_M with (hmr_frag_add_M hmr_frag_M).\n      apply hmrr_M; [ reflexivity | | ];\n        apply hmrr_C_copy_inv; assumption.\n  - inversion f.\n  - inversion Ha; subst.\n    destruct IHpi as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    { apply Forall_inf_cons; try assumption.\n      eapply seq_basic_app_inv_r; eapply seq_basic_app_inv_r; apply X. }\n    split with L.\n    repeat split; auto.\n    + intros n0; specialize (Hsum n0).\n      destruct L; try now inversion Hlen.\n      simpl; rewrite ? sum_weight_seq_app.\n      case_eq (n0 =? n); intros H.\n      * apply Nat.eqb_eq in H; subst.\n        rewrite ? sum_weight_seq_var_app;rewrite ? sum_weight_seq_covar_app.\n        rewrite sum_weight_seq_covar_vec_covar_eq;rewrite sum_weight_seq_var_vec_var_eq.\n        rewrite sum_weight_seq_var_vec_neq; [ | now auto ]; rewrite sum_weight_seq_covar_vec_neq; [ | now auto].\n        destruct n1; simpl in *; nra.\n      * apply Nat.eqb_neq in H.\n        rewrite ? sum_weight_seq_var_app;rewrite ? sum_weight_seq_covar_app.\n        rewrite ? sum_weight_seq_covar_vec_neq ; [ | now auto | intro H'; inversion H'; now auto]; rewrite ? sum_weight_seq_var_vec_neq; [ | intro H'; inversion H'; now auto | now auto ].\n        destruct n1; simpl in *; nra.\n    + destruct L; try now inversion Hlen.\n      simpl; rewrite ? sum_weight_seq_one_app; rewrite ? sum_weight_seq_coone_app.\n      rewrite ? sum_weight_seq_one_vec_neq; try now auto.\n      rewrite ? sum_weight_seq_coone_vec_neq; try now auto.\n      destruct n0; simpl in *; nra.\n    + destruct L; try now inversion Hlen.\n      simpl.\n      rewrite ? only_diamond_seq_app.\n      rewrite only_diamond_seq_vec_var; rewrite only_diamond_seq_vec_covar.\n      apply Hind.\n  - destruct r; [ | inversion Ha; inversion X; inversion X1].\n    destruct (IHpi Ha) as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    split with L.\n    repeat split; try assumption.\n  - destruct r; [ | inversion Ha; inversion X; inversion X1].\n    destruct (IHpi Ha) as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    split with L.\n    repeat split; try assumption.\n  - destruct r; [ | inversion Ha; inversion X; inversion X1].\n    destruct (IHpi Ha) as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    split with L.\n    repeat split; try assumption.\n  - destruct r; [ | inversion Ha; inversion X; inversion X1].\n    destruct IHpi as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    { inversion Ha; subst.\n      apply Forall_inf_cons ; [ | apply Forall_inf_cons ]; assumption. }\n    destruct L ; [ | destruct L]; try now inversion Hlen.\n    split with ((n + n0)%nat :: L).\n    repeat split; auto.\n    + inversion Hex; subst.\n      * apply Exists_inf_cons_hd.\n        lia.\n      * inversion X; subst; auto.\n        apply Exists_inf_cons_hd; lia.\n    + intros n1.\n      specialize (Hsum n1).\n      destruct n; destruct n0; simpl in *; try rewrite Nat.add_0_r; try nra.\n      rewrite Nat.add_succ_r.\n      rewrite <- S_INR.\n      replace ((S(S (n + n0)))%nat) with (((S n) + (S n0))%nat) by lia.\n      rewrite plus_INR.\n      simpl; nra.\n    + destruct n; destruct n0; simpl in *; try rewrite Nat.add_0_r; try nra.\n      rewrite Nat.add_succ_r.\n      rewrite <- S_INR.\n      replace ((S(S (n + n0)))%nat) with (((S n) + (S n0))%nat) by lia.\n      rewrite plus_INR.\n      simpl; nra.\n    + simpl in Hind |- *.\n      rewrite copy_seq_plus.\n      rewrite <- app_assoc; apply Hind.\n  - destruct r; [ | inversion Ha; inversion X; inversion X1].\n    destruct (IHpi1 Ha) as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    split with L.\n    repeat split; try assumption.\n  - inversion Ha; subst.\n    destruct IHpi as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    { apply Forall_inf_cons; try assumption.\n      eapply seq_basic_app_inv_r; eapply seq_basic_app_inv_r; apply X. }\n    split with L.\n    repeat split; auto.\n    + intros n0; specialize (Hsum n0).\n      destruct L; try now inversion Hlen.\n      simpl; rewrite ? sum_weight_seq_app.\n      rewrite ? sum_weight_seq_var_app;rewrite ? sum_weight_seq_covar_app.\n      rewrite ? sum_weight_seq_covar_vec_neq ; [ | now auto | intro H'; inversion H'; now auto]; rewrite ? sum_weight_seq_var_vec_neq; [ | intro H'; inversion H'; now auto | now auto ].\n      destruct n; simpl in *; nra.\n    + destruct L; try now inversion Hlen.\n      simpl; rewrite ? sum_weight_seq_one_app; rewrite ? sum_weight_seq_coone_app.\n      rewrite ? sum_weight_seq_one_vec_one_eq; rewrite ? sum_weight_seq_coone_vec_coone_eq.\n      rewrite ? sum_weight_seq_one_vec_neq; try now auto.\n      rewrite ? sum_weight_seq_coone_vec_neq; try now auto.\n      destruct n; simpl in *; try nra.\n      change (match n with\n              | 0%nat => 1\n              | S _ => INR n + 1\n              end) with (INR (S n)) in *.\n      assert (INR_pos := INR_S_n_pos n).\n      nra.\n    + destruct L; try now inversion Hlen.\n      simpl.\n      rewrite ? only_diamond_seq_app.\n      rewrite only_diamond_seq_vec_one; rewrite only_diamond_seq_vec_coone.\n      apply hmrr_ex_seq with (copy_seq n (vec s HMR_coone) ++ copy_seq n (vec r HMR_one) ++ copy_seq n (only_diamond_seq T) ++ concat_with_coeff_copy (only_diamond_hseq G) L).\n      { rewrite 2 app_assoc; apply Permutation_Type_app; [ | reflexivity].\n        rewrite <- app_assoc.\n        etransitivity ; [ | symmetry; apply copy_seq_app ].\n        apply Permutation_Type_app ; [ reflexivity | ].\n        symmetry; apply copy_seq_app. }\n      simpl in Hind.\n      remember (copy_seq n (only_diamond_seq T)) as D.\n      clear - r0 Hind.\n      induction n; try apply Hind.\n      eapply hmrr_ex_seq ; [ | apply hmrr_one ; [ apply r0 | apply IHn]].\n      simpl; Permutation_Type_solve.\n  - split with (1%nat :: nil).\n    repeat split; auto.\n    + intros n.\n      simpl.\n      rewrite ? sum_weight_seq_var_app; rewrite ? sum_weight_seq_covar_app.\n      rewrite ? sum_weight_seq_var_vec_neq; try now auto.\n      rewrite ? sum_weight_seq_covar_vec_neq; try now auto.\n      rewrite sum_weight_seq_var_seq_diamond; rewrite sum_weight_seq_covar_seq_diamond.\n      nra.\n    + simpl.\n      rewrite ? sum_weight_seq_one_app; rewrite ? sum_weight_seq_coone_app.\n      rewrite sum_weight_seq_one_vec_one_eq; rewrite sum_weight_seq_coone_vec_coone_eq.\n      rewrite ? sum_weight_seq_one_vec_neq; try now auto.\n      rewrite ? sum_weight_seq_coone_vec_neq; try now auto.\n      rewrite sum_weight_seq_one_seq_diamond; rewrite sum_weight_seq_coone_seq_diamond.\n      nra.\n    + simpl.\n      rewrite app_nil_r; rewrite ? only_diamond_seq_app.\n      rewrite only_diamond_seq_vec_coone; rewrite only_diamond_seq_vec_one; rewrite only_diamond_seq_only_diamond.\n      apply pi.\n  - destruct IHpi as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    { inversion Ha; subst.\n      apply Forall_inf_cons; try assumption.\n      apply seq_basic_perm with T2; [ Permutation_Type_solve | apply X]. }\n    split with L.\n    destruct L; try now inversion Hlen.\n    repeat split; auto.\n    + intro n1; specialize (Hsum n1).\n      simpl in *.\n      rewrite <- (sum_weight_seq_var_perm _ _ _ p); rewrite <- (sum_weight_seq_covar_perm _ _ _ p); apply Hsum.\n    + simpl in *.\n      rewrite <- (sum_weight_seq_one_perm _ _ p); rewrite <- (sum_weight_seq_coone_perm _ _ p); apply Hone.\n    + simpl in Hind |- *.\n      eapply hmrr_ex_seq; [ | apply Hind].\n      apply Permutation_Type_app ; [ | reflexivity ].\n      apply copy_seq_perm; apply only_diamond_seq_perm.\n      apply p.\n  - destruct IHpi as [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    { apply hseq_basic_perm with H; try assumption.\n      symmetry; apply p. }\n    destruct (sum_weight_with_coeff_perm_r_int G H L p) as [L' [Hperm' [[Hsum' Hone'] Hpc]]].\n    { apply Hlen. }\n    split with L'.\n    repeat split.\n    + apply Permutation_Type_length in p.\n      apply Permutation_Type_length in Hperm'.\n      lia.\n    + apply Exists_inf_Permutation_Type with L; assumption.\n    + intros n.\n      rewrite <- (Hsum' n); apply Hsum.\n    + rewrite <- Hone'; apply Hone.\n    + eapply hmrr_ex_seq ; [ apply Hpc | ].\n      apply Hind.\n  - inversion f.\nQed.\n\nLemma int_lambda_prop_inv :\n  forall G,\n    hseq_is_basic G ->\n    { L &\n      prod (length L = length G)\n           ((Exists_inf (fun x => x <> 0%nat) L) *\n            (forall n, sum_weight_with_coeff n G (map nat_oRpos L) = 0) *\n            (0 <= sum_weight_with_coeff_one G (map nat_oRpos L)) *\n            (HMR_M ((concat_with_coeff_copy (only_diamond_hseq G) L) :: nil)))} ->\n    HMR_M G.\nProof.\n  enough (forall G H,\n             hseq_is_basic G ->\n             hseq_is_basic H ->\n             { L &\n      prod (length L = length G)\n           ((Exists_inf (fun x => x <> 0%nat) L) *\n            (forall n, (sum_weight_var n H - sum_weight_covar n H) + sum_weight_with_coeff n G (map nat_oRpos L) = 0) *\n            (0 <= (sum_weight_one H - sum_weight_coone H) + sum_weight_with_coeff_one G (map nat_oRpos L)) *\n            (HMR_M ((flat_map only_diamond_seq H ++ concat_with_coeff_copy (only_diamond_hseq G) L) :: nil)))} + HMR_M H ->\n             HMR_M (H ++  G)).\n  { intros G Hat [L [Hlen [[[Hex Hsum] Hone] Hind]]].\n    change G with (nil ++ G).\n    refine (X G nil Hat _ _).\n    - apply Forall_inf_nil.\n    - left.\n      split with L.\n      repeat split; auto.\n      + intros n; specialize (Hsum n); simpl in *; nra.\n      + simpl in *; nra. }\n  intros G.\n  remember (length G) as n.\n  revert G Heqn.\n  induction n; intros G Heqn H HatG HatH [ [L [Hlen [[[Hex Hsum] Hone] Hind]]] | pi].\n  - destruct L; inversion Hlen; inversion Hex.\n  - destruct G; inversion Heqn; rewrite app_nil_r; apply pi.\n  - destruct (Exists_inf_split _ _ _ Hex) as [[[r La] Lb] [Hp HeqL]].\n    assert (Permutation_Type L (r :: La ++ Lb)) as Hperm by (rewrite HeqL ; Permutation_Type_solve).\n    destruct (sum_weight_with_coeff_perm_l_int G _ _ Hperm) as [G' [HpermG [[Hsum' Hone'] Hpc]]].\n    { lia. }\n    destruct G' as [ | T G'].\n    { symmetry in HpermG; apply Permutation_Type_nil in HpermG.\n      subst; inversion Heqn. }\n    apply hmrr_ex_hseq with (T :: H ++ G') ; [ Permutation_Type_solve | ].\n    apply (Permutation_Type_Forall_inf HpermG) in HatG.\n    inversion HatG; clear x l H1 H2.\n    destruct r.\n    { exfalso.\n      apply Hp; reflexivity. }\n    apply hmrr_C_copy with r.\n    change (copy_seq (S r) T :: H ++ G') with ((copy_seq (S r) T :: H) ++ G').\n    apply IHn.\n    + rewrite (Permutation_Type_length HpermG) in Heqn; simpl in Heqn.\n      apply eq_add_S; apply Heqn.\n    + apply X0.\n    + apply Forall_inf_cons; try assumption.\n      apply copy_seq_basic; apply X.\n    + destruct (Forall_inf_Exists_inf_dec (fun x => x = 0%nat)) with (La ++ Lb).\n      { intro x; destruct x; [ left | right]; lia. }\n      * right.\n        apply basic_proof_all_eq.\n        -- apply copy_seq_basic; assumption.\n        -- apply HatH.\n        -- intros n0.\n           specialize (Hsum' n0); specialize (Hsum n0).\n           simpl in *.\n           change (match r with\n                   | 0%nat => 1\n                   | S _ => INR r + 1\n                   end) with (INR (S r)) in *.\n           rewrite (sum_weight_with_coeff_all_0 _ (map nat_oRpos (La ++ Lb))) in Hsum'.\n           ++ rewrite sum_weight_seq_var_app; rewrite sum_weight_seq_covar_app; rewrite sum_weight_seq_var_copy; rewrite sum_weight_seq_covar_copy; simpl.\n              rewrite S_INR in Hsum'.\n              nra.\n           ++ remember (La ++ Lb); clear - f.\n              induction l; simpl in *; auto.\n              inversion f; subst.\n              apply Forall_inf_cons; auto.\n        -- simpl in *.\n           change (match r with\n                   | 0%nat => 1\n                   | S _ => INR r + 1\n                   end) with (INR (S r)) in *.\n           rewrite (sum_weight_with_coeff_one_all_0 _ (map nat_oRpos (La ++ Lb))) in Hone'.\n           ++ rewrite sum_weight_seq_one_app; rewrite sum_weight_seq_coone_app; rewrite sum_weight_seq_one_copy; rewrite sum_weight_seq_coone_copy; simpl.\n              rewrite S_INR in Hone'.\n              nra.\n           ++ remember (La ++ Lb); clear - f.\n              induction l; simpl in *; auto.\n              inversion f; subst.\n              apply Forall_inf_cons; auto.\n        -- eapply hmrr_ex_seq ; [ | apply Hind].\n           simpl.\n           etransitivity ; [ | apply Permutation_Type_app_swap].\n           apply Permutation_Type_app ; [ reflexivity | ].\n           rewrite concat_with_coeff_copy_only_diamond.\n           apply only_diamond_seq_perm.\n           simpl in Hpc.\n           rewrite (concat_with_coeff_copy_all_0  G') in Hpc; [rewrite app_nil_r in Hpc; apply Hpc | ].\n           apply f.\n      * left.\n        split with (La ++ Lb).\n        repeat split.\n        -- rewrite HeqL in Hlen.\n           rewrite app_length; rewrite app_length in Hlen; simpl in *.\n           lia.\n        -- apply e.\n        -- intros n0.\n           specialize (Hsum' n0); specialize (Hsum n0).\n           simpl in *.\n           rewrite sum_weight_seq_var_app; rewrite sum_weight_seq_covar_app; rewrite sum_weight_seq_var_copy; rewrite sum_weight_seq_covar_copy; simpl.\n           change (match r with\n          | 0%nat => 1\n          | S _ => INR r + 1\n          end) with (INR (S r)) in *.\n           rewrite S_INR in Hsum'; nra.\n        -- simpl in *.\n           rewrite sum_weight_seq_one_app; rewrite sum_weight_seq_coone_app; rewrite sum_weight_seq_one_copy; rewrite sum_weight_seq_coone_copy; simpl.\n           change (match r with\n          | 0%nat => 1\n          | S _ => INR r + 1\n          end) with (INR (S r)) in *.\n           rewrite S_INR in Hone'; nra.\n        -- eapply hmrr_ex_seq ; [ | apply Hind ].\n           simpl in Hpc |- *.\n           etransitivity ; [ apply Permutation_Type_app_swap | ].\n           etransitivity ; [ | apply Permutation_Type_app_swap].\n           rewrite app_assoc.\n           apply Permutation_Type_app; [ | reflexivity].\n           rewrite ? concat_with_coeff_copy_only_diamond.\n           rewrite <- only_diamond_seq_app; apply only_diamond_seq_perm.\n           Permutation_Type_solve.\n  - eapply hmrr_ex_hseq; [ apply Permutation_Type_app_comm | ].\n    apply hmrr_W_gen.\n    apply pi.\nQed.\n\n\nLemma HMR_M_not_complete : { G : _ & HMR_zero <== sem_hseq G & (HMR_M G -> False) }.\nProof.\n  assert (0 <? sqrt 2 = true) as H by (apply R_blt_lt; apply Rlt_sqrt2_0).\n  set (sq2 := (existT (fun x => 0 <? x = true) (sqrt 2) H)).\n  split with (((One, HMR_var 0) :: nil) :: ((sq2, HMR_covar 0) :: nil):: nil).\n  - apply hmr_sound with hmr_frag_full.\n    apply hmrr_T with sq2; try reflexivity.\n    apply hmrr_S.\n    apply hmrr_ex_seq with (vec (sq2 :: nil) (HMR_covar 0) ++ vec (time_pos sq2 One :: nil) (HMR_var 0) ++ nil).\n    + unfold seq_mul.\n      replace (time_pos sq2 One) with sq2 by (unfold sq2; unfold One; apply Rpos_eq; simpl; nra).\n      simpl.\n      apply Permutation_Type_swap.\n    + apply hmrr_ID ; [ | apply hmrr_INIT].\n      simpl.\n      nra.\n  - intros pi.\n    apply int_lambda_prop in pi as [L [Hlen [[[Hex Hsum] Hone] Hstep]]].\n    + specialize (Hsum 0)%nat.\n      simpl in Hlen.\n      clear Hone Hstep.\n      destruct L; [ | destruct L ; [ | destruct L]]; inversion Hlen.\n      destruct n0; destruct n; try lia.\n      * inversion Hex; [ lia | ].\n        inversion X; [ lia | ].\n        inversion X0.\n      * simpl in *.\n        change (match n with\n                | 0%nat => 1\n                | S _ => INR n + 1\n                end)\n          with (INR (S n)) in Hsum.\n        replace (INR (S n) * (1 + 0 - 0) + 0) with (INR (S n)) in Hsum by lra.\n        change 0 with (INR 0) in Hsum; apply INR_inj in Hsum; inversion Hsum.\n      * simpl in *.\n        change (match n0 with\n                | 0%nat => 1\n                | S _ => INR n0 + 1\n                end)\n          with (INR (S n0)) in Hsum.\n        replace (INR (S n0) * (0 - (sqrt 2 + 0)) + 0) with (- INR (S n0) * sqrt 2) in Hsum by lra.\n        enough (INR ((S n0) * (S n0) * 2) = 0).\n        { change 0 with (INR 0) in H0.\n          apply INR_inj in H0.\n          lia. }\n        rewrite ? mult_INR.\n        change (INR 2) with 2.\n        replace 2 with (sqrt 2 * sqrt 2) by (apply sqrt_def; nra).\n        nra.\n      * simpl in *.\n        change (match n with\n                | 0%nat => 1\n                | S _ => INR n + 1\n                end)\n          with (INR (S n)) in Hsum.\n        change (match n0 with\n                | 0%nat => 1\n                | S _ => INR n0 + 1\n                end)\n          with (INR (S n0)) in Hsum.\n        replace (INR (S n) * (1 + 0 - 0)) with (INR (S n)) in Hsum by nra.\n        replace (0 - (sqrt 2 + 0)) with (- sqrt 2) in Hsum by nra.\n        replace (INR (S n0) * - sqrt 2 + 0) with (- INR (S n0) * sqrt 2) in Hsum by nra.\n        assert (INR ((S n) * (S n)) = INR (2 * (S n0) * (S n0))).\n        { rewrite ? mult_INR.\n          change (INR 2) with 2.\n          replace 2 with (sqrt 2 * sqrt 2) by (apply sqrt_def; nra).\n          nra. }\n        apply INR_inj in H0.\n        apply sqrt2_not_rational with (S n) (S n0); auto.\n        lia.\n    + repeat apply Forall_inf_cons; try apply Forall_inf_nil; apply I.\nQed.\n", "meta": {"author": "clucas26e4", "repo": "riesz-logic", "sha": "6ad0da80c8922d186c777d2c8f1a42d381abfb2d", "save_path": "github-repos/coq/clucas26e4-riesz-logic", "path": "github-repos/coq/clucas26e4-riesz-logic/riesz-logic-6ad0da80c8922d186c777d2c8f1a42d381abfb2d/hmr/completeness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22418192331223902}}
{"text": "Require Import Coq.Unicode.Utf8 Arith Bool Ring Setoid String.\nRequire Import Coq.Lists.ListSet.\nRequire Import Coq.Sets.Powerset.\nRequire Import Coq.Logic.Classical_Pred_Type.\nRequire Import Coq.Classes.EquivDec.\nRequire Import Coq.Classes.SetoidClass.\nRequire Import Coq.Logic.Decidable.\nRequire Import Coq.Structures.Equalities.\nRequire Import Coq.Logic.Eqdep_dec.\nRequire Import Coq.Logic.ClassicalFacts.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.ProofIrrelevance.\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\n(* helpers *)\nDefinition dec2decb {A : Type} (dec : ∀ a1 a2 : A, {a1 = a2} + {a1 ≠ a2}) : (A -> A -> bool) :=\n  fun a b => if dec a b then true else false.\nDefinition except {A : Type} (A_decb : A -> A -> bool) (a b : list A) : list A :=\n  filter (fun x => negb (existsb (A_decb x) b)) a.\n\nDefinition option_bind {A B : Type} (f : A -> option B) (x : option A) : option B :=\nmatch x with\n| Some x' => f x'\n| None => None\nend.\n\nDefinition nat_decb := dec2decb eq_nat_dec.\nHint Resolve eq_nat_dec.\nHint Resolve list_eq_dec eq_nat_dec.\n\nProgram Instance string_EqDec : EqDec string eq := string_dec.\nDefinition string_decb := dec2decb string_dec.\nHint Resolve string_dec.\nHint Resolve list_eq_dec string_dec.\n\n(* Figure 1: Syntax of a Java-like language for core language *)\nDefinition C := string.\nDefinition f := string.\nDefinition m := string.\nDefinition o := nat.\nInductive x :=\n| xUserDef : string -> x\n| xthis : x\n| xresult : x.\nInductive T :=\n| TPrimitiveInt : T\n| TClass : C -> T.\nInductive v :=\n| vn : nat -> v\n| vnull : v\n| vo : o -> v.\nInductive e :=\n| ev : v -> e\n| ex : x -> e\n| edot : e -> f -> e.\nInductive phi' :=\n| phiTrue : phi'\n| phiEq : e -> e -> phi'\n| phiNeq : e -> e -> phi'\n| phiAcc : e -> f -> phi'.\nDefinition phi := list phi'.\nInductive s :=\n| sMemberSet : x -> f -> x -> s\n| sAssign : x -> e -> s\n| sAlloc : x -> C -> s\n| sCall : x -> x -> m -> list x -> s\n| sReturn : x -> s\n| sAssert : phi' -> s\n| sRelease : phi' -> s.\nInductive contract :=\n| Contract : phi -> phi -> contract.\nInductive method :=\n| Method : T -> m -> list (T * x) -> contract -> list s -> method.\nInductive field :=\n| Field : T -> f -> field.\nInductive cls :=\n| Cls : C -> list field -> list method -> cls.\nInductive program :=\n| Program : (list cls) -> (list s) -> program.\n\nDefinition Gamma := x -> option T.\nDefinition H := o -> option (C * (f -> option v)).\nDefinition rho := x -> option v.\nInductive name :=\n| namex : x -> name\n| nameo : o -> name.\nDefinition A := list (name * f).\nDefinition S := list (rho * A * list s).\n\n(* equality *)\n\nDefinition C_decb := string_decb.\nDefinition f_decb := string_decb.\nDefinition m_decb := string_decb.\n\nDefinition o_dec : ∀ n m : o, {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance o_EqDec : EqDec o eq := o_dec.\nDefinition o_decb := dec2decb o_dec.\nHint Resolve o_dec.\nHint Resolve list_eq_dec o_dec.\n\nDefinition x_dec : ∀ n m : x, {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance x_EqDec : EqDec x eq := x_dec.\nDefinition x_decb := dec2decb x_dec.\nHint Resolve x_dec.\nHint Resolve list_eq_dec x_dec.\n\nDefinition T_dec : ∀ n m : T, {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance T_EqDec : EqDec T eq := T_dec.\nDefinition T_decb := dec2decb T_dec.\nHint Resolve T_dec.\nHint Resolve list_eq_dec T_dec.\n\nDefinition v_dec : ∀ n m : v, {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance v_EqDec : EqDec v eq := v_dec.\nDefinition v_decb := dec2decb v_dec.\nHint Resolve v_dec.\nHint Resolve list_eq_dec v_dec.\n\nDefinition e_dec : ∀ n m : e, {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance e_EqDec : EqDec e eq := e_dec.\nDefinition e_decb := dec2decb e_dec.\nHint Resolve e_dec.\nHint Resolve list_eq_dec e_dec.\n\nDefinition phi'_dec : ∀ n m : phi', {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance phi'_EqDec : EqDec phi' eq := phi'_dec.\nDefinition phi'_decb := dec2decb phi'_dec.\nHint Resolve phi'_dec.\nHint Resolve list_eq_dec phi'_dec.\n\nDefinition phi_dec : ∀ n m : phi, {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance phi_EqDec : EqDec phi eq := phi_dec.\nDefinition phi_decb := dec2decb phi_dec.\nHint Resolve phi_dec.\nHint Resolve list_eq_dec phi_dec.\n\nDefinition s_dec : ∀ n m : s, {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance s_EqDec : EqDec s eq := s_dec.\nDefinition s_decb := dec2decb s_dec.\nHint Resolve s_dec.\nHint Resolve list_eq_dec s_dec.\n\nDefinition contract_dec : ∀ n m : contract, {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance contract_EqDec : EqDec contract eq := contract_dec.\nDefinition contract_decb := dec2decb contract_dec.\nHint Resolve contract_dec.\nHint Resolve list_eq_dec contract_dec.\n\nDefinition method_dec : ∀ n m : method, {n = m} + {n ≠ m}. decide equality. apply (list_eq_dec (prod_eqdec T_dec x_dec)). Defined.\nProgram Instance method_EqDec : EqDec method eq := method_dec.\nDefinition method_decb := dec2decb method_dec.\nHint Resolve method_dec.\nHint Resolve list_eq_dec method_dec.\n\nDefinition field_dec : ∀ n m : field, {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance field_EqDec : EqDec field eq := field_dec.\nDefinition field_decb := dec2decb field_dec.\nHint Resolve field_dec.\nHint Resolve list_eq_dec field_dec.\n\nDefinition cls_dec : ∀ n m : cls, {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance cls_EqDec : EqDec cls eq := cls_dec.\nDefinition cls_decb := dec2decb cls_dec.\nHint Resolve cls_dec.\nHint Resolve list_eq_dec cls_dec.\n\nDefinition program_dec : ∀ n m : program, {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance program_EqDec : EqDec program eq := program_dec.\nDefinition program_decb := dec2decb program_dec.\nHint Resolve program_dec.\nHint Resolve list_eq_dec program_dec.\n\nDefinition name_dec : ∀ n m : name, {n = m} + {n ≠ m}. decide equality. Defined.\nProgram Instance name_EqDec : EqDec name eq := name_dec.\nDefinition name_decb := dec2decb name_dec.\nHint Resolve name_dec.\nHint Resolve list_eq_dec name_dec.\n\nDefinition A_dec : ∀ n m : A, {n = m} + {n ≠ m}. decide equality. apply (prod_eqdec name_dec string_dec). Defined.\nProgram Instance A_EqDec : EqDec A eq := A_dec.\nDefinition A_decb := dec2decb A_dec.\nHint Resolve A_dec.\nHint Resolve list_eq_dec A_dec.\n\nDefinition A'_decb (a b : name * f) : bool := name_decb (fst a) (fst b) && string_decb (snd a) (snd b).\nDefinition Aexcept := except A'_decb.\n\n\nModule Semantics.\n\nParameter p : program.\n\n(* accessors *)\nDefinition classes : list cls := match p with Program clss _ => clss end.\nDefinition class (C' : C) : option cls :=\n    find (fun class => match class with Cls C'' _ _ => C_decb C'' C' end) classes.\nDefinition fields (C' : C) : option (list (T * f)) :=\n  match class C' with\n  | None => None\n  | Some class => \n    match class with\n    | Cls _ fs _ => Some (map (fun f => match f with Field T' f' => (T', f') end) fs)\n    end\n  end.\nDefinition fieldType (C' : C) (f' : f) : option T :=\n  match class C' with\n  | None => None\n  | Some class => \n    match class with\n    | Cls C'' fs _ => option_map\n        (fun f => match f with Field T' _ => T' end)\n        (find (fun f => match f with Field _ f'' => f_decb f'' f' end) fs)\n    end\n  end.\nDefinition allMethods : list method := flat_map (fun cl => match cl with Cls _ _ x => x end) classes.\nDefinition mmethod (C' : C) (m' : m) : option method :=\n  match class C' with\n  | None => None\n  | Some class => \n    match class with\n    | Cls C'' _ ms =>\n      find (fun me => match me with Method _ m'' _ _ _ => m_decb m'' m' end) ms\n    end\n  end.\nDefinition mcontract (C' : C) (m' : m) : option contract :=\n  option_map\n    (fun me => match me with Method _ _ _ contr _ => contr end)\n    (mmethod C' m').\nDefinition mpre (C' : C) (m' : m) : option phi :=\n  option_map\n    (fun contr => match contr with Contract res _ => res end)\n    (mcontract C' m').\nDefinition mpost (C' : C) (m' : m) : option phi :=\n  option_map\n    (fun contr => match contr with Contract _ res => res end)\n    (mcontract C' m').\nDefinition mbody (C' : C) (m' : m) : option (list s) :=\n  option_map\n    (fun me => match me with Method _ _ _ _ instrs => instrs end)\n    (mmethod C' m').\nDefinition mparams (C' : C) (m' : m) : option (list x) :=\n  option_map\n    (fun me => match me with Method _ _ params _ _ => map snd params end)\n    (mmethod C' m').\n\nDefinition getMain : list s := match p with Program _ main => main end.\n\n(* substitution *)\nFixpoint eSubst (x' : x) (e' : e) (ee : e) : e :=\nmatch ee with\n| ex x'' => if x_decb x'' x' then e' else ee\n| edot e'' f' => edot (eSubst x' e' e'') f'\n| _ => ee\nend.\n\nDefinition eSubsts (r : list (x * e)) (ee : e) : e :=\n  fold_left (fun a b => eSubst (fst b) (snd b) a) r ee.\n\nDefinition phi'Subst (x' : x) (e' : e) (p : phi') : phi' :=\nmatch p with\n| phiEq  e1 e2 => phiEq  (eSubst x' e' e1) (eSubst x' e' e2)\n| phiNeq e1 e2 => phiNeq (eSubst x' e' e1) (eSubst x' e' e2)\n| phiAcc e'' f'' => phiAcc (eSubst x' e' e'') f''\n| _ => p\nend.\n\nDefinition phiSubst (x' : x) (e' : e) (p : phi) : phi :=\n  map (phi'Subst x' e') p.\n\nDefinition phiSubsts (r : list (x * e)) (p : phi) : phi :=\n  fold_left (fun a b => phiSubst (fst b) (snd b) a) r p.\n\nDefinition HSubst (o' : o) (f' : f) (v' : v) (h : H) : H :=\n  fun o'' =>\n    if o_decb o'' o'\n      then \n      (\n        match h o'' with\n        | Some (C', ff') => Some (C', fun f'' => if f_decb f'' f' then Some v' else ff' f'')\n        | None => None\n        end\n      )\n      else h o''\n.\n\nDefinition HSubsts (o' : o) (r : list (f * v)) (h : H) : H :=\n  fold_left (fun a b => HSubst o' (fst b) (snd b) a) r h.\n\nDefinition rhoSubst (x' : x) (v' : v) (r : rho) : rho :=\n  fun x'' => if x_decb x'' x' then Some v' else r x''.\n\nDefinition GammaSubst (x' : x) (T' : T) (g : Gamma) : Gamma :=\n  fun x'' => if x_decb x'' x' then Some T' else g x''.\n\n(* Figure 2: Static typing rules for expressions of the core language *)\nInductive sfrme : A -> e -> Prop :=\n| WFVar : forall a (x' : x),\n    sfrme a (ex x')\n| WFValue : forall a (v' : v),\n    sfrme a (ev v')\n| WFField : forall a (x' : x) (f' : f),\n    In (namex x', f') a ->\n    sfrme a (edot (ex x') f')\n.\n\n\n(* Figure 4: Deﬁnition of a static version of footprint *)\nFixpoint staticFootprint (p : phi) : A := flat_map (fun p =>\n  match p with\n  | phiAcc (ex x') f' => [(namex x', f')]\n  | _ => []\n  end) p.\n\n(* Figure 3: Static rules for syntactically self-framed formulas *)\nInductive sfrmphi' : A -> phi' -> Prop :=\n| WFTrue : forall a, sfrmphi' a phiTrue\n| WFEqual : forall a (e1 e2 : e), sfrme a e1 -> sfrme a e2 -> sfrmphi' a (phiEq e1 e2)\n| WFNEqual : forall a (e1 e2 : e), sfrme a e1 -> sfrme a e2 -> sfrmphi' a (phiNeq e1 e2)\n| WFAcc : forall a e' f, sfrme a e' -> sfrmphi' a (phiAcc e' f)\n.\nDefinition sfrmphi (a : A) (p : phi) : Prop :=\n  forall p', In p' p -> sfrmphi' a p'.\n\n(* static type derivation *)\nDefinition getType' (v' : v) : option T :=\n  match v' with\n  | vnull => None\n  | vn _ => Some TPrimitiveInt\n  | vo _ => None\n  end.\nFixpoint getType (G : Gamma) (e' : e) : option T :=\n  match e' with\n  | ev v => getType' v\n  | ex x => G x\n  | edot e' f' => \n    option_bind\n      (fun t => \n        match t with\n        | TPrimitiveInt => None\n        | TClass C' => fieldType C' f'\n        end)\n      (getType G e')\n  end.\n\n(* Figure 6: Evaluation of expressions for core language *)\nFixpoint evale (h : H) (r : rho) (e' : e) : option v :=\n  match e' with\n  | ex x' => r x'\n  | edot e'' f' =>\n    match evale h r e'' with\n    | Some (vo o') =>\n      match h o' with\n      | Some (_, ho') => ho' f'\n      | _ => None\n      end\n    | _ => None\n    end\n  | ev v => Some v\n  end.\n(* NOTE: there are tons of calls like \"evale h r (ex x)\", wouldn't it be clearer to just say \"r x\"? or is that less consistent? *)\n\n(* Figure 7: Evaluation of formulas for core language *)\nInductive evalphi' : H -> rho -> A -> phi' -> Prop :=\n| EATrue : forall h r a,\n    evalphi' h r a phiTrue\n| EAEqual : forall h r a e1 e2 v1 v2,\n    evale h r e1 = Some v1 ->\n    evale h r e2 = Some v2 ->\n    v1 = v2 ->\n    evalphi' h r a (phiEq e1 e2)\n| EANEqual : forall h r a e1 e2 v1 v2,\n    evale h r e1 = Some v1 ->\n    evale h r e2 = Some v2 ->\n    v1 <> v2 ->\n    evalphi' h r a (phiNeq e1 e2)\n| EAAcc : forall h r a e' o' f',\n    evale h r e' = Some (vo o') ->\n    In (nameo o', f') a ->\n    evalphi' h r a (phiAcc e' f')\n.\nDefinition evalphi : H -> rho -> A -> phi -> Prop :=\n  fun h r a p => forall p', In p' p -> evalphi' h r a p'.\n\n(* implication on phi *)\nDefinition phiImplies (p1 p2 : phi) : Prop :=\n  forall h r a, evalphi h r a p1 -> evalphi h r a p2.\n\n(* well-typedness *)\nDefinition wellTypedX (G : Gamma) (x' : x) : Prop :=\n  exists T', G x' = Some T'.\nDefinition wellTypedE (G : Gamma) (e' : e) : Prop :=\n  exists T', getType G e' = Some T'.\nDefinition wellTypedPhi' (G : Gamma) (p : phi') : Prop :=\n  match p with\n  | phiTrue => True\n  | phiEq e1 e2 => wellTypedE G e1 /\\ wellTypedE G e2 /\\ getType G e1 = getType G e2\n  | phiNeq e1 e2 => wellTypedE G e1 /\\ wellTypedE G e2 /\\ getType G e1 = getType G e2\n  | phiAcc e' f => wellTypedE G (edot e' f)\n  end.\nDefinition wellTypedPhi (G : Gamma) (p : phi) : Prop :=\n  forall p', In p' p -> wellTypedPhi' G p'.\nDefinition wellTyped (G : Gamma) (s' : s) : Prop :=\n  match s' with\n  | sMemberSet x' f' y' => let e1 := (edot (ex x') f') in\n                           let e2 := ex y' in \n                            wellTypedE G e1 /\\ wellTypedE G e2 /\\ getType G e1 = getType G e2\n  | sAssign x' e' => True\n  | sAlloc x' C' => G x' = Some (TClass C')\n  | sCall x' y' f' z' => exists C' T' ps' contr s',\n                G y' = Some (TClass C') /\\\n                mmethod C' f' = Some (Method T' f' ps' contr s') /\\\n                G x' = Some T' /\\\n                map Some (map fst ps') = map G z' (* /\\ anything with contr and s' ???*)\n  | sReturn x' => wellTypedX G x'\n  | sAssert p => wellTypedPhi' G p\n  | sRelease p => wellTypedPhi' G p\n  end.\n\n(* Figure 5: Hoare-based proof rules for core language *)\nInductive hoareSingle : Gamma -> phi -> s -> phi -> Prop :=\n| HNewObj : forall (G : Gamma) p x' (C' : C) fs,\n    G x' = Some (TClass C') ->\n    fields C' = Some fs ->\n    hoareSingle\n      G\n      p\n      (sAlloc x' C')\n      (fold_left \n        (fun a b => phiAcc (ex x') (snd b) :: a) \n        fs \n        (phiNeq (ex x') (ev vnull) :: p))\n| HFieldAssign : forall G (p : phi) (x' y' : x) (f' : f) e',\n    In (phiAcc (ex x') f') p ->\n    In (phiNeq (ex x') (ev vnull)) p ->\n    In (phiEq (ex y') e') p ->\n    hoareSingle G p (sMemberSet x' f' y') (p ++ [phiEq (edot (ex x') f') (ex y')])\n| HVarAssign : forall G p' p (x' : x) (e' e2' : e),\n    p' = phiSubst x' e' p ->\n    In (phiEq e' e2') p' ->\n    sfrmphi [] p' ->\n    sfrme (staticFootprint p') e' ->\n    hoareSingle G p' (sAssign x' e') p\n| HReturn : forall G p (x' : x) e' p',\n    p' = phiSubst x' e' p ->\n    In (phiEq (ex x') e') p' ->\n    hoareSingle G p' (sReturn x') p\n| HApp : forall G p pp pr pq (x' y' : x) (C' : C) (m' : m) (Xz' : list (x * x)) (zs' := map snd Xz') (Xze' := map (fun pr => (fst pr, ex (snd pr))) Xz'),\n    G y' = Some (TClass C') ->\n    In (phiNeq (ex y') (ev vnull)) p ->\n    phiImplies p (pp ++ pr) ->\n    Some pp = option_map (phiSubsts ((xthis, ex y') :: Xze')) (mpre C' m') ->\n    Some pq = option_map (phiSubsts (((xthis, ex y') :: Xze') ++ [(xresult, ex x')])) (mpost C' m') ->\n    hoareSingle G p (sCall x' y' m' zs') (pq ++ pr)\n| HAssert : forall G p1 p2,\n    In p2 p1 ->\n    hoareSingle G p1 (sAssert p2) p1\n| HRelease : forall G p1 p2 pr,\n    phiImplies p1 (p2 :: pr) ->\n    sfrmphi [] pr ->\n    hoareSingle G p1 (sRelease p2) pr\n.\n\nInductive hoare : phi -> list s -> phi -> Prop :=\n| HSec : forall G (p q1 q2 r : phi) (s1 : s) (s2 : list s), (* w.l.o.g.??? *)\n    hoareSingle G p s1 q1 ->\n    phiImplies q1 q2 ->\n    hoare q2 s2 r ->\n    hoare p (s1 :: s2) r\n| HEMPTY : forall p, hoare p [] p\n.\n\n\n(* Figure 8: Definition of footprint meta-function *)\nFixpoint footprint' (h : H) (r : rho) (p : phi') : A :=\n  match p with\n  | phiAcc e' f' => \n      match evale h r e' with\n      | Some (vo o') => [(nameo o', f')]\n      | _ => [] (*???*)\n      end\n  | _ => []\n  end.\nFixpoint footprint (h : H) (r : rho) (p : phi) : A :=\n  flat_map (footprint' h r) p.\n\n(* Figure 9: Dynamic semantics for core language *)\nDefinition execState : Set := H * S.\nInductive dynSem : execState -> execState -> Prop :=\n| ESFieldAssign : forall h h' (S' : S) (s' : list s) (a : A) r (x' y' : x) (yv' : v) (o' : o) (f' : f),\n    evale h r (ex x') = Some (vo o') ->\n    evale h r (ex y') = Some yv' ->\n    In (nameo o', f') a ->\n    h' = HSubst o' f' yv' h ->\n    dynSem (h, (r, a, sMemberSet x' f' y' :: s') :: S') (h', (r, a, s') :: S')\n(*| ESDefVar : forall h (S' : S) (s' : list s) (a : A) r r' (x' : x) (T' : T),\n    r' = rhoSubst x' vnull r ->\n    dynSem (h, (r, a, sDeclare T' x' :: s') :: S') (h, (r', a, s') :: S')*)\n| ESVarAssign : forall h (S' : S) (s' : list s) (a : A) r r' (x' : x) (e' : e) (v' : v),\n    evale h r e' = Some v' ->\n    r' = rhoSubst x' v' r ->\n    dynSem (h, (r, a, sAssign x' e' :: s') :: S') (h, (r', a, s') :: S')\n| ESNewObj : forall h h' (S' : S) (s' : list s) (a a' : A) r r' (x' : x) (o' : o) (C' : C) Cf',\n    h o' = None ->\n    fields C' = Some Cf' ->\n    r' = rhoSubst x' (vo o') r ->\n    a' = a ++ map (fun cf' => (nameo o', snd cf')) Cf' ->\n    h' = HSubsts o' (map (fun cf' => (snd cf', vnull)) Cf') h ->\n    dynSem (h, (r, a, sAlloc x' C' :: s') :: S') (h', (r', a', s') :: S')\n| ESReturn : forall h (S' : S) (s' : list s) (a : A) r r' (x' : x) (vx : v),\n    evale h r (ex x') = Some vx ->\n    r' = rhoSubst xresult vx r ->\n    dynSem (h, (r, a, sReturn x' :: s') :: S') (h, (r', a, s') :: S')\n| ESApp : forall pre h (S' : S) (s' rs : list s) (a a' : A) (r r' : rho) (x' y' : x) (zs' : list x) (wvs' : list (x * v)) (ws' := map fst wvs') (vs' := map snd wvs') (m' : m) (o' : o) (C' : C) fvf,\n    evale h r (ex y') = Some (vo o') ->\n    map (fun z' => evale h r (ex z')) zs' = map Some vs' ->\n    h o' = Some (C', fvf) ->\n    mbody C' m' = Some rs ->\n    mparams C' m' = Some ws' ->\n    mpre C' m' = Some pre ->\n    r' = (fun rx => if x_decb rx xthis \n      then Some (vo o')\n      else (match find (fun wv => x_decb rx (fst wv)) wvs' with\n            | Some x => Some (snd x)\n            | None => None\n            end)) ->\n    evalphi h r' a pre ->\n    a' = footprint h r' pre ->\n    dynSem (h, (r, a, sCall x' y' m' zs' :: s') :: S') (h, (r', a', rs) :: (r, Aexcept a a', sCall x' y' m' zs' :: s') :: S')\n| ESAppFinish : forall post h (S' : S) (s' : list s) (a a' a'' : A) r r' (x' : x) zs' (m' : m) y' (C' : C) vresult,\n    mpost C' m' = Some post ->\n    evalphi h r' a' post ->\n    a'' = footprint h r' post ->\n    evale h r' (ex xresult) = Some vresult ->\n    dynSem (h, (r', a', []) :: (r, a, sCall x' y' m' zs' :: s') :: S') (h, (rhoSubst x' vresult r, a ++ a'', s') :: S')\n| ESAssert : forall h r a p s' S',\n    evalphi' h r a p ->\n    dynSem (h, (r, a, sAssert p :: s') :: S') (h, (r, a, s') :: S')\n| ESRelease : forall h r a a' p s' S',\n    evalphi' h r a p ->\n    a' = Aexcept a (footprint' h r p) ->\n    dynSem (h, (r, a, sRelease p :: s') :: S') (h, (r, a', s') :: S')\n.\n\n(* helper definitions *)\nDefinition isStuck (s : execState) : Prop :=\n  ~ exists s', dynSem s s'.\nDefinition isFinished (s : execState) : Prop :=\n  exists r a, snd s = [(r,a,[])].\nDefinition isFail (s : execState) : Prop :=\n  isStuck s /\\ ~ isFinished s.\n\nInductive dynSemStar : execState -> execState -> Prop :=\n| ESSNone : forall a, dynSemStar a a\n| ESSStep : forall a b c, dynSem a b -> dynSemStar b c -> dynSemStar a c\n.\n(*Definition dynSemFull (initial final : execState) : Prop := dynSemStar initial final /\\ isFinished final.\n*)\nDefinition newHeap : H := fun _ => None.\nDefinition newRho : rho := fun _ => None.\nDefinition newAccess : A := [].\n\n(* ASSUMPTIONS *)\nDefinition mWellDefined (m : method) := \n  match m with Method T' m' p c s =>\n    match c with Contract pre post =>\n      hoare pre s post /\\\n      sfrmphi (staticFootprint pre) pre /\\\n      sfrmphi (staticFootprint post) post\n    end\n  end.\nAxiom pWellDefined : forall m, In m allMethods -> mWellDefined m.\n\n(* PROOF SECTION *)\nNotation \"'φ'\" := phi.\nNotation \"'ρ'\" := rho.\nNotation \"'Γ'\" := Gamma.\n\n(* determinism? *)\n\nLemma hoareImplies : forall q1 q2 q3 q4 s', phiImplies q1 q2 -> hoare q2 s' q3 -> phiImplies q3 q4 -> hoare q1 s' q4.\nAdmitted.\n\nLemma phiImpliesRefl : forall x, phiImplies x x.\nProof.\n  unfold phiImplies.\n  auto.\nQed.\nHint Resolve phiImpliesRefl.\n\nLemma AexceptReverse : forall a1 a2, Aexcept (a1 ++ a2) a2 = a1.\nAdmitted.\n\nLemma evalPhiImplies : forall H' r A' q1 q2,\n  phiImplies q1 q2 -> evalphi H' r A' q1 -> evalphi H' r A' q2.\nProof.\n  intros.\n  unfold phiImplies in H0.\n  specialize (H0 H' r A').\n  intuition.\nQed.\n\nLemma InAexcept : forall x a a', In x (Aexcept a a') -> In x a.\nProof.\n  unfold Aexcept.\n  unfold except.\n  induction a; intros.\n  - compute in H0.\n    inversion H0.\n  - simpl.\n    simpl filter in H0.\n    destruct (existsb (A'_decb a) a'); simpl in H0.\n    * apply IHa in H0.\n      auto.\n    * inversion H0; auto.\n      apply IHa in H1.\n      auto.\nQed.\n\nLemma HnotTotal : forall (H' : H), exists x, H' x = None.\nAdmitted.\n\nLemma mapSplitFst : forall {A B : Type} (x : list (A * B)), map fst x = fst (split x).\nAdmitted.\nLemma mapSplitSnd : forall {A B : Type} (x : list (A * B)), map snd x = snd (split x).\nAdmitted.\n\n(*\nLemma phiTrueSubst : forall a b p, phiTrue = phiSubst a b p -> p = phiTrue.\nProof.\n  intros.\n  destruct p; auto;\n  unfold phiSubst in H0; inversion H0.\nQed.\nLemma phiTrueSubsts : forall a p, phiTrue = phiSubsts a p -> p = phiTrue.\nProof.\n  induction a; intros.\n  - simpl in H0.\n    auto.\n  - simpl in H0.\n    apply IHa in H0.\n    symmetry in H0.\n    apply phiTrueSubst in H0.\n    assumption.\nQed.\nLemma phiEqSubsts : forall a p e1 e2, phiEq e1 e2 = phiSubsts a p -> exists e1' e2', p = phiEq e1' e2' /\\ e1 = eSubsts a e1' /\\ e2 = eSubsts a e2'.\nProof.\n  induction a; intros.\n  - repeat eexists.\n    simpl in H0.\n    subst.\n    auto.\n  - simpl in H0.\n    apply IHa in H0.\n    inversion H0; clear H0.\n    inversion H1; clear H1.\n    intuition.\n    subst.\n    destruct p; simpl in H1; inversion H1.\n    repeat eexists.\n    * admit.\n    * admit.\nAdmitted.\n\nLemma eSubstsVal : forall x v, eSubsts x (ev v) = (ev v).\nProof.\n  induction x0; intros.\n  - simpl; tauto.\n  - specialize (IHx0 v0).\n    assert (eSubsts (a :: x0) (ev v0) = eSubsts x0 (ev v0)).\n    * admit.\n    * rewrite IHx0 in H0.\n      assumption.\nAdmitted.\n\nLemma phiImpliesConj : forall a b c, phiImplies a (phiConj b c) -> phiImplies a b.\nAdmitted.*)\n\nLtac tmp := repeat eexists; econstructor; econstructor; eauto.\nLtac unfWT := \n  unfold wellTyped in *;\n  unfold wellTypedPhi in *;\n  unfold wellTypedE in *;\n  simpl getType in *.\n\nLemma evaleTClass : forall G e' C' h r, getType G e' = Some (TClass C') -> (let res := evale h r e' in res = Some vnull \\/ exists o', res = Some (vo o')).\nAdmitted. (* TODO: entangle *)\n\nDefinition consistent (H' : H) (r : rho) := forall x' o' res, r x' = Some (vo o') -> H' o' = Some res.\n\nLemma lengthId : forall {A : Type} (a b : list A), a = b -> Datatypes.length a = Datatypes.length b.\nProof.\n  intros.\n  rewrite H0.\n  tauto.\nQed.\n\nTheorem staSemProgress : forall G (s'' : s) (s' : list s) (pre post : phi) initialHeap initialRho initialAccess S',\n  wellTyped G s'' ->\n  hoareSingle G pre s'' post ->\n  consistent initialHeap initialRho ->\n  evalphi initialHeap initialRho initialAccess pre ->\n  exists finalHeap finalRho finalAccess,\n    dynSemStar (initialHeap, (initialRho, initialAccess, s'' :: s') :: S') (finalHeap, (finalRho, finalAccess, s') :: S')\n.\nProof.\n  destruct s''; intros;\n  inversion H1; clear H1; subst; unfold evalphi in H3.\n  (*unfWT; simpl in H0; intuition.*)\n  * apply H3 in H9.\n    apply H3 in H11.\n    apply H3 in H12.\n    clear H3.\n    inversion H9; clear H9; subst.\n    inversion H11; clear H11; subst.\n    inversion H12; clear H12; subst.\n    simpl in *.\n    inversion H10; clear H10. subst.\n    rewrite H4 in *.\n    inversion H7; clear H7. subst.\n    tmp.\n  * apply H3 in H7.\n    clear H3.\n    inversion H7; clear H7; subst.\n    tmp.\n  * specialize (HnotTotal initialHeap). intros.\n    inversion H1.\n    tmp.\n  * subst.\n    apply H3 in H11.\n    inversion H11; clear H11; subst.\n    simpl in *.\n    inversion H10; clear H10; subst.\n    specialize (evaleTClass G (ex x1) C' initialHeap initialRho).\n    intros.\n    intuition.\n    inversion H4; simpl in H1; rewrite H5 in H1; inversion H1; clear H1; try (contradict H12; assumption; fail).\n    inversion H6; clear H6; subst.\n    clear H12 H4.\n    inversion H0; clear H0.\n    inversion H1; clear H1.\n    inversion H0; clear H0.\n    inversion H1; clear H1.\n    inversion H0; clear H0.\n    inversion H1; clear H1.\n    inversion H4; clear H4.\n    inversion H6; clear H6.\n    rewrite H0 in *.\n    inversion H8; clear H8.\n    subst.\n\n    destruct x6.\n\n    unfold mpre in H14.\n    unfold mcontract in H14.\n    rewrite H1 in H14.\n    simpl in H14.\n    inversion H14; clear H14.\n    subst.\n    unfold phiImplies in H13.\n    unfold evalphi in H13.\n    specialize (H13 initialHeap initialRho initialAccess).\n    intuition.\n    clear H3.\n\n    repeat eexists. econstructor; econstructor.\n    instantiate (pre := p0).\n    - eauto.\n    - simpl.\n      instantiate (wvs' := combine (map snd x5) (map (fun xx => match xx with \n            | Some vv => vv\n            | None => vnull\n            end) (map initialRho (map snd Xz')))).\n      rewrite mapSplitSnd.\n      rewrite mapSplitSnd.\n      rewrite combine_split.\n      + simpl.\n        admit.\n        (*rewrite map_map.\n        admit.\n        erewrite map_ext_in.*)\n      + rewrite map_length.\n        rewrite map_length.\n        rewrite map_length.\n        rewrite split_length_r.\n        apply lengthId in H7.\n        rewrite map_length in H7.\n        rewrite map_length in H7.\n        rewrite map_length in H7.\n        rewrite map_length in H7.\n        assumption.\n    - eauto.\n    - instantiate (C' := C').\n      unfold mbody.\n      rewrite H1.\n      simpl.\n      eauto.\n    - unfold mparams.\n      rewrite H1.\n      simpl.\n      rewrite mapSplitFst.\n      rewrite combine_split.\n      + simpl.\n        tauto.\n      + rewrite map_length.\n        rewrite map_length.\n        rewrite map_length.\n        rewrite map_length.\n        apply lengthId in H7.\n        rewrite map_length in H7.\n        rewrite map_length in H7.\n        rewrite map_length in H7.\n        rewrite map_length in H7.\n        assumption.\n    - unfold mpre. unfold mcontract.\n      rewrite H1.\n      simpl.\n      eauto.\n    - intuition.\n    - admit.\n    - intuition.\n    - admit.\n    - admit.\n  * apply H3 in H8.\n    inversion H8; clear H8; subst.\n    tmp.\n  * tmp.\n  * tmp.\n    unfold phiImplies in H5.\n    unfold evalphi in H5.\n    specialize (H5 initialHeap initialRho initialAccess).\n    apply H5; try assumption.\n    apply in_eq.\nAdmitted.\n\nLemma exists_forall : forall {A : Type} (b : A -> Prop) (c : Prop), ((exists a, b a) -> c) -> (forall a, b a -> c).\nProof.\n  intros.\n  apply H0.\n  eauto.\nQed.\n  \n\nLemma rhoVSeSubst : forall e'' e''' h r e' x' v', \n evale h r e' = Some v' ->\n eSubst x' e' e'' = e''' ->\n  evale h (rhoSubst x' v' r) e'' =\n  evale h r e'''.\nProof.\n  induction e''; intros; subst.\n  - simpl. auto.\n  - simpl eSubst. simpl. unfold rhoSubst.\n    case_eq (x_decb x0 x'); intros; simpl; try tauto.\n    rewrite H0.\n    tauto.\nQed.\n\nLemma rhoVSphiSubst1 : forall e'' e''' h r e' x' v' a, \n evale h r e' = Some v' ->\n phi'Subst x' e' e'' = e''' ->\n  (evalphi' h (rhoSubst x' v' r) a e'' ->\n  evalphi' h r a e''').\nProof.\n  induction e''; intros; subst; intros; try constructor; simpl in *.\n  - inversion H2; clear H2; subst.\n    econstructor.\n    * erewrite rhoVSeSubst in H4; eauto.\n    * erewrite rhoVSeSubst in H8; eauto.\n    * tauto.\n  - inversion H2; clear H2; subst.\n    econstructor.\n    * erewrite rhoVSeSubst in H4; eauto.\n    * erewrite rhoVSeSubst in H8; eauto.\n    * tauto.\n  - inversion H2; clear H2; subst.\n    econstructor.\n    * erewrite rhoVSeSubst in H7; eauto.\n    * tauto.\nQed.\nLemma rhoVSphiSubst2 : forall e'' e''' h r e' x' v' a, \n evale h r e' = Some v' ->\n phi'Subst x' e' e'' = e''' ->\n  (evalphi' h r a e''' ->\n  evalphi' h (rhoSubst x' v' r) a e'').\nProof.\n  induction e''; intros; subst; intros; try constructor; simpl in *.\n  - inversion H2; clear H2; subst.\n    specialize (rhoVSeSubst e0 (eSubst x' e' e0) h r e' x' v').\n    intros.\n    specialize (rhoVSeSubst e1 (eSubst x' e' e1) h r e' x' v').\n    intros.\n    intuition.\n    rewrite H8, H4 in *.\n    econstructor; eauto.\n  - inversion H2; clear H2; subst.\n    specialize (rhoVSeSubst e0 (eSubst x' e' e0) h r e' x' v').\n    intros.\n    specialize (rhoVSeSubst e1 (eSubst x' e' e1) h r e' x' v').\n    intros.\n    intuition.\n    rewrite H8, H4 in *.\n    econstructor; eauto.\n  - inversion H2; clear H2; subst.\n    specialize (rhoVSeSubst e0 (eSubst x' e' e0) h r e' x' v').\n    intros.\n    intuition.\n    rewrite H7 in *.\n    econstructor; eauto.\nQed.\n\nTheorem staSemPreservation : forall G (s'' : s) (s' : list s) (pre post : phi) initialHeap initialRho initialAccess S' finalHeap finalRho finalAccess sRem,\n  wellTyped G s'' ->\n  hoareSingle G pre s'' post ->\n  consistent initialHeap initialRho ->\n  evalphi initialHeap initialRho initialAccess pre ->\n  dynSem (initialHeap, (initialRho, initialAccess, s'' :: s') :: S') (finalHeap, (finalRho, finalAccess, sRem) :: S') ->\n  evalphi finalHeap finalRho finalAccess post.\nProof.\n  destruct s'';\n  intros;\n  inversion H4; clear H4;\n  inversion H1; clear H1;\n  simpl in H0;\n  try subst;\n  unfold evalphi; intros;\n  unfold consistent in H2.\n  - apply in_app_or in H1.\n    inversion H1; clear H1.\n    * admit.\n    * inversion H4; clear H4; try inversion H1; clear H1.\n      subst.\n      econstructor; simpl in *.\n      + rewrite H9.\n        instantiate (v1 := yv').\n        unfold HSubst.\n        assert (o_decb o' o' = true). unfold o_decb. unfold dec2decb. destruct (o_dec o' o'); auto.\n        rewrite H1.\n        eapply H2 in H9.\n        rewrite H9.\n        instantiate (res := (_, _)).\n        simpl.\n        unfold f_decb.\n        unfold string_decb.\n        unfold dec2decb.\n        destruct (string_dec f0 f0); auto.\n        contradict n; auto.\n      + eauto.\n      + auto.\n  - unfold evalphi in H3.\n    specialize (H3 (phi'Subst x0 e0 p')).\n    eapply rhoVSphiSubst2; eauto.\n    apply H3.\n    unfold phiSubst.\n    apply in_map.\n    assumption.\n  - rewrite H26 in *.\n    inversion H17; clear H17; subst.\n    clear H24.\n    generalize H26.\n    generalize H1.\n    generalize Cf'.\n    clear H26 H1 Cf'.\n    induction Cf'; simpl; intros.\n    * rewrite app_nil_r.\n      inversion H1; clear H1.\n      + subst.\n        econstructor; simpl.\n          unfold rhoSubst.\n          unfold x_decb.\n          unfold dec2decb.\n          destruct (x_dec x0 x0); try (contradict n; tauto).\n          auto.\n\n          auto.\n\n          unfold not. intros. inversion H1.\n      + admit. (* unfold evalphi in H3.\n        apply H3 in H4. clear H3.\n        eapply (evaleTClass G (ex x0) c initialHeap (rhoSubst x0 (vo o') initialRho)) in H0; simpl in H0.\n        inversion H0.\n          unfold rhoSubst in H1.\n          unfold x_decb in H1.\n          unfold dec2decb in H1.\n          destruct (x_dec x0 x0); try (contradict n; tauto).\n          inversion H1.\n        \n        case_eq (initialRho x0); intros.\n          .\n        specialize H2\n        eapply rhoVSphiSubst2 in H4; eauto.\n          instantiate (e' := ex x0).\n          simpl; auto.\n          generalize evaleTClass.\n          instantiate (e' := ev (vo o')).\n          simpl; auto.\n          \n          simpl; auto.\n          \n          unfold phi'Subst.\n          destruct p'; auto.\n          \n          *)\n    * admit.\n  - apply lengthId in H19.\n    simpl in H19.\n    contradict H19.\n    auto with arith.\n  - eapply rhoVSphiSubst2; eauto.\n    unfold evalphi in H3.\n    admit.\n  - unfold evalphi in H3.\n    intuition.\n  - unfold phiImplies in H17.\n    apply H17 in H3.\n    unfold evalphi in H3.\n    specialize (H3 p').\n    assert (In p' (p0 :: post)).\n      apply in_cons; assumption.\n    intuition.\n    destruct p'; inversion H5; clear H5; subst; econstructor; try eauto.\n    unfold Aexcept.\n    unfold except.\n    apply filter_In.\n    intuition.\n    apply negb_true_iff.\n    apply not_true_is_false.\n    unfold not.\n    intros.\n    apply existsb_exists in H3.\n    inversion H3; clear H3.\n    intuition.\n    unfold A'_decb in *.\n    apply andb_prop in H6.\n    intuition.\n    unfold name_decb, string_decb in *.\n    unfold dec2decb in *.\n    destruct (name_dec (fst (nameo o', f0)) (fst x0)); inversion H5.\n    destruct (string_dec (snd (nameo o', f0)) (snd x0)); inversion H8.\n    simpl in *.\n    clear H8 H5 H4 H17.\n    destruct x0. simpl in *.\n    subst.\n    unfold sfrmphi in *.\n    apply H20 in H1.\n    inversion H1; clear H1; subst.\n    inversion H6; clear H6; subst; simpl in *.\n    destruct p0; simpl in H3; try inversion H3.\n    destruct e1; simpl in H3.\n    * destruct v0; try (inversion H3; clear H3).\n      inversion H20.\n      + inversion H4; clear H4. subst.\n        inversion H7; clear H7. subst.\n\n    apply in_app_or in H1.\n    inversion H1; clear H1.\n    * apply H3 in H4.\n      eapply rhoVSphiSubst2; eauto.\n      assert (p' = phi'Subst xresult (ex x0) p').\n    assert (H333 := H3).\n    specialize (H3 p').\n    unfold phiSubst in H3.\n    rewrite (in_map_iff (phi'Subst x0 e0) post p') in H3.\n    assert (forall x : phi', (phi'Subst x0 e0 x = p' ∧ In x post) → evalphi' finalHeap initialRho finalAccess p').\n      intros.\n      apply H3.\n      eexists. eassumption.\n    \n    eapply rhoVSphiSubst.\n    \n    clear H3.\n    pose proof (H4 p').\n    destruct (phi'Subst x0 e0 p' == p').\n    * rewrite e1 in *. intuition.\n      inversion H5; clear H5; subst; econstructor.\n      + simpl in e1.\n        destruct e2; intros; simpl.\n          eauto.\n\n          unfold rhoSubst.\n          unfold x_decb.\n          unfold dec2decb.\n          destruct (x_dec x1 x0).\n            subst.\n            inversion e1; clear e1.\n            unfold x_decb in *.\n            unfold dec2decb in *.\n            case_eq (x_dec x0 x0); intros;\n            try (clear H5; contradict n; auto; fail).\n            rewrite H5 in *. rewrite H8 in *. clear e1 H5 H8.\n            simpl in *. rewrite H7 in *.\n            assumption.\n\n            simpl in H3. assumption.\n\n          inversion H3; clear H3.\n          assert (evale finalHeap (rhoSubst x0 v' initialRho) e2 = evale finalHeap initialRho e2).\n            inversion e1; clear e1.\n            eapply rhoVSeSubst; eauto. rewrite H5. assumption.\n          rewrite H3.\n          tauto.\n      + assert (evale finalHeap (rhoSubst x0 v' initialRho) e3 = evale finalHeap initialRho e3).\n          inversion e1; clear e1.\n          eapply rhoVSeSubst; eauto. rewrite H9. assumption.\n        rewrite H5.\n        eauto.\n      + tauto.\n      + simpl in e1.\n        destruct e2; simpl.\n          eauto.\n\n          unfold rhoSubst.\n          unfold x_decb.\n          unfold dec2decb.\n          destruct (x_dec x1 x0).\n            subst.\n            inversion e1; clear e1.\n            unfold x_decb in *.\n            unfold dec2decb in *.\n            case_eq (x_dec x0 x0); intros;\n            try (clear H5; contradict n; auto; fail).\n            rewrite H5 in *. rewrite H9 in *. clear e1 H5 H9.\n            simpl in *. rewrite H7 in *.\n            assumption.\n\n            simpl in H3. assumption.\n\n          inversion H3; clear H3.\n          assert (evale finalHeap (rhoSubst x0 v' initialRho) e2 = evale finalHeap initialRho e2).\n            inversion e1; clear e1.\n            eapply rhoVSeSubst; eauto. rewrite H5. assumption.\n          rewrite H3.\n          tauto.\n      + assert (evale finalHeap (rhoSubst x0 v' initialRho) e3 = evale finalHeap initialRho e3).\n          inversion e1; clear e1.\n          eapply rhoVSeSubst; eauto. rewrite H10. assumption.\n        rewrite H5.\n        eauto.\n      + tauto.\n      + simpl in *.\n        unfold rhoSubst.\n        destruct (x_decb x' x0); inversion e1.\n        eauto.\n      + assumption.\n    * specialize (H333 p').\n      clear H4.\n      destruct p'; simpl in *.\n      + intuition.\n      + econstructor.\n        admit. admit. admit.\n      + econstructor.\n        admit. admit. admit.\n      + econstructor.\n          simpl.\n          unfold rhoSubst.\n          destruct (x_decb x1 x0).\n        \n         clear e1.\n        simpl in *.\n\ninversion e1; clear e1.\n          \n          clear H3 H8.\n          inversion e1; clear e1.\n          rewrite H5.\n          rewrite H8.\n\n      + econstructor.\n    intuition.\n    SearchAbout (forall).\n    specialize (H3 p').\n    destruct p'; try constructor.\n    * econstructor.\n      \n\n    SearchPattern (((exists _, _) -> _) -> forall _, _ -> _).\n    SearchAbout In.\n    rewrite in_map in H3.\n     econstructor.\n    \n\n\nTheorem staSemSound : forall (prog : program) (body : list s) (pre post : phi) initialHeap initialRho initialAccess S',\n  @hoare prog pre body post ->\n  evalphi initialHeap initialRho initialAccess pre ->\n  exists finalHeap finalRho finalAccess, (\n    @dynSemStar prog (initialHeap, (initialRho, initialAccess, body) :: S') (finalHeap, (finalRho, finalAccess, []) :: S') /\\\n    evalphi finalHeap finalRho finalAccess post\n  ).\nProof.\n  intro prog.\n  induction body; intros.\n  - repeat eexists.\n    * constructor.\n    * inversion H0.\n      subst.\n      assumption.\n  - inversion H0. clear H0.\n    subst.\n    specialize (IHbody q1 post).\n    destruct a; inversion H4; clear H4; subst.\n    * edestruct IHbody; clear IHbody.\n      + eapply hoareImplies; repeat eauto.\n      + econstructor.\n      ++  eauto.\n      ++  specialize (AexceptReverse initialAccess); intros.\n          rewrite H0.\n          eauto.\n      ++  econstructor.\n          ** simpl.\n          inversion H0; clear H0.\n          inversion H2; clear H2.\n          inversion H0; clear H0.\n          instantiate (initialAccess := x2).\n          symmetry in H2. rewrite H2 in *.\n          apply H1.\n\n    edestruct IHbody; clear IHbody.\n\n    Focus 3.\n      inversion H0; clear H0.\n      inversion H2; clear H2.\n      inversion H0; clear H0.\n      repeat eexists; eauto.\n      econstructor.\n      + destruct a; inversion H4; clear H4; subst.\n    \n\n    + eapply hoareImplies; repeat eauto.\n    +\n    + eapply hoareSingleEvalPhi; repeat eauto.\n    + inversion H0; clear H0.\n      inversion H2; clear H2.\n      inversion H0; clear H0.\n      repeat eexists; eauto.\n\n\n\n    destruct a; inversion H4; clear H4; subst.\n    * edestruct IHbody; clear IHbody.\n      + eapply hoareImplies; repeat eauto.\n      + econstructor.\n      ++  eauto.\n      ++  specialize (AexceptReverse initialAccess); intros.\n          inversion H0; clear H0.\n          inversion H2; clear H2.\n          inversion H0; clear H0.\n          instantiate (initialAccess := x2).\n          symmetry in H2. rewrite H2 in *.\n          apply H1.\n\n\n\n\n      destruct a.\n      * repeat econstructor.\n        ++ simpl. .econstructor.\n      econstructor.\n      * destruct a.\n      exists x0. exists x1. exists x2.\n      repeat eexists.\n      ++ econstructor.\n      repeat eexists; eauto.\n      econstructor; eauto.\n      destruct a.\n    inversion H4; clear H4; subst;\n    repeat eexists.\n    * \n      econstructor;\n      edestruct IHbody.\n      + econstructor.\n        auto.\n      + edestruct IHbody.\n        specialize (IHbody initialHeap (rhoSubst x' vnull initialRho) initialAccess S').\n        destruct IHbody.\n        assert \n        erewrite IHbody.\n        instantiate (b := (_, _)).\n        admit.\n      + \n    rewrite ESSStep.\n    \n    apply IHbody.\n  generalize body. clear body\n\n\nTheorem staSemSoundCorollary : forall prog : program,\n  @hoare prog phiTrue (getMain prog) phiTrue -> exists endState : execState, @dynSemFull prog (newHeap, [(newRho, newAccess, getMain prog)]) endState.\nProof.\n  destruct prog as [classes main]; simpl.\n  generalize main. clear main.\n  induction main; intros.\n  - unfold runsThrough.\n    eexists.\n    split.\n    * constructor.\n    * unfold isFinished.\n      repeat eexists.\n  - destruct main.\n    * \n  \n  simpl in *.\n  \n  \n\n(* playground *)\nOpen Scope string_scope.\n\nNotation \"AA '⊢sfrme' ee\" := (sfrme AA ee) (at level 90).\n\nPrint sfrme.\nPrint dynSem.\n\nNotation \"classes 'main:' main\" := (Program classes main) (at level 100).\nNotation \"'class' c { fs ms }\" := (Cls c fs ms).\n\nCheck (Cls \"a\" [] []).\n\n\n\n", "meta": {"author": "olydis", "repo": "CoqExperiments", "sha": "78b5465a75e5c09c4cf0ad60e9b4de651fc1193a", "save_path": "github-repos/coq/olydis-CoqExperiments", "path": "github-repos/coq/olydis-CoqExperiments/CoqExperiments-78b5465a75e5c09c4cf0ad60e9b4de651fc1193a/GradVer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547238, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22418191751325542}}
{"text": "\nRequire Coq.Program.Tactics.\nRequire Coq.Program.Wf.\n\nRequire Prelude.\nRequire Simple.\nRequire GhcShow.\nImport BinInt.\n\nExample Simple_show_123: Simple.showInt 321%Z = GHC.Base.hs_string__ \"321\".\nProof.\n  simpl.\n  unfold Simple.showInt.\n  unfold Wf.wfFix2.\n  unfold Wf.wfFix1.\n  simpl.\n  rewrite ! Coq.Program.Wf.WfExtensionality.fix_sub_eq_ext.\n  simpl.\n  rewrite ! Coq.Program.Wf.WfExtensionality.fix_sub_eq_ext.\n  simpl.\n  rewrite ! Coq.Program.Wf.WfExtensionality.fix_sub_eq_ext.\n  simpl.\n  rewrite ! Coq.Program.Wf.WfExtensionality.fix_sub_eq_ext.\n  simpl.\n  reflexivity.\nQed.\n\nExample show_321: GhcShow.showInt 321%Z = Simple.showInt 321%Z.\nProof.\n  unfold Simple.showInt.\n  unfold GhcShow.showInt.\n  unfold GhcShow.integerToString.\n  unfold Wf.wfFix2.\n  unfold Wf.wfFix1.\n  simpl.\n  rewrite ! Coq.Program.Wf.WfExtensionality.fix_sub_eq_ext.\n  simpl.\n  rewrite ! Coq.Program.Wf.WfExtensionality.fix_sub_eq_ext.\n  simpl.\n  rewrite ! Coq.Program.Wf.WfExtensionality.fix_sub_eq_ext.\n  simpl.\n  rewrite ! Coq.Program.Wf.WfExtensionality.fix_sub_eq_ext.\n  simpl.\n  reflexivity.\nQed.\n\nExample show_n456: GhcShow.showInt (-456)%Z = Simple.showInt (-456)%Z.\nProof.\n  unfold Simple.showInt.\n  unfold GhcShow.showInt.\n  unfold GhcShow.integerToString.\n  unfold Wf.wfFix2.\n  unfold Wf.wfFix1.\n  simpl.\n  rewrite ! Coq.Program.Wf.WfExtensionality.fix_sub_eq_ext.\n  simpl.\n  rewrite ! Coq.Program.Wf.WfExtensionality.fix_sub_eq_ext.\n  simpl.\n  rewrite ! Coq.Program.Wf.WfExtensionality.fix_sub_eq_ext.\n  simpl.\n  rewrite ! Coq.Program.Wf.WfExtensionality.fix_sub_eq_ext.\n  simpl.\n  reflexivity.\nQed.\n", "meta": {"author": "HMPerson1", "repo": "hs-coq-opt", "sha": "1073832cd86e09d537735c191c64c73842cc64b0", "save_path": "github-repos/coq/HMPerson1-hs-coq-opt", "path": "github-repos/coq/HMPerson1-hs-coq-opt/hs-coq-opt-1073832cd86e09d537735c191c64c73842cc64b0/show-int/Proofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22404405826704674}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom extructures Require Import ord fmap.\nFrom CoqUtils Require Import hseq word.\nRequire Import lib.utils common.types symbolic.symbolic.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport DoNotation.\n\nSection WithClasses.\n\nContext {mt : machine_types}\n        {ops : machine_ops mt}\n        {sp : Symbolic.params}.\n\nVariable table : Symbolic.syscall_table mt.\n\nImport Symbolic.\n\nLocal Open Scope word_scope.\nLocal Notation \"x .+1\" := (x + 1).\n\nDefinition stepf (st : state mt) : option (state mt) :=\n  let 'State mem reg pc@tpc extra := st in\n  match mem pc with\n  | Some iti =>\n    let: i@ti := iti in\n    do! instr <- decode_instr i;\n    match instr with\n    | Nop =>\n      let mvec := IVec NOP tpc ti [hseq] in\n      next_state_pc st mvec (pc.+1)\n    | Const n r =>\n      do! old <- reg r;\n      let: _@told := old in\n      let ivec := IVec CONST tpc ti [hseq told] in\n      next_state_reg st ivec r (swcast n)\n    | Mov r1 r2 =>\n      do! a1 <- reg r1;\n      let: w1@t1 := a1 in\n      do! a2 <- reg r2;\n      let: _@told := a2 in\n      let mvec := IVec MOV tpc ti [hseq t1;told] in\n      next_state_reg st mvec r2 w1\n    | Binop op r1 r2 r3 =>\n      do! a1 <- reg r1;\n      let: w1@t1 := a1 in\n      do! a2 <- reg r2;\n      let: w2@t2 := a2 in\n      do! a3 <- reg r3;\n      let: _@told := a3 in\n      let mvec := IVec (BINOP op) tpc ti [hseq t1;t2;told] in\n      next_state_reg st mvec r3 (binop_denote op w1 w2)\n    | Load r1 r2 =>\n      do! a1 <- reg r1;\n      let: w1@t1 := a1 in\n      do! amem <- mem w1;\n      let: w2@t2 := amem in\n      do! a2 <- reg r2;\n      let: _@told := a2 in\n      let mvec := IVec LOAD tpc ti [hseq t1;t2;told] in\n      next_state_reg st mvec r2 w2\n    | Store r1 r2 =>\n      do! a1 <- reg r1;\n      let: w1@t1 := a1 in\n      do! amem <- mem w1;\n      let: _@told := amem in\n      do! a2 <- reg r2;\n      let: w2@t2 := a2 in\n      let mvec := IVec STORE tpc ti [hseq t1;t2;told] in\n      @next_state _ _ st mvec (fun ov =>\n         do! mem' <- updm mem w1 w2@(tr ov);\n         Some (State mem' reg (pc.+1)@(trpc ov) extra))\n    | Jump r =>\n      do! a <- reg r;\n      let: w@t1 := a in\n      let mvec := IVec JUMP tpc ti [hseq t1] in\n      next_state_pc st mvec w\n    | Bnz r n =>\n      do! a <- reg r;\n      let: w@t1 := a in\n      let pc' := pc + (if w == 0\n                       then 1 else swcast n) in\n      let ivec := IVec BNZ tpc ti [hseq t1] in\n      next_state_pc st ivec pc'\n    | Jal r =>\n      do! a <- reg r;\n      let: w@t1 := a in\n      do! oldtold <- reg ra;\n      let: _@told := oldtold in\n      let mvec := IVec JAL tpc ti [hseq t1; told] in\n      next_state_reg_and_pc st mvec ra (pc.+1) w\n    | JumpEpc | AddRule | GetTag _ _ | PutTag _ _ _ | Halt =>\n      None\n    end\n  | None =>\n    match mem pc with\n    | None =>\n      do! sc <- table pc;\n      run_syscall sc st\n    | Some _ =>\n      None\n    end\n  end.\n\nLemma stepP :\n  forall st st',\n    stepf st = Some st' <->\n    step table st st'.\nProof.\n  intros st st'. split; intros STEP.\n  { destruct st as [mem reg [pc tpc] int].\n    move: STEP => /=; case GET: (mem pc) => [[i ti]|] //= STEP;\n    apply obind_inv in STEP.\n    - destruct STEP as (instr & INSTR & STEP).\n      destruct instr; try discriminate;\n          repeat match goal with\n             | STEP : (do! x <- ?t; _) = Some _ |- _ =>\n               destruct t eqn:?; simpl in STEP; try discriminate\n             | x : atom _ _ |- _ =>\n               destruct x; simpl in *\n             | rv : ovec _ |- _ =>\n               destruct rv; simpl in *\n             | H : Some _ = Some _ |- _ =>\n               inversion H; subst; clear H\n           end;\n      s_econstructor (solve [eauto]).\n\n    - destruct STEP as (sc & GETCALL & STEP).\n      s_econstructor (solve [eauto]).\n  }\n  { unfold stepf.\n    inversion STEP; subst; rewrite PC; try (subst mv);\n    simpl;\n    repeat match goal with\n             | [H: ?Expr = _ |- context[?Expr]] =>\n               rewrite H; simpl\n           end; by reflexivity.\n  }\nQed.\n\nLemma stepP' :\n  forall st st',\n    reflect (step table st st') (stepf st == Some st').\nProof.\n  move => st st'.\n  apply (iffP eqP); by move => /stepP.\nQed.\n\nDefinition build_ivec st : option (ivec ttypes)  :=\n  match mem st (pcv st) with\n    | Some i =>\n      match decode_instr (vala i) with\n        | Some op =>\n          let part := @IVec ttypes (opcode_of op) (pct st) (taga i) in\n          match op return (hseq (tag_type ttypes) (inputs (opcode_of op)) ->\n                           ivec ttypes) -> option (ivec ttypes) with\n            | Nop => fun part => Some (part [hseq])\n            | Const n r => fun part =>\n                do! old <- regs st r;\n                Some (part [hseq taga old])\n            | Mov r1 r2 => fun part =>\n              do! v1 <- regs st r1;\n              do! v2 <- regs st r2;\n              Some (part [hseq (taga v1); (taga v2)])\n            | Binop _ r1 r2 r3 => fun part =>\n              do! v1 <- regs st r1;\n              do! v2 <- regs st r2;\n              do! v3 <- regs st r3;\n              Some (part [hseq (taga v1); (taga v2); (taga v3)])\n            | Load  r1 r2 => fun part =>\n              do! w1 <- regs st r1;\n              do! w2 <- (mem st) (vala w1);\n              do! old <- regs st r2;\n              Some (part [hseq (taga w1); (taga w2); (taga old)])\n            | Store  r1 r2 => fun part =>\n              do! w1 <- regs st r1;\n              do! w2 <- regs st r2;\n              do! w3 <- mem st (vala w1);\n              Some (part [hseq (taga w1); (taga w2); (taga w3)])\n            | Jump  r => fun part =>\n              do! w <- regs st r;\n              Some (part [hseq taga w])\n            | Bnz  r n => fun part =>\n              do! w <- regs st r;\n              Some (part [hseq taga w])\n            | Jal  r => fun part =>\n              do! w <- regs st r;\n              do! old <- regs st ra;\n              Some (part [hseq taga w; taga old])\n            | JumpEpc => fun _ => None\n            | AddRule => fun _ => None\n            | GetTag _ _ => fun _ => None\n            | PutTag _ _ _ => fun _ => None\n            | Halt => fun _ => None\n          end part\n        | None => None\n      end\n    | None =>\n      match table (pcv st) with\n        | Some sc =>\n          Some (IVec SERVICE (pct st) (entry_tag sc) [hseq])\n        | None => None\n      end\n  end.\n\nLemma step_build_ivec st st' :\n  step table st st' ->\n  exists ivec ovec,\n    build_ivec st = Some ivec /\\\n    transfer ivec = Some ovec.\nProof.\n  move/stepP.\n  rewrite {1}(state_eta st) /= /build_ivec.\n  case: (getm _ _) => [[i ti]|] //=; last first.\n    case: (getm _ _) => [sc|] //=.\n    rewrite /run_syscall /=.\n    case TRANS: (transfer _) => [ovec|] //= _.\n    by eauto.\n  case: (decode_instr i) => [instr|] //=.\n  rewrite /next_state_pc /next_state_reg /next_state_reg_and_pc /next_state.\n  by destruct instr; move=> STEP; match_inv; first [ eauto | discriminate ].\nQed.\n\nEnd WithClasses.\n", "meta": {"author": "micro-policies", "repo": "micro-policies-coq", "sha": "28163163c88387fc24475ed219f5705f9e0d4fc6", "save_path": "github-repos/coq/micro-policies-micro-policies-coq", "path": "github-repos/coq/micro-policies-micro-policies-coq/micro-policies-coq-28163163c88387fc24475ed219f5705f9e0d4fc6/symbolic/exec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22404405826704674}}
{"text": "From RecoveryRefinement Require Import Lib.\n\nRequire Export Examples.Logging.TxnDiskAPI.\nRequire Export Examples.Logging.LogEncoding.\nRequire Export Examples.ReplicatedDisk.OneDiskAPI.\n\nFrom Array Require Import Array.\n\nImport ProcNotations.\nLocal Open Scope proc.\n\n(* We encode the log with two blocks: a header and a descriptor block. The header has a bit which commits the transaction: log_commit first records the transaction completes and then applies it, so that recovery (also log_apply) can see that the transaction is committed and finish applying it. *)\n\n(* The logical log is either:\n- a partial list of writes, or\n- a committed list of writes.\n\nThe partial list of writes is represented by a committed flag of false followed\nby [hdr.(log_length)] addresses from the descriptor block (the rest are ignored)\npaired with the values in the log region of the disk. The length of the log is\nrestricted by LogHdr so that there are always enough addresses in the descriptor\nblock and spaces on disk for the values.\n\nA committed transaction is represented almost the same way, except that the committed flag is set to true.\n\nOn crash committed will generally be false, so the logical log is empty and the\nwhole thing is aborted, reverting the disk to its old state. The one exception\nis after writing the commit header but before finishing apply.\n *)\n\n(* Once we have a data region + logical log, we map that to the TxnDiskAPI's two\ndisks by setting the old disk to the data region and the new disk to the data\nregion + writes from the logical log. *)\n\nAxiom LogHdr_fmt: block_encoder LogHdr.\nAxiom Descriptor_fmt: block_encoder Descriptor.\n\nDefinition read a := Call (D.op_read a).\nDefinition write a v := Call (D.op_write a v).\nDefinition size := Call (D.op_size).\n\nDefinition gethdr: proc D.Op LogHdr :=\n  b <- read 0;\n    Ret (LogHdr_fmt.(decode) b).\n\nDefinition writehdr (hdr:LogHdr) :=\n  write 0 (LogHdr_fmt.(encode) hdr).\n\nDefinition hdr_full (hdr:LogHdr) :\n  {hdr.(log_length) = LOG_LENGTH} + {hdr.(log_length) < LOG_LENGTH}.\n  destruct (lt_dec (hdr.(log_length)) LOG_LENGTH).\n  - right; auto.\n  - pose proof (hdr.(log_length_ok)).\n    left; lia.\nDefined.\n\nDefinition hdr_inc (hdr:LogHdr) (pf:hdr.(log_length) < LOG_LENGTH) : LogHdr.\n  refine {| committed := hdr.(committed);\n            log_length := hdr.(log_length) + 1; |}.\n  abstract lia.\nDefined.\n\nDefinition empty_hdr : LogHdr.\n  refine {| committed := false;\n            log_length := 0; |}.\n  abstract lia.\nDefined.\n\nDefinition hdr_setcommit (hdr:LogHdr) : LogHdr :=\n  {| committed := true;\n     log_length := hdr.(log_length);\n     log_length_ok := hdr.(log_length_ok); |}.\n\nDefinition getdesc: proc D.Op Descriptor :=\n  b <- read 1;\n    Ret (Descriptor_fmt.(decode) b).\n\nDefinition writedesc (ds:Descriptor) :=\n  write 1 (Descriptor_fmt.(encode) ds).\n\nGlobal Instance def_desc : Default Descriptor.\n  refine {| addresses := List.repeat 0 LOG_LENGTH |}.\n  apply repeat_length.\nDefined.\n\nDefinition add_addr (ds:Descriptor) (idx:nat) (a:addr) : Descriptor.\n  refine {| addresses := assign ds.(addresses) idx a; |}.\n  rewrite length_assign.\n  apply ds.(addresses_length).\nDefined.\n\n(* log init establishes that the log and descriptor are valid (note that the\nblock_encoder does not assume that every block is parseable, only the encodings)\nand correspond to an empty log *)\nDefinition log_init :=\n  sz <- size;\n    if lt_dec sz (2+LOG_LENGTH) then\n      Ret InitFailed\n    else\n      _ <- writehdr empty_hdr;\n    _ <- writedesc default; (* value is unimportant, ignored due to log_length = 0 *)\n    Ret Initialized.\n\nDefinition log_size :=\n  sz <- size;\n    (* this subtraction never underflows because of the size established by init\n    (and the size is an invariant) *)\n    Ret (sz-(2+LOG_LENGTH)).\n\n(* manipulating the log region *)\nDefinition set_desc desc (i:nat) a v :=\n  _ <- writedesc (add_addr desc i a);\n    write (2+i) v.\n\nDefinition get_logwrite desc (i:nat) :=\n    let a := sel desc.(addresses) i in\n    v <- read (2+i);\n      Ret (a, v).\n\n(* manipulating the data region *)\nDefinition data_read a :=\n  read (2+LOG_LENGTH+a).\n\nDefinition data_write a v :=\n  write (2+LOG_LENGTH+a) v.\n\n(* reads just go directly to the data region (transactions don't read their own\nwrites) *)\nDefinition log_read a :=\n  data_read a.\n\nDefinition log_write a v :=\n  (* I believe out-of-bounds reads at the logical level are always translated to\n  out-of-bounds applies when we attempt to apply the log; this works but is\n  complicated, since the write does actually take space in the physical log but\n  won't do anything when applied. *)\n  hdr <- gethdr;\n    match hdr_full hdr with\n    | left _ => Ret TxnD.WriteErr\n    | right pf =>\n      (* here we've established that the log has at least one position left *)\n      desc <- getdesc;\n        _ <- writehdr (hdr_inc hdr pf);\n        (* a crash here doesn't matter because [committed = false] and therefore\n        the entire log is logically empty *)\n        _ <- set_desc desc hdr.(log_length) a v;\n          (* now the partial transaction has one more write; the descriptor\n          block has the correct address at the new index, and the corresponding\n          value is in the log at the paired address *)\n      Ret TxnD.WriteOK\n    end.\n\n(** log_apply (which is also the recovery procedure) *)\n\n(* Crashes during log_apply will leave the physical disk in a partial state,\nwhere some of the committed writes have been applied, but log_apply always\nstarts at the beginning. Its sub-procedures [apply_at] and [apply_upto] only run\nwhen [committed := true] and always have i < hdr.(log_length). *)\n\n(* apply_at guarantees that index i in the log is applied *)\nDefinition apply_at desc (i:nat) :=\n  a_v <- get_logwrite desc i;\n    let '(a, v) := a_v in\n    _ <- data_write a v;\n      Ret tt.\n\n(* [apply_upto] applies entries i through (len-1) from the log; if it crashes, the\nlog is still partially applied (and it doesn't much matter how much, since\nlog_apply always applies from the beginning).\n\n [apply_upto] maintains an invariant in its recursive subcalls that [i <=\n len]. *)\nFixpoint apply_upto desc i len :=\n  match len with\n  | 0 => Ret tt\n  | S len =>\n    _ <- apply_at desc i;\n      apply_upto desc (i+1) len\n  end.\n\n(* log_apply is just a wrapper around apply_upto that reads the metadata; note\nthat it establishes the invariants of [apply_upto] by checking for a commit.\n\nIts postcondition/recovery postcondition says the log is now empty, because it\nexplicitly sets the header. Note that the descriptor block does not need to be\nchanged because it's ignored with a log length of 0. *)\nDefinition log_apply :=\n  hdr <- gethdr;\n    _ <- if hdr.(committed) then\n          desc <- getdesc;\n            apply_upto desc 0 hdr.(log_length)\n        else Ret tt;\n    writehdr empty_hdr.\n\nDefinition commit :=\n  hdr <- gethdr;\n    _ <- writehdr (hdr_setcommit hdr);\n    (* here we can crash in a committed state, where we need to apply *)\n    log_apply.\n\nDefinition recovery := log_apply.\n", "meta": {"author": "mit-pdos", "repo": "argosy", "sha": "a6a5aa0d3868efd4ada0b40927b5748e5d8967d3", "save_path": "github-repos/coq/mit-pdos-argosy", "path": "github-repos/coq/mit-pdos-argosy/argosy-a6a5aa0d3868efd4ada0b40927b5748e5d8967d3/src/Examples/Logging/Impl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22404155442641654}}
{"text": "From iris.program_logic Require Import adequacy.\nFrom iris_time.heap_lang Require Import notation proofmode.\nFrom iris_time Require Import Base Reduction Tactics.\nFrom iris_time Require Export Translation.\n\nImplicit Type e : expr.\nImplicit Type v : val.\nImplicit Type σ : state.\nImplicit Type t : list expr.\nImplicit Type K : ectx heap_ectx_lang.\nImplicit Type ℓ : loc.\nImplicit Type m n : nat.\nImplicit Type φ : val → Prop.\n\n\n\n(* Our definition of “tick” will depend on a location. This is made a typeclass\n * so as to be inferred automatically. *)\nClass TickCounter := { tick_counter : loc }.\nNotation \"S« σ , n »\" := (<[tick_counter := LitV (LitInt n%nat)]> (translationS σ%V)).\n(* Notation \"« σ , n »\" := (<[ℓ := LitV (LitInt n%nat)]> (translationS σ%V)) (only printing). *)\nLocal Notation ℓ := tick_counter.\n\n\n(* This whole file is parameterized by a “runtime_error” value: *)\nSection Simulation.\nContext (runtime_error : val).\n\n\n\n(*\n * Definition of “tick”\n *)\n\nLocal Instance generic_tick {Hloc : TickCounter} : Tick :=\n (rec: \"tick\" \"x\" :=\n    let: \"k\" := ! #ℓ in\n    if: \"k\" ≤ #0 then\n      runtime_error #()\n    else if: CAS #ℓ \"k\" (\"k\" - #1) then\n      \"x\"\n    else\n      \"tick\" \"x\")%V.\n\n\n(*\n * Operational behavior of “tick”\n *)\n\nSection Tick_exec.\n\n  Context {Hloc : TickCounter}.\n\n  Lemma exec_tick_success n v σ :\n    prim_exec  (tick v) (<[ℓ := #(S n)]> σ)  v (<[ℓ := #n]> σ)  [].\n  Proof.\n    remember (Z.of_nat (S n)) as Sn.\n    unlock tick generic_tick.\n    eapply prim_exec_cons_nofork. (* Initial β-redex *)\n    { by prim_step. }\n    simpl. eapply prim_exec_cons_nofork. (* Load of ℓ *)\n    { prim_step; apply lookup_insert. }\n    simpl. eapply prim_exec_cons_nofork. (* First redex of let *)\n    { by prim_step. }\n    simpl. eapply prim_exec_cons_nofork. (* Second redex of let *)\n    { by prim_step. }\n    simpl. eapply prim_exec_cons_nofork. (* Comparison [\"k\" ≤ #0] *)\n    { by prim_step. }\n    rewrite /= bool_decide_false; [|lia].\n    eapply prim_exec_cons_nofork.        (* If *)\n    { by prim_step. }\n    simpl. eapply prim_exec_cons_nofork. (* Decrementing \"k\" *)\n    { by prim_step. }\n                                         (* CAS *)\n    simpl. eapply (prim_exec_cons_nofork _ _ _ (if: #true then _ else _)).\n    { prim_step; [apply lookup_insert|by left]. }\n    eapply prim_exec_cons_nofork.        (* If *)\n    { by prim_step. }\n    replace (Sn - 1) with (Z.of_nat n) by lia.\n    rewrite insert_insert.\n    apply prim_exec_nil.\n  Qed.\n\n  Lemma exec_tick_case_branch e1 v2 σ :\n    prim_exec  (tick_case_branch (λ: <>, e1) v2)%E  σ ((tick e1) v2) σ  [].\n  Proof.\n    unfold tick_case_branch ; unlock.\n    eapply prim_exec_cons_nofork.\n    { by prim_step. }\n    simpl. eapply prim_exec_cons_nofork.\n    { by prim_step. }\n    simpl. eapply prim_exec_cons_nofork.\n    { by prim_step. }\n    simpl. eapply prim_exec_cons_nofork.\n    { by prim_step. }\n    simpl. eapply prim_exec_cons_nofork.\n    { by prim_step. }\n    apply prim_exec_nil.\n  Qed.\n\nEnd Tick_exec.\n\n\n\n(*\n * Simulation lemma\n *)\n\nSection SimulationLemma.\n\n  Context {Hloc : TickCounter}.\n\n  Local Ltac exec_tick_success :=\n    lazymatch goal with\n    | |- prim_exec ?e _ _ _ _ =>\n        reshape_expr false e ltac:(fun K e' =>\n          eapply prim_exec_fill' with K e' _ ; [ done | done | ] ;\n          eapply exec_tick_success\n        )\n    end ;\n    done.\n  (* in this tactic, the parameter ‘afterwards’ allows to unify the expression\n   * resulting from the step before running the tactic ‘prim_step’;\n   * this matters when the reduction rule to apply is directed by the syntax of\n   * the result (more specifically, ‘CasFailS’ would be picked instead of\n   * ‘CasSucS’ if we did not unify the result with ‘#true’ beforehand). *)\n  Local Ltac tick_then_step_then afterwards :=\n    eapply prim_exec_transitive_nofork ; first (\n      exec_tick_success\n    ) ;\n    eapply prim_exec_cons_nofork, afterwards ; first (\n      prim_step\n    ).\n  Local Ltac tick_then_step_then_stop :=\n    tick_then_step_then prim_exec_nil.\n\n  Lemma simulation_head_step_success n e1 σ1 κ e2 σ2 efs :\n    σ2 !! ℓ = None →\n    head_step e1 σ1 κ e2 σ2 efs →\n    prim_exec «e1» S«σ1, S n» «e2» S«σ2, n» T«efs».\n  Proof.\n    intros Hℓ Hstep.\n    destruct Hstep as\n      [ (* RecS *) f x e σ\n      | (* PairS *) v1 v2 σ\n      | (* InjLS *) v σ\n      | (* InjRS *) v σ\n      | (* BetaS *) f x e1 v2 e' σ  ->\n      | (* UnOpS *) op v v' σ  Hopeval\n      | (* BinOpS *) op v1 v2 v' σ  Hopeval\n      | (* IfTrueS  *) e1 e2 σ\n      | (* IfFalseS *) e1 e2 σ\n      | (* FstS *) v1 v2 σ\n      | (* SndS *) v1 v2 σ\n      | (* CaseLS *) v0 e1 e2 σ\n      | (* CaseRS *) v0 e1 e2 σ\n      | (* ForkS *) e σ\n      | (* AllocS *) v σ l  Hfree_l\n      | (* LoadS *) l v σ  Hbound_l\n      | (* StoreS *) l v σ  Hisbound_l\n      | (* CasFailS *) l v1 v2 vl σ  Hbound_l Hneq_vl_v1\n      | (* CasSucS *) l v1 v2 σ  Hbound_l\n      | (* FaaS *) l i1 i2 σ  Hbound_l\n      ];\n    simpl_trans;\n    (try (\n      assert (ℓ ≠ l) as I by (by apply lookup_insert_None in Hℓ as [ _ I ]) ;\n      rewrite translationS_insert insert_commute ; last exact I\n    )).\n    (* RecS f x e σ : *)\n    - eapply (prim_exec_cons _ _ _ _ _ [] _ _ []).\n      + prim_step.\n      + exec_tick_success.\n    (* PairS *)\n    - tick_then_step_then_stop.\n    (* InjLS *)\n    - tick_then_step_then_stop.\n    (* InjRS *)\n    - tick_then_step_then_stop.\n    (* BetaS f x e1 v2 e' σ : *)\n    - rewrite 2! translation_subst'.\n      by tick_then_step_then_stop.\n    (* UnOpS op v v' σ : *)\n    - tick_then_step_then_stop.\n      by apply un_op_eval_translation.\n    (* BinOpS op v1 v2 v' σ : *)\n    - tick_then_step_then_stop.\n      by apply bin_op_eval_translation.\n    (* IfTrueS e1 e2 σ : *)\n    - tick_then_step_then_stop.\n    (* IfFalseS e1 e2 σ : *)\n    - tick_then_step_then_stop.\n    (* FstS v1 v2 σ : *)\n    - tick_then_step_then_stop.\n    (* SndS v1 v2 σ : *)\n    - tick_then_step_then_stop.\n    (* CaseLS v0 e1 e2 σ : *)\n    - tick_then_step_then exec_tick_case_branch.\n    (* CaseRS v0 e1 e2 σ : *)\n    - tick_then_step_then exec_tick_case_branch.\n    (* ForkS e σ : *)\n    - replace T« [e] » with ([« e »] ++ []) by apply app_nil_r.\n      eapply prim_exec_cons.\n      + prim_step.\n      + exec_tick_success.\n    (* AllocS v σ l : *)\n    - tick_then_step_then_stop.\n      apply lookup_insert_None ; auto using lookup_translationS_None.\n    (* LoadS l v σ : *)\n    - tick_then_step_then_stop.\n      assert (ℓ ≠ l) as I by (intros <- ; rewrite -> Hℓ in * ; discriminate).\n      rewrite lookup_insert_ne ; last exact I.\n      by apply lookup_translationS_Some.\n    (* StoreS l v σ : *)\n    - tick_then_step_then_stop.\n      rewrite lookup_insert_ne ; last exact I.\n      by apply lookup_translationS_is_Some.\n    (* CasFailS l v1 v2 vl σ : *)\n    - tick_then_step_then_stop.\n      + assert (ℓ ≠ l) as I by (intros <- ; rewrite -> Hℓ in * ; discriminate).\n        rewrite lookup_insert_ne ; last done.\n        by apply lookup_translationS_Some.\n      + eauto using translationV_injective.\n      + by apply vals_cas_compare_safe_translationV.\n    (* CasSucS l v1 v2 σ : *)\n    - tick_then_step_then_stop.\n      + rewrite lookup_insert_ne ; last exact I.\n        by apply lookup_translationS_Some.\n      + by apply vals_cas_compare_safe_translationV.\n    (* FaaS l i1 i2 σ : *)\n    - tick_then_step_then_stop.\n      rewrite lookup_insert_ne ; last exact I.\n      change (#i1)%V with V« #i1 ».\n      by apply lookup_translationS_Some.\n  Qed.\n\n  Lemma simulation_prim_step_success n e1 σ1 κ e2 σ2 efs :\n    σ2 !! ℓ = None →\n    prim_step e1 σ1 κ e2 σ2 efs →\n    prim_exec «e1» S«σ1, S n» «e2» S«σ2, n» T«efs».\n  Proof.\n    intros Hℓ [ K e1' e2' -> -> H ].\n    rewrite 2! translation_fill.\n    by eapply prim_exec_fill, simulation_head_step_success.\n  Qed.\n\n  Lemma simulation_step_success n t1 σ1 κ t2 σ2 :\n    σ2 !! ℓ = None →\n    step (t1, σ1) κ (t2, σ2) →\n    rtc erased_step (T«t1», S«σ1, S n») (T«t2», S«σ2, n»).\n  Proof.\n    intros Hℓ Hstep.\n    destruct Hstep as [ e1 σ1_ e2 σ2_ efs t t' E1 E2 Hprimstep ] ;\n    injection E1 as -> <- ;\n    injection E2 as -> <-.\n    repeat rewrite ? fmap_app ? fmap_cons.\n    by eapply exec_frame_singleton_thread_pool, prim_exec_exec,\n       simulation_prim_step_success.\n  Qed.\n\n  Lemma simulation_exec_success m n t1 σ1 t2 σ2 :\n    σ2 !! ℓ = None →\n    relations.nsteps erased_step m (t1, σ1) (t2, σ2) →\n    rtc erased_step (T«t1», S«σ1, m+n») (T«t2», S«σ2, n»).\n  Proof.\n    make_eq (t1, σ1) as config1 E1.\n    make_eq (t2, σ2) as config2 E2.\n    intros Hℓ Hnsteps.\n    revert t1 σ1 E1 ;\n    induction Hnsteps as [ config | m' config1 (t3, σ3) config2 [κ Hstep] Hsteps IHnsteps ] ;\n    intros t1 σ1 E1.\n    - destruct E2 ; injection E1 as -> ->.\n      apply rtc_refl.\n    - destruct E2, E1.\n      specialize (IHnsteps eq_refl t3 σ3 eq_refl).\n      assert (σ3 !! ℓ = None) as Hℓ3 by (eapply loc_fresh_in_dom_nsteps ; cycle 1 ; eassumption).\n      eapply rtc_transitive.\n      + eapply simulation_step_success ; cycle -1 ; eassumption.\n      + apply IHnsteps.\n  Qed.\n\n  Lemma simulation_exec_success' m n t1 σ1 t2 σ2 :\n    σ2 !! ℓ = None →\n    (m ≤ n)%nat →\n    relations.nsteps erased_step m (t1, σ1) (t2, σ2) →\n    rtc erased_step (T«t1», S«σ1, n») (T«t2», S«σ2, n-m»).\n  Proof.\n    intros Hℓ I.\n    replace #n with #(m + (n-m))%nat ; last (repeat f_equal ; lia).\n    by apply simulation_exec_success.\n  Qed.\n\n  (* from a reduction of the translated expression,\n   * deduce a reduction of the source expression. *)\n\n  (* note: this does not depend on the operational behavior of `tick`. *)\n\n  Local Ltac exhibit_prim_step e2 :=\n    eexists _, e2, _, _ ; simpl ; prim_step.\n\n  Local Ltac eexhibit_prim_step :=\n    eexists _, _, _, _ ; simpl ; prim_step.\n\n  Lemma active_item_translation_reducible ki v σ m :\n    ectx_item_is_active ki →\n    loc_fresh_in_expr ℓ (fill_item ki v) →\n    reducible (fill_item Ki«ki» V«v») S«σ, m» →\n    reducible (fill_item ki v) σ.\n  Proof.\n    intros Hactive Hfresh (e2' & σ2' & efs &\n                           [κ Hheadstep % active_item_prim_step_is_head_step]) ;\n      last by apply is_active_translationKi.\n    make_eq (fill_item Ki«ki» V«v») as e1' Ee1' ; rewrite Ee1' in Hheadstep.\n    make_eq (S«σ, m») as σ1' Eσ1' ; rewrite Eσ1' in Hheadstep.\n    destruct Hheadstep  as\n      [ (* RecS *) f x e σ1\n      | (* PairS *) v1 v2 σ1\n      | (* InjLS *) v1 σ1\n      | (* InjRS *) v1 σ1\n      | (* BetaS *) f x e1 v2 e' σ1  ->\n      | (* UnOpS *) op v1 v' σ1  Hopeval\n      | (* BinOpS *) op v1 v2 v' σ1  Hopeval\n      | (* IfTrueS  *) e1 e2 σ1\n      | (* IfFalseS *) e1 e2 σ1\n      | (* FstS *) v1 v2 σ1\n      | (* SndS *) v1 v2 σ1\n      | (* CaseLS *) v0 e1 e2 σ1\n      | (* CaseRS *) v0 e1 e2 σ1\n      | (* ForkS *) e σ1\n      | (* AllocS *) v1 σ1 l  Hfree_l\n      | (* LoadS *) l v1 σ1  Hbound_l\n      | (* StoreS *) l v1 σ1  Hisbound_l\n      | (* CasFailS *) l v1 v2 vl σ1  Hbound_l Hneq_vl_v1\n      | (* CasSucS *) l v1 v2 σ1  Hbound_l\n      | (* FaaS *) l i1 i2 σ1  Hbound_l\n      ];\n    destruct ki ; try contradiction Hactive ; try discriminate Ee1' ;\n    injection Ee1' ; clear Ee1' ;\n    repeat (intros -> || intros <- || intros -> % translationV_lit_inv || intros E) ;\n    destruct Eσ1'.\n    (* replacing the state S«σ, m» with S«σ»: *)\n    all: first [\n        apply lookup_insert_None in Hfree_l as [Hfree_l _]\n      | apply lookup_insert_Some in Hbound_l as [ [<- _] | [_ Hbound_l] ] ; first naive_solver\n      | apply lookup_insert_is_Some in Hisbound_l as [ <- | [_ Hisbound_l] ] ; first naive_solver\n      | idtac\n    ].\n    (* PairS *)\n    - eexhibit_prim_step.\n    (* InjLS *)\n    - eexhibit_prim_step.\n    (* InjRS *)\n    - eexhibit_prim_step.\n    (* BetaS *)\n    - destruct v ; try discriminate E.\n      by eexhibit_prim_step.\n    (* UnOpS *)\n    - eexhibit_prim_step.\n      by eapply un_op_eval_translation_inv.\n    (* BinOpS *)\n    - eexhibit_prim_step.\n      by eapply bin_op_eval_translation_inv.\n    (* IfTrueS *)\n    - eexhibit_prim_step.\n    (* IfFalseS *)\n    - eexhibit_prim_step.\n    (* FstS *)\n    - destruct v ; try discriminate E.\n      eexhibit_prim_step.\n    (* SndS *)\n    - destruct v ; try discriminate E.\n      eexhibit_prim_step.\n    (* CaseLS *)\n    - destruct v ; try discriminate E.\n      eexhibit_prim_step.\n    (* CaseRS *)\n    - destruct v ; try discriminate E.\n      eexhibit_prim_step.\n    (* AllocS *)\n    - eexhibit_prim_step.\n      by eapply lookup_translationS_None_inv.\n    (* LoadS *)\n    - apply lookup_translationS_Some_inv in Hbound_l as (? & ? & _).\n      by eexhibit_prim_step.\n    (* StoreS *)\n    - eexhibit_prim_step.\n      by eapply lookup_translationS_is_Some_inv.\n    (* CasFailS *)\n    - apply lookup_translationS_Some_inv in Hbound_l as (? & ? & ->).\n      exhibit_prim_step (Val #false).\n      + done.\n      + intros ? % (f_equal translationV). contradiction.\n      + by apply vals_cas_compare_safe_translationV_inv.\n    (* CasSucS *)\n    - apply lookup_translationS_Some_inv in Hbound_l as (? & ? & -> % translationV_injective).\n      exhibit_prim_step (Val #true)%E.\n      done. by apply vals_cas_compare_safe_translationV_inv.\n    (* FaaS *)\n    - apply lookup_translationS_Some_inv in Hbound_l as (? & ? & -> % eq_sym % translationV_lit_inv).\n      by eexhibit_prim_step.\n  Qed.\n\n  (* assuming the safety of the translated expression,\n   * a proof that the original expression is m-safe. *)\n\n  Lemma safe_translation__nsafe_here m e σ :\n    loc_fresh_in_expr ℓ e →\n    (m > 0)%nat →\n    safe «e» S«σ, m» →\n    is_Some (to_val e) ∨ reducible e σ.\n  Proof.\n    intros Hfresh Im Hsafe.\n    (* case analysis on whether e is a value… *)\n    destruct (to_val e) as [ v | ] eqn:Hnotval.\n    (* — if e is a value, then we get the result immediately: *)\n    - left. eauto.\n    (* — if e is not a value, then we show that it is reducible: *)\n    - right.\n      (* we decompose e into a maximal evaluation context K and a head-redex: *)\n      pose proof (not_val_fill_active_item _ Hnotval) as He ; clear Hnotval.\n      destruct He as [ (K & x & ->) |\n                     [ (K & e1 & ->) |\n                     [ (K & f & x & e1 & ->) |\n                       (K & ki & v & -> & Hactive) ] ]].\n      (* — either e = K[Var x]: *)\n      + (* then [«fill K x»] is stuck: *)\n        exfalso. clear -Hsafe. rewrite translation_fill in Hsafe.\n        apply safe_fill_inv in Hsafe. destruct Hsafe as [_ Hsafe].\n        destruct (Hsafe _ _ x eq_refl (rtc_refl _ _)) as\n            [[? [=]]|(?&?&?&?&[K' ?? Hx ? Hred])]; first set_solver+; simpl in *.\n        destruct (decide (K' = [])) as [->|(K''&Ki&->)%exists_last]; last first.\n        { rewrite !fill_app in Hx. by destruct Ki. }\n        simpl in Hx. subst e1'. inversion Hred.\n      (* — either e = K[Fork e1]: *)\n      + (* then we easily derive a reduction from e: *)\n        eexists _, _, _, _. apply Ectx_step', ForkS.\n      (* — either e = K[Rec f x e1]: *)\n      + (* then we easily derive a reduction from e: *)\n        eexists _, _, _, _. apply Ectx_step', RecS.\n      (* — or e = K[ki[v]] where ki is an active item: *)\n      + (* it is enough to show that ki[v] is reducible: *)\n        apply loc_fresh_in_expr_fill_inv in Hfresh ;\n        rewrite -> translation_fill in Hsafe ; apply safe_fill_inv in Hsafe ;\n        apply reducible_fill ;\n        clear K.\n        (* we deduce the reducibility of ki[v] from that of «ki»[«v»]: *)\n        eapply active_item_translation_reducible ; [ done | done | ].\n        (* remind that « ki[v] » = «ki»[tick «v»]: *)\n        rewrite -> translation_fill_item_active in Hsafe ; last done.\n        (* we have that «ki»[tick «v»] reduces to «ki»[«v»]\n         * (m ≥ 1 so ‘tick’ can be run): *)\n        assert (\n          prim_exec (fill_item Ki«ki» (tick V«v»)) S«σ, m»\n                    (fill_item Ki«ki» V«v»)        S«σ, m-1» []\n        ) as Hsteps % prim_exec_exec.\n        {\n          assert (fill [Ki«ki»] = fill_item Ki«ki») as E by reflexivity ; destruct E.\n          apply prim_exec_fill. apply safe_fill_inv in Hsafe.\n          rewrite {+1} (_ : m = S (m-1)) ; last lia.\n          apply exec_tick_success.\n        }\n        (* using the safety of «ki»[tick «v»], we proceed by case analysis… *)\n        eapply Hsafe in Hsteps as [ Hisval | Hred ] ; auto using elem_of_list_here.\n        (* — either «ki»[«v»] is a value: this is not possible because ki is active. *)\n        * simpl in Hisval. rewrite active_item_not_val in Hisval ;\n          [ by apply is_Some_None in Hisval | by apply is_active_translationKi ].\n        (* — or «ki»[«v»] reduces to something: this is precisely what we need. *)\n        * exact Hred.\n  Qed.\n  Lemma safe_translation__nsafe m n e σ t2 σ2 e2 :\n    loc_fresh_in_expr ℓ e2 →\n    σ2 !! ℓ = None →\n    safe «e» S«σ, m» →\n    relations.nsteps erased_step n ([e], σ) (t2, σ2) →\n    (n < m)%nat →\n    e2 ∈ t2 →\n    is_Some (to_val e2) ∨ reducible e2 σ2.\n  Proof.\n    intros Hℓe Hℓσ Hsafe Hnsteps Inm He2.\n    assert (safe «e2» S«σ2, m-n») as Hsafe2.\n    {\n      eapply safe_exec.\n      - eapply elem_of_list_fmap_1. eassumption.\n      - eassumption.\n      - change [«e»] with T«[e]». apply simulation_exec_success' ; [ assumption | lia | assumption ].\n    }\n    assert (m - n > 0)%nat by lia.\n    by eapply safe_translation__nsafe_here.\n  Qed.\n\n  (* assuming the adequacy of the translated expression,\n   * a proof that the original expression has m-adequate results. *)\n\n  (* FIXME : this is a weaker result than the adequacy result of Iris,\n     where the predicate can also speak about the final state. *)\n  Lemma adequate_translation__nadequate_result m n φ e σ t2 σ2 v2 :\n    σ2 !! ℓ = None →\n    adequate NotStuck «e» S«σ, m» (λ v σ, φ (invtranslationV v)) →\n    relations.nsteps erased_step n ([e], σ) (Val v2 :: t2, σ2) →\n    (n ≤ m)%nat →\n    φ v2.\n  Proof.\n    intros Hfresh Hadq Hnsteps Inm.\n    assert (safe «e» S«σ, m») as Hsafe by by eapply safe_adequate.\n    replace (φ v2) with ((φ ∘ invtranslationV) (translationV v2))\n      by (simpl ; by rewrite invtranslationV_translationV).\n    eapply (adequate_result _ _ _ (λ v σ, φ (invtranslationV v))); first done.\n    simpl. change [«e»%E] with T«[e]».\n    replace (Val «v2» :: _) with (T«Val v2 :: t2») by done.\n    eapply simulation_exec_success' ; eauto.\n  Qed.\n\nEnd SimulationLemma. (* we close the section here as we now want to quantify over all locations *)\n\n(* now let’s combine the two results. *)\n\nLemma adequate_translation__nadequate m φ e σ :\n  (∀ {Hloc : TickCounter}, adequate NotStuck «e» S«σ, m» (λ v σ, φ (invtranslationV v))) →\n  nadequate NotStuck m e σ φ.\nProof.\n  intros Hadq.\n  split.\n  (* (1) adequate result: *)\n  - intros n t2 σ2 v2 Hnsteps Inm.\n    (* build a location ℓ which is not in the domain of σ2: *)\n    pose (Hloc := Build_TickCounter (fresh (dom (gset loc) σ2)) : TickCounter).\n    assert (σ2 !! ℓ = None)\n      by (simpl ; eapply (not_elem_of_dom (D:=gset loc)), is_fresh).\n    by eapply adequate_translation__nadequate_result.\n  (* (2) safety: *)\n  - intros n t2 σ2 e2 _ Hnsteps Inm He2.\n    (* build a location ℓ which is fresh in e2 and in the domain of σ2: *)\n    pose (set1 := loc_set_of_expr e2 : gset loc).\n    pose (set2 := dom (gset loc) σ2 : gset loc).\n    pose (Hloc := Build_TickCounter (fresh (set1 ∪ set2)) : TickCounter).\n    eassert (ℓ ∉ set1 ∪ set2) as [Hℓ1 Hℓ2] % not_elem_of_union\n      by (unfold ℓ ; apply is_fresh).\n    assert (loc_fresh_in_expr ℓ e2)\n      by by apply loc_not_in_set_is_fresh_in_expr.\n    assert (σ2 !! ℓ = None)\n      by by (simpl ; eapply (not_elem_of_dom (D:=gset loc))).\n    specialize (Hadq Hloc) as Hsafe % safe_adequate.\n    by eapply safe_translation__nsafe.\nQed.\n\nEnd Simulation.\n\n", "meta": {"author": "Ricagraca", "repo": "i-splay-tree", "sha": "263215b780f52dd0168143def37be537bb07e0ea", "save_path": "github-repos/coq/Ricagraca-i-splay-tree", "path": "github-repos/coq/Ricagraca-i-splay-tree/i-splay-tree-263215b780f52dd0168143def37be537bb07e0ea/theories/Simulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2240415544264165}}
{"text": "Require Import Spec.ConcurExec.\n\nRequire Import ProofAutomation.\nRequire Import Spec.Equiv.Automation.\n\nRequire Import Helpers.Instances.\nRequire Import Morphisms.\n\nSection OpSemantics.\n\n  Context {Op:Type -> Type}.\n  Context {State:Type}.\n  Variable op_step: OpSemantics Op State.\n\n  Local Obligation Tactic := try RelInstance_t.\n\n  (** A strong notion of execution equivalence, independent of semantics *)\n\n  Definition exec_equiv_ts (ts1 ts2 : threads_state Op) :=\n    forall (s : State) tr,\n      exec op_step s ts1 tr <->\n      exec op_step s ts2 tr.\n\n  Global Program Instance exec_equiv_ts_equivalence :\n    Equivalence exec_equiv_ts.\n\n  Local Definition exec_equiv_opt (p1 : maybe_proc Op) p2 :=\n    forall (ts : threads_state _) tid,\n      exec_equiv_ts (ts [[ tid := p1 ]]) (ts [[ tid := p2 ]]).\n\n  Definition exec_equiv `(p1 : proc Op T) (p2 : proc _ T) :=\n    exec_equiv_opt (Proc p1) (Proc p2).\n\n  Definition exec_equiv_rx `(p1 : proc Op T) (p2 : proc _ T) :=\n    forall TR (rx : T -> proc _ TR),\n      exec_equiv (Bind p1 rx) (Bind p2 rx).\n\n  Global Program Instance exec_equiv_opt_equivalence :\n    Equivalence exec_equiv_opt.\n\n  Global Program Instance exec_equiv_equivalence :\n    Equivalence (@exec_equiv T).\n\n  Global Program Instance exec_equiv_rx_equivalence :\n    Equivalence (@exec_equiv_rx T).\n\n  Global Instance thread_upd_exec_equiv_proper :\n    Proper (eq ==> eq ==> exec_equiv_opt ==> exec_equiv_ts) (@thread_upd Op).\n  Proof.\n    intros.\n    intros ts0 ts1 H; subst.\n    intros tid tid' H'; subst.\n    intros o0 o1 H'.\n\n    unfold exec_equiv_ts; split; intros.\n    - apply H'; eauto.\n    - apply H'; eauto.\n  Qed.\n\n  Global Instance Proc_exec_equiv_proper :\n    Proper (exec_equiv ==> exec_equiv_opt) (@Proc Op T).\n  Proof.\n    intros.\n    unfold exec_equiv.\n    intros ts0 ts1 H; subst.\n    eauto.\n  Qed.\n\n  Hint Constructors exec_tid.\n  Hint Constructors exec_till.\n\n  Hint Extern 1 (exec _ _ _ _ _) =>\n  match goal with\n  | |- exec_till _ _ _ ?ts _ => first [ is_evar ts; fail 1 | eapply ConcurExec.exec_ts_eq ]\n  end : exec.\n\n  Theorem exec_equiv_ret_None : forall `(v : T),\n      exec_equiv_opt (Proc (Ret v)) NoProc.\n  Proof.\n    split; intros.\n    - ExecEquiv tt.\n    - change tr with (prepend tid nil tr).\n      eapply ExecOne with (tid := tid).\n      autorewrite with t; eauto.\n      rewrite mapping_finite; auto.\n      econstructor.\n      match goal with\n      | |- context[S (thread_max ?ts)] =>\n        rewrite thread_upd_same_eq with (tid := S (thread_max ts))\n      end.\n      autorewrite with t; eauto.\n      rewrite mapping_finite; eauto.\n  Qed.\n\n  Theorem exec_equiv_rx_proof_helper : forall `(p1 : proc Op T) p2,\n      (forall tid tid' `(s : State) s' (ts: threads_state _) tr spawned evs `(rx : _ -> proc _ TR) result,\n          exec_tid op_step tid s (Bind p1 rx) s' result spawned evs ->\n          ts tid' = NoProc ->\n          tid <> tid' ->\n          exec op_step s' (ts [[tid' := spawned]] [[tid := match result with\n                                                           | inl _ => NoProc\n                                                           | inr p' => Proc p'\n                                                           end]]) tr ->\n          exec op_step s (ts [[tid := Proc (Bind p2 rx)]]) (prepend tid evs tr)) ->\n      (forall tid tid' `(s : State) s' (ts: threads_state _) tr evs spawned `(rx : _ -> proc _ TR) result,\n          exec_tid op_step tid s (Bind p2 rx) s' result spawned evs ->\n          ts tid' = NoProc ->\n          tid <> tid' ->\n          exec op_step s' (ts [[tid' := spawned]] [[tid := match result with\n                                                           | inl _ => NoProc\n                                                           | inr p' => Proc p'\n                                                           end]]) tr ->\n          exec op_step s (ts [[tid := Proc (Bind p1 rx)]]) (prepend tid evs tr)) ->\n      exec_equiv_rx p1 p2.\n  Proof.\n    split; intros.\n    - ExecEquiv tt.\n    - ExecEquiv tt.\n  Qed.\n\n  Theorem exec_equiv_rx_bind_bind : forall `(p1 : proc Op T1) `(p2 : T1 -> proc Op T2) `(p3 : T2 -> proc Op T3),\n      exec_equiv_rx (Bind (Bind p1 p2) p3) (Bind p1 (fun v => Bind (p2 v) p3)).\n  Proof.\n    split; intros.\n    - ExecEquiv p1.\n      ExecPrefix tid tid'.\n      destruct result0; eauto.\n    - ExecEquiv p1.\n      ExecPrefix tid tid'.\n      destruct result; eauto.\n  Qed.\n\n  Theorem exec_equiv_ret_bind : forall `(v : T) `(p : T -> proc Op T'),\n      exec_equiv_rx (Bind (Ret v) p) (p v).\n  Proof.\n    intros.\n    eapply exec_equiv_rx_proof_helper; intros; exec_tid_simpl.\n    - simpl.\n      rewrite thread_upd_same_eq with (tid:=tid') in H2 by eauto.\n      eauto.\n    - abstract_tr.\n      ExecPrefix tid tid'.\n      ExecPrefix tid tid'.\n      rewrite <- prepend_app; simpl; auto.\n  Qed.\n\n  Theorem exec_equiv_bind_ret : forall `(p : proc Op T),\n      exec_equiv (Bind p Ret) p.\n  Proof.\n    unfold exec_equiv; split; intros.\n\n    - ExecEquiv p.\n      destruct result0.\n      + ExecPrefix tid tid'.\n        eapply exec_equiv_ret_None; eauto.\n      + ExecPrefix tid tid'.\n\n    - ExecEquiv p.\n      destruct result; guess_ExecPrefix.\n      eapply exec_equiv_ret_None; eauto.\n  Qed.\n\n  Global Instance exec_equiv_rx_to_exec_equiv :\n    subrelation (@exec_equiv_rx T) exec_equiv.\n  Proof.\n    unfold subrelation, exec_equiv_rx; intros.\n    rewrite <- exec_equiv_bind_ret with (p := x).\n    rewrite <- exec_equiv_bind_ret with (p := y).\n    eauto.\n  Qed.\n\n  Theorem exec_equiv_bind_bind : forall `(p1 : proc Op T1) `(p2 : T1 -> proc Op T2) `(p3 : T2 -> proc Op T3),\n      exec_equiv (Bind (Bind p1 p2) p3) (Bind p1 (fun v => Bind (p2 v) p3)).\n  Proof.\n    intros.\n    rewrite exec_equiv_rx_bind_bind; reflexivity.\n  Qed.\n\n  Theorem exec_equiv_bind_a : forall `(p : proc Op T) `(p1 : T -> proc _ T') p2,\n      (forall x, exec_equiv (p1 x) (p2 x)) ->\n      exec_equiv (Bind p p1) (Bind p p2).\n  Proof.\n    unfold exec_equiv; split; intros.\n    - ExecEquiv p.\n      ExecPrefix tid tid'.\n      destruct result0; eauto.\n      eapply H; eauto.\n\n    - ExecEquiv p.\n      ExecPrefix tid tid'.\n      destruct result0; eauto.\n      eapply H; eauto.\n  Qed.\n\n  Local Theorem exec_equiv_congruence : forall T (p1 p2: proc Op T) T' (rx1 rx2: T -> proc Op T'),\n      exec_equiv_rx p1 p2 ->\n      (forall x, exec_equiv_rx (rx1 x) (rx2 x)) ->\n      exec_equiv_rx (Bind p1 rx1) (Bind p2 rx2).\n  Proof.\n    intros.\n    unfold exec_equiv_rx; intros.\n    repeat rewrite exec_equiv_bind_bind.\n    etransitivity.\n    eapply H.\n    eapply exec_equiv_bind_a; intros.\n    eapply H0.\n  Qed.\n\n  Theorem exec_equiv_rx_bind_a : forall `(p : proc Op T) `(p1 : T -> proc _ T') p2,\n      (forall x, exec_equiv_rx (p1 x) (p2 x)) ->\n      exec_equiv_rx (Bind p p1) (Bind p p2).\n  Proof.\n    intros.\n    eapply exec_equiv_rx_proof_helper; intros.\n    - exec_tid_inv.\n      exec_tid_inv.\n      ExecPrefix tid tid'.\n      destruct result; eauto.\n      eapply H; eauto.\n      apply exec_equiv_bind_bind.\n      apply exec_equiv_bind_bind in H3.\n      eapply exec_equiv_bind_a; intros; eauto; simpl.\n      symmetry.\n      eapply H; eauto.\n    - exec_tid_inv.\n      exec_tid_inv.\n      ExecPrefix tid tid'.\n      destruct result; eauto.\n      eapply H; eauto.\n      apply exec_equiv_bind_bind.\n      apply exec_equiv_bind_bind in H3.\n      eapply exec_equiv_bind_a; intros; eauto; simpl.\n      eapply H; eauto.\n  Qed.\n\n  Theorem exec_equiv_atomicret_ret : forall `(v : T),\n      exec_equiv_rx (Atomic (Ret v)) (Ret v).\n  Proof.\n    intros.\n    eapply exec_equiv_rx_proof_helper; intros; exec_tid_simpl.\n    - repeat atomic_exec_inv.\n      ExecPrefix tid tid'.\n    - ExecPrefix tid tid'.\n  Qed.\n\n  Theorem exec_equiv_until : forall `(p : option T -> proc Op T) (c : T -> bool) v,\n      exec_equiv_rx (Until c p v) (until1 c p v).\n  Proof.\n    intros.\n    eapply exec_equiv_rx_proof_helper; intros.\n    - exec_tid_simpl.\n      rewrite thread_upd_same_eq with (tid:=tid') in H2 by congruence.\n      simpl; eauto.\n    - abstract_tr.\n      ExecPrefix tid tid'.\n      ExecPrefix tid tid'.\n      rewrite <- prepend_app; auto.\n  Qed.\n\n  Theorem exec_equiv_spawn : forall `(p1 : proc Op T) p2,\n      exec_equiv p1 p2 ->\n      exec_equiv_rx (Spawn p1) (Spawn p2).\n  Proof.\n    intros.\n    eapply exec_equiv_rx_proof_helper; intros.\n    - exec_tid_simpl.\n      ExecPrefix tid tid'.\n      rewrite thread_upd_ne_comm in * by auto.\n      match goal with\n      | H : exec_equiv _ _ |- _ =>\n        apply H; eauto\n      end.\n    - exec_tid_simpl.\n      ExecPrefix tid tid'.\n      rewrite thread_upd_ne_comm in * by auto.\n      match goal with\n      | H : exec_equiv _ _ |- _ =>\n        apply H; eauto\n      end.\n  Qed.\n\n  Global Instance Bind_exec_equiv_proper :\n    Proper (exec_equiv_rx ==>\n                          pointwise_relation T exec_equiv_rx ==>\n                          @exec_equiv_rx TR) Bind.\n  Proof.\n    unfold Proper, respectful, pointwise_relation; intros.\n    apply exec_equiv_congruence; auto.\n  Qed.\n\n  Global Instance Spawn_exec_equiv_proper :\n    Proper (@exec_equiv T ==> exec_equiv_rx) Spawn.\n  Proof.\n    unfold Proper, respectful, pointwise_relation; intros.\n    apply exec_equiv_spawn; auto.\n  Qed.\n\n  Global Instance exec_proper_exec_equiv :\n    Proper (eq ==> exec_equiv_ts ==> eq ==> iff) (@exec Op State op_step).\n  Proof.\n    unfold Proper, respectful; intros; subst; eauto.\n  Qed.\n\n  Global Instance SpawnN_exec_equiv_proper :\n      Proper (eq ==> (exec_equiv (T:=T)) ==> exec_equiv_rx) SpawnN.\n  Proof.\n    unfold Proper, respectful; intros; subst.\n    induction y; simpl.\n    - reflexivity.\n    - rewrite H0.\n      setoid_rewrite IHy.\n      reflexivity.\n  Qed.\n\nEnd OpSemantics.\n", "meta": {"author": "mit-pdos", "repo": "cspec", "sha": "074e11f5c7758fd0f5624f0466dd23244f9112c4", "save_path": "github-repos/coq/mit-pdos-cspec", "path": "github-repos/coq/mit-pdos-cspec/cspec-074e11f5c7758fd0f5624f0466dd23244f9112c4/src/Spec/Equiv/Execution.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22376948630753707}}
{"text": "Set Implicit Arguments.\n\nRequire Import LibTactics.\nRequire Import LNameless_Meta.\nRequire Import LNameless_Isomorphism.\nRequire Import LNameless_Fsub_Iso.\nRequire Import LN_Template_Two_Sort.\nRequire Import LN_Fsub_basic_Infrastructure.\n\n\n(** ** Fsub Part 1A and 2A *)\n\n(** Reference: Chargueraud's POPL solution using Locally Nameless style\n   and cofinite quantification *)\n\n(** * Properties of Subtyping *)\n\n(** \"apply_fresh T as x\" is used to apply inductive rule which\n   use an universal quantification over a cofinite set *)    \n\nLtac apply_fresh_base_simple lemma gather :=\n  let L0 := gather in let L := beautify_fset L0 in\n  first [apply (@lemma L) | eapply (@lemma L)].\n\nLtac apply_fresh_base lemma gather var_name :=\n  apply_fresh_base_simple lemma gather;\n  try match goal with |- forall _, _ `notin` _ -> _ =>\n    let Fr := fresh \"Fr\" in intros var_name Fr; destruct_notin end.\n\nTactic Notation \"apply_fresh\" constr(T) \"as\" ident(x) :=\n  apply_fresh_base T gather_atoms x.\n\nTactic Notation \"apply_fresh\" \"*\" constr(T) \"as\" ident(x) :=\n  apply_fresh T as x; auto*.\n\n(** These tactics help applying a lemma which conclusion mentions\n  an environment (E & F) in the particular case when F is empty *)\n\nLtac get_env :=\n  match goal with\n  | |- wft ?E _ => E\n  | |- sub ?E _ _  => E\n  | |- typing ?E _ _ => E\n  end.\n\nTactic Notation \"apply_empty_bis\" tactic(get_env) constr(lemma) :=\n  let E := get_env in rewrite <- (app_nil_1 _ E);\n  eapply lemma; try rewrite app_nil_1.\n\nLemma sub_reflexivity : forall E T,\n  okt E -> \n  wft E T -> \n  sub E T T .\nProof.\n  introv Ok WI. poses W (type_from_wft WI). gen E.\n  induction W; intros; inversions WI; eauto.\n  apply_fresh* sub_all as Y.\nQed.\n\n(* ********************************************************************** *)\n(** Weakening *)\n\nLemma sub_weakening : forall E F G S T,\n   sub (E ++ G) S T -> \n   okt (E ++ F ++ G) ->\n   sub (E ++ F ++ G) S T.\nProof.\n  introv Typ. gen_eq (E ++ G) as H. gen E.\n  induction Typ; introv EQ Ok; subst; auto.\n  (* case: fvar trans *)\n  eapply sub_trans_tvar; auto; eapply binds_weaken; auto.\n  (* case: all *)\n  apply_fresh* sub_all as Y. apply_ih_bind* H0.\nQed.\n \n(* ********************************************************************** *)\n(** Narrowing and transitivity *)\n\nSection NarrowTrans.\n\nDefinition transitivity_on Q := forall E S T,\n  sub E S Q -> sub E Q T -> sub E S T.\n\nHint Unfold transitivity_on.\n\nHint Resolve wft_narrow.\n\nImplicit Arguments binds_mid_eq [A x a b E F].\n\nLemma sub_narrowing_aux : forall Q F E Z P S T,\n  transitivity_on Q ->\n  sub (E ++ Z ~<: Q ++ F) S T ->\n  sub F P Q ->\n  sub (E ++ Z ~<: P ++ F) S T.\nProof.\n  introv TransQ SsubT PsubQ.\n  gen_eq (E ++ Z ~<: Q ++ F) as G. gen E.\n  induction SsubT; introv EQ; subst.\n\n  apply sub_top; eauto.\n\n  apply sub_refl_tvar; eauto.\n\n  puts (@okt_narrow E0 F Q).\n  elim sub_regular with (E0 ++ Z ~<: Q ++ F) U T; intros; auto.\n  case (X == Z); intros EQ; subst.\n    assert (bind_sub U = bind_sub Q).\n      apply binds_mid_eq with Z F E0; auto.\n    inversion H3; subst; clear H3.\n    apply (@sub_trans_tvar P).\n      apply binds_app_3; auto.\n    apply TransQ; auto.\n    do_rew <- (app_assoc) (apply_empty* sub_weakening); auto.\n  apply* (@sub_trans_tvar U); auto.\n  analyze_binds H.\n    \n  apply sub_arrow; auto.\n\n  apply_fresh* sub_all as Y. apply_ih_bind* H0.\nQed.\n\nLemma sub_transitivity : forall Q,\n  transitivity_on Q.\nProof.\n  intro Q. introv SsubQ QsubT. asserts* W (type Q).\n  gen E S T. gen_eq Q as Q' eq. gen Q' eq.\n  induction W; intros Q' EQ E S SsubQ;\n    induction SsubQ; try discriminate; inversions EQ;\n      intros T QsubT; inversions QsubT; \n        eauto 4 using sub_trans_tvar.\n  (* case: all / top -> only needed to fix well-formedness,\n     by building back what has been deconstructed too much *)\n  assert (sub E (typ_all S1 S2) (typ_all T1 T2)). \n    apply_fresh* sub_all as y. \n  auto*.\n  (* case: all / all *)\n  apply_fresh sub_all as Y. auto*. \n  forward~ (H0 Y) as K. apply (K (T2 open_tt_var Y)); auto.\n  puts (IHW T1); simpl; apply_empty* (@sub_narrowing_aux T1 E).\nQed.\n\nLemma sub_narrowing : forall Q E F Z P S T,\n  sub F P Q ->\n  sub (E ++ Z ~<: Q ++ F) S T ->\n  sub (E ++ Z ~<: P ++ F) S T.\nProof.\n  intros. \n  apply sub_narrowing_aux with Q; auto.\n  apply* sub_transitivity.\nQed.\n\nEnd NarrowTrans.\n\n(* ********************************************************************** *)\n(** Type substitution preserves subtyping *)\n\nLemma sub_through_subst_tt : forall Q E F Z S T P,\n  sub (E ++ Z ~<: Q ++ F) S T ->\n  sub F P Q ->\n  sub (map (subst_tb Z P) E ++ F) (M_yy.M.Tfsubst S Z P) (M_yy.M.Tfsubst T Z P).\nProof.\n  introv SsubT PsubQ.\n  gen_eq (E ++ Z ~<: Q ++ F) as G. gen E.\n  induction SsubT; introv EQ; subst.\n  apply sub_top; eauto.\n\n  apply sub_reflexivity; eauto.\n\n  elim sub_regular with F P Q;\n    [intros Hokt Hwft; inversion Hwft as [Hp Hq]; clear Hwft | idtac]; auto.\n  elim sub_regular with  (E0 ++ Z ~<: Q ++ F) U T;\n    [intros Hokt0 Hwft0; inversion Hwft0 as [Hu Ht]; clear Hwft0 | idtac]; auto.\n  gsimpl; simpl_alist in *.\n    apply (@sub_transitivity Q).\n      apply_empty* sub_weakening.\n    pattern Q; rewrite* (@M_yy.M.Tfsubst_no_occur Q X P).\n      assert (bind_sub U = bind_sub Q).\n        apply binds_mid_eq with X F E0; auto.\n      inversion H0; subst; clear H0; auto.\n    apply notin_fv_wf with (E:= F); auto.\n    apply fresh_mid_tail with (bind_sub Q) E0; auto.\n  analyze_binds H.\n    apply (@sub_trans_tvar (M_yy.M.Tfsubst U Z P)); auto; simpl.\n    replace (bind_sub (M_yy.M.Tfsubst U Z P)) with (subst_tb Z P (bind_sub U)); auto.\n  apply sub_trans_tvar with (U:= U); auto.\n  pattern U; rewrite* (@M_yy.M.Tfsubst_no_occur U Z P).\n  apply notin_fv_wf with (E:= F); auto.\n    apply wft_from_env_has_sub with X; auto.\n  apply fresh_mid_tail with (bind_sub Q) E0; auto.\n\n  gsimpl; simpl_alist in *; apply sub_arrow.\n\n  gsimpl; simpl_alist in *; apply_fresh* sub_all as X.\n   unsimpl (subst_tb Z P (bind_sub T1)).\n   do 2 grewrite Ybfsubst_permutation_var_wf; auto.\n   apply_ih_map_bind* H0.\nQed.\n\n(* ********************************************************************** *)\n(** * Properties of Typing *)\n\n(* ********************************************************************** *)\n(** Weakening *)\n\nLemma typing_weakening : forall E F G e T,\n   typing (E ++ G) e T -> \n   okt (E ++ F ++ G) ->\n   typing (E ++ F ++ G) e T.\nProof. \n  introv Typ. gen_eq (E ++ G) as H. gen E.\n  induction Typ; introv EQ Ok; subst; auto.\n\n  apply_fresh* typing_abs as x. forward~ (H x) as K.\n  apply_ih_bind (H0 x); auto.\n  apply okt_typ; auto.\n  elim typing_regular with (x ~: V ++ E0 ++ G) (e1 open_ee_var x) T1; intros; auto.\n  inversion H1; auto.\n\n  apply typing_app with T1; auto.\n\n  apply_fresh* typing_tabs as X. forward~ (H X) as K. \n  apply_ih_bind (H0 X); auto.\n  apply okt_sub; auto.\n  elim typing_regular with (X ~<: V ++ E0 ++ G) (e1 open_te_var X) (T1 open_tt_var X); intros; auto.\n  inversion H1; auto.\n\n  eapply typing_tapp; eauto. eapply sub_weakening; eauto.\n  eapply typing_sub; eauto. eapply sub_weakening; eauto.\nQed.\n\n(* ********************************************************************** *)\n(** Strengthening *)\n\nLemma sub_strengthening : forall x U E F S T,\n  sub (E ++ x ~: U ++ F) S T ->\n  sub (E ++ F) S T.\nProof.\n  intros x U E F S T SsubT.\n  gen_eq (E ++ x ~: U ++ F) as G. gen E.\n  induction SsubT; introv EQ; subst; use wft_strengthen.\n  (* case: fvar trans *)\n  apply (@sub_trans_tvar U0); auto.\n  analyze_binds H.\n  (* case: all *)\n  apply_fresh* sub_all as X. apply_ih_bind* H0.\nQed.\n\n(************************************************************************ *)\n(** Preservation by Type Narrowing *)\n\nLemma typing_narrowing : forall Q E F X P e T,\n  sub F P Q ->\n  typing (E ++ X ~<: Q ++ F) e T ->\n  typing (E ++ X ~<: P ++ F) e T.\nProof.\n  introv PsubQ Typ. gen_eq (E ++ X ~<: Q ++ F) as E'. gen E.\n  induction Typ; introv EQ; subst.\n\n  analyze_binds H0; apply typing_var; eauto.\n\n  apply_fresh* typing_abs as y. apply_ih_bind* H0.\n  eapply typing_app; eauto.\n  apply_fresh* typing_tabs as Y. apply_ih_bind* H0.\n  eapply typing_tapp; eauto. eapply (@sub_narrowing Q); eauto.\n  eapply typing_sub; eauto. eapply (@sub_narrowing Q); eauto.\nQed.\n\n(************************************************************************ *)\n(** Preservation by Term Substitution *)\n\nLemma typing_through_subst_ee : forall U E F x T e u,\n  typing (E ++ x ~: U ++ F) e T ->\n  typing F u U ->\n  typing (E ++ F) (M_tt.M.Tfsubst e x u) T.\nProof.\n  introv TypT TypU. gen_eq (E ++ x ~: U ++ F) as E'. gen E.\n  induction TypT; introv EQ; subst; gsimpl; simpl_alist in *.\n\n  assert (bind_typ T = bind_typ U) as Hbind.\n    apply binds_mid_eq with x0 F E0; auto.\n  inversion Hbind; subst; clear Hbind; auto.\n  apply_empty* typing_weakening.\n\n  analyze_binds H0; apply typing_var; eauto.\n\n  apply_fresh* typing_abs as y.\n  grewrite Tbfsubst_permutation_var_TTwf; auto.\n  apply_ih_bind* H0.\n\n  eapply typing_app; eauto.\n\n  apply_fresh* typing_tabs as Y.\n  grewrite noRepr_THbfsubst_permutation_var_1_wf.\n  apply_ih_bind* H0.\n  elim (term_TTwf (proj32 (typing_regular TypU))); tauto.\n\n  eapply typing_tapp; eauto. eapply sub_strengthening; eauto.\n\n  eapply typing_sub; eauto. eapply sub_strengthening; eauto.\nQed.\n\n(************************************************************************ *)\n(** Preservation by Type Substitution *)\n\nLemma typing_through_subst_te : forall Q E F Z e T P,\n  typing (E ++ Z ~<: Q ++ F) e T ->\n  sub F P Q ->\n  typing (map (subst_tb Z P) E ++ F) (M_yt.M.Tfsubst e Z P) (M_yy.M.Tfsubst T Z P).\nProof.\n  introv Typ PsubQ. gen_eq (E ++ Z ~<: Q ++ F) as G. gen E.\n  induction Typ; introv EQ; subst; gsimpl; simpl_alist in *.\n\n  analyze_binds H0; apply typing_var; eauto.\n    apply binds_app_2.\n    replace (bind_typ (M_yy.M.Tfsubst T Z P)) with (subst_tb Z P (bind_typ T)); auto.\n  apply binds_app_3.\n  rewrite* <- (@M_yy.M.Tfsubst_no_occur T Z P).\n  apply notin_fv_wf with (E:= F); auto.\n    apply wft_from_env_has_typ with x; auto.\n  apply fresh_mid_tail with (bind_sub Q) E0; auto.\n\n  apply_fresh* typing_abs as y.\n  unsimpl (subst_tb Z P (bind_typ V)).\n  grewrite noRepr_THbfsubst_permutation_var.\n  apply_ih_map_bind* H0.\n\n  eapply typing_app; eauto.\n  apply IHTyp1; auto.\n\n  apply_fresh* typing_tabs as Y.\n    unsimpl (subst_tb Z P (bind_sub V)).\n    grewrite THbfsubst_permutation_var_wf; auto.\n    grewrite Ybfsubst_permutation_var_wf; auto.\n    apply_ih_map_bind* H0. \n\n  rewrite* <- Ybfsubst_permutation_core_Ywf.\n  apply typing_tapp with (M_yy.M.Tfsubst T1 Z P); auto.\n  apply sub_through_subst_tt with Q; auto. \n\n  eapply typing_sub; eauto. eapply sub_through_subst_tt; eauto.\nQed.\n\n(* ********************************************************************** *)\n(** * Preservation *)\n\n(* ********************************************************************** *)\n(** Inversions for Typing *)\n\nLemma typing_inv_abs : forall E S1 e1 T,\n  typing E (trm_abs S1 e1) T -> \n  forall U1 U2, sub E T (typ_arrow U1 U2) ->\n     sub E U1 S1\n  /\\ exists S2, exists L, forall x, x `notin` L ->\n     typing (x ~: S1 ++ E) (e1 open_ee_var x) S2 /\\ sub E S2 U2.\nProof.\n  introv Typ. gen_eq (trm_abs S1 e1) as e. gen S1 e1.\n  induction Typ; intros S1 b1 EQ U1 U2 Sub; inversions EQ.\n  inversions* Sub. use (@sub_transitivity T).\nQed.\n\nLemma typing_inv_tabs : forall E S1 e1 T,\n  typing E (trm_tabs S1 e1) T -> \n  forall U1 U2, sub E T (typ_all U1 U2) ->\n     sub E U1 S1\n  /\\ exists S2, exists L, forall X, X `notin` L ->\n     typing (X ~<: U1 ++ E) (e1 open_te_var X) (S2 open_tt_var X)\n     /\\ sub (X ~<: U1 ++ E) (S2 open_tt_var X) (U2 open_tt_var X).\nProof.\n  intros E S1 e1 T H. gen_eq (trm_tabs S1 e1) as e. gen S1 e1.\n  induction H; intros S1 b EQ U1 U2 Sub; inversion EQ.\n  inversions Sub. splits; auto.\n   exists T1. let L1 := gather_atoms in exists L1.\n   intros Y Fr; destruct_notin. splits; auto. \n   simpl; apply_empty* (@typing_narrowing S1). \n  use (@sub_transitivity T).\nQed. \n\n(* ********************************************************************** *)\n(** Preservation Result *)\n\nLemma preservation_result : preservation.\nProof.\n  introv Typ. gen e'. induction Typ; introv Red; \n   try solve [ inversion Red ].\n  (* case: app *)\n  inversions Red; try solve [ eapply typing_app; eauto ].\n  destructi (typing_inv_abs Typ1 (U1:=T1) (U2:=T2)) as [P1 [S2 [L P2]]].\n    eapply sub_reflexivity; eauto.\n  pick_fresh X; destruct_notin.  \n  forward~ (P2 X) as K. destruct K.\n\n  rewrite M_tt.M.Tbfsubst_var_intro with (a:=X); simpl; auto.\n  apply_empty (@typing_through_subst_ee V); eauto.  \n  eapply (@typing_sub S2); eauto. apply_empty* sub_weakening.\n  \n  (* case: tapp *)\n  inversions Red; try solve [ eapply typing_tapp; eauto ].\n  destructi (typing_inv_tabs Typ (U1:=T1) (U2:=T2)) as [P1 [S2 [L P2]]].\n    eapply sub_reflexivity; eauto.\n  pick_fresh X; destruct_notin. forward~ (P2 X) as K. destruct K.\n  rewrite M_yt.M.Tbfsubst_var_intro with (a:=X); simpl; auto.\n  rewrite M_yy.M.Tbfsubst_var_intro with (a:=X); simpl; auto.\n  unsimpl (E ++ map (subst_tb X T) empty_env).\n  generalize (@typing_through_subst_te T1 nil); simpl; intros; eauto.\n  (* case sub *)\n  eapply typing_sub; eauto.\nQed.\n\n(* ********************************************************************** *)\n(** * Progress *)\n\n(* ********************************************************************** *)\n(** Canonical Forms *)\n\nLemma canonical_form_abs : forall t U1 U2,\n  value t -> typing empty_env t (typ_arrow U1 U2) -> \n  exists V, exists e1, t = trm_abs V e1.\nProof.\n  introv Val Typ. gen_eq (@empty_env bind) as E.\n  gen_eq (typ_arrow U1 U2) as T. gen U1 U2.\n  induction Typ; introv EQT EQE; \n   try solve [ inversion Val | inversion EQT | eauto ].\n    subst. inversion H. inversion H0. auto*.\nQed.\n\nLemma canonical_form_tabs : forall t U1 U2,\n  value t -> typing empty_env t (typ_all U1 U2) -> \n  exists V, exists e1, t = trm_tabs V e1.\nProof.\n  introv Val Typ. gen_eq (@empty_env bind) as E.\n  gen_eq (typ_all U1 U2) as T. gen U1 U2.\n  induction Typ; introv EQT EQE; \n   try solve [ inversion Val | inversion EQT | eauto ].\n    subst. inversion H. inversion H0. auto*.\nQed.\n\n(* ********************************************************************** *)\n(** Progress Result *)\n\nLemma progress_result : progress.\nProof.\n  introv Typ. gen_eq (@empty_env bind) as E. poses Typ' Typ.\n  induction Typ; intros EQ; subst.\n  (* case: var *)\n  inversion H0.\n  (* case: abs *)\n  left*. \n  (* case: app *)\n  right. destruct* IHTyp1 as [Val1 | [e1' Rede1']].\n    destruct* IHTyp2 as [Val2 | [e2' Rede2']].\n      destruct (canonical_form_abs Val1 Typ1) as [S [e3 EQ]].\n        subst. exists* (M_tt.M.Tbsubst e3 0 e2). \n  (* case: tabs *)\n  left*. \n  (* case: tapp *)\n  right. destruct* IHTyp as [Val1 | [e1' Rede1']]. \n    destruct (canonical_form_tabs Val1 Typ) as [S [e3 EQ]]. \n      subst. exists* (M_yt.M.Tbsubst e3 0 T). \n  (* case: sub *)\n  auto*.\nQed.\n\n\n\n", "meta": {"author": "Blaisorblade", "repo": "knot-esop-2017-case-study", "sha": "cf541cb38a483a514474f4c948bf005bc49b1e6f", "save_path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study", "path": "github-repos/coq/Blaisorblade-knot-esop-2017-case-study/knot-esop-2017-case-study-cf541cb38a483a514474f4c948bf005bc49b1e6f/poplmark_comparison/gmeta/LN_Fsub_basic_Soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.22376948630753704}}
{"text": "(* File: NSound.v  (last edited on 27/10/2000) (c) Klaus Weich  *)\n\nRequire Export Le_Ks.\nRequire Export Derivable_Tools.\n\nDefinition nsound (work : nf_list) (ds : disjs) (ni : nested_imps)\n  (ai : atomic_imps) (a : atoms) (context : flist) :=\n  forall c : normal_form,\n  in_ngamma work ds ni ai a c -> Derivable context (nf2form c).\n\n\nLemma nsound_eqv :\n forall (work : nf_list) (ds : disjs) (ni1 ni2 : nested_imps)\n   (ai : atomic_imps) (a : atoms) (context : flist),\n eqv_ni ni1 ni2 ->\n nsound work ds ni1 ai a context -> nsound work ds ni2 ai a context.\nintros work ds ni1 ni2 ai a context eq12 sound.\nunfold nsound in |- *.\nintros c in_ngamma.\napply sound.\napply in_ngamma_eqv with ni2. \napply eqv_sym; assumption.\nassumption.\nQed.\n\n\nLemma nsound_le :\n forall (work : nf_list) (ds : disjs) (ni1 ni2 : nested_imps)\n   (ai : atomic_imps) (a : atoms) (context : flist),\n le_ni ni1 ni2 ->\n nsound work ds ni1 ai a context -> nsound work ds ni2 ai a context.\nintros work ds ni1 ni2 ai a context le sound.\nunfold nsound in |- *.\nintros c in_ngamma.\napply sound.\napply in_ngamma_ge with ni2; assumption.\nQed.\n\n\nLemma nsound_ge :\n forall (work : nf_list) (ds : disjs) (ni1 ni2 : nested_imps)\n   (ai : atomic_imps) (a : atoms) (context : flist),\n le_ni ni2 ni1 ->\n nsound work ds ni1 ai a context -> nsound work ds ni2 ai a context.\nintros work ds ni1 ni2 ai a context le sound.\nunfold nsound in |- *.\nintros c in_ngamma.\napply sound.\napply in_ngamma_le with ni2; assumption.\nQed.\n\n\n(***********************************************************************)\n\n\n\nLemma nsound_shift_work_ds :\n forall (i j : Int) (work : nf_list) (ds : disjs) (ni : nested_imps)\n   (ai : atomic_imps) (a : atoms) (context : flist),\n nsound (NDisj i j :: work) ds ni ai a context ->\n nsound work ((i, j) :: ds) ni ai a context.\nintros i j work ds ni ai a context sound.\nunfold nsound in |- *.\nintros c in_ngamma.\napply sound.\napply in_ngamma_shift_ds_work; assumption.\nQed.\n\n\n\n\nLemma nsound_shift_work_ni :\n forall (x : nested_imp) (work : nf_list) (ds : disjs) \n   (ni : nested_imps) (ai : atomic_imps) (a : atoms) \n   (context : flist),\n nsound (NImp_NF (nested_imp2nimp x) :: work) ds ni ai a context ->\n nsound work ds (x :: ni) ai a context.\nintros x work ds ni ai a context sound.\nunfold nsound in |- *.\nintros c in_ngamma.\napply sound.\napply in_ngamma_shift_ni_work; assumption.\nQed.\n\n\n\n\n\n\n\nLemma nsound_shift_work_ai :\n forall (i : Int) (b : normal_form) (work : nf_list) \n   (ds : disjs) (ni : nested_imps) (ai ai' : atomic_imps) \n   (a : atoms) (context : flist),\n EQUIV_INS nf_list i (cons b) nf_nil ai ai' ->\n nsound (AImp i b :: work) ds ni ai a context ->\n nsound work ds ni ai' a context.\nintros i b work ds ni ai ai' a context equiv_ins sound.\nunfold nsound in |- *.\nintros c in_ngamma.\napply sound.\napply in_ngamma_shift_ai_work with ai'; assumption.\nQed.\n\n\n\n\n\n\nLemma nsound_shift_work_a :\n forall (i : Int) (work : nf_list) (ds : disjs) (ni : nested_imps)\n   (ai : atomic_imps) (a a' : atoms) (context : flist),\n EQUIV_INS unit i (fun _ : unit => tt) tt a a' ->\n nsound (NAtom i :: work) ds ni ai a context ->\n nsound work ds ni ai a' context.\nintros i work ds ni ai a a' context equiv_ins sound.\nunfold nsound in |- *.\nintros c in_ngamma.\napply sound.\napply in_ngamma_shift_a_work with a'; assumption.\nQed.\n\n\nLemma nsound_shift_work_ni_x_ni :\n forall (x : nested_imp) (work : nf_list) (ds : disjs)\n   (ni1 ni2 : nested_imps) (ai : atomic_imps) (a : atoms) \n   (context : flist),\n nsound (NImp_NF (nested_imp2nimp x) :: work) ds (ni1 ++ ni2) ai a context ->\n nsound work ds (ni1 ++ x :: ni2) ai a context.\nintros x work ds ni1 ni2 ai a context sound.\nunfold nsound in |- *.\nintros c in_ngamma.\napply sound.\napply in_ngamma_shift_ni_x_ni_work; assumption.\nQed.\n\n\nLemma nsound_shift_ni_x_ni_work :\n forall (x : nested_imp) (work : nf_list) (ds : disjs)\n   (ni1 ni2 : nested_imps) (ai : atomic_imps) (a : atoms) \n   (context : flist),\n nsound work ds (ni1 ++ x :: ni2) ai a context ->\n nsound (NImp_NF (nested_imp2nimp x) :: work) ds (ni1 ++ ni2) ai a context.\nintros x work ds ni1 ni2 ai a context sound.\nunfold nsound in |- *.\nintros c in_ngamma.\napply sound.\napply in_ngamma_shift_work_ni_x_ni; assumption.\nQed.\n\n\n\n(***********************************************************************)\n\n\nRemark nsound_app_work :\n forall (bs work : nf_list) (ds : disjs) (ni : nested_imps)\n   (ai : atomic_imps) (a : atoms) (context : flist),\n (forall (n : nat) (b : normal_form),\n  my_nth normal_form n bs b -> Derivable context (nf2form b)) ->\n nsound work ds ni ai a context -> nsound (bs ++ work) ds ni ai a context.\nintros bs work ds ni ai a context der_bs sound.\nunfold nsound in |- *.\nintros c in_ngamma.\nelim (in_ngamma_work_app_rev bs work ds ni ai a c in_ngamma); clear in_ngamma.\nintros in_ngamma.\napply sound; assumption.\nintros nth; elim nth; clear nth.\nintros n nth.\napply der_bs with n; assumption.\nQed.\n\n\n\nLemma nsound_cons_ds_tail :\n forall (work : nf_list) (i j : Int) (ds : disjs) (ni : nested_imps)\n   (ai : atomic_imps) (a : atoms) (context : flist),\n nsound work ((i, j) :: ds) ni ai a context -> nsound work ds ni ai a context.\nintros work i j ds ni ai a context sound.\nunfold nsound in |- *.\nintros c in_ngamma.\napply sound.\napply in_ngamma_cons_ds_tail; assumption.\nQed.\n\n\nRemark nsound_del_ai :\n forall (i : Int) (work : nf_list) (ds : disjs) (ni : nested_imps)\n   (ai ai' : atomic_imps) (a : atoms) (context : flist),\n EQUIV_DEL nf_list i ai ai' ->\n nsound work ds ni ai a context -> nsound work ds ni ai' a context.\nintros i work ds ni ai ai' a context equiv_del sound.\nunfold nsound in |- *.\nintros c in_ngamma.\napply sound.\napply in_ngamma_del_ai_tail with i ai'; assumption.\nQed.\n\n\n\n\n\n(***********************************************************************)\n\n\nLemma nsound_cons_work_cons_context :\n forall (c : normal_form) (work : nf_list) (ds : disjs) \n   (ni : nested_imps) (ai : atomic_imps) (a : atoms) \n   (context : flist),\n nsound work ds ni ai a context ->\n nsound (c :: work) ds ni ai a (nf2form c :: context).\nintros c work ds ni ai a context sound.\nunfold nsound in |- *.\nintros c0 in_gamma.\nelim (in_ngamma_cons_work_rev c work ds ni ai a c0 in_gamma); clear in_gamma.\nintros in_gamma.\napply derivable_weak.\napply sound; assumption.\nintros eq;  rewrite eq; clear eq.\napply Derivable_Intro with (Var 0).\napply ByAssumption.\napply My_NthO.\nQed.\n\n(**********************************************************************)\n\n\nLemma nsound_cons_work_weak :\n forall (b c : normal_form) (work : nf_list) (ds : disjs) \n   (ni : nested_imps) (ai : atomic_imps) (a : atoms) \n   (context : flist),\n (Derivable context (nf2form b) -> Derivable context (nf2form c)) ->\n nsound (b :: work) ds ni ai a context ->\n nsound (c :: work) ds ni ai a context.\nintros b c work ds ni ai a context der_ab sound.\nunfold nsound in |- *.\nintros c0 in_ngamma.\nelim (in_ngamma_cons_work_rev c work ds ni ai a c0 in_ngamma);\n clear in_ngamma.\nintros in_ngamma.\napply sound.\napply in_ngamma_cons_work_tail; assumption.\nintros eq;  rewrite eq; clear eq c0.\napply der_ab.\napply sound.\napply in_ngamma_cons_work_head.\nQed.\n\n\n\n\nLemma nsound_shift_work_ai_strength :\n forall (i : Int) (bs work : nf_list) (ds : disjs) \n   (ni : nested_imps) (ai ai' : atomic_imps) (a a' : atoms) \n   (context : flist),\n EQUIV_INS unit i (fun _ : unit => tt) tt a a' ->\n LOOKUP nf_list i ai bs ->\n EQUIV_DEL nf_list i ai ai' ->\n nsound work ds ni ai a' context -> nsound (bs ++ work) ds ni ai' a' context.\nintros i bs work ds ni ai ai' a a' context equiv_ins lookup equiv_del sound.\napply nsound_app_work; try assumption.\nintros n b nth.\napply derivable_a_a_imp_b__derivable_b with (Atom i).\napply sound with (c := NAtom i).\napply in_ngamma_ins_a_head with a; assumption.\napply sound with (c := AImp i b).\napply In_Atomic_Imps with (i := i) (b := b) (n := n) (bs := bs); assumption.\napply nsound_del_ai with i ai; assumption.\nQed.\n\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/ipc/NSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.223769486307537}}
{"text": "Set Implicit Arguments.\nSet Bullet Behavior \"Strict Subproofs\".\n\nRequire Import String Lists.List.\nImport ListNotations.\nOpen Scope string.\nOpen Scope list.\nFrom Utils Require Import Utils.\nFrom Pyrosome Require Import Theory.Core Compilers.Compilers Elab.Elab Elab.ElabCompilers\n  Tools.Matches.\nFrom Pyrosome.Lang Require Import SimpleVSubst SimpleVCPS SimpleEvalCtx SimpleEvalCtxCPS\n     SimpleUnit NatHeap SimpleVCPSHeap SimpleVCC.\nImport Core.Notations.\n(*TODO: repackage this in compilers*)\nImport CompilerDefs.Notations.\n\nRequire Coq.derive.Derive.\n\n(*TODO: make this divide more sensible*)\nDefinition heap_id'_def : compiler :=\n  match # from (unit_lang ++ heap ++ nat_exp++ nat_lang) with\n  | {{s #\"heap\"}} => {{s#\"heap\"}}\n  end.\n\n\n\n\nDerive heap_id'\n       SuchThat (elab_preserving_compiler subst_cc\n                                          (heap_cps_ops (*TODO: remove via lemma*)\n                                             ++ cc_lang (*TODO: remove via lemma*)\n                                             ++ prod_cc\n                                             ++ cps_prod_lang\n                                             ++ unit_lang\n                                             ++ heap\n                                             ++ nat_exp\n                                             ++ nat_lang\n                                             ++ block_subst\n                                             ++ value_subst)\n                                          heap_id'_def\n                                          heap_id'\n                                          (unit_lang ++ heap ++ nat_exp++ nat_lang))\n       As heap_id'_preserving.\nProof.\n  auto_elab_compiler.\n  - cleanup_elab_after eredex_steps_with heap \"heap_comm\".\n  - cleanup_elab_after eredex_steps_with heap \"lookup_miss\".\n  - cleanup_elab_after eredex_steps_with heap \"lookup_empty\".\nQed.\n#[export] Hint Resolve heap_id'_preserving : elab_pfs.\n\n\n(*TODO: move to value_subst? could conflict w/ cmp_forget\n  not currently used\nTODO: variant of one in SimpleVCC.v\n*)\n(*TODO: generalize? reverse for tactics?*)\nDefinition forget_eq_wkn'_def : lang :=\n  {[l\n      [:= \"G\" : #\"env\", \"A\" : #\"ty\"\n         ----------------------------------------------- (\"forget_eq_wkn\")\n         #\"cmp\" #\"wkn\" #\"forget\" = #\"forget\"\n         : #\"sub\" (#\"ext\" \"G\" \"A\") #\"emp\"\n      ]\n  ]}.\nDerive forget_eq_wkn'\n       SuchThat (elab_lang_ext value_subst\n                               forget_eq_wkn'_def\n                               forget_eq_wkn')\n       As forget_eq_wkn'_wf.\nProof. auto_elab. Qed.\n#[export] Hint Resolve forget_eq_wkn'_wf : elab_pfs.\n\nDefinition heap_cc_def : compiler :=\n  match # from heap_cps_ops with\n  | {{s #\"configuration\" \"G\"}} =>\n    {{s #\"configuration\" (#\"ext\" #\"emp\" \"G\")}}\n  | {{e #\"config\" \"H\" \"G\" \"A\" \"e\"}} =>\n    {{e #\"config\" \"H\" \"e\"}}\n  | {{e #\"get\" \"G\" \"v\" \"e\"}} =>\n    {{e #\"get\" \"v\" (#\"blk_subst\" (#\"snoc\" #\"forget\" (#\"pair\" {ovar 1} #\"hd\")) \"e\")}}\n  | {{e #\"set\" \"G\" \"v\" \"v'\" \"e\" }} =>\n    {{e #\"set\" \"v\" \"v'\" \"e\" }} \n  end.\n\n(*TODO: make proof brief*)\nDerive heap_cc\n       SuchThat (elab_preserving_compiler (heap_id'++subst_cc)\n                                          (heap_cps_ops\n                                             ++ cc_lang\n                                             ++ prod_cc\n                                             ++ forget_eq_wkn'\n                                             ++ cps_prod_lang\n                                             ++ unit_lang\n                                             ++ heap\n                                             ++ nat_exp\n                                             ++ nat_lang\n                                             ++ block_subst\n                                             ++ value_subst)\n                                          heap_cc_def\n                                          heap_cc\n                                          heap_cps_ops)\n       As heap_cc_preserving.\nProof.\n  auto_elab_compiler.\n  {\n    reduce.\n    repeat (term_cong; unfold Model.eq_term; try term_refl; compute_eq_compilation).\n    eapply eq_term_trans; cycle 1.\n    {\n      term_cong; unfold Model.eq_term.\n      - term_refl.\n      - term_refl.\n      - compute_eq_compilation.        \n        estep_under forget_eq_wkn' \"forget_eq_wkn\".\n      - term_refl.\n      - term_refl.\n    }\n    compute_eq_compilation.\n    eapply eq_term_trans; cycle 1.\n    1:estep_under value_subst \"cmp_snoc\".\n    compute_eq_compilation.\n    eapply eq_term_trans; cycle 1.\n    {\n      term_cong; unfold Model.eq_term.\n      - term_refl.\n      - term_refl.\n      - term_refl.\n      - term_refl.\n      - compute_eq_compilation.\n        eapply eq_term_trans; cycle 1.\n        {\n          term_cong; unfold Model.eq_term.\n          - term_refl.\n          - term_refl.\n          - \n            eapply eq_term_trans; cycle 1.\n            {\n              compute_eq_compilation.\n              eredex_steps_with forget_eq_wkn' \"forget_eq_wkn\".\n            }\n            compute_eq_compilation.\n            {\n              term_cong; unfold Model.eq_term.\n              - term_refl.\n              - term_refl.\n              - term_refl.\n              - term_refl.\n              - compute_eq_compilation.\n                eredex_steps_with value_subst \"id_emp_forget\".\n            }\n          - term_refl.\n          - term_refl.\n        }\n        compute_eq_compilation.\n        eapply eq_term_trans; cycle 1.\n        {\n          term_cong; unfold Model.eq_term.\n          - term_refl.\n          - term_refl.\n          - eapply eq_term_sym.\n            eredex_steps_with value_subst \"id_right\".\n          - term_refl.\n          - term_refl.\n        }\n        compute_eq_compilation.\n        by_reduction.\n    }\n    eapply eq_term_trans; cycle 1.\n    {\n      eapply eq_term_sym.\n      eredex_steps_with value_subst \"id_right\".\n    }\n    compute_eq_compilation.\n    term_refl.\n  }\n  {\n    compute_eq_compilation.\n    eapply eq_term_trans.\n    {\n      eredex_steps_with heap_cps_ops \"eval get\".\n    }\n    compute_eq_compilation.\n    reduce.\n    term_cong; try term_refl; unfold Model.eq_term; compute_eq_compilation.\n    term_cong; try term_refl; unfold Model.eq_term; compute_eq_compilation.\n    term_cong; try term_refl; unfold Model.eq_term; compute_eq_compilation.\n    eapply eq_term_trans.\n    {      \n      eapply eq_term_sym.\n      eredex_steps_with forget_eq_wkn' \"forget_eq_wkn\".\n    }      \n    compute_eq_compilation.\n    eapply eq_term_trans; cycle 1.\n    {\n      eredex_steps_with value_subst \"id_right\".\n    }\n    compute_eq_compilation.\n    term_cong; try term_refl; unfold Model.eq_term; compute_eq_compilation.\n    by_reduction.\n  }\nUnshelve.\n  all: repeat t'.\nQed.\n#[export] Hint Resolve heap_cc_preserving : elab_pfs.\n", "meta": {"author": "DIJamner", "repo": "pyrosome", "sha": "a8d7f0aa3141b35a3c59d8d72aadf47a3b0c5df6", "save_path": "github-repos/coq/DIJamner-pyrosome", "path": "github-repos/coq/DIJamner-pyrosome/pyrosome-a8d7f0aa3141b35a3c59d8d72aadf47a3b0c5df6/src/Pyrosome/Lang/SimpleVCCHeap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22376590103326988}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp\nRequire Import path.\nRequire Import Eqdep.\nRequire Import Relation_Operators.\nFrom fcsl\nRequire Import axioms pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL\nRequire Import Freshness State EqTypeX DepMaps Protocols Worlds NetworkSem Rely.\nFrom DiSeL\nRequire Import Actions Injection Process Always HoareTriples InferenceRules.\nFrom DiSeL\nRequire Import InductiveInv While StatePredicates.\nFrom DiSeL\nRequire Import TwoPhaseProtocol TwoPhaseInductiveInv.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nSection TwoPhaseInductiveProof.\n\nVariable l : Label.\nVariables (cn : nid) (pts : seq nid) (others : seq nid).\nHypothesis Hnin : cn \\notin pts.\nHypothesis PtsNonEmpty : pts != [::].\n\nDefinition tpc := TwoPhaseCommitProtocol others Hnin l.\n\n(* Take the transitions *)\nNotation sts := (snd_trans tpc).\nNotation rts := (rcv_trans tpc).\n\nNotation loc z d := (getLocal z d).\n\nNotation Sinv := (@S_inv tpc (fun d _ => Inv cn pts d)).\nNotation Rinv := (@R_inv tpc (fun d _ => Inv cn pts d)).\nNotation coh d := (coh tpc d).\nNotation PI := pf_irr.\n\nExport TPCProtocol.\n\n(*************************************************************)\n(*                  Send-transitions                         *)\n(*************************************************************)\n\n(*** [Coordinator] Send prepare-request ***)\n\nProgram Definition s1: Sinv (cn_send_prep_trans cn pts others).\nProof.\nmove=>this to d msg S h/= Hi/=[]T G.\ncase: (S)=>[][/eqP]Z H1[C]; subst this.\ncase=>[[e[E1][dt]Z']|[e][dt][ps][E1]Z']; subst msg;\nrewrite (PI (cn_safe_coh _) C) E1 in T.\n\n(* We're in the global Init state *)\ncase: (@inv_init l cn pts others Hnin d e _ Hi E1)=>lg{Hi E1}[E1]H2.\nrewrite (PI (cn_this_in _ _) (cn_in _ _ _))\n        (getStL_Kc C (cn_in _ _ _) E1) in T; subst h=>/=.\nexists e, lg; constructor 2; exists dt.\nhave Y: {subset [::to] <= pts} by move=>z; rewrite inE=>/eqP->.\ncase X: (pts == [::to]); [right; exists [::]|left; exists [::to]];\nsplit=>//=; do?[by rewrite /cn_state locE'?(cohVl C)///cstep_send H1 X];\nmove=>pt Hp.\n(* TODO: Factor this out *)\n- move/eqP: X=>Z; rewrite Z inE in Hp; move/eqP: Hp=>Hp _; subst pt.\n  constructor 1=>/=; simpl in G. case/H2: (H1)=>H1' H1''.\n  split=>//; rewrite /pt_state//; last first.\n  apply: msg_specE; rewrite ?(cohVs C)//.\n  apply: no_msg_from_toE'; rewrite ?(cohVs C)//.\n  + by move: (this_not_pts Hnin H1); rewrite eq_sym.\n  by rewrite (G _ (this_not_pts Hnin H1)); rewrite /pt_state in H1'.\n- case: ifP.\n  rewrite inE=>/eqP=>Z; subst pt.\n  constructor 1=>/=; simpl in G; case/H2: (H1)=>H1' H1''.\n  split=>//; rewrite /pt_state//; last first.\n  apply: msg_specE; rewrite ?(cohVs C)//.\n  apply: no_msg_from_toE'; rewrite ?(cohVs C)//.\n  + by move: (this_not_pts Hnin H1); rewrite eq_sym.\n  by move:(this_not_pts Hnin H1)=>/G->; rewrite/pt_state in H1'.\n- rewrite /pt_Init.\n  move=>N/=;simpl in G; case/H2: (Hp)=>H1' H1''; rewrite/pt_state/=.\n  move: (this_not_pts Hnin Hp)=>Hp'; rewrite (G _ Hp'); split=>//.\n  - apply: no_msg_from_toE'; rewrite ?(cohVs C)//.\n    by move: (this_not_pts Hnin Hp); rewrite eq_sym.\n  apply: no_msg_from_toE; rewrite ?(cohVs C)//.\n  by apply/negbTE/negP=>/eqP Z; subst to; rewrite inE eqxx in N.\n\n(* Now we're in a state, when the coordinator is in the\n   CSentPrep position. Repeat the same pattern. *)\ncase: (@inv_prep_send l cn pts others Hnin d e _ _ _ Hi E1).\nmove=> lg{Hi}[ps'][E1']H2 H3 H4 H5.\nrewrite (PI (cn_this_in _ _) (cn_in _ _ _))\n        (getStL_Kc C (cn_in _ _ _) E1') in T; subst h=>/=.\nrewrite (getStC_K C E1') in E1; case: E1=>Z; subst ps'.\nexists e, lg; constructor 2; simpl in G; exists dt.\ncase X: (perm_eq (to :: ps) pts);\n  [right; exists [::]|left; exists (to::ps)]=>/=;\nsplit; do?[by rewrite /cn_state locE'?(cohVl C)///cstep_send H1 X]=>//;\n[move=>pt Hp _| move=>/=; by rewrite H5| |move=>pt Hp]; first 1 last.\n\n- move=>z; rewrite inE=>/orP[];[by move/eqP=>->|by apply: H3].\n- case: ifP; last first.\n  + rewrite inE=>/Bool.orb_false_iff[Z1]Z2.\n    move: (H4 _ Hp); rewrite Z2; move=>[G1 G2].\n    split; first by move:(this_not_pts Hnin Hp)=>/G; rewrite /pt_state=>->.\n    - apply: no_msg_from_toE'; rewrite ?(cohVs C)//.\n      by move: (this_not_pts Hnin Hp); rewrite eq_sym.\n  by apply: no_msg_from_toE; rewrite ?(cohVs C)//.\n\n- rewrite inE=>/orP[].\n  move/eqP=>Z;subst to.\n  move: (H4 _ Hp); move/negbTE: H5->; case=>G1 G2 G3.\n  constructor 1=>/=; split=>//; last 2 first.\n  + apply:no_msg_from_toE'=>//;\n  rewrite ?(cohVs C)//; move:(this_not_pts Hnin Hp).\n  by rewrite eq_sym.\n- by apply:msg_specE;rewrite ?(cohVs C)//.\n  move:(this_not_pts Hnin Hp)=>/G; rewrite /pt_state=>->.\n  by rewrite /pt_state.\n\n- move=>Z; move: (H4 _ Hp); rewrite Z.\n  have Z1: pt == to = false.\n  + by apply/negbTE/negP=>/eqP=>Z1; subst to; rewrite Z in H5.\n  by apply:(@pt_PhaseOneE l cn pts others Hnin d e dt lg pt to _ _ C Hp Z1 G).\n\ncase Z1: (pt == to); last first.\n- move/perm_eq_mem: X=>/(_ pt); rewrite inE Z1/= Hp=>Z.\n  move: (H4 _ Hp); rewrite Z.\n  by apply:(@pt_PhaseOneE l cn pts others Hnin d e dt lg pt to _ _ C Hp Z1 G).\nmove/eqP:Z1=>Z1; subst to.\nmove: (H4 _ H1); rewrite (negbTE H5); case=>G1 G2.\nconstructor 1=>/=; split=>//; last 2 first.\n- apply:no_msg_from_toE'=>//;\n  rewrite ?(cohVs C)//; move: (this_not_pts Hnin Hp).\n  by rewrite eq_sym.\n- by apply:msg_specE;rewrite ?(cohVs C)//.\nmove:(this_not_pts Hnin Hp)=>/G; rewrite /pt_state=>->.\nby rewrite /pt_state.\nQed.\n\n(*** [Coordinator] Send commit-request ***)\n\nProgram Definition s2: Sinv (cn_send_commit_trans cn pts others).\nProof.\nmove=>this to d msg S h/= Hi/=[]T G.\ncase: (S)=>[][/eqP]Z Hto[C]; subst this.\n\nmove=>[[round][next_data][recvd]|[round][next_data][sent]].\n- move=>[St M P A]. subst msg.\n  rewrite (PI (cn_safe_coh _) C) St in T.\n  case: (@inv_waitprep l cn pts others Hnin _ round C next_data recvd Hi St) =>lg.\n  move=>[] Hst Huniq Hsub Hrecvd1 Hrecvd2.\n  exists round, lg. constructor 3.\n  exists next_data.\n  rewrite (getStL_Kc C _ Hst) /cstep_send Hto P A in T.\n  case X: (pts == [::to]);\n    [constructor 3; exists [::]|constructor 1; exists [:: to]];\n    rewrite X in T; subst h; split=>//;\n    do?[by rewrite /cn_state locE' ?(cohVl C)//]; first 1 last.\n  + by move=>x; rewrite inE => /eqP->.\n  + move=>pt Hpt.\n    case: ifP; rewrite inE.\n    * move=>/eqP ?; subst pt.\n      have Htorecv: (to, true) \\in recvd by apply (has_all_true P A).\n      case: (Hrecvd1 _ _ Hpt Htorecv) => M1 M2 PS.\n      constructor 1; split.\n      by move: PS; rewrite /pt_state (G _ (this_not_pts Hnin Hpt)).\n      by apply: msg_specE; rewrite ?(cohVs C).\n      by apply: (no_msg_from_toE' (cohVs C))=>//;\n         rewrite eq_sym (this_not_pts Hnin Hto).\n    * move=> Npt.\n      have Hptrecvd: (pt, true) \\in recvd by apply (has_all_true P A).\n      move: (Hrecvd1 _ _ Hpt Hptrecvd).\n      by apply: (@pt_PhaseOneRespondedE l cn pts others Hnin).\n  + move=>pt Hpt.\n    rewrite in_nil.\n    move/eqP in X.\n    rewrite X inE in Hpt.\n    move /eqP in Hpt. subst pt.\n    have Htorecv: (to, true) \\in recvd by apply (has_all_true P A).\n    case: (Hrecvd1 _ _ Hto Htorecv) => M1 M2 PS.\n    constructor 1; split.\n    by move: PS; rewrite /pt_state (G _ (this_not_pts Hnin Hto)).\n    by apply: msg_specE; rewrite ?(cohVs C).\n    by apply: (no_msg_from_toE' (cohVs C))=>//;\n         rewrite eq_sym (this_not_pts Hnin Hto).\n- move=>[St ? HtoNsent]. subst msg.\n  rewrite (PI (cn_safe_coh _) C) St in T.\n  case: (@inv_sentcommit l cn pts others Hnin _ round C next_data sent Hi St) =>lg.\n  case => Hst Huniq Hsub Hsent.\n  exists round, lg. constructor 3.\n  exists next_data.\n  rewrite (getStL_Kc C _ Hst) /cstep_send Hto in T.\n  case X: (perm_eq (to :: sent) pts); subst h; rewrite X; rewrite X in G.\n  + constructor 3. exists [::].\n    split=>//.\n    by rewrite /cn_state locE' ?(cohVl C).\n    move=>pt Hpt.\n    rewrite in_nil.\n    move/perm_eq_mem: X=>/(_ pt); rewrite inE Hpt.\n    case/orP.\n    * move/eqP=>?; subst pt.\n      move: (Hsent to Hto).\n      move: HtoNsent => /negbTE->.\n      case=> M1 M2 PS.\n      constructor 1; split.\n      by move: PS; rewrite /pt_state (G _ (this_not_pts Hnin Hto)).\n      by apply: msg_specE; rewrite ?(cohVs C).\n      by apply: (no_msg_from_toE' (cohVs C))=>//;\n         rewrite eq_sym (this_not_pts Hnin Hto).\n    * move=> Hptsent.\n      move: (Hsent _ Hpt).\n      rewrite Hptsent.\n      apply: (@pt_PhaseTwoCommitE l cn pts others Hnin)=>//.\n      apply/negP. move=>/eqP ?; subst pt.\n      move/negbTE in HtoNsent.\n      congruence.\n  + constructor 1. exists (to :: sent).\n    split.\n    * by rewrite /cn_state locE' ?(cohVl C).\n    * by rewrite cons_uniq Huniq andbT.\n    * by rewrite /sub_mem => x; rewrite in_cons => /orP[/eqP->|/Hsub].\n    * move=>pt Hpt.\n      rewrite in_cons.\n      case: ifP.\n      case/orP.\n      -- move/eqP=>?; subst pt.\n         move: (Hsent to Hto).\n         move: HtoNsent => /negbTE->.\n         case=> M1 M2 PS.\n         constructor 1; split.\n         by move: PS; rewrite /pt_state (G _ (this_not_pts Hnin Hto)).\n         by apply: msg_specE; rewrite ?(cohVs C).\n         by apply: (no_msg_from_toE' (cohVs C))=>//;\n                   rewrite eq_sym (this_not_pts Hnin Hto).\n      -- move=> Hptsent.\n         move: (Hsent _ Hpt).\n         rewrite Hptsent.\n         apply: (@pt_PhaseTwoCommitE l cn pts others Hnin)=>//.\n         apply/negP. move=>/eqP ?. subst pt.\n         move/negbTE in HtoNsent.\n         congruence.\n      -- move/Bool.orb_false_elim=>[N] HptNsent.\n         move: (Hsent pt Hpt).\n         rewrite HptNsent.\n         by apply: (@pt_PhaseOneRespondedE l cn pts others Hnin).\nQed.\n\n(*** [Coordinator] Send abort-request ***)\n\nProgram Definition s3: Sinv (cn_send_abort_trans cn pts others).\nProof.\nmove=>this to d msg S h/= Hi/=[]T G.\ncase: (S)=>[][/eqP]Z Hto[C]; subst this.\n\nmove=>[[round][next_data][recvd]|[round][next_data][sent]].\n\n- move=>[St M P A]. subst msg.\n  rewrite has_predC in A; move/negbTE: A=>A.\n  rewrite (PI (cn_safe_coh _) C) St in T.\n  case: (@inv_waitprep l cn pts others Hnin _ round C next_data recvd Hi St) =>lg.\n  move=>[] Hst Huniq Hsub Hrecvd1 Hrecvd2.\n  exists round, lg; constructor 3.\n  exists next_data.\n  rewrite (getStL_Kc C _ Hst) /cstep_send Hto P A in T.\n  case X: (pts == [::to]);\n    [constructor 4; exists [::]|constructor 2; exists [:: to]];\n    rewrite X in T; subst h; split=>//;\n    do?[by rewrite /cn_state locE' ?(cohVl C)//]; first 1 last.\n  + by move=>x; rewrite inE => /eqP->.\n  + move=>pt Hpt.\n    case: ifP; rewrite inE.\n    * move=>/eqP ?; subst pt.\n      have Htorecv: exists b, (to, b) \\in recvd\n           by apply: (has_some_false P Hpt).\n      case: Htorecv=>b Htorecv.\n      case: (Hrecvd1 _ _ Hpt Htorecv) => M1 M2 PS.\n      constructor 1; split=>/={Htorecv}.\n      by case: b PS; rewrite /pt_state (G _ (this_not_pts Hnin Hpt));\n         [left | right].\n      by apply: msg_specE; rewrite ?(cohVs C).\n      by apply: (no_msg_from_toE' (cohVs C))=>//;\n         rewrite eq_sym (this_not_pts Hnin Hto).\n    * move=> Npt.\n      have Htorecv: exists b, (pt, b) \\in recvd\n          by apply: (has_some_false P Hpt).\n      case: Htorecv=>b Htorecv/=; exists b.\n      apply: (@pt_PhaseOneRespondedE l cn pts others Hnin)=>//.\n      by apply: (Hrecvd1 pt _ _ Htorecv).\n  + move=>pt Hpt.\n    rewrite in_nil.\n    move/eqP in X.\n    rewrite X inE in Hpt.\n    move /eqP in Hpt. subst pt.\n    have Htorecv: exists b, (to, b) \\in recvd\n        by apply: (has_some_false P Hto).\n    case: Htorecv=>b Htorecv.\n    case: (Hrecvd1 _ _ Hto Htorecv) => M1 M2 PS {Htorecv}.\n    constructor 1; split.\n    by case: b PS; rewrite /pt_state (G _ (this_not_pts Hnin Hto));\n       [left | right].\n    by apply: msg_specE; rewrite ?(cohVs C).\n    by apply: (no_msg_from_toE' (cohVs C))=>//;\n         rewrite eq_sym (this_not_pts Hnin Hto).\n- move=>[St ? HtoNsent]. subst msg.\n  rewrite (PI (cn_safe_coh _) C) St in T.\n  case: (@inv_sentabort l cn pts others Hnin _ round C next_data sent Hi St) =>lg.\n  case => Hst Huniq Hsub Hsent.\n  exists round, lg. constructor 3.\n  exists next_data.\n  rewrite (getStL_Kc C _ Hst) /cstep_send Hto in T.\n  case X: (perm_eq (to :: sent) pts); subst h; rewrite X; rewrite X in G.\n  + constructor 4; exists [::].\n    split=>//.\n    by rewrite /cn_state locE' ?(cohVl C).\n    move=>pt Hpt.\n    rewrite in_nil.\n    move/perm_eq_mem: X=>/(_ pt); rewrite inE Hpt.\n    case/orP.\n    * move/eqP=>?; subst pt.\n      move: (Hsent to Hto).\n      move: HtoNsent => /negbTE->.\n      case=>b [M1] M2 PS.\n      constructor 1; split.\n      by case: b PS; rewrite /pt_state (G _ (this_not_pts Hnin Hto)); [left|right].\n      by apply: msg_specE; rewrite ?(cohVs C).\n      by apply: (no_msg_from_toE' (cohVs C))=>//;\n         rewrite eq_sym (this_not_pts Hnin Hto).\n    * move=> Hptsent.\n      move: (Hsent _ Hpt).\n      rewrite Hptsent.\n      apply: (@pt_PhaseTwoAbortE l cn pts others Hnin)=>//.\n      apply/negP. move=>/eqP ?. subst pt.\n      move/negbTE in HtoNsent.\n      congruence.\n  + constructor 2. exists (to :: sent).\n    split.\n    * by rewrite /cn_state locE' ?(cohVl C).\n    * by rewrite cons_uniq Huniq andbT.\n    * by rewrite /sub_mem => x; rewrite in_cons => /orP[/eqP->|/Hsub].\n    * move=>pt Hpt.\n      rewrite in_cons.\n      case: ifP.\n      case/orP.\n      -- move/eqP=>?; subst pt.\n         move: (Hsent to Hto).\n         move: HtoNsent => /negbTE->.\n         case=>b[M1] M2 PS.\n         constructor 1; split.\n         by case: b PS; rewrite /pt_state (G _ (this_not_pts Hnin Hto));\n            [left|right].\n         by apply: msg_specE; rewrite ?(cohVs C).\n         by apply: (no_msg_from_toE' (cohVs C))=>//;\n                   rewrite eq_sym (this_not_pts Hnin Hto).\n      -- move=> Hptsent.\n         move: (Hsent _ Hpt).\n         rewrite Hptsent.\n         apply: (@pt_PhaseTwoAbortE l cn pts others Hnin)=>//.\n         apply/negP. move=>/eqP ?. subst pt.\n         move/negbTE in HtoNsent.\n         congruence.\n      -- move/Bool.orb_false_elim=>[N] HptNsent.\n         move: (Hsent pt Hpt).\n         rewrite HptNsent; case=>b H; exists b.\n         by apply: (@pt_PhaseOneRespondedE l cn pts others Hnin).\nQed.\n\n(*** [Pariticpant] Send yes ***)\n\nProgram Definition s4: Sinv (pn_send_yes_trans others Hnin).\nProof.\nmove=>this to d m S h I [] T G.\ncase: (S)=>[][] Hthis /eqP ? [H][C] [r][nd][PS] ?. subst to m.\nhave Vl := cohVl C.\nhave Vs := cohVs C.\nmove: (inv_gotrequest(l:=l) Hthis PS I)=> [lg]PO.\nmove: (PhaseOne_round_pt Hthis PO) => [ps] PS'.\nmove: PS.\nrewrite (getStP_K Hnin C _ Hthis PS').\ncase=>?. subst ps.\nmove: PS'=>PS.\nexists r, lg.\nconstructor 2.\nexists nd.\nmove: (PhaseOne_PGotRequest_next_data_pt(l:=l)(Hnin:=Hnin) C Hthis PS PO) =>[]_ NM1 NM2.\ncase: PO=>[[sent]|[recvd]].\n- case=>CS' U Sub Pts.\n  left. exists sent.\n  split=>//.\n  + apply /(cn_state_soupE(Hnin := Hnin) _ _ C)=>//.\n    by apply: (pt_not_cn Hnin).\n  + move=>pt Hpt.\n    move: (Pts _ Hpt).\n    case E: (this == pt).\n    + move/eqP in E. subst pt.\n      case: ifP.\n      * move=>_ _.\n        constructor 3.\n        split.\n        -- rewrite /pt_state locE'//. subst.\n           by rewrite (getStP_K Hnin _ _ Hthis PS)\n                      (getStL_Kp _ _ PS).\n        -- apply /no_msg_from_toE'=>//.\n           by apply/negbTE/(pt_not_cn Hnin).\n        -- by apply /msg_specE.\n      * move=>_ [] PS'.\n        move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _.\n        move: (pt_state_functional V PS PS')=>[]; discriminate.\n    + move/negbT in E.\n      case: ifP.\n      * move=>_.\n        apply: (pt_PhaseOneE' _ _ _ C)=>//.\n        by apply/(pt_not_cn Hnin).\n      * move=>_.\n        apply: (pt_InitE _ _ _ C)=>//.\n        by apply/(pt_not_cn Hnin).\n- case=>CS' U Sub Hrecvd1 Hrecvd2.\n  right. exists recvd.\n  split=>//.\n  + apply /(cn_state_soupE _ _ C)=>//.\n    by apply: (pt_not_cn Hnin).\n  + move=>pt b Hpt Hr.\n    case E: (this == pt).\n    * move/eqP in E. subst pt.\n      exfalso.\n      case: (Hrecvd1 _ _ Hpt Hr)=> _ _.\n      case: ifP=>_ PS';\n        move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n        move: (pt_state_functional V PS PS')=>[]; discriminate.\n    * move: (Hrecvd1 pt b Hpt Hr).\n      apply: (pt_PhaseOneRespondedE' _ _ _ C)=>//.\n      by apply /negbT.\n      by apply: (pt_not_cn Hnin).\n  + move=>pt Hpt Hr.\n    case E: (this == pt).\n    * move/eqP in E. subst pt.\n      constructor 3.\n      split.\n      -- rewrite /pt_state locE'//. subst.\n           by rewrite (getStP_K Hnin _ _ Hthis PS)\n                      (getStL_Kp _ _ PS).\n      -- apply /no_msg_from_toE'=>//.\n         by apply /negbTE/(pt_not_cn Hnin).\n      -- by apply msg_specE=>//.\n    * move: (Hrecvd2 pt Hpt Hr).\n      apply: (pt_PhaseOneE' _ _ _ C)=>//.\n      by apply /negbT.\n      by apply: (pt_not_cn Hnin).\nQed.\n\n(*** [Pariticpant] Send no ***)\n\nProgram Definition s5: Sinv (pn_send_no_trans others Hnin).\nProof.\nmove=>this to d m S h I [] T G.\ncase: (S)=>[][] Hthis /eqP ? [H][C] [r][nd][PS] ?. subst to m.\nhave Vl := cohVl C.\nhave Vs := cohVs C.\nmove: (inv_gotrequest(l := l) Hthis PS I)=> [lg]PO.\nmove: (PhaseOne_round_pt Hthis PO) => [ps] PS'.\nmove: PS.\nrewrite (getStP_K Hnin C _ Hthis PS').\ncase=>?. subst ps.\nmove: PS'=>PS.\nexists r, lg.\nconstructor 2.\nexists nd.\nmove: (PhaseOne_PGotRequest_next_data_pt(l:=l)(Hnin:=Hnin) C Hthis PS PO) =>[]_ NM1 NM2.\ncase: PO=>[[sent]|[recvd]].\n- case=>CS' U Sub Pts.\n  left. exists sent.\n  split=>//.\n  + apply /(cn_state_soupE _ _ C)=>//.\n    by apply: (pt_not_cn Hnin).\n  + move=>pt Hpt.\n    move: (Pts _ Hpt).\n    case E: (this == pt).\n    + move/eqP in E. subst pt.\n      case: ifP.\n      * move=>_ _.\n        constructor 4.\n        split.\n        -- rewrite /pt_state locE'//. subst.\n           by rewrite (getStP_K Hnin _ _ Hthis PS)\n                      (getStL_Kp _ _ PS).\n        -- apply /no_msg_from_toE'=>//.\n           by apply/negbTE/(pt_not_cn Hnin).\n        -- by apply /msg_specE.\n      * move=>_ [] PS'.\n        move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _.\n        move: (pt_state_functional V PS PS')=>[]; discriminate.\n    + move/negbT in E.\n      case: ifP.\n      * move=>_.\n        apply: (pt_PhaseOneE' _ _ _ C)=>//.\n        by apply/(pt_not_cn Hnin).\n      * move=>_.\n        apply: (pt_InitE _ _ _ C)=>//.\n        by apply/(pt_not_cn Hnin).\n- case=>CS' U Sub Hrecvd1 Hrecvd2.\n  right. exists recvd.\n  split=>//.\n  + apply /(cn_state_soupE _ _ C)=>//.\n    by apply: (pt_not_cn Hnin).\n  + move=>pt b Hpt Hr.\n    case E: (this == pt).\n    * move/eqP in E. subst pt.\n      exfalso.\n      case: (Hrecvd1 _ _ Hpt Hr)=> _ _.\n      case: ifP=>_ PS';\n        move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n        move: (pt_state_functional V PS PS')=>[]; discriminate.\n    * move: (Hrecvd1 pt b Hpt Hr).\n      apply: (pt_PhaseOneRespondedE' _ _ _ C)=>//.\n      by apply /negbT.\n      by apply: (pt_not_cn Hnin).\n  + move=>pt Hpt Hr.\n    case E: (this == pt).\n    * move/eqP in E. subst pt.\n      constructor 4.\n      split.\n      -- rewrite /pt_state locE'//. subst.\n           by rewrite (getStP_K Hnin _ _ Hthis PS)\n                      (getStL_Kp _ _ PS).\n      -- apply /no_msg_from_toE'=>//.\n         by apply /negbTE/(pt_not_cn Hnin).\n      -- by apply msg_specE=>//.\n    * move: (Hrecvd2 pt Hpt Hr).\n      apply: (pt_PhaseOneE' _ _ _ C)=>//.\n      by apply /negbT.\n      by apply: (pt_not_cn Hnin).\nQed.\n\n(*** [Pariticpant] Send commit-ack ***)\n\nProgram Definition s6: Sinv (pn_commit_ack_trans others Hnin).\nProof.\nmove=>this to d m S h I [] T G.\ncase: (S)=>[][] Hthis /eqP ? [H][C] [r][nd][PS] ?. subst to m.\nhave Vl := cohVl C.\nhave Vs := cohVs C.\n\nmove: (inv_committed(l:=l) Hthis PS I)=> [lg] PT.\ncase: (PhaseTwo_PCommitted_pt(l := l)(Hnin := Hnin) Hthis PS PT)=>{PS}PS NM1 NM2.\nexists r, lg.\nconstructor 3.\nexists nd.\nhave: this != cn by apply: (pt_not_cn Hnin).\ncase: PT=>[[sent]|[sent]|[recvd]|[recvd]] {I}I;\n  [constructor 1; exists sent|constructor 2; exists sent|\n   constructor 3; exists recvd|constructor 4; exists recvd];\ncase: I=> CS U S' Pts; split=>//;\ndo?[by apply /(cn_state_soupE _ _ C)=>//];\nmove=> pt Hpt; move: (Pts pt Hpt); case: ifP=>_.\n- case E: (this == pt).\n  + move/eqP in E. subst pt.\n    move=>_.\n    constructor 3.\n    split.\n    * by rewrite /pt_state locE'// T\n              (getStP_K _ _ _ _ PS)//\n              (getStL_Kp _ _ PS).\n    * apply /no_msg_from_toE'=>//.\n      by apply: negbTE.\n    * by apply: msg_specE=>//.\n  + move/negbT in E.\n    by apply: (pt_PhaseTwoCommitE' _ _ _ C)=>//.\n- move=>H1.\n  apply: (pt_PhaseOneRespondedE' _ _ _ C)=>//.\n  case E: (this == pt)=>//.\n  move/eqP in E. subst pt.\n  case: H1 => _ _ PS'.\n  move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n  move: (pt_state_functional V PS PS')=>[]; discriminate.\n- move=>H1.\n  apply: (pt_PhaseTwoAbortE' _ _ _ C)=>//.\n  case E: (this == pt)=>//.\n  move/eqP in E. subst pt.\n  case: H1 => [][][]PS' _ _;\n  move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n  move: (pt_state_functional V PS PS')=>[]; discriminate.\n- move=>[b] H1.\n  exists b.\n  apply: (pt_PhaseOneRespondedE' _ _ _ C)=>//.\n  case E: (this == pt)=>//.\n  move/eqP in E. subst pt.\n  case: H1 => _ _; case: ifP=>_ PS';\n  move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n  move: (pt_state_functional V PS PS')=>[]; discriminate.\n- move=>H1.\n  apply: (pt_PhaseTwoRespondedE' _ _ _ C)=>//.\n  case E: (this == pt)=>//.\n  move/eqP in E. subst pt.\n  case: H1=> PS' _ _;\n  move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n  move: (pt_state_functional V PS PS')=>[]; discriminate.\n- case E: (this == pt).\n  + move/eqP in E. subst pt.\n    move=>_.\n    constructor 3.\n    split.\n    * by rewrite /pt_state locE'// T\n              (getStP_K _ _ _ _ PS)//\n              (getStL_Kp _ _ PS).\n    * apply /no_msg_from_toE'=>//.\n      by apply: negbTE.\n    * by apply: msg_specE=>//.\n  + move/negbT in E.\n    by apply: (pt_PhaseTwoCommitE' _ _ _ C)=>//.\n- move=>H1.\n  apply: (pt_PhaseTwoRespondedE' _ _ _ C)=>//.\n  case E: (this == pt)=>//.\n  move/eqP in E. subst pt.\n  case: H1=> PS' _ _;\n  move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n  move: (pt_state_functional V PS PS')=>[]; discriminate.\n- move=>H1.\n  apply: (pt_PhaseTwoAbortE' _ _ _ C)=>//.\n  case E: (this == pt)=>//.\n  move/eqP in E. subst pt.\n  case: H1 => [][][]PS' _ _;\n  move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n  move: (pt_state_functional V PS PS')=>[]; discriminate.\nQed.\n\n(*** [Pariticpant] Send abort-ack ***)\n\nProgram Definition s7: Sinv (pn_abort_ack_trans others Hnin).\nProof.\nmove=>this to d m S h I [] T G.\ncase: (S)=>[][] Hthis /eqP ? [H][C] [r][nd][PS] ?. subst to m.\nhave Vl := cohVl C.\nhave Vs := cohVs C.\n\nmove: (inv_aborted(l:=l) Hthis PS I)=> [lg] PT.\ncase: (PhaseTwo_PAborted_pt(l:=l)(Hnin:=Hnin) Hthis PS PT)=>{PS}PS NM1 NM2.\nexists r, lg.\nconstructor 3.\nexists nd.\nhave: this != cn by apply: (pt_not_cn Hnin).\ncase: PT=>[[sent]|[sent]|[recvd]|[recvd]] {I}I;\n  [constructor 1; exists sent|constructor 2; exists sent|\n   constructor 3; exists recvd|constructor 4; exists recvd];\ncase: I=> CS U S' Pts; split=>//;\ndo?[by apply /(cn_state_soupE _ _ C)=>//];\nmove=> pt Hpt; move: (Pts pt Hpt); case: ifP=>_.\n- move=>H1.\n  apply: (pt_PhaseTwoCommitE' _ _ _ C)=>//.\n  case E: (this == pt)=>//.\n  move/eqP in E. subst pt.\n  case: H1 => [][][]PS' _ _;\n  move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n  move: (pt_state_functional V PS PS')=>[]; discriminate.\n- move=>H1.\n  apply: (pt_PhaseOneRespondedE' _ _ _ C)=>//.\n  case E: (this == pt)=>//.\n  move/eqP in E. subst pt.\n  case: H1 => _ _ PS'.\n  move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n  move: (pt_state_functional V PS PS')=>[]; discriminate.\n- case E: (this == pt).\n  + move/eqP in E. subst pt.\n    move=>_.\n    constructor 3.\n    split.\n    * by rewrite /pt_state locE'// T\n              (getStP_K _ _ _ _ PS)//\n              (getStL_Kp _ _ PS).\n    * apply /no_msg_from_toE'=>//.\n      by apply: negbTE.\n    * by apply: msg_specE=>//.\n  + move/negbT in E.\n    by apply: (pt_PhaseTwoAbortE' _ _ _ C)=>//.\n- move=>[b] H1.\n  exists b.\n  apply: (pt_PhaseOneRespondedE' _ _ _ C)=>//.\n  case E: (this == pt)=>//.\n  move/eqP in E. subst pt.\n  case: H1 => _ _; case: ifP=>_ PS';\n  move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n  move: (pt_state_functional V PS PS')=>[]; discriminate.\n- move=>H1.\n  apply: (pt_PhaseTwoRespondedE' _ _ _ C)=>//.\n  case E: (this == pt)=>//.\n  move/eqP in E. subst pt.\n  case: H1=> PS' _ _;\n  move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n  move: (pt_state_functional V PS PS')=>[]; discriminate.\n- move=>H1.\n  apply: (pt_PhaseTwoCommitE' _ _ _ C)=>//.\n  case E: (this == pt)=>//.\n  move/eqP in E. subst pt.\n  case: H1 => [][][]PS' _ _;\n  move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n  move: (pt_state_functional V PS PS')=>[]; discriminate.\n- move=>H1.\n  apply: (pt_PhaseTwoRespondedE' _ _ _ C)=>//.\n  case E: (this == pt)=>//.\n  move/eqP in E. subst pt.\n  case: H1=> PS' _ _;\n  move: C=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _;\n  move: (pt_state_functional V PS PS')=>[]; discriminate.\n- case E: (this == pt).\n  + move/eqP in E. subst pt.\n    move=>_.\n    constructor 3.\n    split.\n    * by rewrite /pt_state locE'// T\n              (getStP_K _ _ _ _ PS)//\n              (getStL_Kp _ _ PS).\n    * apply /no_msg_from_toE'=>//.\n      by apply: negbTE.\n    * by apply: msg_specE=>//.\n  + move/negbT in E.\n    by apply: (pt_PhaseTwoAbortE' _ _ _ C)=>//.\nQed.\n\n\n(*************************************************************)\n(*                  Receive-transitions                      *)\n(*************************************************************)\n\n(*** [Coordinator] Receive \"yes\" ***)\n\nProgram Definition r1: Rinv (cn_receive_prep_yes_trans cn pts others).\nProof.\nmove=>d from this i C [tag m] H1 I F D/= Hmatch Et G.\nsubst tag.\n\ncase Hinternal: (internal_msg cn pts prep_yes from this); first last.\n- move /negbT in Hinternal.\n  rewrite (rc_step_external _ _ _ F)//.\n  by apply /(invE_consume_external C F)=>//.\n\nrewrite /rc_step/cstep_recv.\ncase CS: (getStC (cn:=cn) (pts:=pts) (others:=others) (d:=d) C) => [round cs].\nhave Hthis := (internal_msg_tagFromParticipant_to_cn Hinternal erefl).\nrewrite Hthis. move/eqP in Hthis. subst this.\nhave Hfrom := (internal_msg_tagFromParticipant_from_pts Hinternal erefl).\nrewrite Hfrom/=.\nhave Hround := (inv_msg_round F Hinternal I CS).\nrewrite Hround/=.\n\nmove: Hmatch.\nrewrite CS/=.\nmove=>/c_matches_tag_prep_yes_inv [next_data] [recvd] ?.\nsubst cs.\nmove: (CS)=>/inv_waitprep.\nmove => /(_ I){I} [lg] I.\ncase: (I) => []Hst U Hsub Hrecvd1 Hrecvd2.\nexists round, lg. constructor 2.\nexists next_data. right.\ncase: ifP.\n- move => Hignore.\n  exists recvd.\n  rewrite (getStL_Kc C _ Hst).\n  by apply: (@cn_PhaseOneReceive_consume l cn pts others _ _ _ _ _ _ _ _ from); try exact: F.\nmove /negbT=>Hnew.\nexists ((from, true) :: recvd).\nsplit.\n- rewrite /cn_state locE'; last by exact: (cohVl C).\n  by rewrite (getStL_Kc C _ Hst) eqxx.\n- by rewrite cons_uniq /= Hnew.\n- by move => x; rewrite inE /=; move=> /orP[/eqP->|]//; exact: Hsub.\n- move => pt b Hpt.\n  rewrite inE => /orP[].\n  + move=>/eqP[] ? ?. subst pt b.\n    move: Hnew.\n    move /(Hrecvd2 _ Hpt)/(@prep_yes_pt_inv cn _ _ _ _ _ _ _ _ F).\n    move /(_ erefl).\n    case=>[]PS NM M.\n    split=>/=.\n    by apply /no_msg_from_to_consume=>//; rewrite (cohVs C).\n    clear G.\n    by apply: (msg_spec_consume (cohVs C) F M).\n    rewrite /pt_state.\n    have HfromN: from != cn.\n    * apply /negbT.\n      case H: (from == cn)=>//.\n      move/eqP in H. subst from.\n      by move: (Hnin); rewrite Hpt.\n    by rewrite locU// (cohVl C).\n  move=>Hr; apply /(@pt_PhaseOneRespondedE_consume l cn pts others _)=>//.\n  by apply: (pt_not_cn Hnin).\n  by apply Hrecvd1; auto.\n- move=>pt Hpt.\n  rewrite inE.\n  move=>/norP/=[] N Hr.\n  apply /(@pt_PhaseOneE_consume l cn pts others _ _ _ _ _ _ _ _ from _)=>//; try exact: F.\n  by apply /(pt_not_cn _ Hpt).\n  apply /Hrecvd2=>//.\nQed.\n\n(*** [Coordinator] Receive \"no\" ***)\n\nProgram Definition r2: Rinv (cn_receive_prep_no_trans cn pts others).\nProof.\nmove=>d from this i C [tag m] H1 I F D/= Hmatch Et G.\nsubst tag.\n\ncase Hinternal: (internal_msg cn pts prep_yes from this); first last.\n- move /negbT in Hinternal.\n  rewrite (rc_step_external _ _ _ F)//.\n  by apply /(invE_consume_external C F)=>//.\n\nrewrite /rc_step/cstep_recv.\ncase CS: (getStC (cn:=cn) (pts:=pts) (others:=others) (d:=d) C) => [round cs].\nhave Hthis := (internal_msg_tagFromParticipant_to_cn Hinternal erefl).\nrewrite Hthis. move/eqP in Hthis. subst this.\nhave Hfrom := (internal_msg_tagFromParticipant_from_pts Hinternal erefl).\nrewrite Hfrom/=.\nhave Hround := (inv_msg_round F Hinternal I CS).\nrewrite Hround/=.\n\nmove: Hmatch.\nrewrite CS/=.\nmove=>/c_matches_tag_prep_yes_inv [next_data] [recvd] ?.\nsubst cs.\nmove: (CS)=>/inv_waitprep.\nmove => /(_ I){I} [lg] I.\ncase: (I) => []Hst U Hsub Hrecvd1 Hrecvd2.\nexists round, lg. constructor 2.\nexists next_data. right.\ncase: ifP.\n- move => Hignore.\n  exists recvd.\n  rewrite (getStL_Kc C _ Hst).\n  by apply: (@cn_PhaseOneReceive_consume l cn pts others _ _ _ _ _ _ _ _ from _ F).\nmove /negbT=>Hnew.\nexists ((from, false) :: recvd).\nsplit.\n- rewrite /cn_state locE'; last by exact: (cohVl C).\n  by rewrite (getStL_Kc C _ Hst).\n- by rewrite cons_uniq /= Hnew.\n- by move => x; rewrite inE /=; move=> /orP[/eqP->|]//; exact: Hsub.\n- move => pt b Hpt.\n  rewrite inE => /orP[].\n  + move=>/eqP[] ? ?. subst pt b.\n    move: Hnew.\n    move /(Hrecvd2 _ Hpt)/(@prep_no_pt_inv cn _ _ _ _ _ _ _ _ F).\n    move /(_ erefl).\n    case=>[]PS NM M.\n    split=>/=.\n    by apply /no_msg_from_to_consume=>//; rewrite (cohVs C).\n    clear G.\n    by apply: (msg_spec_consume (cohVs C) F M).\n    rewrite /pt_state.\n    have HfromN: from != cn.\n    * apply /negbT.\n      case H: (from == cn)=>//.\n      move/eqP in H. subst from.\n      by move: (Hnin); rewrite Hpt.\n    by rewrite locU// (cohVl C).\n  move=>Hr; apply /(@pt_PhaseOneRespondedE_consume l cn pts others _)=>//.\n  by apply: (pt_not_cn Hnin).\n  by apply Hrecvd1; auto.\n- move=>pt Hpt.\n  rewrite inE.\n  move=>/norP/=[] N Hr.\n  apply /(pt_PhaseOneE_consume _ C _ _ _ F)=>//.\n  by apply /(pt_not_cn Hnin).\n  apply /Hrecvd2=>//.\nQed.\n\n\n(*** [Coordinator] Receive commit-ack ***)\n\nProgram Definition r3: Rinv (cn_receive_commit_ack_trans cn pts others).\nProof.\nmove=>d from this i C [tag m] H1 I F D/= Hmatch Et G.\nsubst tag.\nhave Vl := cohVl C.\nhave Vs := cohVs C.\n\ncase Hinternal: (internal_msg cn pts prep_yes from this); first last.\n- move /negbT in Hinternal.\n  rewrite (rc_step_external _ _ _ F)//.\n  by apply /(invE_consume_external C F)=>//.\n\nrewrite /rc_step/cstep_recv.\ncase CS: (getStC (cn:=cn) (pts:=pts) (others:=others) (d:=d) C) => [round cs].\nhave Hthis := (internal_msg_tagFromParticipant_to_cn Hinternal erefl).\nrewrite Hthis. move/eqP in Hthis. subst this.\nhave Hfrom := (internal_msg_tagFromParticipant_from_pts Hinternal erefl).\nrewrite Hfrom/=.\nhave Hround := (inv_msg_round F Hinternal I CS).\nrewrite Hround/=.\n\nmove: Hmatch.\nrewrite CS/=.\nmove=>/c_matches_tag_commit_ack_inv [next_data] [recvd] ?.\nsubst cs.\nmove: (CS)=>/inv_waitcommit.\nmove => /(_ I){I} [lg] I.\ncase: (I) => [] Hst U Hsub Pts.\ncase: ifP.\n- move => Hignore.\n  exfalso.\n  move: (Pts _ Hfrom). rewrite Hignore.\n  by move=>[] _ _ /(_ _ _ _ F).\nmove=>/negbT Hr.\ncase: ifP.\n- move=>P.\n  exists round.+1, (rcons lg (true, next_data)).\n  constructor 1.\n  split.\n  + rewrite /cn_state locE'//.\n    by rewrite (getStL_Kc C _ Hst).\n  + move=>pt Hpt.\n    move/Pts: (Hpt).\n    move: (perm_eq_mem P) => {P}P.\n    move: (Hpt).\n    rewrite -P inE.\n    case/orP.\n    * move/eqP=>?. subst pt.\n      rewrite (negbTE Hr).\n      move/(commit_ack_pt_inv _ F)=>/(_ erefl)[] PS NM M.\n      split.\n      -- rewrite /pt_state locU//.\n         by apply /(@pt_not_cn cn pts Hnin from)=>//.\n      -- by apply /(msg_spec_consume _ F M).\n      -- by apply /no_msg_from_to_consume=>//.\n    * move=>->[] PS NM1 NM2.\n      split.\n      -- apply /(pt_state_consume _ _ _ C)=>//.\n         by apply /(@pt_not_cn cn pts Hnin pt)=>//.\n      -- by apply /no_msg_from_to_consume=>//.\n      -- by apply /no_msg_from_to_consume=>//.\n- move=>P.\n  exists round, lg.\n  constructor 3.\n  exists next_data.\n  constructor 3.\n  exists (from :: recvd).\n  split.\n  + rewrite /cn_state locE'//.\n    by rewrite (getStL_Kc C _ Hst).\n  + by rewrite cons_uniq /= Hr.\n  + by move => x; rewrite inE /=; move=> /orP[/eqP->|]//; exact: Hsub.\n  + move=> pt Hpt.\n    rewrite inE.\n    move: (Pts pt Hpt).\n    case: ifP.\n    * rewrite orbT=>Hr'.\n       apply: (pt_PhaseTwoRespondedE_consume(pts:=pts) _ _ C)=>//.\n       by apply: (pt_not_cn Hnin).\n    * rewrite orbF.\n      case: ifP.\n      -- move/eqP => ? _. subst pt.\n         move/(commit_ack_pt_inv _ F)=>/(_ erefl)[] PS NM M.\n         split.\n         ++ rewrite /pt_state locU//.\n            by apply /(@pt_not_cn cn pts Hnin from)=>//.\n         ++ by apply /no_msg_from_to_consume=>//.\n         ++ by apply /(msg_spec_consume _ F M).\n      -- move=>/negbT N /negbT H.\n         apply: (pt_PhaseTwoCommitE_consume _ C _ _ F)=>//.\n         by apply: (pt_not_cn Hnin).\nQed.\n\n\n\n(*** [Coordinator] Receive abort-ack ***)\n\nProgram Definition r4: Rinv (cn_receive_abort_ack_trans cn pts others).\nProof.\nmove=>d from this i C [tag m] H1 I F D/= Hmatch Et G.\nsubst tag.\nhave Vl := cohVl C.\nhave Vs := cohVs C.\n\ncase Hinternal: (internal_msg cn pts prep_yes from this); first last.\n- move /negbT in Hinternal.\n  rewrite (rc_step_external _ _ _ F)//.\n  by apply /(invE_consume_external C F)=>//.\n\nrewrite /rc_step/cstep_recv.\ncase CS: (getStC (cn:=cn) (pts:=pts) (others:=others) (d:=d) C) => [round cs].\nhave Hthis := (internal_msg_tagFromParticipant_to_cn Hinternal erefl).\nrewrite Hthis. move/eqP in Hthis. subst this.\nhave Hfrom := (internal_msg_tagFromParticipant_from_pts Hinternal erefl).\nrewrite Hfrom/=.\nhave Hround := (inv_msg_round F Hinternal I CS).\nrewrite Hround/=.\n\nmove: Hmatch.\nrewrite CS/=.\nmove=>/c_matches_tag_abort_ack_inv [next_data] [recvd] ?.\nsubst cs.\nmove: (CS)=>/inv_waitabort.\nmove => /(_ I){I} [lg] I.\ncase: (I) => [] Hst U Hsub Pts.\ncase: ifP.\n- move => Hignore.\n  exfalso.\n  move: (Pts _ Hfrom). rewrite Hignore.\n  by move=>[] _ _ /(_ _ _ _ F).\nmove=>/negbT Hr.\ncase: ifP.\n- move=>P.\n  exists round.+1, (rcons lg (false, next_data)).\n  constructor 1.\n  split.\n  + rewrite /cn_state locE'//.\n    by rewrite (getStL_Kc C _ Hst).\n  + move=>pt Hpt.\n    move/Pts: (Hpt).\n    move: (perm_eq_mem P) => {P}P.\n    move: (Hpt).\n    rewrite -P inE.\n    case/orP.\n    * move/eqP=>?. subst pt.\n      rewrite (negbTE Hr).\n      move/(abort_ack_pt_inv _ F)=>/(_ erefl)[] PS NM M.\n      split.\n      -- rewrite /pt_state locU//.\n         by apply /(@pt_not_cn cn pts Hnin from)=>//.\n      -- by apply /(msg_spec_consume _ F M).\n      -- by apply /no_msg_from_to_consume=>//.\n    * move=>->[] PS NM1 NM2.\n      split.\n      -- apply /(pt_state_consume _ _ _ C)=>//.\n         by apply /(@pt_not_cn cn pts Hnin pt)=>//.\n      -- by apply /no_msg_from_to_consume=>//.\n      -- by apply /no_msg_from_to_consume=>//.\n- move=>P.\n  exists round, lg.\n  constructor 3.\n  exists next_data.\n  constructor 4.\n  exists (from :: recvd).\n  split.\n  + rewrite /cn_state locE'//.\n    by rewrite (getStL_Kc C _ Hst).\n  + by rewrite cons_uniq /= Hr.\n  + by move => x; rewrite inE /=; move=> /orP[/eqP->|]//; exact: Hsub.\n  + move=> pt Hpt.\n    rewrite inE.\n    move: (Pts pt Hpt).\n    case: ifP.\n    * rewrite orbT=>Hr'.\n      apply: (pt_PhaseTwoRespondedE_consume(pts:=pts) _ _ C)=>//.\n      by apply: (pt_not_cn Hnin).\n    * rewrite orbF.\n      case: ifP.\n      -- move/eqP => ? _. subst pt.\n         move/(abort_ack_pt_inv _ F)=>/(_ erefl)[] PS NM M.\n         split.\n         ++ rewrite /pt_state locU//.\n            by apply /(@pt_not_cn cn pts Hnin from)=>//.\n         ++ by apply /no_msg_from_to_consume=>//.\n         ++ by apply /(msg_spec_consume _ F M).\n      -- move=>/negbT N /negbT H.\n         apply: (pt_PhaseTwoAbortE_consume _ C _ _ F)=>//.\n         by apply: (pt_not_cn Hnin).\nQed.\n\n(*** [Pariticpant] Receive prep-request ***)\n\nProgram Definition r5: Rinv (pn_receive_got_prep_trans others Hnin).\nProof.\nmove=>d from this i C [tag m] H1 I F D/= _ Et G.\nsubst tag.\nhave Vl := cohVl C.\nhave Vs := cohVs C.\n\ncase Hinternal: (internal_msg cn pts prep_req from this); first last.\n- move /negbT in Hinternal.\n  rewrite (rp_step_external _ _ _ F)//.\n  by apply /(invE_consume_external C F)=>//.\n\nrewrite /rp_step/pstep_recv.\ncase PS: (getStP Hnin C H1) => [round ps].\nhave Hthis := (internal_msg_tagFromCoordinator_to_pts Hinternal erefl).\nrewrite Hthis.\nhave Hfrom := (internal_msg_tagFromCoordinator_from_cn Hinternal erefl).\nrewrite Hfrom/=. move/eqP in Hfrom. subst from.\n\nmove: (fun H => prep_req_cn_inv H Hthis F I) => /(_ erefl) [r][lg][nd] PO.\nmove: (PhaseOne_round_pt Hthis PO)=>[ps'] PS'.\nmove: PS.\nrewrite (getStP_K Hnin C H1 Hthis PS').\ncase=> ? ?. subst.\nmove: (PhaseOne_round_cn PO)=>[cs] CS.\nmove /(getStC_K C) in CS.\nhave Hround := (inv_msg_round F Hinternal I CS).\nrewrite Hround/= !orbF.\n\nhave Hmatch := (p_matches_tag_internal_inv C Hthis F Hinternal PS' I).\nrewrite Hmatch /=.\n\nmove: Hmatch. rewrite /p_matches_tag.\ndestruct ps=>// _.\nexists round, lg.\nconstructor 2.\nexists nd.\nmove: (PhaseOne_msg_next_data C F Hinternal PO) => /eqP Hnd. subst.\nmove: PO=>[].\n- move=>[sent][] CS' U S Pts.\n  left. exists sent. split=>//.\n  + apply/(cn_state_consume _ _ _ C)=>//.\n    by apply /eqP/nesym/eqP/(pt_not_cn Hnin).\n  + move=>pt Hpt.\n    move: (Pts _ Hpt).\n    case: ifP => _ H.\n    * case E: (pt == this).\n      -- move /eqP in E. subst pt.\n         case/(prep_req_pt_inv F): H=>_ NM M.\n         constructor 2.\n         split.\n         ++ by rewrite/ pt_state locE'// (getStL_Kp C H1 PS').\n         ++ by apply /no_msg_from_to_consume.\n         ++ by apply /(msg_spec_consume _ F M).\n      -- move /negbT in E.\n         apply /(pt_PhaseOneE_consume _ C _ _ _ F)=>//.\n         by apply: (pt_not_cn Hnin).\n    * case E: (pt == this).\n      -- move/eqP in E. subst pt.\n         case: H => PS NM1 NM2.\n         by move: (NM2 _ _ _ F).\n      -- move/negbT in E.\n         apply /(pt_InitE_consume _ C _ _ _ F)=>//.\n         by apply /(pt_not_cn Hnin).\n- move=>[recvd][] CS' U S Hrecvd1 Hrecvd2.\n  right. exists recvd. split=>//.\n  + apply/(cn_state_consume _ _ _ C)=>//.\n    by apply /eqP/nesym/eqP/(pt_not_cn Hnin).\n  + move=>pt b Hpt Hr.\n    case E: (pt == this).\n    * move/eqP in E. subst pt.\n      case: (Hrecvd1 _ _ Hpt Hr).\n      by move=>/(_ _ _ _ F).\n    * move/negbT in E.\n      apply /(pt_PhaseOneRespondedE_consume _ _ C)=>//.\n      by apply: Hrecvd1.\n  + move=>pt Hpt Hr.\n    move: (Hrecvd2 _ Hpt Hr).\n    case E: (pt == this).\n    * move/eqP in E. subst pt.\n      case/(prep_req_pt_inv F)=>_ NM1 M.\n      constructor 2. split.\n      ++ by rewrite/ pt_state locE'// (getStL_Kp C H1 PS').\n      ++ by apply /no_msg_from_to_consume.\n      ++ by apply /(msg_spec_consume _ F M).\n    * move/negbT in E.\n      apply /(pt_PhaseOneE_consume _ C _ _ _ F)=>//.\n      by apply: (pt_not_cn Hnin).\nQed.\n\n(*** [Pariticpant] Receive commit-request ***)\n\nProgram Definition r6: Rinv (pn_receive_commit_ack_trans others Hnin).\nProof.\nmove=>d from this i C [tag m] H1 I F D/= _ Et G.\nsubst tag.\nhave Vl := cohVl C.\nhave Vs := cohVs C.\n\ncase Hinternal: (internal_msg cn pts prep_req from this); first last.\n- move /negbT in Hinternal.\n  rewrite (rp_step_external _ _ _ F)//.\n  by apply /(invE_consume_external C F)=>//.\n\nrewrite /rp_step/pstep_recv.\ncase PS: (getStP Hnin C H1) => [round ps].\nhave Hthis := (internal_msg_tagFromCoordinator_to_pts Hinternal erefl).\nrewrite Hthis.\nhave Hfrom := (internal_msg_tagFromCoordinator_from_cn Hinternal erefl).\nrewrite Hfrom/=. move/eqP in Hfrom. subst from.\n\nmove: (fun H => commit_req_cn_inv H Hthis F I) => /(_ erefl) [r][lg][nd] PT.\nmove: (fun H => PhaseTwoCommit_req_round H Hthis F PT) => /(_ erefl) [ps'] PS'.\nmove: PS.\nrewrite (getStP_K Hnin C H1 Hthis PS').\ncase=> ? ?. subst.\nmove: (PhaseTwoCommit_round_cn PT)=>[cs] CS.\nmove /(getStC_K C) in CS.\nhave Hround := (inv_msg_round F Hinternal I CS).\nrewrite Hround/= !orbF.\n\nhave Hmatch := (p_matches_tag_internal_inv C Hthis F Hinternal PS' I).\nrewrite Hmatch /=.\n\nmove: Hmatch. rewrite /p_matches_tag.\ndestruct ps=>// _.\nexists round, lg.\nconstructor 3.\nexists nd.\nmove: PT=>[].\n- move=>[sent][] CS' U S Pts.\n  constructor 1. exists sent.\n  split=>//.\n  + apply/(cn_state_consume _ _ _ C)=>//.\n    by apply /eqP/nesym/eqP/(pt_not_cn Hnin).\n  + move=>pt Hpt.\n    move: (Pts _ Hpt).\n    case: ifP => _ H.\n    * case E: (pt == this).\n      -- move /eqP in E. subst pt.\n         case/(commit_req_pt_inv F): H=>PS'' M NM.\n         pose proof C as C'.\n         move: C'=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _.\n         move: (pt_state_functional V PS' PS'')=>[][]? ?. subst.\n         constructor 2.\n         split.\n         ++ by rewrite/ pt_state locE'// (getStL_Kp C H1 PS').\n         ++ by apply /(msg_spec_consume _ F M).\n         ++ by apply /no_msg_from_to_consume.\n      -- move /negbT in E.\n         apply /(pt_PhaseTwoCommitE_consume _ C _ _ F)=>//.\n         by apply: (pt_not_cn Hnin).\n    * case E: (pt == this).\n      -- move/eqP in E. subst pt.\n         case: H => NM1 NM2 PS.\n         by move: (NM1 _ _ _ F).\n      -- move/negbT in E.\n         by apply /(pt_PhaseOneRespondedE_consume _ _ C)=>//.\n- move=>[recvd][] CS' U S Pts.\n  constructor 3. exists recvd.\n  split=>//.\n  + apply/(cn_state_consume _ _ _ C)=>//.\n    by apply /eqP/nesym/eqP/(pt_not_cn Hnin).\n  + move=>pt Hpt.\n    move: (Pts _ Hpt).\n    case: ifP => _ H.\n    * case E: (pt == this).\n      -- move/eqP in E. subst pt.\n         case: H => PS NM1 NM2.\n         by move: (NM1 _ _ _ F).\n      -- move/negbT in E.\n         by apply /(pt_PhaseTwoRespondedE_consume _ _ C).\n    * case E: (pt == this).\n      -- move /eqP in E. subst pt.\n         case/(commit_req_pt_inv F): H=>PS'' M NM.\n         pose proof C as C'.\n         move: C'=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _.\n         move: (pt_state_functional V PS' PS'')=>[][]? ?. subst.\n         constructor 2.\n         split.\n         ++ by rewrite/ pt_state locE'// (getStL_Kp C H1 PS').\n         ++ by apply /(msg_spec_consume _ F M).\n         ++ by apply /no_msg_from_to_consume.\n      -- move /negbT in E.\n         apply /(pt_PhaseTwoCommitE_consume _ C _ _ F)=>//.\n         by apply: (pt_not_cn Hnin).\nQed.\n\n\n(*** [Pariticpant] Receive abort-request ***)\n\nProgram Definition r7: Rinv (pn_receive_abort_ack_trans others Hnin).\nProof.\nmove=>d from this i C [tag m] H1 I F D/= _ Et G.\nsubst tag.\nhave Vl := cohVl C.\nhave Vs := cohVs C.\n\ncase Hinternal: (internal_msg cn pts prep_req from this); first last.\n- move /negbT in Hinternal.\n  rewrite (rp_step_external _ _ _ F)//.\n  by apply /(invE_consume_external C F)=>//.\n\nrewrite /rp_step/pstep_recv.\ncase PS: (getStP Hnin C H1) => [round ps].\nhave Hthis := (internal_msg_tagFromCoordinator_to_pts Hinternal erefl).\nrewrite Hthis.\nhave Hfrom := (internal_msg_tagFromCoordinator_from_cn Hinternal erefl).\nrewrite Hfrom/=. move/eqP in Hfrom. subst from.\n\nmove: (fun H => abort_req_cn_inv H Hthis F I) => /(_ erefl) [r][lg][nd] PT.\nmove: (fun H => PhaseTwoAbort_req_round H Hthis F PT) => /(_ erefl) [ps'] PS'.\nmove: PS.\nrewrite (getStP_K Hnin C H1 Hthis PS').\ncase=> ? ?. subst.\nmove: (PhaseTwoAbort_round_cn PT)=>[cs] CS.\nmove /(getStC_K C) in CS.\nhave Hround := (inv_msg_round F Hinternal I CS).\nrewrite Hround/= !orbF.\n\nhave Hmatch := (p_matches_tag_internal_inv C Hthis F Hinternal PS' I).\nrewrite Hmatch /=.\n\nmove: Hmatch. rewrite /p_matches_tag.\nexists round, lg.\nconstructor 3.\nexists nd.\nmove: PT=>[].\n- move=>[sent][] CS' U S Pts.\n  constructor 2. exists sent.\n  split=>//.\n  + apply/(cn_state_consume _ _ _ C)=>//.\n    by apply /eqP/nesym/eqP/(pt_not_cn Hnin).\n  + move=>pt Hpt.\n    move: (Pts _ Hpt).\n    case: ifP => _ H.\n    * case E: (pt == this).\n      -- move /eqP in E. subst pt.\n         case/(abort_req_pt_inv F): H=>PS'' M NM.\n         pose proof C as C'.\n         move: C'=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _.\n         constructor 2.\n         split.\n         ++ rewrite/ pt_state locE'// (getStL_Kp C H1 PS').\n            move: Hmatch. destruct ps=>//;\n            (case: PS''=>PS'';\n            move: (pt_state_functional V PS' PS'')=>[]); try discriminate;\n            by move => [] ? ?; subst.\n         ++ by apply /(msg_spec_consume _ F M).\n         ++ by apply /no_msg_from_to_consume.\n      -- move /negbT in E.\n         apply /(pt_PhaseTwoAbortE_consume _ C _ _ F)=>//.\n         by apply: (pt_not_cn Hnin).\n    * move: H => [b] H.\n      exists b.\n      case E: (pt == this).\n      -- move/eqP in E. subst pt.\n         case: H => NM1 NM2 PS.\n         by move: (NM1 _ _ _ F).\n      -- move/negbT in E.\n         by apply /(pt_PhaseOneRespondedE_consume _ _ C)=>//.\n\n- move=>[recvd][] CS' U S Pts.\n  constructor 4. exists recvd.\n  split=>//.\n  + apply/(cn_state_consume _ _ _ C)=>//.\n    by apply /eqP/nesym/eqP/(pt_not_cn Hnin).\n  + move=>pt Hpt.\n    move: (Pts _ Hpt).\n    case: ifP => _ H.\n    * case E: (pt == this).\n      -- move/eqP in E. subst pt.\n         case: H => PS NM1 NM2.\n         by move: (NM1 _ _ _ F).\n      -- move/negbT in E.\n         by apply /(pt_PhaseTwoRespondedE_consume _ _ C).\n    * case E: (pt == this).\n      -- move /eqP in E. subst pt.\n         case/(abort_req_pt_inv F): H=>PS'' M NM.\n         pose proof C as C'.\n         move: C'=>[] _ _ _ /(_ _ (pts_in cn others Hpt)) [] V _.\n         constructor 2.\n         split.\n         ++ rewrite/ pt_state locE'// (getStL_Kp C H1 PS').\n            move: Hmatch. destruct ps=>//;\n            (case: PS''=>PS'';\n            move: (pt_state_functional V PS' PS'')=>[]); try discriminate;\n            by move => [] ? ?; subst.\n         ++ by apply /(msg_spec_consume _ F M).\n         ++ by apply /no_msg_from_to_consume.\n      -- move /negbT in E.\n         apply /(pt_PhaseTwoAbortE_consume _ C _ _ F)=>//.\n         by apply: (pt_not_cn Hnin).\nQed.\n\nDefinition sts' := [:: SI s1; SI s2; SI s3; SI s4; SI s5; SI s6; SI s7].\nDefinition rts' := [:: RI r1; RI r2; RI r3; RI r4; RI r5; RI r6; RI r7].\n\nProgram Definition ii := @ProtocolWithInvariant.II _ _ sts' rts' _ _.\n\nDefinition tpc_with_inv := ProtocolWithIndInv ii.\n\nEnd TwoPhaseInductiveProof.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/disel/Examples/TwoPhaseCommit/TwoPhaseInductiveProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.22375574452098243}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.RefinementCommonTheorems.\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.AllEntriesLeaderSublogInterface.\nRequire Import VerdiRaft.LeaderSublogInterface.\nRequire Import VerdiRaft.RefinedLogMatchingLemmasInterface.\n\nRequire Import VerdiRaft.AllEntriesLogMatchingInterface.\n\nSection AllEntriesLogMatching.\n\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n  Context {rri : raft_refinement_interface}.\n  Context {aelsi : allEntries_leader_sublog_interface}.\n  Context {lsi : leader_sublog_interface}.\n  Context {rlmli : refined_log_matching_lemmas_interface}.\n\n  Definition allEntries_log_matching_nw net :=\n    forall (e e' : entry) (h : name) (p : packet)\n      t leaderId prevLogIndex prevLogTerm entries leaderCommit,\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm entries leaderCommit ->\n      In e entries ->\n      In e' (map snd (allEntries (fst (nwState net h)))) ->\n      eTerm e = eTerm e' -> eIndex e = eIndex e' -> e = e'.\n\n  Definition allEntries_log_matching_inductive net :=\n    allEntries_log_matching net /\\ allEntries_log_matching_nw net.\n\n  Ltac start :=\n    red; unfold allEntries_log_matching_inductive; simpl; intros.\n\n  Ltac start_update :=\n    start; intuition; [unfold allEntries_log_matching in *|unfold allEntries_log_matching_nw in *];\n    intros; repeat find_higher_order_rewrite; repeat (update_destruct; rewrite_update); subst; simpl; eauto.\n  \n  Lemma allEntries_log_matching_init :\n    refined_raft_net_invariant_init allEntries_log_matching_inductive.\n  Proof using. \n    start. split.\n    - unfold allEntries_log_matching. intros. simpl in *. intuition.\n    - unfold allEntries_log_matching_nw. intros. simpl in *. intuition.\n  Qed.\n\n  Definition leader_sublog (net : network) :=\n    forall leader e h,\n      type (snd (nwState net leader)) = Leader ->\n      In e (log (snd (nwState net h))) ->\n      eTerm e = currentTerm (snd (nwState net leader)) ->\n      In e (log (snd (nwState net leader))).\n\n  Lemma lifted_leader_sublog_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      leader_sublog net.\n  Proof using lsi rri. \n    pose proof lift_prop _ leader_sublog_invariant_invariant.\n    unfold leader_sublog, leader_sublog_invariant, leader_sublog_host_invariant in *.\n    intuition.\n    unfold raft_refined_base_params in *.\n    repeat rewrite <- deghost_spec in *.\n    repeat match goal with\n    | [ H : _ |- _ ] => rewrite <- deghost_spec in H\n    end.\n    find_apply_hyp_hyp. intuition.\n    eauto.\n  Qed.\n\n  Lemma lifted_leader_sublog_nw_invariant :\n    forall net p t n pli plt es ci h e,\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      type (snd (nwState net h)) = Leader ->\n      eTerm e = currentTerm (snd (nwState net h)) ->\n      In e es ->\n      In e (log (snd (nwState net h))).\n  Proof using lsi rri. \n    intros.\n    pose proof (lift_prop _ leader_sublog_invariant_invariant _ ltac:(eauto)) as Hinv.\n    unfold leader_sublog_invariant, leader_sublog_nw_invariant in *.\n    destruct Hinv as [Hhost Hnw].\n    find_apply_lem_hyp ghost_packet.\n    eapply_prop_hyp In In; eauto; try find_rewrite_lem deghost_spec; try rewrite deghost_spec; eauto.\n  Qed.\n  \n\n  Lemma invalid_index :\n    forall net h e,\n      refined_raft_intermediate_reachable net ->\n      In e (log (snd (nwState net h))) ->\n      eIndex e = S (maxIndex (log (snd (nwState net h)))) ->\n      False.\n  Proof using rlmli. \n    intros.\n    intro_refined_invariant entries_sorted_invariant.\n    find_apply_lem_hyp maxIndex_is_max; auto.\n    find_rewrite.\n    lia.\n  Qed.\n\n  Ltac fix_data :=\n    do 2 (unfold raft_data in *; simpl in *).\n\n  Ltac contradict_maxIndex :=\n    exfalso; find_apply_lem_hyp maxIndex_is_max;\n    try (fix_data; lia);\n    eapply entries_sorted_invariant; eauto.\n\n  Lemma allEntries_log_matching_client_request :\n    refined_raft_net_invariant_client_request allEntries_log_matching_inductive.\n  Proof using rlmli lsi aelsi rri.\n    start_update.\n    - subst.\n      find_copy_apply_lem_hyp update_elections_data_client_request_log_allEntries.\n      intuition; simpl in *; repeat find_rewrite; eauto.\n      break_exists; intuition; repeat find_rewrite; simpl in *; intuition; subst; simpl in *; eauto.\n      + contradict_maxIndex.\n      + enough (In e' (log (snd (nwState net h0)))) by \n            contradict_maxIndex.\n        eapply allEntries_leader_sublog_invariant; repeat find_rewrite; eauto.\n    - find_apply_lem_hyp update_elections_data_client_request_log_allEntries.\n      intuition; simpl in *; repeat find_rewrite; eauto.\n      break_exists. intuition; repeat find_rewrite; simpl in *; intuition; eauto.\n      subst.\n      enough (In e (log (snd (nwState net h')))) by\n            contradict_maxIndex.\n      eapply lifted_leader_sublog_invariant; repeat find_rewrite; eauto.\n    - find_apply_lem_hyp update_elections_data_client_request_log_allEntries.\n      intuition; simpl in *; repeat find_rewrite; eauto.\n      break_exists. intuition; repeat find_rewrite; simpl in *; intuition; eauto.\n      subst.\n      enough (In e' (log (snd (nwState net h0)))) by \n          contradict_maxIndex.\n      eapply allEntries_leader_sublog_invariant; repeat find_rewrite; eauto.\n    - find_apply_hyp_hyp.\n      intuition;\n        [|exfalso; do_in_map; subst; simpl in *;\n          find_eapply_lem_hyp handleClientRequest_no_append_entries; eauto;\n          intuition; repeat find_rewrite; find_false; repeat eexists; eauto].\n      find_apply_lem_hyp update_elections_data_client_request_log_allEntries.\n      intuition; simpl in *; repeat find_rewrite; eauto.\n      break_exists. intuition; repeat find_rewrite; simpl in *; intuition; eauto.\n      subst.\n      enough (In e (log (snd (nwState net h0)))) by \n          contradict_maxIndex.\n      eapply lifted_leader_sublog_nw_invariant; repeat find_rewrite; eauto.\n    - find_apply_hyp_hyp.\n      intuition;\n        [|exfalso; do_in_map; subst; simpl in *;\n          find_eapply_lem_hyp handleClientRequest_no_append_entries; eauto;\n          intuition; repeat find_rewrite; find_false; repeat eexists; eauto].\n      eauto.\n  Qed.\n\n  Lemma allEntries_log_matching_unchanged :\n    forall net st' h gd d ps',\n      allEntries_log_matching net ->\n      (forall h' : Net.name, st' h' = update name_eq_dec (nwState net) h (gd, d) h') ->\n      log d = log (snd (nwState net h)) ->\n      allEntries gd = allEntries (fst (nwState net h)) ->\n      allEntries_log_matching {| nwPackets := ps'; nwState := st' |}.\n  Proof using. \n    unfold allEntries_log_matching. intros.\n    find_higher_order_rewrite.\n    do 2 (update_destruct; rewrite_update); simpl in *;\n      repeat find_rewrite; eauto.\n  Qed.\n\n  Ltac unchanged :=\n    red; intros; eapply allEntries_log_matching_unchanged; subst; eauto.\n\n  Lemma allEntries_log_matching_timeout :\n    refined_raft_net_invariant_timeout allEntries_log_matching_inductive.\n  Proof using. \n    start_update; simpl in *; try find_erewrite_lem handleTimeout_log_same; eauto;\n    try find_erewrite_lem update_elections_data_timeout_allEntries; eauto;\n    find_apply_hyp_hyp; intuition; eauto;\n    exfalso; do_in_map; subst; simpl in *;\n    find_eapply_lem_hyp handleTimeout_not_is_append_entries; eauto;\n    intuition; repeat find_rewrite; find_false; repeat eexists; eauto.\n  Qed.\n\n  Lemma appendEntries_haveNewEntries_false :\n    forall net p t n pli plt es ci h e,\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      haveNewEntries (snd (nwState net h)) es = false ->\n      In e es ->\n      In e (log (snd (nwState net h))).\n  Proof using rlmli. \n    intros.\n    unfold haveNewEntries in *. do_bool. intuition;\n      [unfold not_empty in *; break_match; subst; simpl in *; intuition; congruence|].\n    break_match; try congruence.\n    do_bool. find_apply_lem_hyp findAtIndex_elim. intuition.\n    assert (es <> nil) by (destruct es; subst; simpl in *; intuition; congruence).\n    find_eapply_lem_hyp maxIndex_non_empty.\n    break_exists. intuition.\n    find_copy_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n    match goal with\n      | H : In e es |- _ => copy_eapply maxIndex_is_max H; eauto\n    end.\n    repeat find_rewrite.\n    find_eapply_lem_hyp entries_match_nw_host_invariant; eauto.\n  Qed.\n\n  Lemma packets_entries_eq:\n    forall net p p0 entries es e e'\n      (d : raft_data) (n : name) (pli : logIndex) (plt : term)\n      (ci : logIndex)\n      (t0 : term) (leaderId : name) (prevLogIndex : logIndex)\n      (prevLogTerm : term) (leaderCommit : logIndex),\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      In p0 (nwPackets net) ->\n      pBody p0 =\n      AppendEntries t0 leaderId prevLogIndex prevLogTerm entries leaderCommit ->\n      pBody p = AppendEntries (currentTerm d) n pli plt es ci ->\n      eTerm e = eTerm e' ->\n      eIndex e = eIndex e' -> In e entries -> In e' es -> e = e'.\n  Proof using rlmli. \n    intros.\n    enough (In e' entries) by\n        (eapply uniqueIndices_elim_eq; eauto; apply sorted_uniqueIndices; eapply entries_sorted_nw_invariant; [| | eauto]; eauto).\n    eapply entries_match_nw_1_invariant.\n    5: { eauto. } 9: { eauto. }\n    4: { eauto. } all:eauto.\n    intuition. repeat find_reverse_rewrite.\n    eapply entries_contiguous_nw_invariant; eauto.\n  Qed.\n\n  Lemma allEntries_log_matching_append_entries :\n    refined_raft_net_invariant_append_entries allEntries_log_matching_inductive.\n  Proof using rlmli. \n    start_update; simpl in *.\n    - match goal with\n        | H : context [handleAppendEntries] |- _ =>\n          eapply update_elections_data_appendEntries_log_allEntries with (h' := n) in H\n      end ; intuition; repeat find_rewrite; simpl in *; intuition; subst; eauto;\n      try (find_rewrite_lem map_app; find_rewrite_lem map_map; simpl in *; find_rewrite_lem map_id;\n           do_in_app; intuition; eauto).\n      + enough (In e' (log (snd (nwState net (pDst p))))) by\n            (eapply uniqueIndices_elim_eq; eauto; apply sorted_uniqueIndices; eapply entries_sorted_invariant; eauto).\n        eapply entries_match_nw_host_invariant; eauto.\n      + eapply uniqueIndices_elim_eq; eauto; apply sorted_uniqueIndices; eapply entries_sorted_nw_invariant; eauto.\n      + do_in_app. intuition.\n        * eapply uniqueIndices_elim_eq; eauto; apply sorted_uniqueIndices;\n          eapply entries_sorted_nw_invariant; eauto.\n        * find_apply_lem_hyp removeAfterIndex_in.\n          enough (In e' (log (snd (nwState net (pDst p))))) by\n              (eapply uniqueIndices_elim_eq; eauto; apply sorted_uniqueIndices; eapply entries_sorted_invariant; eauto).\n          eapply entries_match_nw_host_invariant; eauto.\n      + do_in_app; intuition; eauto using removeAfterIndex_in.\n    - match goal with\n        | H : context [handleAppendEntries] |- _ =>\n          eapply update_elections_data_appendEntries_log_allEntries with (h' := n) in H\n      end ; intuition; repeat find_rewrite; simpl in *; intuition; subst; eauto;\n      try (find_rewrite_lem map_app; find_rewrite_lem map_map; simpl in *; find_rewrite_lem map_id;\n           do_in_app; intuition; eauto).\n      + enough (In e' (log (snd (nwState net h)))) by\n            (eapply uniqueIndices_elim_eq; eauto; apply sorted_uniqueIndices; eapply entries_sorted_invariant; eauto).\n        eapply entries_match_nw_host_invariant; eauto.\n      + enough (In e' (log (snd (nwState net h)))) by\n            (eapply uniqueIndices_elim_eq; eauto; apply sorted_uniqueIndices; eapply entries_sorted_invariant; eauto).\n        eapply entries_match_nw_host_invariant; eauto.\n      + enough (In e' (log (snd (nwState net h)))) by\n            (eapply uniqueIndices_elim_eq; eauto; apply sorted_uniqueIndices; eapply entries_sorted_invariant; eauto).\n        eapply entries_match_nw_host_invariant; eauto.\n    - find_apply_lem_hyp handleAppendEntries_log.\n      intuition; repeat find_rewrite; simpl in *; eauto.\n      do_in_app. intuition; eauto using removeAfterIndex_in.\n    - find_apply_hyp_hyp.\n      intuition;\n        [|exfalso; do_in_map; subst; simpl in *;\n         find_eapply_lem_hyp handleAppendEntries_not_append_entries; eauto;\n         intuition; repeat find_rewrite; find_false; repeat eexists; eauto].\n      assert (In p0 (xs ++ p :: ys)) by in_crush.\n      match goal with\n        | H : context [handleAppendEntries] |- _ =>\n          eapply update_elections_data_appendEntries_log_allEntries with (h' := n) in H\n      end.\n      intuition; repeat find_rewrite; simpl in *; subst; intuition; eauto.\n      + find_rewrite_lem map_app.\n        find_rewrite_lem map_map.\n        simpl in *.\n        find_rewrite_lem map_id.\n        apply in_app_or in H11.\n        intuition; eauto.\n        eauto using packets_entries_eq.\n      + find_rewrite_lem map_app.\n        find_rewrite_lem map_map.\n        simpl in *.\n        find_rewrite_lem map_id.\n        apply in_app_or in H11.\n        intuition; eauto.\n        eauto using packets_entries_eq.\n      + find_rewrite_lem map_app.\n        find_rewrite_lem map_map.\n        simpl in *.\n        find_rewrite_lem map_id.\n        apply in_app_or in H11.\n        intuition; eauto.\n        eauto using packets_entries_eq.\n    - find_apply_hyp_hyp.\n      intuition;\n        [|exfalso; do_in_map; subst; simpl in *;\n         eapply handleAppendEntries_not_append_entries; eauto;\n         intuition; repeat find_rewrite; repeat eexists; eauto].\n      eauto.\nQed.\n\n  Lemma allEntries_log_matching_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply allEntries_log_matching_inductive.\n  Proof using. \n    start_update; simpl in *;\n    try find_erewrite_lem handleAppendEntriesReply_log; eauto;\n    find_apply_hyp_hyp; intuition; eauto;\n    exfalso; do_in_map; subst; simpl in *;\n    find_eapply_lem_hyp handleAppendEntriesReply_packets; eauto;\n    subst; simpl in *; intuition.\n  Qed.\n\n  Lemma allEntries_log_matching_request_vote :\n    refined_raft_net_invariant_request_vote allEntries_log_matching_inductive.\n  Proof using. \n    start_update; simpl in *;\n    try find_erewrite_lem handleRequestVote_log; eauto;\n    try find_erewrite_lem update_elections_data_requestVote_allEntries; eauto;\n    find_apply_hyp_hyp; intuition; eauto;\n    exfalso; subst; simpl in *;\n    subst;\n    find_eapply_lem_hyp handleRequestVote_no_append_entries; eauto;\n    intuition; repeat find_rewrite; try (find_false; repeat eexists; eauto).\n    contradict H.\n    repeat eexists; eauto.\n  Qed.\n\n\n  Lemma allEntries_log_matching_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply allEntries_log_matching_inductive.\n  Proof using. \n    start_update; simpl in *;\n    try find_erewrite_lem handleRequestVoteReply_log; eauto;\n    try find_erewrite_lem update_elections_data_requestVoteReply_allEntries; eauto;\n    find_apply_hyp_hyp; intuition; eauto.\n  Qed.\n\n  Lemma allEntries_log_matching_do_leader :\n    refined_raft_net_invariant_do_leader allEntries_log_matching_inductive.\n  Proof using. \n    start_update; simpl in *;\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end;\n    try find_erewrite_lem doLeader_log; eauto;\n    find_apply_hyp_hyp; intuition; eauto;\n    do_in_map; subst; simpl in *;\n    find_eapply_lem_hyp doLeader_message_entries; eauto.\n  Qed.\n\n  Lemma allEntries_log_matching_do_generic_server :\n    refined_raft_net_invariant_do_generic_server allEntries_log_matching_inductive.\n  Proof using. \n    start_update; simpl in *;\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end;\n    try find_erewrite_lem doGenericServer_log; eauto;\n    find_apply_hyp_hyp; intuition; eauto;\n    find_apply_lem_hyp doGenericServer_packets; subst; simpl in *; intuition.\n  Qed.\n\n  Lemma allEntries_log_matching_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset allEntries_log_matching_inductive.\n  Proof using. \n    start_update; simpl in *.\n    - repeat find_reverse_higher_order_rewrite. eauto.\n    - repeat find_reverse_higher_order_rewrite.\n      find_apply_hyp_hyp. eauto.\n  Qed.\n\n  Lemma allEntries_log_matching_reboot :\n    refined_raft_net_invariant_reboot allEntries_log_matching_inductive.\n  Proof using. \n    start_update; simpl in *;\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end; eauto.\n  Qed.\n\n  Lemma allEntries_log_matching_inductive_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      allEntries_log_matching_inductive net.\n  Proof using rlmli lsi aelsi rri. \n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply allEntries_log_matching_init.\n    - apply allEntries_log_matching_client_request.\n    - apply allEntries_log_matching_timeout.\n    - apply allEntries_log_matching_append_entries.\n    - apply allEntries_log_matching_append_entries_reply.\n    - apply allEntries_log_matching_request_vote.\n    - apply allEntries_log_matching_request_vote_reply.\n    - apply allEntries_log_matching_do_leader.\n    - apply allEntries_log_matching_do_generic_server.\n    - apply allEntries_log_matching_state_same_packet_subset.\n    - apply allEntries_log_matching_reboot.\n  Qed.\n\n\n  Instance aelmi : allEntries_log_matching_interface.\n  Proof.\n    constructor. intros.\n    apply allEntries_log_matching_inductive_invariant; auto.\n  Qed.\nEnd AllEntriesLogMatching.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft-proofs/AllEntriesLogMatchingProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2237557445209824}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import PeanoNat.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Numbers.NatInt.NZOrder.\n\nFrom VLG Require Import ltac.\nFrom VLG Require Import coredefs.\n\nFrom VLG Require Import spec.\nFrom VLG Require Import matcher.\nFrom VLG Require Import prefixer.\nFrom VLG Require Import lexer.\n\nLemma lex'_eq_body :\n  forall rules code (Ha : Acc lt (length code)),\n    (lex' rules code Ha =\n     (match max_of_prefs (max_prefs code rules) as mpref'\n            return max_of_prefs (max_prefs code rules) = mpref' -> _\n      with\n      | (_, None) => fun _ => ([], code) (* Code cannot be processed further *)\n      | (_, Some ([], _)) => fun _ => ([], code) (* Code cannot be processed further *)\n      | (label, Some (ph :: pt, suffix)) =>\n        fun Heq =>\n          match (lex' rules suffix\n                      (acc_recursive_call _ _ _ _ _ _ Ha Heq))\n          with\n          | (lexemes, rest) => (((label, ph :: pt) :: lexemes), rest)\n          end\n      end eq_refl)).\nProof.\n  intros rules code Ha. unfold lex'. destruct Ha. auto.\nQed.\n\nLemma lex'_cases_backward :\n  forall (rules : list sRule)\n         (code : String)\n         (Ha : Acc lt (length code))\n         (pr : Label * option (Prefix * Suffix))\n         (res : list Token * String)\n         (Heq : max_of_prefs (max_prefs code rules) = pr),\n    match pr as mpref' return max_of_prefs (max_prefs code rules) = mpref' -> _ with\n    | (_, None) => fun _ => ([], code) (* Code cannot be processed further *)\n    | (_, Some ([], _)) => fun _ => ([], code) (* Code cannot be processed further *)\n    | (label, Some (h :: t, suffix)) =>\n      fun Heq =>\n        match (lex' rules suffix\n                    (acc_recursive_call _ _ _ _ _ _ Ha Heq))\n        with\n        | (lexemes, rest) => (((label, h :: t) :: lexemes), rest)\n        end\n    end Heq = res\n    -> match res with\n       | ([], code') =>\n         code' = code\n         /\\ (snd pr = None\n             \\/ exists suf, snd pr = Some ([], suf))\n       | ((label, prefix) :: lexemes, rest) =>\n         exists h t suffix (Heq' : max_of_prefs (max_prefs code rules) = (label, Some (h :: t, suffix))),\n         lex' rules suffix (acc_recursive_call _ _ _ _ _ _ Ha Heq') = (lexemes, rest)\n         /\\ h :: t = prefix\n       end.\nProof.\n  intros rules code Ha pr res Heq.\n  repeat dm; intros; subst; simpl in *; try congruence.\n  - split; inv H; eauto.\n  - inv H. exists s0. exists p1. exists s. exists Heq. split. apply E3. reflexivity.\n  - split; inv H; eauto.\nQed.\n\nLemma lex'_cases :\n  forall rules code Ha res,\n    lex' rules code Ha = res\n    -> match res with\n       | ([], code') =>\n         code' = code\n         /\\ (snd (max_of_prefs (max_prefs code rules)) = None\n             \\/ exists suf, snd (max_of_prefs (max_prefs code rules)) = Some ([], suf))\n       | ((label, prefix) :: lexemes, rest) =>\n         exists h t suffix (Heq' : max_of_prefs (max_prefs code rules) = (label, Some (h :: t, suffix))),\n         lex' rules suffix (acc_recursive_call _ _ _ _ _ _ Ha Heq') = (lexemes, rest)\n         /\\ h :: t = prefix\n       end.\nProof.\n  intros rules code Ha res Heq; subst.\n  rewrite lex'_eq_body.\n  eapply lex'_cases_backward; eauto.\nQed.\n\nLemma nil_is_prefix : forall(xs : String),\n    [] ++_= xs.\nProof.\n  intros xs. apply pref_def. exists xs. reflexivity.\nQed.\n\nLemma app_head_prefix : forall(xs ys : String),\n    xs ++_= xs ++ ys.\nProof.\n  intros xs ys. apply pref_def. exists ys. reflexivity.\nQed.\n\nLemma cons_prefix : forall(x y : Sigma) (xs ys : String),\n    x :: xs ++_= y :: ys <-> x = y /\\ xs ++_= ys.\nProof.\n  intros x y xs ys. split; intros H.\n  {\n    inv H. destruct H1.\n    injection H. intros I1 I2. split; subst.\n    - reflexivity.\n    - apply app_head_prefix.\n  }\n  {\n    destruct H. inv H0. destruct H1.\n    apply pref_def. exists x. rewrite <- H. reflexivity.\n  }\nQed.\n\nLemma self_prefix : forall(p : String), p ++_= p.\nProof.\n  intros p. apply pref_def. exists []. apply nil_right.\nQed.\n\nLemma eq_len_eq_pref : forall(x s p : String),\n    length p = length s\n    -> s ++_= x\n    -> p ++_= x\n    -> s = p.\nProof.\n  induction x; intros s p Heq Hs Hp .\n  - inv Hs. inv Hp. destruct H0. destruct H1.\n    apply app_eq_nil in H. destruct H.\n    apply app_eq_nil in H0. destruct H0.\n    subst. reflexivity.\n  - destruct s; destruct p.\n    + reflexivity.\n    + simpl in Heq. discriminate.\n    + simpl in Heq. discriminate.\n    + apply cons_prefix in Hs. apply cons_prefix in Hp.\n      destruct Hs. destruct Hp. subst.\n      assert (length p = length s0).\n      { simpl in Heq. omega. }\n      apply IHx in H.\n      * rewrite H. reflexivity.\n      * apply H0.\n      * apply H2.\nQed.\n\nTheorem re_max_pref_correct__None : forall(code : String) (fsm : State),\n    re_no_max_pref code (init_state_inv fsm)\n    <-> None = max_pref_fn code fsm.\nProof.\n  intros code fsm. split.\n  {\n    generalize dependent fsm; induction code; intros fsm H.\n    - simpl. inv H. specialize (H1 []). assert (A : [] ++_= []).\n      { apply nil_is_prefix. }\n      apply H1 in A. clear H1. destruct (accepting fsm) eqn:E.\n      + exfalso. destruct A. rewrite accepts_nil in E. apply accepts_matches. auto.\n      + reflexivity.\n    - specialize (IHcode (transition a fsm)). inv H.\n      assert (A0 : re_no_max_pref code (init_state_inv (transition a fsm))).\n      {\n        apply re_MP0.\n        - intros cand H. specialize (H1 (a :: cand)).\n          assert (A1 : a :: cand ++_= a :: code).\n          { apply pref_def. inv H. destruct H0. exists x. rewrite <- H. reflexivity. }\n          apply H1 in A1. intros C. destruct A1.\n          apply inv_transition. auto.\n      }\n      apply IHcode in A0.\n      simpl.\n      assert (A1 : accepting (transition a fsm) = false).\n      { specialize (H1 [a]). assert (A2 : [a] ++_= a :: code).\n        { apply pref_def. exists code. reflexivity. }\n        apply H1 in A2. apply false_not_true. intros C. destruct A2.\n        symmetry in C. apply accepting_nilmatch in C. apply inv_transition. auto.\n      }\n      assert (A2 : accepting fsm = false).\n      {\n        specialize (H1 []). assert (A3 : [] ++_= a :: code).\n        { apply nil_is_prefix. }\n        apply H1 in A3. apply false_not_true. intros C. destruct A3.\n        symmetry in C. apply accepting_nilmatch. auto.\n      }\n      rewrite <- A0. rewrite A1. rewrite A2. reflexivity.\n  }\n  {\n    generalize dependent fsm; induction code; intros fsm H.\n    - apply re_MP0.\n      + intros cand H0. simpl in H.\n        assert (A0 : accepting fsm = false).\n        {\n          destruct (accepting fsm).\n          - discriminate.\n          - reflexivity.\n        }\n        assert (A1 : cand = []).\n        {\n          destruct cand.\n          - reflexivity.\n          - inv H0. destruct H1. discriminate.\n        }\n        intros C. rewrite A1 in C. rewrite accepts_nil in A0.\n        apply accepts_matches in C. rewrite A0 in C. discriminate.\n    - specialize (IHcode (transition a fsm)).\n      apply re_MP0.\n      intros cand H0. simpl in H. destruct (max_pref_fn code (transition a fsm)).\n      + destruct p. discriminate.\n      + assert (A0 : accepting (transition a fsm) = false).\n        {\n          destruct (accepting (transition a fsm)).\n          - discriminate.\n          - reflexivity.\n        }\n        assert (A1 : accepting fsm = false).\n        {\n          destruct (accepting fsm).\n          - rewrite A0 in H. discriminate.\n          - reflexivity.\n        }\n        destruct cand.\n        * intros C. rewrite accepts_nil in A1. apply accepts_matches in C.\n          rewrite A1 in C. discriminate.\n        * destruct (Sigma_dec a s).\n          -- rewrite <- e. destruct cand.\n             ++ intros C. apply false_not_true in A0. destruct A0.\n                symmetry. apply accepting_nilmatch. apply inv_transition. auto.\n             ++ assert (A2 : re_no_max_pref code (init_state_inv (transition a fsm))).\n                { apply IHcode. reflexivity. }\n                inv A2. specialize (H1 (s0 :: cand)). inv H0. destruct H2. injection H0.\n                intros I1. assert (A3 :  s0 :: cand ++_= code).\n                { apply pref_def. exists x. apply I1. }\n                apply H1 in A3. intros C. destruct A3.\n                apply inv_transition. auto.\n          -- inv H0. destruct H1. injection H0. intros I1 I2. rewrite I2 in n. contradiction.\n  }\nQed.\n\nLemma max_pref_matches : forall(code p x : String) (fsm : State),\n    Some (p, x) = max_pref_fn code fsm\n    -> exp_match p (init_state_inv fsm).\nProof.\n  induction code; intros p x fsm H.\n  - assert (A0 : p = []).\n    {\n      apply max_pref_fn_splits in H. symmetry in H. destruct p.\n      - reflexivity.\n      - discriminate.\n    }\n    rewrite A0. simpl in H. destruct (accepting fsm) eqn:E0.\n    + apply accepting_nilmatch. auto.\n    + discriminate.\n  - simpl in H. destruct (max_pref_fn code (transition a fsm)) eqn:E0.\n    + destruct p0. injection H. intros I1 I2. rewrite I2.\n      symmetry in E0. apply IHcode in E0. apply inv_transition. auto.\n    + destruct (accepting (transition a fsm)) eqn:E1.\n      * injection H. intros I1 I2. rewrite I2.\n        symmetry in E1. rewrite accepting_nilmatch in E1. apply inv_transition. auto.\n      * destruct (accepting fsm) eqn:E2.\n        -- injection H. intros I1 I2. rewrite I2. apply accepting_nilmatch. auto.\n        -- discriminate.\nQed.\n\nTheorem re_max_pref_correct__Some : forall(code p : String) (fsm : State),\n    re_max_pref code (init_state_inv fsm) p\n    <-> exists(q : String), Some (p, q) = max_pref_fn code fsm.\nProof.\n  induction code.\n  {\n    intros p fsm. split; intros H.\n    - exists []. simpl. assert (A0 : p = []).\n      {\n        inv H. inv H1. destruct H0. destruct x.\n        - rewrite nil_right in H. apply H.\n        - destruct p.\n          + reflexivity.\n          + discriminate.\n      }\n      destruct (accepting fsm) eqn:E0.\n      + rewrite A0. reflexivity.\n      + inv H. rewrite accepts_nil in E0. apply accepts_matches in H2.\n        rewrite E0 in H2. discriminate.\n    - destruct H. apply re_MP1.\n      + apply max_pref_fn_splits in H. symmetry in H.\n        apply pref_def. exists x. apply H.\n      + apply max_pref_matches in H. apply H.\n      + intros cand H0. inv H0. destruct H1.\n        assert (A0 : cand = []).\n        {\n          destruct cand.\n          - reflexivity.\n          - discriminate.\n        }\n        assert (A1 : p = []).\n        {\n          simpl in H. destruct (accepting fsm).\n          - injection H. intros I1 I2. apply I2.\n          - discriminate.\n        }\n        rewrite A0. rewrite A1. left. omega.\n  }\n  {\n    intros p fsm. split; intros H.\n    - destruct p.\n      + exists (a :: code). inv H. simpl.\n        destruct (max_pref_fn code (transition a fsm)) eqn:E0.\n        * destruct p. symmetry in E0.\n          assert (Ae : exists q, Some (p, q) = max_pref_fn code (transition a fsm)).\n          { exists s. apply E0. }\n          apply IHcode in Ae. inv Ae.\n          assert (Ap : a :: p ++_= a :: code).\n          { apply cons_prefix. split. reflexivity. apply H0. }\n          apply H3 in Ap. destruct Ap.\n          -- simpl in H. omega.\n          -- exfalso. destruct H. apply inv_transition. auto.\n        * assert (A0 : accepting (transition a fsm) = false).\n          {\n            destruct code.\n            - simpl in E0. destruct (accepting (transition a fsm)).\n              + discriminate.\n              + reflexivity.\n            - simpl in E0. destruct (max_pref_fn code (transition s (transition a fsm))).\n              + destruct p. discriminate.\n              + destruct (accepting (transition s (transition a fsm))).\n                * discriminate.\n                * destruct (accepting (transition a fsm)).\n                  -- discriminate.\n                  -- reflexivity.\n          }\n          rewrite A0. apply accepts_matches in H2. rewrite <- accepts_nil in H2.\n          rewrite <- H2. reflexivity.\n      + inv H. inv H1. destruct H0. injection H.\n        intros I1 I2. clear H. exists x. subst s.\n        assert (Ap : p ++_= code).\n        { apply pref_def. exists x. apply I1. }\n        simpl. destruct (max_pref_fn code (transition a fsm)) eqn:E0; symmetry in E0.\n        * destruct p0.\n          assert (Ae : exists q, Some (p0, q) = max_pref_fn code (transition a fsm)).\n          { exists s. apply E0. }\n          apply IHcode in Ae. inv Ae. inv H1. destruct H5. apply max_pref_fn_splits in E0.\n          (* Want to show p = p0 *)\n          assert (A0 : p ++_= p ++ x).\n          { apply pref_def. exists x. reflexivity. }\n          assert (A1 : a :: p0 ++_= a :: p ++ x).\n          { apply pref_def. exists x0. rewrite <- H. reflexivity. }\n          apply H3 in A1. apply H4 in A0.\n          (* should follow that p and p0 are prefixes of the same length and thus equal *)\n          assert (A0' : length p <= length p0).\n          {\n            destruct A0.\n            - apply H1.\n            - exfalso. destruct H1. apply inv_transition. auto.\n          }\n          assert (A1' : length p0 <= length p).\n          {\n            destruct A1.\n            - simpl in H1. omega.\n            - exfalso. destruct H1. apply inv_transition; auto.\n          }\n          assert (A : length p = length p0).\n          { omega. }\n          assert (As : p0 ++_= p ++ x).\n          { apply pref_def. exists x0. apply H. }\n          apply eq_len_eq_pref with (x := p ++ x) in A.\n          -- rewrite A. rewrite A in E0. apply app_inv_head in E0. rewrite E0. reflexivity.\n          -- apply As.\n          -- apply Ap.\n        * apply re_max_pref_correct__None in E0. inv E0.\n          assert (A0 : p = []).\n          {\n            assert (A1 : p ++_= p ++ x).\n            { apply pref_def. exists x. reflexivity. }\n            apply H1 in A1. destruct A1. apply inv_transition. auto.\n          }\n          assert (A1 : accepting (transition a fsm) = true).\n          {\n            rewrite A0 in H2. symmetry. apply accepting_nilmatch.\n            apply inv_transition. auto.\n          }\n          rewrite A1. rewrite A0. reflexivity.\n    - destruct H. apply re_MP1.\n      + apply max_pref_fn_splits in H. apply pref_def. exists x. symmetry. apply H.\n      + apply max_pref_matches in H. apply H.\n      + intros cand Hpref. destruct p.\n        * simpl in H.\n          destruct (max_pref_fn code (transition a fsm)) eqn:E0.\n          -- destruct p. discriminate.\n          -- destruct (accepting (transition a fsm)) eqn:E1.\n             ++ discriminate.\n             ++ destruct (accepting fsm) eqn:E2.\n                ** symmetry in E0. apply re_max_pref_correct__None in E0. inv E0. destruct cand.\n                   { left. omega. }\n                   {\n                     right. inv Hpref. destruct H0. injection H0. intros I1 I2.\n                     unfold not. intros C. assert (A : cand ++_= code).\n                     { apply pref_def. exists x0. apply I1. }\n                     apply H1 in A. destruct A. subst. apply inv_transition; auto.\n                   }\n                ** discriminate.\n        * simpl in H.\n          destruct (max_pref_fn code (transition a fsm)) eqn:E0; symmetry in E0.\n          -- destruct p0. injection H. intros I1 I2 I3.\n             assert (Ae : exists q, Some (p0, q) = max_pref_fn code (transition a fsm)).\n             { exists s0. apply E0. }\n             apply IHcode in Ae. inv Ae. destruct cand.\n             ++ left. simpl. omega.\n             ++ inv Hpref. destruct H0. injection H0. intros I1 I2. subst s.\n                assert (Apref : cand ++_= code).\n                { apply pref_def. exists x. apply I1. }\n                apply H3 in Apref. destruct Apref.\n                ** left. simpl. omega.\n                ** right. intros C. destruct H4. apply inv_transition. auto.\n          -- apply re_max_pref_correct__None in E0. inv E0.\n             assert (A0 : accepting (transition a fsm) = true).\n             {\n               destruct (accepting (transition a fsm)); destruct (accepting fsm);\n                 try(reflexivity); try(discriminate).\n             }\n             assert (A1 : [] ++_= code).\n             { apply nil_is_prefix. }\n             apply H1 in A1. destruct A1. apply accepts_matches. rewrite <- accepts_nil.\n             symmetry. apply A0.\n  }\nQed.\n\nTheorem max_pref_correct__None : forall(code : String) (fsm : State),\n    no_max_pref code fsm\n    <-> None = max_pref_fn code fsm.\nProof.\n  intros code fsm. split; intros H.\n  - inv H. destruct H1 as [r]. destruct H. assert(H' := H0). inv H0.\n    (* show that r and (init_state_inv fsm) are equivalent regex's.\n       show that equivalent regex's can be substituted into H'.\n       Then apply previous correctness definition.\n     *)\n    assert(Aeq := inv_eq_model fsm).\n    assert(A0 : forall(s : String), exp_match s r <-> exp_match s (init_state_inv fsm)).\n    {\n      inv H. inv Aeq. intros s.\n      specialize (H2 s). specialize (H0 s).\n      split.\n      - intros H. apply H0 in H. apply H2 in H. apply H.\n      - intros H. apply H0. apply H2. apply H.\n    }\n    assert(A1 : re_no_max_pref code (init_state_inv fsm)).\n    {\n      apply re_MP0.\n      - intros cand Hpref. specialize (H1 cand). apply H1 in Hpref.\n        intros C. destruct Hpref. apply A0 in C. apply C.\n    }\n    apply re_max_pref_correct__None in A1. apply A1.\n  - apply re_max_pref_correct__None in H. apply MP0. exists (init_state_inv fsm). split.\n    + apply inv_eq_model.\n    + apply H.\nQed.\n\nTheorem max_pref_correct__Some : forall(code p : String) (fsm : State),\n    max_pref code fsm p\n    <-> exists(q : String), Some (p, q) = max_pref_fn code fsm.\nProof.\n  intros code p fsm. split; intros H.\n  - inv H. destruct H1 as [r]. destruct H. assert(H' := H0). inv H0.\n    (* show that r and (init_state_inv fsm) are equivalent regex's.\n       show that equivalent regex's can be substituted into H'.\n       Then apply previous correctness definition.\n     *)\n    assert(Aeq := inv_eq_model fsm).\n    assert(A0 : forall(s : String), exp_match s r <-> exp_match s (init_state_inv fsm)).\n    {\n      inv H. inv Aeq. intros s.\n      specialize (H4 s). specialize (H0 s).\n      split.\n      - intros H. apply H0 in H. apply H4 in H. apply H.\n      - intros H. apply H0. apply H4. apply H.\n    }\n    assert(A1 : re_max_pref code (init_state_inv fsm) p).\n    {\n      apply re_MP1.\n      - apply H1.\n      - apply A0. apply H2.\n      - intros cand Hpref. apply H3 in Hpref. destruct Hpref.\n        + left. apply H0.\n        + right. intros C. destruct H. apply A0 in C. contradiction.\n    }\n    apply re_max_pref_correct__Some in A1. apply A1.\n  - apply re_max_pref_correct__Some in H. apply MP1. exists (init_state_inv fsm). split.\n    + apply inv_eq_model.\n    + apply H.\nQed.\n\nLemma no_tokens_suffix_self : forall rus code rest Ha,\n    lex' rus code Ha = ([], rest) -> code = rest.\nProof.\n  intros rus code rest Ha H.\n  apply lex'_cases in H. destruct H.\n  symmetry. apply H.\nQed.\n\nLemma pref_not_no_pref : forall code p r,\n    re_max_pref code r p\n    -> ~(re_no_max_pref code r).\nProof.\n  intros code p r H C. inv H. inv C.\n  apply H0 in H1. contradiction.\nQed.\n\nLemma max_pref_fn_Some_or_None : forall code fsm,\n    (exists p q, Some (p, q) = max_pref_fn code fsm)\n    \\/ None = max_pref_fn code fsm.\nProof.\n  intros code fsm. destruct (max_pref_fn code fsm).\n  - left. destruct p. exists p. exists s. reflexivity.\n  - right. reflexivity.\nQed.\n\nLemma invert_init_correct_max : forall r p code,\n    re_max_pref code (init_state_inv (init_state r)) p\n    <-> re_max_pref code r p.\nProof.\n  split; intros; inv H.\n  - rewrite invert_init_correct' in H2. apply re_MP1; auto.\n    (*\n    intros. apply H3 in H. destruct H.\n    + left. auto.\n    + right; intros C; destruct H; rewrite invert_init_correct' in *; auto.\n    *)\n  - apply re_MP1; auto.\n    (*\n    + apply invert_init_correct'. auto.\n    + intros. apply H3 in H. destruct H.\n      * left. auto.\n      * right. intros C. destruct H. rewrite invert_init_correct' in *. auto.\n    *)\nQed.\n\nLemma invert_init_correct_nomax : forall r code,\n    re_no_max_pref code (init_state_inv (init_state r))\n    <-> re_no_max_pref code r.\nProof.\n  split; intros;\n    inv H; apply re_MP0; intros; apply H1 in H;\n      intros C; destruct H; apply invert_init_correct'; auto.\nQed.\n\nLemma re_pref_or_no_pref : forall code r,\n    (exists p, re_max_pref code r p) \\/ re_no_max_pref code r.\nProof.\n  intros code r. assert(L := max_pref_fn_Some_or_None).\n  specialize (L code). specialize (L (init_state r)). destruct L.\n  - left. destruct H as [p]. apply re_max_pref_correct__Some in H.\n    exists p. rewrite invert_init_correct_max in H. apply H.\n  - right. apply re_max_pref_correct__None in H.\n    rewrite <- invert_init_correct_nomax. auto.\nQed.\n\nLemma part_around_in : forall (T : Type) (xs : list T) (x : T),\n    In x xs -> exists xs1 xs2, xs = xs1 ++ (x :: xs2).\nProof.\n  intros T. induction xs; intros x Hin. contradiction.\n  simpl in Hin. destruct Hin.\n  - exists []. exists xs. rewrite H. reflexivity.\n  - apply IHxs in H. destruct H as (xs1 & xs2 & H).\n    rewrite H. exists (a :: xs1). exists xs2. reflexivity.\nQed.\n\nLemma at_index_In : forall rus ru,\n    (exists n, at_index ru n rus) <-> In ru rus.\nProof.\n  induction rus; intros ru; split; intros H.\n  - inv H. inv H0.\n  - contradiction.\n  - inv H.\n    simpl. destruct x.\n    + inv H0. left. reflexivity.\n    + inv H0. right. apply IHrus. exists x. apply IH.\n  - simpl in H. destruct H.\n    + exists 0. apply AI0. auto.\n    + apply IHrus in H. inv H. exists (S x).\n      apply AI1. apply H0.\nQed.\n\nLemma In_least_index : forall rus ru,\n    In ru rus <-> (exists n, least_index ru n rus).\nProof.\n  intros rus ru. split.\n  {\n    generalize dependent ru. induction rus; intros ru H. contradiction.\n    destruct (ru_dec a ru).\n    {\n      subst. exists 0. apply LI1.\n      - apply AI0. auto.\n      - intros n' Hlt. omega.\n    }\n    {\n      destruct H.\n      - contradiction.\n      - apply IHrus in H. destruct H. exists (S x). inv H. apply LI1.\n        + apply AI1. apply Hat.\n        + intros n' Hlt. intros C. destruct n'.\n          * inv C. contradiction.\n          * assert(Hlt' : n' < x). omega.\n            apply Hnot in Hlt'. inv C. contradiction.\n    }\n  }\n  {\n    generalize dependent ru. induction rus; intros ru H.\n    - inv H. inv H0. inv Hat.\n    - destruct (ru_dec a ru); subst.\n      + simpl. auto.\n      + inv H. destruct x.\n        * inv H0. inv Hat. contradiction.\n        * simpl. right. apply IHrus. exists x. inv H0. apply LI1.\n          -- inv Hat. apply IH.\n          -- intros n' Hlt. specialize (Hnot (S n')).\n             assert(A : S n' < S x). omega.\n             apply Hnot in A. intros C. destruct A.\n             apply AI1. apply C.\n  }\nQed.\n\nLemma at_index_num_prev : forall rus1 ru rus2,\n    at_index ru (length rus1) (rus1 ++ ru :: rus2).\nProof.\n  induction rus1; intros ru rus2.\n  - simpl. apply AI0. reflexivity.\n  - simpl. apply AI1. apply IHrus1.\nQed.\n\nLemma part_around_least_index : forall rus n ru,\n    least_index ru n rus -> (exists rus1 rus2,\n                                rus = rus1 ++ (ru :: rus2)\n                                /\\ length rus1 = n\n                                /\\ ~(In ru rus1)).\nProof.\n  induction rus; intros n ru H.\n  {\n    inv H. inv Hat.\n  }\n  {\n    inv H. inv Hat.\n    - exists []. exists rus. split; [| split]; try(auto).\n    - assert(least_index ru n0 rus).\n      {\n        apply LI1.\n        - apply IH.\n        - intros n' H C.\n          assert(A0 : S n' < S n0).\n          { omega. }\n          apply Hnot in A0. destruct A0.\n          apply AI1. apply C.\n      }\n      apply IHrus in H.\n      destruct H as (rus1 & rus2 & IH').\n      destruct IH' as (Heq & Hlen & Hnin).\n      exists (a :: rus1). exists rus2. split; [| split].\n      + rewrite Heq. reflexivity.\n      + simpl. omega.\n      + intros C. destruct Hnin. simpl in C. destruct C.\n        * specialize (Hnot 0). rewrite H in Hnot. destruct Hnot.\n          -- omega.\n          -- apply AI0. reflexivity.\n        * apply H.\n  }\nQed.\n\n(* Ah so this is what proof automation can do... *)\nLemma lgr_pref_assoc : forall a b c,\n    longer_pref (longer_pref a b) c = longer_pref a (longer_pref b c).\nProof.\n  intros a b c. unfold longer_pref.\n  repeat dm; repeat inj_all; subst; repeat eqb_eq_all; repeat ltb_lt_all;\n    try(discriminate);\n    try(omega);\n    try(auto).\nQed.\n\nLemma mpref_app_dist : forall ps1 ps2,\n    max_of_prefs (ps1 ++ ps2) = longer_pref (max_of_prefs ps1) (max_of_prefs ps2).\nProof.\n  induction ps1; intros ps2.\n  - simpl. destruct (max_of_prefs ps2). reflexivity.\n  - simpl. rewrite IHps1. symmetry. apply lgr_pref_assoc.\nQed.\n\nLemma mpref_cons : forall ps p,\n    max_of_prefs (p :: ps) = longer_pref p (max_of_prefs ps).\nProof.\n  intros ps p. simpl. reflexivity.\nQed.\n\nLemma nil_mpref_nil_or_no_pref : forall rus code s l l1 r,\n    max_of_prefs (max_prefs code (map init_srule rus)) = (l1, Some ([], s))\n    -> In (l, r) rus\n    -> re_max_pref code r [] \\/ re_no_max_pref code r.\nProof.\n  intros rus code s l l1 r Hmax Hin. assert(L := re_pref_or_no_pref code r).\n  destruct L.\n  - destruct H. destruct x.\n    + left. apply H.\n    (* This was a fun one *)\n    + exfalso.\n      apply invert_init_correct_max in H.\n      apply re_max_pref_correct__Some in H. destruct H as [q]. symmetry in H.\n      assert(L := (part_around_in _ rus (l, r)) Hin).\n      destruct L as (rus1 & rus2 & L). subst rus. clear Hin.\n      rewrite map_app in Hmax. rewrite map_cons in Hmax. simpl in Hmax.\n      unfold max_prefs in Hmax. rewrite map_app in Hmax. rewrite map_cons in Hmax. simpl in Hmax.\n      rewrite H in Hmax. rewrite mpref_app_dist in Hmax. rewrite mpref_cons in Hmax.\n      simpl in Hmax. unfold longer_pref in Hmax.\n      (* 32 subgoals, 7 subproofs ! *)\n      repeat dmh; subst;\n        try (discriminate);\n        try(injection Hmax; intros I1 I2 I3; subst p0;\n            destruct p2; [discriminate | simpl in E5; discriminate]);\n        try(injection E2; intros; subst; discriminate);\n        try(rewrite Hmax in E1; discriminate).\n      * injection E2; intros; injection Hmax; intros; subst;\n          rewrite E11 in E5; simpl in E5; discriminate.\n      * injection E2; intros; injection Hmax; intros; subst;\n          destruct (length p0); simpl in E6; rewrite Nat.ltb_lt in E6; omega.\n      * rewrite Hmax in E1. injection E1; intros; subst. simpl in E7; discriminate.\n  - right. apply H.\nQed.\n\nLemma no_mpref_no_pref : forall rus code l l1 r,\n    max_of_prefs (max_prefs code (map init_srule rus)) = (l1, None)\n    -> In (l, r) rus\n    -> re_no_max_pref code r.\nProof.\n  intros rus code l l1 r Hmax Hin. assert(L := re_pref_or_no_pref code r).\n  destruct L.\n  - exfalso. destruct H. apply invert_init_correct_max in H.\n    apply re_max_pref_correct__Some in H. destruct H as [q]. symmetry in H.\n    assert(L := (part_around_in _ rus (l, r)) Hin).\n    destruct L as (rus1 & rus2 & L). subst rus. clear Hin.\n    rewrite map_app in Hmax. rewrite map_cons in Hmax. simpl in Hmax.\n    unfold max_prefs in Hmax. rewrite map_app in Hmax. rewrite map_cons in Hmax. simpl in Hmax.\n    rewrite H in Hmax. rewrite mpref_app_dist in Hmax. rewrite mpref_cons in Hmax.\n    simpl in Hmax. unfold longer_pref in Hmax.\n    repeat dmh; repeat inj_all; subst;\n      try(discriminate);\n      try(rewrite Hmax in E1; discriminate).\n  - apply H.\nQed.\n\nLemma no_tokens_no_pref : forall code rest rus l r Ha,\n    lex' (map init_srule rus) code Ha = ([], rest)\n    -> In (l, r) rus\n    -> re_max_pref code r [] \\/ re_no_max_pref code r.\nProof.\n  intros code rest rus l r Ha Hlex Hin.\n  apply lex'_cases in Hlex. destruct Hlex.\n  destruct H0; destruct (max_of_prefs (max_prefs code (map init_srule rus))) eqn:E0;\n    simpl in H0; [| destruct H0 as (suf & H0)]; rewrite H0 in E0.\n  - apply no_mpref_no_pref with (l := l) (r := r) in E0.\n    + right. apply E0.\n    + apply Hin.\n  - apply nil_mpref_nil_or_no_pref with (l := l) (r := r) in E0.\n    + apply E0.\n    + apply Hin.\nQed.\n\nLemma max_pref_unique : forall code r p p',\n    re_max_pref code r p\n    -> re_max_pref code r p'\n    -> p = p'.\nProof.\n  intros code r p p' Hp Hp'.\n  inv Hp. inv Hp'.\n  assert(Hp := H1). assert(Hp' := H0).\n  apply H5 in H1. apply H3 in H0. clear H3 H5.\n  assert(A : length p <= length p' /\\ length p' <= length p).\n  { split; [destruct H1 | destruct H0]; try (apply H); try (contradiction). }\n  assert (Aeq : length p' = length p).\n  { omega. }\n  apply eq_len_eq_pref with (x := code) in Aeq.\n  apply Aeq. apply Hp. apply Hp'.\nQed.\n\nLemma max_pref_longer : forall xs l p s l' p' s' code,\n    max_of_prefs xs = (l, Some(p, s))\n    -> In (l', Some(p', s')) xs\n    -> (l', Some(p', s')) <> (l, Some(p, s))\n    -> p ++_= code\n    -> p' ++_= code\n    -> longer_pref (l, Some(p, s)) (l', Some(p', s')) = (l, Some(p, s)).\nProof.\n  intros xs l p s l' p' s' code Hmax Hin Hneq Hpref Hpref'.\n  assert(Apart : exists xs1 xs2, xs = xs1 ++ ((l', Some(p', s')) :: xs2)).\n  { apply part_around_in. apply Hin.  }\n  destruct Apart as (xs1 & xs2 & Apart).\n  rewrite Apart in *.\n  rewrite mpref_app_dist in Hmax. rewrite mpref_cons in Hmax.\n  destruct (max_of_prefs xs1); destruct (max_of_prefs xs2).\n  unfold longer_pref in Hmax. unfold longer_pref.\n  repeat dm; subst;\n    try(rewrite <- E0 in Hmax; injection Hmax; intros; subst);\n    repeat inj_all;\n    repeat ltb_lt_all;\n    repeat eqb_eq_all;\n    try(omega);\n    try(discriminate).\nQed.\n\nLemma app_smaller_pref : forall {T : Type} (rus p1 p2 s1 s2 : list T) a1 a2,\n    length p1 < length p2\n    -> rus = p1 ++ a1 :: s1\n    -> rus = p2 ++ a2 :: s2\n    -> exists x y, (x ++ a2 :: y = s1\n                    /\\ p1 ++ a1 :: x = p2\n                    /\\ rus = p1 ++ (a1 :: x) ++ (a2 :: y) ).\nProof.\n  intros T. induction rus; intros.\n  - exfalso. assert(L := app_cons_not_nil p1 s1 a1). contradiction.\n  - destruct p1; destruct p2; try(simpl in H; omega).\n    + simpl in H0. injection H0. injection H1. intros. subst.\n      exists p2. exists s2. split; [|split]; reflexivity.\n    + injection H0. injection H1. intros.\n      assert(H' : length p1 < length p2).\n      { simpl in H. omega. }\n      apply IHrus with (s1 := s1) (s2 := s2) (a1 := a1) (a2 := a2) in H'.\n      2:{ apply H4. }\n      2:{ apply H2. }\n      subst.\n      destruct H' as (x & y & H'). destruct H'. destruct H3.\n      exists x. exists y. split; [|split].\n      * auto.\n      * simpl. rewrite H3. auto.\n      * simpl. simpl in H5. rewrite H5. auto.\nQed.\n\nLemma exists_rus_of_mpref : forall rus code l ph pt suffix,\n    max_of_prefs (max_prefs code (map init_srule rus)) = (l, Some (ph :: pt, suffix))\n    -> (exists r, In (l, r) rus\n                  /\\ max_pref_fn code (init_state r) = Some (ph :: pt, suffix)).\nProof.\n  induction rus; intros.\n  {\n    simpl in H. discriminate.\n  }\n  {\n    unfold max_prefs in H.\n    repeat first [rewrite map_cons in H | rewrite map_app in H].\n    symmetry in H. apply max_first_or_rest in H. destruct H.\n    - destruct a. simpl in H. injection H; intros; subst.\n      exists r. split.\n      * left. auto.\n      * auto.\n    - symmetry in H. apply IHrus in H. destruct H as [r]. destruct H.\n      exists r. split.\n      + right. apply H.\n      + apply H0.\n  }\nQed.\n\nLemma first_token_mpref : forall rus code l ph pt suffix,\n    max_of_prefs (max_prefs code (map init_srule rus)) = (l, Some (ph :: pt, suffix))\n    -> rules_is_function rus\n    -> first_token code rus (l, ph :: pt).\nProof.\n  intros rus code l ph pt suffix H Hfunc.\n  assert(Aex := exists_rus_of_mpref rus code l ph pt suffix H).\n  destruct Aex as [r]. destruct H0 as (Hin & Hmpref_fn).\n  assert(Hmpref : re_max_pref code r (ph :: pt)).\n  {\n    symmetry in Hmpref_fn.\n    assert(exists q, Some (ph :: pt, q) = max_pref_fn code (init_state r)).\n    { eexists; eauto. }\n    apply re_max_pref_correct__Some in H0. rewrite invert_init_correct_max in H0. auto.\n  }\n  apply FT1 with (r := r).\n  - intros C. discriminate.\n  - apply Hin.\n  - apply Hmpref.\n  - intros l0 r0 p0 Hlen Hmpref'. intros C.\n    apply invert_init_correct_max in Hmpref'.\n    apply re_max_pref_correct__Some with (fsm := init_state r0) in Hmpref'. destruct Hmpref'.\n    assert(Ain : In (l0, max_pref_fn code (init_state r0))\n                    (max_prefs code (map init_srule rus))).\n    {\n      apply part_around_in in C. destruct C as (rus1 & rus2 & C). rewrite C.\n      unfold max_prefs. repeat rewrite map_app. repeat rewrite map_cons. simpl.\n      apply in_or_app. right. simpl. left. reflexivity.\n    }\n    assert(Aneq : (l0, max_pref_fn code (init_state r0)) <> (l, Some (ph :: pt, suffix))).\n    { rewrite <- H0. intros C1. injection C1; intros; subst. omega. }\n    apply max_pref_longer\n      with (l' := l0) (p' := p0) (s' := x) (code := code)\n      in H.\n    + rewrite <- H0 in *. unfold longer_pref in H. repeat dmh.\n      * eqb_eq_all. omega.\n      * contradiction.\n      * ltb_lt_all. omega.\n    + rewrite <- H0 in Ain. apply Ain.\n    + rewrite <- H0 in Aneq. apply Aneq.\n    + inv Hmpref. apply H1.\n    + assert(A : exists q, Some (p0, q) = max_pref_fn code (init_state r0)).\n      { exists x. apply H0. }\n      apply re_max_pref_correct__Some in A. inv A. apply H1.\n  - intros r0 l0 Hearly Hin0 Hmpref0.\n    assert(Hmpref_fn0 : max_pref_fn code (init_state r0) = Some (ph :: pt, suffix)).\n    {\n      apply invert_init_correct_max in Hmpref0.\n      apply re_max_pref_correct__Some with (fsm := init_state r0) in Hmpref0.\n      destruct Hmpref0 as (x & Hmpref_fn0).\n      assert(Asuff : x = suffix).\n      {\n        symmetry in Hmpref_fn. apply max_pref_fn_splits in Hmpref_fn.\n        apply max_pref_fn_splits in Hmpref_fn0.\n        rewrite Hmpref_fn in Hmpref_fn0. apply app_inv_head in Hmpref_fn0.\n        symmetry. apply Hmpref_fn0.\n      }\n      subst. auto.\n    }\n    assert(Aneq : l <> l0).\n    {\n      intros C. subst. unfold rules_is_function in Hfunc.\n      apply Hfunc with (r := r0) in Hin.\n      2:{ apply Hin0. }\n      subst. inv Hearly. apply In_least_index in Hin0.\n      destruct Hin0. apply H0 with (n1 := x) in H1.\n      2:{ apply H1. }\n      omega.\n    }\n    inv Hearly. apply In_least_index in Hin. apply In_least_index in Hin0.\n    assert(Hin' := Hin).\n    destruct Hin as (n2 & Hleast). destruct Hin0 as (n1 & Hleast').\n    assert(Alt : n1 < n2).\n    { auto. }\n    apply part_around_least_index in Hleast.\n    destruct Hleast as (rus1 & rus2 & Hleast). destruct Hleast as (Heq & Hlen & Hnin).\n    apply part_around_least_index in Hleast'.\n    destruct Hleast' as (rus1' & rus2' & Hleast'). destruct Hleast' as (Heq' & Hlen' & Hnin').\n    rewrite <- Hlen in Alt. rewrite <- Hlen' in Alt.\n    clear Hlen Hlen'.\n    apply app_smaller_pref with (rus0 := rus)\n                                (s1 := rus2')\n                                (s2 := rus2)\n                                (a2 := (l,r))\n                                (a1 := (l0, r0)) in Alt.\n    2:{ apply Heq'. }\n    2:{ apply Heq. }\n    destruct Alt as (x & y & H1). destruct H1. destruct H2.\n    clear H0 Heq Heq'.\n    rewrite H3 in *.\n    assert(A0 : max_of_prefs (map (extract_fsm_for_max code) (map init_srule rus1')) <>\n                (l, Some (ph :: pt, suffix))).\n    {\n      intros C. apply exists_rus_of_mpref in C.\n      destruct C as (r' & C). destruct C as (C1 & C2).\n      destruct (regex_eq r r') eqn:E.\n      - destruct Hnin.  apply regex_eq_correct in E. subst. apply in_or_app. left. apply C1.\n      - subst. apply In_least_index in Hin'.\n        assert(C1' : In (l, r') (rus1' ++ ((l0, r0) :: x) ++ (l, r) :: y)).\n        { apply in_or_app. left. apply C1. }\n        apply false_not_true in E. destruct E. apply regex_eq_correct.\n        unfold rules_is_function in Hfunc. apply Hfunc with (l1 := l).\n        + apply Hin'.\n        + apply C1'.\n    }\n    unfold max_prefs in H.\n    repeat first [rewrite map_cons in H | rewrite map_app in H].\n    repeat first [rewrite mpref_cons in H | rewrite mpref_app_dist in H].\n    unfold longer_pref in H.\n    repeat dmh; repeat simpl in *; rewrite Hmpref_fn in *; rewrite Hmpref_fn0 in *;\n      repeat inj_all; subst; repeat ltb_lt_all; repeat eqb_eq_all; subst;\n        try(omega); try(contradiction); try(discriminate).\nQed.\n\nLemma lex'_splits : forall ts code rest rus Ha,\n    lex' (map init_srule rus) code Ha = (ts, rest)\n    -> code = (concat (map snd ts)) ++ rest.\nProof.\n  induction ts; intros code rest rus Ha H.\n  {\n    simpl. apply no_tokens_suffix_self in H. auto.\n  }\n  {\n    destruct a. apply lex'_cases in H.\n    destruct H as (h & t & H). destruct H as (s & Heq & H).\n    destruct H. apply IHts in H.\n    apply exists_rus_of_mpref in Heq. destruct Heq. destruct H1.\n    symmetry in H2. apply max_pref_fn_splits in H2.\n    subst. simpl.\n    replace ((t ++ concat (map snd ts)) ++ rest)\n      with (t ++ concat (map snd ts) ++ rest).\n    2:{ apply app_assoc. }\n    reflexivity.\n  }\nQed.\n\nLemma eq_index_eq_ru : forall n rus ru1 ru2,\n    at_index ru1 n rus\n    -> at_index ru2 n rus\n    -> ru1 = ru2.\nProof.\n  induction n; intros.\n  - inv H. inv H0. auto.\n  - inv H. inv H0. eapply IHn; eauto.\nQed.\n\nLemma eq_LI_eq_ru : forall n rus ru1 ru2,\n    least_index ru1 n rus\n    -> least_index ru2 n rus\n    -> ru1 = ru2.\nProof.\n  intros. inv H. inv H0. eapply eq_index_eq_ru; eauto.\nQed.\n\nLemma least_index_unique : forall rus ru n1 n2,\n    least_index ru n1 rus\n    -> least_index ru n2 rus\n    -> n1 = n2.\nProof.\n  intros. inv H. inv H0.\n  destruct (Nat.lt_trichotomy n1 n2); [| destruct H].\n  - apply Hnot0 in H. contradiction.\n  - auto.\n  - apply Hnot in H. contradiction.\nQed.\n\nLemma earlier_rule_split : forall rus ru1 ru2,\n    In ru1 rus\n    -> In ru2 rus\n    -> ru1 = ru2 \\/\n      earlier_rule ru1 ru2 rus \\/\n      earlier_rule ru2 ru1 rus.\nProof.\n  intros.\n  apply In_least_index in H. destruct H as [n1].\n  apply In_least_index in H0. destruct H0 as [n2].\n  assert(L := Nat.lt_trichotomy n1 n2). destruct L as [| L]; [|destruct L].\n  - right. left. apply ERu1. intros.\n    apply least_index_unique with (n1 := n0) in H; auto; subst.\n    apply least_index_unique with (n1 := n3) in H0; auto; subst.\n    auto.\n  - left. subst. apply eq_LI_eq_ru with (ru1 := ru1) in H0; auto.\n  - right. right. apply ERu1. intros.\n    apply least_index_unique with (n1 := n3) in H; auto; subst.\n    apply least_index_unique with (n1 := n0) in H0; auto; subst.\n    auto.\nQed.\n\nLemma flip_gt : forall n m,\n    n > m <-> m < n.\nProof.\n  intros. omega.\nQed.\n\nLemma first_token_unique : forall t t' code rus,\n    first_token code rus t\n    -> first_token code rus t'\n    -> t = t'.\nProof.\n  intros. inv H; inv H0.\n  (* show p and p0 are prefixes of equal length and thus equal *)\n  assert(Alen : length p = length p0).\n  {\n    destruct (Nat.lt_trichotomy (length p) (length p0)); [|destruct H].\n    - apply flip_gt in H. eapply Hout in H; destruct H; eauto.\n    - auto.\n    - apply flip_gt in H. apply Hout0 with (l' := l) (r' := r) in H; destruct H; auto.\n  }\n  assert(Aeq : p = p0).\n  {\n    inv Hmpref. inv Hmpref0.\n    eapply eq_len_eq_pref in Alen; eauto.\n  }\n  subst.\n  (* show neither rule can be earlier than the other and thus they are equal *)\n  specialize (Hlater r0 l0).\n  specialize (Hlater0 r l).\n  clear Hout Hout0 Hnempt Hnempt0.\n  assert(L := earlier_rule_split rus (l,r) (l0,r0) Hex Hex0). destruct L; [| destruct H].\n  - inv H. auto.\n  - apply Hlater0 in H; auto. contradiction.\n  - apply Hlater in H; auto. contradiction.\nQed.\n", "meta": {"author": "egolf-cs", "repo": "vlg", "sha": "84f22921f9671cac506bef1b4887d73ecc74436d", "save_path": "github-repos/coq/egolf-cs-vlg", "path": "github-repos/coq/egolf-cs-vlg/vlg-84f22921f9671cac506bef1b4887d73ecc74436d/aux/lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.22375062479902422}}
{"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Tactics.\nRequire Import Sequence.\nRequire Import Relation.\nRequire Import Syntax.\nRequire Import Subst.\nRequire Import SimpSub.\nRequire Import Dynamic.\nRequire Import Promote.\nRequire Import Hygiene.\nRequire Import Rules.\nRequire Import DerivedRules.\nRequire Defs.\nRequire Import Obligations.\nRequire Import Morphism.\nRequire Import DefsEquiv.\nRequire Import Equivalence.\n\nRequire Import ValidationUtil.\nRequire Import Defined.\nRequire Import NatLemmas.\nRequire Import LevelLemmas.\n\n\nHint Rewrite def_lsucc : prepare.\n\n\n\nLemma univKind_valid : univKind_obligation.\nProof.\nprepare.\nintros G i j ext0 H.\napply tr_univ_kind_formation; auto.\neapply tr_eq_reflexivity; eauto.\nQed.\n\n\nLemma univKindEq_valid : univKindEq_obligation.\nProof.\nprepare.\nintros G i j k ext1 ext0 Hjk Hji.\napply tr_univ_kind_formation; auto.\nQed.\n\n\nLemma univForm_valid : univForm_obligation.\nProof.\nprepare.\nintros G i ext0 H.\napply tr_univ_formation; auto.\nQed.\n\n\nLemma univEq_valid : univEq_obligation.\nProof.\nprepare.\nintros G i j ext0 H.\napply tr_univ_formation; auto.\nQed.\n\n\nLemma univFormUniv_valid : univFormUniv_obligation.\nProof.\nprepare.\nintros G i j ext Hleq.\nso (lleq_explode _#5 Hleq) as (H & Hsj & Hi).\nso (tr_nsucc_nattp_invert _#3 Hsj) as Hj.\napply tr_univ_formation_univ; auto.\nunfold ltpagetp.\nrewrite -> equiv_lttp.\nauto.\nQed.\n\n\nLemma univFormUnivSucc_valid : univFormUnivSucc_obligation.\nProof.\nprepare.\nintros G i ext0 H.\napply tr_univ_formation_univ; auto.\n  {\n  unfold pagetp.\n  apply tr_nsucc_nattp; auto.\n  }\n\n  {\n  unfold ltpagetp.\n  rewrite -> equiv_lttp.\n  apply tr_leqtp_refl.\n  apply tr_nsucc_nattp; auto.\n  }\nQed.\n\n\nLemma univEqUniv_valid : univEqUniv_obligation.\nProof.\nprepare.\nintros G i j k ext1 ext Hjk Hleq.\nso (lleq_explode _#5 Hleq) as (H & Hsj & Hi).\nso (tr_nsucc_nattp_invert _#3 Hsj) as Hj.\napply tr_univ_formation_univ; auto.\nunfold ltpagetp.\nrewrite -> equiv_lttp.\neapply tr_leqtp_eta2; eauto.\nQed.\n\n\nLemma univCumulativeOf_valid : univCumulativeOf_obligation.\nProof.\nprepare.\nintros G a i j ext1 ext0 Ha Hleq.\nso (lleq_explode _#5 Hleq) as (H & Hi & Hj).\neapply tr_univ_cumulative; eauto.\nQed.\n\n\nLemma univCumulativeEq_valid : univCumulativeEq_obligation.\nProof.\nprepare.\nintros G a b i j ext1 ext0 Hab Hleq.\nso (lleq_explode _#5 Hleq) as (H & Hi & Hj).\neapply tr_univ_cumulative; eauto.\nQed.\n\n\nLemma univCumulativeSuccOf_valid : univCumulativeSuccOf_obligation.\nProof.\nprepare.\nintros G a i ext0 H.\neapply tr_univ_cumulative; eauto.\n  {\n  unfold pagetp.\n  apply tr_nsucc_nattp.\n  fold (@pagetp obj).\n  apply tr_univ_formation_invert.\n  eapply tr_inhabitation_formation; eauto.\n  }\n\n  {\n  unfold leqpagetp.\n  apply tr_leqtp_succ.\n  fold (@pagetp obj).\n  apply tr_univ_formation_invert.\n  eapply tr_inhabitation_formation; eauto.\n  }\nQed.\n\n\nLemma univSub_valid : univSub_obligation.\nProof.\nprepare.\nintros G i j ext0 Hleq.\nso (lleq_explode _#5 Hleq) as (H & Hi & Hj).\napply tr_subtype_intro; auto using tr_univ_formation.\nsimpsub.\napply (tr_univ_cumulative _ (subst sh1 i)).\n  {\n  eapply hypothesis; eauto using index_0.\n  }\n\n  {\n  eapply (weakening _ [_] []).\n    {\n    cbn [length Dots.unlift].\n    simpsub.\n    reflexivity.\n    }\n\n    {\n    cbn [length Dots.unlift].\n    simpsub.\n    reflexivity.\n    }\n  cbn [length Dots.unlift].\n  simpsub.\n  auto.\n  }\n\n  {\n  eapply (weakening _ [_] []).\n    {\n    cbn [length Dots.unlift].\n    simpsub.\n    reflexivity.\n    }\n\n    {\n    cbn [length Dots.unlift].\n    simpsub.\n    reflexivity.\n    }\n  cbn [length Dots.unlift].\n  simpsub.\n  unfold leqpagetp.\n  eapply tr_leqtp_eta2; eauto.\n  }\nQed.\n\n\nLemma univForgetOf_valid : univForgetOf_obligation.\nProof.\nprepare.\nintros G a i ext0 H.\neapply tr_formation_weaken; eauto.\nQed.\n\n\nLemma univForgetEq_valid : univForgetEq_obligation.\nProof.\nprepare.\nintros G a b i ext0 H.\neapply tr_formation_weaken; eauto.\nQed.\n\n\nLemma univIntroEqtype_valid : univIntroEqtype_obligation.\nProof.\nprepare.\nintros G a b i ext2 ext1 ext0 Hab Ha Hb.\neapply tr_formation_strengthen; eauto.\nQed.\n  \n\nLemma univFormInv_valid : univFormInv_obligation.\nProof.\nprepare.\nintros G I ext0 Huniv.\napply tr_univ_formation_invert.\nauto.\nQed.\n\n\nLemma kindForm_valid : kindForm_obligation.\nProof.\nprepare.\nintros G i ext0 H.\napply tr_kuniv_formation; auto.\nQed.\n\n\nLemma kindEq_valid : kindEq_obligation.\nProof.\nprepare.\nintros G i j ext0 H.\napply tr_kuniv_formation; eauto.\nQed.\n\n\nLemma kindFormUniv_valid : kindFormUniv_obligation.\nProof.\nprepare.\nintros G i k ext0 Hleq.\nso (lleq_explode _#5 Hleq) as (H & Hssi & Hk).\nso (tr_nsucc_nattp_invert _#3 Hssi) as Hsi.\nso (tr_nsucc_nattp_invert _#3 Hsi) as Hi.\napply tr_kuniv_formation_univ; auto.\nunfold ltpagetp.\nrewrite -> equiv_lttp.\neapply tr_leqtp_eta2; eauto.\nQed.\n\n\nLemma kindEqUniv_valid : kindEqUniv_obligation.\nProof.\nprepare.\nintros G i j k ext1 ext0 Hij Hleq.\nso (lleq_explode _#5 Hleq) as (H & _ & Hk).\napply tr_kuniv_formation_univ; auto.\nunfold ltpagetp.\nrewrite -> equiv_lttp.\neapply tr_leqtp_eta2; eauto.\napply tr_nsucc_nattp.\napply tr_nsucc_nattp.\neapply tr_eq_reflexivity; eauto.\nQed.\n\n\nLemma kindForgetOf_valid : kindForgetOf_obligation.\nProof.\nprepare.\nintros G a i ext0 H.\napply tr_kuniv_weaken; auto.\nQed.\n\n\nLemma kindForgetEq_valid : kindForgetEq_obligation.\nProof.\nprepare.\nintros G a b i ext0 H.\napply tr_kuniv_weaken; auto.\nQed.\n\n\nLemma kindUnivSub_valid : kindUnivSub_obligation.\nProof.\nprepare.\nintros G i j ext0 Hleq.\nso (lleq_explode _#5 Hleq) as (H & Hsi & Hj).\nso (tr_nsucc_nattp_invert _#3 Hsi) as Hi.\napply tr_subtype_intro.\n  {\n  apply tr_kuniv_formation; eauto.\n  }\n\n  {\n  apply tr_univ_formation; eauto.\n  }\nsimpsub.\napply (tr_univ_cumulative _ (nsucc (subst sh1 i))).\n  {\n  apply tr_kuniv_weaken.\n  eapply hypothesis; eauto using index_0.\n  }\n\n  {\n  eapply (weakening _ [_] []).\n    {\n    cbn [length Dots.unlift].\n    simpsub.\n    reflexivity.\n    }\n\n    {\n    cbn [length Dots.unlift].\n    simpsub.\n    reflexivity.\n    }\n  cbn [length Dots.unlift].\n  simpsub.\n  auto.\n  }\n\n  {\n  eapply (weakening _ [_] []).\n    {\n    cbn [length Dots.unlift].\n    simpsub.\n    reflexivity.\n    }\n\n    {\n    cbn [length Dots.unlift].\n    simpsub.\n    reflexivity.\n    }\n  cbn [length Dots.unlift].\n  simpsub.\n  unfold leqpagetp.\n  eapply tr_leqtp_eta2; eauto.\n  }\nQed.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/ValidationUniv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22375061921504105}}
{"text": "(* This file is an automatic translation, the licence of the source can be found here: *)\n(* https://github.com/herd/herdtools7/blob/master/LICENSE.txt *)\n(* Translation of model C++11 *)\nFrom Coq Require Import Relations Ensembles String.\nFrom RelationAlgebra Require Import lattice prop monoid rel kat.\nFrom Catincoq.lib Require Import Cat proprel.\nSection Model.\nVariable c : candidate.\nDefinition events := events c.\nDefinition R := R c.\nDefinition W := W c.\nDefinition IW := IW c.\nDefinition FW := FW c.\nDefinition B := B c.\nDefinition RMW := RMW c.\nDefinition F := F c.\nDefinition rf := rf c.\nDefinition po := po c.\nDefinition int := int c.\nDefinition ext := ext c.\nDefinition loc := loc c.\nDefinition addr := addr c.\nDefinition data := data c.\nDefinition ctrl := ctrl c.\nDefinition amo := amo c.\nDefinition rmw := rmw c.\nDefinition unknown_set := unknown_set c.\nDefinition unknown_relation := unknown_relation c.\nDefinition M := R ⊔ W.\nDefinition emptyset : set events := empty.\nDefinition classes_loc : set events -> Ensemble (Ensemble events) := partition loc.\nDefinition A := unknown_set \"A\".\nDefinition ACQ := unknown_set \"ACQ\".\nDefinition ACQ_REL := unknown_set \"ACQ_REL\".\nDefinition CON := unknown_set \"CON\".\nDefinition I := unknown_set \"I\".\nDefinition LK := unknown_set \"LK\".\nDefinition LS := unknown_set \"LS\".\nDefinition REL := unknown_set \"REL\".\nDefinition SC := unknown_set \"SC\".\nDefinition UL := unknown_set \"UL\".\nDefinition coi := unknown_relation \"coi\".\nDefinition tag2events := unknown_relation \"tag2events\".\nDefinition emptyset_0 : set events := domain 0.\nDefinition partition := classes_loc.\nDefinition tag2instrs := tag2events.\nDefinition po_loc := po ⊓ loc.\nDefinition rfe := rf ⊓ ext.\nDefinition rfi := rf ⊓ int.\nDefinition co0 := loc ⊓ ([IW] ⋅ top ⋅ [(W ⊓ !IW)] ⊔ [(W ⊓ !FW)] ⋅ top ⋅ [FW]).\nDefinition toid (s : set events) : relation events := [s].\nDefinition fencerel (B : set events) := (po ⊓ [top] ⋅ top ⋅ [B]) ⋅ po.\nDefinition ctrlcfence (CFENCE : set events) := (ctrl ⊓ [top] ⋅ top ⋅ [CFENCE]) ⋅ po.\nDefinition imply (A : relation events) (B : relation events) := !A ⊔ B.\nDefinition nodetour (R1 : relation events) (R2 : relation events) (R3 : relation events) := R1 ⊓ !(R2 ⋅ R3).\nDefinition singlestep (R : relation events) := nodetour R R R.\n(* Definition of map already included in the prelude *)\nDefinition LKW := (*failed: try LKW with emptyset_0*) emptyset_0.\n(* Definition of co_locs already included in the prelude *)\n(* Definition of cross already included in the prelude *)\nDefinition generate_orders s pco := cross (co_locs pco (partition s)).\nDefinition generate_cos pco := generate_orders W pco.\nDefinition mobase := co0.\nVariable mo : relation events.\nDefinition moi := mo ⊓ int.\nDefinition moe := mo ⊓ ext.\nDefinition co := mo.\nDefinition coe := moe.\nDefinition coi_0 := coi.\nDefinition fr := rf° ⋅ mo ⊓ !id.\nDefinition fri := fr ⊓ int.\nDefinition fre := fr ⊓ ext.\nDefinition crit := let Mutex := LS ⊔ UL in let poMutex := po_loc ⊓ [Mutex] ⋅ top ⋅ [Mutex] in po_loc ⊓ [LS] ⋅ top ⋅ [UL] ⊓ !(poMutex ⋅ poMutex).\nVariable loLL : relation events.\nDefinition loLU := (loLL ⊔ 1) ⋅ crit.\nDefinition loUL := crit° ⋅ loLL.\nDefinition lo := (loLL ⊔ (loLU ⊔ loUL))^+.\nDefinition asw := [I] ⋅ top ⋅ [(M ⊓ !I)].\nDefinition sb := po.\nDefinition mo_0 := co.\nDefinition cacq := ACQ ⊔ (SC ⊓ (R ⊔ F) ⊔ (ACQ_REL ⊔ F ⊓ CON)).\nDefinition crel := REL ⊔ (SC ⊓ (W ⊔ F) ⊔ ACQ_REL).\nDefinition ccon := R ⊓ CON.\nDefinition fr_0 := rf° ⋅ mo_0.\nDefinition dd := (data ⊔ addr)^+.\nDefinition fsb := sb ⊓ [F] ⋅ top ⋅ [top].\nDefinition sbf := sb ⊓ [top] ⋅ top ⋅ [F].\nDefinition rs_prime := int ⊔ [top] ⋅ top ⋅ [(R ⊓ W)].\nDefinition rs := mo_0 ⊓ rs_prime ⊓ !((mo_0 ⊓ !rs_prime) ⋅ mo_0).\nDefinition swra := ext ⊓ toid crel ⋅ ((fsb ⊔ 1) ⋅ (toid (A ⊓ W) ⋅ ((rs ⊔ 1) ⋅ (rf ⋅ (toid (R ⊓ A) ⋅ ((sbf ⊔ 1) ⋅ toid cacq)))))).\nDefinition swul := ext ⊓ toid UL ⋅ (lo ⋅ toid LK).\nDefinition pp_asw := asw ⊓ !(asw ⋅ sb).\nDefinition sw := pp_asw ⊔ (swul ⊔ swra).\nDefinition cad := (rf ⊓ sb ⊔ dd)^+.\nDefinition dob := (ext ⊓ toid (W ⊓ crel) ⋅ ((fsb ⊔ 1) ⋅ (toid (A ⊓ W) ⋅ ((rs ⊔ 1) ⋅ (rf ⋅ toid ccon))))) ⋅ (cad ⊔ 1).\nDefinition ithbr := sw ⊔ (dob ⊔ sw ⋅ sb).\nDefinition ithb := (ithbr ⊔ sb ⋅ ithbr)^+.\nDefinition hb := sb ⊔ ithb.\nDefinition Hb := acyclic hb.\nDefinition hbl := hb ⊓ loc.\nDefinition Coh := irreflexive ((rf° ⊔ 1) ⋅ (mo_0 ⋅ ((rf ⊔ 1) ⋅ hb))).\nDefinition vis := hbl ⊓ [W] ⋅ top ⋅ [R] ⊓ !(hbl ⋅ (toid W ⋅ hbl)).\nDefinition Rf := irreflexive (rf ⋅ hb).\nDefinition NaRf := is_empty (rf ⋅ [(R ⊓ !A)] ⊓ !vis).\nDefinition NaRf_0 := is_empty ([(FW ⊓ !A)] ⋅ (hbl ⋅ [W])).\nDefinition Rmw := irreflexive (rf ⊔ (mo_0 ⋅ (mo_0 ⋅ rf°) ⊔ mo_0 ⋅ rf)).\nDefinition Lo1 := irreflexive (lo ⋅ hb).\nDefinition Lo2 := irreflexive (toid LS ⋅ (lo° ⋅ (toid LS ⋅ !(lo ⋅ (toid UL ⋅ lo))))).\nDefinition Mutex := UL ⊔ LS.\nDefinition cnf := ([W] ⋅ top ⋅ [top] ⊔ [top] ⋅ top ⋅ [W]) ⊓ loc ⊓ !([Mutex] ⋅ top ⋅ [top] ⊔ [top] ⋅ top ⋅ [Mutex]).\nDefinition dr := ext ⊓ (cnf ⊓ !hb ⊓ !hb° ⊓ !([A] ⋅ top ⋅ [A])).\nDefinition ur := int ⊓ (([W] ⋅ top ⋅ [M] ⊔ [M] ⋅ top ⋅ [W]) ⊓ (loc ⊓ (!id ⊓ (!sb^+ ⊓ !(sb^+)°)))).\nDefinition bl := toid LS ⋅ ((sb ⊓ lo) ⋅ toid LK) ⊓ !(lo ⋅ (toid UL ⋅ lo)).\nDefinition losbwoul := sb ⊓ (lo ⊓ !(lo ⋅ (toid UL ⋅ lo))).\nDefinition lu := toid UL ⊓ !(toid UL ⋅ (losbwoul° ⋅ (toid LS ⋅ (losbwoul ⋅ toid UL)))).\nDefinition witness_conditions := generate_orders (W ⊓ (A ⊔ I)) mobase mo /\\ generate_orders LS po loLL.\nDefinition model_conditions := Hb /\\ (Coh /\\ (Rf /\\ (NaRf /\\ (NaRf_0 /\\ (Rmw /\\ (Lo1 /\\ Lo2)))))).\nEnd Model.\n\nHint Unfold events R W IW FW B RMW F rf po int ext loc addr data ctrl amo rmw unknown_set unknown_relation M emptyset classes_loc A ACQ ACQ_REL CON I LK LS REL SC UL coi tag2events emptyset_0 partition tag2instrs po_loc rfe rfi co0 toid fencerel ctrlcfence imply nodetour singlestep LKW generate_orders generate_cos mobase moi moe co coe coi_0 fr fri fre crit loLU loUL lo asw sb mo_0 cacq crel ccon fr_0 dd fsb sbf rs_prime rs swra swul pp_asw sw cad dob ithbr ithb hb Hb hbl Coh vis Rf NaRf NaRf_0 Rmw Lo1 Lo2 Mutex cnf dr ur bl losbwoul lu witness_conditions model_conditions : cat.\n\nDefinition valid (c : candidate) :=\n  exists mo loLL : relation (events c),\n    witness_conditions c mo loLL /\\\n    model_conditions c mo loLL.\n\n(* End of translation of model C++11 *)\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/models/c11_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22375061363105778}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*              Layers of VMM                                          *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file defines the abstract data and the primitives for the MALInit layer, which will introduce the abstract allocation table*)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import LoadStoreSem1.\nRequire Import ObservationImpl.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\nRequire Import LayerCalculusLemma.\n\nRequire Import AbstractDataType.\n\nRequire Export ObjCPU.\nRequire Export ObjMM.\nRequire Export ObjFlatMem.\nRequire Export ObjPMM.\n\nSection WITHMEM.\n\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n\n  (** * Raw Abstract Data*)\n  (*Record RData :=\n    mkRData {\n        HP: flatmem; (**r we model the memory from 1G to 3G as heap*)\n        MM: MMTable; (**r table of the physical memory's information*)\n        MMSize: Z; (**r size of MMTable*)\n        CR3: globalpointer; (**r abstract of CR3, stores the pointer to page table*)          \n        ti: trapinfo; (**r abstract of CR2, stores the address where page fault happens*)\n        pg: bool; (**r abstract of CR0, indicates whether the paging is enabled or not*)\n        ikern: bool; (**r pure logic flag, shows whether it's in kernel mode or not*)\n        ihost: bool; (**r logic flag, shows whether it's in the host mode or not*)         \n        AT: ATable; (**r allocation table*)\n        nps: Z; (**r number of the pages*)\n        init: bool (**r pure logic flag, show whether the initialization at this layer has been called or not*)\n      }.*)\n\n  (** ** Invariants at this layer *)\n  Record high_level_invariant (abd: RData) :=\n    mkInvariant {\n        valid_kern: ikern abd = false -> pg abd = true /\\ init abd = true;\n        valid_mm: init abd = true -> MM_valid (MM abd) (MMSize abd);\n        correct_mm: init abd = true -> MM_correct (MM abd) (MMSize abd);\n        valid_mm_kern: init abd = true -> MM_kern (MM abd) (MMSize abd);\n        valid_mm_size: init abd = true -> 0 < MMSize abd <= Int.max_unsigned;\n        valid_CR3: pg abd = true -> CR3_valid (CR3 abd);\n        valid_ihost: ihost abd = false -> pg abd = true /\\ init abd = true /\\ ikern abd = true\n      }.\n\n  (** ** Definition of the abstract state ops *)\n  Global Instance malinit_data_ops : CompatDataOps RData :=\n    {\n      empty_data := init_adt;\n      high_level_invariant := high_level_invariant;\n      low_level_invariant := low_level_invariant;\n      kernel_mode adt := ikern adt = true /\\ ihost adt = true;\n      observe := ObservationImpl.observe\n    }.\n\n  (** ** Proofs that the initial abstract_data should satisfy the invariants*)    \n  Section Property_Abstract_Data.\n\n    Lemma empty_data_high_level_invariant:\n      high_level_invariant init_adt.\n    Proof.\n      constructor; auto; simpl; try discriminate 1.\n    Qed.\n\n    (** ** Definition of the abstract state *)\n    Global Instance malinit_data_prf : CompatData RData.\n    Proof.\n      constructor.\n      - apply low_level_invariant_incr.\n      - apply empty_data_low_level_invariant.\n      - apply empty_data_high_level_invariant.\n    Qed.\n\n  End Property_Abstract_Data.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  (** * Proofs that the primitives satisfies the invariants at this layer *)\n  Section INV.\n\n    Global Instance setPG_inv: PreservesInvariants setPG0_spec.\n    Proof. \n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n    Qed.\n\n    Global Instance clearCR2_inv: PreservesInvariants clearCR2_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n    Qed.\n\n    Global Instance set_nps_inv: PreservesInvariants set_nps_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n    Qed.\n\n    Global Instance set_at_u_inv: PreservesInvariants set_at_u_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n    Qed.\n\n    Global Instance set_at_norm_inv: PreservesInvariants set_at_norm_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n    Qed. \n\n    Global Instance set_at_c_inv: PreservesInvariants set_at_c_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n    Qed.\n\n    Global Instance setCR3_inv: SetCR3Invariants setCR30_spec.\n    Proof.\n      constructor; intros; functional inversion H.\n      - inv H0; constructor; trivial.\n      - inv H0; constructor; auto.\n      - assumption.\n    Qed.\n\n    Global Instance bootloader0_inv: PreservesInvariants bootloader0_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant.\n      - apply real_valid_mm.\n      - apply real_correct_mm.\n      - apply real_valid_mm_kern.\n      - apply real_valid_mm_size.\n    Qed.\n\n    Global Instance trapin_inv: PrimInvariants trapin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance trapout_inv: PrimInvariants trapout0_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance hostin_inv: PrimInvariants hostin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance hostout_inv: PrimInvariants hostout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance fstore_inv: PreservesInvariants fstore'_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n    Qed.\n\n    Global Instance flatmem_copy_inv: PreservesInvariants flatmem_copy'_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto.      \n    Qed.\n\n    Global Instance device_output_inv: PreservesInvariants device_output_spec.\n    Proof. \n      preserves_invariants_simpl'' low_level_invariant high_level_invariant; auto.\n    Qed.\n\n  End INV.\n\n  (** * Specification of primitives that will be implemented at this layer*)\n  Definition exec_loadex {F V} := exec_loadex1 (F := F) (V := V).\n\n  Definition exec_storeex {F V} := exec_storeex1 (flatmem_store:= flatmem_store') (F := F) (V := V).\n\n  Global Instance flatmem_store_inv: FlatmemStoreInvariant (flatmem_store:= flatmem_store').\n  Proof.\n    split; inversion 1; intros. \n    - functional inversion H0; constructor; auto.\n    - functional inversion H1; constructor; auto.\n  Qed.\n\n  Global Instance trapinfo_set_inv: TrapinfoSetInvariant.\n  Proof.\n    split; inversion 1; intros; constructor; auto.\n  Qed.\n\n  (** * Layer Definition *)\n  (** ** Layer Definition viewed at C level  *)\n\n  (** ** Layer Definition newly introduced  *)\n  Definition malinit_fresh: compatlayer (cdata RData) :=\n    (at_get ↦ gensem get_at_u_spec\n            ⊕ is_norm ↦ gensem is_at_norm_spec\n            ⊕ at_get_c ↦ gensem get_at_c_spec\n            ⊕ at_set ↦ gensem set_at_u_spec\n            ⊕ set_norm ↦ gensem set_at_norm_spec\n            ⊕ at_set_c ↦ gensem set_at_c_spec)\n      ⊕ (set_nps ↦ gensem set_nps_spec\n                 ⊕ get_nps ↦ gensem get_nps_spec).\n\n  (** ** Layer Definition passthrough  *)\n  Definition malinit_passthrough: compatlayer (cdata RData) :=\n    fload ↦ gensem fload'_spec\n          ⊕ fstore ↦ gensem fstore'_spec\n          ⊕ flatmem_copy ↦ gensem flatmem_copy'_spec\n          ⊕ vmxinfo_get ↦ gensem vmxinfo_get_spec\n          ⊕ device_output ↦ gensem device_output_spec\n          ⊕ get_size ↦ gensem MMSize\n          ⊕ is_usable ↦ gensem is_mm_usable_spec\n          ⊕ get_mms ↦ gensem get_mm_s_spec\n          ⊕ get_mml ↦ gensem get_mm_l_spec\n          ⊕ boot_loader ↦ gensem bootloader0_spec\n          ⊕ set_pg ↦ gensem setPG0_spec\n          ⊕ clear_cr2 ↦ gensem clearCR2_spec\n          ⊕ set_cr3 ↦ setCR3_compatsem setCR30_spec\n          ⊕ trap_in ↦ primcall_general_compatsem trapin_spec\n          ⊕ trap_out ↦ primcall_general_compatsem trapout0_spec\n          ⊕ host_in ↦ primcall_general_compatsem hostin_spec\n          ⊕ host_out ↦ primcall_general_compatsem hostout_spec\n          ⊕ trap_get ↦ primcall_trap_info_get_compatsem trap_info_get_spec\n          ⊕ trap_set ↦ primcall_trap_info_ret_compatsem trap_info_ret_spec\n          ⊕ accessors ↦ {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.\n\n  (** ** Layer Definition *)\n  Definition malinit : compatlayer (cdata RData) := malinit_fresh ⊕ malinit_passthrough.\n\n  (*Definition semantics := LAsm.Lsemantics malinit.\n\n  Section Linking.\n\n    Definition malinit_c : compatlayer (cdata RData) :=\n    fload ↦ gensem (fun n d => fload_spec d n)\n          ⊕ fstore ↦ gensem (fun a b d => fstore_spec d a b)\n          ⊕ get_size ↦ gensem MMSize\n          ⊕ is_usable ↦ gensem (fun n d => is_mm_usable_spec d n)\n          ⊕ get_mms ↦ gensem (fun n d => get_mm_s_spec d n)\n          ⊕ get_mml ↦ gensem (fun n d => get_mm_l_spec d n)\n          ⊕ boot_loader ↦ gensem (fun n d => bootloader_spec d n)   \n          ⊕ set_pg ↦ gensem (fun d => setPG_spec d)\n          ⊕ set_cr3 ↦ setCR3_compatsem setCR3_spec\n          ⊕ at_get ↦ gensem (fun n d => get_at_u_spec d n)\n          ⊕ is_norm ↦ gensem (fun n d => is_at_norm_spec d n)\n          ⊕ at_get_c ↦ gensem (fun n d => get_at_c_spec d n)\n          ⊕ at_set ↦ gensem (fun n b d => set_at_u_spec d n b)\n          ⊕ set_norm ↦ gensem (fun n b d => set_at_norm_spec d n b)\n          ⊕ at_set_c ↦ gensem (fun n b d => set_at_c_spec d n b)\n          ⊕ set_nps ↦ gensem (fun n d => set_nps_spec d n)\n          ⊕ get_nps ↦ gensem (fun d => get_nps_spec d).\n\n    Definition malinit_asm : compatlayer (cdata RData) :=\n      trap_in ↦ primcall_general_compatsem trapin_spec\n              ⊕ trap_out ↦ primcall_general_compatsem trapout_spec\n              ⊕ host_in ↦ primcall_general_compatsem hostin_spec\n              ⊕ host_out ↦ primcall_general_compatsem hostout_spec\n              ⊕ trap_get ↦ primcall_trap_info_get_compatsem trap_info_get_spec\n              ⊕ trap_set ↦ primcall_trap_info_ret_compatsem trap_info_ret_spec\n              ⊕ accessors ↦ {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.\n\n    Lemma link_c_impl:\n      malinit_c ≤ malinit.\n    Proof.\n      apply (layer_le_trans malinit_asm).\n      reflexivity.\n    Qed.\n\n  End Linking.*)\n\nEnd WITHMEM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/MALInit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.2236577712582944}}
{"text": "Require Import Coq.Bool.Bool.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\n\nRequire Import Helix.FSigmaHCOL.FSigmaHCOL.\nRequire Import Helix.FSigmaHCOL.Int64asNT.\nRequire Import Helix.FSigmaHCOL.Float64asCT.\nRequire Import Helix.LLVMGen.Utils.\nRequire Import Helix.Util.Misc.\nRequire Import Helix.Tactics.HelixTactics.\n\nRequire Import Vellvm.Semantics.IntrinsicsDefinitions.\nRequire Import Vellvm.Utils.Util.\nRequire Import Vellvm.Numeric.Floats.\nRequire Import Vellvm.Semantics.TopLevel.\nRequire Import Vellvm.Syntax.LLVMAst.\nRequire Import Helix.Util.ErrorSetoid.\n\nRequire Import Flocq.IEEE754.Binary.\nRequire Import Flocq.IEEE754.Bits.\n\nRequire Import Coq.Numbers.BinNums. (* for Z scope *)\nRequire Import Coq.ZArith.BinInt.\nFrom Coq Require Import ZArith.\n\nRequire Import ExtLib.Structures.Monads.\nRequire Import Helix.Util.ErrorWithState.\nRequire Import Helix.LLVMGen.Data.\n\nImport ListNotations.\nImport MonadNotation.\nOpen Scope monad_scope.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nImport FHCOL.\n\n(* Both [String] and [List] define [(++)] notation. We use both.\n   To avoid implicit scoping, we re-define one for String *)\nNotation \"x @@ y\" := (String.append x y) (right associativity, at level 60) : string_scope.\n\nSection withErrorStateMonad.\n\n  Record IRState :=\n    mkIRState\n      {\n        block_count: nat ;\n        local_count: nat ;\n        void_count : nat ;\n        Γ: list (ident * typ)\n      }.\n\n  Definition newState: IRState :=\n    {|\n      block_count := 0 ;\n      local_count := 0 ;\n      void_count  := 0 ;\n      Γ := []\n    |}.\n\n  Definition cerr := errS IRState.\n\n  Definition setVars (s:IRState) (newvars:list (ident * typ)): IRState :=\n    {|\n      block_count := block_count s ;\n      local_count := local_count s ;\n      void_count  := void_count s ;\n      Γ := newvars\n    |}.\n\n  (* Returns n-th varable from state or error if [n] index oob *)\n  Definition getStateVar (msg:string) (n:nat): cerr (ident * typ) :=\n    st <- get ;;\n    option2errS msg (List.nth_error (Γ st) n).\n\n  (* for debugging and error reporting *)\n  Definition getVarsAsString : cerr string :=\n    st <- get ;;\n    ret (string_of_Γ (Γ st)).\n\n  Definition nat_eq_or_cerr msg a b : cerr _ := err2errS (nat_eq_or_err msg a b).\n  Definition Z_eq_or_cerr msg a b : cerr _ := err2errS (Z_eq_or_err msg a b).\n  Definition Int64_eq_or_cerr msg a b : cerr _ := Z_eq_or_cerr msg\n                                                               (Int64.intval a)\n                                                               (Int64.intval b).\n\n  Definition evalCErrS {St:Type} {A:Type} (c : errS St A) (initial : St) : cerr A :=\n    match c initial with\n    | inl msg => raise msg\n    | inr (s,v) => ret v\n    end.\n\nEnd withErrorStateMonad.\n\n(* 64-bit IEEE floats *)\nDefinition SizeofFloatT: nat := 8.\n\nDefinition getIRType (t: DSHType): typ :=\n  match t with\n  | DSHnat => IntType\n  | DSHCType => TYPE_Double\n  | DSHPtr n => TYPE_Array (Z.to_N (Int64.intval n)) TYPE_Double\n  end.\n\nDefinition add_comments (b:block typ) (xs:list string): block typ :=\n  {|\n    blk_id    := blk_id b;\n    blk_phis  := blk_phis b;\n    blk_code  := blk_code b;\n    blk_term  := blk_term b;\n    blk_comments := match blk_comments b with\n                    | None => Some xs\n                    | Some ys => Some (ys++xs)\n                    end\n  |}.\n\nDefinition add_comment (bs:list (block typ)) (xs:list string): list (block typ) :=\n  match bs with\n  | nil => nil\n  | b::bs => (add_comments b xs)::bs\n  end.\n\nDefinition incBlockNamed (prefix:string): (cerr block_id) :=\n  st <- get  ;;\n  put\n    {|\n      block_count := S (block_count st);\n      local_count := local_count st ;\n      void_count := void_count st ;\n      Γ := Γ st\n    |} ;;\n  ret (Name (prefix ++ string_of_nat (block_count st))).\n\nDefinition incBlock := incBlockNamed \"b\".\n\nDefinition incLocalNamed (prefix:string): (cerr raw_id) :=\n  st <- get ;;\n  put\n    {|\n      block_count := block_count st ;\n      local_count := S (local_count st) ;\n      void_count  := void_count st ;\n      Γ := Γ st\n    |} ;;\n  ret (Name (prefix @@ string_of_nat (local_count st))).\n\nDefinition incLocal := incLocalNamed \"l\".\n\nDefinition incVoid: (cerr int) :=\n  st <- get ;;\n  put\n    {|\n      block_count := block_count st ;\n      local_count := local_count st ;\n      void_count  := S (void_count st) ;\n      Γ := Γ st\n    |} ;;\n  ret (Z.of_nat (void_count st)).\n\nDefinition addVars (newvars: list (ident * typ)): cerr unit :=\n  st <- get ;;\n  put\n    {|\n      block_count := block_count st ;\n      local_count := local_count st ;\n      void_count  := void_count st ;\n      Γ := newvars ++ Γ st\n    |}.\n\nDefinition newLocalVar (t:typ) (prefix:string): (cerr raw_id) :=\n  st <- get ;;\n  let v := Name (prefix @@ string_of_nat (local_count st)) in\n  put\n    {|\n      block_count := block_count st ;\n      local_count := S (local_count st) ;\n      void_count  := void_count st ;\n      Γ := [(ID_Local v,t)] ++ (Γ st)\n    |} ;;\n  ret v.\n\nDefinition intrinsic_exp (d:declaration typ): exp typ :=\n  EXP_Ident (ID_Global (dc_name d)).\n\n(* TODO: move *)\nFixpoint drop_err {A:Type} (n:nat) (lst:list A) : err (list A)\n  := match n, lst with\n     | O, xs => ret xs\n     | S n', (_::xs) => drop_err n' xs\n     | _, _ => raise \"drop on empty list\"\n     end.\n\nDefinition dropVars (n: nat): cerr unit :=\n  st <- get ;;\n  Γ' <- err2errS (drop_err n (Γ st)) ;;\n  put {|\n      block_count := block_count st ;\n      local_count := local_count st ;\n      void_count  := void_count st ;\n      Γ := Γ'\n    |}.\n\nDefinition swap_err {A:Type} (lst:list A) : err (list A)\n  := match lst with\n     | (x :: y :: xs) => ret (y :: x :: xs)\n     | _ => raise \"drop on empty list\"\n     end.\n\n(* Swap top most elements on list. Used in IMapLoopBody *)\nDefinition swapVars : cerr unit :=\n  st <- get ;;\n  Γ' <- err2errS (swap_err (Γ st)) ;;\n  put {|\n      block_count := block_count st ;\n      local_count := local_count st ;\n      void_count  := void_count st ;\n      Γ := Γ'\n    |}.\n\nDefinition allocTempArrayCode (name: local_id) (size:Int64.int)\n  :=\n    [(IId name, INSTR_Alloca (getIRType (DSHPtr size)) None (Some PtrAlignment))].\n\nDefinition allocTempArrayBlock\n           (name: local_id)\n           (nextblock: block_id)\n           (size: Int64.int): (cerr (local_id * (block typ)))\n  :=\n    bid <- incBlock ;;\n    ret (bid,\n         {|\n           blk_id    := bid ;\n           blk_phis  := [];\n           blk_code  := allocTempArrayCode name size;\n           blk_term  := TERM_Br_1 nextblock ;\n           blk_comments := None\n         |}).\n\nFixpoint genNExpr\n         (nexp: NExpr) :\n  cerr ((exp typ) * (code typ))\n  :=\n    let gen_binop a b iop :=\n        '(aexp, acode) <- genNExpr a ;;\n        '(bexp, bcode) <- genNExpr b ;;\n        res <- incLocal ;;\n        ret (EXP_Ident (ID_Local res),\n             acode ++ bcode ++\n                   [(IId res, INSTR_Op (OP_IBinop iop\n                                                  IntType\n                                                  aexp\n                                                  bexp))\n            ]) in\n    match nexp with\n    | NVar n => '(i,t) <- getStateVar \"NVar out of range\" n ;;\n                match t, IntType with\n                | TYPE_I z, TYPE_I zi =>\n                  if BinNat.N.eq_dec z zi then\n                    ret (EXP_Ident i, [])\n                  else\n                    (sΓ <- getVarsAsString ;;\n                     raise (\"NVar #\" @@ string_of_nat n @@ \" dimensions mismatch in \" @@ sΓ))\n                | TYPE_Pointer (TYPE_I z), TYPE_I zi =>\n                  if BinNat.N.eq_dec z zi then\n                    res <- incLocal ;;\n                    ret (EXP_Ident (ID_Local res),\n                         [(IId res, INSTR_Load false (IntType)\n                                               (TYPE_Pointer (IntType),\n                                                (EXP_Ident i))\n                                               (ret 8%Z))])\n                  else\n                    (sΓ <- getVarsAsString ;;\n                     raise (\"NVar #\" @@ string_of_nat n @@ \" pointer type mismatch in \" @@ sΓ))\n                | _,_ =>\n                  sΓ <- getVarsAsString ;;\n                  raise (\"NVar #\" @@ string_of_nat n @@ \" type mismatch in \" @@ sΓ)\n                end\n    | NConst v => ret (EXP_Integer (Int64.intval v), [])\n    | NDiv   a b => gen_binop a b (UDiv false)\n    | NMod   a b => gen_binop a b URem\n    | NPlus  a b => gen_binop a b (Add false false)\n    | NMinus a b => gen_binop a b (Sub false false)\n    | NMult  a b => gen_binop a b (Mul false false)\n    | NMin   a b => raise \"NMin not implemented\" (* TODO *)\n    | NMax   a b => raise \"NMax not implemented\" (* TODO *)\n    end.\n\nDefinition genMExpr\n           (mexp: MExpr)\n  :\n    cerr ((exp typ) * (code typ) * typ)\n  := match mexp with\n     | MPtrDeref (PVar x) => '(i,t) <- getStateVar \"PVar un MPtrDeref out of range\" x ;;\n                             match t with\n                             | TYPE_Pointer (TYPE_Array zi TYPE_Double) =>\n                               ret (EXP_Ident i, [], (TYPE_Array zi TYPE_Double))\n                             | _  =>\n                               sΓ <- getVarsAsString ;;\n                               raise (\"MPtrDeref's PVar #\" @@ string_of_nat x @@ \" type mismatch in \" @@ sΓ)\n                             end\n     | MConst _ _ => raise \"MConst not implemented\" (* TODO *)\n     end.\n\nFixpoint genAExpr\n         (fexp: AExpr) :\n  cerr ((exp typ) * (code typ))\n  :=\n    let gen_binop a b fop :=\n        '(aexp, acode) <- genAExpr a ;;\n        '(bexp, bcode) <- genAExpr b ;;\n        res <- incLocal ;;\n        ret (EXP_Ident (ID_Local res),\n             acode ++ bcode ++\n                   [(IId res, INSTR_Op (OP_FBinop fop\n                                                  [] (* TODO: list fast_math *)\n                                                  TYPE_Double\n                                                  aexp\n                                                  bexp))\n            ]) in\n    let gen_call1 a f :=\n        '(aexp, acode) <- genAExpr a ;;\n        res <- incLocal ;;\n        let ftyp := TYPE_Double in\n        ret (EXP_Ident (ID_Local res),\n             acode ++\n                   [(IId res, INSTR_Call (ftyp,f) [(ftyp,aexp)])\n            ]) in\n    let gen_call2 a b f :=\n        '(aexp, acode) <- genAExpr a ;;\n        '(bexp, bcode) <- genAExpr b ;;\n        res <- incLocal ;;\n        let ftyp := TYPE_Double in\n        ret (EXP_Ident (ID_Local res),\n             acode ++ bcode ++\n                   [(IId res, INSTR_Call (ftyp,f)\n                                         [(ftyp,aexp); (ftyp,bexp)])\n            ]) in\n    match fexp with\n    | AVar n => '(i,t) <- getStateVar \"AVar out of range\" n ;;\n                match t with\n                | TYPE_Double => ret (EXP_Ident i, [])\n                | TYPE_Pointer TYPE_Double =>\n                  res <- incLocal ;;\n                  ret (EXP_Ident (ID_Local res),\n                       [(IId res, INSTR_Load false TYPE_Double\n                                             (TYPE_Pointer TYPE_Double,\n                                              (EXP_Ident i))\n                                             (ret 8%Z))])\n                | _ =>\n                  sΓ <- getVarsAsString ;;\n                  raise (\"AVar #\" @@ string_of_nat n @@ \" type mismatch in \" @@ sΓ)\n                end\n    | AConst v => ret (EXP_Double v, [])\n    | ANth vec i =>\n      '(iexp, icode) <- genNExpr i ;;\n      '(vexp, vcode, xtyp) <- genMExpr vec ;;\n      px <- incLocal ;;\n      let xptyp := TYPE_Pointer xtyp in\n      res <- incLocal ;;\n      ret (EXP_Ident (ID_Local res),\n           icode ++ vcode ++\n                 [\n                   (IId px,  INSTR_Op (OP_GetElementPtr\n                                         xtyp (xptyp, vexp)\n                                         [(IntType, EXP_Integer 0%Z);\n                                            (IntType, iexp)]\n\n                   )) ;\n                     (IId res, INSTR_Load false TYPE_Double\n                                          (TYPE_Pointer TYPE_Double,\n                                           (EXP_Ident (ID_Local px)))\n                                          (ret 8%Z))\n          ])\n    | AAbs a => gen_call1 a (intrinsic_exp fabs_64_decl)\n    | APlus a b => gen_binop a b FAdd\n    | AMinus a b => gen_binop a b FSub\n    | AMult a b => gen_binop a b FMul\n    | AMin a b => gen_call2 a b (intrinsic_exp minimum_64_decl)\n    | AMax a b => gen_call2 a b (intrinsic_exp maxnum_64_decl)\n    | AZless a b =>\n      (* this is special as requires bool -> double cast *)\n      '(aexp, acode) <- genAExpr a ;;\n      '(bexp, bcode) <- genAExpr b ;;\n      ires <- incLocal ;;\n      fres <- incLocal ;;\n      void0 <- incVoid ;;\n      ret (EXP_Ident (ID_Local fres),\n           acode ++ bcode ++\n                 [(IId ires, INSTR_Op (OP_FCmp FOlt\n                                               TYPE_Double\n                                               aexp\n                                               bexp));\n                    (IVoid void0, INSTR_Comment \"Casting bool to float\") ;\n                    (IId fres, INSTR_Op (OP_Conversion\n                                           Uitofp\n                                           (TYPE_I 1%N)\n                                           (EXP_Ident (ID_Local ires))\n                                           TYPE_Double))\n          ])\n    end.\n\n(* List of blocks with entry point *)\nDefinition segment:Type := block_id * list (block typ).\n\nDefinition genFSHAssign\n           (i o: Int64.int)\n           (x y: ident)\n           (src dst: NExpr)\n           (nextblock: block_id)\n  : cerr segment\n  :=\n    entryblock <- incBlockNamed \"Assign\" ;;\n    storeid <- incVoid ;;\n    px <- incLocal ;;\n    py <- incLocal ;;\n    v <- incLocal ;;\n    let xtyp := getIRType (DSHPtr i) in\n    let xptyp := TYPE_Pointer xtyp in\n    let ytyp := getIRType (DSHPtr o) in\n    let yptyp := TYPE_Pointer ytyp in\n    '(src_nexpr, src_nexpcode) <- genNExpr src  ;;\n    '(dst_nexpr, dst_nexpcode) <- genNExpr dst  ;;\n    ret (entryblock, [\n           {|\n             blk_id    := entryblock ;\n             blk_phis  := [];\n             blk_code  := src_nexpcode ++ dst_nexpcode ++ [\n                                         (IId px,  INSTR_Op (OP_GetElementPtr\n                                                               xtyp (xptyp, (EXP_Ident x))\n                                                               [(IntType, EXP_Integer 0%Z);\n                                                                  (IntType, src_nexpr)]\n\n                                         )) ;\n                                           (IId v, INSTR_Load false TYPE_Double\n                                                              (TYPE_Pointer TYPE_Double,\n                                                               (EXP_Ident (ID_Local px)))\n                                                              (ret 8%Z));\n\n                                           (IId py,  INSTR_Op (OP_GetElementPtr\n                                                                 ytyp (yptyp, (EXP_Ident y))\n                                                                 [(IntType, EXP_Integer 0%Z);\n                                                                    (IntType, dst_nexpr)]\n\n                                           ));\n\n                                           (IVoid storeid, INSTR_Store false\n                                                                       (TYPE_Double, (EXP_Ident (ID_Local v)))\n                                                                       (TYPE_Pointer TYPE_Double,\n                                                                        (EXP_Ident (ID_Local py)))\n                                                                       (ret 8%Z))\n\n                                       ];\n             blk_term  := TERM_Br_1 nextblock;\n             blk_comments := None\n           |}\n        ]).\n\n(* Generates while loop `init_code(); i=from; while(i<to){ body(); i++;}`\n\n    .entry:\n      (init_code)\n      %c0 = icmp ult i32 %start, %n\n      br i1 %c0, label %.loop, label %.nextblock\n    .loop:\n      %i = phi i32 [ %next_i, .loopcontblock], [ %start, .entry ]\n     (body)\n    .loopcontblock:\n      %next_i = add nsw i32 %i, 1\n      %c = icmp ult i32 %next_i, %n\n      br i1 %c, label %.loop, label nextblock\n    nextblock:\n *)\nDefinition genWhileLoop\n           (prefix: string)\n           (from to: exp typ)\n           (loopvar: raw_id)\n           (loopcontblock: block_id)\n           (body_entry: block_id)\n           (body_blocks: list (block typ))\n           (init_code: (code typ))\n           (nextblock: block_id)\n  : cerr segment\n  :=\n    entryblock <- incBlockNamed (prefix @@ \"_entry\") ;;\n    loopblock <- incBlockNamed (prefix @@ \"_loop\") ;;\n    loopcond <- incLocal ;;\n    loopcond1 <- incLocal ;;\n    nextvar <- incLocalNamed (prefix @@ \"_next_i\") ;;\n\n    (* Not strictly necessary to split loop blocks, but for\n        readability it is nice to have body in-place inside the\n        loop *)\n    let loop_pre := [\n          {|\n            blk_id    := entryblock ;\n            blk_phis  := [];\n            blk_code  :=\n              init_code ++\n                        [\n                          (IId loopcond, INSTR_Op (OP_ICmp Ult\n                                                           IntType\n                                                           from\n                                                           to))\n\n                        ];\n            blk_term  := TERM_Br (TYPE_I 1%N, EXP_Ident (ID_Local loopcond)) loopblock nextblock;\n            blk_comments := None\n          |} ;\n\n            {|\n              blk_id    := loopblock ;\n              blk_phis  := [(loopvar, Phi IntType [(entryblock, from); (loopcontblock, EXP_Ident (ID_Local nextvar))])];\n              blk_code  := [];\n              blk_term  := TERM_Br_1 body_entry;\n              blk_comments := None\n            |}\n        ] in\n    let loop_post := [\n          {|\n            blk_id    := loopcontblock;\n            blk_phis  := [];\n            blk_code  := [\n                          (IId nextvar, INSTR_Op (OP_IBinop (Add false false)\n                                                            IntType\n                                                            (EXP_Ident (ID_Local loopvar))\n                                                            (EXP_Integer 1%Z))) ;\n                            (IId loopcond1, INSTR_Op (OP_ICmp Ult\n                                                              IntType\n                                                              (EXP_Ident (ID_Local nextvar))\n                                                              to))\n\n                        ];\n            blk_term  := TERM_Br (TYPE_I 1%N, EXP_Ident (ID_Local loopcond1)) loopblock nextblock;\n            blk_comments := None\n          |}\n        ] in\n    ret (entryblock, loop_pre ++ body_blocks ++ loop_post).\n\nDefinition genIMapBody\n           (i o: Int64.int)\n           (x y: ident)\n           (f: AExpr)\n           (loopvar: raw_id)\n           (nextblock: block_id)\n  : cerr segment\n  :=\n    pwblock <- incBlockNamed \"IMapLoopBody\" ;;\n    storeid <- incVoid ;;\n    px <- incLocal ;;\n    py <- incLocal ;;\n    v <- incLocal ;;\n    let xtyp := getIRType (DSHPtr i) in\n    let ytyp := getIRType (DSHPtr o) in\n    let xptyp := TYPE_Pointer xtyp in\n    let yptyp := TYPE_Pointer ytyp in\n    let loopvarid := ID_Local loopvar in\n    addVars [(ID_Local v, TYPE_Double)];;\n    (* swapVars ;; *)\n    '(fexpr, fexpcode) <- genAExpr f ;;\n    dropVars 1 ;;\n    ret (pwblock,\n         [\n           {|\n             blk_id    := pwblock ;\n             blk_phis  := [];\n             blk_code  := [\n                           (IId px,  INSTR_Op (OP_GetElementPtr\n                                                 xtyp (xptyp, (EXP_Ident x))\n                                                 [(IntType, EXP_Integer 0%Z);\n                                                    (IntType,(EXP_Ident loopvarid))]\n\n                           ));\n\n                             (IId v, INSTR_Load false TYPE_Double\n                                                (TYPE_Pointer TYPE_Double,\n                                                 (EXP_Ident (ID_Local px)))\n                                                (ret 8%Z))\n                         ]\n\n                            ++ fexpcode ++\n\n                            [ (IId py,  INSTR_Op (OP_GetElementPtr\n                                                    ytyp (yptyp, (EXP_Ident y))\n                                                    [(IntType, EXP_Integer 0%Z);\n                                                       (IntType,(EXP_Ident loopvarid))]\n\n                              ));\n\n                                (IVoid storeid, INSTR_Store false\n                                                            (TYPE_Double, fexpr)\n                                                            (TYPE_Pointer TYPE_Double,\n                                                             (EXP_Ident (ID_Local py)))\n                                                            (ret 8%Z))\n\n\n                            ];\n             blk_term  := TERM_Br_1 nextblock;\n             blk_comments := None\n           |}\n        ]).\n\nDefinition genBinOpBody\n           (i o: Int64.int)\n           (n: nat)\n           (x y: ident)\n           (f: AExpr)\n           (loopvar: raw_id)\n           (nextblock: block_id)\n  : cerr segment\n  :=\n    binopblock <- incBlockNamed \"BinOpLoopBody\" ;;\n    storeid <- incVoid ;;\n    loopvar2 <- incLocal ;;\n    px0 <- incLocal ;;\n    px1 <- incLocal ;;\n    py <- incLocal ;;\n    v0 <- incLocal ;;\n    v1 <- incLocal ;;\n    n' <- err2errS (MInt64asNT.from_nat n) ;;\n    let xtyp := getIRType (DSHPtr i) in\n    let xptyp := TYPE_Pointer xtyp in\n    let ytyp := getIRType (DSHPtr o) in\n    let yptyp := TYPE_Pointer ytyp in\n    let loopvarid := ID_Local loopvar in\n    addVars [(ID_Local v1, TYPE_Double); (ID_Local v0, TYPE_Double); (loopvarid, IntType)] ;;\n    '(fexpr, fexpcode) <- genAExpr f ;;\n    dropVars 3 ;;\n    ret (binopblock,\n         [\n           {|\n             blk_id    := binopblock ;\n             blk_phis  := [];\n             blk_code  := [\n                           (IId px0,  INSTR_Op (OP_GetElementPtr\n                                                  xtyp (xptyp, (EXP_Ident x))\n                                                  [(IntType, EXP_Integer 0%Z);\n                                                     (IntType,(EXP_Ident loopvarid))]\n\n                           ));\n\n                             (IId v0, INSTR_Load false TYPE_Double\n                                                 (TYPE_Pointer TYPE_Double,\n                                                  (EXP_Ident (ID_Local px0)))\n                                                 (ret 8%Z));\n\n                             (IId loopvar2, INSTR_Op (OP_IBinop (Add false false)\n                                                                IntType\n                                                                (EXP_Ident loopvarid)\n                                                                (EXP_Integer (Z.of_nat n))));\n\n\n                             (IId px1,  INSTR_Op (OP_GetElementPtr\n                                                    xtyp (xptyp, (EXP_Ident x))\n                                                    [(IntType, EXP_Integer 0%Z);\n                                                       (IntType,(EXP_Ident (ID_Local loopvar2)))]\n\n                             ));\n\n                             (IId v1, INSTR_Load false TYPE_Double\n                                                 (TYPE_Pointer TYPE_Double,\n                                                  (EXP_Ident (ID_Local px1)))\n                                                 (ret 8%Z))\n                         ]\n\n\n                            ++ fexpcode ++\n\n                            [ (IId py,  INSTR_Op (OP_GetElementPtr\n                                                    ytyp (yptyp, (EXP_Ident y))\n                                                    [(IntType, EXP_Integer 0%Z);\n                                                       (IntType, (EXP_Ident loopvarid))]\n\n                              ));\n\n                                (IVoid storeid, INSTR_Store false\n                                                            (TYPE_Double, fexpr)\n                                                            (TYPE_Pointer TYPE_Double,\n                                                             (EXP_Ident (ID_Local py)))\n                                                            (ret 8%Z))\n\n\n                            ];\n             blk_term  := TERM_Br_1 nextblock;\n             blk_comments := None\n           |}\n        ]).\n\nDefinition genMemMap2Body\n           (i0 i1 o: Int64.int)\n           (x0 x1 y: ident)\n           (f: AExpr)\n           (loopvar: raw_id)\n           (nextblock: block_id)\n  : cerr segment\n  :=\n    binopblock <- incBlockNamed \"MemMapTwoLoopBody\" ;;\n    storeid <- incVoid ;;\n    px0 <- incLocal ;;\n    px1 <- incLocal ;;\n    py <- incLocal ;;\n    v0 <- incLocal ;;\n    v1 <- incLocal ;;\n    let x0typ := getIRType (DSHPtr i0) in\n    let x1typ := getIRType (DSHPtr i1) in\n    let ytyp := getIRType (DSHPtr o) in\n    let x0ptyp := TYPE_Pointer x0typ in\n    let x1ptyp := TYPE_Pointer x1typ in\n    let yptyp := TYPE_Pointer ytyp in\n    let loopvarid := ID_Local loopvar in\n    addVars [(ID_Local v1, TYPE_Double); (ID_Local v0, TYPE_Double)] ;;\n    '(fexpr, fexpcode) <- genAExpr f ;;\n    dropVars 2 ;;\n    ret (binopblock,\n         [\n           {|\n             blk_id    := binopblock ;\n             blk_phis  := [];\n             blk_code  := [\n                           (IId px0,  INSTR_Op (OP_GetElementPtr\n                                                  x0typ (x0ptyp, (EXP_Ident x0))\n                                                  [(IntType, EXP_Integer 0%Z);\n                                                     (IntType,(EXP_Ident loopvarid))]\n\n                           ));\n\n                             (IId v0, INSTR_Load false TYPE_Double\n                                                 (TYPE_Pointer TYPE_Double,\n                                                  (EXP_Ident (ID_Local px0)))\n                                                 (ret 8%Z));\n\n                             (IId px1,  INSTR_Op (OP_GetElementPtr\n                                                    x1typ (x1ptyp, (EXP_Ident x1))\n                                                    [(IntType, EXP_Integer 0%Z);\n                                                       (IntType,(EXP_Ident (ID_Local loopvar)))]\n\n                             ));\n\n                             (IId v1, INSTR_Load false TYPE_Double\n                                                 (TYPE_Pointer TYPE_Double,\n                                                  (EXP_Ident (ID_Local px1)))\n                                                 (ret 8%Z))\n                         ]\n\n\n                            ++ fexpcode ++\n\n                            [ (IId py,  INSTR_Op (OP_GetElementPtr\n                                                    ytyp (yptyp, (EXP_Ident y))\n                                                    [(IntType, EXP_Integer 0%Z);\n                                                       (IntType, (EXP_Ident loopvarid))]\n\n                              ));\n\n                                (IVoid storeid, INSTR_Store false\n                                                            (TYPE_Double, fexpr)\n                                                            (TYPE_Pointer TYPE_Double,\n                                                             (EXP_Ident (ID_Local py)))\n                                                            (ret 8%Z))\n\n\n                            ];\n             blk_term  := TERM_Br_1 nextblock;\n             blk_comments := None\n           |}\n        ]).\n\nDefinition genMemInit\n           (size: Int64.int)\n           (y: ident)\n           (initial: binary64)\n           (nextblock: block_id):\n  cerr segment\n  :=\n    let ini := genFloatV initial in\n    let ttyp := getIRType (DSHPtr size) in\n    let tptyp := TYPE_Pointer ttyp in\n    pt <- incLocal ;;\n    init_block_id <- incBlockNamed \"MemInit_init\" ;;\n    loopcontblock <- incBlockNamed \"MemInit_init_lcont\" ;;\n    loopvar <- incLocalNamed \"MemInit_init_i\" ;;\n    storeid <- incVoid ;;\n    let init_block :=\n        {|\n          blk_id    := init_block_id ;\n          blk_phis  := [];\n          blk_code  := [\n                        (IId pt,  INSTR_Op (OP_GetElementPtr\n                                              ttyp (tptyp, (EXP_Ident y))\n                                              [(IntType, EXP_Integer 0%Z);\n                                                 (IntType,(EXP_Ident (ID_Local loopvar)))]\n\n                        ));\n\n                          (IVoid storeid, INSTR_Store false\n                                                      (TYPE_Double, ini)\n                                                      (TYPE_Pointer TYPE_Double,\n                                                       (EXP_Ident (ID_Local pt)))\n                                                      (ret 8%Z))\n\n\n\n                      ];\n          blk_term  := TERM_Br_1 loopcontblock;\n          blk_comments := None\n        |} in\n    genWhileLoop \"MemInit_loop\" (EXP_Integer 0%Z) (EXP_Integer (Int64.intval size)) loopvar loopcontblock init_block_id [init_block] [] nextblock.\n\nDefinition genPower\n           (i o: Int64.int)\n           (x y: ident)\n           (src dst: NExpr)\n           (n: NExpr)\n           (f: AExpr)\n           (initial: binary64)\n           (nextblock: block_id): cerr segment\n  :=\n    loopcontblock <- incBlockNamed \"Power_lcont\" ;;\n    let xtyp := getIRType (DSHPtr i) in\n    let xptyp := TYPE_Pointer xtyp in\n    let ytyp := getIRType (DSHPtr o) in\n    let yptyp := TYPE_Pointer ytyp in\n    '(nexp, ncode) <- genNExpr n ;;\n    '(src_nexpr, src_nexpcode) <- genNExpr src  ;;\n    '(dst_nexpr, dst_nexpcode) <- genNExpr dst  ;;\n    py <- incLocal ;;\n    storeid0 <- incVoid ;;\n    px <- incLocal ;;\n    let ini := genFloatV initial in\n    let init_code := ncode ++ src_nexpcode ++ dst_nexpcode ++ [\n                                    (IId px,  INSTR_Op (OP_GetElementPtr\n                                                          xtyp (xptyp, (EXP_Ident x))\n                                                          [(IntType, EXP_Integer 0%Z);\n                                                          (IntType, src_nexpr)]\n\n                                    ));\n           \n                                  (IId py,  INSTR_Op (OP_GetElementPtr\n                                                        ytyp (yptyp, (EXP_Ident y))\n                                                        [(IntType, EXP_Integer 0%Z);\n                                                        (IntType,dst_nexpr)]\n\n                                  ));\n\n                                  (IVoid storeid0, INSTR_Store false\n                                                               (TYPE_Double, ini)\n                                                               (TYPE_Pointer TYPE_Double,\n                                                                (EXP_Ident (ID_Local py)))\n                                                               (ret 8%Z))\n                           ] in\n\n    body_block_id <- incBlockNamed \"PowerLoopBody\" ;;\n    storeid1 <- incVoid ;;\n    void2 <- incVoid ;;\n    xv <- incLocal ;;\n    yv <- incLocal ;;\n    addVars [(ID_Local xv, TYPE_Double); (ID_Local yv, TYPE_Double)] ;;\n    '(fexpr, fexpcode) <- genAExpr f ;;\n    dropVars 2 ;;\n    let body_block := {|\n          blk_id    := body_block_id ;\n          blk_phis  := [];\n          blk_code  := [ (IId xv, INSTR_Load false TYPE_Double\n                                              (TYPE_Pointer TYPE_Double,\n                                               (EXP_Ident (ID_Local px)))\n                                              (ret 8%Z));\n\n                          (IId yv, INSTR_Load false TYPE_Double\n                                              (TYPE_Pointer TYPE_Double,\n                                               (EXP_Ident (ID_Local py)))\n                                              (ret 8%Z))\n                      ]\n                         ++ fexpcode ++\n                         [\n                           (IVoid storeid1, INSTR_Store false\n                                                        (TYPE_Double, fexpr)\n                                                        (TYPE_Pointer TYPE_Double,\n                                                         (EXP_Ident (ID_Local py)))\n                                                        (ret 8%Z))\n                         ];\n          blk_term  := TERM_Br_1 loopcontblock;\n          blk_comments := None\n        |} in\n    loopvar <- incLocalNamed \"Power_i\" ;;\n    genWhileLoop \"Power\" (EXP_Integer 0%Z) nexp loopvar loopcontblock body_block_id [body_block] init_code nextblock.\n\nDefinition resolve_PVar (p:PExpr): cerr (ident*Int64.int)\n  :=\n    sΓ <- getVarsAsString ;;\n    match p with\n    | PVar n =>\n      let ns := string_of_nat n in\n      '(l,t) <- getStateVar (\"NVar#\" @@ ns @@ \" out of range in \" @@ sΓ) n ;;\n      match t with\n      | TYPE_Pointer (TYPE_Array sz TYPE_Double) =>\n        sz' <- err2errS (MInt64asNT.from_N sz) ;;\n        ret (l, sz')\n      | _ => raise (\"Invalid type of PVar#\" @@ ns @@ \" in \" @@ sΓ)\n      end\n    end.\n\nDefinition genNop (nextblock: block_id) : cerr segment\n  :=\n    nopblock <- incBlockNamed \"Nop\" ;;\n    ret (nopblock,\n         [\n           {|\n             blk_id    := nopblock ;\n             blk_phis  := [];\n             blk_code  := [];\n             blk_term  := TERM_Br_1 nextblock;\n             blk_comments := None\n           |}\n        ]).\n\nFixpoint genIR\n         (fshcol: DSHOperator)\n         (nextblock: block_id):\n  cerr segment\n  :=\n    let fshcol_s := string_of_DSHOperator fshcol in\n    let op_s := (\"--- Operator: \" @@ fshcol_s @@ \"---\") in\n    let add_comment r : cerr (segment) := '((e, b)) <- r ;; ret (e,add_comment b [op_s]) in\n    catch (\n        match fshcol with\n        | DSHNop =>\n          '(body_entry, body_blocks) <- genNop nextblock ;;\n          add_comment\n            (ret (body_entry, body_blocks))\n        | DSHAssign (src_p,src_n) (dst_p,dst_n) =>\n          '(x,i) <- resolve_PVar src_p ;;\n          '(y,o) <- resolve_PVar dst_p ;;\n          add_comment\n            (genFSHAssign i o x y src_n dst_n nextblock)\n        | DSHIMap n x_p y_p f =>\n          (* the following check ensures loop bound fits integer. *)\n          _ <- err2errS (MInt64asNT.from_nat n) ;;\n          '(x,i) <- resolve_PVar x_p ;;\n          '(y,o) <- resolve_PVar y_p ;;\n          loopcontblock <- incBlockNamed \"IMap_lcont\" ;;\n          loopvar <- newLocalVar IntType \"IMap_i\" ;;\n          '(body_entry, body_blocks) <- genIMapBody i o x y f loopvar loopcontblock ;;\n          dropVars 1 ;;\n          add_comment\n            (genWhileLoop \"IMap\" (EXP_Integer 0%Z) (EXP_Integer (Z.of_nat n)) loopvar loopcontblock body_entry body_blocks [] nextblock)\n        | DSHBinOp n x_p y_p f =>\n          loopcontblock <- incBlockNamed \"BinOp_lcont\" ;;\n          '(x,i) <- resolve_PVar x_p ;;\n          '(y,o) <- resolve_PVar y_p ;;\n          loopvar <- incLocalNamed \"BinOp_i\" ;;\n          '(body_entry, body_blocks) <- genBinOpBody i o n x y f loopvar loopcontblock ;;\n          add_comment\n            (genWhileLoop \"BinOp\" (EXP_Integer 0%Z) (EXP_Integer (Z.of_nat n)) loopvar loopcontblock body_entry body_blocks [] nextblock)\n        | DSHMemMap2 n x0_p x1_p y_p f =>\n          loopcontblock <- incBlockNamed \"MemMapTwo_lcont\" ;;\n          '(x0,i0) <- resolve_PVar x0_p ;;\n          '(x1,i1) <- resolve_PVar x1_p ;;\n          '(y,o) <- resolve_PVar y_p ;;\n          n' <- err2errS (MInt64asNT.from_nat n) ;;\n          loopvar <- incLocalNamed \"MemMapTwo_i\" ;;\n          '(body_entry, body_blocks) <- genMemMap2Body i0 i1 o x0 x1 y f loopvar loopcontblock ;;\n          add_comment\n            (genWhileLoop \"MemMapTwo\" (EXP_Integer 0%Z) (EXP_Integer (Z.of_nat n)) loopvar loopcontblock body_entry body_blocks [] nextblock)\n        | DSHPower n (src_p,src_n) (dst_p,dst_n) f initial =>\n          '(x,i) <- resolve_PVar src_p ;;\n          '(y,o) <- resolve_PVar dst_p ;;\n          add_comment\n            (genPower i o x y src_n dst_n n f initial nextblock)\n        | DSHLoop n body =>\n          (* the following check ensures loop bound fits integer. *)\n          _ <- err2errS (MInt64asNT.from_nat n) ;;\n          loopcontblock <- incBlockNamed \"Loop_lcont\" ;;\n\n          loopvar <- newLocalVar IntType \"Loop_i\" ;;\n          '(child_block_id, child_blocks) <- genIR body loopcontblock ;;\n          dropVars 1 ;;\n          add_comment\n            (genWhileLoop \"Loop_loop\" (EXP_Integer 0%Z) (EXP_Integer (Z.of_nat n))\n                          loopvar loopcontblock child_block_id child_blocks[] nextblock)\n        | DSHAlloc size body =>\n          aname <- newLocalVar (TYPE_Pointer (getIRType (DSHPtr size))) \"a\" ;;\n          '(bblock, bcode) <- genIR body nextblock ;;\n          '(ablock,acode) <- allocTempArrayBlock aname bblock size ;;\n          dropVars 1 ;;\n          add_comment (ret (ablock, [acode]++bcode))\n        | DSHMemInit y_p value =>\n          '(y,size) <- resolve_PVar y_p ;; (* ignore actual block size *)\n          '(ablock,acode) <- genMemInit size y value nextblock ;;\n          add_comment (ret (ablock, acode))\n        | DSHSeq f g =>\n          '(gb, g') <- genIR g nextblock ;;\n          '(fb, f') <- genIR f gb ;;\n          add_comment (ret (fb, f'++g'))\n        end)\n          (fun m => raise (m @@ \" in \" @@ fshcol_s)).\n\nDefinition body_non_empty_cast (body : list (block typ)) : cerr (block typ * list (block typ)) :=\n  match body with\n  | [] => raise \"Attempting to generate a function containing no block\"\n  | b::body => ret (b,body)\n  end.\n\nDefinition LLVMGen\n           (i o: Int64.int)\n           (fshcol: DSHOperator)\n           (funname: string)\n  : cerr (toplevel_entities typ (block typ * list (block typ)))\n  :=\n    rid <- incBlock ;;\n    let retblock :=\n        {|\n          blk_id    := rid ;\n          blk_phis  := [];\n          blk_code  := [];\n          blk_term  := TERM_Ret_void;\n          blk_comments := None\n        |} in\n\n    '(_,body) <- genIR fshcol rid ;;\n\n    bodyt <- body_non_empty_cast (body ++ [retblock]) ;;\n    let all_intrinsics:toplevel_entities typ (block typ * list (block typ))\n        := [TLE_Comment \"Prototypes for intrinsics we use\"]\n             ++ (List.map (TLE_Declaration) defined_intrinsics_decls)\n    in\n\n    let x := Name \"X\" in\n    let xtyp := TYPE_Pointer (getIRType (DSHPtr i)) in\n    let y := Name \"Y\" in\n    let ytyp := TYPE_Pointer (getIRType (DSHPtr o)) in\n\n    ret\n      (all_intrinsics ++\n                      [\n                        TLE_Comment \"Top-level operator definition\" ;\n                      TLE_Definition \n                        {|\n                          df_prototype   :=\n                            {|\n                              dc_name        := Name funname;\n                              dc_type        := TYPE_Function TYPE_Void [xtyp; ytyp] ;\n                              dc_param_attrs := ([],\n                                                 [[PARAMATTR_Readonly] ++ ArrayPtrParamAttrs;\n                                                 ArrayPtrParamAttrs]);\n                              dc_linkage     := None ;\n                              dc_visibility  := None ;\n                              dc_dll_storage := None ;\n                              dc_cconv       := None ;\n                              dc_attrs       := []   ;\n                              dc_section     := None ;\n                              dc_align       := None ;\n                              dc_gc          := None\n                            |} ;\n                          df_args        := [x; y];\n                          df_instrs      := bodyt\n                        |}\n      ]).\n\n\n(* Creates 64 bit integer from floating pointer data list by interpreting\n   first 64 floating point values as bit values. *)\nDefinition int64FromData (data:list binary64) : (Int64.int*(list binary64)) :=\n  let fix int64FromData (n: nat) (data:list binary64) (i: Int64.int) {struct n}: (Int64.int*(list binary64)) :=\n      match n with\n      | O => (Int64.zero, data)\n      | S m =>\n        let '(f,data) := rotate Float64Zero data in\n        let si := Int64.add i Int64.one in\n        match f with\n        | B754_zero _ => int64FromData m data si\n        | _ =>\n          let '(x,data) := int64FromData m data si in\n          (Int64.add (Int64.repr (two_power_nat m)) x, data)\n        end\n      end\n  in int64FromData 64 data Int64.zero.\n\nDefinition initOneIRGlobal\n           (data: list binary64)\n           (nmt:string * DSHType)\n  : cerr (list binary64 * (toplevel_entity typ (block typ * list (block typ))))\n  :=\n    let (nm,t) := nmt in\n    match t with\n    | DSHnat =>\n      let '(xi, data) := int64FromData data in\n      let xu := Integers.Int64.unsigned xi in\n      let v_id := Name nm in\n      let v_typ := getIRType t in\n      let g := TLE_Global {|\n                   g_ident        := v_id;\n                   g_typ          := v_typ ;\n                   g_constant     := true ;\n                   g_exp          := Some (EXP_Integer xu);\n                   g_linkage      := Some LINKAGE_Internal ;\n                   g_visibility   := None ;\n                   g_dll_storage  := None ;\n                   g_thread_local := None ;\n                   g_unnamed_addr := true ;\n                   g_addrspace    := None ;\n                   g_externally_initialized := false ;\n                   g_section      := None ;\n                   g_align        := None ; (* TODO: maybe need to alight to 64-bit boundary? *)\n                 |} in\n      addVars [(ID_Global v_id, TYPE_Pointer v_typ)] ;;\n      ret (data, g)\n\n    | DSHCType =>\n      let '(x, data) := rotate Float64Zero data in\n      let v_id := Name nm in\n      let v_typ := getIRType t in\n      let g := TLE_Global {|\n                   g_ident        := v_id;\n                   g_typ          := v_typ ;\n                   g_constant     := true ;\n                   g_exp          := Some (EXP_Double x);\n                   g_linkage      := Some LINKAGE_Internal ;\n                   g_visibility   := None ;\n                   g_dll_storage  := None ;\n                   g_thread_local := None ;\n                   g_unnamed_addr := true ;\n                   g_addrspace    := None ;\n                   g_externally_initialized := false ;\n                   g_section      := None ;\n                   g_align        := None ; (* TODO: maybe need to alight to 64-bit boundary? *)\n                 |} in\n      addVars [(ID_Global v_id, TYPE_Pointer v_typ)] ;;\n      ret (data, g)\n    | DSHPtr n =>\n      let (data, arr) := constArray (MInt64asNT.to_nat n) data in\n      let v_id := Name nm in\n      let v_typ := getIRType t in\n      let g := TLE_Global {|\n                   g_ident        := v_id;\n                   g_typ          := v_typ;\n                   g_constant     := true ;\n                   g_exp          := Some (EXP_Array arr);\n                   g_linkage      := Some LINKAGE_Internal ;\n                   g_visibility   := None ;\n                   g_dll_storage  := None ;\n                   g_thread_local := None ;\n                   g_unnamed_addr := true ;\n                   g_addrspace    := None ;\n                   g_externally_initialized := false ;\n                   g_section      := None ;\n                   g_align        := Some Utils.PtrAlignment ;\n                 |} in\n      addVars [(ID_Global v_id, TYPE_Pointer v_typ)] ;;\n      ret (data, g)\n    end.\n\nDefinition globals_name_present\n           (name:string)\n           (l:list (string * DSHType)) : bool\n  :=\n    List.fold_right (fun v f => orb f (string_beq (fst v) name)) false l.\n\n\nFact nth_to_globals_name_present (globals:list (string * DSHType)) nm :\n  (exists res j, (nth_error globals j = Some res /\\ fst res = nm))\n  ->\n  globals_name_present nm globals = true.\nProof.\n  revert nm.\n  unfold globals_name_present.\n  induction globals.\n  -\n    cbn.\n    intros.\n    exfalso.\n    destruct H as [res [j [H0 H1]]].\n    rewrite Util.nth_error_nil in H0.\n    inv H0.\n  -\n    intros.\n    destruct H as [res [j H]].\n    specialize (IHglobals nm).\n    cbn.\n    apply orb_true_iff.\n    destruct j.\n    +\n      right.\n      cbn in H.\n      destruct H.\n      inv H.\n      unfold Misc.string_beq.\n      break_if; auto.\n    +\n      left.\n      apply IHglobals.\n      eauto.\nQed.\n\n\nDefinition global_uniq_chk: string * DSHType -> list (string * DSHType) -> cerr unit\n  := fun x xs =>\n       let nm := (fst x) in\n       err2errS (assert_false_to_err\n         (\"duplicate global name: \" @@ nm)\n         (globals_name_present nm xs)\n         tt).\n\n\n(*\n  Generate IR external definitoins for all globals.\n  They are externally linked and not initialized here.\n  (c.f [initIRglobals]\n\n  TODO: this is ugly. 2 maps should be replaced with single monadic fold.\n *)\nDefinition genIRGlobals\n           {FnBody: Set}\n           (x: list (string*DSHType))\n  : cerr (list (toplevel_entity _ FnBody))\n  := let l := List.map\n                (fun g:(string * DSHType) =>\n                   let (n,t) := g in\n                   TLE_Global {|\n                       g_ident        := Name n;\n                       g_typ          := getIRType t ; (* globals are always pointers *)\n                       g_constant     := true ;\n                       g_exp          := None ;\n                       g_linkage      := Some LINKAGE_External ;\n                       g_visibility   := None ;\n                       g_dll_storage  := None ;\n                       g_thread_local := None ;\n                       g_unnamed_addr := true ; (* TODO: unsure about this *)\n                       g_addrspace    := None ;\n                       g_externally_initialized:= true ;\n                       g_section      := None ;\n                       g_align        := Some PtrAlignment ;\n                     |}\n                ) x in\n     match l with\n     | nil => ret []\n     | _::_ =>\n       (* Add globals *)\n       addVars\n         (List.map\n            (fun g:(string* DSHType) =>\n               let (n,t) := g in (ID_Global (Name n), TYPE_Pointer (getIRType t)))\n            x) ;;\n       ret ([TLE_Comment \"Global variables\"] ++ l)\n     end.\n\n\nDefinition rev_firstn {A : Type} (n : nat) (l : list A) : list A :=\n  rev (firstn n l) ++ skipn n l.\n\nDefinition rev_firstn_Γ (n : nat) (st : IRState) : IRState :=\n  {| block_count := block_count st;\n     local_count := local_count st;\n     void_count := void_count st;\n     Γ := rev_firstn n (Γ st) |}.\n\n \n(* [initIRGlobals], except globals are appended to the start of [Γ] in reverse *)\nDefinition initIRGlobals_rev\n         (data: list binary64)\n         (x: list (string * DSHType))\n  : cerr (list binary64 * list (toplevel_entity typ (block typ * list (block typ))))\n  := init_with_data initOneIRGlobal global_uniq_chk data x.\n\n(*\n  Generate delclarations for all globals. They are all internally linked\n  and initialized in-place.\n\n  (c.f. genIRglobals)\n\n  NOTE: Could not use [monadic_fold_left] here because of error check.\n*)\nDefinition initIRGlobals\n         (data: list binary64)\n         (x: list (string * DSHType))\n  : cerr (list binary64 * list (toplevel_entity typ (block typ * list (block typ))))\n  := fun st =>\n       match initIRGlobals_rev data x st with\n       | inr (st, r) => inr (rev_firstn_Γ (length x) st, r)\n       | l => l\n       end.\n\n(*\n   When code genration generates [main], the input\n   will be stored in pre-initialized [X] global placeholder variable.\n *)\nDefinition initXYplaceholders (i o:Int64.int) (data:list binary64) x xtyp y ytyp:\n  cerr (list binary64 * (LLVMAst.toplevel_entities _ (LLVMAst.block typ * list (LLVMAst.block typ))))\n  :=\n    let '(data,ydata) := constArray (MInt64asNT.to_nat o) data in\n    let '(data,xdata) := constArray (MInt64asNT.to_nat i) data in\n    addVars [(ID_Global y, ytyp); (ID_Global x, xtyp)] ;;\n    ret (data,[ TLE_Global\n        {|\n          g_ident        := y;\n          g_typ          := ytyp;\n          g_constant     := true;\n          g_exp          := Some (EXP_Array ydata);\n          g_linkage      := None;\n          g_visibility   := None;\n          g_dll_storage  := None;\n          g_thread_local := None;\n          g_unnamed_addr := false;\n          g_addrspace    := None;\n          g_externally_initialized := false;\n          g_section      := None;\n          g_align        := None;\n        |}\n      ; TLE_Global\n          {|\n            g_ident        := x;\n            g_typ          := xtyp;\n            g_constant     := true;\n            g_exp          := Some (EXP_Array xdata);\n            g_linkage      := None;\n            g_visibility   := None;\n            g_dll_storage  := None;\n            g_thread_local := None;\n            g_unnamed_addr := false;\n            g_addrspace    := None;\n            g_externally_initialized := false;\n            g_section      := None;\n            g_align        := None;\n          |}\n    ]).\n\n(* Generates \"main\" function which will call \"op_name\", passing\n   global \"x\" and \"y\" as arguments. Returns \"y\". Pseudo-code:\n\n   global float[i] x;\n   global float[y] y;\n\n   float[o] main() {\n        tmp = op_name(x,y);\n        return y;\n   }\n*)\nDefinition genMain\n           (op_name: string)\n           (* Global X placeholder: *)\n           (x:raw_id) (xptyp:typ)\n           (* Global Y placeholder: *)\n           (y:raw_id) (ytyp:typ)\n           (yptyp:typ)\n  : LLVMAst.toplevel_entities _ (LLVMAst.block typ * list (LLVMAst.block typ))\n  :=\n    let z := Name \"z\" in\n    [\n      TLE_Comment \" Main function\"\n      ; TLE_Definition\n          {|\n            df_prototype   :=\n              {|\n                dc_name        := Name (\"main\") ;\n                dc_type        := TYPE_Function ytyp [] ;\n                dc_param_attrs := ([],\n                                   []);\n                dc_linkage     := None ;\n                dc_visibility  := None ;\n                dc_dll_storage := None ;\n                dc_cconv       := None ;\n                dc_attrs       := []   ;\n                dc_section     := None ;\n                dc_align       := None ;\n                dc_gc          := None\n              |} ;\n            df_args        := [];\n            df_instrs      := (\n                               {|\n                                 blk_id    := Name \"main_block\" ;\n                                 blk_phis  := [];\n                                 blk_code  :=\n                                   [\n                                     (IVoid 0%Z, INSTR_Call (TYPE_Void, EXP_Ident (ID_Global (Name op_name))) [(xptyp, EXP_Ident (ID_Global x)); (yptyp, EXP_Ident (ID_Global y))]) ;\n                                   (IId z, INSTR_Load false ytyp (yptyp, EXP_Ident (ID_Global y)) None )\n                                   ]\n                                 ;\n\n                                 blk_term  := TERM_Ret (ytyp, EXP_Ident (ID_Local z)) ;\n                                 blk_comments := None\n                               |}, [])\n          |}].\n\n\n(* Drop 2 vars before the last 2 in Γ *)\nDefinition dropFakeVars: cerr unit :=\n  st <- get ;;\n  let l := List.length (Γ st) in\n  if Nat.ltb l 4 then raise \"Γ too short\"\n  else\n    '(globals, Γ') <- option2errS \"Γ too short\"\n                                 (ListUtil.split (Γ st) (l-4)) ;;\n    '(_, Γ'') <- option2errS \"Γ too short\"\n                            (ListUtil.split Γ' 2) ;;\n    put {|\n        block_count := block_count st ;\n        local_count := local_count st ;\n        void_count  := void_count st ;\n        Γ := (globals ++ Γ'')\n      |}.\n\nDefinition not_in_globals (g: list (string * DSHType)) (n:string) : bool\n  := is_None_bool (List.find (fun x => eqb n (fst x)) g).\n\n(* Return list of names of declrations. E.g. defined_intrinsics_decls *)\nFixpoint declaration_names (decls: list (declaration typ)) : list string :=\n  match decls with\n  | [] => []\n  | (d::ds) => match dc_name d with\n             | Name s => s::declaration_names ds\n             | _ => declaration_names ds\n             end\n  end.\n\nDefinition valid_program (p: FSHCOLProgram) : bool :=\n  (negb (eqb (name p) \"main\")) &&\n  not_in_globals (globals p) \"main\" &&\n  not_in_globals (globals p) (name p) &&\n  (let dnames := declaration_names defined_intrinsics_decls in\n   (forallb (fun x => not_in_globals (globals p) x) (declaration_names defined_intrinsics_decls)) &&\n   (is_None_bool (List.find (fun x => eqb (name p) x) dnames))).\n\nDefinition compile (p: FSHCOLProgram) (just_compile:bool) (data:list binary64): cerr (toplevel_entities typ (block typ * list (block typ))) :=\n  match p with\n  | mkFSHCOLProgram i o name globals op =>\n    if valid_program p then\n      if just_compile then\n        (* While generate operator's function body, add parameters as\n         locals X=PVar 1, Y=PVar 0.\n\n        We want them to be in `Γ` before globals *)\n        let x := Name \"X\" in\n        let xtyp := TYPE_Pointer (getIRType (DSHPtr i)) in\n        let y := Name \"Y\" in\n        let ytyp := TYPE_Pointer (getIRType (DSHPtr o)) in\n\n        addVars [(ID_Local y, ytyp);(ID_Local x, xtyp)] ;;\n        ginit <- genIRGlobals (FnBody:= block typ * list (block typ)) globals ;;\n\n        (* Γ := [y; x; fake_y; fake_x] *)\n        prog <- LLVMGen i o op name ;;\n        ret (ginit ++ prog)\n      else\n        (* Global placeholders for X,Y *)\n        let gx := Anon 0%Z in\n        let gxtyp := getIRType (DSHPtr i) in\n        let gxptyp := TYPE_Pointer gxtyp in\n\n        let gy := Anon 1%Z in\n        let gytyp := getIRType (DSHPtr o) in\n        let gyptyp := TYPE_Pointer gytyp in\n\n        '(data,yxinit) <- initXYplaceholders i o data gx gxtyp gy gytyp ;;\n        (* Γ := [fake_y; fake_x] *)\n\n        (* While generate operator's function body, add parameters as\n         locals X=PVar 1, Y=PVar 0.\n\n        We want them to be in `Γ` before globals *)\n        let x := Name \"X\" in\n        let xtyp := TYPE_Pointer (getIRType (DSHPtr i)) in\n        let y := Name \"Y\" in\n        let ytyp := TYPE_Pointer (getIRType (DSHPtr o)) in\n\n        addVars [(ID_Local y, ytyp);(ID_Local x, xtyp)] ;;\n        (* Γ := [y; x; fake_y; fake_x] *)\n\n        (* Global variables *)\n        '(data,ginit) <- initIRGlobals data globals ;;\n        (* Γ := [globals; y; x; fake_y; fake_x] *)\n\n        (* operator function *)\n        prog <- LLVMGen i o op name ;;\n\n        (* After generation of operator function, we no longer need\n         [x] and [y] in [Γ]. *)\n\n        dropFakeVars ;;\n\n        (* Main function *)\n        let main := genMain name gx gxptyp gy gytyp gyptyp in\n        ret (ginit ++ yxinit ++ prog ++ main)\n    else\n      raise \"invalid program name\"\n  end.\n\nDefinition compile_w_main (p: FSHCOLProgram): list binary64 -> cerr (toplevel_entities typ (block typ * list (block typ))) :=\n  compile p false.\n", "meta": {"author": "asosyuk", "repo": "helix-ci1", "sha": "03afe6a3ffb0b058d9f08d30f4f7bb0b5d84a3d2", "save_path": "github-repos/coq/asosyuk-helix-ci1", "path": "github-repos/coq/asosyuk-helix-ci1/helix-ci1-03afe6a3ffb0b058d9f08d30f4f7bb0b5d84a3d2/coq/LLVMGen/Compiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22362351616714526}}
{"text": "From Usuba Require Import usuba_AST usuba_sem equiv_rel collect collectProof clean.\nFrom Coq Require Import MSets MSets.MSetToFiniteSet MSets.MSetFacts.\n\nFrom mathcomp Require Import all_ssreflect.\nRequire Import Coq.Sets.Ensembles.\n\nLemma clean_in_deqs_freevars:\n    forall eqns vars x,\n        iset.mem x (fst (clean_in_deqs vars (list_deq_of_deqL eqns))) = true <->\n            iset.mem x vars = true \\/\n            In ident (deqs_vars (snd (clean_in_deqs vars (list_deq_of_deqL eqns)))) x.\nProof.\n    move=> eqns; induction eqns as [|v e l tl HRec | i ae1 ae2 dL' HRec1 opt tl HRec2]; simpl.\n    {\n        split; auto.\n        move => [|[]]; trivial.\n    }\n    {\n        move=> vars x; specialize HRec with vars x.\n        destruct (clean_in_deqs vars (list_deq_of_deqL tl)); simpl in *.\n        case (iset.exists_ (iset.mem^~ t) (collect_varl v)); simpl; trivial.\n        do 2 rewrite iset.mem_spec; do 2 rewrite iset.mem_spec in HRec.\n        do 2 rewrite iset.union_spec; rewrite collect_expr_soundness.\n        rewrite collect_varl_soundness.\n        rewrite HRec; clear HRec; split.\n        + move=> [[]|[]]; auto; move=> H; right.\n            + constructor; assumption.\n            + do 2 constructor; assumption.\n            + do 2 constructor; assumption.\n        + move=> [HIn|[elt' [elt HIn|elt HIn]|HIn]]; auto.\n    }\n    {\n        move=> vars x; specialize HRec2 with vars x.\n        destruct (clean_in_deqs vars (list_deq_of_deqL tl)) as [vars' tl']; simpl in *.\n        case (iset.exists_ (iset.mem^~ vars') (collect_bounddeqs (list_deq_of_deqL dL')) || iset.mem i vars'); simpl; auto.\n        rewrite iset.mem_spec; rewrite iset.add_spec; do 3 rewrite iset.union_spec; do 2 rewrite collect_aexpr_soundness.\n        rewrite collect_deqs_soundness.\n        rewrite iset.mem_spec in HRec2; rewrite HRec2; split.\n        - move=> [|[[]|[[]|]]]; auto.\n            * move=> ->; by do 3 constructor.\n            * intros; right; constructor; assumption.\n            * intros; right; do 3 constructor; assumption.\n            * intros; right; do 4 constructor; assumption.\n            * intros; right; do 4 constructor; assumption.\n        - move=> [|[elt' [elt []|elt [|elt'2 []]]|]]; auto.\n    }\nQed.\n\nLemma loop_rec_change_ctxt arch prog:\n    forall e s body i ens ctxt1 ctxt2 type_ctxt,\n        context_srel (Union ident (fun elt => iset.In elt (collect_deqs (list_deq_of_deqL body))) ens) ctxt1 ctxt2 ->\n        opt_rel (context_srel (Union ident (fun elt => iset.In elt (collect_deqs (list_deq_of_deqL body))) ens))\n            (loop_rec ctxt1 ((eval_deq_list arch prog type_ctxt)^~ (list_deq_of_deqL body)) i s e)\n            (loop_rec ctxt2 ((eval_deq_list arch prog type_ctxt)^~ (list_deq_of_deqL body)) i s e).\nProof.\n    move=> e; induction e as [|e HRec]; simpl; auto.\n    move=> s body i ens ctxt1 ctxt2 type_ctxt HRel.\n    case (match s with 0 => false | m'.+1 => PeanoNat.Nat.leb e m' end); simpl; auto.\n    pose (p := HRec s body i ens ctxt1 ctxt2 type_ctxt HRel); move:p.\n    destruct (loop_rec ctxt1 ((eval_deq_list arch prog type_ctxt)^~ (list_deq_of_deqL body)) i s e).\n    all: destruct (loop_rec ctxt2 ((eval_deq_list arch prog type_ctxt)^~ (list_deq_of_deqL body)) i s e); simpl; auto.\n    2: move=> [].\n    2: discriminate.\n    move=> HRel2.\n    apply eval_deqL_change_ctxt.\n    {\n        reflexivity.\n    }\n    {\n        move=> elt HIn.\n        constructor 1.\n        unfold In.\n        rewrite collect_deqs_soundness.\n        assumption.\n    }\n    {\n        move=> elt HIn; simpl.\n        case (String.eqb elt i); trivial.\n        apply HRel2; assumption.\n    }\nQed.\n\nLemma clean_in_deqs_soundness arch prog:\n    forall eqns vars ctxt1 ctxt2 type_ctxt,\n        eval_deq_list arch prog type_ctxt ctxt1 (list_deq_of_deqL eqns) <> None ->\n        context_srel (deqs_vars (snd (clean_in_deqs vars (list_deq_of_deqL eqns)))) ctxt1 ctxt2 ->\n        context_srel (fun i => iset.mem i vars = true) ctxt1 ctxt2 ->\n        opt_rel (context_srel (fun i => iset.mem i vars = true))\n            (eval_deq_list arch prog type_ctxt ctxt1 (list_deq_of_deqL eqns))\n            (eval_deq_list arch prog type_ctxt ctxt2 (snd (clean_in_deqs vars (list_deq_of_deqL eqns)))).\nProof.\n    move=> eqns; induction eqns as [|v expr b tl HRec'|i aei1 aei2 body HRecBody opt tl HRecTL]; simpl.\n    { auto. }\n    {\n        move=> vars ctxt1 ctxt2 type_ctxt.\n        pose (p := clean_in_deqs_freevars tl vars); move:p.\n        pose (HRec := HRec' vars); move: HRec.\n        destruct (clean_in_deqs vars (list_deq_of_deqL tl)) as [vars' tl']; simpl in *.\n        clear HRec'.\n        case_eq (iset.exists_ (iset.mem^~ vars') (collect_varl v)); simpl.\n        {\n            move=> _ HRec _ HnoErr HRel1 HRel2.\n            rewrite <- (eval_expr_change_ctxt _ _ ctxt1 ctxt2 prog prog).\n            + destruct (eval_expr arch prog ctxt1 expr) as [val|]; simpl; trivial.\n                assert (context_srel (Union ident (varl_freevars v)\n                    (Union ident (deqs_vars tl') (fun i : ident => iset.mem i vars = true))) ctxt1 ctxt2) as HRel3.\n                {\n                    move=> x HIn; destruct HIn as [|x []].\n                    - apply HRel1; do 2 constructor; assumption.\n                    - apply HRel1; constructor; assumption.\n                    - apply HRel2; assumption.\n                }\n                pose (H := context_srel_bind v type_ctxt _ _ val _ HRel3); move: H.\n                destruct (bind ctxt1 type_ctxt v val) as [ctxt1'|]; simpl.\n                2: by move=> ->; simpl; reflexivity.\n                destruct (bind ctxt2 type_ctxt v val) as [ctxt2'|]; simpl.\n                2: by move=> [].\n                move=> HRel4; apply HRec; trivial.\n                - move=> x HIn; apply HRel4; do 2 constructor; assumption.\n                - move=> x HIn; apply HRel4; do 2 constructor; assumption.\n            + reflexivity.\n            + move=> x HIn; apply HRel1; do 2 constructor; assumption.\n        }\n        {\n            rewrite <- not_true_iff_false.\n            rewrite iset.exists_spec.\n            move=> NegExists HRec Hfreevars HnoErr HRel1 HRel2.\n            case (eval_expr arch prog ctxt1 expr) as [x|].\n            2: exfalso; apply HnoErr; reflexivity.\n            pose (p := context_srel_bind_compl v x ctxt1 type_ctxt); move:p.\n            case (bind ctxt1 type_ctxt v x) as [ctxt'|].\n            2: exfalso; apply HnoErr; reflexivity.\n            move=> HRel3; apply HRec; trivial.\n            all: transitivity ctxt1; trivial.\n            all: symmetry; move=> elt HIn; apply HRel3.\n            all: assert (iset.mem elt vars' = true) as Hfreevars' by (rewrite Hfreevars; auto).\n            all: clear Hfreevars; unfold Complement; unfold In; move=> HIn'.\n            all: apply NegExists; unfold iset.Exists; exists elt; split; trivial.\n            all: rewrite collect_varl_soundness; unfold In; assumption.\n        }\n    }\n    {\n        move=> vars ctxt1 ctxt2 type_ctxt HnoErr HRel1 HRel2.\n        pose (p := clean_in_deqs_freevars tl vars); move:p.\n        pose (p := HRecTL vars); move: p; clear HRecTL.\n        destruct (clean_in_deqs vars (list_deq_of_deqL tl)) as [vars' tl']; simpl.\n        move=> HRecTL.\n        case_eq (iset.exists_ (iset.mem^~ vars') (collect_bounddeqs (list_deq_of_deqL body))\n            || iset.mem i vars').\n        all: move=> HEq; rewrite HEq in HRel1; simpl.\n        {\n            move=> _; clear HEq; move: HnoErr.\n            rewrite (eval_aexpr_change_ctxt _ ctxt1 ctxt2).\n            2: apply context_srel_imp_context_csrel; move=> x HIn; apply HRel1; simpl; do 3 constructor; assumption.\n            rewrite (eval_aexpr_change_ctxt _ ctxt1 ctxt2).\n            2: apply context_srel_imp_context_csrel; move=> x HIn; apply HRel1; simpl; do 4 constructor; assumption.\n            destruct (eval_arith_expr ctxt2 aei1) as [s|]; simpl; trivial.\n            destruct (eval_arith_expr ctxt2 aei2) as [e|]; simpl; trivial.\n            assert (context_srel (Union ident (iset.In^~ (collect_deqs (list_deq_of_deqL body)))\n               (Union ident (fun i : ident => iset.mem i vars = true) (deqs_vars tl'))) ctxt1 ctxt2) as HRel3.\n            {\n                move=> x' [x HIn|x'' [x HIn|x HIn]].\n                + apply HRel1; simpl; unfold In in HIn; rewrite collect_deqs_soundness in HIn.\n                    do 4 constructor; assumption.\n                + apply HRel2; assumption.\n                + apply HRel1; simpl; constructor; assumption. \n            }\n            pose (p := loop_rec_change_ctxt arch prog e s body i _ ctxt1 ctxt2 type_ctxt HRel3); move: p; clear HRel3.\n            destruct (loop_rec ctxt1 ((eval_deq_list arch prog type_ctxt)^~ (list_deq_of_deqL body)) i s e) as [ctxt1'|].\n            2: move=> _ HnoErr; exfalso; apply HnoErr; reflexivity.\n            destruct (loop_rec ctxt2 ((eval_deq_list arch prog type_ctxt)^~ (list_deq_of_deqL body)) i s e) as [ctxt2'|]; simpl.\n            2: move=> [].\n            assert (match find_val ctxt1 i with Some v => Some ((i, v) :: ctxt1') | None => Some ctxt1' end\n                = Some match find_val ctxt1 i with Some v => (i, v)::ctxt1' | None => ctxt1' end) as HEq\n                by (case (find_val ctxt1 i); simpl; auto).\n            rewrite HEq; clear HEq.\n            assert (match find_val ctxt2 i with Some v => Some ((i, v) :: ctxt2') | None => Some ctxt2' end\n                = Some match find_val ctxt2 i with Some v => (i, v)::ctxt2' | None => ctxt2' end) as HEq\n                by (case (find_val ctxt2 i); simpl; auto).\n            rewrite HEq; clear HEq.\n            move=> HRel3 HnoErr.\n            apply HRecTL; auto; move=> x HIn; case_eq (String.eqb x i).\n            1,3: rewrite String.eqb_eq; move=> HEq; destruct HEq.\n            {\n                assert (find_val ctxt1 x = find_val ctxt2 x) as HEq\n                    by (apply HRel1; simpl; constructor; assumption); destruct HEq.\n                case (find_val ctxt1 x); simpl.\n                + rewrite String.eqb_refl; reflexivity.\n                + apply HRel3; do 2 constructor; assumption.\n            }\n            {\n                assert (find_val ctxt1 x = find_val ctxt2 x) as HEq\n                    by (apply HRel2; simpl; assumption); destruct HEq.\n                case (find_val ctxt1 x); simpl.\n                + rewrite String.eqb_refl; reflexivity.\n                + apply HRel3; do 2 constructor; assumption.\n            }\n            all: case (find_val ctxt1 i); case (find_val ctxt2 i); simpl.\n            1,5: move=> v v' ->.\n            3,4,6,7: move=> v ->.\n            7,8: move=> _.\n            all: apply HRel3; do 2 constructor; assumption.\n        }\n        {\n            rewrite orb_false_iff in HEq; destruct HEq as [Hexists HnegMem].\n            destruct (eval_arith_expr ctxt1 aei1) as [i1|].\n            2: exfalso; apply HnoErr; reflexivity.\n            destruct (eval_arith_expr ctxt1 aei2) as [i2|].\n            2: exfalso; apply HnoErr; reflexivity.\n            pose (p := loop_rec_unchanged_ctxt arch prog i i1 i2 body ctxt1 type_ctxt); move:p.\n            destruct (loop_rec ctxt1 ((eval_deq_list arch prog type_ctxt)^~ (list_deq_of_deqL body)) i i1 i2) as [ctxt'|].\n            2: exfalso; apply HnoErr; reflexivity.\n            clear HRecBody.\n            move=> HRel Hvars'.\n            case_eq (find_val ctxt1 i).\n            1: move=> v Hfind_val; rewrite Hfind_val in HnoErr.\n            2: move=> Hfind_val; rewrite Hfind_val in HnoErr.\n            all: apply HRecTL; trivial; transitivity ctxt1; trivial; symmetry.\n            all: move=> elt HIn; simpl.\n            {\n                case_eq (String.eqb elt i).\n                + rewrite String.eqb_eq; move=> HEq2; destruct HEq2; assumption.\n                + move=> HnotEq; apply HRel; unfold Complement, In; move=> HIn'.\n                    rewrite <- not_true_iff_false in Hexists; apply Hexists.\n                    rewrite iset.exists_spec; unfold iset.Exists.\n                    exists elt.\n                    destruct HIn' as [elt' []|].\n                    by rewrite String.eqb_refl in HnotEq.\n                    rewrite collect_bounddeqs_soundness_lemma; split; trivial.\n                    rewrite Hvars'; auto.\n            }\n            {\n                case_eq (String.eqb elt i).\n                + rewrite String.eqb_eq; move=> HEq2; destruct HEq2; assumption.\n                + move=> HnotEq; apply HRel; unfold Complement, In; move=> HIn'.\n                    rewrite <- not_true_iff_false in Hexists; apply Hexists.\n                    rewrite iset.exists_spec; unfold iset.Exists.\n                    exists elt.\n                    destruct HIn' as [elt' []|].\n                    by rewrite String.eqb_refl in HnotEq.\n                    rewrite collect_bounddeqs_soundness_lemma; split; trivial.\n                    rewrite Hvars'; auto.\n            }\n            all: rewrite <- not_true_iff_false in HnegMem; rewrite Hvars' in HnegMem.\n            all: apply HRel; unfold Complement, In; move=> HIn'; destruct HIn' as [elt' []|elt' HIn'].\n            1,3: apply HnegMem; auto.\n            all: rewrite <- not_true_iff_false in Hexists; apply Hexists.\n            all: rewrite iset.exists_spec; unfold iset.Exists.\n            all: exists elt'.\n            all: rewrite Hvars'; split; auto.\n            all: rewrite collect_bounddeqs_soundness_lemma; trivial.\n        }\n    }\nQed.\n\nTheorem clean_node_soudness arch prog:\n    forall node param input,\n        eval_node node arch prog param input <> None ->\n        eval_node node arch prog param input =\n        eval_node (clean_node node) arch prog param input.\nProof.\n    unfold clean_node.\n    move=> [id p_in p_out node_opt [temp_vars eqns| | |]]; simpl; trivial.\n    unfold eval_node; simpl.\n    move=> [] input; trivial.\n    case (build_ctxt p_in input); trivial.\n    move=> ctxt HnoErr.\n    assert (eval_deq_list arch prog (build_type_ctxt (temp_vars ++ p_in ++ p_out)) ctxt eqns <> None) as HnoErr1.\n    {\n        move=> HEq; rewrite HEq in HnoErr; apply HnoErr; trivial.\n    }\n    pose (p := clean_in_deqs_soundness arch prog (deqL_of_list_deq eqns) (collect_vdecl p_out) ctxt ctxt); move: p.\n    rewrite deqL_is_list_deq; move=> p.\n    pose (p' := p (build_type_ctxt (_ ++ _ ++ _)%list) HnoErr1 (context_srel_refl _ _) (context_srel_refl _ _)); move: p'; clear p.\n    destruct (eval_deq_list arch prog _ ctxt eqns); simpl.\n    2: by move=> ->; trivial.\n    destruct (eval_deq_list arch prog _ ctxt (snd (clean_in_deqs (collect_vdecl p_out) eqns))); simpl.\n    {\n        induction p_out as [|a tl HRec]; simpl; trivial.\n        move=> HRel; rewrite HRec.\n        + rewrite HRel; trivial.\n            unfold Ensembles.In; rewrite iset.mem_spec; rewrite iset.add_spec; auto.\n        + simpl in HnoErr; move=> HEq; rewrite HEq in HnoErr; apply HnoErr; case (find_val c (VD_ID a)); trivial.\n        + move=> x HIn; apply HRel; unfold Ensembles.In in *.\n            rewrite iset.mem_spec; rewrite iset.mem_spec in HIn; rewrite iset.add_spec; auto.\n    }\n    {\n        move=> [].\n    }\nQed.\n", "meta": {"author": "samsa1", "repo": "usuba_coq", "sha": "330d365e74fef62b90ff20244d160f0bcbbf4234", "save_path": "github-repos/coq/samsa1-usuba_coq", "path": "github-repos/coq/samsa1-usuba_coq/usuba_coq-330d365e74fef62b90ff20244d160f0bcbbf4234/src/normalization/cleanProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22362351616714526}}
{"text": "Require Export MicroBFTprops2.\n\n\nSection MicroBFTprim.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext          }.\n  Context { microbft_context    : MicroBFT_context      }.\n  Context { m_initial_keys      : MicroBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys     }.\n  Context { usig_hash           : USIG_hash             }.\n  Context { microbft_auth       : MicroBFT_auth         }.\n\n\n  Lemma not_primary_false_implies :\n    forall n,\n      not_primary n = false\n      -> n = MicroBFT_primary.\n  Proof.\n    introv h.\n    apply negb_false_iff in h.\n    unfold is_primary in *; smash_microbft2.\n  Qed.\n  Hint Resolve not_primary_false_implies : microbft.\n\n  Lemma uis_from_primary :\n    forall {eo : EventOrdering} (e : Event) ui,\n      knows_after e (microbft_data_ui ui)\n      -> ui2rep ui = MicroBFT_primary.\n  Proof.\n    introv kn.\n    unfold knows_after, state_after in kn; exrepnd; simpl in *.\n    unfold MicroBFT_data_knows in *; simpl in *.\n    rewrite M_state_sys_on_event_unfold in kn2; apply map_option_Some in kn2; exrepnd; rev_Some.\n    unfold MicroBFTheader.node2name in *; simpl in *.\n    rewrite kn1 in *; simpl in *.\n    unfold MicroBFTsys in *; simpl in *.\n    applydup M_run_ls_on_event_ls_is_microbft in kn2; exrepnd; subst; simpl in *.\n\n    apply option_map_Some in kn3; exrepnd; subst; simpl in *; microbft_simp.\n\n    remember (loc e) as n; symmetry in Heqn.\n    revert dependent s2.\n    revert dependent s1.\n    revert dependent s.\n    induction e as [e ind] using predHappenedBeforeInd;[]; introv run i.\n\n    rewrite M_run_ls_on_event_unroll2 in run.\n    apply map_option_Some in run; exrepnd; rev_Some.\n    apply map_option_Some in run0; exrepnd; rev_Some.\n    simpl in *.\n    applydup M_run_ls_before_event_ls_is_microbft in run1; exrepnd; subst; simpl in *.\n\n    unfold M_run_ls_on_input_ls, M_run_ls_on_input in *.\n    autorewrite with microbft in *.\n\n    rewrite M_run_ls_before_event_unroll_on in run1.\n\n    Time microbft_dest_msg Case;\n      try (destruct (dec_isFirst e));\n      repeat(simpl in *; autorewrite with microbft in *; smash_microbft2);\n      try (complete (apply ind in run1; autorewrite with eo; eauto 3 with eo));\n      try (dup run1 as w; eapply preserves_usig_id2 in w);\n      autorewrite with microbft eo in *; eauto;\n        repndors; ginv;\n          try (complete (apply ind in run1; autorewrite with eo; eauto 3 with eo));\n          try (complete (unfold ui_in_log_entry in *;\n                           simpl in *; smash_microbft2;\n                             allrw; eauto 3 with microbft));\n          try (complete (unfold ui_in_log_entry in *; simpl in *; smash_microbft2;\n                           apply invalid_request_false_implies_ui2rep_eq in Heqx; auto)).\n  Qed.\n\nEnd MicroBFTprim.\n\n\nHint Resolve not_primary_false_implies : microbft.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MicroBFTprim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22347072557142936}}
{"text": "Set Implicit Arguments.\n\n(* there is a name conflict on tactic 'unfolder' between GeneralTactics and MakeADT *)\nRequire Import Bedrock.Platform.Cito.GeneralTactics.\n\nRequire Import Bedrock.Platform.Facade.examples.FiatADTs.\nImport Adt.\nRequire Import Bedrock.Platform.Cito.WordMap.\nRequire Import Bedrock.Platform.Cito.RepInv Bedrock.Platform.Cito.MakeADT.\n\nRequire Import Bedrock.Platform.AutoSep.\n\nRequire Import Bedrock.Platform.Facade.examples.ListSetF Bedrock.Platform.Facade.examples.ListSeqF Bedrock.Platform.Facade.examples.FiatRepInv.\n\nModule Import Made := MakeADT.Make(FiatADTs.Adt)(Ri).\n\nImport Semantics.\n\nImport LinkMake.StubsMake.StubMake.CompileFuncSpecMake.InvMake.SemanticsMake.\nImport LinkMake.StubsMake.StubMake.CompileFuncSpecMake.InvMake2.\nImport LinkMake.StubsMake.StubMake.CompileFuncSpecMake.InvMake.\n\nLemma is_heap_eat : forall w v,\n  is_heap heap_empty\n  ===> is_heap (WordMap.remove w (heap_upd heap_empty w v)).\n  intros; apply is_heap_Equal.\n  apply Properties.F.Equal_mapsto_iff; intuition.\n  apply Properties.F.empty_mapsto_iff in H; tauto.\n  apply Properties.F.remove_mapsto_iff in H; intuition.\n  apply Properties.F.add_mapsto_iff in H1; intuition.\nQed.\nRequire Import Bedrock.Platform.Cito.SemanticsFacts5.\nRequire Import Bedrock.Platform.Cito.LayoutHintsUtil.\n\nLemma readd_FEnsemble : forall c rv rv',\n  lset rv' c * is_heap heap_empty\n  ===> is_heap (WordMap.add c (FEnsemble rv') (heap_upd heap_empty c (FEnsemble rv))).\n  intros.\n  unfold is_heap at 2.\n  assert (List.In (c, FEnsemble rv') (heap_elements (WordMap.add c (FEnsemble rv') (heap_upd heap_empty c (FEnsemble rv))))).\n  apply InA_In.\n  apply WordMap.elements_1.\n  apply WordMap.add_1.\n  auto.\n  eapply starL_in in H; try (apply NoDupA_NoDup; apply WordMap.elements_3w).\n  destruct H; intuition idtac.\n  eapply Himp_trans; [ | apply H0 ].\n  simpl.\n  apply Himp_star_frame; try apply Himp_refl.\n  apply starL_permute; auto.\n  apply NoDupA_NoDup; apply WordMap.elements_3w.\n  intuition.\n  apply H2 in H1; intuition.\n  apply In_InA' in H4.\n  apply WordMap.elements_2 in H4.\n  apply Properties.F.add_mapsto_iff in H4; intuition.\n  apply Properties.F.add_mapsto_iff in H5; intuition.\n  apply Properties.F.empty_mapsto_iff in H6; tauto.\nQed.\nImport LayoutHintsUtil.\n\nLemma readd_List : forall c rv rv',\n  lseq rv' c * is_heap heap_empty\n  ===> is_heap (WordMap.add c (List rv') (heap_upd heap_empty c (List rv))).\n  intros.\n  unfold is_heap at 2.\n  assert (List.In (c, List rv') (heap_elements (WordMap.add c (List rv') (heap_upd heap_empty c (List rv))))).\n  apply InA_In.\n  apply WordMap.elements_1.\n  apply WordMap.add_1.\n  auto.\n  eapply starL_in in H; try (apply NoDupA_NoDup; apply WordMap.elements_3w).\n  destruct H; intuition idtac.\n  eapply Himp_trans; [ | apply H0 ].\n  simpl.\n  apply Himp_star_frame; try apply Himp_refl.\n  apply starL_permute; auto.\n  apply NoDupA_NoDup; apply WordMap.elements_3w.\n  intuition.\n  apply H2 in H1; intuition.\n  apply In_InA' in H4.\n  apply WordMap.elements_2 in H4.\n  apply Properties.F.add_mapsto_iff in H4; intuition.\n  apply Properties.F.add_mapsto_iff in H5; intuition.\n  apply Properties.F.empty_mapsto_iff in H6; tauto.\nQed.\n\nLemma get_rval : forall specs st P (Q : Prop) R S T Z,\n  (Q -> interp specs (![P * R * S * T] st ---> Z)%PropX)\n  -> interp specs (![P * (([|Q|] * R) * S) * T] st ---> Z)%PropX.\n  intros.\n  apply Imply_trans with (![[|Q|] * (P * R * S * T)]st)%PropX.\n  assert (P * ([|Q|] * R * S) * T ===> [|Q|] * (P * R * S * T)).\n  sepLemma.\n  rewrite sepFormula_eq.\n  apply H0.\n  apply Imply_trans with ([|Q|] /\\ ![P * R * S * T]st)%PropX.\n  rewrite sepFormula_eq.\n  do 2 (apply existsL; intro).\n  apply andL; apply injL; intro.\n  apply andL.\n  apply andL.\n  apply injL; intro.\n  apply injL; intro.\n  apply split_semp in H0; auto; subst.\n  apply andR.\n  apply injR; auto.\n  apply Imply_refl.\n  apply andL.\n  apply injL; auto.\nQed.\n\nLemma get_rval' : forall specs st P (Q : Prop) R S T Z,\n  (Q -> interp specs (![P * R * S * T] st ---> Z)%PropX)\n  -> interp specs (![P * ((R * [|Q|]) * S) * T] st ---> Z)%PropX.\n  intros.\n  apply Imply_trans with (![[|Q|] * (P * R * S * T)]st)%PropX.\n  assert (P * (R * [|Q|] * S) * T ===> [|Q|] * (P * R * S * T)).\n  sepLemma.\n  rewrite sepFormula_eq.\n  apply H0.\n  apply Imply_trans with ([|Q|] /\\ ![P * R * S * T]st)%PropX.\n  rewrite sepFormula_eq.\n  do 2 (apply existsL; intro).\n  apply andL; apply injL; intro.\n  apply andL.\n  apply andL.\n  apply injL; intro.\n  apply injL; intro.\n  apply split_semp in H0; auto; subst.\n  apply andR.\n  apply injR; auto.\n  apply Imply_refl.\n  apply andL.\n  apply injL; auto.\nQed.\n\nLemma get_rval'' : forall specs st P (Q : Prop) R S Z,\n  (Q -> interp specs (![P * R * S] st ---> Z)%PropX)\n  -> interp specs (![P * ([|Q|] * R) * S] st ---> Z)%PropX.\n  intros.\n  apply Imply_trans with (![[|Q|] * (P * R * S)]st)%PropX.\n  assert (P * ([|Q|] * R) * S ===> [|Q|] * (P * R * S)).\n  sepLemma.\n  rewrite sepFormula_eq.\n  apply H0.\n  apply Imply_trans with ([|Q|] /\\ ![P * R * S]st)%PropX.\n  rewrite sepFormula_eq.\n  do 2 (apply existsL; intro).\n  apply andL; apply injL; intro.\n  apply andL.\n  apply andL.\n  apply injL; intro.\n  apply injL; intro.\n  apply split_semp in H0; auto; subst.\n  apply andR.\n  apply injR; auto.\n  apply Imply_refl.\n  apply andL.\n  apply injL; auto.\nQed.\n\nDefinition hints : TacPackage.\n  prepare (store_pair_inl_fwd, store_pair_inr_fwd)\n  (store_pair_inl_bwd, store_pair_inr_bwd).\nDefined.\n\nArguments SCA {ADTValue} _.\nArguments ADT {ADTValue} _.\n\nRequire Bedrock.Platform.Cito.AxSpec.\nImport AxSpec.ConformTactic.\n\nDefinition m0 := bimport [[ \"sys\"!\"abort\" @ [abortS],\n\n                            \"ListSet\"!\"new\" @ [ListSetF.newS],\n                            \"ListSet\"!\"delete\" @ [ListSetF.deleteS],\n                            \"ListSet\"!\"mem\" @ [ListSetF.memS],\n                            \"ListSet\"!\"add\" @ [ListSetF.addS],\n                            \"ListSet\"!\"remove\" @ [ListSetF.removeS],\n                            \"ListSet\"!\"size\" @ [ListSetF.sizeS],\n\n                            \"ListSeq\"!\"new\" @ [ListSeqF.newS],\n                            \"ListSeq\"!\"delete\" @ [ListSeqF.deleteS],\n                            \"ListSeq\"!\"pop\" @ [ListSeqF.popS],\n                            \"ListSeq\"!\"empty\" @ [ListSeqF.emptyS],\n                            \"ListSeq\"!\"push\" @ [ListSeqF.pushS],\n                            \"ListSeq\"!\"copy\" @ [ListSeqF.copyS],\n                            \"ListSeq\"!\"rev\" @ [ListSeqF.revS],\n                            \"ListSeq\"!\"length\" @ [ListSeqF.lengthS] ]]\n  fmodule \"ADT\" {{\n    ffunction \"sEmpty\" reserving 8 [FEnsemble_sEmpty] := \"ListSet\"!\"new\"\n    with ffunction \"sDelete\" reserving 7 [FEnsemble_sDelete] := \"ListSet\"!\"delete\"\n    with ffunction \"sAdd\" reserving 9 [FEnsemble_sAdd] := \"ListSet\"!\"add\"\n    with ffunction \"sRemove\" reserving 7 [FEnsemble_sRemove] := \"ListSet\"!\"remove\"\n    with ffunction \"sIn\" reserving 1 [FEnsemble_sIn] := \"ListSet\"!\"mem\"\n    with ffunction \"sSize\" reserving 1 [FEnsemble_sSize] := \"ListSet\"!\"size\"\n    with ffunction \"new\" reserving 8 [List_new] := \"ListSeq\"!\"new\"\n    with ffunction \"delete\" reserving 7 [List_delete] := \"ListSeq\"!\"delete\"\n    with ffunction \"pop\" reserving 8 [List_pop] := \"ListSeq\"!\"pop\"\n    with ffunction \"empty\" reserving 0 [List_empty] := \"ListSeq\"!\"empty\"\n    with ffunction \"push\" reserving 8 [List_push] := \"ListSeq\"!\"push\"\n    with ffunction \"copy\" reserving 10 [List_copy] := \"ListSeq\"!\"copy\"\n    with ffunction \"rev\" reserving 2 [List_rev] := \"ListSeq\"!\"rev\"\n    with ffunction \"length\" reserving 1 [List_length] := \"ListSeq\"!\"length\"\n  }}.\n\nTheorem ok0 : moduleOk m0.\n  vcgen.\n\n\n  (* ListSet *)\n\n  (* sEmpty *)\n\n  do_abort (@nil string).\n  do_abort (@nil string).\n  do_abort (@nil string).\n\n  do_delegate1 (@nil string) hints.\n  do 2 (descend; step auto_ext).\n  2: returnAdt.\n  simpl.\n  make_toArray (@nil string).\n  step auto_ext.\n  etransitivity; [ | apply himp_star_frame; [ apply (@is_state_in x4) | reflexivity ] ].\n  unfolder.\n  do_delegate2 (@nil string).\n\n  (* sDelete *)\n\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n\n  do_delegate1 (\"self\" :: nil) hints.\n  descend; step auto_ext.\n  repeat (apply andL || (apply injL; intro) || (apply existsL; intro)); reduce.\n  apply get_rval''; intro.\n  descend; step auto_ext.\n  2: returnScalar.\n  simpl.\n  make_toArray (\"self\" :: nil).\n  step auto_ext.\n  etransitivity; [ | apply (@is_state_in x2) ].\n  unfolder.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply is_heap_eat ] ].\n  do_delegate2 (\"self\" :: nil).\n\n  (* sAdd *)\n\n  do_abort (\"self\" :: \"n\" :: nil).\n  do_abort (\"self\" :: \"n\" :: nil).\n  do_abort (\"self\" :: \"n\" :: nil).\n\n  do_delegate1 (\"self\" :: \"n\" :: nil) hints.\n  add_side_conditions.\n  descend; step hints.\n  simpl.\n  descend; step auto_ext.\n  descend; step auto_ext.\n  simpl.\n  repeat (apply andL || (apply injL; intro) || (apply existsL; intro)); reduce.\n  apply get_rval; intro.\n  descend; step auto_ext.\n  2: returnScalar.\n  simpl.\n  make_toArray (\"self\" :: \"n\" :: nil).\n  step auto_ext.\n  etransitivity; [ | apply (@is_state_in x2) ].\n  unfolder.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply readd_FEnsemble ] ].\n  do_delegate2 (\"self\" :: \"n\" :: nil).\n\n  (* sRemove *)\n\n  do_abort (\"self\" :: \"n\" :: nil).\n  do_abort (\"self\" :: \"n\" :: nil).\n  do_abort (\"self\" :: \"n\" :: nil).\n\n  do_delegate1 (\"self\" :: \"n\" :: nil) hints.\n  add_side_conditions.\n  descend; step hints.\n  simpl.\n  descend; step auto_ext.\n  descend; step auto_ext.\n  simpl.\n  repeat (apply andL || (apply injL; intro) || (apply existsL; intro)); reduce.\n  apply get_rval; intro.\n  descend; step auto_ext.\n  2: returnScalar.\n  simpl.\n  make_toArray (\"self\" :: \"n\" :: nil).\n  step auto_ext.\n  etransitivity; [ | apply (@is_state_in x2) ].\n  unfolder.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply readd_FEnsemble ] ].\n  do_delegate2 (\"self\" :: \"n\" :: nil).\n\n  (* sIn *)\n\n  do_abort (\"self\" :: \"n\" :: nil).\n  do_abort (\"self\" :: \"n\" :: nil).\n  do_abort (\"self\" :: \"n\" :: nil).\n\n  do_delegate1 (\"self\" :: \"n\" :: nil) hints.\n  add_side_conditions.\n  descend; step hints.\n  simpl.\n  descend; step auto_ext.\n  repeat (apply andL || (apply injL; intro) || (apply existsL; intro)); reduce.\n  apply get_rval; intro.\n  step auto_ext.\n  descend; step auto_ext.\n  2: rewrite FiniteSetF.Has.has_eq in *; returnSomething; eauto 6.\n  simpl.\n  make_toArray (\"self\" :: \"n\" :: nil).\n  step auto_ext.\n  etransitivity; [ | apply (@is_state_in x2) ].\n  unfolder.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply readd_FEnsemble ] ].\n  do_delegate2 (\"self\" :: \"n\" :: nil).\n\n  (* sSize *)\n\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n\n  do_delegate1 (\"self\" :: nil) hints.\n  descend; step hints.\n  repeat (apply andL || (apply injL; intro) || (apply existsL; intro)); reduce.\n  apply get_rval; intro.\n  destruct H0 as [ ? [ ] ].\n  step auto_ext.\n  2: returnScalar.\n  simpl.\n  make_toArray (\"self\" :: nil).\n  step auto_ext.\n  etransitivity; [ | apply (@is_state_in x2) ].\n  unfolder.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply readd_FEnsemble ] ].\n  do_delegate2 (\"self\" :: nil).\n\n\n  (* ListSeq *)\n\n  (* new *)\n\n  do_abort (@nil string).\n  do_abort (@nil string).\n  do_abort (@nil string).\n\n  do_delegate1 (@nil string) hints.\n  do 2 (descend; step auto_ext).\n  2: returnAdt.\n  simpl.\n  make_toArray (@nil string).\n  step auto_ext.\n  etransitivity; [ | apply himp_star_frame; [ apply (@is_state_in x4) | reflexivity ] ].\n  unfolder.\n  do_delegate2 (@nil string).\n\n  (* delete *)\n\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n\n  do_delegate1 (\"self\" :: nil) hints.\n  descend; step auto_ext.\n  repeat (apply andL || (apply injL; intro) || (apply existsL; intro)); reduce.\n  apply get_rval''; intro.\n  descend; step auto_ext.\n  2: returnScalar.\n  simpl.\n  make_toArray (\"self\" :: nil).\n  step auto_ext.\n  etransitivity; [ | apply (@is_state_in x2) ].\n  unfolder.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply is_heap_eat ] ].\n  do_delegate2 (\"self\" :: nil).\n\n  (* pop *)\n\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n\n  do_delegate1 (\"self\" :: nil) hints.\n  repeat (apply andL || (apply injL; intro) || (apply existsL; intro)); reduce.\n  apply get_rval; intro.\n  descend; step auto_ext.\n  descend; step auto_ext.\n  2: returnScalar.\n  simpl.\n  make_toArray (\"self\" :: nil).\n  step auto_ext.\n  etransitivity; [ | apply (@is_state_in x2) ].\n  unfolder.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply readd_List ] ].\n  do_delegate2 (\"self\" :: nil).\n\n  (* empty *)\n\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n\n  do_delegate1 (\"self\" :: nil) hints.\n  repeat (apply andL || (apply injL; intro) || (apply existsL; intro)); reduce.\n  apply get_rval; intro.\n  step auto_ext.\n  descend; step auto_ext.\n  2: returnScalar.\n  simpl.\n  make_toArray (\"self\" :: nil).\n  step auto_ext.\n  etransitivity; [ | apply (@is_state_in x2) ].\n  unfolder.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply readd_List ] ].\n  do_delegate2 (\"self\" :: nil).\n\n  (* push *)\n\n  do_abort (\"self\" :: \"n\" :: nil).\n  do_abort (\"self\" :: \"n\" :: nil).\n  do_abort (\"self\" :: \"n\" :: nil).\n\n  do_delegate1 (\"self\" :: \"n\" :: nil) hints.\n  add_side_conditions.\n  descend; step hints.\n  simpl.\n  descend; step auto_ext.\n  descend; step auto_ext.\n  simpl.\n  repeat (apply andL || (apply injL; intro) || (apply existsL; intro)); reduce.\n  apply get_rval; intro.\n  descend; step auto_ext.\n  2: returnScalar.\n  simpl.\n  make_toArray (\"self\" :: \"n\" :: nil).\n  step auto_ext.\n  etransitivity; [ | apply (@is_state_in x2) ].\n  unfolder.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply readd_List ] ].\n  do_delegate2 (\"self\" :: \"n\" :: nil).\n\n  (* copy *)\n\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n\n  do_delegate1 (\"self\" :: nil) hints.\n  descend; step hints.\n  simpl.\n  descend; step auto_ext.\n  2: returnAdt.\n  simpl.\n  make_toArray (\"self\" :: nil).\n  step auto_ext.\n  etransitivity; [ | apply (@is_state_in x2) ].\n  unfolder.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply readd_List ] ].\n  do_delegate2 (\"self\" :: nil).\n\n  (* rev *)\n\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n\n  do_delegate1 (\"self\" :: nil) hints.\n  descend; step hints.\n  simpl.\n  repeat (apply andL || (apply injL; intro) || (apply existsL; intro)); reduce.\n  apply get_rval; intro.\n  descend; step auto_ext.\n  2: returnScalar.\n  simpl.\n  make_toArray (\"self\" :: nil).\n  step auto_ext.\n  etransitivity; [ | apply (@is_state_in x2) ].\n  unfolder.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply readd_List ] ].\n  do_delegate2 (\"self\" :: nil).\n\n  (* length *)\n\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n  do_abort (\"self\" :: nil).\n\n  do_delegate1 (\"self\" :: nil) hints.\n  descend; step hints.\n  repeat (apply andL || (apply injL; intro) || (apply existsL; intro)); reduce.\n  apply get_rval; intro.\n  step auto_ext.\n  2: returnScalar.\n  simpl.\n  make_toArray (\"self\" :: nil).\n  step auto_ext.\n  etransitivity; [ | apply (@is_state_in x2) ].\n  unfolder.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply readd_List ] ].\n  do_delegate2 (\"self\" :: nil).\n\n\n  Grab Existential Variables.\n  exact 0.\n  exact 0.\n  exact 0.\n  exact 0.\n  exact 0.\n  exact 0.\n  exact 0.\n  exact 0.\n  exact 0.\n  exact 0.\nQed.\n\nDefinition m1 := link ListSetF.m m0.\nDefinition m2 := link ListSeqF.m m1.\nDefinition m := link Malloc.m m2.\n\nTheorem ok1 : moduleOk m1.\n  link ListSetF.ok ok0.\nQed.\n\nTheorem ok2 : moduleOk m2.\n  link ListSeqF.ok ok1.\nQed.\n\nTheorem ok : moduleOk m.\n  link Malloc.ok ok2.\nQed.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Platform/Facade/examples/FiatImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2234707191715048}}
{"text": "Require Import Kami.Syntax Kami.Lib.Fold.\nImport Word.Notations.\nImport ListNotations.\nRequire Import Coq.Sorting.Permutation.\nRequire Import Coq.Sorting.PermutEq.\nRequire Import RelationClasses Setoid Morphisms.\nRequire Import ZArith.\n\nDefinition filterRegs f m (o: RegsT) :=\n  filter (fun x => f (getBool (in_dec string_dec (fst x) (map fst (getAllRegisters m))))) o.\n\nDefinition filterExecs f m (l: list FullLabel) :=\n  filter (fun x => f match fst (snd x) with\n                     | Rle y =>\n                       getBool (in_dec string_dec y (map fst (getAllRules m)))\n                     | Meth (y, _) =>\n                       getBool (in_dec string_dec y (map fst (getAllMethods m)))\n                     end) l.\n\nInductive WeakInclusions : list (list FullLabel) -> list (list (FullLabel)) -> Prop :=\n| WI_Nil : WeakInclusions nil nil\n| WI_Cons : forall (ls ls' : list (list FullLabel)) (l l' : list FullLabel), WeakInclusions ls ls' -> WeakInclusion l l' -> WeakInclusions (l::ls)(l'::ls').\n\n\nDefinition WeakEqualities ls ls' := WeakInclusions ls ls' /\\ WeakInclusions ls' ls.\n\nNotation \"l '[=]' r\" :=\n  ((@Permutation _ (l) (r)))\n    (at level 70, no associativity).\n\nSection Semantics.\n  Variable o: RegsT.\n\n  Inductive PSemAction:\n    forall k, ActionT type k -> RegsT -> RegsT -> MethsT -> type k -> Prop :=\n  | PSemMCall\n      meth s (marg: Expr type (SyntaxKind (fst s)))\n      (mret: type (snd s))\n      retK (fret: type retK)\n      (cont: type (snd s) -> ActionT type retK)\n      readRegs newRegs (calls: MethsT) acalls\n      (HAcalls: acalls [=] (meth, (existT _ _ (evalExpr marg, mret))) :: calls)\n      (HPSemAction: PSemAction (cont mret) readRegs newRegs calls fret):\n      PSemAction (MCall meth s marg cont) readRegs newRegs acalls fret\n  | PSemLetExpr\n      k (e: Expr type k) retK (fret: type retK)\n      (cont: fullType type k -> ActionT type retK) readRegs newRegs calls\n      (HPSemAction: PSemAction (cont (evalExpr e)) readRegs newRegs calls fret):\n      PSemAction (LetExpr e cont) readRegs newRegs calls fret\n  | PSemLetAction\n      k (a: ActionT type k) (v: type k) retK (fret: type retK)\n      (cont: type k -> ActionT type retK)\n      readRegs newRegs readRegsCont newRegsCont calls callsCont\n      (HDisjRegs: DisjKey newRegs newRegsCont)\n      (HPSemAction: PSemAction a readRegs newRegs calls v)\n      ureadRegs unewRegs ucalls\n      (HUReadRegs: ureadRegs [=] readRegs ++ readRegsCont)\n      (HUNewRegs: unewRegs [=] newRegs ++ newRegsCont)\n      (HUCalls: ucalls [=] calls ++ callsCont)\n      (HPSemActionCont: PSemAction (cont v) readRegsCont newRegsCont callsCont fret):\n      PSemAction (LetAction a cont) (ureadRegs) (unewRegs)\n                (ucalls) fret\n  | PSemReadNondet\n      valueT (valueV: fullType type valueT)\n      retK (fret: type retK) (cont: fullType type valueT -> ActionT type retK)\n      readRegs newRegs calls\n      (HPSemAction: PSemAction (cont valueV) readRegs newRegs calls fret):\n      PSemAction (ReadNondet _ cont) readRegs newRegs calls fret\n  | PSemReadReg\n      (r: string) regT (regV: fullType type regT)\n      retK (fret: type retK) (cont: fullType type regT -> ActionT type retK)\n      readRegs newRegs calls areadRegs\n      (HRegVal: In (r, existT _ regT regV) o)\n      (HPSemAction: PSemAction (cont regV) readRegs newRegs calls fret)\n      (HNewReads: areadRegs [=] (r, existT _ regT regV) :: readRegs):\n      PSemAction (ReadReg r _ cont) areadRegs newRegs calls fret\n  | PSemWriteReg\n      (r: string) k\n      (e: Expr type k)\n      retK (fret: type retK)\n      (cont: ActionT type retK) readRegs newRegs calls anewRegs\n      (HRegVal: In (r, k) (getKindAttr o))\n      (HDisjRegs: key_not_In r newRegs)\n      (HANewRegs: anewRegs [=] (r, (existT _ _ (evalExpr e))) :: newRegs)\n      (HPSemAction: PSemAction cont readRegs newRegs calls fret):\n      PSemAction (WriteReg r e cont) readRegs anewRegs calls fret\n  | PSemIfElseTrue\n      (p: Expr type (SyntaxKind Bool)) k1\n      (a: ActionT type k1)\n      (a': ActionT type k1)\n      (r1: type k1)\n      k2 (cont: type k1 -> ActionT type k2)\n      readRegs1 readRegs2  newRegs1 newRegs2 calls1 calls2 (r2: type k2)\n      (HDisjRegs: DisjKey newRegs1 newRegs2)\n      (HTrue: evalExpr p = true)\n      (HAction: PSemAction a readRegs1 newRegs1 calls1 r1)\n      (HPSemAction: PSemAction (cont r1) readRegs2 newRegs2 calls2 r2)\n      ureadRegs unewRegs ucalls\n      (HUReadRegs: ureadRegs [=] readRegs1 ++ readRegs2)\n      (HUNewRegs: unewRegs [=] newRegs1 ++ newRegs2)\n      (HUCalls: ucalls [=] calls1 ++ calls2) :\n      PSemAction (IfElse p a a' cont) ureadRegs unewRegs ucalls r2\n  | PSemIfElseFalse\n      (p: Expr type (SyntaxKind Bool)) k1\n      (a: ActionT type k1)\n      (a': ActionT type k1)\n      (r1: type k1)\n      k2 (cont: type k1 -> ActionT type k2)\n      readRegs1 readRegs2 newRegs1 newRegs2 calls1 calls2 (r2: type k2)\n      (HDisjRegs: DisjKey newRegs1 newRegs2)\n      (HFalse: evalExpr p = false)\n      (HAction: PSemAction a' readRegs1 newRegs1 calls1 r1)\n      (HPSemAction: PSemAction (cont r1) readRegs2 newRegs2 calls2 r2)\n      ureadRegs unewRegs ucalls\n      (HUReadRegs: ureadRegs [=] readRegs1 ++ readRegs2)\n      (HUNewRegs: unewRegs [=] newRegs1 ++ newRegs2)\n      (HUCalls: ucalls [=] calls1 ++ calls2):\n      PSemAction (IfElse p a a' cont) ureadRegs unewRegs ucalls r2\n  | PSemDisplay\n      (ls: list (SysT type)) k (cont: ActionT type k)\n      r readRegs newRegs calls\n      (HPSemAction: PSemAction cont readRegs newRegs calls r):\n      PSemAction (Sys ls cont) readRegs newRegs calls r\n  | PSemReturn\n      k (e: Expr type (SyntaxKind k)) evale\n      (HEvalE: evale = evalExpr e)\n      readRegs newRegs calls\n      (HReadRegs: readRegs = nil)\n      (HNewRegs: newRegs = nil)\n      (HCalls: calls = nil) :\n      PSemAction (Return e) readRegs newRegs calls evale.  \nEnd Semantics.\n\n\nSection BaseModule.\n  Variable m: BaseModule.\n  Variable o: RegsT.\n  Inductive PSubsteps: list FullLabel -> Prop :=\n  | NilPSubstep (HRegs: getKindAttr o [=] getKindAttr (getRegisters m)) : PSubsteps nil\n  | PAddRule (HRegs: getKindAttr o [=] getKindAttr (getRegisters m))\n             rn rb\n             (HInRules: In (rn, rb) (getRules m))\n             reads u cs\n             (HPAction: PSemAction o (rb type) reads u cs WO)\n             (HReadsGood: SubList (getKindAttr reads)\n                                  (getKindAttr (getRegisters m)))\n             (HUpdGood: SubList (getKindAttr u)\n                                (getKindAttr (getRegisters m)))\n             l ls (HLabel: l [=] (u, (Rle rn, cs)) :: ls)\n             (HDisjRegs: forall x, In x ls -> DisjKey (fst x) u)\n             (HNoRle: forall x, In x ls -> match fst (snd x) with\n                                           | Rle _ => False\n                                           | _ => True\n                                           end)\n             (HPSubstep: PSubsteps ls):\n      PSubsteps l\n  | PAddMeth (HRegs: getKindAttr o [=] getKindAttr (getRegisters m))\n             fn fb\n             (HInMeths: In (fn, fb) (getMethods m))\n             reads u cs argV retV\n             (HPAction: PSemAction o ((projT2 fb) type argV) reads u cs retV)\n             (HReadsGood: SubList (getKindAttr reads)\n                                  (getKindAttr (getRegisters m)))\n             (HUpdGood: SubList (getKindAttr u)\n                                (getKindAttr (getRegisters m)))\n             l ls (HLabel: l [=] (u, (Meth (fn, existT _ _ (argV, retV)), cs)) :: ls )\n             (HDisjRegs: forall x, In x ls -> DisjKey (fst x) u)\n             (HPSubsteps: PSubsteps ls):\n      PSubsteps l.\n\n  Inductive PPlusSubsteps: RegsT -> list RuleOrMeth -> MethsT -> Prop :=\n  | NilPPlusSubstep (HRegs: getKindAttr o [=] getKindAttr (getRegisters m)) : PPlusSubsteps nil nil nil\n  | PPlusAddRule (HRegs: getKindAttr o [=] getKindAttr (getRegisters m))\n            rn rb\n            (HInRules: In (rn, rb) (getRules m))\n            reads u cs\n            (HPAction: PSemAction o (rb type) reads u cs WO)\n            (HReadsGood: SubList (getKindAttr reads)\n                                 (getKindAttr (getRegisters m)))\n            (HUpdGood: SubList (getKindAttr u)\n                               (getKindAttr (getRegisters m)))\n            upds execs calls oldUpds oldExecs oldCalls\n            (HUpds: upds [=] u ++ oldUpds)\n            (HExecs: execs [=] Rle rn :: oldExecs)\n            (HCalls: calls [=] cs ++ oldCalls)\n            (HDisjRegs: DisjKey oldUpds u)\n            (HNoRle: forall x, In x oldExecs -> match x with\n                                                | Rle _ => False\n                                                | _ => True\n                                                end)\n            (HPSubstep: PPlusSubsteps oldUpds oldExecs oldCalls):\n      PPlusSubsteps upds execs calls\n  | PPlusAddMeth (HRegs: getKindAttr o [=] getKindAttr (getRegisters m))\n            fn fb\n            (HInMeths: In (fn, fb) (getMethods m))\n            reads u cs argV retV\n            (HPAction: PSemAction o ((projT2 fb) type argV) reads u cs retV)\n            (HReadsGood: SubList (getKindAttr reads)\n                                 (getKindAttr (getRegisters m)))\n            (HUpdGood: SubList (getKindAttr u)\n                               (getKindAttr (getRegisters m)))\n            upds execs calls oldUpds oldExecs oldCalls\n            (HUpds: upds [=] u ++ oldUpds)\n            (HExecs: execs [=] Meth (fn, existT _ _ (argV, retV)) :: oldExecs)\n            (HCalls: calls [=] cs ++ oldCalls)\n            (HDisjRegs: DisjKey oldUpds u)\n            (HPSubstep: PPlusSubsteps oldUpds oldExecs oldCalls):\n      PPlusSubsteps upds execs calls.\nEnd BaseModule.\n\nInductive PStep: Mod -> RegsT -> list FullLabel -> Prop :=\n| PBaseStep m o l (HPSubsteps: PSubsteps m o l) (HMatching: MatchingExecCalls_Base l m):\n    PStep (Base m) o l\n| PHideMethStep m s o l (HPStep: PStep m o l)\n               (HHidden : forall v, In (s, projT1 v) (getKindAttr (getAllMethods m)) -> getListFullLabel_diff (s, v) l = 0%Z):\n    PStep (HideMeth m s) o l\n| PConcatModStep m1 m2 o1 o2 l1 l2\n                 (HPStep1: PStep m1 o1 l1)\n                 (HPStep2: PStep m2 o2 l2)\n                 (HMatching1: MatchingExecCalls_Concat l1 l2 m2)\n                 (HMatching2: MatchingExecCalls_Concat l2 l1 m1)\n                 (HNoRle: forall x y, In x l1 -> In y l2 -> match fst (snd x), fst (snd y) with\n                                                            | Rle _, Rle _ => False\n                                                            | _, _ => True\n                                                            end)\n                 o l\n                 (HRegs: o [=] o1 ++ o2)\n                 (HLabels: l [=] l1 ++ l2):\n    PStep (ConcatMod m1 m2) o l.\n\nSection PPlusStep.\n  Variable m: BaseModule.\n  Variable o: RegsT.\n  \n  Definition MatchingExecCalls_flat (calls : MethsT) (execs : list RuleOrMeth) (m : BaseModule) :=\n    forall (f : MethT),\n      In (fst f, projT1 (snd f)) (getKindAttr (getMethods m)) ->\n      (getNumFromCalls f calls <= getNumFromExecs f execs)%Z.\n  \n  Inductive PPlusStep :  RegsT -> list RuleOrMeth -> MethsT -> Prop :=\n  | BasePPlusStep upds execs calls:\n      PPlusSubsteps m o upds execs calls ->\n      MatchingExecCalls_flat calls execs m -> PPlusStep upds execs calls.\nEnd PPlusStep.\n\n\nSection Trace.\n  Variable m: Mod.\n  Definition PUpdRegs (u: list RegsT) (o o': RegsT)\n    := getKindAttr o [=] getKindAttr o' /\\\n       (forall s v, In (s, v) o' -> ((exists x, In x u /\\ In (s, v) x) \\/\n                                     ((~ exists x, In x u /\\ In s (map fst x)) /\\ In (s, v) o))).\n\n  Inductive PTrace: RegsT -> list (list FullLabel) -> Prop :=\n  | PInitTrace (o' o'' : RegsT) ls'\n               (HPerm : o' [=] o'')\n               (HUpdRegs : Forall2 regInit o'' (getAllRegisters m))\n               (HTrace: ls' = nil):\n      PTrace o' ls'\n  | PContinueTrace o ls l o' ls'\n                   (PHOldTrace: PTrace o ls)\n                   (HPStep: PStep m o l)\n                   (HPUpdRegs: PUpdRegs (map fst l) o o')\n                   (HTrace: ls' = l :: ls):\n      PTrace o' ls'.\nEnd Trace.\n\n\n\nDefinition PPlusUpdRegs (u o o' : RegsT) :=\n  getKindAttr o [=] getKindAttr o' /\\\n  (forall s v, In (s, v) o' -> In (s, v) u \\/ (~ In s (map fst u) /\\ In (s, v) o)).\n  \nSection PPlusTrace.\n  Variable m: BaseModule.\n  Inductive PPlusTrace : RegsT -> list (RegsT * ((list RuleOrMeth) * MethsT)) -> Prop :=\n  | PPlusInitTrace (o' o'' : RegsT) ls'\n                   (HPerm : o' [=] o'')\n                   (HUpdRegs : Forall2 regInit o'' (getRegisters m))\n                   (HTrace : ls' = nil):\n      PPlusTrace o' ls'\n  | PPlusContinueTrace (o o' : RegsT)\n                       (upds : RegsT)\n                       (execs : list RuleOrMeth)\n                       (calls : MethsT)\n                       (ls ls' : list (RegsT * ((list RuleOrMeth) * MethsT)))\n                       (PPlusOldTrace : PPlusTrace o ls)\n                       (HPPlusStep : PPlusStep m o upds execs calls)\n                       (HUpdRegs : PPlusUpdRegs upds o o')\n                       (HPPlusTrace : ls' = ((upds, (execs, calls))::ls)):\n      PPlusTrace o' ls'.\nEnd PPlusTrace.\n\nDefinition PTraceList (m : Mod) (ls : list (list FullLabel)) :=\n  (exists (o : RegsT), PTrace m o ls).\n\nDefinition PTraceInclusion (m m' : Mod) :=\n  forall (o : RegsT) (ls : list (list FullLabel)),\n    PTrace m o ls -> exists (ls' : list (list FullLabel)), PTraceList m' ls' /\\ WeakInclusions ls ls'.\n\nDefinition PStepSubstitute m o l :=\n  PSubsteps (BaseMod (getAllRegisters m) (getAllRules m) (getAllMethods m)) o l /\\\n  MatchingExecCalls_Base l (getFlat m) /\\\n  (forall s v, In (s, projT1 v) (getKindAttr (getAllMethods m)) ->\n               In s (getHidden m) ->\n               (getListFullLabel_diff (s, v) l = 0%Z)).\n\nDefinition StepSubstitute m o l :=\n  Substeps (BaseMod (getAllRegisters m) (getAllRules m) (getAllMethods m)) o l /\\\n  MatchingExecCalls_Base l (getFlat m) /\\\n  (forall s v, In (s, projT1 v) (getKindAttr (getAllMethods m)) ->\n               In s (getHidden m) ->\n               (getListFullLabel_diff (s, v) l = 0%Z)).\n\nDefinition InExec f (l: list (RegsT * (RuleOrMeth * MethsT))) :=\n  In (Meth f) (map getRleOrMeth l).\n\nDefinition InCall f (l: list (RegsT * (RuleOrMeth * MethsT))) :=\n  exists x, In x l /\\ In f (snd (snd x)).\n\nLemma Kind_eq: forall k, Kind_dec k k = left eq_refl.\nProof.\n  intros; destruct (Kind_dec k k).\n  - f_equal.\n    apply Eqdep_dec.UIP_dec.\n    apply Kind_dec.\n  - apply (match n eq_refl with end).\nQed.\n\n(*\nLemma Signature_eq: forall sig, Signature_dec sig sig = left eq_refl.\nProof.\n  intros; destruct (Signature_dec sig sig).\n  - f_equal.\n    apply Eqdep_dec.UIP_dec.\n    apply Signature_dec.\n  - apply (match n eq_refl with end).\nQed.\n*)\n\nSection InverseSemAction.\n  Variable o: RegsT.\n\n  Lemma inversionSemAction\n          k a reads news calls retC\n          (evalA: @SemAction o k a reads news calls retC):\n    match a with\n    | MCall m s e c =>\n      exists mret pcalls,\n      SemAction o (c mret) reads news pcalls retC /\\\n      calls = (m, (existT _ _ (evalExpr e, mret))) :: pcalls\n    | LetExpr _ e cont =>\n      SemAction o (cont (evalExpr e)) reads news calls retC\n    | LetAction _ a cont =>\n      exists reads1 news1 calls1 reads2 news2 calls2 r1,\n      DisjKey news1 news2 /\\\n      SemAction o a reads1 news1 calls1 r1 /\\\n      SemAction o (cont r1) reads2 news2 calls2 retC /\\\n      reads = reads1 ++ reads2 /\\\n      news = news1 ++ news2 /\\\n      calls = calls1 ++ calls2\n    | ReadNondet k c =>\n      exists rv,\n      SemAction o (c rv) reads news calls retC\n    | ReadReg r k c =>\n      exists rv reads2,\n      In (r, existT _ k rv) o /\\\n      SemAction o (c rv) reads2 news calls retC /\\\n      reads = (r, existT _ k rv) :: reads2\n    | WriteReg r k e a =>\n      exists pnews,\n      In (r, k) (getKindAttr o) /\\\n      key_not_In r pnews /\\\n      SemAction o a reads pnews calls retC /\\\n      news = (r, (existT _ _ (evalExpr e))) :: pnews\n    | IfElse p _ aT aF c =>\n      exists reads1 news1 calls1 reads2 news2 calls2 r1,\n      DisjKey news1 news2 /\\\n      match evalExpr p with\n      | true =>\n        SemAction o aT reads1  news1 calls1 r1 /\\\n        SemAction o (c r1) reads2 news2 calls2 retC /\\\n        reads = reads1 ++ reads2 /\\\n        news = news1 ++ news2 /\\\n        calls = calls1 ++ calls2\n      | false =>\n        SemAction o aF reads1 news1 calls1 r1 /\\\n        SemAction o (c r1) reads2 news2 calls2 retC /\\\n        reads = reads1 ++ reads2 /\\\n        news = news1 ++ news2 /\\\n        calls = calls1 ++ calls2\n      end\n    | Sys _ c =>\n      SemAction o c reads news calls retC\n    | Return e =>\n      retC = evalExpr e /\\\n      news = nil /\\\n      calls = nil /\\\n      reads = nil\n    end.\n  Proof.\n    destruct evalA; eauto; repeat eexists; try destruct (evalExpr p); eauto; try discriminate.\n  Qed.\n\n  Lemma SemActionReadsSub k a reads upds calls ret:\n    @SemAction o k a reads upds calls ret ->\n    SubList reads o.\n  Proof.\n    induction 1; auto; subst;\n      unfold SubList in *; intros;\n        rewrite ?in_app_iff in *.\n    - subst; firstorder.\n    - repeat (subst; firstorder).\n    - subst.\n      rewrite ?in_app_iff in H1.\n      destruct H1; intuition.\n    - subst.\n      rewrite ?in_app_iff in H1.\n      destruct H1; intuition.\n    - subst; simpl in *; intuition.\n  Qed.\nEnd InverseSemAction.\n\nSection evalExpr.\n\n  Lemma castBits_same ty ni no (pf: ni = no) (e: Expr ty (SyntaxKind (Bit ni))): castBits pf e = match pf in _ = Y return Expr ty (SyntaxKind (Bit Y)) with\n                                                                                                 | eq_refl => e\n                                                                                                 end.\n  Proof.\n    unfold castBits.\n    destruct pf.\n    rewrite nat_cast_same.\n    auto.\n  Qed.\n\n  Lemma evalExpr_castBits: forall ni no (pf: ni = no) (e: Expr type (SyntaxKind (Bit ni))), evalExpr (castBits pf e) =\n                                                                                            nat_cast (fun n => word n) pf (evalExpr e).\n  Proof.\n    intros.\n    unfold castBits.\n    destruct pf.\n    rewrite ?nat_cast_same.\n    auto.\n  Qed.\n\n  Lemma evalExpr_BinBit: forall kl kr k (op: BinBitOp kl kr k)\n                                (l1 l2: Expr type (SyntaxKind (Bit kl)))\n                                (r1 r2: Expr type (SyntaxKind (Bit kr))),\n    evalExpr l1 = evalExpr l2 ->\n    evalExpr r1 = evalExpr r2 ->\n    evalExpr (BinBit op l1 r1) = evalExpr (BinBit op l2 r2).\n  Proof.\n    intros.\n    induction op; simpl; try congruence.\n  Qed.\n\n  Lemma evalExpr_ZeroExtend: forall lsb msb (e1 e2: Expr type (SyntaxKind (Bit lsb))), evalExpr e1 = evalExpr e2 ->\n                                                                                       evalExpr (ZeroExtend msb e1) = evalExpr (ZeroExtend msb e2).\n  Proof.\n    intros.\n    unfold ZeroExtend.\n    erewrite evalExpr_BinBit; eauto.\n  Qed.\n\n  Lemma evalExpr_pack_Bool: forall (e1 e2: Expr type (SyntaxKind Bool)),\n      evalExpr e1 = evalExpr e2 ->\n      evalExpr (pack e1) = evalExpr (pack e2).\n  Proof.\n    intros.\n    simpl.\n    rewrite H.\n    reflexivity.\n  Qed.\n\n  Lemma evalExpr_Void (e: Expr type (SyntaxKind (Bit 0))):\n    evalExpr e = WO.\n  Proof.\n    destruct (evalExpr e).\n    arithmetizeWord; simpl in *.\n    rewrite Z.mod_1_r; lia.\n  Qed.\n\n  Lemma evalExpr_countLeadingZeros ni: forall no (e: Expr type (SyntaxKind (Bit ni))),\n      evalExpr (countLeadingZeros no e) = countLeadingZerosWord _ no (evalExpr e).\n  Proof.\n    induction ni; simpl; intros; auto.\n    rewrite evalExpr_castBits.\n    simpl.\n    unfold wzero at 2.\n    rewrite wzero_wplus.\n    match goal with\n    | |- (if getBool ?P then _ else _) = (if ?P then _ else _) => destruct P; auto\n    end.\n    repeat f_equal.\n    rewrite IHni.\n    simpl.\n    rewrite evalExpr_castBits.\n    repeat f_equal.\n  Qed.\n\n  Lemma fin_to_nat_bound : forall n (x: Fin.t n), proj1_sig (Fin.to_nat x) < n.\n  Proof.\n    induction x; cbn; try lia.\n    destruct (Fin.to_nat x); cbn in *; lia.\n  Qed.\n\n  Lemma fin_to_word_id : forall n (i : Fin.t n),\n    wordToNat (natToWord (Nat.log2_up n) (proj1_sig (Fin.to_nat i))) = proj1_sig (Fin.to_nat i).\n  Proof.\n    intros.\n    pose proof (log2_up_pow2 n); pose proof (fin_to_nat_bound i).\n    rewrite wordToNat_natToWord; lia.\n  Qed.\n\n  Lemma eval_ReadArray_in_bounds : forall A n (arr : Expr type (SyntaxKind (Array n A))) i m,\n    n <= 2 ^ m ->\n    evalExpr\n      (ReadArray arr\n        (Var type (SyntaxKind (Bit m))\n          (natToWord m (proj1_sig (Fin.to_nat i))))) =\n    evalExpr arr i.\n  Proof.\n    intros.\n    simpl.\n    pose proof (fin_to_nat_bound i).\n    rewrite Z.mod_small.\n    rewrite Nat2Z.id.\n    destruct (lt_dec (proj1_sig (to_nat i)) n); try lia.\n    unfold evalExpr at 1.\n    erewrite Fin.of_nat_ext, Fin.of_nat_to_nat_inv; eauto.\n    split; try lia. rewrite pow2_of_nat.\n    apply Nat2Z.inj_lt. lia.\n  Qed.\n\n  Corollary eval_ReadArray_in_bounds_log : forall A n (arr : Expr type (SyntaxKind (Array n A))) i,\n    evalExpr\n      (ReadArray arr\n        (Var type (SyntaxKind (Bit (Nat.log2_up n)))\n          (natToWord (Nat.log2_up n) (proj1_sig (Fin.to_nat i))))) =\n    evalExpr arr i.\n  Proof. intros; apply eval_ReadArray_in_bounds, log2_up_pow2. Qed.\n\n  Corollary eval_ReadArray_in_bounds_pow : forall A n (arr : Expr type (SyntaxKind (Array (2 ^ n) A))) i,\n    evalExpr\n      (ReadArray arr\n        (Var type (SyntaxKind (Bit n))\n          (natToWord n (proj1_sig (Fin.to_nat i))))) =\n    evalExpr arr i.\n  Proof. intros; apply eval_ReadArray_in_bounds; auto. Qed.\nEnd evalExpr.\n\n\nLemma seq_nil n m :\n  seq n m = nil ->\n  m = 0.\nProof.\n  induction m; auto; intro; exfalso.\n  rewrite seq_eq in H.\n  apply app_eq_nil in H; dest.\n  inv H0.\nQed.\n\nLemma Reduce_seq :\n  forall m n k,\n    k <= n ->\n    (map (fun x => x - k) (seq n m)) = (seq (n - k) m).\nProof.\n  induction m; intros; simpl; auto.\n  apply f_equal2; auto.\n  rewrite IHm, Nat.sub_succ_l; auto.\nQed.\n\nLemma getKindAttr_fst {A B : Type} {P : B -> Type}  {Q : B -> Type} (l1 : list (A * {x : B & P x})):\n  forall  (l2 : list (A * {x : B & Q x})),\n    getKindAttr l1 = getKindAttr l2 ->\n    (map fst l1) = (map fst l2).\nProof.\n  induction l1, l2; intros; auto; simpl in *; inv H.\n  erewrite IHl1; eauto.\nQed.\n\nLemma NoDup_app_split {A : Type} (l l' : list A) :\n  NoDup (l++l') ->\n  forall a,\n    In a l ->\n    ~ In a l'.\nProof.\n  induction l'; repeat intro;[inv H1|].\n  specialize (NoDup_remove _ _ _ H) as P0; dest.\n  inv H1; apply H3; rewrite in_app_iff; auto.\n  exfalso; eapply IHl'; eauto.\nQed.\n\nLemma KeyMatch (l1 : RegsT) :\n  NoDup (map fst l1) ->\n  forall l2,\n    map fst l1 = map fst l2 ->\n    (forall s v, In (s, v) l1 -> In (s, v) l2) ->\n    l1 = l2.\nProof.\n  induction l1; intros.\n  - destruct l2; inv H0; auto.\n  - destruct a; simpl in *.\n    destruct l2; inv H0.\n    destruct p; simpl in *.\n    inv H.\n    specialize (H1 _ _ (or_introl (eq_refl))) as TMP; destruct TMP.\n    + rewrite H in *.\n      assert (forall s v, In (s, v) l1 -> In (s, v) l2).\n      { intros.\n        destruct (H1 _ _ (or_intror H0)); auto.\n        exfalso.\n        inv H2.\n        apply H3.\n        rewrite in_map_iff.\n        exists (s2, v); auto.\n      }\n      rewrite (IHl1 H5 _ H4 H0).\n      reflexivity.\n    + exfalso.\n      apply H3.\n      rewrite H4, in_map_iff.\n      exists (s, s0); auto.\nQed.\n\nLemma seq_app' s e :\n  forall m (Hm_lte_e : m <= e),\n    seq s e = seq s m ++ seq (s + m) (e - m).\nProof.\n  induction e; intros.\n  - rewrite Nat.le_0_r in *; subst; simpl; reflexivity.\n  - destruct (le_lt_or_eq _ _ Hm_lte_e).\n    + rewrite Nat.sub_succ_l; [|lia].\n      repeat rewrite seq_eq.\n      assert (s + m + (e - m) = s + e) as P0.\n      { lia. }\n      rewrite (IHe m), app_assoc, P0; auto.\n      lia.\n    + rewrite <- H.\n      rewrite Nat.sub_diag, app_nil_r; reflexivity.\nQed.\n\nLemma fst_getKindAttr {A B : Type} {P : B -> Type} (l : list (A * {x : B & P x})) :\n  map fst (getKindAttr l) = map fst l.\nProof.\n  induction l; simpl; auto.\n  rewrite IHl; reflexivity.\nQed.\n\nLemma key_not_In_app {A B : Type} (key : A) (ls1 ls2 : list (A * B)):\n  key_not_In key (ls1 ++ ls2) ->\n  key_not_In key ls1 /\\ key_not_In key ls2.\nProof.\n  induction ls1; simpl; intros; split;\n    repeat intro; auto; eapply H; eauto; simpl; rewrite in_app_iff; eauto.\n  inv H0; eauto.\nQed.\n\nLemma key_not_In_app_iff {A B : Type} (key : A) (ls1 ls2 : list (A * B)):\n  key_not_In key (ls1 ++ ls2) <-> key_not_In key ls1 /\\ key_not_In key ls2.\nProof.\n  split; eauto using key_not_In_app.\n  repeat intro; dest.\n  rewrite in_app_iff in H0.\n  destruct H0.\n  - eapply H; eauto.\n  - eapply H1; eauto.\nQed.\n\nLemma existsb_nexists_str str l :\n  existsb (String.eqb str) l = false <->\n  ~ In str l.\nProof.\n  split; repeat intro.\n  - assert (exists x, In x l /\\ (String.eqb str) x = true) as P0.\n    { exists str; split; auto. apply String.eqb_refl. }\n    rewrite <- existsb_exists in P0; rewrite P0 in *; discriminate.\n  - remember (existsb _ _) as exb; symmetry in Heqexb; destruct exb; auto.\n    exfalso; rewrite existsb_exists in Heqexb; dest.\n    rewrite String.eqb_eq in *; subst; auto.\nQed.\n\nLemma nth_error_map_None_iff :\n  forall {A B : Type} (f : A -> B) (l : list A) (n : nat),\n    nth_error l n = None <-> nth_error (map f l) n = None.\nProof.\n  intros; split; intros; rewrite nth_error_None, map_length in *; assumption.\nQed.\n\nLemma nth_error_map_Some1 :\n  forall {A B : Type} (f : A -> B) (l : list A) (b : B) (n : nat),\n    nth_error (map f l) n = Some b -> exists a, nth_error l n = Some a /\\ (f a = b).\nProof.\n  intros.\n  specialize (nth_error_map f (fun b => nth_error (map f l) n = Some b) n l) as P0.\n  rewrite H in P0.\n  remember (nth_error l _) as err0; symmetry in Heqerr0; destruct err0.\n  - exists a; split; auto.\n    destruct P0 as [P0 P1].\n    specialize (P0 eq_refl); inv P0; reflexivity.\n  - exfalso.\n    rewrite nth_error_None in Heqerr0.\n    enough (Some b <> None).\n    { eapply H0; rewrite <- H.\n      rewrite nth_error_None, map_length; assumption. }\n    intro; discriminate.\nQed.\n\nLemma nth_error_map_Some2 :\n  forall {A B : Type} (f : A -> B) (l : list A) (b : B) (n : nat),\n    (exists a, nth_error l n = Some a /\\ (f a = b)) -> nth_error (map f l) n = Some b.\nProof.\n  intros; dest.\n  rewrite <- H0; eapply map_nth_error; eauto.\nQed.\n\nLemma nth_error_map_iff :\n  forall {A B : Type} (f : A -> B) (l : list A) (b : B) (n : nat),\n    nth_error (map f l) n = Some b <-> (exists a, nth_error l n = Some a /\\ (f a = b)).\nProof.\n  repeat red; intros; dest; eauto using nth_error_map_Some1, nth_error_map_Some2.\nQed.\n\nLemma nth_error_nil_None :\n  forall {A : Type} (n : nat),\n    nth_error (nil : list A) n = None.\nProof.\n  intros; rewrite nth_error_None; simpl; lia.\nQed.\n\nLemma SubList_map_iff  {A B : Type} (f : A -> B) (l' : list B) :\n  forall (l : list A),\n    SubList l' (map f l) <->\n    exists l'',\n      SubList l'' l /\\\n      (map f l'' = l').\nProof.\n  intros; split.\n  - induction l'; simpl; intros.\n    + exists nil; simpl; split; repeat intro; auto.\n      destruct l; auto.\n      exfalso; inv H0.\n    + unfold SubList in *; simpl in *.\n      specialize (IHl' (ltac : (eauto))); dest.\n      specialize (H _ (or_introl eq_refl)); rewrite in_map_iff in H; dest.\n      exists (x0 :: x); split; intros; [inv H3; auto|].\n      simpl; apply f_equal2; assumption.\n  - repeat intro; dest.\n    rewrite <- H1 in H0.\n    rewrite in_map_iff in *; dest.\n    specialize (H _ H2).\n    exists x1; split; assumption.\nQed.\n\nLemma KeyPair_Equiv {A B : Type} (l : list (A * B)) :\n  NoDup (map fst l) ->\n  forall l',\n    SubList l l' ->\n    map fst l = map fst l' ->\n    l = l'.\nProof.\n  induction l; simpl; intros.\n  - rewrite (map_eq_nil _ _ (eq_sym H1)); reflexivity.\n  - destruct l'; [discriminate|].\n    apply f_equal2; simpl in *.\n    + assert (In a (p :: l')).\n      { apply H0; left; reflexivity. }\n      inv H2; eauto.\n      exfalso.\n      apply (in_map fst) in H3; rewrite H1 in H; inv H1.\n      rewrite <- H4 in H; inv H; contradiction.\n    + enough (SubList l l').\n      { inv H; inv H1; eapply IHl; eauto. }\n      repeat intro.\n      specialize (H0 _ (in_cons _ _ _ H2)).\n      inv H0; eauto.\n      exfalso.\n      apply (in_map fst) in H2.\n      inv H1; rewrite H3 in H; inv H; contradiction.\nQed.\n\nLemma getNumCalls_nil f :\n  getNumCalls f nil = 0%Z.\nProof.\n  reflexivity.\nQed.\n\nLemma getNumExecs_nil f :\n  getNumExecs f nil = 0%Z.\nProof.\n  reflexivity.\nQed.\n\nLemma getNumFromCalls_eq_cons f g l :\n  f = g ->\n  getNumFromCalls f (g::l) = (1 + (getNumFromCalls f l))%Z.\nProof.\n  intro;unfold getNumFromCalls; destruct MethT_dec; auto; contradiction.\nQed.\n\nLemma getNumFromCalls_neq_cons f g l :\n  f <> g ->\n  getNumFromCalls f (g::l) = getNumFromCalls f l.\nProof.\n  intro; unfold getNumFromCalls; destruct MethT_dec; auto; contradiction.\nQed.\n\nOpaque getNumFromCalls.\nLemma getNumFromCalls_app f l1:\n  forall l2,\n  getNumFromCalls f (l1++l2) = (getNumFromCalls f l1 + getNumFromCalls f l2)%Z.\nProof.\n  induction l1.\n  - simpl; reflexivity.\n  - intros.\n    destruct (MethT_dec f a).\n    + simpl; repeat rewrite getNumFromCalls_eq_cons; auto.\n      rewrite IHl1; ring.\n    + simpl; repeat rewrite getNumFromCalls_neq_cons; auto.\nQed.\nTransparent getNumFromCalls.\n\nCorollary getNumCalls_app f l1 :\n  forall l2,\n    getNumCalls f (l1 ++ l2) = (getNumCalls f l1 + getNumCalls f l2)%Z.\nProof.\n  unfold getNumCalls.\n  intro.\n  rewrite map_app, concat_app, getNumFromCalls_app.\n  reflexivity.\nQed.\n\nLemma getNumCalls_cons f a l :\n  getNumCalls f (a::l) = ((getNumFromCalls f (snd (snd a))) + getNumCalls f l)%Z.\nProof.\n  unfold getNumCalls.\n  simpl; rewrite getNumFromCalls_app; reflexivity.\nQed.\nTransparent getNumFromCalls.\n\nLemma getNumFromCalls_nonneg f l :\n  (0 <= getNumFromCalls f l)%Z.\nProof.\n  induction l.\n  - unfold getNumFromCalls; reflexivity.\n  - destruct (MethT_dec f a);[rewrite getNumFromCalls_eq_cons; auto| rewrite getNumFromCalls_neq_cons; auto].\n    Omega.omega.\nQed.\n\nLemma getNumCalls_nonneg f l:\n  (0 <= (getNumCalls f l))%Z.\nProof.\n  induction l.\n  - rewrite getNumCalls_nil;reflexivity.\n  - rewrite getNumCalls_cons.\n    specialize (getNumFromCalls_nonneg f (snd (snd a))) as B1.\n    Omega.omega.\nQed.\n    \nLemma getNumFromExecs_eq_cons f g l :\n  f = g ->\n  getNumFromExecs f ((Meth g)::l) = (1 + (getNumFromExecs f l))%Z.\nProof.\n  intros; simpl; destruct (MethT_dec f g); auto; contradiction.\nQed.\n\nLemma getNumFromExecs_neq_cons f g l :\n  f <> g ->\n  getNumFromExecs f ((Meth g)::l) = (getNumFromExecs f l).\nProof.\n  intros; simpl; destruct (MethT_dec f g); auto; contradiction.\nQed.\n\nLemma getNumFromExecs_Rle_cons f rn l:\n  getNumFromExecs f ((Rle rn)::l) = (getNumFromExecs f l).\nProof.\n  intros; simpl; reflexivity.\nQed.\n\nOpaque getNumFromExecs.\nLemma getNumFromExecs_app f l1:\n  forall l2,\n    getNumFromExecs f (l1++l2) = (getNumFromExecs f l1 + getNumFromExecs f l2)%Z.\nProof.\n  induction l1.\n  - simpl; reflexivity.\n  - intros; destruct a;[|destruct (MethT_dec f f0)];simpl.\n    + repeat rewrite getNumFromExecs_Rle_cons; apply IHl1.\n    + repeat rewrite getNumFromExecs_eq_cons; auto.\n      rewrite IHl1; ring.\n    + repeat rewrite getNumFromExecs_neq_cons; auto.\nQed.\nTransparent getNumFromExecs.\n\nCorollary getNumExecs_app f l1 :\n  forall l2,\n    getNumExecs f (l1++l2) = (getNumExecs f l1 + getNumExecs f l2)%Z.\nProof.\n  unfold getNumExecs.\n  intros;rewrite map_app, getNumFromExecs_app; reflexivity.\nQed.\n\nLemma getNumFromExecs_nonneg f l:\n  (0 <= (getNumFromExecs f l))%Z.\nProof.\n  induction l.\n  - simpl; reflexivity.\n  - destruct a;[rewrite getNumFromExecs_Rle_cons\n               |destruct (MethT_dec f f0);[rewrite getNumFromExecs_eq_cons\n                                          |rewrite getNumFromExecs_neq_cons]]; auto; Omega.omega.\nQed.\n\nCorollary getNumExecs_nonneg f l :\n  (0 <= (getNumExecs f l))%Z.\nProof.\n  unfold getNumExecs;apply getNumFromExecs_nonneg.\nQed.\n\nLemma getNumFromCalls_perm f l l':\n  l [=] l' ->\n  getNumFromCalls f l = getNumFromCalls f l'.\nProof.\n  induction 1; auto.\n  - destruct (MethT_dec f x);[repeat rewrite getNumFromCalls_eq_cons| repeat rewrite getNumFromCalls_neq_cons];auto.\n    rewrite IHPermutation; reflexivity.\n  - destruct (MethT_dec f x), (MethT_dec f y).\n    + repeat rewrite getNumFromCalls_eq_cons; auto.\n    + rewrite getNumFromCalls_neq_cons, getNumFromCalls_eq_cons, getNumFromCalls_eq_cons, getNumFromCalls_neq_cons ; auto.\n    + rewrite getNumFromCalls_eq_cons, getNumFromCalls_neq_cons, getNumFromCalls_neq_cons, getNumFromCalls_eq_cons ; auto.\n    + repeat rewrite getNumFromCalls_neq_cons; auto.\n  - rewrite IHPermutation1, IHPermutation2; reflexivity.\nQed.\n\nGlobal Instance getNumFromCalls_perm_rewrite' :\n  Proper (eq ==> @Permutation (MethT) ==> eq) (@getNumFromCalls) | 10.\nProof.\n  repeat red; intros; subst; eauto using getNumFromCalls_perm.\nQed.\n\nLemma concat_perm_rewrite (A : Type) (l l' : list (list A)):\n  l [=] l' ->\n  concat l [=] concat l'.\nProof.\n  induction 1.\n  - reflexivity.\n  - simpl; rewrite IHPermutation; reflexivity.\n  - simpl; repeat rewrite app_assoc.\n    apply Permutation_app_tail, Permutation_app_comm.\n  - eauto using Permutation_trans.\nQed.\n\nGlobal Instance concat_perm_rewrite' {A : Type}:\n  Proper (@Permutation (list A) ==> @Permutation A) (@concat A) | 10.\nProof.\n  repeat red; eauto using concat_perm_rewrite.\nQed.\n\nCorollary getNumCalls_perm_rewrite f l l':\n  l [=] l' ->\n  getNumCalls f l = getNumCalls f l'.\nProof.\n  unfold getNumCalls.\n  intros; rewrite H; reflexivity.\nQed.\n\nGlobal Instance getNumCalls_perm_rewrite' :\n  Proper (eq ==> @Permutation FullLabel ==> eq) (@getNumCalls) | 10.\nProof.\n  repeat red; intros; subst; eauto using getNumCalls_perm_rewrite.\nQed.\n\nLemma getNumFromExecs_perm f l l':\n  l [=] l' ->\n  getNumFromExecs f l = getNumFromExecs f l'.\nProof.\n  induction 1; auto.\n  - destruct x;[repeat rewrite getNumFromExecs_Rle_cons;rewrite IHPermutation; reflexivity|].\n    destruct (MethT_dec f f0);[repeat rewrite getNumFromExecs_eq_cons| repeat rewrite getNumFromExecs_neq_cons];auto.\n    rewrite IHPermutation; reflexivity.\n  - destruct x, y.\n    + repeat rewrite getNumFromExecs_Rle_cons; reflexivity.\n    + destruct (MethT_dec f f0).\n      * rewrite getNumFromExecs_eq_cons, getNumFromExecs_Rle_cons, getNumFromExecs_Rle_cons, getNumFromExecs_eq_cons; auto.\n      * rewrite getNumFromExecs_neq_cons, getNumFromExecs_Rle_cons, getNumFromExecs_Rle_cons, getNumFromExecs_neq_cons; auto.\n    + destruct (MethT_dec f f0).\n      * rewrite getNumFromExecs_eq_cons, getNumFromExecs_Rle_cons, getNumFromExecs_Rle_cons, getNumFromExecs_eq_cons; auto.\n      * rewrite getNumFromExecs_neq_cons, getNumFromExecs_Rle_cons, getNumFromExecs_Rle_cons, getNumFromExecs_neq_cons; auto.\n    + destruct (MethT_dec f f0), (MethT_dec f f1).\n      * repeat rewrite getNumFromExecs_eq_cons; auto.\n      * rewrite getNumFromExecs_neq_cons, getNumFromExecs_eq_cons, getNumFromExecs_eq_cons, getNumFromExecs_neq_cons; auto.\n      * rewrite getNumFromExecs_eq_cons, getNumFromExecs_neq_cons, getNumFromExecs_neq_cons, getNumFromExecs_eq_cons; auto.\n      * repeat rewrite getNumFromExecs_neq_cons; auto.\n  - eauto using eq_trans.\nQed.\n\nGlobal Instance getNumFromExecs_perm_rewrite' :\n  Proper (eq ==> @Permutation RuleOrMeth ==> eq) (@getNumFromExecs) | 10.\nProof.\n  repeat red; intros; subst; eauto using getNumFromExecs_perm.\nQed.\n\nCorollary getNumExecs_perm_rewrite f l l':\n  l [=] l' ->\n  getNumExecs f l = getNumExecs f l'.\nProof.\n  intros; unfold getNumExecs; rewrite H; reflexivity.\nQed.\n\nGlobal Instance getNumExecs_perm_rewrite' :\n  Proper (eq ==> @Permutation FullLabel ==> eq) (@getNumExecs) | 10.\nProof.\n  repeat red; intros; subst; eauto using getNumExecs_perm_rewrite.\nQed.\n\nDefinition UpdRegs' (u: list RegsT) (o o': RegsT)\n  := map fst o = map fst o' /\\\n     (forall s v, In (s, v) o' -> ((exists x, In x u /\\ In (s, v) x) \\/\n                                   ((~ exists x, In x u /\\ In s (map fst x)) /\\ In (s, v) o))).\n\n\nLemma UpdRegs_same: forall u o o', UpdRegs u o o' -> UpdRegs' u o o'.\nProof.\n  unfold UpdRegs, UpdRegs'.\n  intros; dest.\n  apply (f_equal (map fst)) in H.\n  rewrite ?map_map in H; simpl in *.\n  setoid_rewrite (functional_extensionality (fun x => fst x) fst) in H; tauto.\nQed.\n\n\nLemma getKindAttr_map_fst A (P Q: A -> Type)\n  : forall (l2: list (Attribute (sigT P))) (l1: list (Attribute (sigT Q))),\n    getKindAttr l1 = getKindAttr l2 ->\n    map fst l1 = map fst l2.\nProof.\n  induction l2; simpl; auto; intros.\n  - apply map_eq_nil in H; subst; auto.\n  - destruct l1; simpl in *.\n    + discriminate.\n    + inv H; f_equal.\n      apply IHl2; auto.\nQed.\n\nLemma Step_getAllRegisters m o l:\n  Step m o l ->\n  getKindAttr o = getKindAttr (getAllRegisters m).\nProof.\n  induction 1; auto; simpl.\n  - inv HSubsteps; auto.\n  - rewrite map_app.\n    rewrite <- IHStep1, <- IHStep2, HRegs.\n    rewrite map_app.\n    auto.\nQed.\n\nLemma Step_getAllRegisters_fst m o l:\n  Step m o l ->\n  map fst o = map fst (getAllRegisters m).\nProof.\n  intros.\n  apply Step_getAllRegisters in H.\n  eapply getKindAttr_map_fst; eauto.\nQed.\n\nLemma DisjRegs_1_id (l1: list RegInitT):\n  forall l2 (o1 o2: RegsT),\n    DisjKey l1 l2 ->\n    map fst o1 = map fst l1 ->\n    map fst o2 = map fst l2 ->\n    filter (fun x => id (getBool (in_dec string_dec (fst x) (map fst l1)))) (o1 ++ o2) = o1.\nProof.\n  intros.\n  rewrite filter_app.\n  rewrite <- H0.\n  erewrite filter_in_dec_map.\n  erewrite filter_not_in_dec_map.\n  - rewrite app_nil_r; auto.\n  - unfold DisjKey in *; intros.\n    specialize (H k).\n    firstorder congruence.\nQed.\n  \nLemma DisjRegs_1_negb (l1: list RegInitT):\n  forall l2 (o1 o2: RegsT),\n    DisjKey l1 l2 ->\n    map fst o1 = map fst l1 ->\n    map fst o2 = map fst l2 ->\n    filter (fun x => negb (getBool (in_dec string_dec (fst x) (map fst l1)))) (o1 ++ o2) = o2.\nProof.\n  intros.\n  rewrite filter_app.\n  rewrite <- H0.\n  erewrite filter_negb_in_dec_map.\n  erewrite filter_negb_not_in_dec_map.\n  - auto.\n  - unfold DisjKey in *; intros.\n    specialize (H k).\n    firstorder congruence.\nQed.\n  \nLemma DisjRegs_2_id (l1: list RegInitT):\n  forall l2 (o1 o2: RegsT),\n    DisjKey l1 l2 ->\n    map fst o1 = map fst l1 ->\n    map fst o2 = map fst l2 ->\n    filter (fun x => id (getBool (in_dec string_dec (fst x) (map fst l2)))) (o1 ++ o2) = o2.\nProof.\n  intros.\n  rewrite filter_app.\n  rewrite <- H1.\n  erewrite filter_in_dec_map.\n  erewrite filter_not_in_dec_map.\n  - rewrite ?app_nil_r; auto.\n  - unfold DisjKey in *; intros.\n    specialize (H k).\n    firstorder congruence.\nQed.\n  \nLemma DisjRegs_2_negb (l1: list RegInitT):\n  forall l2 (o1 o2: RegsT),\n    DisjKey l1 l2 ->\n    map fst o1 = map fst l1 ->\n    map fst o2 = map fst l2 ->\n    filter (fun x => negb (getBool (in_dec string_dec (fst x) (map fst l2)))) (o1 ++ o2) = o1.\nProof.\n  intros.\n  rewrite filter_app.\n  rewrite <- H1.\n  erewrite filter_negb_in_dec_map.\n  erewrite filter_negb_not_in_dec_map.\n  - rewrite ?app_nil_r; auto.\n  - unfold DisjKey in *; intros.\n    specialize (H k).\n    firstorder congruence.\nQed.\n\nLemma Substeps_rm_In m o l:\n  Substeps m o l ->\n  forall fv, In fv l ->\n             match fst (snd fv) with\n             | Rle r => getBool (in_dec string_dec r (map fst (getRules m)))\n             | Meth (f, v) => getBool (in_dec string_dec f (map fst (getMethods m)))\n             end = true.\nProof.\n  induction 1; simpl; intros; subst; try tauto.\n  - simpl in *.\n    destruct H0.\n    + inv H0.\n      simpl.\n      destruct (in_dec string_dec rn (map fst (getRules m))); simpl; auto.\n      exfalso; apply (n (in_map fst _ _ HInRules)).\n    + eapply IHSubsteps; eauto.\n  - simpl in *.\n    destruct H0.\n    + inv H0.\n      simpl.\n      destruct (in_dec string_dec fn (map fst (getMethods m))); simpl; auto.\n      exfalso; apply (n (in_map fst _ _ HInMeths)).\n    + eapply IHSubsteps; eauto.\nQed.\n\nLemma Step_rm_In m o l:\n  Step m o l ->\n  forall fv, In fv l ->\n             match fst (snd fv) with\n             | Rle r => getBool (in_dec string_dec r (map fst (getAllRules m)))\n             | Meth (f, v) => getBool (in_dec string_dec f (map fst (getAllMethods m)))\n             end = true.\nProof.\n  induction 1; simpl; auto; intros.\n  - eapply Substeps_rm_In; eauto.\n  - subst.\n    specialize (IHStep1 fv).\n    specialize (IHStep2 fv).\n    rewrite ?map_app, in_app_iff in *.\n    destruct fv as [? [b ?]]; simpl; auto.\n    destruct b as [b | b]; auto; simpl in *; [| destruct b];\n      match goal with\n      | |- getBool ?P = _ => destruct P\n      end; simpl; auto;\n        rewrite in_app_iff in *.\n    + destruct (in_dec string_dec b (map fst (getAllRules m1))),\n      (in_dec string_dec b (map fst (getAllRules m2))); simpl in *; tauto.\n    + destruct (in_dec string_dec s (map fst (getAllMethods m1))),\n      (in_dec string_dec s (map fst (getAllMethods m2))); simpl in *; tauto.\nQed.\n\nLemma Substeps_rm_not_In m1 m2 o l:\n  DisjKey (getAllRules m1) (getRules m2) ->\n  DisjKey (getAllMethods m1) (getMethods m2) ->\n  Substeps m2 o l ->\n  forall fv, In fv l ->\n             match fst (snd fv) with\n             | Rle r => getBool (in_dec string_dec r (map fst (getAllRules m1)))\n             | Meth (f, v) => getBool (in_dec string_dec f (map fst (getAllMethods m1)))\n             end = false.\nProof.\n  intros DisjRules DisjMeths.\n  induction 1; simpl; auto; intros; subst; try tauto.\n  - destruct H0.\n    + inv H0.\n      simpl.\n      destruct (in_dec string_dec rn (map fst (getAllRules m1))); simpl; auto.\n      apply (in_map fst) in HInRules.\n      clear - DisjRules DisjMeths HInRules i.\n      specialize (DisjRules rn); specialize (DisjMeths rn); tauto.\n    + eapply IHSubsteps; eauto.\n  - simpl in *.\n    destruct H0.\n    + inv H0.\n      simpl.\n      destruct (in_dec string_dec fn (map fst (getAllMethods m1))); simpl; auto.\n      apply (in_map fst) in HInMeths.\n      clear - DisjRules DisjMeths HInMeths i.\n      specialize (DisjRules fn); specialize (DisjMeths fn); tauto.\n    + eapply IHSubsteps; eauto.\nQed.\n\nLemma Step_rm_not_In m1 m2 o l:\n  DisjKey (getAllRules m1) (getAllRules m2) ->\n  DisjKey (getAllMethods m1) (getAllMethods m2) ->\n  Step m2 o l ->\n  forall fv, In fv l ->\n             match fst (snd fv) with\n             | Rle r => getBool (in_dec string_dec r (map fst (getAllRules m1)))\n             | Meth (f, v) => getBool (in_dec string_dec f (map fst (getAllMethods m1)))\n             end = false.\nProof.\n  intros DisjRules DisjMeths.\n  induction 1; simpl; auto; intros.\n  - eapply Substeps_rm_not_In; eauto.\n  - subst.\n    assert (sth1: DisjKey (getAllRules m1) (getAllRules m0)) by\n        (clear - DisjRules; unfold DisjKey in *; simpl in *;\n         rewrite ?map_app in *; setoid_rewrite in_app_iff in DisjRules; firstorder fail).\n    assert (sth2: DisjKey (getAllMethods m1) (getAllMethods m0)) by\n    (clear - DisjMeths; unfold DisjKey in *; simpl in *; intro k;\n        rewrite ?map_app in *; specialize (DisjMeths k); rewrite in_app_iff in DisjMeths;\n          tauto).\n    assert (sth3: DisjKey (getAllRules m1) (getAllRules m2)) by\n        (clear - DisjRules; unfold DisjKey in *; simpl in *; intro k;\n        rewrite ?map_app in *; specialize (DisjRules k); rewrite in_app_iff in DisjRules;\n          tauto).\n    assert (sth4: DisjKey (getAllMethods m1) (getAllMethods m2)) by\n        (clear - DisjMeths; unfold DisjKey in *; simpl in *; intro k;\n        rewrite ?map_app in *; specialize (DisjMeths k); rewrite in_app_iff in DisjMeths;\n          tauto).\n    specialize (IHStep1 sth1 sth2 fv).\n    specialize (IHStep2 sth3 sth4 fv).\n    rewrite ?map_app, in_app_iff in *.\n    destruct fv as [? [b ?]]; simpl; auto.\n    destruct b as [b | b]; auto; simpl in *; [| destruct b];\n      match goal with\n      | |- getBool ?P = _ => destruct P\n      end; simpl; auto;\n        rewrite ?in_app_iff in *; simpl in *;\n          clear - IHStep1 IHStep2 H1; firstorder fail.\nQed.\n  \nLemma DisjMeths_1_id m1 o1 l1 m2 o2 l2:\n  DisjKey (getAllRules m1) (getAllRules m2) ->\n  DisjKey (getAllMethods m1) (getAllMethods m2) ->\n  Step m1 o1 l1 ->\n  Step m2 o2 l2 ->\n  filterExecs id m1 (l1 ++ l2) = l1.\nProof.\n  intros DisjRules DisjMeths Step1 Step2.\n  unfold filterExecs, id.\n  rewrite filter_app.\n  rewrite filter_true_list at 1.\n  - rewrite filter_false_list at 1.\n    + rewrite ?app_nil_r; auto.\n    + eapply Step_rm_not_In; eauto.\n  - eapply Step_rm_In; eauto.\nQed.\n  \nLemma DisjMeths_2_id m1 o1 l1 m2 o2 l2:\n  DisjKey (getAllRules m1) (getAllRules m2) ->\n  DisjKey (getAllMethods m1) (getAllMethods m2) ->\n  Step m1 o1 l1 ->\n  Step m2 o2 l2 ->\n  filterExecs id m2 (l1 ++ l2) = l2.\nProof.\n  intros DisjRules DisjMeths Step1 Step2.\n  unfold filterExecs, id.\n  rewrite filter_app.\n  rewrite filter_false_list at 1.\n  - rewrite filter_true_list at 1.\n    + rewrite ?app_nil_r; auto.\n    + eapply Step_rm_In; eauto.\n  - eapply Step_rm_not_In; eauto.\n    + clear - DisjRules; firstorder fail.\n    + clear - DisjMeths; intro k; specialize (DisjMeths k); tauto.\nQed.\n  \nLemma DisjMeths_1_negb m1 o1 l1 m2 o2 l2:\n  DisjKey (getAllRules m1) (getAllRules m2) ->\n  DisjKey (getAllMethods m1) (getAllMethods m2) ->\n  Step m1 o1 l1 ->\n  Step m2 o2 l2 ->\n  filterExecs negb m1 (l1 ++ l2) = l2.\nProof.\n  intros DisjRules DisjMeths Step1 Step2.\n  unfold filterExecs, id.\n  rewrite filter_app.\n  rewrite filter_false_list at 1.\n  - rewrite filter_true_list at 1.\n    + rewrite ?app_nil_r; auto.\n    + setoid_rewrite negb_true_iff.\n      eapply Step_rm_not_In; eauto.\n  - setoid_rewrite negb_false_iff.\n    eapply Step_rm_In; eauto.\nQed.\n  \nLemma DisjMeths_2_negb m1 o1 l1 m2 o2 l2:\n  DisjKey (getAllRules m1) (getAllRules m2) ->\n  DisjKey (getAllMethods m1) (getAllMethods m2) ->\n  Step m1 o1 l1 ->\n  Step m2 o2 l2 ->\n  filterExecs negb m2 (l1 ++ l2) = l1.\nProof.\n  intros DisjRules DisjMeths Step1 Step2.\n  unfold filterExecs, id.\n  rewrite filter_app.\n  rewrite filter_true_list at 1.\n  - rewrite filter_false_list at 1.\n    + rewrite ?app_nil_r; auto.\n    + setoid_rewrite negb_false_iff.\n      eapply Step_rm_In; eauto.\n  - setoid_rewrite negb_true_iff.\n    eapply Step_rm_not_In; eauto.\n    + clear - DisjRules; firstorder fail.\n    + clear - DisjMeths; intro k; specialize (DisjMeths k); tauto.\nQed.\n\nLemma Substeps_upd_SubList_key m o l:\n  Substeps m o l ->\n  forall x s v, In x (map fst l) ->\n                In (s, v) x ->\n                In s (map fst (getRegisters m)).\nProof.\n  induction 1; intros.\n  - simpl in *; tauto.\n  - subst.\n    destruct H0; subst; simpl in *.\n    + apply (in_map (fun x => (fst x, projT1 (snd x)))) in H1; simpl in *.\n      specialize (HUpdGood _ H1).\n      apply (in_map fst) in HUpdGood.\n      rewrite map_map in HUpdGood.\n      simpl in *.\n      setoid_rewrite (functional_extensionality (fun x => fst x) fst) in HUpdGood; auto.\n    + eapply IHSubsteps; eauto.\n  - subst.\n    destruct H0; subst; simpl in *.\n    + apply (in_map (fun x => (fst x, projT1 (snd x)))) in H1; simpl in *.\n      specialize (HUpdGood _ H1).\n      apply (in_map fst) in HUpdGood.\n      rewrite map_map in HUpdGood.\n      simpl in *.\n      setoid_rewrite (functional_extensionality (fun x => fst x) fst) in HUpdGood; auto.\n    + eapply IHSubsteps; eauto.\nQed.\n\nLemma Substeps_upd_In m o l:\n  Substeps m o l ->\n  forall x, In x (map fst l) ->\n            forall s: string, In s (map fst x) ->\n                              In s (map fst (getRegisters m)).\nProof.\n  intros.\n  rewrite in_map_iff in H1; dest; subst.\n  destruct x0; simpl.\n  eapply Substeps_upd_SubList_key; eauto.\nQed.\n\nLemma Substeps_read m o l:\n  Substeps m o l ->\n  forall s v, In (s, v) o ->\n              In s (map fst (getRegisters m)).\nProof.\n  induction 1; intros.\n  - apply (f_equal (map fst)) in HRegs.\n    rewrite ?map_map in *.\n    setoid_rewrite (functional_extensionality (fun x => fst x) fst) in HRegs; auto.\n    apply (in_map fst) in H.\n    simpl in *.\n    congruence.\n  - subst.\n    apply (f_equal (map fst)) in HRegs.\n    rewrite ?map_map in *.\n    setoid_rewrite (functional_extensionality (fun x => fst x) fst) in HRegs; auto.\n    apply (in_map fst) in H0.\n    simpl in *.\n    congruence.\n  - subst.\n    apply (f_equal (map fst)) in HRegs.\n    rewrite ?map_map in *.\n    setoid_rewrite (functional_extensionality (fun x => fst x) fst) in HRegs; auto.\n    apply (in_map fst) in H0.\n    simpl in *.\n    congruence.\nQed.\n  \nLemma Step_upd_SubList_key m o l:\n  Step m o l ->\n  forall x s v, In x (map fst l) ->\n                In (s, v) x ->\n                In s (map fst (getAllRegisters m)).\nProof.\n  induction 1; intros.\n  - eapply Substeps_upd_SubList_key; eauto.\n  - eapply IHStep; eauto.\n  - simpl.\n    subst.\n    rewrite map_app in *.\n    rewrite in_app_iff in *.\n    specialize (IHStep1 x s v).\n    specialize (IHStep2 x s v).\n    tauto.\nQed.\n\nLemma Step_read m o l:\n  Step m o l ->\n  forall s v, In (s, v) o ->\n              In s (map fst (getAllRegisters m)).\nProof.\n  induction 1; intros.\n  - eapply Substeps_read; eauto.\n  - eapply IHStep; eauto.\n  - simpl.\n    subst.\n    rewrite map_app in *.\n    rewrite in_app_iff in *.\n    specialize (IHStep1 s v).\n    specialize (IHStep2 s v).\n    tauto.\nQed.\n \nLemma Forall2_impl A B (P Q: A -> B -> Prop):\n  (forall a b, P a b -> Q a b) ->\n  forall la lb,\n    Forall2 P la lb ->\n    Forall2 Q la lb.\nProof.\n  induction la; destruct lb; simpl; auto; intros.\n  - inv H0; tauto.\n  - inv H0; tauto.\n  - inv H0; constructor; firstorder fail.\nQed.\n\nLemma Forall2_map_eq A B C (f: A -> C) (g: B -> C):\n  forall la lb,\n    Forall2 (fun a b => f a = g b) la lb ->\n    map f la = map g lb.\nProof.\n  induction la; destruct lb; simpl; auto; intros.\n  - inv H.\n  - inv H.\n  - inv H.\n    f_equal; firstorder fail.\nQed.\n\nLemma Forall2_app_eq_length A B (P: A -> B -> Prop) :\n  forall l1a l2a l1b l2b,\n    Forall2 P (l1a ++ l2a) (l1b ++ l2b) ->\n    length l1a = length l1b ->\n    Forall2 P l1a l1b /\\\n    Forall2 P l2a l2b.\nProof.\n  induction l1a; simpl; auto; intros.\n  - apply eq_sym in H0.\n    rewrite length_zero_iff_nil in H0.\n    subst; simpl in *.\n    split; auto.\n  - destruct l1b; simpl in *; [discriminate|].\n    split; inv H; [| eapply IHl1a; eauto].\n    constructor; auto.\n    specialize (IHl1a _ _ _ H6).\n    destruct IHl1a; auto.\nQed.\n\nLemma same_length_map_DisjKey A B (o: list (Attribute A)):\n  forall (l1 l2: list (Attribute B)),\n    map fst o = map fst l1 ++ map fst l2 ->\n    DisjKey l1 l2 ->\n    o = filter (fun x => getBool (in_dec string_dec (fst x) (map fst l1))) o ++\n               filter (fun x => getBool (in_dec string_dec (fst x) (map fst l2))) o ->\n    length (map fst l1) = length (filter (fun x => getBool (in_dec string_dec (fst x) (map fst l1))) o).\nProof.\n  induction o; simpl; auto; intros.\n  - apply eq_sym in H.\n    apply app_eq_nil in H; subst; dest; subst.\n    rewrite H; auto.\n  - destruct l1; simpl; rewrite ?filter_false; auto; simpl in *.\n    inv H; subst.\n    rewrite H3 in *.\n    destruct (string_dec (fst p) (fst p)); [simpl in *| exfalso; clear - n; tauto].\n    inv H1.\n    assert (sth: DisjKey l1 l2) by (clear - H0; firstorder fail).\n    specialize (IHo _ _ H4 sth).\n    destruct (in_dec string_dec (fst p) (map fst l2)); simpl in *.\n    + unfold DisjKey in *.\n      specialize (H0 (fst p)); simpl in *.\n      destruct H0; tauto.\n    + rewrite <- H2.\n      simpl in *.\n      assert (sth2:\n                (fun x : string * A =>\n                   getBool\n                     match string_dec (fst p) (fst x) with\n                     | left e => left (or_introl e)\n                     | right n =>\n                       match in_dec string_dec (fst x) (map fst l1) with\n                       | left i => left (or_intror i)\n                       | right n0 => right (fun H0 : fst p = fst x \\/ In (fst x) (map fst l1) => match H0 with\n                                                                                                 | or_introl Hc1 => n Hc1\n                                                                                                 | or_intror Hc2 => n0 Hc2\n                                                                                                 end)\n                       end\n                     end) = (fun x : string * A =>\n                               match string_dec (fst p) (fst x) with\n                               | left _ => true\n                               | right _ =>\n                                 getBool (in_dec string_dec (fst x) (map fst l1))\n                               end)). {\n        extensionality x.\n        destruct (string_dec (fst p) (fst x)); auto.\n        destruct (in_dec string_dec (fst x) (map fst l1)); auto.\n      }\n      setoid_rewrite sth2 in H2.\n      setoid_rewrite sth2.\n      clear sth2.\n      destruct (in_dec string_dec (fst p) (map fst l1)).\n      * assert (sth3: (fun x: string * A => if string_dec (fst p) (fst x) then true else getBool (in_dec string_dec (fst x) (map fst l1))) =\n                      fun x => getBool (in_dec string_dec (fst x) (map fst l1))). {\n          extensionality x.\n          destruct (string_dec (fst p) (fst x)); auto.\n          rewrite <- e0.\n          destruct (in_dec string_dec (fst p) (map fst l1)); auto.\n          exfalso; tauto.\n        }\n        rewrite sth3 in *.\n        specialize (IHo H2).\n        auto.\n      * assert (sth2: ~ In (fst p) (map fst o)). {\n          rewrite H4.\n          rewrite in_app_iff.\n          intro.\n          tauto.\n        }\n        assert (sth3: filter (fun x: string * A => if string_dec (fst p) (fst x) then true else getBool (in_dec string_dec (fst x) (map fst l1))) o =\n                      filter (fun x => getBool (in_dec string_dec (fst x) (map fst l1))) o). {\n          clear - sth2.\n          generalize p sth2; clear p sth2.\n          induction o; simpl; auto; intros.\n          assert (sth4: ~ In (fst p) (map fst o)) by tauto.\n          assert (sth5: fst a <> fst p) by tauto.\n          specialize (IHo _ sth4).\n          rewrite IHo.\n          destruct (string_dec (fst p) (fst a)); try tauto.\n          rewrite e in *; tauto.\n        }\n        rewrite sth3 in *.\n        specialize (IHo H2).\n        auto.\nQed.\n  \nSection SplitJoin.\n  Variable m1 m2: Mod.\n\n  Variable DisjRegs: DisjKey (getAllRegisters m1) (getAllRegisters m2).\n  Variable DisjRules: DisjKey (getAllRules m1) (getAllRules m2).\n  Variable DisjMethods: DisjKey (getAllMethods m1) (getAllMethods m2).\n\n  Lemma SplitStep o l:\n    Step (ConcatMod m1 m2) o l ->\n    Step m1 (filterRegs id m1 o) (filterExecs id m1 l) /\\\n    Step m2 (filterRegs id m2 o) (filterExecs id m2 l) /\\\n    o = filterRegs id m1 o ++ filterRegs id m2 o /\\\n    MatchingExecCalls_Concat (filterExecs id m1 l) (filterExecs id m2 l) m2 /\\\n    MatchingExecCalls_Concat (filterExecs id m2 l) (filterExecs id m1 l) m1 /\\\n    (forall x y : FullLabel,\n        In x (filterExecs id m1 l) ->\n        In y (filterExecs id m2 l) ->\n        match fst (snd x) with\n        | Rle _ => match fst (snd y) with\n                   | Rle _ => False\n                   | Meth _ => True\n                   end\n        | Meth _ => True\n        end) /\\\n    l = filterExecs id m1 l ++ filterExecs id m2 l.\n  Proof.\n    intros H.\n    inv H; intros.\n    pose proof (Step_getAllRegisters_fst HStep1) as HRegs1.\n    pose proof (Step_getAllRegisters_fst HStep2) as HRegs2.\n    unfold filterRegs.\n    rewrite DisjRegs_1_id with (l2 := getAllRegisters m2) (o1 := o1),\n                               DisjRegs_2_id with (l1 := getAllRegisters m1) (o2 := o2); auto.\n    rewrite DisjMeths_1_id with (m2 := m2) (o1 := o1) (o2 := o2), DisjMeths_2_id with (m1 := m1) (o1 := o1) (o2 := o2); auto.\n    Opaque MatchingExecCalls_Concat.\n    repeat split; auto.\n    Transparent MatchingExecCalls_Concat.\n  Qed.\n\n  Lemma Step_upd_1 o l:\n    Step (ConcatMod m1 m2) o l ->\n    forall x s v,\n      In x (map fst l) ->\n      In (s, v) x ->\n      In s (map fst (getAllRegisters m1)) ->\n      In x (map fst (filterExecs id m1 l)).\n  Proof.\n    remember (ConcatMod m1 m2) as m.\n    destruct 1; try discriminate; intros.\n    inv Heqm.\n    pose proof (Step_getAllRegisters_fst H) as HRegs1.\n    pose proof (Step_getAllRegisters_fst H0) as HRegs2.\n    unfold filterRegs.\n    rewrite DisjMeths_1_id with (m2 := m2) (o1 := o1) (o2 := o2); auto.\n    rewrite map_app in *.\n    rewrite in_app_iff in *.\n    destruct H1; auto.\n    pose proof (Step_upd_SubList_key H0 _ _ _ H1 H2) as sth.\n    specialize (DisjRegs s); tauto.\n  Qed.\n    \n  Lemma Step_upd_2 o l:\n    Step (ConcatMod m1 m2) o l ->\n    forall x s v,\n      In x (map fst l) ->\n      In (s, v) x ->\n      In s (map fst (getAllRegisters m2)) ->\n      In x (map fst (filterExecs id m2 l)).\n  Proof.\n    remember (ConcatMod m1 m2) as m.\n    destruct 1; try discriminate; intros.\n    inv Heqm.\n    pose proof (Step_getAllRegisters_fst H) as HRegs1.\n    pose proof (Step_getAllRegisters_fst H0) as HRegs2.\n    unfold filterRegs.\n    rewrite DisjMeths_2_id with (m1 := m1) (o1 := o1) (o2 := o2); auto.\n    rewrite map_app in *.\n    rewrite in_app_iff in *.\n    destruct H1; auto.\n    pose proof (Step_upd_SubList_key H _ _ _ H1 H2) as sth.\n    specialize (DisjRegs s); tauto.\n  Qed.\n\n  Local Notation optFullType := (fun fk => option (fullType type fk)).\n  \n  Lemma SplitTrace o ls:\n    Trace (ConcatMod m1 m2) o ls ->\n    Trace m1 (filterRegs id m1 o) (map (filterExecs id m1) ls) /\\\n    Trace m2 (filterRegs id m2 o) (map (filterExecs id m2) ls) /\\\n    o = filterRegs id m1 o ++ filterRegs id m2 o /\\\n    mapProp\n      (fun l =>\n         MatchingExecCalls_Concat (filterExecs id m1 l) (filterExecs id m2 l) m2 /\\\n         MatchingExecCalls_Concat (filterExecs id m2 l) (filterExecs id m1 l) m1 /\\\n         (forall x y : FullLabel,\n             In x (filterExecs id m1 l) ->\n             In y (filterExecs id m2 l) ->\n             match fst (snd x) with\n             | Rle _ => match fst (snd y) with\n                        | Rle _ => False\n                        | Meth _ => True\n                        end\n             | Meth _ => True\n             end) /\\\n         l = filterExecs id m1 l ++ filterExecs id m2 l) ls /\\\n  map fst o = map fst (getAllRegisters (ConcatMod m1 m2)).\n  Proof.\n    Opaque MatchingExecCalls_Concat.\n    induction 1; subst; simpl.\n    - unfold filterRegs, filterExecs; simpl.\n      rewrite ?map_app, ?filter_app.\n      unfold id in *.\n      assert (sth: Forall2 (fun o' r => fst o' = fst r) o' (getAllRegisters (ConcatMod m1 m2))) by\n          (eapply Forall2_impl; eauto; intros; simpl in *; tauto).\n      apply Forall2_map_eq in sth.\n      simpl in sth.\n      rewrite map_app in sth.\n      assert (DisjRegs': DisjKey (getAllRegisters m2) (getAllRegisters m1)) by\n          (clear - DisjRegs; firstorder).\n      match goal with\n      | |- _ /\\ _ /\\ ?P /\\ _ /\\ _ => assert P by (eapply filter_map_app_sameKey; eauto)\n      end.\n      simpl in *.\n      pose proof (same_length_map_DisjKey sth DisjRegs H) as sth2.\n      rewrite H in HUpdRegs.\n      apply Forall2_app_eq_length in HUpdRegs; auto; dest.\n      repeat split; auto; constructor; auto; subst; rewrite ?filter_app in *.\n      rewrite map_length in *.\n      congruence.\n    - pose proof HStep as HStep'.\n      apply SplitStep in HStep.\n      dest.\n      repeat split; try econstructor 2; eauto.\n      + unfold UpdRegs in *; dest.\n        repeat split; intros.\n        * unfold filterRegs, id.\n          pose proof (filter_map_simple (fun x => (fst x, projT1 (snd x))) (fun x => getBool (in_dec string_dec (fst x) (map fst (getAllRegisters m1))))\n                                        o) as sth_o.\n          pose proof (filter_map_simple (fun x => (fst x, projT1 (snd x))) (fun x => getBool (in_dec string_dec (fst x) (map fst (getAllRegisters m1))))\n                                        o') as sth_o'.\n          simpl in sth_o, sth_o'.\n          rewrite <- ?sth_o, <- ?sth_o'.\n          rewrite H12; auto.\n        * unfold filterRegs, id in H14.\n          rewrite filter_In in H14; dest.\n          simpl in *.\n          destruct (in_dec string_dec s (map fst (getAllRegisters m1))); [simpl in *| discriminate].\n          specialize (H13 _ _ H14).\n          destruct H13; [left; dest | right].\n          -- exists x; repeat split; auto.\n             eapply Step_upd_1; eauto.\n          -- split; try intro; dest.\n             ++ unfold filterExecs, id in H16.\n                rewrite in_map_iff in H16; dest.\n                rewrite filter_In in H19; dest.\n                setoid_rewrite in_map_iff at 1 in H13.\n                clear - H13 H16 H19 H18.\n                firstorder fail.\n             ++ unfold filterRegs, id.\n                rewrite filter_In.\n                simpl.\n                destruct (in_dec string_dec s (map fst (getAllRegisters m1))); simpl; auto.\n      + unfold UpdRegs in *; dest.\n        repeat split; intros.\n        * unfold filterRegs, id.\n          pose proof (filter_map_simple (fun x => (fst x, projT1 (snd x))) (fun x => getBool (in_dec string_dec (fst x) (map fst (getAllRegisters m2))))\n                                        o) as sth_o.\n          pose proof (filter_map_simple (fun x => (fst x, projT1 (snd x))) (fun x => getBool (in_dec string_dec (fst x) (map fst (getAllRegisters m2))))\n                                        o') as sth_o'.\n          simpl in sth_o, sth_o'.\n          rewrite <- ?sth_o, <- ?sth_o'.\n          rewrite H12; auto.\n        * unfold filterRegs, id in H14.\n          rewrite filter_In in H14; dest.\n          simpl in *.\n          destruct (in_dec string_dec s (map fst (getAllRegisters m2))); [simpl in *| discriminate].\n          specialize (H13 _ _ H14).\n          destruct H13; [left; dest | right].\n          -- exists x; repeat split; auto.\n             eapply Step_upd_2; eauto.\n          -- split; try intro; dest.\n             ++ unfold filterExecs, id in H16.\n                rewrite in_map_iff in H16; dest.\n                rewrite filter_In in H19; dest.\n                setoid_rewrite in_map_iff at 1 in H13.\n                clear - H13 H16 H19 H18.\n                firstorder fail.\n             ++ unfold filterRegs, id.\n                rewrite filter_In.\n                simpl.\n                destruct (in_dec string_dec s (map fst (getAllRegisters m2))); simpl; auto.\n      + apply UpdRegs_same in HUpdRegs.\n        unfold UpdRegs' in *; dest.\n        rewrite H12 in H4.\n        simpl in H4.\n        rewrite map_app in H4.\n        unfold filterRegs, id.\n        apply filter_map_app_sameKey; auto.\n      + apply UpdRegs_same in HUpdRegs.\n        unfold UpdRegs' in *; dest.\n        rewrite H12 in H4.\n        simpl in H4.\n        auto.\n    Transparent MatchingExecCalls_Concat.\n  Qed.\n\n  Lemma JoinStep o1 o2 l1 l2:\n    Step m1 o1 l1 ->\n    Step m2 o2 l2 ->\n    (MatchingExecCalls_Concat l1 l2 m2) ->\n    (MatchingExecCalls_Concat l2 l1 m1) ->\n    (forall x1 x2, In x1 l1 -> In x2 l2 -> match fst (snd x1), fst (snd x2) with\n                                           | Rle _, Rle _ => False\n                                           | _, _ => True\n                                           end) ->\n    Step (ConcatMod m1 m2) (o1 ++ o2) (l1 ++ l2).\n  Proof.\n    intros.\n    econstructor 3; eauto.\n  Qed.\n\n  Lemma JoinTrace_basic l:\n    forall o1 o2,\n    Trace m1 o1 (map fst l) ->\n    Trace m2 o2 (map snd l) ->\n    (mapProp2 (fun l1 l2 => MatchingExecCalls_Concat l1 l2 m2) l) ->\n    (mapProp2 (fun l1 l2 => MatchingExecCalls_Concat l2 l1 m1) l) ->\n    (mapProp2 (fun l1 l2 =>\n                 (forall x1 x2 : RegsT * (RuleOrMeth * MethsT),\n                     In x1 l1 -> In x2 l2 -> match fst (snd x1) with\n                                             | Rle _ => match fst (snd x2) with\n                                                        | Rle _ => False\n                                                        | Meth _ => True\n                                                        end\n                                             | Meth _ => True\n                                             end)) l) ->\n    Trace (ConcatMod m1 m2) (o1 ++ o2) (map (fun x => fst x ++ snd x) l).\n  Proof.\n    induction l; simpl; intros.\n    - inversion H; inversion H0; subst; try discriminate.\n      constructor; auto.\n      simpl.\n      eapply Forall2_app in HUpdRegs0; eauto.\n    - destruct a; simpl in *; dest.\n      inv H; [discriminate| ]; inv H0; [discriminate|].\n      inv HTrace; inv HTrace0.\n      specialize (IHl _ _ HOldTrace HOldTrace0 H6 H5 H4).\n      econstructor 2 with (o := o ++ o0); eauto.\n      eapply JoinStep; eauto.\n      unfold UpdRegs in *; dest.\n      split.\n      + rewrite ?map_app.\n        congruence.\n      + intros.\n        rewrite in_app_iff in H9.\n        destruct H9.\n        * specialize (H8 _ _ H9).\n          rewrite ?map_app.\n          repeat setoid_rewrite in_app_iff.\n          destruct H8; [left; dest | right; dest].\n          -- exists x; split; auto.\n          -- split; auto.\n             intro.\n             dest.\n             destruct H11;[apply H8; eexists; eauto|].\n             rewrite in_map_iff in H12; dest.\n             destruct x0.\n             subst.\n             simpl in *.\n             pose proof (Step_upd_SubList_key HStep0 _ _ _ H11 H13).\n             pose proof (Step_read HStep _ _ H10).\n             specialize (DisjRegs s0); tauto.\n        * specialize (H0 _ _ H9).\n          rewrite ?map_app.\n          repeat setoid_rewrite in_app_iff.\n          destruct H0; [left; dest | right; dest].\n          -- exists x; split; auto.\n          -- split; auto.\n             intro.\n             dest.\n             destruct H11; [|apply H0; eexists; eauto].\n             rewrite in_map_iff in H12; dest.\n             destruct x0.\n             subst.\n             simpl in *.\n             pose proof (Step_upd_SubList_key HStep _ _ _ H11 H13).\n             pose proof (Step_read HStep0 _ _ H10).\n             specialize (DisjRegs s0); tauto.\n  Qed.\n\n  Lemma JoinTrace_len l1:\n    forall l2 o1 o2,\n      length l1 = length l2 ->\n      Trace m1 o1 l1 ->\n      Trace m2 o2 l2 ->\n      (mapProp_len (fun l1 l2 => MatchingExecCalls_Concat l1 l2 m2) l1 l2) ->\n      (mapProp_len (fun l1 l2 => MatchingExecCalls_Concat l2 l1 m1) l1 l2) ->\n      (mapProp_len (fun l1 l2 =>\n                      (forall x1 x2 : RegsT * (RuleOrMeth * MethsT),\n                          In x1 l1 -> In x2 l2 -> match fst (snd x1) with\n                                                  | Rle _ => match fst (snd x2) with\n                                                             | Rle _ => False\n                                                             | Meth _ => True\n                                                             end\n                                                  | Meth _ => True\n                                                  end)) l1 l2) ->\n      Trace (ConcatMod m1 m2) (o1 ++ o2) (map (fun x => fst x ++ snd x) (List.combine l1 l2)).\n  Proof.\n    intros.\n    eapply JoinTrace_basic; rewrite ?fst_combine, ?snd_combine; eauto;\n      eapply mapProp2_len_same; eauto.\n  Qed.\n\n  Lemma JoinTrace l1:\n    forall l2 o1 o2,\n      length l1 = length l2 ->\n      Trace m1 o1 l1 ->\n      Trace m2 o2 l2 ->\n      nthProp2 (fun l1 l2 => MatchingExecCalls_Concat l1 l2 m2 /\\\n                             MatchingExecCalls_Concat l2 l1 m1 /\\\n                             (forall x1 x2 : RegsT * (RuleOrMeth * MethsT),\n                                 In x1 l1 -> In x2 l2 -> match fst (snd x1) with\n                                                         | Rle _ => match fst (snd x2) with\n                                                                    | Rle _ => False\n                                                                    | Meth _ => True\n                                                                    end\n                                                         | Meth _ => True\n                                                         end)) l1 l2 ->\n      Trace (ConcatMod m1 m2) (o1 ++ o2) (map (fun x => fst x ++ snd x) (List.combine l1 l2)).\n  Proof.\n    intros ? ? ? ?.\n    setoid_rewrite <- mapProp_len_nthProp2; auto.\n    repeat rewrite mapProp_len_conj; auto.\n    pose proof (@JoinTrace_len l1 l2 o1 o2 H).\n    intros; dest.\n    eapply H0; eauto.\n  Qed.\nEnd SplitJoin.\n\nLemma InExec_dec: forall x l, {InExec x l} + {~ InExec x l}.\nProof.\n  unfold InExec; intros.\n  apply in_dec; intros.\n  decide equality.\n  - apply string_dec.\n  - apply MethT_dec.\nQed.\n\nLemma Substeps_meth_In m o l:\n  Substeps m o l ->\n  forall u f cs, In (u, (Meth f, cs)) l ->\n                 In (fst f) (map fst (getMethods m)).\nProof.\n  induction 1; simpl; intros; subst; try tauto.\n  - simpl in *.\n    destruct H0.\n    + inv H0.\n    + eapply IHSubsteps; eauto.\n  - simpl in *.\n    destruct H0.\n    + inv H0.\n      simpl.\n      apply (in_map fst _ _ HInMeths).\n    + eapply IHSubsteps; eauto.\nQed.\n\nLemma Step_meth_In m o l:\n  Step m o l ->\n  forall u f cs, In (u, (Meth f, cs)) l ->\n                 In (fst f) (map fst (getAllMethods m)).\nProof.\n  induction 1; simpl; intros; subst; try tauto.\n  - eapply Substeps_meth_In; eauto.\n  - eauto.\n  - rewrite map_app, in_app_iff in *.\n    clear - IHStep1 IHStep2 H1.\n    specialize (IHStep1 u f cs); specialize (IHStep2 u f cs).\n    tauto.\nQed.\n\nLemma Step_meth_InExec m o l:\n  Step m o l ->\n  forall f, InExec f l ->\n            In (fst f) (map fst (getAllMethods m)).\nProof.\n  intros.\n  unfold InExec in *.\n  rewrite in_map_iff in H0.\n  dest.\n  destruct x; simpl in *.\n  destruct p; simpl in *; subst.\n  eapply Step_meth_In; eauto.\nQed.\n\nLemma Trace_meth_In m o ls:\n  Trace m o ls ->\n  forall u f cs i l, nth_error ls i = Some l ->\n                     In (u, (Meth f, cs)) l ->\n                     In (fst f) (map fst (getAllMethods m)).\nProof.\n  induction 1; simpl; intros; auto; destruct i; simpl in *.\n  - subst; simpl in *; congruence.\n  - subst; simpl in *; congruence.\n  - subst.\n    eapply Step_meth_In with (o := o) (u := u) (f := f) (cs := cs) in H1; eauto.\n    inv H0; auto.\n  - subst; simpl in *.\n    eapply IHTrace; eauto.\nQed.\n  \nLemma Trace_meth_In_map m o ls:\n  Trace m o ls ->\n  forall f i l, nth_error ls i = Some l ->\n                In (Meth f) (map (fun x => fst (snd x)) l) ->\n                In (fst f) (map fst (getAllMethods m)).\nProof.\n  intros.\n  rewrite in_map_iff in H1; dest.\n  destruct x.\n  destruct p.\n  simpl in *; subst.\n  eapply Trace_meth_In; eauto.\nQed.\n  \nLemma Trace_meth_InExec m o ls:\n  Trace m o ls ->\n  forall f i l, nth_error ls i = Some l ->\n                InExec f l ->\n                In (fst f) (map fst (getAllMethods m)).\nProof.\n  apply Trace_meth_In_map.\nQed.\n\n\nLemma InExec_app_iff: forall x l1 l2, InExec x (l1 ++ l2) <-> InExec x l1 \\/ InExec x l2.\nProof.\n  unfold InExec in *; intros.\n  rewrite map_app.\n  rewrite in_app_iff.\n  tauto.\nQed.\n\nLemma InCall_app_iff: forall x l1 l2, InCall x (l1 ++ l2) <-> InCall x l1 \\/ InCall x l2.\nProof.\n  unfold InCall in *; intros.\n  setoid_rewrite in_app_iff.\n  firstorder fail.\nQed.\n\nLemma NotInDef_ZeroExecs_Substeps m o ls f :\n  ~In (fst f) (map fst (getMethods m)) ->\n  Substeps m o ls ->\n  (getNumExecs f ls = 0%Z).\nProof.\n  induction 2.\n  - reflexivity.\n  - rewrite HLabel.\n    unfold getNumExecs in *; simpl; assumption.\n  - rewrite HLabel.\n    unfold getNumExecs.\n    Opaque getNumFromExecs.\n    simpl; destruct (MethT_dec f (fn, existT _ (projT1 fb) (argV, retV))).\n    + destruct f; inv e.\n      apply (in_map fst) in HInMeths; simpl in *; contradiction.\n    + rewrite getNumFromExecs_neq_cons; auto.\n    Transparent getNumFromExecs.\nQed.\n\nLemma NotInDef_ZeroExecs_Substeps' m o ls f :\n  ~In (fst f, projT1 (snd f)) (getKindAttr (getMethods m)) ->\n  Substeps m o ls ->\n  (getNumExecs f ls = 0%Z).\nProof.\n  induction 2.\n  - reflexivity.\n  - rewrite HLabel.\n    unfold getNumExecs in *; simpl; assumption.\n  - rewrite HLabel.\n    unfold getNumExecs.\n    Opaque getNumFromExecs.\n    simpl; destruct (MethT_dec f (fn, existT _ (projT1 fb) (argV, retV))); subst.\n    + apply (in_map (fun x => (fst x, projT1 (snd x)))) in HInMeths; contradiction.\n    + rewrite getNumFromExecs_neq_cons; auto.\n    Transparent getNumFromExecs.\nQed.  \n\nLemma NotInDef_ZeroExecs_Step m o ls f:\n  ~In (fst f) (map fst (getAllMethods m)) ->\n  Step m o ls ->\n  (getNumExecs f ls = 0%Z).\nProof.\n  induction 2; simpl in *; auto.\n  - apply (NotInDef_ZeroExecs_Substeps _ H HSubsteps).\n  - rewrite HLabels.\n    rewrite getNumExecs_app.\n    rewrite map_app, in_app_iff in H.\n    assert (~In (fst f) (map fst (getAllMethods m1)) /\\ ~In (fst f) (map fst (getAllMethods m2)));[tauto|]; dest.\n    rewrite IHStep1, IHStep2; auto.\nQed.  \n\nLemma NotInDef_ZeroExecs_Step' m o ls f:\n  ~In (fst f, projT1 (snd f)) (getKindAttr (getAllMethods m)) ->\n  Step m o ls ->\n  (getNumExecs f ls = 0%Z).\nProof.\n  induction 2; simpl in *; auto.\n  - apply (NotInDef_ZeroExecs_Substeps' _ H HSubsteps).\n  - rewrite HLabels.\n    rewrite getNumExecs_app.\n    rewrite map_app, in_app_iff in H.\n    rewrite IHStep1, IHStep2; auto.\nQed.\n\nLemma Trace_meth_InExec' m o ls:\n  Trace m o ls ->\n  forall f i l, nth_error ls i = Some l ->\n                (0 < getNumExecs f l)%Z ->\n                In (fst f) (map fst (getAllMethods m)).\nProof.\n  induction 1; subst; simpl; intros; auto; destruct i; simpl in *; try discriminate.\n  - inv H0.\n    destruct (in_dec string_dec (fst f) (map fst (getAllMethods m))); auto.\n    specialize (NotInDef_ZeroExecs_Step _ n HStep) as noExec_zero.\n    apply False_ind; Omega.omega.\n  - eapply IHTrace; eauto.\nQed.\n\nLemma Step_meth_InCall_InDef_InExec m o ls:\n  Step m o ls ->\n  forall (f : MethT),\n    In (fst f, projT1 (snd f)) (getKindAttr (getAllMethods m)) ->\n    (getNumCalls f ls <= getNumExecs f ls)%Z.\nProof.\n  induction 1; eauto.\n  - subst.\n    simpl.\n    rewrite map_app.\n    setoid_rewrite getNumCalls_app.\n    setoid_rewrite getNumExecs_app.\n    setoid_rewrite in_app_iff.\n    intros.\n    unfold MatchingExecCalls_Concat in *.\n    specialize (getNumExecs_nonneg f l1) as P1;specialize (getNumExecs_nonneg f l2) as P2.\n    destruct H1.\n    + specialize (IHStep1 _ H1); destruct (Z.eq_dec (getNumCalls f l2) 0%Z).\n      * rewrite e, Z.add_0_r;Omega.omega.\n      * specialize (HMatching2 _ n H1); dest; Omega.omega.\n    + specialize (IHStep2 _ H1); destruct (Z.eq_dec (getNumCalls f l1) 0%Z).\n      * rewrite e; simpl; Omega.omega.\n      * specialize (HMatching1 _ n H1); dest; Omega.omega.\nQed.\n\nLemma Trace_meth_InCall_InDef_InExec m o ls:\n  Trace m o ls ->\n  forall (f : MethT) (i : nat) (l : list (RegsT * (RuleOrMeth * MethsT))),\n    nth_error ls i = Some l ->\n    In (fst f, projT1 (snd f)) (getKindAttr (getAllMethods m)) ->\n    (getNumCalls f l <= getNumExecs f l)%Z.\nProof.\n  induction 1; subst; auto; simpl; intros.\n  - destruct i; simpl in *; try congruence.\n  - destruct i; simpl in *.\n    + inv H0.\n      eapply Step_meth_InCall_InDef_InExec; eauto.\n    + eapply IHTrace; eauto.\nQed.\n  \nLemma Trace_meth_InCall_not_InExec_not_InDef m o ls:\n  Trace m o ls ->\n  forall (f : MethT) (i : nat) (l : list (RegsT * (RuleOrMeth * MethsT))),\n    nth_error ls i = Some l ->\n    ~(getNumCalls f l <= getNumExecs f l)%Z ->\n    ~ In (fst f, projT1 (snd f)) (getKindAttr (getAllMethods m)).\nProof.\n  repeat intro.\n  eapply Trace_meth_InCall_InDef_InExec in H2; eauto.\nQed.\n\nLemma InCall_dec: forall x l, InCall x l \\/ ~ InCall x l.\nProof.\n  unfold InCall; intros.\n  induction l; simpl.\n  - right.\n    intro.\n    dest; auto.\n  - destruct IHl; dest.\n    + left.\n      exists x0.\n      split; tauto.\n    + pose proof (in_dec MethT_dec x (snd (snd a))).\n      destruct H0.\n      * left; exists a; tauto.\n      * right; intro.\n        dest.\n        destruct H0; subst.\n        -- auto.\n        -- firstorder fail.\nQed.\n\nLemma InCall_dec_quant1: forall (f: string) l,\n    {exists v: {x: Kind * Kind & SignT x}, In (f, v) l} + {forall v, ~ In (f, v) l}.\nProof.\n  unfold InCall; intros.\n  induction l; simpl.\n  - right; intro; intro; auto.\n  - destruct IHl.\n    + left.\n      dest.\n      exists x; tauto.\n    + assert (sth: {exists v, a = (f, v)} + {forall v, a <> (f, v)}).\n      { destruct a; simpl in *.\n        destruct (string_dec f s); subst.\n        - left.\n          exists s0; auto.\n        - right; intro; intro.\n          inv H.\n          tauto.\n      }\n      destruct sth.\n      * left.\n        dest.\n        exists x; auto.\n      * right.\n        intro.\n        specialize (n v).\n        specialize (n0 v).\n        tauto.\nQed.\n\nLemma InCall_dec_quant2: forall f l, (exists v, InCall (f, v) l) \\/ forall v, ~ InCall (f, v) l.\nProof.\n  unfold InCall; intros.\n  induction l; simpl.\n  - right.\n    intro.\n    intro.\n    dest; auto.\n  - destruct IHl; dest.\n    + left.\n      exists x.\n      exists x0.\n      split; tauto.\n    + destruct (InCall_dec_quant1 f (snd (snd a))).\n      * left; dest.\n        exists x.\n        exists a.\n        tauto.\n      * right; intro; intro.\n        dest.\n        specialize (H v).\n        specialize (n v).\n        destruct H0; subst; auto.\n        firstorder fail.\nQed.\n\nLemma TraceInclusion_refl: forall m, TraceInclusion m m.\nProof.\n  unfold TraceInclusion; intros.\n  exists o1, ls1.\n  repeat split; auto.\n  unfold nthProp2; intros.\n  destruct (nth_error ls1 i); auto.\n  repeat split; intros; tauto.\nQed.\n\nLemma TraceInclusion_trans: forall m1 m2 m3, TraceInclusion m1 m2 ->\n                                               TraceInclusion m2 m3 ->\n                                               TraceInclusion m1 m3.\nProof.\n  unfold TraceInclusion; intros.\n  specialize (H _ _ H1); dest.\n  specialize (H0 _ _ H); dest.\n  exists x1, x2.\n  repeat split; auto.\n  - congruence.\n  - unfold nthProp2, WeakInclusion in *; intros.\n    specialize (H3 i); specialize (H5 i).\n    case_eq (nth_error ls1 i);\n      case_eq (nth_error x0 i);\n      case_eq (nth_error x2 i);\n      intros; auto.\n    + rewrite H6, H7, H8 in *.\n      dest.\n      split;[eauto using eq_trans|auto].\n    + pose proof (nth_error_len _ _ _ H7 H6 H4); contradiction.\nQed.\n\nGlobal Instance TraceEquiv_rewrite_l:\n  Proper (eq ==> TraceEquiv ==> iff) TraceInclusion.\nProof.\n   unfold Proper, iff, Basics.flip, Basics.impl, TraceEquiv, respectful; intros; dest; try split; intros; auto; subst;\n    repeat (eapply TraceInclusion_trans; eauto).\nQed.\n\nGlobal Instance TraceEquiv_rewrite_r:\n  Proper (TraceEquiv ==> eq ==> iff) TraceInclusion.\nProof.\n   unfold Proper, iff, Basics.flip, Basics.impl, TraceEquiv, respectful; intros; dest; try split; intros; auto; subst;\n    repeat (eapply TraceInclusion_trans; eauto).\nQed.\n\nSection Test.\n  Variable m1 m2 m3 m4: Mod.\n  Variable H1: TraceEquiv m1 m2.\n  Variable H2: TraceEquiv m3 m4.\n\n  Goal TraceInclusion m2 m4 <-> TraceInclusion m1 m3.\n  Proof.\n    rewrite H1.\n    rewrite H2.\n    tauto.\n  Qed.\n\n  Goal TraceInclusion m1 m4 <-> TraceInclusion m2 m3.\n    rewrite H1.\n    rewrite H2.\n    tauto.\n  Qed.\nEnd Test.\n\n\nLemma UpdRegs_nil_upd: forall o, NoDup (map fst o) -> forall o', UpdRegs [] o o' -> o = o'.\nProof.\n  unfold UpdRegs.\n  intros.\n  dest.\n  simpl in *.\n  assert (sth: forall s v, In (s, v) o' -> In (s, v) o).\n  { intros.\n    specialize (H1 s v H2).\n    destruct H1; dest; try auto.\n    tauto.\n  }\n  clear H1.\n  generalize o' H H0 sth.\n  clear o' H H0 sth.\n  induction o; destruct o'; simpl; auto; intros.\n  - discriminate.\n  - discriminate.\n  - inv H0.\n    inv H.\n    specialize (IHo _ H6 H4).\n    destruct p, a; simpl in *; subst; auto; repeat f_equal; auto.\n    + specialize (sth s s0 (or_introl eq_refl)).\n      destruct sth.\n      * inv H; subst; auto.\n      * apply (in_map fst) in H; simpl in *; tauto.\n    + eapply IHo; intros.\n      specialize (sth _ _ (or_intror H)).\n      destruct sth; [|auto].\n      inv H0; subst.\n      apply (f_equal (map fst)) in H4.\n      rewrite ?map_map in *; simpl in *.\n      setoid_rewrite (functional_extensionality (fun x => fst x) fst) in H4; try tauto.\n      apply (in_map fst) in H; simpl in *; congruence.\nQed.\n\nLemma Trace_NoDup m o l:\n  Trace m o l ->\n  NoDup (map fst (getAllRegisters m)) ->\n  NoDup (map fst o).\nProof.\n  induction 1; subst.\n  - intros.\n    assert (sth: Forall2 (fun o' r => fst o' = fst r) o' (getAllRegisters m)) by\n        (eapply Forall2_impl; eauto; intros; simpl in *; tauto).\n    clear HUpdRegs.\n    apply Forall2_map_eq in sth.\n    congruence.\n  - unfold UpdRegs in *; intros; dest.\n    apply (f_equal (map fst)) in H1.\n    rewrite ?map_map in *; simpl in *.\n    setoid_rewrite (functional_extensionality (fun x => fst x) fst) in H1; try tauto.\n    rewrite H1 in *; eapply IHTrace; eauto.\nQed.\n\nLemma Trace_sameRegs m o l:\n  Trace m o l ->\n  getKindAttr o = getKindAttr (getAllRegisters m).\nProof.\n  induction 1; subst; auto.\n  - assert (sth: Forall2 (fun o' r => (fun x => (fst x, projT1 (snd x))) o' = (fun x => (fst x, projT1 (snd x))) r) o' (getAllRegisters m)). {\n      eapply Forall2_impl; eauto; intro; simpl in *.\n      intros; dest.\n      f_equal; auto.\n    }\n    clear HUpdRegs.\n    apply Forall2_map_eq in sth.\n    congruence.\n  - unfold UpdRegs in *; dest. congruence.\nQed.\n\nLemma Step_empty m:\n  forall o,\n    getKindAttr o = getKindAttr (getAllRegisters m) ->\n    Step m o [].\nProof.\n  induction m; simpl; intros; auto.\n  - constructor; auto.\n    + constructor; auto.\n    + unfold MatchingExecCalls_Base.\n      intros; rewrite getNumCalls_nil, getNumExecs_nil; reflexivity.\n  - constructor 2.\n    + eapply IHm; eauto.\n    + intros.\n      unfold getListFullLabel_diff; auto.\n  - rewrite map_app in H.\n    pose proof (list_split _ _ _ _ _ H).\n    dest.\n    specialize (IHm1 _ H1).\n    specialize (IHm2 _ H2).\n    eapply ConcatModStep with (o1 := x) (o2 := x0) (l1 := []) (l2 := []); eauto.\n    + unfold MatchingExecCalls_Concat; intros.\n      rewrite getNumCalls_nil in H3; apply False_ind; apply H3; reflexivity.\n    + unfold MatchingExecCalls_Concat; intros.\n      rewrite getNumCalls_nil in H3; apply False_ind; apply H3; reflexivity.\n    + intros.\n      simpl in *; tauto.\nQed.\n\nLemma Trace_Step_empty m o l:\n  Trace m o l ->\n  Step m o [].\nProof.\n  intros.\n  apply Trace_sameRegs in H.\n  apply Step_empty in H.\n  auto.\nQed.\n\nSection StepSimulation.\n  Variable imp spec: Mod.\n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable initRel: forall rimp, Forall2 regInit rimp (getAllRegisters imp) -> exists rspec, Forall2 regInit rspec (getAllRegisters spec) /\\ simRel rimp rspec.\n  Variable NoDupRegs: NoDup (map fst (getAllRegisters imp)).\n  \n  Variable stepSimulationNonZero:\n    forall oImp lImp oImp',\n      Step imp oImp lImp ->\n      lImp <> nil ->\n      UpdRegs (map fst lImp) oImp oImp' ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        exists lSpec oSpec',\n          Step spec oSpec lSpec /\\\n          UpdRegs (map fst lSpec) oSpec oSpec' /\\\n          simRel oImp' oSpec' /\\ WeakInclusion lImp lSpec.\n\n  Lemma StepSimulation':\n    forall (oImp : RegsT) (lsImp : list (list FullLabel)),\n      Trace imp oImp lsImp ->\n      exists (oSpec : RegsT) (lsSpec : list (list FullLabel)),\n        Trace spec oSpec lsSpec /\\\n        Datatypes.length lsImp = Datatypes.length lsSpec /\\\n        nthProp2 WeakInclusion lsImp lsSpec /\\\n        simRel oImp oSpec.\n  Proof.\n    induction 1; subst; simpl; auto; intros.\n    - pose proof (initRel HUpdRegs) as [rspec rspecProp].\n      exists rspec, []; repeat split; dest; auto.\n      + econstructor 1; eauto.\n      + unfold nthProp2; intros.\n        destruct (nth_error [] i); auto.\n        repeat split; intros; tauto.\n    - dest.\n      destruct l.\n      + simpl in *.\n        exists x, ([] :: x0); repeat split; simpl in *; auto.\n        * constructor 2 with (o := x) (ls := x0) (l := []); simpl; auto.\n          -- eapply Trace_Step_empty; eauto.\n          -- clear.\n             unfold UpdRegs; split; intros; try tauto.\n             right; split; try intro; dest; auto.\n        * rewrite nthProp2_cons; split; simpl; auto; repeat split; dest; simpl in *; try tauto.\n        * pose proof (Trace_NoDup H NoDupRegs) as sth.\n          pose proof (UpdRegs_nil_upd sth HUpdRegs); subst; auto.\n      + specialize (stepSimulationNonZero HStep ltac:(intro; discriminate) HUpdRegs H3).\n        destruct stepSimulationNonZero as [lSpec [oSpec' [stepSpec [updSpec [sim lSpecProp]]]]].\n        exists oSpec', (lSpec :: x0); repeat split; simpl in *; auto.\n        * econstructor 2; eauto.\n        * simpl.\n          rewrite nthProp2_cons; split; auto.\n  Qed.\n\n  Theorem StepSimulation:\n    TraceInclusion imp spec.\n  Proof.\n    unfold TraceInclusion; intros.\n    eapply StepSimulation' in H.\n    dest.\n    exists x, x0.\n    repeat split; auto.\n  Qed.\nEnd StepSimulation.\n\nLemma NoMeths_Substeps m o ls:\n  getMethods m = [] ->\n  Substeps m o ls ->\n  ls = nil \\/ exists u rl cs, ls = (u, (Rle rl, cs)) :: nil.\nProof.\n  intros nilMeths substeps.\n  induction substeps; intros; auto; subst.\n  - destruct IHsubsteps; subst.\n    + right.\n      repeat eexists; eauto.\n    + dest; subst.\n      specialize (HNoRle _ (or_introl eq_refl)); simpl in *.\n      tauto.\n  - rewrite nilMeths in *.\n    simpl in *.\n    tauto.\nQed.\n\n\nSection SimulationZero.\n  Variable imp spec: BaseModule.\n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) -> exists rspec, Forall2 regInit rspec (getRegisters spec) /\\ simRel rimp rspec.\n  Variable NoDupRegs: NoDup (map fst (getRegisters imp)).\n\n  Variable NoMeths: getMethods imp = [].\n  Variable NoMethsSpec: getMethods spec = [].\n\n  Variable simulation:\n    forall oImp uImp rleImp csImp oImp',\n      Substeps imp oImp [(uImp, (Rle rleImp, csImp))] ->\n      UpdRegs [uImp] oImp oImp' ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((getKindAttr oSpec = getKindAttr (getRegisters spec) /\\ simRel oImp' oSpec /\\ csImp = []) \\/\n         (exists uSpec rleSpec oSpec',\n             Substeps spec oSpec [(uSpec, (Rle rleSpec, csImp))] /\\\n             UpdRegs [uSpec] oSpec oSpec' /\\\n             simRel oImp' oSpec')).\n\n  Theorem simulationZero:\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    apply StepSimulation with (simRel := simRel); auto; intros.\n    inv H.\n    pose proof HSubsteps as sth.\n    inv HSubsteps; simpl in *.\n    - tauto.\n    - pose proof (NoMeths_Substeps NoMeths HSubstep).\n      destruct H; [subst | dest; subst].\n      + simpl in *.\n        specialize (@simulation _ _ _ _ oImp' sth H1 _ H2).\n        destruct simulation; dest; subst.\n        * exists nil, oSpec.\n          repeat split; auto.\n          constructor; auto.\n          -- constructor; auto.\n          -- unfold MatchingExecCalls_Base; intros; reflexivity.\n          -- intros.\n             right; split; try intro; dest; simpl in *; try tauto.\n          -- intros; dest. inv H4.\n        \n        * exists [(x, (Rle x0, cs))], x1.\n          repeat split; auto.\n          -- constructor; auto.\n             unfold MatchingExecCalls_Base; intros.\n             rewrite NoMethsSpec in *; simpl in *; tauto.\n          -- unfold UpdRegs in *; dest.\n             auto.\n          -- intros.\n             unfold UpdRegs in *; dest.\n             simpl in *.\n             eapply H6; eauto.\n          -- intros; dest.\n             destruct H5;simpl in *; inv H5.\n             exists rn; left; reflexivity.\n      + specialize (HNoRle _ (or_introl eq_refl)); simpl in *; tauto.\n    - rewrite NoMeths in *.\n      simpl in *; tauto.\n  Qed.\nEnd SimulationZero.\n\nLemma createHide_hides: forall hides m, getHidden (createHide m hides) = hides.\nProof.\n  induction hides; simpl; auto; intros; f_equal; auto.\nQed.\n\nLemma createHide_Regs: forall m l, getAllRegisters (createHide m l) = getRegisters m.\nProof.\n  intros.\n  induction l; simpl; auto; intros.\nQed.\n  \nLemma createHide_Rules: forall m l, getAllRules (createHide m l) = getRules m.\nProof.\n  intros.\n  induction l; simpl; auto; intros.\nQed.\n  \nLemma createHide_Meths: forall m l, getAllMethods (createHide m l) = getMethods m.\nProof.\n  intros.\n  induction l; simpl; auto; intros.\nQed.\n  \nLemma createHideMod_Meths: forall m l, getAllMethods (createHideMod m l) = getAllMethods m.\nProof.\n  intros.\n  induction l; simpl; auto; intros.\nQed.\n  \nLemma getFlat_Hide m s:\n  getFlat (HideMeth m s) = getFlat m.\nProof.\n  unfold getFlat; auto.\nQed.\n\nLemma getAllRegisters_flatten: forall m, getAllRegisters (flatten m) = getAllRegisters m.\nProof.\n  unfold flatten, getFlat; intros.\n  rewrite createHide_Regs.\n  auto.\nQed.\n\nLemma WfMod_Hidden ty m:\n  WfMod ty m ->\n  forall s, In s (getHidden m) -> In s (map fst (getAllMethods m)).\nProof.\n  induction 1; simpl; auto; intros.\n  - tauto.\n  - destruct H0; subst; auto.\n  - rewrite map_app, in_app_iff in *.\n    specialize (IHWfMod1 s); specialize (IHWfMod2 s); tauto.\nQed.\n\nLemma SemActionUpdSub o k a reads upds calls ret:\n  @SemAction o k a reads upds calls ret ->\n  SubList (getKindAttr upds) (getKindAttr o).\nProof.\n  induction 1; auto; subst;\n    unfold SubList in *; intros;\n      rewrite ?in_app_iff in *.\n  - rewrite map_app, in_app_iff in *.\n    destruct H1; firstorder fail.\n  - subst; firstorder; simpl in *.\n    subst.\n    assumption.\n  - subst.\n    rewrite map_app, in_app_iff in *.\n    destruct H1; intuition.\n  - subst.\n    rewrite map_app, in_app_iff in *.\n    destruct H1; intuition.\n  - subst; simpl in *; intuition.\nQed.\n\nLemma SemActionExpandRegs o k a reads upds calls ret:\n  @SemAction o k a reads upds calls ret ->\n  forall o', SubList reads o' ->\n             SubList (getKindAttr upds) (getKindAttr o') ->\n             @SemAction o' k a reads upds calls ret.\nProof.\n  intros.\n  induction H; try solve [econstructor; auto].\n  - subst.\n    specialize (IHSemAction H0).\n    econstructor; eauto.\n  - subst.\n    apply SubList_app_l in H0; dest.\n    rewrite map_app in *.\n    apply SubList_app_l in H1; dest.\n    specialize (IHSemAction1 H0 H1).\n    specialize (IHSemAction2 H3 H4).\n    econstructor; eauto.\n  - subst.\n    apply SubList_cons in H0; dest.\n    specialize (IHSemAction H2 H1).\n    econstructor; eauto.\n  - subst.\n    simpl in *.\n    apply SubList_cons in H1; dest.\n    specialize (IHSemAction H0 H2).\n    econstructor; eauto.\n  - subst.\n    apply SubList_app_l in H0; dest.\n    rewrite map_app in *.\n    apply SubList_app_l in H1; dest.\n    specialize (IHSemAction1 H0 H1).\n    specialize (IHSemAction2 H3 H4).\n    econstructor; eauto.\n  - subst.\n    apply SubList_app_l in H0; dest.\n    rewrite map_app in *.\n    apply SubList_app_l in H1; dest.\n    specialize (IHSemAction1 H0 H1).\n    specialize (IHSemAction2 H3 H4).\n    econstructor 8; eauto.\nQed.\n\nLemma Substeps_combine m1 o1 l1:\n  Substeps m1 o1 l1 ->\n  forall m2 o2 l2  (DisjRegs: DisjKey (getRegisters m1) (getRegisters m2)) (DisjMeths: DisjKey (getMethods m1) (getMethods m2))\n         (HOneRle: forall x1 x2, In x1 l1 -> In x2 l2 -> match fst (snd x1), fst (snd x2) with\n                                                         | Rle _, Rle _ => False\n                                                         | _, _ => True\n                                                         end),\n    Substeps m2 o2 l2 ->\n    Substeps (BaseMod (getRegisters m1 ++ getRegisters m2) (getRules m1 ++ getRules m2) (getMethods m1 ++ getMethods m2)) (o1 ++ o2) (l1 ++ l2).\nProof.\n  induction 1; intros.\n  - induction H; simpl in *.\n    + constructor 1; auto; simpl.\n      rewrite ?map_app; congruence.\n    + econstructor 2; eauto; simpl; rewrite ?map_app; try congruence.\n      * rewrite in_app_iff; right; eassumption.\n      * pose proof (SemActionReadsSub HAction).\n        pose proof (SemActionUpdSub HAction).\n        eapply SemActionExpandRegs; eauto; unfold SubList in *; intros; rewrite ?map_app, ?in_app_iff; right.\n        -- eapply H0; eauto.\n        -- eapply H1; eauto.\n      * unfold SubList in *; intros.\n        rewrite in_app_iff; right; eapply HReadsGood; eauto.\n      * unfold SubList in *; intros.\n        rewrite in_app_iff; right; eapply HUpdGood; eauto.\n      * eapply IHSubsteps; intros;\n          unfold InCall in *; simpl in *; dest; tauto.\n    + econstructor 3; eauto; simpl; rewrite ?map_app; try congruence.\n      * rewrite in_app_iff; right; eassumption.\n      * pose proof (SemActionReadsSub HAction).\n        pose proof (SemActionUpdSub HAction).\n        eapply SemActionExpandRegs; eauto; unfold SubList in *; intros; rewrite ?map_app, ?in_app_iff; right.\n        -- eapply H0; eauto.\n        -- eapply H1; eauto.\n      * unfold SubList in *; intros.\n        rewrite in_app_iff; right; eapply HReadsGood; eauto.\n      * unfold SubList in *; intros.\n        rewrite in_app_iff; right; eapply HUpdGood; eauto.\n      * eapply IHSubsteps; intros;\n          unfold InCall in *; simpl in *; dest; tauto.\n  - subst; simpl.\n    assert (sth_else: forall x1 x2, In x1 ls -> In x2 l2 -> match fst (snd x1), fst (snd x2) with\n                                                            | Rle _, Rle _ => False\n                                                            | _, _ => True\n                                                            end) by (clear - HOneRle; firstorder fail).\n    econstructor 2; eauto; simpl; rewrite ?map_app; try congruence.\n    + inv H0; congruence.\n    + rewrite in_app_iff; left; eassumption.\n    + pose proof (SemActionReadsSub HAction).\n      pose proof (SemActionUpdSub HAction).\n      eapply SemActionExpandRegs; eauto; unfold SubList in *; intros; rewrite ?map_app, ?in_app_iff; left.\n      * eapply H1; eauto.\n      * eapply H2; eauto.\n    + unfold SubList in *; intros.\n      rewrite in_app_iff; left; eapply HReadsGood; eauto.\n    + unfold SubList in *; intros.\n      rewrite in_app_iff; left; eapply HUpdGood; eauto.\n    + intros.\n      rewrite in_app_iff in *.\n      destruct H1; [eapply HDisjRegs; eauto| ].\n      rewrite DisjKeyWeak_same by apply string_dec; intro; intros.\n      rewrite in_map_iff in H2; dest; subst.\n      pose proof (Substeps_upd_In H0 _ (in_map fst _ _ H1) _ (in_map fst _ _ H4)).\n      apply (SubList_map fst) in HUpdGood.\n      rewrite ?map_map in *; simpl in *.\n      rewrite ?(functional_extensionality (fun x => fst x) fst) in HUpdGood by tauto.\n      setoid_rewrite (functional_extensionality (fun x => fst x) fst) in HUpdGood; [|tauto].\n      specialize (HUpdGood _ H3).\n      clear - H2 DisjRegs HUpdGood; firstorder fail.\n    + intros.\n      rewrite in_app_iff in *.\n      destruct H1; [eapply HNoRle; eauto| ].\n      unfold SubList in *.\n      specialize (HOneRle _ x (or_introl eq_refl) H1); simpl in *; assumption.\n  - subst; simpl.\n    assert (sth_else: forall x1 x2, In x1 ls -> In x2 l2 -> match fst (snd x1), fst (snd x2) with\n                                                            | Rle _, Rle _ => False\n                                                            | _, _ => True\n                                                            end) by (clear - HOneRle; firstorder fail).\n    econstructor 3; eauto; simpl; rewrite ?map_app; try congruence.\n    + inv H0; congruence.\n    + rewrite in_app_iff; left; eassumption.\n    + pose proof (SemActionReadsSub HAction).\n      pose proof (SemActionUpdSub HAction).\n      eapply SemActionExpandRegs; eauto; unfold SubList in *; intros; rewrite ?map_app, ?in_app_iff; left.\n      * eapply H1; eauto.\n      * eapply H2; eauto.\n    + unfold SubList in *; intros.\n      rewrite in_app_iff; left; eapply HReadsGood; eauto.\n    + unfold SubList in *; intros.\n      rewrite in_app_iff; left; eapply HUpdGood; eauto.\n    + intros.\n      rewrite in_app_iff in *.\n      destruct H1; [eapply HDisjRegs; eauto| ].\n      rewrite DisjKeyWeak_same by apply string_dec; intro; intros.\n      rewrite in_map_iff in H2; dest; subst.\n      pose proof (Substeps_upd_In H0 _ (in_map fst _ _ H1) _ (in_map fst _ _ H4)).\n      apply (SubList_map fst) in HUpdGood.\n      rewrite ?map_map in *; simpl in *.\n      rewrite ?(functional_extensionality (fun x => fst x) fst) in HUpdGood by tauto.\n      setoid_rewrite (functional_extensionality (fun x => fst x) fst) in HUpdGood; [|tauto].\n      specialize (HUpdGood _ H3).\n      clear - H2 DisjRegs HUpdGood; firstorder fail.\nQed.\n\nLemma Substeps_flatten m o l:\n  Substeps (BaseMod (getRegisters m) (getRules m) (getMethods m)) o l ->\n  Substeps m o l.\nProof.\n  induction 1; simpl; auto.\n  - constructor 1; auto.\n  - econstructor 2; eauto.\n  - econstructor 3; eauto.\nQed.\n\nLemma flatten_Substeps m o l:\n  Substeps m o l -> Substeps (BaseMod (getRegisters m) (getRules m) (getMethods m)) o l.\n  induction 1; simpl; auto.\n  - constructor 1; auto.\n  - econstructor 2; eauto.\n  - econstructor 3; eauto.\nQed.\n\nLemma Step_substitute' ty m o l:\n  Step m o l -> forall (HWfMod: WfMod ty m), StepSubstitute m o l.\nProof.\n  unfold StepSubstitute.\n  induction 1; auto; simpl; intros; dest; unfold MatchingExecCalls_Base in *; simpl in *.\n  - repeat split.\n    clear HMatching.\n    induction HSubsteps.\n    + econstructor 1; eauto.\n    + econstructor 2; eauto.\n    + econstructor 3; eauto.\n    + simpl; tauto.\n    + intros; tauto.\n  - inv HWfMod.\n    specialize (IHStep HWf); dest.\n    repeat split; auto.\n    intros; destruct H4.\n    + subst.\n      apply HHidden; auto.\n    + apply H2; auto.\n  - inv HWfMod.\n    specialize (IHStep1 HWf1).\n    specialize (IHStep2 HWf2).\n    dest.\n    subst; repeat split; auto.\n    + pose proof (Substeps_combine H4 HDisjRegs HDisjMeths HNoRle H1 (m2 := BaseMod (getAllRegisters m2) _ _)).\n      simpl in *.\n      assumption.\n    + intros.\n      rewrite getNumCalls_app, getNumExecs_app.\n      rewrite map_app, in_app_iff in H7.\n      destruct H7.\n      * destruct (Z.eq_dec (getNumCalls f l2) 0%Z).\n        -- rewrite e.\n           specialize (H5 _ H7).\n           specialize (getNumExecs_nonneg f l2); intros.\n           Omega.omega.\n        -- destruct  (HMatching2 f n H7).\n           assert (getNumExecs f l2 = 0%Z) as P1.\n           { destruct (HDisjMeths (fst f)).\n             - apply (in_map fst) in H7; simpl in *; rewrite fst_getKindAttr in H7; contradiction.\n             - eapply NotInDef_ZeroExecs_Substeps; eauto; simpl; assumption. }\n           Omega.omega.\n      * destruct (Z.eq_dec (getNumCalls f l1) 0%Z).\n        -- rewrite e.\n           specialize (H2 _ H7).\n           specialize (getNumExecs_nonneg f l1); intros.\n           Omega.omega.\n        -- destruct  (HMatching1 f n H7).\n           assert (getNumExecs f l1 = 0%Z) as P1.\n           { destruct (HDisjMeths (fst f)).\n             - eapply NotInDef_ZeroExecs_Substeps; eauto; simpl; assumption.\n             - apply (in_map fst) in H7; simpl in *; rewrite fst_getKindAttr in H7; contradiction. }\n           Omega.omega.\n    + intros s v.\n      rewrite map_app;repeat rewrite in_app_iff.\n      unfold getListFullLabel_diff in *.\n      rewrite getNumExecs_app, getNumCalls_app.\n      intros.\n      destruct H7, H8, (HDisjMeths s); try (apply (in_map fst) in H7; rewrite fst_getKindAttr in H7; contradiction).\n      * assert (getNumExecs (s, v) l2 = 0%Z) as P1.\n        { eapply NotInDef_ZeroExecs_Substeps; eauto; simpl; assumption. }\n        destruct (Z.eq_dec (getNumCalls (s, v) l2) 0%Z).\n        { specialize (H6 _ v H7 H8); Omega.omega. }\n        destruct (HMatching2 _ n H7); contradiction.\n      * pose proof (WfMod_Hidden HWf2 _ H8); contradiction.\n      * pose proof (WfMod_Hidden HWf1 _ H8); contradiction.\n      * assert (getNumExecs (s, v) l1 = 0%Z) as P1.\n        { eapply NotInDef_ZeroExecs_Substeps; eauto; simpl; assumption. }\n        destruct (Z.eq_dec (getNumCalls (s, v) l1) 0%Z);\n          [specialize (H3 _ v H7 H8);Omega.omega|].\n        destruct (HMatching1 _ n H7); contradiction.\nQed.\n\nLemma StepSubstitute_flatten m o l:\n  Step (flatten m) o l <-> StepSubstitute m o l.\nProof.\n  unfold flatten, getFlat, StepSubstitute.\n  split; intros.\n  - induction (getHidden m).\n    + simpl in *.\n      inv H.\n      split; [auto| split; [auto| intros; tauto]].\n    + simpl in *.\n      inv H.\n      specialize (IHl0 HStep); dest.\n      split; [auto| split; [auto| intros]].\n      rewrite createHide_Meths in *; simpl in *.\n      destruct H3; [subst |clear - H1 H2 H3; apply H1; auto].\n      eapply HHidden; eauto.\n  - induction (getHidden m); simpl; auto; dest.\n    + constructor; auto.\n    + assert (sth: Step (createHide (BaseMod (getAllRegisters m) (getAllRules m) (getAllMethods m)) l0) o l).\n      { eapply IHl0; repeat split; auto.\n        intros; apply H1; auto; right; assumption. }\n      assert (sth2: forall v, In (a, projT1 v) (getKindAttr (getAllMethods m)) -> (getListFullLabel_diff (a, v) l = 0%Z)).\n      { intros; apply H1; auto; left; reflexivity. }\n      constructor; auto.\n      rewrite createHide_Meths; auto.\nQed.\n    \nLemma Step_substitute ty m o l (HWfMod: WfMod ty m):\n  Step m o l -> Step (flatten m) o l.\nProof.\n  intros Stp.\n  apply (@Step_substitute' ty) in Stp; auto.\n  rewrite (@StepSubstitute_flatten) in *; auto.\nQed.\n\nLemma splitRegs o m1 m2 (DisjRegisters: DisjKey (getRegisters m1) (getRegisters m2)):\n  getKindAttr o = getKindAttr (getRegisters m1 ++ getRegisters m2) ->\n  getKindAttr (filter (fun x : string * {x : FullKind & fullType type x} => getBool (in_dec string_dec (fst x) (map fst (getRegisters m1)))) o) = getKindAttr (getRegisters m1).\nProof.\n  intros HRegs.\n  rewrite map_app in *.\n  pose proof (filter_map_simple (fun x: string * {x: FullKind & fullType type x} => (fst x, projT1 (snd x)))\n                                (fun x => getBool (in_dec string_dec (fst x) (map fst (getRegisters m1)))) o) as sth.\n  simpl in sth.\n  setoid_rewrite <- sth.\n  setoid_rewrite HRegs.\n  rewrite filter_app.\n  setoid_rewrite filter_false_list at 2.\n  - rewrite filter_true_list at 1.\n    + rewrite app_nil_r; auto.\n    + intros.\n      apply (in_map fst) in H.\n      rewrite map_map in H.\n      simpl in *.\n      setoid_rewrite (functional_extensionality (fun x => fst x) fst) in H; try tauto.\n      destruct (in_dec string_dec (fst a) (map fst (getRegisters m1))); auto.\n  - intros.\n    apply (in_map fst) in H.\n    rewrite map_map in H.\n    simpl in *.\n    setoid_rewrite (functional_extensionality (fun x => fst x) fst) in H; try tauto.\n    destruct (in_dec string_dec (fst a) (map fst (getRegisters m1))); auto.\n    specialize (DisjRegisters (fst a)).\n    tauto.\nQed.\n\nDefinition strcmp (s1 s2 : string) : bool := if (string_dec s1 s2) then true else false.\nDefinition BaseModuleFilter (m : BaseModule)(fl : FullLabel) : bool :=\n  match getRleOrMeth fl with\n  | Rle rn => existsb (strcmp rn) (map fst (getRules m))\n  | Meth f => existsb (strcmp (fst f)) (map fst (getMethods m))\n  end.\nDefinition ModuleFilterLabels (m : BaseModule)(l : list FullLabel) : list FullLabel := filter (BaseModuleFilter m) l.\n\nLemma InRules_Filter : forall (u : RegsT)(rn : string)(rb : Action Void)(l : list FullLabel)(cs : MethsT)(m1 : BaseModule),\n    In (rn, rb) (getRules m1) -> ModuleFilterLabels m1 ((u, (Rle rn, cs))::l) = ((u, (Rle rn, cs))::ModuleFilterLabels m1 l).\nProof.\n  intros. unfold ModuleFilterLabels, BaseModuleFilter. simpl.\n  generalize (existsb_exists (strcmp rn) (map fst (getRules m1))).\n  destruct (existsb (strcmp rn) (map fst (getRules m1))); intro;[reflexivity | destruct H0; clear H0].\n  assert (false=true);[apply H1; exists rn; split| discriminate].\n  - apply in_map_iff; exists (rn, rb); auto.\n  - unfold strcmp;destruct (string_dec rn rn);[reflexivity|contradiction].\nQed.\n\nLemma NotInRules_Filter : forall (u : RegsT)(rn : string)(l : list FullLabel)(cs : MethsT)(m1 : BaseModule),\n    ~In rn (map fst (getRules m1)) ->  ModuleFilterLabels m1 ((u, (Rle rn, cs))::l) = ModuleFilterLabels m1 l.\nProof.\n  intros. unfold ModuleFilterLabels, BaseModuleFilter. simpl.\n  generalize (existsb_exists (strcmp rn) (map fst (getRules m1))).\n  destruct (existsb (strcmp rn) (map fst (getRules m1))); intro H0; destruct H0;[|reflexivity].\n  apply False_ind; apply H.\n  assert (true=true) as TMP;[reflexivity|specialize (H0 TMP); dest].\n  unfold strcmp in H2; destruct (string_dec rn x); subst;[assumption|discriminate].\nQed.\n\nLemma InMethods_Filter : forall (u : RegsT)(fn : string)(fb : {x : Signature & MethodT x})\n                                (argV : type (fst (projT1 fb)))(retV : type (snd (projT1 fb)))\n                                (l : list FullLabel)(cs : MethsT)(m1 : BaseModule),\n    In (fn, fb) (getMethods m1) ->\n    ModuleFilterLabels m1 ((u, (Meth (fn, existT SignT (projT1 fb) (argV, retV)), cs))::l) = ((u, (Meth (fn, existT SignT (projT1 fb) (argV, retV)), cs)):: ModuleFilterLabels m1 l).\nProof.\n  intros. unfold ModuleFilterLabels, BaseModuleFilter. simpl.\n  generalize (existsb_exists (strcmp fn) (map fst (getMethods m1))).\n  destruct (existsb (strcmp fn) (map fst (getMethods m1))); intro;[reflexivity | destruct H0; clear H0].\n  assert (false=true);[apply H1; exists fn; split| discriminate].\n  - apply in_map_iff; exists (fn, fb); auto.\n  - unfold strcmp;destruct (string_dec fn fn);[reflexivity|contradiction].\nQed.\n\nLemma NotInMethods_Filter : forall  (u : RegsT)(fn : string)(fb : {x : Signature & MethodT x})\n                                  (argV : type (fst (projT1 fb)))(retV : type (snd (projT1 fb)))\n                                  (l : list FullLabel)(cs : MethsT)(m1 : BaseModule),\n    ~In fn (map fst (getMethods m1)) -> ModuleFilterLabels m1 ((u, (Meth (fn, existT SignT (projT1 fb) (argV, retV)), cs))::l) = ModuleFilterLabels m1 l.\nProof.\n  intros. unfold ModuleFilterLabels, BaseModuleFilter. simpl.\n  generalize (existsb_exists (strcmp fn) (map fst (getMethods m1))).\n  destruct (existsb (strcmp fn) (map fst (getMethods m1))); intro H0; destruct H0;[|reflexivity].\n  apply False_ind; apply H.\n  assert (true=true) as TMP;[reflexivity|specialize (H0 TMP); dest].\n  unfold strcmp in H2; destruct (string_dec fn x); subst;[assumption|discriminate].\nQed.\n\nLemma InCall_split_InCall f l m1 :\n  InCall f (ModuleFilterLabels m1 l) -> InCall f l.\nProof.\n  unfold InCall, ModuleFilterLabels.\n  intros; dest.\n  generalize (filter_In (BaseModuleFilter m1) x l) as TMP; intro; destruct TMP as [L R];clear R; apply L in H; destruct H.\n  exists x; split; assumption.\nQed.\n\nLemma InExec_split_InExec f l m1 :\n  InExec f (ModuleFilterLabels m1 l) -> InExec f l.\nProof.\n  unfold InExec, ModuleFilterLabels.\n  intros.\n  apply in_map_iff; apply in_map_iff in H;dest.\n  exists x; split;[assumption|].\n  generalize (filter_In (BaseModuleFilter m1) x l) as TMP; intro; destruct TMP as [L R]; clear R; apply L in H0; destruct H0.\n  assumption.\nQed.\n\nLemma InCall_perm l l' f :\n  InCall f l -> Permutation l l' -> InCall f l'.\n  induction 2. assumption.\n  - apply (InCall_app_iff f (x::nil) l').\n    apply (InCall_app_iff f (x::nil) l) in H.\n    destruct H;[left|right; apply IHPermutation];assumption.\n  - apply (InCall_app_iff f (x::y::nil) l).\n    apply (InCall_app_iff f (y::x::nil) l) in H.\n    destruct H;[left;apply (InCall_app_iff f (x::nil) (y::nil)) | right];[apply (InCall_app_iff f (y::nil) (x::nil)) in H; destruct H;[right|left]|];assumption.\n  - apply (IHPermutation2 (IHPermutation1 H)).\nQed.\n\nLemma InExec_perm l l' f :\n  InExec f l -> Permutation l l' -> InExec f l'.\n  induction 2. assumption.\n  - apply (InExec_app_iff f (x::nil) l').\n    apply (InExec_app_iff f (x::nil) l) in H.\n    destruct H;[left|right; apply IHPermutation];assumption.\n  - apply (InExec_app_iff f (x::y::nil) l).\n    apply (InExec_app_iff f (y::x::nil) l) in H.\n    destruct H;[left;apply (InExec_app_iff f (x::nil) (y::nil)) | right];[apply (InExec_app_iff f (y::nil) (x::nil)) in H; destruct H;[right|left]|];assumption.\n  - apply (IHPermutation2 (IHPermutation1 H)).\nQed.\n\nLemma MatchingExecCalls_Base_perm_rewrite l1 l2 m1 :\n  l1 [=] l2 -> MatchingExecCalls_Base l1 m1 -> MatchingExecCalls_Base l2 m1.\nProof.\n  intros HPerm HMec1 f HInDef.\n  specialize (HMec1 f HInDef).\n  repeat rewrite <-HPerm.\n  assumption.\nQed.\n\nGlobal Instance MatchingExecCalls_Base_perm_rewrite' :\n  Proper (@Permutation FullLabel ==> eq ==> iff) (@MatchingExecCalls_Base) | 10.\nProof.\n  repeat red; split; intros; subst; eauto using MatchingExecCalls_Base_perm_rewrite, Permutation_sym.\nQed.\n\nLemma MatchingExecCalls_Concat_perm1 l1 l2 l3 m1 :\n  l1 [=] l2 -> MatchingExecCalls_Concat l1 l3 m1 -> MatchingExecCalls_Concat l2 l3 m1.\nProof.\n  unfold MatchingExecCalls_Concat.\n  intros.\n  rewrite <-H.\n  apply H0; auto.\n  rewrite H; assumption.\nQed.\n\nLemma MatchingExecCalls_Concat_perm2 l1 l2 l3 m1 :\n  l1 [=] l2 -> MatchingExecCalls_Concat l3 l1 m1 -> MatchingExecCalls_Concat l3 l2 m1.\nProof.\n  unfold MatchingExecCalls_Concat.\n  intros.\n  rewrite <- H.\n  apply H0; auto.\nQed.\n\nCorollary MatchingExecCalls_Concat_rewrite l1 l2 l3 l4 m :\n  l1 [=] l2 -> l3 [=] l4 -> MatchingExecCalls_Concat l1 l3 m -> MatchingExecCalls_Concat l2 l4 m.\nProof.\n  eauto using MatchingExecCalls_Concat_perm1, MatchingExecCalls_Concat_perm2.\nQed.\n\nGlobal Instance MatchingExecCalls_Concat_rewrite' :\n  Proper (@Permutation FullLabel ==> @Permutation FullLabel ==> eq ==> iff) (@MatchingExecCalls_Concat) | 10.\nProof.\n  repeat red; intros; split; intro; subst; eauto using MatchingExecCalls_Concat_rewrite, Permutation_sym.\nQed.\n\nLemma InExec_ModuleFilterLabels : forall (f : MethT)(m : BaseModule)(l : list FullLabel),\n    In (fst f) (map fst (getMethods m)) ->\n    (getNumExecs f l = getNumExecs f (ModuleFilterLabels m l)).\nProof.\n  Opaque getNumFromExecs.\n  intros.\n  assert (existsb (strcmp (fst f)) (map fst (getMethods m)) = true);[apply (existsb_exists (strcmp (fst f))(map fst (getMethods m)));exists (fst f);split;\n                                                                     [assumption|unfold strcmp; destruct (string_dec(fst f)(fst f));[reflexivity|contradiction]]|].\n  induction l; auto.\n  - destruct a, p, r0.\n    + unfold ModuleFilterLabels, BaseModuleFilter, getNumExecs in *; simpl.\n      destruct (existsb (strcmp rn) (map fst (getRules m))); simpl;\n        rewrite getNumFromExecs_Rle_cons; assumption.\n    + unfold ModuleFilterLabels, BaseModuleFilter, getNumExecs in *; simpl.\n      destruct (MethT_dec f f0); subst;\n        [rewrite H0; simpl; repeat rewrite getNumFromExecs_eq_cons; auto; rewrite IHl; reflexivity|].\n      destruct (existsb (strcmp (fst f0)) (map fst (getMethods m)));\n        simpl; repeat rewrite getNumFromExecs_neq_cons; auto.\n  Transparent getNumFromExecs.\nQed.\n\nLemma getNumExecs_le_length (f : MethT) (l : list FullLabel) :\n  (getNumExecs f l <= Zlength l)%Z.\nProof.\n  Opaque getNumFromExecs.\n  induction l.\n  - reflexivity.\n  - destruct a, p, r0; unfold getNumExecs in *;simpl.\n    + rewrite getNumFromExecs_Rle_cons, Zlength_cons; Omega.omega.\n    + destruct (MethT_dec f f0); simpl in *;[rewrite getNumFromExecs_eq_cons|rewrite getNumFromExecs_neq_cons];auto; rewrite Zlength_cons; Omega.omega.\n  Transparent getNumFromExecs.\nQed.\n\nLemma getNumFromCalls_le_length (f : MethT) (l : MethsT):\n  (getNumFromCalls f l <= Zlength l)%Z.\nProof.\n  induction l.\n  - reflexivity.\n  - destruct (MethT_dec f a);[rewrite getNumFromCalls_eq_cons|rewrite getNumFromCalls_neq_cons]; auto; rewrite Zlength_cons; Omega.omega.\nQed.\n\nLemma filter_reduces_calls (f : MethT) (g : FullLabel -> bool) (l : list FullLabel) :\n  (getNumCalls f (filter g l) <= getNumCalls f l)%Z.\nProof.\n  induction l; simpl.\n  - reflexivity.\n  - specialize (getNumFromCalls_nonneg f (snd (snd a))) as P1.\n    destruct (g a); repeat rewrite getNumCalls_cons; Omega.omega.\nQed.\n\nLemma filter_reduces_execs (f : MethT) (g : FullLabel -> bool) (l : list FullLabel) :\n  (getNumExecs f (filter g l) <= getNumExecs f l)%Z.\nProof.\n  Opaque getNumFromExecs.\n  induction l; simpl.\n  - reflexivity.\n  - destruct (g a), a, p, r0; unfold getNumExecs in *; simpl in *.\n    + repeat rewrite getNumFromExecs_Rle_cons; assumption.\n    + destruct (MethT_dec f f0);[repeat rewrite getNumFromExecs_eq_cons|repeat rewrite getNumFromExecs_neq_cons];auto;Omega.omega.\n    + rewrite getNumFromExecs_Rle_cons; assumption.\n    + destruct (MethT_dec f f0);[rewrite getNumFromExecs_eq_cons|rewrite getNumFromExecs_neq_cons];auto;Omega.omega.\n  Transparent getNumFromExecs.\nQed.\n\nLemma MatchingExecCalls_Split (l : list FullLabel) (m1 m2 : BaseModule) :\n    MatchingExecCalls_Base l (concatFlat m1 m2) ->\n    MatchingExecCalls_Base (ModuleFilterLabels m1 l) m1.\nProof.\n  intros Mec1 f HDef.\n  specialize (Mec1 f); simpl in *.\n  rewrite map_app, in_app_iff in *.\n  specialize (Mec1 (or_introl _ HDef)).\n  unfold ModuleFilterLabels.\n  specialize (filter_reduces_calls f (BaseModuleFilter m1) l) as P1.\n  fold ((ModuleFilterLabels m1) l).\n  rewrite <-InExec_ModuleFilterLabels; eauto using Z.le_trans.\n  apply (in_map fst) in HDef; rewrite fst_getKindAttr in HDef; assumption.\nQed.\n\nLemma MatchingExecCalls_Split2 (l : list FullLabel) (m1 m2 : BaseModule) :\n    MatchingExecCalls_Base l (concatFlat m1 m2) ->\n    MatchingExecCalls_Base (ModuleFilterLabels m2 l) m2.\nProof.\n  intros Mec1 f HDef.\n  specialize (Mec1 f); simpl in *.\n  rewrite map_app, in_app_iff in *.\n  specialize (Mec1 (or_intror _ HDef)).\n  unfold ModuleFilterLabels.\n  specialize (filter_reduces_calls f (BaseModuleFilter m2) l) as P1.\n  fold ((ModuleFilterLabels m2) l).\n  rewrite <-InExec_ModuleFilterLabels; eauto using Z.le_trans.\n  apply (in_map fst) in HDef; rewrite fst_getKindAttr in HDef; assumption.\nQed.\n\nLemma MatchingExecCalls_Concat_comm : forall (l l' : list FullLabel) (m1 m2 : BaseModule),\n    MatchingExecCalls_Concat l l' (Base (concatFlat m1 m2)) -> MatchingExecCalls_Concat l l' (Base (concatFlat m2 m1)).\nProof.\n  repeat intro.\n  specialize (H f H0).\n  simpl in *. apply H.\n  rewrite (map_app) in *; apply in_app_iff; apply in_app_iff in H1.\n  tauto.\nQed.\n\nLemma MatchingExecCalls_Base_comm : forall (l : list FullLabel) (m1 m2 : BaseModule),\n    MatchingExecCalls_Base l (concatFlat m1 m2) -> MatchingExecCalls_Base l (concatFlat m2 m1).\nProof.\n  repeat intro.\n  specialize (H f).\n  simpl in *; apply H; auto.\n  rewrite map_app, in_app_iff in *; tauto.\nQed.\n\n\n Lemma WfActionT_ReadsWellDefined : forall (k : Kind)(a : ActionT type k)(retl : type k)\n                                          (m1 : BaseModule)(o readRegs newRegs : RegsT)(calls : MethsT),\n    WfActionT (getRegisters m1) a ->\n    SemAction o a readRegs newRegs calls retl ->\n    SubList (getKindAttr readRegs) (getKindAttr (getRegisters m1)).\nProof.\n  induction 2; intros; subst; inversion H; EqDep_subst; auto.\n  - rewrite map_app. repeat intro. apply in_app_iff in H0; destruct H0.\n    + apply (IHSemAction1 H3 _ H0).\n    + apply (IHSemAction2 (H5 v) _ H0).\n  - inversion H; EqDep_subst. repeat intro. destruct H1;[subst;assumption|apply IHSemAction; auto].\n  - rewrite map_app; repeat intro. apply in_app_iff in H0; destruct H0.\n    + apply (IHSemAction1 H7 _ H0).\n    + apply (IHSemAction2 (H4 r1) _ H0).\n  - inversion H; EqDep_subst. rewrite map_app; repeat intro. apply in_app_iff in H0; destruct H0.\n    + apply (IHSemAction1 H8 _ H0).\n    + apply (IHSemAction2 (H4 r1) _ H0).\n  - repeat intro; auto. contradiction.\nQed.\n\nLemma WfActionT_WritesWellDefined : forall (k : Kind)(a : ActionT type k)(retl : type k)\n                                           (m1 : BaseModule)(o readRegs newRegs : RegsT)(calls : MethsT),\n    WfActionT (getRegisters m1) a ->\n    SemAction o a readRegs newRegs calls retl ->\n    SubList (getKindAttr newRegs) (getKindAttr (getRegisters m1)).\nProof.\n  induction 2; intros; subst; inversion H; EqDep_subst; auto.\n  - rewrite map_app. repeat intro. apply in_app_iff in H0; destruct H0.\n    + apply (IHSemAction1 H3 _ H0).\n    + apply (IHSemAction2 (H5 v) _ H0).\n  - inversion H; EqDep_subst. repeat intro. destruct H1;[subst;assumption|apply IHSemAction; auto].\n  - rewrite map_app; repeat intro. apply in_app_iff in H0; destruct H0.\n    + apply (IHSemAction1 H7 _ H0).\n    + apply (IHSemAction2 (H4 r1) _ H0).\n  - inversion H; EqDep_subst. rewrite map_app; repeat intro. apply in_app_iff in H0; destruct H0.\n    + apply (IHSemAction1 H8 _ H0).\n    + apply (IHSemAction2 (H4 r1) _ H0).\n  - repeat intro; auto. contradiction.\nQed.\n\nLemma KeyMatching : forall (l : RegsT) (a b : string * {x : FullKind & fullType type x}),\n    NoDup (map fst l) -> In a l -> In b l -> fst a = fst b -> a = b.\nProof.\n  induction l; intros.\n  - inversion H0.\n  - destruct H0; destruct H1.\n    + symmetry; rewrite <- H1; assumption.\n    + rewrite (map_cons fst) in H.\n      inversion H; subst.\n      apply (in_map fst l b) in H1.\n      apply False_ind. apply H5.\n      destruct a0; destruct b; simpl in *.\n      rewrite H2; assumption.\n    + rewrite (map_cons fst) in H.\n      inversion H; subst.\n      apply (in_map fst l a0) in H0.\n      apply False_ind; apply H5.\n      destruct a0, b; simpl in *.\n      rewrite <- H2; assumption.\n    + inversion H; subst.\n      apply IHl; auto.\nQed.\n\nLemma KeyRefinement : forall (l l' : RegsT) (a : string * {x: FullKind & fullType type x}),\n    NoDup (map fst l) -> SubList l' l -> In a l -> In (fst a) (map fst l') -> In a l'.\nProof.\n  induction l'; intros; inversion H2; subst.\n  - assert (In a (a::l')) as TMP;[left; reflexivity|specialize (H0 _ TMP); rewrite (KeyMatching _ _ _ H H0 H1 H3); left; reflexivity].\n  - right; apply IHl'; auto.\n    repeat intro.\n    apply (H0 x (or_intror _ H4)).\nQed.\n\nLemma GKA_fst : forall (A B : Type)(P : B -> Type)(o : list (A * {x : B & P x})),\n    (map fst o) = (map fst (getKindAttr o)).\nProof.\n  induction o; simpl.\n  - reflexivity.\n  - rewrite IHo.\n    reflexivity.\nQed.\n\nLemma NoDupKey_Expand : forall (A B : Type)(l1 l2 : list (A * B)),\n    NoDup (map fst l1) ->\n    NoDup (map fst l2) ->\n    DisjKey l1 l2 ->\n    NoDup (map fst (l1++l2)).\nProof.\n  intros; rewrite (map_app fst).\n  induction l1; auto.\n  inversion_clear H.\n  destruct (H1 (fst a)).\n  - apply False_ind. apply H; left; reflexivity.\n  - assert (~(In (fst a) ((map fst l1)++(map fst l2)))).\n    + intro in_app12; apply in_app_iff in in_app12; destruct in_app12;[apply H2|apply H]; assumption.\n    + assert (DisjKey l1 l2); repeat intro.\n      * destruct (H1 k);[left|right];intro; apply H5;simpl;auto.\n      * apply (NoDup_cons (fst a) (l:=(map fst l1 ++ map fst l2)) H4 (IHl1 H3 H5)).\nQed.\n\nLemma WfActionT_SemAction : forall (k : Kind)(a : ActionT type k)(retl : type k)\n                                   (m1 : BaseModule)(o readRegs newRegs : RegsT)(calls : MethsT),\n    WfActionT (getRegisters m1) a ->\n    NoDup (map fst o) ->\n    SemAction o a readRegs newRegs calls retl ->\n    (forall (o1 : RegsT),\n        SubList o1 o ->\n        getKindAttr o1 = getKindAttr (getRegisters m1) ->\n        SemAction o1 a readRegs newRegs calls retl).\n  induction 3; intro; subst; inversion H; EqDep_subst.\n  - intros TMP1 TMP2; specialize (IHSemAction (H4 mret) o1 TMP1 TMP2).\n    econstructor 1; eauto.\n  - intros TMP1 TMP2; specialize (IHSemAction (H4 (evalExpr e)) o1 TMP1 TMP2).\n    econstructor 2; eauto.\n  - intros TMP1 TMP2; specialize (IHSemAction1 (H4) o1 TMP1 TMP2); specialize (IHSemAction2 (H6 v) o1 TMP1 TMP2).\n    econstructor 3; eauto.\n  - intros TMP1 TMP2; specialize (IHSemAction (H4 valueV) o1 TMP1 TMP2).\n    econstructor 4; eauto.\n  - intros TMP1 TMP2; specialize (IHSemAction (H5 regV) o1 TMP1 TMP2).\n    econstructor 5; eauto.\n    apply (KeyRefinement (r, existT (fullType type) regT regV) H0 TMP1 HRegVal).\n    change (fun x => RegInitValT x) with RegInitValT in H7.\n    rewrite <- TMP2 in H7; apply (in_map fst) in H7; specialize (GKA_fst (A:=string)(fullType type) o1); intro.\n    simpl in *.\n    setoid_rewrite H2; assumption.\n  - intros TMP1 TMP2; specialize (IHSemAction H5 o1 TMP1 TMP2).\n    econstructor 6; eauto.\n    rewrite TMP2; assumption.\n  - intros TMP1 TMP2; specialize (IHSemAction1 H8 o1 TMP1 TMP2); specialize (IHSemAction2 (H5 r1) o1 TMP1 TMP2).\n    econstructor 7; eauto.\n  - intros TMP1 TMP2; specialize (IHSemAction1 H9 o1 TMP1 TMP2); specialize (IHSemAction2 (H5 r1) o1 TMP1 TMP2).\n    econstructor 8; eauto.\n  - intros TMP1 TMP2; specialize (IHSemAction H4 o1 TMP1 TMP2).\n    econstructor 9; eauto.\n  - intros; econstructor 10; eauto.\nQed.\n\nLemma app_sublist_l : forall {A : Type} (l1 l2 l : list A),\n    l = l1++l2 -> SubList l1 l.\nProof.\n  repeat intro.\n  rewrite H.\n  apply (in_app_iff l1 l2 x); left; assumption.\nQed.\n\nLemma app_sublist_r : forall {A : Type} (l1 l2 l : list A),\n    l = l1++l2 -> SubList l2 l.\nProof.\n  repeat intro.\n  rewrite H.\n  apply (in_app_iff l1 l2 x); right; assumption.\nQed.\n\nSection SplitSubsteps.\n  Variable m1 m2: BaseModule.\n  Variable DisjRegs: DisjKey (getRegisters m1) (getRegisters m2).\n  Variable DisjRules: DisjKey (getRules m1) (getRules m2).\n  Variable DisjMeths: DisjKey (getMethods m1) (getMethods m2).\n\n  Variable WfMod1: WfBaseModule type m1.\n  Variable WfMod2: WfBaseModule type m2.\n  \n  Lemma filter_perm o l :\n    Substeps (concatFlat m1 m2) o l ->\n    Permutation l ((ModuleFilterLabels m1 l)++(ModuleFilterLabels m2 l)).\n    induction 1; subst.\n    - simpl; apply Permutation_refl.\n    - apply in_app_iff in HInRules.\n      destruct HInRules as [HInRules | HInRules]; rewrite (InRules_Filter _ _ _ _ _ _ HInRules).\n      + destruct (DisjRules rn).\n        * generalize (in_map_iff fst (getRules m1) rn). intro TMP; destruct TMP as [L R];clear L.\n          assert (exists x, fst x = rn /\\ In x (getRules m1));[exists (rn, rb); auto| specialize (R H1); contradiction].\n        * rewrite (NotInRules_Filter _ _ _ _ _ H0).\n          constructor. assumption.\n      + destruct (DisjRules rn).\n        * rewrite (NotInRules_Filter _ _ _ _ _ H0).\n          apply (Permutation_cons_app _ _ _ IHSubsteps).\n        * generalize (in_map_iff fst (getRules m2) rn). intro TMP; destruct TMP as [L R];clear L.\n          assert (exists x, fst x = rn /\\ In x (getRules m2));[exists (rn, rb); auto | specialize (R H1); contradiction].\n    - apply in_app_iff in HInMeths.\n      destruct HInMeths as [HInMeths | HInMeths]; rewrite (InMethods_Filter _ _ _ _ _ _ _ _ HInMeths).\n      + destruct (DisjMeths fn).\n        * generalize (in_map_iff fst (getMethods m1) fn). intro TMP; destruct TMP as [L R]; clear L.\n          assert (exists x, fst x = fn /\\ In x (getMethods m1)); [exists (fn, fb); auto| specialize (R H1); contradiction].\n        * rewrite (NotInMethods_Filter _ _ _ _ _ _ _ _ H0).\n          constructor. assumption.\n      + destruct (DisjMeths fn).\n        * rewrite (NotInMethods_Filter _ _ _ _ _ _ _ _ H0).\n          apply (Permutation_cons_app _ _ _ IHSubsteps).\n        * generalize (in_map_iff fst (getMethods m2) fn). intro TMP; destruct TMP as [L R]; clear L.\n          assert (exists x, fst x = fn /\\ In x (getMethods m2)); [exists (fn, fb); auto| specialize (R H1); contradiction].\n  Qed.\n\n\n  Lemma MatchingExecCalls_Mix2 : forall (l : list FullLabel) (o : RegsT),\n      Substeps (concatFlat m1 m2) o l ->\n      MatchingExecCalls_Base l (concatFlat m1 m2) ->\n      MatchingExecCalls_Concat (ModuleFilterLabels m1 l) (ModuleFilterLabels m2 l) (Base m2).\n  Proof.\n    repeat intro. split;[auto|].\n    rewrite <- getNumCalls_app.\n    rewrite <- (filter_perm H).\n    specialize (H0 f); simpl in *;rewrite map_app, in_app_iff in H0.\n    specialize (H0 (or_intror _ H2)).\n    rewrite <-InExec_ModuleFilterLabels; auto.\n    apply (in_map fst) in H2; rewrite fst_getKindAttr in H2; assumption.\n  Qed.\n\n\n  Lemma MatchingExecCalls_Mix1 : forall (l : list FullLabel) (o : RegsT),\n      Substeps (concatFlat m1 m2) o l ->\n      MatchingExecCalls_Base l (concatFlat m1 m2) ->\n      MatchingExecCalls_Concat (ModuleFilterLabels m2 l) (ModuleFilterLabels m1 l) (Base m1).\n  Proof.\n    repeat intro. split;[auto|].\n    rewrite Z.add_comm.\n    rewrite <- getNumCalls_app.\n    rewrite <- (filter_perm H).\n    specialize (H0 f); simpl in *;rewrite map_app, in_app_iff in H0.\n    specialize (H0 (or_introl _ H2)).\n    rewrite <-InExec_ModuleFilterLabels; auto.\n    apply (in_map fst) in H2; rewrite fst_getKindAttr in H2; assumption.\n  Qed.\n  \n  Lemma split_Substeps1 o l:\n    NoDup (map fst (getRegisters m1)) ->\n    NoDup (map fst (getRegisters m2)) ->\n    Substeps (concatFlat m1 m2) o l ->\n    (exists o1 o2, getKindAttr o1 = getKindAttr (getRegisters m1) /\\\n                   getKindAttr o2 = getKindAttr (getRegisters m2) /\\\n                   o = o1++o2 /\\\n                   Substeps m1 o1 (ModuleFilterLabels m1 l) /\\\n                   Substeps m2 o2 (ModuleFilterLabels m2 l)).\n  Proof.\n    unfold concatFlat; induction 3; simpl in *.\n    - rewrite map_app in *; apply list_split in HRegs; dest.\n      exists x, x0;split;[|split;[|split;[|split;[constructor|constructor]]]];assumption.\n    - rewrite map_app in *;apply in_app_iff in HInRules; specialize (DisjRules rn).\n      assert (NoDup (map fst o));[setoid_rewrite GKA_fst;setoid_rewrite HRegs; rewrite <- map_app; rewrite <- GKA_fst; apply (NoDupKey_Expand H H0 DisjRegs)|].\n      destruct HInRules as [HInRules|HInRules];generalize (in_map fst _ _ HInRules);destruct DisjRules;try contradiction.\n      + subst; dest; exists x, x0;split;[|split;[|split;[|split]]];auto.\n        rewrite (InRules_Filter _ _ _ _ _ _ HInRules).\n        destruct (WfMod1) as [WfMod_Rle1 WfMod_Meth1];destruct (WfMod2) as [WfMod_Rle2 WfMod_Meth2].\n        specialize (WfActionT_ReadsWellDefined _ (@WfMod_Rle1 _ HInRules) HAction) as Reads_sublist; specialize (WfActionT_WritesWellDefined _ (WfMod_Rle1 _ HInRules) HAction) as Writes_sublist.\n        constructor 2 with (rn:= rn)(rb:=rb)(reads:=reads)(u:=u)(cs:=cs)(ls:=(ModuleFilterLabels m1 ls)); auto.\n        * specialize (app_sublist_l _ _ H6) as SL_o_x.\n          specialize (WfMod_Rle1 (rn, rb) HInRules); specialize (WfActionT_SemAction _ WfMod_Rle1 H2 HAction SL_o_x H4).\n          simpl; auto.\n        * unfold ModuleFilterLabels;intros;apply HDisjRegs;\n            destruct (filter_In (BaseModuleFilter m1) x1 ls) as [L R];\n            destruct (L H10);assumption.\n        * intros; apply HNoRle;\n            destruct (filter_In (BaseModuleFilter m1) x1 ls) as [L R];\n            destruct (L H10);assumption.\n        * rewrite (NotInRules_Filter _ _ _ _ _ H3); assumption.\n      + subst; dest; exists x, x0; split;[|split;[|split;[|split]]];auto.\n        rewrite (NotInRules_Filter _ _ _ _ _ H3); assumption.\n        rewrite (InRules_Filter _ _ _ _ _ _ HInRules).\n        destruct (WfMod1) as [WfMod_Rle1 WfMod_Meth1];destruct (WfMod2) as [WfMod_Rle2 WfMod_Meth2]; specialize (WfActionT_ReadsWellDefined _ (WfMod_Rle2 _ HInRules) HAction) as Reads_sublist; specialize (WfActionT_WritesWellDefined _ (WfMod_Rle2 _ HInRules) HAction) as Writes_sublist.\n        constructor 2 with (rn:= rn)(rb:=rb)(reads:=reads)(u:=u)(cs:=cs)(ls:=(ModuleFilterLabels m2 ls)); auto.\n        * specialize (app_sublist_r _ _ H6) as SL_o_x.\n          specialize (WfMod_Rle2 (rn, rb) HInRules); specialize (WfActionT_SemAction _ WfMod_Rle2 H2 HAction SL_o_x H5).\n          simpl; auto.\n        * unfold ModuleFilterLabels;intros;apply HDisjRegs;\n            destruct (filter_In (BaseModuleFilter m2) x1 ls) as [L R];\n            destruct (L H10);assumption.\n        * intros; apply HNoRle;\n            destruct (filter_In (BaseModuleFilter m2) x1 ls) as [L R];\n            destruct (L H10);assumption.\n    - rewrite map_app in *;apply in_app_iff in HInMeths; specialize (DisjMeths fn).\n      assert (NoDup (map fst o));[setoid_rewrite GKA_fst;setoid_rewrite HRegs; rewrite <- map_app; rewrite <- GKA_fst; apply (NoDupKey_Expand H H0 DisjRegs)|].\n      destruct HInMeths as [HInMeths|HInMeths];generalize (in_map fst _ _ HInMeths);destruct DisjMeths;try contradiction;intros.\n      + subst; dest; exists x, x0;split;[|split;[|split;[|split]]];auto.\n        * rewrite (InMethods_Filter _ _ _ _ _ _ _ _ HInMeths).\n          destruct (WfMod1) as [WfMod_Rle1 [WfMod_Meth1 _]];destruct (WfMod2) as [WfMod_Rle2 [WfMod_Meth2 _]].\n          specialize (WfActionT_ReadsWellDefined _ (WfMod_Meth1 (fn, fb) HInMeths argV) HAction) as Reads_sublist.\n          specialize (WfActionT_WritesWellDefined _ (WfMod_Meth1 (fn, fb) HInMeths argV) HAction) as Writes_sublist.\n          constructor 3 with (fn:=fn)(fb:=fb)(reads:=reads)(u:=u)(cs:=cs)(argV:=argV)(retV:=retV)(ls:=(ModuleFilterLabels m1 ls)); auto.\n          -- specialize (app_sublist_l _ _ H7) as SL_o_x.\n             specialize (WfMod_Meth1 (fn, fb) HInMeths argV); specialize (WfActionT_SemAction _ WfMod_Meth1 H2 HAction SL_o_x H5).\n             simpl; auto.\n          -- intros; apply HDisjRegs;\n               destruct (filter_In (BaseModuleFilter m1) x1 ls) as [L R];\n               destruct (L H10); assumption.\n        * rewrite (NotInMethods_Filter _ _ _ _ _ _ _ _ H3); assumption.\n      + subst; dest; exists x, x0;split;[|split;[|split;[|split]]]; auto.\n        * rewrite (NotInMethods_Filter _ _ _ _ _ _ _ _ H3); assumption.\n        * rewrite (InMethods_Filter _ _ _ _ _ _ _ _ HInMeths).\n          destruct (WfMod1) as [WfMod_Rle1 [WfMod_Meth1 _]];destruct (WfMod2) as [WfMod_Rle2 [WfMod_Meth2 _]].\n          specialize (WfActionT_ReadsWellDefined _ (WfMod_Meth2 (fn, fb) HInMeths argV) HAction) as Reads_sublist.\n          specialize (WfActionT_WritesWellDefined _ (WfMod_Meth2 (fn, fb) HInMeths argV) HAction) as Writes_sublist.\n          constructor 3 with (fn:=fn)(fb:=fb)(reads:=reads)(u:=u)(cs:=cs)(argV:=argV)(retV:=retV)(ls:=(ModuleFilterLabels m2 ls)); auto.\n          -- specialize (app_sublist_r _ _ H7) as SL_o_x.\n             specialize (WfMod_Meth2 (fn, fb) HInMeths argV); specialize (WfActionT_SemAction _ WfMod_Meth2 H2 HAction SL_o_x H6).\n             simpl; auto.\n          -- intros; apply HDisjRegs;\n               destruct (filter_In (BaseModuleFilter m2) x1 ls) as [L R];\n               destruct (L H10); assumption.\n  Qed.\n  \n  Lemma split_Substeps2 o l:\n    Substeps (concatFlat m1 m2) o l ->\n      (forall x y : FullLabel,\n          In x (ModuleFilterLabels m1 l) ->\n          In y (ModuleFilterLabels m2 l) ->\n          match fst (snd x) with\n          | Rle _ => match fst (snd y) with\n                     | Rle _ => False\n                     | Meth _ => True\n                     end\n          | Meth _ => True\n          end).\n  Proof.\n    induction 1; intros; auto; subst.\n    - intros; contradiction.\n    - simpl in HInRules.\n      destruct (in_app_or _ _ _ HInRules) as [Rle_in | Rle_in]; specialize (in_map fst _ _ Rle_in) as map_Rle_in; destruct (DisjRules rn); try contradiction; rewrite (InRules_Filter u _ _ ls cs _ Rle_in) in *;rewrite (NotInRules_Filter u _ ls cs _ H2) in *; intros.\n      + destruct H0.\n        * rewrite <- H0; simpl.\n          apply HNoRle.\n          unfold ModuleFilterLabels in H1; apply filter_In in H1; destruct H1; assumption.\n        * eapply IHSubsteps; eauto.\n      + destruct H1.\n        * rewrite <- H1; simpl.\n          apply HNoRle.\n          unfold ModuleFilterLabels in H0; apply filter_In in H0; destruct H0; assumption.\n        * eapply IHSubsteps; eauto.\n    - simpl in HInMeths; rewrite in_app_iff in HInMeths; destruct HInMeths, (DisjMeths fn);specialize (in_map fst _ _ H2) as P1 ; try contradiction.\n      + setoid_rewrite (NotInMethods_Filter u _ fb argV retV ls cs _ H3) in H1.\n        setoid_rewrite (InMethods_Filter _ _ _ _ _ _ _ _ H2) in H0.\n        destruct H0;[subst;simpl in *;auto|].\n        apply IHSubsteps; auto.\n      + setoid_rewrite (NotInMethods_Filter u _ fb argV retV ls cs _ H3) in H0.\n        setoid_rewrite (InMethods_Filter _ _ _ _ _ _ _ _ H2) in H1.\n        destruct H1;[subst;simpl in *;destruct x,p,r0;simpl;auto|].\n        apply IHSubsteps;auto.\n  Qed.\n\nEnd SplitSubsteps.\n\nDefinition PWeakInclusion (l1 l2 : list FullLabel) : Prop := \n     (forall f : MethT, InExec f l1 /\\ ~ InCall f l1 <-> InExec f l2 /\\ ~ InCall f l2) /\\\n     (forall f : MethT, ~ InExec f l1 /\\ InCall f l1 <-> ~ InExec f l2 /\\ InCall f l2) /\\\n     (forall f : MethT, InExec f l1 /\\ InCall f l1 \\/ (forall v, ~ InExec (fst f, v) l1 ) /\\ (forall v, ~ InCall (fst f, v) l1) <-> InExec f l2 /\\ InCall f l2 \\/ (forall v, ~ InExec (fst f, v) l2) /\\ (forall v, ~ InCall (fst f, v) l2))\n     /\\ ((exists rle : string, In (Rle rle) (map getRleOrMeth l2)) -> exists rle : string, In (Rle rle) (map getRleOrMeth l1)).\n\n\nLemma InExec_app_comm : forall l1 l2 e, InExec e (l1++l2) -> InExec e (l2++l1).\nProof.\n  intros; rewrite InExec_app_iff in *; firstorder.\nQed.\n\nLemma InCall_app_comm : forall l1 l2 e, InCall e (l1++l2) -> InCall e (l2++l1).\nProof.\n  intros; rewrite InCall_app_iff in *; firstorder.\nQed.\n\nLemma WeakInclusion_app_comm : forall l1 l2, WeakInclusion (l1++l2)(l2++l1).\nProof.\n  intros.\n  unfold WeakInclusion;split;intros.\n  - unfold getListFullLabel_diff; repeat rewrite getNumExecs_app, getNumCalls_app; ring.\n  - dest; exists x; rewrite map_app,in_app_iff in *; firstorder fail.\nQed.\n\nDefinition WeakEquality (l1 l2 : list FullLabel) : Prop :=\n  WeakInclusion l1 l2 /\\ WeakInclusion l2 l1.\n\nLemma commutative_Concat : forall m1 m2 o l,\n    Step (ConcatMod m1 m2) o l ->\n    exists l' o',\n      Step (ConcatMod m2 m1) o' l' /\\\n      WeakEquality l l'.\nProof.\n  intros.\n  inversion_clear H.\n  exists (l2++l1).\n  exists (o2++o1).\n  split.\n  econstructor; try eassumption.\n  intros.\n  generalize (HNoRle y x H0 H).\n  intros.\n  destruct x. subst.\n  destruct y. simpl in *.\n  destruct p. destruct p0.\n  simpl in *.\n  destruct r2. assumption. destruct r1. assumption. assumption.\n  reflexivity.\n  reflexivity.\n  subst.\n  split.\n  apply WeakInclusion_app_comm.\n  apply WeakInclusion_app_comm.\nQed.\n\nLemma WeakInclusionRefl : forall l, WeakInclusion l l.\n  intros.\n  unfold WeakInclusion.\n  split;intros; try assumption.\n  reflexivity.\nQed.\n\nCorollary WeakEqualityRefl : forall l, WeakEquality l l.\n  intros.\n  unfold WeakEquality.\n  split; apply WeakInclusionRefl.\nQed.\n\nLemma WeakInclusionTrans : forall l1 l2 l3, WeakInclusion l1 l2 -> WeakInclusion l2 l3 -> WeakInclusion l1 l3.\n  intros.\n  unfold WeakInclusion in *.\n  dest.\n  split;intros;eauto using eq_trans.\nQed.\n\nCorollary WeakEqualityTrans : forall l1 l2 l3, WeakEquality l1 l2 -> WeakEquality l2 l3 -> WeakEquality l1 l3.\n  unfold WeakEquality; intros;dest; split; eauto using WeakInclusionTrans.\nQed.\n\nLemma WeakEqualitySym : forall l1 l2, WeakEquality l1 l2 -> WeakEquality l2 l1.\n  intros.\n  destruct H; split; auto.\nQed.\n\nLemma WfNoDups ty m (HWfMod : WfMod ty m) :\n    NoDup (map fst (getAllRegisters m)) /\\\n    NoDup (map fst (getAllMethods m))   /\\\n    NoDup (map fst (getAllRules m)).\nProof.\n  specialize (HWfMod).\n  induction m.\n  - inv HWfMod.\n    inv HWfBaseModule.\n    dest.\n    tauto.\n  - inversion HWfMod; subst; apply IHm in HWf.\n    assumption.\n  - inversion HWfMod;subst;destruct (IHm1 HWf1) as [ND_Regs1 [ND_Meths1 ND_Rles1]];destruct (IHm2 HWf2) as [ND_Regs2 [ND_Meths2 ND_Rles2]];split;[|split].\n    + simpl;rewrite map_app.\n      induction (getAllRegisters m1); simpl;[assumption|].\n      constructor.\n      * intro.\n        destruct (HDisjRegs (fst a));apply H0;[left; reflexivity|].\n        inversion_clear ND_Regs1.\n        apply in_app_or in H; destruct H; contradiction.\n      * apply (IHl).\n        intro;split;[|split];auto.\n        -- inversion_clear ND_Regs1; assumption.\n        -- unfold DisjKey; intro; destruct (HDisjRegs k);[left|right]; intro; apply H; auto.\n           right; assumption.\n        -- inversion_clear ND_Regs1; assumption.\n    + simpl;rewrite map_app.\n      induction (getAllMethods m1); simpl;[assumption|].\n      constructor.\n      * intro.\n        destruct (HDisjMeths (fst a));apply H0;[left; reflexivity|].\n        inversion_clear ND_Meths1.\n        apply in_app_or in H; destruct H; contradiction.\n      * apply (IHl).\n        intro;split;[|split];auto.\n        -- inversion_clear ND_Meths1; assumption.\n        -- unfold DisjKey; intro; destruct (HDisjMeths k);[left|right]; intro; apply H; auto.\n           right; assumption.\n        -- inversion_clear ND_Meths1; assumption.\n    + simpl;rewrite map_app.\n      induction (getAllRules m1); simpl;[assumption|].\n      constructor.\n      * intro.\n        destruct (HDisjRules (fst a));apply H0;[left; reflexivity|].\n        inversion_clear ND_Rles1.\n        apply in_app_or in H; destruct H; contradiction.\n      * apply (IHl).\n        intro;split;[|split];auto.\n        -- inversion_clear ND_Rles1; assumption.\n        -- unfold DisjKey; intro; destruct (HDisjRules k);[left|right]; intro; apply H; auto.\n           right; assumption.\n        -- inversion_clear ND_Rles1; assumption.\nQed.\n\nLemma WfMod_WfBaseMod_flat ty m (HWfMod : WfMod ty m):\n  WfBaseModule ty (getFlat m).\nProof.\n  specialize (HWfMod).\n  unfold getFlat;induction m.\n  - simpl; inversion HWfMod; subst; destruct HWfBaseModule.\n    unfold WfBaseModule in *; split; intros.\n    + specialize (H rule H1).\n      induction H; econstructor; eauto.\n    + dest; intros.\n      repeat split; auto; intros.\n  - inversion_clear HWfMod.\n    specialize (IHm HWf).\n    assumption.\n  - inversion_clear HWfMod.\n    specialize (IHm1 HWf1).\n    specialize (IHm2 HWf2).\n    simpl in *.\n    constructor;simpl; repeat split; auto; intros; try destruct (in_app_or _ _ _ H) as [In1 | In1].\n    + destruct IHm1 as [Rle Meth]; clear Meth; specialize (Rle _ In1).\n      induction Rle; econstructor; eauto; setoid_rewrite map_app; apply in_or_app;left; assumption.\n    + destruct IHm2 as [Rle Meth]; clear Meth; specialize (Rle _ In1).\n      induction Rle; econstructor; eauto; setoid_rewrite map_app; apply in_or_app;right; assumption.\n    + destruct IHm1 as [Rle [Meth _]]; clear Rle; specialize (Meth _ In1 v).\n      induction Meth; econstructor; eauto; setoid_rewrite map_app; apply in_or_app;left; assumption.\n    + destruct IHm2 as [Rle [Meth _]]; clear Rle; specialize (Meth _ In1 v).\n      induction Meth; econstructor; eauto; setoid_rewrite map_app; apply in_or_app;right;assumption.\n    + inv IHm1; inv IHm2; dest; apply NoDup_DisjKey; auto.\n    + inv IHm1; inv IHm2; dest; apply NoDup_DisjKey; auto.\n    + inv IHm1; inv IHm2; dest; apply NoDup_DisjKey; auto.\nQed.\n\nLemma WfConcatNotInCalls : forall (m : Mod)(o : RegsT)(k : Kind)(a : ActionT type k)\n                                  (readRegs newRegs : RegsT)(cs : MethsT)(fret : type k)\n                                  (f : MethT),\n    WfConcatActionT a m ->\n    SemAction o a readRegs newRegs cs fret ->\n    In (fst f) (getHidden m) ->\n    ~In f cs.\nProof.\n  intros.\n  induction H0; subst; eauto; inversion H; EqDep_subst; eauto.\n  - specialize (IHSemAction (H8 mret)).\n    intro TMP; destruct TMP;[subst; contradiction|contradiction].\n  - intro TMP; apply in_app_or in TMP; destruct TMP.\n    + eapply IHSemAction1; eauto.\n    + eapply IHSemAction2; eauto.\n  - intro TMP; apply in_app_or in TMP; destruct TMP.\n    + eapply IHSemAction1; eauto.\n    + eapply IHSemAction2; eauto.\n  - intro TMP; apply in_app_or in TMP; destruct TMP.\n    + eapply IHSemAction1; eauto.\n    + eapply IHSemAction2; eauto.\nQed.\n\nLemma getNumFromCalls_notIn f cs :\n  ~In f cs ->\n  (getNumFromCalls f cs = 0%Z).\nProof.\n  induction cs; intros; auto.\n  destruct (MethT_dec f a);[subst;apply False_ind; apply H;left|rewrite getNumFromCalls_neq_cons];auto.\n  apply IHcs; intro; apply H; right; assumption.\nQed.\n\nLemma WfConcats : forall (m1 m2 : Mod) (o : RegsT)(l : list FullLabel),\n    (WfConcat type m2 m1) ->\n    Substeps (getFlat m2) o l ->\n    (forall (s: string)(v : {x : Kind*Kind & SignT x}), In s (getHidden m1) -> (getNumCalls (s, v) l = 0%Z)).\nProof.\n  intros.\n  induction H0; subst.\n  - reflexivity.\n  - specialize (H).\n    inversion H; simpl in HInRules;specialize (H2 _ HInRules).\n    rewrite getNumCalls_cons; rewrite IHSubsteps;simpl.\n    assert (In (fst (s, v)) (getHidden m1)) as P1;auto.\n    rewrite (getNumFromCalls_notIn _ _ (WfConcatNotInCalls _ H2 HAction P1)); ring.\n  - specialize (H).\n    inversion H; simpl in HInMeths;specialize (H3 _ HInMeths argV).\n    rewrite getNumCalls_cons; rewrite IHSubsteps;simpl.\n    assert (In (fst (s, v)) (getHidden m1)) as P1;auto.\n    rewrite (getNumFromCalls_notIn _ _ (WfConcatNotInCalls _ H3 HAction P1)); ring.\nQed.\n\nLemma WfConcats_Substeps : forall (m1 : Mod) m2 (o : RegsT)(l : list FullLabel),\n    (WfConcat type (Base m2) m1) ->\n    Substeps m2 o l ->\n    forall f, In (fst f) (getHidden m1) -> (getNumCalls f l = 0%Z).\nProof.\n  intros.\n  induction H0; subst.\n  - reflexivity.\n  - specialize (H).\n    inversion H; simpl in HInRules;specialize (H2 _ HInRules).\n    rewrite getNumCalls_cons; rewrite IHSubsteps;simpl.\n    assert (In (fst f) (getHidden m1)) as P1;auto.\n    rewrite (getNumFromCalls_notIn _ _ (WfConcatNotInCalls _ H2 HAction P1)); ring.\n  - specialize (H).\n    inversion H; simpl in HInMeths;specialize (H3 _ HInMeths argV).\n    rewrite getNumCalls_cons; rewrite IHSubsteps;simpl.\n    assert (In (fst f) (getHidden m1)) as P1;auto.\n    rewrite (getNumFromCalls_notIn _ _ (WfConcatNotInCalls _ H3 HAction P1)); ring.\nQed.\n\n\n\nLemma WfConcats_Step : forall (m1 m2 : Mod) (o : RegsT) (l : list FullLabel),\n    (WfConcat type m2 m1) ->\n    Step m2 o l ->\n    (forall f, In (fst f) (getHidden m1) -> (getNumCalls f l = 0%Z)).\nProof.\n  intros.\n  induction H0; subst.\n  - eapply WfConcats_Substeps; eauto.\n  - unfold WfConcat in *; simpl in *.\n    specialize (IHStep H); auto.\n  - unfold WfConcat in *; simpl in *.\n    setoid_rewrite in_app_iff in H.\n    assert (sth1: (forall rule : RuleT, In rule (getAllRules m0) -> WfConcatActionT (snd rule type) m1) /\\\n               (forall meth : string * {x : Signature & MethodT x},\n                   In meth (getAllMethods m0) -> forall v : type (fst (projT1 (snd meth))), WfConcatActionT (projT2 (snd meth) type v) m1)) by (split; dest; intros; auto).\n    assert (sth2: (forall rule : RuleT, In rule (getAllRules m2) -> WfConcatActionT (snd rule type) m1) /\\\n               (forall meth : string * {x : Signature & MethodT x},\n                   In meth (getAllMethods m2) -> forall v : type (fst (projT1 (snd meth))), WfConcatActionT (projT2 (snd meth) type v) m1) ) by (split; dest; intros; auto).\n    specialize (IHStep1 sth1).\n    specialize (IHStep2 sth2).\n    rewrite getNumCalls_app; Omega.omega.\nQed.\n\nLemma WfConcats_Trace : forall (m1 m2 : Mod) (o : RegsT) ls (l : list FullLabel),\n    Trace m2 o ls ->\n    (WfConcat type m2 m1) ->\n    forall i,\n      nth_error ls i = Some l ->\n      (forall f, In (fst f) (getHidden m1) -> (getNumCalls f l = 0%Z)).\nProof.\n  induction 1; subst; auto; intros.\n  - destruct i; discriminate.\n  - destruct i; simpl in *.\n    + inv H1.\n      eapply WfConcats_Step; eauto.\n    + eapply IHTrace; eauto.\nQed.\n    \n\nLemma substitute_Step' m (HWfMod: WfMod type m):\n  forall o l,\n    StepSubstitute m o l ->\n    exists l', Permutation l l' /\\\n               Step m o l'.\nProof.\n  unfold StepSubstitute.\n  induction m; simpl in *; intros; dest.\n  - exists l; split;[apply Permutation_refl|constructor; auto].\n    eapply Substeps_flatten; eauto.\n  - assert (exists l' : list FullLabel, l [=] l' /\\ Step m o l');[apply IHm;auto|dest;exists x;split;auto].\n    + intros;\n        specialize (HWfMod);\n        inv HWfMod; auto.\n    + constructor 2; auto.\n      intros.\n      unfold getListFullLabel_diff in *;rewrite <-H2.\n      apply H1; auto.\n  - assert (HWf1: WfMod type m1) by (intros; specialize (HWfMod); inv HWfMod; auto).\n    assert (HWf2: WfMod type m2) by (intros; specialize (HWfMod); inv HWfMod; auto).\n    specialize (IHm1 HWf1).\n    specialize (IHm2 HWf2).\n    destruct (WfNoDups HWf1) as [ND_Regs1 [ND_Meths1 ND_Rules1]].\n    destruct (WfNoDups HWf2) as [ND_Regs2 [ND_Meths2 ND_Rules2]].\n    specialize (WfMod_WfBaseMod_flat HWf1) as WfBaseMod1.\n    specialize (WfMod_WfBaseMod_flat HWf2) as WfBaseMod2.\n    pose proof (HWfMod) as hwfmod2.\n    assert (WfConcat1: WfConcat type m1 m2 ) by (intros; specialize (HWfMod); inv HWfMod; auto).\n    assert (WfConcat2: WfConcat type m2 m1 ) by (intros; specialize (HWfMod); inv HWfMod; auto).\n    inv hwfmod2.\n    pose proof (@split_Substeps1 (getFlat m1) (getFlat m2) HDisjRegs HDisjRules HDisjMeths WfBaseMod1 WfBaseMod2 _ _  ND_Regs1 ND_Regs2 H);dest.\n    assert (Substeps (BaseMod (getAllRegisters m1) (getAllRules m1) (getAllMethods m1)) x (ModuleFilterLabels (getFlat m1) l) /\\\n            MatchingExecCalls_Base (ModuleFilterLabels (getFlat m1) l) (getFlat m1) /\\\n            (forall (s : string) (v : {x : Kind * Kind & SignT x}), In (s, projT1 v) (getKindAttr (getAllMethods m1)) ->\n                                                                    In s (getHidden m1) ->\n                                                                    (getListFullLabel_diff (s, v) (ModuleFilterLabels (getFlat m1) l) = 0%Z))).\n    + split; unfold getFlat at 1 in H5. assumption.\n      split.\n      * unfold getFlat in H0. simpl in H0.\n        unfold getFlat; simpl.\n        assert (MatchingExecCalls_Base l (concatFlat (getFlat m1) (getFlat m2)));[unfold concatFlat, getFlat;simpl; assumption|].\n        apply (MatchingExecCalls_Split H7).\n      * intros; specialize (WfConcats WfConcat2 H6 _ v H8) as P1.\n        rewrite map_app in H1.\n        specialize (H1 s v (in_or_app _ _ _ (or_introl H7)) (in_or_app _ _ _ (or_introl H8))); unfold getListFullLabel_diff in *.\n        assert (DisjKey (getRules (getFlat m1)) (getRules (getFlat m2))) as P2;[repeat intro; apply HDisjRules|].\n        assert (DisjKey (getMethods (getFlat m1))(getMethods (getFlat m2))) as P3;[repeat intro;apply HDisjMeths|].\n        specialize (filter_perm P2 P3 H) as P4.\n        rewrite P4, getNumExecs_app, getNumCalls_app in H1.\n        setoid_rewrite P1 in H1.\n        destruct (P3 s) as [P5|P5];[simpl in P5; apply (in_map fst) in H7; rewrite fst_getKindAttr in H7; contradiction|].\n        assert (~In (fst (s,v)) (map fst (getMethods (getFlat m2)))) as P6;auto.\n        setoid_rewrite (NotInDef_ZeroExecs_Substeps _ P6 H6) in H1; rewrite <-H1.\n        repeat rewrite Z.add_0_r.\n        reflexivity.\n    + assert (Substeps (BaseMod (getAllRegisters m2) (getAllRules m2) (getAllMethods m2)) x0 (ModuleFilterLabels (getFlat m2) l) /\\\n              MatchingExecCalls_Base (ModuleFilterLabels (getFlat m2) l) (getFlat m2) /\\\n              (forall (s : string) (v : {x : Kind * Kind & SignT x}), In (s, projT1 v) (getKindAttr (getAllMethods m2)) ->\n                                                                      In s (getHidden m2) ->\n                                                                      (getListFullLabel_diff (s, v) (ModuleFilterLabels (getFlat m2) l) = 0%Z))).\n      * split;unfold getFlat at 1 in H6. assumption.\n        split.\n        -- unfold getFlat in H0. simpl in H0.\n           unfold getFlat; simpl.\n           assert (MatchingExecCalls_Base l (concatFlat (getFlat m1) (getFlat m2)));[unfold concatFlat, getFlat;simpl; assumption|].\n           apply MatchingExecCalls_Base_comm in H8.\n           eapply (MatchingExecCalls_Split H8).\n        -- intros; specialize (WfConcats WfConcat1 H5 _ v H9) as P1.\n           rewrite map_app in H1.\n           specialize (H1 s v (in_or_app _ _ _ (or_intror H8)) (in_or_app _ _ _ (or_intror H9))); unfold getListFullLabel_diff in *.\n           assert (DisjKey (getRules (getFlat m1)) (getRules (getFlat m2))) as P2;[repeat intro; apply HDisjRules|].\n           assert (DisjKey (getMethods (getFlat m1))(getMethods (getFlat m2))) as P3;[repeat intro;apply HDisjMeths|].\n           specialize (filter_perm P2 P3 H) as P4.\n           rewrite P4, getNumExecs_app, getNumCalls_app in H1.\n           setoid_rewrite P1 in H1.\n           destruct (P3 s) as [P5|P5];[|simpl in P5; apply (in_map fst) in H8; rewrite fst_getKindAttr in H8; contradiction].\n           assert (~In (fst (s,v)) (map fst (getMethods (getFlat m1)))) as P6;auto.\n           setoid_rewrite (NotInDef_ZeroExecs_Substeps _ P6 H5) in H1; rewrite <-H1.\n           repeat rewrite Z.add_0_r.\n           reflexivity.\n      * specialize (IHm1 x (ModuleFilterLabels (getFlat m1) l) H7).\n        specialize (IHm2 x0 (ModuleFilterLabels (getFlat m2) l) H8); dest.\n        exists (x2++x1).\n        split.\n        -- specialize (filter_perm (m1:=(getFlat m1)) (m2:=(getFlat m2)) HDisjRules HDisjMeths H).\n           intro.\n           specialize (Permutation_app H15 H13).\n           intro.\n           apply (Permutation_trans H17 H18).\n        -- econstructor; eauto; specialize (split_Substeps2 (m1:=(getFlat m1)) (m2:=(getFlat m2)) HDisjRules HDisjMeths (o:=o)(l:=l) H); intros.\n           ++ repeat intro.\n              split.\n              ** intro;specialize (WfConcats WfConcat1 H5 _ (snd f) H20);intro.\n                 rewrite <-H15 in H18; destruct f; simpl in *; contradiction.\n              ** assert (MatchingExecCalls_Base l (concatFlat (getFlat m1) (getFlat m2)));[apply H0|].\n                 rewrite <-H15, <-H13.\n                 assert (DisjKey (getRules (getFlat m1)) (getRules (getFlat m2))) as P1; auto.\n                 assert (DisjKey (getMethods (getFlat m1)) (getMethods (getFlat m2))) as P2; auto.\n                 specialize (MatchingExecCalls_Mix2 P1 P2 H H20) as P3.\n                 rewrite <-H15 in H18.\n                 specialize (P3 _ H18 H19); dest; assumption.\n           ++ repeat intro.\n              split.\n              ** intro; specialize (WfConcats WfConcat2 H6 _ (snd f) H20); intro.\n                 rewrite <-H13 in H18; destruct f; simpl in *; contradiction.\n              ** assert (MatchingExecCalls_Base l (concatFlat (getFlat m1) (getFlat m2)));[apply H0|].\n                 rewrite <- H15, <-H13.\n                 assert (DisjKey (getRules (getFlat m1)) (getRules (getFlat m2))) as P1; auto.\n                 assert (DisjKey (getMethods (getFlat m1)) (getMethods (getFlat m2))) as P2; auto.\n                 specialize (MatchingExecCalls_Mix1 P1 P2 H H20) as P3.\n                 rewrite <-H13 in H18.\n                 specialize (P3 _ H18 H19); dest; assumption.\n           ++  rewrite <- H15 in H18; rewrite <- H13 in H19.\n               specialize (H17 _ _ H18 H19); assumption.\nQed.\n\nLemma WeakInclusionsRefl l : WeakInclusions l l.\nProof.\n  induction l; constructor.\n  - assumption.\n  - apply WeakInclusionRefl.\nQed.\n\nCorollary WeakEqualitiesRefl l : WeakEqualities l l.\nProof.\n  unfold WeakEqualities; split; apply WeakInclusionsRefl.\nQed.\n\nLemma WeakInclusionsTrans : forall (l1 l2 l3 : list (list FullLabel)), WeakInclusions l1 l2 -> WeakInclusions l2 l3 -> WeakInclusions l1 l3.\nProof.\n  induction l1, l2, l3; intros; auto; try inversion H; try inversion H0; subst.\n  constructor.\n  - apply (IHl1 _ _ H4 H10).\n  - apply (WeakInclusionTrans H6 H12).\nQed.\n\nCorollary WeakEqualitesTrans ls1 ls2 ls3 : WeakEqualities ls1 ls2 -> WeakEqualities ls2 ls3 -> WeakEqualities ls1 ls3.\nProof.\n  unfold WeakEqualities; intros; dest; split; eapply WeakInclusionsTrans; eauto.\nQed.\n\nLemma WeakEqualitiesSymm ls1 ls2 : WeakEqualities ls1 ls2 -> WeakEqualities ls2 ls1.\nProof.\n  firstorder.\nQed.\n\nLemma WeakInclusionsLen_consistent ls1 ls2 : WeakInclusions ls1 ls2 -> length ls1 = length ls2.\nProof.\n  induction 1; simpl; auto.\nQed.\n\nLemma WeakInclusions_WeakInclusion : forall (ls1 ls2 : list (list FullLabel)),  WeakInclusions ls1 ls2 -> nthProp2 WeakInclusion ls1 ls2.\nProof.\n  induction ls1, ls2; unfold nthProp2; intros; try destruct (nth_error nil i); auto; try inversion H; subst.\n  -  apply WeakInclusionRefl.\n  - destruct i; simpl;[|apply IHls1];assumption.\nQed.\n\nLemma WeakInclusion_WeakInclusions : forall (ls1 ls2 : list (list FullLabel)),\n    length ls1 = length ls2 -> nthProp2 WeakInclusion ls1 ls2 -> WeakInclusions ls1 ls2.\nProof.\n  induction ls1, ls2; intros; try constructor; try inversion H; try  apply nthProp2_cons in H0; try destruct H0;[apply (IHls1 _ H2 H0)|assumption].\nQed.\n\nDefinition TraceList (m : Mod) (ls : list (list FullLabel)) :=\n  (exists (o : RegsT), Trace m o ls).\n\nDefinition TraceInclusion' (m m' : Mod) :=\n  forall (o : RegsT)(ls : list (list FullLabel)), Trace m o ls -> exists (ls': list (list FullLabel)), TraceList m' ls' /\\ WeakInclusions ls ls'.\n\nLemma TraceInclusion'_TraceInclusion : forall (m m' : Mod), TraceInclusion' m m' -> TraceInclusion m m'.\nProof.\n  unfold TraceInclusion', TraceInclusion; intros; generalize (H o1 ls1 H0); unfold TraceList; intros; dest;exists x0, x.\n  repeat split.\n  - assumption.\n  - apply (WeakInclusionsLen_consistent H2).\n  - apply WeakInclusions_WeakInclusion;assumption.\nQed.\n\nLemma TraceInclusion_TraceInclusion' : forall (m m' : Mod), TraceInclusion m m' -> TraceInclusion' m m'.\nProof.\n  unfold TraceInclusion'; intros; generalize (H _ _ H0); intros; dest; unfold TraceList; exists x0.\n  split.\n  - exists x; assumption.\n  - apply (WeakInclusion_WeakInclusions H2 H3).\nQed.\n\nLemma PermutationInCall : forall (l l' : list FullLabel), Permutation l l' -> (forall (f : MethT), InCall f l <-> InCall f l').\nProof.\n  induction 1.\n  - firstorder.\n  - intro; split; intros; try assumption.\n    + apply (InCall_app_iff f (x::nil) l'); apply (InCall_app_iff f (x::nil) l) in H0.\n      destruct H0;[left|right;apply IHPermutation];assumption.\n    + apply (InCall_app_iff f (x::nil) l); apply (InCall_app_iff f (x::nil) l') in H0.\n      destruct H0;[left|right;apply IHPermutation];assumption.\n  - split; intros.\n    + apply (InCall_app_iff f (x::y::nil) l); apply (InCall_app_iff f (y::x::nil) l) in H.\n      destruct H;[left;simpl|right];firstorder.\n    +  apply (InCall_app_iff f (y::x::nil) l); apply (InCall_app_iff f (x::y::nil) l) in H;firstorder.\n  - intros; split;intros.\n    + apply IHPermutation2; apply IHPermutation1; assumption.\n    + apply IHPermutation1; apply IHPermutation2; assumption.\nQed.\n\nCorollary neg_PermutationInCall : forall (l l' : list FullLabel), Permutation l l' -> (forall (f : MethT), ~InCall f l <-> ~InCall f l').\nProof.\n  intros; split; repeat intro; apply H0;specialize (Permutation_sym H) as TMP;  eapply PermutationInCall; eauto.\nQed.\n\nLemma PermutationInExec : forall (l l' : list FullLabel), Permutation l l' -> (forall (f : MethT), InExec f l <-> InExec f l').\nProof.\n  induction 1; firstorder.\nQed.\n\nCorollary neg_PermutationInExec : forall (l l' : list FullLabel), Permutation l l' -> (forall (f : MethT), ~InExec f l <-> ~InExec f l').\nProof.\n  intros; split; repeat intro; apply H0; specialize (Permutation_sym H) as TMP; eapply PermutationInExec; eauto.\nQed.\n\nLemma PermutationWI : forall (l l' : list FullLabel), Permutation l l' -> WeakInclusion l l'.\nProof.\n  unfold WeakInclusion; repeat split; intros.\n  - unfold getListFullLabel_diff; rewrite H; reflexivity.\n  - setoid_rewrite H; assumption.\nQed.\n\nCorollary PermutationWE : forall (l l' : list FullLabel), Permutation l l' -> WeakEquality l l'.\nProof.\n  intros;unfold WeakEquality; split;[apply PermutationWI|apply PermutationWI;apply Permutation_sym];assumption.\nQed.\n\nLemma substitute_Step m o l (HWfMod: WfMod type m):\n  Step (flatten m) o l ->\n  exists l',\n    Permutation l l' /\\\n    Step m o l'.\nProof.\n  rewrite (@StepSubstitute_flatten) in *; auto.\n  apply substitute_Step'; auto.\nQed.\n\nInductive PermutationEquivLists {A : Type} : (list (list A)) -> (list (list A)) -> Prop :=\n|PermutationEquiv_nil : PermutationEquivLists nil nil\n|PermutationEquiv_cons ls ls' l l' : PermutationEquivLists ls ls' -> Permutation l l' -> PermutationEquivLists (l::ls) (l'::ls').\n\nLemma PermutationEquivLists_WeakInclusions : forall (ls ls' : list (list FullLabel)),\n    PermutationEquivLists ls ls' -> WeakInclusions ls ls'.\nProof.\n  induction 1.\n  - constructor.\n  - constructor; auto.\n    apply PermutationWI; assumption.\nQed.\n\nLemma UpdRegs_perm u u' o o' : UpdRegs u o o' -> Permutation u u' -> UpdRegs u' o o'.\nProof.\n  unfold UpdRegs; intros; dest.\n  split; auto.\n  intros.\n  specialize (H1 s v H2).\n  destruct H1;[left|right].\n  - dest; exists x;split;auto.\n    eapply Permutation_in; eauto.\n  - destruct H1; split;[intro; apply H1|assumption].\n    dest; exists x; split;[|assumption].\n    apply Permutation_sym in H0.\n    eapply Permutation_in; eauto.\nQed.\n    \nLemma SameTrace m1 m2:\n  (forall o1 l, Trace m1 o1 l -> exists o2, Trace m2 o2 l) ->\n  TraceInclusion m1 m2.\nProof.\n  unfold TraceInclusion; intros.\n  pose proof (H _ _ H0); dest.\n  exists x, ls1; auto.\n  repeat split; auto.\n  - unfold nthProp2; intros.\n    destruct (nth_error ls1 i); auto.\n    repeat split; tauto.\nQed.\n\nLemma WfMod_createHide l: forall ty m, WfMod ty (createHide m l) <-> (SubList l (map fst (getMethods m)) /\\ WfMod ty (Base m)).\nProof.\n  split.\n  - induction l; simpl; intros; split; unfold SubList; simpl; intros; try tauto.\n    + inv H.\n      destruct H0; subst; rewrite createHide_Meths in *; auto.\n      specialize (IHl HWf); dest; apply H0; assumption.\n    + inv H.\n      destruct (IHl HWf); assumption.\n  - unfold SubList; induction l; simpl; intros; try tauto; dest; constructor.\n    + rewrite createHide_Meths; apply (H a); left; reflexivity.\n    + apply IHl; intros; split;auto.\nQed.\n\nLemma WfMod_createHideMod l: forall ty m, WfMod ty (createHideMod m l) <-> (SubList l (map fst (getAllMethods m)) /\\ WfMod ty m).\nProof.\n  split.\n  - induction l; simpl; intros; split; unfold SubList; simpl; intros; try tauto.\n    + inv H.\n      destruct H0; subst; rewrite createHideMod_Meths in *; auto.\n      specialize (IHl HWf); dest; apply H0; assumption.\n    + inv H.\n      destruct (IHl HWf); assumption.\n  - unfold SubList; induction l; simpl; intros; try tauto; dest; constructor.\n    + rewrite createHideMod_Meths; apply (H a); left; reflexivity.\n    + apply IHl; intros; split;auto.\nQed.\n\nLemma WfActionT_flatten m k ty:\n  forall (a : ActionT ty k),\n    WfActionT (getRegisters m) a <-> WfActionT (getRegisters (getFlat (Base m))) a.\nProof.\n  intro; split; induction 1; econstructor; eauto.\nQed.\n\nTheorem flatten_WfMod ty m: WfMod ty m -> WfMod ty (flatten m).\nProof.\n  unfold flatten.\n  induction 1; simpl; auto; intros.\n  - constructor; auto.\n  - constructor; auto.\n    rewrite createHide_Meths.\n    auto.\n  - unfold getFlat in *; simpl.\n    rewrite WfMod_createHide in *; dest; simpl in *.\n    split.\n    + rewrite map_app.\n      unfold SubList in *; intros.\n      rewrite in_app_iff in *.\n      specialize (H3 x).\n      specialize (H1 x).\n      tauto.\n    + constructor;inversion H4; inversion H2; inversion HWfBaseModule; inversion HWfBaseModule0; subst.\n      * split; intros.\n        -- destruct (in_app_or _ _ _ H6).\n           ++ specialize (H5 _ H7).\n              induction H5; econstructor; eauto; simpl; rewrite map_app; apply in_or_app; left; assumption.\n           ++ specialize (H9 _ H7).\n              induction H9; econstructor; eauto; simpl; rewrite map_app; apply in_or_app; right; assumption.\n        -- repeat split; simpl; intros; dest; try (eapply NoDup_DisjKey; eauto).\n           ++ destruct (in_app_or _ _ _ H6).\n              ** specialize (H8 _ H16 v).\n                 induction H8; econstructor; eauto; simpl; rewrite map_app; apply in_or_app; left; assumption.\n              ** specialize (H7 _ H16 v).\n                 induction H7; econstructor; eauto; simpl; rewrite map_app; apply in_or_app; right; assumption.\nQed.\n\nTheorem flatten_WfMod_new ty m : WfMod_new ty m -> WfMod_new ty (flatten m).\nProof.\n  repeat rewrite WfMod_new_WfMod_iff.\n  apply flatten_WfMod.\nQed.\n\nDefinition flatten_ModWf ty m: ModWf ty :=\n  (Build_ModWf (flatten_WfMod (wfMod m))).\n\nDefinition flatten_ModWf_new ty m: ModWf_new ty :=\n  (Build_ModWf_new _ _ (flatten_WfMod_new _ _ (wfMod_new m))).\n\nSection TraceSubstitute.\n  Variable m: ModWf type.\n\n  Lemma Trace_flatten_same1: forall o l,  Trace m o l -> Trace (flatten m) o l.\n  Proof.\n    induction 1; subst.\n    - constructor 1; auto.\n      unfold flatten.\n      rewrite createHide_Regs.\n      auto.\n    - apply (@Step_substitute type) in HStep; auto.\n      + econstructor 2; eauto.\n      + destruct m; auto.\n  Qed.\n\n  Lemma Trace_flatten_same2: forall o l, Trace (flatten m) o l -> (exists l', (PermutationEquivLists l l') /\\ Trace m o l').\n  Proof.\n    induction 1; subst.\n    - rewrite getAllRegisters_flatten in *.\n      exists nil;split;constructor 1; auto.\n    - apply substitute_Step in HStep;auto; dest.\n      exists (x0::x);split.\n      + constructor; auto.\n      + econstructor 2; eauto.\n        apply (Permutation_map fst) in H2.\n        eapply UpdRegs_perm; eauto.\n      + destruct m; auto.\n  Qed.\n\n  Theorem TraceInclusion_flatten_r: TraceInclusion m (flatten_ModWf m).\n  Proof.\n    unfold TraceInclusion; intros.\n    exists o1, ls1.\n    repeat split; auto; intros; unfold nthProp2; intros; try destruct (nth_error ls1 i); auto; repeat split; intros; try tauto.\n    apply Trace_flatten_same1; auto.\n  Qed.\n\n  Theorem TraceInclusion_flatten_l: TraceInclusion (flatten_ModWf m) m.\n  Proof.\n    apply TraceInclusion'_TraceInclusion.\n    unfold TraceInclusion'; intros.\n    apply Trace_flatten_same2 in H.\n    dest.\n    exists x.\n    split.\n    - unfold TraceList; exists o; auto.\n    - apply PermutationEquivLists_WeakInclusions.\n      assumption.\n  Qed.\n  \nEnd TraceSubstitute.\n\nSection TraceSubstitute_new.\n  Variable m: ModWf_new type.\n\n  Lemma Trace_flatten_same1_new: forall o l,  Trace m o l -> Trace (flatten m) o l.\n  Proof.\n    induction 1; subst.\n    - constructor 1; auto.\n      unfold flatten.\n      rewrite createHide_Regs.\n      auto.\n    - apply (@Step_substitute type) in HStep; auto.\n      + econstructor 2; eauto.\n      + destruct m; apply WfMod_new_WfMod; auto.\n  Qed.\n\n  Lemma Trace_flatten_same2_new : forall o l, Trace (flatten m) o l -> (exists l', (PermutationEquivLists l l') /\\ Trace m o l').\n  Proof.\n    induction 1; subst.\n    - rewrite getAllRegisters_flatten in *.\n      exists nil;split;constructor 1; auto.\n    - apply substitute_Step in HStep;auto; dest.\n      exists (x0::x);split.\n      + constructor; auto.\n      + econstructor 2; eauto.\n        apply (Permutation_map fst) in H2.\n        eapply UpdRegs_perm; eauto.\n      + destruct m; apply WfMod_new_WfMod; auto.\n  Qed.\n\n  Theorem TraceInclusion_flatten_r_new : TraceInclusion m (flatten_ModWf_new m).\n  Proof.\n    unfold TraceInclusion; intros.\n    exists o1, ls1.\n    repeat split; auto; intros; unfold nthProp2; intros; try destruct (nth_error ls1 i); auto; repeat split; intros; auto.\n    apply Trace_flatten_same1_new; auto.\n  Qed.\n\n  Theorem TraceInclusion_flatten_l_new : TraceInclusion (flatten_ModWf_new m) m.\n  Proof.\n    apply TraceInclusion'_TraceInclusion.\n    unfold TraceInclusion'; intros.\n    apply Trace_flatten_same2_new in H.\n    dest.\n    exists x.\n    split.\n    - unfold TraceList; exists o; auto.\n    - apply PermutationEquivLists_WeakInclusions.\n      assumption.\n  Qed.\n  \nEnd TraceSubstitute_new.\n\nSection test.\n  Variable ty: Kind -> Type.\n  Definition Slt2 n (e1 e2: Expr ty (SyntaxKind (Bit (n + 1)))) :=\n    ITE (Eq (UniBit (TruncMsb n 1) e1) (Const ty WO~0))\n        (ITE (Eq (UniBit (TruncMsb n 1) e2) (Const ty WO~0)) (BinBitBool (LessThan _) e1 e2) (Const ty false))\n        (ITE (Eq (UniBit (TruncMsb n 1) e2) (Const ty WO~1)) (BinBitBool (LessThan _) e1 e2) (Const ty true)).\nEnd test.\n\nLemma Slt_same n e1 e2: evalExpr (Slt2 n e1 e2) = evalExpr (Slt n e1 e2).\nProof.\n  unfold Slt2, Slt.\n  simpl.\n  destruct (weq (@truncMsb 1 (n+1) (evalExpr e1)) (ZToWord 1 0)); simpl; auto.\n  - rewrite e.\n    destruct (weq (@truncMsb 1 (n+1) (evalExpr e2)) (ZToWord 1 0)); simpl; auto.\n    + rewrite e0.\n      destruct (wltu (evalExpr e1) (evalExpr e2)); simpl; auto.\n    + case_eq (wltu (evalExpr e1) (evalExpr e2)); intros; simpl; auto.\n      * destruct (weq (ZToWord 1 0) (@truncMsb 1 (n+1) (evalExpr e2))); simpl; auto.\n      * destruct (weq (ZToWord 1 0) (@truncMsb 1 (n+1) (evalExpr e2))); simpl; auto.\n        apply word0_neq in n0.\n        rewrite n0 in n1.\n        assert ((wordVal 1 (truncMsb (evalExpr e1))) < (wordVal 1 (truncMsb (evalExpr e2))))%Z.\n        rewrite e. rewrite n0.\n        simpl. rewrite Zmod_0_l.\n        rewrite Zmod_1_l. lia.\n        rewrite Z.pow_pos_fold. lia.\n        specialize truncMsbLtTrue. intros.\n        specialize (H1 (n+1) 1 (evalExpr e1) (evalExpr e2) H0).\n        rewrite H1 in H. eapply (eq_sym H).\n  - destruct (weq (@truncMsb 1 (n+1) (evalExpr e2)) (ZToWord 1 0)); simpl; auto.\n    + rewrite e.\n      case_eq (wltu (evalExpr e1) (evalExpr e2)); intros; simpl; auto.\n      * destruct (weq (@truncMsb 1 (n+1) (evalExpr e1)) (ZToWord 1 0)); simpl; auto.\n        apply word0_neq in n1.\n        \n        assert (sth:\n                  (wordVal 1 (truncMsb (evalExpr e2)) < wordVal 1 (truncMsb (evalExpr e1)))%Z).\n        {\n          rewrite e, n1.\n          reflexivity.\n        }\n        pose proof (@truncMsbLtFalse (n+1) 1 (evalExpr e2) (evalExpr e1) sth) as sth2.\n        congruence.\n      * destruct (weq (@truncMsb 1 (n+1) (evalExpr e1)) (ZToWord 1 0)); simpl; auto.\n        tauto.\n    + apply word0_neq in n0.\n      apply word0_neq in n1.\n      rewrite ?n0, ?n1.\n      simpl.\n      case_eq (wltu (evalExpr e1) (evalExpr e2)); intros; simpl; auto.\nQed.\n\nLemma mergeSeparatedBaseFile_noHides (rfl : list RegFileBase) :\n  getHidden (mergeSeparatedBaseFile rfl) = nil.\nProof.\n  induction rfl; auto.\nQed.\n\nLemma mergeSeparatedBaseMod_noHides (bl : list BaseModule) :\n  getHidden (mergeSeparatedBaseMod bl) = nil.\nProof.\n  induction bl; auto.\nQed.\n\nLemma getHidden_createHideMod (m : Mod) (hides : list string) :\n  getHidden (createHideMod m hides) = hides++(getHidden m).\nProof.\n  induction hides; auto.\n  - simpl; rewrite IHhides; reflexivity.\nQed.\n\nLemma getAllRegisters_createHideMod (m : Mod) (hides : list string) :\n  getAllRegisters (createHideMod m hides) = getAllRegisters m.\nProof.\n  induction hides; auto.\nQed.\n\nLemma getAllRegisters_mergeBaseFile (rfl : list RegFileBase) :\n  getAllRegisters (mergeSeparatedBaseFile rfl) = (concat (map getRegFileRegisters rfl)).\nProof.\n  induction rfl;auto.\n  simpl; rewrite IHrfl; reflexivity.\nQed.\n\nLemma getAllRegisters_mergeBaseMod (bl : list BaseModule) :\n  getAllRegisters (mergeSeparatedBaseMod bl) = (concat (map getRegisters bl)).\nProof.\n  induction bl; auto.\n  simpl; rewrite IHbl; reflexivity.\nQed.\n\nLemma getAllMethods_createHideMod (m : Mod) (hides : list string) :\n  getAllMethods (createHideMod m hides) = getAllMethods m.\nProof.\n  induction hides; auto.\nQed.\n\nLemma getAllMethods_mergeBaseFile (rfl : list RegFileBase) :\n  getAllMethods (mergeSeparatedBaseFile rfl) = (concat (map getRegFileMethods rfl)).\nProof.\n  induction rfl;auto.\n  simpl; rewrite IHrfl; reflexivity.\nQed.\n\nLemma getAllMethods_mergeBaseMod (bl : list BaseModule) :\n  getAllMethods (mergeSeparatedBaseMod bl) = (concat (map getMethods bl)).\nProof.\n  induction bl; auto.\n  simpl; rewrite IHbl; reflexivity.\nQed.\n\nLemma getAllRules_createHideMod (m : Mod) (hides : list string) :\n  getAllRules (createHideMod m hides) = getAllRules m.\nProof.\n  induction hides; auto.\nQed.\n\nLemma getAllRules_mergeBaseFile (rfl : list RegFileBase) :\n  getAllRules (mergeSeparatedBaseFile rfl) = nil.\nProof.\n  induction rfl;auto.\nQed.\n\nLemma getAllRules_mergeBaseMod (bl : list BaseModule) :\n  getAllRules (mergeSeparatedBaseMod bl) = (concat (map getRules bl)).\nProof.\n  induction bl; auto.\n  simpl; rewrite IHbl; reflexivity.\nQed.\n\n\nLemma separateBaseMod_flatten (m : Mod) :\n  getAllRegisters m [=] getAllRegisters (mergeSeparatedMod (separateMod m)).\nProof.\n  unfold mergeSeparatedMod.\n  rewrite getAllRegisters_createHideMod.\n  unfold separateMod; simpl.\n  rewrite getAllRegisters_mergeBaseFile, getAllRegisters_mergeBaseMod.\n  induction m.\n  - destruct m; simpl; repeat rewrite app_nil_r; reflexivity.\n  - simpl; assumption.\n  - simpl in *.\n    destruct (separateBaseMod m1), (separateBaseMod m2).\n    simpl in *.\n    repeat rewrite map_app, concat_app; rewrite IHm1, IHm2.\n    repeat rewrite <- app_assoc; apply Permutation_app_head.\n    repeat rewrite app_assoc; apply Permutation_app_tail.\n    apply Permutation_app_comm.\nQed.\n\nLemma separateBaseModule_flatten_Methods (m : Mod) :\n  getAllMethods m [=] getAllMethods (mergeSeparatedMod (separateMod m)).\nProof.\n  unfold mergeSeparatedMod.\n  rewrite getAllMethods_createHideMod.\n  unfold separateMod; simpl.\n  rewrite getAllMethods_mergeBaseFile, getAllMethods_mergeBaseMod.\n  induction m.\n  - destruct m; simpl; repeat rewrite app_nil_r; reflexivity.\n  - simpl; assumption.\n  - simpl in *.\n    destruct (separateBaseMod m1), (separateBaseMod m2).\n    simpl in *.\n    repeat rewrite map_app, concat_app; rewrite IHm1, IHm2.\n    repeat rewrite <- app_assoc; apply Permutation_app_head.\n    repeat rewrite app_assoc; apply Permutation_app_tail.\n    apply Permutation_app_comm.\nQed.\n\nLemma separateBaseModule_flatten_Rules (m : Mod) :\n  getAllRules m [=] getAllRules (mergeSeparatedMod (separateMod m)).\nProof.\n  unfold mergeSeparatedMod.\n  rewrite getAllRules_createHideMod.\n  unfold separateMod; simpl.\n  rewrite getAllRules_mergeBaseFile, getAllRules_mergeBaseMod; simpl.\n  induction m.\n  - destruct m; simpl; repeat rewrite app_nil_r; reflexivity.\n  - simpl; assumption.\n  - simpl in *.\n    destruct (separateBaseMod m1), (separateBaseMod m2).\n    simpl in *.\n    repeat rewrite map_app, concat_app; rewrite IHm1, IHm2.\n    reflexivity.\nQed.\n\nLemma separateBaseModule_flatten_Hides (m : Mod) :\n  getHidden m [=] getHidden (mergeSeparatedMod (separateMod m)).\nProof.\n  unfold mergeSeparatedMod.\n  rewrite getHidden_createHideMod;simpl.\n  rewrite mergeSeparatedBaseFile_noHides.\n  rewrite mergeSeparatedBaseMod_noHides.\n  repeat rewrite app_nil_r.\n  reflexivity.\nQed.\n\nLemma dec_def_notHidden f m:\n  (In f (map fst (getAllMethods m)) /\\ ~ In f (getHidden m)) \\/\n  (~ In f (map fst (getAllMethods m))) \\/ (In f (map fst (getAllMethods m)) /\\ In f (getHidden m)).\nProof.\n  destruct (in_dec string_dec f (map fst (getAllMethods m))), (in_dec string_dec f (getHidden m)); auto.\nQed.\n\nLemma NotInDef_ZeroExecs_Trace:\n  forall (m : Mod) (o : RegsT) lss (ls : list FullLabel) (f : string * {x : Kind * Kind & SignT x}),\n    Trace m o lss ->\n    ~ In (fst f) (map fst (getAllMethods m)) ->\n    forall i,\n      nth_error lss i = Some ls ->\n      getNumExecs f ls = 0%Z.\nProof.\n  induction 1; subst; simpl; auto; intros; simpl in *.\n  - destruct i; simpl in *; discriminate.\n  - specialize (IHTrace H0).\n    destruct i; simpl in *.\n    + inv H1.\n      eapply NotInDef_ZeroExecs_Step; eauto.\n    + eauto.\nQed.\n\nLemma NotInDef_ZeroExecs_Trace' :\n  forall (m : Mod) (o : RegsT) lss (ls : list FullLabel) (f : string * {x : Kind * Kind & SignT x}),\n    Trace m o lss ->\n    ~ In (fst f, projT1 (snd f)) (getKindAttr (getAllMethods m)) ->\n    forall i,\n      nth_error lss i = Some ls ->\n      getNumExecs f ls = 0%Z.\nProof.\n  induction 1; subst; simpl; auto; intros; simpl in *.\n  - destruct i; simpl in *; discriminate.\n  - specialize (IHTrace H0).\n    destruct i; simpl in *.\n    + inv H1.\n      eapply NotInDef_ZeroExecs_Step'; eauto.\n    + eauto.\nQed.\n\nSection ModularSubstitution.\n  Variable a b a' b': Mod.\n  Variable SameList_a: forall (x : MethT),\n      (In (fst x, projT1 (snd x)) (getKindAttr (getAllMethods a)) /\\\n       ~ In (fst x) (getHidden a)) <->\n      (In (fst x, projT1 (snd x)) (getKindAttr (getAllMethods a')) /\\\n       ~ In (fst x) (getHidden a')).\n  Variable SameList_b: forall (x : MethT),\n      (In (fst x, projT1 (snd x)) (getKindAttr (getAllMethods b)) /\\\n       ~ In (fst x) (getHidden b)) <->\n      (In (fst x, projT1 (snd x)) (getKindAttr (getAllMethods b')) /\\\n       ~ In (fst x) (getHidden b')).\n\n  Variable wfAConcatB: WfMod type (ConcatMod a b).\n  Variable wfA'ConcatB': WfMod type (ConcatMod a' b').\n\n  Theorem ModularSubstitution: TraceInclusion a a' ->\n                             TraceInclusion b b' ->\n                             TraceInclusion (ConcatMod a b) (ConcatMod a' b').\n  Proof.\n    assert (WfConcat1: WfConcat type a b) by (intros; specialize (wfAConcatB); inv wfAConcatB; auto).\n    assert (WfConcat2: WfConcat type b a) by (intros; specialize (wfAConcatB); inv wfAConcatB; auto).\n    assert (WfConcat0: WfConcat type a' b') by (intros; specialize (wfA'ConcatB'); inv wfA'ConcatB'; auto).\n    assert (WfConcat3: WfConcat type b' a') by (intros; specialize (wfA'ConcatB'); inv wfA'ConcatB'; auto).\n    pose proof (wfAConcatB) as wfAConcatB_dup.\n    pose proof (wfA'ConcatB') as wfA'ConcatB'_dup.\n    inv wfAConcatB_dup.\n    inv wfA'ConcatB'_dup.\n    unfold TraceInclusion, WeakInclusion,getListFullLabel_diff in *; intros.\n    pose proof (SplitTrace HDisjRegs HDisjRules HDisjMeths H1); dest.\n    specialize (@H _ _ H2).\n    specialize (@H0 _ _ H3).\n    dest.\n    exists (x1 ++ x).\n    exists (map (fun x => fst x ++ snd x) (List.combine x2 x0)).\n    pose proof H9 as sth1.\n    pose proof H7 as sth2.\n    rewrite map_length in H9, H7.\n    rewrite H9 in H7.\n    rewrite mapProp_nthProp in H5.\n    repeat split.\n    - apply JoinTrace; auto; unfold nthProp, nthProp2 in *; intros; auto.\n      specialize (H10 i); specialize (H8 i); specialize (H5 i).\n      rewrite nth_error_map in H10, H8;\n        case_eq (nth_error x2 i);\n        case_eq (nth_error x0 i);\n        case_eq (nth_error ls1 i);\n        intros;\n        try congruence; auto;\n          [rewrite H11, H12, H13 in *; dest|\n           solve [exfalso; apply (nth_error_len _ _ _ H11 H13 H9)]].\n      Opaque MatchingExecCalls_Concat.\n      repeat split; intros.\n      Transparent MatchingExecCalls_Concat.\n      + unfold MatchingExecCalls_Concat in *; intros.\n        repeat match goal with\n               | H : forall (x: MethT), _ |- _ => specialize (H f)\n               end; try specialize (HDisjMeths (fst f));\n          try specialize (HDisjMeths0 (fst f));\n          try specialize (SameList_a (fst f));\n          try specialize (SameList_b (fst f));\n          try specialize (Subset_a (fst f));\n          try specialize (Subset_b (fst f)).\n        specialize (getNumExecs_nonneg f l1) as P1;\n          rewrite Z.lt_eq_cases in P1; destruct P1;\n            [specialize (Trace_meth_InExec' H _ _ H13 H21) as P2; clear - HDisjMeths0 P2 H20; apply (in_map fst) in H20; rewrite fst_getKindAttr in H20; tauto|].\n        specialize (getNumCalls_nonneg f l1) as P1; rewrite Z.lt_eq_cases in P1; destruct P1;[|symmetry in H22; contradiction].\n        rewrite <- H21 in H10; simpl in H10.\n        specialize (getNumExecs_nonneg f (filterExecs id a l)) as P1.\n        specialize (getNumCalls_nonneg f (filterExecs id a l)) as P2.\n        assert (getNumCalls f (filterExecs id a l) <> 0%Z);[clear - P1 P2 H22 H10;Omega.omega|].\n        specialize (H5 H23).\n        assert (helper: (getNumExecs f (filterExecs id a l) < getNumCalls f (filterExecs id a l))%Z) by Omega.omega.\n        pose proof (Trace_meth_InCall_InDef_InExec H2 f i) as sth10.\n        pose proof (map_nth_error (filterExecs id a) _ _ H11) as sth11.\n        specialize (sth10 _ sth11).\n        pose proof (in_dec (prod_dec string_dec Signature_dec) (fst f, projT1 (snd f)) (getKindAttr (getAllMethods a))) as [th1 | th2].\n        * clear - H11 H2 helper th1 sth10 sth11.\n          specialize (sth10 th1).\n          pose proof (Trace_meth_InCall_InDef_InExec H2 f i) as sth0.\n          Omega.omega.\n        * pose proof (NotInDef_ZeroExecs_Trace' f H2 th2 _ sth11) as sth12.\n          assert (sth13: (getNumCalls f (filterExecs id a l) > 0)%Z) by (Omega.omega).\n          rewrite sth12 in *.\n          assert (sth14: getNumCalls f (filterExecs id a l) = getNumCalls f l1) by Omega.omega.\n          destruct (in_dec (prod_dec string_dec Signature_dec) (fst f, projT1 (snd f)) (getKindAttr (getAllMethods b))) as [ez|hard].\n          -- specialize (H5 ez); dest.\n             rewrite sth14 in *.\n             split; [tauto |Omega.omega].\n          -- destruct (in_dec string_dec (fst f) (getHidden b')) as [lhs | rhs]; [ |tauto ].\n             apply (in_map fst) in H20; rewrite fst_getKindAttr in H20.\n             pose proof (WfConcats_Trace H WfConcat0 _ H13 f lhs).\n             Omega.omega.\n      + unfold MatchingExecCalls_Concat in *; intros.\n        repeat match goal with\n               | H : forall (x: MethT), _ |- _ => specialize (H f)\n               end; try specialize (HDisjMeths (fst f));\n          try specialize (HDisjMeths0 (fst f));\n          try specialize (SameList_a (fst f));\n          try specialize (SameList_b (fst f));\n          try specialize (Subset_a (fst f));\n          try specialize (Subset_b (fst f)).\n        specialize (getNumExecs_nonneg f l0) as P1;\n          rewrite Z.lt_eq_cases in P1; destruct P1;\n            [specialize (Trace_meth_InExec' H0 _ _ H12 H21) as P2; clear - HDisjMeths0 P2 H20; apply (in_map fst) in H20; rewrite fst_getKindAttr in H20; tauto|].\n        specialize (getNumCalls_nonneg f l0) as P1; rewrite Z.lt_eq_cases in P1; destruct P1;[|symmetry in H22; contradiction].\n        rewrite <- H21 in H8; simpl in H8.\n        specialize (getNumExecs_nonneg f (filterExecs id b l)) as P1.\n        specialize (getNumCalls_nonneg f (filterExecs id b l)) as P2.\n        assert (getNumCalls f (filterExecs id b l) <> 0%Z);[clear - P1 P2 H22 H8;Omega.omega|].\n        specialize (H14 H23).\n        assert (helper: (getNumExecs f (filterExecs id b l) < getNumCalls f (filterExecs id b l))%Z) by Omega.omega.\n        pose proof (Trace_meth_InCall_InDef_InExec H3 f i) as sth10.\n        pose proof (map_nth_error (filterExecs id b) _ _ H11) as sth11.\n        specialize (sth10 _ sth11).\n        pose proof (in_dec (prod_dec string_dec Signature_dec) (fst f, projT1 (snd f)) (getKindAttr (getAllMethods b))) as [th1 | th2].\n        * clear - H11 H3 helper th1 sth10 sth11.\n          specialize (sth10 th1).\n          pose proof (Trace_meth_InCall_InDef_InExec H3 f i) as sth0.\n          Omega.omega.\n        * pose proof (NotInDef_ZeroExecs_Trace' f H3 th2 _ sth11) as sth12.\n          assert (sth13: (getNumCalls f (filterExecs id b l) > 0)%Z) by (Omega.omega).\n          rewrite sth12 in *.\n          assert (sth14: getNumCalls f (filterExecs id b l) = getNumCalls f l0) by Omega.omega.\n          destruct (in_dec (prod_dec string_dec Signature_dec) (fst f, projT1 (snd f)) (getKindAttr (getAllMethods a))) as [ez|hard].\n          -- specialize (H14 ez); dest.\n             rewrite sth14 in *.\n             split; [tauto|Omega.omega].\n          -- destruct (in_dec string_dec (fst f) (getHidden a')) as [lhs | rhs]; [ | tauto].\n             pose proof (WfConcats_Trace H0 WfConcat3 _ H12 f lhs).\n             Omega.omega.\n      + destruct x3, x4, p, p0, r1, r2; simpl; auto.\n        pose proof (in_map (fun x => fst (snd x)) _ _ H19) as sth3.\n        pose proof (in_map (fun x => fst (snd x)) _ _ H20) as sth4.\n        simpl in *.\n        assert (sth5: exists rle, In (Rle rle)\n                                     (map (fun x => fst (snd x))\n                                          (filterExecs id a l))) by\n            (clear - H18 sth3; eauto).\n        assert (sth6: exists rle, In (Rle rle)\n                                     (map (fun x => fst (snd x))\n                                          (filterExecs id b l))) by\n            (clear - H17 sth4; eauto).\n        dest.\n        rewrite in_map_iff in *; dest.\n        specialize (H15 _ _ H24 H23).\n        rewrite H22, H21 in *.\n        assumption.\n    - rewrite map_length.\n      rewrite length_combine_cond; congruence.\n    - unfold nthProp, nthProp2 in *; intros.\n      specialize (H10 i); specialize (H8 i); specialize (H5 i).\n      rewrite nth_error_map in *.\n      simpl in *.\n      case_eq (nth_error ls1 i); intros; rewrite H11 in *; auto.\n      setoid_rewrite (nth_error_combine (fun x3 => fst x3 ++ snd x3) _ i x2 x0); auto.\n      case_eq (nth_error x2 i);\n        case_eq (nth_error x0 i);\n        intros; auto; rewrite H12, H13 in *; simpl in *; intros.\n      split; intros.\n      + dest.\n        rewrite H16 at 1 2.\n        repeat rewrite getNumExecs_app, getNumCalls_app.\n        specialize (H8 f);specialize (H10 f).\n        clear - H8 H10; Omega.omega.\n      + dest.\n        rewrite H17. rewrite map_app, in_app_iff in *; setoid_rewrite in_app_iff.\n        clear - H19 H18 H14.\n        destruct H14.\n        specialize (H19 (ex_intro _ x3 H )); dest; eauto.\n        specialize (H18 (ex_intro _ x3 H )); dest; eauto.\n  Qed.\n  \nEnd ModularSubstitution.\n\nSection ModularSubstitution_new.\n  Variable a b a' b': Mod.\n  Variable SameList_a: forall (x : MethT),\n      (In (fst x, projT1 (snd x)) (getKindAttr (getAllMethods a)) /\\\n       ~ In (fst x) (getHidden a)) <->\n      (In (fst x, projT1 (snd x)) (getKindAttr (getAllMethods a')) /\\\n       ~ In (fst x) (getHidden a')).\n  Variable SameList_b: forall (x : MethT),\n      (In (fst x, projT1 (snd x)) (getKindAttr (getAllMethods b)) /\\\n       ~ In (fst x) (getHidden b)) <->\n      (In (fst x, projT1 (snd x)) (getKindAttr (getAllMethods b')) /\\\n       ~ In (fst x) (getHidden b')).\n\n  Variable wfAConcatB: WfMod_new type (ConcatMod a b).\n  Variable wfA'ConcatB': WfMod_new type (ConcatMod a' b').\n\n  Theorem ModularSubstitution_new : TraceInclusion a a' ->\n                             TraceInclusion b b' ->\n                             TraceInclusion (ConcatMod a b) (ConcatMod a' b').\n  Proof.\n    rewrite WfMod_new_WfMod_iff in wfAConcatB, wfA'ConcatB'.\n    apply ModularSubstitution; auto.\n  Qed.\n\nEnd ModularSubstitution_new.\n\nSection Fold.\n  Variable k: Kind.\n\n  Variable f: LetExprSyntax type k -> LetExprSyntax type k -> LetExprSyntax type k.\n  Variable fEval: type k -> type k -> type k.\n  Variable fEval_f: forall x y, evalLetExpr (f x y) = fEval (evalLetExpr x) (evalLetExpr y).\n\n  Lemma evalFoldLeft_Let ls:\n    forall seed,\n      evalLetExpr (fold_left f ls seed) =\n      fold_left fEval (map (@evalLetExpr _) ls) (evalLetExpr seed).\n  Proof.\n    induction ls; simpl; auto; intros.\n    rewrite IHls; simpl.\n    rewrite fEval_f.\n    reflexivity.\n  Qed.\n\n  Lemma evalFoldRight_Let ls:\n    forall seed,\n      evalLetExpr (fold_right f seed ls) =\n      fold_right fEval (evalLetExpr seed) (map (@evalLetExpr _) ls).\n  Proof.\n    induction ls; simpl; auto; intros.\n    rewrite fEval_f.\n    rewrite IHls; simpl.\n    reflexivity.\n  Qed.\n\n  Local Ltac name_term n t H := \n    assert (H: exists n', n' = t);\n    try (exists t; reflexivity);\n    destruct H as [n H]. \n\n\n  Lemma evalFoldTree_Let ls:\n    forall seed,\n      evalLetExpr (fold_tree f seed ls) =\n      fold_tree fEval (evalLetExpr seed) (map (@evalLetExpr _) ls).\n  Proof.\n    assert (exists l, length ls <= l) \n      as [l K] by (exists (length ls); auto). \n    revert ls K.\n    induction l as [| l]; intros * K.\n    - assert (A1: length ls = 0) by omega. \n      apply length_zero_iff_nil in A1.\n      now subst ls.\n    - destruct ls as [| x1 xs]. now simpl.\n      destruct xs as [| x2 xs].\n      intros.\n      simpl.\n      rewrite ?fold_tree_equation.\n      auto.\n\n      intros.\n      rewrite fold_tree_equation.\n      name_term tpl (unapp_half (x1::x2::xs)) Tpl;\n        rewrite <- Tpl; destruct tpl as [m1 m2].\n      simpl in K. \n      assert (K': S (length xs) <= l) by (rewrite le_S_n; auto); \n        clear K; rename K' into K.\n      assert (length m1 <= length (x2::xs) \n              /\\ length m2 <= length (x2::xs))\n        as [A1 A2]. {\n        symmetry in Tpl.\n        apply unapp_half_nonnil_reduces in Tpl; auto.\n        2: simpl; omega. \n        simpl in *.\n        omega. \n      }\n      simpl in A1, A2.\n      assert (A3: length m1 <= l) by omega; clear A1.\n      assert (A4: length m2 <= l) by omega; clear A2.\n      remember (f (fold_tree f seed m1) (fold_tree f seed m2)) as sth.\n      rewrite fold_tree_equation.\n      simpl.\n      apply unapp_half_map with (f := (@evalLetExpr _)) in Tpl.\n      simpl in Tpl.\n      rewrite <- Tpl.\n      rewrite Heqsth; clear Heqsth.\n      rewrite <- ?IHl; auto.\n      destruct xs; simpl; auto.\n  Qed.\n\n  Variable fComm: forall a b, fEval a b = fEval b a.\n  Variable fAssoc: forall a b c, fEval (fEval a b) c = fEval a (fEval b c).\n  Variable unit: LetExprSyntax type k.\n  Variable fUnit: forall x, fEval (evalLetExpr unit) x = x.\n  \n  Lemma evalFoldTree_evalFoldLeft ls:\n    evalLetExpr (fold_tree f unit ls) =\n    evalLetExpr (fold_left f ls unit).\n  Proof.\n    rewrite evalFoldLeft_Let.\n    rewrite evalFoldTree_Let.\n    rewrite fold_left_fold_tree; auto.\n  Qed.\n\n  \n  Lemma evalFoldTree_evalFoldRight ls:\n    evalLetExpr (fold_tree f unit ls) =\n    evalLetExpr (fold_right f unit ls).\n  Proof.\n    rewrite evalFoldRight_Let.\n    rewrite evalFoldTree_Let.\n    rewrite fold_right_fold_tree; auto.\n  Qed.\nEnd Fold.\n\nSection FoldExpr.\n  Variable k: Kind.\n\n  Variable f: Expr type (SyntaxKind k) -> Expr type (SyntaxKind k) -> Expr type (SyntaxKind k).\n  Variable fEval: type k -> type k -> type k.\n  Variable fEval_f: forall x y, evalExpr (f x y) = fEval (evalExpr x) (evalExpr y).\n\n  Lemma evalFoldLeft_Expr ls:\n    forall seed,\n      evalExpr (fold_left f ls seed) =\n      fold_left fEval (map (@evalExpr _) ls) (evalExpr seed).\n  Proof.\n    induction ls; simpl; auto; intros.\n    rewrite IHls; simpl.\n    rewrite fEval_f.\n    reflexivity.\n  Qed.\n\n  Lemma evalFoldRight_Expr ls:\n    forall seed,\n      evalExpr (fold_right f seed ls) =\n      fold_right fEval (evalExpr seed) (map (@evalExpr _) ls).\n  Proof.\n    induction ls; simpl; auto; intros.\n    rewrite fEval_f.\n    rewrite IHls; simpl.\n    reflexivity.\n  Qed.\n\n  Local Ltac name_term n t H := \n    assert (H: exists n', n' = t);\n    try (exists t; reflexivity);\n    destruct H as [n H]. \n\n\n  Lemma evalFoldTree_Expr ls:\n    forall seed,\n      evalExpr (fold_tree f seed ls) =\n      fold_tree fEval (evalExpr seed) (map (@evalExpr _) ls).\n  Proof.\n    assert (exists l, length ls <= l) \n      as [l K] by (exists (length ls); auto). \n    revert ls K.\n    induction l as [| l]; intros * K.\n    - assert (A1: length ls = 0) by omega. \n      apply length_zero_iff_nil in A1.\n      now subst ls.\n    - destruct ls as [| x1 xs]. now simpl.\n      destruct xs as [| x2 xs].\n      intros.\n      simpl.\n      rewrite ?fold_tree_equation.\n      auto.\n\n      intros.\n      rewrite fold_tree_equation.\n      name_term tpl (unapp_half (x1::x2::xs)) Tpl;\n        rewrite <- Tpl; destruct tpl as [m1 m2].\n      simpl in K. \n      assert (K': S (length xs) <= l) by (rewrite le_S_n; auto); \n        clear K; rename K' into K.\n      assert (length m1 <= length (x2::xs) \n              /\\ length m2 <= length (x2::xs))\n        as [A1 A2]. {\n        symmetry in Tpl.\n        apply unapp_half_nonnil_reduces in Tpl; auto.\n        2: simpl; omega. \n        simpl in *.\n        omega. \n      }\n      simpl in A1, A2.\n      assert (A3: length m1 <= l) by omega; clear A1.\n      assert (A4: length m2 <= l) by omega; clear A2.\n      remember (f (fold_tree f seed m1) (fold_tree f seed m2)) as sth.\n      rewrite fold_tree_equation.\n      simpl.\n      apply unapp_half_map with (f := (@evalExpr _)) in Tpl.\n      simpl in Tpl.\n      rewrite <- Tpl.\n      rewrite Heqsth; clear Heqsth.\n      rewrite <- ?IHl; auto.\n      destruct xs; simpl; auto.\n  Qed.\n\n  Variable fComm: forall a b, fEval a b = fEval b a.\n  Variable fAssoc: forall a b c, fEval (fEval a b) c = fEval a (fEval b c).\n  Variable unit: Expr type (SyntaxKind k).\n  Variable fUnit: forall x, fEval (evalExpr unit) x = x.\n  \n  Lemma evalExprFoldTree_evalExprFoldLeft ls:\n    evalExpr (fold_tree f unit ls) =\n    evalExpr (fold_left f ls unit).\n  Proof.\n    rewrite evalFoldLeft_Expr.\n    rewrite evalFoldTree_Expr.\n    rewrite fold_left_fold_tree; auto.\n  Qed.\n\n  \n  Lemma evalExprFoldTree_evalExprFoldRight ls:\n    evalExpr (fold_tree f unit ls) =\n    evalExpr (fold_right f unit ls).\n  Proof.\n    rewrite evalFoldRight_Expr.\n    rewrite evalFoldTree_Expr.\n    rewrite fold_right_fold_tree; auto.\n  Qed.\nEnd FoldExpr.\n\nSection SimulationZeroAct.\n  Variable imp spec: BaseModuleWf type.\n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\ simRel rimp rspec.\n\n  Variable NoMeths: getMethods imp = [].\n  Variable NoMethsSpec: getMethods spec = [].\n\n  Variable simulation:\n    forall oImp rImp uImp rleImp csImp oImp' aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      UpdRegs [uImp] oImp oImp' ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel oImp' oSpec /\\ csImp = []) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n               exists oSpec',\n                 UpdRegs [uSpec] oSpec oSpec' /\\\n                 simRel oImp' oSpec')).\n\n  Theorem simulationZeroAct:\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    pose proof (wfBaseModule imp) as wfImp.\n    pose proof (wfBaseModule spec) as wfSpec.\n    inv wfImp.\n    inv wfSpec.\n    dest.\n    apply simulationZero with (simRel := simRel); auto; simpl; intros.\n    inv H9; [|discriminate].\n    inv HLabel.\n    specialize (@simulation oImp reads u rn cs oImp' rb HInRules HAction H10 _ H11).\n    pose proof (simRelGood H11).\n    destruct simulation.\n    - left; auto.\n    - right.\n      dest.\n      exists x2, x, x3.\n      split.\n      + pose proof (WfActionT_ReadsWellDefined _ (H1 _ H12) H13) as sth1.\n        pose proof (WfActionT_WritesWellDefined _ (H1 _ H12) H13) as sth2.\n        repeat econstructor; eauto.\n      + split; assumption.\n  Qed.\n\nEnd SimulationZeroAct.\n\nSection SimulationZeroAct_new.\n  Variable imp spec: BaseModuleWf_new type.\n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\ simRel rimp rspec.\n\n  Variable NoMeths: getMethods imp = [].\n  Variable NoMethsSpec: getMethods spec = [].\n\n  Variable simulation:\n    forall oImp rImp uImp rleImp csImp oImp' aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      UpdRegs [uImp] oImp oImp' ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel oImp' oSpec /\\ csImp = []) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n               exists oSpec',\n                 UpdRegs [uSpec] oSpec oSpec' /\\\n                 simRel oImp' oSpec')).\n\n  Theorem simulationZeroAct_new :\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    destruct imp, spec.\n    pose (Build_BaseModuleWf (WfBaseModule_new_WfBaseModule wfBaseModule_new)) as x.\n    pose (Build_BaseModuleWf (WfBaseModule_new_WfBaseModule wfBaseModule_new0)) as y.\n    eapply (simulationZeroAct x y); eauto.\n  Qed.\n\nEnd SimulationZeroAct_new.\n\nSection LemmaNoSelfCall.\n  Variable m: BaseModule.\n  Lemma NoSelfCallAction ls k (a: ActionT type k):\n    NoCallActionT ls a ->\n    forall o reads u cs ret,\n      SemAction o a reads u cs ret ->\n      forall f, In (fst f, projT1 (snd f)) (getKindAttr ls) ->\n                getNumFromCalls f cs = 0%Z.\n  Proof.\n    intro.\n    induction H; simpl; auto; intros; simpl in *.\n    - inv H2.\n      EqDep_subst; simpl.\n      specialize (H1 _ _ _ _ _ _ HSemAction _ H3).\n      rewrite H1 in *.\n      match goal with\n      | |- (if ?P then _ else _) = _ => destruct P\n      end; auto; subst; simpl in *.\n      tauto.\n    - inv H1; EqDep_subst; simpl in *.\n      eapply H0; eauto.\n    - inv H2; EqDep_subst; simpl in *.\n      rewrite getNumFromCalls_app.\n      specialize (H1 _ _ _ _ _ _ HSemActionCont _ H3).\n      specialize (IHNoCallActionT _ _ _ _ _ HSemAction _ H3).\n      rewrite H1, IHNoCallActionT.\n      auto.\n    - inv H1; EqDep_subst; simpl in *.\n      eapply H0; eauto.\n    - inv H1; EqDep_subst; simpl in *.\n      eapply H0; eauto.\n    - inv H0; EqDep_subst; simpl in *.\n      eapply IHNoCallActionT; eauto.\n    - inv H3; EqDep_subst; simpl in *; rewrite getNumFromCalls_app.\n      + specialize (IHNoCallActionT1 _ _ _ _ _ HAction _ H4).\n        specialize (H0 _ _ _ _ _ _ HSemAction _ H4).\n        rewrite H0, IHNoCallActionT1.\n        auto.\n      + specialize (IHNoCallActionT2 _ _ _ _ _ HAction _ H4).\n        specialize (H0 _ _ _ _ _ _ HSemAction _ H4).\n        rewrite H0, IHNoCallActionT2.\n        auto.\n    - inv H0; EqDep_subst; simpl in *.\n      eapply IHNoCallActionT; eauto.\n    - inv H; EqDep_subst; simpl in *.\n      auto.\n  Qed.\n\n  Lemma LetExprNoCallActionT k (e: LetExprSyntax type k): forall ls, NoCallActionT ls (convertLetExprSyntax_ActionT e).\n  Proof.\n    induction e; simpl; auto; intros; constructor; auto.\n  Qed.\n  \n  Lemma NoSelfCallRule_Impl r:\n    NoSelfCallBaseModule m ->\n    In r (getRules m) ->\n    forall o reads u cs ret,\n      SemAction o (snd r type) reads u cs ret ->\n      forall f, In (fst f, projT1 (snd f)) (getKindAttr (getMethods m)) ->\n                getNumFromCalls  f cs = 0%Z.\n  Proof.\n    intros.\n    destruct H.\n    unfold NoSelfCallRulesBaseModule, NoSelfCallMethsBaseModule in *.\n    specialize (H _ type H0); simpl in *.\n    eapply NoSelfCallAction; eauto.\n  Qed.\n\n  Lemma NoSelfCallMeth_Impl f:\n    NoSelfCallBaseModule m ->\n    In f (getMethods m) ->\n    forall o reads u cs arg ret,\n      SemAction o (projT2 (snd f) type arg) reads u cs ret ->\n      forall g, In (fst g, projT1 (snd g)) (getKindAttr (getMethods m)) ->\n                getNumFromCalls  g cs = 0%Z.\n  Proof.\n    intros.\n    destruct H.\n    unfold NoSelfCallRulesBaseModule, NoSelfCallMethsBaseModule in *.\n    specialize (H3 _ type H0 arg); simpl in *.\n    eapply NoSelfCallAction; eauto.\n  Qed.\n  \nEnd LemmaNoSelfCall.\n\nSection SimulationGen.\n  Variable imp spec: BaseModuleWf type.\n  Variable NoSelfCalls: NoSelfCallBaseModule spec.\n  \n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\ simRel rimp rspec.\n\n  Variable simulationRule:\n    forall oImp rImp uImp rleImp csImp oImp' aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      UpdRegs [uImp] oImp oImp' ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel oImp' oSpec /\\ csImp = []) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n               exists oSpec',\n                 UpdRegs [uSpec] oSpec oSpec' /\\\n                 simRel oImp' oSpec')).\n\n  Variable simulationMeth:\n    forall oImp rImp uImp meth csImp oImp' sign aImp arg ret,\n      In (meth, existT _ sign aImp) (getMethods imp) ->\n      SemAction oImp (aImp type arg) rImp uImp csImp ret ->\n      UpdRegs [uImp] oImp oImp' ->\n      forall oSpec,\n        simRel oImp oSpec ->\n          exists aSpec rSpec uSpec,\n            In (meth, existT _ sign aSpec) (getMethods spec) /\\\n            SemAction oSpec (aSpec type arg) rSpec uSpec csImp ret /\\\n              exists oSpec',\n                UpdRegs [uSpec] oSpec oSpec' /\\\n                simRel oImp' oSpec'.\n\n  Variable notMethMeth:\n    forall oImp rImpl1 uImpl1 meth1 sign1 aImp1 arg1 ret1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (meth1, existT _ sign1 aImp1) (getMethods imp) ->\n      SemAction oImp (aImp1 type arg1) rImpl1 uImpl1 csImp1 ret1 ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n          \n  Variable notRuleMeth:\n    forall oImp rImpl1 uImpl1 rleImpl1 aImp1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (rleImpl1, aImp1) (getRules imp) ->\n      SemAction oImp (aImp1 type) rImpl1 uImpl1 csImp1 WO ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n\n  Lemma SubstepsSingle o l:\n    Substeps imp o l ->\n    length l <= 1.\n  Proof.\n    induction 1; simpl; auto; intros; subst.\n    - destruct ls; simpl in *; auto; simpl in *.\n      assert (sth1: length ls = 0) by (simpl in *; Omega.omega).\n      rewrite length_zero_iff_nil in sth1; subst; simpl in *.\n      specialize (HNoRle p (or_introl eq_refl)).\n      specialize (HDisjRegs p (or_introl eq_refl)).\n      repeat destruct p; simpl in *.\n      destruct r0; simpl in *; [tauto|].\n      inv H; [discriminate|].\n      destruct fb; simpl in *.\n      destruct (@notRuleMeth _ _ _ _ _ _ _ _ _ _ _ _ _ _ HInRules HAction HInMeths HAction0) as [k [in1 in2]].\n      specialize (HDisjRegs k).\n      inv HLabel.\n      tauto.\n    - destruct ls; simpl in *; auto; simpl in *.\n      assert (sth1: length ls = 0) by (simpl in *; Omega.omega).\n      rewrite length_zero_iff_nil in sth1; subst; simpl in *.\n      specialize (HDisjRegs p (or_introl eq_refl)).\n      repeat destruct p; simpl in *.\n      inv H.\n      + inv HLabel; simpl in *.\n        inv HSubstep; try congruence.\n        destruct fb.\n        destruct (@notRuleMeth _ _ _ _ _ _ _ _ _ _ _ _ _ _ HInRules HAction0 HInMeths HAction) as [k [in1 in2]].\n        specialize (HDisjRegs k).\n        tauto.\n      + destruct ls; [| discriminate].\n        inv HLabel.\n        destruct fb.\n        destruct fb0.\n        destruct (@notMethMeth _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ HInMeths HAction HInMeths0 HAction0) as [k [in1 in2]].\n        specialize (HDisjRegs k).\n        tauto.\n  Qed.\n\n  Lemma InvertStep o l:\n    l <> nil ->\n    Step imp o l ->\n    (exists r a reads upds calls,\n        l = (upds, (Rle r, calls)) :: nil /\\\n        In (r, a) (getRules imp) /\\\n        SemAction o (a type) reads upds calls WO) \\/\n    (exists f sign arg ret a reads upds calls,\n        l = (upds, (Meth (f, existT SignT sign (arg, ret)), calls)) :: nil /\\\n        In (f, existT MethodT sign a) (getMethods imp) /\\\n        SemAction o (a type arg) reads upds calls ret).\n  Proof.\n    intros ? H.\n    inv H.\n    pose proof (SubstepsSingle HSubsteps).\n    destruct l; simpl.\n    - left; tauto.\n    - simpl in H.\n      assert (sth: Datatypes.length l = 0) by lia.\n      rewrite length_zero_iff_nil in sth; subst; clear H0.\n      destruct p.\n      destruct p.\n      destruct r0.\n      + left.\n        inv HSubsteps; inv HLabel.\n        exists rn0, rb, reads, u, cs.\n        repeat split; auto.\n      + right.\n        inv HSubsteps; inv HLabel.\n        destruct fb.\n        exists fn, x, argV, retV, m, reads, u, cs.\n        repeat split; auto.\n  Qed.\n        \n  Theorem simulationGen:\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    pose proof (wfBaseModule imp) as wfImp.\n    pose proof (wfBaseModule spec) as wfSpec.\n    inv wfImp.\n    inv wfSpec.\n    dest.\n    apply StepSimulation with (simRel := simRel); auto; simpl; intros.\n    inv H9.\n    pose proof (SubstepsSingle HSubsteps) as sth.\n    destruct lImp; [tauto| simpl in *].\n    destruct lImp; simpl in *; [| Omega.omega].\n    repeat destruct p; simpl in *.\n    inv HSubsteps; inv HLabel; simpl in *.\n    - destruct (@simulationRule _ _ _ _ _ _ _ HInRules HAction H11 _ H12); dest; subst.\n      exists nil, oSpec.\n      split.\n      + constructor; auto; simpl in *.\n        * constructor 1; auto.\n          eapply simRelGood; eauto.\n        * unfold MatchingExecCalls_Base, getNumCalls, getNumExecs; intros; simpl.\n          Omega.omega.\n      + simpl.\n        split.\n        * unfold UpdRegs; repeat split; auto; intros.\n          right; split; try intro; simpl in *; auto.\n          dest; auto.\n        * split; auto.\n          unfold WeakInclusion; simpl; intros.\n          unfold getListFullLabel_diff; simpl.\n          split; intros; dest; auto.\n          tauto.\n      + exists [(x2, (Rle x, cs))], x3; simpl.\n        split.\n        * constructor; auto.\n          -- econstructor 2; eauto.\n             ++ eapply WfActionT_ReadsWellDefined; eauto.\n             ++ eapply WfActionT_WritesWellDefined; eauto.\n             ++ simpl; intros; tauto.\n             ++ constructor 1; auto.\n                eapply simRelGood; eauto.\n          -- unfold MatchingExecCalls_Base; unfold getNumCalls, getNumExecs; simpl; intros.\n             rewrite app_nil_r.\n             assert (th1: forall x, (x = 0)%Z -> (x <= 0)%Z) by (intros; Omega.omega).\n             apply th1; clear th1.\n             eapply NoSelfCallRule_Impl; eauto.\n        * split; auto.\n          split; auto.\n          unfold WeakInclusion; simpl; intros.\n          split; intros; auto.\n          exists rn.\n          left; auto.\n    - destruct fb.\n      destruct (@simulationMeth _ _ _ _ _ _ _ _ _ _ HInMeths HAction H11 _ H12); dest; subst.\n      exists [(x2, (Meth (fn, existT _ x (argV, retV)), cs))], x3; simpl.\n      split.\n      * constructor; auto.\n        -- econstructor 3; eauto.\n           ++ eapply WfActionT_ReadsWellDefined; eauto.\n           ++ eapply WfActionT_WritesWellDefined; eauto.\n           ++ simpl; intros; tauto.\n           ++ constructor 1; auto.\n              eapply simRelGood; eauto.\n        -- unfold MatchingExecCalls_Base; unfold getNumCalls, getNumExecs; simpl; intros.\n           rewrite app_nil_r.\n           assert (th1: forall x, (x = 0)%Z -> (x <= 0)%Z) by (intros; Omega.omega).\n           match goal with\n           | |- (_ <= if ?P then _ else _)%Z => destruct P; subst; simpl in *\n           end.\n           ++ assert (th2: forall x, (x = 0)%Z -> (x <= 1)%Z) by (intros; Omega.omega).\n              apply th2; clear th2.\n              eapply NoSelfCallMeth_Impl; eauto.\n           ++ apply th1; clear th1.\n              eapply NoSelfCallMeth_Impl; eauto.\n      * split; auto.\n        split; auto.\n        unfold WeakInclusion; simpl; intros.\n        split; intros; auto.\n  Qed.\nEnd SimulationGen.    \n\nSection SimulationGen_new.\n  Variable imp spec: BaseModuleWf_new type.\n  Variable NoSelfCalls: NoSelfCallBaseModule spec.\n  \n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\ simRel rimp rspec.\n\n  Variable simulationRule:\n    forall oImp rImp uImp rleImp csImp oImp' aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      UpdRegs [uImp] oImp oImp' ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel oImp' oSpec /\\ csImp = []) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n               exists oSpec',\n                 UpdRegs [uSpec] oSpec oSpec' /\\\n                 simRel oImp' oSpec')).\n\n  Variable simulationMeth:\n    forall oImp rImp uImp meth csImp oImp' sign aImp arg ret,\n      In (meth, existT _ sign aImp) (getMethods imp) ->\n      SemAction oImp (aImp type arg) rImp uImp csImp ret ->\n      UpdRegs [uImp] oImp oImp' ->\n      forall oSpec,\n        simRel oImp oSpec ->\n          exists aSpec rSpec uSpec,\n            In (meth, existT _ sign aSpec) (getMethods spec) /\\\n            SemAction oSpec (aSpec type arg) rSpec uSpec csImp ret /\\\n              exists oSpec',\n                UpdRegs [uSpec] oSpec oSpec' /\\\n                simRel oImp' oSpec'.\n\n  Variable notMethMeth:\n    forall oImp rImpl1 uImpl1 meth1 sign1 aImp1 arg1 ret1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (meth1, existT _ sign1 aImp1) (getMethods imp) ->\n      SemAction oImp (aImp1 type arg1) rImpl1 uImpl1 csImp1 ret1 ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n          \n  Variable notRuleMeth:\n    forall oImp rImpl1 uImpl1 rleImpl1 aImp1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (rleImpl1, aImp1) (getRules imp) ->\n      SemAction oImp (aImp1 type) rImpl1 uImpl1 csImp1 WO ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n\n  Theorem simulationGen_new :\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    destruct imp, spec.\n    pose (Build_BaseModuleWf (WfBaseModule_new_WfBaseModule wfBaseModule_new)) as x.\n    pose (Build_BaseModuleWf (WfBaseModule_new_WfBaseModule wfBaseModule_new0)) as y.\n    eapply (simulationGen x y); eauto.\n  Qed.\nEnd SimulationGen_new.\n\nLemma findRegs_Some u:\n  NoDup (map fst u) ->\n  forall s v,\n    In (s, v) u <-> findReg s u = Some v.\nProof.\n  induction u; simpl; split; auto; intros; auto; try (tauto || discriminate).\n  - destruct H0; subst; simpl.\n    + rewrite String.eqb_refl; simpl; tauto.\n    + destruct a; simpl in *.\n      inv H.\n      specialize (IHu H4).\n      destruct (String.eqb s s0) eqn:G; [rewrite String.eqb_eq in G|]; subst; simpl; auto; subst.\n      * apply (in_map fst) in H0; simpl in *; tauto.\n      * rewrite <- IHu; auto.\n  - destruct a; simpl in *.\n    destruct (String.eqb s s0) eqn:G; [rewrite String.eqb_eq in G|] ; simpl in *.\n    inv H0; auto.\n    inv H.\n    specialize (IHu H4).\n    rewrite <- IHu in H0.\n    auto.\nQed.\n\nLemma InvProp A (P Q: A -> Prop):\n  (forall x, P x <-> Q x) ->\n  (forall x, ~ Q x <-> ~ P x).\nProof.\n  intros.\n  firstorder.\nQed.\n\nLemma findRegs_None u:\n  forall s,\n    ~ In s (map fst u) <-> findReg s u = None.\nProof.\n  induction u; simpl; split; auto; destruct a; simpl; intros.\n  - destruct (string_dec s s0); subst.\n    + firstorder fail.\n    + rewrite <- String.eqb_neq in n; rewrite n.\n      rewrite <- IHu.\n      firstorder fail.\n  - destruct (String.eqb s s0) eqn:G; [rewrite String.eqb_eq in G|]; subst.\n    + discriminate.\n    + rewrite <- IHu in H.\n      intro.\n      rewrite String.eqb_neq in G; firstorder.\nQed.\n\nLemma NoDup_app A (l1: list (string * A)):\n  forall l2,\n    DisjKeyWeak l1 l2 ->\n    NoDup (map fst l1) ->\n    NoDup (map fst l2) ->\n    NoDup (map fst (l1 ++ l2)).\nProof.\n  induction l1; unfold DisjKeyWeak; simpl; auto;\n    rewrite ?app_nil_l, ?app_nil_r; intros; auto.\n  inv H0.\n  constructor.\n  - intro.\n    rewrite map_app in *.\n    rewrite in_app_iff in H0.\n    specialize (H (fst a) (or_introl eq_refl)).\n    tauto.\n  - eapply IHl1; auto.\n    unfold DisjKeyWeak; firstorder fail.\nQed.\n\nLemma SemAction_NoDup_u k o (a: ActionT type k) readRegs u calls retl:\n  SemAction o a readRegs u calls retl ->\n  NoDup (map fst u).\nProof.\n  induction 1; simpl; auto; rewrite ?DisjKeyWeak_same in * by (apply string_dec); subst.\n  - apply NoDup_app; auto.\n  - simpl.\n    constructor; auto.\n    unfold key_not_In in *.\n    intro.\n    rewrite in_map_iff in H0; dest.\n    destruct x; simpl in *; subst.\n    firstorder fail.\n  - apply NoDup_app; auto.\n  - apply NoDup_app; auto.\n  - simpl; constructor.\nQed.\n\nLemma NoDup_UpdRegs o:\n  NoDup (map fst o) ->\n  forall u o',\n    NoDup (map fst u) ->\n    UpdRegs [u] o o' ->\n    o' = doUpdRegs u o.\nProof.\n  induction o; simpl; auto; intros.\n  - inv H1; simpl in *.\n    apply eq_sym in H2.\n    apply map_eq_nil in H2.\n    auto.\n  - inv H1; simpl in *.\n    destruct o'; simpl in *; [discriminate|].\n    inv H2.\n    f_equal.\n    + specialize (H3 (fst p) (snd p)).\n      destruct p; simpl in *.\n      specialize (H3 (or_introl eq_refl)).\n      rewrite H4 in *.\n      destruct H3.\n      * dest.\n        destruct H1; [subst|tauto].\n        rewrite findRegs_Some in H2; auto.\n        rewrite H2; auto.\n      * dest.\n        assert (sth2: ~ In s (map fst u)) by firstorder.\n        pose proof sth2 as sth3.\n        rewrite findRegs_None in sth2.\n        rewrite sth2.\n        destruct H2; [congruence|].\n        inv H.\n        apply (in_map fst) in H2; simpl in *.\n        exfalso; tauto.\n    + inv H.\n      eapply IHo; eauto.\n      constructor; auto; intros; simpl.\n      specialize (H3 s v (or_intror H)).\n      destruct H3; [tauto|].\n      dest.\n      destruct H2; subst; simpl in *.\n      * apply (in_map fst) in H; simpl in *.\n        apply (f_equal (map fst)) in H6.\n        rewrite ?map_map in *; simpl in *.\n        assert (sth: forall A B, (fun (x: (A * B)) => fst x) = fst) by (intros; extensionality x; intros; reflexivity).\n        rewrite ?sth in H6.\n        rewrite <- H6 in H.\n        tauto.\n      * right; auto.\nQed.\n\nLemma findRegs_Some' u:\n  forall s v,\n    findReg s u = Some v ->\n    In (s, v) u.\nProof.\n  induction u; simpl; auto; intros; auto; try (tauto || discriminate).\n  destruct (String.eqb s (fst a)) eqn:G; [rewrite String.eqb_eq in G|]; subst; simpl in *.\n  - inv H; auto.\n    destruct a; auto. \n  - specialize (IHu _ _ H).\n    right; auto.\nQed.\n                           \nLemma doUpdRegs_enuf o u:\n  getKindAttr o = getKindAttr (doUpdRegs u o) ->\n  UpdRegs [u] o (doUpdRegs u o).\nProof.\n  induction o; simpl; auto; unfold UpdRegs; intros.\n  - repeat split; simpl; auto.\n  - inv H.\n    specialize (IHo H3).\n    simpl in *; intros.\n    repeat split; auto; intros.\n    + rewrite H1 at 1.\n      rewrite H2 at 1.\n      rewrite H3.\n      auto.\n    + unfold UpdRegs in *.\n      dest.\n      destruct H.\n      * case_eq (findReg (fst a) u); intros; rewrite H5 in *; simpl in *.\n        -- apply findRegs_Some' in H5.\n           inv H; simpl in *.\n           left; eexists; eauto.\n        -- rewrite <- findRegs_None in H5 by auto; subst; simpl in *.\n           right.\n           split; try intro; auto; dest.\n           destruct H; subst; auto.\n      * specialize (H4 _ _ H).\n        clear - H4; firstorder fail.\nQed.\n\nLemma UpdRegs_nil_nil_upd: forall o, NoDup (map fst o) -> forall o', UpdRegs [[]] o o' -> o = o'.\nProof.\n  unfold UpdRegs.\n  intros.\n  dest.\n  simpl in *.\n  assert (sth: forall s v, In (s, v) o' -> In (s, v) o).\n  { intros.\n    specialize (H1 s v H2).\n    destruct H1; dest; try auto.\n    destruct H1; subst; simpl in *; try tauto.\n  }\n  clear H1.\n  generalize o' H H0 sth.\n  clear o' H H0 sth.\n  induction o; destruct o'; simpl; auto; intros.\n  - discriminate.\n  - discriminate.\n  - inv H0.\n    inv H.\n    specialize (IHo _ H6 H4).\n    destruct p, a; simpl in *; subst; auto; repeat f_equal; auto.\n    + specialize (sth s s0 (or_introl eq_refl)).\n      destruct sth.\n      * inv H; subst; auto.\n      * apply (in_map fst) in H; simpl in *; tauto.\n    + eapply IHo; intros.\n      specialize (sth _ _ (or_intror H)).\n      destruct sth; [|auto].\n      inv H0; subst.\n      apply (f_equal (map fst)) in H4.\n      rewrite ?map_map in *; simpl in *.\n      setoid_rewrite (functional_extensionality (fun x => fst x) fst) in H4; try tauto.\n      apply (in_map fst) in H; simpl in *; congruence.\nQed.\n\nLemma getKindAttr_findReg_Some u:\n  forall o: RegsT,\n    (forall s v, In (s, v) u -> In (s, projT1 v) (getKindAttr o)) ->\n    forall s v,\n      findReg s u = Some v ->\n      In (s, projT1 v) (getKindAttr o).\nProof.\n  intros.\n  apply findRegs_Some' in H0.\n  specialize (H _ _ H0); simpl in *.\n  auto.\nQed.\n\nLemma getKindAttr_doUpdRegs' o:\n  forall u,\n    getKindAttr (doUpdRegs u o) = map (fun x => match findReg (fst x) u with\n                                                | Some y => (fst x, projT1 y)\n                                                | None => (fst x, projT1 (snd x))\n                                                end) o.\nProof.\n  induction o; simpl; auto; intros.\n  case_eq (findReg (fst a) u); simpl; intros; f_equal; auto.\nQed.\n\nLemma forall_map A B (f g: A -> B) ls:\n  (map f ls = map g ls) <->\n  forall x, In x ls -> f x = g x.\nProof.\n  induction ls; simpl; split; auto; intros; try tauto.\n  - destruct H0; subst.\n    + inv H.\n      auto.\n    + inv H.\n      rewrite IHls in H3.\n      eapply H3; eauto.\n  - assert (sth1: f a = g a) by firstorder fail.\n    assert (sth2: forall x, In x ls -> f x = g x) by firstorder fail.\n    f_equal; auto.\n    firstorder.\nQed.\n\n\nLemma KeyMatching_gen A B : forall (l : list (A * B)) (a b : A * B),\n    NoDup (map fst l) -> In a l -> In b l -> fst a = fst b -> a = b.\nProof.\n  induction l; intros.\n  - inversion H0.\n  - destruct H0; destruct H1.\n    + symmetry; rewrite <- H1; assumption.\n    + rewrite (map_cons fst) in H.\n      inversion H; subst.\n      apply (in_map fst l b) in H1.\n      apply False_ind. apply H5.\n      destruct a0; destruct b; simpl in *.\n      rewrite H2; assumption.\n    + rewrite (map_cons fst) in H.\n      inversion H; subst.\n      apply (in_map fst l a0) in H0.\n      apply False_ind; apply H5.\n      destruct a0, b; simpl in *.\n      rewrite <- H2; assumption.\n    + inversion H; subst.\n      apply IHl; auto.\nQed.\n\nLemma NoDup_map_fst {A B} {ls: list (A * B)}:\n    NoDup (map fst ls) ->\n    forall {a b c},\n      In (a, b) ls ->\n      In (a, c) ls ->\n      b = c.\nProof.\n  induction ls; simpl; auto; intros.\n  - tauto.\n  - inv H.\n    specialize (@IHls H5).\n    destruct H0, H1; subst; simpl in *.\n    + inv H0.\n      auto.\n    + rewrite in_map_iff in H4.\n      assert (sth: exists x, fst x = a0 /\\ In x ls). {\n        exists (a0, c); split; auto. }\n      tauto.\n    + rewrite in_map_iff in H4.\n      assert (sth: exists x, fst x = a0 /\\ In x ls). {\n        exists (a0, b); split; auto. }\n      tauto.\n    + eapply IHls; eauto.\nQed.\n\nLemma getKindAttr_doUpdRegs o:\n  NoDup (map fst o) ->\n  forall u,\n    (forall s v, In (s, v) u -> In (s, projT1 v) (getKindAttr o)) ->\n    getKindAttr o = getKindAttr (doUpdRegs u o).\nProof.\n  intros.\n  setoid_rewrite getKindAttr_doUpdRegs'.\n  rewrite forall_map; intros.\n  case_eq (findReg (fst x) u); intros; auto.\n  destruct x; simpl in *.\n  f_equal.\n  destruct s1, s; simpl in *.\n  pose proof (findRegs_Some' _ _ H2) as sth.\n  specialize (H0 s0 (existT (fullType type) x0 f0) sth).\n  rewrite in_map_iff in H0; dest.\n  destruct x1; simpl in *.\n  inv H0.\n  pose proof (NoDup_map_fst H H3 H1).\n  subst.\n  auto.\nQed.\n\nLemma getKindAttr_doUpdRegs_app: forall regs upds1 upds2,\n      NoDup (map fst regs) ->\n      (forall (s : string) (v : {x : FullKind & fullType type x}), In (s, v) upds1 -> In (s, projT1 v) (getKindAttr regs)) ->\n      (forall (s : string) (v : {x : FullKind & fullType type x}), In (s, v) upds2 -> In (s, projT1 v) (getKindAttr regs)) ->\n      getKindAttr regs = getKindAttr (doUpdRegs (upds1 ++ upds2) regs).\nProof.\n  induction upds1; intros; simpl.\n  { eapply getKindAttr_doUpdRegs; auto. }\n  {\n    rewrite getKindAttr_doUpdRegs'.\n    rewrite forall_map; intros.\n    case_eq (findReg (fst x) (a :: upds1 ++ upds2)); intros; auto.\n    epose proof (findRegs_Some' _ _ H3) as inSome.\n    clear H3.\n    destruct x; simpl in *.\n    f_equal.\n    destruct s1, s; simpl in *.\n    destruct inSome.\n    {\n      unshelve epose proof (H0 s0 (existT (fullType type) x0 f0) _) as H0; intuition auto.\n      rewrite in_map_iff in H0; dest.\n      destruct x1; simpl in *.\n      inv H0.\n      pose proof (NoDup_map_fst H H4 H2).\n      subst.\n      auto.\n    }\n    {\n      assert (okApp: forall (s : string) (v : {x : FullKind & fullType type x}), In (s, v) (upds1 ++ upds2) -> In (s, projT1 v) (getKindAttr regs)).\n      intros.\n      edestruct (in_app_or _ _ _ H4).\n      {\n        eapply H0.\n        auto.\n      }\n      {\n        eapply H1.\n        auto.\n      }\n      specialize (okApp s0 (existT (fullType type) x0 f0) H3).\n      rewrite in_map_iff in okApp; dest.\n      simpl in H4.\n      inv H4.\n      destruct x1.\n      epose proof (NoDup_map_fst H H5 H2).\n      subst.\n      auto.\n    }\n  }\nQed.\n\nLemma doUpdRegs_UpdRegs' o:\n  NoDup (map fst o) ->\n  forall u,\n    (forall s v, In (s, v) u -> In (s, projT1 v) (getKindAttr o)) ->\n    UpdRegs [u] o (doUpdRegs u o).\nProof.\n  intros.\n  eapply doUpdRegs_enuf; eauto.\n  eapply getKindAttr_doUpdRegs; eauto.\nQed.\n\nLemma doUpdRegs_UpdRegs o:\n  NoDup (map fst o) ->\n  forall u,\n    SubList (getKindAttr u) (getKindAttr o) ->\n    UpdRegs [u] o (doUpdRegs u o).\nProof.\n  intros.\n  eapply doUpdRegs_enuf; eauto.\n  eapply getKindAttr_doUpdRegs; eauto; intros.\n  apply (in_map (fun x => (fst x, projT1 (snd x)))) in H1; simpl in *.\n  eapply H0; eauto.\nQed.\n\nSection SimulationGeneralEx.\n  Variable imp spec: BaseModuleWf type.\n  Variable NoSelfCalls: NoSelfCallBaseModule spec.\n  \n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable simRelImpGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oImp = getKindAttr (getRegisters imp).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\ simRel rimp rspec.\n\n  Variable simulationRule:\n    forall oImp rImp uImp rleImp csImp aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel (doUpdRegs uImp oImp) oSpec /\\ csImp = []) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n               exists oSpec',\n                 UpdRegs [uSpec] oSpec oSpec' /\\\n                 simRel (doUpdRegs uImp oImp) oSpec')).\n\n  Variable simulationMeth:\n    forall oImp rImp uImp meth csImp sign aImp arg ret,\n      In (meth, existT _ sign aImp) (getMethods imp) ->\n      SemAction oImp (aImp type arg) rImp uImp csImp ret ->\n      forall oSpec,\n        simRel oImp oSpec ->\n          exists aSpec rSpec uSpec,\n            In (meth, existT _ sign aSpec) (getMethods spec) /\\\n            SemAction oSpec (aSpec type arg) rSpec uSpec csImp ret /\\\n              exists oSpec',\n                UpdRegs [uSpec] oSpec oSpec' /\\\n                simRel (doUpdRegs uImp oImp) oSpec'.\n\n  Variable notMethMeth:\n    forall oImp rImpl1 uImpl1 meth1 sign1 aImp1 arg1 ret1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (meth1, existT _ sign1 aImp1) (getMethods imp) ->\n      SemAction oImp (aImp1 type arg1) rImpl1 uImpl1 csImp1 ret1 ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n          \n  Variable notRuleMeth:\n    forall oImp rImpl1 uImpl1 rleImpl1 aImp1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (rleImpl1, aImp1) (getRules imp) ->\n      SemAction oImp (aImp1 type) rImpl1 uImpl1 csImp1 WO ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n\n  Theorem simulationGeneralEx:\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    eapply simulationGen; eauto; intros.\n    - pose proof (SemAction_NoDup_u H0) as sth.\n      pose proof (simRelImpGood H2) as sth2.\n      apply (f_equal (map fst)) in sth2.\n      rewrite ?map_map in *; simpl in *.\n      assert (sth3: forall A B, (fun x: (A * B) => fst x) = fst) by\n          (intros; extensionality x; intros; auto).\n      destruct (wfBaseModule imp); dest.\n      rewrite <- sth3 in H6.\n      rewrite <- sth2 in H6.\n      rewrite sth3 in H6.\n      apply NoDup_UpdRegs in H1; subst; auto.\n      eapply simulationRule; eauto.\n    - pose proof (SemAction_NoDup_u H0) as sth.\n      pose proof (simRelImpGood H2) as sth2.\n      apply (f_equal (map fst)) in sth2.\n      rewrite ?map_map in *; simpl in *.\n      assert (sth3: forall A B, (fun x: (A * B) => fst x) = fst) by\n          (intros; extensionality x; intros; auto).\n      destruct (wfBaseModule imp); dest.\n      rewrite <- sth3 in H6.\n      rewrite <- sth2 in H6.\n      rewrite sth3 in H6.\n      apply NoDup_UpdRegs in H1; subst; auto.\n      eapply simulationMeth; eauto.\n  Qed.\nEnd SimulationGeneralEx.\n\nSection SimulationGeneralEx_new.\n  Variable imp spec: BaseModuleWf_new type.\n  Variable NoSelfCalls: NoSelfCallBaseModule spec.\n  \n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable simRelImpGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oImp = getKindAttr (getRegisters imp).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\ simRel rimp rspec.\n\n  Variable simulationRule:\n    forall oImp rImp uImp rleImp csImp aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel (doUpdRegs uImp oImp) oSpec /\\ csImp = []) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n               exists oSpec',\n                 UpdRegs [uSpec] oSpec oSpec' /\\\n                 simRel (doUpdRegs uImp oImp) oSpec')).\n\n  Variable simulationMeth:\n    forall oImp rImp uImp meth csImp sign aImp arg ret,\n      In (meth, existT _ sign aImp) (getMethods imp) ->\n      SemAction oImp (aImp type arg) rImp uImp csImp ret ->\n      forall oSpec,\n        simRel oImp oSpec ->\n          exists aSpec rSpec uSpec,\n            In (meth, existT _ sign aSpec) (getMethods spec) /\\\n            SemAction oSpec (aSpec type arg) rSpec uSpec csImp ret /\\\n              exists oSpec',\n                UpdRegs [uSpec] oSpec oSpec' /\\\n                simRel (doUpdRegs uImp oImp) oSpec'.\n\n  Variable notMethMeth:\n    forall oImp rImpl1 uImpl1 meth1 sign1 aImp1 arg1 ret1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (meth1, existT _ sign1 aImp1) (getMethods imp) ->\n      SemAction oImp (aImp1 type arg1) rImpl1 uImpl1 csImp1 ret1 ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n          \n  Variable notRuleMeth:\n    forall oImp rImpl1 uImpl1 rleImpl1 aImp1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (rleImpl1, aImp1) (getRules imp) ->\n      SemAction oImp (aImp1 type) rImpl1 uImpl1 csImp1 WO ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n\n  Theorem simulationGeneralEx_new:\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    destruct imp, spec.\n    pose (Build_BaseModuleWf (WfBaseModule_new_WfBaseModule wfBaseModule_new)) as x.\n    pose (Build_BaseModuleWf (WfBaseModule_new_WfBaseModule wfBaseModule_new0)) as y.\n    eapply (simulationGeneralEx x y); eauto.\n  Qed.\n\nEnd SimulationGeneralEx_new.\n\n\n\n\nSection SimulationZeroA.\n  Variable imp spec: BaseModuleWf type.\n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec ->\n                                          getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable simRelImpGood: forall oImp oSpec, simRel oImp oSpec ->\n                                             getKindAttr oImp = getKindAttr (getRegisters imp).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\\n                                               simRel rimp rspec.\n\n  Variable NoMeths: getMethods imp = [].\n  Variable NoMethsSpec: getMethods spec = [].\n\n  Variable simulation:\n    forall oImp rImp uImp rleImp csImp aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel (doUpdRegs uImp oImp) oSpec /\\ csImp = []) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n               exists oSpec',\n                 UpdRegs [uSpec] oSpec oSpec' /\\\n                 simRel (doUpdRegs uImp oImp) oSpec')).\n\n  Theorem simulationZeroA:\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    eapply simulationZeroAct; eauto; intros.\n    pose proof (SemAction_NoDup_u H0) as sth.\n    pose proof (simRelImpGood H2) as sth2.\n    apply (f_equal (map fst)) in sth2.\n    rewrite ?map_map in *; simpl in *.\n    assert (sth3: forall A B, (fun x: (A * B) => fst x) = fst) by\n        (intros; extensionality x; intros; auto).\n    destruct (wfBaseModule imp); dest.\n    rewrite <- sth3 in H6.\n    rewrite <- sth2 in H6.\n    rewrite sth3 in H6.\n    apply NoDup_UpdRegs in H1; subst; auto.\n    eapply simulation; eauto.\n  Qed.\nEnd SimulationZeroA.\n\nSection SimulationZeroA_new.\n  Variable imp spec: BaseModuleWf_new type.\n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec ->\n                                          getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable simRelImpGood: forall oImp oSpec, simRel oImp oSpec ->\n                                             getKindAttr oImp = getKindAttr (getRegisters imp).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\\n                                               simRel rimp rspec.\n\n  Variable NoMeths: getMethods imp = [].\n  Variable NoMethsSpec: getMethods spec = [].\n\n  Variable simulation:\n    forall oImp rImp uImp rleImp csImp aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel (doUpdRegs uImp oImp) oSpec /\\ csImp = []) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n               exists oSpec',\n                 UpdRegs [uSpec] oSpec oSpec' /\\\n                 simRel (doUpdRegs uImp oImp) oSpec')).\n\n  Theorem simulationZeroA_new:\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    destruct imp, spec.\n    pose (Build_BaseModuleWf (WfBaseModule_new_WfBaseModule wfBaseModule_new)) as x.\n    pose (Build_BaseModuleWf (WfBaseModule_new_WfBaseModule wfBaseModule_new0)) as y.\n    eapply (simulationZeroA x y); eauto.\n  Qed.\nEnd SimulationZeroA_new.\n\nSection SimulationGeneral.\n  Variable imp spec: BaseModuleWf type.\n  Variable NoSelfCalls: NoSelfCallBaseModule spec.\n  \n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable simRelImpGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oImp = getKindAttr (getRegisters imp).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\ simRel rimp rspec.\n\n  Variable simulationRule:\n    forall oImp rImp uImp rleImp csImp aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel (doUpdRegs uImp oImp) oSpec /\\ csImp = []) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n                 simRel (doUpdRegs uImp oImp) (doUpdRegs uSpec oSpec))).\n\n  Variable simulationMeth:\n    forall oImp rImp uImp meth csImp sign aImp arg ret,\n      In (meth, existT _ sign aImp) (getMethods imp) ->\n      SemAction oImp (aImp type arg) rImp uImp csImp ret ->\n      forall oSpec,\n        simRel oImp oSpec ->\n          exists aSpec rSpec uSpec,\n            In (meth, existT _ sign aSpec) (getMethods spec) /\\\n            SemAction oSpec (aSpec type arg) rSpec uSpec csImp ret /\\\n                simRel (doUpdRegs uImp oImp) (doUpdRegs uSpec oSpec).\n\n  Variable notMethMeth:\n    forall oImp rImpl1 uImpl1 meth1 sign1 aImp1 arg1 ret1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (meth1, existT _ sign1 aImp1) (getMethods imp) ->\n      SemAction oImp (aImp1 type arg1) rImpl1 uImpl1 csImp1 ret1 ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n          \n  Variable notRuleMeth:\n    forall oImp rImpl1 uImpl1 rleImpl1 aImp1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (rleImpl1, aImp1) (getRules imp) ->\n      SemAction oImp (aImp1 type) rImpl1 uImpl1 csImp1 WO ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n\n  Theorem simulationGeneral:\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    eapply simulationGeneralEx; eauto; intros.\n    - specialize (@simulationRule _ _ _ _ _ _ H H0 oSpec H1).\n      destruct simulationRule; auto.\n      dest.\n      right.\n      exists x, x0; repeat split; auto.\n      exists x1, x2; repeat split; auto.\n      exists (doUpdRegs x2 oSpec); split; auto.\n      \n      pose proof (SemAction_NoDup_u H3) as sth.\n      destruct (wfBaseModule spec); dest.\n      pose proof (simRelGood H1) as sth2.\n      apply (f_equal (map fst)) in sth2.\n      rewrite ?map_map in *; simpl in *.\n      assert (sth3: forall A B, (fun x: (A * B) => fst x) = fst) by\n          (intros; extensionality y; intros; auto).\n      rewrite <- sth3 in H8.\n      rewrite <- sth2 in H8.\n      rewrite sth3 in H8.\n      pose proof (SemActionUpdSub H3).\n      eapply doUpdRegs_UpdRegs; eauto.\n    - specialize (@simulationMeth _ _ _ _ _ _ _ _ _ H H0 oSpec H1).\n      pose proof simulationMeth as sth; clear simulationMeth.\n      dest.\n      exists x, x0, x1; repeat split; auto.\n      exists (doUpdRegs x1 oSpec); split; auto.\n      pose proof (SemAction_NoDup_u H3) as sth.\n      destruct (wfBaseModule spec); dest.\n      pose proof (simRelGood H1) as sth2.\n      apply (f_equal (map fst)) in sth2.\n      rewrite ?map_map in *; simpl in *.\n      assert (sth3: forall A B, (fun x: (A * B) => fst x) = fst) by\n          (intros; extensionality y; intros; auto).\n      rewrite <- sth3 in H8.\n      rewrite <- sth2 in H8.\n      rewrite sth3 in H8.\n      pose proof (SemActionUpdSub H3).\n      eapply doUpdRegs_UpdRegs; eauto.\n  Qed.\nEnd SimulationGeneral.\n\nSection SimulationGeneral_new.\n  Variable imp spec: BaseModuleWf_new type.\n  Variable NoSelfCalls: NoSelfCallBaseModule spec.\n  \n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable simRelImpGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oImp = getKindAttr (getRegisters imp).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\ simRel rimp rspec.\n\n  Variable simulationRule:\n    forall oImp rImp uImp rleImp csImp aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel (doUpdRegs uImp oImp) oSpec /\\ csImp = []) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n                 simRel (doUpdRegs uImp oImp) (doUpdRegs uSpec oSpec))).\n\n  Variable simulationMeth:\n    forall oImp rImp uImp meth csImp sign aImp arg ret,\n      In (meth, existT _ sign aImp) (getMethods imp) ->\n      SemAction oImp (aImp type arg) rImp uImp csImp ret ->\n      forall oSpec,\n        simRel oImp oSpec ->\n          exists aSpec rSpec uSpec,\n            In (meth, existT _ sign aSpec) (getMethods spec) /\\\n            SemAction oSpec (aSpec type arg) rSpec uSpec csImp ret /\\\n                simRel (doUpdRegs uImp oImp) (doUpdRegs uSpec oSpec).\n\n  Variable notMethMeth:\n    forall oImp rImpl1 uImpl1 meth1 sign1 aImp1 arg1 ret1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (meth1, existT _ sign1 aImp1) (getMethods imp) ->\n      SemAction oImp (aImp1 type arg1) rImpl1 uImpl1 csImp1 ret1 ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n          \n  Variable notRuleMeth:\n    forall oImp rImpl1 uImpl1 rleImpl1 aImp1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (rleImpl1, aImp1) (getRules imp) ->\n      SemAction oImp (aImp1 type) rImpl1 uImpl1 csImp1 WO ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n\n  Theorem simulationGeneral_new :\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    destruct imp, spec.\n    pose (Build_BaseModuleWf (WfBaseModule_new_WfBaseModule wfBaseModule_new)) as x.\n    pose (Build_BaseModuleWf (WfBaseModule_new_WfBaseModule wfBaseModule_new0)) as y.\n    eapply (simulationGeneral x y); eauto.\n  Qed.\n\nEnd SimulationGeneral_new.\n\n\nSection SimulationZeroAction.\n  Variable imp spec: BaseModuleWf type.\n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec ->\n                                          getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable simRelImpGood: forall oImp oSpec, simRel oImp oSpec ->\n                                             getKindAttr oImp = getKindAttr (getRegisters imp).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\\n                                               simRel rimp rspec.\n\n  Variable NoMeths: getMethods imp = [].\n  Variable NoMethsSpec: getMethods spec = [].\n\n  Variable simulation:\n    forall oImp rImp uImp rleImp csImp aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel (doUpdRegs uImp oImp) oSpec /\\ csImp = []) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n                 simRel (doUpdRegs uImp oImp) (doUpdRegs uSpec oSpec))).\n\n  Theorem simulationZeroAction:\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    eapply simulationZeroA; eauto; intros.\n    specialize (@simulation _ _ _ _ _ _ H H0 _ H1).\n    destruct simulation; auto.\n    right.\n    dest.\n    exists x, x0; split; auto.\n    exists x1, x2; split; auto.\n    exists (doUpdRegs x2 oSpec); split; auto.\n    pose proof (SemAction_NoDup_u H3) as sth.\n    destruct (wfBaseModule spec); dest.\n    pose proof (simRelGood H1) as sth2.\n    apply (f_equal (map fst)) in sth2.\n    rewrite ?map_map in *; simpl in *.\n    assert (sth3: forall A B, (fun x: (A * B) => fst x) = fst) by\n        (intros; extensionality y; intros; auto).\n    rewrite <- sth3 in H8.\n    rewrite <- sth2 in H8.\n    rewrite sth3 in H8.\n    pose proof (SemActionUpdSub H3).\n    eapply doUpdRegs_UpdRegs; eauto.\n  Qed.\nEnd SimulationZeroAction.\n\nSection SimulationZeroAction_new.\n  Variable imp spec: BaseModuleWf_new type.\n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec ->\n                                          getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable simRelImpGood: forall oImp oSpec, simRel oImp oSpec ->\n                                             getKindAttr oImp = getKindAttr (getRegisters imp).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\\n                                               simRel rimp rspec.\n\n  Variable NoMeths: getMethods imp = [].\n  Variable NoMethsSpec: getMethods spec = [].\n\n  Variable simulation:\n    forall oImp rImp uImp rleImp csImp aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel (doUpdRegs uImp oImp) oSpec /\\ csImp = []) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n                 simRel (doUpdRegs uImp oImp) (doUpdRegs uSpec oSpec))).\n\n  Theorem simulationZeroAction_new :\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    destruct imp, spec.\n    pose (Build_BaseModuleWf (WfBaseModule_new_WfBaseModule wfBaseModule_new)) as x.\n    pose (Build_BaseModuleWf (WfBaseModule_new_WfBaseModule wfBaseModule_new0)) as y.\n    eapply (simulationZeroAction x y); eauto.\n  Qed.\n\nEnd SimulationZeroAction_new.\n\nLemma SemAction_if k1 k (e: Expr type (SyntaxKind Bool)) (a1 a2: ActionT type k1) (a: type k1 -> ActionT type k) o reads u cs v:\n  (if evalExpr e\n   then SemAction o (LetAction a1 a) reads u cs v\n   else SemAction o (LetAction a2 a) reads u cs v) ->\n  SemAction o (IfElse e a1 a2 a) reads u cs v.\nProof.\n  case_eq (evalExpr e); intros; inv H0; EqDep_subst.\n  - econstructor 7; eauto.\n  - econstructor 8; eauto.\nQed.\n\nLemma SemAction_if_split k1 k (e: Expr type (SyntaxKind Bool)) (a1 a2: ActionT type k1) (a: type k1 -> ActionT type k) o reads1 reads2 u1 u2 cs1 cs2 v1 v2 reads u cs v:\n  (if evalExpr e\n   then SemAction o (LetAction a1 a) reads1 u1 cs1 v1\n   else SemAction o (LetAction a2 a) reads2 u2 cs2 v2) ->\n  (reads = if evalExpr e then reads1 else reads2) ->\n  (u = if evalExpr e then u1 else u2) ->\n  (cs = if evalExpr e then cs1 else cs2) ->\n  (v = if evalExpr e then v1 else v2) ->\n  SemAction o (IfElse e a1 a2 a) reads u cs v.\nProof.\n  intros.\n  eapply SemAction_if.\n  destruct (evalExpr e); subst; auto.\nQed.\n\nLemma convertLetExprSyntax_ActionT_same o k (e: LetExprSyntax type k):\n  SemAction o (convertLetExprSyntax_ActionT e) nil nil nil (evalLetExpr e).\nProof.\n  induction e; simpl; try constructor; auto.\n  specialize (H (evalLetExpr e)).\n  pose proof (SemLetAction (fun v => convertLetExprSyntax_ActionT (cont v)) (@DisjKey_nil_l string _ nil) IHe H) as sth.\n  rewrite ?(app_nil_l nil) in sth.\n  auto.\n  eapply SemAction_if; eauto;\n  case_eq (evalExpr pred); intros; subst; repeat econstructor; eauto; unfold not; simpl; intros; auto.\nQed.\n\nLemma convertLetExprSyntax_ActionT_full k (e: LetExprSyntax type k):\n  forall o reads writes cs ret,\n    SemAction o (convertLetExprSyntax_ActionT e) reads writes cs ret ->\n    reads = nil /\\ writes = nil /\\ cs = nil /\\ ret = (evalLetExpr e).\nProof.\n  induction e; simpl; auto; intros; dest; subst.\n  - inv H; dest.\n    EqDep_subst.\n    repeat split; auto.\n  - inv H; dest.\n    EqDep_subst.\n    eapply IHe; eauto.\n  - inv H0.\n    EqDep_subst.\n    apply H in HSemActionCont; dest; subst.\n    apply IHe in HSemAction; dest; subst.\n    repeat split; auto.\n  - apply inversionSemAction in H0; dest.\n    destruct (evalExpr pred); dest.\n    + apply IHe1 in H1; dest; subst.\n      apply H in H2; dest; subst.\n      repeat split; auto.\n    + apply IHe2 in H1; dest; subst.\n      apply H in H2; dest; subst.\n      repeat split; auto.\nQed.\n\nSection Simulation.\n  Variable imp spec: BaseModule.\n  Variable impWf: WfBaseModule type imp.\n  Variable specWf: WfBaseModule type spec.\n  Variable NoSelfCalls: NoSelfCallBaseModule spec.\n  \n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable simRelImpGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oImp = getKindAttr (getRegisters imp).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\ simRel rimp rspec.\n\n  Variable simulationRule:\n    forall oImp rImp uImp rleImp csImp aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel (doUpdRegs uImp oImp) oSpec /\\ csImp = nil) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n                 simRel (doUpdRegs uImp oImp) (doUpdRegs uSpec oSpec))).\n\n  Variable simulationMeth:\n    forall oImp rImp uImp meth csImp sign aImp arg ret,\n      In (meth, existT _ sign aImp) (getMethods imp) ->\n      SemAction oImp (aImp type arg) rImp uImp csImp ret ->\n      forall oSpec,\n        simRel oImp oSpec ->\n          exists aSpec rSpec uSpec,\n            In (meth, existT _ sign aSpec) (getMethods spec) /\\\n            SemAction oSpec (aSpec type arg) rSpec uSpec csImp ret /\\\n                simRel (doUpdRegs uImp oImp) (doUpdRegs uSpec oSpec).\n\n  Variable notMethMeth:\n    forall oImp rImpl1 uImpl1 meth1 sign1 aImp1 arg1 ret1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (meth1, existT _ sign1 aImp1) (getMethods imp) ->\n      SemAction oImp (aImp1 type arg1) rImpl1 uImpl1 csImp1 ret1 ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n          \n  Variable notRuleMeth:\n    forall oImp rImpl1 uImpl1 rleImpl1 aImp1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (rleImpl1, aImp1) (getRules imp) ->\n      SemAction oImp (aImp1 type) rImpl1 uImpl1 csImp1 WO ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n\n  Theorem simulation:\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    remember {| baseModule := imp ;\n                wfBaseModule := impWf |} as impMod.\n    remember {| baseModule := spec ;\n                wfBaseModule := specWf |} as specMod.\n    assert (Imp: imp = baseModule impMod) by (rewrite HeqimpMod; auto).\n    assert (Spec: spec = baseModule specMod) by (rewrite HeqspecMod; auto).\n    rewrite Imp, Spec in *.\n    eapply simulationGeneral; eauto; intros.\n  Qed.\nEnd Simulation.\n\nSection Simulation_new.\n  Variable imp spec: BaseModule.\n  Variable impWf: WfBaseModule_new type imp.\n  Variable specWf: WfBaseModule_new type spec.\n  Variable NoSelfCalls: NoSelfCallBaseModule spec.\n  \n  Variable simRel: RegsT -> RegsT -> Prop.\n  Variable simRelGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oSpec = getKindAttr (getRegisters spec).\n  Variable simRelImpGood: forall oImp oSpec, simRel oImp oSpec -> getKindAttr oImp = getKindAttr (getRegisters imp).\n  Variable initRel: forall rimp, Forall2 regInit rimp (getRegisters imp) ->\n                                 exists rspec, Forall2 regInit rspec (getRegisters spec) /\\ simRel rimp rspec.\n\n  Variable simulationRule:\n    forall oImp rImp uImp rleImp csImp aImp,\n      In (rleImp, aImp) (getRules imp) ->\n      SemAction oImp (aImp type) rImp uImp csImp WO ->\n      forall oSpec,\n        simRel oImp oSpec ->\n        ((simRel (doUpdRegs uImp oImp) oSpec /\\ csImp = nil) \\/\n         (exists rleSpec aSpec,\n             In (rleSpec, aSpec) (getRules spec) /\\\n             exists rSpec uSpec,\n               SemAction oSpec (aSpec type) rSpec uSpec csImp WO /\\\n                 simRel (doUpdRegs uImp oImp) (doUpdRegs uSpec oSpec))).\n\n  Variable simulationMeth:\n    forall oImp rImp uImp meth csImp sign aImp arg ret,\n      In (meth, existT _ sign aImp) (getMethods imp) ->\n      SemAction oImp (aImp type arg) rImp uImp csImp ret ->\n      forall oSpec,\n        simRel oImp oSpec ->\n          exists aSpec rSpec uSpec,\n            In (meth, existT _ sign aSpec) (getMethods spec) /\\\n            SemAction oSpec (aSpec type arg) rSpec uSpec csImp ret /\\\n                simRel (doUpdRegs uImp oImp) (doUpdRegs uSpec oSpec).\n\n  Variable notMethMeth:\n    forall oImp rImpl1 uImpl1 meth1 sign1 aImp1 arg1 ret1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (meth1, existT _ sign1 aImp1) (getMethods imp) ->\n      SemAction oImp (aImp1 type arg1) rImpl1 uImpl1 csImp1 ret1 ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n          \n  Variable notRuleMeth:\n    forall oImp rImpl1 uImpl1 rleImpl1 aImp1 csImp1\n           rImpl2 uImpl2 meth2 sign2 aImp2 arg2 ret2 csImp2,\n      In (rleImpl1, aImp1) (getRules imp) ->\n      SemAction oImp (aImp1 type) rImpl1 uImpl1 csImp1 WO ->\n      In (meth2, existT _ sign2 aImp2) (getMethods imp) ->\n      SemAction oImp (aImp2 type arg2) rImpl2 uImpl2 csImp2 ret2 ->\n      exists k, In k (map fst uImpl1) /\\ In k (map fst uImpl2).\n\n  Theorem simulation_new :\n    TraceInclusion (Base imp) (Base spec).\n  Proof.\n    eapply simulation; eauto.\n    - apply WfBaseModule_new_WfBaseModule; auto.\n    - apply WfBaseModule_new_WfBaseModule; auto.\n  Qed.\n\nEnd Simulation_new.\n\nLemma evalExpr_Kor_Default k (e : Expr type (SyntaxKind k)):\n  evalKorOpBin k (evalExpr e) (evalConstT (getDefaultConst k)) = (evalExpr e).\nProof.\n  induction k; simpl.\n  - rewrite orb_false_r; reflexivity.\n  - rewrite wzero_wor; reflexivity.\n  - apply functional_extensionality_dep; intros.\n    apply (H x (Var _ (SyntaxKind (k x)) (evalExpr e x))).\n  - simpl.\n    apply functional_extensionality_dep; intros.\n    apply (IHk (Var _ (SyntaxKind k) (evalExpr e x))).\nQed.\n\nLemma evalExpr_Kor_comm k (e1 e2 : Expr type (SyntaxKind k)):\n  evalKorOpBin k (evalExpr e1) (evalExpr e2) = evalKorOpBin k (evalExpr e2) (evalExpr e1).\nProof.\n  induction k; simpl.\n  - apply orb_comm.\n  - apply wor_comm.\n  - apply functional_extensionality_dep; intros.\n    apply (H x (Var _ (SyntaxKind (k x)) (evalExpr e1 x))\n             (Var _ (SyntaxKind (k x)) (evalExpr e2 x))).\n  - apply functional_extensionality_dep; intros.\n    apply (IHk (Var _ (SyntaxKind k) (evalExpr e1 x))\n               (Var _ (SyntaxKind k) (evalExpr e2 x))).\nQed.\n\nLemma evalExpr_Kor_idemp k (e1 : Expr type (SyntaxKind k)):\n  evalKorOpBin k (evalExpr e1) (evalExpr e1) = (evalExpr e1).\nProof.\n  induction k; simpl.\n  - apply orb_diag.\n  - apply wor_idemp.\n  - apply functional_extensionality_dep; intros.\n    apply (H x (Var _ (SyntaxKind (k x)) (evalExpr e1 x))).\n  - apply functional_extensionality_dep; intros.\n    apply (IHk (Var _ (SyntaxKind k) (evalExpr e1 x))).\nQed.\n\nLocal Lemma Kor_default_rev k (l : list (Expr type (SyntaxKind k))):\n  (forall a,\n    In a (rev l) ->\n    a = Const type Default) ->\n    evalExpr (@Kor _ k (rev l)) = evalExpr (Const type Default).\nProof.\n  cbn [evalExpr].\n  unfold evalKorOp.\n  rewrite <- fold_left_rev_right, map_rev, rev_involutive.\n  induction l; intros; simpl in *; subst; auto.\n  rewrite IHl.\n  - rewrite (H _ (in_or_app _ _ _ (or_intror _ (InSingleton _)))); simpl.\n    assert (evalConstT Default = (evalExpr (@Const type k Default))) as P by reflexivity.\n    repeat rewrite P.\n    apply evalExpr_Kor_idemp.\n  - intros; apply H; rewrite in_app_iff; left; assumption.\nQed.\n\nLocal Lemma Kor_default_rev' k (l : list (Expr type (SyntaxKind k))):\n  (forall a,\n    In (evalExpr a) (map (fun x => evalExpr x) (rev l)) ->\n    (evalExpr a) = (evalExpr (Const type Default))) ->\n    evalExpr (@Kor _ k (rev l)) = evalExpr (Const type Default).\nProof.\n  cbn [evalExpr].\n  unfold evalKorOp.\n  repeat rewrite map_rev.\n  rewrite <- fold_left_rev_right, rev_involutive.\n  induction l; intros; simpl in *; subst; auto.\n  rewrite IHl.\n  - rewrite (H _ (in_or_app _ _ _ (or_intror _ (InSingleton _)))); simpl.\n    assert (evalConstT Default = (evalExpr (@Const type k Default))) as P by reflexivity.\n    repeat rewrite P.\n    apply evalExpr_Kor_idemp.\n  - intros; apply H; rewrite in_app_iff; left; assumption.\nQed.\n\nLemma Kor_default k (l : list (Expr type (SyntaxKind k))):\n  (forall a,\n      In a l ->\n      a = Const type Default) ->\n  evalExpr (@Kor _ k l) = evalExpr (Const type Default).\nProof.\n  setoid_rewrite <- rev_involutive.\n  apply Kor_default_rev.\nQed.\n\nLemma Kor_default' k (l : list (Expr type (SyntaxKind k))):\n  (forall a,\n      In (evalExpr a) (map (fun x => evalExpr x) l) ->\n      (evalExpr a) = (evalExpr (Const type Default))) ->\n  evalExpr (@Kor _ k l) = evalExpr (Const type Default).\nProof.\n  setoid_rewrite <- (rev_involutive l).\n  apply Kor_default_rev'.\nQed.\n  \nLocal Lemma Kor_sparse_rev k (l : list (Expr type (SyntaxKind k))):\n  forall (val : Expr type (SyntaxKind k)),\n    In (evalExpr val) (map (fun x => evalExpr x) (rev l)) ->\n    (forall a,\n        In (evalExpr a) (map (fun x => evalExpr x) (rev l)) ->\n        (evalExpr a) = (evalExpr val) \\/ (evalExpr a) = (evalExpr (Const type Default))) ->\n    evalExpr (@Kor _ k (rev l)) =  evalExpr val.\nProof.\n  intros.\n  cbn [evalExpr].\n  unfold evalKorOp.\n  rewrite <- fold_left_rev_right, map_rev, rev_involutive.\n  induction l; intros; simpl in *; dest; subst; [contradiction|rewrite map_app in *].\n  rewrite in_app_iff in H; destruct H.\n  - rewrite IHl; auto.\n    + destruct (H0 _ (in_or_app _ _ _ (or_intror _ (InSingleton _)))); rewrite H1.\n      * apply evalExpr_Kor_idemp.\n      * apply evalExpr_Kor_Default.\n    + intros.\n      apply H0; rewrite in_app_iff; left; assumption.\n  - inv H; [|contradiction].\n    destruct (In_dec (isEq k) (evalExpr val) (map (fun x => evalExpr x) (rev l))).\n    + rewrite IHl, H1; auto.\n      * apply evalExpr_Kor_idemp.\n      * intros.\n        apply H0; rewrite in_app_iff; left; assumption.\n    + assert (forall a, In (evalExpr a) (map (fun x => evalExpr x) (rev l))\n                                         -> (evalExpr a) = (evalExpr (Const type Default))) as P.\n      { intros.\n        destruct (H0 _ (in_or_app _ _ _ (or_introl _ H))); subst; auto.\n        rewrite H2 in H.\n        exfalso; contradiction.\n      }\n      specialize (Kor_default_rev' l) as P0.\n      cbn [evalExpr] in P0.\n      unfold evalKorOp in P0.\n      repeat rewrite map_rev in P0.\n      rewrite <- fold_left_rev_right, rev_involutive in P0.\n      setoid_rewrite P0; [|rewrite <-map_rev; auto].\n      rewrite H1.\n      assert (@evalConstT k Default = evalExpr (Const type Default)) as P1 by reflexivity.\n      rewrite P1, evalExpr_Kor_comm.\n      apply evalExpr_Kor_Default.\nQed.\n\nLemma Kor_sparse k (l : list (Expr type (SyntaxKind k))):\n  forall val,\n    In (evalExpr val) (map (fun x => evalExpr x) l) ->\n    (forall a,\n        In (evalExpr a) (map (fun x => evalExpr x) l) ->\n        (evalExpr a) = (evalExpr val) \\/ (evalExpr a) = (evalExpr (Const type Default))) ->\n    evalExpr (@Kor _ k l) =  evalExpr val.\nProof.\n  setoid_rewrite <- (rev_involutive l).\n  apply Kor_sparse_rev.\nQed.\n\nLemma evalExpr_Kor_Default_l k (e : Expr type (SyntaxKind k)):\n  evalKorOpBin k (evalConstT Default) (evalExpr e) = evalExpr e.\nProof.\n  assert (@evalConstT k Default = evalExpr (Const type Default)) as P by reflexivity.\n  rewrite P, evalExpr_Kor_comm.\n  apply evalExpr_Kor_Default.\nQed.\n\nLemma evalExpr_Kor_assoc k (e1 e2 e3 : Expr type (SyntaxKind k)):\n  evalKorOpBin k (evalExpr e1) (evalKorOpBin k (evalExpr e2) (evalExpr e3)) =\n  evalKorOpBin k (evalKorOpBin k (evalExpr e1) (evalExpr e2)) (evalExpr e3).\nProof.\n  induction k; simpl.\n  - apply orb_assoc.\n  - apply wor_assoc.\n  - apply functional_extensionality_dep; intros.\n    apply (H _ (Var _ (SyntaxKind (k x)) (evalExpr e1 x))\n             (Var _ (SyntaxKind (k x)) (evalExpr e2 x))\n             (Var _ (SyntaxKind (k x)) (evalExpr e3 x))).\n  - apply functional_extensionality_dep; intros.\n    apply (IHk (Var _ (SyntaxKind k) (evalExpr e1 x))\n             (Var _ (SyntaxKind k) (evalExpr e2 x))\n             (Var _ (SyntaxKind k) (evalExpr e3 x))).\nQed.\n\nLocal Lemma evalExpr_Kor_perm_rev k (l : list (Expr type (SyntaxKind k))) :\n  forall l',\n    l [=] l' ->\n    evalExpr (Kor (rev l)) = evalExpr (Kor (rev l')).\nProof.\n  induction 1; auto.\n  - cbn [evalExpr] in *.\n    unfold evalKorOp in *.\n    repeat rewrite <- fold_left_rev_right, map_rev, rev_involutive in *.\n    simpl.\n    setoid_rewrite IHPermutation.\n    reflexivity.\n  - cbn [evalExpr].\n    unfold evalKorOp.\n    repeat rewrite <- fold_left_rev_right, map_rev, rev_involutive.\n    simpl.\n    assert (evalExpr (Var _ (SyntaxKind k)\n                          (fold_right (fun y0 x0 => evalKorOpBin k x0 y0) (evalConstT Default)\n                                      (map (evalExpr (exprT:=SyntaxKind k)) l))) =\n            (fold_right (fun y0 x0 => evalKorOpBin k x0 y0) (evalConstT Default)\n                        (map (evalExpr (exprT:=SyntaxKind k)) l))) as P by reflexivity.\n    setoid_rewrite <- P.\n    rewrite <- evalExpr_Kor_assoc, evalExpr_Kor_comm, evalExpr_Kor_assoc; reflexivity.\n  - rewrite IHPermutation1, IHPermutation2; reflexivity.\nQed.\n\nLemma evalExpr_Kor_perm k (l : list (Expr type (SyntaxKind k))) :\n  forall l',\n    l [=] l' ->\n    evalExpr (Kor l) = evalExpr (Kor l').\nProof.\n  intros.\n  rewrite (Permutation.Permutation_rev l), (Permutation.Permutation_rev l')  in H.\n  rewrite <- (rev_involutive l),  <- (rev_involutive l').\n  apply evalExpr_Kor_perm_rev; assumption.\nQed.\n\nLemma evalExpr_Kor_head k (e : Expr type (SyntaxKind k)) (l : list (Expr type (SyntaxKind k))):\n  evalExpr (Kor (e :: l)) = evalKorOpBin k (evalExpr e) (evalExpr (Kor l)).\nProof.\n  rewrite (evalExpr_Kor_perm (Permutation.Permutation_rev (e :: l))),\n  (evalExpr_Kor_perm (Permutation.Permutation_rev l)) at 1.\n  cbn [evalExpr].\n  unfold evalKorOp.\n  repeat rewrite <- fold_left_rev_right, map_rev, rev_involutive.\n  simpl.\n  assert ((fold_right (fun y x : type k => evalKorOpBin k x y) (evalConstT Default)\n                      (map (evalExpr (exprT:=SyntaxKind k)) l)) =\n          evalExpr (Var _ (SyntaxKind k)\n                        (fold_right (fun y x : type k => evalKorOpBin k x y) (evalConstT Default)\n                                    (map (evalExpr (exprT:=SyntaxKind k)) l)))) as P\n      by reflexivity.\n  setoid_rewrite P.\n  rewrite evalExpr_Kor_comm; reflexivity.\nQed.\n\nLemma arr_nth_Fin' {A : Type} :\n  forall m (arr : t m -> A),\n    arr = (nth_Fin' _ (list_arr_length arr)).\nProof.\n  intros.\n  apply functional_extensionality; intros.\n  rewrite (nth_Fin'_nth (arr x)).\n  rewrite <- nth_default_eq, <- list_arr_correct.\n  destruct lt_dec.\n  - specialize (of_nat_to_nat_inv x) as P.\n    rewrite (of_nat_ext l (proj2_sig (to_nat x))), P; reflexivity.\n  - exfalso.\n    apply n, fin_to_nat_bound.\nQed.\n\nLemma evalExpr_Kor_same_eval (k : Kind) (l l' : list (Expr type (SyntaxKind k))) :\n  Forall2 (fun x y => evalExpr x = evalExpr y) l l' ->\n  evalExpr (Kor l) = evalExpr (Kor l').\nProof.\n  induction 1; auto.\n  repeat rewrite evalExpr_Kor_head.\n  rewrite H, IHForall2; reflexivity.\nQed.\n\nLemma split_seq :\n  forall start i size,\n    i < size ->\n    seq start size = (seq start i) ++ [start + i] ++ (seq (start + (S i)) (size - (S i))).\nProof.\n  intros.\n  rewrite (@seq_app' start size i), (@seq_app' (start + i) (size - i) 1); try lia.\n  cbn.\n  assert (size - i - 1 = size - S i) as P by lia.\n  rewrite Nat.add_1_r, plus_n_Sm, P; reflexivity.\nQed.\n", "meta": {"author": "sifive", "repo": "Kami", "sha": "ffb77238f27b603dbd42d2622ba911740bf5eadf", "save_path": "github-repos/coq/sifive-Kami", "path": "github-repos/coq/sifive-Kami/Kami-ffb77238f27b603dbd42d2622ba911740bf5eadf/Properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.22335456563896655}}
{"text": "(** * Push-Button Synthesis of Saturated Solinas *)\nRequire Import Coq.Strings.String.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.MSets.MSetPositive.\nRequire Import Coq.Lists.List.\nRequire Import Coq.QArith.QArith_base Coq.QArith.Qround.\nRequire Import Coq.derive.Derive.\nRequire Import Crypto.Util.ErrorT.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.ListUtil.FoldBool.\nRequire Import Crypto.Util.Strings.Decimal.\nRequire Import Crypto.Util.Strings.Show.\nRequire Import Crypto.Util.ZRange.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Zselect.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.Tactics.HasBody.\nRequire Import Crypto.Util.Tactics.Head.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Rewriter.Language.Wf.\nRequire Import Rewriter.Language.Language.\nRequire Import Crypto.Language.API.\nRequire Import Crypto.AbstractInterpretation.AbstractInterpretation.\nRequire Import Crypto.Stringification.Language.\nRequire Import Crypto.Arithmetic.Core.\nRequire Import Crypto.Arithmetic.ModOps.\nRequire Import Crypto.Arithmetic.Saturated.\nRequire Import Crypto.BoundsPipeline.\nRequire Import Crypto.COperationSpecifications.\nRequire Import Crypto.PushButtonSynthesis.ReificationCache.\nRequire Import Crypto.PushButtonSynthesis.Primitives.\nRequire Import Crypto.PushButtonSynthesis.SaturatedSolinasReificationCache.\nRequire Import Crypto.Assembly.Equivalence.\nImport ListNotations.\nLocal Open Scope Z_scope. Local Open Scope list_scope. Local Open Scope bool_scope.\n\nImport\n  Language.Wf.Compilers\n  Language.Compilers\n  AbstractInterpretation.Compilers\n  Stringification.Language.Compilers.\nImport Compilers.API.\n\nImport COperationSpecifications.Primitives.\nImport COperationSpecifications.Solinas.\nImport COperationSpecifications.SaturatedSolinas.\n\nImport Associational Positional.\n\nLocal Coercion Z.of_nat : nat >-> Z.\nLocal Coercion QArith_base.inject_Z : Z >-> Q.\nLocal Coercion Z.pos : positive >-> Z.\n\nLocal Set Keyed Unification. (* needed for making [autorewrite] fast, c.f. COQBUG(https://github.com/coq/coq/issues/9283) *)\n\nLocal Opaque reified_mul_gen. (* needed for making [autorewrite] not take a very long time *)\n(* needed for making [autorewrite] with [Set Keyed Unification] fast *)\nLocal Opaque expr.Interp.\n\nSection __.\n  Context {output_language_api : ToString.OutputLanguageAPI}\n          {language_naming_conventions : language_naming_conventions_opt}\n          {package_namev : package_name_opt}\n          {class_namev : class_name_opt}\n          {static : static_opt}\n          {internal_static : internal_static_opt}\n          {low_level_rewriter_method : low_level_rewriter_method_opt}\n          {only_signed : only_signed_opt}\n          {no_select : no_select_opt}\n          {use_mul_for_cmovznz : use_mul_for_cmovznz_opt}\n          {emit_primitives : emit_primitives_opt}\n          {should_split_mul : should_split_mul_opt}\n          {should_split_multiret : should_split_multiret_opt}\n          {unfold_value_barrier : unfold_value_barrier_opt}\n          {assembly_hints_lines : assembly_hints_lines_opt}\n          {widen_carry : widen_carry_opt}\n          (widen_bytes : widen_bytes_opt := true) (* true, because we don't allow byte-sized things anyway, so we should not expect carries to be widened to byte-size when emitting C code *)\n          {assembly_calling_registers : assembly_calling_registers_opt}\n          {assembly_stack_size : assembly_stack_size_opt}\n          {error_on_unused_assembly_functions : error_on_unused_assembly_functions_opt}\n          {assembly_output_first : assembly_output_first_opt}\n          {assembly_argument_registers_left_to_right : assembly_argument_registers_left_to_right_opt}\n          (s : Z)\n          (c : list (Z * Z))\n          (machine_wordsize : Z).\n\n  Local Existing Instance widen_bytes.\n\n  (* We include [0], so that even after bounds relaxation, we can\n       notice where the constant 0s are, and remove them. *)\n  Definition possible_values_of_machine_wordsize\n    := prefix_with_carry [machine_wordsize].\n\n  Definition n : nat := Z.to_nat (Qceiling (Z.log2_up s / machine_wordsize)).\n  Definition m := s - Associational.eval c.\n  (* Number of reductions is calculated as follows :\n         Let i be the highest limb index of c. Then, each reduction\n         decreases the number of extra limbs by (n-i-1). (The -1 comes\n         from possibly having an extra high partial product at the end\n         of a reduction.) So, to go from the n extra limbs we have\n         post-multiplication down to 0, we need ceil (n / (n - i - 1))\n         reductions.  In some cases. however, [n - i <= 1], and in\n         this case, we do [n] reductions (is this enough?). *)\n  Definition nreductions : nat :=\n    let i := fold_right Z.max 0 (map (fun t => Z.log2 (fst t) / machine_wordsize) c) in\n    if Z.of_nat n - i <=? 1\n    then n\n    else Z.to_nat (Qceiling (Z.of_nat n / (Z.of_nat n - i - 1))).\n  Let possible_values := possible_values_of_machine_wordsize.\n  Definition bound := Some r[0 ~> (2^machine_wordsize - 1)]%zrange.\n  Definition boundsn : list (ZRange.type.option.interp base.type.Z)\n    := repeat bound n.\n\n  Local Instance no_select_size : no_select_size_opt := no_select_size_of_no_select machine_wordsize.\n  Local Instance split_mul_to : split_mul_to_opt := split_mul_to_of_should_split_mul machine_wordsize possible_values.\n  Local Instance split_multiret_to : split_multiret_to_opt := split_multiret_to_of_should_split_multiret machine_wordsize possible_values.\n\n  (** Note: If you change the name or type signature of this\n        function, you will need to update the code in CLI.v *)\n  Definition check_args {T} (res : Pipeline.ErrorT T)\n    : Pipeline.ErrorT T\n    := fold_right\n         (fun '(b, e) k => if b:bool then Error e else k)\n         res\n         [((negb (0 <? s - Associational.eval c))%Z, Pipeline.Value_not_ltZ \"s - Associational.eval c ≤ 0\" 0 (s - Associational.eval c));\n            ((s =? 0)%Z, Pipeline.Values_not_provably_distinctZ \"s ≠ 0\" s 0);\n            ((n =? 0)%nat, Pipeline.Values_not_provably_distinctZ \"n ≠ 0\" n 0);\n            ((negb (0 <? machine_wordsize)), Pipeline.Value_not_ltZ \"0 < machine_wordsize\" 0 machine_wordsize)].\n\n  Local Ltac prepare_use_curve_good _ :=\n    let curve_good := lazymatch goal with | curve_good : check_args _ = Success _ |- _ => curve_good end in\n    clear -curve_good;\n    cbv [check_args] in curve_good |- *;\n    cbn [fold_right] in curve_good |- *;\n    repeat first [ match goal with\n                   | [ H : context[match ?b with true => _ | false => _ end ] |- _ ] => destruct b eqn:?\n                   end\n                 | discriminate\n                 | progress Reflect.reflect_hyps\n                 | assumption\n                 | apply conj\n                 | progress destruct_head'_and ].\n\n  Local Ltac use_curve_good_t :=\n    repeat first [ assumption\n                 | progress rewrite ?map_length, ?Z.mul_0_r, ?Pos.mul_1_r, ?Z.mul_1_r in *\n                 | reflexivity\n                 | lia\n                 | rewrite expr.interp_reify_list, ?map_map\n                 | rewrite map_ext with (g:=id), map_id\n                 | progress distr_length\n                 | progress cbv [Qceiling Qfloor Qopp Qdiv Qplus inject_Z Qmult Qinv] in *\n                 | progress cbv [Qle] in *\n                 | progress cbn -[reify_list] in *\n                 | progress intros\n                 | solve [ auto ] ].\n\n  Context (curve_good : check_args (Success tt) = Success tt).\n\n  Lemma use_curve_good\n    : 0 < s - Associational.eval c\n      /\\ s - Associational.eval c <> 0\n      /\\ s <> 0\n      /\\ 0 < machine_wordsize\n      /\\ n <> 0%nat.\n  Proof using curve_good.\n    prepare_use_curve_good ().\n    { use_curve_good_t. }\n  Qed.\n\n  Local Notation weightf := (weight machine_wordsize 1).\n  Local Notation evalf := (eval weightf n).\n  Local Notation notations_for_docstring\n    := (CorrectnessStringification.dyn_context.cons\n          weightf \"weight\"\n          (CorrectnessStringification.dyn_context.cons\n             evalf \"eval\"\n             CorrectnessStringification.dyn_context.nil))%string.\n  Local Notation \"'docstring_with_summary_from_lemma!' summary correctness\"\n    := (docstring_with_summary_from_lemma_with_ctx!\n          notations_for_docstring\n          summary\n          correctness)\n         (only parsing, at level 10, summary at next level, correctness at next level).\n\n  Definition mul\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         None (* fancy *)\n         possible_values\n         (reified_mul_gen\n            @ GallinaReify.Reify s @ GallinaReify.Reify c @ GallinaReify.Reify machine_wordsize @ GallinaReify.Reify n @ GallinaReify.Reify nreductions)\n         (Some boundsn, (Some boundsn, tt))\n         (Some boundsn, None (* Should be: Some r[0~>0]%zrange, but bounds analysis is not good enough *) ).\n\n  Definition smul (prefix : string)\n    : string * (Pipeline.ErrorT (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString\n          machine_wordsize prefix \"mul\" mul\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [\"The function \" ++ fname ++ \" multiplies two field elements.\"]%string)\n             (mul_correct weightf n m boundsn)).\n\n  Local Ltac solve_extra_bounds_side_conditions :=\n    cbn [lower upper fst snd] in *; Bool.split_andb; Z.ltb_to_lt; lia.\n\n  Hint Rewrite\n       (fun pf => @Rows.eval_mulmod (weight machine_wordsize 1) (@wprops _ _ pf))\n       using solve [ auto with zarith | congruence | solve_extra_bounds_side_conditions ] : push_eval.\n  Hint Unfold mulmod : push_eval.\n\n  Local Ltac prove_correctness _ := Primitives.prove_correctness use_curve_good.\n\n  Lemma mul_correct res\n        (Hres : mul = Success res)\n    : mul_correct (weight machine_wordsize 1) n m boundsn (Interp res).\n  Proof using curve_good. prove_correctness (). Qed.\n\n  Lemma Wf_mul res (Hres : mul = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Section for_stringification.\n    Local Open Scope string_scope.\n    Local Open Scope list_scope.\n\n    Definition known_functions\n      := [(\"mul\", wrap_s smul)].\n\n    Definition valid_names : string := Eval compute in String.concat \", \" (List.map (@fst _ _) known_functions).\n\n    (** Note: If you change the name or type signature of this\n          function, you will need to update the code in CLI.v *)\n    Definition Synthesize (comment_header : list string) (function_name_prefix : string) (requests : list string)\n      : list (synthesis_output_kind * string * Pipeline.ErrorT (list string))\n      := Primitives.Synthesize\n           machine_wordsize valid_names known_functions (fun _ => nil)\n           check_args\n           ((ToString.comment_file_header_block\n               (comment_header\n                  ++ [\"\";\n                     \"Computed values:\";\n                     \"# reductions = \" ++ show false nreductions]%string)))\n           function_name_prefix requests.\n  End for_stringification.\nEnd __.\n\nModule Export Hints.\n  Hint Opaque\n       mul\n  : wf_op_cache.\n  Hint Immediate\n       Wf_mul\n  : wf_op_cache.\nEnd Hints.\n", "meta": {"author": "dip-proto", "repo": "fiat-crypto", "sha": "fc3a9280c51f413943c167cc9292e953b8e42c02", "save_path": "github-repos/coq/dip-proto-fiat-crypto", "path": "github-repos/coq/dip-proto-fiat-crypto/fiat-crypto-fc3a9280c51f413943c167cc9292e953b8e42c02/src/PushButtonSynthesis/SaturatedSolinas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.22325795871853465}}
{"text": "Require Import Syntax TypeAlgo.\n\nTheorem algo_values_all_effect:\n    forall C v T D G max_rho max_X max_rho' max_X',\n        welltyped_algo G max_rho max_X (e_Thread (t_Value v)) T (EffectIntro D D) C max_rho' max_X' ->\n        forall D',\n        welltyped_algo G max_rho max_X (e_Thread (t_Value v)) T (EffectIntro D' D') C max_rho' max_X'.\nProof.\n\n\n", "meta": {"author": "peterbb", "repo": "formal-dlraces", "sha": "dcf9c579b861ab848a4044a47616e758262564bf", "save_path": "github-repos/coq/peterbb-formal-dlraces", "path": "github-repos/coq/peterbb-formal-dlraces/formal-dlraces-dcf9c579b861ab848a4044a47616e758262564bf/coq/Theorem_algo_values_all_effect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2232256316745443}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import gset coPset.\nFrom iris.base_logic.lib Require Export invariants.\nFrom iris Require Import options.\nImport uPred.\n\n(* Non-atomic (\"thread-local\") invariants. *)\n\nDefinition na_inv_pool_name := gname.\n\nClass na_invG Σ :=\n  na_inv_inG :> inG Σ (prodR coPset_disjR (gset_disjR positive)).\nDefinition na_invΣ : gFunctors :=\n  #[ GFunctor (constRF (prodR coPset_disjR (gset_disjR positive))) ].\nInstance subG_na_invG {Σ} : subG na_invΣ Σ → na_invG Σ.\nProof. solve_inG. Qed.\n\nSection defs.\n  Context `{!invG Σ, !na_invG Σ}.\n\n  Definition na_own (p : na_inv_pool_name) (E : coPset) : iProp Σ :=\n    own p (CoPset E, GSet ∅).\n\n  Definition na_inv (p : na_inv_pool_name) (N : namespace) (P : iProp Σ) : iProp Σ :=\n    (∃ i, ⌜i ∈ (↑N:coPset)⌝ ∧\n          inv N (P ∗ own p (CoPset ∅, GSet {[i]}) ∨ na_own p {[i]}))%I.\nEnd defs.\n\nInstance: Params (@na_inv) 3 := {}.\nTypeclasses Opaque na_own na_inv.\n\nSection proofs.\n  Context `{!invG Σ, !na_invG Σ}.\n\n  Global Instance na_own_timeless p E : Timeless (na_own p E).\n  Proof. rewrite /na_own; apply _. Qed.\n\n  Global Instance na_inv_ne p N : NonExpansive (na_inv p N).\n  Proof. rewrite /na_inv. solve_proper. Qed.\n  Global Instance na_inv_proper p N : Proper ((≡) ==> (≡)) (na_inv p N).\n  Proof. apply (ne_proper _). Qed.\n\n  Global Instance na_inv_persistent p N P : Persistent (na_inv p N P).\n  Proof. rewrite /na_inv; apply _. Qed.\n\n  Lemma na_inv_iff p N P Q : na_inv p N P -∗ ▷ □ (P ↔ Q) -∗ na_inv p N Q.\n  Proof.\n    iIntros \"HI #HPQ\". rewrite /na_inv. iDestruct \"HI\" as (i ?) \"HI\".\n    iExists i. iSplit; first done. iApply (inv_iff with \"HI\").\n    iIntros \"!> !>\".\n    iSplit; iIntros \"[[? Ho]|$]\"; iLeft; iFrame \"Ho\"; by iApply \"HPQ\".\n  Qed.\n\n  Lemma na_alloc : ⊢ |==> ∃ p, na_own p ⊤.\n  Proof. by apply own_alloc. Qed.\n\n  Lemma na_own_disjoint p E1 E2 : na_own p E1 -∗ na_own p E2 -∗ ⌜E1 ## E2⌝.\n  Proof.\n    apply wand_intro_r.\n    rewrite /na_own -own_op own_valid -coPset_disj_valid_op. by iIntros ([? _]).\n  Qed.\n\n  Lemma na_own_union p E1 E2 :\n    E1 ## E2 → na_own p (E1 ∪ E2) ⊣⊢ na_own p E1 ∗ na_own p E2.\n  Proof.\n    intros ?. by rewrite /na_own -own_op -pair_op left_id coPset_disj_union.\n  Qed.\n\n  Lemma na_own_acc E2 E1 tid :\n    E2 ⊆ E1 → na_own tid E1 -∗ na_own tid E2 ∗ (na_own tid E2 -∗ na_own tid E1).\n  Proof.\n    intros HF. assert (E1 = E2 ∪ (E1 ∖ E2)) as -> by exact: union_difference_L.\n    rewrite na_own_union; last by set_solver+. iIntros \"[$ $]\". auto.\n  Qed.\n\n  Lemma na_inv_alloc p E N P : ▷ P ={E}=∗ na_inv p N P.\n  Proof.\n    iIntros \"HP\".\n    iMod (own_unit (prodUR coPset_disjUR (gset_disjUR positive)) p) as \"Hempty\".\n    iMod (own_updateP with \"Hempty\") as ([m1 m2]) \"[Hm Hown]\".\n    { apply prod_updateP'. apply cmra_updateP_id, (reflexivity (R:=eq)).\n      apply (gset_disj_alloc_empty_updateP_strong' (λ i, i ∈ (↑N:coPset))).\n      intros Ef. exists (coPpick (↑ N ∖ gset_to_coPset Ef)).\n      rewrite -elem_of_gset_to_coPset comm -elem_of_difference.\n      apply coPpick_elem_of=> Hfin.\n      eapply nclose_infinite, (difference_finite_inv _ _), Hfin.\n      apply gset_to_coPset_finite. }\n    simpl. iDestruct \"Hm\" as %(<- & i & -> & ?).\n    rewrite /na_inv.\n    iMod (inv_alloc N with \"[-]\"); last (iModIntro; iExists i; eauto).\n    iNext. iLeft. by iFrame.\n  Qed.\n\n  Lemma na_inv_acc p E F N P :\n    ↑N ⊆ E → ↑N ⊆ F →\n    na_inv p N P -∗ na_own p F ={E}=∗ ▷ P ∗ na_own p (F∖↑N) ∗\n                       (▷ P ∗ na_own p (F∖↑N) ={E}=∗ na_own p F).\n  Proof.\n    rewrite /na_inv. iIntros (??) \"#Hnainv Htoks\".\n    iDestruct \"Hnainv\" as (i) \"[% Hinv]\".\n    rewrite [F as X in na_own p X](union_difference_L (↑N) F) //.\n    rewrite [X in (X ∪ _)](union_difference_L {[i]} (↑N)) ?na_own_union; [|set_solver..].\n    iDestruct \"Htoks\" as \"[[Htoki $] $]\".\n    iInv \"Hinv\" as \"[[$ >Hdis]|>Htoki2]\" \"Hclose\".\n    - iMod (\"Hclose\" with \"[Htoki]\") as \"_\"; first auto.\n      iIntros \"!> [HP $]\".\n      iInv N as \"[[_ >Hdis2]|>Hitok]\".\n      + iDestruct (own_valid_2 with \"Hdis Hdis2\") as %[_ Hval%gset_disj_valid_op].\n        set_solver.\n      + iSplitR \"Hitok\"; last by iFrame. eauto with iFrame.\n    - iDestruct (na_own_disjoint with \"Htoki Htoki2\") as %?. set_solver.\n  Qed.\n\n  Global Instance into_inv_na p N P : IntoInv (na_inv p N P) N := {}.\n\n  Global Instance into_acc_na p F E N P :\n    IntoAcc (X:=unit) (na_inv p N P)\n            (↑N ⊆ E ∧ ↑N ⊆ F) (na_own p F) (fupd E E) (fupd E E)\n            (λ _, ▷ P ∗ na_own p (F∖↑N))%I (λ _, ▷ P ∗ na_own p (F∖↑N))%I\n              (λ _, Some (na_own p F))%I.\n  Proof.\n    rewrite /IntoAcc /accessor. iIntros ((?&?)) \"#Hinv Hown\".\n    rewrite exist_unit -assoc /=.\n    iApply (na_inv_acc with \"Hinv\"); done.\n  Qed.\nEnd proofs.\n", "meta": {"author": "SkySkimmer", "repo": "iris", "sha": "186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5", "save_path": "github-repos/coq/SkySkimmer-iris", "path": "github-repos/coq/SkySkimmer-iris/iris-186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5/theories/base_logic/lib/na_invariants.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22322563167454426}}
{"text": "(**\n   Version très simplifiée des idée de: \"Java bytecode verification: algorithms\n   and formalizations\", Xavier Leroy (Journal of Automated Reasoning,\n   30(3-4):235-269, 2003).\n\n   Dont voici l'abstract:\n\n   \"Bytecode verification is a crucial security component for Java applets, on\n   the Web and on embedded devices such as smart cards. This paper reviews the\n   various bytecode verification algorithms that have been proposed, recasts\n   them in a common framework of dataflow analysis, and surveys the use of proof\n   assistants to specify bytecode verification and prove its correctness.\"\n\n *)\n\n(* Coq écrira de préférence la syntaxe [foo.(bar)] plutôt que [(bar\n   foo)], pour les champs (bar) de records (foo). *)\nSet Printing Projections.\n\n\nRequire Omega.\n\nRequire Import OrderedType OrderedTypeEx OrderedTypeAlt DecidableType DecidableTypeEx.\nFrom bcv Require Import LibHypsNaming heritage vmtype vmdefinition.\n\n(** * Valeurs manipulée par la machine défensive,\n\n   Ce module servira à instancier VMDefinition plus bas.\n   La définition des types, classes et instruction est fixée dans [vmtype]. *)\n\nModule DefVal <: VMVal.\n\n  Inductive DVal:Set :=\n  | Vint (i:nat)\n  | Vref (clrf:class_id * heap_idx) (** nom de classe * adresse dans le tas *)\n  | Vrefnull\n  | Error\n  | NonInit.\n\n  Definition Val := DVal.\n\n(****)\n Definition build_flds: ClasseDef -> (Dico.t Val) :=\n    Dico.map \n      (fun t:VMType =>\n         match t with\n         | Tint => Vint 0\n         | Tref id => Vref (id, 0) (** null = 0 *)\n         | Object => Vrefnull (** null = 0 *)\n         | Top => Vrefnull (** Should never happen *)\n         | Trefnull => Vrefnull (** Should never happen *)\n         end).\n\n\n  (** Calcul du type d'une valeur défensive. *)\n  Definition v2t (v:Val): VMType :=\n    match v with\n      | Vint i => Tint\n      | Vref (clid,_) => Tref clid\n      | Vrefnull => Trefnull\n      | Error => Top\n      | NonInit => Top\n    end.\n\n  Lemma val_eq_dec : forall v1 v2:Val, {v1=v2}+{v1<>v2}.\n  Proof.\n    intros v1 v2.\n    decide equality.\n    decide equality.\n    decide equality.\n    decide equality.\n    decide equality.\n  Qed.\n\nEnd DefVal.\n\n\n\nModule D (H:Herit).\n\n\n(** États défensifs. *)\n  Module Def := VMDefinition(DefVal)(H).\n  Import DefVal.\n  Include Def.\n  Ltac rename_dvm h th := fail.\n\n  (* Hypothesis renaming stuff from other files + current file.\n     DO NOT REDEFINE IN THIS FILE. Redefine rename_dvm instead. *)\n  Ltac rename_hyp h th ::=\n    match th with\n    | _ => (rename_dvm h th) (* redefine this tactic at will to enrich renaming*)\n    | _ => (Def.rename_vmdef h th) (* renaming from Def *)\n    | _ => (LibHypsNaming.rename_hyp_neg h th) (* basic generic renaming *)\n    end.\n\n  Function new (clid:class_id) (heap:Heap) : option (heap_idx * Heap) :=\n    match Dico.find clid allcl with\n    | None => None (** Classe inconnue *)\n    | Some cldef =>\n      let flds:Obj := {| objclass := clid; objfields := build_flds cldef |} in\n      let newhpidx: nat := maxkey heap in\n      Some((S newhpidx), Dico.add (S newhpidx) flds heap)\n    end.\n\n\n  (** test *)\n  (*\n    Definition obj1:Obj := {| objclass:=1; objfields:=Dico.empty _|}.\n    Definition heap1:Heap := Dico.empty _ .\n    Definition heap2:Heap := Dico.add 1 obj1 heap1.\n    Definition heap3:Heap := Dico.add 2 obj1 heap2.\n    Eval vm_compute in (maxkey heap3).\n    Eval vm_compute in (maxkey heap2). *)\n  (* fin test *)\n\n\n  (** * Fonction d'exécution défensive d'*un* bytecode.\n\n     Pas de vérif d'overflow sur la pile d'opérandes. pas de nb\n     négatifs, on ne vérifie que le typage et les underflow. *)\n\n   Definition exec_step (s:State): option State :=\n    let frm:Frame := s.(frame) in\n    let pc: pc_idx := frm.(pc) in\n    let instr_opt := Dico.find pc (frm.(mdef).(instrs)) in\n    match instr_opt with\n    | None => None\n    | Some instr =>\n      match instr with\n      | ret => Some s\n      | Iconst i =>\n        Some {| framestack := s.(framestack); heap := s.(heap);\n                frame := {| mdef:=s.(frame).(mdef) ; regs:= s.(frame).(regs);\n                            pc:= pc + 1;\n                            stack:= Vint i :: s.(frame).(stack)\n                         |}\n             |}\n\n      | Iadd =>\n        match s.(frame).(stack) with\n        | Vint i1 :: Vint i2 :: stack' =>\n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef); regs:= s.(frame).(regs);\n                              pc:= pc + 1;\n                              stack:= Vint (i1+i2) :: stack'\n                           |}\n               |}\n        | nil | _ :: nil => None (** Stack underflow *)\n        | _ :: _ => None (**Addition de types autres que int**)\n        end\n\n      | Iload ridx =>\n        match Dico.find ridx (s.(frame).(regs)) with\n        | Some (Vint i) =>\n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef); regs:= s.(frame).(regs);\n                              pc:= pc + 1;\n                              stack:=Vint i :: s.(frame).(stack)\n                           |}\n               |}\n        |_ => None      \n       end\n\n      | Rload clid_expected ridx =>\n        match Dico.find ridx (s.(frame).(regs)) with\n        | Some (Vref (clid_actual, hidx)) => if H.sub clid_actual clid_expected  then \n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef) ; \n                              regs:= s.(frame).(regs);\n                              pc:= pc + 1;\n                              stack:= Vref (clid_actual, hidx) :: s.(frame).(stack)\n                           |}\n               |}\n          else\n              None\n        | _ => None\n        end\n\n      | Istore ridx =>\n        match s.(frame).(stack) with\n        | Vint i :: stack' =>\n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef) ;\n                              regs:= Dico.add ridx (Vint i) (s.(frame).(regs));\n                              pc:= pc + 1;\n                              stack:= stack'\n                           |}\n               |}\n        | nil => None (** Stack underflow *)\n        | _ => None\n        end\n\n      | Rstore clid ridx =>\n        match s.(frame).(stack) with\n          | (Vref (clid_actual, hidx)) :: stack'=> if H.sub clid_actual clid then \n            Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef) ;\n                              regs:= Dico.add ridx (Vref (clid_actual, hidx)) (s.(frame).(regs));\n                              pc:= pc + 1;\n                              stack:= stack'\n                           |}\n               |}\n          else\n              None\n        | _ => None (** Stack underflow *)\n        end\n\n      | Iifle jmp => (** ifeqe *)\n        match s.(frame).(stack) with\n        | Vint 0 :: stack' => (** = 0  --> jump *)\n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef) ; regs:= s.(frame).(regs);\n                              pc:= jmp;\n                              stack:= stack'\n                           |}\n               |}\n        | Vint _ :: stack' => (** <> 0  --> pc+1 *)\n          Some {| framestack := s.(framestack); heap := s.(heap);\n                  frame := {| mdef:=s.(frame).(mdef) ; regs:= s.(frame).(regs);\n                              pc:= pc+1;\n                              stack:= stack'\n                           |}\n               |}\n        | _ => None (** Stack underflow or type error *)\n        end\n(*\n      | Goto jmp =>\n        Some {| framestack := s.(framestack); heap := s.(heap);\n                frame := {| mdef:=s.(frame).(mdef) ; regs:= s.(frame).(regs);\n                            stack:= s.(frame).(stack);\n                            pc:= jmp\n                         |}\n             |}\n\n      | Getfield cl namefld typ => None\n      | Putfield cl namefld typ =>\n        match s.(frame).(stack) with\n        | hpidx :: v :: stack' =>\n          match Dico.find hpidx s.(heap) with\n          | None => None (** adresse inconnue, objet non alloué *)\n          | Some {| objclass:= objcl; objfields:= flds |}=>\n            let newflds := {| objclass:= objcl;\n                              objfields:=Dico.add namefld v flds |} in\n            let newheap := Dico.add hpidx newflds s.(heap) in\n            Some {| framestack := s.(framestack);\n                    heap := newheap;\n                    frame := {| mdef:=s.(frame).(mdef) ;\n                                regs:= s.(frame).(regs);\n                                pc:= pc+1;\n                                stack:= stack'\n                             |}\n                 |}\n          end\n        | nil | _ :: nil => None (** Stack underflow *)\n        end\n\n      | New clid =>\n        match new clid s.(heap) with\n        | None => None (** Classe inconnue *)\n        | Some (newobj,newhp) =>\n          Some {| framestack := s.(framestack); heap := newhp;\n                  frame := {| mdef:=s.(frame).(mdef) ; regs:= s.(frame).(regs);\n                              stack:= newobj :: s.(frame).(stack);\n                              pc:= pc+1\n                           |}\n               |}\n\n        end\n      end\n    end.\n*)\n | _ => None\n  end\nend.\n   \n\n  Functional Scheme exec_step_ind := Induction for exec_step Sort Prop.\n\n  (** * Tests *)\n\n  Notation \"k --> i , d\" := (Dico.add k i d) (at level 55, right associativity).\n\n  Definition prog:MethodDef :=\n    {| instrs := (0 --> Iload 1 ,\n                  1 --> Istore 2 ,\n                  2 --> ret ,\n                  Dico.empty ) ;\n       argstype :=( Tint :: Tint:: nil);\n       restype := Tint |}.\n\n  Definition startstate:State :=\n    {|\n      framestack := nil;\n      heap := Dico.empty;\n      frame := {|\n                mdef:= prog ;\n                regs:= (0 --> Vint 32 , 1-->Vint 11, Dico.empty );\n                pc:= 0;\n                stack:= nil\n              |}\n    |}.\n\n  Fixpoint exec_n (s : State) (n:nat) {struct n}: option State :=\n    match n with\n    | 0 => Some s\n    | S n' =>\n      match exec_step s with\n      | None => None\n      | Some s' => exec_n s' n'\n      end\n    end.\n  (*\n    Eval simpl in exec_n startstate 1.\n    Eval simpl in exec_n startstate 2.\n    Eval simpl in exec_n startstate 5.\n   *)\n  (* Eval simpl in exec_n (fun x y => false) (Dico.empty _) startstate 2. *)\n\n\n  (** Exemple de preuve très simple sur la fonction d'exécution: la\n  pile (hormis la méthode en cours d'exécution) ne change pas au cours\n  de exec_step. *)\n\n  Lemma essai : forall s x,\n      exec_step s = Some x ->\n      x.(framestack) = s.(framestack).\n  Proof.\n    intros s.\n    functional induction exec_step s;intros ;simpl;\n      try solve [discriminate | inversion H; subst;simpl;reflexivity] .\n  Qed.\n\n\nEnd D.\n\n\n", "meta": {"author": "kahinaFekir", "repo": "CoqProject", "sha": "cf7cf2b64c54bd02cfe0b9e7d44a331a0667aaeb", "save_path": "github-repos/coq/kahinaFekir-CoqProject", "path": "github-repos/coq/kahinaFekir-CoqProject/CoqProject-cf7cf2b64c54bd02cfe0b9e7d44a331a0667aaeb/dvm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22322563167454426}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\n\nRequire Import Logic.Classical_Prop Coq.Logic.FunctionalExtensionality.\n\nFrom stdpp\nRequire Import\n    base\n    decidable\n    propset\n    fin_maps\n    fin_sets\n.\n\nFrom MatchingLogic\nRequire Import\n    Utils.extralibrary\n    Utils.stdpp_ext\n    Pattern\n    Syntax\n    Semantics\n    DerivedOperators_Syntax\n    DerivedOperators_Semantics\n    PrePredicate\n    monotonic\n    Theories.Definedness_Syntax\n    Theories.Definedness_Semantics\n    Theories.Sorts_Syntax\n    Theories.Sorts_Semantics\n.\n\n\nImport MatchingLogic.Logic.Notations.\nImport MatchingLogic.Semantics.Notations.\n\nSection with_syntax.\n    Context\n        {Σ : Signature}\n        (* TODO: maybe remove and use the imported one from Sorts_Syntax? *)\n        {ds : Definedness_Syntax.Syntax}\n        {ss : Sorts_Syntax.Syntax}\n        (HSortImptDef : imported_definedness = ds)\n        (HDefNeqInh : Definedness_Syntax.inj definedness <> Sorts_Syntax.inj inhabitant)\n    .\n    Open Scope ml_scope.\n\n    Definition is_core_symbol (s : symbols) : Prop\n        := s = Definedness_Syntax.inj definedness \\/ s = Sorts_Syntax.inj inhabitant.\n\n\n    Instance is_core_symbol_dec (s : symbols) : Decision (is_core_symbol s).\n    Proof. solve_decision. Defined.\n\n    Definition is_not_core_symbol (s : symbols) : Prop\n        := ~ is_core_symbol s.\n\n    Instance is_not_core_symbol_dec (s : symbols) : Decision (is_not_core_symbol s).\n    Proof. solve_decision. Defined.\n\n\n\n    Inductive is_SPredicate\n    : Pattern -> Prop :=\n    | spred_bott\n        : is_SPredicate patt_bott\n    | spred_def (ϕ : Pattern)\n        : is_SData ϕ -> is_SPredicate (patt_defined ϕ)\n    (* note that we have to add equality and subseteq manually,\n       since they are usually defined using totality,\n       and we do not have totality in the fragment!\n     *)\n    | spred_eq (ϕ₁ ϕ₂ : Pattern)\n        : is_SData ϕ₁ -> is_SData ϕ₂ -> is_SPredicate (patt_equal ϕ₁ ϕ₂)\n    | spred_subseteq (ϕ₁ ϕ₂ : Pattern)\n        : is_SData ϕ₁ -> is_SData ϕ₂ -> is_SPredicate (patt_subseteq ϕ₁ ϕ₂)\n    | spred_imp (ϕ₁ ϕ₂ : Pattern)\n        : is_SPredicate ϕ₁ -> is_SPredicate ϕ₂ -> is_SPredicate (patt_imp ϕ₁ ϕ₂)\n    | spred_ex (ϕ : Pattern) (s : symbols)\n        : is_SPredicate ϕ -> is_not_core_symbol s -> is_SPredicate (patt_exists_of_sort (patt_sym s) ϕ)\n    | spred_all (ϕ : Pattern) (s : symbols)\n        : is_SPredicate ϕ -> is_not_core_symbol s -> is_SPredicate (patt_forall_of_sort (patt_sym s) ϕ)\n    with is_SData\n    : Pattern -> Prop :=\n    | sdata_bott\n        : is_SData patt_bott\n    | sdata_fevar (x : evar)\n        : is_SData (patt_free_evar x)\n    | sdata_fsvar (X : svar)\n        : is_SData (patt_free_svar X)\n    | sdata_bevar (dbi : db_index)\n        : is_SData (patt_bound_evar dbi)\n    | sdata_bsvar (dbi : db_index)\n        : is_SData (patt_bound_svar dbi)\n    | sdata_sym (s : symbols)\n        : is_not_core_symbol s -> is_SData (patt_sym s)\n    | sdata_inh (s : symbols)\n        : is_not_core_symbol s -> is_SData (patt_inhabitant_set (patt_sym s))\n    | sdata_sneg (ϕ : Pattern) (s : symbols)\n        : is_SData ϕ -> is_not_core_symbol s -> is_SData (patt_sorted_neg (patt_sym s) ϕ)\n    | sdata_app (ϕ₁ ϕ₂ : Pattern)\n        : is_SData ϕ₁ -> is_SData ϕ₂ -> is_SData (patt_app ϕ₁ ϕ₂)\n    | sdata_or (ϕ₁ ϕ₂ : Pattern)\n        : is_SData ϕ₁ -> is_SData ϕ₂ -> is_SData (patt_or ϕ₁ ϕ₂)\n    | sdata_filter (ϕ ψ : Pattern)\n        : is_SData ϕ -> is_SPredicate ψ -> is_SData (patt_and ϕ ψ)\n    | sdata_ex (ϕ : Pattern) (s : symbols)\n        : is_SData ϕ -> is_not_core_symbol s -> is_SData (patt_exists_of_sort (patt_sym s) ϕ)\n    (* This is disabled, because if the sort is empty, then the forall evaluates to full set,\n       and that does not get lifted to full set in the extended model.\n     *)\n    (*\n    | sdata_all (ϕ : Pattern) (s : symbols)\n        : is_SData ϕ -> is_not_core_symbol s -> is_SData (patt_forall_of_sort (patt_sym s) ϕ)\n    *)\n    | sdata_mu (ϕ : Pattern)\n        : is_SData ϕ -> is_SData (patt_mu ϕ)\n    .\n\n    Lemma is_SData_bevar_subst ϕ₁ ϕ₂ dbi:\n        is_SData ϕ₁ ->\n        is_SData ϕ₂ ->\n        is_SData (ϕ₁^[evar: dbi ↦ ϕ₂])\n    with is_SPredicate_bevar_subst ψ ϕ₂ dbi:\n        is_SPredicate ψ ->\n        is_SData ϕ₂ ->\n        is_SPredicate (ψ^[evar: dbi ↦ ϕ₂])\n    .\n    Proof.\n        {\n            intros H1 H2.\n            induction H1; simpl; try constructor; auto.\n            {\n                case_match.\n                { constructor. }\n                { assumption. }\n                { constructor. }\n            }\n        }\n        {\n            intros H1 H2.\n            induction H1; try (solve [simpl; try constructor; auto]).\n        }\n    Qed.\n\n    Lemma is_SData_evar_open x ϕ:\n        is_SData ϕ ->\n        is_SData (ϕ^{evar: 0 ↦ x}).\n    Proof.\n        intros H.\n        unfold evar_open.\n        apply is_SData_bevar_subst.\n        { assumption. }\n        constructor.\n    Qed.\n\n    Lemma is_SPredicate_evar_open x ϕ:\n        is_SPredicate ϕ ->\n        is_SPredicate (ϕ^{evar: 0 ↦ x}).\n    Proof.\n        intros H.\n        unfold evar_open.\n        apply is_SPredicate_bevar_subst.\n        { assumption. }\n        constructor.\n    Qed.\n\n    Lemma is_SData_bsvar_subst ϕ₁ ϕ₂ dbi:\n        is_SData ϕ₁ ->\n        is_SData ϕ₂ ->\n        is_SData (ϕ₁^[svar: dbi ↦ ϕ₂])\n    with is_SPredicate_bsvar_subst ψ ϕ₂ dbi:\n        is_SPredicate ψ ->\n        is_SData ϕ₂ ->\n        is_SPredicate (ψ^[svar: dbi ↦ ϕ₂])\n    .\n    Proof.\n        {\n            intros H1 H2.\n            induction H1; simpl; try constructor; auto.\n            {\n                case_match.\n                { constructor. }\n                { assumption. }\n                { constructor. }\n            }\n        }\n        {\n            intros H1 H2.\n            induction H1; try (solve [simpl; try constructor; auto]).\n        }\n    Qed.\n\n    Lemma is_SData_svar_open x ϕ:\n        is_SData ϕ ->\n        is_SData (ϕ^{svar: 0 ↦ x}).\n    Proof.\n        intros H.\n        unfold evar_open.\n        apply is_SData_bsvar_subst.\n        { assumption. }\n        constructor.\n    Qed.\n\n    Lemma is_SPredicate_svar_open x ϕ:\n        is_SPredicate ϕ ->\n        is_SPredicate (ϕ^{svar: 0 ↦ x}).\n    Proof.\n        intros H.\n        unfold evar_open.\n        apply is_SPredicate_bsvar_subst.\n        { assumption. }\n        constructor.\n    Qed.\n\n    Lemma is_SPredicate_patt_not (ϕ : Pattern) :\n        is_SPredicate ϕ ->\n        is_SPredicate (patt_not ϕ).\n    Proof.\n        intros H.\n        unfold patt_not.\n        apply spred_imp.\n        { assumption. }\n        { apply spred_bott. }\n    Qed.\n\n(*\n    Lemma is_SPredicate_forall_of_sort (s : symbols) (ϕ : Pattern)  :\n        is_SPredicate (patt_forall_of_sort (patt_sym s) ϕ).\n    Proof.\n        unfold patt_forall_of_sort,patt_forall.\n        apply is_SPredicate_patt_not.\n    Qed.\n*)\n    Section ext.\n        Context\n            (M : Model)\n            (indec : forall (s : symbols),\n              is_not_core_symbol s ->\n              forall (m : Domain M) ρ,\n              Decision (m ∈ Minterp_inhabitant (patt_sym s) ρ))\n            (R : Type)\n            (fRM : R -> (Domain M) -> propset (Domain M + R)%type)\n            (fMR : (Domain M) -> R -> propset (Domain M + R)%type)\n            (fRR : R -> R -> propset (Domain M + R)%type)\n            (finh : R -> propset (Domain M + R)%type)\n        .\n\n    Inductive Carrier := cdef | cinh | cel (el: (Domain M + R)%type).\n\n    Instance Carrier_inhabited : Inhabited Carrier := populate cdef.\n\n    Definition new_app_interp (x y : Carrier) : propset Carrier :=\n        match x with\n        | cdef =>\n            ⊤\n        | cinh =>\n            match y with\n            | cdef => ∅\n            | cinh => ∅\n            | cel el =>\n                match el with\n                | inl m =>\n                    cel <$> (@fmap propset _ _ _ inl (@app_ext _ M (sym_interp M (Sorts_Syntax.inj inhabitant)) {[m]}))\n                | inr r =>\n                    cel <$> finh r\n                end\n            end\n        | cel elx =>\n            match y with\n            | cdef => ∅\n            | cinh => ∅\n            | cel ely =>\n                match elx,ely with\n                | (inl mx),(inl my) =>\n                    cel <$> (@fmap propset _ _ _ inl (@app_interp _ M mx my))\n                | (inl mx),(inr ry) =>\n                    cel <$> (fMR mx ry)\n                | (inr rx),(inl my) =>\n                    cel <$> (fRM rx my)\n                | (inr rx),(inr ry) =>\n                    cel <$> (fRR rx ry)\n                end\n            end\n        end.\n\n    Definition new_sym_interp (s : symbols) : propset Carrier :=\n        match (decide (s = Definedness_Syntax.inj definedness)) with\n        | left _ => {[ cdef ]}\n        | right _ =>\n            match (decide (s = Sorts_Syntax.inj inhabitant)) with\n            | left _ => {[ cinh ]}\n            | right _ => cel <$> (@fmap propset _ _ _ inl (@sym_interp _ M s))\n            end\n        end.\n\n    (* TODO: why was this poliorphic? *)\n    Definition Mext : Model :=\n        {|\n            Domain := Carrier ;\n            Domain_inhabited := Carrier_inhabited ;\n            app_interp := new_app_interp ;\n            sym_interp := new_sym_interp ;\n        |}.\n\n    Lemma Mext_satisfies_definedness : Mext ⊨ᵀ Definedness_Syntax.theory.\n    Proof.\n        unfold theory.\n        apply satisfies_theory_iff_satisfies_named_axioms.\n        intros na. destruct na.\n        apply single_element_definedness_impl_satisfies_definedness.\n        exists cdef.\n        simpl. split.\n        {\n            unfold new_sym_interp. case_match.\n            { reflexivity. }\n            contradiction n. reflexivity.\n        }\n        {\n            auto.\n        }\n    Qed.\n\n    Definition lift_value (x : Domain M) : (Domain Mext)\n    := cel (inl x).\n\n    Definition lift_set (xs : propset (Domain M)) : (propset (Domain Mext))\n    := cel <$> (@fmap propset _ _ _ inl xs).\n\n    (* Valuations lifted from the original model to the extended model. *)\n    Definition lift_val (ρ : @Valuation Σ M) : \n      (@Valuation Σ Mext)\n    := {|\n         evar_valuation := λ (x : evar), lift_value (evar_valuation ρ x);\n         svar_valuation := λ (X : svar), lift_set (svar_valuation ρ X)\n       |}.\n\n    Lemma lift_set_mono (xs ys : propset (Domain M)) :\n        xs ⊆ ys <->\n        lift_set xs ⊆ lift_set ys.\n    Proof.\n        unfold lift_set,fmap.\n        with_strategy transparent [propset_fmap] unfold propset_fmap.\n        split.\n        {\n            intros H.\n            clear -H. set_solver.\n        }\n        {\n            intros H.\n            rewrite elem_of_subseteq in H.\n            rewrite elem_of_subseteq.\n            intros x Hx.\n            specialize (H (lift_value x)).\n            unfold lift_value in H.\n            do 2 rewrite elem_of_PropSet in H.\n            feed specialize H.\n            {\n                exists (inl x).\n                split;[reflexivity|].\n                rewrite elem_of_PropSet.\n                exists x.\n                split;[reflexivity|].\n                exact Hx.\n            }\n            destruct H as [a [Ha H] ].\n            inversion Ha. clear Ha. subst.\n            rewrite elem_of_PropSet in H.\n            destruct H as [a [Ha H] ].\n            inversion Ha. clear Ha. subst.\n            exact H.\n        }\n    Qed.\n\n    Lemma lift_set_injective (xs ys : propset (Domain M)) :\n        xs = ys <-> lift_set xs = lift_set ys.\n    Proof.\n        split;[congruence|].\n        intros H.\n        unfold lift_set,fmap in H.\n        with_strategy transparent [propset_fmap] unfold propset_fmap in H.\n        unfold_leibniz.\n        rewrite set_equiv_subseteq in H.\n        do 2 rewrite elem_of_subseteq in H.\n        destruct H as [H1 H2].\n        rewrite set_equiv_subseteq.\n        do 2 rewrite elem_of_subseteq.\n        split; intros x Hx.\n        {\n            specialize (H1 (lift_value x)).\n            do 2 rewrite elem_of_PropSet in H1.\n            feed specialize H1.\n            {\n                unfold lift_value.\n                exists (inl x).\n                split;[reflexivity|].\n                rewrite elem_of_PropSet.\n                exists x.\n                split;[reflexivity|].\n                apply Hx.\n            }\n            destruct H1 as [a [Ha H1] ].\n            unfold lift_value in Ha.\n            inversion Ha. clear Ha. subst. \n            rewrite elem_of_PropSet in H1.\n            destruct H1 as [a [Ha H1] ].\n            inversion Ha. clear Ha. subst.\n            exact H1.\n        }\n        {\n            specialize (H2 (lift_value x)).\n            do 2 rewrite elem_of_PropSet in H2.\n            feed specialize H2.\n            {\n                unfold lift_value.\n                exists (inl x).\n                split;[reflexivity|].\n                rewrite elem_of_PropSet.\n                exists x.\n                split;[reflexivity|].\n                apply Hx.\n            }\n            destruct H2 as [a [Ha H2] ].\n            unfold lift_value in Ha.\n            inversion Ha. clear Ha. subst. \n            rewrite elem_of_PropSet in H2.\n            destruct H2 as [a [Ha H2] ].\n            inversion Ha. clear Ha. subst.\n            exact H2.\n        }\n    Qed.\n\n    Lemma Mext_indec :\n        forall (s : symbols),\n            is_not_core_symbol s ->\n            forall (m : Domain Mext) ρ,\n            Decision (m ∈ @Minterp_inhabitant Σ _ Mext (patt_sym s) (lift_val ρ)).\n    Proof.\n        intros. unfold Minterp_inhabitant.\n        rewrite eval_app_simpl.\n        unfold app_ext,lift_val. simpl.\n        destruct m.\n        {\n            right. intros HContra.\n            rewrite elem_of_PropSet in HContra.\n            destruct HContra as [le [re [HContra1 [HContra2 HContra3] ] ] ].\n            rewrite eval_sym_simpl in HContra1.\n            rewrite eval_sym_simpl in HContra2.\n            simpl in HContra1.\n            simpl in HContra2.\n            unfold new_sym_interp in HContra1, HContra2.\n            unfold new_app_interp in HContra3.\n            repeat case_match; subst; auto; try set_solver.\n        }\n        {\n            right. intros HContra.\n            rewrite elem_of_PropSet in HContra.\n            destruct HContra as [le [re [HContra1 [HContra2 HContra3] ] ] ].\n            rewrite eval_sym_simpl in HContra1.\n            rewrite eval_sym_simpl in HContra2.\n            simpl in HContra1.\n            simpl in HContra2.\n            unfold new_sym_interp in HContra1, HContra2.\n            unfold new_app_interp in HContra3.\n            repeat case_match; subst; auto; try set_solver.\n        }\n        destruct el.\n        2: {\n            right. intros HContra.\n            rewrite elem_of_PropSet in HContra.\n            destruct HContra as [le [re [HContra1 [HContra2 HContra3] ] ] ].\n            rewrite eval_sym_simpl in HContra1.\n            rewrite eval_sym_simpl in HContra2.\n            simpl in HContra1.\n            simpl in HContra2.\n            unfold new_sym_interp in HContra1, HContra2.\n            unfold new_app_interp in HContra3.\n            repeat case_match; subst; auto; try set_solver.\n        }\n        destruct (indec _ H d ρ) as [Hin|Hnotin].\n        {\n            left.\n            unfold Minterp_inhabitant in Hin.\n            rewrite eval_app_simpl in Hin.\n            do 2 rewrite eval_sym_simpl in Hin.\n            unfold app_ext in Hin.\n            rewrite elem_of_PropSet in Hin.\n            destruct Hin as [le [re [Hinle [Hinre Hin] ] ] ].\n            rewrite elem_of_PropSet.\n\n            do 2 rewrite eval_sym_simpl.\n            simpl.\n            unfold new_sym_interp.\n            repeat case_match; subst; auto; try contradiction; try congruence;\n            unfold lift_value.\n            { exfalso. apply H. unfold is_core_symbol. left. reflexivity. }\n            { exfalso. apply H. unfold is_core_symbol. right. reflexivity. }\n\n            exists cinh, (lift_value re).\n            split;[set_solver|].\n            unfold lift_value,new_app_interp.\n            split;[set_solver|].\n            unfold app_ext.\n            clear -Hinle Hinre Hin.\n            set_solver.\n        }\n        {\n            right.\n            unfold Minterp_inhabitant in Hnotin.\n            rewrite eval_app_simpl in Hnotin.\n            do 2 rewrite eval_sym_simpl in Hnotin.\n            unfold app_ext in Hnotin.\n            rewrite elem_of_PropSet in Hnotin.\n            rewrite elem_of_PropSet.\n            intro HContra. apply Hnotin.\n            do 2 rewrite eval_sym_simpl in HContra.\n            simpl in HContra. unfold new_sym_interp in HContra.\n            destruct HContra as [le [re [Hinle [Hinre Hin] ] ] ].\n\n\n            repeat case_match; subst; auto; try contradiction; try congruence;\n            unfold lift_value.\n            { exfalso. apply H. unfold is_core_symbol. left. reflexivity. }\n            { exfalso. apply H. unfold is_core_symbol. right. reflexivity. }\n\n            unfold new_app_interp in Hin.\n            rewrite elem_of_PropSet in Hinre.\n            repeat case_match; subst; auto; try contradiction; try congruence.\n            {\n                unfold app_ext in Hin.\n                rewrite elem_of_PropSet in Hin.\n                destruct Hin as [a [Hin1 Hin2] ].\n                inversion Hin1. subst. clear Hin1.\n                rewrite elem_of_PropSet in Hin2.\n                destruct Hin2 as [a [Hin2 Hin3] ].\n                inversion Hin2. subst. clear Hin2.\n                rewrite elem_of_PropSet in Hin3.\n                destruct Hin3 as [le [lre [Hle [Hre HAlmost] ] ] ].\n                rewrite elem_of_PropSet in Hre.\n                inversion Hre. clear Hre. subst.\n                destruct Hinre as [a' [Ha' Ha''] ].\n                rewrite elem_of_PropSet in Ha''.\n                destruct_and_ex!. subst.\n                exists le, x.\n                split;[assumption|].\n                split;[assumption|].\n                inversion Ha'. subst.\n                assumption.\n            }\n            {\n                rewrite elem_of_PropSet in Hin.\n                destruct Hinre as [a1 [Ja1 Ga1] ].\n                destruct Hin as [a2 [Ja2 Ga2] ].\n                inversion Ja1; clear Ja1; subst.\n                inversion Ja2; clear Ja2; subst.\n                rewrite elem_of_PropSet in Ga1.\n                destruct Ga1 as [a3 [Ja3 Ga3] ].\n                inversion Ja3.\n            }\n        }\n    Qed.\n\n    Section semantic_preservation.\n       Context\n            (M_def : M ⊨ᵀ Definedness_Syntax.theory)\n        .\n\n        Lemma SPred_is_pre_predicate\n            (ψ : Pattern)\n            :\n            is_SPredicate ψ ->\n            M_pre_predicate M ψ.\n        Proof.\n            intros HSPred.\n            induction HSPred.\n            { apply (@M_pre_pre_predicate_impl_M_pre_predicate _ 0). apply M_pre_pre_predicate_bott. }\n            { apply (@M_pre_pre_predicate_impl_M_pre_predicate _ 0). apply T_pre_predicate_defined. exact M_def. }\n            { apply (@M_pre_pre_predicate_impl_M_pre_predicate _ 0). apply T_pre_predicate_equal. exact M_def. }\n            { apply (@M_pre_pre_predicate_impl_M_pre_predicate _ 0). apply T_pre_predicate_subseteq. exact M_def. }\n            { apply M_pre_predicate_imp; assumption. }\n            { \n                unfold patt_exists_of_sort.\n                apply M_pre_predicate_exists.\n                apply M_pre_predicate_and.\n                2: { exact IHHSPred. }\n                unfold patt_in.\n                apply T_pre_predicate_defined.\n                rewrite HSortImptDef.\n                exact M_def.\n            }\n            {\n                unfold patt_forall_of_sort.\n                apply M_pre_predicate_forall.\n                apply M_pre_predicate_imp.\n                2: { exact IHHSPred. }\n                unfold patt_in.\n                apply T_pre_predicate_defined.\n                rewrite HSortImptDef.\n                exact M_def.\n            }\n        Qed.\n\n        Lemma SPred_is_predicate\n            (ψ : Pattern)\n            :\n            well_formed_closed_ex_aux ψ 0 ->\n            is_SPredicate ψ ->\n            M_predicate M ψ.\n        Proof.\n            intros Hwfc Hspred.\n            apply SPred_is_pre_predicate in Hspred.\n            unfold M_pre_predicate in Hspred.\n            specialize (Hspred 0).\n            eapply closed_M_pre_pre_predicate_is_M_predicate.\n            2: { apply Hspred. }\n            apply Hwfc.\n        Qed.\n\n\n        Lemma semantics_preservation_sym (s : symbols)\n            (ρ : @Valuation _ M)\n            ρ0\n            :\n            is_not_core_symbol s ->\n            @eval Σ Mext ρ0 (patt_sym s) =\n            lift_set (@eval Σ M ρ (patt_sym s)).\n        Proof.\n            intros H.\n            do 2 rewrite eval_sym_simpl.\n            clear -H. unfold_leibniz.\n            unfold is_not_core_symbol,is_core_symbol in H.\n            unfold sym_interp at 1. simpl. unfold new_sym_interp.\n            repeat case_match; subst.\n            { exfalso. tauto. }\n            { exfalso. tauto. }\n            unfold lift_set,fmap. reflexivity.\n        Qed.\n\n        Lemma semantics_preservation_inhabitant_set (s : symbols)\n            (ρ : @Valuation _ M)\n            ρ0\n            :\n            is_not_core_symbol s ->\n            @eval Σ Mext ρ0 (patt_inhabitant_set (patt_sym s))\n            = lift_set (@eval Σ M ρ (patt_inhabitant_set (patt_sym s))).\n        Proof.\n            intros H.\n            rename H into Hnc.\n            (* For some reason, the tactic [unfold_leibniz] performed later\n               in the proof script does nothing. *)\n            unfold_leibniz. \n            unfold patt_inhabitant_set.\n            do 2 rewrite eval_app_simpl.\n            rewrite (semantics_preservation_sym _ ρ);[assumption|].\n            remember (eval ρ (patt_sym s)) as ps.\n            unfold Sorts_Syntax.sym.\n            do 2 rewrite eval_sym_simpl.\n            unfold sym_interp at 1. simpl. unfold new_sym_interp.\n            rewrite decide_eq_same.\n            destruct (decide (inj inhabitant = Definedness_Syntax.inj definedness)) as [Heq|Hneq] eqn:Hnid.\n            { clear -HDefNeqInh Heq. congruence. }\n            {\n                clear Hneq Hnid.\n                unfold app_ext at 1.\n                unfold app_interp at 1. simpl. unfold new_app_interp.\n                set_unfold. intros x. split.\n                {\n                    intros [x0 [x1 H] ]. destruct_and!. subst.\n                    repeat case_match.\n                    { exfalso. clear -H2. set_solver. }\n                    { exfalso. clear -H2. set_solver. }\n                    { subst. set_solver. }\n                    { subst. set_solver. }\n                }\n                {\n                    intros [y H]. destruct_and!. subst.\n                    destruct H1 as [y0 H]. destruct_and!. subst.\n                    destruct H1 as [x [x0 H] ].\n                    clear Heqps.\n                    destruct_and!.\n                    exists cinh.\n                    eexists (cel (inl x0)).\n                    split.\n                    { reflexivity. }\n                    split.\n                    {\n                        exists (inl x0). split. reflexivity. exists x0. split.\n                        reflexivity. assumption.\n                    }\n                    {\n                        unfold fmap.\n                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                        set_solver.\n                    }\n                }\n            }\n        Qed.\n\n        Lemma update_evar_val_lift_val_comm\n            (ρ : @Valuation _ M)\n            (x : evar)\n            (d : Domain M)\n            :\n            (@update_evar_val Σ Mext x (cel (inl d)) (lift_val ρ))\n            = lift_val (@update_evar_val Σ M x d ρ).\n        Proof.\n            destruct ρ as [ρₑ ρₛ]. unfold update_evar_val. simpl.\n            unfold lift_val. simpl. f_equal.\n            apply functional_extensionality.\n            intros x'.\n            case_match; reflexivity.\n        Qed.\n \n        Lemma update_svar_val_lift_set_comm\n            (ρ : @Valuation _ M)\n            (X : svar)\n            (D : propset (Domain M))\n            :\n        (@update_svar_val Σ Mext X (lift_set D) (lift_val ρ))\n        = lift_val (@update_svar_val Σ M X D ρ).\n        Proof.\n            destruct ρ as [ρₑ ρₛ]. unfold update_svar_val. simpl.\n            unfold lift_val. simpl. f_equal.\n            apply functional_extensionality.\n            intros X'.\n            case_match; reflexivity.\n        Qed.\n\n        Lemma lift_set_fa_union (C : Type) (f : C -> propset (Domain M)) :\n            lift_set (stdpp_ext.propset_fa_union f) = stdpp_ext.propset_fa_union (λ k, lift_set (f k)).\n        Proof.\n            unfold stdpp_ext.propset_fa_union, lift_set.\n            unfold lift_set,fmap.\n            with_strategy transparent [propset_fmap] unfold propset_fmap.\n            clear. unfold_leibniz. set_solver.\n        Qed.\n\n        Lemma lift_set_fa_intersection (C : Type) {_ : Inhabited C} (f : C -> propset (Domain M)) :\n            lift_set (stdpp_ext.propset_fa_intersection f) = stdpp_ext.propset_fa_intersection (λ k, lift_set (f k)).\n        Proof.\n            unfold stdpp_ext.propset_fa_intersection, lift_set.\n            unfold lift_set,fmap.\n            with_strategy transparent [propset_fmap] unfold propset_fmap.\n            unfold_leibniz. set_unfold.\n            intros x.\n            split; intros H.\n            {\n                destruct_and_ex!.  subst. intros.\n                exists (inl x1).\n                split;[reflexivity|].\n                exists x1.\n                split;[reflexivity|].\n                apply H2.\n            }\n            {\n                pose proof (Htmp := H (@stdpp.base.inhabitant C X)).\n                destruct_and_ex!. subst.\n                exists (inl x1).\n                split;[reflexivity|].\n                exists x1.\n                split;[reflexivity|].\n                intros x.\n                pose proof (Htmp2 := H x).\n                destruct_and_ex!. subst.\n                inversion H0. subst.\n                assumption.\n            }\n        Qed.\n\n        Lemma semantics_preservation\n            (sz : nat)\n            :\n            (\n                forall (ϕ : Pattern) (ρ : @Valuation _ M),\n                size' ϕ < sz ->\n                is_SData ϕ ->\n                well_formed ϕ ->\n                @eval Σ Mext (lift_val ρ) ϕ\n                = lift_set (@eval Σ M ρ ϕ)\n            )\n            /\\\n            (\n                forall (ψ : Pattern) (ρ : @Valuation _ M),\n                size' ψ < sz ->\n                is_SPredicate ψ ->\n                well_formed ψ ->\n                (@eval Σ Mext (lift_val ρ) ψ = ∅\n                <-> @eval Σ M ρ ψ = ∅)\n                /\\\n                (@eval Σ Mext (lift_val ρ) ψ = ⊤\n                <-> @eval Σ M ρ ψ = ⊤)\n            ).\n        Proof.\n            induction sz.\n            {\n                split.\n                {\n                    intros ϕ Hsz.\n                    destruct ϕ; simpl in Hsz; lia.\n                }\n                {\n                    intros ψ Hsz.\n                    destruct ψ; simpl in Hsz; lia.\n                }\n            }\n            {\n                destruct IHsz as [IHszdata IHszpred].\n                split.\n                {\n                    (* preservation of data patterns *)\n                    intros ϕ ρ Hszϕ HSData Hwf.\n                    destruct HSData; simpl in Hszϕ.\n                    {\n                        (* patt_bott *)\n                        do 2 rewrite eval_bott_simpl.\n                        unfold lift_set.\n                        unfold fmap.\n                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                        clear.\n                        unfold_leibniz.\n                        set_solver.\n                    }\n                    {\n                        (* free_evar x*)\n                        do 2 rewrite eval_free_evar_simpl.\n                        unfold lift_set,fmap.\n                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                        clear. unfold_leibniz. set_solver.\n                    }\n                    {\n                        (* free_svar X *)\n                        do 2 rewrite eval_free_svar_simpl.\n                        unfold lift_set,fmap.\n                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                        clear. unfold_leibniz. set_solver.\n                    }\n                    {\n                        (* bound_evar X *)\n                        do 2 rewrite eval_bound_evar_simpl.\n                        unfold lift_set,fmap.\n                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                        clear. unfold_leibniz. set_solver.\n                    }\n                    {\n                        (* bound_svar X *)\n                        do 2 rewrite eval_bound_svar_simpl.\n                        unfold lift_set,fmap.\n                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                        clear. unfold_leibniz. set_solver.\n                    }\n                    {\n                        (* sym s *)\n                        apply semantics_preservation_sym.\n                        { assumption. }\n                    }\n                    {\n                        (* patt_inhabitant_set (patt_sym s) *)\n                        apply semantics_preservation_inhabitant_set.\n                        { assumption. }\n                    }\n                    {\n                        (* patt_sorted_neg (patt_sym s) ϕ *)\n                        unfold patt_sorted_neg.\n                        do 2 rewrite eval_and_simpl.\n                        rewrite (semantics_preservation_inhabitant_set _ ρ);[assumption|].\n                        do 2 rewrite eval_not_simpl.\n                        rewrite IHszdata.\n                        {\n                            lia.\n                        }\n                        {\n                            exact HSData.\n                        }\n                        {\n                            wf_auto2.\n                        }\n                        remember (eval ρ (patt_inhabitant_set (patt_sym s))) as Xinh.\n                        remember (eval ρ ϕ) as Xϕ.\n                        clear HeqXinh HeqXϕ IHszpred IHszdata.\n                        unfold_leibniz.\n                        set_solver.\n                    }\n                    {\n                        (* patt_app ϕ₁ ϕ₂ *)\n                        do 2 rewrite eval_app_simpl.\n                        rewrite IHszdata.\n                        { lia. }\n                        { exact HSData1. }\n                        { wf_auto2. }\n                        rewrite IHszdata.\n                        { lia. }\n                        { exact HSData2. }\n                        { wf_auto2. }\n                        unfold app_ext.\n                        clear. unfold_leibniz.\n                        unfold lift_set,fmap.\n                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                        unfold Mext. simpl. unfold new_app_interp.\n                        set_unfold.\n                        intros x. split.\n                        {\n                            intros [x0 [x1 H] ].\n                            destruct_and!.\n                            destruct H0 as [xH0 H0].\n                            destruct H as [xH H].\n                            destruct_and!. subst.\n                            destruct H4 as [xH4 H4].\n                            destruct H3 as [xH3 H3].\n                            destruct_and!. subst.\n                            destruct x.\n                            {\n                                exfalso.\n                                unfold fmap in H2.\n                                with_strategy transparent [propset_fmap] unfold propset_fmap in H2.\n                                clear -H2. set_solver.\n                            }\n                            {\n                                exfalso.\n                                unfold fmap in H2.\n                                with_strategy transparent [propset_fmap] unfold propset_fmap in H2.\n                                clear -H2. set_solver.\n                            }\n                            {\n                                inversion H2. clear H2. destruct_and!. subst.\n                                inversion H2. clear H2. destruct_and!. subst.\n                                inversion H1. clear H1. subst.\n                                exists (inl x0).\n                                split;[reflexivity|].\n                                exists x0.\n                                split;[reflexivity|].\n                                exists xH4,xH3.\n                                repeat split; assumption.\n                            }\n                        }\n                        {\n                            intros H.\n                            destruct_and_ex!. subst.\n                            exists (cel (inl x2)).\n                            exists (cel (inl x3)).\n                            split.\n                            {\n                                exists (inl x2).\n                                split;[reflexivity|].\n                                exists x2.\n                                split;[reflexivity|].\n                                assumption.\n                            }\n                            split.\n                            {\n                                exists (inl x3).\n                                split;[reflexivity|].\n                                exists x3.\n                                split;[reflexivity|].\n                                assumption.\n                            }\n                            {\n                                unfold fmap.\n                                with_strategy transparent [propset_fmap] unfold propset_fmap.   \n                                set_solver.\n                            }  \n                        }\n                    }\n                    {\n                        (* patt_or ϕ₁ ϕ₂ *)\n                        do 2 rewrite eval_or_simpl.\n                        rewrite IHszdata.\n                        { lia. }\n                        { exact HSData1. }\n                        { wf_auto2. }\n                        rewrite IHszdata.\n                        { lia. }\n                        { exact HSData2. }\n                        { wf_auto2. }\n                        clear.\n                        unfold_leibniz.\n                        unfold lift_set,fmap.\n                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                        set_solver.\n                    }\n                    {\n                        (* patt_and ϕ ψ *)\n                        do 2 rewrite eval_and_simpl.\n\n                        rename H into Hspred.\n                    \n                        destruct (classic (eval ρ ψ = ∅)).\n                        {\n                            rewrite IHszdata.\n                            { lia. }\n                            { exact HSData. }\n                            { wf_auto2. }\n                            clear HSData IHszdata. \n                            unfold_leibniz.\n                            specialize (IHszpred ψ ρ ltac:(lia) ltac:(assumption) ltac:(wf_auto2)).\n                            destruct IHszpred as [Hsp1 Hsp2].\n                            clear Hsp2.\n                            destruct Hsp1 as [Hsp11 Hsp12].\n                            specialize (Hsp12 H). clear Hsp11.\n                            unfold lift_set,fmap.\n                            with_strategy transparent [propset_fmap] unfold propset_fmap.\n                            set_solver.\n                        }\n                        {\n                            apply predicate_not_empty_iff_full in H.\n                            2: {\n                                apply SPred_is_predicate.\n                                2: { assumption. }\n                                {\n                                    clear -Hwf.\n                                    unfold patt_and,patt_or,patt_not in Hwf.\n                                    apply well_formed_imp_proj1 in Hwf.\n                                    apply well_formed_imp_proj2 in Hwf.\n                                    apply well_formed_imp_proj1 in Hwf.\n                                    wf_auto2.\n                                }\n                            }\n                            specialize (IHszpred ψ ρ ltac:(lia) ltac:(assumption) ltac:(wf_auto2)).\n                            specialize (IHszdata ϕ ρ ltac:(lia) HSData ltac:(wf_auto2)).\n\n                            destruct IHszpred as [Hsp1 Hsp2].\n                            clear Hsp1.\n                            destruct Hsp2 as [Hsp21 Hsp22]. clear Hsp21.\n                            specialize (Hsp22 H).\n                            rewrite IHszdata.\n                            rewrite H. rewrite Hsp22.\n                            unfold lift_set,fmap.\n                            with_strategy transparent [propset_fmap] unfold propset_fmap.\n                            clear.\n                            set_unfold.\n                            split; intros H.\n                            {\n                                destruct_and_ex!.\n                                subst.\n                                exists (inl x1).\n                                split.\n                                { reflexivity. }\n                                exists x1. split;[reflexivity|].\n                                split; done.\n                            }\n                            {\n                                destruct_and_ex!.\n                                subst.\n                                split;[|exact I].\n                                exists (inl x1).\n                                split;[reflexivity|].\n                                exists x1.\n                                split; done.\n                            }\n                        }\n                    }\n                    {\n                        (* patt_exists_of_sort (patt_sym s) ϕ *)\n                        unshelve(erewrite eval_exists_of_sort).\n                        3: { rewrite HSortImptDef. apply Mext_satisfies_definedness. }\n                        { intros. apply Mext_indec. assumption. }\n                        unshelve(erewrite eval_exists_of_sort).\n                        3: { rewrite HSortImptDef. assumption. }\n                        { intros. apply indec. assumption. }\n                        rewrite lift_set_fa_union.\n                        unfold_leibniz.\n                        unfold stdpp_ext.propset_fa_union.\n                        apply set_subseteq_antisymm.\n                        {\n                            apply elem_of_subseteq. intros x Hx.\n                            rewrite elem_of_PropSet. rewrite elem_of_PropSet in Hx.\n                            destruct Hx as [c Hc].\n                            destruct (Mext_indec _ H c ρ) as [Hin|Hnotin].\n                            {\n                                unfold Minterp_inhabitant in Hin.\n                                (* [c] comes from [Domain M] *)\n                                destruct c.\n                                {\n                                    exfalso.\n                                    rewrite eval_app_simpl in Hin.\n                                    do 2 rewrite eval_sym_simpl in Hin.\n                                    unfold app_ext in Hin. simpl in Hin.\n                                    unfold new_sym_interp,new_app_interp in Hin.\n                                    rewrite elem_of_PropSet in Hin.\n                                    destruct_and_ex!. repeat case_match; subst; auto; try congruence.\n                                    {\n                                        clear -H3.\n                                        unfold fmap in H3.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap in H3.\n                                        set_solver.\n                                    }\n                                    {\n                                        clear -H3. \n                                        unfold fmap in H3.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap in H3.\n                                        set_solver.\n                                    }\n                                }\n                                {\n                                    exfalso.\n                                    rewrite eval_app_simpl in Hin.\n                                    do 2 rewrite eval_sym_simpl in Hin.\n                                    unfold app_ext in Hin. simpl in Hin.\n                                    unfold new_sym_interp,new_app_interp in Hin.\n                                    rewrite elem_of_PropSet in Hin.\n                                    destruct_and_ex!. repeat case_match; subst; auto; try congruence.\n                                    {\n                                        clear -H3.\n                                        unfold fmap in H3.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap in H3.\n                                        set_solver.\n                                    }\n                                    {\n                                        clear -H3. \n                                        unfold fmap in H3.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap in H3.\n                                        set_solver.\n                                    }\n                                }\n                                destruct el.\n                                2: {\n                                    exfalso.\n                                    rewrite eval_app_simpl in Hin.\n                                    do 2 rewrite eval_sym_simpl in Hin.\n                                    unfold app_ext in Hin. simpl in Hin.\n                                    unfold new_sym_interp,new_app_interp in Hin.\n                                    rewrite elem_of_PropSet in Hin.\n                                    destruct_and_ex!. repeat case_match; subst; auto; try congruence.\n                                    {\n                                        clear -H3. \n                                        unfold fmap in H3.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap in H3.\n                                        set_solver.\n                                    }\n                                    {\n                                        clear -H2. \n                                        unfold fmap in H2.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap in H2.\n                                        set_solver.\n                                    }\n                                }\n                                rewrite update_evar_val_lift_val_comm in Hc.\n                                rewrite IHszdata in Hc.\n                                3: { wf_auto2. }\n                                2: { apply is_SData_evar_open. assumption. }\n                                1: { rewrite evar_open_size'. lia. }\n\n                                (* [x] comes from [Domain M] *)\n                                unfold lift_set,fmap in Hc.\n                                with_strategy transparent [propset_fmap] unfold propset_fmap in Hc.\n                                destruct x.\n                                {\n                                    exfalso.\n                                    clear -Hc.\n                                    set_solver.\n                                }\n                                {\n                                    exfalso.\n                                    clear -Hc.\n                                    set_solver.\n                                }\n                                destruct el.\n                                2: {\n                                    exfalso.\n                                    clear -Hc.\n                                     set_solver.\n                                }\n\n                                rewrite IHszdata in Hin.\n                                3: { wf_auto2. }\n                                2: { constructor. assumption. }\n                                1: { simpl. lia. }\n\n                                exists d.\n                                destruct (indec _ H d ρ) as [Hin'|Hnotin'].\n                                2: {\n                                    exfalso.\n                                    unfold Minterp_inhabitant in Hnotin'.\n                                    unfold lift_set,fmap in Hin.\n                                    with_strategy transparent [propset_fmap] unfold propset_fmap in Hin.\n                                    clear -Hin Hnotin'.\n                                    set_solver.\n                                }\n                                apply Hc.\n                            }\n                            {\n                                exfalso. clear -Hc. set_solver.\n                            }\n                        }\n                        {\n                            rewrite elem_of_subseteq.\n                            intros x Hx.\n                            rewrite elem_of_PropSet in Hx.\n                            destruct Hx as [c Hc].\n                            unfold lift_set,fmap in Hc.\n                            with_strategy transparent [propset_fmap] unfold propset_fmap in Hc.\n                            destruct x.\n                            {\n                                exfalso. clear -Hc. set_solver.\n                            }\n                            {\n                                exfalso. clear -Hc. set_solver.\n                            }\n                            destruct el.\n                            2: {\n                                exfalso. clear -Hc. set_solver.\n                            }\n                            rewrite elem_of_PropSet in Hc.\n                            destruct Hc as [a [Ha Ha'] ].\n                            destruct a.\n                            2: {\n                                inversion Ha.\n                            }\n                            inversion Ha. clear Ha. subst.\n                            rewrite elem_of_PropSet in Ha'.\n                            destruct Ha' as [a [Ha Ha'] ].\n                            inversion Ha. clear Ha. subst.\n                            rewrite elem_of_PropSet.\n                            destruct (indec _ H c ρ).\n                            2: {\n                                exfalso. clear -Ha'. set_solver.\n                            }\n                            exists (lift_value c).\n                            rewrite update_evar_val_lift_val_comm.\n                            destruct (Mext_indec _ H (lift_value c) ρ) as [Hin | Hnotin].\n                            {\n                                rewrite IHszdata.\n                                3: { wf_auto2. }\n                                2: { apply is_SData_evar_open. assumption. }\n                                1: { rewrite evar_open_size'. lia. }\n                                unfold lift_set,fmap.\n                                with_strategy transparent [propset_fmap] unfold propset_fmap.\n                                rewrite elem_of_PropSet.\n                                exists (inl a).\n                                split;[reflexivity|].\n                                rewrite elem_of_PropSet.\n                                exists a.\n                                split;[reflexivity|].\n                                apply Ha'.\n                            }\n                            {\n                                exfalso. rename e into Hin.\n                                unfold Minterp_inhabitant in Hin, Hnotin.\n                                rewrite IHszdata in Hnotin.\n                                3: { wf_auto2. }\n                                2: { constructor. assumption. }\n                                1: { simpl. lia. }\n                                clear -Hin Hnotin.\n                                unfold lift_value,lift_set,fmap in Hnotin.\n                                with_strategy transparent [propset_fmap] unfold propset_fmap in Hnotin.\n                                set_solver.\n                            }\n                        }\n                    }\n                    {\n                        (* patt_mu (patt_sym s) ϕ *)\n                        do 2 rewrite eval_mu_simpl.\n                        cbn zeta.\n                        match goal with\n                        | [ |- (Lattice.LeastFixpointOf ?fF = lift_set (Lattice.LeastFixpointOf ?fG))] =>\n                            remember fF as F; remember fG as G\n                        end.\n\n                        symmetry.\n                        assert (HmonoF: @Lattice.MonotonicFunction\n                            (propset Carrier)\n                            (Lattice.PropsetOrderedSet Carrier) F).\n                        {\n                            subst F.\n                            pose proof (Hmono := @is_monotonic Σ Mext).\n                            simpl in Hmono.\n                            apply Hmono.\n                            {\n                                unfold well_formed in Hwf. simpl in Hwf.\n                                destruct_and!. split_and!; assumption.\n                            }\n                            {\n                                apply set_svar_fresh_is_fresh.\n                            }\n                        }\n                        assert (HmonoG: @Lattice.MonotonicFunction\n                            (propset (Domain M))\n                            (Lattice.PropsetOrderedSet (Domain M)) G).\n                        {\n                            subst G.\n                            apply is_monotonic.\n                            { unfold well_formed in Hwf. simpl in Hwf. wf_auto2. }\n                            { apply set_svar_fresh_is_fresh. }\n                        }\n                        set (Lattice.PowersetLattice (Domain M)) as L in |-.\n                        set (Lattice.PowersetLattice (Domain Mext)) as L' in |-.\n                        assert (HGmuG: G (@Lattice.LeastFixpointOf _ _ L G) = (@Lattice.LeastFixpointOf _ _ L G)).\n                        {\n                            apply Lattice.LeastFixpoint_fixpoint. apply HmonoG.\n                        }\n                        apply Lattice.LeastFixpoint_unique_2.\n                        {\n                            exact HmonoF.\n                        }\n                        {\n                            fold L.\n                            rewrite -[x in (_ = (lift_set x))]HGmuG.\n                            rewrite HeqF.\n                            rewrite update_svar_val_lift_set_comm.\n                            rewrite IHszdata.\n                            {\n                                rewrite svar_open_size'. lia.\n                            }\n                            {\n                                apply is_SData_svar_open. assumption.\n                            }\n                            {\n                                wf_auto2.\n                            }\n                            rewrite HeqG.\n                            reflexivity.\n                        }\n                        {\n                            set (λ (A : propset (Domain Mext)), PropSet (λ (m : Domain M), lift_value m ∈ A)) as strip.\n                            set (λ A, lift_set (eval (update_svar_val (fresh_svar ϕ) (strip A) ρ) (ϕ^{svar: 0 ↦ (fresh_svar ϕ)}))) as G'.\n\n                            assert (Hstripmono: forall x y, x ⊆ y -> strip x ⊆ strip y).\n                            {\n                                intros x y Hxy.\n                                unfold strip. unfold lift_value.\n                                clear -Hxy. set_solver.\n                            }\n\n                            assert (Hstriplift: forall X, strip (lift_set X) = X).\n                            {\n                                intros X. unfold strip,lift_set,lift_value,fmap.\n                                with_strategy transparent [propset_fmap] unfold propset_fmap.\n                                clear. set_solver.\n                            }\n\n                            assert (HmonoG' : @Lattice.MonotonicFunction _ (Lattice.PropsetOrderedSet (Domain Mext)) G').\n                            {\n                                unfold Lattice.MonotonicFunction.\n                                intros x y Hxy.\n                                unfold G'.\n                                simpl.\n                                apply lift_set_mono.\n                                simpl in Hxy.\n                                rewrite HeqG in HmonoG.\n                                unfold Lattice.MonotonicFunction in HmonoG.\n                                simpl in HmonoG.\n                                specialize (HmonoG (strip x) (strip y)).\n                                apply HmonoG.\n                                apply Hstripmono.\n                                apply Hxy.\n                            }\n\n                            assert (Hls: lift_set (@Lattice.LeastFixpointOf _ _ L G) = (@Lattice.LeastFixpointOf _ _ L' G')).\n                            {\n                                assert (G'liftlfpG: G' (lift_set (@Lattice.LeastFixpointOf _ _ L G)) =\n                                    lift_set (@Lattice.LeastFixpointOf _ _ L G)).\n                                {\n                                    rewrite <- HGmuG at 2.\n                                    unfold G'.\n                                    rewrite Hstriplift.\n                                    f_equal.\n                                    rewrite HeqG.\n                                    reflexivity.\n                                }\n                                apply Lattice.LeastFixpoint_unique_2.\n                                {\n                                    exact HmonoG'.\n                                }\n                                {\n                                    apply G'liftlfpG.\n                                }\n                                {\n                                    intros A HA.\n                                    rewrite -HA.\n                                    unfold G'.\n                                    simpl.\n                                    apply lift_set_mono.\n                                    pose proof (Htmp := Lattice.LeastFixpoint_LesserThanPrefixpoint _ _ L G).\n                                    simpl in Htmp. apply Htmp. clear Htmp.\n                                    replace (eval (update_svar_val (fresh_svar ϕ) (strip A) ρ)\n                                    (ϕ^{svar: 0 ↦ (fresh_svar ϕ)}))\n                                    with (G (strip A)) by (subst; reflexivity).\n                                    apply HmonoG. simpl.\n                                    rewrite <- HA at 2.\n                                    unfold G'.\n                                    rewrite HeqG.\n                                    rewrite Hstriplift.\n                                    apply reflexivity.\n                                }\n                            }\n                            (*replace (propset Carrier) with (propset (Domain Mext)) by reflexivity.*)\n                            intros A HA.\n                            rewrite Hls.\n                            apply Lattice.LeastFixpoint_LesserThanPrefixpoint.\n                            simpl.\n                            rewrite <- HA at 2.\n                            unfold G'.\n                            rewrite HeqF.\n                            assert (Hliftstrip: lift_set (strip A) ⊆ A).\n                            {\n                                clear.\n                                unfold lift_set,strip,lift_value,fmap.\n                                with_strategy transparent [propset_fmap] unfold propset_fmap.\n                                set_solver.\n                            }\n\n                            assert (@eval Σ Mext (update_svar_val (fresh_svar ϕ) (lift_set (strip A)) (lift_val ρ)) (ϕ^{svar: 0 ↦ (fresh_svar ϕ)})\n                            ⊆  @eval Σ Mext (update_svar_val (fresh_svar ϕ) A (lift_val ρ)) (ϕ^{svar: 0 ↦ (fresh_svar ϕ)})).\n                            {\n                                apply is_monotonic.\n                                { unfold well_formed in Hwf. destruct_and!. assumption. }\n                                { apply set_svar_fresh_is_fresh. }\n                                apply Hliftstrip.\n                            }\n                            eapply transitivity.\n                            2: { apply H. }\n                            rewrite update_svar_val_lift_set_comm.\n                            rewrite IHszdata.\n                            { rewrite svar_open_size'. lia. }\n                            { apply is_SData_svar_open. assumption. }\n                            { wf_auto2. }\n                            apply reflexivity.\n                        }\n                    }\n                }\n                {   (* preservation of predicates *)\n                    intros ψ ρ Hszϕ HSPred Hwf.\n                    destruct HSPred; simpl in Hszϕ.\n                    {\n                        (* patt_bott *)\n                        rewrite eval_bott_simpl.\n                        rewrite eval_bott_simpl.\n                        split.\n                        {\n                            split; auto.\n                        }\n                        {\n                            split; intros H; exfalso; clear -H.\n                            {\n                                apply full_impl_not_empty in H; unfold Empty in H; contradiction.\n                            }\n                            {\n                                apply full_impl_not_empty in H; unfold Empty in H; contradiction.\n                            }\n                        }\n                    }\n                    {\n                        (* patt_defined ϕ *)\n                        unfold patt_defined.\n                        do 2 rewrite eval_app_simpl.\n                        do 2 rewrite eval_sym_simpl.\n                        rewrite IHszdata.\n                        { lia. }\n                        { assumption. }\n                        { wf_auto2. }\n                        Arguments Domain : simpl never.\n                        unfold app_ext.\n                        simpl.\n                        assert (Htmp: new_sym_interp (Definedness_Syntax.inj definedness) = {[cdef]}).\n                        {\n                            unfold new_sym_interp.\n                            repeat case_match.\n                            { reflexivity. }\n                            { contradiction. }\n                            { contradiction. }\n                        }\n                        rewrite Htmp.\n                        unfold new_app_interp.\n                        unfold_leibniz.\n                        destruct (classic (eval ρ ϕ = ∅)) as [Hempty|Hnonempty].\n                        {\n                            rewrite Hempty.\n                            split.\n                            {\n                                split.\n                                {\n\n                                    intros H'.\n                                    apply set_subseteq_antisymm.\n                                    2: {\n                                        clear. set_solver.\n                                    }\n                                    {\n                                        rewrite set_equiv_subseteq in H'.\n                                        destruct H' as [H' _].\n                                        rewrite elem_of_subseteq in H'.\n                                        rewrite elem_of_subseteq.\n                                        intros x.\n                                        rewrite elem_of_PropSet.\n                                        intros [le [re H''] ].\n                                        specialize (H' (lift_value x)).\n                                        exfalso.\n                                        rewrite elem_of_PropSet in H'.\n                                        cut (@elem_of _ (propset (@Domain Σ Mext)) _ (lift_value x) (@empty (propset (@Domain _ Mext)) _)).\n                                        {\n                                            intros Hcontra. clear -Hcontra. set_solver.\n                                        }\n                                        apply H'. clear H'.\n                                        exists cdef.\n                                        destruct H'' as [H''1 [H''2 H''3] ].\n                                        exfalso. clear -H''2.\n                                        set_solver.\n                                    }\n                                }\n                                {\n                                    intros H'.\n                                    rewrite set_equiv_subseteq.\n                                    rewrite elem_of_subseteq.\n                                    split.\n                                    2: {\n                                        clear. set_solver.\n                                    }\n                                    intros x.\n                                    rewrite elem_of_PropSet.\n                                    rewrite set_equiv_subseteq in H'.\n                                    destruct H' as [H' _].\n                                    rewrite elem_of_subseteq in H'.\n                                    intros HContra.\n                                    destruct HContra as [le [re [Hle [HContra Hrest] ] ] ].\n                                    exfalso. clear -HContra.\n                                    unfold lift_set in HContra.\n                                    unfold fmap in HContra.\n                                    with_strategy transparent [propset_fmap] unfold propset_fmap in HContra.\n                                    set_solver.\n                                }\n                            }\n                            {\n                                split.\n                                {\n                                    intros H'.\n                                    rewrite set_equiv_subseteq.\n                                    split.\n                                    {\n                                        clear. set_solver.\n                                    }\n                                    rewrite elem_of_subseteq.\n                                    intros x Hx.\n                                    rewrite set_equiv_subseteq in H'.\n                                    destruct H' as [_ H'2].\n                                    rewrite elem_of_subseteq in H'2.\n                                    specialize (H'2 (lift_value x)).\n                                    feed specialize H'2.\n                                    {\n                                        clear. set_solver.\n                                    }\n                                    rewrite elem_of_PropSet in H'2.\n                                    destruct H'2 as [le [re [Hle [Hre Hmatch] ] ] ].\n                                    exfalso. clear -Hre.\n                                    unfold lift_set in Hre.\n                                    unfold fmap in Hre.\n                                    with_strategy transparent [propset_fmap] unfold propset_fmap in Hre.\n                                    set_solver.\n                                }\n                                {\n                                    intros H'.\n                                    rewrite set_equiv_subseteq.\n                                    rewrite set_equiv_subseteq in H'.\n                                    destruct H' as [_ H'].\n                                    rewrite elem_of_subseteq in H'.\n                                    rewrite elem_of_subseteq.\n                                    split.\n                                    {\n                                        intros x H''.\n                                        clear. set_solver.\n                                    }\n                                    {\n                                        rewrite elem_of_subseteq.\n                                        intros x Hx.\n                                        rewrite elem_of_PropSet.\n                                        specialize (H' (@stdpp.base.inhabitant (@Domain _ M) (@Domain_inhabited _ M))).\n                                        feed specialize H'.\n                                        {\n                                            clear. set_solver.\n                                        }\n                                        rewrite elem_of_PropSet in H'.\n                                        destruct H' as [le [re [H'1 [H'2 H'3] ] ] ].\n                                        exfalso. clear -H'2.\n                                        set_solver.\n                                    }\n                                }\n                            }\n                        }\n                        {\n                            split.\n                            {\n                                split.\n                                {\n                                    intros H'.\n                                    rewrite set_equiv_subseteq in H'.\n                                    rewrite elem_of_subseteq in H'.\n                                    destruct H' as [H'1 _].\n                                    rewrite set_equiv_subseteq.\n                                    split.\n                                    {\n                                        rewrite elem_of_subseteq.\n                                        intros x Hx.\n                                        cut (@elem_of (@Domain Σ Mext) (propset (@Domain Σ Mext))\n                                        (@propset_elem_of (@Domain Σ Mext)) (lift_value x)\n                                        (@empty (propset (@Domain Σ Mext)) (@propset_empty (@Domain Σ Mext)))).\n                                        {\n                                            intros HContra.\n                                            clear -HContra.\n                                            set_solver.\n                                        }\n                                        apply H'1.\n                                        rewrite elem_of_PropSet in Hx.\n                                        destruct Hx as [le [re [Hx1 [Hx2 Hx3] ] ] ].\n                                        rewrite elem_of_PropSet.\n                                        exists cdef. exists (lift_value re).\n                                        split.\n                                        { clear. set_solver. }\n                                        split.\n                                        2: { clear. set_solver. }\n                                        clear -Hx2.\n                                        unfold lift_value,lift_set,fmap.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                                        set_solver.\n                                    }\n                                    {\n                                        clear. set_solver.\n                                    }\n                                }\n                                {\n                                    intros H'.\n                                    rewrite set_equiv_subseteq.\n                                    split.\n                                    {\n                                        rewrite elem_of_subseteq.\n                                        intros x Hx.\n                                        rewrite elem_of_PropSet in Hx.\n                                        destruct Hx as [le [re [Hx1 [Hx2 Hx3] ] ] ].\n                                        rewrite set_equiv_subseteq in H'.\n                                        destruct H' as [H' _].\n                                        rewrite elem_of_subseteq in H'.\n                                        rewrite elem_of_singleton in Hx1. subst.\n                                        repeat case_match; subst; auto.\n                                        destruct re.\n                                        {\n                                            unfold lift_set,fmap in Hx2.\n                                            with_strategy transparent [propset_fmap] unfold propset_fmap in Hx2.\n                                            exfalso. clear -Hx2. set_solver.\n                                        }\n                                        {\n                                            unfold lift_set,fmap in Hx2.\n                                            with_strategy transparent [propset_fmap] unfold propset_fmap in Hx2.\n                                            exfalso. clear -Hx2. set_solver.\n                                        }\n                                        destruct el.\n                                        2: {\n                                            unfold lift_set,fmap in Hx2.\n                                            with_strategy transparent [propset_fmap] unfold propset_fmap in Hx2.\n                                            exfalso. clear -Hx2. set_solver.\n                                        }\n                                        exfalso. specialize (H' d).\n                                        feed specialize H'.\n                                        {\n                                            clear H' Hx3.\n                                            rewrite elem_of_PropSet.\n\n                                            unfold lift_set,fmap in Hx2.\n                                            with_strategy transparent [propset_fmap] unfold propset_fmap in Hx2.\n                                            rewrite elem_of_PropSet in Hx2.\n                                            destruct Hx2 as [a [Hx21 Hx22] ].\n                                            inversion Hx21. clear Hx21. subst.\n                                            rewrite elem_of_PropSet in Hx22.\n                                            destruct Hx22 as [a [Hx21 Hx22] ].\n                                            inversion Hx21. clear Hx21. subst.\n\n                                            pose proof (Hel := @satisfies_definedness_implies_has_element_for_every_element Σ _ M).\n                                            feed specialize Hel.\n                                            {\n                                                assumption.\n                                            }\n                                            specialize (Hel a a).\n                                            destruct Hel as [z [Hz1 Hz2] ].\n                                            exists z. exists a.\n                                            split.\n                                            { exact Hz1. }\n                                            split.\n                                            { exact Hx22. }\n                                            exact Hz2.\n                                        }\n                                        {\n                                            clear -H'. set_solver.\n                                        }\n                                    }\n                                    {\n                                        clear. set_solver.\n                                    }\n                                }\n                            }\n                            {\n                                split.\n                                {\n                                    intros H'.\n                                    rewrite set_equiv_subseteq in H'.\n                                    rewrite set_equiv_subseteq.\n                                    split.\n                                    {\n                                        clear. set_solver.\n                                    }\n                                    {\n                                        rewrite elem_of_subseteq.\n                                        rewrite elem_of_subseteq in H'.\n                                        intros x Hx.\n                                        rewrite elem_of_PropSet.\n                                        destruct H' as [_ H'].\n                                        rewrite elem_of_subseteq in H'.\n                                        specialize (H' (lift_value x)).\n                                        specialize (H' I).\n                                        rewrite elem_of_PropSet in H'.\n                                        destruct H' as [le [re [Hle [Hre H'] ] ] ].\n                                        rewrite elem_of_singleton in Hle. subst le.\n                                        unfold lift_set,fmap in Hre.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap in Hre.\n                                        rewrite elem_of_PropSet in Hre.\n                                        destruct Hre as [a [Ha Hre] ].\n                                        subst re.\n                                        rewrite elem_of_PropSet in Hre.\n                                        destruct Hre as [a0 [Ha0 Hre] ].\n                                        subst a.\n                                        pose proof (Hel := @satisfies_definedness_implies_has_element_for_every_element Σ _ M).\n                                        feed specialize Hel.\n                                        {\n                                            assumption.\n                                        }\n                                        specialize (Hel a0 x).\n                                        destruct Hel as [z [Hz1 Hz2] ].\n                                        exists z. exists a0.\n                                        split.\n                                        { exact Hz1. }\n                                        split.\n                                        { exact Hre. }\n                                        exact Hz2.\n                                    }\n                                }\n                                {\n                                    intros H'.\n                                    rewrite set_equiv_subseteq in H'.\n                                    destruct H' as [_ H'].\n                                    rewrite elem_of_subseteq in H'.\n                                    rewrite set_equiv_subseteq.\n                                    split.\n                                    {\n                                        clear. set_solver.\n                                    }\n                                    {\n                                        rewrite elem_of_subseteq.\n                                        intros x Hx.\n                                        rewrite elem_of_PropSet.\n                                        exists cdef.\n                                        assert (Hex : exists el, el ∈ eval ρ ϕ).\n                                        {\n                                            clear -Hnonempty.\n                                            apply NNPP. intros HContra.\n                                            set_solver.\n                                        }\n                                        destruct Hex as [el Hel].\n                                        exists (lift_value el).\n                                        split.\n                                        { clear. set_solver. }\n                                        split.\n                                        2: { clear. set_solver. }\n                                        unfold lift_value,lift_set,fmap.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                                        clear -Hel. set_solver.\n                                    }\n                                }\n                            }\n                        }\n                    }\n                    {\n                        (* patt_equal ϕ₁ ϕ₂ *)\n                        rewrite equal_iff_interpr_same.\n                        1: { apply Mext_satisfies_definedness. }\n                        rewrite equal_iff_interpr_same.\n                        1: { apply M_def. }\n                        rewrite not_equal_iff_not_interpr_same_1.\n                        1: { apply Mext_satisfies_definedness. }\n                        rewrite not_equal_iff_not_interpr_same_1.\n                        1: { apply M_def. }\n                        rewrite IHszdata.\n                        { lia. }\n                        { assumption. }\n                        { wf_auto2. }\n                        rewrite IHszdata.\n                        { lia. }\n                        { assumption. }\n                        { wf_auto2. }\n                        rewrite lift_set_injective.\n                        tauto.\n                    }\n                    {\n                        (* patt_subseteq ϕ₁ ϕ₂ *)\n                        rewrite subseteq_iff_interpr_subseteq.\n                        1: { apply Mext_satisfies_definedness. }\n                        rewrite subseteq_iff_interpr_subseteq.\n                        1: { apply M_def. }\n                        rewrite not_subseteq_iff_not_interpr_subseteq_1.\n                        1: { apply Mext_satisfies_definedness. }\n                        rewrite not_subseteq_iff_not_interpr_subseteq_1.\n                        1: { apply M_def. }\n                        rewrite IHszdata.\n                        { lia. }\n                        { assumption. }\n                        { wf_auto2. }\n                        rewrite IHszdata.\n                        { lia. }\n                        { assumption. }\n                        { wf_auto2. }\n                        rewrite lift_set_mono.\n                        tauto.\n                    }\n                    {\n                        (* patt_impl ψ₁ ψ₂*)\n                        do 2 rewrite eval_imp_simpl.\n                        pose proof (IH1 := IHszpred ϕ₁ ρ).\n                        feed specialize IH1.\n                        { lia. }\n                        { assumption. }\n                        { wf_auto2. }\n                        destruct IH1 as [IH11 IH12].\n                        pose proof (IH2 := IHszpred ϕ₂ ρ).\n                        feed specialize IH2.\n                        { lia. }\n                        { assumption. }\n                        { wf_auto2. }\n                        destruct IH2 as [IH21 IH22].\n                        split.\n                        {\n                            split; intros H.\n                            {\n                                rewrite empty_union_L in H.\n                                destruct H as [H1 H2].\n                                rewrite empty_union_L.\n                                split.\n                                {\n                                    rewrite stdpp_ext.complement_empty_iff_full in H1.\n                                    rewrite stdpp_ext.complement_empty_iff_full.\n                                    rewrite -IH12.\n                                    assumption.\n                                }\n                                {\n                                    rewrite -IH21.\n                                    assumption.\n                                }\n                            }\n                            {\n                                rewrite empty_union_L in H.\n                                destruct H as [H1 H2].\n                                rewrite empty_union_L.\n                                split.\n                                {\n                                    rewrite stdpp_ext.complement_empty_iff_full.\n                                    rewrite stdpp_ext.complement_empty_iff_full in H1.\n                                    rewrite IH12.\n                                    exact H1.\n                                }\n                                {\n                                    rewrite IH21.\n                                    exact H2.\n                                }\n                            }\n                        }\n                        {\n                            apply SPred_is_predicate in HSPred1.\n                            2: {\n                                unfold well_formed,well_formed_closed in Hwf.\n                                simpl in Hwf.\n                                destruct_and!.\n                                assumption.\n                            }\n                            apply SPred_is_predicate in HSPred2.\n                            2: {\n                                unfold well_formed,well_formed_closed in Hwf.\n                                simpl in Hwf.\n                                destruct_and!.\n                                assumption.\n                            }\n                            specialize (HSPred1 ρ).\n                            specialize (HSPred2 ρ).\n                            split; intros H.\n                            {\n                                destruct HSPred1 as [H1T|H1B],\n                                HSPred2 as [H2T|H2B].\n                                {\n                                    rewrite H2T.\n                                    clear.\n                                    set_solver.\n                                }\n                                {\n                                    rewrite H2B.\n                                    apply IH21 in H2B.\n                                    rewrite H2B in H.\n                                    assert (H': eval (lift_val ρ) ϕ₁  = ∅).\n                                    {\n                                        clear -H. set_solver.\n                                    }\n                                    rewrite IH11 in H'.\n                                    rewrite H'.\n                                    clear. set_solver.\n                                }\n                                {\n                                    rewrite H1B. rewrite H2T.\n                                    clear. set_solver.\n                                }\n                                {\n                                    rewrite H1B. rewrite H2B. clear. set_solver.\n                                }\n                            }\n                            {\n                                destruct HSPred1 as [H1T|H1B],\n                                HSPred2 as [H2T|H2B].\n                                {\n                                    apply IH12 in H1T.\n                                    rewrite H1T.\n                                    apply IH22 in H2T.\n                                    rewrite H2T.\n                                    clear.\n                                    set_solver.\n                                }\n                                {\n                                    rewrite H1T in H.\n                                    rewrite H2B in H.\n                                    exfalso. clear -H.\n                                    pose proof (Hinh := Domain_inhabited M).\n                                    inversion Hinh.\n                                    set_solver.\n                                }\n                                {\n                                    apply IH11 in H1B.\n                                    rewrite H1B.\n                                    apply IH22 in H2T.\n                                    rewrite H2T.\n                                    clear.\n                                    set_solver.\n                                }\n                                {\n                                    apply IH11 in H1B.\n                                    rewrite H1B.\n                                    apply IH21 in H2B.\n                                    rewrite H2B.\n                                    clear.\n                                    set_solver.\n                                }\n                            }\n                        }\n                    }\n                    {\n                        unshelve (erewrite eval_exists_of_sort).\n                        3: { rewrite HSortImptDef. apply Mext_satisfies_definedness. }\n                        1: { intros m. apply Mext_indec. assumption. }\n\n                        unshelve (erewrite eval_exists_of_sort).\n                        3: { rewrite HSortImptDef. assumption. }\n                        1: { intros m. apply indec. assumption. }\n\n                        do 2 rewrite stdpp_ext.propset_fa_union_empty.\n\n                        specialize (IHszpred (ϕ^{evar: 0 ↦ fresh_evar ϕ})).\n                        split.\n                        {\n                            split; intros H'; intros c.\n                            {\n                                destruct (indec _ H c ρ) as [Hin|Hnotin].\n                                2: { reflexivity. }\n                                specialize (H' (lift_value c)).\n                                rewrite update_evar_val_lift_val_comm in H'.\n                                specialize (IHszpred (update_evar_val (fresh_evar ϕ) c ρ)).\n                                feed specialize IHszpred.\n                                {\n                                    rewrite evar_open_size'. lia.\n                                }\n                                {\n                                    apply is_SPredicate_evar_open. assumption.\n                                }\n                                {\n                                    wf_auto2.\n                                }\n                                destruct IHszpred as [IH1 IH2].\n                                destruct (Mext_indec _ H (lift_value c) ρ) as [Hin'|Hnotin'].\n                                {\n                                    apply IH1 in H'. apply H'.\n                                }\n                                {\n                                    exfalso.\n                                    unfold Minterp_inhabitant in Hin,Hnotin'.\n                                    rewrite eval_app_simpl in Hin.\n                                    rewrite eval_app_simpl in Hnotin'.\n                                    do 2 rewrite eval_sym_simpl in Hin.\n                                    do 2 rewrite eval_sym_simpl in Hnotin'.\n                                    unfold app_ext in Hin,Hnotin'.\n                                    unfold lift_value in Hnotin'. simpl in Hnotin'.\n                                    unfold new_sym_interp in Hnotin'.\n                                    rewrite elem_of_PropSet in Hnotin'.\n                                    unfold is_not_core_symbol,is_core_symbol in H.\n                                    repeat case_match; subst; auto; try contradiction.\n                                    apply Hnotin'.\n                                    clear -Hin.\n                                    rewrite elem_of_PropSet in Hin.\n                                    destruct Hin as [le [re [Hle [Hre Hin] ] ] ].\n                                    exists cinh. exists (cel (inl re)).\n                                    split.\n                                    { clear. set_solver. }\n                                    split.\n                                    {\n                                        unfold fmap.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                                        rewrite elem_of_PropSet.\n                                        exists (inl re).\n                                        split;[reflexivity|].\n                                        rewrite elem_of_PropSet.\n                                        exists re.\n                                        split;[reflexivity|].\n                                        assumption.\n                                    }\n                                    unfold new_app_interp.\n                                    unfold fmap.\n                                    with_strategy transparent [propset_fmap] unfold propset_fmap.\n                                    rewrite elem_of_PropSet.\n                                    exists (inl c).\n                                    split;[reflexivity|].\n                                    rewrite elem_of_PropSet.\n                                    exists c.\n                                    split;[reflexivity|].\n                                    unfold app_ext.\n                                    rewrite elem_of_PropSet.\n                                    exists le. exists re.\n                                    split;[assumption|].\n                                    split;[(clear; set_solver)|].\n                                    assumption.\n                                }\n                            }\n                            {\n                                destruct (Mext_indec _ H c ρ) as [Hin|Hnotin].\n                                {\n                                    unfold Minterp_inhabitant in Hin.\n                                    rewrite eval_app_simpl in Hin.\n                                    do 2 rewrite eval_sym_simpl in Hin.\n                                    unfold app_ext in Hin.\n                                    rewrite elem_of_PropSet in Hin.\n                                    destruct Hin as [le [re [Hle [Hre Hin] ] ] ].\n                                    simpl in Hle,Hre,Hin.\n                                    unfold is_not_core_symbol,is_core_symbol in H.\n                                    unfold new_app_interp in Hin.\n                                    unfold new_sym_interp in Hle,Hre.\n                                    repeat case_match; subst; try contradiction; try congruence.\n                                    2: {\n                                        exfalso. clear -Hre.\n                                        unfold fmap in Hre.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap in Hre.\n                                        set_solver.\n                                    }\n                                    unfold fmap in Hin.\n                                    with_strategy transparent [propset_fmap] unfold propset_fmap in Hin.\n                                    destruct c.\n                                    {\n                                        exfalso. clear -Hin.  set_solver.\n                                    }\n                                    {\n                                        exfalso. clear -Hin.  set_solver.\n                                    }\n                                    destruct el.\n                                    2: {\n                                        exfalso. clear -Hin.  set_solver.\n                                    }\n                                    rewrite update_evar_val_lift_val_comm.\n                                    clear -IHszpred Hszϕ HSPred Hwf H' Hin Hre.\n                                    specialize (IHszpred (update_evar_val (fresh_evar ϕ) d0 ρ)).\n                                    feed specialize IHszpred.\n                                    {\n                                        rewrite evar_open_size'. lia.\n                                    }\n                                    {\n                                        apply is_SPredicate_evar_open. assumption.\n                                    }\n                                    {\n                                        wf_auto2.\n                                    }\n                                    destruct IHszpred as [IH1 IH2].\n                                    rewrite IH1.\n                                    specialize (H' d0).\n                                    destruct (indec _ H d0 ρ) as [Hin'|Hnotin'].\n                                    {\n                                        apply H'.\n                                    }\n                                    {\n                                        exfalso. apply Hnotin'. clear Hnotin'.\n                                        unfold Minterp_inhabitant.\n                                        rewrite eval_app_simpl.\n                                        do 2 rewrite eval_sym_simpl.\n                                        rewrite elem_of_PropSet in Hin.\n                                        destruct Hin as [a [Ha Hin] ].\n                                        inversion Ha. clear Ha. subst.\n                                        rewrite elem_of_PropSet in Hin.\n                                        destruct Hin as [a [Ha Hin] ].\n                                        inversion Ha. clear Ha. subst.\n                                        unfold app_ext in Hin.\n                                        rewrite elem_of_PropSet in Hin.\n                                        destruct Hin as [le [re [Hle' [Hre' Hin] ] ] ].\n                                        rewrite elem_of_singleton in Hre'. subst re.\n                                        unfold app_ext.\n                                        rewrite elem_of_PropSet.\n                                        unfold fmap in Hre.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap in Hre.\n                                        rewrite elem_of_PropSet in Hre.\n                                        destruct Hre as [a' [Ha' Hre'] ].\n                                        rewrite elem_of_PropSet in Hre'.\n                                        destruct Hre' as [a'' [Ha'' Hre'] ].\n                                        subst.\n                                        inversion Ha'. clear Ha'. subst.\n                                        exists le. exists a''.\n                                        split;[assumption|].\n                                        split;assumption.\n                                    }\n                                }\n                                reflexivity.\n                            }\n                        }\n                        {\n                            do 2 rewrite stdpp_ext.propset_fa_union_full.\n                            pose proof (HSPred' := HSPred).\n                            apply SPred_is_pre_predicate in HSPred'.\n                            apply (@M_pre_predicate_evar_open Σ M ϕ (fresh_evar ϕ)) in HSPred'.\n                            specialize (HSPred' 0).\n                            apply closed_M_pre_pre_predicate_is_M_predicate in HSPred'.\n                            2: {\n                                unfold well_formed,well_formed_closed in Hwf. simpl in Hwf.\n                                destruct_and!.\n                                wf_auto2.\n                            }\n                            split; intros H' t.\n                            {\n                                specialize (H' stdpp.base.inhabitant).\n                                destruct H' as [c Hc].\n                                destruct (Mext_indec _ H c ρ) as [Hin|Hnotin].\n                                {\n                                    unfold Minterp_inhabitant in Hin.\n                                    rewrite eval_app_simpl in Hin.\n                                    do 2 rewrite eval_sym_simpl in Hin.\n                                    unfold app_ext in Hin.\n                                    rewrite elem_of_PropSet in Hin.\n                                    simpl in Hin.\n                                    destruct Hin as [le [re [Hle [Hre Hin] ] ] ].\n                                    unfold is_not_core_symbol,is_core_symbol in H.\n                                    unfold new_sym_interp in Hle,Hre.\n                                    unfold new_app_interp in Hin.\n                                    repeat case_match; subst; try contradiction; try congruence;\n                                    unfold fmap in Hre;\n                                    with_strategy transparent [propset_fmap] unfold propset_fmap in Hre;\n                                    rewrite elem_of_PropSet in Hre;\n                                    destruct Hre as [amr [Hamr Hamr'] ];\n                                    inversion Hamr; clear Hamr; subst;\n                                    rewrite elem_of_PropSet in Hamr';\n                                    destruct Hamr' as [amr' [Hamr'' Hamr'] ];\n                                    inversion Hamr''; clear Hamr''; subst.\n                                    unfold fmap in Hin.\n                                    with_strategy transparent [propset_fmap] unfold propset_fmap in Hin.\n                                    rewrite elem_of_PropSet in Hin.\n                                    destruct Hin as [a [Htmp Ha] ].\n                                    subst.\n                                    rewrite elem_of_PropSet in Ha.\n                                    destruct Ha as [a0 [Htmp Ha0] ].\n                                    subst.\n                                    unfold app_ext in Ha0.\n                                    rewrite elem_of_PropSet in Ha0.\n                                    destruct Ha0 as [le' [re' [Hle' [Hre' Hle're'] ] ] ].\n                                    rewrite elem_of_singleton in Hre'. subst re'.\n                                    exists a0.\n                                    destruct (indec _ H a0 ρ) as [Hin'|Hnotin'].\n                                    2: {\n                                        exfalso. apply Hnotin'.\n                                        unfold Minterp_inhabitant.\n                                        rewrite eval_app_simpl.\n                                        do 2 rewrite eval_sym_simpl.\n                                        unfold app_ext.\n                                        rewrite elem_of_PropSet.\n                                        exists le'. exists amr'.\n                                        repeat split; try assumption.\n                                    }\n                                    {\n                                        clear -IHszpred Hc Hwf Hszϕ HSPred HSPred'.\n                                        rewrite update_evar_val_lift_val_comm in Hc.\n                                        specialize (IHszpred (update_evar_val (fresh_evar ϕ) a0 ρ)).\n                                        feed specialize IHszpred.\n                                        {\n                                            rewrite evar_open_size'. lia.\n                                        }\n                                        {\n                                            apply is_SPredicate_evar_open. assumption.\n                                        }\n                                        {\n                                            wf_auto2.\n                                        }\n                                        destruct IHszpred as [IH1 IH2].\n                                        specialize (HSPred' (update_evar_val (fresh_evar ϕ) a0 ρ)).\n                                        destruct HSPred' as [HFull|HEmpty].\n                                        {\n                                            rewrite HFull. clear. set_solver.\n                                        }\n                                        {\n                                            apply IH1 in HEmpty.\n                                            exfalso.\n                                            rewrite HEmpty in Hc.\n                                            clear -Hc.\n                                            set_solver.\n                                        }\n                                    }\n                                }\n                                {\n                                    exfalso. clear -Hc. set_solver.\n                                }\n                            }\n                            {\n                                specialize (H' (@stdpp.base.inhabitant _ (Domain_inhabited M))).\n                                destruct H' as [c Hc].\n                                destruct (indec _ H c ρ) as [Hin|Hnotin].\n                                {\n                                    exists (lift_value c).\n                                    destruct (Mext_indec _ H (lift_value c) ρ) as [Hin'|Hnotin'].\n                                    {\n                                        rewrite update_evar_val_lift_val_comm.\n                                        specialize (IHszpred (update_evar_val (fresh_evar ϕ) c ρ)).\n                                        feed specialize IHszpred.\n                                        {\n                                            rewrite evar_open_size'. lia.\n                                        }\n                                        {\n                                            apply is_SPredicate_evar_open. assumption.\n                                        }\n                                        {\n                                            wf_auto2.\n                                        }\n                                        destruct IHszpred as [IH1 IH2].\n\n                                        specialize (HSPred' (update_evar_val (fresh_evar ϕ) c ρ)).\n                                        destruct HSPred' as [HFull|HEmpty].\n                                        {\n                                            apply IH2 in HFull.\n                                            rewrite HFull.\n                                            clear.\n                                            set_solver.\n                                        }\n                                        {\n                                            rewrite HEmpty in Hc.\n                                            exfalso. clear -Hc.\n                                            set_solver.\n                                        }\n                                    }\n                                    {\n                                        exfalso. apply Hnotin'. clear Hnotin'.\n                                        unfold Minterp_inhabitant.\n                                        rewrite eval_app_simpl.\n                                        do 2 rewrite eval_sym_simpl.\n                                        simpl.\n                                        unfold app_ext.\n                                        rewrite elem_of_PropSet.\n                                        unfold Minterp_inhabitant in Hin.\n                                        rewrite eval_app_simpl in Hin.\n                                        do 2 rewrite eval_sym_simpl in Hin.\n                                        unfold app_ext in Hin.\n                                        rewrite elem_of_PropSet in Hin.\n                                        destruct Hin as [le [re [Hle [Hre Hlere] ] ] ].\n                                        simpl.\n                                        exists cinh.\n                                        exists (lift_value re).\n                                        split.\n                                        {\n                                            unfold new_sym_interp.\n                                            repeat case_match; try congruence.\n                                        }\n                                        simpl.\n                                        split.\n                                        {\n                                            unfold new_sym_interp,lift_value.\n                                            simpl in *.\n                                            unfold is_not_core_symbol,is_core_symbol in H.\n                                            repeat case_match; subst; try tauto.\n                                            unfold fmap.\n                                            with_strategy transparent [propset_fmap] unfold propset_fmap.\n                                            rewrite elem_of_PropSet.\n                                            exists (inl re).\n                                            split;[reflexivity|].\n                                            rewrite elem_of_PropSet.\n                                            exists re.\n                                            split;[reflexivity|].\n                                            assumption.\n                                        }\n                                        {\n                                            unfold fmap,lift_value.\n                                            with_strategy transparent [propset_fmap] unfold propset_fmap.\n                                            rewrite elem_of_PropSet.\n                                            exists (inl c).\n                                            split;[reflexivity|].\n                                            rewrite elem_of_PropSet.\n                                            exists c.\n                                            split;[reflexivity|].\n                                            rewrite elem_of_PropSet.\n                                            exists le. exists re.\n                                            split;[assumption|].\n                                            split;[(clear;set_solver)|].\n                                            assumption.\n                                        }\n                                    }\n                                }\n                                {\n                                    exfalso. clear -Hc. set_solver.\n                                }\n                            }\n                        }\n                    }\n                    {\n                        unshelve (erewrite eval_forall_of_sort).\n                        3: { rewrite HSortImptDef. apply Mext_satisfies_definedness. }\n                        1: { intros m. apply Mext_indec. assumption. }\n\n                        unshelve (erewrite eval_forall_of_sort).\n                        3: { rewrite HSortImptDef. assumption. }\n                        1: { intros m. apply indec. assumption. }\n\n                        do 2 rewrite stdpp_ext.propset_fa_intersection_full.\n                        rewrite stdpp_ext.propset_fa_intersection_empty.\n                        unshelve (erewrite @stdpp_ext.propset_fa_intersection_empty).\n                        3: { apply _. }\n                        2: { apply Domain_inhabited. }\n\n                        split.\n                        {\n                            split.\n                            {\n                                intros H'.\n                                intros t.\n                                specialize (H' (stdpp.base.inhabitant)).\n                                destruct H' as [c Hc].\n                                destruct (Mext_indec _ H c ρ) as [Hin|Hnotin].\n                                {\n                                    unfold Minterp_inhabitant in Hin.\n                                    rewrite eval_app_simpl in Hin.\n                                    do 2 rewrite eval_sym_simpl in Hin.\n                                    unfold app_ext in Hin.\n                                    rewrite elem_of_PropSet in Hin.\n                                    simpl in Hin.\n                                    destruct Hin as [le [re [Hle [Hre Hin] ] ] ].\n                                    unfold is_not_core_symbol,is_core_symbol in H.\n                                    unfold new_sym_interp in Hle,Hre.\n                                    repeat case_match; subst; try contradiction; try congruence; try (solve [exfalso;tauto]).\n                                    unfold fmap in Hre.\n                                    with_strategy transparent [propset_fmap] unfold propset_fmap in Hre.\n                                    rewrite elem_of_PropSet in Hre.\n                                    destruct Hre as [amr [Hamr Hre] ].\n                                    subst re.\n                                    rewrite elem_of_PropSet in Hre.\n                                    destruct Hre as [a [Ha Hre] ].\n                                    subst amr.\n                                    rewrite elem_of_singleton in Hle. subst le.\n                                    unfold new_app_interp in Hin.\n                                    repeat case_match; subst.\n                                    unfold fmap in Hin.\n                                    with_strategy transparent [propset_fmap] unfold propset_fmap in Hin.\n                                    rewrite elem_of_PropSet in Hin.\n                                    destruct Hin as [amr [Hamr Hin] ].\n                                    subst c.\n                                    rewrite elem_of_PropSet in Hin.\n                                    destruct Hin as [a0 [Hamr Hin] ].\n                                    subst amr.\n                                    unfold app_ext in Hin.\n                                    rewrite elem_of_PropSet in Hin.\n                                    destruct Hin as [le [re [Hle [Hre' Hin] ] ] ].\n                                    rewrite elem_of_singleton in Hre'. subst re.\n                                    specialize (IHszpred (ϕ^{evar: 0 ↦ fresh_evar ϕ}) (update_evar_val (fresh_evar ϕ) a0 ρ)).\n                                    feed specialize IHszpred.\n                                    {\n                                        rewrite evar_open_size'.\n                                        lia.\n                                    }\n                                    {\n                                        apply is_SPredicate_evar_open.\n                                        assumption.\n                                    }\n                                    {\n                                        wf_auto2.\n                                    }\n                                    destruct IHszpred as [IH1 IH2].\n                                    pose proof (HSPred' := HSPred).\n                                    apply SPred_is_pre_predicate in HSPred'.\n                                    apply (@M_pre_predicate_evar_open Σ M ϕ (fresh_evar ϕ)) in HSPred'.\n                                    exists a0.\n                                    destruct (indec _ H a0 ρ) as [Hin'|Hnotin'].\n                                    {\n                                        rewrite update_evar_val_lift_val_comm in Hc.\n                                        intros HContra. apply Hc. clear Hc.\n                                        unfold M_pre_predicate in HSPred'.\n                                        specialize (HSPred' 0).\n                                        apply closed_M_pre_pre_predicate_is_M_predicate in HSPred'.\n                                        2: {\n                                            unfold well_formed,well_formed_closed in Hwf.\n                                            simpl in Hwf.\n                                            destruct_and!.\n                                            wf_auto2.\n                                        }\n                                        specialize (HSPred' (update_evar_val (fresh_evar ϕ) a0 ρ)).\n                                        destruct HSPred' as [HFull|HEmpty].\n                                        {\n                                            apply IH2 in HFull.\n                                            rewrite HFull.\n                                            clear.\n                                            set_solver.\n                                        }\n                                        {\n                                            rewrite HEmpty in HContra.\n                                            exfalso. clear -HContra.\n                                            set_solver.\n                                        }\n                                    }\n                                    {\n                                        exfalso. apply Hnotin'.\n                                        unfold Minterp_inhabitant.\n                                        rewrite eval_app_simpl.\n                                        do 2 rewrite eval_sym_simpl.\n                                        unfold app_ext.\n                                        rewrite elem_of_PropSet.\n                                        exists le. exists a.\n                                        repeat split; assumption.\n                                    }\n                                }\n                                {\n                                    exfalso. clear -Hc. set_solver.\n                                }\n                            }\n                            {\n                                intros H'.\n                                intros t.\n                                specialize (H' (@stdpp.base.inhabitant _ (Domain_inhabited M))).\n                                destruct H' as [c Hc].\n                                destruct (indec _ H c ρ) as [Hin|Hnotin].\n                                {\n                                    unfold Minterp_inhabitant in Hin.\n                                    rewrite eval_app_simpl in Hin.\n                                    do 2 rewrite eval_sym_simpl in Hin.\n                                    unfold app_ext in Hin.\n                                    rewrite elem_of_PropSet in Hin.\n                                    destruct Hin as [le [re [Hle [Hre Hin] ] ] ].\n\n                                    specialize (IHszpred (ϕ^{evar: 0 ↦ fresh_evar ϕ}) (update_evar_val (fresh_evar ϕ) c ρ)).\n                                    feed specialize IHszpred.\n                                    {\n                                        rewrite evar_open_size'.\n                                        lia.\n                                    }\n                                    {\n                                        apply is_SPredicate_evar_open.\n                                        assumption.\n                                    }\n                                    {\n                                        wf_auto2.\n                                    }\n                                    destruct IHszpred as [IH1 IH2].\n                                    pose proof (HSPred' := HSPred).\n                                    apply SPred_is_pre_predicate in HSPred'.\n                                    apply (@M_pre_predicate_evar_open Σ M ϕ (fresh_evar ϕ)) in HSPred'.\n\n                                    exists (lift_value c).\n                                    destruct (Mext_indec _ H (lift_value c) ρ) as [Hin'|Hnotin'].\n                                    {\n                                        rewrite update_evar_val_lift_val_comm.\n                                        unfold M_pre_predicate in HSPred'.\n                                        specialize (HSPred' 0).\n                                        apply closed_M_pre_pre_predicate_is_M_predicate in HSPred'.\n                                        2: {\n                                            unfold well_formed,well_formed_closed in Hwf. \n                                            simpl in Hwf.\n                                            destruct_and!.\n                                            wf_auto2.\n                                        }\n                                        specialize (HSPred' (update_evar_val (fresh_evar ϕ) c ρ)).\n                                        destruct HSPred' as [HFull|HEmpty].\n                                        {\n                                            intros HContra. apply Hc. clear Hc.\n                                            rewrite HFull.\n                                            clear. set_solver.\n                                        }\n                                        {\n                                            apply IH1 in HEmpty.\n                                            rewrite HEmpty.\n                                            clear. set_solver.\n                                        }\n                                    }\n                                    {\n                                        exfalso.\n                                        apply Hnotin'. clear Hnotin'.\n                                        unfold Minterp_inhabitant.\n                                        rewrite eval_app_simpl.\n                                        do 2 rewrite eval_sym_simpl.\n                                        unfold app_ext.\n                                        rewrite elem_of_PropSet.\n                                        exists cinh.\n                                        exists (lift_value re).\n                                        simpl.\n                                        unfold lift_value,new_sym_interp.\n                                        unfold is_not_core_symbol,is_core_symbol in H.\n                                        repeat case_match; subst; try congruence; try contradiction; try tauto.\n                                        split.\n                                        {\n                                            clear. set_solver.\n                                        }\n                                        unfold fmap.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                                        split.\n                                        {\n                                            rewrite elem_of_PropSet.\n                                            exists (inl re).\n                                            split;[reflexivity|].\n                                            rewrite elem_of_PropSet.\n                                            exists re.\n                                            split;[reflexivity|].\n                                            assumption.\n                                        }\n                                        {\n                                            rewrite elem_of_PropSet.\n                                            exists (inl c).\n                                            split;[reflexivity|].\n                                            rewrite elem_of_PropSet.\n                                            exists c.\n                                            split;[reflexivity|].\n                                            rewrite elem_of_PropSet.\n                                            exists le. exists re.\n                                            split;[assumption|].\n                                            split;[(clear; set_solver)|].\n                                            assumption.\n                                        }\n                                    }\n                                }\n                                {\n                                    exfalso. clear -Hc.\n                                    set_solver.\n                                }\n                            }\n                        }\n                        {\n                            split;\n                            intros H'.\n                            {\n                                intros c.\n                                destruct (indec _ H c ρ) as [Hin|Hnotin].\n                                {\n                                    specialize (IHszpred (ϕ^{evar: 0 ↦ fresh_evar ϕ}) (update_evar_val (fresh_evar ϕ) c ρ)).\n                                    feed specialize IHszpred.\n                                    {\n                                        rewrite evar_open_size'.\n                                        lia.\n                                    }\n                                    {\n                                        apply is_SPredicate_evar_open.\n                                        assumption.\n                                    }\n                                    {\n                                        wf_auto2.\n                                    }\n                                    destruct IHszpred as [IH1 IH2].\n                                    specialize (H' (lift_value c)).\n                                    destruct (Mext_indec _ H (lift_value c) ρ) as [Hin'|Hnotin'].\n                                    {\n                                        rewrite update_evar_val_lift_val_comm in H'.\n                                        apply IH2 in H'.\n                                        exact H'.\n                                    }\n                                    {\n                                        exfalso. apply Hnotin'. clear Hnotin' H'.\n                                        unfold Minterp_inhabitant in Hin.\n                                        rewrite eval_app_simpl in Hin.\n                                        do 2 rewrite eval_sym_simpl in Hin.\n                                        unfold app_ext in Hin.\n                                        rewrite elem_of_PropSet in Hin.\n                                        destruct Hin as [le [re [Hle [Hre Hin] ] ] ].\n                                        unfold Minterp_inhabitant.\n                                        rewrite eval_app_simpl.\n                                        do 2 rewrite eval_sym_simpl.\n                                        unfold app_ext.\n                                        rewrite elem_of_PropSet.\n                                        exists cinh.\n                                        exists (lift_value re).\n                                        simpl.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                                        unfold new_sym_interp.\n                                        unfold is_not_core_symbol,is_core_symbol in H.\n                                        repeat case_match; subst; try congruence; try contradiction; try tauto.\n                                        split;[(clear; set_solver)|].\n                                        unfold fmap.\n                                        with_strategy transparent [propset_fmap] unfold propset_fmap.\n                                        unfold lift_value.\n                                        repeat setoid_rewrite elem_of_PropSet.\n                                        split.\n                                        {\n                                            exists (inl re).\n                                            split;[reflexivity|].\n                                            exists re.\n                                            split;[reflexivity|].\n                                            assumption.\n                                        }\n                                        {\n                                            exists (inl c).\n                                            split;[reflexivity|].\n                                            exists c.\n                                            split;[reflexivity|].\n                                            exists le.\n                                            exists re.\n                                            split;[assumption|].\n                                            split;[(clear;set_solver)|].\n                                            assumption.\n                                        }\n                                    }\n                                }\n                                { reflexivity. }\n                            }\n                            {\n                                intros c.\n                                destruct (Mext_indec _ H c ρ) as [Hin|Hnotin].\n                                2: { reflexivity. }\n                                unfold Minterp_inhabitant in Hin.\n                                rewrite eval_app_simpl in Hin.\n                                do 2 rewrite eval_sym_simpl in Hin.\n                                unfold app_ext in Hin.\n                                rewrite elem_of_PropSet in Hin.\n                                simpl in Hin.\n                                unfold new_sym_interp,new_app_interp in Hin.\n                                destruct Hin as [le [re [Hle [Hre Hin] ] ] ].\n                                unfold is_not_core_symbol,is_core_symbol in H.\n                                repeat case_match; subst; try congruence; try contradiction.\n                                2: { \n                                    unfold fmap in Hre.\n                                    with_strategy transparent [propset_fmap] unfold propset_fmap in Hre.\n                                    rewrite elem_of_PropSet in Hre.\n                                    destruct Hre as [a [Ha Hre] ].\n                                    inversion Ha. clear Ha. subst.\n                                    rewrite elem_of_PropSet in Hre.\n                                    destruct Hre as [a [Ha Hre] ].\n                                    inversion Ha.\n                                 }\n                                unfold fmap in Hre.\n                                with_strategy transparent [propset_fmap] unfold propset_fmap in Hre.\n                                rewrite elem_of_PropSet in Hre.\n                                destruct Hre as [a [Ha Hre] ].\n                                inversion Ha. clear Ha. subst.\n                                rewrite elem_of_PropSet in Hre.\n                                destruct Hre as [a [Ha Hre] ].\n                                inversion Ha. clear Ha. subst.\n\n                                unfold fmap in Hin.\n                                with_strategy transparent [propset_fmap] unfold propset_fmap in Hin.\n                                rewrite elem_of_PropSet in Hin.\n                                destruct Hin as [a0 [Ha0 Hin] ].\n                                subst.\n                                rewrite elem_of_PropSet in Hin.\n                                destruct Hin as [a1 [Ha1 Hin] ].\n                                subst.\n                                unfold app_ext in Hin.\n                                rewrite elem_of_PropSet in Hin.\n                                destruct Hin as [le' [re' [Hle' [Hre' Hin] ] ] ].\n                                rewrite elem_of_singleton in Hre'. subst.\n                                rewrite update_evar_val_lift_val_comm.\n\n                                specialize (IHszpred (ϕ^{evar: 0 ↦ fresh_evar ϕ}) (update_evar_val (fresh_evar ϕ) a1 ρ)).\n                                feed specialize IHszpred.\n                                {\n                                    rewrite evar_open_size'.\n                                    lia.\n                                }\n                                {\n                                    apply is_SPredicate_evar_open.\n                                    assumption.\n                                }\n                                {\n                                    wf_auto2.\n                                }\n                                destruct IHszpred as [IH1 IH2].\n                                specialize (H' a1).\n                                destruct (indec _ H a1 ρ) as [Hin'|Hnotin'].\n                                {\n                                    apply IH2 in H'.\n                                    apply H'.\n                                }\n                                {\n                                    exfalso.\n                                    apply Hnotin'. clear Hnotin'.\n                                    unfold Minterp_inhabitant.\n                                    rewrite eval_app_simpl.\n                                    do 2 rewrite eval_sym_simpl.\n                                    unfold app_ext.\n                                    rewrite elem_of_PropSet.\n                                    exists le'. exists a.\n                                    repeat split; assumption.\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        Qed.\n\n    End semantic_preservation.\n\n    End ext.\nEnd with_syntax.\n", "meta": {"author": "harp-project", "repo": "AML-Formalization", "sha": "ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d", "save_path": "github-repos/coq/harp-project-AML-Formalization", "path": "github-repos/coq/harp-project-AML-Formalization/AML-Formalization-ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d/matching-logic/src/Theories/ModelExtension.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.22322562579795935}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.client_lemmas.\nRequire Import VST.floyd.nested_field_lemmas.\nRequire Import VST.floyd.type_induction.\nRequire Import VST.floyd.reptype_lemmas.\nRequire Import VST.floyd.aggregate_type.\nRequire Import VST.floyd.sublist.\n\nSection PROJ_REPTYPE.\n\nContext {cs: compspecs}.\n\nDefinition proj_gfield_reptype (t: type) (gf: gfield) (v: reptype t): reptype (gfield_type t gf) :=\n  match t, gf return (REPTYPE t -> reptype (gfield_type t gf))\n  with\n  | Tarray t0 hi a, ArraySubsc i => fun v => @Znth _ (default_val _) i v\n  | Tstruct id _, StructField i => fun v => proj_struct i (co_members (get_co id)) v (default_val _)\n  | Tunion id _, UnionField i => fun v => proj_union i (co_members (get_co id)) v (default_val _)\n  | _, _ => fun _ => default_val _\n  end (unfold_reptype v).\n\nFixpoint proj_reptype (t: type) (gfs: list gfield) (v: reptype t) : reptype (nested_field_type t gfs) :=\n  let res :=\n  match gfs as gfs'\n    return reptype (match gfs' with\n                    | nil => t\n                    | gf :: gfs0 => gfield_type (nested_field_type t gfs0) gf\n                    end)\n  with\n  | nil => v\n  | gf :: gfs0 => proj_gfield_reptype _ gf (proj_reptype t gfs0 v)\n  end\n  in eq_rect_r reptype res (nested_field_type_ind t gfs).\n\nEnd PROJ_REPTYPE.\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/floyd/proj_reptype_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725053, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.2231769962192772}}
{"text": "(*\n    Copyright (C) 2012  G. Gonthier, B. Ziliani, A. Nanevski, D. Dreyer\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n*)\n\nFrom mathcomp\nRequire Import ssreflect ssrbool ssrfun.\nFrom LemmaOverloading\nRequire Import heaps rels stmod stsep stlog.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(******************************************************************************)\n(* This file contains several lemmas automated with canonical structures to   *)\n(* verify programs with HTT                                                   *)\n(******************************************************************************)\n\n\n(*************************************************************************)\n(* First, the mechanism for search-and-replace for the overloaded lemas, *)\n(* pattern-matching on heap expressions.                                 *)\n(*************************************************************************)\n\nStructure tagged_heap := Tag {untag :> heap}.\n\nDefinition right_tag := Tag.\nDefinition left_tag := right_tag.\nCanonical Structure found_tag i := left_tag i.\n\nDefinition update_axiom k r (h : tagged_heap) := untag h = k :+ r.\n\nStructure update (k r : heap) :=\n  Update {heap_of :> tagged_heap;\n        _ : update_axiom k r heap_of}.\n\nLemma updateE r k (f : update k r) : untag f = k :+ r.\nProof. by case: f=>[[j]] /=; rewrite /update_axiom /= => ->. Qed.\n\nLemma found_pf k : update_axiom k empty (found_tag k).\nProof. by rewrite /update_axiom unh0. Qed.\n\nCanonical Structure found_struct k := Update (found_pf k).\n\nLemma left_pf h r (f : forall k, update k r) k :\n        update_axiom k (r :+ h) (left_tag (f k :+ h)).\nProof. by rewrite updateE /update_axiom /= unA. Qed.\n\nCanonical Structure left_struct h r (f : forall k, update k r) k :=\n  Update (left_pf h f k).\n\nLemma right_pf h r (f : forall k, update k r) k :\n        update_axiom k (h :+ r) (right_tag (h :+ f k)).\nProof. by rewrite updateE /update_axiom /= unCA. Qed.\n\nCanonical Structure right_struct h r (f : forall k, update k r) k :=\n  Update (right_pf h f k).\n\n(*********************)\n(* Overloaded lemmas *)\n(*********************)\n\nNotation cont A := (ans A -> heap -> Prop).\n\nSection EvalDoR.\nVariables (A B : Type).\n\nLemma val_doR (s : spec A) i j (f : forall k, update k j) (r : cont A) :\n         s.1 i ->\n         (forall x m, s.2 (Val x) i m -> def (f m) -> r (Val x) (f m)) ->\n         (forall e m, s.2 (Exn e) i m -> def (f m) -> r (Exn e) (f m)) ->\n         verify s (f i) r.\nProof.\nmove=>H1 H2 H3; rewrite updateE; apply: (val_do H1).\n- by move=>x m; move: (H2 x m); rewrite updateE.\nby move=>x m; move: (H3 x m); rewrite updateE.\nQed.\n\nLemma try_doR (s : spec A) s1 s2 i j (f : forall k, update k j) (r : cont B) :\n        s.1 i ->\n        (forall x m, s.2 (Val x) i m -> verify (s1 x) (f m) r) ->\n        (forall e m, s.2 (Exn e) i m -> verify (s2 e) (f m) r) ->\n        verify (try_s s s1 s2) (f i) r.\nProof.\nmove=>H1 H2 H3; rewrite updateE; apply: (try_do H1).\n- by move=>x m; move: (H2 x m); rewrite updateE.\nby move=>x m; move: (H3 x m); rewrite updateE.\nQed.\n\nLemma bnd_doR (s : spec A) s2 i j (f : forall k, update k j) (r : cont B) :\n        s.1 i ->\n        (forall x m, s.2 (Val x) i m -> verify (s2 x) (f m) r) ->\n        (forall e m, s.2 (Exn e) i m -> def (f m) -> r (Exn e) (f m)) ->\n        verify (bind_s s s2) (f i) r.\nProof.\nmove=>H1 H2 H3; rewrite updateE; apply: (bnd_do H1).\n- by move=>x m; move: (H2 x m); rewrite updateE.\nby move=>x m; move: (H3 x m); rewrite updateE.\nQed.\n\nEnd EvalDoR.\n\n(* ret lemmas need no reflection, as they operate on any heap; still *)\n(* rename them for uniformity *)\n\nDefinition val_retR := val_ret.\nDefinition try_retR := try_ret.\nDefinition bnd_retR := bnd_ret.\n\nSection EvalReadR.\nVariables (A B : Type).\n\nLemma val_readR v x i (f : update (x :-> v) i) (r : cont A) :\n        (def f -> r (Val v) f) ->\n        verify (read_s A x) f r.\nProof. by rewrite updateE; apply: val_read. Qed.\n\nLemma try_readR s1 s2 v x i (f : update (x :-> v) i) (r : cont B) :\n        verify (s1 v) f r ->\n        verify (try_s (read_s A x) s1 s2) f r.\nProof. by rewrite updateE; apply: try_read. Qed.\n\nLemma bnd_readR s v x i (f : update (x :-> v) i) (r : cont B) :\n        verify (s v) f r ->\n        verify (bind_s (read_s A x) s) f r.\nProof. by rewrite updateE; apply: bnd_read. Qed.\n\nEnd EvalReadR.\n\nSection EvalWriteR.\nVariables (A B C : Type).\n\nLemma val_writeR (v : A) (w : B) x i (f : forall k, update k i) (r : cont unit) :\n        (def (f (x :-> v)) -> r (Val tt) (f (x :-> v))) ->\n        verify (write_s x v) (f (x :-> w)) r.\nProof. by rewrite !updateE; apply: val_write. Qed.\n\nLemma try_writeR s1 s2 (v : A) (w : C) x i\n                 (f : forall k, update k i) (r : cont B) :\n        verify (s1 tt) (f (x :-> v)) r ->\n        verify (try_s (write_s x v) s1 s2) (f (x :-> w)) r.\nProof. rewrite !updateE; apply: try_write. Qed.\n\nLemma bnd_writeR s (v : A) (w : C) x i (f : forall k, update k i) (r : cont B) :\n        verify (s tt) (f (x :-> v)) r ->\n        verify (bind_s (write_s x v) s) (f (x :-> w)) r.\nProof. by rewrite !updateE; apply: bnd_write. Qed.\n\nEnd EvalWriteR.\n\nDefinition val_allocR := val_alloc.\nDefinition try_allocR := try_alloc.\nDefinition bnd_allocR := bnd_alloc.\nDefinition val_allocbR := val_allocb.\nDefinition try_allocbR := try_allocb.\nDefinition bnd_allocbR := bnd_allocb.\n\nSection EvalDeallocR.\nVariables (A B : Type).\n\nLemma val_deallocR (v : A) x i (f : forall k, update k i) (r : cont unit) :\n        (def (f empty) -> r (Val tt) (f empty)) ->\n        verify (dealloc_s x) (f (x :-> v)) r.\nProof. by rewrite !updateE un0h; apply: val_dealloc. Qed.\n\nLemma try_deallocR s1 s2 (v : B) x i (f : forall k, update k i) (r : cont A) :\n        verify (s1 tt) (f empty) r ->\n        verify (try_s (dealloc_s x) s1 s2) (f (x :-> v)) r.\nProof. by rewrite !updateE un0h; apply: try_dealloc. Qed.\n\nLemma bnd_deallocR s (v : B) x i (f : forall k, update k i) (r : cont A) :\n        verify (s tt) (f empty) r ->\n        verify (bind_s (dealloc_s x) s) (f (x :-> v)) r.\nProof. by rewrite !updateE un0h; apply: bnd_dealloc. Qed.\n\nEnd EvalDeallocR.\n\nDefinition val_throwR := val_throw.\nDefinition try_throwR := try_throw.\nDefinition bnd_throwR := bnd_throw.\n\n(* specialized versions of do lemmas, to handle ghost variables. *)\n\nSection EvalGhostR.\nVariables (A B C : Type) (t : C) (p : C -> Pred heap) (q : C -> post A).\nVariables (s1 : A -> spec B) (s2 : exn -> spec B) (i j : heap).\nVariables (f : forall k, update k j) (P : Pred heap).\n\nLemma val_ghR (r : cont A) :\n        let: s := (fun i => exists x, i \\In p x,\n                   fun y i m => forall x, i \\In p x -> q x y i m) in\n        (forall x m, q t (Val x) i m -> def (f m) -> r (Val x) (f m)) ->\n        (forall e m, q t (Exn e) i m -> def (f m) -> r (Exn e) (f m)) ->\n        i \\In p t ->\n        verify s (f i) r.\nProof.\nmove=>H1 H2; rewrite updateE; apply: val_gh.\n- by move=>x m; move: (H1 x m); rewrite updateE.\nby move=>x m; move: (H2 x m); rewrite updateE.\nQed.\n\nLemma val_gh1R (r : cont A) :\n        let: Q := fun y i m => forall x, i \\In p x -> q x y i m in\n        (i \\In p t -> P i) ->\n        (forall x m, q t (Val x) i m -> def (f m) -> r (Val x) (f m)) ->\n        (forall e m, q t (Exn e) i m -> def (f m) -> r (Exn e) (f m)) ->\n        i \\In p t ->\n        verify (P, Q) (f i) r.\nProof.\nmove=>H1 H2 H3; rewrite updateE; apply: (val_gh1 H1).\n- by move=>x m; move: (H2 x m); rewrite updateE.\nby move=>x m; move: (H3 x m); rewrite updateE.\nQed.\n\nLemma try_ghR (r : cont B) :\n        let: s := (fun i => exists x, i \\In p x,\n                   fun y i m => forall x, i \\In p x -> q x y i m) in\n        (forall x m, q t (Val x) i m -> verify (s1 x) (f m) r) ->\n        (forall e m, q t (Exn e) i m -> verify (s2 e) (f m) r) ->\n        i \\In p t ->\n        verify (try_s s s1 s2) (f i) r.\nProof.\nmove=>H1 H2; rewrite updateE; apply: try_gh.\n- by move=>x m; move: (H1 x m); rewrite updateE.\nby move=>x m; move: (H2 x m); rewrite updateE.\nQed.\n\nLemma try_gh1R (r : cont B) :\n        let: Q := fun y i m => forall x, i \\In p x -> q x y i m in\n        (i \\In p t -> P i) ->\n        (forall x m, q t (Val x) i m -> verify (s1 x) (f m) r) ->\n        (forall e m, q t (Exn e) i m -> verify (s2 e) (f m) r) ->\n        i \\In p t ->\n        verify (try_s (P, Q) s1 s2) (f i) r.\nProof.\nmove=>H1 H2 H3; rewrite updateE; apply: (try_gh1 H1).\n- by move=>x m; move: (H2 x m); rewrite updateE.\nby move=>x m; move: (H3 x m); rewrite updateE.\nQed.\n\nLemma bnd_ghR (r : cont B) :\n        let: s := (fun i => exists x, i \\In p x,\n                   fun y i m => forall x, i \\In p x -> q x y i m) in\n        (forall x m, q t (Val x) i m -> verify (s1 x) (f m) r) ->\n        (forall e m, q t (Exn e) i m -> def (f m) -> r (Exn e) (f m)) ->\n        i \\In p t ->\n        verify (bind_s s s1) (f i) r.\nProof.\nmove=>H1 H2; rewrite updateE; apply: bnd_gh.\n- by move=>x m; move: (H1 x m); rewrite updateE.\nby move=>x m; move: (H2 x m); rewrite updateE.\nQed.\n\nLemma bnd_gh1R (r : cont B) :\n        let: Q := fun y i m => forall x, i \\In p x -> q x y i m in\n        (i \\In p t -> P i) ->\n        (forall x m, q t (Val x) i m -> verify (s1 x) (f m) r) ->\n        (forall e m, q t (Exn e) i m -> def (f m) -> r (Exn e) (f m)) ->\n        i \\In p t ->\n        verify (bind_s (P, Q) s1) (f i) r.\nProof.\nmove=>H1 H2 H3; rewrite updateE; apply: (bnd_gh1 H1).\n- by move=>x m; move: (H2 x m); rewrite updateE.\nby move=>x m; move: (H3 x m); rewrite updateE.\nQed.\n\nEnd EvalGhostR.\n\n(****************************************************)\n(* Automating the selection of which lemma to apply *)\n(* (the hstep tactic made as an overloaded lemma    *)\n(****************************************************)\n\n(* Need to case-split on bnd_, try_, or a val_ lemma. *)\n(* Hence, three classes of canonical structures.      *)\n\nStructure val_form A i r (p : Prop):=\n  ValForm {val_pivot :> spec A;\n           _ : p -> verify val_pivot i r}.\n\nStructure bnd_form A B i (s : A -> spec B) r (p : Prop) :=\n  BndForm {bnd_pivot :> spec A;\n           _ : p -> verify (bind_s bnd_pivot s) i r}.\n\nStructure try_form A B i (s1 : A -> spec B)\n                         (s2 : exn -> spec B) r (p : Prop) :=\n  TryForm {try_pivot :> spec A;\n           _ : p -> verify (try_s try_pivot s1 s2) i r}.\n\n(* The main lemma which triggers the selection. *)\nDefinition hstep A i (r : cont A) p (e : val_form i r p) : p -> verify e i r :=\n  let: ValForm _ pf := e in pf.\n\n(* First check if matching on bnd_ or try_. If so, switch to searching *)\n(* for bnd_ or try_form, respectively. Otherwise, fall through, and    *)\n(* continue searching for a val_form. *)\nDefinition hstep_bnd A B i (s : A -> spec B) r p (e : bnd_form i s r p)\n  : p -> verify (bind_s e s) i r\n  := let: BndForm _ pf := e in pf.\n\nCanonical Structure\n  bnd_case_form A B i (s : A -> spec B) r p (e : bnd_form i s r p) :=\n  ValForm (hstep_bnd e).\n\nLemma try_case_pf A B i (s1 : A -> spec B) (s2 : exn -> spec B) r p\n                        (e : try_form i s1 s2 r p) :\n        p -> verify (try_s e s1 s2) i r.\nProof. by case:e=>[?]; apply. Qed.\n\n(* After that, find the form in the following list.  Notice that the list *)\n(* can be extended arbitrarily in the future. There is no centralized     *)\n(* tactic to maintain. *)\n\nCanonical Structure val_ret_form A v i r :=\n  ValForm (@val_retR A v i r).\nCanonical Structure bnd_ret_form A B s v i r :=\n  BndForm (@bnd_retR A B s v i r).\nCanonical Structure try_ret_form A B s1 s2 v i r :=\n  TryForm (@try_retR A B s1 s2 v i r).\n\nCanonical Structure val_read_form A v x r j f :=\n  ValForm (@val_readR A v x j f r).\nCanonical Structure bnd_read_form A B s v x r j f :=\n  BndForm (@bnd_readR A B s v x j f r).\nCanonical Structure try_read_form A B s1 s2 v x r j f :=\n  TryForm (@try_readR A B s1 s2 v x j f r).\n\nCanonical Structure val_write_form A B v w x r j f :=\n  ValForm (@val_writeR A B v w x j f r).\nCanonical Structure bnd_write_form A B C s v w x r j f :=\n  BndForm (@bnd_writeR A B C s v w x j f r).\n\nCanonical Structure try_write_form A B C s1 s2 v w x r j f :=\n  TryForm (@try_writeR A B C s1 s2 v w x j f r).\n\nCanonical Structure val_alloc_form A v i r :=\n  ValForm (@val_allocR A v i r).\nCanonical Structure bnd_alloc_form A B s v i r :=\n  BndForm (@bnd_allocR A B s v i r).\nCanonical Structure try_alloc_form A B s1 s2 v i r :=\n  TryForm (@try_allocR A B s1 s2 v i r).\n\nCanonical Structure val_allocb_form A v n i r :=\n  ValForm (@val_allocbR A v n i r).\nCanonical Structure bnd_allocb_form A B s v n i r :=\n  BndForm (@bnd_allocbR A B s v n i r).\nCanonical Structure try_allocb_form A B s1 s2 v n i r :=\n  TryForm (@try_allocbR A B s1 s2 v n i r).\n\nCanonical Structure val_dealloc_form A v x r j f :=\n  ValForm (@val_deallocR A v x j f r).\nCanonical Structure bnd_dealloc_form A B s v x r j f :=\n  BndForm (@bnd_deallocR A B s v x j f r).\nCanonical Structure try_dealloc_form A B s1 s2 v x r j f :=\n  TryForm (@try_deallocR A B s1 s2 v x j f r).\n\n(* we still keep one tactic to kill final goals, which *)\n(* are usually full of existentials *)\nLtac vauto := (do ?econstructor=>//).\n\nExample ex_read x :\n  verify (bind_s (write_s x 4) (fun _=> read_s _ x))\n         (x :-> 0) (fun r _ => r = Val 4).\nby do 2! [apply: hstep].\nAbort.\n\nExample ex_val_do (s : spec nat) (r : cont nat) (x y : ptr) :\n         s.1 (y:->2) ->\n         (forall x' m,\n               s.2 (Val x') (y:->2) m -> def (x:->1:+m) -> r (Val x') (x:->1:+m)) ->\n         (forall e m,\n               s.2 (Exn e) (y:->2) m -> def (x:->1:+m) -> r (Exn e) (x:->1:+m)) ->\n         verify s (x:->1 :+ y:->2) r.\nmove=>H1 H2 H3.\napply: (val_doR _ (i:=y:->2))=>//=.\nAbort.\n\nExample ex_bwd i x1 x2 (e : unit -> spec nat) q:\n          verify (e tt) (i :+ (x1 :-> 1 :+ x2 :-> 4)) q ->\n          verify (bind_s (write_s x2 4) e) (i :+ (x1 :-> 1 :+ x2 :-> 2)) q.\nby move=>H; apply: bnd_writeR.\nAbort.\n\n\nExample ex_fwd i x1 x2 (e : unit -> spec nat) q:\n          verify (e tt) (i :+ (x1 :-> 1 :+ x2 :-> 4)) q ->\n          verify (bind_s (write_s x2 4) e) (i :+ (x1 :-> 1 :+ x2 :-> 2)) q.\nmove=>H.\napply: (bnd_writeR (x:=x2) H).\nAbort.\n\n", "meta": {"author": "coq-community", "repo": "lemma-overloading", "sha": "e1c8bb876c7a26b90181d165f606cd35912ffa74", "save_path": "github-repos/coq/coq-community-lemma-overloading", "path": "github-repos/coq/coq-community-lemma-overloading/lemma-overloading-e1c8bb876c7a26b90181d165f606cd35912ffa74/theories/stlogR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22317699621927717}}
{"text": "Require Import sflib.     \nRequire Import Axioms.\nRequire Import Basic.\nRequire Import DataStructure.\nRequire Import Loc.\nRequire Import Coqlib.\nRequire Import Language. \n\nRequire Import Time.\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import NPThread.\nRequire Import Configuration.\nRequire Import MsgMapping.\nRequire Import DelaySet.\nRequire Import NPConfiguration.\nRequire Import ww_RF.\n\nRequire Import LibTactics.\nRequire Import WFConfig.\nRequire Import PromiseConsistent.\nRequire Import CompAuxDef.\nRequire Import LocalSim.\nRequire Import ConfigInitLemmas.\nRequire Import Mem_at_eq_lemmas.\n\nRequire Import Reordering.\nRequire Import np_to_ps_thread.\nRequire Import ps_to_np_thread.\nRequire Import ConsistentProp.\nRequire Import CompThreadSteps.\nRequire Import ConsistentStableEnv.\nRequire Import simPromiseCertified.\nRequire Import wwRFPrsvLemmas.\n\n(** * Write-Write Race Freedom Preservation Proof  *)\n\n(** This file contains the proof of the write-write race freedom preservation. *)\n\n(** The theorem [ww_RF_preservation] in this file shows\n    the write-write race freedom preservation of our thread-local simulation.\n    It says that,\n    if each target thread has thread-local simulation with\n    its corresponding source thread\n    and the source program is safe and write-write race free,\n    then the whole target program is write-write race free.\n\n    The theorem [ww_RF_preservation] is a part of proof in Lemma 6.2 in our paper and\n    also shown as a part of proof of the step 3 in Figure 6 (Our proof path) in our paper.\n*)\n\nLemma source_ww_race_construction1:\n  forall lang st_tgt lc_tgt sc_tgt mem_tgt \n    index index_order \n    st_src lc_src sc_src mem_src lo loc to' b dset inj I\n    from' val' R' i t\n    (T_BOT: Local.promises lc_tgt = Memory.bot)\n    (INDSET: dset_get loc t dset = Some i)\n    (ACC: Acc index_order i)\n    (LOCAL_SIM: @local_sim_state index index_order lang I lo inj dset b\n                                 (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                                 (Thread.mk lang st_src lc_src sc_src mem_src))\n    (RACE_MSG_S: Memory.get loc to' mem_src = Some (from', Message.concrete val' R'))\n    (NOT_PROM_S: Memory.get loc to' (Local.promises lc_src) = None)\n    (RACE_S: Time.lt (View.rlx (TView.cur (Local.tview lc_src)) loc) to')\n    (SAFE: ~ (exists e_src', rtc (Thread.all_step lo) (Thread.mk lang st_src lc_src sc_src mem_src) e_src' /\\\n                        Thread.is_abort e_src' lo))\n    (LOCAL_WF_T: Local.wf lc_tgt mem_tgt)\n    (MEM_CLOSED: Memory.closed mem_tgt)\n    (LOCAL_WF_S: Local.wf lc_src mem_src)\n    (MEM_CLOSED: Memory.closed mem_src)\n    (MONOTONIC_INJ: monotonic_inj inj)\n    (WELL_FOUNDED: well_founded index_order),\n  exists st_src' lc_src' sc_src' mem_src' e_src' stw_src' val0,\n    <<PRE_S: rtc (Thread.nprm_step lo) (Thread.mk lang st_src lc_src sc_src mem_src)\n                 (Thread.mk lang st_src' lc_src' sc_src' mem_src')>> /\\\n    <<WRITE_S: Language.step lang (ProgramEvent.write loc val0 Ordering.plain) st_src' stw_src'>> /\\ \n    <<RACE_MSG_S': Memory.get loc to' mem_src' = Some (from', Message.concrete val' R')>> /\\\n    <<NOT_PROM_S': Memory.get loc to' (Local.promises lc_src') = None>> /\\\n    <<VIEW_S': Time.lt (View.rlx (TView.cur (Local.tview lc_src')) loc) to'>> /\\\n    <<FULFILL_S: rtc (Thread.nprm_step lo)\n                     (Thread.mk lang st_src' lc_src' sc_src' mem_src') e_src'>> /\\ \n    <<BOT_S: Local.promises (Thread.local e_src') = Memory.bot>>.\nProof.\n  ii.\n  generalize dependent st_tgt.\n  generalize dependent lc_tgt.\n  generalize dependent sc_tgt.\n  generalize dependent mem_tgt.\n  generalize dependent st_src.\n  generalize dependent lc_src.\n  generalize dependent sc_src.\n  generalize dependent mem_src.\n  generalize dependent dset.\n  generalize dependent inj.\n  generalize dependent b.\n  induction ACC; ii.\n\n  assert(TGT_PROM_CONS: Local.promise_consistent lc_tgt).\n  {\n    unfold Local.promise_consistent. rewrite T_BOT. ii.\n    rewrite Memory.bot_get in PROMISE. ss.\n  }\n  assert(NOT_ABORT_T: \n          ~ Thread.is_abort (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt) lo).\n  {\n    introv NOT_ABORT_T.\n    inv LOCAL_SIM; ss. \n    contradiction SAFE.\n    eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n    eapply Thread_tau_steps_is_all_steps in NP_STEPS. eauto.\n    clear THRD_STEP RELY_STEP THRD_DONE.\n    exploit THRD_ABORT; eauto. ii; des.\n    contradiction SAFE.\n    eapply na_steps_is_tau_steps in H1; eauto.\n    eapply Thread_tau_steps_is_all_steps in H1; eauto.\n  }\n  unfold Thread.is_abort in NOT_ABORT_T; ss.\n  eapply not_and_or in NOT_ABORT_T.\n  destruct NOT_ABORT_T as [NOT_ABORT_T | NOT_ABORT_T].\n  {\n    clear - T_BOT NOT_ABORT_T.\n    contradiction NOT_ABORT_T.\n    unfold Local.promise_consistent. ii.\n    rewrite T_BOT in PROMISE.\n    rewrite Memory.bot_get in PROMISE; ss.\n  }\n  eapply not_or_and in NOT_ABORT_T. des.\n  eapply NNPP in NOT_ABORT_T. des.\n  {\n    (* target thread takes a step *)\n    exploit state_in_or_out; eauto. instantiate (1 := e).\n    introv AT_OR_NA_STEP.\n    destruct AT_OR_NA_STEP as [AT_STEP_T | NA_STEP_T].\n    {\n      (* target thread takes an atomic step *)\n      inv LOCAL_SIM; ss.\n\n      (* source thread abort *)\n      contradiction SAFE.\n      eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n      eapply Thread_tau_steps_is_all_steps in NP_STEPS. eauto.\n\n      (* source thread not abort *)\n      clear THRD_STEP RELY_STEP THRD_ABORT THRD_DONE.\n      inv STEP_INV. exploit DSET_EMP; eauto. ii; subst.\n      unfold dset_get, dset_init in INDSET.\n      rewrite DenseOrder.DOMap.gempty in INDSET. ss.\n    }\n    {\n      (* target thread takes a non-atomic step *)\n      eapply not_or_and in NOT_ABORT_T0. des.\n      exploit state_in_not_abort_thread_step; eauto.\n      instantiate (1 := sc_tgt).\n      introv TGT_THREAD_STEP.\n      destruct TGT_THREAD_STEP as (te & e_tgt & TGT_THREAD_STEP & IS_NA_STEP & PROM_EQ).\n      destruct e_tgt.\n      renames state to st_tgt', local to lc_tgt', sc to sc_tgt', memory to mem_tgt'.\n      inv LOCAL_SIM; ss.\n\n      (* source abort *)\n      contradiction SAFE.\n      eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n      eapply Thread_tau_steps_is_all_steps in NP_STEPS.\n      exists e_src. split; eauto.\n\n      (* source thread not abort *)\n      clear RELY_STEP THRD_DONE THRD_ABORT.\n      exploit THRD_STEP; eauto. clear THRD_STEP.\n      ii; des.\n      clear H1 H3 H4.\n      exploit H2; eauto. clear H2. ii; des.\n      exploit na_steps_dset_to_Thread_na_steps; [eapply H2 | eauto..].\n      introv NA_STEPS_S.\n      destruct e_src'.\n      assert (LOCAL_WF_S': Local.wf local memory).\n      {\n        eapply Thread_na_steps_is_no_scfence_nprm_steps in NA_STEPS_S.\n        eapply rtc_rtcn in NA_STEPS_S. des.\n        eapply no_scfence_nprm_steps_prsv_local_wf in NA_STEPS_S; eauto.\n      }\n      assert (MEM_CLOSED_S': Memory.closed memory).\n      {\n        eapply Thread_na_steps_is_no_scfence_nprm_steps in NA_STEPS_S.\n        eapply rtc_rtcn in NA_STEPS_S. des.\n        eapply no_scfence_nprm_steps_prsv_memory_closed in NA_STEPS_S; eauto.\n      }\n      eapply Thread_na_steps_to_nprm_steps in NA_STEPS_S.\n      lets S_PROM_FULFILL: H4.\n      assert (TGT_NA_STEP: @Thread.na_step lang lo\n                                           (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                                           (Thread.mk lang st_tgt' lc_tgt' sc_tgt' mem_tgt')).\n      {\n        clear - TGT_THREAD_STEP IS_NA_STEP.\n        destruct te; ss.\n        inv TGT_THREAD_STEP. inv STEP.\n        eapply Thread.na_tau_step_intro; eauto.\n        destruct ord; ss.\n        inv TGT_THREAD_STEP. inv STEP.\n        eapply Thread.na_plain_read_step_intro; eauto.\n        destruct ord; ss.\n        inv TGT_THREAD_STEP. inv STEP.\n        eapply Thread.na_plain_write_step_intro; eauto.\n      }\n      assert (TGT_PROM_CONS': Local.promise_consistent lc_tgt').\n      {\n        unfold Local.promise_consistent.\n        rewrite <- PROM_EQ. rewrite T_BOT.\n        ii. rewrite Memory.bot_get in PROMISE; ss.\n      }\n      assert (LOCAL_WF_T': Local.wf lc_tgt' mem_tgt').\n      {\n        eapply Thread_na_step_is_no_scfence_nprm_step in TGT_NA_STEP.\n        eapply no_scfence_nprm_step_prsv_local_wf in TGT_NA_STEP; ss.\n      }\n      assert (MEM_CLOSED_T': Memory.closed mem_tgt').\n      {\n        eapply Thread_na_step_is_no_scfence_nprm_step in TGT_NA_STEP.\n        eapply no_scfence_nprm_step_prsv_memory_closed in TGT_NA_STEP; ss.\n      }\n\n      exploit na_steps_dset_race_or_not; [eapply H2 | eapply RACE_MSG_S | eapply NOT_PROM_S | eauto..]; ss.\n      {\n        instantiate (1 := x). instantiate (1 := t).\n        clear - INDSET H1. inv H1; eauto.\n        eapply dset_get_add1; eauto.\n      }\n      \n      ii; des.\n      {\n        (* source generate race in current steps *)\n        destruct e0, e1; ss. inv RACE0; ss.\n        eapply lsim_ensures_promise_fulfill_T_BOT in S_PROM_FULFILL; eauto.\n        instantiate (1 := sc) in S_PROM_FULFILL. des.\n        exists state0 local0 sc0 memory0. exists e_srcc' state1 v.\n        exploit race_message_stable; [| eapply RACE_MSG_S | eapply NOT_PROM_S | eauto..]. \n        eapply Thread_na_steps_to_nprm_steps in RACE.\n        eapply Thread_nprm_step_is_tau_step in RACE.\n        eapply Thread_tau_steps_is_all_steps in RACE.\n        eapply RACE.\n        \n        introv RACE_MSG_S'.\n        destruct RACE_MSG_S' as (RACE_MSG_S' & NOT_PROM_S').\n\n        split; eauto.\n        {\n          eapply Thread_na_steps_to_nprm_steps; eauto.\n        }\n        split; eauto. split; eauto. split; eauto. split; eauto.\n        split; eauto.\n        eapply Thread_na_steps_to_nprm_steps in RACE2.\n        eapply Relation_Operators.rt1n_trans.\n        econs. econs; eauto. eauto. eauto.\n        eapply rtc_compose; eauto.\n        rewrite <- PROM_EQ; eauto.\n\n        introv ABORT_S. destruct ABORT_S as (e_src & PSTEPS & ABORT_S).\n        contradiction SAFE.\n        exists e_src; eauto.\n        eapply Thread_tau_steps_is_all_steps in PSTEPS.\n        split; eauto.\n        eapply Thread_nprm_step_is_tau_step in NA_STEPS_S.\n        eapply Thread_tau_steps_is_all_steps in NA_STEPS_S.\n        eapply rtc_compose; eauto.\n\n        unfold Memory.le. ii; eauto.\n      }\n      {\n        (* source not generate race in current steps *)\n        exploit dset_after_na_step_origin_prsv; eauto.\n        introv DSET_GET.\n        \n        exploit dset_reduce; eauto. ii; des.\n        exploit race_message_stable; [| eapply RACE_MSG_S | eapply NOT_PROM_S | eauto..]. \n        eapply Thread_nprm_step_is_tau_step in NA_STEPS_S.\n        eapply Thread_tau_steps_is_all_steps in NA_STEPS_S.\n        eapply NA_STEPS_S.\n\n        introv RACE_MSG_S'. destruct RACE_MSG_S' as (RACE_MSG_S' & NOT_PROM_S').\n\n        exploit H0.\n        eauto. eauto. eauto.\n        eapply RACE_MSG_S'. eauto.\n        eapply NOT_PROM_S'. eauto. eauto.\n\n        introv ABORT_S.\n        destruct ABORT_S as (e_src' & PSTEPS & ABORT_S).\n        contradiction SAFE.\n        exists e_src'. split; eauto.\n        eapply Thread_nprm_step_is_tau_step in NA_STEPS_S.\n        eapply Thread_tau_steps_is_all_steps in NA_STEPS_S.\n        eapply rtc_compose; eauto.\n\n        4: eapply H4.\n        eauto. rewrite <- PROM_EQ; eauto. eauto.\n\n        ii; des.\n        exists st_src' lc_src' sc_src' mem_src'. exists e_src' stw_src' val0.\n        split.\n        eapply rtc_compose; eauto.\n        split; eauto.\n      } \n    }\n  }\n  {\n    (* target thread done *)\n    inv LOCAL_SIM; ss.\n\n    (* source abort *)\n    contradiction SAFE.\n    eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n    eapply Thread_tau_steps_is_all_steps in NP_STEPS. eauto.\n\n    (* source not abort *)\n    exploit THRD_DONE; eauto. unfold Thread.is_done. simpl. eauto. ii; des.\n    exploit na_steps_dset_race_or_not; [eapply H1 | eapply RACE_MSG_S | eapply NOT_PROM_S | eauto..]; ss.\n    ii; des.\n    {\n      (* source generates race *)\n      destruct e0, e1; ss. inv RACE0; ss.\n      exploit race_message_stable; [| eapply RACE_MSG_S | eapply NOT_PROM_S | eauto..].\n      eapply Thread_na_steps_to_nprm_steps in RACE.\n      eapply Thread_nprm_step_is_tau_step in RACE.\n      eapply Thread_tau_steps_is_all_steps in RACE.\n      eapply RACE.\n      introv RACE_MSG_S'. destruct RACE_MSG_S' as (RACE_MSG_S' & NOT_PROM_S').\n      exists state local sc memory. exists e_src state0 v.\n      split.\n      {\n        eapply Thread_na_steps_to_nprm_steps in RACE.\n        eauto.\n      }\n      split; eauto.\n      split; eauto.\n      split; eauto.\n      split; eauto.\n      split.\n      {\n        eapply Relation_Operators.rt1n_trans.\n        econs; eauto. econs; eauto. eauto. eauto.\n        eapply Thread_na_steps_to_nprm_steps in RACE2. eauto.\n      }\n      {\n        inv H2. eauto.\n      }\n    }\n    {\n      (* source not generate race *)\n      rewrite dset_gempty in NOT_RACE0. ss.\n    }\n  }\nQed. \n  \nLemma source_ww_race_construction2':\n  forall n lang st_tgt lc_tgt sc_tgt mem_tgt e_tgt'\n    index index_order \n    st_src lc_src sc_src mem_src lo loc to' b dset inj I\n    from' val' R' t i\n    (FULFILL: rtcn (no_scfence_nprm_step lang lo) n (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt) e_tgt')\n    (BOT: Local.promises (Thread.local e_tgt') = Memory.bot)\n    (INDSET: dset_get loc t dset = Some i)\n    (ACC: Acc index_order i)\n    (LOCAL_SIM: @local_sim_state index index_order lang I lo inj dset b\n                                 (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                                 (Thread.mk lang st_src lc_src sc_src mem_src))\n    (RACE_MSG_S: Memory.get loc to' mem_src = Some (from', Message.concrete val' R'))\n    (NOT_PROM_S: Memory.get loc to' (Local.promises lc_src) = None)\n    (RACE_S: Time.lt (View.rlx (TView.cur (Local.tview lc_src)) loc) to')\n    (SAFE: ~ (exists e_src', rtc (Thread.all_step lo) (Thread.mk lang st_src lc_src sc_src mem_src) e_src' /\\\n                        Thread.is_abort e_src' lo))\n    (LOCAL_WF_T: Local.wf lc_tgt mem_tgt)\n    (MEM_CLOSED: Memory.closed mem_tgt)\n    (LOCAL_WF_S: Local.wf lc_src mem_src)\n    (MEM_CLOSED: Memory.closed mem_src)\n    (MONOTONIC_INJ: monotonic_inj inj)\n    (WELL_FOUNDED: well_founded index_order)\n    (WF_I: wf_I I),\n  exists st_src' lc_src' sc_src' mem_src' e_src' stw_src' val0,\n    <<PRE_S: rtc (Thread.nprm_step lo) (Thread.mk lang st_src lc_src sc_src mem_src)\n                 (Thread.mk lang st_src' lc_src' sc_src' mem_src')>> /\\\n    <<WRITE_S: Language.step lang (ProgramEvent.write loc val0 Ordering.plain) st_src' stw_src'>> /\\ \n    <<RACE_MSG_S': Memory.get loc to' mem_src' = Some (from', Message.concrete val' R')>> /\\\n    <<NOT_PROM_S': Memory.get loc to' (Local.promises lc_src') = None>> /\\\n    <<VIEW_S': Time.lt (View.rlx (TView.cur (Local.tview lc_src')) loc) to'>> /\\\n    <<FULFILL_S: rtc (Thread.nprm_step lo)\n                     (Thread.mk lang st_src' lc_src' sc_src' mem_src') e_src'>> /\\ \n    <<BOT_S: Local.promises (Thread.local e_src') = Memory.bot>>.\nProof.\n  induction n; ii.\n  - inv FULFILL; ss.\n    eapply source_ww_race_construction1; eauto.\n  - assert (TGT_PROM_CONS: Local.promise_consistent lc_tgt).\n    {\n      eapply rtcn_rtc in FULFILL.\n      eapply no_scfence_steps_to_bot_promise_consistent in FULFILL; eauto.\n    }\n    inv FULFILL.\n    destruct a2; ss.\n    assert (TGT_PROM_CONS': Local.promise_consistent local).\n    {\n      eapply rtcn_rtc in A23.\n      eapply no_scfence_steps_to_bot_promise_consistent in A23; eauto; ss.\n      eapply no_scfence_nprm_step_prsv_local_wf in A12; eauto.\n      eapply no_scfence_nprm_step_prsv_memory_closed in A12; eauto.\n    }\n    assert (LOCAL_WF_T': Local.wf local memory).\n    {\n      eapply no_scfence_nprm_step_prsv_local_wf in A12; eauto.\n    }\n    assert (MEM_CLOSED': Memory.closed memory).\n    {\n      eapply no_scfence_nprm_step_prsv_memory_closed in A12; eauto.\n    }\n    inv A12.\n    + (* program step *)\n      exploit state_in_or_out. instantiate (1 := ThreadEvent.get_program_event e).\n      introv AT_OR_NA_STEP.\n      destruct AT_OR_NA_STEP as [AT_STEP | NA_STEP].\n      {\n        (* atomic step *)\n        inv LOCAL_SIM; ss.\n        contradiction SAFE.\n        eapply NPThread_tau_steps_to_thread_all_steps in NP_STEPS; eauto.\n\n        clear THRD_STEP RELY_STEP THRD_DONE THRD_ABORT.\n        inv STEP_INV. inv STEP. exploit DSET_EMP; eauto. ii; subst.\n        clear - INDSET.\n        unfold dset_get, dset_init in INDSET.\n        rewrite DenseOrder.DOMap.gempty in INDSET. ss.\n      }\n      {\n        (* non-atomic step *)\n        exploit state_in_step_implies_threadEvt_is_na_step; eauto.\n        introv IS_NA_STEP.\n        inv LOCAL_SIM; ss.\n\n        (* source abort *)\n        contradiction SAFE.\n        eapply NPThread_tau_steps_to_thread_all_steps in NP_STEPS.\n        exists e_src. split; eauto.\n\n        (* source not abort *)\n        clear THRD_ABORT THRD_DONE RELY_STEP.\n        exploit THRD_STEP; eauto. clear THRD_STEP.\n        ii; des. clear H H1 H2.\n        exploit H0; eauto. ii; des.\n        exploit na_steps_dset_to_Thread_na_steps; [eapply H1 | eauto..].\n        introv NA_STEPS_S.\n        destruct e_src'.\n        assert (LOCAL_WF_S': Local.wf local0 memory0).\n        {\n          eapply Thread_na_steps_is_no_scfence_nprm_steps in NA_STEPS_S.\n          eapply rtc_rtcn in NA_STEPS_S. des.\n          eapply no_scfence_nprm_steps_prsv_local_wf in NA_STEPS_S; eauto.\n        }\n        assert (MEM_CLOSED_S': Memory.closed memory0).\n        {\n          eapply Thread_na_steps_is_no_scfence_nprm_steps in NA_STEPS_S.\n          eapply rtc_rtcn in NA_STEPS_S. des.\n          eapply no_scfence_nprm_steps_prsv_memory_closed in NA_STEPS_S; eauto.\n        }\n\n        exploit na_steps_dset_race_or_not; [eapply H1 | eapply RACE_MSG_S | eapply NOT_PROM_S | eauto..].\n        {\n          instantiate (1 := i). instantiate (1 := t).\n          clear - INDSET H. inv H; eauto.\n          eapply dset_get_add1; eauto.\n        }\n        ii; des.\n        {\n          (* source current steps generate race *)\n          eapply rtcn_rtc in A23.\n          eapply no_scfence_nprm_steps_is_nprm_steps in A23; eauto.\n          eapply rtc_rtcn in A23. des.\n          \n          exploit lsim_ensures_promise_fulfill;\n            [eapply WELL_FOUNDED | eapply MONOTONIC_INJ | eapply WF_I |\n              eapply A23 | eapply BOT | eauto..].\n          {\n            unfold Memory.le. ii; eauto.\n          }\n          {\n            introv GET_NONE GET_MSG.\n            rewrite GET_MSG in GET_NONE. ss.\n          }\n          {\n            introv ABORT_S. destruct ABORT_S as (e_src' & PSTEPS & ABORT_S).\n            contradiction SAFE.\n            eapply na_steps_is_tau_steps in NA_STEPS_S.\n            eapply Thread_tau_steps_is_all_steps in NA_STEPS_S.\n            eapply Thread_tau_steps_is_all_steps in PSTEPS.\n            exists e_src'. split; eauto.\n            eapply rtc_compose; [eapply NA_STEPS_S | eapply PSTEPS].\n          }\n          {\n            instantiate (1 := memory0).\n            unfold Memory.le. ii; eauto.\n          }\n          {\n            introv GET_NONE GET_MSG.\n            rewrite GET_NONE in GET_MSG. ss.\n          }\n\n          instantiate (1 := sc0).\n          introv TEMP. exploit TEMP; eauto.\n          inv H3; ss.\n          contradiction SAFE.\n          eapply na_steps_is_tau_steps in NA_STEPS_S.\n          eapply Thread_tau_steps_is_all_steps in NA_STEPS_S.\n          eapply NPThread_tau_steps_to_thread_all_steps in NP_STEPS.\n          exists e_src. split; eauto.\n          eapply rtc_compose; eauto.\n\n          clear - STEP_INV0. inv STEP_INV0.\n          unfold Mem_at_eq in ATOMIC_COVER. ii.\n          exploit ATOMIC_COVER; eauto.\n          introv MEM_APPROX_EQ.\n          unfold Mem_approxEq_loc in MEM_APPROX_EQ. des.\n          eapply MEM_APPROX_EQ0; eauto.\n\n          introv FULFILL_S. destruct FULFILL_S as (e_src' & FULFILL_S & BOT_S).\n          eapply rtc_rtcn in FULFILL_S. des.\n          eapply tau_steps_fulfill_implies_nprm_steps_fulfill in FULFILL_S; eauto; ss. des.\n          inv RACE0; ss.\n          eapply Thread_na_steps_to_nprm_steps in RACE.\n          eapply Thread_na_steps_to_nprm_steps in RACE2.\n          exists st1 lc1 sc1 mem1 e2. exists st2 v.\n          split; eauto. split; eauto. \n          eapply Thread_nprm_step_is_tau_step in RACE.\n          eapply Thread_tau_steps_is_all_steps in RACE.\n          exploit race_message_stable; [eapply RACE | eauto..]. ii; des.\n          split; eauto. split; eauto. split; eauto.\n          split; eauto.\n          eapply Relation_Operators.rt1n_trans.\n          econs. econs; eauto. ss. eauto. eauto.\n          eapply rtc_compose; eauto.\n        }\n        {\n          (* source thread will not generate race *)\n          ss.\n          exploit dset_reduce; [ | eauto..]; eauto; ss. \n          introv IN_DSET2'.\n          destruct IN_DSET2' as (j & IN_DSET2' & INDEX_DEC).\n          exploit race_message_stable; [ | eapply RACE_MSG_S | eapply NOT_PROM_S | eauto..].\n          eapply na_steps_is_tau_steps in NA_STEPS_S.\n          eapply Thread_tau_steps_is_all_steps; eauto.\n          introv RACE_MSG_S'.\n          destruct RACE_MSG_S' as (RACE_MSG_S' & NOT_PROM_S').\n          eapply IHn in H3; eauto; ss.\n          ii; des.\n          exists st_src' lc_src' sc_src' mem_src'. exists e_src' stw_src' val0.\n          eapply Thread_na_steps_to_nprm_steps in NA_STEPS_S.\n          split. eapply rtc_compose; [eapply NA_STEPS_S | eapply PRE_S].\n          split; eauto.\n\n          introv ABORT_S. destruct ABORT_S as (e_src' & PSTEPS & ABORT_S).\n          contradiction SAFE.\n          exists e_src'. split; eauto.\n          eapply na_steps_is_tau_steps in NA_STEPS_S.\n          eapply Thread_tau_steps_is_all_steps in NA_STEPS_S; eauto.\n          eapply rtc_compose; eauto.\n        }\n      }\n    + (* pf promise step *)\n      inv LOCAL_SIM; ss.\n\n      (* source abort *)\n      contradiction SAFE.\n      eapply NPThread_tau_steps_to_thread_all_steps in NP_STEPS.\n      exists e_src. split; eauto.\n\n      (* source not abort *)\n      clear RELY_STEP THRD_DONE THRD_ABORT.\n      exploit THRD_STEP; eauto.\n      ii; des. clear THRD_STEP H H0 H1.\n      exploit H2; eauto.\n      clear - STEP. inv STEP. inv LOCAL; ss; eauto.\n      ii; des. clear H2.\n      lets TVIEW_UNCHANGE: H.\n      eapply Thread.pf_promise_steps_tview_unchange in TVIEW_UNCHANGE; ss.\n      destruct e_src'; ss.\n      exploit race_message_stable; [| eapply RACE_MSG_S | eapply NOT_PROM_S | eauto.. ].\n      eapply pf_promise_steps_is_no_scfence_nprm_steps with (lo := lo) in H.\n      eapply no_scfence_nprm_steps_is_nprm_steps in H.\n      eapply Thread_nprm_step_is_tau_step in H.\n      eapply Thread_tau_steps_is_all_steps in H.\n      eapply H.\n      introv RACE_MSG_S'.\n      destruct RACE_MSG_S' as (RACE_MSG_S' & NOT_PROM_S'). \n      eapply IHn in H0; eauto.\n      {\n        des.\n        exists st_src' lc_src' sc_src' mem_src'. exists e_src' stw_src' val0.\n        split.\n        eapply pf_promise_steps_is_no_scfence_nprm_steps with (lo := lo) in H.\n        eapply no_scfence_nprm_steps_is_nprm_steps in H.\n        eapply rtc_compose; eauto.\n        split; eauto.\n      }\n      {\n        rewrite <- TVIEW_UNCHANGE; eauto.\n      }\n      {\n        introv ABORT_S.\n        contradiction SAFE.\n        destruct ABORT_S as (e_src' & PSTEPS & ABORT_S).\n        exists e_src'. split; eauto.\n        eapply pf_promise_steps_is_no_scfence_nprm_steps with (lo := lo) in H.\n        eapply no_scfence_nprm_steps_is_nprm_steps in H.\n        eapply Thread_nprm_step_is_tau_step in H.\n        eapply Thread_tau_steps_is_all_steps in H.\n        eapply rtc_compose; eauto.\n      }\n      {\n        eapply pf_promise_steps_is_no_scfence_nprm_steps with (lo := lo) in H.\n        eapply rtc_rtcn in H. des.\n        eapply no_scfence_nprm_steps_prsv_local_wf in H; eauto.\n      }\n      {\n        eapply pf_promise_steps_is_no_scfence_nprm_steps with (lo := lo) in H.\n        eapply rtc_rtcn in H. des.\n        eapply no_scfence_nprm_steps_prsv_memory_closed in H; eauto.\n      }\nQed.\n      \nLemma source_ww_race_construction2:\n  forall n lang st_tgt lc_tgt sc_tgt mem_tgt e_tgt'\n    index index_order \n    st_src lc_src sc_src mem_src lo loc to' b dset inj I\n    from' val' R' t i\n    (FULFILL: rtcn (Thread.nprm_step lo) n (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt) e_tgt')\n    (BOT: Local.promises (Thread.local e_tgt') = Memory.bot)\n    (INDSET: dset_get loc t dset = Some i)\n    (ACC: Acc index_order i)\n    (LOCAL_SIM: @local_sim_state index index_order lang I lo inj dset b\n                                 (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                                 (Thread.mk lang st_src lc_src sc_src mem_src))\n    (RACE_MSG_S: Memory.get loc to' mem_src = Some (from', Message.concrete val' R'))\n    (NOT_PROM_S: Memory.get loc to' (Local.promises lc_src) = None)\n    (RACE_S: Time.lt (View.rlx (TView.cur (Local.tview lc_src)) loc) to')\n    (SAFE: ~ (exists e_src', rtc (Thread.all_step lo) (Thread.mk lang st_src lc_src sc_src mem_src) e_src' /\\\n                        Thread.is_abort e_src' lo))\n    (LOCAL_WF_T: Local.wf lc_tgt mem_tgt)\n    (MEM_CLOSED: Memory.closed mem_tgt)\n    (LOCAL_WF_S: Local.wf lc_src mem_src)\n    (MEM_CLOSED: Memory.closed mem_src)\n    (MONOTONIC_INJ: monotonic_inj inj)\n    (WELL_FOUNDED: well_founded index_order)\n    (WF_I: wf_I I),\n  exists st_src' lc_src' sc_src' mem_src' e_src' stw_src' val0,\n    <<PRE_S: rtc (Thread.nprm_step lo) (Thread.mk lang st_src lc_src sc_src mem_src)\n                 (Thread.mk lang st_src' lc_src' sc_src' mem_src')>> /\\\n    <<WRITE_S: Language.step lang (ProgramEvent.write loc val0 Ordering.plain) st_src' stw_src'>> /\\ \n    <<RACE_MSG_S': Memory.get loc to' mem_src' = Some (from', Message.concrete val' R')>> /\\\n    <<NOT_PROM_S': Memory.get loc to' (Local.promises lc_src') = None>> /\\\n    <<VIEW_S': Time.lt (View.rlx (TView.cur (Local.tview lc_src')) loc) to'>> /\\\n    <<FULFILL_S: rtc (Thread.nprm_step lo)\n                     (Thread.mk lang st_src' lc_src' sc_src' mem_src') e_src'>> /\\ \n    <<BOT_S: Local.promises (Thread.local e_src') = Memory.bot>>.\nProof.\n  ii.\n  eapply nprm_steps_fulfill_implies_no_scfence_nprm_step_fulfill in FULFILL; eauto.\n  des.\n  eapply rtc_rtcn in FULFILL. des.\n  eapply source_ww_race_construction2' in FULFILL; eauto.\nQed.\n  \nLemma source_ww_race_construction:\n  forall n lang st_tgt lc_tgt sc_tgt mem_tgt e_tgt'\n    index index_order \n    st_src lc_src sc_src mem_src lo loc val to' b dset inj stw_tgt I\n    from' val' R'\n    (TGT_WRITE: Language.step lang (ProgramEvent.write loc val Ordering.plain) st_tgt stw_tgt)\n    (FULFILL: rtcn (Thread.nprm_step lo) n (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt) e_tgt')\n    (BOT: Local.promises (Thread.local e_tgt') = Memory.bot)\n    (LOCAL_SIM: @local_sim_state index index_order lang I lo inj dset b\n                                 (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                                 (Thread.mk lang st_src lc_src sc_src mem_src))\n    (RACE_MSG_S: Memory.get loc to' mem_src = Some (from', Message.concrete val' R'))\n    (NOT_PROM_S: Memory.get loc to' (Local.promises lc_src) = None)\n    (RACE_S: Time.lt (View.rlx (TView.cur (Local.tview lc_src)) loc) to')\n    (SAFE: ~ (exists e_src', rtc (Thread.all_step lo) (Thread.mk lang st_src lc_src sc_src mem_src) e_src' /\\\n                        Thread.is_abort e_src' lo))\n    (LOCAL_WF_T: Local.wf lc_tgt mem_tgt)\n    (MEM_CLOSED: Memory.closed mem_tgt)\n    (LOCAL_WF_S: Local.wf lc_src mem_src)\n    (MEM_CLOSED: Memory.closed mem_src)\n    (MONOTONIC_INJ: monotonic_inj inj)\n    (WELL_FOUNDED: well_founded index_order)\n    (WF_I: wf_I I),\n  exists st_src' lc_src' sc_src' mem_src' e_src' stw_src' val0,\n    <<PRE_S: rtc (Thread.nprm_step lo) (Thread.mk lang st_src lc_src sc_src mem_src)\n                 (Thread.mk lang st_src' lc_src' sc_src' mem_src')>> /\\\n    <<WRITE_S: Language.step lang (ProgramEvent.write loc val0 Ordering.plain) st_src' stw_src'>> /\\ \n    <<RACE_MSG_S': Memory.get loc to' mem_src' = Some (from', Message.concrete val' R')>> /\\\n    <<NOT_PROM_S': Memory.get loc to' (Local.promises lc_src') = None>> /\\\n    <<VIEW_S': Time.lt (View.rlx (TView.cur (Local.tview lc_src')) loc) to'>> /\\\n    <<FULFILL_S: rtc (Thread.nprm_step lo)\n                     (Thread.mk lang st_src' lc_src' sc_src' mem_src') e_src'>> /\\ \n    <<BOT_S: Local.promises (Thread.local e_src') = Memory.bot>>.\nProof.\n  induction n; ii.\n  - (* target has fulfilled all its promises *)\n    inv FULFILL; ss.\n    assert (TGT_PROM_CONS: Local.promise_consistent lc_tgt).\n    {\n      unfold Local.promise_consistent.\n      rewrite BOT. ii. rewrite Memory.bot_get in PROMISE. ss.\n    }\n    lets PROGRESS: TGT_WRITE.\n    eapply write_not_abort_progress with (lo := lo) (sc := sc_tgt) (lc := lc_tgt) in PROGRESS; eauto.\n    des.\n    inv LOCAL_SIM; ss.\n\n    (* source abort *)\n    contradiction SAFE.\n    eapply NPThread_tau_steps_to_thread_all_steps in NP_STEPS.\n    exists e_src. split; eauto.\n\n    (* source not abort *)\n    clear RELY_STEP THRD_DONE THRD_ABORT.\n    exploit THRD_STEP.\n    eapply Thread.step_program.\n    econs. \n    instantiate (2 := ThreadEvent.write loc from to val None Ordering.plain). ss. eauto.\n    eapply Local.step_write; eauto.\n    ii. des. clear H H1 H2 THRD_STEP. ss.\n    exploit H0; eauto. clear H0. ii; des.\n\n    assert (DSET_ADD: exists i, dset_get loc to dset1 = Some i).\n    {\n      inv H; ss. inv NA_WRITE.\n      eapply dset_get_gss.\n    }\n    des.\n    exploit na_steps_dset_race_or_not; [eapply H0 | eapply RACE_MSG_S | eapply NOT_PROM_S | eauto..].\n    ii; des.\n    {\n      (* current source steps will generate race *)\n      assert (TGT_LC_BOT': Local.promises lc' = Memory.bot).\n      {\n        clear - BOT PROGRESS.\n        inv PROGRESS; ss. inv WRITE. inv PROMISE.\n        exploit MemoryMerge.MemoryMerge.add_remove; [eapply PROMISES | eapply REMOVE | eauto..].\n        ii; subst; eauto.\n      }\n\n      exploit na_steps_dset_to_Thread_na_steps; [eapply H0 | eauto..].\n      introv NA_STEPS_S.\n      \n      destruct e_src'.\n      exploit lsim_ensures_promise_fulfill_T_BOT;\n        [eapply MONOTONIC_INJ | eapply WELL_FOUNDED | eapply TGT_LC_BOT' | | | eapply H2 | eauto..]. \n      {\n        eapply local_wf_write; eauto.\n      }\n      {\n        eapply write_step_closed_mem; eauto.\n      }\n      {\n        ii; des.\n        contradiction SAFE.\n        exists e_src'.\n        split; eauto. \n        eapply Thread_tau_steps_is_all_steps in H3. \n        eapply rtc_compose; [ | eapply H3 | eauto..].\n        eapply na_steps_is_tau_steps in NA_STEPS_S.\n        eapply Thread_tau_steps_is_all_steps; eauto.\n      }\n      {\n        eapply Thread_na_steps_is_no_scfence_nprm_steps in NA_STEPS_S.\n        eapply rtc_rtcn in NA_STEPS_S. des.\n        eapply no_scfence_nprm_steps_prsv_local_wf in NA_STEPS_S; eauto.\n      }\n      {\n        eapply Thread_na_steps_is_no_scfence_nprm_steps in NA_STEPS_S.\n        eapply rtc_rtcn in NA_STEPS_S. des.\n        eapply no_scfence_nprm_steps_prsv_memory_closed in NA_STEPS_S; eauto.\n      } \n      {\n        unfold Memory.le; ii; eauto.\n      }\n\n      instantiate (1 := sc). ii; des.\n      lets RACE_WRITE: RACE0.\n      inv RACE_WRITE; ss.\n      exists st1 lc1 sc1 mem1. exists e_srcc' st2 v. \n      split.\n      {\n        eapply Thread_na_steps_to_nprm_steps in RACE. eapply RACE.\n      }\n      split; eauto.\n      eapply na_steps_is_tau_steps in RACE.\n      eapply Thread_tau_steps_is_all_steps in RACE.\n      exploit race_message_stable; [eapply RACE | eauto..]. ii; des.\n      split; eauto. split; eauto. split; eauto.\n      split; eauto.\n      eapply Relation_Operators.rt1n_trans.\n      econs. econs; eauto. ss; eauto. ss. eauto.\n      eapply Thread_na_steps_to_nprm_steps in RACE2.\n      eapply rtc_compose; [eapply RACE2 | eauto..].\n    }\n    {\n      (* current source steps will not generate race *)\n      eapply na_steps_dset_to_Thread_na_steps in H0.\n      destruct e_src'; ss.\n      assert (RACE_MSG_PRSV: Memory.get loc to' memory = Some (from', Message.concrete val' R') /\\\n                             Memory.get loc to' (Local.promises local) = None).\n      {\n        eapply race_message_stable; [| eapply RACE_MSG_S | eapply NOT_PROM_S].\n        eapply na_steps_is_tau_steps in H0.\n        eapply Thread_tau_steps_is_all_steps in H0. eapply H0.\n      }\n      des.\n\n      eapply H1 in NOT_RACE0. des; ss.\n      lets WF_INDEX: WELL_FOUNDED.\n      unfold well_founded in WF_INDEX. specialize (WF_INDEX i).  \n      eapply source_ww_race_construction1 in H2; eauto.\n      des.\n\n      exists st_src' lc_src' sc_src' mem_src'. exists e_src' stw_src' val0.\n      split.\n      {\n        eapply Thread_na_steps_to_nprm_steps in H0.\n        eapply rtc_compose; [eapply H0 | eapply PRE_S].\n      }\n      split; eauto.\n      {\n        clear - BOT PROGRESS.\n        inv PROGRESS; ss. inv WRITE; ss. inv PROMISE.\n        exploit MemoryMerge.MemoryMerge.add_remove; [eapply PROMISES | eapply REMOVE | eauto..].\n        ii; subst; eauto.\n      }\n      {\n        introv ABORT. destruct ABORT as (e_src' & PSTEP_S & ABORT_S).\n        contradiction SAFE.\n        exists e_src'. split; eauto.\n        eapply na_steps_is_tau_steps in H0.\n        eapply Thread_tau_steps_is_all_steps in H0.\n        eapply rtc_compose; [eapply H0 | eapply PSTEP_S].\n      }\n      {\n        eapply local_wf_write; eauto.\n      } \n      {\n        eapply write_step_closed_mem; eauto.\n      }\n      {\n        eapply Thread_na_steps_is_no_scfence_nprm_steps in H0.\n        eapply rtc_rtcn in H0; des.\n        eapply no_scfence_nprm_steps_prsv_local_wf in H0; eauto.\n      }\n      {\n        eapply Thread_na_steps_is_no_scfence_nprm_steps in H0.\n        eapply rtc_rtcn in H0; des.\n        eapply no_scfence_nprm_steps_prsv_memory_closed in H0; eauto.\n      }\n    }\n\n    destruct (lo loc) eqn: AT_OR_NA_LOC; eauto.\n    contradiction SAFE. \n    eapply Thread.na_write_on_atomic_loc_is_abort in PROGRESS; eauto.\n    inv LOCAL_SIM; ss.\n    {\n      eapply NPThread_tau_steps_to_thread_all_steps in NP_STEPS; eauto.\n    }\n    {\n      exploit THRD_ABORT; eauto. ii; des.\n      eapply na_steps_is_tau_steps in H.\n      eapply Thread_tau_steps_is_all_steps in H.\n      eauto.\n    }\n  - assert (TGT_PROM_CONS: Local.promise_consistent lc_tgt).\n    {\n      eapply rtcn_rtc in FULFILL.\n      eapply nprm_steps_to_bot_promise_consistent in FULFILL; eauto.\n    }\n    inv FULFILL. inv A12.\n    + destruct a2. inv PROG.\n      exploit (Language.deterministic lang); [eapply TGT_WRITE | eapply STATE | eauto..]. \n      ii; des; subst; ss. \n      destruct e; ss. inv H. clear STATE.\n      inv LOCAL_SIM; ss.\n\n      (* current source thread abort *)\n      contradiction SAFE.\n      eapply NPThread_tau_steps_to_thread_all_steps in NP_STEPS; eauto.\n\n      (* current source thread not abort *)\n      clear RELY_STEP THRD_DONE THRD_ABORT.\n      exploit THRD_STEP.\n      eapply Thread.step_program. econs; eauto.\n      ss; eauto.\n      clear THRD_STEP. ii; des.\n      clear H H1 H2. exploit H0; eauto. ss.\n      clear H0. ii; des.\n\n      destruct e_src'; ss.\n      assert (LOCAL_WF_S': Local.wf local0 memory0).\n      {\n        eapply na_steps_dset_to_Thread_na_steps in H0.\n        eapply Thread_na_steps_is_no_scfence_nprm_steps in H0.\n        eapply rtc_rtcn in H0; des.\n        eapply no_scfence_nprm_steps_prsv_local_wf in H0; eauto.\n      }\n      assert (CLOSED_S': Memory.closed memory0).\n      {\n        eapply na_steps_dset_to_Thread_na_steps in H0.\n        eapply Thread_na_steps_is_no_scfence_nprm_steps in H0.\n        eapply rtc_rtcn in H0; des.\n        eapply no_scfence_nprm_steps_prsv_memory_closed in H0; eauto.\n      }\n\n      assert (DSET_ADD: exists i, dset_get loc0 to dset1 = Some i).\n      {\n        inv H; ss. inv NA_WRITE.\n        eapply dset_get_gss.\n      }\n      des.\n      exploit na_steps_dset_race_or_not; [eapply H0 | eapply RACE_MSG_S | eapply NOT_PROM_S | eauto..]; ss.\n      ii; des; ss.\n      {\n        (* current source steps will generate race *)\n        lets RACE_WRITE_S: RACE0.\n        inv RACE_WRITE_S; ss.\n\n        (* promise fulfill *)\n        eapply lsim_ensures_promise_fulfill\n          with (n := n) (e_tgt' := e_tgt') (mem_tgtc := memory) (mem_srcc := memory0) (sc_srcc := sc0) in H2; eauto.\n\n        des. eapply rtc_rtcn in H2; des.\n        eapply tau_steps_fulfill_implies_nprm_steps_fulfill in H2; eauto; ss.\n        des.\n        exists st1 lc1 sc1 mem1. exists e0 st2 v.\n        split.\n        {\n          eapply Thread_na_steps_to_nprm_steps in RACE. eapply RACE.\n        }\n        split; eauto. \n        eapply na_steps_is_tau_steps in RACE.\n        eapply Thread_tau_steps_is_all_steps in RACE.\n        exploit race_message_stable; [eapply RACE | eauto..]. ii; des.\n        split; eauto. split; eauto. split; eauto.\n        split; eauto.\n        eapply Relation_Operators.rt1n_trans.\n        econs. econs; eauto. ss; eauto. ss. \n        eapply Thread_na_steps_to_nprm_steps in RACE2.\n        eapply rtc_compose; [eapply RACE2 | eauto..].\n\n        inv LOCAL; ss.\n        eapply local_wf_write; eauto.\n\n        inv LOCAL; ss.\n        eapply write_step_closed_mem; eauto.\n\n        unfold Memory.le. ii; eauto.\n\n        introv GET_NONE GET_MSG. rewrite GET_NONE in GET_MSG; ss.\n\n        (* source thread not abort *)\n        introv ABORT_S. destruct ABORT_S as (e_src' & PSTEPS_S & ABORT_S).\n        contradiction SAFE.\n        exists e_src'. split; eauto.\n        eapply na_steps_dset_to_Thread_na_steps in H0.\n        eapply na_steps_is_tau_steps in H0.\n        eapply Thread_tau_steps_is_all_steps in H0.\n        eapply Thread_tau_steps_is_all_steps in PSTEPS_S.\n        eapply rtc_compose; [eapply H0 | eapply PSTEPS_S].\n\n        unfold Memory.le. ii; eauto.\n        \n        introv GET_NONE GET_MSG.\n        rewrite GET_NONE in GET_MSG. ss.\n\n        assert (TGT_PROM_CONS': Local.promise_consistent local).\n        {\n          inv LOCAL.\n          eapply rtcn_rtc in A23.\n          eapply nprm_steps_to_bot_promise_consistent in A23; eauto; ss.\n          eapply local_wf_write; eauto.\n          eapply write_step_closed_mem; eauto.\n        }\n        inv H2; ss.\n        contradiction SAFE.\n        eapply na_steps_dset_to_Thread_na_steps in H0.\n        eapply na_steps_is_tau_steps in H0.\n        eapply Thread_tau_steps_is_all_steps in H0. \n        eapply NPThread_tau_steps_to_thread_all_steps in NP_STEPS.\n        exists e_src. split; eauto. eapply rtc_compose; [eapply H0 | eapply NP_STEPS].\n        clear THRD_STEP RELY_STEP THRD_DONE THRD_ABORT.\n        inv STEP_INV0. ii.\n        unfold Mem_at_eq in ATOMIC_COVER.\n        eapply ATOMIC_COVER in H2. unfold Mem_approxEq_loc in H2. des.\n        eapply H4 in H3. eauto.\n      }\n      {\n        (* source current steps will not generate race *)\n        eapply H1 in NOT_RACE0. des.\n        eapply na_steps_dset_to_Thread_na_steps in H0.\n        exploit race_message_stable; [| eapply RACE_MSG_S | eapply NOT_PROM_S | eauto..].\n        eapply na_steps_is_tau_steps in H0.\n        eapply Thread_tau_steps_is_all_steps in H0. eapply H0.\n        introv RACE_MSG_S'. des.\n\n        eapply source_ww_race_construction2 with (n := n) (e_tgt' := e_tgt') in H2; eauto.\n        {\n          des.\n          exists st_src' lc_src' sc_src' mem_src'. exists e_src' stw_src' val1.\n          split; eauto.\n          {\n            eapply Thread_na_steps_to_nprm_steps in H0.\n            eapply rtc_compose; eauto.\n          }\n          split; eauto.\n        }\n        {\n          introv ABORT_S. destruct ABORT_S as (e_src' & PSTEPS_S & ABORT_S).\n          contradiction SAFE.\n          exists e_src'; eauto.\n          eapply na_steps_is_tau_steps in H0.\n          eapply Thread_tau_steps_is_all_steps in H0.\n          split; eauto.\n          eapply rtc_compose; eauto.\n        }\n        {\n          inv LOCAL.\n          eapply local_wf_write; eauto.\n        }\n        {\n          inv LOCAL.\n          eapply write_step_closed_mem; eauto.\n        }\n      }\n    + destruct a2.\n      inv LOCAL_SIM; ss.\n\n      (* source thread abort *)\n      contradiction SAFE.\n      eapply NPThread_tau_steps_to_thread_all_steps in NP_STEPS; eauto.\n\n      (* source thread will not abort *)\n      clear RELY_STEP THRD_DONE THRD_ABORT.\n      exploit THRD_STEP.\n      econs. eauto. clear THRD_STEP.\n      ii; des. clear H H0 H1.\n      exploit H2; eauto. inv PF. ss. eauto. clear H2.\n      ii; des.\n      destruct e_src'.\n      assert (RACE_MSG_PRSV: Memory.get loc to' memory0 = Some (from', Message.concrete val' R') /\\\n                             Memory.get loc to' (Local.promises local0) = None).\n      {\n        eapply race_message_stable; [ | eapply RACE_MSG_S | eapply NOT_PROM_S].\n        eapply Thread_pf_promise_steps_is_nprm_steps with (lo := lo) in H.\n        eapply Thread_nprm_step_is_tau_step in H.\n        eapply Thread_tau_steps_is_all_steps in H. eapply H.\n      }\n      des.\n      assert (st_tgt = state).\n      {\n        inv PF. eauto.\n      }\n      subst state.\n      eapply IHn in H0; eauto.\n      {\n        des.\n        exists st_src' lc_src' sc_src' mem_src'. exists e_src' stw_src' val0.\n        split; eauto.\n        eapply Thread_pf_promise_steps_is_nprm_steps with (lo := lo) in H.\n        eapply rtc_compose; eauto.\n        split; eauto.\n      }\n      {\n        eapply Thread.pf_promise_steps_tview_unchange in H; ss.\n        rewrite <- H; eauto.\n      }\n      {\n        introv ABORT_S. des.\n        contradiction SAFE.\n        eapply Thread_pf_promise_steps_is_nprm_steps with (lo := lo) in H.\n        eapply Thread_nprm_step_is_tau_step in H.\n        eapply Thread_tau_steps_is_all_steps in H.\n        exists e_src'. split; eauto.\n        eapply rtc_compose; eauto.\n      }\n      inv PF.\n      exploit Local.promise_step_future; eauto. ii; des; eauto.\n      inv PF.\n      exploit Local.promise_step_future; eauto. ii; des; eauto.\n      eapply pf_promise_steps_is_no_scfence_nprm_steps with (lo := lo) in H.\n      eapply rtc_rtcn in H; des.\n      eapply no_scfence_nprm_steps_prsv_local_wf in H; eauto.\n      eapply pf_promise_steps_is_no_scfence_nprm_steps with (lo := lo) in H.\n      eapply rtc_rtcn in H; des.\n      eapply no_scfence_nprm_steps_prsv_memory_closed in H; eauto.\nQed.\n      \nLemma ww_rf_preservation_aux_cur_race\n      (index: Type) (index_order: index -> index -> Prop)\n      (I: Invariant) (lo: Ordering.LocOrdMap) inj\n      (ths_tgt ths_src: Threads.t) (sc_tgt sc_src: TimeMap.t) (mem_tgt mem_src: Memory.t)\n      (ctid: IdentMap.key)\n      (WELL_FOUNDED_ORDER: well_founded index_order)\n      (WELL_FORMED_INV: wf_I I)\n      (AUX_WW_RACE: aux_ww_race lo (Configuration.mk ths_tgt ctid sc_tgt mem_tgt))\n      (LOCAL_SIM: \n         forall lang st_tgt lc_tgt,\n           IdentMap.find ctid ths_tgt = Some (existT _ lang st_tgt, lc_tgt) ->\n           exists st_src lc_src,\n             IdentMap.find ctid ths_src = Some (existT _ lang st_src, lc_src) /\\\n             @local_sim_state index index_order lang I lo inj dset_init true\n                              (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                              (Thread.mk lang st_src lc_src sc_src mem_src) /\\\n             <<TGT_PROM_CONS: Local.promise_consistent lc_tgt>>)\n      (SAFE: ~ (exists npc,\n                   rtc (NPConfiguration.all_step lo)\n                       (NPConfiguration.mk (Configuration.mk ths_src ctid sc_src mem_src) true) npc /\\\n                   Configuration.is_abort (NPConfiguration.cfg npc) lo))\n      (MONOTONIC_INJ: monotonic_inj inj)\n      (WF_CONFIG_TGT: Configuration.wf (Configuration.mk ths_tgt ctid sc_tgt mem_tgt))\n      (WF_CONFIG_SRC: Configuration.wf (Configuration.mk ths_src ctid sc_src mem_src))\n  :\n    aux_ww_race lo (Configuration.mk ths_src ctid sc_src mem_src).\nProof.\n  inv AUX_WW_RACE.\n  exploit LOCAL_SIM; [eapply CTID | eauto..].\n  ii; des.\n  eapply thread_all_step_to_NPThread_all_steps_from_outAtmBlk in STEPS. des.\n  eapply rtc_rtcn in FULFILL. des.\n  eapply tau_steps_fulfill_implies_nprm_steps_fulfill in FULFILL; eauto. des. \n  eapply not_abort_implies_thread_safe with (st := st_src) (lc := lc_src) in SAFE; eauto.\n\n  (* sim holds when target race *) \n  exploit sim_all_steps; [eapply STEPS | eapply H0 | eauto..].\n\n  eapply wf_config_to_local_wf; eauto.\n  ss. inv WF_CONFIG_TGT; ss; eauto.\n  ss. inv WF_CONFIG_TGT; ss; eauto.\n  ss.\n  eapply nprm_steps_to_bot_promise_consistent in FULFILL; eauto.\n  ss. \n\n  ss.\n  eapply NPThread_all_steps_to_Thread_all_steps in STEPS.\n  exploit wf_config_rtc_thread_steps_prsv; [| eapply CTID | eapply STEPS | eauto..]. eauto.\n  ii. inv H1; ss. inv WF.\n  eapply THREADS with (tid := ctid); eauto.\n  rewrite IdentMap.gss; eauto.\n\n  ss.\n  eapply NPThread_all_steps_to_Thread_all_steps in STEPS.\n  exploit wf_config_rtc_thread_steps_prsv; [| eapply CTID | eapply STEPS | eauto..]. eauto.\n  ii. inv H1; ss.\n  \n  ii; des.\n  (* race message exists at last switch point *)\n  exploit race_message_in_starting_mem; [ | eapply RC_MSG | eapply RC_MSG0 | eapply WWRC | eauto..].\n  {\n    eapply NPThread_all_steps_to_Thread_all_steps in STEPS. eauto.\n  }\n  {\n    clear - CTID WF_CONFIG_TGT.\n    inv WF_CONFIG_TGT; ss. inv WF.\n    eapply THREADS in CTID; eauto.\n  }\n  {\n    inv WF_CONFIG_TGT; eauto.\n  }\n  {\n    inv WF_CONFIG_TGT; eauto.\n  }\n  introv RACE_POINT.\n  destruct RACE_POINT as (MEM_RACE_MSG0 & NOT_IN_PROM0).\n\n  (* find source race msg *)\n  inv H0; ss.\n  contradiction SAFE.\n  eapply NPThread_tau_steps_to_thread_all_steps in NP_STEPS.\n  exists e_src. split; eauto.\n  clear THRD_STEP THRD_DONE THRD_ABORT.\n  exploit RELY_STEP; eauto. clear RELY_STEP. ii; des. clear H1.\n  unfold wf_I in WELL_FORMED_INV.\n  eapply WELL_FORMED_INV in H0. ss. inv H0.\n  exploit SOUND; [eapply MEM_RACE_MSG0 | eauto..]. ii; des.\n  assert (NOT_IN_S_PROM0: Memory.get loc t' (Local.promises lc_src) = None).\n  {\n    destruct (Memory.get loc t' (Local.promises lc_src)) eqn:GET_S_PROM; eauto.\n    destruct p.\n    inv STEP_INV. des.\n    inv WF_CONFIG_SRC; ss.\n    inv WF.\n    eapply THREADS in H; eauto. inv H.\n    exploit PROMISES; [eapply GET_S_PROM | eauto..]. ii.\n    rewrite H1 in H. inv H.\n    inv REL_PROMISES0.\n    eapply COMPLETE0 in GET_S_PROM; des.\n\n    clear - GET_S_PROM0 REL_PROMISES.\n    unfold dset_subset in REL_PROMISES.\n    exploit REL_PROMISES; eauto.\n    unfold dset_get, dset_init; ss.\n    rewrite DenseOrder.DOMap.gempty; eauto. ii; ss.\n\n    exploit monotonic_inj_implies_injective;\n      [eapply MONOTONIC_INJ | eapply H0 | eapply GET_S_PROM | eauto..].\n    ii. subst.\n    rewrite NOT_IN_PROM0 in GET_S_PROM0. ss.\n  }\n  \n  (* source race msg in target race point *) \n  ii; des. destruct e_src'.\n  exploit race_message_stable;\n    [ | eapply H1 | eapply NOT_IN_S_PROM0 | eauto..].\n  { \n    eapply NPThread_all_steps_to_Thread_all_steps in S_STEPS.\n    eapply S_STEPS.\n  }\n  ii; des.\n  renames memory to mem_src', local to lc_src'.\n\n  eapply NPThread_all_steps_to_Thread_all_steps in STEPS.\n  exploit wf_config_rtc_thread_steps_prsv; [| eapply CTID | eapply STEPS | eauto..]. eauto.\n  introv WF_CONFIG_TGT'.\n  eapply NPThread_all_steps_to_Thread_all_steps in S_STEPS.\n  exploit wf_config_rtc_thread_steps_prsv; [| eapply H | eapply S_STEPS | eauto..]. eauto.\n  introv WF_CONFIG_SRC'.\n  assert (TGT_PROM_CONS': Local.promise_consistent lc').\n  {\n    eapply nprm_steps_to_bot_promise_consistent in FULFILL; eauto; ss.\n    eapply wf_config_to_local_wf; eauto.\n    instantiate (3 := ctid). rewrite IdentMap.gss; eauto.\n    inv WF_CONFIG_TGT'; eauto.\n  }\n\n  (* in target race point, source has a race message *)\n  lets LOCAL_SIM_PSV': LOCAL_SIM_PSV.\n  inv LOCAL_SIM_PSV; ss.\n  contradiction SAFE.\n  eapply NPThread_tau_steps_to_thread_all_steps in NP_STEPS.\n  exists e_src.\n  split; eauto.\n  eapply rtc_compose. eapply S_STEPS. eapply NP_STEPS.\n  clear THRD_STEP RELY_STEP THRD_DONE THRD_ABORT.\n  inv STEP_INV0.\n  assert (INJ: inj' loc to = Some t').\n  {\n    eapply INJ_INCR; eauto.\n  } \n  exploit VIEW_LE; eauto.\n  introv RACE_S.\n\n  (* aux ww-race *) \n  eapply rtc_rtcn in FULFILL. des.\n  exploit source_ww_race_construction;\n    [eapply WRITE | eapply FULFILL | eapply FULFILL1 | eapply LOCAL_SIM_PSV' |\n     eapply H2 | eapply H3 | eapply RACE_S | eauto..].\n  {\n    clear - S_STEPS SAFE.\n    introv WW_RACE_S.\n    contradiction SAFE. des.\n    exists e_src'.\n    split; eauto.\n    eapply rtc_compose.\n    eapply S_STEPS. eapply WW_RACE_S.\n  }\n  {\n    inv WF_CONFIG_TGT'; ss. inv WF.\n    eapply THREADS; eauto.\n    instantiate (3 := ctid).\n    rewrite IdentMap.gss; eauto.\n  }\n  {\n    inv WF_CONFIG_TGT'; eauto.\n  }\n  ii. exploit H4; eauto.\n  {\n    inv WF_CONFIG_SRC'; ss.\n    inv WF.\n    eapply THREADS with (tid := ctid).\n    rewrite IdentMap.gss; eauto.\n  }\n  {\n    inv WF_CONFIG_SRC'; eauto.\n  }\n  clear H4.\n  ii; des.\n  eapply Thread_nprm_step_is_tau_step in PRE_S.\n  eapply Thread_nprm_step_is_tau_step in FULFILL_S.\n  eapply Thread_tau_steps_is_all_steps in PRE_S.\n  econs.\n  {\n    eauto.\n  }\n  {\n    eapply rtc_compose.\n    eapply S_STEPS. eapply PRE_S.\n  }\n  {\n    eapply WRITE_S.\n  }\n  {\n    eauto.\n  }\n  {\n    eauto.\n  }\n  split. eapply FULFILL_S. eauto.\n\n  ss.\n  eapply NPThread_all_steps_to_Thread_all_steps in STEPS.\n  exploit wf_config_rtc_thread_steps_prsv; [| eapply CTID | eapply STEPS | eauto..]. eauto.\n  ii. inv H1; ss. inv WF.\n  eapply THREADS with (tid := ctid); eauto.\n  rewrite IdentMap.gss; eauto.\n\n  ss.\n  eapply NPThread_all_steps_to_Thread_all_steps in STEPS.\n  exploit wf_config_rtc_thread_steps_prsv; [| eapply CTID | eapply STEPS | eauto..]. eauto.\n  ii. inv H1; ss.\nQed.\n\n(** current thread will not abort *) \nLemma ww_rf_preservation_aux_cur_not_race:\n  forall n (index: Type) (index_order: index -> index -> Prop)\n    (I: Invariant) (lo: Ordering.LocOrdMap) inj\n    (ths_tgt ths_src: Threads.t) (sc_tgt sc_src: TimeMap.t) (mem_tgt mem_src: Memory.t)\n    (ctid: IdentMap.key) npc_tgt b_tgt b_src\n    (WELL_FOUNDED_ORDER: well_founded index_order)\n    (WELL_FORMED_INV: wf_I I)\n    (T_STEPS: rtcn (NPConfiguration.all_step lo) n\n                   (NPConfiguration.mk (Configuration.mk ths_tgt ctid sc_tgt mem_tgt) b_tgt) npc_tgt)\n    (WW_RACE: ww_race lo (NPConfiguration.cfg npc_tgt))\n    (CUR_NOT_RACE: ~ (aux_ww_race lo (Configuration.mk ths_tgt ctid sc_tgt mem_tgt)))\n    (READY_THRDS: \n         forall tid (READY_TID: tid <> ctid) lang st_tgt lc_tgt\n           (READY_TGT_THD: IdentMap.find tid ths_tgt = Some (existT _ lang st_tgt, lc_tgt)),\n         exists st_src lc_src,\n           IdentMap.find tid ths_src = Some (existT _ lang st_src, lc_src) /\\ \n           @rely_local_sim_state index index_order lang I lo inj\n                                 (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                                 (Thread.mk lang st_src lc_src sc_src mem_src) /\\\n           <<R_TGT_PROM_CONS: Local.promise_consistent lc_tgt>>)\n      (CUR_THRD: \n         forall lang st_tgt lc_tgt  \n           (CUR_TGT_THRD: IdentMap.find ctid ths_tgt = Some (existT _ lang st_tgt, lc_tgt)),\n         exists st_src lc_src dset,\n           IdentMap.find ctid ths_src = Some (existT _ lang st_src, lc_src) /\\\n           @local_sim_state index index_order lang I lo inj dset b_tgt\n                            (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                            (Thread.mk lang st_src lc_src sc_src mem_src) /\\\n           (b_tgt = true -> dset = dset_init) /\\\n           <<C_TGT_PROM_CONS: Local.promise_consistent lc_tgt>>)\n      (CONSISTENTS: NPConfiguration.consistent\n                      (NPConfiguration.mk (Configuration.mk ths_tgt ctid sc_tgt mem_tgt) b_tgt) lo)\n      (WWRF: ~(exists npc,\n                    rtc (NPConfiguration.all_step lo)\n                        (NPConfiguration.mk (Configuration.mk ths_src ctid sc_src mem_src) b_src) npc /\\\n                    aux_ww_race lo (NPConfiguration.cfg npc)))\n      (SAFE: ~(exists npc,\n                  rtc (NPConfiguration.all_step lo)\n                      (NPConfiguration.mk (Configuration.mk ths_src ctid sc_src mem_src) b_src) npc /\\\n                  Configuration.is_abort (NPConfiguration.cfg npc) lo))\n      (WF_CONFIG_TGT: Configuration.wf (Configuration.mk ths_tgt ctid sc_tgt mem_tgt))\n      (WF_CONFIG_SRC: Configuration.wf (Configuration.mk ths_src ctid sc_src mem_src))\n      (WF_ATM_BIT: b_tgt = true -> b_src = true)\n      (INV_OUT_ATM: b_tgt = true ->\n                    (Mem_at_eq lo mem_tgt mem_src /\\ I lo inj (Build_Rss sc_tgt mem_tgt sc_src mem_src)))\n      (MONOTONIC_INJ: monotonic_inj inj),\n  exists npc_src,\n    rtc (NPConfiguration.all_step lo)\n        (NPConfiguration.mk (Configuration.mk ths_src ctid sc_src mem_src) b_src) npc_src /\\\n    ww_race lo (NPConfiguration.cfg npc_src).\nProof.\n  induction n; ii.\n  - inv T_STEPS; ss.\n    clear - WW_RACE CUR_NOT_RACE CONSISTENTS WF_CONFIG_TGT.\n    inv WW_RACE.\n    contradiction CUR_NOT_RACE. clear CUR_NOT_RACE.\n    unfold NPConfiguration.consistent in CONSISTENTS; ss.\n    unfold Threads.consistent_nprm in CONSISTENTS.\n    lets T_CONSISTENT: CTID.\n    eapply CONSISTENTS in T_CONSISTENT.\n    eapply Thread_nprm_implies_fulfill in T_CONSISTENT; eauto.\n    {\n      des.\n      econs. eapply CTID.\n      eauto. eauto. eauto. eauto.\n      split.\n      eapply Thread_nprm_step_is_tau_step in T_CONSISTENT.\n      eapply T_CONSISTENT. eauto.\n    }\n    {\n      inv WF_CONFIG_TGT; ss.\n      inv WF. eauto.\n    }\n    {\n      inv WF_CONFIG_TGT; eauto.\n    }\n  - inv T_STEPS. inv A12.\n    lets CONSISTENTS': H.\n    eapply threads_consistent_stable in CONSISTENTS'; eauto. \n    inv H; ss.\n    + (* tau step *)\n      assert(T_STEPS: rtc (NPAuxThread.tau_step lang lo)\n                        (NPAuxThread.mk lang (Thread.mk lang st1 lc1 sc_tgt mem_tgt) b_tgt)\n                        (NPAuxThread.mk lang (Thread.mk lang st2 lc2 sc2 m2) b)).\n      {\n        eapply rtc_n1; [eapply STEPS | eapply STEP].\n      }\n      \n      exploit wf_config_rtc_NPThread_tau_steps_prsv; [ | | eapply T_STEPS | eauto..]; eauto.\n      introv T_CONFIG_WF'.\n      exploit CUR_THRD; [eapply TID1 | eauto..]. ii; des.\n      assert (PROM_CONS_T: Local.promise_consistent lc2).\n      {\n        unfold NPAuxThread.consistent in CONSISTENT.\n        eapply consistent_nprm_promise_consistent in CONSISTENT; ss; eauto.\n        eapply wf_config_to_local_wf; eauto.\n        instantiate (3 := ctid). rewrite IdentMap.gss; eauto.\n        inv T_CONFIG_WF'; ss; eauto.\n        inv T_CONFIG_WF'; ss; eauto.\n      }\n      \n      exploit sim_tau_steps_aux; [eapply T_STEPS | eauto..]; ss.\n      eapply wf_config_to_local_wf; eauto.\n      inv WF_CONFIG_TGT; eauto.\n      inv WF_CONFIG_TGT; eauto.      \n      {\n        (* abort *)\n        introv S_ABORT. des.\n        contradiction SAFE.\n        eexists. split; eauto. ss.\n        econs; ss. \n        eapply NPAuxThread_tau_steps_2_Thread_tau_steps in S_ABORT; ss.\n        do 3 eexists.\n        split; eauto. \n      }\n\n      ii; des.\n      destruct e_src'.\n      exploit wf_config_rtc_NPThread_tau_steps_prsv; [ | | eapply S_STEPS | eauto..]; eauto.\n      introv S_CONFIG_WF'.\n      eapply rtc_rtcn in S_STEPS. destruct S_STEPS as (n0 & S_STEPS).\n      destruct n0.\n      {\n        (* source takes zero step *)\n        inv S_STEPS; ss.\n        eapply IHn with (ths_src := IdentMap.add ctid (existT _ lang state, local) ths_src)\n                        (sc_tgt := sc2) (mem_tgt := m2)\n                        (sc_src := sc) (mem_src := memory) (b_src := b_src') in A23; eauto.\n        {\n          destruct A23 as (npc_src & PSTEPS_SRC & WW_RACE_S).\n          exists npc_src. split; eauto.\n          erewrite IdentMap.gsident in PSTEPS_SRC; eauto.\n        }\n        {\n          eapply NPThread_tau_steps_to_thread_all_steps in T_STEPS.\n          introv AUX_WW_RACE.\n          contradiction CUR_NOT_RACE.\n          inv AUX_WW_RACE.\n          rewrite IdentMap.gss in CTID. inv CTID.\n          eapply inj_pair2 in H4. subst.\n          econs.\n          eapply TID1.\n          eapply rtc_compose. eapply T_STEPS. eapply STEPS0.\n          eauto. eauto. eauto. eauto.\n        }\n        {\n          ii.\n          rewrite IdentMap.gso in READY_TGT_THD; eauto.\n          rewrite IdentMap.gso; eauto.\n          exploit READY_THRDS; [eapply READY_TID | eapply READY_TGT_THD | eauto..].\n          ii; des.\n          do 2 eexists. split. eauto. split; eauto.\n          eapply rtc_rtcn in T_STEPS. des.\n          eapply local_sim_rely_condition with (n_tgt := n0) (n_src := 0) (lang2 := lang0); eauto.\n          eapply wf_config_to_local_wf; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          instantiate (4 := ctid). rewrite IdentMap.gss; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          instantiate (3 := tid). erewrite IdentMap.gso; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          instantiate (3 := tid). erewrite IdentMap.gso; eauto.\n          inv T_CONFIG_WF'; eauto.\n          inv S_CONFIG_WF'; eauto.\n          inv T_CONFIG_WF'; eauto.\n          inv S_CONFIG_WF'; eauto.\n        }\n        {\n          rewrite IdentMap.gss; eauto.\n          ii. inv CUR_TGT_THRD. eapply inj_pair2 in H4. subst.\n          do 3 eexists.\n          split.\n          rewrite IdentMap.gss; eauto.\n          split. eauto. eauto.\n        }\n        {\n          erewrite IdentMap.gsident; eauto.\n        }\n        {\n          erewrite IdentMap.gsident; eauto.\n        }\n        {\n          ii; subst.\n          eapply out_atmblk_I_inj_hold in LOCAL_SIM_PSV; eauto.\n          des; eauto.\n          contradiction SAFE.\n          eexists. split. eauto. ss.\n          econs; ss.\n          eapply NPAuxThread_tau_steps_2_Thread_tau_steps in LOCAL_SIM_PSV; ss.\n          exists state local e_src'.\n          split; eauto.\n        }\n      }\n      {\n        (* source takes multiply steps *)\n        exploit Behavior.rtcn_tail; [eapply S_STEPS | eauto..].\n        introv S_STEPS_CONS.\n        destruct S_STEPS_CONS as (npc & S_STEPS_CONS & S_STEP).\n        destruct npc.\n        destruct (classic (@thrd_ww_race lang lo (Thread.mk lang state local sc memory))) as\n            [THRD_WW_RACE | THRD_NOT_WW_RACE].\n\n        (* source thread ww race *) \n        assert (AUX_WW_RACE_S: aux_ww_race lo (Configuration.mk ths_src ctid sc_src mem_src)).\n        {\n          inv THRD_WW_RACE.\n          eapply rtcn_rtc in S_STEPS.\n          eapply NPThread_tau_steps_to_thread_all_steps in S_STEPS.\n          assert (rtc (Thread.all_step lo)\n                      (Thread.mk lang st_src lc_src sc_src mem_src)\n                      (Thread.mk lang st' lc' sc' mem')).\n          {\n            eapply rtc_compose; [eapply S_STEPS | eapply STEPS0].\n          }\n          lets WF_CONFIG_T_TEMP: H2.\n          eapply wf_config_rtc_thread_steps_prsv in WF_CONFIG_T_TEMP; eauto.\n          eapply wf_config_to_local_wf with (tid := ctid) in WF_CONFIG_T_TEMP; eauto.\n          Focus 2. rewrite IdentMap.gss; eauto.\n          econs. eauto.\n          eapply H2.\n          eauto. eauto.\n          eauto. split; eauto.\n        }\n        contradiction WWRF.\n        eexists. split. eauto. ss.\n        \n        (* source thread not ww race *)\n        assert(CONSISTENT_S: \n                 NPAuxThread.consistent lang (Thread.mk lang state local sc memory) lo).\n        {\n          eapply promise_certified_prsv; [ | eapply CONSISTENT | eauto..]; eauto;\n            try solve [inv T_CONFIG_WF'; eauto];\n            try solve [inv S_CONFIG_WF'; eauto].\n          {\n            clear - SAFE S_STEPS H.\n            eapply rtcn_rtc in S_STEPS.\n            introv S_ABORT. destruct S_ABORT as (e_src' & S_STEPS_TO_ABORT & S_ABORT).\n            contradiction SAFE.\n            eexists. split; eauto; ss.\n            eapply NPAuxThread_tau_steps_2_Thread_tau_steps in S_STEPS; ss.\n            econs; ss.\n            do 3 eexists.\n            split. eapply H.\n            split. eapply rtc_compose; [eapply S_STEPS | eapply S_STEPS_TO_ABORT].\n            eauto.\n          }\n          {\n            eapply wf_config_to_local_wf; eauto.\n            instantiate (3 := ctid). erewrite IdentMap.gss; eauto.\n          }\n          {\n            eapply wf_config_to_local_wf; eauto.\n            instantiate (3 := ctid). erewrite IdentMap.gss; eauto.\n          }\n        }\n\n        eapply IHn with (ths_src := IdentMap.add ctid (existT _ lang state, local) ths_src)\n                        (sc_tgt := sc2) (mem_tgt := m2)\n                        (sc_src := sc) (mem_src := memory) (b_src := b_src') in A23; eauto.\n        {\n          destruct A23 as (npc_src & PSTEPS_SRC & WW_RACE_S).\n          exists npc_src. split; eauto.\n          eapply Relation_Operators.rt1n_trans. 2: eapply PSTEPS_SRC.\n          econs.\n          eapply NPConfiguration.step_tau; ss.\n          eauto.\n          eapply rtcn_rtc in S_STEPS_CONS.\n          eapply S_STEPS_CONS. eapply S_STEP.\n          eauto.\n        }\n        {\n          eapply NPThread_tau_steps_to_thread_all_steps in T_STEPS.\n          introv AUX_WW_RACE.\n          contradiction CUR_NOT_RACE.\n          inv AUX_WW_RACE.\n          rewrite IdentMap.gss in CTID. inv CTID.\n          eapply inj_pair2 in H4. subst.\n          econs.\n          eapply TID1.\n          eapply rtc_compose. eapply T_STEPS. eapply STEPS0.\n          eauto. eauto. eauto. eauto.\n        }\n        {\n          ii.\n          rewrite IdentMap.gso in READY_TGT_THD; eauto.\n          rewrite IdentMap.gso; eauto.\n          exploit READY_THRDS; [eapply READY_TID | eapply READY_TGT_THD | eauto..].\n          ii; des.\n          do 2 eexists. split. eauto. split; eauto.\n          eapply rtc_rtcn in T_STEPS. des.\n          eapply local_sim_rely_condition with (n_tgt := n1) (n_src := S n0) (lang2 := lang0); eauto.\n          eapply wf_config_to_local_wf; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          instantiate (3 := tid). erewrite IdentMap.gso; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          instantiate (3 := tid). erewrite IdentMap.gso; eauto.\n          inv T_CONFIG_WF'; eauto.\n          inv S_CONFIG_WF'; eauto.\n          inv T_CONFIG_WF'; eauto.\n          inv S_CONFIG_WF'; eauto.\n        }\n        {\n          rewrite IdentMap.gss; eauto.\n          ii. inv CUR_TGT_THRD. eapply inj_pair2 in H4. subst.\n          do 3 eexists.\n          split.\n          rewrite IdentMap.gss; eauto.\n          split. eauto. eauto.\n        }\n        {\n          introv AUX_WW_RACE_S.\n          destruct AUX_WW_RACE_S as (npc_src' & PSTEPS_S & AUX_WW_RACE_S).\n          contradiction WWRF.\n          exists npc_src'. split; eauto.\n          eapply Relation_Operators.rt1n_trans; [ | eapply PSTEPS_S].\n          econs.\n          eapply NPConfiguration.step_tau; ss.\n          eauto. eapply rtcn_rtc in S_STEPS_CONS. eapply S_STEPS_CONS. eauto. eauto.\n        }\n        {\n          introv ABORT_S.\n          destruct ABORT_S as (npc_src' & PSTEPS_S & ABORT_S).\n          contradiction SAFE.\n          exists npc_src'. split; eauto.\n          eapply Relation_Operators.rt1n_trans; [ | eapply PSTEPS_S].\n          econs.\n          eapply NPConfiguration.step_tau; ss.\n          eauto. eapply rtcn_rtc in S_STEPS_CONS. eapply S_STEPS_CONS. eauto. eauto.\n        }\n        {\n          ii; subst b.\n          eapply out_atmblk_I_inj_hold in LOCAL_SIM_PSV; eauto.\n          des; eauto.\n          contradiction SAFE.\n          eexists.\n          split.\n          eapply Operators_Properties.clos_rt1n_step.\n          econs.\n          eapply NPConfiguration.step_tau; ss.\n          eauto. eapply rtcn_rtc in S_STEPS_CONS. eapply S_STEPS_CONS. eauto. eauto.\n          ss.\n          econs; ss.\n          eapply NPAuxThread_tau_steps_2_Thread_tau_steps in LOCAL_SIM_PSV; ss.\n          exists state local e_src'.\n          split; eauto.\n          rewrite IdentMap.gss; eauto.\n        }\n      }\n    + (* switch *)\n      subst b_tgt.\n      destruct (Loc.eq_dec ctid tid2); subst.\n      (* switch to the same thread *)\n      eauto.\n\n      (* switch to the different thread *)\n      exploit READY_THRDS; eauto. ii; des.\n      assert(I_INV: I lo inj (Build_Rss sc_tgt mem_tgt sc_src mem_src) /\\\n                    Mem_at_eq lo mem_tgt mem_src).\n      {\n        exploit INV_OUT_ATM; eauto. ii. des. split; eauto.\n      }\n      destruct I_INV as (I_INV & MEM_AT_EQ).\n      exploit rely_local_sim_state_to_local_sim_state; eauto.\n      eapply wf_config_to_local_wf; eauto.\n      eapply wf_config_to_local_wf; eauto.\n      inv WF_CONFIG_TGT; eauto.\n      inv WF_CONFIG_SRC; eauto.\n      inv WF_CONFIG_TGT; eauto.\n      inv WF_CONFIG_SRC; eauto.\n      introv NEW_TH_LOCAL_SIM.\n      exploit WF_ATM_BIT; eauto. ii; subst b_src.\n\n      (* discuss whether the new thread will generate ww race *) \n      destruct (classic (aux_ww_race lo (Configuration.mk ths_tgt tid2 sc_tgt mem_tgt)))\n               as [TID2_WW_RACE | TID2_NOT_WW_RACE].\n      {\n        (* new thread will generate ww race  *)\n        eapply ww_rf_preservation_aux_cur_race with\n            (ths_src := ths_src) (ctid := tid2) (sc_src := sc_src) (mem_src := mem_src)\n          in TID2_WW_RACE; eauto.\n        eapply aux_wwrace_to_np_wwrace_from_outAtmBlk in TID2_WW_RACE; eauto. des.\n        exists npc'. split; eauto.\n        eapply Relation_Operators.rt1n_trans.\n        2: eapply TID2_WW_RACE.\n        econs.\n        eapply NPConfiguration.step_sw with (tid2 := tid2); eauto.\n        eapply wf_config_sw_prsv; eauto.\n        introv TH_TID2.\n        rewrite TID2 in TH_TID2.\n        inv TH_TID2. eapply inj_pair2 in H3. subst.\n        eauto.\n\n        introv ABORT_S.\n        destruct ABORT_S as (npc_src' & PSTEPS_S & ABORT_S).\n        contradiction SAFE.\n        exists npc_src'. split; eauto.\n        eapply Relation_Operators.rt1n_trans; [ | eapply PSTEPS_S].\n        econs.\n        eapply NPConfiguration.step_sw; ss.\n        eauto.\n        eapply wf_config_sw_prsv; eauto.\n        eapply wf_config_sw_prsv; eauto.\n      }\n      {\n        eapply IHn with (ths_src := ths_src) (sc_src := sc_src)\n                        (mem_src := mem_src) (b_src := true) in A23; eauto.\n        {\n          destruct A23 as (npc_src & PSTEPS_SRC & WW_RACE_S).\n          exists npc_src. split; eauto.\n          eapply Relation_Operators.rt1n_trans. 2: eapply PSTEPS_SRC.\n          econs.\n          eapply NPConfiguration.step_sw with (tid2 := tid2); eauto; ss.\n        }\n        {\n          ii.\n          destruct (Loc.eq_dec tid ctid); subst; eauto.\n          (* origin thread *)\n          exploit CUR_THRD; [eapply READY_TGT_THD | eauto..]. ii; des.\n          exploit H3; eauto. ii; subst.\n          exists st_src0 lc_src0.\n          split. eauto. split; eauto.\n          eapply local_sim_state_to_rely_local_sim_state; eauto.\n          instantiate (1 := ctid).\n          introv ABORT. destruct ABORT as (npc' & TO_ABORT & ABORT).\n          contradiction SAFE. clear SAFE.\n          exists npc'.\n          split. eauto.\n          eapply NPConfig_abort_to_Config_abort; eauto.\n        }\n        {\n          ii.\n          rewrite TID2 in CUR_TGT_THRD. inv CUR_TGT_THRD.\n          eapply inj_pair2 in H3. subst st2.\n          exists st_src lc_src (@dset_init index).\n          split; eauto.\n        }\n        {\n          introv AUX_WW_RACE_S.\n          destruct AUX_WW_RACE_S as (npc_src' & PSTEPS_S & AUX_WW_RACE_S).\n          contradiction WWRF.\n          exists npc_src'. split; eauto.\n          eapply Relation_Operators.rt1n_trans; [ | eapply PSTEPS_S].\n          econs.\n          eapply NPConfiguration.step_sw; ss.\n          eauto.\n        }\n        {\n          introv ABORT_S.\n          destruct ABORT_S as (npc_src' & PSTEPS_S & ABORT_S).\n          contradiction SAFE.\n          exists npc_src'. split; eauto.\n          eapply Relation_Operators.rt1n_trans; [ | eapply PSTEPS_S].\n          econs.\n          eapply NPConfiguration.step_sw; ss; eauto.\n        }\n        eapply wf_config_sw_prsv; eauto.\n        eapply wf_config_sw_prsv; eauto.\n      }\n    + (* thread term *)\n      exploit CUR_THRD; [eapply OLD_TID | eauto..].\n      ii; des.\n      inv H0; ss.\n      (* current source thread will abort *)\n      contradiction SAFE.\n      eexists. split; eauto; ss.\n      eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n      econs; eauto; ss.\n      exists st_src lc_src e_src.\n      split; eauto.\n\n      (* current source thread will not abort *)\n      clear THRD_STEP RELY_STEP THRD_ABORT.\n      exploit THRD_DONE0; eauto. ii; des.\n      assert (NEW_TID_NOT_DONE: tid2 <> ctid).\n      {\n        ii; subst.\n        rewrite IdentMap.grs in NEW_TID_OK; ss.\n      }\n      rewrite IdentMap.gro in NEW_TID_OK; eauto.\n      exploit READY_THRDS; eauto. ii; des.\n      exploit na_steps_dset_to_NPThread_tau_steps; eauto.\n      instantiate (1 := b_src). introv Hprefix_tau_steps. des.\n      eapply rtc_rtcn in Hprefix_tau_steps.\n      destruct Hprefix_tau_steps as (n0 & Hprefix_tau_steps).\n      destruct n0.\n      {\n        (* source takes zero prefix step *)\n        inv Hprefix_tau_steps. ss.\n        (* discuss whether the new thread will generate ww race *)\n        destruct (classic (aux_ww_race lo (Configuration.mk (IdentMap.remove ctid ths_tgt) tid2 sc_tgt mem_tgt)))\n          as [TID2_WW_RACE | TID2_NOT_WW_RACE].\n        (* new thread will generate race *)\n        eapply ww_rf_preservation_aux_cur_race with\n            (ths_src := IdentMap.remove ctid ths_src) (ctid := tid2) (sc_src := sc_src) (mem_src := mem_src)\n            (inj := inj')\n          in TID2_WW_RACE; eauto.\n        {\n          eapply aux_wwrace_to_np_wwrace_from_outAtmBlk in TID2_WW_RACE; eauto.\n          des.\n          exists npc'. split; eauto.\n          eapply Relation_Operators.rt1n_trans; [ | eapply TID2_WW_RACE].\n          econs.\n          eapply NPConfiguration.step_thread_term; ss.\n          eauto. eauto.\n          rewrite IdentMap.gro; eauto.\n          eapply wf_config_rm_prsv; eauto.\n        } \n        { \n          repeat (rewrite IdentMap.gro; eauto).\n          introv TID2_T.\n          exploit READY_THRDS; eauto. ii; des. \n          eapply local_sim_rely_condition with\n              (n_tgt := 0) (n_src := 0) (lc_tgt1 := lc1) (lc_src1 := lc_src) in H8; eauto.\n          rewrite H5 in H7. inv H7. eapply inj_pair2 in H11. subst.\n          eapply rely_local_sim_state_to_local_sim_state in H8; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          inv STEP_INV; ss.\n          eapply wf_config_to_local_wf; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n        }\n        {\n          introv ABORT. destruct ABORT as (npc & TO_ABORT & ABORT).\n          contradiction SAFE.\n          exists npc.\n          split.\n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_thread_term; eauto.\n          ss. instantiate (3 := tid2). rewrite IdentMap.gro; eauto.\n          ss. eauto.\n        }\n        { \n          clear - WELL_FORMED_INV H4.\n          unfold wf_I in WELL_FORMED_INV.\n          eapply WELL_FORMED_INV in H4; ss. inv H4; eauto.\n        }\n        eapply wf_config_rm_prsv; eauto.\n        eapply wf_config_rm_prsv; eauto. \n\n        (* new thread will not generate race *)\n        eapply local_sim_rely_condition with\n            (n_tgt := 0) (n_src := 0) (lc_tgt1 := lc1) (lc_src1 := lc_src)\n          in H6; eauto.\n        eapply rely_local_sim_state_to_local_sim_state in H6; eauto.\n        eapply IHn with (ths_src := IdentMap.remove ctid ths_src) (sc_src := sc_src)\n                        (mem_src := mem_src) (b_src := true) (inj := inj') in A23; eauto.\n        {\n          destruct A23 as (npc_src & PSTEPS_SRC & WW_RACE_S).\n          exists npc_src. split; eauto.\n          eapply Relation_Operators.rt1n_trans. 2: eapply PSTEPS_SRC.\n          econs. \n          eapply NPConfiguration.step_thread_term with (tid2 := tid2); eauto; ss.          \n          rewrite IdentMap.gro; eauto.\n        } \n        { \n          ii.\n          assert (NOT_ORIGIN_TID: tid <> ctid).\n          {\n            ii; subst.\n            rewrite IdentMap.grs in READY_TGT_THD. ss.\n          }\n          rewrite IdentMap.gro in READY_TGT_THD; eauto.\n          rewrite IdentMap.gro; eauto.\n          lets READY_TGT_THD_ORIGN: READY_TGT_THD.\n          eapply READY_THRDS in READY_TGT_THD; eauto. des.\n          eapply local_sim_rely_condition with\n              (n_tgt := 0) (n_src := 0) (lc_tgt1 := lc1) (lc_src1 := lc_src)\n              (inj' := inj') in READY_TGT_THD0; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n        } \n        {\n          ii.\n          assert (NOT_ORIGIN_TID: tid2 <> ctid).\n          {\n            ii; subst.\n            rewrite IdentMap.grs in CUR_TGT_THRD. ss.\n          }\n          rewrite IdentMap.gro in CUR_TGT_THRD; eauto.\n          rewrite IdentMap.gro; eauto.\n          rewrite NEW_TID_OK in CUR_TGT_THRD.\n          inv CUR_TGT_THRD. eapply inj_pair2 in H9; eauto. subst.\n          do 3 eexists. split; eauto.\n        }\n        {\n          introv AUX_WW_RACE_S.\n          destruct AUX_WW_RACE_S as (npc_src' & PSTEPS_S & AUX_WW_RACE_S).\n          contradiction WWRF.\n          exists npc_src'. split; eauto.\n          eapply Relation_Operators.rt1n_trans; [ | eapply PSTEPS_S].\n          econs.\n          eapply NPConfiguration.step_thread_term; ss.\n          eauto. eauto. rewrite IdentMap.gro; eauto.\n        }\n        {\n          introv ABORT. destruct ABORT as (npc & TO_ABORT & ABORT).\n          contradiction SAFE.\n          exists npc.\n          split.\n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_thread_term; eauto.\n          ss. instantiate (3 := tid2). rewrite IdentMap.gro; eauto.\n          ss. eauto.\n        } \n        eapply wf_config_rm_prsv; eauto.\n        eapply wf_config_rm_prsv; eauto.\n        {\n          ii.\n          split; eauto. inv STEP_INV; eauto.\n        }\n        unfold wf_I in *. eapply WELL_FORMED_INV in H4; ss. inv H4; eauto.\n        eapply wf_config_to_local_wf; eauto.\n        eapply wf_config_to_local_wf; eauto.\n        inv WF_CONFIG_TGT; eauto.\n        inv WF_CONFIG_SRC; eauto.\n        inv WF_CONFIG_TGT; eauto.\n        inv WF_CONFIG_SRC; eauto.\n        inv STEP_INV; ss.\n        eapply wf_config_to_local_wf; eauto.\n        eapply wf_config_to_local_wf; eauto.\n        inv WF_CONFIG_TGT; eauto.\n        inv WF_CONFIG_SRC; eauto.\n        inv WF_CONFIG_TGT; eauto.\n        inv WF_CONFIG_SRC; eauto.\n        eapply wf_config_to_local_wf; eauto.\n        eapply wf_config_to_local_wf; eauto.\n        inv WF_CONFIG_TGT; eauto.\n        inv WF_CONFIG_SRC; eauto.\n        inv WF_CONFIG_TGT; eauto.\n        inv WF_CONFIG_SRC; eauto.\n      }\n      {\n        (* source thread will take multiply prefix steps *)\n        exploit Behavior.rtcn_tail; [eapply Hprefix_tau_steps | eauto..].\n        introv Hprefix_tau_steps'.\n        destruct Hprefix_tau_steps' as (npc' & PREFIX_STEPS & PREFIX_STEP).\n        destruct npc'. destruct state.\n        eapply rtcn_rtc in PREFIX_STEPS.\n        assert(CONSISTENT_T: Local.promises (Thread.local e_src) = Memory.bot).\n        {\n          clear - H2. inv H2. eauto.\n        }\n        exploit rtcn_rtc; [eapply Hprefix_tau_steps | eauto..]. introv PROFIX_STEPS_TEMP.\n        destruct e_src; ss.\n        exploit wf_config_rtc_NPThread_tau_steps_prsv; [ | | eapply PROFIX_STEPS_TEMP | eauto..]; eauto.\n        introv WF_CONFIG_SRC'.\n        eapply local_sim_rely_condition with (n_tgt := 0) (n_src := (S n0)) in H6; eauto.\n        eapply rely_local_sim_state_to_local_sim_state in H6; eauto.\n\n        (* discuss whether the new thread will generate ww race *)\n        destruct (classic (aux_ww_race lo (Configuration.mk (IdentMap.remove ctid ths_tgt) tid2 sc_tgt mem_tgt)))\n          as [TID2_WW_RACE | TID2_NOT_WW_RACE].\n        (* new thread will generate race *)\n        eapply ww_rf_preservation_aux_cur_race with\n            (ths_src := IdentMap.remove ctid (IdentMap.add ctid (existT Language.state lang state0, local0) ths_src))\n            (ctid := tid2) (sc_src := sc0) (mem_src := memory0) (inj := inj')\n          in TID2_WW_RACE; eauto.\n        {\n          eapply aux_wwrace_to_np_wwrace_from_outAtmBlk in TID2_WW_RACE; eauto.\n          des.\n          exists npc'. split; eauto.\n          eapply Relation_Operators.rt1n_trans.\n          econs. \n          eapply NPConfiguration.step_tau. ss.\n          ss. eauto. eauto.\n          ss. eapply PREFIX_STEPS. eapply PREFIX_STEP. eauto.\n          econs; ss. split; eauto.\n          eauto.\n          ss.\n          eapply Relation_Operators.rt1n_trans; [ | eapply TID2_WW_RACE].\n          econs.\n          eapply NPConfiguration.step_thread_term; ss.\n          rewrite IdentMap.gss; eauto. eauto.\n          rewrite IdentMap.gro; eauto. rewrite IdentMap.gso; eauto.\n          eapply wf_config_rm_prsv; eauto.\n        }\n        {\n          ii. \n          rewrite IdentMap.gro in H7; eauto.\n          rewrite IdentMap.gro; eauto. rewrite IdentMap.gso; eauto.\n          rewrite NEW_TID_OK in H7. inv H7. eapply inj_pair2 in H10. subst.\n          do 2 eexists.\n          split; eauto.\n        } \n        {\n          introv ABORT. destruct ABORT as (npc' & TO_ABORT & ABORT).\n          contradiction SAFE. clear PROFIX_STEPS_TEMP.\n          eexists npc'. split; eauto.\n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_tau; eauto.\n          unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss. ii.\n          eexists. split; eauto.\n          ss. eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_thread_term; ss; eauto.\n          rewrite IdentMap.gss; eauto.\n          ss. instantiate (3 := tid2).\n          rewrite IdentMap.gro; eauto.\n          rewrite IdentMap.gso; eauto.\n          eauto.\n        }\n        {\n          unfold wf_I in *.\n          eapply WELL_FORMED_INV in H4. inv H4; eauto.\n        }\n        eapply wf_config_rm_prsv; eauto.\n        eapply wf_config_rm_prsv; eauto.\n\n        (* new thread will not generate race *)\n        assert (MEM_AT_EQ: Mem_at_eq lo mem_tgt memory0).\n        {\n          eapply out_atmblk_I_inj_hold in H6; eauto.\n          des; eauto.\n          contradiction SAFE.\n          eexists.\n          split.\n          eapply Relation_Operators.rt1n_trans.\n          clear PROFIX_STEPS_TEMP.\n          econs. eapply NPConfiguration.step_tau; eauto.\n          unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss. ii.\n          eexists. split; eauto.\n          ss. eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_thread_term; ss; eauto.\n          rewrite IdentMap.gss; eauto.\n          ss. instantiate (3 := tid2).\n          rewrite IdentMap.gro; eauto.\n          rewrite IdentMap.gso; eauto.\n          eauto.\n          ss. econs; ss.\n          eapply NPAuxThread_tau_steps_2_Thread_tau_steps in H6; ss.\n          do 3 eexists.\n          split.\n          rewrite IdentMap.gro; eauto. rewrite IdentMap.gso; eauto.\n          split. eapply H6. eauto.\n        }\n        eapply IHn with (ths_src := IdentMap.remove ctid (IdentMap.add ctid (existT _ lang state0, local0) ths_src))\n                        (sc_src := sc0)\n                        (mem_src := memory0) (b_src := true) (inj := inj') in A23; eauto.\n        {\n          destruct A23 as (npc_src & PSTEPS_SRC & WW_RACE_S).\n          exists npc_src. split; eauto.\n          eapply Relation_Operators.rt1n_trans.\n          econs. \n          eapply NPConfiguration.step_tau. ss.\n          ss. eauto. eauto.\n          ss. eapply PREFIX_STEPS. eapply PREFIX_STEP. eauto.\n          econs; ss. split; eauto.\n          eauto.\n          ss.\n          eapply Relation_Operators.rt1n_trans; [ | eapply PSTEPS_SRC].\n          econs.\n          eapply NPConfiguration.step_thread_term; ss.\n          rewrite IdentMap.gss; eauto. eauto.\n          rewrite IdentMap.gro; eauto. rewrite IdentMap.gso; eauto.\n        }\n        {\n          ii.\n          assert (READY_TGT_NOT_DONE: tid <> ctid).\n          {\n            ii; subst.\n            rewrite IdentMap.grs in READY_TGT_THD. ss.\n          }\n          rewrite IdentMap.gro in READY_TGT_THD; eauto.\n          rewrite IdentMap.gro; eauto. rewrite IdentMap.gso; eauto.\n          exploit READY_THRDS; [ | eapply READY_TGT_THD | eauto..]; eauto.\n          ii; des.\n          eapply local_sim_rely_condition with (n_tgt := 0) (n_src := (S n0)) in H8; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          eapply wf_config_to_local_wf; eauto.\n          instantiate (3 := tid). rewrite IdentMap.gso; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC'; eauto.\n          inv WF_CONFIG_TGT; eauto.\n          inv WF_CONFIG_SRC'; eauto.\n        }\n        {\n          ii.\n          rewrite IdentMap.gro in CUR_TGT_THRD; eauto.\n          rewrite NEW_TID_OK in CUR_TGT_THRD. inv CUR_TGT_THRD. eapply inj_pair2 in H9. subst.\n          do 3 eexists. split; eauto.\n          rewrite IdentMap.gro; eauto.\n          rewrite IdentMap.gso; eauto.\n        } \n        {\n          introv AUX_WW_RACE_S. destruct AUX_WW_RACE_S as (npc' & PSTEPS_S & AUX_WW_RACE_S).\n          contradiction WWRF. clear PROFIX_STEPS_TEMP.\n          eexists npc'. split; eauto.\n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_tau; eauto.\n          unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss. ii.\n          eexists. split; eauto.\n          ss. eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_thread_term; ss; eauto.\n          rewrite IdentMap.gss; eauto.\n          ss. instantiate (3 := tid2).\n          rewrite IdentMap.gro; eauto.\n          rewrite IdentMap.gso; eauto.\n          eauto.\n        }\n        {\n          introv ABORT. destruct ABORT as (npc' & TO_ABORT & ABORT).\n          contradiction SAFE. clear PROFIX_STEPS_TEMP.\n          eexists npc'. split; eauto.\n          eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_tau; eauto.\n          unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss. ii.\n          eexists. split; eauto.\n          ss. eapply Relation_Operators.rt1n_trans.\n          econs. eapply NPConfiguration.step_thread_term; ss; eauto.\n          rewrite IdentMap.gss; eauto.\n          ss. instantiate (3 := tid2).\n          rewrite IdentMap.gro; eauto.\n          rewrite IdentMap.gso; eauto.\n          eauto.\n        }\n        eapply wf_config_rm_prsv; eauto.\n        eapply wf_config_rm_prsv; eauto.\n\n        unfold wf_I in *. eapply WELL_FORMED_INV in H4; eauto. inv H4; eauto.\n        eapply wf_config_to_local_wf; eauto.\n        eapply wf_config_to_local_wf; eauto.\n        instantiate (3 := tid2). rewrite IdentMap.gso; eauto.\n        inv WF_CONFIG_TGT; eauto.\n        inv WF_CONFIG_SRC'; eauto.\n        inv WF_CONFIG_TGT; eauto.\n        inv WF_CONFIG_SRC'; eauto.\n        { \n          inv STEP_INV.\n          eapply na_steps_dset_to_Thread_na_steps in H0; eauto.\n          eapply Mem_at_eq_na_steps_prsv with (m := mem_tgt) in H0; eauto; ss.\n          eapply Mem_at_eq_reflexive; eauto.\n          eapply Mem_at_eq_reflexive; eauto.\n        }\n        eapply wf_config_to_local_wf; eauto.\n        eapply wf_config_to_local_wf; eauto.\n        inv WF_CONFIG_TGT; eauto.\n        inv WF_CONFIG_SRC; eauto.\n        inv WF_CONFIG_TGT; eauto.\n        inv WF_CONFIG_SRC; eauto.\n        eapply wf_config_to_local_wf; eauto.\n        eapply wf_config_to_local_wf; eauto.\n        instantiate (3 := tid2). rewrite IdentMap.gso; eauto.\n        inv WF_CONFIG_TGT; eauto.\n        inv WF_CONFIG_SRC'; eauto.\n        inv WF_CONFIG_TGT; eauto.\n        inv WF_CONFIG_SRC'; eauto.\n      }\n    + (* output *)\n      exploit CUR_THRD; [eapply TID1 | eauto..]. ii; des.\n      exploit sim_output_steps; [eapply STEP | eauto..]. ii; des.\n      {\n        (* not abort *)\n        destruct e_src'.\n        exploit wf_config_NPThread_out_step_prsv; [ | | eapply STEP | eauto..]; eauto.\n        introv T_CONFIG_WF'.\n        destruct e_src0.\n        exploit wf_config_rtc_NPThread_tau_steps_prsv; [ | | eapply S_STEPS | eauto..]; eauto.\n        introv S_CONFIG_WF'.\n        exploit wf_config_NPThread_out_step_prsv; [ | | eapply S_OUT | eauto..]; eauto.\n        instantiate (1 := ctid).\n        rewrite IdentMap.gss; eauto.\n        introv S_CONFIG_WF''.\n        assert (PROM_BOT: Local.promises local = Memory.bot /\\ Local.promises local0 = Memory.bot).\n        {\n          clear - S_OUT. inv S_OUT; ss. inv H.\n          inv OUT. inv LOCAL. inv LOCAL0; ss.\n          exploit PROMISES; eauto.\n        }\n        destruct PROM_BOT as (PROM_BOT & PROM_BOT').\n\n        assert (TGT_PROM_CONS': Local.promise_consistent lc2).\n        {\n          inv STEP; ss. inv H2; ss. inv OUT; ss. inv LOCAL; ss.\n          inv LOCAL0; ss. exploit PROMISES; eauto. ii; ss.\n          rewrite H2 in PROMISE. rewrite Memory.bot_get in PROMISE. ss.\n        }\n        eapply rtc_rtcn in S_STEPS. des.\n        destruct n0.\n        {\n          (* source thread takes zero steps *)\n          inv S_STEPS.\n          exploit out_atmblk_I_inj_hold; eauto.\n          ii; des.\n          Focus 2.\n          contradiction SAFE.\n          eexists. split.\n          eapply Relation_Operators.rt1n_trans; [ | eauto].\n          econs.\n          eapply NPConfiguration.step_out; eauto.\n          ss. unfold NPAuxThread.consistent; ss; eauto.\n          unfold Thread.consistent_nprm; ss; eauto.\n          ss. econs; ss.\n          exists state local e_src'.\n          split; eauto. rewrite IdentMap.gss; eauto.\n          split; eauto. \n          eapply NPAuxThread_tau_steps_2_Thread_tau_steps in H2; eauto.\n          \n          eapply IHn with (ths_src := IdentMap.add ctid (existT _ lang state, local) ths_src)\n                          (sc_tgt := sc2) (mem_tgt := m2)\n                          (sc_src := sc) (mem_src := memory) (b_src := true) (inj := inj') in A23; eauto.\n          {\n            destruct A23 as (npc_src & PSTEPS_S & WW_RACE_S).\n            exists npc_src. split; eauto.\n            eapply Relation_Operators.rt1n_trans; [ | eapply PSTEPS_S].\n            econs.\n            eapply NPConfiguration.step_out; eauto.\n            ss.\n            econs; eauto.\n          }\n          {\n            introv AUX_WW_RACE_T.\n            contradiction CUR_NOT_RACE.\n            inv STEP; ss.\n            inv AUX_WW_RACE_T.\n            rewrite IdentMap.gss in CTID. inv CTID. eapply inj_pair2 in H9. subst.\n            econs.\n            instantiate (2 := st1). instantiate (1 := lc1). eauto.\n            eapply Relation_Operators.rt1n_trans; [ | eapply STEPS].\n            eapply out_step_is_all_step; eauto.\n            eauto. eauto. eauto. eauto.\n          } \n          {\n            ii.\n            rewrite IdentMap.gso in READY_TGT_THD; eauto.\n            rewrite IdentMap.gso; eauto.\n            exploit READY_THRDS; [ | eapply READY_TGT_THD | eauto..]; eauto.\n            ii; des.\n            do 2 eexists.\n            split; eauto. split; eauto.\n            eapply local_sim_out_rely_condition with (n_src := 0); eauto.\n            eapply wf_config_to_local_wf; eauto.\n            eapply wf_config_to_local_wf; eauto.\n            instantiate (3 := ctid). rewrite IdentMap.gss; eauto.\n            inv WF_CONFIG_TGT; eauto.\n            inv S_CONFIG_WF'; eauto.\n            inv WF_CONFIG_TGT; eauto.\n            inv S_CONFIG_WF'; eauto.\n            eapply wf_config_to_local_wf; eauto. \n            instantiate (3 := tid). rewrite IdentMap.gso; eauto.\n            eapply wf_config_to_local_wf; eauto.\n            instantiate (3 := tid).\n            rewrite IdentMap.gso; eauto. rewrite IdentMap.gso; eauto.\n            inv T_CONFIG_WF'; eauto.\n            inv T_CONFIG_WF'; eauto.\n            inv S_CONFIG_WF''; eauto.\n            inv S_CONFIG_WF''; eauto.\n          }\n          {\n            ii.\n            rewrite IdentMap.gss in CUR_TGT_THRD; eauto.\n            inv CUR_TGT_THRD. eapply inj_pair2 in H7. subst.\n            rewrite IdentMap.gss; eauto.\n            do 3 eexists. split; eauto.\n          }\n          {\n            introv AUX_WW_RACE_S.\n            destruct AUX_WW_RACE_S as (npc_src & PSTEPS_S & AUX_WW_RACE_S).\n            contradiction WWRF.\n            exists npc_src. split; eauto.\n            econs.\n            econs.\n            eapply NPConfiguration.step_out; eauto.\n            ss. unfold NPAuxThread.consistent; ii; ss; eauto.\n            ss.\n          }\n          {\n            introv ABORT_S.\n            destruct ABORT_S as (npc_src & PSTEPS_S & ABORT_S).\n            contradiction SAFE.\n            exists npc_src. split; eauto.\n            econs.\n            econs.\n            eapply NPConfiguration.step_out; eauto.\n            ss. unfold NPAuxThread.consistent; ii; ss; eauto.\n            ss.\n          }\n          {\n            rewrite IdentMap.add_add_eq in S_CONFIG_WF''; eauto.\n          } \n        }\n        {\n          (* source thread takes multiply steps *)\n          exploit Behavior.rtcn_tail; [eapply S_STEPS | eauto..].\n          introv Hprefix_tau_steps'.\n          destruct Hprefix_tau_steps' as (npc' & PREFIX_STEPS & PREFIX_STEP).\n          destruct npc'. destruct state1.\n          eapply rtcn_rtc in PREFIX_STEPS.\n          \n          exploit out_atmblk_I_inj_hold; eauto.\n          ii; des.\n          Focus 2.\n          contradiction SAFE.\n          eexists. split.\n          eapply Relation_Operators.rt1n_trans.\n          econs.\n          eapply NPConfiguration.step_tau; eauto.\n          unfold NPAuxThread.consistent.\n          unfold Thread.consistent_nprm; ss. ii; eauto.\n          eapply Relation_Operators.rt1n_trans; [ | eauto].\n          ss.\n          econs.\n          eapply NPConfiguration.step_out; eauto.\n          ss. rewrite IdentMap.gss; eauto.\n          ss. unfold NPAuxThread.consistent; ss; eauto.\n          unfold Thread.consistent_nprm; ss; eauto.\n          ss. econs; ss.\n          exists state local e_src'.\n          split; eauto. rewrite IdentMap.gss; eauto.\n          split; eauto. \n          eapply NPAuxThread_tau_steps_2_Thread_tau_steps in H2; eauto.\n          \n          eapply IHn with (ths_src := IdentMap.add ctid (existT _ lang state, local) ths_src)\n                          (sc_tgt := sc2) (mem_tgt := m2)\n                          (sc_src := sc) (mem_src := memory) (b_src := true) (inj := inj') in A23; eauto. \n          {\n            destruct A23 as (npc_src & PSTEPS_S & WW_RACE_S).\n            exists npc_src. split; eauto.\n            eapply Relation_Operators.rt1n_trans.\n            econs.\n            eapply NPConfiguration.step_tau; eauto.\n            unfold NPAuxThread.consistent.\n            unfold Thread.consistent_nprm; eauto.\n            ss.\n            eapply Relation_Operators.rt1n_trans.\n            econs.\n            eapply NPConfiguration.step_out; eauto.\n            ss. rewrite IdentMap.gss; eauto.\n            ss. unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; ss.\n            ii. eauto.\n            ss; eauto.\n            rewrite IdentMap.add_add_eq; eauto.\n          }\n          {\n            introv AUX_WW_RACE_T.\n            contradiction CUR_NOT_RACE.\n            inv AUX_WW_RACE_T.\n            rewrite IdentMap.gss in CTID. inv CTID. eapply inj_pair2 in H7. subst.\n            inv STEP; ss.\n            econs. eauto.\n            eapply Relation_Operators.rt1n_trans; [ | eapply STEPS | eauto..].\n            eapply out_step_is_all_step; eauto.\n            eauto. eauto. eauto. eauto.\n          } \n          {\n            ii.\n            rewrite IdentMap.gso in READY_TGT_THD; eauto.\n            rewrite IdentMap.gso; eauto.\n            exploit READY_THRDS; [| eapply READY_TGT_THD | eauto..]; eauto.\n            ii; des.\n            do 2 eexists.\n            split; eauto. split; eauto.\n            eapply local_sim_out_rely_condition with (n_src := S n0); eauto.\n            eapply wf_config_to_local_wf; eauto.\n            eapply wf_config_to_local_wf; eauto.\n            inv WF_CONFIG_TGT; eauto.\n            inv WF_CONFIG_SRC; eauto.\n            inv WF_CONFIG_TGT; eauto.\n            inv WF_CONFIG_SRC; eauto.\n            eapply wf_config_to_local_wf; eauto.\n            instantiate (3 := tid). rewrite IdentMap.gso; eauto.\n            eapply wf_config_to_local_wf; eauto.\n            instantiate (3 := tid). rewrite IdentMap.gso; eauto. rewrite IdentMap.gso; eauto.\n            inv T_CONFIG_WF'; eauto.\n            inv T_CONFIG_WF'; eauto.\n            inv S_CONFIG_WF''; eauto.\n            inv S_CONFIG_WF''; eauto.\n          }\n          {\n            ii.\n            rewrite IdentMap.gss in CUR_TGT_THRD; eauto.\n            inv CUR_TGT_THRD. eapply inj_pair2 in H7. subst.\n            do 3 eexists.\n            split; eauto.\n            rewrite IdentMap.gss; eauto.\n          }\n          {\n            introv AUX_WW_RACE_S.\n            destruct AUX_WW_RACE_S as (npc_src & PSTEPS_S & AUX_WW_RACE_S).\n            contradiction WWRF.\n            exists npc_src. split; eauto.\n            econs.\n            econs.\n            eapply NPConfiguration.step_tau; eauto.\n            unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; eauto.\n            ss.\n            econs. econs.\n            eapply NPConfiguration.step_out; eauto.\n            ss. rewrite IdentMap.gss; eauto.\n            ss. unfold NPAuxThread.consistent; ii; ss; eauto.\n            ss. rewrite IdentMap.add_add_eq; eauto.\n          }\n          {\n            introv ABORT_S.\n            destruct ABORT_S as (npc_src & PSTEPS_S & ABORT_S).\n            contradiction SAFE.\n            exists npc_src. split; eauto.\n            econs.\n            econs.\n            eapply NPConfiguration.step_tau; eauto.\n            unfold NPAuxThread.consistent. unfold Thread.consistent_nprm; eauto.\n            ss.\n            econs. econs.\n            eapply NPConfiguration.step_out; eauto.\n            ss. rewrite IdentMap.gss; eauto.\n            ss. unfold NPAuxThread.consistent; ii; ss; eauto.\n            ss. rewrite IdentMap.add_add_eq; eauto.\n          }\n          {\n            rewrite IdentMap.add_add_eq in S_CONFIG_WF''; eauto.\n          }\n        }\n      }\n      {\n        contradiction SAFE.\n        eexists. split; eauto; ss.\n        econs; ss.\n        eapply NPAuxThread_tau_steps_2_Thread_tau_steps in S_STEPS; ss.\n        do 3 eexists.\n        split; eauto.\n      }\n      Unshelve.\n      exact st2.\n      exact true.\n      exact lang0.\n      exact st_tgt.\n      exact true.\n      exact st_tgt.\n      exact true.\n      exact lang.\n      exact st_src0.\n      exact true.\n      exact st_src0.\n      exact true.\n      exact lang0.\n      exact st_tgt.\n      exact true.\n      exact st_tgt.\n      exact true.\n      exact state.\n      exact true.\n      exact state.\n      exact true.\nQed.\n\n(** ww-race preservation proof *)\nLemma ww_RF_preservation_aux\n      (index: Type) (index_order: index -> index -> Prop)\n      (I: Invariant) (lo: Ordering.LocOrdMap) inj\n      (ths_tgt ths_src: Threads.t) (ctid: IdentMap.key)\n      (sc_tgt sc_src: TimeMap.t) (mem_tgt mem_src: Memory.t) npc_tgt\n      (WELL_FOUNDED_ORDER: well_founded index_order)\n      (WELL_FORMED_INV: wf_I I)\n      (T_STEPS: rtc (NPConfiguration.all_step lo)\n                    (NPConfiguration.mk (Configuration.mk ths_tgt ctid sc_tgt mem_tgt) true) npc_tgt)\n      (WW_RACE: ww_race lo (NPConfiguration.cfg npc_tgt))\n      (READY_THRDS: \n         forall tid (READY_TID: tid <> ctid) lang st_tgt lc_tgt\n           (READY_TGT_THD: IdentMap.find tid ths_tgt = Some (existT _ lang st_tgt, lc_tgt)),\n         exists st_src lc_src,\n           IdentMap.find tid ths_src = Some (existT _ lang st_src, lc_src) /\\ \n           @rely_local_sim_state index index_order lang I lo inj\n                                 (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                                 (Thread.mk lang st_src lc_src sc_src mem_src) /\\\n           <<R_PROM_CONS_T: Local.promise_consistent lc_tgt>>)\n      (CUR_THRD: \n         forall lang st_tgt lc_tgt  \n           (CUR_TGT_THRD: IdentMap.find ctid ths_tgt = Some (existT _ lang st_tgt, lc_tgt)),\n         exists st_src lc_src,\n           IdentMap.find ctid ths_src = Some (existT _ lang st_src, lc_src) /\\\n           @local_sim_state index index_order lang I lo inj dset_init true\n                            (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                            (Thread.mk lang st_src lc_src sc_src mem_src) /\\\n           <<C_PROM_CONS_T: Local.promise_consistent lc_tgt>>)\n      (CONSISTENTS: NPConfiguration.consistent\n                      (NPConfiguration.mk (Configuration.mk ths_tgt ctid sc_tgt mem_tgt) true) lo)\n      (SAFE: ~(exists npc,\n                  rtc (NPConfiguration.all_step lo)\n                      (NPConfiguration.mk (Configuration.mk ths_src ctid sc_src mem_src) true) npc /\\\n                  Configuration.is_abort (NPConfiguration.cfg npc) lo))\n      (WWRF: ~(exists npc,\n                    rtc (NPConfiguration.all_step lo)\n                        (NPConfiguration.mk (Configuration.mk ths_src ctid sc_src mem_src) true) npc /\\\n                    aux_ww_race lo (NPConfiguration.cfg npc)))\n      (WF_CONFIG_TGT: Configuration.wf (Configuration.mk ths_tgt ctid sc_tgt mem_tgt))\n      (WF_CONFIG_SRC: Configuration.wf (Configuration.mk ths_src ctid sc_src mem_src))\n      (INV_OUT_ATM: Mem_at_eq lo mem_tgt mem_src /\\ I lo inj (Build_Rss sc_tgt mem_tgt sc_src mem_src))\n      (MONOTONIC_INJ: monotonic_inj inj):\n  exists npc_src,\n    rtc (NPConfiguration.all_step lo)\n        (NPConfiguration.mk (Configuration.mk ths_src ctid sc_src mem_src) true) npc_src /\\\n    ww_race lo (NPConfiguration.cfg npc_src).\nProof.\n  destruct (classic (aux_ww_race lo (Configuration.mk ths_tgt ctid sc_tgt mem_tgt))) as\n      [CUR_WILL_RACE | CUR_WILL_NOT_RACE].\n  {\n    (* current thread will race *)\n    eapply ww_rf_preservation_aux_cur_race in CUR_WILL_RACE; eauto.\n    eapply sound_np_aux_wwrace. eauto.\n    split. eauto. ss.\n  }\n  {\n    (* current thread will not abort *)\n    eapply rtc_rtcn in T_STEPS. des.\n    eapply ww_rf_preservation_aux_cur_not_race; eauto.\n    introv CTH.\n    eapply CUR_THRD in CTH; eauto. des.\n    do 3 eexists.\n    split; eauto.\n  }\nQed.\n\n(** ** Write-Write Race Freedom Preservation *)\n(** It depicts that, if\n    - [LOCAL_SIM]: local simulation holds;\n    - [SAFE_NP_SRC]: source program is safe;\n    - [WW_RF_NP_SRC]: source program is write-write race free;\n    then the target program is write-write race free. *)\nLemma ww_RF_preservation\n      (lang: language) (index: Type) (index_order: index -> index -> Prop)\n      (I: Invariant) (lo: Ordering.LocOrdMap)\n      (code_t code_s: Language.syntax lang) (fs: list IdentMap.key) (ctid: IdentMap.key)\n      (LOCAL_SIM: @local_sim index index_order lang I lo code_t code_s)\n      (SAFE_NP_SRC: NPConfiguration.safe lo fs code_s ctid)\n      (WW_RF_NP_SRC: ww_rf_np lo fs code_s ctid):\n  ww_rf_np lo fs code_t ctid.\nProof.\n  inv LOCAL_SIM.\n  unfold ww_rf_np. introv ww_Race_np_tgt.\n  unfold ww_rf_np in WW_RF_NP_SRC.\n  contradiction WW_RF_NP_SRC.\n  inv ww_Race_np_tgt.\n\n  (* destruct the target initial state *)\n  unfolds NPConfiguration.init.\n  destruct (Configuration.init fs code_t ctid) eqn:H_tgt_init; tryfalse.\n  inv NPLOAD. \n  renames t to c_tgt.\n\n  (* construct the source initial state *)\n  lets H_src_init : H_tgt_init.\n  eapply cons_source_init_from_target_init_program in H_src_init; eauto.\n  destruct H_src_init as (c_src & H_src_init & Htgt_2_src & Hsrc_2_tgt).\n\n  (* construct ww_race in source *)\n  destruct c_tgt; ss. destruct c_src; ss.\n  renames threads to ths_tgt, sc to sc_tgt, memory to mem_tgt.\n  renames threads0 to ths_src, sc0 to sc_src, memory0 to mem_src.\n  assert (Hctid: tid = ctid /\\ tid0 = ctid).\n  {\n    clear - H_tgt_init H_src_init.\n    unfolds Configuration.init.\n    destruct (Threads.init fs code_t); tryfalse.\n    inv H_tgt_init.\n    destruct (Threads.init fs code_s); tryfalse.\n    inv H_src_init; eauto.\n  }\n  destruct Hctid; subst.\n  eapply config_init_ths_sc_mem in H_tgt_init; simpl in H_tgt_init.\n  destruct H_tgt_init as (Hths_tgt_init & Hsc_tgt_init & Hmem_tgt_init); subst.\n  eapply config_init_ths_sc_mem in H_src_init; simpl in H_src_init.\n  destruct H_src_init as (Hths_src_init & Hsc_src_init & Hmem_src_init); subst.\n  assert (NP_CONFIG_INIT: NPConfiguration.init fs code_s ctid =\n                          Some (NPConfiguration.mk (Configuration.mk ths_src ctid TimeMap.bot Memory.init) true)).\n  {\n    clear - Hths_src_init.\n    unfold NPConfiguration.init, Configuration.init; simpl.\n    rewrite Hths_src_init; eauto.\n  } \n  \n  eapply ww_RF_preservation_aux in STEPS; eauto.\n  instantiate (3 := ths_src) in STEPS.\n  instantiate (2 := TimeMap.bot) in STEPS.\n  instantiate (1 := Memory.init) in STEPS.\n  des.\n  econs; eauto.\n\n  (* ready threads *)\n  introv Hready_tid Hready_th.\n  assert (lang0 = lang).\n  {\n    clear - Hths_tgt_init Hready_th.\n    eapply thread_init_same_lang in Hths_tgt_init; eauto.\n  }\n  subst.\n  eapply Htgt_2_src in Hready_th.\n  destruct Hready_th as (st_src & lc_src & Hlc_tgt_init & Hlc_src_init & Hsrc_ready_th & Hlocal_sim_state); subst.\n  do 2 eexists.\n  split. eapply Hsrc_ready_th.\n  split.\n  eapply local_sim_state_to_rely_local_sim_state; eauto.\n  instantiate (1 := ctid).\n  clear - SAFE_NP_SRC NP_CONFIG_INIT.\n  inv SAFE_NP_SRC.\n  eapply SAFE_EXEC in NP_CONFIG_INIT. ii. des.\n  contradiction NP_CONFIG_INIT. econs; eauto.\n  unfold Local.promise_consistent, Local.init. ii; ss.\n  rewrite Memory.bot_get in PROMISE. ss.\n  unfold Local.promise_consistent, Local.init. ii; ss.\n  rewrite Memory.bot_get in PROMISE. ss.\n\n  (* current thread *)\n  introv Hcur_th.\n  assert (lang0 = lang).\n  {\n    clear - Hths_tgt_init Hcur_th.\n    eapply thread_init_same_lang in Hths_tgt_init; eauto.\n  }\n  subst.\n  eapply Htgt_2_src in Hcur_th.\n  destruct Hcur_th as(st_src & lc_src & Hlc_tgt_init & Hlc_src_init & Hsrc_cur_th & Hlocal_sim_state); subst.\n  do 2 eexists.\n  split; eauto.\n  split; eauto.\n  unfold Local.promise_consistent, Local.init. ii; ss.\n  rewrite Memory.bot_get in PROMISE. ss.\n\n  (* consistent *)\n  unfold NPConfiguration.consistent; ss.\n  unfold Threads.consistent_nprm. intros.\n  assert (lang0 = lang).\n  {\n    clear - Hths_tgt_init TH.\n    eapply thread_init_same_lang in Hths_tgt_init; eauto.\n  }\n  subst.\n  eapply thread_init_lc_init with (fs := fs) (code := code_t) in TH; eauto.\n  subst.\n  unfold Thread.consistent_nprm; ss. ii.\n  eexists. split. eauto. ss.\n\n  (* safe *) \n  eapply sound_np_abort; eauto. \n  clear - SAFE_NP_SRC NP_CONFIG_INIT.\n  inv SAFE_NP_SRC.\n  eapply SAFE_EXEC in NP_CONFIG_INIT; eauto.\n  clear - NP_CONFIG_INIT.\n  introv Hnp_abort.\n  contradict NP_CONFIG_INIT.\n  destruct Hnp_abort as (npc' & Hrtc_steps & Habort).\n  econstructor; eauto.\n\n  (* Source aux safe *)\n  eapply sound_np_aux_wwrf; eauto.\n  eapply wf_config_init with (fs := fs) (code := code_s) (ctid := ctid); eauto.\n  clear - NP_CONFIG_INIT.\n  unfolds NPConfiguration.init; eauto.\n  destruct (Configuration.init fs code_s ctid); tryfalse.\n  inv NP_CONFIG_INIT; eauto.\n  clear - WW_RF_NP_SRC NP_CONFIG_INIT.\n  unfolds ww_rf_np.\n  introv Haux_ww_race.\n  contradict WW_RF_NP_SRC.\n  destruct Haux_ww_race as (npc' & Hrtc & Haux_ww_race).\n  econstructor.\n  Focus 2. eapply Hrtc.\n  eauto.\n  eauto.\n\n  (* well-formed target configuraiton in initialization *)\n  eapply wf_config_init with (fs := fs) (code := code_t) (ctid := ctid); eauto.\n  unfold Configuration.init.\n  rewrite Hths_tgt_init; eauto.\n\n  (* well-formed source configuraiton in initialization *)\n  eapply wf_config_init with (fs := fs) (code := code_s) (ctid := ctid); eauto.\n  unfold Configuration.init.\n  rewrite Hths_src_init; eauto.\n\n  split. eapply Mem_at_eq_init. eauto.\n  unfold monotonic_inj. ii. unfold inj_init in *.\n  des_ifH INJ1; ss. subst. inv INJ1.\n  des_ifH INJ2; ss. subst. inv INJ2.\n  auto_solve_time_rel.\nQed. \n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/proofs/wwRF-preservation/wwRFPrsv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22317699621927717}}
{"text": "Require Import CertiGraph.CertiGC.gc_spec.\nRequire Import CertiGraph.msl_ext.ramification_lemmas.\n\nLocal Open Scope logic.\n\nLemma root_valid_int_or_ptr: forall g (roots: roots_t) root outlier,\n    In root roots ->\n    roots_compatible g outlier roots ->\n    graph_rep g * outlier_rep outlier |-- !! (valid_int_or_ptr (root2val g root)).\nProof.\n  intros. destruct H0. destruct root as [[? | ?] | ?].\n  - simpl root2val. unfold odd_Z2val. replace (2 * z + 1) with (z + z + 1) by lia.\n    apply prop_right, valid_int_or_ptr_ii1.\n  - sep_apply (roots_outlier_rep_single_rep _ _ _ H H0).\n    sep_apply (single_outlier_rep_valid_int_or_ptr g0). entailer!.\n  - red in H1. rewrite Forall_forall in H1.\n    rewrite (filter_sum_right_In_iff v roots) in H.\n    apply H1 in H. simpl. sep_apply (graph_rep_valid_int_or_ptr _ _ H). entailer!.\nQed.\n\nLemma weak_derives_strong: forall (P Q: mpred),\n    P |-- Q -> P |-- (weak_derives P Q && emp) * P.\nProof.\n  intros. cancel. apply andp_right. 2: cancel.\n  assert (HS: emp |-- TT) by entailer; sep_apply HS; clear HS.\n  apply derives_weak. assumption.\nQed.\n\nLemma sapi_ptr_val: forall p m n,\n    isptr p -> Int.min_signed <= n <= Int.max_signed ->\n    (force_val\n       (sem_add_ptr_int int_or_ptr_type Signed (offset_val (WORD_SIZE * m) p)\n                        (vint n))) = offset_val (WORD_SIZE * (m + n)) p.\nProof.\n  intros. rewrite sem_add_pi_ptr_special; [| easy | | easy].\n  - simpl. rewrite offset_offset_val. f_equal. fold WORD_SIZE; rep_lia.\n  - rewrite isptr_offset_val. assumption.\nQed.\n\nLemma sapil_ptr_val: forall p m n,\n    isptr p ->\n    if Archi.ptr64 then\n      force_val\n        (sem_add_ptr_long int_or_ptr_type (offset_val (WORD_SIZE * m) p)\n                          (Vlong (Int64.repr n))) = offset_val (WORD_SIZE * (m + n)) p\n    else\n      force_val\n        (sem_add_ptr_int int_or_ptr_type Signed (offset_val (WORD_SIZE * m) p)\n                         (vint n)) = offset_val (WORD_SIZE * (m + n)) p.\nProof.\n  intros. simpl.\n  first [rewrite sem_add_pi_ptr_special' | rewrite sem_add_pl_ptr_special']; auto.\n  simpl. fold WORD_SIZE. rewrite offset_offset_val. f_equal. lia.\nQed.\n\nLemma data_at_mfs_eq: forall g v i sh nv,\n    field_compatible int_or_ptr_type [] (offset_val (WORD_SIZE * i) nv) ->\n    0 <= i < Zlength (raw_fields (vlabel g v)) ->\n    data_at sh (tarray int_or_ptr_type i) (sublist 0 i (make_fields_vals g v)) nv *\n    field_at sh int_or_ptr_type [] (Znth i (make_fields_vals g v))\n             (offset_val (WORD_SIZE * i) nv) =\n    data_at sh (tarray int_or_ptr_type (i + 1))\n            (sublist 0 (i + 1) (make_fields_vals g v)) nv.\nProof.\n  intros. rewrite field_at_data_at. unfold field_address.\n  rewrite if_true by assumption. simpl nested_field_type.\n  simpl nested_field_offset. rewrite offset_offset_val.\n  replace (WORD_SIZE * i + 0) with (WORD_SIZE * i)%Z by lia.\n  rewrite <- (data_at_singleton_array_eq\n                sh int_or_ptr_type _ [Znth i (make_fields_vals g v)]) by reflexivity.\n  rewrite <- fields_eq_length in H0.\n  rewrite (data_at_tarray_value\n             sh (i + 1) i nv (sublist 0 (i + 1) (make_fields_vals g v))\n             (make_fields_vals g v) (sublist 0 i (make_fields_vals g v))\n             [Znth i (make_fields_vals g v)]).\n  - replace (i + 1 - i) with 1 by lia. reflexivity.\n  - lia.\n  - lia.\n  - autorewrite with sublist. reflexivity.\n  - reflexivity.\n  - rewrite sublist_one; [reflexivity | lia..].\nQed.\n\nLemma data_at__value_0_size: forall sh p,\n    data_at_ sh (tarray int_or_ptr_type 0) p |-- emp.\nProof. intros. rewrite data_at__eq. apply data_at_zero_array_inv; reflexivity. Qed.\n\nLemma data_at_minus1_address: forall sh v p,\n    data_at sh (if Archi.ptr64 then tulong else tuint)\n            v (offset_val (- WORD_SIZE) p) |--\n            !! (force_val (sem_add_ptr_int (if Archi.ptr64 then tulong else tuint)\n                                           Signed p (eval_unop Oneg tint (vint 1))) =\n                field_address (if Archi.ptr64 then tulong else tuint) []\n                              (offset_val (- WORD_SIZE) p)).\nProof.\n  intros. unfold eval_unop. simpl. entailer!.\n  unfold field_address. rewrite if_true by assumption. rewrite offset_offset_val.\n  simpl. reflexivity.\nQed.\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/CertiGC/forward_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.22317699621927714}}
{"text": "Require Import Crypto.\nRequire Import ProtoRep.\nRequire Import CpdtTactics.\nRequire Import Eqdep_dec.\nRequire Import Program.\nRequire Import SfLib.\nRequire Import Coq.Program.Equality.\nRequire Import LibTactics.\n\nDefinition ob (t:type) := list ((message t) * (list (message Key))).\n\nRecord State : Type := mkState\n        {keys : list (message Key);\n         basics : list (message Basic);\n         kOb : ob Key;\n         bOb : ob Basic \n        }.\n\nDefinition emptyState := mkState nil nil nil nil.\n\nDefinition Assertion := State -> Prop.\n\nDefinition addKey : forall mt (m:message mt) (pf: mt = Key),\n    (list (message Key)) -> (list (message Key)).\nProof.\n  intros. subst. exact (m :: X).\nDefined.\n\nDefinition addMKey t (m:message t) : (list (message Key)) -> (list (message Key)) := fun l => (\n  match t as t' return (t = t') -> (list (message Key)) with\n  | Key => fun pf => (addKey t m pf l)\n  | _ => fun _ => l\n  end (eq_refl t)).\n\nDefinition addBasic : forall mt (m:message mt) (pf: mt = Basic),\n    (list (message Basic)) -> (list (message Basic)).\nProof.\n  intros. subst. exact (m :: X).\nDefined.\n\nDefinition addMBasic t (m:message t) : (list (message Basic)) -> (list (message Basic)) := fun l => (\n  match t as t' return (t = t') -> (list (message Basic)) with\n  | Basic => fun pf => (addBasic t m pf l)\n  | _ => fun _ => l\n  end (eq_refl t)).\n\nDefinition addP (t:type) : forall mt (pf:mt = t),  ((message mt) * (list (message Key))) -> (ob t) -> (ob t).\nProof.\n  intros. subst. exact (X :: X0 ).\nDefined.\n\nDefinition addMp mt (p:((message mt)*(list (message Key)))) : (ob Basic) -> (ob Basic) := fun l => (\n  match mt as t' return (mt = t') -> (ob Basic) with\n  | Basic => fun pf => (addP _ _ pf p l)\n  | _ => fun _ => l\n  end (eq_refl mt)).\n\nDefinition addMpK mt (p:((message mt)*(list (message Key)))) : (ob Key) -> (ob Key) := fun l => (\n  match mt as t' return (mt = t') -> (ob Key) with\n  | Key => fun pf => (addP _ _ pf p l)\n  | _ => fun _ => l\n  end (eq_refl mt)).\n\nFixpoint obligations'{mt:type} (m:message mt) (kl: list (message Key))\n                               (l:ob Basic) : ob Basic :=\n  match m with\n  | encrypt mt' m' k => match mt' with\n                       | Basic => let new := (m', (kl ++ [(key k)])) in\n                                 addMp mt' new l\n                       | _ => obligations' m' (kl ++ [(key k)]) l\n                       end\n  | pair _ _ m1 m2 => (obligations' m1 kl l) ++ (obligations' m2 kl l)\n  | basic n => addMp _ ((basic n), kl) l\n  | _ => addMp _ (m, nil) l                                           \n  end.\n\n\nDefinition obligations{mt:type} (m:message mt) : ob Basic :=\n  obligations' m nil nil.\n\nFixpoint obligationsK'{mt:type} (m:message mt) (kl: list (message Key))\n                               (l:ob Key) : ob Key :=\n  match m with\n  | encrypt mt' m' k => match mt' with\n                       | Key => let new := (m', (kl ++ [(key k)])) in\n                                 addMpK _ new l\n                       | _ => obligationsK' m' (kl ++ [(key k)]) l\n                       end\n  | pair _ _ m1 m2 => (obligationsK' m1 kl l) ++ (obligationsK' m2 kl l)\n  | key k => addMpK _ ((key k), kl) l \n  | _ => addMpK _ (m, nil) l                                           \n  end.\n\nDefinition obligationsK{mt:type} (m:message mt) : ob Key :=\n  obligationsK' m nil nil.\n\nDefinition updateState{t:type} (m:message t) (sIn: State) : State :=\n  match t with\n  | Basic => mkState  sIn.(keys) (addMBasic t m sIn.(basics)) sIn.(kOb) sIn.(bOb)\n  | Key => mkState (addMKey t m sIn.(keys)) sIn.(basics) sIn.(kOb) sIn.(bOb)\n  | Encrypt _ => mkState sIn.(keys) sIn.(basics)\n                                       ((obligationsK m) ++ sIn.(kOb))\n                                       ((obligations m) ++ sIn.(bOb))                                                                    \n  | _ =>  sIn\n  end.\n\nInductive step : forall (s:State) (t r t':protoType),\n    (protoExp t) -> (protoExp r) -> (protoExp t') -> State -> Prop :=\n| ST_Send_Rec : forall x y  mt\n                  (m:message mt) (p1':protoExp x)\n                  (f:(message mt) -> protoExp y) (s:State),\n    step s _ _ _ (SendC m p1') (ReceiveC f) p1' s\n| ST_Rec_Send : forall x y mt (m:message mt) (p1':protoExp x)\n                       (f:(message mt) -> protoExp y) s,                     \n    step s _ _ _ (ReceiveC f) (SendC m p1') (f m) (updateState m s)\n| ST_Choice_true : forall rt rt' st st'\n                     (r:protoExp rt) (r0:protoExp rt')\n                     (s:protoExp st) (s0:protoExp st') stt,\n    step stt _ _ _ (ChoiceC true r s) (OfferC r0 s0) r stt\n| ST_Choice_false : forall rt rt' st st'\n                     (r:protoExp rt) (r0:protoExp rt')\n                     (s:protoExp st) (s0:protoExp st') stt,\n    step stt _ _ _ (ChoiceC false r s) (OfferC r0 s0) s stt\n| ST_Offer_true : forall rt rt' st st'\n                     (r:protoExp rt) (r0:protoExp rt')\n                     (s:protoExp st) (s0:protoExp st') stt,\n    step stt _ _ _ (OfferC r0 s0) (ChoiceC true r s) r0 stt\n| ST_Offer_false : forall rt rt' st st'\n                     (r:protoExp rt) (r0:protoExp rt')                     (s:protoExp st) (s0:protoExp st') stt,\n    step stt _ _ _ (OfferC r0 s0) (ChoiceC false r s) s0 stt.\n\n(*Notation \"'stepe' st st'\" := (step st _ _ _ st') (at level 50).*)\n\nInductive multi : forall s (t r t':protoType),\n    (protoExp t) -> (protoExp r)  -> (protoExp t') -> State -> Prop :=\n| multi_refl : forall (t r :protoType) (x:protoExp t) (y:protoExp r) st,\n    multi st _ _ _ x y x st\n| multi_step : forall (t t' r r2 s:protoType),\n    forall (x:protoExp t) (x':protoExp t')\n      (y:protoExp r) (y2:protoExp r2)\n      (z1:protoExp s) st st' st'' st2 st2',\n                    step st _ _ _ x x' y st' ->\n                    step st2 _ _ _ x' x y2 st2' -> \n                    multi st' _ _ _ y y2 z1 st'' ->\n                    multi st _ _ _ x x' z1 st''.\n\n(*Notation \"'multie' st st'\" := (multi st _ _ _ st')\n                                (at level 50).*)\n\nDefinition normal_form {p1t p2t:protoType}\n           (p1:protoExp p1t)(p2:protoExp p2t) : Prop :=\n  forall st st',  ~ exists  t' (x:protoExp t'),  step st _ _ _ p1 p2 x st'.\n\nTheorem nf_ex : normal_form (ReturnC (basic 0)) (ReturnC (basic 1)).\nProof.\n unfold normal_form. unfold not. intros. destruct H. destruct H. inversion H.\nQed.\n\nAxiom updateBoth :  forall t (m:message t) x6 x7 p1t p2t p3t (p1:protoExp p1t) (p2:protoExp p2t) (p3: protoExp p3t),\n    multi x6 _ _ _ p1 p2 p3 x7 ->\n    multi (updateState m x6) _ _ _ p1 p2 p3 (updateState m x7).\n\nLtac bool_destruct :=\n  match goal with H: bool |- _ =>\n                  destruct H\n  end.\n\nLtac steps_destruct :=\n  match goal with H: step _ _ _ _ _ _ _ _ /\\ _ |- _ =>\n                  destruct H\n  end.\n\nLtac step_destruct :=\n  match goal with H: step _ _ _ _ _ _ _ _ |- _ =>\n                  dep_destruct H; clear H\n  end.\n\n\nParameter A B C : Type.\nParameter P : A -> B -> C -> Prop.\nParameter Q : Prop.\n\n(* This will try to match an hypothesis named h with 'exists u: T, P' \n   and return the name of 'u' *)\nLtac extract_name h :=\n  match goal with\n    | [h : ?A |- _ ] => \n      match A with\n        | @ex ?T ?P => match P with\n                          | fun u => _ => u\n                   end\n   end\nend.\n\n(* 'smart' destruct using the name we just computed *)\nLtac one_destruct h :=\n   let a := extract_name h in\n   destruct h as [a h].\n\nGoal (exists (a:A) (b:B) (c:C), P a b c) -> Q.\n  intros H.\n  one_destruct H. one_destruct H. one_destruct H.\nrepeat (one_destruct H).\nAbort.\n(* the goal is now\n1 subgoals\na : A\nb : B\nc : C\nH : P a b c\n______________________________________(1/1)\nQ\n*)\n\n\nLtac ih_dep_destruct :=\n  match goal with\n    | [ IHp1 : forall (p2t:protoType) (p2: protoExp p2t),\n         Dual _ _ -> exists _ _ _ _ _ _ _ _, _,\n          H : protoType,\n          H2 : message ?t0 -> (protoExp _),\n          H3 : message ?t0\n        |- _\n        ] => dep_destruct (IHp1 H (H2 H3))\n  end.\n\nHint Constructors multi.\nHint Resolve updateBoth.\n\nTheorem normalization {p1t p2t :protoType} :\n    forall (p1:protoExp p1t) (p2:protoExp p2t),\n      (Dual p1 p2) ->\n    exists p3t p4t (p3:protoExp p3t) (p4:protoExp p4t) st st' st2 st2',\n      (multi st _ _ _ p1 p2 p3 st') /\\ (multi st2 _ _ _ p2 p1 p4 st2')\n      /\\ normal_form p3 p4.\nProof.\n  intros.\n  generalize dependent p2. generalize dependent p2t.\n  induction p1; destruct p2;\n  try (intros H; inversion H; subst).\n  ih_dep_destruct. assumption.\n\n\n  Ltac ih_destruct :=\n  match goal with\n    | [ H: exists _, _\n        |- _\n        ] => destruct H\n  end.\n\n  repeat ih_destruct.\n\n  Ltac multi_destruct :=\n  match goal with\n    | [ H: multi _ _ _ _ _ _ _ _  /\\ _\n        |- _\n        ] => destruct H\n  end.\n  repeat multi_destruct.\n  \n  eexists. eexists. eexists. eexists.\n  eexists. eexists. eexists. eexists.\n  split. eapply multi_step. constructor. constructor. eassumption.\n  split. apply multi_step with (y:=(p m)) (y2:=p1) (st':=(updateState m x6)) (st2:=x4) (st2':=x4). constructor. constructor. apply updateBoth. eassumption. assumption.\n\n  intros. inversion H0; subst.\n\n  Ltac ih_dep_destruct' :=\n  match goal with\n    | [ IHp1 : forall m (p2t:protoType) (p2: protoExp p2t),\n         Dual _ _ -> exists _ _ _ _ _ _ _ _, _,\n          H : protoType,\n          H2 : (protoExp _),\n          H3: message _\n        |- _\n        ] => dep_destruct (IHp1 H3 H H2)\n                end.\n  ih_dep_destruct'. assumption.\n\n  repeat ih_destruct.\n  repeat multi_destruct.\n\n\n  eexists. eexists. eexists. eexists.\n  eexists. eexists. eexists. eexists.\n  \n  split. apply multi_step with (y:=(p m)) (y2:=p2) (st':=(updateState m x4)) (st2:=x4) (st2':=x4). constructor. constructor. apply updateBoth. eassumption.\n  split. apply multi_step with (y:=(p2)) (y2:=(p m)) (st':=x6) (st2:=x4) (st2':=(updateState m x4)). constructor. constructor. eassumption. assumption.\n\n  intros. inversion H0.\n  intros. inversion H0.\n  intros. inversion H0.\n  intros. inversion H0.\n\nAbort.\n\n(*\n\n  eapply multi_step; constructor. eassumption.\n  \n  apply multi_step with (y:=p2) (st':=(updateState m x6)) (st2:=x4) (st2':=x4).\n  apply multi_step with (y:=p2) (y2:=(p m)) (st':=x4) (st2:=x6) (st2':=(updateState m x6)).\n\n\n  eapply multi_step. constructor. constructor. eassumption.\n  split. apply multi_step with (y:=(p m)) (st':=(updateState m x6)) (st2:=x4) (st2':=x4). constructor. constructor. apply updateBoth. eassumption. assumption.\n\n  \n\n  \n  constructor.\n  split. constructor\n  constructor\n  exists x2. exists x3.\n  exists x4. exists x5. exists x6. exists (updateState m x7).\n\n  \n  try (ih_dep_destruct; inversion H; assumption).\n  dep_destruct (IHp1 p'0 (p m)).\n               inversion H. assumption.\n\n\n\n\n  dep_destruct \n           (p3t p4t : protoType) (p3 : protoExp p3t) \n         (p4 : protoExp p4t) (st st' st2 st2' : State),\n           (multie st p1) p2 p3 st' /\\\n           (multie st2 p2) p1 p4 st2' /\\ normal_form p3 p4\n\n  \n  destruct H0. destruct H0. destruct H0. destruct H0. destruct H0. destruct H0. destruct H0. destruct H0. destruct H4. eexists. eexists. exists x2. exists x3.\n  exists x4. exists x5. exists x6. exists (updateState m x7).\n\n  split. apply multi_step with (y:=p1) (y2:=(p m)) (st':=x4) (st2:=x6) (st2':=(updateState m x6)). constructor. constructor. assumption.\n  split. apply multi_step with (y:=(p m)) (y2:=p1) (st':=(updateState m x6)) (st2:=x4) (st2':=x4). constructor. constructor.\n  apply updateBoth. assumption. assumption.\n\n  intros. inversion H0. subst.\n  dep_destruct (H m _ p2).\n  inversion H0. assumption.\n  destruct H0.  destruct H1. destruct H1. destruct H1. destruct H1. destruct H1. destruct H1. destruct H1. destruct H1. destruct H4.\n\n  eexists. eexists. exists x2. exists x3. exists x4. exists (updateState m x5). exists x6. exists x7.\n\n  split. apply multi_step with (y:=(p m)) (y2:=p2) (st':=(updateState m x4)) (st2:=x6) (st2':=x6). constructor. constructor.\n  apply updateBoth. assumption.\n  split. apply multi_step with (y:=p2) (y2:=(p m)) (st':=x6) (st2:=x4) (st2':=(updateState m x4)). constructor. constructor. assumption. assumption.\n  intros. inversion H0.\n  intros. inversion H0.\n  intros. inversion H0.\n  intros. inversion H0.\n\n  destruct b. dep_destruct (IHp1_1 r0 p2_1). assumption. destruct x. assumption. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H4.\n\n    destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H6.\n\n  eexists. eexists. eexists. eexists.\n\n  exists x11. exists x12. exists x13. exists x14.\n  split. apply multi_step with (y:=p1_1) (y2:=p2_1) (st':=x11) (st2:=x13) (st2':=x13). constructor. constructor. apply H3.\n  split. apply multi_step with (y:=p2_1) (y2:=p1_1) (st':=x13) (st2:=x11) (st2':=x11). constructor. constructor. apply H6. assumption.\n\n  dep_destruct (IHp1_2 s0 p2_2). assumption. destruct x. assumption.\n  destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H4.\n\n  destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H6.\n\n  eexists. eexists. eexists. eexists.\n\n  exists x11. exists x12. exists x13. exists x14.\n  split. apply multi_step with (y:=p1_2) (y2:=p2_2) (st':=x11) (st2:=x13) (st2':=x13). constructor. constructor. apply H3.\n  split. apply multi_step with (y:=p2_2) (y2:=p1_2) (st':=x13) (st2:=x11) (st2':=x11). constructor. constructor. apply H6. assumption.\n\n  destruct b. dep_destruct (IHp1_1 r0 p2_1). assumption. destruct x. assumption. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H4.\n\n    destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H6.\n\n  eexists. eexists. eexists. eexists.\n\n  exists x11. exists x12. exists x13. exists x14.\n  split. apply multi_step with (y:=p1_1) (y2:=p2_1) (st':=x11) (st2:=x13) (st2':=x13). constructor. constructor. apply H3.\n  split. apply multi_step with (y:=p2_1) (y2:=p1_1) (st':=x13) (st2:=x11) (st2':=x11). constructor. constructor. apply H6. assumption.\n\n  dep_destruct (IHp1_2 s0 p2_2). assumption. destruct x. assumption.\n  destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H2. destruct H4.\n\n  destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H3. destruct H6.\n\n  eexists. eexists. eexists. eexists.\n\n  exists x11. exists x12. exists x13. exists x14.\n  split. apply multi_step with (y:=p1_2) (y2:=p2_2) (st':=x11) (st2:=x13) (st2':=x13). constructor. constructor. apply H3.\n  split. apply multi_step with (y:=p2_2) (y2:=p1_2) (st':=x13) (st2:=x11) (st2':=x11). constructor. constructor. apply H6. assumption.\n\n  eexists. eexists. eexists. eexists. exists emptyState. exists emptyState. exists emptyState. exists emptyState.\n  split. constructor. split. constructor.\n  unfold normal_form. intros. unfold not. intros. destruct H0. destruct H0. inversion H0.\nQed.\n\n*)\n\nDefinition isValue {t:protoType} (p:protoExp t) : Prop :=\n  match p with\n  | ReturnC _ => True\n  | _ => False\n  end.\n\nTheorem ex_isValue : isValue (ReturnC (basic 1)).\nProof.\n  simpl. trivial.\nQed.\n\nTheorem progress {t t':protoType} :\n    forall (p1:protoExp t) (p2:protoExp t') st, \n    (Dual p1 p2) ->\n    isValue p1 \\/ (exists t''(p3:protoExp t'') st', step st _ _ _ p1 p2 p3 st').\nProof.\n  intros p1 p2 st dualProof. destruct p1; destruct p2; inversion dualProof;\n  (* Case:  p1 = SendC, p2 = ReceiveC *)\n  (* Case:  p1 = ReceiveC, p2 = SendC *)\n  (* Case:  p1 = ChoiceC, p2 = OfferC *)\n  (* Case:  p1 = OfferC, p2 = ChoiceC *)                             \n  try (right; \n       try (bool_destruct);\n       subst; repeat (eexists); constructor).\n  (* Case:  p1 = ReturnC, p2 = ReturnC *)\n  left. simpl. trivial.\nQed.\n\nTheorem preservation {t t' p3t p4t : protoType} :\n    forall (p1:protoExp t) (p2:protoExp t'), \n    (Dual p1 p2) -> \n    forall (p3:protoExp p3t) (p4:protoExp p4t) st st' st2 st2',\n      step st _ _ _ p1 p2 p3 st' /\\\n      step st _ _ _ p1 p2 p3 st' /\\\n       step st2 _ _ _ p2 p1 p4 st2'\n      -> (Dual p3 p4).\nProof.\n  intros p1 p2 dualProof. destruct p1; destruct p2; inversion dualProof;\n  intros; try (repeat steps_destruct); (repeat step_destruct); assumption.\nQed.\n\nLemma value_is_nf {t t':protoType} (p1:protoExp t) (p2:protoExp t') :\n  (isValue p1) /\\ (isValue p2) -> normal_form p1 p2.\nProof.\n  intros.\n  destruct p1; destruct p2;\n  (cbv; intros; solve by inversion 3).\nQed.\n\nLemma nf_is_value {t t':protoType} (p1:protoExp t) (p2:protoExp t') : (Dual p1 p2) -> \n  normal_form p1 p2 -> (isValue p1) /\\ (isValue p2).\nProof.\n  unfold normal_form.\n  intros D H.\n  destruct p1; destruct p2; try (inversion D);\n  try (try bool_destruct; destruct H with (st:=emptyState) (st':=emptyState);\n       repeat eexists; subst; constructor).\n\n  destruct H with (st:=emptyState) (st':=updateState m emptyState);\n    eexists; subst; eexists; constructor.\n  jauto.\nQed.\n\nCorollary nf_same_as_value {t t':protoType} (p1:protoExp t) (p2:protoExp t')\n  : (Dual p1 p2) -> normal_form p1 p2 <-> (isValue p1) /\\ (isValue p2).\nProof. \n  intros. split.\n  intros. apply nf_is_value in H0. assumption. assumption.\n  intros. apply value_is_nf in H0. assumption.\nQed.", "meta": {"author": "armoredsoftware", "repo": "session", "sha": "ca06d4263c20e0d4a3ef36b70d9eccd0e7cf9173", "save_path": "github-repos/coq/armoredsoftware-session", "path": "github-repos/coq/armoredsoftware-session/session-ca06d4263c20e0d4a3ef36b70d9eccd0e7cf9173/ProtoStateSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.22308822363475897}}
{"text": "Require Import Arith.\nRequire Import Bool.\nRequire Import List.\nRequire Import FMapInterface.\nRequire Import FMapFacts.\nRequire Import Structures.OrderedType.\nRequire Import Structures.OrderedTypeEx.\nRequire Import Log.\nRequire Import Pred.\nRequire Import Prog.\nRequire Import Hoare.\nRequire Import SepAuto.\nRequire Import FunctionalExtensionality.\nRequire Import Omega.\nRequire Import Word.\nRequire Import WordAuto.\nRequire Import Rec.\nRequire Import Array.\nRequire Import Eqdep_dec.\nRequire Import GenSep.\n\nSet Implicit Arguments.\nImport List.ListNotations.\n\n(* XXX parameterize by length and stick in Word.v *)\nModule addr_as_OT <: UsualOrderedType.\n  Definition WIDTH:=addrlen.\n  Definition t := word WIDTH.\n  Definition eq := @eq t.\n  Definition eq_refl := @eq_refl t.\n  Definition eq_sym := @eq_sym t.\n  Definition eq_trans := @eq_trans t.\n  Definition lt := @wlt WIDTH.\n\n  Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.\n  Proof.\n    unfold lt; intros.\n    apply wlt_lt in H; apply wlt_lt in H0.\n    apply lt_wlt.\n    omega.\n  Qed.\n\n  Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y.\n  Proof.\n    unfold lt, eq; intros.\n    apply wlt_lt in H.\n    intro He; subst; omega.\n  Qed.\n\n  Definition compare x y : Compare lt eq x y.\n  Proof.\n    unfold lt, eq.\n    destruct (wlt_dec x y); [ apply LT; auto | ].\n    destruct (weq x y); [ apply EQ; auto | ].\n    apply GT. apply le_neq_lt; auto.\n  Defined.\n\n  Definition eq_dec := @weq WIDTH.\nEnd addr_as_OT.\n\nModule LOG (Map:FMapInterface.WSfun addr_as_OT).\n  Definition memstate := Map.t valu.\n  Definition ms_empty := Map.empty valu : memstate.\n  Definition diskstate := list valu.\n  Module MapFacts := WFacts_fun addr_as_OT Map.\n  Module MapProperties := WProperties_fun addr_as_OT Map.\n\n  Inductive logstate :=\n  | NoTransaction (cur : diskstate)\n  (* Don't touch the disk directly in this state. *)\n  | ActiveTxn (old : diskstate) (cur : diskstate)\n  (* A transaction is in progress.\n   * It started from the first memory and has evolved into the second.\n   * It has not committed yet. *)\n  | FlushedTxn (old : diskstate) (cur : diskstate)\n  (* A transaction has been flushed to the log, but not committed yet. *)\n  | CommittedTxn (cur : diskstate)\n  (* A transaction has committed but the log has not been applied yet. *).\n\n  Record xparams := {\n    (* The actual data region is everything that's not described here *)\n    LogHeader : word addrlen; (* Store the header here *)\n    LogCommit : word addrlen; (* Store true to apply after crash. *)\n\n    LogStart : word addrlen; (* Start of log region on disk *)\n    LogLen : word addrlen  (* Maximum number of entries in log; length but still use addr type *)\n  }.\n\n  Definition header_type := Rec.RecF ([(\"length\", Rec.WordF addrlen)]).\n  Definition header := Rec.data header_type.\n  Definition mk_header (len : nat) : header := ($ len, tt).\n\n(*\n  Theorem header_sz_ok : Rec.len header_type <= valulen.\n  Proof.\n    rewrite valulen_is. simpl. firstorder. (* this could be much faster, say with reflection *)\n  Qed.\n\n  Theorem plus_minus_header : Rec.len header_type + (valulen - Rec.len header_type) = valulen.\n  Proof.\n    apply le_plus_minus_r; apply header_sz_ok.\n  Qed.\n\n  Definition header_to_valu (h : header) : valu.\n    set (zext (Rec.to_word h) (valulen - Rec.len header_type)) as r.\n    rewrite plus_minus_header in r.\n    refine r.\n  Defined.\n  Arguments header_to_valu : simpl never.\n\n  Definition valu_to_header (v : valu) : header.\n    apply Rec.of_word.\n    rewrite <- plus_minus_header in v.\n    refine (split1 _ _ v).\n  Defined.\n\n  Definition header_valu_id : forall h,\n    valu_to_header (header_to_valu h) = h.\n  Proof.\n    unfold valu_to_header, header_to_valu.\n    unfold eq_rec_r, eq_rec.\n    intros.\n    rewrite <- plus_minus_header.\n    do 2 rewrite <- eq_rect_eq_dec by (apply eq_nat_dec).\n    unfold zext.\n    rewrite split1_combine.\n    apply Rec.of_to_id.\n    simpl; destruct h; tauto.\n  Qed.\n\n  Definition addr_per_block := valulen / addrlen.\n  Definition descriptor_type := Rec.ArrayF (Rec.WordF addrlen) addr_per_block.\n  Definition descriptor := Rec.data descriptor_type.\n  Theorem descriptor_sz_ok : valulen = Rec.len descriptor_type.\n    simpl. unfold addr_per_block. rewrite valulen_is. reflexivity.\n  Qed.\n\n  Definition descriptor_to_valu (d : descriptor) : valu.\n    rewrite descriptor_sz_ok.\n    apply Rec.to_word; auto.\n  Defined.\n  Arguments descriptor_to_valu : simpl never.\n\n  Definition valu_to_descriptor (v : valu) : descriptor.\n    rewrite descriptor_sz_ok in v.\n    apply Rec.of_word; auto.\n  Defined.\n\n  Theorem valu_descriptor_id : forall v,\n    descriptor_to_valu (valu_to_descriptor v) = v.\n  Proof.\n    unfold descriptor_to_valu, valu_to_descriptor.\n    unfold eq_rec_r, eq_rec.\n    intros.\n    rewrite Rec.to_of_id.\n    rewrite <- descriptor_sz_ok.\n    do 2 rewrite <- eq_rect_eq_dec by (apply eq_nat_dec).\n    trivial.\n  Defined.\n*)\n\n  Definition indomain' (a : addr) (m : diskstate) := wordToNat a < length m.\n\n  (* Check that the state is well-formed *)\n  Definition valid_entries m (ms : memstate) :=\n    forall a v, Map.MapsTo a v ms -> indomain' a m.\n\n  Definition valid_size xp (ms : memstate) :=\n    Map.cardinal ms <= wordToNat (LogLen xp).\n\n  (* Replay the state in memory *)\n  Definition replay' V (l : list (addr * V)) (m : list V) : list V :=\n    fold_right (fun p m' => upd m' (fst p) (snd p)) m l.\n\n  Definition replay (ms : memstate) (m : diskstate) : diskstate :=\n    replay' (Map.elements ms) m.\n\n  Definition data_rep (old : diskstate) : pred :=\n    diskIs (list2mem old).\n\n  Definition cur_rep (old : diskstate) (ms : memstate) (cur : diskstate) : @pred valu :=\n    [[ cur = replay ms old ]]%pred.\n\n  Theorem firstn_map : forall A B n l (f: A -> B),\n    firstn n (map f l) = map f (firstn n l).\n  Proof.\n    induction n; intros; simpl; auto.\n    destruct l.\n    reflexivity.\n    simpl. rewrite IHn. reflexivity.\n  Qed.\n\n  Definition KIn V := InA (@Map.eq_key V).\n  Definition KNoDup V := NoDupA (@Map.eq_key V).\n\n  Lemma replay_sel_other : forall a ms m def,\n    ~ Map.In a ms -> selN (replay ms m) (wordToNat a) def = selN m (wordToNat a) def.\n  Proof.\n    (* intros; rename a into a'; remember (wordToNat a') as a. *)\n    intros a ms m def HnotIn.\n    destruct (MapFacts.elements_in_iff ms a) as [_ Hr].\n    assert (not (exists e : valu, InA (Map.eq_key_elt (elt:=valu))\n      (a, e) (Map.elements ms))) as HnotElem by auto; clear Hr HnotIn.\n    remember (Map.eq_key_elt (elt:=valu)) as eq in *.\n    unfold replay, replay'.\n    remember (Map.elements ms) as elems in *.\n    assert (forall x y, InA eq (x,y) elems -> x <> a) as Hneq. {\n      intros x y Hin.\n      destruct (addr_as_OT.eq_dec a x); [|intuition].\n      destruct HnotElem; exists y; subst; auto.\n    }\n    clear Heqelems HnotElem.\n    induction elems as [|p]; [reflexivity|].\n    rewrite <- IHelems; clear IHelems; [|intros; eapply Hneq; right; eauto].\n    destruct p as [x y]; simpl.\n    assert (x <> a) as Hsep. {\n      apply (Hneq x y); left; subst eq. \n      apply Equivalence.equiv_reflexive_obligation_1.\n      apply MapProperties.eqke_equiv.\n    }\n    eapply (selN_updN_ne _ y);\n      unfold not; intros; destruct Hsep; apply wordToNat_inj; trivial.\n  Qed.\n\n  Lemma replay'_length : forall V (l:list (addr * V)) (m:list V),\n      length m = length (replay' l m).\n    induction l; [trivial|]; intro.\n    unfold replay'; simpl.\n    rewrite length_upd.\n    eapply IHl.\n  Qed.\n\n  Lemma InA_NotInA_neq : forall T eq, Equivalence eq -> forall l (x y:T),\n      InA eq x l -> ~ (InA eq y l) -> ~ eq x y.\n    intros until 0; intros Eqeq; intros until 0; intros HIn HnotIn.\n    rewrite InA_altdef, Exists_exists in *.\n    intro Hcontra; apply HnotIn; clear HnotIn.\n    elim HIn; clear HIn; intros until 0; intros HIn.\n    destruct HIn as [HIn Heq_x_x0].\n    exists x0. split; [apply HIn|].\n    etransitivity; eauto; symmetry; auto.\n  Qed.\n\n  Lemma replay'_sel : forall V a (v: V) l m def,\n    KNoDup l -> In (a, v) l -> wordToNat a < length m -> sel (replay' l m) a def = v.\n  Proof.\n    intros until 0; intros HNoDup HIn Hbounds.\n\n    induction l as [|p]; [inversion HIn|]; destruct p as [x y]; simpl.\n    destruct HIn. {\n      clear IHl.\n      injection H; clear H;\n        intro H; rewrite H in *; clear H;\n        intro H; rewrite H in *; clear H.\n      apply selN_updN_eq. rewrite <- replay'_length; assumption.\n    } {\n      assert (x <> a) as Hneq. {\n        inversion HNoDup. \n        assert (InA eq (a,v) l). {\n          apply In_InA; subst; eauto using MapProperties.eqk_equiv.\n        }\n      remember (Map.eq_key (elt:=V)) as eq_key in *.\n      assert (forall a b, eq a b -> eq_key a b) as Heq_eqk by (\n        intros; subst; apply MapProperties.eqk_equiv).\n      assert (forall a l, InA eq a l -> InA eq_key a l) as HIn_eq_eqk by (\n        intros until 0; intro HInAeq; induction HInAeq; [subst|right]; auto).\n      assert (@Equivalence (Map.key*V) eq_key) as Eqeq by (\n        subst eq_key; apply MapProperties.eqk_equiv).\n      intro Hcontra; destruct\n        (@InA_NotInA_neq (Map.key*V) eq_key Eqeq l (a,v) (x,y) (HIn_eq_eqk _ _ H4) H2).\n      subst; unfold Map.eq_key; reflexivity.\n      }\n      unfold sel, upd in *.\n      rewrite selN_updN_ne, IHl;\n        try trivial;\n        match goal with\n          | [ H: KNoDup (?a::?l) |- KNoDup ?l ] => inversion H; assumption\n          | [ Hneq: ?a<>?b |- wordToNat ?a <> wordToNat ?b] =>\n            unfold not; intro Hcontra; destruct (Hneq (wordToNat_inj _  _ Hcontra))\n        end.\n    }\n  Qed.\n\n  Lemma InA_eqke_In : forall V a v l,\n    InA (Map.eq_key_elt (elt:=V)) (a, v) l -> In (a, v) l.\n  Proof.\n    intros.\n    induction l.\n    inversion H.\n    inversion H.\n    inversion H1.\n    destruct a0; simpl in *; subst.\n    left; trivial.\n    simpl.\n    right.\n    apply IHl; auto.\n  Qed.\n\n  Lemma mapsto_In : forall V a (v: V) ms,\n    Map.MapsTo a v ms -> In (a, v) (Map.elements ms).\n  Proof.\n    intros.\n    apply Map.elements_1 in H.\n    apply InA_eqke_In; auto.\n  Qed.\n\n  Lemma replay_sel_in : forall a v ms m def,\n    Map.MapsTo a v ms -> selN (replay ms m) (wordToNat a) def = v.\n  Proof.\n    intros.\n    apply mapsto_In in H.\n    unfold replay.\n    apply replay'_sel.\n    apply Map.elements_3w.\n    auto.\n  Qed.\n\n  Lemma replay_sel_invalid : forall a ms m def,\n    ~ goodSize addrlen a -> selN (replay ms m) a def = selN m a def.\n  Proof.\n    intros; unfold goodSize in *.\n    destruct (lt_dec a (length m)); [|\n      repeat (rewrite selN_oob); unfold replay;\n        try match goal with [H: _ |- length (replay' _ _) <= a]\n            => rewrite <- replay'_length end;\n        auto; omega].\n    unfold replay, replay'.\n    induction (Map.elements ms); [reflexivity|].\n    rewrite <- IHl0; clear IHl0; simpl.\n    unfold upd.\n    rewrite selN_updN_ne.\n  Qed.\n\n  Lemma replay'_len : forall V l m,\n    length (@replay' V l m) = length m.\n  Proof.\n    induction l.\n    auto.\n    intros.\n    simpl.\n    rewrite length_upd, IHl.\n  Qed.\n\n  Lemma replay_len : forall ms m,\n    length (replay ms m) = length m.\n  Proof.\n    intros.\n    unfold replay.\n    apply replay'_len.\n  Qed.\n  \n  Lemma replay_add : forall a v ms m,\n    replay (Map.add a v ms) m = upd (replay ms m) a v.\n  Proof.\n    intros.\n    (* Let's show that the lists are equal because [sel] at any index [pos] gives the same valu *)\n    eapply list_selN_ext.\n    rewrite length_upd.\n    repeat rewrite replay_len.\n    trivial.\n    \n    intros.\n    destruct (lt_dec pos (pow2 addrlen)).\n    - (* [pos] is a valid address *)\n      replace pos with (wordToNat (natToWord addrlen (pos))) by word2nat_auto.\n      destruct (weq ($ pos) a).\n      + (* [pos] is [a], the address we're updating *)\n        erewrite replay_sel_in.\n        reflexivity.\n        instantiate (default := $0).\n        subst.\n        unfold upd.\n        rewrite selN_updN_eq.\n        apply Map.add_1.\n        trivial.\n        rewrite replay_len in *.\n        word2nat_auto.\n    \n      + (* [pos] is another address *)\n        unfold upd.\n        rewrite selN_updN_ne by word2nat_auto.\n\n        case_eq (Map.find $ pos ms).\n\n        (* [pos] is in the transaction *)\n        intros w Hf.\n        erewrite replay_sel_in.\n        reflexivity.\n        apply Map.find_2 in Hf.\n\n        erewrite replay_sel_in.\n        apply Map.add_2.\n        unfold not in *; intros; solve [auto].\n        eauto.\n        eauto.\n        \n        (* [pos] is not in the transaction *)\n        Ltac wneq H := intro HeqContra; symmetry in HeqContra; apply H; auto.\n        intro Hf; \n          repeat (erewrite replay_sel_other);\n          try trivial;\n          intro HIn; destruct HIn as [x HIn];\n          try apply Map.add_3 in HIn;\n          try apply Map.find_1 in HIn;\n          try wneq n;\n          replace (Map.find $ (pos) ms) with (Some x) in Hf; inversion Hf.\n    - (* [pos] is an invalid address *)\n      rewrite replay_sel_invalid by auto.\n      unfold upd.\n      rewrite selN_updN_ne by (\n        generalize (wordToNat_bound a); intro Hb;\n        unfold addr_as_OT.WIDTH in *; omega).\n      rewrite replay_sel_invalid by auto; trivial.\n  Qed.\n\n\n  Lemma valid_entries_add : forall a v ms m,\n    valid_entries m ms -> indomain' a m -> valid_entries m (Map.add a v ms).\n  Proof.\n    unfold valid_entries in *.\n    intros.\n    destruct (weq a a0).\n    subst; auto.\n    eapply H.\n    eapply Map.add_3; eauto.\n  Qed.\n\n\n(* Testing.. *)\n\nDefinition do_two_writes a1 a2 v1 v2 rx :=\n  Write a1 v1 ;; Write a2 v2 ;; rx tt.\n\nExample two_writes: forall a1 a2 v1 v2 rx rec,\n  {{ exists v1' v2' F,\n     a1 |-> v1' * a2 |-> v2' * F\n   * [[{{ a1 |-> v1 * a2 |-> v2 * F }} rx tt >> rec]]\n   * [[{{ (a1 |-> v1' * a2 |-> v2' * F) \\/\n          (a1 |-> v1 * a2 |-> v2' * F) \\/\n          (a1 |-> v1 * a2 |-> v2 * F) }} rec >> rec]]\n  }} do_two_writes a1 a2 v1 v2 rx >> rec.\nProof.\n  unfold do_two_writes.\n  hoare.\nQed.\n\nHint Extern 1 ({{_}} progseq (do_two_writes _ _ _ _) _ >> _) => apply two_writes : prog.\n\nExample read_write: forall a v rx rec,\n  {{ exists v' F,\n     a |-> v' * F\n   * [[{{ a |-> v * F }} (rx v) >> rec]]\n   * [[{{ (a |-> v' * F)\n       \\/ (a |-> v * F) }} rec >> rec]]\n  }} Write a v ;; x <- Read a ; rx x >> rec.\nProof.\n  hoare.\nQed.\n\nExample four_writes: forall a1 a2 v1 v2 rx rec,\n  {{ exists v1' v2' F,\n     a1 |-> v1' * a2 |-> v2' * F\n   * [[{{ a1 |-> v1 * a2 |-> v2 * F }} rx >> rec]]\n   * [[{{ (a1 |-> v1' * a2 |-> v2' * F)\n       \\/ (a1 |-> v1 * a2 |-> v2' * F)\n       \\/ (a1 |-> v1 * a2 |-> v2 * F) }} rec >> rec]]\n  }} do_two_writes a1 a2 v1 v2 ;; do_two_writes a1 a2 v1 v2 ;; rx >> rec.\nProof.\n  hoare.\nQed.\n\nExample inc_up_to_5: forall a rx rec,\n  {{ exists v F,\n     a |-> v * F\n   * [[{{ [[v < 5]] * a |-> (S v) * F\n       \\/ [[v >= 5]] * a |-> v * F }} rx >> rec]]\n   * [[{{ a |-> v * F\n       \\/ a |-> S v * F }} rec >> rec]]\n  }} x <- !a;\n  If (lt_dec x 5) {\n    a <-- (S x) ;; rx\n  } else {\n    rx\n  } >> rec.\nProof.\n  hoare.\nQed.\n\nExample count_up: forall (n:nat) rx rec F,\n  {{ F\n   * [[ {{ F }} (rx n) >> rec ]]\n   * [[ {{ F }} rec >> rec ]]\n  }} r <- For i < n\n     Loopvar l <- 0\n     Continuation lrx\n     Invariant\n       F * [[ l=i ]]\n         * [[ {{ F }} rx n >> rec ]]\n         * [[ {{ F }} rec >> rec ]]\n     OnCrash\n       any\n     Begin\n       lrx (S l)\n     Rof; rx r\n  >> rec.\nProof.\n  hoare.\nQed.\n\n\nRequire Import Log.\n\nInductive onestate :=\n| One (a: nat).\n\nModule Type ONEINT.\n  (* Methods *)\n  Parameter read : xparams -> prog nat.\n  Parameter write : xparams -> nat -> prog unit.\n\n  Parameter rep : xparams -> onestate -> pred.\n\n  Axiom read_ok : forall xp v,\n    {{rep xp (One v) /\\\n      [DataStart xp <= 3 < DataStart xp + DataLen xp]}}\n    (read xp)\n    {{r, rep xp (One v)\n      /\\ [r = Crashed \\/ r = Halted v]}}.\n\n  Axiom write_ok : forall xp v0 v,\n    {{rep xp (One v0) /\\\n      [DataStart xp <= 3 < DataStart xp + DataLen xp]}}\n    (write xp v)\n    {{r, rep xp (One v)\n      \\/ ([r = Crashed] /\\ rep xp (One v0))}}.\nEnd ONEINT.\n\nModule Oneint : ONEINT.\n  Definition read xp := $(mem:\n    (Call (fun m : mem => Log.begin_ok xp m));;\n    x <- (Call (fun m : mem => Log.read_ok xp 3 (m, m)));\n    (Call (fun m : mem => Log.commit_ok xp m m));;\n    (Halt x)\n  ).\n\n  Definition write xp v := $(mem:\n    (Call (fun m : mem => Log.begin_ok xp m));;\n    (Call (fun m : mem => Log.write_ok xp 3 v (m, upd m 3 v)));;\n    (Call (fun m : mem => Log.commit_ok xp m (upd m 3 v)))\n  ).\n\n  Definition rep xp (os: onestate) :=\n    match os with\n    | One a => exists lm,\n      Log.rep xp (NoTransaction lm) /\\\n      [lm (DataStart xp + 3) = a]\n    end%pred.\n\n  Theorem read_ok : forall xp a (m:mem),\n    {{rep xp (One a) /\\\n      [DataStart xp <= 3 < DataStart xp + DataLen xp]}}\n    (read xp)\n    {{r, rep xp (One a)\n      /\\ [r = Crashed \\/ r = Halted a]}}.\n  Proof.\n    hoare.\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/Scratch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.22305200822132845}}
{"text": "Require Import Bool.\nRequire Import List.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import Simulation.\n\nSet Implicit Arguments.\n\nSection Compose.\n  Variable (ths1 ths2:Threads.t).\n  Hypothesis (DISJOINT: Threads.disjoint ths1 ths2).\n\n  Lemma compose_comm:\n    Threads.compose ths1 ths2 = Threads.compose ths2 ths1.\n  Proof.\n    apply IdentMap.eq_leibniz. ii.\n    rewrite ? Threads.compose_spec.\n    unfold Threads.compose_option.\n    destruct (IdentMap.find y ths1) eqn:SRC,\n             (IdentMap.find y ths2) eqn:TGT; auto.\n    exfalso. inv DISJOINT. eapply THREAD; eauto.\n  Qed.\n\n  Lemma compose_forall P:\n    (forall tid lang st th (TH: IdentMap.find tid (Threads.compose ths1 ths2) = Some (existT _ lang st, th)),\n        (P tid lang st th):Prop) <->\n    (forall tid lang st th (TH: IdentMap.find tid ths1 = Some (existT _ lang st, th)),\n        (P tid lang st th):Prop) /\\\n    (forall tid lang st th (TH: IdentMap.find tid ths2 = Some (existT _ lang st, th)),\n        (P tid lang st th):Prop).\n  Proof.\n    econs; i.\n    - i. splits.\n      + i. eapply H; eauto.\n        rewrite Threads.compose_spec. rewrite TH. ss.\n      + i. eapply H; eauto.\n        rewrite compose_comm.\n        rewrite Threads.compose_spec. rewrite TH. ss.\n    - des.\n      rewrite Threads.compose_spec in TH.\n      unfold Threads.compose_option in TH.\n      destruct (IdentMap.find tid ths1) eqn:SRC; inv TH.\n      + eapply H; eauto.\n      + eapply H0; eauto.\n  Qed.\n\n  Lemma compose_forall_rev P:\n    (forall tid lang st th (TH: IdentMap.find tid ths1 = Some (existT _ lang st, th)),\n        (P tid lang st th):Prop) ->\n    (forall tid lang st th (TH: IdentMap.find tid ths2 = Some (existT _ lang st, th)),\n        (P tid lang st th):Prop) ->\n    (forall tid lang st th (TH: IdentMap.find tid (Threads.compose ths1 ths2) = Some (existT _ lang st, th)),\n        (P tid lang st th):Prop).\n  Proof.\n    i. apply compose_forall; auto.\n  Qed.\n\n  Lemma compose_is_terminal:\n    Threads.is_terminal (Threads.compose ths1 ths2) <->\n    Threads.is_terminal ths1 /\\ Threads.is_terminal ths2.\n  Proof.\n    apply compose_forall.\n  Qed.\n\n  Lemma compose_threads_wf mem:\n    Threads.wf (Threads.compose ths1 ths2) mem <->\n    <<CONSISTENT1: Threads.wf ths1 mem>> /\\\n    <<CONSISTENT2: Threads.wf ths2 mem>>.\n  Proof.\n    econs; intro X; des; splits; ii.\n    - econs; ss.\n      + i. eapply X; eauto.\n        * rewrite Threads.compose_spec.\n          unfold Threads.compose_option.\n          rewrite TH1. auto.\n        * rewrite Threads.compose_spec.\n          unfold Threads.compose_option.\n          rewrite TH2. auto.\n      + i. eapply X.\n        rewrite Threads.compose_spec.\n        unfold Threads.compose_option.\n        rewrite TH. auto.\n    - econs; ss.\n      + i. eapply X; eauto.\n        * rewrite compose_comm.\n          rewrite Threads.compose_spec.\n          unfold Threads.compose_option.\n          rewrite TH1. auto.\n        * rewrite compose_comm.\n          rewrite Threads.compose_spec.\n          unfold Threads.compose_option.\n          rewrite TH2. auto.\n      + i. eapply X.\n        rewrite compose_comm.\n        rewrite Threads.compose_spec.\n        unfold Threads.compose_option.\n        rewrite TH. auto.\n    - inv CONSISTENT1. inv CONSISTENT2. econs; ss.\n      + i. rewrite ? Threads.compose_spec in *.\n        destruct (IdentMap.find tid1 ths1) eqn:TH11,\n                 (IdentMap.find tid1 ths2) eqn:TH12,\n                 (IdentMap.find tid2 ths1) eqn:TH21,\n                 (IdentMap.find tid2 ths2) eqn:TH22;\n          Configuration.simplify;\n          try (by eapply DISJOINT; eauto);\n          try (by eapply DISJOINT0; eauto);\n          try (by eapply DISJOINT1; eauto).\n        * symmetry. eapply DISJOINT; eauto.\n        * symmetry. eapply DISJOINT; eauto.\n      + i. rewrite ? Threads.compose_spec in *.\n        unfold Threads.compose_option in *.\n        destruct (IdentMap.find tid ths1) eqn:TH1.\n        * inv TH. eapply THREADS. eauto.\n        * eapply THREADS0. eauto.\n  Qed.\n\n  Lemma compose_threads_consistent sc mem:\n    Threads.consistent (Threads.compose ths1 ths2) sc mem <->\n    <<CONSISTENT1: Threads.consistent ths1 sc mem>> /\\\n    <<CONSISTENT2: Threads.consistent ths2 sc mem>>.\n  Proof.\n    econs; intro X; des; splits; ii.\n    - eapply X; eauto.\n      rewrite Threads.compose_spec.\n      unfold Threads.compose_option.\n      rewrite TH. auto.\n    - eapply X; eauto.\n      rewrite compose_comm.\n      rewrite Threads.compose_spec.\n      unfold Threads.compose_option.\n      rewrite TH. auto.\n    - rewrite ? Threads.compose_spec in *.\n      destruct (IdentMap.find tid ths1) eqn:TH11,\n               (IdentMap.find tid ths2) eqn:TH12,\n               (IdentMap.find tid ths1) eqn:TH21,\n               (IdentMap.find tid ths2) eqn:TH22;\n        Configuration.simplify.\n      + exfalso. inv DISJOINT. eapply THREAD; eauto.\n      + eapply CONSISTENT1; eauto.\n      + eapply CONSISTENT2; eauto.\n  Qed.\n\n  Lemma compose_wf sc mem:\n    Configuration.wf (Configuration.mk (Threads.compose ths1 ths2) sc mem) <->\n    <<WF1: Configuration.wf (Configuration.mk ths1 sc mem)>> /\\\n    <<WF2: Configuration.wf (Configuration.mk ths2 sc mem)>>.\n  Proof.\n    econs; intro X.\n    - inv X. splits; econs; ss.\n      + apply compose_threads_wf; auto.\n      + apply compose_threads_wf; auto.\n    - des. inv WF1. inv WF2. econs; ss.\n      apply compose_threads_wf. auto.\n  Qed.\n\n  Lemma compose_consistent sc mem:\n    Configuration.consistent (Configuration.mk (Threads.compose ths1 ths2) sc mem) <->\n    <<CONSISTENT1: Configuration.consistent (Configuration.mk ths1 sc mem)>> /\\\n    <<CONSISTENT2: Configuration.consistent (Configuration.mk ths2 sc mem)>>.\n  Proof.\n    econs; intro X.\n    - splits; apply compose_threads_consistent; auto.\n    - apply compose_threads_consistent. auto.\n  Qed.\nEnd Compose.\n\nLemma compose_step\n      ths1 ths2\n      e tid sc mem ths' sc' mem'\n      (DISJOINT: Threads.disjoint ths1 ths2)\n      (STEP: Configuration.step\n               e tid\n               (Configuration.mk (Threads.compose ths1 ths2) sc mem)\n               (Configuration.mk ths' sc' mem')):\n  (exists ths1',\n      <<NEXT: ths' = Threads.compose ths1' ths2>> /\\\n      <<STEP: Configuration.step\n                e tid\n                (Configuration.mk ths1 sc mem)\n                (Configuration.mk ths1' sc' mem')>>) \\/\n  (exists ths2',\n      <<NEXT: ths' = Threads.compose ths1 ths2'>> /\\\n      <<STEP: Configuration.step\n                e tid\n                (Configuration.mk ths2 sc mem)\n                (Configuration.mk ths2' sc' mem')>>).\nProof.\n  inv STEP. ss.\n  rewrite Threads.compose_spec in TID.\n  unfold Threads.compose_option in TID.\n  destruct (IdentMap.find tid ths1) eqn:TH1,\n           (IdentMap.find tid ths2) eqn:TH2; inv TID.\n  - exfalso. inv DISJOINT. eapply THREAD; eauto.\n  - left. exists (IdentMap.add tid (existT _ lang st3, lc3) ths1). splits; [|econs; eauto].\n    apply IdentMap.eq_leibniz. ii.\n    rewrite ? IdentMap.Facts.add_o.\n    rewrite ? Threads.compose_spec.\n    rewrite ? IdentMap.Facts.add_o.\n    condtac; auto.\n  - right. exists (IdentMap.add tid (existT _ lang st3, lc3) ths2). splits; [|econs; eauto].\n    apply IdentMap.eq_leibniz. ii.\n    rewrite ? IdentMap.Facts.add_o.\n    rewrite ? Threads.compose_spec.\n    rewrite ? IdentMap.Facts.add_o.\n    condtac; auto.\n    subst. unfold Threads.compose_option. rewrite TH1. auto.\nQed.\n\nLemma compose_step1\n      ths1 ths2\n      e tid sc mem ths1' sc' mem'\n      (STEP: Configuration.step\n               e tid\n               (Configuration.mk ths1 sc mem)\n               (Configuration.mk ths1' sc' mem'))\n      (DISJOINT: Threads.disjoint ths1 ths2)\n      (WF1: Configuration.wf (Configuration.mk ths1 sc mem))\n      (WF2: Configuration.wf (Configuration.mk ths2 sc mem))\n      (CONSISTENT1: Configuration.consistent (Configuration.mk ths1 sc mem))\n      (CONSISTENT2: Configuration.consistent (Configuration.mk ths2 sc mem)):\n  <<STEP: Configuration.step\n            e tid\n            (Configuration.mk (Threads.compose ths1 ths2) sc mem)\n            (Configuration.mk (Threads.compose ths1' ths2) sc' mem')>> /\\\n  <<DISJOINT': Threads.disjoint ths1' ths2>> /\\\n  <<WF2': Configuration.wf (Configuration.mk ths2 sc' mem')>> /\\\n  <<CONSISTENT2': Configuration.consistent (Configuration.mk ths2 sc' mem')>>.\nProof.\n  exploit Configuration.step_disjoint; eauto. s. i. des.\n  splits; eauto. inv STEP. ss.\n  replace (Threads.compose (IdentMap.add tid (existT _ lang st3, lc3) ths1) ths2)\n  with (IdentMap.add tid (existT _ lang st3, lc3) (Threads.compose ths1 ths2)).\n  - econs; eauto.\n    s. rewrite Threads.compose_spec. unfold Threads.compose_option.\n    rewrite TID. auto.\n  - apply IdentMap.eq_leibniz. ii.\n    rewrite ? IdentMap.Facts.add_o.\n    rewrite ? Threads.compose_spec.\n    rewrite ? IdentMap.Facts.add_o.\n    condtac; auto.\nQed.\n\nLemma compose_step2\n      ths1 ths2\n      e tid sc mem ths2' sc' mem'\n      (STEP: Configuration.step\n               e tid\n               (Configuration.mk ths2 sc mem)\n               (Configuration.mk ths2' sc' mem'))\n      (DISJOINT: Threads.disjoint ths1 ths2)\n      (WF1: Configuration.wf (Configuration.mk ths1 sc mem))\n      (WF2: Configuration.wf (Configuration.mk ths2 sc mem))\n      (CONSISTENT1: Configuration.consistent (Configuration.mk ths1 sc mem))\n      (CONSISTENT2: Configuration.consistent (Configuration.mk ths2 sc mem)):\n  <<STEP: Configuration.step\n            e tid\n            (Configuration.mk (Threads.compose ths1 ths2) sc mem)\n            (Configuration.mk (Threads.compose ths1 ths2') sc' mem')>> /\\\n  <<DISJOINT': Threads.disjoint ths1 ths2'>> /\\\n  <<WF1': Configuration.wf (Configuration.mk ths1 sc' mem')>> /\\\n  <<CONSISTENT1': Configuration.consistent (Configuration.mk ths1 sc' mem')>>.\nProof.\n  exploit Configuration.step_disjoint; try symmetry; eauto. s. i. des.\n  exploit compose_step1; try apply STEP; try apply CONSISTENT1; eauto.\n  { symmetry. auto. }\n  i. des. splits; eauto.\n  - rewrite (@compose_comm ths1 ths2); auto.\n    rewrite (@compose_comm ths1 ths2'); auto.\n    symmetry. auto.\n  - symmetry. auto.\nQed.\n\nLemma compose_opt_step1\n      ths1 ths2\n      e tid sc mem ths1' sc' mem'\n      (STEP: Configuration.opt_step\n               e tid\n               (Configuration.mk ths1 sc mem)\n               (Configuration.mk ths1' sc' mem'))\n      (DISJOINT: Threads.disjoint ths1 ths2)\n      (WF1: Configuration.wf (Configuration.mk ths1 sc mem))\n      (WF2: Configuration.wf (Configuration.mk ths2 sc mem))\n      (CONSISTENT1: Configuration.consistent (Configuration.mk ths1 sc mem))\n      (CONSISTENT2: Configuration.consistent (Configuration.mk ths2 sc mem)):\n  <<STEP: Configuration.opt_step\n            e tid\n            (Configuration.mk (Threads.compose ths1 ths2) sc mem)\n            (Configuration.mk (Threads.compose ths1' ths2) sc' mem')>> /\\\n  <<DISJOINT': Threads.disjoint ths1' ths2>> /\\\n  <<WF2': Configuration.wf (Configuration.mk ths2 sc' mem')>> /\\\n  <<CONSISTENT2': Configuration.consistent (Configuration.mk ths2 sc' mem')>>.\nProof.\n  inv STEP.\n  - splits; eauto. econs 1.\n  - exploit compose_step1; eauto. i. des. splits; eauto. econs 2. auto.\nQed.\n\nLemma compose_opt_step2\n      ths1 ths2\n      e tid sc mem ths2' sc' mem'\n      (STEP: Configuration.opt_step\n               e tid\n               (Configuration.mk ths2 sc mem)\n               (Configuration.mk ths2' sc' mem'))\n      (DISJOINT: Threads.disjoint ths1 ths2)\n      (WF1: Configuration.wf (Configuration.mk ths1 sc mem))\n      (WF2: Configuration.wf (Configuration.mk ths2 sc mem))\n      (CONSISTENT1: Configuration.consistent (Configuration.mk ths1 sc mem))\n      (CONSISTENT2: Configuration.consistent (Configuration.mk ths2 sc mem)):\n  <<STEP: Configuration.opt_step\n            e tid\n            (Configuration.mk (Threads.compose ths1 ths2) sc mem)\n            (Configuration.mk (Threads.compose ths1 ths2') sc' mem')>> /\\\n  <<DISJOINT': Threads.disjoint ths1 ths2'>> /\\\n  <<WF1': Configuration.wf (Configuration.mk ths1 sc' mem')>> /\\\n  <<CONSISTENT1': Configuration.consistent (Configuration.mk ths1 sc' mem')>>.\nProof.\n  inv STEP.\n  - splits; eauto. econs 1.\n  - exploit compose_step2; eauto. i. des. splits; eauto. econs 2. auto.\nQed.\n\nLemma compose_rtc_step1\n      c1 c2 ths\n      (STEPS: rtc Configuration.tau_step c1 c2)\n      (DISJOINT: Threads.disjoint c1.(Configuration.threads) ths)\n      (WF1: Configuration.wf c1)\n      (WF: Configuration.wf (Configuration.mk ths c1.(Configuration.sc) c1.(Configuration.memory)))\n      (CONSISTENT1: Configuration.consistent c1)\n      (CONSISTENT: Configuration.consistent (Configuration.mk ths c1.(Configuration.sc) c1.(Configuration.memory))):\n  <<STEPS: rtc Configuration.tau_step\n               (Configuration.mk (Threads.compose c1.(Configuration.threads) ths) c1.(Configuration.sc) c1.(Configuration.memory))\n               (Configuration.mk (Threads.compose c2.(Configuration.threads) ths) c2.(Configuration.sc) c2.(Configuration.memory))>> /\\\n  <<DISJOINT': Threads.disjoint c2.(Configuration.threads) ths>> /\\\n  <<WF': Configuration.wf (Configuration.mk ths c2.(Configuration.sc) c2.(Configuration.memory))>> /\\\n  <<CONSISTENT': Configuration.consistent (Configuration.mk ths c2.(Configuration.sc) c2.(Configuration.memory))>>.\nProof.\n  revert CONSISTENT1 CONSISTENT. induction STEPS; auto. i. inv H.\n  exploit Configuration.step_future; eauto. i. des.\n  exploit Configuration.step_disjoint; eauto. i. des.\n  destruct x, y. exploit compose_step1; eauto. s. i. des.\n  exploit IHSTEPS; eauto. s. i. des.\n  splits; eauto.\n  econs; eauto. econs. eauto.\nQed.\n\nLemma compose_rtc_step2\n      c1 c2 ths\n      (STEPS: rtc Configuration.tau_step c1 c2)\n      (DISJOINT: Threads.disjoint ths c1.(Configuration.threads))\n      (WF1: Configuration.wf c1)\n      (WF: Configuration.wf (Configuration.mk ths c1.(Configuration.sc) c1.(Configuration.memory)))\n      (CONSISTENT1: Configuration.consistent c1)\n      (CONSISTENT: Configuration.consistent (Configuration.mk ths c1.(Configuration.sc) c1.(Configuration.memory))):\n  <<STEPS: rtc Configuration.tau_step\n               (Configuration.mk (Threads.compose ths c1.(Configuration.threads)) c1.(Configuration.sc) c1.(Configuration.memory))\n               (Configuration.mk (Threads.compose ths c2.(Configuration.threads)) c2.(Configuration.sc) c2.(Configuration.memory))>> /\\\n  <<DISJOINT': Threads.disjoint ths c2.(Configuration.threads)>> /\\\n  <<WF': Configuration.wf (Configuration.mk ths c2.(Configuration.sc) c2.(Configuration.memory))>> /\\\n  <<CONSISTENT': Configuration.consistent (Configuration.mk ths c2.(Configuration.sc) c2.(Configuration.memory))>>.\nProof.\n  revert CONSISTENT1 CONSISTENT. induction STEPS; auto. i. inv H.\n  exploit Configuration.step_future; eauto. i. des.\n  exploit Configuration.step_disjoint; try symmetry; eauto. i. des.\n  destruct x, y. exploit compose_step2; eauto. s. i. des.\n  exploit IHSTEPS; try symmetry; eauto. s. i. des.\n  splits; eauto.\n  econs; eauto. econs. eauto.\nQed.\n\n\nLemma sim_compose\n      ths1_src ths2_src sc0_src mem0_src\n      ths1_tgt ths2_tgt sc0_tgt mem0_tgt\n      (DISJOINT_SRC: Threads.disjoint ths1_src ths2_src)\n      (DISJOINT_TGT: Threads.disjoint ths1_tgt ths2_tgt)\n      (SIM1: sim ths1_src sc0_src mem0_src ths1_tgt sc0_tgt mem0_tgt)\n      (SIM2: sim ths2_src sc0_src mem0_src ths2_tgt sc0_tgt mem0_tgt):\n  sim (Threads.compose ths1_src ths2_src) sc0_src mem0_src\n      (Threads.compose ths1_tgt ths2_tgt) sc0_tgt mem0_tgt.\nProof.\n  revert\n    ths1_src ths2_src sc0_src mem0_src\n    ths1_tgt ths2_tgt sc0_tgt mem0_tgt\n    DISJOINT_SRC DISJOINT_TGT\n    SIM1 SIM2.\n  pcofix CIH. i. pfold. ii.\n  apply compose_wf in WF_SRC; auto.\n  apply compose_wf in WF_TGT; auto.\n  apply compose_consistent in CONSISTENT_SRC; auto.\n  apply compose_consistent in CONSISTENT_TGT; auto.\n  des. splits; i.\n  - punfold SIM1. exploit SIM1; try apply SC1; eauto. i. des.\n    apply compose_is_terminal in TERMINAL_TGT; auto. des.\n    exploit TERMINAL; eauto. i. des.\n    exploit Configuration.rtc_step_future; eauto. s. i. des.\n    exploit Configuration.rtc_step_disjoint; eauto. s. i. des.\n    exploit compose_rtc_step1; eauto. s. i. des.\n    punfold SIM2. exploit SIM2; try apply SC; eauto.\n    { etrans; eauto. }\n    { etrans; eauto. }\n    i. des.\n    exploit TERMINAL0; eauto. i. des.\n    exploit Configuration.rtc_step_future; eauto. s. i. des.\n    exploit Configuration.rtc_step_disjoint; try symmetry; eauto. s. i. des.\n    exploit compose_rtc_step2; eauto. s. i. des.\n    esplits.\n    + etrans; eauto.\n    + eauto.\n    + eauto.\n    + apply compose_is_terminal; auto.\n  - apply compose_step in STEP_TGT; auto. des; subst.\n    + exploit Configuration.step_future; eauto. s. i. des.\n      exploit Configuration.step_disjoint; eauto. s. i. des.\n      punfold SIM1. exploit SIM1; try apply SC1; eauto. i. des.\n      exploit STEP0; eauto. i. des. inv SIM; [|done].\n      exploit Configuration.rtc_step_future; eauto. s. i. des.\n      exploit Configuration.rtc_step_disjoint; eauto. s. i. des.\n      exploit compose_rtc_step1; eauto. s. i. des.\n      exploit Configuration.opt_step_future; eauto. s. i. des.\n      exploit Configuration.opt_step_disjoint; eauto. s. i. des.\n      exploit compose_opt_step1; eauto. i. des.\n      esplits; eauto.\n      right. apply CIH; auto.\n      eapply sim_future; eauto.\n      * repeat (etrans; eauto).\n      * repeat (etrans; eauto).\n      * repeat (etrans; eauto).\n      * repeat (etrans; eauto).\n    + exploit Configuration.step_future; eauto. s. i. des.\n      exploit Configuration.step_disjoint; try symmetry; eauto. s. i. des.\n      punfold SIM2. exploit SIM2; try apply SC1; eauto. i. des.\n      exploit STEP0; eauto. i. des. inv SIM; [|done].\n      exploit Configuration.rtc_step_future; eauto. s. i. des.\n      exploit Configuration.rtc_step_disjoint; try symmetry; eauto. s. i. des.\n      exploit compose_rtc_step2; eauto. s. i. des.\n      exploit Configuration.opt_step_future; eauto. s. i. des.\n      exploit Configuration.opt_step_disjoint; eauto. s. i. des.\n      exploit compose_opt_step2; eauto. i. des.\n      esplits; eauto.\n      right. apply CIH; auto.\n      { symmetry. auto. }\n      eapply sim_future; eauto.\n      * repeat (etrans; eauto).\n      * repeat (etrans; eauto).\n      * repeat (etrans; eauto).\n      * repeat (etrans; eauto).\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-coq", "sha": "bff53239c51681ea653745cebf3b30ddd38f97ba", "save_path": "github-repos/coq/snu-sf-promising-coq", "path": "github-repos/coq/snu-sf-promising-coq/promising-coq-bff53239c51681ea653745cebf3b30ddd38f97ba/src/opt/Composition.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.22299194281296822}}
{"text": "Require Import Omega.\nRequire Import Bool.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Behavior.\nRequire Import Single.\n\nRequire Import OrdStep.\nRequire Import RARace.\nRequire Import SCStep.\nRequire Import Stable.\n\nRequire Import MemoryProps.\nRequire Import Mapping.\nRequire Import SplitCertification.\n\nRequire Import LocalDRFRA.\n\nSection SIM.\n\n  Variable L: Loc.t -> bool.\n\n  Lemma ra_program_step_sc_program_step_or_race lang\n        (th0 th1: Thread.t lang) e\n        (STEP: OrdThread.program_step L Ordering.acqrel e th0 th1)\n    :\n      (<<STEP: SCThread.program_step L e th0 th1>>) \\/\n      (<<RACE: SCRace.race L th0>>).\n  Proof.\n    destruct (classic (SCRace.race L th0)) as [RACE|RACE]; auto.\n    left. inv STEP. econs; eauto. inv LOCAL; ss.\n    - econs; eauto.\n    - inv LOCAL0. econs; eauto. econs; eauto.\n      i. destruct (Time.le_lt_dec to' ts); auto. exfalso. eapply RACE.\n      unfold SCRace.race, SCLocal.non_maximal. esplits; eauto; ss.\n      inv STEP. inv READABLE. eapply TimeFacts.le_lt_lt; eauto.\n      eapply RLX. des_ifs. etrans; [|eapply Ordering.join_r]. auto.\n    - inv LOCAL0. econs; eauto. econs; eauto.\n      i. destruct (Time.le_lt_dec to to'); auto. exfalso. eapply RACE.\n      unfold SCRace.race, SCLocal.non_maximal. esplits; eauto; ss.\n      inv STEP. inv WRITABLE. eapply TimeFacts.lt_le_lt; eauto.\n    - inv LOCAL1. inv LOCAL2. econs; eauto.\n      + econs; eauto.\n        i. destruct (Time.le_lt_dec to' tsr); auto. exfalso. eapply RACE.\n        unfold SCRace.race, SCLocal.non_maximal. esplits; eauto; ss.\n        inv STEP. inv READABLE. eapply TimeFacts.le_lt_lt; eauto.\n        eapply RLX. des_ifs. etrans; [|eapply Ordering.join_r]. auto.\n      + econs; eauto.\n        i. destruct (Time.le_lt_dec tsw to'); auto. exfalso. eapply RACE.\n        unfold SCRace.race, SCLocal.non_maximal. esplits; eauto; ss.\n        inv STEP0. inv WRITABLE. eapply TimeFacts.lt_le_lt; eauto.\n        eapply TimeFacts.le_lt_lt; eauto. inv STEP. ss.\n        etrans; [|eapply Time.join_l]. eapply Time.join_l.\n    - econs; eauto.\n    - econs; eauto.\n    - econs; eauto.\n  Qed.\n\n  Lemma ra_thread_step_sc_thread_step_or_race lang\n        (th0 th1: Thread.t lang) pf e\n        (STEP: OrdThread.step L Ordering.acqrel pf e th0 th1)\n    :\n      (<<STEP: SCThread.step L pf e th0 th1>>) \\/\n      (<<RACE: SCRace.race L th0>>).\n  Proof.\n    inv STEP.\n    - left. econs; eauto.\n    - eapply ra_program_step_sc_program_step_or_race in STEP0.\n      des; auto. left. econs 2; eauto.\n  Qed.\n\n  Lemma ra_thread_opt_step_sc_thread_opt_step_or_race lang\n        (th0 th1: Thread.t lang) e\n        (STEP: OrdThread.opt_step L Ordering.acqrel e th0 th1)\n    :\n      (<<STEP: SCThread.opt_step L e th0 th1>>) \\/\n      (<<RACE: SCRace.race L th0>>).\n  Proof.\n    inv STEP.\n    - left. econs; eauto.\n    - eapply ra_thread_step_sc_thread_step_or_race in STEP0.\n      des; auto. left. econs 2; eauto.\n  Qed.\n\n  Lemma ra_thread_tau_steps_sc_thread_tau_steps_or_race lang\n        (th0 th1: Thread.t lang)\n        (STEPS: rtc (OrdThread.tau_step L Ordering.acqrel) th0 th1)\n    :\n      (<<STEPS: rtc (SCThread.tau_step L) th0 th1>>) \\/\n      (exists th',\n          (<<STEPS0: rtc (SCThread.tau_step L) th0 th'>>) /\\\n          (<<STEPS1: rtc (OrdThread.tau_step L Ordering.acqrel) th' th1>>) /\\\n          (<<RACE: SCRace.race L th'>>)).\n  Proof.\n    induction STEPS; eauto. dup H. inv H. inv TSTEP.\n    eapply ra_thread_step_sc_thread_step_or_race in STEP; eauto. des.\n    - left. econs; eauto. econs; eauto. econs; eauto.\n    - right. exists th'. esplits; eauto. econs; eauto. econs; eauto. econs; eauto.\n    - right. exists x. esplits; eauto.\n    - right. exists x. esplits; eauto.\n  Qed.\n\n  Lemma ra_thread_all_steps_sc_thread_all_steps_or_race lang\n        (th0 th1: Thread.t lang)\n        (STEPS: rtc (OrdThread.all_step L Ordering.acqrel) th0 th1)\n    :\n      (<<STEPS: rtc (SCThread.all_step L) th0 th1>>) \\/\n      (exists th',\n          (<<STEPS0: rtc (SCThread.all_step L) th0 th'>>) /\\\n          (<<STEPS1: rtc (OrdThread.all_step L Ordering.acqrel) th' th1>>) /\\\n          (<<RACE: SCRace.race L th'>>)).\n  Proof.\n    induction STEPS; eauto. dup H. inv H. inv USTEP.\n    eapply ra_thread_step_sc_thread_step_or_race in STEP; eauto. des.\n    - left. econs; eauto. econs; eauto. econs; eauto.\n    - right. exists th'. esplits; eauto. econs; eauto. econs; eauto. econs; eauto.\n    - right. exists x. esplits; eauto.\n    - right. exists x. esplits; eauto.\n  Qed.\n\n  Lemma cap_step_current_step\n        pf e lang (e0 e1: Thread.t lang) fe0\n        (THREAD: thread_map ident_map e0 fe0)\n        (STEP: SCThread.step L pf e e0 e1)\n        (LOCAL: Local.wf (Thread.local e0) (Thread.memory e0))\n        (FLOCAL: Local.wf (Thread.local fe0) (Thread.memory fe0))\n        (MEMORY: Memory.closed (Thread.memory e0))\n        (FMEMORY: Memory.closed (Thread.memory fe0))\n        (SC: Memory.closed_timemap (Thread.sc e0) (Thread.memory e0))\n        (FSC: Memory.closed_timemap (Thread.sc fe0) (Thread.memory fe0))\n    :\n      (exists fe fe1,\n          (<<THREAD: thread_map ident_map e1 fe1>>) /\\\n          (<<STEP: SCThread.step L pf fe fe0 fe1>>) /\\\n          (<<EVENT: tevent_map ident_map fe e>>)) \\/\n      (<<RACE: SCRace.race L fe0>>)\n  .\n  Proof.\n    destruct (classic (SCRace.race L fe0)) as [RACE|RACE]; auto. left.\n    assert (MAPLT: mapping_map_lt ident_map).\n    { eapply ident_map_lt. }\n    assert (MAPLE: mapping_map_le ident_map).\n    { eapply ident_map_le. }\n    assert (MAPEQ: mapping_map_eq ident_map).\n    { eapply ident_map_eq. }\n\n    inv THREAD. ss. inv STEP.\n    { inv STEP0. inv LOCAL1.\n      exploit promise_map; try apply PROMISE; eauto; ss.\n      { eapply FLOCAL. }\n      { eapply LOCAL0. }\n      { eapply mapping_map_lt_non_collapsable; eauto. }\n      { eapply ident_map_message. }\n      i. des. inv LOCAL0.\n      eexists _, (Thread.mk _ st (Local.mk (Local.tview flc) fprom1) fsc fmem1).\n      esplits; eauto.\n      { econs; eauto.\n        { econs; eauto. }\n        { eapply mapping_map_lt_collapsable_unwritable; eauto. }\n      }\n      { econs 1. econs.\n        { econs; eauto. eapply closed_message_map; eauto.\n          eapply ident_map_message. }\n        { inv KIND; ss. inv MSG; ss. }\n        { ii. clarify. exploit PF; eauto. }\n      }\n      { econs; eauto; ss. eapply ident_map_message. }\n    }\n    { inv STEP0. inv LOCAL1.\n      { esplits; eauto.\n        { econs; eauto. }\n        { econs 2; eauto. econs; eauto. econs 1; eauto. }\n        { econs; eauto. }\n      }\n      { inv LOCAL2. exploit read_step_map; eauto.\n        { eapply ident_map_bot. }\n        { eapply FLOCAL. } i. des.\n        exists (ThreadEvent.read loc fto val freleased ord). esplits.\n        { econs; eauto. eapply mapping_map_lt_collapsable_unwritable; eauto. }\n        { econs 2; eauto. econs; eauto. econs 2; eauto. econs; eauto.\n          ii. destruct (Time.le_lt_dec to' fto); auto. exfalso. eapply RACE.\n          unfold SCRace.race, SCLocal.non_maximal. esplits; eauto; ss.\n          inv READ. inv READABLE. eapply TimeFacts.le_lt_lt; eauto.\n          eapply RLX; eauto. des_ifs. etrans; [|eapply Ordering.join_r]. auto.\n        }\n        { econs; eauto. }\n      }\n      { inv LOCAL2. hexploit write_step_map; try eassumption; eauto.\n        { eapply ident_map_bot. }\n        { eapply FLOCAL. }\n        { eapply FLOCAL. }\n        { econs 2. }\n        { refl. }\n        { refl. }\n        { eapply mapping_map_lt_non_collapsable; eauto. }\n        i. des.\n        exists (ThreadEvent.write loc from to val freleasedw ord). esplits.\n        { econs; eauto. eapply mapping_map_lt_collapsable_unwritable; eauto. }\n        { econs 2; eauto. econs; eauto. econs 3; eauto. econs; eauto.\n          ii. destruct (Time.le_lt_dec to to'); auto. exfalso. eapply RACE.\n          unfold SCRace.race, SCLocal.non_maximal. esplits; eauto; ss.\n          inv WRITE. inv WRITABLE. eapply TimeFacts.lt_le_lt; eauto.\n        }\n        { econs; eauto; ss. }\n      }\n      { inv LOCAL2. inv LOCAL3. exploit read_step_map; eauto.\n        { eapply ident_map_bot. }\n        { eapply FLOCAL. } i. des.\n        hexploit Local.read_step_future; try apply STEP; eauto. i. des.\n        hexploit Local.read_step_future; try apply READ; eauto. i. des.\n        hexploit write_step_map; try eapply STEP0; try eassumption; eauto.\n        { eapply ident_map_bot. }\n        { eapply WF0. }\n        { eapply WF0. }\n        { eapply mapping_map_lt_collapsable_unwritable; eauto. }\n        { refl. }\n        { eapply mapping_map_lt_non_collapsable; eauto. }\n        i. des.\n        exists (ThreadEvent.update loc fto tsw valr valw freleased freleasedw ordr ordw). esplits.\n        { econs; eauto. eapply mapping_map_lt_collapsable_unwritable; eauto. }\n        { econs 2; eauto. econs; eauto. econs 4; eauto.\n          { econs; eauto.\n            ii. destruct (Time.le_lt_dec to' fto); auto. exfalso. eapply RACE.\n            unfold SCRace.race, SCLocal.non_maximal. esplits; eauto; ss.\n            inv READ. inv READABLE. eapply TimeFacts.le_lt_lt; eauto.\n            eapply RLX; eauto. des_ifs. etrans; [|eapply Ordering.join_r]. auto.\n          }\n          { econs; eauto.\n            ii. destruct (Time.le_lt_dec tsw to'); auto. exfalso. eapply RACE.\n            unfold SCRace.race, SCLocal.non_maximal. esplits; eauto; ss.\n            inv WRITE. inv WRITABLE. eapply TimeFacts.lt_le_lt; eauto.\n            eapply TimeFacts.le_lt_lt; eauto. eapply TVIEW_FUTURE0.\n          }\n        }\n        { econs; eauto; ss. }\n      }\n      { inv LOCAL2. exploit fence_step_map; try apply FENCE; eauto.\n        { eapply ident_map_bot. }\n        { eapply FLOCAL. } i. des.\n        exists (ThreadEvent.fence ordr ordw). esplits.\n        { econs; eauto. }\n        { econs 2; eauto. econs; eauto. econs 5; eauto. }\n        { econs; eauto; ss. }\n      }\n      { inv LOCAL2. exploit fence_step_map; eauto.\n        { eapply ident_map_bot. }\n        { eapply FLOCAL. } i. des.\n        exists (ThreadEvent.syscall e0). esplits.\n        { econs; eauto. }\n        { econs 2; eauto. econs; eauto. econs 6; eauto. }\n        { econs; eauto; ss. }\n      }\n      { inv LOCAL2. exploit failure_step_map; eauto. i.\n        exists (ThreadEvent.failure). esplits.\n        { econs; eauto. }\n        { econs 2; eauto. econs; eauto. econs 7; eauto. }\n        { econs; eauto; ss. }\n      }\n    }\n  Qed.\n\n  Lemma sc_race_map f lang (th0 fth0: Thread.t lang)\n        (RACE: SCRace.race L th0)\n        (THREAD: thread_map f th0 fth0)\n        (MAPLT: mapping_map_lt f)\n    :\n      SCRace.race L fth0.\n  Proof.\n    unfold SCRace.race, SCLocal.non_maximal in *. des. inv THREAD. ss.\n    eapply MEM in GET. des; ss. inv MSG. inv MSGLE.\n    esplits; eauto. inv LOCAL. inv TVIEWLE. inv CUR. specialize (RLX loc).\n    eapply TimeFacts.le_lt_lt; eauto.\n    eapply (@MAPLT loc (View.rlx (TView.cur (Local.tview lc)) loc) to (View.rlx (TView.cur ftv') loc) fto); eauto.\n    eapply TVIEW.\n  Qed.\n\n  Lemma cap_tau_steps_current_tau_steps\n        lang (e0 e1: Thread.t lang) fe0\n        (THREAD: thread_map ident_map e0 fe0)\n        (STEPS: rtc (SCThread.tau_step L) e0 e1)\n        (LOCAL: Local.wf (Thread.local e0) (Thread.memory e0))\n        (FLOCAL: Local.wf (Thread.local fe0) (Thread.memory fe0))\n        (MEMORY: Memory.closed (Thread.memory e0))\n        (FMEMORY: Memory.closed (Thread.memory fe0))\n        (SC: Memory.closed_timemap (Thread.sc e0) (Thread.memory e0))\n        (FSC: Memory.closed_timemap (Thread.sc fe0) (Thread.memory fe0))\n    :\n      (exists fe1,\n          (<<THREAD: thread_map ident_map e1 fe1>>) /\\\n          (<<STEP: rtc (SCThread.tau_step L) fe0 fe1>>)) \\/\n      (exists e' fe',\n          (<<FSTEPS: rtc (SCThread.tau_step L) fe0 fe'>>) /\\\n          (<<STEPS0: rtc (SCThread.tau_step L) e0 e'>>) /\\\n          (<<STEPS1: rtc (SCThread.tau_step L) e' e1>>) /\\\n          (<<THREAD: thread_map ident_map e' fe'>>) /\\\n          (<<RACE: SCRace.race L fe'>>)).\n  Proof.\n    ginduction STEPS; i.\n    { left. esplits; eauto. }\n    dup H. inv H. inv TSTEP. exploit cap_step_current_step; eauto.\n    i. des.\n    - exploit SCThread.step_future; try apply STEP; eauto. i. des.\n      exploit SCThread.step_future; try apply STEP0; eauto. i. des.\n      exploit IHSTEPS; eauto. i. des.\n      + left. esplits; eauto. econs; eauto. econs.\n        * econs; eauto.\n        * erewrite <- EVENT. inv EVENT0; eauto.\n      + right. exists e', fe'. esplits; eauto. econs; eauto. econs.\n        * econs; eauto.\n        * erewrite <- EVENT. inv EVENT0; eauto.\n    - right. esplits; eauto.\n  Qed.\n\n  Lemma cap_race_current_race\n        lang (e0 e1: Thread.t lang) cap max\n        (CAP: Memory.cap (Thread.memory e0) cap)\n        (MAX: Memory.max_concrete_timemap cap max)\n        (STEPS: rtc (SCThread.tau_step L) (Thread.mk _ (Thread.state e0) (Thread.local e0) max cap) e1)\n        (LOCAL: Local.wf (Thread.local e0) (Thread.memory e0))\n        (MEMORY: Memory.closed (Thread.memory e0))\n        (SC: Memory.closed_timemap (Thread.sc e0) (Thread.memory e0))\n        (CONSISTENT: Local.promise_consistent (Thread.local e1))\n        (RACE: SCRace.race L e1)\n    :\n      exists e2,\n        (<<STEPS: rtc (SCThread.tau_step L) e0 e2>>) /\\\n        (<<CONSISTENT: Local.promise_consistent (Thread.local e2)>>) /\\\n        (<<RACE: SCRace.race L e2>>).\n  Proof.\n    exploit cap_tau_steps_current_tau_steps.\n    { econs.\n      { eapply ident_map_local. }\n      { instantiate (1:=(Thread.memory e0)). instantiate (1:=cap). econs.\n        - i. eapply Memory.cap_inv in GET; eauto. des; clarify; auto.\n          right. exists to, from, msg, msg.\n          esplits; eauto; try refl. eapply ident_map_message.\n        - i. left.\n          exists fto, ffrom, fto, ffrom. esplits; eauto; try refl.\n          i. econs; eauto. eapply Memory.cap_le; eauto. refl.\n      }\n      { eapply mapping_map_lt_collapsable_unwritable. eapply ident_map_lt. }\n      { eapply ident_map_timemap. }\n      { instantiate (1:=max). instantiate (1:=(Thread.sc e0)).\n        eapply Memory.max_concrete_timemap_spec; eauto.\n        eapply Memory.cap_closed_timemap; eauto. }\n    }\n    { eauto. }\n    { eapply Local.cap_wf; eauto. }\n    { eauto. }\n    { eapply Memory.cap_closed; eauto. }\n    { eauto. }\n    { eapply Memory.max_concrete_timemap_closed; eauto. }\n    { eauto. }\n    i. des.\n    - exists fe1. esplits.\n      + destruct e0. ss.\n      + destruct e1, fe1. destruct local, local0. ss. inv THREAD.\n        inv LOCAL0. ss.\n        eapply promise_consistent_mon.\n        { eapply promise_consistent_map; eauto.\n          { eapply ident_map_le. }\n          { eapply ident_map_eq. }\n        }\n        { eauto. }\n        { refl. }\n      + eapply sc_race_map; eauto. eapply ident_map_lt.\n    - assert (CONSISTENT0: Local.promise_consistent (Thread.local e')).\n      { exploit SCThread.rtc_tau_step_future; try apply STEPS0; eauto.\n        { eapply Local.cap_wf; eauto. }\n        { eapply Memory.max_concrete_timemap_closed; eauto. }\n        { eapply Memory.cap_closed; eauto. }\n        i. des. ss. eapply SCThread.rtc_tau_step_promise_consistent; eauto.\n      }\n      exists fe'. esplits.\n      + destruct e0. ss.\n      + destruct e', fe'. destruct local, local0. ss. inv THREAD.\n        inv LOCAL0. ss.\n        eapply promise_consistent_mon.\n        { eapply promise_consistent_map; eauto.\n          { eapply ident_map_le. }\n          { eapply ident_map_eq. }\n        }\n        { eauto. }\n        { refl. }\n      + auto.\n  Qed.\n\n  Lemma ord_thread_consistent_promise_consistent lang\n        (th0: Thread.t lang)\n        (CONSISTENT: OrdThread.consistent L Ordering.acqrel th0)\n        (LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))\n        (MEMORY: Memory.closed (Thread.memory th0))\n        (SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))\n    :\n      Local.promise_consistent (Thread.local th0).\n  Proof.\n    hexploit (@Memory.cap_exists (Thread.memory th0)); eauto. intros [cap CAP].\n    hexploit (@Memory.max_concrete_timemap_exists cap); eauto.\n    { eapply Memory.cap_closed; eauto. } intros [max MAX].\n    exploit CONSISTENT; eauto. i. des.\n    { unfold OrdThread.steps_failure in FAILURE. des.\n      eapply OrdThread.rtc_tau_step_promise_consistent in STEPS; eauto.\n      { eapply Local.cap_wf; eauto. }\n      { eapply Memory.max_concrete_timemap_closed; eauto. }\n      { eapply Memory.cap_closed; eauto. }\n      { inv FAILURE0; inv STEP. inv LOCAL0. inv LOCAL1. ss. }\n    }\n    { eapply OrdThread.rtc_tau_step_promise_consistent in STEPS; eauto.\n      { eapply Local.cap_wf; eauto. }\n      { eapply Memory.max_concrete_timemap_closed; eauto. }\n      { eapply Memory.cap_closed; eauto. }\n      { eapply Local.bot_promise_consistent; eauto. }\n    }\n  Qed.\n\n  Lemma ra_thread_consistent_sc_thread_consistent_or_race lang\n        (th0: Thread.t lang)\n        (CONSISTENT: OrdThread.consistent L Ordering.acqrel th0)\n        (LOCAL: Local.wf (Thread.local th0) (Thread.memory th0))\n        (MEMORY: Memory.closed (Thread.memory th0))\n        (SC: Memory.closed_timemap (Thread.sc th0) (Thread.memory th0))\n    :\n      (<<CONSISTENT: SCThread.consistent L th0>>) \\/\n      (exists th1,\n          (<<STEPS: rtc (SCThread.tau_step L) th0 th1>>) /\\\n          (<<CONSISTENT: Local.promise_consistent (Thread.local th1)>>) /\\\n          (<<RACE: SCRace.race L th1>>)).\n  Proof.\n    destruct (classic (exists th1,\n                          (<<STEPS: rtc (SCThread.tau_step L) th0 th1>>) /\\\n                          (<<CONSISTENT: Local.promise_consistent (Thread.local th1)>>) /\\\n                          (<<RACE: SCRace.race L th1>>))) as [RACE|RACE]; auto.\n    left. ii. exploit CONSISTENT; eauto. i. des.\n    - unfold OrdThread.steps_failure in *. des.\n      left. unfold SCThread.steps_failure.\n      eapply ra_thread_tau_steps_sc_thread_tau_steps_or_race in STEPS. des.\n      + inv FAILURE0; inv STEP. inv LOCAL0. inv LOCAL1.\n        esplits; eauto. econs 2; eauto; ss. econs; eauto. econs; eauto.\n      + exfalso. eapply RACE.\n        eapply cap_race_current_race; eauto.\n        exploit SCThread.rtc_tau_step_future; try apply STEPS0; eauto.\n        { eapply Local.cap_wf; eauto. }\n        { eapply Memory.max_concrete_timemap_closed; eauto. }\n        { eapply Memory.cap_closed; eauto. }\n        i. des. ss. eapply OrdThread.rtc_tau_step_promise_consistent; eauto.\n        inv FAILURE0; inv STEP. inv LOCAL0. inv LOCAL1. ss.\n    - right. eapply ra_thread_tau_steps_sc_thread_tau_steps_or_race in STEPS. des.\n      + esplits; eauto.\n      + exfalso. eapply RACE.\n        eapply cap_race_current_race; eauto.\n        exploit SCThread.rtc_tau_step_future; try apply STEPS0; eauto.\n        { eapply Local.cap_wf; eauto. }\n        { eapply Memory.max_concrete_timemap_closed; eauto. }\n        { eapply Memory.cap_closed; eauto. }\n        i. des. ss. eapply OrdThread.rtc_tau_step_promise_consistent; eauto.\n        eapply Local.bot_promise_consistent; eauto.\n  Qed.\n\n  Lemma ra_configuration_step_sc_configuration_step_or_race e tid c0 c1\n        (STEP: OrdConfiguration.step L Ordering.acqrel e tid c0 c1)\n        (WF: Configuration.wf c0)\n    :\n      (<<STEP: SCConfiguration.step L e tid c0 c1>>) \\/\n      (<<RACE: SCRace.race_steps L c0 tid>>).\n  Proof.\n    destruct (classic (SCRace.race_steps L c0 tid)) as [RACE|RACE]; auto. left.\n    inv STEP.\n    exploit Thread.rtc_cancel_step_future; eauto; try eapply WF; eauto. i. des. ss.\n    assert ((<<LOCAL: Local.wf lc4 memory4>>) /\\\n            (<<MEMORY: Memory.closed memory4>>) /\\\n            (<<CLOSED: Memory.closed_timemap sc4 memory4>>)).\n    { inv STEP0.\n      - exploit Thread.rtc_reserve_step_future; eauto. i. des. ss.\n      - exploit OrdThread.step_future; eauto. i. des. ss.\n        exploit Thread.rtc_reserve_step_future; eauto. i. des. ss.\n    } des.\n\n    assert ((<<CONSISTENT: Local.promise_consistent (Thread.local e2)>>) /\\\n            (<<CONSISTENT: Local.promise_consistent lc4>>)).\n    { destruct (classic (e = ThreadEvent.failure)).\n      - clarify. inv STEP0. inv STEP; inv STEP0. inv LOCAL0. inv LOCAL1. splits; auto.\n        eapply PromiseConsistent.rtc_reserve_step_promise_consistent2 in RESERVES; eauto.\n      - hexploit ord_thread_consistent_promise_consistent; eauto. i. ss. splits; eauto.\n        eapply PromiseConsistent.rtc_reserve_step_promise_consistent in RESERVES; eauto.\n        inv STEP0; auto. eapply OrdThread.step_promise_consistent in STEP; eauto.\n    }\n\n    exploit ra_thread_opt_step_sc_thread_opt_step_or_race; try apply STEP0.\n    i. des; cycle 1.\n    { exfalso. eapply RACE. unfold SCRace.race_steps. esplits.\n      + eauto.\n      + eapply rtc_implies; try apply CANCELS. i.\n        inv H. inv STEP; [|inv STEP1; inv LOCAL0]. econs; eauto.\n        * econs; eauto. econs 1; eauto. ii. clarify.\n        (* * ss. *)\n      + eauto.\n      + eauto.\n    }\n\n    econs; eauto. i.\n    hexploit ra_thread_consistent_sc_thread_consistent_or_race; eauto; ss. i. des; ss.\n    destruct (ThreadEvent.get_machine_event e) eqn:EVENT.\n    { exfalso. eapply RACE. unfold SCRace.race_steps. esplits.\n      + eauto.\n      + etrans.\n        { eapply rtc_implies; try apply CANCELS. i.\n          inv H0. inv STEP1; [|inv STEP2; inv LOCAL0]. econs.\n          * econs; eauto. econs 1; eauto. ii. clarify.\n          (* * ss. *)\n        } etrans.\n        { instantiate (1:=e3). inv STEP; eauto. econs; eauto.\n          econs; eauto. econs; eauto. } etrans.\n        { eapply rtc_implies; try apply RESERVES. i.\n          inv H0. inv STEP1; [|inv STEP2; inv LOCAL0]. econs.\n          * econs; eauto. econs 1; eauto. ii. clarify.\n          (* * ss. *)\n        }\n        { eapply rtc_implies; try apply STEPS. i. inv H0. econs; eauto. }\n      + eauto.\n      + eauto.\n    }\n    { destruct e; clarify. inv STEP. inv STEP1; inv STEP.\n      inv LOCAL0. inv LOCAL1. hexploit PROMISES; eauto. ii. right. ss.\n      hexploit reserve_steps_le_cancel_steps.\n      { eapply RESERVES. }\n      { eapply Memory.cap_le; eauto. refl. }\n      i. des. esplits.\n      { eapply rtc_implies; try apply STEPS0; eauto. i.\n        inv H1. inv STEP; [|inv STEP1; inv LOCAL1]. econs.\n        * econs; eauto. econs 1; eauto. ii. clarify.\n        * ss.\n      }\n      erewrite LOCAL0. eauto.\n    }\n    { destruct e; ss. }\n  Qed.\n\n  Lemma ra_configuration_steps_sc_configuration_steps_or_race c0 c1\n        (STEPS: rtc (OrdConfiguration.all_step L Ordering.acqrel) c0 c1)\n        (WF: Configuration.wf c0)\n    :\n      (<<STEPS: rtc (SCConfiguration.all_step L) c0 c1>>) \\/\n      (exists c' tid,\n          (<<STEPS: rtc (SCConfiguration.all_step L) c0 c'>>) /\\\n          (<<RACE: SCRace.race_steps L c' tid>>)).\n  Proof.\n    ginduction STEPS; eauto. i. inv H.\n    eapply ra_configuration_step_sc_configuration_step_or_race in STEP; eauto. des.\n    { exploit SCConfiguration.step_future; eauto. i. des.\n      exploit IHSTEPS; eauto. i. des.\n      { left. econs; eauto. econs; eauto. }\n      { right. esplits; [|eapply RACE]. econs; eauto. econs; eauto. }\n    }\n    { right. esplits; eauto. }\n  Qed.\n\n  Lemma ra_behavior_sc_behavior_or_race c\n        (RACEFREE: SCRace.racefree L c)\n        (WF: Configuration.wf c)\n    :\n      behaviors (@OrdConfiguration.machine_step L Ordering.acqrel) c <1=\n      behaviors (@SCConfiguration.machine_step L) c.\n  Proof.\n    i. ginduction PR; eauto; i.\n    - econs 1; eauto.\n    - inv STEP.\n      eapply ra_configuration_step_sc_configuration_step_or_race in STEP0; eauto. des.\n      + econs 2; eauto.\n        * rewrite <- H0. econs; eauto.\n        * eapply IHPR; eauto.\n          { eapply SCRace.step_racefree; eauto. }\n          { eapply SCConfiguration.step_future; eauto. }\n      + exfalso. eapply RACEFREE; eauto.\n    - inv STEP.\n      eapply ra_configuration_step_sc_configuration_step_or_race in STEP0; eauto. des.\n      + econs 3; eauto.\n        * rewrite <- H0. econs; eauto.\n      + exfalso. eapply RACEFREE; eauto.\n    - inv STEP.\n      eapply ra_configuration_step_sc_configuration_step_or_race in STEP0; eauto. des.\n      + econs 4; eauto.\n        * rewrite <- H0. econs; eauto.\n        * eapply IHPR; eauto.\n          { eapply SCRace.step_racefree; eauto. }\n          { eapply SCConfiguration.step_future; eauto. }\n      + exfalso. eapply RACEFREE; eauto.\n  Qed.\n\n  Lemma sc_racefree_ra_racefree c\n        (RACEFREE: SCRace.racefree L c)\n        (WF: Configuration.wf c)\n    :\n      RARace.racefree L c.\n  Proof.\n    ii. unfold RARace.race in *. des. guardH ORDERING.\n    exploit ra_configuration_steps_sc_configuration_steps_or_race.\n    { etrans.\n      { eapply STEPS1. } econs 2.\n      { econs; eauto. }\n      { eapply STEPS2. }\n    }\n    { eauto. }\n    i. des.\n    { exploit ra_thread_all_steps_sc_thread_all_steps_or_race; eauto. i. des.\n      { eapply RACEFREE; eauto. econs. esplits; eauto.\n        unfold ThreadEvent.is_reading in *. des_ifs.\n        - inv READ_STEP; inv STEP. econs; eauto. esplits; eauto; ss.\n          inv LOCAL. inv LOCAL0. inv STEP.\n          unfold SCLocal.non_maximal. esplits; eauto.\n        - inv READ_STEP; inv STEP. econs; eauto. esplits; eauto; ss.\n          inv LOCAL. inv LOCAL1. inv LOCAL2. inv STEP.\n          unfold SCLocal.non_maximal. esplits; eauto.\n      }\n      { eapply RACEFREE; eauto. econs. esplits; eauto.\n        exploit SCConfiguration.all_steps_future; eauto. i. des.\n        exploit SCThread.rtc_all_step_future; eauto; try eapply WF2; eauto.\n        i. des. ss.\n        eapply OrdThread.rtc_all_step_promise_consistent in STEPS3; eauto.\n      }\n    }\n    { eapply RACEFREE; eauto. }\n  Qed.\n\nEnd SIM.\n\n\n(* LDRF-SC theorem *)\nTheorem local_drf_sc L\n        s\n        (RACEFREE: SCRace.racefree_syn L s):\n  behaviors SConfiguration.machine_step (Configuration.init s) <1=\n  behaviors (@SCConfiguration.machine_step L) (Configuration.init s).\nProof.\n  i. eapply local_drf_ra in PR; eauto.\n  - eapply ra_behavior_sc_behavior_or_race; eauto.\n    eapply Configuration.init_wf; eauto.\n  - eapply sc_racefree_ra_racefree; eauto.\n    eapply Configuration.init_wf; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/ldrfsc/LocalDRFSC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.3738758367247084, "lm_q1q2_score": 0.22299194161003727}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef1.Spec.\nRequire Import TableDataOpsRef2.Specs.table_create2.\nRequire Import TableDataOpsRef2.LowSpecs.table_create2.\nRequire Import TableDataOpsRef2.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       table_create_spec\n       table_create1_spec\n    .\n\n  Lemma table_create2_spec_exists:\n    forall habd habd'  labd g_rd map_addr level g_rtt rtt_addr res\n      (Hspec: table_create2_spec g_rd map_addr level g_rtt rtt_addr habd = Some (habd', res))\n      (Hrel: relate_RData habd labd),\n    exists labd', table_create2_spec0 g_rd map_addr level g_rtt rtt_addr labd = Some (labd', res) /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque peq ptr_eq granule_fill_table.fill_table.\n    intros. duplicate Hrel. destruct D. clear hrepl lrepl. destruct g_rtt, g_rd.\n    unfold table_create2_spec, table_create2_spec0 in *.\n    unfold Assertion in *. rm_bind Hspec; rm_bind'. simpl in *.\n    unfold Assertion; rm_bind'; grewrite.\n    repeat simpl_hyp Hspec; extract_prop_dec; simpl_query_oracle; rm_bind'; grewrite.\n    - rewrite_oracle_rel rel_oracle C10.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold create_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec;\n        (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C10.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold create_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec;\n        (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C10.\n      repeat (grewrite; try simpl_htarget; simpl).\n      unfold create_table in *. simpl in *. autounfold in *. simpl in *. grewrite.\n      repeat simpl_hyp Hspec; simpl; inversion Hspec;\n        (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C10.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec; (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n    - rewrite_oracle_rel rel_oracle C10.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec; (eexists; split; [reflexivity| constructor; destruct Hrel; simpl; try assumption; try reflexivity]).\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef2/RefProof/table_create2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2229919332879985}}
{"text": "Require Import bedrock2.Syntax.\nRequire Import bedrock2.NotationsCustomEntry.\nRequire Import bedrock2.FE310CSemantics.\nRequire Import coqutil.Z.Lia.\n\nFrom bedrock2 Require Import BasicC64Semantics ProgramLogic.\nFrom bedrock2 Require Import Array Scalars Separation.\nFrom coqutil Require Import Word.Interface Map.Interface.\n\nFrom coqutil.Tactics Require Import letexists.\n\nFrom coqutil.Tactics Require Import syntactic_unify.\nFrom coqutil.Macros Require Import symmetry.\n\nFrom coqutil.Tactics Require Import syntactic_unify.\nFrom coqutil.Macros Require Import symmetry.\nRequire Import coqutil.Datatypes.List.\n\n\nSection WithParameters.\n  Import Syntax BinInt String List.ListNotations ZArith.\n  Local Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope list_scope.\n\n  Definition tf : bedrock_func :=\n    (\"tf\", ([\"buf\"; \"len\"; \"i\"; \"j\"], [], bedrock_func_body:(\n      require ( i < len ) else { /*skip*/ };\n      store1(buf + i, $0);\n      require ( j < len ) else { r = $-1 };\n      r = load1(buf + j)\n    ))).\n\n    Local Infix \"*\" := sep : type_scope.\n    Local Open Scope sep_scope.\n    Local Notation \"a [ i ]\" := (List.hd _ (List.skipn i a)) (at level 10, left associativity, format \"a [ i ]\").\n    Local Notation \"a [: i ]\" := (List.firstn i a) (at level 10, left associativity, format \"a [: i ]\").\n    Local Notation \"a [ i :]\" := (List.skipn i a) (at level 10, left associativity, format \"a [ i :]\").\n    Local Notation bytes := (array ptsto (word.of_Z 1)).\n    (* Local Notation word_to_nat x := (Z.to_nat (word.unsigned x)). *)\n    Local Infix \"+\" := word.add.\n    Local Infix \"+\" := word.add.\n\n  Local Instance spec_of_tf : spec_of \"tf\". refine (fun functions =>\n    forall t m buf len bs i j R,\n      (sep (array ptsto (word.of_Z 1) buf bs) R) m ->\n      word.unsigned len = Z.of_nat (List.length bs) ->\n      WeakestPrecondition.call functions \"tf\" t m [buf; len; i; j]\n      (fun T M rets =>\n         True)).\n  (* word.unsigned i < word.unsigned len -> word.unsigned j < word.unsigned len ->\n         rets = [word.of_Z (word.unsigned\n                ((bs[:word_to_nat i]++ word.of_Z 0 :: List.tl (bs[word_to_nat i:]))[word_to_nat j]))] *)\n  Defined.\n\n  Import SeparationLogic Lift1Prop.\n\n  Goal program_logic_goal_for_function! tf.\n  Proof.\n    repeat straightline.\n\n    letexists. split; [solve[repeat straightline] |].\n    split; [|solve [repeat straightline]]; repeat straightline.\n    eapply Properties.word.if_nonzero in H1; rewrite word.unsigned_ltu in H1; eapply Z.ltb_lt in H1.\n\n    simple refine (store_one_of_sep _ _ _ _ _ _ (Lift1Prop.subrelation_iff1_impl1 _ _ _ _ _ H) _); shelve_unifiable.\n    1: (etransitivity; [etransitivity|]); cycle -1; [ | | eapply Proper_sep_iff1; [|reflexivity]; eapply bytearray_index_inbounds]; try ecancel; try blia.\n\n    repeat straightline.\n\n    intros.\n\n    seprewrite_in (symmetry! @array_cons) H2.\n    seprewrite_in (@bytearray_index_merge) H2. {\n      pose proof Properties.word.unsigned_range i.\n      rewrite length_firstn_inbounds; blia.\n    }\n\n    letexists.\n    split; [solve[repeat straightline]|].\n    split; [|solve [repeat straightline]].\n\n    repeat straightline.\n    eapply Properties.word.if_nonzero in H3; rewrite word.unsigned_ltu in H3; eapply Z.ltb_lt in H3.\n\n    letexists.\n    split. {\n      letexists.\n      split; repeat straightline.\n      letexists; split. {\n        eapply load_one_of_sep.\n        simple refine (Lift1Prop.subrelation_iff1_impl1 _ _ _ _ _ H2).\n        (etransitivity; [|etransitivity]); [ | eapply Proper_sep_iff1; [|reflexivity]; eapply bytearray_index_inbounds | ].\n        3: ecancel.\n        1: ecancel.\n        pose proof Properties.word.unsigned_range i.\n        pose proof Properties.word.unsigned_range j.\n        rewrite List.app_length, length_cons, length_firstn_inbounds, length_skipn.\n        all: blia.\n    }\n    1: subst v1.\n    exact eq_refl.\n    }\n\n    repeat (straightline; [|..]).\n\n    exact I.\n  Qed.\n\n    (* [eseptract] solves goals of the form [state == needle * ?r] by\n      \"subtracting\" [needle] from [state] with the help of decomposition\n      hints of the form [a = b * c * d * ...]. [?r] will be instantiated\n      with the result of the subtraction \"state - needle\"; in terms of\n      the magic wand operator this tactic simplifies [needle -* state].\n      The process is directed by the syntactic form of [needle]:\n\n      1. If [needle] appears syntactically in [state], the equation is\n         solved by cancellation.\n      2. If [needle] matches a part of a RHS of a decomposition lemma,\n         the non-matched part of the RHS is into [r] and the LHS is\n         subtracted from the state recursively.\n      3. If [needle] is a separating conjunct of multiple clauses, they\n         of them will be subtracted separately. *)\n\n    (* TODO: should side conditions be solved before or after recursing?\n       - before does not work for arrays -- need to know which array before checking bounds\n       - after would mean all leaves of every struct would be explored -- uncontroled search *)\n\n    (* better algorithm might use hints containing:\n       - needle pattern\n       - state pattern = hint lhs\n       - condition when to apply this hint (is needle actually inside pattern?) this might be a judgementally trivial but syntactically informative precondition\n       - hint rhs\n       on match, only the hint rhs (plus original frame) would be searched for further matches *)\nEnd WithParameters.\n", "meta": {"author": "dderjoel", "repo": "base", "sha": "2aa122fb618100b7fed3119ea3cef73cec5bf4a5", "save_path": "github-repos/coq/dderjoel-base", "path": "github-repos/coq/dderjoel-base/base-2aa122fb618100b7fed3119ea3cef73cec5bf4a5/fiat-crypto/rupicola/bedrock2/bedrock2/src/bedrock2Examples/ArrayLoadStore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.22299192912697915}}
{"text": "From ITree Require Import ITree.\nFrom compcert Require Import AST Globalenvs Values Memory.\nFrom compcert Require Clight.\n\nRequire Import sflib.\nRequire Import StdlibExt IntegersExt.\n\nRequire Import SysSem.\nRequire Import SyncSysModel.\nRequire Import IPModel DiscreteTimeModel IntByteModel.\nRequire Import NWSysModel.\nRequire Import OSModel OSNodes.\nRequire Import ProgSem.\n\nRequire Import ZArith String List Lia.\n\n(* Import Params. *)\n\nSet Nested Proofs Allowed.\n\n(* Lemma Int_repr_eq_inv_signed *)\n(*       z i *)\n(*       (RANGE_Z: IntRange.sintz z) *)\n(*       (REPR_EQ: Int.repr z = i) *)\n(*   : z = Int.signed i. *)\n(* Proof. *)\n(*   subst i. r in RANGE_Z. *)\n(*   rewrite Int.signed_repr. *)\n(*   2: { apply RANGE_Z. } *)\n(*   ss. *)\n(* Qed. *)\n\nInductive extcallE: Type -> Type :=\n| ExtcallEvent_Int (fname: string) (* (sig: signature) *) (args: list val)\n  : extcallE int\n| ExtcallEvent_Void (fname: string) (* (sig: signature) *) (args: list val)\n  : extcallE unit\n.\n\nNotation obsE := (extcallE +' errE).\nNotation progE := (osE +' obsE).\n(* Notation nodeE := (nbE +' extcallE). *)\n\n\nLemma IntNat_of_nat_eq_inv_sint\n      n m\n      (RANGE_N: IntRange.sint n)\n      (RANGE_M: IntRange.sint m)\n      (INT_EQ: IntNat.of_nat n = IntNat.of_nat m)\n  : n = m.\nProof.\n  unfold IntNat.of_nat in INT_EQ.\n  assert (Int.signed (Int.repr (Z.of_nat n)) =\n          Int.signed (Int.repr (Z.of_nat m))).\n  { congruence. }\n  rewrite Int.signed_repr in * by range_stac.\n  rewrite Int.signed_repr in * by range_stac.\n  apply Nat2Z.inj. eauto.\nQed.\n\nLemma map_Byte_eq_inv\n      bs1 bs2\n      (MAP_EQ: map Byte bs1 = map Byte bs2)\n  : bs1 = bs2.\nProof.\n  depgen bs2.\n  induction bs1; i;\n    destruct bs2; ss.\n  inv MAP_EQ.\n  erewrite IHbs1; eauto.\nQed.\n\nLemma IntNat_of_nat64_eq_inv_uint\n      n m\n      (RANGE_N: IntRange.uint64 n)\n      (RANGE_M: IntRange.uint64 m)\n      (INT_EQ: IntNat.of_nat64 n = IntNat.of_nat64 m)\n  : n = m.\nProof.\n  unfold IntNat.of_nat64 in INT_EQ.\n  cut (Int64.unsigned (Int64.repr (Z.of_nat n)) =\n          Int64.unsigned (Int64.repr (Z.of_nat m))).\n  { rewrite Int64.unsigned_repr by range_stac.\n    rewrite Int64.unsigned_repr by range_stac.\n    apply Nat2Z.inj.\n  }\n  rewrite INT_EQ. ss.\nQed.\n\n\n(** ** External functions for progE *)\n\n(* OS *)\n\nDefinition open_socket_ef: AST.external_function :=\n  EF_external \"pals_socket\"\n              (mksignature nil AST.Tint cc_default).\nDefinition bind_socket_ef: AST.external_function :=\n  EF_external \"pals_bind\"\n              (mksignature (AST.Tint :: AST.Tint :: nil)\n                           AST.Tint cc_default).\nDefinition join_socket_ef: AST.external_function :=\n  EF_external \"pals_mcast_join\"\n              (mksignature (AST.Tint :: AST.Tlong :: nil)\n                           AST.Tvoid cc_default).\n(* Definition close_socket_ef: AST.external_function := *)\n(*   EF_external \"pals_close\" *)\n(*               (mksignature (AST.Tint :: nil) *)\n(*                            AST.Tint cc_default). *)\n\nDefinition sendto_ef: AST.external_function :=\n  EF_external \"pals_sendto\"\n              (mksignature\n                 (AST.Tint :: AST.Tlong :: AST.Tint :: AST.Tlong ::\n                           AST.Tint :: nil) AST.Tint cc_default).\nDefinition recvfrom_ef: AST.external_function :=\n  EF_external \"pals_recvfrom\"\n              (mksignature (AST.Tint :: AST.Tlong :: AST.Tint :: nil)\n                           AST.Tint cc_default).\nDefinition get_time_ef: AST.external_function :=\n  EF_external \"pals_current_time\"\n              (mksignature nil AST.Tlong cc_default).\nDefinition init_timer_ef: AST.external_function :=\n  EF_external \"pals_init_timer\"\n              (mksignature nil AST.Tint cc_default).\nDefinition wait_timer_ef: AST.external_function :=\n  EF_external \"pals_wait_timer\"\n              (mksignature (AST.Tlong :: nil)\n                           AST.Tint cc_default).\n\nDefinition os_efs: list AST.external_function :=\n  [open_socket_ef; bind_socket_ef; join_socket_ef;\n  sendto_ef; recvfrom_ef;\n  get_time_ef; init_timer_ef; wait_timer_ef ].\n  (* get_user_input_ef; check_demand_ef; *)\n  (* use_resource_ef; mark_complete_ef]. *)\n\n(**)\n\nDefinition check_os_ef (ef: AST.external_function) : bool :=\n  if find (fun ef' => Coqlib.proj_sumbool\n                     (AST.external_function_eq ef ef')) os_efs\n  then true else false.\n\n(* Definition check_tlim_ef (ef: AST.external_function): bool := *)\n(*   Coqlib.proj_sumbool (AST.external_function_eq ef). *)\n\nInductive ip_in_mem (ip: ip_t) (m: Mem.mem)\n          (blk: block) (ofs: ptrofs): Prop :=\n  IPInMem\n    (mvs: list memval) (ip_bytes: list byte)\n    (LOADBYTES: Mem.loadbytes m blk (Ptrofs.unsigned ofs)\n                              (Zlength ip_bytes + 1) = Some mvs)\n    (MEMDATA_BYTES: inj_bytes ip_bytes ++\n                              [Memdata.Byte Byte.zero] = mvs)\n    (CONVERT_FORMAT: IP.convert_brep ip_bytes = Some ip)\n.\n\n\n\nLemma loadbytes_until_zero_length_not_lt\n      z1 z2 bs1 bs2\n      m b ofs\n      (LB1: Mem.loadbytes m b ofs z1 =\n            Some (inj_bytes bs1 ++ [Byte Byte.zero]))\n      (LB2: Mem.loadbytes m b ofs z2 =\n            Some (inj_bytes bs2 ++ [Byte Byte.zero]))\n      (NZERO1: Forall (fun b => b <> Byte.zero) bs1)\n      (NZERO2: Forall (fun b => b <> Byte.zero) bs2)\n      (LT: (0 <= z1 < z2)%Z)\n  : False.\nProof.\n  assert (exists z', <<Z_POS': 0 < z'>> /\\\n                          <<Z'_DIFF: z1 + z' = z2>>)%Z.\n  { exists (z2 - z1)%Z.\n    splits; nia. }\n  destruct LT as [Z1_NNEG LT12]. des.\n  subst z2.\n  apply Mem.loadbytes_split in LB2; cycle 1.\n  { nia. }\n  { nia. }\n\n  destruct LB2 as (bytes1 & bytes2 & BYTES1 & BYTES2 & BS_EQ).\n  rewrite LB1 in BYTES1.\n\n  assert (INJ_BYTE_EX: forall b (IN1: In b bytes1),\n             In b (inj_bytes bs2)).\n  { assert (BYTES2_LEN_POS: 0 < length bytes2).\n    { apply Mem.loadbytes_length in BYTES2.\n      nia. }\n\n    hexploit (des_snoc _ bytes2); eauto. i. des.\n    subst bytes2.\n    unfold snoc in BS_EQ.\n    rewrite app_assoc in BS_EQ.\n\n    hexploit snoc_eq_inv.\n    { unfold snoc.\n      apply BS_EQ. }\n    intros (INJ_BS2_EQ & X_ZERO).\n    rewrite INJ_BS2_EQ.\n    apply in_or_app. left. eauto.\n  }\n\n  assert (BYTE_EX: forall b (IN1: In b bytes1),\n             exists b', In b' bs2 /\\ Byte b' = b).\n  { intros mb MB_IN.\n    hexploit INJ_BYTE_EX; eauto.\n    intro IN_INJ.\n    unfold inj_bytes in IN_INJ.\n    rewrite in_map_iff in IN_INJ. des.\n    esplits; eauto.\n  }\n\n  hexploit (BYTE_EX (Byte Byte.zero)).\n  { clarify.\n    apply in_or_app. right. ss. eauto. }\n  i. des.\n\n  rewrite Forall_forall in NZERO2.\n  hexploit NZERO2; eauto.\n  intro B. apply B. congruence.\nQed.\n\n\nLemma ip_in_mem_unique\n      m blk ofs ip1 ip2\n      (IP1: ip_in_mem ip1 m blk ofs)\n      (IP2: ip_in_mem ip2 m blk ofs)\n  : ip1 = ip2.\nProof.\n  inv IP1.\n  renames ip_bytes LOADBYTES CONVERT_FORMAT into\n          ip_bs1 LOAD1 CONV1.\n  inv IP2.\n  renames ip_bytes LOADBYTES CONVERT_FORMAT into\n          ip_bs2 LOAD2 CONV2.\n\n  hexploit IP.valid_ip_brep_spec; try apply CONV1.\n  intros (NZ1 & MAX1 & IP_RANGE1).\n  hexploit IP.valid_ip_brep_spec; try apply CONV2.\n  intros (NZ2 & MAX2 & IP_RANGE2).\n\n  assert (LEN_EQ: Zlength ip_bs1 = Zlength ip_bs2).\n  { destruct (Z_dec' (Zlength ip_bs1) (Zlength ip_bs2))\n      as [[A | B] | C].\n    - hexploit (loadbytes_until_zero_length_not_lt\n                  (Zlength ip_bs1 + 1) (Zlength ip_bs2 + 1)); eauto.\n      { splits.\n        - rewrite Zlength_correct. nia.\n        - nia. }\n      ss.\n    - hexploit (loadbytes_until_zero_length_not_lt\n                  (Zlength ip_bs2 + 1) (Zlength ip_bs1 + 1)); eauto.\n      { splits.\n        - rewrite Zlength_correct. nia.\n        - nia. }\n      ss.\n    - ss.\n  }\n\n  rewrite <- LEN_EQ in LOAD2.\n  rewrite LOAD2 in LOAD1.\n\n  assert (inj_bytes ip_bs1 = inj_bytes ip_bs2).\n  { inv LOAD1.\n    hexploit snoc_eq_inv; eauto. i. des. eauto. }\n\n  cut (proj_bytes (inj_bytes ip_bs1) =\n       proj_bytes (inj_bytes ip_bs2)).\n  { do 2 rewrite proj_inj_bytes.\n    i. congruence. }\n  congruence.\nQed.\n\n\nInductive cprog_os_ec (senv: Senv.t) (ef: external_function)\n  : list val -> Mem.mem -> forall {R}, osE R -> Prop :=\n(* socket *)\n| CProgOSEC_OpenSocket\n    args m\n    (EF: ef = open_socket_ef)\n    (ARGS: args = [])\n    (* (EC: ec = EventCall (subevent _ OSOpenSocket)) *)\n  : cprog_os_ec senv ef args m OSOpenSocket\n\n| CProgOSEC_BindSocket\n    args m\n    sid pn\n    (EF: ef = bind_socket_ef)\n    (RANGE_SID: IntRange.sint sid)\n    (RANGE_PN: IntRange.sint pn)\n    (ARGS: args = [Vint (IntNat.of_nat sid);\n                  Vint (IntNat.of_nat pn)])\n    (* (EC: ec = EventCall (subevent _ (OSBindSocket sid pn))) *)\n  : cprog_os_ec senv ef args m (OSBindSocket sid pn)\n\n| CProgOSEC_JoinSocket\n    args m\n    sid blk ofs ip_mcast\n    (EF: ef = join_socket_ef)\n    (RANGE_SID: IntRange.sint sid)\n    (ARGS: args = [Vint (IntNat.of_nat sid);\n                  Vptr blk ofs])\n    (IP_IN_MEM: ip_in_mem ip_mcast m blk ofs)\n    (* (EC: ec = EventCall (subevent _ )) *)\n  : cprog_os_ec senv ef args m (OSJoinSocket sid ip_mcast)\n\n| CProgOSEC_Sendto\n    args m\n    sid blk_buf ofs_buf sz_buf\n    blk_ip ofs_ip\n    bs ip_dest pn_dest\n    (EF: ef = sendto_ef)\n    (RANGE_SID: IntRange.sint sid)\n    (RANGE_BUF_SIZE: IntRange.sint sz_buf)\n    (RANGE_PN: IntRange.sint pn_dest)\n    (ARGS: args = [Vint (IntNat.of_nat sid);\n                  Vptr blk_ip ofs_ip;\n                  Vint (IntNat.of_nat pn_dest);\n                  Vptr blk_buf ofs_buf;\n                  Vint (IntNat.of_nat sz_buf)])\n    (BS_IN_MEM: Mem.loadbytes m blk_buf (Ptrofs.unsigned ofs_buf)\n                              (Z.of_nat sz_buf) =\n                Some (List.map Memdata.Byte bs))\n    (IP_IN_MEM: ip_in_mem ip_dest m blk_ip ofs_ip)\n    (* (EC: ec = EventCall (subevent _ (OSSendto sid bs ip_dest pn_dest))) *)\n  : cprog_os_ec senv ef args m\n                (OSSendto sid bs ip_dest pn_dest)\n\n| CProgOSEC_Recvfrom\n    args m\n    sid blk_buf ofs_buf sz_buf\n    (* (mvs: list memval) *)\n    (EF: ef = recvfrom_ef)\n    (RANGE_SID: IntRange.sint sid)\n    (RANGE_BUF_SIZE: IntRange.sint sz_buf)\n    (ARGS: args = [Vint (IntNat.of_nat sid);\n                  Vptr blk_buf ofs_buf;\n                  Vint (IntNat.of_nat sz_buf)])\n    (WRITABLE_PERM: Mem.range_perm\n                      m blk_buf (Ptrofs.unsigned ofs_buf)\n                      (Ptrofs.unsigned ofs_buf + Z.of_nat sz_buf)\n                      Cur Writable)\n    (* (BS_IN_MEM: Mem.loadbytes m blk_buf (Ptrofs.unsigned ofs_buf) *)\n    (*                           (Z.of_nat sz_buf) = *)\n    (*             Some mvs) *)\n    (* (EC: ec = EventCall (subevent _ (OSRecvfrom sid sz_buf))) *)\n  : cprog_os_ec senv ef args m (OSRecvfrom sid sz_buf)\n\n(* timer *)\n| CProgOSEC_GetTime\n    args m\n    (EF: ef = get_time_ef)\n    (ARGS: args = [])\n    (* (EC: ec = EventCall (subevent _ OSGetTime)) *)\n  : cprog_os_ec senv ef args m OSGetTime\n\n| CProgOSEC_InitTimer\n    args m\n    (EF: ef = init_timer_ef)\n    (ARGS: args = [])\n    (* (EC: ec = EventCall (subevent _ OSInitTimer)) *)\n  : cprog_os_ec senv ef args m OSInitTimer\n\n| CProgOSEC_WaitTimer\n    args m tm\n    (EF: ef = wait_timer_ef)\n    (RANGE_TM: IntRange.uint64 tm)\n    (ARGS: args = [Vlong (IntNat.of_nat64 tm)])\n    (* (EC: ec = EventCall (subevent _ (OSWaitTimer tm))) *)\n  : cprog_os_ec senv ef args m (OSWaitTimer tm)\n.\n\nInductive cprog_os_estep\n          (senv: Senv.t)\n  : forall {R}, osE R -> R ->\n         list val -> Mem.mem -> val -> mem -> Prop :=\n(* socket *)\n| CProgOSEStep_OpenSocket\n    (ret: Z) (args: list val) m retv\n    (* (EVT: evt = Event (subevent _ OSOpenSocket) ret) *)\n    (ARGS: args = [])\n    (RANGE_RET: IntRange.sintz ret)\n    (RET_VAL: retv = Vint (Int.repr ret))\n  : cprog_os_estep senv OSOpenSocket\n                   ret args m retv m\n\n| CProgOSEStep_BindSocket\n    (ret: Z) (args: list val) m retv\n    sid pn\n    (* (EVT: evt = Event (subevent _ (OSBindSocket sid pn)) ret) *)\n    (RET_VAL: retv = Vint (Int.repr ret))\n    (RANGE_RET: IntRange.sintz ret)\n  : cprog_os_estep senv (OSBindSocket sid pn) ret\n                   args m retv m\n\n| CProgOSEStep_JoinSocket\n    (ret: unit) (args: list val) m retv\n    sid ip_mcast\n    (* (EVT: evt = Event (subevent _ (OSJoinSocket sid ip_mcast)) ret) *)\n    (RET_VAL: retv = Vundef)\n  : cprog_os_estep senv (OSJoinSocket sid ip_mcast) ret\n                   args m retv m\n\n| CProgOSEStep_Sendto\n    (ret: Z) (args: list val) m retv\n    sid bs ip_d pn_d\n    (* (EVT: evt = Event (subevent _ (OSSendto sid bs ip_d pn_d)) ret) *)\n    (RET_VAL: retv = Vint (Int.repr ret))\n    (RANGE_RET: IntRange.sintz ret)\n  : cprog_os_estep senv (OSSendto sid bs ip_d pn_d) ret\n                   args m retv m\n\n| CProgOSEStep_Recvfrom\n    (ret: (bytes?)) retz\n    (args: list val) m retv m'\n    sid sz_buf\n    blk_buf ofs_buf\n    (* (EVT: evt = Event (subevent _ (OSRecvfrom sid sz_buf)) ret) *)\n    (ARGS: args = [Vint (IntNat.of_nat sid);\n                  Vptr blk_buf ofs_buf;\n                  Vint (IntNat.of_nat sz_buf)])\n    (RETZ: (ret = None /\\ m' = m /\\ retz = Z_mone) \\/\n           (exists bs, ret = Some bs /\\\n                  Mem.storebytes\n                    m blk_buf (Ptrofs.unsigned ofs_buf)\n                    (List.map Memdata.Byte bs) = Some m' /\\\n                  retz = Zlength bs /\\\n                  length bs <= sz_buf /\\\n                  length bs <= Packet.maxlen))\n    (RET_VAL: retv = Vint (Int.repr retz))\n  : cprog_os_estep senv (OSRecvfrom sid sz_buf) ret\n                   args m retv m'\n\n(* timer *)\n| CProgOSEStep_GetTime\n    (ret: Z) (args: list val) m retv\n    (* (EVT: evt = Event (subevent _ OSGetTime) ret) *)\n    (RET_VAL: retv = Vlong (Int64.repr ret))\n    (RANGE_RET: IntRange.uintz64 ret)\n  : cprog_os_estep senv OSGetTime ret\n                   args m retv m\n\n| CProgOSEStep_InitTimer\n    (ret: Z) (args: list val) m retv\n    (* (EVT: evt = Event (subevent _ OSInitTimer) ret) *)\n    (RET_VAL: retv = Vint (Int.repr ret))\n    (RANGE_RET: IntRange.sintz ret)\n  : cprog_os_estep senv OSInitTimer ret\n                   args m retv m\n\n| CProgOSEStep_WaitTimer\n    (ret: Z) (args: list val) m retv tm\n    (* (EVT: evt = Event (subevent _ (OSWaitTimer tm)) ret) *)\n    (RET_VAL: retv = Vint (Int.repr ret))\n    (RANGE_RET: IntRange.sintz ret)\n  : cprog_os_estep senv (OSWaitTimer tm) ret\n                    args m retv m\n\n.\n\n\nSection CPROG_SYS_EC.\n\n  Definition retty_of_extcallE {R} (ec: extcallE R): rettype :=\n    match ec with\n    | ExtcallEvent_Int _ _ => Tint\n    | ExtcallEvent_Void _ _ => Tvoid\n    end.\n\n  Inductive match_extcallE\n    : forall {R}, external_function -> list val -> extcallE R -> Type :=\n  | MatchExtcallE\n      fname sig args\n      (RET_INT: sig_res sig = Tint)\n    : match_extcallE (EF_external fname sig) args\n                     (ExtcallEvent_Int fname args)\n  | MatchExtcallE_Void\n      fname sig args\n      (RET_VOID: sig_res sig = Tvoid)\n    : match_extcallE (EF_external fname sig) args\n                     (ExtcallEvent_Void fname args)\n  .\n\n  Section CPROG_EVENT_SEM.\n    (* Context `{CProgSysEvent}. *)\n\n    (* Match C program states with event calls *)\n    Inductive cprog_ec\n              (senv: Senv.t) (ef: external_function)\n      : list val -> Mem.mem -> event_call (osE +' obsE) -> Prop :=\n    | CProgEC_OS\n        R (ose: osE R) ec\n        args m\n        (OS_EC: cprog_os_ec senv ef args m ose)\n        (EVENT_CALL: ec = EventCall (subevent _ ose))\n      : cprog_ec senv ef args m ec\n\n    (* | CProgEC_TimeLimit *)\n    (*     args m ec tm *)\n    (*     (EF: ef = time_limit_ef) *)\n    (*     (RANGE_TM: IntRange.uint64 tm) *)\n    (*     (ARGS: args = [Vlong (IntNat.of_nat64 tm)]) *)\n    (*     (EVENT_CALL: ec = EventCall (subevent _ (TimeLimitEvent tm))) *)\n    (*   : cprog_ec senv ef args m ec *)\n\n    | CProgEC_SystemEvent\n        R args m ec (exte: extcallE R)\n        (* (ret: R) *)\n        (* fname sig *)\n        (* (EXTFUN_EXTERNAL: ef = EF_external fname sig) *)\n        (* (SYS_EC: cprog_sys_ec senv ef args m syse) *)\n        (NOT_OS_CALL: forall R (ose: osE R), ~ cprog_os_ec senv ef args m ose)\n        (* (NOT_SET_TLIM: ef <> time_limit_ef) *)\n        (EVENT_CALL: ec = EventCall (subevent _ exte))\n        (MATCH_EXTC: match_extcallE ef args exte)\n      : cprog_ec senv ef args m ec\n    .\n\n    Inductive match_ext_retv: rettype -> forall {R}, R -> val -> Prop :=\n    | MatchExtRetv_Int\n        (n: int)\n      : match_ext_retv Tint n (Vint n)\n    | MatchExtRetv_Void\n      : match_ext_retv Tvoid tt Vundef\n    .\n\n    (* system's cprog_match_after_event *)\n    Inductive cprog_estep\n              (senv: Senv.t)\n              (evt: event (osE +' obsE)):\n      list val -> Mem.mem -> val -> mem -> Prop :=\n    (* socket *)\n    | CProgEStep_OS\n        R (ose: osE R) ret\n        args m retv m'\n        (OS_ESTEP: cprog_os_estep senv ose ret\n                                  args m retv m')\n        (EVENT: evt = Event (subevent _ ose) ret)\n      : cprog_estep senv evt args m retv m'\n\n    (* | CProgEStep_TimeLimit *)\n    (*     (args: list val) m retv tm *)\n    (*     (RET_VAL: retv = Vundef) *)\n    (*     (EVENT: evt = Event (subevent _ (TimeLimitEvent tm)) tt) *)\n    (*   : cprog_estep senv evt args m retv m *)\n\n    | CProgEStep_SystemEvent\n        R (exte: extcallE R) (ret: R) (retv: val)\n        (args: list val) m\n        (EVENT: evt = Event (subevent _ exte) ret)\n        (MATCH_RETV: match_ext_retv (retty_of_extcallE exte) ret retv)\n      : cprog_estep senv evt args m retv m\n    .\n\n    Program Instance cprog_event_instance\n      : @cprog_event (osE +' obsE) :=\n      {| cprog_event_call := cprog_ec ;\n         cprog_event_step := cprog_estep ;\n      |}.\n    Next Obligation.\n      inv AT_EVT1; inv AT_EVT2; ss.\n      - inv OS_EC; inv OS_EC0; existT_elim1; ss.\n        + list_eq_inv_tac.\n          repeat f_equal.\n          * apply IntNat_of_nat_eq_inv_sint; eauto.\n            congruence.\n          * apply IntNat_of_nat_eq_inv_sint; eauto.\n            congruence.\n        + list_eq_inv_tac.\n          repeat f_equal.\n          * apply IntNat_of_nat_eq_inv_sint; eauto.\n            congruence.\n          * inv ARGS1.\n            eapply ip_in_mem_unique; eauto.\n        + list_eq_inv_tac.\n          repeat match goal with\n                 | H: Vptr _ _ = Vptr _ _ |- _ => inv H\n                 end.\n          assert (sz_buf0 = sz_buf).\n          { apply IntNat_of_nat_eq_inv_sint; eauto.\n            congruence. }\n          assert (sid0 = sid).\n          { apply IntNat_of_nat_eq_inv_sint; eauto.\n            congruence. }\n          assert (pn_dest0 = pn_dest).\n          { apply IntNat_of_nat_eq_inv_sint; eauto.\n            congruence. }\n          clarify.\n          repeat f_equal.\n          * apply map_Byte_eq_inv; eauto.\n          * eapply ip_in_mem_unique; eauto.\n        + list_eq_inv_tac.\n          repeat match goal with\n                 | H: Vptr _ _ = Vptr _ _ |- _ => inv H\n                 end.\n          assert (sz_buf0 = sz_buf).\n          { apply IntNat_of_nat_eq_inv_sint; eauto.\n            congruence. }\n          assert (sid0 = sid).\n          { apply IntNat_of_nat_eq_inv_sint; eauto.\n            congruence. }\n          clarify.\n        + list_eq_inv_tac.\n          repeat f_equal.\n          eapply IntNat_of_nat64_eq_inv_uint; eauto.\n          congruence.\n      (* - inv OS_EC; ss. *)\n      - exfalso.\n        hexploit NOT_OS_CALL; eauto.\n      (* - inv OS_EC; ss. *)\n      (* - list_eq_inv_tac. *)\n      (*   repeat f_equal. *)\n      (*   eapply IntNat_of_nat64_eq_inv_uint; eauto. *)\n      (*   congruence. *)\n      - exfalso.\n        hexploit NOT_OS_CALL; eauto.\n      - inv MATCH_EXTC; inv MATCH_EXTC0; ss.\n        + congruence.\n        + congruence.\n    Qed.\n\n  End CPROG_EVENT_SEM.\nEnd CPROG_SYS_EC.\n", "meta": {"author": "kim-yoonseung", "repo": "pals-thesis-dev", "sha": "1a165028f5461ed4d00a1e2720b3b1e4542f5dc2", "save_path": "github-repos/coq/kim-yoonseung-pals-thesis-dev", "path": "github-repos/coq/kim-yoonseung-pals-thesis-dev/pals-thesis-dev-1a165028f5461ed4d00a1e2720b3b1e4542f5dc2/src/core/CProgEventSem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.22299192792404815}}
{"text": "From cap_machine Require Export logrel.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.program_logic Require Import weakestpre adequacy lifting.\nFrom stdpp Require Import base.\nFrom cap_machine.ftlr Require Import ftlr_base interp_weakening.\nFrom cap_machine Require Import addr_reg region.\nFrom cap_machine.rules Require Import rules_base rules_Subseg.\n\nSection fundamental.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ} {sealsg: sealStoreG Σ}\n          {nainv: logrel_na_invs Σ}\n          `{MachineParameters}.\n\n  Notation D := ((leibnizO Word) -n> iPropO Σ).\n  Notation R := ((leibnizO Reg) -n> iPropO Σ).\n  Implicit Types w : (leibnizO Word).\n  Implicit Types interp : (D).\n\n  Lemma within_in_range:\n    forall a b b' e e',\n      (b <= b')%a ->\n      (e' <= e)%a ->\n      in_range a b' e' ->\n      in_range a b e.\n  Proof.\n    intros * ? ? [? ?]. split; solve_addr.\n  Qed.\n\n  Lemma subseg_interp_preserved p b b' e e' a :\n      p <> E ->\n\n      (b <= b')%a ->\n      (e' <= e)%a ->\n      (□ ▷ (∀ a0 a1 a2 a3 a4,\n             full_map a0\n          -∗ (∀ (r1 : RegName) v, ⌜r1 ≠ PC⌝ → ⌜a0 !! r1 = Some v⌝ → (fixpoint interp1) v)\n          -∗ registers_mapsto (<[PC:=WCap a1 a2 a3 a4]> a0)\n          -∗ na_own logrel_nais ⊤\n          -∗ □ (fixpoint interp1) (WCap a1 a2 a3 a4) -∗ interp_conf)) -∗\n      (fixpoint interp1) (WCap p b e a) -∗\n      (fixpoint interp1) (WCap p b' e' a).\n  Proof.\n    intros Hne Hb He. iIntros \"#IH Hinterp\".\n    iApply (interp_weakening with \"IH Hinterp\"); eauto.\n    destruct p; reflexivity.\n  Qed.\n\n  Lemma subseg_case (r : leibnizO Reg) (p : Perm)\n        (b e a : Addr) (w : Word) (dst : RegName) (r1 r2 : Z + RegName) (P:D):\n    ftlr_instr r p b e a w (Subseg dst r1 r2) P.\n  Proof.\n    intros Hp Hsome i Hbae Hi.\n    iIntros \"#IH #Hinv #Hinva #Hreg #[Hread Hwrite] Hown Ha HP Hcls HPC Hmap\".\n    rewrite delete_insert_delete.\n    iDestruct ((big_sepM_delete _ _ PC) with \"[HPC Hmap]\") as \"Hmap /=\";\n      [apply lookup_insert|rewrite delete_insert_delete;iFrame|]. simpl.\n    iApply (wp_Subseg with \"[$Ha $Hmap]\"); eauto.\n    { simplify_map_eq; auto. }\n    { rewrite /subseteq /map_subseteq /set_subseteq_instance. intros rr _.\n      apply elem_of_dom. apply lookup_insert_is_Some'; eauto. }\n\n\n    iIntros \"!>\" (regs' retv). iDestruct 1 as (HSpec) \"[Ha Hmap]\".\n    destruct HSpec as [ * Hdst ? Hao1 Hao2 Hwi HincrPC | * Hdst Hoo1 Hoo2 Hwi HincrPC | ].\n    { apply incrementPC_Some_inv in HincrPC as (p''&b''&e''&a''& ? & HPC & Z & Hregs') .\n\n      assert (a'' = a ∧ p'' = p) as (-> & ->).\n      { destruct (decide (PC = dst)); simplify_map_eq; auto. }\n\n      iApply wp_pure_step_later; auto.\n      iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro].\n      iNext ; iIntros \"_\".\n      iApply (\"IH\" $! regs' with \"[%] [] [Hmap] [$Hown]\").\n      { cbn. intros. subst regs'. by repeat (apply lookup_insert_is_Some'; right). }\n      { iIntros (ri v Hri Hvs).\n        subst regs'.\n        rewrite lookup_insert_ne in Hvs; auto.\n        destruct (decide (ri = dst)).\n        { subst ri.\n          rewrite lookup_insert_ne in Hdst; auto.\n          rewrite lookup_insert in Hvs; inversion Hvs. simplify_eq.\n          unshelve iSpecialize (\"Hreg\" $! dst _ _ Hdst); eauto.\n          rewrite /isWithin in Hwi.\n          iApply (interp_weakening with \"IH Hreg\"); auto; try solve_addr.\n          by rewrite PermFlowsToReflexive. }\n        { repeat (rewrite lookup_insert_ne in Hvs); auto.\n          iApply \"Hreg\"; auto. } }\n        { subst regs'. rewrite insert_insert. iApply \"Hmap\". }\n      iModIntro.\n      iApply (interp_weakening with \"IH Hinv\"); auto; try solve_addr.\n      { destruct Hp; by subst p. }\n      { destruct (reg_eq_dec PC dst) as [Heq | Hne]; simplify_map_eq.\n        1,2: rewrite /isWithin in Hwi; solve_addr. }\n      { destruct (reg_eq_dec PC dst) as [Heq | Hne]; simplify_map_eq.\n        1,2: rewrite /isWithin in Hwi; solve_addr. }\n      { by rewrite PermFlowsToReflexive. }\n    }\n    { apply incrementPC_Some_inv in HincrPC as (p''&b''&e''&a''& ? & HPC & Z & Hregs') .\n      assert (dst ≠ PC) as Hne.\n      { destruct (decide (PC = dst)); last auto. simplify_map_eq; auto. }\n\n      assert (p'' = p ∧ b'' = b ∧ e'' = e ∧ a'' = a) as (-> & -> & -> & ->).\n      { simplify_map_eq; auto. }\n\n      iApply wp_pure_step_later; auto.\n      iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro].\n      iNext ; iIntros \"_\".\n      iApply (\"IH\" $! regs' with \"[%] [] [Hmap] [$Hown]\").\n      { cbn. intros. subst regs'. by repeat (apply lookup_insert_is_Some'; right). }\n      { iIntros (ri v Hri Hvs).\n        subst regs'.\n        rewrite lookup_insert_ne in Hvs; auto.\n        destruct (decide (ri = dst)).\n        { subst ri.\n          rewrite lookup_insert_ne in Hdst; auto.\n          rewrite lookup_insert in Hvs; inversion Hvs. simplify_eq.\n          unshelve iSpecialize (\"Hreg\" $! dst _ _ Hdst); eauto.\n          rewrite /isWithin in Hwi.\n          iApply (interp_weakening_ot with \"Hreg\"); auto; try solve_addr.\n          by rewrite SealPermFlowsToReflexive. }\n        { repeat (rewrite lookup_insert_ne in Hvs); auto.\n          iApply \"Hreg\"; auto. } }\n        { subst regs'. rewrite insert_insert. iApply \"Hmap\". }\n      iModIntro.\n      iApply (interp_weakening with \"IH Hinv\"); auto; try solve_addr.\n      { destruct Hp; by subst p. }\n      { by rewrite PermFlowsToReflexive. }\n    }\n    { iApply wp_pure_step_later; auto.\n    iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro].\n    iNext ; iIntros \"_\".\n    iApply wp_value; auto. iIntros; discriminate. }\nQed.\n\nEnd fundamental.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/ftlr/Subseg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22294177633306522}}
{"text": "Require Import Kami.AllNotations.\n\nClass Params :=\n  { name : string;\n    size : nat;\n    inReqK : Kind;\n    vAddrSz : nat;\n    compInstSz : nat;\n    immResK : Kind;\n    finalErrK : Kind;\n    isCompressed: forall ty, Bit compInstSz @# ty -> Bool @# ty;\n    isImmErr: forall ty, immResK @# ty -> Bool @# ty;\n    isFinalErr: forall ty, finalErrK @# ty -> Bool @# ty;\n  }.\n\nSection Ifc.\n  Context {params: Params}.\n\n  Definition VAddr    := Bit vAddrSz.\n  Definition CompInst := Bit compInstSz.\n  Definition InstSz   := compInstSz + compInstSz.\n  Definition Inst     := Bit InstSz.\n\n  Definition OutReq := STRUCT_TYPE { \"inReq\" :: inReqK;\n                                     \"vaddr\" :: VAddr }.\n\n  Definition InRes\n    := STRUCT_TYPE {\n         \"vaddr\"  :: VAddr;\n         \"immRes\" :: immResK;\n         \"error\"  :: finalErrK;\n         \"inst\"   :: Inst\n       }.\n\n  (* if inst contains a compressed instruction the upper 16 bit contain arbitrary data. *)\n  Definition OutRes\n    := STRUCT_TYPE {\n         \"notComplete?\" :: Bool;\n         \"vaddr\"        :: VAddr;\n         \"immRes\"       :: immResK;\n         \"error\"        :: finalErrK;\n         \"compressed?\"  :: Bool;\n         \"errUpper?\"    :: Bool;\n         \"inst\"         :: Inst \n       }.\n\n  Record Ifc: Type :=\n    {\n      regs: list RegInitT;\n      regFiles : list RegFileBase;\n\n      isFull: forall {ty}, ActionT ty Bool;\n      sendAddr (sendReq: forall ty, ty OutReq -> ActionT ty Bool) ty: ty OutReq -> ActionT ty Bool;\n      callback: forall {ty}, ty InRes -> ActionT ty Void;\n      deq: forall {ty}, ActionT ty Bool;\n      first: forall {ty}, ActionT ty (Maybe OutRes);\n\n      canClear: forall {ty}, ActionT ty Bool;\n      clear: forall {ty}, ActionT ty Void;\n\n      notCompleteDeqRule: forall {ty}, ActionT ty Void;\n      transferRule: forall {ty}, ActionT ty Void;\n    }.\nEnd Ifc.\n", "meta": {"author": "sifive", "repo": "StdLibKami", "sha": "01d3dffcec9d8bfc4f864b940974396ffe817314", "save_path": "github-repos/coq/sifive-StdLibKami", "path": "github-repos/coq/sifive-StdLibKami/StdLibKami-01d3dffcec9d8bfc4f864b940974396ffe817314/Fetcher/Ifc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2229417706679483}}
{"text": "Require Import Coq.Strings.Ascii\n        Coq.Bool.Bool\n        Coq.Lists.List\n        Coq.Structures.OrderedType.\n\nRequire Import\n        Fiat.BinEncoders.Env.BinLib.Core\n        Fiat.BinEncoders.Env.Common.Specs\n        Fiat.BinEncoders.Env.Common.Compose\n        Fiat.BinEncoders.Env.Common.ComposeOpt\n        Fiat.BinEncoders.Env.Automation.Solver\n        Fiat.BinEncoders.Env.Lib2.WordOpt\n        Fiat.BinEncoders.Env.Lib2.NatOpt\n        Fiat.BinEncoders.Env.Lib2.StringOpt\n        Fiat.BinEncoders.Env.Lib2.EnumOpt\n        Fiat.BinEncoders.Env.Lib2.FixListOpt\n        Fiat.BinEncoders.Env.Lib2.SumTypeOpt.\n\nRequire Import\n        Fiat.Common.SumType\n        Fiat.Examples.Tutorial.Tutorial\n        Fiat.Examples.DnsServer.DecomposeEnumField\n        Fiat.QueryStructure.Automation.AutoDB\n        Fiat.QueryStructure.Implementation.DataStructures.BagADT.BagADT\n        Fiat.QueryStructure.Automation.IndexSelection\n        Fiat.QueryStructure.Specification.SearchTerms.ListPrefix\n        Fiat.QueryStructure.Automation.SearchTerms.FindPrefixSearchTerms\n        Fiat.QueryStructure.Automation.MasterPlan\n        Fiat.Examples.HACMSDemo.DuplicateFree\n        Fiat.Examples.HACMSDemo.HACMSDemo\n        Fiat.Examples.HACMSDemo.WheelSensor.\n\n(* We first synthesize an implementation of our encoder. *)\nLemma Sharpened_encode_SensorData_Impl\n  : { encode_SensorData_Impl : _ &\n      forall ce (val : SensorType),\n        refine (encode_SensorData_Spec val ce)\n               (ret (encode_SensorData_Impl val ce))}.\nProof.\n  eexists; intros; set_evars.\n  unfold encode_SensorData_Spec.\n  unfold compose, Bind2.\n  setoid_rewrite refine_encode_enum; simplify with monad laws.\n  setoid_rewrite (@refine_encode_SumType\n          bin\n          _\n          2\n          ([nat : Type; nat : Type])\n          _\n          (icons _\n                 (icons _ (inil (A := Type))))).\n  simplify with monad laws.\n  simpl; rewrite app_nil_r.\n  finish honing.\n  simpl; f_equiv.\n  simpl; repeat apply Build_prim_and; eauto;\n    intros; rewrite refine_encode_nat; finish honing.\nDefined.\n\n(* Extract the synthesized encoder. *)\nDefinition encode_SensorData_Impl :=\n  Eval simpl in projT1 Sharpened_encode_SensorData_Impl.\n\n(* Extract its proof of correctness for good measure. *)\nLemma refine_encode_SensorData_Impl\n  : forall ce (val : SensorType),\n        refine (encode_SensorData_Spec val ce)\n               (ret (encode_SensorData_Impl val ce)).\nProof.\n  exact (projT2 Sharpened_encode_SensorData_Impl).\nQed.\n\nOpaque encode_SensorData_Spec.\n\nTheorem SharpenedWheelSensor :\n    FullySharpened WheelSensorSpec.\nProof.\n  start sharpening ADT.\n  start_honing_QueryStructure'.\n  (* We first insert checks for the DuplicateFree constraints.  *)\n  hone method \"AddSpeedSubscriber\". { dropDuplicateFree. }\n  hone method \"AddTirePressureSubscriber\". { dropDuplicateFree. }\n  (* Break down the suscribers 'table' into one for each topic.  *)\n  decompose_EnumField \"subscribers\" \"topic\".\n  (* Select the kinds of searches each 'table' should support. *)\n  chooseIndexes.\n  (* Implement each method using the chosen search operations. *)\n  initializer.\n  insertOne.\n  insertOne.\n  rewrite refine_encode_SensorData_Impl; planOne.\n  rewrite refine_encode_SensorData_Impl; planOne.\n  (* Cleanup the synthesized methods. *)\n  final_optimizations.\n  (* Ensure the implementation is executable. *)\n  determinize.\n  (* Select concrete data structures for each table.  *)\n  choose_data_structures.\n  (* Some final cleanup. *)\n  final_simplification.\n  (* And we're done! *)\n  use_this_one.\nDefined.\n\n(* We can now extract the implementation derived above. *)\nDefinition WheelSensorImpl := Eval simpl in projT1 SharpenedWheelSensor.\nPrint WheelSensorImpl.\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/Examples/HACMSDemo/WheelSensorEncoder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2229417650028313}}
{"text": "(*\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\nRequire Import String.\nRequire Import List.\nRequire Import Compare_dec.\nRequire Import Equivalence.\nRequire Import Morphisms.\nRequire Import Setoid.\nRequire Import EquivDec.\nRequire Import Program.\nRequire Import Utils.\nRequire Import DataRuntime.\nRequire Import NNRSimp.\nRequire Import NNRSimpNorm.\nRequire Import NNRSimpEval.\n\n\nSection NNRSimpEq.\n  (* Equivalence for nnrs_imp *)\n\n  Local Open Scope nnrs_imp_scope.\n\n  Context {fruntime:foreign_runtime}.\n\n  Definition nnrs_imp_expr_eq (e₁ e₂:nnrs_imp_expr) : Prop :=\n    forall (h:list(string*string))\n           (σc:list (string*data))\n           (dn_σc: Forall (data_normalized h) (map snd σc))\n           (σ:pd_bindings)\n           (dn_σ: forall d, In (Some d) (map snd σ) -> data_normalized h d),\n      nnrs_imp_expr_eval h σc σ e₁ = nnrs_imp_expr_eval h σc σ e₂.\n\n  Definition nnrs_imp_stmt_eq (s₁ s₂:nnrs_imp_stmt) : Prop :=\n    forall (h:list(string*string))\n           (σc:list (string*data))\n           (dn_σc: Forall (data_normalized h) (map snd σc))\n           (σ:pd_bindings)\n           (dn_σ: forall d, In (Some d) (map snd σ) -> data_normalized h d),\n      nnrs_imp_stmt_eval h σc s₁ σ = nnrs_imp_stmt_eval h σc s₂ σ.\n  \n  Definition nnrs_imp_eq (si₁ si₂:nnrs_imp) : Prop :=\n    forall (h:list(string*string))\n           (σc:list (string*data))\n           (dn_σc: Forall (data_normalized h) (map snd σc)),\n      nnrs_imp_eval h σc si₁ = nnrs_imp_eval h σc si₂.\n\n  Global Instance nnrs_imp_expr_equiv : Equivalence nnrs_imp_expr_eq.\n  Proof.\n    unfold nnrs_imp_expr_eq. \n    constructor; red; intros.\n    - reflexivity.\n    - symmetry; eauto.\n    - rewrite H; eauto. \n  Qed.\n\n  Global Instance nnrs_imp_stmt_equiv : Equivalence nnrs_imp_stmt_eq.\n  Proof.\n    unfold nnrs_imp_stmt_eq. \n    constructor; red; intros.\n    - reflexivity.\n    - symmetry; eauto.\n    - rewrite H; eauto. \n  Qed.\n\n  Global Instance nnrs_imp_equiv : Equivalence nnrs_imp_eq.\n  Proof.\n    unfold nnrs_imp_eq. \n    constructor; red; intros.\n    - reflexivity.\n    - symmetry; eauto.\n    - rewrite H; eauto. \n  Qed.\n\n  Section proper.\n\n    Global Instance NNRSimpGetConstant_proper v :\n      Proper nnrs_imp_expr_eq (NNRSimpGetConstant v).\n    Proof.\n      unfold Proper, respectful, nnrs_imp_expr_eq; trivial.\n    Qed.\n\n    Global Instance NNRSimpVar_proper v :\n      Proper nnrs_imp_expr_eq (NNRSimpVar v).\n    Proof.\n      unfold Proper, respectful, nnrs_imp_expr_eq; trivial.\n    Qed.\n\n    Global Instance NNRSimpConst_proper d :\n      Proper nnrs_imp_expr_eq (NNRSimpConst d).\n    Proof.\n      unfold Proper, respectful, nnrs_imp_expr_eq; trivial.\n    Qed.\n\n    Global Instance NNRSimpBinop_proper :\n      Proper (binary_op_eq ==> nnrs_imp_expr_eq ==> nnrs_imp_expr_eq ==> nnrs_imp_expr_eq) NNRSimpBinop.\n    Proof.\n      unfold Proper, respectful, nnrs_imp_expr_eq; intros; simpl.\n      rewrite H0, H1 by trivial.\n      apply olift2_ext; intros.\n      apply H\n      ; eapply nnrs_imp_expr_eval_normalized; eauto.\n    Qed.\n\n    Global Instance NNRSimpUnop_proper :\n      Proper (unary_op_eq ==> nnrs_imp_expr_eq ==> nnrs_imp_expr_eq) NNRSimpUnop.\n    Proof.\n      unfold Proper, respectful, nnrs_imp_expr_eq; intros; simpl.\n      rewrite H0 by trivial.\n      apply olift_ext; intros.\n      apply H\n      ; eapply nnrs_imp_expr_eval_normalized; eauto.\n    Qed.\n\n    Global Instance NNRSimpGroupBy_proper s ls :\n      Proper (nnrs_imp_expr_eq ==> nnrs_imp_expr_eq) (NNRSimpGroupBy s ls).\n    Proof.\n      unfold Proper, respectful, nnrs_imp_expr_eq; intros; simpl.\n      rewrite H; trivial.\n    Qed.\n\n    Global Instance NNRSimpSeq_proper :\n      Proper (nnrs_imp_stmt_eq ==> nnrs_imp_stmt_eq ==> nnrs_imp_stmt_eq) NNRSimpSeq.\n    Proof.\n      unfold Proper, respectful, nnrs_imp_stmt_eq; intros; simpl.\n      rewrite H by trivial.\n      apply olift_ext; intros.\n      apply H0; trivial.\n      eapply nnrs_imp_stmt_eval_normalized; eauto.\n    Qed.\n\n    Global Instance NNRSimpAssign_proper v :\n      Proper (nnrs_imp_expr_eq ==> nnrs_imp_stmt_eq) (NNRSimpAssign v).\n    Proof.\n      unfold Proper, respectful, nnrs_imp_stmt_eq; intros; simpl.\n      rewrite H; trivial.\n    Qed.\n\n    Global Instance NNRSimpLet_proper v :\n      Proper (lift2P nnrs_imp_expr_eq ==> nnrs_imp_stmt_eq ==> nnrs_imp_stmt_eq) (NNRSimpLet v).\n    Proof.\n      unfold Proper, respectful, nnrs_imp_stmt_eq; intros; simpl.\n      unfold lift2P in H.\n      destruct x; destruct y; try contradiction; trivial.\n      - rewrite H; eauto 2.\n        apply olift_ext; simpl; intros ? eqq.\n        rewrite H0; trivial; simpl.\n        apply some_lift in eqq.\n        destruct eqq as [???]; subst.\n        intuition.\n        invcs H2; qeauto.\n      - rewrite H0; trivial; simpl.\n        intuition; try discriminate.\n    Qed.\n\n    Global Instance NNRSimpLet_none_proper v :\n      Proper (nnrs_imp_stmt_eq ==> nnrs_imp_stmt_eq) (NNRSimpLet v None).\n    Proof.\n      apply NNRSimpLet_proper.\n      simpl; trivial.\n    Qed.\n\n    Global Instance NNRSimpFor_proper v :\n      Proper (nnrs_imp_expr_eq ==> nnrs_imp_stmt_eq ==> nnrs_imp_stmt_eq) (NNRSimpFor v).\n    Proof.\n      unfold Proper, respectful, nnrs_imp_stmt_eq; intros; simpl.\n      rewrite H; eauto 2.\n      apply olift_ext; simpl; intros ? eqq.\n      destruct a; trivial.\n      eapply nnrs_imp_expr_eval_normalized in eqq; eauto.\n      invcs eqq.\n      revert σ dn_σ.\n      induction l; simpl; trivial; intros σ dn_σ.\n      invcs H2.\n      rewrite H0; simpl; trivial.\n      - repeat (match_case; intros); subst.\n        apply IHl; trivial; intros.\n        eapply nnrs_imp_stmt_eval_normalized; eauto; simpl\n        ; intuition.\n        invcs H7; trivial.\n      - intuition.\n        invcs H3; trivial.\n    Qed.\n\n    Global Instance NNRSimpIf_proper :\n      Proper (nnrs_imp_expr_eq ==> nnrs_imp_stmt_eq ==> nnrs_imp_stmt_eq ==> nnrs_imp_stmt_eq) NNRSimpIf.\n    Proof.\n      unfold Proper, respectful, nnrs_imp_stmt_eq; intros; simpl.\n      rewrite H; eauto 2.\n      match_case; intros ? eqq.\n      destruct d; trivial.\n      destruct b; eauto.\n    Qed.\n\n    Global Instance NNRSimpEither_proper :\n      Proper (nnrs_imp_expr_eq ==> eq ==> nnrs_imp_stmt_eq ==> eq ==> nnrs_imp_stmt_eq ==> nnrs_imp_stmt_eq) NNRSimpEither.\n    Proof.\n      unfold Proper, respectful, nnrs_imp_stmt_eq; intros; simpl.\n      subst.\n      rewrite H; eauto 2.\n      match_case; intros ? eqq.\n      eapply nnrs_imp_expr_eval_normalized in eqq; eauto.\n      destruct d; trivial\n      ; invcs eqq.\n      - rewrite H1; eauto; simpl; intuition\n        ; invcs H4; eauto.\n      - rewrite H3; eauto; simpl; intuition\n        ; invcs H4; eauto.\n    Qed.      \n\n    Lemma NNRSImp_proper {s₁ s₂} : nnrs_imp_stmt_eq s₁ s₂ ->\n                                   forall v, nnrs_imp_eq (s₁, v) (s₂, v).\n    Proof.\n      unfold nnrs_imp_eq; intros eqq v; intros; simpl.\n      rewrite eqq; trivial.\n      simpl; intuition congruence.\n    Qed.\n    \n  End proper.\n  \nEnd NNRSimpEq.\n\nNotation \"X ≡ᵉ Y\" := (nnrs_imp_expr_eq X Y) (at level 90) : nnrs_imp_scope. (* ≡ = \\equiv *)\n\nNotation \"X ≡ˢ Y\" := (nnrs_imp_stmt_eq X Y) (at level 90) : nnrs_imp_scope. (* ≡ = \\equiv *)\n\nNotation \"X ≡ˢⁱ Y\" := (nnrs_imp_eq X Y) (at level 90) : nnrs_imp_scope. (* ≡ = \\equiv *)\n\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/NNRSimp/Lang/NNRSimpEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.22279367514197138}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Bool.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import ZArith NArith Nnat Ndec Ndigits.\nFrom IntMap Require Import Map.\nFrom IntMap Require Import Allmaps.\nRequire Import List.\nRequire Import Wf_nat.\n\nRequire Import misc.\nRequire Import bool_fun.\nRequire Import myMap.\nRequire Import config.\nRequire Import alloc.\nRequire Import make.\n\nSection BDD_neg.\n\nVariable gc : BDDconfig -> list ad -> BDDconfig.\nHypothesis gc_is_OK : gc_OK gc.\n\nFixpoint BDDneg_1 (cfg : BDDconfig) (ul : list ad) \n (node : ad) (bound : nat) {struct bound} : BDDconfig * ad :=\n  match bound with\n  | O => (* Error *)  (initBDDconfig, BDDzero)\n  | S bound' =>\n      match MapGet _ (negm_of_cfg cfg) node with\n      | Some node' => (cfg, node')\n      | None =>\n          match MapGet _ (fst cfg) node with\n          | None =>\n              if Neqb node BDDzero\n              then (BDDneg_memo_put cfg BDDzero BDDone, BDDone)\n              else (BDDneg_memo_put cfg BDDone BDDzero, BDDzero)\n          | Some (x, (l, r)) =>\n              match BDDneg_1 cfg ul l bound' with\n              | (cfgl, nodel) =>\n                  match BDDneg_1 cfgl (nodel :: ul) r bound' with\n                  | (cfgr, noder) =>\n                      match\n                        BDDmake gc cfgr x nodel noder (noder :: nodel :: ul)\n                      with\n                      | (cfg', node') =>\n                          (BDDneg_memo_put cfg' node node', node')\n                      end\n                  end\n              end\n          end\n      end\n  end.\n  \nLemma BDDneg_1_lemma :\n forall (bound : nat) (cfg : BDDconfig) (ul : list ad) (node : ad),\n nat_of_N (node_height cfg node) < bound ->\n BDDconfig_OK cfg ->\n used_list_OK cfg ul ->\n used_node' cfg ul node ->\n BDDconfig_OK (fst (BDDneg_1 cfg ul node bound)) /\\\n config_node_OK (fst (BDDneg_1 cfg ul node bound))\n   (snd (BDDneg_1 cfg ul node bound)) /\\\n used_nodes_preserved cfg (fst (BDDneg_1 cfg ul node bound)) ul /\\\n Neqb\n   (node_height (fst (BDDneg_1 cfg ul node bound))\n      (snd (BDDneg_1 cfg ul node bound))) (node_height cfg node) = true /\\\n bool_fun_eq\n   (bool_fun_of_BDD (fst (BDDneg_1 cfg ul node bound))\n      (snd (BDDneg_1 cfg ul node bound)))\n   (bool_fun_neg (bool_fun_of_BDD cfg node)).\nProof.\n  simple induction bound.  intros.  absurd (nat_of_N (node_height cfg node) < 0).\n  apply lt_n_O.  assumption.  simpl in |- *.  intros.\n  elim (option_sum _ (MapGet _ (negm_of_cfg cfg) node)).  intro y.\n  elim y; clear y; intros node' H4.  rewrite H4.  simpl in |- *.\n  elim (negm_of_cfg_OK _ H1 node node' H4).  intros.  split.  assumption.\n  split.  inversion H6.  inversion H8.  assumption.  split.\n  apply used_nodes_preserved_refl.  split.  exact (proj1 (proj2 H6)).\n  exact (proj2 (proj2 H6)).  intro y.  rewrite y.\n  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) (fst cfg) node)).  intro y0.\n  elim y0; clear y0.\n  intro x; elim x; clear x; intros x x0; elim x0; clear x0; intros l r H4.\n  rewrite H4.  elim (prod_sum _ _ (BDDneg_1 cfg ul l n)).  intros cfgl H5.\n  elim H5; clear H5.  intros nodel H5.  rewrite H5.\n  elim (prod_sum _ _ (BDDneg_1 cfgl (nodel :: ul) r n)).  intros cfgr H6.\n  elim H6; clear H6; intros noder H6.  rewrite H6.\n  elim (prod_sum _ _ (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  intros cfg' H7; elim H7; clear H7; intros node' H7.  rewrite H7.  simpl in |- *.\n  cut (nat_of_N (node_height cfg l) < n).  cut (nat_of_N (node_height cfg r) < n).\n  intros.  cut (used_node' cfg ul l).  cut (used_node' cfg ul r).  intros.\n  cut\n   (BDDconfig_OK cfgl /\\\n    config_node_OK cfgl nodel /\\\n    used_nodes_preserved cfg cfgl ul /\\\n    Neqb (node_height cfgl nodel) (node_height cfg l) = true /\\\n    bool_fun_eq (bool_fun_of_BDD cfgl nodel)\n      (bool_fun_neg (bool_fun_of_BDD cfg l))).\n  intro.  elim H12; clear H12; intros.  elim H13; clear H13; intros.\n  elim H14; clear H14; intros.  elim H15; clear H15; intros.\n  cut (config_node_OK cfg l).  cut (config_node_OK cfg r).  intros.\n  cut (used_list_OK cfgl ul).  intro.  cut (used_list_OK cfgl (nodel :: ul)).\n  intro.  cut (used_node' cfgl ul r).  intro.\n  cut (used_node' cfgl (r :: ul) r).  intro.\n  cut\n   (BDDconfig_OK cfgr /\\\n    config_node_OK cfgr noder /\\\n    used_nodes_preserved cfgl cfgr (nodel :: ul) /\\\n    Neqb (node_height cfgr noder) (node_height cfgl r) = true /\\\n    bool_fun_eq (bool_fun_of_BDD cfgr noder)\n      (bool_fun_neg (bool_fun_of_BDD cfgl r))).\n  intros.  elim H23; clear H23; intros.  elim H24; clear H24; intros.\n  elim H25; clear H25; intros.  elim H26; clear H26; intros.\n  cut (used_list_OK cfgr (nodel :: ul)).  intro.\n  cut (used_list_OK cfgr (noder :: nodel :: ul)).  intro.\n  cut (used_node' cfgr (noder :: nodel :: ul) nodel).\n  cut (used_node' cfgr (noder :: nodel :: ul) noder).  intros.\n  cut\n   (forall (xl : BDDvar) (ll rl : ad),\n    MapGet _ (fst cfgr) nodel = Some (xl, (ll, rl)) ->\n    BDDcompare xl x = Datatypes.Lt).\n  cut\n   (forall (xr : BDDvar) (lr rr : ad),\n    MapGet _ (fst cfgr) noder = Some (xr, (lr, rr)) ->\n    BDDcompare xr x = Datatypes.Lt).\n  intros.  cut (BDDconfig_OK cfg').\n  cut (used_nodes_preserved cfgr cfg' (noder :: nodel :: ul)).\n  cut (config_node_OK cfg' node').\n  cut\n   (bool_fun_eq (bool_fun_of_BDD cfg' node')\n      (bool_fun_if x (bool_fun_of_BDD cfgr noder)\n         (bool_fun_of_BDD cfgr nodel))).\n  cut (Neqb (node_height cfg' node') (ad_S x) = true).  intros.\n  cut (config_node_OK cfg' node).  intro.\n  cut (nodes_preserved cfg' (BDDneg_memo_put cfg' node node')).  intro.\n  cut (BDDconfig_OK (BDDneg_memo_put cfg' node node')).  intro.  split.\n  assumption.  split.  apply nodes_preserved_config_node_OK with (cfg1 := cfg').\n  assumption.  assumption.  split.\n  apply used_nodes_preserved_trans with (cfg2 := cfgr).  assumption.\n  apply used_nodes_preserved_trans with (cfg2 := cfgl).  assumption.  assumption.\n  apply used_nodes_preserved_cons with (node := nodel).  assumption.  \n  apply used_nodes_preserved_trans with (cfg2 := cfg').  assumption.\n  apply used_nodes_preserved_cons with (node := nodel).\n  apply used_nodes_preserved_cons with (node := noder).\n  assumption.  apply nodes_preserved_used_nodes_preserved.  assumption.\n  rewrite\n   (Neqb_complete (node_height (BDDneg_memo_put cfg' node node') node')\n      (node_height cfg' node')).\n  split.  rewrite (Neqb_complete _ _ H34).  unfold node_height in |- *.  unfold bs_node_height in |- *.\n  rewrite H4.  apply Neqb_correct.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfg' node').\n  apply nodes_preserved_bool_fun.  assumption.  assumption.  assumption.  \n  assumption.  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_if x (bool_fun_of_BDD cfgr noder)\n                (bool_fun_of_BDD cfgr nodel)).\n  assumption.  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_if x (bool_fun_neg (bool_fun_of_BDD cfg r))\n                (bool_fun_neg (bool_fun_of_BDD cfg l))).\n  apply bool_fun_if_preserves_eq.  apply bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_of_BDD cfgl r)).\n  assumption.  apply bool_fun_neg_preserves_eq.\n  apply used_nodes_preserved'_bool_fun with (ul := ul).\n  assumption.  assumption.  assumption.  assumption.  assumption.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfgl nodel).\n  apply used_nodes_preserved'_bool_fun with (ul := nodel :: ul).  assumption.\n  assumption.  assumption.  assumption.  apply used_node'_cons_node_ul.\n  assumption.  apply bool_fun_eq_sym.\n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_neg\n                (bool_fun_if x (bool_fun_of_BDD cfg r)\n                   (bool_fun_of_BDD cfg l))).\n  apply bool_fun_neg_preserves_eq.  apply bool_fun_of_BDD_int.  assumption.\n  assumption.  apply bool_fun_neg_orthogonal.  apply nodes_preserved_node_height_eq.\n  assumption.  assumption.  assumption.  assumption.  apply BDDnegm_put_OK.\n  assumption.  assumption.  assumption.  rewrite (Neqb_complete _ _ H34).\n  rewrite (Neqb_complete (node_height cfg' node) (node_height cfg node)).  unfold node_height in |- *.\n  unfold bs_node_height in |- *.  rewrite H4.  apply Neqb_correct.\n  apply used_nodes_preserved'_node_height_eq with (ul := ul).  assumption.  assumption.\n  apply used_nodes_preserved_trans with (cfg2 := cfgl).  assumption.  assumption.\n  apply used_nodes_preserved_trans with (cfg2 := cfgr).  assumption.  \n  apply used_nodes_preserved_cons with (node := nodel).  assumption.  \n  apply used_nodes_preserved_cons with (node := nodel).\n  apply used_nodes_preserved_cons with (node := noder).  assumption.  assumption.\n  assumption.  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_if x (bool_fun_of_BDD cfgr noder)\n                (bool_fun_of_BDD cfgr nodel)).\n  assumption.  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_if x (bool_fun_neg (bool_fun_of_BDD cfg r))\n                (bool_fun_neg (bool_fun_of_BDD cfg l))).\n  apply bool_fun_if_preserves_eq.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_of_BDD cfgl r)).\n  assumption.  apply bool_fun_neg_preserves_eq.\n  apply used_nodes_preserved'_bool_fun with (ul := ul).\n  assumption.  assumption.  assumption.  assumption.  assumption.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfgl nodel).\n  apply used_nodes_preserved'_bool_fun with (ul := nodel :: ul).  assumption.\n  assumption.  assumption.  assumption.  apply used_node'_cons_node_ul.\n  assumption.  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_neg (bool_fun_of_BDD cfg node)).\n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_neg\n                (bool_fun_if x (bool_fun_of_BDD cfg r)\n                   (bool_fun_of_BDD cfg l))).\n  apply bool_fun_eq_sym.  apply bool_fun_neg_orthogonal.\n  apply bool_fun_neg_preserves_eq.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_int.  assumption.  assumption.\n  apply bool_fun_neg_preserves_eq.  apply bool_fun_eq_sym.\n  apply used_nodes_preserved'_bool_fun with (ul := ul).  assumption.  assumption.\n  apply used_nodes_preserved_trans with (cfg2 := cfgl).  assumption.  assumption.  \n  apply used_nodes_preserved_trans with (cfg2 := cfgr).  assumption.  \n  apply used_nodes_preserved_cons with (node := nodel).  assumption.  \n  apply used_nodes_preserved_cons with (node := nodel).\n  apply used_nodes_preserved_cons with (node := noder).  assumption.  assumption.\n  assumption.  apply BDDnegm_put_nodes_preserved.  \n  apply used_nodes_preserved_node_OK' with (ul := ul) (cfg := cfg).  assumption.\n  assumption.  assumption.  apply used_nodes_preserved_trans with (cfg2 := cfgl).\n  assumption.  assumption.  apply used_nodes_preserved_trans with (cfg2 := cfgr).\n  assumption.  apply used_nodes_preserved_cons with (node := nodel).  assumption.\n  apply used_nodes_preserved_cons with (node := nodel).\n  apply used_nodes_preserved_cons with (node := noder).  assumption.\n  replace cfg' with\n   (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  replace node' with\n   (snd (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  apply BDDmake_node_height_eq.  assumption.  intros.  apply not_true_is_false.\n  unfold not in |- *; intro.  apply eq_true_false_abs with (b := Neqb l r).\n  apply BDDunique with (cfg := cfg).  assumption.  assumption.  assumption.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfgl r).\n  apply bool_fun_eq_neg_eq.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfgl nodel).\n  apply bool_fun_eq_sym.  assumption.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfgr nodel).\n  apply bool_fun_eq_sym.\n  apply used_nodes_preserved'_bool_fun with (ul := nodel :: ul).  assumption.\n  assumption.  assumption.  assumption.  apply used_node'_cons_node_ul.\n  rewrite (Neqb_complete _ _ H34).  assumption.\n  apply used_nodes_preserved'_bool_fun with (ul := ul).  assumption.  assumption.\n  assumption.  assumption.  assumption.\n  apply low_high_neq with (cfg := cfg) (node := node) (x := x).  assumption.  assumption.\n  rewrite H7.  reflexivity.  rewrite H7.  reflexivity.  \n  replace cfg' with\n   (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  replace node' with\n   (snd (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  apply BDDmake_bool_fun.  assumption.  assumption.  assumption.  assumption.\n  assumption.  assumption.  assumption.  rewrite H7.  reflexivity.  rewrite H7.\n  reflexivity.  replace cfg' with\n   (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  replace node' with\n   (snd (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  apply BDDmake_node_OK.  assumption.  assumption.  assumption.  assumption.  \n  assumption.  assumption.  assumption.  rewrite H7.  reflexivity.  rewrite H7.\n  reflexivity.  replace cfg' with\n   (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  replace node' with\n   (snd (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  apply BDDmake_preserves_used_nodes.  assumption.  assumption.  assumption.  \n  rewrite H7.  reflexivity.  rewrite H7.  reflexivity.\n  replace cfg' with\n   (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  apply BDDmake_keeps_config_OK.  assumption.  assumption.  assumption.\n  assumption.  assumption.  assumption.  assumption.  rewrite H7.  reflexivity.\n  intros.  rewrite (ad_S_compare xr x).\n  replace (ad_S xr) with (bs_node_height (fst cfgr) noder).\n  replace (ad_S x) with (bs_node_height (fst cfg) node).  unfold node_height in H26.\n  rewrite (Neqb_complete _ _ H26).  cut (Neqb (node_height cfgl r) (node_height cfg r) = true).\n  intro.  unfold node_height in H33.  rewrite (Neqb_complete _ _ H33).\n  apply bs_node_height_right with (x := x) (l := l).  exact (proj1 H1).  assumption.\n  apply used_nodes_preserved'_node_height_eq with (ul := ul).  assumption.  assumption.\n  assumption.  assumption.  assumption.  unfold bs_node_height in |- *.  rewrite H4.\n  reflexivity.  unfold bs_node_height in |- *.  rewrite H32.  reflexivity.  intros.\n  rewrite (ad_S_compare xl x).  replace (ad_S xl) with (bs_node_height (fst cfgr) nodel).\n  replace (ad_S x) with (bs_node_height (fst cfg) node).\n  cut (Neqb (node_height cfgr nodel) (node_height cfgl nodel) = true).  intro.\n  unfold node_height in H33.  rewrite (Neqb_complete _ _ H33).  unfold node_height in H15.\n  rewrite (Neqb_complete _ _ H15).  apply bs_node_height_left with (x := x) (r := r).\n  exact (proj1 H1).  assumption.  \n  apply used_nodes_preserved'_node_height_eq with (ul := nodel :: ul).  assumption.\n  assumption.  assumption.  assumption.  apply used_node'_cons_node_ul.  \n  unfold bs_node_height in |- *.  rewrite H4.  reflexivity.  unfold bs_node_height in |- *.  rewrite H32.\n  reflexivity.  apply used_node'_cons_node_ul.  apply used_node'_cons_node'_ul.\n  apply used_node'_cons_node_ul.  apply node_OK_list_OK.  assumption.  \n  assumption.  apply used_nodes_preserved_list_OK with (cfg := cfgl).  assumption.  \n  assumption.  replace cfgr with (fst (BDDneg_1 cfgl (nodel :: ul) r n)).\n  replace noder with (snd (BDDneg_1 cfgl (nodel :: ul) r n)).  apply H.\n  apply lt_trans_1 with (y := nat_of_N (node_height cfg node)).\n  cut (Neqb (node_height cfgl r) (node_height cfg r) = true).  intro.\n  rewrite (Neqb_complete _ _ H23).  apply BDDcompare_lt.  unfold node_height in |- *.\n  apply bs_node_height_right with (x := x) (l := l).  exact (proj1 H1).  assumption.\n  apply used_nodes_preserved'_node_height_eq with (ul := ul).  assumption.  assumption.\n  assumption.  assumption.  assumption.  assumption.  assumption.  assumption.\n  apply used_node'_cons_node'_ul.  assumption.  rewrite H6.  reflexivity.  \n  rewrite H6.  reflexivity.  apply used_node'_cons_node_ul.  \n  apply used_nodes_preserved_used_node' with (cfg := cfg).  assumption.  assumption.\n  assumption.  apply node_OK_list_OK.  assumption.  assumption.  \n  apply used_nodes_preserved_list_OK with (cfg := cfg).  assumption.  assumption.  \n  apply used_node'_OK with (ul := ul).  assumption.  assumption.  assumption.  \n  apply used_node'_OK with (ul := ul).  assumption.  assumption.  assumption.  \n  replace cfgl with (fst (BDDneg_1 cfg ul l n)).\n  replace nodel with (snd (BDDneg_1 cfg ul l n)).  apply H.\n  apply lt_trans_1 with (y := nat_of_N (node_height cfg node)).  apply BDDcompare_lt.\n  unfold node_height in |- *.  apply bs_node_height_left with (x := x) (r := r).  exact (proj1 H1).\n  assumption.  assumption.  assumption.  assumption.  assumption.  rewrite H5.\n  reflexivity.  rewrite H5.  reflexivity.  \n  apply high_used' with (x := x) (l := l) (node := node).  assumption.  assumption.  \n  assumption.  apply low_used' with (x := x) (r := r) (node := node).  assumption.  \n  assumption.  assumption.  apply lt_trans_1 with (y := nat_of_N (node_height cfg node)).\n  apply BDDcompare_lt.  unfold node_height in |- *.  apply bs_node_height_right with (x := x) (l := l).\n  exact (proj1 H1).  assumption.  assumption.\n  apply lt_trans_1 with (y := nat_of_N (node_height cfg node)).  apply BDDcompare_lt.\n  unfold node_height in |- *.  apply bs_node_height_left with (x := x) (r := r).  exact (proj1 H1).\n  assumption.  assumption.  intro y0.  rewrite y0.\n  elim (sumbool_of_bool (Neqb node BDDzero)).  intro y1.  rewrite y1.\n  rewrite (Neqb_complete _ _ y1).  simpl in |- *.\n  cut (BDDconfig_OK (BDDneg_memo_put cfg BDDzero BDDone)).  intro.  split.\n  assumption.  cut (nodes_preserved cfg (BDDneg_memo_put cfg BDDzero BDDone)).\n  intro.  split.  apply nodes_preserved_config_node_OK with (cfg1 := cfg).\n  assumption.  apply one_OK.  split.  apply nodes_preserved_used_nodes_preserved.\n  assumption.  split.  rewrite <-\n   (Neqb_complete (node_height cfg BDDone) (node_height cfg BDDzero))\n   .\n  apply nodes_preserved_node_height_eq.  assumption.  assumption.  assumption.\n  apply one_OK.  rewrite (Neqb_complete _ _ (node_height_zero _ H1)).\n  rewrite (Neqb_complete _ _ (node_height_one _ H1)).  reflexivity.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_one).  apply bool_fun_of_BDD_one.\n  assumption.  apply bool_fun_eq_trans with (bf2 := bool_fun_neg bool_fun_zero).\n  apply bool_fun_eq_sym.  exact bool_fun_neg_zero.\n  apply bool_fun_neg_preserves_eq.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_zero.  assumption.  apply BDDnegm_put_nodes_preserved.\n  apply BDDnegm_put_OK.  assumption.  apply zero_OK.  apply one_OK.  \n  rewrite (Neqb_complete _ _ (node_height_zero _ H1)).\n  rewrite (Neqb_complete _ _ (node_height_one _ H1)).  reflexivity.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_neg bool_fun_zero).  \n  apply bool_fun_of_BDD_one.  assumption.  apply bool_fun_neg_preserves_eq.\n  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_zero.  assumption.  intro y1.\n  rewrite y1.  simpl in |- *.  cut (BDDconfig_OK (BDDneg_memo_put cfg BDDone BDDzero)).\n  intro.  split.  assumption.\n  cut (nodes_preserved cfg (BDDneg_memo_put cfg BDDone BDDzero)).  intro.\n  split.  apply nodes_preserved_config_node_OK with (cfg1 := cfg).  assumption.\n  apply zero_OK.  split.  apply nodes_preserved_used_nodes_preserved.\n  assumption.  elim (used_node'_OK cfg ul node H1 H2 H3).  intro.\n  rewrite H6 in y1.  simpl in y1.  discriminate.  intro.  elim H6.  intro.\n  rewrite H7.  split.  rewrite <-\n   (Neqb_complete (node_height cfg BDDzero) (node_height cfg BDDone))\n   .\n  apply nodes_preserved_node_height_eq.  assumption.  assumption.  assumption.\n  apply zero_OK.  rewrite (Neqb_complete _ _ (node_height_zero _ H1)).\n  rewrite (Neqb_complete _ _ (node_height_one _ H1)).  reflexivity.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_zero).  apply bool_fun_of_BDD_zero.\n  assumption.  apply bool_fun_eq_trans with (bf2 := bool_fun_neg bool_fun_one).\n  apply bool_fun_eq_sym.  exact bool_fun_neg_one.\n  apply bool_fun_neg_preserves_eq.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_one.  assumption.  intro.  unfold in_dom in H7.\n  rewrite y0 in H7.  discriminate.  apply BDDnegm_put_nodes_preserved.\n  apply BDDnegm_put_OK.  assumption.  apply one_OK.  apply zero_OK.  \n  rewrite (Neqb_complete _ _ (node_height_zero _ H1)).\n  rewrite (Neqb_complete _ _ (node_height_one _ H1)).  reflexivity.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_neg bool_fun_one).\n  apply bool_fun_of_BDD_zero.  assumption.  apply bool_fun_neg_preserves_eq.\n  apply bool_fun_eq_sym.  apply bool_fun_of_BDD_one.  assumption.  \nQed.\n\nEnd BDD_neg.", "meta": {"author": "coq-contribs", "repo": "smc", "sha": "e175520faa82eda0f014d300705612892fc7e778", "save_path": "github-repos/coq/coq-contribs-smc", "path": "github-repos/coq/coq-contribs-smc/smc-e175520faa82eda0f014d300705612892fc7e778/neg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.2227630896119682}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition init_rec_sysregs_spec0 (rec: Pointer) (mpidr: Z64) (adt: RData) : option RData :=\n    match rec, mpidr with\n    | (_rec_base, _rec_ofst), VZ64 _mpidr =>\n      when adt == set_rec_sysregs_spec (_rec_base, _rec_ofst) 39 (VZ64 64) adt;\n      when adt == set_rec_sysregs_spec (_rec_base, _rec_ofst) 47 (VZ64 12912760) adt;\n      when adt == set_rec_sysregs_spec (_rec_base, _rec_ofst) 65 (VZ64 4096) adt;\n      rely is_int64 _mpidr;\n      when adt == set_rec_sysregs_spec (_rec_base, _rec_ofst) 72 (VZ64 _mpidr) adt;\n      when adt == set_rec_sysregs_spec (_rec_base, _rec_ofst) 69 (VZ64 3072) adt;\n      Some adt\n     end\n    .\n\nEnd SpecLow.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RmiAux/LowSpecs/init_rec_sysregs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.2227630844026316}}
{"text": "Require Import Coq.Logic.Classical_Prop.\nRequire Import EqNat.\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import List.\nRequire Import Relations.\nRequire Import FunctionalExtensionality.\n\nRequire Import Semantics.\nRequire Import Utils Lattices CLattices.\nRequire Import Instr.\nRequire Import AbstractCommon Rules QuasiAbstractMachine.\nRequire Import Concrete ConcreteMachine CodeGen CodeSpecs.\nRequire Import FaultRoutine.\nRequire Import Determinism.\nRequire Import ConcreteExecutions.\nRequire Import Refinement.\nRequire Import RefinementAC.\nRequire Import Encodable.\n\nRequire Import Refinement.\nRequire RefinementAC.\n\n(** The Abstract Machine refines the Concrete Machine (with appropriate fault handler). *)\n\nSet Implicit Arguments.\nLocal Open Scope Z_scope.\n\nSection QuasiAbstractAbstract.\n\nContext {T: Type}\n        {Latt: JoinSemiLattice T}.\n\nProgram Definition quasi_abstract_abstract_sref :=\n  @strong_refinement tini_quasi_abstract_machine\n                     AbstractMachine.abstract_machine\n                     eq eq _.\nNext Obligation.\n  exists a2. exists s22.\n  repeat split; trivial.\n  - generalize abstract_step_equiv. simpl. intuition.\n    rewrite H. trivial.\n  - destruct a2; constructor; trivial.\nQed.\n\nProgram Definition quasi_abstract_abstract_ref :=\n  @refinement_from_state_refinement tini_quasi_abstract_machine\n                                    AbstractMachine.abstract_machine\n                                    quasi_abstract_abstract_sref eq\n                                    _.\n\nEnd QuasiAbstractAbstract.\n\nSection Ref.\n\nContext {L: Type}\n        {Latt: JoinSemiLattice L}\n        {CLatt: ConcreteLattice L}\n        {ELatt: Encodable L}\n        {WFCLatt: WfConcreteLattice L Latt CLatt ELatt}.\n\n\n\n(** The fault handler code and its correctness *)\nNotation fetch_rule_g := fetch_rule. (* Should be able to replace this with a generic one later *)\nDefinition fetch_rule_withsig := (fun opcode => existT _ (labelCount opcode) (fetch_rule_g opcode)).\nDefinition LCL := LatticeConcreteLabels fetch_rule_withsig.\nDefinition faultHandler := @FaultRoutine.faultHandler L ELatt labelCount\n                                                      (ifc_run_tmr fetch_rule_g)\n                                                      LCL.\n\n(* Bit more glue *)\nLemma handler_correct :\n  forall m i s raddr c opcode vls pcl olr lpc,\n  forall (INPUT: cache_hit c (opCodeToZ opcode) (@labsToZs L ELatt _ vls) (labToZ pcl))\n         (RULE: apply_rule (fetch_rule_g opcode) pcl vls = Some (olr,lpc)),\n    exists c',\n    runsToEscape (CState c m faultHandler i (CRet raddr false false::s) (0,handlerTag) true)\n                 (CState c' m faultHandler i s raddr false) /\\\n    handler_final_mem_matches (T:=L) olr lpc c c'.\nProof.\n  intros.\n  exploit (handler_correct_succeed (CT := LCL)); unfold fetch_rule_withsig; eauto.\nQed.\n\nLemma match_stacks_args' : forall args s cs,\n   match_stacks (args ++ s) cs ->\n   exists args' cs', cs = args'++cs'\n                      /\\ match_stacks args args'\n                      /\\ match_stacks s cs'.\nProof.\n  induction args; intros.\n  - simpl in *. exists nil; exists cs. repeat (split; eauto). constructor.\n  - simpl in *.\n    inv H.\n    + exploit IHargs; eauto; intros [args' [cs' [Heq [Hmatch Hmatch']]]]; subst.\n      exists (atom_labToZ a0 ::: args').\n      eexists; split; eauto ; try reflexivity.\n      split; eauto.\n      constructor; eauto.\n    + exploit IHargs; eauto; intros [args' [cs' [Heq [Hmatch Hmatch']]]]; subst.\n      exists (CRet (atom_labToZ a0) r false :: args').\n      eexists; split; eauto ; try reflexivity.\n      split; eauto.\n      constructor; eauto.\nQed.\n\nLemma match_stacks_data' : forall s cs,\n    match_stacks s cs ->\n    (forall a, In a s -> exists d : Atom, a = AData d) ->\n    (forall a, In a cs -> exists d : Atom, a = CData d).\nProof.\n  induction 1;  intros.\n  - inv H0.\n  - inv H2.  eauto.\n    eapply IHmatch_stacks; eauto.\n    intros; eapply H1; eauto.\n    econstructor 2; eauto.\n  - inv H2.\n    eelim (H1 (ARet a r)); eauto. intros. congruence.\n    constructor; auto.\n    eapply IHmatch_stacks; eauto.\n    intros; eapply H1; eauto.\n    econstructor 2; eauto.\nQed.\n\nLemma match_stacks_pop_to_return : forall dstk cdstk pcv pcl b stk cs p,\n   match_stacks (dstk  ++ ARet (pcv, pcl)        b   :: stk)\n                (cdstk ++ CRet (pcv, labToZ pcl) b p :: cs) ->\n   (forall e, In e dstk -> exists a, e = AData a) ->\n   length dstk = length cdstk ->\n   pop_to_return   (dstk  ++ ARet (pcv, pcl)        b   :: stk) (ARet (pcv, pcl) b :: stk) ->\n   c_pop_to_return (cdstk ++ CRet (pcv, labToZ pcl) b p :: cs)  (CRet (pcv, labToZ pcl) b p ::cs).\nProof.\n  intros.\n  exploit match_stacks_app_length; eauto. intros [Hmatch Hmatch'].\n  inv Hmatch'. inv H10.\n  assert (Hcdstk:= match_stacks_data' Hmatch H0); eauto.\n  eapply c_pop_to_return_pops_data; eauto.\nQed.\n\n(** Observing a concete cache is just projecting it a the abstract level.\n    Defining related notions and conversions\n *)\nFixpoint c_to_a_stack (cs : list CStkElmt): list (@StkElmt L) :=\n  match cs with\n    | nil => nil\n    | CData s :: cs => (AData (atom_ZToLab s))::(c_to_a_stack cs)\n    | CRet a r p::cs => ARet (atom_ZToLab a) r::(c_to_a_stack cs)\n  end.\n\nLemma match_stacks_obs : forall s s',\n    match_stacks s s' ->\n    c_to_a_stack s' = s.\nProof.\n  induction s ; intros.\n  inv H; simpl; auto.\n  inv H; simpl; rewrite IHs; eauto;\n  rewrite <- atom_ZToLab_labToZ_id; auto.\nQed.\n\nHint Rewrite match_stacks_obs.\n\nDefinition observe_cstate (cs: CS) : @AS L :=\n  match cs with\n    | CState c m fh i s pc p =>\n      AState (mem_ZToLab m) i (c_to_a_stack s) (atom_ZToLab pc)\n  end.\n\nLemma handler_cache_hit_read :\n  forall rl m rpcl tmuc,\n    handler_final_mem_matches rpcl rl m tmuc ->\n    cache_hit_read tmuc (labToZ rl) (labToZ rpcl).\nProof.\n  intros; inv H ; auto.\nQed.\n\nLtac allinv' :=\n  allinv ;\n    (match goal with\n       | [ H1:  ?f _ _ = _ ,\n           H2:  ?f _ _ = _ |- _ ] => rewrite H1 in H2 ; inv H2\n     end).\n\nLemma handler_final_cache_hit_preserved:\n  forall tmuc tmuc' rl opcode labs rpcl pcl,\n    handler_final_mem_matches rpcl rl tmuc tmuc' ->\n    cache_hit tmuc  opcode labs pcl ->\n    cache_hit tmuc' opcode labs pcl.\nProof.\n  intros *. intros Hfinal HCHIT. inv HCHIT.\n  inv Hfinal. unfold update_cache_spec_rvec in *.\n  assert (exists tagr tagrpc, cache_hit_read tmuc' tagr tagrpc)\n    by (eexists; eexists; eauto).\n  destruct H1 as [tagr' [tagrpc' C]].\n  inv C.\n  repeat (match goal with\n    | [ HTAG : tag_in_mem _ ?addr _ |- _ ] => inv HTAG\n  end).\n  econstructor;\n  try solve [econstructor;\n              try (rewrite <- H0; eauto;\n                   match goal with\n                     | [ |- ?a <> ?b ] => try (unfold a, b ; congruence)\n                   end; fail); eauto];\n  eauto.\nQed.\n\nLemma opCodeToZ_inj: forall o1 o2, opCodeToZ o1 = opCodeToZ o2 -> o1 = o2.\nProof.\n  intros o1 o2 Heq.\n  destruct o1, o2; inv Heq; try congruence.\nQed.\n\nHint Constructors cstep runsToEscape match_stacks match_states : core.\n\nLtac inv_cache_update :=\n  unfold cache_up2date in *;\n  unfold cache_up2date_weak; intros;\n  exploit handler_final_cache_hit_preserved; eauto; intros;\n  let P1 := fresh in let P2 := fresh in let P3 := fresh in\n  match goal with\n    |  [CHIT: cache_hit ?C _ _ _,\n        CHIT': cache_hit ?C _ _ _ |- _] =>\n       destruct (cache_hit_unique CHIT CHIT') as [P1 [P2 P3]];\n       subst;\n       apply opCodeToZ_inj in P1; subst;\n       apply labsToZs_inj in P2; try (zify; lia); subst;\n       apply labToZ_inj in P3 ;subst\n   end;\n  try allinv';\n  try match goal with\n        | [H : apply_rule _ _ _ = _ |- _] =>\n          rewrite H\n      end;\n  try solve [eapply handler_cache_hit_read; eauto].\n\nLemma match_observe:\n  forall s1 s2,\n    match_states fetch_rule_g s1 s2 ->\n    s1 = observe_cstate s2.\nProof.\n  intros.\n  inv H.\n  simpl. erewrite match_stacks_obs; eauto.\n  rewrite <- atom_ZToLab_labToZ_id.\n  rewrite <- mem_ZToLab_labToZ_id.\n  auto.\nQed.\n\nHint Constructors star plus : core.\n\nLemma update_list_map : forall xv rl m n m',\n   update_list n (xv, rl) m = Some m' ->\n   update_list n (xv, labToZ rl) (mem_labToZ m) = Some (mem_labToZ m').\nProof.\n  induction m ; intros; simpl in *.\n  destruct n ; simpl in *; inv H.\n  destruct n ; simpl in *.\n  - inv H. reflexivity.\n  - case_eq (update_list n (xv,rl) m); intros; rewrite H0 in *; inv H.\n    erewrite IHm ; eauto. reflexivity.\nQed.\n\nLemma upd_m_mem_labToZ : forall m addrv xv rl m',\n  upd_m addrv (xv, rl) m = Some m' ->\n  upd_m addrv (xv, labToZ rl) (mem_labToZ m) = Some (mem_labToZ m').\nProof.\n  unfold upd_m.\n  intros; simpl in *.\n  case (addrv <? 0) in *. inv H.\n  eapply update_list_map; eauto.\nQed.\n\nLtac renaming :=\n  match goal with\n    | [ Hrule : ifc_run_tmr _ ?opcode ?pcl ?v = Some (?rpcl, ?rl) |- _ ]  =>\n      set (tags := labsToZs v);\n      set (op := opCodeToZ opcode);\n      set (pct := labToZ pcl);\n      set (rpct := labToZ rpcl);\n      set (rt := labToZ rl)\n  end;\n  match goal with\n    | [ HH: match_states _ (AState ?m _ _ _) _ |- _ ] => set (cm := mem_labToZ m)\n  end.\n\nLtac solve_read_m :=\n  (unfold nth_labToZ; simpl);\n  (unfold Vector.nth_order; simpl);\n  (eapply read_m_labToZ; eauto).\n\nLtac res_label :=\n  try match goal with\n    | [Hrule: apply_rule _ _ _ = Some (_,_),\n       Hcache : cache_up2date_weak _ _,\n       CHIT : cache_hit _ _ _ _ |- _ ] =>\n      let ASSERT := fresh \"Assert\" in\n      assert (ASSERT := Hcache _ _ _ _ _ Hrule CHIT); eauto;\n      simpl in ASSERT;\n      inv ASSERT\n      end.\n\nLemma update_cache_hit :\n  forall opcode tags pctag tmuc,\n    cache_hit (update_cache opcode tags pctag tmuc) opcode tags pctag.\nProof.\n  intros.\n  destruct tags as [[t1 t2] t3].\n  econstructor; econstructor; unfold update_cache;\n  rewrite index_list_Z_update_list_list;\n  reflexivity.\nQed.\n\nLtac build_cache_and_tmu :=\n  simpl;\n  match goal with\n    | [Hmiss: ~ cache_hit ?tmuc ?op ?tags ?pct ,\n       Hrule: apply_rule _ _ _ = Some _ ,\n       i : list Instr\n     |- context[ (CState _ ?cm _ _ ?cstk (?pcv,_) _) ] ] =>\n      let CHIT := fresh \"CHIT\" in\n      set (tmuc':= update_cache op tags pct tmuc);\n      assert (CHIT : cache_hit tmuc' op tags pct)\n        by (eauto using update_cache_hit);\n      edestruct (handler_correct cm i cstk (pcv,pct) _ _ CHIT Hrule) as [c [Hruns Hmfinal]];\n      eauto\n  end.\n\nHint Resolve match_stacks_app match_stacks_data' match_stacks_length : core.\n\nDefinition op_cons_ZToLab (oe: Event+τ) (t: list CEvent) :=\n  match oe with\n    | E (EInt e) => (CEInt (atom_labToZ e))::t\n    | Silent => t\n  end.\n\nLemma op_cons_ZToLab_none : (op_cons_ZToLab Silent nil) = (op_cons Silent (@nil CEvent)).\nProof. reflexivity. Qed.\n\nLtac hint_event := rewrite op_cons_ZToLab_none.\n\nLtac priv_steps :=\n  match goal with\n    | [Hruns : runsToEscape ?s ?s',\n       Hmfinal: handler_final_mem_matches _ _ _ _ |- _ ] =>\n      (eapply runsToEscape_plus in Hruns; [| congruence]);\n        let Hll := fresh \"Hll\" in\n        let Hspec := fresh \"Hspec\" in\n      (generalize Hmfinal; intros [Hll Hspec]; inv Hll);\n      (simpl atom_labToZ);\n      (eapply plus_trans with (s2:= s) (t:= @nil CEvent); eauto);\n      try (match goal with\n          | [ |- cstep _ _ _ ] =>\n            [> once (econstructor; solve [ eauto | eauto; solve_read_m ]) ..]\n          | [ |- cstep _ _ _ ] =>\n            econstructor ; eauto\n           end);\n      try match goal with\n            | [ |- plus _ _ _ _ ] =>\n              (eapply plus_right with (s2:= s') (t:= nil) (e:= Silent); eauto);\n              [> once (econstructor; solve [eauto;\n                                            try (eapply handler_final_cache_hit_preserved; eauto);\n                                            try (solve_read_m; eauto)]) ..]\n          end\n  end.\n\nLemma step_preserved:\n  forall s1 s1' e s2,\n    step_rules (ifc_run_tmr fetch_rule_g) s1 e s1' ->\n    match_states fetch_rule_g s1 s2 ->\n    (exists s2', plus (step (concrete_machine faultHandler)) s2 (op_cons_ZToLab e nil) s2' /\\ match_states fetch_rule_g s1' s2').\nProof.\n  intros s1 s1' e s2 Hstep Hmatch.\n  inv Hstep; renaming;\n  match goal with\n    | [Htmr : ifc_run_tmr _ _ _ _ = _ ,\n       Hmatch : match_states _ _ _ |- _ ] =>\n      inv Hmatch;\n      unfold ifc_run_tmr in Htmr\n  end;\n  generalize (cache_up2date_success CACHE);\n  intros CACHE'.\n\n  - (* Noop *)\n    destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n    + exists (CState tmuc cm faultHandler i cstk (pcv+1, pct) false).\n      res_label. subst pct.\n      inv H0.\n      split; eauto.\n      hint_event.\n      eapply plus_step; eauto; eapply cstep_nop; eauto.\n      econstructor; eauto.\n\n    + build_cache_and_tmu.\n      exists (CState c cm faultHandler i cstk (pcv+1, rpct) false). split.\n      * priv_steps.\n      * econstructor; eauto.\n        inv_cache_update.\n\n - (* Add *)\n   inv STKS. inv H3.\n   destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n   + exists (CState tmuc cm faultHandler i ((x1v+x2v,rt):::cs0) (pcv+1,rpct) false).\n     split.\n     * eapply plus_step ; eauto. eapply cstep_add ; eauto.\n       auto.\n     * eauto.\n       econstructor; eauto.\n   + build_cache_and_tmu.\n     exists (CState c cm faultHandler i ((CData (x1v+x2v,rt))::cs0) (pcv+1, rpct) false).\n     split.\n     * priv_steps.\n     * econstructor ; eauto.\n       inv_cache_update.\n\n - (* Sub *)\n   inv STKS. inv H3.\n   destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n   + exists (CState tmuc cm faultHandler i ((x1v-x2v,rt):::cs0) (pcv+1,rpct) false).\n     split.\n     * eapply plus_step ; eauto. eapply cstep_sub ; eauto.\n       auto.\n     * eauto.\n       econstructor; eauto.\n   + build_cache_and_tmu.\n     exists (CState c cm faultHandler i ((x1v-x2v,rt):::cs0) (pcv+1, rpct) false).\n     split.\n     * priv_steps.\n     * econstructor ; eauto.\n       inv_cache_update.\n\n- (* Push *)\n  destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n   + exists (CState tmuc cm faultHandler i ((cv,rt):::cstk) (pcv+1,rpct) false).\n     split.\n     * eapply plus_step ; eauto. eapply cstep_push ; eauto.\n       auto.\n     * eauto.\n       econstructor; eauto.\n   + build_cache_and_tmu.\n     exists (CState c cm faultHandler i ((cv,rt):::cstk) (pcv+1, rpct) false). split.\n     * priv_steps.\n     * econstructor ; eauto.\n       inv_cache_update.\n\n- (* Pop *)\n  inv STKS.\n  destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n  + exists (CState tmuc cm faultHandler i cs (pcv+1,rpct) false).\n    hint_event.\n    split; eauto.\n    eapply plus_step; eauto.\n    eapply cstep_pop; eauto.\n    econstructor; eauto.\n  + build_cache_and_tmu.\n    exists (CState c cm faultHandler i cs (pcv+1, rpct) false). split.\n    * priv_steps.\n    * econstructor; eauto.\n      inv_cache_update.\n\n- (* Load *)\n  inv STKS.\n  destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n   + exists (CState tmuc cm faultHandler i ((xv,rt):::cs) (pcv+1,rpct) false).\n     split.\n     * eapply plus_step ; eauto.\n       eapply cstep_load ; eauto.\n       solve_read_m. auto.\n     * eauto.\n       econstructor; eauto.\n   + build_cache_and_tmu.\n     exists (CState c cm faultHandler i ((xv,rt):::cs) (pcv+1, rpct) false). split.\n     * priv_steps. reflexivity.\n     * econstructor ; eauto.\n       inv_cache_update.\n\n- (* Store *)\n  inv STKS. inv H5.\n  exploit upd_m_mem_labToZ ; eauto. intros Hcm'.\n  destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n   + exists (CState tmuc (mem_labToZ m') faultHandler i cs0 (pcv+1,rpct) false).\n     split.\n     * eapply plus_step ; eauto.\n       eapply cstep_store  ; eauto.\n       solve_read_m. auto.\n     * econstructor; eauto.\n   + build_cache_and_tmu.\n     exists (CState c (mem_labToZ m') faultHandler i cs0 (pcv+1, rpct) false). split.\n     * priv_steps. reflexivity.\n     * econstructor ; eauto.\n       inv_cache_update.\n\n- (* Jump *)\n  inv STKS.\n  destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n   + exists (CState tmuc cm faultHandler i cs (pcv',rpct) false).\n     split.\n     * eapply plus_step ; eauto. simpl.\n       res_label. hint_event. reflexivity.\n     * econstructor; eauto.\n   + build_cache_and_tmu. res_label.\n     exists (CState c cm faultHandler i cs (pcv', rpct) false). split.\n     * priv_steps.\n     * econstructor ; eauto.\n       inv_cache_update.\n\n- (* Branch *)\n  inv STKS.\n  destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n   + exists (CState tmuc cm faultHandler i cs\n                    (if 0 =? 0 then pcv+1 else pcv+offv , rpct) false).\n     split.\n     * eapply plus_step ; eauto. res_label.\n       eapply cstep_bnz ; eauto. auto.\n     * econstructor; eauto.\n   + build_cache_and_tmu.\n     res_label.\n     exists (CState c cm faultHandler i cs\n                    (if 0 =? 0 then pcv+1 else pcv+offv , rpct) false).\n     split.\n     * res_label. priv_steps.\n     * econstructor ; eauto.\n       inv_cache_update.\n\n- (* Branch YES *)\n  inv STKS.\n  destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n   + exists (CState tmuc cm faultHandler i cs\n                    (if av =? 0 then pcv+1 else pcv+offv , rpct) false).\n     split.\n     * eapply plus_step ; eauto. res_label.\n       eapply cstep_bnz ; eauto. auto.\n     * econstructor; eauto.\n       case_eq (av =? 0)%Z; intros; auto.\n       eelim H1; eauto.\n       rewrite Z.eqb_eq in H2. auto.\n   + build_cache_and_tmu. res_label.\n     exists (CState c cm faultHandler i cs\n                    (if av =? 0 then pcv+1 else pcv+offv , rpct) false).\n     split.\n     * priv_steps.\n     * econstructor ; eauto.\n       inv_cache_update.\n       case_eq (av =? 0)%Z; intros; auto.\n       eelim H1; eauto.\n       rewrite Z.eqb_eq in H2. auto.\n\n- (* Call *)\n  inv STKS.\n  edestruct (match_stacks_args' _ _ H4) as [args' [cs' [Heq [Hargs Hcs]]]]; eauto.\n  inv Heq.\n  destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n   + exists (CState tmuc cm faultHandler i\n                    (args'++ (CRet (pcv+1, rt) r false)::cs') (pcv',rpct) false).\n     split.\n     * eapply plus_step; eauto.\n       eapply cstep_call ; eauto.\n       auto.\n     * econstructor; eauto.\n   + build_cache_and_tmu.\n     exists (CState c cm faultHandler i\n                    (args'++ (CRet (pcv+1, rt) r false)::cs') (pcv',rpct) false).\n     split.\n     * priv_steps.\n     * econstructor ; eauto.\n       inv_cache_update.\n\n- (* Ret *)\n  exploit @pop_to_return_spec; eauto.\n  intros [dstk [stk [a [b [Heq Hdata]]]]]. inv Heq.\n  exploit @pop_to_return_spec2; eauto. intros Heq. inv Heq.\n  exploit @pop_to_return_spec3; eauto. intros Heq. inv Heq.\n\n  edestruct (match_stacks_args' _ _ STKS) as [args' [cs' [Heq [Hargs Hcs]]]]; eauto.\n  inv Heq. inv Hcs. simpl atom_labToZ in *.\n\n  exploit match_stacks_pop_to_return; eauto.\n  erewrite match_stacks_length; auto.\n  intros.\n\n  destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n  + exists (CState tmuc cm faultHandler i cs (pcv',rpct) false).\n     split.\n     * simpl. res_label.\n     * econstructor; eauto.\n\n   + build_cache_and_tmu.\n     exists (CState c cm faultHandler i cs (pcv',rpct) false). res_label.\n     split.\n     * priv_steps.\n     * econstructor ; eauto.\n       inv_cache_update.\n\n- (* VRet *)\n  inv STKS.\n  exploit @pop_to_return_spec; eauto.\n  intros [dstk [stk [a [b [Heq Hdata]]]]]. inv Heq.\n  exploit @pop_to_return_spec2; eauto. intros Heq. inv Heq.\n  exploit @pop_to_return_spec3; eauto. intros Heq. inv Heq.\n  edestruct (match_stacks_args' _ _ H4) as [args' [cs' [Heq [Hargs Hcs]]]]; eauto.\n  inv Heq. inv Hcs. simpl atom_labToZ in *.\n  exploit match_stacks_pop_to_return; eauto.\n  erewrite match_stacks_length; auto.\n  intros.\n\n  destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n   + exists (CState tmuc cm faultHandler i (CData (resv,rt)::cs) (pcv',rpct) false).\n     split.\n     * eapply plus_step ; eauto.\n       eapply cstep_vret ; eauto.\n       auto.\n     * econstructor; eauto.\n   + build_cache_and_tmu.\n     exists (CState c cm faultHandler i (CData (resv,rt)::cs) (pcv',rpct) false).\n     split.\n     * (eapply runsToEscape_plus in Hruns; [| congruence]);\n       (generalize Hmfinal; intros [Hll Hspec]; inv Hll);\n       (simpl atom_labToZ).\n       (eapply plus_trans with (s2:= (CState tmuc' (mem_labToZ m) faultHandler i\n                                             (CRet (pcv, pct) false false\n                                                   :: (resv, labToZ resl)\n                                                   ::: args' ++ CRet (pcv', labToZ pcl') true false :: cs)\n                                             (0, handlerTag) true)); eauto).\n       eapply plus_right ; eauto.\n       eapply cstep_vret; eauto.\n       eapply handler_final_cache_hit_preserved; eauto.\n       reflexivity.\n     * econstructor ; eauto.\n       inv_cache_update.\n\n- (* Output *)\n  inv STKS.\n  destruct (classic (cache_hit tmuc op tags pct)) as [CHIT | CMISS].\n   + exists (CState tmuc cm faultHandler i cs (pcv+1,rpct) false).\n     split.\n     * eapply plus_step ; eauto.\n       eapply cstep_out ; eauto.\n       auto.\n     * econstructor; eauto.\n   + build_cache_and_tmu.\n     exists (CState c cm faultHandler i cs (pcv+1, rpct) false).\n     split.\n     *\n       (eapply runsToEscape_plus in Hruns; [| congruence]);\n       (generalize Hmfinal; intros [Hll Hspec]; inv Hll);\n       (simpl atom_labToZ).\n       (eapply plus_trans ; eauto).\n       eapply plus_right ; eauto.\n       eapply cstep_out; eauto.\n       eapply handler_final_cache_hit_preserved; eauto.\n       simpl.\n       reflexivity.\n     * econstructor ; eauto.\n       inv_cache_update.\nQed.\n\nLemma plus_exec :\n  forall (S : semantics) s t s',\n    plus (step S) s t s' ->\n    TINI.exec s t s'.\nProof.\n  induction 1 as [s t s' [e|] STEP E|s s' s'' [e|] t t' STEP PLUS IH E]; simpl in *; subst; eauto.\nQed.\n\nLemma exec_trans :\n  forall (S : semantics) (s : Semantics.state S) t1 s' t2 s''\n         (E1 : TINI.exec s t1 s')\n         (E2 : TINI.exec s' t2 s''),\n    TINI.exec s (t1 ++ t2) s''.\nProof. induction 1; simpl; eauto. Qed.\n\nLemma concrete_quasi_abstract_sref_prop :\n  state_refinement_statement (concrete_machine faultHandler)\n                             (ifc_quasi_abstract_machine fetch_rule_g)\n                             (fun cs qas => match_states fetch_rule_g qas cs)\n                             (fun e1 e2 => RefinementAC.match_events e2 e1).\nProof.\n  intros s1 s2 t2 s2' MATCH EXEC.\n  gdep s1.\n  induction EXEC as [s2|s2 e2 s2' t2 s2'' STEP EXEC IH|s2 s2' t2 s2'' STEP EXEC IH]; intros.\n  - eexists nil.\n    exists s1.\n    split; constructor.\n  - exploit step_preserved; eauto.\n    intros [s1' [PLUS MATCH']].\n    exploit IH; eauto.\n    intros [t1 [s1'' [EXEC' MATCH'']]].\n    exists (op_cons_ZToLab (E e2) t1).\n    exists s1''.\n    destruct e2 as [e2].\n    split.\n    + exploit plus_exec; eauto.\n      simpl.\n      intros.\n      exploit exec_trans; eauto.\n    + simpl. constructor; eauto.\n      destruct e2. reflexivity.\n  - exploit step_preserved; eauto.\n    intros [s1' [PLUS MATCH']].\n    exploit IH; eauto.\n    intros [t1 [s1'' [EXEC' MATCH'']]].\n    exists (op_cons_ZToLab Silent t1).\n    exists s1''.\n    split; eauto.\n    exploit plus_exec; eauto.\n    simpl.\n    intros.\n    exploit exec_trans; eauto.\nQed.\n\nDefinition concrete_quasi_abstract_sref :=\n  {| sref_prop := concrete_quasi_abstract_sref_prop |}.\n\nDefinition concrete_quasi_abstract_ref :\n  refinement (concrete_machine faultHandler)\n             (ifc_quasi_abstract_machine fetch_rule_g) :=\n  @refinement_from_state_refinement _ _\n                                    concrete_quasi_abstract_sref\n                                    (fun i1 i2 => ac_match_initial_data i2 i1)\n                                    (fun i1 i2 => @ac_match_initial_data_match_initial_states _ _ _ _ _ _ i2 i1).\n\nLemma step_preserved_observ:\n  forall s1 e s1' s2,\n    step_rules (ifc_run_tmr fetch_rule_g) s1 e s1' ->\n    match_states fetch_rule_g s1 s2 ->\n    s1 = observe_cstate s2 /\\ (exists s2', plus cstep s2 (op_cons_ZToLab e nil) s2' /\\ match_states fetch_rule_g s1' s2').\nProof.\n  intros.\n  split.\n  apply match_observe; auto.\n  eapply step_preserved; eauto.\nQed.\n\nEnd Ref.\n\n(** Combining the above into the final result *)\n(** This is where we instantiate the generic refinement *)\nSection RefCA.\n\nContext {observer: Type}\n        {Latt: JoinSemiLattice observer}\n        {CLatt: ConcreteLattice observer}\n        {ELatt : Encodable observer}\n        {WFCLatt: WfConcreteLattice observer Latt CLatt ELatt}.\n\nDefinition tini_fetch_rule_withsig :=\n  (fun opcode => existT _\n                        (QuasiAbstractMachine.labelCount opcode)\n                        (QuasiAbstractMachine.fetch_rule opcode)).\nDefinition tini_faultHandler := @FaultRoutine.faultHandler observer ELatt\n                                                           labelCount\n                                                           (ifc_run_tmr fetch_rule)\n                                                           (LatticeConcreteLabels (fetch_rule_impl fetch_rule)).\nDefinition tini_match_states := match_states QuasiAbstractMachine.fetch_rule.\n\nProgram Definition concrete_abstract_ref :\n  refinement tini_concrete_machine AbstractMachine.abstract_machine :=\n  @ref_composition _ _ _\n                   concrete_quasi_abstract_ref\n                   quasi_abstract_abstract_ref\n                   (fun i1 i2 => @ac_match_initial_data _ _ _ _ _ fetch_rule i2 i1)\n                   (fun e1 e2 => match_events e2 e1)\n                   _ _.\n\nNext Obligation.\n  eauto.\nQed.\n\nEnd RefCA.\n", "meta": {"author": "micro-policies", "repo": "verified-ifc", "sha": "1ce5075b3a5580679feddb718d274d89fc7dd77f", "save_path": "github-repos/coq/micro-policies-verified-ifc", "path": "github-repos/coq/micro-policies-verified-ifc/verified-ifc-1ce5075b3a5580679feddb718d274d89fc7dd77f/basic_machines/RefinementCA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.2227630801975114}}
{"text": "Require Import Bool.\nRequire Import ZArith.\nRequire Import BinPos.\n\nRequire Import Axioms.\n\nRequire Import compcert_imports. Import CompcertCommon.\n\nRequire Import sepcomp. Import SepComp.\nRequire Import arguments.\n\nRequire Import rc_semantics.\n\nRequire Import ssreflect ssrbool ssrfun seq eqtype fintype.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport SM_simulation.\n\nSection rc_2lems.\n\nVariables F_S V_S F_T V_T : Type.\n\nVariables C D : Type.\n\nVariable eff_S : @EffectSem (Genv.t F_S V_S) C.\n\nVariable eff_T : @EffectSem (Genv.t F_T V_T) D.\n\nVariable ge_S : Genv.t F_S V_S.\n\nVariable ge_T : Genv.t F_T V_T.\n\nVariable sim : SM_simulation_inject eff_S eff_T ge_S ge_T.\n\nLemma rc_sim : \n  SM_simulation_inject (RC.effsem eff_S) eff_T ge_S ge_T.\nProof.\ncase: sim=> cd mtch ord (*d*) e f g h i j init step halt atext aftext. \neapply Build_SM_simulation_inject with\n       (core_data   := cd)\n       (core_ord    := ord)\n       (match_state := \n         fun cd mu c m d tm => \n           mtch cd mu (RC.core c) m d tm); eauto.\n{ move=> v vals1 c1 m1 j0 vals2 m2 dS dT.\nmove=> init1 inj vinj pres pres2 H I J K.\nhave [c1' init1']:\n  exists c1', initial_core eff_S ge_S v vals1 = Some c1'.\n{ move: init1; rewrite /= /RC.initial_core.\n  case x: (initial_core _ _ _ _)=> //.\n  by case; case: c1=> c ?; case=> -> _; exists c. }\nmove: (init v vals1 c1' m1 j0 vals2 m2 dS dT init1').\ncase/(_ inj vinj pres pres2 H I J K)=> x []c2' []init2' mtch12.\nexists x,c2'; split=> //.\nmove: init1; rewrite /= /RC.initial_core; rewrite init1'; case.\nby case: c1=> ? ?; case=> <- <- /=. }\n{ move=> st1 m1 st1' m1' U1 estep cd0 st2 mu m2 mtch12.\nmove: estep; rewrite /= /RC.effstep=> [][]estep []ctnd' locs.\nmove: (step (RC.core st1) m1 (RC.core st1') m1' U1 estep cd0).\ncase/(_ st2 mu m2 mtch12)=> st2' []m2' []cd' []mu'.\ncase=> incr (*[]sep*) []localloc []mtch12' []U2 []estep' trackback.\nexists st2',m2',cd',mu'=> /=.\nsplit=> //.\nsplit=> //.\nsplit=> //.\nsplit=> //.\nby exists estep'.                    \n(*by exists U2.*) }\n{ move=> cd0 mu c1 m1 c2 m2 v1 M; rewrite /= /RC.halted.\n  case hlt1: (halted _ _)=> //.\n  case def1: (vals_def _)=> //; case=> <-.\n  case: (halt _ _ _ _ _ _ _ M hlt1)=> v2 []? []? ?.\n  exists v2; split=> //. }                                         \n{ move=> cd0 mu c1 m1 c2 m2 e0 vals1 ef_sig mtch' at1.\nhave at1': at_external eff_S (RC.core c1) = Some (e0, ef_sig, vals1).\n{ move: at1; rewrite /= /RC.at_external.\n  by case q: (at_external _ _)=> [[[? ?] ?]|//]; case r: (vals_def _). }\ncase: (atext cd0 mu (RC.core c1) m1 c2 m2 e0 vals1 ef_sig mtch' at1').\nby move=> H H2; split. }\n{ move=> cd0 mu st1 st2 m1 e0 vals1 m2 sig vals2 e' ef_sig'.\nmove=> inj mtch' at1 at2 vinj pSrc' H pTgt' I nu J nu' ret1 m1' ret2 m2'.\nmove=> ty1 ty2 eincr sep wd val inj' vinj' fwd fwd' fS' K fT' L mu' M unch1 unch2.\nhave at1': at_external eff_S (RC.core st1) = Some (e0, sig, vals1).\n{ move: at1; rewrite /= /RC.at_external.\n  by case q: (at_external _ _)=> [[[? ?] ?]|//]; case r: (vals_def _). }\ncase: (aftext cd0 mu (RC.core st1) st2 m1 e0 vals1 m2 sig vals2 e' ef_sig'\n  inj mtch' at1' at2 vinj pSrc' H pTgt' I nu J nu' ret1 m1' ret2 m2'\n  ty1 ty2 eincr sep wd val inj' vinj' fwd fwd' fS' K fT' L mu' M unch1 unch2).\nmove=> cd' []st1' []st2' []aft1' []aft2' mtch12'.\nexists cd'.\nexists (RC.mk st1' [predU getBlocks [::ret1] & RC.locs st1]).\nexists st2'.\nsplit=> //.\nby rewrite /= /RC.after_external aft1'. }\nQed.\n\nEnd rc_2lems.\n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/linking/rc_semantics_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631556226291, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.22276307599239117}}
{"text": "Require Import Bool.\nRequire Import ZArith.\nRequire Import BinPos.\n\nRequire Import Axioms.\n\nRequire Import concurrency.compcert_imports. Import CompcertCommon.\n\nRequire Import concurrency.sepcomp. Import SepComp.\nRequire Import sepcomp.arguments.\n\nRequire Import concurrency.rc_semantics.\n\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun seq fintype.\nSet Implicit Arguments.\n\nImport SM_simulation.\n\nSection rc_2lems.\n\nVariables F_S V_S F_T V_T : Type.\n\nVariables C D : Type.\n\nVariable eff_S : @EffectSem (Genv.t F_S V_S) C.\n\nVariable eff_T : @EffectSem (Genv.t F_T V_T) D.\n\nVariable ge_S : Genv.t F_S V_S.\n\nVariable ge_T : Genv.t F_T V_T.\n\nVariable sim : SM_simulation_inject eff_S eff_T ge_S ge_T.\n\nLemma rc_sim :\n  SM_simulation_inject (RC.effsem eff_S) eff_T ge_S ge_T.\nProof.\ncase: sim=> cd mtch ord e f g genv_infos h i j init step halt atext aftext.\neapply Build_SM_simulation_inject with\n       (core_data   := cd)\n       (core_ord    := ord)\n       (match_state :=\n         fun cd mu c m d tm =>\n           mtch cd mu (RC.core c) m d tm); eauto.\n{ move=> v vals1 c1 m1 j0 vals2 m2 dS dT.\nmove=> init1 inj vinj pres pres2 H I resp1 resp2 J K.\nhave [c1' init1']:\n  exists c1', initial_core eff_S ge_S v vals1 = Some c1'.\n{ move: init1; rewrite /= /RC.initial_core.\n  case x: (initial_core _ _ _ _)=> //.\n  by case; case: c1=> c ?; case=> -> _; exists c. }\nmove: (init v vals1 c1' m1 j0 vals2 m2 dS dT init1').\ncase/(_ inj vinj pres pres2 H I resp1 resp2 J K)=> x []c2' []init2' mtch12.\nexists x,c2'; split=> //.\nmove: init1; rewrite /= /RC.initial_core; rewrite init1'; case.\nby case: c1=> ? ?; case=> <- <- /=. }\n{ move=> st1 m1 st1' m1' U1 estep cd0 st2 mu m2 mtch12.\nmove: estep; rewrite /= /RC.effstep=> [][]estep []ctnd' locs.\nmove: (step (RC.core st1) m1 (RC.core st1') m1' U1 estep cd0).\ncase/(_ st2 mu m2 mtch12)=> st2' []m2' []cd' []mu'.\ncase=> incr (*[]sep*) []localloc []mtch12' []U2 []estep' trackback.\nexists st2',m2',cd',mu'=> /=.\nsplit=> //.\nsplit=> //.\nsplit=> //.\nsplit=> //.\nby exists estep'.\n(*by exists U2.*) }\n{ move=> cd0 mu c1 m1 c2 m2 v1 M; rewrite /= /RC.halted.\n  case hlt1: (halted _ _)=> //.\n  case def1: (vals_def _)=> //; case=> <-.\n  case: (halt _ _ _ _ _ _ _ M hlt1)=> v2 []? []? ?.\n  exists v2; split=> //. }\n{ move=> cd0 mu c1 m1 c2 m2 e0 vals1 mtch' at1.\nhave at1': at_external eff_S (RC.core c1) = Some (e0, vals1).\n{ move: at1; rewrite /= /RC.at_external.\n  by case q: (at_external _ _)=> [[? ?]|//]; case r: (vals_def _). }\ncase: (atext cd0 mu (RC.core c1) m1 c2 m2 e0 vals1 mtch' at1').\nby move=> H H2; split. }\n{ move=> cd0 mu st1 st2 m1 e0 vals1 m2 vals2 e'.\nmove=> inj mtch' at1 at2 vinj pSrc' H pTgt' I nu J nu' ret1 m1' ret2 m2'.\nmove=> ty1 ty2 eincr sep wd val inj' vinj' fwd fwd' rdo rdo' fS' K fT' L mu' M unch1 unch2.\nhave at1': at_external eff_S (RC.core st1) = Some (e0, vals1).\n{ move: at1; rewrite /= /RC.at_external.\n  by case q: (at_external _ _)=> [[? ?]|//]; case r: (vals_def _). }\ncase: (aftext cd0 mu (RC.core st1) st2 m1 e0 vals1 m2 vals2 e'\n  inj mtch' at1' at2 vinj pSrc' H pTgt' I nu J nu' ret1 m1' ret2 m2'\n  ty1 ty2 eincr sep wd val inj' vinj' fwd fwd' rdo rdo' fS' K fT' L mu' M unch1 unch2).\nmove=> cd' []st1' []st2' []aft1' []aft2' mtch12'.\nexists cd'.\nexists (RC.mk st1' [predU getBlocks [::ret1] & RC.locs st1]).\nexists st2'.\nsplit=> //.\nby rewrite /= /RC.after_external aft1'. }\nQed.\n\nEnd rc_2lems.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/concurrency/rc_semantics_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.22275926247970904}}
{"text": "From mathcomp Require Import ssreflect ssrbool ssrnat eqtype ssrfun seq path.\nFrom Coq Require Import Eqdep Relation_Operators.\nFrom pcm Require Import pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL Require Import Freshness State EqTypeX Protocols Worlds NetworkSem.\nFrom DiSeL Require Import Rely Actions Injection Process Always.\nFrom DiSeL Require Import HoareTriples InferenceRules InductiveInv While.\nFrom DiSeL Require Import CalculatorProtocol CalculatorInvariant.\nFrom DiSeL Require Import CalculatorClientLib CalculatorServerLib.\nFrom DiSeL Require Import DelegatingCalculatorServer SimpleCalculatorServers.\n\nExport CalculatorProtocol.\n\nSection CalculatorApp.\n\nDefinition l1 := 1.\nDefinition l2 := 2.\nLemma lab_dis : l2 != l1. Proof. by []. Qed.\n\nDefinition f args :=\n  match args with\n  | x::y::_ => Some (x + y)\n  | _ => None\n  end.\n\nDefinition prec (args : input) :=\n  if args is x::y::_ then true else false.\n\nLemma prec_valid :\n  forall i, prec i -> exists v, f i = Some v.\nProof. by move=>i; case: i=>//=x; case=>//y _ _; eexists _. Qed.\n\n(* Two overlapping calculator systems *)\n(* System 1: one server, one client *)\nDefinition cs1 := [::1].\nDefinition cls1 := [::2].\n\n(* System 2: one server, one client *)\nDefinition cs2 := [::3].\nDefinition cls2 := [::1].\n\nNotation nodes1 := (cs1 ++ cls1).\nNotation nodes2 := (cs2 ++ cls2).\nLemma Huniq1 : uniq nodes1. Proof. by []. Qed.\nLemma Huniq2 : uniq nodes2. Proof. by []. Qed.\n\n(* Protocol I'm a server in *)\nNotation cal1 := (cal_with_inv l1 f prec cs1 cls1).\nNotation cal2 := (cal_with_inv l2 f prec cs2 cls2).\n\nNotation W1 := (mkWorld cal1).\nNotation W2 := (mkWorld cal2).\n\n(* Composite world *)\nDefinition V := W1 \\+ W2.\nLemma validV : valid V.\nProof.\nrewrite /V; apply/andP=>/=.\nsplit; first by rewrite validPtUn/= validPt/= domPt inE/=.\nby rewrite unitR valid_unit.\nQed.\n\n(* This server node *)\nDefinition sv : nid := 1.\nDefinition cl : nid := 2.\n(* It's a server in protocol cal1 *)\nLemma  Hs1 : sv \\in cs1. Proof. by []. Qed.\n(* It's a client in protocol cal2 *)\nLemma  Hc2 : sv \\in cls2. Proof. by []. Qed.\nLemma Hc1 : cl \\in cls1. Proof. by []. Qed.\n(* Delegate server *)\nDefinition sd := 3.\nLemma Hs2 : sd \\in cs2. Proof. by []. Qed.\n\nNotation loc i k := (getLocal sv (getStatelet i k)).\nNotation loc1 i := (loc i l1).\nNotation loc2 i := (loc i l2).\n\n(****************************************************)\n(***********        Initial state     ***************)\n(****************************************************)\n\nDefinition init_loc := st :-> ([::] : reqs).\n\nDefinition init_dstate1 := sv \\\\-> init_loc \\+ cl \\\\-> init_loc.\nDefinition init_dstate2 := sv \\\\-> init_loc \\+ sd \\\\-> init_loc.\n\nLemma valid_init_dstate1 : valid init_dstate1.\nProof.\ncase: validUn=>//=;\ndo?[case: validUn=>//; do?[rewrite ?validPt/=//]|by rewrite validPt/=].\nby move=>k; rewrite !domPt !inE/==>/eqP<-/eqP.\nQed.\n\nLemma valid_init_dstate2 : valid init_dstate2.\nProof.\ncase: validUn=>//=;\ndo?[case: validUn=>//; do?[rewrite ?validPt/=//]|by rewrite validPt/=].\nby move=>k; rewrite !domPt !inE/==>/eqP<-/eqP.\nQed.\n\nNotation init_dstatelet1 := (DStatelet init_dstate1 Unit).\nNotation init_dstatelet2 := (DStatelet init_dstate2 Unit).\n\nDefinition init_state : state :=\n  l1 \\\\-> init_dstatelet1 \\+ l2 \\\\-> init_dstatelet2.\n\nLemma validI : valid init_state.\nProof.\ncase: validUn=>//=; do?[case: validUn=>//;\n  do?[rewrite ?gen_validPt/=//]|by rewrite validPt/=];\n  by move=>k; rewrite !domPt !inE/==>/eqP<-/eqP.\nQed.\n\nLemma coh1': calcoh prec cs1 cls1 init_dstatelet1 /\\\n             CalcInv l1 f prec cs1 cls1 init_dstatelet1.\nProof.\nsplit; last by move=>?????????/=/esym/unitbP/=; rewrite um_unitbPtUn.\nsplit=>//; rewrite ?valid_init_dstate1//.\n- split; first by rewrite valid_unit.\n  by move=>m ms; rewrite find0E.\n- move=>z; rewrite /=/init_dstate1 domUn !inE/= valid_init_dstate1/=.\n  by rewrite !domPt !inE !(eq_sym z).\nmove=>n/=; rewrite inE=>/orP; case=>//=.\n- move/eqP=>->/=; exists [::]=>/=.\n  rewrite /getLocal/init_dstate1/= findUnL?valid_init_dstate1//.\n  by rewrite domPt/= findPt/=.\nrewrite inE=>/eqP=>->; exists [::]=>/=.\nrewrite /getLocal/init_dstate1/= findUnL?valid_init_dstate1//.\nby rewrite domPt/= findPt.\nQed.\n\nLemma coh1 : l1 \\\\-> init_dstatelet1 \\In Coh W1.\nProof.\nsplit=>//.\n- apply/andP; split; last by rewrite valid_unit.\n  by rewrite ?validPt.\n- by rewrite validPt/=.\n- by apply: hook_complete_unit.\n- by move=>z; rewrite !domPt !inE/=.\nmove=>k; case B: (l1==k); last first.\n- have X: (k \\notin dom W1.1).\n    by rewrite /init_state/W1/=!domPt !inE/=; move/negbT: B.\n  by rewrite /getProtocol /getStatelet/= ?findPt2 eq_sym !B/=.\nmove/eqP:B=>B; subst k; rewrite prEq/getStatelet/init_state findPt/=.\nexact: coh1'.\nQed.\n\nLemma coh2' : calcoh prec cs2 cls2 init_dstatelet2 /\\\n              CalcInv l2 f prec cs2 cls2 init_dstatelet2.\nProof.\nsplit; last by move=>?????????/=/esym/unitbP/=; rewrite um_unitbPtUn.\nsplit=>//; rewrite ?valid_init_dstate2//.\n- split; first by rewrite valid_unit.\n  by move=>m ms; rewrite find0E//.\n- move=>z; rewrite /=/init_dstate2 domUn !inE/= valid_init_dstate2//=.\n  by rewrite !domPt !inE !(eq_sym z) orbC.\nmove=>n/=; rewrite inE=>/orP; case=>//=.\n- move/eqP=>->/=; exists [::]=>/=.\n  rewrite /getLocal/init_dstate2/= findUnL?valid_init_dstate2//.\n  by rewrite domPt/= findPt/=.\nrewrite inE=>/eqP=>->; exists [::]=>/=.\nrewrite /getLocal/init_dstate2/= findUnL?valid_init_dstate2//.\nby rewrite domPt/= findPt.\nQed.\n\nLemma coh2 : l2 \\\\-> init_dstatelet2 \\In Coh W2.\nProof.\nsplit.\n- apply/andP; split; last by rewrite valid_unit.\n  by rewrite ?validPt.\n- by rewrite validPt/=.\n- by apply: hook_complete_unit.\n- by move=>z; rewrite !domPt !inE/=.\nmove=>k; case B: (l2==k); last first.\n- have X: (k \\notin dom W2.1).\n    by rewrite /init_state/W2/=!domPt !inE/=; move/negbT: B.\n  by rewrite /getProtocol /getStatelet/= ?findPt2 eq_sym !B/=.\nmove/eqP:B=>B; subst k; rewrite prEq/getStatelet/init_state findPt/=.\nexact: coh2'.\nQed.\n\nLemma init_coh : init_state \\In Coh V.\nProof.\nsplit=>//; first by apply: validV.\n- by apply: validI.\n- rewrite /V/=/init_state/==>z.\n- by move=>???; rewrite domUn !inE/= dom0 andbC.\n- rewrite /V/init_state=>z; rewrite !domUn !inE; case/andP:validV=>->_/=.\n  by rewrite validI/= !domPt.\nmove=>k; case B: ((l1 == k) || (l2 == k)); last first.\n- have X: (k \\notin dom V.1).\n  + by rewrite /V domUn inE/= !domPt!inE/= B andbC.\n  rewrite /getProtocol /getStatelet/=.\n  case: dom_find (X)=>//->_/=; rewrite /init_state.\n  case/negbT/norP: B=>/negbTE N1/negbTE N2.\n  rewrite findUnL; rewrite ?validI// domPt inE N1.\n  rewrite findPt2 eq_sym N1/=.\n  by rewrite findPt2 eq_sym N2/=.\ncase/andP: validV=>V1 V2.\ncase/orP:B=>/eqP Z; subst k;\nrewrite /getProtocol/V findUnL/= ?V1 ?domPt ?inE/= ?findPt;\nrewrite /getStatelet ?findUnL/= ?validI// ?domPt ?inE/= ?findPt;\n[by case: coh1'|by case coh2'].\nQed.\n\n(****************************************************)\n(***********    Runnable programs     ***************)\n(****************************************************)\n\nDefinition client_input :=\n  [:: [::1; 2]; [::3; 4]; [::5; 6]; [::7; 8]; [::9; 10]].\n\nDefinition compute_input := compute_list_f l1 f prec cs1 cls1 cl Hc1 sv.\n\n(* [C] A simple client, evaluating a serives of requests *)\nProgram Definition client_run (u : unit) :\n  DHT [cl, V]\n   (fun i => network_rely V cl init_state i,\n   fun (res : seq (input * nat)) m =>\n     [/\\ all (fun e => f e.1 == Some e.2) res &\n      client_input = map fst res]) :=\n  Do (uinject (compute_input client_input)).\n\nNext Obligation.\nrewrite -(unitR V)/V.\nhave V: valid (W1 \\+ W2 \\+ Unit) by rewrite unitR validV.\napply: (injectL V); do?[apply: hook_complete_unit | apply: hooks_consistent_unit].\nby move=>??????; rewrite dom0.\nQed.\n\nNext Obligation.\nmove=>i/=R.\nhave X: injects W1 V Unit.\n- move: (@injectL W1 W2 Unit)=>/=; rewrite !unitR =>H.\n  apply: H=>//; do? [by apply: hook_complete0].\n  + by rewrite -[Unit]unitR; move: validV.\n  by move=>l _=>????; rewrite dom0.\ncase: (rely_ext X coh1 R)=>i1[j1][Z]C'; subst i.\napply: inject_rule=>//.\napply: call_rule=>C1{C'}/=; last by move=>m[H1]H2 H3.\nhave E: (getStatelet i1 l1) = (getStatelet (i1 \\+ j1) l1).\n- by rewrite (locProjL (proj2 (rely_coh R)) _ C1)=>//; rewrite /W1 domPt.\nrewrite E (rely_loc' _ R)/getLocal/=/getStatelet/=.\nrewrite findUnL ?validI// domPt inE eqxx findPt/=.\nby rewrite /init_dstate1 findUnR?valid_init_dstate1// domPt/= findPt/=.\nQed.\n\n(* [S1] Delegating server, serving the client's needs *)\nDefinition delegating_server (u : unit) :=\n  delegating_server_loop l1 l2 lab_dis f prec cs1 cls1 cs2 cls2 sv\n                         Hs1 Hc2 sd Hs2.\n\nProgram Definition server1_run (u : unit) :\n  DHT [sv, V]\n   (fun i => network_rely V sv init_state i,\n   fun (res : unit) m => False) :=\n  Do (delegating_server u).\nNext Obligation.\nmove=>i/=R; apply: call_rule=>C1//=.\nrewrite (rely_loc' _ R)/getLocal/=/getStatelet/=.\nrewrite findUnL ?validI ?valid_init_dstate1//.\nrewrite domPt inE eqxx findPt/=.\nrewrite findUnR ?validI ?valid_init_dstate1//=.\nrewrite domPt inE/= findPt/=; split=>//.\nrewrite -(rely_loc _ R)/=/getStatelet findUnR ?validI ?valid_init_dstate1//=.\nrewrite domPt inE/= findPt/= /init_dstate2/=.\nrewrite findUnL ?validI ?valid_init_dstate2//.\nby rewrite domPt inE/= findPt/= /init_dstate2/=.\nQed.\n\n(* [S2] A memoizing server, serving as a delegate *)\n\nDefinition secondary_server (u : unit) :=\n  with_inv (ii l2 f prec cs2 cls2)\n           (memoizing_server l2 f prec prec_valid cs2 cls2 sd Hs2).\n\nProgram Definition server2_run (u : unit) :\n  DHT [sd, V]\n   (fun i => network_rely V sd init_state i,\n    fun (res : unit) m => False) :=\n  Do _ (@inject sd W2 V Unit _ _ (secondary_server u);; ret _ _ tt).\n\nNext Obligation.\nrewrite -(unitR V)/V.\nhave V: valid (W1 \\+ W2 \\+ Unit) by rewrite unitR validV.\napply: (injectR V); do?[apply: hook_complete_unit | apply: hooks_consistent_unit].\nby move=>??????; rewrite dom0.\nQed.\n\nNext Obligation.\nmove=>i/=R; apply: step.\nrewrite /init_state joinC.\n\nhave X: injects W2 V Unit.\n- move: (@injectL W2 W1 Unit)=>/=; rewrite !unitR=>H.\n  rewrite /V joinC;apply: H=>//; do? [by apply: hook_complete0].\n  + by rewrite joinC -[Unit]unitR; move: validV.\n  by move=>l _=>????; rewrite dom0.\nrewrite /V joinC in R X; rewrite /init_state [l1 \\\\->_ \\+ _]joinC in R.\ncase: (rely_ext X coh2 R)=>j1[i1][Z]C'; subst i.\napply: inject_rule=>//=.\napply: with_inv_rule; apply:call_rule=>//_.\nhave E: (getStatelet j1 l2) = (getStatelet (j1 \\+ i1) l2).\n- by rewrite (locProjL (proj2 (rely_coh R)) _ C')=>//; rewrite /W1 domPt.\nrewrite E (rely_loc' _ R)/getLocal/=/getStatelet/=.\nrewrite findUnL ?validI//; last by rewrite joinC validI.\nrewrite domPt/= findPt/=.\nby rewrite /init_dstate2 findUnL ?valid_init_dstate2 ?domPt/= ?findPt.\nQed.\n\nEnd CalculatorApp.\n\n(***************************************************)\n(* Now all three programs run in the same world!   *)\n(***************************************************)\n\nDefinition c_runner (u : unit) := client_run u.\nDefinition s_runner1 (u : unit) := server1_run u.\nDefinition s_runner2 (u : unit) := server2_run u.\n", "meta": {"author": "DistributedComponents", "repo": "disel", "sha": "88dc15450394a5963f513d220001b49389c6b52f", "save_path": "github-repos/coq/DistributedComponents-disel", "path": "github-repos/coq/DistributedComponents-disel/disel-88dc15450394a5963f513d220001b49389c6b52f/theories/Examples/Calculator/SimpleCalculatorApp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283033, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.222759262479709}}
{"text": "Require Import Rel.Definitions.\nRequire Import Rel.BasicFacts.\nRequire Import Rel.Compat_weaken_X.\nRequire Import Util.Subset.\nRequire Import Lang.BindingsFacts.\nRequire Import Lang.Static.\nSet Implicit Arguments.\n\nSection section_ccompat_tm_down.\nContext (EV HV : Set).\nContext (Ξ : XEnv EV HV).\nContext (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig).\nContext (ρ₁ ρ₂ : HV → hd0) (ρ : HV → IRel 𝓣_Sig).\nContext (X : var).\nContext (T : ty EV HV ∅) (𝓔 : eff EV HV ∅).\n\nHint Resolve postfix_refl.\nHint Rewrite in_singleton.\n\nLemma ccompat_tm_down_aux n :\nn ⊨ ( ∀ᵢ ξ₁' ξ₂' t₁' t₂' ψ Xs₁ Xs₂,\n      𝓤⟦ (Ξ & X ~ (T, 𝓔)) ⊢ 𝓔 ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁' ξ₂' t₁' t₂' ψ Xs₁ Xs₂ ⇒\n      (X ∉ Xs₁ ∧ X ∉ Xs₂)ᵢ\n    ) →\nn ⊨ ∀ᵢ ζ₁ ζ₂ ξ₁ ξ₂ t₁ t₂,\n    𝓣⟦ Ξ & (X ~ (T,𝓔)) ⊢ T # (ef_lbl (lbl_id (lid_f X))) :: 𝓔 ⟧\n      δ₁ δ₂ δ ρ₁ ρ₂ ρ\n      (ζ₁ ++ X :: ξ₁) (ζ₂ ++ X :: ξ₂) t₁ t₂ ⇒\n    𝓣⟦ Ξ & (X ~ (T,𝓔)) ⊢ T # 𝓔 ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ\n      (ζ₁ ++ X :: ξ₁) (ζ₂ ++ X :: ξ₂)\n      (ktx_plug (ktx_down ktx_hole X) t₁)\n      (ktx_plug (ktx_down ktx_hole X) t₂).\nProof.\nintro FrX.\nloeb_induction LöbIH.\niintro ζ₁ ; iintro ζ₂ ; iintro ξ₁ ; iintro ξ₂ ; iintro t₁ ; iintro t₂ ; iintro Ht.\napply plug1 with\n  (ε := ef_lbl (lbl_id (lid_f X))) (Ta := T) (ξ₁ := ζ₁ ++ X :: ξ₁) (ξ₂ := ζ₂ ++ X :: ξ₂).\n+ exact FrX.\n+ iintro ξ₁' ; iintro ξ₂' ; iintro v₁ ; iintro v₂ ;\n  iintro Hξ₁' ; iintro Hξ₂' ; iintro Hv.\n  ielim_prop Hξ₁' ; ielim_prop Hξ₂'.\n  eapply 𝓣_step_r.\n  { simpl.\n    apply step_down_val.\n  }\n  eapply 𝓣_step_l.\n  { simpl.\n    apply step_down_val.\n  }\n  iintro_later.\n  apply 𝓥_in_𝓣 ; apply Hv.\n+ clear - LöbIH.\n  iintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂'.\n  iintro K₁ ; iintro K₂ ;\n  iintro s₁ ; iintro s₂ ; iintro ψ ; iintro Xs₁ ; iintro Xs₂.\n  iintro H.\n  iintro Xs_K₁K₂.\n  iintro Hw.\n  ielim_prop Hξ₁' ; ielim_prop Hξ₂'.\n  ielim_prop Xs_K₁K₂.\n\n  idestruct H as 𝔽 H ;\n  idestruct H as X₁ H ; idestruct H as X₂ H ;\n  idestruct H as h₁ H ; idestruct H as h₂ H ;\n  idestruct H as v₁ H ; idestruct H as v₂ H ;\n  idestruct H as Hρ₁ρ₂ H ;\n  idestruct H as Hs₁s₂ H ; idestruct H as HXs₁Xs₂ H ; idestruct H as Hr H ;\n  idestruct H as Hv Hψ.\n\n  ielim_prop Hρ₁ρ₂ ; destruct Hρ₁ρ₂ as [Hρ₁ Hρ₂].\n  ielim_prop Hs₁s₂ ; destruct Hs₁s₂ as [Hs₁ Hs₂].\n  ielim_prop HXs₁Xs₂ ; destruct HXs₁Xs₂ as [HXs₁ HXs₂].\n  simpl in Hρ₁, Hρ₂ ; inversion Hρ₁ ; inversion Hρ₂ ; clear Hρ₁ Hρ₂.\n  subst s₁ s₂ Xs₁ Xs₂ X₁ X₂.\n\n  idestruct Hr as r₁ Hr ; idestruct Hr as r₂ Hr ; idestruct Hr as H_r₁r₂ Hr.\n  ielim_prop H_r₁r₂ ; destruct H_r₁r₂ as [H_r₁ H_r₂].\n  subst h₁ h₂.\n\n  idestruct Hr as _T Hr ; idestruct Hr as _𝓔 Hr ; idestruct Hr as _BindsX Hr.\n  ielim_prop _BindsX.\n  apply binds_concat_inv in _BindsX.\n  destruct _BindsX as [ _BindsX | [ H1 H2 ] ] ;\n  [ | rewrite dom_single in H1 ; apply notin_same in H1 ; contradict H1 ].\n  apply binds_single_inv in _BindsX.\n  destruct _BindsX as [ _ H' ] ; inversion H' ; clear H' ; subst _T _𝓔.\n\n  simpl.\n  specialize (Xs_K₁K₂ X).\n  assert (tunnels X K₁) ; [ crush | ].\n  assert (tunnels X K₂) ; [ crush | ].\n  eapply 𝓣_step_r.\n  { apply step_down_up ; eauto. }\n  eapply 𝓣_step_l.\n  { apply step_down_up ; eauto. }\n  later_shift.\n\n  ispecialize Hr ξ₁' ; ispecialize Hr ξ₂'.\n  ispecialize Hr ; [ auto | ].\n  ispecialize Hr ; [ auto | ].\n  iespecialize Hr.\n  ispecialize Hr ; [ apply Hv | ].\n  erewrite I_iff_elim_M ; [ | apply fold_𝓥𝓤_in_𝓣 ].\n  iapply Hr.\n\n  clear - LöbIH Hψ Hw Hξ₁' Hξ₂'.\n  iintro ξ₁'' ; iintro ξ₂'' ; iintro u₁ ; iintro u₂ ;\n  iintro Hξ₁'' ; iintro  Hξ₂'' ; iintro Hu.\n  ispecialize Hψ ξ₁'' ; ispecialize Hψ ξ₂''.\n  iespecialize Hψ ; idestruct Hψ as Hψ Hψr ; clear Hψr.\n  ispecialize Hψ.\n  { iintro_later ; repeat ieexists ; isplit.\n    + iintro_prop ; split ; reflexivity.\n    + eassumption.\n  }\n  iespecialize Hw.\n  ispecialize Hw ; [ apply Hξ₁'' | ].\n  ispecialize Hw ; [ apply Hξ₂'' | ].\n  ispecialize Hw ; [ apply Hψ | ].\n\n  later_shift.\n  erewrite <- I_iff_elim_M ; [ | apply fold_𝓥𝓤_in_𝓣 ].\n\n  simpl ktx_plug in LöbIH.\n  ielim_prop Hξ₁'' ; ielim_prop Hξ₂''.\n  apply postfix_inv_app in Hξ₁'' ; destruct Hξ₁'' as [ ζ₁'' Hξ₁'' ].\n  apply postfix_inv_app in Hξ₂'' ; destruct Hξ₂'' as [ ζ₂'' Hξ₂'' ].\n  apply postfix_inv_app in Hξ₁' ; destruct Hξ₁' as [ ζ₁' Hξ₁' ].\n  apply postfix_inv_app in Hξ₂' ; destruct Hξ₂' as [ ζ₂' Hξ₂' ].\n  ispecialize LöbIH (ζ₁'' ++ ζ₁' ++ ζ₁) ;\n  ispecialize LöbIH (ζ₂'' ++ ζ₂' ++ ζ₂) ;\n  ispecialize LöbIH ξ₁ ;\n  ispecialize LöbIH ξ₂.\n  repeat rewrite <- app_assoc in LöbIH.\n  rewrite <- Hξ₁', <- Hξ₂', <- Hξ₁'', <- Hξ₂'' in LöbIH.\n  iespecialize LöbIH.\n  ispecialize LöbIH ; [ apply Hw | ].\n  apply LöbIH.\n+ crush.\n+ crush.\n+ assumption.\nQed.\n\nContext (FrX_Ξ : X # Ξ).\nContext (Wf_Ξ : wf_XEnv Ξ).\nContext (Wf_T : wf_ty Ξ T).\nContext (Wf_𝓔 : wf_eff Ξ 𝓔).\n\nHint Constructors wf_XEnv.\n\nLemma ccompat_tm_down n ξ₁ ξ₂ t₁ t₂ :\nn ⊨ ( ∀ᵢ ξ₁' ξ₂' t₁' t₂' ψ Xs₁ Xs₂,\n      𝓤⟦ (Ξ & X ~ (T, 𝓔)) ⊢ 𝓔 ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁' ξ₂' t₁' t₂' ψ Xs₁ Xs₂ ⇒\n      (X ∉ Xs₁ ∧ X ∉ Xs₂)ᵢ\n    ) →\nX ∉ from_list ξ₁ → X ∉ from_list ξ₂ →\nn ⊨ 𝓣⟦ (Ξ & (X ~ (T, 𝓔))) ⊢ T # (ef_lbl (lbl_id (lid_f X))) :: 𝓔 ⟧\n    δ₁ δ₂ δ ρ₁ ρ₂ ρ\n    (X :: ξ₁) (X :: ξ₂)\n    (L_subst_tm (lid_f X) t₁) (L_subst_tm (lid_f X) t₂) →\nn ⊨ 𝓣⟦ Ξ ⊢ T # 𝓔 ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ (⬇ t₁) (⬇ t₂).\nProof.\nintros FrX_𝓔 FrX_ξ₁ FrX_ξ₂ Ht.\nspecialize (ccompat_tm_down_aux FrX_𝓔) as H.\nispecialize H ([] : list var).\nispecialize H ([] : list var).\niespecialize H.\nrepeat rewrite app_nil_l in H.\nsimpl ktx_plug in H.\n\neapply 𝓣_step_r.\n{ apply step_Down with (X := X) ; assumption. }\neapply 𝓣_step_l.\n{ apply step_Down with (X := X) ; assumption. }\n\niintro_later.\niespecialize H ; ispecialize H ; [ apply Ht | ].\nerewrite I_iff_elim_M ; [ apply H | apply X_weaken_𝓣 ] ; crush.\nQed.\n\nEnd section_ccompat_tm_down.\n\n\nSection section_compat_tm_down.\nContext (n : nat).\nContext (EV HV V : Set).\nContext (Ξ : XEnv EV HV).\nContext (P : HV → F).\nContext (Γ : V → ty EV HV ∅).\nContext (Wf_Γ : wf_Γ Ξ Γ).\nContext (t₁ t₂ : tm EV HV V (inc ∅)).\nContext (T : ty EV HV ∅) (𝓔 : eff EV HV ∅).\nContext (Wf_Ξ : wf_XEnv Ξ).\nContext (Wf_T : wf_ty Ξ T).\nContext (Wf_𝓔 : wf_eff Ξ 𝓔).\n\nHint Resolve subset_union_l subset_union_r postfix_refl.\nHint Resolve 𝓥_monotone.\nHint Rewrite in_union.\nHint Constructors wf_XEnv postfix.\n\nLemma compat_tm_down (B : vars) :\n( ∀ X, X \\notin B →\n  n ⊨ ⟦ (Ξ & (X ~ (T, 𝓔))) P Γ ⊢\n        (L_subst_tm (lid_f X) t₁) ≼ˡᵒᵍ (L_subst_tm (lid_f X) t₂) :\n        T # (ef_lbl (lbl_id (lid_f X))) :: 𝓔 ⟧\n) →\nn ⊨ ⟦ Ξ P Γ ⊢ (⬇ t₁) ≼ˡᵒᵍ (⬇ t₂) : T # 𝓔 ⟧.\nProof.\nintro Ht.\niintro ξ₁ ; iintro ξ₂ ; iintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ; iintro γ₁ ; iintro γ₂.\npick_fresh_gen (from_list ξ₁ \\u from_list ξ₂ \\u B) X.\nassert (X ∉ B) as FrB ; [ crush | ].\nspecialize (Ht X FrB).\niintro Hξ ; iintro cl_δ ; iintro cl_ρ₁ρ₂ ; iintro Hρ ; iintro Hγ.\nielim_prop Hξ ; ielim_prop cl_ρ₁ρ₂.\nspecialize Hξ as Hξ_copy ; destruct Hξ_copy as [Hξ₁ Hξ₂].\n\nassert (X ∉ from_list ξ₁) as Frξ₁ ; [ crush | ].\nassert (X ∉ from_list ξ₂) as Frξ₂ ; [ crush | ].\nassert (X ∉ dom Ξ) as FrΞ ; [ intro ; crush | ].\n\nispecialize Ht (X :: ξ₁) ; ispecialize Ht (X :: ξ₂).\nispecialize Ht δ₁ ; ispecialize Ht δ₂ ; ispecialize Ht δ.\nispecialize Ht ρ₁ ; ispecialize Ht ρ₂ ; ispecialize Ht ρ.\nispecialize Ht γ₁ ; ispecialize Ht γ₂.\nispecialize Ht.\n{ iintro_prop ; split ; [ clear - Hξ₁ | clear - Hξ₂ ] ;\n  rewrite dom_concat, from_list_cons, dom_single, union_comm ;\n  apply subset_union_2 ; crush.\n}\nispecialize Ht.\n{ repeat iintro ; iespecialize cl_δ ; ispecialize cl_δ ; [ eassumption | ].\n  repeat rewrite from_list_cons ; ielim_prop cl_δ.\n  crush.\n}\nispecialize Ht.\n{ iintro_prop ; intros α Y ; specialize (cl_ρ₁ρ₂ α Y) ;\n  clear - cl_ρ₁ρ₂ ; repeat rewrite from_list_cons ; crush.\n}\nispecialize Ht.\n{ eapply 𝑷_monotone ; eauto. }\nispecialize Ht.\n{ iintro x ; ispecialize Hγ x ; clear - Wf_Ξ Wf_Γ Wf_T Wf_𝓔 FrΞ Hγ.\n  erewrite <- I_iff_elim_M ; [ | apply X_weaken_𝓥 ] ; eauto.\n}\n\nsimpl.\napply ccompat_tm_down with (X := X) ; try assumption.\n+ iintro ξ₁' ; iintro ξ₂' ;\n  iintro s₁ ; iintro s₂ ; iintro ψ ; iintro Xs₁ ; iintro Xs₂ ; iintro Hs.\n  erewrite <- I_iff_elim_M in Hs ; [ | apply X_weaken_𝓤 ; crush ].\n  iintro_prop.\n  assert (Xs₁ \\c from_list ξ₁ ∧ Xs₂ \\c from_list ξ₂) as HXs₁Xs₂.\n  { eapply Xs_is_𝓤_bounded ; eassumption. }\n  clear - HXs₁Xs₂ Frξ₁ Frξ₂.\n  destruct HXs₁Xs₂.\n  split ; intro ; auto.\n+ clear - Ht.\n  repeat erewrite <- V_L_bind_tm, <- HV_L_bind_tm, <- EV_L_bind_tm.\n  { apply Ht. }\n  { intro ; unfold compose.\n    erewrite L_bind_map_eff, L_bind_eff_id, L_map_eff_id ; crush. }\n  { intro ; unfold compose.\n    erewrite L_bind_map_hd, L_bind_hd_id, L_map_hd_id ; crush. }\n  { intro ; unfold compose.\n    erewrite L_bind_map_val, L_bind_val_id, L_map_val_id ; crush. }\n  { intro ; unfold compose.\n    erewrite L_bind_map_eff, L_bind_eff_id, L_map_eff_id ; crush. }\n  { intro ; unfold compose.\n    erewrite L_bind_map_hd, L_bind_hd_id, L_map_hd_id ; crush. }\n  { intro ; unfold compose.\n    erewrite L_bind_map_val, L_bind_val_id, L_map_val_id ; crush. }\n\nQed.\n\nEnd section_compat_tm_down.\n", "meta": {"author": "yizhouzhang", "repo": "abseff-coq", "sha": "129c08fde2b4e41b5348db397c8a8f0e30f14cb5", "save_path": "github-repos/coq/yizhouzhang-abseff-coq", "path": "github-repos/coq/yizhouzhang-abseff-coq/abseff-coq-129c08fde2b4e41b5348db397c8a8f0e30f14cb5/coq-src/ABS/Rel/Compat_tm_down.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22266021582819526}}
{"text": "Require Import Kami.All Kami.Compiler.Compiler.\nRequire Import Kami.Notations.\nRequire Import Kami.Compiler.CompilerSimple.\n\nSection SemSimple.\n  Local Notation UpdRegT := RegsT.\n  Local Notation UpdRegsT := (list UpdRegT).\n\n  Local Notation RegMapType := (RegsT * UpdRegsT)%type.\n  \n  Inductive Sem_RmeSimple: (RmeSimple type RegMapType) -> RegMapType -> Prop :=\n  | SemVarRME v:\n      Sem_RmeSimple (VarRME _ v) v\n  | SemUpdRegRMETrue r (pred: Bool @# type) k val regMap\n                  (HPredTrue: evalExpr pred = true)\n                  old upds\n                  (HSem_RmeSimple : Sem_RmeSimple regMap (old, upds))\n                  upds'\n                  (HEqual : upds' = (hd nil upds ++ ((r, existT _ k (evalExpr val)) :: nil)) :: tl upds):\n      Sem_RmeSimple (@UpdRegRME _ _ r pred k val regMap) (old, upds')\n  | SemUpdRegRMEFalse r (pred: Bool @# type) k val regMap\n                   (HPredFalse: evalExpr pred = false)\n                   old upds\n                   (HSem_RmeSimple: Sem_RmeSimple regMap (old, upds)):\n      Sem_RmeSimple (@UpdRegRME _ _ r pred k val regMap) (old, upds)\n  | SemWriteRMESome idxNum num writePort dataArray idx Data val optMask mask pred writeMap readMap arr old upds\n                      (HMask : optMask = Some mask)\n                      (HUpdate : Sem_RmeSimple\n                                   (UpdRegRME dataArray pred\n                                           (fold_left (fun newArr i =>\n                                                         ITE\n                                                           (ReadArrayConst mask i)\n                                                           (UpdateArray newArr\n                                                                        (CABit Add (idx :: Const type (natToWord _ (proj1_sig (Fin.to_nat i)))\n                                                                                        :: nil))\n                                                                        (ReadArrayConst val i))\n                                                           newArr\n                                                      ) (getFins num)\n                                                      arr)\n                                           writeMap) (old, upds)):\n                      Sem_RmeSimple (@WriteRME _ _ idxNum num writePort dataArray idx Data val optMask pred writeMap readMap arr) (old, upds)\n  | SemWriteRMENone idxNum num writePort dataArray idx Data val optMask pred writeMap readMap arr old upds\n                      (HMask : optMask = None)\n                      (HUpdate : Sem_RmeSimple\n                                   (UpdRegRME dataArray pred\n                                              (fold_left (fun newArr i =>\n                                                            (UpdateArray newArr\n                                                                         (CABit Add (idx :: Const type (natToWord _ (proj1_sig (Fin.to_nat i)))\n                                                                                         :: nil))\n                                                                         (ReadArrayConst val i))\n                                                         ) (getFins num)\n                                                         arr)\n                                              writeMap) (old, upds)):\n                      Sem_RmeSimple (@WriteRME _ _ idxNum num writePort dataArray idx Data val optMask pred writeMap readMap arr) (old, upds)\n  | SemReadReqRMETrue idxNum num readReq readReg dataArray idx Data isAddr pred writeMap readMap arr old upds\n                   (HisAddr : isAddr = true)\n                   (HWriteMap : Sem_RmeSimple (UpdRegRME readReg pred (Var type (SyntaxKind _) (evalExpr idx)) writeMap) (old, upds)):\n                   Sem_RmeSimple (@ReadReqRME _ _ idxNum num readReq readReg dataArray idx Data isAddr pred writeMap readMap arr) (old, upds)\n  | SemReadReqRMEFalse idxNum num readReq readReg dataArray idx Data isAddr pred writeMap readMap arr old upds\n                   (HisAddr : isAddr = false)\n                   (HWriteMap : Sem_RmeSimple\n                                  (UpdRegRME readReg pred\n                                             (BuildArray (fun i : Fin.t num =>\n                                                            ReadArray\n                                                              arr\n                                                              (CABit Add (Var type (SyntaxKind _) (evalExpr idx) ::\n                                                                              Const type (natToWord _ (proj1_sig (Fin.to_nat i)))::nil))))\n                                             writeMap) (old, upds)):\n      Sem_RmeSimple (@ReadReqRME _ _ idxNum num readReq readReg dataArray idx Data isAddr pred writeMap readMap arr) (old, upds)\n  | SemReadRespRME idxNum num readResp readReg dataArray writePort isWriteMask Data isAddr writeMap readMap old upds\n                       (HWriteMap : Sem_RmeSimple writeMap (old, upds)):\n      Sem_RmeSimple (@ReadRespRME _ _ idxNum num readResp readReg dataArray writePort isWriteMask Data isAddr writeMap readMap) (old, upds)\n  | SemAsyncReadRME (idxNum num : nat) (readPort dataArray : string) writePort isWriteMask (idx : Bit (Nat.log2_up idxNum) @# type) (pred : Bool @# type) (k : Kind) (writeMap readMap : RmeSimple type RegMapType)\n                 old upds (HNoOp : Sem_RmeSimple writeMap (old, upds)):\n      Sem_RmeSimple (@AsyncReadRME _ _ idxNum num readPort dataArray writePort isWriteMask idx pred k writeMap readMap) (old, upds)\n  | SemCompactRME old upds regMap (HSemRegMap: Sem_RmeSimple regMap (old, upds)):\n      Sem_RmeSimple (@CompactRME _ _ regMap) (old, nil::upds).\n\n  Definition WfRmeSimple (regMapExpr : RmeSimple type RegMapType) (regMap : RegMapType) :=\n    Sem_RmeSimple regMapExpr regMap /\\\n    let '(old, new) := regMap in\n    forall u, In u new -> NoDup (map fst u) /\\ SubList (getKindAttr u) (getKindAttr old).\n  \n  Inductive SemCompActionSimple: forall k, CompActionSimple type RegMapType k -> RegMapType ->  MethsT -> type k -> Prop :=\n  | SemCompCall_simple_True (f: string) (argRetK: Kind * Kind) (pred: Bool @# type)\n                            (arg: fst argRetK @# type)\n                            lret (cont: fullType type (SyntaxKind (snd argRetK)) -> CompActionSimple _ _ lret)\n                            (ret: fullType type (SyntaxKind (snd argRetK)))\n                            regMap calls val newCalls\n                            (HNewCalls : newCalls = (f, existT _ argRetK (evalExpr arg, ret)) :: calls)\n                            (HSemCompActionSimple: SemCompActionSimple (cont ret) regMap calls val)\n                            (HPred : evalExpr pred = true):\n      SemCompActionSimple (@CompCall_simple _ _ f argRetK pred arg lret cont) regMap newCalls val\n  | SemCompCall_simple_False (f: string) (argRetK: Kind * Kind) (pred: Bool @# type)\n                             (arg: fst argRetK @# type)\n                             lret (cont: fullType type (SyntaxKind (snd argRetK)) -> CompActionSimple _ _ lret)\n                             (ret: fullType type (SyntaxKind (snd argRetK)))\n                             regMap calls val\n                             (HSemCompActionSimple: SemCompActionSimple (cont ret) regMap calls val)\n                             (HPred : evalExpr pred = false):\n      SemCompActionSimple (@CompCall_simple _ _ f argRetK pred arg lret cont) regMap calls val\n  | SemCompLetExpr_simple k e lret cont\n                          regMap calls val\n                          (HSemCompActionSimple: SemCompActionSimple (cont (evalExpr e)) regMap calls val):\n      SemCompActionSimple (@CompLetExpr_simple _ _ k e lret cont) regMap calls val\n  | SemCompNondet_simple k lret cont\n                         ret regMap calls val\n                         (HSemCompActionSimple: SemCompActionSimple (cont ret) regMap calls val):\n      SemCompActionSimple (@CompNondet_simple _ _ k lret cont) regMap calls val\n  | SemCompSys_simple pred ls lret cont\n               regMap calls val\n               (HSemCompActionSimple: SemCompActionSimple cont regMap calls val):\n      SemCompActionSimple (@CompSys_simple _ _ pred ls lret cont) regMap calls val\n  | SemCompReadReg_simple r k readMap lret cont\n                          regMap calls val regVal\n                          updatedRegs readMapValOld readMapValUpds\n                          (HReadMap: Sem_RmeSimple readMap (readMapValOld, readMapValUpds))\n                          (HUpdatedRegs: PriorityUpds readMapValOld readMapValUpds updatedRegs)\n                          (HIn: In (r, (existT _ k regVal)) updatedRegs)\n                          (HSemCompActionT: SemCompActionSimple (cont regVal) regMap calls val):\n      SemCompActionSimple (@CompReadReg_simple _ _ r k readMap lret cont) regMap calls val\n  | SemCompRet_simple lret e regMap regMapVal calls\n                      (HCallsNil : calls = nil)\n                      (HRegMapWf: WfRmeSimple regMap regMapVal):\n      SemCompActionSimple (@CompRet_simple _ _ lret e regMap) regMapVal calls (evalExpr e)\n  | SemCompLetFull_simple k a lret cont\n                          regMap_a calls_a val_a\n                          (HSemCompActionSimple_a: SemCompActionSimple a regMap_a calls_a val_a)\n                          regMap_cont calls_cont val_cont newCalls\n                          (HNewCalls : newCalls = calls_a ++ calls_cont)\n                          (HSemCompActionSimple_cont: SemCompActionSimple (cont val_a regMap_a) regMap_cont calls_cont val_cont):\n      SemCompActionSimple (@CompLetFull_simple _ _ k a lret cont) regMap_cont newCalls val_cont\n  | SemCompAsyncReadRmeSimple num (readPort dataArray : string) writePort isWriteMask idxNum (idx : Bit (Nat.log2_up idxNum) @# type) pred Data readMap lret\n                            updatedRegs readMapValOld readMapValUpds regVal regMap\n                            (HReadMap : Sem_RmeSimple readMap (readMapValOld, readMapValUpds))\n                            (HUpdatedRegs : PriorityUpds readMapValOld readMapValUpds updatedRegs)\n                            (HIn :  In (dataArray, (existT _ (SyntaxKind (Array idxNum Data)) regVal)) updatedRegs)\n                            cont calls val contArray\n                            (HContArray : contArray =\n                                          BuildArray (fun i : Fin.t num =>\n                                                        ReadArray\n                                                          (Var type _ regVal)\n                                                          (CABit Add (Var type (SyntaxKind _) (evalExpr idx) ::\n                                                                          Const type (natToWord _ (proj1_sig (Fin.to_nat i)))::nil))))\n                            (HSemCompActionSimple : SemCompActionSimple (cont (evalExpr contArray)) regMap calls val):\n      SemCompActionSimple (@CompAsyncRead_simple _ _ idxNum num readPort dataArray writePort isWriteMask idx pred Data readMap lret cont) regMap calls val\n  | SemCompWrite_simple (writePort dataArray : string) idxNum Data (readMap : RmeSimple type RegMapType) lret\n                     updatedRegs readMapValOld readMapValUpds regVal\n                     (HReadMap : Sem_RmeSimple readMap (readMapValOld, readMapValUpds))\n                     (HUpdatedRegs : PriorityUpds readMapValOld readMapValUpds updatedRegs)\n                     (HIn : In (dataArray, (existT _ (SyntaxKind (Array idxNum Data)) regVal)) updatedRegs)\n                     cont regMap_cont calls val\n                     (HSemCompActionSimple : SemCompActionSimple (cont regVal) regMap_cont calls val):\n      SemCompActionSimple (@CompWrite_simple _ _ idxNum Data writePort dataArray readMap lret cont) regMap_cont calls val\n  | SemCompSyncReadReq_simple_True num idxNum readReq readReg dataArray k (isAddr : bool) readMap lret cont\n                                   regMapVal\n                                   (HisAddr : isAddr = true)\n                                   regMap_cont calls val\n                                   (HSemCompActionSimple : SemCompActionSimple (cont regMapVal) regMap_cont calls val):\n      SemCompActionSimple (@CompSyncReadReq_simple _ _ idxNum num k readReq readReg dataArray isAddr readMap lret cont) regMap_cont calls val\n  | SemCompSyncReadReq_simple_False num idxNum readReq readReg dataArray (idx : Bit (Nat.log2_up idxNum) @# type) Data (isAddr : bool)\n                                    (writeMap : RegMapExpr type RegMapType) readMap lret cont\n                                    (HisAddr : isAddr = false)\n                                    updatedRegs readMapValOld readMapValUpds regV \n                                    (HReadMap : Sem_RmeSimple readMap (readMapValOld, readMapValUpds))\n                                    (HUpdatedRegs : PriorityUpds readMapValOld readMapValUpds updatedRegs)\n                                    (HRegVal : In (dataArray, (existT _ (SyntaxKind (Array idxNum Data)) regV)) updatedRegs)\n                                    regMap_cont calls val\n                                    (HSemCompActionSimple : SemCompActionSimple (cont regV) regMap_cont calls val):\n      SemCompActionSimple (@CompSyncReadReq_simple _ _ idxNum num Data readReq readReg dataArray isAddr readMap lret cont) regMap_cont calls val\n  | SemCompSyncReadRes_simple_True num idxNum readResp readRegName dataArray writePort isWriteMask Data isAddr readMap lret cont\n                                   (HisAddr : isAddr = true)\n                                   updatedRegs readMapValOld readMapValUpds regVal idx\n                                   (HReadMap : Sem_RmeSimple readMap (readMapValOld, readMapValUpds))\n                                   (HUpdatedRegs : PriorityUpds readMapValOld readMapValUpds updatedRegs)\n                                   (HRegVal1 : In (readRegName, existT _ (SyntaxKind (Bit (Nat.log2_up idxNum))) idx) updatedRegs)\n                                   (HRegVal2 : In (dataArray, existT _ (SyntaxKind (Array idxNum Data)) regVal) updatedRegs)\n                                   (contArray : Expr type (SyntaxKind (Array num Data)))\n                                   (HContArray : contArray =\n                                                 BuildArray (fun i : Fin.t num =>\n                                                               ReadArray\n                                                                 (Var type _ regVal)\n                                                                 (CABit Add (Var type (SyntaxKind _) idx ::\n                                                                                 Const type (natToWord _ (proj1_sig (Fin.to_nat i)))::nil))))\n                                   regMap calls val\n                                   (HSemCompActionSimple : SemCompActionSimple (cont (evalExpr contArray)) regMap calls val):\n      SemCompActionSimple (@CompSyncReadRes_simple _ _ idxNum num readResp readRegName dataArray writePort isWriteMask Data isAddr readMap lret cont) regMap calls val\n  | SemCompSyncReadRes_simple_False num idxNum readResp readRegName dataArray writePort isWriteMask Data isAddr readMap lret cont\n                                    (HisAddr : isAddr = false)\n                                    updatedRegs readMapValOld readMapValUpds regVal\n                                    (HReadMap : Sem_RmeSimple readMap (readMapValOld, readMapValUpds))\n                                    (HUpdatedRegs : PriorityUpds readMapValOld readMapValUpds updatedRegs)\n                                    (HIn1 : In (readRegName, (existT _ (SyntaxKind (Array num Data)) regVal)) updatedRegs)\n                                    regMap calls val\n                                    (HSemCompActionSimple : SemCompActionSimple (cont regVal) regMap calls val):\n      SemCompActionSimple (@CompSyncReadRes_simple _ _ idxNum num readResp readRegName dataArray writePort isWriteMask Data isAddr readMap lret cont) regMap calls val.\n  Variable (k : Kind) (a : CompActionSimple type RegMapType k) (regInits : list RegInitT).\n  \n\n  Section Loop.\n    Variable f: RegsT -> CompActionSimple type RegMapType Void.\n\n    Inductive SemCompActionSimple_Trace: RegsT -> list UpdRegsT -> list MethsT -> Prop :=\n    | SemCompActionSimple_TraceInit (oInit : RegsT) (lupds : list UpdRegsT) (lcalls : list MethsT)\n                             (HNoUpds : lupds = nil) (HNoCalls : lcalls = nil)\n                             (HInitRegs : Forall2 regInit oInit regInits) :\n        SemCompActionSimple_Trace oInit lupds lcalls\n    | SemCompActionSimple_TraceCont (o o' : RegsT) (lupds lupds' : list UpdRegsT) (upds : UpdRegsT)\n                             (lcalls lcalls' : list MethsT) (calls : MethsT) val\n                             (HOldTrace : SemCompActionSimple_Trace o lupds lcalls)\n                             (HSemAction : SemCompActionSimple (f o) (o, upds) calls val)\n                             (HNewUpds : lupds' = upds :: lupds)\n                             (HNewCalls : lcalls' = calls :: lcalls)\n                             (HPriorityUpds : PriorityUpds o upds o') :\n        SemCompActionSimple_Trace o' lupds' lcalls'.\n  End Loop.\nEnd SemSimple.\n", "meta": {"author": "sifive", "repo": "Kami", "sha": "ffb77238f27b603dbd42d2622ba911740bf5eadf", "save_path": "github-repos/coq/sifive-Kami", "path": "github-repos/coq/sifive-Kami/Kami-ffb77238f27b603dbd42d2622ba911740bf5eadf/Compiler/CompilerSimpleSem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2226602158281952}}
{"text": "From Velus Require Import Common.\nFrom Velus Require Import Environment.\nFrom Velus Require Import Operators.\nFrom Velus Require Import Clocks.\nFrom Velus Require Import Lustre.LSyntax.\nFrom Velus Require Import CoreExpr.CESyntax.\nFrom Velus Require Import NLustre.NLSyntax.\n\nFrom Coq Require Import Omega.\nFrom Coq Require Import Permutation.\nFrom Coq Require Import String.\n\nFrom Coq Require Import List.\nImport List.ListNotations.\n\nFrom compcert Require Import common.Errors.\nOpen Scope error_monad_scope.\n\n(** * Turn a normalized Lustre program into an NLustre program *)\n\n(** Transcription algorithm and common lemmas for Correctness,\n    Typing and Clocking preservation *)\n\nModule Type TR\n       (Import Ids  : IDS)\n       (Import Op   : OPERATORS)\n       (Import OpAux: OPERATORS_AUX Op)\n       (L           : LSYNTAX  Ids Op)\n       (Import CE   : CESYNTAX     Op)\n       (NL          : NLSYNTAX Ids Op CE).\n\n  Fixpoint to_lexp (e : L.exp) : res CE.exp :=\n    match e with\n    | L.Econst c                 => OK (CE.Econst c)\n    | L.Evar x (ty, ck)          => OK (CE.Evar x ty)\n    | L.Eunop op e (ty, ck)      => do le <- to_lexp e;\n                                    OK (CE.Eunop op le ty)\n    | L.Ebinop op e1 e2 (ty, ck) => do le1 <- to_lexp e1;\n                                    do le2 <- to_lexp e2;\n                                    OK (CE.Ebinop op le1 le2 ty)\n    | L.Ewhen [e] x b ([ty], ck) => do le <- to_lexp e;\n                                    OK (CE.Ewhen le x b)\n    | L.Efby _ _ _\n    | L.Earrow _ _ _\n    | L.Ewhen _ _ _ _\n    | L.Emerge _ _ _ _\n    | L.Eite _ _ _ _\n    | L.Eapp _ _ _ _    => Error (msg \"expression not normalized\")\n    end.\n\n  Fixpoint to_cexp (e : L.exp) : res CE.cexp :=\n    match e with\n    | L.Econst _\n    | L.Evar _ _\n    | L.Eunop _ _ _\n    | L.Ebinop _ _ _ _\n    | L.Ewhen _ _ _ _                 => do le <- to_lexp e;\n                                         OK (CE.Eexp le)\n\n    | L.Emerge x [et] [ef] ([ty], ck) => do cet <- to_cexp et;\n                                         do cef <- to_cexp ef;\n                                         OK (CE.Emerge x cet cef)\n\n    | L.Eite e [et] [ef] ([ty], ck)   => do le <- to_lexp e;\n                                         do cet <- to_cexp et;\n                                         do cef <- to_cexp ef;\n                                         OK (CE.Eite le cet cef)\n\n    | L.Emerge _ _ _ _\n    | L.Eite _ _ _ _\n    | L.Efby _ _ _\n    | L.Earrow _ _ _\n    | L.Eapp _ _ _ _    => Error (msg \"control expression not normalized\")\n    end.\n\n  Fixpoint suffix_of_clock (ck : clock) (acc : list (ident * bool))\n                                                    : list (ident * bool) :=\n    match ck with\n    | Cbase => acc\n    | Con ck' x b => suffix_of_clock ck' ((x, b) :: acc)\n    end.\n\n  Fixpoint clock_of_suffix (sfx : list (ident * bool)) (ck : clock) : clock :=\n    match sfx with\n    | [] => ck\n    | (x, b) :: sfx' => clock_of_suffix sfx' (Con ck x b)\n    end.\n\n  Fixpoint common_suffix (sfx1 sfx2 : list (ident * bool))\n                                                 : list (ident * bool) :=\n    match sfx1, sfx2 with\n    | [],  _ => []\n    | _ , [] => []\n    | (x1, b1)::sfx1', (x2, b2)::sfx2' =>\n      if (Pos.eqb x1 x2) && (b1 ==b b2) then (x1, b1) :: common_suffix sfx1' sfx2'\n      else []\n    end.\n\n  Definition find_base_clock (cks : list clock) : clock :=\n    match cks with\n    | [] => Cbase\n    | ck::cks =>\n      let sfx := fold_left\n                   (fun sfx1 ck2 => common_suffix sfx1 (suffix_of_clock ck2 []))\n                   cks (suffix_of_clock ck [])\n      in\n      clock_of_suffix sfx Cbase\n    end.\n\n  Definition find_clock (env : Env.t (type * clock)) (x : ident) : res clock :=\n    match Env.find x env with\n    | None => Error (msg \"find_clock failed unexpectedly\")\n    | Some (ty, ck) => OK ck\n    end.\n\n  Fixpoint to_constant (e : L.exp) : res const :=\n    match e with\n    | L.Econst c => OK c\n    | L.Ewhen [e] _ _ _ => to_constant e\n    | _ => Error (msg \"not a constant\")\n    end.\n\n  Definition to_equation (env : Env.t (type * clock)) (envo : ident -> res unit)\n                         (eq : L.equation) : res NL.equation :=\n    let (xs, es) := eq in\n    match es with\n    | [e] =>\n      match e with\n      | L.Eapp f es None _ =>\n        do les <- mmap to_lexp es;\n        OK (NL.EqApp xs (find_base_clock (L.clocksof es)) f les None)\n      | L.Eapp f es (Some (L.Evar x (_, (ckx, _)))) _ => (* use clock annot or lookup? *)\n        do les <- mmap to_lexp es;\n        OK (NL.EqApp xs (find_base_clock (L.clocksof es)) f les (Some (x, ckx)))\n      | L.Eapp f es (Some _) _ => Error (msg \"reset equation not normalized\")\n      | L.Efby [e0] [e] _ =>\n        match xs with\n          | [x] =>\n            do _  <- envo x;\n            do c0 <- to_constant e0;\n            do ck <- find_clock env x;\n            do le <- to_lexp e;\n            OK (NL.EqFby x ck c0 le)\n          | _ => Error (msg \"fby equation not normalized\")\n        end\n      | _ =>\n        match xs with\n        | [x] =>\n          do ck <- find_clock env x;\n          do ce <- to_cexp e;\n          OK (NL.EqDef x ck ce)\n        | _ => Error (msg \"basic equation not normalized\")\n        end\n      end\n    | _ => Error (msg \"equation not normalized\")\n    end.\n\n    (* match eq with *)\n    (* | (xs, [L.Eapp f es None _]) => *)\n    (*     do les <- mmap to_lexp es; *)\n    (*     OK (NL.EqApp xs (find_base_clock (L.clocksof es)) f les None) *)\n\n    (* | (xs, [L.Eapp f es (Some (L.Evar x _)) _]) => *)\n    (*     do les <- mmap to_lexp es; *)\n    (*     OK (NL.EqApp xs (find_base_clock (L.clocksof es)) f les (Some x)) *)\n\n    (* | ([x], [L.Efby [e0] [e] _]) => *)\n    (*     do _  <- envo x; *)\n    (*     do c0 <- to_constant e0; *)\n    (*     do ck <- find_clock env x; *)\n    (*     do le <- to_lexp e; *)\n    (*     OK (NL.EqFby x ck c0 le) *)\n\n    (* | ([x], [e]) => *)\n    (*     do ck <- find_clock env x; *)\n    (*     do ce <- to_cexp e; *)\n    (*     OK (NL.EqDef x ck ce) *)\n\n    (* | _ => Error (msg \"equation not normalized\") *)\n    (* end. *)\n\n  Lemma find_clock_in_env :\n    forall x env ty ck,\n      Env.find x env = Some (ty, ck) ->\n      find_clock env x = OK ck.\n  Proof.\n    intros * H. unfold find_clock. now rewrite H.\n  Qed.\n\n  Lemma find_clock_out : forall n x ty ck,\n      In (x, (ty, ck)) (L.n_out n) ->\n      find_clock\n        (Env.adds' (L.n_vars n)\n                   (Env.adds' (L.n_in n) (Env.from_list (L.n_out n)))\n        ) x = OK ck.\n  Proof.\n    intros * Hin.\n    unfold Env.from_list. eapply find_clock_in_env.\n    apply In_InMembers in Hin as Hinm.\n    pose proof (L.n_nodup n) as Hnodup.\n    rewrite 2 Env.gsso'. apply Env.In_find_adds'; eauto.\n    - eapply NoDupMembers_app_r, NoDupMembers_app_r, NoDupMembers_app_l in Hnodup; eauto.\n    - eapply NoDupMembers_app_InMembers_l; eauto.\n      repeat rewrite InMembers_app; auto.\n    - eapply NoDupMembers_app_r in Hnodup.\n      eapply NoDupMembers_app_InMembers_l; eauto.\n      rewrite InMembers_app; auto.\n  Qed.\n\n  Lemma ok_fst_defined eq eq' :\n    forall env envo,\n      to_equation env envo eq = OK eq' -> fst eq = NL.var_defined eq'.\n  Proof.\n    intros env envo Htoeq.\n    unfold to_equation in Htoeq.\n    cases; monadInv Htoeq; inv EQ; simpl; auto.\n  Qed.\n\n  Lemma nl_vars_defined_cons:\n    forall eq eqs,\n      NL.vars_defined (eq::eqs) = NL.var_defined eq ++ NL.vars_defined eqs.\n  Proof.\n    intros. unfold NL.vars_defined. now simpl.\n  Qed.\n\n  Remark mmap_cons:\n    forall (A B: Type) (f: A -> res B) (l: list A) (r: list B) (x: A),\n      mmap f (x :: l) = OK r ->\n      exists x' l', r = x' :: l' /\\ f x = OK x' /\\ mmap f l = OK l'.\n  Proof.\n    induction l; simpl; intros.\n    monadInv H. exists x0, []. auto.\n    monadInv H. exists x0, x1. auto.\n  Qed.\n\n  Remark mmap_cons2:\n    forall (A B: Type) (f: A -> res B) (l: list A) (r: list B) (x: B),\n      mmap f (l) = OK (x :: r) ->\n      exists x' l', l = x' :: l' /\\ f x' = OK x /\\ mmap f l' = OK r.\n  Proof.\n    induction l; simpl; intros.\n    monadInv H.\n    monadInv H. exists a, l. auto.\n  Qed.\n\n  Remark mmap_cons3:\n    forall (A B: Type) (f: A -> res B) (l: list A) (r: list B) (x: A) (y : B),\n      mmap f (x :: l) = OK (y :: r) ->\n      f x = OK y /\\ mmap f l = OK r.\n  Proof.\n    induction l; simpl; intros; monadInv H; auto.\n  Qed.\n\n  Definition mmap_to_equation env envo n :\n    res { neqs | mmap (to_equation env envo) n.(L.n_eqs) = OK neqs }.\n  Proof.\n    destruct (mmap (to_equation env envo) n.(L.n_eqs)).\n    left. eauto.\n    right. auto.\n  Defined.\n\n  Unset Program Cases.\n  Program Definition to_node (n : L.node)\n    (Hpref : PS.Equal (L.n_prefixes n) (PSP.of_list gensym_prefs)) : res NL.node :=\n    let envo := Env.from_list n.(L.n_out) in\n    let env := Env.adds' n.(L.n_vars) (Env.adds' n.(L.n_in) envo) in\n    let is_not_out :=\n        fun x => if Env.mem x envo\n              then Error (msg \"output variable defined as a fby\")\n              else OK tt in\n    match mmap_to_equation env is_not_out n (* return _ *) with\n    | OK (exist neqs P) =>\n      OK {|\n          NL.n_name     := n.(L.n_name);\n          NL.n_in       := n.(L.n_in);\n          NL.n_out      := n.(L.n_out);\n          NL.n_vars     := n.(L.n_vars);\n          NL.n_eqs      := neqs;\n\n          NL.n_ingt0    := L.n_ingt0 n;\n          NL.n_outgt0   := L.n_outgt0 n;\n          NL.n_defd     := _;\n          NL.n_vout     := _;\n          NL.n_nodup    := _;\n          NL.n_good     := _\n        |}\n    | Error e => Error e\n    end.\n\n  (* NL.n_defd obligation *)\n  Next Obligation.\n    clear H0 H.\n    monadInv P.\n    assert (NL.vars_defined neqs = L.vars_defined (L.n_eqs n)). clear P.\n    { revert H. revert neqs. induction (L.n_eqs n); simpl.\n    - intros neqs Htr. inv Htr. auto.\n    - intros neqs Htoeq. inv Htoeq.\n      apply IHl in H3. simpl.\n      apply ok_fst_defined in H1. rewrite H3. now rewrite <- H1.\n    }\n    rewrite H0.\n    exact (L.n_defd n).\n  Qed.\n\n  (* NL.n_vout obligation *)\n  Next Obligation.\n    clear H H1. rename H0 into Hin. rename P into Heqr.\n\n    monadInv Heqr. induction H as [| eq leq eq' leq' Htoeq ].\n    intro Hbad. inv Hbad.\n    assert (Hmmap := Heqr).\n    apply mmap_cons2 in Heqr.\n    destruct Heqr as (eq'' & leq'' & Heqs' & Htoeq' & Hmmap').\n    inv Heqs'.\n    simpl. destruct (NL.is_fby eq') eqn:?.\n    - unfold NL.vars_defined, flat_map. simpl. rewrite in_app.\n      intro Hi. destruct Hi.\n      + unfold to_equation in Htoeq. destruct eq''.\n        cases_eqn E; monadInv1 Htoeq; inv Heqb.\n        simpl in H0. destruct H0; auto. subst. inv EQ.\n        apply Env.Props.P.F.not_mem_in_iff in E8. apply E8.\n        rewrite in_map_iff in Hin.\n        destruct Hin as ((x & ?) & Hfst & Hin). inv Hfst.\n        eapply Env.find_In. eapply Env.In_find_adds'; simpl; eauto.\n        destruct n. simpl. assert (Hnodup := n_nodup).\n        apply NoDupMembers_app_r, NoDupMembers_app_r, NoDupMembers_app_l in Hnodup; auto.\n      + apply IHlist_forall2; auto.\n    - apply IHlist_forall2; eauto.\n  Qed.\n\n  Next Obligation.\n    specialize (L.n_nodup n) as Hndup.\n    repeat rewrite app_assoc in *. apply NoDupMembers_app_l in Hndup; auto.\n  Qed.\n\n  (* NL.n_good obligation *)\n  Next Obligation.\n    pose proof (L.n_good n) as (Hgood&Hat).\n    split; auto.\n    repeat rewrite map_app in *.\n    eapply Forall_impl; [|eapply Forall_incl; eauto].\n    - intros * [?|(pref&?&?&?)]; subst; [left|right]; auto.\n      exists pref. rewrite <- Hpref. eauto.\n    - apply incl_appr', incl_appr', incl_appl, incl_refl.\n  Qed.\n\n  Fixpoint to_global (g : L.global) :\n    Forall (fun n => PS.Equal (L.n_prefixes n) (PSP.of_list gensym_prefs)) g ->\n    res NL.global.\n  Proof.\n    destruct g as [|hd tl]; intros Hprefs.\n    - exact (OK []).\n    - refine (bind (to_node hd _) (fun hd' => bind (to_global tl _) (fun tl' => OK (hd'::tl')))).\n      + inv Hprefs; auto.\n      + inv Hprefs; auto.\n  Defined.\n\n  (** Helper for the l_to_nl function *)\n  Program Definition to_global' (G : {G | Forall (fun n => PS.Equal (L.n_prefixes n) (PSP.of_list gensym_prefs)) G}) :\n    res NL.global := to_global G _.\n\n  Ltac tonodeInv H :=\n    match type of H with\n    | (to_node ?n _ = OK _) =>\n      let Hs := fresh in\n      let Hmmap := fresh \"Hmmap\" in\n      unfold to_node in H;\n      destruct(mmap_to_equation\n               (Env.adds' (L.n_vars n)\n                (Env.adds' (L.n_in n)\n                 (Env.from_list (L.n_out n))))\n            (fun x : Env.key =>\n             if Env.mem x (Env.from_list (L.n_out n))\n             then Error (msg \"output variable defined as a fby\")\n             else OK tt) n)\n      as [ Hs | Hs ];\n      try (destruct Hs as (? & Hmmap)); inv H\n    end.\n\n  Lemma find_node_hd f a G n :\n    L.find_node f (a :: G) = Some n ->\n    ((ident_eqb (L.n_name a) f) = true  /\\ a = n) \\/\n    ((ident_eqb (L.n_name a) f) = false /\\ L.find_node f G = Some n).\n  Proof.\n    simpl. intro.\n    case_eq (ident_eqb (L.n_name a) f); intro; rewrite H0 in H; inv H.\n    auto. right. auto.\n  Qed.\n\n  Lemma find_node_In :\n    forall f G n, L.find_node f G = Some n -> In n G.\n  Proof.\n    induction G; intros * Hfind; try discriminate.\n    inv Hfind. destruct (ident_eqb (L.n_name a) f).\n    inv H0. simpl. now left.\n    simpl. right. now apply IHG.\n  Qed.\n\n  Lemma to_node_name n n' Hpref :\n    to_node n Hpref = OK n' -> L.n_name n = NL.n_name n'.\n  Proof.\n    intro Htr. tonodeInv Htr. now simpl.\n  Qed.\n\n  Lemma to_node_in n n' Hpref :\n    to_node n Hpref = OK n' -> L.n_in n = NL.n_in n'.\n  Proof.\n    intro Htr. tonodeInv Htr. now simpl.\n  Qed.\n\n  Lemma to_node_out n n' Hpref :\n    to_node n Hpref = OK n' -> L.n_out n = NL.n_out n'.\n  Proof.\n    intro Htr. tonodeInv Htr. now simpl.\n  Qed.\n\n  Lemma to_node_vars n n' Hpref :\n    to_node n Hpref = OK n' -> L.n_vars n = NL.n_vars n'.\n  Proof.\n    intro Htr. tonodeInv Htr. now simpl.\n  Qed.\n\n  Lemma find_node_global (G: L.global) Hprefs (P: NL.global) (f: ident) (n: L.node) :\n    to_global G Hprefs = OK P ->\n    L.find_node f G = Some n ->\n    exists n' Hpref, NL.find_node f P = Some n' /\\ to_node n Hpref = OK n'.\n  Proof.\n    revert P.\n    induction G; intros * Htrans Hfind. inversion Hfind.\n    apply find_node_hd in Hfind.\n    destruct Hfind as [(Heq&?)|(Hneq&Hfind)]; subst.\n    - monadInv Htrans.\n      exists x. eexists; split; eauto.\n      simpl. apply to_node_name in EQ. rewrite <- EQ, Heq. reflexivity.\n    - monadInv Htrans.\n      eapply IHG in EQ1 as (n'&?&P'&nP); eauto.\n      exists n'. eexists; split; eauto. simpl.\n      apply to_node_name in EQ. rewrite <- EQ, Hneq; auto.\n  Qed.\n\n  Lemma find_node_global' (G: L.global) Hprefs (P: NL.global) (f: ident) (n': NL.node) :\n    to_global G Hprefs = OK P ->\n    NL.find_node f P = Some n' ->\n    exists n Hpref, L.find_node f G = Some n /\\ to_node n Hpref = OK n'.\n  Proof.\n    revert P.\n    induction G; intros * Htrans Hfind; simpl in *; monadInv Htrans; simpl in *; try congruence.\n    destruct (ident_eqb (NL.n_name x) f) eqn:Hname.\n    - clear EQ1. inv Hfind.\n      erewrite to_node_name, Hname; eauto.\n    - eapply IHG in EQ1 as (n&?&Hfind'&Hton); eauto.\n      erewrite to_node_name, Hname; eauto.\n  Qed.\n\n  Section Envs_eq.\n\n    Definition envs_eq (env : Env.t (type * clock))\n               (cenv : list (ident * clock)) :=\n      forall (x : ident) (ck : clock),\n        In (x,ck) cenv <-> exists ty, Env.find x env = Some (ty,ck).\n\n    Lemma envs_eq_find :\n      forall env cenv x ck,\n        envs_eq env cenv ->\n        In (x, ck) cenv ->\n        find_clock env x = OK ck.\n    Proof.\n      unfold find_clock, envs_eq. intros * Heq Hin.\n      rewrite Heq in Hin. destruct Hin as [? Hfind].\n      now rewrite Hfind.\n    Qed.\n\n    Lemma envs_eq_find' :\n      forall env cenv x ck,\n        envs_eq env cenv ->\n        find_clock env x = OK ck ->\n        In (x, ck) cenv.\n    Proof.\n      unfold find_clock, envs_eq. intros * Heq Hfind.\n      rewrite Heq.\n      destruct Env.find.\n      - destruct p. inv Hfind. eexists; eauto.\n      - inv Hfind.\n    Qed.\n\n    Lemma envs_eq_app_comm :\n      forall env (xs ys : list (ident * (type * clock))),\n        envs_eq env (idck (xs ++ ys))\n        <-> envs_eq env (idck (ys ++ xs)).\n    Proof.\n      split; unfold envs_eq; intros Heq x ck; split; intro Hin;\n        try (rewrite idck_app in Hin;\n             apply in_app_comm in Hin; apply Heq; now rewrite idck_app);\n        try (rewrite idck_app; rewrite in_app_comm; rewrite <- idck_app;\n             now apply Heq).\n    Qed.\n\n    Lemma env_eq_env_from_list:\n      forall xs,\n        NoDupMembers xs ->\n        envs_eq (Env.from_list xs) (idck xs).\n    Proof.\n      intros xs Hnodup x ck. split.\n      - unfold idck. rewrite in_map_iff.\n        intro Hxs. destruct Hxs as (y & Hx & Hin). inv Hx.\n        exists (fst (snd y)).\n        apply Env.In_find_adds'; auto.\n        destruct y as [? [? ?]]. auto.\n      - intro Hfind. destruct Hfind as [ty Hfind].\n        apply Env.from_list_find_In in Hfind.\n        unfold idck. rewrite in_map_iff. exists (x,(ty,ck)). simpl. tauto.\n    Qed.\n\n    Lemma env_eq_env_adds':\n      forall s xs ys,\n        NoDupMembers (xs ++ ys) ->\n        envs_eq s (idck ys) ->\n        envs_eq (Env.adds' xs s) (idck (xs ++ ys)).\n    Proof.\n      intros s xs ys Hnodup Heq x ck. split.\n      - rewrite idck_app. rewrite in_app_iff. destruct 1 as [Hin | Hin].\n        unfold idck in Hin. rewrite in_map_iff in Hin.\n        destruct Hin as (y & Hx & Hin). inv Hx. exists (fst (snd y)).\n        apply Env.In_find_adds'; auto.\n        now apply NoDupMembers_app_l in Hnodup.\n        destruct y as (? & ? & ?). now simpl.\n        assert (Hin' := Hin).\n        apply Heq in Hin. destruct Hin as [ty Hin].\n        exists ty. rewrite <- Hin. apply Env.gsso'.\n        apply In_InMembers in Hin'. rewrite InMembers_idck in Hin'.\n        eapply NoDupMembers_app_InMembers; eauto.\n        now rewrite Permutation_app_comm.\n      - destruct 1 as [ty Hfind].\n        apply Env.find_env_from_list' in Hfind.\n        destruct Hfind as [Hin | [Hin Hfind]];\n          rewrite idck_app; apply in_app_iff.\n        left. rewrite In_idck_exists. eauto.\n        right. unfold envs_eq in Heq. rewrite Heq. eauto.\n    Qed.\n\n    Lemma envs_eq_node (n : L.node) :\n      envs_eq\n        (Env.adds' (L.n_vars n)\n                   (Env.adds' (L.n_in n)\n                              (Env.from_list (L.n_out n))))\n        (idck (L.n_in n ++ L.n_vars n ++ L.n_out n)).\n    Proof.\n      rewrite envs_eq_app_comm.\n      rewrite <- app_assoc.\n      apply env_eq_env_adds'. rewrite app_assoc.\n      rewrite Permutation_app_comm. specialize (L.n_nodup n) as Hnd.\n      repeat rewrite app_assoc in *. apply NoDupMembers_app_l in Hnd; auto.\n      rewrite envs_eq_app_comm.\n      apply env_eq_env_adds'. assert (Hnodup := L.n_nodup n).\n      repeat rewrite app_assoc in Hnodup. apply NoDupMembers_app_l in Hnodup. rewrite <- app_assoc in Hnodup.\n      rewrite Permutation_app_comm in Hnodup.\n      rewrite <- app_assoc in Hnodup. apply NoDupMembers_app_r in Hnodup.\n      now rewrite Permutation_app_comm.\n      apply env_eq_env_from_list. assert (Hnodup := L.n_nodup n).\n      now apply NoDupMembers_app_r, NoDupMembers_app_r, NoDupMembers_app_l in Hnodup.\n    Qed.\n\n  End Envs_eq.\n\n  Section Clock_operations.\n\n    Lemma suffix_of_clock_app:\n      forall sfx sfx' ck,\n        suffix_of_clock ck (sfx ++ sfx') = (suffix_of_clock ck sfx) ++ sfx'.\n    Proof.\n      intros sfx sfx'; revert sfx' sfx.\n      induction sfx' as [|xb sfx' IH].\n      now setoid_rewrite app_nil_r.\n      intros sfx ck.\n      rewrite <-app_last_app, IH, <-app_last_app  with (xs':=sfx'). f_equal.\n      revert sfx; clear.\n      induction ck; auto.\n      simpl; intros sfx.\n      now rewrite app_comm_cons, IHck.\n    Qed.\n\n    Lemma clock_of_suffix_app:\n      forall sfx sfx' ck,\n        clock_of_suffix (sfx ++ sfx') ck\n        = clock_of_suffix sfx' (clock_of_suffix sfx ck).\n    Proof.\n      induction sfx as [|(x, b) sfx IH].\n      now setoid_rewrite app_nil_l.\n      intros sfx' ck.\n      now simpl; rewrite IH.\n    Qed.\n\n    Remark clock_of_suffix_of_clock:\n      forall ck,\n        clock_of_suffix (suffix_of_clock ck []) Cbase = ck.\n    Proof.\n      induction ck; auto; simpl in *.\n      now rewrite <-(app_nil_l [(i, b)]),\n      suffix_of_clock_app, clock_of_suffix_app, IHck.\n    Qed.\n\n    Lemma common_suffix_app :\n      forall l l1 l2,\n        common_suffix (l ++ l1) (l ++ l2) = l ++ common_suffix l1 l2.\n    Proof.\n      induction l; simpl; auto.\n      intros. cases_eqn HH. now f_equal.\n      now rewrite equiv_decb_refl, Pos.eqb_refl in HH0.\n    Qed.\n\n    Lemma common_suffix_app_l :\n      forall l l1 l2,\n        length l2 < length l1 ->\n        common_suffix l1 l2 = common_suffix (l1 ++ l) l2.\n    Proof.\n      induction l1; simpl; intros * Hlen.\n      - inv Hlen.\n      - cases_eqn HH. f_equal. apply IHl1. simpl in Hlen. omega.\n    Qed.\n\n    Lemma clock_parent_length :\n      forall ck ck',\n        clock_parent ck ck' ->\n        length (suffix_of_clock ck []) < length (suffix_of_clock ck' []).\n    Proof.\n      induction 1; simpl;\n        setoid_rewrite <- app_nil_l at 4;\n        setoid_rewrite suffix_of_clock_app;\n        rewrite app_length; simpl; omega.\n    Qed.\n\n    Lemma parent_common_suffix :\n      forall ck ck',\n        clock_parent ck ck' ->\n        common_suffix (suffix_of_clock ck' []) (suffix_of_clock ck []) =\n        suffix_of_clock ck [].\n    Proof.\n      induction 1; simpl; setoid_rewrite <- app_nil_l at 3.\n      - setoid_rewrite <- app_nil_r at 7.\n        rewrite suffix_of_clock_app.\n        rewrite common_suffix_app. simpl. now rewrite app_nil_r.\n      - rewrite suffix_of_clock_app, <- common_suffix_app_l; auto.\n        now apply clock_parent_length.\n    Qed.\n\n    Lemma common_suffix_id :\n      forall sfx, common_suffix sfx sfx = sfx.\n    Proof.\n      induction sfx as [| []]; simpl. auto. rewrite IHsfx.\n      rewrite equiv_decb_refl, Pos.eqb_refl. now simpl.\n    Qed.\n\n    Lemma common_suffix_comm :\n      forall sfx1 sfx2, common_suffix sfx1 sfx2 = common_suffix sfx2 sfx1.\n    Proof.\n      induction sfx1 as [| [i1 b1]], sfx2 as [| [i2 b2]]; simpl; auto.\n      cases_eqn EQ.\n      - apply andb_prop in EQ as [H].\n        apply Peqb_true_eq in H. subst.\n        Coq.Bool.Bool.destr_bool; f_equal; auto; f_equal.\n      -  apply andb_prop in EQ as [H].\n         apply Peqb_true_eq in H. subst.\n         apply Bool.andb_false_iff in EQ0 as [];\n           Coq.Bool.Bool.destr_bool; now rewrite Pos.eqb_refl in H.\n      -  apply andb_prop in EQ0 as [H].\n         apply Peqb_true_eq in H. subst.\n         apply Bool.andb_false_iff in EQ as [];\n           Coq.Bool.Bool.destr_bool; now rewrite Pos.eqb_refl in H.\n    Qed.\n\n    Inductive prefix {A} : list A -> list A -> Prop :=\n    | prefixNil: forall (l: list A), prefix nil l\n    | prefixCons: forall (a: A)(l m:list A), prefix l m -> prefix (a::l) (a::m).\n    Hint Constructors prefix.\n\n    Lemma prefix_app:\n      forall {A} (l l' : list A), prefix l (l ++ l').\n    Proof.\n      induction l; simpl; auto.\n    Qed.\n\n    Lemma prefix_app':\n      forall {A} (l l1 l2 : list A), prefix l l1 -> prefix l (l1 ++ l2).\n    Proof.\n      induction 1; simpl; auto.\n    Qed.\n\n    Lemma prefix_refl :\n      forall {A} (l : list A), prefix l l.\n    Proof. induction l; auto. Qed.\n\n    Lemma prefix_app3 :\n      forall {A} (l1 l2 : list A) e,\n        prefix l1 (l2 ++ [e]) ->\n        prefix l1 l2 \\/ l1 = (l2 ++ [e]).\n    Proof.\n      intros * Hp. revert dependent l1.\n      induction l2; simpl; intros.\n      - inv Hp; auto. inv H1; auto.\n      - inv Hp; auto. specialize (IHl2 _ H1) as []; auto.\n        right. now f_equal.\n    Qed.\n\n    Lemma suffix_of_clock_Con:\n      forall ck i b,\n        suffix_of_clock (Con ck i b) [] =\n        suffix_of_clock ck [(i, b)].\n    Proof. auto. Qed.\n\n    Lemma suffix_of_clock_inj :\n      forall ck ck',\n        suffix_of_clock ck [] = suffix_of_clock ck' [] ->\n        ck = ck'.\n    Proof.\n      induction ck, ck'; simpl; auto; intros * Hs.\n      - setoid_rewrite <- app_nil_l in Hs at 3.\n        rewrite suffix_of_clock_app in Hs.\n        now apply app_cons_not_nil in Hs.\n      - setoid_rewrite <- app_nil_l in Hs at 2.\n        rewrite suffix_of_clock_app in Hs.\n        symmetry in Hs. now apply app_cons_not_nil in Hs.\n      - setoid_rewrite <- app_nil_l in Hs at 2.\n        symmetry in Hs. setoid_rewrite <- app_nil_l in Hs at 2. symmetry in Hs.\n        rewrite 2 suffix_of_clock_app in Hs.\n        apply app_inj_tail in Hs as [He Hp]. inv Hp.\n        specialize (IHck _ He). now subst.\n    Qed.\n\n    Lemma prefix_parent :\n      forall bk ck,\n        ck = bk \\/ clock_parent bk ck <->\n        prefix (suffix_of_clock bk []) (suffix_of_clock ck []).\n    Proof.\n      split.\n      - destruct 1 as [|H]. subst. apply prefix_refl.\n        induction H; simpl.\n        + setoid_rewrite <- app_nil_l at 4.\n          rewrite suffix_of_clock_app. apply prefix_app.\n        + setoid_rewrite <- app_nil_l at 4.\n          rewrite suffix_of_clock_app. now apply prefix_app'.\n      - intro Hp. revert dependent bk.\n        induction ck; intros.\n        + simpl in *. inv Hp. destruct bk; simpl in *; auto.\n          setoid_rewrite <- app_nil_l in H0 at 3.\n          rewrite suffix_of_clock_app in H0.\n          now apply app_cons_not_nil in H0.\n        + simpl in *.\n          setoid_rewrite <- app_nil_l in Hp at 4.\n          rewrite suffix_of_clock_app in Hp.\n          apply prefix_app3 in Hp as [Hp|Heq].\n          specialize (IHck _ Hp) as []; subst; auto.\n          rewrite <- suffix_of_clock_app in Heq.\n          rewrite app_nil_l, <- suffix_of_clock_Con in Heq.\n          apply suffix_of_clock_inj in Heq. subst. auto.\n    Qed.\n\n    Lemma prefix_common_suffix :\n      forall sfx1 sfx2 p,\n        prefix p sfx1 ->\n        prefix p sfx2 ->\n        prefix p (common_suffix sfx1 sfx2).\n    Proof.\n      intros. revert dependent sfx2.\n      induction H as [|a]. auto. intros * Hp. simpl. destruct a.\n      destruct sfx2. inv Hp. destruct p. inv Hp.\n      rewrite equiv_decb_refl, Pos.eqb_refl. simpl. constructor. auto.\n    Qed.\n\n    Lemma suffix_of_clock_of_suffix :\n      forall sfx, sfx = suffix_of_clock (clock_of_suffix sfx Cbase) [].\n    Proof.\n      intro sfx.\n      assert (suffix_of_clock Cbase [] = []) by auto.\n      rewrite <- app_nil_l, <- H at 1.\n      generalize Cbase.\n      induction sfx as [|[i b]]. simpl in *; auto.\n      now setoid_rewrite app_nil_r.\n      simpl in *. setoid_rewrite <- IHsfx.\n      setoid_rewrite <- suffix_of_clock_app. setoid_rewrite app_nil_l at 2.\n      now simpl.\n    Qed.\n\n    Lemma Tim :\n      forall bk ck ck',\n        clock_parent bk ck ->\n        clock_parent bk ck' ->\n        exists d, (d = bk \\/ clock_parent bk d) /\\\n             suffix_of_clock d [] =\n             common_suffix (suffix_of_clock ck []) (suffix_of_clock ck' []).\n    Proof.\n      intros * Hp Hp'.\n      eapply or_intror in Hp. apply prefix_parent in Hp.\n      eapply or_intror in Hp'. apply prefix_parent in Hp'.\n      pose proof (prefix_common_suffix _ _ _ Hp Hp') as Hc.\n      rewrite suffix_of_clock_of_suffix in Hc.\n      apply prefix_parent in Hc.\n      esplit. split; eauto using suffix_of_clock_of_suffix.\n    Qed.\n\n    Lemma find_base_clock_bck:\n      forall lck bk,\n        In bk lck ->\n        Forall (fun ck => ck = bk \\/ clock_parent bk ck) lck ->\n        find_base_clock lck = bk.\n    Proof.\n      destruct lck. inversion 1.\n      simpl. intros * Hin Hf. rewrite <- fold_left_map.\n      apply Forall_cons2 in Hf as [Hf1 Hf2].\n      revert dependent c. induction lck. simpl. intros.\n      inv Hin; try tauto.\n      now rewrite clock_of_suffix_of_clock.\n      simpl. apply Forall_cons2 in Hf2 as [? Hf]. specialize (IHlck Hf).\n      intros. destruct H, Hf1; subst.\n      - rewrite common_suffix_id. eauto.\n      - rewrite parent_common_suffix; eauto.\n      - rewrite common_suffix_comm, parent_common_suffix; eauto.\n      - pose proof (Tim _ _ _ H H0) as (?&?& H2).\n        rewrite common_suffix_comm, <- H2.\n        eapply IHlck; eauto.\n        destruct Hin as [|[]]; auto; subst; exfalso;\n          eapply clock_parent_not_refl; eauto.\n    Qed.\n\n  End Clock_operations.\n\n  Fact to_global_names : forall name G G' Hprefs,\n      Forall (fun n => (name <> L.n_name n)%type) G ->\n      to_global G Hprefs = OK G' ->\n      Forall (fun n => (name <> NL.n_name n)%type) G'.\n  Proof.\n    induction G; intros * Hnames Htog; inv Hnames; monadInv Htog; constructor; eauto.\n    erewrite to_node_name in H1; eauto.\n  Qed.\n\n  Ltac simpl_Foralls :=\n    repeat\n      match goal with\n      | H: Forall _ [] |- _ => inv H\n      | H: Forall _ [_] |- _ => inv H\n      | H: Forall _ (_::_) |- _ => inv H\n      | H: Forall2 _ [_] _ |- _ => inv H\n      | H: Forall2 _ [] _ |- _ => inv H\n      | H: Forall2 _ _ [_] |- _ => inv H\n      | H: Forall2 _ _ [] |- _ => inv H\n      end.\n\nEnd TR.\n\nModule TrFun\n       (Ids   : IDS)\n       (Op    : OPERATORS)\n       (OpAux : OPERATORS_AUX Op)\n       (L     : LSYNTAX  Ids Op)\n       (CE    : CESYNTAX     Op)\n       (NL    : NLSYNTAX Ids Op CE)\n       <: TR Ids Op OpAux L CE NL.\n  Include TR Ids Op OpAux L CE NL.\nEnd TrFun.\n", "meta": {"author": "INRIA", "repo": "velus", "sha": "116a88bc71f3608ff43ed967895743e8b9a340e0", "save_path": "github-repos/coq/INRIA-velus", "path": "github-repos/coq/INRIA-velus/velus-116a88bc71f3608ff43ed967895743e8b9a340e0/src/Transcription/Tr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.22266021582819517}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Export PBFT_A_1_9_part1.\nRequire Export PBFT_A_1_2_5.\nRequire Export PBFT_A_1_9_misc1.\nRequire Export PBFT_A_1_9_misc2.\nRequire Export PBFT_A_1_9_misc3.\n\n\nSection PBFT_A_1_9_misc4.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { pbft_context : PBFTcontext      }.\n  Context { pbft_auth    : PBFTauth         }.\n  Context { pbft_keys    : PBFTinitial_keys }.\n  Context { pbft_hash    : PBFThash         }.\n\n\n  Lemma in_view_change_cert2max_seq_vc_implies_view_change2seq_le :\n    forall vc C max x,\n      In vc C\n      -> view_change_cert2max_seq_vc C = Some (max, x)\n      -> view_change2seq vc <= max.\n  Proof.\n    induction C; introv i m; simpl in *; tcsp; repndors; subst; smash_pbft; try omega;[].\n    destruct C; simpl in *; smash_pbft.\n  Qed.\n\n  Lemma entry2prepared_info_preserves_request_data :\n    forall a x rd,\n      is_request_data_for_entry a rd = true\n      -> entry2prepared_info a = Some x\n      -> prepared_info2request_data x = rd.\n  Proof.\n    introv isreq eqx.\n    destruct a; simpl in *.\n    destruct log_entry_pre_prepare_info; smash_pbft;[].\n    unfold is_request_data_for_entry, eq_request_data in *; simpl in *; smash_pbft.\n    unfold prepared_info2request_data; simpl.\n    destruct rd; simpl; auto.\n  Qed.\n  Hint Resolve entry2prepared_info_preserves_request_data : pbft.\n\n  Lemma entry2prepared_info_none_implies_is_prepared_entry_false :\n    forall a,\n      entry2prepared_info a = None\n      -> is_prepared_entry a = false.\n  Proof.\n    introv h; destruct a; simpl in *.\n    destruct log_entry_pre_prepare_info; simpl in *; smash_pbft.\n  Qed.\n\n  Lemma is_prepared_entry_implies_info_is_prepared :\n    forall a x,\n      is_prepared_entry a = true\n      -> entry2prepared_info a = Some x\n      -> well_formed_log_entry a\n      -> info_is_prepared x = true.\n  Proof.\n    introv isprep h wf.\n    unfold info_is_prepared.\n    destruct x, a, log_entry_pre_prepare_info, log_entry_request_data; simpl in *;\n      unfold prepared_info2senders, prepared_info2pp_sender, prepared_info2view in *;\n      simpl in *; smash_pbft.\n    allrw map_map; simpl in *; autorewrite with list; dands; auto.\n\n    - unfold prepared_info_has_correct_digest, prepared_info2requests; simpl; smash_pbft.\n      apply well_formed_log_entry_correct_digest in wf.\n      simpl in *.\n      unfold same_digests in wf; smash_pbft.\n\n    - apply well_formed_log_entry_prepares in wf; simpl in *.\n      apply norepeatsb_as_no_repeats.\n      rename_hyp_with length len; clear len.\n      induction log_entry_prepares; simpl in *; tcsp.\n      inversion wf as [|? ? ni norep]; subst; clear wf.\n      autodimp IHlog_entry_prepares hyp.\n      constructor; auto;[].\n      destruct a; simpl in *.\n      intro xx; apply in_map_iff in xx; exrepnd.\n      destruct x; simpl in *; subst.\n      destruct ni; apply in_map_iff; eexists; dands; eauto.\n      simpl; auto.\n\n    - apply well_formed_log_entry_no_prepare_from_leader in wf; simpl in *.\n      rewrite forallb_forall; introv xx.\n      apply in_map_iff in xx; exrepnd.\n      destruct x0; simpl in *; subst; smash_pbft.\n      destruct wf; apply in_map_iff.\n      eexists; dands; eauto.\n      simpl; auto.\n\n    - apply forallb_forall; introv xx; simpl in *.\n      apply in_map_iff in xx; exrepnd; subst; simpl in *.\n      destruct x0; simpl in *; smash_pbft.\n  Qed.\n  Hint Resolve is_prepared_entry_implies_info_is_prepared : pbft.\n\n  Lemma prepared_implies :\n    forall rd L sn,\n      well_formed_log L\n      -> prepared_log rd L = true\n      -> sn < request_data2seq rd\n      ->\n      exists pi,\n        In pi (gather_prepared_messages L sn)\n        /\\ info_is_prepared pi = true\n        /\\ prepared_info2request_data pi = rd.\n  Proof.\n    induction L; introv wf prep gtsn; simpl in *; tcsp; smash_pbft;\n      try (inversion wf as [|? ? imp wf1 wf2]; subst; clear wf); auto.\n\n    - exists x; dands; tcsp; eauto 3 with pbft.\n\n    - rewrite entry2prepared_info_none_implies_is_prepared_entry_false in prep; ginv.\n\n    - unfold is_request_data_for_entry, eq_request_data in *; smash_pbft.\n      destruct a, log_entry_request_data; simpl in *; try omega.\n\n    - eapply IHL in prep;[| |eauto];auto; exrepnd.\n      exists pi; dands; auto.\n  Qed.\n\n  Lemma pre_prepare2view_prepared_info_pre_prepare :\n    forall pi,\n      pre_prepare2view (prepared_info_pre_prepare pi)\n      = prepared_info2view pi.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite pre_prepare2view_prepared_info_pre_prepare : pbft.\n\n  Lemma requests2digest_pre_prepare2requests_prepared_info_pre_prepare :\n    forall pi,\n      info_is_prepared pi = true\n      -> requests2digest (pre_prepare2requests (prepared_info_pre_prepare pi))\n         = prepared_info2digest pi.\n  Proof.\n    introv prep.\n    apply info_is_prepared_implies_prepared_info_has_correct_digest in prep.\n    destruct pi, prepared_info_pre_prepare, b; simpl.\n    unfold prepared_info_has_correct_digest in prep; simpl in *.\n    unfold prepared_info2requests in *; simpl in *; smash_pbft.\n  Qed.\n\n  Lemma prepared_info2request_data_eq_request_data_implies_prepared_info2view :\n    forall pi v n d,\n      prepared_info2request_data pi = request_data v n d\n      -> prepared_info2view pi = v.\n  Proof.\n    introv prep; destruct pi, prepared_info_pre_prepare, b; simpl in *.\n    unfold prepared_info2request_data in *; simpl in *; ginv; tcsp.\n  Qed.\n\n  Lemma prepared_info2request_data_eq_request_data_implies_prepared_info2digest :\n    forall pi v n d,\n      prepared_info2request_data pi = request_data v n d\n      -> prepared_info2digest pi = d.\n  Proof.\n    introv prep; destruct pi, prepared_info_pre_prepare, b; simpl in *.\n    unfold prepared_info2request_data in *; simpl in *; ginv; tcsp.\n  Qed.\n\n  Lemma PBFT_A_1_4_same_loc :\n    forall (eo : EventOrdering)\n           (e  : Event)\n           (i  : Rep)\n           (n  : SeqNum)\n           (v  : View)\n           (d1 : PBFTdigest)\n           (d2 : PBFTdigest)\n           (st : PBFTstate),\n      authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> PBFTcorrect_keys eo\n      -> exists_at_most_f_faulty [e] F\n      -> loc e = PBFTreplica i\n      -> state_sm_on_event (PBFTreplicaSM i) e = Some st\n      -> prepared (request_data v n d1) st = true\n      -> prepared (request_data v n d2) st = true\n      -> d1 = d2.\n  Proof.\n    introv sentbyz ckeys atMost eqloc eqst prep1 prep2.\n    eapply A_1_4; eauto; eauto 3 with pbft eo.\n  Qed.\n\n  Lemma PBFT_A_1_4_same_loc_before :\n    forall (eo : EventOrdering)\n           (e  : Event)\n           (i  : Rep)\n           (n  : SeqNum)\n           (v  : View)\n           (d1 : PBFTdigest)\n           (d2 : PBFTdigest)\n           (st : PBFTstate),\n      authenticated_messages_were_sent_or_byz_usys eo PBFTsys\n      -> PBFTcorrect_keys eo\n      -> exists_at_most_f_faulty [e] F\n      -> loc e = PBFTreplica i\n      -> state_sm_before_event (PBFTreplicaSM i) e = Some st\n      -> prepared (request_data v n d1) st = true\n      -> prepared (request_data v n d2) st = true\n      -> d1 = d2.\n  Proof.\n    introv sentbyz ckeys atMost eqloc eqst prep1 prep2.\n    rewrite <- ite_first_state_sm_on_event_as_before in eqst.\n    unfold ite_first in *.\n    destruct (dec_isFirst e) as [d|d]; ginv; subst; simpl in *;[].\n    eapply PBFT_A_1_4_same_loc; try (exact eqst); eauto;\n      autorewrite with pbft eo in *; eauto 3 with pbft eo.\n  Qed.\n\n  Lemma prepared_info2request_data_eq_request_data_implies_prepared_info2seq :\n    forall pi v n d,\n      prepared_info2request_data pi = request_data v n d\n      -> prepared_info2seq pi = n.\n  Proof.\n    introv prep; destruct pi, prepared_info_pre_prepare, b; simpl in *.\n    unfold prepared_info2request_data in *; simpl in *; ginv; tcsp.\n  Qed.\n\n  Lemma entry2prepared_info_some_implies_is_prepared_entry :\n    forall a nfo,\n      entry2prepared_info a = Some nfo\n      -> is_prepared_entry a = true.\n  Proof.\n    introv h.\n    destruct a, log_entry_pre_prepare_info; simpl in *; smash_pbft.\n  Qed.\n  Hint Resolve entry2prepared_info_some_implies_is_prepared_entry : pbft.\n\n  Lemma in_gather_prepared_messages_implies :\n    forall nfo L n,\n      In nfo (gather_prepared_messages L n)\n      ->\n      exists entry,\n        In entry L\n        /\\ n < entry2seq entry\n        /\\ entry2prepared_info entry = Some nfo.\n  Proof.\n    induction L; introv i; simpl in *; tcsp; smash_pbft;\n      repndors; subst; tcsp;\n        try (complete (apply IHL in i; exrepnd; exists entry; tcsp)).\n    exists a; dands; tcsp.\n  Qed.\n\n  Lemma in_gather_prepared_messages_implies_prepared :\n    forall nfo L n,\n      well_formed_log L\n      -> In nfo (gather_prepared_messages L n)\n      -> prepared_log\n           (request_data\n              (prepared_info2view nfo)\n              (prepared_info2seq nfo)\n              (prepared_info2digest nfo)) L = true.\n  Proof.\n    introv wf i.\n    apply in_gather_prepared_messages_implies in i; exrepnd.\n    induction L; simpl in *; tcsp; repndors; subst; tcsp; smash_pbft;\n      try (inversion wf as [|? ? imp wf1 wf2]; subst; clear wf); tcsp;[|].\n\n    - unfold is_request_data_for_entry, eq_request_data in *.\n      smash_pbft.\n      destruct entry, log_entry_pre_prepare_info, log_entry_request_data;\n        simpl in *; smash_pbft.\n\n    - repeat (autodimp IHL hyp).\n      apply prepared_log_implies in IHL; exrepnd.\n      unfold is_request_data_for_entry, eq_request_data in *; smash_pbft.\n      rewrite IHL2 in *; clear IHL2.\n      apply imp in IHL1.\n      unfold entries_have_different_request_data in *; tcsp.\n  Qed.\n  Hint Resolve in_gather_prepared_messages_implies_prepared : pbft.\n\n  Lemma entry2prepared_info_some_implies_entry2pre_prepare_some :\n    forall entry nfo,\n      entry2prepared_info entry = Some nfo\n      -> exists pp, entry2pre_prepare entry = Some pp.\n  Proof.\n    introv h; destruct entry, log_entry_pre_prepare_info, log_entry_request_data;\n      simpl in *; smash_pbft.\n  Qed.\n\n  Lemma in_entry_implies_pre_prepare_in_log :\n    forall pp entry L,\n      well_formed_log L\n      -> In entry L\n      -> entry2pre_prepare entry = Some pp\n      -> pre_prepare_in_log pp (pre_prepare2digest pp) L = true.\n  Proof.\n    induction L; introv wf i h; simpl in *; tcsp.\n    inversion wf as [|? ? imp wf1 wf2]; subst; clear wf.\n    repndors; subst; tcsp; smash_pbft.\n\n    - clear imp IHL wf2.\n      destruct entry, log_entry_request_data, log_entry_pre_prepare_info; simpl in *; ginv; simpl in *.\n      unfold eq_request_data in *; smash_pbft.\n\n    - clear imp IHL wf2.\n      destruct entry, log_entry_request_data, log_entry_pre_prepare_info; simpl in *; ginv; simpl in *.\n      unfold eq_request_data in *; smash_pbft.\n      unfold pre_prepare2digest in *; simpl in *.\n      apply well_formed_log_entry_correct_digest in wf1; simpl in wf1.\n      unfold same_digests in *; smash_pbft.\n      rewrite requests2digest_map_fst_as_requests_and_replies2digest in n; tcsp.\n\n    - repeat (autodimp IHL hyp).\n      apply entry_of_pre_prepare_in_log2 in IHL; exrepnd.\n      applydup imp in IHL0.\n\n      unfold entries_have_different_request_data in *.\n      unfold similar_entry_and_pre_prepare in *.\n      destruct a; simpl in *.\n      unfold eq_request_data in *; smash_pbft.\n  Qed.\n\n  Lemma pre_prepare_in_log_before_implies_in_on :\n    forall (eo : EventOrdering) (e : Event) i st pp d,\n      pre_prepare_in_log pp d (log st) = true\n      -> state_sm_before_event (PBFTreplicaSM i) e = Some st\n      ->\n      exists e',\n        direct_pred e = Some e'\n        /\\ state_sm_on_event (PBFTreplicaSM i) e' = Some st.\n  Proof.\n    introv prep eqst.\n    rewrite <- ite_first_state_sm_on_event_as_before in eqst.\n    unfold ite_first in *.\n    destruct (dec_isFirst e) as [d1|d1]; ginv;[].\n    exists (local_pred e); dands; auto; eauto 3 with eo.\n  Qed.\n\n  Lemma entry2prepared_info_some_implies_equal_views :\n    forall entry nfo,\n      entry2prepared_info entry = Some nfo\n      -> entry2view entry = prepared_info2view nfo.\n  Proof.\n    introv j.\n    destruct entry, log_entry_pre_prepare_info, log_entry_request_data; simpl in *; smash_pbft.\n  Qed.\n  Hint Resolve entry2prepared_info_some_implies_equal_views : pbft.\n\n  Lemma entry2prepared_info_some_implies_equal_seqs :\n    forall entry nfo,\n      entry2prepared_info entry = Some nfo\n      -> entry2seq entry = prepared_info2seq nfo.\n  Proof.\n    introv j.\n    destruct entry, log_entry_pre_prepare_info, log_entry_request_data; simpl in *; smash_pbft.\n  Qed.\n  Hint Resolve entry2prepared_info_some_implies_equal_seqs : pbft.\n\n  Lemma entry2pre_prepare_some_implies_equal_views :\n    forall entry pp,\n      entry2pre_prepare entry = Some pp\n      -> entry2view entry = pre_prepare2view pp.\n  Proof.\n    introv h.\n    destruct entry, log_entry_request_data, log_entry_pre_prepare_info; simpl in *; smash_pbft.\n  Qed.\n  Hint Resolve entry2pre_prepare_some_implies_equal_views : pbft.\n\n  Lemma entry2pre_prepare_some_implies_equal_seqs :\n    forall entry pp,\n      entry2pre_prepare entry = Some pp\n      -> entry2seq entry = pre_prepare2seq pp.\n  Proof.\n    introv h.\n    destruct entry, log_entry_request_data, log_entry_pre_prepare_info; simpl in *; smash_pbft.\n  Qed.\n  Hint Resolve entry2pre_prepare_some_implies_equal_seqs : pbft.\n\n  Lemma entry2pre_prepare_some_implies_equal_digests :\n    forall entry pp,\n      well_formed_log_entry entry\n      -> entry2pre_prepare entry = Some pp\n      -> entry2digest entry = pre_prepare2digest pp.\n  Proof.\n    introv wf h.\n    destruct entry, log_entry_request_data, log_entry_pre_prepare_info; simpl in *; smash_pbft.\n    unfold pre_prepare2digest; simpl.\n    apply well_formed_log_entry_correct_digest in wf; simpl in *.\n    unfold same_digests in *; smash_pbft.\n  Qed.\n  Hint Resolve entry2pre_prepare_some_implies_equal_digests : pbft.\n\n  Lemma entry2prepared_info_some_implies_equal_digests :\n    forall entry nfo,\n      entry2prepared_info entry = Some nfo\n      -> entry2digest entry = prepared_info2digest nfo.\n  Proof.\n    introv j.\n    destruct entry, log_entry_pre_prepare_info, log_entry_request_data; simpl in *; smash_pbft.\n  Qed.\n  Hint Resolve entry2prepared_info_some_implies_equal_digests : pbft.\n\n  Lemma prepared_log_add_new_pre_prepare2log_implies :\n    forall rd pp d L,\n      prepared_log rd (add_new_pre_prepare2log pp d L) = true\n      -> prepared_log rd L = true \\/ similar_pre_prepare_and_request_data pp d rd = true.\n  Proof.\n    induction L; introv prep; simpl in *; tcsp; smash_pbft.\n\n    - clear IHL prep.\n      right.\n      unfold is_request_data_for_entry, eq_request_data in *; smash_pbft;[].\n      unfold similar_entry_and_pre_prepare in *; destruct a; simpl in *.\n      unfold eq_request_data in *; smash_pbft;[].\n      unfold similar_pre_prepare_and_request_data, eq_request_data; smash_pbft.\n\n    - clear IHL prep.\n      assert False; tcsp.\n      unfold is_request_data_for_entry, eq_request_data in *; smash_pbft.\n\n    - clear IHL prep.\n      assert False; tcsp.\n      unfold is_request_data_for_entry, eq_request_data in *; smash_pbft.\n  Qed.\n\n  Lemma check_send_replies_preserves_prepared_log :\n    forall i v keys giop s1 n msgs s2 rd,\n      check_send_replies i v keys giop s1 n = (msgs, s2)\n      -> prepared_log rd (log s2) = true\n      -> prepared_log rd (log s1) = true.\n  Proof.\n    introv check prep.\n    unfold check_send_replies in check; smash_pbft.\n    destruct x; smash_pbft.\n  Qed.\n\n  Lemma add_new_pre_prepare_and_prepare2log_preserves_prepared_log_backward :\n    forall rd L K pp d Fp Fc giop slf,\n      add_new_pre_prepare_and_prepare2log slf L pp d Fp Fc = (giop, K)\n      -> prepared_log rd K = true\n      -> prepared_log rd L = true \\/ similar_pre_prepare_and_request_data pp d rd = true.\n  Proof.\n    induction L; introv add prep; repeat (simpl in *; smash_pbft).\n\n    - right; clear IHL.\n      rename_hyp_with fill_out_pp_info_with_prepare fill.\n      apply fill_out_pp_info_with_prepare_preserves_request_data in fill.\n      remember (gi_entry x) as entry; clear Heqentry.\n      unfold similar_pre_prepare_and_request_data.\n      destruct a; simpl in *.\n      unfold is_request_data_for_entry in *; simpl in *.\n      unfold eq_request_data in *; smash_pbft.\n\n    - clear prep IHL.\n      assert False; tcsp.\n      rename_hyp_with fill_out_pp_info_with_prepare fill.\n      apply fill_out_pp_info_with_prepare_preserves_request_data in fill.\n      remember (gi_entry x) as entry; clear Heqentry.\n      unfold similar_pre_prepare_and_request_data.\n      destruct a; simpl in *.\n      unfold is_request_data_for_entry in *; simpl in *.\n      unfold eq_request_data in *; smash_pbft.\n\n    - clear prep IHL.\n      assert False; tcsp.\n      rename_hyp_with fill_out_pp_info_with_prepare fill.\n      apply fill_out_pp_info_with_prepare_preserves_request_data in fill.\n      remember (gi_entry x) as entry; clear Heqentry.\n      unfold similar_pre_prepare_and_request_data.\n      destruct a; simpl in *.\n      unfold is_request_data_for_entry in *; simpl in *.\n      unfold eq_request_data in *; smash_pbft.\n  Qed.\n\n  Lemma request_data2view_prepare_2request_data :\n    forall pp d,\n      request_data2view (pre_prepare2request_data pp d)\n      = pre_prepare2view pp.\n  Proof.\n    introv; destruct pp, b; tcsp.\n  Qed.\n  Hint Rewrite request_data2view_prepare_2request_data : pbft.\n\n  Lemma add_new_prepare2log_preserves_prepared_log_backward :\n    forall rd L K p Fc giop slf,\n      add_new_prepare2log slf L p Fc = (giop, K)\n      -> prepared_log rd K = true\n      -> prepared_log rd L = true \\/ rd = prepare2request_data p.\n  Proof.\n    induction L; introv add prep; repeat (simpl in *; smash_pbft).\n\n    - right; clear IHL prep.\n      rename_hyp_with add_prepare2entry add.\n      apply gi_entry_of_add_prepare2entry_some in add.\n      remember (gi_entry x) as entry; clear Heqentry.\n      unfold is_prepare_for_entry in *.\n      destruct a; simpl in *.\n      unfold is_request_data_for_entry in *; simpl in *.\n      unfold eq_request_data in *; smash_pbft.\n\n    - clear prep IHL.\n      assert False; tcsp.\n      rename_hyp_with add_prepare2entry add.\n      apply gi_entry_of_add_prepare2entry_some in add.\n      remember (gi_entry x) as entry; clear Heqentry.\n      unfold is_prepare_for_entry in *.\n      destruct a; simpl in *.\n      unfold is_request_data_for_entry in *; simpl in *.\n      unfold eq_request_data in *; smash_pbft.\n\n    - clear prep IHL.\n      assert False; tcsp.\n      rename_hyp_with add_prepare2entry add.\n      apply gi_entry_of_add_prepare2entry_some in add.\n      remember (gi_entry x) as entry; clear Heqentry.\n      unfold is_prepare_for_entry in *.\n      destruct a; simpl in *.\n      unfold is_request_data_for_entry in *; simpl in *.\n      unfold eq_request_data in *; smash_pbft.\n  Qed.\n\n  Lemma request_data2view_prepare2request_data :\n    forall p,\n      request_data2view (prepare2request_data p)\n      = prepare2view p.\n  Proof.\n    introv; destruct p, b; auto.\n  Qed.\n  Hint Rewrite request_data2view_prepare2request_data : pbft.\n\n  Lemma request_data2seq_prepare2request_data :\n    forall p,\n      request_data2seq (prepare2request_data p)\n      = prepare2seq p.\n  Proof.\n    introv; destruct p, b; auto.\n  Qed.\n  Hint Rewrite request_data2seq_prepare2request_data : pbft.\n\n  Lemma add_new_commit2log_preserves_prepared_log_backward :\n    forall rd L K com gi,\n      add_new_commit2log L com = (gi, K)\n      -> prepared_log rd K = true\n      -> prepared_log rd L = true.\n  Proof.\n    induction L; introv add prep; repeat (simpl in *; tcsp; smash_pbft2).\n\n    - destruct a; simpl in *; smash_pbft.\n\n    - clear IHL prep.\n      assert False; tcsp.\n      rename_hyp_with add_commit2entry add.\n      apply add_commit2entry_preserves_log_entry_request_data in add.\n      unfold is_request_data_for_entry, eq_request_data in *; smash_pbft.\n\n    - clear IHL prep.\n      assert False; tcsp.\n      rename_hyp_with add_commit2entry add.\n      apply add_commit2entry_preserves_log_entry_request_data in add.\n      unfold is_request_data_for_entry, eq_request_data in *; smash_pbft.\n  Qed.\n  Hint Resolve add_new_commit2log_preserves_prepared_log_backward : pbft.\n\n  Lemma clear_log_checkpoint_preserves_prepared_log2 :\n    forall rd L sn,\n      well_formed_log L\n      -> prepared_log rd (clear_log_checkpoint L sn) = true\n      -> prepared_log rd L = true /\\ sn < request_data2seq rd.\n  Proof.\n    induction L; simpl in *; introv wf h; tcsp.\n    inversion wf as [|? ? imp wf1 wf2]; subst; clear wf.\n    smash_pbft.\n\n    - assert False; tcsp.\n\n      apply IHL in h; repnd; auto.\n\n      match goal with\n      | [ H : prepared_log _ _ = _ |- _ ] => apply entry_of_prepared_log in H\n      end.\n      exrepnd.\n      pose proof (imp entry) as q; autodimp q hyp; apply q; auto.\n      allrw; auto.\n      unfold is_request_data_for_entry in *. unfold eq_request_data in *. smash_pbft.\n\n    - dands; auto.\n      unfold is_request_data_for_entry, eq_request_data in *; smash_pbft.\n      destruct a; simpl in *; auto.\n  Qed.\n\n  Lemma check_stable_preserves_prepared_backward :\n    forall rd slf state entry state',\n      well_formed_log (log state)\n      -> check_stable slf state entry = Some state'\n      -> prepared rd state' = true\n      -> prepared rd state = true\n         /\\ cp_sn entry < request_data2seq rd.\n  Proof.\n    introv wf h q.\n    unfold check_stable in h; smash_pbft;[].\n    unfold prepared in *; simpl in *.\n    apply clear_log_checkpoint_preserves_prepared_log2 in q; auto.\n  Qed.\n  Hint Resolve check_stable_preserves_prepared_backward : pbft.\n\n  Lemma find_and_execute_requests_preserves_prepared_backward :\n    forall msg i s1 s2 rd v keys,\n      find_and_execute_requests i v keys s1 = (msg, s2)\n      -> prepared rd s2 = true\n      -> prepared rd s1 = true.\n  Proof.\n    introv fexec prep.\n    unfold find_and_execute_requests in fexec; smash_pbft.\n    unfold prepared in *; simpl in *.\n    unfold execute_requests in *.\n    destruct (ready s1); smash_pbft;[].\n    unfold check_broadcast_checkpoint in *; smash_pbft2.\n  Qed.\n  Hint Resolve find_and_execute_requests_preserves_prepared_backward : pbft.\n\n  Lemma update_state_new_view_preserves_prepared_log2 :\n    forall rd i s1 nv s2 msgs,\n      correct_new_view nv = true\n      -> well_formed_log (log s1)\n      -> update_state_new_view i s1 nv = (s2, msgs)\n      -> prepared_log rd (log s2) = true\n      -> exists n,\n          view_change_cert2max_seq (new_view2cert nv) = Some n\n          /\\ prepared_log rd (log s1) = true\n          /\\\n          (\n            (\n              low_water_mark s1 < n\n              /\\ low_water_mark s2 < request_data2seq rd\n              /\\ low_water_mark s2 = n\n            )\n            \\/\n            (\n              n <= low_water_mark s1\n              /\\ low_water_mark s1 = low_water_mark s2\n            )\n          ).\n  Proof.\n    introv cor wf upd prep.\n    unfold update_state_new_view in upd; smash_pbft;[| |].\n\n    - rename_hyp_with log_checkpoint_cert_from_new_view chk.\n      rename_hyp_with view_change_cert2max_seq_vc mseq.\n\n      applydup sn_of_view_change_cert2max_seq_vc in mseq.\n      applydup view_change_cert2_max_seq_vc_some_in in mseq.\n      applydup correct_new_view_implies_correct_view_change in mseq1;auto.\n\n      applydup log_checkpoint_cert_from_new_view_preserves_log in chk.\n      subst; rewrite chk0.\n\n      eapply clear_log_checkpoint_preserves_prepared_log2 in prep; eauto;\n        try (complete (allrw <- ; auto)); repnd.\n\n      unfold view_change_cert2max_seq; allrw.\n      eexists; dands; eauto.\n\n      dup chk as chk'.\n      eapply log_checkpoint_cert_from_new_view_preserves_low_water_mark in chk';\n        [| |eauto]; auto;[].\n      dup chk as chk''.\n      eapply log_checkpoint_cert_from_new_view_preserves_low_water_mark2 in chk'';\n        [| |eauto]; auto;[].\n      rewrite chk''.\n      left; dands; try omega; auto.\n\n    - unfold view_change_cert2max_seq; allrw.\n      eexists; dands; eauto.\n\n    - rewrite view_change_cert2max_seq_vc_none_implies_correct_new_view_false in cor; auto; ginv.\n  Qed.\n\n  Lemma prepared_log_log_pre_prepares_implies :\n    forall rd P L n,\n      prepared_log rd (log_pre_prepares L n P) = true\n      -> prepared_log rd L = true\n         \\/\n         exists pp d,\n           In (pp,d) P\n           /\\ similar_pre_prepare_and_request_data pp d rd = true\n           /\\ n < request_data2seq rd.\n  Proof.\n    induction P; introv prep; simpl in *; tcsp;[].\n    repnd; smash_pbft;[|].\n\n    - apply IHP in prep.\n      repndors;[|].\n\n      + apply prepared_log_add_new_pre_prepare2log_implies in prep.\n        repndors; tcsp;[].\n\n        right.\n        exists a0 a; dands; tcsp.\n        clear IHP.\n        unfold similar_pre_prepare_and_request_data, eq_request_data in *; smash_pbft.\n\n      + exrepnd.\n        right.\n        exists pp d; dands; auto.\n\n    - apply IHP in prep; repndors; tcsp;[].\n      exrepnd.\n      right.\n      exists pp d; dands; auto.\n  Qed.\n\n  Lemma add_prepare_to_log_from_new_view_pre_prepare_preserves_prepared_log_backward :\n    forall i rd pp d s1 s2 msgs,\n      add_prepare_to_log_from_new_view_pre_prepare i s1 (pp,d) = (s2, msgs)\n      -> prepared_log rd (log s2) = true\n      -> prepared_log rd (log s1) = true\n         \\/\n         (\n           similar_pre_prepare_and_request_data pp d rd = true\n           /\\ low_water_mark s1 < pre_prepare2seq pp\n         ).\n  Proof.\n    introv add prep.\n    unfold add_prepare_to_log_from_new_view_pre_prepare in add; smash_pbft;[].\n    eapply check_send_replies_preserves_prepared_log in prep;[|eauto]; simpl in *.\n    eapply add_new_pre_prepare_and_prepare2log_preserves_prepared_log_backward in prep;[|eauto].\n    repndors; tcsp.\n  Qed.\n\n  Lemma add_prepares_to_log_from_new_view_pre_prepares_preserves_prepared_log_backward :\n    forall i rd pps s1 s2 msgs,\n      add_prepares_to_log_from_new_view_pre_prepares i s1 pps = (s2, msgs)\n      -> prepared_log rd (log s2) = true\n      -> prepared_log rd (log s1) = true\n         \\/\n         exists pp d,\n           In (pp,d) pps\n           /\\ similar_pre_prepare_and_request_data pp d rd = true\n           /\\ low_water_mark s1 < pre_prepare2seq pp.\n  Proof.\n    induction pps; introv add prep; repeat (simpl in *; tcsp; smash_pbft).\n    dup prep as prep'.\n\n    rename_hyp_with add_prepare_to_log_from_new_view_pre_prepare add.\n    applydup add_prepare_to_log_from_new_view_pre_prepare_preserves_low_water_mark in add.\n\n    eapply IHpps in prep';[|eauto].\n    repndors; repnd; tcsp.\n\n    - eapply add_prepare_to_log_from_new_view_pre_prepare_preserves_prepared_log_backward in prep';[|eauto].\n      repndors; repnd; tcsp.\n      right.\n      exists a0 a; dands; auto.\n\n    - exrepnd.\n      right.\n      exists pp d; dands; auto; try congruence.\n  Qed.\n\n  Lemma prepared_log_check_one_stable_implies :\n    forall rd i s l,\n      well_formed_log (log s)\n      -> prepared_log rd (log (check_one_stable i s l)) = true\n      -> prepared_log rd (log s) = true.\n  Proof.\n    induction l; introv wf prep; simpl in *; smash_pbft.\n    eapply check_stable_preserves_prepared_backward in prep;[| |eauto]; tcsp.\n  Qed.\n  Hint Resolve prepared_log_check_one_stable_implies : pbft.\n\n  Lemma prepared_log_from_matching_view_and_seq :\n    forall (eo : EventOrdering) (e : Event) i st rd,\n      state_sm_on_event (PBFTreplicaSM i) e = Some st\n      -> prepared_log rd (log st) = true\n      ->\n      exists e' st',\n        e' ⊑ e\n        /\\ state_sm_on_event (PBFTreplicaSM i) e' = Some st'\n        /\\ prepared_log rd (log st') = true\n        /\\ current_view st' = request_data2view rd\n        /\\ low_water_mark st' < request_data2seq rd.\n  Proof.\n    intros eo e.\n    induction e as [? ind] using predHappenedBeforeInd_local_pred;[].\n    introv eqst prep.\n\n    dup eqst as eqst_At_e; hide_hyp eqst_At_e.\n    rewrite state_sm_on_event_unroll2 in eqst.\n\n    match goal with\n    | [ H : context[map_option _ ?s] |- _ ] =>\n      remember s as sop; symmetry in Heqsop; destruct sop; simpl in *;[|ginv];op_st_some m eqtrig\n    end.\n\n    unfold PBFTreplica_update in eqst.\n\n    destruct m;\n      simpl in *; ginv; subst; tcsp;\n        try smash_handlers; try (smash_pbft_ind ind).\n\n    {\n      (* request *)\n\n      rename_hyp_with check_new_request check.\n\n      applydup prepared_log_add_new_pre_prepare2log_implies in prep; repndors;\n        [try (smash_pbft_ind ind)|];[].\n\n      unfold similar_pre_prepare_and_request_data, eq_request_data in prep0;smash_pbft;[].\n\n      exists e; eexists; dands; eauto; eauto 2 with eo; simpl.\n      autorewrite with pbft.\n      apply check_new_requests_some_iff in check; repnd; simpl in *.\n      subst; simpl in *; autorewrite with pbft in *.\n\n      rename_hyp_with check_between_water_marks bwm.\n      apply check_between_water_marks_implies_lt in bwm; auto.\n    }\n\n    {\n      (* pre-prepare *)\n\n      rename_hyp_with check_send_replies check.\n      rename_hyp_with add_new_pre_prepare_and_prepare2log add.\n      rename_hyp_with check_between_water_marks bwm.\n\n      dup prep as prep'.\n      eapply check_send_replies_preserves_prepared_log in prep';[|eauto].\n      simpl in *.\n\n      eapply add_new_pre_prepare_and_prepare2log_preserves_prepared_log_backward in prep';[|eauto].\n      repndors;[try (smash_pbft_ind ind)|];[].\n\n      applydup check_send_replies_preserves_current_view in check.\n      applydup PBFTordering.check_send_replies_preserves_low_water_mark in check.\n      simpl in *; autorewrite with pbft in *.\n\n      unfold similar_pre_prepare_and_request_data, eq_request_data in prep';smash_pbft;[].\n      apply check_between_water_marks_implies_lt in bwm; auto.\n\n      exists e; eexists; dands; eauto; eauto 2 with eo; simpl; autorewrite with pbft in *;\n        try congruence;\n        try (complete (rewrite <- check1; auto)).\n    }\n\n    {\n      (* prepare *)\n\n      rename_hyp_with check_send_replies check.\n      rename_hyp_with add_new_prepare2log add.\n      rename_hyp_with check_between_water_marks bwm.\n\n      dup prep as prep'.\n      eapply check_send_replies_preserves_prepared_log in prep';[|eauto].\n      simpl in *.\n\n      eapply add_new_prepare2log_preserves_prepared_log_backward in prep';[|eauto].\n      repndors;[try (smash_pbft_ind ind)|];[].\n\n      applydup check_send_replies_preserves_current_view in check.\n      applydup PBFTordering.check_send_replies_preserves_low_water_mark in check.\n      simpl in *; autorewrite with pbft in *.\n\n      subst.\n      apply check_between_water_marks_implies_lt in bwm; auto.\n\n      exists e; eexists; dands; eauto; eauto 2 with eo; simpl; autorewrite with pbft in *;\n        try congruence;\n        try (complete (rewrite <- check1; auto)).\n    }\n\n    {\n      (* commit *)\n\n      rename_hyp_with check_send_replies check.\n      rename_hyp_with add_new_commit2log add.\n      rename_hyp_with check_between_water_marks bwm.\n\n      dup prep as prep'.\n      eapply check_send_replies_preserves_prepared_log in prep';[|eauto].\n      simpl in *.\n\n      eapply add_new_commit2log_preserves_prepared_log_backward in prep';[|eauto].\n      try (smash_pbft_ind ind).\n    }\n\n    {\n      (* check-ready *)\n\n      rename_hyp_with find_and_execute_requests fexec.\n      dup prep as prep'.\n      eapply find_and_execute_requests_preserves_prepared_backward in prep';[|eauto].\n      unfold prepared in *.\n      try (smash_pbft_ind ind).\n    }\n\n    {\n      (* check-bcast-new-view *)\n\n      rename_hyp_with update_state_new_view upd.\n      rename_hyp_with check_broadcast_new_view check.\n      rename_hyp_with CheckBCastNewView2entry cb.\n\n      apply CheckBCastNewView2entry_some_implies in cb.\n\n      applydup update_state_new_view_preserves_current_view in upd; simpl in *.\n      applydup check_broadcast_new_view_implies in check.\n\n      dup prep as prep'.\n      eapply update_state_new_view_preserves_prepared_log2 in prep';\n        [| | |eauto];simpl in *; autorewrite with pbft in *; eauto 4 with pbft;[].\n\n      exrepnd.\n      match goal with\n      | [ H : new_view2cert _ = _ |- _ ] => rename H into eqcert\n      end.\n\n      match goal with\n      | [ H1 : view_change_cert2max_seq _ = _, H2 : view_change_cert2max_seq _ = _ |- _ ] =>\n        rename H1 into mseq1; rename H2 into mseq2\n      end.\n      rewrite <- eqcert in mseq1.\n      rewrite mseq2 in mseq1; inversion mseq1 as [xx].\n      rewrite xx in *; clear mseq1 xx.\n\n      hide_hyp upd.\n      apply prepared_log_log_pre_prepares_implies in prep'2.\n      destruct prep'2 as [prep'|prep'];[try (smash_pbft_ind ind)|];[].\n\n      exrepnd.\n\n      dup prep'1 as j.\n      eapply in_check_broadcast_new_view_implies_between_water_marks2 in j as bwm;\n        [|eauto|eauto];[].\n      apply check_between_water_marks_implies_lt in bwm; auto.\n\n      dup prep'1 as k.\n      eapply check_broadcast_new_view_preserves_view in k;[|eauto];[].\n\n      unfold similar_pre_prepare_and_request_data, eq_request_data in prep'3;smash_pbft;[].\n\n      exists e; eexists; dands; eauto; eauto 2 with eo; simpl; autorewrite with pbft in *;\n        try congruence;\n        try (complete (repndors; repnd; tcsp; rewrite <- prep'0; auto)).\n\n      applydup check_broadcast_new_view_implies_eq_views in check;[|eauto 3 with pbft];[].\n\n      rewrite k in *.\n      rewrite upd0.\n      rewrite check2.\n      rewrite less_max_view; auto.\n    }\n\n    {\n      (* new-view *)\n\n      rename_hyp_with update_state_new_view upd.\n      rename_hyp_with add_prepares_to_log_from_new_view_pre_prepares add.\n      rename_hyp_with has_new_view hnv.\n\n      applydup add_prepares_to_log_from_new_view_pre_prepares_preserves_wf in add;\n        simpl; autorewrite with pbft; eauto 3 with pbft;[].\n      applydup update_state_new_view_preserves_wf in upd; simpl; eauto 3 with pbft;[].\n\n      applydup add_prepares_to_log_from_new_view_pre_prepares_preserves_low_water_mark in add.\n      applydup add_prepares_to_log_from_new_view_pre_prepares_preserves_current_view in add.\n      applydup update_state_new_view_preserves_current_view in upd.\n      simpl in *; autorewrite with pbft in *.\n\n      dup prep as prep'.\n      eapply update_state_new_view_preserves_prepared_log2 in prep';\n        [| | |eauto];simpl in *; autorewrite with pbft in *; eauto 4 with pbft;[].\n      exrepnd.\n\n      eapply add_prepares_to_log_from_new_view_pre_prepares_preserves_prepared_log_backward in prep'2;[|eauto];[].\n      simpl in *; autorewrite with pbft in *.\n\n      destruct prep'2 as [prep'|prep'];[try (smash_pbft_ind ind)|];[].\n      exrepnd.\n\n      unfold similar_pre_prepare_and_request_data, eq_request_data in prep'4;smash_pbft;[].\n\n      dup prep'2 as j.\n      apply pre_prepare_in_map_correct_new_view_implies2 in j; auto; simpl in *.\n\n      rename_hyp_with view_change_cert2max_seq mseq.\n      unfold view_change_cert2max_seq in mseq; smash_pbft;[].\n\n      dup prep'2 as k.\n      eapply correct_new_view_implies_between_water_marks in k;auto;[|eauto].\n\n      apply check_between_water_marks_implies_lt in k; auto.\n\n      exists e; eexists; dands; eauto; eauto 2 with eo; simpl; autorewrite with pbft in *;\n        try congruence;\n        try (complete (repndors; repnd; tcsp; congruence)).\n\n      rewrite <- j.\n      rewrite upd1.\n      rewrite add2.\n      rewrite less_max_view; auto.\n    }\n  Qed.\n\n  Lemma pre_prepares_dont_get_garbage_collected :\n    forall i (eo : EventOrdering) (e1 e2 : Event) state1 state2 pp d,\n      e1 ⊏ e2\n      -> state_sm_on_event (PBFTreplicaSM i) e1 = Some state1\n      -> state_sm_on_event (PBFTreplicaSM i) e2 = Some state2\n      -> pre_prepare_in_log pp d (log state1) = true\n      -> low_water_mark state2 < pre_prepare2seq pp\n      -> pre_prepare_in_log pp d (log state2) = true.\n  Proof.\n    introv ltes eqst1 eqst2 prep1 lwm.\n    match goal with\n    | [ |- ?x = _ ] => remember x as b; symmetry in Heqb; destruct b; auto\n    end.\n    assert False; tcsp.\n    pose proof (pre_prepares_get_garbage_collected_v2 i eo e1 e2 state1 state2 pp d) as q.\n    repeat (autodimp q hyp); try omega.\n  Qed.\n\n  Lemma prepares_dont_get_garbage_collected :\n    forall i (eo : EventOrdering) (e1 e2 : Event) state1 state2 p,\n      e1 ⊏ e2\n      -> state_sm_on_event (PBFTreplicaSM i) e1 = Some state1\n      -> state_sm_on_event (PBFTreplicaSM i) e2 = Some state2\n      -> prepare_in_log p (log state1) = true\n      -> low_water_mark state2 < prepare2seq p\n      -> prepare_in_log p (log state2) = true.\n  Proof.\n    introv ltes eqst1 eqst2 prep1 lwm.\n    match goal with\n    | [ |- ?x = _ ] => remember x as b; symmetry in Heqb; destruct b; auto\n    end.\n    assert False; tcsp.\n\n    apply prepare_somewhere_in_log_iff_prepare_in_log in prep1;[|eauto 3 with pbft].\n    apply prepare_somewhere_in_log_false_iff_prepare_in_log_false in Heqb;[|eauto 3 with pbft].\n\n    pose proof (prepares_get_garbage_collected_v2 i eo e1 e2 state1 state2 p) as q.\n    repeat (autodimp q hyp); try omega.\n  Qed.\n\n  Lemma pre_prepare2digest_as_requests2digests :\n    forall v s r a,\n      pre_prepare2digest (mk_pre_prepare v s r a)\n      = requests2digest r.\n  Proof.\n    tcsp.\n  Qed.\n\n  Lemma pre_prepare2request_data_pre_prepare2digest :\n    forall pp,\n      pre_prepare2request_data pp (pre_prepare2digest pp)\n      = pre_prepare2rd pp.\n  Proof.\n    destruct pp, b; simpl; tcsp.\n  Qed.\n  Hint Rewrite pre_prepare2request_data_pre_prepare2digest : pbft.\n\n  Lemma prepared_implies2 :\n    forall rd L,\n      well_formed_log L\n      -> prepared_log rd L = true\n      ->\n      exists (R : list Rep) (pp : Pre_prepare),\n        2 * F <= length R\n        /\\ no_repeats R\n        /\\ pre_prepare_in_log pp (pre_prepare2digest pp) L = true\n        /\\ pre_prepare2rd pp = rd\n        /\\ forall i,\n            In i R\n            -> exists rt,\n              prepare_in_log (request_data_and_rep_toks2prepare rd rt) L = true\n              /\\ rt_rep rt = i.\n  Proof.\n    induction L; introv wf prep; simpl in *; tcsp.\n    inversion wf as [|? ? imp wf1 wf2]; subst; clear wf.\n    smash_pbft;[|].\n\n    - destruct a; simpl in *; smash_pbft;[].\n      unfold is_request_data_for_entry, eq_request_data in *; simpl in *; smash_pbft;[].\n      destruct log_entry_pre_prepare_info; simpl in *; ginv.\n\n      applydup well_formed_log_entry_prepares in wf1; simpl in *.\n      applydup well_formed_log_entry_correct_digest in wf1; simpl in *.\n\n      hide_hyp wf1.\n      hide_hyp imp.\n\n      unfold same_digests in *; smash_pbft.\n\n      exists (map rt_rep log_entry_prepares)\n             (request_data2pre_prepare rd (map fst reqs) auth).\n      autorewrite with pbft list in *.\n      dands; auto.\n\n      + smash_pbft.\n        destruct rd; simpl in *; autorewrite with pbft in *.\n        subst; tcsp.\n        fold (mk_pre_prepare v s (map fst reqs) auth) in *.\n        rewrite pre_prepare2digest_as_requests2digests in *.\n        rewrite requests2digest_map_fst_as_requests_and_replies2digest in n; tcsp.\n\n      + destruct rd; simpl in *; subst.\n        rewrite requests2digest_map_fst_as_requests_and_replies2digest; tcsp.\n\n      + introv j.\n        allrw in_map_iff; exrepnd; subst.\n        exists x; simpl.\n        unfold is_prepare_for_entry, eq_request_data; simpl; autorewrite with pbft.\n        smash_pbft.\n        dands; auto.\n        rewrite existsb_exists.\n        exists x; dands; auto.\n        autorewrite with pbft; auto.\n\n    - repeat (autodimp IHL hyp).\n      exrepnd.\n\n      applydup well_formed_log_entry_prepares in wf1; simpl in *.\n      applydup well_formed_log_entry_correct_digest in wf1; simpl in *.\n\n      hide_hyp wf1.\n      hide_hyp imp.\n\n      exists R pp; dands; auto.\n\n      + smash_pbft.\n        destruct a; simpl in *.\n        unfold is_request_data_for_entry, eq_request_data in *; simpl in *; smash_pbft.\n\n      + introv j.\n        applydup IHL1 in j.\n        exrepnd; subst.\n        exists rt; simpl; autorewrite with pbft.\n        smash_pbft.\n        dands; auto.\n\n        unfold is_request_data_for_entry in *.\n        unfold is_prepare_for_entry in *.\n        unfold eq_request_data in *.\n        simpl in *; smash_pbft.\n  Qed.\n\n  Lemma request_data2seq_pre_prepare2rd :\n    forall pp,\n      request_data2seq (pre_prepare2rd pp)\n      = pre_prepare2seq pp.\n  Proof.\n    introv; destruct pp, b; auto.\n  Qed.\n  Hint Rewrite request_data2seq_pre_prepare2rd : pbft.\n\n  Lemma implies_no_repeats_map_rt_rep_remove_elt :\n    forall L x,\n      no_repeats (map rt_rep L)\n      -> no_repeats (map rt_rep (remove_elt RepToksDeq x L)).\n  Proof.\n    induction L; introv norep; simpl in *; tcsp.\n    inversion norep as [|? ? diff nr]; subst; clear norep.\n    smash_pbft;[].\n    constructor; tcsp;[].\n    introv j.\n    destruct diff.\n    allrw in_map_iff; exrepnd.\n    allrw @in_remove_elt; repnd.\n    exists x0; dands; auto.\n  Qed.\n  Hint Resolve implies_no_repeats_map_rt_rep_remove_elt : pbft.\n\n  Lemma no_repeats_map_rt_rep_implies :\n    forall L,\n      no_repeats (map rt_rep L)\n      -> no_repeats L.\n  Proof.\n    induction L; introv norep; simpl in *; tcsp.\n    inversion norep as [|? ? diff nr]; subst; clear norep.\n    constructor; auto.\n    introv j; destruct diff.\n    allrw in_map_iff.\n    eexists; dands; eauto.\n  Qed.\n  Hint Resolve no_repeats_map_rt_rep_implies : pbft.\n\n  Lemma implies_le_length_of_len_of_reps :\n    forall R n L,\n      n <= length R\n      -> no_repeats R\n      -> no_repeats (map rt_rep L)\n      -> (forall i, In i R -> exists rt, existsb (same_rep_tok rt) L = true /\\ rt_rep rt = i)\n      -> n <= length L.\n  Proof.\n    induction R; introv len norep norep' imp; simpl in *; try omega;[].\n    inversion norep as [|? ? diff nr]; subst; clear norep.\n    destruct n; try omega.\n    assert (n <= length R) as len' by omega.\n    pose proof (imp a) as q; autodimp q hyp; exrepnd; subst; simpl in *.\n    rewrite existsb_exists in q1; exrepnd.\n    unfold same_rep_tok in *; smash_pbft;[].\n    pose proof (IHR n (remove_elt RepToksDeq x L)) as h; clear IHR.\n    repeat (autodimp h hyp); eauto 3 with pbft;[|].\n\n    {\n      introv j.\n      pose proof (imp i) as q; autodimp q hyp; exrepnd.\n      allrw existsb_exists; exrepnd; smash_pbft.\n      destruct (RepToksDeq x x0); subst; tcsp.\n\n      exists x0; dands; auto.\n      allrw existsb_exists.\n      exists x0; smash_pbft; dands; auto.\n      apply in_remove_elt; dands; auto.\n    }\n\n    {\n      rewrite length_remove_elt_if_no_repeats in h; eauto 3 with pbft.\n      smash_pbft; try omega.\n      destruct L; simpl in *; try omega.\n    }\n  Qed.\n\n  Lemma implies_prepared :\n    forall R rd pp d L,\n      well_formed_log L\n      -> 2 * F <= length R\n      -> no_repeats R\n      -> pre_prepare_in_log pp d L = true\n      -> similar_pre_prepare_and_request_data pp d rd = true\n      -> (forall i,\n             In i R\n             -> exists rt,\n               prepare_in_log (request_data_and_rep_toks2prepare rd rt) L = true\n               /\\ rt_rep rt = i)\n      -> prepared_log rd L = true.\n  Proof.\n    induction L; introv wf len norep prep sim imp; simpl in *; tcsp;[].\n    inversion wf as [|? ? diff wf1 wf2]; subst; clear wf.\n    smash_pbft.\n\n    - destruct a; simpl in *.\n      allrw requests_matches_logEntryPrePrepareInfo_true_iff; repnd.\n      destruct log_entry_pre_prepare_info; simpl in *; tcsp;[].\n      unfold is_request_data_for_entry, eq_request_data in *; simpl in *.\n      smash_pbft;[].\n      dands; auto; GC;[].\n\n      applydup well_formed_log_entry_prepares in wf1; simpl in *.\n\n      clear diff wf1 IHL sim wf2.\n\n      unfold is_prepare_for_entry in *; simpl in *.\n\n      assert (forall i : Rep,\n                 In i R\n                 ->\n                 exists rt,\n                   existsb (same_rep_tok rt) log_entry_prepares = true\n                   /\\ rt_rep rt = i) as imp'.\n      {\n        introv k.\n        apply imp in k; clear imp.\n        exrepnd; autorewrite with pbft in *.\n        exists rt; auto.\n      }\n      clear imp.\n\n      eapply implies_le_length_of_len_of_reps; eauto.\n\n    - clear IHL imp wf1 wf2 diff prep prep0.\n\n      destruct a; simpl in *.\n      unfold is_request_data_for_entry in *; simpl in *.\n      unfold similar_pre_prepare_and_request_data in *.\n      unfold eq_request_data in *; smash_pbft.\n\n    - clear IHL imp wf1 wf2 diff prep.\n\n      destruct a; simpl in *.\n      unfold is_request_data_for_entry in *; simpl in *.\n      unfold similar_pre_prepare_and_request_data in *.\n      unfold eq_request_data in *; smash_pbft.\n\n    - repeat (autodimp IHL hyp).\n      introv j.\n      applydup imp in j; exrepnd; clear imp.\n      autorewrite with pbft in *.\n      smash_pbft.\n\n      clear diff wf1 wf2.\n\n      destruct a; simpl in *.\n      unfold is_request_data_for_entry in *; simpl in *.\n      unfold is_prepare_for_entry in *; simpl in *.\n      unfold eq_request_data in *; smash_pbft.\n  Qed.\n\n  Lemma prepared_get_garbage_collected :\n    forall i (eo : EventOrdering) (e1 e2 : Event) state1 state2 rd,\n      e1 ⊏ e2\n      -> state_sm_on_event (PBFTreplicaSM i) e1 = Some state1\n      -> state_sm_on_event (PBFTreplicaSM i) e2 = Some state2\n      -> prepared rd state1 = true\n      -> prepared rd state2 = false\n      -> request_data2seq rd <= low_water_mark state2.\n  Proof.\n    introv ltes eqst1 eqst2 prep1 prep2.\n\n    destruct (le_dec (request_data2seq rd) (low_water_mark state2)) as [d|d]; tcsp;[].\n    rewrite <- not_true_iff_false in prep2; destruct prep2.\n    assert (low_water_mark state2 < request_data2seq rd) as ltrd by omega.\n    clear d.\n\n    applydup prepared_implies2 in prep1;[|eauto 2 with pbft].\n    exrepnd.\n\n    eapply pre_prepares_dont_get_garbage_collected in prep4;\n      [| |exact eqst1|exact eqst2|]; auto;\n        [|subst;autorewrite with pbft in *; auto];[].\n\n    assert (forall i : Rep,\n               In i R\n               ->\n               exists rt,\n                 prepare_in_log (request_data_and_rep_toks2prepare rd rt) (log state2) = true\n                 /\\ rt_rep rt = i) as imp.\n    {\n      introv j.\n      applydup prep0 in j; exrepnd.\n      exists rt; dands; auto.\n      eapply prepares_dont_get_garbage_collected in j0;\n        [| |exact eqst1|exact eqst2|]; auto; autorewrite with pbft in *; auto.\n    }\n\n    hide_hyp prep0.\n\n    eapply implies_prepared;[|eauto|eauto|eauto| |];auto;[eauto 2 with pbft|].\n    subst.\n    unfold similar_pre_prepare_and_request_data, eq_request_data; smash_pbft.\n  Qed.\n\nEnd PBFT_A_1_9_misc4.\n\n\nHint Resolve entry2prepared_info_preserves_request_data : pbft.\nHint Resolve is_prepared_entry_implies_info_is_prepared : pbft.\nHint Resolve entry2prepared_info_some_implies_is_prepared_entry : pbft.\nHint Resolve in_gather_prepared_messages_implies_prepared : pbft.\nHint Resolve entry2prepared_info_some_implies_equal_views : pbft.\nHint Resolve entry2prepared_info_some_implies_equal_seqs : pbft.\nHint Resolve entry2pre_prepare_some_implies_equal_views : pbft.\nHint Resolve entry2pre_prepare_some_implies_equal_seqs : pbft.\nHint Resolve entry2pre_prepare_some_implies_equal_digests : pbft.\nHint Resolve entry2prepared_info_some_implies_equal_digests : pbft.\nHint Resolve add_new_commit2log_preserves_prepared_log_backward : pbft.\nHint Resolve check_stable_preserves_prepared_backward : pbft.\nHint Resolve find_and_execute_requests_preserves_prepared_backward : pbft.\nHint Resolve implies_no_repeats_map_rt_rep_remove_elt : pbft.\nHint Resolve no_repeats_map_rt_rep_implies : pbft.\nHint Resolve prepared_log_check_one_stable_implies : pbft.\n\n\nHint Rewrite @pre_prepare2view_prepared_info_pre_prepare : pbft.\nHint Rewrite @request_data2view_prepare_2request_data : pbft.\nHint Rewrite @request_data2view_prepare2request_data : pbft.\nHint Rewrite @request_data2seq_prepare2request_data : pbft.\nHint Rewrite @pre_prepare2request_data_pre_prepare2digest : pbft.\nHint Rewrite @request_data2seq_pre_prepare2rd : pbft.\n", "meta": {"author": "vrahli", "repo": "Velisarios", "sha": "6fb353b18610cd79210755fcc90123536c367aaa", "save_path": "github-repos/coq/vrahli-Velisarios", "path": "github-repos/coq/vrahli-Velisarios/Velisarios-6fb353b18610cd79210755fcc90123536c367aaa/PBFT/PBFT_A_1_9_misc4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.22256175291053035}}
{"text": "From Coq Require Export ZArith Utf8.\nFrom compcert Require Export Integers Values Csyntax Smallstep Csem.\n\nInductive compcertc_final_state(Q: Z → Prop): state → Prop :=\n  compcertc_final_state_intro i m:\n  Q (Int.signed i) → compcertc_final_state Q (Returnstate (Vint i) Kstop m).\n\nDefinition compcertc_safe_state_n(Q: Z → Prop)(p: program)(n: nat)(s: state): Prop :=\n  ∀ trace s',\n  starN (Smallstep.step (Csem.semantics p)) (Smallstep.globalenv (Csem.semantics p)) n s trace s' →\n  compcertc_final_state Q s' ∨\n  ∃ trace' s'', Step (Csem.semantics p) s' trace' s''.\n\nDefinition compcertc_safe_state(Q: Z → Prop)(p: program)(s: state): Prop :=\n  ∀ n, compcertc_safe_state_n Q p n s.\n\nInductive compcertc_safe_program(Q: Z → Prop)(p: program): Prop :=\n  compcertc_safe_program_intro s0:\n  Csem.initial_state p s0 → compcertc_safe_state Q p s0 → compcertc_safe_program Q p.", "meta": {"author": "btj", "repo": "ch2o-compcert", "sha": "286d73579becdd03ed877a614caf2161171859bd", "save_path": "github-repos/coq/btj-ch2o-compcert", "path": "github-repos/coq/btj-ch2o-compcert/ch2o-compcert-286d73579becdd03ed877a614caf2161171859bd/compcertc_safety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.3276683073862188, "lm_q1q2_score": 0.22254533051596515}}
{"text": "From iris.program_logic Require Export weakestpre.\nFrom iris.proofmode Require Import tactics.\nFrom iris.bi Require Import fixpoint big_op.\nSet Default Proof Using \"Type\".\nImport uPred.\n\nDefinition twp_pre `{irisG Λ Σ} (s : stuckness)\n      (wp : coPset → expr Λ → (val Λ → iProp Σ) → iProp Σ) :\n    coPset → expr Λ → (val Λ → iProp Σ) → iProp Σ := λ E e1 Φ,\n  match to_val e1 with\n  | Some v => |={E}=> Φ v\n  | None => ∀ σ1 κs n,\n     state_interp σ1 κs n ={E,∅}=∗\n       ⌜if s is NotStuck then reducible_no_obs e1 σ1 else True⌝ ∗\n       ∀ κ e2 σ2 efs, ⌜prim_step e1 σ1 κ e2 σ2 efs⌝ ={∅,E}=∗\n         ⌜κ = []⌝ ∗\n         state_interp σ2 κs (length efs + n) ∗\n         wp E e2 Φ ∗\n         [∗ list] ef ∈ efs, wp ⊤ ef fork_post\n  end%I.\n\nLemma twp_pre_mono `{irisG Λ Σ} s\n    (wp1 wp2 : coPset → expr Λ → (val Λ → iProp Σ) → iProp Σ) :\n  ((□ ∀ E e Φ, wp1 E e Φ -∗ wp2 E e Φ) →\n  ∀ E e Φ, twp_pre s wp1 E e Φ -∗ twp_pre s wp2 E e Φ)%I.\nProof.\n  iIntros \"#H\"; iIntros (E e1 Φ) \"Hwp\". rewrite /twp_pre.\n  destruct (to_val e1) as [v|]; first done.\n  iIntros (σ1 κs n) \"Hσ\". iMod (\"Hwp\" with \"Hσ\") as \"($ & Hwp)\"; iModIntro.\n  iIntros (κ e2 σ2 efs) \"Hstep\".\n  iMod (\"Hwp\" with \"Hstep\") as (?) \"(Hσ & Hwp & Hfork)\".\n  iModIntro. iFrame \"Hσ\". iSplit; first done. iSplitL \"Hwp\".\n  - by iApply \"H\".\n  - iApply (@big_sepL_impl with \"Hfork\"); iIntros \"!#\" (k e _) \"Hwp\".\n    by iApply \"H\".\nQed.\n\n(* Uncurry [twp_pre] and equip its type with an OFE structure *)\nDefinition twp_pre' `{irisG Λ Σ} (s : stuckness) :\n  (prodC (prodC (leibnizC coPset) (exprC Λ)) (val Λ -c> iProp Σ) → iProp Σ) →\n  prodC (prodC (leibnizC coPset) (exprC Λ)) (val Λ -c> iProp Σ) → iProp Σ :=\n    curry3 ∘ twp_pre s ∘ uncurry3.\n\nLocal Instance twp_pre_mono' `{irisG Λ Σ} s : BiMonoPred (twp_pre' s).\nProof.\n  constructor.\n  - iIntros (wp1 wp2) \"#H\"; iIntros ([[E e1] Φ]); iRevert (E e1 Φ).\n    iApply twp_pre_mono. iIntros \"!#\" (E e Φ). iApply (\"H\" $! (E,e,Φ)).\n  - intros wp Hwp n [[E1 e1] Φ1] [[E2 e2] Φ2]\n      [[?%leibniz_equiv ?%leibniz_equiv] ?]; simplify_eq/=.\n    rewrite /uncurry3 /twp_pre. do 24 (f_equiv || done). by apply pair_ne.\nQed.\n\nDefinition twp_def `{irisG Λ Σ} (s : stuckness) (E : coPset)\n    (e : expr Λ) (Φ : val Λ → iProp Σ) :\n  iProp Σ := bi_least_fixpoint (twp_pre' s) (E,e,Φ).\nDefinition twp_aux `{irisG Λ Σ} : seal (@twp_def Λ Σ _). by eexists. Qed.\nInstance twp' `{irisG Λ Σ} : Twp Λ (iProp Σ) stuckness := twp_aux.(unseal).\nDefinition twp_eq `{irisG Λ Σ} : twp = @twp_def Λ Σ _ := twp_aux.(seal_eq).\n\nSection twp.\nContext `{irisG Λ Σ}.\nImplicit Types s : stuckness.\nImplicit Types P : iProp Σ.\nImplicit Types Φ : val Λ → iProp Σ.\nImplicit Types v : val Λ.\nImplicit Types e : expr Λ.\n\n(* Weakest pre *)\nLemma twp_unfold s E e Φ : WP e @ s; E [{ Φ }] ⊣⊢ twp_pre s (twp s) E e Φ.\nProof. by rewrite twp_eq /twp_def least_fixpoint_unfold. Qed.\nLemma twp_ind s Ψ :\n  (∀ n E e, Proper (pointwise_relation _ (dist n) ==> dist n) (Ψ E e)) →\n  (□ (∀ e E Φ, twp_pre s (λ E e Φ, Ψ E e Φ ∧ WP e @ s; E [{ Φ }]) E e Φ -∗ Ψ E e Φ) →\n  ∀ e E Φ, WP e @ s; E [{ Φ }] -∗ Ψ E e Φ)%I.\nProof.\n  iIntros (HΨ). iIntros \"#IH\" (e E Φ) \"H\". rewrite twp_eq.\n  set (Ψ' := curry3 Ψ :\n    prodC (prodC (leibnizC coPset) (exprC Λ)) (val Λ -c> iProp Σ) → iProp Σ).\n  assert (NonExpansive Ψ').\n  { intros n [[E1 e1] Φ1] [[E2 e2] Φ2]\n      [[?%leibniz_equiv ?%leibniz_equiv] ?]; simplify_eq/=. by apply HΨ. }\n  iApply (least_fixpoint_strong_ind _ Ψ' with \"[] H\").\n  iIntros \"!#\" ([[??] ?]) \"H\". by iApply \"IH\".\nQed.\n\nGlobal Instance twp_ne s E e n :\n  Proper (pointwise_relation _ (dist n) ==> dist n) (twp (PROP:=iProp Σ) s E e).\nProof.\n  intros Φ1 Φ2 HΦ. rewrite !twp_eq. by apply (least_fixpoint_ne _), pair_ne, HΦ.\nQed.\nGlobal Instance twp_proper s E e :\n  Proper (pointwise_relation _ (≡) ==> (≡)) (twp (PROP:=iProp Σ) s E e).\nProof.\n  by intros Φ Φ' ?; apply equiv_dist=>n; apply twp_ne=>v; apply equiv_dist.\nQed.\n\nLemma twp_value' s E Φ v : Φ v -∗ WP of_val v @ s; E [{ Φ }].\nProof. iIntros \"HΦ\". rewrite twp_unfold /twp_pre to_of_val. auto. Qed.\nLemma twp_value_inv' s E Φ v : WP of_val v @ s; E [{ Φ }] ={E}=∗ Φ v.\nProof. by rewrite twp_unfold /twp_pre to_of_val. Qed.\n\nLemma twp_strong_mono s1 s2 E1 E2 e Φ Ψ :\n  s1 ⊑ s2 → E1 ⊆ E2 →\n  WP e @ s1; E1 [{ Φ }] -∗ (∀ v, Φ v ={E2}=∗ Ψ v) -∗ WP e @ s2; E2 [{ Ψ }].\nProof.\n  iIntros (? HE) \"H HΦ\". iRevert (E2 Ψ HE) \"HΦ\"; iRevert (e E1 Φ) \"H\".\n  iApply twp_ind; first solve_proper.\n  iIntros \"!#\" (e E1 Φ) \"IH\"; iIntros (E2 Ψ HE) \"HΦ\".\n  rewrite !twp_unfold /twp_pre. destruct (to_val e) as [v|] eqn:?.\n  { iApply (\"HΦ\" with \"[> -]\"). by iApply (fupd_mask_mono E1 _). }\n  iIntros (σ1 κs n) \"Hσ\". iMod (fupd_intro_mask' E2 E1) as \"Hclose\"; first done.\n  iMod (\"IH\" with \"[$]\") as \"[% IH]\".\n  iModIntro; iSplit; [by destruct s1, s2|]. iIntros (κ e2 σ2 efs Hstep).\n  iMod (\"IH\" with \"[//]\") as (?) \"(Hσ & IH & IHefs)\"; auto.\n  iMod \"Hclose\" as \"_\"; iModIntro.\n  iFrame \"Hσ\". iSplit; first done. iSplitR \"IHefs\".\n  - iDestruct \"IH\" as \"[IH _]\". iApply (\"IH\" with \"[//] HΦ\").\n  - iApply (big_sepL_impl with \"IHefs\"); iIntros \"!#\" (k ef _) \"[IH _]\".\n    iApply \"IH\"; auto.\nQed.\n\nLemma fupd_twp s E e Φ : (|={E}=> WP e @ s; E [{ Φ }]) -∗ WP e @ s; E [{ Φ }].\nProof.\n  rewrite twp_unfold /twp_pre. iIntros \"H\". destruct (to_val e) as [v|] eqn:?.\n  { by iMod \"H\". }\n  iIntros (σ1 κs n) \"Hσ1\". iMod \"H\". by iApply \"H\".\nQed.\nLemma twp_fupd s E e Φ : WP e @ s; E [{ v, |={E}=> Φ v }] -∗ WP e @ s; E [{ Φ }].\nProof. iIntros \"H\". iApply (twp_strong_mono with \"H\"); auto. Qed.\n\nLemma twp_atomic s E1 E2 e Φ `{!Atomic (stuckness_to_atomicity s) e} :\n  (|={E1,E2}=> WP e @ s; E2 [{ v, |={E2,E1}=> Φ v }]) -∗ WP e @ s; E1 [{ Φ }].\nProof.\n  iIntros \"H\". rewrite !twp_unfold /twp_pre /=.\n  destruct (to_val e) as [v|] eqn:He.\n  { by iDestruct \"H\" as \">>> $\". }\n  iIntros (σ1 κs n) \"Hσ\". iMod \"H\". iMod (\"H\" $! σ1 with \"Hσ\") as \"[$ H]\".\n  iModIntro. iIntros (κ e2 σ2 efs Hstep).\n  iMod (\"H\" with \"[//]\") as (?) \"(Hσ & H & Hefs)\". destruct s.\n  - rewrite !twp_unfold /twp_pre. destruct (to_val e2) as [v2|] eqn:He2.\n    + iDestruct \"H\" as \">> $\". by iFrame.\n    + iMod (\"H\" with \"[$]\") as \"[H _]\". iDestruct \"H\" as %(? & ? & ? & ?).\n      by edestruct (atomic _ _ _ _ _ Hstep).\n  - destruct (atomic _ _ _ _ _ Hstep) as [v <-%of_to_val].\n    iMod (twp_value_inv' with \"H\") as \">H\".\n    iModIntro. iSplit; first done. iFrame \"Hσ Hefs\". by iApply twp_value'.\nQed.\n\nLemma twp_bind K `{!LanguageCtx K} s E e Φ :\n  WP e @ s; E [{ v, WP K (of_val v) @ s; E [{ Φ }] }] -∗ WP K e @ s; E [{ Φ }].\nProof.\n  revert Φ. cut (∀ Φ', WP e @ s; E [{ Φ' }] -∗ ∀ Φ,\n    (∀ v, Φ' v -∗ WP K (of_val v) @ s; E [{ Φ }]) -∗ WP K e @ s; E [{ Φ }]).\n  { iIntros (help Φ) \"H\". iApply (help with \"H\"); auto. }\n  iIntros (Φ') \"H\". iRevert (e E Φ') \"H\". iApply twp_ind; first solve_proper.\n  iIntros \"!#\" (e E1 Φ') \"IH\". iIntros (Φ) \"HΦ\".\n  rewrite /twp_pre. destruct (to_val e) as [v|] eqn:He.\n  { apply of_to_val in He as <-. iApply fupd_twp. by iApply \"HΦ\". }\n  rewrite twp_unfold /twp_pre fill_not_val //.\n  iIntros (σ1 κs n) \"Hσ\". iMod (\"IH\" with \"[$]\") as \"[% IH]\". iModIntro; iSplit.\n  { iPureIntro. unfold reducible_no_obs in *.\n    destruct s; naive_solver eauto using fill_step. }\n  iIntros (κ e2 σ2 efs Hstep).\n  destruct (fill_step_inv e σ1 κ e2 σ2 efs) as (e2'&->&?); auto.\n  iMod (\"IH\" $! κ e2' σ2 efs with \"[//]\") as (?) \"(Hσ & IH & IHefs)\".\n  iModIntro. iFrame \"Hσ\". iSplit; first done. iSplitR \"IHefs\".\n  - iDestruct \"IH\" as \"[IH _]\". by iApply \"IH\".\n  - by setoid_rewrite and_elim_r.\nQed.\n\nLemma twp_bind_inv K `{!LanguageCtx K} s E e Φ :\n  WP K e @ s; E [{ Φ }] -∗ WP e @ s; E [{ v, WP K (of_val v) @ s; E [{ Φ }] }].\nProof.\n  iIntros \"H\". remember (K e) as e' eqn:He'.\n  iRevert (e He'). iRevert (e' E Φ) \"H\". iApply twp_ind; first solve_proper.\n  iIntros \"!#\" (e' E1 Φ) \"IH\". iIntros (e ->).\n  rewrite !twp_unfold {2}/twp_pre. destruct (to_val e) as [v|] eqn:He.\n  { iModIntro. apply of_to_val in He as <-. rewrite !twp_unfold.\n    iApply (twp_pre_mono with \"[] IH\"). by iIntros \"!#\" (E e Φ') \"[_ ?]\". }\n  rewrite /twp_pre fill_not_val //.\n  iIntros (σ1 κs n) \"Hσ\". iMod (\"IH\" with \"[$]\") as \"[% IH]\". iModIntro; iSplit.\n  { destruct s; eauto using reducible_no_obs_fill. }\n  iIntros (κ e2 σ2 efs Hstep).\n  iMod (\"IH\" $! κ (K e2) σ2 efs with \"[]\") as (?) \"(Hσ & IH & IHefs)\"; eauto using fill_step.\n  iModIntro. iFrame \"Hσ\". iSplit; first done. iSplitR \"IHefs\".\n  - iDestruct \"IH\" as \"[IH _]\". by iApply \"IH\".\n  - by setoid_rewrite and_elim_r.\nQed.\n\nLemma twp_wp s E e Φ : WP e @ s; E [{ Φ }] -∗ WP e @ s; E {{ Φ }}.\nProof.\n  iIntros \"H\". iLöb as \"IH\" forall (E e Φ).\n  rewrite wp_unfold twp_unfold /wp_pre /twp_pre. destruct (to_val e) as [v|]=>//.\n  iIntros (σ1 κ κs n) \"Hσ\". iMod (\"H\" with \"Hσ\") as \"[% H]\". iIntros \"!>\". iSplitR.\n  { destruct s; last done. eauto using reducible_no_obs_reducible. }\n  iIntros (e2 σ2 efs) \"Hstep\". iMod (\"H\" with \"Hstep\") as (->) \"(Hσ & H & Hfork)\".\n  iApply step_fupd_intro; [set_solver+|]. iNext.\n  iFrame \"Hσ\". iSplitL \"H\". by iApply \"IH\".\n  iApply (@big_sepL_impl with \"Hfork\").\n  iIntros \"!#\" (k ef _) \"H\". by iApply \"IH\".\nQed.\n\n(** * Derived rules *)\nLemma twp_mono s E e Φ Ψ :\n  (∀ v, Φ v -∗ Ψ v) → WP e @ s; E [{ Φ }] -∗ WP e @ s; E [{ Ψ }].\nProof.\n  iIntros (HΦ) \"H\"; iApply (twp_strong_mono with \"H\"); auto.\n  iIntros (v) \"?\". by iApply HΦ.\nQed.\nLemma twp_stuck_mono s1 s2 E e Φ :\n  s1 ⊑ s2 → WP e @ s1; E [{ Φ }] ⊢ WP e @ s2; E [{ Φ }].\nProof. iIntros (?) \"H\". iApply (twp_strong_mono with \"H\"); auto. Qed.\nLemma twp_stuck_weaken s E e Φ :\n  WP e @ s; E [{ Φ }] ⊢ WP e @ E ?[{ Φ }].\nProof. apply twp_stuck_mono. by destruct s. Qed.\nLemma twp_mask_mono s E1 E2 e Φ :\n  E1 ⊆ E2 → WP e @ s; E1 [{ Φ }] -∗ WP e @ s; E2 [{ Φ }].\nProof. iIntros (?) \"H\"; iApply (twp_strong_mono with \"H\"); auto. Qed.\nGlobal Instance twp_mono' s E e :\n  Proper (pointwise_relation _ (⊢) ==> (⊢)) (twp (PROP:=iProp Σ) s E e).\nProof. by intros Φ Φ' ?; apply twp_mono. Qed.\n\nLemma twp_value s E Φ e v : IntoVal e v → Φ v -∗ WP e @ s; E [{ Φ }].\nProof. intros <-. by apply twp_value'. Qed.\nLemma twp_value_fupd' s E Φ v : (|={E}=> Φ v) -∗ WP of_val v @ s; E [{ Φ }].\nProof. intros. by rewrite -twp_fupd -twp_value'. Qed.\nLemma twp_value_fupd s E Φ e v : IntoVal e v → (|={E}=> Φ v) -∗ WP e @ s; E [{ Φ }].\nProof. intros ?. rewrite -twp_fupd -twp_value //. Qed.\nLemma twp_value_inv s E Φ e v : IntoVal e v → WP e @ s; E [{ Φ }] ={E}=∗ Φ v.\nProof. intros <-. by apply twp_value_inv'. Qed.\n\nLemma twp_frame_l s E e Φ R : R ∗ WP e @ s; E [{ Φ }] -∗ WP e @ s; E [{ v, R ∗ Φ v }].\nProof. iIntros \"[? H]\". iApply (twp_strong_mono with \"H\"); auto with iFrame. Qed.\nLemma twp_frame_r s E e Φ R : WP e @ s; E [{ Φ }] ∗ R -∗ WP e @ s; E [{ v, Φ v ∗ R }].\nProof. iIntros \"[H ?]\". iApply (twp_strong_mono with \"H\"); auto with iFrame. Qed.\n\nLemma twp_wand s E e Φ Ψ :\n  WP e @ s; E [{ Φ }] -∗ (∀ v, Φ v -∗ Ψ v) -∗ WP e @ s; E [{ Ψ }].\nProof.\n  iIntros \"H HΦ\". iApply (twp_strong_mono with \"H\"); auto.\n  iIntros (?) \"?\". by iApply \"HΦ\".\nQed.\nLemma twp_wand_l s E e Φ Ψ :\n  (∀ v, Φ v -∗ Ψ v) ∗ WP e @ s; E [{ Φ }] -∗ WP e @ s; E [{ Ψ }].\nProof. iIntros \"[H Hwp]\". iApply (twp_wand with \"Hwp H\"). Qed.\nLemma twp_wand_r s E e Φ Ψ :\n  WP e @ s; E [{ Φ }] ∗ (∀ v, Φ v -∗ Ψ v) -∗ WP e @ s; E [{ Ψ }].\nProof. iIntros \"[Hwp H]\". iApply (twp_wand with \"Hwp H\"). Qed.\nEnd twp.\n\n(** Proofmode class instances *)\nSection proofmode_classes.\n  Context `{irisG Λ Σ}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types Φ : val Λ → iProp Σ.\n\n  Global Instance frame_twp p s E e R Φ Ψ :\n    (∀ v, Frame p R (Φ v) (Ψ v)) →\n    Frame p R (WP e @ s; E [{ Φ }]) (WP e @ s; E [{ Ψ }]).\n  Proof. rewrite /Frame=> HR. rewrite twp_frame_l. apply twp_mono, HR. Qed.\n\n  Global Instance is_except_0_wp s E e Φ : IsExcept0 (WP e @ s; E [{ Φ }]).\n  Proof. by rewrite /IsExcept0 -{2}fupd_twp -except_0_fupd -fupd_intro. Qed.\n\n  Global Instance elim_modal_bupd_twp p s E e P Φ :\n    ElimModal True p false (|==> P) P (WP e @ s; E [{ Φ }]) (WP e @ s; E [{ Φ }]).\n  Proof.\n    by rewrite /ElimModal intuitionistically_if_elim\n      (bupd_fupd E) fupd_frame_r wand_elim_r fupd_twp.\n  Qed.\n\n  Global Instance elim_modal_fupd_twp p s E e P Φ :\n    ElimModal True p false (|={E}=> P) P (WP e @ s; E [{ Φ }]) (WP e @ s; E [{ Φ }]).\n  Proof.\n    by rewrite /ElimModal intuitionistically_if_elim\n      fupd_frame_r wand_elim_r fupd_twp.\n  Qed.\n\n  Global Instance elim_modal_fupd_twp_atomic p s E1 E2 e P Φ :\n    Atomic (stuckness_to_atomicity s) e →\n    ElimModal True p false (|={E1,E2}=> P) P\n            (WP e @ s; E1 [{ Φ }]) (WP e @ s; E2 [{ v, |={E2,E1}=> Φ v }])%I.\n  Proof.\n    intros. by rewrite /ElimModal intuitionistically_if_elim\n      fupd_frame_r wand_elim_r twp_atomic.\n  Qed.\n\n  Global Instance add_modal_fupd_twp s E e P Φ :\n    AddModal (|={E}=> P) P (WP e @ s; E [{ Φ }]).\n  Proof. by rewrite /AddModal fupd_frame_r wand_elim_r fupd_twp. Qed.\nEnd proofmode_classes.\n", "meta": {"author": "izgzhen", "repo": "iris-coq", "sha": "4a1eb8a3d20789af6265b9011939be8274da042c", "save_path": "github-repos/coq/izgzhen-iris-coq", "path": "github-repos/coq/izgzhen-iris-coq/iris-coq-4a1eb8a3d20789af6265b9011939be8274da042c/theories/program_logic/total_weakestpre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22241572906712487}}
{"text": "Require Import Coq.Strings.String\n        Coq.omega.Omega\n        Coq.Lists.List\n        Coq.Logic.FunctionalExtensionality\n        Coq.Sets.Ensembles\n        Fiat.Common.List.ListFacts\n        Fiat.Common.Ensembles.IndexedEnsembles\n        Fiat.Common.ilist2\n        Fiat.Computation\n        Fiat.Computation.Refinements.Iterate_Decide_Comp\n        Fiat.ADT\n        Fiat.ADTRefinement\n        Fiat.ADTNotation\n        Fiat.QueryStructure.Specification.Representation.Schema\n        Fiat.QueryStructure.Specification.Representation.QueryStructureSchema\n        Fiat.ADTRefinement.BuildADTRefinements\n        Fiat.QueryStructure.Specification.Representation.QueryStructure\n        Fiat.QueryStructure.Specification.Operations.Query\n        Fiat.QueryStructure.Specification.Operations.Mutate\n        Fiat.QueryStructure.Implementation.Constraints.ConstraintChecksRefinements\n        Fiat.Common.IterateBoundedIndex\n        Fiat.Common.DecideableEnsembles\n        Fiat.Common.List.PermutationFacts\n        Fiat.QueryStructure.Implementation.Operations.General.QueryRefinements\n        Fiat.Common.Ensembles.EnsembleListEquivalence.\n\n(* Facts about implements delete operations. *)\n\nSection MutateRefinements.\n\n  Hint Resolve crossConstr.\n  Hint Unfold SatisfiesCrossRelationConstraints\n       SatisfiesAttributeConstraints\n       SatisfiesTupleConstraints.\n\n  Arguments GetUnConstrRelation : simpl never.\n  Arguments UpdateUnConstrRelation : simpl never.\n  Arguments replace_BoundedIndex : simpl never.\n  Arguments BuildQueryStructureConstraints : simpl never.\n  Arguments BuildQueryStructureConstraints' : simpl never.\n\n  Program\n    Definition Mutate_Valid\n    (qsSchema : QueryStructureSchema)\n    (qs : QueryStructure qsSchema)\n    (Ridx : _)\n    (MutatedTuples : @IndexedEnsemble RawTuple)\n    (attrConstr :\n       (forall tup : IndexedRawTuple,\n         GetRelation qs Ridx tup\n         -> SatisfiesAttributeConstraints Ridx (indexedElement tup))\n       -> MutationPreservesAttributeConstraints MutatedTuples (SatisfiesAttributeConstraints Ridx))\n    (tupConstr :\n       (forall tup tup' : IndexedRawTuple,\n          elementIndex tup <> elementIndex tup'\n          -> GetRelation qs Ridx tup\n          -> GetRelation qs Ridx tup'\n          -> SatisfiesTupleConstraints Ridx (indexedElement tup) (indexedElement tup')) ->\n       MutationPreservesTupleConstraints MutatedTuples (SatisfiesTupleConstraints Ridx))\n    (* And is compatible with the cross-schema constraints. *)\n    (CrossConstr :\n       (@Iterate_Ensemble_BoundedIndex_filter\n          _ (fun Ridx' =>\n             forall tup' : IndexedRawTuple,\n               GetUnConstrRelation (DropQSConstraints qs) Ridx tup' ->\n               SatisfiesCrossRelationConstraints Ridx Ridx' (indexedElement tup') (GetRelation qs Ridx'))\n          (fun idx => if fin_eq_dec Ridx idx then false else true)\n       ) ->\n       (forall Ridx',\n          (Ridx' <> Ridx) ->\n          MutationPreservesCrossConstraints MutatedTuples (GetRelation qs Ridx')\n                                            (SatisfiesCrossRelationConstraints Ridx Ridx')))\n    (CrossConstr' :\n       (@Iterate_Ensemble_BoundedIndex_filter\n          _\n          (fun Ridx' =>\n             forall tup' : IndexedRawTuple,\n               GetUnConstrRelation (DropQSConstraints qs) Ridx' tup' ->\n               SatisfiesCrossRelationConstraints Ridx' Ridx (indexedElement tup') (GetRelation qs Ridx))\n          (fun idx => if fin_eq_dec Ridx idx then false else true)) ->\n       (forall Ridx',\n          (Ridx' <> Ridx) ->\n          MutationPreservesCrossConstraints (GetRelation qs Ridx')\n                                            MutatedTuples\n                                            (SatisfiesCrossRelationConstraints Ridx' Ridx)))\n  : QueryStructure qsSchema :=\n    {| rawRels :=\n         UpdateRelation (rawRels qs) Ridx {| rawRel := MutatedTuples|}\n    |}.\n  Next Obligation.\n    unfold MutationPreservesAttributeConstraints,\n    SatisfiesAttributeConstraints, QSGetNRelSchema, GetNRelSchema,\n    GetRelation in *.\n    set ((ith2 (rawRels qs) Ridx )) as X in *; destruct X; simpl in *.\n    destruct (attrConstraints  (Vector.nth\n                         (Vector.map schemaRaw (QSschemaSchemas qsSchema))\n                         Ridx)); eauto.\n  Qed.\n  Next Obligation.\n    unfold MutationPreservesTupleConstraints,\n    SatisfiesTupleConstraints, QSGetNRelSchema, GetNRelSchema,\n    GetRelation in *.\n    set ((ith2 (rawRels qs) Ridx )) as X in *; destruct X; simpl in *.\n    destruct (tupleConstraints\n       (Vector.nth (Vector.map schemaRaw (QSschemaSchemas qsSchema)) Ridx)); eauto.\n  Qed.\n  Next Obligation.\n    unfold MutationPreservesCrossConstraints,\n    SatisfiesCrossRelationConstraints, QSGetNRelSchema, GetNRelSchema,\n    GetRelation, UpdateRelation in *.\n    case_eq (BuildQueryStructureConstraints qsSchema idx idx'); eauto.\n    destruct (fin_eq_dec Ridx idx'); subst; intros.\n    - rewrite ith_replace2_Index_eq; simpl.\n      rewrite ith_replace2_Index_neq in H1; eauto.\n      generalize (fun c => CrossConstr' c idx H0).\n      rewrite H; intros H'; eapply H'; eauto.\n      eapply (Iterate_Ensemble_filter_neq\n                (fun Ridx' =>\n                   forall tup' : IndexedRawTuple,\n                     GetUnConstrRelation (DropQSConstraints qs) Ridx' tup' ->\n                     match BuildQueryStructureConstraints qsSchema Ridx' idx' with\n                       | Some CrossConstr => CrossConstr (indexedElement tup') (GetRelation qs idx')\n                       | None => True\n                     end)).\n      intros; generalize (crossConstr qs idx0 idx').\n      rewrite GetRelDropConstraints in H3.\n      destruct (BuildQueryStructureConstraints qsSchema idx0 idx');\n        eauto.\n    - rewrite ith_replace2_Index_neq; eauto using string_dec.\n      destruct (fin_eq_dec Ridx idx); subst.\n      + rewrite ith_replace2_Index_eq in H1; simpl in *; eauto.\n      generalize (fun c => CrossConstr c idx' (not_eq_sym n) _ H1).\n      rewrite H; intros H'; eapply H'; eauto.\n      eapply (Iterate_Ensemble_filter_neq\n                (fun Ridx' =>\n                   forall tup' : IndexedRawTuple,\n                     GetUnConstrRelation (DropQSConstraints qs) idx tup' ->\n                     match BuildQueryStructureConstraints qsSchema idx Ridx' with\n                       | Some CrossConstr => CrossConstr (indexedElement tup') (GetRelation qs Ridx')\n                       | None => True\n                     end)); intros.\n      destruct (fin_eq_dec idx0 idx); subst; try congruence.\n      case_eq (BuildQueryStructureConstraints qsSchema idx idx0); intros; eauto.\n      pose (crossConstr qs idx idx0) as crossConstr'; rewrite H4 in crossConstr'.\n      eapply crossConstr'; eauto.\n      unfold GetUnConstrRelation, DropQSConstraints in H3.\n      rewrite <- ith_imap2 in H3; eauto.\n      + rewrite ith_replace2_Index_neq in H1; eauto using string_dec.\n        pose (crossConstr qs idx idx') as crossConstr'; rewrite H in crossConstr';\n        eapply crossConstr'; eauto.\n  Qed.\n\n  Lemma QSMutateSpec_refine :\n    forall (qsSchema : QueryStructureSchema)\n           (qs : QueryStructure qsSchema)\n           Ridx (MutatedTuples : IndexedEnsemble ),\n      refine\n        (Pick (QSMutateSpec qs Ridx MutatedTuples))\n        (attributeConstr <- {b |\n                       (forall tup,\n                          GetRelation qs Ridx tup\n                          -> SatisfiesAttributeConstraints Ridx (indexedElement tup))\n                       -> decides b\n                                  (MutationPreservesAttributeConstraints\n                                     MutatedTuples\n                                     (SatisfiesAttributeConstraints Ridx))};\n         tupleConstr <- {b |\n                         (forall tup tup',\n                            elementIndex tup <> elementIndex tup'\n                            -> GetRelation qs Ridx tup\n                            -> GetRelation qs Ridx tup'\n                            -> SatisfiesTupleConstraints Ridx (indexedElement tup) (indexedElement tup'))\n                         -> decides b\n                               (MutationPreservesTupleConstraints\n                                  MutatedTuples\n                                  (SatisfiesTupleConstraints Ridx))};\n         crossConstr <- {b |\n                         (forall Ridx',\n                            Ridx' <> Ridx ->\n                            forall tup',\n                              (GetRelation qs Ridx') tup'\n                              -> SatisfiesCrossRelationConstraints\n                                   Ridx' Ridx (indexedElement tup') (GetRelation qs Ridx))\n                         -> decides\n                              b\n                              (forall Ridx',\n                                 Ridx' <> Ridx\n                                 -> MutationPreservesCrossConstraints\n                                      (GetRelation qs Ridx')\n                                      MutatedTuples\n                                      (SatisfiesCrossRelationConstraints Ridx' Ridx))};\n         crossConstr' <- {b |\n                         (forall Ridx',\n                            Ridx' <> Ridx ->\n                            forall tup',\n                              (GetRelation qs Ridx) tup'\n                              -> SatisfiesCrossRelationConstraints\n                                   Ridx Ridx' (indexedElement tup') (GetRelation qs Ridx'))\n                         -> decides\n                              b\n                              (forall Ridx',\n                                 Ridx' <> Ridx\n                                 -> MutationPreservesCrossConstraints\n                                      MutatedTuples\n                                      (GetRelation qs Ridx')\n                                      (SatisfiesCrossRelationConstraints Ridx Ridx'))};\n         match attributeConstr, tupleConstr, crossConstr, crossConstr' with\n           | true, true, true, true =>\n             {qs' |\n              (forall Ridx',\n                 Ridx <> Ridx' ->\n                 GetRelation qs Ridx' =\n                 GetRelation qs' Ridx')\n              /\\ forall t,\n                   GetRelation qs' Ridx t <-> MutatedTuples t\n             }\n\n           | _, _, _, _ => ret qs\n         end).\n  Proof.\n    intros qsSchema qs Ridx MutatedTuples v Comp_v.\n    computes_to_inv.\n    assert (decides v0\n                      (MutationPreservesAttributeConstraints\n                         MutatedTuples\n                       (SatisfiesAttributeConstraints Ridx)))\n      as H0' by\n          (apply Comp_v; intros;\n           unfold SatisfiesAttributeConstraints, QSGetNRelSchema, GetNRelSchema;\n           pose proof (rawAttrconstr ((ith2 (rawRels qs) Ridx))) as H';\n           destruct (attrConstraints (Vector.nth (qschemaSchemas qsSchema) Ridx));\n           [apply H' | ]; eauto); clear Comp_v.\n    assert (decides v1\n                    (MutationPreservesTupleConstraints\n                       MutatedTuples\n                       (SatisfiesTupleConstraints Ridx)))\n      as H1'\n        by\n          (apply Comp_v';\n           unfold SatisfiesTupleConstraints, QSGetNRelSchema, GetNRelSchema;\n           pose proof (rawTupleconstr ((ith2 (rawRels qs) Ridx))) as H';\n           destruct (tupleConstraints (Vector.nth (qschemaSchemas qsSchema) Ridx));\n           [apply H' | ]; eauto); clear Comp_v'.\n    assert (decides v2\n                    (forall Ridx',\n                       Ridx' <> Ridx ->\n                       MutationPreservesCrossConstraints\n                         (GetRelation qs Ridx')\n                         MutatedTuples\n                         (SatisfiesCrossRelationConstraints Ridx' Ridx)))\n      as H2' by\n          (apply Comp_v''; intros;\n           pose proof (crossConstr qs Ridx' Ridx);\n           unfold SatisfiesCrossRelationConstraints; simpl;\n           destruct (BuildQueryStructureConstraints qsSchema Ridx' Ridx); eauto); clear Comp_v''.\n\n    assert (decides v3\n                    (forall Ridx',\n                       Ridx' <> Ridx ->\n                       MutationPreservesCrossConstraints\n                         MutatedTuples\n                         (GetRelation qs Ridx')\n                         (SatisfiesCrossRelationConstraints Ridx Ridx')))\n      as H3' by\n          (apply Comp_v'''; intros;\n           pose proof (crossConstr qs Ridx Ridx');\n           unfold SatisfiesCrossRelationConstraints; simpl;\n           destruct (BuildQueryStructureConstraints qsSchema Ridx Ridx'); eauto); clear Comp_v'''.\n\n    destruct v0; destruct v1; destruct v2; destruct v3;\n    try solve\n        [computes_to_econstructor; computes_to_inv; subst; unfold QSMutateSpec; simpl in *; right; subst; intuition].\n    computes_to_inv; subst;\n    computes_to_econstructor; unfold QSMutateSpec; simpl in *; left; intuition eauto.\n    - rewrite <- H; eauto.\n    - rewrite <- H; eauto.\n    - unfold Same_set, Included, In; eauto; intuition; eapply H0; eauto.\n    - rewrite H; intuition.\n  Qed.\n\n  Lemma QSMutateSpec_UnConstr_refine' :\n    forall qsSchema qs Ridx or MutatedTuples,\n      @DropQSConstraints_AbsR qsSchema or qs ->\n      refine\n        {or' | QSMutateSpec or Ridx MutatedTuples or'}\n        (attributeConstr <- {b |\n                             (forall tup,\n                                GetUnConstrRelation qs Ridx tup\n                                -> SatisfiesAttributeConstraints Ridx (indexedElement tup))\n                             -> decides b\n                                        (MutationPreservesAttributeConstraints\n                                           MutatedTuples\n                                           (SatisfiesAttributeConstraints Ridx))};\n         tupleConstr <- {b |\n                         (forall tup tup',\n                            elementIndex tup <> elementIndex tup'\n                            -> GetUnConstrRelation qs Ridx tup\n                            -> GetUnConstrRelation qs Ridx tup'\n                            -> SatisfiesTupleConstraints Ridx (indexedElement tup) (indexedElement tup'))\n                       -> decides b\n                               (MutationPreservesTupleConstraints\n                                  MutatedTuples\n                                  (SatisfiesTupleConstraints Ridx))};\n         crossConstr <- {b |\n                         (forall Ridx',\n                            Ridx' <> Ridx ->\n                            forall tup',\n                              (GetUnConstrRelation qs Ridx') tup'\n                              -> SatisfiesCrossRelationConstraints\n                                   Ridx' Ridx (indexedElement tup') (GetUnConstrRelation qs Ridx))\n                         -> decides\n                              b\n                              (forall Ridx',\n                                 Ridx' <> Ridx\n                                 -> MutationPreservesCrossConstraints\n                                      (GetUnConstrRelation qs Ridx')\n                                      MutatedTuples\n                                      (SatisfiesCrossRelationConstraints Ridx' Ridx))};\n         crossConstr' <- {b |\n                         (forall Ridx',\n                            Ridx' <> Ridx ->\n                            forall tup',\n                              (GetUnConstrRelation qs Ridx tup')\n                              -> SatisfiesCrossRelationConstraints\n                                   Ridx Ridx' (indexedElement tup') (GetUnConstrRelation qs Ridx'))\n                         -> decides\n                              b\n                              (forall Ridx',\n                                 Ridx' <> Ridx\n                                 -> MutationPreservesCrossConstraints\n                                      MutatedTuples\n                                      (GetUnConstrRelation qs Ridx')\n                                      (SatisfiesCrossRelationConstraints Ridx Ridx'))};\n         match attributeConstr, tupleConstr, crossConstr, crossConstr' with\n           | true, true, true, true =>\n             {or' | DropQSConstraints_AbsR or' (UpdateUnConstrRelation qs Ridx MutatedTuples)}\n           | _, _, _, _ => ret or\n         end).\n  Proof.\n    unfold DropQSConstraints_AbsR; intros; subst.\n    setoid_rewrite QSMutateSpec_refine.\n    repeat setoid_rewrite refineEquiv_bind_bind.\n    rewrite !GetRelDropConstraints.\n    f_equiv; unfold pointwise_relation; intros.\n    f_equiv; unfold pointwise_relation; intros.\n    f_equiv; unfold pointwise_relation; intros.\n    { intros v Comp_v; subst; computes_to_inv;\n      unfold decides, If_Then_Else in *; find_if_inside; intros; computes_to_econstructor; intros.\n      - rewrite <- GetRelDropConstraints in *; eapply Comp_v; intros; eauto;\n        eapply H; eauto; rewrite <- GetRelDropConstraints; eauto.\n      - unfold not; intros; eapply Comp_v; intros.\n        + eapply H; eauto; rewrite <- GetRelDropConstraints; eauto.\n        + rewrite GetRelDropConstraints; eauto.\n    }\n    f_equiv; unfold pointwise_relation; intros.\n    { intros v Comp_v; subst; computes_to_inv;\n      unfold decides, If_Then_Else in *; find_if_inside; intros; computes_to_econstructor; intros.\n      - rewrite <- GetRelDropConstraints in *; eapply Comp_v; intros; eauto.\n        rewrite GetRelDropConstraints; eapply H; eauto.\n      - unfold not; intros; eapply Comp_v; intros.\n        + rewrite GetRelDropConstraints; eauto.\n        + rewrite GetRelDropConstraints; eauto.\n    }\n    repeat find_if_inside; try reflexivity.\n    intros v Comp_v; computes_to_inv; subst; computes_to_econstructor;\n    simpl.\n    rewrite <- GetRelDropConstraints;\n      setoid_rewrite <- GetRelDropConstraints; subst; rewrite Comp_v;\n      split; intros;\n      unfold GetUnConstrRelation, DropQSConstraints, UpdateUnConstrRelation.\n    rewrite ith_replace2_Index_neq;\n    eauto using string_dec.\n    rewrite ith_replace2_Index_eq;\n    intuition.\n  Qed.\n\n  Lemma ComplementIntersection {A} :\n    forall (ens : Ensemble A) (a : A),\n      ~ In _ (Intersection A ens (Complement A ens)) a.\n  Proof.\n    unfold In, not; intros; inversion H; subst.\n    unfold Complement, In in *; tauto.\n  Qed.\n\n  Corollary ComplementIntersectionIndexedList {heading}\n  : forall (ens : Ensemble (@IndexedRawTuple heading)),\n      UnIndexedEnsembleListEquivalence\n        (Intersection IndexedRawTuple ens\n                      (Complement IndexedRawTuple ens))\n        [].\n\n  Proof.\n    unfold UnIndexedEnsembleListEquivalence.\n    exists (@nil (@IndexedRawTuple heading)); simpl; intuition.\n    - exfalso; eapply ComplementIntersection; eauto.\n    - constructor.\n  Qed.\n\n    Lemma ibound_check_dec {n} :\n    forall b a,\n            (fun idx =>\n             if fin_eq_dec (m := n) b idx then false else true) a = true <->\n            (fun idx => b <> idx) a.\n  Proof.\n    intros; simpl; find_if_inside; intuition.\n  Qed.\n\n  Lemma refine_Iterate_MutationPreservesCrossConstraints\n  : forall qsSchema qs Ridx MutatedTuples or,\n      @DropQSConstraints_AbsR qsSchema or qs\n      ->\n    ((forall Ridx',\n     Ridx' <> Ridx ->\n     forall tup' : IndexedRawTuple,\n     GetRelation or Ridx tup' ->\n     SatisfiesCrossRelationConstraints Ridx Ridx' (indexedElement tup')\n       (GetUnConstrRelation (DropQSConstraints or) Ridx')) ->\n    forall Ridx',\n    Ridx' <> Ridx ->\n    MutationPreservesCrossConstraints MutatedTuples\n      (GetUnConstrRelation (DropQSConstraints or) Ridx')\n      (SatisfiesCrossRelationConstraints Ridx Ridx')) ->\n   Iterate_Ensemble_BoundedIndex_filter\n     (fun Ridx' =>\n      forall tup' : IndexedRawTuple,\n      GetUnConstrRelation (DropQSConstraints or) Ridx tup' ->\n      SatisfiesCrossRelationConstraints Ridx Ridx'\n                                        (indexedElement tup') (GetRelation or Ridx'))\n     (fun idx => if fin_eq_dec Ridx idx then false else true) ->\n   forall Ridx',\n   Ridx' <> Ridx ->\n   MutationPreservesCrossConstraints\n     MutatedTuples (GetRelation or Ridx')\n     (SatisfiesCrossRelationConstraints Ridx Ridx').\n  Proof.\n    intros; rewrite <- GetRelDropConstraints in *; eapply H0; eauto.\n    intros; rewrite GetRelDropConstraints in *.\n    intros; eapply (proj1 (Iterate_Ensemble_BoundedIndex_filter_equiv\n                          _\n                          (Build_DecideableEnsemble _ _ (ibound_check_dec _) )) H1); \n    try rewrite GetRelDropConstraints; eauto.\n  Qed.\n\n  Lemma refine_Iterate_MutationPreservesCrossConstraints'\n  : forall qsSchema qs Ridx MutatedTuples or,\n      @DropQSConstraints_AbsR qsSchema or qs\n      ->\n    ((forall Ridx' ,\n     Ridx' <> Ridx ->\n     forall tup' : IndexedRawTuple,\n       GetUnConstrRelation (DropQSConstraints or) Ridx' tup' ->\n     SatisfiesCrossRelationConstraints Ridx' Ridx (indexedElement tup')\n       (GetRelation or Ridx)) ->\n    forall Ridx' ,\n    Ridx' <> Ridx ->\n    MutationPreservesCrossConstraints\n      (GetUnConstrRelation (DropQSConstraints or) Ridx')\n      MutatedTuples\n      (SatisfiesCrossRelationConstraints Ridx' Ridx)) ->\n      Iterate_Ensemble_BoundedIndex_filter\n        (fun Ridx' =>\n           forall tup' : IndexedRawTuple,\n             GetUnConstrRelation (DropQSConstraints or) Ridx' tup' ->\n             SatisfiesCrossRelationConstraints Ridx' Ridx (indexedElement tup')\n                                               (GetRelation or Ridx))\n        (fun idx => if fin_eq_dec Ridx idx then false else true) ->\n  forall Ridx',\n  Ridx' <> Ridx ->\n  MutationPreservesCrossConstraints (GetRelation or Ridx') MutatedTuples\n                                    (SatisfiesCrossRelationConstraints Ridx' Ridx).\n    intros; rewrite <- GetRelDropConstraints in *; eapply H0; eauto.\n    intros; eapply (proj1 (Iterate_Ensemble_BoundedIndex_filter_equiv\n                             _\n                             (Build_DecideableEnsemble _ _ (ibound_check_dec _) )) H1); eauto.\n  Qed.\n\n  Lemma QSMutateSpec_UnConstr_refine :\n    forall qsSchema qs Ridx MutatedTuples or\n           refined_attrConstr refined_tupleConstr\n           refined_crossConstr refined_crossConstr',\n      @DropQSConstraints_AbsR qsSchema or qs\n      -> refine {b | (forall tup,\n                        GetUnConstrRelation qs Ridx tup\n                        -> SatisfiesAttributeConstraints Ridx (indexedElement tup))\n                     ->  decides b (MutationPreservesAttributeConstraints\n                                      MutatedTuples\n                                      (SatisfiesAttributeConstraints Ridx))}\n                refined_attrConstr\n      -> refine {b | (forall tup tup',\n                        elementIndex tup <> elementIndex tup'\n                          -> GetUnConstrRelation qs Ridx tup\n                          -> GetUnConstrRelation qs Ridx tup'\n                          -> SatisfiesTupleConstraints Ridx (indexedElement tup) (indexedElement tup'))\n                     ->  decides b (MutationPreservesTupleConstraints\n                                      MutatedTuples\n                                      (SatisfiesTupleConstraints Ridx))}\n                refined_tupleConstr\n      -> refine {b |\n                         (forall Ridx',\n                            Ridx' <> Ridx ->\n                            forall tup',\n                              (GetUnConstrRelation qs Ridx') tup'\n                              -> SatisfiesCrossRelationConstraints\n                                   Ridx' Ridx (indexedElement tup') (GetUnConstrRelation qs Ridx))\n                         -> decides\n                              b\n                              (forall Ridx',\n                                 Ridx' <> Ridx\n                                 -> MutationPreservesCrossConstraints\n                                      (GetUnConstrRelation qs Ridx')\n                                      MutatedTuples\n                                      (SatisfiesCrossRelationConstraints Ridx' Ridx))}\n\n           (* @Iterate_Decide_Comp_Pre\n                           _\n                           ((fun Ridx' =>\n                               Ridx' <> Ridx\n                               -> MutationPreservesCrossConstraints\n                                    (GetUnConstrRelation qs Ridx')\n                                    MutatedTuples\n                                    (SatisfiesCrossRelationConstraints Ridx' Ridx)))\n                           (@Iterate_Ensemble_BoundedIndex_filter\n                              _ (fun idx =>\n                                   if (fin_eq_dec (ibound Ridx) idx)\n                                   then false else true)\n                              (fun Ridx' =>\n                                 forall tup',\n                                   (GetUnConstrRelation qs Ridx') tup'\n                                   -> SatisfiesCrossRelationConstraints\n                                        Ridx' Ridx (indexedElement tup')\n                                        (GetUnConstrRelation qs Ridx)))\n           *)\n                refined_crossConstr\n      -> refine {b |\n                         (forall Ridx',\n                            Ridx' <> Ridx ->\n                            forall tup',\n                              (GetUnConstrRelation qs Ridx tup')\n                              -> SatisfiesCrossRelationConstraints\n                                   Ridx Ridx' (indexedElement tup') (GetUnConstrRelation qs Ridx'))\n                         -> decides\n                              b\n                              (forall Ridx',\n                                 Ridx' <> Ridx\n                                 -> MutationPreservesCrossConstraints\n                                      MutatedTuples\n                                      (GetUnConstrRelation qs Ridx')\n                                      (SatisfiesCrossRelationConstraints Ridx Ridx'))}\n           (*@Iterate_Decide_Comp_Pre\n                           _\n                           ((fun Ridx' =>\n                               Ridx' <> Ridx\n                               -> MutationPreservesCrossConstraints\n                                    MutatedTuples\n                                    (GetUnConstrRelation qs Ridx')\n                                    (SatisfiesCrossRelationConstraints Ridx Ridx')))\n                           (@Iterate_Ensemble_BoundedIndex_filter\n                              _ (fun idx =>\n                                   if (fin_eq_dec (ibound Ridx) idx)\n                                   then false else true)\n                              (fun Ridx' =>\n                                 forall tup',\n                                   (GetUnConstrRelation qs Ridx) tup'\n                                   -> SatisfiesCrossRelationConstraints\n                                        Ridx Ridx' (indexedElement tup') (GetUnConstrRelation qs Ridx')))\n                *)\n                refined_crossConstr'\n      ->\n      refine\n        (or' <- QSMutate or Ridx MutatedTuples;\n         nr' <- {nr' | DropQSConstraints_AbsR (fst or') nr'};\n         ret (nr', snd or'))\n        (attrConstr <- refined_attrConstr;\n         tupleConstr <- refined_tupleConstr;\n         crossConstr <- refined_crossConstr;\n         crossConstr' <- refined_crossConstr';\n            match attrConstr, tupleConstr, crossConstr, crossConstr' with\n              | true, true, true, true =>\n                mutated   <- Pick (UnIndexedEnsembleListEquivalence\n                                     (Intersection _\n                                                   (GetRelation or Ridx)\n                                                   (Complement _ (GetUnConstrRelation (UpdateUnConstrRelation qs Ridx MutatedTuples) Ridx))));\n              ret (UpdateUnConstrRelation qs Ridx MutatedTuples, mutated)\n              | _, _, _, _ => ret (DropQSConstraints or, [])\n            end).\n  Proof.\n    intros; unfold QSMutate; simplify with monad laws.\n    setoid_rewrite (@QSMutateSpec_UnConstr_refine' _ qs Ridx); eauto.\n    setoid_rewrite <- H0; setoid_rewrite <- H1.\n    setoid_rewrite <- H2; setoid_rewrite <- H3.\n    simplify with monad laws;\n      repeat (eapply refine_under_bind; intros; eauto); eauto.\n    repeat find_if_inside;\n      try solve\n          [simplify with monad laws; refine pick val _;\n           [ simplify with monad laws; refine pick val (DropQSConstraints or);\n             try simplify with monad laws\n           | eauto using ComplementIntersectionIndexedList]; reflexivity\n          ].\n     computes_to_inv; simpl in *.\n    unfold DropQSConstraints_AbsR in *; subst.\n    repeat rewrite (fun Ridx => GetRelDropConstraints or Ridx) in *.\n    refine pick val\n           (Mutate_Valid\n              or H4 H5\n              (refine_Iterate_MutationPreservesCrossConstraints (refl_equal _) H7)\n              (refine_Iterate_MutationPreservesCrossConstraints' (refl_equal _) H6));\n      [ simplify with monad laws\n      | unfold Mutate_Valid, DropQSConstraints,\n        UpdateRelation, UpdateUnConstrRelation; simpl;\n        repeat rewrite imap_replace2_Index by eauto using string_dec;\n        simpl; try reflexivity].\n    f_equiv.\n    - unfold GetRelation, GetUnConstrRelation, Mutate_Valid,\n      UpdateRelation, DropQSConstraints, UpdateUnConstrRelation; simpl;\n      repeat rewrite ith_replace2_Index_eq; reflexivity.\n    - unfold pointwise_relation; intros.\n      refine pick val _;\n        [ simplify with monad laws; reflexivity\n        | unfold GetRelation, GetUnConstrRelation, Mutate_Valid,\n          UpdateRelation, DropQSConstraints, UpdateUnConstrRelation; simpl;\n          rewrite imap_replace2_Index by eauto using string_dec; try reflexivity ].\n  Qed.\n\n  Local Transparent QSMutate.\n\n  Lemma refine_SatisfiesAttributeConstraintsMutate\n  : forall qsSchema qs Ridx MutatedTuples,\n      refine\n        {b | (forall tup,\n                GetUnConstrRelation qs Ridx tup\n                -> SatisfiesAttributeConstraints Ridx (indexedElement tup))\n                     -> decides b (MutationPreservesAttributeConstraints\n                                     MutatedTuples\n                                     (SatisfiesAttributeConstraints Ridx))}\n        match attrConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx) with\n          | Some Constr =>\n            {b | (forall tup,\n                          GetUnConstrRelation qs Ridx tup\n                          -> SatisfiesAttributeConstraints Ridx (indexedElement tup))\n                 -> decides b (MutationPreservesAttributeConstraints\n                                 MutatedTuples\n                                 (SatisfiesAttributeConstraints Ridx)) }\n          | None => ret true\n        end.\n  Proof.\n    intros; unfold MutationPreservesAttributeConstraints, SatisfiesAttributeConstraints.\n    destruct (attrConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx)); try reflexivity.\n    intros v Comp_v; computes_to_econstructor; computes_to_inv; subst.\n    simpl; tauto.\n  Qed.\n\n  Lemma refine_SatisfiesTupleConstraintsMutate\n  : forall qsSchema qs Ridx MutatedTuples,\n      refine\n        {b | (forall tup tup',\n                elementIndex tup <> elementIndex tup'\n                -> GetUnConstrRelation qs Ridx tup\n                -> GetUnConstrRelation qs Ridx tup'\n                -> SatisfiesTupleConstraints Ridx (indexedElement tup)\n                                             (indexedElement tup'))\n                     -> decides b (MutationPreservesTupleConstraints\n                                     MutatedTuples\n                                     (SatisfiesTupleConstraints Ridx))}\n        match tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx) with\n          | Some Constr =>\n            {b | (forall tup tup',\n                    elementIndex tup <> elementIndex tup'\n                    -> GetUnConstrRelation qs Ridx tup\n                    -> GetUnConstrRelation qs Ridx tup'\n                    -> Constr (indexedElement tup)\n                                                 (indexedElement tup'))\n                 -> decides b\n                            (MutationPreservesTupleConstraints\n                               MutatedTuples\n                               Constr) }\n          | None => ret true\n        end.\n  Proof.\n    intros; unfold MutationPreservesTupleConstraints, SatisfiesTupleConstraints;\n    destruct (tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx)); try reflexivity.\n    intros v Comp_v; computes_to_econstructor;  computes_to_inv; subst;\n    econstructor;  computes_to_inv; subst; simpl; tauto.\n  Qed.\n\n  Lemma refine_SatisfiesCrossConstraintsMutate\n  : forall  qsSchema qs Ridx MutatedTuples,\n      refine\n        {b |\n                         (forall Ridx',\n                            Ridx' <> Ridx ->\n                            forall tup',\n                              (GetUnConstrRelation qs Ridx') tup'\n                              -> SatisfiesCrossRelationConstraints\n                                   Ridx' Ridx (indexedElement tup') (GetUnConstrRelation qs Ridx))\n                         -> decides\n                              b\n                              (forall Ridx',\n                                 Ridx' <> Ridx\n                                 -> MutationPreservesCrossConstraints\n                                      (GetUnConstrRelation qs Ridx')\n                                      MutatedTuples\n                                      (SatisfiesCrossRelationConstraints Ridx' Ridx))}\n        (Iterate_Decide_Comp_opt_Pre _\n                                  (fun Ridx' =>\n                                      if fin_eq_dec Ridx Ridx'\n                                      then None\n                                      else\n                                        match\n                                          BuildQueryStructureConstraints qsSchema Ridx'\n                                                                         Ridx\n                                        with\n                                          | Some CrossConstr =>\n                                            Some\n                                              (\n                                                (MutationPreservesCrossConstraints\n                                                   (GetUnConstrRelation qs Ridx')\n                                                   MutatedTuples\n                                                   CrossConstr))\n                                          | None => None\n                                        end)\n                                  (@Iterate_Ensemble_BoundedIndex_filter\n                                     _\n                                     (fun Ridx' =>\n                                        forall tup',\n                                          (GetUnConstrRelation qs Ridx') tup'\n                                          -> SatisfiesCrossRelationConstraints\n                                               Ridx' Ridx (indexedElement tup') (GetUnConstrRelation qs Ridx))\n                                     (fun idx =>\n                                        if (fin_eq_dec Ridx idx)\n                                        then false else true)\n        )).\n  Proof.\n    intros; simpl.\n    unfold MutationPreservesCrossConstraints.\n    setoid_rewrite <- refine_Iterate_Decide_Comp_Pre.\n    setoid_rewrite Iterate_Decide_Comp_BoundedIndex_Pre.\n    eapply refine_Iterate_Decide_Comp_equiv_Pre; eauto using string_dec.\n    - unfold SatisfiesCrossRelationConstraints; intros.\n      destruct (fin_eq_dec Ridx idx);\n        [congruence\n        | destruct (BuildQueryStructureConstraints qsSchema idx Ridx); eauto].\n    - unfold not; intros; eapply H.\n      unfold SatisfiesCrossRelationConstraints in *.\n      destruct (fin_eq_dec Ridx idx);\n      [ eauto\n      | destruct (BuildQueryStructureConstraints qsSchema idx Ridx); eauto].\n    - setoid_rewrite <- Iterate_Ensemble_filter_neq; eauto using string_dec.\n  Qed.\n\n  Lemma refine_SatisfiesCrossConstraintsMutate'\n  : forall   qsSchema qs Ridx MutatedTuples,\n      refine\n        {b |\n         (forall Ridx',\n             Ridx' <> Ridx ->\n             forall tup',\n               (GetUnConstrRelation qs Ridx tup')\n               -> SatisfiesCrossRelationConstraints\n                    Ridx Ridx' (indexedElement tup') (GetUnConstrRelation qs Ridx'))\n         -> decides\n              b\n              (forall Ridx',\n                  Ridx' <> Ridx\n                  -> MutationPreservesCrossConstraints\n                       MutatedTuples\n                       (GetUnConstrRelation qs Ridx')\n                       (SatisfiesCrossRelationConstraints Ridx Ridx'))}\n        (Iterate_Decide_Comp_opt_Pre _\n                                  (fun Ridx' =>\n                                      if fin_eq_dec Ridx Ridx'\n                                      then None\n                                      else\n                                        match\n                                          BuildQueryStructureConstraints qsSchema Ridx\n                                                                         Ridx'\n                                        with\n                                          | Some CrossConstr =>\n                                            Some\n                                              (\n                                                (MutationPreservesCrossConstraints\n                                                   MutatedTuples\n                                                   (GetUnConstrRelation qs Ridx')\n                                                   CrossConstr))\n                                          | None => None\n                                        end)\n                                  (@Iterate_Ensemble_BoundedIndex_filter\n                                     _\n                                     (fun Ridx' =>\n                                        forall tup',\n                                          (GetUnConstrRelation qs Ridx) tup'\n                                          -> SatisfiesCrossRelationConstraints\n                                               Ridx Ridx' (indexedElement tup') (GetUnConstrRelation qs Ridx'))\n                                     (fun idx =>\n                                        if (fin_eq_dec Ridx idx)\n                                        then false else true)\n        )).\n  Proof.\n    intros; simpl.\n    unfold MutationPreservesCrossConstraints.\n    setoid_rewrite <- refine_Iterate_Decide_Comp_Pre.\n    setoid_rewrite Iterate_Decide_Comp_BoundedIndex_Pre.\n    eapply refine_Iterate_Decide_Comp_equiv_Pre; eauto using string_dec.\n    - unfold SatisfiesCrossRelationConstraints; intros.\n      destruct (fin_eq_dec Ridx idx);\n        [congruence\n        | destruct (BuildQueryStructureConstraints qsSchema Ridx idx); eauto].\n    - unfold not; intros; eapply H.\n      unfold SatisfiesCrossRelationConstraints in *.\n      destruct (fin_eq_dec Ridx idx);\n      [ eauto\n      | destruct (BuildQueryStructureConstraints qsSchema Ridx idx); eauto].\n    - setoid_rewrite <- Iterate_Ensemble_filter_neq; eauto using string_dec.\n  Qed.\n\n  Definition UpdateUnConstrRelationMutateC {qsSchema} (qs : UnConstrQueryStructure qsSchema) Ridx MutatedTuples :=\n    ret (UpdateUnConstrRelation qs Ridx MutatedTuples).\n\n  Lemma QSMutateSpec_refine_subgoals' ResultT :\n    forall qsSchema (qs : QueryStructure qsSchema) qs' Ridx\n           default success refined_schConstr_self\n           refined_schConstr refined_qsConstr refined_qsConstr'\n           MutatedTuples\n           (k : _ -> Comp ResultT),\n      DropQSConstraints_AbsR qs qs'\n      -> refine {b | (forall tup,\n                         GetUnConstrRelation qs' Ridx tup\n                         -> SatisfiesAttributeConstraints Ridx (indexedElement tup))\n                     ->  decides b (MutationPreservesAttributeConstraints\n                                      MutatedTuples\n                                      (SatisfiesAttributeConstraints Ridx))}\n                refined_schConstr_self\n      -> refine {b | (forall tup tup',\n                        elementIndex tup <> elementIndex tup'\n                          -> GetUnConstrRelation qs' Ridx tup\n                          -> GetUnConstrRelation qs' Ridx tup'\n                          -> SatisfiesTupleConstraints Ridx (indexedElement tup) (indexedElement tup'))\n                     ->  decides b (MutationPreservesTupleConstraints\n                                      MutatedTuples\n                                      (SatisfiesTupleConstraints Ridx))}\n                refined_schConstr\n      -> refine {b |\n                         (forall Ridx',\n                            Ridx' <> Ridx ->\n                            forall tup',\n                              (GetUnConstrRelation qs' Ridx') tup'\n                              -> SatisfiesCrossRelationConstraints\n                                   Ridx' Ridx (indexedElement tup') (GetUnConstrRelation qs' Ridx))\n                         -> decides\n                              b\n                              (forall Ridx',\n                                 Ridx' <> Ridx\n                                 -> MutationPreservesCrossConstraints\n                                      (GetUnConstrRelation qs' Ridx')\n                                      MutatedTuples\n                                      (SatisfiesCrossRelationConstraints Ridx' Ridx))}\n                refined_qsConstr\n      -> refine         {b |\n         (forall Ridx',\n             Ridx' <> Ridx ->\n             forall tup',\n               (GetUnConstrRelation qs' Ridx tup')\n               -> SatisfiesCrossRelationConstraints\n                    Ridx Ridx' (indexedElement tup') (GetUnConstrRelation qs' Ridx'))\n         -> decides\n              b\n              (forall Ridx',\n                  Ridx' <> Ridx\n                  -> MutationPreservesCrossConstraints\n                       MutatedTuples\n                       (GetUnConstrRelation qs' Ridx')\n                       (SatisfiesCrossRelationConstraints Ridx Ridx'))}\n                        refined_qsConstr'\n      -> (forall qs'' qs''' mutated,\n             DropQSConstraints_AbsR qs'' qs'''\n             -> (forall Ridx',\n                    Ridx <> Ridx' ->\n                    GetRelation qs Ridx' =\n                    GetRelation qs'' Ridx')\n             -> (forall t,\n                    GetRelation qs'' Ridx t <-> MutatedTuples t)\n             -> UnIndexedEnsembleListEquivalence\n                                    (Intersection _\n                                                  (GetRelation qs Ridx)\n                                                  (Complement _ (GetUnConstrRelation (UpdateUnConstrRelation qs' Ridx MutatedTuples) Ridx))) mutated\n             -> refine (k (qs'', mutated))\n                       (success qs''' mutated))\n      -> refine (k (qs, [ ])) default\n      -> refine\n           (qs' <- QSMutate qs Ridx MutatedTuples; k qs')\n           (schConstr_self <- refined_schConstr_self;\n             schConstr <- refined_schConstr;\n             qsConstr <- refined_qsConstr;\n             qsConstr' <- refined_qsConstr';\n             match schConstr_self, schConstr, qsConstr, qsConstr' with\n             | true, true, true, true =>\n               mutated   <- Pick (UnIndexedEnsembleListEquivalence\n                                    (Intersection _\n                                                  (GetRelation qs Ridx)\n                                                  (Complement _ (GetUnConstrRelation (UpdateUnConstrRelation qs' Ridx MutatedTuples) Ridx))));\n                 qs'' <- UpdateUnConstrRelationMutateC qs' Ridx MutatedTuples;\n                 success qs'' mutated\n             | _, _, _, _ => default\n             end).\n  Proof.\n    intros.\n    unfold QSMutate.\n    simplify with monad laws.\n    setoid_rewrite QSMutateSpec_refine.\n    simplify with monad laws.\n    apply refine_under_bind_both.\n    rewrite <- H0, <- H, (GetRelDropConstraints qs); reflexivity.\n    rewrite <- !GetRelDropConstraints; rewrite !H.\n    intros; repeat (apply refine_under_bind_both;\n            [repeat rewrite <- (GetRelDropConstraints qs); eauto\n            | intros]).\n    - computes_to_inv; eauto.\n      rewrite <- H2.\n      intros v Comp_v; computes_to_inv; computes_to_econstructor; intros.\n      setoid_rewrite <- GetRelDropConstraints; rewrite H.\n      eapply Comp_v; intros; eapply H8; eauto.\n      rewrite <- GetRelDropConstraints, H; eauto.\n    - computes_to_inv; eauto.\n      rewrite <- H3.\n      intros v Comp_v; computes_to_inv; computes_to_econstructor; intros.\n      setoid_rewrite <- GetRelDropConstraints; rewrite H.\n      eapply Comp_v; intros.\n      rewrite <- H, GetRelDropConstraints; eapply H9; eauto.\n    - repeat find_if_inside; try simplify with monad laws;\n      try solve [rewrite refine_SuccessfulInsert_Bind; eauto].\n      +  computes_to_inv; simpl in *.\n         assert (Iterate_Ensemble_BoundedIndex_filter\n                   (fun Ridx' : Fin.t (numRawQSschemaSchemas qsSchema) =>\n                      forall tup' : IndexedRawTuple,\n                        GetUnConstrRelation (DropQSConstraints qs) Ridx' tup' ->\n                        SatisfiesCrossRelationConstraints Ridx' Ridx\n                                                          (indexedElement tup') (GetRelation qs Ridx))\n                   (fun idx : Fin.t (numRawQSschemaSchemas qsSchema) =>\n                      if fin_eq_dec Ridx idx then false else true) ->\n                 forall Ridx' : Fin.t (numRawQSschemaSchemas qsSchema),\n                   Ridx' <> Ridx ->\n                   MutationPreservesCrossConstraints (GetRelation qs Ridx') MutatedTuples\n                                                     (SatisfiesCrossRelationConstraints Ridx' Ridx))\n           as H8' by\n               (intros; eapply H8; intros; eauto;\n         rewrite <- H, GetRelDropConstraints;\n         rewrite <- GetRelDropConstraints, H in H13;\n         intros; eapply (proj1 (Iterate_Ensemble_BoundedIndex_filter_equiv\n                                  _\n                                  (Build_DecideableEnsemble _ _ (ibound_check_dec _) )) H10); eauto;\n         rewrite H; eauto).\n         assert (Iterate_Ensemble_BoundedIndex_filter\n                   (fun Ridx' : Fin.t (numRawQSschemaSchemas qsSchema) =>\n                      forall tup' : IndexedRawTuple,\n                        GetUnConstrRelation (DropQSConstraints qs) Ridx tup' ->\n                        SatisfiesCrossRelationConstraints (qsSchema := qsSchema) Ridx Ridx'\n                                                          (indexedElement tup') (GetRelation qs Ridx'))\n                   (fun idx : Fin.t (numRawQSschemaSchemas qsSchema) =>\n                      if fin_eq_dec Ridx idx then false else true) ->\n                 forall Ridx' : Fin.t (numRawQSschemaSchemas qsSchema),\n                   Ridx' <> Ridx ->\n                   MutationPreservesCrossConstraints MutatedTuples\n                                                     (GetRelation qs Ridx') (SatisfiesCrossRelationConstraints (qsSchema := qsSchema) Ridx Ridx')) as H9' by\n               (intros; eapply H9; intros; eauto;\n                intros; eapply (proj1 (Iterate_Ensemble_BoundedIndex_filter_equiv\n                                         _\n                                         (Build_DecideableEnsemble _ _ (ibound_check_dec _) )) H10); eauto;\n                rewrite H; eauto).\n         assert ((forall tup tup' : IndexedRawTuple,\n                     elementIndex tup <> elementIndex tup' ->\n                     GetRelation qs Ridx tup ->\n                     GetRelation qs Ridx tup' ->\n                     SatisfiesTupleConstraints (qsSchema := qsSchema) Ridx (indexedElement tup) (indexedElement tup')) ->\n                 MutationPreservesTupleConstraints MutatedTuples\n                                                   (SatisfiesTupleConstraints (qsSchema := qsSchema) Ridx))\n           as H7' by\n               (intros; eapply H7; intros; eauto;\n                rewrite <- H, GetRelDropConstraints in H12, H13; eauto).\n         assert ((forall tup : IndexedRawTuple,\n                    GetRelation qs Ridx tup ->\n    SatisfiesAttributeConstraints (qsSchema := qsSchema) Ridx (indexedElement tup)) ->\n         MutationPreservesAttributeConstraints MutatedTuples\n                                               (SatisfiesAttributeConstraints (qsSchema := qsSchema) Ridx)) as H6' by\n               (intros; eapply H6; intros; eauto;\n                rewrite <- H, GetRelDropConstraints in H11; eauto).\n         refine pick val (Mutate_Valid qs (MutatedTuples := MutatedTuples) H6' H7' H9' H8').\n         rewrite <- !H, !GetRelDropConstraints.\n         simplify with monad laws.\n         eapply refine_under_bind_both.\n         unfold Mutate_Valid; simpl.\n         unfold UpdateRelation.\n         unfold GetRelation; simpl.\n         rewrite ilist2.ith_replace2_Index_eq; simpl.\n         unfold GetUnConstrRelation, UpdateUnConstrRelation.\n         rewrite ilist2.ith_replace2_Index_eq; simpl; reflexivity.\n         intros.\n         unfold UpdateUnConstrRelationMutateC; rewrite refineEquiv_bind_unit.\n         eapply H4.\n         unfold DropQSConstraints_AbsR, DropQSConstraints, Mutate_Valid; simpl.\n         unfold UpdateRelation.\n         rewrite ilist2.imap_replace2_Index; simpl; reflexivity.\n         intros; unfold Mutate_Valid, GetRelation, UpdateRelation; simpl.\n         rewrite ilist2.ith_replace2_Index_neq; simpl; eauto.\n         intros; unfold Mutate_Valid, GetRelation, UpdateRelation; simpl.\n         rewrite ilist2.ith_replace2_Index_eq; simpl; eauto.\n         reflexivity.\n         apply Pick_inv in H10.\n         revert H10.\n         unfold Mutate_Valid, GetRelation, UpdateRelation; simpl.\n         rewrite ilist2.ith_replace2_Index_eq; simpl; eauto.\n         unfold GetUnConstrRelation, UpdateUnConstrRelation.\n         rewrite ilist2.ith_replace2_Index_eq; simpl; eauto.\n         split.\n         unfold Mutate_Valid, GetRelation, UpdateRelation; simpl.\n         intros; rewrite ilist2.ith_replace2_Index_neq; simpl; eauto.\n         unfold Mutate_Valid, GetRelation, UpdateRelation; simpl.\n         intros; rewrite ilist2.ith_replace2_Index_eq; simpl; eauto.\n         reflexivity.\n      + refine pick val _.\n        simplify with monad laws; eauto.\n        rewrite <- H, GetRelDropConstraints.\n        eapply ComplementIntersectionIndexedList.\n      + refine pick val _.\n        simplify with monad laws; eauto.\n        rewrite <- H, GetRelDropConstraints.\n        eapply ComplementIntersectionIndexedList.\n      + refine pick val _.\n        simplify with monad laws; eauto.\n        rewrite <- H, GetRelDropConstraints.\n        eapply ComplementIntersectionIndexedList.\n      + refine pick val _.\n        simplify with monad laws; eauto.\n        rewrite <- H, GetRelDropConstraints.\n        eapply ComplementIntersectionIndexedList.\n  Qed.\n\n  Lemma QSMutateSpec_refine_subgoals ResultT :\n    forall qsSchema (qs : QueryStructure qsSchema) qs' Ridx\n           default success refined_schConstr_self\n           refined_schConstr refined_qsConstr refined_qsConstr'\n           MutatedTuples\n           (k : _ -> Comp ResultT),\n      DropQSConstraints_AbsR qs qs'\n      -> refine match attrConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx) with\n                | Some Constr =>\n                  {b | (forall tup,\n                           GetUnConstrRelation qs' Ridx tup\n                           -> SatisfiesAttributeConstraints Ridx (indexedElement tup))\n                       -> decides b (MutationPreservesAttributeConstraints\n                                       MutatedTuples\n                                       (SatisfiesAttributeConstraints Ridx)) }\n                | None => ret true\n                end\n                refined_schConstr_self\n      -> refine match tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx) with\n                | Some Constr =>\n                  {b | (forall tup tup',\n                           elementIndex tup <> elementIndex tup'\n                           -> GetUnConstrRelation qs' Ridx tup\n                           -> GetUnConstrRelation qs' Ridx tup'\n                           -> Constr (indexedElement tup)\n                                                        (indexedElement tup'))\n                       -> decides b\n                                  (MutationPreservesTupleConstraints\n                                     MutatedTuples\n                                     Constr) }\n                | None => ret true\n                end\n                refined_schConstr\n      -> refine (Iterate_Decide_Comp_opt_Pre _\n                                  (fun Ridx' =>\n                                      if fin_eq_dec Ridx Ridx'\n                                      then None\n                                      else\n                                        match\n                                          BuildQueryStructureConstraints qsSchema Ridx'\n                                                                         Ridx\n                                        with\n                                          | Some CrossConstr =>\n                                            Some\n                                              (\n                                                (MutationPreservesCrossConstraints\n                                                   (GetUnConstrRelation qs' Ridx')\n                                                   MutatedTuples\n                                                   CrossConstr))\n                                          | None => None\n                                        end)\n                                  (@Iterate_Ensemble_BoundedIndex_filter\n                                     _\n                                     (fun Ridx' =>\n                                        forall tup',\n                                          (GetUnConstrRelation qs' Ridx') tup'\n                                          -> SatisfiesCrossRelationConstraints\n                                               Ridx' Ridx (indexedElement tup') (GetUnConstrRelation qs' Ridx))\n                                     (fun idx =>\n                                        if (fin_eq_dec Ridx idx)\n                                        then false else true)\n                )) refined_qsConstr\n      -> refine (Iterate_Decide_Comp_opt_Pre _\n                                  (fun Ridx' =>\n                                      if fin_eq_dec Ridx Ridx'\n                                      then None\n                                      else\n                                        match\n                                          BuildQueryStructureConstraints qsSchema Ridx\n                                                                         Ridx'\n                                        with\n                                          | Some CrossConstr =>\n                                            Some\n                                              (\n                                                (MutationPreservesCrossConstraints\n                                                   MutatedTuples\n                                                   (GetUnConstrRelation qs' Ridx')\n                                                   CrossConstr))\n                                          | None => None\n                                        end)\n                                  (@Iterate_Ensemble_BoundedIndex_filter\n                                     _\n                                     (fun Ridx' =>\n                                        forall tup',\n                                          (GetUnConstrRelation qs' Ridx) tup'\n                                          -> SatisfiesCrossRelationConstraints\n                                               Ridx Ridx' (indexedElement tup') (GetUnConstrRelation qs' Ridx'))\n                                     (fun idx =>\n                                        if (fin_eq_dec Ridx idx)\n                                        then false else true)\n        ))\n                refined_qsConstr'\n      -> (forall qs'' qs''' mutated,\n             DropQSConstraints_AbsR qs'' qs'''\n             -> (forall Ridx',\n                    Ridx <> Ridx' ->\n                    GetRelation qs Ridx' =\n                    GetRelation qs'' Ridx')\n             -> (forall t,\n                    GetRelation qs'' Ridx t <-> MutatedTuples t)\n             -> UnIndexedEnsembleListEquivalence\n                                    (Intersection _\n                                                  (GetRelation qs Ridx)\n                                                  (Complement _ (GetUnConstrRelation (UpdateUnConstrRelation qs' Ridx MutatedTuples) Ridx))) mutated\n             -> refine (k (qs'', mutated))\n                       (success qs''' mutated))\n      -> refine (k (qs, [ ])) default\n      -> refine\n           (qs' <- QSMutate qs Ridx MutatedTuples; k qs')\n           (schConstr_self <- refined_schConstr_self;\n             schConstr <- refined_schConstr;\n             qsConstr <- refined_qsConstr;\n             qsConstr' <- refined_qsConstr';\n             match schConstr_self, schConstr, qsConstr, qsConstr' with\n             | true, true, true, true =>\n               mutated   <- Pick (UnIndexedEnsembleListEquivalence\n                                    (Intersection _\n                                                  (GetRelation qs Ridx)\n                                                  (Complement _ (GetUnConstrRelation (UpdateUnConstrRelation qs' Ridx MutatedTuples) Ridx))));\n                 qs'' <- UpdateUnConstrRelationMutateC qs' Ridx MutatedTuples;\n                 success qs'' mutated\n             | _, _, _, _ => default\n             end).\n  Proof.\n    intros; rewrite QSMutateSpec_refine_subgoals'; eauto; f_equiv.\n    rewrite refine_SatisfiesAttributeConstraintsMutate; eauto.\n    rewrite refine_SatisfiesTupleConstraintsMutate; eauto.\n    rewrite refine_SatisfiesCrossConstraintsMutate; eauto.\n    rewrite refine_SatisfiesCrossConstraintsMutate'; eauto.\n  Qed.\n\n  Lemma QSMutateSpec_UnConstr_refine_opt :\n    forall qsSchema qs Ridx MutatedTuples or,\n      @DropQSConstraints_AbsR qsSchema or qs ->\n      refine\n        (or' <- QSMutate or Ridx MutatedTuples;\n         nr' <- {nr' | DropQSConstraints_AbsR (fst or') nr'};\n         ret (nr', snd or'))\n        match (attrConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx)),\n              (tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx)) with\n          | Some aConstr, Some tConstr =>\n            attrConstr <- {b | (forall tup,\n                                  GetUnConstrRelation qs Ridx tup\n                                  -> aConstr (indexedElement tup))\n                                  -> decides b (MutationPreservesAttributeConstraints\n                                                  MutatedTuples\n                                                  aConstr) };\n              tupleConstr <- {b | (forall tup tup',\n                                     elementIndex tup <> elementIndex tup'\n                                     -> GetUnConstrRelation qs Ridx tup\n                                     -> GetUnConstrRelation qs Ridx tup'\n                                     -> tConstr (indexedElement tup) (indexedElement tup'))\n                                  -> decides b (MutationPreservesTupleConstraints\n                                                  MutatedTuples\n                                                  tConstr) };\n              crossConstr <- (Iterate_Decide_Comp_opt_Pre _\n                                  (fun Ridx' => if fin_eq_dec Ridx Ridx'\n                                      then None\n                                      else\n                                        match\n                                          BuildQueryStructureConstraints qsSchema Ridx'\n                                                                         Ridx\n                                        with\n                                          | Some CrossConstr =>\n                                            Some\n                                              ((MutationPreservesCrossConstraints\n                                                     (GetUnConstrRelation qs Ridx')\n                                                     MutatedTuples\n                                                 CrossConstr))\n                                          | None => None\n                                        end)\n                                  (@Iterate_Ensemble_BoundedIndex_filter\n                                     _\n                                     (fun Ridx' =>\n                                        forall tup',\n                                          (GetUnConstrRelation qs Ridx') tup'\n                                          -> SatisfiesCrossRelationConstraints\n                                               Ridx' Ridx (indexedElement tup') (GetUnConstrRelation qs Ridx))\n                                     (fun idx =>\n                                          if (fin_eq_dec Ridx idx)\n                                          then false else true)));\n              crossConstr' <- (Iterate_Decide_Comp_opt_Pre _\n                                  (fun Ridx' =>\n                                      if fin_eq_dec Ridx Ridx'\n                                      then None\n                                      else\n                                        match\n                                          BuildQueryStructureConstraints qsSchema Ridx\n                                                                         Ridx'\n                                        with\n                                          | Some CrossConstr =>\n                                            Some\n                                              ((MutationPreservesCrossConstraints\n                                                  MutatedTuples\n                                                  (GetUnConstrRelation qs Ridx')\n                                                  CrossConstr))\n                                          | None => None\n                                        end)\n                                  (@Iterate_Ensemble_BoundedIndex_filter\n                                     _\n                                     (fun Ridx' =>\n                                        forall tup',\n                                          (GetUnConstrRelation qs Ridx) tup'\n                                          -> SatisfiesCrossRelationConstraints\n                                               Ridx Ridx' (indexedElement tup') (GetUnConstrRelation qs Ridx'))\n                                     (fun idx =>\n                                          if (fin_eq_dec Ridx idx)\n                                          then false else true)));\n              match attrConstr, tupleConstr, crossConstr, crossConstr' with\n                | true, true, true, true =>\n                  mutated   <- Pick (UnIndexedEnsembleListEquivalence\n                                       (Intersection _\n                                                     (GetRelation or Ridx)\n                                                     (Complement _ (GetUnConstrRelation (UpdateUnConstrRelation qs Ridx MutatedTuples) Ridx))));\n                    ret (UpdateUnConstrRelation qs Ridx MutatedTuples, mutated)\n                | _, _, _, _ => ret (DropQSConstraints or, [])\n              end\n          | Some aConstr, None =>\n            attrConstr <- {b | (forall tup,\n                                  GetUnConstrRelation qs Ridx tup\n                                  -> aConstr (indexedElement tup))\n                               -> decides b (MutationPreservesAttributeConstraints\n                                               MutatedTuples\n                                               aConstr) };\n              crossConstr <- (Iterate_Decide_Comp_opt_Pre _\n                                  (fun Ridx' =>\n                                      if fin_eq_dec Ridx Ridx'\n                                      then None\n                                      else\n                                        match\n                                          BuildQueryStructureConstraints qsSchema Ridx'\n                                                                         Ridx\n                                        with\n                                          | Some CrossConstr =>\n                                            Some\n                                              ((MutationPreservesCrossConstraints\n                                                     (GetUnConstrRelation qs Ridx')\n                                                     MutatedTuples\n                                                 CrossConstr))\n                                          | None => None\n                                        end)\n                                  (@Iterate_Ensemble_BoundedIndex_filter\n                                     _\n                                     (fun Ridx' =>\n                                        forall tup',\n                                          (GetUnConstrRelation qs Ridx') tup'\n                                          -> SatisfiesCrossRelationConstraints\n                                               Ridx' Ridx (indexedElement tup') (GetUnConstrRelation qs Ridx))\n                                  (fun idx =>\n                                          if (fin_eq_dec Ridx idx)\n                                          then false else true)));\n              crossConstr' <- (Iterate_Decide_Comp_opt_Pre _\n                                  (fun Ridx' =>\n                                      if fin_eq_dec Ridx Ridx'\n                                      then None\n                                      else\n                                        match\n                                          BuildQueryStructureConstraints qsSchema Ridx\n                                                                         Ridx'\n                                        with\n                                          | Some CrossConstr =>\n                                            Some\n                                              ((MutationPreservesCrossConstraints\n                                                  MutatedTuples\n                                                  (GetUnConstrRelation qs Ridx')\n                                                  CrossConstr))\n                                          | None => None\n                                        end)\n                                  (@Iterate_Ensemble_BoundedIndex_filter\n                                     _\n                                     (fun Ridx' =>\n                                        forall tup',\n                                          (GetUnConstrRelation qs Ridx) tup'\n                                          -> SatisfiesCrossRelationConstraints\n                                               Ridx Ridx' (indexedElement tup') (GetUnConstrRelation qs Ridx'))\n                                     (fun idx =>\n                                          if (fin_eq_dec Ridx idx)\n                                          then false else true)));\n              match attrConstr, crossConstr, crossConstr' with\n                | true, true, true =>\n                  mutated   <- Pick (UnIndexedEnsembleListEquivalence\n                                       (Intersection _\n                                                     (GetRelation or Ridx)\n                                                     (Complement _ (GetUnConstrRelation (UpdateUnConstrRelation qs Ridx MutatedTuples) Ridx))));\n                    ret (UpdateUnConstrRelation qs Ridx MutatedTuples, mutated)\n                | _, _, _ => ret (DropQSConstraints or, [])\n            end\n          | None, Some tConstr =>\n              tupleConstr <- {b | (forall tup tup',\n                                     elementIndex tup <> elementIndex tup'\n                                     -> GetUnConstrRelation qs Ridx tup\n                                     -> GetUnConstrRelation qs Ridx tup'\n                                     -> tConstr (indexedElement tup) (indexedElement tup'))\n                                  -> decides b (MutationPreservesTupleConstraints\n                                                  MutatedTuples\n                                                  tConstr) };\n              crossConstr <- (Iterate_Decide_Comp_opt_Pre _\n                                  (fun Ridx'  =>\n                                      if fin_eq_dec Ridx Ridx'\n                                      then None\n                                      else\n                                        match\n                                          BuildQueryStructureConstraints qsSchema Ridx'\n                                                                         Ridx\n                                        with\n                                          | Some CrossConstr =>\n                                            Some\n                                              ((MutationPreservesCrossConstraints\n                                                     (GetUnConstrRelation qs Ridx')\n                                                     MutatedTuples\n                                                 CrossConstr))\n                                          | None => None\n                                        end)\n                                  (@Iterate_Ensemble_BoundedIndex_filter\n                                     _\n                                     (fun Ridx' =>\n                                        forall tup',\n                                          (GetUnConstrRelation qs Ridx') tup'\n                                          -> SatisfiesCrossRelationConstraints\n                                               Ridx' Ridx (indexedElement tup') (GetUnConstrRelation qs Ridx))\n                             (fun idx =>\n                                          if (fin_eq_dec Ridx idx)\n                                          then false else true)));\n              crossConstr' <- (Iterate_Decide_Comp_opt_Pre _\n                                 (fun Ridx' =>\n                                      if fin_eq_dec Ridx Ridx'\n                                      then None\n                                      else\n                                        match\n                                          BuildQueryStructureConstraints qsSchema Ridx\n                                                                         Ridx'\n                                        with\n                                          | Some CrossConstr =>\n                                            Some\n                                              ((MutationPreservesCrossConstraints\n                                                  MutatedTuples\n                                                  (GetUnConstrRelation qs Ridx')\n                                                  CrossConstr))\n                                          | None => None\n                                        end)\n                                  (@Iterate_Ensemble_BoundedIndex_filter\n                                     _\n                                     (fun Ridx' =>\n                                        forall tup',\n                                          (GetUnConstrRelation qs Ridx) tup'\n                                          -> SatisfiesCrossRelationConstraints\n                                               Ridx Ridx' (indexedElement tup') (GetUnConstrRelation qs Ridx'))\n                              (fun idx =>\n                                          if (fin_eq_dec Ridx idx)\n                                          then false else true)));\n              match tupleConstr, crossConstr, crossConstr' with\n                | true, true, true =>\n                  mutated   <- Pick (UnIndexedEnsembleListEquivalence\n                                       (Intersection _\n                                                     (GetRelation or Ridx)\n                                                     (Complement _ (GetUnConstrRelation (UpdateUnConstrRelation qs Ridx MutatedTuples) Ridx))));\n                    ret (UpdateUnConstrRelation qs Ridx MutatedTuples, mutated)\n                | _, _, _ => ret (DropQSConstraints or, [])\n              end\n          | None, None =>\n                          crossConstr <- (Iterate_Decide_Comp_opt_Pre _\n                                  (fun Ridx' =>\n                                      if fin_eq_dec Ridx Ridx'\n                                      then None\n                                      else\n                                        match\n                                          BuildQueryStructureConstraints qsSchema Ridx'\n                                                                         Ridx\n                                        with\n                                          | Some CrossConstr =>\n                                            Some\n                                              ((MutationPreservesCrossConstraints\n                                                     (GetUnConstrRelation qs Ridx')\n                                                     MutatedTuples\n                                                 CrossConstr))\n                                          | None => None\n                                        end)\n                                  (@Iterate_Ensemble_BoundedIndex_filter\n                                     _\n                                     (fun Ridx' =>\n                                        forall tup',\n                                          (GetUnConstrRelation qs Ridx') tup'\n                                          -> SatisfiesCrossRelationConstraints\n                                               Ridx' Ridx (indexedElement tup') (GetUnConstrRelation qs Ridx))\n                                         (fun idx =>\n                                          if (fin_eq_dec Ridx idx)\n                                          then false else true)));\n              crossConstr' <- (Iterate_Decide_Comp_opt_Pre _\n                                 (fun Ridx' =>\n                                      if fin_eq_dec Ridx Ridx'\n                                      then None\n                                      else\n                                        match\n                                          BuildQueryStructureConstraints qsSchema Ridx\n                                                                         Ridx'\n                                        with\n                                          | Some CrossConstr =>\n                                            Some\n                                              ((MutationPreservesCrossConstraints\n                                                  MutatedTuples\n                                                  (GetUnConstrRelation qs Ridx')\n                                                  CrossConstr))\n                                          | None => None\n                                        end)\n                                  (@Iterate_Ensemble_BoundedIndex_filter\n                                     _\n                                     (fun Ridx' =>\n                                        forall tup',\n                                          (GetUnConstrRelation qs Ridx) tup'\n                                          -> SatisfiesCrossRelationConstraints\n                                               Ridx Ridx' (indexedElement tup') (GetUnConstrRelation qs Ridx'))\n                              (fun idx =>\n                                          if (fin_eq_dec Ridx idx)\n                                          then false else true)));\n              match crossConstr, crossConstr' with\n                | true, true =>\n                  mutated   <- Pick (UnIndexedEnsembleListEquivalence\n                                       (Intersection _\n                                                     (GetRelation or Ridx)\n                                                     (Complement _ (GetUnConstrRelation (UpdateUnConstrRelation qs Ridx MutatedTuples) Ridx))));\n                    ret (UpdateUnConstrRelation qs Ridx MutatedTuples, mutated)\n                | _, _ => ret (DropQSConstraints or, [])\n              end\n        end.\n  Proof.\n    intros; rewrite QSMutateSpec_UnConstr_refine;\n    eauto using\n          refine_SatisfiesTupleConstraintsMutate,\n    refine_SatisfiesAttributeConstraintsMutate,\n    refine_SatisfiesCrossConstraintsMutate,\n    refine_SatisfiesCrossConstraintsMutate'.\n    - unfold SatisfiesTupleConstraints, SatisfiesAttributeConstraints.\n      destruct (attrConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx)).\n      + destruct (tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx)).\n        reflexivity.\n        simplify with monad laws; f_equiv.\n      + simplify with monad laws; f_equiv.\n        destruct (tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) Ridx)).\n        reflexivity.\n        simplify with monad laws; f_equiv.\n  Qed.\n\nEnd MutateRefinements.\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/QueryStructure/Implementation/Operations/General/MutateRefinements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22241571663760062}}
{"text": "(** Authors: Jianzhou Zhao. *)\n\nRequire Export LinF_Parametricity.\nRequire Import LinF_Parametricity_Macro.\nRequire Import LinF_PreLib.\nRequire Import LinF_Renaming.\nRequire Export LinF_ContextualEq_Def.\nRequire Import LinF_ContextualEq_Infrastructure.\nRequire Export LinF_ContextualEq_Lemmas.\n\nLemma contexting_regular : forall E D T C E' D' T',\n  contexting E D T C E' D' T' ->\n  wf_env E /\\ wf_lenv E D /\\ wf_typ E T kn_lin /\\\n  wf_env E' /\\ wf_lenv E' D' /\\ wf_typ E' T' kn_lin.\nProof.\n  intros E D T C E' D' T' Hcontexting.\n  (contexting_cases (induction Hcontexting) Case); auto.\n  Case \"contexting_hole\".\n    repeat(split; auto).\n      destruct K; auto.\n      destruct K; auto.\n  Case \"contexting_abs_free\".\n    pick fresh x.\n    assert (x `notin` L) as xnotin. auto.\n    apply H1 in xnotin.\n    destruct xnotin as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    repeat(split; auto).\n      inversion J4; subst. auto.\n\n       rewrite_env (nil ++ [(x, bind_typ T1')] ++E') in J5.\n       apply wf_lenv_strengthening in J5; auto.\n\n       apply wft_strengthen_ex in J6; auto.\n       destruct K.\n         apply wf_typ_arrow with (K1:=kn_nonlin) (K2:=kn_lin); auto.\n\n         apply wf_typ_sub.\n           apply wf_typ_arrow with (K1:=kn_nonlin) (K2:=kn_lin); auto.\n  Case \"contexting_labs_free\".\n    pick fresh x.\n    assert (x `notin` L) as xnotin. auto.\n    apply H1 in xnotin.\n    destruct xnotin as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    repeat(split; auto).\n       inversion J5; subst; auto.\n\n       inversion J5; subst.\n       destruct K.\n         apply wf_typ_arrow with (K1:=kn_lin) (K2:=kn_lin); auto.\n\n         apply wf_typ_sub.\n           apply wf_typ_arrow with (K1:=kn_lin) (K2:=kn_lin); auto.\n  Case \"contexting_abs_capture\".\n    destruct IHHcontexting as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    assert (J:=@env_remove_inv E' y (bind_typ T1') J4 H0).\n    destruct J as [E1'0 [E2'0 [EQ1 EQ2]]]; subst.\n    rewrite EQ1 in *.\n    repeat(split; auto).\n      apply wf_env_strengthening in J4; auto.\n      apply wf_lenv_strengthening in J5; auto.\n      destruct K.\n        apply wf_typ_arrow with (K1:=kn_nonlin) (K2:=kn_lin); auto.\n          apply wf_typ_strengthening in J6; auto.\n        apply wf_typ_sub.\n          apply wf_typ_arrow with (K1:=kn_nonlin) (K2:=kn_lin); auto.\n            apply wf_typ_strengthening in J6; auto.\n  Case \"contexting_labs_capture\".\n    destruct IHHcontexting as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    assert (J:=@lenv_remove_inv E' D' y (lbind_typ T1') J5 H0).\n    destruct J as [D1'0 [D2'0 [EQ1 EQ2]]]; subst.\n    rewrite EQ1 in *.\n    repeat(split; auto).\n      apply wf_lenv_lin_strengthening' in J5; auto.\n      destruct K.\n        apply wf_typ_arrow with (K1:=kn_lin) (K2:=kn_lin); auto.\n        apply wf_typ_sub.\n          apply wf_typ_arrow with (K1:=kn_lin) (K2:=kn_lin); auto.\n  Case \"contexting_app1\".\n    destruct IHHcontexting as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    repeat(split; auto).\n     inversion J6; subst.\n       destruct K2; auto.\n\n       inversion H2; subst; auto.\n       destruct K2; auto. \n  Case \"contexting_app2\".\n    destruct IHHcontexting as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    repeat(split; auto).\n      apply typing_regular in H. \n      destruct H as [J7 [J8 [J9 J10]]].\n      inversion J10; subst.\n       destruct K2; auto.\n\n       inversion H; subst; auto.\n       destruct K2; auto. \n  Case \"contexting_tabs_free\".\n    pick fresh X.\n    assert (X `notin` L) as Xnotin. auto.\n    apply H1 in Xnotin.\n    destruct Xnotin as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    repeat(split; auto).\n       inversion J4; subst; auto.\n\n       apply wf_lenv_strengthening_typ in J5; auto.\n\n       apply wf_all_exists with (x:=X); auto.\n         inversion J4; subst; auto.\n  Case \"contexting_tabs_capture\".\n    destruct IHHcontexting as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    assert (J:=@env_remove_inv E' Y (bind_kn K) J4 H).\n    destruct J as [E1'0 [E2'0 [EQ1 EQ2]]]; subst.\n    rewrite EQ1 in *.\n    repeat(split; auto).\n     apply wf_all_exists with (x:=Y); auto.\n       assert (Y `notin` (fv_tt (close_tt T1' Y))) as YnT1'.\n         apply  notin_close_tt; auto.\n       apply uniq_from_wf_env in J4.\n       assert (Y `notin` dom E1'0) as YnE1'0.\n         apply fresh_mid_head in J4; auto.\n       assert (Y `notin` dom E2'0) as YnE1'2.\n         apply fresh_mid_tail in J4; auto.\n       simpl_env. auto.\n\n       rewrite close_open_tt__subst_tt; eauto using type_from_wf_typ.\n       apply wf_typ_typ_permute; auto.\n       apply wf_typ_typ_renaming_one; auto.\n         apply uniq_from_wf_env in J4. solve_uniq.\n  Case \"contexting_tapp\".\n    destruct IHHcontexting as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    repeat(split; auto).\n      inversion J6; subst... \n      SSCase \"wf_typ_all\".\n        pick fresh Y.\n        rewrite (subst_tt_intro Y); auto.\n        rewrite_env ((map (subst_tb Y T') empty) ++ E'); auto.\n        eapply (wf_typ_subst_tb empty K); auto.\n        rewrite_env ([(Y, bind_kn K)] ++ E'); auto.\n      SSCase \"wf_typ_sub\".\n        apply wf_typ_sub.\n          inversion H0; subst...\n          pick fresh Y.\n          rewrite (subst_tt_intro Y); auto.\n          rewrite_env ((map (subst_tb Y T') empty) ++ E'); auto.\n          eapply (wf_typ_subst_tb empty K); auto.\n          rewrite_env ([(Y, bind_kn K)] ++ E'); auto.\n  Case \"contexting_apair1\".\n    destruct IHHcontexting as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    apply typing_regular in H. \n    destruct H as [J7 [J8 [J9 J10]]]. \n    repeat(split; eauto).\n  Case \"contexting_apair2\".\n    destruct IHHcontexting as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    apply typing_regular in H. \n    destruct H as [J7 [J8 [J9 J10]]]. \n    repeat(split; eauto).\n  Case \"contexting_fst\".\n    destruct IHHcontexting as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    repeat(split; eauto).\n      inversion J6; subst.\n       destruct K1; auto.\n\n       inversion H; subst; auto.\n  Case \"contexting_snd\".\n    destruct IHHcontexting as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n    repeat(split; eauto).\n      inversion J6; subst.\n       destruct K2; auto.\n\n       inversion H; subst; auto.\nQed.\n\nLemma contexting_nonlin_renaming_one : forall E1 E2 D t t' T T' (x y:atom) C E1' E2' D',\n  contexting (E1++[(x,bind_typ t)]++E2) D T C (E1'++[(x,bind_typ t')]++E2') D' T' ->\n  y `notin` dom E1 `union` dom E2 `union` dom D  `union` dom E1' `union` dom E2' `union` dom D' `union` cv_ec C ->\n  contexting (E1++[(y,bind_typ t)]++E2) D T (subst_ec x y C) (E1'++[(y,bind_typ t')]++E2') D' T'.\nProof.\n  intros E1 E2 D t t' T T' x y C E1' E2' D' Hcontexting yndom.\n  remember (E1++[(x, bind_typ t)]++E2) as E.\n  remember (E1'++[(x, bind_typ t')]++E2') as E'.\n  generalize dependent E1.\n  generalize dependent E2.\n  generalize dependent E1'.\n  generalize dependent E2'.\n  generalize dependent x.\n  generalize dependent t.\n  generalize dependent t'.\n  (contexting_cases (induction Hcontexting) Case); intros; subst; simpl.\n  Case \"contexting_hole\".\n    assert (uniq (E1'++[(x,bind_typ t')]++E2')) as Uniq. auto.\n    apply mid_list_inv' in HeqE; auto.\n    destruct HeqE as [J1 [J2 J3]]; subst.  \n    inversion J3; subst.\n    apply contexting_hole with (K:=K); simpl_env; auto.\n      apply wf_lenv_nonlin_renaming_one with (x:=x); auto.\n      apply wf_typ_renaming_one with (x:=x); auto.\n  Case \"contexting_abs_free\".\n    apply contexting_abs_free with (L:=L `union` {{y}} `union` {{x}}); simpl_env; auto.\n      apply wf_typ_renaming_one with (x:=x); auto.\n        pick fresh z.\n        assert (z `notin` L) as zn. auto.\n        apply H0 in zn.\n        apply contexting_regular in zn.\n        decompose [and] zn.\n        inversion H6; subst; auto.\n\n      simpl in yndom. simpl_env in H0. simpl_env. auto.\n\n      intros x0 x0n.\n      assert (x0 `notin` L) as J. auto.\n      apply H1 with (E1'0:=[(x0, bind_typ T1')]++E1') (E2'0:=E2') (t0:=t) (t'0:=t') (x1:=x) (E3:=E2) (E4:=E1) in J; auto.\n        simpl_env.\n        rewrite subst_ec_open_ec_var; auto.\n\n        rewrite (@cv_ec_open_ec_rec C1 0 x0). simpl. simpl in yndom. auto.\n  Case \"contexting_labs_free\".\n    apply contexting_labs_free with (L:=L `union` {{y}} `union` {{x}}); simpl_env; auto.\n      apply wf_typ_renaming_one with (x:=x); auto.\n        pick fresh z.\n        assert (z `notin` L) as zn. auto.\n        apply H0 in zn.\n        apply contexting_regular in zn.\n        decompose [and] zn.\n        inversion H6; subst; auto.\n\n      simpl in yndom. simpl_env in H0. simpl_env. auto.\n\n      intros x0 x0n.\n      assert (x0 `notin` L) as J. auto.\n      apply H1 with (E1'0:=E1') (E2'0:=E2') (t0:=t) (t'0:=t')  (x1:=x) (E3:=E2) (E4:=E1) in J; auto.\n        simpl_env.\n        rewrite subst_ec_open_ec_var; auto.\n\n        rewrite (@cv_ec_open_ec_rec C1 0 x0). simpl. simpl in yndom. auto.\n  Case \"contexting_abs_capture\".\n    assert (wf_env E') as Wfe.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (J:=@env_remove_inv E' y0 (bind_typ T1') Wfe H0).\n    destruct J as [E1'0 [E2'0 [EQ1 EQ2]]]; subst.\n    rewrite EQ1 in *.\n\n    assert (uniq (E1'0++E2'0)) as Uniq.\n      apply uniq_from_wf_env in Wfe.\n       solve_uniq.\n    apply app_mid_inv in HeqE'; auto.\n    destruct HeqE' as [[F [fEQ1 fEQ2]] | [F [fEQ1 fEQ2]]]; subst.\n      assert ((E1'++[(x, bind_typ t')]++F)++[(y0, bind_typ T1')]++E2'0 =\n                        E1'++[(x, bind_typ t')]++(F++[(y0, bind_typ T1')]++E2'0)) as J. \n        simpl_env. auto.\n      simpl in yndom. simpl_env in yndom. simpl_env. \n      unfold close_ec in yndom. rewrite cv_ec_close_ec_rec in yndom.\n      apply IHHcontexting with (E3:=E2) (E4:=E1) (t0:=t) in J; auto.\n        assert (env_remove (y0, bind_typ T1') (E1'++[(y, bind_typ t')]++F++[(y0, bind_typ T1')]++E2'0) \n                          = E1'++[(y, bind_typ t')]++F++E2'0) as EQ.\n          rewrite_env ((E1'++[(y, bind_typ t')]++F)++[(y0, bind_typ T1')]++E2'0).\n          rewrite_env ((E1'++[(y, bind_typ t')]++F)++E2'0).\n          apply env_remove_opt.\n            apply contexting_regular in J.\n            simpl_env.\n            decompose [and] J; auto.\n        rewrite <- EQ.\n        rewrite subst_ec_close_ec; auto.\n          apply contexting_abs_capture; auto.\n            rewrite EQ.\n            apply wf_typ_renaming_one with (x:=x); auto.\n              apply contexting_regular in J.\n              decompose [and] J.\n              rewrite_env ((E1'++[(y, bind_typ t')]++F) ++[(y0, bind_typ T1')]++E2'0) in H6.\n              apply wf_env_strengthening in H6.\n              simpl_env in H6.\n              assert (x `notin` dom E1' `union` dom F `union` dom E2'0) as xnd.\n                clear J EQ H3 H5 H4 H7 H9 EQ1 Wfe H H0 yndom Hcontexting IHHcontexting H6.\n                simpl_env in Uniq.\n                solve_uniq.\n              apply wf_env_renaming_one with (x:=y); simpl_env; auto.\n\n              simpl_env in H. assumption.\n\n            apply binds_weaken.\n            apply binds_weaken.\n            apply binds_app_3.\n            apply binds_app_2. auto.\n\n             rewrite cv_ec_subst_ec_rec. auto.\n\n          simpl.\n          apply uniq_from_wf_env in Wfe.\n          apply fresh_mid_head in Wfe.\n          simpl_env in Wfe.\n          auto.          \n\n      assert (E1'0++[(y0, bind_typ T1')]++F++[(x, bind_typ t')]++E2' =\n                        (E1'0++[(y0, bind_typ T1')]++F)++[(x, bind_typ t')]++E2') as J. \n        simpl_env. auto.\n      simpl in yndom. simpl_env in yndom. simpl_env. \n      unfold close_ec in yndom. rewrite cv_ec_close_ec_rec in yndom.\n      apply IHHcontexting with (E3:=E2) (E4:=E1) (t0:=t) in J; auto.\n        assert (env_remove (y0, bind_typ T1') (E1'0++[(y0, bind_typ T1')]++F++[(y, bind_typ t')]++E2') \n                          = E1'0++F++[(y, bind_typ t')]++E2') as EQ.\n          apply env_remove_opt.\n            apply contexting_regular in J.\n            decompose [and] J.\n            simpl_env in H6. auto.\n        rewrite <- EQ.\n        rewrite subst_ec_close_ec; auto.\n          simpl_env in J.\n          apply contexting_abs_capture; auto.\n            rewrite EQ.\n            rewrite_env ((E1'0++F)++[(y, bind_typ t')]++E2').\n            apply wf_typ_renaming_one with (x:=x); simpl_env; auto.\n              apply contexting_regular in J.\n              decompose [and] J.\n              apply wf_env_strengthening in H6.\n              rewrite_env ((E1'0++F) ++[(x, bind_typ t')]++E2').\n              assert (x `notin` dom E1'0 `union` dom F `union` dom E2') as xnd.\n                clear J EQ H3 H5 H4 H7 H9 EQ1 Wfe H H0 yndom Hcontexting IHHcontexting H6.\n                simpl_env in Uniq.\n                solve_uniq.\n              apply wf_env_renaming_one with (x:=y); simpl_env; auto.\n\n            rewrite cv_ec_subst_ec_rec. auto.\n\n          simpl.\n          apply uniq_from_wf_env in Wfe.\n          apply fresh_mid_tail in Wfe.\n          simpl_env in Wfe.\n          auto.          \n  Case \"contexting_labs_capture\".\n    assert (wf_lenv (E1'++[(x, bind_typ t')]++E2') D') as Wfle.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (J:=@lenv_remove_inv (E1'++[(x, bind_typ t')]++E2') D' y0 (lbind_typ T1') Wfle H0).\n    destruct J as [D1'0 [D2'0 [EQ1 EQ2]]]; subst.\n    simpl_env.\n    simpl_env in yndom. simpl in yndom.\n    unfold close_ec in yndom.\n    rewrite cv_ec_close_ec_rec in yndom.\n    rewrite subst_ec_close_ec; auto.\n      apply contexting_labs_capture; simpl; auto.\n        simpl_env.\n        apply wf_typ_renaming_one with (x:=x); simpl_env; auto.\n  \n        simpl_env in H1. simpl_env. auto.\n\n        rewrite cv_ec_subst_ec_rec. auto.\n\n        simpl_env in yndom.\n        rewrite EQ1 in yndom.\n        simpl_env.\n        apply IHHcontexting; auto.\n\n      apply wf_lenv_notin_dom with (x:=y0) (T:=T1') in Wfle; auto.\n  Case \"contexting_app1\".\n    simpl_env.\n    apply contexting_app1 with (D1':=D1') (D2':=D2') (T1':=T1') (K:=K); auto.\n      apply IHHcontexting; auto.\n        apply dom_lenv_split in H0.\n        rewrite H0 in yndom. auto.\n\n      apply dom_lenv_split in H0. rewrite H0 in yndom.\n      apply typing_nonlin_renaming_one with (x:=x); simpl_env; auto.\n\n      apply lenv_split_nonlin_renaming_one with (x:=x); simpl_env; auto.\n\n      apply disjdom_sym_1.\n      apply disjdom_sub with (D1:=fv_ee e2 `union` fv_ee y).\n        eapply  disjdom_app_r.\n        split; auto.\n          simpl.\n          apply disjdom_one_2; auto.\n        apply subst_ee_fv_ee_sub; auto.\n  Case \"contexting_app2\".\n    simpl_env.\n    apply contexting_app2 with (D1':=D1') (D2':=D2') (T1':=T1') (K:=K); auto.\n      apply dom_lenv_split in H0. rewrite H0 in yndom.\n      apply typing_nonlin_renaming_one with (x:=x); simpl_env; auto.\n\n      apply IHHcontexting; auto.\n        apply dom_lenv_split in H0.\n        rewrite H0 in yndom. auto.\n\n      apply lenv_split_nonlin_renaming_one with (x:=x); simpl_env; auto.\n\n      apply disjdom_sym_1.\n      apply disjdom_sub with (D1:=fv_ee e1  `union` fv_ee y).\n        eapply  disjdom_app_r.\n        split; auto.\n          simpl.\n          apply disjdom_one_2; auto.\n        apply subst_ee_fv_ee_sub; auto.\n  Case \"contexting_tabs_free\".\n    apply contexting_tabs_free with (L:=L `union` {{y}} `union` {{x}}); simpl_env; auto.\n      simpl in yndom. simpl_env in H0. simpl_env. auto.\n\n      intros X0 X0n.\n      rewrite subst_ec_open_tc_var; auto.\n      apply vcontext_through_subst_ec; auto.\n\n      intros X0 X0n.\n      assert (X0 `notin` L) as J. auto.\n      apply H1 with (E1'0:=[(X0, bind_kn K)]++E1') (E2'0:=E2') (t0:=t) (t'0:=t') (x0:=x) (E3:=E2) (E4:=E1) in J; auto.\n        simpl_env.\n        rewrite subst_ec_open_tc_var; auto.\n\n        rewrite (@cv_ec_open_tc_rec C1 0 X0). simpl. simpl in yndom. auto.\n  Case \"contexting_tabs_capture\".\n    assert (wf_env E') as Wfe.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (J:=@env_remove_inv E' Y (bind_kn K) Wfe H).\n    destruct J as [E1'0 [E2'0 [EQ1 EQ2]]]; subst.\n    rewrite EQ1 in *.\n\n    assert (uniq (E1'0++E2'0)) as Uniq.\n      apply uniq_from_wf_env in Wfe.\n       solve_uniq.\n    apply app_mid_inv in HeqE'; auto.\n    destruct HeqE' as [[F [fEQ1 fEQ2]] | [F [fEQ1 fEQ2]]]; subst.\n      assert ((E1'++[(x, bind_typ t')]++F)++[(Y, bind_kn K)]++E2'0 =\n                        E1'++[(x, bind_typ t')]++(F++[(Y, bind_kn K)]++E2'0)) as J. \n        simpl_env. auto.\n      simpl in yndom. simpl_env in yndom. simpl_env. \n      unfold close_tc in yndom. rewrite cv_ec_close_tc_rec in yndom.\n      apply IHHcontexting with (E3:=E2) (E4:=E1) (t0:=t) in J; auto.\n        assert (env_remove (Y, bind_kn K) (E1'++[(y, bind_typ t')]++F++[(Y, bind_kn K)]++E2'0) \n                          = E1'++[(y, bind_typ t')]++F++E2'0) as EQ.\n          rewrite_env ((E1'++[(y, bind_typ t')]++F)++[(Y, bind_kn K)]++E2'0).\n          rewrite_env ((E1'++[(y, bind_typ t')]++F)++E2'0).\n          apply env_remove_opt.\n            apply contexting_regular in J.\n            simpl_env.\n            decompose [and] J; auto.\n        rewrite <- EQ.\n        rewrite subst_ec_close_tc; auto.\n          apply contexting_tabs_capture; auto.\n            apply binds_weaken.\n            apply binds_weaken.\n            apply binds_app_3.\n            apply binds_app_2. auto.\n\n             rewrite cv_ec_subst_ec_rec. auto.\n\n             apply vcontext_through_subst_ec; auto.\n\n             rewrite EQ.\n             simpl_env in H2.\n             apply wf_lenv_nonlin_renaming_one with (x:=x); auto.\n\n          simpl.\n          apply uniq_from_wf_env in Wfe.\n          apply fresh_mid_head in Wfe.\n          simpl_env in Wfe.\n          auto.          \n\n      assert (E1'0++[(Y, bind_kn K)]++F++[(x, bind_typ t')]++E2' =\n                        (E1'0++[(Y, bind_kn K)]++F)++[(x, bind_typ t')]++E2') as J. \n        simpl_env. auto.\n      simpl in yndom. simpl_env in yndom. simpl_env. \n      unfold close_tc in yndom. rewrite cv_ec_close_tc_rec in yndom.\n      apply IHHcontexting with (E3:=E2) (E4:=E1) (t0:=t) in J; auto.\n        assert (env_remove (Y, bind_kn K) (E1'0++[(Y, bind_kn K)]++F++[(y, bind_typ t')]++E2') \n                          = E1'0++F++[(y, bind_typ t')]++E2') as EQ.\n          apply env_remove_opt.\n            apply contexting_regular in J.\n            decompose [and] J.\n            simpl_env in H7. auto.\n        rewrite <- EQ.\n        rewrite subst_ec_close_tc; auto.\n          simpl_env in J.\n          apply contexting_tabs_capture; auto.\n            rewrite cv_ec_subst_ec_rec. auto.\n\n            apply vcontext_through_subst_ec; auto.\n\n            rewrite EQ.\n            rewrite_env ((E1'0++F)++[(y, bind_typ t')]++E2').\n            apply wf_lenv_nonlin_renaming_one with (x:=x); simpl_env; auto.\n\n          simpl.\n          apply uniq_from_wf_env in Wfe.\n          apply fresh_mid_tail in Wfe.\n          simpl_env in Wfe.\n          auto.          \n  Case \"contexting_tapp\".\n    simpl_env.\n    apply contexting_tapp with (K:=K); auto.\n      apply wf_typ_renaming_one with (x:=x); simpl_env; auto.\n        apply contexting_regular in Hcontexting. \n        decompose [and] Hcontexting; auto.\n  Case \"contexting_apair1\".\n    simpl_env.\n    apply contexting_apair1 with (T1':=T1'); auto.\n      apply typing_nonlin_renaming_one with (x:=x); simpl_env; auto.\n  Case \"contexting_apair2\".\n    simpl_env.\n    apply contexting_apair2 with (T1':=T1'); auto.\n      apply typing_nonlin_renaming_one with (x:=x); simpl_env; auto.\n  Case \"contexting_fst\".\n    simpl_env.\n    apply contexting_fst with (T2':=T2'); auto.\n  Case \"contexting_snd\".\n    simpl_env.\n    apply contexting_snd with (T1':=T1'); auto.\nQed.\n\nLemma contexting_lin_renaming_one : forall E D1 D2 t t' T T' (x y:atom) C E' D1' D2',\n  contexting E (D1++[(x,lbind_typ t)]++D2) T C E' (D1'++[(x,lbind_typ t')]++D2') T' ->\n  y `notin` dom D1 `union` dom D2 `union` dom E  `union` dom D1' `union` dom D2' `union` dom E' `union` cv_ec C ->\n  contexting E (D1++[(y,lbind_typ t)]++D2) T (subst_ec x y C) E' (D1'++[(y,lbind_typ t')]++D2') T'.\nProof.\n  intros E D1 D2 t t' T T' x y C E' D1' D2' Hcontexting yndom.\n  remember (D1++[(x, lbind_typ t)]++D2) as D.\n  remember (D1'++[(x, lbind_typ t')]++D2') as D'.\n  generalize dependent D1.\n  generalize dependent D2.\n  generalize dependent D1'.\n  generalize dependent D2'.\n  generalize dependent x.\n  generalize dependent t.\n  generalize dependent t'.\n  (contexting_cases (induction Hcontexting) Case); intros; subst; simpl.\n  Case \"contexting_hole\".\n    assert (uniq (D1'++[(x,lbind_typ t')]++D2')) as Uniq. eauto.\n    apply mid_list_inv' in HeqD; auto.\n    destruct HeqD as [J1 [J2 J3]]; subst.  \n    inversion J3; subst.\n    apply contexting_hole with (K:=K); auto.\n      simpl_env.\n      apply wf_lenv_renaming_one with (x0:=x); auto.\n        assert (x `notin` dom E) as xnE. \n          apply wf_lenv_notin_dom with (x:=x) (T:=t) in H; auto.\n        assert (x `notin` dom D1) as xnD1. \n          apply fresh_mid_head in Uniq; auto.\n        assert (x `notin` dom D2) as xnD2. \n          apply fresh_mid_tail in Uniq; auto.\n        auto.\n  Case \"contexting_abs_free\".\n    apply contexting_abs_free with (L:=L `union` {{y}} `union` {{x}}); auto.\n      simpl in yndom. simpl_env in H0. simpl_env. auto.\n\n      intros x0 x0n.\n      assert (x0 `notin` L) as J. auto.\n      apply H1 with (D1'0:=D1') (D2'0:=D2') (t0:=t) (t'0:=t') (x1:=x) (D3:=D2) (D4:=D1) in J; auto.\n        simpl_env.\n        rewrite subst_ec_open_ec_var; auto.\n\n        rewrite (@cv_ec_open_ec_rec C1 0 x0). simpl. simpl in yndom. auto.\n\n        intros J. apply H2 in J.\n        contradict J. simpl.\n        apply app_cons_not_nil.\n  Case \"contexting_labs_free\".\n    apply contexting_labs_free with (L:=L `union` {{y}} `union` {{x}}); auto.\n      simpl in yndom. simpl_env in H0. simpl_env. auto.\n\n      intros x0 x0n.\n      assert (x0 `notin` L) as J. auto.\n      apply H1 with (D1'0:=[(x0, lbind_typ T1')]++D1') (D2'0:=D2') (t0:=t) (t'0:=t')  (x1:=x) (D3:=D2) (D4:=D1) in J; auto.\n        simpl_env.\n        rewrite subst_ec_open_ec_var; auto.\n\n        rewrite (@cv_ec_open_ec_rec C1 0 x0). simpl. simpl in yndom. auto.\n\n        intros J. apply H2 in J.\n        contradict J. simpl.\n        apply app_cons_not_nil.\n  Case \"contexting_abs_capture\".\n    assert (wf_env E') as Wfe.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (J:=@env_remove_inv E' y0 (bind_typ T1') Wfe H0).\n    destruct J as [E1'0 [E2'0 [EQ1 EQ2]]]; subst.\n    simpl_env.\n    simpl_env in yndom. simpl in yndom.\n    unfold close_ec in yndom.\n    rewrite cv_ec_close_ec_rec in yndom.\n    rewrite subst_ec_close_ec; auto.\n      apply contexting_abs_capture; simpl; auto.\n        rewrite cv_ec_subst_ec_rec. auto.\n\n        simpl_env in yndom.\n        rewrite EQ1 in yndom.\n        simpl_env.\n        apply IHHcontexting; auto.\n\n        intros J. apply H2 in J.\n        contradict J. simpl.\n        apply app_cons_not_nil.\n  Case \"contexting_labs_capture\".\n    assert (wf_lenv E' D') as Wfle.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (J:=@lenv_remove_inv E' D' y0 (lbind_typ T1') Wfle H0).\n    destruct J as [D1'0 [D2'0 [EQ1 EQ2]]]; subst.\n    rewrite EQ1 in *.\n    assert (uniq (D1'0++D2'0)) as Uniq.\n      apply uniq_from_wf_lenv in Wfle.\n      solve_uniq.\n    apply app_mid_inv in HeqD'; auto.\n    destruct HeqD' as [[F [fEQ1 fEQ2]] | [F [fEQ1 fEQ2]]]; subst.\n      assert ((D1'++[(x, lbind_typ t')]++F)++[(y0, lbind_typ T1')]++D2'0 =\n                        D1'++[(x, lbind_typ t')]++(F++[(y0, lbind_typ T1')]++D2'0)) as J. \n        simpl_env. auto.\n      simpl in yndom. simpl_env in yndom. simpl_env. \n      unfold close_ec in yndom. rewrite cv_ec_close_ec_rec in yndom.\n      apply IHHcontexting with (D3:=D2) (D4:=D1) (t0:=t) in J; auto.\n        assert (lenv_remove (y0, lbind_typ T1') (D1'++[(y, lbind_typ t')]++F++[(y0, lbind_typ T1')]++D2'0) \n                          = D1'++[(y, lbind_typ t')]++F++D2'0) as EQ.\n          rewrite_env ((D1'++[(y, lbind_typ t')]++F)++[(y0, lbind_typ T1')]++D2'0).\n          rewrite_env ((D1'++[(y, lbind_typ t')]++F)++D2'0).\n          apply lenv_remove_opt.\n            apply contexting_regular in J.\n            simpl_env.\n            decompose [and] J; eauto.\n\n        rewrite <- EQ.\n        rewrite subst_ec_close_ec; auto.\n          apply contexting_labs_capture; auto.\n            apply binds_weaken.\n            apply binds_weaken.\n            apply binds_app_3.\n            apply binds_app_2. auto.\n\n             rewrite cv_ec_subst_ec_rec. auto.\n\n             intros JJ.\n             apply H2 in JJ.\n             simpl_env in JJ.\n             contradict JJ. simpl.\n             apply app_cons_not_nil.\n\n          simpl.\n          apply uniq_from_wf_lenv in Wfle.\n          apply fresh_mid_head in Wfle.\n          simpl_env in Wfle.\n          auto.          \n\n      assert (D1'0++[(y0, lbind_typ T1')]++F++[(x, lbind_typ t')]++D2' =\n                        (D1'0++[(y0, lbind_typ T1')]++F)++[(x, lbind_typ t')]++D2') as J. \n        simpl_env. auto.\n      simpl in yndom. simpl_env in yndom. simpl_env. \n      unfold close_ec in yndom. rewrite cv_ec_close_ec_rec in yndom.\n      apply IHHcontexting with (D3:=D2) (D4:=D1) (t0:=t) in J; auto.\n        assert (lenv_remove (y0, lbind_typ T1') (D1'0++[(y0, lbind_typ T1')]++F++[(y, lbind_typ t')]++D2') \n                          = D1'0++F++[(y, lbind_typ t')]++D2') as EQ.\n          apply lenv_remove_opt.\n            apply contexting_regular in J.\n            decompose [and] J.\n            simpl_env in H7; eauto.\n\n        rewrite <- EQ.\n        rewrite subst_ec_close_ec; auto.\n          simpl_env in J.\n          apply contexting_labs_capture; auto.\n             rewrite cv_ec_subst_ec_rec. auto.\n\n             intros JJ.\n             apply H2 in JJ.\n             rewrite_env ((D1'0++F)++[(x, lbind_typ t')]++D2') in JJ.\n             contradict JJ. simpl.\n             apply app_cons_not_nil.\n\n          simpl.\n          apply uniq_from_wf_lenv in Wfle.\n          apply fresh_mid_tail in Wfle.\n          simpl_env in Wfle.\n          auto.          \n  Case \"contexting_app1\".\n    simpl_env.\n    assert (Split:=H0).\n    apply lenv_split_cases_mid in H0.\n    destruct H0 as [LEFT | RIGHT].\n    SCase \"left\".\n      destruct LEFT as [D1L' [D1R' [D2L' [D2R' [Q1 [Q2 [S1 S2]]]]]]]; subst.\n      assert (D1L' ++ [(x, lbind_typ t')] ++ D1R'=D1L' ++ [(x, lbind_typ t')] ++ D1R') as IH1. auto.\n      assert (DomEq2:=S2).\n      apply dom_lenv_split in DomEq2.\n      rewrite DomEq2 in yndom.\n      assert (DomEq1:=S1).\n      apply dom_lenv_split in DomEq1.\n      rewrite DomEq1 in yndom.\n      apply IHHcontexting with (D3:=D2) (D4:=D1) (t0:=t) in IH1; auto.\n      clear IHHcontexting.\n      assert (x `notin` (dom (D2L'++D2R') `union` dom E')) as J.\n        eapply lenv_split_not_in_left; eauto.\n          simpl_env. auto.\n      rewrite <- (non_subst E' (D2L'++D2R') e2 T1' x y); auto.\n      apply contexting_app1 with (D1':=D1L' ++ [(y, lbind_typ t')] ++ D1R') (D2':=D2L' ++ D2R') (T1':=T1') (K:=K); auto.\n        eapply lenv_split_sub_left; eauto.\n          apply wf_lenv_split in Split.\n          assert (x `notin` dom D1'0) as xnotinD1'0.\n            apply uniq_from_wf_lenv in Split.\n            apply fresh_mid_head in Split; auto.\n          assert (x `notin` dom D2'0) as xnotinD2'0.\n            apply uniq_from_wf_lenv in Split.\n            apply fresh_mid_tail in Split; auto.\n          apply wf_lenv_renaming_one with (x0:=x); auto.\n             rewrite DomEq1. rewrite DomEq2. auto.\n        destruct H1 as [H11 H12].\n        assert (y `notin` fv_ee e2) as yne2.\n          apply notin_fv_ee_typing with (y:=y) in H; auto.\n        split; intros x0 x0Fv.\n          destruct (y==x0); subst.\n            contradict x0Fv; auto.\n\n            apply H11 in x0Fv.\n            simpl_env. simpl_env in x0Fv. auto.  \n          destruct (y==x0); subst; auto.\n            apply H12.\n            clear J yne2 IH1 Split yndom H11 H12 Hcontexting Split DomEq2 DomEq1 S1 S2 H.  \n            simpl_env in *. fsetdec.\n    SCase \"right\".\n      destruct RIGHT as [D1L' [D1R' [D2L' [D2R' [Q1 [Q2 [S1 S2]]]]]]]; subst.\n      assert (x `in` fv_ee e2) as xine2.\n        apply in_lfv_ee_typing with (y:=x) in H; auto.\n          simpl_env. auto.\n      assert (x `notin` fv_ee e2) as xnotine2.\n        destruct H1 as [J1 J2].\n        assert (x `in` dom (D1++[(x, lbind_typ t)]++D2)) as J. simpl_env. auto.\n        apply J2 in J. auto.\n      contradict xine2; auto.\n  Case \"contexting_app2\".\n    simpl_env.\n    assert (Split:=H0).\n    apply lenv_split_cases_mid in H0.\n    destruct H0 as [LEFT | RIGHT].\n    SCase \"left\".\n      destruct LEFT as [D1L' [D1R' [D2L' [D2R' [Q1 [Q2 [S1 S2]]]]]]]; subst.\n      assert (x `in` fv_ee e1) as xinv1.\n        apply in_lfv_ee_typing with (y:=x) in H; auto.\n          simpl_env. auto.\n      assert (x `notin` fv_ee e1) as xnotinv1.\n        destruct H1 as [J1 J2].\n        assert (x `in` dom (D1++[(x, lbind_typ t)]++D2)) as J. simpl_env. auto.\n        apply J2 in J. auto.\n      contradict xinv1; auto.\n    SCase \"right\".\n      destruct RIGHT as [D1L' [D1R' [D2L' [D2R' [Q1 [Q2 [S1 S2]]]]]]]; subst.\n      assert (D2L' ++ [(x, lbind_typ t')] ++ D2R'=D2L' ++ [(x, lbind_typ t')] ++ D2R') as IH2. auto.\n      assert (DomEq2:=S2).\n      apply dom_lenv_split in DomEq2.\n      rewrite DomEq2 in yndom.\n      assert (DomEq1:=S1).\n      apply dom_lenv_split in DomEq1.\n      rewrite DomEq1 in yndom.\n      apply IHHcontexting with (D3:=D2) (D4:=D1) (t0:=t) in IH2; auto.\n      clear IHHcontexting.\n      assert (x `notin` (dom (D1L'++D1R') `union` dom E')) as J.\n        eapply lenv_split_not_in_right; eauto.\n          simpl_env. auto.\n      rewrite <- (non_subst E' (D1L'++D1R') e1 (typ_arrow K T1' T2') x y); auto.\n      apply contexting_app2 with (T1':=T1') (K:=K) (D1':=D1L' ++ D1R') (D2':=D2L' ++ [(y, lbind_typ t')] ++ D2R'); auto.\n        simpl_env.\n        eapply lenv_split_sub_right; eauto.\n          apply wf_lenv_split in Split.\n          assert (x `notin` dom D1'0) as xnotinD1'0.\n            apply uniq_from_wf_lenv in Split.\n            apply fresh_mid_head in Split; auto.\n          assert (x `notin` dom D2'0) as xnotinD2'0.\n            apply uniq_from_wf_lenv in Split.\n            apply fresh_mid_tail in Split; auto.\n          apply wf_lenv_renaming_one with (x0:=x); auto.\n             rewrite DomEq1. rewrite DomEq2. auto.\n        destruct H1 as [H21 H22].\n        assert (y `notin` fv_ee e1) as yne1.\n          apply notin_fv_ee_typing with (y:=y) in H; auto.\n        split; intros x0 x0Fv.\n          destruct (y==x0); subst.\n            contradict x0Fv; auto.\n\n            apply H21 in x0Fv.\n            simpl_env. simpl_env in x0Fv. auto.  \n          destruct (y==x0); subst; auto.\n            apply H22.\n            clear J yne1 IH2 Split yndom H21 H22 Hcontexting Split DomEq2 DomEq1 S1 S2 H.  \n            simpl_env in *. fsetdec.\n  Case \"contexting_tabs_free\".\n    apply contexting_tabs_free with (L:=L `union` {{y}} `union` {{x}}); auto.\n      simpl in yndom. simpl_env in H0. simpl_env. auto.\n\n      intros X0 X0n.\n      rewrite subst_ec_open_tc_var; auto.\n      apply vcontext_through_subst_ec; auto.\n\n      intros X0 X0n.\n      assert (X0 `notin` L) as J. auto.\n      apply H1 with (D1'0:=D1') (D2'0:=D2') (t0:=t) (t'0:=t') (x0:=x) (D3:=D2) (D4:=D1) in J; auto.\n        simpl_env.\n        rewrite subst_ec_open_tc_var; auto.\n\n        rewrite (@cv_ec_open_tc_rec C1 0 X0). simpl. simpl in yndom. auto.\n  Case \"contexting_tabs_capture\".\n    assert (wf_env E') as Wfe.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (J:=@env_remove_inv E' Y (bind_kn K) Wfe H).\n    destruct J as [E1'0 [E2'0 [EQ1 EQ2]]]; subst.\n    simpl_env.\n    simpl_env in yndom. simpl in yndom.\n    unfold close_tc in yndom.\n    rewrite cv_ec_close_tc_rec in yndom.\n    rewrite subst_ec_close_tc; auto.\n      apply contexting_tabs_capture; simpl; auto.\n        rewrite cv_ec_subst_ec_rec. auto. \n\n        apply vcontext_through_subst_ec; auto.\n\n        simpl_env in yndom.\n        rewrite EQ1 in yndom.\n        simpl_env.\n        apply IHHcontexting; auto.\n\n        simpl_env.\n        simpl_env in yndom.\n        rewrite EQ1 in *.\n        assert (x `notin` dom (E1'0++E2'0)) as ynE0.\n          apply wf_lenv_notin_dom with (x:=x) (T:=t') in H2; auto.\n        assert (x `notin` dom D1') as ynD1'.\n          apply fresh_mid_head with (E:=D2') (a:=lbind_typ t'); auto.\n            apply uniq_from_wf_lenv in H2; auto.\n        assert (x `notin` dom D2') as ynD2'.\n          apply fresh_mid_tail with (F:=D1') (a:=lbind_typ t'); auto.\n             apply uniq_from_wf_lenv in H2; auto.\n        apply wf_lenv_renaming_one with (x0:=x); auto.\n\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting.\n      apply wf_lenv_notin_dom with (x:=x) (T:=t') in H7; auto.\n  Case \"contexting_tapp\".\n    simpl_env.\n    apply contexting_tapp with (K:=K); auto.\n  Case \"contexting_apair1\".\n    simpl_env.\n    apply contexting_apair1 with (T1':=T1'); auto.\n      apply typing_lin_renaming_one; auto.\n  Case \"contexting_apair2\".\n    simpl_env.\n    apply contexting_apair2 with (T1':=T1'); auto.\n      apply typing_lin_renaming_one; auto.\n  Case \"contexting_fst\".\n    simpl_env.\n    apply contexting_fst with (T2':=T2'); auto.\n  Case \"contexting_snd\".\n    simpl_env.\n    apply contexting_snd with (T1':=T1'); auto.\nQed.\n\nLemma contexting_plug_typing : forall E D T C E' D' T' e,\n  contexting E D T C E' D' T' ->\n  typing E D e T ->\n  typing E' D' (plug C e) T'.\nProof.\n  intros E D T C E' D' T' e Hcontexting Htyping.\n  generalize dependent e.\n  (contexting_cases (induction Hcontexting) Case); \n    intros e Htyping; simpl in *; eauto.\n  Case \"contexting_abs_free\".\n    apply typing_abs with (L:=L `union` cv_ec C1); auto.\n      intros x xn.\n      assert (x `notin` L) as xnL. auto.\n      apply H1 with (e:=open_ee (shift_ee e) x) in xnL; auto.\n        rewrite open_ee_plug; auto.\n          eapply disjdom_app_l; auto.\n          split; simpl.\n            apply disjdom_one_2; auto.\n            apply disjdom_nil_1.\n\n        rewrite <- shift_ee_expr; auto.\n        rewrite <- open_ee_expr; auto.\n\n  Case \"contexting_labs_free\".\n    apply typing_labs with (L:=L `union` cv_ec C1); auto.\n      intros x xn.\n      assert (x `notin` L) as xnL. auto.\n      apply H1 with (e:=open_ee (shift_ee e) x) in xnL; auto.\n        rewrite open_ee_plug; auto.\n          eapply disjdom_app_l; auto.\n          split; simpl.\n            apply disjdom_one_2; auto.\n            apply disjdom_nil_1.\n\n        rewrite <- shift_ee_expr; auto.\n        rewrite <- open_ee_expr; auto.\n\n  Case \"contexting_abs_capture\".\n    apply typing_abs with (L:=dom D' `union` dom (env_remove (y, bind_typ T1') E') `union` cv_ec C1 `union`  (cv_ec (close_ec C1 y))); auto.\n      intros x xnL.\n      assert (disjdom (union (fv_ee x) (fv_te x)) (cv_ec (close_ec C1 y))) as Disj.\n        eapply disjdom_app_l.\n        split.\n          apply disjdom_one_2; auto.\n          simpl. apply disjdom_nil_1.\n      rewrite open_ee_plug; auto.\n      assert (J:=Htyping).\n      apply IHHcontexting in J.\n      rewrite <- shift_ee_expr; auto.\n      assert (wf_env E') as Wfe. \n        apply contexting_regular in Hcontexting.\n        decompose [and] Hcontexting; auto.\n      assert (J':=@env_remove_inv E' y (bind_typ T1') Wfe H0).\n      destruct J' as [E1' [E2' [EQ1 EQ2]]]; subst.\n      rewrite EQ1 in *.\n      rewrite close_open_ee__subst_ee; auto.\n      assert (context C1) as Ctx1.\n        apply contexting__context in Hcontexting; auto.\n      rewrite close_open_ec__subst_ec; auto.\n      assert (disjdom (union {{y}} (union (fv_ee x) (fv_te x))) (cv_ec C1)) as Disj'.\n        eapply disjdom_app_l.\n        split.\n          apply disjdom_one_2; auto.\n        eapply disjdom_app_l.\n        split.\n          apply disjdom_one_2; auto.\n          simpl. apply disjdom_nil_1.\n      rewrite <- subst_ee_plug; auto.\n     apply typing_nonlin_renaming_permute with (x:=y); auto.\n\n  Case \"contexting_labs_capture\".\n    apply typing_labs with (L:=dom E' `union` dom (lenv_remove (y, lbind_typ T1') D') `union` cv_ec C1 `union`  (cv_ec (close_ec C1 y))); auto.\n      intros x xnL.\n      assert (disjdom (union (fv_ee x) (fv_te x)) (cv_ec (close_ec C1 y))) as Disj.\n        eapply disjdom_app_l.\n        split.\n          apply disjdom_one_2; auto.\n          simpl. apply disjdom_nil_1.\n      rewrite open_ee_plug; auto.\n      assert (J:=Htyping).\n      apply IHHcontexting in J.\n        rewrite <- shift_ee_expr; auto.\n        assert (wf_lenv E' D') as Wfle. \n          apply contexting_regular in Hcontexting.\n          decompose [and] Hcontexting; auto.\n        assert (J':=@lenv_remove_inv E' D' y (lbind_typ T1') Wfle H0).\n        destruct J' as [D1' [D2' [EQ1 EQ2]]]; subst.\n        rewrite EQ1 in *.\n        rewrite close_open_ee__subst_ee; auto.\n        assert (context C1) as Ctx1.\n          apply contexting__context in Hcontexting; auto.\n        rewrite close_open_ec__subst_ec; auto.\n      assert (disjdom (union {{y}} (union (fv_ee x) (fv_te x))) (cv_ec C1)) as Disj'.\n        eapply disjdom_app_l.\n        split.\n          apply disjdom_one_2; auto.\n        eapply disjdom_app_l.\n        split.\n          apply disjdom_one_2; auto.\n          simpl. apply disjdom_nil_1.\n        rewrite <- subst_ee_plug; auto.\n       apply typing_lin_renaming_permute with (x:=y); auto.\n\n  Case \"contexting_tabs_free\".\n    apply typing_tabs with (L:=L `union` cv_ec C1); auto.\n      intros X Xn.\n      rewrite <- shift_te_expr; auto.\n      rewrite open_te_plug; auto.\n          rewrite <- open_te_expr'; auto.\n            apply plug_vcontext__value; auto.\n              apply H1 with (X:=X) in Htyping; auto.\n                 apply typing_regular in Htyping.\n                 decompose [and] Htyping; auto.\n            apply disjdom_one_2; auto.        \n\n      intros X Xn.\n      assert (X `notin` L) as XnL. auto.\n      apply H1 with (e:=open_te (shift_te e) X) in XnL; auto.\n        rewrite open_te_plug; auto.\n          apply disjdom_one_2; auto.\n        rewrite <- shift_te_expr; auto.\n        rewrite <- open_te_expr'; auto.\n  Case \"contexting_tabs_capture\".\n    apply typing_tabs with (L:=dom D' `union` dom (env_remove (Y, bind_kn K) E') `union` cv_ec C1 `union`  (cv_ec (close_tc C1 Y))); auto.\n      intros X Xn.\n      rewrite <- shift_te_expr; auto.\n      rewrite open_te_plug; auto.\n        rewrite close_open_te__subst_te; auto.\n        rewrite close_open_tc__subst_tc; auto.\n          apply plug_vcontext__value.\n            apply vcontext_through_subst_tc; auto.\n            apply plug_context__expr.\n              apply context_through_subst_tc; auto.\n                apply vcontext__context in H1; auto.\n              apply subst_te_expr; auto.             \n          apply vcontext__context in H1; auto.\n        apply disjdom_one_2; auto.        \n\n      intros X XnL.\n      assert (disjdom (fv_tt X) (cv_ec (close_tc C1 Y))) as Disj.\n        apply disjdom_one_2; auto.\n      rewrite open_te_plug; auto.\n      assert (J:=Htyping).\n      apply IHHcontexting in J.\n      rewrite <- shift_te_expr; auto.\n      assert (wf_env E') as Wfe. \n        apply contexting_regular in Hcontexting.\n        decompose [and] Hcontexting; auto.\n      assert (J':=@env_remove_inv E' Y (bind_kn K) Wfe H).\n      destruct J' as [E1' [E2' [EQ1 EQ2]]]; subst.\n      rewrite EQ1 in *.\n      rewrite close_open_te__subst_te; auto.\n      assert (context C1) as Ctx1.\n        apply contexting__context in Hcontexting; auto.\n      rewrite close_open_tc__subst_tc; auto.\n      assert (disjdom (union {{Y}} (fv_tt X)) (cv_ec C1)) as Disj'.\n        eapply disjdom_app_l.\n        split.\n          apply disjdom_one_2; auto.\n          apply disjdom_one_2; auto.\n      rewrite <- subst_te_plug; auto.\n      rewrite close_open_tt__subst_tt; auto.\n        apply typing_typ_renaming_permute with (X:=Y); auto.\n\n        apply contexting_regular in Hcontexting. \n        decompose  [and] Hcontexting.\n        apply type_from_wf_typ in H9; auto.\nQed.\n\nLemma contexting_typ_renaming_one : forall E1 E2 D K K' T T' (X Y:atom) C E1' E2' D',\n  contexting (E1++[(X,bind_kn K)]++E2) D T C (E1'++[(X,bind_kn K')]++E2') D' T' ->\n  Y `notin` dom E1 `union` dom E2 `union` dom D  `union` dom E1' `union` dom E2' `union` dom D' `union` cv_ec C ->\n  contexting (map (subst_tb X Y) E1 ++[(Y,bind_kn K)]++E2) (map (subst_tlb X Y) D) (subst_tt X Y T) (subst_tc X Y C) (map (subst_tb X Y) E1' ++[(Y,bind_kn K')]++E2') (map (subst_tlb X Y) D') (subst_tt X Y T').\nProof.\n  intros E1 E2 D K K' T T' X Y C E1' E2' D' Hcontexting yndom.\n  remember (E1++[(X, bind_kn K)]++E2) as E.\n  remember (E1'++[(X, bind_kn K')]++E2') as E'.\n  generalize dependent E1.\n  generalize dependent E2.\n  generalize dependent E1'.\n  generalize dependent E2'.\n  generalize dependent X.\n  generalize dependent K.\n  generalize dependent K'.\n  (contexting_cases (induction Hcontexting) Case); intros; subst; simpl.\n  Case \"contexting_hole\".\n    assert (uniq (E1'++[(X,bind_kn K')]++E2')) as Uniq. auto.\n    apply mid_list_inv' in HeqE; auto.\n    destruct HeqE as [J1 [J2 J3]]; subst.  \n    inversion J3; subst.\n    apply contexting_hole with (K:=K); simpl_env; auto.\n      apply wf_lenv_typ_renaming_one with (X:=X); auto.\n      apply wf_typ_typ_renaming_one' with (X:=X); auto.\n  Case \"contexting_abs_free\".\n    apply contexting_abs_free with (L:=L `union` {{Y}} `union` {{X}}); simpl_env; auto.\n      apply wf_typ_typ_renaming_one' with (X:=X); auto.\n        pick fresh Z.\n        assert (Z `notin` L) as zn. auto.\n        apply H0 in zn.\n        apply contexting_regular in zn.\n        decompose [and] zn.\n        inversion H6; subst; auto.\n\n      simpl in yndom. simpl_env in H0. simpl_env. auto.\n\n      intros x0 x0n.\n      assert (x0 `notin` L) as J. auto.\n      apply H1 with (E1'0:=[(x0, bind_typ T1')]++E1') (E2'0:=E2') (K:=K0) (K'0:=K') (X0:=X) (E3:=E2) (E4:=E1) in J; auto.\n        simpl_env.\n        rewrite subst_tc_open_ec_var; auto.\n\n        rewrite (@cv_ec_open_ec_rec C1 0 x0). simpl. simpl in yndom. auto.\n\n      intros J.\n      apply H2 in J.\n      subst. auto.\n  Case \"contexting_labs_free\".\n    apply contexting_labs_free with (L:=L `union` {{Y}} `union` {{X}}); simpl_env; auto.\n      apply wf_typ_typ_renaming_one' with (X:=X); auto.\n        pick fresh z.\n        assert (z `notin` L) as zn. auto.\n        apply H0 in zn.\n        apply contexting_regular in zn.\n        decompose [and] zn.\n        inversion H6; subst; auto.\n\n      simpl in yndom. simpl_env in H0. simpl_env. auto.\n\n      intros x0 x0n.\n      assert (x0 `notin` L) as J. auto.\n      apply H1 with (E1'0:=E1') (E2'0:=E2') (K:=K0) (K'0:=K')  (X0:=X) (E3:=E2) (E4:=E1) in J; auto.\n        simpl_env.\n        rewrite subst_tc_open_ec_var; auto.\n\n        rewrite (@cv_ec_open_ec_rec C1 0 x0). simpl. simpl in yndom. auto.\n\n      intros J.\n      apply H2 in J.\n      subst. auto.\n  Case \"contexting_abs_capture\".\n    assert (wf_env E') as Wfe.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (J:=@env_remove_inv E' y (bind_typ T1') Wfe H0).\n    destruct J as [E1'0 [E2'0 [EQ1 EQ2]]]; subst.\n    rewrite EQ1 in *.\n\n    assert (uniq (E1'0++E2'0)) as Uniq.\n      apply uniq_from_wf_env in Wfe.\n       solve_uniq.\n    apply app_mid_inv in HeqE'; auto.\n    destruct HeqE' as [[F [fEQ1 fEQ2]] | [F [fEQ1 fEQ2]]]; subst.\n      assert ((E1'++[(X, bind_kn K')]++F)++[(y, bind_typ T1')]++E2'0 =\n                        E1'++[(X, bind_kn K')]++(F++[(y, bind_typ T1')]++E2'0)) as J. \n        simpl_env. auto.\n      simpl in yndom. simpl_env in yndom. simpl_env. \n      unfold close_ec in yndom. rewrite cv_ec_close_ec_rec in yndom.\n      apply IHHcontexting with (E3:=E2) (E4:=E1) (K:=K0) in J; auto.\n        assert (env_remove (y, bind_typ (subst_tt X Y T1')) (map (subst_tb X Y) E1'++[(Y, bind_kn K')]++F++[(y, bind_typ (subst_tt X Y T1'))]++E2'0) \n                          = map (subst_tb X Y) E1'++[(Y, bind_kn K')]++F++E2'0) as EQ.\n          rewrite_env ((map (subst_tb X Y) E1'++[(Y, bind_kn K')]++F)++[(y, bind_typ (subst_tt X Y T1'))]++E2'0).\n          rewrite_env ((map (subst_tb X Y) E1'++[(Y, bind_kn K')]++F)++E2'0).\n          apply env_remove_opt.\n            apply contexting_regular in J.\n            decompose [and] J; auto.\n            apply uniq_from_wf_env in H6.\n            clear H3 H5 H4 H7 H9 J Uniq EQ1 Wfe IHHcontexting H0 H yndom H1.\n            rewrite_env ((map (subst_tb X Y) E1'++[(Y, bind_kn K')]++F)++[(y, bind_typ T1')]++E2'0) in H6.\n            apply uniq_insert_mid; auto.     \n              apply uniq_remove_mid in H6; auto.\n              solve_uniq.\n              solve_uniq.\n        rewrite <- EQ.\n        rewrite subst_tc_close_ec; auto.\n          apply contexting_abs_capture; auto.\n            rewrite EQ.\n            simpl_env in H.\n            apply wf_typ_typ_renaming_one' with (X:=X); auto.\n              apply contexting_regular in Hcontexting.\n              decompose [and] Hcontexting.\n              apply wf_env_strengthening in H6.\n              simpl_env in H6; auto.\n\n            apply binds_weaken.\n            apply binds_weaken.\n            apply binds_app_3.\n            apply binds_app_2. auto.\n\n            rewrite cv_ec_subst_tc_rec. auto.\n\n            rewrite <- subst_tt_fresh with (T:=T1'); auto.\n              apply notin_fv_wf with (E:=E2'0) (K:=kn_nonlin); auto.\n                apply wf_env_strengthening_tail in Wfe.\n                inversion Wfe; subst; auto.\n\n                apply uniq_from_wf_env in Wfe.\n                clear EQ1 Uniq J EQ IHHcontexting Hcontexting H0 yndom.\n                solve_uniq.\n\n            intros JJ.\n            apply H2 in JJ. subst. auto.\n\n      assert (E1'0++[(y, bind_typ T1')]++F++[(X, bind_kn K')]++E2' =\n                        (E1'0++[(y, bind_typ T1')]++F)++[(X, bind_kn K')]++E2') as J. \n        simpl_env. auto.\n      simpl in yndom. simpl_env in yndom. simpl_env. \n      unfold close_ec in yndom. rewrite cv_ec_close_ec_rec in yndom.\n      apply IHHcontexting with (E3:=E2) (E4:=E1) (K:=K0) in J; auto.\n        assert (env_remove (y, bind_typ (subst_tt X Y T1')) (map (subst_tb X Y)  E1'0++[(y, bind_typ (subst_tt X Y T1'))]++map (subst_tb X Y) F++[(Y, bind_kn K')]++E2') \n                          = map (subst_tb X Y) E1'0++map (subst_tb X Y) F++[(Y, bind_kn K')]++E2') as EQ.\n          apply env_remove_opt.\n            apply contexting_regular in J.\n            decompose [and] J.\n            apply uniq_from_wf_env in H6.\n            clear H3 H5 H4 H7 H9 J Uniq EQ1 Wfe IHHcontexting H0 H yndom H1.\n            rewrite map_app in H6.\n            rewrite map_app in H6.\n            simpl in H6. simpl_env in H6. auto.\n        rewrite <- EQ.\n        rewrite subst_tc_close_ec; auto.\n          simpl_env in J.\n          apply contexting_abs_capture; auto.\n            rewrite EQ.\n            rewrite_env ((map (subst_tb X Y) (E1'0 ++ F))++[(Y, bind_kn K')]++E2').\n            apply wf_typ_typ_renaming_one' with (X:=X); simpl_env; auto.\n              apply contexting_regular in Hcontexting.\n              decompose [and] Hcontexting.\n              apply wf_env_strengthening in H6.\n              simpl_env in H6; auto.\n\n            rewrite cv_ec_subst_tc_rec. auto.\n\n            intros JJ.\n            apply H2 in JJ. subst. auto.\n  Case \"contexting_labs_capture\".\n    assert (wf_lenv (E1'++[(X, bind_kn K')]++E2') D') as Wfle.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (J:=@lenv_remove_inv (E1'++[(X, bind_kn K')]++E2') D' y (lbind_typ T1') Wfle H0).\n    destruct J as [D1'0 [D2'0 [EQ1 EQ2]]]; subst.\n    simpl_env.\n    simpl_env in yndom. simpl in yndom.\n    unfold close_ec in yndom.\n    rewrite cv_ec_close_ec_rec in yndom.\n    rewrite subst_tc_close_ec; auto.\n      destruct (X == Y); subst.\n        repeat (rewrite subst_tb_id).\n        repeat (rewrite subst_tlb_id).\n        repeat (rewrite subst_tt_id).\n        repeat (rewrite subst_tc_id).\n        apply contexting_labs_capture; simpl; auto.\n\n        simpl_env in yndom.\n        rewrite EQ1 in yndom.\n        assert (uniq (D1'0 ++ [(y, lbind_typ T1')] ++ D2'0)) as UniqD. eauto.       \n        assert (Y `notin` union (fv_lenv (D1'0 ++ [(y, lbind_typ T1')] ++ D2'0)) (fv_tt T1')) as YnD.\n          apply notin_fv_wf with (X:=Y) in H; auto.\n          apply notin_fv_lenv_wfle with (X:=Y) in Wfle; auto.\n        rewrite map_lenv_remove; auto.\n        apply contexting_labs_capture; simpl; auto.\n          simpl_env.\n          apply wf_typ_typ_renaming_one' with (X:=X); simpl_env; auto.\n  \n          rewrite cv_ec_subst_tc_rec.\n          simpl_env in H1. simpl_env. simpl. \n          rewrite gdom_map. fsetdec.\n\n          simpl_env in yndom.\n          simpl_env.\n          rewrite_env (map (subst_tlb X Y) (D1'0 ++ [(y, lbind_typ T1')] ++ D2'0)).\n          apply IHHcontexting; auto.\n\n          intros JJ.\n          apply H2 in JJ. \n          rewrite_env (map (subst_tlb X Y) (D1'0 ++ [(y, lbind_typ T1')] ++ D2'0)).\n          rewrite lenv_remove_opt in JJ.\n            rewrite map_app. simpl. simpl_env. \n            rewrite lenv_remove_opt.\n              rewrite <- map_app.  rewrite JJ. auto.\n\n              apply uniq_map_2 with (f:=(subst_tlb X Y)) in UniqD.\n              rewrite map_app in UniqD. simpl in UniqD. simpl_env in UniqD. assumption.\n          assumption.\n  Case \"contexting_app1\".\n    simpl_env.\n    apply contexting_app1 with (D1':=map (subst_tlb X Y) D1') (D2':=map (subst_tlb X Y) D2') (T1':=subst_tt X Y T1') (K:=K); auto.\n      apply IHHcontexting; auto.\n        apply dom_lenv_split in H0.\n        rewrite H0 in yndom. auto.\n\n      apply dom_lenv_split in H0. rewrite H0 in yndom.\n      apply typing_typ_renaming_one with (X:=X); simpl_env; auto.\n\n      apply lenv_split_typ_renaming_one with (X:=X); simpl_env; auto.\n\n      apply disjdom_eq with (D1:=fv_ee e2).\n        apply disjdom_sym_1.\n        apply disjdom_eq with (D1:=dom D).\n          apply disjdom_sym_1; auto.\n          \n          assert (J:=@dom_map lbinding lbinding (subst_tlb X Y) D).\n          rewrite J. clear. fsetdec.\n        rewrite subst_te_fv_ee_eq. clear. fsetdec.\n  Case \"contexting_app2\".\n    simpl_env.\n    apply contexting_app2 with (D1':=map (subst_tlb X Y) D1') (D2':=map (subst_tlb X Y) D2') (T1':=subst_tt X Y T1') (K:=K); auto.\n      apply dom_lenv_split in H0. rewrite H0 in yndom.\n      assert (typ_arrow K (subst_tt X Y T1') (subst_tt X Y T2') = subst_tt X Y (typ_arrow K T1' T2')) as EQ. auto.\n      rewrite EQ.\n      apply typing_typ_renaming_one with (X:=X); simpl_env; auto.\n\n      apply IHHcontexting; auto.\n        apply dom_lenv_split in H0.\n        rewrite H0 in yndom. auto.\n\n      apply lenv_split_typ_renaming_one with (X:=X); simpl_env; auto.\n\n      apply disjdom_eq with (D1:=fv_ee e1).\n        apply disjdom_sym_1.\n        apply disjdom_eq with (D1:=dom D).\n          apply disjdom_sym_1; auto.\n          \n          assert (J:=@dom_map lbinding lbinding (subst_tlb X Y) D).\n          rewrite J. clear. fsetdec.\n        rewrite subst_te_fv_ee_eq. clear. fsetdec.\n  Case \"contexting_tabs_free\".\n    apply contexting_tabs_free with (L:=L `union` {{Y}}`union` {{X}}); simpl_env; auto.\n      simpl in yndom. simpl_env in H0. simpl_env. auto.\n\n      intros X0 Xn.\n      rewrite subst_tc_open_tc_var; auto.\n      apply vcontext_through_subst_tc; auto.\n\n      intros X0 X0n.\n      assert (X0 `notin` L) as J. auto.\n      apply H1 with (E1'0:=[(X0, bind_kn K)]++E1') (E2'0:=E2') (K1:=K0) (K'0:=K') (X1:=X) (E3:=E2) (E4:=E1) in J; auto.\n        simpl_env.\n        rewrite map_app in J.\n        simpl in J. simpl_env in J.\n        rewrite subst_tc_open_tc_var; auto.\n        rewrite subst_tt_open_tt_var; auto.\n\n        rewrite (@cv_ec_open_tc_rec C1 0 X0). simpl. simpl in yndom. auto.\n  Case \"contexting_tabs_capture\".\n    assert (wf_env E') as Wfe.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (J:=@env_remove_inv E' Y0 (bind_kn K) Wfe H).\n    destruct J as [E1'0 [E2'0 [EQ1 EQ2]]]; subst.\n    rewrite EQ1 in *.\n\n    assert (uniq (E1'0++E2'0)) as Uniq.\n      apply uniq_from_wf_env in Wfe.\n       solve_uniq.\n    apply app_mid_inv in HeqE'; auto.\n    destruct HeqE' as [[F [fEQ1 fEQ2]] | [F [fEQ1 fEQ2]]]; subst.\n      assert ((E1'++[(X, bind_kn K')]++F)++[(Y0, bind_kn K)]++E2'0 =\n                        E1'++[(X, bind_kn K')]++(F++[(Y0, bind_kn K)]++E2'0)) as J. \n        simpl_env. auto.\n      simpl in yndom. simpl_env in yndom. simpl_env. \n      unfold close_tc in yndom. rewrite cv_ec_close_tc_rec in yndom.\n      apply IHHcontexting with (E3:=E2) (E4:=E1) (K1:=K0) in J; auto.\n        assert (env_remove (Y0, bind_kn K) (map (subst_tb X Y) E1'++[(Y, bind_kn K')]++F++[(Y0, bind_kn K)]++E2'0) \n                          = map (subst_tb X Y) E1'++[(Y, bind_kn K')]++F++E2'0) as EQ.\n          rewrite_env ((map (subst_tb X Y) E1'++[(Y, bind_kn K')]++F)++[(Y0, bind_kn K)]++E2'0).\n          rewrite_env ((map (subst_tb X Y) E1'++[(Y, bind_kn K')]++F)++E2'0).\n          apply env_remove_opt.\n            apply contexting_regular in J.\n            decompose [and] J; auto.\n            apply uniq_from_wf_env in H6.\n            clear - H6.\n            rewrite_env ((map (subst_tb X Y) E1'++[(Y, bind_kn K')]++F)++[(Y0, bind_kn K)]++E2'0) in H6.\n            apply uniq_insert_mid; auto.     \n              apply uniq_remove_mid in H6; auto.\n              solve_uniq.\n              solve_uniq.\n        rewrite <- EQ.\n        assert (X <> Y0) as XnY0.\n          apply uniq_from_wf_env in Wfe.\n          apply fresh_mid_head in Wfe.\n          simpl_env in Wfe.\n          auto.\n        rewrite subst_tc_close_tc; auto.\n        rewrite subst_tt_close_tt; auto.\n          apply contexting_tabs_capture; auto.\n            apply binds_weaken.\n            apply binds_weaken.\n            apply binds_app_3.\n            apply binds_app_2. auto.\n\n             rewrite cv_ec_subst_tc_rec. auto.\n\n             apply vcontext_through_subst_tc; auto.\n\n             rewrite EQ.\n             simpl_env in H2.\n             apply wf_lenv_typ_renaming_one with (X:=X); auto.\n\n      assert (E1'0++[(Y0, bind_kn K)]++F++[(X, bind_kn K')]++E2' =\n                        (E1'0++[(Y0, bind_kn K)]++F)++[(X, bind_kn K')]++E2') as J. \n        simpl_env. auto.\n      simpl in yndom. simpl_env in yndom. simpl_env. \n      unfold close_tc in yndom. rewrite cv_ec_close_tc_rec in yndom.\n      apply IHHcontexting with (E3:=E2) (E4:=E1) (K1:=K0) in J; auto.\n        assert (env_remove (Y0, bind_kn K) (map (subst_tb X Y)  E1'0++[(Y0, bind_kn K)]++map (subst_tb X Y) F++[(Y, bind_kn K')]++E2') \n                          = map (subst_tb X Y) E1'0++map (subst_tb X Y) F++[(Y, bind_kn K')]++E2') as EQ.\n          apply env_remove_opt.\n            apply contexting_regular in J.\n            decompose [and] J.\n            apply uniq_from_wf_env in H6.\n            clear - H6.\n            rewrite map_app in H6.\n            rewrite map_app in H6.\n            simpl in H6. simpl_env in H6. auto.\n        rewrite <- EQ.\n        assert (X <> Y0) as XnY0.\n          apply uniq_from_wf_env in Wfe.\n          apply fresh_mid_tail in Wfe.\n          simpl_env in Wfe.\n          auto.\n        rewrite subst_tc_close_tc; auto.\n        rewrite subst_tt_close_tt; auto.\n          simpl_env in J.\n          apply contexting_tabs_capture; auto.\n            rewrite cv_ec_subst_tc_rec. auto.\n\n            apply vcontext_through_subst_tc; auto.\n\n            rewrite EQ.\n            rewrite_env (map (subst_tb X Y) (E1'0++F)++[(Y, bind_kn K')]++E2').\n            apply wf_lenv_typ_renaming_one with (X:=X); simpl_env; auto.\n\n  Case \"contexting_tapp\".\n    simpl_env.\n    rewrite subst_tt_open_tt; auto.\n    apply contexting_tapp with (K:=K); auto.\n      assert (subst_tt X Y (typ_all K T2') = typ_all K (subst_tt X Y T2')) as EQ. auto.\n      rewrite <- EQ.\n      auto.\n\n      apply wf_typ_typ_renaming_one' with (X:=X); simpl_env; auto.\n        apply contexting_regular in Hcontexting. \n        decompose [and] Hcontexting; auto.\n  Case \"contexting_apair1\".\n    simpl_env.\n    apply contexting_apair1 with (T1':=subst_tt X Y T1'); auto.\n      apply typing_typ_renaming_one with (X:=X); simpl_env; auto.\n  Case \"contexting_apair2\".\n    simpl_env.\n    apply contexting_apair2 with (T1':=subst_tt X Y T1'); auto.\n      apply typing_typ_renaming_one with (X:=X); simpl_env; auto.\n  Case \"contexting_fst\".\n    simpl_env.\n    apply contexting_fst with (T2':=subst_tt X Y T2'); auto.\n      assert (subst_tt X Y (typ_with T1' T2') = typ_with (subst_tt X Y T1') (subst_tt X Y T2')) as EQ. auto.\n      rewrite <- EQ.\n      auto.\n  Case \"contexting_snd\".\n    simpl_env.\n    apply contexting_snd with (T1':=subst_tt X Y T1'); auto.\n      assert (subst_tt X Y (typ_with T1' T2') = typ_with (subst_tt X Y T1') (subst_tt X Y T2')) as EQ. auto.\n      rewrite <- EQ.\n      auto.\nQed.\n\nExport Parametricity.\n\nDefinition F_logical_related E lE e e' t : Prop :=\n  typing E lE e t /\\\n  typing E lE e' t /\\\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n   F_related_subst E lE gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n   F_Rsubst E rsubst dsubst dsubst'->\n   F_related_terms t rsubst dsubst dsubst'\n                                 (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n                                 (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e'))).\n\n\nLemma F_logical_related_congruence__abs_free :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n   F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n   F_Rsubst E rsubst dsubst dsubst'->\n   F_related_terms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n  ) ->\n  forall L K T1' C1 T2' E' D',\n  wf_typ E' T1' kn_nonlin ->\n  (forall x,\n    x `notin` L ->\n    contexting E D T (open_ec C1 x) ((x, bind_typ T1')::E') D' T2'\n  ) ->\n  (forall x,\n    x `notin` L ->\n   typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E rsubst dsubst dsubst' ->\n     F_related_terms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst ((x, bind_typ T1')::E') D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst ((x, bind_typ T1')::E') rsubst dsubst dsubst' ->\n     F_related_terms T2' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug (open_ec C1 x) e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug (open_ec C1 x) e'))))\n  ) ->\n  (K = kn_nonlin -> D' = lempty) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n  F_related_subst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n  F_Rsubst E' rsubst dsubst dsubst'  ->\n  F_related_terms (typ_arrow K T1' T2') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug C1 (shift_ee e))))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug C1 (shift_ee e')))))).\nProof.\n    intros e e' E D T Htyp Htyp' Hlr L K T1' C1 T2' E' D' H H1 H2 H3 dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Hrel_sub HRsub.\n    assert (J:=Hrel_sub). apply F_related_subst__inversion in J. \n    destruct J as [[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe].\n\n    rename H into WFTV.\n    \n    assert (value (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug C1 (shift_ee e))))))) as Value.\n      apply delta_gamma_lgamma_subst_value with (E:=E') (D:=D'); auto.\n        apply FrTyping__absvalue with (L:=L  `union` cv_ec C1) (E:=E') (D:=D') (T1:=T2') (K:=kn_nonlin); auto.\n          intros x xn.\n          assert (x `notin` L) as xnFv. auto.\n          apply H1 in xnFv.\n          apply contexting_plug_typing with (e:=e) in xnFv; auto.\n          simpl_env in xnFv.\n          rewrite open_ee_expr with (e:=e) (u:=x) in xnFv; auto.\n          assert (disjdom ((fv_ee x) `union` (fv_te x)) (cv_ec C1)) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite <- open_ee_plug in xnFv; auto. \n          rewrite shift_ee_expr with (e:=e) in xnFv; auto.\n    assert (value (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug C1 (shift_ee e'))))))) as Value'.\n      apply delta_gamma_lgamma_subst_value with (E:=E') (D:=D'); auto.\n        apply FrTyping__absvalue with (L:=L  `union` cv_ec C1) (E:=E') (D:=D') (T1:=T2') (K:=kn_nonlin); auto.\n          intros x xn.\n          assert (x `notin` L) as xnFv. auto.\n          apply H1 in xnFv.\n          apply contexting_plug_typing with (e:=e') in xnFv; auto.\n          simpl_env in xnFv.\n          rewrite open_ee_expr with (e:=e') (u:=x) in xnFv; auto.\n          assert (disjdom ((fv_ee x) `union` (fv_te x)) (cv_ec C1)) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite <- open_ee_plug in xnFv; auto. \n          rewrite shift_ee_expr with (e:=e') in xnFv; auto.\n    exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug C1 (shift_ee e)))))).\n    exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug C1 (shift_ee e')))))).\n    split.\n      assert (typing E' D' (plug (ctx_abs_free K T1' C1) e) (typ_arrow K T1' T2')) as Hptyp.\n        apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n           apply contexting_abs_free with (L:=L); auto.\n      apply typing_subst with (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst) in Hptyp; auto.\n    split. \n      assert (typing E' D' (plug (ctx_abs_free K T1' C1) e') (typ_arrow K T1' T2')) as Hptyp'.\n        apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n           apply contexting_abs_free with (L:=L); auto.\n      apply typing_subst with (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst') in Hptyp'; auto.\n    split. split; auto.\n    split. split; auto.\n      SCase \"Frel\".\n      apply F_related_values_arrow_req.\n      split; auto.\n      split; auto.\n      SSCase \"arrow\".\n        intros x x' Htyping Htyping' Harrow_left.\n        pick fresh z.\n        assert (z `notin` L) as Fry. auto.\n        assert (wf_typ ([(z, bind_typ T1')]++E') T2' kn_lin) as WFT'. \n          apply H1 in Fry.\n          apply contexting_regular in Fry.\n          decompose [and] Fry; auto.\n        assert (F_related_subst ([(z, bind_typ T1')]++E') D' ([(z,x)]++gsubst) ([(z,x')]++gsubst') lgsubst lgsubst' rsubst dsubst dsubst') as Hrel_sub'.           \n          apply F_related_subst_typ; auto.\n        assert (F_Rsubst ([(z, bind_typ T1')]++E') rsubst dsubst dsubst') as HRsub'. \n          apply F_Rsubst_typ; auto.\n        apply H2 with (dsubst:=dsubst) (gsubst:=[(z,x)]++gsubst) (lgsubst:=lgsubst) (dsubst':=dsubst') (gsubst':=[(z,x')]++gsubst') (lgsubst':=lgsubst') (rsubst:=rsubst) in Fry; auto.\n        simpl_env in Fry.\n        assert (\n            apply_delta_subst dsubst (apply_gamma_subst ([(z,x)]++gsubst) (apply_gamma_subst lgsubst (plug (open_ec C1 z) e))) =\n            apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (subst_ee z x (plug (open_ec C1 z) e))))\n                  ) as Heq1. simpl. \n           rewrite swap_subst_ee_lgsubst with (E:=E')(D:=D')(dsubst:=dsubst)(lgsubst:=lgsubst)(gsubst:=gsubst)(t:=apply_delta_subst_typ dsubst T1'); auto.\n             apply wf_lgamma_subst__nfv with (x:=z) in Hwflg; auto.\n         assert (\n            apply_delta_subst dsubst' (apply_gamma_subst ([(z,x')]++gsubst') (apply_gamma_subst lgsubst' (plug (open_ec C1 z) e'))) =\n            apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (subst_ee z x' (plug (open_ec C1 z) e'))))\n                  ) as Heq2.  simpl.\n           rewrite swap_subst_ee_lgsubst with (E:=E')(D:=D')(dsubst:=dsubst')(lgsubst:=lgsubst')(gsubst:=gsubst')(t:=apply_delta_subst_typ dsubst' T1'); auto.\n             apply wf_lgamma_subst__nfv with (x:=z) in Hwflg'; auto.\n         rewrite Heq1 in Fry. rewrite Heq2 in Fry. clear Heq1 Heq2.\n         destruct Fry as [v [v' [Ht [Ht' [[Hbrc Hv] [[Hbrc' Hv'] Hrel]]]]]].\n         exists (v). exists (v').\n         split.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst dsubst (apply_gamma_subst gsubst  (apply_gamma_subst lgsubst (subst_ee z x (plug (open_ec C1 z) e)))))); auto.\n              rewrite <- shift_ee_expr; auto.\n             assert (plug (open_ec C1 z) e = open_ee (plug C1 e) z) as EQ.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n                eapply disjdom_app_l.\n                split.\n                  apply disjdom_one_2; auto.\n                  simpl. apply disjdom_nil_1.\n             rewrite EQ.\n             eapply m_red_abs_subst with (T1:=T2') (L:=L `union` cv_ec C1); eauto.\n               apply F_related_values_inversion in Harrow_left.\n               decompose [prod] Harrow_left; auto.\n\n               assert (typing E' D' (plug (ctx_abs_free K T1' C1) e) (typ_arrow K T1' T2')) as Hptyp.\n                 apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n                   apply contexting_abs_free with (L:=L); auto.\n               apply notin_fv_ee_typing with (y:=z) in Hptyp; auto.\n               simpl in Hptyp.\n               rewrite <- shift_ee_expr in Hptyp; auto.\n\n               intros x0 x0dom.\n               assert (x0 `notin` L) as x0n. auto.\n               apply H1 in x0n.\n               assert (disjdom ((fv_ee x0) `union` fv_te x0) (cv_ec C1)) as Disj.\n                 eapply disjdom_app_l.\n                 split.\n                   apply disjdom_one_2; auto.\n                   simpl. apply disjdom_nil_1.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n               apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.       \n         split; auto.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (subst_ee z x' (plug (open_ec C1 z) e')))))); auto.\n              rewrite <- shift_ee_expr; auto.\n             assert (plug (open_ec C1 z) e' = open_ee (plug C1 e') z) as EQ.\n               assert (disjdom (fv_ee z `union` fv_te z) (cv_ec C1)) as Disj.\n                 eapply disjdom_app_l.\n                 split.\n                   apply disjdom_one_2; auto.\n                   simpl. apply disjdom_nil_1.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n             rewrite EQ.\n             eapply m_red_abs_subst with (T1:=T2') (L:=L `union` cv_ec C1); eauto.\n               apply F_related_values_inversion in Harrow_left.\n               decompose [prod] Harrow_left; auto.\n\n               assert (typing E' D' (plug (ctx_abs_free K T1' C1) e') (typ_arrow K T1' T2')) as Hptyp.\n                 apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n                   apply contexting_abs_free with (L:=L); auto.\n               apply notin_fv_ee_typing with (y:=z) in Hptyp; auto.\n               simpl in Hptyp.\n               rewrite <- shift_ee_expr in Hptyp; auto.\n\n               intros x0 x0dom.\n               assert (x0 `notin` L) as x0n. auto.\n               apply H1 in x0n.\n               assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec C1)) as Disj.\n                 eapply disjdom_app_l.\n                 split.\n                   apply disjdom_one_2; auto.\n                   simpl. apply disjdom_nil_1.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n               apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.       \nQed.\n\nLemma F_logical_related_congruence__labs_free :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n   F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n   F_Rsubst E rsubst dsubst dsubst' ->\n   F_related_terms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n  ) ->\n  forall L K T1' C1 T2' E' D',\n  wf_typ E' T1' kn_lin ->\n  (forall x,\n    x `notin` L ->\n    contexting E D T (open_ec C1 x) E' ((x, lbind_typ T1')::D') T2'\n  ) ->\n  (forall x,\n    x `notin` L ->\n   typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E rsubst dsubst dsubst' ->\n     F_related_terms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E' ((x, lbind_typ T1')::D') gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E' rsubst dsubst dsubst' ->\n     F_related_terms T2' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug (open_ec C1 x) e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug (open_ec C1 x) e'))))\n  ) ->\n  (K = kn_nonlin -> D' = lempty) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n  F_related_subst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n  F_Rsubst E' rsubst dsubst dsubst' ->\n  F_related_terms (typ_arrow K T1' T2') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug C1 (shift_ee e))))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug C1 (shift_ee e')))))).\nProof.\n    intros e e' E D T Htyp Htyp' Hlr L K T1' C1 T2' E' D' H H1 H2 H3 dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Hrel_sub HRsub.\n    assert (J:=Hrel_sub). apply F_related_subst__inversion in J. \n    destruct J as [[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe].\n\n    rename H into WFTV.\n\n    assert (value (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug C1 (shift_ee e))))))) as Value.\n      apply delta_gamma_lgamma_subst_value with (E:=E') (D:=D'); auto.\n        apply FrTyping__labsvalue with (L:=L  `union` cv_ec C1) (E:=E') (D:=D') (T1:=T2') (K:=kn_lin); auto.\n          intros x xn.\n          assert (x `notin` L) as xnFv. auto.\n          apply H1 in xnFv.\n          apply contexting_plug_typing with (e:=e) in xnFv; auto.\n          simpl_env in xnFv.\n          rewrite open_ee_expr with (e:=e) (u:=x) in xnFv; auto.\n          assert (disjdom (fv_ee x `union` fv_te x) (cv_ec C1)) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite <- open_ee_plug in xnFv; auto. \n          rewrite shift_ee_expr with (e:=e) in xnFv; auto.\n    assert (value (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug C1 (shift_ee e'))))))) as Value'.\n      apply delta_gamma_lgamma_subst_value with (E:=E') (D:=D'); auto.\n        apply FrTyping__labsvalue with (L:=L  `union` cv_ec C1) (E:=E') (D:=D') (T1:=T2') (K:=kn_lin); auto.\n          intros x xn.\n          assert (x `notin` L) as xnFv. auto.\n          apply H1 in xnFv.\n          apply contexting_plug_typing with (e:=e') in xnFv; auto.\n          simpl_env in xnFv.\n          rewrite open_ee_expr with (e:=e') (u:=x) in xnFv; auto.\n          assert (disjdom (fv_ee x `union` fv_te x) (cv_ec C1)) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite <- open_ee_plug in xnFv; auto. \n          rewrite shift_ee_expr with (e:=e') in xnFv; auto.\n    \n    exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug C1 (shift_ee e)))))).\n    exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug C1 (shift_ee e')))))).\n    split.\n      assert (typing E' D' (plug (ctx_abs_free K T1' C1) e) (typ_arrow K T1' T2')) as Hptyp.\n        apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n           apply contexting_labs_free with (L:=L); auto.\n      apply typing_subst with (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst) in Hptyp; auto.\n    split.\n      assert (typing E' D' (plug (ctx_abs_free K T1' C1) e') (typ_arrow K T1' T2')) as Hptyp'.\n        apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n           apply contexting_labs_free with (L:=L); auto.\n      apply typing_subst with (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst') in Hptyp'; auto.\n    split. split; auto.\n    split. split; auto.\n      SCase \"Frel\".\n      apply F_related_values_arrow_req.\n      split; auto.\n      split; auto.\n      SSCase \"arrow\".\n        intros x x' Htyping Htyping' Harrow_left.\n        pick fresh z.\n        assert (z `notin` L) as Fry. auto.\n        assert (wf_typ E' T2' kn_lin) as WFT'. \n          apply H1 in Fry.\n          apply contexting_regular in Fry.\n          decompose [and] Fry; auto.\n        assert (F_related_subst E' ([(z, lbind_typ T1')]++D') gsubst gsubst' ([(z,x)]++lgsubst) ([(z,x')]++lgsubst') rsubst dsubst dsubst') as Hrel_sub'.        \n          apply F_related_subst_ltyp; auto.\n        apply H2 with (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=[(z,x)]++lgsubst) (dsubst':=dsubst') (gsubst':=gsubst') (lgsubst':=[(z,x')]++lgsubst') (rsubst:=rsubst) in Fry; auto.\n        simpl_env in Fry.\n        assert (\n            apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst ([(z,x)]++lgsubst) (plug (open_ec C1 z) e))) =\n            apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (subst_ee z x (plug (open_ec C1 z) e))))\n                  ) as Heq1. simpl. reflexivity.\n         assert (\n            apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst ([(z,x')]++lgsubst') (plug (open_ec C1 z) e'))) =\n            apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (subst_ee z x' (plug (open_ec C1 z) e'))))\n                  ) as Heq2.  simpl. reflexivity.\n         rewrite Heq1 in Fry. rewrite Heq2 in Fry. clear Heq1 Heq2.\n         destruct Fry as [v [v' [Ht [Ht' [[Hbrc Hv] [[Hbrc' Hv'] Hrel]]]]]].\n         exists (v). exists (v').\n         split.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst dsubst (apply_gamma_subst gsubst  (apply_gamma_subst lgsubst (subst_ee z x (plug (open_ec C1 z) e)))))); auto.\n              rewrite <- shift_ee_expr; auto.\n             assert (plug (open_ec C1 z) e = open_ee (plug C1 e) z) as EQ.\n              assert (disjdom (fv_ee z `union` fv_te z) (cv_ec C1)) as Disj.\n                eapply disjdom_app_l.\n                split.\n                  apply disjdom_one_2; auto.\n                  simpl. apply disjdom_nil_1.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n             rewrite EQ.\n             eapply m_red_labs_subst with (T1:=T2') (L:=L `union` cv_ec C1); eauto.\n               apply F_related_values_inversion in Harrow_left.\n               decompose [prod] Harrow_left; auto.\n\n               assert (typing E' D' (plug (ctx_abs_free K T1' C1) e) (typ_arrow K T1' T2')) as Hptyp.\n                 apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n                   apply contexting_labs_free with (L:=L); auto.\n               apply notin_fv_ee_typing with (y:=z) in Hptyp; auto.\n               simpl in Hptyp.\n               rewrite <- shift_ee_expr in Hptyp; auto.\n\n               intros x0 x0dom.\n               assert (x0 `notin` L) as x0n. auto.\n               apply H1 in x0n.\n               assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec C1)) as Disj.\n                 eapply disjdom_app_l.\n                 split.\n                   apply disjdom_one_2; auto.\n                   simpl. apply disjdom_nil_1.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n               apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.       \n         split; auto.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (subst_ee z x' (plug (open_ec C1 z) e')))))); auto.\n              rewrite <- shift_ee_expr; auto.\n             assert (plug (open_ec C1 z) e' = open_ee (plug C1 e') z) as EQ.\n               assert (disjdom (fv_ee z `union` fv_te z) (cv_ec C1)) as Disj.\n                 eapply disjdom_app_l.\n                 split.\n                   apply disjdom_one_2; auto.\n                   simpl. apply disjdom_nil_1.\n               rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n             rewrite EQ.\n             eapply m_red_labs_subst with (T1:=T2') (L:=L `union` cv_ec C1); eauto.\n               apply F_related_values_inversion in Harrow_left.\n               decompose [prod] Harrow_left; auto.\n\n               assert (typing E' D' (plug (ctx_abs_free K T1' C1) e') (typ_arrow K T1' T2')) as Hptyp.\n                 apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n                   apply contexting_labs_free with (L:=L); auto.\n               apply notin_fv_ee_typing with (y:=z) in Hptyp; auto.\n               simpl in Hptyp.\n               rewrite <- shift_ee_expr in Hptyp; auto.\n\n               intros x0 x0dom.\n               assert (x0 `notin` L) as x0n. auto.\n               apply H1 in x0n.\n               assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec C1)) as Disj.\n                 eapply disjdom_app_l.\n                 split.\n                   apply disjdom_one_2; auto.\n                   simpl. apply disjdom_nil_1.\n             rewrite open_ee_plug; auto.\n               rewrite <- open_ee_expr; auto.\n               apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.       \nQed.\n\nLemma F_logical_related_congruence__abs_capture :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n   F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n   F_Rsubst E rsubst dsubst dsubst' ->\n   F_related_terms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n  ) ->\n  forall K y T1' C1 T2' E' D',\n  wf_typ (env_remove (y, bind_typ T1') E') T1' kn_nonlin ->\n  binds y (bind_typ T1') E' ->\n  y `notin` dom D `union` cv_ec C1 ->\n  contexting E D T C1 E' D' T2' ->\n  (K = kn_nonlin -> D' = lempty) ->\n  (typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E rsubst dsubst dsubst' ->\n     F_related_terms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E' rsubst dsubst dsubst' ->\n     F_related_terms T2' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n  F_related_subst (env_remove (y, bind_typ T1') E') D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n  F_Rsubst (env_remove (y, bind_typ T1') E') rsubst dsubst dsubst' ->\n  F_related_terms (typ_arrow K T1' T2') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e) y))))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e') y)))))).\nProof.\n    intros e e' E D T Htyp Htyp' Hlr K y T1' C1 T2' E' D' H H0 H1 Hcontexting H2 IHHcontexting dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Hrel_sub HRsub. \n    assert (J:=Hrel_sub). apply F_related_subst__inversion in J. \n    destruct J as [[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe].\n\n    rename H into WFTV.\n    \n    assert (wf_typ E' T2' kn_lin) as WFT'. \n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (Fry := @IHHcontexting Htyp Htyp' Hlr).\n    assert (wf_env E') as Wfe'.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (EQ1:=@env_remove_typ_inv E' y T1'  Wfe' H0).\n    destruct EQ1 as [E1' [E2' [EQ1' [EQ2' Sub]]]]; subst.\n    rewrite EQ1' in *.\n\n    assert (EQ:=Hwflg).\n    apply wf_lgsubst_app_inv in EQ.\n    destruct EQ as [dsubst1 [dsubst2 [gsubst1 [gsubst2 [dEQ1 [dEQ2 [dEQ3 [gEQ1 [gEQ2 gEQ3]]]]]]]]]; subst.\n\n    assert (EQ:=Hwflg').\n    apply wf_lgsubst_app_inv in EQ.\n    destruct EQ as [dsubst1' [dsubst2' [gsubst1' [gsubst2' [dEQ1' [dEQ2' [dEQ3' [gEQ1' [gEQ2' gEQ3']]]]]]]]]; subst.\n       \n    assert (EQ:=Hwfr).\n    apply wf_rsubst_app_inv in EQ.\n    destruct EQ as [rsubst1 [rsubst2 [rEQ1 [rEQ2 rEQ3]]]]; subst.\n\n    assert (wf_typ E2' T1' kn_nonlin) as WFTV'.\n    apply wft_strengthen_sub with (F:=E1'); auto.\n\n    assert (value (apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e) y))))))) as Value.\n      apply delta_gamma_lgamma_subst_value with (E:=E1'++E2') (D:=D'); auto.\n        apply FrTyping__absvalue with (L:=dom (E1'++E2') `union` dom D' `union` cv_ec (close_ec C1 y) `union` cv_ec C1) (E:=E1'++E2') (D:=D') (T1:=T2') (K:=kn_nonlin); auto.\n          intros x xnFv.\n          rewrite <- shift_ee_expr with (e:=e); auto.\n          assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite open_ee_plug; auto. \n          rewrite close_open_ee__subst_ee; auto.\n          assert (context C1) as Ctx1.\n            apply contexting__context in Hcontexting; auto.\n          rewrite close_open_ec__subst_ec; auto.\n          assert (disjdom (union {{y}} (fv_ee x `union` fv_te x)) (cv_ec C1)) as Disj'.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n            eapply disjdom_app_l.\n            split.\n               apply disjdom_one_2; auto.\n               simpl. apply disjdom_nil_1.\n          rewrite <- subst_ee_plug; auto. \n          assert (typing (E1'++[(y, bind_typ T1')]++E2') D' (plug C1 e) T2') as Htyp2.\n            apply contexting_plug_typing with (e:=e) in Hcontexting; auto.\n\n          apply typing_nonlin_renaming_permute with (x:=y); auto.\n    assert (value (apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (exp_abs K T1' (plug (close_ec C1 y)  (close_ee (shift_ee e') y))))))) as Value'.\n      apply delta_gamma_lgamma_subst_value with (E:=E1'++E2') (D:=D'); auto.\n        apply FrTyping__absvalue with (L:=dom (E1'++E2') `union` dom D' `union` cv_ec (close_ec C1 y) `union` cv_ec C1) (E:=E1'++E2') (D:=D') (T1:=T2') (K:=kn_nonlin); auto.\n          intros x xnFv.\n          rewrite <- shift_ee_expr with (e:=e'); auto.\n          assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite open_ee_plug; auto. \n          rewrite close_open_ee__subst_ee; auto.\n          assert (context C1) as Ctx1.\n            apply contexting__context in Hcontexting; auto.\n          rewrite close_open_ec__subst_ec; auto.\n          assert (disjdom (union {{y}} (fv_ee x `union` fv_te x)) (cv_ec C1)) as Disj'.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite <- subst_ee_plug; auto. \n          assert (typing (E1'++[(y, bind_typ T1')]++E2') D' (plug C1 e') T2') as Htyp2'.\n            apply contexting_plug_typing with (e:=e') in Hcontexting; auto.\n          apply typing_nonlin_renaming_permute with (x:=y); auto.\n    exists (apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e) y)))))).\n    exists (apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e') y)))))).\n    split.\n      assert (typing (E1'++E2') D' (plug (ctx_abs_capture K y T1' (close_ec C1 y)) e) (typ_arrow K T1' T2')) as Hptyp.\n        destruct (in_dec y (fv_ee e)) as [yine | ynine].\n          simpl.\n          apply typing_abs with (L:=dom (E1'++E2') `union` dom D' `union` dom E `union` dom D `union` {{y}} `union` cv_ec C1 `union` cv_ec (close_ec C1 y)); auto.\n            intros x xn.\n            rewrite <- shift_ee_expr; auto.\n            assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n              eapply disjdom_app_l.\n              split.\n                apply disjdom_one_2; auto.\n                simpl. apply disjdom_nil_1.\n            rewrite open_ee_plug; auto.\n            assert (y `in` gdom_env E \\/ y `in` dom D) as yED.\n              assert (y `in` gdom_env E `union` dom D) as J.\n                apply in_fv_ee_typing' with (x:=y) in Htyp; auto.\n              fsetdec.\n            rewrite close_open_ee__subst_ee; auto.\n            assert (context C1) as Ctx1.\n              apply contexting__context in Hcontexting; auto.\n            rewrite close_open_ec__subst_ec; auto.\n            destruct yED as [yE | yD].\n              apply gbinds_In_inv in yE.\n              destruct yE as [t Binds].\n              assert (wf_env E) as Wfe. auto.\n              assert (J:=@env_remove_inv E y (bind_typ t) Wfe Binds).\n              destruct J as [E1 [E2 [EQ1 EQ2]]]; subst.\n\n              apply typing_nonlin_permute; auto. \n              apply contexting_plug_typing with (E:=E1++[(x, bind_typ t)]++E2) (D:=D) (T:=T); auto.\n\n                apply contexting_nonlin_renaming_one; auto.\n\n                simpl_env in xn.\n                apply typing_nonlin_renaming_one with (x:=y); auto.\n\n              contradict yD; auto.\n          rewrite <- EQ1'.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n            apply contexting_abs_capture; auto.\n              rewrite EQ1'. auto.\n      apply typing_subst with (dsubst:=dsubst1++dsubst2) (gsubst:=gsubst1++gsubst2) (lgsubst:=lgsubst) in Hptyp; auto.\n    split.\n      assert (typing (E1'++E2') D' (plug (ctx_abs_capture K y T1' (close_ec C1 y)) e') (typ_arrow K T1' T2')) as Hptyp'.\n        destruct (in_dec y (fv_ee e')) as [yine | ynine'].\n          simpl.\n          apply typing_abs with (L:=dom (E1'++E2') `union` dom D' `union` dom E `union` dom D `union` cv_ec C1 `union` cv_ec (close_ec C1 y)); auto.\n            intros x xn.\n            rewrite <- shift_ee_expr; auto.\n            assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n              eapply disjdom_app_l.\n              split.\n                apply disjdom_one_2; auto.\n                simpl. apply disjdom_nil_1.\n            rewrite open_ee_plug; auto.\n            assert (y `in` gdom_env E \\/ y `in` dom D) as yED.\n              assert (y `in` gdom_env E `union` dom D) as J.\n                apply in_fv_ee_typing' with (x:=y) in Htyp'; auto.\n              fsetdec.\n            rewrite close_open_ee__subst_ee; auto.\n            assert (context C1) as Ctx1.\n              apply contexting__context in Hcontexting; auto.\n            rewrite close_open_ec__subst_ec; auto.\n            destruct yED as [yE | yD].\n              apply gbinds_In_inv in yE.\n              destruct yE as [t Binds].\n              assert (wf_env E) as Wfe. auto.\n              assert (J:=@env_remove_inv E y (bind_typ t) Wfe Binds).\n              destruct J as [E1 [E2 [EQ1 EQ2]]]; subst.\n              apply typing_nonlin_permute; auto. \n              apply contexting_plug_typing with (E:=E1++[(x, bind_typ t)]++E2) (D:=D) (T:=T); auto.\n                apply contexting_nonlin_renaming_one; auto.\n\n                simpl_env in xn.\n                apply typing_nonlin_renaming_one with (x:=y); auto.\n\n              contradict yD; auto.\n          rewrite <- EQ1'.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n            apply contexting_abs_capture; auto.\n              rewrite EQ1'. auto.\n      apply typing_subst with (dsubst:=dsubst1'++dsubst2') (gsubst:=gsubst1'++gsubst2') (lgsubst:=lgsubst') in Hptyp'; auto.\n    split. split; auto.\n    split. split; auto.\n      SCase \"Frel\".\n      apply F_related_values_arrow_req.\n      split; auto.\n      split; auto.\n      SSCase \"arrow\".\n        intros x x' Htyping Htyping' Harrow_left.\n\n        assert (F_related_values T1' rsubst2 dsubst2 dsubst2' x x') as Harrow_left'.\n          apply Frel_stronger_heads with (E:=E2') (E':=E1') in Harrow_left; auto.       \n        assert (F_related_subst (E1'++[(y, bind_typ T1')]++E2') D' (gsubst1++[(y,x)]++gsubst2) (gsubst1'++[(y,x')]++gsubst2') lgsubst lgsubst' (rsubst1++rsubst2) (dsubst1++dsubst2) (dsubst1'++dsubst2')) as Hrel_sub'.\n          apply F_related_subst_gweaken; auto.\n             assert (y `notin` dom E1') as ynE1'.\n                apply fresh_mid_head with (E:=E2') (a:=bind_typ T1'); auto.\n             assert (y `notin` dom E2') as ynE2'.\n                apply fresh_mid_tail with (F:=E1') (a:=bind_typ T1'); auto.\n             assert (y `notin` dom D') as ynD'.\n               apply contexting_regular in Hcontexting.\n               decompose [and] Hcontexting.\n               apply wf_lenv_notin_fv_lenv with (x:=y) (T:=T1') in H6; auto.\n             auto.\n\n             rewrite apply_delta_subst_typ_strenghen with (E1:=E1') (E2:=E2') in Htyping; auto.\n             rewrite apply_delta_subst_typ_strenghen with (E1:=E1') (E2:=E2') in Htyping'; auto.\n\n        assert (F_Rsubst (E1'++[(y, bind_typ T1')] ++E2') (rsubst1++rsubst2) (dsubst1++dsubst2) (dsubst1'++dsubst2')) as HRsub'. \n          apply F_Rsubst_gweaken; auto.       \n             assert (y `notin` dom E1') as ynE1'.\n                apply fresh_mid_head with (E:=E2') (a:=bind_typ T1'); auto.\n             assert (y `notin` dom E2') as ynE2'.\n                apply fresh_mid_tail with (F:=E1') (a:=bind_typ T1'); auto.\n             auto.\n        assert (J:=@Fry (dsubst1++dsubst2) (dsubst1'++dsubst2') (gsubst1++[(y,x)]++gsubst2) (gsubst1'++[(y,x')]++gsubst2') lgsubst lgsubst' (rsubst1++rsubst2) Hrel_sub' HRsub').\n        assert (\n            apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++[(y,x)]++gsubst2) (apply_gamma_subst lgsubst (plug C1 e))) =\n            apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (subst_ee y x (plug C1 e))))\n                  ) as Heq1. simpl.\n           simpl_env.\n           rewrite gamma_subst_opt with (E':=E1') (E:=E2') (D:=D') (dsubst:=dsubst1++dsubst2) (t:=T1') (lgsubst:=lgsubst); auto.\n             rewrite swap_subst_ee_lgsubst with  (D:=D') (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (t:=apply_delta_subst_typ (dsubst1++dsubst2) T1') (gsubst:=gsubst1++gsubst2); auto.\n                apply contexting_regular in Hcontexting.\n                decompose [and] Hcontexting.\n                assert (y `notin` dom (E1'++E2')) as ynE'.\n                  apply uniq_from_wf_env in H5.\n                  simpl_env. solve_uniq.\n                assert (y `notin` dom D') as ynD'.\n                  apply wf_lenv_notin_fv_lenv with (x:=y) (T:=T1') in H6; auto.\n                apply wf_lgamma_subst__nfv with (x:=y) in Hwflg; auto.\n             apply F_related_subst__inversion in Hrel_sub'.\n             decompose [prod] Hrel_sub'; auto.\n         assert (\n            apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++[(y,x')]++gsubst2') (apply_gamma_subst lgsubst' (plug C1 e'))) =\n            apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (subst_ee y x' (plug C1 e'))))\n                  ) as Heq2.  simpl.\n           simpl_env.\n           rewrite gamma_subst_opt with (E':=E1') (E:=E2') (D:=D') (dsubst:=dsubst1'++dsubst2') (t:=T1') (lgsubst:=lgsubst'); auto.\n             rewrite swap_subst_ee_lgsubst with  (D:=D') (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (t:=apply_delta_subst_typ (dsubst1'++dsubst2') T1') (gsubst:=gsubst1'++gsubst2'); auto.\n                apply contexting_regular in Hcontexting.\n                decompose [and] Hcontexting.\n                assert (y `notin` dom (E1'++E2')) as ynE'.\n                  apply uniq_from_wf_env in H5.\n                  simpl_env. solve_uniq.\n                assert (y `notin` dom D') as ynD'.\n                  apply wf_lenv_notin_fv_lenv with (x:=y) (T:=T1') in H6; auto.\n                apply wf_lgamma_subst__nfv with (x:=y) in Hwflg'; auto.\n             apply F_related_subst__inversion in Hrel_sub'.\n             decompose [prod] Hrel_sub'; auto.\n         rewrite Heq1 in J. rewrite Heq2 in J. clear Heq1 Heq2.\n         destruct J as [v [v' [Ht [Ht' [[Hbrc Hv] [[Hbrc' Hv'] Hrel]]]]]].\n         exists (v). exists (v').\n         split.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2)  (apply_gamma_subst lgsubst (subst_ee y x (plug C1 e)))))); auto.\n              assert (apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst x)) =x) as Heq1.\n                 rewrite gamma_subst_closed_exp with (t:= apply_delta_subst_typ (dsubst1++dsubst2) T1'); auto.\n                 rewrite gamma_subst_closed_exp with (t:= apply_delta_subst_typ  (dsubst1++dsubst2) T1'); auto.\n                 rewrite delta_subst_closed_exp with (t:= apply_delta_subst_typ  (dsubst1++dsubst2) T1'); auto.\n                 rewrite gamma_subst_closed_exp with (t:= apply_delta_subst_typ  (dsubst1++dsubst2) T1'); auto.\n              rewrite <- Heq1.\n              rewrite commut_gamma_subst_abs.\n              rewrite commut_gamma_subst_abs.\n              assert (subst_ee y (apply_delta_subst  (dsubst1++dsubst2) (apply_gamma_subst  (gsubst1++gsubst2) (apply_gamma_subst lgsubst x))) (plug C1 e) = subst_ee y x (plug C1 e)) as Heq2. \n                 rewrite Heq1. auto. \n              rewrite Heq2.\n              assert (typing (E1'++[(y, bind_typ T1')]++E2') D' (plug C1 e) T2') as Typinge.\n                apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n\n             assert (disjdom (union {{y}} (fv_ee x `union` fv_te x)) (cv_ec C1)) as Disj0.\n               eapply disjdom_app_l.\n               split.\n                 apply disjdom_one_2; auto.\n               eapply disjdom_app_l.\n               split.\n                  eapply empty_typing_disjdom; eauto.\n                  eapply empty_typing_disjdom'; eauto.\n              rewrite subst_ee_plug; auto.\n              rewrite <- close_open_ee__subst_ee; auto.\n              assert (context C1) as Context1.\n                apply contexting__context in Hcontexting; auto.    \n              rewrite <- close_open_ec__subst_ec; auto.\n              assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n               eapply disjdom_app_l.\n               split.\n                  eapply empty_typing_disjdom; eauto.\n                  eapply empty_typing_disjdom'; eauto.\n              rewrite <- open_ee_plug; auto.\n              rewrite commut_lgamma_subst_open_ee with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(gsubst:=gsubst1++gsubst2); auto.\n              rewrite commut_gamma_subst_open_ee with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(lgsubst:=lgsubst); auto.\n              rewrite <- shift_ee_expr; auto.\n              apply red_abs_preserved_under_delta_subst with (dE:=E1'++E2'); auto.\n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_gamma_subst_open_ee with (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (D:=D') (lgsubst:=lgsubst); auto.\n              apply red_abs_preserved_under_gamma_subst with (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (D:=D') (lgsubst:=lgsubst); auto. \n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_lgamma_subst_open_ee with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(gsubst:=gsubst1++gsubst2); auto.\n              apply red_abs_preserved_under_lgamma_subst with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(gsubst:=gsubst1++gsubst2); auto. \n\n              apply red_abs.\n                apply expr_abs with (L:=(cv_ec (close_ec C1 y)) `union` cv_ec C1).\n                   apply type_from_wf_typ in WFTV; assumption.\n\n                   intros.\n                   assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec (close_ec C1 y))) as Disj'.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite open_ee_plug; auto.\n                   rewrite close_open_ec__subst_ec; auto.\n                   rewrite close_open_ee__subst_ee; auto.\n                  assert (disjdom (union {{y}} (fv_ee x0 `union` fv_te x0)) (cv_ec C1)) as Disj0'.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjdom_one_2; auto.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite <- subst_ee_plug; auto.\n\n               apply F_related_values_inversion in Harrow_left'.\n               decompose [prod] Harrow_left'; auto.\n         split; auto.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (subst_ee y x' (plug C1 e')))))); auto.\n              assert (apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' x')) =x') as Heq1'.\n                 rewrite gamma_subst_closed_exp with (t:= apply_delta_subst_typ (dsubst1'++dsubst2') T1'); auto.\n                 rewrite gamma_subst_closed_exp with (t:= apply_delta_subst_typ  (dsubst1'++dsubst2') T1'); auto.\n                 rewrite delta_subst_closed_exp with (t:= apply_delta_subst_typ  (dsubst1'++dsubst2') T1'); auto.\n                 rewrite gamma_subst_closed_exp with (t:= apply_delta_subst_typ  (dsubst1'++dsubst2') T1'); auto.\n              rewrite <- Heq1'.\n              rewrite commut_gamma_subst_abs.\n              rewrite commut_gamma_subst_abs.\n              assert (subst_ee y (apply_delta_subst  (dsubst1'++dsubst2') (apply_gamma_subst  (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' x'))) (plug C1 e') = subst_ee y x' (plug C1 e')) as Heq2'. \n                 rewrite Heq1'. auto. \n              rewrite Heq2'.\n              assert (typing (E1'++[(y, bind_typ T1')]++E2') D' (plug C1 e') T2') as Typinge'.\n                apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n             assert (disjdom (union {{y}} (fv_ee x' `union` fv_te x')) (cv_ec C1)) as Disj0.\n               eapply disjdom_app_l.\n               split.\n                 apply disjdom_one_2; auto.\n               eapply disjdom_app_l.\n               split.\n                  eapply empty_typing_disjdom; eauto.\n                  eapply empty_typing_disjdom'; eauto.\n              rewrite subst_ee_plug; auto.\n              rewrite <- close_open_ee__subst_ee; auto.\n              assert (context C1) as Context1.\n                apply contexting__context in Hcontexting; auto.    \n              rewrite <- close_open_ec__subst_ec; auto.\n              assert (disjdom (fv_ee x' `union` fv_te x') (cv_ec (close_ec C1 y))) as Disj.\n                eapply disjdom_app_l.\n                split.\n                   eapply empty_typing_disjdom; eauto.\n                   eapply empty_typing_disjdom'; eauto.\n              rewrite <- open_ee_plug; auto.\n              rewrite commut_lgamma_subst_open_ee with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(gsubst:=gsubst1'++gsubst2'); auto.\n              rewrite commut_gamma_subst_open_ee with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(lgsubst:=lgsubst'); auto.\n              rewrite <- shift_ee_expr; auto.\n              apply red_abs_preserved_under_delta_subst with (dE:=E1'++E2'); auto.\n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_gamma_subst_open_ee with (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (D:=D') (lgsubst:=lgsubst'); auto.\n              apply red_abs_preserved_under_gamma_subst with (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (D:=D') (lgsubst:=lgsubst'); auto. \n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_lgamma_subst_open_ee with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(gsubst:=gsubst1'++gsubst2'); auto.\n              apply red_abs_preserved_under_lgamma_subst with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(gsubst:=gsubst1'++gsubst2'); auto. \n\n              apply red_abs.\n                apply expr_abs with (L:=cv_ec (close_ec C1 y) `union` cv_ec C1).\n                   apply type_from_wf_typ in WFTV; assumption.\n\n                   intros.\n                   assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec (close_ec C1 y))) as Disj'.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite open_ee_plug; auto.\n                   rewrite close_open_ec__subst_ec; auto.\n                   rewrite close_open_ee__subst_ee; auto.\n                  assert (disjdom (union {{y}} (fv_ee x0 `union` fv_te x0)) (cv_ec C1)) as Disj0'.\n                    eapply disjdom_app_l.\n                    split.\n                      apply disjdom_one_2; auto.\n                    eapply disjdom_app_l.\n                    split.\n                      apply disjdom_one_2; auto.\n                      simpl. apply disjdom_nil_1.\n                   rewrite <- subst_ee_plug; auto.\n\n               apply F_related_values_inversion in Harrow_left'.\n               decompose [prod] Harrow_left'; auto.\nQed.\n\nLemma F_logical_related_congruence__labs_capture :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n   F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n   F_Rsubst E rsubst dsubst dsubst' ->\n   F_related_terms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n  ) ->\n  forall K y T1' C1 T2' E' D',\n  wf_typ E' T1' kn_lin ->\n  binds y (lbind_typ T1') D' ->\n  y `notin` gdom_env E `union` cv_ec C1 ->\n  contexting E D T C1 E' D' T2' ->\n  (K = kn_nonlin -> lenv_remove (y, lbind_typ T1') D' = lempty) ->\n  (typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E rsubst dsubst dsubst' ->\n     F_related_terms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E' rsubst dsubst dsubst' ->\n     F_related_terms T2' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n  F_related_subst E' (lenv_remove (y, lbind_typ T1') D') gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n  F_Rsubst E' rsubst dsubst dsubst' ->\n  F_related_terms (typ_arrow K T1' T2') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e) y))))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e') y)))))).\nProof.\n    intros e e' E D T Htyp Htyp' Hlr K y T1' C1 T2' E' D' H H0 H1 Hcontexting H2 IHHcontexting dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Hrel_sub HRsub.  \n    assert (J:=Hrel_sub). apply F_related_subst__inversion in J. \n    destruct J as [[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe].\n\n    rename H into WFTV.\n    \n    assert (wf_typ E' T2' kn_lin) as WFT'. \n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (Fry := @IHHcontexting Htyp Htyp' Hlr).\n    assert (wf_lenv E' D') as Wfle'.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (EQ1:=@lenv_remove_inv E' D' y (lbind_typ T1')  Wfle' H0).\n    destruct EQ1 as [D1' [D2' [EQ1' EQ2']]]; subst.\n    rewrite EQ1' in *.\n\n    assert (EQ:=Hwflg).\n    apply wf_lgsubst_lapp_inv in EQ.\n    destruct EQ as [lgsubst1 [lgsubst2 [gEQ1 [gEQ2 gEQ3]]]]; subst.\n\n    assert (EQ:=Hwflg').\n    apply wf_lgsubst_lapp_inv in EQ.\n    destruct EQ as [lgsubst1' [lgsubst2' [gEQ1' [gEQ2' gEQ3']]]]; subst.\n       \n    assert (value (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst (lgsubst1++lgsubst2) (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e) y))))))) as Value.\n      apply delta_gamma_lgamma_subst_value with (E:=E') (D:=D1'++D2'); auto.\n        apply FrTyping__labsvalue with (L:=dom E' `union` dom (D1'++D2') `union` cv_ec (close_ec C1 y) `union` cv_ec C1) (D:=D1'++D2') (E:=E') (T1:=T2') (K:=kn_lin); auto.\n          intros x xnFv.\n          rewrite <- shift_ee_expr with (e:=e); auto.\n          assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite open_ee_plug; auto. \n          rewrite <- EQ1'.\n          rewrite close_open_ee__subst_ee; auto.\n          assert (context C1) as Ctx1.\n            apply contexting__context in Hcontexting; auto.\n          rewrite close_open_ec__subst_ec; auto.\n          assert (disjdom (union {{y}} (fv_ee x `union` fv_te x)) (cv_ec C1)) as Disj'.\n             eapply disjdom_app_l.\n             split.\n               apply disjdom_one_2; auto.\n             eapply disjdom_app_l.\n             split.\n               apply disjdom_one_2; auto.\n               simpl. apply disjdom_nil_1.\n          rewrite <- subst_ee_plug; auto. \n          assert (typing E' (D1'++[(y, lbind_typ T1')]++D2') (plug C1 e) T2') as Htyp2.\n            apply contexting_plug_typing with (e:=e) in Hcontexting; auto.\n              rewrite EQ1'. auto.\n         apply typing_lin_renaming_permute with (x:=y); auto.\n    assert (value (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst (lgsubst1'++lgsubst2') (exp_abs K T1' (plug (close_ec C1 y)  (close_ee (shift_ee e') y))))))) as Value'.\n      apply delta_gamma_lgamma_subst_value with (E:=E') (D:=D1'++D2'); auto.\n        apply FrTyping__labsvalue with (L:=dom E' `union` dom (D1'++D2') `union` cv_ec (close_ec C1 y) `union` cv_ec C1) (D:=D1'++D2') (E:=E') (T1:=T2') (K:=kn_lin); auto.\n          intros x xnFv.\n          rewrite <- shift_ee_expr with (e:=e'); auto.\n          assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite open_ee_plug; auto. \n          rewrite <- EQ1'.\n          rewrite close_open_ee__subst_ee; auto.\n          assert (context C1) as Ctx1.\n            apply contexting__context in Hcontexting; auto.\n          rewrite close_open_ec__subst_ec; auto.\n          assert (disjdom (union {{y}} (fv_ee x `union` fv_te x)) (cv_ec C1)) as Disj'.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              simpl. apply disjdom_nil_1.\n          rewrite <- subst_ee_plug; auto. \n          assert (typing E' (D1'++[(y, lbind_typ T1')]++D2') (plug C1 e') T2') as Htyp2'.\n            apply contexting_plug_typing with (e:=e') in Hcontexting; auto.\n              rewrite EQ1'. auto.\n         apply typing_lin_renaming_permute with (x:=y); auto.\n    exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst (lgsubst1++lgsubst2) (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e) y)))))).\n    exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst (lgsubst1'++lgsubst2') (exp_abs K T1' (plug (close_ec C1 y) (close_ee (shift_ee e') y)))))).\n    split. \n      assert (typing E' (D1'++D2') (plug (ctx_abs_capture K y T1' (close_ec C1 y)) e) (typ_arrow K T1' T2')) as Hptyp.\n        destruct (in_dec y (fv_ee e)) as [yine | ynine].\n          simpl.\n          apply typing_labs with (L:=dom (D1'++D2') `union` dom E' `union` dom E `union` dom D `union` cv_ec C1 `union` cv_ec (close_ec C1 y)); auto.\n            intros x xn.\n            rewrite <- shift_ee_expr; auto.\n            assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n              eapply disjdom_app_l.\n              split.\n                apply disjdom_one_2; auto.\n                simpl. apply disjdom_nil_1.\n            rewrite open_ee_plug; auto.\n            assert (y `in` gdom_env E \\/ y `in` dom D) as yED.\n              assert (y `in` gdom_env E `union` dom D) as J.\n                apply in_fv_ee_typing' with (x:=y) in Htyp; auto.\n              fsetdec.\n            rewrite close_open_ee__subst_ee; auto.\n            assert (context C1) as Ctx1.\n              apply contexting__context in Hcontexting; auto.\n            rewrite close_open_ec__subst_ec; auto.\n            destruct yED as [yE | yD].\n              contradict H1; auto.\n\n              apply binds_In_inv in yD.\n              destruct yD as [b Binds]. destruct b.\n              assert (wf_lenv E D) as Wfle. auto.\n              assert (J:=@lenv_remove_inv E D y (lbind_typ t) Wfle Binds).\n              destruct J as [D1 [D2 [dEQ1 dEQ2]]]; subst.\n              apply typing_lin_permute.\n              simpl_env in xn.\n              apply contexting_plug_typing with (E:=E) (D:=D1++[(x, lbind_typ t)]++D2) (T:=T); auto.\n                apply contexting_lin_renaming_one; auto.\n\n                apply typing_lin_renaming_one with (x:=y); auto.\n\n          rewrite <- EQ1'.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n            apply contexting_labs_capture; auto.\n              intros J. apply H2 in J.\n              rewrite lenv_remove_opt; auto.\n              apply uniq_from_wf_lenv in Wfle'. assumption.\n      apply typing_subst with (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst1++lgsubst2) in Hptyp; auto.\n    split.\n      assert (typing E' (D1'++D2') (plug (ctx_abs_capture K y T1' (close_ec C1 y)) e') (typ_arrow K T1' T2')) as Hptyp'.\n        destruct (in_dec y (fv_ee e')) as [yine' | ynine'].\n          simpl.\n          apply typing_labs with (L:=dom (D1'++D2') `union` dom E' `union` dom D `union` dom E `union` cv_ec C1 `union` cv_ec (close_ec C1 y)); auto.\n            intros x xn.\n            rewrite <- shift_ee_expr; auto.\n            assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n              eapply disjdom_app_l.\n              split.\n                apply disjdom_one_2; auto.\n                simpl. apply disjdom_nil_1.\n            rewrite open_ee_plug; auto.\n            assert (y `in` gdom_env E \\/ y `in` dom D) as yED.\n              assert (y `in` gdom_env E `union` dom D) as J.\n                apply in_fv_ee_typing' with (x:=y) in Htyp'; auto.\n              fsetdec.\n            rewrite close_open_ee__subst_ee; auto.\n            assert (context C1) as Ctx1.\n              apply contexting__context in Hcontexting; auto.\n            rewrite close_open_ec__subst_ec; auto.\n            destruct yED as [yE | yD].\n              contradict H1; auto.\n\n              apply binds_In_inv in yD.\n              destruct yD as [b Binds]. destruct b.\n              assert (wf_lenv E D) as Wfle. auto.\n              assert (J:=@lenv_remove_inv E D y (lbind_typ t) Wfle Binds).\n              destruct J as [D1 [D2 [dEQ1 dEQ2]]]; subst.\n              apply typing_lin_permute.\n              simpl_env in xn.\n              apply contexting_plug_typing with (E:=E) (D:=D1++[(x, lbind_typ t)]++D2) (T:=T); auto.\n                apply contexting_lin_renaming_one; auto.\n\n                apply typing_lin_renaming_one with (x:=y); auto.\n          rewrite <- EQ1'.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n            apply contexting_labs_capture; auto.\n              intros J. apply H2 in J.\n              rewrite lenv_remove_opt; auto.\n              apply uniq_from_wf_lenv in Wfle'. assumption.\n      apply typing_subst with (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst1'++lgsubst2') in Hptyp'; auto.\n    split. split; auto.\n    split. split; auto.\n      SCase \"Frel\".\n      apply F_related_values_arrow_req.\n      split; auto.\n      split; auto.\n      SSCase \"arrow\".\n        intros x x' Htyping Htyping' Harrow_left.\n\n        assert (F_related_subst E' (D1'++[(y, lbind_typ T1')]++D2') gsubst gsubst' (lgsubst1++[(y,x)]++lgsubst2) (lgsubst1'++[(y,x')]++lgsubst2') rsubst dsubst dsubst') as Hrel_sub'.        \n          apply F_related_subst_lgweaken; auto.\n             assert (y `notin` dom D1') as ynD1'.\n                apply fresh_mid_head with (E:=D2') (a:=lbind_typ T1'); auto.\n                  apply contexting_regular in Hcontexting.\n                  decompose [and] Hcontexting. eauto.\n             assert (y `notin` dom D2') as ynD2'.\n                apply fresh_mid_tail with (F:=D1') (a:=lbind_typ T1'); auto.\n                  apply contexting_regular in Hcontexting.\n                  decompose [and] Hcontexting. eauto.\n             assert (y `notin` dom E') as ynE'.\n               apply contexting_regular in Hcontexting.\n               decompose [and] Hcontexting.\n              apply wf_lenv_notin_dom with (x:=y) (T:=T1') in H6; auto.\n             auto.\n        assert (J:=@Fry dsubst dsubst' gsubst gsubst' (lgsubst1++[(y,x)]++lgsubst2) (lgsubst1'++[(y,x')]++lgsubst2') rsubst Hrel_sub' HRsub).\n        assert (\n            apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst (lgsubst1++[(y,x)]++lgsubst2) (plug C1 e))) =\n            apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst (lgsubst1++lgsubst2) (subst_ee y x (plug C1 e))))\n                  ) as Heq1.\n           simpl_env.\n           rewrite lgamma_subst_opt with (D':=D1') (D:=D2') (E:=E') (dsubst:=dsubst) (t:=T1') (gsubst:=gsubst); auto.\n             apply F_related_subst__inversion in Hrel_sub'.\n             decompose [prod] Hrel_sub'; auto.\n         assert (\n            apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst  (lgsubst1'++[(y,x')]++lgsubst2') (plug C1 e'))) =\n            apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst  (lgsubst1'++lgsubst2') (subst_ee y x' (plug C1 e'))))\n                  ) as Heq2.\n           simpl_env.\n           rewrite lgamma_subst_opt with (D':=D1') (D:=D2') (E:=E') (dsubst:=dsubst') (t:=T1') (gsubst:=gsubst'); auto.\n             apply F_related_subst__inversion in Hrel_sub'.\n             decompose [prod] Hrel_sub'; auto.\n         rewrite Heq1 in J. rewrite Heq2 in J. clear Heq1 Heq2.\n         destruct J as [v [v' [Ht [Ht' [[Hbrc Hv] [[Hbrc' Hv'] Hrel]]]]]].\n         exists (v). exists (v').\n         split.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst dsubst (apply_gamma_subst gsubst  (apply_gamma_subst (lgsubst1++lgsubst2) (subst_ee y x (plug C1 e)))))); auto.\n              assert (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst (lgsubst1++lgsubst2) x)) =x) as Heq1.\n                 rewrite gamma_subst_closed_exp with (t:= apply_delta_subst_typ dsubst T1'); auto.\n                 rewrite gamma_subst_closed_exp with (t:= apply_delta_subst_typ dsubst T1'); auto.\n                 rewrite delta_subst_closed_exp with (t:= apply_delta_subst_typ dsubst T1'); auto.\n                 rewrite gamma_subst_closed_exp with (t:= apply_delta_subst_typ dsubst T1'); auto.\n              rewrite <- Heq1.\n              rewrite commut_gamma_subst_abs.\n              rewrite commut_gamma_subst_abs.\n              assert (subst_ee y (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst (lgsubst1++lgsubst2) x))) (plug C1 e) = subst_ee y x (plug C1 e)) as Heq2. \n                 rewrite Heq1. auto. \n              rewrite Heq2.\n              assert (typing E' (D1'++[(y, lbind_typ T1')]++D2') (plug C1 e) T2') as Typinge.\n                apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n             assert (disjdom (union {{y}} (fv_ee x `union` fv_te x)) (cv_ec C1)) as Disj'.\n               eapply disjdom_app_l.\n               split.\n                 apply disjdom_one_2; auto.\n               eapply disjdom_app_l.\n               split.\n                 eapply empty_typing_disjdom; eauto.\n                 eapply empty_typing_disjdom'; eauto.\n              rewrite subst_ee_plug; auto.\n              rewrite <- close_open_ee__subst_ee; auto.\n              assert (context C1) as Context1.\n                apply contexting__context in Hcontexting; auto.    \n              rewrite <- close_open_ec__subst_ec; auto.\n              assert (disjdom (fv_ee x `union` fv_te x) (cv_ec (close_ec C1 y))) as Disj.\n               eapply disjdom_app_l.\n               split.\n                 eapply empty_typing_disjdom; eauto.\n                 eapply empty_typing_disjdom'; eauto.\n              rewrite <- open_ee_plug; auto.\n              rewrite commut_lgamma_subst_open_ee with (D:=D1'++D2')(E:=E')(dsubst:=dsubst)(gsubst:=gsubst); auto.\n              rewrite commut_gamma_subst_open_ee with (D:=D1'++D2')(E:=E')(dsubst:=dsubst)(lgsubst:=lgsubst1++lgsubst2); auto.\n              rewrite <- shift_ee_expr; auto.\n              apply red_abs_preserved_under_delta_subst with (dE:=E'); auto.\n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_gamma_subst_open_ee with (D:=D1'++D2') (dsubst:=dsubst) (E:=E') (lgsubst:=lgsubst1++lgsubst2); auto.\n              apply red_abs_preserved_under_gamma_subst with (D:=D1'++D2') (dsubst:=dsubst) (E:=E')(lgsubst:=lgsubst1++lgsubst2); auto.\n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_lgamma_subst_open_ee with (D:=D1'++D2')(E:=E')(dsubst:=dsubst)(gsubst:=gsubst); auto.\n              apply red_abs_preserved_under_lgamma_subst with (D:=D1'++D2')(E:=E')(dsubst:=dsubst)(gsubst:=gsubst); auto. \n\n              apply red_abs.\n                apply expr_abs with (L:=cv_ec (close_ec C1 y) `union` cv_ec C1).\n                   apply type_from_wf_typ in WFTV; assumption.\n\n                   intros.\n                   assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec (close_ec C1 y))) as Disj0'.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite open_ee_plug; auto.\n                   rewrite close_open_ec__subst_ec; auto.\n                   rewrite close_open_ee__subst_ee; auto.\n                  assert (disjdom (union {{y}} (fv_ee x0 `union` fv_te x0)) (cv_ec C1)) as Disj1'.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjdom_one_2; auto.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite <- subst_ee_plug; auto.\n               apply F_related_values_inversion in Harrow_left.\n               decompose [prod] Harrow_left; auto.\n         split; auto.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst (lgsubst1'++lgsubst2') (subst_ee y x' (plug C1 e')))))); auto.\n              assert (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst (lgsubst1'++lgsubst2') x')) =x') as Heq1'.\n                 rewrite gamma_subst_closed_exp with (t:= apply_delta_subst_typ dsubst' T1'); auto.\n                 rewrite gamma_subst_closed_exp with (t:= apply_delta_subst_typ dsubst' T1'); auto.\n                 rewrite delta_subst_closed_exp with (t:= apply_delta_subst_typ dsubst' T1'); auto.\n                 rewrite gamma_subst_closed_exp with (t:= apply_delta_subst_typ dsubst' T1'); auto.\n              rewrite <- Heq1'.\n              rewrite commut_gamma_subst_abs.\n              rewrite commut_gamma_subst_abs.\n              assert (subst_ee y (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst (lgsubst1'++lgsubst2') x'))) (plug C1 e') = subst_ee y x' (plug C1 e')) as Heq2'. \n                 rewrite Heq1'. auto. \n              rewrite Heq2'.\n              assert (typing E' (D1'++[(y, lbind_typ T1')]++D2') (plug C1 e') T2') as Typinge'.\n                apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n             assert (disjdom (union {{y}} (fv_ee x' `union` fv_te x')) (cv_ec C1)) as Disj0'.\n               eapply disjdom_app_l.\n               split.\n                 apply disjdom_one_2; auto.\n               eapply disjdom_app_l.\n               split.\n                 eapply empty_typing_disjdom; eauto.\n                 eapply empty_typing_disjdom'; eauto.\n              rewrite subst_ee_plug; auto.\n              rewrite <- close_open_ee__subst_ee; auto.\n              assert (context C1) as Context1.\n                apply contexting__context in Hcontexting; auto.    \n              rewrite <- close_open_ec__subst_ec; auto.\n              assert (disjdom (fv_ee x' `union` fv_te x') (cv_ec (close_ec C1 y))) as Disj.\n                eapply disjdom_app_l.\n                split.\n                  eapply empty_typing_disjdom; eauto.\n                  eapply empty_typing_disjdom'; eauto.\n              rewrite <- open_ee_plug; auto.\n              rewrite commut_lgamma_subst_open_ee with (D:=D1'++D2')(E:=E')(dsubst:=dsubst')(gsubst:=gsubst'); auto.\n              rewrite commut_gamma_subst_open_ee with (D:=D1'++D2')(E:=E')(dsubst:=dsubst')(lgsubst:=lgsubst1'++lgsubst2'); auto.\n              rewrite <- shift_ee_expr; auto.\n              apply red_abs_preserved_under_delta_subst with (dE:=E'); auto.\n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_gamma_subst_open_ee with (D:=D1'++D2') (dsubst:=dsubst') (E:=E') (lgsubst:=lgsubst1'++lgsubst2'); auto.\n              apply red_abs_preserved_under_gamma_subst with (D:=D1'++D2') (dsubst:=dsubst') (E:=E')(lgsubst:=lgsubst1'++lgsubst2'); auto.\n\n              rewrite <- commut_gamma_subst_abs; auto.\n              rewrite <- commut_lgamma_subst_open_ee with (D:=D1'++D2')(E:=E')(dsubst:=dsubst')(gsubst:=gsubst'); auto.\n              apply red_abs_preserved_under_lgamma_subst with (D:=D1'++D2')(E:=E')(dsubst:=dsubst')(gsubst:=gsubst'); auto. \n\n              apply red_abs.\n                apply expr_abs with (L:=cv_ec (close_ec C1 y) `union` cv_ec C1).\n                   apply type_from_wf_typ in WFTV; assumption.\n\n                   intros.\n                   assert (disjdom (fv_ee x0 `union` fv_te x0) (cv_ec (close_ec C1 y))) as Disj'.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite open_ee_plug; auto.\n                   rewrite close_open_ec__subst_ec; auto.\n                   rewrite close_open_ee__subst_ee; auto.\n                  assert (disjdom (union {{y}} (fv_ee x0 `union` fv_te x0)) (cv_ec C1)) as Disj1'.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjdom_one_2; auto.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjdom_one_2; auto.\n                       simpl. apply disjdom_nil_1.\n                   rewrite <- subst_ee_plug; auto.\n               apply F_related_values_inversion in Harrow_left.\n               decompose [prod] Harrow_left; auto.\nQed.\n\nLemma F_logical_related_congruence__app1 :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n   F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n   F_Rsubst E rsubst dsubst dsubst' ->\n   F_related_terms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n  ) ->\n  forall T1' K  E' D1' D2' D3' C1 e2 T2',\n  contexting E D T C1 E' D1' (typ_arrow K T1' T2') ->\n  typing E' D2' e2 T1' ->\n  lenv_split E' D1' D2' D3' ->\n  disjdom (fv_ee e2) (dom D) ->\n  (typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E rsubst dsubst dsubst' ->\n     F_related_terms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E' D1' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E' rsubst dsubst dsubst' ->\n     F_related_terms (typ_arrow K T1' T2') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n  F_related_subst E' D3' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n  F_Rsubst E' rsubst dsubst dsubst' ->\n  F_related_terms T2' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_app (plug C1 e) e2))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_app (plug C1 e') e2)))).\nProof.\n   intros e e' E D T Htyp Htyp' Hlr T1' K E' D1' D2' D3' C1 e2 T2' Hcontexting H H0 H1 IHHcontexting dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Hrel_sub HRsub.  \n   assert (J:=Hrel_sub). apply F_related_subst__inversion in J. \n   destruct J as [[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe].\n   apply F_related_subst_split with (lE1:=D1') (lE2:=D2') in Hrel_sub; auto.\n   destruct Hrel_sub as [lgsubst1 [lgsubst1' [lgsubst2 [lgsubst2' [J1 [J2 [J3 J4]]]]]]].\n\n   assert (\n      F_related_terms (typ_arrow K T1' T2') rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst1 (plug C1 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst1' (plug C1 e'))))\n     ) as FR_ArrowType.\n    apply IHHcontexting; auto.\n   destruct FR_ArrowType as [v [v' [Ht [Ht' [Hn [Hn' Hrel]]]]]].\n\n   apply F_related_values_arrow_leq in Hrel.\n   destruct Hrel as [Hv [Hv' Harrow]]; subst.\n\n   assert (\n      F_related_terms T1' rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst2 e2)))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst'(apply_gamma_subst lgsubst2' e2)))\n     ) as FR_T1.\n    apply parametricity with (E:=E') (lE:=D2'); auto.\n   destruct FR_T1 as [v0 [v'0 [Ht1 [Ht1' [Hn1 [Hn1' Hrel_wft1]]]]]].\n\n   destruct (@Harrow v0 v'0) as [u [u' [Hnorm_vxu [Hnorm_v'x'u' Hrel_wft2]]]]; auto.\n     eapply preservation_normalization; eauto.\n     eapply preservation_normalization; eauto.\n\n   exists(u). exists(u').\n   split. \n     assert (typing E' D3' (exp_app (plug C1 e) e2) T2') as Hptyp.\n       apply typing_app with (D1:=D1') (D2:=D2') (K:=K) (T1:=T1'); auto.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n      apply typing_subst with (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst) in Hptyp; auto. \n   split.\n     assert (typing E' D3' (exp_app (plug C1 e') e2) T2') as Hptyp'.\n       apply typing_app with (D1:=D1') (D2:=D2') (K:=K) (T1:=T1'); auto.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n      apply typing_subst with (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst') in Hptyp'; auto. \n   assert (apply_delta_subst dsubst\n            (apply_gamma_subst gsubst\n              (apply_gamma_subst lgsubst (exp_app (plug C1 e) e2)) \n            ) =\n            apply_delta_subst dsubst\n            (apply_gamma_subst gsubst\n              (exp_app \n                (apply_gamma_subst lgsubst1 (plug C1 e))\n                (apply_gamma_subst lgsubst2 e2)\n              )               \n            )\n          ) as EQ.\n     simpl_commut_subst in *.\n     rewrite lgamma_subst_split_subst' with (lgsubst1:=lgsubst1) (lgsubst2:=lgsubst2) (E:=E') (lE:=D3') (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst); auto.\n     rewrite lgamma_subst_split_subst with (lgsubst1:=lgsubst1) (lgsubst2:=lgsubst2) (E:=E') (lE:=D3') (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst); auto.\n     apply F_related_subst__inversion in J3.\n     decompose [prod] J3; auto.\n     apply F_related_subst__inversion in J4.\n     decompose [prod] J4; auto.\n     rewrite lgamma_subst_split_shuffle2 with (lgsubst:=lgsubst) (lgsubst1:=lgsubst1) (E:=E') (lE:=D3') ; auto.\n     erewrite gamma_subst_closed_exp; eauto.\n     rewrite lgamma_subst_split_shuffle1 with (lgsubst:=lgsubst) (lgsubst2:=lgsubst2) (E:=E') (lE:=D3') (e:=apply_gamma_subst lgsubst2 e2) ; auto.\n     erewrite gamma_subst_closed_exp with \n         (e:=apply_delta_subst dsubst\n            (apply_gamma_subst gsubst\n              (apply_gamma_subst lgsubst2 e2))\n          ); eauto.\n   repeat(rewrite EQ). clear EQ.\n   assert (apply_delta_subst dsubst'\n            (apply_gamma_subst gsubst'\n              (apply_gamma_subst lgsubst' (exp_app (plug C1 e') e2)) \n            ) =\n            apply_delta_subst dsubst'\n            (apply_gamma_subst gsubst'\n              (exp_app \n                (apply_gamma_subst lgsubst1' (plug C1 e'))\n                (apply_gamma_subst lgsubst2' e2)\n              )               \n            )\n          ) as EQ.\n     simpl_commut_subst in *.\n     rewrite lgamma_subst_split_subst' with (lgsubst1:=lgsubst1') (lgsubst2:=lgsubst2') (E:=E') (lE:=D3') (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst'); auto.\n     rewrite lgamma_subst_split_subst with (lgsubst1:=lgsubst1') (lgsubst2:=lgsubst2') (E:=E') (lE:=D3') (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst'); auto.\n     apply F_related_subst__inversion in J3.\n     decompose [prod] J3; auto.\n     apply F_related_subst__inversion in J4.\n     decompose [prod] J4; auto.\n     rewrite lgamma_subst_split_shuffle2 with (lgsubst:=lgsubst') (lgsubst1:=lgsubst1') (E:=E') (lE:=D3') ; auto.\n     erewrite gamma_subst_closed_exp; eauto.\n     rewrite lgamma_subst_split_shuffle1 with (lgsubst:=lgsubst') (lgsubst2:=lgsubst2') (E:=E') (lE:=D3') (e:=apply_gamma_subst lgsubst2' e2) ; auto.\n     erewrite gamma_subst_closed_exp with \n         (e:=apply_delta_subst dsubst'\n            (apply_gamma_subst gsubst'\n              (apply_gamma_subst lgsubst2' e2))\n          ); eauto.\n   repeat(rewrite EQ). clear EQ.\n   repeat(split; try solve [simpl_commut_subst in *; eauto |\n                                              simpl_commut_subst; apply congr_app with (v1:=v) (v2:=v0); auto |\n                                              simpl_commut_subst; apply congr_app with (v1:=v') (v2:=v'0); auto]).\nQed.\n\nLemma F_logical_related_congruence__app2 :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n   F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n   F_Rsubst E rsubst dsubst dsubst' ->\n   F_related_terms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n  ) ->\n  forall T1' K  E' D1' D2' D3' e1 C2 T2',\n  typing E' D1' e1 (typ_arrow K T1' T2') ->\n  contexting E D T C2 E' D2' T1' ->\n  disjdom (fv_ee e1) (dom D) ->\n  lenv_split E' D1' D2' D3' ->\n  (typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst'->\n     F_Rsubst E rsubst dsubst dsubst' ->\n     F_related_terms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E' D2' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E' rsubst dsubst dsubst' ->\n     F_related_terms T1' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C2 e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C2 e'))))\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n  F_related_subst E' D3' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n  F_Rsubst E' rsubst dsubst dsubst' ->\n  F_related_terms T2' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_app e1 (plug C2 e)))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_app e1 (plug C2 e'))))).\nProof.\n   intros e e' E D T Htyp Htyp' Hlr T1' K E' D1' D2' D3' e1 C2 T2' H Hcontexting H0 H1 IHHcontexting dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Hrel_sub HRsub.  \n   assert (J:=Hrel_sub). apply F_related_subst__inversion in J. \n   destruct J as [[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe].\n   apply F_related_subst_split with (lE1:=D1') (lE2:=D2') in Hrel_sub; auto.\n   destruct Hrel_sub as [lgsubst1 [lgsubst1' [lgsubst2 [lgsubst2' [J1 [J2 [J3 J4]]]]]]].\n\n   assert (\n      F_related_terms (typ_arrow K T1' T2') rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst1 e1)))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst1' e1)))\n     ) as FR_ArrowType.\n    apply parametricity with (E:=E') (lE:=D1'); auto.\n   destruct FR_ArrowType as [v [v' [Ht [Ht' [Hn [Hn' Hrel]]]]]].\n\n   apply F_related_values_arrow_leq in Hrel.\n   destruct Hrel as [Hv [Hv' Harrow]]; subst.\n\n   assert (\n      F_related_terms T1' rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst2 (plug C2 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst'(apply_gamma_subst lgsubst2' (plug C2 e'))))\n     ) as FR_T1.\n    apply IHHcontexting; auto.\n   destruct FR_T1 as [v0 [v'0 [Ht1 [Ht1' [Hn1 [Hn1' Hrel_wft1]]]]]].\n\n   destruct (@Harrow v0 v'0) as [u [u' [Hnorm_vxu [Hnorm_v'x'u' Hrel_wft2]]]]; auto.\n     eapply preservation_normalization; eauto.\n     eapply preservation_normalization; eauto.\n\n   exists(u). exists(u').\n   split. \n     assert (typing E' D3' (exp_app e1 (plug C2 e)) T2') as Hptyp.\n       apply typing_app with (D1:=D1') (D2:=D2') (K:=K) (T1:=T1'); auto.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n      apply typing_subst with (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst) in Hptyp; auto. \n   split.\n     assert (typing E' D3' (exp_app e1 (plug C2 e')) T2') as Hptyp'.\n       apply typing_app with (D1:=D1') (D2:=D2') (K:=K) (T1:=T1'); auto.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n      apply typing_subst with (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst') in Hptyp'; auto. \n   assert (apply_delta_subst dsubst\n            (apply_gamma_subst gsubst\n              (apply_gamma_subst lgsubst (exp_app e1 (plug C2 e))) \n            ) =\n            apply_delta_subst dsubst\n            (apply_gamma_subst gsubst\n              (exp_app \n                (apply_gamma_subst lgsubst1 e1)\n                (apply_gamma_subst lgsubst2 (plug C2 e))\n              )               \n            )\n          ) as EQ.\n     simpl_commut_subst in *.\n     rewrite lgamma_subst_split_subst' with (lgsubst1:=lgsubst1) (lgsubst2:=lgsubst2) (E:=E') (lE:=D3') (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst); auto.\n     rewrite lgamma_subst_split_subst with (lgsubst1:=lgsubst1) (lgsubst2:=lgsubst2) (E:=E') (lE:=D3') (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst); auto.\n     apply F_related_subst__inversion in J3.\n     decompose [prod] J3; auto.\n     apply F_related_subst__inversion in J4.\n     decompose [prod] J4; auto.\n     rewrite lgamma_subst_split_shuffle2 with (lgsubst:=lgsubst) (lgsubst1:=lgsubst1) (E:=E') (lE:=D3') ; auto.\n     erewrite gamma_subst_closed_exp; eauto.\n     rewrite lgamma_subst_split_shuffle1 with (lgsubst:=lgsubst) (lgsubst2:=lgsubst2) (E:=E') (lE:=D3') (e:=apply_gamma_subst lgsubst2 (plug C2 e)) ; auto.\n     erewrite gamma_subst_closed_exp with \n         (e:=apply_delta_subst dsubst\n            (apply_gamma_subst gsubst\n              (apply_gamma_subst lgsubst2 (plug C2 e)))\n          ); eauto.\n   repeat(rewrite EQ). clear EQ.\n   assert (apply_delta_subst dsubst'\n            (apply_gamma_subst gsubst'\n              (apply_gamma_subst lgsubst' (exp_app e1 (plug C2 e'))) \n            ) =\n            apply_delta_subst dsubst'\n            (apply_gamma_subst gsubst'\n              (exp_app \n                (apply_gamma_subst lgsubst1' e1 )\n                (apply_gamma_subst lgsubst2' (plug C2 e'))\n              )               \n            )\n          ) as EQ.\n     simpl_commut_subst in *.\n     rewrite lgamma_subst_split_subst' with (lgsubst1:=lgsubst1') (lgsubst2:=lgsubst2') (E:=E') (lE:=D3') (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst'); auto.\n     rewrite lgamma_subst_split_subst with (lgsubst1:=lgsubst1') (lgsubst2:=lgsubst2') (E:=E') (lE:=D3') (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst'); auto.\n     apply F_related_subst__inversion in J3.\n     decompose [prod] J3; auto.\n     apply F_related_subst__inversion in J4.\n     decompose [prod] J4; auto.\n     rewrite lgamma_subst_split_shuffle2 with (lgsubst:=lgsubst') (lgsubst1:=lgsubst1') (E:=E') (lE:=D3') ; auto.\n     erewrite gamma_subst_closed_exp; eauto.\n     rewrite lgamma_subst_split_shuffle1 with (lgsubst:=lgsubst') (lgsubst2:=lgsubst2') (E:=E') (lE:=D3') (e:=apply_gamma_subst lgsubst2' (plug C2 e')) ; auto.\n     erewrite gamma_subst_closed_exp with \n         (e:=apply_delta_subst dsubst'\n            (apply_gamma_subst gsubst'\n              (apply_gamma_subst lgsubst2' (plug C2 e')))\n          ); eauto.\n   repeat(rewrite EQ). clear EQ.\n   repeat(split; try solve [simpl_commut_subst in *; eauto |\n                                              simpl_commut_subst; apply congr_app with (v1:=v) (v2:=v0); auto |\n                                              simpl_commut_subst; apply congr_app with (v1:=v') (v2:=v'0); auto]).\nQed.\n\nLemma F_logical_related_congruence__tabs_free :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n   F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n   F_Rsubst E rsubst dsubst dsubst' ->\n   F_related_terms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n  ) ->\n  forall L K C1 T1' E' D',\n  (forall X, X `notin` L -> vcontext (open_tc C1 X)) ->\n  (forall X,\n    X `notin` L ->\n    contexting E D T (open_tc C1 X) ((X, bind_kn K)::E') D' (open_tt T1' X)\n  ) ->\n  (forall X,\n   X `notin` L ->\n   typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E rsubst dsubst dsubst' ->\n     F_related_terms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst ((X, bind_kn K)::E') D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst ((X, bind_kn K)::E') rsubst dsubst dsubst' ->\n     F_related_terms (open_tt T1' X) rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug (open_tc C1 X) e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug (open_tc C1 X) e'))))\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n  F_related_subst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n  F_Rsubst E' rsubst dsubst dsubst' ->\n  F_related_terms (typ_all K T1') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_tabs K (plug C1 (shift_te e))))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_tabs K (plug C1 (shift_te e')))))).\nProof.\n  intros e e' E D T Htyp Htyp' Hlr L K C1 T1' E' D' H0 H1 H2 dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Hrel_sub HRsub.\n  assert (J:=Hrel_sub). apply F_related_subst__inversion in J.\n  destruct J as [[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe].\n  assert (value (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_tabs K (plug C1 (shift_te e))))))) as Value.\n    apply delta_gamma_lgamma_subst_value with (E:=E') (D:=D'); auto.\n      apply value_tabs; auto.\n        apply expr_tabs with (L:=L `union` cv_ec C1); auto.\n          intros X Xn.\n          assert (X `notin` L) as XnFv. auto.\n          apply H1 in XnFv.\n          apply contexting_plug_typing with (e:=e) in XnFv; auto.\n          simpl_env in XnFv.\n          rewrite open_te_expr' with (e:=e) (u:=X) in XnFv; auto.\n          assert (disjdom (fv_tt X) (cv_ec C1)) as Disj.\n            apply disjdom_one_2; auto.\n          rewrite <- open_te_plug in XnFv; auto. \n          rewrite shift_te_expr with (e:=e) in XnFv; auto.\n  assert (value (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_tabs K (plug C1 (shift_te e'))))))) as Value'.\n    apply delta_gamma_lgamma_subst_value with (E:=E') (D:=D'); auto.\n      apply value_tabs; auto.\n        apply expr_tabs with (L:=L `union` cv_ec C1); auto.\n          intros X Xn.\n          assert (X `notin` L) as XnFv. auto.\n          apply H1 in XnFv.\n          apply contexting_plug_typing with (e:=e') in XnFv; auto.\n          simpl_env in XnFv.\n          rewrite open_te_expr' with (e:=e') (u:=X) in XnFv; auto.\n          assert (disjdom (fv_tt X) (cv_ec C1)) as Disj.\n            apply disjdom_one_2; auto.\n          rewrite <- open_te_plug in XnFv; auto. \n          rewrite shift_te_expr with (e:=e') in XnFv; auto.\n    \n  exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_tabs K (plug C1 (shift_te e)))))).\n  exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_tabs K (plug C1 (shift_te e')))))).\n    split.\n      assert (typing E' D' (plug (ctx_tabs_free K C1) e) (typ_all K T1')) as Hptyp.\n        apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n           apply contexting_tabs_free with (L:=L); auto.\n      apply typing_subst with (dsubst:=dsubst) (gsubst:=gsubst) (lgsubst:=lgsubst) in Hptyp; auto.\n    split.\n      assert (typing E' D' (plug (ctx_tabs_free K C1) e') (typ_all K T1')) as Hptyp'.\n        apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n           apply contexting_tabs_free with (L:=L); auto.\n      apply typing_subst with (dsubst:=dsubst') (gsubst:=gsubst') (lgsubst:=lgsubst') in Hptyp'; auto.\n    split. split; auto.\n    split. split; auto.\n      SCase \"Frel\".\n      apply F_related_values_all_req.\n      split; auto.\n      split; auto.\n        SSCase \"Frel\".\n        exists (L `union` fv_te e `union` dom E `union` fv_env E `union` fv_lenv D `union` fv_env E' `union` fv_lenv D' `union` cv_ec C1 `union` fv_te (plug C1 e) `union` fv_te (plug C1 e')).\n        intros X t2 t2' R Fr HwfR Hfv.\n        assert (X `notin` L) as FryL. auto.\n        assert (wf_typ ([(X,bind_kn K)]++E') (open_tt T1' X) kn_lin) as WFT'.\n          apply H1 in FryL.\n          apply contexting_regular in FryL.\n          decompose [and] FryL; auto.\n        apply H2 with (dsubst:=[(X, t2)]++dsubst) \n                         (dsubst':=[(X, t2')]++dsubst') \n                         (gsubst:=gsubst)\n                         (gsubst':=gsubst') \n                         (lgsubst:=lgsubst)\n                         (lgsubst':=lgsubst') \n                         (rsubst:=[(X,R)]++rsubst)in FryL; auto.\n        simpl in FryL. simpl_env in FryL.\n        erewrite swap_subst_te_gsubst with (E:=E') (dsubst:=dsubst) in FryL; eauto using wfr_left_inv. \n        erewrite swap_subst_te_lgsubst with (E:=E') (dsubst:=dsubst) in FryL; eauto using wfr_left_inv. \n        erewrite swap_subst_te_gsubst with  (E:=E')  (dsubst:=dsubst') in FryL; eauto using wfr_right_inv.\n        erewrite swap_subst_te_lgsubst with  (E:=E')  (dsubst:=dsubst') in FryL; eauto using wfr_right_inv.\n        destruct FryL as [v [v' [Ht [Ht' [[Hbrc Hv] [[Hbrc' Hv'] Hrel]]]]]].\n        exists (v). exists (v').\n        split.\n          SSSCase \"norm\".\n          split; auto.\n          apply bigstep_red_trans with (e':=(apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (subst_te X t2 (plug (open_tc C1 X) e)))))); auto.\n              rewrite <- shift_te_expr; auto.\n             assert (plug (open_tc C1 X) e = open_te (plug C1 e) X) as EQ.\n               rewrite open_te_plug; auto.\n                 rewrite <- open_te_expr'; auto.\n                 apply disjdom_one_2; auto.\n             rewrite EQ.\n             eapply m_red_tabs_subst with (T1:=T1') (L:=L  `union` cv_ec C1); eauto.\n               apply wfr_left_inv in HwfR; auto.\n\n               intros X0 X0dom.\n               assert (X0 `notin` L) as X0n. auto.\n               apply H1 in X0n.\n               assert (disjdom (fv_tt X0) (cv_ec C1)) as Disj.\n                 apply disjdom_one_2; auto.\n               rewrite open_te_plug; auto.\n               rewrite <- open_te_expr'; auto.\n               apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.       \n\n        split; auto.\n          SSSCase \"norm\".\n          split; auto.\n          apply bigstep_red_trans with (e':=(apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (subst_te X t2' (plug (open_tc C1 X) e')))))); auto.\n              rewrite <- shift_te_expr; auto.\n             assert (plug (open_tc C1 X) e' = open_te (plug C1 e') X) as EQ.\n               rewrite open_te_plug; auto.\n                 rewrite <- open_te_expr'; auto.\n                 apply disjdom_one_2; auto.\n             rewrite EQ.\n             eapply m_red_tabs_subst with (T1:=T1') (L:=L `union` cv_ec C1); eauto.\n               apply wfr_right_inv in HwfR; auto.\n\n               intros X0 X0dom.\n               assert (X0 `notin` L) as X0n. auto.\n               apply H1 in X0n.\n               assert (disjdom (fv_tt X0) (cv_ec C1)) as Disj.\n                 apply disjdom_one_2; auto.\n               rewrite open_te_plug; auto.\n               rewrite <- open_te_expr'; auto.\n               apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.       \n\n          SSSCase \"Fsubst\".\n          simpl_env.\n          apply F_related_subst_kind; auto.\n          SSSCase \"FRsubst\".\n          simpl_env.\n          apply F_Rsubst_rel; auto.\nQed.\n\nLemma F_logical_related_congruence__tabs_capture :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n   F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n   F_Rsubst E rsubst dsubst dsubst' ->\n   F_related_terms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n  ) ->\n  forall Y K C1 T1' E' D',\n  binds Y (bind_kn K) E' ->\n  Y `notin` cv_ec C1 ->\n  vcontext C1 ->\n  contexting E D T C1 E' D' T1' ->\n  wf_lenv (env_remove (Y, bind_kn K) E') D' ->\n  (typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst'->\n     F_Rsubst E rsubst dsubst dsubst' ->\n     F_related_terms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E' rsubst dsubst dsubst' ->\n     F_related_terms T1' rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n  F_related_subst (env_remove (Y, bind_kn K) E') D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n  F_Rsubst (env_remove (Y, bind_kn K) E') rsubst dsubst dsubst' ->\n  F_related_terms (typ_all K (close_tt T1' Y)) rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_tabs K (plug (close_tc C1 Y) (close_te (shift_te e) Y))))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_tabs K (plug (close_tc C1 Y) (close_te (shift_te e') Y)))))).\nProof.\n    intros e e' E D T Htyp Htyp' Hlr Y K C1 T1' E' D' H H0 H1 Hcontexting H2 IHHcontexting dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Hrel_sub HRsub.\n    assert (J:=Hrel_sub). apply F_related_subst__inversion in J. \n    destruct J as [[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe].\n\n    assert (Fry := @IHHcontexting Htyp Htyp' Hlr).\n    assert (wf_env E') as Wfe'.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (EQ1:=@env_remove_inv E' Y (bind_kn K)  Wfe' H).\n    destruct EQ1 as [E1' [E2' [EQ1' EQ2']]]; subst.\n    rewrite EQ1' in *.\n\n    assert (EQ:=Hwflg).\n    apply wf_lgsubst_app_inv in EQ.\n    destruct EQ as [dsubst1 [dsubst2 [gsubst1 [gsubst2 [dEQ1 [dEQ2 [dEQ3 [gEQ1 [gEQ2 gEQ3]]]]]]]]]; subst.\n\n    assert (EQ:=Hwflg').\n    apply wf_lgsubst_app_inv in EQ.\n    destruct EQ as [dsubst1' [dsubst2' [gsubst1' [gsubst2' [dEQ1' [dEQ2' [dEQ3' [gEQ1' [gEQ2' gEQ3']]]]]]]]]; subst.\n       \n    assert (EQ:=Hwfr).\n    apply wf_rsubst_app_inv in EQ.\n    destruct EQ as [rsubst1 [rsubst2 [rEQ1 [rEQ2 rEQ3]]]]; subst.\n\n    assert (value (apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (exp_tabs K (plug (close_tc C1 Y) (close_te (shift_te e) Y))))))) as Value.\n      apply delta_gamma_lgamma_subst_value with (E:=E1'++E2') (D:=D'); auto.\n        apply value_tabs.\n        apply expr_tabs with (L:=dom (E1'++E2') `union` dom D' `union` cv_ec (close_tc C1 Y) `union` cv_ec C1); auto.\n          intros X XnFv.\n          rewrite <- shift_te_expr with (e:=e); auto.\n          assert (disjdom (fv_tt X) (cv_ec (close_tc C1 Y))) as Disj.\n            apply disjdom_one_2; auto.\n          rewrite open_te_plug; auto. \n          rewrite close_open_te__subst_te; auto.\n          assert (context C1) as Ctx1.\n            apply contexting__context in Hcontexting; auto.\n          rewrite close_open_tc__subst_tc; auto.\n          assert (disjdom (union {{Y}} (fv_tt X)) (cv_ec C1)) as Disj'.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              apply disjdom_one_2; auto.\n          rewrite <- subst_te_plug; auto. \n          assert (typing (E1'++[(Y, bind_kn K)]++E2') D' (plug C1 e) T1') as Htyp2.\n            apply contexting_plug_typing with (e:=e) in Hcontexting; auto.\n          apply subst_te_expr; auto.\n\n    assert (value (apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (exp_tabs K (plug (close_tc C1 Y)  (close_te (shift_te e') Y))))))) as Value'.\n      apply delta_gamma_lgamma_subst_value with (E:=E1'++E2') (D:=D'); auto.\n        apply value_tabs.\n        apply expr_tabs with (L:=dom (E1'++E2') `union` dom D' `union` cv_ec (close_tc C1 Y) `union` cv_ec C1); auto.\n          intros X XnFv.\n          rewrite <- shift_te_expr with (e:=e'); auto.\n          assert (disjdom (fv_tt X) (cv_ec (close_tc C1 Y))) as Disj.\n            apply disjdom_one_2; auto.\n          rewrite open_te_plug; auto. \n          rewrite close_open_te__subst_te; auto.\n          assert (context C1) as Ctx1.\n            apply contexting__context in Hcontexting; auto.\n          rewrite close_open_tc__subst_tc; auto.\n          assert (disjdom (union {{Y}} (fv_tt X)) (cv_ec C1)) as Disj'.\n            eapply disjdom_app_l.\n            split.\n              apply disjdom_one_2; auto.\n              apply disjdom_one_2; auto.\n          rewrite <- subst_te_plug; auto. \n          assert (typing (E1'++[(Y, bind_kn K)]++E2') D' (plug C1 e') T1') as Htyp2'.\n            apply contexting_plug_typing with (e:=e') in Hcontexting; auto.\n          apply subst_te_expr; auto.\n\n    exists (apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (exp_tabs K (plug (close_tc C1 Y) (close_te (shift_te e) Y)))))).\n    exists (apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (exp_tabs K (plug (close_tc C1 Y) (close_te (shift_te e') Y)))))).\n    split.\n      assert (typing (E1'++E2') D' (plug (ctx_tabs_capture Y K (close_tc C1 Y)) e) (typ_all K (close_tt T1' Y))) as Hptyp.\n        destruct (in_dec Y (fv_te e)) as [yine | ynine].\n          simpl.\n          apply typing_tabs with (L:=dom (E1'++E2') `union` dom D' `union` dom E `union` dom D `union` {{Y}} `union` cv_ec C1 `union` cv_ec (close_tc C1 Y)); auto.\n            intros X Xn.\n            rewrite <- shift_te_expr; auto.\n            rewrite open_te_plug; auto.\n              rewrite close_open_te__subst_te; auto.\n              rewrite close_open_tc__subst_tc; auto.\n                apply plug_vcontext__value.\n                  apply vcontext_through_subst_tc; auto.\n                  apply plug_context__expr.\n                    apply context_through_subst_tc; auto.\n                      apply vcontext__context in H1; auto.\n                    apply subst_te_expr; auto.             \n                apply vcontext__context in H1; auto.\n              apply disjdom_one_2; auto.        \n\n            intros X Xn.\n            rewrite <- shift_te_expr; auto.\n            assert (disjdom (fv_tt X) (cv_ec (close_tc C1 Y))) as Disj.\n              apply disjdom_one_2; auto.\n            rewrite open_te_plug; auto.\n            assert (Y `in` ddom_env E) as J.\n              apply in_fv_te_typing' with (X:=Y) in Htyp; auto.\n            rewrite close_open_te__subst_te; auto.\n            assert (context C1) as Ctx1.\n              apply contexting__context in Hcontexting; auto.\n            rewrite close_open_tc__subst_tc; auto.\n            apply dbinds_In_inv in J.\n            destruct J as [k Binds].\n            assert (wf_env E) as Wfe. auto.\n            assert (J:=@env_remove2_inv E Y (bind_kn k) Wfe Binds).\n            destruct J as [E1 [E2 [EQ1 EQ2]]]; subst.\n\n            apply typing_typ_permute; auto. \n            assert (J:=Hcontexting).\n            apply contexting_typ_renaming_one with (Y:=X) in Hcontexting; auto.\n            assert (Y `notin` fv_env E1' `union` fv_env E2' `union` fv_lenv D') as YnE1'E2'D'.\n              apply wf_lenv_notin_fv_env with (K:=K); auto.          \n                 apply contexting_regular in J.\n                 decompose [and] J; auto.\n            assert (Y `notin` dom (E1' ++ E2')) as YndE1'E2'D'.\n              clear Xn.\n              destruct_notin.\n              apply free_env__free_dom in YnE1'E2'D'.\n              apply free_env__free_dom in NotInTac.\n              auto.\n            rewrite <- map_subst_tlb_id with (G:=E1'++E2') (D:=D') in Hcontexting; try solve [assumption].\n            rewrite <- map_subst_tb_id' with (G:=E1') (G':=E2') in Hcontexting; try solve [assumption].\n            apply contexting_plug_typing with (E:=map (subst_tb Y X) E1++[(X, bind_kn k)]++E2) (D:=map (subst_tlb Y X) D) (T:=subst_tt Y X T); auto.\n              rewrite close_open_tt__subst_tt; auto.\n                apply contexting_regular in J.\n                decompose [and] J.\n                apply type_from_wf_typ in H9; auto.\n\n              simpl_env in Xn.\n              apply typing_typ_renaming_one with (Y:=X) in Htyp; auto.\n\n          rewrite <- EQ1'.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n            apply contexting_tabs_capture; auto.\n              rewrite EQ1'. auto.\n      apply typing_subst with (dsubst:=dsubst1++dsubst2) (gsubst:=gsubst1++gsubst2) (lgsubst:=lgsubst) in Hptyp; auto.\n    split.\n      assert (typing (E1'++E2') D' (plug (ctx_tabs_capture Y K (close_tc C1 Y)) e') (typ_all K (close_tt T1' Y))) as Hptyp'.\n        destruct (in_dec Y (fv_te e')) as [yine' | ynine'].\n          simpl.\n          apply typing_tabs with (L:=dom (E1'++E2') `union` dom D' `union` dom E `union` dom D `union` {{Y}} `union` cv_ec C1 `union` cv_ec (close_tc C1 Y)); auto.\n            intros X Xn.\n            rewrite <- shift_te_expr; auto.\n            rewrite open_te_plug; auto.\n              rewrite close_open_te__subst_te; auto.\n              rewrite close_open_tc__subst_tc; auto.\n                apply plug_vcontext__value.\n                  apply vcontext_through_subst_tc; auto.\n                  apply plug_context__expr.\n                    apply context_through_subst_tc; auto.\n                      apply vcontext__context in H1; auto.\n                    apply subst_te_expr; auto.             \n                apply vcontext__context in H1; auto.\n              apply disjdom_one_2; auto.        \n\n            intros X Xn.\n            rewrite <- shift_te_expr; auto.\n            assert (disjdom (fv_tt X) (cv_ec (close_tc C1 Y))) as Disj.\n              apply disjdom_one_2; auto.\n            rewrite open_te_plug; auto.\n            assert (Y `in` ddom_env E) as J.\n              apply in_fv_te_typing' with (X:=Y) in Htyp'; auto.\n            rewrite close_open_te__subst_te; auto.\n            assert (context C1) as Ctx1.\n              apply contexting__context in Hcontexting; auto.\n            rewrite close_open_tc__subst_tc; auto.\n            apply dbinds_In_inv in J.\n            destruct J as [k Binds].\n            assert (wf_env E) as Wfe. auto.\n            assert (J:=@env_remove2_inv E Y (bind_kn k) Wfe Binds).\n            destruct J as [E1 [E2 [EQ1 EQ2]]]; subst.\n\n            apply typing_typ_permute; auto. \n            assert (J:=Hcontexting).\n            apply contexting_typ_renaming_one with (Y:=X) in Hcontexting; auto.\n            assert (Y `notin` fv_env E1' `union` fv_env E2' `union` fv_lenv D') as YnE1'E2'D'.\n              apply wf_lenv_notin_fv_env with (K:=K); auto.          \n                 apply contexting_regular in J.\n                 decompose [and] J; auto.\n            assert (Y `notin` dom (E1' ++ E2')) as YndE1'E2'D'.\n              clear Xn.\n              destruct_notin.\n              apply free_env__free_dom in YnE1'E2'D'.\n              apply free_env__free_dom in NotInTac.\n              auto.\n            rewrite <- map_subst_tlb_id with (G:=E1'++E2') (D:=D') in Hcontexting; try solve [assumption].\n            rewrite <- map_subst_tb_id' with (G:=E1') (G':=E2') in Hcontexting; try solve [assumption].\n            apply contexting_plug_typing with (E:=map (subst_tb Y X) E1++[(X, bind_kn k)]++E2) (D:=map (subst_tlb Y X) D) (T:=subst_tt Y X T); auto.\n              rewrite close_open_tt__subst_tt; auto.\n                apply contexting_regular in J.\n                decompose [and] J.\n                apply type_from_wf_typ in H9; auto.\n\n              simpl_env in Xn.\n              apply typing_typ_renaming_one with (Y:=X) in Htyp'; auto.\n\n          rewrite <- EQ1'.\n          apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n            apply contexting_tabs_capture; auto.\n              rewrite EQ1'. auto.\n      apply typing_subst with (dsubst:=dsubst1'++dsubst2') (gsubst:=gsubst1'++gsubst2') (lgsubst:=lgsubst') in Hptyp'; auto.\n    split. split; auto.\n    split. split; auto.\n      SCase \"Frel\".\n      apply F_related_values_all_req.\n      split; auto.\n      split; auto.\n\n        SSCase \"Frel\".\n        exists (fv_te e `union` dom E `union` fv_env E `union` fv_lenv D `union` {{Y}} `union` fv_env E1' `union` fv_lenv D' `union` cv_ec C1 `union` fv_te (plug C1 e) `union` fv_te (plug C1 e') `union` dom E1' `union` dom E2' `union` fv_tt T1').\n        intros X t2 t2' R Fr HwfR Hfv.\n\n        assert (F_related_subst (E1'++[(Y, bind_kn K)]++E2') D' (gsubst1++gsubst2) (gsubst1'++gsubst2') lgsubst lgsubst' (rsubst1++[(Y,R)]++rsubst2) (dsubst1++[(Y,t2)]++dsubst2) (dsubst1'++[(Y,t2')]++dsubst2')) as Hrel_sub'.\n          apply F_related_subst_dweaken; auto.\n             assert (Y `notin` dom E1') as YnE1'.\n                apply fresh_mid_head with (E:=E2') (a:=bind_kn K); auto.\n             assert (Y `notin` dom E2') as YnE2'.\n                apply fresh_mid_tail with (F:=E1') (a:=bind_kn K); auto.\n             assert (Y `notin` dom D') as YnD'.\n               apply contexting_regular in Hcontexting.\n               decompose [and] Hcontexting.\n               apply wf_lenv_notin_fv_env with (E1:=E1') (E2:=E2') (X:=Y) (K:=K) in H7; auto.\n             auto.\n\n        assert (F_Rsubst (E1'++[(Y, bind_kn K)] ++E2') (rsubst1++[(Y, R)]++rsubst2) (dsubst1++[(Y, t2)] ++dsubst2) (dsubst1'++[(Y, t2')] ++dsubst2')) as HRsub'. \n          apply F_Rsubst_dweaken; auto.       \n             assert (Y `notin` dom E1') as ynE1'.\n                apply fresh_mid_head with (E:=E2') (a:=bind_kn K); auto.\n             assert (Y `notin` dom E2') as ynE2'.\n                apply fresh_mid_tail with (F:=E1') (a:=bind_kn K); auto.\n             auto.\n\n        assert (J:=@Fry (dsubst1++[(Y, t2)]++dsubst2) (dsubst1'++[(Y, t2')]++dsubst2') (gsubst1++gsubst2) (gsubst1'++gsubst2') lgsubst lgsubst' (rsubst1++[(Y, R)]++rsubst2) Hrel_sub' HRsub').\n\n        assert (\n            apply_delta_subst (dsubst1++[(Y, t2)]++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (plug C1 e))) =\n            apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2) (apply_gamma_subst lgsubst (subst_te Y t2 (plug C1 e))))\n                  ) as Heq1. simpl.\n           simpl_env.\n           assert (wf_typ nil t2 K) as Wft2. apply wfr_left_inv in HwfR; auto.\n           apply F_related_subst__inversion in Hrel_sub'.\n           decompose [prod] Hrel_sub'; auto.\n           apply F_related_subst__inversion in Hrel_sub.\n           decompose [prod] Hrel_sub; auto.\n           rewrite delta_subst_opt' with (E':=E1') (E:=E2') (k:=K); auto.\n           rewrite swap_subst_te_gsubst with  (D:=D') (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (K:=K) (lgsubst:=lgsubst); auto.\n           rewrite swap_subst_te_lgsubst with  (D:=D') (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (K:=K) (gsubst:=gsubst1++gsubst2); auto.\n\n         assert (\n            apply_delta_subst (dsubst1'++[(Y,t2')]++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (plug C1 e'))) =\n            apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2') (apply_gamma_subst lgsubst' (subst_te Y t2' (plug C1 e'))))\n                  ) as Heq2.  simpl.\n           simpl_env.\n           assert (wf_typ nil t2' K) as Wft2. apply wfr_right_inv in HwfR; auto.\n           apply F_related_subst__inversion in Hrel_sub'.\n           decompose [prod] Hrel_sub'; auto.\n           apply F_related_subst__inversion in Hrel_sub.\n           decompose [prod] Hrel_sub; auto.\n           rewrite delta_subst_opt' with (E':=E1') (E:=E2') (k:=K); auto.\n           rewrite swap_subst_te_gsubst with  (D:=D') (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (K:=K) (lgsubst:=lgsubst'); auto.\n           rewrite swap_subst_te_lgsubst with  (D:=D') (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (K:=K) (gsubst:=gsubst1'++gsubst2'); auto.\n\n         rewrite Heq1 in J. rewrite Heq2 in J. clear Heq1 Heq2.\n         destruct J as [v [v' [Ht [Ht' [[Hbrc Hv] [[Hbrc' Hv'] Hrel]]]]]].\n         exists (v). exists (v').\n         split.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst (dsubst1++dsubst2) (apply_gamma_subst (gsubst1++gsubst2)  (apply_gamma_subst lgsubst (subst_te Y t2 (plug C1 e)))))); auto.\n              assert (apply_delta_subst_typ (dsubst1++dsubst2) t2 = t2) as Heq1.\n                 rewrite delta_subst_closed_typ with (K:=K); auto.\n                   apply wfr_left_inv in HwfR; auto.\n              rewrite <- Heq1.\n              rewrite commut_gamma_subst_tabs.\n              rewrite commut_gamma_subst_tabs.\n              assert (subst_te Y (apply_delta_subst_typ  (dsubst1++dsubst2) t2) (plug C1 e) = subst_te Y t2 (plug C1 e)) as Heq2. \n                 rewrite Heq1. auto. \n              rewrite Heq2.\n              assert (typing (E1'++[(Y, bind_kn K)]++E2') D' (plug C1 e) T1') as Typinge.\n                apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n             assert (disjdom (union {{Y}} (fv_tt t2)) (cv_ec C1)) as Disj0.\n               eapply disjdom_app_l.\n               split.\n                 apply disjdom_one_2; auto.\n                 eapply empty_wft_disjdom with (k:=K); eauto using wfr_left_inv.\n             assert (type t2) as Type2.\n               apply wfr_left_inv in HwfR.\n               apply type_from_wf_typ in HwfR; auto. \n              rewrite subst_te_plug; auto.\n              rewrite <- close_open_te__subst_te; auto.\n              assert (context C1) as Context1.\n                apply contexting__context in Hcontexting; auto.    \n              rewrite <- close_open_tc__subst_tc; auto.\n              assert (disjdom (fv_tt t2) (cv_ec (close_tc C1 Y))) as Disj.\n                eapply empty_wft_disjdom with (k:=K); eauto using wfr_left_inv.\n              rewrite <- open_te_plug; auto.\n              rewrite commut_lgamma_subst_open_te with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(gsubst:=gsubst1++gsubst2); auto.\n              rewrite commut_gamma_subst_open_te with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(lgsubst:=lgsubst); auto.\n              rewrite <- shift_te_expr; auto.\n              apply red_tabs_preserved_under_delta_subst with (dE:=E1'++E2'); auto.\n\n              rewrite <- commut_gamma_subst_tabs; auto.\n              rewrite <- commut_gamma_subst_open_te with (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (D:=D') (lgsubst:=lgsubst); auto.\n              apply red_tabs_preserved_under_gamma_subst with (E:=E1'++E2') (dsubst:=dsubst1++dsubst2) (D:=D') (lgsubst:=lgsubst); auto. \n\n              rewrite <- commut_gamma_subst_tabs; auto.\n              rewrite <- commut_lgamma_subst_open_te with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(gsubst:=gsubst1++gsubst2); auto.\n              apply red_tabs_preserved_under_lgamma_subst with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1++dsubst2)(gsubst:=gsubst1++gsubst2); auto. \n\n              apply red_tabs; auto.\n                apply expr_tabs with (L:=(cv_ec (close_tc C1 Y)) `union` cv_ec C1).\n                   intros.\n                   assert (disjdom (fv_tt X0) (cv_ec (close_tc C1 Y))) as Disj'.\n                     apply disjdom_one_2; auto.\n                   rewrite open_te_plug; auto.\n                   rewrite close_open_tc__subst_tc; auto.\n                   rewrite close_open_te__subst_te; auto.\n                  assert (disjdom (union {{Y}} (fv_tt X0)) (cv_ec C1)) as Disj0'.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjdom_one_2; auto.\n                       apply disjdom_one_2; auto.\n                   rewrite <- subst_te_plug; auto.\n\n         split; auto.\n           SSSCase \"norm\".\n           split; auto.\n           apply bigstep_red_trans with (e':=(apply_delta_subst (dsubst1'++dsubst2') (apply_gamma_subst (gsubst1'++gsubst2')  (apply_gamma_subst lgsubst' (subst_te Y t2' (plug C1 e')))))); auto.\n              assert (apply_delta_subst_typ (dsubst1'++dsubst2') t2' = t2') as Heq1.\n                 rewrite delta_subst_closed_typ with (K:=K); auto.\n                   apply wfr_right_inv in HwfR; auto.\n              rewrite <- Heq1.\n              rewrite commut_gamma_subst_tabs.\n              rewrite commut_gamma_subst_tabs.\n              assert (subst_te Y (apply_delta_subst_typ  (dsubst1'++dsubst2') t2') (plug C1 e') = subst_te Y t2' (plug C1 e')) as Heq2. \n                 rewrite Heq1. auto. \n              rewrite Heq2.\n              assert (typing (E1'++[(Y, bind_kn K)]++E2') D' (plug C1 e') T1') as Typinge'.\n                apply contexting_plug_typing with (E:=E) (D:=D) (T:=T); auto.\n             assert (disjdom (union {{Y}} (fv_tt t2')) (cv_ec C1)) as Disj0.\n               eapply disjdom_app_l.\n               split.\n                 apply disjdom_one_2; auto.\n                 eapply empty_wft_disjdom with (k:=K); eauto using wfr_right_inv.\n             assert (type t2') as Type2'.\n               apply wfr_right_inv in HwfR.\n               apply type_from_wf_typ in HwfR; auto. \n              rewrite subst_te_plug; auto.\n              rewrite <- close_open_te__subst_te; auto.\n              assert (context C1) as Context1.\n                apply contexting__context in Hcontexting; auto.    \n              rewrite <- close_open_tc__subst_tc; auto.\n              assert (disjdom (fv_tt t2') (cv_ec (close_tc C1 Y))) as Disj.\n                eapply empty_wft_disjdom with (k:=K); eauto using wfr_right_inv.\n              rewrite <- open_te_plug; auto.\n              rewrite commut_lgamma_subst_open_te with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(gsubst:=gsubst1'++gsubst2'); auto.\n              rewrite commut_gamma_subst_open_te with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(lgsubst:=lgsubst'); auto.\n              rewrite <- shift_te_expr; auto.\n              apply red_tabs_preserved_under_delta_subst with (dE:=E1'++E2'); auto.\n\n              rewrite <- commut_gamma_subst_tabs; auto.\n              rewrite <- commut_gamma_subst_open_te with (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (D:=D') (lgsubst:=lgsubst'); auto.\n              apply red_tabs_preserved_under_gamma_subst with (E:=E1'++E2') (dsubst:=dsubst1'++dsubst2') (D:=D') (lgsubst:=lgsubst'); auto. \n\n              rewrite <- commut_gamma_subst_tabs; auto.\n              rewrite <- commut_lgamma_subst_open_te with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(gsubst:=gsubst1'++gsubst2'); auto.\n              apply red_tabs_preserved_under_lgamma_subst with (E:=E1'++E2')(D:=D')(dsubst:=dsubst1'++dsubst2')(gsubst:=gsubst1'++gsubst2'); auto. \n\n              apply red_tabs; auto.\n                apply expr_tabs with (L:=(cv_ec (close_tc C1 Y)) `union` cv_ec C1).\n                   intros.\n                   assert (disjdom (fv_tt X0) (cv_ec (close_tc C1 Y))) as Disj'.\n                     apply disjdom_one_2; auto.\n                   rewrite open_te_plug; auto.\n                   rewrite close_open_tc__subst_tc; auto.\n                   rewrite close_open_te__subst_te; auto.\n                  assert (disjdom (union {{Y}} (fv_tt X0)) (cv_ec C1)) as Disj0'.\n                     eapply disjdom_app_l.\n                     split.\n                       apply disjdom_one_2; auto.\n                       apply disjdom_one_2; auto.\n                   rewrite <- subst_te_plug; auto.\n\n               simpl_env.\n               rewrite close_open_tt__subst_tt; auto.\n                 assert (wf_delta_subst ([(X, bind_kn K)]++E1'++E2') ([(X, t2)]++dsubst1++dsubst2)) as Wfd.\n                   apply F_Rsubst__wf_subst in HRsub.\n                   decompose [prod] HRsub.\n                   eapply dsubst_weaken_head; simpl_env; eauto using wfr_left_inv.\n\n                 assert (wf_delta_subst ([(X, bind_kn K)]++E1'++E2') ([(X, t2')]++dsubst1'++dsubst2')) as Wfd'.\n                   apply F_Rsubst__wf_subst in HRsub.\n                   decompose [prod] HRsub.\n                   eapply dsubst_weaken_head; simpl_env; eauto using wfr_right_inv.\n\n                 apply F_Rsubst__wf_subst in HRsub'.\n                 decompose [prod] HRsub'; auto.\n                 apply Frel_typ_permute_renaming_one with (E1:=E1')(E2:=E2')(K:=K) (X:=Y); auto.\n               \n                 apply contexting_regular in Hcontexting.\n                 decompose [and] Hcontexting.\n                 apply type_from_wf_typ in H9; auto.\nQed.\n\nLemma F_logical_related_congruence__tapp :\n  forall e e' E D T,\n  typing E D e T ->\n  typing E D e' T ->\n  (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n   F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n   F_Rsubst E rsubst dsubst dsubst' ->\n   F_related_terms T rsubst dsubst dsubst' \n     (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n     (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n  ) ->\n  forall K  C1 T' T2' E' D',\n  contexting E D T C1 E' D' (typ_all K T2') ->\n  wf_typ E' T' K ->\n  (typing E D e T ->\n   typing E D e' T ->\n    (forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E D gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E rsubst dsubst dsubst' ->\n     F_related_terms T rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e)))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e')))\n    ) ->\n   forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n     F_related_subst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n     F_Rsubst E' rsubst dsubst dsubst' ->\n     F_related_terms (typ_all K T2') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n  ) ->\n  forall dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst,\n  F_related_subst E' D' gsubst gsubst' lgsubst lgsubst' rsubst dsubst dsubst' ->\n  F_Rsubst E' rsubst dsubst dsubst' ->\n  F_related_terms (open_tt T2' T') rsubst dsubst dsubst' \n      (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_tapp (plug C1 e) T'))))\n      (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_tapp (plug C1 e') T')))).\nProof.\n   intros e e' E D T Htyp Htyp' Hlr K C1 T' T2' E' D' Hcontexting H IHHcontexting dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Hrel_sub HRsub.  \n   assert (J:=Hrel_sub). apply F_related_subst__inversion in J. \n   destruct J as [[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe].\n   assert (\n      F_related_terms (typ_all K T2') rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n     ) as FR_AllType.\n      apply IHHcontexting; auto.\n   destruct FR_AllType as [v [v' [Ht [Ht' [Hn [Hn' Hrel]]]]]].\n\n   apply F_related_values_all_leq in Hrel.\n   destruct Hrel as [Hv [Hv' [L Hall]]]; subst.\n   unfold open_tt in Hall.\n\n   assert (forall X,\n     X `notin` dom (E') `union` fv_tt T2' ->\n     wf_typ ([(X, bind_kn K)]++E') (open_tt T2' X) kn_lin) as w.\n     apply contexting_regular in Hcontexting.\n     destruct Hcontexting as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n     eapply wft_all_inv; eauto.\n\n   pick fresh y.\n   assert (y `notin` L) as Fr'. auto.\n   destruct (@Hall y (apply_delta_subst_typ dsubst T') (apply_delta_subst_typ dsubst' T') \n                                (F_Rel T' (rho_nil++rsubst) (delta_nil++dsubst) (delta_nil++dsubst'))\n                                Fr'\n                   ) as [u [u' [Hn_vt2u [Hn_v't2'u' Hrel_wft]]]]; auto.\n          split; try solve [apply wft_subst with (E:=E'); auto].\n              assert (ddom_env E' [=] dom rsubst) as EQ.\n                apply dom_rho_subst; auto.\n              assert (y `notin` ddom_env E') as Fv.\n                 apply dom__ddom; auto.\n              rewrite EQ in Fv. auto.\n\n   exists(u). exists (u').\n       split. simpl_commut_subst in *; rewrite commut_delta_subst_open_tt with (dE:=E'); auto.\n                eapply typing_tapp; eauto using wft_subst.\n       split. simpl_commut_subst in *; rewrite commut_delta_subst_open_tt with (dE:=E'); auto.\n                eapply typing_tapp; eauto using wft_subst.\n       split.\n       SCase \"Norm\".\n       simpl_commut_subst.\n       eapply m_congr_tapp; eauto.\n\n      split.\n      SCase \"Norm\".\n      simpl_commut_subst.\n      eapply m_congr_tapp; eauto.\n\n      SCase \"Frel\".\n      unfold open_tt.\n      assert (F_related_values (open_tt_rec 0 T' T2') (rho_nil++rsubst) (delta_nil++dsubst) (delta_nil++dsubst') u u' =\n                  F_related_values (open_tt_rec 0 T' T2') rsubst dsubst dsubst' u u').\n         simpl. reflexivity.\n      rewrite <- H0.\n      apply parametricity_subst_value with\n                (E:=E') (E':=@nil (atom*binding))\n                (rsubst:=rsubst) (rsubst':=rho_nil)\n                (k:=0)\n                (t:=T2') (t2:=T') (K:=kn_lin) (Q:=K)\n                (X:=y) (R:=(F_Rel T' (rho_nil++rsubst) (delta_nil++dsubst) (delta_nil++dsubst')))\n                ; auto.\n        SSCase \"wft\".\n          simpl_env. unfold open_tt in w. apply w; auto.\n\n        SSCase \"wft\".\n          simpl_env. rewrite subst_tt_intro_rec with (X:=y); auto.\n          rewrite_env (map (subst_tb y T') nil ++ E').\n          eapply wf_typ_subst_tb with (Q:=K); auto.\n          apply w; auto.\n\n        SSCase \"Rel__R\".\n        unfold F_Rel__R. split; auto.\n\n        SSCase \"fv\".\n        eapply m_tapp_fv with (dsubst:=dsubst) (dsubst':=dsubst') (v:=v) (v':=v'); \n           eauto using notin_fv_te_typing.\n\n        SSCase \"eq\".\n        apply dom_delta_subst; auto.\n        apply dom_delta_subst; auto.\n        apply dom_rho_subst; auto.\n        SSCase \"rsubst\".\n        eapply rsubst_weaken with (X:=y) (rsubst:=rsubst) (rsubst':=rho_nil); eauto.\n          apply dom_rho_subst; auto.\n        SSCase \"dsubst\".   \n        apply dsubst_weaken with (X:=y) (K:=K) (dsubst:=dsubst) (dsubst':=delta_nil) (t:=(apply_delta_subst_typ dsubst T')); auto.\n          apply wft_subst_closed with (E:=E') (E':=@nil (atom*binding)) (dsubst:=dsubst) ; auto.\n          apply dom_delta_subst in Hwfd; auto.\n        SSCase \"dsubst'\".\n        apply dsubst_weaken with (X:=y) (K:=K) (dsubst:=dsubst') (dsubst':=delta_nil) (t:=(apply_delta_subst_typ dsubst' T')); auto.\n          apply wft_subst_closed with (E:=E') (E':=@nil (atom*binding)) (dsubst:=dsubst'); auto.\n          apply dom_delta_subst in Hwfd'; auto.\nQed.\n\nLemma F_logical_related_congruence : forall E lE e e' t C E' lE' t',\n  F_logical_related E lE e e' t ->\n  contexting E lE t C E' lE' t' ->\n  F_logical_related E' lE' (plug C e) (plug C e') t'.\nProof.\n  intros E lE e e' t C E' lE' t' Hlr Hcontexting.\n  destruct Hlr as [Htyp [Htyp' Hlr]]. \n  split. apply contexting_plug_typing with (e:=e) in Hcontexting; auto.\n  split. apply contexting_plug_typing with (e:=e') in Hcontexting; auto.\n  (contexting_cases (induction Hcontexting) Case); \n    intros dsubst dsubst' gsubst gsubst' lgsubst lgsubst' rsubst Hrel_sub HRsub; simpl in *; auto.\n  Case \"contexting_abs_free\".\n    apply F_logical_related_congruence__abs_free with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (L:=L) (K:=K) (T1':=T1') (C1:=C1) (T2':=T2') (E':=E') (D':=D') \n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst); assumption.\n\n  Case \"contexting_labs_free\". \n    apply F_logical_related_congruence__labs_free with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (L:=L) (K:=K) (T1':=T1') (C1:=C1) (T2':=T2') (E':=E') (D':=D') \n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst); assumption.\n\n  Case \"contexting_abs_capture\". \n    apply F_logical_related_congruence__abs_capture with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (K:=K) (y:=y) (T1':=T1') (C1:=C1) (T2':=T2') (E':=E') (D':=D') \n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst); assumption.\n\n  Case \"contexting_labs_capture\". \n    apply F_logical_related_congruence__labs_capture with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (K:=K) (y:=y) (T1':=T1') (C1:=C1) (T2':=T2') (E':=E') (D':=D') \n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst); assumption.\n\n  Case \"contexting_app1\". \n    apply F_logical_related_congruence__app1 with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (K:=K) (T1':=T1') (C1:=C1) (T2':=T2') (E':=E') (D1':=D1')  (D2':=D2')  (D3':=D3') \n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst); assumption.\n\n  Case \"contexting_app2\". \n    apply F_logical_related_congruence__app2 with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (K:=K) (T1':=T1') (C2:=C2) (T2':=T2') (E':=E') (D1':=D1')  (D2':=D2')  (D3':=D3') \n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst); assumption.\n\n   Case \"contexting_tabs_free\".\n     apply F_logical_related_congruence__tabs_free with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (K:=K) (L:=L) (T1':=T1') (C1:=C1) (E':=E') (D':=D')\n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst); assumption.\n\n   Case \"contexting_tabs_capture\".\n    apply F_logical_related_congruence__tabs_capture with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (K:=K) (T1':=T1') (C1:=C1) (E':=E') (D':=D')\n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst); assumption.\n\n   Case \"contexting_tapp\".\n    apply F_logical_related_congruence__tapp with \n     (e:=e) (e':=e') (E:=E) (D:=D) (T:=T) (K:=K) (T':=T') (C1:=C1) (E':=E') (D':=D')\n     (dsubst:=dsubst) (dsubst':=dsubst') (gsubst:=gsubst) (gsubst':=gsubst') (lgsubst:=lgsubst) (lgsubst':=lgsubst') (rsubst:=rsubst); assumption.\n\n    Case \"contexting_apair1\".\n    assert (J:=Hrel_sub). apply F_related_subst__inversion in J. decompose [prod] J. clear J.\n\n    assert (\n      F_related_terms T1' rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n     ) as FR_T1.\n       apply IHHcontexting; auto.\n    destruct FR_T1 as [v [v' [Ht1 [Ht1' [Hn1 [Hn1' Hrel1]]]]]].\n\n    assert (\n      F_related_terms T2' rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e2)))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e2)))\n     ) as FR_T2.\n       apply parametricity with (E:=E') (lE:=D'); auto.\n    destruct FR_T2 as [v0 [v'0 [Ht2 [Ht2' [Hn2 [Hn2' Hrel2]]]]]].\n\n    exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_apair (plug C1 e)  e2)))).\n    exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_apair (plug C1 e') e2)))).\n    split; simpl_commut_subst; auto.\n    split; simpl_commut_subst; auto.\n    split. split; simpl_commut_subst; auto.\n    split. split; simpl_commut_subst; auto.\n      SCase \"Frel\".\n        SSCase \"Frel\".\n        apply F_related_values_with_req.\n        repeat (split; simpl_commut_subst; auto).\n        exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e)))).\n        exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e2))).\n        exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e')))).\n        exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e2))).\n        repeat(split; auto).\n          exists (v). exists (v'). split; auto.\n          exists (v0). exists (v'0). split; auto.\n\n    Case \"contexting_apair2\".\n    assert (J:=Hrel_sub). apply F_related_subst__inversion in J. decompose [prod] J. clear J.\n\n    assert (\n      F_related_terms T1' rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e1)))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e1)))\n     ) as FR_T1.\n       apply parametricity with (E:=E') (lE:=D'); auto.\n    destruct FR_T1 as [v [v' [Ht1 [Ht1' [Hn1 [Hn1' Hrel1]]]]]].\n\n    assert (\n      F_related_terms T2' rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C2 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C2 e'))))\n     ) as FR_T2.\n       apply IHHcontexting; auto.\n    destruct FR_T2 as [v0 [v'0 [Ht2 [Ht2' [Hn2 [Hn2' Hrel2]]]]]].\n\n    exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (exp_apair e1 (plug C2 e))))).\n    exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (exp_apair e1 (plug C2 e'))))).\n    split; simpl_commut_subst; auto.\n    split; simpl_commut_subst; auto.\n    split. split; simpl_commut_subst; auto.\n    split. split; simpl_commut_subst; auto.\n      SCase \"Frel\".\n        SSCase \"Frel\".\n        apply F_related_values_with_req.\n        repeat (split; simpl_commut_subst; auto).\n        exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst e1))).\n        exists (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C2 e)))).\n        exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' e1))).\n        exists (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C2 e')))).\n        repeat(split; auto).\n          exists (v). exists (v'). split; auto.\n          exists (v0). exists (v'0). split; auto.\n\n    Case \"contexting_fst\".\n    assert (J:=Hrel_sub). apply F_related_subst__inversion in J.\n    destruct J as [[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe].\n    assert (wf_typ E' (typ_with T1' T2') kn_lin) as WFTwith.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (\n      F_related_terms (typ_with T1' T2') rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n     ) as FR_With.\n       apply IHHcontexting; auto.\n    destruct FR_With as [ee1 [ee1' [Ht [Ht' [Hn [Hn' FR_With]]]]]].\n\n    simpl_commut_subst in Ht. simpl_commut_subst in Ht'. \n    apply congr_fst with (T1:=apply_delta_subst_typ dsubst T1') (T2:=apply_delta_subst_typ dsubst T2') in Hn; auto.\n    apply congr_fst with (T1:=apply_delta_subst_typ dsubst' T1') (T2:=apply_delta_subst_typ dsubst' T2') in Hn'; auto.\n    destruct Hn as [e1 [e2 [Hbrc Heq]]].\n    destruct Hn' as [e1' [e2' [Hbrc' Heq']]].\n    apply F_related_values_with_leq in FR_With.\n    subst.\n    destruct FR_With as [Hv [Hv' [ee1 [ee2 [ee1' [ee2' [Heq [Heq' \n                                [[u1 [u1' [[Hbrc_e1u1 Hu1][[Hbrc_e1'u1' Hu1'] Hrel_wft1]]]] \n                                 [u2 [u2' [[Hbrc_e2u2 Hu2][[Hbrc_e2'u2' Hu2'] Hrel_wft2]]]]]\n                              ]]]]]]]]; subst.\n    inversion Heq. inversion Heq'. subst. clear Heq Heq'.\n    exists(u1). exists(u1').\n        repeat(split; simpl_commut_subst; auto; try solve [\n          apply typing_fst with (T2:=apply_delta_subst_typ dsubst T2'); auto |\n          apply typing_fst with (T2:=apply_delta_subst_typ dsubst' T2');auto |\n          split; auto; apply bigstep_red__trans with (e':=ee1); auto |\n          split; auto; apply bigstep_red__trans with (e':=ee1'); auto]).\n\n    Case \"contexting_snd\".\n    assert (J:=Hrel_sub). apply F_related_subst__inversion in J.\n    destruct J as [[[[[Hwfd Hwfd'] Hwflg] Hwflg'] Hwfr] Hwfe].\n    assert (wf_typ E' (typ_with T1' T2') kn_lin) as WFTwith.\n      apply contexting_regular in Hcontexting.\n      decompose [and] Hcontexting; auto.\n    assert (\n      F_related_terms (typ_with T1' T2') rsubst dsubst dsubst'\n         (apply_delta_subst dsubst (apply_gamma_subst gsubst (apply_gamma_subst lgsubst (plug C1 e))))\n         (apply_delta_subst dsubst' (apply_gamma_subst gsubst' (apply_gamma_subst lgsubst' (plug C1 e'))))\n     ) as FR_With.\n       apply IHHcontexting; auto.\n    destruct FR_With as [ee2 [ee2' [Ht [Ht' [Hn [Hn' FR_With]]]]]].\n\n    simpl_commut_subst in Ht. simpl_commut_subst in Ht'. \n    apply congr_snd with (T1:=apply_delta_subst_typ dsubst T1') (T2:=apply_delta_subst_typ dsubst T2') in Hn; auto.\n    apply congr_snd with (T1:=apply_delta_subst_typ dsubst' T1') (T2:=apply_delta_subst_typ dsubst' T2') in Hn'; auto.\n    destruct Hn as [e1 [e2 [Hbrc Heq]]].\n    destruct Hn' as [e1' [e2' [Hbrc' Heq']]].\n    apply F_related_values_with_leq in FR_With.\n    subst.\n    destruct FR_With as [Hv [Hv' [ee1 [ee2 [ee1' [ee2' [Heq [Heq' \n                                [[u1 [u1' [[Hbrc_e1u1 Hu1][[Hbrc_e1'u1' Hu1'] Hrel_wft1]]]] \n                                 [u2 [u2' [[Hbrc_e2u2 Hu2][[Hbrc_e2'u2' Hu2'] Hrel_wft2]]]]]\n                              ]]]]]]]]; subst.\n    inversion Heq. inversion Heq'. subst. clear Heq Heq'.\n    exists (u2). exists (u2').\n        repeat(split; simpl_commut_subst; auto; try solve [\n          apply typing_snd with (T1:=apply_delta_subst_typ dsubst T1'); auto |\n          apply typing_snd with (T1:=apply_delta_subst_typ dsubst' T1'); auto |\n          split; auto; apply bigstep_red__trans with (e':=ee2); auto |\n          split; auto; apply bigstep_red__trans with (e':=ee2'); auto]).\nQed.\n\nLemma F_Rsubst_refl : forall E rsubst dsubst,\n  wf_rho_subst E rsubst ->\n  wf_delta_subst E dsubst ->\n  F_Rsubst E rsubst dsubst dsubst.\nProof.\n  induction E; intros rsubst dsubst Hwfr Hwfd.\n     inversion Hwfr; subst.\n     inversion Hwfd; subst. auto.\n\n     destruct a.\n     inversion Hwfr; subst.\n       inversion Hwfd; subst. simpl_env in *.\n       apply F_Rsubst_rel; auto.\n         unfold wfr. split; auto.\n         apply notin_wf_env; auto.\n           apply wf_delta_subst__uniq in H2. decompose [and] H2; auto.\n\n       inversion Hwfd; subst. simpl_env in *.\n       apply F_Rsubst_typ; auto.\n         apply notin_wf_env; auto.\n           apply wf_delta_subst__uniq in H3. decompose [and] H3; auto.\nQed.\n\nLemma F_related_subst_refl : forall E rsubst dsubst,\n  wf_rho_subst E rsubst ->\n  wf_delta_subst E dsubst ->\n  gdom_env E [=] {} ->\n  F_related_subst E nil nil nil nil nil rsubst dsubst dsubst.\nProof.\n  induction E; intros rsubst dsubst Hwfr Hwfd EQ.\n     inversion Hwfr; subst.\n     inversion Hwfd; subst. auto.\n\n     destruct a.\n     inversion Hwfr; subst; simpl in EQ.\n       inversion Hwfd; subst. simpl_env in *.\n       apply F_related_subst_kind; auto.\n         apply notin_wf_env in H6; auto.\n           apply wf_delta_subst__uniq in H2. decompose [and] H2; auto.\n \n         unfold wfr. split; auto.\n \n       assert (a `in` Metatheory.empty) as FALSE.\n         rewrite <- EQ. auto.\n       contradict FALSE; auto.\nQed.\n\nAxiom F_related_values__consistent : forall v v',\n  F_related_values Two nil nil nil v v' ->\n  ((v = tt /\\ v' =tt) \\/ (v = ff /\\ v' =ff)).\n\nRequire Import LinF_Parametricity_App.\n\nLemma wf_delta_subst__wf_rho_subst : forall E dsubst,\n  wf_delta_subst E dsubst ->\n  exists rsubst, wf_rho_subst E rsubst.\nProof.\n  intros E dsubst H.\n  induction H.\n    exists nil. auto.\n\n    destruct IHwf_delta_subst as [rsubst Hwfr].\n    exists ([(X, Rid T)]++rsubst).\n    apply wf_rho_subst_srel; auto.\n\n    destruct IHwf_delta_subst as [rsubst Hwfr].\n    exists (rsubst). auto.\nQed.\n\nLemma F_logical_related__sound : forall E lE e e' t,\n  F_logical_related E lE e e' t ->\n  F_observational_eq E lE e e' t.\nProof.\n  intros E lE e e' t Hlr.\n  assert (J:=Hlr).\n  destruct J as [Htyp [Htyp' J]].\n  split; auto.\n  split; auto.\n    intros C Hcontext.\n    apply F_logical_related_congruence with (C:=C) (E':=nil) (lE':=nil) (t':=Two) in Hlr; auto.\n    split. eapply contexting_plug_typing; eauto.\n    split. eapply contexting_plug_typing; eauto.\n      assert (F_Rsubst nil nil nil nil) as J1. auto.\n      assert (F_related_subst nil nil nil nil nil nil nil nil nil) as J2. auto.\n      destruct Hlr as [Htyp1 [Htyp1' Hlr]].\n      assert (Hrel:=@Hlr nil nil nil nil nil nil nil J2 J1).\n      destruct Hrel as [v [v' [Htypv [Htypv' [Hn [Hn' Hrel]]]]]].\n      simpl in *.\n      assert (JJ:=@F_related_values__consistent v v' Hrel).\n      destruct JJ as [[EQ EQ'] | [EQ EQ']]; subst; auto.\nQed.\n", "meta": {"author": "Zdancewic", "repo": "linearity", "sha": "b2662939b2e8fb8fbe34f7ec0d3c69ef1bdff916", "save_path": "github-repos/coq/Zdancewic-linearity", "path": "github-repos/coq/Zdancewic-linearity/linearity-b2662939b2e8fb8fbe34f7ec0d3c69ef1bdff916/parametricity/LinF_ContextualEq_Sound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2223319673104275}}
{"text": "Require Import Platform.AutoSep Platform.Malloc Platform.Arrays8 Platform.MoreArrays.\n\n\nDefinition bmallocS : spec := SPEC(\"n\") reserving 8\n  PRE[V] [| V \"n\" >= $2 |] * mallocHeap 0\n  POST[R] [| R <> 0 |] * [| freeable R (wordToNat (V \"n\")) |]\n    * R =?>8 (wordToNat (V \"n\") * 4) * mallocHeap 0.\n\nDefinition bfreeS : spec := SPEC(\"p\", \"n\") reserving 6\n  PRE[V] [| V \"p\" <> 0 |] * [| freeable (V \"p\") (wordToNat (V \"n\")) |]\n    * V \"p\" =?>8 (wordToNat (V \"n\") * 4) * mallocHeap 0\n  POST[_] mallocHeap 0.\n\nDefinition containsS : spec := SPEC(\"haystack\", \"len\", \"needle\") reserving 2\n  PRE[V] V \"haystack\" =?>8 wordToNat (V \"len\")\n  POST[_] V \"haystack\" =?>8 wordToNat (V \"len\").\n\nDefinition copyS : spec := SPEC(\"dst\", \"src\", \"srcLen\") reserving 2\n  Al dstLen,\n  PRE[V] V \"dst\" =?>8 wordToNat dstLen * V \"src\" =?>8 wordToNat (V \"srcLen\") * [| V \"srcLen\" <= dstLen |]\n  POST[_] V \"dst\" =?>8 wordToNat dstLen * V \"src\" =?>8 wordToNat (V \"srcLen\").\n\nInductive debufferize : Prop := Debufferize.\nHint Constructors debufferize.\n\nDefinition neg1 : W := wones _.\n\nDefinition m := bimport [[ \"sys\"!\"abort\" @ [abortS],\n                           \"malloc\"!\"malloc\" @ [mallocS], \"malloc\"!\"free\" @ [freeS] ]]\n  bmodule \"buffers\" {{\n    bfunction \"bmalloc\"(\"n\", \"r\") [bmallocS]\n      \"r\" <-- Call \"malloc\"!\"malloc\"(0, \"n\")\n      [PRE[_, R] Emp\n       POST[R'] [| R' = R |] ];;\n      Return \"r\"\n    end with bfunction \"bfree\"(\"p\", \"n\") [bfreeS]\n      Assert [PRE[V] [| V \"p\" <> 0 |] * [| freeable (V \"p\") (wordToNat (V \"n\")) |]\n        * V \"p\" =?> wordToNat (V \"n\") * mallocHeap 0\n        POST[_] mallocHeap 0];;\n\n      Call \"malloc\"!\"free\"(0, \"p\", \"n\")\n      [PRE[_] Emp\n       POST[_] Emp ];;\n      Return 0\n    end with bfunction \"contains\"(\"haystack\", \"len\", \"needle\", \"i\", \"tmp\") [containsS]\n      Note [debufferize];;\n\n      Assert [Al bs, PRE[V] array8 bs (V \"haystack\") * [| length bs = wordToNat (V \"len\") |]\n        POST[_] array8 bs (V \"haystack\")];;\n\n      \"i\" <- 0;;\n\n      [Al bs, PRE[V] array8 bs (V \"haystack\") * [| length bs = wordToNat (V \"len\") |]\n        POST[_] array8 bs (V \"haystack\")]\n      While (\"i\" < \"len\") {\n        Assert [Al bs, PRE[V] array8 bs (V \"haystack\") * [| length bs = wordToNat (V \"len\") |]\n          * [| (V \"i\" < natToW (length bs))%word |]\n          POST[_] array8 bs (V \"haystack\")];;\n\n        \"tmp\" <-*8 \"haystack\" + \"i\";;\n        If (\"tmp\" = \"needle\") {\n          Return \"i\"\n        } else {\n          \"i\" <- \"i\" + 1\n        }\n      };;\n\n      Return neg1\n    end with bfunction \"copy\"(\"dst\", \"src\", \"srcLen\", \"i\", \"tmp\") [copyS]\n      Note [debufferize];;\n\n      Assert [Al src, Al dst,\n        PRE[V] array8 dst (V \"dst\") * array8 src (V \"src\")\n          * [| length src = wordToNat (V \"srcLen\") |] * [| (wordToNat (V \"srcLen\") <= length dst)%nat |]\n          * [| goodSize (length dst) |]\n        POST[_] Ex dst', array8 dst' (V \"dst\") * array8 src (V \"src\")\n          * [| length dst' = length dst |] ];;\n\n      \"i\" <- 0;;\n\n      [Al src, Al dst,\n        PRE[V] array8 dst (V \"dst\") * array8 src (V \"src\") * [| (wordToNat (V \"srcLen\") <= length dst)%nat |]\n          * [| length src = wordToNat (V \"srcLen\") |]\n          * [| goodSize (length dst) |]\n        POST[_] Ex dst', array8 dst' (V \"dst\") * array8 src (V \"src\")\n          * [| length dst' = length dst |] ]\n      While (\"i\" < \"srcLen\") {\n        Assert [Al src, Al dst,\n          PRE[V] array8 dst (V \"dst\") * array8 src (V \"src\") * [| (wordToNat (V \"srcLen\") <= length dst)%nat |]\n            * [| length src = wordToNat (V \"srcLen\") |] * [| goodSize (length dst) |]\n            * [| (V \"i\" < natToW (length dst))%word |] * [| (V \"i\" < natToW (length src))%word |]\n          POST[_] Ex dst', array8 dst' (V \"dst\") * array8 src (V \"src\")\n            * [| length dst' = length dst |] ];;\n\n        \"tmp\" <-*8 \"src\" + \"i\";;\n        \"dst\" + \"i\" *<-8 \"tmp\";;\n        \"i\" <- \"i\" + 1\n      };;\n\n      Return 0\n    end\n  }}.\n\nTheorem dematerialize_buffer : forall p n, p =?>8 (n * 4) ===> p =?> n.\n  unfold buffer; sepLemma; apply decomission_array8; auto.\nQed.\n\nLtac finish :=\n  repeat match goal with\n           | [ H : _ = _ |- _ ] => rewrite H\n         end; try apply materialize_array8;\n  try (etransitivity; [ apply himp_star_comm | apply himp_star_frame; reflexivity || apply dematerialize_buffer ]);\n    try rewrite natToW_wordToNat; try rewrite length_upd; auto; try nomega.\n\nLtac t :=\n  try match goal with\n        | [ |- context[debufferize] ] => unfold buffer\n      end; sep_auto; finish.\n\nLocal Hint Extern 1 (@eq W _ _) => words.\n\nTheorem ok : moduleOk m.\n  vcgen; abstract t.\nQed.\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Buffers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22233196731042748}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation, either version 2 of the License, or  *)\n(*  (at your option) any later version.  This file is also distributed *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Constructions of ordered types, for use with the [FSet] functors\n  for finite sets and the [FMap] functors for finite maps. *)\n\nRequire Import FSets.\nRequire Import Coqlib.\nRequire Import Maps.\n(* Require Import Integers. *)\n\n(** The ordered type of positive numbers *)\n\nModule OrderedPositive <: OrderedType.\n\nDefinition t := positive.\nDefinition eq (x y: t) := x = y.\nDefinition lt := Plt.\n\nLemma eq_refl : forall x : t, eq x x.\nProof (@eq_refl t).\nLemma eq_sym : forall x y : t, eq x y -> eq y x.\nProof (@eq_sym t).\nLemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z.\nProof (@eq_trans t).\nLemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z.\nProof Plt_trans.\nLemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y.\nProof Plt_ne.\nLemma compare : forall x y : t, Compare lt eq x y.\nProof.\n  intros. destruct (Pos.compare x y) as [] eqn:E.\n  apply EQ. red. apply Pos.compare_eq_iff. assumption.\n  apply LT. assumption.\n  apply GT. apply Pos.compare_gt_iff. assumption.\nDefined.\n\nDefinition eq_dec : forall x y, { eq x y } + { ~ eq x y } := peq.\n\nEnd OrderedPositive.\n\n(** The ordered type of integers *)\n\n(* Module OrderedZ <: OrderedType. *)\n\n(* Definition t := Z. *)\n(* Definition eq (x y: t) := x = y. *)\n(* Definition lt := Z.lt. *)\n\n(* Lemma eq_refl : forall x : t, eq x x. *)\n(* Proof (@eq_refl t). *)\n(* Lemma eq_sym : forall x y : t, eq x y -> eq y x. *)\n(* Proof (@eq_sym t). *)\n(* Lemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z. *)\n(* Proof (@eq_trans t). *)\n(* Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z. *)\n(* Proof Z.lt_trans. *)\n(* Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y. *)\n(* Proof. unfold lt, eq, t; intros. omega. Qed. *)\n(* Lemma compare : forall x y : t, Compare lt eq x y. *)\n(* Proof. *)\n(*   intros. destruct (Z.compare x y) as [] eqn:E. *)\n(*   apply EQ. red. apply Z.compare_eq_iff. assumption. *)\n(*   apply LT. assumption. *)\n(*   apply GT. apply Z.compare_gt_iff. assumption. *)\n(* Defined. *)\n\n(* Definition eq_dec : forall x y, { eq x y } + { ~ eq x y } := zeq. *)\n\n(* End OrderedZ. *)\n\n(* (** The ordered type of machine integers *) *)\n\n(* Module OrderedInt <: OrderedType. *)\n\n(* Definition t := int. *)\n(* Definition eq (x y: t) := x = y. *)\n(* Definition lt (x y: t) := Int.unsigned x < Int.unsigned y. *)\n\n(* Lemma eq_refl : forall x : t, eq x x. *)\n(* Proof (@eq_refl t). *)\n(* Lemma eq_sym : forall x y : t, eq x y -> eq y x. *)\n(* Proof (@eq_sym t). *)\n(* Lemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z. *)\n(* Proof (@eq_trans t). *)\n(* Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z. *)\n(* Proof. *)\n(*   unfold lt; intros. omega. *)\n(* Qed. *)\n(* Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y. *)\n(* Proof. *)\n(*   unfold lt,eq; intros; red; intros. subst. omega. *)\n(* Qed. *)\n(* Lemma compare : forall x y : t, Compare lt eq x y. *)\n(* Proof. *)\n(*   intros. destruct (zlt (Int.unsigned x) (Int.unsigned y)). *)\n(*   apply LT. auto. *)\n(*   destruct (Int.eq_dec x y). *)\n(*   apply EQ. auto. *)\n(*   apply GT. *)\n(*   assert (Int.unsigned x <> Int.unsigned y). *)\n(*     red; intros. rewrite <- (Int.repr_unsigned x) in n. rewrite <- (Int.repr_unsigned y) in n. congruence. *)\n(*   red. omega. *)\n(* Defined. *)\n\n(* Definition eq_dec : forall x y, { eq x y } + { ~ eq x y } := Int.eq_dec. *)\n\n(* End OrderedInt. *)\n\n(* (** Indexed types (those that inject into [positive]) are ordered. *) *)\n\n(* Module OrderedIndexed(A: INDEXED_TYPE) <: OrderedType. *)\n\n(* Definition t := A.t. *)\n(* Definition eq (x y: t) := x = y. *)\n(* Definition lt (x y: t) := Plt (A.index x) (A.index y). *)\n\n(* Lemma eq_refl : forall x : t, eq x x. *)\n(* Proof (@eq_refl t). *)\n(* Lemma eq_sym : forall x y : t, eq x y -> eq y x. *)\n(* Proof (@eq_sym t). *)\n(* Lemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z. *)\n(* Proof (@eq_trans t). *)\n\n(* Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z. *)\n(* Proof. *)\n(*   unfold lt; intros. eapply Plt_trans; eauto. *)\n(* Qed. *)\n\n(* Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y. *)\n(* Proof. *)\n(*   unfold lt; unfold eq; intros. *)\n(*   red; intro. subst y. apply Plt_strict with (A.index x). auto. *)\n(* Qed. *)\n\n(* Lemma compare : forall x y : t, Compare lt eq x y. *)\n(* Proof. *)\n(*   intros. case (OrderedPositive.compare (A.index x) (A.index y)); intro. *)\n(*   apply LT. exact l. *)\n(*   apply EQ. red; red in e. apply A.index_inj; auto. *)\n(*   apply GT. exact l. *)\n(* Defined. *)\n\n(* Lemma eq_dec : forall x y, { eq x y } + { ~ eq x y }. *)\n(* Proof. *)\n(*   intros. case (peq (A.index x) (A.index y)); intros. *)\n(*   left. apply A.index_inj; auto. *)\n(*   right; red; unfold eq; intros; subst. congruence. *)\n(* Defined. *)\n\n(* End OrderedIndexed. *)\n\n(* (** The product of two ordered types is ordered. *) *)\n\n(* Module OrderedPair (A B: OrderedType) <: OrderedType. *)\n\n(* Definition t := (A.t * B.t)%type. *)\n\n(* Definition eq (x y: t) := *)\n(*   A.eq (fst x) (fst y) /\\ B.eq (snd x) (snd y). *)\n\n(* Lemma eq_refl : forall x : t, eq x x. *)\n(* Proof. *)\n(*   intros; split; auto. *)\n(* Qed. *)\n\n(* Lemma eq_sym : forall x y : t, eq x y -> eq y x. *)\n(* Proof. *)\n(*   unfold eq; intros. intuition auto. *)\n(* Qed. *)\n\n(* Lemma eq_trans : forall x y z : t, eq x y -> eq y z -> eq x z. *)\n(* Proof. *)\n(*   unfold eq; intros. intuition eauto. *)\n(* Qed. *)\n\n(* Definition lt (x y: t) := *)\n(*   A.lt (fst x) (fst y) \\/ *)\n(*   (A.eq (fst x) (fst y) /\\ B.lt (snd x) (snd y)). *)\n\n(* Lemma lt_trans : forall x y z : t, lt x y -> lt y z -> lt x z. *)\n(* Proof. *)\n(*   unfold lt; intros. *)\n(*   elim H; elim H0; intros. *)\n\n(*   left. apply A.lt_trans with (fst y); auto. *)\n\n(*   left.  elim H1; intros. *)\n(*   case (A.compare (fst x) (fst z)); intro. *)\n(*   assumption. *)\n(*   generalize (A.lt_not_eq H2); intro. elim H5. *)\n(*   apply A.eq_trans with (fst z). auto. auto. *)\n(*   generalize (@A.lt_not_eq (fst z) (fst y)); intro. *)\n(*   elim H5. apply A.lt_trans with (fst x); auto. *)\n(*   apply A.eq_sym; auto. *)\n\n(*   left. elim H2; intros. *)\n(*   case (A.compare (fst x) (fst z)); intro. *)\n(*   assumption. *)\n(*   generalize (A.lt_not_eq H1); intro. elim H5. *)\n(*   apply A.eq_trans with (fst x). *)\n(*   apply A.eq_sym. auto. auto. *)\n(*   generalize (@A.lt_not_eq (fst y) (fst x)); intro. *)\n(*   elim H5. apply A.lt_trans with (fst z); auto. *)\n(*   apply A.eq_sym; auto. *)\n\n(*   right. elim H1; elim H2; intros. *)\n(*   split. apply A.eq_trans with (fst y); auto. *)\n(*   apply B.lt_trans with (snd y); auto. *)\n(* Qed. *)\n\n(* Lemma lt_not_eq : forall x y : t, lt x y -> ~ eq x y. *)\n(* Proof. *)\n(*   unfold lt, eq, not; intros. *)\n(*   elim H0; intros. *)\n(*   elim H; intro. *)\n(*   apply (@A.lt_not_eq _ _ H3 H1). *)\n(*   elim H3; intros. *)\n(*   apply (@B.lt_not_eq _ _ H5 H2). *)\n(* Qed. *)\n\n(* Lemma compare : forall x y : t, Compare lt eq x y. *)\n(* Proof. *)\n(*   intros. *)\n(*   case (A.compare (fst x) (fst y)); intro. *)\n(*   apply LT. red. left. auto. *)\n(*   case (B.compare (snd x) (snd y)); intro. *)\n(*   apply LT. red. right. tauto. *)\n(*   apply EQ. red. tauto. *)\n(*   apply GT. red. right. split. apply A.eq_sym. auto. auto. *)\n(*   apply GT. red. left. auto. *)\n(* Defined. *)\n\n(* Lemma eq_dec : forall x y, { eq x y } + { ~ eq x y }. *)\n(* Proof. *)\n(*   unfold eq; intros. *)\n(*   case (A.eq_dec (fst x) (fst y)); intros. *)\n(*   case (B.eq_dec (snd x) (snd y)); intros. *)\n(*   left; auto. *)\n(*   right; intuition. *)\n(*   right; intuition. *)\n(* Defined. *)\n\n(* End OrderedPair. *)\n\n", "meta": {"author": "Aurele-Barriere", "repo": "CoreJIT", "sha": "8740d4149be649d0746d9f0d2d759b387a8f3246", "save_path": "github-repos/coq/Aurele-Barriere-CoreJIT", "path": "github-repos/coq/Aurele-Barriere-CoreJIT/CoreJIT-8740d4149be649d0746d9f0d2d759b387a8f3246/src/coqjit/lib/Ordered.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22233196731042748}}
{"text": "From Undecidability.L Require Import Tactics.LTactics Prelim.MoreList Prelim.MoreBase.\nFrom Complexity.Complexity Require Import NP Definitions Monotonic.\nFrom Complexity.NP Require Import L.GenNP.\n\n\n(** * From L to TMs *)\n\n(** Start: *)\n(** * This start might be bad, as we need to check the bound explicitly, e.g. count the beta-steps during the simulation. *)\n(** * But we can choose the bound large enough such that the term we simulate halts in the bound or always diverges *)\n(** * We might want to simulate some L term that always halts *)\n(** * But that means we need to distinguish true/false in the representation. *)\n\n(** * Eventuell moechten wir nicht mit einem \"einfachen\" problem starten, sondern erst eienn lambda-trm scheiben, der decider für eine lang genuge zeit simulirt und dann hält oder divergiert, je nachdem ob der Decider wahr oder falsch sagt *)\n(** * Divergenz ist ein schlechter Problem, wenn man von divergens reduziert, da man häufig nur obere schranken für die Laufzeit der Simulatoren hat.\n\nDa der simulierte Term evtl aber mit groesserer Schranke haelt muesste man dann schritte mitzählen. *)\n\n(* Weitere Idee: Prädikat nutzen, um Probleminstanzen weiter einzuschränken? *)\n\nFrom Undecidability.TM Require Import TM CodeTM.\nFrom Undecidability Require Import LFinType.\n\nFrom Complexity Require Import NP L_to_LM LM_to_mTM mTM_to_singleTapeTM TMGenNP_fixed_mTM Subtypes.\n\nImport LNat.\nLemma GenNP_to_TMGenNP:\n  GenNP (list bool) ⪯p TMGenNP_fixed (projT1 (M_multi2mono.M__mono (projT1 M.M))).\nProof.\n  eapply reducesPolyMO_transitive. now apply GenNP_to_LMGenNP.\n  eapply reducesPolyMO_transitive. now apply LMGenNP_to_TMGenNP_mTM.\n  now apply TMGenNP_mTM_to_TMGenNP_singleTM.\nQed.\n\n(*\nPrint Assumptions GenNP_to_TMGenNP.\n*)\n(** Not Complete: nice form of Time bound *)\n(*From Undecidability.L.AbstractMachines.TM_LHeapInterpreter  Require TM.LMBounds. *)\n\n\n(** Approach: simulate step-indexed L interpreter inside TM *)\n(** Problems: Well-formedness of certificate-input? *)\n\n(** Maybe intermediate problem in terms of Heap-Machine? *)\n", "meta": {"author": "uds-psl", "repo": "coq-library-complexity", "sha": "5a996877f16fd6fe16dc5f0c3b933486957869df", "save_path": "github-repos/coq/uds-psl-coq-library-complexity", "path": "github-repos/coq/uds-psl-coq-library-complexity/coq-library-complexity-5a996877f16fd6fe16dc5f0c3b933486957869df/theories/NP/TM/IntermediateProblems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.3451052844289767, "lm_q1q2_score": 0.2223254886102664}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import gmap auth agree gset coPset.\nFrom Perennial.base_logic.lib Require Import wsat.\nFrom Perennial.program_logic Require Export weakestpre.\nFrom Perennial.program_logic Require Export crash_lang dist_lang crash_weakestpre recovery_weakestpre.\nImport uPred.\n\nSet Default Proof Using \"Type\".\n\n(*** Distributed WP ***)\n\nSection wpd.\nContext `{HI: !irisGS Λ Σ}.\n\nDefinition wpd CS (E: coPset) (ers: list node_init_cfg) :=\n ([∗ list] i↦σ ∈ ers, ∀ `(Hc: !crashGS Σ),\n   |={⊤}=> ∃ (stateI : state Λ → nat → iProp Σ) (* for the initial generation *) Φ Φrx Φinv,\n   let HG := GenerationGS Λ Σ Hc stateI in\n   stateI σ.(init_local_state) 0 ∗\n   wpr CS NotStuck HG E σ.(init_thread) σ.(init_restart) Φ Φinv Φrx)%I.\n\nLemma wpd_compose CS E ers1 ers2 :\n  wpd CS E ers1 -∗\n  wpd CS E ers2 -∗\n  wpd CS E (ers1 ++ ers2).\nProof. rewrite /wpd big_sepL_app. iIntros \"$ $\". Qed.\n\nEnd wpd.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_logic/dist_weakestpre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.22232548861026638}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import Global.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import Progress.\nRequire Import ReorderInternal.\n\nRequire Import SimLocal.\nRequire Import SimMemory.\nRequire Import SimGlobal.\nRequire Import SimThread.\nRequire Import Compatibility.\n\nRequire Import ReorderStep.\nRequire Import ReorderLoad.\nRequire Import ReorderFence.\nRequire Import ReorderAbort.\nRequire Import ReorderChoose.\n\nRequire Import ITreeLang.\nRequire Import ITreeLib.\n\nSet Implicit Arguments.\n\n\nVariant reorder: forall R0 R1 (i1: MemE.t R0) (i2: MemE.t R1), Prop :=\n| reorder_intro_load\n    R1 l1 o1 (i2: MemE.t R1)\n    (REORDER: reorder_load l1 o1 i2):\n    reorder (MemE.read l1 o1) i2\n| reorder_intro_fence\n    R1 or1 ow1 (i2: MemE.t R1)\n    (REORDER: reorder_fence or1 ow1 i2):\n    reorder (MemE.fence or1 ow1) i2\n| reorder_intro_abort\n    R1 (i2: MemE.t R1)\n    (REORDER: reorder_abort i2):\n    reorder MemE.abort i2\n| reorder_intro_choose\n    R1 (i2: MemE.t R1)\n    (REORDER: reorder_choose i2):\n    reorder MemE.choose i2\n.\n\nLemma reorder_sim_itree R0 R1\n      (i1: MemE.t R0) (i2: MemE.t R1) (REORDER: reorder i1 i2):\n  sim_itree eq\n            (r2 <- ITree.trigger i2;; r1 <- ITree.trigger i1;; Ret (r1, r2))\n            (r1 <- ITree.trigger i1;; r2 <- ITree.trigger i2;; Ret (r1, r2)).\nProof.\n  replace (r2 <- ITree.trigger i2;; r1 <- ITree.trigger i1;; Ret (r1, r2)) with\n      (Vis i2 (fun r2 => Vis i1 (fun r1 => Ret (r1, r2)))).\n  2:{ unfold ITree.trigger. grind. repeat f_equal. extensionality r2. grind.\n      repeat f_equal. extensionality r1. grind. }\n  replace (r1 <- ITree.trigger i1;; r2 <- ITree.trigger i2;; Ret (r1, r2)) with\n      (Vis i1 (fun r1 => Vis i2 (fun r2 => Ret (r1, r2)))).\n  2:{ unfold ITree.trigger. grind. repeat f_equal. extensionality r2. grind.\n      repeat f_equal. extensionality r1. grind. }\n  pcofix CIH. ii. subst. pfold. ii. splits; ii.\n  { inv TERMINAL_TGT. eapply f_equal with (f:=observe) in H; ss. }\n  { right. esplits; eauto. inv LOCAL. congr. }\n  inv STEP_TGT; [|destruct REORDER; ss; dependent destruction STATE; inv LOCAL0]; ss; clarify.\n  - (* internal *)\n    right.\n    exploit sim_local_internal; eauto. i. des.\n    esplits; try apply GL2; eauto.\n    inv LOCAL0; ss.\n  - (* load *)\n    right.\n    exploit sim_local_read; eauto; try refl. i. des.\n    esplits; try apply GLOBAL; eauto; ss.\n    left. eapply paco9_mon; [apply sim_load_sim_thread|]; ss.\n    econs; eauto.\n    eapply Local.read_step_future; eauto.\n  - (* racy read *)\n    right.\n    exploit sim_local_racy_read; eauto; try refl. i. des.\n    esplits; try apply GLOBAL; eauto; ss.\n    left. eapply paco9_mon; [apply sim_load_sim_thread|]; ss.\n    econs 2; eauto.\n  - (* fence *)\n    right.\n    exploit sim_local_fence; eauto; try refl. i. des.\n    exploit Local.fence_step_future; try exact LOCAL1; eauto. i. des.\n    assert (GLOBAL3: sim_global gl1_src gl3_tgt).\n    { etrans; [|eauto]. inv STEP_SRC. inv GLOBAL2.\n      econs; ss; try refl.\n      apply TViewFacts.write_fence_sc_incr.\n    }\n    esplits.\n    + ss.\n    + refl.\n    + econs 1.\n    + ss.\n    + ss.\n    + left. eapply paco9_mon; [apply sim_fence_sim_thread|]; ss.\n      econs; eauto.\n  - (* abort *)\n    left.\n    eapply sim_abort_steps_failure.\n    econs; eauto.\n  - (* choose *)\n    right.\n    esplits; eauto; ss.\n    left. eapply paco9_mon; [apply sim_choose_sim_thread|]; ss.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/trans/Reorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22228498504105879}}
{"text": "Require Import FcEtt.sigs.\n\n\nRequire Import FcEtt.imports.\nRequire Import FcEtt.tactics.\n\nRequire Import FcEtt.ett_ott.\nRequire Import FcEtt.ett_inf.\nRequire Import FcEtt.ett_inf_cs.\nRequire Import FcEtt.ett_ind.\n\n\nRequire Import FcEtt.ett_par.\nRequire Import FcEtt.ext_invert.\nRequire Import FcEtt.ext_red.\nRequire Import FcEtt.ext_red_one.\nRequire Import FcEtt.erase_syntax.\n\nRequire Import FcEtt.fc_invert FcEtt.fc_unique.\n\nModule fc_preservation (wf : fc_wf_sig) (weak : fc_weak_sig) (subst : fc_subst_sig)\n        (e_subst : ext_subst_sig).\n\nImport subst weak wf.\n\nModule e_invert := ext_invert e_subst.\nImport e_invert.\n\nModule red := ext_red e_invert.\nImport red.\n\nModule red_one := ext_red_one e_invert.\nImport red_one.\n\nModule invert := fc_invert wf weak subst.\nModule unique := fc_unique wf subst.\nImport invert unique.\n\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Implicit Arguments.\n\n\n(* This version is just for \"head reduction.\"\n *)\n\nLemma open_a_Conv : forall a b g,\n    open_tm_wrt_tm (a_Conv a g) b =\n    a_Conv (open_tm_wrt_tm a b) (open_co_wrt_tm g b).\nintros.\nunfold open_tm_wrt_tm. simpl. auto.\nQed.\n\nLemma open_a_Conv_co : forall a b g,\n    open_tm_wrt_co (a_Conv a g) b =\n    a_Conv (open_tm_wrt_co a b) (open_co_wrt_co g b).\nintros.\nunfold open_tm_wrt_co. simpl. auto.\nQed.\n\n(* Helper tactic for below. Solves lc_tm goals using hypotheses from\n   the annotated language. Perhaps it is useful elsewhere? *)\nLtac lc_erase_hyp :=\n  match goal with\n  | H : AnnTyping ?G ?a ?A0 |- lc_tm (erase_tm ?a) => eapply lc_erase; apply (AnnTyping_lc H)\n  | H : AnnTyping ?G ?a ?A0 |- lc_tm ?a => apply (AnnTyping_lc1 H)\n  | H : lc_tm ?a |- lc_tm (erase ?a) => eapply lc_erase; eauto\n  | H : lc_tm (a_Abs ?r ?a ?b) |- lc_tm ?c => apply lc_erase in H; simpl in H; auto\n  | H : lc_tm (a_CAbs ?a ?b) |- lc_tm ?c => apply lc_erase in H; simpl in H; auto\n  end.\n\n\nLemma binds_toplevel: forall F a A,\n  binds F (Ax a A) an_toplevel ->\n  binds F (Ax (erase a) (erase A)) toplevel.\nProof.\n  intros.\n  unfold toplevel. unfold erase_sig.\n  eapply binds_map with (f:= erase_csort) in H.\n  auto.\nQed.\n\n\nLtac do_rho :=\n  match goal with\n    H : ∀ x : atom, x `notin` ?L → RhoCheck Irrel x (erase_tm (open_tm_wrt_tm ?b (a_Var_f x))) |-\n                    ?x `notin` fv_tm_tm_tm (open_tm_wrt_tm (erase ?b) (a_Var_f ?x)) =>\n    let h := fresh in\n    let F := fresh in\n    assert (F : x `notin` L); auto;\n    move: (H x F) => h; inversion h; subst;\n    replace (a_Var_f x) with (erase (a_Var_f x)); auto;\n    rewrite open_tm_erase_tm; auto\n  end.\n\n(* A specialized version of eauto that only uses the most common\n   lc lemmas to cut down the search space. *)\nLtac eauto_lc := simpl; eauto using AnnTyping_lc1, Value_lc,\n                        AnnDefEq_lc3, AnnPropWff_lc.\n\n\n(* We need to know that the term type checks.  But if it does, our annotated\n   operational semantics corresponds with reduction_in_one. *)\nLemma head_reduction_in_one : forall G a b,\n    head_reduction G a b -> forall A,  AnnTyping G a A ->\n    reduction_in_one (erase a) (erase b) \\/ erase a = erase b.\nProof.\n  move: lc_erase => [lc_er_tm _] G a b H.\n  induction H; intros AA TT ; inversion TT; try (simpl; eauto).\n  - destruct rho.\n    destruct (IHhead_reduction _ H6); subst; simpl.\n    left. eauto. simpl in H8. rewrite H8. eauto.\n    destruct (IHhead_reduction _ H6); subst; simpl.\n    left. eauto. simpl in H8. rewrite H8. eauto.\n  - subst. destruct rho; left; simpl_erase.\n    ++ eapply E_AppAbs; eauto using lc_er_tm.\n       eapply Value_lc in H0. lc_erase_hyp.\n    ++ inversion H6; clear H6; subst.\n       pose EB := erase w.\n       pick fresh x.\n       rewrite (tm_subst_tm_tm_intro x); auto using fv_tm_erase_tm.\n       rewrite tm_subst_tm_tm_fresh_eq.\n       rewrite -(tm_subst_tm_tm_fresh_eq (open_tm_wrt_tm (erase w) (a_Var_f x)) a_Bullet x).\n       rewrite -tm_subst_tm_tm_intro; eauto.\n       econstructor. auto.\n       eapply Value_erase in H0. auto.\n       do_rho.\n       do_rho. \n  - subst.\n    destruct (IHhead_reduction _ H4); simpl.\n    eauto.\n    simpl in H1. rewrite H1.\n    eauto.\n  - subst. left. autorewcs.\n    erewrite <- open_co_erase_tm2.\n    econstructor. apply lc_er_tm in H0. eauto.\n  - subst.\n    pick fresh x.\n    edestruct (H1 x); eauto.\n    left. apply E_AbsTerm_exists with (x:=x).\n    eauto using fv_tm_erase_tm.\n    rewrite <- open_tm_erase_tm in H2.\n    rewrite <- open_tm_erase_tm in H2.\n    simpl in H2. eauto.\n    right. f_equal.\n    move: (H9 x ltac:(auto)) => h0. inversion h0. subst.\n    rewrite <- open_tm_erase_tm in H2.\n    rewrite <- open_tm_erase_tm in H2.\n    simpl in H2.\n    apply open_tm_wrt_tm_inj in H2.\n    auto.\n    eauto using fv_tm_erase_tm.\n    eauto using fv_tm_erase_tm.\n  - left.\n    assert (Ax a A = Ax a0 AA).\n    { eapply binds_unique; eauto. apply uniq_an_toplevel. } inversion H6. subst.\n    apply binds_toplevel in H.\n    eauto.\n  - subst. destruct rho.\n    simpl. eauto.\n    simpl. eauto.\nQed.\n\n\n(* We need to know that the term type checks.  But if it does, our annotated\n   operational semantics corresponds with parallel reduction. *)\n\nLemma head_reduction_erased : forall G a b, head_reduction G a b ->\n    forall A, AnnTyping G a A ->  Par G (dom G) (erase a) (erase b).\nProof.\n  intros G a b H.\n  induction H; intros AA TT ; inversion TT; try (simpl; econstructor; eauto).\n  + destruct rho; simpl. econstructor; eauto. econstructor.\n    eapply lc_erase. eapply AnnTyping_lc with (A := A). eauto.\n    econstructor; eauto.\n  + destruct rho; simpl_erase.\n    econstructor.\n    econstructor. apply Value_lc in H0. lc_erase_hyp.\n    econstructor. apply Value_lc in H0. lc_erase_hyp.\n    match goal with\n      H :  AnnTyping ?G (a_Abs Irrel ?A ?b) (a_Pi Irrel ?A0 ?B) |- _ => inversion H; clear H end. subst.\n    pose EB := (erase w).\n    pick fresh x.\n    rewrite (tm_subst_tm_tm_intro x); auto using fv_tm_erase_tm.\n    rewrite tm_subst_tm_tm_fresh_eq.\n    rewrite -(tm_subst_tm_tm_fresh_eq (open_tm_wrt_tm (erase w) (a_Var_f x)) a_Bullet x).\n    rewrite -tm_subst_tm_tm_intro; eauto.\n    econstructor. econstructor. apply Value_lc in H0.\n    match goal with H : lc_tm (a_Abs Irrel ?A0 ?b) |-\n                    lc_tm (a_UAbs Irrel (erase ?b)) => eapply lc_erase in H; simpl in H; auto end.\n    do_rho.\n    do_rho.\n  + subst. simpl.\n    autorewcs. rewrite -(open_co_erase_tm2 _ _ g_Triv).\n    econstructor. econstructor. lc_erase_hyp.\n  + intros.\n    assert (x `notin` L \\u L0). eapply H10.\n    replace (a_Var_f x) with (erase (a_Var_f x)); auto.\n    rewrite open_tm_erase_tm.\n    rewrite open_tm_erase_tm.\n    eapply context_Par_irrelevance; eauto.\n  + unfold toplevel. unfold erase_sig.\n    apply binds_map with (f := erase_csort) in H.\n    simpl in H.\n    eauto.\n  + simpl. eauto.\n  + match goal with\n      H : AnnTyping ?G (a_Conv ?v ?g1) ?A |- lc_tm (erase_tm ?v) =>\n      inversion H end.\n    lc_erase_hyp.\n  + destruct rho; subst; simpl; eauto using lc_erase.\n    econstructor. eapply AnnTyping_lc1 in TT. eapply lc_tm_erase in TT. eauto.\n    econstructor. eapply AnnTyping_lc1 in TT. eapply lc_tm_erase in TT. eauto.\n  + eapply AnnTyping_lc1 in TT. eapply lc_tm_erase in TT. eauto.\nQed.\n\nLemma preservation : forall G a A, AnnTyping G a A -> forall a', head_reduction G a a' -> AnnTyping G a' A.\nProof.\n  intros G a A H. induction H.\n  - intros. inversion H0.\n  - intros. inversion H1.\n  - intros. inversion H2; subst.\n  - intros. inversion H3. subst.\n    pick fresh x and apply An_Abs; eauto 3.\n    have RC: RhoCheck Irrel x (erase_tm (open_tm_wrt_tm a (a_Var_f x))); eauto.\n    inversion RC. subst.\n    have HR: head_reduction ([(x, Tm A)] ++ G) (open_tm_wrt_tm a (a_Var_f x))\n                            (open_tm_wrt_tm b' (a_Var_f x)); eauto.\n    have Ta: AnnTyping ([(x, Tm A)] ++ G) (open_tm_wrt_tm b' (a_Var_f x))\n                       (open_tm_wrt_tm B (a_Var_f x)); eauto.\n    constructor.\n    eapply Par_fv_preservation; eauto.\n    eapply head_reduction_erased; eauto.\n  - (* application case *)\n    intros. inversion H1; subst.\n    + eauto.\n    + inversion H. subst.\n      pick fresh x.\n      rewrite (tm_subst_tm_tm_intro x); auto.\n      rewrite (tm_subst_tm_tm_intro x B); auto.\n      eapply AnnTyping_tm_subst; eauto.\n    + (* Push case *)\n      inversion H. subst. resolve_unique_subst.\n      move: (AnnDefEq_regularity H7)  => [C1 [C2 [g' hyps]]]. split_hyp.\n      invert_syntactic_equality.\n      inversion H2. inversion H6. subst.\n      eapply An_Conv; eauto.\n      eapply An_PiSnd; eauto.\n      eapply An_EraseEq; eauto.\n      eapply AnnTyping_tm_subst_nondep; eauto.\n  - intros. inversion H2; subst.\n    + eauto.\n    + inversion H. subst.\n      econstructor; eauto 2.\n      eapply An_Trans with (a1 := A); eauto 2 using AnnTyping_regularity.\n      eapply An_Refl; eauto with ctx_wff.\n  - intros. inversion H2.\n  - intros. inversion H2.\n  - intros. inversion H1; subst.\n    + eauto.\n    + inversion H; subst.\n      pick fresh c.\n      rewrite (co_subst_co_tm_intro c); auto.\n      rewrite (co_subst_co_tm_intro c B); auto.\n      eapply AnnTyping_co_subst; eauto.\n    + (* CPush case *)\n      inversion H. subst. resolve_unique_subst.\n      move: (AnnDefEq_regularity H5)  => [C1 [C2 [g' hyps]]]. split_hyp.\n      invert_syntactic_equality.\n      inversion H2. inversion H7. subst. destruct phi1.\n      eapply An_Conv; eauto.\n      eapply AnnTyping_co_subst_nondep; eauto.\n  - move=> a' hr.\n    inversion hr.\n  - move=> a' hr.\n    inversion hr. subst.\n\n    assert (Ax a A = Ax a' A0).\n    { eapply binds_unique; eauto. apply uniq_an_toplevel. }\n    inversion H2. subst. clear H2. clear H0.\n    apply an_toplevel_closed in H4.\n    eapply AnnTyping_weakening with (F:=nil)(G:=nil)(E:=G) in H4; eauto.\n    simpl in H4.\n    rewrite app_nil_r in H4.\n    auto.\n    rewrite app_nil_r. simpl. auto.\nQed. (* preservation *)\n\n\n\n\nEnd fc_preservation.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/corespec/src/FcEtt/fc_preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22228497944320313}}
{"text": "Require Import CompCert.Events.\nRequire Import CompCert.Smallstep.\nRequire Import CompCert.Behaviors.\nRequire Import Common.Definitions.\nRequire Import Common.Util.\nRequire Import Common.Linking.\nRequire Import Common.Memory.\nRequire Import Common.Traces.\nRequire Import Common.CompCertExtensions.\nRequire Import Intermediate.Machine.\nRequire Import Intermediate.GlobalEnv.\nRequire Import Lib.Extra.\nRequire Import Lib.Monads.\nRequire Import Intermediate.CS.\nImport CS.\n\nFrom mathcomp Require ssreflect ssrfun ssrbool eqtype.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nModule CS.\n\nImport Intermediate.\n\n(* A similar result is used above. Here is a weaker formulation. *)\nLemma initial_state_stack_state0 p s :\n  initial_state p s ->\n  stack_state_of s = Traces.stack_state0.\nProof.\n  intros Hini.\n  unfold initial_state, initial_machine_state in Hini.\n  destruct (prog_main p) as [mainP |]; simpl in Hini.\n  - destruct (prepare_procedures p (prepare_initial_memory p))\n      as [[mem dummy] entrypoints].\n    destruct (EntryPoint.get Component.main mainP entrypoints).\n    + subst. reflexivity.\n    + subst. reflexivity.\n  - subst. reflexivity.\nQed.\n\nLemma comes_from_initial_state_mergeable_sym :\n  forall s iface1 iface2,\n    Linking.mergeable_interfaces iface1 iface2 ->\n    comes_from_initial_state s (unionm iface1 iface2) ->\n    comes_from_initial_state s (unionm iface2 iface1).\nProof.\n  intros s iface1 iface2 [[_ Hdisjoint] _] Hfrom_initial.\n  rewrite <- (unionmC Hdisjoint).\n  exact Hfrom_initial.\nQed.\n\n(* RB: NOTE: Consider possible alternatives on [CS.comes_from_initial_state]\n   complemented instead by, say, [PS.step] based on what we usually have in\n   the context, making for more direct routes. *)\nLemma comes_from_initial_state_step_trans p s t s' :\n  CS.comes_from_initial_state s (prog_interface p) ->\n  CS.step (prepare_global_env p) s t s' ->\n  CS.comes_from_initial_state s' (prog_interface p).\nAdmitted. (* Grade 2. *)\n\n(* RB: TODO: These domain lemmas should now be renamed to reflect their\n   operation on linked programs. *)\nSection ProgramLink.\n  Variables p c : program.\n  Hypothesis Hwfp  : well_formed_program p.\n  Hypothesis Hwfc  : well_formed_program c.\n  Hypothesis Hmergeable_ifaces :\n    mergeable_interfaces (prog_interface p) (prog_interface c).\n  Hypothesis Hprog_is_closed  : closed_program (program_link p c).\n\n  Import ssreflect.\n\n  (* RB: NOTE: Check with existing results (though currently unused). *)\n  Lemma star_stack_cons_domm {s frame gps mem regs pc t} :\n    initial_state (program_link p c) s ->\n    Star (sem (program_link p c)) s t (frame :: gps, mem, regs, pc) ->\n    Pointer.component frame \\in domm (prog_interface p) \\/\n    Pointer.component frame \\in domm (prog_interface c).\n  Proof.\n    intros Hini Hstar.\n    assert (H : Pointer.component frame \\in domm (prog_interface (program_link p c))).\n    { eapply CS.comes_from_initial_state_stack_cons_domm.\n      destruct (cprog_main_existence Hprog_is_closed) as [i [_ [? _]]].\n      exists (program_link p c), i, s, t.\n      split; first (destruct Hmergeable_ifaces; now apply linking_well_formedness).\n      repeat split; eauto. }\n    move: H. simpl. rewrite domm_union. now apply /fsetUP.\n  Qed.\nEnd ProgramLink.\n\nEnd CS.\n", "meta": {"author": "secure-compilation", "repo": "when-good-components-go-bad", "sha": "7bef0fa18780f1e9699abcdadd61e15bf3aba95d", "save_path": "github-repos/coq/secure-compilation-when-good-components-go-bad", "path": "github-repos/coq/secure-compilation-when-good-components-go-bad/when-good-components-go-bad-7bef0fa18780f1e9699abcdadd61e15bf3aba95d/Old/Intermediate/CSExtra.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2222849738453474}}
{"text": "Require Import coqutil.Macros.subst coqutil.Macros.unique coqutil.Map.Interface coqutil.Word.Properties.\nRequire Import coqutil.Word.Bitwidth.\nRequire bedrock2.WeakestPrecondition.\n\nRequire Import Coq.Classes.Morphisms.\n\nSection WeakestPrecondition.\n  Context {width} {BW: Bitwidth width} {word: word.word width} {mem: map.map word Byte.byte}.\n  Context {locals: map.map String.string word}.\n  Context {env: map.map String.string (list String.string * list String.string * Syntax.cmd)}.\n  Context {ext_spec: Semantics.ExtSpec}.\n\n  Ltac ind_on X :=\n    intros;\n    (* Note: Comment below dates from when we were using a parameter record p *)\n    (* Note: \"before p\" means actually \"after p\" when reading from top to bottom, because,\n       as the manual points out, \"before\" and \"after\" are with respect to the direction of\n       the move, and we're moving hypotheses upwards here.\n       We need to make sure not to revert/clear p, because the other lemmas depend on it.\n       If we still reverted/cleared p, we'd get errors like\n       \"Error: Proper_load depends on the variable p which is not declared in the context.\"\n       when trying to use Proper_load, or, due to COQBUG https://github.com/coq/coq/issues/11487,\n       we'd get a typechecking failure at Qed time. *)\n    repeat match goal with x : ?T |- _ => first\n       [ constr_eq T X; move x before ext_spec\n       | constr_eq T X; move x before env\n       | constr_eq T X; move x before locals\n       | constr_eq T X; move x at top\n       | revert x ] end;\n    match goal with x : X |- _ => induction x end;\n    intros.\n\n  Local Hint Mode word.word - : typeclass_instances.\n\n  (* we prove weakening lemmas for all WP definitions in a syntax-directed fashion,\n   * moving from postcondition towards precondition one logical connective at a time. *)\n  Global Instance Proper_literal : Proper (pointwise_relation _ ((pointwise_relation _ Basics.impl) ==> Basics.impl)) WeakestPrecondition.literal.\n  Proof using. clear. cbv [WeakestPrecondition.literal]; cbv [Proper respectful pointwise_relation Basics.impl dlet.dlet]. eauto. Qed.\n\n  Global Instance Proper_get : Proper (pointwise_relation _ (pointwise_relation _ ((pointwise_relation _ Basics.impl) ==> Basics.impl))) WeakestPrecondition.get.\n  Proof using. clear. cbv [WeakestPrecondition.get]; cbv [Proper respectful pointwise_relation Basics.impl]; intros * ? (?&?&?); eauto. Qed.\n\n  Global Instance Proper_load : Proper (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ ((pointwise_relation _ Basics.impl) ==> Basics.impl)))) WeakestPrecondition.load.\n  Proof using. clear. cbv [WeakestPrecondition.load]; cbv [Proper respectful pointwise_relation Basics.impl]; intros * ? (?&?&?); eauto. Qed.\n\n  Global Instance Proper_store : Proper (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ ((pointwise_relation _ Basics.impl) ==> Basics.impl))))) WeakestPrecondition.store.\n  Proof using. clear. cbv [WeakestPrecondition.store]; cbv [Proper respectful pointwise_relation Basics.impl]; intros * ? (?&?&?); eauto. Qed.\n\n  Global Instance Proper_expr : Proper (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ ((pointwise_relation _ Basics.impl) ==> Basics.impl)))) WeakestPrecondition.expr.\n  Proof using.\n    clear.\n    cbv [Proper respectful pointwise_relation Basics.impl]; ind_on Syntax.expr.expr;\n      cbn in *; intuition (try typeclasses eauto with core).\n    { eapply Proper_literal; eauto. }\n    { eapply Proper_get; eauto. }\n    { eapply IHa1; eauto; intuition idtac. eapply Proper_load; eauto using Proper_load. }\n    { eapply IHa1; eauto; intuition idtac. eapply Proper_load; eauto using Proper_load. }\n    { eapply IHa1_1; eauto; intuition idtac.\n      Tactics.destruct_one_match; eauto using Proper_load. }\n  Qed.\n\n  Global Instance Proper_list_map {A B} :\n    Proper ((pointwise_relation _ (pointwise_relation _ Basics.impl ==> Basics.impl)) ==> pointwise_relation _ (pointwise_relation _ Basics.impl ==> Basics.impl)) (WeakestPrecondition.list_map (A:=A) (B:=B)).\n  Proof using.\n    clear.\n    cbv [Proper respectful pointwise_relation Basics.impl]; ind_on (list A);\n      cbn in *; intuition (try typeclasses eauto with core).\n  Qed.\n\n  Context {word_ok : word.ok word} {mem_ok : map.ok mem}.\n  Context {locals_ok : map.ok locals}.\n  Context {env_ok : map.ok env}.\n  Context {ext_spec_ok : Semantics.ext_spec.ok ext_spec}.\n\n  Global Instance Proper_cmd :\n    Proper (\n     (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ ((pointwise_relation _ (pointwise_relation _ Basics.impl))) ==> Basics.impl)))) ==>\n     pointwise_relation _ (\n     pointwise_relation _ (\n     pointwise_relation _ (\n     pointwise_relation _ (\n     (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ Basics.impl))) ==>\n     Basics.impl)))))) WeakestPrecondition.cmd.\n  Proof.\n    cbv [Proper respectful pointwise_relation Basics.flip Basics.impl]; ind_on Syntax.cmd.cmd;\n      cbn in *; cbv [dlet.dlet] in *; intuition (try typeclasses eauto with core).\n    { destruct H1 as (?&?&?). eexists. split.\n      1: eapply Proper_expr.\n      1: cbv [pointwise_relation Basics.impl]; intuition eauto 2.\n      all: eauto. }\n    { destruct H1 as (?&?&?). eexists. split.\n      { eapply Proper_expr.\n        { cbv [pointwise_relation Basics.impl]; intuition eauto 2. }\n        { eauto. } }\n      { destruct H2 as (?&?&?). eexists. split.\n        { eapply Proper_expr.\n          { cbv [pointwise_relation Basics.impl]; intuition eauto 2. }\n          { eauto. } }\n        { eapply Proper_store; eauto; cbv [pointwise_relation Basics.impl]; eauto. } } }\n    { eapply H1; [ | | eapply H3; eassumption ].\n      2 : intros ? ? ? (?&?&?&?&?). all : eauto 7. }\n    { destruct H1 as (?&?&?). eexists. split.\n      { eapply Proper_expr.\n        { cbv [pointwise_relation Basics.impl]; intuition eauto 2. }\n        { eauto. } }\n      { intuition eauto 6. } }\n    { destruct H1 as (?&?&?&?&?&HH).\n      eassumption || eexists.\n      eassumption || eexists.\n      eassumption || eexists.\n      eassumption || eexists. { eassumption || eexists. }\n      eassumption || eexists. { eassumption || eexists. }\n      intros X Y Z T W.\n      specialize (HH X Y Z T W).\n      destruct HH as (?&?&?). eexists. split.\n      1: eapply Proper_expr.\n      1: cbv [pointwise_relation Basics.impl].\n      all:intuition eauto 2.\n      - eapply H2; eauto; cbn; intros.\n        match goal with H:_ |- _ => destruct H as (?&?&?); solve[eauto] end.\n      - intuition eauto. }\n    { destruct H1 as (?&?&?). eexists. split.\n      { eapply Proper_list_map; eauto; try exact H4; cbv [respectful pointwise_relation Basics.impl]; intuition eauto 2.\n        eapply Proper_expr; eauto. }\n      { eapply H. 2: eauto.\n        (* COQBUG (performance), measured in Coq 8.9:\n           \"firstorder eauto\" works, but takes ~100s and increases memory usage by 1.8GB.\n           On the other hand, the line below takes just 5ms *)\n        cbv beta; intros ? ? ? (?&?&?); eauto. } }\n    { destruct H1 as (?&?&?). eexists. split.\n      { eapply Proper_list_map; eauto; try exact H4; cbv [respectful pointwise_relation Basics.impl].\n        { eapply Proper_expr; eauto. }\n        { eauto. } }\n      { destruct H2 as (mKeep & mGive & ? & ?).\n        exists mKeep. exists mGive.\n        split; [assumption|].\n        eapply Semantics.ext_spec.weaken; [|solve[eassumption]].\n        intros ? ? (?&?&?); eauto 10. } }\n  Qed.\n\n  Global Instance Proper_func :\n    Proper (\n     (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ ((pointwise_relation _ (pointwise_relation _ Basics.impl))) ==> Basics.impl)))) ==>\n     pointwise_relation _ (\n     pointwise_relation _ (\n     pointwise_relation _ (\n     pointwise_relation _ (\n     (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ Basics.impl))) ==>\n     Basics.impl)))))) WeakestPrecondition.func.\n  Proof.\n    cbv [Proper respectful pointwise_relation Basics.flip Basics.impl  WeakestPrecondition.func]; intros.\n    destruct a. destruct p.\n    destruct H1; intuition idtac.\n    eexists.\n    split; [eauto|].\n    eapply Proper_cmd;\n      cbv [Proper respectful pointwise_relation Basics.flip Basics.impl  WeakestPrecondition.func];\n      try solve [typeclasses eauto with core].\n    intros.\n    eapply Proper_list_map;\n      cbv [Proper respectful pointwise_relation Basics.flip Basics.impl  WeakestPrecondition.func];\n      try solve [typeclasses eauto with core].\n    - intros.\n      eapply Proper_get;\n        cbv [Proper respectful pointwise_relation Basics.flip Basics.impl  WeakestPrecondition.func];\n        eauto.\n    - eauto.\n  Qed.\n\n  Global Instance Proper_call :\n    Proper (\n     (pointwise_relation _ (\n     (pointwise_relation _ (\n     pointwise_relation _ (\n     pointwise_relation _ (\n     pointwise_relation _ (\n     (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ Basics.impl))) ==>\n     Basics.impl)))))))) WeakestPrecondition.call.\n  Proof.\n    cbv [Proper respectful pointwise_relation Basics.impl]; ind_on (list (String.string * (list String.string * list String.string * Syntax.cmd.cmd)));\n      cbn in *; intuition (try typeclasses eauto with core).\n    destruct a.\n    destruct (String.eqb s a1); eauto.\n    eapply Proper_func;\n      cbv [Proper respectful pointwise_relation Basics.flip Basics.impl  WeakestPrecondition.func];\n      eauto.\n  Qed.\n\n  Global Instance Proper_program :\n    Proper (\n     pointwise_relation _ (\n     pointwise_relation _ (\n     pointwise_relation _ (\n     pointwise_relation _ (\n     pointwise_relation _ (\n     (pointwise_relation _ (pointwise_relation _ (pointwise_relation _ Basics.impl))) ==>\n     Basics.impl)))))) WeakestPrecondition.program.\n  Proof.\n    cbv [Proper respectful pointwise_relation Basics.impl  WeakestPrecondition.program]; intros.\n    eapply Proper_cmd;\n    cbv [Proper respectful pointwise_relation Basics.flip Basics.impl  WeakestPrecondition.func];\n    try solve [typeclasses eauto with core].\n    intros.\n    eapply Proper_call;\n    cbv [Proper respectful pointwise_relation Basics.flip Basics.impl  WeakestPrecondition.func];\n    solve [typeclasses eauto with core].\n  Qed.\n\n  Ltac t :=\n      repeat match goal with\n             | |- forall _, _ => progress intros\n             | H: exists _, _ |- _ => destruct H\n             | H: and _ _ |- _ => destruct H\n             | H: eq _ ?y |- _ => subst y\n             | H: False |- _ => destruct H\n             | _ => progress cbn in *\n             | _ => progress cbv [dlet.dlet WeakestPrecondition.dexpr WeakestPrecondition.dexprs WeakestPrecondition.store] in *\n             end; eauto.\n\n  Lemma expr_sound m l e mc post (H : WeakestPrecondition.expr m l e post)\n    : exists v mc', Semantics.eval_expr m l e mc = Some (v, mc') /\\ post v.\n  Proof.\n    ind_on Syntax.expr; t.\n    { destruct H. destruct H. eexists. eexists. rewrite H. eauto. }\n    { eapply IHe in H; t. cbv [WeakestPrecondition.load] in H0; t. rewrite H. rewrite H0. eauto. }\n    { eapply IHe in H; t. cbv [WeakestPrecondition.load] in H0; t. rewrite H. rewrite H0. eauto. }\n    { eapply IHe1 in H; t. eapply IHe2 in H0; t. rewrite H, H0; eauto. }\n    { eapply IHe1 in H; t. rewrite H. Tactics.destruct_one_match.\n      { eapply IHe3 in H0; t. }\n      { eapply IHe2 in H0; t. } }\n  Qed.\n\n  Lemma sound_args : forall m l args mc P,\n      WeakestPrecondition.list_map (WeakestPrecondition.expr m l) args P ->\n      exists x mc', Semantics.evaluate_call_args_log m l args mc = Some (x, mc') /\\ P x.\n  Proof.\n    induction args; cbn; repeat (subst; t).\n    unfold Semantics.eval_expr in *.\n    eapply expr_sound in H; t; rewrite H.\n    eapply IHargs in H0; t; rewrite H0.\n    eauto.\n  Qed.\n\n  Lemma sound_getmany l a P :\n    WeakestPrecondition.list_map (WeakestPrecondition.get l) a P\n    -> exists vs, map.getmany_of_list l a = Some vs /\\ P vs.\n  Proof.\n    cbv [map.getmany_of_list] in *.\n    revert P l; induction a; cbn; repeat (subst; t).\n    cbv [WeakestPrecondition.get] in H; t.\n    epose proof (IHa _ l _); clear IHa; t.\n    rewrite H. erewrite H1. eexists; split; eauto. exact H2.\n    Unshelve.\n    eapply Proper_list_map; try exact H0.\n    all : cbv [respectful pointwise_relation Basics.impl WeakestPrecondition.get]; intros; cbv beta; t.\n  Qed.\n\n  Local Notation semantics_call := (fun e n t m args post =>\n    exists params rets fbody, map.get e n = Some (params, rets, fbody) /\\\n    exists lf, map.putmany_of_list_zip params args map.empty = Some lf /\\\n    forall mc', Semantics.exec e fbody t m lf mc' (fun t' m' st1 mc'' =>\n      exists retvs, map.getmany_of_list st1 rets = Some retvs /\\\n      post t' m' retvs)).\n\n  Local Hint Constructors Semantics.exec : core.\n  Lemma sound_cmd' e c t m l mc post\n        (H:WeakestPrecondition.cmd (semantics_call e) c t m l post)\n    : Semantics.exec e c t m l mc (fun t' m' l' mc' => post t' m' l').\n  Proof.\n    ind_on Syntax.cmd; repeat (t; try match reverse goal with H : WeakestPrecondition.expr _ _ _ _ |- _ => eapply expr_sound in H end).\n    { destruct (BinInt.Z.eq_dec (Interface.word.unsigned x) (BinNums.Z0)) as [Hb|Hb]; cycle 1.\n      { econstructor; t. }\n      { eapply Semantics.exec.if_false; t. } }\n    { revert dependent l; revert dependent m; revert dependent t; revert dependent mc; pattern x2.\n      eapply (well_founded_ind H); t.\n      pose proof (H1 _ _ _ _ ltac:(eassumption));\n        repeat (t; try match goal with H : WeakestPrecondition.expr _ _ _ _ |- _ => eapply expr_sound in H end).\n      { destruct (BinInt.Z.eq_dec (Interface.word.unsigned x4) (BinNums.Z0)) as [Hb|Hb].\n        { eapply Semantics.exec.while_false; t. }\n        { eapply Semantics.exec.while_true; t. t. } } }\n    { eapply sound_args in H; t. }\n    { eapply sound_args in H; t. }\n  Qed.\n\n\n  Section WithE.\n    Context fs (E: env) (HE: List.Forall (fun '(k, v) => map.get E k = Some v) fs).\n    Import coqutil.Tactics.Tactics.\n    Lemma sound_call' n t m args post\n      (H : WeakestPrecondition.call fs n t m args post)\n      : semantics_call E n t m args post.\n    Proof.\n      revert H; revert post args m t n; induction HE; intros.\n      { contradiction H. }\n      destruct x as [n' ((X&Y)&Z)]; t.\n      destr (String.eqb n' n); t.\n      eexists X, Y, Z; split; [assumption|].\n      eexists; eauto.\n      eexists; eauto.\n      intros.\n      eapply sound_cmd'.\n      eapply Proper_cmd; try eapply H0.\n      all : cbv [respectful pointwise_relation Basics.impl]; intros; cbv beta.\n      1: eapply IHf, Proper_call; eauto.\n      2: eassumption.\n      eauto using sound_getmany.\n    Qed.\n\n    Lemma sound_cmd'' c t m l mc post\n      (H : WeakestPrecondition.cmd (WeakestPrecondition.call fs) c t m l post)\n      : Semantics.exec E c t m l mc (fun t' m' l' mc' => post t' m' l').\n    Proof.\n      eapply Proper_cmd in H; [ .. | reflexivity ].\n      1: apply sound_cmd'; exact H.\n      cbv [respectful pointwise_relation Basics.impl]; intros; cbv beta.\n      eapply sound_call', Proper_call, H1.\n      cbv [respectful pointwise_relation Basics.impl]; eauto.\n    Qed.\n  End WithE.\n\n  Lemma sound_cmd fs c t m l mc post\n    (Hnd : List.NoDup (List.map fst fs))\n    (H : WeakestPrecondition.cmd (WeakestPrecondition.call fs) c t m l post)\n    : Semantics.exec (map.of_list fs) c t m l mc (fun t' m' l' mc' => post t' m' l').\n  Proof.\n    eapply sound_cmd'';\n      try eapply Properties.map.all_gets_from_map_of_NoDup_list; eauto.\n  Qed.\n\n  (** Ad-hoc lemmas here? *)\n\n  Import bedrock2.Syntax bedrock2.Semantics bedrock2.WeakestPrecondition.\n  Lemma interact_nomem call action binds arges t m l post\n        args (Hargs : dexprs m l arges args)\n        (Hext : ext_spec t map.empty binds args (fun mReceive (rets : list word) =>\n           mReceive = map.empty /\\\n           exists l0 : locals, map.putmany_of_list_zip action rets l = Some l0 /\\\n           post (cons (map.empty, binds, args, (map.empty, rets)) t) m l0))\n    : WeakestPrecondition.cmd call (cmd.interact action binds arges) t m l post.\n  Proof.\n    exists args; split; [exact Hargs|].\n    exists m.\n    exists map.empty.\n    split; [eapply Properties.map.split_empty_r; exact eq_refl|].\n    eapply ext_spec.weaken; [|eapply Hext]; intros ? ? [? [? []]]. subst a; subst.\n    eexists; split; [eassumption|].\n    intros. eapply Properties.map.split_empty_r in H. subst. assumption.\n  Qed.\n\n  Lemma intersect_expr: forall m l e (post1 post2: word -> Prop),\n      WeakestPrecondition.expr m l e post1 ->\n      WeakestPrecondition.expr m l e post2 ->\n      WeakestPrecondition.expr m l e (fun v => post1 v /\\ post2 v).\n  Proof.\n    induction e; cbn; unfold literal, dlet.dlet, WeakestPrecondition.get; intros.\n    - eauto.\n    - decompose [and ex] H. decompose [and ex] H0. assert (x0 = x1) by congruence. subst. eauto.\n    - eapply Proper_expr.\n      2: eapply IHe.\n      2: eapply H.\n      2: eapply H0.\n      unfold Morphisms.pointwise_relation, Basics.impl.\n      unfold load. intros. decompose [and ex] H1. assert (x0 = x) by congruence. subst. eauto.\n    - eapply Proper_expr.\n      2: eapply IHe.\n      2: eapply H.\n      2: eapply H0.\n      unfold Morphisms.pointwise_relation, Basics.impl.\n      unfold load. intros. decompose [and ex] H1. assert (x0 = x) by congruence. subst. eauto.\n    - eapply Proper_expr.\n      2: eapply IHe1.\n      2: eapply H.\n      2: eapply H0.\n      unfold Morphisms.pointwise_relation, Basics.impl.\n      unfold load. intros. decompose [and ex] H1.\n      eapply IHe2; eassumption.\n    - eapply Proper_expr.\n      2: eapply IHe1.\n      2: eapply H.\n      2: eapply H0.\n      unfold Morphisms.pointwise_relation, Basics.impl.\n      intros ? [? ?]. Tactics.destruct_one_match; eauto using Proper_expr.\n  Qed.\n\n  Lemma dexpr_expr (m : mem) l e P\n    (H : WeakestPrecondition.expr m l e P)\n    : exists v, WeakestPrecondition.dexpr m l e v /\\ P v.\n  Proof.\n    revert dependent P; induction e; cbn.\n    { cbv [WeakestPrecondition.literal dlet.dlet]; cbn; eauto. }\n    { cbv [WeakestPrecondition.get]; intros ?(?&?&?); eauto. }\n    { intros v H; case (IHe _ H) as (?&?&?&?&?); clear IHe H.\n      cbv [WeakestPrecondition.dexpr] in *.\n      eexists; split; [|eassumption].\n      eapply Proper_expr; [|eauto].\n      intros ? ?; subst.\n      eexists; eauto. }\n    { intros v H; case (IHe _ H) as (?&?&?&?&?); clear IHe H.\n      cbv [WeakestPrecondition.dexpr] in *.\n      eexists; split; [|eassumption].\n      eapply Proper_expr; [|eauto].\n      intros ? ?; subst.\n      eexists; eauto. }\n    { intros P H.\n      case (IHe1 _ H) as (?&?&H'); case (IHe2 _ H') as (?&?&?);\n      clear IHe1 IHe2 H H'.\n      cbv [WeakestPrecondition.dexpr] in *.\n      eexists; split; [|eassumption].\n      eapply Proper_expr; [|eauto]; intros ? [].\n      eapply Proper_expr; [|eauto]; intros ? [].\n      trivial.\n    }\n    { intros P H.\n      case (IHe1 _ H) as (?&?&H'). Tactics.destruct_one_match_hyp.\n      { case (IHe3 _ H') as (?&?&?).\n        clear IHe1 IHe2 H H'.\n        cbv [WeakestPrecondition.dexpr] in *.\n        eexists; split; [|eassumption].\n        eapply Proper_expr; [|eauto]; intros ? [].\n        rewrite word.eqb_eq by reflexivity. assumption. }\n      { case (IHe2 _ H') as (?&?&?).\n        clear IHe1 IHe3 H H'.\n        cbv [WeakestPrecondition.dexpr] in *.\n        eexists; split; [|eassumption].\n        eapply Proper_expr; [|eauto]; intros ? [].\n        Tactics.destruct_one_match. 1: contradiction. assumption. } }\n  Qed.\nEnd WeakestPrecondition.\n", "meta": {"author": "mit-plv", "repo": "bedrock2", "sha": "7f2d764ed79f394fe715505a04301d0fb502407f", "save_path": "github-repos/coq/mit-plv-bedrock2", "path": "github-repos/coq/mit-plv-bedrock2/bedrock2-7f2d764ed79f394fe715505a04301d0fb502407f/bedrock2/src/bedrock2/WeakestPreconditionProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22220688810458894}}
{"text": "  Lemma same_next :\n    forall x y,\n      (x! = R0 //\\\\ y! = R0 |-- x! = y!).\n  Proof. solve_linear. Qed.\n\n  Lemma UpperLower_X_Proposed_refine :\n    forall t,\n      (UpperLower_X.Monitor.SafeAcc t //\\\\ \"a\"! = t\n       |-- UpperLower_X.Monitor.SafeAcc \"a\"!).\n  Proof.\n    breakAbstraction. solve_linear. rewrite H1 in *.\n    solve_linear.\n  Qed.\n\n(*\n  Definition refined_UpperLower_X_SpecR :\n    { ins : list Var &\n       { outs : list Var &\n           { p : Parallel ins outs &\n                 tlaParD p |--\n                 Prog (projT1 UpperLower_X_SpecR)} } }.\n  Proof.\n    Opaque UpperLower_X.Monitor.SafeAcc\n           UpperLower_X.Monitor.Default.\n    eexists. eexists. eexists. simpl. restoreAbstraction.\n    match goal with\n    | [ |- context [ rename_formula ?m _ ] ]\n      => remember m as rx\n    end.\n    match goal with\n    | [ |- context\n             [ rename_formula _ (rename_formula ?m _) ] ]\n      => remember m as rm\n    end.\n    repeat rewrite minus_eq.\n    rewrite land_distr.\n    apply par_disjoint_refine.\n    { repeat rewrite land_lor_distr_R.\n      pose proof UpperLower_X_Proposed_refine\n        as Hrefine. specialize (Hrefine \"A\").\n      apply (Proper_Rename rx rx) in Hrefine;\n        [ | reflexivity].\n      rewrite <- Rename_ok in Hrefine.\n      rewrite <- Rename_ok in Hrefine.\n      rewrite <- Hrefine at 1. clear Hrefine.\n      pose proof UpperLower_X_Proposed_refine as Hrefine.\n      specialize (Hrefine \"A\").\n      apply (Proper_Rename rm rm) in Hrefine;\n        [ | reflexivity].\n      apply (Proper_Rename rx rx) in Hrefine;\n        [ | reflexivity].\n      rewrite <- Rename_ok with (m:=rm) in Hrefine.\n      rewrite <- Rename_ok with (m:=rm) in Hrefine.\n      rewrite <- Rename_ok with (m:=rx) in Hrefine.\n      rewrite <- Rename_ok with (m:=rx) in Hrefine.\n      rewrite <- Hrefine at 1. clear Hrefine.\n      repeat rewrite lorA.\n      Transparent UpperLower_X.Monitor.SafeAcc\n                  UpperLower_X.Monitor.Default.\n      subst. simpl. restoreAbstraction.\n      repeat rewrite minus_eq. rewrite land_distr.\n      apply ite_refine.\n      { reflexivity. }\n      { apply Assign_refine; reflexivity. }\n      { rewrite <- lor_intro2. rewrite <- lor_intro2.\n        apply ite_refine_and_impl.\n        { reflexivity. }\n        { solve_linear. }\n        { apply ite_refine_and_impl.\n          { reflexivity. }\n          { solve_linear. }\n          { rewrite <- leq_eq_refine.\n            apply Assign_refine; reflexivity. }\n          { rewrite <- leq_eq_refine.\n            apply Assign_refine; reflexivity. } }\n        { apply ite_refine_and_impl.\n          { reflexivity. }\n          { solve_linear. }\n          { rewrite <- leq_eq_refine.\n            rewrite minus_0_l_equiv.\n            rewrite <- neg_eq.\n            apply Assign_refine; reflexivity. }\n          { rewrite <- leq_eq_refine.\n            rewrite minus_0_l_equiv.\n            rewrite <- neg_eq.\n            apply Assign_refine; reflexivity. } } }\n      admit.\n      admit.\n      admit.\n      admit.\n      admit.\n      admit.\n      admit.\n      admit.\n      admit.\n      admit.\n      admit.\n      admit. }\n    { rewrite landtrueR.\n      rewrite <- same_next.\n      repeat apply par_disjoint_refine;\n      try (apply Assign_refine; reflexivity). }\n    Grab Existential Variables.\n    { decide_disjoint_var_sets. }\n    { decide_disjoint_var_sets. }\n    { decide_disjoint_var_sets. }\n    { decide_disjoint_var_sets. }\n    { decide_disjoint_var_sets. }\n    { decide_disjoint_var_sets. }\n  Defined.\n*)", "meta": {"author": "dricketts", "repo": "quadcopter", "sha": "62bb21915612a141e1ffabc73df3dc2d931c54ce", "save_path": "github-repos/coq/dricketts-quadcopter", "path": "github-repos/coq/dricketts-quadcopter/quadcopter-62bb21915612a141e1ffabc73df3dc2d931c54ce/oldexamples/BoxCode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.22220688215258028}}
{"text": "Require Import Kami.AllNotations ProcKami.FU ProcKami.Div.\nRequire Import ProcKami.RiscvIsaSpec.Insts.Alu.AluFuncs.\nRequire Import List.\n\nSection Alu.\n  Context `{procParams: ProcParams}.\n\n  Section Ty.\n    Variable ty: Kind -> Type.\n\n    Definition AddInputType\n      := STRUCT_TYPE {\n           \"xlen\"  :: XlenValue;\n           \"arg1\" :: Bit (Xlen + 1);\n           \"arg2\" :: Bit (Xlen + 1)\n         }.\n\n    Definition AddOutputType\n      := STRUCT_TYPE {\n           \"xlen\" :: XlenValue;\n           \"res\" :: Bit (Xlen + 1)\n         }.\n\n    Local Open Scope kami_expr.\n\n    Definition Add: FUEntry :=\n      {| fuName := \"add\" ;\n         fuFunc := (fun ty i => LETE x: AddInputType <- i;\n                               LETC a: Bit (Xlen + 1) <- #x @% \"arg1\";\n                               LETC b: Bit (Xlen + 1) <- #x @% \"arg2\";\n                               LETC res: Bit (Xlen + 1) <- #a + #b ;\n                               RetE\n                                 (STRUCT {\n                                    \"xlen\" ::= #x @% \"xlen\";\n                                    \"res\" ::= #res\n                                  } : AddOutputType @# ty)) ;\n         fuInsts := {| instName     := \"addi\" ;\n                       xlens        := xlens_all;\n                       extensions   := \"I\" :: nil;\n                       ext_ctxt_off := nil;\n                       uniqId       := fieldVal instSizeField ('b\"11\") ::\n                                                fieldVal opcodeField ('b\"00100\") ::\n                                                fieldVal funct3Field ('b\"000\") :: nil ;\n                       inputXform   := (fun ty (cfg_pkt : ContextCfgPkt @# ty) gcpin => LETE gcp: ExecContextPkt <- gcpin;\n                                                       RetE ((STRUCT { \"xlen\"  ::= (cfg_pkt @% \"xlen\");\n                                                                       \"arg1\" ::= xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg1\");\n                                                                       \"arg2\" ::= SignExtendTruncLsb (Xlen + 1) (imm (#gcp @% \"inst\"))\n                                                             }): AddInputType @# _)) ;\n                       outputXform  := (fun ty (resultExpr : AddOutputType ## ty)\n                                         => LETE res <- resultExpr;\n                                            RetE (intRegTag (xlen_sign_extend Rlen (#res @% \"xlen\") (#res @% \"res\")))) ;\n                       optMemParams  := None ;\n                       instHints    := falseHints<|hasRs1 := true|><|hasRd := true|>\n                    |} ::\n                       {| instName     := \"slti\" ;\n                          xlens        := xlens_all;\n                          extensions   := \"I\" :: nil;\n                          ext_ctxt_off := nil;\n                          uniqId       := fieldVal instSizeField ('b\"11\") ::\n                                                   fieldVal opcodeField ('b\"00100\") ::\n                                                   fieldVal funct3Field ('b\"010\") :: nil ;\n                          inputXform   := (fun ty (cfg_pkt : ContextCfgPkt @# ty) gcpin => LETE gcp: ExecContextPkt <- gcpin;\n                                                          RetE ((STRUCT { \"xlen\"  ::= (cfg_pkt @% \"xlen\");\n                                                                          \"arg1\" ::= xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg1\");\n                                                                          \"arg2\" ::= neg (SignExtendTruncLsb\n                                                                                            (Xlen + 1) (imm (#gcp @% \"inst\")))\n                                                                }): AddInputType @# _)) ;\n                          outputXform  := (fun ty (resultExpr : AddOutputType ## ty)\n                                            => LETE res <- resultExpr;\n                                               LETC resultMsb: Bit 1 <- UniBit (TruncMsb _ 1) (#res @% \"res\");\n                                               RetE (intRegTag (ZeroExtendTruncLsb Rlen #resultMsb)));\n                          optMemParams  := None ;\n                          instHints    := falseHints<|hasRs1 := true|><|hasRd := true|>\n                       |} ::\n                       {| instName     := \"sltiu\" ;\n                          xlens        := xlens_all;\n                          extensions   := \"I\" :: nil;\n                          ext_ctxt_off := nil;\n                          uniqId       := fieldVal instSizeField ('b\"11\") ::\n                                                   fieldVal opcodeField ('b\"00100\") ::\n                                                   fieldVal funct3Field ('b\"011\") :: nil ;\n                          inputXform   := (fun ty (cfg_pkt : ContextCfgPkt @# ty) gcpin\n                                             => LETE gcp: ExecContextPkt <- gcpin;\n                                                RetE\n                                                  ((STRUCT {\n                                                    \"xlen\"  ::= (cfg_pkt @% \"xlen\");\n                                                    \"arg1\" ::= ZeroExtendTruncLsb (Xlen + 1) (xlen_sign_extend (Xlen) (cfg_pkt @% \"xlen\") (#gcp @% \"reg1\"));\n                                                    \"arg2\" ::= neg (ZeroExtendTruncLsb (Xlen + 1) (SignExtendTruncLsb Xlen (imm (#gcp @% \"inst\"))))\n                                                  }): AddInputType @# _)) ;\n                          outputXform  := (fun ty (resultExpr : AddOutputType ## ty)\n                                            => LETE res <- resultExpr;\n                                               LETC resultMsb: Bit 1 <- UniBit (TruncMsb _ 1) (#res @% \"res\");\n                                               RetE (intRegTag (ZeroExtendTruncLsb Rlen #resultMsb))) ;\n                          optMemParams  := None ;\n                          instHints    := falseHints<|hasRs1 := true|><|hasRd := true|>\n                       |} ::\n                       {| instName     := \"add\" ; \n                          xlens        := xlens_all;\n                          extensions   := \"I\" :: nil;\n                          ext_ctxt_off := nil;\n                          uniqId       := fieldVal instSizeField ('b\"11\") ::\n                                                   fieldVal opcodeField ('b\"01100\") ::\n                                                   fieldVal funct3Field ('b\"000\") ::\n                                                   fieldVal funct7Field ('b\"0000000\") :: nil ;\n                          inputXform   := (fun ty (cfg_pkt : ContextCfgPkt @# ty) gcpin => LETE gcp: ExecContextPkt <- gcpin;\n                                                          RetE ((STRUCT { \"xlen\"  ::= (cfg_pkt @% \"xlen\");\n                                                                          \"arg1\" ::= xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg1\");\n                                                                          \"arg2\" ::= xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg2\")\n                                                                }): AddInputType @# _)) ;\n                          outputXform  := (fun ty (resultExpr : AddOutputType ## ty)\n                                            => LETE res <- resultExpr;\n                                               RetE (intRegTag (xlen_sign_extend Rlen (#res @% \"xlen\") (#res @% \"res\")))) ;\n                          optMemParams  := None ;\n                          instHints    := falseHints<|hasRs1 := true|><|hasRs2 := true|><|hasRd := true|>\n                       |} ::\n                       {| instName     := \"sub\" ; \n                          xlens        := xlens_all;\n                          extensions   := \"I\" :: nil;\n                          ext_ctxt_off := nil;\n                          uniqId       := fieldVal instSizeField ('b\"11\") ::\n                                                   fieldVal opcodeField ('b\"01100\") ::\n                                                   fieldVal funct3Field ('b\"000\") ::\n                                                   fieldVal funct7Field ('b\"0100000\") :: nil ;\n                          inputXform   := (fun ty (cfg_pkt : ContextCfgPkt @# ty) gcpin => LETE gcp: ExecContextPkt <- gcpin;\n                                                          RetE ((STRUCT { \"xlen\"  ::= (cfg_pkt @% \"xlen\");\n                                                                          \"arg1\" ::= xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg1\");\n                                                                          \"arg2\" ::= neg (xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg2\"))\n                                                                }): AddInputType @# _)) ;\n                          outputXform  := (fun ty (resultExpr : AddOutputType ## ty)\n                                            => LETE res <- resultExpr;\n                                               RetE (intRegTag (xlen_sign_extend Rlen (#res @% \"xlen\") (#res @% \"res\")))) ;\n                          optMemParams  := None ;\n                          instHints    := falseHints<|hasRs1 := true|><|hasRs2 := true|><|hasRd := true|>\n                       |} ::\n                       {| instName     := \"slt\" ;\n                          xlens        := xlens_all;\n                          extensions   := \"I\" :: nil;\n                          ext_ctxt_off := nil;\n                          uniqId       := fieldVal instSizeField ('b\"11\") ::\n                                                   fieldVal opcodeField ('b\"01100\") ::\n                                                   fieldVal funct3Field ('b\"010\") ::\n                                                   fieldVal funct7Field ('b\"0000000\") :: nil ;\n                          inputXform   := (fun ty (cfg_pkt : ContextCfgPkt @# ty) gcpin => LETE gcp: ExecContextPkt <- gcpin;\n                                                          RetE ((STRUCT { \"xlen\"  ::= (cfg_pkt @% \"xlen\");\n                                                                          \"arg1\" ::= xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg1\");\n                                                                          \"arg2\" ::= neg (xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg2\"))\n                                                                }): AddInputType @# _)) ;\n                          outputXform  := (fun ty (resultExpr : AddOutputType ## ty)\n                                            => LETE res <- resultExpr;\n                                               LETC resultMsb : Bit 1 <- UniBit (TruncMsb _ 1) (#res @% \"res\") ;\n                                               RetE (intRegTag (ZeroExtendTruncLsb Rlen (#resultMsb)))) ;\n                          optMemParams  := None ;\n                          instHints    := falseHints<|hasRs1 := true|><|hasRs2 := true|><|hasRd := true|>\n                       |} ::\n                       {| instName     := \"sltu\" ;\n                          xlens        := xlens_all;\n                          extensions   := \"I\" :: nil;\n                          ext_ctxt_off := nil;\n                          uniqId       := fieldVal instSizeField ('b\"11\") ::\n                                                   fieldVal opcodeField ('b\"01100\") ::\n                                                   fieldVal funct3Field ('b\"011\") ::\n                                                   fieldVal funct7Field ('b\"0000000\") :: nil ;\n                          inputXform   := (fun ty (cfg_pkt : ContextCfgPkt @# ty) gcpin\n                                            => LETE gcp: ExecContextPkt <- gcpin;\n                                               RetE ((STRUCT {\n                                                 \"xlen\"  ::= (cfg_pkt @% \"xlen\");\n                                                 \"arg1\" ::= xlen_zero_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg1\");\n                                                 \"arg2\" ::= neg (xlen_zero_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg2\"))\n                                               }): AddInputType @# _)) ;\n                          outputXform  := (fun ty (resultExpr : AddOutputType ## ty)\n                                            => LETE res <- resultExpr;\n                                               LETC resultMsb: Bit 1 <- UniBit (TruncMsb _ 1) (#res @% \"res\");\n                                               RetE (intRegTag (ZeroExtendTruncLsb Rlen (#resultMsb)))) ;\n                          optMemParams  := None ;\n                          instHints    := falseHints<|hasRs1 := true|><|hasRs2 := true|><|hasRd := true|>\n                       |} ::\n                       {| instName     := \"addiw\" ; \n                          xlens        :=  (Xlen64 :: nil);\n                          extensions   := \"I\" :: nil;\n                          ext_ctxt_off := nil;\n                          uniqId\n                            := fieldVal instSizeField ('b\"11\") ::\n                               fieldVal opcodeField ('b\"00110\") ::\n                               fieldVal funct3Field ('b\"000\") ::\n                               nil;\n                          inputXform  \n                            := fun ty (cfg_pkt : ContextCfgPkt @# ty) gcpin\n                                 => LETE gcp\n                                      :  ExecContextPkt\n                                      <- gcpin;\n                                    RetE\n                                      (STRUCT {\n                                         \"xlen\"  ::= (cfg_pkt @% \"xlen\");\n                                         \"arg1\" ::= sign_extend_trunc 32 (Xlen + 1) (#gcp @% \"reg1\");\n                                         \"arg2\" ::= SignExtendTruncLsb (Xlen + 1) (imm (#gcp @% \"inst\")) \n                                       }: AddInputType @# _);\n                          outputXform\n                            := fun ty (resultExpr : AddOutputType ## ty)\n                                 => LETE res <- resultExpr;\n                                    RetE (intRegTag (sign_extend_trunc 32 Rlen (#res @% \"res\")));\n                          optMemParams  := None ;\n                          instHints    := falseHints<|hasRs1 := true|><|hasRd := true|>\n                       |} ::\n                       {| instName     := \"addw\" ; \n                          xlens        :=  (Xlen64 :: nil);\n                          extensions   := \"I\" :: nil;\n                          ext_ctxt_off := nil;\n                          uniqId       := fieldVal instSizeField ('b\"11\") ::\n                                                   fieldVal opcodeField ('b\"01110\") ::\n                                                   fieldVal funct3Field ('b\"000\") :: \n                                                   fieldVal funct7Field ('b\"0000000\") :: nil ;\n                          inputXform   := (fun ty (cfg_pkt : ContextCfgPkt @# ty) gcpin => LETE gcp: ExecContextPkt <- gcpin;\n                                                          RetE ((STRUCT { \"xlen\"  ::= (cfg_pkt @% \"xlen\");\n                                                                          \"arg1\" ::= xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg1\");\n                                                                          \"arg2\" ::= xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg2\")\n                                                                }): AddInputType @# _)) ;\n                          outputXform  := (fun ty (resultExpr : AddOutputType ## ty)\n                                            => LETE res <- resultExpr;\n                                               RetE (intRegTag (sign_extend_trunc 32 Rlen (#res @% \"res\")))) ;\n                          optMemParams  := None ;\n                          instHints    := falseHints<|hasRs1 := true|><|hasRs2 := true|><|hasRd := true|>\n                       |} ::\n                       {| instName     := \"subw\" ; \n                          xlens        :=  (Xlen64 :: nil);\n                          extensions   := \"I\" :: nil;\n                          ext_ctxt_off := nil;\n                          uniqId       := fieldVal instSizeField ('b\"11\") ::\n                                                   fieldVal opcodeField ('b\"01110\") ::\n                                                   fieldVal funct3Field ('b\"000\") ::\n                                                   fieldVal funct7Field ('b\"0100000\") :: nil ;\n                          inputXform   := (fun ty (cfg_pkt : ContextCfgPkt @# ty) gcpin => LETE gcp: ExecContextPkt <- gcpin;\n                                                          RetE ((STRUCT { \"xlen\"  ::= (cfg_pkt @% \"xlen\");\n                                                                          \"arg1\" ::= xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg1\");\n                                                                          \"arg2\" ::= neg (xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"reg2\"))\n                                                                }): AddInputType @# _)) ;\n                          outputXform  := (fun ty (resultExpr : AddOutputType ## ty)\n                                            => LETE res <- resultExpr;\n                                               RetE (intRegTag (sign_extend_trunc 32 Rlen (#res @% \"res\"))));\n                          optMemParams  := None ;\n                          instHints    := falseHints<|hasRs1 := true|><|hasRs2 := true|><|hasRd := true|>\n                       |} ::\n                       {| instName     := \"lui\" ; \n                          xlens        := xlens_all;\n                          extensions   := \"I\" :: nil;\n                          ext_ctxt_off := nil;\n                          uniqId\n                            := fieldVal instSizeField ('b\"11\") ::\n                               fieldVal opcodeField ('b\"01101\") ::\n                               nil;\n                          inputXform\n                            := fun ty (cfg_pkt : ContextCfgPkt @# ty) gcpin\n                                 => LETE gcp\n                                      :  ExecContextPkt\n                                      <- gcpin;\n                                    LETC imm\n                                      :  Bit 32\n                                      <- {<\n                                           UniBit (TruncMsb 12 20) (#gcp @% \"inst\"),\n                                           $$(natToWord 12 0)\n                                         >};\n                                    RetE\n                                      (STRUCT {\n                                         \"xlen\"  ::= (cfg_pkt @% \"xlen\");\n                                         \"arg1\" ::= SignExtendTruncLsb (Xlen + 1) #imm;\n                                         \"arg2\" ::= $0\n                                       }: AddInputType @# _);\n                          outputXform\n                            := fun ty (resultExpr : AddOutputType ## ty)\n                                 => LETE res <- resultExpr;\n                                    RetE (intRegTag (xlen_sign_extend Rlen (#res @% \"xlen\") (#res @% \"res\")));\n                          optMemParams  := None ;\n                          instHints    := falseHints<|hasRd := true|>\n                       |} ::\n                       {| instName     := \"auipc\" ; \n                          xlens        := xlens_all;\n                          extensions   := \"I\" :: nil;\n                          ext_ctxt_off := nil;\n                          uniqId\n                            := fieldVal instSizeField ('b\"11\") ::\n                               fieldVal opcodeField ('b\"00101\") ::\n                               nil;\n                          inputXform\n                            := fun ty (cfg_pkt : ContextCfgPkt @# ty) gcpin\n                                 => LETE gcp: ExecContextPkt <- gcpin;\n                                    RetE\n                                      (STRUCT {\n                                         \"xlen\" ::= (cfg_pkt @% \"xlen\");\n                                         \"arg1\"\n                                           ::= SignExtendTruncLsb (Xlen + 1)\n                                                 ({<\n                                                   ZeroExtendTruncMsb 20 (#gcp @% \"inst\"), \n                                                   $$(natToWord 12 0)\n                                                 >});\n                                         \"arg2\" ::= xlen_sign_extend (Xlen + 1) (cfg_pkt @% \"xlen\") (#gcp @% \"pc\")\n                                       }: AddInputType @# _);\n                          outputXform\n                            := fun ty (resultExpr : AddOutputType ## ty)\n                                 => LETE res <- resultExpr;\n                                    RetE (intRegTag (xlen_sign_extend Rlen (#res @% \"xlen\") (#res @% \"res\")));\n                          optMemParams  := None ;\n                          instHints    := falseHints<|hasRd := true|>\n                       |} ::\n                       nil\n                       \n      |}.\n\n    Local Close Scope kami_expr.\n\n  End Ty.\n\nEnd Alu.\n", "meta": {"author": "sifive", "repo": "ProcKami", "sha": "7094363c5587d50653b918c323e043105fd172d6", "save_path": "github-repos/coq/sifive-ProcKami", "path": "github-repos/coq/sifive-ProcKami/ProcKami-7094363c5587d50653b918c323e043105fd172d6/RiscvIsaSpec/Insts/Alu/Add.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22220688215258025}}
{"text": "Require Import oeuf.Common.\nRequire oeuf.StepLib.\nRequire Import Psatz.\n\nRequire Import oeuf.Utopia.\nRequire Import oeuf.Monads.\n\nRequire Export oeuf.HigherValue.\nRequire Import oeuf.AllValues.\nRequire Import oeuf.OpaqueOps.\nRequire Import oeuf.ListLemmas.\n\nInductive expr :=\n| Arg\n| Self\n| Var (i : nat)\n| Deref (e : expr) (off : nat)\n.\n\nInductive stmt :=\n| Skip\n| Seq (s1 : stmt) (s2 : stmt)\n| Call (dst : nat) (f : expr) (a : expr)\n| MkConstr (dst : nat) (tag : nat) (args : list expr)\n| Switch (dst : nat) (cases : list stmt)\n| MkClose (dst : nat) (f : function_name) (free : list expr)\n| OpaqueOp (dst : nat) (op : opaque_oper_name) (args : list expr)\n| Assign (dst : nat) (e : expr)\n.\n\nDefinition env := list (stmt * expr).\n\n\n(* Continuation-based step relation *)\n\nRecord frame := Frame {\n    arg : value;\n    self : value;\n    locals : list (nat * value)\n}.\n\nDefinition set f l v :=\n    Frame (arg f) (self f) ((l, v) :: locals f).\n\nDefinition local f l := lookup (locals f) l.\n\n\n\nInductive cont :=\n| Kseq (code : stmt) (k : cont)\n| Kswitch (k : cont)\n| Kreturn (ret : expr) (k : cont)\n| Kcall (dst : nat) (f : frame) (k : cont)\n| Kstop (ret : expr).\n\nInductive state :=\n| Run (s : stmt) (f : frame) (k : cont)\n| Return (v : value) (k : cont)\n| Stop (v : value).\n\nInductive eval : frame -> expr -> value -> Prop :=\n| EArg : forall f,\n        eval f Arg (arg f)\n| ESelf : forall f,\n        eval f Self (self f)\n\n| EVar : forall f i v,\n        local f i = Some v ->\n        eval f (Var i) v\n\n| EDerefConstr : forall f e off tag args v,\n        eval f e (Constr tag args) ->\n        nth_error args off = Some v ->\n        eval f (Deref e off) v\n| EDerefClose : forall f e off fname free v,\n        eval f e (Close fname free) ->\n        nth_error free off = Some v ->\n        eval f (Deref e off) v\n.\n\nInductive sstep (E : env) : state -> state -> Prop :=\n| SSeq : forall s1 s2 f k,\n        sstep E (Run (Seq s1 s2) f k)\n                (Run s1 f (Kseq s2 k))\n\n| SConstrDone : forall dst tag args f k vs,\n        Forall2 (eval f) args vs ->\n        sstep E (Run (MkConstr dst tag args) f k)\n                (Run Skip (set f dst (Constr tag vs)) k)\n| SCloseDone : forall dst fname free f k vs,\n        Forall2 (eval f) free vs ->\n        sstep E (Run (MkClose dst fname free) f k)\n                (Run Skip (set f dst (Close fname vs)) k)\n| SOpaqueOpDone : forall dst op args f k vs v,\n        Forall2 (eval f) args vs ->\n        opaque_oper_denote_higher op vs = Some v ->\n        sstep E (Run (OpaqueOp dst op args) f k)\n                (Run Skip (set f dst v) k)\n\n| SMakeCall : forall dst fe ae f k  fname free arg body ret,\n        eval f fe (Close fname free) ->\n        eval f ae arg ->\n        nth_error E fname = Some (body, ret) ->\n        sstep E (Run (Call dst fe ae) f k)\n                (Run body (Frame arg (Close fname free) [])\n                    (Kreturn ret (Kcall dst f k)))\n\n(* NB: `Switch` still has an implicit target of `Arg` *)\n| SSwitchinate : forall dst cases f k  tag args case,\n        arg f = Constr tag args ->\n        nth_error cases tag = Some case ->\n        sstep E (Run (Switch dst cases) f k)\n                (Run case f (Kswitch k))\n\n| SAssign : forall dst src f k v,\n        eval f src v ->\n        sstep E (Run (Assign dst src) f k)\n                (Run Skip (set f dst v) k)\n\n| SContSeq : forall f s k,\n        sstep E (Run Skip f (Kseq s k))\n                (Run s f k)\n| SContSwitch : forall f k,\n        sstep E (Run Skip f (Kswitch k))\n                (Run Skip f k)\n| SContReturn : forall f ret k v,\n        eval f ret v ->\n        sstep E (Run Skip f (Kreturn ret k))\n                (Return v k)\n| SContCall : forall v dst f k,\n        sstep E (Return v (Kcall dst f k))\n                (Run Skip (set f dst v) k)\n| SContStop : forall ret f v,\n        eval f ret v ->\n        sstep E (Run Skip f (Kstop ret))\n                (Stop v)\n.\n\n\n\nDefinition sstar BE := StepLib.sstar (sstep BE).\nDefinition SStarNil := @StepLib.SStarNil state.\nDefinition SStarCons := @StepLib.SStarCons state.\n\nDefinition splus BE := StepLib.splus (sstep BE).\nDefinition SPlusOne := @StepLib.SPlusOne state.\nDefinition SPlusCons := @StepLib.SPlusCons state.\n\n\n\nRequire Import oeuf.Metadata.\nRequire oeuf.Semantics.\n\n\nDefinition prog_type : Type := env * list metadata.\nDefinition val_level := VlHigher.\nDefinition valtype := value_type val_level.\n\nInductive is_callstate (prog : prog_type) : valtype -> valtype -> state -> Prop :=\n| IsCallstate : forall fname free av body ret,\n        nth_error (fst prog) fname = Some (body, ret) ->\n        let fv := Close fname free in\n        HigherValue.public_value (snd prog) fv ->\n        HigherValue.public_value (snd prog) av ->\n        is_callstate prog fv av\n            (Run body\n                 (Frame av fv [])\n                 (Kstop ret)).\n\nInductive final_state (prog : prog_type) : state -> valtype -> Prop :=\n| FinalState : forall v,\n        HigherValue.public_value (snd prog) v ->\n        final_state prog (Stop v) v.\n\nDefinition initial_env (prog : prog_type) : env := fst prog.\n\nDefinition semantics (prog : prog_type) : Semantics.semantics :=\n  @Semantics.Semantics_gen state env val_level\n                 (is_callstate prog)\n                 (sstep)\n                 (final_state prog)\n                 (initial_env prog).\n\n\n(*\n\nDefinition prog_type : Type := env * list metadata.\n\nInductive initial_state (prog : prog_type) : state -> Prop :=.\n\nInductive final_state (prog : prog_type) : state -> Prop :=\n| FinalState : forall v, final_state prog (Stop v).\n\nDefinition initial_env (prog : prog_type) : env := fst prog.\n\nDefinition semantics (prog : prog_type) : Semantics.semantics :=\n  @Semantics.Semantics_gen state env\n                 (sstep)\n                 (initial_state prog)\n                 (final_state prog)\n                 (initial_env prog).\n\n*)\n\n(*\n * Mutual recursion/induction schemes for expr\n *)\n\nDefinition stmt_rect_mut\n        (P : stmt -> Type)\n        (Pl : list stmt -> Type)\n    (HSkip :    P Skip)\n    (HSeq :     forall s1 s2, P s1 -> P s2 -> P (Seq s1 s2))\n    (HCall :    forall dst f a, P (Call dst f a))\n    (HConstr :  forall dst tag args, P (MkConstr dst tag args))\n    (HSwitch :  forall dst cases, Pl cases -> P (Switch dst cases))\n    (HClose :   forall dst fname free, P (MkClose dst fname free))\n    (HOpaqueOp : forall dst op args, P (OpaqueOp dst op args))\n    (HAssign :  forall dst src, P (Assign dst src))\n    (Hnil :     Pl [])\n    (Hcons :    forall i is, P i -> Pl is -> Pl (i :: is))\n    (i : stmt) : P i :=\n    let fix go i :=\n        let fix go_list is :=\n            match is as is_ return Pl is_ with\n            | [] => Hnil\n            | i :: is => Hcons i is (go i) (go_list is)\n            end in\n        match i as i_ return P i_ with\n        | Skip => HSkip\n        | Seq s1 s2 => HSeq s1 s2 (go s1) (go s2)\n        | Call dst f a => HCall dst f a\n        | MkConstr dst tag args => HConstr dst tag args\n        | Switch dst cases => HSwitch dst cases (go_list cases)\n        | MkClose dst fname free => HClose dst fname free\n        | OpaqueOp dst op args => HOpaqueOp dst op args\n        | Assign dst src => HAssign dst src\n        end in go i.\n\n(* Useful wrapper for `expr_rect_mut with (Pl := Forall P)` *)\nDefinition stmt_ind' (P : stmt -> Prop)\n    (HSkip :    P Skip)\n    (HSeq :     forall s1 s2, P s1 -> P s2 -> P (Seq s1 s2))\n    (HCall :    forall dst f a, P (Call dst f a))\n    (HConstr :  forall dst tag args, P (MkConstr dst tag args))\n    (HSwitch :  forall dst cases, Forall P cases -> P (Switch dst cases))\n    (HClose :   forall dst fname free, P (MkClose dst fname free))\n    (HOpaqueOp : forall dst op args, P (OpaqueOp dst op args))\n    (HAssign :  forall dst src, P (Assign dst src))\n    (i : stmt) : P i :=\n    ltac:(refine (@stmt_rect_mut P (Forall P)\n        HSkip HSeq HCall HConstr HSwitch HClose HOpaqueOp HAssign _ _ i); eauto).\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/FlatExprRet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22220688215258025}}
{"text": "Require Import Coqlib Maps Integers Floats Errors Globalenvs.\nRequire Import AST Linking Values Memory Events.\n\nRecord attr : Type := mk_attr {\n                          attr_volatile: bool;\n                          attr_alignas: option N         (**r log2 of required alignment *)\n                        }.\n\nInductive signedness : Type :=\n| Signed: signedness\n| Unsigned: signedness.\n\nInductive intsize : Type :=\n| I8: intsize\n| I16: intsize\n| I32: intsize\n| IBool: intsize.\n\nInductive floatsize : Type :=\n| F32: floatsize\n| F64: floatsize.\n\nInductive type : Type :=\n| Tvoid: type                                    (**r the [void] type *)\n| Tint: intsize -> signedness -> attr -> type    (**r integer types *)\n| Tlong: signedness -> attr -> type              (**r 64-bit integer types *)\n| Tfloat: floatsize -> attr -> type              (**r floating-point types *)\n| Tpointer: type -> attr -> type                 (**r pointer types ([*ty]) *)\n| Tarray: type -> Z -> attr -> type              (**r array types ([ty[len]]) *)\n| Tfunction: typelist -> type -> calling_convention -> type    (**r function types *)\n| Tstruct: ident -> attr -> type                 (**r struct types *)\n| Tunion: ident -> attr -> type                  (**r union types *)\nwith typelist : Type :=\n     | Tnil: typelist\n     | Tcons: type -> typelist -> typelist.\n\n\nInductive expr : Type :=\n| Eval (v: val) (ty: type)\n| Evar (x: ident) (ty: type)\n| Eseqand (r1 r2: expr) (ty: type)\n| Econdition (r1 r2 r3: expr) (ty: type)\n| Eparen (r: expr) (tycast: type) (ty: type).\n\nInductive kind : Type := LV | RV.\n\nInductive context: kind -> kind -> (expr -> expr) -> Prop :=\n| ctx_top: forall k,\n    context k k (fun x => x)\n| ctx_seqand: forall k C r2 ty,\n    context k RV C -> context k RV (fun x => Eseqand (C x) r2 ty)\n| ctx_condition: forall k C r2 r3 ty,\n    context k RV C -> context k RV (fun x => Econdition (C x) r2 r3 ty)\n| ctx_paren: forall k C ty tycast,\n    context k RV C -> context k RV (fun x => Eparen (C x) tycast ty).\n\n(** Strategy for reducing expressions. We reduce the leftmost innermost\n  non-simple subexpression, evaluating its arguments (which are necessarily\n  simple expressions) with the big-step semantics.\n  If there are none, the whole expression is simple and is evaluated in\n  one big step. *)\nDefinition env := PTree.t block.\nDefinition empty_env: env := (PTree.empty block).\n\nSection SIMPLE_EXPRS.\n\n  Variable e: env.\n\n\n  Inductive eval_simple_lvalue: expr -> block -> ptrofs -> Prop :=\n  | esl_var_local: forall x b ty,\n      e!x = Some b ->\n      eval_simple_lvalue (Evar x ty) b Ptrofs.zero.\n\n  Inductive eval_simple_rvalue: expr -> val -> Prop :=\n  | esr_val: forall v ty, eval_simple_rvalue (Eval v ty) v.\n\nEnd SIMPLE_EXPRS.\n\n\nInductive state: Type :=\n| ExprState                           (**r reduction of an expression *)\n    (r: expr)\n    (e: env)\n    (m: mem) : state.\n\n\nInductive classify_bool_cases : Type :=\n| bool_case_i                           (**r integer *)\n| bool_case_l                           (**r long *)\n| bool_case_f                           (**r double float *)\n| bool_case_s                           (**r single float *)\n| bool_default.\n\nDefinition noattr := {| attr_volatile := false; attr_alignas := None |}.\n\nDefinition change_attributes (f: attr -> attr) (ty: type) : type :=\n  match ty with\n  | Tvoid => ty\n  | Tint sz si a => Tint sz si (f a)\n  | Tlong si a => Tlong si (f a)\n  | Tfloat sz a => Tfloat sz (f a)\n  | Tpointer elt a => Tpointer elt (f a)\n  | Tarray elt sz a => Tarray elt sz (f a)\n  | Tfunction args res cc => ty\n  | Tstruct id a => Tstruct id (f a)\n  | Tunion id a => Tunion id (f a)\n  end.\n\nDefinition remove_attributes (ty: type) : type :=\n  change_attributes (fun _ => noattr) ty.\n\nDefinition typeconv (ty: type) : type :=\n  match ty with\n  | Tint (I8 | I16 | IBool) _ _ => Tint I32 Signed noattr\n  | Tarray t sz a       => Tpointer t noattr\n  | Tfunction _ _ _     => Tpointer ty noattr\n  | _                   => remove_attributes ty\n  end.\n\n\nDefinition classify_bool (ty: type) : classify_bool_cases :=\n  match typeconv ty with\n  | Tint _ _ _ => bool_case_i\n  | Tpointer _ _ => if Archi.ptr64 then bool_case_l else bool_case_i\n  | Tfloat F64 _ => bool_case_f\n  | Tfloat F32 _ => bool_case_s\n  | Tlong _ _ => bool_case_l\n  | _ => bool_default\n  end.\n\n\nDefinition bool_val (v: val) (t: type) (m: mem) : option bool :=\n  match classify_bool t with\n  | bool_case_i =>\n    match v with\n    | Vint n => Some (negb (Int.eq n Int.zero))\n    | Vptr b ofs =>\n      if Archi.ptr64 then None else\n        if Mem.weak_valid_pointer m b (Ptrofs.unsigned ofs) then Some true else None\n    | _ => None\n    end\n  | bool_case_l =>\n    match v with\n    | Vlong n => Some (negb (Int64.eq n Int64.zero))\n    | Vptr b ofs =>\n      if negb Archi.ptr64 then None else\n        if Mem.weak_valid_pointer m b (Ptrofs.unsigned ofs) then Some true else None\n    | _ => None\n    end\n  | bool_case_f =>\n    match v with\n    | Vfloat f => Some (negb (Float.cmp Ceq f Float.zero))\n    | _ => None\n    end\n  | bool_case_s =>\n    match v with\n    | Vsingle f => Some (negb (Float32.cmp Ceq f Float32.zero))\n    | _ => None\n    end\n  | bool_default => None\n  end.\n\nDefinition typeof (a: expr) : type :=\n  match a with\n  | Evar _ ty => ty\n  | Eval _ ty => ty\n  | Econdition _ _ _ ty => ty\n  | Eseqand _ _ ty => ty\n  | Eparen _ _ ty => ty\n  end.\n\n\nInductive classify_cast_cases : Type :=\n  | cast_case_pointer                              (**r between pointer types or intptr_t types *)\n  | cast_case_i2i (sz2:intsize) (si2:signedness)   (**r int -> int *)\n  | cast_case_f2f                                  (**r double -> double *)\n  | cast_case_s2s                                  (**r single -> single *)\n  | cast_case_f2s                                  (**r double -> single *)\n  | cast_case_s2f                                  (**r single -> double *)\n  | cast_case_i2f (si1: signedness)                (**r int -> double *)\n  | cast_case_i2s (si1: signedness)                (**r int -> single *)\n  | cast_case_f2i (sz2:intsize) (si2:signedness)   (**r double -> int *)\n  | cast_case_s2i (sz2:intsize) (si2:signedness)   (**r single -> int *)\n  | cast_case_l2l                       (**r long -> long *)\n  | cast_case_i2l (si1: signedness)     (**r int -> long *)\n  | cast_case_l2i (sz2: intsize) (si2: signedness) (**r long -> int *)\n  | cast_case_l2f (si1: signedness)                (**r long -> double *)\n  | cast_case_l2s (si1: signedness)                (**r long -> single *)\n  | cast_case_f2l (si2:signedness)                 (**r double -> long *)\n  | cast_case_s2l (si2:signedness)                 (**r single -> long *)\n  | cast_case_i2bool                               (**r int -> bool *)\n  | cast_case_l2bool                               (**r long -> bool *)\n  | cast_case_f2bool                               (**r double -> bool *)\n  | cast_case_s2bool                               (**r single -> bool *)\n  | cast_case_struct (id1 id2: ident)              (**r struct -> struct *)\n  | cast_case_union  (id1 id2: ident)              (**r union -> union *)\n  | cast_case_void                                 (**r any -> void *)\n  | cast_case_default.\n\nLemma intsize_eq: forall (s1 s2: intsize), {s1=s2} + {s1<>s2}.\nProof.\n  decide equality.\nDefined.\n\nDefinition classify_cast (tfrom tto: type) : classify_cast_cases :=\n  match tto, tfrom with\n  (* To [void] *)\n  | Tvoid, _ => cast_case_void\n  (* To [_Bool] *)\n  | Tint IBool _ _, Tint _ _ _ => cast_case_i2bool\n  | Tint IBool _ _, Tlong _ _ => cast_case_l2bool\n  | Tint IBool _ _, Tfloat F64 _ => cast_case_f2bool\n  | Tint IBool _ _, Tfloat F32 _ => cast_case_s2bool\n  | Tint IBool _ _, (Tpointer _ _ | Tarray _ _ _ | Tfunction _ _ _) => \n      if Archi.ptr64 then cast_case_l2bool else cast_case_i2bool\n  (* To [int] other than [_Bool] *)\n  | Tint sz2 si2 _, Tint _ _ _ =>\n      if Archi.ptr64 then cast_case_i2i sz2 si2\n      else if intsize_eq sz2 I32 then cast_case_pointer\n      else cast_case_i2i sz2 si2\n  | Tint sz2 si2 _, Tlong _ _ => cast_case_l2i sz2 si2\n  | Tint sz2 si2 _, Tfloat F64 _ => cast_case_f2i sz2 si2\n  | Tint sz2 si2 _, Tfloat F32 _ => cast_case_s2i sz2 si2\n  | Tint sz2 si2 _, (Tpointer _ _ | Tarray _ _ _ | Tfunction _ _ _) =>\n      if Archi.ptr64 then cast_case_l2i sz2 si2\n      else if intsize_eq sz2 I32 then cast_case_pointer\n      else cast_case_i2i sz2 si2\n  (* To [long] *)\n  | Tlong _ _, Tlong _ _ =>\n      if Archi.ptr64 then cast_case_pointer else cast_case_l2l\n  | Tlong _ _, Tint sz1 si1 _ => cast_case_i2l si1\n  | Tlong si2 _, Tfloat F64 _ => cast_case_f2l si2\n  | Tlong si2 _, Tfloat F32 _ => cast_case_s2l si2\n  | Tlong si2 _, (Tpointer _ _ | Tarray _ _ _ | Tfunction _ _ _) =>\n      if Archi.ptr64 then cast_case_pointer else cast_case_i2l si2\n  (* To [float] *)\n  | Tfloat F64 _, Tint sz1 si1 _ => cast_case_i2f si1\n  | Tfloat F32 _, Tint sz1 si1 _ => cast_case_i2s si1\n  | Tfloat F64 _, Tlong si1 _ => cast_case_l2f si1\n  | Tfloat F32 _, Tlong si1 _ => cast_case_l2s si1\n  | Tfloat F64 _, Tfloat F64 _ => cast_case_f2f\n  | Tfloat F32 _, Tfloat F32 _ => cast_case_s2s\n  | Tfloat F64 _, Tfloat F32 _ => cast_case_s2f\n  | Tfloat F32 _, Tfloat F64 _ => cast_case_f2s\n  (* To pointer types *)\n  | Tpointer _ _, Tint _ _ _ =>\n      if Archi.ptr64 then cast_case_i2l Unsigned else cast_case_pointer\n  | Tpointer _ _, Tlong _ _ =>\n      if Archi.ptr64 then cast_case_pointer else cast_case_l2i I32 Unsigned\n  | Tpointer _ _, (Tpointer _ _ | Tarray _ _ _ | Tfunction _ _ _) => cast_case_pointer\n  (* To struct or union types *)\n  | Tstruct id2 _, Tstruct id1 _ => cast_case_struct id1 id2\n  | Tunion id2 _, Tunion id1 _ => cast_case_union id1 id2\n  (* Catch-all *)\n  | _, _ => cast_case_default\n  end.\n\nDefinition cast_int_int (sz: intsize) (sg: signedness) (i: int) : int :=\n  match sz, sg with\n  | I8, Signed => Int.sign_ext 8 i\n  | I8, Unsigned => Int.zero_ext 8 i\n  | I16, Signed => Int.sign_ext 16 i\n  | I16, Unsigned => Int.zero_ext 16 i\n  | I32, _ => i\n  | IBool, _ => if Int.eq i Int.zero then Int.zero else Int.one\n  end.\n\nDefinition cast_int_float (si: signedness) (i: int) : float :=\n  match si with\n  | Signed => Float.of_int i\n  | Unsigned => Float.of_intu i\n  end.\n\nDefinition cast_float_int (si : signedness) (f: float) : option int :=\n  match si with\n  | Signed => Float.to_int f\n  | Unsigned => Float.to_intu f\n  end.\n\nDefinition cast_int_single (si: signedness) (i: int) : float32 :=\n  match si with\n  | Signed => Float32.of_int i\n  | Unsigned => Float32.of_intu i\n  end.\n\nDefinition cast_single_int (si : signedness) (f: float32) : option int :=\n  match si with\n  | Signed => Float32.to_int f\n  | Unsigned => Float32.to_intu f\n  end.\n\nDefinition cast_int_long (si: signedness) (i: int) : int64 :=\n  match si with\n  | Signed => Int64.repr (Int.signed i)\n  | Unsigned => Int64.repr (Int.unsigned i)\n  end.\n\nDefinition cast_long_float (si: signedness) (i: int64) : float :=\n  match si with\n  | Signed => Float.of_long i\n  | Unsigned => Float.of_longu i\n  end.\n\nDefinition cast_long_single (si: signedness) (i: int64) : float32 :=\n  match si with\n  | Signed => Float32.of_long i\n  | Unsigned => Float32.of_longu i\n  end.\n\nDefinition cast_float_long (si : signedness) (f: float) : option int64 :=\n  match si with\n  | Signed => Float.to_long f\n  | Unsigned => Float.to_longu f\n  end.\n\nDefinition cast_single_long (si : signedness) (f: float32) : option int64 :=\n  match si with\n  | Signed => Float32.to_long f\n  | Unsigned => Float32.to_longu f\n  end.\n\nDefinition sem_cast (v: val) (t1 t2: type) (m: mem): option val :=\n  match classify_cast t1 t2 with\n  | cast_case_pointer =>\n      match v with\n      | Vptr _ _ => Some v\n      | Vint _ => if Archi.ptr64 then None else Some v\n      | Vlong _ => if Archi.ptr64 then Some v else None\n      | _ => None\n      end\n  | cast_case_i2i sz2 si2 =>\n      match v with\n      | Vint i => Some (Vint (cast_int_int sz2 si2 i))\n      | _ => None\n      end\n  | cast_case_f2f =>\n      match v with\n      | Vfloat f => Some (Vfloat f)\n      | _ => None\n      end\n  | cast_case_s2s =>\n      match v with\n      | Vsingle f => Some (Vsingle f)\n      | _ => None\n      end\n  | cast_case_s2f =>\n      match v with\n      | Vsingle f => Some (Vfloat (Float.of_single f))\n      | _ => None\n      end\n  | cast_case_f2s =>\n      match v with\n      | Vfloat f => Some (Vsingle (Float.to_single f))\n      | _ => None\n      end\n  | cast_case_i2f si1 =>\n      match v with\n      | Vint i => Some (Vfloat (cast_int_float si1 i))\n      | _ => None\n      end\n  | cast_case_i2s si1 =>\n      match v with\n      | Vint i => Some (Vsingle (cast_int_single si1 i))\n      | _ => None\n      end\n  | cast_case_f2i sz2 si2 =>\n      match v with\n      | Vfloat f =>\n          match cast_float_int si2 f with\n          | Some i => Some (Vint (cast_int_int sz2 si2 i))\n          | None => None\n          end\n      | _ => None\n      end\n  | cast_case_s2i sz2 si2 =>\n      match v with\n      | Vsingle f =>\n          match cast_single_int si2 f with\n          | Some i => Some (Vint (cast_int_int sz2 si2 i))\n          | None => None\n          end\n      | _ => None\n      end\n  | cast_case_i2bool =>\n      match v with\n      | Vint n =>\n          Some(Vint(if Int.eq n Int.zero then Int.zero else Int.one))\n      | Vptr b ofs =>\n          if Archi.ptr64 then None else\n          if Mem.weak_valid_pointer m b (Ptrofs.unsigned ofs) then Some Vone else None\n      | _ => None\n      end\n  | cast_case_l2bool =>\n      match v with\n      | Vlong n =>\n          Some(Vint(if Int64.eq n Int64.zero then Int.zero else Int.one))\n      | Vptr b ofs =>\n          if negb Archi.ptr64 then None else\n          if Mem.weak_valid_pointer m b (Ptrofs.unsigned ofs) then Some Vone else None\n\n      | _ => None\n      end\n  | cast_case_f2bool =>\n      match v with\n      | Vfloat f =>\n          Some(Vint(if Float.cmp Ceq f Float.zero then Int.zero else Int.one))\n      | _ => None\n      end\n  | cast_case_s2bool =>\n      match v with\n      | Vsingle f =>\n          Some(Vint(if Float32.cmp Ceq f Float32.zero then Int.zero else Int.one))\n      | _ => None\n      end\n  | cast_case_l2l =>\n      match v with\n      | Vlong n => Some (Vlong n)\n      | _ => None\n      end\n  | cast_case_i2l si =>\n      match v with\n      | Vint n => Some(Vlong (cast_int_long si n))\n      | _ => None\n      end\n  | cast_case_l2i sz si =>\n      match v with\n      | Vlong n => Some(Vint (cast_int_int sz si (Int.repr (Int64.unsigned n))))\n      | _ => None\n      end\n  | cast_case_l2f si1 =>\n      match v with\n      | Vlong i => Some (Vfloat (cast_long_float si1 i))\n      | _ => None\n      end\n  | cast_case_l2s si1 =>\n      match v with\n      | Vlong i => Some (Vsingle (cast_long_single si1 i))\n      | _ => None\n      end\n  | cast_case_f2l si2 =>\n      match v with\n      | Vfloat f =>\n          match cast_float_long si2 f with\n          | Some i => Some (Vlong i)\n          | None => None\n          end\n      | _ => None\n      end\n  | cast_case_s2l si2 =>\n      match v with\n      | Vsingle f =>\n          match cast_single_long si2 f with\n          | Some i => Some (Vlong i)\n          | None => None\n          end\n      | _ => None\n      end\n  | cast_case_struct id1 id2 =>\n      match v with\n      | Vptr b ofs =>\n          if ident_eq id1 id2 then Some v else None\n      | _ => None\n      end\n  | cast_case_union id1 id2 =>\n      match v with\n      | Vptr b ofs =>\n          if ident_eq id1 id2 then Some v else None\n      | _ => None\n      end\n  | cast_case_void =>\n      Some v\n  | cast_case_default =>\n      None\n  end.\n\nDefinition type_int32s := Tint I32 Signed noattr.\n\nDefinition type_bool := Tint IBool Signed noattr.\n\nInductive estep: state -> trace -> state -> Prop :=\n| step_expr: forall r e m v ty,\n    eval_simple_rvalue r v ->\n    match r with Eval _ _ => False | _ => True end ->\n    ty = typeof r ->\n    estep (ExprState r e m)\n          E0 (ExprState (Eval v ty) e m)\n| step_seqand_true: forall C r1 r2 ty e m v,\n    context RV RV C ->\n    eval_simple_rvalue r1 v ->\n    bool_val v (typeof r1) m = Some true ->\n    estep (ExprState (C (Eseqand r1 r2 ty)) e m)\n          E0 (ExprState (C (Eparen r2 type_bool ty)) e m)\n| step_seqand_false: forall C r1 r2 ty e m v,\n    context RV RV C ->\n    eval_simple_rvalue r1 v ->\n    bool_val v (typeof r1) m = Some false ->\n    estep (ExprState (C (Eseqand r1 r2 ty)) e m)\n          E0 (ExprState (C (Eval (Vint Int.zero) ty)) e m)\n| step_condition: forall C r1 r2 r3 ty e m v b,\n    context RV RV C ->\n    eval_simple_rvalue r1 v ->\n    bool_val v (typeof r1) m = Some b ->\n    estep (ExprState (C (Econdition r1 r2 r3 ty)) e m)\n          E0 (ExprState (C (Eparen (if b then r2 else r3) ty ty)) e m)\n| step_paren: forall C r tycast ty e m v1 v,\n    context RV RV C ->\n    eval_simple_rvalue r v1 ->\n    sem_cast v1 (typeof r) tycast m = Some v ->\n    estep (ExprState (C (Eparen r tycast ty)) e m)\n          E0 (ExprState (C (Eval v ty)) e m).\n\n", "meta": {"author": "Artalik", "repo": "monad-frame-src", "sha": "7aa9364eb94c10f447a215351cd84dcbc8506714", "save_path": "github-repos/coq/Artalik-monad-frame-src", "path": "github-repos/coq/Artalik-monad-frame-src/monad-frame-src-7aa9364eb94c10f447a215351cd84dcbc8506714/LightComp/cfrontend/Csyntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22220688215258025}}
{"text": "From stdpp Require Import namespaces.\nFrom iris.algebra Require Export gmap coPset local_updates.\nFrom iris.algebra Require Import updates proofmode_classes.\nFrom iris.prelude Require Import options.\n\n(** The camera [namespace_map A] over a camera [A] provides the connectives\n[namespace_map_data N a], which associates data [a : A] with a namespace [N],\nand [namespace_map_token E], which says that no data has been associated with\nthe namespaces in the mask [E]. The important properties of this camera are:\n\n- The lemma [namespace_map_token_union] enables one to split [namespace_map_token]\n  w.r.t. disjoint union. That is, if we have [E1 ## E2], then we get\n  [namespace_map_token (E1 ∪ E2) = namespace_map_token E1 ⋅ namespace_map_token E2]\n- The lemma [namespace_map_alloc_update] provides a frame preserving update to\n  associate data to a namespace [namespace_map_token E ~~> namespace_map_data N a]\n  provided [↑N ⊆ E] and [✓ a]. *)\n\nRecord namespace_map (A : Type) := NamespaceMap {\n  namespace_map_data_proj : gmap positive A;\n  namespace_map_token_proj : coPset_disj\n}.\nAdd Printing Constructor namespace_map.\nGlobal Arguments NamespaceMap {_} _ _.\nGlobal Arguments namespace_map_data_proj {_} _.\nGlobal Arguments namespace_map_token_proj {_} _.\nGlobal Instance: Params (@NamespaceMap) 1 := {}.\nGlobal Instance: Params (@namespace_map_data_proj) 1 := {}.\nGlobal Instance: Params (@namespace_map_token_proj) 1 := {}.\n\n(** TODO: [positives_flatten] violates the namespace abstraction. *)\nDefinition namespace_map_data {A : cmra} (N : namespace) (a : A) : namespace_map A :=\n  NamespaceMap {[ positives_flatten N := a ]} ε.\nDefinition namespace_map_token {A : cmra} (E : coPset) : namespace_map A :=\n  NamespaceMap ∅ (CoPset E).\nGlobal Instance: Params (@namespace_map_data) 2 := {}.\n\n(* Ofe *)\nSection ofe.\nContext {A : ofe}.\nImplicit Types x y : namespace_map A.\n\nLocal Instance namespace_map_equiv : Equiv (namespace_map A) := λ x y,\n  namespace_map_data_proj x ≡ namespace_map_data_proj y ∧\n  namespace_map_token_proj x = namespace_map_token_proj y.\nLocal Instance namespace_map_dist : Dist (namespace_map A) := λ n x y,\n  namespace_map_data_proj x ≡{n}≡ namespace_map_data_proj y ∧\n  namespace_map_token_proj x = namespace_map_token_proj y.\n\nGlobal Instance NamespaceMap_ne : NonExpansive2 (@NamespaceMap A).\nProof. by split. Qed.\nGlobal Instance NamespaceMap_proper : Proper ((≡) ==> (=) ==> (≡)) (@NamespaceMap A).\nProof. by split. Qed.\nGlobal Instance namespace_map_data_proj_ne: NonExpansive (@namespace_map_data_proj A).\nProof. by destruct 1. Qed.\nGlobal Instance namespace_map_data_proj_proper :\n  Proper ((≡) ==> (≡)) (@namespace_map_data_proj A).\nProof. by destruct 1. Qed.\n\nDefinition namespace_map_ofe_mixin : OfeMixin (namespace_map A).\nProof.\n  by apply (iso_ofe_mixin\n    (λ x, (namespace_map_data_proj x, namespace_map_token_proj x))).\nQed.\nCanonical Structure namespace_mapO :=\n  Ofe (namespace_map A) namespace_map_ofe_mixin.\n\nGlobal Instance NamespaceMap_discrete a b :\n  Discrete a → Discrete b → Discrete (NamespaceMap a b).\nProof. intros ?? [??] [??]; split; unfold_leibniz; by eapply discrete. Qed.\nGlobal Instance namespace_map_ofe_discrete :\n  OfeDiscrete A → OfeDiscrete namespace_mapO.\nProof. intros ? [??]; apply _. Qed.\nEnd ofe.\n\nGlobal Arguments namespace_mapO : clear implicits.\n\n(* Camera *)\nSection cmra.\nContext {A : cmra}.\nImplicit Types a b : A.\nImplicit Types x y : namespace_map A.\n\nGlobal Instance namespace_map_data_ne i : NonExpansive (@namespace_map_data A i).\nProof. solve_proper. Qed.\nGlobal Instance namespace_map_data_proper N :\n  Proper ((≡) ==> (≡)) (@namespace_map_data A N).\nProof. solve_proper. Qed.\nGlobal Instance namespace_map_data_discrete N a :\n  Discrete a → Discrete (namespace_map_data N a).\nProof. intros. apply NamespaceMap_discrete; apply _. Qed.\nGlobal Instance namespace_map_token_discrete E : Discrete (@namespace_map_token A E).\nProof. intros. apply NamespaceMap_discrete; apply _. Qed.\n\nLocal Instance namespace_map_valid_instance : Valid (namespace_map A) := λ x,\n  match namespace_map_token_proj x with\n  | CoPset E =>\n     ✓ (namespace_map_data_proj x) ∧\n     (* dom (namespace_map_data_proj x) ⊥ E *)\n     ∀ i, namespace_map_data_proj x !! i = None ∨ i ∉ E\n  | CoPsetBot => False\n  end.\nGlobal Arguments namespace_map_valid_instance !_ /.\nLocal Instance namespace_map_validN_instance : ValidN (namespace_map A) := λ n x,\n  match namespace_map_token_proj x with\n  | CoPset E =>\n     ✓{n} (namespace_map_data_proj x) ∧\n     (* dom (namespace_map_data_proj x) ⊥ E *)\n     ∀ i, namespace_map_data_proj x !! i = None ∨ i ∉ E\n  | CoPsetBot => False\n  end.\nGlobal Arguments namespace_map_validN_instance !_ /.\nLocal Instance namespace_map_pcore_instance : PCore (namespace_map A) := λ x,\n  Some (NamespaceMap (core (namespace_map_data_proj x)) ε).\nLocal Instance namespace_map_op_instance : Op (namespace_map A) := λ x y,\n  NamespaceMap (namespace_map_data_proj x ⋅ namespace_map_data_proj y)\n               (namespace_map_token_proj x ⋅ namespace_map_token_proj y).\n\nDefinition namespace_map_valid_eq :\n  valid = λ x, match namespace_map_token_proj x with\n               | CoPset E =>\n                  ✓ (namespace_map_data_proj x) ∧\n                  (* dom (namespace_map_data_proj x) ⊥ E *)\n                  ∀ i, namespace_map_data_proj x !! i = None ∨ i ∉ E\n               | CoPsetBot => False\n               end := eq_refl _.\nDefinition namespace_map_validN_eq :\n  validN = λ n x, match namespace_map_token_proj x with\n                  | CoPset E =>\n                     ✓{n} (namespace_map_data_proj x) ∧\n                     (* dom (namespace_map_data_proj x) ⊥ E *)\n                     ∀ i, namespace_map_data_proj x !! i = None ∨ i ∉ E\n                  | CoPsetBot => False\n                  end := eq_refl _.\n\nLemma namespace_map_included x y :\n  x ≼ y ↔\n    namespace_map_data_proj x ≼ namespace_map_data_proj y ∧\n    namespace_map_token_proj x ≼ namespace_map_token_proj y.\nProof.\n  split; [intros [[z1 z2] Hz]; split; [exists z1|exists z2]; apply Hz|].\n  intros [[z1 Hz1] [z2 Hz2]]; exists (NamespaceMap z1 z2); split; auto.\nQed.\n\nLemma namespace_map_data_proj_validN n x : ✓{n} x → ✓{n} namespace_map_data_proj x.\nProof. by destruct x as [? [?|]]=> // -[??]. Qed.\nLemma namespace_map_token_proj_validN n x : ✓{n} x → ✓{n} namespace_map_token_proj x.\nProof. by destruct x as [? [?|]]=> // -[??]. Qed.\n\nLemma namespace_map_cmra_mixin : CmraMixin (namespace_map A).\nProof.\n  apply cmra_total_mixin.\n  - eauto.\n  - by intros n x y1 y2 [Hy Hy']; split; simpl; rewrite ?Hy ?Hy'.\n  - solve_proper.\n  - intros n [m1 [E1|]] [m2 [E2|]] [Hm ?]=> // -[??]; split; simplify_eq/=.\n    + by rewrite -Hm.\n    + intros i. by rewrite -(dist_None n) -Hm dist_None.\n  - intros [m [E|]]; rewrite namespace_map_valid_eq namespace_map_validN_eq /=\n      ?cmra_valid_validN; naive_solver eauto using O.\n  - intros n [m [E|]]; rewrite namespace_map_validN_eq /=;\n      naive_solver eauto using cmra_validN_S.\n  - split; simpl; [by rewrite assoc|by rewrite assoc_L].\n  - split; simpl; [by rewrite comm|by rewrite comm_L].\n  - split; simpl; [by rewrite cmra_core_l|by rewrite left_id_L].\n  - split; simpl; [by rewrite cmra_core_idemp|done].\n  - intros ??; rewrite! namespace_map_included; intros [??].\n    by split; simpl; apply: cmra_core_mono. (* FIXME: FIXME(Coq #6294): needs new unification *)\n  - intros n [m1 [E1|]] [m2 [E2|]]=> //=; rewrite namespace_map_validN_eq /=.\n    rewrite {1}/op /cmra_op /=. case_decide; last done.\n    intros [Hm Hdisj]; split; first by eauto using cmra_validN_op_l.\n    intros i. move: (Hdisj i). rewrite lookup_op.\n    case: (m1 !! i)=> [a|]; last auto.\n    move=> [].\n    { by case: (m2 !! i). }\n    set_solver.\n  - intros n x y1 y2 ? [??]; simpl in *.\n    destruct (cmra_extend n (namespace_map_data_proj x)\n      (namespace_map_data_proj y1) (namespace_map_data_proj y2))\n      as (m1&m2&?&?&?); auto using namespace_map_data_proj_validN.\n    destruct (cmra_extend n (namespace_map_token_proj x)\n      (namespace_map_token_proj y1) (namespace_map_token_proj y2))\n      as (E1&E2&?&?&?); auto using namespace_map_token_proj_validN.\n    by exists (NamespaceMap m1 E1), (NamespaceMap m2 E2).\nQed.\nCanonical Structure namespace_mapR :=\n  Cmra (namespace_map A) namespace_map_cmra_mixin.\n\nGlobal Instance namespace_map_cmra_discrete :\n  CmraDiscrete A → CmraDiscrete namespace_mapR.\nProof.\n  split; first apply _.\n  intros [m [E|]]; rewrite namespace_map_validN_eq namespace_map_valid_eq //=.\n  by intros [?%cmra_discrete_valid ?].\nQed.\n\nLocal Instance namespace_map_empty_instance : Unit (namespace_map A) := NamespaceMap ε ε.\nLemma namespace_map_ucmra_mixin : UcmraMixin (namespace_map A).\nProof.\n  split; simpl.\n  - rewrite namespace_map_valid_eq /=. split; [apply ucmra_unit_valid|]. set_solver.\n  - split; simpl; [by rewrite left_id|by rewrite left_id_L].\n  - do 2 constructor; [apply (core_id_core _)|done].\nQed.\nCanonical Structure namespace_mapUR :=\n  Ucmra (namespace_map A) namespace_map_ucmra_mixin.\n\nGlobal Instance namespace_map_data_core_id N a :\n  CoreId a → CoreId (namespace_map_data N a).\nProof. do 2 constructor; simpl; auto. apply core_id_core, _. Qed.\n\nLemma namespace_map_data_valid N a : ✓ (namespace_map_data N a) ↔ ✓ a.\nProof. rewrite namespace_map_valid_eq /= singleton_valid. set_solver. Qed.\nLemma namespace_map_token_valid E : ✓ (namespace_map_token E).\nProof. rewrite namespace_map_valid_eq /=. split; first done. by left. Qed.\nLemma namespace_map_data_op N a b :\n  namespace_map_data N (a ⋅ b) = namespace_map_data N a ⋅ namespace_map_data N b.\nProof.\n  by rewrite {2}/op /namespace_map_op_instance /namespace_map_data /= singleton_op left_id_L.\nQed.\nLemma namespace_map_data_mono N a b :\n  a ≼ b → namespace_map_data N a ≼ namespace_map_data N b.\nProof. intros [c ->]. rewrite namespace_map_data_op. apply cmra_included_l. Qed.\nGlobal Instance namespace_map_data_is_op N a b1 b2 :\n  IsOp a b1 b2 →\n  IsOp' (namespace_map_data N a) (namespace_map_data N b1) (namespace_map_data N b2).\nProof. rewrite /IsOp' /IsOp=> ->. by rewrite namespace_map_data_op. Qed.\n\nLemma namespace_map_token_union E1 E2 :\n  E1 ## E2 →\n  namespace_map_token (E1 ∪ E2) = namespace_map_token E1 ⋅ namespace_map_token E2.\nProof.\n  intros. by rewrite /op /namespace_map_op_instance\n    /namespace_map_token /= coPset_disj_union // left_id_L.\nQed.\nLemma namespace_map_token_difference E1 E2 :\n  E1 ⊆ E2 →\n   namespace_map_token E2 = namespace_map_token E1 ⋅ namespace_map_token (E2 ∖ E1).\nProof.\n  intros. rewrite -namespace_map_token_union; last set_solver.\n  by rewrite -union_difference_L.\nQed.\nLemma namespace_map_token_valid_op E1 E2 :\n  ✓ (namespace_map_token E1 ⋅ namespace_map_token E2) ↔ E1 ## E2.\nProof.\n  rewrite namespace_map_valid_eq /= {1}/op /cmra_op /=. case_decide; last done.\n  split; [done|]; intros _. split.\n  - by rewrite left_id.\n  - intros i. rewrite lookup_op lookup_empty. auto.\nQed.\n\n(** [↑N ⊆ E] is stronger than needed, just [positives_flatten N ∈ E] would be\nsufficient. However, we do not have convenient infrastructure to prove the\nlatter, so we use the former. *)\nLemma namespace_map_alloc_update E N a :\n  ↑N ⊆ E → ✓ a → namespace_map_token E ~~> namespace_map_data N a.\nProof.\n  assert (positives_flatten N ∈ (↑N : coPset)).\n  { rewrite nclose_eq. apply elem_coPset_suffixes.\n    exists 1%positive. by rewrite left_id_L. }\n  intros ??. apply cmra_total_update=> n [mf [Ef|]] //.\n  rewrite namespace_map_validN_eq /= {1}/op /cmra_op /=. case_decide; last done.\n  rewrite left_id_L {1}left_id. intros [Hmf Hdisj]; split.\n  - destruct (Hdisj (positives_flatten N)) as [Hmfi|]; last set_solver.\n    move: Hmfi. rewrite lookup_op lookup_empty left_id_L=> Hmfi.\n    intros j. rewrite lookup_op.\n    destruct (decide (positives_flatten N = j)) as [<-|].\n    + rewrite Hmfi lookup_singleton right_id_L. by apply cmra_valid_validN.\n    + by rewrite lookup_singleton_ne // left_id_L.\n  - intros j. destruct (decide (positives_flatten N = j)); first set_solver.\n    rewrite lookup_op lookup_singleton_ne //.\n    destruct (Hdisj j) as [Hmfi|?]; last set_solver.\n    move: Hmfi. rewrite lookup_op lookup_empty; auto.\nQed.\nLemma namespace_map_updateP P (Q : namespace_map A → Prop) N a :\n  a ~~>: P →\n  (∀ a', P a' → Q (namespace_map_data N a')) → namespace_map_data N a ~~>: Q.\nProof.\n  intros Hup HP. apply cmra_total_updateP=> n [mf [Ef|]] //.\n  rewrite namespace_map_validN_eq /= left_id_L. intros [Hmf Hdisj].\n  destruct (Hup n (mf !! positives_flatten N)) as (a'&?&?).\n  { move: (Hmf (positives_flatten N)).\n    by rewrite lookup_op lookup_singleton Some_op_opM. }\n  exists (namespace_map_data N a'); split; first by eauto.\n  rewrite /= left_id_L. split.\n  - intros j. destruct (decide (positives_flatten N = j)) as [<-|].\n    + by rewrite lookup_op lookup_singleton Some_op_opM.\n    + rewrite lookup_op lookup_singleton_ne // left_id_L.\n      move: (Hmf j). rewrite lookup_op. eauto using cmra_validN_op_r.\n  - intros j. move: (Hdisj j).\n    rewrite !lookup_op !op_None !lookup_singleton_None. naive_solver.\nQed.\nLemma namespace_map_update N a b :\n  a ~~> b → namespace_map_data N a ~~> namespace_map_data N b.\nProof.\n  rewrite !cmra_update_updateP. eauto using namespace_map_updateP with subst.\nQed.\nEnd cmra.\n\nGlobal Arguments namespace_mapR : clear implicits.\nGlobal Arguments namespace_mapUR : clear implicits.\n", "meta": {"author": "gares", "repo": "iris", "sha": "7b4a04ce0d396cb27eeef22e883a9f3b738e83f4", "save_path": "github-repos/coq/gares-iris", "path": "github-repos/coq/gares-iris/iris-7b4a04ce0d396cb27eeef22e883a9f3b738e83f4/iris/algebra/namespace_map.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.2222068762005715}}
{"text": "Require Import Coq.Strings.String Coq.Lists.List.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core Fiat.Parsers.ContextFreeGrammar.Notations.\nRequire Import Fiat.Parsers.StringLike.String.\n\nRequire Import Fiat.Parsers.Grammars.JSON.\n\nLocal Arguments Equality.ascii_beq !_ !_.\nLocal Arguments Equality.string_beq !_ !_.\nLocal Arguments list_to_productions / _ _ _ _.\nLocal Arguments ascii_of_nat !_ / .\nLocal Arguments ascii_of_pos !_ / .\n\nLocal Notation LF := (ascii_of_nat 10).\nLocal Notation CR := (ascii_of_nat 13).\nLocal Notation TAB := (ascii_of_nat 9).\nLocal Notation SPACE := \" \"%char.\n\nLocal Coercion test_string_of_ascii (ch : ascii) := String.String ch EmptyString.\nGlobal Arguments test_string_of_ascii / _.\n\nLocal Notation newline := (String.String LF EmptyString).\n\nLocal Ltac unfolder :=\n  unfold Lookup;\n  repeat match goal with\n         | [ |- context[Operations.List.first_index_error ?f ?ls] ]\n           => let c := constr:(Operations.List.first_index_error f ls) in\n              let c' := (eval cbv in c) in\n              change c with c'\n         | _ => progress unfold option_rect\n         | _ => progress unfold nth\n         end.\n\nLocal Ltac safe_step :=\n  idtac;\n  (match goal with\n   | _ => reflexivity\n   | [ |- context[Valid_nonterminals ?G] ]\n     => let c := constr:(Valid_nonterminals G) in\n        let c' := (eval cbv in c) in\n        change c with c'\n   | [ |- context G[Lookup ?x ?y] ]\n     => is_var x;\n        let x' := (eval unfold x in x) in\n        let G' := context G[Lookup x' y] in\n        change G';\n        unfolder\n   | [ |- parse_of_production _ ?s (Terminal _ :: _) ]\n     => apply ParseProductionCons with (n := 1)\n   | [ |- parse_of_production _ ?s (_ :: nil) ]\n     => apply ParseProductionCons with (n := String.length s)\n   | [ |- parse_of_production _ ?s (_ :: nil) ]\n     => apply ParseProductionCons with (n := String.length s)\n   | [ |- parse_of_production _ ?s (_ :: Terminal _ :: nil) ]\n     => apply ParseProductionCons with (n := String.length s - 1)\n   | [ |- parse_of_production _ ?s (_ :: Terminal _ :: Terminal _ :: nil) ]\n     => apply ParseProductionCons with (n := String.length s - 2)\n   | [ |- parse_of_production _ _ nil ]\n     => apply ParseProductionNil\n   | [ |- parse_of_item _ (String.String ?ch EmptyString) (Terminal _) ]\n     => refine (ParseTerminal _ _ ch _ _ _); simpl; reflexivity\n   | [ |- parse_of_item _ _ (Terminal _) ]\n     => (refine (ParseTerminal _ _ _ _ _ _);\n          simpl;\n          erewrite ?Equality.ascii_lb by reflexivity;\n          reflexivity)\n   | [ |- parse_of_item _ _ (NonTerminal _) ]\n     => apply ParseNonTerminal\n   | [ |- parse_of _ _ (_::nil) ] => apply ParseHead\n   | [ |- parse_of _ ?s (nil::_) ]\n     => first [ unify s \"\"%string; apply ParseHead\n              | apply ParseTail ]\n    | [ |- parse_of _ (String.String ?ch _) (((Terminal (Equality.ascii_beq ?ch')):: _)::_) ]\n      => first [ unify ch ch'; fail 1\n               | apply ParseTail ]\n   | [ |- is_true (is_char (take 1 _) _) ] => apply get_0\n   | _ => progress simpl\n   | _ => tauto\n   end).\n\nSection json.\n  Example json_parses_singleline : parse_of_grammar (\"[ \" ++ CR ++ LF ++ TAB ++ \"\"\"xy ]z\\\"\"\"\" ]\")%string json_grammar.\n  Proof.\n    hnf; simpl.\n    apply ParseTail; repeat safe_step.\n    apply ParseHead; repeat safe_step.\n    apply ParseProductionCons with (n := 4); repeat safe_step.\n    apply ParseProductionCons with (n := 9); simpl; repeat safe_step.\n    { apply ParseHead; repeat safe_step.\n      apply ParseProductionCons with (n := 1); repeat safe_step.\n      apply ParseProductionCons with (n := 1); repeat safe_step.\n      apply ParseProductionCons with (n := 1); repeat safe_step.\n      apply ParseProductionCons with (n := 1); repeat safe_step.\n      apply ParseProductionCons with (n := 1); repeat safe_step.\n      apply ParseHead; repeat safe_step.\n      apply ParseProductionCons with (n := 1); repeat safe_step. }\n    { apply ParseProductionCons with (n := 1); simpl; repeat safe_step. }\n  Qed.\nEnd json.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/Grammars/JSONTests.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22220687620057147}}
{"text": "(** * Properties about Context Free Grammars *)\nRequire Import Coq.Numbers.Natural.Peano.NPeano.\nRequire Import Fiat.Common Fiat.Common.UIP.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Equality.\n\nSet Implicit Arguments.\n\nLocal Open Scope list_scope.\n\nGlobal Instance item_rect_Proper {Char T}\n: Proper (pointwise_relation _ eq ==> pointwise_relation _ eq ==> eq ==> eq)\n         (@item_rect Char (fun _ => T)).\nProof.\n  lazy.\n  intros ?? H ?? H' ? [?|?] ?; subst; eauto with nocore.\nQed.\nGlobal Instance item_rect_Proper_forall {Char T}\n: Proper (forall_relation (fun _ => eq) ==> forall_relation (fun _ => eq) ==> forall_relation (fun _ => eq))\n         (@item_rect Char T).\nProof.\n  lazy.\n  intros ?? H ?? H' [?|?]; subst; eauto with nocore.\nQed.\n\nGlobal Instance item_rect_Proper_forall_R {C A} {R : relation A}\n  : Proper\n      ((pointwise_relation _ R)\n         ==> (pointwise_relation _ R)\n         ==> forall_relation (fun _ : item C => R))\n      (item_rect (fun _ : item C => A)).\nProof.\n  lazy; intros ?????? [?|?]; trivial.\nQed.\n\nHint Extern 1 (Proper _ (@item_rect _ _)) => exact item_rect_Proper : typeclass_instances.\nHint Extern 0 (Proper _ (@item_rect _ _)) => exact item_rect_Proper_forall : typeclass_instances.\nHint Extern 0 (Proper (pointwise_relation _ _ ==> pointwise_relation _ _ ==> forall_relation _) (item_rect _))\n=> refine item_rect_Proper_forall_R : typeclass_instances.\n\nSection cfg.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char} (G : grammar Char).\n\n  Definition parse_of_item_respectful'\n             (parse_of_respectful : forall {str1 str2} (H : str1 =s str2) {pats pats'} (Hpats : productions_code pats pats') (p : parse_of G str1 pats), parse_of G str2 pats')\n             {str1 str2} (H : str1 =s str2) {it it'} (Hit : item_code it it') (p : parse_of_item G str1 it)\n  : parse_of_item G str2 it'\n    := match p in (parse_of_item _ _ it), it' return item_code it it' -> parse_of_item G str2 it' with\n         | ParseTerminal ch P pf0 pf1, Terminal P' => fun Hit => ParseTerminal G str2 ch P' (transitivity (symmetry (Hit _)) pf0) (transitivity (eq_sym (is_char_Proper H eq_refl)) pf1)\n         | ParseTerminal _ _ _ _, NonTerminal _ => fun Hit => match Hit with end\n         | ParseNonTerminal nt H' p', NonTerminal nt'\n           => fun Hit\n              => ParseNonTerminal\n                   _\n                   (match Hit in (_ = nt') return List.In nt' _ with\n                      | eq_refl => H'\n                    end)\n                   (@parse_of_respectful\n                      _ _ H (Lookup G nt) (Lookup G nt')\n                      (match Hit in (_ = nt') return productions_code (G nt) (G nt') with\n                         | eq_refl => reflexivity _\n                       end)\n                      p')\n         | ParseNonTerminal _ _ _, Terminal _ => fun Hit => match Hit with end\n       end Hit.\n\n  Global Arguments parse_of_item_respectful' _ _ _ _ _ !_ _ !_ / .\n\n  Section bodies.\n    Context (parse_of_respectful : forall {str1 str2} (H : str1 =s str2) {pats pats'} (Hpats : productions_code pats pats') (p : parse_of G str1 pats), parse_of G str2 pats')\n            (parse_of_production_respectful : forall {str1 str2} (H : str1 =s str2) {pat pat'} (Hpat : production_code pat pat') (p : parse_of_production G str1 pat), parse_of_production G str2 pat').\n\n    Definition parse_of_respectful_step {str1 str2} (H : str1 =s str2) {pats pats'} (Hpats : productions_code pats pats') (p : parse_of G str1 pats) : parse_of G str2 pats'.\n    Proof.\n      refine (match p in (parse_of _ _ pats), pats' return productions_code pats pats' -> parse_of G str2 pats' with\n                | ParseHead pat pats p', pat'::pats' => fun Hpats' => ParseHead pats' (@parse_of_production_respectful _ _ H _ _ _ p')\n                | ParseTail pat pats p', pat'::pats' => fun Hpats' => ParseTail pat' (@parse_of_respectful _ _ H _ _ _ p')\n                | ParseHead _ _ _, nil => fun Hpats' => match _ : False with end\n                | ParseTail _ _ _, nil => fun Hpats' => match _ : False with end\n              end Hpats);\n      try solve [ clear -Hpats'; abstract inversion Hpats'\n                | clear -Hpats'; inversion Hpats'; subst; assumption ].\n    Defined.\n\n    Definition parse_of_production_respectful_step {str1 str2} (H : str1 =s str2) {pat pat'} (Hpat : production_code pat pat') (p : parse_of_production G str1 pat) : parse_of_production G str2 pat'.\n    Proof.\n      refine (match p in (parse_of_production _ _ pat), pat' return production_code pat pat' -> parse_of_production G str2 pat' with\n                | ParseProductionNil pf, nil => fun Hpat' => ParseProductionNil G str2 (transitivity (eq_sym (length_Proper H)) pf)\n                | ParseProductionCons n pat pats p0 p1, pat'::pats' => fun Hpat' => ParseProductionCons _ n (parse_of_item_respectful' (@parse_of_respectful) (take_Proper eq_refl H) _ p0) (@parse_of_production_respectful _ _ (drop_Proper eq_refl H) _ _ _ p1)\n                | ParseProductionNil _, _::_ => fun Hpat' => match _ : False with end\n                | ParseProductionCons _ _ _ _ _, nil => fun Hpat' => match _ : False with end\n              end Hpat);\n      try solve [ clear -Hpat'; abstract inversion Hpat'\n                | clear -Hpat'; inversion Hpat'; subst; assumption ].\n    Defined.\n\n    Global Arguments parse_of_respectful_step _ _ _ _ _ _ !_ / .\n    Global Arguments parse_of_production_respectful_step _ _ _ _ _ _ !_ / .\n  End bodies.\n\n  Fixpoint parse_of_respectful {str1 str2} (H : str1 =s str2) {pats pats'} (Hpats : productions_code pats pats') (p : parse_of G str1 pats) : parse_of G str2 pats'\n    := @parse_of_respectful_step (@parse_of_respectful) (@parse_of_production_respectful) _ _ H _ _ Hpats p\n  with parse_of_production_respectful {str1 str2} (H : str1 =s str2) {pat pat'} (Hpat : production_code pat pat') (p : parse_of_production G str1 pat) : parse_of_production G str2 pat'\n    := @parse_of_production_respectful_step (@parse_of_respectful) (@parse_of_production_respectful) _ _ H _ _ Hpat p.\n\n  Definition parse_of_item_respectful : forall {str1 str2} H {it it'} Hit p, _\n    := @parse_of_item_respectful' (@parse_of_respectful).\n\n  Global Arguments parse_of_item_respectful _ _ _ _ !_ _ !_ / .\n\n  Fixpoint parse_of_respectful_refl {str pf pats Hpats} (p : parse_of G str pats) : parse_of_respectful pf Hpats p = p\n    := match p return forall Hpats, parse_of_respectful pf Hpats p = p with\n         | ParseHead pat pats p' => fun Hpats => f_equal (ParseHead _) (parse_of_production_respectful_refl p')\n         | ParseTail pat pats p' => fun Hpats => f_equal (@ParseTail _ _ _ _ _ _ _) (parse_of_respectful_refl p')\n       end Hpats\n  with parse_of_production_respectful_refl {str pf pat Hpat} (p : parse_of_production G str pat) : parse_of_production_respectful pf Hpat p = p\n       := match p return forall Hpat, parse_of_production_respectful pf Hpat p = p with\n            | ParseProductionNil pf => fun Hpat => f_equal (ParseProductionNil _ _) (dec_eq_uip (Nat.eq_dec _) _ _)\n            | ParseProductionCons n pat pats p0 p1\n              => fun Hpat => f_equal2 (@ParseProductionCons _ _ _ _ _ _ _ _)\n                                      (parse_of_item_respectful_refl p0)\n                                      (parse_of_production_respectful_refl p1)\n          end Hpat\n  with parse_of_item_respectful_refl {str pf it Hit} (p : parse_of_item G str it) : parse_of_item_respectful pf Hit p = p\n       := match p return forall Hit, parse_of_item_respectful pf Hit p = p with\n            | ParseTerminal ch P pf1 pf2 => fun Hit => f_equal2 (ParseTerminal _ _ _ _) (dec_eq_uip (Bool.bool_dec _) _ _) (dec_eq_uip (Bool.bool_dec _) _ _)\n            | ParseNonTerminal nt H' p'\n              => fun Hit'\n                 => f_equal2 (ParseNonTerminal nt)\n                             match dec_eq_uip (@Equality.string_eq_dec nt) eq_refl Hit' in (_ = Hit') return match Hit' in (_ = nt') return List.In nt' _ with eq_refl => H' end = H' with\n                               | eq_refl => eq_refl\n                             end\n                             (@parse_of_respectful_refl _ _ _ _ p')\n          end Hit.\n\n  (*Global Instance parse_of_Proper : Proper (beq ==> eq ==> iff) (parse_of G).\n  Proof.\n    split; subst; apply parse_of_respectful; [ assumption | symmetry; assumption ].\n  Qed.\n\n  Global Instance parse_of_production_Proper : Proper (beq ==> eq ==> iff) (parse_of_production G).\n  Proof.\n    split; subst; apply parse_of_production_respectful; [ assumption | symmetry; assumption ].\n  Qed.\n\n  Global Instance parse_of_item_Proper : Proper (beq ==> eq ==> iff) (parse_of_item G).\n  Proof.\n    split; subst; apply parse_of_item_respectful; [ assumption | symmetry; assumption ].\n  Qed.*)\n\n  Definition ParseProductionSingleton str it (p : parse_of_item G str it) : parse_of_production G str [ it ].\n  Proof.\n    econstructor.\n    { eapply parse_of_item_respectful; [ | reflexivity | eassumption ].\n      rewrite take_long; reflexivity. }\n    { constructor.\n      rewrite drop_length; auto with arith. }\n  Defined.\n\n  Section definitions.\n    Context (P : String -> String.string -> Type).\n\n    Definition Forall_parse_of_item'\n               (Forall_parse_of : forall {str pats} (p : parse_of G str pats), Type)\n               {str it} (p : parse_of_item G str it)\n      := match p return Type with\n           | ParseTerminal ch P pf1 pf2 => unit\n           | ParseNonTerminal nt H' p'\n             => (P str nt * Forall_parse_of p')%type\n         end.\n\n    Fixpoint Forall_parse_of {str pats} (p : parse_of G str pats)\n      := match p with\n           | ParseHead pat pats p'\n             => Forall_parse_of_production p'\n           | ParseTail _ _ p'\n             => Forall_parse_of p'\n         end\n    with Forall_parse_of_production {str pat} (p : parse_of_production G str pat)\n         := match p return Type with\n              | ParseProductionNil pf => unit\n              | ParseProductionCons pat strs pats p' p''\n                => (Forall_parse_of_item' (@Forall_parse_of) p' * Forall_parse_of_production p'')%type\n            end.\n\n    Definition Forall_parse_of_item {str it} (p : parse_of_item G str it)\n      := @Forall_parse_of_item' (@Forall_parse_of) str it p.\n  End definitions.\n\n  (*Section expand.\n    Context {P P' : String -> String.string -> Type}.\n\n    Definition expand_forall_parse_of_item'\n               {str str' str''}\n               {Forall_parse_of : forall P {str pats} (p : parse_of G str pats), Type}\n               (expand : forall {pats pats' pats''} (Hpats : productions_code pats pats') (Hpats' : productions_code pats' pats'') (H : str =s str') (H' : str =s str'') {p}, @Forall_parse_of P str' pats' (parse_of_respectful H Hpats p) -> @Forall_parse_of P' str'' pats'' (parse_of_respectful H' Hpats' p))\n               (f : forall n, P str' n -> P' str'' n)\n               {it p} (H : str =s str') (H' : str =s str'')\n    : @Forall_parse_of_item' P (@Forall_parse_of P) str' it (parse_of_item_respectful H p)\n      -> @Forall_parse_of_item' P' (@Forall_parse_of P') str'' it (parse_of_item_respectful H' p).\n    Proof.\n      destruct p; simpl.\n      { exact (fun x => x). }\n      { intro ab.\n        exact (f _ (fst ab), expand _ H H' _ (snd ab)). }\n    Defined.\n\n    Global Arguments expand_forall_parse_of_item' : simpl never.\n\n    Fixpoint expand_forall_parse_of\n             str str' str''\n             (f : forall str0' str1', str0' ≤s str -> str0' =s str1' -> forall n, P str0' n -> P' str1' n)\n             pats (H : str =s str') (H' : str =s str'') (p : parse_of G str pats)\n             {struct p}\n    : Forall_parse_of P (parse_of_respectful H p) -> Forall_parse_of P' (parse_of_respectful H' p)\n    with expand_forall_parse_of_production\n           str str' str''\n           (f : forall str0' str1', str0' ≤s str -> str0' =s str1' -> forall n, P str0' n -> P' str1' n)\n           pat (H : str =s str') (H' : str =s str'') (p : parse_of_production G str pat)\n           {struct p}\n         : Forall_parse_of_production P (parse_of_production_respectful H p) -> Forall_parse_of_production P' (parse_of_production_respectful H' p).\n    Proof.\n      { destruct p.\n        simpl.\n        { apply expand_forall_parse_of_production; exact f. }\n        { refine (expand_forall_parse_of _ _ _ _ _ _ _ p); exact f. } }\n      { destruct p as [ | n pat pats pit pits ]; simpl.\n        { exact (fun x => x). }\n        { pose proof (fun f' f'' => @expand_forall_parse_of_item' _ (take n str') (take n str'') (@Forall_parse_of) (@expand_forall_parse_of _ _ _ f') f'' _ pit) as expand_forall_parse_of_item.\n          specialize (fun f' H H' => expand_forall_parse_of_production _ (drop n str') (drop n str'') f' _ H H' pits).\n          clear expand_forall_parse_of.\n          change (Forall_parse_of_item P (parse_of_item_respectful (take_Proper eq_refl H) pit) * Forall_parse_of_production P (parse_of_production_respectful (drop_Proper eq_refl H) pits)\n                  -> Forall_parse_of_item P' (parse_of_item_respectful (take_Proper eq_refl H') pit) * Forall_parse_of_production P' (parse_of_production_respectful (drop_Proper eq_refl H') pits))%type.\n          intro xy.\n          split.\n          { eapply expand_forall_parse_of_item; [ .. | exact (fst xy) ].\n            { intros ? ? H''; apply f.\n              rewrite str_le_take in H''; assumption. }\n            { intro; apply f.\n              { clear -H HSLP.\n                rewrite str_le_take, H; reflexivity. }\n              { rewrite <- H, <- H'; reflexivity. } } }\n          { eapply expand_forall_parse_of_production; [ .. | exact (snd xy) ].\n            intros ? ? H''; apply f.\n            etransitivity; [ eassumption | apply str_le_drop ]. } } }\n    Defined.\n\n    Global Arguments expand_forall_parse_of : simpl never.\n    Global Arguments expand_forall_parse_of_production : simpl never.\n\n    Definition expand_forall_parse_of_item {str str' str''} f {it} {p : parse_of_item G str it} (H : str =s str') (H' : str =s str'')\n      := @expand_forall_parse_of_item' str str' str'' _ (@expand_forall_parse_of str str' str'' f) (f _ _ ((_ : Proper (beq ==> beq ==> impl) str_le) _ _ H _ _ (reflexivity _) (reflexivity _)) (transitivity (symmetry H) H')) it p.\n\n    Global Arguments expand_forall_parse_of_item : simpl never.\n  End expand.*)\nEnd cfg.\n\nLtac simpl_parse_of_respectful :=\n  repeat match goal with\n           | [ |- context[@parse_of_respectful ?Char ?HSLM ?HSL ?HSLP ?G ?str1 ?str2 ?H ?pat ?pat' ?Hpat ?p] ]\n             => change (@parse_of_respectful Char HSLM HSL HSLP G str1 str2 H pat pat' Hpat p)\n                with (@parse_of_respectful_step Char HSLM HSL G (@parse_of_respectful Char HSLM HSL HSLP G) (@parse_of_production_respectful Char HSLM HSL HSLP G) str1 str2 H pat pat' Hpat p);\n               simpl @parse_of_respectful_step\n           | [ |- context[@parse_of_production_respectful ?Char ?HSLM ?HSL ?HSLP ?G ?str1 ?str2 ?H ?pat ?pat' ?Hpat ?p] ]\n             => change (@parse_of_production_respectful Char HSLM HSL HSLP G str1 str2 H pat pat' Hpat p)\n                with (@parse_of_production_respectful_step Char HSLM HSL G (@parse_of_respectful Char HSLM HSL HSLP G) (@parse_of_production_respectful Char HSLM HSL HSLP G) str1 str2 H pat pat' Hpat p);\n               simpl @parse_of_production_respectful_step\n           | _ => progress simpl @parse_of_item_respectful\n           | _ => progress simpl @parse_of_item_respectful'\n         end.\n\nSection parse_of_proper.\n  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char} {G : grammar Char} {str : String}.\n\n  Local Ltac t_parse_of_impl lem :=\n    repeat intro;\n    match goal with\n      | [ H : Proper _ _, H' : _ -> _ |- _ ] => eapply H; [ eassumption.. | apply H'; try clear H H' ]\n    end;\n    eapply lem; [ .. | eassumption ];\n    try first [ assumption\n              | reflexivity\n              | symmetry; assumption ].\n\n  Section fun0.\n    Context {P : _ -> _ -> Prop}\n            {H : Proper (@item_code Char ==> @production_code Char ==> impl) P}.\n\n    Global Instance parse_of_item_fun0_Proper\n    : Proper (item_code ==> production_code ==> impl) (fun it (its : production Char) => parse_of_item G str it -> P it its).\n    Proof. t_parse_of_impl (@parse_of_item_respectful). Qed.\n    Global Instance parse_of_production_fun0_Proper\n    : Proper (item_code ==> production_code ==> impl) (fun (it : item Char) (its : production Char) => parse_of_production G str its -> P it its).\n    Proof. t_parse_of_impl (@parse_of_production_respectful). Qed.\n  End fun0.\n  Section fun0_flip.\n    Context {P : _ -> _ -> Prop}\n            {H : Proper (@item_code Char ==> @production_code Char ==> flip impl) P}.\n\n    Global Instance parse_of_item_fun0_Proper_flip\n    : Proper (item_code ==> production_code ==> flip impl) (fun it (its : production Char) => parse_of_item G str it -> P it its).\n    Proof. t_parse_of_impl (@parse_of_item_respectful). Qed.\n    Global Instance parse_of_production_fun0_Proper_flip\n    : Proper (item_code ==> production_code ==> flip impl) (fun (it : item Char) (its : production Char) => parse_of_production G str its -> P it its).\n    Proof. t_parse_of_impl (@parse_of_production_respectful). Qed.\n  End fun0_flip.\n\n  Section fun1.\n    Context {A} {RA : relation A}\n            {P : _ -> _ -> _ -> Prop}\n            {H : Proper (@item_code Char ==> @production_code Char ==> RA ==> impl) P}.\n\n    Global Instance parse_of_item_fun1_Proper\n    : Proper (item_code ==> production_code ==> RA ==> impl) (fun it (its : production Char) x => parse_of_item G str it -> P it its x).\n    Proof. t_parse_of_impl (@parse_of_item_respectful). Qed.\n    Global Instance parse_of_production_fun1_Proper\n    : Proper (item_code ==> production_code ==> RA ==> impl) (fun (it : item Char) (its : production Char) x => parse_of_production G str its -> P it its x).\n    Proof. t_parse_of_impl (@parse_of_production_respectful). Qed.\n  End fun1.\n  Section fun1_flip.\n    Context {A} {RA : relation A}\n            {P : _ -> _ -> _ -> Prop}\n            {H : Proper (@item_code Char ==> @production_code Char ==> RA ==> flip impl) P}.\n\n    Global Instance parse_of_item_fun1_Proper_flip\n    : Proper (item_code ==> production_code ==> RA ==> flip impl) (fun it (its : production Char) x => parse_of_item G str it -> P it its x).\n    Proof. t_parse_of_impl (@parse_of_item_respectful). Qed.\n    Global Instance parse_of_production_fun1_Proper_flip\n    : Proper (item_code ==> production_code ==> RA ==> flip impl) (fun (it : item Char) (its : production Char) x => parse_of_production G str its -> P it its x).\n    Proof. t_parse_of_impl (@parse_of_production_respectful). Qed.\n  End fun1_flip.\nEnd parse_of_proper.\n", "meta": {"author": "proofskiddie", "repo": "CoqStuff", "sha": "fc8ecdf8045bc835bb10b2e4791f041d82451b5d", "save_path": "github-repos/coq/proofskiddie-CoqStuff", "path": "github-repos/coq/proofskiddie-CoqStuff/CoqStuff-fc8ecdf8045bc835bb10b2e4791f041d82451b5d/idontevnkno/src/Parsers/ContextFreeGrammar/Properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.22220496259739314}}
{"text": "From aneris.examples.transaction_commit Require Export\n    two_phase_runner_code.\nFrom aneris.examples.transaction_commit Require Import\n    two_phase_runner_code two_phase_prelude two_phase_tm two_phase_rm.\n(** * A simple runner (without aux. clients), proving safety  *)\nSection runner.\n\n  Open Scope nat_scope.\n  Definition tm_addr := SocketAddressInet \"tm\" 80.\n  Definition rm1_addr := SocketAddressInet \"rm.01\" 80.\n  Definition rm2_addr := SocketAddressInet \"rm.02\" 80.\n  Definition rm3_addr := SocketAddressInet \"rm.03\" 80.\n  Definition rms : gset socket_address :=\n    {[ rm1_addr; rm2_addr; rm3_addr ]}.\n  Definition addrs : gset socket_address := {[ tm_addr ]} ∪ rms.\n  Definition ips : gset string := {[ \"tm\"; \"rm.01\"; \"rm.02\"; \"rm.03\" ]}.\n\n  Program Instance my_topo : network_topo :=\n    {| RMs := rms; tm := tm_addr |}.\n  Solve All Obligations with set_solver.\n\n  Context `{!anerisG (TC_model rms) Σ, !tcG Σ}.\n\n  Notation pending_frac := (dfrac_oneshot.pending tc_oneshot_gname).\n\n  Lemma RMs_size :\n    size RMs = 3.\n  Proof. rewrite /RMs !size_union ?size_singleton //; set_solver. Qed.\n\n  Lemma runner_spec :\n    {{{ inv tcN tc_inv ∗\n        tm_addr ⤇ tm_si ∗\n        tm_addr ⤳ (∅, ∅) ∗\n        ([∗ set] rm ∈ rms, rm ⤇ rm_si) ∗\n        ([∗ set] rm ∈ rms, rm ↦●{1/2} WORKING) ∗\n        ([∗ set] ip ∈ ips, free_ip ip) ∗\n        pending_frac 1 }}}\n      runner @[\"system\"]\n    {{{ v, RET v; True }}}.\n  Proof.\n    iIntros (Φ) \"(#Hinv & #Htm_si & Htm_a & #Hrms_si & Hwork & Hips & Hpend) HΦ\".\n    rewrite /runner.\n    do 4 (wp_makeaddress; wp_let).\n    wp_apply (wp_set_empty socket_address); [done|]; iIntros (?) \"%H\".\n    do 3 (wp_apply (wp_set_add (A := socket_address) with \"[//]\");\n          iIntros (?) \"%\").\n    wp_pures.\n    rewrite (pending_split_N _ (size RMs + 1)); [|lia].\n    iDestruct (big_sepS_delete _ _ \"rm.01\" with \"Hips\") as \"(Hrm1 & Hips)\"; [set_solver|].\n    iDestruct (big_sepS_delete _ _ \"rm.02\" with \"Hips\") as \"(Hrm2 & Hips)\"; [set_solver|].\n    iDestruct (big_sepS_delete _ _ \"rm.03\" with \"Hips\") as \"(Hrm3 & Hips)\"; [set_solver|].\n    iDestruct (big_sepS_delete _ _ \"tm\" with \"Hips\") as \"(Htm & _)\"; [set_solver|].\n    iDestruct (big_sepS_delete _ _ rm1_addr with \"Hwork\") as \"(Hw1 & Hwork)\"; [set_solver|].\n    iDestruct (big_sepS_delete _ _ rm2_addr with \"Hwork\") as \"(Hw2 & Hwork)\"; [set_solver|].\n    iDestruct (big_sepS_delete _ _ rm3_addr with \"Hwork\") as \"(Hw3 & _)\"; [set_solver|].\n    rewrite RMs_size.\n    iDestruct (big_sepS_delete _ _ 0 with \"Hpend\") as \"(Hp1 & Hpend)\"; [set_solver|].\n    iDestruct (big_sepS_delete _ _ 1 with \"Hpend\") as \"(Hp2 & Hpend)\"; [set_solver|].\n    iDestruct (big_sepS_delete _ _ 2 with \"Hpend\") as \"(Hp3 & Hpend)\"; [set_solver|].\n    iDestruct (big_sepS_delete _ _ 3 with \"Hpend\") as \"(Ht & _)\"; [set_solver|].\n    rewrite -RMs_size.\n    wp_apply (aneris_wp_start {[port_of_address rm1_addr]}); iFrame.\n    iSplitR \"Hw1 Hp1\"; last first.\n    { iIntros \"!> Hport\".\n      wp_apply (resource_manager_spec rm1_addr with \"[$] [$] [] [$] [$]\");\n        [set_solver| |done].\n      iApply (big_sepS_elem_of with \"Hrms_si\"); set_solver. }\n    iModIntro; wp_seq.\n    wp_apply (aneris_wp_start {[port_of_address rm2_addr]}); iFrame.\n    iSplitR \"Hw2 Hp2\"; last first.\n    { iIntros \"!> Hport\".\n      wp_apply (resource_manager_spec rm2_addr with \"[$] [$] [] [$] [$] \");\n        [set_solver| |done].\n      iApply (big_sepS_elem_of with \"Hrms_si\"); set_solver. }\n    iModIntro; wp_seq.\n    wp_apply (aneris_wp_start {[port_of_address rm3_addr]}); iFrame.\n    iSplitR \"Hw3 Hp3\"; last first.\n    { iIntros \"!> Hport\".\n      wp_apply (resource_manager_spec rm3_addr with \"[$] [$] [] [$] [$] \");\n        [set_solver| |done].\n      iApply (big_sepS_elem_of with \"Hrms_si\"); set_solver. }\n    iModIntro; wp_seq.\n    wp_apply (aneris_wp_start {[port_of_address tm_addr]}); iFrame.\n    iSplitL \"HΦ\"; [by iApply \"HΦ\"|].\n    iIntros \"!> Hport\".\n    wp_apply aneris_wp_wand_r; iSplitL.\n    { wp_apply (transaction_manager_spec\n                  with \"[$] [$] [$] [$] [$]\").\n      by rewrite !union_assoc_L union_empty_r_L in H2. }\n    by iIntros (?) \"?\".\n  Qed.\n\nEnd runner.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/transaction_commit/two_phase_runner_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2220755216739912}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import ITreeLang.\n\nRequire Import PromiseConsistent.\nRequire Import CompressSteps.\n\nRequire Import iPromotionDef.\nRequire Import SimCommon.\nRequire Import PromotionProgress.\n\nSet Implicit Arguments.\n\n\nModule SimThreadPromotion.\n  Import SimCommon.\n  Section TYPE.\n  Variable R: Type.\n\n  (* sim_state *)\n\n  Inductive sim_state (l: Loc.t) (val: Const.t)\n            (st_src: itree MemE.t R) (st_tgt: itree MemE.t (Const.t * R)): Prop :=\n  | sim_state_intro\n      (STMTS: st_tgt = promote_itree l val st_src)\n  .\n  Hint Constructors sim_state: core.\n\n\n  (* sim_thread *)\n\n  Definition safe (l: Loc.t) (lc: Local.t) (mem: Memory.t): Prop :=\n    forall from to val released\n      (GET: Memory.get l to mem = Some (from, Message.concrete val (Some released))),\n      View.le released (TView.cur (Local.tview lc)).\n\n  Inductive sim_thread (l: Loc.t) (e_src: Thread.t (lang R)) (e_tgt: Thread.t (lang (Const.t * R))): Prop :=\n  | sim_thread_intro\n      val\n      (STATE: sim_state l val (Thread.state e_src) (Thread.state e_tgt))\n      (LOCAL: sim_local l (Thread.local e_src) (Thread.local e_tgt))\n      (SC: sim_timemap l (Thread.sc e_src) (Thread.sc e_tgt))\n      (MEMORY: sim_memory l (Thread.memory e_src) (Thread.memory e_tgt))\n      (FULFILLABLE: fulfillable l (Local.tview (Thread.local e_src)) (Thread.memory e_src)\n                                  (Local.promises (Thread.local e_src)))\n      (LATEST: exists from released,\n          Memory.get l (Memory.max_ts l (Thread.memory e_src)) (Thread.memory e_src) =\n          Some (from, Message.concrete val released))\n      (PROMISES: forall to, Memory.get l to (Local.promises (Thread.local e_src)) = None)\n      (SAFE: safe l (Thread.local e_src) (Thread.memory e_src))\n  .\n  Hint Constructors sim_thread: core.\n\n  Inductive sim_thread_reserve (l: Loc.t) (e_src: Thread.t (lang R)) (e_tgt: Thread.t (lang (Const.t * R))): Prop :=\n  | sim_thread_reserve_intro\n      val\n      (STATE: sim_state l val (Thread.state e_src) (Thread.state e_tgt))\n      (LOCAL: sim_local l (Thread.local e_src) (Thread.local e_tgt))\n      (SC: sim_timemap l (Thread.sc e_src) (Thread.sc e_tgt))\n      (MEMORY: sim_memory l (Thread.memory e_src) (Thread.memory e_tgt))\n      (FULFILLABLE: fulfillable l (Local.tview (Thread.local e_src)) (Thread.memory e_src)\n                                  (Local.promises (Thread.local e_src)))\n      (LATEST: exists from from' released,\n          <<MEM: Memory.get l (Memory.max_ts l (Thread.memory e_src)) (Thread.memory e_src) =\n                 Some (from, Message.reserve)>> /\\\n          <<PROMISE: Memory.get l (Memory.max_ts l (Thread.memory e_src)) (Local.promises (Thread.local e_src)) =\n                     Some (from, Message.reserve)>> /\\\n          <<LATEST: Memory.get l from (Thread.memory e_src) =\n                    Some (from', Message.concrete val released)>>)\n      (PROMISES: forall to (TO: to <> Memory.max_ts l (Thread.memory e_src)),\n          Memory.get l to (Local.promises (Thread.local e_src)) = None)\n      (SAFE: safe l (Thread.local e_src) (Thread.memory e_src))\n  .\n  Hint Constructors sim_thread_reserve: core.\n\n  Definition sim_thread_all (l: Loc.t): forall (e_src: Thread.t (lang R)) (e_tgt: Thread.t (lang (Const.t * R))), Prop :=\n    (sim_thread l) \\2/ (sim_thread_reserve l).\n  Hint Unfold sim_thread_all: core.\n\n\n  Lemma step_sim_thread_reserve\n        l e1_src e_tgt\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (SIM1: sim_thread l e1_src e_tgt):\n    exists from to e2_src,\n      <<STEP: Thread.step false (ThreadEvent.promise l from to Message.reserve Memory.op_kind_add)\n                          e1_src e2_src>> /\\\n      <<SIM2: sim_thread_reserve l e2_src e_tgt>>.\n  Proof.\n    destruct e1_src as [st1_src [tview1_src promises1_src] sc1_src mem1_src].\n    destruct e_tgt as [st_tgt [tview_tgt promises_tgt] sc_tgt mem_tgt].\n    inv SIM1. ss. des.\n    dup WF1_SRC. inv WF1_SRC0. ss.\n    clear TVIEW_WF TVIEW_CLOSED FINITE BOT.\n    exploit (@Memory.add_exists_max_ts mem1_src l (Time.incr (Memory.max_ts l mem1_src)) Message.reserve).\n    { apply Time.incr_spec. }\n    { econs. }\n    i. des.\n    exploit Memory.add_exists_le; eauto. i. des.\n    assert (MAX: Memory.max_ts l mem2 = Time.incr (Memory.max_ts l mem1_src)).\n    { exploit Memory.add_get0; try exact x0. i. des.\n      exploit Memory.max_ts_spec; try exact GET0. i. des.\n      inv MAX; ss.\n      revert GET1. erewrite Memory.add_o; eauto. condtac; ss; try by des; ss.\n      guardH o. i.\n      exploit Memory.max_ts_spec; try exact GET1. i. des.\n      specialize (Time.incr_spec (Memory.max_ts l mem1_src)). i.\n      rewrite H in H0. timetac.\n    }\n    esplits.\n    - econs 1. econs; ss. econs; eauto.\n    - econs; s; eauto.\n      + inv LOCAL. econs; ss.\n        etrans; eauto. econs; i.\n        * revert GET_SRC. erewrite Memory.add_o; eauto. condtac; ss.\n          { des. subst. ss. }\n          { esplits; eauto. refl. }\n        * erewrite Memory.add_o; eauto. condtac; ss.\n          { des. subst. ss. }\n          { esplits; eauto. refl. }\n      + etrans; eauto. econs; i.\n        * revert GET_SRC. erewrite Memory.add_o; eauto. condtac; ss.\n          { des. subst. ss. }\n          { esplits; eauto. refl. }\n        * erewrite Memory.add_o; eauto. condtac; ss.\n          { des. subst. ss. }\n          { esplits; eauto. refl. }\n      + ii. revert GETP.\n        erewrite Memory.add_o; eauto. condtac; ss. i. guardH o.\n        exploit FULFILLABLE; eauto. i. des. split; ss.\n        unfold prev_released_le_loc in *.\n        erewrite Memory.add_o; eauto. condtac; ss.\n      + exploit Memory.add_get0; try exact x0. i. des.\n        exploit Memory.add_get0; try exact x1. i. des.\n        exploit Memory.add_get1; try exact LATEST; eauto. i.\n        rewrite MAX. esplits; eauto.\n      + i. rewrite MAX in *.\n        erewrite Memory.add_o; eauto. condtac; ss.\n        des. subst. ss.\n      + ii. revert GET.\n        erewrite Memory.add_o; eauto. condtac; ss; eauto.\n  Qed.\n\n  Lemma step_reserve_sim_thread\n        l e1_src e_tgt\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (SIM1: sim_thread_reserve l e1_src e_tgt):\n    exists from to e2_src,\n      <<STEP: Thread.step true (ThreadEvent.promise l from to Message.reserve Memory.op_kind_cancel)\n                          e1_src e2_src>> /\\\n      <<SIM2: sim_thread l e2_src e_tgt>>.\n  Proof.\n    destruct e1_src as [st1_src [tview1_src promises1_src] sc1_src mem1_src].\n    destruct e_tgt as [st_tgt [tview_tgt promises_tgt] sc_tgt mem_tgt].\n    inv SIM1. ss. des.\n    dup WF1_SRC. inv WF1_SRC0. ss.\n    clear TVIEW_WF TVIEW_CLOSED FINITE BOT.\n    exploit (@Memory.remove_exists promises1_src l from (Memory.max_ts l mem1_src) Message.reserve); ss.\n    i. des.\n    exploit Memory.remove_exists_le; eauto. i. des.\n    assert (MAX: Memory.max_ts l mem0 = from).\n    { exploit Memory.get_ts; try exact MEM. i. des.\n      { rewrite x3 in *.\n        inv CLOSED1_SRC. rewrite INHABITED in *. ss. }\n      exploit Memory.remove_get0; try exact x1. i. des.\n      exploit Memory.remove_get1; try exact LATEST; eauto. i. des.\n      { subst. timetac. }\n      exploit Memory.max_ts_spec; try exact GET2. i. des.\n      inv MAX; ss.\n      revert GET1. erewrite Memory.remove_o; eauto. condtac; ss.\n      i. des; ss.\n      exploit Memory.max_ts_spec; try exact GET1. i. des.\n      exploit Memory.get_ts; try exact GET1. i. des.\n      { subst. rewrite x4 in *. inv H. }\n      exploit Memory.get_disjoint; [exact MEM|exact GET1|..]. i. des.\n      { subst. rewrite x4 in *. congr. }\n      exfalso.\n      apply (x4 (Memory.max_ts l mem0)); econs; ss. refl.\n    }\n    esplits.\n    - econs. econs; ss. econs; eauto.\n    - econs; s; eauto.\n      + inv LOCAL. econs; ss.\n        etrans; eauto. econs; i.\n        * revert GET_SRC. erewrite Memory.remove_o; eauto. condtac; ss. i.\n          esplits; eauto. refl.\n        * erewrite Memory.remove_o; eauto. condtac; ss; try by des; ss.\n          esplits; eauto. refl.\n      + etrans; eauto. econs; i.\n        * revert GET_SRC. erewrite Memory.remove_o; eauto. condtac; ss. i.\n          esplits; eauto. refl.\n        * erewrite Memory.remove_o; eauto. condtac; ss; try by des; ss.\n          esplits; eauto. refl.\n      + ii. revert GETP.\n        erewrite Memory.remove_o; eauto. condtac; ss. i. guardH o.\n        exploit FULFILLABLE; eauto. i. des. split; ss.\n        unfold prev_released_le_loc in *.\n        erewrite Memory.remove_o; eauto. condtac; ss.\n      + rewrite MAX.\n        erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n        des. subst. rewrite a0 in *.\n        exploit Memory.get_ts; try exact MEM. i. des; timetac.\n        rewrite x2 in *.\n        inv CLOSED1_SRC. rewrite INHABITED in MEM. ss.\n      + i. erewrite Memory.remove_o; eauto. condtac; ss.\n        apply PROMISES. des; ss.\n      + ii. revert GET.\n        erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n  Qed.\n\n  Lemma eq_loc_max_ts\n        loc mem1 mem2\n        (MEMLOC: forall to, Memory.get loc to mem1 = Memory.get loc to mem2):\n    Memory.max_ts loc mem1 = Memory.max_ts loc mem2.\n  Proof.\n    unfold Memory.max_ts.\n    replace (mem1 loc) with (mem2 loc); ss.\n    apply Cell.ext. eauto.\n  Qed.\n\n  Lemma sim_thread_promise_step\n        l e1_src\n        pf e_tgt e1_tgt e2_tgt\n        (SIM1: sim_thread l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (STEP_TGT: Thread.promise_step pf e_tgt e1_tgt e2_tgt):\n    exists e_src e2_src,\n      <<STEP_SRC: Thread.opt_promise_step e_src e1_src e2_src>> /\\\n      <<SIM2: sim_thread l e2_src e2_tgt>>.\n  Proof.\n    inversion STEP_TGT. subst.\n    destruct (Loc.eq_dec loc l).\n    { subst. inv LOCAL; ss.\n      esplits; [econs 1|]; eauto.\n      inv SIM1. ss.\n      exploit promise_loc; try exact PROMISE; try apply LOCAL; eauto. i. des.\n      econs; ss; eauto.\n      econs; ss; eauto; try apply LOCAL.\n    }\n    exploit promise_step; try exact LOCAL; try apply SIM1;\n      try apply WF1_SRC; try apply WF1_TGT; eauto.\n    i. des.\n    destruct e1_src. ss.\n    esplits.\n    - econs 2. econs; eauto.\n    - inv SIM1. inv STEP_SRC. ss.\n      econs; eauto; ss; ii.\n      + erewrite Memory.promise_get_diff; eauto.\n        erewrite <- eq_loc_max_ts; eauto.\n        i. symmetry. eapply Memory.promise_get_diff; eauto.\n      + erewrite Memory.promise_get_diff_promise; eauto.\n      + erewrite Memory.promise_get_diff in GET; eauto.\n  Qed.\n\n  Lemma promote_itree_step\n        l val X (i: MemE.t X) k\n        st1_tgt\n        e st2_tgt\n        (STMTS1: sim_state l val (Vis i k) st1_tgt)\n        (STEP_TGT: ILang.step (ThreadEvent.get_program_event e) st1_tgt st2_tgt)\n        (NORMAL: loc_free_event l i)\n    :\n      exists st2_src,\n        (<<STEP_SRC: ILang.step (ThreadEvent.get_program_event e) (Vis i k) st2_src>>) /\\\n        (<<STMTS2: sim_state l val st2_src st2_tgt>>) /\\\n        (<<NORMAL: ~ ThreadEvent.is_accessing_loc l e>>)\n  .\n  Proof.\n    subst. inv STMTS1. rewrite unfold_promote_itree in *. ss. destruct i.\n    - des_ifs; ss. dependent destruction STEP_TGT. esplits; eauto.\n      + rewrite <- x. econs; eauto.\n      + destruct e; ss; clarify.\n    - des_ifs; ss. dependent destruction STEP_TGT. esplits; eauto.\n      + rewrite <- x. econs; eauto.\n      + destruct e; ss; clarify.\n    - destruct rmw; des_ifs; ss; dependent destruction STEP_TGT.\n      + esplits; eauto.\n        * rewrite <- x. econs; eauto.\n        * destruct e; ss; clarify.\n      + esplits; eauto.\n        * rewrite <- x. econs; eauto.\n        * destruct e; ss; clarify.\n      + esplits; eauto.\n        * rewrite <- x. econs; eauto.\n        * destruct e; ss; clarify.\n      + esplits; eauto.\n        * rewrite <- x. econs; eauto.\n        * destruct e; ss; clarify.\n    - des_ifs; ss. dependent destruction STEP_TGT. esplits; eauto.\n      + rewrite <- x. econs; eauto.\n      + destruct e; ss; clarify.\n    - des_ifs; ss. dependent destruction STEP_TGT. esplits; eauto.\n      + rewrite <- x. econs; eauto.\n      + destruct e; ss; clarify.\n    - des_ifs; ss. dependent destruction STEP_TGT. esplits; eauto.\n      + rewrite <- x. econs; eauto.\n      + econs. apply bisim_is_eq. ginit. gcofix CIH.\n        gstep. red. cbn. econs. gbase. auto.\n      + destruct e; ss; clarify.\n    - des_ifs; ss. dependent destruction STEP_TGT. esplits; eauto.\n      + rewrite <- x. econs; eauto.\n      + destruct e; ss; clarify.\n  Qed.\n\n  Lemma sim_thread_program_step\n        l e1_src\n        e_tgt e1_tgt e2_tgt\n        (SIM1: sim_thread l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_SRC: Memory.closed_timemap (Thread.sc e1_src) (Thread.memory e1_src))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEP_TGT: Thread.program_step e_tgt e1_tgt e2_tgt):\n    exists e_src e2_src,\n      <<STEP_SRC: Thread.opt_program_step e_src e1_src e2_src>> /\\\n      <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n      <<SIM2: sim_thread l e2_src e2_tgt>>.\n  Proof.\n    destruct e1_src as [stmts1_src lc1_src sc1_src mem1_src].\n    destruct e1_tgt as [stmts1_tgt lc1_tgt sc1_tgt mem1_tgt].\n    dup SIM1. inv SIM0. ss. inv STATE. inv STEP_TGT. des.\n    ides stmts1_src.\n    (* ret *)\n    { rewrite unfold_promote_itree in STATE. inv STATE. }\n    (* tau *)\n    { rewrite unfold_promote_itree in STATE. inv STATE. inv LOCAL0; ss. esplits; eauto.\n      { econs 2. econs 1; eauto. econs; eauto. }\n      { ss. }\n      { econs; eauto. ss. }\n    }\n    (* normal *)\n    destruct (classic (loc_free_event l e)) as [NORMAL|PROMOTE].\n    { exploit promote_itree_step; eauto. i. des.\n      exploit program_step; try eapply SIM1; try exact LOCAL; eauto.\n      s. i. des. esplits.\n      { econs 2. econs.\n        { rewrite EVENT2. eauto. }\n        { eauto. }\n      }\n      { ss. }\n      { econs; ss.\n        + eauto.\n        + cut (forall to, Memory.get l to mem1_src = Memory.get l to mem2_src).\n          { i. hexploit eq_loc_max_ts; eauto. i.\n            rewrite <- H. rewrite <- H0.\n            inv SIM1. ss. eauto. }\n          unfold ThreadEvent.is_accessing_loc in *.\n          eapply Local.program_step_get_diff; try exact STEP_SRC0.\n          rewrite ThreadEvent.eq_program_event_eq_loc; eauto.\n        + i. erewrite <- Local.program_step_get_diff_promises; try exact STEP_SRC0; eauto.\n          rewrite ThreadEvent.eq_program_event_eq_loc; eauto.\n        + ii. exploit Local.program_step_future; try exact STEP_SRC; eauto. i. des.\n          etrans; try eapply TVIEW_FUTURE.\n          inv SIM1. ss. revert GET.\n          unfold ThreadEvent.is_accessing_loc in *.\n          erewrite <- Local.program_step_get_diff; eauto.\n          rewrite ThreadEvent.eq_program_event_eq_loc; eauto.\n      }\n    }\n    rewrite unfold_promote_itree in STATE. destruct e; ss.\n    (* load *)\n    { des_ifs; ss.\n      inv STATE. destruct e_tgt; ss; try by inv LOCAL0.\n      exploit PromotionProgress.progress_read; try eapply LATEST; eauto.\n      { destruct released; eauto using View.bot_spec. }\n      i. des. esplits.\n      - econs 2. econs; cycle 1.\n        + econs 2; eauto.\n        + econs. econs.\n      - ss.\n      - inv LOCAL0; ss. econs; ss; eauto.\n        + etrans; eauto. symmetry. ss.\n        + ii. inv STEP. inv LC. ss.\n          exploit FULFILLABLE; eauto.\n        + inv STEP. inv LC. ss.\n        + ii. etrans; try eapply SAFE; eauto.\n          exploit Local.read_step_future; eauto. i. des.\n          apply TVIEW_FUTURE.\n    }\n    (* store *)\n    { des_ifs; ss.\n      inv STATE. destruct e_tgt; ss; try by inv LOCAL0.\n      exploit PromotionProgress.progress_write; try exact WF1_SRC; try exact SC1_SRC; eauto.\n      { ss. apply View.bot_spec. }\n      i. des. esplits.\n      - econs 2. econs; cycle 1.\n        + econs 3; eauto.\n        + econs. econs.\n      - ss.\n      - inv LOCAL0. econs; ss; eauto.\n        + etrans; eauto. symmetry. ss.\n        + etrans; eauto. symmetry. ss.\n        + ii. inv STEP. inv LC. ss.\n          inv WRITE. inv PROMISE. revert GETP.\n          erewrite Memory.remove_o; eauto. condtac; ss.\n          erewrite Memory.add_o; eauto. condtac; ss. i.\n          guardH o. guardH o0.\n          destruct (Loc.eq_dec loc l); try by subst; congr.\n          exploit FULFILLABLE; eauto. i. des. split.\n          * unfold tview_released_le_loc in *.\n            unfold TView.write_tview. ss.\n            unfold LocFun.add. condtac; ss.\n          * unfold prev_released_le_loc in *.\n            erewrite Memory.add_o; eauto. condtac; ss.\n            des. subst. ss.\n        + inv STEP. inv WRITE. inv PROMISE. ss.\n          exploit Memory.add_get0; try exact MEM0. i. des.\n          replace (Memory.max_ts l mem0) with (Time.incr (Memory.max_ts l mem1_src)); eauto.\n          exploit Memory.max_ts_spec; try exact GET0. i. des. inv MAX; ss.\n          revert GET1. erewrite Memory.add_o; eauto. condtac; ss; try by des.\n          guardH o. i.\n          exploit Memory.max_ts_spec; try exact GET1. i. des.\n          exploit TimeFacts.lt_le_lt; try exact H; try exact MAX. i.\n          specialize (Time.incr_spec (Memory.max_ts l mem1_src)). i.\n          rewrite x0 in H1. timetac.\n        + exploit Local.write_step_future; eauto. i. des.\n          inv STEP. inv WRITE. inv PROMISE. ss.\n          ii. revert GET.\n          erewrite Memory.add_o; eauto. condtac; ss; i.\n          * inv GET. rewrite H3 in *. ss.\n          * etrans; try eapply TVIEW_FUTURE; eauto.\n    }\n    { des_ifs; ss.\n      (* fa *)\n      { inv STATE. destruct e_tgt; ss; try by inv LOCAL0.\n        exploit PromotionProgress.progress_read; try eapply LATEST; eauto.\n        { destruct released; eauto using View.bot_spec. }\n        i. des.\n        exploit Local.read_step_future; eauto. i. des.\n        exploit PromotionProgress.progress_write; try exact WF2; eauto.\n        { inv STEP. ss. }\n        { etrans; try eapply TVIEW_FUTURE.\n          destruct released; try apply View.bot_spec.\n          eapply SAFE; eauto. }\n        i. des. esplits.\n        - econs 2. econs; cycle 1.\n          + econs 4; eauto.\n          + econs; eauto. econs; eauto.\n        - ss.\n        - inv LOCAL0. econs; ss; eauto.\n          + etrans; eauto. symmetry. etrans; eauto.\n          + etrans; eauto. symmetry. ss.\n          + ii. inv STEP. inv LC0. ss. inv STEP0. ss.\n            inv WRITE. inv PROMISE. revert GETP.\n            erewrite Memory.remove_o; eauto. condtac; ss.\n            erewrite Memory.add_o; eauto. condtac; ss. i.\n            guardH o. guardH o0.\n            destruct (Loc.eq_dec loc l); try by subst; congr.\n            exploit FULFILLABLE; eauto. i. des. split.\n            * unfold tview_released_le_loc in *.\n              unfold TView.write_tview. ss.\n              unfold LocFun.add. condtac; ss.\n            * unfold prev_released_le_loc in *.\n              erewrite Memory.add_o; eauto. condtac; ss.\n              des. subst. ss.\n          + inv STEP0. inv WRITE. inv PROMISE. ss.\n            exploit Memory.add_get0; try exact MEM0. i. des.\n            replace (Memory.max_ts l mem0) with (Time.incr (Memory.max_ts l mem1_src)); eauto.\n            exploit Memory.max_ts_spec; try exact GET0. i. des. inv MAX; ss.\n            revert GET1. erewrite Memory.add_o; eauto. condtac; ss; try by des.\n            guardH o. i.\n            exploit Memory.max_ts_spec; try exact GET1. i. des.\n            exploit TimeFacts.lt_le_lt; try exact H; try exact MAX. i.\n            specialize (Time.incr_spec (Memory.max_ts l mem1_src)). i.\n            rewrite x0 in H1. timetac.\n          + exploit Local.write_step_future; eauto. i. des.\n            inv STEP0. inv WRITE. inv PROMISE. ss.\n            ii. revert GET.\n            erewrite Memory.add_o; eauto. condtac; ss; i.\n            * inv GET. rewrite H3 in *. ss.\n            * etrans; try eapply TVIEW_FUTURE0.\n              etrans; try eapply TVIEW_FUTURE; eauto.\n      }\n      (* cas success *)\n      { inv STATE. destruct e_tgt; ss; try by inv LOCAL0.\n        exploit PromotionProgress.progress_read; try eapply LATEST; eauto.\n        { destruct released; eauto using View.bot_spec. }\n        i. des.\n        exploit Local.read_step_future; eauto. i. des.\n        exploit PromotionProgress.progress_write; try exact WF2; eauto.\n        { inv STEP. ss. }\n        { etrans; try eapply TVIEW_FUTURE.\n          destruct released; try apply View.bot_spec.\n          eapply SAFE; eauto. }\n        i. des. esplits.\n        - econs 2. econs; cycle 1.\n          + econs 4; eauto.\n          + econs; eauto. econs 2; eauto.\n            rewrite Const.eqb_sym. ii. congr.\n        - ss.\n        - inv LOCAL0. econs; ss; eauto.\n          + etrans; eauto. symmetry. etrans; eauto.\n          + etrans; eauto. symmetry. ss.\n          + ii. inv STEP. inv LC0. ss. inv STEP0. ss.\n            inv WRITE. inv PROMISE. revert GETP.\n            erewrite Memory.remove_o; eauto. condtac; ss.\n            erewrite Memory.add_o; eauto. condtac; ss. i.\n            guardH o. guardH o0.\n            destruct (Loc.eq_dec loc l); try by subst; congr.\n            exploit FULFILLABLE; eauto. i. des. split.\n            * unfold tview_released_le_loc in *.\n              unfold TView.write_tview. ss.\n              unfold LocFun.add. condtac; ss.\n            * unfold prev_released_le_loc in *.\n              erewrite Memory.add_o; eauto. condtac; ss.\n              des. subst. ss.\n          + inv STEP0. inv WRITE. inv PROMISE. ss.\n            exploit Memory.add_get0; try exact MEM0. i. des.\n            replace (Memory.max_ts l mem0) with (Time.incr (Memory.max_ts l mem1_src)); eauto.\n            exploit Memory.max_ts_spec; try exact GET0. i. des. inv MAX; ss.\n            revert GET1. erewrite Memory.add_o; eauto. condtac; ss; try by des.\n            guardH o. i.\n            exploit Memory.max_ts_spec; try exact GET1. i. des.\n            exploit TimeFacts.lt_le_lt; try exact H; try exact MAX. i.\n            specialize (Time.incr_spec (Memory.max_ts l mem1_src)). i.\n            rewrite x0 in H1. timetac.\n          + exploit Local.write_step_future; eauto. i. des.\n            inv STEP0. inv WRITE. inv PROMISE. ss.\n            ii. revert GET.\n            erewrite Memory.add_o; eauto. condtac; ss; i.\n            * inv GET. rewrite H3 in *. ss.\n            * etrans; try eapply TVIEW_FUTURE0.\n              etrans; try eapply TVIEW_FUTURE; eauto.\n      }\n      (* cas fail *)\n      { inv STATE. destruct e_tgt; ss; try by inv LOCAL0.\n        exploit PromotionProgress.progress_read; try eapply LATEST; eauto.\n        { destruct released; eauto using View.bot_spec. }\n        i. des. esplits.\n        - econs 2. econs; cycle 1.\n          + econs 2; eauto.\n          + econs; eauto. econs 3; eauto.\n            rewrite Const.eqb_sym. ii. congr.\n        - ss.\n        - inv LOCAL0. econs; ss; eauto.\n          + etrans; eauto. symmetry. ss.\n          + ii. inv STEP. inv LC. ss.\n            exploit FULFILLABLE; eauto.\n          + inv STEP. inv LC. ss.\n          + ii. etrans; try eapply SAFE; eauto.\n            exploit Local.read_step_future; eauto. i. des.\n            apply TVIEW_FUTURE.\n      }\n      { inv STATE. destruct e_tgt; ss; try by inv LOCAL0.\n        exploit PromotionProgress.progress_read; try eapply LATEST; eauto.\n        { destruct released; eauto using View.bot_spec. }\n        i. des. esplits.\n        - econs 2. econs; cycle 1.\n          + econs 2; eauto.\n          + econs; eauto. econs 3; eauto.\n            rewrite Const.eqb_sym. ii. congr.\n        - ss.\n        - inv LOCAL0. econs; ss; eauto.\n          + etrans; eauto. symmetry. ss.\n          + ii. inv STEP. inv LC. ss.\n            exploit FULFILLABLE; eauto.\n          + inv STEP. inv LC. ss.\n          + ii. etrans; try eapply SAFE; eauto.\n            exploit Local.read_step_future; eauto. i. des.\n            apply TVIEW_FUTURE.\n      }\n    }\n  Qed.\n\n  Lemma sim_thread_step\n        l e1_src\n        pf e_tgt e1_tgt e2_tgt\n        (SIM1: sim_thread l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_SRC: Memory.closed_timemap (Thread.sc e1_src) (Thread.memory e1_src))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEP_TGT: Thread.step pf e_tgt e1_tgt e2_tgt):\n    exists e_src e2_src,\n      <<STEP_SRC: Thread.opt_step e_src e1_src e2_src>> /\\\n      <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n      <<SIM2: sim_thread l e2_src e2_tgt>>.\n  Proof.\n    inv STEP_TGT.\n    - exploit sim_thread_promise_step; eauto. i. des.\n      esplits.\n      + inv STEP_SRC.\n        * econs 1.\n        * econs 2. econs 1; eauto.\n      + inv STEP. inv STEP_SRC; ss. inv STEP. ss.\n      + ss.\n    - exploit sim_thread_program_step; eauto. i. des.\n      esplits.\n      + inv STEP_SRC.\n        * econs 1.\n        * econs 2. econs 2; eauto.\n      + ss.\n      + ss.\n  Qed.\n\n  Lemma sim_thread_opt_step\n        l e1_src\n        e_tgt e1_tgt e2_tgt\n        (SIM1: sim_thread l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_SRC: Memory.closed_timemap (Thread.sc e1_src) (Thread.memory e1_src))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEP_TGT: Thread.opt_step e_tgt e1_tgt e2_tgt):\n    exists e_src e2_src,\n      <<STEP_SRC: Thread.opt_step e_src e1_src e2_src>> /\\\n      <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n      <<SIM2: sim_thread l e2_src e2_tgt>>.\n  Proof.\n    inv STEP_TGT.\n    - esplits; eauto. econs 1.\n    - exploit sim_thread_step; eauto.\n  Qed.\n\n  Lemma sim_thread_rtc_tau_step\n        l e1_src\n        e1_tgt e2_tgt\n        (SIM1: sim_thread l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_SRC: Memory.closed_timemap (Thread.sc e1_src) (Thread.memory e1_src))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEPS_TGT: rtc (@Thread.tau_step (lang (Const.t * R))) e1_tgt e2_tgt):\n    exists e2_src,\n      <<STEPS_SRC: rtc (@Thread.tau_step (lang R)) e1_src e2_src>> /\\\n      <<SIM2: sim_thread l e2_src e2_tgt>>.\n  Proof.\n    revert e1_src SIM1 WF1_SRC SC1_SRC CLOSED1_SRC.\n    induction STEPS_TGT; i.\n    - esplits; eauto.\n    - inv H. inv TSTEP.\n      exploit sim_thread_step; eauto. i. des.\n      exploit Thread.step_future; try exact STEP; eauto. i. des.\n      exploit Thread.opt_step_future; try exact STEP_SRC; eauto. i. des.\n      exploit IHSTEPS_TGT; eauto. i. des.\n      inv STEP_SRC.\n      + esplits; eauto.\n      + esplits; [M|..]; eauto.\n        econs; [|eauto].\n        econs; [econs; eauto|]. rewrite <- EVENT. ss.\n  Qed.\n\n  Lemma sim_thread_plus_step\n        l e1_src\n        pf e_tgt e1_tgt e2_tgt e3_tgt\n        (SIM1: sim_thread l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_SRC: Memory.closed_timemap (Thread.sc e1_src) (Thread.memory e1_src))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEPS_TGT: rtc (@Thread.tau_step (lang (Const.t * R))) e1_tgt e2_tgt)\n        (STEP_TGT: Thread.step pf e_tgt e2_tgt e3_tgt):\n    exists e_src e2_src e3_src,\n      <<STEPS_SRC: rtc (@Thread.tau_step (lang R)) e1_src e2_src>> /\\\n      <<STEP_SRC: Thread.opt_step e_src e2_src e3_src>> /\\\n      <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n      <<SIM3: sim_thread l e3_src e3_tgt>>.\n  Proof.\n    exploit sim_thread_rtc_tau_step; eauto. i. des.\n    exploit Thread.rtc_tau_step_future; try exact STEPS_SRC; eauto. i. des.\n    exploit Thread.rtc_tau_step_future; try exact STEPS_TGT; eauto. i. des.\n    exploit sim_thread_step; eauto. i. des.\n    esplits; eauto.\n  Qed.\n\n  Lemma sim_thread_all_plus_step\n        l e1_src\n        pf e_tgt e1_tgt e2_tgt e3_tgt\n        (SIM1: sim_thread_all l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_SRC: Memory.closed_timemap (Thread.sc e1_src) (Thread.memory e1_src))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEPS_TGT: rtc (@Thread.tau_step (lang (Const.t * R))) e1_tgt e2_tgt)\n        (STEP_TGT: Thread.step pf e_tgt e2_tgt e3_tgt)\n        (EVENT: ThreadEvent.get_machine_event e_tgt <> MachineEvent.silent):\n    exists e_src e2_src e3_src,\n      <<STEPS_SRC: rtc (@Thread.tau_step (lang R)) e1_src e2_src>> /\\\n      <<STEP_SRC: Thread.step true e_src e2_src e3_src>> /\\\n      <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n      <<SIM3: sim_thread l e3_src e3_tgt>>.\n  Proof.\n    inv SIM1.\n    { exploit sim_thread_plus_step; eauto. i. des.\n      esplits; eauto.\n      inv STEP_SRC; ss; try congr.\n      destruct pf0; [|inv STEP; inv STEP0; ss; congr]. ss.\n    }\n    { exploit step_reserve_sim_thread; try exact H; eauto. i. des.\n      exploit Thread.step_future; eauto. i. des.\n      exploit sim_thread_plus_step; try exact SIM2; eauto. i. des.\n      exploit Thread.rtc_tau_step_future; try exact STEPS_SRC; eauto. i. des.\n      exploit Thread.opt_step_future; try exact STEP_SRC; eauto. i. des.\n      inv STEP_SRC; ss; try congr.\n      destruct pf0; [|inv STEP0; inv STEP1; ss; congr].\n      esplits.\n      - econs 2; try exact STEPS_SRC. econs; [econs; eauto|]. ss.\n      - eauto.\n      - ss.\n      - ss.\n    }\n  Qed.\n\n  Lemma sim_thread_all_plus_step_silent\n        l e1_src\n        pf e_tgt e1_tgt e2_tgt e3_tgt\n        (SIM1: sim_thread_all l e1_src e1_tgt)\n        (WF1_SRC: Local.wf (Thread.local e1_src) (Thread.memory e1_src))\n        (WF1_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n        (SC1_SRC: Memory.closed_timemap (Thread.sc e1_src) (Thread.memory e1_src))\n        (SC1_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n        (CLOSED1_SRC: Memory.closed (Thread.memory e1_src))\n        (CLOSED1_TGT: Memory.closed (Thread.memory e1_tgt))\n        (STEPS_TGT: rtc (@Thread.tau_step (lang (Const.t * R))) e1_tgt e2_tgt)\n        (STEP_TGT: Thread.step pf e_tgt e2_tgt e3_tgt)\n        (EVENT: ThreadEvent.get_machine_event e_tgt = MachineEvent.silent):\n    exists e_src e2_src e3_src,\n      <<STEPS_SRC: rtc (@Thread.tau_step (lang R)) e1_src e2_src>> /\\\n      <<STEP_SRC: Thread.opt_step e_src e2_src e3_src>> /\\\n      <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n      <<SIM3: sim_thread_reserve l e3_src e3_tgt>>.\n  Proof.\n    inv SIM1.\n    { exploit sim_thread_plus_step; try exact SIM2; eauto. i. des.\n      exploit Thread.rtc_tau_step_future; try exact STEPS_SRC; eauto. i. des.\n      exploit Thread.opt_step_future; try exact STEP_SRC; eauto. i. des.\n      exploit step_sim_thread_reserve; try exact SIM3; eauto. i. des.\n      exploit Thread.tau_opt_tau; try exact STEPS_SRC; eauto; i.\n      { rewrite EVENT0. ss. }\n      esplits.\n      - apply x0.\n      - econs 2; eauto.\n      - ss.\n      - ss.\n    }\n    { exploit step_reserve_sim_thread; try exact H; eauto. i. des.\n      exploit Thread.step_future; eauto. i. des.\n      exploit sim_thread_plus_step; try exact SIM2; eauto. i. des.\n      exploit Thread.rtc_tau_step_future; try exact STEPS_SRC; eauto. i. des.\n      exploit Thread.opt_step_future; try exact STEP_SRC; eauto. i. des.\n      exploit step_sim_thread_reserve; try exact SIM3; eauto. i. des.\n      exploit Thread.tau_opt_tau; try exact STEPS_SRC; eauto; i.\n      { rewrite EVENT0. ss. }\n      esplits.\n      - econs 2; try exact x0. econs; [econs; eauto|]. ss.\n      - econs 2; eauto.\n      - ss.\n      - ss.\n    }\n  Qed.\n\n\n  (* future *)\n\n  Lemma sim_thread_future\n        l\n        st_src lc_src sc1_src mem1_src sc2_src mem2_src\n        st_tgt lc_tgt sc1_tgt mem1_tgt sc2_tgt mem2_tgt\n        (SIM1: sim_thread l\n                          (Thread.mk (lang R) st_src lc_src sc1_src mem1_src)\n                          (Thread.mk (lang (Const.t * R)) st_tgt lc_tgt sc1_tgt mem1_tgt))\n        (WF1_SRC: Local.wf lc_src mem1_src)\n        (MEM_SRC: Memory.future mem1_src mem2_src)\n        (SC: sim_timemap l sc2_src sc2_tgt)\n        (MEM: sim_memory l mem2_src mem2_tgt)\n        (PREV: Memory.prev_None mem1_src mem2_src)\n        (MEMLOC: forall to, Memory.get l to mem1_src = Memory.get l to mem2_src):\n    sim_thread l\n               (Thread.mk (lang R) st_src lc_src sc2_src mem2_src)\n               (Thread.mk (lang (Const.t * R)) st_tgt lc_tgt sc2_tgt mem2_tgt).\n  Proof.\n    inv SIM1. des. ss. econs; s; eauto.\n    - ii. exploit FULFILLABLE; eauto. i. des. split; ss.\n      unfold prev_released_le_loc in *. des_ifs; ss.\n      + exploit Memory.future_get1; try exact Heq0; eauto; ss. i. des.\n        inv MSG_LE. inv RELEASED; try congr.\n        rewrite Heq in *. inv GET.\n        unnw. etrans; eauto. split; apply LE.\n      + exploit Memory.future_get1; try exact Heq0; eauto; ss. i. des.\n        inv MSG_LE. inv RELEASED; try congr.\n      + exploit Memory.future_get1; try exact Heq0; eauto; ss. i. des.\n        rewrite GET in *. inv Heq. inv MSG_LE.\n      + inv WF1_SRC. exploit PROMISES0; eauto. i.\n        exploit PREV; eauto; ss. ii. congr.\n      + inv WF1_SRC. exploit PROMISES0; eauto. i.\n        exploit PREV; eauto; ss. ii. congr.\n    - erewrite <- eq_loc_max_ts; eauto.\n      rewrite MEMLOC in *.\n      esplits; eauto.\n    - ii. rewrite <- MEMLOC in *. eauto.\n  Qed.\n\n  Lemma sim_thread_reserve_future\n        l\n        st_src lc_src sc1_src mem1_src sc2_src mem2_src\n        st_tgt lc_tgt sc1_tgt mem1_tgt sc2_tgt mem2_tgt\n        (SIM1: sim_thread_reserve l\n                          (Thread.mk (lang R) st_src lc_src sc1_src mem1_src)\n                          (Thread.mk (lang (Const.t * R)) st_tgt lc_tgt sc1_tgt mem1_tgt))\n        (WF1_SRC: Local.wf lc_src mem1_src)\n        (MEM_SRC: Memory.future mem1_src mem2_src)\n        (SC: sim_timemap l sc2_src sc2_tgt)\n        (MEM: sim_memory l mem2_src mem2_tgt)\n        (PREV: Memory.prev_None mem1_src mem2_src)\n        (MEMLOC: forall to, Memory.get l to mem1_src = Memory.get l to mem2_src):\n    sim_thread_reserve l\n               (Thread.mk (lang R) st_src lc_src sc2_src mem2_src)\n               (Thread.mk (lang (Const.t * R)) st_tgt lc_tgt sc2_tgt mem2_tgt).\n  Proof.\n    inv SIM1. des. ss. econs; s; eauto.\n    - ii. exploit FULFILLABLE; eauto. i. des. split; ss.\n      unfold prev_released_le_loc in *. des_ifs; ss.\n      + exploit Memory.future_get1; try exact Heq0; eauto; ss. i. des.\n        inv MSG_LE. inv RELEASED; try congr.\n        rewrite Heq in *. inv GET.\n        unnw. etrans; eauto. split; apply LE.\n      + exploit Memory.future_get1; try exact Heq0; eauto; ss. i. des.\n        inv MSG_LE. inv RELEASED; try congr.\n      + exploit Memory.future_get1; try exact Heq0; eauto; ss. i. des.\n        rewrite GET in *. inv Heq. inv MSG_LE.\n      + inv WF1_SRC. exploit PROMISES0; eauto. i.\n        exploit PREV; eauto; ss. ii. congr.\n      + inv WF1_SRC. exploit PROMISES0; eauto. i.\n        exploit PREV; eauto; ss. ii. congr.\n    - erewrite <- eq_loc_max_ts; eauto.\n      rewrite MEMLOC in *.\n      esplits; eauto.\n    - erewrite <- eq_loc_max_ts; eauto.\n    - ii. rewrite <- MEMLOC in *. eauto.\n  Qed.\n\n  Lemma sim_thread_all_future\n        l\n        st_src lc_src sc1_src mem1_src sc2_src mem2_src\n        st_tgt lc_tgt sc1_tgt mem1_tgt sc2_tgt mem2_tgt\n        (SIM1: sim_thread_all l\n                          (Thread.mk (lang R) st_src lc_src sc1_src mem1_src)\n                          (Thread.mk (lang (Const.t * R)) st_tgt lc_tgt sc1_tgt mem1_tgt))\n        (WF1_SRC: Local.wf lc_src mem1_src)\n        (MEM_SRC: Memory.future mem1_src mem2_src)\n        (SC: sim_timemap l sc2_src sc2_tgt)\n        (MEM: sim_memory l mem2_src mem2_tgt)\n        (PREV: Memory.prev_None mem1_src mem2_src)\n        (MEMLOC: forall to, Memory.get l to mem1_src = Memory.get l to mem2_src):\n    sim_thread_all l\n               (Thread.mk (lang R) st_src lc_src sc2_src mem2_src)\n               (Thread.mk (lang (Const.t * R)) st_tgt lc_tgt sc2_tgt mem2_tgt).\n  Proof.\n    inv SIM1.\n    - left. eapply sim_thread_future; eauto.\n    - right. eapply sim_thread_reserve_future; eauto.\n  Qed.\n\n\n  (* terminal *)\n\n  Lemma sim_thread_promises_bot\n        l e_src e_tgt\n        (SIM: sim_thread l e_src e_tgt)\n        (PROMISES_TGT: (Local.promises (Thread.local e_tgt)) = Memory.bot):\n    <<PROMISES_SRC: (Local.promises (Thread.local e_src)) = Memory.bot>>.\n  Proof.\n    inv SIM. inv LOCAL. apply Memory.ext. i.\n    rewrite Memory.bot_get.\n    destruct (Loc.eq_dec loc l); subst; ss.\n    symmetry in PROMISES1.\n    exploit sim_memory_get_None_src; eauto.\n    rewrite PROMISES_TGT. rewrite Memory.bot_get. ss.\n  Qed.\n\n  Lemma sim_thread_terminal\n        l e_src e_tgt\n        (SIM: sim_thread l e_src e_tgt)\n        (TERMINAL_TGT: (Language.is_terminal (lang _)) (Thread.state e_tgt)):\n    <<TERMINAL_SRC: (Language.is_terminal (lang _)) (Thread.state e_src)>>.\n  Proof.\n    unfold Language.is_terminal in *. ss.\n    unfold ILang.is_terminal in *.\n    inv SIM.\n    clear - TERMINAL_TGT STATE.\n    destruct e_src, e_tgt. ss.\n    inv STATE. des.\n    rewrite unfold_promote_itree in *. ides state0; eauto.\n    destruct e; ss; des_ifs; ss.\n  Qed.\n\n\n  (* certification *)\n\n  Lemma cap_sim_thread_reserve\n        l\n        st_src lc_src sc_src mem_src\n        st_tgt lc_tgt sc_tgt mem_tgt\n        cap_src cap_tgt\n        (SIM: sim_thread_reserve l\n                                 (Thread.mk (lang _) st_src lc_src sc_src mem_src)\n                                 (Thread.mk (lang _) st_tgt lc_tgt sc_tgt mem_tgt))\n        (WF_SRC: Local.wf lc_src mem_src)\n        (WF_TGT: Local.wf lc_tgt mem_tgt)\n        (SC_SRC: Memory.closed_timemap sc_src mem_src)\n        (CLOSED_SRC: Memory.closed mem_src)\n        (CLOSED_TGT: Memory.closed mem_tgt)\n        (CAP_SRC: Memory.cap mem_src cap_src)\n        (CAP_TGT: Memory.cap mem_tgt cap_tgt):\n    exists mem1_src,\n      <<REMOVE: Memory.remove cap_src l (Memory.max_ts l mem_src)\n                              (Time.incr (Memory.max_ts l mem_src)) Message.reserve mem1_src>> /\\\n      <<SIM: sim_thread_reserve l\n                                (Thread.mk (lang _) st_src lc_src sc_src mem1_src)\n                                (Thread.mk (lang _) st_tgt lc_tgt sc_tgt cap_tgt)>> /\\\n      <<WF_SRC: Local.wf lc_src mem1_src>> /\\\n      <<SC_SRC: Memory.closed_timemap sc_src mem1_src>> /\\\n      <<CLOSED_SRC: Memory.closed mem1_src>>.\n  Proof.\n    exploit sim_memory_cap; try eapply SIM; eauto. intros x. des.\n    exploit (@Memory.remove_exists cap_src l (Memory.max_ts l mem_src)\n                                   (Time.incr (Memory.max_ts l mem_src)) Message.reserve);\n      try apply CAP_SRC.\n    intros x0. des.\n    assert (MAX: Memory.max_ts l mem2 = Memory.max_ts l mem_src).\n    { inv SIM. ss. des.\n      dup CAP_SRC. inv CAP_SRC0.\n      exploit Memory.cap_max_ts; try exact CAP_SRC; eauto.\n      instantiate (1 := l). intros x1.\n      exploit SOUND; try exact MEM. intros x2.\n      exploit Memory.remove_get1; try exact x; eauto. i. des.\n      { specialize (Time.incr_spec (Memory.max_ts l mem_src)). i.\n        rewrite <- LOCTS0 in *. timetac. }\n      exploit Memory.max_ts_spec; try exact GET2. i. des.\n      apply TimeFacts.antisym; ss.\n      destruct (TimeFacts.le_lt_dec (Memory.max_ts l mem2) (Memory.max_ts l mem_src)); ss.\n      exfalso.\n      exploit Memory.max_ts_spec; try exact GET. i. des.\n      revert GET0. erewrite Memory.remove_o; eauto. condtac; ss. des; ss. i.\n      exploit Memory.cap_inv; try exact GET0; try exact CAP_SRC; eauto. i. des.\n      - exploit Memory.max_ts_spec; try exact x4. i. des. timetac.\n      - inv x3. exploit Memory.max_ts_spec; try exact GET3. i. des.\n        exploit Memory.get_ts; try exact GET3. intros x6. des.\n        { rewrite x6 in *. inv l0. }\n        { exploit TimeFacts.lt_le_lt; try exact x6; try exact MAX1. i. timetac. }\n      - subst. ss.\n    }\n    esplits; eauto.\n    - inv SIM. ss. des. econs; ss; eauto.\n      + inv x. econs; i.\n        * revert GET_SRC.\n          erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n        * erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n          des. subst. ss.\n      + des. ii.\n        exploit FULFILLABLE; eauto. i. des. splits; ss.\n        unfold prev_released_le_loc in *. des_ifs; ss; revert Heq.\n        * erewrite Memory.remove_o; eauto. condtac; ss. i. guardH o.\n          exploit Memory.cap_inv; try exact CAP_SRC; eauto. i. des; congr.\n        * erewrite Memory.remove_o; eauto. condtac; ss. i. guardH o.\n          exploit Memory.cap_inv; try exact CAP_SRC; eauto. i. des; congr.\n        * erewrite Memory.remove_o; eauto. condtac; ss. i. guardH o.\n          exploit Memory.cap_inv; try exact CAP_SRC; eauto. i. des; congr.\n        * erewrite Memory.remove_o; eauto. condtac; ss. i. guardH o.\n          exploit Memory.cap_inv; try exact CAP_SRC; eauto. i. des; congr.\n        * erewrite Memory.remove_o; eauto. condtac; ss. i. guardH o.\n          exploit Memory.cap_inv; try exact CAP_SRC; eauto. i. des; congr.\n      + rewrite MAX. inv CAP_SRC.\n        exploit SOUND; try exact MEM. i.\n        exploit Memory.remove_get1; try exact x; eauto. i. des.\n        { specialize (Time.incr_spec (Memory.max_ts l mem_src)). i.\n          rewrite <- LOCTS0 in *. timetac. }\n        esplits; eauto.\n        instantiate (1 := released).\n        instantiate (1 := from').\n        erewrite Memory.remove_o; eauto. condtac; ss; eauto.\n        des. subst.\n        exploit Memory.get_ts; try exact MEM. i. des.\n        * specialize (Time.incr_spec (Memory.max_ts l mem_src)). i.\n          rewrite x3 in H. inv H.\n        * specialize (Time.incr_spec (Memory.max_ts l mem_src)). i.\n          rewrite x3 in H. timetac.\n      + i. rewrite MAX in *. eauto.\n      + ii. revert GET.\n        erewrite Memory.remove_o; eauto. condtac; ss. des; ss. i.\n        exploit Memory.cap_inv; try exact GET; try exact CAP_SRC; eauto. i. des; ss.\n        eapply SAFE; eauto.\n    - exploit Local.cap_wf; try exact CAP_SRC; eauto. i.\n      inv x2. econs; ii; eauto.\n      + inv TVIEW_CLOSED.\n        econs; i; eauto using Memory.cancel_closed_view.\n      + inv WF_SRC. exploit PROMISES0; eauto. intros x1.\n        erewrite Memory.remove_o; eauto. condtac; ss; cycle 1.\n        { apply CAP_SRC. ss. }\n        des. subst.\n        exploit Memory.max_ts_spec; try exact x1. i. des.\n        specialize (Time.incr_spec (Memory.max_ts l mem_src)). i.\n        exploit TimeFacts.le_lt_lt; try exact MAX0; try exact H. i. timetac.\n    - hexploit Memory.cap_closed_timemap; try exact CAP_SRC; eauto. i.\n      eapply Memory.cancel_closed_timemap; eauto.\n    - exploit Memory.cap_closed; try exact CAP_SRC; eauto. i.\n      eapply Memory.cancel_closed; eauto.\n  Qed.\n\n  Lemma cap_sim_thread\n        l e_src e_tgt\n        cap_src cap_tgt\n        (SIM: sim_thread_reserve l e_src e_tgt)\n        (WF_SRC: Local.wf (Thread.local e_src) (Thread.memory e_src))\n        (WF_TGT: Local.wf (Thread.local e_tgt) (Thread.memory e_tgt))\n        (SC_SRC: Memory.closed_timemap (Thread.sc e_src) (Thread.memory e_src))\n        (SC_TGT: Memory.closed_timemap (Thread.sc e_tgt) (Thread.memory e_tgt))\n        (CLOSED_SRC: Memory.closed (Thread.memory e_src))\n        (CLOSED_TGT: Memory.closed (Thread.memory e_tgt))\n        (CAP_SRC: Memory.cap (Thread.memory e_src) cap_src)\n        (CAP_TGT: Memory.cap (Thread.memory e_tgt) cap_tgt):\n    exists from e2_src mem_src,\n      <<STEP: Thread.step true (ThreadEvent.promise l from (Memory.max_ts l (Thread.memory e_src)) Message.reserve Memory.op_kind_cancel)\n                          (Thread.mk (lang _) (Thread.state e_src) (Thread.local e_src) (Thread.sc e_src) cap_src) e2_src>> /\\\n      <<SPACE: CompressSteps.spatial_mem (Thread.memory e2_src) mem_src>> /\\\n      <<SIM: sim_thread l\n                        (Thread.mk (lang _) (Thread.state e2_src) (Thread.local e2_src) (Thread.sc e2_src) mem_src)\n                        (Thread.mk (lang _) (Thread.state e_tgt) (Thread.local e_tgt) (Thread.sc e_tgt) cap_tgt)>> /\\\n      <<WF_SRC: Local.wf (Thread.local e2_src) mem_src>> /\\\n      <<SC_SRC: Memory.closed_timemap (Thread.sc e2_src) mem_src>> /\\\n      <<MEM_SRC: Memory.closed mem_src>>.\n  Proof.\n    destruct e_src as [st1_src lc1_src sc1_src mem1_src].\n    destruct e_tgt as [st1_tgt lc1_tgt sc1_tgt mem1_tgt].\n    ss.\n    exploit cap_sim_thread_reserve; eauto. i. des.\n    exploit step_reserve_sim_thread; try exact SIM0; eauto. i. des.\n    assert (to = Memory.max_ts l mem1_src); subst.\n    { inv SIM. ss. des.\n      inv STEP; inv STEP0; inv LOCAL; inv LOCAL0. inv PROMISE0.\n      exploit Memory.remove_get0; try exact PROMISES0. i. des.\n      destruct (Time.eq_dec to (Memory.max_ts l mem1_src)); ss.\n      exploit PROMISES; eauto. i. congr.\n    }\n    destruct e2_src as [st2_src lc2_src sc2_src mem2_src]. ss.\n    cut (exists mem'_src,\n            <<STEP': Thread.step true (ThreadEvent.promise l from (Memory.max_ts l mem1_src) Message.reserve Memory.op_kind_cancel)\n                                 (Thread.mk (lang _) st1_src lc1_src sc1_src cap_src)\n                                 (Thread.mk (lang _) st1_src lc2_src sc2_src mem'_src)>> /\\\n            <<SPACE: CompressSteps.spatial_mem mem'_src mem2_src>>).\n    { i. des.\n      exploit Thread.step_future; try exact STEP; eauto. s. i. des.\n      inv STEP; inv STEP0; inv LOCAL. ss.\n      esplits; try exact STEP'; eauto.\n    }\n    inv SIM. ss. des. dup CAP_SRC. inv CAP_SRC0.\n    inv STEP; inv STEP0; inv LOCAL0. inv PROMISE0. ss.\n    replace from0 with from in *; cycle 1.\n    { exploit SOUND; try exact MEM. intros x.\n      exploit Memory.remove_get0; try exact MEM0. i. des.\n      revert GET. erewrite Memory.remove_o; eauto. condtac; ss. i.\n      rewrite GET in *. inv x. ss. }\n    exploit (@Memory.remove_exists cap_src l from (Memory.max_ts l mem1_src) Message.reserve).\n    { exploit SOUND; try exact MEM. ss. }\n    i. des. exists mem2. split.\n    - econs 1. econs; eauto.\n    - move MEM0 at bottom. move REMOVE at bottom.\n      exploit (@Memory.add_exists mem2_src l (Memory.max_ts l mem1_src)\n                                  (Time.incr (Memory.max_ts l mem1_src)) Message.reserve).\n      { ii. revert GET2.\n        erewrite Memory.remove_o; eauto. condtac; ss.\n        erewrite Memory.remove_o; eauto. condtac; ss.\n        i. des; ss.\n        exploit Memory.remove_get0; try exact REMOVE. i. des.\n        exploit Memory.get_disjoint; [exact GET2|exact GET|..]. i. des; eauto. }\n      { apply Time.incr_spec. }\n      { econs. }\n      i. des.\n      cut (mem2 = mem0).\n      { i. subst. econs; eauto.\n        destruct (TimeFacts.le_lt_dec (Memory.max_ts l mem1_src) (Memory.max_ts l mem2_src)); ss.\n        inv CLOSED_SRC0. clear CLOSED0.\n        specialize (INHABITED l).\n        exploit Memory.remove_get1; try exact INHABITED; eauto. i. des.\n        { rewrite <- LOCTS0 in *.\n          inv CLOSED_SRC. rewrite INHABITED0 in *. congr. }\n        exploit Memory.max_ts_spec; try exact GET2. i. des.\n        revert GET.\n        erewrite Memory.remove_o; eauto. condtac; ss.\n        erewrite Memory.remove_o; eauto. condtac; ss.\n        des; ss. i.\n        exploit Memory.cap_inv; try exact GET; try exact CAP_SRC; eauto. i. des.\n        - exploit Memory.max_ts_spec; try exact x2. i. des.\n          exploit TimeFacts.antisym; [exact l0|exact MAX0|..]. i. congr.\n        - inv x3. exploit Memory.get_ts; try exact GET0. i. des.\n          + subst. rewrite x3 in *. inv x4.\n          + exploit Memory.max_ts_spec; try exact GET0. i. des.\n            rewrite l0 in MAX0.\n            exploit TimeFacts.lt_le_lt; try exact x3; try exact MAX0. i. timetac.\n        - subst. rewrite x4 in *. ss.\n      }\n      apply Memory.ext. i.\n      erewrite Memory.remove_o; eauto. condtac; ss.\n      + des. subst.\n        erewrite Memory.add_o; eauto. condtac; ss.\n        * des. specialize (Time.incr_spec (Memory.max_ts l mem1_src)). i.\n          rewrite <- a0 in *. timetac.\n        * des; ss.\n          exploit Memory.remove_get0; try exact MEM0. i. des. ss.\n      + erewrite (@Memory.add_o mem0); eauto. condtac; ss.\n        * des; ss. subst.\n          exploit Memory.remove_get0; try exact REMOVE. i. des. ss.\n        * erewrite (@Memory.remove_o mem2_src); eauto. condtac; ss.\n          erewrite (@Memory.remove_o mem1_src0); eauto. condtac; ss.\n  Qed.\n\n  Lemma sim_thread_reserve_consistent\n        l e_src e_tgt\n        (SIM: sim_thread_reserve l e_src e_tgt)\n        (WF_SRC: Local.wf (Thread.local e_src) (Thread.memory e_src))\n        (WF_TGT: Local.wf (Thread.local e_tgt) (Thread.memory e_tgt))\n        (SC_SRC: Memory.closed_timemap (Thread.sc e_src) (Thread.memory e_src))\n        (SC_TGT: Memory.closed_timemap (Thread.sc e_tgt) (Thread.memory e_tgt))\n        (CLOSED_SRC: Memory.closed (Thread.memory e_src))\n        (CLOSED_TGT: Memory.closed (Thread.memory e_tgt))\n        (CONSISTENT_TGT: Thread.consistent e_tgt):\n    <<CONSISTENT_SRC: Thread.consistent e_src>>.\n  Proof.\n    exploit Memory.cap_exists; try exact CLOSED_TGT. i. des.\n    exploit Memory.cap_closed; eauto. i.\n    ii. rename mem1 into cap_src, mem2 into cap_tgt.\n    exploit Local.cap_wf; try exact WF_SRC; eauto. intro WF_CAP_SRC.\n    exploit Local.cap_wf; try exact WF_TGT; eauto. intro WF_CAP_TGT.\n    hexploit Memory.cap_closed_timemap; try exact SC_SRC; eauto. intro SC_CAP_SRC.\n    hexploit Memory.cap_closed_timemap; try exact SC_TGT; eauto. intro SC_CAP_TGT.\n    exploit Memory.cap_closed; try exact CAP0; eauto. i.\n    exploit cap_sim_thread; try exact SIM; eauto. i. des.\n    exploit Thread.step_future; try exact STEP; eauto. s. i. des.\n    exploit CONSISTENT_TGT; eauto. i. des.\n    - left. unfold Thread.steps_failure in *. des.\n      exploit sim_thread_plus_step; try exact STEPS; eauto. s. i. des.\n      exploit (@CompressSteps.compress_steps_failure\n                 (lang _) e2_src\n                 (Thread.mk (lang _) (Thread.state e2_src) (Thread.local e2_src) (Thread.sc e2_src) mem_src)); eauto.\n      { econs; eauto. }\n      { unfold Thread.steps_failure.\n        inv STEP_SRC; ss; try congr.\n        destruct pf; try by inv STEP0; inv STEP1; ss; congr.\n        esplits; eauto. congr.\n      }\n      unfold Thread.steps_failure. i. des.\n      esplits; try exact STEP_FAILURE0; ss.\n      econs 2.\n      + econs; [econs; exact STEP|]. ss.\n      + ss.\n    - right.\n      exploit sim_thread_rtc_tau_step; try exact STEPS; eauto. i. des.\n      exploit (@CompressSteps.compress_steps_fulfill\n                 (lang _) e2_src\n                 (Thread.mk (lang _) (Thread.state e2_src) (Thread.local e2_src) (Thread.sc e2_src) mem_src)); eauto.\n      { econs; eauto. }\n      { inv SIM2. apply Memory.ext. i.\n        rewrite Memory.bot_get.\n        destruct (Loc.eq_dec loc l); subst; ss.\n        inv LOCAL. eapply sim_memory_get_None_tgt; eauto.\n        rewrite PROMISES. apply Memory.bot_get.\n      }\n      i. des.\n      esplits; [|exact PROMISES_SRC].\n      econs 2.\n      + econs; [econs; exact STEP|]. ss.\n      + ss.\n  Qed.\n  End TYPE.\nEnd SimThreadPromotion.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/promotion/iSimThreadPromotion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.22206991791466832}}
{"text": "Require MirrorCore.Lambda.TypedFoldLazy.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nDefinition typed_mfold_lazy\n           (typ : Set) (typD : list Type -> typ -> Type) (func : Set)\n           (_ : SymI.RSym typD func)\n           (_ : TypesI2.Typ2 typD PreFun.Fun)\n           (ts : list Type)\n           (T : Type)\n       (do_var : ExprCore.var -> typ -> TypedFoldLazy.Lazy T)\n       (do_uvar : ExprCore.uvar -> typ -> TypedFoldLazy.Lazy T)\n       (do_inj : func -> typ -> TypedFoldLazy.Lazy T)\n       (do_app : list typ -> list typ -> typ -> typ ->\n                 TypedFoldLazy.Lazy T -> TypedFoldLazy.Lazy T -> TypedFoldLazy.Lazy T)\n       (do_abs : list typ -> list typ -> typ -> typ ->\n                 TypedFoldLazy.Lazy T -> TypedFoldLazy.Lazy T)\n       (tus tvs : list typ) (t : typ) (e : ExprCore.expr typ func)\n: option T :=\n  @TypedFoldLazy.typed_mfold_cpsL typ typD func _ _ ts T\n                                  do_var do_uvar do_inj do_app do_abs\n                                  (option T) tus tvs t e\n                                  (fun x => x tt)\n                                  None.\n\nDefinition typed_mfold_infer_lazy\n           (typ : Type) (typD : list Type -> typ -> Type) (func : Type)\n           (_ : SymI.RSym typD func)\n           (_ : TypesI2.Typ2 typD PreFun.Fun)\n           (ts : list Type)\n           (T : Type)\n       (do_var : ExprCore.var -> typ -> TypedFoldLazy.Lazy T)\n       (do_uvar : ExprCore.uvar -> typ -> TypedFoldLazy.Lazy T)\n       (do_inj : func -> typ -> TypedFoldLazy.Lazy T)\n       (do_app : list typ -> list typ -> typ -> typ ->\n                 TypedFoldLazy.Lazy T -> TypedFoldLazy.Lazy T -> TypedFoldLazy.Lazy T)\n       (do_abs : list typ -> list typ -> typ -> typ ->\n                 TypedFoldLazy.Lazy T -> TypedFoldLazy.Lazy T)\n       (tus tvs : list typ) (e : ExprCore.expr typ func)\n: option (typ * T) :=\n  @TypedFoldLazy.typed_mfold_infer_cpsL typ typD func _ _ ts T\n                                  do_var do_uvar do_inj do_app do_abs\n                                  (option (typ * T)) tus tvs e\n                                  (fun t x => match x tt with\n                                                | None => None\n                                                | Some val => Some (t,val)\n                                              end)\n                                  None.\n", "meta": {"author": "gmalecha", "repo": "mirror-core", "sha": "b962fbca15b0b5a4653f66d29d7115bb04ebd4f3", "save_path": "github-repos/coq/gmalecha-mirror-core", "path": "github-repos/coq/gmalecha-mirror-core/mirror-core-b962fbca15b0b5a4653f66d29d7115bb04ebd4f3/theories/Lambda/TypedFold.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2220117204248458}}
{"text": "From mathcomp Require Import\n     all_ssreflect\n     finmap.\n\nRequire Import Relations.\n\nFrom PoS_NSB Require Import\n     Network\n     Protocol\n     GlobalState\n     Blocks\n     Messages\n     MessageTuple\n     Parameters\n     BlockTree\n     LocalState\n     StateMonad.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** * Schedule \n      This file contains the semantics for an execution of the protocol.\n**)\n\nDefinition upd_local (p: Party) (l: LocalState) (N: GlobalState) : GlobalState :=\n  N[[state_map := setf (state_map N) p l ]].\n\n(** Handy functions for using the network functionality to broadcast\n    several messages. **)\nDefinition flood_msgs (msgs : Messages) (N : GlobalState) : GlobalState :=\n  foldr flood_msg N msgs.\n\nDefinition flood_msgs_adv (msgs : seq (Message * DelayMap)) (N : GlobalState) : GlobalState :=\n  foldr (fun ' (m , ϕ) => flood_msg_adv m ϕ) N msgs.\n\n(** Our development is parameterised by a map deciding the honesty of\n    parties. **)\nParameter CorruptionStatus : Party -> Honesty.\n\n(** The adversary is modelled as two functions: \n    1) Decides how the adversary acts when baking.\n    2) Decides how the adversary acts when recieving \n       messages. *)\nParameter AdversarialBake:\n  Slot ->\n  History ->\n  MessagePool ->\n  State AdversarialState (seq (Message * DelayMap)).\n\nParameter AdversarialRcv:\n  Messages ->\n  Slot ->\n  History ->\n  MessagePool ->\n  State AdversarialState (seq (Message * DelayMap)).\n\n(** We translate the map of honesty a boolean value. **)\nDefinition is_corrupt p : bool := CorruptionStatus p == Corrupt.\nDefinition is_honest p : bool := CorruptionStatus p == Honest.\n\n(** If the party is honest an honest step is taken with the correct\n    messages. Otherwise will the [AdversarialStep] function be called with\n    the correct inputs and the world updated accordingly to this.  **)\nDefinition party_bake_step_world (p : Party) (N : GlobalState) : GlobalState :=\n  if (state_map N).[? p] is Some l\n  then if ~~(is_corrupt p)\n       then let '(n_msgs, new_ls) := honest_bake (t_now N) l\n            in flood_msgs n_msgs (upd_local p new_ls N)\n       else let '(n_msgs, adv_state') := AdversarialBake (t_now N) (history N) (msg_buff N) (adv_state N)\n            in (flood_msgs_adv n_msgs N)[[adv_state := adv_state']]\n  else N.\n\n(** If the party is honest he calls the honest recieve functions.\n    Otherwise the [AdversarialRcv] function.  **)\nDefinition party_rcv_step_world (p : Party) (N : GlobalState) : GlobalState :=\n  if (state_map N).[? p] is Some l\n  then let '(msgs, N') := fetch_msgs p N in\n       if ~~(is_corrupt p)\n       then let '(_, new_ls) := honest_rcv msgs (t_now N') l\n            in (upd_local p new_ls N')\n       else let '(n_msgs, adv_state') := AdversarialRcv msgs (t_now N') (history N') (msg_buff N') (adv_state N')\n            in (flood_msgs_adv n_msgs N')[[adv_state := adv_state']]\n  else N.\n\nDefinition inc_round (N : GlobalState) : GlobalState :=\n  N[[t_now := S (t_now N)]].\n\n(** ** Definition: Related states **)\n\nReserved Notation \"A ⤳ B\" (at level 80, no associativity).\n\nNotation \"N '@' p\" := (progress N = p) (at level 20).\n\nInductive SingleStep: GlobalState -> GlobalState -> Prop :=\n(* Delivering messages to all parties *)\n| Deliver : forall N, N @ Ready -> N ⤳\n                 (foldr party_rcv_step_world N (exec_order N))[[progress := Delivered]]\n(* Executing all party concurrenctly *)\n| Bake : forall N, N @ Delivered -> N ⤳\n              (foldr party_bake_step_world N (exec_order N))[[progress := Baked]]\n(* When messages are delivered and  *)\n| NextRound : forall N, N @ Baked -> N ⤳ (inc_round (round_tick N))[[progress := Ready]]\n(* Permuting parties leads to related states *)\n| PermParties : forall N ps, perm_eq (exec_order N) ps -> N ⤳ N[[exec_order := ps]]\n(* Permuting message buffer leads to related states  *)\n| PermMsgs : forall N mb, perm_eq (msg_buff N) mb -> N ⤳ N[[msg_buff := mb]]\nwhere \"N ⤳ N'\" := (SingleStep N N').\n\n(** BigStep semantics are just the reflexive transitive closure of the\n    SingleStep relation **)\nDefinition BigStep (N N' : GlobalState) := clos_refl_trans_n1 GlobalState SingleStep N N'.\n\nNotation \"N '⇓' N'\" := (BigStep N N') (at level 20).\nNotation \"N '⇓[' s ']' N'\" := (N ⇓ N' /\\ (s + t_now N) = (t_now N')) (at level 20).\nNotation \"N '⇓^+' N'\" := (N ⇓ N' /\\ t_now N < t_now N') (at level 20).\n", "meta": {"author": "anonymous1446", "repo": "PoS-NSB", "sha": "c461c3d6a8fa364ecf87ef27a32fb746d1681ae3", "save_path": "github-repos/coq/anonymous1446-PoS-NSB", "path": "github-repos/coq/anonymous1446-PoS-NSB/PoS-NSB-c461c3d6a8fa364ecf87ef27a32fb746d1681ae3/Model/Schedule.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2220117204248458}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export sequents_tacs.\n(*Require Import rules_pertype2.*)\nRequire Export subst_tacs.\nRequire Export cequiv_tacs.\nRequire Export tactics2.\nRequire Export per_props_per.\nRequire Export rwper.\nRequire Export list. (* why *)\n\n\n(* begin hide *)\n\n\nLemma unfold_mk_iper_function_rel2 {o} :\n  forall A B : @NTerm o,\n    {va, vb, vf, vg, vx : NVar\n     $ mk_iper_function_rel A B\n       = mk_lam vf (mk_lam vg (mk_per_function_base va vb vf vg vx A B))\n     # (va, vb, vf, vg, vx) = newvars5 [A, B] }.\nProof.\n  apply unfold_mk_iper_function_rel.\nQed.\n\nLemma equality_in_iper_function {o} :\n  forall lib f g A B w s c,\n    @equality o lib f g (lsubstc (mk_iper_function A B) w s c)\n    -> {wa : wf_term A\n        , {wb : wf_term B\n        , {ca : cover_vars A s\n        , {cb : cover_vars B s\n        , let cA := lsubstc A wa s ca in\n          let cB := lsubstc B wb s cb in\n          type lib cA\n          # forall a a',\n              equality lib a a' cA\n              -> equality lib (mkc_apply f a) (mkc_apply g a') (mkc_apply cB a)\n                 # tequality lib (mkc_apply cB a) (mkc_apply cB a')}}}}.\nProof.\n  introv eq.\n\n  assert (wf_term A)\n    as wA by (dup w as w'; apply wf_term_mk_iper_function in w'; sp).\n  assert (wf_term B)\n    as wB by (dup w as w'; apply wf_term_mk_iper_function in w'; sp).\n\n  assert (cover_vars A s)\n    as cA by (dup c as c'; apply cover_vars_iper_function in c'; sp).\n  assert (cover_vars B s)\n    as cB by (dup c as c'; apply cover_vars_iper_function in c'; sp).\n\n  exists wA wB cA cB; cbv zeta.\n\n  unfold mk_iper_function in eq.\n  lsubst_tac.\n  rwpers.\n  generalize (unfold_mk_iper_function_rel2 A B); intro e; exrepnd.\n  apply newvars5_prop2 in e0; simpl in e0;\n  repeat (rw app_nil_r in e0); repeat (rw in_app_iff in e0);\n  repeat (rw not_over_or in e0); repnd.\n\n  revert dependent eq0.\n  revert dependent w1.\n  revert dependent c1.\n  rw e1; introv isper ty inh.\n  lsubst_tac.\n  repeat (betared; repeat substc_lsubstc_vars3; lsubst_tac; auto).\n  unfold mk_per_function_base in inh.\n  lsubst_tac.\n  unfold inhabited_type in inh; exrepnd.\n  rwpers.\n\n  dands.\n\n  generalize (inh0 mkc_axiom mkc_axiom); intro k.\n  autodimp k hyp; repnd.\n  rwpers; auto.\n  repeat substc_lsubstc_vars3; lsubst_tac.\n  rwpers.\n  generalize (k0 mkc_axiom mkc_axiom); intro j.\n  autodimp j hyp; repnd.\n  rwpers; auto.\n  repeat substc_lsubstc_vars3; lsubst_tac.\n  rwpers.\n\n  introv ea.\n  generalize (inh0 a a); clear inh0; intro k.\n  autodimp k hyp; repnd.\n  rwpers.\n  clear k.\n  repeat substc_lsubstc_vars3; lsubst_tac.\n  rwpers.\n  generalize (k0 a' a'); clear k0; intro eq.\n  autodimp eq hyp; repnd.\n  rwpers.\n  clear eq.\n  repeat substc_lsubstc_vars3; lsubst_tac.\n  rwpers.\n  generalize (eq0 mkc_axiom mkc_axiom); clear eq0; intro eq'.\n  autodimp eq' hyp; repnd.\n  rwpers.\n  clear eq'.\n  repeat substc_lsubstc_vars3; lsubst_tac.\n  apply equality_in_uand_implies in eq'0; exrepnd.\n  lsubst_tac.\n  rwpers; repnd; dands; auto.\n  apply inhabited_implies_tequality in eq'0.\n  rw @tequality_iff_mkc_tequality in eq'0; auto.\nQed.\n\nLemma tequality_mk_iper_function_implies {o} :\n  forall lib A B w s1 s2 c1 c2,\n    @tequality o lib (lsubstc (mk_iper_function A B) w s1 c1)\n              (lsubstc (mk_iper_function A B) w s2 c2)\n    -> {wa : wf_term A\n        , {wb : wf_term B\n        , {ca1 : cover_vars A s1\n        , {ca2 : cover_vars A s2\n        , {cb1 : cover_vars B s1\n        , {cb2 : cover_vars B s2\n        , let A1 := lsubstc A wa s1 ca1 in\n          let A2 := lsubstc A wa s2 ca2 in\n          let B1 := lsubstc B wb s1 cb1 in\n          let B2 := lsubstc B wb s2 cb2 in\n          tequality lib A1 A2\n          # forall a1 a2,\n              equality lib a1 a2 A1\n              -> tequality lib (mkc_apply B1 a1) (mkc_apply B2 a2)}}}}}}.\nProof.\n  introv teq.\n\n  assert (wf_term A)\n    as wA by (dup w as w'; apply wf_term_mk_iper_function in w'; sp).\n  assert (wf_term B)\n    as wB by (dup w as w'; apply wf_term_mk_iper_function in w'; sp).\n\n  assert (cover_vars A s1)\n    as cA1 by (dup c1 as c'; apply cover_vars_iper_function in c'; sp).\n  assert (cover_vars B s1)\n    as cB1 by (dup c1 as c'; apply cover_vars_iper_function in c'; sp).\n  assert (cover_vars A s2)\n    as cA2 by (dup c2 as c'; apply cover_vars_iper_function in c'; sp).\n  assert (cover_vars B s2)\n    as cB2 by (dup c2 as c'; apply cover_vars_iper_function in c'; sp).\n\n  exists wA wB cA1 cA2 cB1 cB2; cbv zeta.\n\n  unfold mk_iper_function in teq.\n  lsubst_tac.\n  rwpers.\n  generalize (unfold_mk_iper_function_rel2 A B); intro e; exrepnd.\n  apply newvars5_prop2 in e0; simpl in e0;\n  repeat (rw app_nil_r in e0); repeat (rw in_app_iff in e0);\n  repeat (rw not_over_or in e0); repnd.\n\n  revert dependent teq0.\n  revert dependent w1.\n  revert dependent c0.\n  revert dependent c3.\n  rw e1; introv isper teq.\n  lsubst_tac.\n\n  generalize (teq mkc_axiom mkc_axiom); clear teq; intro teq.\n  repeat (betared; repeat substc_lsubstc_vars3; lsubst_tac; auto).\n  unfold mk_per_function_base in teq.\n  lsubst_tac.\n  rwpers.\n\n  dands.\n\n  generalize (teq mkc_axiom mkc_axiom); clear teq; intro teq.\n  autodimp teq hyp.\n  rwpers.\n  repeat substc_lsubstc_vars3; lsubst_tac; auto; rwpers.\n  generalize (teq mkc_axiom mkc_axiom); clear teq; intro teq.\n  autodimp teq hyp.\n  rwpers.\n  repeat substc_lsubstc_vars3; lsubst_tac; auto; rwpers; repnd; auto.\n\n  introv ea.\n  generalize (teq a1 a1); clear teq; intro teq.\n  autodimp teq hyp.\n  rwpers.\n  repeat substc_lsubstc_vars3; lsubst_tac; auto; rwpers.\n  generalize (teq a2 a2); clear teq; intro teq.\n  autodimp teq hyp.\n  rwpers.\n  repeat substc_lsubstc_vars3; lsubst_tac; auto; rwpers; repnd; auto.\n  generalize (teq mkc_axiom mkc_axiom); clear teq; intro teq.\n  autodimp teq hyp.\n  rwpers.\n  repeat substc_lsubstc_vars3.\n  apply tequality_uand_implies in teq; exrepnd.\n  clear teq3.\n  lsubst_tac.\n  rw @tequality_mkc_tequality in teq4; repnd.\n  apply tequality_trans with (t2 := mkc_apply (lsubstc B wB s1 cB1) a2); auto.\nQed.\n\n\n(* end hide *)\n\n\n(* [29] ============ IPER-FUNCTION ELIMINATION ============ *)\n\n  (*\n   H, f : iper-function(A,B), J |- C ext e[z\\axiom]\n\n     By iperFunctionElimination s y z\n\n     H, f : iper-function(A,B), J |- a in A\n     H, f : iper-function(A,B), J, z : (f a) in (B a) |- C ext e\n *)\nDefinition rule_iper_function_elimination {o}\n           (A B C a e : NTerm)\n           (f z : NVar)\n           (H J : @barehypotheses o) :=\n  mk_rule\n    (mk_bseq\n       (snoc H (mk_hyp f (mk_iper_function A B)) ++ J)\n       (mk_concl C (subst e z mk_axiom)))\n    [ mk_bseq\n        (snoc H (mk_hyp f (mk_iper_function A B)) ++ J)\n        (mk_conclax (mk_member a A)),\n      mk_bseq\n        (snoc (snoc H (mk_hyp f (mk_iper_function A B)) ++ J)\n              (mk_hyp z (mk_member (mk_apply (mk_var f) a) (mk_apply B a))))\n        (mk_concl C e)\n    ]\n    [sarg_term a, sarg_var z].\n\nLemma rule_iper_function_elimination_true {o} :\n  forall lib (A B C a e : NTerm),\n  forall f z : NVar,\n  forall H J : @barehypotheses o,\n    rule_true lib (rule_iper_function_elimination\n                 A B C a e\n                 f z\n                 H J).\nProof.\n  unfold rule_iper_function_elimination, rule_true, closed_type_baresequent, closed_extract_baresequent; simpl.\n  intros.\n\n  (* We prove the well-formedness of things *)\n  destseq; allsimpl.\n  dLin_hyp; exrepnd.\n  rename Hyp0 into hyp1.\n  rename Hyp1 into hyp2.\n  destseq; allsimpl; proof_irr; GC.\n\n  assert (covered\n            (subst e z mk_axiom)\n            (nh_vars_hyps (snoc H (mk_hyp f (mk_iper_function A B)) ++ J))) as cv.\n  (* begin proof of assert *)\n  clear hyp1 hyp2.\n  dwfseq.\n  intros.\n  generalize (isprogram_lsubst2 e [(z,mk_axiom)]); simpl; intro k.\n  dest_imp k hyp; sp; cpx.\n  unfold subst in X; rw k in X; clear k.\n  rw in_remove_nvars in X; simpl in X; sp.\n  apply not_over_or in X; sp.\n  generalize (ce x); sp.\n  allrw in_app_iff; allrw in_snoc; sp.\n  allrw in_app_iff; allrw in_snoc; sp.\n  (* end proof of assert *)\n\n  exists cv.\n\n  (* We prove some simple facts on our sequents *)\n  assert (!LIn f (vars_hyps H)\n          # !LIn f (vars_hyps J)\n          # !LIn z (vars_hyps H)\n          # !LIn z (vars_hyps J)\n          # !(z = f)\n          # !LIn f (free_vars (mk_iper_function_rel A B))\n          # disjoint (free_vars (mk_iper_function_rel A B)) (vars_hyps J)\n          # !LIn z (free_vars C)) as vhyps.\n\n  clear hyp1 hyp2.\n  remember (mk_iper_function A B) as pf.\n  remember (mk_iper_function_rel A B) as pfr.\n  dwfseq.\n  subst.\n  allrw @free_vars_mk_iper_function.\n  allrw @free_vars_iper_function_rel_eq.\n  sp;\n    try (complete (allunfold @disjoint; introv k; discover; allrw in_app_iff; sp));\n    try (complete (discover; repeat (first [ progress (allrw in_app_iff) | progress (allrw in_snoc) ]); sp));\n    try (complete (unfold disjoint; unfold disjoint in wfh11; introv i; discover; sp)).\n\n  destruct vhyps as [ nifH vhyps ].\n  destruct vhyps as [ nifJ vhyps ].\n  destruct vhyps as [ nizH vhyps ].\n  destruct vhyps as [ nizJ vhyps ].\n  destruct vhyps as [ nezf vhyps ].\n  destruct vhyps as [ nifFR vhyps ].\n  destruct vhyps as [ disjFRJ nizC ].\n  (* done with proving these simple facts *)\n\n\n  (* The following is used by lsubst_tac to clean some substitutions *)\n  assert (!LIn f (free_vars (mk_iper_function_rel A B))) as nffrel.\n  (* begin proof of assert *)\n  clear hyp1 hyp2.\n  allapply @vswf_hypotheses_nil_implies.\n  rw @wf_hypotheses_app in wfh; destruct wfh as [wfha wfhb].\n  rw @wf_hypotheses_snoc in wfha; destruct wfha as [isp wfha].\n  destruct wfha as [ni wfh]; simphyps.\n  rw @isprog_vars_eq in isp; destruct isp as [sv ntwf].\n  intro k; rw subvars_prop in sv.\n  rw <- @free_vars_mk_iper_function in k.\n  apply sv in k; sp.\n  (* end proof of assert *)\n\n  assert (!LIn z (free_vars (subst e z mk_axiom))) as nizs.\n  (* begin proof of assert *)\n  unfold subst.\n  rw @isprogram_lsubst2; try (complete (simpl; sp; cpx)).\n  rw in_remove_nvars; simpl; sp.\n  (* end proof of assert *)\n\n  assert (disjoint (free_vars A) (vars_hyps J))\n    as disjAJ\n      by (allrw @free_vars_iper_function_rel_eq; allrw disjoint_app_l; sp).\n\n  assert (disjoint (free_vars B) (vars_hyps J))\n    as disjBJ\n      by (allrw @free_vars_iper_function_rel_eq; allrw disjoint_app_l; sp).\n\n  assert (!LIn f (free_vars A))\n    as nifA\n      by (allrw @free_vars_iper_function_rel_eq; allrw in_app_iff; sp).\n\n  assert (!LIn f (free_vars B))\n    as nifB\n      by (allrw @free_vars_iper_function_rel_eq; allrw in_app_iff; sp).\n\n  vr_seq_true.\n\n  dup sim as simapp.\n  rw @similarity_app in sim; simpl in sim; exrepnd; subst; cpx.\n  rw @similarity_snoc in sim5; simpl in sim5; exrepnd; subst; cpx.\n\n  apply equality_in_iper_function in sim2; exrepnd; cbv zeta in sim2; repnd.\n\n  vr_seq_true in hyp2.\n  generalize (hyp2 (snoc (snoc s1a0 (f, t1) ++ s1b) (z, mkc_axiom))\n                   (snoc (snoc s2a0 (f, t2) ++ s2b) (z, mkc_axiom)));\n    clear hyp2; intros hyp2.\n  repeat (autodimp hyp2 h); exrepnd.\n\n  (* hyps_functionality *)\n\n  generalize (hyps_functionality_snoc\n                lib (snoc H (mk_hyp f (mk_iper_function A B)) ++ J)\n                (mk_hyp z (mk_member (mk_apply (mk_var f) a) (mk_apply B a)))\n                (snoc s1a0 (f, t1) ++ s1b)\n                mkc_axiom); simpl; intro k.\n  apply k; try (complete auto); clear k.\n  introv eq sim; GC; lsubst_tac.\n  rw @tequality_mkc_member.\n  apply equality_refl in eq.\n  rw <- @member_member_iff in eq.\n\n  vr_seq_true in hyp1.\n  generalize (hyp1 (snoc s1a0 (f, t1) ++ s1b) s'); clear hyp1; intros hyp1.\n  repeat (autodimp hyp1 h); exrepnd.\n  lsubst_tac.\n  rw @member_eq in hyp1.\n  rw <- @member_member_iff in hyp1.\n  rw @tequality_mkc_member in hyp0; repnd.\n\n  assert (equality lib (lsubstc a w2 (snoc s1a0 (f, t1) ++ s1b) c2)\n                   (lsubstc a w2 s' c4)\n                   (lsubstc A wa s1a0 ca)) as eqa.\n  sp.\n  unfold member in hyp1.\n  spcast; apply @equality_respects_cequivc_right with (t2 := lsubstc a w2 (snoc s1a0 (f, t1) ++ s1b) c2); sp.\n  clear hyp0.\n\n  applydup sim2 in eqa.\n\n  duplicate sim as sim'.\n  apply eqh in sim'.\n\n  rw @eq_hyps_app in sim'; simpl in sim'; exrepnd; subst; cpx.\n  apply app_split in sim'0; repnd; allrw length_snoc;\n  try (complete (allrw; sp)); subst; cpx.\n\n  rw @eq_hyps_snoc in sim'5; simpl in sim'5; exrepnd; subst; cpx.\n  lsubst_tac.\n\n  apply tequality_mk_iper_function_implies in sim'0; exrepnd;\n  cbv zeta in sim'0; repnd; proof_irr; GC.\n\n  applydup sim'0 in eqa as teq.\n\n  split; try (complete auto).\n\n  rw @similarity_app in sim; simpl in sim; exrepnd; subst; inj.\n  allrw length_snoc.\n  apply app_split in sim5; repnd; allrw length_snoc; try (complete (allrw; sp)); subst; inj.\n  apply app_split in sim8; repnd; allrw length_snoc; try (complete (allrw; sp)); subst; inj.\n  allrw length_snoc; inj; GC.\n  rw @similarity_snoc in sim11; simpl in sim11; exrepnd; subst; inj.\n  apply equality_in_iper_function in sim8; exrepnd; cbv zeta in sim8; repnd; proof_irr; GC.\n  applydup sim8 in eqa as eqf; repnd.\n\n  split; try (complete (left; auto)).\n\n  split; intro m; try (complete auto).\n  apply equality_sym in eqf0.\n  apply equality_refl in eqf0.\n  allunfold @member.\n  apply @tequality_preserving_equality with (A := mkc_apply (lsubstc B wb s1a0 cb)\n                                                           (lsubstc a w2 (snoc s1a0 (f, t1) ++ s1b) c2)); sp.\n\n  (* similarity *)\n\n  assert (wf_term (mk_member (mk_apply (mk_var f) a) (mk_apply B a))) as wm.\n  clear hyp1.\n  apply wf_member; sp; try (apply wf_apply; sp); apply wf_member_iff in wfct1; sp.\n\n  assert (cover_vars (mk_member (mk_apply (mk_var f) a) (mk_apply B a))\n                     (snoc s1a0 (f, t1) ++ s1b)) as cm.\n  (* end proof of assert *)\n  apply cover_vars_member; sp; apply cover_vars_apply; sp.\n  apply cover_vars_var.\n  rw @dom_csub_app; rw @dom_csub_snoc; rw in_app_iff; rw in_snoc; simpl; sp.\n  dup ct0 as cvm.\n  apply covered_iff_cover_vars with (s := snoc s1a0 (f, t1) ++ s1b) in cvm.\n  rw @cover_vars_member in cvm; sp.\n  rw @dom_csub_app; rw @dom_csub_snoc; rw @vars_hyps_app; rw @vars_hyps_snoc; simpl.\n  allapply @similarity_dom; repnd; allrw; rw @vars_hyps_substitute_hyps; sp.\n  apply cover_vars_app_weak; apply cover_vars_snoc_weak; auto.\n  dup ct0 as cvm.\n  apply covered_iff_cover_vars with (s := snoc s1a0 (f, t1) ++ s1b) in cvm.\n  rw @cover_vars_member in cvm; sp.\n  rw @dom_csub_app; rw @dom_csub_snoc; rw @vars_hyps_app; rw @vars_hyps_snoc; simpl.\n  allapply @similarity_dom; repnd; allrw; rw @vars_hyps_substitute_hyps; sp.\n  (* end proof of assert *)\n\n  rw @similarity_snoc; simpl.\n  exists (snoc s1a0 (f, t1) ++ s1b)\n         (snoc s2a0 (f, t2) ++ s2b)\n         (@mkc_axiom o) (@mkc_axiom o)\n         wm cm; sp.\n  lsubst_tac.\n  rw @member_eq.\n  rw <- @member_member_iff.\n\n  vr_seq_true in hyp1.\n  generalize (hyp1 (snoc s1a0 (f, t1) ++ s1b)\n                   (snoc s2a0 (f, t2) ++ s2b));\n    clear hyp1; intros hyp1.\n  repeat (autodimp hyp1 h); exrepnd.\n  lsubst_tac.\n  rw @member_eq in hyp1.\n  rw <- @member_member_iff in hyp1.\n  rw @tequality_mkc_member in hyp0; repnd.\n  unfold member in hyp1.\n  apply sim2 in hyp1; repnd; auto.\n  apply equality_refl in hyp4; auto.\n\n  (* conclusion *)\n\n  lsubst_tac; sp.\n\n  assert (lsubstc e wfce0 (snoc (snoc s1a0 (f, t1) ++ s1b) (z, mkc_axiom)) pt0\n          = lsubstc (subst e z mk_axiom) wfce (snoc s1a0 (f, t1) ++ s1b) pt1) as eq1.\n  apply lsubstc_eq_if_csubst.\n  rw <- @csubst_swap.\n  rw cons_as_app.\n  rw <- @csubst_app.\n  unfold csubst, subst; simpl; sp.\n  rw @dom_csub_app; rw @dom_csub_snoc; simpl; rw in_app_iff; rw in_snoc.\n  insub.\n\n  assert (lsubstc e wfce0 (snoc (snoc s2a0 (f, t2) ++ s2b) (z, mkc_axiom)) pt3\n          = lsubstc (subst e z mk_axiom) wfce (snoc s2a0 (f, t2) ++ s2b) pt2) as eq2.\n  apply lsubstc_eq_if_csubst.\n  rw <- @csubst_swap.\n  rw cons_as_app.\n  rw <- @csubst_app.\n  unfold csubst, subst; simpl; sp.\n  rw @dom_csub_app; rw @dom_csub_snoc; simpl; rw in_app_iff; rw in_snoc.\n  insub.\n\n  rw eq1 in hyp2; rw eq2 in hyp2; sp.\nQed.\n\n\n(* begin hide *)\n", "meta": {"author": "coq-contribs", "repo": "intuitionistic-nuprl", "sha": "6279ed83244dc4aec2e23ffb4c87e3f10a50326d", "save_path": "github-repos/coq/coq-contribs-intuitionistic-nuprl", "path": "github-repos/coq/coq-contribs-intuitionistic-nuprl/intuitionistic-nuprl-6279ed83244dc4aec2e23ffb4c87e3f10a50326d/rules_iper_function.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2220117204248458}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** RTL function inlining *)\n\nRequire Import Coqlib.\nRequire Import Wfsimpl.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\n\n(** ** Environment of inlinable functions *)\n\n(** We maintain a mapping from function names to their definitions.\n  In this mapping, we only include internal functions that are eligible for\n  inlining, as determined by the external heuristic\n  [should_inline]. *)\n\nDefinition funenv : Type := PTree.t function.\n\nDefinition size_fenv (fenv: funenv) := PTree_Properties.cardinal fenv.\n\nParameter should_inline: ident -> function -> bool.\n\n(** [CompCertX:test-compcert-void-symbols] We now allow a symbol to be\nassociated to no variable or function. *)\n\nDefinition add_globdef (fenv: funenv) (idg: ident * option (globdef fundef unit)) : funenv :=\n  match idg with\n  | (id, Some (Gfun (Internal f))) =>\n      if should_inline id f\n      then PTree.set id f fenv\n      else PTree.remove id fenv\n  | (id, _) =>\n      PTree.remove id fenv\n  end.\n\nDefinition funenv_program (p: program) : funenv :=\n  List.fold_left add_globdef p.(prog_defs) (PTree.empty function).\n\n(** State monad *)\n\n(** To construct incrementally the CFG of a function after inlining,\n  we use a state monad similar to that used in module [RTLgen].\n  It records the current state of the CFG, plus counters to generate\n  fresh pseudo-registers and fresh CFG nodes.  It also records the\n  stack size needed for the inlined function. *)\n\nRecord state : Type := mkstate {\n  st_nextreg: positive;                 (**r last used pseudo-register *)\n  st_nextnode: positive;                (**r last used CFG node *)\n  st_code: code;                        (**r current CFG  *)\n  st_stksize: Z                         (**r current stack size *)\n}.\n\n(** Monotone evolution of the state. *)\n\nInductive sincr (s1 s2: state) : Prop :=\n  Sincr (NEXTREG: Ple s1.(st_nextreg) s2.(st_nextreg))\n        (NEXTNODE: Ple s1.(st_nextnode) s2.(st_nextnode))\n        (STKSIZE: s1.(st_stksize) <= s2.(st_stksize)).\n\nRemark sincr_refl: forall s, sincr s s.\nProof.\n  intros; constructor; xomega.\nQed.\n\nLemma sincr_trans: forall s1 s2 s3, sincr s1 s2 -> sincr s2 s3 -> sincr s1 s3.\nProof.\n  intros. inv H; inv H0. constructor; xomega.\nQed.\n\n(** Dependently-typed state monad, ensuring that the final state is\n  greater or equal (in the sense of predicate [sincr] above) than\n  the initial state. *)\n\nInductive res {A: Type} {s: state}: Type := R (x: A) (s': state) (I: sincr s s').\n\nDefinition mon (A: Type) : Type := forall (s: state), @res A s.\n\n(** Operations on this monad. *)\n\nDefinition ret {A: Type} (x: A): mon A :=\n  fun s => R x s (sincr_refl s).\n\nDefinition bind {A B: Type} (x: mon A) (f: A -> mon B): mon B :=\n  fun s1 => match x s1 with R vx s2 I1 =>\n              match f vx s2 with R vy s3 I2 =>\n                R vy s3 (sincr_trans s1 s2 s3 I1 I2)\n              end\n            end.\n\nNotation \"'do' X <- A ; B\" := (bind A (fun X => B))\n   (at level 200, X ident, A at level 100, B at level 200).\n\nDefinition initstate :=\n  mkstate 1%positive 1%positive (PTree.empty instruction) 0.\n\nProgram Definition set_instr (pc: node) (i: instruction): mon unit :=\n  fun s => \n    R tt\n      (mkstate s.(st_nextreg) s.(st_nextnode) (PTree.set pc i s.(st_code)) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition add_instr (i: instruction): mon node :=\n  fun s =>\n    let pc := s.(st_nextnode) in\n    R pc\n      (mkstate s.(st_nextreg) (Psucc pc) (PTree.set pc i s.(st_code)) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition reserve_nodes (numnodes: positive): mon positive :=\n  fun s =>\n    R s.(st_nextnode)\n      (mkstate s.(st_nextreg) (Pplus s.(st_nextnode) numnodes) s.(st_code) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition reserve_regs (numregs: positive): mon positive :=\n  fun s =>\n    R s.(st_nextreg)\n      (mkstate (Pplus s.(st_nextreg) numregs) s.(st_nextnode) s.(st_code) s.(st_stksize))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition request_stack (sz: Z): mon unit :=\n  fun s => \n    R tt\n      (mkstate s.(st_nextreg) s.(st_nextnode) s.(st_code) (Zmax s.(st_stksize) sz))\n      _.\nNext Obligation.\n  intros; constructor; simpl; xomega.\nQed.\n\nProgram Definition ptree_mfold {A: Type} (f: positive -> A -> mon unit) (t: PTree.t A): mon unit :=\n  fun s =>\n    R tt \n      (PTree.fold (fun s1 k v => match f k v s1 return _ with R _ s2 _ => s2 end) t s)\n      _.\nNext Obligation.\n  apply PTree_Properties.fold_rec.\n  auto.\n  apply sincr_refl.\n  intros. destruct (f k v a). eapply sincr_trans; eauto. \nQed.\n\n(** ** Inlining contexts *)\n\n(** A context describes how to insert the CFG for a source function into\n  the CFG for the function after inlining:\n- a source instruction at PC [n] is relocated to PC [n + ctx.(dpc)];\n- all pseudo-registers of this instruction are shifted by [ctx.(dreg)];\n- all stack references are shifted by [ctx.(dstk)];\n- \"return\" instructions are transformed into \"return\" or \"move\" instructions\n  as governed by [ctx.(retinfo)].\n*)\n\nRecord context: Type := mkcontext {\n  dpc: positive;                        (**r offset for PCs *)\n  dreg: positive;                       (**r offset for pseudo-regs *)\n  dstk: Z;                              (**r offset for stack references *)\n  mreg: positive;                       (**r max pseudo-reg number *)\n  mstk: Z;                              (**r original stack block size *)\n  retinfo: option(node * reg)           (**r where to branch on return *)\n                                        (**r and deposit return value *)\n}.\n\n(** The following functions \"shift\" (relocate) PCs, registers, operations, etc. *)\n\nDefinition shiftpos (p amount: positive) := Ppred (Pplus p amount).\n\nDefinition spc (ctx: context) (pc: node) := shiftpos pc ctx.(dpc).\n\nDefinition sreg (ctx: context) (r: reg) := shiftpos r ctx.(dreg).\n\nDefinition sregs (ctx: context) (rl: list reg) := List.map (sreg ctx) rl.\n\nDefinition sros (ctx: context) (ros: reg + ident) := sum_left_map (sreg ctx) ros.\n\nDefinition sop (ctx: context) (op: operation) :=\n  shift_stack_operation (Int.repr ctx.(dstk)) op.\n\nDefinition saddr (ctx: context) (addr: addressing) :=\n  shift_stack_addressing (Int.repr ctx.(dstk)) addr.\n\n(** The initial context, used to copy the CFG of a toplevel function. *)\n\nDefinition initcontext (dpc dreg nreg: positive) (sz: Z) :=\n  {| dpc := dpc;\n     dreg := dreg;\n     dstk := 0;\n     mreg := nreg;\n     mstk := Zmax sz 0;\n     retinfo := None |}.\n\n(** The context used to inline a call to another function. *)\n\nDefinition min_alignment (sz: Z) :=\n  if zle sz 1 then 1\n  else if zle sz 2 then 2\n  else if zle sz 4 then 4 else 8.\n\nDefinition callcontext (ctx: context)\n                      (dpc dreg nreg: positive) (sz: Z)\n                      (retpc: node) (retreg: reg) :=\n  {| dpc := dpc;\n     dreg := dreg;\n     dstk := align (ctx.(dstk) + ctx.(mstk)) (min_alignment sz);\n     mreg := nreg;\n     mstk := Zmax sz 0;\n     retinfo := Some (spc ctx retpc, sreg ctx retreg) |}.\n\n(** The context used to inline a tail call to another function. *)\n\nDefinition tailcontext (ctx: context) (dpc dreg nreg: positive) (sz: Z) :=\n  {| dpc := dpc;\n     dreg := dreg;\n     dstk := align ctx.(dstk) (min_alignment sz);\n     mreg := nreg;\n     mstk := Zmax sz 0;\n     retinfo := ctx.(retinfo) |}.\n\n(** ** Recursive expansion and copying of a CFG *)\n\n(** Insert \"move\" instructions to copy the arguments of an inlined\n    function into its parameters. *)\n\nFixpoint add_moves (srcs dsts: list reg) (succ: node): mon node :=\n  match srcs, dsts with\n  | s1 :: sl, d1 :: dl =>\n      do n <- add_instr (Iop Omove (s1 :: nil) d1 succ);\n      add_moves sl dl n\n  | _, _ =>\n      ret succ\n  end.\n\n(** To prevent infinite inlining of a recursive function, when we\n  inline the body of a function [f], this function is removed from the\n  environment of inlinable functions and therefore becomes ineligible\n  for inlining.  This decreases the size (number of entries) of the\n  environment and guarantees termination.  Inlining is, therefore,\n  presented as a well-founded recursion over the size of the environment. *)\n\nSection EXPAND_CFG.\n\nVariable fenv: funenv.\n\n(** The [rec] parameter is the recursor: [rec fenv' P ctx f] copies \n  the body of function [f], with inline expansion within, as governed\n  by context [ctx].  It can only be called for function environments\n  [fenv'] strictly smaller than the current environment [fenv]. *)\n\nVariable rec: forall fenv', (size_fenv fenv' < size_fenv fenv)%nat -> context -> function -> mon unit.\n\n(** Given a register-or-symbol [ros], can we inline the corresponding call? *)\n\nInductive inline_decision (ros: reg + ident) : Type :=\n  | Cannot_inline\n  | Can_inline (id: ident) (f: function) (P: ros = inr reg id) (Q: fenv!id = Some f).\n\nProgram Definition can_inline (ros: reg + ident): inline_decision ros :=\n  match ros with\n  | inl r => Cannot_inline _\n  | inr id => match fenv!id with Some f => Can_inline _ id f _ _ | None => Cannot_inline _ end\n  end.\n\n(** Inlining of a call to function [f].  An appropriate context is\n  created, then the CFG of [f] is recursively copied, then moves\n  are inserted to copy the arguments of the call to the parameters of [f]. *)\n\nDefinition inline_function (ctx: context) (id: ident) (f: function)\n                           (P: PTree.get id fenv = Some f)\n                           (args: list reg)\n                           (retpc: node) (retreg: reg) : mon node :=\n  let npc := max_pc_function f in\n  let nreg := max_reg_function f in\n  do dpc <- reserve_nodes npc;\n  do dreg <- reserve_regs nreg;\n  let ctx' := callcontext ctx dpc dreg nreg f.(fn_stacksize) retpc retreg in \n  do x <- rec (PTree.remove id fenv) (PTree_Properties.cardinal_remove P) ctx' f;\n  add_moves (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)).\n\n(** Inlining of a tail call to function [f].  Similar to [inline_function],\n  but the new context is different. *)\n\nDefinition inline_tail_function (ctx: context) (id: ident) (f: function)\n                               (P: PTree.get id fenv = Some f)\n                               (args: list reg): mon node :=\n  let npc := max_pc_function f in\n  let nreg := max_reg_function f in\n  do dpc <- reserve_nodes npc;\n  do dreg <- reserve_regs nreg;\n  let ctx' := tailcontext ctx dpc dreg nreg f.(fn_stacksize) in \n  do x <- rec (PTree.remove id fenv) (PTree_Properties.cardinal_remove P) ctx' f;\n  add_moves (sregs ctx args) (sregs ctx' f.(fn_params)) (spc ctx' f.(fn_entrypoint)).\n\n(** The instruction generated for a [Ireturn] instruction found in an\n  inlined function body. *)\n\nDefinition inline_return (ctx: context) (or: option reg) (retinfo: node * reg) :=\n  match retinfo, or with\n  | (retpc, retreg), Some r => Iop Omove (sreg ctx r :: nil) retreg retpc\n  | (retpc, retreg), None   => Inop retpc\n  end.\n\n(** Expansion and copying of an instruction.  For most instructions,\n  its registers and successor PC are shifted as per the context [ctx],\n  then the instruction is inserted in the final CFG at its final position\n  [spc ctx pc].  \n\n  [Icall] instructions are either replaced by a \"goto\" to the expansion\n  of the called function, or shifted as described above.\n\n  [Itailcall] instructions are similar, with one additional case.  If\n  the [Itailcall] occurs in the body of an inlined function, and\n  cannot be inlined itself, it must be turned into an [Icall]\n  instruction that branches to the return point of the inlined\n  function.\n\n  Finally, [Ireturn] instructions within an inlined function are\n  turned into a \"move\" or \"goto\" that stores the result, if any,\n  into the destination register, then branches back to the successor\n  of the inlined call. *)\n\nDefinition expand_instr (ctx: context) (pc: node) (i: instruction): mon unit :=\n  match i with\n  | Inop s =>\n      set_instr (spc ctx pc) (Inop (spc ctx s))\n  | Iop op args res s =>\n      set_instr (spc ctx pc)\n                (Iop (sop ctx op) (sregs ctx args) (sreg ctx res) (spc ctx s))\n  | Iload chunk addr args dst s =>\n      set_instr (spc ctx pc)\n                (Iload chunk (saddr ctx addr) (sregs ctx args) (sreg ctx dst) (spc ctx s))\n  | Istore chunk addr args src s =>\n      set_instr (spc ctx pc)\n                (Istore chunk (saddr ctx addr) (sregs ctx args) (sreg ctx src) (spc ctx s))\n  | Icall sg ros args res s =>\n      match can_inline ros with\n      | Cannot_inline =>\n          set_instr (spc ctx pc)\n                    (Icall sg (sros ctx ros) (sregs ctx args) (sreg ctx res) (spc ctx s))\n      | Can_inline id f P Q =>\n          do n <- inline_function ctx id f Q args s res;\n          set_instr (spc ctx pc) (Inop n)\n      end\n  | Itailcall sg ros args =>\n      match can_inline ros with\n      | Cannot_inline =>\n          match ctx.(retinfo) with\n          | None =>\n              set_instr (spc ctx pc)\n                        (Itailcall sg (sros ctx ros) (sregs ctx args))\n          | Some(rpc, rreg) =>\n              set_instr (spc ctx pc)\n                        (Icall sg (sros ctx ros) (sregs ctx args) rreg rpc)\n          end\n      | Can_inline id f P Q =>\n          do n <- inline_tail_function ctx id f Q args;\n          set_instr (spc ctx pc) (Inop n)\n      end          \n  | Ibuiltin ef args res s =>\n      set_instr (spc ctx pc)\n                (Ibuiltin ef (sregs ctx args) (sreg ctx res) (spc ctx s))\n  | Icond cond args s1 s2 =>\n      set_instr (spc ctx pc)\n                (Icond cond (sregs ctx args) (spc ctx s1) (spc ctx s2))\n  | Ijumptable r tbl =>\n      set_instr (spc ctx pc)\n                (Ijumptable (sreg ctx r) (List.map (spc ctx) tbl))\n  | Ireturn or =>\n      match ctx.(retinfo) with\n      | None =>\n          set_instr (spc ctx pc) (Ireturn (option_map (sreg ctx) or))\n      | Some rinfo =>\n          set_instr (spc ctx pc) (inline_return ctx or rinfo)\n      end\n  end.\n\n(** The expansion of a function [f] iteratively expands all its\n  instructions, after recording how much stack it needs. *)\n\nDefinition expand_cfg_rec (ctx: context) (f: function): mon unit :=\n  do x <- request_stack (ctx.(dstk) + ctx.(mstk));\n  ptree_mfold (expand_instr ctx) f.(fn_code).\n\nEnd EXPAND_CFG.\n\n(** Here we \"tie the knot\" of the recursion, taking the fixpoint\n  of [expand_cfg_rec]. *)\n\nDefinition expand_cfg := Fixm size_fenv expand_cfg_rec.\n\n(** Start of the recursion: copy and inline function [f] in the\n  initial context. *)\n\nDefinition expand_function (fenv: funenv) (f: function): mon context :=\n  let npc := max_pc_function f in\n  let nreg := max_reg_function f in\n  do dpc <- reserve_nodes npc;\n  do dreg <- reserve_regs nreg;\n  let ctx := initcontext dpc dreg nreg f.(fn_stacksize) in \n  do x <- expand_cfg fenv ctx f;\n  ret ctx.\n\n(** ** Inlining in functions and whole programs. *)\n\nLocal Open Scope string_scope.\n\n(** Inlining can increase the size of the function's stack block.  We must\n  make sure that the new size does not exceed [Int.max_unsigned], otherwise\n  address computations within the stack would overflow and produce incorrect\n  results. *)\n\nDefinition transf_function (fenv: funenv) (f: function) : Errors.res function :=\n  let '(R ctx s _) := expand_function fenv f initstate in\n  if zlt s.(st_stksize) Int.max_unsigned then\n    OK (mkfunction f.(fn_sig) \n                   (sregs ctx f.(fn_params))\n                   s.(st_stksize)\n                   s.(st_code)\n                   (spc ctx f.(fn_entrypoint)))\n  else\n    Error(msg \"Inlining: stack too big\").\n\nDefinition transf_fundef (fenv: funenv) (fd: fundef) : Errors.res fundef :=\n  AST.transf_partial_fundef (transf_function fenv) fd.\n\nDefinition transf_program (p: program): Errors.res program :=\n  let fenv := funenv_program p in\n  AST.transform_partial_program (transf_fundef fenv) p.\n\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/compcert/backend/Inlining.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.22201172042484577}}
{"text": "(** ** Memories equal up to alpha-renaming *)\n\nRequire Import compcert.lib.Axioms.\nRequire Import concurrency.sepcomp. Import SepComp.\nRequire Import sepcomp.val_casted.\n\nRequire Import concurrency.pos.\n\nRequire Import compcert.lib.Coqlib.\nRequire Import Coq.Program.Program.\nFrom mathcomp.ssreflect Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\n(*NOTE: because of redefinition of [val], these imports must appear\n  after Ssreflect eqtype.*)\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Values. (*for val*)\n(* Require Import compcert.common.Globalenvs. *)\nRequire Import compcert.common.Memory.\nRequire Import concurrency.memory_lemmas.\n(* Require Import compcert.common.Events. *)\nRequire Import compcert.lib.Integers.\n\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import concurrency.threads_lemmas.\nRequire Import concurrency.permissions.\nRequire Import concurrency.dry_context.\nRequire Import concurrency.semantics.\n\n(** ** Block renamings*)\nModule Renamings.\nDefinition memren := block -> option block.\n\nDefinition ren_incr f1 f2 :=\nforall (b b' : block),\n  f1 b = Some b' -> f2 b = Some b'.\n\nDefinition ren_separated (f f' : memren) m1 m2 :=\nforall (b1 b2 : block),\nf b1 = None ->\nf' b1 = Some b2 ->\n~ Mem.valid_block m1 b1 /\\ ~ Mem.valid_block m2 b2.\n\nDefinition ren_domain_incr (f1 f2: memren) :=\n  forall b,\n    f1 b -> f2 b.\n\n(** Defining the domain of a renaming with respect to a memory*)\nDefinition domain_memren (f: memren) m :=\n  forall b, Mem.valid_block m b <-> isSome (f b).\n\nLemma restrPermMap_domain:\n  forall f m p (Hlt: permMapLt p (getMaxPerm m)),\n    domain_memren f m <-> domain_memren f (restrPermMap Hlt).\nProof.\n  intros.\n  unfold domain_memren.\n  split; intros; specialize (H b);\n  erewrite restrPermMap_valid in *;\n    by auto.\nQed.\n\nLemma domain_memren_incr:\n  forall f f' f'' m,\n    domain_memren f' m ->\n    domain_memren f'' m ->\n    ren_domain_incr f f' <-> ren_domain_incr f f''.\nProof.\n  intros.\n  unfold domain_memren in *;\n  split; intros Hincr b Hf;\n  apply Hincr in Hf;\n  destruct (H b), (H0 b);\n    by eauto.\nQed.\n\nLemma domain_memren_trans:\n  forall f f' m m',\n    domain_memren f m ->\n    domain_memren f m' ->\n    domain_memren f' m' ->\n    domain_memren f' m.\nProof.\n  intros.\n  split;\n    destruct (H b), (H0 b), (H1 b); auto.\nQed.\n\nLemma ren_incr_domain_incr:\n  forall f f',\n    ren_incr f f' ->\n    ren_domain_incr f f'.\nProof.\n  intros f f' Hincr b Hf.\n  destruct (f b) as [b'|] eqn:Hfb; try by exfalso.\n  specialize (Hincr b b' Hfb);\n    by rewrite Hincr.\nQed.\n\nLemma ren_domain_incr_refl:\n  forall f,\n    ren_domain_incr f f.\nProof.\n  intros.\n  unfold ren_domain_incr;\n    by auto.\nQed.\n\nLemma ren_domain_incr_trans:\n  forall f f' f'',\n    ren_domain_incr f f' ->\n    ren_domain_incr f' f'' ->\n    ren_domain_incr f f''.\nProof.\n  intros.\n  unfold ren_domain_incr;\n    by auto.\nQed.\n\nLemma ren_incr_trans:\n  forall f f' f'',\n    ren_incr f f' ->\n    ren_incr f' f'' ->\n    ren_incr f f''.\nProof.\n  intros.\n  unfold ren_incr;\n    by auto.\nQed.\n\nLemma ren_incr_refl:\n  forall f,\n    ren_incr f f.\nProof.\n  unfold ren_incr; auto.\nQed.\n\nLemma ren_separated_refl:\n  forall f m m',\n    ren_separated f f m m'.\nProof.\n  unfold ren_separated.\n    by congruence.\nQed.\n\n (** Results about id injections*)\n  Definition id_ren m :=\n    fun b => if is_left (valid_block_dec m b) then Some b else None.\n\n  Hint Unfold id_ren.\n\n  Lemma id_ren_correct:\n    forall m (b1 b2 : block), (id_ren m) b1 = Some b2 -> b1 = b2.\n  Proof.\n    intros. unfold id_ren in *.\n    destruct (valid_block_dec m b1); simpl in *;\n      by inversion H.\n  Qed.\n\n  Lemma id_ren_domain:\n    forall m, domain_memren (id_ren m) m.\n  Proof.\n    unfold id_ren, domain_memren.\n    intros.\n    destruct (valid_block_dec m b); simpl;\n    split; intuition.\n  Qed.\n\n  Lemma id_ren_validblock:\n    forall m b\n      (Hvalid: Mem.valid_block m b),\n      id_ren m b = Some b.\n  Proof.\n    intros.\n    eapply id_ren_domain in Hvalid.\n    destruct (id_ren m b) eqn:Hid.\n    apply id_ren_correct in Hid;\n      by subst.\n      by exfalso.\n  Qed.\n\n  Lemma id_ren_invalidblock:\n    forall m b\n      (Hinvalid: ~ Mem.valid_block m b),\n      id_ren m b = None.\n  Proof.\n    intros.\n    assert (Hnot:= iffLRn (id_ren_domain m b) Hinvalid).\n    destruct (id_ren m b) eqn:Hid;\n      first by exfalso.\n      by reflexivity.\n  Qed.\n\n  Lemma is_id_ren :\n    forall f m\n      (Hdomain: domain_memren f m)\n      (Hf_id: forall b1 b2, f b1 = Some b2 -> b1 = b2),\n      f = id_ren m.\n  Proof.\n    intros. extensionality b.\n    assert (Hdomain_id := id_ren_domain m).\n    destruct (f b) eqn:Hf, (id_ren m b) eqn:Hid;\n      try (assert (H:= id_ren_correct _ _ Hid));\n      try (specialize (Hf_id b _ Hf));\n      subst; auto.\n    assert (Hid': ~ id_ren m b0)\n      by (rewrite Hid; auto).\n    assert (Hf': f b0)\n      by (rewrite Hf; auto).\n    apply (proj2 (Hdomain b0)) in Hf'.\n    apply (iffRLn (Hdomain_id b0)) in Hid';\n      by exfalso.\n    assert (Hid': id_ren m b0)\n      by (rewrite Hid; auto).\n    assert (Hf': ~ f b0)\n      by (rewrite Hf; auto).\n    apply (proj2 (Hdomain_id b0)) in Hid'.\n    apply (iffRLn (Hdomain b0)) in Hf';\n      by exfalso.\n  Qed.\n\n  Lemma id_ren_restr:\n    forall pmap m (Hlt: permMapLt pmap (getMaxPerm m)),\n      id_ren m = id_ren (restrPermMap Hlt).\n  Proof.\n    intros.\n    extensionality b.\n    unfold id_ren.\n    destruct (valid_block_dec m b), (valid_block_dec (restrPermMap Hlt) b); simpl; auto.\n    erewrite restrPermMap_valid in n; by exfalso.\n    erewrite restrPermMap_valid in v; by exfalso.\n  Qed.\n\n\n  Lemma incr_domain_id:\n    forall m f f'\n      (Hincr: ren_incr f f')\n      (Hf_id: forall b b', f b = Some b' -> b = b')\n      (Hdomain_f: domain_memren f' m),\n      ren_incr f (id_ren m).\n  Proof.\n    intros.\n    intros b1 b2 Hf.\n    assert (b1 = b2)\n      by (eapply Hf_id in Hf; by subst).\n    subst b2.\n    apply Hincr in Hf.\n    destruct (Hdomain_f b1).\n    specialize (H0 ltac:(rewrite Hf; auto)).\n    assert (Hdomain_id := id_ren_domain m).\n    apply Hdomain_id in H0.\n    destruct (id_ren m b1) eqn:Hid; try by exfalso.\n    apply id_ren_correct in Hid;\n      by subst.\n  Qed.\n\n  Hint Immediate ren_incr_refl ren_separated_refl : renamings.\n\n  Hint Resolve id_ren_correct id_ren_domain id_ren_validblock\n       id_ren_invalidblock : id_renamings.\n\nEnd Renamings.\n\n(** ** Well-Defined values with respect to a renaming*)\nModule ValueWD.\n\n  Import Renamings.\n\n  Hint Immediate ren_domain_incr_refl : wd.\n\n  (** Valid values are the ones that have no pointers outside the domain of f*)\n  Definition valid_val (f: memren) (v : val) : Prop :=\n    match v with\n    | Vptr b _ =>\n      exists b', f b = Some b'\n    | _ => True\n    end.\n\n  Inductive valid_val_list (f: memren) : seq val -> Prop :=\n  | vs_nil: valid_val_list f [::]\n  | vs_cons: forall v vs,\n      valid_val f v ->\n      valid_val_list f vs ->\n      valid_val_list f (v :: vs).\n\n  Definition valid_memval (f: memren) (mv : memval) : Prop :=\n    match mv with\n    | Fragment v _ _ =>\n      valid_val f v\n    | _ => True\n    end.\n\n  Inductive valid_memval_list (f : memren) : seq memval -> Prop :=\n  |  mvs_nil : valid_memval_list f [::]\n  | mvs_cons : forall (v : memval) (vs : seq memval),\n      valid_memval f v ->\n      valid_memval_list f vs -> valid_memval_list f (v :: vs).\n\n  Lemma valid_val_incr:\n    forall f f' v\n      (Hvalid: valid_val f v)\n      (Hincr: ren_domain_incr f f'),\n      valid_val f' v.\n  Proof.\n    intros.\n    unfold valid_val in *.\n    destruct v; auto.\n    destruct Hvalid as [? Hf].\n    assert (Hfb: f b)\n      by (rewrite Hf; auto).\n    specialize (Hincr b Hfb).\n    destruct (f' b) eqn:Hf'; try by exfalso.\n      by eexists; eauto.\n  Qed.\n\n  Lemma valid_val_list_incr:\n    forall f f' vs\n      (Hvalid: valid_val_list f vs)\n      (Hincr: ren_domain_incr f f'),\n      valid_val_list f' vs.\n  Proof.\n    intros.\n    induction vs;\n      first by constructor.\n    inversion Hvalid; subst.\n    constructor; eauto.\n    eapply valid_val_incr;\n      by eauto.\n  Qed.\n\n  Lemma valid_val_domain:\n    forall f f' m v,\n      valid_val f v ->\n      domain_memren f m ->\n      domain_memren f' m ->\n      valid_val f' v.\n  Proof.\n    intros.\n    destruct v; auto.\n    destruct H as [b' Hf].\n    unfold domain_memren in *.\n    destruct (H0 b).\n    destruct (H1 b).\n    rewrite Hf in H2.\n    specialize (H2 ltac:(auto)).\n    specialize (H3 H2).\n    destruct (f' b) eqn:Hf'; try by exfalso.\n    econstructor; eauto.\n  Qed.\n\n  Lemma valid_val_list_domain:\n    forall f f' m vs\n      (Hvalid: valid_val_list f vs)\n      (Hdomain: domain_memren f m)\n      (Hdomain': domain_memren f' m),\n      valid_val_list f' vs.\n  Proof.\n    intros.\n    induction vs; first by constructor.\n    inversion Hvalid; subst.\n    constructor; [eapply valid_val_domain|];\n      by eauto.\n  Qed.\n\n  Lemma ofs_val_lt :\n    forall ofs chunk v,\n      ofs < ofs + Z.of_nat (length (encode_val chunk v)).\n  Proof.\n    destruct chunk, v; simpl; try omega;\n    rewrite length_inj_bytes encode_int_length;\n    simpl; omega.\n  Qed.\n\n  (** Lemmas about the well-definedness of the various value\n  constructors*)\n\n  Lemma valid_val_int:\n    forall f n,\n      valid_val f (Vint n).\n  Proof.\n    simpl; auto.\n  Qed.\n\n  Lemma valid_val_one:\n    forall f, valid_val f Vone.\n  Proof.\n    simpl; auto.\n  Qed.\n\n  Lemma valid_val_single:\n    forall f n,\n      valid_val f (Vsingle n).\n  Proof.\n    simpl; auto.\n  Qed.\n\n  Lemma valid_val_float:\n    forall f n,\n      valid_val f (Vfloat n).\n  Proof.\n    simpl; auto.\n  Qed.\n\n  Lemma valid_val_add:\n    forall f v1 v2,\n      valid_val f v1 ->\n      valid_val f v2 ->\n      valid_val f (Val.add v1 v2).\n  Proof.\n    intros.\n    destruct v1, v2; simpl in *; auto.\n  Qed.\n\n  Lemma valid_val_sub:\n    forall f v1 v2,\n      valid_val f v1 ->\n      valid_val f v2 ->\n      valid_val f (Val.sub v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n    destruct (eq_block b b0); simpl; auto.\n  Qed.\n\n  Lemma valid_val_mul:\n    forall f v1 v2,\n      valid_val f (Val.mul v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_mulhu:\n    forall f v1 v2,\n      valid_val f (Val.mulhu v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_and:\n    forall f v1 v2,\n      valid_val f (Val.and v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_or:\n    forall f v1 v2,\n      valid_val f (Val.or v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_xor:\n    forall f v1 v2,\n      valid_val f (Val.xor v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_intoffloat:\n    forall f v,\n      valid_val f (Val.maketotal (Val.intoffloat v)).\n  Proof.\n    destruct v; simpl; auto; unfold Val.maketotal;\n    unfold option_map;\n    match goal with\n    | [|- context[match match ?Expr with _ => _ end with _ => _ end]] =>\n      destruct Expr\n    end; simpl; auto.\n  Qed.\n\n  Lemma valid_intofsingle:\n    forall f v,\n      valid_val f (Val.maketotal (Val.intofsingle v)).\n  Proof.\n    destruct v; simpl; auto; unfold Val.maketotal;\n    unfold option_map;\n    match goal with\n    | [|- context[match match ?Expr with _ => _ end with _ => _ end]] =>\n      destruct Expr\n    end; simpl; auto.\n  Qed.\n\n  Lemma valid_singleofint:\n    forall f v,\n      valid_val f (Val.maketotal (Val.singleofint v)).\n  Proof.\n    destruct v; simpl; auto; unfold Val.maketotal;\n    unfold option_map;\n    match goal with\n    | [|- context[match match ?Expr with _ => _ end with _ => _ end]] =>\n      destruct Expr\n    end; simpl; auto.\n  Qed.\n\n  Lemma valid_floatofint:\n    forall f v,\n      valid_val f (Val.maketotal (Val.floatofint v)).\n  Proof.\n    destruct v; simpl; auto; unfold Val.maketotal;\n    unfold option_map;\n    match goal with\n    | [|- context[match match ?Expr with _ => _ end with _ => _ end]] =>\n      destruct Expr\n    end; simpl; auto.\n  Qed.\n\n  Lemma valid_val_singleoffloat:\n    forall f v,\n      valid_val f (Val.singleoffloat v).\n  Proof.\n    destruct v; simpl; auto.\n  Qed.\n\n  Lemma valid_val_floatofsingle:\n    forall f v,\n      valid_val f (Val.floatofsingle v).\n  Proof.\n    destruct v; simpl; auto.\n  Qed.\n\n  Lemma valid_val_neg:\n    forall f v,\n      valid_val f (Val.neg v).\n  Proof.\n    destruct v; simpl; auto.\n  Qed.\n\n  Lemma valid_val_sign_ext:\n    forall f v n,\n      valid_val f (Val.sign_ext n v).\n  Proof.\n    intros; destruct v; simpl; auto.\n  Qed.\n\n  Lemma valid_val_zero_ext:\n    forall f v n,\n      valid_val f (Val.zero_ext n v).\n  Proof.\n    intros.\n    destruct v; simpl; auto.\n  Qed.\n\n  Lemma valid_val_mulhs:\n    forall f v1 v2,\n      valid_val f (Val.mulhs v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_undef:\n    forall f,\n      valid_val f Vundef.\n  Proof.\n    simpl; auto.\n  Qed.\n\n  Lemma valid_val_shl:\n    forall f v1 v2,\n      valid_val f (Val.shl v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto;\n    match goal with\n    | [|- context[match ?Expr with _ => _ end]] =>\n      destruct Expr\n    end; simpl; auto.\n  Qed.\n\n  Lemma valid_val_shru:\n    forall f v1 v2,\n      valid_val f (Val.shru v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto;\n    match goal with\n    | [|- context[match ?Expr with _ => _ end]] =>\n      destruct Expr\n    end; simpl; auto.\n  Qed.\n\n  Lemma valid_val_shr:\n    forall f v1 v2,\n      valid_val f (Val.shr v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto;\n    match goal with\n    | [|- context[match ?Expr with _ => _ end]] =>\n      destruct Expr\n    end; simpl; auto.\n  Qed.\n\n  Lemma valid_val_ror:\n    forall f v1 v2,\n      valid_val f (Val.ror v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto;\n    match goal with\n    | [|- context[match ?Expr with _ => _ end]] =>\n      destruct Expr\n    end; simpl; auto.\n  Qed.\n\n  Lemma valid_val_addf:\n    forall f v1 v2,\n      valid_val f (Val.addf v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_mulf:\n    forall f v1 v2,\n      valid_val f (Val.mulf v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_subf:\n    forall f v1 v2,\n      valid_val f (Val.subf v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_divf:\n    forall f v1 v2,\n      valid_val f (Val.divf v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_addfs:\n    forall f v1 v2,\n      valid_val f (Val.addfs v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_mulfs:\n    forall f v1 v2,\n      valid_val f (Val.mulfs v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_subfs:\n    forall f v1 v2,\n      valid_val f (Val.subfs v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_divfs:\n    forall f v1 v2,\n      valid_val f (Val.divfs v1 v2).\n  Proof.\n    intros.\n    destruct v1; simpl; auto;\n    destruct v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_negf:\n    forall f v,\n      valid_val f (Val.negf v).\n  Proof.\n    intros.\n    destruct v; simpl; auto.\n  Qed.\n\n  Lemma valid_val_absf:\n    forall f v,\n      valid_val f (Val.absf v).\n  Proof.\n    intros.\n    destruct v; simpl; auto.\n  Qed.\n\n  Lemma valid_val_negfs:\n    forall f v,\n      valid_val f (Val.negfs v).\n  Proof.\n    intros.\n    destruct v; simpl; auto.\n  Qed.\n\n  Lemma valid_val_absfs:\n    forall f v,\n      valid_val f (Val.absfs v).\n  Proof.\n    intros.\n    destruct v; simpl; auto.\n  Qed.\n\n  Lemma valid_val_divu:\n    forall f v1 v2 v,\n      Val.divu v1 v2 = Some v ->\n      valid_val f v.\n  Proof.\n    intros.\n    destruct v1, v2; simpl in *; try discriminate.\n    destruct (Int.eq i0 Int.zero); try discriminate.\n    inv H; simpl; auto.\n  Qed.\n\n  Lemma valid_val_modu:\n    forall f v1 v2 v,\n      Val.modu v1 v2 = Some v ->\n      valid_val f v.\n  Proof.\n    intros.\n    destruct v1, v2; simpl in *; try discriminate.\n    destruct (Int.eq i0 Int.zero); try discriminate.\n    inv H; simpl; auto.\n  Qed.\n\n  Lemma valid_val_divs:\n    forall f v1 v2 v,\n      Val.divs v1 v2 = Some v ->\n      valid_val f v.\n  Proof.\n    intros.\n    destruct v1, v2; simpl in *; try discriminate;\n    match goal with\n    | [H: context[match ?Expr with _ => _ end] |- _] =>\n      destruct Expr\n    end; try discriminate.\n    inv H; simpl; auto.\n  Qed.\n\n  Lemma valid_val_mods:\n    forall f v1 v2 v,\n      Val.mods v1 v2 = Some v ->\n      valid_val f v.\n  Proof.\n    intros.\n    destruct v1, v2; simpl in *; try discriminate;\n    match goal with\n    | [H: context[match ?Expr with _ => _ end] |- _] =>\n      destruct Expr\n    end; try discriminate.\n    inv H; simpl; auto.\n  Qed.\n\n  Lemma valid_val_notint:\n    forall f v,\n      valid_val f (Val.notint v).\n  Proof.\n    destruct v; simpl; auto.\n  Qed.\n\n  Lemma valid_val_vzero:\n    forall f,\n      valid_val f (Vzero).\n  Proof.\n    simpl; auto.\n  Qed.\n\n  Lemma valid_val_of_optbool:\n    forall f b,\n      valid_val f (Val.of_optbool b).\n  Proof.\n    destruct b as [[|] |]; simpl; auto.\n  Qed.\n\n\n  Lemma valid_val_offset:\n    forall f b ofs ofs',\n      valid_val f (Vptr b ofs) ->\n      valid_val f (Vptr b ofs').\n  Proof.\n    intros. unfold valid_val in *.\n    auto.\n  Qed.\n\n  Lemma valid_val_sub_overflow:\n    forall f v1 v2,\n      valid_val f (Val.sub_overflow v1 v2).\n  Proof.\n    destruct v1,v2; simpl; auto.\n  Qed.\n\n  Lemma valid_val_negative:\n    forall f v,\n      valid_val f (Val.negative v).\n  Proof.\n    destruct v; simpl; auto.\n  Qed.\n\n  Lemma valid_val_of_bool:\n    forall f b,\n      valid_val f (Val.of_bool b).\n  Proof.\n    destruct b; simpl; auto.\n  Qed.\n\n  Hint Resolve valid_val_sub : wd.\n  Hint Immediate  valid_val_int valid_val_one valid_val_undef\n       valid_val_single valid_val_float valid_val_add\n       valid_val_mul valid_val_mulhu valid_val_mulhs\n       valid_val_and valid_val_or valid_val_xor\n       valid_intoffloat valid_intofsingle\n       valid_singleofint valid_floatofint\n       valid_val_singleoffloat valid_val_floatofsingle\n       valid_val_neg valid_val_sign_ext valid_val_zero_ext\n       valid_val_divu valid_val_modu\n       valid_val_divs valid_val_mods\n       valid_val_notint valid_val_vzero\n       valid_val_shl valid_val_shru valid_val_shr\n       valid_val_ror valid_val_addf valid_val_mulf\n       valid_val_subf valid_val_divf\n       valid_val_addfs valid_val_mulfs\n       valid_val_subfs valid_val_divfs\n       valid_val_negf valid_val_absf\n       valid_val_negfs valid_val_absfs\n       valid_val_of_optbool valid_val_sub_overflow\n       valid_val_negative valid_val_of_bool : wd.\nEnd ValueWD.\n\n(** ** Well-defined Memories*)\nModule MemoryWD.\n\n  Import Renamings MemoryLemmas ValueWD.\n  (** Valid memories are the ones that do not contain any dangling pointers*)\n  Definition valid_mem m :=\n    forall b,\n      Mem.valid_block m b ->\n      forall ofs mv,\n        Maps.ZMap.get ofs (Mem.mem_contents m) # b = mv ->\n        match mv with\n        | Fragment v q n =>\n          mem_wd.val_valid v m\n        | _ => True\n        end.\n\n  Lemma wd_val_valid:\n    forall v m f\n      (Hdomain: domain_memren f m),\n      mem_wd.val_valid v m <-> valid_val f v.\n  Proof.\n    intros.\n    unfold mem_wd.val_valid, valid_val.\n    destruct v; try tauto.\n    split.\n    intro H.\n    apply Hdomain in H.\n    destruct (f b) as [b0|];\n      by [exists b0; eauto | intuition].\n    intros (b' & H).\n    assert (H': f b)\n      by (rewrite H; auto);\n      by apply Hdomain in H'.\n  Qed.\n\n  Lemma restrPermMap_val_valid:\n    forall m p (Hlt: permMapLt p (getMaxPerm m)) v,\n      mem_wd.val_valid v m <-> mem_wd.val_valid v (restrPermMap Hlt).\n  Proof.\n    intros; split; unfold mem_wd.val_valid;\n      by destruct v.\n  Qed.\n\n  Lemma restrPermMap_mem_valid :\n    forall m p (Hlt: permMapLt p (getMaxPerm m)),\n      valid_mem m <-> valid_mem (restrPermMap Hlt).\n  Proof.\n    intros.\n    split; intros Hvalid b;\n    specialize (Hvalid b);\n    erewrite restrPermMap_valid in *; simpl; intros Hb ofs mv Hmv;\n    specialize (Hvalid Hb ofs mv Hmv);\n    destruct mv; auto.\n  Qed.\n\n  Lemma inj_bytes_type:\n    forall bs mv,\n      In mv (inj_bytes bs) ->\n      match mv with\n      | Byte _ => True\n      | _ => False\n      end.\n  Proof.\n    induction bs; intros; simpl in *;\n    first  by exfalso.\n    destruct H.\n    rewrite <- H; auto.\n    eapply IHbs; eauto.\n  Qed.\n\n  Lemma decode_val_wd:\n    forall f (vl : seq memval) (chunk : memory_chunk),\n      valid_memval_list f vl ->\n      valid_val f (decode_val chunk vl).\n  Proof.\n    intros.\n    unfold decode_val.\n    destruct (proj_bytes vl) as [bl|] eqn:PB1;\n      destruct chunk; simpl; auto;\n      match goal with\n      | [|- context[proj_value ?Q ?V]] =>\n        destruct (proj_value Q V) eqn:?\n      end; simpl; auto;\n      repeat match goal with\n             | [H: proj_value ?Q ?V = _ |- _] =>\n               destruct (proj_value Q V) eqn:?;\n                        unfold  proj_value in *\n             | [H: match ?Expr with _ => _ end = _ |- _] =>\n               destruct Expr eqn:?; try discriminate\n             | [H: Vptr _ _ = Vptr _ _ |- _ ] =>\n               inversion H; clear H\n             end; subst;\n      inversion H; subst;\n      inversion H2; eexists; eauto.\n  Qed.\n\n  Lemma getN_wd :\n    forall (f : memren) (m : mem) b,\n      Mem.valid_block m b ->\n      valid_mem m ->\n      domain_memren f m ->\n      forall (n : nat) (ofs : Z),\n        valid_memval_list f (Mem.getN n ofs (Mem.mem_contents m) # b).\n  Proof.\n    induction n; intros; simpl;\n    constructor.\n    unfold valid_mem in H0.\n    specialize (H0 _ H ofs _ ltac:(reflexivity)).\n    destruct (ZMap.get ofs (Mem.mem_contents m) # b); simpl; auto.\n    erewrite <- wd_val_valid; eauto.\n    eauto.\n  Qed.\n\n  Lemma valid_val_encode:\n    forall v m chunk\n      (Hval_wd: mem_wd.val_valid v m),\n    forall v',\n      List.In v' (encode_val chunk v) ->\n      match v' with\n      | Undef => True\n      | Byte _ => True\n      | Fragment v'' _ _ =>\n        mem_wd.val_valid v'' m\n      end.\n  Proof.\n    intros.\n    destruct v'; auto.\n    destruct v, chunk; simpl in *;\n    repeat (match goal with\n            | [H: _ \\/ _ |- _] =>\n              destruct H\n            | [H: False |- _] =>\n                by exfalso\n            | [H: _ = _ |- _] =>\n              inversion H; subst; clear H\n            end); simpl; auto;\n    apply inj_bytes_type in H;\n      by exfalso.\n  Qed.\n\n  Lemma valid_val_store:\n    forall v m m' chunk b ofs v'\n      (Hvalid: mem_wd.val_valid v m)\n      (Hstore: Mem.store chunk m b ofs v' = Some m'),\n      mem_wd.val_valid v m'.\n  Proof.\n    intros.\n    destruct v; simpl; auto.\n    eapply Mem.store_valid_block_1; eauto.\n  Qed.\n\n  (** Well-definedeness is preserved through storing of a well-defined value *)\n  Lemma store_wd_domain:\n    forall (m m' : mem) (chunk : memory_chunk) (v : val) b ofs f\n      (Hdomain: domain_memren f m)\n      (Hstore: Mem.store chunk m b ofs v = Some m')\n      (Hval_wd: mem_wd.val_valid v m)\n      (Hmem_wd: valid_mem m),\n      valid_mem m' /\\ domain_memren f m'.\n  Proof.\n    intros.\n    unfold valid_mem in *.\n    split.\n    { intros b0 Hvalid ofs0 mv Hget.\n      eapply Mem.store_valid_block_2 in Hvalid; eauto.\n      rewrite (Mem.store_mem_contents _ _ _ _ _ _ Hstore) in Hget.\n      destruct (Pos.eq_dec b b0) as [Heq | Hneq].\n      - (*case it's the same block*)\n        subst.\n        rewrite Maps.PMap.gss.\n        destruct (Intv.In_dec ofs0\n                              (ofs,\n                               (ofs + Z.of_nat (length (encode_val chunk v)))%Z)).\n\n        + apply Mem.setN_in with (c:= (Mem.mem_contents m) # b0) in i.\n          apply valid_val_encode with (m := m) in i; auto.\n          destruct (ZMap.get ofs0\n                             (Mem.setN (encode_val chunk v) ofs (Mem.mem_contents m) # b0));\n            simpl; auto.\n          eapply valid_val_store; eauto.\n        + apply Intv.range_notin in n.\n          erewrite Mem.setN_outside by eauto.\n          specialize (Hmem_wd _ Hvalid ofs0 _ ltac:(reflexivity)).\n          destruct (ZMap.get ofs0 (Mem.mem_contents m) # b0); auto.\n          eapply valid_val_store; eauto.\n          simpl.\n          apply ofs_val_lt.\n      - erewrite Maps.PMap.gso in Hget by eauto.\n        specialize (Hmem_wd _ Hvalid ofs0 _ ltac:(reflexivity)).\n        destruct (ZMap.get ofs0 (Mem.mem_contents m) # b0); subst; auto.\n        eapply valid_val_store; eauto. }\n    { split.\n      intros. eapply Mem.store_valid_block_2 in H; eauto.\n      eapply Hdomain; auto.\n      intros. eapply Mem.store_valid_block_1; eauto.\n      apply Hdomain; auto.\n    }\n  Qed.\n\n  Lemma storev_wd_domain:\n    forall (m m' : mem) (chunk : memory_chunk) (vptr v : val) f,\n      domain_memren f m ->\n      Mem.storev chunk m vptr v = Some m' ->\n      mem_wd.val_valid v m ->\n      valid_mem m ->\n      valid_mem m' /\\ domain_memren f m'.\n  Proof.\n    intros.\n    destruct vptr; simpl in *; try discriminate.\n    eapply store_wd_domain; eauto.\n  Qed.\n\n  (** Loading a value from a well-defined memory returns a valid value*)\n  Lemma valid_mem_load:\n    forall chunk m b ofs v f\n      (Hwd: valid_mem m)\n      (Hdomain: domain_memren f m)\n      (Hload: Mem.load chunk m b ofs = Some v),\n      valid_val f v.\n  Proof.\n    intros.\n    unfold valid_mem in Hwd.\n    assert (Hvalid: Mem.valid_block m b)\n      by (eapply load_valid_block; eauto).\n    exploit Mem.load_result; eauto. intro. rewrite H.\n    eapply decode_val_wd; eauto.\n    apply getN_wd; auto.\n  Qed.\n\n  Lemma loadv_wd:\n    forall chunk m vptr v f\n      (Hwd: valid_mem m)\n      (Hdomain: domain_memren f m)\n      (Hload: Mem.loadv chunk m vptr = Some v),\n      valid_val f v.\n  Proof.\n    intros.\n    destruct vptr; try discriminate.\n    eapply valid_mem_load; eauto.\n  Qed.\n\n  Lemma domain_memren_store:\n    forall chunk m m' b ofs v f\n      (Hdomain: domain_memren f m)\n      (Hstore: Mem.store chunk m b ofs v = Some m'),\n      domain_memren f m'.\n  Proof.\n    intros.\n    split.\n    - intros Hvalid.\n      eapply Mem.store_valid_block_2 in Hvalid; eauto.\n      edestruct Hdomain; auto.\n    - intros Hf.\n      eapply Mem.store_valid_block_1; eauto.\n      edestruct Hdomain; eauto.\n  Qed.\n\n  Lemma domain_memren_storev:\n    forall chunk m m' vptr v f\n      (Hdomain: domain_memren f m)\n      (Hstore: Mem.storev chunk m vptr v = Some m'),\n      domain_memren f m'.\n  Proof.\n    intros.\n    unfold Mem.storev in Hstore.\n    destruct vptr; try discriminate.\n    eapply domain_memren_store; eauto.\n  Qed.\n\nEnd MemoryWD.\n\n(** ** Renamings on values*)\nModule ValObsEq.\n\n  Import ValueWD MemoryWD Renamings MemoryLemmas.\n\n  (** Strong injections on values *)\n  Inductive val_obs (mi : memren) : val -> val -> Prop :=\n    obs_int : forall i : int, val_obs mi (Vint i) (Vint i)\n  | obs_long : forall i : int64, val_obs mi (Vlong i) (Vlong i)\n  | obs_float : forall f : Floats.float,\n      val_obs mi (Vfloat f) (Vfloat f)\n  | obs_single : forall f : Floats.float32,\n      val_obs mi (Vsingle f) (Vsingle f)\n  | obs_ptr : forall (b1 b2 : block) (ofs : int),\n      mi b1 = Some b2 ->\n      val_obs mi (Vptr b1 ofs) (Vptr b2 ofs)\n  | obs_undef : val_obs mi Vundef Vundef.\n\n  (** Strong injections on memory values*)\n  Inductive memval_obs_eq (f : memren) : memval -> memval -> Prop :=\n  | memval_obs_byte : forall n : byte,\n      memval_obs_eq f (Byte n) (Byte n)\n  | memval_obs_frag : forall (v1 v2 : val) (q : quantity) (n : nat)\n                        (Hval_obs: val_obs f v1 v2),\n      memval_obs_eq f (Fragment v1 q n) (Fragment v2 q n)\n  | memval_obs_undef : memval_obs_eq f Undef Undef.\n\n\n  Inductive val_obs_list (mi : memren) : seq val -> seq val -> Prop :=\n    val_obs_list_nil : val_obs_list mi [::] [::]\n  | val_obs_list_cons : forall (v v' : val) (vl vl' : seq val),\n                       val_obs mi v v' ->\n                       val_obs_list mi vl vl' ->\n                       val_obs_list mi (v :: vl) (v' :: vl').\n\n  Hint Constructors val_obs : val_renamings.\n\n  Lemma val_obs_incr:\n    forall f f' v v'\n      (Hval_obs: val_obs f v v')\n      (Hincr: ren_incr f f'),\n      val_obs f' v v'.\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v; inversion Hval_obs; subst...\n  Qed.\n\n  Lemma val_obs_trans:\n    forall (v v' v'' : val) (f f' f'' : memren),\n      val_obs f v v'' ->\n      val_obs f' v v' ->\n      (forall b b' b'' : block,\n          f b = Some b'' ->\n          f' b = Some b' ->\n          f'' b' = Some b'') ->\n      val_obs f'' v' v''.\n  Proof with eauto with val_renamings.\n    intros v v' v'' f f' f'' Hval'' Hval' Hf.\n    inversion Hval'; subst; inversion Hval''; subst...\n  Qed.\n\n  Lemma memval_obs_trans:\n    forall (v v' v'' : memval) (f f' f'' : memren),\n      memval_obs_eq f v v'' ->\n      memval_obs_eq f' v v' ->\n      (forall b b' b'' : block,\n          f b = Some b'' ->\n          f' b = Some b' ->\n          f'' b' = Some b'') ->\n      memval_obs_eq f'' v' v''.\n  Proof.\n    intros v v' v'' f f' f'' Hval'' Hval' Hf.\n    inversion Hval'; subst; inversion Hval''; subst;\n    try constructor.\n    eapply val_obs_trans;\n      by eauto.\n  Qed.\n\n  Lemma val_obs_list_trans:\n    forall (vs vs' vs'' : seq val) (f f' f'' : memren),\n      val_obs_list f vs vs'' ->\n      val_obs_list f' vs vs' ->\n      (forall b b' b'' : block,\n          f b = Some b'' ->\n          f' b = Some b' ->\n          f'' b' = Some b'') ->\n      val_obs_list f'' vs' vs''.\n  Proof.\n    intros vs vs' vs'' f f' f'' Hobs Hobs' Hf.\n    generalize dependent vs''.\n    induction Hobs'; subst; intros;\n    inversion Hobs; subst. constructor.\n    constructor; auto.\n      by eapply val_obs_trans; eauto.\n  Qed.\n\n  Lemma val_obs_list_incr:\n    forall (vs vs' : seq val) (f f' : memren),\n      val_obs_list f vs vs' ->\n      ren_incr f f' ->\n      val_obs_list f' vs vs'.\n  Proof.\n    intros.\n    induction H;\n      constructor;\n      eauto using val_obs_incr.\n  Qed.\n\n  (** Two values that are equal are related by the id injection on a valid memory*)\n  Lemma val_obs_id:\n    forall f v\n      (Hvalid: valid_val f v)\n      (Hid: forall b b', f b = Some b' -> b = b'),\n      val_obs f v v.\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v...\n    destruct Hvalid as [b' Hf].\n    specialize (Hid _ _ Hf);\n      subst...\n  Qed.\n\n  Lemma val_obs_list_id :\n    forall f vs\n      (Hvalid: valid_val_list f vs)\n      (Hf: forall b1 b2, f b1 = Some b2 -> b1 = b2),\n      val_obs_list f vs vs.\n  Proof.\n    intros.\n    induction vs; first by constructor.\n    inversion Hvalid; subst.\n    constructor;\n      [eapply val_obs_id; eauto | eauto].\n  Qed.\n\n  Lemma memval_obs_eq_id:\n    forall f mv\n      (Hvalid: valid_memval f mv)\n      (Hid: forall b b', f b = Some b' -> b = b'),\n                    memval_obs_eq f mv mv.\n  Proof.\n    intros.\n    destruct mv;\n    econstructor;\n    eapply val_obs_id;\n      by eauto.\n  Qed.\n\n  Lemma ren_cmp_bool:\n    forall f v v' v0 cmp,\n      val_obs f v v' ->\n      Val.cmp_bool cmp v v0 = Val.cmp_bool cmp v' v0.\n  Proof.\n    intros.\n    destruct v; inversion H; subst;\n      by reflexivity.\n  Qed.\n\n  Lemma val_obs_hiword:\n    forall f v v',\n      val_obs f v v' ->\n      val_obs f (Val.hiword v) (Val.hiword v').\n  Proof with eauto with val_renamings.\n    intros;\n    destruct v; inversion H; subst;\n    simpl...\n  Qed.\n\n  Lemma val_obs_loword:\n    forall f v v',\n      val_obs f v v' ->\n      val_obs f (Val.loword v) (Val.loword v').\n  Proof with eauto with val_renamings.\n    intros;\n    destruct v; inversion H; subst;\n    simpl...\n  Qed.\n\n  Lemma val_obs_longofwords:\n    forall f vhi vhi' vlo vlo'\n      (Hobs_hi: val_obs f vhi vhi')\n      (Hobs_lo: val_obs f vlo vlo'),\n      val_obs f (Val.longofwords vhi vlo) (Val.longofwords vhi' vlo').\n  Proof with eauto with val_renamings.\n    intros;\n    destruct vhi; inversion Hobs_hi; subst; simpl...\n    destruct vlo; inversion Hobs_lo...\n  Qed.\n\n  Lemma val_obs_load_result:\n    forall f v v' chunk\n      (Hval_obs: val_obs f v v'),\n      val_obs f (Val.load_result chunk v) (Val.load_result chunk v').\n  Proof with eauto with val_renamings.\n    intros;\n    destruct v; inversion Hval_obs; subst;\n    destruct chunk; simpl...\n  Qed.\n\n  Lemma val_obs_ext:\n    forall f v v' n\n      (Hval_obs: val_obs f v v'),\n      val_obs f (Val.zero_ext n v) (Val.zero_ext n v').\n  Proof with eauto with val_renamings.\n    intros; destruct v; inversion Hval_obs; subst; simpl...\n  Qed.\n\n  Definition val_obsC f v :=\n    match v with\n    | Vptr b n => match f b with\n                 | Some b' => Vptr b' n\n                 | None => Vundef\n                 end\n    | _ => v\n    end.\n\n  Lemma val_obsC_correct:\n    forall f v,\n      valid_val f v ->\n      val_obs f v (val_obsC f v).\n  Proof.\n    intros.\n    destruct v; simpl;\n    try constructor.\n    simpl in H.\n    destruct H.\n    rewrite H;\n      by constructor.\n  Qed.\n\n  Lemma val_has_type_obs:\n    forall f v v' ty\n      (Hval_obs: val_obs f v v'),\n      val_casted.val_has_type_func v ty <-> val_casted.val_has_type_func v' ty.\n  Proof.\n    intros.\n    destruct v; inversion Hval_obs; subst; simpl;\n      by tauto.\n  Qed.\n\n  Lemma val_has_type_list_obs:\n    forall f vs vs' ts\n      (Hval_obs: val_obs_list f vs vs'),\n      val_casted.val_has_type_list_func vs ts <->\n      val_casted.val_has_type_list_func vs' ts.\n  Proof.\n    intros.\n    generalize dependent vs'.\n    generalize dependent ts.\n    induction vs;\n      intros. inversion Hval_obs; subst.\n    simpl; destruct ts; split;\n      by auto.\n    inversion Hval_obs; subst.\n    destruct ts; simpl; first by split; auto.\n    split; intros; move/andP:H=>[H H'];\n      apply/andP.\n    split;\n      [erewrite <- val_has_type_obs; eauto |\n       destruct (IHvs ts _ H3); eauto].\n    split;\n      [erewrite val_has_type_obs; eauto |\n       destruct (IHvs ts _ H3); eauto].\n  Qed.\n\n  Lemma vals_defined_obs:\n    forall f vs vs'\n      (Hval_obs: val_obs_list f vs vs'),\n      val_casted.vals_defined vs <-> val_casted.vals_defined vs'.\n  Proof.\n    intros.\n    induction Hval_obs;\n      simpl; try tauto.\n    destruct v; inversion H;\n      by tauto.\n  Qed.\n\n  Lemma zlength_obs:\n    forall f v v'\n      (Hval_obs: val_obs_list f v v'),\n      Zlength v = Zlength v'.\n  Proof.\n    induction 1; simpl; auto.\n    do 2 rewrite Zlength_cons;\n      by rewrite IHHval_obs.\n  Qed.\n\n  Lemma val_obs_add:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.add v1 v1') (Val.add v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_sign_ext:\n    forall f v v' n\n      (Hval_obs: val_obs f v v'),\n      val_obs f (Val.sign_ext n v) (Val.sign_ext n v').\n  Proof with eauto with val_renamings.\n    intros; destruct v; inversion Hval_obs; subst; simpl...\n  Qed.\n\n\n  Lemma val_obs_singleoffloat:\n    forall f v v'\n      (Hval_obs: val_obs f v v'),\n      val_obs f (Val.singleoffloat v) (Val.singleoffloat v').\n  Proof with eauto with val_renamings.\n    intros; destruct v; inversion Hval_obs; subst; simpl...\n  Qed.\n\n  Lemma val_obs_floatofsingle:\n    forall f v v'\n      (Hval_obs: val_obs f v v'),\n      val_obs f (Val.floatofsingle v) (Val.floatofsingle v').\n  Proof with eauto with val_renamings.\n    intros; destruct v; inversion Hval_obs; subst; simpl...\n  Qed.\n\n  Lemma val_obs_intoffloat:\n    forall f v v'\n      (Hval_obs: val_obs f v v'),\n      val_obs f (Val.maketotal (Val.intoffloat v))\n              (Val.maketotal (Val.intoffloat v')).\n  Proof with eauto with val_renamings.\n    intros; destruct v; unfold Val.maketotal;\n    inversion Hval_obs; subst; simpl...\n    match goal with\n    | [|- context[match ?Expr with _ => _ end]] =>\n      destruct Expr eqn:?\n    end...\n    unfold Coqlib.option_map in Heqo.\n    destruct (Floats.Float.to_int f0); inversion Heqo...\n  Qed.\n\n  Lemma val_obs_floatofint:\n    forall f v v'\n      (Hval_obs: val_obs f v v'),\n      val_obs f (Val.maketotal (Val.floatofint v))\n              (Val.maketotal (Val.floatofint v')).\n  Proof with eauto with val_renamings.\n    intros; destruct v; unfold Val.maketotal;\n    inversion Hval_obs; subst; simpl...\n  Qed.\n\n  Lemma val_obs_intofsingle:\n    forall f v v'\n      (Hval_obs: val_obs f v v'),\n      val_obs f (Val.maketotal (Val.intofsingle v))\n              (Val.maketotal (Val.intofsingle v')).\n  Proof with eauto with val_renamings.\n    intros; destruct v; unfold Val.maketotal;\n    inversion Hval_obs; subst; simpl...\n    match goal with\n    | [|- context[match ?Expr with _ => _ end]] =>\n      destruct Expr eqn:?\n    end...\n    unfold Coqlib.option_map in Heqo.\n    destruct (Floats.Float32.to_int f0); inversion Heqo...\n  Qed.\n\n  Lemma val_obs_singleofint:\n    forall f v v'\n      (Hval_obs: val_obs f v v'),\n      val_obs f (Val.maketotal (Val.singleofint v))\n              (Val.maketotal (Val.singleofint v')).\n  Proof with eauto with val_renamings.\n    intros; destruct v; unfold Val.maketotal;\n    inversion Hval_obs; subst; simpl...\n  Qed.\n\n  Lemma val_obs_mul:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.mul v1 v1') (Val.mul v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_mulhs:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.mulhs v1 v1') (Val.mulhs v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_mulhu:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.mulhu v1 v1') (Val.mulhu v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_and:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.and v1 v1') (Val.and v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_or:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.or v1 v1') (Val.or v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_xor:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.xor v1 v1') (Val.xor v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_notint:\n    forall f v1 v2\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.notint v1) (Val.notint v2).\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1; inversion Hval_obs; subst;\n    simpl...\n  Qed.\n\n  Lemma val_obs_shl:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.shl v1 v1') (Val.shl v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n    destruct (Int.ltu i0 Int.iwordsize)...\n  Qed.\n\n  Lemma val_obs_shr:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.shr v1 v1') (Val.shr v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n    destruct (Int.ltu i0 Int.iwordsize)...\n  Qed.\n\n\n  Lemma val_obs_shru:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.shru v1 v1') (Val.shru v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n    destruct (Int.ltu i0 Int.iwordsize)...\n  Qed.\n\n  Lemma val_obs_ror:\n  forall f v1 v2 ofs\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.ror v1 (Vint ofs)) (Val.ror v2 (Vint ofs)).\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1; inversion Hval_obs; subst; simpl...\n  Qed.\n\n  Lemma val_obs_suboverflow:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.sub_overflow v1 v1') (Val.sub_overflow v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_negative:\n    forall f v1 v2\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.negative v1) (Val.negative v2).\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1; inversion Hval_obs; subst;\n    simpl...\n  Qed.\n\n  Lemma val_obs_neg:\n    forall f v1 v2\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.neg v1) (Val.neg v2).\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1; inversion Hval_obs; subst;\n    simpl...\n  Qed.\n\n  Lemma val_obs_sub:\n    forall f v1 v2 v1' v2'\n      (Hinjective: forall b1 b1' b2,\n          f b1 = Some b2 -> f b1' = Some b2 -> b1 = b1')\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.sub v1 v1') (Val.sub v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n    destruct (eq_block b b0); subst.\n    rewrite H6 in H2; inversion H2; subst.\n    destruct (eq_block b2 b2)...\n      by exfalso.\n      destruct (eq_block b2 b4)...\n      subst.\n      assert (b0 = b)\n        by (eapply Hinjective; eauto).\n      subst.\n        by exfalso.\n  Qed.\n\n  (** Floating point functions *)\n  Lemma val_obs_addf:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.addf v1 v1') (Val.addf v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_addfs:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.addfs v1 v1') (Val.addfs v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_mulf:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.mulf v1 v1') (Val.mulf v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_mulfs:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.mulfs v1 v1') (Val.mulfs v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_negf:\n    forall f v1 v2\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.negf v1) (Val.negf v2).\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1; inversion Hval_obs;\n    subst; simpl...\n  Qed.\n\n  Lemma val_obs_negfs:\n    forall f v1 v2\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.negfs v1) (Val.negfs v2).\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1; inversion Hval_obs;\n    subst; simpl...\n  Qed.\n\n  Lemma val_obs_absf:\n    forall f v1 v2\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.absf v1) (Val.absf v2).\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1; inversion Hval_obs;\n    subst; simpl...\n  Qed.\n\n  Lemma val_obs_absfs:\n    forall f v1 v2\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.absfs v1) (Val.absfs v2).\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1; inversion Hval_obs;\n    subst; simpl...\n  Qed.\n\n  Lemma val_obs_subf:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.subf v1 v1') (Val.subf v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_subfs:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.subfs v1 v1') (Val.subfs v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_divf:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.divf v1 v1') (Val.divf v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma val_obs_divfs:\n    forall f v1 v2 v1' v2'\n      (Hval_obs': val_obs f v1' v2')\n      (Hval_obs: val_obs f v1 v2),\n      val_obs f (Val.divfs v1 v1') (Val.divfs v2 v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl...\n  Qed.\n\n  Lemma divu_ren:\n    forall f v1 v2 v1' v2'\n      (Hval_obs: val_obs f v1 v1')\n      (Hval_obs': val_obs f v2 v2'),\n      Val.divu v1 v2 = Val.divu v1' v2'.\n  Proof.\n    intros.\n    destruct v1; inversion Hval_obs; subst;\n    destruct v2; inversion Hval_obs'; subst; simpl in *;\n    auto.\n  Qed.\n\n  Lemma modu_ren:\n    forall f v1 v2 v1' v2'\n      (Hval_obs: val_obs f v1 v1')\n      (Hval_obs': val_obs f v2 v2'),\n      Val.modu v1 v2 = Val.modu v1' v2'.\n  Proof.\n    intros.\n    destruct v1; inversion Hval_obs; subst;\n    destruct v2; inversion Hval_obs'; subst; simpl in *;\n    auto.\n  Qed.\n\n  Lemma val_obs_divu_id:\n    forall f v1 v2 v,\n      Val.divu v1 v2 = Some v ->\n      val_obs f v v.\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v2; simpl in *; try discriminate.\n    destruct (Int.eq i0 Int.zero); try discriminate.\n    inversion H...\n  Qed.\n\n  Lemma val_obs_modu_id:\n    forall f v1 v2 v,\n      Val.modu v1 v2 = Some v ->\n      val_obs f v v.\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v2; simpl in *; try discriminate.\n    destruct (Int.eq i0 Int.zero); try discriminate.\n    inversion H...\n  Qed.\n\n  Lemma divs_ren:\n    forall f v1 v2 v1' v2'\n      (Hval_obs: val_obs f v1 v1')\n      (Hval_obs': val_obs f v2 v2'),\n      Val.divs v1 v2 = Val.divs v1' v2'.\n  Proof.\n    intros.\n    destruct v1; inversion Hval_obs; subst;\n    destruct v2; inversion Hval_obs'; subst; simpl in *;\n    auto.\n  Qed.\n\n  Lemma mods_ren:\n    forall f v1 v2 v1' v2'\n      (Hval_obs: val_obs f v1 v1')\n      (Hval_obs': val_obs f v2 v2'),\n      Val.mods v1 v2 = Val.mods v1' v2'.\n  Proof.\n    intros.\n    destruct v1; inversion Hval_obs; subst;\n    destruct v2; inversion Hval_obs'; subst; simpl in *;\n    auto.\n  Qed.\n\n  Lemma val_obs_divs_id:\n    forall f v1 v2 v,\n      Val.divs v1 v2 = Some v ->\n      val_obs f v v.\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v2; simpl in *; try discriminate.\n    match goal with\n    | [H: match ?Expr with _ => _ end = _ |- _] =>\n      destruct Expr\n    end; try discriminate.\n    inversion H...\n  Qed.\n\n  Lemma val_obs_mods_id:\n    forall f v1 v2 v,\n      Val.mods v1 v2 = Some v ->\n      val_obs f v v.\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v2; simpl in *; try discriminate.\n    match goal with\n    | [H: match ?Expr with _ => _ end = _ |- _] =>\n      destruct Expr\n    end; try discriminate.\n    inversion H...\n  Qed.\n\n  Lemma val_obs_of_bool:\n    forall f b,\n      val_obs f (Val.of_bool b) (Val.of_bool b).\n  Proof.\n    intros.\n    destruct b; simpl; constructor.\n  Qed.\n\n  Hint Resolve\n       val_obs_add valid_val_incr val_obs_incr val_obsC_correct\n       val_obs_load_result val_obs_hiword val_obs_loword\n       val_obs_longofwords val_obs_load_result val_obs_ext\n       val_obs_sign_ext val_obs_singleoffloat val_obs_floatofsingle\n       val_obs_intoffloat val_obs_floatofint val_obs_intofsingle\n       val_obs_singleofint val_obs_neg\n       val_obs_mul val_obs_mulhs val_obs_mulhu\n       val_obs_and val_obs_sub\n       val_obs_or val_obs_xor val_obs_notint\n       val_obs_shl val_obs_shr val_obs_shru\n       val_obs_ror val_obs_suboverflow val_obs_negative\n       val_obs_addf val_obs_addfs val_obs_mulf\n       val_obs_mulfs val_obs_negf val_obs_negfs\n       val_obs_absf val_obs_absfs val_obs_subf\n       val_obs_subfs val_obs_divf val_obs_divfs\n       val_obs_divu_id val_obs_modu_id\n       val_obs_divs_id val_obs_mods_id val_obs_of_bool : val_renamings.\n\nEnd ValObsEq.\n\n(** ** Renamings between memories *)\nModule MemObsEq.\n\n  Import ValObsEq ValueWD MemoryWD Renamings MemoryLemmas.\n\n  (* A compcert injection would not work because it allows permissions to go up *)\n  (* Moreover, we require that undefined values are matched by the\n     target memory, unlike compcert injections. Although the latter is\n     not neccessary and in retrospect may be a limiting factor. For\n     example we would be able to reuse this development for our final\n     erasure if we allowed undefined values to become more defined. *)\n\n  (** Weak injection between memories *)\n  Record weak_mem_obs_eq (f : memren) (mc mf : mem) :=\n    {\n      domain_invalid: forall b, ~(Mem.valid_block mc b) -> f b = None;\n      domain_valid: forall b, Mem.valid_block mc b -> exists b', f b = Some b';\n      codomain_valid: forall b1 b2, f b1 = Some b2 -> Mem.valid_block mf b2;\n      injective: forall b1 b1' b2, f b1 = Some b2 ->\n                              f b1' = Some b2 ->\n                              b1 = b1';\n      perm_obs_weak :\n        forall b1 b2 ofs (Hrenaming: f b1 = Some b2),\n          Mem.perm_order''\n            (permission_at mc b1 ofs Cur)\n            (permission_at mf b2 ofs Cur)}.\n\n\n\n  (** Strong injection between memories *)\n  Record strong_mem_obs_eq (f : memren) (mc mf : mem) :=\n    { perm_obs_strong :\n        forall b1 b2 ofs (Hrenaming: f b1 = Some b2),\n            permission_at mf b2 ofs Cur =\n            (permission_at mc b1 ofs Cur);\n      val_obs_eq :\n        forall b1 b2 ofs (Hrenaming: f b1 = Some b2)\n          (Hperm: Mem.perm mc b1 ofs Cur Readable),\n          memval_obs_eq f (Maps.ZMap.get ofs mc.(Mem.mem_contents)#b1)\n                        (Maps.ZMap.get ofs mf.(Mem.mem_contents)#b2)}.\n\n\n  (** Renaming between memories *)\n  Record mem_obs_eq (f : memren) (mc mf : mem) :=\n    { weak_obs_eq : weak_mem_obs_eq f mc mf;\n      strong_obs_eq : strong_mem_obs_eq f mc mf }.\n\n  Lemma weak_obs_eq_domain_ren:\n    forall f m m',\n      weak_mem_obs_eq f m m' ->\n      domain_memren f m.\n  Proof.\n    intros f m m' Hobs_eq.\n    destruct Hobs_eq.\n    intros b. split;\n    intros Hb.\n    specialize (domain_valid0 _ Hb).\n    destruct (domain_valid0) as [? H].\n    rewrite H;\n      by auto.\n    destruct (valid_block_dec m b); auto.\n    specialize (domain_invalid0 _ n).\n    rewrite domain_invalid0 in Hb;\n      by exfalso.\n  Qed.\n\n  Corollary mem_obs_eq_domain_ren:\n    forall f m m',\n      mem_obs_eq f m m' ->\n      domain_memren f m.\n  Proof.\n    intros f m m' H; destruct H;\n    eapply weak_obs_eq_domain_ren;\n      by eauto.\n  Qed.\n\n  Lemma mem_obs_eq_setMaxPerm :\n    forall m,\n      valid_mem m ->\n      mem_obs_eq (id_ren m) m (setMaxPerm m).\n  Proof with eauto with renamings id_renamings val_renamings.\n    intros.\n    constructor; constructor;\n      eauto with id_renamings; unfold id_ren; intros;\n        repeat match goal with\n               | [H: context[valid_block_dec ?M ?B] |- _] =>\n                 destruct (valid_block_dec M B); simpl in *\n               | [H: _ = Some _ |- _] => inv H; clear H\n               end; auto.\n    rewrite setMaxPerm_Cur;\n      apply po_refl.\n    rewrite setMaxPerm_Cur; auto.\n    destruct (ZMap.get ofs (Mem.mem_contents m) # b2) eqn:Hget;\n      constructor.\n    destruct v0; constructor.\n    specialize (H _ v _ _ Hget).\n    simpl in H.\n    (*this gives an anomaly:\n  erewrite Coqlib2.if_true with (E:= {Mem.valid_block m b} + {~ Mem.valid_block m b}).\n     *)\n    destruct (valid_block_dec m b); simpl; tauto.\n  Qed.\n\n  Lemma mem_obs_eq_id :\n    forall m,\n      valid_mem m ->\n      mem_obs_eq (id_ren m) m m.\n  Proof with eauto with renamings id_renamings val_renamings.\n    intros.\n    constructor; constructor;\n      eauto with id_renamings; unfold id_ren; intros;\n        repeat match goal with\n               | [H: context[valid_block_dec ?M ?B] |- _] =>\n                 destruct (valid_block_dec M B); simpl in *\n               | [H: _ = Some _ |- _] => inv H; clear H\n               end; auto.\n    now apply po_refl.\n    destruct (ZMap.get ofs (Mem.mem_contents m) # b2) eqn:Hget;\n      constructor.\n    destruct v0; constructor.\n    specialize (H _ v _ _ Hget).\n    simpl in H.\n    destruct (valid_block_dec m b); simpl; tauto.\n  Qed.\n\n  Lemma mem_obs_eq_extend:\n    forall m1 m1' m2' f pmap pmap'\n      (Hlt1: permMapLt pmap (getMaxPerm m1))\n      (Hlt1': permMapLt pmap' (getMaxPerm m1'))\n      (Hlt2': permMapLt pmap' (getMaxPerm m2'))\n      (Hmem_obs_eq: mem_obs_eq f (restrPermMap Hlt1) (restrPermMap Hlt1'))\n      (Hextend': forall b, Mem.valid_block m1' b -> Mem.valid_block m2' b)\n      (Hstable: forall b ofs, Mem.perm (restrPermMap Hlt1') b ofs Cur Readable ->\n                         ZMap.get ofs (Mem.mem_contents m1') # b = ZMap.get ofs (Mem.mem_contents m2') # b),\n      mem_obs_eq f (restrPermMap Hlt1) (restrPermMap Hlt2').\n  Proof.\n    intros.\n    destruct Hmem_obs_eq.\n    constructor.\n    destruct weak_obs_eq0.\n    econstructor; eauto.\n    intros; erewrite restrPermMap_valid.\n    eapply Hextend'.\n    eapply codomain_valid0; eauto.\n    intros.\n    rewrite! restrPermMap_Cur.\n    specialize (perm_obs_weak0 _ _ ofs Hrenaming).\n    rewrite! restrPermMap_Cur in perm_obs_weak0.\n    eauto.\n    destruct strong_obs_eq0.\n    assert (Hperm_eq: forall (b1 b2 : block) (ofs : Z),\n               f b1 = Some b2 ->\n               permission_at (restrPermMap Hlt2') b2 ofs Cur =\n               permission_at (restrPermMap Hlt1) b1 ofs Cur).\n    { intros; rewrite! restrPermMap_Cur.\n      specialize (perm_obs_strong0 _ _ ofs H).\n      rewrite! restrPermMap_Cur in perm_obs_strong0.\n      assumption.\n    }\n    constructor; eauto.\n    intros.\n    simpl.\n    erewrite <- Hstable.\n    eapply val_obs_eq0; eauto.\n    unfold permission_at, Mem.perm in *.\n    erewrite <- perm_obs_strong0 in Hperm; eauto.\n  Qed.\n\n  Lemma mapped_dec :\n    forall (f : positive -> option positive) m j\n      (Hdomain_invalid : forall b, ~ (b < m)%positive -> f b = None)\n      (Hdomain_valid : forall b, (b < m)%positive -> exists b', f b = Some b'),\n      (exists i, f i = Some j) \\/ ~ exists i, f i = Some j.\n  Proof.\n    intros f m.\n    generalize dependent f.\n    induction m using Pos.peano_ind.\n    - intros.\n      right.\n      intros (i & Hcontra).\n      specialize (Hdomain_invalid i ltac:(zify; omega)).\n      now congruence.\n    - intros.\n      destruct (f m) as [last|] eqn:Hf_last.\n      + destruct (Pos.eq_dec last j); subst.\n        * left; eexists; eauto.\n        * pose (g x := if plt x m then f x else None).\n          specialize (IHm g j).\n          unfold g in IHm.\n          edestruct IHm.\n          intros.\n          destruct (plt b m); simpl; eauto.\n          intros.\n          destruct (plt b m); simpl.\n          eapply Hdomain_valid. zify; omega.\n          exfalso.\n          unfold Plt in n0.\n          now auto.\n          destruct H as [i Hfi].\n          destruct (plt i m); simpl in Hfi; try discriminate.\n          left; eexists; now eauto.\n          right.\n          intros (i & Hcontra).\n          destruct (plt i m).\n          apply H.\n          exists i.\n          destruct (plt i m); simpl; auto.\n          exfalso; auto.\n          unfold Plt in n0.\n          apply Pos.le_nlt in n0.\n          apply Pos.lt_eq_cases in n0.\n          destruct n0 as [Hlt | Heq].\n          specialize (Hdomain_invalid i ltac:(apply Pos.le_nlt; zify; omega)).\n          now congruence.\n          subst.\n          rewrite Hcontra in Hf_last.\n          inv Hf_last; now auto.\n      + exfalso.\n        destruct (Hdomain_valid m ltac:(zify; omega)).\n        congruence.\n  Qed.\n\n  Axiom EM: ClassicalFacts.excluded_middle.\n  Lemma pigeon_positive:\n    forall (n m: positive) (f: positive -> option positive),\n      (forall i, (i < n)%positive ->\n            exists j, (j < m)%positive /\\ f i = Some j) ->\n      (forall i i' j j',\n          f i = Some j -> f i' = Some j' ->\n          i<>i' -> j<>j') ->\n      (n <= m)%positive.\n  Proof.\n    induction n using Pos.peano_ind; intros;\n      first by (zify; omega).\n    assert (Hlast: exists last, f n = Some last /\\ (last<m)%positive).\n    { destruct (H n) as [last [? ?]]. zify; omega.\n      exists last; auto.\n    }\n    destruct Hlast as [last [Hf_last Hlast_m]].\n    destruct m using Pos.peano_ind.\n    - exfalso;\n        eapply Pos.nlt_1_r;\n        now eauto.\n    - clear IHm.\n      assert (Hmapped: (exists i, f i = Some m) \\/ ~ (exists i, f i = Some m))\n        by (apply EM).\n      destruct Hmapped as [Hmapped | Hunmapped].\n      + destruct Hmapped as [i Hf].\n        pose (g x := if Pos.eq_dec x i then Some last else if Pos.eq_dec x n then Some m else f x).\n        specialize (IHn m g).\n        assert ((n <= m)%positive);\n               [ | zify; omega].\n        apply IHn.\n        intros. unfold g.\n        destruct (Pos.eq_dec i0 i); subst; simpl.\n        * exists last; split; eauto.\n          assert (last <> m)\n            by (apply (H0 _ _ _ _ Hf_last Hf);\n                zify; omega).\n          zify; omega.\n          destruct (Pos.eq_dec i0 n); subst; simpl;\n            first by (zify; omega).\n          generalize (H i0); intros.\n          destruct H2 as [j [? ?]]. zify; omega.\n          exists j; split; auto.\n          assert (j <> m); [ | zify; omega].\n          apply (H0 _ _ _ _ H3 Hf); auto.\n          intros.\n          unfold g in H1, H2.\n          destruct (Pos.eq_dec i0 i); subst; simpl in *; inv H1.\n          { destruct (Pos.eq_dec i' i); subst; simpl in *; inv H2.\n            - zify; omega.\n            - destruct (Pos.eq_dec i' n); subst; simpl in *; inv H4.\n              + eapply H0; try eassumption.\n              + eapply H0; try eassumption. zify; omega.\n          }\n          { destruct (Pos.eq_dec i' i); subst; simpl in *; inv H2.\n            - destruct (Pos.eq_dec i0 n); subst; simpl in *; inv H5.\n              + eapply H0; try eauto.\n              + eapply H0; try eassumption.\n            - destruct (Pos.eq_dec i0 n); subst; simpl in *; inv H5.\n              + destruct (Pos.eq_dec i' n); subst; simpl in *; inv H4;\n                eapply H0; eauto.\n              + destruct (Pos.eq_dec i' n); subst; simpl in *; inv H4;\n                  eapply H0; eauto.\n          }\n      + assert (n <= m)%positive; [ | zify; omega].\n        apply (IHn m f).\n        intros.\n        destruct (H i). zify; omega. destruct H2; exists x; split; auto.\n        assert (x<>m). contradict Hunmapped; subst.\n        exists i; subst; auto.\n        zify; omega.\n        intros.\n        apply (H0 _ _ _ _ H1 H2).\n        now auto.\n  Qed.\n\n  (** If a memory [m] injects into a memory [m'] then [m'] is at least\nas big as [m] *)\n  Lemma weak_mem_obs_eq_nextblock:\n    forall f m m'\n      (Hobs_eq: weak_mem_obs_eq f m m'),\n      (Mem.nextblock m <= Mem.nextblock m')%positive.\n  Proof.\n    intros.\n    pose proof (domain_valid Hobs_eq).\n    pose proof (codomain_valid Hobs_eq).\n    pose proof (injective Hobs_eq).\n    eapply pigeon_positive with (f := f); eauto.\n    intros.\n    destruct (H _ H2).\n    specialize (H0 _ _ H3).\n    unfold Mem.valid_block, Plt in *.\n    eexists; split;\n      now eauto.\n    intros.\n    intro Hcontra. subst.\n    now eauto.\n  Qed.\n\n  Lemma mf_align :\n    forall (m : mem) (f : memren) (b1 b2 : block) (delta : Z) (chunk : memory_chunk)\n      (ofs : Z) (p : permission),\n      f b1 = Some b2 ->\n      Mem.range_perm m b1 ofs (ofs + size_chunk chunk) Max p ->\n      (align_chunk chunk | 0%Z)%Z.\n  Proof.\n    intros.\n      by apply mem_wd.align_chunk_0.\n  Qed.\n\n  Lemma memval_obs_eq_incr:\n    forall (mc mf : mem) (f f': memren)\n      (b1 b2 : block) (ofs : Z)\n      (Hf': f' b1 = Some b2)\n      (Hincr: ren_incr f f')\n      (Hobs_eq: memval_obs_eq f (Maps.ZMap.get ofs (Mem.mem_contents mc) # b1)\n                              (Maps.ZMap.get ofs (Mem.mem_contents mf) # b2)),\n      memval_obs_eq f' (Maps.ZMap.get ofs (Mem.mem_contents mc) # b1)\n                    (Maps.ZMap.get ofs (Mem.mem_contents mf) # b2).\n  Proof.\n    intros.\n    inversion Hobs_eq;\n      constructor.\n    inversion Hval_obs; subst; constructor.\n    apply Hincr in H1.\n      by auto.\n  Qed.\n\n  (* Proof as in compcert*)\n  Lemma proj_bytes_obs:\n    forall (f : memren) (vl vl' : seq memval),\n      Coqlib.list_forall2 (memval_obs_eq f) vl vl' ->\n      forall bl : seq byte,\n        proj_bytes vl = Some bl -> proj_bytes vl' = Some bl.\n  Proof.\n    induction 1; simpl. intros. congruence.\n    inversion H; subst; try congruence.\n    destruct (proj_bytes al); intros.\n    inversion H; subst; rewrite (IHlist_forall2 l); auto.\n    congruence.\n  Qed.\n\n  Lemma proj_bytes_obs_none:\n    forall (f : memren) (vl vl' : seq memval),\n      Coqlib.list_forall2 (memval_obs_eq f) vl vl' ->\n      proj_bytes vl = None -> proj_bytes vl' = None.\n  Proof.\n    induction 1; simpl. intros.  congruence.\n    inversion H; subst; try congruence.\n    destruct (proj_bytes al); intros.\n    discriminate.\n      by rewrite (IHlist_forall2 (Logic.eq_refl _)).\n  Qed.\n\n  Lemma val_obs_equal:\n    forall f v1 v1' v2 v2'\n      (Hinjective: forall b1 b1' b2, f b1 = Some b2 -> f b1' = Some b2 -> b1 = b1')\n      (Hval1: val_obs f v1 v1')\n      (Hval2: val_obs f v2 v2'),\n      Val.eq v1 v2 <-> Val.eq v1' v2'.\n  Proof.\n    intros.\n    destruct v1; inv Hval1;\n    split; intro H;\n    match goal with\n    | [H: is_true (proj_sumbool (Val.eq ?V1 ?V2)) |- _] =>\n      destruct (Val.eq V1 V2)\n    end; subst; try (by exfalso);\n    inv Hval2; auto;\n    match goal with\n    | [|- is_true (proj_sumbool (Val.eq ?V1 ?V2))] =>\n      destruct (Val.eq V1 V2)\n    end; auto.\n    rewrite H2 in H4; inv H4; auto.\n    specialize (Hinjective _ _ _ H2 H3); subst.\n    auto.\n  Qed.\n\n  Lemma check_value_obs:\n    forall f n vl vl' v v' q\n      (Hf: forall b1 b1' b2, f b1 = Some b2 -> f b1' = Some b2 -> b1 = b1'),\n      Coqlib.list_forall2 (memval_obs_eq f) vl vl' ->\n      val_obs f v v' ->\n      check_value n v q vl = check_value n v' q vl'.\n  Proof.\n    intros f n.\n    induction n; intros; simpl in *.\n    destruct vl; inv H; auto.\n    destruct vl; inv H; auto.\n    destruct m; inv H3; auto.\n    erewrite IHn; eauto.\n    assert (Val.eq v v0 <-> Val.eq v' v2)\n      by (eapply val_obs_equal; eauto).\n    destruct (Val.eq v v0) eqn:?.\n    destruct (Val.eq v' v2); auto.\n    exfalso. specialize ((proj1 H) ltac:(auto)); auto.\n    destruct (Val.eq v' v2); auto.\n    exfalso. specialize ((proj2 H) ltac:(auto)); auto.\n  Qed.\n\n\n  Lemma proj_value_obs:\n    forall f q vl1 vl2,\n      (forall b1 b1' b2 : block, f b1 = Some b2 -> f b1' = Some b2 -> b1 = b1') ->\n      Coqlib.list_forall2 (memval_obs_eq f) vl1 vl2 ->\n      val_obs f (proj_value q vl1) (proj_value q vl2).\n  Proof.\n    intros f q vl1 v2 Hinjective Hlst. unfold proj_value.\n    inversion Hlst; subst. constructor.\n    inversion H; subst; try constructor.\n    erewrite check_value_obs; eauto.\n    destruct (check_value (size_quantity_nat q) v2 q (Fragment v2 q0 n :: bl));\n      eauto with val_renamings.\n  Qed.\n\n  Lemma load_result_obs:\n    forall f chunk v1 v2,\n      val_obs f v1 v2 ->\n      val_obs f (Val.load_result chunk v1) (Val.load_result chunk v2).\n  Proof.\n    intros. inversion H; destruct chunk; simpl; econstructor; eauto.\n  Qed.\n\n  Lemma decode_val_obs:\n    forall f vl1 vl2 chunk,\n      (forall b1 b1' b2 : block, f b1 = Some b2 -> f b1' = Some b2 -> b1 = b1') ->\n      Coqlib.list_forall2 (memval_obs_eq f) vl1 vl2 ->\n      val_obs f (decode_val chunk vl1) (decode_val chunk vl2).\n  Proof.\n    intros f vl1 vl2 chunk Hinjective Hobs_eq.\n    unfold decode_val.\n    destruct (proj_bytes vl1) as [bl1|] eqn:PB1.\n    eapply proj_bytes_obs with (vl' := vl2) in PB1; eauto.\n    rewrite PB1.\n    destruct chunk; constructor.\n    destruct (proj_bytes vl2) eqn:PB2.\n    exfalso.\n    eapply proj_bytes_obs_none with (f := f) (vl := vl1) in PB1;\n      eauto.\n      by congruence.\n      destruct chunk; try constructor;\n      apply load_result_obs;\n      apply proj_value_obs; auto.\n  Qed.\n\n  Lemma valid_access_obs_eq:\n    forall f m1 m2 b1 b2 chunk ofs p,\n      strong_mem_obs_eq f m1 m2 ->\n      f b1 = Some b2 ->\n      Mem.valid_access m1 chunk b1 ofs p ->\n      Mem.valid_access m2 chunk b2 ofs p.\n  Proof.\n    intros. destruct H1 as [A B]. constructor; auto.\n    intros ofs' Hofs.\n    specialize (A ofs' Hofs).\n    destruct H.\n    specialize (perm_obs_strong0 _ _ ofs' H0).\n    unfold permission_at in *.\n    unfold Mem.perm in *.\n    rewrite perm_obs_strong0; auto.\n  Qed.\n\n  Lemma getN_obs:\n    forall f m1 m2 b1 b2,\n      strong_mem_obs_eq f m1 m2 ->\n      f b1 = Some b2 ->\n      forall n ofs,\n        Mem.range_perm m1 b1 ofs (ofs + Z_of_nat n) Cur Readable ->\n        list_forall2 (memval_obs_eq f)\n                     (Mem.getN n ofs (m1.(Mem.mem_contents)#b1))\n                     (Mem.getN n ofs (m2.(Mem.mem_contents)#b2)).\n  Proof.\n    induction n; intros; simpl.\n    constructor.\n    rewrite inj_S in H1.\n    destruct H.\n    constructor.\n    eapply val_obs_eq0; eauto.\n    apply H1. omega.\n    apply IHn. red; intros; apply H1; omega.\n  Qed.\n\n  Transparent Mem.load.\n  Lemma load_val_obs:\n    forall (mc mf : mem) (f:memren)\n      (b1 b2 : block) chunk (ofs : Z) v1\n      (Hload: Mem.load chunk mc b1 ofs = Some v1)\n      (Hf: f b1 = Some b2)\n      (Hinjective: forall b0 b1' b3 : block, f b0 = Some b3 -> f b1' = Some b3 -> b0 = b1')\n      (Hobs_eq: strong_mem_obs_eq f mc mf),\n    exists v2,\n      Mem.load chunk mf b2 ofs = Some v2 /\\\n      val_obs f v1 v2.\n  Proof.\n    intros.\n    exists (decode_val chunk (Mem.getN (size_chunk_nat chunk) ofs (mf.(Mem.mem_contents)#b2))).\n    split. unfold Mem.load. apply pred_dec_true.\n    eapply valid_access_obs_eq; eauto.\n    eapply Mem.load_valid_access; eauto.\n    exploit Mem.load_result; eauto. intro. rewrite H.\n    apply decode_val_obs; auto.\n    apply getN_obs; auto.\n    rewrite <- size_chunk_conv.\n    exploit Mem.load_valid_access; eauto. intros [A B]. auto.\n  Qed.\n  Opaque Mem.load.\n\n  Lemma loadv_val_obs:\n    forall (mc mf : mem) (f:memren)\n      (vptr1 vptr2 : val) chunk v1\n      (Hload: Mem.loadv chunk mc vptr1 = Some v1)\n      (Hf: val_obs f vptr1 vptr2)\n      (Hinjective: forall b0 b1' b3 : block, f b0 = Some b3 -> f b1' = Some b3 -> b0 = b1')\n      (Hobs_eq: strong_mem_obs_eq f mc mf),\n    exists v2,\n      Mem.loadv chunk mf vptr2 = Some v2 /\\\n      val_obs f v1 v2.\n  Proof.\n    intros.\n    unfold Mem.loadv in *.\n    destruct vptr1; try discriminate.\n    inversion Hf; subst.\n    eapply load_val_obs in Hload; eauto.\n  Qed.\n\n  (** ** Lemmas about [Mem.store] and [mem_obs_eq]*)\n\n  Lemma encode_val_obs_eq:\n    forall (f : memren) (v1 v2 : val) (chunk : memory_chunk),\n      val_obs f v1 v2 ->\n      list_forall2 (memval_obs_eq f) (encode_val chunk v1)\n                   (encode_val chunk v2).\n  Proof.\n    intros.\n    destruct v1; inversion H; subst; destruct chunk;\n    simpl; repeat constructor; auto.\n  Qed.\n\n  Lemma setN_obs_eq :\n    forall (access : Z -> Prop) (f : memren) (vl1 vl2 : seq memval),\n      list_forall2 (memval_obs_eq f) vl1 vl2 ->\n      forall (p : Z) (c1 c2 : ZMap.t memval),\n        (forall q : Z,\n            access q ->\n            memval_obs_eq f (ZMap.get q c1) (ZMap.get q c2)) ->\n        forall q : Z,\n          access q ->\n          memval_obs_eq f (ZMap.get q (Mem.setN vl1 p c1))\n                        (ZMap.get q (Mem.setN vl2 p c2)).\n  Proof.\n    induction 1; intros; simpl.\n    auto.\n    apply IHlist_forall2; auto.\n    intros. erewrite ZMap.gsspec at 1. destruct (ZIndexed.eq q0 p). subst q0.\n    rewrite ZMap.gss. auto.\n    rewrite ZMap.gso. auto. unfold ZIndexed.t in *. omega.\n  Qed.\n\n\n  (** Storing related values on related memories results in related memories*)\n  Transparent Mem.store.\n  Lemma store_val_obs:\n    forall (mc mc' mf : mem) (f:memren)\n      (b1 b2 : block) chunk (ofs: Z) v1 v2\n      (Hstore: Mem.store chunk mc b1 ofs v1 = Some mc')\n      (Hf: f b1 = Some b2)\n      (Hval_obs_eq: val_obs f v1 v2)\n      (Hobs_eq: mem_obs_eq f mc mf),\n    exists mf',\n      Mem.store chunk mf b2 ofs v2 = Some mf' /\\\n      mem_obs_eq f mc' mf'.\n  Proof.\n    intros.\n    pose proof (strong_obs_eq Hobs_eq) as Hstrong_obs_eq.\n    assert (HvalidF: Mem.valid_access mf chunk b2 ofs Writable).\n      by (eapply valid_access_obs_eq; eauto with mem).\n    destruct (Mem.valid_access_store _ _ _ _ v2 HvalidF) as [mf' HstoreF].\n    exists mf'; split. auto.\n    constructor.\n    { pose proof (weak_obs_eq Hobs_eq).\n      inversion H.\n      constructor; simpl; auto; intros.\n      eapply domain_invalid0. intro Hcontra.\n      eapply Mem.store_valid_block_1 in Hcontra; eauto.\n      eapply Mem.store_valid_block_2 in H0; eauto.\n      eapply Mem.store_valid_block_1; eauto.\n      assert (H1 := mem_store_cur _ _ _ _ _ _ Hstore b0 ofs0).\n      assert (H2 := mem_store_cur _ _ _ _ _ _ HstoreF b3 ofs0).\n      do 2 rewrite getCurPerm_correct in H1.\n      do 2 rewrite getCurPerm_correct in H2.\n      rewrite <- H1.\n      rewrite <- H2.\n      eauto.\n    }\n    { destruct Hstrong_obs_eq.\n      constructor.\n      - intros.\n        assert (H1 := mem_store_cur _ _ _ _ _ _ Hstore b0 ofs0).\n        assert (H2 := mem_store_cur _ _ _ _ _ _ HstoreF b3 ofs0).\n        do 2 rewrite getCurPerm_correct in H1.\n        do 2 rewrite getCurPerm_correct in H2.\n        rewrite <- H1.\n        rewrite <- H2.\n        eauto.\n      - intros.\n        eapply Mem.perm_store_2 in Hperm; eauto.\n        rewrite (Mem.store_mem_contents _ _ _ _ _ _ Hstore).\n        rewrite (Mem.store_mem_contents _ _ _ _ _ _ HstoreF).\n        clear Hstore HstoreF.\n        destruct (Pos.eq_dec b1 b0).\n        + subst.\n          assert (b2 = b3)\n            by (rewrite Hrenaming in Hf; inversion Hf; subst; auto).\n          subst b3.\n          do 2 rewrite Maps.PMap.gss.\n          destruct (Intv.In_dec ofs0\n                                (ofs,\n                                 (ofs + Z.of_nat (length (encode_val chunk v1)))%Z)).\n          * apply setN_obs_eq with\n            (access := fun ofs => Mem.perm mc b0 ofs Cur Readable); auto.\n            eapply encode_val_obs_eq; eauto.\n          * apply Intv.range_notin in n.\n            simpl in n.\n            erewrite Mem.setN_outside by eauto.\n            apply encode_val_obs_eq with (chunk := chunk) in Hval_obs_eq.\n            apply list_forall2_length in Hval_obs_eq. rewrite Hval_obs_eq in n.\n            erewrite Mem.setN_outside by eauto.\n            eauto.\n            clear.\n            simpl.\n            apply ofs_val_lt.\n        + rewrite Maps.PMap.gso; auto.\n          rewrite Maps.PMap.gso; auto.\n          intros Hcontra. subst.\n          pose proof (injective (weak_obs_eq Hobs_eq)).\n          specialize (H _ _ _ Hrenaming Hf). auto.\n    }\n  Qed.\n  Opaque Mem.store.\n\n  Lemma storev_val_obs:\n    forall (mc mc' mf : mem) (f:memren)\n      (vptr1 vptr2: val) chunk v1 v2\n      (Hstore: Mem.storev chunk mc vptr1 v1 = Some mc')\n      (Hf: val_obs f vptr1 vptr2)\n      (Hval_obs_eq: val_obs f v1 v2)\n      (Hobs_eq: mem_obs_eq f mc mf),\n    exists mf',\n      Mem.storev chunk mf vptr2 v2 = Some mf' /\\\n      mem_obs_eq f mc' mf'.\n  Proof.\n    intros.\n    unfold Mem.storev in *.\n    destruct vptr1; try discriminate.\n    inversion Hf; subst.\n    eapply store_val_obs in Hstore; eauto.\n  Qed.\n\n  Lemma mem_obs_eq_storeF:\n    forall f mc mf mf' chunk b ofs v pmap pmap2\n      (Hlt: permMapLt pmap (getMaxPerm mf))\n      (Hlt': permMapLt pmap (getMaxPerm mf'))\n      (Hlt2: permMapLt pmap2 (getMaxPerm mf))\n      (Hstore: Mem.store chunk (restrPermMap Hlt2) b ofs v = Some mf')\n      (Hdisjoint: permMapCoherence pmap pmap2 \\/ permMapsDisjoint pmap pmap2)\n      (Hobs_eq: mem_obs_eq f mc (restrPermMap Hlt)),\n      mem_obs_eq f mc (restrPermMap Hlt').\n  Proof.\n    intros.\n    destruct Hobs_eq as [Hweak_obs_eq Hstrong_obs_eq].\n    destruct Hweak_obs_eq.\n    constructor.\n    (* weak_obs_eq *)\n    constructor; auto.\n    intros b1 b2 Hf.\n    erewrite restrPermMap_valid.\n    specialize (codomain_valid0 _ _ Hf).\n    erewrite restrPermMap_valid in codomain_valid0.\n    eapply Mem.store_valid_block_1;\n      by eauto.\n    intros b1 b2 ofs0 Hf.\n    specialize (perm_obs_weak0 _ _ ofs0 Hf).\n    rewrite restrPermMap_Cur in perm_obs_weak0;\n      by rewrite restrPermMap_Cur.\n    destruct Hstrong_obs_eq.\n    constructor.\n    intros b1 b2 ofs0 Hf.\n    specialize (perm_obs_strong0 _ _ ofs0 Hf).\n    rewrite restrPermMap_Cur in perm_obs_strong0;\n      by rewrite restrPermMap_Cur.\n    intros b1 b2 ofs0 Hf Hperm.\n    simpl.\n    specialize (perm_obs_strong0 _ _ ofs0 Hf).\n    rewrite restrPermMap_Cur in perm_obs_strong0.\n    assert (Hstable: ~ Mem.perm (restrPermMap Hlt2) b2 ofs0 Cur Writable).\n    { intros Hcontra.\n      assert (Hcur := restrPermMap_Cur Hlt2 b2 ofs0).\n      unfold Mem.perm in *.\n      unfold permission_at in *.\n      rewrite <- perm_obs_strong0 in Hperm.\n      rewrite Hcur in Hcontra.\n      destruct Hdisjoint as [Hdisjoint | Hdisjoint];\n      specialize (Hdisjoint b2 ofs0);\n      clear - Hdisjoint Hcontra Hperm.\n      destruct (pmap # b2 ofs0) as [p1|];\n        destruct (pmap2 # b2 ofs0) as [p2|];\n        simpl in *; inversion Hperm; inversion Hcontra; subst;\n          auto.\n      eapply perm_order_clash; eauto.\n    }\n    erewrite store_contents_other with (m := restrPermMap Hlt2) (m' := mf')\n      by eauto.\n    simpl;\n      by auto.\n  Qed.\n\n  Lemma mem_obs_eq_disjoint_lock:\n    forall f  mc mf mc' mf' pmap pmapF bl1 bl2 ofsl sz\n      (Hf: f bl1 = Some bl2)\n      (Hlt: permMapLt pmap (getMaxPerm mc))\n      (HltF: permMapLt pmapF (getMaxPerm mf))\n      (Hlt': permMapLt pmap (getMaxPerm mc'))\n      (HltF': permMapLt pmapF (getMaxPerm mf'))\n      (Hvb : forall b : block, Mem.valid_block mc b <-> Mem.valid_block mc' b)\n      (HvbF : forall b : block, Mem.valid_block mf b <-> Mem.valid_block mf' b)\n      (Hobs_eq: mem_obs_eq f (restrPermMap Hlt) (restrPermMap HltF))\n      (Hlock: forall ofs, Intv.In ofs (ofsl, ofsl + sz)%Z ->\n                     memval_obs_eq f (ZMap.get ofs (Mem.mem_contents mc') # bl1)\n                                   (ZMap.get ofs (Mem.mem_contents mf') # bl2))\n      (Hstable: forall b ofs,\n          (b <> bl1 \\/ (b = bl1 /\\ ~ Intv.In ofs (ofsl, ofsl + sz)%Z)) ->\n          Mem.perm (restrPermMap Hlt) b ofs Cur Readable ->\n          ZMap.get ofs (Mem.mem_contents mc) # b = ZMap.get ofs (Mem.mem_contents mc') # b)\n      (HstableF: forall b ofs,\n          (b <> bl2 \\/ (b = bl2 /\\  ~ Intv.In ofs (ofsl, ofsl + sz)%Z)) ->\n          Mem.perm (restrPermMap HltF) b ofs Cur Readable ->\n          ZMap.get ofs (Mem.mem_contents mf) # b = ZMap.get ofs (Mem.mem_contents mf') # b),\n      mem_obs_eq f (restrPermMap Hlt') (restrPermMap HltF').\n  Proof.\n    intros.\n    destruct Hobs_eq as [Hweak_obs_eq Hstrong_obs_eq].\n    constructor.\n    - destruct Hweak_obs_eq.\n      constructor; intros; eauto.\n      + eapply domain_invalid0.\n        erewrite restrPermMap_valid in *.\n        intro Hcontra; eapply Hvb in Hcontra.\n        now auto.\n      + erewrite restrPermMap_valid in H.\n        erewrite <- Hvb in H.\n        now eauto.\n      + erewrite restrPermMap_valid.\n        apply HvbF.\n        eapply codomain_valid0;\n          now eauto.\n      + rewrite! restrPermMap_Cur.\n        specialize (perm_obs_weak0 _ _ ofs Hrenaming).\n        rewrite! restrPermMap_Cur in perm_obs_weak0.\n        assumption.\n    - destruct Hstrong_obs_eq.\n      constructor.\n      + intros.\n        rewrite! restrPermMap_Cur.\n        specialize (perm_obs_strong0 _ _ ofs Hrenaming).\n        rewrite! restrPermMap_Cur in perm_obs_strong0.\n        assumption.\n      + intros.\n        unfold Mem.perm in *.\n        pose proof (restrPermMap_Cur Hlt b1 ofs) as Hpmap.\n        pose proof (restrPermMap_Cur Hlt' b1 ofs) as Hpmap'.\n        unfold permission_at in *.\n        rewrite Hpmap' in Hperm.\n        rewrite <- Hpmap in Hperm.\n        specialize (val_obs_eq0 _ _ ofs Hrenaming Hperm).\n        simpl in val_obs_eq0; simpl.\n        destruct (Pos.eq_dec b1 bl1).\n        * subst.\n          assert (b2 = bl2)\n            by (rewrite Hf in Hrenaming; inversion Hrenaming; by subst);\n            subst.\n          destruct (Intv.In_dec ofs (ofsl, ofsl +sz)%Z);\n            first by (eapply Hlock; eauto).\n          erewrite <- Hstable by auto.\n          erewrite <- HstableF.\n          assumption.\n          right; auto.\n          erewrite perm_obs_strong0 by eauto.\n          assumption.\n        * erewrite <- Hstable by auto.\n          erewrite <- HstableF.\n          assumption.\n          left. intro Hcontra.\n          eapply (injective Hweak_obs_eq) in Hf;\n            subst b2; eauto.\n          erewrite perm_obs_strong0 by eauto.\n          assumption.\n  Qed.\n\n  Lemma mem_obs_eq_changePerm:\n    forall mc mf rmap rmapF rmap' rmapF' f\n      (Hlt: permMapLt rmap (getMaxPerm mc))\n      (HltF: permMapLt rmapF (getMaxPerm mf))\n      (Hlt': permMapLt rmap' (getMaxPerm mc))\n      (HltF': permMapLt rmapF' (getMaxPerm mf))\n      (Hrmap: forall b1 b2 ofs,\n          f b1 = Some b2 ->\n          rmap' # b1 ofs = rmapF' # b2 ofs)\n      (Hobs_eq: mem_obs_eq f (restrPermMap Hlt) (restrPermMap HltF))\n      (Hnew: forall b ofs, Mem.perm_order' (rmap' # b ofs) Readable ->\n                      Mem.perm_order' (rmap # b ofs) Readable),\n      mem_obs_eq f (restrPermMap Hlt') (restrPermMap HltF').\n  Proof.\n    intros.\n    destruct Hobs_eq.\n    constructor.\n    - destruct weak_obs_eq0.\n      constructor; eauto.\n      intros.\n      rewrite! restrPermMap_Cur.\n      erewrite Hrmap by eauto.\n      now apply po_refl.\n    - destruct strong_obs_eq0.\n      constructor.\n      intros.\n      rewrite! restrPermMap_Cur.\n      erewrite Hrmap by eauto.\n      reflexivity.\n      intros.\n      unfold Mem.perm in Hperm.\n      pose proof (restrPermMap_Cur Hlt' b1 ofs) as Heq.\n      unfold permission_at in Heq.\n      rewrite Heq in Hperm.\n      specialize (Hnew _ _ Hperm).\n      simpl.\n      eapply val_obs_eq0; eauto.\n      unfold Mem.perm.\n      pose proof (restrPermMap_Cur Hlt b1 ofs) as Heq'.\n      unfold permission_at in Heq'.\n      rewrite Heq'.\n      assumption.\n  Qed.\n\n  Lemma weak_mem_obs_eq_store:\n    forall mc mf mc' mf' rmap rmapF bl1 bl2 f\n      (Hlt: permMapLt rmap (getMaxPerm mc))\n      (HltF: permMapLt rmapF (getMaxPerm mf))\n      (Hlt2: permMapLt rmap (getMaxPerm mc'))\n      (Hlt2F: permMapLt rmapF (getMaxPerm mf'))\n      (Hf: f bl1 = Some bl2)\n      (Hinjective: forall b1 b1' b2 : block, f b1 = Some b2 -> f b1' = Some b2 -> b1 = b1')\n      (Hobs_eq: weak_mem_obs_eq f (restrPermMap Hlt) (restrPermMap HltF))\n      (Hvb: forall b, Mem.valid_block mc b <-> Mem.valid_block mc' b)\n      (HvbF: forall b, Mem.valid_block mf b <-> Mem.valid_block mf' b),\n      weak_mem_obs_eq f (restrPermMap Hlt2) (restrPermMap Hlt2F).\n  Proof.\n    intros.\n    destruct Hobs_eq.\n    constructor;\n      try (intros b1; erewrite restrPermMap_valid);\n      try (erewrite <- Hvb');\n      try (erewrite <- Hvb);\n      try by eauto.\n      intros b1 b2 Hf1. erewrite restrPermMap_valid.\n      erewrite <- HvbF.\n      specialize (codomain_valid0 _ _ Hf1);\n        by erewrite restrPermMap_valid in codomain_valid0.\n      intros b1 b2 ofs0 Hf1.\n      do 2 rewrite restrPermMap_Cur.\n      specialize (perm_obs_weak0 _ _ ofs0 Hf1).\n      rewrite! restrPermMap_Cur in perm_obs_weak0.\n      assumption.\n  Qed.\n\n  Lemma strong_mem_obs_eq_store:\n    forall mc mf mc' mf' rmap rmapF bl1 bl2 ofsl f v\n      (Hlt: permMapLt rmap (getMaxPerm mc))\n      (HltF: permMapLt rmapF (getMaxPerm mf))\n      (Hlt2: permMapLt rmap (getMaxPerm mc'))\n      (Hlt2F: permMapLt rmapF (getMaxPerm mf'))\n      (Hf: f bl1 = Some bl2)\n      (Hinjective: forall b1 b1' b2 : block, f b1 = Some b2 -> f b1' = Some b2 -> b1 = b1')\n      (Hobs_eq: strong_mem_obs_eq f (restrPermMap Hlt) (restrPermMap HltF))\n      (Hstore: Mem.mem_contents mc' = PMap.set bl1 (Mem.setN (encode_val Mint32 (Vint v)) ofsl (Mem.mem_contents mc) # bl1)\n                                               (Mem.mem_contents mc))\n      (HstoreF: Mem.mem_contents mf' = PMap.set bl2 (Mem.setN (encode_val Mint32 (Vint v)) ofsl (Mem.mem_contents mf) # bl2)\n                                                (Mem.mem_contents mf))\n      (Hvb: forall b, Mem.valid_block mc b <-> Mem.valid_block mc' b)\n      (HvbF: forall b, Mem.valid_block mf b <-> Mem.valid_block mf' b),\n      strong_mem_obs_eq f (restrPermMap Hlt2) (restrPermMap Hlt2F).\n  Proof.\n    intros.\n    assert (Hvb': forall b, ~ Mem.valid_block mc b <-> ~ Mem.valid_block mc' b)\n      by (intros; split; intros Hinvalid Hcontra;\n            by apply Hvb in Hcontra).\n    (** proof of [strong_mem_obs_eq]*)\n    destruct Hobs_eq.\n    constructor.\n    - intros b1 b2 ofs0 Hf1.\n      specialize (perm_obs_strong0 _ _ ofs0 Hf1).\n      erewrite! restrPermMap_Cur in *.\n      assumption.\n    - intros b1 b2 ofs0 Hf1 Hperm.\n      unfold Mem.perm in *.\n      assert (Hperm_eq2 := restrPermMap_Cur Hlt2 b1 ofs0).\n      assert (Hperm_eq := restrPermMap_Cur Hlt b1 ofs0).\n      unfold permission_at in Hperm_eq, Hperm_eq2.\n      rewrite Hperm_eq2 in Hperm.\n      specialize (val_obs_eq0 _ _ ofs0 Hf1).\n      rewrite Hperm_eq in val_obs_eq0.\n      specialize (val_obs_eq0 Hperm).\n      simpl.\n      rewrite Hstore HstoreF.\n      destruct (Pos.eq_dec b1 bl1) as [Heq | Hneq];\n        [| assert (b2 <> bl2)\n           by (intros Hcontra; subst;\n               apply Hneq; eapply Hinjective; eauto);\n           subst;\n           erewrite! Maps.PMap.gso by auto;\n           assumption].\n      subst bl1.\n      assert (b2 = bl2)\n        by (rewrite Hf1 in Hf; inversion Hf; by subst); subst bl2.\n      rewrite! Maps.PMap.gss.\n      destruct (Z_lt_le_dec ofs0 ofsl) as [Hofs_lt | Hofs_ge].\n      erewrite! Mem.setN_outside by (left; auto);\n        by assumption.\n      destruct (Z_lt_ge_dec\n                  ofs0 (ofsl + (size_chunk Mint32)))\n        as [Hofs_lt | Hofs_ge'].\n\n      apply setN_obs_eq with (access := fun q => q = ofs0);\n        eauto using encode_val_obs_eq, val_obs.\n      intros; subst; assumption.\n\n      erewrite! Mem.setN_outside by (right; rewrite size_chunk_conv in Hofs_ge';\n                                       by rewrite encode_val_length);\n        by auto.\n  Qed.\n\n  Corollary mem_obs_eq_store :\n    forall (mc mf mc' mf' : mem) (rmap rmapF : access_map) (bl1 bl2 : block) (ofsl : Z) f v\n      (Hlt : permMapLt rmap (getMaxPerm mc)) (HltF : permMapLt rmapF (getMaxPerm mf))\n      (Hlt2 : permMapLt rmap (getMaxPerm mc'))\n      (Hlt2F : permMapLt rmapF (getMaxPerm mf'))\n      (Hfl: f bl1 = Some bl2)\n      (Hinjective: forall b1 b1' b2 : block,\n          f b1 = Some b2 -> f b1' = Some b2 -> b1 = b1')\n      (Hmem_obs_eq: mem_obs_eq f (restrPermMap Hlt) (restrPermMap HltF))\n      (Hcontents: Mem.mem_contents mc' =\n                  PMap.set bl1 (Mem.setN (encode_val Mint32 (Vint v)) ofsl\n                                         (Mem.mem_contents mc) # bl1) (Mem.mem_contents mc))\n      (HcontentsF: Mem.mem_contents mf' =\n                   PMap.set bl2 (Mem.setN (encode_val Mint32 (Vint v)) ofsl\n                                          (Mem.mem_contents mf) # bl2) (Mem.mem_contents mf))\n      (Hvb: forall b : block, Mem.valid_block mc b <-> Mem.valid_block mc' b)\n      (HvbF: forall b : block, Mem.valid_block mf b <-> Mem.valid_block mf' b),\n      mem_obs_eq f (restrPermMap Hlt2) (restrPermMap Hlt2F).\n  Proof.\n    intros;\n      destruct Hmem_obs_eq;\n      constructor;\n      eauto using weak_mem_obs_eq_store, strong_mem_obs_eq_store.\n  Qed.\n\n\n  Lemma alloc_perm_eq:\n    forall f m m' sz m2 m2' b b'\n      (Hobs_eq: mem_obs_eq f m m')\n      (Halloc: Mem.alloc m 0 sz = (m2, b))\n      (Halloc': Mem.alloc m' 0 sz = (m2', b'))\n      b1 b2 ofs\n      (Hf: (if proj_sumbool (valid_block_dec m b1)\n            then f b1\n            else if proj_sumbool (valid_block_dec m2 b1)\n                 then Some b' else None) = Some b2),\n      permission_at m2 b1 ofs Cur =\n      permission_at m2' b2 ofs Cur.\n  Proof.\n    intros.\n    destruct (valid_block_dec m b1); simpl in Hf.\n    - assert (H := perm_obs_strong (strong_obs_eq Hobs_eq) _ ofs Hf).\n      erewrite <- permission_at_alloc_1; eauto.\n      erewrite <- permission_at_alloc_1 with (m' := m2'); eauto.\n      eapply (codomain_valid (weak_obs_eq Hobs_eq));\n        by eauto.\n    - destruct (valid_block_dec m2 b1); simpl in *; try discriminate.\n      inv Hf.\n      eapply Mem.valid_block_alloc_inv in v; eauto.\n      destruct v; subst; try (by exfalso).\n      destruct (zle 0 ofs), (zlt ofs sz);\n        [erewrite permission_at_alloc_2 by eauto;\n         erewrite permission_at_alloc_2 by eauto;\n         reflexivity | | |];\n        erewrite permission_at_alloc_3 by (eauto; omega);\n        erewrite permission_at_alloc_3 by (eauto; omega);\n        auto.\n  Qed.\n\nLemma setPermBlock_var_eq:\n    forall f bl1 bl2 ofsl b1 b2 ofs pmap pmap' p\n      (Hf: f b1 = Some b2)\n      (Hfl: f bl1 = Some bl2)\n      (Hinjective: forall b1 b1' b2 : block,\n          f b1 = Some b2 -> f b1' = Some b2 -> b1 = b1')\n      (Hperm: pmap # b1 ofs = pmap' # b2 ofs),\n      (setPermBlock_var p bl1 ofsl pmap\n                    lksize.LKSIZE_nat) # b1 ofs =\n      (setPermBlock_var p bl2 ofsl pmap'\n                    lksize.LKSIZE_nat) # b2 ofs.\n  Proof.\n    intros.\n    destruct (Pos.eq_dec b1 bl1).\n    - subst.\n      assert (b2 = bl2)\n        by (rewrite Hf in Hfl; inversion Hfl; subst; auto).\n      subst.\n      destruct (Intv.In_dec ofs (ofsl, (ofsl + lksize.LKSIZE)%Z)).\n      + erewrite setPermBlock_var_same by eauto.\n        erewrite setPermBlock_var_same by eauto.\n        reflexivity.\n      + apply Intv.range_notin in n.\n        simpl in n.\n        erewrite setPermBlock_var_other_1 by eauto.\n        erewrite setPermBlock_var_other_1 by eauto.\n        eauto.\n        unfold lksize.LKSIZE. simpl. omega.\n    - erewrite setPermBlock_var_other_2 by eauto.\n      assert (b2 <> bl2)\n        by (intros Hcontra;\n            subst; specialize (Hinjective _ _ _ Hf Hfl); subst; auto).\n      erewrite setPermBlock_var_other_2 by eauto.\n      eauto.\n  Qed.\n\n  Lemma setPermBlock_var_weak_obs_eq:\n    forall (f : block -> option block) (bl1 bl2 : block) (ofsl : Z)\n      (pmap pmapF : access_map) (mc mf : mem) p (Hlt : permMapLt pmap (getMaxPerm mc))\n      (HltF : permMapLt pmapF (getMaxPerm mf))\n      (Hfl: f bl1 = Some bl2)\n      (Hweak_obs_eq: weak_mem_obs_eq f (restrPermMap Hlt) (restrPermMap HltF))\n      (Hlt' : permMapLt (setPermBlock_var p bl1 ofsl pmap lksize.LKSIZE_nat) (getMaxPerm mc))\n      (HltF' : permMapLt (setPermBlock_var p bl2 ofsl pmapF lksize.LKSIZE_nat) (getMaxPerm mf)),\n      weak_mem_obs_eq f (restrPermMap Hlt') (restrPermMap HltF').\n  Proof.\n    intros.\n    destruct Hweak_obs_eq.\n    constructor; eauto.\n    intros.\n    rewrite! restrPermMap_Cur.\n    specialize (perm_obs_weak0 _ _ ofs Hrenaming).\n    rewrite! restrPermMap_Cur in perm_obs_weak0.\n    destruct (Pos.eq_dec bl1 b1).\n    + subst.\n      assert (b2 = bl2) by (rewrite Hrenaming in Hfl; inversion Hfl; by subst);\n        subst.\n      destruct (Intv.In_dec ofs (ofsl, ofsl + lksize.LKSIZE)%Z).\n      * erewrite! setPermBlock_var_same\n          by (unfold lksize.LKSIZE in i;\n              simpl in *;\n              auto).\n        now apply po_refl.\n      * erewrite! setPermBlock_var_other_1\n          by (apply Intv.range_notin in n; eauto;\n              unfold lksize.LKSIZE in *; simpl in *; omega).\n        assumption.\n    + assert (bl2 <> b2)\n        by (intros ?; subst; apply n; eauto).\n      erewrite! setPermBlock_var_other_2 by assumption.\n      assumption.\n  Qed.\n\n  Lemma setPermBlock_var_obs_eq:\n    forall f bl1 bl2 ofsl pmap pmapF mc mf p\n      (Hlt: permMapLt pmap (getMaxPerm mc))\n      (HltF: permMapLt pmapF (getMaxPerm mf))\n      (Hfl: f bl1 = Some bl2)\n      (Hval_obs_eq: forall ofs0, (ofsl <= ofs0 < ofsl + Z.of_nat (lksize.LKSIZE_nat))%Z ->\n                            memval_obs_eq f (ZMap.get ofs0 (Mem.mem_contents mc) # bl1)\n                                          (ZMap.get ofs0 (Mem.mem_contents mf) # bl2))\n      (Hobs_eq: mem_obs_eq f (restrPermMap Hlt) (restrPermMap HltF))\n      (Hlt': permMapLt (setPermBlock_var p bl1 ofsl pmap lksize.LKSIZE_nat) (getMaxPerm mc))\n      (HltF': permMapLt (setPermBlock_var p bl2 ofsl pmapF lksize.LKSIZE_nat) (getMaxPerm mf)),\n      mem_obs_eq f (restrPermMap Hlt') (restrPermMap HltF').\n  Proof.\n    intros.\n    destruct Hobs_eq.\n    constructor;\n      first by (eapply setPermBlock_var_weak_obs_eq; eauto).\n    destruct strong_obs_eq0.\n    constructor.\n    - intros b1 b2 ofs Hf.\n      specialize (perm_obs_strong0 _ _ ofs Hf).\n      erewrite! restrPermMap_Cur in *.\n      pose proof (injective weak_obs_eq0).\n      erewrite <- setPermBlock_var_eq; eauto.\n    - intros.\n      simpl.\n      pose proof (restrPermMap_Cur Hlt' b1 ofs).\n      unfold permission_at in H.\n      unfold Mem.perm in *.\n      rewrite H in Hperm.\n      destruct (Pos.eq_dec bl1 b1).\n      + subst.\n        destruct (Intv.In_dec ofs (ofsl, ofsl + lksize.LKSIZE)%Z).\n        erewrite! setPermBlock_var_same in Hperm\n          by (unfold lksize.LKSIZE in i;\n              simpl in *;\n              auto).\n        rewrite Hfl in Hrenaming; inversion Hrenaming; subst.\n        eapply Hval_obs_eq;\n          by eauto.\n        erewrite! setPermBlock_var_other_1 in Hperm\n          by (apply Intv.range_notin in n; eauto;\n              unfold lksize.LKSIZE in *; simpl in *; omega);\n          eapply val_obs_eq0; eauto.\n        pose proof (restrPermMap_Cur Hlt b1 ofs) as Heq.\n        unfold permission_at in Heq. rewrite Heq.\n        assumption.\n      + erewrite! setPermBlock_var_other_2 in Hperm by eauto.\n        eapply val_obs_eq0; eauto.\n        pose proof (restrPermMap_Cur Hlt b1 ofs) as Heq.\n        unfold permission_at in Heq. rewrite Heq.\n        assumption.\n  Qed.\n\n  Lemma setPermBlock_weak_obs_eq:\n    forall (f : block -> option block) (bl1 bl2 : block) (ofsl : Z)\n      (pmap pmapF : access_map) (mc mf : mem) (p : option permission) (Hlt : permMapLt pmap (getMaxPerm mc))\n      (HltF : permMapLt pmapF (getMaxPerm mf))\n      (Hfl: f bl1 = Some bl2)\n      (Hweak_obs_eq: weak_mem_obs_eq f (restrPermMap Hlt) (restrPermMap HltF))\n      (Hlt' : permMapLt (setPermBlock p bl1 ofsl pmap lksize.LKSIZE_nat) (getMaxPerm mc))\n      (HltF' : permMapLt (setPermBlock p bl2 ofsl pmapF lksize.LKSIZE_nat) (getMaxPerm mf)),\n      weak_mem_obs_eq f (restrPermMap Hlt') (restrPermMap HltF').\n  Proof.\n    intros.\n    assert (Hlt2' : permMapLt (setPermBlock_var (fun _ => p) bl1 ofsl pmap lksize.LKSIZE_nat) (getMaxPerm mc))\n      by (rewrite <- setPermBlock_setPermBlock_var; auto).\n    assert (HltF2' : permMapLt (setPermBlock_var (fun _ => p) bl2 ofsl pmapF lksize.LKSIZE_nat) (getMaxPerm mf))\n      by (rewrite <- setPermBlock_setPermBlock_var; auto).\n    erewrite restrPermMap_irr' with (Hlt' :=  Hlt2')\n      by (eapply setPermBlock_setPermBlock_var; eauto).\n    erewrite restrPermMap_irr' with (Hlt' :=  HltF2')\n      by (eapply setPermBlock_setPermBlock_var; eauto).\n    eapply setPermBlock_var_weak_obs_eq;\n      now eauto.\n  Qed.\n\n  Lemma setPermBlock_obs_eq:\n    forall f bl1 bl2 ofsl pmap pmapF mc mf p\n      (Hlt: permMapLt pmap (getMaxPerm mc))\n      (HltF: permMapLt pmapF (getMaxPerm mf))\n      (Hfl: f bl1 = Some bl2)\n      (Hval_obs_eq: forall ofs0, (ofsl <= ofs0 < ofsl + Z.of_nat (lksize.LKSIZE_nat))%Z ->\n                            memval_obs_eq f (ZMap.get ofs0 (Mem.mem_contents mc) # bl1)\n                                          (ZMap.get ofs0 (Mem.mem_contents mf) # bl2))\n      (Hobs_eq: mem_obs_eq f (restrPermMap Hlt) (restrPermMap HltF))\n      (Hlt': permMapLt (setPermBlock p bl1 ofsl pmap lksize.LKSIZE_nat) (getMaxPerm mc))\n      (HltF': permMapLt (setPermBlock p bl2 ofsl pmapF lksize.LKSIZE_nat) (getMaxPerm mf)),\n      mem_obs_eq f (restrPermMap Hlt') (restrPermMap HltF').\n  Proof.\n    intros.\n    assert (Hlt2' : permMapLt (setPermBlock_var (fun _ => p) bl1 ofsl pmap lksize.LKSIZE_nat) (getMaxPerm mc))\n      by (rewrite <- setPermBlock_setPermBlock_var; auto).\n    assert (HltF2' : permMapLt (setPermBlock_var (fun _ => p) bl2 ofsl pmapF lksize.LKSIZE_nat) (getMaxPerm mf))\n      by (rewrite <- setPermBlock_setPermBlock_var; auto).\n    erewrite restrPermMap_irr' with (Hlt' :=  Hlt2')\n      by (eapply setPermBlock_setPermBlock_var; eauto).\n    erewrite restrPermMap_irr' with (Hlt' :=  HltF2')\n      by (eapply setPermBlock_setPermBlock_var; eauto).\n    eapply setPermBlock_var_obs_eq;\n      now eauto.\n  Qed.\n\n  Lemma mem_free_obs_perm:\n    forall f m m' m2 m2' sz b1 b2\n      (Hmem_obs_eq: mem_obs_eq f m m')\n      (Hf: f b1 = Some b2)\n      (Hfree: Mem.free m b1 0 sz = Some m2)\n      (Hfree': Mem.free m' b2 0 sz = Some m2') b0 b3 ofs\n      (Hf0: f b0 = Some b3),\n      permissions.permission_at m2 b0 ofs Cur =\n      permissions.permission_at m2' b3 ofs Cur.\n  Proof.\n    intros.\n    pose proof (injective (weak_obs_eq Hmem_obs_eq)) as Hinjective.\n    pose proof (perm_obs_strong (strong_obs_eq Hmem_obs_eq)) as Hperm_eq.\n    eapply Mem.free_result in Hfree.\n    eapply Mem.free_result in Hfree'.\n    subst.\n    specialize (Hperm_eq _ _ ofs Hf0).\n    unfold permissions.permission_at, Mem.unchecked_free in *. simpl.\n    destruct (Pos.eq_dec b0 b1) as [Heq | Hneq].\n    - subst.\n      assert (b2 = b3)\n        by (rewrite Hf0 in Hf; by inv Hf).\n      subst b3.\n      do 2 rewrite Maps.PMap.gss.\n      rewrite Hperm_eq.\n      reflexivity.\n    - rewrite Maps.PMap.gso; auto.\n      rewrite Maps.PMap.gso; auto.\n      intros Hcontra.\n      subst.\n      apply Hneq; eapply Hinjective; eauto.\n  Qed.\n\n  Transparent Mem.free.\n\n  Lemma mem_free_obs:\n    forall f m m' sz b1 b2 m2\n      (Hmem_obs_eq: mem_obs_eq f m m')\n      (Hf: f b1 = Some b2)\n      (Hfree: Mem.free m b1 0 sz = Some m2),\n    exists m2',\n      Mem.free m' b2 0 sz = Some m2' /\\\n      mem_obs_eq f m2 m2'.\n  Proof.\n    intros.\n    assert (Hfree': Mem.free m' b2 0 sz = Some (Mem.unchecked_free m' b2 0 sz)).\n    { unfold Mem.free.\n      destruct (Mem.range_perm_dec m' b2 0 sz Cur Freeable); auto.\n      apply Mem.free_range_perm in Hfree.\n      unfold Mem.range_perm in *.\n      destruct Hmem_obs_eq as [_ [HpermEq _]].\n      unfold Mem.perm, permissions.permission_at in *.\n      exfalso.\n      apply n. intros ofs Hofs.\n      specialize (HpermEq _ _ ofs Hf).\n      rewrite HpermEq;\n        auto.\n    }\n    - eexists; split; eauto.\n      constructor.\n      + (*weak_obs_eq*)\n        inversion Hmem_obs_eq as [Hweak_obs_eq Hstrong_obs_eq].\n        destruct Hweak_obs_eq.\n        assert (Heq_nb := Mem.nextblock_free _ _ _ _ _ Hfree).\n        constructor; simpl; unfold Mem.valid_block; try (rewrite Heq_nb);\n        auto.\n        intros.\n        erewrite mem_free_obs_perm with (b1 := b1) (b0 := b0); eauto.\n        apply permissions.po_refl.\n      + constructor.\n        intros.\n        erewrite mem_free_obs_perm with (b1 := b1) (b0 := b0); eauto.\n        intros.\n        erewrite <- mem_free_contents; eauto.\n        erewrite <- mem_free_contents with (m2 := Mem.unchecked_free m' b2 0 sz);\n          eauto.\n        apply (val_obs_eq (strong_obs_eq Hmem_obs_eq)); auto.\n        eapply Mem.perm_free_3; eauto.\n  Qed.\n  Opaque Mem.free.\n\n  Lemma valid_pointer_ren:\n    forall f m m' b1 b2 ofs\n      (Hmem_obs_eq: mem_obs_eq f m m')\n      (Hf: f b1 = Some b2),\n      Mem.valid_pointer m b1 ofs = Mem.valid_pointer m' b2 ofs.\n  Proof.\n    intros.\n    unfold Mem.valid_pointer in *.\n    destruct Hmem_obs_eq as [_ [Hperm_eq _]].\n    specialize (Hperm_eq _ _ ofs Hf).\n    unfold permissions.permission_at in *.\n    unfold Coqlib.proj_sumbool in *.\n    destruct (Mem.perm_dec m b1 ofs Cur Nonempty);\n      destruct (Mem.perm_dec m' b2 ofs Cur Nonempty); auto.\n    unfold Mem.perm in *. rewrite Hperm_eq in n.\n      by exfalso.\n      unfold Mem.perm in *. rewrite Hperm_eq in p.\n        by exfalso.\n  Qed.\n\n  Lemma val_obs_cmpu:\n    forall f v1 v2 v1' v2' m m' (comp : comparison)\n      (Hval_obs': val_obs f v2 v2')\n      (Hval_obs: val_obs f v1 v1')\n      (Hmem_obs_eq: mem_obs_eq f m m'),\n      val_obs f (Val.cmpu (Mem.valid_pointer m) comp v1 v2)\n              (Val.cmpu (Mem.valid_pointer m') comp v1' v2').\n  Proof with eauto with val_renamings.\n    intros.\n    destruct v1, v1'; inversion Hval_obs;\n    inversion Hval_obs'; subst; simpl; eauto with val_renamings;\n    unfold Val.cmpu,Val.of_optbool, Val.cmpu_bool, Vtrue, Vfalse...\n    - destruct (Int.cmpu comp i0 i2)...\n    - assert (Int.eq i0 Int.zero &&\n                     (Mem.valid_pointer m b1 (Int.unsigned ofs)\n                      || Mem.valid_pointer m b1 (Int.unsigned ofs - 1))\n              = Int.eq i0 Int.zero &&\n                       (Mem.valid_pointer m' b2 (Int.unsigned ofs)\n                        || Mem.valid_pointer m' b2 (Int.unsigned ofs - 1))).\n      { destruct (Int.eq i0 Int.zero); simpl; try reflexivity.\n        erewrite valid_pointer_ren; eauto.\n        erewrite valid_pointer_ren with (ofs := (Int.unsigned ofs - 1)%Z);\n          eauto.\n      }\n      rewrite H.\n      repeat match goal with\n             | [|- context[match ?Expr with _ => _ end]] =>\n               destruct Expr eqn:?\n             end...\n    - assert (Int.eq i1 Int.zero &&\n                     (Mem.valid_pointer m b (Int.unsigned i0)\n                      || Mem.valid_pointer m b (Int.unsigned i0 - 1))\n              = Int.eq i1 Int.zero &&\n                       (Mem.valid_pointer m' b0 (Int.unsigned i0)\n                        || Mem.valid_pointer m' b0 (Int.unsigned i0 - 1))).\n      { destruct (Int.eq i1 Int.zero); simpl; try reflexivity.\n        erewrite valid_pointer_ren; eauto.\n        erewrite valid_pointer_ren with (ofs := (Int.unsigned i0 - 1)%Z);\n          eauto.\n      }\n      rewrite H.\n      repeat match goal with\n             | [|- context[match ?Expr with _ => _ end]] =>\n               destruct Expr eqn:?\n             end...\n    - assert (Hequiv: (eq_block b b3) <-> (eq_block b0 b4)).\n      { split.\n        - intros Heq.\n          destruct (eq_block b b3); subst.\n          + rewrite H4 in H0; inversion H0; subst.\n            destruct (eq_block b0 b0); auto.\n          + by exfalso.\n        - intros Heq.\n          destruct (eq_block b b3); subst.\n          + rewrite H4 in H0; inversion H0; subst.\n            destruct (eq_block b0 b0); auto.\n          + destruct (eq_block b0 b4); subst; auto.\n            assert (Hinjective := injective (weak_obs_eq Hmem_obs_eq)).\n            specialize (Hinjective _ _ _ H4 H0); subst.\n              by exfalso.\n      }\n      destruct (eq_block b b3) eqn:Hb;\n        destruct (eq_block b0 b4) eqn:Hb0; simpl in *; subst;\n        destruct Hequiv; try (by exfalso; eauto).\n      assert (Hif: (Mem.valid_pointer m b3 (Int.unsigned i0)\n                    || Mem.valid_pointer m b3 (Int.unsigned i0 - 1))\n                     &&\n                     (Mem.valid_pointer m b3 (Int.unsigned ofs0)\n                      || Mem.valid_pointer m b3 (Int.unsigned ofs0 - 1))\n                   =\n                   (Mem.valid_pointer m' b4 (Int.unsigned i0)\n                    || Mem.valid_pointer m' b4 (Int.unsigned i0 - 1))\n                     &&\n                     (Mem.valid_pointer m' b4 (Int.unsigned ofs0)\n                      || Mem.valid_pointer m' b4 (Int.unsigned ofs0 - 1))).\n      { erewrite valid_pointer_ren; eauto.\n        erewrite valid_pointer_ren with\n        (m := m) (b1:=b3) (ofs := (Int.unsigned i0 - 1)%Z); eauto.\n        erewrite valid_pointer_ren with\n        (m := m) (b1:=b3) (ofs := Int.unsigned ofs0); eauto.\n        erewrite valid_pointer_ren with\n        (m := m) (b1:=b3) (ofs := (Int.unsigned ofs0 - 1)%Z); eauto.\n      }\n      rewrite Hif.\n      repeat match goal with\n             | [|- context[match ?Expr with _ => _ end]] =>\n               destruct Expr eqn:?\n             end...\n      erewrite valid_pointer_ren; eauto.\n      erewrite valid_pointer_ren with (b1 := b3); eauto.\n      repeat match goal with\n             | [|- context[match ?Expr with _ => _ end]] =>\n               destruct Expr eqn:?\n             end...\n  Qed.\n\n  Hint Resolve val_obs_cmpu : val_renamings.\n\n  Lemma mem_obs_eq_of_weak_strong:\n    forall m m' f pmap1 pmap1' pmap2 pmap2'\n      (Hlt1: permMapLt pmap1 (getMaxPerm m))\n      (Hlt2: permMapLt pmap2 (getMaxPerm m'))\n      (Hlt1': permMapLt pmap1' (getMaxPerm m))\n      (Hlt2': permMapLt pmap2' (getMaxPerm m'))\n      (Hstrong_obs: strong_mem_obs_eq f (restrPermMap Hlt1) (restrPermMap Hlt2))\n      (Hweak: weak_mem_obs_eq f (restrPermMap Hlt1') (restrPermMap Hlt2')),\n      mem_obs_eq f (restrPermMap Hlt1) (restrPermMap Hlt2).\n  Proof.\n    intros.\n    destruct Hweak.\n    constructor; auto.\n    constructor; intros.\n    - specialize (domain_invalid0 b).\n      erewrite restrPermMap_valid in H, domain_invalid0;\n        eauto.\n    - specialize (domain_valid0 b).\n      erewrite restrPermMap_valid in H, domain_valid0;\n        eauto.\n    - specialize (codomain_valid0 _ _ H);\n      erewrite restrPermMap_valid in *;\n      eauto.\n    - eauto.\n    - destruct Hstrong_obs as [Hpermeq _].\n      specialize (Hpermeq _ _ ofs Hrenaming).\n      rewrite Hpermeq;\n        apply po_refl.\n  Qed.\n\nEnd MemObsEq.\n\nModule Type CoreInjections (SEM: Semantics).\n\n  Import ValObsEq ValueWD MemoryWD Renamings MemObsEq SEM event_semantics.\n\n  (** Pointers in the core are well-defined *)\n  Parameter core_wd : memren -> C -> Prop.\n  (** Pointers in the global env are well-defined *)\n  Parameter ge_wd : memren -> G -> Prop.\n\n  Parameter ge_wd_incr: forall f f' (g : G),\n      ge_wd f g ->\n      ren_domain_incr f f' ->\n      ge_wd f' g.\n\n  Parameter ge_wd_domain : forall f f' m (g : G),\n      ge_wd f g ->\n      domain_memren f m ->\n      domain_memren f' m ->\n      ge_wd f' g.\n\n  Parameter core_wd_incr : forall f f' c,\n      core_wd f c ->\n      ren_domain_incr f f' ->\n      core_wd f' c.\n\n  Parameter core_wd_domain : forall f f' m c,\n      core_wd f c ->\n      domain_memren f m ->\n      domain_memren f' m ->\n      core_wd f' c.\n\n  Parameter at_external_wd:\n    forall f c ef args,\n      core_wd f c ->\n      at_external Sem c = Some (ef, args) ->\n      valid_val_list f args.\n\n  Parameter after_external_wd:\n    forall c c' f ef args ov,\n      at_external Sem c = Some (ef, args) ->\n      core_wd f c ->\n      valid_val_list f args ->\n      after_external Sem ov c = Some c' ->\n      match ov with\n            | Some v => valid_val f v\n            | None => True\n            end ->\n      core_wd f c'.\n\n  Parameter initial_core_wd:\n    forall the_ge f vf arg c_new,\n      initial_core Sem the_ge vf [:: arg] = Some c_new ->\n      valid_val f arg ->\n      ge_wd f the_ge ->\n      core_wd f c_new.\n\n  (** Renamings on cores *)\n  Parameter core_inj: memren -> C -> C -> Prop.\n\n  Parameter core_inj_ext:\n    forall c c' f (Hinj: core_inj f c c'),\n      match at_external Sem c, at_external Sem c' with\n      | Some (ef, vs), Some (ef', vs') =>\n        ef = ef' /\\ val_obs_list f vs vs'\n      | None, None => True\n      | _, _ => False\n      end.\n\n  Parameter core_inj_after_ext:\n    forall c cc c' ov1 f (Hinj: core_inj f c c'),\n      match ov1 with\n      | Some v1 => valid_val f v1\n      | None => True\n      end ->\n      after_external Sem ov1 c = Some cc ->\n      exists ov2 cc',\n        after_external Sem ov2 c' = Some cc' /\\\n        core_inj f cc cc' /\\\n        match ov1 with\n        | Some v1 => match ov2 with\n                    | Some v2 => val_obs f v1 v2\n                    | _ => False\n                    end\n        | None => match ov2 with\n                 | None => True\n                 | _ => False\n                 end\n        end.\n\n  Parameter core_inj_halted:\n    forall c c' f (Hinj: core_inj f c c'),\n      match halted Sem c, halted Sem c' with\n      | Some v, Some v' => val_obs f v v'\n      | None, None => True\n      | _, _ => False\n      end.\n\n  Parameter core_inj_init:\n    forall vf vf' arg arg' c_new f fg the_ge\n      (Hf: val_obs_list f arg arg')\n      (Hf': val_obs f vf vf')\n      (Hfg: forall b1 b2, fg b1 = Some b2 -> b1 = b2)\n      (Hge_wd: ge_wd fg the_ge)\n      (Hincr: ren_incr fg f)\n      (Hinit: initial_core Sem the_ge vf arg = Some c_new),\n    exists c_new',\n      initial_core Sem the_ge vf' arg' = Some c_new' /\\\n      core_inj f c_new c_new'.\n\n  Parameter core_inj_id: forall c f,\n      core_wd f c ->\n      (forall b1 b2, f b1 = Some b2 -> b1 = b2) ->\n      core_inj f c c.\n\n  Parameter core_inj_trans:\n    forall c c' c'' (f f' f'' : memren)\n      (Hcore_inj: core_inj f c c'')\n      (Hcore_inj': core_inj f' c c')\n      (Hf: forall b b' b'',\n          f b = Some b'' ->\n          f' b = Some b' ->\n          f'' b' = Some b''),\n      core_inj f'' c' c''.\n\n  Parameter corestep_obs_eq:\n    forall cc cf cc' mc mf mc' f fg the_ge\n      (Hobs_eq: mem_obs_eq f mc mf)\n      (Hcode_eq: core_inj f cc cf)\n      (Hfg: (forall b1 b2, fg b1 = Some b2 -> b1 = b2))\n      (Hge_wd: ge_wd fg the_ge)\n      (Hincr: ren_incr fg f)\n      (Hstep: corestep Sem the_ge cc mc cc' mc'),\n    exists cf' mf' f',\n      corestep Sem the_ge cf mf cf' mf'\n      /\\ core_inj f' cc' cf'\n      /\\ mem_obs_eq f' mc' mf'\n      /\\ ren_incr f f'\n      /\\ ren_separated f f' mc mf\n      /\\ ((exists p, ((Mem.nextblock mc' = Mem.nextblock mc + p)%positive /\\\n                (Mem.nextblock mf' = Mem.nextblock mf + p)%positive))\n         \\/ ((Mem.nextblock mc' = Mem.nextblock mc) /\\\n            (Mem.nextblock mf' = Mem.nextblock mf)))\n      /\\ (forall b,\n            Mem.valid_block mf' b ->\n            ~ Mem.valid_block mf b ->\n            let bz := ((Zpos b) - ((Zpos (Mem.nextblock mf)) -\n                                   (Zpos (Mem.nextblock mc))))%Z in\n            f' (Z.to_pos bz) = Some b /\\\n            f (Z.to_pos bz) = None)\n      /\\ (Mem.nextblock mc = Mem.nextblock mf ->\n         (forall b1 b2, f b1 = Some b2 -> b1 = b2) ->\n         forall b1 b2, f' b1 = Some b2 -> b1 = b2)\n      /\\ (forall b2, (~exists b1, f' b1 = Some b2) ->\n               forall ofs, permission_at mf b2 ofs Cur = permission_at mf' b2 ofs Cur).\n\n  (* Starting from a wd state, we get a new valid memory and the fact\n     that there exists some renaming whose domain is the same as the\n     new memory and additionally that the new core is well defined\n     with respect to all renamings withe same domain.  Note that we\n     cannot say anything about the codomain, i.e. that f' is an\n     extension of f.*)\n  Parameter corestep_wd:\n    forall c m c' m' f fg the_ge\n      (Hwd: core_wd f c)\n      (Hmem_wd: valid_mem m)\n      (Hge_wd: ge_wd fg the_ge)\n      (Hincr: ren_domain_incr fg f)\n      (Hdomain: domain_memren f m)\n      (Hcorestep: corestep Sem the_ge c m c' m'),\n      valid_mem m' /\\\n      (exists f', ren_domain_incr f f' /\\ domain_memren f' m') /\\\n      forall f', domain_memren f' m' ->\n            core_wd f' c'.\n\n\nEnd CoreInjections.\n\nModule ThreadPoolInjections (SEM: Semantics)\n       (Machines: MachinesSig with Module SEM := SEM)\n       (CI: CoreInjections SEM).\n\n  Import ValObsEq ValueWD MemoryWD Renamings CI.\n  Import concurrent_machine Machines.DryMachine ThreadPool.\n  (** Renamings on Thread Pools *)\n\n  (*not clear what should happen with vf. Normally it should be in the\ngenv and hence should be mapped to itself, but let's not expose this\nhere*)\n  Definition ctl_inj f cc cf : Prop :=\n    match cc, cf with\n    | Kinit vf arg, Kinit vf' arg' =>\n      val_obs f vf vf' /\\ val_obs f arg arg'\n    | Krun c, Krun c' => core_inj f c c'\n    | Kblocked c, Kblocked c' => core_inj f c c'\n    | Kresume c arg, Kresume c' arg' => core_inj f c c' /\\ val_obs f arg arg'\n    | _, _  => False\n    end.\n\n  (*Again we do not require that the first argument to Kinit is valid\n  as we never map it, although maybe we should*)\n  Definition ctl_wd f t : Prop :=\n    match t with\n    | Krun c => core_wd f c\n    | Kblocked c => core_wd f c\n    | Kresume c v => core_wd f c /\\ valid_val f v\n    | Kinit vf v => valid_val f vf /\\ valid_val f v\n    end.\n\n  Lemma ctl_wd_incr : forall f f' c,\n      ctl_wd f c ->\n      ren_domain_incr f f' ->\n      ctl_wd f' c.\n  Proof.\n    intros f f' c Hwd Hincr.\n    destruct c; simpl in *;\n    repeat match goal with\n           | [H: _ /\\ _ |- _] =>\n             destruct H\n           | [ |- _] => split\n           end;\n    try (eapply core_wd_incr; eauto);\n    try (eapply valid_val_incr; eauto).\n  Qed.\n\n  Lemma ctl_inj_trans:\n    forall c c' c'' (f f' f'' : memren)\n      (Hcore_inj: ctl_inj f c c'')\n      (Hcore_inj': ctl_inj f' c c')\n      (Hf: forall b b' b'',\n          f b = Some b'' ->\n          f' b = Some b' ->\n          f'' b' = Some b''),\n      ctl_inj f'' c' c''.\n  Proof.\n    intros.\n    destruct c, c', c''; simpl in *; try (by exfalso);\n    try (destruct Hcore_inj, Hcore_inj'; split);\n    try (eapply core_inj_trans; eauto);\n    eapply val_obs_trans;\n      by eauto.\n  Qed.\n\n  Definition tp_wd (f: memren) (tp : thread_pool) : Prop :=\n    forall i (cnti: containsThread tp i),\n      ctl_wd f (getThreadC cnti).\n\n  Lemma tp_wd_incr : forall f f' tp,\n      tp_wd f tp ->\n      ren_domain_incr f f' ->\n      tp_wd f' tp.\n  Proof.\n    intros.\n    intros i cnti.\n    specialize (H i cnti).\n    eapply ctl_wd_incr;\n      by eauto.\n  Qed.\n\n  Lemma ctl_wd_domain:\n    forall f f' m (c : ctl),\n      ctl_wd f c ->\n      domain_memren f m ->\n      domain_memren f' m ->\n      ctl_wd f' c.\n  Proof.\n    intros f f' m c Hwd Hf Hf'.\n    destruct c; simpl in *;\n    repeat match goal with\n           | [H: _ /\\ _ |- _] => destruct H\n           | [|- _ /\\ _] => split\n           | [|- core_wd _ _] => eapply core_wd_domain; eauto\n           | [|- valid_val _ _] => eapply valid_val_domain; eauto\n           end.\n  Qed.\n\n  Lemma tp_wd_domain:\n    forall f f' m (tp : thread_pool),\n      tp_wd f tp ->\n      domain_memren f m ->\n      domain_memren f' m ->\n      tp_wd f' tp.\n  Proof.\n    intros.\n    intros i cnti.\n    specialize (H i cnti).\n    destruct (getThreadC cnti); simpl in *;\n    repeat match goal with\n           | [H: _ /\\ _ |- _] => destruct H\n           | [|- _ /\\ _] => split\n           | [|- core_wd _ _] => eapply core_wd_domain; eauto\n           | [|- valid_val _ _] => eapply valid_val_domain; eauto\n           end.\n  Qed.\n\n  Lemma tp_wd_lockSet:\n    forall tp f addr rmap\n      (Htp_wd: tp_wd f tp),\n      tp_wd f (updLockSet tp addr rmap).\n  Proof.\n    intros.\n    intros i cnti'.\n    assert (cnti := cntUpdateL' cnti').\n    specialize (Htp_wd _ cnti).\n      by rewrite gLockSetCode.\n  Qed.\n\n  Lemma tp_wd_remLock :\n    forall (tp : thread_pool) (f : memren) (addr : address)\n      (Htp_wd: tp_wd f tp),\n      tp_wd f (remLockSet tp addr).\n  Proof.\n    intros.\n    intros i cnti'.\n    assert (cnti := cntRemoveL' cnti').\n    specialize (Htp_wd _ cnti);\n      by rewrite gRemLockSetCode.\n  Qed.\n\n  Lemma ctl_inj_id:\n    forall f c,\n      ctl_wd f c ->\n      (forall b1 b2, f b1 = Some b2 -> b1 = b2) ->\n      ctl_inj f c c.\n  Proof.\n    intros.\n    destruct c; simpl in *;\n    repeat match goal with\n           |[H: _ /\\ _ |- _] =>\n            destruct H\n           |[|- _ /\\ _] => split; auto\n           |[|- core_inj _ _ _] =>\n            eapply core_inj_id; eauto\n           |[|- val_obs _ _ _] =>\n            eapply val_obs_id; eauto\n           end.\n  Qed.\n\nEnd ThreadPoolInjections.\n\n\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/concurrency/mem_obs_eq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.22201171427283595}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import sha.SHA256.\nRequire Import sha.spec_sha.\nRequire Import sha.sha.\nRequire Export sha.pure_lemmas.\nRequire Export sha.general_lemmas.\nRequire Export sha.vst_lemmas.\nExport ListNotations.\n\nLocal Open Scope logic.\n\nGlobal Opaque K256.\n\nTransparent peq.\n\nLemma mapsto_tc_val:\n  forall sh t p v,\n  readable_share sh ->\n  v <> Vundef ->\n  mapsto sh t p v = !! tc_val t v && mapsto sh t p v .\nProof.\nintros.\napply pred_ext; [ | normalize].\napply andp_right; auto.\nunfold mapsto; simpl.\ndestruct (access_mode t); try apply FF_left.\ndestruct (attr_volatile (attr_of_type t)); try apply FF_left.\ndestruct p; try apply FF_left.\nif_tac; try contradiction. apply orp_left.\nnormalize.\nnormalize.\nQed.\n\nFixpoint loops (s: statement) : list statement :=\n match s with\n  | Ssequence a b => loops a ++ loops b\n  | Sloop _ _ => [s]\n  | Sifthenelse _ a b => loops a ++ loops b\n  | _ => nil\n  end.\n\nLemma big_endian_integer_bytelist:\n   forall bl, Zlength bl = 4->\n  bytelist_to_intlist bl = big_endian_integer bl :: nil.\nProof.\nintros.\ndestruct bl as [| a [|b [|c [|d [|]]]]]; inv H.\n2: rewrite ?Zlength_cons in H1; list_solve. \nunfold big_endian_integer, bytes_to_Int.\nsimpl.\nf_equal.\nf_equal.\nrewrite <- ?Int.or_shl.\nf_equal.\nrewrite ?Int.shl_shl by reflexivity.\nautorewrite with norm.\nsimpl.\nchange (Int.shl (Int.shl Int.zero (Int.repr 8))\n        (Int.repr 24)) with Int.zero.\nrewrite Int.or_zero_l.\nrewrite ?Int.shl_shl by reflexivity.\nreflexivity.\nQed.\n\nLemma nth_big_endian_integer:\n  forall i bl w,\n   nth_error bl i = Some w ->\n    w = big_endian_integer\n                   (sublist (Z.of_nat i * WORD)\n                        (Z.succ (Z.of_nat i) * WORD)\n                   (intlist_to_bytelist bl)).\nProof.\nintros.\nchange WORD with 4.\nassert (nth_error bl i <> None) by congruence.\nrewrite nth_error_Some in H0.\nmatch goal with |- ?A = ?B => assert (A::nil = B::nil) end;\n [ | congruence].\nrewrite <- big_endian_integer_bytelist.\n2:{ \nrewrite Zlength_sublist; try omega.\nrewrite (Zlength_intlist_to_bytelist bl).\nrewrite Zlength_correct.\nomega.\n}\nunfold sublist.\nreplace (Z.to_nat (Z.of_nat i * 4)) with (4 * i)%nat.\n2:{ rewrite Z2Nat.inj_mul by omega. \n     rewrite Nat2Z.id. simpl. omega.\n}\nrewrite skipn_intlist_to_bytelist.\nreplace (Z.to_nat\n        (Z.succ (Z.of_nat i) * 4 -\n         Z.of_nat i * 4)) with (4*1)%nat.\n2:{ unfold Z.succ. replace ((Z.of_nat i + 1) * 4 - Z.of_nat i * 4) with 4 by omega. reflexivity.\n}\nrewrite firstn_intlist_to_bytelist.\nrewrite intlist_to_bytelist_to_intlist.\nclear H0.\nrevert bl H; induction i; destruct bl; simpl; intros; inv H; auto.\nrewrite (IHi _ H1). reflexivity.\nQed.\n\nLemma Znth_big_endian_integer:\n  forall i bl,\n   0 <= i < Zlength bl ->\n   Znth i bl =\n     big_endian_integer\n                   (sublist (i * WORD) (Z.succ i * WORD)\n                   (intlist_to_bytelist bl)).\nProof.\nintros.\nunfold Znth.\n rewrite if_false by omega.\npose proof (nth_error_nth _ Int.zero (Z.to_nat i) bl).\nrewrite <- (Z2Nat.id i) at 2 3 by omega.\napply nth_big_endian_integer.\napply H0.\napply Nat2Z.inj_lt.\nrewrite Z2Nat.id by omega.\nrewrite <- Zlength_correct; omega.\nQed.\n\nFixpoint sequence (cs: list statement) s :=\n match cs with\n | nil => s\n | c::cs' => Ssequence c (sequence cs' s)\n end.\n\nFixpoint rsequence (cs: list statement) s :=\n match cs with\n | nil => s\n | c::cs' => Ssequence (rsequence cs' s) c\n end.\n\nLemma sequence_rsequence:\n forall Espec CS Delta P cs s0 s R,\n    @semax CS Espec Delta P (Ssequence s0 (sequence cs s)) R  <->\n  @semax CS Espec Delta P (Ssequence (rsequence (rev cs) s0) s) R.\nProof.\nintros.\nrevert Delta P R s0 s; induction cs; intros.\nsimpl. apply iff_refl.\nsimpl.\nrewrite seq_assoc.\nrewrite IHcs; clear IHcs.\nreplace (rsequence (rev cs ++ [a]) s0) with\n    (rsequence (rev cs) (Ssequence s0 a)); [apply iff_refl | ].\nrevert s0 a; induction (rev cs); simpl; intros; auto.\nrewrite IHl. auto.\nQed.\n\nLemma seq_assocN:\n  forall {Espec: OracleKind} CS,\n   forall Q Delta P cs s R,\n        @semax CS Espec Delta P (sequence cs Sskip) (normal_ret_assert Q) ->\n         @semax CS Espec\n       Delta  Q s R ->\n        @semax CS Espec Delta P (sequence cs s) R.\nProof.\nintros.\nrewrite semax_skip_seq.\nrewrite sequence_rsequence.\nrewrite semax_skip_seq in H.\nrewrite sequence_rsequence in H.\nrewrite <- semax_seq_skip in H.\neapply semax_seq'; [apply H | ].\neapply semax_extensionality_Delta; try apply H0.\nclear.\napply tycontext_sub_refl.\nQed.\n\nFixpoint sequenceN (n: nat) (s: statement) : list statement :=\n match n, s with\n | S n', Ssequence a s' => a::sequenceN n' s'\n | _, _ => nil\n end.\n\nRequire Import JMeq.\n\nLemma reptype_tarray {cs: compspecs}:\n   forall t len, reptype (tarray t len) = list (reptype t).\nProof.\nintros.\nrewrite reptype_eq. simpl. reflexivity.\nQed.\n\nLocal Open Scope nat.\n\n(*** Application of Omega stuff ***)\n\nLemma CBLOCKz_eq : CBLOCKz = 64%Z.\nProof. reflexivity. Qed.\nLemma LBLOCKz_eq : LBLOCKz = 16%Z.\nProof. reflexivity. Qed.\nLemma WORD_eq: WORD = 4%Z.\nProof. reflexivity. Qed.\n\nHint Rewrite CBLOCKz_eq LBLOCKz_eq WORD_eq : rep_omega.\n\n(*\nLtac helper2 :=\n match goal with\n   | |- context [CBLOCK] => add_nonredundant (CBLOCK_eq)\n   | |- context [LBLOCK] => add_nonredundant (LBLOCK_eq)\n   | |- context [CBLOCKz] => add_nonredundant (CBLOCKz_eq)\n   | |- context [LBLOCKz] => add_nonredundant (LBLOCKz_eq)\n   | H: context [CBLOCK] |- _ => add_nonredundant (CBLOCK_eq)\n   | H: context [LBLOCK] |- _ => add_nonredundant (LBLOCK_eq)\n   | H: context [CBLOCKz] |- _ => add_nonredundant (CBLOCKz_eq)\n   | H: context [LBLOCKz] |- _ => add_nonredundant (LBLOCKz_eq)\n  end.\n\nLtac Omega1 := Omega (helper1 || helper2).\n*)\nLtac Omega1 := rep_omega.\n\nLtac MyOmega :=\n  rewrite ?length_list_repeat, ?skipn_length, ?map_length,\n   ?Zlength_map, ?Zlength_nil;\n  pose proof CBLOCK_eq;\n(*  pose proof CBLOCKz_eq;*)\n  pose proof LBLOCK_eq;\n(*  pose proof LBLOCKz_eq; *)\n  Omega1.\n(*** End Omega stuff ***)\n\nLocal Open Scope Z.\n\nLocal Open Scope logic.\n\nLemma sizeof_tarray_tuchar:\n forall (n:Z), (n>=0)%Z -> (sizeof (tarray tuchar n) =  n)%Z.\nProof. intros.\n unfold sizeof,tarray; cbv beta iota.\n  rewrite Z.max_r by omega.\n  unfold alignof, tuchar; cbv beta iota.\n  rewrite Z.mul_1_l. auto.\nQed.\n\n\nLemma Zlength_bytelist_to_intlist:\n  forall (n:Z) (l: list byte),\n   (Zlength l = WORD*n)%Z -> Zlength (bytelist_to_intlist l) = n.\nProof.\nintros.\nrewrite Zlength_correct in *.\nrewrite (length_bytelist_to_intlist (Z.to_nat n)); rep_omega.\nQed.\n\nLemma nth_intlist_to_bytelist_eq:\n forall d (n i j k: nat) al, (i < n)%nat -> (i < j*4)%nat -> (i < k*4)%nat ->\n    nth i (intlist_to_bytelist (firstn j al)) d = nth i (intlist_to_bytelist (firstn k al)) d.\nProof.\n induction n; destruct i,al,j,k; simpl; intros; auto; try omega.\n destruct i; auto. destruct i; auto. destruct i; auto.\n apply IHn; omega.\nQed.\n\n\nGlobal Opaque WORD.\n\nLemma S256abs_data:\n  forall hashed data,\n   (LBLOCKz | Zlength hashed) ->\n   Zlength data < CBLOCKz ->\n   s256a_data (S256abs hashed data) = data.\nProof.\nintros. unfold S256abs, s256a_data.\nrewrite Zlength_app.\nrewrite Zlength_intlist_to_bytelist.\ndestruct H as [n ?].\nrewrite H.\nassert (CBLOCKz > 0) by rep_omega. \npose proof (Zmod_eq (n * CBLOCKz + Zlength data) CBLOCKz H1).\npose proof (Zmod_eq (Zlength data) CBLOCKz H1).\nrewrite sublist_app2; rewrite Zlength_intlist_to_bytelist; rewrite H;\n rewrite <- Z.mul_assoc; change (LBLOCKz * 4)%Z with CBLOCKz.\napply sublist_same.\nrewrite Z.div_add_l by omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by rep_omega. omega.\nomega.\nrewrite Z.div_add_l by  omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by rep_omega.\nsplit; [ | omega].\napply Z.mul_nonneg_nonneg.\nclear - H.\nassert (n < 0 \\/ 0 <= n) by omega.\ndestruct H0; auto.\nassert (n * LBLOCKz < 0).\napply Z.mul_neg_pos; auto.\nrep_omega.\nomega.\nQed.\n\nLemma S256abs_hashed:\n  forall hashed data,\n   (LBLOCKz | Zlength hashed) ->\n   Zlength data < CBLOCKz ->\n   s256a_hashed (S256abs hashed data) = hashed.\nProof.\nintros;  unfold S256abs, s256a_hashed.\nrewrite Zlength_app.\nrewrite Zlength_intlist_to_bytelist.\ndestruct H as [n ?].\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (n * CBLOCKz + Zlength data) CBLOCKz H1).\npose proof (Zmod_eq (Zlength data) CBLOCKz H1).\npose proof (Zlength_nonneg data).\nrewrite sublist_app1; rewrite ?Zlength_intlist_to_bytelist;\n  rewrite H.\nrewrite sublist_same; try omega.\napply intlist_to_bytelist_to_intlist.\nrewrite Zlength_intlist_to_bytelist.\n  rewrite H.\nrewrite <- Z.mul_assoc; change (LBLOCKz*4)%Z with CBLOCKz.\nrewrite Z.div_add_l by omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega.  omega.\nsplit; [omega | ].\nrewrite <- Z.mul_assoc; change (LBLOCKz*4)%Z with CBLOCKz.\nrewrite Z.div_add_l by omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega.\nclear - H.\nassert (n < 0 \\/ 0 <= n) by omega.\nsimpl.\ndestruct H0.\npose proof (Zlength_nonneg hashed).\nassert (n * LBLOCKz < 0).\napply Z.mul_neg_pos; auto.\nomega.\nrewrite Z.add_0_r.\napply Z.mul_nonneg_nonneg; auto.\nrewrite <- Z.mul_assoc; change (LBLOCKz*4)%Z with CBLOCKz.\nrewrite Z.div_add_l by omega.\nrewrite Z.mul_add_distr_r.\nrewrite Z.div_small by omega.  omega.\nQed.\n\nLemma s256a_hashed_divides:\n  forall a, (LBLOCKz | Zlength (s256a_hashed a)).\nProof.\nintros. unfold s256a_hashed.\nexists (Zlength a / CBLOCKz)%Z.\nerewrite Zlength_bytelist_to_intlist; [reflexivity |].\nrewrite Zlength_sublist.\nrewrite (Z.mul_comm WORD).\nrewrite <- Z.mul_assoc.\nchange (LBLOCKz * WORD)%Z with CBLOCKz.\nomega.\nsplit; [ omega  |] .\napply Z.mul_nonneg_nonneg; auto.\napply Z.div_pos.\napply Zlength_nonneg.\nrewrite CBLOCKz_eq; omega.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (Zlength a) CBLOCKz H).\npose proof (Z_mod_lt (Zlength a) CBLOCKz H).\nomega.\nQed.\n\nLemma s256a_data_len:\n  forall a: s256abs,\n  Zlength (s256a_data a) = Zlength a mod CBLOCKz.\nProof.\nintros.\nunfold s256a_data.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (Zlength a) CBLOCKz H).\npose proof (Z_mod_lt (Zlength a) CBLOCKz H).\nrewrite H0.\nrewrite Zlength_sublist; try omega.\nsplit; try omega.\napply Z.mul_nonneg_nonneg.\napply Z.div_pos.\napply Zlength_nonneg.\nomega. omega.\nQed.\n\nLemma s256a_data_Zlength_less:\n  forall a, Zlength (s256a_data a) < CBLOCKz.\nProof.\nintros.\nrewrite s256a_data_len.\napply Z_mod_lt.\nrewrite CBLOCKz_eq; omega.\nQed.\n\nLemma hashed_data_recombine:\n  forall a,\n    intlist_to_bytelist (s256a_hashed a) ++ s256a_data a = a.\nProof.\nintros.\nunfold s256a_hashed, s256a_data.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\nrewrite bytelist_to_intlist_to_bytelist.\nrewrite sublist_rejoin.\nautorewrite with sublist. auto.\nsplit; [ omega  |] .\napply Z.mul_nonneg_nonneg; auto.\napply Z.div_pos.\napply Zlength_nonneg.\nrewrite CBLOCKz_eq; omega.\nassert (CBLOCKz > 0) by (rewrite CBLOCKz_eq; omega).\npose proof (Zmod_eq (Zlength a) CBLOCKz H).\npose proof (Z_mod_lt (Zlength a) CBLOCKz H).\nomega.\nrewrite Zlength_sublist.\nrewrite Z.sub_0_r.\napply Z.divide_mul_r.\nexists LBLOCKz. reflexivity.\nsplit; [ omega  |] .\napply Z.mul_nonneg_nonneg; auto.\napply Z.div_pos.\napply Zlength_nonneg.\nomega.\npose proof (Zmod_eq (Zlength a) CBLOCKz H).\npose proof (Z_mod_lt (Zlength a) CBLOCKz H).\nomega.\nQed.\n\nDefinition bitlength (hashed: list int) (data: list byte) : Z :=\n   ((Zlength hashed * WORD + Zlength data) * 8)%Z.\n\nLemma bitlength_eq:\n  forall hashed data,\n  bitlength hashed data = s256a_len (S256abs hashed data).\nProof.\nintros.\nunfold bitlength, s256a_len, S256abs.\nrewrite Zlength_app.\nrewrite Zlength_intlist_to_bytelist.\nreflexivity.\nQed.\n\nLemma S256abs_recombine:\n forall a, \n    S256abs (s256a_hashed a) (s256a_data a) = a.\nProof.\nintros.\napply hashed_data_recombine; auto.\nQed.\n\nLemma bytelist_to_intlist_app:\n  forall a b,\n  (WORD | Zlength a) ->\n   bytelist_to_intlist (a++b) = bytelist_to_intlist a ++ bytelist_to_intlist b.\nProof.\nintros.\ndestruct H as [na H].\nrewrite <- (Z2Nat.id na) in H.\n2:{\ndestruct (zlt na 0); try omega.\nassert (na * WORD < 0); [apply Z.mul_neg_pos; auto | ].\npose proof (Zlength_nonneg a); omega.\n}\nrevert a H; induction (Z.to_nat na); intros.\nsimpl in H. destruct a. simpl. auto. rewrite Zlength_cons in H.\npose proof (Zlength_nonneg a); omega.\nrewrite inj_S in H.\nunfold Z.succ in H. rewrite Z.mul_add_distr_r in H.\nchange (1*WORD)%Z with 4 in H.\nassert (Zlength a >= 4).\nassert (0 <= Z.of_nat n * WORD); [ | omega].\napply Z.mul_nonneg_nonneg; try omega.\nchange WORD with 4%Z; omega.\ndo 4 (destruct a; [rewrite Zlength_nil in H0; omega | rewrite Zlength_cons in H,H0  ]).\nsimpl.\ndo 4 f_equal. apply IHn.\nomega.\nQed.\n\nLemma round_range:\n forall {A} (a: list A) (N:Z),\n  N > 0 ->\n   0 <= Zlength a / N * N <= Zlength a.\nProof.\nintros.\nsplit.\napply Z.mul_nonneg_nonneg; auto; try omega.\napply Z.div_pos; try omega.\napply Zlength_nonneg.\npose proof (Zmod_eq (Zlength a) N H).\npose proof (Z_mod_lt (Zlength a) N H).\nomega.\nQed.\n\nLemma CBLOCKz_gt: CBLOCKz > 0.\nProof. rewrite CBLOCKz_eq; omega.\nQed.\n\nLemma bytelist_to_intlist_inj:\n  forall a b,\n   (WORD | Zlength a) ->\n   (WORD | Zlength b) ->\n   bytelist_to_intlist a = bytelist_to_intlist b ->\n   a=b.\nProof.\nintros.\nrewrite <- (bytelist_to_intlist_to_bytelist a) by auto.\nrewrite H1.\napply bytelist_to_intlist_to_bytelist; auto.\nQed.\n\nDefinition update_abs (incr: list byte) (a: list byte) (a': list byte) :=\n    a' = a ++ incr.\n\nLemma update_abs_eq:\n  forall msg a a',\n (update_abs msg a a' <->\n  exists blocks,\n    s256a_hashed a' = s256a_hashed a ++ blocks /\\\n    s256a_data a ++ msg = intlist_to_bytelist blocks ++ s256a_data a').\nProof.\nintros. pose proof I.\nunfold update_abs.\nassert (0 <= 0 <= Zlength a / CBLOCKz * CBLOCKz). {\n split; [omega | ].\n apply Z.mul_nonneg_nonneg.\n apply Z.div_pos.\n apply Zlength_nonneg.\n rewrite CBLOCKz_eq; omega.\n rewrite CBLOCKz_eq; omega.\n}\npose proof (round_range a _ CBLOCKz_gt).\npose proof (round_range (a++msg) _ CBLOCKz_gt).\nsplit; intro.\n*\nsubst a'.\nunfold s256a_hashed.\nexists (bytelist_to_intlist\n            (sublist (Zlength a / CBLOCKz * CBLOCKz) (Zlength (a++msg) / CBLOCKz * CBLOCKz)\n                  (a++msg))).\nsplit.\n +\n rewrite (sublist_split 0 (Zlength a / CBLOCKz * CBLOCKz)); auto.\n rewrite bytelist_to_intlist_app.\n f_equal.\n rewrite sublist_app1; auto. omega.\n rewrite Zlength_sublist; auto.\n rewrite Z.sub_0_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n rewrite Zlength_app.\n pose proof (Zlength_nonneg msg); omega.\n split; [ | apply round_range; apply CBLOCKz_gt].\n apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].\n rewrite Zlength_app; Omega1.\n +\n rewrite bytelist_to_intlist_to_bytelist.\n 2:{ rewrite Zlength_sublist. rewrite <- Z.mul_sub_distr_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n split; [Omega1 | ].\n apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].\n rewrite Zlength_app; Omega1.\n apply round_range. apply CBLOCKz_gt.\n }\n unfold s256a_data.\n destruct (zlt   (Zlength (a ++ msg) / CBLOCKz * CBLOCKz) (Zlength a) ).\n  -\n   rewrite sublist_app1; try omega.\n   rewrite (sublist_split (Zlength (a ++ msg) / CBLOCKz * CBLOCKz)\n               (Zlength a) (Zlength (a ++ msg))); try omega.\n   rewrite sublist_app1; try omega.\n   rewrite sublist_app2 by omega.\n   autorewrite with sublist.\n   rewrite (sublist_same 0) by omega.\n   rewrite <- app_ass. f_equal.\n   rewrite sublist_rejoin; try omega. auto.\n   split. apply round_range; apply CBLOCKz_gt.\n apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].\n  Omega1.\n  rewrite Zlength_app in l; omega.\n  rewrite Zlength_app; Omega1.\n   split. apply round_range; apply CBLOCKz_gt.\n apply Zmult_le_compat_r; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_le_mono; [rewrite CBLOCKz_eq; omega| ].\n  rewrite Zlength_app; Omega1.\n -\n   rewrite (sublist_split (Zlength a / CBLOCKz * CBLOCKz) (Zlength a)\n                  (Zlength (a ++ msg) / CBLOCKz * CBLOCKz) ); auto.\n   rewrite app_ass.\n   rewrite sublist_app1; try omega.\n   rewrite sublist_app2; try omega.\n   rewrite Z.sub_diag.\n   f_equal.\n   rewrite sublist_app2; try omega.\n   rewrite sublist_rejoin.\n   autorewrite with sublist. auto.\n   omega.\n  split; try omega. rewrite Zlength_app; Omega1.\n   omega.\n*\ndestruct H3 as [blocks [? ?]].\nmatch type of H3 with ?A = ?B =>\n  assert (Zlength A * WORD = Zlength B * WORD)%Z by congruence\nend.\nmatch type of H4 with ?A = ?B =>\n  assert (sublist 0 (Zlength a / CBLOCKz * CBLOCKz) a ++ A =\n              sublist 0 (Zlength a / CBLOCKz * CBLOCKz) a ++ B) by congruence\nend.\nunfold s256a_hashed, s256a_data in *.\nrewrite <- app_ass in H6.\nrewrite sublist_rejoin in H6 by omega.\nrewrite sublist_same in H6 by omega.\nrewrite H6.\nclear H6 H4.\nrewrite <- (sublist_same 0 (Zlength a') a') at 1; auto.\nrewrite <- app_ass.\nrewrite (sublist_split 0 (Zlength a' / CBLOCKz * CBLOCKz) (Zlength a')); try omega.\nf_equal.\napply bytelist_to_intlist_inj.\nrewrite Zlength_sublist.\n rewrite Z.sub_0_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n split; [clear; omega | ].\n apply Z.mul_nonneg_nonneg; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_pos; [ | rewrite CBLOCKz_eq; omega].\n apply Zlength_nonneg.\n apply round_range; apply CBLOCKz_gt.\n rewrite Zlength_app.\n apply Z.divide_add_r.\nrewrite Zlength_sublist.\n rewrite Z.sub_0_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n split; [clear; omega | ].\n apply Z.mul_nonneg_nonneg; [ | rewrite CBLOCKz_eq; omega].\n apply Z.div_pos; [ | rewrite CBLOCKz_eq; omega].\n apply Zlength_nonneg.\n apply round_range; apply CBLOCKz_gt.\n exists (Zlength blocks).\n apply Zlength_intlist_to_bytelist.\n rewrite H3.\n rewrite bytelist_to_intlist_app. f_equal.\n symmetry; apply intlist_to_bytelist_to_intlist.\nrewrite Zlength_sublist.\n rewrite Z.sub_0_r.\n apply Z.divide_mul_r.\n exists LBLOCKz; reflexivity.\n auto.\n omega.\n split; [clear; omega |].\n apply round_range; apply CBLOCKz_gt.\n split; [ | clear; omega].\n apply round_range; apply CBLOCKz_gt.\nQed.\n\nLemma array_at_memory_block:\n forall {cs: compspecs} sh t gfs lo hi v p n,\n  sizeof (nested_field_array_type t gfs lo hi) = n ->\n  lo <= hi ->\n  array_at sh t gfs lo hi v p |--\n  memory_block sh n (field_address0 t (ArraySubsc lo :: gfs) p).\nProof.\nintros.\nrewrite  array_at_data_at by auto.\nnormalize.\nunfold at_offset.\nrewrite field_address0_offset by auto.\nsubst n.\napply data_at_memory_block.\nQed.\n\nHint Extern 2 (array_at _ _ _ _ _ _ _ |-- memory_block _ _ _) =>\n   (apply array_at_memory_block; try reflexivity; try omega) : cancel.\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/sha/sha_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22179253962631099}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Strings.String.\nRequire Import MetaCoq.Template.TemplateMonad.Extractable.\nRequire Import MetaCoq.Template.Loader.\nRequire Import MetaCoq.Template.Ast.\nRequire Import ExtLib.Structures.Monad.\nImport MonadNotation.\nLocal Open Scope string_scope.\n\nRequire Import seal.seal.\n\nModule __seal.\n\n  Local Definition q_eq := <% @eq %>.\n  Local Definition q_eq_refl := <% @eq_refl %>.\n  Local Definition q_opaque := <% @_opaque %>.\n  Local Definition q_seal := <% @_seal %>.\n  Local Definition q_opaque_ind : inductive :=\n    ltac:(lazymatch eval red in q_opaque with\n          | tInd ?t _ => exact t\n          | _ => fail \"_opaque is not an inductive?\"\n          end).\n\n  Local Fixpoint string_rev (pre s : string) : string :=\n    match s with\n    | EmptyString => pre\n    | String s ss => string_rev (String s pre) ss\n    end.\n\n  Local Fixpoint get_base (pre nm : string) : TM string :=\n    match nm with\n    | EmptyString => tmFail \"the name must end with _def\"\n    | \"_def\" => tmReturn (string_rev \"\" pre)\n    | String \".\"%char ss => get_base \"\" ss\n    | String \"#\"%char ss => get_base \"\" ss\n    | String s ss => get_base (String s pre) ss\n    end.\n\n  Instance Monad_TM : Monad TM :=\n    { ret := @tmReturn\n    ; bind := @tmBind }.\n\n  Local Definition mk_sealed (name : string) (type def : Ast.term) : TM kername :=\n    tmOpaqueDefinition name None\n      (tApp q_seal (type :: def :: def :: tApp q_eq_refl (type :: def :: nil) :: nil)).\n\n  Local Definition mk_eq (name base_kn : string) (type def sealed : Ast.term) : TM kername :=\n    tmDefinition name\n                 (Some (tApp q_eq (type :: def :: tConst base_kn nil :: nil)))\n                 (tProj ((q_opaque_ind, 2), 1) sealed).\n\n  Definition generate (def : Ast.term) : TM _ :=\n    match def with\n    | tConst kn ui =>\n      base <- get_base \"\" kn ;;\n      cnst <- tmQuoteConstant kn false ;;\n      match cnst with\n      | ParameterEntry p => tmFail \"parameter, already opaque\"\n      | DefinitionEntry d =>\n        let body := d.(definition_entry_body) in\n        let type := d.(definition_entry_type) in\n        sealed_kn <- mk_sealed (base ++ \"_seal\")%string type body ;;\n        let sealed := tConst sealed_kn nil in\n        base_kn <- tmDefinition base None (tProj ((q_opaque_ind, 2), 0) sealed) ;;\n        mk_eq (base ++ \"_eq\")%string base_kn type def sealed ;;\n        tmMsg (\"sealed [\" ++ base ++ \"] as [\" ++ base ++ \"_seal] with equation [\" ++ base ++ \"_eq]\")%string\n      end\n    | _ => tmFail \"not a constant\"\n    end%monad.\n\nEnd __seal.\n\nDefinition seal' := __seal.generate.\n\nNotation \"'seal' x\" := ltac:(let p y := exact (seal' y) in quote_term x p)\n   (at level 200, x at level 0, only parsing).\n", "meta": {"author": "gmalecha", "repo": "coq-seal", "sha": "801331b5c589d3633d67eec8bc1d435b16e895f1", "save_path": "github-repos/coq/gmalecha-coq-seal", "path": "github-repos/coq/gmalecha-coq-seal/coq-seal-801331b5c589d3633d67eec8bc1d435b16e895f1/theories/TC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22179253962631099}}
{"text": "(*\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\nRequire Import String.\nRequire Import List.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import Bool.\nRequire Import EquivDec.\nRequire Import Assoc.\nRequire Import Bindings.\nRequire Import SortingAdd.\nRequire Import CoqLibAdd.\nRequire Import ForeignEJson.\nRequire Import EJson.\n\nSection EJsonNorm.\n  Context {foreign_ejson_model:Set}.\n  Context {fejson:foreign_ejson foreign_ejson_model}.\n\n  Fixpoint normalize_ejson (d:ejson) : ejson :=\n    match d with\n    | ejobject rl => ejobject (rec_sort (map (fun x => (fst x, normalize_ejson (snd x))) rl))\n    | ejarray l => ejarray (map normalize_ejson l)\n    | ejforeign fd => ejforeign (foreign_ejson_normalize fd)\n    | _ => d\n    end.\n\n  Inductive ejson_normalized : ejson -> Prop :=\n  | ejnnull :\n      ejson_normalized ejnull\n  | ejnnumber n :\n      ejson_normalized (ejnumber n)\n  | ejnbigint n :\n      ejson_normalized (ejbigint n)\n  | ejnbool b :\n      ejson_normalized (ejbool b)\n  | ejnstring s :\n      ejson_normalized (ejstring s)\n  | ejnarray dl :\n      Forall (fun x => ejson_normalized x) dl -> ejson_normalized (ejarray dl)\n  | ejnobject dl :\n      Forall (fun d => ejson_normalized (snd d)) dl ->\n      (is_list_sorted ODT_lt_dec (domain dl) = true) ->\n      ejson_normalized (ejobject dl)\n  | ejnforeign fd :\n      foreign_ejson_normalized fd ->\n      ejson_normalized (ejforeign fd).\n\n  Theorem ejson_normalize_normalizes :\n    forall (d:ejson), ejson_normalized (normalize_ejson d).\n  Proof.\n    induction d using ejsonInd2; simpl.\n    - apply ejnnull.\n    - apply ejnnumber.\n    - apply ejnbigint.\n    - apply ejnbool.\n    - apply ejnstring.\n    - apply ejnarray.\n      apply Forall_forall; intros.\n      induction c; elim H0; intros.\n      rewrite <- H1.\n      apply (H a); left; reflexivity.\n      assert (forall x:ejson, In x c -> ejson_normalized (normalize_ejson x))\n        by (intros; apply (H x0); right; assumption).\n      specialize (IHc H2 H1).\n      assumption.\n    - apply ejnobject.\n      + apply Forall_sorted.\n        apply Forall_forall; intros.\n        induction r.\n        contradiction.\n        simpl in *.\n        elim H0; intros; clear H0.\n        rewrite <- H1.\n        simpl.\n        apply (H (fst a) (snd a)).\n        left; destruct a; reflexivity.\n        assert (forall (x : string) (y : ejson),\n                   In (x, y) r -> ejson_normalized (normalize_ejson y)); intros.\n        apply (H x0 y); right; assumption.\n        apply (IHr H0).\n        assumption.\n      + apply (@rec_sort_sorted string ODT_string) with (l1 := (map (fun x : string * ejson => (fst x, normalize_ejson (snd x))) r)).\n        reflexivity.\n    - constructor.\n      apply foreign_ejson_normalize_normalizes.\n  Qed.\n\n  Theorem ejson_normalize_normalized_eq {d}:\n    ejson_normalized d ->\n    normalize_ejson d = d.\n  Proof.\n    induction d using ejsonInd2; simpl; trivial.\n    - intros.\n      rewrite (@map_eq _ _ normalize_ejson id).\n      + rewrite map_id; trivial.\n      + inversion H0; simpl; subst.\n        revert H2. apply Forall_impl_in.\n        auto.\n    - intros.\n      inversion H0; subst.\n      rewrite (@map_eq _ _ (fun x : string * ejson => (fst x, normalize_ejson (snd x))) id).\n      + rewrite map_id.\n        rewrite rec_sorted_id; trivial.\n      + revert H2. apply Forall_impl_in.\n        destruct a; unfold id; simpl; intros.\n        f_equal; eauto.\n    - inversion 1; subst.\n      f_equal.\n      apply foreign_ejson_normalize_idempotent.\n      trivial.\n  Qed.\n\n  Lemma ejson_map_normalize_normalized_eq c :\n    Forall (fun x => ejson_normalized (snd x)) c ->\n    (map\n       (fun x0 : string * ejson => (fst x0, normalize_ejson (snd x0)))\n       c) = c.\n  Proof.\n    induction c; simpl; trivial.\n    destruct a; inversion 1; simpl in *; subst.\n    rewrite ejson_normalize_normalized_eq; trivial.\n    rewrite IHc; trivial.\n  Qed.\n\n  Corollary ejson_normalize_idem d :\n    normalize_ejson (normalize_ejson d) = normalize_ejson d.\n  Proof.\n    apply ejson_normalize_normalized_eq.\n    apply ejson_normalize_normalizes.\n  Qed.\n\n  Corollary normalize_ejson_eq_normalized {d} :\n    normalize_ejson d = d -> ejson_normalized d.\n  Proof.\n    intros.\n    generalize (ejson_normalize_normalizes d).\n    congruence.\n  Qed.\n\n  Theorem normalized_ejson_dec d : {ejson_normalized d} + {~ ejson_normalized d}.\n  Proof.\n    destruct (normalize_ejson d == d); unfold equiv, complement in *.\n    - left. apply normalize_ejson_eq_normalized; trivial.\n    - right. intro dn; elim c. apply ejson_normalize_normalized_eq; trivial.\n  Defined.\n\n  Lemma ejson_normalized_jarray a l :\n    (ejson_normalized a /\\ ejson_normalized (ejarray l)) <->\n    ejson_normalized (ejarray (a :: l)).\n  Proof.\n    split.\n    - destruct 1 as [d1 d2]. inversion d2; subst.\n      constructor; auto.\n    - inversion 1; subst. inversion H1; subst.\n      split; trivial.\n      constructor; auto.\n  Qed.\n  \n  Lemma ejson_normalized_rec_sort_app l1 l2 :\n    ejson_normalized (ejobject l1) ->\n    ejson_normalized (ejobject l2) ->\n    ejson_normalized (ejobject (rec_sort (l1 ++ l2))).\n  Proof.\n    inversion 1; inversion 1; subst.\n    constructor; eauto 1 with qcert.\n    apply Forall_sorted.\n    apply Forall_app; trivial.\n  Qed.\n\n  Lemma ejson_normalized_rec_concat_sort l1 l2 :\n    ejson_normalized (ejobject l1) ->\n    ejson_normalized (ejobject l2) ->\n    ejson_normalized (ejobject (rec_concat_sort l1 l2)).\n  Proof.\n    apply ejson_normalized_rec_sort_app.\n  Qed.\n\n  Lemma ejson_normalized_jarray_in x l :\n    In x l ->\n    ejson_normalized (ejarray l) ->\n    ejson_normalized x.\n  Proof.\n    inversion 2; subst.\n    rewrite Forall_forall in H2.\n    eauto.\n  Qed.\n\n  Lemma ejnobject_nil : ejson_normalized (ejobject nil).\n  Proof.\n    econstructor; trivial.\n  Qed.\n\n  Lemma ejnobject_sort_content c :\n    Forall (fun d : string * ejson => ejson_normalized (snd d)) c ->\n    Forall (fun d : string * ejson => ejson_normalized (snd d)) (rec_sort c).\n  Proof.\n    intros F.\n    apply Forall_sorted; trivial.\n  Qed.\n\n  Lemma ejnobject_sort c :\n    Forall (fun d : string * ejson => ejson_normalized (snd d)) c ->\n    ejson_normalized (ejobject (rec_sort c)).\n  Proof.\n    intros F; econstructor; trivial with qcert.\n    apply Forall_sorted; trivial.\n  Qed.\n\n  Lemma ejson_normalized_jarray_Forall l :\n    ejson_normalized (ejarray l) <-> Forall ejson_normalized l.\n  Proof.\n    split; intros H.\n    - invcs H; trivial.\n    - constructor; trivial.\n  Qed.\n  \nEnd EJsonNorm.\n\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/EJson/Model/EJsonNorm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22179253962631099}}
{"text": "(** This file provides an efficient proof search strategy\n   for our derivation system defined in [Sat]. *)\nRequire Import Containers.Sets.\nRequire Import Env Sat.\nRequire Import SetoidList.\nRequire Import Arith.\nRequire Import FoldProps.\n\nFact belim : forall b, b = false -> b = true -> False.\nProof. congruence. Qed.\n\n(** * The functor [SATSTRATEGY] *)\nModule SATCAML \n  (Import CNF : Cnf.CNF)\n  (Import E : ENV_INTERFACE CNF).\n\n  (** We start by importing some efinitions from the SAT functor. *)\n  Module Import S := SAT CNF E.\n  Module SemF := S.SemF.\n  Definition submodel_e G (M : Sem.model) := forall l, G |= l -> M l.\n  Definition compatible_e G (D : cset) :=\n    forall (M : Sem.model), submodel_e G M -> Sem.sat_goal M D.\n  \n  Notation \"G |- D\" := (mk_sequent G D) (at level 80).\n\n  (** Relating lists of literals to clauses, and lists of lists of literals\n     to sets of clauses (the reverse of [elements]). *)\n  Fixpoint l2s (l : list L.t) : clause :=\n    match l with\n      | nil => {}\n      | a::q => {a; l2s q}\n    end.\n  Fixpoint ll2s (l : list (list L.t)) : cset :=\n    match l with\n      | nil => {}\n      | a::q => {l2s a; ll2s q}\n    end.\n\n  Property l2s_iff : forall l C, l \\In l2s C <-> InA _eq l C.\n  Proof.\n    intros; induction C; simpl.\n    intuition.\n    split; simpl; intro H.\n    rewrite add_iff in H; destruct H; intuition.\n    rewrite add_iff; inversion H; intuition.\n  Qed.\n\n  Property ll2s_app : forall l l', ll2s (app l l') [=] ll2s l ++ ll2s l'.\n  Proof.\n    induction l; intros l'; simpl.\n    intro k; set_iff; intuition.\n    rewrite IHl, Props.union_add; reflexivity.\n  Qed.\n  Property ll2s_cfl : forall ll, cfl ll [=] ll2s ll.\n  Proof.\n    induction ll; rewrite cfl_1; simpl.\n    reflexivity.\n    apply add_m; auto. rewrite cfl_1 in IHll; exact IHll.\n  Qed.\n  Property l2s_Subset : \n    forall C C', (forall l, InA _eq l C -> InA _eq l C') <-> l2s C [<=] l2s C'.\n  Proof.\n    intros C C'; split; intros H k.\n    rewrite !l2s_iff; auto.\n    rewrite <- !l2s_iff; auto.\n  Qed.\n\n  Lemma ll2s_expand : forall (M : Sem.model) l, M l ->\n    forall C, C \\In ll2s (L.expand l) -> Sem.sat_clause M C.\n  Proof.\n    intros M l Hl C HC.\n    assert (HM := Sem.wf_expand M l Hl).\n    set (L := L.expand l) in *; clearbody L; clear l Hl.\n    revert L HC HM; induction L; intros; simpl in  *.\n    contradiction (empty_1 HC).\n    rewrite add_iff in HC; destruct HC as [HC|HC].\n\n    destruct (HM a (or_introl _ (refl_equal _))) as [k [Hk1 Hk2]].\n    clear HM; exists k; split; auto.\n    assert (Hk := ListIn_In Hk1); rewrite <- l2s_iff, HC in Hk; auto.   \n\n    apply (IHL HC); intuition.\n  Qed.\n  \n  (** Facts about measures of lists of (lists of) literals *)\n  Property lsize_pos : forall l, l <> nil -> L.lsize l > 0.\n  Proof.\n    induction l; intros; simpl; auto.\n    congruence.\n    generalize (L.size_pos a); omega.\n  Qed.\n  Property llsize_app : \n    forall l l', L.llsize (app l l') = L.llsize l + L.llsize l'.\n  Proof.\n    induction l; simpl; intros; intuition.\n    generalize (IHl l'); omega.\n  Qed.\n\n  (** ** Functions computing the BCP\n     \n     The following functions compute the proof search in a way that is similar\n     to the OCaml procedure in [JFLA08]. We perform all possible binary \n     constraint propagation (BCP) before we start splitting on literals. *)\n\n  (** The first function reduces a clause with respect to a partial \n     assignment. It returns [redNone] if the clause contains a literal\n     that is true in the assignment, and the reduced clause in the \n     other case (with a flag telling if the function has changed anything). *)\n  Section Reduce.\n    Variable G : E.t.\n    Variable D : cset.\n\n    Inductive redRes : Type :=\n    | redSome : list L.t -> bool -> redRes\n    | redNone : redRes.\n\n    Fixpoint reduce (C : list L.t) : redRes :=\n      match C with\n        | nil => redSome nil false\n        | l::C' =>\n          if query l G then redNone\n            else\n            match reduce C' with\n              | redNone => redNone\n              | redSome Cred b => \n                if query (L.mk_not l) G then\n                  redSome Cred true\n                  else redSome (l::Cred) b\n            end\n      end.\n\n    Inductive reduce_spec_ (C : list L.t) : redRes -> Type :=\n    | reduce_redSome : \n      forall Cred (bred : bool) \n        (HCred : Cred = List.filter (fun l => negb (query (L.mk_not l) G)) C)\n        (Hsub : forall l, List.In l Cred -> query l G = false)\n        (Hbred : if bred then L.lsize Cred < L.lsize C else C = Cred),\n        reduce_spec_ C (redSome Cred bred)\n    | reduce_redNone : \n      forall l (Hl : query l G = true) (Hin : List.In l C),\n        reduce_spec_ C redNone.\n    Theorem reduce_spec : forall C, reduce_spec_ C (reduce C).\n    Proof.\n      induction C; simpl.\n      constructor; auto; intros; contradiction.\n      case_eq (query a G); intro Hq.\n      constructor 2 with a; intuition.\n      destruct IHC; simpl.\n      case_eq (query (L.mk_not a) G); intro Hnq.\n      constructor; auto; simpl. \n      rewrite Hnq; simpl; auto.\n      generalize (L.size_pos a); destruct bred; try rewrite Hbred; omega.\n      constructor.\n      simpl; rewrite Hnq; simpl; congruence.\n      intros l Hl; inversion Hl; subst; eauto.\n      destruct bred; try congruence; simpl; omega.\n      constructor 2 with l; intuition.\n    Qed.\n\n    Unset Regular Subst Tactic.\n\n    Corollary reduce_correct : forall C Cred bred,\n      reduce C = redSome Cred bred -> derivable (G |- {l2s Cred; D}) -> \n      derivable (G |- {l2s C; D}).\n    Proof.\n      intros C Cred bred Hred Hder; \n        destruct (reduce_spec C); inversion Hred; subst.\n      set (reds := filter (fun l : L.t => query (L.mk_not l) G) (l2s C)).\n      assert (M : Proper (_eq ==> @eq bool) (fun l => query (L.mk_not l) G))\n        by (eauto with typeclass_instances).\n      apply ARed with reds (l2s C).\n\n      unfold reds; intros k Hk; apply (filter_2 Hk).\n      unfold reds; intros k Hk; apply (filter_1 Hk).\n      apply add_1; auto.\n      assert (E : l2s Cred [=] l2s C \\ reds).\n      rewrite <- H0; unfold reds; revert M; clear; intro M; induction C; simpl.\n      intuition.\n      case_eq (query (L.mk_not a) G); intro Ha; simpl.\n      rewrite IHC, EProps.filter_add_1; auto.\n      intro k; set_iff; intuition.\n      apply H1; apply filter_3; auto; rewrite <- H2; assumption.\n      rewrite IHC, EProps.filter_add_2; auto.\n      intro k; set_iff; intuition.\n      rewrite H0 in Ha; rewrite (filter_2 H) in Ha; discriminate.\n      rewrite <- E; refine (weakening _ Hder _ _); split; simpl; intuition.\n    Qed.\n(*     Corollary reduce_complete : forall C Cred bred M, *)\n(*       reduce C = redSome Cred bred ->  *)\n(*       submodel_e G M -> Sem.sat_clause M (l2s C) -> Sem.sat_clause M (l2s Cred). *)\n(*     Proof. *)\n(*       intros C Cred bred M Hred Hsub;  *)\n(*         destruct (reduce_spec C); inversion Hred; subst. *)\n(*       intros [l Hsatl]; exists l; intuition. *)\n(*       rewrite <- H0; revert H H1 Hsub; clear; induction C; simpl; auto; intros. *)\n(*       rewrite add_iff in H1; destruct H1. *)\n(*       case_eq (query (L.mk_not a) G); intro Hq; simpl. *)\n(*       contradiction (SemF.model_em M l H). *)\n(*       apply Hsub; rewrite <- H0; auto. *)\n(*       apply add_1; auto. *)\n(*       destruct (negb (query (L.mk_not a) G)); [apply add_2 |]; *)\n(*         exact (IHC H H0 Hsub). *)\n(*     Qed. *)\n    Corollary reduce_complete : forall C Cred bred M,\n      reduce C = redSome Cred bred -> \n      submodel_e G M -> Sem.sat_clause M (l2s Cred) -> \n      Sem.sat_clause M (l2s C).\n    Proof.\n      intros C Cred bred M Hred Hsub; \n        destruct (reduce_spec C); inversion Hred; subst.\n      intros [l Hsatl]; exists l; intuition.\n      rewrite <- H0 in H1; revert H H1 Hsub; clear; \n        induction C; simpl; auto; intros.\n      destruct (query (L.mk_not a) G); simpl in *.\n      apply add_2; apply IHC; auto.\n      rewrite add_iff in H1; destruct H1; [apply add_1 | apply add_2]; auto.\n    Qed.\n \n  End Reduce.\n  \n  (** The second function simplifies a set of clauses  with respect \n     to a partial assignment. It returns [bcpNone] if one of the clauses\n     reduced to the empty clause. Otherwise, it returns the set of\n     simplified clauses along with a new partial assignment. Indeed,\n     if simplification yields a unitary clause, [AAssume] is\n     immediately applied and the literal is added to the partial\n     assignment for the rest of the simplification. Again, we return\n     a flag saying if the function has simplified anything or not.\n     *)\n  Section BCP.\n    Inductive bcpRes : Type :=\n    | bcpSome : E.t -> list (list L.t) -> bool -> bcpRes\n    | bcpNone : bcpRes.\n\n    Definition extend l s := app (L.expand l) s.\n    Fixpoint bcp (G : E.t) (D : list (list L.t)) : bcpRes :=\n      match D with\n        | nil => bcpSome G nil false\n        | C::D' =>\n          match reduce G C with\n            | redNone => \n              match bcp G D' with\n                | bcpNone => bcpNone\n                | bcpSome G' D' _ => bcpSome G' D' true\n              end\n            | redSome nil bred => bcpNone\n            | redSome (l::nil) _ =>\n              match assume l G with\n                | Normal newG =>\n                  match bcp newG D' with\n                    | bcpNone => bcpNone\n                    | bcpSome G' D' _ => bcpSome G' (extend l D') true\n                  end\n                | Inconsistent => bcpNone\n              end\n            | redSome Cred bred =>\n              match bcp G D' with\n                | bcpNone => bcpNone\n                | bcpSome G' D' b =>\n                  bcpSome G' (Cred::D') (bred || b)\n              end\n          end\n      end.\n\n    Lemma weak_assume : \n      forall (G : t) (D : cset) (l : L.t), \n        singleton l \\In D -> ~ G |= l ->\n        forall newG, assume l G = Normal newG ->\n        derivable (newG |- cfl (L.expand l) ++ D) ->\n        derivable (G |- D).\n    Proof.\n      intros G0 D0 l Hl HGl G1 Hass1 Hder.\n      case_eq (query (L.mk_not l) G0); intro Hquery.\n      (* - if [L.mk_not l] is entailed by [G0] then\n         we can reduce [{l}] and apply [AConflict]. *)\n      apply ARed with (reds:={l}) (C:={l}); intuition.\n      rewrite <- (singleton_1 H); assumption.\n      apply AConflict; apply add_1; intro k; set_iff; intuition.\n      (* - otherwise, we first [AUnsat] with [l], the left branch\n         is our hypothesis and we reduce and apply [AConflict] on\n         the right. *)\n      case_eq (assume (L.mk_not l) G0); [intros G2 Hass2 | intros Hass2].\n      apply (AUnsat G0 D0 l G1 G2 Hass1 Hass2 Hder).\n      apply ARed with (reds:={l}) (C:={l}).\n      intro k; set_iff; intro Hk; apply query_assumed; \n        rewrite (assumed_assume Hass2); apply add_1; rewrite Hk; auto.\n      reflexivity.\n      apply union_3; auto.\n      apply AConflict; apply add_1; intro k; set_iff; intuition.\n      contradiction HGl; rewrite <- (L.mk_not_invol l);\n        apply assumed_inconsistent; assumption.\n    Qed.\n      \n    Theorem bcp_correct :\n      forall D Dbasis G Gext Dred b,\n        bcp G D = bcpSome Gext Dred b ->\n        derivable (Gext |- ll2s Dred ++ Dbasis) ->\n        derivable (G |- ll2s D ++ Dbasis).\n    Proof with (eauto with typeclass_instances).\n      intro D0; induction D0; intros Dbasis G0 Gext Dred b Hbcp Hder;\n        simpl in Hbcp.\n      inversion Hbcp; subst; simpl in Hder; inversion Hder; eauto with set.\n      assert (Hred := reduce_correct G0 (ll2s D0 ++ Dbasis) a).\n      assert (Hred' := reduce_spec G0 a).\n      destruct (reduce G0 a) as [ared bred|].\n      (* - if the reduction returned a clause (it can't be empty) *)\n      destruct ared as [|l ared]; try discriminate.\n      inversion Hred'; subst; destruct ared.\n      (* - if it is a singleton [{l}], [l] is consistent with [G0] and\n         we can apply [AAssume] *)\n      assert (Hl' : ~ (G0 |= l)) by\n        (intro abs; rewrite (Hsub l (or_introl _ (refl_equal _))) in abs; \n          discriminate).\n      case_eq (assume l G0); [intros newG Hass | intros Hass];\n        rewrite Hass in Hbcp.\n      simpl; rewrite Props.union_add.\n      apply (Hred (l::nil) bred (refl_equal _)); clear Hred.\n      assert (IH := IHD0 (cfl (L.expand l) ++ Dbasis) newG); clear IHD0.\n      destruct (bcp newG D0) as [Gext' Dred' b'|];\n        try discriminate; inversion Hbcp.\n      assert (IH' := IH Gext' Dred' b' (refl_equal _)); clear IH; subst.\n      assert (Hl : Equal (l2s (l::nil)) {l})\n        by (simpl; symmetry; apply Props.singleton_equal_add).\n      destruct (In_dec (ll2s D0 ++ Dbasis) {l}).\n      refine (weak_assume G0 _ l (add_1 _ _) Hl' _ Hass _)...\n      rewrite Props.add_equal.\n      2:(simpl; rewrite <- Props.singleton_equal_add; exact Htrue).\n      rewrite <- Props.union_assoc.\n      rewrite (Props.union_sym (cfl (L.expand l)) (ll2s D0)).\n      rewrite Props.union_assoc; apply IH'.\n      unfold extend in Hder; rewrite ll2s_app in Hder.\n      rewrite ll2s_cfl, <- Props.union_assoc,\n        (Props.union_sym (ll2s Dred')); exact Hder.\n      refine (AAssume G0 _ l (add_1 _ _) _ Hass _)...\n      rewrite Hl, Props.remove_add; auto.\n      rewrite <- Props.union_assoc.\n      rewrite (Props.union_sym (cfl (L.expand l)) (ll2s D0)).\n      rewrite Props.union_assoc; apply IH'.\n      unfold extend in Hder; rewrite ll2s_app in Hder.\n      rewrite ll2s_cfl, <- Props.union_assoc,\n        (Props.union_sym (ll2s Dred')); exact Hder.\n      assert (Z : List.In l (l::nil)) by (left; auto).\n      assert (Hnotl : ~ (G0 |= L.mk_not l)). \n      rewrite HCred, filter_In in Z; destruct (query (L.mk_not l) G0);\n        auto; destruct Z; discriminate.\n      contradiction (Hnotl (assumed_inconsistent Hass)).\n      (* - if the reduced clause is not unitary *)\n      simpl; rewrite Props.union_add.\n      apply (Hred _ _ (refl_equal _)).\n      set (Cred := l::t0::ared) in *; clearbody Cred.\n      assert (IH := IHD0 {l2s Cred; Dbasis} G0); clear IHD0.\n      destruct (bcp G0 D0) as [Gext' Dred' b'|];\n        try discriminate; inversion Hbcp.\n      assert (IH' := IH Gext' Dred' b' (refl_equal _)); clear IH; subst.\n      rewrite Props.union_sym, <- Props.union_add, Props.union_sym.\n      apply IH'. \n      rewrite Props.union_sym, Props.union_add, \n        Props.union_sym, <- Props.union_add; exact Hder.\n      (* - if the clause was eliminated *)\n      assert (IH := fun D => IHD0 D G0).\n      destruct (bcp G0 D0); inversion Hbcp; subst.\n      refine (weakening _ (IH _ _ _ _ (refl_equal _) Hder) _ _).\n      split; simpl; try rewrite Props.union_add; intuition.\n    Qed.\n\n    Theorem bcp_unsat :\n      forall D Dbasis G, bcp G D = bcpNone -> derivable (G |- ll2s D ++ Dbasis).\n    Proof with (eauto with typeclass_instances).\n      intro D0; induction D0; intros Dbasis G0 Hbcp; simpl in Hbcp.\n      discriminate.\n      assert (Hred := reduce_correct G0 (ll2s D0 ++ Dbasis) a).\n      destruct (reduce_spec G0 a).\n      (* - if the clause reduced to the empty clause, we apply [AConflict] *)\n      simpl; rewrite Props.union_add.      \n      destruct Cred as [|l Cred].\n      apply (Hred nil bred (refl_equal _)).\n      apply AConflict; apply add_1; reflexivity.\n      destruct Cred.\n      (* - if the clause is a singleton [{l}], [G0] must be\n         consistent with [l] *)\n      assert (Z : List.In l (l::nil)) by (left; auto).\n      assert (Hnotl : ~ (G0 |= L.mk_not l)). \n      rewrite HCred, filter_In in Z; destruct (query (L.mk_not l) G0);\n        auto; destruct Z; discriminate.\n      assert (Hl' : ~ (G0 |= l)) by\n        (intro abs; rewrite (Hsub l (or_introl _ (refl_equal _))) in abs; \n          discriminate).\n      clear Z; apply (Hred (l::nil) bred (refl_equal _)).\n      case_eq (assume l G0); [intros newG Hass | intros Hass];\n        rewrite Hass in Hbcp.\n      2:(contradiction (Hnotl (assumed_inconsistent Hass))).\n      assert (IH := IHD0 (ll2s (L.expand l) ++ Dbasis) newG); \n        clear IHD0.\n      destruct (bcp newG D0); try discriminate.\n      simpl; rewrite <- Props.singleton_equal_add.\n      assert (Hl : Equal (l2s (l::nil)) {l})\n        by (simpl; symmetry; apply Props.singleton_equal_add).\n      destruct (In_dec (ll2s D0 ++ Dbasis) {l}).\n      refine (weak_assume G0 _ l (add_1 _ _) Hl' _ Hass _)...\n      rewrite Props.add_equal; auto.\n      rewrite <- Props.union_assoc.\n      rewrite (Props.union_sym (cfl (L.expand l)) (ll2s D0)).\n      rewrite Props.union_assoc, ll2s_cfl; exact (IH (refl_equal _)).\n      refine (AAssume G0 _ l (add_1 _ _) _ Hass _)...\n      rewrite Props.remove_add; auto.\n      rewrite <- Props.union_assoc.\n      rewrite (Props.union_sym (cfl (L.expand l)) (ll2s D0)).\n      rewrite Props.union_assoc, ll2s_cfl; exact (IH (refl_equal _)).\n      (* if the clause is not unitary after reduction *)\n      assert (IH := IHD0 Dbasis G0); clear IHD0.\n      destruct (bcp G0 D0); try discriminate.\n      apply (Hred _ _ (refl_equal _)).\n      refine (weakening _ (IH (refl_equal _)) _ _).\n      split; simpl; intuition.\n      (* if the clause was eliminated *)\n      assert (IH := IHD0 Dbasis G0); clear IHD0.\n      destruct (bcp G0 D0); try discriminate.\n      refine (weakening _ (IH (refl_equal _)) _ _).\n      split; simpl; intuition; rewrite Props.union_add; intuition.\n    Qed.\n\n    Theorem bcp_progress :\n      forall D G Gext Dred b,\n        bcp G D = bcpSome Gext Dred b -> \n        if b then L.llsize Dred < L.llsize D else Gext = G /\\ Dred = D.\n    Proof.\n      intro D0; induction D0; intros G0 Gext Dred b Hbcp; simpl in Hbcp.\n      inversion Hbcp; subst; split; reflexivity.\n      destruct (reduce_spec G0 a).\n      destruct Cred; try discriminate.\n      destruct Cred.\n      case_eq (assume t0 G0); [intros newG Hass | intros Hass];\n        rewrite Hass in Hbcp; try discriminate.\n      assert (IH := IHD0 newG).\n      destruct (bcp newG D0); inversion Hbcp; subst.\n      assert (IH' := IH _ _ _ (refl_equal _)); destruct b0.\n      unfold extend; simpl; rewrite llsize_app.\n      destruct bred; subst; simpl in *; generalize (L.size_expand t0); omega.\n      destruct IH'; subst; unfold extend; simpl; rewrite llsize_app.\n      destruct bred; subst; simpl in *; generalize (L.size_expand t0); omega.\n      assert (IH := IHD0 G0).\n      destruct (bcp G0 D0); inversion Hbcp; subst.\n      destruct bred; simpl.\n      assert (IH' := IH _ _ _ (refl_equal _)); destruct b0; simpl in *.\n      omega. rewrite (proj2 IH'); omega.\n      assert (IH' := IH _ _ _ (refl_equal _)); destruct b0; simpl in *.\n      rewrite Hbred; simpl; omega.\n      destruct IH'; split; congruence.\n      assert (IH := IHD0 G0).\n      destruct (bcp G0 D0); inversion Hbcp; subst.\n      assert (IH' := IH _ _ _ (refl_equal _)); destruct b0; simpl.\n      omega.\n      rewrite (proj2 IH'); revert Hin; clear; induction a; simpl.\n      contradiction. generalize (L.size_pos a); intuition.\n    Qed.\n\n    Theorem bcp_consistent :\n      forall D G Gext Dred,\n        bcp G D = bcpSome Gext Dred false -> \n        forall l C, C \\In ll2s Dred -> l \\In C -> \n          ~ Gext |= l /\\ ~ Gext |= L.mk_not l.\n    Proof.\n      intros D0 G0 Gext Dred Hbcp l C HC Hl.\n      assert (Hprog := bcp_progress D0 G0 _ _ _ Hbcp).\n      destruct Hprog; subst.\n      revert G0 l C Hl HC Hbcp; induction D0; intros; simpl in Hbcp.\n      simpl in HC; contradiction (empty_1 HC).\n      destruct (reduce_spec G0 a).\n      destruct Cred; try discriminate.\n      destruct Cred.\n      case_eq (assume t0 G0); [intros newG Hass | intros Hass];\n        rewrite Hass in Hbcp; try discriminate.\n      destruct (bcp newG D0); discriminate.\n      assert (IH := IHD0 G0 l); clear IHD0.\n      destruct (bcp G0 D0); inversion Hbcp; subst.\n      destruct bred; simpl in H3; try discriminate.\n      set (Z := t0 :: t1 :: Cred) in *; clearbody Z.\n      simpl in HC; rewrite add_iff in HC; destruct HC.\n      rewrite <- H in Hl; rewrite l2s_iff in Hl.\n      rewrite InA_alt in Hl; destruct Hl as [k [Hk1 Hk2]].\n      split; intro abs.\n      assert (Hk := Hsub k Hk2); rewrite <- Hk1 in Hk; congruence.\n      rewrite HCred in Hk2; rewrite filter_In in Hk2.\n      rewrite Hk1 in abs; destruct (query (L.mk_not k) G0); \n        destruct Hk2; discriminate.\n      clear HCred; subst; eauto.\n      destruct (bcp G0 D0); inversion Hbcp; subst.\n    Qed.\n\n    Lemma bcp_monotonic_env : \n      forall D G Gext Dred b,\n        bcp G D = bcpSome Gext Dred b -> dom G [<=] dom Gext.\n    Proof.\n      intro D0; induction D0; intros G0 Gext Dred b Hbcp;\n        simpl in Hbcp.\n      inversion Hbcp; subst; simpl; reflexivity.\n      destruct (reduce G0 a) as [Cred bred|].\n      destruct Cred as [|l Cred]; try discriminate.\n      destruct Cred.\n      case_eq (assume l G0); [intros newG Hass | intros Hass];\n        rewrite Hass in Hbcp; try discriminate.\n      assert (IH := IHD0 newG).\n      destruct (bcp newG D0); inversion Hbcp; subst.\n      transitivity (dom newG).\n      rewrite (assumed_assume Hass); intuition.\n      exact (IH _ _ _ (refl_equal _)).\n      assert (IH := IHD0 G0).\n      destruct (bcp G0 D0); inversion Hbcp; subst.\n      exact (IH _ _ _ (refl_equal _)).\n      assert (IH := IHD0 G0).\n      destruct (bcp G0 D0); inversion Hbcp; subst.\n      exact (IH _ _ _ (refl_equal _)).\n    Qed.\n\n(*     Theorem bcp_complete :  *)\n(*       forall D Dbasis G Gext Dred b, *)\n(*         bcp G D = bcpSome Gext Dred b -> *)\n(*         compatible_e G (ll2s D ++ Dbasis) ->  *)\n(*         compatible_e Gext (ll2s Dred ++ Dbasis). *)\n(*     Proof. *)\n(*       intro D0; induction D0; intros Dbasis G0 Gext Dred b Hbcp Hsat; *)\n(*         simpl in Hbcp. *)\n(*       inversion Hbcp; subst; simpl; exact Hsat. *)\n(*       assert (Hred := reduce_complete G0 a). *)\n(*       destruct (reduce G0 a) as [Cred bred|]. *)\n(*       destruct Cred as [|l Cred]; try discriminate. *)\n(*       destruct Cred. *)\n      \n(*       assert (Hmon := bcp_monotonic_env D0 (assume l G0)). *)\n(*       assert (IH := IHD0 (ll2s (L.expand l) ++ Dbasis) (assume l G0)); *)\n(*         clear IHD0; destruct (bcp (assume l G0) D0); inversion Hbcp; subst. *)\n(*       assert (IH' := IH _ _ _ (refl_equal _)); clear IH. *)\n(*       intros M HM C HC; unfold extend in HC;  *)\n(*         simpl in HC; rewrite ll2s_app in HC. *)\n(*       rewrite (Props.union_sym _ (ll2s l0)), Props.union_assoc in HC. *)\n(*       revert M HM C HC; apply IH'. *)\n(*       intros M HM C HC; unfold extend in HC; simpl in HC;  *)\n(*         rewrite (Props.union_sym (ll2s D0)),  Props.union_assoc in HC. *)\n(*       rewrite union_iff in HC; destruct HC. *)\n(*       apply ll2s_expand with l; auto; apply HM; apply EnvF.query_assume; auto. *)\n(*       apply Hsat; auto. *)\n(*       intros k Hk; apply HM; apply query_monotonic with G0; auto. *)\n(*       rewrite assumed_assume; intuition. *)\n(*       simpl; rewrite Props.union_add, Props.union_sym; apply add_2; auto. *)\n\n(*       assert (Hmon := bcp_monotonic_env D0 G0). *)\n(*       assert (IH := IHD0 Dbasis G0); *)\n(*         clear IHD0; destruct (bcp G0 D0); inversion Hbcp; subst. *)\n(*       assert (IH' := IH _ _ _ (refl_equal _)); clear IH. *)\n(*       intros M HM C HC; simpl in HC; rewrite Props.union_add in HC. *)\n(*       rewrite add_iff in HC; destruct HC. *)\n(*       destruct (Hred _ _ M (refl_equal _)). *)\n(*       intros k Hk; apply HM; apply query_monotonic with G0; auto; *)\n(*         exact (Hmon _ _ _ (refl_equal _)). *)\n(*       apply Hsat; [|simpl; apply union_2; apply add_1; auto]. *)\n(*       intros k Hk; apply HM; apply query_monotonic with G0; auto; *)\n(*         exact (Hmon _ _ _ (refl_equal _)). *)\n(*       exists x; rewrite <- H; exact H0. *)\n(*       apply IH'; auto; intros M' HM' C' HC'; apply Hsat; auto; *)\n(*         simpl; rewrite Props.union_add; apply add_2; auto. *)\n\n(*       assert (IH := IHD0 Dbasis G0); clear IHD0; destruct (bcp G0 D0); *)\n(*         inversion Hbcp; subst. *)\n(*       apply (IH Gext Dred b0 (refl_equal _)). *)\n(*       intros M HM C HC; apply Hsat; auto. *)\n(*       simpl; rewrite Props.union_add; apply add_2; exact HC. *)\n(*     Qed. *)\n\n    Theorem bcp_complete : \n      forall D Dbasis G Gext Dred b M,\n        bcp G D = bcpSome Gext Dred b ->\n        submodel_e Gext M -> Sem.sat_goal M (ll2s Dred ++ Dbasis) ->\n        submodel_e G M /\\ Sem.sat_goal M (ll2s D ++ Dbasis).\n    Proof.\n      intro D0; induction D0; intros Dbasis G0 Gext Dred b M Hbcp Hsub Hsat;\n        simpl in Hbcp.\n      inversion Hbcp; subst; simpl; tauto.\n      assert (Hred := reduce_spec G0 a).\n      assert (Hred' := reduce_complete G0 a).\n      destruct (reduce G0 a) as [Cred bred|].\n      destruct Cred as [|l Cred]; try discriminate.\n      destruct Cred.\n\n      case_eq (assume l G0); [intros newG Hass | intros Hass];\n        rewrite Hass in Hbcp; try discriminate.\n      assert (IH := IHD0 (ll2s (L.expand l) ++ Dbasis) newG); clear IHD0.\n      destruct (bcp newG D0) as [Gext' Dred' b'|]; \n        inversion Hbcp; subst.\n      destruct (IH Gext Dred' b' M) as [IH1 IH2]; auto.\n      intros C HC; apply Hsat; simpl; unfold extend; \n        rewrite ll2s_app, (Props.union_sym _ (ll2s Dred')),\n          Props.union_assoc; exact HC.\n      split.\n      intros k Hk; apply IH1; apply query_monotonic with G0; auto.\n      rewrite (assumed_assume Hass); intuition.\n      intros C HC; simpl in HC; rewrite Props.union_add, add_iff in HC; \n        destruct HC as [HC|HC].\n      destruct (Hred' _ _ M (refl_equal _)) as [k [Hk1 Hk2]].\n      intros k Hk; apply IH1; apply query_monotonic with G0; auto.\n      rewrite (assumed_assume Hass); intuition.\n      simpl; exists l; simpl; split; intuition.\n      apply IH1; apply (EnvF.query_assume Hass); auto.\n      exists k; rewrite <- HC; tauto.\n      apply IH2; revert HC; set_iff; clear; tauto.\n\n      assert (IH := IHD0 Dbasis G0); clear IHD0.\n      destruct (bcp G0 D0) as [Gext' Dred' b'|]; inversion Hbcp; subst.\n      destruct (IH Gext Dred' b' M) as [IH1 IH2]; auto.\n      intros C HC; apply Hsat; simpl; rewrite Props.union_add;\n        apply add_2; auto.\n      split; auto; intros C HC; simpl in HC; \n        rewrite Props.union_add, add_iff in HC; \n          destruct HC as [HC|HC].\n      destruct (Hred' _ _ _ (refl_equal _) IH1) as [k [Hk1 Hk2]].\n      apply Hsat; simpl; apply union_2; apply add_1; auto.\n      exists k; rewrite <- HC; tauto.\n      auto.\n\n      assert (IH := IHD0 Dbasis G0); clear IHD0.\n      destruct (bcp G0 D0); inversion Hbcp; subst.\n      destruct (IH Gext Dred b0 M) as [IH1 IH2]; auto.\n      split; auto; intros C HC; simpl in HC; \n        rewrite Props.union_add, add_iff in HC; destruct HC as [HC|HC].\n      inversion Hred; exists l; split.\n      apply IH1; auto. rewrite <- HC, l2s_iff; exact (ListIn_In Hin).\n      apply IH2; auto.\n    Qed.\n          \n  End BCP.\n\n  (** ** The main [proof_search] function *)\n  (**  The [proof_search] function applies [bcp] repeatedly as long as \n     progress has been made, and otherwise just picks a literal to split on. *)\n  Inductive Res : Type :=\n  | Sat : E.t -> Res\n  | Unsat.\n  Fixpoint proof_search (G : E.t) (D : list (list L.t)) \n    (n : nat) {struct n} : Res :=\n    match n with\n      | O => Sat empty (* assert false *)\n      | S n0 =>\n        match bcp G D with \n          | bcpNone => Unsat\n          | bcpSome newG newD b =>\n            match newD with\n              | nil => Sat newG\n              | cons nil newD' => Unsat (* assert false *)\n              | cons (cons l C) newD' =>\n  (*   tant qu'on a progressé avec bcp, on reessaye *)\n  (*   (si bcp etait recursive on n'aurait pas besoin de ça  *)\n  (*    mais ca ne change rien en terme de performance ici) *)\n                if b then proof_search newG newD n0\n                else (* from that point on, G = newG, D = newD *)\n                  match assume l G with\n                    | Normal G1 =>\n                      match proof_search G1 (extend l newD') n0 with\n                        | Sat M => Sat M\n                        | Unsat =>\n                          let lbar := L.mk_not l in\n                            match assume lbar G with\n                              | Normal G2 =>\n                                proof_search G2 (extend lbar (cons C newD')) n0\n                              | Inconsistent => Unsat\n                            end\n                      end\n                    | Inconsistent => Unsat\n                  end\n            end\n        end\n    end.\n\n  Lemma expand_nonrec : \n    forall l C, C \\In (cfl (L.expand l)) -> l \\In C -> False.\n  Proof.\n    intros l C; rewrite cfl_1.\n    assert (Hsize := L.size_expand l).\n    revert Hsize; generalize (L.expand l); intro L; induction L;\n      intros Hsize H Hl; simpl in *.\n    contradiction (empty_1 H).\n    rewrite add_iff in H; destruct H.\n    set (N := L.llsize L) in *; clearbody N; clear L IHL.\n    rewrite <- H in Hl; clear H C; induction a.\n    simpl in Hl; contradiction (empty_1 Hl).\n    simpl in Hl; rewrite add_iff in Hl; destruct Hl.\n    simpl in Hsize; rewrite H in Hsize; omega.\n    simpl in Hsize; apply IHa; auto; omega.\n    apply IHL; auto.\n    revert Hsize; clear; induction a; simpl; auto.\n    intro; omega.\n  Qed.\n  Lemma expand_nonrec_2 : \n    forall l C, C \\In (cfl (L.expand l)) -> L.mk_not l \\In C -> False.\n  Proof.\n    intros l C; rewrite cfl_1.\n    assert (Hsize := L.size_expand l).\n    revert Hsize; generalize (L.expand l); intro L; induction L;\n      intros Hsize H Hl; simpl in *.\n    contradiction (empty_1 H).\n    rewrite add_iff in H; destruct H.\n    set (N := L.llsize L) in *; clearbody N; clear L IHL.\n    rewrite <- H in Hl; clear H C; induction a.\n    simpl in Hl; contradiction (empty_1 Hl).\n    simpl in Hl; rewrite add_iff in Hl; destruct Hl.\n    simpl in Hsize; rewrite H in Hsize; assert (Z := L.size_mk_not l); omega.\n    simpl in Hsize; apply IHa; auto; omega.\n    apply IHL; auto.\n    revert Hsize; clear; induction a; simpl; auto.\n    intro; omega.\n  Qed.\n\n  Property remove_transpose : forall (D : cset) (C C' : clause),\n    {{D ~ C'} ~ C} [=] {{D ~ C} ~ C'}.\n  Proof.\n    intros; intro k; set_iff; intuition.\n  Qed.\n  Lemma remove_union : forall (D D' : cset) (C : clause), \n    ~C \\In D -> {(D ++ D') ~ C} [=] D ++ {D' ~ C}.\n  Proof.\n    intros; intro k; set_iff; intuition.\n    intro abs; rewrite abs in H; tauto.\n  Qed.\n  Lemma union_remove : forall (D D' : cset) (C : clause), \n    C \\In D -> D ++ D' [=] D ++ {D' ~ C}.\n  Proof.\n    intros; intro k; set_iff; intuition.\n    destruct (eq_dec C k); auto.\n    rewrite H0 in H; left; auto.\n  Qed.\n\n(*   Lemma remove_singleton : forall l (A : clause),  *)\n(*     singleton l \\ A =/= singleton l -> singleton l \\ A === {}. *)\n(*   Proof. *)\n(*     intros; intro k; split; set_iff; intuition. *)\n(*     apply H; intro z; set_iff; intuition. *)\n(*     rewrite <- H1 in H2; rewrite H0 in H2; tauto. *)\n(*   Qed. *)\n(*   Lemma diff_union : forall (A B C : clause), C \\ (A ++ B) [=] C \\ A \\ B. *)\n(*   Proof. *)\n(*     intros; intro k; set_iff; intuition. *)\n(*   Qed. *)\n    \n  Theorem proof_search_unsat :\n    forall n G D, proof_search G D n = Unsat -> derivable (G |- ll2s D).\n  Proof with (eauto with typeclass_instances).\n    induction n; intros G0 D0; unfold proof_search.\n    (* - if [D0] is empty, it is satisfiable *)\n    intro abs; discriminate abs.\n    (* - otherwise, we do a step of BCP *)\n    fold proof_search; intro Hunsat.\n    assert (Hbcp := bcp_correct D0 {} G0).\n    assert (Hbcp2 := bcp_unsat D0 {} G0).\n    assert (Hprogress := bcp_progress D0 G0).\n    assert (Hcons := bcp_consistent D0 G0).\n    destruct (bcp G0 D0) as [Gext Dred b|].\n    (* -- if BCP returns a sequent, it can't be empty *)\n    assert (Hbcp' := Hbcp Gext _ _ (refl_equal _)); clear Hbcp.\n    rewrite !Props.empty_union_2 in Hbcp'; intuition.\n    rewrite !Props.empty_union_2 in Hbcp2; intuition.\n    (* -- if BCP returns a sequent, it can't be empty *)\n    destruct Dred as [|C Dred]; try discriminate.\n    destruct C as [|l C].\n    (* -- if BCP returned a sequent with the empty clause, [AConflict] *)\n    apply Hbcp'; simpl; apply AConflict; apply add_1; auto.\n    destruct b; auto.\n    (* -- if BCP didnt change anything... *)\n    assert (Hcons' := Hcons Gext _ (refl_equal _)); clear Hcons.\n    destruct (Hprogress _ _ _ (refl_equal _)); subst.\n    simpl in Hcons'; destruct (Hcons' l {l; l2s C}) as [Hl Hnotl];\n      try (simpl; apply add_1; reflexivity).\n    case_eq (assume l G0); [intros G1 Hass1 | intros Hass1];\n      rewrite Hass1 in Hunsat.\n    2:(contradiction (Hnotl (assumed_inconsistent Hass1))).\n    assert (IH1 := IHn G1 (extend l Dred)).\n    (* -- the first recursive call must have return Unsat *)\n    destruct (proof_search G1 (extend l Dred)); try discriminate.\n    case_eq (assume (L.mk_not l) G0); [intros G2 Hass2 | intros Hass2];\n      rewrite Hass2 in Hunsat.\n    2:(rewrite <- (L.mk_not_invol l) in Hl;\n      contradiction (Hl (assumed_inconsistent Hass2))).\n    destruct (In_dec (ll2s Dred) (l2s (l :: C))).\n    simpl; rewrite Props.add_equal; auto.\n    apply AUnsat with l G1 G2; auto.\n    unfold extend in IH1; rewrite ll2s_app in IH1.\n    rewrite ll2s_cfl; exact (IH1 (refl_equal _)).\n    destruct (In_dec (l2s C) l).\n    simpl in Htrue; rewrite (Props.add_equal Htrue0) in Htrue.\n    assert (IH2 := IHn _ _ Hunsat); unfold extend in IH2.\n    rewrite ll2s_app in IH2; rewrite ll2s_cfl.\n    simpl in IH2; rewrite (Props.add_equal Htrue) in IH2.\n    exact IH2.\n    apply ARed with {l} {l; l2s C}.\n    intro k; set_iff; intro Hk; apply (EnvF.query_assume Hass2); \n      rewrite Hk; auto.\n    intro k; set_iff; intuition.\n    apply union_3; auto.\n    assert (IH2 := IHn _ _ Hunsat); unfold extend in IH2.\n    rewrite ll2s_app in IH2; rewrite ll2s_cfl.\n    rewrite Props.union_sym, <- Props.union_add, Props.union_sym.\n    rewrite <- Props.remove_diff_singleton, (Props.remove_add Hfalse).\n    exact IH2.\n\n    apply AUnsat with l G1 G2; auto.\n    apply AElim with l (l2s (l::C)).\n    apply query_assumed; rewrite (assumed_assume Hass1); apply add_1; auto.\n    simpl; apply add_1; auto.\n    apply union_3; simpl; apply add_1; auto.\n    rewrite remove_union.\n    2:(intro abs; apply expand_nonrec with l {l; l2s C}; intuition).\n    simpl in Hfalse |- *; rewrite (Props.remove_add Hfalse).\n    rewrite ll2s_cfl; unfold extend in IH1. \n    rewrite ll2s_app in IH1; exact (IH1 (refl_equal _)).\n    assert (IH2 := IHn _ _ Hunsat).\n    unfold extend in IH2; rewrite ll2s_app, <- ll2s_cfl in IH2; simpl in *.\n    destruct (In_dec (l2s C) l).\n    simpl in *; rewrite (Props.add_equal Htrue).\n    exact IH2.\n    apply AStrongRed with (C:=l2s (l::C))(reds := {l}).\n    intro k; set_iff; intro Hk; apply (EnvF.query_assume Hass2); \n      rewrite Hk; auto.\n    intro k; simpl; set_iff; intuition.\n    apply union_3; simpl; apply add_1; auto.\n    rewrite remove_union.\n    2:(intro abs; apply expand_nonrec_2 \n      with (L.mk_not l) {l; l2s C}; try rewrite L.mk_not_invol; intuition).\n    simpl in Hfalse; rewrite (Props.remove_add Hfalse).\n    rewrite Props.union_sym, <- Props.union_add, Props.union_sym.\n    rewrite <- Props.remove_diff_singleton.\n    rewrite (Props.remove_add Hfalse0).\n    exact IH2.\n    (* -- if BCP did not return a sequent, we apply the correctness of [bcp] *)\n    rewrite Props.empty_union_2 in Hbcp2.\n    exact (Hbcp2 (refl_equal _)).\n    intuition.\n  Qed.\n\n  Theorem proof_search_sat :\n    forall n G D M, L.llsize D < n ->\n      proof_search G D n = Sat M -> \n      dom G [<=] dom M /\\ compatible_e M (ll2s D).\n  Proof.\n    induction n; intros G0 D0 M Hlt; unfold proof_search.\n\n    apply False_rec; omega.\n    \n    fold proof_search; intros Hsat.\n    assert (Hbcp := bcp_complete D0 {} G0).\n    assert (Hmon := bcp_monotonic_env D0 G0).\n    assert (Hprogress := bcp_progress D0 G0).\n    destruct (bcp G0 D0) as [Gext Dred b|]; try discriminate.\n    destruct Dred as [|C Dred].\n\n    inversion Hsat; subst; split.\n    exact (Hmon _ _ _ (refl_equal _)).\n    intros Model Hsub; destruct (Hbcp _ _ _ _ (refl_equal _) Hsub).\n    intros k Hk; simpl in Hk.\n    rewrite !Props.empty_union_2 in Hk; try solve [intuition].\n    contradiction (empty_1 Hk).\n    intros C HC; apply H0; apply union_2; auto.\n\n    destruct C as [|l C]; try discriminate.\n    assert (Hbcp' := fun Model => Hbcp _ _ _ Model (refl_equal _)); clear Hbcp.\n    assert (Hprogress' := Hprogress _ _ _ (refl_equal _)); clear Hprogress.\n    assert (Hmon' := Hmon _ _ _ (refl_equal _)); clear Hmon.\n    destruct b; auto.\n    \n    destruct (IHn Gext ((l::C)::Dred) M) as [IH1 IH2]; auto; try omega.\n    split. transitivity (dom (Gext)); auto.\n    intros Model Hsub; destruct (Hbcp' Model) as [Hbcp1 Hbcp2].\n    intros k Hk; apply Hsub; apply query_monotonic with Gext; auto.\n    intros B HB; rewrite !Props.empty_union_2 in HB; try solve [intuition].\n    apply IH2; auto.\n    intros B HB; apply Hbcp2; apply union_2; auto.\n\n    destruct Hprogress'; subst; clear Hmon' Hbcp'.\n    case_eq (assume l G0) ; [intros G1 Hass1 | intros Hass1]; \n      rewrite Hass1 in Hsat; try discriminate.\n    case_eq (proof_search G1 (extend l Dred) n);\n      [intros M' Heq | intros Heq]; rewrite Heq in Hsat; simpl in Hsat.\n    inversion Hsat; subst.\n    destruct (IHn G1 (extend l Dred) M) as [IH1 IH2]; auto.\n    unfold extend; simpl in *; rewrite llsize_app.\n    generalize (L.size_expand l); omega.\n    split.\n    transitivity (dom G1); auto. rewrite (assumed_assume Hass1); intuition.\n    simpl; intros Model Hsub B HB; rewrite add_iff in HB; destruct HB.\n    exists l; split; [|rewrite <- H; apply add_1; auto].\n    apply Hsub; apply query_monotonic with G1; auto.\n    apply (EnvF.query_assume Hass1); auto.\n    apply IH2; auto; unfold extend; rewrite ll2s_app; apply union_3; auto.\n\n    case_eq (assume (L.mk_not l) G0); [intros G2 Hass2 | intros Hass2]; \n      rewrite Hass2 in Hsat; try discriminate.    \n    destruct (IHn G2 (extend (L.mk_not l) (C::Dred)) M) as [IH1 IH2]; auto.\n    unfold extend; simpl in *; rewrite llsize_app; simpl.\n    generalize (L.size_mk_not l) (L.size_expand (L.mk_not l)); omega.\n    split.\n    transitivity (dom G2); auto.\n    rewrite (assumed_assume Hass2); intuition.\n    simpl; intros Model Hsub B HB; rewrite add_iff in HB; destruct HB.\n    destruct (IH2 _ Hsub (l2s C)) as [k [Hk1 Hk2]].\n    unfold extend; rewrite ll2s_app; apply union_3; apply add_1; auto.\n    exists k; split; auto; rewrite <- H; apply add_2; auto.\n    apply IH2; auto; unfold extend; rewrite ll2s_app; \n      apply union_3; apply add_2; auto.\n  Qed.\n\n  (** ** The main entry point to the SAT-solver *)\n  Definition dpll (Pb : formula) :=\n    let D0 := make Pb in\n    let D0_as_list := List.map elements (elements D0) in\n    let mu := (Datatypes.S (L.llsize D0_as_list)) in\n      proof_search empty D0_as_list mu.\n\n  Remark l2s_elements : forall C, l2s (elements C) [=] C.\n  Proof.\n    intros C k; rewrite (elements_iff C).\n    remember (elements C) as L; clear C HeqL; revert k; induction L.\n    simpl; split; intuition.\n    intros k; split; intuition.\n    simpl in H; rewrite add_iff in H; destruct H.\n    constructor 1; auto.\n    constructor 2; exact ((proj1 (IHL k)) H).\n    inversion H; subst.\n    apply add_1; auto.\n    apply add_2; exact ((proj2 (IHL k)) H1).\n  Qed.\n  Remark ll2s_map_elements : \n    forall D, ll2s (List.map elements (elements D)) [=] D.\n  Proof.\n    intros D0 k; rewrite (elements_iff D0).\n    remember (elements D0) as L; clear HeqL; revert D0 k; induction L.\n    simpl; split; intuition.\n    intros D0 k; split; intuition.\n    simpl in H; rewrite add_iff in H; destruct H.\n    constructor 1. rewrite l2s_elements in H; symmetry; auto.\n    constructor 2; exact ((proj1 (H0 k)) H).\n    simpl; inversion H; subst.\n    apply add_1; rewrite l2s_elements; symmetry; auto.\n    apply add_2; exact ((proj2 (H0 k)) H2).\n  Qed.\n\n  Theorem dpll_correct :\n    forall Pb, dpll Pb = Unsat -> Sem.incompatible {} (make Pb).\n  Proof.\n    intros Pb Hunsat; unfold dpll in Hunsat.\n    intros M HM; apply (soundness (empty |- make Pb)).\n    assert (H := proof_search_unsat _ _ _ Hunsat).\n    rewrite ll2s_map_elements in H; assumption.\n    simpl; intros l; rewrite assumed_empty; set_iff; intro Hl.\n    rewrite <- (Sem.morphism _ _ _ Hl); apply Sem.wf_true.\n  Qed.\n\nEnd SATCAML.\n", "meta": {"author": "coq-contribs", "repo": "ergo", "sha": "d31962ab6cb56861e5d83691d4d5cea1b769f2c2", "save_path": "github-repos/coq/coq-contribs-ergo", "path": "github-repos/coq/coq-contribs-ergo/ergo-d31962ab6cb56861e5d83691d4d5cea1b769f2c2/theories/SatCaml.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22179253962631099}}
{"text": "From iris.program_logic Require Import weakestpre.\nRequire Import FunctionalExtensionality.\nFrom iris.base_logic.lib Require Import gen_heap.\nFrom iris.proofmode Require Import tactics.\nRequire Import Ctypes.\n\nModule monad.\n\n  Section monad_rules.\n    Context {state  : Type}.\n    Context ( M : Type -> Type).\n    Context ( ret : forall X, X -> M X).\n    Context ( bind : forall X Y, M X -> (X -> M Y) -> M Y ).\n    Arguments ret {_} x.\n    Arguments bind {_ _} x f.\n    Inductive err (X: Type) : Type :=\n    | Erro : Errors.errmsg -> err X\n    | Res : X -> err X.\n\n    Class MonadProp :=\n      {\n        left_id (X Y : Type) (a : X) (f : X -> M Y) : bind (ret a) f = f a;\n        right_id (X : Type) (m : M X) : bind m ret = m;\n        assoc_bind (X Y Z : Type) (m : M X) f (g : Y -> M Z) :\n          bind (bind m f) g = bind m (fun x => bind (f x) g)\n      }.\n\n  End monad_rules.\n\n  Structure monad :=\n    Monad {\n        M : Type -> Type;\n        state : Type;\n        ret : forall (X : Type), X -> M X;\n        bind : forall X Y, M X -> (X -> M Y) -> M Y;\n        run : forall X, M X -> state -> err (state * X);\n        prop : MonadProp M ret bind\n      }.\n  \nEnd monad.\n\nModule gensym.\n  Import monad.\n  Local Open Scope positive_scope.\n  \n  Definition ident := positive.\n  Definition state := gmap ident type.\n  Definition empty_state : state := gmap_empty.\n  Definition state_to_list (s : state) := gmap_to_list s.\n  \n  (* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%ùùùùù*)\n  Inductive sig (X : Type) : Type :=\n  | Err : Errors.errmsg -> sig X\n  | Gensym : type -> (ident -> X) -> sig X.\n\n  Arguments Err [X].\n  Arguments Gensym [X].\n  \n  Inductive mon (X : Type) : Type :=\n  | ret : X -> mon X\n  | op : sig (mon X) -> mon X.\n\n  Arguments ret {_} x.\n  Arguments op {_} s.\n  \n  Fixpoint bind {X Y} (m : mon X) (f : X -> mon Y) : mon Y :=\n    match m with\n    | ret x => f x\n    | op (Err e) => op (Err e)\n    | op (Gensym t g) => op (Gensym t (fun x => bind (g x) f))\n    end.\n\n  Definition error {X} (e : Errors.errmsg) : mon X := op (Err e).\n  Definition gensym (t : type) : mon ident := op (Gensym t ret).  \n\n  Lemma lid : forall X Y (a : X) (f : X -> mon Y), bind (ret a) f = f a.\n  Proof. auto. Qed.\n\n  Lemma rid : forall X (m : mon X), bind m ret = m.\n  Proof.\n    fix m 2.\n    destruct m0.\n    * reflexivity.\n    * destruct s.\n      ** reflexivity.\n      ** simpl. do 2 f_equal. apply functional_extensionality. intro. apply m.\n  Qed.\n\n  Lemma ass_bind : forall X Y Z (m : mon X) f (g : Y -> mon Z),\n      bind (bind m f) g = bind m (fun x => bind (f x) g).\n  Proof.\n    fix m 4.\n    destruct m0; intros.\n    * reflexivity.\n    * destruct s.\n      ** reflexivity.\n      ** simpl. do 2 f_equal. apply functional_extensionality. intro. apply m.\n  Qed.\n\n  Hint Resolve lid rid ass_bind.\n\n  Instance mP : @MonadProp mon (@ret) (@bind).\n  Proof. split; eauto. Qed.\n\n  Arguments Erro [X].\n  Arguments Res [X].\n  Local Open Scope positive_scope.\n\n  Definition fresh (s : state) :=\n    map_fold (fun x _ res => Pos.max res (x+1)) 1 s.\n  \n  Fixpoint run {X} (m : mon X) : state -> err (state * X) :=\n    match m with\n    | ret v => fun s => Res (s, v)\n    | op (Err e) => fun s => Erro e\n    | op (Gensym t f) =>\n      fun s =>\n        let l := fresh s in\n        run (f l) (<[l := t]>s)\n    end.\n  \n\n  Canonical Structure gensym_monad := @Monad mon state (@ret) (@bind) (@run) mP.\n\nEnd gensym.\n\nModule weakestpre_gensym.\n  Import monad.\n  Export gensym.\n  Export gen_heap.\n  \n  (** Override the notations so that scopes and coercions work out *)\n  Notation \"l ↦ t\" :=\n    (mapsto (L:=ident) (V:=type) l 1 t) (at level 20) : bi_scope.\n\n  Notation \"\\s l\" :=\n    (∃ t, l ↦ t)%I (at level 20) : bi_scope.\n\n  Notation \"P ⨈ Q\" := (((P -∗ False) ∗ (Q -∗ False)) -∗ False)%I (at level 19) : bi_scope.\n  Class heapG Σ :=\n    HeapG {\n        heap_preG_iris :> invG Σ;\n        heapG_gen_heapG :> gen_heapG ident type Σ;\n      }.\n  Section mwp.\n    Context `{!heapG Σ}.\n    \n    Fixpoint mwp {X} `{!heapG Σ} (e1 : mon X) (Q : X -> iProp Σ) : iProp Σ :=\n      match e1 with\n      | ret v => Q v\n      | op (Err e) => True\n      | op (Gensym t f) =>\n        ∀ σ, gen_heap_ctx σ ==∗ mwp (f (fresh σ)) Q ∗ gen_heap_ctx (<[ fresh σ := t ]>σ)\n      end%I.\n  End mwp.\n\n  Notation \"'WP' e |{ Φ } |\" := (mwp e Φ)\n                                  (at level 20, e, Φ at level 200, only parsing) : bi_scope.\n  \n  Notation \"'WP' e |{ v , Q } |\" := (mwp e (λ v, Q))\n                                      (at level 20, e, Q at level 200,\n                                       format \"'[' 'WP'  e  '[ ' |{  v ,  Q  } | ']' ']'\") : bi_scope.\n  \n  Notation \"'|{{' P } } | e |{{ x .. y , 'RET' pat ; Q } } |\" :=\n    (∀ Φ,\n        P -∗ (∀ x, .. (∀ y, Q -∗ Φ pat) .. ) -∗ WP e |{ Φ }|)%I\n        (at level 20, x closed binder, y closed binder,\n        format \"'[hv' |{{  P  } } |  '/  ' e  '/'  |{{  x  ..  y ,  RET  pat ;  Q  } } | ']'\") : bi_scope.\n\n  Lemma fresh_is_fresh : forall σ, σ !! (fresh σ) = None.\n  Admitted.\n\n  Section mwp_proof.\n    Context `{!heapG Σ}.\n    Lemma mwp_value' {X} Φ (v : X) : Φ v ⊢ WP ret v |{ Φ }|.\n    Proof. auto. Qed.\n    Lemma mwp_value_inv' {X} Φ (v : X) : WP ret v |{ Φ }| -∗ Φ v.\n    Proof. auto. Qed.\n\n    Lemma mwp_mono {X} e Φ Ψ :\n      WP e |{ Φ }| -∗ (∀ (v : X), Φ v -∗ Ψ v) -∗ WP e |{ Ψ }|.\n    Proof.\n      iIntros \"HA HB\". revert e. fix e 1.\n      destruct e0.\n      { iApply \"HB\". iApply \"HA\". }\n      { destruct s.\n        { simpl. trivial. }\n        { simpl. iIntros (σ) \"HC\".\n          iDestruct (\"HA\" with \"HC\") as \"HA\".\n          iMod \"HA\" as \"[HA HC]\". \n          iFrame \"HC\". iModIntro.\n          iPoseProof \"HB\" as \"HB\". apply e. }}\n    Qed.\n\n    Lemma mwp_bind {X Y} (e : mon X) (f :  X → mon Y) (Φ : Y -> iProp Σ)  (Φ' : X -> iProp Σ) :\n      WP e |{ Φ' }| -∗ (∀ v,  Φ' v -∗ WP (f v) |{ Φ }|) -∗ WP bind e f |{ Φ }|%I.\n    Proof.\n      iIntros \"HA HB\". revert e. fix e 1.\n      destruct e0.\n      { iApply \"HB\". iApply \"HA\". }\n      { destruct s.\n        { simpl. auto. }\n        { simpl. iIntros (σ) \"HC\". iDestruct (\"HA\" with \"HC\") as \"HA\".\n          iMod \"HA\" as \"[HA HC]\". iFrame \"HC\".\n          iPoseProof \"HB\" as \"HB\". iModIntro. apply e. }}\n    Qed.\n    \n    Open Scope bi_scope.\n    Lemma mwp_gensym t : WP gensym t |{ l, l ↦ t }|.\n    Proof.\n      simpl. iIntros (σ) \"HA\". iDestruct (gen_heap_alloc with \"HA\") as \"HA\".\n      apply fresh_is_fresh. iMod \"HA\" as \"[HA [HB _]]\". iFrame. iModIntro. trivial. Qed.\n\n    Lemma mwp_frame_l {X} (e : mon X) Φ (R : iProp Σ) : R ∗ WP e |{ Φ }| ⊢ WP e |{ v, R ∗ Φ v }|.\n    Proof. iIntros \"[? H]\". iApply (mwp_mono with \"H\"). auto with iFrame. Qed.\n    Lemma mwp_frame_r {X} (e : mon X) Φ R : WP e |{ Φ }| ∗ R ⊢ WP e |{ v, Φ v ∗ R }|.\n    Proof. iIntros \"[H ?]\". iApply (mwp_mono with \"H\"); auto with iFrame. Qed.\n\n  End mwp_proof.\n  Open Scope bi_scope.\n\n  Section adequacy.\n    Inductive step {X} : mon X -> state -> mon X -> state -> Prop :=\n    | gensym_step : forall σ t m,\n        step (op (Gensym t m)) σ (m (fresh σ)) (<[ fresh σ := t ]>σ).\n\n\n    Inductive nsteps {X} : nat ->  mon X -> state -> mon X -> state -> Prop :=\n    | step_0 : forall e σ, nsteps 0 e σ e σ\n    | step_l : forall e1 σ1 e2 σ2 e3 σ3 n,\n        step e1 σ1 e2 σ2 ->\n        nsteps n e2 σ2 e3 σ3 ->\n        nsteps (S n) e1 σ1 e3 σ3.\n\n    Section step.\n      Context `{!heapG Σ}.\n\n      Lemma wp_step {X} (e1 : mon X) σ1 e2 σ2 (Φ : X -> iProp Σ) :\n        step e1 σ1 e2 σ2 →\n        gen_heap_ctx σ1 -∗ WP e1 |{ Φ }| ==∗\n        gen_heap_ctx σ2 ∗ WP e2 |{ Φ }|.\n      Proof.\n        iIntros (Hstep) \"HA HB\".\n        inversion Hstep. subst.\n        simpl.\n        iDestruct (\"HB\" with \"HA\") as \"HA\".\n        iMod \"HA\" as \"[HA HB]\". iModIntro. iFrame.\n      Qed.\n\n      Lemma wp_steps {X} n (e1 e2 : mon X) σ1 σ2 Φ :\n        nsteps n e1 σ1 e2 σ2 →\n        gen_heap_ctx σ1 -∗ WP e1 |{ Φ }| ==∗ gen_heap_ctx σ2 ∗ WP e2 |{ Φ }|.\n      Proof.\n        revert e1 e2 σ1 σ2 Φ.\n        induction n as [| n IH]=> e1 e2 σ1 σ2 Φ /=.\n        * inversion_clear 1. iIntros \"HA HB\". iFrame.  trivial.\n        * iIntros (Hsteps) \"HA HB\". inversion_clear Hsteps.\n          eapply (wp_step _ _ _ _ Φ)in H. iDestruct (H with \"HA\") as \"HA\".\n          iMod (\"HA\" with \"HB\") as \"HC\".\n          apply (IH _ _ _ _ Φ) in H0. iDestruct \"HC\" as \"[HA HB]\".\n          iDestruct (H0 with \"HA\") as \"HC\". iMod (\"HC\" with \"HB\") as \"HC\".\n          iFrame. trivial.\n      Qed.\n    End step.\n    \n    Class heapPreG Σ :=\n    HeapPreG {\n        heappre_preG_iris :> invPreG Σ;\n        heap_preG_heap :> gen_heapPreG ident type Σ;\n      }.\n    \n    Theorem wp_strong_adequacy {X} `{!heapPreG Σ} n (e1 : mon X) σ1 e2 σ2 φ :\n      (∀ `{Hinv : !invG Σ},\n          (|==> ∃ (heap : gen_heapG ident type Σ)\n                  (Φ : X → iProp Σ),\n                let _ : heapG Σ := HeapG Σ _ heap in\n                gen_heap_ctx σ1 ∗\n                WP e1 |{ Φ }| ∗\n                (gen_heap_ctx σ2 ==∗ ⌜ φ ⌝))%I) →\n      nsteps n e1 σ1 e2 σ2 →\n      φ.\n    Proof.\n      intros Hwp ?.\n      epose (step_fupdN_soundness' φ 2).\n      simpl in φ0. apply φ0. intro.\n      iMod Hwp as (heap Φ) \"(HA & HB & HC)\".\n      iApply step_fupd_intro; eauto. iNext.\n      epose step_fupdN_S_fupd.\n      iApply (e 0%nat).\n      iApply (step_fupdN_wand _ _ _ (gen_heap_ctx σ2)with \"[-HC]\").\n      - simpl in Hwp. iDestruct (@wp_steps _ (HeapG _ Hinv heap) _ _ _ _ _ _ Φ) as \"HC\".\n        + apply H.\n        + iDestruct (\"HC\" with \"HA\") as \"HA\".\n          iDestruct (\"HA\" with \"HB\") as \"HD\". iMod \"HD\" as \"[HD HE]\". iFrame \"HD\".\n          iApply step_fupd_mask_mono; eauto.\n      - iIntros \"HA\". iDestruct (\"HC\" with \"HA\") as \"HB\". iMod \"HB\" as \"HB\".\n        iModIntro. iApply \"HB\".\n    Qed.\n\n    Definition adequate {X} (e : mon X) σ (Q : X -> state -> Prop) : Prop :=\n      match run e σ with\n      | Erro e => True\n      | Res (σ', v) => Q v σ'\n      end.\n\n    Corollary wp_adequacy Σ {X} `{!heapPreG Σ} (e : mon X) σ φ :\n      (∀ `{Hinv : !invG Σ}, |==> ∃ (heap : gen_heapG ident type Σ),\n              let _ : heapG Σ := HeapG Σ _ heap in\n              gen_heap_ctx σ ∗ WP e |{ v, ⌜φ v⌝ }|)%I →\n      adequate e σ (λ v _, φ v).\n    Proof.\n      revert e σ φ. fix e 1; intros.\n      unfold adequate.\n      destruct e0; simpl.\n      - eapply (wp_strong_adequacy 0 (ret x)). iIntros.\n        iMod (H $! Hinv) as (heap) \"[HA #HB]\".\n        iModIntro. iExists heap. iExists (fun x => ⌜ φ x ⌝).\n        iFrame. iSplitL. iFrame \"HB\". iFrame \"HB\". eauto. constructor.\n      - destruct s; simpl; auto.\n        eapply (wp_strong_adequacy 1 (op (Gensym t m))).\n        + iIntros. iMod (H $! Hinv) as (heap) \"[HA HB]\".\n          iIntros. iModIntro. iExists heap. iExists (fun x => ⌜ φ x ⌝).\n          iFrame. iIntros.\n          iModIntro. iPureIntro. apply e.\n          simpl in H. iIntros. iMod (H $! Hinv0) as (heap0) \"[HA HB]\".\n          iMod (\"HB\" with \"HA\") as \"[HA HB]\".\n          iModIntro. iExists heap0. iFrame.\n        + do 3 econstructor.\n    Qed.\n\n    Lemma step_to_run {X} : forall n (e : mon X) σ v σ',\n        nsteps n e σ (ret v) σ' -> run e σ = Res (σ',v).\n    Proof.\n      induction n; intros.\n      - inversion H. subst. simpl. reflexivity.\n      - inversion H. subst.\n        inversion H1. subst. simpl in *. apply IHn.\n        apply H2.\n    Qed.\n\n    Lemma run_to_step {X} : forall (e : mon X) σ v σ',\n        run e σ = Res (σ',v) -> exists n, nsteps n e σ (ret v) σ' .\n    Proof.\n      fix e 1. destruct e0; intros.\n      - exists (0)%nat. inversion H. subst. constructor.\n      - destruct s.\n        + inversion H.\n        + simpl in *. apply e in H. destruct H. exists (S x). econstructor.\n          * constructor.\n          * apply H.\n    Qed.\n\n    Definition heap_adequacy Σ {X} `{!heapPreG Σ} (e : mon X) σ Q :\n      (∀ `{!heapG Σ}, WP e |{ v, ⌜Q v⌝ }|%I) →\n      adequate e σ (λ v _, Q v).\n    Proof.\n      intros Hwp. eapply (wp_adequacy Σ).\n      iMod (gen_heap_init σ) as (?) \"Hh\".\n      iIntros. iModIntro. iExists H. iFrame. iApply Hwp.\n    Qed.\n  End adequacy.\n\nEnd weakestpre_gensym.\n\nModule proofmode.\n  Export weakestpre_gensym.\n  Open Scope bi_scope.\n  Ltac early S := iIntros (Φ) S.\n  Section proofmode_intro.\n    Context `{!heapG Σ}.    \n    \n    Lemma gensym_spec t :\n    |{{ True }}| gensym t |{{ l, RET l; l ↦ t }}|.\n    Proof.\n      iIntros (Φ) \"HA HB\". simpl.\n      iIntros (σ) \"HC\". pose mwp_gensym.\n      simpl in u. iMod (u $! σ with \"HC\") as \"[HC HD]\".\n      iModIntro. iFrame. iApply \"HB\". iApply \"HC\".\n    Qed.\n    \n    Lemma ret_spec {X} (v : X) :\n    |{{ True }}| ret v |{{ v', RET v'; ⌜ v' = v ⌝  }}|.\n    Proof. early \"HA HB\". iApply \"HB\". auto. Qed.\n    \n    Lemma ret_spec_bis {X} (v : X) (Q : X -> iProp Σ) :\n      Q v\n      <->\n    |{{ True }}| ret v |{{ v', RET v'; Q v' }}|.\n    Proof.\n      split.\n      - intro. early \"HA HB\". iApply \"HB\". iApply H.\n      - intro. iApply H; eauto.\n    Qed. \n    \n    Lemma error_spec {X} (Q : X -> iProp Σ) e :\n    |{{ True }}| error e |{{ v, RET v; Q v }}|.\n    Proof. early \"HA HB\". iApply \"HA\". Qed.\n    \n    Lemma bind_spec {X Y} (e : mon X) (f : X -> mon Y) Φ' Φ'' H :\n    |{{ H }}| e |{{ v, RET v; Φ'' v }}| ->\n                                        (∀ v, |{{ Φ'' v }}| (f v) |{{ v', RET v'; Φ' v' }}|) ->\n    |{{ H }}| (bind e f) |{{ v, RET v; Φ' v}}|.\n    Proof.\n      intros. early \"HA HB\".\n      iApply (mwp_bind e f _ Φ'' with \"[HA]\").\n      - iApply (H0 with \"[HA]\"); auto. \n      - iIntros (v) \"HC\". iApply (H1 with \"[HC]\"); auto.\n    Qed.\n    \n    Lemma frame_r {X} H R Φ' (e : mon X) :\n    |{{ H }}| e |{{ v, RET v; Φ' v }}| ->\n    |{{ H ∗ R }}| e |{{ v, RET v; Φ' v ∗ R }}|.\n    Proof.\n      intro P. early \"HA HB\". iDestruct \"HA\" as \"[HA HC]\".\n      iApply (P with \"[HA]\"); auto.\n      iIntros (v) \"HA\". iApply \"HB\". iFrame.\n    Qed.\n\n    Lemma frame_l {X} H R Φ' (e : mon X) :\n    |{{ H }}| e |{{ v, RET v; Φ' v }}| ->\n    |{{ R ∗ H }}| e |{{ v, RET v; R ∗ Φ' v }}|.\n    Proof. intro P. early \"HA HB\". iDestruct \"HA\" as \"[HA HC]\".\n           iApply (P with \"[HC]\"); auto.\n           iIntros (v) \"HC\". iApply \"HB\". iFrame.\n    Qed.\n\n    Lemma consequence_post {X} Φ'' H Φ'  (e : mon X) :\n      (forall v, Φ'' v -∗ Φ' v) ->\n    |{{ H }}| e |{{ v, RET v; Φ'' v }}| ->\n    |{{ H }}| e |{{ v, RET v; Φ' v }}|.\n    Proof.\n      intros P P'. early \"HA HB\".\n      iApply (P' with \"[HA]\"); auto.\n      iIntros (v) \"HA\". iApply \"HB\". iApply P. iApply \"HA\".\n    Qed.\n\n    Lemma consequence_pre {X} H' Φ' (H : iProp Σ)  (e : mon X) :\n      (H -∗ H') ->\n    |{{ H' }}| e |{{ v, RET v; Φ' v }}| ->\n    |{{ H }}| e |{{ v, RET v; Φ' v }}|.\n    Proof.\n      intros P P'. early \"HA HB\".\n      iApply (P' with \"[HA]\"); auto.\n      iApply P. iApply \"HA\".\n    Qed.\n    \n    Lemma tLeft {X} (Q : X -> iProp Σ) (R : X -> iProp Σ) S (e : mon X) :\n    |{{ S }}| e |{{ v, RET v; R v }}| ->\n    |{{ S }}| e |{{ v, RET v; R v ⨈ Q v }}|.\n    Proof.\n      intro H. early \"HA HB\".\n      iApply (H with \"[HA]\"); auto.\n      iIntros (v) \"HA\". iApply \"HB\". iIntros \"HB\". iDestruct \"HB\" as \"[HB HC]\".\n      iApply \"HB\". iApply \"HA\".\n    Qed.\n\n    Lemma tRight {X} (Q : X -> iProp Σ) (R : X -> iProp Σ) S (e : mon X) :\n    |{{ S }}| e |{{ v, RET v; Q v }}| ->\n    |{{ S }}| e |{{ v, RET v; R v ⨈ Q v }}|.\n    Proof.\n      intro H. early \"HA HB\".\n      iApply (H with \"[HA]\"); auto.\n      iIntros (v) \"HA\". iApply \"HB\". iIntros \"HB\". iDestruct \"HB\" as \"[HB HC]\".\n      iApply \"HC\". iApply \"HA\".\n    Qed.\n\n    Lemma ret_spec_complete {X} (Q : X -> iProp Σ) S (v : X) :\n      (S -∗ Q v) ->\n    |{{ S }}| ret v |{{ v', RET v'; Q v' }}|.\n    Proof.\n      intro. early \"HA HB\". iApply \"HB\". iDestruct (H with \"HA\") as \"HA\". iApply \"HA\".\n    Qed.\n\n    \n    Lemma True_pre_l {X} H Φ' (e : mon X) :\n    |{{ True ∗ H}}| e |{{ v, RET v; Φ' v }}| ->\n    |{{ H }}| e |{{ v, RET v; Φ' v }}|.\n    Proof.\n      intro P. early \"HA HB\". \n      iApply (P with \"[HA]\"); auto.\n    Qed.\n\n    Lemma True_pre_r {X} H Φ' (e : mon X) :\n    |{{ H ∗ True}}| e |{{ v, RET v; Φ' v }}| ->\n    |{{ H }}| e |{{ v, RET v; Φ' v }}|.\n    Proof.\n      intro P. early \"HA HB\". \n      iApply (P with \"[HA]\"); auto.\n    Qed.\n\n  End proofmode_intro.\n\n  Ltac tFrame_l := apply True_pre_r; apply frame_l; eauto.\n  Ltac tFrame_r := apply True_pre_l; apply frame_r; eauto.\n  \n  Section proofmode_divers.\n    Context `{!heapG Σ}.\n    \n    Lemma comm_post {X} R Φ' (e : mon X) H :\n    |{{ H }}| e |{{ v, RET v; Φ' v ∗ R v }}| ->\n    |{{ H }}| e |{{ v, RET v; R v ∗ Φ' v}}|.\n    Proof.\n      intro P. early \"HA HB\".\n      iApply (P with \"[HA]\"); auto.\n      iIntros (v) \"HA\". iApply \"HB\". iDestruct \"HA\" as \"[HA HC]\". iFrame.\n    Qed.\n\n    Lemma comm_pre {X} R Φ' (e : mon X) H :\n    |{{ R ∗ H}}| e |{{ v, RET v; Φ' v }}| ->\n    |{{ H ∗ R}}| e |{{ v, RET v; Φ' v}}|.\n    Proof.\n      intro P. early \"HA HB\".\n      iApply (P with \"[HA]\"); auto.\n      iDestruct \"HA\" as \"[HA HC]\". iFrame.\n    Qed.\n\n    Lemma impl_post_id {X} R P Φ' (e : mon X) :\n    |{{ R }}| e |{{ v, RET v; Φ' v }}| ->\n    |{{ R }}| e |{{ v, RET v; P -∗ P ∗ Φ' v}}|.\n    Proof.\n      intro H. early \"HA HB\".\n      iApply (H with \"[HA]\"); auto.\n      iIntros (v) \"HA\". iApply \"HB\". iIntros \"HB\". iFrame.\n    Qed.\n\n    Lemma impl_post {X} R P Φ' (e : mon X) :\n    |{{ R }}| e |{{ v, RET v; Φ' v }}| ->\n    |{{ R }}| e |{{ v, RET v; P -∗ Φ' v}}|.\n    Proof.\n      intro H. early \"HA HB\".\n      iApply (H with \"[HA]\"); auto.\n      iIntros (v) \"HA\". iApply \"HB\". eauto.\n    Qed.\n\n    Lemma star_assoc_post {X} R Q S T (e : mon X) :\n    |{{ T }}| e |{{ v, RET v; R v ∗ (Q v ∗ S v)}}| <->\n    |{{ T }}| e |{{ v, RET v; (R v ∗ Q v) ∗ S v }}|.\n    Proof.\n      split; intro H; early \"HA HB\";\n        iApply (H with \"[HA]\"); try (iApply \"HA\");\n          iIntros (v) \"HA\"; iApply \"HB\".\n      - iDestruct \"HA\" as \"[HA [HB HC]]\". iFrame.\n      - iDestruct \"HA\" as \"[[HA HB] HC]\". iFrame.\n    Qed.\n\n    Lemma star_assoc_pre {X} R Q S T (e : mon X) :\n    |{{ (T ∗ R) ∗ S }}| e |{{ v, RET v; Q v }}| <->\n    |{{ T ∗ (R ∗ S) }}| e |{{ v, RET v; Q v }}|.\n    Proof.\n      split; intro H; early \"HA HB\"; iApply (H with \"[HA]\"); eauto.\n      - iDestruct \"HA\" as \"[HA [HB HC]]\". iFrame.\n      - iDestruct \"HA\" as \"[[HA HB] HC]\". iFrame.\n    Qed.\n\n    Lemma impl_true_pre {X} (R : X -> iProp Σ) Q (e : mon X) :\n    |{{ Q }}| e |{{ v', RET v'; R v'}}| ->\n    |{{ True -∗ Q }}| e |{{ v', RET v'; R v'}}|.\n    Proof.\n      intro H. early \"HA HB\". iApply (H with \"[HA]\"); eauto. iApply \"HA\"; auto.\n    Qed.\n\n    Lemma impl_true_post {X} (R : X -> iProp Σ) Q (e : mon X) :\n    |{{ Q }}| e |{{ v', RET v'; R v'}}| ->\n    |{{ Q }}| e |{{ v', RET v'; True -∗ R v'}}|.\n    Proof.\n      intro H. early \"HA HB\". iApply (H with \"[HA]\"); eauto.\n      iIntros (v') \"HA\". iApply \"HB\". auto.\n    Qed.\n\n    Lemma exist {X Y} v (R : Y -> X -> iProp Σ) Q (e : mon X) :\n    |{{ Q }}| e |{{ v', RET v'; R v v'}}| ->\n    |{{ Q }}| e |{{ v', RET v'; ∃ t, R t v'}}|.\n    Proof.\n      intro H. early \"HA HB\".\n      iApply (H with \"[HA]\"); auto.\n      iIntros (v0) \"HC\". iApply \"HB\". iExists v. iFrame.\n    Qed.\n\n    Lemma exists_frame_r {X Y} v (Q : Y -> iProp Σ) R (e : mon X) :\n    |{{ True }}| e |{{ v', RET v'; R v v' }}| ->\n    |{{ Q v }}| e |{{ v', RET v'; ∃ t, R t v' ∗ Q t}}|.\n    Proof.\n      intro.\n      iApply (exist v). tFrame_r.\n    Qed.\n\n    Lemma exists_frame_l {X Y} v (Q : Y -> iProp Σ) R (e : mon X) :\n    |{{ True }}| e |{{ v', RET v'; R v v'}}| ->\n    |{{ Q v }}| e |{{ v', RET v'; ∃ t, Q t ∗ R t v'}}|.\n    Proof.\n      intro.\n      iApply (exist v).\n      tFrame_l.\n    Qed.\n\n    Lemma exists_out_l {X Y} (Q : iProp Σ) (R : Y -> X -> iProp Σ) S (e : mon X) :\n    |{{ S }}| e |{{ v', RET v'; Q ∗ ∃ t, R t v' }}| ->\n    |{{ S }}| e |{{ v', RET v'; ∃ t, Q ∗ R t v'}}|.\n    Proof.\n      intro H. early \"HA HB\".\n      iApply (H with \"[HA]\"); auto.\n      iIntros (v) \"HA\". iApply \"HB\". iDestruct \"HA\" as \"[HA HB]\". iDestruct \"HB\" as (t) \"HB\".\n      iExists t. iFrame.\n    Qed.\n\n    Lemma exists_out_r {X Y} (Q : iProp Σ) (R : Y -> X -> iProp Σ) S (e : mon X) :\n    |{{ S }}| e |{{ v', RET v'; (∃ t, R t v') ∗ Q }}| ->\n    |{{ S }}| e |{{ v', RET v'; ∃ t, R t v' ∗ Q }}|.\n    Proof.\n      intro H. early \"HA HB\".\n      iApply (H with \"[HA]\"); auto.\n      iIntros (v) \"HA\". iApply \"HB\". iDestruct \"HA\" as \"[HA HB]\". iDestruct \"HA\" as (t) \"HA\".\n      iExists t. iFrame.\n    Qed.\n\n    Lemma ret_frame_l {X Y} (R : Y -> iProp Σ) (R' Φ' : X -> iProp Σ) (v' : X) (v'': Y) : \n      Φ' v' -> R v'' = R' v' ->\n    |{{ R v'' }}| ret v' |{{ v, RET v; R' v ∗ Φ' v }}|.\n    Proof.\n      intros H H'. early \"HA HB\".\n      iApply mwp_value'. iApply \"HB\". rewrite H'. iFrame. iApply H.\n    Qed.\n\n    Lemma ret_frame_r {X Y} (R : Y -> iProp Σ) (R' Φ' : X -> iProp Σ) (v' : X) (v'' : Y): \n      Φ' v' -> R v'' = R' v' ->\n    |{{ R v'' }}| ret v' |{{ v, RET v; Φ' v ∗ R' v }}|.\n    Proof.\n      intros H H'. early \"HA HB\".\n      iApply mwp_value'. iApply \"HB\". rewrite H'. iFrame. iApply H.\n    Qed.\n\n  End proofmode_divers.\n  \nEnd proofmode.\n\n", "meta": {"author": "Artalik", "repo": "monad-frame-src", "sha": "7aa9364eb94c10f447a215351cd84dcbc8506714", "save_path": "github-repos/coq/Artalik-monad-frame-src", "path": "github-repos/coq/Artalik-monad-frame-src/monad-frame-src-7aa9364eb94c10f447a215351cd84dcbc8506714/src/Monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22179253962631093}}
{"text": "Require Import ParserArg.\n\n(* Grammar should be parametrized by a PARSER_ARG module; however, that\n   would impede code extraction because of a Coq bug.  Instead, we\n   introduce a bunch of definitions below to achieve some separation as\n   long as we never directly use definitions in X86_PARSER_ARG *)\nDefinition char_p := X86_PARSER_ARG.char_p.\nDefinition char_dec := X86_PARSER_ARG.char_dec.\nDefinition user_type := X86_PARSER_ARG.user_type.\nDefinition user_type_dec := X86_PARSER_ARG.user_type_dec.\nDefinition user_type_denote := X86_PARSER_ARG.user_type_denote.\nDefinition token_id := X86_PARSER_ARG.token_id.\nDefinition num_tokens := X86_PARSER_ARG.num_tokens.\nDefinition token_id_to_chars := X86_PARSER_ARG.token_id_to_chars.\n\n(** The [type]s for our grammars. *)\nInductive type : Type := \n| Unit_t : type\n| Char_t : type\n| Void_t : type\n| Pair_t : type -> type -> type\n| Sum_t : type -> type -> type\n| List_t : type -> type\n| Option_t : type -> type\n| User_t : user_type -> type.\n\n(** [void] is an empty type. *)\nInductive void : Type := .\n\n(** The interpretation of [type]s as Coq [Type]s. *)\nFixpoint interp (t:type) : Type := \n  match t with \n    | Unit_t => unit\n    | Char_t => char_p\n    | Void_t => void\n    | Pair_t t1 t2 => (interp t1) * (interp t2)\n    | Sum_t t1 t2 => (interp t1) + (interp t2)\n    | List_t t => list (interp t)\n    | Option_t t => option (interp t)\n    | User_t t => user_type_denote t\n  end%type.\n", "meta": {"author": "gangtan", "repo": "CPUmodels", "sha": "a6decc3085e1f8d8d4875e67f9ad9c7663910f8a", "save_path": "github-repos/coq/gangtan-CPUmodels", "path": "github-repos/coq/gangtan-CPUmodels/CPUmodels-a6decc3085e1f8d8d4875e67f9ad9c7663910f8a/x86model/Model/GrammarType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2217925396263109}}
{"text": "Require Import Fiat.Narcissus.Examples.NetworkStack.IPv4Header.\nRequire Import Fiat.Narcissus.Examples.NetworkStack.TCP_Packet.\nRequire Import Bedrock.Word.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Lists.List.\nRequire Import Fiat.QueryStructure.Automation.MasterPlan.\nRequire Import Fiat.Common.Ensembles.IndexedEnsembles.\nRequire Import Fiat.Narcissus.Examples.Guard.Core.\nRequire Import Fiat.Narcissus.Examples.Guard.IPTables.\nRequire Import Fiat.Narcissus.Examples.Guard.PacketFiltersLemmas.\nRequire Import Fiat.Narcissus.Examples.Guard.DropFields.\nImport ListNotations.\n\n(**\nwe are 18.X.X.X\noutside world is all other IP addresses\nfilter allows outside address to talk to us only if we have talked to it first\n**)\n\nDefinition OutgoingRule :=\n  iptables -A FORWARD --source 18'0'0'0/24.\n\nDefinition IncomingRule :=\n  iptables -A FORWARD --destination 18'0'0'0/24.\n\nDefinition OutgoingToRule (dst: address) :=\n  and_cf OutgoingRule (lift_condition in_ip4 (cond_dstaddr {| saddr := dst; smask := None |})).\n\nDefinition OutgoingToRule' (cur pre : input) : Prop :=\n  (OutgoingToRule cur.(in_ip4).(ipv4_source)).(cf_cond) pre = true.\n\nOpaque OutgoingRule IncomingRule OutgoingToRule OutgoingToRule'.\n\nDefinition FilterMethodGen {h T} cont\n           (topkt: @Tuple h -> input)\n           (totup: input -> @Tuple h)\n           (r: T) (inp: input) :=\n  If OutgoingRule.(cf_cond) inp\n  Then <ACCEPT>\n  Else (\n      If negb (IncomingRule.(cf_cond) inp)\n      Then ret None\n      Else with r (cont totup),\n                if historically (OutgoingToRule' inp) then <ACCEPT> else <DROP>).\nDefinition FilterMethod: FilterType. filter_gen @FilterMethodGen. Defined.\nDefinition FilterMethod_Count: FilterType. filter_count FilterMethod. Defined.\n\nTransparent computes_to.\n\nNotation IndexType sch :=\n  (@ilist3 RawSchema (fun sch : RawSchema =>\n                        list (string * Attributes (rawSchemaHeading sch)))\n           (numRawQSschemaSchemas sch) (qschemaSchemas sch)).\n\n(* This computes the set of columns to keep *)\nTheorem DroppedFilterMethod : FilterAdapter (@FilterMethod).\nProof. solve_drop_fields @FilterMethod. Defined.\n\nDefinition IPFilterSchema :=\n  Eval cbn in PacketHistorySchema (DroppedFilterMethod.(h _)).\n\n(** Genpatcher hooks here **)\n\n(* ‘columns’ is the list of columns available; this will vary depending on the filter *)\n\nDefinition columns :=\n  Eval compute in (Vector.to_list (DroppedFilterMethod.(h _).(HeadingNames))).\n\nPrint columns.\n(* columns = [\"Chain\"; \"TransportLayerPacket\"; \"DestAddress\"; \"SourceAddress\"]%list\n     : list string *)\n\nOpen Scope list_scope.\n\n(* Here are two examples *)\n\nDefinition SlowIndex : IndexType IPFilterSchema :=\n  {| prim_fst := [];\n     prim_snd := () |}.\n\nDefinition FastIndex :=\n  {| prim_fst := [(\"EqualityIndex\", \"DestAddress\" # \"History\" ## IPFilterSchema)]%list;\n     prim_snd := () |}.\n\n(* Genpatcher should mutate the following definition: *)\nDefinition Index : IndexType IPFilterSchema :=\n  {| prim_fst := [];\n     prim_snd := () |}.\n\n(** End of GenPatcher hooks **)\n\nDefinition myh := (h _ DroppedFilterMethod).\nDefinition mytopkt := (topkt _ DroppedFilterMethod).\nDefinition mytotup := (totup _ DroppedFilterMethod).\nDefinition mythm := (thm _ DroppedFilterMethod).\n\nLemma CompPreservesFilterMethod:\n  forall r inp,\n    refine (FilterMethod myh mytopkt mytotup r inp)\n           (FilterMethod_Count myh mytopkt mytotup r inp).\nProof. prove_count_refine. Qed.\n\n\nDefinition NoIncomingConnectionsFilter : ADT StatefulFilterSig :=\n  Eval simpl in Def ADT {\n    rep := QueryStructure Complete_PacketHistorySchema,\n    Def Constructor0 \"Init\" : rep := empty,,\n\n    Def Method1 \"Filter\" (r: rep) (inp: input) : rep * option result :=\n      res <- FilterMethodGen In_History_Constr Complete_topkt Complete_totup r inp;\n      `(r, _) <- Insert (Complete_totup inp) into r!\"History\";\n      ret (r, res)\n  }%methDefParsing.\n\nLtac FindAttributeUses := EqExpressionAttributeCounter.\nLtac BuildEarlyIndex := ltac:(LastCombineCase6 BuildEarlyEqualityIndex).\nLtac BuildLastIndex := ltac:(LastCombineCase5 BuildLastEqualityIndex).\nLtac IndexUse := EqIndexUse.\nLtac createEarlyTerm := createEarlyEqualityTerm.\nLtac createLastTerm := createLastEqualityTerm.\nLtac IndexUse_dep := EqIndexUse_dep.\nLtac createEarlyTerm_dep := createEarlyEqualityTerm_dep.\nLtac createLastTerm_dep := createLastEqualityTerm_dep.\nLtac BuildEarlyBag := BuildEarlyEqualityBag.\nLtac BuildLastBag := BuildLastEqualityBag.\nLtac PickIndex := ltac:(fun makeIndex => let attrlist' := eval compute in Index in makeIndex attrlist').\n\nArguments wand: simpl never.\nArguments Nat.ltb: simpl never.\nArguments N.land: simpl nomatch.\nArguments chain_beq: simpl never.\nArguments GetAttribute: simpl never.\nHint Unfold cf_cond combine_conditions cond_srcaddr cond_dstaddr cond_chain match_address : iptables.\n\n(* Hint Rewrite -> wand_full_mask : iptables. *)\nHint Rewrite -> andb_true_iff andb_true_l andb_true_r : iptables.\nHint Rewrite -> internal_chain_dec_bl : iptables.\nHint Rewrite -> N.eqb_eq : iptables.\nHint Rewrite -> weqb_true_iff : iptables.\n\nTheorem SharpenNoIncomingFilter:\n  FullySharpened NoIncomingConnectionsFilter.\nProof.\n  start sharpening ADT.\n\n  Transparent QSInsert.\n  drop_constraints_under_bind Complete_PacketHistorySchema ltac:(\n    instantiate (1:=(FilterMethodGen In_History Complete_topkt Complete_totup r_n d));\n    unfold FilterMethodGen; red; intros v Hv; red in Hv; red;\n\n    repeat match goal with\n    | [H: (If _ Then _ Else _) v |- (If ?cond Then _ Else _) v] =>\n      destruct cond; [ apply H | cbn; cbn in H ]\n    | [Hv: _ v |- _ v] => repeat comp_inv; apply Pick_inv in H1;\n                          repeat computes_to_econstructor; [ | eassumption ]\n    | [H: decides ?b _ |- _] => destruct b; cbn in *\n    | [H: exists pre, ?A /\\ ?B |- exists _, _ /\\ _] =>\n      destruct H as [pre [Ha Hb]]; exists pre; split; [ | assumption ]\n    | [Hrel: DropQSConstraints_AbsR ?r_o ?r_n, Hhist: In_History _ _ _ |- _] =>\n      unfold In_History, In_History_Constr, GetRelationBnd, GetUnConstrRelationBnd in *;\n      rewrite <- (GetRelDropConstraints r_o); rewrite <- Hrel in Hhist; apply Hhist\n    | [H: ~ _ |- ~ _] => intro; apply H\n    | [Hrel: DropQSConstraints_AbsR ?r_o ?r_n, Hhist: In_History_Constr _ _ _ |- _] =>\n      unfold In_History; rewrite <- Hrel; red in Hhist; unfold GetRelationBnd in Hhist;\n      rewrite <- (GetRelDropConstraints r_o) in Hhist; apply Hhist\n    end).\n\n  hone representation using (Complete_Dropped_qs_equiv mytotup);\n    try simplify with monad laws;\n  [ refine pick val (DropQSConstraints (QSEmptySpec _));\n    [ subst H; reflexivity\n    | red; intros; split; intros Htmp; cbv in Htmp; inversion Htmp]\n  | eapply refine_bind; [ apply mythm; apply H0 | intro res; cbn ];\n    eapply refine_bind; [ apply (DropPreservesFreshIdx _ _ _ mytotup H0)\n                        | intro idx; cbn ];\n    apply refine_pair; apply refine_pick; intros qs Hins; comp_inv; subst qs;\n    instantiate (1 := (UpdateUnConstrRelation r_n Fin.F1\n                         (BuildADT.EnsembleInsert\n                            {| elementIndex := idx;\n                               indexedElement := mytotup d |}\n                            (GetUnConstrRelation r_n Fin.F1))));\n\n    red; intros oinp oidx; split; intros Hoinp; destruct Hoinp as [Hoinp | Hoinp];\n    [ apply in_ensemble_insert_iff; left; inversion Hoinp; reflexivity\n    | right; apply H0 in Hoinp; apply Hoinp\n    | exists d; split; [ apply in_ensemble_insert_iff; left | ];\n      inversion Hoinp; reflexivity\n    | pose proof (H0 oinp oidx) as H0spec;\n      destruct H0spec as [_ Hspec]; specialize (Hspec Hoinp);\n      destruct Hspec as [inp' [H1 H2]]; exists inp'; split;\n      [ apply in_ensemble_insert_iff; right; apply H1 | apply H2 ]\n    ]\n  | ].\n\n\n - hone method \"Filter\".\n   subst r_o; refine pick eq; simplify with monad laws;\n   apply refine_bind; [ apply CompPreservesFilterMethod; reflexivity | intro ];\n   apply refine_bind; [ reflexivity | intro; simpl; higher_order_reflexivity ].\n\n   PickIndex ltac:(fun attrlist =>\n                     make_simple_indexes attrlist BuildEarlyIndex BuildLastIndex).\n\n   + plan CreateTerm EarlyIndex LastIndex makeClause_dep EarlyIndex_dep LastIndex_dep.\n   + etransitivity. simplify with monad laws.\n     eapply refine_bind; [ | intro ].\n\n     { (* Filter *)\n       unfold FilterMethod_Count.\n       repeat lazymatch goal with\n              | [  |- refine (if _ then _ else _) _ ] => eapply refine_If_Then_Else\n              | [  |- context[UnConstrQuery_In] ] => idtac\n              | _ => higher_order_reflexivity\n              end.\n\n       Transparent OutgoingToRule OutgoingToRule' OutgoingRule.\n       Hint Unfold OutgoingToRule OutgoingToRule' OutgoingRule : iptables.\n\n       repeat (autounfold with iptables; cbn).\n\n       etransitivity; [ setoid_rewrite refine_UnConstrQuery_In | ].\n       { reflexivity. }\n       { intro.\n         etransitivity; [apply refine_Query_Where_Cond | ].\n         { autorewrite with iptables.\n           repeat match goal with\n                  | _ => rewrite and_assoc\n                  | [  |- context[chain_beq ?x ?y = true /\\ ?z] ] => rewrite (and_comm (chain_beq x y = true) z)\n                  end.\n           rewrite <- !and_assoc.\n           reflexivity. }\n         { higher_order_reflexivity. } }\n\n       implement_Query IndexUse createEarlyTerm createLastTerm\n       IndexUse_dep createEarlyTerm_dep createLastTerm_dep.\n       simplify with monad laws.\n\n       simpl; repeat first [ setoid_rewrite refine_bind_unit\n                           | setoid_rewrite refine_bind_bind ].\n       apply refine_bind; [ reflexivity | intro; simpl ].\n       repeat rewrite ?map_length, ?app_nil_r.\n       higher_order_reflexivity. }\n\n     { (* Insertion *)\n       unfold mytotup; simpl.\n       etransitivity.\n       insertion IndexUse createEarlyTerm createLastTerm IndexUse_dep createEarlyTerm_dep createLastTerm_dep.\n       simplify with monad laws.\n       higher_order_reflexivity. }\n\n     simpl.\n     subst H.\n     higher_order_reflexivity.\n\n   + Implement_Bags BuildEarlyBag BuildLastBag.\nDefined.\n\nDefinition GuardImpl :=\n  Eval simpl in projT1 SharpenNoIncomingFilter.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Narcissus/Examples/Guard/StatefulGuard.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2216837463375855}}
{"text": "Require Import VST.progs.conclib.\n\n(* Axiomatization of view shifts, PCMs, and ghost state *)\n\nClass PCM (A : Type) :=\n  { join : A -> A -> A -> Prop;\n    join_comm : forall a b c (Hjoin : join a b c), join b a c;\n    join_assoc : forall a b c d e (Hjoin1 : join a b c) (Hjoin2 : join c d e),\n                 exists c', join b d c' /\\ join a c' e }.\n\nSection Ghost.\n\nContext {CS : compspecs}.\n\n(* This is an overapproximation of IRIS's concept of view shift. *)\nDefinition view_shift A B := forall (Espec : OracleKind) D P Q R C P',\n  semax D (PROPx P (LOCALx Q (SEPx (B :: R)))) C P' ->\n  semax D (PROPx P (LOCALx Q (SEPx (A :: R)))) C P'.\n\nSection ViewShift.\n\nAxiom view_shift_super_non_expansive : forall n P Q, compcert_rmaps.RML.R.approx n (!!view_shift P Q) =\n  compcert_rmaps.RML.R.approx n (!!view_shift (compcert_rmaps.RML.R.approx n P) (compcert_rmaps.RML.R.approx n Q)).\n\nAxiom view_shift_later : forall P Q, view_shift P Q -> view_shift (|>P) (|>Q).\n\nGlobal Instance view_shift_refl : RelationClasses.Reflexive view_shift.\nProof.\n  repeat intro; auto.\nQed.\n\nGlobal Instance view_shift_trans : RelationClasses.Transitive view_shift.\nProof.\n  repeat intro; apply H; auto.\nQed.\n\nLemma derives_view_shift : forall P Q, P |-- Q -> view_shift P Q.\nProof.\n  repeat intro; eapply semax_pre; [|eauto].\n  go_lowerx; cancel.\nQed.\n\nLemma view_shift_sepcon : forall P Q P' Q' (HP : view_shift P P') (HQ : view_shift Q Q'),\n  view_shift (P * Q) (P' * Q').\nProof.\n  repeat intro.\n  rewrite flatten_sepcon_in_SEP in *; apply HP.\n  focus_SEP 1; apply HQ.\n  focus_SEP 1; auto.\nQed.\n\nCorollary view_shift_sepcon1 : forall P Q P' (HP : view_shift P P'), view_shift (P * Q) (P' * Q).\nProof.\n  intros; apply view_shift_sepcon; auto; reflexivity.\nQed.\n\nCorollary view_shift_sepcon2 : forall P Q Q' (HQ : view_shift Q Q'), view_shift (P * Q) (P * Q').\nProof.\n  intros; apply view_shift_sepcon; auto; reflexivity.\nQed.\n\nLemma view_shift_sepcon_list : forall l1 l2 (Hlen : Zlength l1 = Zlength l2)\n  (Hall : forall i, 0 <= i < Zlength l1 -> view_shift (Znth i l1 FF) (Znth i l2 FF)),\n  view_shift (fold_right sepcon emp l1) (fold_right sepcon emp l2).\nProof.\n  induction l1; intros.\n  - symmetry in Hlen; apply Zlength_nil_inv in Hlen; subst; reflexivity.\n  - destruct l2; [apply Zlength_nil_inv in Hlen; discriminate|].\n    rewrite !Zlength_cons in *.\n    simpl; apply view_shift_sepcon, IHl1; try omega; intros.\n    + lapply (Hall 0); [|pose proof (Zlength_nonneg l1); omega].\n      rewrite !Znth_0_cons; auto.\n    + lapply (Hall (i + 1)); [|omega].\n      rewrite !Znth_pos_cons, Z.add_simpl_r by omega; auto.\nQed.\n\nLemma view_shift_exists : forall {A} (P : A -> mpred) Q,\n  (forall x, view_shift (P x) Q) -> view_shift (EX x : _, P x) Q.\nProof.\n  repeat intro.\n  rewrite extract_exists_in_SEP; Intro x.\n  apply H; auto.\nQed.\n\nLemma view_shift_prop : forall (P1 : Prop) P Q,\n  (P1 -> view_shift P Q) -> view_shift (!!P1 && P) Q.\nProof.\n  repeat intro.\n  erewrite extract_prop_in_SEP with (n := O); [|simpl; eauto].\n  Intros; simpl; apply H; auto.\nQed.\n\nLemma view_shift_assert : forall P Q PP, P |-- !!PP -> (PP -> view_shift P Q) -> view_shift P Q.\nProof.\n  intros.\n  rewrite (add_andp P (!!PP)) by auto.\n  rewrite andp_comm; apply view_shift_prop; auto.\nQed.\n\nLemma view_shift_assert_later : forall P Q PP (HPP : P |-- |>!!PP) (Hshift : PP -> view_shift P Q),\n  view_shift P Q.\nProof.\n  intros.\n  rewrite (add_andp _ _ HPP).\n  repeat intro; eapply semax_extract_later_prop''; eauto.\n  intro X; apply (Hshift X) in H.\n  rewrite <- add_andp; auto.\nQed.\n\nLemma view_shift_prop_right : forall (P1 : Prop) P Q, P1 -> view_shift P Q -> view_shift P (!!P1 && Q).\nProof.\n  intros.\n  etransitivity; eauto.\n  apply derives_view_shift; entailer!.\nQed.\n\nEnd ViewShift.\n\n(* General PCM-based ghost state *)\n\nParameter ghost : forall {A} {P : PCM A} (g : A) (p : val), mpred.\n\nSection PCM.\n\nContext `{M : PCM}.\n\nDefinition joins a b := exists c, join a b c.\n\nDefinition update a b := forall c, joins a c -> joins b c.\n\n(* subject to change *)\n(* We need to make sure we can't allocate invalid ghost state (which would immediately entail False). *)\nAxiom ghost_alloc : forall (g : A) P, (exists g', joins g g') -> view_shift P (EX p : val, ghost g p * P).\nAxiom ghost_dealloc : forall (g : A) p, view_shift (ghost g p) emp.\n\nAxiom ghost_join : forall g1 g2 g p, join g1 g2 g -> ghost g1 p * ghost g2 p = ghost g p.\nAxiom ghost_conflict : forall g1 g2 p, ghost g1 p * ghost g2 p |-- !!joins g1 g2.\nAxiom ghost_update : forall g g' p, update g g' -> view_shift (ghost g p) (ghost g' p).\nAxiom ghost_inj : forall p g1 g2 r1 r2 r\n  (Hp1 : predicates_hered.app_pred (ghost g1 p) r1)\n  (Hp1 : predicates_hered.app_pred (ghost g2 p) r2)\n  (Hr1 : sepalg.join_sub r1 r) (Hr2 : sepalg.join_sub r2 r),\n  r1 = r2 /\\ g1 = g2.\n\nLemma ghost_join' : forall g1 g2 p, ghost g1 p * ghost g2 p = EX g : A, !!(join g1 g2 g) && ghost g p.\nProof.\n  intros.\n  apply mpred_ext.\n  - assert_PROP (joins g1 g2) as Hjoin by (apply ghost_conflict).\n    destruct Hjoin as (g & ?); Exists g; entailer!.\n    erewrite ghost_join; eauto.\n  - Intros g.\n    erewrite ghost_join; eauto.\nQed.\n\nLemma ex_ghost_precise : forall p, precise (EX g : A, ghost g p).\nProof.\n  intros ???? (? & ?) (? & ?) ??.\n  eapply ghost_inj; eauto.\nQed.\n\nCorollary ghost_precise : forall g p, precise (ghost g p).\nProof.\n  intros.\n  eapply derives_precise, ex_ghost_precise.\n  intros ??; exists g; eauto.\nQed.\n\nLemma ghost_list_alloc : forall lg P g, Forall (fun g => exists g', joins g g') lg ->\n  view_shift P (EX lp : list val, !!(Zlength lp = Zlength lg) &&\n    fold_right sepcon emp (map (fun i => ghost (Znth i lg g) (Znth i lp Vundef)) (upto (Z.to_nat (Zlength lg)))) * P).\nProof.\n  induction 1.\n  - apply derives_view_shift; Exists (@nil val); entailer!.\n  - etransitivity; eauto.\n    apply view_shift_exists; intro lp.\n    etransitivity; [apply ghost_alloc; eauto|].\n    apply derives_view_shift; Intros p.\n    Exists (p :: lp); rewrite !Zlength_cons, Z2Nat.inj_succ by apply Zlength_nonneg.\n    rewrite (upto_app 1), map_app, sepcon_app; simpl.\n    rewrite !Znth_0_cons; entailer!.\n    erewrite map_map, map_ext_in; eauto; intros; simpl.\n    rewrite In_upto in *; rewrite !Znth_pos_cons by omega.\n    rewrite Z.add_comm, Z.add_simpl_r; auto.\nQed.\n\nCorollary ghost_list_alloc' : forall g i P, 0 <= i -> (exists g', joins g g') ->\n  view_shift P (EX lp : list val, !!(Zlength lp = i) &&\n    fold_right sepcon emp (map (fun i => ghost g (Znth i lp Vundef)) (upto (Z.to_nat i))) * P).\nProof.\n  intros.\n  etransitivity; [apply ghost_list_alloc with (lg := repeat g (Z.to_nat i))|].\n  { apply Forall_repeat; auto. }\n  apply derives_view_shift; Intros lp; Exists lp.\n  rewrite Zlength_repeat, Z2Nat.id in H1 |- * by auto; entailer!.\n  erewrite map_ext_in; eauto; intros; simpl.\n  rewrite Znth_repeat; auto.\nQed.\n\nEnd PCM.\n\n(* operations on PCMs *)\n\nSection Ops.\n\nContext {A B : Type} {MA : PCM A} {MB : PCM B}.\n\nInstance prod_PCM : PCM (A * B) := { join a b c := join (fst a) (fst b) (fst c) /\\ join (snd a) (snd b) (snd c) }.\nProof.\n  - intros ??? (? & ?); split; apply join_comm; auto.\n  - intros ????? (? & ?) (HA & HB).\n    eapply join_assoc in HA; eauto.\n    eapply join_assoc in HB; eauto.\n    destruct HA as (c'a & ? & ?), HB as (c'b & ? & ?); exists (c'a, c'b); split; split; auto.\nDefined.\n\n(* Two different ways of adding a unit to a PCM. *)\nInstance option_PCM : PCM (option A) := { join a b c :=\n  match a, b, c with\n  | Some a', Some b', Some c' => join a' b' c'\n  | Some a', None, Some c' => c' = a'\n  | None, Some b', Some c' => c' = b'\n  | None, None, None => True\n  | _, _, _ => False\n  end }.\nProof.\n  - destruct a, b, c; auto.\n    apply join_comm.\n  - destruct a, b, c, d, e; try contradiction; intros; subst;\n      try solve [eexists (Some _); split; auto; auto]; try solve [exists None; split; auto].\n    eapply join_assoc in Hjoin2; eauto.\n    destruct Hjoin2 as (c' & ? & ?); exists (Some c'); auto.\nDefined.\n\nInstance exclusive_PCM : PCM (option A) := { join a b c := a = c /\\ b = None \\/ b = c /\\ a = None }.\nProof.\n  - tauto.\n  - intros ????? [(? & ?) | (? & ?)]; subst; eauto.\nDefined.\n\nLemma exclusive_update : forall v v' p, view_shift (ghost (Some v) p) (ghost (Some v') p).\nProof.\n  intros; apply ghost_update; intros ? (? & [[]|[]]); try discriminate; subst.\n  eexists; simpl; eauto.\nQed.\n\nEnd Ops.\n\nGlobal Instance share_PCM : PCM share := { join := sepalg.join }.\nProof.\n  - intros; apply sepalg.join_comm; auto.\n  - intros.\n    eapply sepalg.join_assoc in Hjoin2; eauto.\n    destruct Hjoin2; eauto.\nDefined.\n\nClass PCM_order `{P : PCM} (ord : A -> A -> Prop) := { ord_refl :> RelationClasses.Reflexive ord;\n  ord_trans :> RelationClasses.Transitive ord;\n  ord_lub : forall a b c, ord a c -> ord b c -> exists c', join a b c' /\\ ord c' c;\n  join_ord : forall a b c, join a b c -> ord a c /\\ ord b c; ord_join : forall a b, ord b a -> join a b a }.\n\nClass lub_ord {A} (ord : A -> A -> Prop) := { lub_ord_refl :> RelationClasses.Reflexive ord;\n  lub_ord_trans :> RelationClasses.Transitive ord;\n  has_lub : forall a b c, ord a c -> ord b c -> exists c', ord a c' /\\ ord b c' /\\\n    forall d, ord a d -> ord b d -> ord c' d }.\n\nGlobal Instance ord_PCM `{lub_ord} : PCM A := { join a b c := ord a c /\\ ord b c /\\\n  forall c', ord a c' -> ord b c' -> ord c c' }.\nProof.\n  - intros ??? (? & ? & ?); eauto.\n  - intros ????? (? & ? & Hc) (? & ? & He).\n    destruct (has_lub b d e) as (c' & ? & ? & Hlub); try solve [etransitivity; eauto].\n    exists c'; repeat split; auto.\n    + etransitivity; eauto.\n    + apply Hlub; auto; transitivity c; auto.\n    + intros.\n      apply He.\n      * apply Hc; auto; etransitivity; eauto.\n      * etransitivity; eauto.\nDefined.\n\nGlobal Instance ord_PCM_ord `{lub_ord} : PCM_order ord.\nProof.\n  constructor.\n  - apply lub_ord_refl.\n  - apply lub_ord_trans.\n  - intros ??? Ha Hb.\n    destruct (has_lub _ _ _ Ha Hb) as (c' & ? & ? & ?).\n    exists c'; simpl; eauto.\n  - simpl; intros; tauto.\n  - intros; simpl.\n    repeat split; auto.\n    reflexivity.\nDefined.\n\n(* Instances of ghost state *)\nSection Snapshot.\n(* One common kind of PCM is one in which a central authority has a reference copy, and clients pass around\n   partial knowledge. *)\n\nContext `{ORD : PCM_order}.\n\nLemma join_refl : forall v, join v v v.\nProof.\n  intros; apply ord_join; reflexivity.\nQed.\n\nLemma join_compat : forall v1 v2 v' v'', join v2 v' v'' -> ord v1 v2 -> exists v0, join v1 v' v0 /\\ ord v0 v''.\nProof.\n  intros.\n  destruct (join_ord _ _ _ H).\n  apply ord_lub; auto; etransitivity; eauto.\nQed.\n\nLemma join_ord_eq : forall a b, ord a b <-> exists c, join a c b.\nProof.\n  split.\n  - intros; exists b.\n    apply ord_join in H.\n    apply join_comm; auto.\n  - intros (? & H); apply join_ord in H; tauto.\nQed.\n\n(* The master-snapshot PCM in the RCU paper divides the master into shares, which is useful for having both\n   an authoritative writer and an up-to-date invariant. *)\n(* This generalizes both ghost_var and master-snapshot. *)\n\nGlobal Instance snap_PCM : PCM (share * A) :=\n  { join a b c := sepalg.join (fst a) (fst b) (fst c) /\\\n      if eq_dec (fst a) Share.bot then if eq_dec (fst b) Share.bot then join (snd a) (snd b) (snd c)\n        else ord (snd a) (snd b) /\\ snd c = snd b else snd c = snd a /\\\n          if eq_dec (fst b) Share.bot then ord (snd b) (snd a) else snd c = snd b }.\nProof.\n  - intros ??? [? Hjoin].\n    if_tac; if_tac; try destruct Hjoin; auto.\n    split; auto; apply join_comm; auto.\n  - intros.\n    destruct Hjoin1 as [Hsh1 Hjoin1], Hjoin2 as [Hsh2 Hjoin2].\n    destruct (sepalg.join_assoc Hsh1 Hsh2) as [sh' []].\n    destruct (eq_dec (fst b) Share.bot).\n    + assert (fst c = fst a) as Hc.\n      { eapply sepalg.join_eq; eauto.\n        rewrite e0; apply join_bot_eq. }\n      rewrite Hc in *.\n      assert (sh' = fst d) as Hd.\n      { eapply sepalg.join_eq; eauto.\n        rewrite e0; apply bot_join_eq. }\n      rewrite Hd in *.\n      destruct (eq_dec (fst d) Share.bot).\n      * destruct (eq_dec (fst a) Share.bot).\n        -- destruct (join_assoc _ _ _ _ _ Hjoin1 Hjoin2) as [c' []].\n           exists (Share.bot, c'); simpl; rewrite eq_dec_refl; rewrite ?e2, ?e0, ?e1 in *; auto.\n        -- destruct Hjoin1 as [Hc' ?]; rewrite Hc' in *.\n           destruct Hjoin2; exploit (ord_lub (snd b) (snd d)); eauto; intros [c' []].\n           exists (Share.bot, c'); simpl; rewrite eq_dec_refl; rewrite ?e0, ?e1 in *; auto.\n      * exists d.\n        destruct (eq_dec (fst a) Share.bot); if_tac; try contradiction.\n        -- destruct Hjoin2.\n           apply join_ord in Hjoin1; destruct Hjoin1.\n           split; split; auto; split; auto; etransitivity; eauto.\n        -- destruct Hjoin2 as [He1 He2]; rewrite He1, He2 in *.\n           destruct Hjoin1 as [Hd' ?]; rewrite Hd' in *; auto.\n    + exists (sh', snd b); simpl.\n      destruct (eq_dec (fst c) Share.bot).\n      { rewrite e0 in Hsh1; apply join_Bot in Hsh1; destruct Hsh1; contradiction. }\n      destruct (eq_dec sh' Share.bot).\n      { subst; apply join_Bot in H; destruct H; contradiction. }\n      destruct Hjoin2 as [He ?]; rewrite He in *; split; auto; split; auto; split; auto.\n      replace (snd b) with (snd c) by (destruct (eq_dec (fst a) Share.bot); tauto); auto.\nDefined.\n\nDefinition ghost_snap (a : A) p := ghost (Share.bot, a) p.\n\nLemma ghost_snap_join : forall v1 v2 p v, join v1 v2 v ->\n  ghost_snap v1 p * ghost_snap v2 p = ghost_snap v p.\nProof.\n  intros; apply ghost_join; simpl.\n  rewrite !eq_dec_refl; auto.\nQed.\n\nLemma ghost_snap_conflict : forall v1 v2 p, ghost_snap v1 p * ghost_snap v2 p |-- !!(joins v1 v2).\nProof.\n  intros; eapply derives_trans; [apply ghost_conflict|].\n  apply prop_left; intros ((?, a) & ? & Hj); simpl in Hj.\n  rewrite !eq_dec_refl in Hj.\n  apply prop_right; exists a; auto.\nQed.\n\nLemma ghost_snap_join' : forall v1 v2 p,\n  ghost_snap v1 p * ghost_snap v2 p = EX v : _, !!(join v1 v2 v) && ghost_snap v p.\nProof.\n  intros; apply mpred_ext.\n  - assert_PROP (joins v1 v2) as H by apply ghost_snap_conflict.\n    destruct H as [v]; Exists v; entailer!.\n    erewrite ghost_snap_join; eauto.\n  - Intros v; erewrite ghost_snap_join; eauto.\nQed.\n\nLemma snap_master_join : forall v1 sh v2 p, sh <> Share.bot ->\n  ghost_snap v1 p * ghost (sh, v2) p = !!(ord v1 v2) && ghost (sh, v2) p.\nProof.\n  intros; apply mpred_ext.\n  - eapply derives_trans; [apply prop_and_same_derives, ghost_conflict|].\n    apply derives_extract_prop; intros ((sh', ?) & Hj).\n    setoid_rewrite ghost_join; eauto.\n    simpl in Hj.\n    rewrite eq_dec_refl in Hj; destruct Hj as [Hsh Hj].\n    unfold share in Hj; destruct (eq_dec sh Share.bot); [contradiction|].\n    assert (sh' = sh) by (eapply sepalg.join_eq; eauto; apply bot_join_eq).\n    destruct Hj; subst; entailer!.\n  - Intros; setoid_rewrite ghost_join; eauto.\n    simpl; rewrite eq_dec_refl; split.\n    + apply bot_join_eq.\n    + if_tac; auto; contradiction.\nQed.\n\nLemma master_update : forall v v' p, ord v v' -> view_shift (ghost (Tsh, v) p) (ghost (Tsh, v') p).\nProof.\n  intros; apply ghost_update.\n  intros ? (x & Hj); simpl in Hj.\n  exists (Tsh, v'); simpl.\n  destruct (eq_dec Tsh Share.bot); [contradiction Share.nontrivial|].\n  destruct Hj as [Hsh [? Hc']]; apply join_Tsh in Hsh; destruct Hsh as [? Hc]; rewrite Hc in *.\n  rewrite eq_dec_refl in Hc' |- *; split; auto; split; auto.\n  etransitivity; eauto.\nQed.\n\nLemma master_init : forall (a : A), exists g', joins (Tsh, a) g'.\nProof.\n  intros; exists (Share.bot, a), (Tsh, a); simpl.\n  split; auto.\n  if_tac; [contradiction Share.nontrivial|].\n  rewrite eq_dec_refl; split; reflexivity.\nQed.\n\nLemma make_snap : forall (sh : share) v p, view_shift (ghost (sh, v) p) (ghost_snap v p * ghost (sh, v) p).\nProof.\n  intros; destruct (eq_dec sh Share.bot).\n  - subst; setoid_rewrite ghost_snap_join; [unfold ghost_snap; reflexivity | apply join_refl].\n  - rewrite snap_master_join by auto.\n    apply derives_view_shift; entailer!.\nQed.\n\nLemma ghost_snap_forget : forall v1 v2 p, ord v1 v2 -> view_shift (ghost_snap v2 p) (ghost_snap v1 p).\nProof.\n  intros; apply ghost_update.\n  intros (shc, c) [(shx, x) [? Hj]]; simpl in *.\n  rewrite eq_dec_refl in Hj.\n  assert (shx = shc) by (eapply sepalg.join_eq; eauto); subst.\n  unfold share in Hj; destruct (eq_dec shc Share.bot); subst.\n  - destruct (join_compat _ _ _ _ Hj H) as [x' []].\n    exists (Share.bot, x'); simpl.\n    rewrite !eq_dec_refl; auto.\n  - destruct Hj; subst.\n    exists (shc, c); simpl.\n    rewrite eq_dec_refl; if_tac; [contradiction|].\n    split; auto; split; auto.\n    etransitivity; eauto.\nQed.\n\nLemma ghost_snap_choose : forall v1 v2 p, view_shift (ghost_snap v1 p * ghost_snap v2 p) (ghost_snap v1 p).\nProof.\n  intros.\n  eapply view_shift_assert.\n  { apply ghost_conflict. }\n  intros [x [? Hj]]; simpl in *.\n  rewrite !eq_dec_refl in Hj.\n  erewrite ghost_snap_join by eauto; apply join_ord in Hj; destruct Hj.\n  apply ghost_snap_forget; eauto.\nQed.\n\nLemma master_share_join : forall sh1 sh2 sh v p, sepalg.join sh1 sh2 sh ->\n  ghost (sh1, v) p * ghost (sh2, v) p = ghost (sh, v) p.\nProof.\n  intros; apply ghost_join; simpl; split; auto.\n  if_tac; if_tac; try split; auto; try apply ord_refl; apply join_refl.\nQed.\n\nLemma master_inj : forall sh1 sh2 v1 v2 p, readable_share sh1 -> readable_share sh2 ->\n  ghost (sh1, v1) p * ghost (sh2, v2) p |-- !!(v1 = v2).\nProof.\n  intros.\n  eapply derives_trans; [apply ghost_conflict|].\n  apply prop_left; intros ((?, ?) & Hj); simpl in Hj.\n  destruct (eq_dec sh1 Share.bot); [subst; contradiction unreadable_bot|].\n  destruct (eq_dec sh2 Share.bot); [subst; contradiction unreadable_bot|].\n  destruct Hj as [? []]; subst; apply prop_right; auto.\nQed.\n\nLemma master_share_join' : forall sh1 sh2 sh v1 v2 p, readable_share sh1 -> readable_share sh2 ->\n  sepalg.join sh1 sh2 sh ->\n  ghost (sh1, v1) p * ghost (sh2, v2) p = !!(v1 = v2) && ghost (sh, v2) p.\nProof.\n  intros; apply mpred_ext.\n  - assert_PROP (v1 = v2) by (apply master_inj; auto).\n    subst; erewrite master_share_join; eauto; entailer!.\n  - Intros; subst.\n    erewrite master_share_join; eauto.\nQed.\n\n(* useful when we only want to deal with full masters *)\nDefinition ghost_master (a : A) p := ghost (Tsh, a) p.\n\nLemma snap_master_join1 : forall v1 v2 p,\n  ghost_snap v1 p * ghost_master v2 p = !!(ord v1 v2) && ghost_master v2 p.\nProof.\n  intros; apply snap_master_join, Share.nontrivial.\nQed.\n\nLemma snap_master_update1 : forall v1 v2 p v', ord v2 v' ->\n  view_shift (ghost_snap v1 p * ghost_master v2 p) (ghost_snap v' p * ghost_master v' p).\nProof.\n  intros; rewrite !snap_master_join1.\n  etransitivity.\n  - apply view_shift_prop; intro.\n    apply master_update; eauto.\n  - apply derives_view_shift; entailer!.\nQed.\n\nEnd Snapshot.\n\nSection GVar.\n\nContext {A : Type}.\n\nInstance univ_PCM : PCM A := { join a b c := True }.\nProof.\n  - auto.\n  - eauto.\nDefined.\n\nInstance univ_order : PCM_order (fun _ _ => True).\nProof.\n  constructor; auto.\n  intros; exists a; auto.\nDefined.\n\nDefinition ghost_var (sh : share) (v : A) p := ghost (sh, v) p.\n\nLemma ghost_var_share_join : forall sh1 sh2 sh v p, sepalg.join sh1 sh2 sh ->\n  ghost_var sh1 v p * ghost_var sh2 v p = ghost_var sh v p.\nProof.\n  apply master_share_join.\nQed.\n\nLemma ghost_var_inj : forall sh1 sh2 v1 v2 p, readable_share sh1 -> readable_share sh2 ->\n  ghost_var sh1 v1 p * ghost_var sh2 v2 p |-- !!(v1 = v2).\nProof.\n  apply master_inj.\nQed.\n\nLemma ghost_var_share_join' : forall sh1 sh2 sh v1 v2 p, readable_share sh1 -> readable_share sh2 ->\n  sepalg.join sh1 sh2 sh ->\n  ghost_var sh1 v1 p * ghost_var sh2 v2 p = !!(v1 = v2) && ghost_var sh v2 p.\nProof.\n  apply master_share_join'.\nQed.\n\nLemma ghost_var_update : forall v p v', view_shift (ghost_var Tsh v p) (ghost_var Tsh v' p).\nProof.\n  intros; apply master_update; auto.\nQed.\n\nLemma ghost_var_precise : forall sh p, precise (EX v : A, ghost_var sh v p).\nProof.\n  intros; apply derives_precise' with (EX g : share * A, ghost g p), ex_ghost_precise.\n  Intro v; Exists (sh, v); auto.\nQed.\n\nLemma ghost_var_precise' : forall sh v p, precise (ghost_var sh v p).\nProof.\n  intros; apply derives_precise with (Q := EX v : A, ghost_var sh v p);\n    [exists v; auto | apply ghost_var_precise].\nQed.\n\nLemma ghost_var_init : forall (g : share * A), exists g', joins g g'.\nProof.\n  intros (sh, a); exists (Share.bot, a), (sh, a); simpl.\n  split; auto.\n  rewrite !eq_dec_refl; if_tac; auto.\nQed.\n\nEnd GVar.\n\nSection Reference.\n(* One common kind of PCM is one in which a central authority has a reference copy, and clients pass around\n   partial knowledge. When a client recovers all pieces, it can gain full knowledge. *)\n(* This is related to the snapshot PCM, but the snapshots aren't duplicable. *)\n\nContext `{P : PCM}.\n\nInstance pos_PCM : PCM (option (share * A)) := { join a b c :=\n  match a, b, c with\n  | Some (sha, a'), Some (shb, b'), Some (shc, c') =>\n      sha <> Share.bot /\\ shb <> Share.bot /\\ sepalg.join sha shb shc /\\ join a' b' c'\n  | Some (sha, a'), None, Some c' => sha <> Share.bot /\\ c' = (sha, a')\n  | None, Some (shb, b'), Some c' => shb <> Share.bot /\\ c' = (shb, b')\n  | None, None, None => True\n  | _, _, _ => False\n  end }.\nProof.\n  - destruct a as [(?, ?)|], b as [(?, ?)|], c as [(?, ?)|]; auto.\n    intros (? & ? & ? & ?); repeat (split; auto); apply join_comm; auto.\n  - destruct a as [(?, ?)|], b as [(?, ?)|], c as [(?, ?)|], d as [(?, ?)|], e as [(?, ?)|]; try contradiction;\n      intros; decompose [and] Hjoin1; decompose [and] Hjoin2;\n      repeat match goal with H : (_, _) = (_, _) |- _ => inv H end;\n      try solve [eexists (Some _); split; auto; auto]; try solve [exists None; split; auto].\n    + destruct (@sepalg.join_assoc _ _ _ s s0 s2 s1 s3) as (sh' & ? & ?); auto.\n      destruct (join_assoc a a0 a1 a2 a3) as (a' & ? & ?); auto.\n      exists (Some (sh', a')); repeat (split; auto).\n      intro; subst.\n      exploit join_Bot; eauto; tauto.\n    + exists (Some (s2, a2)); repeat (split; auto).\n      intro; subst.\n      exploit join_Bot; eauto; tauto.\nDefined.\n\nDefinition completable a r := exists x, join a x (Some (Tsh, r)).\n\nGlobal Instance ref_PCM : PCM (option (share * A) * option A) :=\n  { join a b c := join (fst a) (fst b) (fst c) /\\ @join _ exclusive_PCM (snd a) (snd b) (snd c) /\\\n      match snd c with Some r => completable (fst c) r | None => True end }.\nProof.\n  - intros ??? (Hfst & Hsnd & ?).\n    split; [|split]; try apply join_comm; auto.\n  - intros ????? (Hfst1 & Hsnd1 & Hcase1) (Hfst2 & Hsnd2 & Hcase2).\n    destruct (join_assoc _ _ _ _ _ Hfst1 Hfst2) as (c'1 & ? & Hc'1).\n    destruct (join_assoc _ _ _ _ _ Hsnd1 Hsnd2) as (c'2 & ? & Hc'2).\n    exists (c'1, c'2).\n    destruct Hc'2 as [(He & ?) | (? & ?)]; subst; [repeat split; simpl; auto|].\n    repeat split; try solve [simpl; auto].\n    simpl snd; destruct (snd e); auto.\n    unfold completable.\n    destruct Hcase2 as (? & Hcase2).\n    apply join_comm in Hc'1.\n    destruct (join_assoc _ _ _ _ _ Hc'1 Hcase2) as (? & ? & ?); eauto.\nDefined.\n\nLemma ref_sub : forall (sh : share) (a b : A) p,\n  ghost (Some (sh, a), @None A) p * ghost (@None (share * A), Some b) p |--\n    !!(if eq_dec sh Tsh then a = b else exists x, join a x b).\nProof.\n  intros.\n  eapply derives_trans; [apply ghost_conflict|].\n  apply prop_left; intros (c & Hjoin & [(? & ?) | (Hc & ?)] & Hcompat); [discriminate | apply prop_right].\n  rewrite <- Hc in Hcompat; destruct Hcompat as (c' & Hsub).\n  simpl in Hjoin.\n  destruct (fst c); [|contradiction].\n  destruct Hjoin; subst.\n  simpl in Hsub.\n  destruct c' as [(?, ?)|].\n  - destruct Hsub as (? & ? & Hsh & ?).\n    if_tac; eauto; subst.\n    apply join_Tsh in Hsh; tauto.\n  - destruct Hsub as (? & Hsub); inv Hsub.\n    rewrite eq_dec_refl; auto.\nQed.\n\nEnd Reference.\n\nSection PVar.\n(* Like ghost variables, but the partial values may be out of date. *)\n\nInstance max_PCM : PCM Z := { join a b c := c = Z.max a b }.\nProof.\n  - intros; rewrite Z.max_comm; auto.\n  - intros; do 2 eexists; eauto; subst.\n    rewrite Z.max_assoc; auto.\nDefined.\n\nGlobal Instance max_order : PCM_order Z.le.\nProof.\n  constructor; simpl; intros.\n  - intro; omega.\n  - intros ???; omega.\n  - do 2 eexists; eauto; apply Z.max_lub; auto.\n  - subst; split; [apply Z.le_max_l | apply Z.le_max_r].\n  - rewrite Z.max_l; auto.\nDefined.\n\nLemma ghost_snap_join_Z : forall v1 v2 p, ghost_snap v1 p * ghost_snap v2 p = ghost_snap (Z.max v1 v2) p.\nProof.\n  intros; apply ghost_snap_join; simpl; auto.\nQed.\n\nLemma snap_master_join' : forall v1 v2 p,\n  ghost_snap v1 p * ghost_master v2 p = !!(v1 <= v2) && ghost_master v2 p.\nProof.\n  intros; apply snap_master_join1.\nQed.\n\nLemma snap_master_update' : forall (v1 v2 : Z) p v', v2 <= v' ->\n  view_shift (ghost_snap v1 p * ghost_master v2 p) (ghost_snap v' p * ghost_master v' p).\nProof.\n  intros; apply snap_master_update1; auto.\nQed.\n\nEnd PVar.\n\nSection ListMap.\n\nRequire Import Sorting.Permutation.\n\nContext {A B : Type}.\n\nDefinition disjoint (h1 h2 : list (A * B)) := forall n e, In (n, e) h1 -> forall e', ~In (n, e') h2.\n\nLemma disjoint_nil : forall l, disjoint l [].\nProof.\n  repeat intro; contradiction.\nQed.\nHint Resolve disjoint_nil.\n\nLemma disjoint_comm : forall a b, disjoint a b -> disjoint b a.\nProof.\n  intros ?? Hdisj ?? Hin ? Hin'.\n  eapply Hdisj; eauto.\nQed.\n\nLemma disjoint_app : forall a b c, disjoint (a ++ b) c <-> disjoint a c /\\ disjoint b c.\nProof.\n  split.\n  - intro; split; repeat intro; eapply H; eauto; rewrite in_app; eauto.\n  - intros (Ha & Hb) ?????.\n    rewrite in_app in H; destruct H; [eapply Ha | eapply Hb]; eauto.\nQed.\n\nRequire Import Morphisms.\n\nGlobal Instance Permutation_disjoint :\n  Proper (@Permutation _ ==> @Permutation _ ==> iff) disjoint.\nProof.\n  intros ?? Hp1 ?? Hp2.\n  split; intro Hdisj; repeat intro.\n  - eapply Hdisj; [rewrite Hp1 | rewrite Hp2]; eauto.\n  - eapply Hdisj; [rewrite <- Hp1 | rewrite <- Hp2]; eauto.\nQed.\n\nGlobal Instance map_PCM : PCM (list (A * B)) := { join a b c := disjoint a b /\\ Permutation (a ++ b) c }.\nProof.\n  - intros ??? (Hdisj & ?); split.\n    + apply disjoint_comm; auto.\n    + etransitivity; [|eauto].\n      apply Permutation_app_comm.\n  - intros ????? (Hd1 & Hc) (Hd2 & He).\n    rewrite <- Hc, disjoint_app in Hd2; destruct Hd2 as (Hd2 & Hd3).\n    exists (b ++ d); repeat split; auto.\n    + apply disjoint_comm; rewrite disjoint_app; split; apply disjoint_comm; auto.\n    + etransitivity; [|eauto].\n      rewrite app_assoc; apply Permutation_app_tail; auto.\nDefined.\n\nLemma ghost_map_init : exists g', joins (@nil (A * B)) g'.\nProof.\n  exists []; exists []; simpl; auto.\nQed.\n\nEnd ListMap.\nHint Resolve disjoint_nil.\n\nSection GHist.\n\n(* Ghost histories in the style of Nanevsky *)\nContext {hist_el : Type}.\n\nNotation hist_part := (list (nat * hist_el)).\n\nDefinition hist_sub sh (h : hist_part) hr := if eq_dec sh Tsh then h = hr\n  else sh <> Share.bot /\\ exists h', disjoint h h' /\\ Permutation (h ++ h') hr.\n\nLemma completable_alt : forall sh h hr, completable (Some (sh, h)) hr <-> hist_sub sh h hr.\nProof.\n  unfold completable, hist_sub; intros; simpl; split.\n  - intros ([(?, ?)|] & Hcase).\n    + destruct Hcase as (? & ? & Hsh & ? & ?).\n      if_tac; eauto.\n      subst; apply join_Tsh in Hsh; tauto.\n    + destruct Hcase as (? & Heq); inv Heq.\n      rewrite eq_dec_refl; auto.\n  - if_tac.\n    + intro; subst; exists None; split; auto.\n      apply Share.nontrivial.\n    + intros (? & h' & ?); exists (Some (Share.comp sh, h')).\n      split; auto.\n      split.\n      { intro Hbot; contradiction H.\n        rewrite <- Share.comp_inv at 1.\n        rewrite Hbot; apply comp_bot. }\n      split; [apply comp_join_top | auto].\nQed.\n\nLemma hist_sub_snoc : forall sh h hr t' e (Hsub : hist_sub sh h hr) (Hfresh : ~In t' (map fst hr)),\n  hist_sub sh (h ++ [(t', e)]) (hr ++ [(t', e)]).\nProof.\n  unfold hist_sub; intros.\n  if_tac; subst; auto.\n  destruct Hsub as (? & h' & ? & Hperm); split; auto.\n  exists h'; split.\n  - rewrite disjoint_app; split; auto.\n    intros ?? [Heq | ?]; [inv Heq | contradiction].\n    intros ??; contradiction Hfresh; rewrite in_map_iff.\n    do 2 eexists; [|rewrite <- Hperm, in_app; eauto]; auto.\n  - rewrite <- app_assoc; etransitivity; [apply Permutation_app_head, Permutation_app_comm|].\n    rewrite app_assoc; apply Permutation_app; auto.\nQed.\n\nDefinition ghost_hist (sh : share) (h : hist_part) p := (ghost (Some (sh, h), @None hist_part) p).\n\nLemma ghost_hist_join : forall sh1 sh2 sh h1 h2 h p (Hsh : sepalg.join sh1 sh2 sh)\n  (Hh : Permutation (h1 ++ h2) h) (Hsh1 : sh1 <> Share.bot) (Hsh2 : sh2 <> Share.bot),\n  ghost_hist sh1 h1 p * ghost_hist sh2 h2 p = !!(disjoint h1 h2) && ghost_hist sh h p.\nProof.\n  intros; unfold ghost_hist.\n  apply mpred_ext.\n  - assert_PROP (disjoint h1 h2).\n    { eapply derives_trans; [apply ghost_conflict|].\n      apply prop_left; intros (x & ? & ?); simpl in *.\n      apply prop_right; destruct (fst x) as [(?, ?)|]; [tauto | contradiction]. }\n    erewrite ghost_join; [entailer!|].\n    repeat (split; simpl; auto).\n  - Intros.\n    erewrite ghost_join; eauto.\n    repeat (split; simpl; auto).\nQed.\n\nDefinition hist_incl (h : hist_part) l := forall t e, In (t, e) h -> nth_error l t = Some e.\n\nDefinition hist_list (h : hist_part) l := NoDup h /\\ forall t e, In (t, e) h <-> nth_error l t = Some e.\n\nLemma hist_list_inj : forall h l1 l2 (Hl1 : hist_list h l1) (Hl2 : hist_list h l2), l1 = l2.\nProof.\n  unfold hist_list; intros; apply list_nth_error_eq.\n  destruct Hl1 as (? & Hl1), Hl2 as (? & Hl2).\n  intro j; specialize (Hl1 j); specialize (Hl2 j).\n  destruct (nth_error l1 j).\n  - symmetry; rewrite <- Hl2, Hl1; auto.\n  - destruct (nth_error l2 j); auto.\n    specialize (Hl2 h0); rewrite Hl1 in Hl2; tauto.\nQed.\n\nLemma hist_list_nil_inv1 : forall l, hist_list [] l -> l = [].\nProof.\n  unfold hist_list; intros.\n  destruct l; auto.\n  destruct H as (_ & H).\n  specialize (H O h); destruct H; simpl in *; contradiction.\nQed.\n\nLemma hist_list_nil_inv2 : forall h, hist_list h [] -> h = [].\nProof.\n  unfold hist_list; intros.\n  destruct h as [|(t, e)]; auto.\n  destruct H as (_ & H).\n  specialize (H t e); destruct H as (H & _).\n  exploit H; [simpl; auto | rewrite nth_error_nil; discriminate].\nQed.\n\nLemma NoDup_remove_0 : forall {A} (l : list (nat * A)), NoDup (map fst l) -> ~In O (map fst l) ->\n  NoDup (map fst (map (fun '(t, e) => ((t - 1)%nat, e)) l)).\nProof.\n  induction l; auto; simpl; intros.\n  inv H.\n  constructor; auto.\n  destruct a.\n  rewrite in_map_iff; intros ((?, ?) & Heq & Hin); simpl in *; inv Heq.\n  rewrite in_map_iff in Hin; destruct Hin as ((?, ?) & Heq & ?); inv Heq.\n  assert (In n (map fst l)); [|contradiction].\n  rewrite in_map_iff; do 2 eexists; eauto.\n  destruct n; [tauto|].\n  destruct n0; [|simpl in *; omega].\n  assert (In O (map fst l)); [|tauto].\n  rewrite in_map_iff; do 2 eexists; eauto; auto.\nQed.\n\nLemma NoDup_remove_0' : forall {A} (l : list (nat * A)), NoDup l -> ~In O (map fst l) ->\n  NoDup (map (fun '(t, e) => ((t - 1)%nat, e)) l).\nProof.\n  induction l; auto; simpl; intros.\n  inv H.\n  constructor; auto.\n  destruct a.\n  rewrite in_map_iff; intros ((?, ?) & Heq & Hin); simpl in *; inv Heq.\n  destruct n; [tauto|].\n  destruct n0; [|simpl in *; assert (n0 = n) by omega; subst; contradiction].\n  assert (In O (map fst l)); [|tauto].\n  rewrite in_map_iff; do 2 eexists; eauto; auto.\nQed.\n\nLemma remove_0_inj : forall {A} (l : list (nat * A)), ~In O (map fst l) ->\n  map fst (map (fun '(t, e) => ((t - 1)%nat, e)) l) = map (fun t => t - 1)%nat (map fst l).\nProof.\n  induction l; auto; simpl; intros.\n  destruct a; rewrite IHl; auto.\nQed.\n\nLemma hist_list_NoDup : forall l h (Hl : hist_list h l), NoDup (map fst h).\nProof.\n  induction l; intros; [apply hist_list_nil_inv2 in Hl; subst; constructor|].\n  destruct Hl as (Hd & Hl).\n  assert (In (O, a) h) as Hin.\n  { unfold hist_list in Hl; rewrite Hl; auto. }\n  exploit in_split; eauto; intros (h1 & h2 & ?); subst.\n  apply NoDup_remove in Hd; destruct Hd as (? & Hn).\n  assert (~In O (map fst (h1 ++ h2))) as HO.\n  { rewrite in_map_iff; intros ((?, e) & ? & ?); simpl in *; subst.\n    specialize (Hl O e); destruct Hl as (Hl & _); exploit Hl.\n    { rewrite in_app in *; simpl; tauto. }\n    simpl; intro X; inv X; contradiction. }\n  exploit (IHl (map (fun x => let '(t, e) := x in ((t - 1)%nat, e)) (h1 ++ h2))).\n  { split.\n    { apply NoDup_remove_0'; auto. }\n    intros t e.\n    rewrite in_map_iff; split.\n    + intros ((?, ?) & Heq & ?); inv Heq.\n      specialize (Hl n e).\n      destruct Hl as (Hl & _); exploit Hl.\n      { rewrite in_app in *; simpl; tauto. }\n      destruct n; simpl; [|rewrite Nat.sub_0_r; auto].\n      contradiction HO.\n      rewrite in_map_iff; do 2 eexists; eauto; auto.\n    + intro Ht; specialize (Hl (S t) e); simpl in Hl.\n      destruct Hl as (_ & Hl); specialize (Hl Ht).\n      exists (S t, e); split; [simpl; rewrite Nat.sub_0_r; auto|].\n      rewrite in_app in *; destruct Hl as [? | [Heq | ?]]; auto.\n      inv Heq. }\n  intro Hd; rewrite map_app; simpl; apply NoDup_add; rewrite <- map_app; auto.\n  rewrite remove_0_inj in Hd; auto.\n  eapply NoDup_map_inv; eauto.\nQed.\n\nLemma hist_list_length : forall l h (Hl : hist_list h l), Zlength h = Zlength l.\nProof.\n  induction l; intros.\n  - apply hist_list_nil_inv2 in Hl; subst; auto.\n  - pose proof (hist_list_NoDup _ _ Hl) as Hdisj; destruct Hl as (? & Hl).\n    assert (In (O, a) h) as Hin.\n    { unfold hist_list in Hl; rewrite Hl; auto. }\n    exploit in_split; eauto; intros (h1 & h2 & ?); subst.\n    rewrite map_app in Hdisj; simpl in Hdisj; apply NoDup_remove in Hdisj.\n    destruct Hdisj as (Hdisj & Hn).\n    exploit (IHl (map (fun x => let '(t, e) := x in ((t - 1)%nat, e)) (h1 ++ h2))).\n    { split.\n      { apply NoDup_remove in H; destruct H.\n        apply NoDup_remove_0'; auto.\n        rewrite map_app; auto. }\n      intros t e.\n      rewrite in_map_iff; split.\n      + intros ((?, ?) & Heq & ?); inv Heq.\n        specialize (Hl n e).\n        destruct Hl as (Hl & _); exploit Hl.\n        { rewrite in_app in *; simpl; tauto. }\n        destruct n; simpl; [|rewrite Nat.sub_0_r; auto].\n        contradiction Hn.\n        rewrite <- map_app, in_map_iff; do 2 eexists; eauto; auto.\n      + intro Ht; specialize (Hl (S t) e); simpl in Hl.\n        destruct Hl as (_ & Hl); specialize (Hl Ht).\n        exists (S t, e); split; [simpl; rewrite Nat.sub_0_r; auto|].\n        rewrite in_app in *; destruct Hl as [? | [Heq | ?]]; auto.\n        inv Heq. }\n    rewrite Zlength_map, !Zlength_app, !Zlength_cons; omega.\nQed.\n\nDefinition ghost_ref l p := EX hr : hist_part, !!(hist_list hr l) &&\n  ghost (@None (share * hist_part), Some hr) p.\n\nLemma hist_next : forall h l (Hlist : hist_list h l), ~In (length l) (map fst h).\nProof.\n  intros; rewrite in_map_iff; intros ((?, ?) & ? & Hin); simpl in *; subst.\n  destruct Hlist as (? & Hlist); rewrite Hlist in Hin.\n  pose proof (nth_error_Some l (length l)) as (Hlt & _).\n  exploit Hlt; [|omega].\n  rewrite Hin; discriminate.\nQed.\n\nLemma hist_add : forall (sh : share) (h h' : hist_part) e p t' (Hfresh : ~In t' (map fst h')),\n  view_shift (ghost (Some (sh, h), Some h') p) (ghost (Some (sh, h ++ [(t', e)]), Some (h' ++ [(t', e)])) p).\nProof.\n  intros; apply ghost_update.\n  intros (c1, c2) ((d1, d2) & Hjoin1 & [(<- & ?) | (? & ?)] & Hcompat); try discriminate.\n  simpl in *.\n  destruct c1 as [(shc, hc)|], d1 as [(?, ?)|]; try contradiction.\n  - destruct Hjoin1 as (? & ? & ? & Hdisj & Hperm).\n    rewrite completable_alt in Hcompat; unfold hist_sub in Hcompat.\n    destruct (eq_dec s Tsh).\n    + subst; exists (Some (Tsh, h' ++ [(t', e)]), Some (h' ++ [(t', e)])).\n      repeat (split; simpl; auto).\n      * rewrite disjoint_app; split; auto.\n        intros ?? [Heq | ?]; [inv Heq | contradiction].\n        intros ??; contradiction Hfresh; rewrite in_map_iff.\n        do 2 eexists; [|rewrite <- Hperm, in_app; eauto]; auto.\n      * rewrite <- app_assoc.\n        etransitivity; [apply Permutation_app_head, Permutation_app_comm|].\n        rewrite app_assoc; apply Permutation_app; auto.\n      * rewrite completable_alt; apply hist_sub_snoc; auto.\n        unfold hist_sub; rewrite eq_dec_refl; auto.\n    + destruct Hcompat as (? & l' & ? & Hperm').\n      exists (Some (s, h ++ hc ++ [(t', e)]), Some (h' ++ [(t', e)])); repeat (split; simpl; auto).\n      * rewrite disjoint_app; split; auto.\n        intros ?? [Heq | ?]; [inv Heq | contradiction].\n        intros ??; contradiction Hfresh; rewrite in_map_iff.\n        do 2 eexists; [|rewrite <- Hperm', in_app, <- Hperm, in_app; eauto]; auto.\n      * rewrite <- app_assoc; apply Permutation_app_head, Permutation_app_comm.\n      * rewrite completable_alt, app_assoc; apply hist_sub_snoc; auto.\n        unfold hist_sub; if_tac; [contradiction n; auto|].\n        split; auto; exists l'; split.\n        { eapply Permutation_disjoint; eauto. }\n        etransitivity; [|eauto].\n        apply Permutation_app; auto.\n  - simpl in H; destruct Hjoin1 as (? & Hjoin1); inv Hjoin1.\n    exists (Some (sh, h ++ [(t', e)]), Some (h' ++ [(t', e)])); simpl; repeat (split; auto).\n    rewrite completable_alt in *; apply hist_sub_snoc; auto.\nQed.\n\nLemma hist_incl_nil : forall h, hist_incl [] h.\nProof.\n  repeat intro; contradiction.\nQed.\n\nLemma hist_list_nil : hist_list [] [].\nProof.\n  split; [constructor|].\n  split; [contradiction | rewrite nth_error_nil; discriminate].\nQed.\n\nLemma hist_list_snoc : forall h l e, hist_list h l -> hist_list (h ++ [(length l, e)]) (l ++ [e]).\nProof.\n  unfold hist_list; intros.\n  destruct H as (Hd & H).\n  assert (~In (length l, e) h).\n  { rewrite H; intro Hnth.\n    assert (length l < length l)%nat; [|omega].\n    rewrite <- nth_error_Some, Hnth; discriminate. }\n  split.\n  { apply NoDup_app_iff; repeat constructor; auto.\n    intros ?? [? | ?]; subst; contradiction. }\n  intros; rewrite in_app; split.\n  - intros [Hin | [Heq | ?]]; try contradiction.\n    + rewrite H in Hin.\n      rewrite nth_error_app1; auto.\n      rewrite <- nth_error_Some, Hin; discriminate.\n    + inv Heq; rewrite nth_error_app2, minus_diag; auto.\n  - destruct (lt_dec t (length l)).\n    + rewrite nth_error_app1 by auto.\n      rewrite <- H; auto.\n    + rewrite nth_error_app2 by omega.\n      destruct (eq_dec t (length l)).\n      * subst; rewrite minus_diag.\n        intro Heq; inv Heq; simpl; auto.\n      * destruct (t - length l)%nat eqn: Hminus; [omega | simpl; rewrite nth_error_nil; discriminate].\nQed.\n\nLemma hist_incl_permute : forall h1 h2 h' (Hincl : hist_incl h1 h') (Hperm : Permutation h1 h2),\n  hist_incl h2 h'.\nProof.\n  repeat intro.\n  rewrite <- Hperm in H; auto.\nQed.\n\nLemma hist_sub_incl : forall sh h h', hist_sub sh h h' -> incl h h'.\nProof.\n  unfold hist_sub; intros.\n  destruct (eq_dec sh Tsh); [subst; apply incl_refl|].\n  destruct H as (? & ? & ? & Hperm); repeat intro.\n  rewrite <- Hperm, in_app; auto.\nQed.\n\nCorollary hist_sub_list_incl : forall sh h h' l (Hsub : hist_sub sh h h') (Hlist : hist_list h' l),\n  hist_incl h l.\nProof.\n  unfold hist_list, hist_incl; intros.\n  destruct Hlist as (_ & <-); eapply hist_sub_incl; eauto.\nQed.\n\nLemma hist_sub_Tsh : forall h h', hist_sub Tsh h h' = (h = h').\nProof.\n  intros; unfold hist_sub; rewrite eq_dec_refl; auto.\nQed.\n\nLemma hist_ref_join : forall sh h l p, sh <> Share.bot ->\n  ghost_hist sh h p * ghost_ref l p =\n  EX h' : hist_part, !!(hist_list h' l /\\ hist_sub sh h h') && ghost (Some (sh, h), Some h') p.\nProof.\n  unfold ghost_hist, ghost_ref; intros; apply mpred_ext.\n  - Intros hr; Exists hr.\n    eapply derives_trans; [apply prop_and_same_derives, ghost_conflict|].\n    apply derives_extract_prop; intros (x & Hj1 & Hj2 & Hcompat).\n    destruct Hj2 as [(? & ?) | (Hsnd & ?)]; [discriminate|].\n    rewrite <- Hsnd in Hcompat; simpl in *.\n    destruct (fst x); [destruct Hj1 as (_ & Heq); inv Heq | contradiction].\n    assert (hist_sub sh h hr) by (rewrite <- completable_alt; auto).\n    entailer!.\n    erewrite ghost_join; eauto.\n    simpl; auto.\n  - Intros h'.\n    Exists h'; entailer!.\n    erewrite ghost_join; eauto.\n    repeat (split; simpl; auto).\n    rewrite completable_alt; auto.\nQed.\n\nCorollary hist_ref_join_nil : forall sh p, sh <> Share.bot ->\n  ghost_hist sh [] p * ghost_ref [] p = ghost (Some (sh, [] : hist_part), Some ([] : hist_part)) p.\nProof.\n  intros; rewrite hist_ref_join by auto.\n  apply mpred_ext; entailer!.\n  - destruct h' as [|(t, e)]; auto.\n    match goal with H : hist_list _ _ |- _ => destruct H as (_ & H);\n      specialize (H t e); destruct H as (Hin & _) end.\n    exploit Hin; [simpl; auto | rewrite nth_error_nil; discriminate].\n  - Exists ([] : hist_part); entailer!.\n    split; [apply hist_list_nil|].\n    unfold hist_sub; if_tac; auto.\n    split; auto; exists []; auto.\nQed.\n\nLemma hist_ref_incl : forall sh h h' p, sh <> Share.bot ->\n  ghost_hist sh h p * ghost_ref h' p |-- !!hist_incl h h'.\nProof.\n  intros; rewrite hist_ref_join by auto.\n  Intros l; eapply prop_right, hist_sub_list_incl; eauto.\nQed.\n\nLemma hist_add' : forall sh h h' e p, sh <> Share.bot ->\n  view_shift (ghost_hist sh h p * ghost_ref h' p)\n  (ghost_hist sh (h ++ [(length h', e)]) p * ghost_ref (h' ++ [e]) p).\nProof.\n  intros; rewrite hist_ref_join by auto.\n  repeat intro.\n  rewrite extract_exists_in_SEP; Intro hr.\n  erewrite extract_prop_in_SEP with (n := O); simpl; eauto; Intros.\n  match goal with H : hist_list _ _ |- _ => pose proof (hist_next _ _ H) end.\n  apply hist_add with (e := e)(t' := length h'); auto.\n  eapply semax_pre; [|eauto].\n  go_lowerx; rewrite hist_ref_join by auto.\n  Exists (hr ++ [(length h', e)]); entailer!.\n  split; [apply hist_list_snoc | apply hist_sub_snoc]; auto.\nQed.\n\nDefinition newer (l : hist_part) t := Forall (fun x => fst x < t)%nat l.\n\nLemma newer_trans : forall l t1 t2, newer l t1 -> (t1 <= t2)%nat -> newer l t2.\nProof.\n  intros.\n  eapply Forall_impl, H; simpl; intros; omega.\nQed.\n\nCorollary newer_snoc : forall l t1 e t2, newer l t1 -> (t1 < t2)%nat -> newer (l ++ [(t1, e)]) t2.\nProof.\n  unfold newer; intros.\n  rewrite Forall_app; split; [|repeat constructor; auto].\n  eapply newer_trans; eauto; omega.\nQed.\n\nLemma hist_incl_lt : forall h l, hist_incl h l -> newer h (length l).\nProof.\n  unfold hist_incl; intros.\n  unfold newer; rewrite Forall_forall; intros (?, ?) Hin.\n  erewrite <- nth_error_Some, H; eauto; discriminate.\nQed.\n\nVariable (d : hist_el).\n\nDefinition ordered_hist h := forall i j (Hi : 0 <= i < j) (Hj : j < Zlength h),\n  (fst (Znth i h (O, d)) < fst (Znth j h (O, d)))%nat.\n\nLemma ordered_nil : ordered_hist [].\nProof.\n  repeat intro.\n  rewrite Zlength_nil in *; omega.\nQed.\n\nLemma ordered_cons : forall t e h, ordered_hist ((t, e) :: h) ->\n  Forall (fun x => let '(m, _) := x in t < m)%nat h /\\ ordered_hist h.\nProof.\n  unfold ordered_hist; split.\n  - rewrite Forall_forall; intros (?, ?) Hin.\n    apply In_Znth with (d0 := (O, d)) in Hin.\n    destruct Hin as (j & ? & Hj).\n    exploit (H 0 (j + 1)); try omega.\n    { rewrite Zlength_cons; omega. }\n    rewrite Znth_0_cons, Znth_pos_cons, Z.add_simpl_r, Hj by omega; auto.\n  - intros; exploit (H (i + 1) (j + 1)); try omega.\n    { rewrite Zlength_cons; omega. }\n    rewrite !Znth_pos_cons, !Z.add_simpl_r by omega; auto.\nQed.\n\nLemma ordered_last : forall t e h (Hordered : ordered_hist h) (Hin : In (t, e) h)\n  (Ht : Forall (fun x => let '(m, _) := x in m <= t)%nat h), last h (O, d) = (t, e).\nProof.\n  induction h; [contradiction | simpl; intros].\n  destruct a; apply ordered_cons in Hordered; destruct Hordered as (Ha & ?).\n  inversion Ht as [|??? Hp]; subst.\n  destruct Hin as [Hin | Hin]; [inv Hin|].\n  - destruct h; auto.\n    inv Ha; inv Hp; destruct p; omega.\n  - rewrite IHh; auto.\n    destruct h; auto; contradiction.\nQed.\n\nLemma ordered_snoc : forall h t e, ordered_hist h -> newer h t -> ordered_hist (h ++ [(t, e)]).\nProof.\n  repeat intro.\n  rewrite Zlength_app, Zlength_cons, Zlength_nil in Hj.\n  rewrite app_Znth1 by omega.\n  destruct (eq_dec j (Zlength h)).\n  - rewrite Znth_app1; auto.\n    apply Forall_Znth; auto; omega.\n  - specialize (H i j).\n    rewrite app_Znth1 by omega; apply H; auto; omega.\nQed.\n\nLemma ordered_hist_list : forall l h i (Hordered : ordered_hist h) (Hl : hist_list h l)\n  (Hi : 0 <= i < Zlength l), Znth i h (O, d) = (Z.to_nat i, Znth i l d).\nProof.\n  intros.\n  pose proof (hist_list_length _ _ Hl) as Hlen.\n  destruct Hl as (? & Hl).\n  assert (nth (Z.to_nat i) (map fst h) (fst (O, d)) = Z.to_nat i) as Ht.\n  { assert (length h = length l) as Hlen'\n      by (rewrite Zlength_length, ZtoNat_Zlength in Hlen by (apply Zlength_nonneg); auto).\n    apply nat_sorted_list_eq with (n := length h).\n    - intro j; specialize (Hl j).\n      split; intro Hin.\n      + specialize (Hl (nth j l d)).\n        erewrite nth_error_nth in Hl by omega.\n        destruct Hl as (_ & Hl); rewrite in_map_iff; do 2 eexists; [|apply Hl]; eauto.\n      + rewrite in_map_iff in Hin; destruct Hin as ((?, e) & ? & Hin); simpl in *; subst.\n        rewrite Hl in Hin; rewrite Hlen', <- nth_error_Some, Hin; discriminate.\n    - apply map_length.\n    - intros i' j' ?.\n      exploit (Hordered (Z.of_nat i') (Z.of_nat j')).\n      { split; [omega|].\n        apply Nat2Z.inj_lt; tauto. }\n      { rewrite Zlength_correct; apply Nat2Z.inj_lt; tauto. }\n      rewrite !map_nth, !nth_Znth; auto.\n    - rewrite <- ZtoNat_Zlength; apply Z2Nat.inj_lt; omega. }\n  rewrite nth_Znth, Z2Nat.id in Ht by tauto.\n  erewrite Znth_map with (d' := (O, d)) in Ht by omega.\n  destruct (Znth i h (O, d)) as (t, e) eqn: Heq.\n  specialize (Hl t e); rewrite <- Heq in Hl.\n  destruct Hl as (Hl & _); exploit Hl.\n  { apply Znth_In; omega. }\n  intro Hnth; rewrite nth_error_nth with (d := d) in Hnth by (rewrite <- nth_error_Some, Hnth; discriminate).\n  simpl in *; inv Hnth.\n  rewrite nth_Znth, Z2Nat.id; tauto.\nQed.\n\n(* We want to be able to remove irrelevant operations from a history, leading to a slightly weaker\n   correspondence between history and list of operations. *)\nInductive hist_list' : hist_part -> list hist_el -> Prop :=\n| hist_list'_nil : hist_list' [] []\n| hist_list'_snoc : forall h l t e h1 h2 (He : h = h1 ++ (t, e) :: h2)\n    (Hlast : newer (h1 ++ h2) t) (Hrest : hist_list' (h1 ++ h2) l),\n    hist_list' h (l ++ [e]).\nHint Resolve hist_list'_nil.\n\nLemma hist_list'_in : forall h l (Hl : hist_list' h l) e, (exists t, In (t, e) h) <-> In e l.\nProof.\n  induction 1.\n  - split; [intros (? & ?)|]; contradiction.\n  - intro; subst; split.\n    + intros (? & Hin); rewrite in_app in *.\n      destruct Hin as [? | [Heq | ?]]; try solve [left; rewrite <- IHHl; eexists; rewrite in_app; eauto].\n      inv Heq; simpl; auto.\n    + rewrite in_app; intros [Hin | [Heq | ?]]; [| inv Heq | contradiction].\n      * rewrite <- IHHl in Hin; destruct Hin as (? & ?).\n        eexists; rewrite in_app in *; simpl; destruct H; eauto.\n      * eexists; rewrite in_app; simpl; eauto.\nQed.\n\nLemma hist_list_weak : forall l h (Hl : hist_list h l), hist_list' h l.\nProof.\n  induction l using rev_ind; intros.\n  - apply hist_list_nil_inv2 in Hl; subst; auto.\n  - pose proof (hist_list_NoDup _ _ Hl) as HNoDup.\n    destruct Hl as (Hd & Hl).\n    destruct (Hl (length l) x) as (_ & H); exploit H.\n    { rewrite nth_error_app2, minus_diag by omega; auto. }\n    intro; exploit in_split; eauto; intros (h1 & h2 & ?).\n    subst; rewrite map_app in HNoDup; simpl in HNoDup; apply NoDup_remove in HNoDup.\n    rewrite <- map_app in HNoDup.\n    assert (hist_list (h1 ++ h2) l) as Hl'.\n    { split.\n      { apply NoDup_remove in Hd; tauto. }\n      intros t e; specialize (Hl t e).\n      split; intro Hin.\n      + destruct Hl as (Hl & _); exploit Hl.\n        { rewrite in_app in *; simpl; tauto. }\n        intro Hnth; assert (t < length (l ++ [x]))%nat.\n        { rewrite <- nth_error_Some, Hnth; discriminate. }\n        rewrite app_length in *; simpl in *.\n        rewrite nth_error_app1 in Hnth; auto.\n        destruct (eq_dec t (length l)); [|omega].\n        destruct HNoDup as (? & HNoDup); contradiction HNoDup.\n        rewrite in_map_iff; do 2 eexists; eauto; auto.\n      + assert (t < length l)%nat.\n        { rewrite <- nth_error_Some, Hin; discriminate. }\n        destruct Hl as (_ & Hl); exploit Hl.\n        { rewrite nth_error_app1; auto. }\n        rewrite !in_app; intros [? | [Heq | ?]]; auto; inv Heq; omega. }\n    econstructor; eauto.\n    subst; unfold newer; rewrite Forall_forall; intros (t, e) Hin.\n    rewrite <- nth_error_Some.\n    destruct Hl' as (? & Hl').\n    destruct (Hl' t e) as (Hnth & _); simpl; rewrite Hnth by auto; discriminate.\nQed.\n\nLemma hist_list'_NoDup : forall h l, hist_list' h l -> NoDup (map fst h).\nProof.\n  induction 1.\n  - constructor.\n  - subst; rewrite map_app in *; simpl.\n    apply NoDup_add; auto.\n    rewrite <- map_app, in_map_iff; intros ((?, ?) & ? & ?); subst.\n    unfold newer in Hlast; rewrite Forall_forall in Hlast.\n    exploit Hlast; eauto; omega.\nQed.\n\nLemma hist_list'_perm : forall h l, hist_list' h l -> Permutation.Permutation (map snd h) l.\nProof.\n  induction 1; auto; subst.\n  rewrite map_app; simpl.\n  symmetry; etransitivity; [apply Permutation.Permutation_app_comm|].\n  apply Permutation.Permutation_cons_app; symmetry.\n  rewrite map_app in *; auto.\nQed.\n\nCorollary hist_list_perm : forall h l, hist_list h l -> Permutation.Permutation (map snd h) l.\nProof.\n  intros; apply hist_list'_perm, hist_list_weak; auto.\nQed.\n\nLemma ghost_hist_init : exists g', joins (Some (Tsh, ([] : hist_part)), Some ([] : hist_part)) g'.\nProof.\n  exists (None, None), (Some (Tsh, []), Some []); simpl.\n  pose proof Share.nontrivial.\n  unfold completable; repeat split; auto.\n  exists None; simpl.\n  split; auto.\nQed.\n\nInductive add_events h : list hist_el -> hist_part -> Prop :=\n| add_events_nil : add_events h [] h\n| add_events_snoc : forall le h' t e (Hh' : add_events h le h') (Ht : newer h' t),\n    add_events h (le ++ [e]) (h' ++ [(t, e)]).\nHint Resolve add_events_nil.\n\nLemma add_events_1 : forall h t e (Ht : newer h t), add_events h [e] (h ++ [(t, e)]).\nProof.\n  intros; apply (add_events_snoc _ []); auto.\nQed.\n\nLemma add_events_trans : forall h le h' le' h'' (H1 : add_events h le h') (H2 : add_events h' le' h''),\n  add_events h (le ++ le') h''.\nProof.\n  induction 2.\n  - rewrite app_nil_r; auto.\n  - rewrite app_assoc; constructor; auto.\nQed.\n\nLemma add_events_add : forall h le h', add_events h le h' -> exists h2, h' = h ++ h2 /\\ map snd h2 = le.\nProof.\n  induction 1.\n  - eexists; rewrite app_nil_r; auto.\n  - destruct IHadd_events as (? & -> & ?).\n    rewrite <- app_assoc; do 2 eexists; eauto.\n    subst; rewrite map_app; auto.\nQed.\n\nCorollary add_events_snd : forall h le h', add_events h le h' -> map snd h' = map snd h ++ le.\nProof.\n  intros; apply add_events_add in H.\n  destruct H as (? & ? & ?); subst.\n  rewrite map_app; auto.\nQed.\n\nCorollary add_events_incl : forall h le h', add_events h le h' -> incl h h'.\nProof.\n  intros; apply add_events_add in H.\n  destruct H as (? & ? & ?); subst.\n  apply incl_appl, incl_refl.\nQed.\n\nCorollary add_events_newer : forall h le h' t, add_events h le h' -> newer h' t -> newer h t.\nProof.\n  intros; eapply Forall_incl, add_events_incl; eauto.\nQed.\n\nLemma add_events_in : forall h le h' e, add_events h le h' -> In e le -> exists t, newer h t /\\ In (t, e) h'.\nProof.\n  induction 1; [contradiction|].\n  rewrite in_app; intros [? | [? | ?]]; try contradiction.\n  - destruct IHadd_events as (? & ? & ?); auto.\n    do 2 eexists; [|rewrite in_app]; eauto.\n  - subst; do 2 eexists; [|rewrite in_app; simpl; eauto].\n    eapply add_events_newer; eauto.\nQed.\n\nLemma add_events_ordered : forall h le h', add_events h le h' -> ordered_hist h -> ordered_hist h'.\nProof.\n  induction 1; auto; intros.\n  apply ordered_snoc; auto.\nQed.\n\nLemma add_events_last : forall h le h', add_events h le h' -> le <> [] -> snd (last h' (O, d)) = last le d.\nProof.\n  intros; apply add_events_add in H.\n  destruct H as (? & ? & ?); subst.\n  rewrite last_app.\n  setoid_rewrite last_map at 2; auto.\n  { intro; subst; contradiction. }\nQed.\n\nLemma add_events_NoDup : forall h le h', add_events h le h' -> NoDup (map fst h) -> NoDup (map fst h').\nProof.\n  induction 1; auto; intros.\n  rewrite map_app, NoDup_app_iff.\n  split; auto.\n  split; [repeat constructor; simpl; auto|].\n  simpl; intros ? Hin [? | ?]; [subst | contradiction].\n  unfold newer in Ht.\n  rewrite in_map_iff in Hin; destruct Hin as (? & ? & Hin); subst.\n  rewrite Forall_forall in Ht; specialize (Ht _ Hin); omega.\nQed.\n\nEnd GHist.\n\nSection AEHist.\n\n(* These histories should be usable for any atomically accessed location. *)\nInductive AE_hist_el := AE (r : val) (w : val).\n\nFixpoint apply_hist a h :=\n  match h with\n  | [] => Some a\n  | AE r w :: h' => if eq_dec r a then apply_hist w h' else None\n  end.\n\nArguments eq_dec _ _ _ _ : simpl never.\n\nLemma apply_hist_app : forall h1 i h2, apply_hist i (h1 ++ h2) =\n  match apply_hist i h1 with Some v => apply_hist v h2 | None => None end.\nProof.\n  induction h1; auto; simpl; intros.\n  destruct a.\n  destruct (eq_dec r i); auto.\nQed.\n\nEnd AEHist.\n\nNotation AE_hist := (list (nat * AE_hist_el)).\n\nEnd Ghost.\n\nHint Resolve disjoint_nil hist_incl_nil hist_list_nil ordered_nil hist_list'_nil add_events_nil.\nHint Resolve ghost_var_precise ghost_var_precise'.\nHint Resolve ghost_var_init master_init ghost_map_init ghost_hist_init : init.\n\nLtac view_shift_intro a := repeat rewrite ?exp_sepcon1, ?exp_sepcon2, ?sepcon_andp_prop, ?sepcon_andp_prop';\n  repeat match goal with\n    | |-view_shift (exp _) _ => apply view_shift_exists; intro a\n    | |-view_shift (!!_ && _) _ => apply view_shift_prop; fancy_intros false\n  end.\n\nLtac view_shift_intros := repeat rewrite ?exp_sepcon1, ?exp_sepcon2, ?sepcon_andp_prop, ?sepcon_andp_prop';\n  repeat match goal with\n    | |-view_shift (!!_ && _) _ => apply view_shift_prop; fancy_intros false\n  end.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/progs/ghost.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22168374045063394}}
{"text": "Require Import Events.\nRequire Import Memory.\nRequire Import Coqlib.\nRequire Import compcert.common.Values.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import AST.\n\nRequire Import Globalenvs.\n\nRequire Import Axioms.\n\nRequire Import sepcomp.mem_lemmas. (*needed for definition of mem_forward etc*)\nRequire Import sepcomp.core_semantics.\nRequire Import sepcomp.effect_semantics.\nRequire Import sepcomp.StructuredInjections.\nRequire Import sepcomp.effect_simulations.\n\nGoal forall mu Etgt Esrc m2 m2' (WD: SM_wd mu) m1\n            (TgtHyp: forall b ofs, Etgt b ofs = true ->\n                       (Mem.valid_block m2 b /\\\n                         (locBlocksTgt mu b = false ->\n                           exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                           Esrc b1 (ofs-delta1) = true /\\ Mem.perm m1 b1 (ofs-delta1) Max Nonempty)))\n            (Unch2: Mem.unchanged_on (fun b z => Etgt b z = false) m2 m2')\n            (*(SrcHyp: forall b ofs, Esrc b ofs = true -> vis mu b = true)*)\n            nu (WDnu: SM_wd nu)\n         (X1: forall b, locBlocksTgt nu b = true -> locBlocksTgt mu b = false)\n         (X2: forall b1 b2 d, foreign_of mu b1 = Some(b2, d) ->\n                              locBlocksSrc nu b1 || locBlocksTgt nu b2 = true ->\n                              pub_of nu b1 = Some(b2,d)),\n   Mem.unchanged_on (fun b2 z => locBlocksTgt nu b2 = true /\\\n                      forall b1 d, (as_inj nu) b1 = Some (b2,d) ->\n                                 loc_out_of_bounds m1 b1 (z-d)) m2 m2'.\nProof. intros.\n  eapply mem_unchanged_on_sub; try eassumption; clear Unch2.\n  unfold loc_out_of_bounds; simpl; intros. rename b into b2.\n  case_eq (Etgt b2 ofs); intros; trivial.\n  destruct (TgtHyp _ _ H0) as [VB2 F]; clear TgtHyp.\n  destruct H.\n  specialize (X1 _ H).\n  destruct (F X1) as [b1 [d1 [Frg [ES P]]]]; clear F.\n  destruct (foreign_DomRng _ WD _ _ _ Frg) as [AA [BB [CC [DD [EE [FF [GG HH]]]]]]].\n  clear DD.\n  (*destruct (SrcHyp _ _ ES); clear SrcHyp.\n    rewrite H2 in *. inv CC.\n  clear H2.*)\n  specialize (X2 _ _ _ Frg). rewrite H in X2.\n  rewrite orb_true_r in X2. specialize (X2 (eq_refl _)).\n  destruct (H1 b1 d1).\n    apply pub_in_all in X2; trivial.\n  assumption.\nQed.\n\n\n\nLemma FreeEffect_validblock: forall m lo hi sp b ofs\n        (EFF: FreeEffect m lo hi sp b ofs = true),\n      Mem.valid_block m b.\nProof. intros.\n  unfold FreeEffect in EFF.\n  destruct (valid_block_dec m b); trivial; inv EFF.\nQed.\n\nLemma FreelistEffect_validblock: forall l m b ofs\n        (EFF: FreelistEffect m l b ofs = true),\n      Mem.valid_block m b.\nProof. intros l.\n  induction l; unfold FreelistEffect; simpl; intros.\n     unfold EmptyEffect in EFF. inv EFF.\n  destruct a as [[bb lo] hi].\n  apply orb_true_iff in EFF.\n  destruct EFF.\n  apply IHl in H. assumption.\n  eapply FreeEffect_validblock; eassumption.\nQed.\n\nLemma StoreEffectD: forall vaddr v b ofs\n      (STE: StoreEffect vaddr v b ofs = true),\n      exists i, vaddr = Vptr b i /\\\n        (Int.unsigned i) <= ofs < (Int.unsigned i + Z.of_nat (length v)).\nProof. intros.\n  unfold StoreEffect in STE. destruct vaddr; inv STE.\n  destruct (eq_block b0 b); inv H0.\n  exists i.\n  destruct (zle (Int.unsigned i) ofs); inv H1.\n  destruct (zlt ofs (Int.unsigned i + Z.of_nat (length v))); inv H0.\n  intuition.\nQed.\n\nLemma StoreEffect_PropagateLeft: forall chunk m vaddr v m'\n          (ST: Mem.storev chunk m vaddr v = Some m')\n          mu m2 (WD: SM_wd mu) (INJ : Mem.inject (as_inj mu) m m2)\n          vaddr'\n          (VINJ : val_inject (restrict (as_inj mu) (vis mu)) vaddr vaddr')\n          v' m2' (ST2: Mem.storev chunk m2 vaddr' v' = Some m2')\n          b2 ofs\n          (EFF : StoreEffect vaddr' (encode_val chunk v') b2 ofs = true)\n          (LBT2: locBlocksTgt mu b2 = false),\n      exists b1 delta, foreign_of mu b1 = Some (b2, delta) /\\\n          StoreEffect vaddr (encode_val chunk v) b1 (ofs - delta) = true /\\\n          Mem.perm m b1 (ofs - delta) Max Nonempty.\nProof. intros.\n      apply StoreEffectD in EFF. destruct EFF as [i [VADDR' Hoff]]. subst.\n        simpl in ST2. inv VINJ. Focus 2. inv ST.\n      destruct (restrictD_Some _ _ _ _ _ H2); clear H2.\n      exists b1, delta.\n      split. destruct (joinD_Some _ _ _ _ _ H) as [EXT | [EXT LOC]]; clear H.\n             unfold vis in H0.\n             destruct (extern_DomRng' _ WD _ _ _ EXT) as [_ [_ [? _]]].\n             rewrite H in H0. simpl in H0.\n             destruct (frgnSrc _ WD _ H0) as [bb [dd [FF FT]]].\n             rewrite (foreign_in_extern _ _ _ _ FF) in EXT. inv EXT.\n             trivial.\n          destruct (local_DomRng _ WD _ _ _ LOC).\n            congruence.\n      rewrite encode_val_length in Hoff. rewrite <- size_chunk_conv in Hoff.\n      assert (Arith: Int.unsigned ofs1 <= ofs - delta < Int.unsigned ofs1 + size_chunk chunk).\n         assert (DD: delta >= 0 /\\ 0 <= Int.unsigned ofs1 + delta <= Int.max_unsigned).\n                 eapply INJ. apply H. left.\n                 apply Mem.store_valid_access_3 in ST.\n                 eapply Mem.perm_implies. eapply Mem.valid_access_perm. eassumption. constructor.\n         destruct DD as [DD1 DD2].\n         specialize (Int.unsigned_range ofs1); intros I.\n         assert (URdelta: Int.unsigned (Int.repr delta) = delta).\n            apply Int.unsigned_repr. split. omega. omega.\n\n         rewrite Int.add_unsigned in Hoff. rewrite URdelta in Hoff.\n         rewrite (Int.unsigned_repr _ DD2) in Hoff. omega.\n\n      split. unfold StoreEffect.\n        destruct (eq_block b1 b1); try congruence. simpl; clear e.\n        destruct Arith. rewrite encode_val_length . rewrite <- size_chunk_conv.\n        destruct (zle (Int.unsigned ofs1) (ofs - delta)); try omega.\n          destruct (zlt (ofs - delta) (Int.unsigned ofs1 + size_chunk chunk)); try omega. trivial.\n      apply Mem.store_valid_access_3 in ST.\n            eapply Mem.perm_implies.\n            eapply Mem.perm_max. eapply ST. eassumption. constructor.\nQed.\n\nLemma free_free_inject : forall f m1 m1' m2 b1 lo hi b2 d m2'\n       (INJ: Mem.inject f m1 m2)\n       (FREE1: Mem.free m1 b1 lo hi = Some m1')\n       (FREE2: Mem.free m2 b2 (lo+d) (hi+d) = Some m2')\n       (B: f b1 = Some(b2,d)),\n      Mem.inject f m1' m2'.\nProof. intros.\n       eapply Mem.free_inject with (l:=(b1,lo,hi)::nil); try eassumption.\n       simpl. rewrite FREE1. trivial.\n       intros.\n          destruct (eq_block b0 b1); subst. rewrite H in B. inv B.\n            exists lo, hi. intuition.\n          assert (P1: Mem.perm m1 b0 ofs Max Nonempty).\n            eapply Mem.perm_implies. eapply Mem.perm_max; eassumption. apply perm_any_N.\n          assert (PM: Mem.perm m1 b1 (ofs - d + delta) Max Nonempty).\n            eapply Mem.perm_implies. eapply Mem.perm_max.\n              eapply (Mem.free_range_perm _ _ _ _ _ FREE1). omega.\n              constructor.\n          exfalso.\n          destruct (Mem.mi_no_overlap _ _ _ INJ b0 _ _ _ _ _ _ _ n\n               H B P1 PM) as [X | X]; apply X; trivial. omega.\nQed.\n\nLemma free_free_inject_same_block : forall f m1 m1' m2 b lo hi m2'\n       (INJ: Mem.inject f m1 m2)\n       (FREE1: Mem.free m1 b lo hi = Some m1')\n       (FREE2: Mem.free m2 b lo hi = Some m2')\n       (B: f b = Some(b,0)),\n      Mem.inject f m1' m2'.\nProof. intros. eapply free_free_inject; try eassumption.\n   repeat rewrite Zplus_0_r. trivial.\nQed.\n\nInductive match_freelists (j:meminj): list (block * Z * Z) -> list (block * Z * Z) -> Prop :=\n  match_freelists_nil: match_freelists j nil nil\n| match_freelists_cons: forall b1 lo1 hi1 t1 b2 lo2 hi2 t2 delta,\n        j b1 = Some (b2,delta) ->\n        lo2 = lo1+delta -> hi2 = hi1+delta ->\n        match_freelists j t1 t2 ->\n        match_freelists j ((b1,lo1,hi1)::t1) ((b2,lo2,hi2)::t2).\n\nLemma freelist_freelist_inject : forall f l1 l2\n       (F: match_freelists f l1 l2)  m1 m1' m2 m2'\n       (INJ: Mem.inject f m1 m2)\n       (FREE1: Mem.free_list m1 l1 = Some m1')\n       (FREE2: Mem.free_list m2 l2 = Some m2'),\n      Mem.inject f m1' m2'.\nProof. intros f l1 l2 F.\n  induction F; simpl; intros.\n    inv FREE1; inv FREE2. assumption.\n  remember (Mem.free m1 b1 lo1 hi1) as F1.\n  destruct F1; inv FREE1; apply eq_sym in HeqF1.\n  remember (Mem.free m2 b2 (lo1 + delta) (hi1 + delta)) as F2.\n  destruct F2; inv FREE2; apply eq_sym in HeqF2.\n  assert (Mem.inject f m m0).\n    eapply free_free_inject; eassumption.\n  eapply (IHF _ _ _ _ H0); try eassumption.\nQed.\n\nLemma FreeEffect_PropagateLeft: forall\n   m sp lo hi m'\n   (FREE : Mem.free m sp lo hi = Some m')\n   mu m2 (SMV : sm_valid mu m m2)\n   (WD: SM_wd mu) spb'\n   (AI: as_inj mu sp = Some (spb', 0))\n   (VIS : vis mu sp = true) b2 ofs\n   (EFF : FreeEffect m2 lo hi spb' b2 ofs = true)\n   (LB: locBlocksTgt mu b2 = false),\n  exists b1 delta,\n    foreign_of mu b1 = Some (b2, delta) /\\\n    FreeEffect m lo hi sp b1 (ofs - delta) = true /\\\n    Mem.perm m b1 (ofs - delta) Max Nonempty.\nProof. intros.\n      unfold FreeEffect in EFF.\n        destruct (valid_block_dec m2 b2); inv EFF.\n        destruct (eq_block b2 spb'); simpl in *; inv H0.\n        exists sp, 0. rewrite Zminus_0_r.\n        split. unfold vis in VIS.\n               destruct (joinD_Some _ _ _ _ _ AI) as [EXT | [NEXT LOC]]; clear H1.\n                 assert (LSP: locBlocksSrc mu sp = false). eapply (extern_DomRng' _ WD _ _ _ EXT).\n                 rewrite LSP in *. simpl in VIS.\n                 destruct (frgnSrc _ WD _ VIS) as [bb2 [dd [F1 F2]]].\n                   rewrite (foreign_in_extern _ _ _ _ F1) in EXT. inv EXT. apply F1.\n               destruct (local_DomRng _ WD _ _ _ LOC); congruence.\n        split. unfold FreeEffect.\n               destruct (valid_block_dec m sp).\n                 destruct (eq_block sp sp); trivial. elim n; trivial.\n               elim n; clear n. apply SMV. eapply as_inj_DomRng; eassumption.\n        eapply Mem.perm_implies. eapply Mem.perm_max.\n           eapply (Mem.free_range_perm _ _ _ _ _ FREE).\n              destruct (zle lo ofs); simpl in H1; try discriminate.\n              destruct (zlt ofs hi); try discriminate. split; trivial.\n             constructor.\nQed.\n\n(***** Some results on meminj_preserves_globals and variants of\n        LSR-clause match_genv  ************************************)\nLemma match_genv_meminj_preserves_globals_extern_implies_foreign:\n      forall {F V} (ge: Genv.t F V) mu (WDmu : SM_wd mu)\n             (PG: meminj_preserves_globals ge (extern_of mu) /\\\n                 (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true)),\n      meminj_preserves_globals ge (foreign_of mu).\nProof. intros.\ndestruct PG as [PG GF].\napply meminj_preserves_genv2blocks in PG.\ndestruct PG as [PGa [PGb PGc]].\napply meminj_preserves_genv2blocks.\n  split; intros.\n    specialize (PGa _ H).\n    destruct (frgnSrc _ WDmu b) as [b2 [d [Frg1 FT2]]].\n      apply GF. unfold isGlobalBlock.\n      apply genv2blocksBool_char1 in H. rewrite H. intuition.\n    rewrite (foreign_in_extern _ _ _ _ Frg1) in PGa.\n      inv PGa. assumption.\n  split; intros.\n    specialize (PGb _ H).\n    destruct (frgnSrc _ WDmu b) as [b2 [d [Frg1 FT2]]].\n      apply GF. unfold isGlobalBlock.\n      apply genv2blocksBool_char2 in H. rewrite H. intuition.\n    rewrite (foreign_in_extern _ _ _ _ Frg1) in PGb.\n      inv PGb. assumption.\n  apply foreign_in_extern in H0. apply (PGc _ _ _ H H0).\nQed.\n\nLemma match_genv_meminj_preserves_extern_iff_all:\n      forall {F V} (ge: Genv.t F V) mu (WDmu : SM_wd mu)\n             (GF: forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true),\n      meminj_preserves_globals ge (as_inj mu) <->\n      meminj_preserves_globals ge (extern_of mu).\nProof. intros.\nsplit; intros PG;\n       apply meminj_preserves_genv2blocks;\n       apply meminj_preserves_genv2blocks in PG;\n       destruct PG as [PGa [PGb PGc]].\n  split; intros.\n    destruct (frgnSrc _ WDmu b) as [b2 [dd [Frg1 FT2]]].\n      apply GF. unfold isGlobalBlock.\n      apply genv2blocksBool_char1 in H. intuition.\n    specialize (PGa _ H).\n    rewrite (foreign_in_all _ _ _ _ Frg1) in PGa. inv PGa.\n    apply foreign_in_extern; eassumption.\n  split; intros.\n    destruct (frgnSrc _ WDmu b) as [b2 [dd [Frg1 FT2]]].\n      apply GF. unfold isGlobalBlock.\n      apply genv2blocksBool_char2 in H. intuition.\n    specialize (PGb _ H).\n    rewrite (foreign_in_all _ _ _ _ Frg1) in PGb. inv PGb.\n    apply foreign_in_extern; eassumption.\n  apply extern_in_all in H0. eauto.\nsplit; intros.\n  apply extern_in_all. eauto.\nsplit; intros.\n  apply extern_in_all. eauto.\nspecialize (PGb _ H).\n  destruct (joinD_Some _ _ _ _ _ H0) as [EXT | [EXT LOC]]; clear H0.\n    eauto.\n  destruct (extern_DomRng _ WDmu _ _ _ PGb) as [? ?].\n    destruct (local_DomRng _ WDmu _ _ _ LOC).\n    destruct (disjoint_extern_local_Tgt _ WDmu b2); congruence.\nQed.\n\nLemma meminj_preserves_globals_initSM_all: forall {F1 V1} (ge: Genv.t F1 V1) j\n                  (PG : meminj_preserves_globals ge j) DomS DomT X Y,\n      meminj_preserves_globals ge (as_inj (initial_SM DomS DomT X Y j)).\nProof. intros.\n    apply meminj_preserves_genv2blocks.\n    apply meminj_preserves_genv2blocks in PG.\n    destruct PG as [PGa [PGb PGc]].\n    unfold initial_SM; split; intros; unfold as_inj; simpl in *.\n       apply joinI; left. eauto.\n    split; intros; simpl in *.\n       apply joinI; left. eauto.\n    destruct (joinD_Some _ _ _ _ _ H0) as [HH | [_ HH]]; clear H0.\n       eauto. inv HH.\nQed.\n\n(*version of Lemma meminj_preserves_globals_initSM, for a\n  definition of clause match_genv that uses foreign_of*)\nLemma meminj_preserves_globals_initSM_frgn: forall {F1 V1} (ge: Genv.t F1 V1) j\n                  (PG : meminj_preserves_globals ge j) DomS DomT m R Y\n                  (HR: forall b, isGlobalBlock ge b = true -> R b = true),\n      meminj_preserves_globals ge (foreign_of (initial_SM DomS DomT (REACH m R) Y j)).\nProof. intros.\n    apply meminj_preserves_genv2blocks.\n    apply meminj_preserves_genv2blocks in PG.\n    destruct PG as [PGa [PGb PGc]].\n    unfold initial_SM; split; intros; simpl in *.\n       specialize (PGa _ H). rewrite PGa.\n       assert (REACH m R b = true).\n         apply REACH_nil. apply HR.\n         unfold isGlobalBlock, genv2blocksBool; simpl.\n         destruct H as [id ID].\n         apply Genv.find_invert_symbol in ID. rewrite ID. reflexivity.\n       rewrite H0; trivial.\n    split; intros; simpl in *.\n       specialize (PGb _ H). rewrite PGb.\n       assert (REACH m R b = true).\n         apply REACH_nil. apply HR.\n         unfold isGlobalBlock, genv2blocksBool; simpl.\n         destruct H as [id ID]. rewrite ID. intuition.\n       rewrite H0; trivial.\n     apply (PGc _ _ delta H).\n       remember (REACH m R b1) as d.\n       destruct d; congruence.\nQed.\n\nLemma core_initial_wd_as_inj : forall {F1 V1 F2 V2} (ge1: Genv.t F1 V1) (ge2: Genv.t F2 V2)\n                               vals1 m1 j vals2 m2 DomS DomT\n          (MInj: Mem.inject j m1 m2)\n          (VInj: Forall2 (val_inject j) vals1 vals2)\n          (HypJ: forall b1 b2 d, j b1 = Some (b2, d) -> DomS b1 = true /\\ DomT b2 = true)\n          (R: forall b, REACH m2 (fun b' => isGlobalBlock ge2 b' || getBlocks vals2 b') b = true ->\n                        DomT b = true)\n          (PG: meminj_preserves_globals ge1 j)\n          (GenvsDomEQ: genvs_domain_eq ge1 ge2)\n          (HS: forall b, DomS b = true -> Mem.valid_block m1 b)\n          (HT: forall b, DomT b = true -> Mem.valid_block m2 b)\n          mu (Hmu: mu = initial_SM DomS DomT\n                         (REACH m1 (fun b => isGlobalBlock ge1 b || getBlocks vals1 b))\n                         (REACH m2 (fun b => isGlobalBlock ge2 b || getBlocks vals2 b)) j),\n       (forall b, REACH m1 (fun b' => isGlobalBlock ge1 b' || getBlocks vals1 b') b = true ->\n                  DomS b = true) /\\\n       SM_wd mu /\\ sm_valid mu m1 m2 /\\\n       meminj_preserves_globals ge1 (as_inj mu) /\\\n       (forall b, isGlobalBlock ge1 b = true -> frgnBlocksSrc mu b = true).\nProof. intros.\n  destruct (core_initial_wd _ _ _ _ _ _ _ _ _ MInj\n             VInj HypJ R PG GenvsDomEQ HS HT _ Hmu)\n    as [RDom [WDmu [SMVmu [PGext GF]]]].\n  intuition.\n  rewrite match_genv_meminj_preserves_extern_iff_all; assumption.\nQed.\n\nLemma intern_incr_meminj_preserves_globals_frgn:\n      forall {F V} (ge: Genv.t F V) mu\n             (PG: meminj_preserves_globals ge (foreign_of mu))\n             mu' (Inc: intern_incr mu mu'),\n      meminj_preserves_globals ge (foreign_of mu').\nProof. intros.\n  rewrite (intern_incr_foreign _ _ Inc) in PG. trivial.\nQed.\n\nLemma intern_incr_meminj_preserves_globals_as_inj:\n      forall {F V} (ge: Genv.t F V) mu (WDmu: SM_wd mu)\n             (PG: meminj_preserves_globals ge (as_inj mu) /\\\n                  (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true))\n             mu' (WDmu': SM_wd mu') (Inc: intern_incr mu mu'),\n      meminj_preserves_globals ge (as_inj mu') /\\\n      (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu' b = true).\nProof. intros.\n  rewrite match_genv_meminj_preserves_extern_iff_all in PG.\n    destruct (intern_incr_meminj_preserves_globals _ _ PG _ Inc).\n    rewrite match_genv_meminj_preserves_extern_iff_all; eauto.\n  assumption. apply PG.\nQed.\n\nLemma replace_externs_meminj_preserves_globals_as_inj:\n      forall {F V} (ge: Genv.t F V) nu (WDnu: SM_wd nu)\n          (PG: meminj_preserves_globals ge (as_inj nu) /\\\n               (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc nu b = true))\n          mu  fSrc fTgt (Hyp: mu = replace_externs nu fSrc fTgt)\n          (WDmu: SM_wd mu)\n          (FRG: forall b, frgnBlocksSrc nu b = true -> fSrc b = true),\n      meminj_preserves_globals ge (as_inj mu) /\\\n      (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true).\nProof. intros.\n  rewrite match_genv_meminj_preserves_extern_iff_all in PG.\n    destruct (replace_externs_meminj_preserves_globals _ _ PG _ _ _ Hyp FRG).\n    rewrite match_genv_meminj_preserves_extern_iff_all; eauto.\n  assumption. apply PG.\nQed.\n\nLemma after_external_meminj_preserves_globals_as_inj:\n      forall {F V} (ge: Genv.t F V) mu (WDmu : SM_wd mu)\n             (PG: meminj_preserves_globals ge (as_inj mu) /\\\n                 (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true))\n             nu pubSrc' pubTgt' vals1 m1\n             (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                (REACH m1 (exportedSrc mu vals1) b))\n\n\n             (Hnu: nu = replace_locals mu pubSrc' pubTgt')\n             nu' (WDnu' : SM_wd nu') (INC: extern_incr nu nu')\n             m2 (SMV: sm_valid mu m1 m2) (SEP: sm_inject_separated nu nu' m1 m2)\n             frgnSrc' ret1 m1'\n             (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n             frgnTgt' ret2 m2'\n             (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n             mu' (WDmu': SM_wd mu') (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt'),\n      meminj_preserves_globals ge (as_inj mu') /\\\n     (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu' b = true).\nProof. intros.\n  rewrite match_genv_meminj_preserves_extern_iff_all in PG.\n    destruct (after_external_meminj_preserves_globals\n          _ _ WDmu PG _ _ _ _ _ pubSrcHyp Hnu _ WDnu' INC _ SMV\n         SEP _ _ _ frgnSrcHyp _ _ _ frgnTgtHyp _ Mu'Hyp).\n    rewrite match_genv_meminj_preserves_extern_iff_all; eauto.\n  assumption. apply PG.\nQed.\n\nLemma match_genv_meminj_preserves_globals_foreign_and_extern:\n      forall {F V} (ge: Genv.t F V) mu (WDmu : SM_wd mu)\n             (PG: meminj_preserves_globals ge (as_inj mu) /\\\n                 (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true)),\n      meminj_preserves_globals ge (foreign_of mu) /\\\n      meminj_preserves_globals ge (extern_of mu).\nProof. intros.\n  rewrite match_genv_meminj_preserves_extern_iff_all in PG; intuition.\n  apply match_genv_meminj_preserves_globals_extern_implies_foreign; intuition.\nQed.\n\n(***********************************************************************)\n\nGoal forall mu (WD: SM_wd mu) m1 m2 m2'\n(U: Mem.unchanged_on (local_out_of_reach mu m1) m2 m2'),\nMem.unchanged_on (fun b ofs => pubBlocksTgt mu b = true /\\\n                  loc_out_of_reach (pub_of mu) m1 b ofs) m2 m2'.\nProof.\nintros.\neapply mem_unchanged_on_sub; try eassumption.\nintros. destruct H.\nunfold local_out_of_reach.\nsplit. apply (pubBlocksLocalTgt _ WD _ H).\nintros.\nremember (pubBlocksSrc mu b0) as d.\ndestruct d; try (right; reflexivity).\nleft.\neapply H0. unfold pub_of.\ndestruct mu; simpl in *. rewrite <- Heqd. assumption.\nQed.\n\nGoal forall mu (WD: SM_wd mu) m1 m2 m2'\n(U: Mem.unchanged_on (local_out_of_reach mu m1) m2 m2'),\nMem.unchanged_on (fun b ofs => locBlocksTgt mu b = true /\\\n                    pubBlocksTgt mu b = false) m2 m2'.\nintros.\neapply mem_unchanged_on_sub; try eassumption.\nintros. unfold local_out_of_reach. destruct H.\nsplit; trivial. intros.\nremember (pubBlocksSrc mu b0) as d.\ndestruct d; try (right; reflexivity).\napply eq_sym in Heqd.\ndestruct (pubSrc _ WD _ Heqd) as [b2 [dd [PUB TGT]]].\napply pub_in_local in PUB. rewrite PUB in H1. inv H1.\nrewrite TGT in H0. discriminate.\nQed.\n\nGoal forall mu m1 m2 m2' (WD:SM_wd mu)\n  (U1: Mem.unchanged_on (fun b ofs => locBlocksTgt mu b = true /\\\n                    pubBlocksTgt mu b = false) m2 m2')\n  (U2: Mem.unchanged_on (fun b ofs => pubBlocksTgt mu b = true /\\\n                  loc_out_of_reach (pub_of mu) m1 b ofs) m2 m2'),\nMem.unchanged_on (local_out_of_reach mu m1) m2 m2'.\nintros.\ndestruct U1 as [P1 C1]. destruct U2 as [P2 C2].\nsplit; intros.\n  clear C1 C2.\n  specialize (P1 b ofs k p). specialize (P2 b ofs k p).\n  remember (locBlocksTgt mu b) as d.\n  destruct d; apply eq_sym in Heqd; simpl in *.\n    remember (pubBlocksTgt mu b) as q.\n    destruct q; apply eq_sym in Heqq; simpl in *.\n      clear P1.\n      apply P2; trivial. split; trivial.\n      intros b0; intros.\n      destruct H. destruct (H2 b0 delta).\n        apply pub_in_local; trivial.\n        assumption.\n        unfold pub_of in H1. destruct mu. simpl in *.  rewrite H3 in H1.  discriminate.\n    apply P1; trivial. split; trivial.\n  clear P1.\n  remember (pubBlocksTgt mu b) as q.\n    destruct q; apply eq_sym in Heqq; simpl in *.\n      assert (locBlocksTgt mu b = true). eapply (pubBlocksLocalTgt _ WD). eassumption.\n      rewrite H1 in Heqd. discriminate.\n  destruct H. rewrite H in Heqd. discriminate.\ndestruct H.\n  clear P1 P2.\n  specialize (C1 b ofs). specialize (C2 b ofs).\n  rewrite H in *.\n  remember (pubBlocksTgt mu b) as d.\n  destruct d; apply eq_sym in Heqd.\n    clear C1. apply C2; trivial; clear C2.\n    split; trivial. intros b1; intros.\n     destruct (pub_locBlocks _ WD _ _ _ H2).\n     apply pub_in_local in H2.\n     destruct (H1 _ _ H2). assumption. rewrite H5 in *. inv H3.\n  clear C2. apply C1; eauto.\nQed.\n\nLemma eff_atexternal_check:\n      forall {F1 V1 C1 F2 V2 C2:Type} (ge1: Genv.t F1 V1) (ge2: Genv.t F2 V2)\n         mu (WDmu: SM_wd mu)\n         (GenvsDomEq: genvs_domain_eq ge1 ge2)\n         m1 m2 (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n         vals1 vals2 (ValInjMu: Forall2 (val_inject (as_inj mu)) vals1 vals2)\n         (MatchGenv: meminj_preserves_globals ge1 (extern_of mu) /\\\n                        (forall b, isGlobalBlock ge1 b = true -> frgnBlocksSrc mu b = true)),\n      (forall b, isGlobalBlock ge1 b = true -> REACH m1 (exportedSrc mu vals1) b = true) /\\\n      (forall b, isGlobalBlock ge2 b = true -> REACH m2 (exportedTgt mu vals2) b = true).\nProof. intros.\ndestruct MatchGenv as [PG GF].\nassert (forall b,\n       isGlobalBlock ge1 b = true -> REACH m1 (exportedSrc mu vals1) b = true).\n  intros.\n  apply REACH_nil. unfold exportedSrc.\n  apply GF in H. rewrite (frgnSrc_shared _ WDmu _ H). intuition.\nsplit; trivial. intros.\n  rewrite <- (genvs_domain_eq_isGlobal _ _ GenvsDomEq) in *.\n  specialize (H _ H0).\n  destruct (REACH_as_inj_REACH _ WDmu _ _ _ _ MemInjMu ValInjMu _ H) as [b2 [d [A R]]].\n  specialize (meminj_preserves_globals_isGlobalBlock _ _ PG _ H0). intros.\n  rewrite (extern_in_all _ _ _ _ H1) in A. inv A.\n  trivial.\nQed.\n\nLemma eff_after_check1:\n      forall mu (WD: SM_wd mu) m1 m2 (SMValMu: sm_valid mu m1 m2)\n          (*selected standard assumptions:*)\n          (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n          vals1 vals2 (ValInjMu: Forall2 (val_inject (as_inj mu)) vals1 vals2)\n\n          pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n          pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n          nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n       SM_wd nu /\\ sm_valid nu m1 m2 /\\\n       Mem.inject (as_inj nu) m1 m2 /\\\n       Forall2 (val_inject (as_inj nu)) vals1 vals2.\nProof. intros. subst.\nsplit. eapply replace_locals_wd; trivial.\n      intros. apply andb_true_iff in H. destruct H as [locBSrc ReachSrc].\n        destruct (REACH_local_REACH _ WD _ _ _ _  MemInjMu ValInjMu _ ReachSrc locBSrc)\n            as [b2 [d [Loc ReachTgt]]]; clear ReachSrc.\n        exists b2, d; split; trivial.\n        destruct (local_DomRng _ WD _ _ _ Loc). rewrite H0, ReachTgt. trivial.\n      intros. apply andb_true_iff in H. apply H.\nsplit.\n  split; intros.\n    rewrite replace_locals_DOM in H.\n    eapply SMValMu; apply H.\n  rewrite replace_locals_RNG in H.\n    eapply SMValMu; apply H.\nrewrite replace_locals_as_inj. split; assumption.\nQed.\n\nLemma eff_after_check2:\n      forall nu' ret1 m1' m2' ret2\n         (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n         (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n         frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                  (andb (negb (locBlocksSrc nu' b))\n                                                        (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n         frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                  (andb (negb (locBlocksTgt nu' b))\n                                                        (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n         mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n         (WD: SM_wd nu') (SMValid: sm_valid nu' m1' m2'),\n\n      SM_wd mu' /\\ sm_valid mu' m1' m2'.\nProof. intros. subst.\nsplit.\neapply replace_externs_wd. assumption.\n  intros. do 2 rewrite andb_true_iff in H.\n          destruct H as [DomB1 [notMyB1 ReachB1]].\n          assert (VALS: Forall2 (val_inject (as_inj nu')) (ret1::nil) (ret2::nil)).\n            constructor. assumption. constructor.\n          apply negb_true_iff in notMyB1.\n          destruct (REACH_extern_REACH _ WD _ _ _ _ MemInjNu' VALS _\n                    ReachB1 notMyB1) as [b2 [d [EXT ReachB2]]].\n          exists b2, d; split; trivial.\n          do 2 rewrite andb_true_iff. rewrite negb_true_iff.\n          destruct (extern_DomRng _ WD _ _ _ EXT) as [? ?].\n          unfold DomTgt. intuition.\n          destruct (disjoint_extern_local_Tgt _ WD b2); congruence.\n  intros. do 2 rewrite andb_true_iff in H. rewrite negb_true_iff in H.\n          unfold DomTgt in H. destruct H as [? [? ?]].\n          rewrite H0 in H; simpl in H. assumption.\nsplit; intros.\n  rewrite replace_externs_DOM in H. apply SMValid. apply H.\n  rewrite replace_externs_RNG in H. apply SMValid. apply H.\nQed.\n\nLemma eff_after_check3:\n      forall nu' ret1 m1' m2' ret2\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt'),\n\n     Mem.inject (as_inj mu') m1' m2' /\\ val_inject (as_inj mu') ret1 ret2.\nProof. intros. subst. rewrite replace_externs_as_inj. split; assumption. Qed.\n\nLemma eff_after_check4:\n      forall mu pubSrc' pubTgt'\n             nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt')\n             nu' (INC: extern_incr nu nu')\n             mu' frgnSrc' frgnTgt'\n            (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n            (SMwdNu': SM_wd nu'),\n      inject_incr (as_inj mu) (as_inj mu').\nProof. intros. subst.\n  rewrite replace_externs_as_inj.\n  intros b; intros.\n    eapply extern_incr_as_inj. apply INC. assumption.\n    rewrite replace_locals_as_inj. apply H.\nQed.\n\nLemma eff_after_check5a:\n      forall mu pubSrc' pubTgt' nu\n             (NuHyp: nu = replace_locals mu pubSrc' pubTgt')\n             kappa m1 m2\n            (SEP: sm_inject_separated nu kappa m1 m2),\n      sm_inject_separated mu kappa m1 m2.\nProof. intros. subst.\ndestruct SEP as [SEPa [SEPb SEPc]].\nrewrite replace_locals_as_inj,\n        replace_locals_DomSrc,\n        replace_locals_DomTgt in *.\nsplit; intros; eauto.\nQed.\n\nLemma eff_after_check5b:\n      forall nu' mu' frgnSrc' frgnTgt'\n             (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n             kappa m1 m2 (SEP: sm_inject_separated kappa nu' m1 m2),\n      sm_inject_separated kappa mu' m1 m2.\nProof. intros. subst.\ndestruct SEP as [SEPa [SEPb SEPc]].\nsplit; intros.\n  rewrite replace_externs_as_inj in H0.\n  apply (SEPa _ _ _ H H0).\nsplit; intros.\n  rewrite replace_externs_DomSrc in *.\n  apply (SEPb _ H H0).\nrewrite replace_externs_DomTgt in *.\n  apply (SEPc _ H H0).\nQed.\n\nLemma eff_after_check5:\n      forall mu pubSrc' pubTgt' nu\n             (NuHyp: nu = replace_locals mu pubSrc' pubTgt')\n             nu' mu' frgnSrc' frgnTgt'\n             (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n             m1 m2 (SEP: sm_inject_separated nu nu' m1 m2),\n      sm_inject_separated mu mu' m1 m2.\nProof. intros.\neapply eff_after_check5b; try eassumption.\neapply eff_after_check5a; try eassumption.\nQed.\n\nLemma eff_after_check5_explicitProof:\n      forall mu pubSrc' pubTgt' nu\n             (NuHyp: nu = replace_locals mu pubSrc' pubTgt')\n             nu' mu' frgnSrc' frgnTgt'\n             (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n             m1 m2 (SEP: sm_inject_separated nu nu' m1 m2),\n      sm_inject_separated mu mu' m1 m2.\nProof. intros. subst.\ndestruct SEP as [SEPa [SEPb SEPc]].\nrewrite replace_locals_as_inj in *.\nrewrite replace_locals_DomSrc, replace_locals_DomTgt in *.\nsplit; intros.\n  rewrite replace_externs_as_inj in H0.\n  apply (SEPa _ _ _ H H0).\nsplit; intros.\n  rewrite replace_externs_DomSrc in *.\n  apply (SEPb _ H H0).\nrewrite replace_externs_DomTgt in *.\n  apply (SEPc _ H H0).\nQed.\n\n    (*One might consider variants that require Mem.inject j ma m2 on smaller\n        injections j than as_inj mu, omething like this:\n    core_halted : forall cd mu c1 m1 c2 m2 v1,\n      match_state cd mu c1 m1 c2 m2 ->\n      halted Sem1 c1 = Some v1 ->\n\n      exists v2,\n             Mem.inject (locvisible_of mu) m1 m2 /\\\n             val_inject (locvisible_of mu) v1 v2;\n\n     (-follows from halted_loc_check:-)\n      /\\\n      exists pubSrc' pubTgt' nu,\n        (pubSrc' = fun b => (locBlocksSrc mu b) &&\n                            (REACH m1 (exportedSrc mu (v1::nil)) b))\n        /\\\n        (pubTgt' = fun b => (locBlocksTgt mu b) &&\n                            (REACH m2 (exportedTgt mu (v2::nil)) b))\n        /\\\n        (nu = replace_locals mu pubSrc' pubTgt')\n         /\\\n        val_inject (shared_of nu) v1 v2 /\\\n        halted Sem2 c2 = Some v2 /\\\n        Mem.inject (shared_of nu) m1 m2; (*/\\ val_valid v2 m2*)\n     But this would mean to carry the invariant Mem.inject (locvisible_of mu) m1 m2\n         around, ie through corediagram, afterexternal etc (ie require match_state\n         to imply Mem.inject loc_visible ...\n       This maybe possible, but is maybe not required.\n    *)\n\nLemma halted_check_aux: forall mu m1 v1 b1 b2 delta (WD: SM_wd mu),\n      join (foreign_of mu)\n           (fun b =>\n              if locBlocksSrc mu b && REACH m1 (exportedSrc mu (v1 :: nil)) b\n              then local_of mu b\n              else None) b1 = Some (b2, delta) ->\n      as_inj mu b1= Some (b2, delta).\nProof. intros; apply joinI.\n  destruct (joinD_Some _ _ _ _ _ H) as [FRG | [FRG LOC]]; clear H.\n    left. apply foreign_in_extern; eassumption.\n    right.\n    remember (locBlocksSrc mu b1 && REACH m1 (exportedSrc mu (v1 :: nil)) b1) as d.\n    destruct d; inv LOC; apply eq_sym in Heqd. rewrite H0.\n    destruct (disjoint_extern_local _ WD b1). rewrite H. split; trivial.\n    rewrite H in H0; discriminate.\nQed.\n\n(* Goal (*Lemma halted_check:*) forall mu m1 m2 v1 v2 *)\n(*       (MInj: Mem.inject (as_inj mu) m1 m2) *)\n(*       (VInj: val_inject (locvisible_of mu) v1 v2) (WD: SM_wd mu), *)\n(*       exists pubSrc' pubTgt' nu,  *)\n(*         (pubSrc' = fun b => (locBlocksSrc mu b) && *)\n(*                             (REACH m1 (exportedSrc mu (v1::nil)) b)) *)\n(*         /\\ *)\n(*         (pubTgt' = fun b => (locBlocksTgt mu b) && *)\n(*                             (REACH m2 (exportedTgt mu (v2::nil)) b)) *)\n(*         /\\ *)\n(*         (nu = replace_locals mu pubSrc' pubTgt') *)\n(*          /\\ SM_wd nu /\\ *)\n(*         val_inject (shared_of nu) v1 v2 /\\ *)\n(*         Mem.inject (shared_of nu) m1 m2. (*/\\ val_valid v2 m2*) *)\n(* Proof. intros. eexists; eexists; eexists. *)\n(*   split. reflexivity. *)\n(*   split. reflexivity. *)\n(*   split. reflexivity. *)\n(*   split.  *)\n(*       apply replace_locals_wd; trivial. *)\n(*       intros. rewrite andb_true_iff in H. destruct H.  *)\n(*       assert (VALS12: Forall2 (val_inject (as_inj mu)) (v1 :: nil) (v2 :: nil)). *)\n(*         constructor. eapply val_inject_incr; try eassumption. *)\n(*                       unfold locvisible_of, join; simpl. *)\n(*                       intros b; intros. remember (foreign_of mu b).  *)\n(*                       destruct o; apply eq_sym in Heqo. *)\n(*                          destruct p. inv H1. apply foreign_in_all; eassumption. *)\n(*                       apply local_in_all; eassumption. *)\n(*         constructor. *)\n(*       destruct (REACH_local_REACH _ WD _ _ (v1::nil) (v2::nil) MInj VALS12 _ H0 H) *)\n(*         as [b2 [d1 [LOC12 R2]]]. *)\n(*       exists b2, d1. rewrite LOC12, R2. *)\n(*       destruct (local_locBlocks _ WD _ _ _ LOC12) as [_ [? _]]. *)\n(*       rewrite H1. intuition. *)\n(*       intros. apply andb_true_iff in H. intuition. *)\n(*   rewrite replace_locals_shared.  *)\n(*   split. inv VInj; try constructor. *)\n(*          econstructor. *)\n(*          unfold locvisible_of in H. *)\n(*          apply joinI. *)\n(*          destruct (joinD_Some _ _ _ _ _ H); clear H. *)\n(*             left; eassumption. *)\n(*          destruct H0. right. split; trivial. *)\n(*          remember (locBlocksSrc mu b1 && REACH m1 (exportedSrc mu (Vptr b1 ofs1 :: nil)) b1) as d.  *)\n(*               destruct d; apply eq_sym in Heqd. assumption. *)\n(*          apply andb_false_iff in Heqd.  *)\n(*               destruct (local_locBlocks _ WD _ _ _ H0) as [? [? [? [? ?]]]]. *)\n(*               rewrite H1 in *. *)\n(*               destruct Heqd; try discriminate. *)\n(*               assert (REACH m1 (exportedSrc mu (Vptr b1 ofs1 :: nil)) b1 = true). *)\n(*                 apply REACHAX. exists nil. constructor. *)\n(*                 unfold exportedSrc, sharedSrc, getBlocks. simpl. *)\n(*                  destruct (eq_block b1 b1). simpl. trivial. *)\n(*                  exfalso. apply n; trivial. *)\n(*               rewrite H7 in H6. inv H6. *)\n(*            reflexivity. *)\n(*     split. *)\n(*          (*goal Mem.mem_inj*)  *)\n(*            split; intros.  *)\n(*            (*subgoal mi_perm*) *)\n(*              apply halted_check_aux in H; trivial.  *)\n(*              eapply MInj; try eassumption. *)\n(*            (*subgoal mi_align*) *)\n(*              apply halted_check_aux in H; trivial.  *)\n(*              eapply MInj; try eassumption. *)\n(*            (*subgoal mi_memval*) *)\n(*              assert (X:= halted_check_aux _ _ _ _ _ _ WD H); trivial. *)\n(*              assert (MV:= Mem.mi_memval _ _ _ (Mem.mi_inj _ _ _ MInj) _ _ _ _ X H0). clear X. *)\n(*              inv MV; try econstructor; try reflexivity. *)\n(*                    apply joinI. *)\n(*                    remember (foreign_of mu b0) as f. *)\n(*                    destruct f; apply eq_sym in Heqf. *)\n(*                       destruct p. rewrite (foreign_in_all _ _ _ _ Heqf) in H3. left; trivial. *)\n(*                    right. split; trivial. *)\n(* (*THIS Need not hold - if we want to enforce that there are no *)\n(* pointers to unknown, we can probably do so by adding *)\n(*  the match_inject_clause:  *)\n(*     match_validblocks: forall d j c1 m1 c2 m2,  *)\n(*           match_state d j c1 m1 c2 m2 -> *)\n(*           mem_inject (as_inj mu) m1 m2 /\\ *)\n(*           mem_inject (locvisible mu) m1 m2, *)\n(*    or add an invariant reach_closed  *)\n\n(* and /or tweaking match_norm. cf the Lemma halted_loc_check below. *)\n(* *) *)\n(* Qed. *)\n\nLemma halted_loc_check_aux: forall mu m1 v1 b1 b2 delta (WD: SM_wd mu),\n      join (foreign_of mu)\n           (fun b =>\n              if locBlocksSrc mu b && REACH m1 (exportedSrc mu (v1 :: nil)) b\n              then local_of mu b\n              else None) b1 = Some (b2, delta) ->\n      locvisible_of mu b1= Some (b2, delta).\nProof. intros; apply joinI.\n  destruct (joinD_Some _ _ _ _ _ H) as [FRG | [FRG LOC]];\n     rewrite FRG; clear H.\n    left; trivial.\n    right; split; trivial.\n    remember (locBlocksSrc mu b1 && REACH m1 (exportedSrc mu (v1 :: nil)) b1) as d.\n    destruct d; inv LOC; apply eq_sym in Heqd. trivial.\nQed.\n\nLemma halted_loc_check: forall mu m1 m2 v1 v2\n      (MInj: Mem.inject (locvisible_of mu)  m1 m2)\n      (VInj: val_inject (locvisible_of mu) v1 v2) (WD: SM_wd mu),\n      exists pubSrc' pubTgt' nu,\n        (pubSrc' = fun b => (locBlocksSrc mu b) &&\n                            (REACH m1 (exportedSrc mu (v1::nil)) b))\n        /\\\n        (pubTgt' = fun b => (locBlocksTgt mu b) &&\n                            (REACH m2 (exportedTgt mu (v2::nil)) b))\n        /\\\n        (nu = replace_locals mu pubSrc' pubTgt')\n         /\\ SM_wd nu /\\\n        val_inject (shared_of nu) v1 v2 /\\\n        Mem.inject (shared_of nu) m1 m2. (*/\\ val_valid v2 m2*)\nProof. intros. eexists; eexists; eexists.\n  split. reflexivity.\n  split. reflexivity.\n  split. reflexivity.\n  split.\n      apply replace_locals_wd; trivial.\n      intros. rewrite andb_true_iff in H. destruct H.\n      assert (X: forall b, exportedSrc mu (v1 :: nil) b = true ->\n                 exists jb d, locvisible_of mu b = Some (jb, d) /\\\n                              exportedTgt mu (v2 :: nil) jb = true).\n          intros. unfold exportedSrc in H1. unfold exportedTgt.\n          apply orb_true_iff in H1.\n          destruct H1. unfold getBlocks in H1; simpl in H1. destruct v1; inv H1.\n               destruct (eq_block b0 b); inv H3.\n               inv VInj.  exists b2, delta. split; trivial.\n                    simpl. apply orb_true_iff. left. unfold getBlocks; simpl.\n                  destruct (eq_block b2 b2); trivial. exfalso. apply n; trivial.\n               rewrite locvisible_sharedprivate.\n                unfold join.\n                destruct (shared_SrcTgt _ WD _ H1) as [b2 [d1 [SH TGT]]].\n                rewrite SH. exists b2, d1; split; trivial.\n                rewrite TGT. destruct (getBlocks (v2 :: nil) b2); trivial.\n\n      destruct (REACH_inject _ _ _ MInj _ (exportedTgt mu (v2 :: nil)) X _ H0)\n           as [b2 [d1 [lv exp]]].\n        clear X. destruct (joinD_Some _ _ _ _ _ lv).\n            destruct (foreign_DomRng _ WD _ _ _ H1) as [? [? [? ?]]].\n            rewrite H in H4. inv H4.\n         destruct H1. rewrite H2. exists b2, d1. rewrite exp.\n            destruct (local_locBlocks _ WD _ _ _ H2) as [? [? [? [? ?]]]].\n             rewrite H4. intuition.\n     intros. apply andb_true_iff in H. destruct H; trivial.\n   split. rewrite replace_locals_shared.\n          inv VInj; try econstructor; trivial.\n          apply joinI.\n          destruct (joinD_Some _ _ _ _ _ H); clear H.\n             left; trivial.\n          destruct H0 as [FRG LOC]. rewrite FRG, LOC.\n          right; split; trivial.\n          destruct (local_locBlocks _ WD _ _ _ LOC) as [? [? [? [? [? ?]]]]].\n          rewrite H. simpl.\n          assert (R: REACH m1 (exportedSrc mu (Vptr b1 ofs1:: nil)) b1 = true).\n            apply REACHAX. exists nil.\n            constructor. unfold exportedSrc, getBlocks; simpl.\n            apply orb_true_iff; left.\n            destruct (eq_block b1 b1); trivial. exfalso. apply n; trivial.\n          rewrite R. trivial.\n    split. rewrite replace_locals_shared.\n         (*goal Mem.mem_inj*)\n           split; intros.\n           (*subgoal mi_perm*) apply halted_loc_check_aux in H; trivial.\n             eapply MInj; try eassumption.\n           (*subgoal mi_align*) apply halted_loc_check_aux in H; trivial.\n             eapply MInj; try eassumption.\n           (*subgoal mi_memval*)\n             assert (X:= halted_loc_check_aux _ _ _ _ _ _ WD H); trivial.\n             assert (MV:= Mem.mi_memval _ _ _ (Mem.mi_inj _ _ _ MInj) _ _ _ _ X H0). clear X.\n             inv MV; try econstructor; try reflexivity.\n                   apply joinI.\n                   destruct (joinD_Some _ _ _ _ _ H3) as [FRG | [FRG LOC]]; clear H3; rewrite FRG.\n                     left; reflexivity.\n                     right; split; trivial.\n                      destruct (local_locBlocks _ WD _ _ _ LOC) as [? [? [? [? [? ?]]]]].\n                      rewrite H3, LOC. simpl.\n                      destruct (joinD_Some _ _ _ _ _ H) as [FRG1 | [FRG1 LOC1]]; clear H.\n                        assert (REACH m1 (exportedSrc mu (v1 :: nil)) b0 = true).\n                        apply REACHAX. exists ((b1,ofs)::nil).\n                          apply eq_sym in H1.\n                          econstructor. constructor.\n                            unfold exportedSrc. apply orb_true_iff; right.\n                            apply sharedSrc_iff. unfold shared_of, join; simpl. rewrite FRG1. exists b2, delta; trivial.\n                            assumption. apply H1. rewrite H. trivial.\n                      remember (locBlocksSrc mu b1 && REACH m1 (exportedSrc mu (v1 :: nil)) b1) as d.\n                        destruct d; apply eq_sym in Heqd; inv LOC1.\n                          apply andb_true_iff in Heqd. destruct Heqd.\n                          assert (REACH m1 (exportedSrc mu (v1 :: nil)) b0 = true).\n                          apply REACHAX. apply REACHAX in H10. destruct H10 as [L RL].\n                          eexists. eapply reach_cons. apply RL.\n                          eassumption. rewrite <- H1. reflexivity.\n                          rewrite H11. trivial.\n    intros. rewrite replace_locals_shared.\n            assert (LV:= Mem.mi_freeblocks _ _ _ MInj _ H).\n            apply joinD_None in LV. destruct LV as [FRG LOC].\n            apply joinI_None. trivial.\n            rewrite LOC.\n            destruct (locBlocksSrc mu b && REACH m1 (exportedSrc mu (v1 :: nil)) b); trivial.\n    intros. rewrite replace_locals_shared in H.\n            eapply (Mem.mi_mappedblocks _ _ _ MInj b b' delta).\n            apply halted_loc_check_aux in H; trivial.\n    rewrite replace_locals_shared. intros b1; intros.\n            apply halted_loc_check_aux in H0; trivial.\n            apply halted_loc_check_aux in H1; trivial.\n            eapply MInj; eassumption.\n    rewrite replace_locals_shared; intros.\n            apply halted_loc_check_aux in H; trivial.\n            eapply MInj; eassumption.\nQed.\n\n\nLemma get_freelist:\n  forall fbl m m' (FL: Mem.free_list m fbl = Some m') b\n  (H: forall b' lo hi, In (b', lo, hi) fbl -> b' <> b) z,\n  ZMap.get z (Mem.mem_contents m') !! b =\n  ZMap.get z (Mem.mem_contents m) !! b.\nProof. intros fbl.\n  induction fbl; simpl; intros; inv FL; trivial.\n  destruct a. destruct p.\n  remember (Mem.free m b0 z1 z0) as d.\n  destruct d; inv H1. apply eq_sym in Heqd.\n  rewrite (IHfbl _ _ H2 b).\n     clear IHfbl H2.\n     case_eq (eq_block b0 b); intros.\n      exfalso. eapply (H b0). left. reflexivity. assumption.\n     apply Mem.free_result in Heqd. subst. reflexivity.\n  eauto.\nQed.\n\nLemma intern_incr_vis_inv: forall mu nu (WDmu: SM_wd mu) (WDnu: SM_wd nu)\n      (INC: intern_incr mu nu)\n       b1 b2 d (AI: as_inj mu b1 = Some(b2,d))\n      (VIS: vis nu b1 = true), vis mu b1 = true.\nProof. unfold vis; simpl. intros.\n  destruct INC as [L [E [LS [_ [_ [_ [F _]]]]]]].\n  rewrite F in *.\n  apply orb_true_iff in VIS. destruct VIS; intuition.\n  destruct (joinD_Some _ _ _ _ _ AI) as [EXT | [_ LOC]]; clear AI.\n    rewrite E in EXT.\n    destruct (extern_DomRng _ WDnu _ _ _ EXT) as [? ?].\n    rewrite (extBlocksSrc_locBlocksSrc _ WDnu _ H0) in H. discriminate.\n  destruct (local_DomRng _ WDmu _ _ _ LOC).\n    intuition.\nQed.\n\nLemma intern_incr_vis: forall mu nu (INC: intern_incr mu nu)\n       b (VIS: vis mu b = true), vis nu b = true.\nProof. unfold vis; simpl. intros.\n  destruct INC as [_ [_ [L [_ [_ [_ [F _]]]]]]].\n    apply orb_true_iff in VIS. destruct VIS.\n    apply L in H. intuition.\n    rewrite F in H. intuition.\nQed.\n\nLemma restrict_sm_intern_incr: forall mu1 mu2 (WD2 : SM_wd mu2)\n          (INC : intern_incr mu1 mu2),\n      intern_incr (restrict_sm mu1 (vis mu1))\n                  (restrict_sm mu2 (vis mu2)).\nProof.\n     red; intros. destruct INC.\n     destruct mu1; destruct mu2; simpl in *.\n        unfold restrict_sm, vis in *; simpl in *. intuition.\n     red; intros.\n       destruct (restrictD_Some _ _ _ _ _ H8) as [f M]; clear H8.\n       eapply restrictI_Some. eapply H; eassumption.\n       apply orb_true_iff in M.\n       destruct M as [M | M]. apply H0 in M. intuition.\n       rewrite H5 in M. rewrite M. intuition.\n     rewrite <- H1 in *.\n       extensionality b.\n       remember (restrict extern_of (fun b0 : block => locBlocksSrc b0 || frgnBlocksSrc b0) b) as d.\n       destruct d; apply eq_sym in Heqd.\n         destruct p. destruct (restrictD_Some _ _ _ _ _ Heqd) as [f M]; clear Heqd.\n         apply eq_sym. eapply restrictI_Some; try eassumption.\n         apply orb_true_iff in M.\n         destruct M as [M | M]. apply H0 in M. intuition.\n         rewrite H5 in M. rewrite M. intuition.\n       apply eq_sym. apply restrictI_None.\n         apply restrictD_None' in Heqd. destruct Heqd.\n         left; trivial.\n         destruct H8 as [b2 [dd [EXT M]]].\n         apply orb_false_iff in M. destruct M.\n         destruct (extern_DomRng _ WD2 _ _ _ EXT). simpl in *.\n           apply (extBlocksSrc_locBlocksSrc _ WD2) in H11. simpl in H11.\n           rewrite H5 in H10. rewrite H10, H11. right; reflexivity.\nQed.\nLemma intern_incr_restrict: forall mu1 mu2 (WD2 : SM_wd mu2)\n          (INC : intern_incr mu1 mu2),\n      inject_incr (restrict (as_inj mu1) (vis mu1))\n                  (restrict (as_inj mu2) (vis mu2)).\nProof.\n     red; intros. destruct (restrictD_Some _ _ _ _ _ H).\n     apply (intern_incr_as_inj _ _ INC) in H0; trivial.\n     eapply restrictI_Some; try eassumption.\n     eapply intern_incr_vis; eassumption.\nQed.\n\nLemma vis_restrict_sm: forall mu X,\n      vis (restrict_sm mu X) = vis mu.\nProof. intros. unfold vis. destruct mu; trivial. Qed.\n\nLemma REACH_split: forall m X Y b\n      (RCH:REACH m (fun b' => X b' || Y b') b = true),\n      REACH m X b = true \\/ REACH m Y b = true.\nProof. intros.\n  rewrite REACHAX in RCH.\n  destruct RCH as [L HL].\n  generalize dependent b.\n  induction L; simpl; intros; inv HL.\n    apply orb_true_iff in H.\n    destruct H.\n       left. apply REACH_nil. trivial.\n       right. apply REACH_nil. trivial.\n  destruct (IHL _ H1); clear IHL H1.\n    left. eapply REACH_cons; try eassumption.\n    right. eapply REACH_cons; try eassumption.\nQed.\n\nLemma reachD: forall m R L b (RCH :reach m (fun u => R u = true) L b),\n      exists r, R r = true /\\ reach m (fun bb => bb=r) L b.\nProof. intros m R L.\n  induction L; simpl; intros; inv RCH.\n    exists b. split; trivial. constructor. trivial.\n  destruct (IHL _ H1) as [r [Rr RCH]]; clear IHL H1.\n    exists r. split; trivial.\n    econstructor; eassumption.\nQed.\n\nLemma reachD': forall m R L b (RCH :reach m (fun u => R u = true)  L b),\n      exists r, R r = true /\\ reach m (fun bb => bb=r) L b /\\\n         match rev L with nil => True\n           | HD::TL => exists z, HD = (r,z)\n         end.\nProof. intros m R L.\n  induction L; simpl; intros; inv RCH.\n    exists b. intuition. constructor. trivial.\n  destruct (IHL _ H1) as [r [Rr [RCH1 RCH2]]]; clear IHL H1.\n    exists r. split; trivial.\n    split. econstructor; eassumption.\n    remember (rev L) as d. destruct d; simpl in *.\n      destruct L; simpl in *. inv RCH1. eexists; reflexivity.\n      apply app_cons_not_nil in Heqd. contradiction.\n    apply RCH2.\nQed.\n\n(*We can always \"normalize\" a reach-chain so that there's only a single root,\n  and the root at most occurs once in the chain*)\nLemma reachD'': forall m R L b (RCH :reach m (fun u => R u = true) L b),\n      exists r M, R r = true /\\ reach m (fun bb => bb=r) M b /\\\n         match rev M with nil => True\n           | HD::TL => exists z, HD = (r,z) /\\ (forall zz, ~ In (r,zz) TL) /\\\n                       (forall x zx, R x = true -> In (x,zx) M -> x=r)\n         end.\nProof. intros m R L.\n  induction L; simpl; intros; inv RCH.\n    exists b, nil; simpl. intuition. constructor. trivial.\n  destruct (IHL _ H1) as [r [M [Rr [RCH1 RCH2]]]]; clear IHL H1.\n    remember (R b) as Rb.\n    destruct Rb; apply eq_sym in HeqRb.\n      exists b, nil; simpl. intuition. constructor; trivial.\n    remember (R b') as Rb'.\n    destruct Rb'; apply eq_sym in HeqRb'.\n      exists b'; eexists. split; trivial.\n      split. eapply reach_cons; try eassumption.\n               eapply reach_nil. trivial.\n      simpl. exists z; intuition. inv H1. trivial.\n    exists r; eexists.\n      split. trivial.\n      split. eapply reach_cons; try eassumption.\n      simpl.\n      remember (rev M) as d. destruct d; simpl in *.\n        destruct M. inv RCH1. congruence.\n        simpl in Heqd. apply app_cons_not_nil in Heqd. contradiction.\n      destruct RCH2 as [zz [Hzz1 [Hzz2 Hzz3]]].\n      exists zz; intuition.\n      apply in_app_or in H.\n        destruct H. apply (Hzz2 _ H).\n        destruct H; try contradiction. inv H. congruence.\n      subst. inv H1. congruence.\n      subst. apply (Hzz3 _ _ H H1).\nQed.\n\nLemma encode_val_pointer_inv':\n  forall chunk v b ofs n B1 mvl,\n  encode_val chunk v = B1++Pointer b ofs n :: mvl ->\n  chunk = Mint32 /\\ v = Vptr b ofs.\nProof.\n  intros until B1.\n  assert (A: forall mvl, list_repeat (size_chunk_nat chunk) Undef = B1++Pointer b ofs n :: mvl ->\n            chunk = Mint32 /\\ v = Vptr b ofs).\n    intros. destruct (size_chunk_nat_pos chunk) as [sz SZ]. rewrite SZ in H. simpl in H.\n         clear SZ. generalize dependent sz.\n         induction B1. simpl; intros. inv H.\n         simpl; intros. inv H.\n           destruct sz; simpl in *. destruct B1; inv H2.\n         apply (IHB1 _ H2).\n  intros mvl.\n  assert (B: forall bl, inj_bytes bl = B1++Pointer b ofs n :: mvl ->\n            chunk = Mint32 /\\ v = Vptr b ofs).\n    clear A. intros bl. generalize dependent B1.\n       induction bl. simpl; intros. destruct B1; inv H.\n       simpl; intros.\n       destruct B1; simpl in *. inv H.\n       inv H. eapply IHbl. eassumption.\n  intros.\n  specialize (A mvl).\n  unfold encode_val; destruct v; destruct chunk;\n  (apply A; assumption) ||\n  (eapply B; rewrite encode_int_length; congruence) || idtac.\n\n  eapply B. simpl in H. eassumption.\n  eapply B. simpl in H. eassumption.\n  eapply B. simpl in H. eassumption.\n  eapply B. simpl in H. eassumption.\n  eapply B. simpl in H. eassumption.\n  eapply B. simpl in H. eassumption.\n  eapply B. simpl in H. eassumption.\n  eapply B. simpl in H. eassumption.\n  eapply B. simpl in H. eassumption.\n  simpl in H. clear -H.\n  assert (forall L, (forall mv, In mv L -> exists n, mv = Pointer b0 i n) ->\n          forall  mv, In mv L -> exists n, mv = Pointer b0 i n).\n    intros. apply H0. trivial.\n  assert (exists k, Pointer b ofs n = Pointer b0 i k).\n    apply (H0 (B1 ++ Pointer b ofs n :: mvl)).\n    intros. rewrite <- H in H1. clear -H1.\n    destruct H1. subst. eexists; reflexivity.\n    destruct H. subst. eexists; reflexivity.\n    destruct H. subst. eexists; reflexivity.\n    destruct H. subst. eexists; reflexivity.\n    inv H.\n  apply in_or_app. right. left. trivial.\n  destruct H1. inv H1. split; trivial.\nQed.\n\nLemma list_split: forall {A} n (L:list A) (Hn : (n < length L)%nat),\n      exists vl1 u vl2,\n                     L = vl1 ++ u :: vl2 /\\\n                     length vl1 = n.\nProof. intros A n.\n  induction n; simpl; intros.\n    exists nil; simpl. destruct L; simpl in *. inv Hn.\n     exists a, L. split; trivial.\n  destruct L; simpl in Hn. inv Hn.\n    destruct (IHn L) as [L1 [u [L2 [HL LL]]]].\n       omega.\n    subst. exists (a::L1), u, L2; simpl. split; trivial.\nQed.\n\nLemma REACH_Store: forall m chunk b i v m'\n     (ST: Mem.store chunk m b (Int.unsigned i) v = Some m')\n     Roots (VISb: Roots b = true)\n     (VISv : forall b', getBlocks (v :: nil) b' = true ->\n             Roots b' = true)\n     (R: REACH_closed m Roots),\n     REACH_closed m' Roots.\nProof. intros.\nintros bb Hbb.\napply R. clear R.\nrewrite REACHAX.\nremember (Roots bb) as Rb. destruct Rb; apply eq_sym in HeqRb.\n  eexists. eapply reach_nil; trivial.\nrewrite REACHAX in Hbb.\ndestruct Hbb as [L HL].\ndestruct (reachD'' _ _ _ _ HL) as [r [M [Rr [RCH HM]]]]; clear HL L.\ndestruct (eq_block r b); subst.\n(*we stored into the root of the access path to bb*)\n  clear VISb.\n  generalize dependent bb.\n  induction M; simpl in *; intros.\n  inv RCH. congruence.\n  inv RCH.\n  apply (Mem.perm_store_2 _ _ _ _ _ _ ST) in H2.\n  remember (rev M) as rm.\n  destruct rm; simpl in *. destruct HM as [zz [Hzz1 [Hzz2 Hzz3]]].\n        inv Hzz1.\n        intuition.\n        assert (M= nil). destruct M; trivial.\n             assert (@length (block * Z) nil = length (rev (p :: M))). rewrite Heqrm; trivial.\n             rewrite rev_length in H3. simpl in H3. inv H3.\n        subst. simpl in *. clear H Heqrm H0 H1.\n          specialize (Mem.loadbytes_store_same _ _ _ _ _ _ ST). intros LD.\n          apply loadbytes_D in LD. destruct LD.\n\n     rewrite (Mem.store_mem_contents _ _ _ _ _ _ ST) in H4, H0.\n          apply Mem.store_valid_access_3 in ST. destruct ST as [RP ALGN].\n          rewrite PMap.gss in H4.\n          destruct (zlt zz (Int.unsigned i)).\n            rewrite Mem.setN_outside in H4.\n            eexists. eapply reach_cons; try eassumption.\n                     apply reach_nil. assumption.\n            left; trivial.\n          destruct (zlt zz ((Int.unsigned i) + Z.of_nat (length (encode_val chunk v)))).\n          Focus 2.\n            rewrite Mem.setN_outside in H4.\n            eexists. eapply reach_cons; try eassumption.\n                     apply reach_nil. assumption.\n            right; trivial.\n          rewrite encode_val_length in *. rewrite <- size_chunk_conv in *.\n            rewrite PMap.gss in H0.\n            remember ((Mem.setN (encode_val chunk v) (Int.unsigned i)\n          (Mem.mem_contents m) !! b)) as c. apply eq_sym in H0.\n          specialize (getN_aux (nat_of_Z ((size_chunk chunk))) (Int.unsigned i) c).\n          assert (exists z, zz = Int.unsigned i + z /\\ z>=0 /\\ z < size_chunk chunk).\n            exists (zz - Int.unsigned i). omega.\n          destruct H1 as [z [Z1 [Z2 Z3]]]. clear g l. subst zz.\n          rewrite <- (nat_of_Z_eq _ Z2) in H4.\n          assert (SPLIT: exists vl1 u vl2,\n                     encode_val chunk v = vl1 ++ u :: vl2 /\\\n                     length vl1 = nat_of_Z z).\n            eapply list_split. rewrite encode_val_length.\n                 rewrite size_chunk_conv in Z3.\n            remember (size_chunk_nat chunk) as k. clear Heqk H2 H4 Hzz3.\n            specialize (Z2Nat.inj_lt z (Z.of_nat k)); intros.\n            rewrite Nat2Z.id in H1. apply H1. omega. omega.  assumption.\n\n          destruct SPLIT as [B1 [u [B2 [EE LL]]]].\n          rewrite EE in *. rewrite <- LL in H4.\n          intros. apply H1 in H0. clear H1.\n          rewrite <- H0 in H4. clear H0. subst u.\n          destruct (encode_val_pointer_inv' _ _ _ _ _ _ _ EE).\n          subst.\n          rewrite VISv in HeqRb. discriminate.\n             rewrite getBlocks_char. exists off; left. trivial.\n  destruct HM as [zz [Hzz1 [Hzz2 Hzz3]]].\n    subst.\n    remember (Roots b') as q.\n    destruct q; apply eq_sym in Heqq.\n      assert (b' = b). apply (Hzz3 _ z Heqq). left; trivial.\n      subst. elim (Hzz2 z). apply in_or_app. right. left. trivial.\n    destruct (eq_block b' b); try congruence.\n        rewrite (Mem.store_mem_contents _ _ _ _ _ _ ST) in H4.\n        rewrite PMap.gso in H4; trivial.\n        assert (Hb': exists L : list (block * Z),\n            reach m (fun bb0 : block => Roots bb0 = true) L b').\n          apply IHM; trivial. clear IHM.\n          exists zz. intuition.\n          eapply (Hzz2 zz0). apply in_or_app. left; trivial.\n          eapply (Hzz3 _ zx H). right; trivial.\n        destruct Hb' as [L HL].\n          eexists. eapply reach_cons; try eassumption.\n(*we stored elsewhere*)\ngeneralize dependent bb.\ninduction M; simpl in *; intros.\n  inv RCH. congruence.\n  inv RCH.\n  apply (Mem.perm_store_2 _ _ _ _ _ _ ST) in H2.\n  rewrite (Mem.store_mem_contents _ _ _ _ _ _ ST) in H4.\n  remember (rev M) as rm.\n  destruct rm; simpl in *. destruct HM as [zz [Hzz1 [Hzz2 Hzz3]]].\n        inv Hzz1.\n        rewrite PMap.gso in H4; trivial.\n        eexists. eapply reach_cons; try eassumption.\n           apply reach_nil. assumption.\n  destruct HM as [zz [Hzz1 [Hzz2 Hzz3]]].\n    subst.\n    remember (Roots b') as q.\n    destruct q; apply eq_sym in Heqq.\n      assert (b' = r). apply (Hzz3 _ z Heqq). left; trivial.\n      subst.\n        rewrite PMap.gso in H4; trivial.\n          eexists. eapply reach_cons; try eassumption.\n           apply reach_nil. assumption.\n    destruct (eq_block b' b); try congruence.\n        rewrite PMap.gso in H4; trivial.\n        assert (Hb': exists L : list (block * Z),\n            reach m (fun bb0 : block => Roots bb0 = true) L b').\n          apply IHM; trivial. clear IHM.\n          exists zz. intuition.\n          eapply (Hzz2 zz0). apply in_or_app. left; trivial.\n          eapply (Hzz3 _ zx H). right; trivial.\n        destruct Hb' as [L HL].\n          eexists. eapply reach_cons; try eassumption.\nQed.\n\n(*similar proof as Lemma REACH_Store. *)\nLemma REACH_Storebytes: forall m b i bytes m'\n     (ST: Mem.storebytes m b (Int.unsigned i) bytes = Some m')\n     Roots (VISb: Roots b = true)\n     (VISv : forall b' z n, In (Pointer b' z n) bytes ->\n             Roots b' = true)\n     (R: REACH_closed m Roots),\n     REACH_closed m' Roots.\nProof. intros.\nintros bb Hbb.\napply R. clear R.\nrewrite REACHAX.\nremember (Roots bb) as Rb. destruct Rb; apply eq_sym in HeqRb.\n  eexists. eapply reach_nil; trivial.\nrewrite REACHAX in Hbb.\ndestruct Hbb as [L HL].\ndestruct (reachD'' _ _ _ _ HL) as [r [M [Rr [RCH HM]]]]; clear HL L.\ndestruct (eq_block r b); subst.\n(*we stored into the root of the access path to bb*)\n  clear VISb.\n  generalize dependent bb.\n  induction M; simpl in *; intros.\n  inv RCH. congruence.\n  inv RCH.\n  apply (Mem.perm_storebytes_2 _ _ _ _ _ ST) in H2.\n  remember (rev M) as rm.\n  destruct rm; simpl in *. destruct HM as [zz [Hzz1 [Hzz2 Hzz3]]].\n        inv Hzz1.\n        intuition.\n        assert (M= nil). destruct M; trivial.\n             assert (@length (block * Z) nil = length (rev (p :: M))). rewrite Heqrm; trivial.\n             rewrite rev_length in H3. simpl in H3. inv H3.\n        subst. simpl in *. clear H Heqrm H0 H1.\n          specialize (Mem.loadbytes_storebytes_same _ _ _ _ _ ST). intros LD.\n          apply loadbytes_D in LD. destruct LD.\n\n     rewrite (Mem.storebytes_mem_contents _ _ _ _ _ ST) in H4, H0.\n          apply Mem.storebytes_range_perm in ST. (*destruct ST as [RP ALGN].*)\n          rewrite PMap.gss in H4.\n          destruct (zlt zz (Int.unsigned i)).\n            rewrite Mem.setN_outside in H4.\n            eexists. eapply reach_cons; try eassumption.\n                     apply reach_nil. assumption.\n            left; trivial.\n          destruct (zlt zz ((Int.unsigned i) + Z.of_nat (length bytes))).\n          Focus 2.\n            rewrite Mem.setN_outside in H4.\n            eexists. eapply reach_cons; try eassumption.\n                     apply reach_nil. assumption.\n            right; trivial.\n          rewrite nat_of_Z_of_nat in H0. rewrite PMap.gss in H0.\n            remember ((Mem.setN bytes (Int.unsigned i)\n          (Mem.mem_contents m) !! b)) as c. apply eq_sym in H0.\n          specialize (getN_aux (length bytes) (Int.unsigned i) c).\n          assert (exists z, zz = Int.unsigned i + z /\\ z>=0 /\\ z < Z.of_nat(length bytes)).\n            exists (zz - Int.unsigned i). omega.\n          destruct H1 as [z [Z1 [Z2 Z3]]]. clear g l. subst zz.\n          rewrite <- (nat_of_Z_eq _ Z2) in H4.\n          assert (SPLIT: exists vl1 u vl2,\n                     bytes = vl1 ++ u :: vl2 /\\\n                     length vl1 = nat_of_Z z).\n            eapply list_split.\n            specialize (Z2Nat.inj_lt z (Z.of_nat (length bytes))); intros.\n            rewrite Nat2Z.id in H1. apply H1. omega. omega.  assumption.\n          destruct SPLIT as [B1 [u [B2 [EE LL]]]].\n          rewrite EE in *. rewrite <- LL in H4.\n          intros. apply H1 in H0. clear H1.\n          rewrite <- H0 in H4. clear H0. subst u.\n          subst.\n          rewrite (VISv bb off n) in HeqRb. discriminate.\n             eapply in_or_app. right. left. trivial.\n  destruct HM as [zz [Hzz1 [Hzz2 Hzz3]]].\n    subst.\n    remember (Roots b') as q.\n    destruct q; apply eq_sym in Heqq.\n      assert (b' = b). apply (Hzz3 _ z Heqq). left; trivial.\n      subst. elim (Hzz2 z). apply in_or_app. right. left. trivial.\n    destruct (eq_block b' b); try congruence.\n        rewrite (Mem.storebytes_mem_contents _ _ _ _ _ ST) in H4.\n        rewrite PMap.gso in H4; trivial.\n        assert (Hb': exists L : list (block * Z),\n            reach m (fun bb0 : block => Roots bb0 = true) L b').\n          apply IHM; trivial. clear IHM.\n          exists zz. intuition.\n          eapply (Hzz2 zz0). apply in_or_app. left; trivial.\n          eapply (Hzz3 _ zx H). right; trivial.\n        destruct Hb' as [L HL].\n          eexists. eapply reach_cons; try eassumption.\n(*we stored elsewhere*)\ngeneralize dependent bb.\ninduction M; simpl in *; intros.\n  inv RCH. congruence.\n  inv RCH.\n  apply (Mem.perm_storebytes_2 _ _ _ _ _ ST) in H2.\n  rewrite (Mem.storebytes_mem_contents _ _ _ _ _ ST) in H4.\n  remember (rev M) as rm.\n  destruct rm; simpl in *. destruct HM as [zz [Hzz1 [Hzz2 Hzz3]]].\n        inv Hzz1.\n        rewrite PMap.gso in H4; trivial.\n        eexists. eapply reach_cons; try eassumption.\n           apply reach_nil. assumption.\n  destruct HM as [zz [Hzz1 [Hzz2 Hzz3]]].\n    subst.\n    remember (Roots b') as q.\n    destruct q; apply eq_sym in Heqq.\n      assert (b' = r). apply (Hzz3 _ z Heqq). left; trivial.\n      subst.\n        rewrite PMap.gso in H4; trivial.\n          eexists. eapply reach_cons; try eassumption.\n           apply reach_nil. assumption.\n    destruct (eq_block b' b); try congruence.\n        rewrite PMap.gso in H4; trivial.\n        assert (Hb': exists L : list (block * Z),\n            reach m (fun bb0 : block => Roots bb0 = true) L b').\n          apply IHM; trivial. clear IHM.\n          exists zz. intuition.\n          eapply (Hzz2 zz0). apply in_or_app. left; trivial.\n          eapply (Hzz3 _ zx H). right; trivial.\n        destruct Hb' as [L HL].\n          eexists. eapply reach_cons; try eassumption.\nQed.\n\nLemma REACH_load_vis: forall chunk m b i b1 ofs1\n        (LD: Mem.load chunk m b (Int.unsigned i) = Some (Vptr b1 ofs1))\n         mu (VIS: vis mu b = true),\n      REACH m (vis mu) b1 = true.\nProof.\n  intros.\n  eapply REACH_cons with(z:=Int.unsigned i)(off:=ofs1).\n    apply REACH_nil. apply VIS.\n    eapply Mem.load_valid_access. apply LD.\n    split. omega. destruct chunk; simpl; omega.\n    apply Mem.load_result in LD.\n    apply eq_sym in LD.\n    destruct (decode_val_pointer_inv _ _ _ _ LD); clear LD; subst.\n    simpl in *.\n    inv H0. eassumption.\nQed.\n\nSection ALLOC.\n\nVariable m1: mem.\nVariables lo hi: Z.\nVariable m2: mem.\nVariable b: Values.block.\nHypothesis ALLOC: Mem.alloc m1 lo hi = (m2, b).\n\nTransparent Mem.alloc.\nLemma AllocContentsUndef:\n     (Mem.mem_contents m2) !! b = ZMap.init Undef.\nProof.\n   injection ALLOC. simpl; intros. subst.\n   simpl. rewrite PMap.gss. reflexivity.\nQed.\nOpaque Mem.alloc.\n\nLemma AllocContentsUndef1: forall z,\n     ZMap.get z (Mem.mem_contents m2) !! b = Undef.\nProof. intros. rewrite AllocContentsUndef . apply ZMap.gi. Qed.\n\nEnd ALLOC.\n\n(*The following 2 lemmas are from Cminorgenproof.v*)\nLemma nextblock_storev:\n  forall chunk m addr v m',\n  Mem.storev chunk m addr v = Some m' -> Mem.nextblock m' = Mem.nextblock m.\nProof.\n  unfold Mem.storev; intros. destruct addr; try discriminate.\n  eapply Mem.nextblock_store; eauto.\nQed.\nLemma nextblock_freelist:\n  forall fbl m m',\n  Mem.free_list m fbl = Some m' ->\n  Mem.nextblock m' = Mem.nextblock m.\nProof.\n  induction fbl; intros until m'; simpl.\n  congruence.\n  destruct a as [[b lo] hi].\n  case_eq (Mem.free m b lo hi); intros; try congruence.\n  transitivity (Mem.nextblock m0). eauto. eapply Mem.nextblock_free; eauto.\nQed.\nLemma perm_freelist:\n  forall fbl m m' b ofs k p,\n  Mem.free_list m fbl = Some m' ->\n  Mem.perm m' b ofs k p ->\n  Mem.perm m b ofs k p.\nProof.\n  induction fbl; simpl; intros until p.\n  congruence.\n  destruct a as [[b' lo] hi]. case_eq (Mem.free m b' lo hi); try congruence.\n  intros. eauto with mem.\nQed.\n\n\nLemma store_freshloc: forall ch m addr v m'\n         (ST: Mem.storev ch m addr v = Some m'),\n         freshloc m m' = fun b => false.\nProof. intros.\n  extensionality b.\n  apply nextblock_storev in ST.\n  (*specialize (storev_valid_block_2 _ _ _ _ _ ST b); intros.\n  specialize (storev_valid_block_1 _ _ _ _ _ ST b); intros.*)\n  apply freshloc_charF.\n  unfold Mem.valid_block. rewrite ST. xomega.\nQed.\n\nLemma freshloc_alloc: forall m1 lo hi m2 b\n      (ALLOC: Mem.alloc m1 lo hi = (m2, b)),\n      freshloc m1 m2 = fun bb => eq_block bb b.\nProof. intros.\n  unfold freshloc. extensionality bb.\n  destruct (eq_block bb b); subst; simpl.\n    specialize (Mem.valid_new_block _ _ _ _ _ ALLOC).\n    apply Mem.fresh_block_alloc in ALLOC.\n    intros.\n    destruct (valid_block_dec m2 b); try contradiction; simpl.\n    destruct (valid_block_dec m1 b); try contradiction; trivial.\n  destruct (valid_block_dec m2 bb); simpl; trivial.\n    destruct (Mem.valid_block_alloc_inv _ _ _ _ _ ALLOC _ v); try contradiction.\n    destruct (valid_block_dec m1 bb); try contradiction; trivial.\nQed.\n\nLemma freshloc_free: forall m sp i n m'\n      (F: Mem.free m sp i n = Some m'),\n      freshloc m m' = fun b => false.\nProof. intros.\n  unfold freshloc. extensionality b.\n  remember (valid_block_dec m' b) as d'.\n  destruct d'; simpl; trivial; clear Heqd'.\n    apply (Mem.valid_block_free_2 _ _ _ _ _ F ) in v.\n    remember (valid_block_dec m b) as d.\n    destruct d; trivial. congruence.\nQed.\n\nLemma freshloc_free_list: forall m n m'\n      (F: Mem.free_list m n = Some m'),\n      freshloc m m' = fun b => false.\nProof. intros.\n  unfold freshloc. apply nextblock_freelist in F.\n  extensionality b.\n  remember (valid_block_dec m' b) as d'.\n  destruct d'; simpl; trivial; clear Heqd'.\n    remember (valid_block_dec m b) as d.\n    destruct d; trivial. unfold Mem.valid_block in *.\n    rewrite F in v. congruence.\nQed.\n\n(*new lemma*)\nLemma free_parallel_inject:\n  forall j (m1 m2 : mem) (b : block) (lo hi : Z) (m1' : mem) ,\n  Mem.inject j m1 m2 ->\n  Mem.free m1 b lo hi = Some m1' ->\n  forall b2 d (J: j b = Some(b2,d)),\n    exists m2' : mem, Mem.free m2 b2 (lo+d) (hi+d) = Some m2' /\\\n                Mem.inject j m1' m2'.\nProof. intros.\n  destruct (Mem.range_perm_free m2 b2 (lo+d) (hi+d)) as [m2' Hm2'].\n    intros. intros off; intros.\n    specialize (Mem.perm_inject _ _ _ _ _ _ (off-d) Cur Freeable J H). intros.\n    assert (off - d + d = off) by omega. rewrite H3 in H2.\n    apply H2. clear H2 H3.\n    eapply (Mem.free_range_perm _ _ _ _ _ H0). omega.\n  exists m2'; split; trivial.\n  eapply (Mem.free_inject _ _ ((b,lo,hi)::nil)); try eassumption.\n    simpl. rewrite H0. trivial.\n  intros.\n  destruct (eq_block b1 b); subst.\n    rewrite H1 in J; inv J. exists lo, hi; split. left; trivial. omega.\n  assert (P: Mem.perm m1 b (ofs + delta - d) Max Nonempty).\n    eapply Mem.perm_implies.\n      eapply Mem.perm_max.\n      apply (Mem.free_range_perm _ _ _ _ _ H0). omega.\n    constructor.\n  assert (P1: Mem.perm m1 b1 ofs Max Nonempty).\n    eapply Mem.perm_implies.\n      eapply Mem.perm_max. eassumption. eapply perm_any_N.\n  exfalso.\n  destruct (Mem.mi_no_overlap _ _ _ H b1 _ _ _ _ _ _ _ n H1 J P1 P)\n    as [X | X]; apply X; trivial. omega.\nQed.\n\nLemma REACH_closed_free: forall m1 b lo hi m2\n       (F: Mem.free m1 b lo hi = Some m2) X\n       (RC: REACH_closed m1 X),\n      REACH_closed m2 X.\nProof. intros.\n      red; intros. apply RC; clear RC.\n          rewrite REACHAX in H. destruct H as [L HL].\n          generalize dependent b0.\n          induction L; simpl; intros; inv HL.\n            apply REACH_nil. assumption.\n          specialize (IHL _ H1); clear H1.\n            eapply REACH_cons; try eassumption.\n            eapply Mem.perm_free_3; eassumption.\n            rewrite (Mem.free_result _ _ _ _ _ F) in H4.\n            apply H4.\nQed.\n\nLemma REACH_closed_freelist: forall X l m m'\n  (FL : Mem.free_list m l = Some m')\n  (RC : REACH_closed m X),\n  REACH_closed m' X.\nProof. intros X l.\n induction l; simpl; intros.\n   inv FL. trivial.\n destruct a as [[b lo] hi].\n remember (Mem.free m b lo hi).\n destruct o; inv FL. apply eq_sym in Heqo.\n eapply (IHl _ _ H0).\n eapply REACH_closed_free; eassumption.\nQed.\n\nDefinition alloc_right_sm (mu: SM_Injection) sp: SM_Injection :=\n  Build_SM_Injection (locBlocksSrc mu)\n                     (fun b => eq_block b sp || locBlocksTgt mu b)\n                     (pubBlocksSrc mu) (pubBlocksTgt mu)\n                     (local_of mu)\n                     (extBlocksSrc mu) (extBlocksTgt mu)\n                     (frgnBlocksSrc mu) (frgnBlocksTgt mu) (extern_of mu).\n\nLemma alloc_right_sm_wd: forall mu sp (WD: SM_wd mu)\n      (NEW1: DomTgt mu sp = false),\n      SM_wd (alloc_right_sm mu sp).\nProof. intros.\neconstructor; simpl in *; try solve [eapply WD].\n  intros. unfold DomTgt in NEW1.\n    apply orb_false_iff in NEW1.\n    destruct NEW1.\n    remember (eq_block b sp) as d.\n    destruct d; simpl in *; apply eq_sym in Heqd.\n      subst. right. assumption.\n      eapply WD.\n  intros.\n    destruct (local_DomRng _ WD _ _ _ H). intuition.\n  intros. rewrite (pubBlocksLocalTgt _ WD _ H). intuition.\nQed.\n\nLemma alloc_right_sm_locBlocksTgt: forall mu sp,\n  locBlocksTgt (alloc_right_sm mu sp) = fun b => eq_block b sp || locBlocksTgt mu b.\nProof. intros. reflexivity. Qed.\n\nLemma alloc_right_sm_DomSrc: forall mu sp,\n      DomSrc (alloc_right_sm mu sp) = DomSrc mu.\nProof. intros. extensionality b.\n  unfold DomSrc, alloc_right_sm; simpl. trivial.\nQed.\n\nLemma alloc_right_sm_DomTgt: forall mu sp,\n      DomTgt (alloc_right_sm mu sp) = fun b => eq_block b sp || DomTgt mu b.\nProof. intros. extensionality b.\n  unfold DomTgt, alloc_right_sm; simpl.\n  rewrite <- orb_assoc. trivial.\nQed.\n\nLemma alloc_right_sm_as_inj: forall mu sp,\n      as_inj (alloc_right_sm mu sp) = as_inj mu.\nProof. intros. unfold alloc_right_sm, as_inj; reflexivity. Qed.\n\nLemma alloc_right_sm_intern_incr: forall mu sp,\n      intern_incr mu (alloc_right_sm mu sp).\nProof. intros. red; intros. simpl. intuition. Qed.\n\n\nDefinition alloc_left_sm (mu: SM_Injection) b1 b2 delta: SM_Injection :=\n  Build_SM_Injection (fun b => eq_block b b1 || locBlocksSrc mu b)\n                     (locBlocksTgt mu) (*b2 is already in locBlocksTgt!*)\n                     (pubBlocksSrc mu) (pubBlocksTgt mu)\n                     (fun b => if eq_block b b1 then Some(b2, delta)\n                               else local_of mu b)\n                     (extBlocksSrc mu) (extBlocksTgt mu)\n                     (frgnBlocksSrc mu) (frgnBlocksTgt mu) (extern_of mu).\n\nLemma alloc_left_sm_wd: forall mu b1 b2 delta (WD: SM_wd mu)\n      (NEW1: DomSrc mu b1 = false) (NEW2: locBlocksTgt mu b2 = true),\n      SM_wd (alloc_left_sm mu b1 b2 delta).\nProof. intros.\neconstructor; simpl in *; try solve [eapply WD].\n  intros. apply orb_false_iff in NEW1.\n    remember (eq_block b b1) as d.\n    destruct d; simpl in *; apply eq_sym in Heqd.\n      subst. right. apply NEW1.\n      apply WD.\n  intros.\n    remember (eq_block b0 b1) as d.\n      destruct d; simpl in *; apply eq_sym in Heqd. inv H. split; trivial.\n    apply (local_DomRng _ WD _ _ _ H).\n  intros.\n    destruct (pubSrc _ WD _ H) as [bb [dd [PB PT]]].\n    exists bb, dd.\n    remember (eq_block b0 b1) as d.\n      destruct d; simpl in *; apply eq_sym in Heqd.\n        subst. unfold DomSrc in NEW1.\n        rewrite (pubBlocksLocalSrc _ WD _ H) in NEW1. simpl in *. discriminate.\n      rewrite (pub_in_local _ _ _ _ PB).\n      split; trivial.\nQed.\n\nLemma alloc_left_sm_as_inj_same: forall mu b1 b2 delta (WD: SM_wd mu)\n      (NEW1: DomSrc mu b1 = false),\n      as_inj (alloc_left_sm mu b1 b2 delta) b1 = Some(b2,delta).\nProof. intros.\n  unfold as_inj, join; simpl.\n  remember (extern_of mu b1) as d.\n  destruct d; apply eq_sym in Heqd; simpl. destruct p.\n    destruct (extern_DomRng' _ WD _ _ _ Heqd). rewrite NEW1 in H0. intuition.\n  destruct (eq_block b1 b1); subst; trivial.\n    elim n. trivial.\nQed.\n\nLemma alloc_left_sm_as_inj_other: forall mu b1 b2 delta b (H: b<>b1),\n      as_inj (alloc_left_sm mu b1 b2 delta) b = as_inj mu b.\nProof. intros.\n  unfold as_inj, join; simpl.\n  destruct (eq_block b b1); subst; trivial. elim H. trivial.\nQed.\n\nLemma alloc_left_sm_intern_incr:\n      forall mu b1 b2 delta (H: as_inj mu b1 = None) (WD: SM_wd mu),\n      intern_incr mu (alloc_left_sm mu b1 b2 delta).\nProof. intros.\n  specialize (local_in_all _ WD); intros.\n  red; intros. destruct mu; simpl in *.\n  intuition.\n  red; intros.\n  destruct (eq_block b b1); subst.\n     rewrite (H0 _ _ _ H1) in H. inv H.\n  assumption.\nQed.\n\nLemma alloc_left_sm_inject_incr:\n      forall mu b1 b2 delta (H: as_inj mu b1 = None),\n      inject_incr (as_inj mu) (as_inj (alloc_left_sm mu b1 b2 delta)).\nProof. intros.\n  red; intros.\n  destruct (eq_block b b1); subst. congruence.\n  rewrite alloc_left_sm_as_inj_other; trivial.\nQed.\n\nLemma alloc_DomSrc: forall mu m1 m2 (SMV: sm_valid mu m1 m2) lo hi m1' b1\n      (ALLOC: Mem.alloc m1 lo hi = (m1', b1)),\n      DomSrc mu b1 = false.\nProof. intros.\n  remember (DomSrc mu b1) as d.\n  destruct d; trivial; apply eq_sym in Heqd.\n  apply Mem.fresh_block_alloc in ALLOC.\n  elim ALLOC. apply SMV. apply Heqd.\nQed.\n\nLemma alloc_left_sm_DomSrc: forall mu b1 b2 delta,\n      DomSrc (alloc_left_sm mu b1 b2 delta) = fun b => eq_block b b1 || DomSrc mu b.\nProof. intros. extensionality b.\n  unfold DomSrc, alloc_left_sm; simpl.\n  rewrite <- orb_assoc. trivial.\nQed.\n\nLemma alloc_left_sm_DomTgt: forall mu b1 b2 delta,\n      DomTgt (alloc_left_sm mu b1 b2 delta) = DomTgt mu.\nProof. intros. reflexivity. Qed.\n\nLemma REACH_closed_alloc_left_sm: forall m lo hi sp m'\n          (ALLOC : Mem.alloc m lo hi = (m', sp))\n          mu (RC: REACH_closed m (vis mu)) b' delta,\n      REACH_closed m' (vis (alloc_left_sm mu sp b' delta)).\nProof.\n  red; intros.\n  unfold vis. simpl.\n  destruct (eq_block b sp); try subst b. trivial.\n  simpl.\n  apply RC. rewrite REACHAX in H.\n  destruct H as [L HL].\n  generalize dependent b.\n  induction L; simpl; intros; inv HL.\n    apply REACH_nil.\n      unfold vis in H. simpl in H.\n      destruct (eq_block b sp); try subst b. elim n; trivial.\n      apply H.\n    destruct (eq_block b'0 sp); try subst b'0.\n      clear - ALLOC H2 H4 n.\n      rewrite (AllocContentsUndef1 _ _ _ _ _ ALLOC) in H4. inv H4.\n    specialize (IHL _ H1 n1); clear H1.\n      apply (Mem.perm_alloc_4 _ _ _ _ _ ALLOC) in H2; trivial.\n      destruct (Mem.alloc_unchanged_on (fun bb zz => True)\n         _ _ _ _ _ ALLOC) as [UP UC].\n      rewrite UC in H4; trivial.\n        eapply REACH_cons; eassumption.\nQed.\n\nTheorem alloc_left_mapped_sm_inject:\n  forall mu m1 m2 lo hi m1' b1 b2 delta (WD: SM_wd mu)\n        (SMV: sm_valid mu m1 m2) (RC: REACH_closed m1 (vis mu))\n        (Locb2: locBlocksTgt mu b2 = true),\n  Mem.inject (as_inj mu) m1 m2 ->\n  Mem.alloc m1 lo hi = (m1', b1) ->\n  Mem.valid_block m2 b2 ->\n  0 <= delta <= Int.max_unsigned ->\n  (forall ofs k p, Mem.perm m2 b2 ofs k p -> delta = 0 \\/ 0 <= ofs < Int.max_unsigned) ->\n  (forall ofs k p, lo <= ofs < hi -> Mem.perm m2 b2 (ofs + delta) k p) ->\n  Mem.inj_offset_aligned delta (hi-lo) ->\n  (forall b delta' ofs k p,\n   as_inj mu b = Some (b2, delta') ->\n   Mem.perm m1 b ofs k p ->\n   lo + delta <= ofs + delta' < hi + delta -> False) ->\n  exists mu',\n     Mem.inject (as_inj mu') m1' m2\n  /\\ intern_incr mu mu'\n  /\\ as_inj mu' b1 = Some(b2, delta)\n  /\\ (forall b, b <> b1 -> as_inj mu' b = as_inj mu b)\n  /\\ SM_wd mu' /\\ sm_valid mu' m1' m2\n  /\\ sm_locally_allocated mu mu' m1 m2 m1' m2\n  /\\ REACH_closed m1' (vis mu').\nProof.\n  intros. inversion H.\n  assert (AIb: as_inj mu b1 = None). eauto with mem.\n  assert (DS:= alloc_DomSrc _ _ _ SMV _ _ _ _ H0).\n  set (mu' := alloc_left_sm mu b1 b2 delta).\n  assert (intern_incr mu mu').\n    red; unfold mu'; intros. simpl.\n    intuition.\n    red; intros. destruct (eq_block b b1). subst b.\n       apply (local_in_all _ WD) in H2. congruence.\n    auto.\n  assert (Mem.mem_inj (as_inj mu') m1 m2).\n    inversion mi_inj; constructor; eauto with mem.\n    unfold mu'; intros. destruct (eq_block b0 b1).\n      subst b0.\n      elim (Mem.fresh_block_alloc _ _ _ _ _ H0). eauto with mem.\n    rewrite alloc_left_sm_as_inj_other in H8; trivial.\n      eauto.\n    unfold mu'; simpl. intros. destruct (eq_block b0 b1).\n      subst b0.\n      elim (Mem.fresh_block_alloc _ _ _ _ _ H0).\n      eapply Mem.perm_valid_block with (ofs := ofs). apply H9. generalize (size_chunk_pos chunk); omega.\n    rewrite alloc_left_sm_as_inj_other in H8; trivial.\n      eauto.\n    unfold mu'; simpl; intros. destruct (eq_block b0 b1).\n      subst b0.\n      elim (Mem.fresh_block_alloc _ _ _ _ _ H0). eauto with mem.\n    rewrite alloc_left_sm_as_inj_other in H8; trivial.\n      apply memval_inject_incr with (as_inj mu); auto.\n      apply alloc_left_sm_inject_incr; assumption.\n  exists mu'. split. constructor.\n(* inj *)\n  eapply Mem.alloc_left_mapped_inj; eauto.\n  unfold mu'; simpl. rewrite alloc_left_sm_as_inj_same; trivial.\n(* freeblocks *)\n  unfold mu'; simpl; intros. destruct (eq_block b b1). subst b.\n  elim H9. eauto with mem.\n  rewrite alloc_left_sm_as_inj_other; trivial.\n  eauto with mem.\n(* mappedblocks *)\n  unfold mu'; simpl; intros.\n  destruct (eq_block b b1).\n    subst. rewrite alloc_left_sm_as_inj_same in H9; trivial.\n     congruence. eauto.\n  rewrite alloc_left_sm_as_inj_other in H9; trivial.\n    eauto.\n(* overlap *)\n  unfold mu'; red; intros.\n  exploit Mem.perm_alloc_inv. eauto. eexact H12. intros P1.\n  exploit Mem.perm_alloc_inv. eauto. eexact H13. intros P2.\n  destruct (eq_block b0 b1); try subst b0; destruct (eq_block b3 b1); try subst b3.\n    elim H9; trivial.\n    rewrite alloc_left_sm_as_inj_same in H10; trivial.\n    inversion H10. subst b1' delta1.\n    rewrite alloc_left_sm_as_inj_other in H11; trivial.\n    destruct (eq_block b2 b2'); auto. subst b2'. right; red; intros.\n    eapply H6; eauto. omega.\n\n  rewrite alloc_left_sm_as_inj_same in H11; trivial.\n    rewrite alloc_left_sm_as_inj_other in H10; trivial.\n    inversion H11. subst b2' delta2.\n    destruct (eq_block b1' b2); auto. subst b1'. right; red; intros.\n    eapply H6; eauto. omega.\n  rewrite alloc_left_sm_as_inj_other in H10; trivial.\n  rewrite alloc_left_sm_as_inj_other in H11; trivial.\n  eauto.\n(* representable *)\n  unfold mu'; intros.\n  destruct (eq_block b b1).\n   subst.\n    rewrite alloc_left_sm_as_inj_same in H9; trivial.\n    injection H9; intros; subst b' delta0. clear H9; destruct H10.\n    exploit Mem.perm_alloc_inv; eauto; rewrite dec_eq_true; intro.\n    exploit H3. apply H4 with (k := Max) (p := Nonempty); eauto.\n    generalize (Int.unsigned_range_2 ofs). omega.\n   exploit Mem.perm_alloc_inv; eauto; rewrite dec_eq_true; intro.\n   exploit H3. apply H4 with (k := Max) (p := Nonempty); eauto.\n   generalize (Int.unsigned_range_2 ofs). omega.\n  rewrite alloc_left_sm_as_inj_other in H9; trivial.\n  eapply mi_representable; try eassumption.\n  destruct H10; eauto using Mem.perm_alloc_4.\n(* incr *)\n  split. auto.\n(* image of b1 *)\n  split. unfold mu'; simpl.\n    rewrite alloc_left_sm_as_inj_same; trivial.\n(* image of others *)\n  split. intros. unfold mu'; simpl.\n  rewrite alloc_left_sm_as_inj_other; trivial.\n(* SM_wd*)\n  split. unfold mu'. eapply alloc_left_sm_wd; try eassumption.\n (* sm_valid*)\n  split. red.\n  split; intros. unfold mu' in H9; simpl in H9.\n    unfold DOM, DomSrc in H9; simpl in H9.\n    destruct (eq_block b0 b1); try subst b0.\n      apply (Mem.valid_new_block _ _ _ _ _ H0).\n    simpl in H9.\n    apply (Mem.valid_block_alloc _ _ _ _ _ H0).\n    apply SMV. apply H9.\n  unfold mu' in H9; simpl in H9. unfold RNG, DomTgt in H9; simpl in H9.\n    destruct (eq_block b0 b2); try subst b0.\n      assumption.\n    simpl in H9.\n    apply SMV. apply H9.\n(*sm_locally_allocated*)\n  split. apply sm_locally_allocatedChar. unfold mu'; simpl.\n  repeat split; extensionality bb;\n   try rewrite (freshloc_irrefl m2);\n   try rewrite (freshloc_alloc _ _ _ _ _ H0); simpl.\n  unfold DomSrc; simpl. rewrite <- orb_assoc. rewrite orb_comm. trivial.\n  unfold DomTgt; simpl. destruct (eq_block bb b2); try subst bb; simpl.\n    rewrite Locb2. trivial.\n    intuition.\n  intuition.\n  destruct (eq_block bb b2); try subst bb; simpl.\n    rewrite Locb2. trivial.\n  intuition.\n(* REACH_closed*)\n  clear - RC H0.\n  eapply REACH_closed_alloc_left_sm; eassumption.\nQed.\n\nLemma genv_find_add_globals_fresh: forall {F V} defs (g:Genv.t F V) i\n  (G: ~ In i (map fst defs)),\n  Genv.find_symbol (Genv.add_globals g defs) i =  Genv.find_symbol g i.\nProof. intros F V defs.\n  induction defs; simpl; intros. trivial.\n  destruct a.\n  rewrite IHdefs.\n    unfold Genv.find_symbol, Genv.genv_symb. simpl. rewrite PTree.gso. reflexivity.\n    intros N. apply G; left. subst; simpl; trivial.\n  intros N. apply G; right; trivial.\nQed.\n\nLemma add_globals_find_symbol: forall {F V} (defs : list (ident * globdef F V))\n    (R: list_norepet (map fst defs)) (g: Genv.t F V) m0 m\n    (G: Genv.alloc_globals (Genv.add_globals g defs) m0 defs = Some m)\n    (N: Genv.genv_next g = Mem.nextblock m0)\n    b (VB: Mem.valid_block m b),\n    Mem.valid_block m0 b \\/\n    exists id, Genv.find_symbol (Genv.add_globals g defs) id = Some b.\nProof. intros F V defs.\ninduction defs; simpl; intros.\n  inv G. left; trivial.\nremember (Genv.alloc_global (Genv.add_globals (Genv.add_global g a) defs) m0 a) as d.\n  destruct d; inv G. apply eq_sym in Heqd.\n  inv R.\n  specialize (IHdefs H3 _ _ _ H0). simpl in *.\n  rewrite N in *.\n  assert (P: Pos.succ (Mem.nextblock m0) = Mem.nextblock m1).\n    clear IHdefs N VB H0.\n    rewrite (@Genv.alloc_global_nextblock _ _ _ _ _ _ Heqd). trivial.\n  destruct (IHdefs P _ VB); try (right; assumption).\n  clear IHdefs P VB H0.\n  destruct a. destruct g0. simpl in Heqd.\n   remember (Mem.alloc m0 0 1) as t.\n   destruct t; inv Heqd. apply eq_sym in Heqt.\n   apply (Mem.drop_perm_valid_block_2 _ _ _ _ _ _ H1) in H. clear H1.\n   apply (Mem.valid_block_alloc_inv _ _ _ _ _ Heqt) in H.\n   destruct H; subst; try (left; assumption).\n     right. apply Mem.alloc_result in Heqt. subst.\n     exists i. rewrite genv_find_add_globals_fresh; trivial.\n     unfold Genv.find_symbol, Genv.genv_symb. simpl.\n     rewrite PTree.gss. rewrite N. trivial.\nsimpl in *.\n  remember (Mem.alloc m0 0 (Genv.init_data_list_size (gvar_init v))) as t.\n  destruct t; inv Heqd. apply eq_sym in Heqt.\n  remember (store_zeros m2 b0 0 (Genv.init_data_list_size (gvar_init v))) as q.\n  destruct q; inv H1. apply eq_sym in Heqq.\n  remember (Genv.store_init_data_list\n         (Genv.add_globals (Genv.add_global g (i, Gvar v)) defs) m3 b0 0\n         (gvar_init v)) as w.\n  destruct w; inv H4. apply eq_sym in Heqw.\n  apply (Mem.drop_perm_valid_block_2 _ _ _ _ _ _ H1) in H. clear H1.\n  assert (VB3: Mem.valid_block m3 b). unfold Mem.valid_block.\n    rewrite <- (@Genv.store_init_data_list_nextblock _ _ _ _ _ _ _ _ Heqw).\n    apply H.\n  clear H Heqw.\n  assert (VB2: Mem.valid_block m2 b). unfold Mem.valid_block.\n    rewrite <- (@Genv.store_zeros_nextblock _ _ _ _ _ Heqq).\n    apply VB3.\n  clear VB3 Heqq.\n  apply (Mem.valid_block_alloc_inv _ _ _ _ _ Heqt) in VB2.\n   destruct VB2; subst; try (left; assumption).\n     right. apply Mem.alloc_result in Heqt. subst.\n     exists i. rewrite genv_find_add_globals_fresh; trivial.\n     unfold Genv.find_symbol, Genv.genv_symb. simpl.\n     rewrite PTree.gss. rewrite N. trivial.\nQed.\n\nLemma valid_init_is_global :\n  forall {F V} (prog:AST.program F V)\n         (R: list_norepet (map fst (prog_defs prog)))\n  m (G: Genv.init_mem prog = Some m)\n  b (VB: Mem.valid_block m b),\n  exists id, Genv.find_symbol (Genv.globalenv prog) id = Some b.\nProof. intros.\n  unfold Genv.init_mem, Genv.globalenv in G. simpl in *.\n  destruct (add_globals_find_symbol _ R (@Genv.empty_genv _ _ ) _ _ G (eq_refl _) _ VB)\n    as [VBEmpty | X]; trivial.\n  exfalso. clear - VBEmpty. unfold Mem.valid_block in VBEmpty.\n    rewrite Mem.nextblock_empty in VBEmpty. xomega.\nQed.\n\nLemma find_symbol_isGlobal: forall {V F} (ge : Genv.t F V) x b\n       (Find: Genv.find_symbol ge x = Some b),\n     isGlobalBlock ge b = true.\nProof. intros.\n  unfold isGlobalBlock.\n  unfold genv2blocksBool. simpl.\n  rewrite (Genv.find_invert_symbol _ _ Find). reflexivity.\nQed.\n\n\n(*New Lemma, based on (proof of) Mem.alloc_parallel_inject*)\nTheorem alloc_parallel_intern:\n  forall mu m1 m2 lo1 hi1 m1' b1 lo2 hi2\n        (SMV: sm_valid mu m1 m2) (WD: SM_wd mu),\n  Mem.inject (as_inj mu) m1 m2 ->\n  Mem.alloc m1 lo1 hi1 = (m1', b1) ->\n  lo2 <= lo1 -> hi1 <= hi2 ->\n  exists mu', exists m2', exists b2,\n  Mem.alloc m2 lo2 hi2 = (m2', b2)\n  /\\ Mem.inject (as_inj mu') m1' m2'\n  /\\ intern_incr mu mu'\n  /\\ as_inj mu' b1 = Some(b2, 0)\n  /\\ (forall b, b <> b1 -> as_inj mu' b = as_inj mu b)\n  /\\ sm_inject_separated mu mu' m1 m2\n  /\\ sm_locally_allocated mu mu' m1 m2 m1' m2'\n  /\\ SM_wd mu' /\\ sm_valid mu' m1' m2' /\\\n  (REACH_closed m1 (vis mu) -> REACH_closed m1' (vis mu')).\nProof.\n  intros.\n  case_eq (Mem.alloc m2 lo2 hi2). intros m2' b2 ALLOC.\n  exploit Mem.alloc_left_mapped_inject.\n  eapply Mem.alloc_right_inject; eauto.\n  eauto.\n  instantiate (1 := b2). eauto with mem.\n  instantiate (1 := 0). unfold Int.max_unsigned. generalize Int.modulus_pos; omega.\n  auto.\n  intros. apply Mem.perm_implies with Freeable; auto with mem.\n  eapply Mem.perm_alloc_2; eauto. omega.\n  red; intros. apply Zdivide_0.\n  intros. eapply Mem.fresh_block_alloc; try eassumption.\n          eapply SMV. eapply as_inj_DomRng in H3. eapply H3. assumption.\n  intros [j' [A [B [C D]]]].\n  exists (alloc_left_sm (alloc_right_sm mu b2) b1 b2 0).\n  assert (WDr: SM_wd (alloc_right_sm mu b2)).\n    eapply alloc_right_sm_wd; try eassumption.\n      remember (DomTgt mu b2) as d.\n      destruct d; trivial. apply eq_sym in Heqd.\n      exfalso. apply (Mem.fresh_block_alloc _ _ _ _ _ ALLOC).\n                 apply SMV. apply Heqd.\n  assert (DomSP:= alloc_DomSrc _ _ _ SMV _ _ _ _ H0).\n  assert (TgtB2: DomTgt mu b2 = false).\n    remember (DomTgt mu b2) as d.\n    destruct d; trivial; apply eq_sym in Heqd.\n    elim (Mem.fresh_block_alloc _ _ _ _ _ ALLOC).\n      apply SMV. assumption.\n  exists m2'; exists b2; auto.\n  assert (J': (as_inj (alloc_left_sm (alloc_right_sm mu b2) b1 b2 0)) = j').\n    extensionality b.\n     destruct (eq_block b b1); subst.\n        rewrite alloc_left_sm_as_inj_same, C; trivial.\n     rewrite alloc_left_sm_as_inj_other; trivial.\n        rewrite alloc_right_sm_as_inj. rewrite <- (D _ n). trivial.\n  rewrite J'. intuition.\n  split; simpl; intuition.\n  red; intros.\n       destruct (eq_block b b1); subst.\n         assert (DomSrc mu b1 = true).\n           eapply as_inj_DomRng. eapply local_in_all; eassumption.\n           assumption.\n         congruence.\n       assumption.\n(*inject_separated*)\n  red. split; intros.\n    destruct (eq_block b0 b1); subst.\n      rewrite alloc_left_sm_as_inj_same in H4. inv H4.\n      split; trivial.\n      trivial.\n      rewrite alloc_right_sm_DomSrc. assumption.\n    rewrite (D _ n) in H4. congruence.\n  split; intros. rewrite alloc_left_sm_DomSrc, alloc_right_sm_DomSrc in H4.\n    destruct (eq_block b0 b1); subst; simpl in *.\n      eapply (Mem.fresh_block_alloc _ _ _ _ _ H0).\n    congruence.\n  rewrite alloc_left_sm_DomTgt, alloc_right_sm_DomTgt in H4.\n    destruct (eq_block b0 b2); subst; simpl in *.\n      eapply (Mem.fresh_block_alloc _ _ _ _ _ ALLOC).\n    congruence.\n(*locally_separated*)\n  rewrite sm_locally_allocatedChar. unfold DomSrc, DomTgt.\n  rewrite (freshloc_alloc _ _ _ _ _ H0).\n  rewrite (freshloc_alloc _ _ _ _ _ ALLOC).\n  destruct mu; simpl. intuition.\n    extensionality b. rewrite <- orb_assoc. rewrite orb_comm. trivial.\n    extensionality b. rewrite <- orb_assoc. rewrite orb_comm. trivial.\n    extensionality b. rewrite orb_comm. trivial.\n    extensionality b. rewrite orb_comm. trivial.\n(*SM_wd*)\n  eapply alloc_left_sm_wd. assumption. apply DomSP.\n   destruct mu; simpl. destruct (eq_block b2 b2); try reflexivity.\n   elim n; trivial.\n(*sm_valid*)\n  split; intros. unfold DOM in H3. rewrite alloc_left_sm_DomSrc in H3.\n    destruct (eq_block b0 b1); simpl in *; subst.\n       eapply (Mem.valid_new_block _ _ _ _ _ H0).\n     eapply (Mem.valid_block_alloc _ _ _ _ _ H0).\n       eapply SMV. apply H3.\n  unfold RNG in H3. rewrite alloc_left_sm_DomTgt, alloc_right_sm_DomTgt in H3.\n    destruct (eq_block b0 b2); simpl in *; subst.\n       eapply (Mem.valid_new_block _ _ _ _ _ ALLOC).\n     eapply (Mem.valid_block_alloc _ _ _ _ _ ALLOC).\n       eapply SMV. apply H3.\n(*REACH_closed*)\n  eapply REACH_closed_alloc_left_sm; eassumption.\nQed.\n\nLemma freelist_right_inject: forall j m1 l m2 m2'\n       (F:Mem.free_list m2 l = Some m2')\n       (Inj : Mem.inject j m1 m2)\n       (Hyp: forall b2 lo2 hi2 (L:In ((b2,lo2),hi2) l)\n                    b1 delta ofs k p\n                    (J:j b1 = Some (b2, delta))\n                    (P: Mem.perm m1 b1 ofs k p)\n                    (OFS: lo2 <= ofs + delta < hi2),\n                    False),\n     Mem.inject j m1 m2'.\nProof. intros j m1 l.\n  induction l; simpl; intros.\n    inv F; trivial.\n  destruct a as [[b2 lo2] hi2].\n  remember (Mem.free m2 b2 lo2 hi2) as d.\n  destruct d; inv F; apply eq_sym in Heqd.\n  eapply (IHl _ _ H0).\n  eapply Mem.free_right_inject; try eassumption.\n    intros. eapply Hyp; try eassumption. left; trivial.\n  intros. eapply Hyp; try eassumption. right; trivial.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/sepcomp/submit_shmem/effect_properties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.22160411760919888}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom compcert Require Import Coqlib Integers AST Maps Values Memory Memtype Memdata.\nFrom bpf.comm Require Import MemRegion State rBPFAST.\nFrom bpf.model Require Import Semantics.\nFrom bpf.isolation Require Import AlignChunk.\nFrom Coq Require Import ZArith Lia List.\nImport ListNotations.\n\nOpen Scope Z_scope.\n\nDefinition is_byte_memval (mv: memval): Prop :=\n  match mv with\n  | Byte b => True\n  | _ => False\n  end.\n\nDefinition is_byte_block (b:block) (m:mem): Prop := \n  forall o,\n      Mem.perm m b o Cur Readable ->\n      is_byte_memval (ZMap.get o ((Mem.mem_contents m) !! b)). (**r Notation \"a !! b\" := (PMap.get b a) *)\n\nLemma is_byte_memval_iff:\n  forall mv,\n    is_byte_memval mv <-> exists b, mv = Byte b.\nProof.\n  unfold is_byte_memval; split; intros.\n  - destruct mv; try intuition.\n    exists i; reflexivity.\n  - destruct H as (b & H).\n    rewrite H.\n    constructor.\nQed.\n\nDefinition inv_memory_region (m:mem) (mr: memory_region): Prop :=\n  exists b,\n    (block_ptr mr) = Vptr b Ptrofs.zero /\\ Mem.valid_block m b /\\ is_byte_block b m /\\\n    exists base len,\n      start_addr mr = Vint base /\\ block_size mr = Vint len /\\\n      perm_order (block_perm mr) Readable /\\\n      Mem.range_perm m b 0 (Int.unsigned len) Cur (block_perm mr).\n\n(**TODO: exists start_blk, ... *)\nFixpoint disjoint_blocks (n:nat) (mrs: list memory_region): Prop :=\n  match mrs with\n  | [] => True\n  | hd :: tl => Vptr (Pos.of_nat n) Ptrofs.zero = block_ptr hd /\\ disjoint_blocks (n+1) tl\n  end.\n\nFixpoint inv_memory_regions (m:mem) (mrs: list memory_region): Prop :=\n  match mrs with\n  | [] => True\n  | hd :: tl => inv_memory_region m hd /\\ inv_memory_regions m tl\n  end.\n\nLemma In_inv_memory_regions:\n  forall mr m l,\n    List.In mr l -> inv_memory_regions m l ->\n      inv_memory_region m mr.\nProof.\n  intros.\n  induction l;\n  simpl in *.\n  inversion H.\n  destruct H.\n  - subst. intuition.\n  - apply IHl.\n    assumption.\n    intuition.\nQed.\n\nDefinition memory_inv (st: state): Prop :=\n  (1 <= mrs_num st)%nat /\\\n  List.length (bpf_mrs st) = mrs_num st /\\\n  (exists start_blk,\n    disjoint_blocks start_blk (bpf_mrs st)) /\\\n  inv_memory_regions (bpf_m st) (bpf_mrs st).\n\nFixpoint is_byte_list_memval (l: list memval): Prop :=\n  match l with\n  | nil => True\n  | hd :: tl => is_byte_memval hd /\\ is_byte_list_memval tl\n  end.\n\nLemma memval_proj_bytes_some:\n    forall l, is_byte_list_memval l ->\n      exists lb, proj_bytes l = Some lb.\nProof.\n  intros l H.\n  unfold proj_bytes.\n  induction l.\n  - exists nil; reflexivity.\n  - simpl in H.\n    destruct H.\n    apply (is_byte_memval_iff _) in H; destruct H.\n    rewrite H.\n    apply IHl in H0; destruct H0.\n    rewrite H0.\n    exists (x::x0); reflexivity.\nQed.\n\nDefinition is_vlong_or_vint (v: val): Prop :=\n  match v with\n  | Vlong _ | Vint _ => True\n  | _ => False\n  end.\n\nLemma is_vlong_or_vint_iff_some:\n  forall v, is_vlong_or_vint v <->\n    (exists vl, v = Vlong vl) \\/ exists vi, v = Vint vi.\nProof.\n  split; intros.\n  - destruct v; try inversion H.\n    + right; exists i; reflexivity.\n    + left; exists i; reflexivity.\n  - do 2 destruct H; rewrite H; apply I.\nQed.\n\nLemma decode_val_byte_some_vlong_or_vint:\n  forall chunk l,\n    is_well_chunk chunk -> \n    is_byte_list_memval l ->\n      (exists vl, decode_val chunk l = Vlong vl) \\/ (exists vi, decode_val chunk l = Vint vi).\nProof.\n  intros chunk l IWC IBLM.\n  unfold decode_val.\n  apply memval_proj_bytes_some in IBLM; destruct IBLM.\n  rewrite H.\n  destruct chunk; simpl in IWC; try contradiction.\n  - right; exists (Int.zero_ext 8 (Int.repr (decode_int x))); reflexivity.\n  - right; exists (Int.zero_ext 16 (Int.repr (decode_int x))); reflexivity.\n  - right; exists (Int.repr (decode_int x)); reflexivity.\n  - left;  exists (Int64.repr (decode_int x)); reflexivity.\nQed.\n\nLemma inv_memory_region_freeable_implies_is_byte_memval:\n  forall b m lo hi, \n    Mem.range_perm m b lo hi Cur Readable ->\n    is_byte_block b m ->\n     forall ofs, lo <= ofs < hi -> is_byte_memval (ZMap.get ofs (Mem.mem_contents m) !! b).\nProof.\n  unfold is_byte_block.\n  intros.\n  apply (H0 ofs) in H; try assumption.\nQed.\n\nLemma getN_byte_list_memval:\n  forall chunk m b lo hi, \n    Mem.range_perm m b lo hi Cur Readable -> \n    is_byte_block b m -> \n    is_well_chunk chunk ->\n      forall ofs, lo <= ofs /\\ ofs + (size_chunk chunk) < hi -> is_byte_list_memval (Mem.getN (size_chunk_nat chunk) ofs ((Mem.mem_contents m) !! b)).\nProof. \n  intro chunk.\n  assert (Ha: forall x y z n, x <= y /\\ y + (size_chunk chunk) < z -> 0 <=n <= (size_chunk chunk) -> x <= y+n < z). {\n    intros x y z n H0 H1.\n    unfold size_chunk in *; destruct chunk; try lia.\n  }\n  intros m b lo hi H0 H1 H2.\n  assert (Hb: forall ofs, lo <= ofs < hi -> is_byte_memval (ZMap.get ofs (Mem.mem_contents m) !! b)). {\n    apply (inv_memory_region_freeable_implies_is_byte_memval _ _ _ _); assumption.\n  }\n  unfold size_chunk_nat, size_chunk.\n  destruct chunk eqn:k in H2; try contradiction; subst; simpl; simpl in *; unfold is_byte_list_memval, Mem.getN; intros ofs H3.\n  - split; try (apply I).\n    apply (Hb _); assert (H4: lo <= ofs + 0 < hi -> lo <= ofs < hi); try lia.\n  - split.\n    apply (Hb _); assert (H4: lo <= ofs + 0 < hi -> lo <= ofs < hi); try lia.\n    split; try (apply I).\n    apply (Hb _); apply (Ha _ _ _ 1); lia.\n  - split.\n    apply (Hb _); assert (H4: lo <= ofs + 0 < hi -> lo <= ofs < hi); try lia.\n    split.\n    apply (Hb _); apply (Ha _ _ _ 1); lia.\n    split.\n    apply (Hb _); assert (H4: lo <= ofs + 2 < hi -> lo <= ofs+1+1 < hi); try lia.\n    split;try (apply I).\n    apply (Hb _); assert (H4: lo <= ofs + 3 < hi -> lo <= ofs+1+1+1 < hi); try lia.\n  - split.\n    apply (Hb _); assert (H4: lo <= ofs + 0 < hi -> lo <= ofs < hi); try lia.\n    split.\n    apply (Hb _); apply (Ha _ _ _ 1); lia.\n    split.\n    apply (Hb _); assert (H4: lo <= ofs + 2 < hi -> lo <= ofs+1+1 < hi); try lia.\n    split.\n    apply (Hb _); assert (H4: lo <= ofs + 3 < hi -> lo <= ofs+1+1+1 < hi); try lia.\n    split.\n    apply (Hb _); assert (H4: lo <= ofs + 4 < hi -> lo <= ofs+1+1+1+1 < hi); try lia.\n    split.\n    apply (Hb _); assert (H4: lo <= ofs + 5 < hi -> lo <= ofs+1+1+1+1+1 < hi); try lia.\n    split.\n    apply (Hb _);\n    assert (H4: lo <= ofs + 6 < hi -> lo <= ofs+1+1+1+1+1+1 < hi); try lia.\n    split.\n    apply (Hb _);\n    assert (H4: lo <= ofs + 7 < hi -> lo <= ofs+1+1+1+1+1+1+1 < hi); try lia.\n    split;try (apply I).\nQed.\n\nLemma load_some_well_chunk_vlong_or_vint:\n  forall m mr chunk b ofs v len,\n    inv_memory_region m mr ->\n    block_ptr mr = Vptr b Ptrofs.zero ->\n    block_size mr = Vint len ->\n    is_well_chunk chunk ->\n    0 <= ofs /\\ ofs + size_chunk chunk < Int.unsigned len ->\n    Mem.load chunk m b ofs = Some v ->\n      is_vlong_or_vint v.\nProof.\n  Transparent Mem.load.\n  unfold Mem.load.\n  intros m mr chunk b ofs v len IMR Hptr Hsize IWC Hrange Hload.\n  destruct IMR as [bi [Hi1 [Hi2 [Hi3 [basei [leni [Hi4 [Hi5 [Hpermi Hi6]]]]]]]]].\n  rewrite Hi1 in Hptr; inversion Hptr; subst.\n  rewrite Hi5 in Hsize; inversion Hsize; subst.\n  assert (HpermReadable: Mem.range_perm m b 0 (Int.unsigned len) Cur Readable). {\n    eapply Mem.range_perm_implies; eauto.\n  }\n\n  unfold inv_memory_region in Hload.\n  destruct (Mem.valid_access_dec _ _ _ _ _) in Hload.\n  - assert (Hiblm: forall o, \n      0%Z <= o /\\ o + (size_chunk chunk) < Int.unsigned len ->\n      is_byte_list_memval (Mem.getN (size_chunk_nat chunk) o ((Mem.mem_contents m) !! b))). {\n        apply (getN_byte_list_memval _ _ _ _ _ HpermReadable Hi3 IWC).\n    }\n    apply (Hiblm _) in Hrange.\n    inversion Hload.\n    rewrite -> H0 in *.\n    set (l := Mem.getN (size_chunk_nat chunk) ofs (Mem.mem_contents m) !! b).\n    assert (Hdecode: (exists vl, v = Vlong vl) \\/ (exists vi, v = Vint vi)). {\n      rewrite <- H0.\n      apply (decode_val_byte_some_vlong_or_vint _ _ IWC Hrange).\n    }\n    rewrite -> is_vlong_or_vint_iff_some; assumption.\n  - inversion Hload.\nQed.\n\nLemma range_perm_included:\n  forall m b p lo hi ofs_lo ofs_hi, \n    lo <= ofs_lo -> ofs_lo < ofs_hi -> ofs_hi < hi -> \n    Mem.range_perm m b lo hi Cur p ->\n      Mem.range_perm m b ofs_lo ofs_hi Cur p.\nProof.\n  intros.\n  apply (Mem.range_perm_implies _ _ _ _ _ p _). 2:{ constructor. }\n  unfold Mem.range_perm in *; intros.\n  apply H2.\n  lia.\nQed.\n\n(** Store operations *)\n\nLemma inj_bytes_is_byte_list_memval:\n  forall bl,\n    is_byte_list_memval (inj_bytes bl).\nProof.\n  unfold is_byte_list_memval, is_byte_memval.\n  induction bl.\n  - simpl. apply I.\n  - simpl.\n    split; try (apply I).\n    assumption.\nQed.\n\nLemma encode_val_is_byte_list_memval:\n  forall chunk v src\n    (Hwell_chunk: is_well_chunk chunk)\n    (Hvlong: exists vl, v = Vlong vl)\n    (Hvint_vlong: vlong_to_vint_or_vlong chunk v = src),\n    is_byte_list_memval (encode_val chunk src).\nProof.\n  unfold vlong_to_vint_or_vlong.\n  intros.\n  destruct Hvlong as [vl Hvlong].\n  rewrite -> Hvlong in Hvint_vlong.\n  destruct chunk in *; try inversion Hwell_chunk; rewrite <- Hvint_vlong; simpl; try apply (inj_bytes_is_byte_list_memval _).\nQed.\n\nLemma encode_val_is_byte_list_memval_vint:\n  forall chunk v src\n    (Hwell_chunk: is_well_chunk chunk)\n    (Hvint: exists vi, v = Vint vi)\n    (Hvint_vlong: vint_to_vint_or_vlong chunk v = src),\n    is_byte_list_memval (encode_val chunk src).\nProof.\n  unfold vint_to_vint_or_vlong.\n  intros.\n  destruct Hvint as [vl Hvint].\n  rewrite -> Hvint in Hvint_vlong.\n  destruct chunk in *; try inversion Hwell_chunk; rewrite <- Hvint_vlong; simpl; try apply (inj_bytes_is_byte_list_memval _).\nQed.\n\nLemma setN_other_is_byte_list_memval:\n  forall vl c p q,\n    is_byte_list_memval vl ->\n    is_byte_memval (ZMap.get q c) ->\n    p <= q < p + Z_of_nat (length vl) ->\n      is_byte_memval (ZMap.get q (Mem.setN vl p c)).\nProof.\n  induction vl; intros; unfold is_byte_list_memval, is_byte_memval in *; simpl.\n  - assumption.\n  - destruct (zeq p q).\n    + subst q.\n      rewrite Mem.setN_outside.\n      * rewrite ZMap.gss.\n        destruct H as [Ha H]; assumption.\n      * left; lia.\n    + apply IHvl.\n      * destruct H as [Ha H]; assumption.\n      * rewrite ZMap.gso.\n        assumption.\n        lia.\n      * simpl length in H1; rewrite inj_S in H1.\n        lia.\nQed.\n\nLemma get_setN_is_byte_list_memval:\n  forall vl c p q,\n    is_byte_list_memval vl ->\n    is_byte_memval (ZMap.get q c) ->\n    ~(p <= q < p + Z_of_nat (length vl)) ->\n      is_byte_memval (ZMap.get q (Mem.setN vl p c)).\nProof.\n  intros; unfold is_byte_list_memval, is_byte_memval in *; simpl.\n  destruct (zle p q).\n  destruct (zlt q (p + Z.of_nat (length vl))).\n  - apply (setN_other_is_byte_list_memval _ _ _ _ H H0).\n    split; assumption.\n  - rewrite Mem.setN_outside.\n    assumption.\n    right; assumption.\n  - rewrite Mem.setN_outside.\n    assumption.\n    left; lia.\nQed.\n\n\nLemma setN_is_byte_list_memval:\n  forall vl c p q,\n    is_byte_list_memval vl ->\n    is_byte_memval (ZMap.get q c) ->\n      is_byte_memval (ZMap.get q (Mem.setN vl p c)).\nProof.\n  intros.\n  destruct (zle p q).\n  destruct (zlt q (p + Z_of_nat (length vl))).\n  - apply (setN_other_is_byte_list_memval _ _ _ _ H H0).\n    split; assumption.\n  - apply (get_setN_is_byte_list_memval _ _ _ _ H H0).\n    lia.\n  - apply (get_setN_is_byte_list_memval _ _ _ _ H H0).\n    lia.\nQed.\n\nLemma store_is_byte_block:\n  forall chunk m1 blk ofs v m2\n    (Hwell_chunk: is_well_chunk chunk)\n    (Hvlong: exists vl, v = Vlong vl)\n    (Hstore: Mem.store chunk m1 blk ofs (vlong_to_vint_or_vlong chunk v) = Some m2)\n    (His_byte: is_byte_block blk m1),\n      is_byte_block blk m2.\nProof.\n  intros.\n  unfold is_byte_block.\n  intros o Hperm.\n  apply (Mem.perm_store_2 _ _ _ _ _ _ Hstore) in Hperm.\n  apply His_byte in Hperm.\n  \n  Transparent Mem.store.\n  unfold Mem.store in Hstore.\n  destruct (Mem.valid_access_dec _ _ _ _ _) in Hstore. 2:{ inversion Hstore. }\n  inversion Hstore; clear Hstore H0.\n  simpl.\n\n  assert (His_byte_list: is_byte_list_memval (encode_val chunk (vlong_to_vint_or_vlong chunk v))). {\n    apply (encode_val_is_byte_list_memval _ _ _ Hwell_chunk Hvlong); reflexivity.\n  }\n  rewrite PMap.gss.\n  apply (setN_is_byte_list_memval _ _ _ _ His_byte_list Hperm).\nQed.\n\nLemma store_is_byte_block_vint:\n  forall chunk m1 blk ofs v m2\n    (Hwell_chunk: is_well_chunk chunk)\n    (HVint: exists vi, v = Vint vi)\n    (Hstore: Mem.store chunk m1 blk ofs (vint_to_vint_or_vlong chunk v) = Some m2)\n    (His_byte: is_byte_block blk m1),\n      is_byte_block blk m2.\nProof.\n  intros.\n  unfold is_byte_block.\n  intros o Hperm.\n  apply (Mem.perm_store_2 _ _ _ _ _ _ Hstore) in Hperm.\n  apply His_byte in Hperm.\n  \n  Transparent Mem.store.\n  unfold Mem.store in Hstore.\n  destruct (Mem.valid_access_dec _ _ _ _ _) in Hstore. 2:{ inversion Hstore. }\n  inversion Hstore; clear Hstore H0.\n  simpl.\n\n  assert (His_byte_list: is_byte_list_memval (encode_val chunk (vint_to_vint_or_vlong chunk v))). {\n    apply (encode_val_is_byte_list_memval_vint _ _ _ Hwell_chunk HVint); reflexivity.\n  }\n  rewrite PMap.gss.\n  apply (setN_is_byte_list_memval _ _ _ _ His_byte_list Hperm).\nQed.\n\nLemma store_is_byte_block_disjoint:\n  forall chunk m1 m2 b1 b2 ofs v,\n    is_byte_list_memval (encode_val chunk v) ->\n    Mem.store chunk m1 b1 ofs v = Some m2 ->\n    b1 <> b2 ->\n    is_byte_block b1 m1 ->\n    is_byte_block b2 m1 ->\n      is_byte_block b2 m2.\nProof.\n  unfold is_byte_block.\n  intros.\n  assert (H5:= H0).\n  unfold Mem.store in H0.\n  destruct (Mem.valid_access_dec _ _ _ _ _); try inversion H0.\n  simpl.\n  rewrite PMap.gso. 2:{ lia. }\n  apply H3.\n  apply (Mem.perm_store_2 _ _ _ _ _ _ H5).\n  assumption.\nQed.\n\nLemma store_is_region_freeable_disjoint:\n  forall chunk m1 m2 b1 b2 ofs v lo_1 hi_1 lo_2 hi_2 p,\n    is_byte_list_memval (encode_val chunk v) ->\n    Mem.store chunk m1 b1 ofs v = Some m2 ->\n    b1 <> b2 ->\n    Mem.range_perm m1 b1 lo_1 hi_1 Cur p ->\n    Mem.range_perm m1 b2 lo_2 hi_2 Cur p ->\n      Mem.range_perm m2 b2 lo_2 hi_2 Cur p.\nProof.\n  unfold Mem.range_perm.\n  intros.\n  apply H3 in H4.\n  apply (Mem.perm_store_1 _ _ _ _ _ _ H0 _ _ _ _ H4).\nQed.\n\nLemma store_memory_region_including:\n  forall m1 m2 mr1 mr2 b1 b2 len1 len2 chunk ofs v,\n    inv_memory_region m1 mr1 ->\n    block_ptr mr1 = Vptr b1 Ptrofs.zero ->\n    block_size mr1 = Vint len1 ->\n    inv_memory_region m1 mr2 ->\n    block_ptr mr2 = Vptr b2 Ptrofs.zero ->\n    block_size mr2 = Vint len2 ->\n    b1 <> b2 ->\n    Mem.store chunk m1 b1 ofs v = Some m2 ->\n    is_byte_list_memval (encode_val chunk v) ->\n    inv_memory_region m2 mr2.\nProof.\n  intros.\n  destruct H as [blk1 [Hptr1 [Hvalid_blk1 [Hbyte1 [start1 [len_1 [Haddr1 [Hlen1 Hperm1]]]]]]]].\n  rewrite Hptr1 in H0; inversion H0; subst blk1; clear H0.\n  rewrite Hlen1 in H1; inversion H1; subst len_1; clear H1.\n  \n  destruct H2 as [blk2 [Hptr2 [Hvalid_blk2 [Hbyte2 [start2 [len_2 [Haddr2 [Hlen2 Hperm2]]]]]]]].\n  rewrite Hptr2 in H3; inversion H3; subst blk2; clear H3.\n  rewrite Hlen2 in H4; inversion H4; subst len_2; clear H4.\n\n  unfold inv_memory_region.\n  exists b2.\n  split; try assumption.\n  split.\n  apply (Mem.store_valid_block_1 _ _ _ _ _ _ H6 _ Hvalid_blk2).\n  split.\n  apply (store_is_byte_block_disjoint _ _ _ _ _ _ _ H7 H6 H5 Hbyte1 Hbyte2).\n  exists start2, len2.\n  split; try assumption.\n  split; try assumption.\n  unfold Mem.range_perm in *.\n  split; [intuition | idtac].\n  intros ofs0 Hofs0_range.\n  apply Hperm2 in Hofs0_range.\n  apply (Mem.perm_store_1 _ _ _ _ _ _ H6); assumption.\nQed.\n\n\n\n(*\nDefinition inv_memory_regions_state (st: state) := inv_memory_regions (eval_mem st) (eval_mem_regions st). *)\n\n(** alu: upd_reg wiil never have effect on memory and memory regions *)\nLemma mem_inv_upd_reg_mem:\n  forall st1 st2 r n\n    (Halu: upd_reg r (Vlong n) st1 = st2),\n      eval_mem st1 = eval_mem st2.\nProof.\n  unfold upd_reg, eval_mem; intros.\n  inversion Halu.\n  simpl; reflexivity.\nQed.\n\nLemma mem_inv_upd_reg_memregions:\n  forall st1 st2 r n\n    (Halu: upd_reg r (Vlong n) st1 = st2),\n      eval_mem_regions st1 = eval_mem_regions st2.\nProof.\n  unfold upd_reg, eval_mem_regions; intros.\n  inversion Halu.\n  simpl; reflexivity.\nQed.\n\n(** alu: upd_flag wiil have no effect on memory and memory regions *)\nLemma mem_inv_upd_flag_mem:\n  forall st1 st2 f\n    (Halu: upd_flag f st1 = st2),\n      eval_mem st1 = eval_mem st2.\nProof.\n  unfold upd_flag, eval_mem; intros.\n  inversion Halu.\n  simpl; reflexivity.\nQed.\n\nLemma mem_inv_upd_flag_memregions:\n  forall st1 st2 f\n    (Halu: upd_flag f st1 = st2),\n      eval_mem_regions st1 = eval_mem_regions st2.\nProof.\n  unfold upd_flag, eval_mem_regions; intros.\n  inversion Halu.\n  simpl; reflexivity.\nQed.\n\nLemma mem_inv_upd_mem_mem:\n  forall st1 st2 m\n    (Hmem: upd_mem m st1 = st2),\n      eval_mem st2 = m.\nProof.\n  unfold upd_mem, eval_mem; intros.\n  inversion Hmem.\n  simpl; reflexivity.\nQed.\n\nLemma mem_inv_upd_mem_memregions:\n  forall st1 st2 m\n    (Hmem: upd_mem m st1 = st2),\n      eval_mem_regions st1 = eval_mem_regions st2.\nProof.\n  unfold upd_mem, eval_mem_regions; intros.\n  inversion Hmem.\n  simpl; reflexivity.\nQed.\n\nLemma mem_inv_upd_pc_incr_mem:\n  forall st1 st2\n    (Hpc: upd_pc_incr st1 = st2),\n      eval_mem st1 = eval_mem st2.\nProof.\n  unfold upd_pc_incr, eval_mem; intros.\n  inversion Hpc.\n  simpl; reflexivity.\nQed.\n\nLemma mem_inv_upd_pc_incr_memregions:\n  forall st1 st2\n    (Hpc: upd_pc_incr st1 = st2),\n      eval_mem_regions st1 = eval_mem_regions st2.\nProof.\n  unfold upd_pc_incr, eval_mem_regions; intros.\n  inversion Hpc.\n  simpl; reflexivity.\nQed.\n\nLemma mem_inv_upd_pc_mem:\n  forall st1 st2 p\n    (Hpc: upd_pc p st1 = st2),\n      eval_mem st1 = eval_mem st2.\nProof.\n  unfold upd_pc, eval_mem; intros.\n  inversion Hpc.\n  simpl; reflexivity.\nQed.\n\nLemma mem_inv_upd_pc_memregions:\n  forall st1 st2 p\n    (Hpc: upd_pc p st1 = st2),\n      eval_mem_regions st1 = eval_mem_regions st2.\nProof.\n  unfold upd_pc, eval_mem_regions; intros.\n  inversion Hpc.\n  simpl; reflexivity.\nQed.\n\nLemma mem_inv_upd_reg:\n  forall st1 st2 r n\n    (Hmem_inv: memory_inv st1)\n    (Halu: upd_reg r (Vlong n) st1 = st2),\n      memory_inv st2.\nProof.\n  unfold memory_inv, upd_reg.\n  intros.\n  rewrite <- Halu.\n  simpl.\n  assumption.\nQed.\n\nLemma mem_inv_upd_flag:\n  forall st1 st2 f\n    (Hmem_inv: memory_inv st1)\n    (Hflag: upd_flag f st1 = st2),\n      memory_inv st2.\nProof.\n  unfold memory_inv, upd_flag.\n  intros.\n  rewrite <- Hflag.\n  simpl.\n  assumption.\nQed.\n\nLemma Mem_range_perm_store:\n  forall m m0 b b0 lo hi k p chunk i v\n  (Hrange_perm : Mem.range_perm m0 b0 lo hi k p)\n  (Hstore : Mem.store chunk m0 b i v = Some m),\n    Mem.range_perm m b0 lo hi k p.\nProof.\n  unfold Mem.range_perm.\n  intros.\n  eapply Mem.perm_store_1; eauto.\nQed.\n\nLemma mem_inv_store_mem_regions_vlong:\n  forall m m0 chunk l b i vl\n    (Hwell_chunk: is_well_chunk chunk)\n    (Hmem_inv : inv_memory_regions m0 l)\n    (Hstore: Mem.store chunk m0 b (Ptrofs.unsigned i) (vlong_to_vint_or_vlong chunk (Vlong vl)) = Some m),\n      inv_memory_regions m l.\nProof.\n  induction l.\n  simpl; intros.\n  constructor.\n\n  simpl; intros.\n  destruct Hmem_inv as (Hmem_inv_mr & Hmem_inv_mrs).\n  split.\n  -\n    unfold inv_memory_region in *.\n    destruct Hmem_inv_mr as (b0 & Hptr & Hvalid & Hbyte & base & len & Hstart & Hsize & Hperm & Hrange_perm).\n    exists b0.\n    repeat (split; [try assumption | idtac]).\n    + eapply Mem.store_valid_block_1; eauto.\n    + destruct ((b =? b0)%positive) eqn: Hb_eq.\n      * rewrite Pos.eqb_eq in Hb_eq.\n        subst.\n        eapply store_is_byte_block; eauto.\n      * rewrite Pos.eqb_neq in Hb_eq.\n        unfold is_byte_block in *.\n        erewrite Mem.store_mem_contents; eauto.\n        erewrite PMap.gso; eauto.\n        intros.\n        apply Hbyte.\n        eapply Mem.perm_store_2; eauto.\n    + exists base, len.\n      repeat (split; [try assumption | idtac]).\n      eapply Mem_range_perm_store; eauto.\n  - eapply IHl; eauto.\nQed.\n\nLemma mem_inv_store_mem_regions_vint:\n  forall m m0 chunk l b i vl\n    (Hwell_chunk: is_well_chunk chunk)\n    (Hmem_inv : inv_memory_regions m0 l)\n    (Hstore: Mem.store chunk m0 b (Ptrofs.unsigned i) (vint_to_vint_or_vlong chunk (Vint vl)) = Some m),\n      inv_memory_regions m l.\nProof.\n  induction l.\n  simpl; intros.\n  constructor.\n\n  simpl; intros.\n  destruct Hmem_inv as (Hmem_inv_mr & Hmem_inv_mrs).\n  split.\n  -\n    unfold inv_memory_region in *.\n    destruct Hmem_inv_mr as (b0 & Hptr & Hvalid & Hbyte & base & len & Hstart & Hsize & Hperm & Hrange_perm).\n    exists b0.\n    repeat (split; [try assumption | idtac]).\n    + eapply Mem.store_valid_block_1; eauto.\n    + destruct ((b =? b0)%positive) eqn: Hb_eq.\n      * rewrite Pos.eqb_eq in Hb_eq.\n        subst.\n        eapply store_is_byte_block_vint with (v:= Vint vl); eauto.\n      * rewrite Pos.eqb_neq in Hb_eq.\n        unfold is_byte_block in *.\n        erewrite Mem.store_mem_contents; eauto.\n        erewrite PMap.gso; eauto.\n        intros.\n        apply Hbyte.\n        eapply Mem.perm_store_2; eauto.\n    + exists base, len.\n      repeat (split; [try assumption | idtac]).\n      eapply Mem_range_perm_store; eauto.\n  - eapply IHl; eauto.\nQed.\n\nLemma mem_inv_store_length:\n  forall st1 st2 m chunk b i vl\n    (Hmem_inv : Datatypes.length (bpf_mrs st1) = mrs_num st1)\n    (Hstore: Mem.store chunk (bpf_m st1) b (Ptrofs.unsigned i) (vlong_to_vint_or_vlong chunk (Vlong vl)) = Some m)\n    (Hst2: upd_mem m st1 = st2),\n      Datatypes.length (bpf_mrs st2) = mrs_num st2.\nProof.\n  intros.\n  subst.\n  unfold upd_mem, bpf_mrs in *.\n  intuition.\nQed.\n\nLemma mem_inv_store_disjoint:\n  forall st1 st2 m chunk b i vl\n    (Hmem_inv : disjoint_blocks 0 (bpf_mrs st1))\n    (Hstore: Mem.store chunk (bpf_m st1) b (Ptrofs.unsigned i) (vlong_to_vint_or_vlong chunk (Vlong vl)) = Some m)\n    (Hst2: upd_mem m st1 = st2),\n      disjoint_blocks 0 (bpf_mrs st2).\nProof.\n  intros.\n  subst.\n  unfold upd_mem, bpf_mrs in *.\n  intuition.\nQed.\n\nLemma mem_inv_store_length_vint:\n  forall st1 st2 m chunk b i vl\n    (Hmem_inv : Datatypes.length (bpf_mrs st1) = mrs_num st1)\n    (Hstore: Mem.store chunk (bpf_m st1) b (Ptrofs.unsigned i) (vint_to_vint_or_vlong chunk (Vint vl)) = Some m)\n    (Hst2: upd_mem m st1 = st2),\n      Datatypes.length (bpf_mrs st2) = mrs_num st2.\nProof.\n  intros.\n  subst.\n  unfold upd_mem, bpf_mrs in *.\n  intuition.\nQed.\n\nLemma mem_inv_store_disjoint_vint:\n  forall st1 st2 m chunk b i vl blk\n    (Hmem_inv : disjoint_blocks blk (bpf_mrs st1))\n    (Hstore: Mem.store chunk (bpf_m st1) b (Ptrofs.unsigned i) (vint_to_vint_or_vlong chunk (Vint vl)) = Some m)\n    (Hst2: upd_mem m st1 = st2),\n      disjoint_blocks blk (bpf_mrs st2).\nProof.\n  intros.\n  subst.\n  unfold upd_mem, bpf_mrs in *.\n  intuition.\nQed.\n\nLemma store_mem_reg_well_chunk:\n  forall st1 chunk addr src\n    (Hwell_chunk: is_well_chunk chunk),\n    store_mem_reg addr chunk (Vlong src) st1 =\n    match\n      Mem.storev chunk (bpf_m st1) addr (vlong_to_vint_or_vlong chunk (Vlong src))\n    with\n    | Some m => Some (upd_mem m st1)\n    | None => None\n    end.\nProof.\n  unfold is_well_chunk, store_mem_reg; intros.\n  destruct chunk; try inversion Hwell_chunk.\n  all: reflexivity.\nQed.\n\nLemma mem_inv_store_reg:\n  forall st1 st2 chunk addr src\n    (Hwell_chunk: is_well_chunk chunk)\n    (Hmem_inv: memory_inv st1)\n    (Hstore: store_mem_reg addr chunk (Vlong src) st1 = Some st2),\n      memory_inv st2.\nProof.\n  intros.\n  rewrite store_mem_reg_well_chunk in Hstore; [| assumption].\n  unfold vlong_to_vint_or_vlong, Mem.storev in Hstore.\n  assert (Hmem_inv' := Hmem_inv).\n  unfold memory_inv in Hmem_inv'.\n  destruct Hmem_inv' as (Hmem_inv_low & Hmem_inv_length & Hmem_inv_disjoint &_ ).\n  unfold memory_inv.\n\n  destruct addr; try inversion Hstore; clear Hstore.\n  destruct Mem.store eqn: Hstore; try inversion H0.\n  clear H0.\n\n  split.\n  unfold upd_mem; simpl; assumption.\n  split.\n  eapply mem_inv_store_length; eauto.\n  split.\n  destruct Hmem_inv_disjoint as (start_blk & Hmem_inv_disjoint).\n  exists start_blk. unfold upd_mem; simpl. assumption.\n\n  subst.\n  clear Hmem_inv_length Hmem_inv_disjoint.\n  eapply mem_inv_store_mem_regions_vlong; eauto.\n  unfold memory_inv in Hmem_inv.\n  intuition.\nQed.\n\nLemma mem_inv_store_imm_well_chunk:\n  forall st1 chunk addr i\n    (Hwell_chunk: is_well_chunk chunk),\n      store_mem_imm addr chunk (Vint i) st1 =\n       match\n         match addr with\n         | Vptr b ofs =>\n             Mem.store chunk (bpf_m st1) b (Ptrofs.unsigned ofs)\n               (vint_to_vint_or_vlong chunk (Vint i))\n         | _ => None\n         end\n       with\n       | Some m => Some (upd_mem m st1)\n       | None => None\n       end.\nProof.\n  unfold is_well_chunk, store_mem_imm; intros.\n  destruct chunk; try inversion Hwell_chunk.\n  all: reflexivity.\nQed.\n\nLemma mem_inv_store_imm:\n  forall st1 st2 chunk addr i\n    (Hwell_chunk: is_well_chunk chunk)\n    (Hmem_inv: memory_inv st1)\n    (Hstore: store_mem_imm addr chunk (Vint i) st1 = Some st2),\n      memory_inv st2.\nProof.\n  intros.\n  rewrite mem_inv_store_imm_well_chunk in Hstore; [| assumption].\n  unfold rBPFAST.vlong_to_vint_or_vlong, Mem.storev in Hstore.\n  assert (Hmem_inv' := Hmem_inv).\n  unfold memory_inv in Hmem_inv'.\n  destruct Hmem_inv' as (Hmem_inv_low & Hmem_inv_length & Hmem_inv_disjoint &_ ).\n  unfold memory_inv.\n\n  destruct addr; try inversion Hstore; clear Hstore.\n  destruct (Mem.store chunk (bpf_m st1) b (Ptrofs.unsigned i0)) eqn: Hstore; try inversion H0.\n  clear H0.\n\n  unfold upd_mem; simpl.\n  split; [assumption |].\n  split; [assumption |].\n  split; [assumption |].\n\n  subst.\n  clear Hmem_inv_length Hmem_inv_disjoint.\n  eapply mem_inv_store_mem_regions_vint; eauto.\n  unfold memory_inv in Hmem_inv.\n  intuition.\nQed.\n\n\nLemma mem_inv_upd_pc:\n  forall st1 st2 p\n    (Hmem_inv: memory_inv st1)\n    (Hpc: upd_pc p st1 = st2),\n      memory_inv st2.\nProof.\n  unfold memory_inv.\n  intros.\n  rewrite <- Hpc.\n  simpl; assumption.\nQed.\n\nLemma mem_inv_upd_pc_incr:\n  forall st1 st2\n    (Hmem_inv: memory_inv st1)\n    (Hpc: upd_pc_incr st1 = st2),\n      memory_inv st2.\nProof.\n  unfold memory_inv.\n  intros.\n  rewrite <- Hpc.\n  simpl; assumption.\nQed.\n\nClose Scope Z_scope.", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/isolation/MemInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.22158371806695448}}
{"text": "Require Import ssreflect.\nRequire Import Coq.Classes.EquivDec.\nRequire Import Metalib.Metatheory.\n\nRequire Import Coq.Structures.Orders.\nRequire Import Coq.Bool.Sumbool.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Classes.RelationClasses.\n\nRequire Import dqtt_ott.\nRequire Import dqtt_inf.\nRequire Import usage.\nRequire Import dctx.\nRequire Import dctx_sub.\nRequire Import semimodule.\nRequire Import tactics.\n\nRequire Import beta.\nRequire Import structural.\n\n(* ------------------------------------------------------- *)\n\nLemma invert_Type {D G A} :\n  Typing D G a_Type A -> \n  exists G1, Beta (subst_def D A) a_Type /\\ ctx_mul 0 G1 = G1 /\\ ctx_sub D G1 G.\nProof.\n  intros HA.\n  dependent induction HA.\n  - destruct IHHA as [G3 [h0 [ h1 h2]]]; auto.\n    exists G3. subst. repeat split; auto. transitivity G1; auto.\n  - exists nil. repeat split; auto.\n\n  - (* T_weak *) destruct IHHA1 as [G3 [h0 [h1 h2]]]; auto. clear IHHA2.\n    exists (x ~ (0, Tm A) ++ G3). repeat split; auto. simpl.  ring_simpl. f_equal.  auto. \n    econstructor; auto. reflexivity.\n  - (* T_weak_def *) destruct IHHA1 as [G3 [h0 [h1 h2]]]; auto. clear IHHA2.\n    exists (x ~ (0, Def a A) ++ G3).\n    repeat split. asimpl.\n    erewrite subst_def_subst_tm_tm; eauto.\n    replace a_Type with (subst_tm_tm (subst_def D5 a) x a_Type); try reflexivity.\n    eapply subst_Beta1. eapply subst_def_lc_tm; eauto using Typing_lc_ctx, Typing_lc. auto.\n    eauto using Typing_ctx_wff_regularity.\n    asimpl. f_equal. auto.\n    econstructor; auto. reflexivity.\n  - destruct IHHA1 as [G3 [h0 [h1 h2]]]; auto.\n    exists G3. repeat split; auto.\n    asimpl.\n    eapply B_Trans. eapply B_Sym. eauto. eauto.\nQed.\n\n\nLemma invert_Unit {D G A} :\n  Typing D G a_TmUnit A -> \n  exists G1, Beta (subst_def D A) a_TyUnit /\\ ctx_mul 0 G1 = G1 /\\ ctx_sub D G1 G.\nProof.\n  intros HA.\n  dependent induction HA.\n  - destruct IHHA as [G3 [h0 [ h1 h2]]]; auto.\n    exists G3. subst. repeat split; auto. transitivity G1; auto.\n  - (* T_weak *) destruct IHHA1 as [G3 [h0 [h1 h2]]]; auto. clear IHHA2.\n    exists (x ~ (0, Tm A) ++ G3). repeat split; auto. simpl.  ring_simpl. f_equal.  auto. \n    econstructor; auto. reflexivity.\n  - (* T_weak_def *) destruct IHHA1 as [G3 [h0 [h1 h2]]]; auto. clear IHHA2.\n    exists (x ~ (0, Def a A) ++ G3).\n    repeat split.\n    asimpl. \n    erewrite subst_def_subst_tm_tm; eauto.\n    replace a_TyUnit with (subst_tm_tm (subst_def D5 a) x a_TyUnit); try reflexivity.\n    eapply subst_Beta1. eapply subst_def_lc_tm; eauto using Typing_lc_ctx, Typing_lc. auto.\n    eauto using Typing_ctx_wff_regularity.\n    asimpl. f_equal. auto.\n    econstructor; auto. reflexivity.\n  - destruct IHHA1 as [G3 [h0 [h1 h2]]]; auto.\n    exists G3. repeat split; auto.\n    asimpl.\n    eapply B_Trans. eapply B_Sym. eauto. eauto.\n  - exists nil. repeat split; auto.\nQed.\n\nLemma invert_box {D G q a A} :\n Typing D G (a_box q a) A -> \n exists A0,  \n   Beta (subst_def D A) (a_Box q (subst_def D A0)) /\\\n   exists G0, ctx_sub D (ctx_mul q G0) G /\\ Typing D G0 a A0.\nProof.\n  intros HA.\n  dependent induction HA.\n  + edestruct IHHA as [A0 [HB [G0 [SS TA]]]]. eauto.\n    eexists. split. eauto.\n    exists G0. split.\n    transitivity G1; auto. auto.\n  + (* T_weak *) clear IHHA2.\n    specialize (IHHA1 q a ltac:(auto)).\n    move: IHHA1 => [A0 [HB [G0 [SS TA]]]].\n    exists A0. split. asimpl. auto.\n    exists (x ~ (0, Tm A) ++ G0). split.\n    econstructor. auto. rewrite qmul_0_r. reflexivity.\n    eauto. eauto.\n    eapply T_weak. eauto. auto. eauto.\n  + (* T_weak_def *) clear IHHA2.\n    specialize (IHHA1 q a ltac:(auto)).\n    move: IHHA1 => [A0 [HB [G0 [SS TA]]]].\n    exists A0. split. asimpl.\n          erewrite subst_def_subst_tm_tm; eauto using Typing_ctx_wff_regularity.\n          erewrite subst_def_subst_tm_tm; eauto using Typing_ctx_wff_regularity.\n          replace (a_Box q (subst_tm_tm (subst_def D5 a0) x (subst_def D5 A0))) with  (subst_tm_tm (subst_def D5 a0) x (a_Box q (subst_def D5 A0))); try reflexivity.\n      eapply subst_Beta1. eauto using subst_def_lc_tm, Typing_lc_ctx, Typing_lc. auto.\n    exists (x ~ (0, Def a0 A) ++ G0). split.\n    econstructor. auto. rewrite qmul_0_r. reflexivity.\n    eauto. eauto.\n    eapply T_weak_def. eauto. auto. eauto.\n  + clear IHHA2.\n    specialize (IHHA1 q a ltac:(auto)).\n    move: IHHA1 => [A0 [HB [G0 [SS TA]]]].\n    eexists.  split. eapply B_Trans. eapply B_Sym; eauto. eauto.\n    eexists. split. eauto. auto.\n  + clear IHHA.    \n    eexists.  split. \n    rewrite <- subst_def_Box.\n    eapply subst_def_Beta; eauto using Typing_lc_ctx.\n    eapply B_Refl. econstructor. eapply Typing_lc2; eauto.\n    exists G. split.\n    eapply ctx_sub_refl. eclarify_ctx. eauto.\nQed.    \n\nLemma invert_Box {D G q A B} :\n   Typing D G (a_Box q A) B -> \n   Beta (subst_def D B) a_Type /\\ Typing D G A a_Type.\nProof.\n  intros HA. \n  dependent induction HA; intros.\n  + specialize (IHHA _ _ ltac:(auto)). destruct IHHA.\n    split. auto.\n    eapply T_sub; eauto.\n  + specialize (IHHA1 _ _ ltac:(auto)). destruct IHHA1.\n    split. auto.\n    eapply T_weak; eauto.\n  + specialize (IHHA1 _ _ ltac:(auto)). destruct IHHA1.\n    split. asimpl.\n    erewrite subst_def_subst_tm_tm; eauto.\n    replace a_Type with (subst_tm_tm (subst_def D5 a) x a_Type); try reflexivity.\n    eapply subst_Beta1. eapply subst_def_lc_tm; eauto using Typing_lc_ctx, Typing_lc. auto.\n    eauto using Typing_ctx_wff_regularity.\n    eapply T_weak_def; eauto.\n  + specialize (IHHA1 _ _ ltac:(auto)). destruct IHHA1.\n    split. eapply B_Trans. eapply B_Sym. eauto. eauto. auto.\n  + clear IHHA.\n    split. \n    rewrite subst_def_Type.\n    eapply B_Refl. eauto. eauto.\nQed.\n\n\nLemma invert_Pi : forall D G q A B A0,\n  Typing D G (a_Pi q A B) A0 ->\n  Beta (subst_def D A0) a_Type /\\\n  exists G1, exists G2, exists r,\n      ctx_sub D (ctx_plus G1 G2) G /\\\n      Typing D G1 A a_Type /\\\n      forall x, x `notin` dom D \\u fv_tm_tm (subst_def D B) ->\n           Typing ([(x, Tm A)] ++ D) ([(x, (r, Tm A))] ++ G2)\n                  (open_tm_wrt_tm B (a_Var_f x)) a_Type.\nProof.\nintros.\ndependent induction H.  \n- (* sub *) \n  move: (IHTyping _ _ _ ltac:(reflexivity)) => [E [G1' [G2' [r [? [? ?]]]]]].\n  split; auto.\n  eexists. eexists. eexists.\n  split; eauto.\n  transitivity G1; auto.\n- (* weak *) \n  move: (IHTyping1 _ _ _ ltac:(reflexivity)) => [E [G1' [G2' [r [? [? hb]]]]]].\n  split; auto.\n  clear IHTyping1 IHTyping2.\n  exists (x ~ (0,Tm A0) ++ G1'). exists (x ~ (0,Tm A0) ++ G2'). eexists.\n  repeat split.\n  + asimpl.\n    econstructor; eauto.\n    reflexivity. \n  + eapply T_weak; eauto.\n  + intros y Fr.\n    asimpl in Fr.\n    specialize (hb y ltac:(auto)). \n    eapply weakening. eapply hb. \n    move: (Typing_ctx hb) => CB.\n    destruct_ctx.\n    eclarify_ctx. \n    simpl_env. fsetdec.\n    eauto.\n- (* weak def *)\n  move: (IHTyping1 _ _ _ ltac:(reflexivity)) => [E [G1' [G2' [r [? [? hb]]]]]].\n  clear IHTyping1 IHTyping2.\n  split. \n  (* Beta equal to Type *)\n  asimpl. \n  erewrite subst_def_subst_tm_tm; eauto.\n  replace a_Type with (subst_tm_tm (subst_def D5 a) x a_Type); try reflexivity.\n  eapply subst_Beta1. eapply subst_def_lc_tm; eauto using Typing_lc_ctx, Typing_lc. auto.\n  eauto using Typing_ctx_wff_regularity.\n\n  exists (x ~ (0,Def a A0) ++ G1'). exists (x ~ (0,Def a A0) ++ G2'). eexists.\n  repeat split.\n  + asimpl.\n    econstructor; eauto.\n    reflexivity. \n  + eapply T_weak_def; eauto.\n  + intros y Fr.\n    asimpl in Fr.\n    rewrite <- fv_subst_def_lower in Fr; eauto using Typing_ctx_wff_regularity.\n    rewrite <- fv_tm_tm_subst_tm_tm_lower in Fr.\n    specialize (hb y).\n    rewrite -> fv_subst_def in hb; eauto using Typing_ctx_wff_regularity.\n    specialize (hb ltac:(fsetdec)).\n    eapply weakening_sort. eapply hb. \n    move: (Typing_ctx hb) => CB.\n    destruct_ctx.\n    eclarify_ctx. \n    simpl_env. fsetdec.\n    econstructor; eauto. \n- (* pi *) \n  pick fresh z. move:(H0 z ltac:(auto)) => h.\n  move: (Typing_ctx h) => C0. destruct_ctx.\n  clear IHTyping H1. \n  rewrite subst_def_Type. \n  split; auto.\n  exists G1. exists G2. exists r.\n  repeat split.  \n  + eapply ctx_sub_refl. eclarify_ctx.\n  + auto.\n  + intros.\n  pick fresh y for (L \\u {{x}} \\u dom D5 \\u fv_tm_tm (subst_def D5 B) \\u fv_tm_tm B).\n  specialize (H0 y ltac:(auto)).\n  eapply Typing_rename with (y:= x) in H0; eauto.\n  asimpl in H0.\n  rewrite <- subst_tm_tm_intro in H0.\n  auto.\n  fsetdec.\n- (* conv *) \n  move: (IHTyping1 _ _ _ ltac:(reflexivity)) => [E [G1' [G2' [r [? [? hb]]]]]].\n  clear IHTyping1 IHTyping2.\n  split.\n  eapply B_Trans with (A1 := subst_def D5 A0). eapply B_Sym. eauto. eauto.\n  eexists. eexists. eexists.\n  split.\n  2: { split. eauto. \n       eauto. }\n  transitivity G1. auto.\n  eapply ctx_sub_refl. eclarify_ctx.\nQed.\n\nLemma invert_Sigma : forall D G q A B A0,\n  Typing D G (a_Sigma q A B) A0 ->\n  Beta (subst_def D A0) a_Type /\\\n  exists G1, exists G2, exists r,\n      ctx_sub D (ctx_plus G1 G2) G /\\\n      Typing D G1 A a_Type /\\\n      forall x, x `notin` dom D \\u fv_tm_tm (subst_def D B) ->\n           Typing ([(x, Tm A)] ++ D) ([(x, (r, Tm A))] ++ G2)\n                  (open_tm_wrt_tm B (a_Var_f x)) a_Type.\nProof.\nintros.\ndependent induction H.  \n- (* sub *) \n  move: (IHTyping _ _ _ ltac:(reflexivity)) => [E [G1' [G2' [r [? [? ?]]]]]].\n  split; auto.\n  eexists. eexists. eexists.\n  split; eauto.\n  transitivity G1; auto.\n- (* weak *) \n  move: (IHTyping1 _ _ _ ltac:(reflexivity)) => [E [G1' [G2' [r [? [? hb]]]]]].\n  split; auto.\n  clear IHTyping1 IHTyping2.\n  exists (x ~ (0,Tm A0) ++ G1'). exists (x ~ (0,Tm A0) ++ G2'). eexists.\n  repeat split.\n  + asimpl.\n    econstructor; eauto.\n    reflexivity. \n  + eapply T_weak; eauto.\n  + intros y Fr.\n    asimpl in Fr.\n    specialize (hb y ltac:(auto)). \n    eapply weakening. eapply hb. \n    move: (Typing_ctx hb) => CB.\n    destruct_ctx.\n    eclarify_ctx. \n    simpl_env. fsetdec.\n    eauto.\n- (* weak_def *) \n  move: (IHTyping1 _ _ _ ltac:(reflexivity)) => [E [G1' [G2' [r [? [? hb]]]]]].\n  clear IHTyping1 IHTyping2.\n  split.\n  (* Beta equal to Type *)\n  asimpl. \n  erewrite subst_def_subst_tm_tm; eauto.\n  replace a_Type with (subst_tm_tm (subst_def D5 a) x a_Type); try reflexivity.\n  eapply subst_Beta1. eapply subst_def_lc_tm; eauto using Typing_lc_ctx, Typing_lc. auto.\n  eauto using Typing_ctx_wff_regularity.\n\n  exists (x ~ (0,Def a A0) ++ G1'). exists (x ~ (0,Def a A0) ++ G2'). eexists.\n  repeat split.\n  + asimpl.\n    econstructor; eauto.\n    reflexivity. \n  + eapply T_weak_def; eauto.\n  + intros y Fr.\n    asimpl in Fr.\n    rewrite <- fv_subst_def_lower in Fr; eauto using Typing_ctx_wff_regularity.\n    rewrite <- fv_tm_tm_subst_tm_tm_lower in Fr.\n    specialize (hb y).\n    rewrite -> fv_subst_def in hb; eauto using Typing_ctx_wff_regularity.\n    specialize (hb ltac:(fsetdec)).\n    eapply weakening_sort. eapply hb. \n    move: (Typing_ctx hb) => CB.\n    destruct_ctx.\n    eclarify_ctx. \n    simpl_env. fsetdec.\n    econstructor; eauto. \n- (* conv *)\n  move: (IHTyping1 _ _ _ ltac:(reflexivity)) => [E [G1' [G2' [r [? [? hb]]]]]].\n  clear IHTyping1 IHTyping2.\n(*   pick fresh z. move: (hb z ltac:(auto)) => Thb. move: (Typing_ctx Thb) => C. destruct_ctx. clear dependent z. *)\n  split.\n  eapply B_Trans with (subst_def D5 A0); auto. \n  eexists. eexists. eexists.\n  repeat split; eauto. \n- (* sigma *) \n  pick fresh z. move:(H0 z ltac:(auto)) => h.\n  move: (Typing_ctx h) => C0. destruct_ctx.\n  clear IHTyping H1. \n  rewrite subst_def_Type.\n  split; auto.\n  exists G1. exists G2. exists r.\n  repeat split.  \n  + eapply ctx_sub_refl. eclarify_ctx.\n  + auto.\n  + intros.\n  pick fresh y for (L \\u {{x}} \\u dom D5 \\u fv_tm_tm B).\n  specialize (H0 y ltac:(auto)).\n  eapply Typing_rename with (y:= x) in H0; eauto.\n  asimpl in H0.\n  rewrite <- subst_tm_tm_intro in H0.\n  auto.\n  fsetdec.\nQed.\n\n\nLemma invert_With : forall D G A B A0,\n  Typing D G (a_With A B) A0 ->\n  Beta (subst_def D A0) a_Type /\\\n  exists G1, exists G2, exists r,\n      ctx_sub D (ctx_plus G1 G2) G /\\\n      Typing D G1 A a_Type /\\\n      forall x, x `notin` dom D \\u fv_tm_tm (subst_def D B) ->\n           Typing ([(x, Tm A)] ++ D) ([(x, (r, Tm A))] ++ G2)\n                  (open_tm_wrt_tm B (a_Var_f x)) a_Type.\nProof.\nintros.\ndependent induction H.  \n- (* sub *) \n  move: (IHTyping _ _ ltac:(reflexivity)) => [E [G1' [G2' [r [? [? ?]]]]]].\n  split; auto.\n  eexists. eexists. eexists.\n  split; eauto.\n  transitivity G1; auto.\n- (* weak *) \n  move: (IHTyping1 _ _ ltac:(reflexivity)) => [E [G1' [G2' [r [? [? hb]]]]]].\n  split; auto.\n  clear IHTyping1 IHTyping2.\n  exists (x ~ (0,Tm A0) ++ G1'). exists (x ~ (0,Tm A0) ++ G2'). eexists.\n  repeat split.\n  + asimpl.\n    econstructor; eauto.\n    reflexivity. \n  + eapply T_weak; eauto.\n  + intros y Fr.\n    asimpl in Fr.\n    specialize (hb y ltac:(auto)). \n    eapply weakening. eapply hb. \n    move: (Typing_ctx hb) => CB.\n    destruct_ctx.\n    eclarify_ctx. \n    simpl_env. fsetdec.\n    eauto.\n- (* weak_def *) \n  move: (IHTyping1 _ _ ltac:(reflexivity)) => [E [G1' [G2' [r [? [? hb]]]]]].\n  clear IHTyping1 IHTyping2.\n  split.\n  (* Beta equal to Type *)\n  asimpl. \n  erewrite subst_def_subst_tm_tm; eauto.\n  replace a_Type with (subst_tm_tm (subst_def D5 a) x a_Type); try reflexivity.\n  eapply subst_Beta1. eapply subst_def_lc_tm; eauto using Typing_lc_ctx, Typing_lc. auto.\n  eauto using Typing_ctx_wff_regularity.\n\n  exists (x ~ (0,Def a A0) ++ G1'). exists (x ~ (0,Def a A0) ++ G2'). eexists.\n  repeat split.\n  + asimpl.\n    econstructor; eauto.\n    reflexivity. \n  + eapply T_weak_def; eauto.\n  + intros y Fr.\n    asimpl in Fr.\n    rewrite <- fv_subst_def_lower in Fr; eauto using Typing_ctx_wff_regularity.\n    rewrite <- fv_tm_tm_subst_tm_tm_lower in Fr.\n    specialize (hb y).\n    rewrite -> fv_subst_def in hb; eauto using Typing_ctx_wff_regularity.\n    specialize (hb ltac:(fsetdec)).\n    eapply weakening_sort. eapply hb. \n    move: (Typing_ctx hb) => CB.\n    destruct_ctx.\n    eclarify_ctx. \n    simpl_env. fsetdec.\n    econstructor; eauto. \n- (* conv *)\n  move: (IHTyping1 _ _ ltac:(reflexivity)) => [E [G1' [G2' [r [? [? hb]]]]]].\n  clear IHTyping1 IHTyping2.\n  split.\n  eapply B_Trans with (subst_def D5 A0); auto. \n  eexists. eexists. eexists.\n  repeat split; eauto. \n- (* with *) \n  pick fresh z. move:(H0 z ltac:(auto)) => h.\n  move: (Typing_ctx h) => C0. destruct_ctx.\n  clear IHTyping H1. \n  rewrite subst_def_Type.\n  split; auto.\n  exists G1. exists G2. exists r.\n  repeat split.  \n  + eapply ctx_sub_refl. eclarify_ctx.\n  + auto.\n  + intros.\n  pick fresh y for (L \\u {{x}} \\u dom D5 \\u fv_tm_tm B).\n  specialize (H0 y ltac:(auto)).\n  eapply Typing_rename with (y:= x) in H0; eauto.\n  asimpl in H0.\n  rewrite <- subst_tm_tm_intro in H0.\n  auto.\n  fsetdec.\nQed.\n\n\n(* Lemma 6.1 *)\nLemma Typing_regularity : \n  forall {D G a B}, Typing D G a B -> exists G', Typing D G' B a_Type.\nProof.\n  intros. induction H.\n  all: try destruct IHTyping as [G' h].\n  all: try destruct IHTyping1 as [G1' h1].\n  all: try destruct IHTyping2 as [G2' h2].\n\n  all: try solve [eexists; eauto].\n  all: try solve [eexists; eapply T_weak; eauto].\n  - exists (x ~ (0, Def a A) ++ G').\n    eapply weakening_sort with (D1 :=nil) (G1:=nil); eauto.\n    econstructor; eauto. eapply Typing_ctx; eauto.\n  - exists (x ~ (0, Def a A) ++ G1').\n    eapply weakening_sort with (D1 :=nil) (G1:=nil); eauto.\n    econstructor; eauto. eapply Typing_ctx; eauto.\n  - pick fresh x for (L \\u fv_tm_tm B \\u dom D5).\n    specialize (H x ltac:(auto)).\n    specialize (H0 x ltac:(auto)).\n    destruct H0 as [G0 h0].\n    move: (Typing_ctx h0) => C0.\n    destruct_ctx.\n    eexists.\n    eapply (T_pi_exists x); eauto.\n    asimpl in h0.\n    eapply h0.\n  - apply invert_Pi in h1.\n    move: h1 => [_ [G1'' [G2'' [r [? [? hb]]]]]].\n    pick fresh x for (dom D5 \\u fv_tm_tm (subst_def D5 B) \\u fv_tm_tm B).\n    specialize (hb x ltac:(auto)).  \n    move: (substitution _ nil _ nil _ _ _ _ _ hb _ _ H0) => hs.\n    asimpl in hs.\n    erewrite <- subst_tm_tm_intro in hs; auto.\n    eauto.\n  - (* UnitE *) \n    pick_fresh x.\n    specialize (H2 x ltac:(auto)).\n    have LC: lc_tm a. { eapply Typing_lc; eauto. }\n    move: (fun x y => substitution x nil y nil) => s.\n    eapply s in H. 2: { simpl_env. apply H2. }\n    simpl_env in H.\n    rewrite subst_tm_tm_open_tm_wrt_tm in H; auto.\n    rewrite subst_tm_same in H; auto.\n    simpl in H.\n    rewrite subst_tm_tm_fresh_eq in H. fsetdec.\n    eexists. eauto.\n  - (* unbox *)\n    pick_fresh x.\n    specialize (H2 x ltac:(auto)).\n    have LC: lc_tm a. { eapply Typing_lc; eauto. }\n    move: (fun x y => substitution x nil y nil) => s.\n    eapply s in H. 2: { simpl_env. apply H2. }\n    simpl_env in H.\n    rewrite subst_tm_tm_open_tm_wrt_tm in H; auto.\n    rewrite subst_tm_same in H; auto.\n    simpl in H.\n    rewrite subst_tm_tm_fresh_eq in H. fsetdec.\n    eexists. eauto.\n  - (* inj1 *)\n    eexists. eapply T_sum; eauto.\n  - (* inj2 *)\n    eexists. eapply T_sum; eauto.\n  - (* case *)\n    pick fresh x.\n    repeat match goal with [H : forall x, x `notin` ?L -> _ |- _ ] => specialize (H x ltac:(auto)) end.\n    repeat match goal with [H : forall y, y `notin` ?L -> _ |- _ ] => specialize (H x ltac:(auto)) end.\n    repeat match goal with [H : exists G' , Typing _ _ _ _ |- _ ] => destruct H end.\n    move: (fun y => substitution D5 nil y nil) => s.\n    match goal with [H5 : Typing _ _ (open_tm_wrt_tm ?B _) a_Type |- _ ] => \n                    eapply s in H5; eauto; clear s;\n                    asimpl in H5;\n                    rewrite subst_tm_tm_open_tm_wrt_tm in H5; eauto using Typing_lc;\n                    rewrite subst_tm_same in H5; auto;\n                    rewrite subst_tm_tm_fresh_eq in H5; eauto\n    end.\n  - pick fresh x for (L \\u fv_tm_tm B \\u dom D5).\n    specialize (H1 x ltac:(auto)).\n    specialize (H2 x ltac:(auto)).\n    destruct H2 as [G0 h0].\n    move: (Typing_ctx h0) => C0.\n    destruct_ctx.\n    eexists.\n    eapply (T_Sigma_exists x); eauto.\n  - (* spread *)\n    subst A.\n    pick fresh x.\n    repeat match goal with [H : forall x, x `notin` ?L -> _ |- _ ] => specialize (H x ltac:(auto)) end.\n    repeat match goal with [H : forall y, y `notin` ?L -> _ |- _ ] => specialize (H x ltac:(auto)) end.\n    repeat match goal with [H : exists G' , Typing _ _ _ _ |- _ ] => destruct H end.\n    move: (fun y => substitution D5 nil y nil) => s.\n    match goal with [H5 : Typing _ _ (open_tm_wrt_tm ?B _) a_Type |- _ ] => \n                    eapply s in H5; eauto; clear s;\n                    asimpl in H5;\n                    rewrite subst_tm_tm_open_tm_wrt_tm in H5; eauto using Typing_lc;\n                    rewrite subst_tm_same in H5; auto;\n                    rewrite subst_tm_tm_fresh_eq in H5; eauto\n    end.\n  - (* with *)\n    pick fresh x.\n    repeat match goal with [H : forall x, x `notin` ?L -> _ |- _ ] => specialize (H x ltac:(auto)) end.\n    repeat match goal with [H : exists G' , Typing _ _ _ _ |- _ ] => destruct H end.\n    eexists.\n    eapply T_With_exists with (x:=x); eauto.\n  - (* Prj1 *)\n    move: (invert_With _ _ _ _ _ h) => [Be [G0 [G2 [Ta [r [Sub Tb]]]]]].\n    eexists.\n    eauto.\n  - (* Prj2 *)\n    move: (invert_With _ _ _ _ _ h) => [Be [G0 [G2 [Ta [r [Sub Tb]]]]]].\n    pick fresh z for (dom D5 \\u fv_tm_tm (subst_def D5 B) \\u fv_tm_tm B). \n    specialize (Tb z ltac:(auto)).\n    have Tp1: Typing D5 G (a_Prj1 a) A; eauto.\n    eapply substitution with (D2 := nil) (G2 := nil)  in Tp1.\n    2: { simpl_env. eapply Tb. }\n    asimpl in Tp1.\n    rewrite subst_tm_tm_open_tm_wrt_tm in Tp1; eauto using Typing_lc.\n    rewrite subst_tm_same in Tp1; auto.\n    rewrite subst_tm_tm_fresh_eq in Tp1; auto.\n    eexists.\n    eauto.\nQed.\n\n\nLemma invert_Lam D G q a A C : \n  Typing D G (a_Lam q A a) C ->\n     (forall x, x `notin` fv_tm_tm a `union` dom G `union` dom D -> \n           exists B,  Beta (subst_def D C) (subst_def D (a_Pi q A B)) /\\\n           exists G1, Typing D G1 (a_Pi q A B) a_Type /\\\n           Typing \n             (x ~ Tm A ++ D)\n             ([(x, (q, Tm A))] ++ G) (open_tm_wrt_tm a (a_Var_f x)) \n                                     (open_tm_wrt_tm B (a_Var_f x))).      \nProof.      \n  intros HA.\n  dependent induction HA; intros y Fr.\n  - have D: dom G1 = dom G2. eapply dom_ctx_sub; eauto.\n    rewrite <- D in Fr.\n    specialize (IHHA q a A ltac:(auto) y ltac:(auto)).\n    move: IHHA => [B [HB [GA [hA HT]]]].\n    exists B. split; auto. \n    exists GA. split; auto.\n    eapply T_sub. eauto. econstructor; eauto. reflexivity. \n  - (* T_weak *) \n    specialize (IHHA1 _ _ _  ltac:(auto) y ltac:(auto)).\n    clear IHHA2.\n    move: IHHA1 => [B0 [HB [GA [hA  HT]]]].\n    exists B0. split. auto.\n    exists (x ~ (0, Tm A0) ++ GA). split.\n    eapply T_weak; eauto.\n    eapply weakening. eauto. eclarify_ctx. solve_uniq. eauto.\n  - (* T_weak_def *)\n    specialize (IHHA1 _ _ _  ltac:(auto) y ltac:(auto)).\n    clear IHHA2.\n    move: IHHA1 => [B0 [HB [GA [hA  HT]]]].\n    exists B0. split. simpl. \n    rewrite subst_def_Pi.\n    repeat erewrite subst_def_subst_tm_tm; eauto using Typing_ctx_wff_regularity.\n    eapply (subst_Beta1 (subst_def D5 a0) x) in HB; eauto using Typing_lc, subst_def_lc_tm, Typing_lc_ctx.\n    rewrite subst_def_Pi in HB. simpl in HB. auto.\n\n    exists (x ~ (0, Def a0 A0) ++ GA). split.\n    eapply T_weak_def; eauto.\n    eapply weakening_sort. eauto. eclarify_ctx. solve_uniq. eauto. \n\n  - (* lam *)\n    clear IHHA. clear H0.\n    exists B. split.\n      eapply subst_def_Beta. eauto using Typing_lc_ctx.\n      eapply B_Refl. \n      pick fresh z. \n      move: (Typing_regularity (H z ltac:(auto))) => [GG TB].      \n      eapply (lc_a_Pi_exists z);\n      eapply Typing_lc; eauto.\n    + pick fresh z.\n      move: (H z ltac:(auto)) => h.\n      move: (Typing_regularity h) => [G h1].\n      move: (Typing_ctx h1) => C1.\n      destruct_ctx.\n      eexists. split.\n      eapply (T_pi_exists z); eauto.\n      eapply h1.\n      move: (Typing_rename _ _ _ z y _ _ _ _ HA h ltac:(auto)) => rn.\n      rewrite subst_tm_tm_open_tm_wrt_tm in rn. auto.\n      rewrite subst_tm_same in rn. auto.\n      rewrite subst_tm_tm_fresh_eq in rn. {  clear Fr H3 H8. fsetdec. }\n      rewrite subst_tm_tm_open_tm_wrt_tm in rn. auto.\n      rewrite subst_tm_same in rn. auto.\n      rewrite subst_tm_tm_fresh_eq in rn. { clear Fr H3 H8. fsetdec. }\n      eapply rn.\n  - (* conv *)\n    specialize (IHHA1 _ _ _ ltac:(reflexivity) y Fr).\n    destruct IHHA1 as [B0 [BB [G2' [T1 T2]]]]. clear IHHA2.\n    exists B0.\n    split. eapply B_Sym. eauto. eauto.\nQed.\n\n\nLemma invert_inj1 : \n       forall {D G a A}, Typing D G (a_Inj1 a) A -> \n                    exists A1, exists A2, exists G1, Beta (subst_def D (a_Sum A1 A2)) (subst_def D A) /\\\n                                Typing D G a A1 /\\ Typing D G1 A2 a_Type.\nProof. intros D G a A TA. dependent induction TA.\n       - destruct (IHTA _ ltac:(auto)) as [A1 [A2 [G1' [BA [T1 T2]]]]].\n         exists A1. exists A2. eexists. split. auto. split.\n         eapply T_sub; eauto. eauto.\n       - destruct (IHTA1 _ ltac:(auto)) as [A1 [A2 [G1' [BA [T1 T2]]]]].\n         eexists. eexists. eexists.\n         split. asimpl. eauto. split.\n         eapply T_weak; auto. eauto.\n         eapply T_weak; auto. eauto. eauto.\n       - destruct (IHTA1 _ ltac:(auto)) as [A1 [A2 [G1' [BA [T1 T2]]]]].\n         exists A1. exists A2. eexists.\n         split. simpl.\n         replace (a_Sum (subst_tm_tm a0 x A1) (subst_tm_tm a0 x A2)) with\n                 (subst_tm_tm a0 x (a_Sum A1 A2)); try reflexivity.\n         repeat erewrite subst_def_subst_tm_tm; eauto using Typing_ctx_wff_regularity.\n         eapply subst_Beta1; eauto using Typing_lc, subst_def_lc_tm, Typing_lc_ctx.\n         split.\n         eapply T_weak_def; eauto.\n         eapply T_weak_def; eauto.\n       - destruct (IHTA1 _ ltac:(auto)) as [A1 [A2 [G1' [BA [T1 T2]]]]].\n         eexists. eexists. eexists.\n         split. eapply B_Trans. eauto. eauto. \n         split; eauto.\n       - eexists. eexists. eexists.\n         split.\n         eapply subst_def_Beta. eauto using Typing_lc_ctx.\n         eapply B_Refl. econstructor. eapply Typing_lc2; eauto. eapply Typing_lc; eauto.\n         split; eauto.\nQed.\n\n\nLemma invert_inj2 : \n       forall {D G a A}, Typing D G (a_Inj2 a) A -> \n                    exists A1, exists A2, exists G1, Beta (subst_def D (a_Sum A1 A2)) (subst_def D A) /\\\n                                Typing D G a A2 /\\ Typing D G1 A1 a_Type.\nProof. intros D G a A TA. dependent induction TA.\n       - destruct (IHTA _ ltac:(auto)) as [A1 [A2 [G1' [BA [T1 T2]]]]].\n         exists A1. exists A2. eexists. split. auto. split.\n         eapply T_sub; eauto. eauto.\n       - destruct (IHTA1 _ ltac:(auto)) as [A1 [A2 [G1' [BA [T1 T2]]]]].\n         eexists. eexists. eexists.\n         split. asimpl. \n         eauto. split.\n         eapply T_weak; auto. eauto.\n         eapply T_weak; auto. eauto. eauto.\n       - destruct (IHTA1 _ ltac:(auto)) as [A1 [A2 [G1' [BA [T1 T2]]]]].\n         exists A1. exists A2. eexists.\n         split. simpl.\n         replace (a_Sum (subst_tm_tm a0 x A1) (subst_tm_tm a0 x A2)) with\n                 (subst_tm_tm a0 x (a_Sum A1 A2)); try reflexivity.\n         repeat erewrite subst_def_subst_tm_tm; eauto using Typing_ctx_wff_regularity.\n         eapply subst_Beta1; eauto using Typing_lc, subst_def_lc_tm, Typing_lc_ctx.\n         split.\n         eapply T_weak_def; eauto.\n         eapply T_weak_def; eauto.\n       - destruct (IHTA1 _ ltac:(auto)) as [A1 [A2 [G1' [BA [T1 T2]]]]].\n         eexists. eexists. eexists.\n         split. eapply B_Trans. eauto. eauto. \n         split; eauto.\n       - eexists. eexists. eexists.\n         split. \n         eapply subst_def_Beta. eauto using Typing_lc_ctx.\n         eapply B_Refl. econstructor. eapply Typing_lc; eauto. eapply Typing_lc2; eauto.\n         split; eauto.\nQed.\n\nLemma invert_Sum : forall {D G A1 A2 B},\n       Typing D G (a_Sum A1 A2) B -> \n       Beta (subst_def D B) a_Type /\\ \n       exists G1, exists G2, ctx_sub D (ctx_plus G1 G2) G /\\ Typing D G1 A1 a_Type /\\ Typing D G2 A2 a_Type.\nProof.\n       intros. dependent induction H.\n       - destruct (IHTyping _ _ ltac:(auto)) as [Be [G1' [G2' [S [T1 T2]]]]]. \n         split. auto. exists G1'. exists G2'.\n         split. transitivity G1; auto.\n         split; auto.\n       - destruct (IHTyping1 _ _ ltac:(auto)) as [Be [G1' [G2' [S [T1 T2]]]]]. \n         split. auto. exists (x ~ (0, Tm A) ++ G1'). exists (x ~ (0, Tm A) ++ G2').\n         split. econstructor; eauto. ring_simpl; reflexivity.\n         split. eapply T_weak; eauto.\n                eapply T_weak; eauto.\n       - destruct (IHTyping1 _ _ ltac:(auto)) as [Be [G1' [G2' [S [T1 T2]]]]]. \n         split. asimpl. \n\n         (* Beta equal to Type *)\n         asimpl. \n         erewrite subst_def_subst_tm_tm; eauto.\n         replace a_Type with (subst_tm_tm (subst_def D5 a) x a_Type); try reflexivity.\n         eapply subst_Beta1. eapply subst_def_lc_tm; eauto using Typing_lc_ctx, Typing_lc. auto.\n         eauto using Typing_ctx_wff_regularity.\n\n         exists (x ~ (0, Def a A) ++ G1'). exists (x ~ (0, Def a A) ++ G2').\n         split. econstructor; eauto. ring_simpl; reflexivity.\n         split. eapply T_weak_def; eauto.\n                eapply T_weak_def; eauto.\n       - destruct (IHTyping1 _ _ ltac:(auto)) as [Be [G1' [G2' [S [T1 T2]]]]]. \n         split. eapply B_Trans. eapply B_Sym. eauto. auto. \n         exists G1'. exists G2'. split. eauto. split. eauto. eauto.\n       - split. \n         rewrite subst_def_Type.\n         eapply B_Refl. auto. \n         exists G1. exists G2. split. eapply ctx_sub_refl. eclarify_ctx.\n         split; auto.\nQed.\n\n\n\nLemma invert_Tensor : forall {D G a1 a2 B},\n       Typing D G (a_Tensor a1 a2) B -> \n       exists A1, exists A2, exists q, Beta (subst_def D B) (subst_def D (a_Sigma q A1 A2)) /\\ \n       exists G1, exists G2, exists G3, exists r,\n             ctx_sub D (ctx_plus (ctx_mul q G1) G2) G \n             /\\ Typing D G1 a1 A1 \n             /\\ Typing D G2 a2 (open_tm_wrt_tm A2 a1)\n             /\\ (forall x, x `notin` dom D -> \n                    Typing (x ~ Tm A1 ++ D) (x ~ (r, Tm A1) ++ G3) (open_tm_wrt_tm A2 (a_Var_f x)) a_Type).\nProof.\n  intros. dependent induction H.\n  - destruct (IHTyping a1 a2 ltac:(auto)) as [A1 [A2 [q [BA [G1' [G2' [G3 [r [SS [Ta1 [Ta2 U]]]]]]]]]]].\n    exists A1. exists A2. exists q. split. auto.\n    exists G1'. exists G2'. exists G3. exists r.\n    repeat split; auto. transitivity G1; auto.\n  - destruct (IHTyping1 _ _ ltac:(auto))  as [A1 [A2 [q [BA [G1' [G2' [G3 [r [SS [Ta1 [Ta2 U]]]]]]]]]]].\n    exists A1. exists A2. exists q. split. auto.\n    exists (x ~ (0, Tm A) ++ G1'). exists (x ~ (0, Tm A) ++ G2'). exists (x ~ (0, Tm A) ++ G3). exists r.\n    repeat split; auto. econstructor; eauto.  ring_simpl; reflexivity.\n    eapply T_weak; eauto.\n    eapply T_weak; eauto.\n    intros. simpl in H2.\n    move: (U x0 ltac:(auto)) => TB.\n    eapply weakening; eauto.\n    move: (Typing_ctx TB) => C. destruct_ctx.\n    solve_ctx.\n  - destruct (IHTyping1 _ _ ltac:(auto))  as [A1 [A2 [q [BA [G1' [G2' [G3 [r [SS [Ta1 [Ta2 U]]]]]]]]]]].\n    exists A1. exists A2. exists q. split. asimpl.\n    rewrite subst_def_Sigma.\n    repeat erewrite subst_def_subst_tm_tm; eauto using Typing_ctx_wff_regularity.\n    eapply (subst_Beta1 (subst_def D5 a) x) in BA; eauto using Typing_lc, subst_def_lc_tm, Typing_lc_ctx.\n    rewrite subst_def_Sigma in BA. simpl in BA. auto.\n\n    exists (x ~ (0, Def a A) ++ G1'). exists (x ~ (0, Def a A) ++ G2'). exists (x ~ (0, Def a A) ++ G3). exists r.\n    repeat split; auto. asimpl. econstructor; eauto.  ring_simpl; reflexivity.\n    eapply T_weak_def; eauto.\n    eapply T_weak_def; eauto.\n    intros. simpl in H2.\n    move: (U x0 ltac:(auto)) => TB.\n    eapply weakening_sort; eauto.\n    move: (Typing_ctx TB) => C. destruct_ctx.\n    solve_ctx. \n\n  - destruct (IHTyping1 _ _ ltac:(auto))  as [A1 [A2 [q [BA [G1' [G2' [G3 [r [SS [Ta1 [Ta2 U]]]]]]]]]]].\n    exists A1. exists A2. exists q. split. eapply B_Trans. eapply B_Sym. eauto. auto.\n    exists G1'. exists G2'. exists G3. exists r.\n    repeat split; eauto.\n  -  clear H2 IHTyping1 IHTyping2.\n     move: (Typing_ctx H) => C1. move: (Typing_ctx H0) => C2.\n     have LC: lc_tm (a_Sigma q A B). { \n       pick fresh z.\n       eapply lc_a_Sigma_exists. eapply Typing_lc2; eauto.\n       eapply Typing_lc; eauto.\n     }\n     exists A. exists B. exists q. split. eapply subst_def_Beta; eauto using Typing_lc_ctx. \n     exists G1. exists G2. exists G3. exists r.\n     repeat split; eauto.\n     eapply ctx_sub_refl. solve_ctx.\n     pick fresh z.\n     intros x Frx.\n     move: (Typing_regularity H) => [GA TA].\n     move: (H1 z ltac:(auto)) => h.\n     move: (Typing_regularity h) => [G h1].\n     move: (Typing_ctx h1) => C3.\n     destruct_ctx.\n     move: (Typing_rename _ _ _ z x _ _ _ _ TA h ltac:(auto)) => rn.\n     rewrite subst_tm_tm_open_tm_wrt_tm in rn. auto.\n     rewrite subst_tm_same in rn. auto.\n     rewrite subst_tm_tm_fresh_eq in rn. { clear Frx H5 H10. fsetdec. }\n     asimpl in rn.\n     eapply rn.\nQed.\n\n\nLemma invert_Pair : forall {D G a1 a2 B},\n       Typing D G (a_Pair a1 a2) B -> \n       exists A1, exists A2, Beta (subst_def D B) (subst_def D (a_With A1 A2)) /\\ \n       exists G3, exists r,\n               Typing D G a1 A1 \n             /\\ Typing D G a2 (open_tm_wrt_tm A2 a1)\n             /\\ (forall x, x `notin` dom D -> \n                    Typing (x ~ Tm A1 ++ D) (x ~ (r, Tm A1) ++ G3) \n                           (open_tm_wrt_tm A2 (a_Var_f x)) a_Type).\nProof.\n  intros. dependent induction H.\n  - (* sub *) destruct (IHTyping a1 a2 ltac:(auto)) as [A1 [A2 [BA [G3 [r [Ta1 [Ta2 U]]]]]]].\n    exists A1. exists A2. split. auto.\n    exists G3. exists r.\n    repeat split; auto.\n    eapply T_sub; eauto.\n    eapply T_sub; eauto.\n  - (* weak *) destruct (IHTyping1 a1 a2 ltac:(auto)) as [A1 [A2 [BA [G3 [r [Ta1 [Ta2 U]]]]]]].\n    clear IHTyping2.\n    exists A1. exists A2. split. auto.\n    exists (x ~ (0, Tm A) ++ G3). exists r.\n    repeat split; auto.\n    eapply T_weak; eauto.\n    eapply T_weak; eauto.\n    intros. simpl in H2.\n    move: (U x0 ltac:(auto)) => TB.\n    eapply weakening; eauto.\n    move: (Typing_ctx TB) => C. destruct_ctx.\n    solve_ctx.\n  - (* weak_def *)\n    destruct (IHTyping1 a1 a2 ltac:(auto)) as [A1 [A2 [BA [G3 [r [Ta1 [Ta2 U]]]]]]].\n    clear IHTyping2.\n    exists A1. exists A2. split. asimpl.\n    rewrite subst_def_With.\n    repeat erewrite subst_def_subst_tm_tm; eauto using Typing_ctx_wff_regularity.\n    eapply (subst_Beta1 (subst_def D5 a) x) in BA; eauto using Typing_lc, subst_def_lc_tm, Typing_lc_ctx.\n    rewrite subst_def_With in BA. simpl in BA. auto.\n    exists (x ~ (0, Def a A) ++ G3). exists r.\n    repeat split; auto.\n    eapply T_weak_def; eauto.\n    eapply T_weak_def; eauto.\n    intros. simpl in H2.\n    move: (U x0 ltac:(auto)) => TB.\n    eapply weakening_sort; eauto.\n    move: (Typing_ctx TB) => C. destruct_ctx.\n    solve_ctx. \n  - destruct (IHTyping1 a1 a2 ltac:(auto)) as [A1 [A2 [BA [G3 [r [Ta1 [Ta2 U]]]]]]].\n    clear IHTyping2.\n    exists A1. exists A2. split. eapply B_Trans. eapply B_Sym. eauto. auto.\n    exists G3. exists r.\n    repeat split; eauto.    \n  - clear H2 IHTyping1 IHTyping2.\n     move: (Typing_ctx H) => C1. move: (Typing_ctx H0) => C2.\n     have LC: lc_tm (a_With A B). { \n       pick fresh z.\n       eapply lc_a_With_exists. eapply Typing_lc2; eauto.\n       eapply Typing_lc; eauto.\n     }\n     exists A. exists B. split. eapply subst_def_Beta; eauto using Typing_lc_ctx. \n     exists G2. exists r.\n     repeat split; eauto.\n     pick fresh z.\n     intros x Frx.\n     move: (Typing_regularity H) => [GA TA].\n     move: (H1 z ltac:(auto)) => h.\n     move: (Typing_ctx h) => C3.\n     destruct_ctx.\n     move: (Typing_rename _ _ _ z x _ _ _ _ TA h ltac:(auto)) => rn.\n     rewrite subst_tm_tm_open_tm_wrt_tm in rn. auto.\n     rewrite subst_tm_same in rn. auto.\n     rewrite subst_tm_tm_fresh_eq in rn. { fsetdec. }\n     asimpl in rn.\n     eapply rn.\nQed.\n", "meta": {"author": "sweirich", "repo": "graded-haskell", "sha": "97eee95dfb6aedef81c81e8a64b9ad2b718c2815", "save_path": "github-repos/coq/sweirich-graded-haskell", "path": "github-repos/coq/sweirich-graded-haskell/graded-haskell-97eee95dfb6aedef81c81e8a64b9ad2b718c2815/GraD/src-def/inversion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.22158371393221235}}
{"text": "Require Import Verdi.Verdi.\nRequire Import Verdi.HandlerMonad.\nRequire Import Verdi.NameOverlay.\n\nRequire Import NameAdjacency.\nRequire Import FailureRecorderStatic.\n\nRequire Import Sumbool.\nRequire Import MSetFacts.\nRequire Import MSetProperties.\n\nRequire Import mathcomp.ssreflect.ssreflect.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nSet Implicit Arguments.\n\nModule FailureRecorderCorrect (Import NT : NameType) \n (NOT : NameOrderedType NT) (NSet : MSetInterface.S with Module E := NOT)\n (Import ANT : AdjacentNameType NT) (Import A : Adjacency NT NOT NSet ANT).\n\nModule FR := FailureRecorder NT NOT NSet ANT A.\nImport FR.\n\nModule NSetFacts := Facts NSet.\nModule NSetProps := Properties NSet.\nModule NSetOrdProps := OrdProperties NSet.\n\nLemma Failure_node_not_adjacent_self : \nforall net failed tr n, \n step_ordered_failure_star step_ordered_failure_init (failed, net) tr ->\n ~ In n failed ->\n ~ NSet.In n (onwState net n).(adjacent).\nProof.\nmove => net failed tr n H.\nremember step_ordered_failure_init as y in *.\nhave ->: failed = fst (failed, net) by [].\nhave ->: net = snd (failed, net) by [].\nmove: Heqy.\ninduction H using refl_trans_1n_trace_n1_ind => H_init /=.\n  rewrite H_init /step_ordered_failure_init /=.\n  move => H_f.\n  exact: not_adjacent_self.\nmove => H_f.\nmatch goal with\n| [ H : step_ordered_failure _ _ _ |- _ ] => invc H\nend; rewrite /=.\n- find_apply_lem_hyp net_handlers_NetHandler.\n  rewrite /update /=.\n  case name_eq_dec => H_dec /=; last exact: IHrefl_trans_1n_trace1.\n  rewrite -H_dec in H3.\n  net_handler_cases.\n  apply NSet.remove_spec in H0.\n  by move: H0 => [H0 H_neq].\n- by find_apply_lem_hyp input_handlers_IOHandler.\n- exact: IHrefl_trans_1n_trace1.\nQed.\n\nLemma Failure_self_channel_empty : \nforall onet failed tr, \n step_ordered_failure_star step_ordered_failure_init (failed, onet) tr -> \n forall n, ~ In n failed ->\n   onet.(onwPackets) n n = [].\nProof.\nmove => onet failed tr H.\nhave H_eq_f: failed = fst (failed, onet) by [].\nhave H_eq_o: onet = snd (failed, onet) by [].\nrewrite H_eq_f {H_eq_f}.\nrewrite {2}H_eq_o {H_eq_o}.\nremember step_ordered_failure_init as y in *.\nmove: Heqy.\ninduction H using refl_trans_1n_trace_n1_ind => H_init {failed}; first by rewrite H_init /step_ordered_failure_init /=.\nconcludes.\nmatch goal with\n| [ H : step_ordered_failure _ _ _ |- _ ] => invc H\nend; simpl.\n- find_apply_lem_hyp net_handlers_NetHandler.\n  net_handler_cases.\n  rewrite /= /update2.\n  case (sumbool_and _ _ _ _) => H_dec; last exact: IHrefl_trans_1n_trace1.\n  move: H_dec => [H_dec H_dec'].\n  rewrite H_dec H_dec' in H2.\n  by rewrite IHrefl_trans_1n_trace1 in H2.\n- by find_apply_lem_hyp input_handlers_IOHandler.\n- move => n H_in.\n  rewrite collate_neq.\n  apply: IHrefl_trans_1n_trace1.\n    move => H_in'.\n    case: H_in.\n    by right.\n  move => H_eq.\n  by case: H_in; left.\nQed.\n\nLemma Failure_not_failed_no_fail :\nforall onet failed tr,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr -> \n  forall n n',\n  ~ In n failed ->\n  ~ In Fail (onet.(onwPackets) n n').\nProof.\nmove => onet failed tr H.\nhave H_eq_f: failed = fst (failed, onet) by [].\nhave H_eq_o: onet = snd (failed, onet) by [].\nrewrite H_eq_f {H_eq_f}.\nrewrite {2}H_eq_o {H_eq_o}.\nremember step_ordered_failure_init as y in *.\nmove: Heqy.\ninduction H using refl_trans_1n_trace_n1_ind => H_init {failed}; first by rewrite H_init /step_ordered_failure_init /=.\nconcludes.\nmove => n n' H_in.\nmatch goal with\n| [ H : step_ordered_failure _ _ _ |- _ ] => invc H\nend; simpl.\n- find_apply_lem_hyp net_handlers_NetHandler.\n  net_handler_cases.\n  rewrite /= in H0, H_in.\n  contradict H0.\n  have H_in' := IHrefl_trans_1n_trace1 _ n' H_in.\n  rewrite /update2 /=.\n  case (sumbool_and _ _ _ _) => H_dec //.\n  move: H_dec => [H_eq H_eq'].\n  rewrite H_eq H_eq' in H2.\n  rewrite H2 in H_in'.\n  move => H_inn.\n  case: H_in'.\n  by right.\n- by find_apply_lem_hyp input_handlers_IOHandler.\n- rewrite /= in H_in.\n  have H_neq: h <> n by move => H_eq; case: H_in; left.\n  have H_f: ~ In n failed by move => H_in''; case: H_in; right.\n  rewrite collate_neq //.\n  exact: IHrefl_trans_1n_trace1.\nQed.\n\nSection SingleNodeInv.\n\nVariable onet : ordered_network.\n\nVariable failed : list name.\n\nVariable tr : list (name * (input + output)).\n\nHypothesis H_step : step_ordered_failure_star step_ordered_failure_init (failed, onet) tr.\n\nVariable n : name.\n\nHypothesis not_failed : ~ In n failed.\n\nVariable P : Data -> Prop.\n\nHypothesis after_init : P (InitData n).\n\nHypothesis recv_fail : \n  forall onet failed tr n',\n    step_ordered_failure_star step_ordered_failure_init (failed, onet) tr ->\n    ~ In n failed ->\n    P (onet.(onwState) n) ->\n    P (mkData (NSet.remove n' (onet.(onwState) n).(adjacent))).\n\nTheorem P_inv_n : P (onwState onet n).\nProof.\nmove: onet failed tr H_step not_failed.\nclear onet failed not_failed tr H_step.\nmove => onet' failed' tr H'_step.\nhave H_eq_f: failed' = fst (failed', onet') by [].\nhave H_eq_o: onet' = snd (failed', onet') by [].\nrewrite H_eq_f {H_eq_f}.\nrewrite {2}H_eq_o {H_eq_o}.\nremember step_ordered_failure_init as y in H'_step.\nmove: Heqy.\ninduction H'_step using refl_trans_1n_trace_n1_ind => /= H_init.\n  rewrite H_init /step_ordered_init /= => H_in_f.\n  exact: after_init.\nconcludes.\nmatch goal with\n| [ H : step_ordered_failure _ _ _ |- _ ] => invc H\nend; simpl.\n- move => H_in_f.\n  find_apply_lem_hyp net_handlers_NetHandler.\n  net_handler_cases.\n  rewrite /update /=.\n  case name_eq_dec => H_dec //.\n  rewrite -H_dec {H_dec H'_step2 to} in H0 H1 H5.\n  case: d H5 => /=.\n  move => adjacent0 H_eq.\n  rewrite H_eq {H_eq adjacent0}.\n  exact: (recv_fail _ H'_step1).\n- by find_apply_lem_hyp input_handlers_IOHandler.\n- move => H_in_f.\n  apply: IHH'_step1.\n  move => H'_in_f.\n  case: H_in_f.\n  by right.\nQed.\n\nEnd SingleNodeInv.\n\nSection SingleNodeInvOut.\n\nVariable onet : ordered_network.\n\nVariable failed : list name.\n\nVariable tr : list (name * (input + output)).\n\nHypothesis H_step : step_ordered_failure_star step_ordered_failure_init (failed, onet) tr.\n\nVariables n n' : name.\n\nHypothesis not_failed : ~ In n failed.\n\nVariable P : Data -> list msg -> Prop.\n\nHypothesis after_init : P (InitData n) [].\n\nHypothesis recv_fail_from_eq :\n  forall onet failed tr ms,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr ->\n  ~ In n failed ->\n  In n' failed ->\n  n' <> n ->\n  onet.(onwPackets) n' n = Fail :: ms ->\n  P (onet.(onwState) n) (onet.(onwPackets) n n') ->\n  P (mkData (NSet.remove n' (onet.(onwState) n).(adjacent))) (onet.(onwPackets) n n').\n\nHypothesis recv_fail_from_neq :\n  forall onet failed tr from ms,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr ->\n  ~ In n failed ->\n  In from failed ->\n  from <> n ->\n  from <> n' ->\n  onet.(onwPackets) from n = Fail :: ms ->\n  P (onet.(onwState) n) (onet.(onwPackets) n n') ->\n  P (mkData (NSet.remove from (onet.(onwState) n).(adjacent))) (onet.(onwPackets) n n').\n\nTheorem P_inv_n_out : P (onet.(onwState) n) (onet.(onwPackets) n n').\nProof.\nmove: onet failed tr H_step not_failed.\nclear onet failed not_failed tr H_step.\nmove => onet' failed' tr H'_step.\nhave H_eq_f: failed' = fst (failed', onet') by [].\nhave H_eq_o: onet' = snd (failed', onet') by [].\nrewrite H_eq_f {H_eq_f}.\nrewrite {2 3}H_eq_o {H_eq_o}.\nremember step_ordered_failure_init as y in H'_step.\nmove: Heqy.\ninduction H'_step using refl_trans_1n_trace_n1_ind => /= H_init.\n  rewrite H_init /step_ordered_failure_init /= => H_in_f.\n  exact: after_init.\nconcludes.\nmatch goal with\n| [ H : step_ordered_failure _ _ _ |- _ ] => invc H\nend; simpl.\n- move => H_in_f.\n  find_apply_lem_hyp net_handlers_NetHandler.\n  net_handler_cases.\n  rewrite /update /=.\n  case name_eq_dec => H_dec.\n    rewrite -H_dec in H1 H5 H0.\n    rewrite -H_dec /update2 /= {H_dec to H'_step2}.\n    case (sumbool_and _ _ _ _) => H_dec.\n      move: H_dec => [H_eq H_eq'].\n      rewrite H_eq {H_eq from} in H5 H0. \n      by rewrite (Failure_self_channel_empty H'_step1) in H0.\n    case: d H5 => /=.\n    move => adjacent0 H_eq.\n    rewrite H_eq {adjacent0 H_eq}.\n    case: H_dec => H_dec.\n      case (name_eq_dec from n') => H_dec'.\n        rewrite H_dec'.\n        rewrite H_dec' in H0 H_dec.\n        case (In_dec name_eq_dec n' failed) => H_in; first exact: (recv_fail_from_eq H'_step1 _ _ _ H0).\n        have H_inl := Failure_not_failed_no_fail H'_step1 _ n H_in.\n        rewrite H0 in H_inl.\n        by case: H_inl; left.\n      case (In_dec name_eq_dec from failed) => H_in; first exact: (recv_fail_from_neq H'_step1 _ _ _ _ H0).\n      have H_inl := Failure_not_failed_no_fail H'_step1 _ n H_in.\n      rewrite H0 in H_inl.\n      by case: H_inl; left.      \n    case (name_eq_dec from n) => H_neq; first by rewrite H_neq (Failure_self_channel_empty H'_step1) in H0.\n    case (name_eq_dec from n') => H_dec'.\n      rewrite H_dec'.\n      rewrite H_dec' in H0 H_dec.\n      case (In_dec name_eq_dec n' failed) => H_in; first by apply: (recv_fail_from_eq H'_step1 _ _ _ H0) => //; auto.\n      have H_inl := Failure_not_failed_no_fail H'_step1 _ n H_in.\n      rewrite H0 in H_inl.\n      by case: H_inl; left.\n    case (In_dec name_eq_dec from failed) => H_in; first exact: (recv_fail_from_neq H'_step1 _ _ _ _ H0).\n    have H_inl := Failure_not_failed_no_fail H'_step1 _ n H_in.\n    rewrite H0 in H_inl.\n    by case: H_inl; left.\n  rewrite /update2 /=.\n  case (sumbool_and _ _ _ _) => H_dec' //.\n  move: H_dec' => [H_eq H_eq'].\n  rewrite H_eq H_eq' in H0 H1 H5 H_dec.\n  have H_f := Failure_not_failed_no_fail H'_step1 _ n' H_in_f.\n  rewrite H0 in H_f.\n  by case: H_f; left.\n- by find_apply_lem_hyp input_handlers_IOHandler.\n- move => H_in.\n  have H_neq: h <> n by move => H_eq; case: H_in; left.\n  have H_f: ~ In n failed by move => H_in'; case: H_in; right.\n  rewrite collate_neq //.\n  exact: IHH'_step1.\nQed.\n\nEnd SingleNodeInvOut.\n\nSection SingleNodeInvIn.\n\nVariable onet : ordered_network.\n\nVariable failed : list name.\n\nVariable tr : list (name * (input + output)).\n\nHypothesis H_step : step_ordered_failure_star step_ordered_failure_init (failed, onet) tr.\n\nVariables n n' : name.\n\nHypothesis not_failed : ~ In n failed.\n\nVariable P : Data -> list msg -> Prop.\n\nHypothesis after_init : P (InitData n) [].\n\nHypothesis recv_fail_neq :\n  forall onet failed tr ms,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr ->\n  ~ In n failed ->\n  In n' failed ->\n  n <> n' ->\n  onet.(onwPackets) n' n = Fail :: ms ->\n  P (onet.(onwState) n) (onet.(onwPackets) n' n) ->\n  P (mkData (NSet.remove n' (onet.(onwState) n).(adjacent))) ms.\n\nHypothesis recv_fail_other_neq :\n  forall onet failed tr from ms,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr ->\n  ~ In n failed ->\n  n <> from ->\n  n' <> from ->\n  onet.(onwPackets) from n = Fail :: ms ->\n  P (onet.(onwState) n) (onet.(onwPackets) n' n) ->\n  P (mkData (NSet.remove from (onet.(onwState) n).(adjacent))) (onet.(onwPackets) n' n).\n\nHypothesis fail_adjacent :\n  forall onet failed tr,\n    step_ordered_failure_star step_ordered_failure_init (failed, onet) tr ->\n    n' <> n ->\n    ~ In n failed ->\n    ~ In n' failed ->\n    adjacent_to n' n ->\n    P (onet.(onwState) n) (onet.(onwPackets) n' n) ->\n    P (onwState onet n) (onwPackets onet n' n ++ [Fail]).\n\nTheorem P_inv_n_in : P (onet.(onwState) n) (onet.(onwPackets) n' n).\nProof.\nmove: onet failed tr H_step not_failed.\nclear onet failed not_failed tr H_step.\nmove => onet' failed' tr H'_step.\nhave H_eq_f: failed' = fst (failed', onet') by [].\nhave H_eq_o: onet' = snd (failed', onet') by [].\nrewrite H_eq_f {H_eq_f}.\nrewrite {2 3}H_eq_o {H_eq_o}.\nremember step_ordered_failure_init as y in H'_step.\nmove: Heqy.\ninduction H'_step using refl_trans_1n_trace_n1_ind => /= H_init.\n  rewrite H_init /step_ordered_failure_init /= => H_in_f.\n  exact: after_init.\nconcludes.\nmatch goal with\n| [ H : step_ordered_failure _ _ _ |- _ ] => invc H\nend; simpl.\n- move => H_in_f.\n  find_apply_lem_hyp net_handlers_NetHandler.\n  net_handler_cases.\n  rewrite /update /=.\n  case name_eq_dec => H_dec.\n    rewrite -H_dec in H1 H5 H0.\n    have H_neq: n <> from.\n      move => H_eq.\n      rewrite -H_eq in H0.\n      by rewrite (Failure_self_channel_empty H'_step1) in H0.\n    rewrite -H_dec /update2 /= {H_dec to H'_step2}.\n    case (sumbool_and _ _ _ _) => H_dec.\n      move: H_dec => [H_eq H_eq'].\n      rewrite H_eq {H_eq from} in H0 H5 H_neq.\n      case: d H5 => /= adjacent0 H_eq.\n      rewrite H_eq {H_eq adjacent0}.\n      case (In_dec name_eq_dec n' failed) => H_in; first exact: (recv_fail_neq H'_step1).\n      have H_inl := Failure_not_failed_no_fail H'_step1 _ n H_in.\n      rewrite H0 in H_inl.\n      by case: H_inl; left.\n    case: H_dec => H_dec //.\n    case: d H5 => /= adjacent0 H_eq.\n    rewrite H_eq {H_eq adjacent0}.\n    apply: (recv_fail_other_neq H'_step1 _ _ _ H0) => //.\n    move => H_neq'.\n    by case: H_dec.\n  rewrite /update2 /=.\n  case (sumbool_and _ _ _ _) => H_dec' //.\n  move: H_dec' => [H_eq H_eq'].\n  by rewrite H_eq' in H_dec.\n- by find_apply_lem_hyp input_handlers_IOHandler.\n- move => H_in.\n  have H_neq: h <> n by move => H_eq; case: H_in; left.\n  have H_f: ~ In n failed by move => H_in'; case: H_in; right.\n  case (name_eq_dec h n') => H_dec.\n    rewrite H_dec in H0 H_neq H_f.\n    rewrite H_dec {H_dec h H'_step2 H_in}.\n    case (adjacent_to_dec n' n) => H_dec.\n      rewrite collate_map2snd_not_in_related //.\n      * apply (fail_adjacent H'_step1) => //.\n        exact: IHH'_step1.\n      * exact: all_names_nodes.\n      * exact: no_dup_nodes.\n    rewrite collate_map2snd_not_related //.\n    exact: IHH'_step1.\n  rewrite collate_neq //.\n  exact: IHH'_step1.\nQed.\n\nEnd SingleNodeInvIn.\n\nSection DualNodeInv.\n\nVariable onet : ordered_network.\n\nVariable failed : list name.\n\nVariable tr : list (name * (input + output)).\n\nHypothesis H_step : step_ordered_failure_star step_ordered_failure_init (failed, onet) tr.\n\nVariables n n' : name.\n\nHypothesis not_failed_n : ~ In n failed.\n\nHypothesis not_failed_n' : ~ In n' failed.\n\nVariable P : Data -> Data -> list msg -> list msg -> Prop.\n\n(* FIXME *)\nHypothesis after_init : P (InitData n) (InitData n') [] [].\n\nHypothesis recv_fail_self :\n  forall onet failed tr from ms,\n    step_ordered_failure_star step_ordered_failure_init (failed, onet) tr ->\n    n' = n ->\n    ~ In n failed ->\n    onet.(onwPackets) from n = Fail :: ms ->\n    n <> from ->\n    P (onet.(onwState) n) (onet.(onwState) n) (onet.(onwPackets) n n) (onet.(onwPackets) n n) ->\n    P (mkData (NSet.remove from (onet.(onwState) n).(adjacent)))\n      (mkData (NSet.remove from (onet.(onwState) n).(adjacent)))\n      (onet.(onwPackets) n n) (onet.(onwPackets) n n).\n\nHypothesis recv_fail_other :\n  forall onet failed tr from ms,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr ->\n    ~ In n failed ->\n    ~ In n' failed ->\n    onet.(onwPackets) from n = Fail :: ms ->\n    n <> n' ->\n    from <> n ->\n    from <> n' ->\n    P (onet.(onwState) n) (onet.(onwState) n') (onet.(onwPackets) n n') (onet.(onwPackets) n' n) ->\n    P (mkData (NSet.remove from (onet.(onwState) n).(adjacent))) (onet.(onwState) n')\n      (onet.(onwPackets) n n') (onet.(onwPackets) n' n).\n\nHypothesis recv_other_fail :\n  forall onet failed tr from ms,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr ->\n    ~ In n failed ->\n    ~ In n' failed ->\n    onet.(onwPackets) from n' = Fail :: ms ->\n    n <> n' ->\n    from <> n ->\n    from <> n' ->\n    P (onet.(onwState) n) (onet.(onwState) n') (onet.(onwPackets) n n') (onet.(onwPackets) n' n) ->\n    P (onet.(onwState) n) (mkData (NSet.remove from (onet.(onwState) n').(adjacent))) \n      (onet.(onwPackets) n n') (onet.(onwPackets) n' n).\n\nTheorem P_dual_inv : P (onet.(onwState) n) (onet.(onwState) n') (onet.(onwPackets) n n') (onet.(onwPackets) n' n).\nProof.\nmove: onet failed tr H_step not_failed_n not_failed_n'.\nclear onet failed not_failed_n not_failed_n' tr H_step.\nmove => onet' failed' tr H'_step.\nhave H_eq_f: failed' = fst (failed', onet') by [].\nhave H_eq_o: onet' = snd (failed', onet') by [].\nrewrite H_eq_f {H_eq_f}.\nrewrite {3 4 5 6}H_eq_o {H_eq_o}.\nremember step_ordered_failure_init as y in H'_step.\nmove: Heqy.\ninduction H'_step using refl_trans_1n_trace_n1_ind => /= H_init.\n  rewrite H_init /step_ordered_failure_init /= => H_in_f H_in_f'.\n  exact: after_init.\nconcludes.\nmatch goal with\n| [ H : step_ordered_failure _ _ _ |- _ ] => invc H\nend; simpl.\n- rewrite /= in IHH'_step1.\n  move {H'_step2}.\n  move => H_in_f H_in_f'.\n  find_apply_lem_hyp net_handlers_NetHandler.\n  net_handler_cases.\n  rewrite /update /=.\n  case name_eq_dec => H_dec_n.\n    rewrite -H_dec_n.\n    rewrite -H_dec_n {H_dec_n to} in H5 H6 H1 H0.\n    case name_eq_dec => H_dec_n'.\n      rewrite H_dec_n'.\n      rewrite H_dec_n' in H_in_f' H6.\n      rewrite /update2.\n      case (sumbool_and _ _ _ _) => H_dec.\n        move: H_dec => [H_eq H_eq'].\n        rewrite H_eq in H0.\n        by rewrite (Failure_self_channel_empty H'_step1) in H0.\n      case: H_dec => H_dec //.\n      case: d H5 => /= adjacent0 H_eq.\n      rewrite H_eq {H_eq adjacent0}.\n      apply (recv_fail_self H'_step1 H_dec_n' H1 H0) => //.\n      move => H_neq.\n      by rewrite H_neq in H_dec.\n    case: d H5 => /= adjacent0 H_eq.\n    rewrite H_eq {H_eq adjacent0}.\n    rewrite /update2 /=.\n    case (sumbool_and _ _ _ _) => H_dec; case (sumbool_and _ _ _ _) => H_dec'.\n    * move: H_dec => [H_eq_n H_eq_n'].\n      by rewrite H_eq_n' in H_dec_n'.\n    * move: H_dec => [H_eq_n H_eq_n'].\n      by rewrite H_eq_n' in H_dec_n'.    \n    * move: H_dec' => [H_eq_n H_eq_n'].\n      rewrite H_eq_n in H0.\n      have H_inl := Failure_not_failed_no_fail H'_step1 _ n H_in_f'.\n      case: H_inl.\n      by rewrite H0; left.\n    * case: H_dec' => H_dec' //.\n      have H_neq: from <> n.\n        move => H_eq'.\n        rewrite H_eq' in H0.\n        by rewrite (Failure_self_channel_empty H'_step1) in H0.\n      move {H_dec}.\n      apply (recv_fail_other H'_step1 H_in_f H_in_f' H0) => //.\n      move => H_neq'.\n      by rewrite H_neq' in H_dec_n'.\n    case name_eq_dec => H_dec_n'.\n      rewrite -H_dec_n'.\n      rewrite -H_dec_n' {to H_dec_n'} in H0 H_dec_n H1 H5.\n      case: d H5 => /= adjacent0 H_eq.\n      rewrite H_eq {adjacent0 H_eq}.\n      rewrite /update2 /=.\n      case (sumbool_and _ _ _ _) => H_dec; case (sumbool_and _ _ _ _) => H_dec'.\n      * move: H_dec' => [H_eq H_eq'].\n        by rewrite H_eq' in H_dec_n.\n      * move: H_dec => [H_eq H_eq'].\n        rewrite H_eq in H0.\n        have H_inl := Failure_not_failed_no_fail H'_step1 _ n' H_in_f.\n        case: H_inl.\n        rewrite H0.\n        by left.\n      * move: H_dec' => [H_eq H_eq'].\n        by rewrite H_eq' in H_dec_n.\n      * case: H_dec => H_dec //.\n        have H_neq: from <> n'.\n          move => H_eq'.\n          rewrite H_eq' in H0.\n          by rewrite (Failure_self_channel_empty H'_step1) in H0.\n        move {H_dec'}.\n        exact: (recv_other_fail H'_step1 H_in_f H_in_f' H0).\n      rewrite /update2 /=.\n      case (sumbool_and _ _ _ _) => H_dec; case (sumbool_and _ _ _ _) => H_dec'.\n      * move: H_dec => [H_eq H_eq'].\n        by rewrite H_eq' in H_dec_n'.\n      * move: H_dec => [H_eq H_eq'].\n        by rewrite H_eq' in H_dec_n'.\n      * move: H_dec' => [H_eq H_eq'].\n        by rewrite H_eq' in H_dec_n.\n      * exact: H6.\n- rewrite /= in IHH'_step1.\n  move {H'_step2}.\n  move => H_in_f H_in_f'.\n  find_apply_lem_hyp input_handlers_IOHandler.\n  by io_handler_cases.\n- rewrite /= in IHH'_step1.\n  move => H_nor H_nor'.\n  have H_neq: h <> n.\n    move => H_eq.\n    case: H_nor.\n    by left.\n  have H_in_f: ~ In n failed.\n    move => H_in_f.\n    case: H_nor.\n    by right.    \n  have H_neq': h <> n'.\n    move => H_eq.\n    case: H_nor'.\n    by left.\n  have H_in_f': ~ In n' failed.\n    move => H_in_f'.\n    case: H_nor'.\n    by right.\n  have IH := IHH'_step1 H_in_f H_in_f'.\n  move {H_nor H_nor' IHH'_step1}.\n  rewrite collate_neq //.\n  by rewrite collate_neq.\nQed.\n\nEnd DualNodeInv.\n\nLemma Failure_in_adj_adjacent_to :\nforall onet failed tr,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr -> \n  forall (n n' : name),\n    ~ In n failed ->\n    NSet.In n' (onet.(onwState) n).(adjacent) ->\n    adjacent_to n' n.\nProof.\nmove => net failed tr H_st.\nmove => n n' H_f.\npose P_curr (d : Data) := NSet.In n' d.(adjacent) -> adjacent_to n' n.\nrewrite -/(P_curr _).\napply: (P_inv_n H_st); rewrite /P_curr //= {P_curr net tr H_st failed H_f}.\n- move => H_ins.\n  apply adjacent_to_node_adjacency in H_ins.\n  apply filter_rel_related in H_ins.\n  move: H_ins => [H_in H_adj].\n  by apply adjacent_to_symmetric in H_adj.\n- move => net failed tr n0 H_st H_in_f IH H_adj.\n  apply: IH.\n  by apply NSetFacts.remove_3 in H_adj.\nQed.\n\nLemma Failure_in_adj_or_incoming_fail :\nforall onet failed tr,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr -> \n  forall n n',\n    ~ In n failed ->\n    NSet.In n' (onet.(onwState) n).(adjacent) ->\n    ~ In n' failed \\/ (In n' failed /\\ In Fail (onet.(onwPackets) n' n)).\nProof.\nmove => onet failed tr H.\nhave H_eq_f: failed = fst (failed, onet) by [].\nhave H_eq_o: onet = snd (failed, onet) by [].\nrewrite H_eq_f {H_eq_f}.\nrewrite {2 5}H_eq_o {H_eq_o}.\nremember step_ordered_failure_init as y in *.\nmove: Heqy.\ninduction H using refl_trans_1n_trace_n1_ind => /= H_init.\n  rewrite H_init /= {H_init}.\n  move => n n' H_ins.\n  by left.\nconcludes.\nmatch goal with\n| [ H : step_ordered_failure _ _ _ |- _ ] => invc H\nend; simpl.\n- move => n n' H_in_f H_ins.\n  find_apply_lem_hyp net_handlers_NetHandler.\n  net_handler_cases.  \n  rewrite /= /update2 {H1}.\n  case (sumbool_and _ _ _ _) => H_dec.\n    move: H_dec => [H_eq H_eq'].\n    rewrite H_eq H_eq' {H_eq H_eq' to from} in H7 H_ins H3 H2.\n    rewrite /= in IHrefl_trans_1n_trace1.\n    move: H_ins.\n    rewrite /update /=.\n    case name_eq_dec => H_dec //.\n    move => H_ins.\n    case: d H7 H_ins => /= adjacent0 H_eq H_adj.\n    rewrite H_eq in H_adj.\n    by apply NSetFacts.remove_1 in H_adj.\n  move: H_ins.\n  rewrite /update /=.\n  case name_eq_dec => H_dec'.\n    case: H_dec => H_dec; last by rewrite H_dec' in H_dec.\n    case: d H7 => /= adjacent0 H_eq.\n    move => H_ins.\n    rewrite H_eq {adjacent0 H_eq} in H_ins.\n    rewrite -H_dec' {to H_dec'} in H2 H3 H_ins.\n    apply NSetFacts.remove_3 in H_ins.\n    exact: IHrefl_trans_1n_trace1.\n  move => H_ins.\n  exact: IHrefl_trans_1n_trace1.\n- find_apply_lem_hyp input_handlers_IOHandler.\n  by io_handler_cases.\n- move => n n' H_in_f H_ins.\n  rewrite /= in IHrefl_trans_1n_trace1.\n  have H_neq: h <> n.\n    move => H_eq.\n    case: H_in_f.\n    by left.\n  have H_in_f': ~ In n failed0.\n    move => H_in.\n    case: H_in_f.\n    by right.  \n  have IH := IHrefl_trans_1n_trace1 _ _ H_in_f' H_ins.\n  case (name_eq_dec h n') => H_dec.\n    rewrite H_dec.\n    right.\n    split; first by left.\n    rewrite H_dec in H2.\n    have H_adj := Failure_in_adj_adjacent_to H _ H_in_f' H_ins.\n    rewrite collate_map2snd_not_in_related //.\n    * apply in_or_app.\n      by right; left.\n    * exact: all_names_nodes.\n    * exact: no_dup_nodes.\n  case: IH => IH.\n    left.\n    move => H_or.\n    by case: H_or => H_or.\n  move: IH => [H_in H_fail].\n  right.\n  split; first by right.\n  by rewrite collate_neq.\nQed.\n\nLemma Failure_le_one_fail : \n  forall onet failed tr,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr -> \n  forall n n',\n    ~ In n failed ->\n    count_occ Msg_eq_dec (onet.(onwPackets) n' n) Fail <= 1.\nProof.\nmove => onet failed tr H_st.\nmove => n n' H_in_f.\npose P_curr (d : Data) (l : list Msg) := \n  count_occ Msg_eq_dec l Fail <= 1.\nrewrite -/(P_curr (onet.(onwState) n) _).\napply: (P_inv_n_in H_st); rewrite /P_curr //= {P_curr onet tr H_st failed H_in_f}.\n- by auto with arith.\n- move => onet failed tr ms.\n  move => H_st H_in_f H_in_f' H_neq H_eq IH.\n  rewrite H_eq /= in IH.\n  by omega.\n- move => onet failed tr H_st H_neq H_in_f H_in_f'.\n  move => H_adj IH.\n  have H_f := Failure_not_failed_no_fail H_st _ n H_in_f'.\n  have H_cnt : ~ count_occ Msg_eq_dec (onwPackets onet n' n) Fail > 0.\n    move => H_cnt.\n    by apply count_occ_In in H_cnt.\n  have H_cnt_eq: count_occ Msg_eq_dec (onwPackets onet n' n) Fail = 0 by omega.\n  rewrite count_occ_app /= H_cnt_eq.\n  by auto with arith.\nQed.\n\nLemma Failure_adjacent_to_in_adj :\nforall onet failed tr,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr -> \n  forall n n',\n    ~ In n failed ->\n    ~ In n' failed ->\n    adjacent_to n' n ->\n    NSet.In n' (onet.(onwState) n).(adjacent).\nProof.\nmove => onet failed tr H_st.\nmove => n n' H_f H_f'.\npose P_curr (d d' : Data) (l l' : list Msg) := \n  adjacent_to n' n -> \n  NSet.In n' d.(adjacent).\nrewrite -/(P_curr _ (onet.(onwState) n') (onet.(onwPackets) n n')\n (onet.(onwPackets) n' n)).\napply: (P_dual_inv H_st); rewrite /P_curr //= {P_curr onet tr H_st failed H_f H_f'}.\n- move => H_adj.\n  apply adjacent_to_node_adjacency.\n  apply related_filter_rel; first exact: all_names_nodes.\n  exact: adjacent_to_symmetric.\n- move => onet failed tr from ms H_st H_eq H_in_f H_eq' H_neq H_adj H_adj_to.\n  rewrite H_eq in H_adj_to.\n  contradict H_adj_to.\n  exact: adjacent_to_irreflexive.\n- move => onet failed tr from ms H_st H_in_f H_in_f' H_eq H_neq H_neq_f H_neq_f' IH H_adj.\n  concludes.\n  by apply NSetFacts.remove_2.\nQed.\n\nLemma Failure_in_queue_fail_then_adjacent : \n  forall onet failed tr,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr -> \n  forall n n',\n    ~ In n failed ->\n    In Fail (onet.(onwPackets) n' n) ->\n    NSet.In n' (onet.(onwState) n).(adjacent).\nProof.\nmove => onet failed tr H_st.\nmove => n n' H_in_f.\npose P_curr (d : Data) (l : list Msg) := \n  In Fail l ->\n  NSet.In n' d.(adjacent).\nrewrite -/(P_curr _ _).\napply: (P_inv_n_in H_st); rewrite /P_curr //= {P_curr onet tr H_st failed H_in_f}.\n- move => onet failed tr ms H_st H_in_f H_in_f' H_neq H_eq IH H_in.\n  have H_cnt: count_occ Msg_eq_dec ms Fail > 0 by apply count_occ_In.\n  have H_cnt': count_occ Msg_eq_dec (onet.(onwPackets) n' n) Fail > 1 by rewrite H_eq /=; auto with arith.\n  have H_le := Failure_le_one_fail H_st _ n' H_in_f.\n  by omega.\n- move => onet failed tr from ms H_st H_in_f H_neq H_neq'.\n  move => H_eq IH H_in.\n  apply NSetFacts.remove_2; first by move => H_eq'; rewrite H_eq' in H_neq'.\n  exact: IH.\n- move => onet failed tr H_st H_neq H_in_f H_in_f' H_adj IH H_in.\n  exact (Failure_adjacent_to_in_adj H_st H_in_f H_in_f' H_adj).\nQed.\n\nLemma Failure_first_fail_in_adj : \n  forall onet failed tr,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr -> \n  forall n n',\n    ~ In n failed ->\n    head (onet.(onwPackets) n' n) = Some Fail ->\n    NSet.In n' (onet.(onwState) n).(adjacent).\nProof.\nmove => onet failed tr H_st.\nmove => n n' H_in_f.\npose P_curr (d : Data) (l : list Msg) := \n  hd_error l = Some Fail ->\n  NSet.In n' d.(adjacent).\nrewrite -/(P_curr _ _).\napply: (P_inv_n_in H_st); rewrite /P_curr //= {P_curr onet tr H_st failed H_in_f}.\n- move => onet failed tr ms H_st H_in_f H_in_f' H_neq H_eq IH H_hd.\n  have H_neq' := hd_error_some_nil H_hd.\n  case: ms H_eq H_hd H_neq' => //.\n  case => ms H_eq H_hd H_neq'.\n  have H_cnt: count_occ Msg_eq_dec (onwPackets onet n' n) Fail > 1 by rewrite H_eq /=; auto with arith.\n  have H_le := Failure_le_one_fail H_st _ n' H_in_f.\n  by omega.\n- move => onet failed tr from ms H_st H_in_f H_neq H_neq' H_eq IH H_hd.\n  concludes.\n  apply NSetFacts.remove_2 => //.\n  move => H_eq'.\n  by rewrite H_eq' in H_neq'.\n- move => onet failed tr H_st H_neq H_in_f H_in_f' H_adj IH H_hd.\n  by have H_a := Failure_adjacent_to_in_adj H_st H_in_f H_in_f' H_adj.\nQed.\n\nLemma Failure_adjacent_failed_incoming_fail : \n  forall onet failed tr,\n  step_ordered_failure_star step_ordered_failure_init (failed, onet) tr -> \n  forall n n',\n    ~ In n failed ->\n    NSet.In n' (onet.(onwState) n).(adjacent) ->\n    In n' failed ->\n    In Fail (onet.(onwPackets) n' n).\nProof.\nmove => onet failed tr H_st n n' H_in_f H_adj H_in_f'.\nhave H_or := Failure_in_adj_or_incoming_fail H_st _ H_in_f H_adj.\ncase: H_or => H_or //.\nby move: H_or => [H_in H_in'].\nQed.\n\nEnd FailureRecorderCorrect.\n", "meta": {"author": "DistributedComponents", "repo": "verdi-aggregation", "sha": "c81681555d63d4a3db225119600833868caf4607", "save_path": "github-repos/coq/DistributedComponents-verdi-aggregation", "path": "github-repos/coq/DistributedComponents-verdi-aggregation/verdi-aggregation-c81681555d63d4a3db225119600833868caf4607/systems/FailureRecorderStaticCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22158186035846725}}
{"text": "From HypVeri.algebra Require Import base.\nFrom HypVeri.rules Require Import rules_base.\n\nSection instr.\n  (* shorthands for writing programs *)\n\n  Context `{hypparams: HypervisorParameters}.\n\n  Definition mov_word_I ra w := encode_instruction (Mov ra (inl w)).\n  Definition mov_reg_I ra rb := encode_instruction (Mov ra (inr rb)).\n  Definition add_I ra rb := encode_instruction (Add ra rb).\n  Definition halt_I := encode_instruction Halt.\n  Definition str_I ra rb := encode_instruction (Str ra rb).\n  Definition ldr_I ra rb := encode_instruction (Ldr ra rb).\n  Definition br_I r := encode_instruction (Br r).\n  Definition cmp_word_I ra w := encode_instruction (Cmp ra (inl w)).\n  Definition bne_I r := encode_instruction (Bne r).\n\n  Definition hvc_I := encode_instruction Hvc.\n  Definition run_I := encode_hvc_func Run.\n  Definition yield_I := encode_hvc_func Yield.\n  Definition mem_lend_I := encode_hvc_func Lend.\n  Definition mem_share_I := encode_hvc_func Share.\n  Definition mem_reclaim_I := encode_hvc_func Reclaim.\n  Definition mem_retrieve_I := encode_hvc_func Retrieve.\n  Definition mem_relinquish_I := encode_hvc_func Relinquish.\n  Definition msg_send_I := encode_hvc_func Send.\n  Definition msg_poll_I := encode_hvc_func Poll.\n\n  Definition encode_instructions (l: list instruction) :=\n    map encode_instruction l.\n\n  Lemma encode_instructions_length l :\n   length (encode_instructions l) = length l.\n  Proof. rewrite map_length //. Qed.\n\n  Context `{gen_VMG Σ}.\n\n  Definition program (instr: list Word) (b:Addr):=\n    ([∗ list] a;w ∈ (finz.seq b (length instr));instr, (a ->a w))%I.\n\nEnd instr.\n", "meta": {"author": "logsem", "repo": "VMSL", "sha": "0a9b005b599a770e40c07abc9aa10a4ee9759315", "save_path": "github-repos/coq/logsem-VMSL", "path": "github-repos/coq/logsem-VMSL/VMSL-0a9b005b599a770e40c07abc9aa10a4ee9759315/theories/examples/instr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2215818603584672}}
{"text": "From Velus Require Import Common.\nFrom Velus Require Import Environment.\nFrom Velus Require Import Operators.\nFrom Velus Require Import Clocks.\nFrom Velus Require Import Lustre.LSyntax.\n\nFrom Coq Require Import List.\nImport List.ListNotations.\nOpen Scope list_scope.\n\nFrom Coq Require Import Morphisms.\nFrom Coq Require Import Permutation.\n\nFrom Coq Require Import Program.Basics Program.Wf.\nOpen Scope program_scope.\n\n(** * Lustre clocking *)\n\n(**\n\n  Clocking judgements for Lustre.\n  Classify Lustre programs which are statically well-formed.\n\n *)\n\nModule Type LCLOCKING\n       (Import Ids  : IDS)\n       (Import Op   : OPERATORS)\n       (Import Syn  : LSYNTAX Ids Op).\n\n  (** Substitutions and conversion between clock types.\n\n      The clocking of function applications is complicated by the possibility\n      of 'anonymous' variables and their clocks.\n\n      Consider, for instance, the two node (clock) interfaces\n          f (a :: .; b :: . on a) returns (w :: .; x :: . on w)\n          g (c :: .; d :: . on c) returns (y :: .; z :: . on y)\n\n       and the equation\n          u, v = g(f(b, e when b))\n\n       The input parameters of f and their clocks are instantiated from\n       the expressions; f yields two streams and the second one is dependent\n       on the first. This dependency needs to be captured and verified in\n       the application of g. The problem is that these intermediate flows\n       are not bound to variable names in the environment.\n\n       To treat this detail, we introduce \"named streams\" that allow us to\n       bind such flows to a local name. Clock annotations within\n       expressions are then made with \"named clocks\" (nclock), a pair where\n       the second member is either None for an anonymous stream, or Some for\n       a locally named stream.\n\n       The structure of an expression can be seen as stacks of function\n       applications rooted in an equation (a pattern binding of variable\n       names to resulting streams):\n\n       The expressions at the tips are clocked in the node environment, thus\n       any variables are directly named. Each function call, however, may\n       introduce fresh clock names to track dependencies between node outputs\n       and for checking dependencies at node inputs. Unlike for a named clock,\n       the scope of a fresh clock is limited to its \"column\". The freshness\n       of clocks is ensured by a constraint (NoDup) applied on the collected\n       clocks (anon_in).\n\n       Three kinds of substitutions are needed to handle node applications and\n       equation patterns:\n\n       1. input substitutions: map some input parameter names to clock ids.\n          For instance, in \"f(t :: ck, e1 :: ck on t)\", \"f\" must be\n          instantiated with the input substitution \"(ck, [ t / a ])\", giving\n          the base clock and variable mappings, before testing for equality\n          of the clocks of the arguments, \"[(t : ck); ck on t]\", against the\n          instantiated input parameters and clocks.\n\n       2. output substitutions: map some output parameter names to fresh\n          clock indexes. For instance, in the previous example, an output\n          substitution for \"f\" could be \"[ w / 1 ]\" giving the output\n          clocks \"[(1 : ck); ck on 1]\". The use of \"1\" is arbitrary, other\n          valid substitutions would give \"[(2: ck); ck on 2]\" or\n          \"[(42 : ck); ck on 42]\". Substitutions need only reflect clock\n          dependencies and satisfy the freshness constraint whenever\n          expression \"branches\" join.\n\n       3. pattern substitutions: in an equation, the fresh clock indexes\n          must be mapped to the variable names appearing in the lhs pattern.\n          An unmapped index indicates an escaping clock and thus a clocking\n          problem. In the example, we may have:\n             f [(b:ck); ck on b] -> [(1:ck); ck on 1]\n             g [(1:ck); ck on 1] -> [(2:ck); ck on 2]\n\n          and thus \"[(2:ck); ck on 2]\" must be unified with\n          \"[(u:ck); ck on u]\", and the required substitution is \"[ u / 2 ]\".\n   *)\n\n  (* substitution of identifiers *)\n  Definition ident_map := ident -> option ident.\n\n  (* xc : name and clock from the node interface\n     nc : named clock from the annotated expression *)\n  Definition WellInstantiated (bck : clock) (sub : ident_map)\n                              (xc : ident * clock) (nc : nclock) : Prop :=\n    sub (fst xc) = snd nc\n    /\\ instck bck sub (snd xc) = Some (fst nc).\n\n  Section WellClocked.\n\n    Variable G    : global.\n    Variable vars : list (ident * clock).\n\n    (** EvarAnon is used at toplevel of an equation, to allow for equations of the form\n        x = y, without having to specify a name. Evar is used internally to expressions *)\n    Inductive wc_exp : exp -> Prop :=\n    | wc_Econst: forall c,\n        wc_exp (Econst c)\n\n    | wc_Evar: forall x ty ck,\n        In (x, ck) vars ->\n        wc_exp (Evar x (ty, (ck, Some x)))\n\n    | wc_EvarAnon: forall x ty ck,\n        In (x, ck) vars ->\n        wc_exp (Evar x (ty, (ck, None)))\n\n    | wc_Eunop: forall op e ty ck,\n        wc_exp e ->\n        clockof e = [ck] ->\n        wc_exp (Eunop op e (ty, (ck, None)))\n\n    | wc_Ebinop: forall op e1 e2 ty ck,\n        wc_exp e1 ->\n        wc_exp e2 ->\n        clockof e1 = [ck] ->\n        clockof e2 = [ck] ->\n        wc_exp (Ebinop op e1 e2 (ty, (ck, None)))\n\n    | wc_Efby: forall e0s es anns,\n        Forall wc_exp e0s ->\n        Forall wc_exp es ->\n        Forall2 eq (map clock_of_nclock anns) (clocksof e0s) ->\n        Forall2 eq (map clock_of_nclock anns) (clocksof es) ->\n        Forall unnamed_stream anns ->\n        wc_exp (Efby e0s es anns)\n\n    | wc_Earrow: forall e0s es anns,\n        Forall wc_exp e0s ->\n        Forall wc_exp es ->\n        Forall2 eq (map clock_of_nclock anns) (clocksof e0s) ->\n        Forall2 eq (map clock_of_nclock anns) (clocksof es) ->\n        Forall unnamed_stream anns ->\n        wc_exp (Earrow e0s es anns)\n\n    | wc_Ewhen: forall es x b tys ck,\n        Forall wc_exp es ->\n        In (x, ck) vars ->\n        Forall (eq ck) (clocksof es) ->\n        length tys = length (clocksof es) ->\n        wc_exp (Ewhen es x b (tys, (Con ck x b, None)))\n\n    | wc_Emerge: forall x ets efs tys ck,\n        Forall wc_exp ets ->\n        Forall wc_exp efs ->\n        In (x, ck) vars ->\n        Forall (eq (Con ck x true))  (clocksof ets) ->\n        Forall (eq (Con ck x false)) (clocksof efs) ->\n        length tys = length (clocksof ets) ->\n        length tys = length (clocksof efs) ->\n        wc_exp (Emerge x ets efs (tys, (ck, None)))\n\n    | wc_Eifte: forall e ets efs tys ck,\n        wc_exp e ->\n        Forall wc_exp ets ->\n        Forall wc_exp efs ->\n        clockof e = [ck] ->\n        Forall (eq ck) (clocksof ets) ->\n        Forall (eq ck) (clocksof efs) ->\n        length tys = length (clocksof ets) ->\n        length tys = length (clocksof efs) ->\n        0 < length tys ->\n        wc_exp (Eite e ets efs (tys, (ck, None)))\n\n    | wc_Eapp: forall f es anns n bck sub,\n        Forall wc_exp es ->\n        find_node f G = Some n ->\n        Forall2 (WellInstantiated bck sub) (idck n.(n_in)) (nclocksof es) ->\n        Forall2 (WellInstantiated bck sub) (idck n.(n_out)) (map snd anns) ->\n        wc_exp (Eapp f es None anns)\n\n    | wc_EappReset: forall f es r ckr anns n bck sub,\n        Forall wc_exp es ->\n        find_node f G = Some n ->\n        Forall2 (WellInstantiated bck sub) (idck n.(n_in)) (nclocksof es) ->\n        Forall2 (WellInstantiated bck sub) (idck n.(n_out)) (map snd anns) ->\n        wc_exp r ->\n        clockof r = [ckr] ->\n        wc_exp (Eapp f es (Some r) anns).\n\n  Definition wc_equation (xses : equation) : Prop :=\n    let (xs, es) := xses in\n    Forall wc_exp es\n    /\\ Forall2 (fun x nc => LiftO True (eq x) (snd nc)) xs (nclocksof es)\n    /\\ Forall2 (fun x ck => In (x, ck) vars) xs (clocksof es).\n  End WellClocked.\n\n  Definition wc_node (G: global) (n: node) : Prop\n    :=    wc_env (idck  n.(n_in))\n       /\\ wc_env (idck (n.(n_in) ++ n.(n_out)))\n       /\\ wc_env (idck (n.(n_in) ++ n.(n_out) ++ n.(n_vars)))\n       /\\ Forall (wc_equation G (idck (n.(n_in) ++ n.(n_vars) ++ n.(n_out)))) n.(n_eqs).\n\n  Inductive wc_global : global -> Prop :=\n  | wcg_nil:\n      wc_global []\n  | wcg_cons: forall n ns,\n      wc_global ns ->\n      wc_node ns n ->\n      Forall (fun n'=> n.(n_name) <> n'.(n_name) :> ident) ns ->\n      wc_global (n::ns).\n\n  (** ** Basic properties of clocking *)\n\n  Hint Constructors wc_exp wc_global : lclocking.\n  Hint Unfold wc_equation wc_node wc_env : lclocking.\n\n  Section wc_exp_ind2.\n\n    Variable G    : global.\n    Variable vars : list (ident * clock).\n    Variable P : exp -> Prop.\n\n    Hypothesis EconstCase:\n      forall c : const,\n        P (Econst c).\n\n    Hypothesis EvarCase:\n      forall x ty ck,\n        In (x, ck) vars ->\n        P (Evar x (ty, (ck, Some x))).\n\n    Hypothesis EvarAnonCase:\n      forall x ty ck,\n        In (x, ck) vars ->\n        P (Evar x (ty, (ck, None))).\n\n    Hypothesis EunopCase:\n      forall op e ty ck,\n        wc_exp G vars e ->\n        P e ->\n        clockof e = [ck] ->\n        P (Eunop op e (ty, (ck, None))).\n\n    Hypothesis EbinopCase:\n      forall op e1 e2 ty ck,\n        wc_exp G vars e1 ->\n        P e1 ->\n        wc_exp G vars e2 ->\n        P e2 ->\n        clockof e1 = [ck] ->\n        clockof e2 = [ck] ->\n        P (Ebinop op e1 e2 (ty, (ck, None))).\n\n    Hypothesis EfbyCase:\n      forall e0s es anns,\n        Forall (wc_exp G vars) e0s ->\n        Forall (wc_exp G vars) es ->\n        Forall P es ->\n        Forall P e0s ->\n        Forall2 eq (map clock_of_nclock anns) (clocksof e0s) ->\n        Forall2 eq (map clock_of_nclock anns) (clocksof es) ->\n        Forall unnamed_stream anns ->\n        P (Efby e0s es anns).\n\n    Hypothesis EarrowCase:\n      forall e0s es anns,\n        Forall (wc_exp G vars) e0s ->\n        Forall (wc_exp G vars) es ->\n        Forall P es ->\n        Forall P e0s ->\n        Forall2 eq (map clock_of_nclock anns) (clocksof e0s) ->\n        Forall2 eq (map clock_of_nclock anns) (clocksof es) ->\n        Forall unnamed_stream anns ->\n        P (Earrow e0s es anns).\n\n    Hypothesis EwhenCase:\n      forall es x b tys ck,\n        Forall (wc_exp G vars) es ->\n        Forall P es ->\n        In (x, ck) vars ->\n        Forall (eq ck) (clocksof es) ->\n        length tys = length (clocksof es) ->\n        P (Ewhen es x b (tys, (Con ck x b, None))).\n\n    Hypothesis EmergeCase:\n      forall x ets efs tys ck,\n        Forall (wc_exp G vars) ets ->\n        Forall P ets ->\n        Forall (wc_exp G vars) efs ->\n        Forall P efs ->\n        In (x, ck) vars ->\n        Forall (eq (Con ck x true))  (clocksof ets) ->\n        Forall (eq (Con ck x false)) (clocksof efs) ->\n        length tys = length (clocksof ets) ->\n        length tys = length (clocksof efs) ->\n        P (Emerge x ets efs (tys, (ck, None))).\n\n    Hypothesis EiteCase:\n      forall e ets efs tys ck,\n        wc_exp G vars e ->\n        P e ->\n        Forall (wc_exp G vars) ets ->\n        Forall P ets ->\n        Forall (wc_exp G vars) efs ->\n        Forall P efs ->\n        clockof e = [ck] ->\n        Forall (eq ck)  (clocksof ets) ->\n        Forall (eq ck) (clocksof efs) ->\n        length tys = length (clocksof ets) ->\n        length tys = length (clocksof efs) ->\n        0 < length tys ->\n        P (Eite e ets efs (tys, (ck, None))).\n\n    Hypothesis EappCase:\n      forall f es anns n bck sub,\n        Forall (wc_exp G vars) es ->\n        Forall P es ->\n        find_node f G = Some n ->\n        Forall2 (WellInstantiated bck sub) (idck n.(n_in)) (nclocksof es) ->\n        Forall2 (WellInstantiated bck sub) (idck n.(n_out)) (map snd anns) ->\n        P (Eapp f es None anns).\n\n    Hypothesis EappResetCase:\n      forall f es r ckr anns n bck sub,\n        Forall (wc_exp G vars) es ->\n        Forall P es ->\n        find_node f G = Some n ->\n        Forall2 (WellInstantiated bck sub) (idck n.(n_in)) (nclocksof es) ->\n        Forall2 (WellInstantiated bck sub) (idck n.(n_out)) (map snd anns) ->\n        wc_exp G vars r ->\n        clockof r = [ckr] ->\n        P r ->\n        P (Eapp f es (Some r) anns).\n\n    Fixpoint wc_exp_ind2 (e: exp) (H: wc_exp G vars e) {struct H} : P e.\n    Proof.\n      destruct H; eauto.\n      - apply EfbyCase; auto.\n        + clear H2. induction H0; auto.\n        + clear H1. induction H; auto.\n      - apply EarrowCase; auto.\n        + clear H2. induction H0; auto.\n        + clear H1. induction H; auto.\n      - apply EwhenCase; auto.\n        clear H1 H2. induction H; auto.\n      - apply EmergeCase; auto.\n        clear H2 H4. induction H; auto.\n        clear H3 H5. induction H0; auto.\n      - apply EiteCase; auto.\n        clear H3 H5. induction H0; auto.\n        clear H4 H6. induction H1; auto.\n      - eapply EappCase; eauto.\n        clear H0 H1. induction H; eauto.\n      - eapply EappResetCase; eauto.\n        clear H0 H1 H2. induction H; eauto.\n    Qed.\n\n  End wc_exp_ind2.\n\n  Lemma wc_global_NoDup:\n    forall g,\n      wc_global g ->\n      NoDup (map n_name g).\n  Proof.\n    induction g; eauto using NoDup.\n    intro WTg. simpl. constructor.\n    2:apply IHg; now inv WTg.\n    intro Hin.\n    inversion_clear WTg as [|? ? ? WTn Hn].\n    change (Forall (fun n' => (fun i=> a.(n_name) <> i) n'.(n_name)) g)%type in Hn.\n    apply Forall_map in Hn.\n    apply Forall_forall with (1:=Hn) in Hin.\n    now contradiction Hin.\n  Qed.\n\n  Lemma wc_global_app:\n    forall G G',\n      wc_global (G' ++ G) ->\n      wc_global G.\n  Proof.\n    induction G'; auto.\n    simpl. intro Hwc.\n    inversion Hwc; auto.\n  Qed.\n\n  Lemma wc_find_node:\n    forall G f n,\n      wc_global G ->\n      find_node f G = Some n ->\n      exists G', wc_node G' n.\n  Proof.\n    intros G f n' Hwc Hfind.\n    apply find_node_split in Hfind.\n    destruct Hfind as (bG & aG & HG).\n    subst. apply wc_global_app in Hwc.\n    inversion Hwc. eauto.\n  Qed.\n\n  Lemma indexes_app:\n    forall xs ys,\n      indexes (xs ++ ys) = indexes xs ++ indexes ys.\n  Proof.\n    induction xs as [|x xs IH]. reflexivity.\n    destruct x; simpl; auto.\n    destruct o; simpl; auto.\n    now setoid_rewrite IH.\n  Qed.\n\n  Instance wc_exp_Proper:\n    Proper (@eq global ==> @Permutation.Permutation (ident * clock)\n                ==> @eq exp ==> iff)\n           wc_exp.\n  Proof.\n    intros G G' HG env' env Henv e' e He.\n    rewrite HG, He. clear HG He.\n    split; intro H;\n      induction H using wc_exp_ind2;\n      (rewrite Henv in * || rewrite <-Henv in * || idtac);\n      eauto with lclocking.\n  Qed.\n\n  Instance wc_exp_pointwise_Proper:\n    Proper (@eq global ==> @Permutation.Permutation (ident * clock)\n                ==> pointwise_relation _ iff)\n           wc_exp.\n  Proof.\n    intros G G' HG env' env Henv e.\n    now rewrite Henv, HG.\n  Qed.\n\n  Instance wc_equation_Proper:\n    Proper (@eq global ==> @Permutation.Permutation (ident * clock)\n                ==> @eq equation ==> iff)\n           wc_equation.\n  Proof with auto.\n    intros G1 G2 HG env1 env2 Henv eq1 eq2 Heq; subst.\n    destruct eq2 as (xs & es). unfold wc_equation. rewrite Henv.\n    split; intros (HA & HB & HC);\n      repeat split...\n    - setoid_rewrite <- Henv...\n    - setoid_rewrite Henv...\n  Qed.\n\n  Instance wc_equation_pointwise_Proper:\n    Proper (@eq global ==> @Permutation.Permutation (ident * clock)\n                ==> pointwise_relation _ iff)\n           wc_equation.\n  Proof.\n    intros G1 G2 HG env1 env2 Henv eq; subst. now rewrite Henv.\n  Qed.\n\n  Lemma wc_env_Is_free_in_clock_In : forall vars x id ck,\n      wc_env vars ->\n      In (x, ck) vars ->\n      Is_free_in_clock id ck ->\n      InMembers id vars.\n  Proof.\n    intros * Hwenv Hin Hfree.\n    unfold wc_env in Hwenv.\n    eapply Forall_forall in Hin; eauto; simpl in Hin.\n    induction Hfree; inv Hin; eauto using In_InMembers.\n  Qed.\n\n  Lemma wc_env_has_Cbase':\n    forall vars x xck,\n      wc_env vars ->\n      In (x, xck) vars ->\n      exists y, In (y, Cbase) vars.\n  Proof.\n    intros vars x xck WC Ix.\n    revert x Ix. induction xck; eauto.\n    intros; eapply Forall_forall in WC; eauto.\n    inv WC; eauto.\n  Qed.\n\n  Lemma wc_env_has_Cbase:\n    forall vars,\n      wc_env vars ->\n      0 < length vars ->\n      exists y, In (y, Cbase) vars.\n  Proof.\n    intros * Hwc Hl. destruct vars. now inv Hl.\n    destruct p. eapply wc_env_has_Cbase'; eauto. now left.\n  Qed.\n\n  Lemma WellInstantiated_parent :\n    forall bck sub cks lck,\n      Forall2 (WellInstantiated bck sub) cks lck ->\n      Forall (fun ck => fst ck = bck \\/ clock_parent bck (fst ck)) lck.\n  Proof.\n    intros. apply Forall_forall. intros * Hin.\n    pose proof (Forall2_in_right _ _ _ _ H Hin) as (?&?&?&?).\n    eauto using instck_parent.\n  Qed.\n\n  Lemma WellInstantiated_bck :\n    forall vars bck sub lck,\n      wc_env vars ->\n      0 < length vars ->\n      Forall2 (WellInstantiated bck sub) vars lck ->\n      In bck (map stripname lck).\n  Proof.\n    intros * Henv Hlen Wi.\n    apply wc_env_has_Cbase in Henv as [x Hin]; auto.\n    pose proof (Forall2_in_left _ _ _ _ Wi Hin) as (nc &?&?& He).\n    simpl in *. apply in_map_iff. exists nc. destruct nc. simpl in *.\n    now inv He.\n  Qed.\n\n  (** Adding variables to the environment preserves clocking *)\n\n  Section incl.\n\n    Fact wc_clock_incl : forall vars vars' cl,\n      incl vars vars' ->\n      wc_clock vars cl ->\n      wc_clock vars' cl.\n    Proof.\n      intros vars vars' cl Hincl Hwc.\n      induction Hwc; auto.\n    Qed.\n\n    Hint Constructors wc_exp.\n    Fact wc_exp_incl : forall G vars vars' e,\n        incl vars vars' ->\n        wc_exp G vars e ->\n        wc_exp G vars' e .\n    Proof with eauto.\n      induction e using exp_ind2; intros Hincl Hwc; inv Hwc; eauto;\n        econstructor; rewrite Forall_forall in *; eauto.\n    Qed.\n\n    Fact wc_equation_incl : forall G vars vars' eq,\n        incl vars vars' ->\n        wc_equation G vars eq ->\n        wc_equation G vars' eq.\n    Proof with eauto.\n      intros G vars vars' [xs es] Hincl Hwc.\n      destruct Hwc as [? [? ?]].\n      repeat split...\n      - rewrite Forall_forall in *; intros.\n        eapply wc_exp_incl...\n      - clear H H0.\n        eapply Forall2_impl_In; [| eauto].\n        intros a b Hin1 Hin2 Hin; simpl in Hin. eapply Hincl...\n    Qed.\n  End incl.\n\n  (** The global can also be extended ! *)\n\n  Section global_incl.\n    Fact wc_exp_global_incl : forall G G' vars e,\n      incl G G' ->\n      NoDup (map n_name G) ->\n      NoDup (map n_name G') ->\n      wc_exp G vars e ->\n      wc_exp G' vars e.\n    Proof.\n      intros * Hincl Hndup1 Hndup2 Hwc.\n      induction Hwc using wc_exp_ind2; eauto using wc_exp, find_node_incl.\n    Qed.\n\n    Fact wc_equation_global_incl : forall G G' vars e,\n      incl G G' ->\n      NoDup (map n_name G) ->\n      NoDup (map n_name G') ->\n      wc_equation G vars e ->\n      wc_equation G' vars e.\n    Proof.\n      intros G G' vars [xs es] Hincl Hndup1 Hndup2 [Hwc1 Hwc2].\n      constructor; auto.\n      eapply Forall_impl; [|eauto]. intros; eauto using wc_exp_global_incl.\n    Qed.\n\n    Fact wc_node_global_incl : forall G G' e,\n      incl G G' ->\n      NoDup (map n_name G) ->\n      NoDup (map n_name G') ->\n      wc_node G e ->\n      wc_node G' e.\n    Proof.\n      intros * Hincl Hndup1 Hndup2 (?&?&?&?).\n      repeat constructor; auto.\n      eapply Forall_impl; [|eauto]. intros; eauto using wc_equation_global_incl.\n    Qed.\n\n    (** Now that we know this, we can deduce a weaker version of wc_global using Forall: *)\n    Lemma wc_global_Forall : forall G,\n        wc_global G ->\n        Forall (wc_node G) G.\n    Proof.\n      intros G Hwc.\n      specialize (wc_global_NoDup _ Hwc) as Hndup.\n      induction Hwc; constructor.\n      - eapply wc_node_global_incl in H; eauto.\n        apply incl_tl, incl_refl.\n        inv Hndup; auto.\n      - inv Hndup. specialize (IHHwc H4).\n        eapply Forall_impl; [|eauto]. intros.\n        eapply wc_node_global_incl in H1; eauto.\n        apply incl_tl, incl_refl.\n        constructor; auto.\n    Qed.\n  End global_incl.\n\n  (** ** Validation *)\n\n  Hint Extern 2 (In _ (idck _)) => apply In_idck_exists.\n\n  Section ValidateExpression.\n\n    Variable G : global.\n    Variable venv : Env.t clock.\n\n    Open Scope option_monad_scope.\n\n    Definition check_var (x : ident) (ck : clock) : bool :=\n      match Env.find x venv with\n      | None => false\n      | Some xc => ck ==b xc\n      end.\n\n    Definition check_paired_clocks (nc1 nc2 : nclock) (tc : ann) : bool :=\n      match tc with\n      | (t, (c, None)) => (fst nc1 ==b c) && (fst nc2 ==b c)\n      | _ => false\n      end.\n\n    Definition check_merge_clocks {A} (x : ident) (ck : clock) (nc1 nc2 : nclock) (ty : A) : bool :=\n      match nc1, nc2 with\n      | (Con ck1 x1 true, _), (Con ck2 x2 false, _) =>\n        (ck1 ==b ck) && (ck2 ==b ck) && (x1 ==b x) && (x2 ==b x)\n      | _, _ => false\n      end.\n\n    Definition check_ite_clocks {A} (ck : clock) (nc1 nc2 : nclock) (ty : A) : bool :=\n      (fst nc1 ==b ck) && (fst nc2 ==b ck).\n\n    Definition add_isub\n               (sub : Env.t ident)\n               (nin : (ident * (type * clock)))\n               (nc : nclock) : Env.t ident :=\n      match snd nc, nin with\n      | Some y, (x, (xt, xc)) => Env.add x y sub\n      | None, _ => sub\n      end.\n\n    Definition add_osub\n               (sub : Env.t ident)\n               (nin : (ident * (type * clock)))\n               (tnc : type * nclock) : Env.t ident :=\n      add_isub sub nin (snd tnc).\n\n    Section CheckInst.\n      Variables (bck : clock) (sub : Env.t ident).\n\n      Fixpoint check_inst (ick ck : clock) : bool :=\n        match ick with\n        | Cbase => (ck ==b bck)\n        | Con ick' x xb =>\n          match ck, Env.find x sub with\n          | Con ck' y yb, Some sx =>\n            (yb ==b xb) && (y ==b sx) && (check_inst ick' ck')\n          | _, _ => false\n          end\n        end.\n    End CheckInst.\n\n    Fixpoint find_base_clock (ick ck : clock) : option clock :=\n      match ick with\n      | Cbase => Some ck\n      | Con ick' _ _ =>\n        match ck with\n        | Cbase => None\n        | Con ck' _ _ => find_base_clock ick' ck'\n        end\n      end.\n\n    Definition check_reset (rt : option (option (list nclock))) : bool :=\n      match rt with\n      | None => true\n      | Some (Some [nckr]) => true\n      | _ => false\n      end.\n\n    Lemma nclockof_clockof:\n      forall e xs ys,\n        nclockof e = xs ->\n        ys = map fst xs ->\n        clockof e = ys.\n    Proof.\n      intros e xs ys NC Hys; subst.\n      now rewrite clockof_nclockof.\n    Qed.\n\n    Fixpoint check_exp (e : exp) : option (list nclock) :=\n      match e with\n      | Econst c => Some ([(Cbase, None)])\n\n      | Evar x (xt, nc) =>\n        match nc with\n        | (xc, Some n) => if (check_var x xc) && (x ==b n) then Some [nc] else None\n        | (xc, None) => if (check_var x xc) then Some [nc] else None\n        end\n\n      | Eunop op e (xt, nc) =>\n        match nc with\n        | (xc, None) =>\n          do nce <- assert_singleton (check_exp e);\n          if xc ==b fst nce then Some [nc] else None\n        | _ => None\n        end\n\n      | Ebinop op e1 e2 (xt, nc) =>\n        match nc with\n        | (xc, None) =>\n          do nc1 <- assert_singleton (check_exp e1);\n          do nc2 <- assert_singleton (check_exp e2);\n          if (xc ==b fst nc1) && (xc ==b fst nc2) then Some [nc] else None\n        | _ => None\n        end\n\n      | Efby e0s es anns =>\n        do nc0s <- oconcat (map check_exp e0s);\n        do ncs <- oconcat (map check_exp es);\n        if forall3b check_paired_clocks nc0s ncs anns\n        then Some (map snd anns) else None\n\n      | Earrow e0s es anns =>\n        do nc0s <- oconcat (map check_exp e0s);\n        do ncs <- oconcat (map check_exp es);\n        if forall3b check_paired_clocks nc0s ncs anns\n        then Some (map snd anns) else None\n\n      | Ewhen es x b (tys, nc) =>\n        match nc with\n        | (Con xc y yb, None) =>\n          do nces <- oconcat (map check_exp es);\n          if (x ==b y) && (b ==b yb) && (check_var x xc)\n             && (forall2b (fun '(c, _) _ => equiv_decb xc c) nces tys)\n          then Some (map (fun _ => nc) tys) else None\n        | _ => None\n        end\n\n      | Emerge x e1s e2s (tys, (ck, None)) =>\n        do nc1s <- oconcat (map check_exp e1s);\n        do nc2s <- oconcat (map check_exp e2s);\n        let nc' := (ck, None) in\n        if check_var x ck && (forall3b (check_merge_clocks x ck) nc1s nc2s tys)\n        then Some (map (fun _ => nc') tys) else None\n\n      | Eite e e1s e2s (tys, (ck, None)) =>\n        do nc1s <- oconcat (map check_exp e1s);\n        do nc2s <- oconcat (map check_exp e2s);\n        do (ce, _) <- assert_singleton (check_exp e);\n        let nc' := (ck, None) in\n        if (ce ==b ck) && (forall3b (check_ite_clocks ck) nc1s nc2s tys)\n                       && (length tys <>b 0)\n        then Some (map (fun _ => nc') tys) else None\n\n      | Eapp f es ro anns =>\n        do n <- find_node f G;\n        do nces <- oconcat (map check_exp es);\n        do nin0 <- option_map (fun '(_, (_, ck)) => ck) (hd_error n.(n_in));\n        do nces0 <- option_map fst (hd_error nces);\n        do bck <- find_base_clock nin0 nces0;\n        let isub := fold_left2 add_isub n.(n_in) nces (Env.empty ident) in\n        let sub := fold_left2 add_osub n.(n_out) anns isub in\n        if (forall2b (fun '(_, (_, ck)) '(ck', _) => check_inst bck sub ck ck')\n                     n.(n_in) nces)\n           && (forall2b (fun '(_, (_, ck)) '(_, (ck', _)) => check_inst bck sub ck ck')\n                        n.(n_out) anns)\n           && (check_reset (option_map check_exp ro))\n        then Some (map snd anns) else None\n\n      | _ => None end.\n\n    Definition check_nclock (x : ident) (nck : nclock) : bool :=\n      let '(ck, nm) := nck in\n      check_var x ck && (match nm with\n                         | None => true\n                         | Some n => n ==b x\n                         end).\n\n    Definition check_equation (eq : equation) : bool :=\n      let '(xs, es) := eq in\n      match oconcat (map check_exp es) with\n      | None => false\n      | Some ncks => forall2b check_nclock xs ncks\n      end.\n\n    Lemma check_var_correct:\n      forall x ck,\n        check_var x ck = true <-> In (x, ck) (Env.elements venv).\n    Proof.\n      unfold check_var. split; intros HH.\n      - cases_eqn Heq; simpl.\n        rewrite equiv_decb_equiv in HH. inv HH.\n        take (Env.find _ _ = Some _) and apply Env.elements_correct in it; eauto.\n      - apply Env.elements_complete in HH as ->.\n        apply equiv_decb_refl.\n    Qed.\n\n    Lemma check_paired_clocks_correct:\n      forall cks1 cks2 anns,\n        forall3b check_paired_clocks cks1 cks2 anns = true ->\n        map stripname cks1 = map clock_of_nclock anns\n        /\\ map stripname cks2 = map clock_of_nclock anns\n        /\\ Forall unnamed_stream anns.\n    Proof.\n      unfold unnamed_stream.\n      setoid_rewrite forall3b_Forall3.\n      induction 1 as [|(ck1, n1) (ck2, n2) (ty, (ck, n)) cks1 cks2 anns\n                                 IH1 IH2 (Hcks1 & Hcks2 & Hanns)];\n        subst; simpl in *; eauto.\n      destruct n; try discriminate.\n      rewrite Bool.andb_true_iff in IH1.\n      setoid_rewrite equiv_decb_equiv in IH1.\n      destruct IH1 as (Hck1 & Hck2). inv Hck1; inv Hck2.\n      rewrite Hcks1, Hcks2; auto.\n    Qed.\n\n    Lemma check_merge_clocks_correct:\n      forall {A} x ck nc1 nc2 (ty : A),\n        check_merge_clocks x ck nc1 nc2 ty = true ->\n        stripname nc1 = Con ck x true\n        /\\ stripname nc2 = Con ck x false.\n    Proof.\n      intros A x ck (ck1, n1) (ck2, n2) ty CM; simpl in CM.\n      cases_eqn Heq; subst.\n      repeat rewrite Bool.andb_true_iff in CM.\n      repeat take (_ /\\ _) and destruct it.\n      now repeat take (_ ==b _ = true) and rewrite equiv_decb_equiv in it; inv it.\n    Qed.\n\n    Lemma check_forall3b_merge_clocks_correct:\n      forall {A} x ck ets efs (tys : list A),\n        forall3b (check_merge_clocks x ck) (nclocksof ets) (nclocksof efs) tys = true ->\n        Forall (eq (Con ck x true)) (clocksof ets)\n        /\\ Forall (eq (Con ck x false)) (clocksof efs)\n        /\\ length (clocksof ets) = length tys\n        /\\ length (clocksof efs) = length tys.\n    Proof.\n      setoid_rewrite forall3b_Forall3.\n      intros * FA3. pose proof (Forall3_length _ _ _ _ FA3) as (L1 & L2).\n      setoid_rewrite clocksof_nclocksof; setoid_rewrite Forall_map.\n      setoid_rewrite map_length. rewrite L2, L1, L2.\n      repeat split; auto.\n      - apply Forall3_ignore23 in FA3.\n        apply Forall_impl_In with (2:=FA3).\n        intros nc Inc (y & z & CE).\n        now apply check_merge_clocks_correct in CE as (? & ?).\n      - apply Forall3_ignore13 in FA3.\n        apply Forall_impl_In with (2:=FA3).\n        intros nc Inc (y & z & CE).\n        now apply check_merge_clocks_correct in CE as (? & ?).\n    Qed.\n\n    Lemma check_ite_clocks_correct:\n      forall {A} ck nc1 nc2 (ty : A),\n        check_ite_clocks ck nc1 nc2 ty = true ->\n        stripname nc1 = ck\n        /\\ stripname nc2 = ck.\n    Proof.\n      intros A ck (ck1, n1) (ck2, n2) ty CM.\n      unfold check_ite_clocks in CM.\n      rewrite Bool.andb_true_iff in CM.\n      take (_ /\\ _) and destruct it.\n      now repeat take (_ ==b _ = true) and rewrite equiv_decb_equiv in it; inv it.\n    Qed.\n\n    Lemma check_forall3b_ite_clocks_correct:\n      forall {A} ck ncs1 ncs2 (tys : list A),\n        forall3b (check_ite_clocks ck) (nclocksof ncs1) (nclocksof ncs2) tys = true ->\n        length (clocksof ncs1) = length tys\n        /\\ length (clocksof ncs2) = length tys\n        /\\ Forall (eq ck) (clocksof ncs1)\n        /\\ Forall (eq ck) (clocksof ncs2).\n    Proof.\n      setoid_rewrite forall3b_Forall3.\n      intros * FA3. pose proof (Forall3_length _ _ _ _ FA3) as (L1 & L2).\n      setoid_rewrite clocksof_nclocksof; setoid_rewrite Forall_map.\n      setoid_rewrite map_length. rewrite L2, L1, L2.\n      repeat split; auto.\n      - apply Forall3_ignore23 in FA3.\n        apply Forall_impl_In with (2:=FA3).\n        intros nc Inc (y & z & CE).\n        now apply check_ite_clocks_correct in CE as (? & ?).\n      - apply Forall3_ignore13 in FA3.\n        apply Forall_impl_In with (2:=FA3).\n        intros nc Inc (y & z & CE).\n        now apply check_ite_clocks_correct in CE as (? & ?).\n    Qed.\n\n    Lemma oconcat_map_check_exp':\n      forall {f} es cks,\n        (forall e cks,\n            In e es ->\n            f e = Some cks ->\n            wc_exp G (Env.elements venv) e /\\ nclockof e = cks) ->\n        oconcat (map f es) = Some cks ->\n        Forall (wc_exp G (Env.elements venv)) es\n        /\\ nclocksof es = cks.\n    Proof.\n      induction es as [|e es IH]; intros cks WTf CE. now inv CE; auto.\n      simpl in CE. destruct (f e) eqn:Ce; [|now omonadInv CE].\n      destruct (oconcat (map f es)) as [ces|]; [|now omonadInv CE].\n      omonadInv CE. simpl.\n      apply WTf in Ce as (Ce1 & ->); auto with datatypes.\n      destruct (IH ces) as (? & ->); auto.\n      intros * Ies Fe. apply WTf in Fe; auto with datatypes.\n    Qed.\n\n    Lemma find_add_isub:\n      forall sub x tc ck nm,\n        ~Env.In x sub ->\n        Env.find x (add_isub sub (x, tc) (ck, nm)) = nm.\n    Proof.\n      unfold add_isub; simpl. intros sub x (ty, ck) ? nm NI.\n      destruct nm. now rewrite Env.gss.\n      now apply Env.Props.P.F.not_find_in_iff in NI.\n    Qed.\n\n    Lemma fold_left2_add_osub_skip:\n      forall x xs anns sub,\n        ~In x (map fst xs) ->\n        Env.find x (fold_left2 add_osub xs anns sub) = Env.find x sub.\n    Proof.\n      induction xs as [|(y, (yt, yc)) xs IH]; auto.\n      simpl; intros anns sub NIx.\n      apply Decidable.not_or in NIx as (Nx & NIx).\n      destruct anns as [|(ty, (ck, n)) anns]; auto.\n      rewrite (IH _ _ NIx).\n      unfold add_osub, add_isub; simpl.\n      destruct n; auto.\n      rewrite Env.gso; auto.\n    Qed.\n\n    Lemma fold_left2_add_isub_skip:\n      forall x xs ncs sub,\n        ~In x (map fst xs) ->\n        Env.find x (fold_left2 add_isub xs ncs sub) = Env.find x sub.\n    Proof.\n      induction xs as [|(y, (yt, yc)) xs IH]; auto.\n      simpl; intros ncs sub NIx.\n      apply Decidable.not_or in NIx as (Nx & NIx).\n      destruct ncs as [|(ck, n) anns]; auto.\n      rewrite (IH _ _ NIx).\n      unfold add_isub; simpl.\n      destruct n; auto.\n      rewrite Env.gso; auto.\n    Qed.\n\n    Lemma fold_left2_add_isub:\n      forall x xt xc ck nm xs ncs sub,\n        In ((x, (xt, xc)), (ck, nm)) (combine xs ncs) ->\n        NoDupMembers xs ->\n        ~Env.In x sub ->\n        Env.find x (fold_left2 add_isub xs ncs sub) = nm.\n    Proof.\n      induction xs as [|(y, (yt, yc)) xs IH]. now inversion 1.\n      intros ncs sub Ix ND NI.\n      destruct ncs as [|(ck', nm') ncs]. now inversion Ix.\n      simpl in *.\n      destruct Ix as [Ix|Ix].\n      - inv Ix. inv ND. rewrite fold_left2_add_isub_skip.\n        now apply find_add_isub.\n        rewrite in_map_iff.\n        intros ((y, (yt, yc)) & Fy & Iy). simpl in *; subst.\n        take (~InMembers _ _) and apply it.\n        apply In_InMembers with (1:=Iy).\n      - inv ND. eapply IH in Ix; eauto.\n        apply in_combine_l, In_InMembers in Ix.\n        take (~InMembers _ xs) and apply InMembers_neq with (2:=it) in Ix.\n        unfold add_isub; simpl. destruct nm'; auto.\n        setoid_rewrite Env.Props.P.F.add_in_iff.\n        apply not_or'; auto.\n    Qed.\n\n    Lemma fold_left2_add_osub:\n      forall x xt xc ty ck nm xs ans sub,\n        In ((x, (xt, xc)), (ty, (ck, nm))) (combine xs ans) ->\n        NoDupMembers xs ->\n        ~Env.In x sub ->\n        Env.find x (fold_left2 add_osub xs ans sub) = nm.\n    Proof.\n      induction xs as [|(y, (yt, yc)) xs IH]. now inversion 1.\n      intros ncs sub Ix ND NI.\n      destruct ncs as [|(ck', nm') ncs]. now inversion Ix.\n      simpl in *.\n      destruct Ix as [Ix|Ix].\n      - inv Ix. inv ND. rewrite fold_left2_add_osub_skip.\n        now apply find_add_isub.\n        rewrite in_map_iff.\n        intros ((y, (yt, yc)) & Fy & Iy). simpl in *; subst.\n        take (~InMembers _ _) and apply it.\n        apply In_InMembers with (1:=Iy).\n      - inv ND. eapply IH in Ix; eauto.\n        apply in_combine_l, In_InMembers in Ix.\n        take (~InMembers _ xs) and apply InMembers_neq with (2:=it) in Ix.\n        unfold add_osub, add_isub; simpl. destruct nm'; auto. simpl.\n        destruct o; auto.\n        setoid_rewrite Env.Props.P.F.add_in_iff.\n        apply not_or'; auto.\n    Qed.\n\n    Lemma check_inst_correct:\n      forall bck xc ck sub,\n        check_inst bck sub xc ck = true ->\n        instck bck (fun x => Env.find x sub) xc = Some ck.\n    Proof.\n      induction xc as [|xc' ? x b]; simpl.\n      now setoid_rewrite equiv_decb_equiv; inversion 2.\n      destruct ck. now inversion 1.\n      intros sub Fx. cases_eqn Heq.\n      1,2:repeat take (_ && _ = true) and apply andb_prop in it as (? & ?).\n      1,2:repeat take ((_ ==b _) = true) and rewrite equiv_decb_equiv in it; inv it.\n      1,2:erewrite IHxc in Heq0; [|eauto]; inv Heq0; auto.\n    Qed.\n\n    Lemma check_exp_correct:\n      forall e ncks,\n        check_exp e = Some ncks ->\n        wc_exp G (Env.elements venv) e\n        /\\ nclockof e = ncks.\n    Proof.\n      induction e using exp_ind2; simpl; intros ncks CE;\n      repeat progress\n               match goal with\n               | H:None = Some _ |- _ => discriminate\n               | H:Some _ = Some _ |- _ => inv H\n               | a:ann |- _ => destruct a\n               | a:lann |- _ => destruct a\n               | nc:nclock |- _ => destruct nc\n               | H:obind _ _ = Some _ |- _ => omonadInv H\n               | H: _ && _ = true |- _ => apply Bool.andb_true_iff in H as (? & ?)\n               | H: ((_ ==b _) = true) |- _ => rewrite equiv_decb_equiv in H; inv H\n               | H:(if ?c then Some _ else None) = Some _ |- _ =>\n                 let C := fresh \"C0\" in\n                 destruct c eqn:C\n               | H:check_var _ _ = true |- _ => apply check_var_correct in H\n               | H:assert_singleton _ = Some _ |- _ => apply assert_singleton_spec in H\n               | H:obind ?v _ = Some _ |- _ =>\n                 let OE:=fresh \"OE0\" in destruct v eqn:OE; [simpl in H|now omonadInv H]\n               | H:(match ?o with Some _ => _ | None => None end) = Some _ |- _ =>\n                 destruct o\n               | H:(match ?o with Some _ => None | None => _ end) = Some _ |- _ =>\n                 destruct o\n               | H:(match ?o with Some _ => if _ then _ else _ | None => _ end) = Some _ |- _ =>\n                 destruct o\n               | H:(match ?c with Cbase => None | _ => _ end) = Some _ |- _ =>\n                 destruct c\n               | H:forall3b check_paired_clocks ?cks1 ?cks2 ?anns = true |- _ =>\n                 apply check_paired_clocks_correct in H as (? & ? & ?)\n               | H:(?xs <>b 0) = true |- _ =>\n                 apply nequiv_decb_true in H;\n                   assert (0 < xs) by (destruct l;\n                     [now exfalso; apply H|apply PeanoNat.Nat.lt_0_succ])\n               | H:obind2 (assert_singleton ?ce) _ = Some _ |- _ =>\n                 destruct (assert_singleton ce) as [(ck, n)|] eqn:AS;\n                   try discriminate; simpl in H\n               end.\n      - (* Econst *)\n        eauto using wc_exp.\n      - (* Evar *)\n        eauto using wc_exp.\n      - (* Evar *)\n        eauto using wc_exp.\n      - (* Eunop *)\n        apply IHe in OE0 as (? & ?).\n        eauto using wc_exp, nclockof_clockof.\n      - (* Ebinop *)\n        apply IHe1 in OE0 as (? & ?); apply IHe2 in OE1 as (? & ?).\n        eauto using wc_exp, nclockof_clockof.\n      - (* Efby *)\n        repeat take (Forall (fun e :exp => _) _) and rewrite Forall_forall in it.\n        apply oconcat_map_check_exp' in OE0 as (? & ?); auto.\n        apply oconcat_map_check_exp' in OE1 as (? & ?); auto. subst.\n        repeat take (map stripname _ = map clock_of_nclock _)\n               and rewrite <-clocksof_nclocksof in it.\n        eauto using wc_exp.\n      - (* Earrow *)\n        repeat take (Forall (fun e :exp => _) _) and rewrite Forall_forall in it.\n        apply oconcat_map_check_exp' in OE0 as (? & ?); auto.\n        apply oconcat_map_check_exp' in OE1 as (? & ?); auto. subst.\n        repeat take (map stripname _ = map clock_of_nclock _)\n               and rewrite <-clocksof_nclocksof in it.\n        eauto using wc_exp.\n      - (* Ewhen *)\n        take (Forall _ es) and rewrite Forall_forall in it.\n        take (oconcat (map check_exp _) = Some _) and\n             apply oconcat_map_check_exp' in it as (? & ?); auto.\n        take (forall2b _ _ _ = true) and rename it into FA2; apply forall2b_Forall2 in FA2.\n        subst; simpl; repeat split; auto. constructor; auto; rewrite clocksof_nclocksof.\n        2:rewrite map_length; pose proof (Forall2_length _ _ _ FA2) as Hlen; auto.\n        apply Forall2_ignore2 in FA2. rewrite Forall_map.\n        apply Forall_impl_In with (2:=FA2). intros (? & ?) ? (? & HH).\n        now rewrite equiv_decb_equiv in HH; inv HH.\n      - (* Emerge *)\n        repeat take (Forall _ _) and rewrite Forall_forall in it.\n        repeat take (oconcat (map check_exp _) = Some _) and\n               apply oconcat_map_check_exp' in it as (? & ?); auto.\n        repeat take (nclocksof _ = _) and rewrite <- it in *; clear it.\n        take (forall3b (check_merge_clocks _ _) _ _ _ = true)\n        and apply check_forall3b_merge_clocks_correct in it as (? & ? & ? & ?).\n        eauto using wc_exp.\n      - (* Eite *)\n        repeat take (Forall _ _) and rewrite Forall_forall in it.\n        repeat take (oconcat (map check_exp _) = Some _) and\n               apply oconcat_map_check_exp' in it as (? & ?); auto.\n        repeat take (nclocksof _ = _) and rewrite <- it in *; clear it.\n        take (forall3b (check_ite_clocks _) _ _ _ = true)\n        and apply check_forall3b_ite_clocks_correct in it as (? & ? & ? & ?).\n        apply IHe in AS as (? & ?); auto.\n        eauto using wc_exp, nclockof_clockof.\n      - (* Eapp *)\n        take (Forall _ _) and rewrite Forall_forall in it.\n        take (oconcat (map check_exp _) = Some _) and\n             apply oconcat_map_check_exp' in it as (? & ?); auto.\n        take (nclocksof _ = _) and rewrite <- it in *; clear it.\n        repeat take (forall2b _ _ _ = true) and apply forall2b_Forall2 in it.\n        split; auto.\n        match goal with H:find_base_clock _ _ = Some ?c |- _ => rename c into bck end.\n\n        assert (Forall2 (WellInstantiated bck\n           (fun x => Env.find x (fold_left2 add_osub n.(n_out) a\n              (fold_left2 add_isub n.(n_in) (nclocksof es) (Env.empty _)))))\n                        (idck n.(n_in)) (nclocksof es)).\n        { apply Forall2_map_1, Forall2_forall.\n          take (Forall2 _ n.(n_in) (nclocksof es)) and rename it into FA2.\n          split; [|now apply Forall2_length with (1:=FA2)].\n          intros (x, (xt, xc)) (ck, nm) Ix.\n          constructor; simpl;\n            [|now apply Forall2_In with (1:=Ix), check_inst_correct in FA2].\n          pose proof (NoDupMembers_app_l _ _ n.(n_nodup)).\n          rewrite fold_left2_add_osub_skip, fold_left2_add_isub with (1:=Ix); auto.\n          now rewrite Env.Props.P.F.empty_in_iff.\n          apply in_combine_l, In_InMembers in Ix.\n          rewrite <-fst_InMembers.\n          apply NoDupMembers_app_InMembers with (2:=Ix).\n          pose proof n.(n_nodup) as ND.\n          rewrite Permutation_swap in ND. apply NoDupMembers_app_r in ND.\n          rewrite app_assoc in ND. apply NoDupMembers_app_l in ND. auto. }\n\n        assert (Forall2 (WellInstantiated bck\n           (fun x => Env.find x (fold_left2 add_osub n.(n_out) a\n             (fold_left2 add_isub n.(n_in) (nclocksof es) (Env.empty ident)))))\n                        (idck n.(n_out)) (map snd a)).\n        { apply Forall2_map_1, Forall2_forall.\n          take (Forall2 _ n.(n_out) _) and rename it into FA2.\n          split; [|now rewrite map_length; apply Forall2_length with (1:=FA2)].\n          intros (x, (xt, xc)) (ck, nm) Ix.\n          rewrite combine_map_snd, in_map_iff in Ix.\n          destruct Ix as (((y & (yt & yc)), (yc' & ynm)) & EE & Ix); inv EE.\n          constructor; simpl.\n          2:now apply Forall2_In with (1:=Ix), check_inst_correct in FA2.\n          pose proof (NoDupMembers_app_l _ _ (NoDupMembers_app_r _ _ (NoDupMembers_app_r _ _ n.(n_nodup)))).\n          rewrite fold_left2_add_osub with (1:=Ix); auto.\n          setoid_rewrite Env.Props.P.F.not_find_in_iff.\n          rewrite fold_left2_add_isub_skip; auto using Env.gempty.\n          rewrite <-fst_InMembers.\n          apply in_combine_l, In_InMembers in Ix.\n          apply NoDupMembers_app_InMembers with (2:=Ix).\n          rewrite Permutation_app_comm.\n          pose proof n.(n_nodup) as ND.\n          rewrite Permutation_swap in ND. apply NoDupMembers_app_r in ND.\n          rewrite app_assoc in ND. apply NoDupMembers_app_l in ND. auto. }\n\n        destruct ro;\n          simpl in *; cases_eqn Heq; subst;\n            try match goal with H:check_exp ?e = Some [?nc] |- _ => destruct nc end;\n            econstructor; eauto;\n            take (forall ncks, Some _ = Some ncks -> _ /\\ _) and rename it into CE;\n            specialize (CE _ eq_refl) as (CE1 & CE2); eauto.\n        now apply nclockof_clockof with (1:=CE2).\n    Qed.\n\n    Lemma oconcat_map_check_exp:\n      forall es ncks,\n        oconcat (map check_exp es) = Some ncks ->\n        Forall (wc_exp G (Env.elements venv)) es\n        /\\ nclocksof es = ncks.\n    Proof.\n      induction es as [|e es IH]; intros ncks CE. now inv CE; eauto.\n      simpl in CE. cases_eqn Heq.\n      take (check_exp _ = Some _) and rename it into CWF.\n      apply check_exp_correct in CWF as (WCe & NCe).\n      destruct (oconcat (map check_exp es)) eqn:CWF; inv CE.\n      specialize (IH _ eq_refl) as (? & ?).\n      split; auto.\n      simpl. take (nclocksof _ = _) and rewrite it. eauto.\n    Qed.\n\n    Lemma check_equation_correct:\n      forall eq,\n        check_equation eq = true ->\n        wc_equation G (Env.elements venv) eq.\n    Proof.\n      intros eq CE. destruct eq as (xs, es); simpl in CE.\n      cases_eqn Heq.\n      take (oconcat (map _ _) = Some _)\n      and apply oconcat_map_check_exp in it as (WC & NC).\n      subst. apply forall2b_Forall2 in CE.\n      constructor; auto.\n      rewrite clocksof_nclocksof, Forall2_map_2.\n      split; apply Forall2_impl_In with (2:=CE); intros x (ck, nm) Ix Inc CNC;\n        simpl in *; cases_eqn Heq;\n        apply Bool.andb_true_iff in CNC as (CNC1 & CNC2);\n        take (check_var _ _ = true) and apply check_var_correct in it;\n        simpl; auto.\n      now rewrite equiv_decb_equiv in CNC2.\n    Qed.\n\n  End ValidateExpression.\n\n  Section ValidateGlobal.\n\n    Fixpoint check_clock xenv (ck : clock) : bool :=\n      match ck with\n      | Cbase => true\n      | Con ck' x b =>\n        check_var xenv x ck' && check_clock xenv ck'\n      end.\n\n    Definition check_env (env : list (ident * clock)) : bool :=\n      forallb (check_clock (Env.from_list env)) (List.map snd env).\n\n    Definition check_node (G : global) (n : node) :=\n      check_env (idck (n_in n)) &&\n      check_env (idck (n_in n ++ n_out n)) &&\n      check_env (idck (n_in n ++ n_out n ++ n_vars n)) &&\n      forallb (check_equation G (Env.from_list (idck (n_in n ++ n_vars n ++ n_out n)))) (n_eqs n).\n\n    Definition check_global (G : global) :=\n      check_nodup (List.map n_name G) &&\n      (fix aux G := match G with\n                    | [] => true\n                    | hd::tl => check_node tl hd && aux tl\n                    end) G.\n\n    Lemma check_clock_correct : forall xenv ck,\n        check_clock xenv ck = true ->\n        wc_clock (Env.elements xenv) ck.\n    Proof.\n      induction ck; intros Hcheck; simpl; auto.\n      apply Bool.andb_true_iff in Hcheck as [Hc1 Hc2].\n      constructor; auto.\n      rewrite check_var_correct in Hc1; auto.\n    Qed.\n\n    Lemma check_env_correct : forall env,\n        check_env env = true ->\n        wc_env env.\n    Proof.\n      intros env Hcheck.\n      unfold wc_env, check_env in *.\n      apply forallb_Forall, Forall_map in Hcheck.\n      eapply Forall_impl; eauto; intros ? Hc; simpl in Hc.\n      apply check_clock_correct in Hc.\n      eapply wc_clock_incl; eauto.\n      apply Env.elements_from_list_incl.\n    Qed.\n\n    Lemma check_node_correct : forall G n,\n        check_node G n = true ->\n        wc_node G n.\n    Proof.\n      intros * Hcheck.\n      unfold check_node in Hcheck.\n      repeat rewrite Bool.andb_true_iff in Hcheck. destruct Hcheck as [[[Hc1 Hc2] Hc3] Hc4].\n      repeat constructor.\n      1-3:apply check_env_correct; auto.\n      apply forallb_Forall in Hc4.\n      eapply Forall_impl; [|eauto]. intros ? Hcheck; simpl in Hcheck.\n      apply check_equation_correct in Hcheck.\n      eapply wc_equation_incl; eauto.\n      apply Env.elements_from_list_incl.\n    Qed.\n\n    Lemma check_global_correct : forall G,\n        check_global G = true ->\n        wc_global G.\n    Proof.\n      intros G Hcheck.\n      apply Bool.andb_true_iff in Hcheck; destruct Hcheck as [Hndup Hcheck].\n      apply check_nodup_correct in Hndup.\n      induction G; constructor; inv Hndup.\n      1-3:simpl in Hcheck; apply Bool.andb_true_iff in Hcheck as [Hc1 Hc2]; auto.\n      - apply check_node_correct in Hc1; auto.\n      - apply Forall_forall. intros ? Hin contra.\n        apply H1. rewrite in_map_iff. exists x; split; auto.\n    Qed.\n\n  End ValidateGlobal.\n\n  (** *** Some additional properties related to remove_member *)\n\n  Definition remove_member {B} := @remove_member _ B EqDec_instance_0.\n\n  (* Its possible to remove ids not present in a clock from the typing environment *)\n  Lemma wc_clock_nfreein_remove : forall vars id ck,\n      ~Is_free_in_clock id ck ->\n      wc_clock vars ck ->\n      wc_clock (remove_member id vars) ck.\n  Proof.\n    intros vars id ck Hnfree Hwc.\n    induction Hwc; constructor.\n    - apply IHHwc.\n      intro Hfree'. apply Hnfree; constructor; auto.\n    - clear IHHwc Hwc.\n      eapply remove_member_neq_In; eauto.\n      intro contra; subst. apply Hnfree. constructor.\n  Qed.\n\n  Lemma wc_env_nfreein_remove : forall id vars,\n      NoDupMembers vars ->\n      wc_env vars ->\n      Forall (fun '(_, ck) => ~Is_free_in_clock id ck) vars ->\n      wc_env (remove_member id vars).\n  Proof.\n    intros id vars Hndup Hwc Hfree.\n    unfold wc_env in Hwc.\n    eapply Forall_Forall in Hwc; eauto.\n    eapply Forall_incl. 2:eapply remove_member_incl.\n    eapply Forall_impl; eauto.\n    intros [id' ck'] H; simpl in H; destruct H as [H1 H2].\n    eapply wc_clock_nfreein_remove in H1; simpl; eauto.\n  Qed.\n\n  Lemma wc_clock_nfreein_remove' : forall vars id ck ck',\n      ~Is_free_in_clock id ck' ->\n      wc_clock ((id, ck)::vars) ck' ->\n      wc_clock vars ck'.\n  Proof.\n    intros vars id ck ck' Hnfree Hwc.\n    induction Hwc; constructor.\n    - apply IHHwc.\n      intro Hfree'. apply Hnfree; constructor; auto.\n    - clear IHHwc Hwc.\n      inv H; auto.\n      exfalso. inv H0.\n      apply Hnfree. constructor.\n  Qed.\n\n  Fact clock_parent_In : forall vars ck ck' id b,\n      wc_clock vars ck ->\n      clock_parent (Con ck' id b) ck ->\n      In (id, ck') vars.\n  Proof.\n    induction ck; intros * Hwc Hparent; inv Hwc; inv Hparent; eauto.\n    inv H1; eauto.\n  Qed.\n\n  (** The clock of a var cant depend on its var *)\n  Lemma wc_nfree_in_clock : forall vars ck id,\n      NoDupMembers vars ->\n      In (id, ck) vars ->\n      wc_clock vars ck ->\n      ~Is_free_in_clock id ck.\n  Proof.\n    intros vars ck id Hndup Hin Hwc contra.\n    apply Is_free_in_clock_self_or_parent in contra as [ck' [b [H|H]]]; subst.\n    - inv Hwc.\n      eapply NoDupMembers_det in Hndup. 2:eapply H3. 2:eapply Hin.\n      apply clock_not_in_clock in Hndup; auto.\n    - assert (In (id, ck') vars) as Hin' by (eapply clock_parent_In; eauto).\n      apply clock_parent_parent' in H.\n      apply clock_parent_no_loops in H.\n      eapply NoDupMembers_det in Hndup. 2:eapply Hin. 2:eapply Hin'. congruence.\n  Qed.\n\n  (** *** A clock dependency order *)\n\n  Inductive dep_ordered_clocks : list (ident * clock) -> Prop :=\n  | dep_ord_clock_nil : dep_ordered_clocks nil\n  | dep_ord_clock_cons : forall ck id ncks,\n      dep_ordered_clocks ncks ->\n      ~Exists (Is_free_in_clock id) (map snd ncks) ->\n      dep_ordered_clocks ((id, ck)::ncks).\n\n  Program Fixpoint wc_env_dep_ordered (vars : list (ident * clock)) {measure (length vars)} :\n      NoDupMembers vars ->\n      wc_env vars ->\n      exists vars', Permutation vars vars' /\\ dep_ordered_clocks vars' := _.\n  Next Obligation.\n    rename H into Hndup. rename H0 into Hwc.\n    specialize (exists_child_clock' vars Hndup Hwc) as [?|[id [ck [Hin Hfree]]]]; subst; simpl.\n    - exists []. split; auto. constructor.\n    - remember (remove_member id vars) as vars'.\n      assert (NoDupMembers vars') as Hndup'.\n      { subst. apply remove_member_NoDupMembers; eauto. }\n      assert (wc_env vars') as Hwc'.\n      { subst. eapply wc_env_nfreein_remove; eauto. }\n      assert (length vars' < length vars) as Hlen.\n      { rewrite Heqvars'.\n        specialize (remove_member_Perm EqDec_instance_0 _ _ _ Hndup Hin) as Hperm. symmetry in Hperm.\n        apply Permutation_length in Hperm. rewrite Hperm; simpl. apply PeanoNat.Nat.lt_succ_diag_r. }\n      specialize (wc_env_dep_ordered _ Hlen Hndup' Hwc') as [vars'' [Hperm Hdep]].\n      exists ((id, ck)::vars''). split; auto.\n      + rewrite <- Hperm, Heqvars'.\n        setoid_rewrite remove_member_Perm; eauto.\n      + simpl. constructor; simpl; eauto.\n        rewrite <- Forall_Exists_neg, Forall_map, <- Hperm, Heqvars'.\n        eapply Forall_incl. 2:eapply remove_member_incl.\n        eapply Forall_impl; eauto.\n        intros [id' ck'] H; auto.\n  Qed.\n\n  Fact wc_clock_dep_ordered_remove : forall id ck x xs,\n      NoDupMembers (x::xs) ->\n      In (id, ck) xs ->\n      dep_ordered_clocks (x::xs) ->\n      wc_clock (x::xs) ck ->\n      wc_clock xs ck.\n  Proof.\n    intros id ck [id' ck'] xs Hndup Hin Hdep Hwc.\n    eapply wc_clock_nfreein_remove with (id:=id') in Hwc.\n    - simpl in Hwc.\n      destruct EqDec_instance_0 in Hwc; try congruence.\n      inv Hndup.\n      unfold remove_member in Hwc. rewrite remove_member_nIn_idem in Hwc; auto.\n    - inv Hdep. rewrite <- Forall_Exists_neg, Forall_forall in H3.\n      eapply H3. rewrite in_map_iff. exists (id, ck); auto.\n  Qed.\n\n  Corollary wc_env_dep_ordered_remove : forall x xs,\n      NoDupMembers (x::xs) ->\n      dep_ordered_clocks (x::xs) ->\n      wc_env (x::xs) ->\n      wc_env xs.\n  Proof with eauto.\n    intros [id' ck'] xs Hndup Hdep Hwc.\n    unfold wc_env in *. inv Hwc.\n    eapply Forall_impl_In; [| eauto]. intros [id ck] Hin Hwc.\n    eapply wc_clock_dep_ordered_remove in Hwc...\n  Qed.\n\n  (** *** Another equivalent clock dependency order *)\n\n  Definition only_depends_on (vars : list ident) (ck : clock) :=\n    forall id, Is_free_in_clock id ck -> In id vars.\n\n  Lemma only_depends_on_Con : forall vars ck id b,\n      only_depends_on vars (Con ck id b) ->\n      only_depends_on vars ck.\n  Proof.\n    intros vars ck id b Hon id' Hisfree.\n    apply Hon. constructor; auto.\n  Qed.\n\n  Lemma only_depends_on_incl : forall vars vars' ck,\n      incl vars vars' ->\n      only_depends_on vars ck ->\n      only_depends_on vars' ck.\n  Proof.\n    intros vars vars' ck Hincl Honly id Hfree. eauto.\n  Qed.\n\n  Lemma wc_clock_only_depends_on : forall vars ck,\n      wc_clock vars ck ->\n      only_depends_on (map fst vars) ck.\n  Proof.\n    intros vars ck Hwc id Hisfree; induction Hwc; inv Hisfree; eauto.\n    rewrite in_map_iff. exists (x, ck); auto.\n  Qed.\n\n  Inductive dep_ordered_on : list (ident * clock) -> Prop :=\n  | dep_ordered_nil : dep_ordered_on []\n  | dep_ordered_cons : forall nck ncks,\n      dep_ordered_on ncks ->\n      only_depends_on (map fst ncks) (snd nck) ->\n      dep_ordered_on (nck::ncks).\n\n  Lemma dep_ordered_on_InMembers : forall ncks,\n      dep_ordered_on ncks ->\n      Forall (fun ck => forall id, Is_free_in_clock id ck -> InMembers id ncks) (map snd ncks).\n  Proof.\n    intros ncks Hdep. induction Hdep; simpl; constructor.\n    - intros id Hfree.\n      destruct nck as [id' ck']; simpl in *.\n      apply H in Hfree.\n      right. rewrite fst_InMembers; auto.\n    - rewrite Forall_map in *.\n      eapply Forall_impl; eauto.\n      intros [id ck] Hin id' Hisfree; simpl in *.\n      destruct nck as [id'' ck''].\n      apply Hin in Hisfree; auto.\n  Qed.\n\n  Lemma dep_ordered_dep_ordered_on : forall ncks,\n      NoDupMembers ncks ->\n      wc_env ncks ->\n      dep_ordered_clocks ncks ->\n      dep_ordered_on ncks.\n  Proof with eauto.\n    induction ncks; intros Hndup Hwc Hdep; [constructor|].\n    inv Hndup. inv Hdep. constructor; simpl.\n    - eapply IHncks...\n      eapply wc_env_dep_ordered_remove with (x:=(a0, b)) in Hwc...\n      1,2:constructor...\n    - inv Hwc; simpl in *.\n      eapply wc_clock_only_depends_on, wc_clock_no_loops_remove...\n  Qed.\n\n  Lemma dep_ordered_on_dep_ordered : forall ncks,\n      NoDupMembers ncks ->\n      wc_env ncks ->\n      dep_ordered_on ncks ->\n      dep_ordered_clocks ncks.\n  Proof with eauto.\n    induction ncks as [|[id ck]]; intros Hndup Hwc Hdep; [constructor|].\n    assert (Hndup':=Hndup). inv Hndup'; inv Hdep. simpl in *; constructor.\n    - apply IHncks...\n      eapply wc_env_nfreein_remove with (id:=id) in Hwc.\n      + simpl in *. destruct EqDec_instance_0 in Hwc; try congruence.\n        unfold remove_member in Hwc. rewrite remove_member_nIn_idem in Hwc...\n      + constructor...\n      + constructor.\n        * eapply wc_nfree_in_clock in Hndup... 1:constructor...\n           inv Hwc...\n        * apply dep_ordered_on_InMembers in H2.\n          rewrite Forall_map in H2.\n          eapply Forall_impl; eauto. intros [? ?] ? contra.\n          apply H in contra. congruence.\n    - apply dep_ordered_on_InMembers in H2.\n      rewrite <- Forall_Exists_neg.\n      eapply Forall_impl; eauto.\n      intros a H; simpl in H.\n      intro contra. apply H in contra. congruence.\n  Qed.\n\n  Corollary dep_ordered_iff : forall vars,\n      NoDupMembers vars ->\n      wc_env vars ->\n      (dep_ordered_clocks vars <-> dep_ordered_on vars).\n  Proof with eauto.\n    intros. split.\n    - eapply dep_ordered_dep_ordered_on...\n    - eapply dep_ordered_on_dep_ordered...\n  Qed.\n\n  Corollary wc_env_dep_ordered_on_remove : forall x xs,\n      NoDupMembers (x::xs) ->\n      dep_ordered_on (x::xs) ->\n      wc_env (x::xs) ->\n      wc_env xs.\n  Proof with eauto.\n    intros x xs Hndup Hdep Hwenv.\n    apply dep_ordered_on_dep_ordered in Hdep...\n    eapply wc_env_dep_ordered_remove...\n  Qed.\n\n  Corollary wc_env_dep_ordered_on : forall vars,\n      NoDupMembers vars ->\n      wc_env vars ->\n      exists vars', Permutation vars vars' /\\ dep_ordered_on vars'.\n  Proof.\n    intros vars Hndup Hwenv.\n    specialize (wc_env_dep_ordered vars Hndup Hwenv) as [vars' [Hperm Hdep]].\n    exists vars'. split; auto.\n    eapply dep_ordered_dep_ordered_on in Hdep; eauto.\n    - rewrite <- Hperm; auto.\n    - rewrite <- Hperm; auto.\n  Qed.\n\n  Instance only_depends_on_Proper:\n    Proper (@Permutation.Permutation ident ==> @eq clock ==> iff)\n           only_depends_on.\n  Proof.\n    intros vars vars' Hperm ck ck' ?; subst.\n    unfold only_depends_on.\n    split; intros; [rewrite <- Hperm|rewrite Hperm]; eauto.\n  Qed.\n\n  (** *** Additional properties about WellInstantiated *)\n\n  Definition anon_streams (l : list nclock) : list (ident * clock) :=\n    map_filter (fun '(ck, id) => match id with\n                              | None => None\n                              | Some id => Some (id, ck)\n                              end) l.\n\n  Lemma anon_streams_anon_streams : forall (anns : list ann),\n      anon_streams (map snd anns) = idck (Syn.anon_streams anns).\n  Proof.\n    induction anns; simpl; auto.\n    destruct a as [ty [ck [id|]]]; simpl; congruence.\n  Qed.\n\n  Fact WellInstantiated_sub_fsts : forall bck sub ins outs,\n      Forall2 (WellInstantiated bck sub) ins outs ->\n      map_filter sub (map fst ins) = (map fst (anon_streams outs)).\n  Proof.\n    intros bck sub ins outs Hinst.\n    induction Hinst; simpl; auto.\n    destruct H as [Hsub _]; destruct y as [ck id]; simpl in *; subst.\n    destruct sub; simpl; [f_equal|]; auto.\n  Qed.\n\n  Lemma instck_only_depends_on : forall vars bck bckvars sub ck ck',\n      only_depends_on bckvars bck ->\n      only_depends_on vars ck ->\n      instck bck sub ck = Some ck' ->\n      only_depends_on (bckvars++map_filter sub vars) ck'.\n  Proof with eauto.\n    induction ck; intros ck' Hbck Hdep Hinst; simpl in *.\n    - inv Hinst...\n      eapply only_depends_on_incl; eauto. apply incl_appl, incl_refl.\n    - destruct instck eqn:Hinst'; try congruence.\n      destruct sub eqn:Hsub; try congruence.\n      inv Hinst.\n      specialize (only_depends_on_Con _ _ _ _ Hdep) as Hdep'.\n      specialize (IHck _ Hbck Hdep' eq_refl).\n      intros id Hfree. inv Hfree.\n      + specialize (Hdep i (FreeCon1 _ _ _)).\n        apply in_or_app; right.\n        eapply map_filter_In; eauto.\n      + apply IHck...\n  Qed.\n\n  (** *** Relation between nclocksof and fresh_ins *)\n\n  Lemma anon_streams_nclockof_fresh_in : forall G vars e,\n      wc_exp G vars e ->\n      incl (anon_streams (nclockof e)) (vars++idck (fresh_in e)).\n  Proof with eauto.\n    induction e using exp_ind2; intros Hwc;\n      inv Hwc; simpl; try apply incl_nil'.\n    - (* var *)\n      rewrite app_nil_r.\n      intros id Hin; inv Hin... inv H.\n    - (* fby *)\n      replace (anon_streams _) with (@nil (ident * clock)).\n      2: { clear H H0 H4 H5 H6 H7.\n           induction a; simpl; auto. inv H8.\n           rewrite <- IHa... unfold unnamed_stream in H1.\n           destruct a as [ty [ck id]]; simpl in *; subst. reflexivity. }\n      apply incl_nil'.\n    - (* arrow *)\n      replace (anon_streams _) with (@nil (ident * clock)).\n      2: { clear H H0 H4 H5 H6 H7.\n           induction a; simpl; auto. inv H8.\n           rewrite <- IHa... unfold unnamed_stream in H1.\n           destruct a as [ty [ck id]]; simpl in *; subst. reflexivity. }\n      apply incl_nil'.\n    - (* when *)\n      replace (anon_streams _) with (@nil (ident * clock)).\n      2: { clear H H4 H5 H6 H7.\n           induction tys; simpl; auto. }\n      apply incl_nil'.\n    - (* merge *)\n      replace (anon_streams _) with (@nil (ident * clock)).\n      2: { clear H H0 H5 H6 H7 H8 H9 H10 H11.\n           induction tys; simpl; auto. }\n      apply incl_nil'.\n    - (* ite *)\n      replace (anon_streams _) with (@nil (ident * clock)).\n      2: { clear H H0 H5 H6 H7 H8 H9 H10 H11 H12 H13.\n           induction tys; simpl; auto. }\n      apply incl_nil'.\n    - (* app *)\n      unfold idck. rewrite map_app.\n      apply incl_appr, incl_appr.\n      rewrite anon_streams_anon_streams. reflexivity.\n    - (* app *)\n      unfold idck. repeat rewrite map_app.\n      apply incl_appr, incl_appr, incl_appr.\n      rewrite anon_streams_anon_streams. reflexivity.\n  Qed.\n\n  Corollary anon_streams_nclocksof_fresh_ins : forall G vars es,\n      Forall (wc_exp G vars) es ->\n      incl (anon_streams (nclocksof es)) (vars++idck (fresh_ins es)).\n  Proof with eauto.\n    induction es; intros Hf; inv Hf; simpl.\n    - eapply incl_nil'.\n    - unfold anon_streams. rewrite map_filter_app.\n      apply incl_app.\n      + etransitivity. eapply anon_streams_nclockof_fresh_in in H1...\n        unfold fresh_ins, idck; simpl.\n        apply incl_appr', incl_map, incl_appl, incl_refl.\n      + etransitivity...\n        unfold fresh_ins, idck; simpl.\n        apply incl_appr', incl_map, incl_appr, incl_refl.\n  Qed.\n\n  (** *** wc_exp implies wc_clock *)\n\n  Definition preserving_sub bck (sub : ident -> option ident) (vars vars' : list (ident * clock)) dom :=\n    Forall (fun i => forall i' ck ck',\n                sub i = Some i' ->\n                instck bck sub ck = Some ck' ->\n                In (i, ck) vars ->\n                In (i', ck') vars'\n           ) dom.\n\n  Fact preserving_sub_incl1 : forall bck sub vars1 vars1' vars2 dom,\n      incl vars1' vars1 ->\n      preserving_sub bck sub vars1 vars2 dom ->\n      preserving_sub bck sub vars1' vars2 dom.\n  Proof.\n    intros bck sub vars1 vars1' vars2 dom Hincl Hpre.\n    unfold preserving_sub in *.\n    eapply Forall_impl; eauto.\n    intros; eauto.\n  Qed.\n\n  Fact preserving_sub_incl2 : forall bck sub vars1 vars2 vars2' dom,\n      incl vars2 vars2' ->\n      preserving_sub bck sub vars1 vars2 dom ->\n      preserving_sub bck sub vars1 vars2' dom.\n  Proof.\n    intros bck sub vars1 vars2 vars2' dom Hincl Hpre.\n    unfold preserving_sub in *.\n    eapply Forall_impl; eauto.\n    intros; eauto.\n  Qed.\n\n  Fact preserving_sub_incl3 : forall bck sub vars vars' dom dom',\n      incl dom dom' ->\n      preserving_sub bck sub vars vars' dom' ->\n      preserving_sub bck sub vars vars' dom.\n  Proof.\n    intros bck sub vars vars' dom dom' Hincl Hpre.\n    unfold preserving_sub in *.\n    eapply Forall_incl; eauto.\n  Qed.\n\n  Instance preserving_sub_Proper:\n    Proper (@eq clock ==> @eq (ident -> option ident)\n                ==> @Permutation (ident * clock) ==> @Permutation (ident * clock) ==> @Permutation ident\n                ==> iff)\n           preserving_sub.\n  Proof.\n    intros bck bck' ? sub sub' ?; subst.\n    intros vars1 vars1' Hperm1 vars2 vars2' Hperm2 dom dom' Hperm3.\n    split; intro H.\n    1,2:eapply preserving_sub_incl1 in H. 2:rewrite Hperm1. 4:rewrite <- Hperm1. 2,4:reflexivity.\n    1,2:eapply preserving_sub_incl2 in H. 2:rewrite Hperm2. 4:rewrite <- Hperm2. 2,4:reflexivity.\n    1,2:eapply preserving_sub_incl3 in H. 2:rewrite Hperm3. 4:rewrite <- Hperm3. 2,4:reflexivity.\n    1,2:assumption.\n  Qed.\n\n  Fixpoint frees_in_clock (ck : clock) :=\n    match ck with\n    | Cbase => []\n    | Con ck' id _ => id::(frees_in_clock ck')\n    end.\n\n  Lemma Is_free_in_frees_in_clock : forall ck,\n      Forall (fun id => Is_free_in_clock id ck) (frees_in_clock ck).\n  Proof with eauto.\n    induction ck; simpl; constructor.\n    - constructor.\n    - eapply Forall_impl...\n      intros a H; simpl in H. constructor...\n  Qed.\n\n  Lemma only_depends_on_frees_in_clock : forall vars ck,\n      only_depends_on vars ck ->\n      incl (frees_in_clock ck) vars.\n  Proof.\n    induction ck; intros Hdep; simpl.\n    - apply incl_nil'.\n    - apply incl_cons.\n      + apply Hdep, FreeCon1.\n      + eapply IHck, only_depends_on_Con, Hdep.\n  Qed.\n\n  Fact instck_wc_clock : forall vars vars' bck sub ck ck',\n      wc_clock vars ck ->\n      wc_clock vars' bck ->\n      preserving_sub bck sub vars vars' (frees_in_clock ck) ->\n      instck bck sub ck = Some ck' ->\n      wc_clock vars' ck'.\n  Proof with eauto.\n    intros vars vars' bck sub.\n    induction ck; intros ck' Hwc Hwcb Hpre Hinst; simpl in *.\n    - inv Hinst...\n    - inv Hwc.\n      destruct (instck bck sub ck) eqn:Hinst'; try congruence.\n      assert (preserving_sub bck sub vars vars' (frees_in_clock ck)) as Hpre'.\n      { eapply preserving_sub_incl3; eauto. apply incl_tl, incl_refl. }\n      specialize (IHck _ H1 Hwcb Hpre' eq_refl).\n      unfold preserving_sub in Hpre; rewrite Forall_forall in Hpre.\n      destruct (sub i) eqn:Hsub; try congruence.\n      inv Hinst. constructor...\n      eapply Hpre... left...\n  Qed.\n\n  Fact WellInstantiated_wc_clock : forall vars vars' sub bck id ck ck' name,\n      wc_clock vars ck ->\n      wc_clock vars' bck ->\n      preserving_sub bck sub vars vars' (frees_in_clock ck) ->\n      WellInstantiated bck sub (id, ck) (ck', name) ->\n      wc_clock vars' ck'.\n  Proof.\n    intros vars vars' sub bck id ck ck' name Hwc Hwcb Hpre Hinst.\n    destruct Hinst as [Hsub Hinst]; simpl in *.\n    eapply instck_wc_clock in Hinst; eauto.\n  Qed.\n\n  Lemma WellInstantiated_wc_clocks' : forall vars' bck sub xs ys,\n      NoDupMembers xs ->\n      dep_ordered_on xs ->\n      wc_clock vars' bck ->\n      wc_env xs ->\n      Forall2 (WellInstantiated bck sub) xs ys ->\n      (preserving_sub bck sub xs (anon_streams ys) (map fst xs) /\\\n       Forall (wc_clock (vars'++anon_streams ys)) (map fst ys)).\n  Proof with eauto.\n    intros vars' bck sub xs ys Hndup Hdep Hbck Hwc Hwinst.\n    induction Hwinst; simpl.\n    - rewrite app_nil_r. unfold preserving_sub...\n    - assert (wc_env l) as Hwc' by (eapply wc_env_dep_ordered_on_remove in Hwc; eauto).\n      simpl in Hdep. inv Hdep.\n      inv Hndup.\n      specialize (IHHwinst H5 H2 Hwc') as [Hpres' Hwc''].\n      assert (preserving_sub bck sub ((a, b)::l) (anon_streams (y::l')) (map fst ((a, b)::l))) as Hpres''.\n      { constructor; simpl in *; auto.\n        - intros id' ck ck' Hsub Hinst Hin.\n          inv Hin. 2:(apply In_InMembers in H0; congruence).\n          inv H0. destruct y as [ck'' ?]. destruct H as [? Hinst']; simpl in *; subst.\n          rewrite Hsub.\n          left. f_equal; congruence.\n        - eapply Forall_impl; [|eauto].\n          intros id' Hin id'' ck' ck'' Hsub Hinst Hin'; simpl in *.\n          destruct Hin' as [Heq|Hin'].\n          + inv Heq.\n             destruct y as [? ?]; destruct H as [Hsub' Hinst']; simpl in *.\n             rewrite Hsub in Hsub'. rewrite Hinst in Hinst'. inv Hinst'.\n             left...\n          + specialize (Hin _ _ _ Hsub Hinst Hin').\n             destruct y as [? [?|]]...\n             right... }\n      split; simpl...\n      constructor; simpl.\n      + destruct y as [ck [id|]]; simpl in *.\n        * eapply WellInstantiated_wc_clock in H...\n          -- inv Hwc...\n          -- eapply wc_clock_incl...\n             apply incl_appl, incl_refl.\n          -- eapply preserving_sub_incl3. 1:eapply incl_tl, only_depends_on_frees_in_clock...\n             eapply preserving_sub_incl2... apply incl_appr, incl_refl.\n        * eapply WellInstantiated_wc_clock in H...\n          -- inv Hwc...\n          -- eapply wc_clock_incl...\n             apply incl_appl, incl_refl.\n          -- eapply preserving_sub_incl3. 1:eapply incl_tl, only_depends_on_frees_in_clock...\n             eapply preserving_sub_incl2... apply incl_appr, incl_refl.\n      + eapply Forall_impl; [|eauto].\n          intros. eapply wc_clock_incl; eauto.\n          apply incl_appr'.\n          destruct y as [ck [id|]]; [apply incl_tl|]; apply incl_refl.\n  Qed.\n\n  Corollary WellInstantiated_wc_clocks : forall vars' bck sub xs ys,\n      NoDupMembers xs ->\n      wc_clock vars' bck ->\n      wc_env xs ->\n      Forall2 (WellInstantiated bck sub) xs ys ->\n      Forall (wc_clock (vars'++anon_streams ys)) (map fst ys).\n  Proof with eauto.\n    intros vars' bck sub xs ys Hndup Hwc Hwenv Hwellinst.\n    specialize (wc_env_dep_ordered_on _ Hndup Hwenv) as [xs' [Hperm1 Hdep1]].\n    assert (NoDupMembers xs') as Hndup'' by (rewrite <- Hperm1; eauto).\n    eapply Forall2_Permutation_1 in Hwellinst as [ys' [Hperm2 Hwellinst]]...\n    eapply WellInstantiated_wc_clocks' in Hwellinst as (_&?);\n      try rewrite app_nil_r in *; simpl in *...\n    - eapply Forall_impl. 2:rewrite Hperm2...\n      intros. unfold anon_streams. rewrite Hperm2...\n    - rewrite <- Hperm1. assumption.\n  Qed.\n\n  Lemma wc_exp_clockof : forall G vars e,\n      wc_global G ->\n      wc_env vars ->\n      wc_exp G vars e ->\n      Forall (wc_clock (vars++idck (fresh_in e))) (clockof e).\n  Proof with eauto.\n    Local Ltac Forall_clocksof :=\n      unfold clocksof; rewrite flat_map_concat_map;\n      apply Forall_concat; rewrite Forall_map;\n      rewrite Forall_forall in *; intros ? Hin; eauto.\n\n    intros G vars e HG Henv.\n    induction e using exp_ind2; intros Hwc; inv Hwc;\n      simpl; unfold clock_of_nclock, stripname; simpl; repeat constructor.\n    - (* var *)\n      simpl_list.\n      unfold wc_env in Henv; rewrite Forall_forall in Henv.\n      apply Henv in H0...\n    - (* var (anon) *)\n      simpl_list.\n      unfold wc_env in Henv; rewrite Forall_forall in Henv.\n      apply Henv in H0...\n    - (* unop *)\n      apply IHe in H1...\n      rewrite H3 in H1. inv H1...\n    - (* binop *)\n      apply IHe1 in H3...\n      rewrite H5 in H3. inv H3. clear H2.\n      eapply wc_clock_incl; eauto.\n      eapply incl_appr', incl_map, incl_appl, incl_refl.\n    - (* fby *)\n      rewrite Forall2_eq in H6, H7. unfold clock_of_nclock, stripname in H6; rewrite H6.\n      Forall_clocksof...\n      specialize (H _ Hin (H4 _ Hin)). rewrite Forall_forall in *; intros.\n        apply H in H1. eapply wc_clock_incl; eauto. eapply incl_appr', incl_map, incl_appl, fresh_in_incl, Hin.\n    - (* arrow *)\n      rewrite Forall2_eq in H6, H7. unfold clock_of_nclock, stripname in H6; rewrite H6.\n      Forall_clocksof...\n      specialize (H _ Hin (H4 _ Hin)). rewrite Forall_forall in *; intros.\n        apply H in H1. eapply wc_clock_incl; eauto. eapply incl_appr', incl_map, incl_appl, fresh_in_incl, Hin.\n    - (* when *)\n      destruct tys; [simpl in *; auto|].\n      rewrite Forall_map. eapply Forall_forall; intros ? _.\n      constructor. 2:eapply in_or_app...\n      assert (Forall (wc_clock (vars++idck (fresh_ins es))) (clocksof es)) as Hwc.\n      { Forall_clocksof.\n        specialize (H _ Hin (H4 _ Hin)). rewrite Forall_forall in *; intros.\n        apply H in H0. eapply wc_clock_incl; eauto. eapply incl_appr', incl_map, fresh_in_incl, Hin.\n      } clear H.\n      eapply Forall_Forall in H6...\n      destruct (clocksof es); simpl in *; try congruence.\n      inv H6. destruct H1; subst...\n    - (* merge *)\n      destruct tys; [simpl in *; auto|].\n      rewrite Forall_map. eapply Forall_forall; intros ? _.\n      assert (Forall (wc_clock (vars++idck (fresh_ins ets))) (clocksof ets)) as Hwc.\n      { Forall_clocksof.\n        specialize (H _ Hin (H5 _ Hin)). rewrite Forall_forall in *; intros.\n        apply H in H1. eapply wc_clock_incl; eauto. eapply incl_appr', incl_map, fresh_in_incl, Hin.\n      } clear H.\n      eapply Forall_Forall in H8...\n      destruct (clocksof ets); simpl in *; try congruence.\n      inv H8. destruct H2; subst. inv H.\n      eapply wc_clock_incl... apply incl_appr', incl_map, incl_appl, incl_refl.\n    - (* ite *)\n      destruct tys; [simpl in *; auto|].\n      rewrite Forall_map. eapply Forall_forall; intros ? _.\n      assert (Forall (wc_clock (vars++idck (fresh_ins ets))) (clocksof ets)) as Hwc.\n      { Forall_clocksof.\n        specialize (H _ Hin (H6 _ Hin)). rewrite Forall_forall in *; intros.\n        apply H in H1. eapply wc_clock_incl; eauto. eapply incl_appr', incl_map, fresh_in_incl, Hin.\n      } clear H.\n      eapply Forall_Forall in H9...\n      destruct (clocksof ets); simpl in *; try congruence.\n      inv H9. destruct H2; subst.\n      eapply wc_clock_incl... apply incl_appr', incl_map, incl_appr, incl_appl, incl_refl.\n    - (* app *)\n      assert (Forall (wc_clock (vars++idck (fresh_ins es))) (clocksof es)) as Hwc.\n      { Forall_clocksof.\n        specialize (H0 _ Hin (H5 _ Hin)). rewrite Forall_forall in *; intros.\n        apply H0 in H1. eapply wc_clock_incl; eauto. eapply incl_appr', incl_map, fresh_in_incl, Hin.\n      } clear H.\n      eapply wc_find_node in H6 as [G' Hwcnode]...\n      assert (wc_clock (vars ++ idck (fresh_ins es)) bck) as Hbck.\n      { eapply WellInstantiated_bck in H7...\n        + rewrite <- clocksof_nclocksof in H7.\n          rewrite Forall_forall in Hwc. apply Hwc in H7...\n        + destruct Hwcnode as [? _]...\n        + unfold idck. rewrite map_length. apply n_ingt0... }\n      specialize (Forall2_app H7 H8) as Hinst.\n      eapply WellInstantiated_wc_clocks in Hinst...\n      + rewrite map_app, map_map, Forall_app in Hinst. destruct Hinst as [_ Hinst].\n        eapply Forall_impl; [|eauto].\n        intros; simpl in *. eapply wc_clock_incl...\n        unfold anon_streams; rewrite map_filter_app.\n        repeat rewrite <- app_assoc. repeat apply incl_app.\n        * apply incl_appl, incl_refl.\n        * apply incl_appr, incl_map, incl_appl, incl_refl.\n        * etransitivity. eapply anon_streams_nclocksof_fresh_ins...\n          apply incl_appr', incl_map, incl_appl, incl_refl.\n        * unfold idck; rewrite map_app.\n          apply incl_appr, incl_appr. rewrite anon_streams_anon_streams.\n          reflexivity.\n      + specialize (n_nodup n) as Hndup.\n        repeat rewrite app_assoc in Hndup. eapply NoDupMembers_app_l in Hndup.\n        rewrite <- app_assoc, <- Permutation_swap in Hndup. eapply NoDupMembers_app_r in Hndup.\n        rewrite fst_NoDupMembers in Hndup. rewrite fst_NoDupMembers.\n        unfold idck. rewrite map_app in *. repeat rewrite map_map; simpl...\n      + destruct Hwcnode as [_ [Hwcnode _]].\n        unfold idck in *. rewrite map_app in Hwcnode...\n    - (* app (reset) *)\n      assert (Forall (wc_clock (vars++idck (fresh_ins es))) (clocksof es)) as Hwc.\n      { Forall_clocksof.\n        specialize (H0 _ Hin (H5 _ Hin)). rewrite Forall_forall in *; intros.\n        apply H0 in H1. eapply wc_clock_incl; eauto. eapply incl_appr', incl_map, fresh_in_incl, Hin.\n      } clear H.\n      eapply wc_find_node in H6 as [G' Hwcnode]...\n      assert (wc_clock (vars ++ idck (fresh_ins es)) bck) as Hbck.\n      { eapply WellInstantiated_bck in H7...\n        + rewrite <- clocksof_nclocksof in H7.\n          rewrite Forall_forall in Hwc. apply Hwc in H7...\n        + destruct Hwcnode as [? _]...\n        + unfold idck. rewrite map_length. apply n_ingt0... }\n      specialize (Forall2_app H7 H8) as Hinst.\n      eapply WellInstantiated_wc_clocks in Hinst...\n      + rewrite map_app, map_map, Forall_app in Hinst. destruct Hinst as [_ Hinst].\n        eapply Forall_impl; [|eauto].\n        intros; simpl in *. eapply wc_clock_incl...\n        unfold anon_streams; rewrite map_filter_app.\n        repeat rewrite <- app_assoc. repeat apply incl_app.\n        * apply incl_appl, incl_refl.\n        * apply incl_appr, incl_map, incl_appl, incl_refl.\n        * etransitivity. eapply anon_streams_nclocksof_fresh_ins...\n          apply incl_appr', incl_map, incl_appl, incl_refl.\n        * unfold idck; repeat rewrite map_app.\n          apply incl_appr, incl_appr, incl_appr. rewrite anon_streams_anon_streams.\n          reflexivity.\n      + specialize (n_nodup n) as Hndup.\n        repeat rewrite app_assoc in Hndup. eapply NoDupMembers_app_l in Hndup.\n        rewrite <- app_assoc, <- Permutation_swap in Hndup. eapply NoDupMembers_app_r in Hndup.\n        rewrite fst_NoDupMembers in Hndup. rewrite fst_NoDupMembers.\n        unfold idck. rewrite map_app in *. repeat rewrite map_map; simpl...\n      + destruct Hwcnode as [_ [Hwcnode _]].\n        unfold idck in *. rewrite map_app in Hwcnode...\n  Qed.\n\n  Corollary wc_exp_clocksof : forall G vars es,\n      wc_global G ->\n      wc_env vars ->\n      Forall (wc_exp G vars) es ->\n      Forall (wc_clock (vars++idck (fresh_ins es))) (clocksof es).\n  Proof with eauto.\n    intros G vars es HwG Hwenv Hwc.\n    induction Hwc; simpl. constructor.\n    - eapply Forall_app. split.\n      + eapply wc_exp_clockof in H...\n        eapply Forall_impl; [|eauto]. intros.\n        eapply wc_clock_incl; [|eauto].\n        unfold fresh_ins, idck. simpl; rewrite map_app.\n        apply incl_appr', incl_appl, incl_refl.\n      + eapply Forall_impl; [|eauto]. intros.\n        eapply wc_clock_incl; [|eauto].\n        unfold fresh_ins, idck. simpl; rewrite map_app.\n        apply incl_appr', incl_appr, incl_refl.\n  Qed.\n\n  Lemma wc_clock_is_free_in : forall vars ck,\n      wc_clock vars ck ->\n      forall x, Is_free_in_clock x ck -> InMembers x vars.\n  Proof.\n    intros * Hwc ? Hfree.\n    induction Hwc; inv Hfree; eauto using In_InMembers.\n  Qed.\n\n  Corollary Forall_wc_clock_is_free_in : forall vars cks,\n      Forall (wc_clock vars) cks ->\n      Forall (fun ck => forall x, Is_free_in_clock x ck -> InMembers x vars) cks.\n  Proof.\n    intros * Hwcs.\n    eapply Forall_impl; eauto.\n    intros ck Hwc. eapply wc_clock_is_free_in; eauto.\n  Qed.\n\n  Corollary wc_env_is_free_in : forall vars,\n      wc_env vars ->\n      Forall (fun '(_, ck) => forall x, Is_free_in_clock x ck -> InMembers x vars) vars.\n  Proof.\n    intros * Hwenv. unfold wc_env in Hwenv.\n    eapply Forall_impl; eauto.\n    intros [? ck] Hwc. eapply wc_clock_is_free_in; eauto.\n  Qed.\n\n  Inductive dep_ordered_on' : list ident -> list nclock -> Prop :=\n  | dep_ordered'_nil : forall vars, dep_ordered_on' vars []\n  | dep_ordered'_cons : forall vars ncks ck name,\n      dep_ordered_on' vars ncks ->\n      only_depends_on (vars++map fst (anon_streams ncks)) ck ->\n      dep_ordered_on' vars ((ck, name)::ncks).\n\n  Fact dep_ordered_on'_Forall : forall vars ncks,\n      dep_ordered_on' vars ncks ->\n      Forall (fun '(ck, _) => only_depends_on (vars++map fst (anon_streams ncks)) ck) ncks.\n  Proof.\n    intros * Hdep; induction Hdep; constructor.\n    - destruct name; simpl; auto.\n      eapply only_depends_on_incl; eauto.\n      apply incl_appr', incl_tl, incl_refl.\n    - destruct name; simpl; auto.\n      eapply Forall_impl; eauto.\n      intros [ck' name'] Hdep'.\n      eapply only_depends_on_incl; eauto.\n      apply incl_appr', incl_tl, incl_refl.\n  Qed.\n\n  Lemma WellInstantiated_dep_ordered_on : forall bck bckinputs sub cks ncks,\n      dep_ordered_on cks ->\n      only_depends_on bckinputs bck ->\n      Forall2 (WellInstantiated bck sub) cks ncks ->\n      dep_ordered_on' bckinputs ncks.\n  Proof.\n    induction cks; intros * Hdep Hbck Hwi; inv Hdep; inv Hwi; simpl; try constructor.\n    destruct y as [ck name].\n    constructor; auto; simpl.\n    erewrite <- WellInstantiated_sub_fsts; eauto.\n    inv H3; simpl in *. eapply instck_only_depends_on in H0; eauto.\n  Qed.\n\n  Lemma WellInstantiated_is_free_in : forall G f n inputs ins outs sub bck,\n      wc_global G ->\n      find_node f G = Some n ->\n      Forall (fun '(ck, _) => forall x, Is_free_in_clock x ck -> In x inputs) ins ->\n      Forall2 (WellInstantiated bck sub) (idck (n_in n)) ins ->\n      Forall2 (WellInstantiated bck sub) (idck (n_out n)) outs ->\n      Forall (fun '(ck, _) => forall x, Is_free_in_clock x ck ->\n                                In x inputs \\/\n                                In x (map fst (anon_streams ins)) \\/\n                                In x (map fst (anon_streams outs))) outs.\n  Proof.\n    intros * HwcG Hfind Hinputs Hwi1 Hwi2.\n    eapply wc_find_node in HwcG as [? Hwnode]; eauto.\n\n    assert (In bck (map stripname ins)) as Hbck.\n    { eapply WellInstantiated_bck in Hwi1; eauto.\n      - destruct Hwnode as [? _]; eauto.\n      - rewrite length_idck. exact (n_ingt0 n). }\n\n    specialize (Forall2_app Hwi1 Hwi2) as Hwi. clear Hwi1 Hwi2.\n    rewrite <- idck_app in Hwi.\n\n    assert (exists vars, Permutation (idck (n_in n ++ n_out n)) vars /\\ dep_ordered_on vars) as [vars [Hperm Hdepo]].\n    { eapply wc_env_dep_ordered_on.\n      - specialize (n_nodup n) as Hndup.\n        rewrite NoDupMembers_idck.\n        rewrite (Permutation_app_comm (n_vars n)), <- app_assoc, app_assoc in Hndup.\n        apply NoDupMembers_app_l in Hndup; auto.\n      - destruct Hwnode as [_ [? _]]; auto. }\n    eapply Forall2_Permutation_1 in Hwi as [vars' [Hperm' Hwi]]; eauto.\n\n    eapply WellInstantiated_dep_ordered_on with (bckinputs:=inputs) in Hwi; eauto.\n    - apply dep_ordered_on'_Forall in Hwi.\n      rewrite <- Hperm', Forall_app in Hwi. destruct Hwi as [_ ?].\n      eapply Forall_impl; eauto. intros [ck ?] Hondep ? Hfree.\n      eapply Hondep in Hfree. unfold anon_streams in Hfree; rewrite <- Hperm' in Hfree.\n      rewrite map_filter_app, map_app in Hfree.\n      repeat rewrite in_app_iff in Hfree; auto.\n    - apply in_map_iff in Hbck as [[? ?] [? Hbck]]; subst.\n      eapply Forall_forall in Hbck; eauto; simpl in *; auto.\n  Qed.\n\n  Section interface_eq.\n\n    Hint Constructors wc_exp.\n    Fact iface_eq_wc_exp : forall G G' vars e,\n        global_iface_eq G G' ->\n        wc_exp G vars e ->\n        wc_exp G' vars e.\n    Proof with eauto.\n      induction e using exp_ind2; intros Heq Hwt; inv Hwt...\n      - (* fby *)\n        econstructor...\n        + rewrite Forall_forall in *...\n        + rewrite Forall_forall in *...\n      - (* arrow *)\n        econstructor...\n        + rewrite Forall_forall in *...\n        + rewrite Forall_forall in *...\n      - (* when *)\n        econstructor...\n        rewrite Forall_forall in *...\n      - (* merge *)\n        econstructor...\n        + rewrite Forall_forall in *...\n        + rewrite Forall_forall in *...\n      - (* ite *)\n        econstructor...\n        + rewrite Forall_forall in *...\n        + rewrite Forall_forall in *...\n      - (* app *)\n        assert (Forall (wc_exp G' vars) es) as Hwt by (rewrite Forall_forall in *; eauto).\n        specialize (Heq f).\n        remember (find_node f G') as find.\n        destruct Heq.\n        + congruence.\n        + inv H6.\n          destruct H1 as [? [? [? ?]]].\n          eapply wc_Eapp with (n:=sy)...\n          * rewrite <- H3...\n          * rewrite <- H4...\n      - (* app (reset) *)\n        assert (Forall (wc_exp G' vars) es) as Hwt by (rewrite Forall_forall in *; eauto).\n        assert (wc_exp G' vars r) as Hwt' by (rewrite Forall_forall in *; eauto).\n        specialize (Heq f).\n        remember (find_node f G') as find.\n        destruct Heq.\n        + congruence.\n        + inv H6.\n          destruct H1 as [? [? [? ?]]].\n          eapply wc_EappReset with (n:=sy)...\n          * rewrite <- H3...\n          * rewrite <- H4...\n    Qed.\n\n    Fact iface_eq_wc_equation : forall G G' vars equ,\n        global_iface_eq G G' ->\n        wc_equation G vars equ ->\n        wc_equation G' vars equ.\n    Proof.\n      intros G G' vars [xs es] Heq Hwc.\n      simpl in *. destruct Hwc as [Hwc1 [Hwc2 Hwc3]].\n      repeat split; auto.\n      rewrite Forall_forall in *. intros x Hin.\n      eapply iface_eq_wc_exp; eauto.\n    Qed.\n\n    Lemma iface_eq_wc_node : forall G G' n,\n        global_iface_eq G G' ->\n        wc_node G n ->\n        wc_node G' n.\n    Proof.\n      intros G G' n Heq Hwt.\n      destruct Hwt as [? [? [? Hwc]]].\n      repeat split; auto.\n      rewrite Forall_forall in *; intros.\n      eapply iface_eq_wc_equation; eauto.\n    Qed.\n\n  End interface_eq.\n\n  (** ** wc implies wl *)\n\n  Hint Constructors wl_exp.\n  Fact wc_exp_wl_exp : forall G vars e,\n      wc_exp G vars e ->\n      wl_exp G e.\n  Proof with eauto.\n    induction e using exp_ind2; intro Hwt; inv Hwt; auto.\n    - (* unop *)\n      constructor...\n      rewrite <- length_clockof_numstreams. rewrite H3. reflexivity.\n    - (* binop *)\n      constructor...\n      + rewrite <- length_clockof_numstreams. rewrite H5. reflexivity.\n      + rewrite <- length_clockof_numstreams. rewrite H6. reflexivity.\n    - (* fby *)\n      constructor; rewrite Forall_forall in *...\n      + apply Forall2_length in H6. rewrite clocksof_annots in H6. repeat rewrite map_length in H6...\n      + apply Forall2_length in H7. rewrite clocksof_annots in H7. repeat rewrite map_length in H7...\n    - (* arrow *)\n      constructor; rewrite Forall_forall in *...\n      + apply Forall2_length in H6. rewrite clocksof_annots in H6. repeat rewrite map_length in H6...\n      + apply Forall2_length in H7. rewrite clocksof_annots in H7. repeat rewrite map_length in H7...\n    - (* when *)\n      constructor; rewrite Forall_forall in *...\n      rewrite clocksof_annots, map_length, map_length in H7...\n    - (* merge *)\n      constructor; rewrite Forall_forall in *...\n      + rewrite clocksof_annots, map_length, map_length in H10...\n      + rewrite clocksof_annots, map_length, map_length in H11...\n    - (* ite *)\n      constructor; rewrite Forall_forall in *...\n      + rewrite <- length_clockof_numstreams, H8. reflexivity.\n      + rewrite clocksof_annots, map_length, map_length in H11...\n      + rewrite clocksof_annots, map_length, map_length in H12...\n    - (* app *)\n      econstructor...\n      + rewrite Forall_forall in *...\n      + apply Forall2_length in H7. unfold idck in H7.\n        rewrite nclocksof_annots in H7. repeat rewrite map_length in H7...\n      + apply Forall2_length in H8. unfold idck in H8.\n        repeat rewrite map_length in H8...\n    - (* app (reset) *)\n      econstructor...\n      + rewrite Forall_forall in *...\n      + rewrite <- length_clockof_numstreams, H10...\n      + apply Forall2_length in H7. unfold idck in H7.\n        rewrite nclocksof_annots in H7. repeat rewrite map_length in H7...\n      + apply Forall2_length in H8. unfold idck in H8.\n        repeat rewrite map_length in H8...\n  Qed.\n  Hint Resolve wc_exp_wl_exp.\n\n  Corollary Forall_wc_exp_wl_exp : forall G vars es,\n      Forall (wc_exp G vars) es ->\n      Forall (wl_exp G) es.\n  Proof. intros. rewrite Forall_forall in *; eauto. Qed.\n  Hint Resolve Forall_wc_exp_wl_exp.\n\n  Fact wc_equation_wl_equation : forall G vars equ,\n      wc_equation G vars equ ->\n      wl_equation G equ.\n  Proof with eauto.\n    intros G vars [xs es] [Hwc1 [Hwc2 _]].\n    constructor.\n    + rewrite Forall_forall in *...\n    + rewrite nclocksof_annots in Hwc2.\n      apply Forall2_length in Hwc2.\n      rewrite map_length in Hwc2...\n  Qed.\n  Hint Resolve wc_equation_wl_equation.\n\n  Fact wc_node_wl_node : forall G n,\n      wc_node G n ->\n      wl_node G n.\n  Proof with eauto.\n    intros G n [_ [_ [_ Hwc]]].\n    unfold wl_node.\n    rewrite Forall_forall in *...\n  Qed.\n  Hint Resolve wc_node_wl_node.\n\n  Fact wc_global_wl_global : forall G,\n      wc_global G ->\n      wl_global G.\n  Proof with eauto.\n    intros G Hwt.\n    induction Hwt; constructor...\n  Qed.\n  Hint Resolve wc_global_wl_global.\nEnd LCLOCKING.\n\nModule LClockingFun\n       (Ids  : IDS)\n       (Op   : OPERATORS)\n       (Syn  : LSYNTAX Ids Op)\n       <: LCLOCKING Ids Op Syn.\n  Include LCLOCKING Ids Op Syn.\nEnd LClockingFun.\n", "meta": {"author": "INRIA", "repo": "velus", "sha": "116a88bc71f3608ff43ed967895743e8b9a340e0", "save_path": "github-repos/coq/INRIA-velus", "path": "github-repos/coq/INRIA-velus/velus-116a88bc71f3608ff43ed967895743e8b9a340e0/src/Lustre/LClocking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2215818603584672}}
{"text": "Set Warnings \"-notation-overridden\".\n\nRequire Import Coq.Program.Basics.\nRequire Import Coq.Init.Logic.\nRequire Import Coq.Logic.Eqdep_dec.\n\nFrom Equations Require Import Equations.\nUnset Equations With Funext.\n\nRequire Import Category.Lib.\nRequire Import Category.Theory.\nRequire Import Category.Instance.Coq.\n\nRequire Import Embed.Theory.Functor.Void.\nRequire Import Embed.Theory.Functor.Refined.Def.\nRequire Import Embed.Theory.Functor.Refined.Iso.\nRequire Import Embed.Theory.Functor.Refined.ToFrom.\n\nRequire Import Embed.Theory.Utils.\n\nGeneralizable All Variables.\nSet Universe Polymorphism.\nSet Nested Proofs Allowed.\n\nSection EmbedRefined.\nContext `{F : Coq ⟶ Coq}.\n\nClass EmbedRefinedCat (G : RefinedCat ⟶ Coq) := {\n  embed_iso_refined x y :\n    iso_refined x y ↔ G x = G y;\n\n  embed_refined x : G x;\n  embed_refined_unique x (xs : G x) : embed_refined x = xs;\n\n  run_embed_refined {x} (xs : G x) : F 1;\n\n  cast_run_embed_refined {x y} (xs : G x) (pf : G x = G y) :\n      run_embed_refined (cast pf xs) = run_embed_refined xs;\n\n  fobj_run_embed_refined {x} (xs : G x) :\n    G (run_embed_refined xs) = G x;\n\n  canonical_refined (x : F 1) : F 1 :=\n    run_embed_refined (embed_refined x);\n}.\n\nContext (G : RefinedCat ⟶ Coq).\nContext {eqDecG : forall x, EqDec (G x)}.\nContext {embedRefinedCatG : EmbedRefinedCat G}.\n\nLemma iso_refined_canonical_refined {x y : F 1} :\n  iso_refined (canonical_refined x) y ↔ iso_refined x y.\nsplit.\n\nintro.\nrefine (snd (embed_iso_refined _ _) _).\npose (X' := fst (embed_iso_refined _ _) X).\nunfold canonical_refined in *.\nrewrite fobj_run_embed_refined in X'.\nexact X'.\n\n(* Practically the same proof as above *)\nintro.\nrefine (snd (embed_iso_refined _ _) _).\npose (X' := fst (embed_iso_refined _ _) X).\nunfold canonical_refined in *.\nrewrite fobj_run_embed_refined.\nexact X'.\nQed.\n\nLemma unfold_canonical_refined_eq {x y : F 1} :\n    canonical_refined x = canonical_refined y ↔ iso_refined x y.\nsplit.\n\nunfold canonical_refined.\nintro.\npose (H' := f_equal G H).\nrepeat (rewrite fobj_run_embed_refined in H').\nexact (snd (embed_iso_refined x y) H').\n\nintro.\nunfold canonical_refined.\npose (X' := fst (embed_iso_refined x y) X).\npose (embed_refined_unique x (cast (eq_sym X') (embed_refined y))).\npose (f_equal run_embed_refined e).\nrewrite cast_run_embed_refined in e0.\nexact e0.\nQed.\n\nProgram Instance canonical_refined_Idempotent : Idempotent canonical_refined.\nNext Obligation.\nsimpl.\nrefine (snd unfold_canonical_refined_eq _).\nrefine (snd (embed_iso_refined (canonical_refined x) x) _).\nunfold canonical_refined.\nrewrite fobj_run_embed_refined.\nreflexivity.\nQed.\n\nContext `{monadF : @Monad Coq F}.\n\nDefinition section (A : Type) (x y : F 1) : Type :=\n    { z : F (F A) |\n      canonical_refined (void[F] z) = canonical_refined x /\\\n      canonical_refined (void[F] (join[F] z)) = canonical_refined y\n    }.\n\nLemma eq_section {A} {F1_dec : EqDec (F 1)} {x y : F 1} (xs ys : section A x y)\n  (pf : proj1_sig xs = proj1_sig ys) : xs = ys.\ndestruct xs, ys.\nunfold proj1_sig in pf.\nrefine (eq_sig\n  (exist\n  (λ z : F (F A),\n   canonical_refined (void[F] z) = canonical_refined x /\\\n   canonical_refined (void[F] (join[F] z)) = canonical_refined y) x0 a)\n  (exist\n  (λ z : F (F A),\n   canonical_refined (void[F] z) = canonical_refined x /\\\n   canonical_refined (void[F] (join[F] z)) = canonical_refined y) x1 a0)\n  pf\n  _\n).\nsimpl.\n\ndestruct pf.\nsimpl.\nrefine (eq_and _ _).\nQed.\n\nDefinition fst_section {A} {x y : F 1} : section A x y -> F (F A) := @proj1_sig _ _.\n\nDefinition snd_section {A} {x y : F 1} (xy : section A x y) :\n  canonical_refined (void[F] (fst_section xy)) = canonical_refined x /\\\n  canonical_refined (void[F] (join[F] (fst_section xy))) = canonical_refined y :=\n    @proj2_sig _\n      (fun z =>\n        canonical_refined (void[F] z) = canonical_refined x /\\\n        canonical_refined (void[F] (join[F] z)) = canonical_refined y\n      )\n      _.\n\nLemma unfold_snd_section {A} {x y : F 1} (z : F (F A)) :\n  canonical_refined (void[F] z) = canonical_refined x /\\\n  canonical_refined (void[F] (join[F] z)) = canonical_refined y ↔\n  iso_refined (void[F] z) x *\n  iso_refined (void[F] (join[F] z)) y.\nsplit.\n\nintro.\ndestruct H.\nsplit.\n\npose (H' := f_equal canonical_refined H).\npose (idem_z := idem (void[F] z)).\nsimpl in idem_z.\nrewrite idem_z in H'.\nclear idem_z.\npose (H'' := Equivalence_Symmetric _ _ (fst unfold_canonical_refined_eq H')).\nexact (Equivalence_Symmetric _ _ (fst iso_refined_canonical_refined H'')).\n\npose (H0' := f_equal canonical_refined H0).\npose (idem_z := idem (void[F] (join[F] z))).\nsimpl in idem_z.\nrewrite idem_z in H0'.\nclear idem_z.\npose (H0'' := Equivalence_Symmetric _ _ (fst unfold_canonical_refined_eq H0')).\nexact (Equivalence_Symmetric _ _ (fst iso_refined_canonical_refined H0'')).\n\nintro.\ndestruct X.\nsplit.\n\nexact (snd unfold_canonical_refined_eq i).\n\nexact (snd unfold_canonical_refined_eq i0).\nQed.\n\n(* TODO: Cleanup class definition *)\nClass Iso_refined_void_join :=\n  iso_refined_void_join : forall (x : F (F 1)) (y : F 1)\n  (pf : iso_refined (join[F] x) y) (A : Type),\n    @refined (Compose F F) x A ≅ refined y A.\n\nDefinition wrapped_section A : Type :=\n  { i & section A (canonical_refined (ret[F] tt)) i }.\n\nLemma eq_wrapped_section {A} {F1_dec : EqDec (F 1)} (xs ys : wrapped_section A)\n  (pf1 : projT1 xs = projT1 ys)\n  (pf2 : proj1_sig (projT2 xs) = proj1_sig (projT2 ys)) : xs = ys.\ndestruct xs, ys.\ndestruct s, s0.\nsimpl in pf1, pf2.\ndestruct pf1.\ndestruct pf2.\nrewrite (eq_and a a0).\nreflexivity.\nQed.\n\nEquations from_wrapped_section {A} (xs : wrapped_section A) : F A :=\nfrom_wrapped_section xs := join[F] (proj1_sig (projT2 xs)).\n\nClass Iso_refined_void_ret : Type := {\n  iso_refined_void_ret {A} {x : F A}\n    (pf : iso_refined (void[F] x) (ret tt)) :\n      { y | ret y = x}\n}.\n\nLemma iso_refined_void_ret_join {A} {Iso_refined_void_retF : Iso_refined_void_ret}\n  (x : F (F A))\n  (pf : iso_refined (void x) (ret tt)) :\n  ret (join x) = x.\ndestruct (iso_refined_void_ret pf).\nrewrite <- e.\npose (H := join_ret x0).\nsimpl in H.\nrewrite H.\nreflexivity.\nQed.\n\nEnd EmbedRefined.\n\n", "meta": {"author": "michaeljklein", "repo": "btree-lattice-experiments", "sha": "769670d3c98591a4ddb3854feea22eae554323f5", "save_path": "github-repos/coq/michaeljklein-btree-lattice-experiments", "path": "github-repos/coq/michaeljklein-btree-lattice-experiments/btree-lattice-experiments-769670d3c98591a4ddb3854feea22eae554323f5/Theory/Functor/Refined.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.22158185426967658}}
{"text": "(* DEC1 language development.\n   Paolo Torrini, \n   Universite' Lille-1 - CRIStAL-CNRS\n *)\n(* useful DEC definitions *)\n\nRequire Export Coq.Program.Equality.\nRequire Import Coq.Init.Specif.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Strings.String.\nRequire Import Omega.\nRequire Import Coq.Lists.List.\n\nRequire Export EnvLibA.\nRequire Export RelLibA.\nRequire Export PRelLibA.\n\nRequire Import StaticSemA.\nRequire Import DynamicSemA.\nRequire Import TRInductA.\nRequire Import WeakenA.\nRequire Import TSoundnessA.\nRequire Import IdModTypeA.\nRequire Import DetermA.\nRequire Import STypingA.\n\nModule Abbrev (IdT: IdModType) <: IdModType.\n\nDefinition Id := IdT.Id.\nDefinition IdEqDec := IdT.IdEqDec.\nDefinition IdEq := IdT.IdEq.\nDefinition W := IdT.W.\nDefinition Loc_PI := IdT.Loc_PI.\nDefinition BInit := IdT.BInit.\nDefinition WP := IdT.WP.\n\nModule STypingI := STyping IdT.\nExport STypingI.\n\nOpen Scope string_scope.\nImport ListNotations.\n\n\n(** special value constructors *)\n\nDefinition NatCst (v: nat) : Value := cst nat v.\n\nDefinition UnitCst (v: unit) : Value := cst unit v.\n\nDefinition BoolCst (v: bool) : Value := cst bool v.\n \nDefinition TrueV : Exp := Val (cst bool true).\n\nDefinition FalseV : Exp := Val (cst bool false).\n\nDefinition UnitV : Exp := Val (cst unit tt).\n\nDefinition VLift := Return LL.\n\nDefinition Skip : Exp := VLift (QV (cst unit tt)).\n\nDefinition NoRet (e: Exp) : Exp := BindN e Skip. \n\n\n(**************************************************************************)\n\nInstance PState_ValTyp : ValTyp (PState W).\n\n\nDefinition xf_read {T: Type} (f: W -> T) : XFun unit T := {|\n   b_mod := fun x _ => (x, f x)     \n|}.                                                     \n\nDefinition xf_write {T: Type} (f: T -> W) : XFun T unit := {|\n   b_mod := fun _ x => (f x, tt)     \n|}.                                                     \n\nDefinition xf_reset : XFun (PState W) unit := {|\n   b_mod := fun x _ => (b_init, tt)     \n|}.                                                     \n\n\nDefinition Read {T: Type} (VT: ValTyp T) (f: W -> T) : Exp :=\n  Modify unit T UnitVT VT (xf_read f) (QV (cst unit tt)).\n\nDefinition Write {T: Type} (VT: ValTyp T) (f: T -> W) (x: T) : Exp :=\n  Modify T unit VT UnitVT (xf_write f) (QV (cst T x)).\n\nDefinition Reset : Exp :=\n  Modify (PState W) unit PState_ValTyp UnitVT xf_reset\n         (QV (cst (PState W) WP)).\n\n(*\nDefinition ReadA (VT: ValTyp Value) (f: W -> Value) : Exp :=\n  Modify unit Value UnitVT VT (xf_read f) (QV (cst unit tt)).\n\nDefinition WriteA (VT: ValTyp Value) (f: Value -> W) (v: Value) : Exp :=\n  Modify Value unit VT UnitVT (xf_write f) (QV (cst Value x)).\n\nDefinition CReturn (VT: ValTyp Value)\n           (toStack: Value -> W) (fromStack: W -> Value) (e: Exp) : Exp :=\n  BindN (NoRet (BindS x e (WriteA toStack x))) (Read fromStack).  \n*)\n\n(**********************************************************************)\n\nLemma emptyFTyping : FEnvTyping emptyE emptyE.\n  constructor.\nDefined.\n\nLemma emptyVTyping : EnvTyping emptyE emptyE.\n  constructor.\nDefined.\n\n\nDefinition expTypingTest (e: Exp) (t: VTyp): Type :=\n  ExpTyping emptyE emptyE emptyE e t.\n\nDefinition runTest (e: Exp) (t: VTyp)\n (k: expTypingTest e t) (s: W) :=  projT1 (sigT_of_sigT2 \n (ExpEval emptyE emptyE emptyE e t k emptyFTyping emptyE emptyVTyping s)).\n\n\nEnd Abbrev.", "meta": {"author": "2xs", "repo": "dec", "sha": "79290ae2f92d437fe365a1b366a30e1eb2b83d19", "save_path": "github-repos/coq/2xs-dec", "path": "github-repos/coq/2xs-dec/dec-79290ae2f92d437fe365a1b366a30e1eb2b83d19/src/DEC1/AbbrevA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.22148315733699367}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Recognition of combined operations, addressing modes and conditions \n  during the [CSE] phase. *)\n\nRequire Import Coqlib.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Op.\nRequire Import RTL.\nRequire Import CSEdomain.\nRequire Import CombineOp.\n\n(** [CompCertX:test-compcert-param-memory] We create section [WITHMEM] and associated\n contexts to parameterize the proof over the memory model. *)\nSection WITHMEM.\nContext `{memory_model: Mem.MemoryModel}.\n\nSection COMBINE.\n\nVariable ge: genv.\nVariable sp: val.\nVariable m: mem.\nVariable get: valnum -> option rhs.\nVariable valu: valnum -> val.\nHypothesis get_sound: forall v rhs, get v = Some rhs -> rhs_eval_to valu ge sp m rhs (valu v).\n\nLemma get_op_sound:\n  forall v op vl, get v = Some (Op op vl) -> eval_operation ge sp op (map valu vl) m = Some (valu v).\nProof.\n  intros. exploit get_sound; eauto. intros REV; inv REV; auto. \nQed.\n\nLtac UseGetSound :=\n  match goal with\n  | [ H: get _ = Some _ |- _ ] =>\n      let x := fresh \"EQ\" in (generalize (get_op_sound _ _ _ H); intros x; simpl in x; FuncInv)\n  end.\n  \nLemma combine_compimm_ne_0_sound:\n  forall x cond args,\n  combine_compimm_ne_0 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Cne (valu x) (Vint Int.zero) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Cne (valu x) (Vint Int.zero).\nProof.\n  intros until args. functional induction (combine_compimm_ne_0 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H. \n  destruct (eval_condition cond (map valu args) m); simpl; auto. destruct b; auto.\n  (* of and *)\n  UseGetSound. rewrite <- H. \n  destruct v; simpl; auto. \nQed.\n\nLemma combine_compimm_eq_0_sound:\n  forall x cond args,\n  combine_compimm_eq_0 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Ceq (valu x) (Vint Int.zero) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Ceq (valu x) (Vint Int.zero).\nProof.\n  intros until args. functional induction (combine_compimm_eq_0 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  rewrite eval_negate_condition. \n  destruct (eval_condition c (map valu args) m); simpl; auto. destruct b; auto.\n  (* of and *)\n  UseGetSound. rewrite <- H. destruct v; auto. \nQed.\n\nLemma combine_compimm_eq_1_sound:\n  forall x cond args,\n  combine_compimm_eq_1 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Ceq (valu x) (Vint Int.one) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Ceq (valu x) (Vint Int.one).\nProof.\n  intros until args. functional induction (combine_compimm_eq_1 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H. \n  destruct (eval_condition cond (map valu args) m); simpl; auto. destruct b; auto.\nQed.\n\nLemma combine_compimm_ne_1_sound:\n  forall x cond args,\n  combine_compimm_ne_1 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Cne (valu x) (Vint Int.one) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Cne (valu x) (Vint Int.one).\nProof.\n  intros until args. functional induction (combine_compimm_ne_1 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H. \n  rewrite eval_negate_condition.\n  destruct (eval_condition c (map valu args) m); simpl; auto. destruct b; auto.\nQed.\n\nTheorem combine_cond_sound:\n  forall cond args cond' args',\n  combine_cond get cond args = Some(cond', args') ->\n  eval_condition cond' (map valu args') m = eval_condition cond (map valu args) m.\nProof.\n  intros. functional inversion H; subst.\n  (* compimm ne zero *)\n  simpl; eapply combine_compimm_ne_0_sound; eauto.\n  (* compimm ne one *)\n  simpl; eapply combine_compimm_ne_1_sound; eauto.\n  (* compimm eq zero *)\n  simpl; eapply combine_compimm_eq_0_sound; eauto.\n  (* compimm eq one *)\n  simpl; eapply combine_compimm_eq_1_sound; eauto.\n  (* compuimm ne zero *)\n  simpl; eapply combine_compimm_ne_0_sound; eauto.\n  (* compuimm ne one *)\n  simpl; eapply combine_compimm_ne_1_sound; eauto.\n  (* compuimm eq zero *)\n  simpl; eapply combine_compimm_eq_0_sound; eauto.\n  (* compuimm eq one *)\n  simpl; eapply combine_compimm_eq_1_sound; eauto.\nQed.\n\nTheorem combine_addr_sound:\n  forall addr args addr' args',\n  combine_addr get addr args = Some(addr', args') ->\n  eval_addressing ge sp addr' (map valu args') = eval_addressing ge sp addr (map valu args).\nProof.\n  intros. functional inversion H; subst.\n  (* indexed - lea *)\n  UseGetSound. simpl. eapply eval_offset_addressing_total; eauto. \nQed.\n\nTheorem combine_op_sound:\n  forall op args op' args',\n  combine_op get op args = Some(op', args') ->\n  eval_operation ge sp op' (map valu args') m = eval_operation ge sp op (map valu args) m.\nProof.\n  intros. functional inversion H; subst.\n(* lea-lea *)\n  simpl. eapply combine_addr_sound; eauto. \n(* andimm - andimm *)\n  UseGetSound; simpl. rewrite <- H0. rewrite Val.and_assoc. auto.\n(* orimm - orimm *)\n  UseGetSound; simpl. rewrite <- H0. rewrite Val.or_assoc. auto.\n(* xorimm - xorimm *)\n  UseGetSound; simpl. rewrite <- H0. rewrite Val.xor_assoc. auto.\n(* cmp *)\n  simpl. decEq; decEq. eapply combine_cond_sound; eauto.\nQed.\n\nEnd COMBINE.\n\nEnd WITHMEM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/compcert/ia32/CombineOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.22148315733699367}}
{"text": "Require Import String Omega List FunctionalExtensionality Ensembles\n        Sorting.Permutation\n        Computation ADT ADTRefinement ADTNotation BuildADTRefinements\n        QueryStructureSchema QueryStructure\n        EnsembleListEquivalence\n        QueryQSSpecs InsertQSSpecs EmptyQSSpecs DeleteQSSpecs\n        QueryStructureNotations\n        GeneralQueryRefinements GeneralInsertRefinements GeneralDeleteRefinements.\n\nLtac subst_strings :=\n  repeat match goal with\n           | [ H : string |- _ ] => subst H\n         end.\n\nLtac pose_string_ids :=\n  subst_strings;\n  repeat match goal with\n           | |- context [String ?R ?R'] =>\n             let str := fresh \"StringId\" in\n             set (String R R') as str in *\n         end.\n\nLemma Constructor_DropQSConstraints {MySchema} {Dom}\n: forall oldConstructor (d : Dom),\n    refine\n      (or' <- oldConstructor d;\n       {nr' |\n          DropQSConstraints_AbsR (qsSchema := MySchema) or' nr'})\n        (or' <- oldConstructor d;\n         ret (DropQSConstraints or')).\nProof.\n  unfold refine; intros; inversion_by computes_to_inv.\n  repeat econstructor; eauto.\nQed.\n\n(* Queries over an empty relation return empty lists. *)\nLemma refine_For_In_Empty  :\n  forall ResultT MySchema R bod,\n    refine (Query_For (@UnConstrQuery_In ResultT MySchema\n                                   (DropQSConstraints (QSEmptySpec MySchema))\n                                   R bod))\n           (ret []).\nProof.\n  intros; rewrite refine_For.\n  simplify with monad laws.\n  unfold In, DropQSConstraints, GetUnConstrRelation in *.\n  rewrite <- ith_Bounded_imap.\n  unfold QSEmptySpec; simpl rels.\n  rewrite Build_EmptyRelation_IsEmpty; simpl.\n  rewrite refine_pick_val with\n  (A := list (IndexedTuple)) (a := [])\n    by (repeat econstructor; eauto).\n  simplify with monad laws.\n  rewrite refine_pick_val with\n  (A := list ResultT) (a := []); reflexivity.\nQed.\n\nLemma Ensemble_List_Equivalence_Insert {A}\n: forall (a : A) (Ens : Ensemble A),\n    ~ In _ Ens a ->\n    refine {l |\n            EnsembleListEquivalence (EnsembleInsert a Ens) l}\n           (l <- { l |\n                   EnsembleListEquivalence Ens l};\n            ret (a :: l) ).\nProof.\n  unfold EnsembleListEquivalence, refine, In,\n  EnsembleInsert; intros.\n  inversion_by computes_to_inv; subst; econstructor.\n  simpl; intuition.\n  econstructor; eauto.\n  intuition; eapply H; eapply H3; eauto.\n  right; eapply H3; eauto.\n  right; eapply H3; eauto.\nQed.\n\nLemma refine_For_In_Insert\n: forall ResultT MySchema R or a tup bod,\n    ~ In _ (GetUnConstrRelation or R)\n      {| tupleIndex := a;\n         indexedTuple := tup |}\n    -> refine (Query_For\n                 (@UnConstrQuery_In\n                    ResultT MySchema\n                    (UpdateUnConstrRelation\n                       or R\n                       (EnsembleInsert {| tupleIndex := a;\n                                          indexedTuple := tup |}\n                                       (GetUnConstrRelation or R)))\n                    R bod))\n              (newResults <- bod tup;\n               origResults <- (Query_For\n                                 (@UnConstrQuery_In\n                                    ResultT MySchema or R bod));\n               {l | Permutation.Permutation (newResults ++ origResults) l}).\nProof.\n  intros; rewrite refine_For.\n  unfold UnConstrQuery_In,\n  GetUnConstrRelation at 1, UpdateUnConstrRelation.\n  rewrite ith_replace_BoundIndex_eq.\n  unfold QueryResultComp; simplify with monad laws.\n  rewrite Ensemble_List_Equivalence_Insert by eauto.\n  setoid_rewrite refineEquiv_bind_bind.\n  setoid_rewrite refineEquiv_bind_unit; simpl.\n  simplify with monad laws.\n  Transparent Query_For.\n  unfold Query_For.\n  repeat setoid_rewrite refineEquiv_bind_bind; simpl.\n  unfold refine; intros; inversion_by computes_to_inv.\n  econstructor; eauto.\n  econstructor; eauto.\n  econstructor; eauto.\n  econstructor.\n  rewrite Permutation.Permutation_app_head; eauto.\nQed.\n\nLtac start_honing_QueryStructure :=\n  pose_string_ids;\n  match goal with\n      |- context [@BuildADT (QueryStructure ?Rep) _ _ _ _] =>\n      hone representation using (@DropQSConstraints_AbsR Rep);\n        match goal with\n            |- context [Build_consDef (@Build_consSig ?Id _)\n                                      (@absConstructor _ _ _ _ _)] =>\n            hone constructor Id;\n              [ etransitivity;\n                [apply Constructor_DropQSConstraints |\n                 simplify with monad laws; finish honing]\n              | ]\n        end; pose_string_ids;\n        repeat (match goal with\n                  | |- context [Build_methDef (@Build_methSig ?Id _ _)\n                                              (absMethod _ (fun _ _ => Insert _ into _))] =>\n                    drop constraints from insert Id\n                  | |- context [Build_methDef (@Build_methSig ?Id _ _)\n                                              (absMethod _ (fun _ _ => Delete _ from _ where _))] =>\n                    drop constraints from delete Id\n                  | |- context [Build_methDef (@Build_methSig ?Id _ _)\n                                              (@absMethod _ _ _ _ _ _)] =>\n                    drop constraints from query Id\n                end; pose_string_ids)\n  end.\n\nLemma refine_trivial_if_then_else :\n  forall x,\n    refine\n      (If_Then_Else x (ret true) (ret false))\n      (ret x).\nProof.\n  destruct x; reflexivity.\nQed.\n\nTactic Notation \"start\" \"honing\" \"QueryStructure\" := start_honing_QueryStructure.\n", "meta": {"author": "JasonGross", "repo": "adt-synthesis", "sha": "30a5cd361af029f42864e103a5a604ffa9ee07a7", "save_path": "github-repos/coq/JasonGross-adt-synthesis", "path": "github-repos/coq/JasonGross-adt-synthesis/adt-synthesis-30a5cd361af029f42864e103a5a604ffa9ee07a7/src/QueryStructure/Refinements/GeneralQueryStructureRefinements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.22148315733699367}}
{"text": "Definition person := Type.\n\nCheck person.\n(* person : Type@{Top.1+1} *)\n\nDefinition out := Type.\n\nCheck out.\n(* out : Type@{Top.2+1} *)\n\nDefinition x : person. Admitted.\n\nInductive W : person -> out :=.\n\nDefinition y : W x. Admitted.\n\nCheck y.\n(* y : W x *)\n\nInductive F : person -> out :=.\n\nDefinition z : person. Admitted.\n\nCheck F z.\n\nDefinition x : F z := out.\n\n(* The term \"out\" has type \"Type@{Top.2+1}\" while it is expected to have type\n \"F z\". *)\n\n", "meta": {"author": "zunction", "repo": "Coqy", "sha": "a588f3b9000329eb1db25a4a81da8219bcb8f053", "save_path": "github-repos/coq/zunction-Coqy", "path": "github-repos/coq/zunction-Coqy/Coqy-a588f3b9000329eb1db25a4a81da8219bcb8f053/Reasoning/xrelation2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.22145540579507858}}
{"text": "\nLoad \"foo_prot2\".\n Section frame3.\n\n \n(*******************************************************************************)\n(* Theorem frame3ind : (phi3 0 1) ~ (phi3 1 0). \nProof. repeat unf. unfold phi3. simpl. unfold t1, t2. unfold q1_s, q2_s, q3_s; repeat unf.\n       unfold q11, q12, q13, q21, q22, q23, q31, q32.\n       repeat unfold admin, achecks.\n       ufcma_pi1 x1.  \nufcma_pi1 (x2t 0).\nufcma_pi2 (x2t 0).\nufcma_pi1 (x2ft 1). \nufcma_pi2 (x2ft 0). \nufcma_pi1 (x2t 1).\nufcma_pi2 (x2t 1).\nufcma_pi1 (x2ft 0).\nrepeat aply_andB_elm.  \nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nufcma_pi1 (x3tft 0 1).\nufcma_pi2 (x3tft 0 1).\nufcma_pi1 (x3ftt 1).\nufcma_pi1 (x3ftt 0).\nufcma_pi1 (x3ftft 0 1).\nufcma_pi2 (x3ftft 0 1).\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\n\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\nrew_mupbver;aply_bver; rew_hyps; try split; try reflexivity.\n(*\nassert((ifb (eqm (pi1 (pi2 (pi1 (x3tft 0 1)))) (e (b 0 7) 8))\n                     (ver (pk 1) (e (b 0 7) 8) (pi2 (pi2 (pi1 (x3tft 0 1)))))\n                     FAlse) ## (eqm (pi1 (pi2 (pi1 (x3tft 0 1)))) (e (b 0 7) 8))).\n\nAxiom eqbrmsg_bol :forall ( b1 b2: Bool) (n1 n2 n3 :nat ), (ifb (eqm  (Mvar n1)  (Mvar n2)) [[n3 := (Mvar n1)]]b1 b2) ## (ifb (eqm  (Mvar n1)(Mvar n2)) [[n3:= (Mvar n2)]] b1 b2). \npose proof(  eqbrmsg_bol (ver (pk 1) (e (b 0 7) 8) (Mvar 2) ) FAlse 0 1 2). simpl in H. \napply Forall_ELM_EVAL_B3 with (n:= 0) (b:= (pi1 (pi2 (pi1 (x3tft 0 1))))) in H. simpl in H.\n\napply Forall_ELM_EVAL_B3 with (n:= 1) (b:= (e (b 0 7) 8)) in H. simpl in H.\nrewrite correctness with (n:= 1) (t:= (e (b 0 7) 8)) in H. *)\n       apply IFBRANCH_M3 with (ml1:= phi0) (ml2:= phi0). simpl.\n       apply IFBRANCH_M2 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n    msg (pk 1, (e (b 0 7) 8, sign (sk 1) (e (b 0 7) 8)))]) (ml2:=  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n   msg (pk 1, (e (b 1 7) 8, sign (sk 1) (e (b 1 7) 8)))]).\n       simpl.\napply IFBRANCH_M1 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n    msg (pk 1, (e (b 0 7) 8, sign (sk 1) (e (b 0 7) 8)));\n    bol (eqm (to (x2t 0)) (V 2));\n    msg (pk 2, (e (b 1 11) 12, sign (sk 2) (e (b 1 11) 12)))]) (ml2:=  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n   msg (pk 1, (e (b 1 7) 8, sign (sk 1) (e (b 1 7) 8)));\n   bol (eqm (to (x2t 1)) (V 2));\n   msg (pk 2, (e (b 0 11) 12, sign (sk 2) (e (b 0 11) 12)))]). simpl.\nufcma_pi1 (x3tft 1 0).\nufcma_pi2 (x3tft 1 0).\napply IFBRANCH_M1 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n    msg (pk 1, (e (b 0 7) 8, sign (sk 1) (e (b 0 7) 8)));\n    bol (eqm (to (x2t 0)) (V 2));\n    msg (pk 2, (e (b 1 11) 12, sign (sk 2) (e (b 1 11) 12)));\n    bol (eqm (to (x3tft 0 1)) (pk 3))]) (ml2:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n   msg (pk 1, (e (b 1 7) 8, sign (sk 1) (e (b 1 7) 8)));\n   bol (eqm (to (x2t 1)) (V 2));\n   msg (pk 2, (e (b 0 11) 12, sign (sk 2) (e (b 0 11) 12)));\n   bol (eqm (to (x3tft 1 0)) (pk 3))]). simpl.\napply IFBRANCH_M1 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n    msg (pk 1, (e (b 0 7) 8, sign (sk 1) (e (b 0 7) 8)));\n    bol (eqm (to (x2t 0)) (V 2));\n    msg (pk 2, (e (b 1 11) 12, sign (sk 2) (e (b 1 11) 12)));\n    bol (eqm (to (x3tft 0 1)) (pk 3));\n    bol\n      (ifb (eqm (pi1 (pi2 (pi1 (x3tft 0 1)))) (e (b 0 7) 8))\n         (ver (pk 1) (e (b 0 7) 8) (pi2 (pi2 (pi1 (x3tft 0 1))))) FAlse)]) (ml2:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1));\n   msg (pk 1, (e (b 1 7) 8, sign (sk 1) (e (b 1 7) 8)));\n   bol (eqm (to (x2t 1)) (V 2));\n   msg (pk 2, (e (b 0 11) 12, sign (sk 2) (e (b 0 11) 12)));\n   bol (eqm (to (x3tft 1 0)) (pk 3));\n   bol\n     (ifb (eqm (pi1 (pi2 (pi1 (x3tft 1 0)))) (e (b 1 7) 8))\n        (ver (pk 1) (e (b 1 7) 8) (pi2 (pi2 (pi1 (x3tft 1 0))))) FAlse)]). simpl. \naply_blindness 3 8 12 0 1 (b 0 7) (b 1 11)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] .\naplyprojn 1 16 H; try split; try reflexivity.\nrep_commits 0 1 11 21 7 22 fr1 fr2 temp H H0.\nrename H0 into H.\nappconst H. \nx1checks x1 x1 H. \nfunapp_vtrm 1 0 1 7 8 H.\nx1checks (x2t 0 ) (x2t 1) H.\nfunapp_vtrm 2 1 0 11 12 H.\nx1checks (x3tft 0 1) (x3tft 1 0) H.\nadminchecks (x3tft 0 1) (x3tft 1 0) H.\nver_suc 1 (pi1 (x3tft 0 1)) (e (b 0 7) 8) (pi1 (x3tft 1 0)) (e (b 1 7) 8) H.\nver_suc 2 (pi2 (x3tft 0 1)) (e (b 1 11) 12) (pi2 (x3tft 1 0)) (e (b 0 11) 12) H.\nrestrsublis H. \n(** subgoal 2 *)\n \nsimpl.\naply_blindness 3 8 12 0 1 (b 0 7) (b 1 11)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] .\naplyprojn 1 16 H; try split; try reflexivity.\nrep_commits 0 1 11 21 7 22 fr1 fr2 temp H H0.\nrename H0 into H.\nappconst H. \nx1checks x1 x1 H. \nfunapp_vtrm 1 0 1 7 8 H.\nx1checks (x2t 0 ) (x2t 1) H.\nfunapp_vtrm 2 1 0 11 12 H.\nx1checks (x3tft 0 1) (x3tft 1 0) H.\nadminchecks (x3tft 0 1) (x3tft 1 0) H.\n ver_suc 1 (pi1 (x3tft 0 1)) (e (b 0 7) 8) (pi1 (x3tft 1 0)) (e (b 1 7) 8) H.\nver_suc 2 (pi2 (x3tft 0 1)) (e (b 1 11) 12) (pi2 (x3tft 1 0)) (e (b 0 11) 12) H.\n\nrestrsublis H.\n(** subgoal 3*)\nsimpl.\nsimpl.\naply_blindness 3 8 12 0 1 (b 0 7) (b 1 11)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] .\naplyprojn 1 16 H; try split; try reflexivity.\nrep_commits 0 1 11 21 7 22 fr1 fr2 temp H H0.\nrename H0 into H.\nappconst H. \nx1checks x1 x1 H. \nfunapp_vtrm 1 0 1 7 8 H.\nx1checks (x2t 0 ) (x2t 1) H.\nfunapp_vtrm 2 1 0 11 12 H.\nx1checks (x3tft 0 1) (x3tft 1 0) H.\nadminchecks (x3tft 0 1) (x3tft 1 0) H.\n ver_suc 1 (pi1 (x3tft 0 1)) (e (b 0 7) 8) (pi1 (x3tft 1 0)) (e (b 1 7) 8) H.\nver_suc 2 (pi2 (x3tft 0 1)) (e (b 1 11) 12) (pi2 (x3tft 1 0)) (e (b 0 11) 12) H.\nrestrsublis H.\n(** subgola 4 *)\nsimpl.\naply_blindness 3 8 12 0 1 (b 0 7) (b 1 11)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] .\naplyprojn 1 16 H; try split; try reflexivity.\nrep_commits 0 1 11 21 7 22 fr1 fr2 temp H H0.\nrename H0 into H.\nappconst H. \nx1checks x1 x1 H. \nfunapp_vtrm 1 0 1 7 8 H.\nx1checks (x2t 0 ) (x2t 1) H.\nfunapp_vtrm 2 1 0 11 12 H.\nx1checks (x3tft 0 1) (x3tft 1 0) H.\nadminchecks (x3tft 0 1) (x3tft 1 0) H.\nrestrsublis H.\n(** subgoal *)\n\nsimpl.\naply_blindness 3 8 12 0 1 (b 0 7) (b 1 7)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] .\naplyprojn 2 15 H; try split; try reflexivity.\nappconst H. \nx1checks x1 x1 H. \nfunapp_vtrm 1 0 1 7 8 H.\nx1checks (x2t 0 ) (x2t 1) H.\nrestrsublis H.\n(** subgoal *)\nsimpl.\nufcma_pi1 (x3ftft 1 0).\nufcma_pi2 (x3ftft 1 0).\napply IFBRANCH_M3 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1))]) (ml2:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                             msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1))]).\nsimpl.\napply IFBRANCH_M2 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1)); \n    bol (eqm (to x1) (V 2));\n    msg (pk 2, (e (b 1 9) 10, sign (sk 2) (e (b 1 9) 10)))]) (ml2:=  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1)); \n   bol (eqm (to x1) (V 2));\n   msg (pk 2, (e (b 0 9) 10, sign (sk 2) (e (b 0 9) 10)))]).\nsimpl.\napply IFBRANCH_M1 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1)); \n    bol (eqm (to x1) (V 2));\n    msg (pk 2, (e (b 1 9) 10, sign (sk 2) (e (b 1 9) 10)));\n    bol (eqm (to (x2ft 1)) (V 1));\n    msg (pk 1, (e (b 0 13) 14, sign (sk 1) (e (b 0 13) 14)))]) (ml2:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1)); \n   bol (eqm (to x1) (V 2));\n   msg (pk 2, (e (b 0 9) 10, sign (sk 2) (e (b 0 9) 10)));\n   bol (eqm (to (x2ft 0)) (V 1));\n   msg (pk 1, (e (b 1 13) 14, sign (sk 1) (e (b 1 13) 14)))]).\nsimpl. \napply IFBRANCH_M1 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1)); \n    bol (eqm (to x1) (V 2));\n    msg (pk 2, (e (b 1 9) 10, sign (sk 2) (e (b 1 9) 10)));\n    bol (eqm (to (x2ft 1)) (V 1));\n    msg (pk 1, (e (b 0 13) 14, sign (sk 1) (e (b 0 13) 14)));\n    bol (eqm (to (x3ftft 0 1)) (pk 3))]) (ml2:=  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1)); \n   bol (eqm (to x1) (V 2));\n   msg (pk 2, (e (b 0 9) 10, sign (sk 2) (e (b 0 9) 10)));\n   bol (eqm (to (x2ft 0)) (V 1));\n   msg (pk 1, (e (b 1 13) 14, sign (sk 1) (e (b 1 13) 14)));\n   bol (eqm (to (x3ftft 1 0)) (pk 3))]).\nsimpl.\napply IFBRANCH_M1 with (ml1:= [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n    msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1)); \n    bol (eqm (to x1) (V 2));\n    msg (pk 2, (e (b 1 9) 10, sign (sk 2) (e (b 1 9) 10)));\n    bol (eqm (to (x2ft 1)) (V 1));\n    msg (pk 1, (e (b 0 13) 14, sign (sk 1) (e (b 0 13) 14)));\n    bol (eqm (to (x3ftft 0 1)) (pk 3));\n    bol\n      (ifb (eqm (pi1 (pi2 (pi1 (x3ftft 0 1)))) (e (b 0 13) 14))\n         (ver (pk 1) (e (b 0 13) 14) (pi2 (pi2 (pi1 (x3ftft 0 1))))) FAlse)]) (ml2:=  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n   msg (nonce 4); msg (pk 5); bol (eqm (to x1) (V 1)); \n   bol (eqm (to x1) (V 2));\n   msg (pk 2, (e (b 0 9) 10, sign (sk 2) (e (b 0 9) 10)));\n   bol (eqm (to (x2ft 0)) (V 1));\n   msg (pk 1, (e (b 1 13) 14, sign (sk 1) (e (b 1 13) 14)));\n   bol (eqm (to (x3ftft 1 0)) (pk 3));\n   bol\n     (ifb (eqm (pi1 (pi2 (pi1 (x3ftft 1 0)))) (e (b 1 13) 14))\n          (ver (pk 1) (e (b 1 13) 14) (pi2 (pi2 (pi1 (x3ftft 1 0))))) FAlse)]); try repeat\n  (aply_blindness 3 10 14 0 1 (b 1 9) (b 0 13)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] ; simpl;\naplyprojn 1 16 H; try split; try reflexivity;\nrep_commits 1 0 13 21 9 22 fr1 fr2 temp H H0;\nrename H0 into H;\nappconst H;\nx1checks x1 x1 H;\nfunapp_vtrm 2 1 0 9 10 H;\nfunapp_vtrm 1 0 1 13 14 H;\nx1checks (x2ft 1 ) (x2ft 0) H;\nx1checks (x3ftft 0 1) (x3ftft 1 0) H;\nadminchecks (x3ftft 0 1) (x3ftft 1 0) H;\nver_suc 1 (pi1 (x3ftft 0 1)) (e (b 0 13) 14) (pi1 (x3ftft 1 0)) (e (b 1 13) 14) H;\nver_suc 2 (pi2 (x3ftft 0 1)) (e (b 1 9) 10) (pi2 (x3ftft 1 0)) (e (b 0 9) 10) H;\nrestrsublis H). \n\n(** subgoal *)\n  (aply_blindness 3 10 14 0 1 (b 1 9) (b 0 13)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] ; simpl;\naplyprojn 1 16 H; try split; try reflexivity;\nrep_commits 1 0 13 21 9 22 fr1 fr2 temp H H0;\nrename H0 into H;\nappconst H;\nx1checks x1 x1 H;\nfunapp_vtrm 2 1 0 9 10 H;\nfunapp_vtrm 1 0 1 13 14 H;\nx1checks (x2ft 1 ) (x2ft 0) H;\nx1checks (x3ftft 0 1) (x3ftft 1 0) H;\nadminchecks (x3ftft 0 1) (x3ftft 1 0) H;\nver_suc 1 (pi1 (x3ftft 0 1)) (e (b 0 13) 14) (pi1 (x3ftft 1 0)) (e (b 1 13) 14) H;\nver_suc 2 (pi2 (x3ftft 0 1)) (e (b 1 9) 10) (pi2 (x3ftft 1 0)) (e (b 0 9) 10) H;\nrestrsublis H). try  (aply_blindness 3 10 14 0 1 (b 1 9) (b 0 13)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] ; simpl;\naplyprojn 1 16 H; try split; try reflexivity;\nrep_commits 1 0 13 21 9 22 fr1 fr2 temp H H0;\nrename H0 into H;\nappconst H;\nx1checks x1 x1 H;\nfunapp_vtrm 2 1 0 9 10 H;\nfunapp_vtrm 1 0 1 13 14 H;\nx1checks (x2ft 1 ) (x2ft 0) H;\nx1checks (x3ftft 0 1) (x3ftft 1 0) H;\nadminchecks (x3ftft 0 1) (x3ftft 1 0) H;\nver_suc 1 (pi1 (x3ftft 0 1)) (e (b 0 13) 14) (pi1 (x3ftft 1 0)) (e (b 1 13) 14) H;\nver_suc 2 (pi2 (x3ftft 0 1)) (e (b 1 9) 10) (pi2 (x3ftft 1 0)) (e (b 0 9) 10) H;\nrestrsublis H).\n\n   (aply_blindness 3 10 14 0 1 (b 1 9) (b 0 13)  ((Mvar 0), (Mvar 1)) ((Mvar 0), (Mvar 1))  [msg (pk 0); msg (pk 1); msg (pk 2); msg (pk 3); \n                                                                                       msg (nonce 4); msg (pk 5); msg (sk 1); msg (sk 2); msg (sk 3) ] ; simpl;\naplyprojn 1 16 H; try split; try reflexivity;\nrep_commits 1 0 13 21 9 22 fr1 fr2 temp H H0;\nrename H0 into H;\nappconst H;\nx1checks x1 x1 H;\nfunapp_vtrm 2 1 0 9 10 H;\nfunapp_vtrm 1 0 1 13 14 H;\nx1checks (x2ft 1 ) (x2ft 0) H;\nx1checks (x3ftft 0 1) (x3ftft 1 0) H;\nadminchecks (x3ftft 0 1) (x3ftft 1 0) H;\nver_suc 1 (pi1 (x3ftft 0 1)) (e (b 0 13) 14) (pi1 (x3ftft 1 0)) (e (b 1 13) 14) H;\nver_suc 2 (pi2 (x3ftft 0 1)) (e (b 1 9) 10) (pi2 (x3ftft 1 0)) (e (b 0 9) 10) H;\nrestrsublis H). reflexivity.\nQed. *)\nEnd frame3.", "meta": {"author": "ajayeeralla", "repo": "vote_privacy_proofs", "sha": "87a689040f7c4f4cb8bb0434efcef0fa0bb01a96", "save_path": "github-repos/coq/ajayeeralla-vote_privacy_proofs", "path": "github-repos/coq/ajayeeralla-vote_privacy_proofs/vote_privacy_proofs-87a689040f7c4f4cb8bb0434efcef0fa0bb01a96/src/.other/foo/frame3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.221455018583502}}
{"text": "Require Import include_frm.\nRequire Import math_auto.\nRequire Import ucos_include.\nRequire Import os_ucos_h.\nRequire Import OSTimeDlyPure.\n\nRequire Import OSQPostPure.\nLocal Open Scope code_scope.\n\nImport DeprecatedTactic.\n\n(* Local Ltac mytac := simpljoin;\n *     match goal with\n *       | |- _ /\\ _ =>splits\n *       | _ => idtac\n *     end; subst. *)\n\n(* TODO: move to mathlib *)\nLemma val_inj_eq\n     : forall i0 a: int32,\n       val_inj\n         (notint\n            (val_inj\n               (if Int.eq i0  a\n                then Some (Vint32 Int.one)\n                else Some (Vint32 Int.zero)))) = Vint32 Int.zero \\/\n       val_inj\n         (notint\n            (val_inj\n               (if Int.eq i0  a\n                then Some (Vint32 Int.one)\n                else Some (Vint32 Int.zero)))) = Vnull ->\n       i0 = a.\nProof.\n  intros.\n  destruct H; intros.\n  int auto.\n  apply unsigned_inj; auto.\n  int auto.\nQed.\n\n(* TODO: move to mathlib *)\nLemma ecbjoin_sig_join'\n     : forall (x x1 v'35 x0 : EcbMod.map) (v'61 : block) \n         v3,\n       EcbMod.join x x1 v'35 ->\n       EcbMod.join x0 (EcbMod.sig (v'61, Int.zero) (v3, nil)) x1 ->\n       exists y,\n       EcbMod.join x0 x y /\\\n       EcbMod.join y (EcbMod.sig (v'61, Int.zero) (v3, nil)) v'35.\nProof.\n  intros.\n\n  set ( EcbMod.join_assoc_r H0 H).\n  mytac.\n  exists x2.\n  split; auto.\n  apply EcbMod.join_comm in H1.\n  auto.\nQed.\n\nLemma joinsig_join_ex_my:\n  forall x1 v1 ma mb mab m,\n    EcbMod.joinsig x1 v1 mab m ->\n    EcbMod.join ma mb mab ->\n    exists mm, EcbMod.joinsig x1 v1 ma mm /\\ EcbMod.join mm mb m.\nProof.\n  intros x1 v1 ma mb mab m.\n  unfold EcbMod.joinsig.\n  intros F1 F2.\n  apply EcbMod.join_assoc_spec_1 with (mab:=mab); trivial.\nQed.\n\nLemma joinsig_join_ex:\n  forall x0 x x1 t x4 x5,\n    EcbMod.joinsig x0 x x1 t ->\n    EcbMod.join x4 x5 x1 ->\n    exists y,  EcbMod.joinsig x0 x x4 y /\\  EcbMod.join y x5 t.\nProof.\n  intros x0 x x1 t x4 x5.\n  apply joinsig_join_ex_my with (mab:=x1).\nQed.  \n\n\nLemma get_last_prop:\n  forall (l : list EventCtr)  x v y,\n    l <> nil -> \n    (get_last_ptr ((x, v) :: l)  =   y <->\n     get_last_ptr  l =  y).\nProof.\n  destruct l.\n  intros.\n  tryfalse.\n  intros.\n  unfolds get_last_ptr.\n  simpl.\n  destruct l; splits;auto.\nQed.\n\n\nLemma ecblist_p_decompose :\n  forall  y1 z1  x y2 z2 t z ,\n    length y1 = length y2 ->\n    ECBList_P x Vnull (y1++z1) (y2++z2) t z ->\n    exists x1 t1 t2,\n      ECBList_P x x1 y1 y2 t1 z /\\ ECBList_P x1 Vnull z1 z2 t2 z /\\\n      EcbMod.join t1 t2 t /\\  (get_last_ptr y1 = None \\/ get_last_ptr y1  = Some x1).\nProof.\n  inductions y1; inductions y2.\n  simpl.\n  intros.\n  do 3 eexists; splits; eauto.\n  eapply EcbMod.join_emp; eauto.\n  intros.\n  simpl in H.\n  tryfalse.\n  intros.\n  simpl in H; tryfalse.\n  intros.\n  simpl in H.\n  inverts H.\n  simpl in H0.\n  mytac.\n  destruct a.\n  mytac.\n  lets Hx : IHy1 H2 H4.\n  mytac.\n  lets Hex : joinsig_join_ex H1 H7.\n  mytac.\n  do 3 eexists.\n  splits.\n  simpl.\n  eexists; splits; eauto.\n  do 3 eexists; splits.\n  eauto.\n  2: eauto.\n  3: eauto.\n  2 : eauto.\n  eauto.\n  eauto.\n  assert (y1 = nil \\/ y1 <> nil) by tauto.\n  destruct H11.\n  subst y1.  \n  right.\n  simpl in H2.\n  apply eq_sym in H2.\n  apply length_zero_nil in H2.\n  subst y2.\n  simpl in H5.\n  mytac.\n  unfolds.\n  simpl.\n  auto.\n  destruct H8.\n  left.\n  eapply  get_last_prop in H11.\n  eapply H11; eauto.\n  eapply  get_last_prop in H11.\n  right.\n  eapply H11; eauto.\nQed.  \n\n\nLemma  ecb_joinsig_ex_split:\n  forall x x0 x1 ecbls x3 x4,\n    EcbMod.joinsig x x0 x1 ecbls ->\n    EcbMod.join x3 x4 x1 ->\n    exists y, EcbMod.joinsig x x0 x3 y /\\ EcbMod.join y x4 ecbls.\nProof.\n  intros.\n  exists (EcbMod.minus ecbls x4).\n  split.\n  unfolds; intro.\n  pose proof H a.\n  pose proof H0 a.\n  destruct(tidspec.beq x a) eqn:eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some.\n  rewrite EcbMod.get_sig_some in H1.\n  rewrite EcbMod.minus_sem.\n  destruct( EcbMod.get x3 a);\n  destruct( EcbMod.get x4 a);\n  destruct( EcbMod.get x1 a);\n  destruct( EcbMod.get ecbls a);\n  tryfalse; substs; auto.\n  apply tidspec.beq_false_neq in eq1.\n  rewrite EcbMod.get_sig_none; auto.\n  rewrite EcbMod.get_sig_none in H1; auto.\n  rewrite EcbMod.minus_sem.\n  destruct( EcbMod.get x3 a);\n  destruct( EcbMod.get x4 a);\n  destruct( EcbMod.get x1 a);\n  destruct( EcbMod.get ecbls a);\n  tryfalse; substs; auto.\n\n  intro.\n  pose proof H a.\n  pose proof H0 a.\n  rewrite EcbMod.minus_sem.\n  destruct(tidspec.beq x a) eqn:eq1.\n  pose proof tidspec.beq_true_eq _ _ eq1; substs.\n  rewrite EcbMod.get_sig_some in H1.\n  destruct( EcbMod.get x3 a);\n  destruct( EcbMod.get x4 a);\n  destruct( EcbMod.get x1 a);\n  destruct( EcbMod.get ecbls a);\n  tryfalse; substs; auto.\n  \n  apply tidspec.beq_false_neq in eq1.\n  rewrite EcbMod.get_sig_none in H1; auto.\n  destruct( EcbMod.get x3 a);\n  destruct( EcbMod.get x4 a);\n  destruct( EcbMod.get x1 a);\n  destruct( EcbMod.get ecbls a);\n  tryfalse; substs; auto.\nQed.\n\nLemma ecblist_p_decompose':\n  forall l1 ll1 l2 ll2 head ecbls tcbls,\n    length l1 = length ll1 ->\n    ECBList_P head Vnull\n              (l1++\n                 l2) (ll1 ++ ll2) ecbls tcbls ->\n    exists ecbls1 ecbls2 x,\n      ECBList_P head x l1 ll1 ecbls1 tcbls /\\\n      ECBList_P x Vnull l2 ll2 ecbls2 tcbls /\\\n      EcbMod.join ecbls1 ecbls2 ecbls.\nProof.\n  inductions l1.\n  simpl.\n  intros.\n  destruct ll1.\n  simpl in H0.\n  do 3 eexists;splits; eauto.\n  eapply EcbMod.join_emp; auto.\n  simpl in H.\n  tryfalse.\n  intros.\n  destruct ll1.\n  simpl in H.\n  tryfalse.\n  simpl in H.\n  assert (length l1 = length ll1) by omega.\n  simpl in H0.\n  mytac.\n  destruct a.\n  mytac.\n  lets Hxs : IHl1 H1 H5.\n  mytac.\n  lets Hsx :     ecb_joinsig_ex_split H3 H8.\n  mytac.\n  exists x6 x4 x5.\n  simpl.\n  splits.\n  eexists.\n  splits; eauto.\n  do 3 eexists.\n  splits; eauto.\n  auto.\n  auto.\nQed.\n\n(* similar to eventtype_neq_q in common.v *)\nLocal Open Scope list_scope.\nLocal Open Scope int_scope.\nLemma eventtype_neq_mbox:\n  forall v'38 v'21 i1 i0 i2 x2 x3 v'42 v'40 v'22 v'23 v'41 v'24 v'34 v'35 v'49 s P v'43 v'45 v'44 v'46,\n    length v'21 = length v'23-> \n    ECBList_P v'38 Vnull\n              (v'21 ++\n                    ((Vint32 i1 :: Vint32 i0 :: Vint32 i2 :: x2 :: x3 :: v'42 :: nil,\n                      v'40) :: nil) ++ v'22) (v'23 ++ (v'41 :: nil) ++ v'24) v'34 v'35 ->\n    ECBList_P v'38 (Vptr (v'49, Int.zero)) v'21 v'23 v'43 v'35 ->\n    EcbMod.join v'43 v'45 v'34 ->\n    EcbMod.joinsig (v'49, Int.zero) v'46 v'44 v'45 ->\n    false = Int.eq i1 ($  OS_EVENT_TYPE_MBOX) ->\n    s|= AEventData\n     (Vint32 i1 :: Vint32 i0 :: Vint32 i2 :: x2 :: x3 :: v'42 :: nil) v'41 ** P ->\n    s |= AEventData\n      (Vint32 i1 :: Vint32 i0 :: Vint32 i2 :: x2 :: x3 :: v'42 :: nil) v'41 **\n      [|~ exists x z, EcbMod.get v'34 (v'49,Int.zero) = Some (absmbox x, z) |] ** P.\nProof.\n  intros.\n\n  apply ecblist_p_decompose' in H0;auto.\n  mytac.\n \n  assert (x1 = Vptr (v'49, Int.zero) /\\ x = v'43).\n  eapply ecblist_p_eqh;eauto.\n  instantiate (1:=v'34).\n  eapply EcbMod.join_sub_l;eauto.\n  eapply EcbMod.join_sub_l;eauto.\n  destruct H8;subst.\n  destruct v'41.\n  Focus 3.\n  unfold AEventData in *.\n  sep normal in H5.\n  sep split in H5.\n  unfolds in H8;simpl in H8.\n  inverts H8.\n  rewrite Int.eq_true in H4;tryfalse.\n  sep auto.\n  simpl in H6.\n  simpljoin.\n  destruct x1.\n  destruct e;tryfalse.\n  simpljoin.\n  intro.\n  simpljoin.\n  inverts H6.\n  lets Hx:EcbMod.join_joinsig_get H7 H10.\n  rewrite H16 in Hx.\n  tryfalse.\n  sep auto.\n  simpl in H6.\n  mytac.\n  destruct x1.\n  destruct e;tryfalse.\n  mytac.\n  intro.\n  mytac.\n  inverts H6.\n  lets Hx:EcbMod.join_joinsig_get H7 H10.\n  rewrite H11 in Hx.\n  tryfalse.\n  sep auto.\n  simpl in H6.\n  mytac.\n  destruct x1.\n  destruct e;tryfalse.\n\n  mytac.\n  intro.\n  mytac.\n  inverts H6.\n  lets Hx:EcbMod.join_joinsig_get H7 H10.\n  rewrite H14 in Hx.\n  tryfalse.\nQed.\n\n\nLemma eventtype_neq_mbox':\n  forall v'38 v'21 i1 i0 i2 x2 x3 v'42 v'40 v'22 v'23 v'41 v'24 v'34 v'35 v'49 s P v'43 v'45 v'44 v'46,\n    length v'21 = length v'23-> \n    ECBList_P v'38 Vnull\n              (v'21 ++\n                    ((Vint32 i1 :: Vint32 i0 :: Vint32 i2 :: x2 :: x3 :: v'42 :: nil,\n                      v'40) :: nil) ++ v'22) (v'23 ++ (v'41 :: nil) ++ v'24) v'34 v'35 ->\n    ECBList_P v'38 (Vptr (v'49, Int.zero)) v'21 v'23 v'43 v'35 ->\n    EcbMod.join v'43 v'45 v'34 ->\n    EcbMod.joinsig (v'49, Int.zero) v'46 v'44 v'45 ->\n    false = Int.eq i1 ($  OS_EVENT_TYPE_MBOX) ->\n    s|= AEventData\n     (Vint32 i1 :: Vint32 i0 :: Vint32 i2 :: x2 :: x3 :: v'42 :: nil) v'41 ** P ->\n    s |= AEventData\n      (Vint32 i1 :: Vint32 i0 :: Vint32 i2 :: x2 :: x3 :: v'42 :: nil) v'41 **\n      [| exists d, EcbMod.get v'34 (v'49,Int.zero) = Some d /\\ (~exists x z, d= (absmbox x, z)) |] ** P.\n  intros.\n  lets aaa : eventtype_neq_mbox H5; eauto.\n  clear H5.\n  sep auto.\n  eexists.\n  assert ( EcbMod.get v'34 (v'49, Int.zero) = Some v'46).\n  eapply EcbMod.join_get_get_r.\n  eauto.\n  eapply EcbMod.join_get_get_l.\n  eauto.\n  eapply EcbMod.get_a_sig_a.\n  apply CltEnvMod.beq_refl.\n  split.\n  eauto.\n  intro.\n  rewrite H6 in H5.\n  apply H5.\n  inversion H7.\n  inversion H8.\n  exists x x0.\n  rewrite H9.\n  auto.\nQed.  \nLemma length8_ex:\n  forall v'40 :vallist,\n    length v'40 = ∘OS_EVENT_TBL_SIZE ->\n    exists v1 v2 v3 v4 v5 v6 v7 v8,\n      v'40 = v1::v2::v3::v4::v5::v6::v7::v8::nil.\nProof.\n  introv Hlen.\n  try do 8  (destruct v'40; simpl in Hlen; tryfalse).\n  do 8 eexists; eauto.\n  assert (length v'40 = 0)%nat.\n  unfold Pos.to_nat in Hlen.\n  simpl in Hlen.\n  inverts Hlen.\n  auto.\n  assert (v'40 = nil).\n  destruct v'40.\n  auto.\n  simpl in H; tryfalse.\n  subst.\n  eauto.\nQed.\n\nLemma ecblist_ecbmod_get_aux_mbox :\n  forall v'61 i6  x4 x8 v'58 v'42  \n         v'63 x20 v'37 v'35 v'36 v'38,\n    array_type_vallist_match Int8u v'58->\n    RH_CurTCB v'38 v'36 ->\n    length v'58 = ∘OS_EVENT_TBL_SIZE ->\n    RH_TCBList_ECBList_P v'35 v'36 v'38 ->\n    RL_Tbl_Grp_P v'58 (V$0) ->\n    ECBList_P (Vptr (v'61, Int.zero)) Vnull\n              (\n                   ((V$OS_EVENT_TYPE_MBOX\n                      :: V$0 :: Vint32 i6 :: v'63 :: x4 :: x8 :: nil,\n                     v'58) :: nil) ++ v'42)\n                                       ((DMbox x20 :: nil) ++ v'37) v'35 v'36 ->\n    exists msgls,\n      EcbMod.get v'35 (v'61, Int.zero) = Some (absmbox msgls , nil)\n    /\\ exists vv,  EcbMod.join vv  (EcbMod.sig (v'61, Int.zero) (absmbox msgls, nil)) v'35 /\\ECBList_P x8 Vnull v'42 v'37  vv  v'36.\nProof.\n  introv  Harr Hcur Hrl Htcb Hre Hep.\n  unfolds in Hre.\n  assert (forall n, (0 <= n < 8)%nat  ->  nth_val n v'58 = Some (Vint32 ($ 0))).\n  intros.\n  lets Hex : n07_arr_len_ex H  Harr Hrl.\n  destruct Hex as (vh & Hnth & Hneq).\n  assert (V$0 = V$0) as Hasrt by auto.\n  lets Hres : Hre H Hnth Hasrt.\n  destruct Hres as (Hrs1 & Hrs2).\n  destruct Hrs1 as (Hrs11 & Hrs22).\n  rewrite Int.and_zero_l in Hrs11.\n  assert (vh = $ 0) .\n  apply Hrs11.\n  auto.\n  subst vh.\n  auto.\n  simpl in Hep.\n  destruct Hep as (qid & Heq & Heb & Hex).\n  destruct Hex as (absmq & mqls' & v' & Hv & Hej & Hmt & Hlp).\n  destruct absmq.\n  destruct e; tryfalse.\n  usimpl Hv.\n  inverts Heq.\n  destruct Hmt as (Hm1 & Hm2 ). (* & Hm3 & Hm4). *)\n  mytac.\n  exists m.\n  assert (w = nil \\/ w <> nil) by tauto.\n  destruct H0 as [Hnil | Hnnil].\n  Focus 2.\n  unfolds in Hcur.\n  unfolds in Htcb.\n  destruct Htcb as (Htcb1&Htcb2&Htcb3&Htcb4).\n  lets Hj : ecbmod_joinsig_get Hej.\n  lets Hea : qwaitset_notnil_ex Hnnil.\n  destruct Hea as (tid & Hin).\n  assert ( EcbMod.get v'35 (v'61, Int.zero) = Some (absmbox m, w) /\\ In tid w) by (split; auto).\n  destruct Htcb3 as (Htb & Htb2).\n  lets Hjj : Htb H0.\n  destruct Hjj as (prio & m0 & n & Htcg).\n  unfolds in Heb.\n  destruct Heb as (Heb1 & Heb2 & _).\n  unfolds  in Heb2.\n  destruct Heb2 as (Heba & Hebb & Hebc & Hebd).\n  lets Hebs : Hebc Htcg.\n  lets Hbb : prioinq_exists Hebs.\n  destruct Hbb as (n0 & Hnn & Hnth).\n  lets Hfs : H Hnn.\n  tryfalse.\n  subst w.\n  split.\n \n  eapply ecbmod_joinsig_get; eauto.\n  eexists; splits; eauto.\n \n  eapply  ecbmod_joinsig_sig; eauto.\nQed.\n\n\nLemma ecblist_ecbmod_get_mbox :\n  forall v'61 i6  x4 x8 v'58 v'42 v'21 v'63 x20 v'37 v'35 v'36 v'38,\n    length v'21 = O  ->\n    array_type_vallist_match Int8u v'58->\n    RH_CurTCB v'38 v'36 ->\n    length v'58 = ∘OS_EVENT_TBL_SIZE ->\n    RH_TCBList_ECBList_P v'35 v'36 v'38 ->\n    RL_Tbl_Grp_P v'58 (V$0) ->\n    ECBList_P (Vptr (v'61, Int.zero)) Vnull\n              (nil ++\n                   ((V$OS_EVENT_TYPE_MBOX\n                      :: V$0 :: Vint32 i6 :: v'63 :: x4 :: x8 :: nil,\n                     v'58) :: nil) ++ v'42)\n              (v'21 ++\n                    (DMbox x20 :: nil) ++ v'37) v'35 v'36 ->\n    exists msgls,\n      EcbMod.get v'35 (v'61, Int.zero) = Some (absmbox msgls, nil)\n      /\\ exists vv,  EcbMod.join vv  (EcbMod.sig (v'61, Int.zero) (absmbox msgls , nil)) v'35 /\\ECBList_P x8 Vnull v'42 v'37  vv  v'36.\nProof.\n  introv Hlen Harr Hcur Hrl Htcb Hre Hep.\n  destruct v'21.\n  2 : simpl in Hlen; tryfalse.\n  rewrite app_nil_l in Hep.\n  rewrite app_nil_l in Hep.\n  eapply ecblist_ecbmod_get_aux_mbox;eauto.\nQed.\n\n(* the following two lemmas are in OSQDelPure.v *)\n\n(* in common.v there's a lemma have the same name. but they have small differences *)\nLemma ecblist_p_decompose'' :\n  forall  y1 z1  x y2 z2 t z ,\n    length y1 = length y2 ->\n    ECBList_P x Vnull (y1++z1) (y2++z2) t z ->\n    exists x1 t1 t2,\n      ECBList_P x x1 y1 y2 t1 z /\\ ECBList_P x1 Vnull z1 z2 t2 z /\\\n      EcbMod.join t1 t2 t /\\  (get_last_ptr y1 = None \\/ get_last_ptr y1  = Some x1).\nProof.\n  inductions y1; inductions y2.\n  simpl.\n  intros.\n  do 3 eexists; splits; eauto.\n  eapply EcbMod.join_emp; eauto.\n  intros.\n  simpl in H.\n  tryfalse.\n  intros.\n  simpl in H; tryfalse.\n  intros.\n  simpl in H.\n  inverts H.\n  simpl in H0.\n  mytac.\n  destruct a.\n  mytac.\n  lets Hx : IHy1 H2 H4.\n  mytac.\n  lets Hex : joinsig_join_ex H1 H7.\n  mytac.\n  do 3 eexists.\n  splits.\n  simpl.\n  eexists; splits; eauto.\n  do 3 eexists; splits.\n  eauto.\n  2: eauto.\n  3: eauto.\n  2 : eauto.\n  eauto.\n  eauto.\n  assert (y1 = nil \\/ y1 <> nil) by tauto.\n  destruct H11.\n  subst y1.  \n  right.\n  simpl in H2.\n  apply eq_sym in H2.\n  apply length_zero_nil in H2.\n  subst y2.\n  simpl in H5.\n  mytac.\n  unfolds.\n  simpl.\n  auto.\n  destruct H8.\n  left.\n  eapply  get_last_prop in H11.\n  eapply H11; eauto.\n  eapply  get_last_prop in H11.\n  right.\n  eapply H11; eauto.\nQed.\n\nLocal Open Scope Z_scope.\n\nLemma ecblist_ecbmod_get_mbox' :\n  forall v'40 v'52 v'61 i6  x4 x8 v'58 v'42 v'21 xx\n         v'63 x20 i5 v'37 v'35 v'36 v'38,\n    Some (Vptr (v'61, Int.zero)) = get_last_ptr v'40 ->\n    length v'40 = length v'21 ->\n    Int.unsigned i5 <= 65535 -> \n    array_type_vallist_match Int8u v'58->\n    RH_CurTCB v'38 v'36 ->\n    length v'58 = ∘OS_EVENT_TBL_SIZE ->\n    RH_TCBList_ECBList_P v'35 v'36 v'38 ->\n    RL_Tbl_Grp_P v'58 (V$0) ->\n    ECBList_P v'52 Vnull\n              (v'40 ++\n                    ((V$OS_EVENT_TYPE_MBOX\n                       :: xx :: Vint32 i6 :: v'63 :: x4 :: x8 :: nil,\n                      v'58) :: nil) ++ v'42)\n              (v'21 ++\n                                              (DMbox x20 :: nil) ++ v'37) v'35 v'36 ->\n \n     exists msgls,\n      EcbMod.get v'35 (v'61, Int.zero) = Some (absmbox msgls , nil)\n    /\\ exists vg vv vx,\n         ECBList_P v'52 (Vptr (v'61, Int.zero)) v'40 v'21 vg v'36 /\\\n         EcbMod.join vg vx v'35/\\\n         EcbMod.join vv  (EcbMod.sig (v'61, Int.zero) (absmbox msgls, nil)) vx/\\\n         ECBList_P x8 Vnull v'42 v'37  vv  v'36.\n  introv Hsom Hlen Hi Harr Hcur Hrl Htcb Hre Hep.\n  lets Hex : ecblist_p_decompose'' Hlen Hep.\n\n\n  mytac.\n  destruct H2.\n  rewrite H2 in Hsom; tryfalse.\n  rewrite H2 in Hsom ; inverts Hsom.\n  unfolds in Hre.\n  assert (forall n, (0 <= n < 8)%nat  ->  nth_val n v'58 = Some (Vint32 ($ 0))).\n  intros.\n  lets Hex : n07_arr_len_ex H3  Harr Hrl.\n  destruct Hex as (vh & Hnth & Hneq).\n  assert (V$0 = V$0) as Hasrt by auto.\n  lets Hres : Hre H3 Hnth Hasrt.\n  destruct Hres as (Hrs1 & Hrs2).\n  destruct Hrs1 as (Hrs11 & Hrs22).\n  rewrite Int.and_zero_l in Hrs11.\n  assert (vh = $ 0) .\n  apply Hrs11.\n  auto.\n  subst vh.\n  auto.\n  simpl in H0.\n  destruct H0 as (qid & Heq & Heb & Hex).\n  destruct Hex as (absmq & mqls' & v' & Hv & Hej & Hmt & Hlp).\n  destruct absmq.\n  destruct e; tryfalse.\n  usimpl Hv.\n  inverts Heq.\n  destruct Hmt as (Hm1 & Hm2). (* & Hm3 & Hm4). *)\n  assert (w = nil \\/ w <> nil) by tauto.\n  destruct H0 as [Hnil | Hnnil].\n  Focus 2.\n  unfolds in Hcur.\n  unfolds in Htcb.\n  destruct Htcb as (Htcb1&Htcb2&Htcb3&Htcb4).\n  lets Hj : ecbmod_joinsig_get Hej.\n  lets Hea : qwaitset_notnil_ex Hnnil.\n  destruct Hea as (tid & Hin).\n  assert ( EcbMod.get x1 (v'61, Int.zero) = Some (absmbox m, w) /\\ In tid w) by (split; auto).\n  lets Has : EcbMod.join_get_get_r H1 H0.\n  assert ( EcbMod.get v'35 (v'61, Int.zero) = Some (absmbox m, w) /\\ In tid w) by (split; auto).\n  destruct Htcb3 as (Htc & Htc').\n  lets Hjj : Htc H4.\n  destruct Hjj as (prio & m0 & n & Htcg).\n  unfolds in Heb.\n  destruct Heb as (Heb1 & Heb2 &  Heb3).\n  unfolds  in Heb1.\n  unfolds in Heb2.\n  destruct Heb2 as (Hebbb & Heb2 & Hebb & Heb4).\n  lets Hebs : Hebb Htcg.\n  lets Hbb : prioinq_exists Hebs.\n  destruct Hbb as (n0 & Hnn & Hnth).\n  lets Hfs : H3 Hnn.\n  tryfalse.\n  subst w.\n  exists m.\n  split.\n  assert (EcbMod.get x1 (v'61, Int.zero) = Some (absmbox m, nil)).\n  eapply ecbmod_joinsig_get; eauto.\n  eapply EcbMod.join_get_get_r;eauto.\n  do 3 eexists; splits; eauto.\n  eapply ecbmod_joinsig_sig.\n  eauto.\nQed. \n\nLemma  ecb_wt_ex_prop_mbox :\n  forall\n    v'43  v'34 v'38 x v'21 tid\n    v'23 v'35 i i3 x2 x3 v'42 v'40,\n    Int.eq i ($ 0) = false ->\n    Int.unsigned i <= 255 ->\n    array_type_vallist_match Int8u v'40 ->\n    length v'40 = ∘OS_EVENT_TBL_SIZE ->\n    RL_Tbl_Grp_P v'40 (Vint32 i) -> \n    ECBList_P v'38 (Vptr x)  v'21 v'23 v'43 v'35->\n    R_ECB_ETbl_P x\n                 (V$OS_EVENT_TYPE_MBOX\n                   :: Vint32 i\n                   :: Vint32 i3 :: x2 :: x3 :: v'42 :: nil,\n                  v'40) v'35 ->\n    RH_TCBList_ECBList_P v'34 v'35 tid ->\n    exists z t' tl,\n      EcbMod.get v'34 x = Some (absmbox z, t' :: tl).\nProof.\n  introv Hinteq Hiu Harr Hlen  Hrl Hep Hrp Hz.\n  unfolds in Hrp.\n  unfolds in Hrl.\n  lets Hex : int8_neq0_ex Hiu Hinteq.\n  destruct Hex as (n & Hn1 & Hn2).\n  lets Heu :  n07_arr_len_ex Hn1 Harr Hlen.\n  destruct Heu as (vv & Hnth & Hint).\n  assert ( Vint32 i = Vint32 i) by auto.\n  lets Hed : Hrl Hn1 Hnth H.\n  destruct Hed as (Hed1 & Hed2).\n  destruct Hed2.\n  lets Hed22 : H0 Hn2.\n  destruct Hrp as (Hrp1 & Hrp2).\n  unfold PrioWaitInQ in Hrp1.\n  lets Hexx : prio_inq Hn1 Hed22 Hint Hnth.\n  destruct Hexx as (prio & Hpro).\n  unfolds in Hrp1.\n  destruct Hrp1 as (Hrpa & Hrpb & Hrp1 & Hrpc).\n  lets Hxq : Hrp1 Hpro.\n  destruct Hxq as (tid' & n0 & m & Hte).\n  unfolds; simpl; auto.\n  unfolds in Hz.\n  destruct Hz as (Hz1 & Hz2 & Hz3 & Hz4).\n  destruct Hz3.\n  lets Hea : H3 Hte.\n  mytac.\n  apply  inlist_ex in H5.\n  mytac.\n  do 3 eexists.\n  eauto.\nQed.\n\n  Lemma  Mutex_owner_set: forall x y z t, (~exists aa bb cc, t = (absmutexsem aa bb, cc))->   RH_TCBList_ECBList_MUTEX_OWNER x y ->  RH_TCBList_ECBList_MUTEX_OWNER (EcbMod.set x z t) y.\n  Proof.\n    intros.\n    unfold RH_TCBList_ECBList_MUTEX_OWNER in *.\n    intros.\n    assert ( eid = z \\/ eid <> z).\n    tauto.\n    elim H2; intros.\n    subst eid.\n    rewrite EcbMod.set_a_get_a in H1.\n    inverts H1.\n    false.\n    apply H.\n    eauto.\n    go.\n\n    rewrite EcbMod.set_a_get_a' in H1.\n    eapply H0; eauto.\n    go.\n  Qed.\n  \n\nLemma upd_last_prop:\n  forall v g x vl z ,\n    V_OSEventListPtr v = Some x ->\n    vl = upd_last_ectrls ((v, g) :: nil) z ->\n    exists v', vl = ((v', g) ::nil) /\\ V_OSEventListPtr v' = Some z.\nProof.\n  intros.\n  unfolds in H.\n  destruct v;simpl in H; tryfalse.\n  destruct v0; simpl in H; tryfalse.\n  destruct v1; simpl in H; tryfalse.\n  destruct v2; simpl in H; tryfalse.\n  destruct v3; simpl in H; tryfalse.\n  destruct v4; simpl in H; tryfalse.\n  inverts H.\n  unfold upd_last_ectrls in H0.\n  simpl in H0.\n  eexists; splits; eauto.\nQed.\n\n(* there's some lemma which has the same name with fixpoint update_nth *)\n\nLocal Open Scope list_scope.\n\nLemma nth_val_upd_prop:\n  forall vl n m v x,\n    (n<>m)%nat ->\n    (nth_val n (ifun_spec.update_nth val m vl v) = Some x  <->\n     nth_val n vl  = Some x).\nProof.\n  inductions vl.\n  intros.\n  simpl.\n  split;\n    intros; tryfalse.\n  intros.\n  simpl.\n  destruct n.\n  destruct m.\n  tryfalse.\n  simpl.\n  intros; split; auto.\n  destruct m.\n  simpl.\n  split; auto.\n  assert (n <> m) by omega.\n  simpl.\n  eapply IHvl.\n  eauto.\nQed.\n\nLemma R_ECB_upd_hold :\n  forall x1 v v0 v'36 x8,\n    R_ECB_ETbl_P x1 (v, v0) v'36 ->\n    R_ECB_ETbl_P x1 (ifun_spec.update_nth val 5 v x8, v0) v'36.\nProof.\n  introv Hr.\n  unfolds in Hr.\n  destruct Hr.\n  unfolds.\n  splits.\n  destruct H as (Hr1 & Hr2 & Hr3 & Hr4).\n  unfolds in Hr1.\n  splits.\n  unfolds.\n  intros.\n  unfolds in H1.\n  eapply Hr1; eauto.\n  unfolds.\n  assert (0<>5)%nat by omega.\n  eapply nth_val_upd_prop; eauto.\n  unfolds in Hr2.\n  unfolds.\n  intros.\n  eapply Hr2; eauto.\n  assert (0<>5)%nat by omega.\n  eapply nth_val_upd_prop; eauto.\n  unfolds in Hr3.\n  unfolds.\n  intros.\n  eapply Hr3; eauto.\n  assert (0<>5)%nat by omega.\n  eapply nth_val_upd_prop; eauto.\n  unfolds in Hr4.\n  unfolds.\n  intros.\n  eapply Hr4; eauto.\n  assert (0<>5)%nat by omega.\n  eapply nth_val_upd_prop; eauto.\n  destruct H0 as (H0 & _).\n  destruct H0 as (Hr1 & Hr2 & Hr3 & Hr4).\n  unfolds.\n  splits.\n  unfolds in Hr1.\n  unfolds.\n  intros.\n  apply Hr1 in H0.\n  destruct H0.\n  split; eauto.\n  assert (0<>5)%nat by omega.\n  eapply nth_val_upd_prop; eauto.\n  unfolds in Hr2.\n  unfolds.\n  intros.\n  apply Hr2 in H0.\n  destruct H0.\n  split; eauto.\n  assert (0<>5)%nat by omega.\n  eapply nth_val_upd_prop; eauto.\n  unfolds in Hr3.\n  unfolds.\n  intros.\n  apply Hr3 in H0.\n  destruct H0.\n  split; eauto.\n  assert (0<>5)%nat by omega.\n  eapply nth_val_upd_prop; eauto.\n  unfolds in Hr4.\n  unfolds.\n  intros.\n  apply Hr4 in H0.\n  destruct H0.\n  split; eauto.\n  assert (0<>5)%nat by omega.\n  eapply nth_val_upd_prop; eauto.\n  destruct H0.\n  unfolds in H1.\n  unfolds.\n  simpl in *.\n  unfold V_OSEventType in *.\n  destruct H1.\n  left.\n  eapply nth_val_upd_prop; eauto.\n  destruct H1.\n  branch 2.\n  eapply nth_val_upd_prop; eauto.\n  destruct H1.\n  branch 3.\n  eapply nth_val_upd_prop; eauto.\n  branch 4.\n  eapply nth_val_upd_prop; eauto.\nQed.\n\n\n    \nLemma ecb_list_join_join :\n  forall v'40  v'52 v'61 v'21 x x2  v'36 x8 v'42 v'37 x0 v'51,\n     v'40 <> nil ->\n     ECBList_P v'52 (Vptr (v'61, Int.zero)) v'40 v'21 x v'36 ->\n     ECBList_P x8 Vnull v'42 v'37 x0 v'36 ->\n     v'51 = upd_last_ectrls v'40 x8 -> \n     EcbMod.join x0 x x2 -> \n     ECBList_P v'52 Vnull (v'51 ++ v'42) (v'21 ++ v'37) x2 v'36.\nProof.\n  inductions v'40.\n  simpl.\n  intros.\n  mytac.\n  unfold upd_last_ectrls in H.\n  simpl in H.\n  tryfalse.\n  introv Hneq Hep Hepp Hsom Hj.\n  assert (v'40 = nil \\/ v'40 <> nil) by tauto.\n  destruct H.\n  subst v'40.\n  destruct v'21.\n  simpl in Hep.\n  mytac; tryfalse.\n  simpl in Hep.\n  mytac.\n  destruct a.\n  mytac.\n  remember (upd_last_ectrls ((v, v0) :: nil) x8) as vl.\n  lets Hx : upd_last_prop  H Heqvl.\n  mytac.\n  unfolds in H3.\n  simpl in H3.\n  inverts H3.\n  unfolds upd_last_ectrls.\n  simpl.\n  eexists; splits; eauto.\n(* ** ac:   Check R_ECB_upd_hold. *)\n  eapply R_ECB_upd_hold; eauto.\n  do 2 eexists.\n  exists x8.\n  split; auto.\n  split.\n  eapply ecbmod_join_sigg; eauto.\n  split; eauto.\n  destruct a.\n  lets Hzz :  upd_last_prop' Hsom;auto.\n  destruct Hzz as (vll & Hv1 & Hv2).\n  rewrite Hv1.\n  destruct v'21.\n  simpl in Hep; mytac; tryfalse.\n  simpl.\n  simpl in Hep.\n  destruct Hep as (qid & Heq & Hr &Hex).\n  destruct Hex as (abs & mqls & vv & Heaq & Hjoin & Hrl & Hepc ).\n  lets Hxz : joinsig_join_sig2 Hjoin Hj.\n  destruct Hxz as (x6 & Hj1 & Hj2).\n  subst v'52.\n  eexists.\n  split; eauto.\n  split; auto.\n  do 2 eexists.\n  exists vv.\n  splits; eauto.\nQed.\n\nLemma RH_TCBList_ECBList_MUTEX_OWNER_subset_hold : forall x y z t,  RH_TCBList_ECBList_MUTEX_OWNER z t -> EcbMod.join x y z ->   RH_TCBList_ECBList_MUTEX_OWNER x t.\nProof.\n  intros.\n  unfold RH_TCBList_ECBList_MUTEX_OWNER in *.\n  intros.\n  unfold get in *; simpl in *.\n  assert ( EcbMod.get z eid = Some (absmutexsem pr (Some (tid, opr)), wls)) by go.\n  eapply H; eauto.\nQed.\n\nLemma ecb_del_prop_RHhold:\n  forall v'35 v'36 v'38 x y absmg,\n    RH_TCBList_ECBList_P v'35 v'36 v'38 ->\n    EcbMod.join x (EcbMod.sig y (absmg, nil))\n                v'35 ->  RH_TCBList_ECBList_P x v'36 v'38 .\nProof.\n  introv Hrh Hjo.\n  unfolds in Hrh.\n  destruct Hrh as (Hrh1&Hrh2&Hrh3&Hrh4).\n  unfolds.\n  splits.\n  destruct Hrh1.\n  splits.\n  intros.\n  mytac.\n  lets Hg : EcbMod.join_get_get_l Hjo H1.\n  eapply H.\n  eauto.\n  intros.\n  assert (eid = y \\/ eid <>y) by tauto.\n  apply H0 in H1.\n  mytac.\n  destruct H2.\n  subst y.\n  apply EcbMod.join_comm in Hjo.\n  eapply EcbMod.join_sig_get in Hjo.\n  unfold get in *; simpl in *.\n  rewrite H1 in Hjo.\n  inverts Hjo.\n  simpl in H3.\n  tryfalse.\n  do 3 eexists; split; try eapply ecbmod_get_join_get; eauto.\n  destruct Hrh2.\n  splits.\n  intros.\n  mytac.\n  lets Hg : EcbMod.join_get_get_l Hjo H1.\n  eapply H.\n  eauto.\n  intros.\n  assert (eid = y \\/ eid <>y) by tauto.\n  apply H0 in H1.\n  mytac.\n  destruct H2.\n  subst y.\n  apply EcbMod.join_comm in Hjo.\n  eapply EcbMod.join_sig_get in Hjo.\n  unfold get in *; simpl in *.\n\n  rewrite H1 in Hjo.\n  inverts Hjo.\n  simpl in H3.\n  tryfalse.\n  do 2 eexists; split; try eapply ecbmod_get_join_get; eauto.\n  destruct Hrh3.\n  splits.\n  intros.\n  mytac.\n  lets Hg : EcbMod.join_get_get_l Hjo H1.\n  eapply H.\n  eauto.\n  intros.\n  assert (eid = y \\/ eid <>y) by tauto.\n  apply H0 in H1.\n  mytac.\n  destruct H2.\n  subst y.\n  apply EcbMod.join_comm in Hjo.\n  eapply EcbMod.join_sig_get in Hjo.\n  unfold get in *; simpl in *.\n  rewrite H1 in Hjo.\n  inverts Hjo.\n  simpl in H3.\n  tryfalse.\n  do 2 eexists; split; try eapply ecbmod_get_join_get; eauto.\n  destruct Hrh4.\n  splits.\n  intros.\n  mytac.\n  lets Hg : EcbMod.join_get_get_l Hjo H1.\n  eapply H.\n  eauto.\n  intros.\n  assert (eid = y \\/ eid <>y) by tauto.\n  apply H0 in H1.\n  mytac.\n  destruct H2.\n  subst y.\n  apply EcbMod.join_comm in Hjo.\n  eapply EcbMod.join_sig_get in Hjo.\n  unfold get in *; simpl in *.\n  rewrite H1 in Hjo.\n  inverts Hjo.\n  simpl in H3.\n  tryfalse.\n  do 3 eexists; split; try eapply ecbmod_get_join_get; eauto.\n\n\n  eapply  RH_TCBList_ECBList_MUTEX_OWNER_subset_hold; eauto.\n  tauto.\nQed.  \n\nLemma  Mutex_owner_hold_for_set_tcb: forall x y pcur a b c,  RH_TCBList_ECBList_MUTEX_OWNER x y ->  RH_TCBList_ECBList_MUTEX_OWNER x (TcbMod.set y pcur (a, b, c)).\nProof.\n  intros.\n  unfold   RH_TCBList_ECBList_MUTEX_OWNER  in *.\n  intros.\n  assert ( pcur = tid  \\/ pcur <> tid ) by tauto.\n  elim H1; intros.\n  subst pcur.\n  rewrite TcbMod.set_a_get_a; auto.\n  eauto.\n  go.\n  rewrite TcbMod.set_a_get_a'; auto.\n  eapply H; eauto.\n  go.\nQed.\n\n(* infer step rule *)\n(* Lemma absinfer_mbox_acc_err_return :\n *   forall P x , \n *     can_change_aop P ->\n *     isptr x ->\n *     absinfer (<|| mbox_acc (x :: nil) ||>  **  P) ( <|| END (Some Vnull) ||>  **  P).\n * Proof.\n *   infer_solver 0%nat.\n * Qed.\n * \n * \n * Lemma  absinfer_mbox_acc_succ_return:\n *   forall P mqls x wl v v1 v3 v4 a,\n *     can_change_aop P ->  \n *     v = Vptr a -> \n *     EcbMod.get mqls x = Some (absmbox v, wl) -> \n *     absinfer\n *       ( <|| mbox_acc (Vptr x :: nil) ||>  ** \n *             HECBList mqls **  HTCBList v1 **\n *       HTime v3 **\n *       HCurTCB v4 **\n *        P) \n *       (<|| END (Some v) ||>  ** HECBList (EcbMod.set mqls x (absmbox Vnull, nil)) **  HTCBList v1 **\n *       HTime v3 **\n *       HCurTCB v4 **\n *                     P).\n * Proof.\n *   infer_solver 1%nat.\n * Qed. *)\n\n\nLemma absmbox_ptr_wt_nil: forall a w, RH_ECB_P  (absmbox (Vptr a), w) -> w = nil.\n  intros.\n  unfolds in H; try inversion H.\n  clear H1.\n  mytac.\n  assert (w=nil \\/ w<>nil) by tauto.\n  elim H2; intros.\n  auto.\n  apply H.\n  intro; tryfalse.\n  \nQed.    \n\n\nLemma ecb_sig_join_sig'_set : forall a b c d b', EcbMod.joinsig a b c d -> EcbMod.joinsig a b' c (EcbMod.set d a b').\n  intros.\n  unfolds.\n  unfolds in H.\n  unfolds.\n  intros.\n  unfolds in H.\n  lets aaa : H a0.\n  assert (a = a0 \\/ a<> a0) by tauto.\n  elim H0; intros.\n  subst.\n  rewrite EcbMod.get_a_sig_a.\n  rewrite EcbMod.get_a_sig_a in aaa.\n  rewrite EcbMod.set_a_get_a.\n  destruct (EcbMod.get c a0).\n  inversion aaa.\n  auto.\n  apply CltEnvMod.beq_refl.\n  apply CltEnvMod.beq_refl.\n  apply CltEnvMod.beq_refl.\n  \n  rewrite EcbMod.get_a_sig_a'.\n  rewrite EcbMod.get_a_sig_a' in aaa.\n  rewrite EcbMod.set_a_get_a'.\n  destruct (EcbMod.get c a0).\n  destruct (EcbMod.get d a0).\n  auto.\n  auto.\n  auto.\n  apply tidspec.neq_beq_false; auto.\n  apply tidspec.neq_beq_false; auto.\n  apply tidspec.neq_beq_false; auto.\nQed.\n\n\nLemma R_ECB_ETbl_P_high_ecb_mbox_acpt_hold :\n  forall x2 i i1 a  x3 v'42 v'40 v'35,\n R_ECB_ETbl_P x2\n          (V$OS_EVENT_TYPE_MBOX\n           :: Vint32 i :: Vint32 i1 :: Vptr a :: x3 :: v'42 :: nil, v'40) v'35\n->\n R_ECB_ETbl_P x2\n     (V$OS_EVENT_TYPE_MBOX\n      :: Vint32 i :: Vint32 i1 :: Vnull :: x3 :: v'42 :: nil, v'40) v'35\n.\n  intros.\n  splits.\n  unfolds in H.\n  mytac.\n  unfolds in H.\n  mytac.\n  unfolds .\n  splits;  unfolds; auto.\n  unfolds in H.\n  mytac.\n  clear -H0.\n  unfolds in H0.\n  mytac.\n  unfolds.\n  splits; unfolds; auto.\n  unfolds in H.\n  mytac.\n  clear -H1.\n  unfolds in H1.\n  unfolds.\n  auto.\nQed.\n\nLemma mbox_acpt_rh_tcblist_ecblist_p_hold: forall v'34 v'35 v'37 v w m, EcbMod.get v'34 v = Some (absmbox m, w) ->RH_TCBList_ECBList_P v'34 v'35 v'37 ->\nRH_TCBList_ECBList_P\n     (EcbMod.set v'34 v (absmbox Vnull, w)) v'35 v'37.\nProof.\n  intros.\n  unfolds in H0.\n  mytac.\n  unfolds.\n  mytac; [clear -H H0| clear -H H1; rename H1 into H0|clear -H H2; rename H2 into H0| clear -H H3; rename H3 into H0]; unfolds; unfolds in H0; mytac; intros; unfold get in *; simpl in *; \n  try solve [eapply H0;\n              mytac; eauto;\n              assert ( eid = v \\/ eid <> v)  as aa by tauto; destruct aa;[subst;\n                                                                           rewrite EcbMod.set_a_get_a in e;[\n                                                                             inversion e|\n                                                                             apply CltEnvMod.beq_refl] \n                                                                         |\n                                                                         rewrite EcbMod.set_a_get_a' in e;[\n                                                                             eauto|\n                                                                             apply tidspec.neq_beq_false];\n                                                                         auto]]\n  ;\n  try solve[\n         lets aaa : H1 H2;\n         mytac;\n         assert ( eid = v \\/ eid <> v)  as aa by tauto; destruct aa;[subst eid;rewrite H in H3;inversion H3|\n                                                                     rewrite EcbMod.set_a_get_a';[\n                                                                         rewrite H3;\n                                                                         eauto|\n                                                                         apply tidspec.neq_beq_false;\n                                                                           auto]]\n       ]\n  .\n\n  assert (eid = v \\/ eid <> v) as aa by tauto; destruct aa;[subst eid; rewrite EcbMod.set_a_get_a in H2|idtac].\n  elim H2; intros.\n\n  inversion H3.\n  subst.\n  eapply H0.\n  splits; eauto.\n  apply CltEnvMod.beq_refl.\n  eapply H0.\n  rewrite EcbMod.set_a_get_a' in H2.\n  eauto.\n  apply tidspec.neq_beq_false; auto.\n\n  assert (eid = v \\/ eid <> v) as aa by tauto; destruct aa. \n  subst.\n  rewrite EcbMod.set_a_get_a.\n  repeat eexists.\n  lets aaa : H1 H2.\n  mytac; auto.\n  rewrite H in H3.\n  inversion H3.\n  subst.\n  auto.\n  apply CltEnvMod.beq_refl.\n\n  rewrite EcbMod.set_a_get_a'.\n  eapply H1.\n  eauto.\n  apply tidspec.neq_beq_false; auto.\n  assert ( v = eid \\/ v <> eid) by tauto.\n  elim H4; intros.\n  apply H1 in H3.\n  simpljoin.\n  rewrite H3 in H.\n  inversion H.\n  rewrite EcbMod.set_a_get_a' .\n  eapply H1; eauto.\n  go.\n  eapply Mutex_owner_set.\n  intro.\n  mytac.\n  auto.\nQed.\n\nLemma RLH_ECBData_p_high_mbox_acpt_hold:\n  forall a e w,\n RLH_ECBData_P (DMbox (Vptr a)) (e, w) ->  RLH_ECBData_P (DMbox Vnull) (absmbox Vnull, w).\nProof.\n  intros.\n  unfolds in H.\n  destruct e; tryfalse.\n  unfolds.\n  mytac.\n  auto.\n  unfolds in H0.\n  assert (w = nil).\n  mytac.\n  assert (w = nil \\/ w <> nil) by tauto.\n  elim H1; auto.\n(*  intro.\n  apply H0 in H2.\n  inverts H2. *)\n\n  unfolds.\n  mytac; auto.\nQed.\n\n\n(* absinfer lemmas *)\n(* Lemma absinfer_mbox_del_null_return : forall P , \n * can_change_aop P ->\n * absinfer (<|| mbox_del (Vnull :: nil) ||> ** P) ( <|| END (Some (Vint32 (Int.repr MBOX_DEL_NULL_ERR))) ||> ** P).\n * Proof.\n *   infer_solver 0%nat.\n * Qed.\n * \n * Lemma absinfer_mbox_del_p_not_legal_return : forall x a P tcbls tm curtid, \n *                                   can_change_aop P ->\n *                                   ~ (exists x0 wls, EcbMod.get x a = Some (absmbox x0, wls)) ->\n * absinfer (<|| mbox_del (Vptr a :: nil) ||> ** HECBList x **   HTCBList tcbls ** HTime tm **  HCurTCB curtid **\n *             P) ( <|| END (Some  (V$ MBOX_DEL_P_NOT_LEGAL_ERR)) ||> ** HECBList x **   HTCBList tcbls ** HTime tm **  HCurTCB curtid  ** P).\n * Proof.\n *   infer_solver 1%nat.\n * Qed.\n * \n * Lemma absinfer_mbox_del_wrong_type_return : forall x a P tcbls tm curtid ,\n *                                   can_change_aop P ->\n *  (exists d,\n *   EcbMod.get x a = Some d /\\ ~ (exists x wls, d = (absmbox x, wls))) ->\n * absinfer (<||mbox_del (Vptr a :: nil) ||>  ** HECBList x **   HTCBList tcbls ** HTime tm **  HCurTCB curtid **  P) ( <|| END (Some  (V$ OS_ERR_EVENT_TYPE)) ||> ** HECBList x **   HTCBList tcbls ** HTime tm **  HCurTCB curtid ** P).\n * Proof.\n *   infer_solver 2%nat.\n * Qed.\n * \n * \n * Lemma absinfer_mbox_del_task_wt_return : forall x a P tcbls tm curtid, \n *                                   can_change_aop P ->\n *  (exists y t tl,\n *   EcbMod.get x a = Some (absmbox y, t::tl)) ->\n * absinfer (<|| mbox_del (Vptr a :: nil) ||>  ** HECBList x **   HTCBList tcbls ** HTime tm **  HCurTCB curtid ** P) ( <|| END (Some  (V$ MBOX_DEL_TASK_WAITING_ERR)) ||>   ** HECBList x **   HTCBList tcbls ** HTime tm **  HCurTCB curtid ** P).\n * Proof.\n *   infer_solver 3%nat.\n * Qed.\n * \n * Lemma absinfer_mbox_del_succ_return :\n *   forall ecbls ecbls' x a P tid tcbls t, \n *     can_change_aop P ->\n *     EcbMod.get ecbls a = Some (absmbox x, nil) ->\n *     EcbMod.join ecbls' (EcbMod.sig a (absmbox x, nil)) ecbls -> \n *     absinfer (<|| mbox_del (Vptr a :: nil) ||> ** HECBList ecbls **\n *               HTCBList tcbls ** HTime t **  HCurTCB tid **  P) ( <||  END (Some  (V$NO_ERR)) ||> **\n *                          HECBList ecbls' ** HTCBList tcbls ** HTime t **  HCurTCB tid  ** P).\n * Proof.\n *   infer_solver 4%nat.\n * Qed. *)\n\nLemma RH_TCBList_ECBList_P_high_get_msg_hold_mbox :\n  forall ecbls tcbls pcur qid m  wl prio  m',\n    RH_TCBList_ECBList_P ecbls tcbls pcur ->\n    EcbMod.get ecbls qid = Some (absmbox (Vptr m), wl) ->\n    TcbMod.get tcbls pcur = Some (prio, rdy, m') ->\n    RH_TCBList_ECBList_P (EcbMod.set ecbls qid (absmbox Vnull, wl)) (TcbMod.set tcbls pcur (prio, rdy, (Vptr m))) pcur. \nProof.\n  introv Hr Ht He.\n  unfolds in Hr.\n  destruct Hr as (Hr3 & Hr2 & Hr1 & Hr4).\n  unfolds.\n  splits.\n  Focus 3.\n  splits.  \n  intros.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H0.\n  subst.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  inverts H0.\n  assert ( EcbMod.get ecbls eid = Some (absmbox (Vptr m), wls) /\\ In tid wls).\n  splits; auto.\n  apply Hr1 in H.\n  mytac.\n  assert (tid = pcur \\/ tid <> pcur) by tauto.\n  destruct H0.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite He in H; inverts H.\n  rewrite TcbMod.set_sem ;\n    rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists; eauto.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; auto.\n  apply Hr1 in H.\n  mytac.\n  assert (tid = pcur \\/ tid <> pcur) by tauto.\n  destruct H1.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite He in H; inverts H.\n  rewrite TcbMod.set_sem ;\n    rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists; eauto.\n  intros.\n  assert (tid = pcur \\/ tid <> pcur) by tauto.\n  destruct H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; auto.\n  apply Hr1 in H.\n  mytac.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H2.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H in Ht.\n  inverts Ht.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; auto.\n  do 2 eexists; splits; eauto.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 2 eexists; splits; eauto.\nFocus 2.\n{\n  splits.  \n  intros.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H0.\n  subst.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  inverts H0.\n  destruct H as (Ha & Hb).\n  rewrite EcbMod.set_sem in Ha.\n  rewrite tidspec.neq_beq_false in Ha; auto.\n  assert ( EcbMod.get ecbls eid = Some (abssem n, wls)/\\ In tid wls).\n  splits; auto.\n  apply Hr2 in H.\n  mytac.\n  assert (tid = pcur \\/ tid <> pcur) by tauto.\n  destruct H1.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite He in H; inverts H.\n  rewrite TcbMod.set_sem ;\n    rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists; eauto.\n  intros.\n  assert (tid = pcur \\/ tid <> pcur) by tauto.\n  destruct H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; auto.\n  apply Hr2 in H.\n  mytac.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H2.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H in Ht.\n  inverts Ht.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 2 eexists; splits; eauto.\n}\n  Unfocus.\n{\n  splits.\n  intros.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H0.\n  subst.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  inverts H0.\n  destruct H as (Ha & Hb).\n  rewrite EcbMod.set_sem in Ha.\n  rewrite tidspec.neq_beq_false in Ha; auto.\n  assert ( EcbMod.get ecbls eid =Some (absmsgq x y, qwaitset)/\\ In tid qwaitset).\n  splits; auto.\n  apply Hr3 in H.\n  mytac.\n  assert (tid = pcur \\/ tid <> pcur) by tauto.\n  destruct H1.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite He in H; inverts H.\n  rewrite TcbMod.set_sem ;\n    rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists; eauto.\n  intros.\n  assert (tid = pcur \\/ tid <> pcur) by tauto.\n  destruct H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; auto.\n  apply Hr3 in H.\n  mytac.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H2.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H in Ht.\n  inverts Ht.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists; splits; eauto.\n}\n{\n  splits.  \n  intros.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H0.\n  subst.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  inverts H0.\n  destruct H as (Ha & Hb).\n  rewrite EcbMod.set_sem in Ha.\n  rewrite tidspec.neq_beq_false in Ha; auto.\n  assert ( EcbMod.get ecbls eid =Some (absmutexsem n1 n2, wls)/\\ In tid wls).\n  splits; auto.\n  apply Hr4 in H.\n  mytac.\n  assert (tid = pcur \\/ tid <> pcur) by tauto.\n  destruct H1.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite He in H; inverts H.\n  rewrite TcbMod.set_sem ;\n    rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists; eauto.\n  intros.\n  assert (tid = pcur \\/ tid <> pcur) by tauto.\n  destruct H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; auto.\n  apply Hr4 in H.\n  mytac.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H2.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H in Ht.\n  inverts Ht.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists; splits; eauto.\n\n  unfolds in Hr4.\n  mytac.\n\n  eapply Mutex_owner_hold_for_set_tcb.\n  eapply Mutex_owner_set.\n  intro; mytac.\n  auto.\n}\nQed.  \n\nLemma TCBListP_head_in_tcb:\n  forall v'51 v'52 v'22 x9 x8 i9 i8 i6 i5 i4 i3 v'33 v'34 v'50 xx,\n    TCBList_P (Vptr v'52)\n              ((v'51\n                  :: v'22\n                  :: x9\n                  :: x8\n                  :: Vint32 i9\n                  :: Vint32 i8\n                  :: Vint32 xx\n                  :: Vint32 i6\n                  :: Vint32 i5\n                  :: Vint32 i4 :: Vint32 i3 :: nil) :: v'33)\n              v'34 v'50 ->\n    exists st, TcbMod.get v'50 v'52 = Some ( xx, st, x8).\nProof.\n  intros.\n  unfolds in H.\n  fold TCBList_P in H.\n  mytac.\n  unfolds in H2.\n  destruct x2; destruct p.\n  mytac.\n  unfolds in H2.\n  unfolds in H4.\n  simpl in H2.\n  simpl in H4.\n  inverts H2.\n  inverts H4.\n  inverts H.\n  unfolds in H0; simpl in H0.\n  inverts H0.\n  unfolds in H6.\n  eexists.\n  eapply TcbMod.join_get_l.\n  exact H1.\n  eapply TcbMod.get_a_sig_a.\n  apply CltEnvMod.beq_refl.\nQed.\n\n\nLemma tcblist_p_node_rl_mbox:\n  forall v'47 v'39 v'19 x15 x10 i10 i9 i8 i7 i6 i5 i1 v'31 v'32 v'36 i,\n    TCBList_P (Vptr (v'47, Int.zero))\n              ((v'39\n                  :: v'19\n                  :: x15\n                  :: x10\n                  :: Vint32 i10\n                  :: Vint32 i9\n                  :: Vint32 i8\n                  :: Vint32 i7\n                  :: Vint32 i6\n                  :: Vint32 i5 :: Vint32 i1 :: nil) :: v'31)\n              v'32 v'36 ->\n    RL_TCBblk_P\n      (v'39\n         :: v'19\n         :: x15\n         :: Vnull\n         :: Vint32 i\n         :: V$OS_STAT_MBOX\n         :: Vint32 i8\n         :: Vint32 i7\n         :: Vint32 i6 :: Vint32 i5 :: Vint32 i1 :: nil).\nProof.\n  introv Ht.\n  simpl in Ht.\n  mytac;simpl_hyp.\n  inverts H.\n  unfolds in H2.\n  destruct x2.\n  destruct p.\n  mytac; simpl_hyp.\n  funfold H2.\n  unfolds.\n  do 6 eexists;splits; try unfolds; simpl;  eauto.\n  splits; auto.\n  eexists.\n  splits.\n  unfolds.\n  simpl; eauto.\n  introv Hf.\n  inverts Hf.\n Qed. \n\n\n(* absinfer lemmas *)\n(* Lemma absinfer_mbox_pend_null_return : forall P x, \n *                                        can_change_aop P ->\n *                                        tl_vl_match  (Tint16 :: nil) x = true ->\n *                                        absinfer (<|| mbox_pend (Vnull :: x) ||> ** P) ( <|| END (Some (Vint32 (Int.repr MBOX_PEND_NULL_ERR))) ||> ** P).\n * Proof.\n *   infer_solver 0%nat.\n * Qed.\n * \n * Open Scope code_scope.\n * \n * \n * Lemma absinfer_mbox_pend_p_not_legal_return : forall x a P b v'33 v'16 v'35, \n *                                               can_change_aop P ->\n *                                               Int.unsigned b<=65535 ->\n *                                               EcbMod.get x a = None ->\n *                                               absinfer (<|| mbox_pend (Vptr a ::Vint32 b:: nil) ||> ** HECBList x **\n *     HTCBList v'33 **\n *     HTime v'16 **\n *     HCurTCB v'35 **\n *                                                           P) ( <|| END (Some  (V$ MBOX_PEND_P_NOT_LEGAL_ERR)) ||> ** HECBList x **\n *     HTCBList v'33 **\n *     HTime v'16 **\n *     HCurTCB v'35 ** P).\n * Proof.\n *   infer_solver 1%nat.\n * Qed.\n * \n * \n * Lemma absinfer_mbox_pend_wrong_type_return : forall x a b P v'33 v'16 v'35, \n *                                              can_change_aop P ->\n *                                              Int.unsigned b <= 65535 ->\n *                                              (exists d,\n *                                                 EcbMod.get x a = Some d /\\ ~ (exists x wls, d = (absmbox x, wls))) ->\n *                                              absinfer (<|| mbox_pend (Vptr a :: Vint32 b :: nil) ||> ** HECBList x **\n *     HTCBList v'33 **\n *     HTime v'16 **\n *     HCurTCB v'35 **\n *                                                          P) ( <|| END (Some  (V$MBOX_PEND_WRONG_TYPE_ERR)) ||> ** HECBList x **\n *     HTCBList v'33 **\n *     HTime v'16 **\n *     HCurTCB v'35 ** P).\n * Proof.\n *   intros.\n *   mytac.\n *   destruct x0.\n *   infer_solver 2%nat.\n *   repeat tri_exists_and_solver1.\n *   intro.\n *   apply H2.\n *   mytac.\n *   eauto.\n * Qed.\n * \n * Lemma absinfer_mbox_pend_from_idle_return : forall x a b P y t ct, \n *                                              can_change_aop P ->\n *                                              Int.unsigned b <= 65535 ->\n *                                              (exists st msg, TcbMod.get y ct = Some (Int.repr OS_IDLE_PRIO, st, msg)) ->\n *                                              absinfer (<|| mbox_pend (Vptr a :: Vint32 b :: nil) ||> ** HECBList x ** HTCBList y ** HTime t ** HCurTCB ct **\n *                                                          P) ( <|| END (Some  (V$MBOX_PEND_FROM_IDLE_ERR)) ||> ** HECBList x ** HTCBList y ** HTime t ** HCurTCB ct ** P).\n * Proof.\n *   infer_solver 3%nat.\n * Qed.\n * Lemma absinfer_mbox_pend_not_ready_return :\n *   forall P ecbls tcbls t ct st msg v x prio,\n *     Int.unsigned v <= 65535 ->\n *     TcbMod.get tcbls ct = Some (prio, st, msg) ->\n *     ~ st = rdy ->\n *     can_change_aop P ->\n *     absinfer (<|| mbox_pend (Vptr x :: Vint32 v :: nil) ||> ** HECBList ecbls ** HTCBList tcbls ** HTime t ** HCurTCB ct ** P)\n *            (<|| END (Some (Vint32 (Int.repr MBOX_PEND_NOT_READY_ERR)))||> ** HECBList ecbls ** HTCBList tcbls ** HTime t ** HCurTCB ct ** P).\n * Proof.\n *   infer_solver 4%nat.\n * Qed.\n * \n * \n * Lemma  absinfer_mbox_pend_inst_get_return:\n *   forall P mqls x wl v v1 v3 v4 a v00 msg p,\n *     can_change_aop P ->  \n *     v = Vptr a -> \n *     Int.unsigned v00 <= 65535 ->\n *     EcbMod.get mqls x = Some (absmbox v, wl) -> \n *     TcbMod.get v1 v4 = Some (p, rdy, msg) ->\n *     absinfer\n *       ( <|| mbox_pend (Vptr x ::Vint32 v00 :: nil) ||>  ** \n *             HECBList mqls **  HTCBList v1 **\n *       HTime v3 **\n *       HCurTCB v4 **\n *        P) \n *       (<|| END (Some (Vint32 (Int.repr MBOX_PEND_SUCC))) ||>  ** HECBList (EcbMod.set mqls x (absmbox Vnull, nil)) **  HTCBList (TcbMod.set v1 v4 (p, rdy, v)) **\n *       HTime v3 **\n *       HCurTCB v4 **\n *                     P).\n * Proof.\n *   infer_solver 5%nat.\n * Qed.\n * \n * Lemma absinfer_mbox_pend_block:\n *   forall P mqls qid v wl p m t ct tls,\n *     Int.unsigned v <= 65535 ->\n *     can_change_aop P ->\n *     EcbMod.get mqls qid = Some (absmbox Vnull, wl) ->\n *     TcbMod.get tls ct = Some (p,rdy,m) ->\n *     absinfer\n *       ( <|| mbox_pend (Vptr qid :: Vint32 v :: nil) ||>  ** \n *            HECBList mqls ** HTCBList tls ** HTime t ** HCurTCB ct ** P) \n *       (<|| isched;; (mbox_pend_timeout_err (|Vptr qid :: Vint32 v :: nil|) ?? mbox_pend_block_get_succ (|Vptr qid :: Vint32 v :: nil|))||>  ** HECBList (EcbMod.set mqls qid (absmbox Vnull,ct::wl)) ** HTCBList (TcbMod.set tls ct (p,wait (os_stat_mbox qid) v, Vnull) ) ** HTime t ** HCurTCB ct ** P).\n * Proof.\n *   \n *   unfold mbox_pend; intros.\n *   infer_branch 6%nat.\n *   eapply absinfer_trans.\n *   Focus 2.\n *   eapply absinfer_seq_end.\n *   3:sep auto.\n *   can_change_aop_solver.\n *   can_change_aop_solver.\n *   instantiate (1:= None).\n *   eapply absinfer_seq.\n *   can_change_aop_solver.\n *   can_change_aop_solver.\n *   tri_infer_prim.\n *   infer_part2.\n * Qed. *)\n\n\nLemma low_stat_q_impl_high_stat_q\n : forall (tcur : addrval) (tcurl : vallist) (tcblist : list vallist)\n          (rtbl : vallist) (tcbls : TcbMod.map) (msg : val),\n     TCBList_P (Vptr tcur) (tcurl :: tcblist) rtbl tcbls ->\n     V_OSTCBMsg tcurl = Some msg ->\n     exists prio st,\n       TcbMod.get tcbls tcur = Some (prio, st, msg).\nProof.\n  introv Ht Hv.\n  simpl in Ht.\n  mytac.\n  inverts H.\n  funfold H2.\n  destruct x2.\n  destruct p.\n  mytac.\n  unfolds in H.\n  rewrite H in H4.\n  inverts H4.\n  apply tcbjoin_get_a in H1.\n  do 2 eexists; eauto.\nQed.\n\n\nLemma low_stat_nordy_imp_high:\n  forall a b c d e f g h i j st rtbl p t m,\n    R_TCB_Status_P\n      (a\n         :: b\n         :: c\n         :: d\n         :: Vint32 e\n         :: Vint32 st\n         :: f\n         :: g\n         :: h :: i :: j :: nil)\n      rtbl (p, t, m) -> (Int.eq st ($ OS_STAT_RDY) = false \\/ Int.eq e ($ 0) = false) ->\n    ~(t = rdy ).\nProof.\n  introv Hr Heq.\n  unfolds in Hr.\n  mytac.\n  introv Hf.\n  clear H H1.\n  subst t.\n  assert ( (p, rdy, m) = (p, rdy, m)) by auto.\n  apply H0 in H.\n  mytac.\n  unfolds in H1.\n  simpl in H1.\n  inverts H1.\n  simpl_hyp.\n  repeat rewrite Int.eq_true in Heq.\n  destruct Heq; tryfalse.\nQed.\n\n\nLemma r_tcb_status_p_nrdy:\n  forall v'39 v'19 x15 x10 i10 i9 i8 i7 i6 i5 i1 p t m v'32,\n    R_TCB_Status_P\n      (v'39\n         :: v'19\n         :: x15\n         :: x10\n         :: Vint32 i10\n         :: Vint32 i9\n         :: Vint32 i8\n         :: Vint32 i7\n         :: Vint32 i6 :: Vint32 i5 :: Vint32 i1 :: nil)\n      v'32 (p, t, m) ->\n    Int.eq i9 ($ OS_STAT_RDY) = false \\/ Int.eq i10 ($ 0) = false ->\n    ~ t =rdy.\nProof.\n  intros.\n  eapply low_stat_nordy_imp_high; eauto.\nQed.\n\n\nLemma TCBList_P_impl_high_tcbcur_Some :  \n  forall tcbls tcur tcurl tcblist rtbl,\n    TCBList_P (Vptr tcur) (tcurl::tcblist) rtbl tcbls ->\n    exists prio st m, TcbMod.get tcbls tcur = Some (prio, st, m).\nProof.\n  introv Htcb.\n  simpl in Htcb.\n  mytac.\n  inverts H.\n  apply tcbjoin_get_a in H1.\n  destruct x2.\n  destruct p.\n  eauto.\nQed.\n\nLemma TCBList_P_impl_high_tcbcur_rdy:\n  forall (tcbls : TcbMod.map) (tcur : addrval) \n         (tcurl : vallist) (tcblist : list vallist)\n         (rtbl : vallist) v'39 v'19 x15 x10 i10 i9 i8 i7 i6 i5 i1,\n    Int.eq i9 ($ OS_STAT_RDY) = true ->\n    Int.eq i10 ($ 0) = true ->\n    array_type_vallist_match Int8u rtbl ->\n    length rtbl = ∘OS_RDY_TBL_SIZE ->\n    TCBList_P (Vptr tcur) ((v'39\n                              :: v'19\n                              :: x15\n                              :: x10\n                              :: Vint32 i10\n                              :: Vint32 i9\n                              :: Vint32 i8\n                              :: Vint32 i7\n                              :: Vint32 i6\n                              :: Vint32 i5 :: Vint32 i1 :: nil) :: tcblist) rtbl tcbls ->\n    exists prio m, TcbMod.get tcbls tcur = Some (prio, rdy, m).\nProof.\n  introv Heq1 Heq2 Harr Hlen Htc Htsp.\n  lets Hs : TCBList_P_impl_high_tcbcur_Some  Htsp.\n  mytac.\n  unfolds in Htsp.\n  fold TCBList_P in Htsp.\n  mytac.\n  simpl_hyp.\n  unfolds in H3.\n  destruct x5.\n  destruct p.\n  mytac.\n  simpl_hyp.\n  \n\n  lets Hsd : low_stat_rdy_imp_high H5 H6 Heq2 Harr; eauto.\n  subst.\n  inverts H0.\n  apply tcbjoin_get_a in H2.\n  rewrite H2 in H.\n  inverts H.\n  do 2 eexists; eauto.\nQed.\n\n\n\n\nLemma  ecb_etbl_set_hold:\n  forall x y tcbls prio st m ptcb m',\n    TcbMod.get tcbls ptcb = Some (prio, st, m) ->\n    R_ECB_ETbl_P x y tcbls  ->\n    R_ECB_ETbl_P x y  (TcbMod.set tcbls ptcb (prio, st, m')).\nProof.\n  introv Htc Hr.\n  unfolds in Hr.\n  destruct Hr as (Hr1 & Hr2 & Hr3).\n  destruct Hr1 as (Hra1 & Hra2 & Hra3 & Hra4).\n  destruct Hr2 as (Hrb1 & Hrb2 & Hrb3 & Hrb4).\n  unfolds.\n  splits.\n  unfolds.\n  splits.\n  unfolds.\n  destruct y.\n  intros.\n  eapply Hra1 in H0; eauto.\n  mytac.\n  assert (ptcb = x0 \\/ ptcb <> x0) by tauto.\n  destruct H1.\n  subst.\n  unfold get in *; simpl in *.\n\n  rewrite H0 in Htc.\n  inverts Htc.\n  exists x0.\n  exists x1 m'.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; auto.\n  exists x0.\n  exists x1 x2.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n  unfolds.\n  destruct y.\n  intros.\n  eapply Hra2 in H0; eauto.\n  mytac.\n  assert (ptcb = x0 \\/ ptcb <> x0) by tauto.\n  destruct H1.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H0 in Htc.\n  inverts Htc.\n  exists x0.\n  exists x1 m'.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; auto.\n  exists x0.\n  exists x1 x2.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n  unfolds.\n  destruct y.\n  intros.\n  eapply Hra3 in H0; eauto.\n  mytac.\n  assert (ptcb = x0 \\/ ptcb <> x0) by tauto.\n  destruct H1.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H0 in Htc.\n  inverts Htc.\n  exists x0.\n  exists x1 m'.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; auto.\n  exists x0.\n  exists x1 x2.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n  unfolds.\n  destruct y.\n  intros.\n  eapply Hra4 in H0; eauto.\n  mytac.\n  assert (ptcb = x0 \\/ ptcb <> x0) by tauto.\n  destruct H1.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H0 in Htc.\n  inverts Htc.\n  exists x0.\n  exists x1 m'.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; auto.\n  exists x0.\n  exists x1 x2.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n  unfolds.\n  splits.\n  unfolds.\n  destruct y.\n  intros.\n  assert (ptcb = tid \\/ ptcb <> tid) by tauto. \n  destruct H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  eapply Hrb1; eauto.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; eauto.\n  unfolds.\n  destruct y.\n  intros.\n  assert (ptcb = tid \\/ ptcb <> tid) by tauto. \n  destruct H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  eapply Hrb2; eauto.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; eauto.\n  unfolds.\n  destruct y.\n  intros.\n  assert (ptcb = tid \\/ ptcb <> tid) by tauto. \n  destruct H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  eapply Hrb3; eauto.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; eauto.\n  unfolds.\n  destruct y.\n  intros.\n  assert (ptcb = tid \\/ ptcb <> tid) by tauto. \n  destruct H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  eapply Hrb4; eauto.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; eauto.\n  auto.\nQed.\n\n\nLemma ECBList_P_high_tcb_get_msg_hold:\n  forall  ectrl head tail msgql ecbls tcbls ptcb prio st m m',\n    ECBList_P head tail ectrl msgql ecbls tcbls ->\n    TcbMod.get tcbls ptcb = Some (prio, st, m) ->\n    ECBList_P head tail ectrl msgql ecbls \n              (TcbMod.set tcbls ptcb (prio, st, m')).\nProof.\n  inductions ectrl.\n  intros.\n  simpl in H.\n  mytac.\n  simpl; splits; auto.\n  intros.\n  simpl in H.\n  mytac.\n  destruct msgql; tryfalse.\n  destruct a.\n  mytac.\n  simpl.\n  eexists.\n  splits; eauto.\n\n\n  eapply ecb_etbl_set_hold; eauto.\n  do 3 eexists; splits; eauto.\nQed.\n\n\nLemma TCBList_P_tcb_get_msg_hold :\n    forall ptcb v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 rtbl vl\n           tcbls prio st m m',\n    TCBList_P (Vptr ptcb) ((v1::v2::v3::v4::v5::v6::v7::v8::v9::v10::v11::nil)::vl) rtbl tcbls ->\n    TcbMod.get tcbls ptcb = Some (prio, st, m) ->\n    TCBList_P (Vptr ptcb) ((v1::v2::v3::m'::v5::v6::v7::v8::v9::v10::v11::nil)::vl) rtbl (TcbMod.set tcbls ptcb (prio, st, m')).\nProof.\n  introv Htc Hget.\n  unfolds in Htc.\n  mytac.\n  simpl_hyp.\n  inverts H.\n  fold TCBList_P in H3.\n  unfolds.\n  fold TCBList_P.\n  do 4 eexists; splits; eauto.\n  unfolds; simpl; auto.\n  instantiate (1:=(prio,st,m')).\n  eapply tcbjoin_set; eauto.\n  funfold H2.\n  destruct x2.\n  destruct p.\n   lets Heq : tcbjoin_get H1 Hget.\n  inverts Heq.\n  mytac.\n  simpl_hyp.\n  unfolds.\n  splits; try unfolds; simpl; auto.\n  splits.\n  funfold H4.\n  clear - H.\n  funfold H.\n  unfolds.\n  intros.\n   assert (RdyTCBblk\n        (x0\n         :: v2\n            :: v3\n               :: m\n                  :: v5 :: v6 :: Vint32 prio :: v8 :: v9 :: v10 :: v11 :: nil)\n        rtbl prio0).\n  unfolds.\n  funfold H0; simpl; auto.\n  apply H in H1.\n  destruct H1 as (Ha & Hb & Hc).\n  splits; try unfolds;simpl; eauto.\n  destruct Hc.\n  inverts H1.\n  eexists; eauto.\n  destruct H4 as (_ & Hhl & _).\n  unfolds in Hhl.\n  unfolds.\n  intros.\n  inverts H.\n  assert ( (prio0, rdy, m) = (prio0, rdy, m)) by auto. \n  apply Hhl in H.\n  mytac; try unfolds;simpl; auto.\n  destruct H4 as (_ & _ & Hhl & _).\n  unfolds in Hhl.\n  unfolds.\n  mytac; try unfolds;simpl; auto.\n  intros.\n  simpl_hyp.\n  unfolds in H.\n  assert (WaitTCBblk\n         (x0\n          :: v2\n             :: v3\n                :: m\n                   :: v5\n                      :: V$OS_STAT_RDY\n                         :: Vint32 prio :: v8 :: v9 :: v10 :: v11 :: nil)\n         rtbl prio0 t).\n  funfold H7.\n  unfolds; simpl; auto.\n  apply H in H8.\n  destruct H8.\n  splits; eauto.\n  mytac; eexists; eauto.\n  unfolds; simpl; auto.\n  intros.\n  simpl_hyp.\n  assert ( WaitTCBblk\n         (x0\n          :: v2\n             :: Vptr eid\n                :: m\n                   :: v5\n                      :: V$OS_STAT_SEM\n                         :: Vint32 prio :: v8 :: v9 :: v10 :: v11 :: nil)\n         rtbl prio0 t).\n  funfold H7.\n  unfolds; simpl; eauto.\n  eapply H0 in H8.\n  unfold V_OSTCBStat in H8.\n  unfold  V_OSTCBEventPtr in H8.\n  simpl in H8; eauto.\n  assert (exists m0, (prio, st, m) = (prio0, wait (os_stat_sem eid) t, m0)).\n  eapply H8;eauto.\n  mytac.\n  eexists; eauto.\n  intros.\n  simpl_hyp.\n  assert ( WaitTCBblk\n         (x0\n          :: v2\n             :: Vptr eid\n                :: m\n                   :: v5\n                      :: V$OS_STAT_Q\n                         :: Vint32 prio :: v8 :: v9 :: v10 :: v11 :: nil)\n         rtbl prio0 t).\n  funfold H7; unfolds; simpl;eauto.\n  eapply H4 in H8.\n   unfold V_OSTCBStat in H8.\n  unfold  V_OSTCBEventPtr in H8.\n  simpl in H8; eauto.\n  assert ( exists m0, (prio, st, m) = (prio0, wait (os_stat_q eid) t, m0)).\n  eapply H8; eauto.\n  mytac.\n  eexists; eauto.\n intros.\n  simpl_hyp.\n  assert ( WaitTCBblk\n         (x0\n          :: v2\n             :: Vptr eid\n                :: m\n                   :: v5\n                      :: V$OS_STAT_MBOX\n                         :: Vint32 prio :: v8 :: v9 :: v10 :: v11 :: nil)\n         rtbl prio0 t).\n  funfold H7; unfolds; simpl;eauto.\n  eapply H5 in H8.\n   unfold V_OSTCBStat in H8.\n  unfold  V_OSTCBEventPtr in H8.\n  simpl in H8; eauto.\n  assert ( exists m0, (prio, st, m) = (prio0, wait (os_stat_mbox eid) t, m0)).\n  eapply H8; eauto.\n  mytac.\n  eexists; eauto.\n   intros.\n  simpl_hyp.\n  assert ( WaitTCBblk\n         (x0\n          :: v2\n             :: Vptr eid\n                :: m\n                   :: v5\n                      ::V$OS_STAT_MUTEX\n                         :: Vint32 prio :: v8 :: v9 :: v10 :: v11 :: nil)\n         rtbl prio0 t).\n  funfold H7; unfolds; simpl;eauto.\n  eapply H6 in H8.\n   unfold V_OSTCBStat in H8.\n  unfold  V_OSTCBEventPtr in H8.\n  simpl in H8; eauto.\n  assert ( exists m0, (prio, st, m) = (prio0, wait (os_stat_mutexsem eid) t, m0)).\n  eapply H8; eauto.\n  mytac.\n  eexists; eauto.\n  unfolds.\n  splits;\n  unfolds;\n  intros;\n  inverts H;\n  eapply H4; eauto.\nQed.\n\n\n\nLemma RH_CurTCB_high_get_msg_hold :\n  forall ptcb tcbls prio st m m',\n    RH_CurTCB ptcb tcbls ->\n    TcbMod.get tcbls ptcb = Some (prio, st, m) ->\n    RH_CurTCB ptcb (TcbMod.set tcbls ptcb (prio, st, m')).\nProof.\n  introv Hrh Htc.\n  unfolds in Hrh.\n  mytac.\n  unfolds.\n  unfold get in *; simpl in *.\n  rewrite H in Htc.\n  inverts Htc.\n  exists prio st m'.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; eauto.\nQed.\n\n\n(* absinfer lemmas *)\n(* Lemma absinfer_mbox_pend_block_get_return\n *      : forall (P : asrt) (mqls : EcbMod.map) (qid : addrval) \n *          (v : int32) (p : priority) (t : ostime) (ct : tidspec.A)\n *          (tls : TcbMod.map) (m : msg) (st : taskstatus),\n *        Int.unsigned v <= 65535 ->\n *        can_change_aop P ->\n *        TcbMod.get tls ct = Some (p, st, m) ->\n *        m <> Vnull ->\n *        ⊢  <|| mbox_pend_timeout_err (|Vptr qid :: Vint32 v :: nil|)\n *     ?? mbox_pend_block_get_succ (|Vptr qid :: Vint32 v :: nil|)\n *     ||>\n *   **\n *         HECBList mqls ** HTCBList tls ** HTime t ** HCurTCB ct ** P\n *        ⇒  <|| END (Some (V$ MBOX_PEND_SUCC)) ||>  **\n *          HECBList mqls ** HTCBList tls ** HTime t ** HCurTCB ct ** P\n * .\n * Proof.\n *   infer_part1 1%nat.\n *   infer_part2.\n * Qed.\n * \n * \n * Lemma absinfer_mbox_pend_to_return :\n *    forall P mqls qid v t ct tls st prio,\n *     Int.unsigned v <= 65535 ->\n *     TcbMod.get tls ct = Some (prio, st, Vnull) ->\n *     can_change_aop P ->\n *     absinfer\n *       ( <||\n *     mbox_pend_timeout_err (|Vptr qid :: Vint32 v :: nil|)\n *     ?? mbox_pend_block_get_succ (|Vptr qid :: Vint32 v :: nil|)\n *     ||>  ** \n *            HECBList mqls ** HTCBList tls ** HTime t ** HCurTCB ct ** P) \n *       (<||  END (Some (Vint32 (Int.repr MBOX_PEND_TIMEOUT_ERR)))||>  ** HECBList mqls  ** HTCBList tls ** HTime t ** HCurTCB ct ** P).\n * Proof.\n *   infer_part1 0%nat.\n *   infer_part2.\n * Qed. *)\n\n\n\nLemma ECBList_P_high_tcb_block_hold_mbox:\n  forall  ectrl head tail msgql ecbls tcbls ptcb prio  m qid time m' ,\n    ECBList_P head tail ectrl msgql ecbls tcbls ->\n    TcbMod.get tcbls ptcb = Some (prio, rdy, m) ->\n    EcbMod.get ecbls qid = None ->\n    ECBList_P head tail ectrl msgql ecbls \n              (TcbMod.set tcbls ptcb (prio, wait (os_stat_mbox qid) time, m')).\nProof.\n  inductions ectrl.\n  intros.\n  simpl.\n  simpl in H.\n  mytac; auto.\n  intros.\n  simpl in H.\n  mytac.\n  destruct msgql; tryfalse.\n  destruct a.\n  mytac.\n  simpl.\n  exists x.\n  splits; auto.\n  unfolds.\n  destruct H2 as (Hr1 & Hr2 & Hr3).\n  destruct Hr1 as (Hra3 & Hra2 & Hra1 & Hra4).\n  destruct Hr2 as (Hrb3 & Hrb2 & Hrb1 & Hrb4).\n  simpl in Hr3.\n  splits.\n  unfolds.\n  splits.\nFocus 3.\n{\n  unfolds.\n  intros.\n  eapply Hra1 in H6;eauto.\n  mytac.\n  assert (x3 = ptcb \\/ x3 <> ptcb) by tauto.\n  destruct H7.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H0 in H6.\n  inverts H6.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n}\nUnfocus.\nFocus 2.\n{\n  unfolds.\n  intros.\n  eapply Hra2 in H6;eauto.\n  mytac.\n  assert (x3 = ptcb \\/ x3 <> ptcb) by tauto.\n  destruct H7.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H0 in H6.\n  inverts H6.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n}\nUnfocus.\n{\n  unfolds.\n  intros.\n  eapply Hra3 in H6;eauto.\n  mytac.\n  assert (x3 = ptcb \\/ x3 <> ptcb) by tauto.\n  destruct H7.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H0 in H6.\n  inverts H6.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n}\n{\n  unfolds.\n  intros.\n  eapply Hra4 in H6;eauto.\n  mytac.\n  assert (x3 = ptcb \\/ x3 <> ptcb) by tauto.\n  destruct H7.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H0 in H6.\n  inverts H6.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n}\n  unfolds.\n  splits.\nFocus 3.\n{\n  unfolds.\n  intros.\n  assert (tid = ptcb \\/ tid <> ptcb) by tauto.\n  destruct H6.\n  subst.\n  rewrite TcbMod.set_sem in H2.\n  rewrite tidspec.eq_beq_true in H2; eauto.\n  inverts H2.\n  apply ecbmod_joinsig_get in H3.\n  rewrite H3 in H1.\n  tryfalse.\n  rewrite TcbMod.set_sem in H2.\n  rewrite tidspec.neq_beq_false in H2; eauto.\n}\nUnfocus.\n\n  unfolds.\n  intros.\n  assert (tid = ptcb \\/ tid <> ptcb) by tauto.\n  destruct H6.\n  subst.\n  rewrite TcbMod.set_sem in H2.\n  rewrite tidspec.eq_beq_true in H2; eauto.\n  inverts H2.\n  rewrite TcbMod.set_sem in H2.\n  rewrite tidspec.neq_beq_false in H2; eauto.\n  unfolds.\n  intros.\n  assert (tid = ptcb \\/ tid <> ptcb) by tauto.\n  destruct H6.\n  subst.\n  rewrite TcbMod.set_sem in H2.\n  rewrite tidspec.eq_beq_true in H2; eauto.\n  inverts H2.\n  rewrite TcbMod.set_sem in H2.\n  rewrite tidspec.neq_beq_false in H2; eauto.\n   unfolds.\n  intros.\n  assert (tid = ptcb \\/ tid <> ptcb) by tauto.\n  destruct H6.\n  subst.\n  rewrite TcbMod.set_sem in H2.\n  rewrite tidspec.eq_beq_true in H2; eauto.\n  inverts H2.\n  rewrite TcbMod.set_sem in H2.\n  rewrite tidspec.neq_beq_false in H2; eauto.\n  simpl; auto.\n  do 3 eexists; splits; eauto.\n  eapply IHectrl; eauto.\n  eapply  ecbmod_joinsig_get_none; eauto.\nQed.\n\nLemma ejoin_get_none_r : forall ma mb mc x a, EcbMod.get ma x = Some a -> EcbMod.join ma mb mc -> EcbMod.get mb x = None.\nProof.\n  intros.\n  unfolds in H0.\n  lets adf : H0 x.\n  destruct (EcbMod.get ma x).\n  destruct (EcbMod.get mb x).\n  tryfalse.\n  auto.\n  destruct (EcbMod.get mb x).\n  tryfalse.\n  auto.\nQed.\n\nLemma ejoin_get_none_l : forall ma mb mc x a, EcbMod.get mb x = Some a -> EcbMod.join ma mb mc -> EcbMod.get ma x = None.\nProof.\n  intros.\n  apply EcbMod.join_comm in H0.\n  eapply ejoin_get_none_r; eauto.\nQed.\n\n\nLemma R_ECB_ETbl_P_high_tcb_block_hold:\n  forall (l : addrval) (vl : vallist) (egrp : int32) \n    (v2 v3 v4 v5 : val) (etbl : vallist) (tcbls : TcbMod.map)\n    (ptcb : tidspec.A) (prio : int32) (st : taskstatus) \n    (m m' : msg) (y bity bitx ey time : int32) (av : addrval),\n  Int.unsigned prio < 64 ->\n  R_PrioTbl_P vl tcbls av ->\n  R_ECB_ETbl_P l\n    (V$OS_EVENT_TYPE_MBOX :: Vint32 egrp :: v2 :: v3 :: v4 :: v5 :: nil, etbl)\n    tcbls ->\n  TcbMod.get tcbls ptcb = Some (prio, st, m) ->\n  y = Int.shru prio ($ 3) ->\n  bity = Int.shl ($ 1) y ->\n  bitx = Int.shl ($ 1) (prio&ᵢ$ 7) ->\n  nth_val ∘(Int.unsigned y) etbl = Some (Vint32 ey) ->\n  R_ECB_ETbl_P l\n    (V$OS_EVENT_TYPE_MBOX\n     :: Vint32 (Int.or egrp bity) :: v2 :: v3 :: v4 :: v5 :: nil,\n    update_nth_val ∘(Int.unsigned y) etbl (Vint32 (Int.or ey bitx)))\n    (TcbMod.set tcbls ptcb (prio, wait (os_stat_mbox l) time, m'))\n.\nProof.\n  introv Hran Hrs  Hre Htc Hy Hb1 Hb2 Hnth.\n  subst.\n  unfolds in Hre.\n  destruct Hre as (Hre1 & Hre2 & Het).\n  unfolds.\n  splits.\n  unfolds.\n  splits.\n  Focus 3.\n{\n  unfolds.\n  intros.\n  destruct Hre1 as (_ & _ &Hre1 & _).\n  destruct Hre2 as (_ & _ & Hre2 & _).\n  unfolds in Hre1.\n  unfolds in Hre2.\n  assert (prio = $ prio0 \\/ prio <> $ prio0) by tauto.\n  destruct H1.\n  subst.\n  exists ptcb time m'.\n  rewrite TcbMod.set_sem.\n  erewrite tidspec.eq_beq_true; eauto.\n  lets Hres : prio_wt_inq_keep Hran H1 Hnth .\n  destruct Hres.\n  apply H2 in H.\n  apply Hre1 in H.\n  mytac.\n  exists x x0 x1.\n  assert (x = ptcb \\/ x <> ptcb) by tauto.\n  destruct H4.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite Htc in H.\n  inverts H.\n  tryfalse.\n  rewrite TcbMod.set_sem.\n  erewrite tidspec.neq_beq_false; eauto.\n  unfolds. \n  simpl; auto.\n}\nUnfocus.\nFocus 2.\n{\n  unfolds.\n  intros.\n  usimpl H0.\n}\nUnfocus.\n{\n  unfolds.\n  intros.\n  usimpl H0.\n}\n{\n   unfolds.\n  intros.\n  usimpl H0.\n}\n  unfolds.\n  splits.\nFocus 3.\n{\n  unfolds.\n  intros.\n  assert (tid = ptcb \\/ tid <> ptcb) by tauto.  \n  destruct H0.\n  subst.\n  splits.\n  rewrite TcbMod.set_sem in H.\n  erewrite tidspec.eq_beq_true in H; eauto.\n  inverts H.\n  unfolds.\n  rewrite Int.repr_unsigned.\n  exists ( prio0&ᵢ$ 7).\n  exists (Int.shru prio0 ($3)).\n  exists ((Int.or ey ($ 1<<ᵢ(prio0&ᵢ$ 7)))).\n  splits; eauto.\n  clear - Hran.\n  int auto.\n  eapply update_nth; eauto.\n  rewrite Int.and_commut.\n  rewrite Int.or_commut.\n  unfold Int.one.\n  rewrite Int.and_or_absorb.\n  auto.\n  unfolds; simpl; auto.\n  rewrite TcbMod.set_sem in H.\n  erewrite tidspec.neq_beq_false in H; eauto.\n  unfolds in Hre2.\n  destruct Hre2 as (_ & _ & Hre2 & _).\n  lets Hasd : Hre2  H.\n   destruct Hasd as (Has1 & Has2).\n  splits.\n  eapply prio_wt_inq_keep; eauto.\n  rewrite Int.repr_unsigned.\n  unfolds  in Hrs.\n  destruct Hrs.\n  destruct H2.\n  unfolds in H3.\n  lets Hdd : H3 H0 H Htc.\n  eauto.\n  unfolds; simpl; auto.\n}\nUnfocus.\nFocus 2.\n{\n   unfolds.\n\n  intros.\n  assert (tid = ptcb \\/ tid <> ptcb) by tauto.  \n  destruct H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  erewrite tidspec.eq_beq_true in H; eauto.\n  inverts H.\n  rewrite TcbMod.set_sem in H.\n  erewrite tidspec.neq_beq_false in H; eauto.\n  destruct Hre2 as (_&Hre2&_).\n  apply Hre2 in H.\n  destruct H.\n  usimpl H1.\n}\nUnfocus.\n{\n   unfolds.\n  intros.\n  assert (tid = ptcb \\/ tid <> ptcb) by tauto.  \n  destruct H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  erewrite tidspec.eq_beq_true in H; eauto.\n  inverts H.\n  rewrite TcbMod.set_sem in H.\n  erewrite tidspec.neq_beq_false in H; eauto.\n  destruct Hre2 as (Hre2&_).\n  apply Hre2 in H.\n  destruct H.\n  usimpl H1.\n}\n   unfolds.\n  intros.\n  assert (tid = ptcb \\/ tid <> ptcb) by tauto.  \n  destruct H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  erewrite tidspec.eq_beq_true in H; eauto.\n  inverts H.\n  rewrite TcbMod.set_sem in H.\n  erewrite tidspec.neq_beq_false in H; eauto.\n  destruct Hre2 as (_&_& _ &Hre2).\n  apply Hre2 in H.\n  destruct H.\n  usimpl H1.\n  simpl.\n  unfolds.\n  branch 3.\n  unfolds; simpl; auto.\nQed.\n\n\n\n(**)\n(* TODO *)\nLemma TCBList_P_tcb_block_hold :\n    forall ptcb v1 v2 v3 v4 v5 v6 v8 v9 v10 v11 rtbl vl\n           tcbls prio st m qid time ry,\n    TCBList_P (Vptr ptcb) ((v1::v2::v3::v4::v5::(Vint32 v6)::(Vint32 prio)::v8::(Vint32 v9)::(Vint32 v10)::v11::nil)::vl) rtbl tcbls ->\n    TcbMod.get tcbls ptcb = Some (prio, st, m) ->\n    prio_neq_cur tcbls ptcb ( prio) ->\n    st = rdy \\/ (exists n, st = wait os_stat_time n) -> \n    nth_val (nat_of_Z (Int.unsigned v9)) rtbl = Some (Vint32 ry) ->\n    TCBList_P (Vptr ptcb) ((v1::v2::(Vptr qid)::Vnull::(Vint32 time)::(Vint32 ($ OS_STAT_MBOX))::(Vint32 prio)::v8::(Vint32 v9)::(Vint32 v10)::v11::nil)::vl) \n(update_nth_val ∘(Int.unsigned v9) rtbl (Vint32 (Int.and ry (Int.not v10)))) \n (TcbMod.set tcbls ptcb ( prio, wait (os_stat_mbox qid) ( time), Vnull)).\nProof.\n  introv  Htcb Htm Hst Hprio Hnth.\n  unfolds in Htcb;fold TCBList_P in Htcb.\n  mytac.\n  inverts H.\n  unfolds in H0.\n  simpl in H0; inverts H0.\n  unfolds.\n  fold TCBList_P.\n  exists x x0.\n  exists x1.\n  exists (prio,wait (os_stat_mbox qid) time,Vnull).\n  splits; eauto.\n  eapply tcbjoin_set; eauto.\n{\n  unfolds in H2.\n  destruct x2.\n  destruct p.\n  mytac.\n  unfolds in H0.\n  simpl in H0; inverts H0.\n  unfolds in H;simpl in H; inverts H.\n  unfolds.\n  split.  \n  unfolds.\n  simpl.\n  auto.\n  funfold H2.\n  splits.\n  auto.\n  unfolds.\n  do 6 eexists; splits; try unfolds; simpl; eauto.\n  splits; eauto.\n  eexists.\n  splits.\n  unfolds;simpl; eauto.\n  introv Hf.\n  inverts Hf.\n  lets Hexa : tcbjoin_get H1 Htm.\n  inverts Hexa.\n  unfolds in H4.\n  split.\n  unfolds.\n  intros.\n  simpl_hyp.\n  unfolds in H.\n  destruct H.\n  simpl_hyp.\n  unfolds in H0.\n  assert (prio&ᵢ$ 7 = prio&ᵢ$ 7) by auto.\n  assert (Int.shru ( prio) ($ 3) =Int.shru (prio) ($ 3)) by auto.\n  assert ( nth_val ∘(Int.unsigned (Int.shru (prio) ($ 3)))\n         (update_nth_val ∘(Int.unsigned (Int.shru (prio) ($ 3))) rtbl\n            (Vint32 (ry&ᵢInt.not ($ 1<<ᵢ(prio&ᵢ$ 7))))) = \n           Some (Vint32  (ry&ᵢInt.not ($ 1<<ᵢ(prio&ᵢ$ 7))))).\n  eapply update_nth; eauto.\n  lets Hr: H0 H H2 H5.\n  rewrite Int.and_assoc in Hr.\n  assert (Int.not ($ 1<<ᵢ(prio&ᵢ$ 7))&ᵢ($ 1<<ᵢ(prio&ᵢ$ 7)) = $ 0).\n  rewrite Int.and_commut.\n  rewrite Int.and_not_self.\n  auto.\n  rewrite H6  in Hr.\n  rewrite Int.and_zero in Hr.\n  assert ( $ 1<<ᵢ(prio&ᵢ$ 7) <> $ 0) by (apply  math_prop_neq_zero2; try omega).\n  unfold Int.zero in Hr.\n  tryfalse.\n  split.\n  unfolds.\n  intros.\n  inverts H.\n  split.\n  unfolds.\n  split.\n  unfolds.\n  intros.\n  inverts H0.\n  split.\n  unfolds.\n  intros.\n  inverts H0.\n\n  split.\n  unfolds.\n  intros.\n  inverts H0.\n  split.\n  unfolds.\n  intros.\n\n\n  unfolds in H.\n  mytac.\n  simpl_hyp.\n  eexists.\n  eauto.\n  unfolds.\n  \n\n  intros.\n  inverts H0.\n\n  unfolds.\n  split.\n  unfolds.\n  intros.\n  inverts H.\n  split.\n  unfolds.\n  intros.\n  inverts H.\n  split.\n  unfolds.\n  intros.\n  inverts H.\n  splits; try unfolds ; simpl ; auto.\n  split.\n  inverts H.\n  unfolds; simpl ; auto.\n  splits; try unfolds; simpl ; auto.\n\n  intros.\n  subst.\n  apply nth_upd_eq in H2.\n  inverts H2.\n  rewrite Int.and_assoc.\n  assert (Int.not ($ 1<<ᵢ(prio&ᵢ$ 7))&ᵢ($ 1<<ᵢ(prio&ᵢ$ 7)) = $ 0).\n  rewrite Int.and_commut.\n  rewrite Int.and_not_self.\n  auto.\n  rewrite H.\n  rewrite  Int.and_zero.\n  auto.\n  split.\n  unfolds.\n  intros.\n  inverts H.\n  split.\n  inverts H.\n  unfolds; simpl; auto.\n  intros.\n  inverts H.\n}\n  unfolds in H2.\n  destruct x2.\n  destruct p.\n  mytac; simpl_hyp.\n  funfold H2.\n  eapply update_rtbl_tcblist_hold; eauto.\n  unfolds in Hst.\n  intros.\n  lets Has : tcbjoin_get_getneq H1 H.\n  destruct Has.\n  eapply Hst; eauto.\nQed.\n\nLemma RH_CurTCB_high_block_hold_mbox :\n  forall ptcb tcbls prio st m qid time m',\n    RH_CurTCB ptcb tcbls ->\n    TcbMod.get tcbls ptcb = Some (prio, st, m) ->\n    RH_CurTCB ptcb (TcbMod.set tcbls ptcb\n        (prio, wait (os_stat_mbox qid) time, m')).\nProof.\n  introv Hr Ht.\n  unfolds in Hr.\n  mytac.\n  unfold get in *; simpl in *.\n  rewrite H in Ht.\n  inverts Ht.\n  unfolds.\n  do 3 eexists.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; eauto.\nQed.\n\nLemma RH_TCBList_ECBList_P_high_block_hold_mbox :\n  forall ecbls tcbls pcur qid m ml wl prio  time m',\n    RH_TCBList_ECBList_P ecbls tcbls pcur ->\n    EcbMod.get ecbls qid = Some (absmbox ml, wl) ->\n    TcbMod.get tcbls pcur = Some (prio, rdy, m) ->\n    RH_TCBList_ECBList_P (EcbMod.set ecbls qid (absmbox ml, pcur::wl)) (TcbMod.set tcbls pcur (prio, wait (os_stat_mbox qid) time, m')) pcur. \nProof.\n  introv Hr Ht He.\n  unfolds in Hr.\n  destruct Hr as (Hr3 & Hr2 & Hr1 & Hr4).\n  unfolds.\n  splits.\n  Focus 3.\n{\n  unfolds.\n  splits.\n  intros.\n  mytac.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H1.\n  subst.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  simpl in H0.\n  destruct H0.\n  do 3 eexists;\n    rewrite TcbMod.set_sem ;\n    rewrite tidspec.eq_beq_true; auto.\n  assert (EcbMod.get ecbls eid = Some (absmbox n, wl) /\\ In tid wl) by eauto.\n  apply Hr1 in H0.\n  mytac.\n  assert (pcur = tid \\/ pcur <> tid) by tauto.\n  destruct  H1.\n  do 3 eexists;\n    rewrite TcbMod.set_sem ;\n    rewrite tidspec.eq_beq_true; auto.\n  do 3 eexists;\n    rewrite TcbMod.set_sem ;\n    rewrite tidspec.neq_beq_false; eauto.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; auto.\n  assert (EcbMod.get ecbls eid = Some (absmbox n, wls) /\\ In tid wls) by eauto.\n  apply Hr1 in H2.\n  mytac.\n  assert (pcur = tid \\/ pcur <> tid) by tauto.\n  destruct  H3.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H2 in He.\n  inverts He. \n  do 3 eexists;\n    rewrite TcbMod.set_sem ;\n    rewrite tidspec.neq_beq_false; eauto.\n  intros.\n  assert (pcur = tid \\/ pcur <> tid) by tauto.\n  destruct  H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; eauto.\n  inverts H.\n  exists ml.\n  exists (tid::wl).\n  splits; eauto.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; eauto.\n  simpl; left; auto.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; eauto.\n  apply Hr1 in H.\n  mytac.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H2.\n  subst.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; auto.\n  do 2 eexists; splits; eauto.\n  unfold get in *; simpl in *.\n  rewrite H in Ht.\n  inverts Ht.\n  simpl.\n  right; auto.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 2 eexists; splits; eauto.\n}\n  Unfocus.\n  Focus 2.\n{\n  splits.\n  intros.\n  mytac.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H1.\n  subst.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; auto.\n  assert (EcbMod.get ecbls eid =Some (abssem n, wls) /\\ In tid wls) by eauto.\n  apply Hr2 in H2.\n  mytac.\n  assert (pcur = tid \\/ pcur <> tid) by tauto.\n  destruct  H3.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H2 in He.\n  inverts He. \n  do 3 eexists;\n    rewrite TcbMod.set_sem ;\n    rewrite tidspec.neq_beq_false; eauto.\n  intros.\n  assert (pcur = tid \\/ pcur <> tid) by tauto.\n  destruct  H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; eauto.\n  inverts H.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; eauto.\n  apply Hr2 in H.\n  mytac.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H2.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H in Ht.\n  inverts Ht.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 2 eexists; splits; eauto.\n}\n  Unfocus.\n{\n  splits.\n  intros.\n  mytac.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H1.\n  subst.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; auto.\n  assert (EcbMod.get ecbls eid = Some (absmsgq x y, qwaitset) /\\ In tid qwaitset) by eauto.\n  apply Hr3 in H2.\n  mytac.\n  assert (pcur = tid \\/ pcur <> tid) by tauto.\n  destruct  H3.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H2 in He.\n  inverts He. \n  do 3 eexists;\n    rewrite TcbMod.set_sem ;\n    rewrite tidspec.neq_beq_false; eauto.\n  intros.\n  assert (pcur = tid \\/ pcur <> tid) by tauto.\n  destruct  H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; eauto.\n  inverts H.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; eauto.\n  apply Hr3 in H.\n  mytac.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H2.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H in Ht.\n  inverts Ht.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists; splits; eauto.\n}\n{\n  splits.\n  intros.\n  mytac.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H1.\n  subst.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; auto.\n  inverts H.\n  rewrite EcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; auto.\n  assert (EcbMod.get ecbls eid = Some (absmutexsem n1 n2, wls) /\\ In tid wls) by eauto.\n  apply Hr4 in H2.\n  mytac.\n  assert (pcur = tid \\/ pcur <> tid) by tauto.\n  destruct  H3.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H2 in He.\n  inverts He. \n  do 3 eexists;\n    rewrite TcbMod.set_sem ;\n    rewrite tidspec.neq_beq_false; eauto.\n  intros.\n  assert (pcur = tid \\/ pcur <> tid) by tauto.\n  destruct  H0.\n  subst.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.eq_beq_true in H; eauto.\n  inverts H.\n  rewrite TcbMod.set_sem in H.\n  rewrite tidspec.neq_beq_false in H; eauto.\n  apply Hr4 in H.\n  mytac.\n  assert (qid  = eid \\/ qid <> eid) by tauto.\n  destruct H2.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H in Ht.\n  inverts Ht.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists; splits; eauto.\n  apply Mutex_owner_hold_for_set_tcb; eauto.\n  eapply Mutex_owner_set; eauto.\n  intro; mytac.\n  unfolds in Hr4.\n  mytac.\n  auto.\n}\nQed.\n\n\nLemma TcbMod_set_R_PrioTbl_P_hold :\n  (*OSQPendPure*)\n  forall ptbl tcbls ptcb pr st m st' m' av,\n    R_PrioTbl_P ptbl tcbls av ->\n    TcbMod.get tcbls ptcb = Some (pr, st, m) ->\n    R_PrioTbl_P ptbl (TcbMod.set tcbls ptcb (pr,st',m')) av.\nProof.\n  intros.\n  unfold R_PrioTbl_P in *.\n  mytac.\n  intros.\n  lets H100 : H H3 H4 H5.\n  mytac.\n  rewrite TcbMod.set_sem.\n  unfold get in *; simpl in *.\n  rewrite H6.\n  remember (tidspec.beq ptcb tcbid) as bool; destruct bool.\n  symmetry in Heqbool; apply tidspec.beq_true_eq in Heqbool.\n  subst.\n  rewrite H0 in H6.  \n  inverts H6.\n  eauto.\n  eauto.\n  intros.\n  rewrite TcbMod.set_sem in H3.\n  remember (tidspec.beq ptcb tcbid) as bool; destruct bool.\n  inverts H3.\n  symmetry in Heqbool; apply tidspec.beq_true_eq in Heqbool.\n  subst.\n  eapply H1; eauto.\n  eapply H1; eauto.\n  eapply  R_Prio_NoChange_Prio_hold; eauto.\nQed.\n\n\n\nLemma TCBList_P_tcb_block_hold'' :\n  (*OSQPendPure*)\n  forall v ptcb rtbl vl y bitx\n         tcbls prio ry x1 tcs tcs' t m,\n    0 <= Int.unsigned prio < 64 ->\n    TcbMod.join (TcbMod.sig ptcb (prio, t, m)) x1 tcs ->\n    TcbMod.join tcbls tcs tcs' -> \n    TCBList_P v vl rtbl tcbls ->\n    y = Int.shru prio ($ 3) ->\n    bitx = ($ 1) <<ᵢ (Int.and prio ($ 7)) ->\n    prio_neq_cur tcbls ptcb  prio ->\n    nth_val (nat_of_Z (Int.unsigned y)) rtbl = Some (Vint32 ry) ->\n    TCBList_P v vl (update_nth_val ∘(Int.unsigned y) rtbl (Vint32 (Int.and ry (Int.not bitx)))) tcbls.\nProof.\n  introv Hran Htc Hy Hb Hpro Hnth.\n  eapply TCBList_P_tcb_dly_hold'; eauto.\nQed.\n\n\nLemma TCBList_P_tcb_block_hold':\n  (*OSQPendPure*)\n  forall v ptcb rtbl vl y bitx\n         tcbls prio ry tcs tcs' t m,\n    0 <= Int.unsigned prio < 64 ->\n    TcbMod.get  tcs ptcb = Some (prio, t, m)->\n    TcbMod.join tcbls tcs tcs' -> \n    TCBList_P v vl rtbl tcbls ->\n    y = Int.shru prio ($ 3) ->\n    bitx = ($ 1) <<ᵢ (Int.and prio ($ 7)) ->\n    prio_neq_cur tcbls ptcb  prio ->\n    nth_val (nat_of_Z (Int.unsigned y)) rtbl = Some (Vint32 ry) ->\n    TCBList_P v vl (update_nth_val ∘(Int.unsigned y) rtbl (Vint32 (Int.and ry (Int.not bitx)))) tcbls.\nProof.\n  intros.\n  lets Hx:tcb_get_join H0.\n  mytac.\n  eapply TCBList_P_tcb_block_hold'';eauto.\nQed.\n\n\n\n(* absinfer lemma *)\n(* Lemma absinfer_mbox_post_exwt_succ: \n *   forall P mqls x v wl tls t ct p st m m'  t' , \n *     can_change_aop P ->  \n *     EcbMod.get mqls x = Some (absmbox m ,wl) ->\n *     ~ wl=nil ->\n *     GetHWait tls wl t' ->\n *     TcbMod.get tls t' = Some (p,st, m') ->\n *     absinfer\n *       ( <|| mbox_post (Vptr x :: Vptr v :: nil) ||>  ** \n *             HECBList mqls ** HTCBList tls ** HTime t ** HCurTCB ct ** P) \n *       (<|| isched;;END (Some (Vint32 (Int.repr NO_ERR))) ||>  ** HECBList (EcbMod.set mqls x (absmbox m, (remove_tid t' wl))) ** HTCBList (TcbMod.set tls t' (p,rdy , (Vptr v)) ) ** HTime t ** HCurTCB ct ** P).\n * Proof.\n *   unfold mbox_post; intros.\n *   infer_branch 5%nat.\n *   eapply absinfer_trans.\n *   Focus 2.\n *   eapply absinfer_seq_end.\n *   3:sep auto.\n *   can_change_aop_solver.\n *   can_change_aop_solver.\n *   instantiate (1:= (Some (V$NO_ERR))).\n *   eapply absinfer_seq.\n *   can_change_aop_solver.\n *   can_change_aop_solver.\n *   tri_infer_prim.\n * \n *   infer_part2.\n * Qed. *)\n\nLemma mbox_rh_tcblist_ecblist_p_hold: forall v'34 v'35 v'37 v w m m2, EcbMod.get v'34 v = Some (absmbox m, w) ->RH_TCBList_ECBList_P v'34 v'35 v'37 ->\n                                                                      RH_TCBList_ECBList_P\n                                                                        (EcbMod.set v'34 v (absmbox m2, w)) v'35 v'37.\nProof.\n  intros.\n  unfolds in H0.\n  mytac.\n  unfolds.\n  mytac; [clear -H H0| clear -H H1; rename H1 into H0|clear -H H2; rename H2 into H0| clear -H H3; rename H3 into H0]; unfolds; unfolds in H0; mytac; intros; unfold get in *; simpl in *;\n\n  try solve [eapply H0;\n              mytac; eauto;\n              assert ( eid = v \\/ eid <> v)  as aa by tauto; destruct aa;[subst;\n                                                                           rewrite EcbMod.set_a_get_a in e;[\n                                                                             inversion e|\n                                                                             apply CltEnvMod.beq_refl] \n                                                                         |\n                                                                         rewrite EcbMod.set_a_get_a' in e;[\n                                                                             eauto|\n                                                                             apply tidspec.neq_beq_false];\n                                                                         auto]]\n  ;try solve[\n         lets aaa : H1 H2;\n         mytac;\n         assert ( eid = v \\/ eid <> v)  as aa by tauto; destruct aa;[subst eid;rewrite H in H3;inversion H3|\n                                                                     rewrite EcbMod.set_a_get_a';[\n                                                                         rewrite H3;\n                                                                         eauto|\n                                                                         apply tidspec.neq_beq_false;\n                                                                           auto]]\n       ]\n  .\n\n  assert (eid = v \\/ eid <> v) as aa by tauto; destruct aa;[subst eid; rewrite EcbMod.set_a_get_a in H2|idtac].\n  elim H2; intros.\n\n  inversion H3.\n  subst.\n  eapply H0.\n  splits; eauto.\n  apply CltEnvMod.beq_refl.\n  eapply H0.\n  rewrite EcbMod.set_a_get_a' in H2.\n  eauto.\n  apply tidspec.neq_beq_false; auto.\n\n  assert (eid = v \\/ eid <> v) as aa by tauto; destruct aa. \n  subst.\n  rewrite EcbMod.set_a_get_a.\n  repeat eexists.\n  lets aaa : H1 H2.\n  mytac; auto.\n  rewrite H in H3.\n  inversion H3.\n  subst.\n  auto.\n  apply CltEnvMod.beq_refl.\n\n  rewrite EcbMod.set_a_get_a'.\n  eapply H1.\n  eauto.\n  apply tidspec.neq_beq_false; auto.\n  \n  assert ( v= eid \\/ v<> eid) by tauto.\n  elim H4; intros.\n  subst eid.\n\n  lets aaa : H1 H3.\n  simpljoin.\n  rewrite H5 in H.\n  inverts H.\n \n  rewrite EcbMod.set_a_get_a' .\n  eapply H1; eauto.\n  go.\n  eapply Mutex_owner_set.\n  intro; mytac.\n  auto.\n\nQed.\n\n\nLemma post_exwt_succ_pre_mbox\n     : forall (v'36 v'13 : vallist) (v'12 : int32) \n         (v'32 : block) (v'15 : int32) (v'24 : block) \n         (v'35 v'0 : val) (v'8 : tid) (v'9 v'11 : EcbMod.map)\n         (x : val) (x0 : maxlen) (x1 : waitset)\n         (v'6 v'10 : EcbMod.map) (v'38 v'69 v'39 : int32) \n         (v'58 : block) (a : priority) (b : taskstatus) \n         (c :msg) (v'62 v'7 : TcbMod.map) \n         (vhold : addrval),\n       v'12 <> Int.zero ->\n       R_PrioTbl_P v'36 v'7 vhold ->\n       RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n       R_ECB_ETbl_P (v'32, Int.zero)\n         (V$OS_EVENT_TYPE_MBOX\n          :: Vint32 v'12\n             :: Vint32 v'15 :: Vptr (v'24, Int.zero) :: v'35 :: v'0 :: nil,\n         v'13) v'7 ->\n       RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n       EcbMod.join v'9 v'10 v'11 ->\n       EcbMod.joinsig (v'32, Int.zero) (absmbox x , x1) v'6 v'10 ->\n       Int.unsigned v'12 <= 255 ->\n       array_type_vallist_match Int8u v'13 ->\n       length v'13 = ∘OS_EVENT_TBL_SIZE ->\n       nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n       Int.unsigned v'38 <= 7 ->\n       nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n       Int.unsigned v'69 <= 255 ->\n       nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n       Int.unsigned v'39 <= 7 ->\n       nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 =\n       Vptr (v'58, Int.zero) ->\n       TcbJoin (v'58, Int.zero) (a, b, c) v'62 v'7 ->\n       a = (v'38<<ᵢ$ 3)+ᵢv'39/\\ b<> rdy /\\\n       x1 <> nil /\\\n       GetHWait v'7 x1 (v'58, Int.zero) /\\\n       TcbMod.get v'7 (v'58, Int.zero) = Some (a, b, c)\n.\nProof.\n  intros.\n  lets Hs :  tcbjoin_get_a  H16.\n  unfolds in H3.\n  unfolds in H1.\n  unfolds in H0.\n  unfolds in H2.\n  destruct H2.\n  destruct H17 as (H17&Htype).\n  unfolds in H2.\n  unfolds in H17.\n  lets Hg : EcbMod.join_joinsig_get H4 H5.\n  clear H4 H5.\n  clear H16.\n  assert ( Int.unsigned v'38 < 8) as Hx by omega.\n  assert (Int.unsigned v'39 < 8) as Hy by omega.\n  clear H10 H12.\n  lets Hrs : math_xy_prio_cons Hx Hy.\n  unfold nat_of_Z in H0.\n  destruct H0 as (Hpr1 & Hpr2).\n  assert ((v'58, Int.zero) <> vhold) as Hnvhold.\n  destruct Hpr2.\n  apply H0 in Hs.\n  destruct Hs;auto.\n  lets Hnth : nth_val'_imp_nth_val_vptr H15.\n  lets Hsd : Hpr1 Hrs Hnth.\n  destruct Hsd as (st & m & Hst);auto.\n  unfold get in *; simpl in *.\n\n  rewrite Hs in Hst.\n  inverts Hst.\n  assert (Int.shru ((v'38<<ᵢ$ 3)+ᵢv'39) ($ 3)= v'38).\n  eapply math_shrl_3_eq; eauto.\n  eapply nat_8_range_conver; eauto.\n  assert ( (Z.to_nat (Int.unsigned v'38))  < length v'13)%nat.\n  rewrite H8.\n  simpl.\n  unfold Pos.to_nat; simpl.\n  clear - Hx.\n  mauto.\n  lets Has : array_int8u_nth_lt_len H7 H4.\n  destruct Has as (i & Hnthz & Hinsa).\n  rewrite H11 in Hnthz.\n  inverts Hnthz.\n  assert ((((v'38<<ᵢ$ 3)+ᵢv'39)&ᵢ$ 7) = v'39).\n  eapply math_8range_eqy; eauto.\n  eapply  nat_8_range_conver; eauto.\n  apply nth_val'_imp_nth_val_int in H11.\n  assert ( Vint32 v'12 = Vint32 v'12) by auto.\n  lets Hzs : H1 H11 H10.\n  eapply  nat_8_range_conver; eauto.\n  destruct Hzs.\n  lets Has : math_8_255_eq H6 H9 H.\n  assert (i <> $ 0).\n  assert ($ 1<<ᵢ$ Z.of_nat ∘(Int.unsigned v'38) = $ 1<<ᵢv'38).\n  clear -Hx.\n  mauto.\n  rewrite H18 in H16.\n  apply H16 in Has.\n  apply ltu_eq_false in Has.\n  pose (Int.eq_spec i ($0)).\n  rewrite Has in y.\n  auto.\n  assert (PrioWaitInQ (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39)) v'13).\n  unfolds.\n  rewrite Int.repr_unsigned in *.\n  exists ( ((v'38<<ᵢ$ 3)+ᵢv'39)&ᵢ$ 7 ).\n  exists (Int.shru ((v'38<<ᵢ$ 3)+ᵢv'39) ($ 3) ).\n  rewrite H0 in *.\n  exists i.\n  splits; eauto.\n  rewrite H5.\n  eapply math_8_255_eq; eauto.\n  destruct H2 as (H2'&H2''&H2&Hres).\n  lets Hes : H2 H19.\n  unfold V_OSEventType in Hes.\n  simpl nth_val in Hes.\n  assert (Some (V$OS_EVENT_TYPE_MBOX) = Some (V$OS_EVENT_TYPE_MBOX)) by auto.\n  apply Hes in H20.\n  clear Hes.\n  rename H20 into Hes.\n  destruct Hes as (td & nn &mm & Hge).\n  destruct Hpr2 as (Hpr2 & Hpr3).\n  unfolds in Hpr3.\n  assert (td = (v'58, Int.zero)  \\/ td <> (v'58, Int.zero) ) by tauto.\n  destruct H20.\n  Focus 2.\n  lets Hass : Hpr3 H20 Hge Hs.\n  rewrite Int.repr_unsigned in *.\n  tryfalse.\n  rewrite Int.repr_unsigned in *.\n  subst td.\n  unfold get in *; simpl in *.\n  rewrite Hs in Hge.\n  inverts Hge.\n  destruct H3 as (H3'&H3''&H3&Hres').\n  destruct H3 as (Heg1 & Heg2).\n  lets Hrgs : Heg2 Hs.\n  destruct Hrgs as (xz &  qw & Hem & Hin).\n  unfold get in *; simpl in *.\n  rewrite Hg in Hem.\n  inverts Hem.\n  split.\n  auto.\n  split.\n  intro; tryfalse.\n\n\n\n  assert (qw = nil \\/ qw <> nil) by tauto.\n  destruct H3.\n  subst qw.\n  simpl in Hin; tryfalse.\n  splits; auto.\n  unfolds.\n  splits; auto.\n  do 3 eexists; splits; eauto.\n  intros.\n  assert (EcbMod.get v'11 (v'32, Int.zero) = Some (absmbox xz, qw) /\\ In t' qw) .\n  splits; auto.\n  lets Habs : Heg1 H22.\n  destruct Habs as (prio' & m' & n' & Hbs).\n  do 3 eexists; splits; eauto.\n  destruct H17 as (H17'&H17''&H17&Hres'').\n  lets Hpro : H17 Hbs.\n  destruct Hpro as (Hpro&Hss).\n  clear Hss.\n  unfolds in Hpro.\n  destruct Hpro as (xa & xb & zz & Hran & Hxx & Hyy & Hnths & Hzz).\n  subst xa xb.\n  rewrite Int.repr_unsigned in *.\n  lets Hat : math_highest_prio_select H13 H9 H11 Hnths  Hzz;\n    try eapply int_usigned_tcb_range; try omega;\n    eauto.\n  assert (Vint32 v'12 = Vint32 v'12) by auto.\n  lets Hzs : H1 Hnths H23.\n  eapply nat_8_range_conver; eauto.\n  try eapply int_usigned_tcb_range; eauto.  \n  destruct Hzs.\n  assert (zz = $ 0 \\/ zz <> $ 0) by tauto.\n  destruct H26.\n  subst zz.\n  rewrite Int.and_commut in Hzz.\n  rewrite Int.and_zero in Hzz.\n  unfold Int.one in *.\n  unfold Int.zero in *.\n  assert ($ 1<<ᵢ(prio'&ᵢ$ 7) <> $ 0 ).\n  eapply math_prop_neq_zero2; eauto.\n  tryfalse.\n  assert (Int.ltu ($ 0) zz = true).\n  clear - H26.\n  int auto.\n  assert (0<=Int.unsigned zz ).\n  int auto.\n  assert (Int.unsigned zz = 0).\n  omega.\n  rewrite <- H0 in H26.\n  rewrite Int.repr_unsigned in *.\n  tryfalse.\n  apply H25 in H27.\n  assert ($ Z.of_nat ∘(Int.unsigned (Int.shru prio' ($ 3))) = (Int.shru prio' ($ 3))).\n  clear -Hran.\n  mauto.\n  rewrite H28 in *.\n  auto.\n  lets Hasss : Hpr3 H20 Hs Hbs; eauto.\n  unfolds.\n  rewrite zlt_true; auto.\n  assert (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39) < Int.unsigned prio' \\/\n          Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39) = Int.unsigned prio').\n  omega.\n  destruct H23; auto; tryfalse.\n  false.\n  apply Hasss.\n  apply unsigned_inj; eauto.\nQed.\n\nLemma get_tcb_stat_mbox\n: forall (p : int32) (etbl : vallist) (ptbl : list val) \n         (tid : addrval) (tcbls : TcbMod.map) (abstcb : abstcb.B)\n         (tcbls' : TcbMod.map) (vl rtbl : vallist) \n         (qid : addrval) (vle : list val) (vhold : addrval),\n    0 <= Int.unsigned p < 64 ->\n    array_type_vallist_match Int8u etbl ->\n    length etbl = ∘OS_EVENT_TBL_SIZE ->\n    prio_in_tbl p etbl ->\n    nth_val' (Z.to_nat (Int.unsigned p)) ptbl = Vptr tid ->\n    R_PrioTbl_P ptbl tcbls vhold ->\n    TcbJoin tid abstcb tcbls' tcbls ->\n    TCBNode_P vl rtbl abstcb ->\n    R_ECB_ETbl_P qid (V$OS_EVENT_TYPE_MBOX :: vle, etbl) tcbls ->\n    V_OSTCBStat vl = Some (V$OS_STAT_MBOX).\nProof.\n  introv Hran Harr Hlen Hpri Hnth Hr Htj Htn Hre.\n  unfolds in Hre.\n  destruct Hre as (Hre1 & Hre2 & Hre3).\n  unfolds in Hre2.\n  destruct Hre1 as (Hre1'&Hre1''&Hre1& _).\n  unfolds in Hre1.\n  unfolds in Htn.\n  destruct abstcb.\n  destruct p0.\n  destruct Htn as (Hv1 & Hv2 &  Hrl & Hrc).\n  funfold Hrl.\n  rewrite H8 in H4.\n  inverts H4.\n  unfolds in Hrc.\n  destruct Hrc as (_&_&_&Hrc).\n  unfolds in Hrc.\n  destruct Hrc as (_&_&_&Hrc&_).\n  unfolds in Hrc.\n  unfolds in Hpri.\n  lets Hges : tcbjoin_get_a Htj.\n  unfolds in Hr.\n  destruct Hr.\n  apply nth_val'_imp_nth_val_vptr in Hnth.\n  lets Hs : H Hnth; eauto.\n  assert (tid <> vhold) as Hnvhold.\n  apply H4 in Hges;destruct Hges;auto.\n  destruct Hs as (st & mm & Hgs);auto.\n  unfold get in *; simpl in *.\n  rewrite Hges in Hgs.\n  inverts Hgs.\n  assert (PrioWaitInQ (Int.unsigned p) etbl).\n  unfolds.\n  rewrite Int.repr_unsigned.\n  remember (Int.shru p ($3)) as py.\n  remember ( p&ᵢ$ 7) as px.\n  lets Hrs : n07_arr_len_ex ∘(Int.unsigned py)  Harr Hlen.\n  subst py.\n  clear - H17.\n  mauto.\n  destruct Hrs as (vx & Hntht & Hin).\n  do 3 eexists; splits; eauto.\n  assert ( V_OSEventType (V$OS_EVENT_TYPE_MBOX :: vle) = Some (V$OS_EVENT_TYPE_MBOX)).\n  unfolds.\n  simpl; auto.\n  lets Hsd : Hre1 H15 H20.\n  mytac.\n  rewrite Int.repr_unsigned in H21.\n  assert (x = tid \\/ x <> tid) by tauto.\n  destruct H23.\n  subst x.\n  rewrite Hges in H21.\n  inverts H21.\n  eapply Hrc; eauto.\n  unfolds in H22.\n  lets Hfs : H22 H23 H21 Hges.\n  tryfalse.\nQed.\n\nLemma msglist_p_compose_mbox\n: forall (p : val) (qid : addrval) (mqls : EcbMod.map)\n         (qptrl1 qptrl2 : list EventCtr) (i i1 : int32) \n         (a : val) (x3 p' : val) (v'41 : vallist)\n         (msgqls1 msgqls2 : list EventData) (msgq : EventData)\n         (mqls1 mqls2 : EcbMod.map) (mq : absecb.B) \n         (mqls' : EcbMod.map) (tcbls : TcbMod.map),\n    R_ECB_ETbl_P qid\n                 (V$OS_EVENT_TYPE_MBOX\n                   :: Vint32 i :: Vint32 i1 ::  a :: x3 :: p' :: nil, v'41) tcbls ->\n    ECBList_P p (Vptr qid) qptrl1 msgqls1 mqls1 tcbls ->\n    ECBList_P p' Vnull qptrl2 msgqls2 mqls2 tcbls ->\n    RLH_ECBData_P msgq mq ->\n    EcbMod.joinsig qid mq mqls2 mqls' ->\n    EcbMod.join mqls1 mqls' mqls ->\n    ECBList_P p Vnull\n              (qptrl1 ++\n                      ((V$OS_EVENT_TYPE_MBOX\n                         :: Vint32 i :: Vint32 i1 ::  a :: x3 :: p' :: nil, v'41)\n                         :: nil) ++ qptrl2) (msgqls1 ++ (msgq :: nil) ++ msgqls2) mqls\n              tcbls.\nProof.\n  intros.\n  simpl.\n  eapply ecblist_p_compose; eauto.\n  simpl.\n  eexists; splits; eauto.\n  do 3 eexists; splits; eauto.\n  unfolds; simpl; auto.\nQed.\n\n\nLemma TCBList_P_post_mbox\n: forall (v'42 : val) (v'48 : list vallist) (v'47 : TcbMod.map)\n         (v'60 : val) (v'50 : list vallist) (v'37 : vallist)\n         (v'59 v'49 v'44 : TcbMod.map) (v'63 v'64 v'65 : val)\n         (v'51 v'52 v'53 v'54 v'55 v'56 : int32) (x00 : addrval)\n         (v'58 : block) (v'40 v'38 : int32) (prio : priority)\n         (st : taskstatus) (msg0 :msg)\n         (v'7 v'62 v'43 : TcbMod.map) (v'36 : vallist) \n         (v'39 : int32) (v'13 : vallist) (vhold : addrval),\n    Int.unsigned v'38 <= 7 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    prio_in_tbl ((v'38<<ᵢ$ 3)+ᵢv'39) v'13 ->\n    RL_RTbl_PrioTbl_P v'13 v'36 vhold ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 =\n    Vptr (v'58, Int.zero) ->\n    R_PrioTbl_P v'36 v'7 vhold ->\n    array_type_vallist_match Int8u v'37 ->\n    length v'37 = ∘OS_RDY_TBL_SIZE ->\n    TcbMod.join v'44 v'43 v'7 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg0) v'62 v'7 ->\n    get_last_tcb_ptr v'48 v'42 = Some (Vptr (v'58, Int.zero)) ->\n    TCBList_P v'42 v'48 v'37 v'47 ->\n    TCBList_P v'60 v'50 v'37 v'59 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg0) v'59 v'49 ->\n    TcbMod.join v'47 v'49 v'44 ->\n    TCBNode_P\n      (v'60\n         :: v'63\n         :: v'64\n         :: v'65\n         :: Vint32 v'51\n         :: V$OS_STAT_MBOX\n         :: Vint32 v'52\n         :: Vint32 v'53\n         :: Vint32 v'54\n         :: Vint32 v'55 :: Vint32 v'56 :: nil) v'37\n      (prio, st, msg0) ->\n    TCBList_P v'42\n              (v'48 ++\n                    (v'60\n                       :: v'63\n                       :: Vnull\n                       :: Vptr x00\n                       :: V$0\n                       :: V$0\n                       :: Vint32 v'52\n                       :: Vint32 v'53\n                       :: Vint32 v'54\n                       :: Vint32 v'55 :: Vint32 v'56 :: nil)\n                    :: v'50)\n              (update_nth_val (Z.to_nat (Int.unsigned v'38)) v'37\n                              (val_inj\n                                 (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37)\n                                     (Vint32 v'40))))\n              (TcbMod.set v'44 (v'58, Int.zero) (prio, rdy, Vptr x00)).\nProof.\n  intros.\n  unfolds in H5.\n  destruct H5 as (Ha1 & Ha2 & Ha3).\n  assert ( 0 <= Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39) < 64).\n  clear -H H0.\n  mauto.\n  unfold nat_of_Z in Ha1.\n  eapply nth_val'_imp_nth_val_vptr in H4.\n  lets Hps : Ha1 H5 H4.\n  \n  lets Hgs : tcbjoin_get_a H9.\n  assert ((v'58, Int.zero) <> vhold) as Hnvhold.\n  apply Ha2 in Hgs.\n  destruct Hgs;auto.\n  apply Hps in Hnvhold.\n  clear Hps.\n  mytac.\n  unfold get in *; simpl in *.\n  rewrite H16 in Hgs.\n  inverts Hgs.\n  remember ((v'38<<ᵢ$ 3)) as px.\n  remember (v'39) as py.\n  clear Heqpy.\n  remember (px+ᵢpy) as prio.\n  remember ( (v'58, Int.zero)) as tid.\n  lets Hps : tcbjoin_set_ex (prio,st,msg0) (prio,rdy,Vptr x00)  H14;eauto.\n  destruct Hps as (b&Htx & Hty).\n  remember (val_inj\n              (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37) (Vint32 v'40))) as Hv.\n  assert (0<= Z.to_nat (Int.unsigned v'38) <8)%nat.\n  clear -H.\n  mauto.\n  lets Hsx : n07_arr_len_ex H6 H7; eauto.\n  destruct Hsx as (vx & Hnth & Hi).\n  lets Hns :  nth_val_nth_val'_some_eq  Hnth.\n  rewrite Hns in HeqHv.\n  simpl in HeqHv.\n  subst Hv.\n  assert (v'38 = Int.shru prio ($ 3)).\n  subst.\n  clear - H H0.\n  mauto.\n  rewrite H19.\n  assert (v'40 = ($ 1<<ᵢ(prio &ᵢ$ 7))).  \n  rewrite Heqprio.\n  rewrite Heqpx.\n  assert ((((v'38<<ᵢ$ 3)+ᵢpy)&ᵢ$ 7) = py).\n  clear -H H0.\n  mauto.\n  rewrite H20.\n  clear -H0 H1.\n  mautoext.\n  rewrite H20.\n  eapply TCBList_P_Combine; eauto.\n  eapply TCBList_P_rtbl_add_simpl_version; eauto.\n  rewrite <-H19.\n  auto.\n  intros.\n  unfolds in Ha3.\n  lets Hsx : tcbjoin_join_get_neq H13 H14 H21.\n  destruct Hsx.\n  eapply Ha3; eauto.\n  lets Hacb  :  TcbMod.join_get_l H8 H23; eauto.\n  simpl.\n  do 4 eexists; splits; eauto.\n  unfolds; simpl; eauto.\n  exact Htx.\n  unfolds.\n  auto.\n  fsimpl.\n  usimpl H15.\n  usimpl H22.\n  splits.\n  unfolds; simpl; auto.\n  unfolds; simpl; auto.\n  funfold H23.\n  unfolds.\n  do 6 eexists; splits; try solve [unfolds; simpl;auto].\n  omega.\n  splits; eauto.\n  eexists.\n  split.\n  unfolds;simpl; eauto.\n  auto.\n  unfolds.\n  splits.\n  unfolds.\n  intros.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  splits; try solve [unfolds; simpl;auto].\n  eexists; eauto.\n  unfolds.\n  intros.\n  inverts H15.\n  splits; try solve [unfolds; simpl;auto].\n  unfolds.\n  splits; try solve [unfolds; simpl;auto].\n  apply prio_in_tbl_orself ; auto.\n  unfolds.\n  splits.\n  unfolds.\n  intros.\n  usimpl H22.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  usimpl H25.\n  false.\n  rewrite H26 in H19.\n  rewrite H19 in Hnth.\n  rewrite H26 in H17.\n  rewrite H26 in H22.\n  lets Hfs :  prio_notin_tbl_orself  H17 Hnth.\n  tryfalse.\n\n  unfolds.\n  intros.\n  usimpl H22.\n  unfolds.\n  intros.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  usimpl H25.\n\n  unfolds.\n  intros.\n  usimpl H22.\n  unfolds.\n  intros.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  usimpl H25.\n  \n  unfolds.\n  splits; try solve [\n                unfolds;\n                introv Hf; inverts Hf].\n  eapply TCBList_P_rtbl_add_simpl_version; eauto.\n  rewrite <-H19.\n  auto.\n  intros.\n  lets Hnas : tcbjoin_tid_neq H13 H21.\n  unfolds in Ha3.\n  eapply Ha3; eauto.\n  lets Haxc  : TcbMod.join_get_r H13 H21.\n  lets Haa : TcbMod.join_get_r H14 Haxc.\n  lets Ad :  TcbMod.join_get_l H8 Haa; eauto.\nQed.\n\n  Lemma ECBList_P_Set_Rdy_hold_mbox\n  : forall (a : list EventCtr) (tcbls : TcbMod.map) \n           (tid : tidspec.A) (prio : priority) (msg0 msg' : msg) \n           (x y : val) (b : list EventData) (c : EcbMod.map) \n           (eid : ecbid) (nl : int32),\n      TcbMod.get tcbls tid = Some (prio, wait (os_stat_mbox eid) nl, msg0) ->\n      EcbMod.get c eid = None ->\n      ECBList_P x y a b c tcbls ->\n      ECBList_P x y a b c (TcbMod.set tcbls tid (prio, rdy, msg')).\nProof.\n  inductions a; intros.\n  simpl in *; auto.\n  simpl in H1.\n  mytac.\n  destruct b; tryfalse.\n  destruct a.\n  mytac.\n  simpl.\n  eexists.\n  splits; eauto.\n  unfolds.\n  unfolds in H2.\n\n  splits.\n  \n  destructs H2.\n  unfolds in H2.\n  mytac.\n  unfolds.\n  splits; unfolds;intros.\n\n  apply H2 in H11.\n  apply H11 in H12.\n  mytac.\n  assert (tid = x3 \\/ tid <> x3) by tauto.\n  destruct H13.\n  subst tid.\n  unfold get in *; simpl in *.\n  rewrite H12 in H.\n  inverts H.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n  \n  \n  apply H8 in H11.\n  apply H11 in H12.\n  mytac.\n  assert (tid = x3 \\/ tid <> x3) by tauto.\n  destruct H13.\n  subst tid.\n  unfold get in *; simpl in *.\n  rewrite H12 in H.\n  inverts H.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n\n  \n  apply H9 in H11.\n  apply H11 in H12.\n  mytac.\n  assert (tid = x3 \\/ tid <> x3) by tauto.\n  destruct H13.\n  subst tid.\n  unfold get in *; simpl in *.\n  rewrite H12 in H.\n  inverts H.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n\n  \n  apply H10 in H11.\n  apply H11 in H12.\n  mytac.\n  assert (tid = x3 \\/ tid <> x3) by tauto.\n  destruct H13.\n  subst tid.\n  unfold get in *; simpl in *.\n  rewrite H12 in H.\n  inverts H.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n\n\n\n  \n  unfolds.\n  destructs H2;unfolds in H6;destructs H6.\n  splits;intros prio' mg ng x3 Hti;\n  assert (tid = x3\n          \\/ tid <> x3) by tauto.\n  destruct H11.\n  subst tid.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  rewrite H in Hti.\n  inverts Hti.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  rewrite tidspec.eq_beq_true in Hti; tryfalse; auto.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  eapply H6; eauto.\n\n  destruct H11.\n  subst tid.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  rewrite H in Hti.\n  inverts Hti.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  rewrite tidspec.eq_beq_true in Hti; tryfalse; auto.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  eapply H8; eauto.\n\n  destruct H11.\n  subst tid.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  rewrite H in Hti.\n  inverts Hti.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  rewrite tidspec.eq_beq_true in Hti; tryfalse; auto.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  eapply H9; eauto.\n\n  destruct H11.\n  subst tid.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti;  auto.\n  rewrite H in Hti.\n  inverts Hti.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  rewrite tidspec.eq_beq_true in Hti; tryfalse; auto.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  eapply H10; eauto.\n\n  mytac;auto.\n\n\n  do 3 eexists; splits; eauto.\n  eapply IHa; eauto.\n  eapply ecbmod_joinsig_get_none; eauto.\nQed.\n\nLemma ecblist_p_post_exwt_hold_mbox\n: forall (v'36 : vallist) (v'12 : int32) (v'13 : vallist)\n         (v'38 v'69 v'39 : int32) (v'58 : block) (v'40 : int32)\n         (v'32 : block) (v'15 : int32) (v'24 : val)\n         (v'35 v'16 v'18 v'19 v'20 v'34 : val) (v'21 v'22 : int32)\n         (v'23 : block) (v'25 v'26 : val) (v'27 : vallist)\n         (x : list msg) (x0 : maxlen) (x1 : waitset) \n         (v'0 : val) (v'1 : list EventCtr) (v'5 : list EventData)\n         (v'6 : EcbMod.map) (v'7 : TcbMod.map) (x00 : addrval)\n         (v'11 : EcbMod.map) (v'31 : list EventData) \n         (v'30 : list EventCtr) (v'29 : val) (v'10 v'9 : EcbMod.map)\n         (prio : priority) (v'62 : TcbMod.map) (st : taskstatus)\n         (msg0 : msg) (y : int32) (vhold : addrval),\n    (* RL_RTbl_PrioTbl_P v'13 v'36 vhold -> *)\n    True ->\n    v'12 <> Int.zero ->\n    Int.unsigned v'12 <= 255 ->\n    array_type_vallist_match Int8u v'13 ->\n    length v'13 = ∘OS_EVENT_TBL_SIZE ->\n    nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n    Int.unsigned v'38 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n    Int.unsigned v'69 <= 255 ->\n    nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 =\n    Vptr (v'58, Int.zero) ->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    Int.unsigned v'40 <= 128 ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    R_ECB_ETbl_P (v'32, Int.zero)\n                 (V$OS_EVENT_TYPE_MBOX\n                   :: Vint32 v'12\n                   :: Vint32 v'15 :: v'24 :: v'35 :: v'0 :: nil,\n                  v'13) v'7 ->\n    RLH_ECBData_P\n      (DMbox v'24) (absmbox v'24, x1) ->\n    ECBList_P v'0 Vnull v'1 v'5 v'6 v'7 ->\n    ECBList_P v'29 (Vptr (v'32, Int.zero)) v'30 v'31 v'9 v'7 ->\n    EcbMod.joinsig (v'32, Int.zero) (absmbox v'24, x1) v'6 v'10 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg0) v'62 v'7 ->\n    R_PrioTbl_P v'36 v'7 vhold ->\n    x1 <> nil ->\n    ECBList_P v'29 Vnull\n              (v'30 ++\n                    ((V$OS_EVENT_TYPE_MBOX\n                       :: Vint32 y\n                       :: Vint32 v'15 :: v'24 :: v'35 :: v'0 :: nil,\n                      update_nth_val (Z.to_nat (Int.unsigned v'38)) v'13\n                                     (Vint32 (v'69&ᵢInt.not v'40))) :: nil) ++ v'1)\n              (v'31 ++\n                    (DMbox v'24 ::nil)\n                    ++ v'5)\n              (EcbMod.set v'11 (v'32, Int.zero)\n                          (absmbox v'24, remove_tid (v'58, Int.zero) x1))\n              (TcbMod.set v'7 (v'58, Int.zero) (prio, rdy, Vptr x00))\n.\nProof.\n  intros.\n  unfolds in H21.\n  destruct H21 as (Ha1 & Ha2 & Ha3).\n  assert ( 0 <= Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39) < 64).\n  clear -H5 H9.\n  mauto.\n  unfold nat_of_Z in Ha1.\n  eapply nth_val'_imp_nth_val_vptr in H10.\n  lets Hps : Ha1 H21 H10.\n  apply tcbjoin_get_a in H20.\n  assert ((v'58, Int.zero) <> vhold) as Hnvhold.\n  apply Ha2 in H20.\n  destruct H20;auto.\n  destruct Hps as (sts & mg & Hget);auto.\n  unfold get in *; simpl in *.\n  rewrite Hget in H20.\n  inverts H20.\n  remember ((v'38<<ᵢ$ 3)) as px.\n  remember (v'39) as py.\n  clear Heqpy.\n  remember (px+ᵢpy) as prio.\n  remember ( (v'58, Int.zero)) as tid.\n  unfolds in H14.\n  destruct H14 as (Ha & Hb & Hc).\n  destruct Ha as (Ha''&Ha'&Ha&Ha''').\n  destruct Hb as (Hb''&Hb'&Hb&Hb''').\n  lets Hz : math_unmap_get_y H1 H4.\n  lets Heq1 :  math_mapval_core_prop H11; eauto.\n  omega.\n  subst v'40.\n  assert (v'38 = Int.shru prio ($3)).\n  subst.\n  clear -Hz H9.\n  mauto.\n  assert (py = prio &ᵢ $ 7).\n  subst prio. \n  rewrite Heqpx.\n  clear -Hz H9.\n  mauto.\n  rewrite H14 in H6.\n  assert (PrioWaitInQ (Int.unsigned prio) v'13) as Hcp.\n  unfolds.\n  do 3 eexists; splits; eauto.\n  rewrite Int.repr_unsigned.\n  eapply nth_val'_imp_nth_val_int; eauto.\n  rewrite Int.repr_unsigned.\n  rewrite <- H20.\n  unfold Int.one.\n  eapply math_8_255_eq; eauto.\n  \n  unfold Int.zero in H0.\n  rewrite <-H14 in *.\n  lets Hneq :  rl_tbl_grp_neq_zero H1 H0  H4 H6 H13.\n  omega.\n  auto.\n  lets Hecp : Ha Hcp.\n  unfold V_OSEventType in Hecp.\n  simpl nth_val in Hecp.\n  assert (Some (V$OS_EVENT_TYPE_MBOX) = Some (V$OS_EVENT_TYPE_MBOX)) by auto.\n  apply Hecp in H23.\n  clear Hecp.\n  rename H23 into Hecp.\n  destruct Hecp as (ct & nl & mg & Hcg).\n  assert (ct = tid) as Hed.\n  assert (ct = tid \\/ ct <> tid)  by tauto.\n  destruct H23; auto.\n  lets Heqs : Ha3 H23 Hcg Hget.\n  rewrite Int.repr_unsigned in Heqs.\n  tryfalse.\n  subst ct.\n  unfold get in *; simpl in *.\n  rewrite Hget in Hcg.\n  inversion Hcg.\n  subst mg st .\n  clear Hcg.\n  \n  lets Hsds : ecb_set_join_join  (absmbox v'24, remove_tid tid x1)  H18  H19.\n  destruct Hsds as ( vv & Hsj1 & Hsj2).\n\n  eapply msglist_p_compose_mbox.\n  instantiate (1:= (v'32, Int.zero)).\n  unfolds.\n  splits.\n  unfolds.\n  splits;unfolds.\n  Focus 3.\n  \n  introv Hprs Hxx.\n  clear Hxx.\n  apply prio_wt_inq_convert in Hprs.\n  destruct Hprs as (Hprs1 & Hprs2).\n  rewrite H14 in Hprs1.\n  rewrite H20 in Hprs1.\n  lets Hrs : prio_wt_inq_tid_neq  H6 H21 .\n  destruct Hrs as (Hrs & _).\n  apply Hrs in Hprs1.\n  destruct Hprs1 as (Hpq & Hneq).\n  lets Hxs : Ha Hpq.\n  rewrite Int.repr_unsigned in Hxs.\n  destruct Hxs as (tid' & nn & mm & Htg).\n  unfolds;simpl;auto.\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  unfold get in *; simpl in *.\n  rewrite Hget in Htg.\n  inversion Htg.\n  tryfalse.\n  exists tid' nn mm.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false;eauto.\n\n  intros.\n  unfolds in H25;simpl in H25;tryfalse.\n  intros.\n  unfolds in H25;simpl in H25;tryfalse.\n  intros.\n  unfolds in H25;simpl in H25;tryfalse.\n  \n\n\n  unfolds.\n  splits;\n    intros prio' mm nn tid'.\n  Focus 3.\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  lets Hga : Hb Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H23 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n\n  lets Hrs : prio_wt_inq_tid_neq  H6 H21 .\n  destruct Hrs as (_ & Hrs).\n  apply Hrs in H25.\n  rewrite H20.\n  rewrite H14.\n  auto.\n\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  lets Hga : Hb'' Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H23 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n  unfolds in Hx;simpl in Hx;tryfalse.\n\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  lets Hga : Hb' Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H23 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n  unfolds in Hx;simpl in Hx;tryfalse.\n\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  lets Hga : Hb''' Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H23 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n  unfolds in Hx;simpl in Hx;tryfalse.\n\n  simpl fst in Hc;simpl;auto.\n  \n  instantiate (1:=v'9).\n\n\n  \n  eapply ECBList_P_Set_Rdy_hold_mbox;eauto.\n  rewrite Int.repr_unsigned.  \n  eauto.\n  eapply joinsig_join_getnone; eauto.\n  instantiate (1:=v'6).\n  eapply ECBList_P_Set_Rdy_hold_mbox;eauto.\n  rewrite Int.repr_unsigned.  \n  eauto.\n  eapply  joinsig_get_none; eauto.\n  3:eauto.\n  2:eauto.\n  unfolds.\n  splits; auto.\n  unfolds.\n    destruct H15; intros.\n   destruct H23; intros.\n  splits; intros; auto; tryfalse.\n  apply H23 in H26.\n  subst x1.\n  simpl.\n  auto.\nQed.\n\n\n\nLemma rh_tcblist_ecblist_p_post_exwt_mbox\n: forall (v'8 tid : tid) (v'11 : EcbMod.map) \n         (v'7 : TcbMod.map) (v'9 v'10 : EcbMod.map) \n         (eid : tidspec.A) (x : val) \n         (x0 : maxlen) (x1 : waitset) (v'6 : EcbMod.map) \n         (prio : priority) (msg0 : msg) \n         (x00 : addrval) (xl : int32),\n    RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    EcbMod.joinsig eid (absmbox x , x1) v'6 v'10 ->\n    In tid x1 ->\n    TcbMod.get v'7 tid = Some (prio, wait (os_stat_mbox eid) xl, msg0) ->\n    RH_TCBList_ECBList_P\n      (EcbMod.set v'11 eid (absmbox x, remove_tid tid x1))\n      (TcbMod.set v'7 tid (prio, rdy, Vptr x00)) v'8\n.\nProof.\n  intros.\n  unfolds.\n  splits.\n  Focus 3.\n  splits; intros.\n  destruct H4.\n  unfolds in H.\n  destruct H as (Hy&Hx&H&Hz).\n  destruct H.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H7.\n  subst.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  assert (EcbMod.get v'11 eid = Some (absmbox x, x1)/\\ In tid0 x1 ).\n  splits; auto.\n  lets Hsa : H H7.\n  mytac.\n  unfold get in *; simpl in *.\n\n  rewrite H3 in H8.\n  inverts H8.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H8.\n  subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n  apply  in_wtset_rm_notin in H9.\n  tryfalse.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert (EcbMod.get v'11 eid0 = Some (absmbox n, wls) /\\ In tid0 wls ).\n\n  splits; auto.\n  lets Hsc : H H10.\n  mytac.\n  rewrite H3 in H11.\n  inverts H11.\n  tryfalse.\n  rewrite TcbMod.set_sem .\n  rewrite tidspec.neq_beq_false; auto.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H8.\n  subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n  lets Hbss :tidneq_inwt_in  x1 H7.\n  destruct Hbss as (Hbss & _).\n  lets Hbssc : Hbss H5.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  assert ( EcbMod.get v'11 eid0 = Some (absmbox n, x1) /\\ In tid0 x1 ).\n  splits; auto.\n  apply H in H4.\n  mytac.\n  do 3 eexists; eauto.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert ( EcbMod.get v'11 eid0 = Some (absmbox n, wls)/\\ In tid0 wls ).\n  splits; auto.\n  apply H in H9.\n  mytac.\n  do 3 eexists; eauto .\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H5.\n  subst.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  \n  unfolds in H.\n  destruct H as (H6 & H7 & H & H8).\n  destruct H.\n  apply H9 in H4.\n  mytac.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H11.\n  subst.\n  unfold get in *; simpl in *.\n  rewrite H4 in Hget.\n  inverts Hget.\n  lets Hbss :tidneq_inwt_in  x1 H5.\n  destruct Hbss as (_ & Hbss).\n  lets Hbssc : Hbss H10.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; auto.\n  do 2 eexists; splits; eauto.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 2 eexists; splits; eauto.\n\n\n  splits; intros.\n  destruct H4.\n  unfolds in H.\n  destruct H as (H&_).\n  destruct H.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H7;subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  tryfalse.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert (EcbMod.get v'11 eid0 = Some (absmsgq x2 y, qwaitset) /\\ In tid0 qwaitset).\n  split;auto.\n  apply H in H8.\n  mytac.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H9;subst.\n  unfold get in *; simpl in *.\n  rewrite H3 in H8;tryfalse.\n  do 3 eexists.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  eauto.\n\n  unfolds in H.\n  destruct H as (H&_).\n  destruct H.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H6;subst.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  apply H5 in H4.\n  mytac.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H8;subst.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  unfold get in *; simpl in *.\n  rewrite H4 in Hget;tryfalse.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists;split;eauto.\n\n  \n  splits; intros.\n  destruct H4.\n  unfolds in H.\n  destruct H as (Hh&H&_).\n  destruct H.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H7;subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  tryfalse.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert (EcbMod.get v'11 eid0 = Some (abssem n, wls) /\\ In tid0 wls).\n  split;auto.\n  apply H in H8.\n  mytac.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H9;subst.\n  unfold get in *; simpl in *.\n  rewrite H3 in H8;tryfalse.\n  do 3 eexists.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  eauto.\n\n  unfolds in H.\n  destruct H as (Hh&H&_).\n  destruct H.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H6;subst.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  apply H5 in H4.\n  mytac.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H8;subst.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  unfold get in *; simpl in *.\n  rewrite H4 in Hget;tryfalse.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 2 eexists;split;eauto.\n\n  \n  splits; intros.\n  destruct H4.\n  unfolds in H.\n  destruct H as (Hh&Hhh&Hx&H).\n  destruct H.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H7;subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  tryfalse.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert (EcbMod.get v'11 eid0 = Some (absmutexsem n1 n2, wls) /\\ In tid0 wls).\n  split;auto.\n  apply H in H8.\n  destruct H6 as (H6 & HHHHH).\n  mytac.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H9;subst.\n  unfold get in *; simpl in *.\n  rewrite H3 in H8;tryfalse.\n  do 3 eexists.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  eauto.\n\n  unfolds in H.\n  destruct H as (Hh&Hx&Hhh&H).\n  destruct H.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H6;subst.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  apply H5 in H4.\n  destruct H5 as (H5 & HHHHH).\n  mytac.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H8;subst.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  unfold get in *; simpl in *.\n  rewrite H4 in Hget;tryfalse.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists;split;eauto.\n\n  apply Mutex_owner_hold_for_set_tcb.\n  eapply Mutex_owner_set; eauto.\n  intro; mytac.\n  unfolds in H.\n  mytac.\n  unfolds in H6; mytac.\n  auto.\nQed.\n\nLemma rh_tcblist_ecblist_p_post_exwt_aux_mbox\n: forall (v'8 tid0 : tid) (v'11 : EcbMod.map) \n         (v'7 : TcbMod.map) (v'9 v'10 : EcbMod.map) \n         (eid : tidspec.A) (x : val) \n         (x0 : maxlen) (x1 : waitset) (v'6 : EcbMod.map) \n         (prio : priority) (msg0 : msg) \n         (st : taskstatus),\n    RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    EcbMod.joinsig eid (absmbox x, x1) v'6 v'10 ->\n    In tid0 x1 ->\n    TcbMod.get v'7 tid0 = Some (prio, st, msg0) ->\n    exists xl, st = wait (os_stat_mbox eid) xl\n.\n  intros.\n  unfolds in H.\n  destruct H as (Hexaa & Hexa & Hex & Hexaaa).\n  lets Hget : EcbMod.join_joinsig_get H0 H1.\n  assert (EcbMod.get v'11 eid = Some (absmbox x, x1) /\\ In tid0 x1).\n  split; auto.\n  apply Hex in H.\n  mytac.\n  unfold get in *; simpl in *.\n  rewrite H3 in H.\n  inverts H.\n  eauto.\nQed.\n\n\nLemma TCBList_P_post_msg_mbox\n: forall (v'42 : val) (v'48 : list vallist) (v'47 : TcbMod.map)\n         (v'60 : val) (v'50 : list vallist) (v'37 : vallist)\n         (v'59 v'49 v'44 : TcbMod.map) (v'63 v'64 v'65 : val)\n         (v'51 v'52 v'53 v'54 v'55 v'56 : int32) (x00 : addrval)\n         (v'58 : block) (v'40 v'38 : int32) (prio : priority)\n         (st : taskstatus) (msg : msg)\n         (v'7 v'62 v'43 : TcbMod.map) (v'36 : vallist) \n         (v'39 : int32) (v'13 : vallist) (vhold : addrval),\n    Int.unsigned v'38 <= 7 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    prio_in_tbl ((v'38<<ᵢ$ 3)+ᵢv'39) v'13 ->\n    RL_RTbl_PrioTbl_P v'13 v'36 vhold ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 =\n    Vptr (v'58, Int.zero) ->\n    R_PrioTbl_P v'36 v'7 vhold ->\n    array_type_vallist_match Int8u v'37 ->\n    length v'37 = ∘OS_RDY_TBL_SIZE ->\n    TcbMod.join v'44 v'43 v'7 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg) v'62 v'7 ->\n    get_last_tcb_ptr v'48 v'42 = Some (Vptr (v'58, Int.zero)) ->\n    TCBList_P v'42 v'48 v'37 v'47 ->\n    TCBList_P v'60 v'50 v'37 v'59 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg) v'59 v'49 ->\n    TcbMod.join v'47 v'49 v'44 ->\n    TCBNode_P\n      (v'60\n         :: v'63\n         :: v'64\n         :: v'65\n         :: Vint32 v'51\n         :: V$OS_STAT_MBOX\n         :: Vint32 v'52\n         :: Vint32 v'53\n         :: Vint32 v'54\n         :: Vint32 v'55 :: Vint32 v'56 :: nil) v'37\n      (prio, st, msg) ->\n    TCBList_P v'42\n              (v'48 ++\n                    (v'60\n                       :: v'63\n                       :: Vnull\n                       :: Vptr x00\n                       :: V$0\n                       :: Vint32 ($ OS_STAT_MBOX&ᵢInt.not ($ OS_STAT_MBOX))\n                       :: Vint32 v'52\n                       :: Vint32 v'53\n                       :: Vint32 v'54\n                       :: Vint32 v'55 :: Vint32 v'56 :: nil)\n                    :: v'50)\n              (update_nth_val (Z.to_nat (Int.unsigned v'38)) v'37\n                              (val_inj\n                                 (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37)\n                                     (Vint32 v'40))))\n              (TcbMod.set v'44 (v'58, Int.zero) (prio, rdy, Vptr x00)).\nProof.\n  intros.\n  unfolds in H5.\n  destruct H5 as (Ha1 & Ha2 & Ha3).\n  assert ( 0 <= Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39) < 64).\n  clear -H H0.\n  mauto.\n  unfold nat_of_Z in Ha1.\n  eapply nth_val'_imp_nth_val_vptr in H4.\n  lets Hps : Ha1 H5 H4.\n  \n  lets Hgs : tcbjoin_get_a H9.\n  assert ((v'58, Int.zero) <> vhold) as Hnvhold.\n  apply Ha2 in Hgs.\n  destruct Hgs;auto.\n  apply Hps in Hnvhold.\n  clear Hps.\n  mytac.\n  unfold get in *; simpl in *.\n  rewrite H16 in Hgs.\n  inverts Hgs.\n  remember ((v'38<<ᵢ$ 3)) as px.\n  remember (v'39) as py.\n  clear Heqpy.\n  remember (px+ᵢpy) as prio.\n  remember ( (v'58, Int.zero)) as tid.\n  lets Hps : tcbjoin_set_ex (prio,st,msg) (prio,rdy,Vptr x00)  H14;eauto.\n  destruct Hps as (b&Htx & Hty).\n  remember (val_inj\n              (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37) (Vint32 v'40))) as Hv.\n  assert (0<= Z.to_nat (Int.unsigned v'38) <8)%nat.\n  clear -H.\n  mauto.\n  lets Hsx : n07_arr_len_ex H6 H7; eauto.\n  destruct Hsx as (vx & Hnth & Hi).\n  lets Hns :  nth_val_nth_val'_some_eq  Hnth.\n  rewrite Hns in HeqHv.\n  simpl in HeqHv.\n  subst Hv.\n  assert (v'38 = Int.shru prio ($ 3)).\n  subst.\n  clear - H H0.\n  mauto.\n  rewrite H19.\n  assert (v'40 = ($ 1<<ᵢ(prio &ᵢ$ 7))).  \n  rewrite Heqprio.\n  rewrite Heqpx.\n  assert ((((v'38<<ᵢ$ 3)+ᵢpy)&ᵢ$ 7) = py).\n  clear -H H0.\n  mauto.\n  rewrite H20.\n  clear -H0 H1.\n  mautoext.\n  rewrite H20.\n  eapply TCBList_P_Combine; eauto.\n  eapply TCBList_P_rtbl_add_simpl_version; eauto.\n  rewrite <-H19.\n  auto.\n  intros.\n  unfolds in Ha3.\n  lets Hsx : tcbjoin_join_get_neq H13 H14 H21.\n  destruct Hsx.\n  eapply Ha3; eauto.\n  lets Hacb  :  TcbMod.join_get_l H8 H23; eauto.\n  simpl.\n  do 4 eexists; splits; eauto.\n  unfolds; simpl; eauto.\n  exact Htx.\n  unfolds.\n  fsimpl.\n  usimpl H15.\n  usimpl H22.\n  splits.\n  unfolds; simpl; auto.\n  unfolds; simpl; auto.\n  funfold H23.\n  unfolds.\n  do 6 eexists; splits; try solve [unfolds; simpl;auto].\n  omega.\n  splits; eauto.\n  eexists.\n  split.\n  unfolds;simpl; eauto.\n  auto.\n  unfolds.\n  splits.\n  unfolds.\n  intros.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  splits; try solve [unfolds; simpl;auto].\n  eexists; eauto.\n  unfolds.\n  intros.\n  inverts H15.\n  splits; try solve [unfolds; simpl;auto].\n  unfolds.\n  splits; try solve [unfolds; simpl;auto].\n  apply prio_in_tbl_orself ; auto.\n  unfolds.\n  splits.\n  unfolds.\n  intros.\n  usimpl H22.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  usimpl H25.\n  false.\n  rewrite H26 in H19.\n  rewrite H19 in Hnth.\n  rewrite H26 in H17.\n  rewrite H26 in H22.\n  lets Hfs :  prio_notin_tbl_orself  H17 Hnth.\n  tryfalse.\n\n  unfolds.\n  intros.\n  usimpl H22.\n  unfolds.\n  intros.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  usimpl H25.\n\n  unfolds.\n  intros.\n  usimpl H22.\n  unfolds.\n  intros.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  usimpl H25.\n  \n  unfolds.\n  splits; try solve [\n                unfolds;\n                introv Hf; inverts Hf].\n  eapply TCBList_P_rtbl_add_simpl_version; eauto.\n  rewrite <-H19.\n  auto.\n  intros.\n  lets Hnas : tcbjoin_tid_neq H13 H21.\n  unfolds in Ha3.\n  eapply Ha3; eauto.\n  lets Haxc  : TcbMod.join_get_r H13 H21.\n  lets Haa : TcbMod.join_get_r H14 Haxc.\n  lets Ad :  TcbMod.join_get_l H8 Haa; eauto.\nQed.\n\nLemma statmbox_and_not_statmbox_eq_rdy : Int.eq ($ OS_STAT_MBOX&ᵢInt.not ($ OS_STAT_MBOX)) ($ OS_STAT_RDY) = true.\nProof.\n  unfold OS_STAT_MBOX, OS_STAT_RDY.\n  unfold Int.not.\n  unfold Int.xor.\n  unfold Z.lxor.\n  int auto.\n  compute.\n  split; intros; tryfalse.\n  int auto.\n  compute.\n  intro; tryfalse.\n  compute.\n  intro; tryfalse.\n  compute.\n  split; intros; tryfalse.\nQed.\n\nLemma tcb_inrtbl_not_vhold: forall v'42 v'62 v'93 v'57 v'81, RL_RTbl_PrioTbl_P v'42 v'62 v'93 ->  prio_in_tbl ((v'57)) v'42 -> nth_val' (Z.to_nat (Int.unsigned ((v'57)))) v'62 =  Vptr (v'81, Int.zero) ->   0 <= Int.unsigned v'57 < 64 -> (v'81, Int.zero) <> v'93.\nProof.\n  introv H H0 H1 asdfasfd.\n  unfolds in H.\n  lets adaf: H H0.\n  auto.\n  mytac.\n  apply nth_val_nth_val'_some_eq in H2.\n  rewrite H1 in H2.\n  inverts H2.\n  auto.\nQed.\n\nLemma le7_le7_range64:  forall v'57 v'59, Int.unsigned v'57 <= 7 -> Int.unsigned v'59 <= 7 ->  0 <= Int.unsigned ((v'57<<ᵢ$ 3)+ᵢv'59) < 64.\n  intros.\n  mauto.\nQed.\n\n\n\n(* absinfer lemma *)\n(* Lemma absinfer_mbox_post_put_mail_return : forall P x m mqls tcbls t ct,\n *                                            can_change_aop P ->\n *                                            EcbMod.get mqls x = Some (absmbox Vnull, nil) ->\n *                                            absinfer (<|| mbox_post (Vptr x :: Vptr m ::nil) ||> **HECBList mqls** HTCBList tcbls ** HTime t ** HCurTCB ct ** P) (<|| END (Some (Vint32 (Int.repr MBOX_POST_SUCC))) ||> **HECBList (EcbMod.set mqls x (absmbox (Vptr m),nil))** HTCBList tcbls ** HTime t ** HCurTCB ct ** P).\n * Proof.\n *   infer_solver 6%nat.\n * Qed.\n * \n * \n * Lemma absinfer_mbox_post_null_return : forall P x, \n *                                        can_change_aop P ->\n *                                        tl_vl_match  ((Void) ∗ :: nil) x = true ->\n *                                        absinfer (<|| mbox_post (Vnull :: x) ||> ** P) ( <|| END (Some (Vint32 (Int.repr MBOX_POST_NULL_ERR))) ||> ** P).\n * Proof.\n *   infer_solver 0%nat.\n * Qed.\n * \n * Lemma absinfer_mbox_post_msg_null_return:\n *   forall P v, \n *     can_change_aop P -> \n *     absinfer\n *       ( <|| mbox_post (Vptr v :: Vnull ::nil) ||>  **\n *             P) (<|| END (Some (Vint32 (Int.repr  OS_ERR_POST_NULL_PTR))) ||>  **\n *                     P).\n * Proof.\n *   infer_solver 1%nat.\n * Qed.\n * \n * Lemma absinfer_mbox_post_p_not_legal_return : forall x a P b tcbls t ct, \n *                                               can_change_aop P ->\n *                                               EcbMod.get x a = None ->\n *                                               absinfer (<|| mbox_post (Vptr a ::Vptr b:: nil) ||> ** HECBList x** HTCBList tcbls ** HTime t ** HCurTCB ct  **\n *                                                           P) ( <|| END (Some  (V$ MBOX_POST_P_NOT_LEGAL_ERR)) ||> ** HECBList x ** HTCBList tcbls ** HTime t ** HCurTCB ct  ** P).\n * Proof.\n *   infer_solver 2%nat.\n * Qed.\n * \n * Lemma absinfer_mbox_post_wrong_type_return : forall x a b P tcbls t ct, \n *                                              can_change_aop P ->\n *                                              (exists d,\n *                                                 EcbMod.get x a = Some d /\\ ~ (exists x wls, d = (absmbox x, wls))) ->\n *                                              absinfer (<|| mbox_post (Vptr a :: Vptr b :: nil) ||> ** HECBList x ** HTCBList tcbls ** HTime t ** HCurTCB ct **\n *                                                          P) ( <|| END (Some  (V$MBOX_POST_WRONG_TYPE_ERR)) ||> ** HECBList x ** HTCBList tcbls ** HTime t ** HCurTCB ct ** P).\n * Proof.\n *   infer_solver 3%nat.\n *   destruct x0.\n *   repeat tri_exists_and_solver1.\n *   intro.\n *   apply H2.\n *   mytac.\n *   eauto.\n * Qed. *)\n\n(* Lemma absinfer_mbox_post_full_return :   forall P mqls x a wl y tcbls t ct, \n *                                          can_change_aop P ->  \n *                                          EcbMod.get mqls x = Some (absmbox a,wl) ->\n *                                          (exists b, a= Vptr b) ->\n *                                          absinfer\n *                                            ( <|| mbox_post (Vptr x :: Vptr y :: nil) ||>  **HECBList mqls ** \n *                                                  HTCBList tcbls ** HTime t ** HCurTCB ct ** P) \n *                                            (<|| END (Some (Vint32 (Int.repr MBOX_POST_FULL_ERR))) ||> **HECBList mqls ** HTCBList tcbls ** HTime t ** HCurTCB ct  ** P).\n * Proof.\n *   infer_solver 4%nat.\n * Qed. *)\n\nLemma something_in_not_nil : forall (T:Type) (y: @list T), y<>nil -> exists x, In x y.\nProof.\n  intros T y.\n  elim y.\n  intro; tryfalse.\n  intros.\n  exists a.\n  simpl.\n  left; auto.\nQed.\n\nLemma rg1 :  forall x2 x6 ,  0 <= Int.unsigned x2 < 64->\n                             x6 = $ Int.unsigned x2&ᵢ$ 7 ->\n                             0<= Int.unsigned x6 < 8.\nProof.\n  intros.\n  subst x6.\n\n  mauto.\nQed.\n\nLemma rg2 :  forall x2 x7 ,  0 <= Int.unsigned x2 < 64->\n                             x7 = Int.shru ($ Int.unsigned x2) ($ 3) ->\n                             0<= Int.unsigned x7 < 8.\nProof.\n  intros.\n  subst x7.\n  mauto.\nQed.\n\nLemma post_exwt_succ_pre_mbox'\n: forall (v'36 v'13 : vallist) (v'12 : int32) \n         (v'32 : block) (v'15 : int32) (v'24 : val) \n         (v'35 v'0 : val) (v'8 : tid) (v'9 v'11 : EcbMod.map)\n         (x : val) (x1 : waitset)\n         (v'6 v'10 : EcbMod.map) (v'38 v'69 v'39 : int32) \n         (v'58 : block) (a : priority)\n         (c : msg) (v'62 v'7 : TcbMod.map) \n         (vhold : addrval),\n    v'12 = Int.zero ->\n    R_PrioTbl_P v'36 v'7 vhold ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    R_ECB_ETbl_P (v'32, Int.zero)\n                 (V$OS_EVENT_TYPE_MBOX\n                   :: Vint32 v'12\n                   :: Vint32 v'15 :: v'24 :: v'35 :: v'0 :: nil,\n                  v'13) v'7 ->\n    RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    EcbMod.joinsig (v'32, Int.zero) (absmbox x , x1) v'6 v'10 ->\n    x1 = nil\n.\nProof.\n  intros.\n  unfolds in H2.\n  destruct H2 as (H2 & H2' & _).\n  destruct H2 as (_ & _ & H2 & _).\n  destruct H2' as (_ & _ & H2' & _).\n  unfolds in H2.\n  unfolds in H2'.\n  \n\n  unfolds in H3.\n  unfolds in H1.\n  unfolds in H0.\n  destruct H3 as (_ & _ & H3 & _).\n  unfolds in H3.\n  destruct H3 as (H3 & H3').\n\n  lets Hg : EcbMod.join_joinsig_get H4 H5.\n  clear H4 H5.\n  assert ( x1 = nil \\/ x1 <> nil) by tauto.\n  destruct H4; intros; auto.\n\n  idtac.\n  apply something_in_not_nil in H4.\n  inversion H4.\n  assert (EcbMod.get v'11 (v'32, Int.zero) = Some (absmbox x, x1) /\\ In x0 x1) by tauto.\n  lets aadf : H3 H6.\n  mytac.\n  lets bbdf : H2' H7.\n  destruct bbdf.\n  unfolds in H.\n  do 3 destruct H.\n  destruct H as (Ha & Hb & Hc & Hd& He).\n  cut ( 0<=(∘(Int.unsigned x7)) <8)%nat.\n  intro.\n  assert (V$0 = V$0) by auto.\n  lets adfafd : H1 H Hd H12.\n  destruct adfafd.\n  destruct H13.\n  destruct H14.\n  cut ( $ 0&ᵢ($ 1<<ᵢ$ Z.of_nat ∘(Int.unsigned x7)) = $ 0).\n  intro.\n  apply H13 in H17.\n  subst x8.\n\n  lets rg : rg1 Ha Hb.\n  clear -He rg.\n  false.\n  gen He.\n  mauto.\n\n  lets rg : rg2 Ha Hc.\n  clear -rg.\n  mauto.\n\n  lets rg : rg2 Ha Hc.\n  clear -rg.\n  mauto.\nQed.\n\nLemma val_inj_lemma: forall m0 a,  val_inj (notint (val_inj (val_eq m0 a))) = Vint32 Int.zero \\/\n                                   val_inj (notint (val_inj (val_eq m0 a))) = Vnull -> m0 = a.\n  intros.\n\n  destruct H; intros; int auto.\n  destruct m0; destruct a; try destruct a0; try destruct m0; simpl in *; int auto.\n  destruct a; int auto.\n  apply unsigned_inj in e.\n  subst.\n  auto.\n\n  destruct a.\n  int auto.\n  destruct (peq b b0).\n  apply unsigned_inj in e;subst;auto.\n\n  int auto.\n  destruct (peq b b0); int auto.\n  destruct (val_eq m0 a).\n  destruct v; int auto.\n  int auto.\nQed.\n\n\nLemma AOSTCBPrioTbl_high_tcblist_get_msg :\n  forall tcbls p prio st m vl rtbl m' s P av,\n    TcbMod.get tcbls p = Some (prio, st, m) ->\n    s|= AOSTCBPrioTbl vl rtbl tcbls av ** P ->\n    s|= AOSTCBPrioTbl vl rtbl (TcbMod.set tcbls p (prio, st, m')) av ** P.\nProof.\n  introv Htcb Hs.\n  sep cancel 2%nat 2%nat.\n  unfold AOSTCBPrioTbl  in Hs.\n  unfold AOSTCBPrioTbl.\n  sep cancel 1%nat 1%nat.\n  sep split in Hs.\n  sep split; eauto.\n  unfolds.\n  unfolds  in H1.\n  unfolds in   H0.\n  splits.\n  intros.\n  destruct H1.\n  lets Hrs : H1 H2 H3 H4.\n  mytac.\n  assert (tcbid = p \\/ tcbid <> p) by tauto.\n  destruct H10.\n  subst.\n  unfold get in *; simpl in *.\n\n  rewrite Htcb in H6.\n  inverts H6.\n  exists  x m'.\n  rewrite TcbMod.set_sem.\n  erewrite tidspec.eq_beq_true; eauto.\n  exists x x0.\n  rewrite TcbMod.set_sem.\n  erewrite tidspec.neq_beq_false; eauto.\n  intros.\n  assert (tcbid = p \\/ tcbid <> p) by tauto.\n  destruct H3.\n  subst.\n  rewrite TcbMod.set_sem in H2.\n  erewrite tidspec.eq_beq_true in H2; eauto.\n  inverts H2.\n  destruct H1.\n  eapply H2; eauto.\n  rewrite TcbMod.set_sem in H2.\n  erewrite tidspec.neq_beq_false in H2; eauto.\n  destruct H1.\n  eapply H4; eauto.\n  destruct H1.\n  destruct H2.\n  eapply R_Prio_NoChange_Prio_hold; eauto.\nQed.\n\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/ucos_lib/Mbox_common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038302, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22145500722782935}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\n\nSection CroniesCorrectInterface.\n\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Definition votes_received_cronies net :=\n    forall h crony,\n      In crony (votesReceived (snd (nwState net h))) ->\n      (type (snd (nwState net h)) = Leader \\/ type (snd (nwState net h)) = Candidate) ->\n      In crony (cronies (fst (nwState net h))\n                        (currentTerm (snd (nwState net h)))).\n\n  Definition cronies_votes net :=\n    forall t candidate crony,\n      In crony (cronies (fst (nwState net candidate)) t) ->\n      In (t, candidate) (votes (fst (nwState net crony))).\n\n  Definition votes_nw net :=\n    forall p t,\n      pBody p = RequestVoteReply t true ->\n      In p (nwPackets net) ->\n      In (t, pDst p) (votes (fst (nwState net (pSrc p)))).\n\n  Definition votes_received_leaders net :=\n    forall h,\n      type (snd (nwState net h)) = Leader ->\n      wonElection (dedup name_eq_dec (votesReceived (snd (nwState net h)))) = true.\n\n  Definition cronies_correct net :=\n    votes_received_cronies net /\\ cronies_votes net /\\ votes_nw net /\\ votes_received_leaders net.\n\n  Class cronies_correct_interface : Prop :=\n    {\n      cronies_correct_invariant :\n        forall (net : network),\n          refined_raft_intermediate_reachable net ->\n          cronies_correct net\n    }.\nEnd CroniesCorrectInterface.", "meta": {"author": "ahmet-celik", "repo": "pverdi", "sha": "dc88c4a5fd7d90b5bb48e583bd8286097f983f81", "save_path": "github-repos/coq/ahmet-celik-pverdi", "path": "github-repos/coq/ahmet-celik-pverdi/pverdi-dc88c4a5fd7d90b5bb48e583bd8286097f983f81/raft/CroniesCorrectInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.3276683008207139, "lm_q1q2_score": 0.22142663429142195}}
{"text": "(*********************************************************************)\n(*             Stability in Weak Memory Models                       *)\n(*                                                                   *)\n(*   Jade Alglave INRIA Paris-Rocquencourt, France                   *)\n(*                University of Oxford, UK                           *)\n(*                                                                   *)\n(*  Copyright 2010 Institut National de Recherche en Informatique et *)\n(*  en Automatique. All rights reserved. This file is distributed    *)\n(*  under the terms of the Lesser GNU General Public License.        *)\n(*********************************************************************)\n\nRequire Import Ensembles.\nRequire Import Arith.\nRequire Import Bool.\nFrom CoqCat Require Import util.\nFrom CoqCat Require Import wmm.\nFrom CoqCat Require Import basic.\nFrom CoqCat Require Import hierarchy.\nFrom CoqCat Require Import sc.\nFrom CoqCat Require Import valid.\nFrom CoqCat Require Import covering.\nFrom CoqCat Require Import drf.\nRequire Import Classical_Prop.\n(*Require Import orders.*)\nImport OEEvt.\nSet Implicit Arguments.\n\nModule Locks (A: Archi) (dp:Dp).\n\nModule ARes <: Archi.\n\nParameter ppo : Event_struct -> Rln Event.\n\nHypothesis ppo_valid : forall E, rel_incl (ppo E) (po_iico E).\n\nHypothesis ppo_fun :\n  forall E s x y,\n  ppo E x y /\\ s x /\\ s y <->\n  ppo (mkes (Intersection Event (events E) s) (rrestrict (iico E) s)) x y.\n\nParameter inter : bool.\nParameter intra : bool.\n\nParameter abc : Event_struct -> Execution_witness -> Rln Event.\n\nHypothesis ab_evts : forall (E:Event_struct) (X:Execution_witness),\n  forall x y, well_formed_event_structure E ->\n  rfmaps_well_formed E (events E) (rf X) ->\n  abc E X x y -> In _ (events E) x /\\ In _ (events E) y.\n\nHypothesis ab_incl :\n  forall E X, rel_incl (abc E X) (tc (rel_union (com E X) (po_iico E))).\n\nHypothesis ab_fun :\n  forall E X s x y,\n  well_formed_event_structure E ->\n  rfmaps_well_formed E (events E) (rf X) ->\n  (abc E X x y /\\ s x /\\ s y <->\n  abc (mkes (Intersection Event (events E) s) (rrestrict (iico E) s))\n    (mkew (rrestrict (ws X) s) (rrestrict (rf X) s)) x y).\n\nParameter stars : Event_struct -> set Event.\n\nEnd ARes.\n\nImport ARes.\n\n(** locks *)\nModule An <: Archi.\n\nDefinition ppo := A.ppo.\n\nLemma ppo_valid : forall E, rel_incl (ppo E) (po_iico E).\nProof.\n  apply A.ppo_valid.\nQed.\n\nLemma ppo_fun :\n  forall E s x y,\n  ppo E x y /\\ s x /\\ s y <->\n  ppo (mkes (Intersection Event (events E) s) (rrestrict (iico E) s)) x y.\nProof.\n  apply A.ppo_fun.\nQed.\n\nDefinition inter := A.inter.\nDefinition intra := A.intra.\n\nDefinition abc (E:Event_struct) (X:Execution_witness) : Rln Event :=\n  fun e1 => fun e2 => False.\n\nLemma ab_evts : forall (E:Event_struct) (X:Execution_witness),\n  forall x y, well_formed_event_structure E ->\n  rfmaps_well_formed E (events E) (rf X) ->\n abc E X x y -> In _ (events E) x /\\ In _ (events E) y.\nProof.\nintros E X x y Hwf Hrf Hxy. inversion Hxy.\nQed.\n\nLemma ab_incl :\n  forall E X, rel_incl (abc E X) (tc (rel_union (com E X) (po_iico E))).\nProof.\nintros E X x y Hxy. inversion Hxy.\nQed.\n\nLemma ab_fun :\n  forall E X s x y,\n  well_formed_event_structure E ->\n  rfmaps_well_formed E (events E) (rf X) ->\n  (abc E X x y /\\ s x /\\ s y <->\n  abc (mkes\n   (Intersection Event (events E) s) (rrestrict (iico E) s))\n    (mkew (rrestrict (ws X) s) (rrestrict (rf X) s)) x y).\nProof.\nintros E X s x y Hwf Hrfwf; split; intro Hxy.\n  destruct Hxy as [Hxy ?]; inversion Hxy.\n  inversion Hxy.\nQed.\n\nParameter stars : Event_struct -> set Event.\n\nEnd An.\n\nModule AnWmm := Wmm An dp.\n\nModule VA := Valid An dp.\nImport VA. Import VA.ScAx.\nModule Covering := Covering ARes An dp.\nImport Covering.\n\nDefinition atom (E:Event_struct) (r w: Event) (l:Location): Prop :=\n  reads E r /\\ stars E r /\\ loc r = l /\\\n  writes E w /\\ stars E w /\\ loc w = l /\\ po_iico E r w /\\\n  ~(exists e, stars E e /\\ po_iico E r e /\\ po_iico E e w) /\\\n         (forall X, ~(exists w', proc_of w' <> proc_of r /\\\n                       writes E w' /\\ loc w' = l /\\ fr E X r w' /\\ ws X w' w)). (*w' pas sur le meme proc*)\n\nLtac destruct_atom H :=\n  destruct H as [Hr [Hatr [Hlr [Hw [Haw [Hlw [Hporw [Hnoc Hno]]]]]]]].\n\nDefinition taken (E:Event_struct) (l:Location) r : Prop :=\n  (exists w, atom E r w l (*/\\ value_of r = Some 0 /\\ value_of w = Some 1*)).\n\nDefinition free (E:Event_struct) (l:Location) r w : Prop :=\n  po_iico E r w /\\ taken E l r /\\ loc w = l (*/\\ value_of w = Some 0*).\n\nDefinition ImportBarrier (E: Event_struct) (b: Event) : Prop :=\n  forall X,\n  (forall r e, reads E r -> stars E r -> po_iico E r b -> po_iico E b e -> abc E X r e) (*/\\\n  (forall r w rw, reads E r -> po_iico E r b -> po_iico E b w -> rf X w rw -> abc E X r rw)*).\n\nDefinition ExportBarrier (E: Event_struct) (b: Event) : Prop :=\n  forall X,\n  (forall e w r, stars E r ->\n    po_iico E e b -> po_iico E b w -> rf X w r -> abc E X e r) (*/\\\n  (forall e1 e2, po_iico E e1 b -> po_iico E b e2 -> ~(writes E e1 /\\ reads E e2) -> abc E X e1 e2)*).\n\nDefinition Lock (E:Event_struct) (l:Location) (r c:Event) : Prop :=\n  taken E l r /\\ ImportBarrier E c /\\ po_iico E r c.\n\nDefinition Unlock (E:Event_struct) (l:Location) r (b w:Event) : Prop :=\n  free E l r w /\\ ExportBarrier E b /\\ po_iico E b w.\n\nRecord Cs' : Type := mkcs\n{Read: Event ;\n  Ib: Event ;\n  Eb: Event;\n  Write: Event;\n  Evts: set Event}.\n\nDefinition Cs := Cs'.\n\nDefinition cs (E:Event_struct) (l:Location) crit :=\n  Lock E l crit.(Read) crit.(Ib) /\\\n  (forall e, crit.(Evts) e <-> po_iico E crit.(Ib) e /\\ po_iico E e crit.(Eb)) /\\\n  Unlock E l crit.(Read) crit.(Eb) crit.(Write) /\\\n  po_iico E crit.(Ib) crit.(Eb).\n\nDefinition evts (cs:Cs) := Evts cs.\n\nDefinition sc E l :=\n  fun s1 => fun s2 => cs E l s1 /\\ cs E l s2 /\\ s1 <> s2.\n\nDefinition s E (X:Execution_witness) :=\n  fun e1 => fun e2 => exists l, exists s1, exists s2, sc E l s1 s2 /\\ evts s1 e1 /\\ evts s2 e2.\n\nDefinition css E X l :=\n   fun s1 => fun s2 => sc E l s1 s2 /\\\n    (rf X) s1.(Write) s2.(Read).\n\nLtac destruct_css H :=\n  destruct H as [[Hcs1 [Hcs2 Hdcs]] Hrf].\n\nDefinition css_lift E X l :=\n  fun e1 => fun e2 => exists s1, exists s2,\n    css E X l s1 s2 /\\ (Evts s1) e1 /\\ (Evts s2) e2.\n\nLtac destruct_csslift H :=\n  destruct H as [s1 [s2 [Hcss [Hev1 Hev2]]]].\n\nInductive lockc' E X l : Event -> Event -> Prop :=\n  | RF : forall e1 e2, css_lift E X l e1 e2 -> lockc' E X l e1 e2\n  | Trans :\n    forall e1 e e2,\n    lockc' E X l e1 e -> lockc' E X l e e2 -> lockc' E X l e1 e2.\n\nDefinition lockc E X l := lockc' E X l.\nDefinition lock E X := fun e1 => fun e2 => exists l, lockc E X l e1 e2.\n\nParameter inite : Location -> Event.\n\nAxiom init_evt : forall E l, events E (inite l).\nAxiom init_store : forall l, write_to (inite l) l.\nAxiom init_ws : forall X l, ~(exists e, ws X e (inite l)).\nAxiom init_cs : forall E l cr, cs E l cr /\\ Write cr = inite l -> Evts cr (inite l).\n\nModule DaRaFr := DataRaceFree ARes A dp.\nImport DaRaFr.\nModule HB : HappensBefore.\nModule AResDrf := DataRaceFree ARes A dp.\nImport AResDrf.\nModule AResBasic := Basic ARes dp.\nImport AResBasic.\nModule AResWmm := Wmm ARes dp.\nImport AResWmm.\nImport ARes.\n\nDefinition sync := s.\n\nDefinition happens_before E X :=\n  tc (rel_union (po_iico E) (sync E X)).\n\nHypothesis happens_before_compat_com :\n  forall E X x y, com E X x y -> ~(happens_before E X y x).\n\nDefinition competing E (X:Execution_witness) :=\n  fun e1 => fun e2 => events E e1 /\\ events E e2 /\\\n    loc e1 = loc e2 /\\ proc_of e1 <> proc_of e2 /\\\n    (writes E e1 \\/ writes E e2).\n\nDefinition cns E X :=\n  fun e1 => fun e2 => competing E X e1 e2 /\\\n  ~ (happens_before E X e1 e2 \\/ happens_before E X e2 e1).\n\nDefinition convoluted_wf :=\n  forall E X Y x y,\n  competing E X x y ->\n  ~ (happens_before E X x y \\/ happens_before E X y x) ->\n  rf Y = so_rfm E\n         (LE (tc (rel_union (rel_union (rel_inter (cns E X) (pair x y)) (A.ppo E)) (pio_llh E)))) ->\n  ws Y = so_ws\n         (LE (tc (rel_union (rel_union (rel_inter (cns E X) (pair x y)) (A.ppo E)) (pio_llh E)))) ->\n  competing E Y x y /\\ ~ (happens_before E Y x y \\/ happens_before E Y y x).\n\nLemma compete_in_events :\n  forall E X x y,\n  well_formed_event_structure E ->\n  rfmaps_well_formed E (events E) (rf X) ->\n  competing E X x y ->\n  events E x /\\ events E y.\nProof.\nintros E X x y Hwf Hrfwf [Hex [Hey ?]]; split; auto.\nQed.\n\nLemma udr_xy_ppo2_in_events :\n  forall E X r x y,\n  well_formed_event_structure E ->\n  rfmaps_well_formed E (events E) (rf X) ->\n  competing E X x y ->\n  Included _   (Union _ (dom (tc (rel_union (rel_union (rel_inter r (pair x y)) (A.ppo E)) (pio_llh E))))\n     (ran (tc (rel_union (rel_union (rel_inter r (pair x y)) (A.ppo E)) (pio_llh E))))) (events E).\nProof.\nintros E X r x y Hwf Hwfrf Hc e1 Hudr.\ngeneralize (compete_in_events Hwf Hwfrf Hc); intros [Hex Hey].\ninversion Hudr as [e Hd |e Hr].\ngeneralize (dom_tc_in_dom Hd); intros [e2 Hi];\n  inversion Hi as [Hu | Hpio].\n  inversion Hu as [Hp | Hppo].\n  destruct Hp as [? [? ?]]; subst; auto.\napply ABasic.po_iico_domain_in_events with e2; auto.\napply A.ppo_valid; auto.\ndestruct Hpio as [? [Hpo ?]].\napply ABasic.po_iico_domain_in_events with e2; auto.\ngeneralize (ran_tc_in_ran Hr); intros [e2 Hi];\n  inversion Hi as [Hu | Hpio].\n  inversion Hu as [Hp | Hppo].\n  destruct Hp as [? [? ?]]; subst; auto.\napply ABasic.po_iico_range_in_events with e2; auto.\napply A.ppo_valid; auto.\ndestruct Hpio as [? [Hpo ?]].\napply ABasic.po_iico_range_in_events with e2; auto.\nQed.\n\nLtac destruct_valid H :=\n  destruct H as [[Hws_tot Hws_cands] [[Hrf_init [Hrf_cands Hrf_uni]] [Hsp [Hth Hvalid]]]];\n  unfold write_serialization_well_formed in Hws_tot(*; unfold uniproc in Hsp*).\n\nLemma u_in_pair_po :\n  forall E X x y e1 e2,\n  tc (rel_union (rel_union (rel_inter (cns E X) (pair x y)) (A.ppo E))\n          (pio_llh E)) e1 e2 ->\n  tc (rel_union (rel_inter (cns E X) (pair x y)) (po_iico E)) e1 e2.\nProof.\nintros E X x y e1 e2 H12.\ninduction H12 as [e1 e2 Hu |]; [apply trc_step|].\n  inversion Hu as [Hun | Hpio].\n    inversion Hun as [Hp | Hppo].\n      left; auto.\n      right; apply A.ppo_valid; auto.\n      right; destruct Hpio as [? [? ?]]; auto.\n  apply trc_ind with z; auto.\nQed.\n\nLemma competing_irr : forall E X,\n  well_formed_event_structure E ->\n  AWmm.valid_execution E X ->\n  ~ (exists z, competing E X z z).\nProof.\nintros E X Hwf Hv [z [? [? [? [Hdp ?]]]]].\napply Hdp; trivial.\nQed.\n\nLemma pair_irr :\n  forall E X x y,\n  well_formed_event_structure E ->\n  AWmm.valid_execution E X ->\n  ~ (exists z, (rel_inter (cns E X) (pair x y) z z)).\nProof.\nintros E X x y Hwf Hv1 [z [[Hx Hy] [Hc ?]]].\ndestruct Hc as [? [? [? [Hdp ?]]]].\n   assert (exists z, competing E X z z) as Hc.\n     exists z; auto.\n    apply (competing_irr Hwf Hv1 Hc).\nQed.\n\nLemma competing_not_po :\n  forall E X x y,\n  well_formed_event_structure E ->\n    AWmm.valid_execution E X ->\n  competing E X x y -> ~ (po_iico E y x).\nProof.\nintros E X x y Hwf Hv [? [? [? [Hdp ?]]]] Hpo.\nassert (In _ (events E) x) as Hx.\n  apply AResBasic.po_iico_range_in_events with y; auto.\nassert (In _ (events E) y) as Hy.\n  apply AResBasic.po_iico_domain_in_events with x; auto.\ngeneralize (AResBasic.po_implies_same_proc Hwf Hy Hx Hpo); intro Heq;\nsubst; auto.\nQed.\n\nLemma tc_pair_po_in_pair_po :\n  forall E X x y,\n  well_formed_event_structure E ->\n  AWmm.valid_execution E X ->\n  rel_incl (tc (rel_seq (rel_inter (cns E X) (pair x y)) (po_iico E)))\n    (rel_seq (rel_inter (cns E X) (pair x y)) (po_iico E)).\nProof.\nintros E X x y Hwf Hv1 e1 e2 H12.\ninduction H12; auto.\n  destruct IHtc1 as [z1 [H1 Hz1]];\n  destruct IHtc2 as [z2 [H2 Hz2]].\n  assert (po_iico E y x) as Hpo.\n    destruct H1 as [? [? Hy]]; rewrite Hy in Hz1.\n    destruct H2 as [? [Hx ?]]; rewrite Hx in Hz1.\n  auto.\n  destruct H1 as [Hc [Hx Hy]];\n    rewrite Hx in Hc; rewrite Hy in Hc.\n  destruct Hc as [Hc ?].\n  generalize (competing_not_po Hwf Hv1 Hc); intro; contradiction.\nQed.\n\nLemma competing_ac_ppo2 :\n  forall E X x y,\n  well_formed_event_structure E ->\n  AWmm.valid_execution E X ->\n  competing E X x y ->\n  (forall z, ~ tc (rel_union (rel_union (rel_inter (cns E X) (pair x y)) (A.ppo E)) (pio_llh E)) z z).\nProof.\nintros E X x y Hwf Hv Hc z Hz.\ngeneralize (u_in_pair_po Hz); intro Hu.\nrewrite union_triv in Hu.\nassert (~ (exists x, po_iico E x x)) as Hi1.\n  intros [e He]; apply (A2Basic.po_ac Hwf He).\nassert (~ (exists z, (rel_inter (cns E X) (pair x y)) z z)) as Hi2.\n  apply pair_irr; auto.\nassert (~ (exists z, (rel_union (po_iico E) (rel_inter (cns E X) (pair x y)) z z))) as Hiu.\n  intros [e He]; inversion He.\n    apply (A2Basic.po_ac Hwf H).\n    assert (exists z, rel_inter (cns E X) (pair x y) z z) as Hco.\n      exists e; auto.\n    apply (pair_irr Hwf Hv Hco).\nassert (trans (rel_inter (cns E X) (pair x y))) as Ht2.\n  unfold trans; intros e1 e2 e3 H12 H23.\n  destruct H12 as [? [? Hy]];\n  destruct H23 as [[Hco ?] [Hx Hy2]].\n  rewrite Hx in Hco; rewrite Hy2 in Hco.\n  rewrite <- Hx in Hco; rewrite <- Hy in Hco.\n  assert (exists z, competing E X z z) as Hcon.\n    exists e2; auto.\n  generalize (competing_irr Hwf Hv Hcon); intro Ht; inversion Ht.\nassert (trans (po_iico E)) as Ht1.\n  intros e1 e2 e3 H12 H23; apply A2Basic.po_trans with e2; auto.\ngeneralize (union_cycle_implies_seq_cycle2 Hi1 Hi2 Hiu Ht2 Ht1 Hu);\n  intros [e Htc].\ngeneralize (tc_pair_po_in_pair_po Hwf Hv Htc); intro He.\ndestruct He as [e' [[[Hee' ?] ?] He'e]].\ngeneralize (competing_not_po Hwf Hv Hee'); intro; contradiction.\nQed.\n\nLemma convoluted_wf_implies_wf :\n  convoluted_wf ->\n  (forall E X x y,\n  well_formed_event_structure E ->\n  AResWmm.valid_execution E X ->\n  competing E X x y ->\n  ~ (happens_before E X x y \\/ happens_before E X y x) ->\n  (exists Y, AnWmm.valid_execution E Y /\\\n  competing E Y x y /\\ ~ (happens_before E Y x y \\/ happens_before E Y y x))).\nProof.\nintros Hcwf E X x y Hwf Hv1 Hcxy Hns.\nassert (exists so, vexec E so /\\\n               so_rfm E so = (so_rfm E\n                 (LE (tc (rel_union (rel_union (rel_inter (cns E X) (pair x y))\n                       (A.ppo E)) (pio_llh E))))) /\\\n               so_ws so = (so_ws\n               (LE (tc (rel_union (rel_union (rel_inter (cns E X) (pair x y))\n                       (A.ppo E)) (pio_llh E)))))) as Hvexec.\n  exists (LE (tc (rel_union (rel_union (rel_inter (cns E X) (pair x y))\n                       (A.ppo E)) (pio_llh E)))).\n  split; [|split]; auto.\n\n  assert (partial_order (tc (rel_union (rel_union (rel_inter (cns E X) (pair x y)) (A.ppo E)) (pio_llh E))) (events E)) as Hp.\n    split.\n      apply udr_xy_ppo2_in_events with X; auto.\n      destruct_valid Hv1; split; auto.\n      split.\n        intros x1 x2 x3 [H12 H23]; apply trc_ind with x2; auto.\n        intro e; apply competing_ac_ppo2; auto.\n  assert (Included _ (events E) (events E)) as Htriv.\n    unfold Included; trivial.\n  generalize (OE Htriv Hp); intros [Hincl Hle].\n  split; auto.\n    apply lin_implies_part; auto.\n    generalize (le_lso Hle); intro Heq; rewrite Heq.\n    split.\n      apply incl_ac with (LE\n           (tc\n              (rel_union (rel_union (rel_inter (cns E X) (pair x y)) (A.ppo E))\n                 (pio_llh E)))).\n        intros e1 e2 H12; inversion H12 as [Hppo|]; auto.\n        apply Hincl; apply trc_step; left; right; auto.\n    generalize (lso_is_tc Hle); intro Htc.\n    intros e He; rewrite Htc in He; destruct_lin Hle;\n    apply (Hac e He).\n\n      apply incl_ac with (LE\n           (tc\n              (rel_union (rel_union (rel_inter (cns E X) (pair x y)) (A.ppo E))\n                 (pio_llh E)))).\n        intros e1 e2 H12; inversion H12 as [Hppo|]; auto.\n        apply Hincl; apply trc_step; right; auto.\n    generalize (lso_is_tc Hle); intro Htc.\n    intros e He; rewrite Htc in He; destruct_lin Hle;\n    apply (Hac e He).\n\ngeneralize (ScModel.vexec_is_valid E\n  (so_rfm E (LE (tc (rel_union (rel_union (rel_inter (cns E X) (pair x y))\n                       (A.ppo E)) (pio_llh E)))))\n  (so_ws\n               (LE (tc (rel_union (rel_union (rel_inter (cns E X) (pair x y))\n                       (A.ppo E)) (pio_llh E)))))\n  Hwf Hvexec); intros [Y [Hv2Y [? ?]]].\n  exists Y; split; auto.\nQed.\n\nLemma convoluted_wf_holds :\n  convoluted_wf.\nProof.\nintros E X Y x y Hcxy Hnxy Hrf Hwf.\nsplit; [apply Hcxy |apply Hnxy].\nQed.\n\nLemma hb_stable :\n (* forall E X x y,\n  well_formed_event_structure E ->\n  A1Wmm.valid_execution E X ->\n  competing E X x y ->\n  ~ (happens_before E X x y \\/ happens_before E X y x) ->\n  (exists Y, A2nWmm.valid_execution E Y /\\\n  competing E Y x y /\\ ~ (happens_before E Y x y \\/ happens_before E Y y x)).*)\n\n  forall E X x y,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  competing E X x y ->\n  ~ (happens_before E X x y \\/ happens_before E X y x) ->\n  (exists Y, AnWmm.valid_execution E Y /\\\n  competing E Y x y /\\ ~ (happens_before E Y x y \\/ happens_before E Y y x)).\nProof.\nintros E X x y Hwf HX Hcxy Hnxy.\napply convoluted_wf_implies_wf with X; auto.\nunfold convoluted_wf; apply convoluted_wf_holds.\nQed.\n\n(*Import OEEvt.*)\n\n(** DRF progs have SC sem *)\n\nLemma in_lockc_rf_case_implies_in_ab :\n  forall E X l e1 e2,\n    well_formed_event_structure E ->\n    valid_execution E X ->\n    css_lift E X l e1 e2 ->\n    tc (abc E X) e1 e2.\nProof.\nintros E X l e1 e2 Hwf Hv Hcsslift.\ndestruct_csslift Hcsslift.\n  destruct_css Hcss.\ndestruct Hcs1 as [HL1 [Hee1 [HUL1 Hib1]]].\n  destruct HUL1 as [Hur1 [Heb1 Hpobw1]].\ndestruct Hcs2 as [[Hres2 [Hib2 Hporc2]] [Hee2 HUL2]].\napply trc_ind with (Read s2); auto; apply trc_step; auto.\n\n  (*destruct (Heb1 X) as [Hcumul Hbase].*) generalize (Heb1 X); intro Hcumul.\n  apply (Hcumul e1 (Write s1) (Read s2)).\n  destruct Hres2 as [? (*[*)Hat2 (*?]*)]; destruct_atom Hat2; auto.\n  destruct (Hee1 e1) as [Hee1d Hee1b].\n  subst; destruct (Hee1d Hev1); auto.\n  auto.\n  auto.\n\n  (*destruct (Hib2 X) as [Hbase Hcumul]*)\n  generalize (Hib2 X); intro Hbase.\n  apply (Hbase (Read s2) e2); auto.\n    split; destruct_valid Hv;\n      [apply ran_rf_in_events with X (Write s1) |\n       apply ran_rf_is_read with E X (Write s1)]; auto; split; auto.\n  destruct Hres2 as [? (*[*)Hat2 (*?]*)]; destruct_atom Hat2; auto.\n  destruct (Hee2 e2) as [Hee2d Hee2b].\n  subst; destruct (Hee2d Hev2); auto.\nQed.\n\nLemma in_lockc_implies_in_ab :\n  forall E X l e1 e2,\n    well_formed_event_structure E ->\n    valid_execution E X ->\n    lockc E X l e1 e2 ->\n    tc (abc E X) e1 e2.\nProof.\nintros E X l e1 e2 Hwf Hv H12.\ninduction H12.\n  apply (in_lockc_rf_case_implies_in_ab Hwf Hv H).\n  apply trc_ind with e; auto.\nQed.\n\nLemma lockc_u_ghb_in_ghb :\n  forall E X l,\n    well_formed_event_structure E ->\n    valid_execution E X ->\n    rel_incl (tc (rel_union (lockc E X l) (ghb E X))) (tc (ghb E X)).\nProof.\nintros E X l Hwf Hv x y H.\ninduction H as [x y Hxy |].\ninversion Hxy.\n\n  assert (rel_incl (abc E X) (ghb E X)) as Hi.\n    apply ab_in_ghb; auto.\n  apply (tc_incl Hi).\n  apply in_lockc_implies_in_ab with l; auto.\n\n  apply trc_step; auto.\n\napply trc_ind with z; auto.\nQed.\n\nLemma lockc_ghb : forall E X l,\n    well_formed_event_structure E ->\n    valid_execution E X ->\n    acyclic (rel_union (lockc E X l) (ghb E X)).\nProof.\nintros E X l Hwf Hv x Hx.\ngeneralize (lockc_u_ghb_in_ghb Hwf Hv Hx); intro Hcy.\ndestruct_valid Hv; apply (Hvalid x Hcy).\nQed.\n\nLemma lockc_irrefl :\n  forall E X l,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  ~(exists x, lockc E X l x x).\nProof.\nintros E X l Hwf Hv [x Hx].\ngeneralize (in_lockc_implies_in_ab Hwf Hv Hx); intro Hc.\ndestruct_valid Hv; unfold acyclic in Hvalid; apply (Hvalid x).\nassert (rel_incl (abc E X) (ghb E X)) as Hi.\n  intros e1 e2; apply ab_in_ghb; auto.\napply (tc_incl Hi Hc).\nQed.\n\nLemma lock_irrefl :\n  forall E X,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  ~(exists x, lock E X x x).\nProof.\nintros E X Hwf Hv [x [l Hx]].\ngeneralize (in_lockc_implies_in_ab Hwf Hv Hx); intro Hc.\ndestruct_valid Hv; unfold acyclic in Hvalid; apply (Hvalid x).\nassert (rel_incl (abc E X) (ghb E X)) as Hi.\n  intros e1 e2; apply ab_in_ghb; auto.\napply (tc_incl Hi Hc).\nQed.\n\nLemma po_irrefl :\n  forall E, well_formed_event_structure E ->\n  ~(exists x, po_iico E x x).\nProof.\nintros E Hwf [x Hx]. apply (po_ac Hwf Hx).\nQed.\n\nLemma lockc_po_irrefl :\n  forall E X l,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  ~(exists x, (rel_union (po_iico E) (lockc E X l)) x x).\nProof.\nintros E X l Hwf Hv [x Hx]; inversion Hx.\n  assert (exists x, po_iico E x x) as He.\n    exists x; auto.\n  apply (po_irrefl Hwf He); auto.\n  assert (exists x, lockc E X l x x) as He.\n    exists x; auto.\n  apply (lockc_irrefl Hwf Hv He).\nQed.\n\nLemma lock_po_irrefl :\n  forall E X,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  ~(exists x, (rel_union (po_iico E) (lock E X)) x x).\nProof.\nintros E X Hwf Hv [x Hx]; inversion Hx.\n  assert (exists x, po_iico E x x) as He.\n    exists x; auto.\n  apply (po_irrefl Hwf He); auto.\n  assert (exists x, lock E X x x) as He.\n    exists x; auto.\n  apply (lock_irrefl Hwf Hv He).\nQed.\n\nLemma lockc_trans :\n  forall E X l,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  trans (lockc E X l).\nProof.\nintros E X l Hwf Hv x y z Hxy Hyz.\nunfold lockc in * |- *;\napply Trans with y; auto.\nQed.\n\nLemma po_trans :\n  forall E, well_formed_event_structure E ->\n  trans (po_iico E).\nProof.\n  intros E Hwf x y z Hxy Hyz. apply po_trans with y; auto.\nQed.\n\nLemma lockc_rf_implies_in_ab_with_lwarx :\n forall E X l e1 s1 s2,\n    well_formed_event_structure E ->\n    valid_execution E X ->\n    Evts s1 e1 ->\n    css E X l s1 s2 ->\n    tc (abc E X) e1 (Read s2).\nProof.\nintros E X l e1 s1 s2 Hwf Hv Hev1 Hcss.\ndestruct_css Hcss.\ndestruct Hcs1 as [HL1 [Hee1 [HUL1 Hib1]]].\ndestruct HUL1 as [Hur1 [Heb1 Hpobw1]].\ndestruct Hcs2 as [[Hres2 [Hib2 Hporc2]] [Hee2 HUL2]].\napply trc_step; auto.\n\n  (*destruct (Heb1 X) as [Hcumul Hbase].*) generalize (Heb1 X); intro Hcumul.\n  apply (Hcumul e1 (Write s1) (Read s2)).\n  destruct Hres2 as [? (*[*)Hat2 (*?]*)]; destruct_atom Hat2; auto.\n  destruct (Hee1 e1) as [Hee1d Hee1b].\n  subst;\n  destruct (Hee1d Hev1); auto.\n  auto.\n  auto.\nQed.\n\nLemma lockc_seq_po_in_ab :\n  forall E X l x y z,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  lockc E X l x y -> po_iico E y z -> tc (abc E X) x z.\nProof.\nintros E X l x y z Hwf Hv Hxy Hyz.\ninduction Hxy.\n  destruct_csslift H.\n  destruct_css Hcss.\n  assert (po_iico E (Eb s2) z \\/ po_iico E z (Eb s2)) as Hor.\n    apply same_proc_implies_po; auto.\n    assert (In _ (events E) e2) as Hee2.\n      apply po_iico_domain_in_events with z; auto.\n    assert (In _ (events E) z) as Hez.\n      apply po_iico_range_in_events with e2; auto.\n    rewrite <- (po_implies_same_proc Hwf Hee2 Hez Hyz).\n    destruct Hcs2 as  [HL2 [Heve2 [HUL2 Hib2]]].\n    destruct HUL2 as [Hur2 [Heb2 Hpobw2]].\n    generalize (Heve2 e2); intros [Hd Hb].\n    subst; destruct (Hd Hev2) as [Hpoce2 Hpobe2].\n    assert (In _ (events E) (Eb s2)) as Heeb2.\n      apply po_iico_range_in_events with e2; auto.\n    rewrite <- (po_implies_same_proc Hwf Hee2 Heeb2 Hpobe2); trivial.\n    destruct Hcs2 as  [HL2 [Heve2 [HUL2 Hib2]]].\n    destruct HUL2 as [Hur2 [Heb2 Hpobw2]].\n    generalize (Heve2 e2); intros [Hd Hb].\n    subst; destruct (Hd Hev2) as [Hpoce2 Hpobe2].\n      apply po_iico_range_in_events with e2; auto.\n      apply po_iico_range_in_events with e2; auto.\n\n  inversion Hor as [Haf | Hbef].\n\n    apply trc_ind with (Read s2).\n    apply lockc_rf_implies_in_ab_with_lwarx\n      with l s1; auto.\n     split; auto.\n     split; auto.\n(*    destruct Hcs2 as [HL2 [Hee2 [Hur2 [Heb2 Hpobw2]]]].\n\n    apply trc_step; destruct (Heb2 X) as [Hcumul Hbase];\n      apply (Hbase (Read s2) z); auto.\n      destruct (Hee2 e2) as [Hee2d Hee2b].\n      apply po_trans with (Ib s2); auto.\n      destruct HL2 as [? [? Hrc2]]; auto.\n      apply po_trans with e2; auto.\n        destruct (Hee2d Hev2); auto.\n        destruct (Hee2d Hev2); auto.\n      destruct_valid Hv; generalize (ran_rf_is_read E X (Write s1) (Read s2) Hrf_cands Hrf);\n      intros [lr [vr Har]] [[? [lr' [vr' Hwr]]] ?].\n      rewrite Hwr in Har; inversion Har. *)\n      destruct Hcs2 as [[Htk2 [Hib2 Hporb]] [? HUL2]].\n      destruct Htk2 as [? (*[*)Hat2 (*?]*)]; destruct_atom Hat2.\n      apply trc_step; apply (Hib2 X); auto.\n      apply po_trans with (Eb s2); auto.\n      destruct HUL2 as [? ?]; auto.\n\n    apply in_lockc_rf_case_implies_in_ab\n      with l; auto.\n     exists s1; exists s2.\n     split; auto.\n      split; auto.\n    split; auto.\n    split; auto.\n    destruct Hcs2 as [HL2 [Hee2 [HUL2 Hieb2]]].\n    destruct HUL2 as [Hur2 [Heb2 Hpobw2]].\n    destruct (Hee2 z) as [? Hee2b].\n    apply Hee2b; split; auto.\n    apply po_trans with e2; auto.\n    destruct (Hee2 e2) as [Hee2d ?].\n    destruct (Hee2d Hev2); auto.\n\n  apply trc_ind with e.\n    apply in_lockc_implies_in_ab with l; auto.\n  apply (IHHxy2 Hyz).\n(*x in cs1 y in cs2 and y -po-> z\n   thus x -ab-> r2 by Bcumul of b1\n   and r2 -ab-> z by commit rule or lwsync base*)\nQed.\n\nLemma lockc_seq_po_ghb :\n  forall E X l x y,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  tc (rel_seq (lockc E X l) (po_iico E)) x y ->\n  tc (ghb E X) x y.\nProof.\nintros E X l x y Hwf Hv Hxy.\ninduction Hxy as [x y Hs |].\n\n  destruct Hs as [z [Hxz Hzy]].\n    generalize (lockc_seq_po_in_ab Hwf Hv Hxz Hzy); apply tc_incl.\n      apply ab_in_ghb; auto.\n\n  apply trc_ind with z; auto.\nQed.\n\nLemma lockc_in_ghb :\n  forall E X l x y,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  lockc E X l x y ->\n  tc (ghb E X) x y.\nProof.\nintros E X l x y Hwf Hv Hxy.\ninduction Hxy.\n destruct_csslift H. destruct_css Hcss.\n\n  apply trc_ind with (Read s2).\n    assert (rel_incl (abc E X) (ghb E X)) as Hincl.\n      intros x y Hxy; apply ab_in_ghb; auto.\n    apply (tc_incl Hincl).\n\n    apply lockc_rf_implies_in_ab_with_lwarx\n      with l s1; auto.\n     split; auto. split; auto.\n\n     destruct Hcs2 as [[Hres2 [Hib2 Hporc2]] [Hee2 HUL2]].\n\n        assert (rel_incl (abc E X) (ghb E X)) as Hincl.\n      intros x y Hxy; apply ab_in_ghb; auto.\n    apply (tc_incl Hincl). apply trc_step.\n    (*destruct (Hib2 X) as [Hbase Hcumul].*)\n      generalize (Hib2 X); intro Hbase.\n      apply (Hbase (Read s2) e2); auto.\n\n      destruct_valid Hv; split.\n\n      apply (ran_rf_in_events X (Write s1) (Read s2) Hwf). split; auto. auto.\n      generalize (ran_rf_is_read E X (Write s1) (Read s2) Hrf_cands Hrf); intros [lr (*[vr*) Har(*]*)].\n      exists lr; (*exists vr;*) auto.\n      destruct Hres2 as [? (*[*)Hat2 (*?]*)]; destruct_atom Hat2; auto.\n      destruct (Hee2 e2) as [Hee2d Hee2b].\n      destruct (Hee2d Hev2); auto.\n\n    apply trc_ind with e; auto.\nQed.\n\nLemma lock_in_ghb :\n  forall E X x y,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  lock E X x y ->\n  tc (ghb E X) x y.\nProof.\nintros E X x y Hwf Hv Hxy.\ndestruct Hxy as [l Hxy]; apply lockc_in_ghb with l; auto.\nQed.\n\nLemma tclock_in_ghb :\n  forall E X x y,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  tc (lock E X) x y ->\n  tc (ghb E X) x y.\nProof.\nintros E X x y Hwf Hv Hxy.\ninduction Hxy.\n  apply lock_in_ghb; auto.\n  apply trc_ind with z; auto.\nQed.\n\nLemma lock_seq_po_ghb :\n  forall E X x y,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  tc (rel_seq (tc (lock E X)) (maybe (po_iico E))) x y ->\n  tc (ghb E X) x y.\nProof.\nintros E X x y Hwf Hv Hxy.\ninduction Hxy as [x y Hs |].\n\n  destruct Hs as [z [Htc_xz Hor_zy]].\n  induction Htc_xz as [x z Hxz |].\n\n  destruct Hxz as [l Hxz].\n   inversion Hor_zy as [Hzy | Heq].\n    generalize (lockc_seq_po_in_ab Hwf Hv Hxz Hzy); apply tc_incl.\n      apply ab_in_ghb; auto.\n\n\n    subst; apply lockc_in_ghb with l; auto.\n\n  apply trc_ind with z.\n    apply tclock_in_ghb; auto.\n    apply (IHHtc_xz2 Hor_zy).\n\n  apply trc_ind with z; auto.\nQed.\n\nLemma lockc_po : forall E X l,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  acyclic (rel_union (lockc E X l) (po_iico E)).\nProof.\nintros E X l Hwf Hv x Hx.\nrewrite union_triv in Hx.\ngeneralize (lockc_irrefl); intro Hlir.\ngeneralize (po_irrefl); intro Hpoir.\ngeneralize (lockc_po_irrefl); intro Hlpoir.\ngeneralize (lockc_trans); intro Hlt.\ngeneralize (po_trans); intro Hpot.\ngeneralize (union_cycle_implies_seq_cycle2 (Hpoir E Hwf) (Hlir E X l Hwf Hv) (Hlpoir E X l Hwf Hv) (Hlt E X l Hwf Hv)  (Hpot E Hwf) Hx);\nintros [y Hy].\ngeneralize (lockc_seq_po_ghb Hwf Hv Hy); intro Hc.\ndestruct_valid Hv; unfold acyclic in Hvalid; unfold not in Hvalid; apply (Hvalid y Hc).\nQed.\n\nLemma lock_pop : forall E X,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  acyclic (rel_union (lock E X) (po_iico E)).\nProof.\nintros E X Hwf Hv x Hx.\nrewrite union_triv in Hx.\ngeneralize (lock_irrefl); intro Hlir.\ngeneralize (po_irrefl); intro Hpoir.\ngeneralize (lock_po_irrefl); intro Hlpoir.\ngeneralize (po_trans); intro Hpot.\ngeneralize (union_cycle_implies_seq_cycle3 (Hpoir E Hwf) (Hlir E X Hwf Hv) (Hlpoir E X Hwf Hv) (Hpot E Hwf) Hx);\nintros [y Hy].\ngeneralize (lock_seq_po_ghb Hwf Hv Hy); intro Hc.\ndestruct_valid Hv; unfold acyclic in Hvalid; unfold not in Hvalid; apply (Hvalid y Hc).\nQed.\n\nLemma rf_irrefl :\n  forall E X,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  ~(exists x, rf X x x).\nProof.\nintros E X Hwf Hv [x Hx].\ndestruct_valid Hv.\ngeneralize (dom_rf_is_write E X x x Hrf_cands Hx); intros [l [v Hwx]].\ngeneralize (ran_rf_is_read E X x x Hrf_cands Hx); intros [l' [v' Hrx]].\nrewrite Hrx in Hwx; inversion Hwx.\nQed.\n\nLemma lockc_rf_irrefl :\n  forall E X l,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  ~(exists x, (rel_union (rf X) (lockc E X l)) x x).\nProof.\nintros E X l Hwf Hv [x Hx]; inversion Hx.\n  assert (exists x, rf X x x) as He.\n    exists x; auto.\n  apply (rf_irrefl Hwf Hv He); auto.\n  assert (exists x, lockc E X l x x) as He.\n    exists x; auto.\n  apply (lockc_irrefl Hwf Hv He).\nQed.\n\nLemma rf_trans :\n  forall E X, well_formed_event_structure E ->\n  valid_execution E X ->\n  trans (rf X).\nProof.\n  intros E X Hwf Hv x y z Hxy Hyz.\n  destruct_valid Hv.\n  generalize (dom_rf_is_write E X y z Hrf_cands Hyz); intros [l [v Hwy]].\n  generalize (ran_rf_is_read E X x y Hrf_cands Hxy); intros [l' [v' Hry]].\n  rewrite Hry in Hwy; inversion Hwy.\nQed.\n\nAxiom unic_css :\n  forall E l e,\n    forall cs1 cs2,\n    cs E l cs1 ->\n    cs E l cs2 ->\n    Evts cs1 e -> Evts cs2 e ->\n    cs1 = cs2.\n\nAxiom cs_wf : forall E l c, cs E l c ->\n  (forall X, ~(exists w, fr E X (Read c) w /\\ ws X w (Write c))).\n\nAxiom cs_fr : (*provable from uniproc equivs*)\n  forall E X l c, cs E l c -> fr E X (Read c) (Write c).\n\nAxiom diff_cs : forall E X l1 l2 c1 c2, cs E l1 c1 -> cs E l2 c2 ->\n  rf X (Write c1) (Read c2) -> c1 <> c2.\n\nAxiom cs_diff : forall E cs1 cs2, cs1 <> cs2 ->\n  (forall e1 e2, Evts cs1 e1 -> Evts cs2 e2 -> e1 <> e2) /\\\n  (forall l ws1 ws2, atom E (Read cs1) ws1 l -> atom E (Read cs2) ws2 l -> ws1 <> ws2).\n\nAxiom no_other_stores : forall E l w, write_to w l -> (exists crit, cs E l crit /\\ (Write crit) = w /\\ exists e, Evts crit e).\n\nSet Implicit Arguments.\nInductive nsteps (A:Set) (r:Rln A) : nat -> A -> A -> Prop :=\n (* | rtriv : forall x y, x = y -> nsteps r 0 x y *)\n  | rintro : forall x y, r x y -> ~(exists z, r x z /\\ r z y) -> nsteps r 1 x y\n  | rtrans : forall x y z n, r x y -> nsteps r n y z -> nsteps r (S n) x z.\n\nLemma n1_is_r : forall A r x y,\n  @nsteps A r 1 x y -> r x y.\nProof.\nintros A r x y H1.\ninversion H1; auto.\ninversion H2.\nQed.\n\nDefinition discrete (A:Set) (r:Rln A) := forall x y, r x y -> exists n, nsteps r n x y. (*has a meaning only if r irrefl*)\nDefinition decr (A:Set) (r:Rln A) := forall x y n, nsteps r (S n) x y -> exists z, nsteps r 1 x z /\\ nsteps r n z y.\n\nUnset Implicit Arguments.\nAxiom dis_ws : forall X, discrete (ws X).\nAxiom dec_ws : forall X, decr (ws X).\n\nDefinition pio_cs E := fun e1 => fun e2 => exists l, exists cr, cs E l cr /\\ e1 = Read cr /\\ e2 = Write cr /\\ (exists e, Evts cr e).\n\nAxiom dec_rfpio : forall E X, decr (rel_seq (rf X) (pio_cs E)).\n\nLemma nws_implies_write :\n  forall X n w1 w2,\n  nsteps (ws X) n w1 w2 ->\n  exists l, write_to w2 l.\nProof.\nintros X n.\ninduction n; intros w1 w2 H12.\n  inversion H12.\n  generalize (dec_ws X); intro Hd.\n  generalize (Hd w1 w2 n H12); intros [w [H1w Hw2]].\n  apply (IHn w w2 Hw2).\nQed.\n\nLemma nsteps_implies_nrfpio :\n  forall E X n,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  forall w1 w2,\n  nsteps (ws X) n w1 w2 ->\n  nsteps (rel_seq (rf X) (pio_cs E)) n w1 w2 (*\\/ exists w, ws X w w1*).\nProof.\nintros E X n Hwf Hv.\ninduction n.\n\n  intros w1 w2 H0.\n  inversion H0.\n\n  intros w1 w2 Hsn.\n  generalize (dec_ws X); intro Hde.\n  generalize (Hde w1 w2 n Hsn); intros [z [H1z Hz2]].\n\n  generalize (IHn z w2 Hz2); intro Htc (* Hor.\n    inversion Hor as [Htc | Hws]*).\n\n    assert (exists l, write_to z l) as Hwz.\n      apply nws_implies_write with X 1 w1; auto.\n    destruct Hwz as [l Hwz].\n    generalize (no_other_stores E Hwz); intros [cz [Hcz [Hwwz ?]]].\n    assert (In _ (reads E) (Read cz)) as Hercz.\n      destruct Hcz as [Hlcz ?]; destruct Hlcz as [Htk ?];\n        destruct Htk as [w [[Hez ?] ?]]; split; auto.\n    destruct_valid Hv; generalize (Hrf_init (Read cz) Hercz);\n    intros [wrcz [Horcz Hrfcz]].\n (*inversion Horcz as [Hecz | Hicz].*)\n    destruct (eqEv_dec w1 wrcz) as [Heq | Hneq].\n        (*left.*) apply rtrans with z; auto.\n        exists (Read cz); split.\n          subst; auto.\n          unfold pio_cs; exists l; exists cz; split; auto; split; auto.\n\n        assert (ws X w1 wrcz \\/ ws X wrcz w1) as Horw.\n          assert (In Event (writes_to_same_loc_l (events E) l) w1) as Hww1.\n            split.\n              inversion H1z.\n                apply dom_ws_in_events with X z; auto.\n                split; auto.\n                inversion H2.\n              inversion H1z.\n                assert (write_serialization_well_formed (events E) (ws X)) as Hwswf.\n                  split; auto.\n                generalize (dom_ws_is_write E X w1 z Hwswf H0); intros [l1 [v1 Hww1]].\n                assert (write_serialization_well_formed (events E) (ws X) /\\\n                             rfmaps_well_formed E (events E) (rf X)) as Hs.\n                  split; split; auto.\n                generalize (ws_implies_same_loc X w1 z Hs H0); intro Heql.\n                destruct Hwz as [? Hwz]; unfold loc in Heql; rewrite Hwz in Heql; rewrite Hww1 in Heql.\n                subst; exists v1; auto.\n                inversion H2.\n          assert (In Event (writes_to_same_loc_l (events E) l) wrcz) as Hwwrcz.\n            generalize (Hrf_cands wrcz (Read cz) Hrfcz); intros [? [? [lz [Hwzw ?]]]]; auto.\n            split; auto.\n  destruct Hcz as [HLz ?]; destruct HLz as [Htkz ?]; destruct Htkz as [xz (*[*)Hatz (*?]*)].\n(*  destruct Hatz as [? [? [Hlz ?]]]. *)\n    destruct Hatz as [? [? Hlz]].\n  destruct H2 as [[? ?] ?]; unfold loc in Hlz; rewrite H2 in Hlz; inversion Hlz; subst; auto.\n          apply ws_tot with E l; auto.\n        inversion Horw.\n          (*then wrcz in between w1 and z, contrad H1z*)\n          inversion H1z.\n            rewrite <- H4 in H1; rewrite <- H5 in H1;\n            rewrite <- H4 in H2; rewrite <- H5 in H2;\n            assert (exists z, ws X x z /\\ ws X z y) as Hc.\n              exists wrcz; split; auto.\n                rewrite H4; auto.\n                rewrite H5.\n                  assert (fr E X (Read cz) z) as Hfr.\n                    rewrite <- Hwwz.\n          apply cs_fr with l; auto.\n                  destruct Hfr as [? [? [w [Hrf Hws]]]].\n                  generalize (Hrf_uni (Read cz) w wrcz Hrf Hrfcz); intro Heq; rewrite <- Heq; auto.\n                  contradiction.\n                 inversion H3.\n          (*right; exists wrcz; auto.*)\n          assert (fr E X (Read cz) w1) as Hfr.\n            split.\n              apply ran_rf_in_events with X wrcz; auto.\n               split; auto.\n              split.\n                apply ran_ws_in_events with X wrcz; auto.\n                split; auto.\n                exists wrcz; split; auto.\n           generalize (cs_wf Hcz); intro HnoX; generalize (HnoX X); intro Hno.\n           assert (exists w : Event, fr E X (Read cz) w /\\ ws X w (Write cz)) as Hc.\n             exists w1; split; auto.\n           rewrite Hwwz; inversion H1z; auto.\n           inversion H3.\n           contradiction.\nQed.\n\nLemma wsrf_implies_rfpio :\n  forall E X l cr1 cr2,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  cs E l cr1 -> cs E l cr2 ->\n  (rel_seq (ws X) (rf X)) (Write cr1) (Read cr2) ->\n  (exists n, rel_seq (nsteps (rel_seq (rf X) (pio_cs E)) n) (rf X) (Write cr1) (Read cr2)) (*\\/\n    exists w, ws X w (Write cr1)*).\nProof.\nintros E X l cr1 cr2 Hwf Hv Hcs1 Hcs2 [wr2 [Hws12 Hrf2]].\ngeneralize (dis_ws X); intro Hd.\ngeneralize (Hd (Write cr1) wr2 Hws12); intros [n Hn].\ngeneralize (nsteps_implies_nrfpio E X n Hwf Hv (Write cr1) wr2 Hn); intro Htc (*Hor.\ninversion Hor as [Htc | Hws]*).\n (* left;*) exists n; exists wr2; split; auto.\n (* right; auto. *)\nQed.\n\nLemma nrfpio_implies_lock :\n  forall E X l n,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  forall cr1 cr2, cs E l cr1 -> cs E l cr2 ->\n  nsteps (rel_seq (rf X) (pio_cs E)) n (Write cr1) (Write cr2) ->\n  forall e1 e2, Evts cr1 e1 -> Evts cr2 e2 -> lockc' E X l e1 e2.\nProof.\nintros E X l n Hwf Hv.\ninduction n; intros cr1 cr2 Hcs1 Hcs2 H12 e1 e2 He1 He2.\n  inversion H12.\n    generalize (dec_rfpio E X); intro Hde.\n    generalize (Hde (Write cr1) (Write cr2) n H12); intros [z [H1z Hz2]].\n        generalize (n1_is_r H1z); intros [r [Hrf [lz [cz [Hcsz [Hrcz [Hwcz [e He]]]]]]]].\n       assert (l = lz) as Heql.\n        assert (l = loc (Write cr1)) as Hl.\n          destruct Hcs1 as [? [? HUL1]]; destruct HUL1 as [Hfr1 ?].\n          destruct Hfr1 as [Hfr1 ?]; destruct Hfr1 as [? [? (*[*)Hl1 (*?]*)]].\n          rewrite Hl1; auto.\n        assert (lz = loc r) as Hlz.\n          destruct Hcsz as [HLz ?]; destruct HLz as [Htkz ?]; destruct Htkz as [xz (*[*)Hatz (*?]*)];\n          destruct Hatz as [? [? [Hlz ?]]]. rewrite Hrcz; rewrite Hlz; auto.\n\n        rewrite Hl; rewrite Hlz.\n        apply rf_implies_same_loc2 with E X; auto.\n          split; split; destruct_valid Hv; auto.\n    apply Trans with e.\n\n      apply RF; unfold css_lift; exists cr1; exists cz; split; [unfold css| split; auto].\n      split; auto. split; auto. split; auto.\n        subst; auto.\n        apply diff_cs with E X l lz; auto.\n        rewrite <- Hrcz; auto.\n        subst; auto.\n\n      rewrite <- Heql in Hcsz; rewrite Hwcz in Hz2; apply (IHn cz cr2 Hcsz Hcs2 Hz2 e e2 He He2).\nQed.\n\nLemma nrfpio_rf_implies_lock :\n  forall E X l cr1 cr2 n,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  cs E l cr1 -> cs E l cr2 ->\n  rel_seq (nsteps (rel_seq (rf X) (pio_cs E)) n) (rf X) (Write cr1) (Read cr2) ->\n  forall e1 e2, Evts cr1 e1 -> Evts cr2 e2 -> lockc E X l e1 e2.\nProof.\nintros E X l cr1 cr2 n Hwf Hv Hcs1 Hcs2 H12 e1 e2 He1 He2.\ndestruct H12 as [wr2 [Htc Hrf]].\nassert (write_to wr2 l) as Hwwr2.\n  destruct_valid Hv; generalize (Hrf_cands wr2 (Read cr2) Hrf); intros [? [? [l2 [Hwr2 ?]]]].\n  destruct Hcs2 as [HL2 ?]; destruct HL2 as [Htk2 ?]; destruct Htk2 as [x2 (*[*)Hat2 (*?]*)]; destruct Hat2 as [? [? [Hl2 ?]]].\n  destruct H1 as [[? ?] ?]; unfold loc in Hl2; rewrite H1 in Hl2; inversion Hl2; subst; auto.\n  generalize (no_other_stores E Hwwr2); intros [c [Hcs [Hec [e He]]]].\n\nunfold lockc; apply Trans with e.\n\n  apply nrfpio_implies_lock with n cr1 c; subst; auto.\n\n  apply RF; unfold css_lift; exists c; exists cr2; split; [unfold css|split]; auto.\n  split; auto. split; auto. split; auto.\n  apply diff_cs with E X l l; auto.\n    rewrite Hec; auto.\n  rewrite Hec; auto.\nQed.\n\nLemma mws_rf_implies_lock :\n  forall E X l crit,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  cs E l crit ->\n  rel_seq (ws X) (rf X) (inite l) (Read crit) ->\n  (forall e, (Evts crit) e -> lockc E X l (inite l) e).\nProof.\nintros E X l crit Hwf Hv Hcs Hmwsrf (*[w [Hmws Hrf]]*) e He.\n    generalize (init_store l); intro Hiw.\n    generalize (no_other_stores E Hiw); intros [ci [Hcsi [Hecsi ?]]].\n    rewrite <- Hecsi in Hmwsrf.\ngeneralize (wsrf_implies_rfpio E X l ci crit Hwf Hv Hcsi Hcs Hmwsrf); intro (*Hor.\ninversion Hor as [Htc | Hws].*) Htc.\ndestruct Htc as [n Htc]; apply nrfpio_rf_implies_lock with ci crit n; auto.\nassert (cs E l ci /\\ Write ci = inite l) as Hand.\n  split; auto.\napply (init_cs Hand).\n\n (* rewrite Hecsi in Hws; generalize (init_ws X l); intro Hc; contradiction.*)\nQed.\n\nLemma init_rf_implies_lock :\n  forall E X l crit,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  cs E l crit ->\n  (rf X) (inite l) (Read crit) ->\n  (forall e, (Evts crit) e -> lockc E X l (inite l) e).\nProof.\nintros E X l cr Hwf Hv Hcs Hrf e He.\ngeneralize (init_store l); intro Hwi.\ngeneralize (no_other_stores E Hwi); intros [ci [Hcsi [Hwcsi ?]]].\nassert (cs E l ci /\\ Write ci = inite l) as Hand.\n  split; auto.\ngeneralize (init_cs Hand); intro Hei.\nunfold lockc; apply RF; unfold css_lift.\n  exists ci; exists cr; split; [unfold css| split; auto].\n    split; auto. split; auto. split; auto.\n  apply diff_cs with E X l l; auto.\n  rewrite Hwcsi; auto.\n  rewrite Hwcsi; auto.\nQed.\n\nLemma css_init : forall E X l,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  forall crit, cs E l crit ->\n  (forall e, (Evts crit) e -> lockc E X l (inite l) e).\nProof.\nintros E X l Hwf Hv crit Hcs e He.\ngeneralize Hv; intro Hva.\n    assert (In _ (reads E) (Read crit)) as Hercrit.\n      destruct Hcs as [Hlcs ?]; destruct Hlcs as [Htk ?];\n        destruct Htk as [w [[Hev ?] ?]]; split; auto.\ndestruct_valid Hv;\ngeneralize (Hrf_init (Read crit) Hercrit); intros [w [Horc Hrfw]].\n  destruct (eqEv_dec (inite l) w) as [Heq | Hneq].\n    subst.\n      apply init_rf_implies_lock with crit; auto.\n\n  assert (rel_seq (ws X) (rf X) (inite l) (Read crit)) as Hir.\n    exists w; split; auto.\n\n    generalize (Hws_tot l); intro Hlin; destruct_lin Hlin.\n    assert (In Event (writes_to_same_loc_l (events E) l) (inite l)) as Hinit.\n      split; [apply (init_evt E l) | apply (init_store l)].\n    assert (In Event (writes_to_same_loc_l (events E) l) w) as Hw.\n      split; auto.\n      (*apply dom_rf_in_events with X (Read crit); auto.\n        split; auto.*)\n      apply rf_implies_same_loc with E X (Read crit); auto.\n        destruct Hcs as [HL ?]. destruct HL as [Htk ?]. destruct Htk as [wr (*[*)Hat (*?]*)].\n        destruct_atom Hat.\n        destruct Hr as [Her [lr [vr Hrr]]].\n        exists vr; unfold loc in Hlr; rewrite Hrr in Hlr; inversion Hlr as [Heq]; rewrite <- Heq; auto.\n    generalize (Htot (inite l) w Hneq Hinit Hw); intro Hor; inversion Hor as [Hiw | Hwi].\n    destruct Hiw; auto.\n    destruct Hwi; generalize (init_ws X l); intro Hn.\n    assert (exists e, ws X e (inite l)) as Hc.\n      exists w; auto.\n    contradiction.\n    apply mws_rf_implies_lock with crit; auto.\nQed.\n\nLemma rf_contrad :\n  forall E X l,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  forall w cs2 cs3,\n  rf X w (Read cs2) -> rf X w (Read cs3) -> cs2 <> cs3 ->\n  ~(cs E l cs2 /\\ cs E l cs3).\nProof.\nintros E X l Hwf Hv w cs2 cs3 Hrf2 Hrf3 Hd [Hcs2 Hcs3].\ngeneralize Hcs2; intro Hcs2'; generalize Hcs3; intro Hcs3'.\ndestruct Hcs2 as [[Htk2 ?] ?]; destruct Hcs3 as [[Htk3 ?] ?].\n  destruct Htk2 as [ws2 (*[*)Hrmw2 (*?]*)]; destruct Htk3 as [ws3 (*[*)Hrmw3 (*?]*)].\n      generalize Hrmw2; intro Hrmw2b; generalize Hrmw3; intro Hrmw3b.\n      destruct Hrmw2 as [Hr2 [Hatr2 [Hlr2 [Hw2 [Haw2 [Hlw2 [Hporw2 [Hnoc2 Hno2]]]]]]]];\n      destruct Hrmw3 as [Hr3 [Hatr3 [Hlr3 [Hw3 [Haw3 [Hlw3 [Hporw3 [Hnoc3 Hno3]]]]]]]].\n        assert (ws X w ws2) as Hws_wws2.\n\n          destruct (eqEv_dec w ws2) as [Heq | Hneq].\n\n          assert (tc (rel_union (com E X) (pio_llh E)) w w) as Hcy.\n            apply trc_ind with (Read cs2); apply trc_step.\n            left; left; left; auto.\n            right; split; auto; subst; auto.\n            (*  rewrite Hlr2; rewrite Hlw2; auto. *)\n            split; auto.\n              intros [? [? [? [? Hrws2]]]]; destruct Hw2 as [? [? [? Hw2]]];\n              rewrite Hrws2 in Hw2; inversion Hw2.\n          destruct_valid Hv; unfold not in Hsp; unfold acyclic in Hsp;\n            generalize (Hsp w Hcy); intro Ht; inversion Ht.\n\n          assert (In _ (writes_to_same_loc_l (events E) l) w) as Hww.\n            split.\n              apply dom_rf_in_events with X (Read cs2); auto.\n              split; destruct_valid Hv; auto.\n              assert (read_from (Read cs2) l) as Hrcs2.\n                destruct Hr2 as [? [l2 [v2 Har2]]]; exists v2.\n                unfold loc in Hlr2; rewrite Har2 in Hlr2; inversion Hlr2 as [Heq]; rewrite <- Heq; auto.\n              apply (rf_implies_same_loc w Hv Hrf2 Hrcs2); auto.\n             (*   destruct_valid Hv;\n                generalize (ran_rf_is_read E X w (Read cs2) Hrf_cands Hrf2);\n                intros [l2 [v2 Har2]]; exists v2.\n                unfold loc in Hlr2; rewrite Har2 in Hlr2; inversion Hlr2 as [Heq].\n                rewrite <- Heq; auto. *)\n          assert (In _ (writes_to_same_loc_l (events E) l) ws2) as Hww2.\n            split; destruct Hw2 as [Hews2 [lws2 [vws2 Haws2]]]; auto; exists vws2.\n                unfold loc in Hlw2; rewrite Haws2 in Hlw2; inversion Hlw2 as [Heq].\n                rewrite <- Heq; auto.\n         assert (In _ (writes_to_same_loc_l (events E) l) w /\\\n                     In _ (writes_to_same_loc_l (events E) l) ws2) as Hand.\n           split; auto.\n          destruct_valid Hv; generalize (ws_tot E X (Hws_tot l) Hand Hneq); intro Hor.\n          inversion Hor; auto.\n          assert (tc (rel_union (com E X) (pio_llh E)) w w) as Hcy.\n            apply trc_ind with (Read cs2). apply trc_step;\n            left; left; left; auto.\n            apply trc_ind with ws2; apply trc_step.\n            right; split; auto; subst; auto.\n            split; auto.\n              intros [? [? [? [? Hrws2]]]]; destruct Hw2 as [? [? [? Hw2]]];\n              rewrite Hrws2 in Hw2; inversion Hw2.\n            left; right; auto.\n          unfold not in Hsp; unfold acyclic in Hsp;\n            generalize (Hsp w Hcy); intro Ht; inversion Ht.\n\n        assert (fr E X (Read cs3) ws2) as Hfr_r3ws2.\n          split. destruct Hr3; auto.\n            split; destruct Hw2; auto.\n              exists w; split; auto.\n        assert (ws X w ws3) as Hws_wws3.\n\n          destruct (eqEv_dec w ws3) as [Heq | Hneq].\n\n          assert (tc (rel_union (com E X) (pio_llh E)) w w) as Hcy.\n            apply trc_ind with (Read cs3); apply trc_step.\n            left; left; left; auto.\n            right; split; auto; subst; auto.\n              rewrite Hlr3; rewrite Hlw3; auto.\n            split; auto.\n              intros [? [? [? [? Hrws3]]]]; destruct Hw3 as [? [? [? Hw3]]];\n              rewrite Hrws3 in Hw3; inversion Hw3.\n          destruct_valid Hv; unfold not in Hsp; unfold acyclic in Hsp;\n            generalize (Hsp w Hcy); intro Ht; inversion Ht.\n\n          assert (In _ (writes_to_same_loc_l (events E) l) w) as Hww.\n            split.\n              apply dom_rf_in_events with X (Read cs2); auto.\n              split; destruct_valid Hv; auto.\n              assert (read_from (Read cs2) l) as Hrcs2.\n                destruct Hr2 as [? [l2 [v2 Har2]]]; exists v2.\n                unfold loc in Hlr2; rewrite Har2 in Hlr2; inversion Hlr2 as [Heq]; rewrite <- Heq; auto.\n              apply (rf_implies_same_loc w Hv Hrf2 Hrcs2); auto.\n              (*  destruct_valid Hv;\n                generalize (ran_rf_is_read E X w (Read cs2) Hrf_cands Hrf2);\n                intros [l2 [v2 Har2]]; exists v2.\n                unfold loc in Hlr2; rewrite Har2 in Hlr2; inversion Hlr2 as [Heq].\n                rewrite <- Heq; auto. *)\n          assert (In _ (writes_to_same_loc_l (events E) l) ws3) as Hww3.\n            split; destruct Hw3 as [Hews3 [lws3 [vws3 Haws3]]]; auto; exists vws3.\n                unfold loc in Hlw3; rewrite Haws3 in Hlw3; inversion Hlw3 as [Heq].\n                rewrite <- Heq; auto.\n         assert (In _ (writes_to_same_loc_l (events E) l) w /\\\n                     In _ (writes_to_same_loc_l (events E) l) ws3) as Hand.\n           split; auto.\n          destruct_valid Hv; generalize (ws_tot E X (Hws_tot l) Hand Hneq); intro Hor.\n          inversion Hor; auto.\n          assert (tc (rel_union (com E X) (pio_llh E)) w w) as Hcy.\n            apply trc_ind with (Read cs3). apply trc_step;\n            left; left; left; auto.\n            apply trc_ind with ws3; apply trc_step.\n            right; split; auto; subst; auto.\n              rewrite Hlr3; rewrite Hlw3; auto.\n            split; auto.\n              intros [? [? [? [? Hrws3]]]]; destruct Hw3 as [? [? [? Hw3]]];\n              rewrite Hrws3 in Hw3; inversion Hw3.\n            left; right; auto.\n          unfold not in Hsp; unfold acyclic in Hsp;\n            generalize (Hsp w Hcy); intro Ht; inversion Ht.\n\n        assert (fr E X (Read cs2) ws3) as Hfr_r2ws3.\n          split. destruct Hr2; auto.\n            split; destruct Hw3; auto.\n              exists w; split; auto.\n\n        assert (ws X ws2 ws3 \\/ ws X ws3 ws2) as Hor_ws.\n          assert (ws2 <> ws3) as Hneq.\n            generalize (cs_diff E Hd); intros [? Hws].\n              apply (Hws l ws2 ws3); auto.\n\n          assert (In _ (writes_to_same_loc_l (events E) l) ws2) as Hww2.\n            split; destruct Hw2 as [Hews2 [lws2 [vws2 Haws2]]]; auto; exists vws2.\n                unfold loc in Hlw2; rewrite Haws2 in Hlw2; inversion Hlw2 as [Heq].\n                rewrite <- Heq; auto.\n          assert (In _ (writes_to_same_loc_l (events E) l) ws3) as Hww3.\n            split; destruct Hw3 as [Hews3 [lws3 [vws3 Haws3]]]; auto; exists vws3.\n                unfold loc in Hlw3; rewrite Haws3 in Hlw3; inversion Hlw3 as [Heq].\n                rewrite <- Heq; auto.\n         assert (In _ (writes_to_same_loc_l (events E) l) ws2 /\\\n                     In _ (writes_to_same_loc_l (events E) l) ws3) as Hand.\n           split; auto.\n          destruct_valid Hv; apply (ws_tot E X (Hws_tot l) Hand Hneq).\n\n        inversion Hor_ws as [H23 | H32].\n\n          destruct (eqProc_dec (proc_of ws2) (proc_of (Read cs3))) as [Heqp23 | Hdiffp23].\n\n      assert (exists e : Event, stars E e /\\ po_iico E (Read cs3) e /\\ po_iico E e ws3) as Hco.\n        exists ws2; split; auto.\n          split.\n           assert (In _ (events E) ws2) as Hews2.\n             destruct Hw2; auto.\n           assert (In _ (events E) (Read cs3)) as Her3.\n             destruct Hr3; auto.\n           generalize (same_proc_implies_po ws2 (Read cs3) Hwf Heqp23 Hews2 Her3); intro Hor.\n           inversion Hor; auto.\n           assert (tc (rel_union (com E X) (pio_llh E)) (Read cs3) (Read cs3)) as Hcy.\n             apply trc_ind with ws2; apply trc_step.\n               left; left; right; auto.\n               right; split; auto.\n               apply sym_eq; apply fr_implies_same_loc with E X; auto.\n                 destruct_valid Hv; split; split; auto.\n               split; auto.\n              intros [[? [? [? Hrws2]]] ?]; destruct Hw2 as [? [? [? Hw2]]];\n              rewrite Hrws2 in Hw2; inversion Hw2.\n               destruct_valid Hv; unfold not in Hsp; unfold acyclic in Hsp;\n               generalize (Hsp (Read cs3) Hcy); intro Ht; inversion Ht.\n         assert (proc_of ws2 = proc_of ws3) as Heqp.\n           rewrite Heqp23.\n           apply po_implies_same_proc with E; auto.\n           apply po_iico_domain_in_events with ws3; auto.\n           apply po_iico_range_in_events with (Read cs3); auto.\n           assert (In _ (events E) ws2) as Hews2.\n             destruct Hw2; auto.\n           assert (In _ (events E) ws3) as Hews3.\n             destruct Hw3; auto.\n           generalize (same_proc_implies_po ws2 ws3 Hwf Heqp Hews2 Hews3); intro Hor.\n           inversion Hor; auto.\n           assert (tc (rel_union (com E X) (pio_llh E)) ws3 ws3) as Hcy.\n             apply trc_ind with ws2; apply trc_step.\n               right; split; auto.\n               apply sym_eq;\n               apply ws_implies_same_loc with E X; auto.\n                 destruct_valid Hv; split; split; auto.\n               split; auto.\n              intros [[? [? [? Hrws3]]] ?]; destruct Hw3 as [? [? [? Hw3]]];\n              rewrite Hrws3 in Hw3; inversion Hw3.\n               left; right; auto.\n\n               destruct_valid Hv; unfold not in Hsp; unfold acyclic in Hsp;\n               generalize (Hsp ws3 Hcy); intro Ht; inversion Ht.\n      contradiction.\n\n            assert (exists w' : Event,\n          proc_of w' <> proc_of (Read cs3) /\\\n          writes E w' /\\ loc w' = (*Some*) l /\\ fr E X (Read cs3) w' /\\ ws X w' ws3) as Hc.\n            exists ws2; split; auto.\n            generalize (Hno3 X); intro Hco; contradiction.\n\n          destruct (eqProc_dec (proc_of ws3) (proc_of (Read cs2))) as [Heqp23 | Hdiffp23].\n\n            assert (exists e : Event, stars E e /\\ po_iico E (Read cs2) e /\\ po_iico E e ws2) as Hc.\n              exists ws3; split; auto.\n          split.\n           assert (In _ (events E) ws3) as Hews3.\n             destruct Hw3; auto.\n           assert (In _ (events E) (Read cs2)) as Her2.\n             destruct Hr2; auto.\n           generalize (same_proc_implies_po ws3 (Read cs2) Hwf Heqp23 Hews3 Her2); intro Hor.\n           inversion Hor; auto.\n           assert (tc (rel_union (com E X) (pio_llh E)) (Read cs2) (Read cs2)) as Hcy.\n             apply trc_ind with ws3; apply trc_step.\n               left; left; right; auto.\n               right; split; auto.\n               apply sym_eq; apply fr_implies_same_loc with E X; auto.\n                 destruct_valid Hv; split; split; auto.\n               split; auto.\n              intros [[? [? [? Hrws3]]] ?]; destruct Hw3 as [? [? [? Hw3]]];\n              rewrite Hrws3 in Hw3; inversion Hw3.\n               destruct_valid Hv; unfold not in Hsp; unfold acyclic in Hsp;\n               generalize (Hsp (Read cs2) Hcy); intro Ht; inversion Ht.\n         assert (proc_of ws3 = proc_of ws2) as Heqp.\n           rewrite Heqp23.\n           apply po_implies_same_proc with E; auto.\n           apply po_iico_domain_in_events with ws2; auto.\n           apply po_iico_range_in_events with (Read cs2); auto.\n           assert (In _ (events E) ws3) as Hews3.\n             destruct Hw3; auto.\n           assert (In _ (events E) ws2) as Hews2.\n             destruct Hw2; auto.\n           generalize (same_proc_implies_po ws3 ws2 Hwf Heqp Hews3 Hews2); intro Hor.\n           inversion Hor; auto.\n           assert (tc (rel_union (com E X) (pio_llh E)) ws2 ws2) as Hcy.\n             apply trc_ind with ws3; apply trc_step.\n               right; split; auto.\n               apply sym_eq;\n               apply ws_implies_same_loc with E X; auto.\n                 destruct_valid Hv; split; split; auto.\n               split; auto.\n              intros [[? [? [? Hrws2]]] ?]; destruct Hw2 as [? [? [? Hw2]]];\n              rewrite Hrws2 in Hw2; inversion Hw2.\n               left; right; auto.\n\n               destruct_valid Hv; unfold not in Hsp; unfold acyclic in Hsp;\n               generalize (Hsp ws2 Hcy); intro Ht; inversion Ht.\n\n            contradiction.\n\n            assert (exists w' : Event,\n          proc_of w' <> proc_of (Read cs2) /\\\n          writes E w' /\\ loc w' = (*Some*) l /\\ fr E X (Read cs2) w' /\\ ws X w' ws2) as Hc.\n            exists ws3; split; auto.\n          generalize (Hno2 X); intro Hco; contradiction.\nQed.\n\nLemma rf_contrad_or :\n  forall E X l,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  forall w cs2 cs3,\n  rf X w (Read cs2) -> rf X w (Read cs3) ->\n  ~(cs E l cs2 /\\ cs E l cs3) \\/ cs2 = cs3.\nProof.\nintros E X l Hwf Hv w cs2 cs3 Hrf2 Hrf3.\n  generalize (classic (cs2 = cs3)); intro Hor; inversion Hor; auto.\n  left; apply rf_contrad with X w; auto.\nQed.\n\nLemma same_cs_lock :\n    forall E X l, forall x y z crit,\n    well_formed_event_structure E ->\n    valid_execution E X ->\n    cs E l crit ->\n    Evts crit x -> Evts crit y ->\n    lockc E X l x z ->\n    lockc E X l y z.\nProof.\nintros E X l x y z crit Hwf Hv Hcrit Hx Hy Hxz.\ninduction Hxz.\n  destruct_csslift H.\n  generalize Hcss; intro Hcssb;\n  destruct_css Hcss.\n  generalize (unic_css e1 Hcrit Hcs1 Hx Hev1); intro Heq; subst.\n    unfold lockc; apply RF; unfold css_lift.\n      exists s1; exists s2; split; auto.\n  unfold lockc; apply Trans with e; auto.\n    apply (IHHxz1 Hx).\nQed.\n\nLemma lockc_step_contrad :\n  forall E X,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  forall l z x cs1 cs2,\n    css E X l cs1 cs2 ->\n    Evts cs1 z -> Evts cs2 x ->\n   forall y, (lockc E X l z y) ->\n   (lockc E X l x y) \\/ (x = y) \\/ Evts cs2 y.\nProof.\nintros E X Hwf Hv l z x cs1 cs2 Hcsszx Hez Hex y Hzy.\ninduction Hzy as [z y Hszy |].\n    destruct_css Hcsszx.\n    destruct_csslift Hszy.\ngeneralize (classic (x = y)); intro Hore.\ninversion Hore; auto.\ngeneralize (classic (cs2 = s2)); intro Horcs.\ninversion Horcs.\n  subst; auto.\n  destruct Hcss as [[Hcs1' [Hcs2' Hdcs']] Hrf'].\n  generalize (unic_css z Hcs1 Hcs1' Hez Hev1); intro Heq; subst.\n  generalize (rf_contrad_or E X l Hwf Hv (Write s1) cs2 s2 Hrf Hrf'); intro Hor.\n  inversion Hor.\n    assert (cs E l cs2 /\\ cs E l s2) as Hc.\n      split; auto. contradiction.\n   subst; auto.\n\n  generalize (IHHzy1 Hez); intro Hor.\n  inversion Hor.\n  left; unfold lockc in * |- *;apply Trans with e; auto; apply IHlockc1; auto.\n  inversion H.\n    subst; auto.\n  left; apply same_cs_lock with e cs2; auto.\n    destruct_css Hcsszx; auto.\nQed.\n\nLemma same_source_implies_ordered :\n  forall E X l, forall x y z,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  (lockc E X) l z x /\\ (lockc E X) l z y ->\n  (lockc E X) l x y \\/ (lockc E X) l y x \\/  x = y \\/ (exists crit, cs E l crit /\\ Evts crit x /\\ Evts crit y).\nProof.\nintros E X l x y z Hwf Hv [Hzx Hzy].\ninduction Hzx.\n  destruct_csslift H.\n  generalize (lockc_step_contrad E X Hwf Hv l e1 e2 s1 s2 Hcss Hev1 Hev2 y Hzy); intro Hor.\n  inversion Hor.\n    left; auto.\n    inversion H.\n    right; right; auto.\n    right; right; right.\n    exists s2; split; auto.\n    destruct_css Hcss; auto.\n\n  generalize (IHHzx1 Hzy); intro Hor.\n  inversion Hor as [Hley | Hulye].\n  apply IHHzx2; auto.\n\n  inversion Hulye as [Hlye | Hueq].\n  right; left; unfold lockc in * |- *;apply Trans with e; auto.\n\n  inversion Hueq.\n    subst; auto.\n  destruct H as [crit [Hcscrit [Hecrit Hycrit]]].\n  right; left; apply same_cs_lock with e crit; auto.\nQed.\n\nLemma lockc_tot : forall E X l,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  forall e1 e2, (events E e1 /\\ events E e2) /\\\n  (exists cs1, exists cs2, (cs E l) cs1 /\\ cs E l cs2 /\\\n    cs1 <> cs2 /\\ (Evts cs1) e1 /\\ (Evts cs2) e2) -> (lockc E X l) e1 e2 \\/ (lockc E X l) e2 e1.\nProof.\nintros E X l Hwf Hv e1 e2 [[He1 He2] [cs1 [cs2 [Hcs1 [Hcs2 [Hdiff [Hee1 Hee2]]]]]]].\ngeneralize (css_init E X l Hwf Hv cs1 Hcs1 e1 Hee1); intro Hl1.\ngeneralize (css_init E X l Hwf Hv cs2 Hcs2 e2 Hee2); intro Hl2.\n(*generalize (init_css E X l); intros [cri [ei [Heei Hncr]]].*)\nassert (lockc E X l (inite l) e1 /\\ lockc E X l (inite l) e2) as Hand.\n (* assert (lockc E X l ei e1 /\\ lockc E X l ei e2) as Hand. *)\n  split; auto.\ngeneralize (same_source_implies_ordered E X l e1 e2 (inite l) Hwf Hv Hand); intro Htor.\ninversion Htor.\n  left; auto.\n  inversion H.\n  right; auto.\n  inversion H0.\n  generalize (cs_diff E Hdiff); intros [Hed ?].\n    generalize (Hed e1 e2 Hee1 Hee2); intro Hc.\n    contradiction.\n  destruct H1 as [crit [Hcrit [Hcrit1 Hcrit2]]].\n    generalize (unic_css e1 Hcs1 Hcrit Hee1 Hcrit1); intro Heq.\n    generalize (unic_css e2 Hcs2 Hcrit Hee2 Hcrit2); intro Heq2.\n    rewrite <- Heq2 in Heq; contradiction.\nQed.\n\nLemma s_tot_l :\nforall E X,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  forall e1 e2, (events E e1 /\\ events E e2) /\\ s E X e1 e2->\n  (exists l, (lockc E X l) e1 e2 \\/ (lockc E X l) e2 e1).\nProof.\nintros E X Hwf Hv e1 e2 [[He1 He2] Hs].\ndestruct Hs as [l [s1 [s2 [Hsc [Hes1 Hes2]]]]].\nexists l; apply lockc_tot; auto; split; auto.\nexists s1; exists s2; destruct Hsc as [Hcs1 [Hcs2 Hdcs]];\nsplit; auto; split; auto.\nQed.\n\nLemma s_tot :\nforall E X,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  forall e1 e2, (events E e1 /\\ events E e2) /\\ s E X e1 e2->\n  ((lock E X) e1 e2 \\/ (lock E X) e2 e1).\nProof.\nintros E X Hwf Hv e1 e2 Hand;\ngeneralize (s_tot_l E X Hwf Hv e1 e2 Hand); intros [l Hor];\ninversion Hor; [left | right]; exists l; auto.\nQed.\n\nHypothesis ac_s_lock :\n  forall E X, acyclic (rel_union (s E X) (lock E X)).\n\nLemma s_lock :\n  forall E X,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  rel_incl (s E X) (lock E X).\nProof.\nintros E X Hwf Hv x y Hxy.\nassert ((events E x /\\ events E y) /\\ s E X x y) as Hand.\n  split; [split|]; auto; destruct Hxy as [l [s1 [s2 [Hs12 [Hex Hey]]]]];\n  destruct Hs12 as [Hcs1 [Hcs2 ?]].\n    destruct Hcs1 as [? [Hev ?]].\n    generalize (Hev x); intro Heq; destruct Heq as [Hd Hb].\n    generalize (Hd Hex); intros [Hpo1 Hpo2];\n    change (events E x) with (In _ (events E) x);\n    apply po_iico_domain_in_events with (Eb s1); auto.\n    destruct Hcs2 as [? [Hev ?]].\n    generalize (Hev y); intro Heq; destruct Heq as [Hd Hb].\n    generalize (Hd Hey); intros [Hpo1 Hpo2];\n    change (events E y) with (In _ (events E) y);\n    apply po_iico_domain_in_events with (Eb s2); auto.\ngeneralize (s_tot E X Hwf Hv x y Hand); intro Hor; inversion Hor; auto.\ngeneralize (ac_s_lock E X); intro Hac; assert False as Ht.\n  unfold acyclic in Hac; assert (tc (rel_union (s E X) (lock E X)) x x) as Hin.\n    apply trc_ind with y; apply trc_step; [left | right]; auto.\n  apply (Hac x Hin).\ninversion Ht.\nQed.\n\nLemma s_po_ac :\n  forall E X,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  acyclic (rel_union (s E X) (po_iico E)).\nProof.\nintros E X Hwf Hv;\napply incl_ac with (rel_union (lock E X) (po_iico E)).\nintros x y Hxy; inversion Hxy; [left | right]; auto.\napply s_lock; auto.\napply lock_pop; auto.\nQed.\n\nLemma happens_before_irr :\n  forall E X x,\n  well_formed_event_structure E ->\n  valid_execution E X ->\n  ~(happens_before E X x x).\nProof.\nintros E X x Hwf Hv Hx.\n(*generalize (lock_pop Hwf Hv); intro Hac;*)\ngeneralize (s_po_ac E X Hwf Hv); intro Hac;\n  unfold happens_before in Hx; rewrite union_triv in Hx;\n  apply (Hac x Hx).\nQed.\n\nDefinition covered E X r :=\n  forall e1 e2, (competing E X e1 e2) -> (r E X e1 e2 \\/ r E X e2 e1).\n\nDefinition covering s :=\n  forall E X, well_formed_event_structure E ->\n    AResWmm.valid_execution E X ->\n    covered E X s -> acyclic (AnWmm.ghb E X).\n\nEnd HB.\n\nModule DrfG := DrfGuarantee HB.\nModule AWmm := Wmm A dp.\n\nModule AResWmm := Wmm ARes dp.\nLemma locks_provide_drf_guarantee :\n  (forall E X, AnWmm.valid_execution E X -> DrfG.Drf.covered E X DrfG.Drf.s) ->\n  (forall E X, well_formed_event_structure E ->\n   (AResWmm.valid_execution E X <-> AnWmm.valid_execution E X)).\nProof.\napply DrfG.drf_guarantee.\nQed.\n\nEnd Locks.\n", "meta": {"author": "herd", "repo": "CoqCat", "sha": "e9afddbfe4cd17de335596454b8e9de0dd8ce5c2", "save_path": "github-repos/coq/herd-CoqCat", "path": "github-repos/coq/herd-CoqCat/CoqCat-e9afddbfe4cd17de335596454b8e9de0dd8ce5c2/locks.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.2213952210880445}}
{"text": "(* ***************************************************************** *)\n(* Validation.v                                                      *)\n(*                                                                   *)\n(* 2019 Xuan Huang                                                   *)\n(* ***************************************************************** *)\n\n\n(* ################################################################# *)\n(** * Validation *)\n\nFrom Wasm Require Export Structure.\nFrom Coq Require Export Structures.Equalities.\n\n(* Test imports/exports *)\n\nModule ImportExportTests.\n\n  Definition ex_fun_nu : functype := [] --> [T_i32].\n\nEnd ImportExportTests.\n\n\n(* ================================================================= *)\n(** ** Conventions *)\n(** http://webassembly.github.io/spec/core/valid/conventions.html *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Contexts *)\n(** http://webassembly.github.io/spec/core/valid/conventions.html#contexts *)\n\nRecord context :=\n  {\n    C_types : list functype;\n    C_funcs : list functype;\n    C_tables : list tabletype;\n    (* C_mems : list memtype; *)\n    (* C_globals : list globaltype; *)\n    C_locals : list valtype;\n    C_labels : list resulttype;\n    C_return : option resulttype;  \n  }.\n\nDefinition empty_context :=\n  {|\n    C_types := [];\n    C_funcs := [];\n    C_tables := [];\n    (* C_mems := []; *)\n    (* C_globals := []; *)\n    C_locals := [];\n    C_labels := [];\n    C_return := Some [];\n  |}.\n\n\n(** functional update - replacing fields *)\n\nDefinition replace_locals(C: context) (xs: list valtype) :=\n  {|\n    C_locals := xs;\n    C_types  := C.(C_types);\n    C_funcs  := C.(C_funcs);\n    C_tables := C.(C_tables);\n    C_labels := C.(C_labels);\n    C_return := C.(C_return);\n  |}.\nNotation \"C 'with_locals' = xs\" :=\n  (replace_locals C xs)\n  (at level 68, left associativity) : wasm_scope.\n\nDefinition replace_labels (C: context) (xs: list resulttype) :=\n  {|\n    C_labels := xs;\n    C_types := C.(C_types);\n    C_funcs := C.(C_funcs);\n    C_tables := C.(C_tables);\n    C_locals := C.(C_locals);\n    C_return := C.(C_return);\n  |}.\nNotation \"C 'with_labels' = x\" :=\n  (replace_labels C x)\n  (at level 68, left associativity) : wasm_scope.\n\nDefinition replace_return (C: context) (x: option resulttype) :=\n  {|\n    C_return:= x;\n    C_types := C.(C_types);\n    C_funcs := C.(C_funcs);\n    C_tables := C.(C_tables);\n    C_locals := C.(C_locals);\n    C_labels := C.(C_labels);\n  |}.\nNotation \"C 'with_return' = x\" :=\n  (replace_return C x)\n  (at level 68, left associativity) : wasm_scope.\n\n\n(** functional update - cons on fields *)\n\nDefinition cons_labels (C: context) (x: resulttype) :=\n  {|\n    C_labels := x :: C.(C_labels);\n    C_types := C.(C_types);\n    C_funcs := C.(C_funcs);\n    C_tables := C.(C_tables);\n    C_locals := C.(C_locals);\n    C_return := C.(C_return);\n  |}.\nNotation \"C ',labels' x\" :=\n  (cons_labels C x)\n  (at level 67, left associativity) : wasm_scope.\n\nDefinition cons_locals (C: context) (x: valtype) :=\n  {|\n    C_locals := x :: C.(C_locals);\n    C_types := C.(C_types);\n    C_funcs := C.(C_funcs);\n    C_tables := C.(C_tables);\n    C_labels := C.(C_labels);\n    C_return := C.(C_return);\n  |}.\nNotation \"C ',locals' x\" :=\n  (cons_locals C x)\n  (at level 67, left associativity) : wasm_scope.\n\n\n(** functional update - prepend on fields *)\n\nDefinition prepend_locals (C: context) (xs: list valtype) :=\n  {|\n    C_locals := xs ++ C.(C_locals);\n    C_types := C.(C_types);\n    C_funcs := C.(C_funcs);\n    C_tables := C.(C_tables);\n    C_labels := C.(C_labels);\n    C_return := C.(C_return);\n  |}.\nNotation \"C ',locals*' xs\" :=  \n  (prepend_locals C xs)\n  (at level 67, left associativity) : wasm_scope.\n\n\n(** Tests *)\n\nModule ContextTests.\n\n  (* nth is total and require default *)\n  Example ex1 : (nth 1 [1;2;3] 0) = 2. auto. Qed.\n  Example ex2 : (idx [1;2;3] 1) = Some 2. auto. Qed.\n\n  Example ex_C :=\n    {|\n      C_types := [];\n      C_funcs := [];\n      C_tables := [];\n      C_locals := [T_i32; T_i32];\n      C_labels := [];\n      C_return := None;\n    |}.\n\n  Example ex3 : (idx ex_C.(C_locals) 0) = Some T_i32. auto. Qed.\n  Example ex4 : (idx ex_C.(C_locals) 1) = Some T_i32. auto. Qed.\n  Example ex5 : (idx ex_C.(C_locals) 2) = None. auto. Qed.\n\n  (* Testing Updates Notation *)\n  Example ex_Crl := ex_C with_labels = [[T_i32]].\n  (* Compute ex_Crl. *)\n\n  Example ex_Crr := ex_C with_return = Some [T_i32].\n  (* Compute ex_Crr. *)\n\n  Example ex_Crlr := ex_C with_locals = [T_i32] with_return = Some [T_i32].\n  (* Compute ex_Crlr. *)\n\n  (* Testing if break pair *)\n  Example pair1 := (1,2).\n  Example pair2 := (1, 2).\n\n  (* Testing Field Cons Notation *)\n  Example ex_Cc0 := ex_C,locals* [T_i32]. \n  (* Compute ex_Cc0. *)\n\n  Example ex_Cc1 := ex_C,labels [T_i32]. \n  (* Compute ex_Cc1. *)\n\n  Example ex_Cc2 := ex_C,labels [T_f32],labels [T_i32]. \n  (* Compute ex_Cc2. *)\n\n  (* Testing associativity *)\n  Example ex_Ca1 := ex_C ,labels [T_f32] ,labels [T_i32] with_return = Some [T_i32].\n  (* Compute ex_Ca1. *)\n\n  (* Testing Indexing Notation *)\n  Example i1 : ([1;2;3].[1] ) = Some 2. auto. Qed.\n\n  Example i2 : (ex_C.(C_locals).[0]) = Some T_i32. auto. Qed.\n  Example i3 : (ex_C.(C_locals).[1]) = Some T_i32. auto. Qed.\n  Example i4 : (ex_C.(C_locals).[2]) = None. auto. Qed.\n\n  Example i5 : forallb (fun ty => eqb_valtype ty T_i32) ex_C.(C_locals) = true.\n  auto. Qed.\n\n  Example i6 : all_valtype ex_C.(C_locals) T_i32 = true.\n  auto. Qed.\n\n  Example all_i32 := Forall (fun ty => ty = T_i32) (C_locals ex_C).\n\n  Lemma ex_forall : all_i32.\n  Proof with eauto.\n    unfold all_i32.\n    simpl.\n    eapply Forall_cons...\n  Qed.\n\nEnd ContextTests.\n\n\n(**************************************************************)\n(** ** Implicit Types - subset of ExtendedTyping *)\n\n(* Primary *)\nImplicit Type b : bool.\n\n(* Value *)\nImplicit Type val : val.\nImplicit Type vals : list val.\n\n(* Structure *)\nImplicit Type M: module.\nImplicit Type l : labelidx.\n\nImplicit Type instr : instr.\nImplicit Type instrs : list instr.\nImplicit Type f func : func.\nImplicit Type fs funcs : list func.\nImplicit Type tab table: table.\nImplicit Type tabs tables: list table.\n\n(* Type *)\nImplicit Type t : valtype.\nImplicit Type ts : list valtype.\nImplicit Type rt : resulttype.\nImplicit Type bt : blocktype.\nImplicit Type ft functype: functype.\nImplicit Type fts functypes: list functype.\nImplicit Type tt tabletype: tabletype.\nImplicit Type tts tabletypes: list tabletype.\n\n(* Validation *)\nImplicit Type C : context.\n\n\n\n(* ================================================================= *)\n(** ** Types *)\n(** http://webassembly.github.io/spec/core/valid/types.html *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Limits *)\n\nReserved Notation \"'⊢l' l '∈' k\" (at level 70).\nInductive valid_limit : limits -> I32.t -> Prop :=\n\n  (* No max limits *)\n  (* should it be [I32. <=] or Coq [<=] ?\n     anyways we need axiomize this...\n     in the paper we simply use Coq [<=]\n   *)\n\n  | VL__none: forall n k,\n      I32.le_u n k = true ->\n      ⊢l {| L_min := n; L_max := None |} ∈ k \n\n  (* Has max limits *)\n       \n  | VL__some: forall n m k,\n      I32.le_u n k = true ->\n      I32.le_u m k = true ->\n      I32.le_u n m = true ->\n      ⊢l {| L_min := n; L_max := (Some m) |} ∈ k\n\nwhere \"'⊢l' l '∈' k \" := (valid_limit l k).\n\nHint Constructors valid_limit.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Block Types *)\n(** https://webassembly.github.io/multi-value/core/valid/types.html#block-types *)\n\n(** Block types may be expressed in one of two forms, both of which are converted to plain function types by the following rules. *)\n\nReserved Notation \"C '⊢bt' bt '∈' ft\" (at level 70).\nInductive valid_blocktype : context -> blocktype -> functype -> Prop :=\n\n  | VBT_typeidx: forall C i ft,\n      C.(C_types).[i] = Some ft ->\n      C ⊢bt BT_typeidx i ∈ ft\n\n  | VBT_valtype__some: forall C t,\n      C ⊢bt BT_valtype (Some t) ∈ [] --> [t]\n\n  | VBT_valtype__none: forall C, \n      C ⊢bt BT_valtype None ∈ [] --> []\n\nwhere \"C '⊢bt' bt '∈' ft\" := (valid_blocktype C bt ft).\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Function Types *)\n(** https://webassembly.github.io/multi-value/core/valid/types.html#function-types *)\n\n\nReserved Notation \"'⊢ft' ft 'ok'\" (at level 70).\nInductive valid_functype : functype -> Prop :=\n\n  | VFT: forall ts1 ts2,\n      ⊢ft ts1 --> ts2 ok\n\nwhere \"'⊢ft' ft 'ok' \" := (valid_functype ft).\nHint Constructors valid_functype.\n\n\n(* This is not explicitly defined but occured as\n\n     (⊢ functype ok)*\n\n*)\nReserved Notation \"'⊢ft*' fts 'ok'\" (at level 70).\nInductive valid_functypes : list functype -> Prop :=\n\n  | VFTS: forall fts,\n      Forall (fun ft => ⊢ft ft ok) fts ->\n      ⊢ft* fts ok\n\nwhere \"'⊢ft*' fts 'ok' \" := (valid_functypes fts).\nHint Constructors valid_functypes.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Table Types *)\n\nReserved Notation \"'⊢tt' tt 'ok'\" (at level 70).\nInductive valid_tabletype : tabletype -> Prop :=\n\n  | VTT: forall limits elemtype,\n      ⊢l limits ∈ I32.max ->      (* spec use literal [2^32] here *)\n      ⊢tt (limits, elemtype) ok\n\nwhere \"'⊢tt' tt 'ok' \" := (valid_tabletype tt).\nHint Constructors valid_tabletype.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Memory Types *)\n\nReserved Notation \"'⊢met' met 'ok'\" (at level 70).\nInductive valid_memtype : memtype -> Prop :=\n\n  | VMT: forall limits,\n      ⊢l limits ∈ I32.max16 ->      (* spec use literal [2^16] here *)\n      ⊢met limits ok\n\nwhere \"'⊢met' met 'ok' \" := (valid_memtype met).\nHint Constructors valid_memtype.\n\n(* ----------------------------------------------------------------- *)\n(** *** Global Types *)\n\nReserved Notation \"'⊢gt' gt 'ok'\" (at level 70).\nInductive valid_globaltype : globaltype -> Prop :=\n\n  | VGT: forall mut vt,\n      ⊢gt (mut, vt) ok\n\nwhere \"'⊢gt' gt 'ok' \" := (valid_globaltype gt).\nHint Constructors valid_globaltype.\n\n(* ----------------------------------------------------------------- *)\n(** *** External Types *)\n\nReserved Notation \"'⊢et' et 'ok'\" (at level 70).\nInductive valid_externtype : externtype -> Prop :=\n\n  | VET_func: forall ft,\n      ⊢ft ft ok ->\n      ⊢et (ET_func ft) ok\n\n  | VET_table: forall tt,\n      ⊢tt tt ok ->\n      ⊢et (ET_table tt) ok\n\n  | VET_mem: forall mt,\n      ⊢met mt ok ->\n      ⊢et (ET_mem mt) ok\n\n  | VET_global: forall gt,\n      ⊢gt gt ok ->\n      ⊢et (ET_global gt) ok\n\nwhere \"'⊢et' et 'ok' \" := (valid_externtype et).\nHint Constructors valid_externtype.\n\n\n(* ================================================================= *)\n(** ** Instructions *)\n(** https://webassembly.github.io/spec/core/valid/instructions.html *)\n\n(** Instructions are classified by _function types_ [[t1∗] --> [t2∗]]\n    that describe how they manipulate the _operand stack_.\n\n    Typing extends to instruction sequences [instr∗]. Such a sequence\n    has a function type [[t1∗] --> [t2∗]] if the _accumulative effect_\n    of executing the instructions is consuming values of types [t1∗]\n    off the operand stack and pushing new values of types [t2∗].\n *)\n\n\nReserved Notation \"C '⊢' instr '∈' ft\" (at level 70).\nReserved Notation \"C '⊢*' instrs '∈' ft\" (at level 70).\n\nInductive valid_instr : context -> instr -> functype -> Prop :=\n(* ----------------------------------------------------------------- *)\n(** *** Numeric Instruction *)\n\n  | VI_const : forall C t val,\n      t = type_of val ->\n      C ⊢ val ∈ [] --> [t]\n\n  | VI_unop : forall C t op,\n      t = type_of op ->\n      C ⊢ Unop op ∈ [t] --> [t]\n\n  | VI_binop : forall C t op,\n      t = type_of op ->\n      C ⊢ Binop op ∈ [t; t] --> [t]\n\n  | VI_testop : forall C t op,\n      t = type_of op ->\n      C ⊢ Testop op ∈ [t] --> [T_i32]\n\n  | VI_relop : forall C t op,\n      t = type_of op ->\n      C ⊢ Relop op ∈ [t; t] --> [T_i32]\n(*\n  | VI_cvtop : forall C t1 t2 sx op,\n      C ⊢ Cvtop t2 t1 sx op ∈ [t1] --> [t2]\n*)\n\n(* ----------------------------------------------------------------- *)\n(** *** Parametric Instruction *)\n\n  | VI_drop : forall C t,\n      C ⊢ Drop ∈ [t] --> []\n\n  | VI_select : forall C t,\n      C ⊢ Select ∈ [t; t; T_i32] --> [t]\n\n(* ----------------------------------------------------------------- *)\n(** *** Variable Instruction *)\n\n  (* | VI_local_get : forall C x t, *)\n  (*     C.(C_locals).[x] = Some t -> *)\n  (*     C ⊢ Local_get x ∈ [] --> [t] *)\n\n  (* | VI_local_set : forall C x t, *)\n  (*     C.(C_locals).[x] = Some t -> *)\n  (*     C ⊢ Local_set x ∈ [t] --> [] *)\n\n  (* | VI_local_tee : forall C x t, *)\n  (*     C.(C_locals).[x] = Some t -> *)\n  (*     C ⊢ Local_tee x ∈ [t] --> [t] *)\n\n(*\n  | VI_global_get : forall C x t,\n      C.(globals).[x] = Some t ->\n      C ⊢ Global_get x ∈ [] --> [t]\n\n  | VI_global_set : forall C x t,\n      C.(globals).[x] = Some t ->\n      C ⊢ Global_set x ∈ [t] --> []\n*)\n   \n(* ----------------------------------------------------------------- *)\n(** *** Memory Instruction *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Control Instructions *)\n\n  | VI_nop : forall C,\n      C ⊢ Nop ∈ [] --> []\n\n  | VI_unreachable : forall C ts1 ts2,\n      C ⊢ Unreachable ∈ ts1 --> ts2\n\n  | VI_block : forall C bt ts1 ts2 instrs,\n      C ⊢bt bt ∈ ts1 --> ts2 ->\n      C,labels ts2 ⊢* instrs ∈ ts1 --> ts2 ->\n      C ⊢ Block bt instrs ∈ ts1 --> ts2\n\n  | VI_loop : forall C bt ts1 ts2 instrs,\n      C ⊢bt bt ∈ ts1 --> ts2 ->\n      C,labels ts1 ⊢* instrs ∈ ts1 --> ts2 ->\n      C ⊢ Loop bt instrs ∈ ts1 --> ts2\n\n  | VI_if : forall C bt ts1 ts2 instrs1 instrs2,\n      C ⊢bt bt ∈ ts1 --> ts2 ->\n      C,labels ts2 ⊢* instrs1 ∈ ts1 --> ts2 ->\n      C,labels ts2 ⊢* instrs2 ∈ ts1 --> ts2 ->\n      C ⊢ If bt instrs1 instrs2 ∈ (ts1 ++ [T_i32]) --> ts2\n\n  | VI_br : forall C l ts ts1 ts2,\n      C.(C_labels).[l] = Some ts ->\n      C ⊢ Br l ∈ (ts1 ++ ts) --> ts2\n\n  | VI_br_if : forall C l ts,\n      C.(C_labels).[l] = Some ts ->\n      C ⊢ Br_if l ∈ (ts ++ [T_i32]) --> ts\n\n  | VI_br_table : forall C ls l__N ts ts1 ts2,\n      Forall (fun l => C.(C_labels).[l] = Some ts) ls ->\n      C.(C_labels).[l__N] = Some ts ->\n      C ⊢ Br_table ls l__N ∈ (ts1 ++ ts ++ [T_i32]) --> ts2\n\n  (* | VI_return : forall C tr ts1 ts2, *)\n  (*     C.(C_return) = Some tr -> *)\n  (*     C ⊢ Return ∈ (ts1 ++ tr) --> ts2 *)\n\n  (* | VI_call : forall C x ts1 ts2, *)\n  (*     C.(C_funcs).[x] = Some (ts1 --> ts2) -> *)\n  (*     C ⊢ Call x ∈ ts1 --> ts2 *)\n\n(*\n  | VI_call_indirect : forall C x ts1 ts2,\n      C.(tables).[0] = ??? ->\n      C.(C_types).[x] = Some (ts1 --> ts2) ->\n      C ⊢ [call_indirect x] ∈ (ts1 ++ [i32]) --> ts2\n*)\n\n(* ----------------------------------------------------------------- *)\n(** *** Instruction Sequences *)\n(** http://webassembly.github.io/spec/core/valid/instructions.html#instruction-sequences *)\n\nwith valid_instrs : context -> list instr -> functype -> Prop :=\n\n  | VIS_empty : forall C ts,\n      C ⊢* [] ∈ ts --> ts\n\n  | VIS_snoc : forall C instrs instr__N ts0 ts1 ts ts3,\n      C ⊢* instrs ∈ ts1 --> (ts0 ++ ts) (* ts2 *) ->\n      C ⊢  instr__N ∈ ts --> ts3 ->\n      C ⊢* instrs ++ [instr__N] ∈ ts1 --> (ts0 ++ ts3)\n\nwhere \"C '⊢' instr '∈' ft\" := (valid_instr C instr ft)\n  and \"C '⊢*' instrs '∈' ft\" := (valid_instrs C instrs ft).\n\nHint Constructors valid_instr.\nHint Constructors valid_instrs.\n\n\n(* postpone functional type checking.\n\nFixpoint check_instr \n\n*)\n\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Expressions *)\n(** http://webassembly.github.io/spec/core/valid/instructions.html#expressions *)\n\n(** expression, a.k.a block is almost the same as [list instr]\n    except it is typechecking against the [resulttype] rather than [functype].\n\n    so we need this rule to establish the relation between them.\n *)\n\nReserved Notation \"C '⊢e' expr '∈' ty\" (at level 70).\nInductive valid_expr : context -> expr -> resulttype -> Prop :=\n\n  | VE : forall C e tr,\n      C ⊢* e ∈ [] --> tr ->\n      C ⊢e e ∈ tr\n\nwhere \"C '⊢e' expr '∈' ty\" := (valid_expr C expr ty).\n\nHint Constructors valid_expr.\n\n\n(** **** Constant Expressions *)\n(** http://webassembly.github.io/spec/core/valid/instructions.html#constant-expressions *)\n\n(** the spec said:\n\n    > In a constant expression [instr* 𝖾𝗇𝖽] all instructions in [instr*] must be constant.\n\n    so which extract the [instr*] from [expr] without defining a [Inductive const_instrs].\n *)\n\nReserved Notation \"C '⊢e' instrs 'const'\" (at level 70).\nReserved Notation \"C '⊢' instr 'const'\" (at level 70).\nInductive const_expr : context -> expr -> Prop :=\n\n  | CE: forall C e,\n      Forall (fun instr => C ⊢ instr const) e ->\n      C ⊢e e const\n\nwith const_instr : context -> instr -> Prop :=\n\n  | CI_const : forall C v,\n      C ⊢ Const v const\n\n  (* | CI_global_get *)\n\nwhere \"C '⊢e' e 'const' \" := (const_expr C e)\n  and \"C '⊢' instr 'const' \" := (const_instr C instr).\n    \nHint Constructors const_expr.\nHint Constructors const_instr.\n\n\n(** **** Constant Expressions - Lemma *)\n(** To get [val] back from [instr], we need boolean operations. \n    Naming conventions follow the Coq standard lib that postfix with a [b]\n*)\n\nSection ConstLemma.\n\n  Definition const_b (i: instr) : bool := \n    match i with\n    | Const _ => true\n    | _ => false\n    end.\n\n  Definition consts_b (instrs: list instr) : bool :=\n    forallb const_b instrs.\n\n  Lemma const_eqbP : forall instr C,\n      reflect (C ⊢ instr const) (const_b instr).\n  Proof.\n    intros.\n    apply iff_reflect. split; intros.\n    - (* -> *)\n      destruct instr;\n        try (inversion H).\n      reflexivity.\n    - (* <- *)\n      destruct instr;\n        try (inversion H). \n      constructor.\n  Qed.\n\n  Lemma consts_eqbP : forall e C,\n      reflect (C ⊢e e const) (consts_b e).\n  Proof with auto.\n    intros.\n    apply iff_reflect. split; intros.\n    - (* -> *)\n      inverts H.\n      induction e.\n      + (* [] *) simpl...\n      + (* :: *)\n        simpl. \n        apply andb_true_iff.\n        split.\n        ++ (* head *)\n          apply Forall_inv in H0.\n          destruct (const_eqbP a C)...\n        ++ (* tail *)\n          apply Forall_inv_tail in H0.\n          apply IHe...\n    - (* <- *)\n      induction e.\n      + (* [] *) constructor. apply Forall_nil.\n      + (* :: *)\n        simpl in H.\n        apply andb_true_iff in H.\n        destruct H.\n        constructor.\n        constructor.\n        ++ destruct (const_eqbP a C). auto. inverts H.\n        ++ apply IHe in H0. inverts H0...\n  Qed.\n\n  Lemma const_val : forall instr C,\n      C ⊢ instr const ->\n      exists val, instr = Const val.\n  Proof with auto.\n    introv H.\n    destruct instr;\n      try (inversion H); subst.\n    exists val...\n  Qed.\n\n  Lemma consts_vals : forall e C,\n      C ⊢e e const ->\n      exists vals, e = map Const vals.\n  Proof with auto.\n    introv H.\n    induction e.\n    - exists (@nil val)...\n    - inverts H.\n      inverts H0.\n      assert (C ⊢e e const). constructor. assumption.\n      apply IHe in H.\n      destruct H.\n      apply const_val in H2.\n      destruct H2; subst.\n      exists (x0 :: x). simpl...\n  Qed.\n\nEnd ConstLemma.\n\n(* postpone functional type checking.\n\nFixpoint check_expr (C : context) (e : expr) (tr : resulttype) :=\n\n*)\n\n\n\n(* ================================================================= *)\n(** ** Modules *)\n(** http://webassembly.github.io/spec/core/valid/modules.html *)\n\n(* ----------------------------------------------------------------- *)\n(** *** Functions *)\n(** http://webassembly.github.io/spec/core/valid/modules.html#functions *)\n\n(** Issue on \"validation rule for function is inaccurate\"\n  * https://github.com/WebAssembly/spec/issues/1072\n\n  * we need to update this rule with just locals* and labels and maybe return\n  * the \"replace\" is a stronger requirement that we might be able to show\n  *)\n\nReserved Notation \"C '⊢f' f ∈ ft\" (at level 70).\nInductive valid_func : context -> func -> functype -> Prop :=\n\n  | VF : forall C x ts expr ts1 ts2,\n      C.(C_types).[x] = Some (ts1 --> ts2) ->\n      C with_locals = (ts1 ++ ts) with_labels = [ts2] with_return = Some ts2 ⊢e expr ∈ ts2 ->\n      C ⊢f {| F_type := x; F_locals := ts; F_body := expr |} ∈ ts1 --> ts2\n\nwhere \"C '⊢f' f ∈ ft\" := (valid_func C f ft).\nHint Constructors valid_functypes.\n\n(* This is not explicitly defined but occured as\n\n     (⊢ func : ft)*\n\n   when typing modules as a pairwise relation.\n\n   > Let ft∗ be the concatenation of the internal function types fti, in index order.\n*)\n\nReserved Notation \"C '⊢f*' fs ∈ fts\" (at level 70).\nInductive valid_funcs : context -> list func -> list functype -> Prop :=\n\n  | VFS: forall C fs fts,\n      Forall2 (fun func ft => C ⊢f func ∈ ft) fs fts ->  \n      C ⊢f* fs ∈ fts\n\nwhere \"C '⊢f*' fs ∈ fts\" := (valid_funcs C fs fts).\nHint Constructors valid_funcs.\n\n\nModule FuncTyTest.\n\n  Definition ft := [T_i32] --> [T_i32].\n  Definition ins :=\n    let '(ins --> outs) := ft in ins.\n  Definition ins2 :=\n    match ft with\n    | (ins --> outs) => ins\n    end.\n\n  Definition foo := Build_func 0 [] []. \n  Definition a :=\n    (* By let pattern *)\n    let 'Build_func a b c := foo in a.\n  Definition a2 :=\n    (* By constructor pattern *)\n    match foo with\n      | Build_func a b c  => a\n    end.\n  Definition a3 :=\n    (* By notational pattern *)\n    match foo with\n      | {| F_type := a; F_locals := b; F_body := c |} => a\n    end.\n\nEnd FuncTyTest.\n\n(* postpone functional type checking.\n\nFixpoint check_func (C: context) (f: func) :=\n  let '(Build_func type locals body) := f in\n  let '(ts1 --> ts2) := C.(C_types).[type] in\n  let C' = C, locals__s (ts1 ++ ts), labels ts2 with_return = Some ts2 in\n  check_expr C' body ts2.\n*)\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Tables *)\n\nReserved Notation \"C '⊢t' t ∈ tt\" (at level 70).\nInductive valid_table : context -> table -> tabletype -> Prop :=\n\n  | VT : forall C tt,\n      ⊢tt tt ok ->\n      C ⊢t {| T_type := tt |} ∈ tt\n\nwhere \"C '⊢t' t ∈ tt\" := (valid_table C t tt).\nHint Constructors valid_table.\n\n(* This is not explicitly defined but occured as\n\n     (⊢ table : tt)*\n\n   when typing modules as a pairwise relation.\n\n   > Let tt∗ be the concatenation of the internal table types tti, in index order.\n*)\n\nReserved Notation \"C '⊢t*' tabs ∈ tts\" (at level 70).\nInductive valid_tables : context -> list table -> list tabletype -> Prop :=\n\n  | VTS: forall C tabs tts,\n      Forall2 (fun table tt => C ⊢t table ∈ tt) tabs tts ->\n      C ⊢t* tabs ∈ tts\n\nwhere \"C '⊢t*' tabs '∈' tts\" := (valid_tables C tabs tts).\nHint Constructors valid_tables.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Memories *)\n\nReserved Notation \"C '⊢me' mem ∈ met\" (at level 70).\nInductive valid_mem : context -> mem -> memtype -> Prop :=\n\n  | VME : forall C met,\n      ⊢met met ok ->\n      C ⊢me {| ME_type := met |} ∈ met\n\nwhere \"C '⊢me' mem ∈ met\" := (valid_mem C mem met).\nHint Constructors valid_mem.\n\n(* ----------------------------------------------------------------- *)\n(** *** Globals *)\n\nReserved Notation \"C '⊢g' g ∈ gt\" (at level 70).\nInductive valid_global : context -> global -> globaltype -> Prop :=\n\n  | VG : forall C e mut t,\n      ⊢gt (mut, t) ok ->\n      C ⊢e e ∈ [t] ->\n      C ⊢e e const ->\n      C ⊢g {| G_type := (mut, t); G_init := e |} ∈ (mut, t)\n\nwhere \"C '⊢g' g ∈ gt\" := (valid_global C g gt).\nHint Constructors valid_global.\n\n(* ----------------------------------------------------------------- *)\n(** *** Element Segments *)\n\nReserved Notation \"C '⊢el' elem 'ok' \" (at level 70).\nInductive valid_elem : context -> elem -> Prop :=\n\n  | VEL : forall C x limits e ys,\n      C.(C_tables).[x] = Some (limits, funcref) ->\n      C ⊢e e ∈ [T_i32] ->\n      C ⊢e e const ->\n      Forall (fun y => C.(C_funcs).[y] <> None) ys ->\n      C ⊢el {| EL_table := x; EL_offset := e; EL_init := ys |} ok\n\nwhere \"C '⊢el' elem 'ok' \" := (valid_elem C elem).\nHint Constructors valid_elem.\n\n(* ----------------------------------------------------------------- *)\n(** *** Data Segments *)\n\nReserved Notation \"C '⊢d' data 'ok' \" (at level 70).\nInductive valid_data : context -> data -> Prop :=\n\n  | VD : forall C x e bs,\n      (* C.(C_mems).[x] <> None -> *)\n      C ⊢e e ∈ [T_i32] ->\n      C ⊢e e const ->\n      C ⊢d {| D_data := x; D_offset := e; D_init := bs |} ok\n\nwhere \"C '⊢d' data 'ok' \" := (valid_data C data).\nHint Constructors valid_data.\n\n(* ----------------------------------------------------------------- *)\n(** *** Start Function *)\n\nReserved Notation \"C '⊢start' start 'ok' \" (at level 70).\nInductive valid_start : context -> start -> Prop :=\n\n  | VStart : forall C x, \n      C.(C_funcs).[x] = Some ([] --> []) ->\n      C ⊢start {| START_func := x |} ok\n\nwhere \"C '⊢start' start 'ok' \" := (valid_start C start).\nHint Constructors valid_start.\n\n(* ----------------------------------------------------------------- *)\n(** *** Exports *)\n\nReserved Notation \"C '⊢ex' ex '∈' et \" (at level 70).\nReserved Notation \"C '⊢exd' exd '∈' et \" (at level 70).\nInductive valid_export : context -> export -> externtype -> Prop :=\n\n  | VEX : forall C name exd et, \n      C ⊢exd exd ∈ et ->\n      C ⊢ex {| EX_name := name; EX_desc := exd |} ∈ et\n\nwith valid_exportdesc : context -> exportdesc -> externtype -> Prop :=\n\n  | VEXD_func : forall C x ft,\n      C.(C_funcs).[x] = Some ft ->\n      C ⊢exd EXD_func x ∈ ET_func ft\n\n  | VEXD_table : forall C x tt,\n      C.(C_tables).[x] = Some tt ->\n      C ⊢exd EXD_table x ∈ ET_table tt\n\n  (* | VEXD_mem : forall C x met, *)\n  (*     C.(C_mems).[x] = Some met -> *)\n  (*     C ⊢exd EXD_mem x ∈ ET_mem met *)\n\n  (* | VEXD_global : forall C x gt, *)\n  (*     C.(C_globals).[x] = Some gt -> *)\n  (*     C ⊢exd EXD_global x ∈ ET_global gt *)\n\nwhere \"C '⊢ex' ex '∈' et \" := (valid_export C ex et)\n  and \"C '⊢exd' exd '∈' et \" := (valid_exportdesc C exd et).\n\nHint Constructors valid_export.\nHint Constructors valid_exportdesc.\n\n(* ----------------------------------------------------------------- *)\n(** *** Imports *)\n\nReserved Notation \"C '⊢im' im '∈' et \" (at level 70).\nReserved Notation \"C '⊢imd' imd '∈' et \" (at level 70).\nInductive valid_import : context -> import -> externtype -> Prop :=\n\n  | VIM : forall C name1 name2 imd et,\n      C ⊢imd imd ∈ et ->\n      C ⊢im {| IM_module := name1; IM_name := name2; IM_desc := imd |} ∈ et\n\nwith valid_importdesc : context -> importdesc -> externtype -> Prop :=\n\n  | VIMD_func : forall C x ft,\n      C.(C_funcs).[x] = Some ft ->\n      C ⊢imd IMD_func x ∈ ET_func ft\n\n  | VIMD_table : forall C x tt,\n      C.(C_tables).[x] = Some tt ->\n      C ⊢imd IMD_table x ∈ ET_table tt\n\n  (* | VIMD_mem : forall C x met, *)\n  (*     C.(C_mems).[x] = Some met -> *)\n  (*     C ⊢imd IMD_mem x ∈ ET_mem met *)\n\n  (* | VIMD_global : forall C x gt, *)\n  (*     C.(C_globals).[x] = Some gt -> *)\n  (*     C ⊢imd IMD_global x ∈ ET_global gt *)\n\nwhere \"C '⊢im' im '∈' et \" := (valid_import C im et)\n  and \"C '⊢imd' imd '∈' et \" := (valid_importdesc C imd et).\n\nHint Constructors valid_import.\nHint Constructors valid_importdesc.\n\n\n(* ----------------------------------------------------------------- *)\n(** *** Modules *)\n(** http://webassembly.github.io/spec/core/valid/modules.html#valid-module *)\n\n(** A module is entirely closed, i.e., no initial context is required.\n    Instead, the context C for validation of the module’s content is constructed from the definitions in the module. *)\n\n(** Let ft∗ be the concatenation of the internal function types fti, in index order.\n *)\n\nReserved Notation \"'⊢' M ∈ ty\" (at level 70).\nInductive valid_module: module -> functype -> Prop :=\n  | VM : forall its ets fts tts functypes funcs tables,\n\n(* Let C be a context where: *)\n      let\n        C := {|\n          C_types := functypes;\n          C_funcs := fts;  (* ++ ifts *)\n          C_tables := tts; (* ++ itts *)\n          C_locals := [];\n          C_labels := [];\n          C_return := None;\n        |}\n      in\n\n        ⊢ft* functypes ok ->\n\n      C ⊢f* funcs ∈ fts ->\n      C ⊢t* tables ∈ tts ->\n\n      (* length limitatin of current Wasm version *)\n      length C.(C_tables) <= 1 ->\n      (* length C.(C_mems) <= 1 -> *)\n\n      ⊢ {|\n           M_types := functypes;\n           M_funcs := funcs;\n           M_tables := tables;\n        |} ∈ its --> ets\n      \nwhere \"'⊢' M ∈ ty\" := (valid_module M ty).\n\n\n(* postpone functional type checking.\n\nFixpoint prepass_funcs (funcs : list func) : list functype :=\n  map (fun func => C.(C_types).[func.type]) funcs. \n\nFixpoint check_module \n\n*)\n", "meta": {"author": "Huxpro", "repo": "WasmCert", "sha": "7b7385ccbaa62b0aaf6b7757e6847c7d5c32933c", "save_path": "github-repos/coq/Huxpro-WasmCert", "path": "github-repos/coq/Huxpro-WasmCert/WasmCert-7b7385ccbaa62b0aaf6b7757e6847c7d5c32933c/coq/Validation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.22114752338165658}}
{"text": "Require Import QuantumLib.Proportional.\nRequire Export RzQGateSet.\nImport RzQList.\nRequire Import MappingConstraints.\n\nImport Qreals. (* Coq version < 8.13.0 has Q2R defined in Qreals *) \n\nLocal Close Scope C_scope.\nLocal Close Scope R_scope.\nLocal Close Scope Q_scope.\n\nLocal Open Scope ucom_scope.\n\n(* Propagate an X gate on qubit q as far right as possible, cancelling the\n   gate if possible. The rules in Nam et al. use Toffoli gates with +/- controls;\n   we achieve the same effect by propagating X through H, CNOT, and Rz gates \n   (although our omission of the Toffoli gate does not allow us to change polarity \n   of T/T† gates).\n\n   Note that this optimization may increase the number of gates due to how\n   X propagates through CNOT. These additional gates will often be removed by\n   later passes. *)\n\nRequire Import FSets.FSetAVL.\nRequire Import FSets.FSetFacts.\nRequire Import FSets.FSetProperties.\n\nModule FSet := FSetAVL.Make(Coq.Structures.OrderedTypeEx.Nat_as_OT).\nModule FSetFacts := FSetFacts.Facts FSet.\nModule FSetProps := FSetProperties.Properties FSet.\n\nLemma mem_reflect : forall x s, reflect (FSet.In x s) (FSet.mem x s).\nProof. intros x l. apply iff_reflect. apply FSetFacts.mem_iff. Qed.\n#[export] Hint Resolve mem_reflect : bdestruct.\n\n(* Apply an X gate to every qubits in set qs. *)\nDefinition finalize {dim} qs : RzQ_ucom_l dim := \n  FSet.fold (fun q a => X q :: a) qs []. \n\n(* l   : input program\n   qs  : qubits where an X gate is currently being propagated\n   acc : accumulator for tail recursion *)\n\nFixpoint not_propagation' {dim} (l acc : RzQ_ucom_l dim) qs :=\n  match l with\n  | [] => rev_append acc (finalize qs)\n  | App1 URzQ_X q :: t => \n      let qs' := if FSet.mem q qs then FSet.remove q qs else FSet.add q qs in\n      not_propagation' t acc qs'\n  | App1 URzQ_H q :: t =>\n      if FSet.mem q qs\n      then not_propagation' t (RzQGateSet.Z q :: H q :: acc) (FSet.remove q qs)\n      else not_propagation' t (H q :: acc) qs\n  | App1 (URzQ_Rz a) q :: t =>\n      if FSet.mem q qs\n      then not_propagation' t (invert_rotation a q :: acc) qs\n      else not_propagation' t (Rzq a q :: acc) qs\n  | App2 URzQ_CNOT m n :: t =>\n      let qs' := if FSet.mem m qs \n                 then if FSet.mem n qs then FSet.remove n qs else FSet.add n qs\n                 else qs in\n      not_propagation' t (CNOT m n :: acc) qs'\n  | _ => acc (* impossible case *)\n  end.\n\nDefinition not_propagation {dim} (l : RzQ_ucom_l dim) := \n  not_propagation' l [] FSet.empty.\n\n(** semantics preservation **)\n\nLemma finalize_unfold : forall {dim} q qs,\n  FSet.In q qs ->\n  finalize qs =l= [@X dim q] ++ finalize (FSet.remove q qs).\nProof.\n  intros.\n  symmetry.\n  simpl.\n  unfold finalize.\n  specialize (FSetProps.remove_fold_1 (uc_equiv_l_rel dim)) as Hfold.\n  specialize (Hfold (fun q a => X q :: a)).\n  simpl in Hfold.\n  apply Hfold; auto; clear Hfold.\n  unfold compat_op; solve_proper. \n  unfold transpose.\n  intros.\n  rewrite 2 (cons_to_app _ (_ :: _)).\n  rewrite 2 (cons_to_app _ z).\n  apply_app_congruence.\n  bdestruct (x =? y).\n  subst.\n  reflexivity.\n  apply does_not_reference_commutes_app1.\n  simpl.\n  apply andb_true_intro; split; auto.\n  rewrite negb_true_iff. \n  apply Nat.eqb_neq; auto.\nQed.\n\nLemma finalize_equal : forall {dim} qs1 qs2,\n  FSet.Equal qs1 qs2 ->\n  @finalize dim qs1 =l= finalize qs2.\nProof.\n  intros.\n  unfold finalize.\n  apply FSetProps.fold_equal; auto.\n  apply uc_equiv_l_rel.\n  unfold compat_op; solve_proper. \n  unfold transpose.\n  intros.\n  rewrite 2 (cons_to_app _ (_ :: _)).\n  rewrite 2 (cons_to_app _ z).\n  apply_app_congruence.\n  bdestruct (x =? y).\n  subst.\n  reflexivity.\n  apply does_not_reference_commutes_app1.\n  simpl.\n  apply andb_true_intro; split; auto.\n  rewrite negb_true_iff. \n  apply Nat.eqb_neq; auto.\nQed.\n\nLemma finalize_empty : forall {dim},\n  @finalize dim FSet.empty = [].\nProof. \n  intros.\n  unfold finalize.\n  apply FSetProps.fold_empty.\nQed.\n\nLemma finalize_dnr : forall {dim} q qs,\n  not (FSet.In q qs) -> \n  does_not_reference (@finalize dim qs) q = true.\nProof.\n  intros.\n  unfold finalize.\n  apply FSetProps.fold_rec; intros.\n  reflexivity.\n  simpl.\n  apply andb_true_intro; split; auto.\n  rewrite negb_true_iff. \n  apply Nat.eqb_neq.\n  intro contra.\n  subst.\n  contradiction.\nQed.\nLemma not_propagation'_preserves_semantics : forall {dim} (l acc : RzQ_ucom_l dim) qs,\n  uc_well_typed_l l ->\n  not_propagation' l acc qs ≅l≅ \n    (rev acc ++ (finalize qs) ++ l).\nProof.\n  intros dim l.\n  induction l; intros acc qs WT.\n  simpl.\n  rewrite rev_append_rev, app_nil_r.\n  reflexivity.\n  destruct a; dependent destruction r; simpl;\n  inversion WT; subst.\n  - (* H case *)\n    bdestruct (FSet.mem n qs); rewrite IHl by assumption; \n    apply uc_equiv_cong_l; simpl.\n    + rewrite (finalize_unfold _ _ H) by assumption.\n      rewrite (cons_to_app _ l).\n      apply_app_congruence.\n      rewrite <- (does_not_reference_commutes_app1 _ URzQ_H).\n      apply_app_congruence.\n      unfold_uc_equiv_l.\n      unfold one_Q.\n      replace (Q2R 1 * PI)%R with PI.\n      apply H_comm_Z.\n      unfold Q2R; simpl; lra.\n      apply finalize_dnr.\n      apply FSet.remove_1; auto.\n    + rewrite (cons_to_app _ l).\n      apply_app_congruence.\n      apply does_not_reference_commutes_app1.\n      apply finalize_dnr; auto.\n  - (* X case *)\n    rewrite IHl by assumption.\n    apply uc_equiv_cong_l.\n    rewrite (cons_to_app _ l).\n    bdestruct (FSet.mem n qs).\n    + rewrite (finalize_unfold n qs) by assumption.\n      unfold X.\n      rewrite (does_not_reference_commutes_app1 _ URzQ_X).\n      rewrite <- (app_nil_r (finalize _)) at 1.\n      apply_app_congruence.\n      unfold uc_equiv_l; simpl.\n      rewrite SKIP_id_r.\n      symmetry.\n      rewrite <- (ID_equiv_SKIP dim n) by assumption.\n      apply X_X_id.\n      apply finalize_dnr.\n      apply FSet.remove_1; auto.\n    + rewrite (finalize_unfold n (FSet.add n qs)); auto.\n      unfold X.\n      rewrite (does_not_reference_commutes_app1 _ URzQ_X).\n      apply_app_congruence.\n      apply finalize_equal.\n      apply FSetProps.remove_add; auto.\n      apply finalize_dnr.\n      apply FSet.remove_1; auto.\n      apply FSet.add_1; auto.\n  - (* Rz case *)\n    bdestruct (FSet.mem n qs); rewrite IHl by assumption; simpl.\n    + rewrite (cons_to_app _ l).\n      apply_app_congruence_cong.\n      specialize (@finalize_unfold dim n qs H) as unf.\n      apply uc_equiv_cong_l in unf.\n      rewrite unf.\n      assert (@does_not_reference _ dim (finalize (FSet.remove n qs)) n = true).\n      apply finalize_dnr.\n      apply FSet.remove_1; auto.\n      specialize (@does_not_reference_commutes_app1 dim (finalize (FSet.remove n qs)) (URzQ_Rz a) n H0) as comm.\n      apply uc_equiv_cong_l in comm.\n      rewrite <- app_assoc.\n      rewrite <- comm.\n      apply_app_congruence_cong.\n      unfold uc_cong_l. simpl. \n      erewrite uc_seq_cong.\n      2: { apply uc_equiv_cong.\n           specialize (@invert_rotation_semantics dim a n) as tmp. \n           simpl in tmp. rewrite SKIP_id_r in tmp.\n           apply tmp. }\n      2: apply uc_equiv_cong; apply SKIP_id_r.      \n      erewrite (uc_seq_cong _ _ (_ ; _)).\n      2: reflexivity.\n      2: apply uc_equiv_cong; apply SKIP_id_r.\n      symmetry.\n      apply X_comm_Rz.  \n    + apply uc_equiv_cong_l.\n      rewrite (cons_to_app _ l).\n      apply_app_congruence.\n      apply does_not_reference_commutes_app1.\n      apply finalize_dnr; auto.\n  - (* CNOT case *)\n    rewrite IHl by assumption. \n    simpl.\n    rewrite (cons_to_app _ l).\n    apply uc_equiv_cong_l.\n    apply_app_congruence.\n    bdestruct (FSet.mem n qs).\n    + bdestruct (FSet.mem n0 qs).\n      * rewrite (finalize_unfold n0 qs) by assumption.\n        rewrite (finalize_unfold n (FSet.remove n0 qs)).\n        repeat rewrite <- app_assoc.\n        rewrite <- does_not_reference_commutes_app2.\n        apply_app_congruence.\n        rewrite (uc_app_congruence [X n0] [X n0] _ ([CNOT n n0] ++ [X n] ++ [X n0])).\n        2: reflexivity.\n        2: { unfold_uc_equiv_l.\n             apply X_comm_CNOT_control. }\n        rewrite app_assoc.\n        rewrite (uc_app_congruence ([X n0] ++ [CNOT n n0]) ([CNOT n n0] ++ [X n0]) _ ([X n] ++ [X n0])).\n        2: { unfold_uc_equiv_l.\n             apply X_comm_CNOT_target. }\n        2: reflexivity.\n        unfold X.\n        rewrite does_not_reference_commutes_app1.\n        rewrite <- (app_nil_r [CNOT n n0]) at 1.\n        apply_app_congruence.\n        unfold uc_equiv_l; simpl.\n        rewrite SKIP_id_r.\n        rewrite <- (ID_equiv_SKIP dim n0) by assumption.\n        symmetry.\n        apply X_X_id.\n        simpl.\n        apply andb_true_intro; split; auto.\n        rewrite negb_true_iff. \n        apply Nat.eqb_neq; auto.\n        apply finalize_dnr.\n        apply FSet.remove_1; auto.\n        apply finalize_dnr.\n        intro contra.\n        apply FSet.remove_3 in contra.\n        contradict contra.\n        apply FSet.remove_1; auto.\n        apply FSet.remove_2; auto.\n      * rewrite (finalize_unfold n0 (FSet.add n0 qs)); auto.\n        erewrite finalize_equal.\n        2: apply FSetProps.remove_add; auto.\n        rewrite (finalize_unfold n qs); auto.\n        rewrite <- app_assoc.\n        rewrite <- does_not_reference_commutes_app2.\n        apply_app_congruence.\n        unfold X.\n        rewrite (does_not_reference_commutes_app1 _ _ n0).     \n        unfold_uc_equiv_l.\n        symmetry.\n        apply X_comm_CNOT_control.\n        simpl.\n        apply andb_true_intro; split; auto.\n        rewrite negb_true_iff. \n        apply Nat.eqb_neq; auto.\n        apply finalize_dnr.\n        apply FSet.remove_1; auto.\n        apply finalize_dnr.\n        intro contra.\n        apply FSet.remove_3 in contra.\n        contradiction.\n        apply FSet.add_1; auto.\n    + bdestruct (FSet.mem n0 qs).\n      * rewrite (finalize_unfold n0 qs) by assumption.\n        rewrite <- app_assoc.\n        rewrite <- does_not_reference_commutes_app2.\n        apply_app_congruence.   \n        unfold_uc_equiv_l.\n        symmetry.\n        apply X_comm_CNOT_target.\n        apply finalize_dnr.\n        intro contra.\n        apply FSet.remove_3 in contra.\n        contradiction.\n        apply finalize_dnr.\n        apply FSet.remove_1; auto.\n      * apply does_not_reference_commutes_app2.\n        apply finalize_dnr; auto.\n        apply finalize_dnr; auto.\nQed.\nLemma not_propagation_sound : forall {dim} (l : RzQ_ucom_l dim), \n  uc_well_typed_l l -> not_propagation l ≅l≅ l.\nProof.\n  intros.\n  unfold not_propagation.\n  rewrite not_propagation'_preserves_semantics; auto.\n  rewrite finalize_empty.\n  reflexivity.\nQed.\n\nLemma not_propagation_WT : forall {dim} (l : RzQ_ucom_l dim),\n  uc_well_typed_l l -> uc_well_typed_l (not_propagation l).\nProof.\n  intros dim l WT.\n  specialize (not_propagation_sound l WT) as H.\n  symmetry in H.\n  apply uc_cong_l_implies_WT in H; assumption.\nQed.\n\n(** mapping preservation **)\n\nLemma finalize_respects_constraints: forall {dim} qs (is_in_graph : nat -> nat -> bool),\n  respects_constraints_directed is_in_graph URzQ_CNOT (@finalize dim qs).\nProof.\n  intros.\n  unfold finalize.\n  apply FSetProps.fold_rec.\n  - intros.\n    constructor.\n  - intros.\n    constructor; assumption.\nQed.\n\nLemma not_propagation'_respects_constraints : forall {dim} (l acc : RzQ_ucom_l dim) (is_in_graph : nat -> nat -> bool) qs,\n  respects_constraints_directed is_in_graph URzQ_CNOT l -> \n  respects_constraints_directed is_in_graph URzQ_CNOT acc ->\n  respects_constraints_directed is_in_graph URzQ_CNOT (not_propagation' l acc qs).\nProof.\n  intros dim l acc is_in_graph qs H H1.\n  generalize dependent acc. generalize dependent qs.\n  induction l.\n  intros qs acc H1.\n  simpl.\n  rewrite rev_append_rev.\n  apply respects_constraints_directed_app.\n  - apply rev_respects_constraints. assumption.\n  - apply finalize_respects_constraints.\n  - intros qs acc H1.\n    simpl.\n    destruct a. \n    dependent destruction r; \n      destruct (NotPropagation.FSet.mem n qs) eqn:H2; \n      apply IHl; inversion H; subst; try (apply H4); \n      repeat constructor; try assumption.      \n    + dependent destruction r.\n      apply IHl.\n      inversion H; subst.\n      apply H7.\n      constructor.\n      inversion H; subst.\n      apply H5.\n      apply H1.\n   + assumption.\nQed.\n\nLemma not_propagation_respects_constraints :\n  forall {dim} (l : RzQ_ucom_l dim) (is_in_graph : nat -> nat -> bool),\n    respects_constraints_directed is_in_graph URzQ_CNOT l ->\n    respects_constraints_directed is_in_graph URzQ_CNOT (not_propagation l).\nProof.\n  intros dim l is_in_graph  H.\n  unfold not_propagation.\n  apply not_propagation'_respects_constraints; try assumption; try constructor.\nQed. \n", "meta": {"author": "inQWIRE", "repo": "SQIR", "sha": "7d2938bf63080e37d47059befa27a57f12cc099c", "save_path": "github-repos/coq/inQWIRE-SQIR", "path": "github-repos/coq/inQWIRE-SQIR/SQIR-7d2938bf63080e37d47059befa27a57f12cc099c/VOQC/NotPropagation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.22114752338165658}}
{"text": "Require Import AST.\nRequire Import Coqlib.\nRequire Import String.\n(* AST *)\nDefinition str := string.\nRecord ident := { name: str; key: BinNums.positive }.\n\nInductive singleclock : Type :=\n  | Clock : bool -> ident -> singleclock\n  | NOCLOCK : singleclock.\n\nInductive funcType : Type :=\n  | Function: funcType\n  | Node: funcType.\n\nInductive atomType : Type :=\n  | Bool : atomType\n  | Int : atomType\n  | Real : atomType.\n\nInductive unOp : Type :=\n  | NOT : unOp\n  | POS : unOp\n  | NEG : unOp.\n\nInductive binOp : Type :=\n  | ADD : binOp\n  | SUB : binOp\n  | MUL : binOp\n  | DIVF : binOp\n  | DIV : binOp\n  | MOD : binOp\n  | AND : binOp\n  | OR : binOp\n  | XOR : binOp\n  | GT : binOp\n  | LT : binOp\n  | GE : binOp\n  | LE : binOp\n  | EQ : binOp\n  | NE : binOp.\n\nInductive atomExpr : Type :=\n  | EIdent : ident -> atomExpr\n  | EBool : ident -> atomExpr\n  | EInt : ident -> atomExpr\n  | EReal : ident -> atomExpr.\n\nInductive constExpr : Type :=\n  | CEAtom: atomExpr -> constExpr\n  | CEUnOpExpr : unOp -> constExpr -> constExpr\n  | CEBinOpExpr : binOp -> constExpr -> constExpr -> constExpr\n  | CEConstructor: cNameItems -> constExpr\n  | CEArray: constExprlist -> constExpr\nwith constExprlist : Type :=\n  | CEnil : constExprlist\n  | CEcons : constExpr -> constExprlist -> constExprlist\nwith cNameItems : Type :=\n  | CNamesNil : cNameItems\n  | CNamesCons: ident -> constExpr -> cNameItems -> cNameItems.\n\nInductive kind : Type :=\n  | AtomType : atomType -> kind \n  | Struct : fieldlist -> kind\n  | Array : kind -> constExpr -> kind\n  | EnumType : list ident -> kind\n  | TypeDef: ident -> kind\nwith fieldlist : Type :=\n  | Fnil : fieldlist\n  | Fcons : ident -> kind -> fieldlist -> fieldlist.\n\nInductive mega : Type :=\n  | Mega : ident -> ident -> mega.\n\nInductive expr : Type :=\n  | AtomExpr : atomExpr -> expr\n  | UnOpExpr : unOp -> expr -> expr\n  | BinOpExpr : binOp -> expr -> expr -> expr\n  | FieldExpr : expr -> ident -> expr\n  | ArrAccessExpr : expr -> constExpr -> expr\n  | ArrInitExpr : expr -> constExpr -> expr\n  | ArrConstructExpr : exprlist -> expr\n  | NameConstructExpr : namelist -> expr\n  | PreExpr : expr -> expr\n  | FbyExpr : exprlist -> constExpr -> exprlist -> expr\n  | ArrowExpr : expr -> expr -> expr\n  | WhenExpr : expr -> bool -> ident -> expr\n  | CurrentExpr : expr -> expr\n  | IfExpr : expr -> expr -> expr -> expr\n  | ExprList : exprlist -> expr\n  | Call : ident -> exprlist -> expr\n  | DieseExpr : expr -> expr\n  | NorExpr : expr -> expr\n  | MergeExpr : ident -> expr -> expr -> expr\n\nwith exprlist : Type :=\n  | Enil : exprlist\n  | Econs : expr -> exprlist -> exprlist \n\nwith namelist : Type :=\n  | NamesNil : namelist\n  | NamesCons : ident -> expr -> namelist -> namelist.\n\nInductive lhs : Type :=\n  | LVIdent : list ident -> lhs\n  | LVMega : mega -> lhs.\n\nInductive rhs : Type :=\n  | RVExpr : expr -> rhs\n  | RVMega : mega -> rhs.\n\nInductive eqStmt : Type :=\n  | EqStmt : lhs -> rhs -> eqStmt.\n\nInductive varBlk : Type :=\n  | VarList : list (ident * kind * singleclock) -> varBlk.\n\nInductive paramBlk : Type :=\n  | ParamBlk : list (ident * kind * singleclock) -> paramBlk.\n\nInductive staticBlk : Type :=\n  | StaticBlk : list (ident * kind) -> staticBlk.\n\nInductive returnBlk : Type :=\n  | ReturnBlk : list (ident * kind * singleclock) -> returnBlk.\n\nInductive bodyBlk : Type :=\n  | BodyBlk : varBlk -> list eqStmt -> bodyBlk.\n\nInductive typeStmt : Type :=\n  | TypeStmt : ident -> kind -> typeStmt.\n\nInductive constStmt : Type :=\n  | ConstStmt : ident -> kind -> constExpr -> constStmt.\n\nInductive nodeBlk : Type :=\n  | TypeBlk : list typeStmt -> nodeBlk\n  | ConstBlk : list constStmt -> nodeBlk\n  | FuncBlk : funcType -> ident -> paramBlk -> returnBlk -> bodyBlk -> nodeBlk\n  | WidgetBlk : ident -> staticBlk -> paramBlk -> returnBlk -> nodeBlk\n  | ControlBlk : ident -> bodyBlk -> nodeBlk.\n\nInductive program : Type :=\n  | Program : list nodeBlk -> program.\n", "meta": {"author": "linusboyle", "repo": "L2CDisplay", "sha": "4eb5b4dbb01da56534c0b0a1560dec8c715a68a4", "save_path": "github-repos/coq/linusboyle-L2CDisplay", "path": "github-repos/coq/linusboyle-L2CDisplay/L2CDisplay-4eb5b4dbb01da56534c0b0a1560dec8c715a68a4/display/LDisplay.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22114752338165655}}
{"text": "(* From TreeItrp.v\n *\n * An attempt to get spItrpUniq working without assuming UIP.\n * I couldn't get it to work.\n *)\n\nDefinition HProp T := forall x y:T,x = y.\n\nDefinition HPropUIP T (P:HProp T) x := eq_trans\n\t(match eq_sym (P x x) as p in _ = y return _ = eq_trans (P y x) p with eq_refl => eq_refl (P x x) end)\n\t(match P x x as p return eq_trans p (eq_sym p) = eq_refl x with eq_refl => eq_refl (eq_refl x) end).\nImplicit Arguments HPropUIP [T].\n\nInductive ExSimpParamItrp G F la : Type :=\n\texSimpParamItrp T' la' : SimpParamItrp G F la T' la'->ExSimpParamItrp G F la.\nImplicit Arguments exSimpParamItrp [G F la].\n\n(* You were about to prove some lemmas about the structure of ExSimpParamItrp paths. *)\n\nLemma spItrpProp G F la : forall Tla1 Tla2:ExSimpParamItrp G F la,Tla1 = Tla2.\n\tinduction la;intros.\n\n\tdestruct Tla1 as (T1,la1,s1).\n\tdestruct Tla2 as (T2,la2,s2).\n\tdestruct s1.\n\tdestruct s2.\n\treflexivity.\n\n\tdestruct Tla1 as (T1,la1,s1).\n\tdestruct Tla2 as (T2,la2,s2).\n\tsimpl in s1,s2.\n\tdestruct s1 as (P1,a1,B1,BS1,la1,s1).\n\tdestruct s2 as (P2,a2,B2,BS2,la2,s2).\n\tsimpl in la1,la2.\n\trevert B2 BS2 la2 s2.\n\tapply (tr (fun xa=>forall B2 (BS2:forall g p,TypS (B2 g p)) la2\n\t\t(s2:SimpParamItrp G F la (fun g=>typPi (xa_T xa g) (fun p=>typ (BS2 g p))) la2),\n\t\t_ = exSimpParamItrp (la := a :: la) (fun g=>typ (BS2 g (ctxProj (xa_a xa) g)))\n\t\t\t(fun g f=>la2 g f (ctxProj (xa_a xa) g)) (spItrpCons (xa_a xa) BS2 s2))\n\t(atCtxUniq a1 a2)).\n\tsimpl.\n\tclear P2 a2.\n\tintros.\n\tassert (IHlaU := HPropUIP IHla).\n=======\n\tpose (Fn (A:G->Typ) (B:forall g,A g->Typ) g := typPi (A g) (fun a=>B g a)).\n\tassert (IHP := fun A1 A2 B1 B2 la1 la2 s1 s2=>ap (fun s g=>typDom (projT1 s g)) (IHla (Fn A1 B1) (Fn A2 B2) la1 la2 s1 s2)).\n\tsimpl in IHP.\n\tpose (AEta A (g:G) := typ (typSc (A g))).\n\tassert (IHPU : forall A B1 B2 la1 la2 s1 s2,IHP (AEta A) (AEta A) B1 B2 la1 la2 s1 s2 = eq_refl _).\n\t\tclear B1 BS1 la1 s B2 BS2 la2 X.\n\t\tpose (BlasT (A:G->Typ) := {B:_ & {la':_ & SimpParamItrp G F la (Fn A B) la'}}).\n\t\tpose (Blas A B la' s := existT (fun B=>{la':_ & SimpParamItrp G F la (Fn A B) la'}) B (existT (fun la'=>SimpParamItrp G F la (Fn A B) la') la' s)).\n\t\tchange (forall A B la',SimpParamItrp G F la (Fn A B) la'->BlasT A) in (type of Blas).\n\t\tpose (IHP' A1 A2 (Blas1:BlasT A1) (Blas2:BlasT A2) :=\n\t\t\tlet B1 := projT1 Blas1 in\n\t\t\tlet las1 := projT2 Blas1 in\n\t\t\tlet la1 := projT1 las1 in\n\t\t\tlet s1 := projT2 las1 in\n\n\t\t\tlet B2 := projT1 Blas2 in\n\t\t\tlet las2 := projT2 Blas2 in\n\t\t\tlet la2 := projT1 las2 in\n\t\t\tlet s2 := projT2 las2 in\n\n\t\t\tIHP A1 A2 B1 B2 la1 la2 s1 s2).\n\t\tintros.\n\t\tpose (Blas1 := Blas A B1 la1 s1).\n\t\tpose (Blas2 := Blas A B2 la2 s2).\n\t\tchange (IHP' (AEta A) (AEta A) Blas1 Blas2 = eq_refl (AEta A)).\n\t\tset (IHPAA := IHP' (AEta A) (AEta A) Blas1 Blas2).\n\t\tchange (AEta A = AEta A) in (type of IHPAA).\n\t\ttransitivity (eq_trans IHPAA (eq_sym IHPAA)).\n\n\t\tgeneralize (eq_sym IHPAA).\n\t\tintro p.\n\t\tsubst IHPAA.\n\t\trevert B1 B2 la1 la2 s1 s2 Blas1 Blas2.\n\t\trefine (match p as p in _ = A' return forall B1 B2 la1 la2\n\t\t\t(s1:SimpParamItrp G F la (Fn A' B1) la1) (s2:SimpParamItrp G F la (Fn A B2) la2),\n\t\t\t\tlet Blas1 := Blas A' B1 la1 s1 in let Blas2 := Blas A B2 la2 s2 in\n\t\t\tIHP' A' A' Blas1 (tr BlasT p Blas2) = eq_trans (IHP' A' (AEta A) Blas1 Blas2) p\n\t\twith eq_refl => _ end).\n\n\t\trefine (match IHPAA as p return eq_trans p (eq_sym p) = eq_refl (AEta A) with eq_refl => _ end).\n\t\tsimpl.\n\t\treflexivity.\nQed.\nImplicit Arguments spItrpProp [G F la].\n", "meta": {"author": "GallagherCommaJack", "repo": "outrageous-interpreter", "sha": "5556e2aafe45f4efc73c3fb1f58b5d3e833fc617", "save_path": "github-repos/coq/GallagherCommaJack-outrageous-interpreter", "path": "github-repos/coq/GallagherCommaJack-outrageous-interpreter/outrageous-interpreter-5556e2aafe45f4efc73c3fb1f58b5d3e833fc617/Old/TreeItrpHProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22114752338165655}}
{"text": "Require Import MyUtils.\nRequire Export IPPGrammar.\n\nSection IPPGrammarTheorems.\n\nCreate HintDb IPPGrammar.\nHint Resolve CPrio_infix_infix_1 CPrio_infix_infix_2 CPrio_prefix_infix CPrio_infix_prefix CLeft_prefix_infix\n  CRight_infix_prefix CRight_postfix_infix CRight_postfix_infix CPrio_postfix_infix CPrio_postfix_prefix\n  CPrio_infix_postfix CLeft_infix_postfix CPrio_prefix_postfix CLeft_prefix_postfix CRight_postfix_prefix CLeft CRight\n  HMatch InfixMatch PrefixMatch PostfixMatch Atomic_wf Infix_wf Prefix_wf Postfix_wf Atomic_cf Infix_cf Prefix_cf\n  Postfix_cf Atomic_drmcf Infix_drmcf Prefix_drmcf Postfix_drmcf Match_rm InfixMatch_rm PrefixMatch_rm InfixMatch_drm\n  PrefixMatch_drm PostfixMatch_drm Atomic_dlmcf Infix_dlmcf Prefix_dlmcf Postfix_dlmcf Match_lm InfixMatch_lm\n  PostfixMatch_lm InfixMatch_dlm PrefixMatch_dlm PostfixMatch_dlm\n    : IPPGrammar.\n\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* The following lemmas relate to the functions boolean functions that check for conflicts in trees,\n   such as [is_i_conflict_pattern]. *)\n\nLemma is_i_conflict_pattern_true {g} (pr : drules g) q :\n  i_conflict_pattern pr q <-> is_i_conflict_pattern pr q = true.\nProof.\n  split; intro.\n  - inv H; simpl; auto using decide_True, decide_False.\n    + destruct (decide (prio pr (InfixProd o1) (InfixProd o2))); auto using decide_True, decide_False.\n    + destruct (decide (prio pr (InfixProd o1) (InfixProd o2))); auto using decide_True, decide_False.\n    + destruct (decide (prio pr (PrefixProd o1) (InfixProd o2))); auto using decide_True, decide_False.\n    + destruct (decide (prio pr (PostfixProd o1) (InfixProd o2))); auto using decide_True, decide_False.\n  - destruct q; inv H.\n    + destruct q1, q2; inv H1.\n      * destruct q2_1, q2_2; inv H0.\n        destruct (decide (prio pr (InfixProd o) (InfixProd o0))); eauto with IPPGrammar.\n        destruct (decide (left_a pr (InfixProd o) (InfixProd o0))); eauto with IPPGrammar.\n        inv H1.\n      * destruct q1_1, q1_2; inv H0.\n        destruct (decide (prio pr (InfixProd o) (InfixProd o0))); eauto with IPPGrammar.\n        destruct (decide (right_a pr (InfixProd o) (InfixProd o0))); eauto with IPPGrammar.\n        inv H1.\n      * destruct q1_1, q1_2; inv H0.\n      * destruct q1_1, q1_2; inv H0.\n      * destruct q1_1, q1_2; inv H0.\n    + destruct q; inv H1.\n      destruct q1, q2; inv H0.\n      destruct (decide (prio pr (PrefixProd o) (InfixProd o0))); eauto with IPPGrammar.\n      destruct (decide (left_a pr (PrefixProd o) (InfixProd o0))); eauto with IPPGrammar.\n      inv H1.\n    + destruct q; inv H1.\n      destruct q1, q2; inv H0.\n      destruct (decide (prio pr (PostfixProd o) (InfixProd o0))); eauto with IPPGrammar.\n      destruct (decide (right_a pr (PostfixProd o) (InfixProd o0))); eauto with IPPGrammar.\n      inv H1.\nQed.\n\nLemma is_i_conflict_pattern_false {g} (pr : drules g) q :\n  ~ i_conflict_pattern pr q <-> is_i_conflict_pattern pr q = false.\nProof.\n  split; intro.\n  - destruct (is_i_conflict_pattern pr q) eqn:E; auto.\n    exfalso. destruct H. apply is_i_conflict_pattern_true. assumption.\n  - intro. apply is_i_conflict_pattern_true in H0. rewrite H in H0. inv H0.\nQed.\n\nLemma is_lm_conflict_pattern_true {g} (pr : drules g) q :\n  lm_conflict_pattern pr q <-> is_lm_conflict_pattern pr q = true.\nProof.\n  split; intro.\n  - inv H; simpl; auto using decide_True, decide_False.\n    + destruct (decide (prio pr (InfixProd o1) (PostfixProd o2))); auto using decide_True, decide_False.\n    + destruct (decide (prio pr (PrefixProd o1) (PostfixProd o2))); auto using decide_True, decide_False.\n  - destruct q; inv H.\n    + destruct q1, q2; inv H1.\n      destruct q2; inv H0.\n      destruct (decide (prio pr (InfixProd o) (PostfixProd o0))); eauto with IPPGrammar.\n      destruct (decide (left_a pr (InfixProd o) (PostfixProd o0))); eauto with IPPGrammar.\n      inv H1.\n    + destruct q; inv H1.\n      destruct q; inv H0.\n      destruct (decide (prio pr (PrefixProd o) (PostfixProd o0))); eauto with IPPGrammar.\n      destruct (decide (left_a pr (PrefixProd o) (PostfixProd o0))); eauto with IPPGrammar.\n      inv H1.\nQed.\n\nLemma is_lm_conflict_pattern_false {g} (pr : drules g) q :\n  ~ lm_conflict_pattern pr q <-> is_lm_conflict_pattern pr q = false.\nProof.\n  split; intro.\n  - destruct (is_lm_conflict_pattern pr q) eqn:E; auto.\n    exfalso. destruct H. apply is_lm_conflict_pattern_true. assumption.\n  - intro. apply is_lm_conflict_pattern_true in H0. rewrite H in H0. inv H0.\nQed.\n\nLemma has_infix_lm_conflicts_true {g} (pr : drules g) o t2 :\n  has_infix_lm_conflicts pr o t2 = true <->\n  exists x, lm_conflict_pattern pr (CR_infix_postfix o x) /\\ matches_lm t2 (PostfixPatt HPatt x).\nProof.\n  induction t2; split; intros.\n  - inv H.\n  - inv H. inv H0. inv H1. inv H0.\n  - apply IHt2_1 in H. inv H. inv H0. eauto with IPPGrammar.\n  - simpl. inv H. inv H0.\n    inv H1. \n    + inv H0.\n    + apply IHt2_1. eauto with IPPGrammar.\n  - inv H.\n  - inv H. inv H0. inv H1. inv H0.\n  - cbn [has_infix_lm_conflicts] in H.\n    destruct (is_lm_conflict_pattern pr (CR_infix_postfix o o0)) eqn:E.\n    + apply is_lm_conflict_pattern_true in E. eauto with IPPGrammar.\n    + apply IHt2 in H. inv H. inv H0. eauto with IPPGrammar.\n  - inv H. inv H0. cbn [has_infix_lm_conflicts].\n    destruct (is_lm_conflict_pattern pr (CR_infix_postfix o o0)) eqn:E; auto.\n    inv H1.\n    + inv H0. apply is_lm_conflict_pattern_true in H. rewrite H in E. inv E.\n    + rewrite IHt2. eauto with IPPGrammar.\nQed.\n\nLemma has_infix_lm_conflicts_false {g} (pr : drules g) o t2 :\n  has_infix_lm_conflicts pr o t2 = false <->\n  (forall x, matches_lm t2 (PostfixPatt HPatt x) -> ~ lm_conflict_pattern pr (CR_infix_postfix o x)).\nProof.\n  split; intros.\n  - intro. assert (has_infix_lm_conflicts pr o t2 = true). { apply has_infix_lm_conflicts_true. eauto. }\n    rewrite H in H2. inv H2.\n  - destruct (has_infix_lm_conflicts pr o t2) eqn:E; auto.\n    apply has_infix_lm_conflicts_true in E. inv E. inv H0. exfalso. eapply H; eauto.\nQed.\n\nLemma has_prefix_lm_conflicts_true {g} (pr : drules g) o t2 :\n  has_prefix_lm_conflicts pr o t2 = true <->\n  exists x, lm_conflict_pattern pr (CR_prefix_postfix o x) /\\ matches_lm t2 (PostfixPatt HPatt x).\nProof.\n  induction t2; split; intros.\n  - inv H.\n  - inv H. inv H0. inv H1. inv H0.\n  - apply IHt2_1 in H. inv H. inv H0. eauto with IPPGrammar.\n  - simpl. inv H. inv H0.\n    inv H1. \n    + inv H0.\n    + apply IHt2_1. eauto with IPPGrammar.\n  - inv H.\n  - inv H. inv H0. inv H1. inv H0.\n  - cbn [has_prefix_lm_conflicts] in H.\n    destruct (is_lm_conflict_pattern pr (CR_prefix_postfix o o0)) eqn:E.\n    + apply is_lm_conflict_pattern_true in E. eauto with IPPGrammar.\n    + apply IHt2 in H. inv H. inv H0. eauto with IPPGrammar.\n  - inv H. inv H0. cbn [has_prefix_lm_conflicts].\n    destruct (is_lm_conflict_pattern pr (CR_prefix_postfix o o0)) eqn:E; auto.\n    inv H1.\n    + inv H0. apply is_lm_conflict_pattern_true in H. rewrite H in E. inv E.\n    + rewrite IHt2. eauto with IPPGrammar.\nQed.\n\nLemma has_prefix_lm_conflicts_false {g} (pr : drules g) o t2 :\n  has_prefix_lm_conflicts pr o t2 = false <->\n  (forall x, matches_lm t2 (PostfixPatt HPatt x) -> ~ lm_conflict_pattern pr (CR_prefix_postfix o x)).\nProof.\n  split; intros.\n  - intro. assert (has_prefix_lm_conflicts pr o t2 = true). { apply has_prefix_lm_conflicts_true. eauto. }\n    rewrite H in H2. inv H2.\n  - destruct (has_prefix_lm_conflicts pr o t2) eqn:E; auto.\n    apply has_prefix_lm_conflicts_true in E. inv E. inv H0. exfalso. eapply H; eauto.\nQed.\n\nLemma has_postfix_rm_conflicts_true {g} (pr : drules g) t1 o :\n  has_postfix_rm_conflicts pr t1 o = true <->\n  exists x, rm_conflict_pattern pr (CL_postfix_prefix o x) /\\ matches_rm t1 (PrefixPatt x HPatt).\nProof.\n  induction t1; split; intros.\n  - inv H.\n  - inv H. inv H0. inv H1. inv H0.\n  - simpl in H. apply IHt1_2 in H. inv H. inv H0. eauto with IPPGrammar.\n  - simpl. inv H. inv H0.\n    inv H1.\n    + inv H0.\n    + apply IHt1_2. eauto with IPPGrammar.\n  - simpl in H. destruct (decide (prio pr (PostfixProd o) (PrefixProd o0))).\n    + eexists. eauto with IPPGrammar.\n    + destruct (decide (right_a pr (PostfixProd o) (PrefixProd o0))).\n      * eexists. eauto with IPPGrammar.\n      * apply IHt1 in H. inv H. inv H0. eexists. eauto with IPPGrammar.\n  - simpl. destruct (decide (prio pr (PostfixProd o) (PrefixProd o0))),\n             (decide (right_a pr (PostfixProd o) (PrefixProd o0))); auto.\n    inv H. inv H0.\n    inv H1.\n    + inv H0. exfalso. inv H; auto.\n    + apply IHt1. eexists. eauto.\n  - inv H.\n  - inv H. inv H0. inv H1. inv H0.\nQed.\n\nLemma has_postfix_rm_conflicts_false {g} (pr : drules g) t1 o :\n  has_postfix_rm_conflicts pr t1 o = false <->\n  (forall x, matches_rm t1 (PrefixPatt x HPatt) -> ~ rm_conflict_pattern pr (CL_postfix_prefix o x)).\nProof.\n  split; intros.\n  - intro. assert (has_postfix_rm_conflicts pr t1 o = true). { apply has_postfix_rm_conflicts_true. eauto. }\n    rewrite H in H2. inv H2.\n  - destruct (has_postfix_rm_conflicts pr t1 o) eqn:E; auto.\n    apply has_postfix_rm_conflicts_true in E. inv E. inv H0. edestruct H; eauto.\nQed.\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* The following lemmas relate safety to relations between conflict patterns. *)\n\nLemma safe_infix_infix {g} (pr : drules g) o1 o2 :\n  safe_pr pr ->\n  i_conflict_pattern pr (CL_infix_infix o1 o2) ->\n  i_conflict_pattern pr (CR_infix_infix o2 o1) ->\n  False.\nProof.\n  intros H_safe H_CL H_CR. unfold safe_pr in H_safe. inv H_CL; inv H_CR; eauto.\nQed.\n\nLemma safe_infix_prefix {g} (pr : drules g) o1 o2 :\n  safe_pr pr ->\n  rm_conflict_pattern pr (CL_infix_prefix o1 o2) ->\n  i_conflict_pattern pr (CR_prefix_infix o2 o1) ->\n  False.\nProof.\n  intros. unfold safe_pr in H. inv H0; inv H1; eauto.\nQed.\n\nLemma safe_infix_postfix {g} (pr : drules g) o1 o2 :\n  safe_pr pr ->\n  lm_conflict_pattern pr (CR_infix_postfix o1 o2) ->\n  i_conflict_pattern pr (CL_postfix_infix o2 o1) ->\n  False.\nProof.\n  intros. unfold safe_pr in H. inv H0; inv H1; eauto.\nQed.\n\nLemma safe_prefix_postfix {g} (pr : drules g) o1 o2 :\n  safe_pr pr ->\n  lm_conflict_pattern pr (CR_prefix_postfix o1 o2) ->\n  rm_conflict_pattern pr (CL_postfix_prefix o2 o1) ->\n  False.\nProof.\n  intros. unfold safe_pr in H. inv H0; inv H1; eauto.\nQed.\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* Helper tactics for simplifying specific repair terms. *)\n\n(* Simplifies the term [insert_in pr t1 o (InfixNode t21 o2 t22)] *)\nLtac insert_in_inode_destruct pr o t21 o2 t22 :=\n    cbn [insert_in] in *;\n    destruct (is_i_conflict_pattern pr (CR_infix_infix o o2)) eqn:E;\n    [ apply is_i_conflict_pattern_true in E |\n      apply is_i_conflict_pattern_false in E;\n      destruct (has_infix_lm_conflicts pr o (InfixNode t21 o2 t22)) eqn:E2;\n      [ apply has_infix_lm_conflicts_true in E2 |\n        assert (forall x, matches_lm (InfixNode t21 o2 t22) (PostfixPatt HPatt x) ->\n              ~ lm_conflict_pattern pr (CR_infix_postfix o x));\n        [apply has_infix_lm_conflicts_false; assumption|]\n      ]\n    ].\n\n(* Simplifies the term [insert_in pr t1 o (PostfixNode t21 o2)] *)\nLtac insert_in_pnode_destruct pr o t21 o2 :=\n    cbn [insert_in] in *;\n     destruct (has_infix_lm_conflicts pr o (PostfixNode t21 o2)) eqn:E;\n     [apply has_infix_lm_conflicts_true in E |\n      assert (forall x, matches_lm (PostfixNode t21 o2) (PostfixPatt HPatt x) ->\n              ~ lm_conflict_pattern pr (CR_infix_postfix o x));\n      [apply has_infix_lm_conflicts_false; assumption|]\n    ].\n\n(* Simplifies the term [insert_pre pr o (InfixNode t21 o2 t22)] *)\nLtac insert_pre_inode_destruct pr o t21 o2 t22 :=\n    cbn [insert_pre] in *;\n    destruct (is_i_conflict_pattern pr (CR_prefix_infix o o2)) eqn:E;\n    [ apply is_i_conflict_pattern_true in E |\n      apply is_i_conflict_pattern_false in E;\n      destruct (has_prefix_lm_conflicts pr o (InfixNode t21 o2 t22)) eqn:E2;\n      [ apply has_prefix_lm_conflicts_true in E2 |\n        assert (forall x, matches_lm (InfixNode t21 o2 t22) (PostfixPatt HPatt x) ->\n              ~ lm_conflict_pattern pr (CR_prefix_postfix o x));\n        [apply has_prefix_lm_conflicts_false; assumption|]\n      ]\n    ].\n\n(* Simplifies the term [insert_pre pr o (PostfixNode t21 o2)] *)\nLtac insert_pre_pnode_destruct pr o t21 o2 :=\n    cbn [insert_pre] in *;\n     destruct (has_prefix_lm_conflicts pr o (PostfixNode t21 o2)) eqn:E;\n     [apply has_prefix_lm_conflicts_true in E |\n      assert (forall x, matches_lm (PostfixNode t21 o2) (PostfixPatt HPatt x) ->\n              ~ lm_conflict_pattern pr (CR_prefix_postfix o x));\n      [apply has_prefix_lm_conflicts_false; assumption|]\n    ].\n\n(* Simplifies the term [insert_post pr (InfixNode t11 o1 t12) o] *)\nLtac insert_post_inode_destruct pr t11 o1 t12 o :=\n    cbn [insert_post] in *;\n    destruct (is_i_conflict_pattern pr (CL_postfix_infix o o1)) eqn:E;\n    [ apply is_i_conflict_pattern_true in E |\n      apply is_i_conflict_pattern_false in E;\n      destruct (has_postfix_rm_conflicts pr (InfixNode t11 o1 t12) o) eqn:E2;\n      [ apply has_postfix_rm_conflicts_true in E2 |\n        assert (forall x, matches_rm (InfixNode t11 o1 t12) (PrefixPatt x HPatt) ->\n              ~ rm_conflict_pattern pr (CL_postfix_prefix o x));\n        [apply has_postfix_rm_conflicts_false; assumption|]\n      ]\n    ].\n\n(* Simplifies the term [insert_post pr (PrefixNode o1 t12) o] *)\nLtac insert_post_pnode_destruct pr o1 t12 o :=\n    cbn [insert_post] in *;\n    destruct (has_postfix_rm_conflicts pr (PrefixNode o1 t12) o) eqn:E;\n    [ apply has_postfix_rm_conflicts_true in E |\n      assert (forall x, matches_rm (PrefixNode o1 t12) (PrefixPatt x HPatt) ->\n            ~ rm_conflict_pattern pr (CL_postfix_prefix o x));\n      [apply has_postfix_rm_conflicts_false; assumption|]\n    ].\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* Lemmas that show well-formedness of [repair] *)\n\nLemma insert_in_wf {g} (pr : drules g) t1 o t2 :\n  wf_parse_tree g t1 -> wf_parse_tree g t2 -> g.(prods) (InfixProd (inl o)) ->\n  wf_parse_tree g (insert_in pr t1 (inl o) t2).\nProof.\n  intros. induction t2.\n  - simpl. auto with IPPGrammar.\n  - inv H0.\n    insert_in_inode_destruct pr (@inl (OPinpre g) (OPpost g) o) t2_1 (@inl (OPinpre g) (OPpost g) o1) t2_2;\n    auto with IPPGrammar.\n  - simpl. inv H0. auto with IPPGrammar.\n  - inv H0.\n    insert_in_pnode_destruct pr (@inl (OPinpre g) (OPpost g) o) t2 (@inr (OPinpre g) (OPpost g) o1);\n    auto with IPPGrammar.\nQed.\n\nLemma insert_pre_wf {g} (pr : drules g) o t2 :\n  wf_parse_tree g t2 -> g.(prods) (PrefixProd (inl o)) ->\n  wf_parse_tree g (insert_pre pr (inl o) t2).\nProof.\n  intros. induction H; eauto with IPPGrammar.\n  - insert_pre_inode_destruct pr (@inl (OPinpre g) (OPpost g) o) t1 (@inl (OPinpre g) (OPpost g) o0) t2;\n    auto with IPPGrammar.\n  - insert_pre_pnode_destruct pr (@inl (OPinpre g) (OPpost g) o) t (@inr (OPinpre g) (OPpost g) o0);\n    auto with IPPGrammar.\nQed.\n\nLemma repair_in_wf {g} (pr : drules g) t1 o t2 :\n  wf_parse_tree g t1 -> wf_parse_tree g t2 -> g.(prods) (InfixProd (inl o)) ->\n  wf_parse_tree g (repair_in pr t1 (inl o) t2).\nProof.\n  intro. revert o t2. induction H; intros; simpl; auto using insert_in_wf, insert_pre_wf with IPPGrammar.\nQed.\n\nLemma insert_post_wf {g} (pr : drules g) t1 o :\n  wf_parse_tree g t1 -> g.(prods) (PostfixProd (inr o)) ->\n  wf_parse_tree g (insert_post pr t1 (inr o)).\nProof.\n  intros. induction H; eauto with IPPGrammar.\n  - insert_post_inode_destruct pr t1 (@inl (OPinpre g) (OPpost g) o0) t2 (@inr (OPinpre g) (OPpost g) o);\n    auto with IPPGrammar.\n  - insert_post_pnode_destruct pr (@inl (OPinpre g) (OPpost g) o0) t (@inr (OPinpre g) (OPpost g) o);\n    auto with IPPGrammar.\nQed.\n\nLemma repair_wf {g} (pr : drules g) t :\n  wf_parse_tree g t ->\n  wf_parse_tree g (repair pr t).\nProof.\n  intro. induction H; simpl; auto using repair_in_wf, insert_pre_wf, insert_post_wf with IPPGrammar.\nQed.\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* Lemmas that show yield-preservation of [repair] *)\n\nLemma insert_pre_yield_preserve {g} (pr : drules g) o t2 :\n  yield (insert_pre pr o t2) = inr o :: yield t2.\nProof.\n  induction t2; try reflexivity.\n  - insert_pre_inode_destruct pr o t2_1 o0 t2_2; auto; simpl; rewrite IHt2_1; auto.\n  - insert_pre_pnode_destruct pr o t2 o0; simpl; auto. rewrite IHt2. reflexivity.\nQed.\n\nLemma insert_in_yield_preserve {g} (pr : drules g) t1 o t2 :\n  yield (insert_in pr t1 o t2) = yield t1 ++ inr o :: yield t2.\nProof.\n  induction t2; try reflexivity.\n  - insert_in_inode_destruct pr o t2_1 o0 t2_2; simpl; auto.\n    + rewrite IHt2_1. simplify_list_eq. reflexivity.\n    + rewrite IHt2_1. simplify_list_eq. reflexivity.\n  - insert_in_pnode_destruct pr o t2 o0; simpl; auto. rewrite IHt2. simplify_list_eq. reflexivity.\nQed.\n\nLemma repair_in_yield_preserve {g} (pr : drules g) t1 o t2 :\n  yield (repair_in pr t1 o t2) = yield t1 ++ inr o :: yield t2.\nProof.\n  revert o t2. induction t1; intros.\n  - simpl. rewrite insert_in_yield_preserve. reflexivity.\n  - simplify_list_eq. rewrite <- IHt1_2. rewrite <- IHt1_1. reflexivity.\n  - simpl. rewrite <- IHt1. rewrite insert_pre_yield_preserve. reflexivity.\n  - simpl. rewrite insert_in_yield_preserve. reflexivity.\nQed.\n\nLemma insert_post_yield_preserve {g} (pr : drules g) t1 o :\n  yield (insert_post pr t1 o) = yield t1 ++ [inr o].\nProof.\n  induction t1; try reflexivity.\n  - insert_post_inode_destruct pr t1_1 o0 t1_2 o; auto; simplify_list_eq; rewrite IHt1_2; auto.\n  - insert_post_pnode_destruct pr o0 t1 o; auto; simplify_list_eq; rewrite IHt1; auto.\nQed.\n\nLemma repair_yield_preserve {g} (pr : drules g) t :\n  yield (repair pr t) = yield t.\nProof.\n  induction t; auto; simpl.\n  - rewrite repair_in_yield_preserve. rewrite IHt1. rewrite IHt2. reflexivity.\n  - rewrite insert_pre_yield_preserve. rewrite IHt. reflexivity.\n  - rewrite insert_post_yield_preserve. rewrite IHt. reflexivity.\nQed.\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* Auxiliary lemmas and tactics that help proving safety. *)\n\nLemma i_conflict_pattern_cases {g} (pr : drules g) q :\n  i_conflict_pattern pr q -> exists o1 o2,\n  q = CR_infix_infix o1 o2 \\/ q = CL_infix_infix o1 o2 \\/ q = CR_prefix_infix o1 o2 \\/ q = CL_postfix_infix o1 o2.\nProof.\n  intros. inv H; eauto 7.\nQed.\n\nLtac icp_cases H :=\n  apply i_conflict_pattern_cases in H as T; destruct T as [? T1]; destruct T1 as [? T2]; destruct T2 as [T5|T3];\n  [|destruct T3 as [T5|T4]; [|destruct T4 as [T5|T5]]]; rewrite T5 in *; clear T5.\n\nLemma rm_conflict_pattern_cases {g} (pr : drules g) q :\n  rm_conflict_pattern pr q -> exists o1 o2,\n  q = CL_infix_prefix o1 o2 \\/ q = CL_postfix_prefix o1 o2.\nProof.\n  intros. inv H; eauto.\nQed.\n\nLtac rcp_cases H :=\n  apply rm_conflict_pattern_cases in H as T; destruct T as [? T1]; destruct T1 as [? T2]; destruct T2; subst.\n\nLemma lm_conflict_pattern_cases {g} (pr : drules g) q :\n  lm_conflict_pattern pr q -> exists o1 o2,\n  q = CR_infix_postfix o1 o2 \\/ q = CR_prefix_postfix o1 o2.\nProof.\n  intros. inv H; eauto.\nQed.\n\nLtac lcp_cases H :=\n  apply lm_conflict_pattern_cases in H as T; destruct T as [? T1]; destruct T1 as [? T2]; destruct T2; subst.\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* Proving safety of shallow conflict patterns (i_conflict_patterns). *)\n\nLemma insert_in_top {g} (pr : drules g) t1 o t2 :\n  matches (insert_in pr t1 o t2) (InfixPatt HPatt o HPatt) \\/\n  (exists o2, matches t2 (InfixPatt HPatt o2 HPatt) /\\ matches (insert_in pr t1 o t2) (InfixPatt HPatt o2 HPatt)) \\/\n  (exists o2, matches t2 (PostfixPatt HPatt o2) /\\ matches (insert_in pr t1 o t2) (PostfixPatt HPatt o2)).\nProof.\n  destruct t2; eauto 6 with IPPGrammar.\n  - insert_in_inode_destruct pr o t2_1 o0 t2_2; eauto 7 with IPPGrammar.\n  - insert_in_pnode_destruct pr o t2 o0; eauto 7 with IPPGrammar.\nQed.\n\nLemma insert_in_top_unchanged {g} (pr : drules g) t1 o t2 x :\n  matches_lm t2 (PostfixPatt HPatt x) ->\n  lm_conflict_pattern pr (CR_infix_postfix o x) ->\n  (exists o2, matches t2 (InfixPatt HPatt o2 HPatt) /\\ matches (insert_in pr t1 o t2) (InfixPatt HPatt o2 HPatt)) \\/\n  (exists o2, matches t2 (PostfixPatt HPatt o2) /\\ matches (insert_in pr t1 o t2) (PostfixPatt HPatt o2)).\nProof.\n  intros. destruct t2.\n  - inv H. inv H1.\n  - inv H. inv H1. left.\n    eexists. split; auto with IPPGrammar.\n    insert_in_inode_destruct pr o t2_1 o0 t2_2; auto with IPPGrammar. exfalso. apply H with x; auto with IPPGrammar.\n  - inv H. inv H1.\n  - right. eexists. split; auto with IPPGrammar.\n    insert_in_pnode_destruct pr o t2 o0; auto with IPPGrammar. exfalso. apply H1 with x; auto.\nQed.\n\nLemma insert_in_icfree {g} (pr : drules g) t1 o t2 :\n  safe_pr pr ->\n  i_conflict_free (i_conflict_pattern pr) t1 ->\n  i_conflict_free (i_conflict_pattern pr) t2 ->\n  (forall o1, i_conflict_pattern pr (CL_infix_infix o o1) -> ~ matches t1 (InfixPatt HPatt o1 HPatt)) ->\n  i_conflict_free (i_conflict_pattern pr) (insert_in pr t1 o t2).\nProof.\n  intros. induction t2 as [l2|t21 ? o2 t22|o2 t22|t21 ? o2].\n  - simpl. apply Infix_cf; auto. intro. inv H3. inv H4. icp_cases H3; inv H5. inv H12. eapply H2; eauto.\n  - insert_in_inode_destruct pr o t21 o2 t22.\n    + inv H1. apply Infix_cf; auto. intro. inv H1. inv H3. icp_cases H1; inv H4.\n      * destruct H6. eexists. eauto with IPPGrammar.\n      * inv H9. decompose [or] (insert_in_top pr t1 o t21); rewrite <- H3 in *.\n        **inv H4. eauto using safe_infix_infix.\n        **inv H5. inv H4. inv H9. destruct H6. eexists. eauto with IPPGrammar.\n        **inv H5. inv H4. inv H9.\n    + inv H1. apply Infix_cf; auto with IPPGrammar. intro. inv H1. inv H3. icp_cases H1; inv H4.\n      * destruct H6. eexists. eauto with IPPGrammar.\n      * inv E2. inv H3. inv H5. inv H3.\n        inv H9. apply insert_in_top_unchanged with pr t1 o t21 x2 in H13; auto. destruct H13; rewrite <- H3 in *.\n        **inv H5. inv H9. inv H10. destruct H6. eexists. eauto with IPPGrammar.\n        **inv H5. inv H9. inv H10.\n    + apply Infix_cf; auto. intro. inv H4. inv H5. icp_cases H4; inv H6.\n      * inv H13. contradiction.\n      * inv H8. apply H2 with x1; auto with IPPGrammar.\n  - simpl. apply Infix_cf; auto with IPPGrammar. intro. inv H3. inv H4. icp_cases H3; inv H5. inv H12. inv H1.\n    eapply H2; eauto with IPPGrammar.\n  - insert_in_pnode_destruct pr o t21 o2.\n    + inv H1. apply Postfix_cf; auto with IPPGrammar. intro. inv H1. inv H3. icp_cases H1; inv H4. inv H7. inv E.\n      inv H4. inv H8.\n      * inv H4. decompose [or] (insert_in_top pr t1 o t21); rewrite <- H3 in *.\n        **inv H4. eauto using safe_infix_postfix.\n        **inv H8. inv H4. inv H12. destruct H5. eexists. eauto with IPPGrammar.\n        **inv H8. inv H4. inv H12.\n      * apply insert_in_top_unchanged with pr t1 o t21 x2 in H13; auto. destruct H13; auto; rewrite <- H3 in *.\n        **inv H4. inv H8. inv H10. destruct H5. eexists. eauto with IPPGrammar.\n        **inv H4. inv H8. inv H10.\n    + apply Infix_cf; auto with IPPGrammar. intro. inv H4. inv H5. icp_cases H4; inv H6. inv H13. inv H8.\n      eapply H2; eauto with IPPGrammar.\nQed.\n\nLemma insert_pre_top {g} (pr : drules g) o t2 :\n  matches (insert_pre pr o t2) (PrefixPatt o HPatt) \\/\n  (exists o2, matches t2 (InfixPatt HPatt o2 HPatt) /\\ matches (insert_pre pr o t2) (InfixPatt HPatt o2 HPatt)) \\/\n  (exists o2, matches t2 (PostfixPatt HPatt o2) /\\ matches (insert_pre pr o t2) (PostfixPatt HPatt o2)).\nProof.\n  destruct t2; eauto with IPPGrammar.\n  - insert_pre_inode_destruct pr o t2_1 o0 t2_2; eauto 7 with IPPGrammar.\n  - insert_pre_pnode_destruct pr o t2 o0; eauto 7 with IPPGrammar.\nQed.\n\nLemma insert_pre_top_unchanged {g} (pr : drules g) o t2 x :\n  matches_lm t2 (PostfixPatt HPatt x) ->\n  lm_conflict_pattern pr (CR_prefix_postfix o x) ->\n  (exists o2, matches t2 (InfixPatt HPatt o2 HPatt) /\\ matches (insert_pre pr o t2) (InfixPatt HPatt o2 HPatt)) \\/\n  (exists o2, matches t2 (PostfixPatt HPatt o2) /\\ matches (insert_pre pr o t2) (PostfixPatt HPatt o2)).\nProof.\n  intros. destruct t2.\n  - inv H. inv H1.\n  - inv H. inv H1. left.\n    eexists. split; auto with IPPGrammar.\n    insert_pre_inode_destruct pr o t2_1 o0 t2_2; auto with IPPGrammar. exfalso. apply H with x; auto with IPPGrammar.\n  - inv H. inv H1.\n  - right. eexists. split; auto with IPPGrammar.\n    insert_pre_pnode_destruct pr o t2 o0; auto with IPPGrammar. exfalso. apply H1 with x; auto.\nQed.\n\nLemma insert_pre_icfree {g} (pr : drules g) o t2 :\n  safe_pr pr ->\n  i_conflict_free (i_conflict_pattern pr) t2 ->\n  i_conflict_free (i_conflict_pattern pr) (insert_pre pr o t2).\nProof.\n  intros. induction t2 as [l2|t21 ? o2 t22|o2 t22|t21 ? o2].\n  - simpl. apply Prefix_cf; auto. intro. inv H1. inv H2. icp_cases H1; inv H3. inv H4.\n  - insert_pre_inode_destruct pr o t21 o2 t22.\n    + inv H0. apply Infix_cf; auto. intro. inv H0. inv H1. icp_cases H0; inv H2.\n      * inv H12. destruct H4. eexists. eauto with IPPGrammar.\n      * decompose [or] (insert_pre_top pr o t21).\n        **inv H7. rewrite <- H2 in *. inv H1.\n        **inv H2. inv H1. inv H7. rewrite <- H1 in *. inv H3. destruct H4. eexists. eauto with IPPGrammar.\n        **inv H2. inv H1. inv H7. rewrite <- H1 in *. inv H3.\n    + inv H0. apply Infix_cf; auto. intro. inv H0. inv H1. inv E2. inv H1. inv H7. inv H1. icp_cases H0; inv H2.\n      * destruct H4. eexists. eauto with IPPGrammar.\n      * apply insert_pre_top_unchanged with pr o t21 x0 in H11; auto. destruct H11.\n        **inv H1. inv H2. inv H8. rewrite <- H2 in *. inv H7. destruct H4. eexists. eauto with IPPGrammar.\n        **inv H1. inv H2. inv H8. rewrite <- H2 in *. inv H7.\n    + apply Prefix_cf; auto. intro. inv H2. inv H3. icp_cases H2; inv H4. inv H5. contradiction.\n  - simpl. apply Prefix_cf; auto. intro. inv H1. inv H2. icp_cases H1; inv H3. inv H4.\n  - insert_pre_pnode_destruct pr o t21 o2.\n    + inv H0. apply Postfix_cf; auto. inv E. inv H0. intro. inv H0. inv H5. icp_cases H0; inv H6. inv H7. inv H2.\n      * inv H6. decompose [or] (insert_pre_top pr o t21); rewrite <- H5 in *.\n        ** inv H2.\n        ** inv H6. inv H2. inv H8. destruct H3. eexists. eauto with IPPGrammar.\n        ** inv H6. inv H2. inv H8.\n      * apply insert_pre_top_unchanged with pr o t21 x in H10; auto.\n        destruct H10; rewrite <- H5 in *.\n        ** inv H2. inv H6. inv H7. destruct H3. eexists. eauto with IPPGrammar.\n        ** inv H2. inv H6. inv H7.\n    + apply Prefix_cf; auto.\n      intro. inv H2. inv H3. icp_cases H2; inv H4. inv H5.\nQed.\n\nLemma repair_in_icfree {g} (pr : drules g) t1 o t2 :\n  safe_pr pr ->\n  i_conflict_free (i_conflict_pattern pr) t1 ->\n  i_conflict_free (i_conflict_pattern pr) t2 ->\n  i_conflict_free (i_conflict_pattern pr) (repair_in pr t1 o t2).\nProof.\n  intro. revert o t2. induction t1 as [l1|t11 ? o1 t12|o1 t12|t11 ? o1]; intros; simpl.\n  - apply insert_in_icfree; auto with IPPGrammar. intros. intro. inv H3.\n  - inv H0. auto.\n  - inv H0. apply insert_pre_icfree; auto.\n  - apply insert_in_icfree; auto with IPPGrammar. intros. intro. inv H3. \nQed.\n\nLemma insert_post_top {g} (pr : drules g) t1 o :\n  matches (insert_post pr t1 o) (PostfixPatt HPatt o) \\/\n  (exists o1, matches t1 (InfixPatt HPatt o1 HPatt) /\\ matches (insert_post pr t1 o) (InfixPatt HPatt o1 HPatt)) \\/\n  (exists o1, matches t1 (PrefixPatt o1 HPatt) /\\ matches (insert_post pr t1 o) (PrefixPatt o1 HPatt)).\nProof.\n  destruct t1; eauto with IPPGrammar.\n  - insert_post_inode_destruct pr t1_1 o0 t1_2 o; eauto 7 with IPPGrammar.\n  - insert_post_pnode_destruct pr o0 t1 o; eauto 7 with IPPGrammar.\nQed.\n\nLemma insert_post_top_unchanged {g} (pr : drules g) t1 o x :\n  matches_rm t1 (PrefixPatt x HPatt) ->\n  rm_conflict_pattern pr (CL_postfix_prefix o x) ->\n  (exists o1, matches t1 (InfixPatt HPatt o1 HPatt) /\\ matches (insert_post pr t1 o) (InfixPatt HPatt o1 HPatt)) \\/\n  (exists o1, matches t1 (PrefixPatt o1 HPatt) /\\ matches (insert_post pr t1 o) (PrefixPatt o1 HPatt)).\nProof.\n  intros. destruct t1.\n  - inv H. inv H1.\n  - inv H. inv H1. left.\n    eexists. split; auto with IPPGrammar.\n    insert_post_inode_destruct pr t1_1 o0 t1_2 o; auto with IPPGrammar. exfalso. apply H with x; auto with IPPGrammar.\n  - right. eexists. split; auto with IPPGrammar.\n    insert_post_pnode_destruct pr o0 t1 o; auto with IPPGrammar. exfalso. apply H1 with x; auto.\n  - inv H. inv H1.\nQed.\n\nLemma insert_post_icfree {g} (pr : drules g) t1 o :\n  safe_pr pr ->\n  i_conflict_free (i_conflict_pattern pr) t1 ->\n  i_conflict_free (i_conflict_pattern pr) (insert_post pr t1 o).\nProof.\n  intros. induction t1 as [l1|t11 ? o1 t12|o1 t12|t11 ? o1].\n  - simpl. apply Postfix_cf; auto. intro. inv H1. inv H2. icp_cases H1; inv H3. inv H4.\n  - insert_post_inode_destruct pr t11 o1 t12 o.\n    + inv H0. apply Infix_cf; auto. intro. inv H0. inv H1. icp_cases H0; inv H2.\n      * decompose [or] (insert_post_top pr t12 o).\n        **inv H12. rewrite <- H2 in *. inv H1.\n        **inv H2. inv H1. inv H12. rewrite <- H1 in *. inv H3. destruct H4. eexists. eauto with IPPGrammar.\n        **inv H2. inv H1. inv H12. rewrite <- H1 in *. inv H3.\n      * inv H12. destruct H4. eexists. eauto with IPPGrammar.\n    + inv H0. apply Infix_cf; auto. intro. inv H0. inv H1. inv E2. inv H1. inv H7. inv H1. icp_cases H0; inv H2.\n      * apply insert_post_top_unchanged with pr t12 o x0 in H11; auto. destruct H11.\n        **inv H1. inv H2. inv H7. rewrite <- H2 in *. inv H14. destruct H4. eexists. eauto with IPPGrammar.\n        **inv H1. inv H2. inv H7. rewrite <- H2 in *. inv H14.\n      * destruct H4. eexists. eauto with IPPGrammar.\n    + apply Postfix_cf; auto. intro. inv H2. inv H3. icp_cases H2; inv H4. inv H5. contradiction.\n  - insert_post_pnode_destruct pr o1 t12 o.\n    + inv H0. apply Prefix_cf; auto. inv E. inv H0. intro. inv H0. inv H5. icp_cases H0; inv H6. inv H7. inv H2.\n      * inv H6. decompose [or] (insert_post_top pr t12 o); rewrite <- H5 in *.\n        **inv H2.\n        **inv H6. inv H2. inv H8. destruct H3. eexists. eauto with IPPGrammar.\n        **inv H6. inv H2. inv H8.\n      * apply insert_post_top_unchanged with pr t12 o x in H10; auto.\n        destruct H10; rewrite <- H5 in *.\n        **inv H2. inv H6. inv H7. destruct H3. eexists. eauto with IPPGrammar.\n        **inv H2. inv H6. inv H7.\n    + apply Postfix_cf; auto. intro. inv H2. inv H3. icp_cases H2; inv H4. inv H5.\n  - simpl. apply Postfix_cf; auto. intro. inv H1. inv H2. icp_cases H1; inv H3. inv H4.\nQed.\n\nLemma repair_icfree {g} (pr : drules g) t :\n  safe_pr pr ->\n  i_conflict_free (i_conflict_pattern pr) (repair pr t).\nProof.\n  intro. induction t; simpl; auto using repair_in_icfree, insert_pre_icfree, insert_post_icfree with IPPGrammar.\nQed.\n\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* Proving safety of deep rm conflict patterns. *)\n\nLemma insert_in_matches_rm {g} (pr : drules g) t1 o1 t2 o2 :\n  matches_rm (insert_in pr t1 o1 t2) (PrefixPatt o2 HPatt) ->\n  matches_rm t2 (PrefixPatt o2 HPatt).\nProof.\n  intros. destruct t2.\n  - simpl in H. inv H. inv H0. inv H4. inv H.\n  - insert_in_inode_destruct pr o1 t2_1 o t2_2.\n    + inv H. inv H0. auto with IPPGrammar.\n    + inv H. inv H0. auto with IPPGrammar.\n    + inv H. inv H1. assumption.\n  - simpl in H. inv H. inv H0. assumption.\n  - insert_in_pnode_destruct pr o1 t2 o.\n    + inv H. inv H0.\n    + inv H. inv H1. inv H5. inv H.\nQed.\n\nLemma insert_in_drmcfree {g} (pr : drules g) t1 o t2 :\n  safe_pr pr ->\n  drm_conflict_free (rm_conflict_pattern pr) t1 ->\n  drm_conflict_free (rm_conflict_pattern pr) t2 ->\n  (forall x, rm_conflict_pattern pr (CL_infix_prefix o x) -> ~ matches_rm t1 (PrefixPatt x HPatt)) ->\n  drm_conflict_free (rm_conflict_pattern pr) (insert_in pr t1 o t2).\nProof.\n  intros. induction t2 as [l2|t21 ? o2 t22|o2 t22|t21 ? o2].\n  - simpl. apply Infix_drmcf; auto. intro. inv H3. inv H4. rcp_cases H3; inv H5. eapply H2; eauto.\n  - insert_in_inode_destruct pr o t21 o2 t22.\n    + inv H1. apply Infix_drmcf; auto. intro. inv H1. inv H3. rcp_cases H1; inv H4.\n      destruct H6. eexists. eauto using insert_in_matches_rm with IPPGrammar.\n    + inv H1. apply Infix_drmcf; auto. intro. inv H1. inv H3. rcp_cases H1; inv H4.\n      destruct H6. eexists. eauto using insert_in_matches_rm with IPPGrammar.\n    + apply Infix_drmcf; auto with IPPGrammar. intro. inv H4. inv H5. rcp_cases H4; inv H6. eapply H2; eauto.\n  - simpl. apply Infix_drmcf; auto with IPPGrammar. intro. inv H3. inv H4. rcp_cases H3; inv H5. eapply H2; eauto.\n  - insert_in_pnode_destruct pr o t21 o2.\n    + inv H1. apply Postfix_drmcf; auto. intro. inv H1. inv H3. rcp_cases H1; inv H4.\n      destruct H5. eexists. eauto using insert_in_matches_rm with IPPGrammar.\n    + apply Infix_drmcf; auto with IPPGrammar. intro. inv H4. inv H5. rcp_cases H4; inv H6. eapply H2; eauto.\nQed.\n\nLemma prefixnode_single_drmcfree {g} (pr : drules g) o l2 :\n  drm_conflict_free (rm_conflict_pattern pr) (PrefixNode o (AtomicNode l2)).\nProof.\n  apply Prefix_drmcf; auto using Atomic_drmcf. intro. destruct H as [q]. inv H. rcp_cases H0; inv H1.\nQed.\n\nLemma insert_pre_matches_rm {g} (pr : drules g) o t2 o2 :\n  matches_rm (insert_pre pr o t2) (PrefixPatt o2 HPatt) ->\n  matches_rm t2 (PrefixPatt o2 HPatt) \\/ o2 = o.\nProof.\n  intros. destruct t2.\n  - simpl in H. inv H.\n    + inv H0. auto.\n    + inv H3. inv H.\n  - insert_pre_inode_destruct pr o t2_1 o0 t2_2.\n    + inv H. inv H0. left. auto with IPPGrammar.\n    + inv H. inv H0. left. auto with IPPGrammar.\n    + inv H; auto. inv H1. auto.\n  - inv H; auto. inv H0. auto.\n  - insert_pre_pnode_destruct pr o t2 o0.\n    + inv H. inv H0.\n    + inv H; auto. inv H1. auto.\nQed.\n\nLemma insert_pre_drmcfree {g} (pr : drules g) o t2 :\n  safe_pr pr ->\n  drm_conflict_free (rm_conflict_pattern pr) t2 ->\n  drm_conflict_free (rm_conflict_pattern pr) (insert_pre pr o t2).\nProof.\n  intros. induction t2 as [l2|t21 ? o2 t22|o2 t22|t21 ? o2].\n  - simpl. apply prefixnode_single_drmcfree.\n  - insert_pre_inode_destruct pr o t21 o2 t22.\n    + inv H0. apply Infix_drmcf; auto. intro. inv H0. inv H1. rcp_cases H0; inv H2.\n      apply insert_pre_matches_rm in H7. inv H7.\n      * destruct H4. eexists. eauto with IPPGrammar.\n      * eapply safe_infix_prefix; eauto using CPrio_infix_prefix.\n    + inv H0. apply Infix_drmcf; auto. intro. inv H0. inv H1. rcp_cases H0; inv H2. inv E2. inv H1. inv H3. inv H1.\n      destruct t21.\n      **inv H11. inv H1.\n      **inv H11. inv H1. rename E into E'. insert_pre_inode_destruct pr o t21_1 o0 t21_2.\n        ***inv H7. inv H1. destruct H4. eexists. eauto with IPPGrammar.\n        ***inv H7. inv H1. destruct H4. eexists. eauto with IPPGrammar.\n        ***eapply H1; eauto with IPPGrammar.\n      **inv H11. inv H1.\n      **rename E into E'. insert_pre_pnode_destruct pr o t21 o0.\n        ***inv H7. inv H1.\n        ***eapply H1; eauto.\n    + apply Prefix_drmcf; auto. intro. inv H2. inv H3. rcp_cases H2; inv H4.\n  - simpl. apply Prefix_drmcf; auto. intro. inv H1. inv H2. rcp_cases H1; inv H3.\n  - insert_pre_pnode_destruct pr o t21 o2.\n    + inv H0. apply Postfix_drmcf; auto. intro. inv H0. inv H1. rcp_cases H0; inv H2. inv E. inv H1. inv H6.\n      * inv H1. destruct t21.\n        **simpl in H5. inv H5.\n          ***inv H1. eauto using safe_prefix_postfix.\n          ***inv H9. inv H1.\n        **insert_pre_inode_destruct pr o t21_1 o0 t21_2.\n          ***inv H5. inv H1. destruct H3. eexists. eauto with IPPGrammar.\n          ***inv H5. inv H1. destruct H3. eexists. eauto with IPPGrammar.\n          ***inv H5.\n            ****inv H6. eauto using safe_prefix_postfix.\n            ****inv H10. inv H5. destruct H3. eexists. eauto with IPPGrammar.\n        **simpl in H5. inv H5.\n          ***inv H1. eauto using safe_prefix_postfix.\n          ***destruct H3. eexists. eauto with IPPGrammar.\n        **insert_pre_pnode_destruct pr o t21 o0.\n          ***inv H5. inv H1.\n          ***inv H5.\n            ****inv H6. eauto using safe_prefix_postfix.\n            ****inv H10. inv H5.\n      * destruct t21.\n        **inv H9. inv H1.\n        **inv H9. inv H1. insert_pre_inode_destruct pr o t21_1 o0 t21_2.\n          ***inv H5. inv H1. destruct H3. eexists. eauto with IPPGrammar.\n          ***inv H5. inv H1. destruct H3. eexists. eauto with IPPGrammar.\n          ***inv H5.\n            ****inv H6. eapply H1; eauto with IPPGrammar.\n            ****inv H9. inv H5. destruct H3. eexists. eauto with IPPGrammar.\n        **inv H9. inv H1.\n        **insert_pre_pnode_destruct pr o t21 o0.\n          ***inv H5. inv H1.\n          ***eapply H1; eauto.\n    + apply Prefix_drmcf; auto. intro. inv H2. inv H3. rcp_cases H2; inv H4.\nQed.\n\nLemma postfixnode_single_drmcfree {g} (pr : drules g) o l1 :\n  drm_conflict_free (rm_conflict_pattern pr) (PostfixNode (AtomicNode l1) o).\nProof.\n  apply Postfix_drmcf; auto using Atomic_drmcf. intro. destruct H as [q]. inv H. rcp_cases H0; inv H1. inv H2. inv H.\nQed.\n\nLemma insert_post_drmcfree {g} (pr : drules g) t1 o :\n  safe_pr pr ->\n  drm_conflict_free (rm_conflict_pattern pr) t1 ->\n  drm_conflict_free (rm_conflict_pattern pr) (insert_post pr t1 o).\nProof.\n  intros. induction t1 as [l1|t11 ? o1 t12|o1 t12|t11 ? o1].\n  - simpl. apply Postfix_drmcf; auto. intro. inv H1. inv H2. rcp_cases H1; inv H3. inv H4. inv H2.\n  - insert_post_inode_destruct pr t11 o1 t12 o.\n    + inv H0. apply Infix_drmcf; auto. intro. inv H0. inv H1. rcp_cases H0; inv H2.\n      destruct H4. eexists. eauto with IPPGrammar.\n    + inv H0. apply Infix_drmcf; auto. intro. inv H0. inv H1. rcp_cases H0; inv H2.\n      destruct H4. eexists. eauto with IPPGrammar.\n    + apply Postfix_drmcf; auto. intro. inv H2. inv H3. rcp_cases H2; inv H4. inv H5. inv H3.\n      eapply H1; eauto with IPPGrammar.\n  - insert_post_pnode_destruct pr o1 t12 o.\n    + inv H0. apply Prefix_drmcf; auto. intro. inv H0. inv H1. rcp_cases H0; inv H2.\n    + apply Postfix_drmcf; auto. intro. inv H2. inv H3. rcp_cases H2; inv H4. eapply H1; eauto.\n  - simpl. apply Postfix_drmcf; auto. intro. inv H1. inv H2. rcp_cases H1; inv H3. inv H4. inv H2.\nQed.\n\nLemma repair_in_drmcfree {g} (pr : drules g) t1 o t2 :\n  safe_pr pr ->\n  drm_conflict_free (rm_conflict_pattern pr) t1 ->\n  drm_conflict_free (rm_conflict_pattern pr) t2 ->\n  drm_conflict_free (rm_conflict_pattern pr) (repair_in pr t1 o t2).\nProof.\n  intro. revert o t2. induction t1 as [l1|t11 ? o1 t12|o1 t12|t11 ? o1]; intros; simpl.\n  - apply insert_in_drmcfree; auto with IPPGrammar. intros. intro. inv H3. inv H4.\n  - inv H0. auto.\n  - inv H0. apply insert_pre_drmcfree; auto.\n  - apply insert_in_drmcfree; auto with IPPGrammar. intros. intro. inv H3. inv H4. \nQed.\n\nLemma repair_drmcfree {g} (pr : drules g) t :\n  safe_pr pr ->\n  drm_conflict_free (rm_conflict_pattern pr) (repair pr t).\nProof.\n  intro. induction t; simpl; auto using repair_in_drmcfree, insert_pre_drmcfree, insert_post_drmcfree with IPPGrammar.\nQed.\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* Proving safety of deep lm conflict patterns. *)\n\nLemma insert_in_dlmcfree {g} (pr : drules g) t1 o t2 :\n  safe_pr pr ->\n  dlm_conflict_free (lm_conflict_pattern pr) t1 ->\n  dlm_conflict_free (lm_conflict_pattern pr) t2 ->\n  dlm_conflict_free (lm_conflict_pattern pr) (insert_in pr t1 o t2).\nProof.\n  intros. induction t2 as [l2|t21 ? o2 t22|o2 t22|t21 ? o2].\n  - simpl. apply Infix_dlmcf; auto. intro. inv H2. inv H3. lcp_cases H2; inv H4. inv H11. inv H3.\n  - insert_in_inode_destruct pr o t21 o2 t22.\n    + inv H1. apply Infix_dlmcf; auto. intro. inv H1. inv H2. lcp_cases H1; inv H3.\n      destruct H5. eexists. eauto with IPPGrammar.\n    + inv H1. apply Infix_dlmcf; auto. intro. inv H1. inv H2. lcp_cases H1; inv H3.\n      destruct H5. eexists. eauto with IPPGrammar.\n    + apply Infix_dlmcf; auto. intro. inv H3. inv H4. lcp_cases H3; inv H5. inv H12. inv H4.\n      eapply H2; eauto with IPPGrammar.\n  - simpl. apply Infix_dlmcf; auto with IPPGrammar. intro. inv H2. inv H3. lcp_cases H2; inv H4. inv H11. inv H3.\n  - insert_in_pnode_destruct pr o t21 o2.\n    + inv H1. apply Postfix_dlmcf; auto. intro. inv H1. inv H2. lcp_cases H1; inv H3.\n    + apply Infix_dlmcf; auto with IPPGrammar. intro. inv H3. inv H4. lcp_cases H3; inv H5. eapply H2; eauto.\nQed.\n\nLemma insert_pre_dlmcfree {g} (pr : drules g) o t2 :\n  safe_pr pr ->\n  dlm_conflict_free (lm_conflict_pattern pr) t2 ->\n  dlm_conflict_free (lm_conflict_pattern pr) (insert_pre pr o t2).\nProof.\n  intros. induction t2 as [l2|t21 ? o2 t22|o2 t22|t21 ? o2].\n  - simpl. apply Prefix_dlmcf; auto. intro. inv H1. inv H2. lcp_cases H1; inv H3. inv H4. inv H2.\n  - insert_pre_inode_destruct pr o t21 o2 t22.\n    + inv H0. apply Infix_dlmcf; auto. intro. inv H0. inv H1. lcp_cases H0; inv H2.\n      destruct H4. eexists. eauto with IPPGrammar.\n    + inv H0. apply Infix_dlmcf; auto. intro. inv H0. inv H1. lcp_cases H0; inv H2.\n      destruct H4. eexists. eauto with IPPGrammar.\n    + apply Prefix_dlmcf; auto. intro. inv H2. inv H3. lcp_cases H2; inv H4. inv H5. inv H3.\n      eapply H1; eauto with IPPGrammar.\n  - simpl. apply Prefix_dlmcf; auto. intro. inv H1. inv H2. lcp_cases H1; inv H3. inv H4. inv H2.\n  - insert_pre_pnode_destruct pr o t21 o2.\n    + inv H0. apply Postfix_dlmcf; auto. intro. inv H0. inv H1. lcp_cases H0; inv H2.\n    + apply Prefix_dlmcf; auto with IPPGrammar. intro. inv H2. inv H3. lcp_cases H2; inv H4. eapply H1; eauto.\nQed.\n\nLemma postfixnode_single_dlmcfree {g} (pr : drules g) o l1 :\n  dlm_conflict_free (lm_conflict_pattern pr) (PostfixNode (AtomicNode l1) o).\nProof.\n  apply Postfix_dlmcf; auto with IPPGrammar. intro. destruct H as [q]. inv H. lcp_cases H0; inv H1.\nQed.\n\nLemma insert_post_matches_lm {g} (pr : drules g) o t1 o1 :\n  matches_lm (insert_post pr t1 o) (PostfixPatt HPatt o1) ->\n  matches_lm t1 (PostfixPatt HPatt o1) \\/ o1 = o.\nProof.\n  intros. destruct t1.\n  - simpl in H. inv H.\n    + inv H0. auto.\n    + inv H3. inv H.\n  - insert_post_inode_destruct pr t1_1 o0 t1_2 o.\n    + inv H. inv H0. left. auto with IPPGrammar.\n    + inv H. inv H0. left. auto with IPPGrammar.\n    + inv H; auto. inv H1. auto.\n  - insert_post_pnode_destruct pr o0 t1 o.\n    + inv H. inv H0.\n    + inv H; auto. inv H1; auto.\n  - inv H; auto. inv H0. auto.\nQed.\n\nLemma insert_post_dlmcfree {g} (pr : drules g) t1 o :\n  safe_pr pr ->\n  dlm_conflict_free (lm_conflict_pattern pr) t1 ->\n  dlm_conflict_free (lm_conflict_pattern pr) (insert_post pr t1 o).\nProof.\n  intros. induction t1 as [l1|t11 ? o1 t12|o1 t12|t11 ? o1].\n  - simpl. apply postfixnode_single_dlmcfree.\n  - insert_post_inode_destruct pr t11 o1 t12 o.\n    + inv H0. apply Infix_dlmcf; auto. intro. inv H0. inv H1. lcp_cases H0; inv H2.\n      apply insert_post_matches_lm in H12. inv H12.\n      * destruct H4. eexists. eauto with IPPGrammar.\n      * eauto using safe_infix_postfix.\n    + inv H0. apply Infix_dlmcf; auto. intro. inv H0. inv H1. lcp_cases H0; inv H2. inv E2. inv H1. inv H3. inv H1.\n      destruct t12.\n      **inv H11. inv H1.\n      **inv H11. inv H1. rename E into E'. insert_post_inode_destruct pr t12_1 o0 t12_2 o.\n        ***inv H12. inv H1. destruct H4. eexists. eauto with IPPGrammar.\n        ***inv H12. inv H1. destruct H4. eexists. eauto with IPPGrammar.\n        ***eapply H1; eauto with IPPGrammar.\n      **rename E into E'. insert_post_pnode_destruct pr o0 t12 o.\n        ***inv H12. inv H1.\n        ***eapply H1; eauto.\n      **inv H11. inv H1.\n    + apply Postfix_dlmcf; auto. intro. inv H2. inv H3. lcp_cases H2; inv H4.\n  - insert_post_pnode_destruct pr o1 t12 o.\n    + inv H0. apply Prefix_dlmcf; auto. intro. inv H0. inv H1. lcp_cases H0; inv H2. inv E. inv H1. inv H6.\n      * inv H1. destruct t12.\n        **simpl in H5. inv H5.\n          ***inv H1. eauto using safe_prefix_postfix.\n          ***inv H9. inv H1.\n        **insert_post_inode_destruct pr t12_1 o0 t12_2 o.\n          ***inv H5. inv H1. destruct H3. eexists. eauto with IPPGrammar.\n          ***inv H5. inv H1. destruct H3. eexists. eauto with IPPGrammar.\n          ***inv H5.\n            ****inv H6. eauto using safe_prefix_postfix.\n            ****inv H10. inv H5. destruct H3. eexists. eauto with IPPGrammar.\n        **insert_post_pnode_destruct pr o0 t12 o.\n          ***inv H5. inv H1.\n          ***inv H5.\n            ****inv H6. eauto using safe_prefix_postfix.\n            ****inv H10. inv H5.\n        **simpl in H5. inv H5.\n          ***inv H1. eauto using safe_prefix_postfix.\n          ***destruct H3. eexists. eauto with IPPGrammar.\n      * destruct t12.\n        **inv H9. inv H1.\n        **inv H9. inv H1. insert_post_inode_destruct pr t12_1 o0 t12_2 o.\n          ***inv H5. inv H1. destruct H3. eexists. eauto with IPPGrammar.\n          ***inv H5. inv H1. destruct H3. eexists. eauto with IPPGrammar.\n          ***inv H5.\n            ****inv H6. eapply H1; eauto with IPPGrammar.\n            ****inv H9. inv H5. destruct H3. eexists. eauto with IPPGrammar.\n        **insert_post_pnode_destruct pr o0 t12 o.\n          ***inv H5. inv H1.\n          ***eapply H1; eauto.\n        **inv H9. inv H1.\n    + apply Postfix_dlmcf; auto. intro. inv H2. inv H3. lcp_cases H2; inv H4.\n  - simpl. apply Postfix_dlmcf; auto. intro. inv H1. inv H2. lcp_cases H1; inv H3.\nQed.\n\nLemma repair_in_dlmcfree {g} (pr : drules g) t1 o t2 :\n  safe_pr pr ->\n  dlm_conflict_free (lm_conflict_pattern pr) t1 ->\n  dlm_conflict_free (lm_conflict_pattern pr) t2 ->\n  dlm_conflict_free (lm_conflict_pattern pr) (repair_in pr t1 o t2).\nProof.\n  intro. revert o t2. induction t1 as [l1|t11 ? o1 t12|o1 t12|t11 ? o1]; intros; simpl.\n  - apply insert_in_dlmcfree; auto with IPPGrammar.\n  - inv H0. auto.\n  - inv H0. apply insert_pre_dlmcfree; auto.\n  - apply insert_in_dlmcfree; auto with IPPGrammar. \nQed.\n\nLemma repair_dlmcfree {g} (pr : drules g) t :\n  safe_pr pr ->\n  dlm_conflict_free (lm_conflict_pattern pr) (repair pr t).\nProof.\n  intro. induction t; simpl; auto using repair_in_dlmcfree, insert_pre_dlmcfree, insert_post_dlmcfree with IPPGrammar.\nQed.\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* SAFETY *)\n\nTheorem safety {g} (pr : drules g) :\n  safe_pr pr -> safe pr.\nProof.\n  unfold safe. unfold language. unfold dlanguage. unfold cfree. unfold conflict_free.\n  intros. destruct H0 as [t]. destruct H0.\n  exists (repair pr t).\n  erewrite repair_yield_preserve; eauto.\n  eauto 10 using repair_wf, repair_yield_preserve, repair_icfree, repair_drmcfree, repair_dlmcfree.\nQed.\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* The following lemmas relate completeness to relations between conflict patterns. *)\n\nLemma complete_trans_1 {g} (pr : drules g) o1 o2 o3 :\n  complete_pr pr ->\n  i_conflict_pattern pr (CL_infix_infix o1 o2) ->\n  i_conflict_pattern pr (CL_infix_infix o2 o3) ->\n  i_conflict_pattern pr (CL_infix_infix o1 o3).\nProof.\n  intros. destruct H. inv H0; inv H1; eauto with IPPGrammar.\nQed.\n\nLemma complete_trans_2 {g} (pr : drules g) o1 o2 o3 :\n  complete_pr pr ->\n  i_conflict_pattern pr (CL_infix_infix o1 o2) ->\n  rm_conflict_pattern pr (CL_infix_prefix o2 o3) ->\n  rm_conflict_pattern pr (CL_infix_prefix o1 o3).\nProof.\n  intros. destruct H. inv H0; inv H1; eauto with IPPGrammar.\nQed.\n\nLemma complete_trans_3 {g} (pr : drules g) o1 o2 o3 :\n  complete_pr pr ->\n  i_conflict_pattern pr (CR_prefix_infix o1 o2) ->\n  i_conflict_pattern pr (CR_infix_infix o2 o3) ->\n  i_conflict_pattern pr (CR_prefix_infix o1 o3).\nProof.\n  intros. destruct H. inv H0; inv H1; eauto with IPPGrammar.\nQed.\n\nLemma complete_trans_4 {g} (pr : drules g) o1 o2 o3 :\n  complete_pr pr ->\n  i_conflict_pattern pr (CR_infix_infix o1 o2) ->\n  i_conflict_pattern pr (CR_infix_infix o2 o3) ->\n  i_conflict_pattern pr (CR_infix_infix o1 o3).\nProof.\n  intros. destruct H. inv H0; inv H1; eauto with IPPGrammar.\nQed.\n\nLemma complete_trans_5 {g} (pr : drules g) o1 o2 o3 :\n  complete_pr pr ->\n  i_conflict_pattern pr (CL_postfix_infix o1 o2) ->\n  i_conflict_pattern pr (CL_infix_infix o2 o3) ->\n  i_conflict_pattern pr (CL_postfix_infix o1 o3).\nProof.\n  intros. destruct H. inv H0; inv H1; eauto with IPPGrammar.\nQed.\n\nLemma complete_trans_6 {g} (pr : drules g) o1 o2 o3 :\n  complete_pr pr ->\n  i_conflict_pattern pr (CL_postfix_infix o1 o2) ->\n  rm_conflict_pattern pr (CL_infix_prefix o2 o3) ->\n  rm_conflict_pattern pr (CL_postfix_prefix o1 o3).\nProof.\n  intros. destruct H. inv H0; inv H1; eauto with IPPGrammar.\nQed.\n\nLemma complete_trans_7 {g} (pr : drules g) o1 o2 o3 :\n  complete_pr pr ->\n  i_conflict_pattern pr (CR_infix_infix o1 o2) ->\n  lm_conflict_pattern pr (CR_infix_postfix o2 o3) ->\n  lm_conflict_pattern pr (CR_infix_postfix o1 o3).\nProof.\n  intros. destruct H. inv H0; inv H1; eauto with IPPGrammar.\nQed.\n\nLemma complete_trans_8 {g} (pr : drules g) o1 o2 o3 :\n  complete_pr pr ->\n  i_conflict_pattern pr (CR_prefix_infix o1 o2) ->\n  lm_conflict_pattern pr (CR_infix_postfix o2 o3) ->\n  lm_conflict_pattern pr (CR_prefix_postfix o1 o3).\nProof.\n  intros. destruct H. inv H0; inv H1; eauto with IPPGrammar.\nQed.\n\nLemma complete_neg_1 {g} (pr : drules g) o1 o2 :\n  complete_pr pr ->\n  ~ i_conflict_pattern pr (CR_infix_infix o1 o2) ->\n  i_conflict_pattern pr (CL_infix_infix o2 o1).\nProof.\n  intros. destruct H.\n  specialize complete_1 with (InfixProd o1) (InfixProd o2).\n  decompose [or] complete_1; auto with IPPGrammar.\n  - destruct H0. auto with IPPGrammar.\n  - destruct H0. auto with IPPGrammar.\nQed.\n\nLemma complete_neg_2 {g} (pr : drules g) o1 o2 :\n  complete_pr pr ->\n  ~ rm_conflict_pattern pr (CL_infix_prefix o1 o2) ->\n  i_conflict_pattern pr (CR_prefix_infix o2 o1).\nProof.\n  intros. destruct H.\n  specialize complete_1 with (PrefixProd o2) (InfixProd o1) .\n  decompose [or] complete_1; auto with IPPGrammar.\n  - destruct H0. auto with IPPGrammar.\n  - destruct H0. auto with IPPGrammar.\nQed.\n\nLemma complete_neg_3 {g} (pr : drules g) o1 o2 :\n  complete_pr pr ->\n  ~ i_conflict_pattern pr (CL_infix_infix o1 o2) ->\n  i_conflict_pattern pr (CR_infix_infix o2 o1).\nProof.\n  intros. destruct H.\n  specialize complete_1 with (InfixProd o2) (InfixProd o1).\n  decompose [or] complete_1; auto with IPPGrammar.\n  - destruct H0. auto with IPPGrammar.\n  - destruct H0. auto with IPPGrammar.\nQed.\n\nLemma complete_neg_4 {g} (pr : drules g) o1 o2 :\n  complete_pr pr ->\n  ~ i_conflict_pattern pr (CL_postfix_infix o1 o2) ->\n  lm_conflict_pattern pr (CR_infix_postfix o2 o1).\nProof.\n  intros. destruct H.\n  specialize complete_1 with (InfixProd o2) (PostfixProd o1).\n  decompose [or] complete_1; auto with IPPGrammar.\n  - destruct H0. auto with IPPGrammar.\n  - destruct H0. auto with IPPGrammar.\nQed.\n\nLemma complete_neg_5 {g} (pr : drules g) o1 o2 :\n  complete_pr pr ->\n  ~ rm_conflict_pattern pr (CL_postfix_prefix o1 o2) ->\n  lm_conflict_pattern pr (CR_prefix_postfix o2 o1).\nProof.\n  intros. destruct H.\n  specialize complete_1 with (PrefixProd o2) (PostfixProd o1).\n  decompose [or] complete_1; auto with IPPGrammar.\n  - destruct H0. auto with IPPGrammar.\n  - destruct H0. auto with IPPGrammar.\nQed.\n\nLemma complete_neg_6 {g} (pr : drules g) o1 o2 :\n  complete_pr pr ->\n  ~ i_conflict_pattern pr (CR_prefix_infix o1 o2) ->\n  rm_conflict_pattern pr (CL_infix_prefix o2 o1).\nProof.\n  intros. destruct H.\n  specialize complete_1 with (PrefixProd o1) (InfixProd o2).\n  decompose [or] complete_1; auto with IPPGrammar.\n  - destruct H0. auto with IPPGrammar.\n  - destruct H0. auto with IPPGrammar.\nQed.\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* Lemmas showing [repair t] = t if [t] is conflict free *)\n\nLemma insert_in_complete {g} (pr : drules g) t1 o t2 :\n  complete_pr pr ->\n  cfree pr (InfixNode t1 o t2) ->\n  insert_in pr t1 o t2 = InfixNode t1 o t2.\nProof.\n  intros. inv H0. inv H2. destruct t2; auto.\n  - insert_in_inode_destruct pr o t2_1 o0 t2_2; auto.\n    + inv H1. destruct H6. eexists. eauto with IPPGrammar.\n    + inv E2. inv H2. inv H3. destruct H8. eexists. eauto with IPPGrammar.\n  - insert_in_pnode_destruct pr o t2 o0; auto. inv E. inv H2. inv H3. destruct H8. eexists. eauto with IPPGrammar.\nQed.\n\nLemma insert_in_matches_lm {g} (pr : drules g) t1 o t2 x :\n  lm_conflict_pattern pr (CR_infix_postfix o x) ->\n  matches_lm t2 (PostfixPatt HPatt x) ->\n  matches_lm (insert_in pr t1 o t2) (PostfixPatt HPatt x).\nProof.\n  intros. induction t2 as [l2|t21 ? o2 t22|o2 t22|t21 ? o2].\n  - inv H0. inv H1.\n  - inv H0. inv H1. insert_in_inode_destruct pr o t21 o2 t22.\n    + auto with IPPGrammar.\n    + inv E2. inv H0. inv H2. inv H0. auto with IPPGrammar.\n    + edestruct H0; eauto with IPPGrammar.\n  - inv H0. inv H1.\n  - insert_in_pnode_destruct pr o t21 o2.\n    + inv H0.\n      * inv H1. auto with IPPGrammar.\n      * auto with IPPGrammar.\n    + edestruct H1; eauto with IPPGrammar.\nQed.\n\nLemma insert_in_assoc {g} (pr : drules g) t11 o1 t12 o t2 :\n  complete_pr pr ->\n  cfree pr (InfixNode t11 o1 t12) ->\n  ~ i_conflict_pattern pr (CL_infix_infix o o1) ->\n  insert_in pr t11 o1 (insert_in pr t12 o t2) = insert_in pr (InfixNode t11 o1 t12) o t2.\nProof.\n  intros. assert (H0' := H0). inv H0'. inv H3.\n  induction t2 as [l2|t21 ? o2 t22|o2 t22|t21 ? o2].\n  - assert (insert_in pr t12 o (AtomicNode l2) = InfixNode t12 o (AtomicNode l2)); auto. rewrite H3.\n    insert_in_inode_destruct pr o1 t12 o (AtomicNode l2).\n    + rewrite insert_in_complete; auto.\n    + rewrite insert_in_complete; auto.\n    + exfalso. destruct H1. auto using complete_neg_1.\n  - insert_in_inode_destruct pr o t21 o2 t22.\n    + rewrite <- IHt2_1. rename E into E'. insert_in_inode_destruct pr o1 (insert_in pr t12 o t21) o2 t22; auto.\n      destruct E. apply complete_trans_4 with o; auto. auto using complete_neg_3.\n    + rewrite <- IHt2_1. rename E into E'. rename E2 into E2'.\n      insert_in_inode_destruct pr o1 (insert_in pr t12 o t21) o2 t22; auto. exfalso. inv E2'. inv H6. inv H8.\n      inv H6. apply insert_in_matches_lm with pr t12 o t21 x in H12; auto. edestruct H3; eauto with IPPGrammar.\n      apply complete_trans_7 with o; auto. auto using complete_neg_3.\n    + rename E into E'. rename E2 into E2'. insert_in_inode_destruct pr o1 t12 o (InfixNode t21 o2 t22).\n      * rewrite insert_in_complete; auto.\n      * destruct H1. auto using complete_neg_1.\n      * destruct H1. auto using complete_neg_1.\n  - insert_in_inode_destruct pr o1 t12 o (PrefixNode o2 t22).\n    + rewrite insert_in_complete; auto.\n    + rewrite insert_in_complete; auto.\n    + destruct H1. auto using complete_neg_1.\n  - insert_in_pnode_destruct pr o t21 o2.\n    + rewrite <- IHt2. rename E into E'. insert_in_pnode_destruct pr o1 (insert_in pr t12 o t21) o2; auto.\n      exfalso. inv E'. inv H6. inv H8.\n      * inv H6. edestruct H3; eauto with IPPGrammar. apply complete_trans_7 with o; auto. auto using complete_neg_3.\n      * apply insert_in_matches_lm with pr t12 o t21 x in H11; auto. edestruct H3; eauto with IPPGrammar.\n        apply complete_trans_7 with o; auto. auto using complete_neg_3.\n    + rename E into E'. insert_in_inode_destruct pr o1 t12 o (PostfixNode t21 o2).\n      * rewrite insert_in_complete; auto.\n      * destruct H1. auto using complete_neg_1.\n      * destruct H1. auto using complete_neg_1.\nQed.\n\nLemma insert_pre_complete {g} (pr : drules g) o t2 :\n  cfree pr (PrefixNode o t2) ->\n  insert_pre pr o t2 = PrefixNode o t2.\nProof.\n  intro. inv H. inv H1. destruct t2 as [l2|t21 o2 t22|o2 t22|t21 o2]; auto.\n  - insert_pre_inode_destruct pr o t21 o2 t22; auto.\n    + inv H0. destruct H4. eexists. eauto with IPPGrammar.\n    + inv E2. inv H1. inv H4. inv H1. inv H2. destruct H5. eexists. eauto with IPPGrammar.\n  - insert_pre_pnode_destruct pr o t21 o2; auto. inv E. inv H1. inv H2. destruct H6. eexists. eauto with IPPGrammar.\nQed.\n\nLemma insert_in_prefix {g} (pr : drules g) o1 t12 o t2 :\n  complete_pr pr ->\n  cfree pr (PrefixNode o1 t12) ->\n  ~ rm_conflict_pattern pr (CL_infix_prefix o o1) ->\n  insert_in pr (PrefixNode o1 t12) o t2 = insert_pre pr o1 (insert_in pr t12 o t2).\nProof.\n  intros. assert (H0' := H0). inv H0'. inv H3. induction t2 as [l2|t21 ? o2 t22|o2 t22|t21 ? o2].\n  - cbn [insert_in]. insert_pre_inode_destruct pr o1 t12 o (AtomicNode l2).\n    + rewrite insert_pre_complete; auto.\n    + rewrite insert_pre_complete; auto.\n    + destruct E. auto using complete_neg_2.\n  - insert_in_inode_destruct pr o t21 o2 t22.\n    + rewrite IHt2_1. rename E into E'. insert_pre_inode_destruct pr o1 (insert_in pr t12 o t21) o2 t22; auto.\n      destruct E. apply complete_trans_3 with o; auto. auto using complete_neg_2.\n    + rewrite IHt2_1. rename E into E', E2 into E2'.\n      insert_pre_inode_destruct pr o1 (insert_in pr t12 o t21) o2 t22; auto. exfalso. inv E2'. inv H6. inv H8. inv H6.\n      apply insert_in_matches_lm with pr t12 o t21 x in H12; auto. edestruct H3; eauto with IPPGrammar.\n      apply complete_trans_8 with o; auto. auto using complete_neg_2.\n    + rename E into E', E2 into E2'. insert_pre_inode_destruct pr o1 t12 o (InfixNode t21 o2 t22).\n      * rewrite insert_pre_complete; auto.\n      * rewrite insert_pre_complete; auto.\n      * destruct E. auto using complete_neg_2.\n  - cbn [insert_in]. insert_pre_inode_destruct pr o1 t12 o (PrefixNode o2 t22).\n    + rewrite insert_pre_complete; auto.\n    + rewrite insert_pre_complete; auto.\n    + destruct E. auto using complete_neg_2.\n  - insert_in_pnode_destruct pr o t21 o2.\n    + rewrite IHt2. rename E into E'. insert_pre_pnode_destruct pr o1 (insert_in pr t12 o t21) o2; auto. exfalso.\n      inv E'. inv H6. inv H8.\n      * inv H6. edestruct H3; eauto with IPPGrammar. apply complete_trans_8 with o; auto. auto using complete_neg_2.\n      * apply insert_in_matches_lm with pr t12 o t21 x in H11; auto. edestruct H3; eauto with IPPGrammar.\n        apply complete_trans_8 with o; auto. auto using complete_neg_2.\n    + rename E into E'. insert_pre_inode_destruct pr o1 t12 o (PostfixNode t21 o2).\n      * rewrite insert_pre_complete; auto.\n      * rewrite insert_pre_complete; auto.\n      * destruct E. auto using complete_neg_2.\nQed.\n\nLemma repair_in_insert_in {g} (pr : drules g) t1 o t2 :\n  complete_pr pr ->\n  cfree pr t1 ->\n  (forall x1, matches t1 (InfixPatt HPatt x1 HPatt) -> ~ i_conflict_pattern pr (CL_infix_infix o x1)) ->\n  (forall x1, matches_rm t1 (PrefixPatt x1 HPatt) -> ~ rm_conflict_pattern pr (CL_infix_prefix o x1)) ->\n  repair_in pr t1 o t2 = insert_in pr t1 o t2.\nProof.\n  unfold cfree. unfold conflict_free. intro. intro.\n  revert o t2. induction t1 as [l1|t11 ? o1 t12|o1 t12|t11 ? o1]; intros; simpl; auto.\n  - rewrite IHt12.\n    + rewrite IHt1_1.\n      * rewrite insert_in_assoc; auto. apply H1. auto with IPPGrammar.\n      * inv H0. inv H4. inv H3. inv H0. inv H5. auto.\n      * intros. inv H3. rename x1 into o11, t1 into t111, t0 into t112. intro. inv H0. inv H4. destruct H10.\n        eexists. eauto with IPPGrammar.\n      * intros. intro. inv H0. inv H6. inv H0. destruct H10. eexists. eauto with IPPGrammar.\n    + inv H0. inv H4. inv H3. inv H0. inv H5. auto.\n    + intros. inv H3. rename x1 into o12, t1 into t121, t0 into t122. intro. apply H1 with o1; auto with IPPGrammar.\n      apply complete_trans_1 with o12; auto. apply complete_neg_1; auto. intro. inv H0. inv H5. destruct H11. eexists.\n      eauto with IPPGrammar.\n    + intros. apply H2. auto with IPPGrammar.\n  - rewrite IHt12.\n    + rewrite insert_in_prefix; auto. apply H2. auto with IPPGrammar.\n    + inv H0. inv H4. inv H3. inv H0. inv H5. auto.\n    + intros. inv H3. rename x1 into o12, t1 into t121, t0 into t122. intro. apply H2 with o1; auto with IPPGrammar.\n      apply complete_trans_2 with o12; auto. apply complete_neg_6; auto. intro. inv H0. inv H5. destruct H10. eexists.\n      eauto with IPPGrammar.\n    + intros. apply H2. auto with IPPGrammar.\nQed.\n\nLemma repair_in_complete {g} (pr : drules g) t1 o t2 :\n  complete_pr pr ->\n  cfree pr (InfixNode t1 o t2) ->\n  repair_in pr t1 o t2 = InfixNode t1 o t2.\nProof.\n  intros. assert (H0' := H0). inv H0. inv H2. inv H1. inv H0. inv H3. rewrite repair_in_insert_in; auto.\n  - rewrite insert_in_complete; auto.\n  - unfold cfree. unfold conflict_free. auto.\n  - intros. intro. destruct H6. eexists. eauto with IPPGrammar.\n  - intros. intro. destruct H5. eexists. eauto with IPPGrammar.\nQed.\n\nLemma insert_post_complete {g} (pr : drules g) t1 o :\n  cfree pr (PostfixNode t1 o) ->\n  insert_post pr t1 o = PostfixNode t1 o.\nProof.\n  intro. inv H. inv H1. destruct t1 as [l1|t11 o1 t12|o1 t12|t11 o1]; auto.\n  - insert_post_inode_destruct pr t11 o1 t12 o; auto.\n    + inv H0. destruct H4. eexists. eauto with IPPGrammar.\n    + inv E2. inv H1. inv H4. inv H1. inv H. destruct H5. eexists. eauto with IPPGrammar.\n  - insert_post_pnode_destruct pr o1 t12 o; auto. inv E. inv H1. inv H. destruct H6. eexists. eauto with IPPGrammar.\nQed.\n\nLemma repair_complete {g} (pr : drules g) t :\n  complete_pr pr ->\n  cfree pr t ->\n  repair pr t = t.\nProof.\n  intro. induction t; simpl; auto; intros.\n  - assert (H0' := H0). inv H0'. inv H2. inv H1. inv H3. inv H4. rewrite IHt1; try split; auto.\n    rewrite IHt2; try split; auto. apply repair_in_complete; auto.\n  - assert (H0' := H0). inv H0'. inv H2. inv H1. inv H3. inv H4. rewrite IHt; try split; auto.\n    apply insert_pre_complete; auto.\n  - assert (H0' := H0). inv H0'. inv H2. inv H1. inv H3. inv H4. rewrite IHt; try split; auto.\n    apply insert_post_complete; auto.\nQed.\n\n(*\n  ############################################## \n  ##############################################\n  ##############################################\n*)\n\n(* COMPLETENESS *)\n\nTheorem completeness {g} (pr : drules g) :\n  complete_pr pr ->\n  complete pr.\nProof.\n  intro. intro. intros.\n  assert (repair_fully_yield_dependent: forall x y, yield x = yield y -> repair pr x = repair pr y). {\n    admit. (* FUTURE WORK *)\n  }\n  apply repair_fully_yield_dependent in H0.\n  rewrite repair_complete in H0; auto. rewrite repair_complete in H0; auto.\nAdmitted.\n\nEnd IPPGrammarTheorems.\n", "meta": {"author": "metaborg", "repo": "disamb-verification", "sha": "e7fecc14f2c85879ae4b1e50849b86d1e3ce4c15", "save_path": "github-repos/coq/metaborg-disamb-verification", "path": "github-repos/coq/metaborg-disamb-verification/disamb-verification-e7fecc14f2c85879ae4b1e50849b86d1e3ce4c15/IPPGrammarTheorems.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5234203340678568, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.22114751709966027}}
{"text": "Require Import syntax.\nRequire Import alist.\nRequire Import FMapWeakList.\n\nRequire Import Classical.\nRequire Import Coqlib.\nRequire Import infrastructure.\nRequire Import Metatheory.\nImport LLVMsyntax.\nImport LLVMinfra.\nRequire Import opsem.\nRequire Import memory_props.\n\nRequire Import sflib.\nRequire Import paco.\nImport Opsem.\n\nRequire Import TODO.\nRequire Import TODOProof.\nRequire Import Exprs.\nRequire Import Hints.\nRequire Import Postcond.\nRequire Import Validator.\nRequire Import GenericValues.\nRequire AssnMem.\nRequire AssnState.\nRequire Import Inject.\nRequire Import SoundBase.\nRequire Import SoundForgetStack.\nRequire Import SoundForgetMemory.\nRequire Import SoundPostcondCmdAdd.\nRequire Import MemAux.\n\nSet Implicit Arguments.\n\n\nLemma postcond_cmd_is_call\n      c_src c_tgt inv1 inv2\n      (POSTCOND: Postcond.postcond_cmd c_src c_tgt inv1 = Some inv2):\n  Instruction.isCallInst c_src = Instruction.isCallInst c_tgt.\nProof.\n  unfold\n    Postcond.postcond_cmd,\n  Postcond.postcond_cmd_check in *.\n  destruct c_src, c_tgt; ss; des_ifs.\nQed.\n\nLemma noncall_event\n      conf st0 st1 evt cmd cmds\n      (STEP: sInsn conf st0 st1 evt)\n      (CMDS: st0.(EC).(CurCmds) = cmd::cmds)\n      (NONCALL: Instruction.isCallInst cmd = false):\n  evt = events.E0.\nProof.\n  inv STEP; ss. inv CMDS. ss.\nQed.\n\n(* TODO: move this *)\n\nLemma postcond_cmd_check_forgets_Subset\n      cmd_src cmd_tgt inv0\n      (COND : postcond_cmd_check\n                cmd_src cmd_tgt\n                (AtomSetImpl_from_list (Cmd.get_def cmd_src))\n                (AtomSetImpl_from_list (Cmd.get_def cmd_tgt))\n                (AtomSetImpl_from_list (Cmd.get_ids cmd_src))\n                (AtomSetImpl_from_list (Cmd.get_ids cmd_tgt))\n                (ForgetStack.t\n                   (AtomSetImpl_from_list (Cmd.get_def cmd_src))\n                   (AtomSetImpl_from_list (Cmd.get_def cmd_tgt))\n                   (AtomSetImpl_from_list (Cmd.get_leaked_ids cmd_src))\n                   (AtomSetImpl_from_list (Cmd.get_leaked_ids cmd_tgt))\n                   (ForgetMemory.t\n                      (Cmd.get_def_memory cmd_src) (Cmd.get_def_memory cmd_tgt)\n                      (Cmd.get_leaked_ids_to_memory cmd_src) (Cmd.get_leaked_ids_to_memory cmd_tgt)\n                      inv0)) = true)\n  : postcond_cmd_check\n      cmd_src cmd_tgt\n      (AtomSetImpl_from_list (Cmd.get_def cmd_src))\n      (AtomSetImpl_from_list (Cmd.get_def cmd_tgt))\n      (AtomSetImpl_from_list (Cmd.get_ids cmd_src))\n      (AtomSetImpl_from_list (Cmd.get_ids cmd_tgt))\n      inv0 = true.\nProof.\n  unfold postcond_cmd_check in *.\n  des_ifs.\n  clear -Heq1 Heq2.\n  rename Heq1 into INJECT_F. rename Heq2 into INJECT_T.\n  apply negb_false_iff in INJECT_T.\n  apply negb_true_iff in INJECT_F.\n  exploit postcond_cmd_inject_event_Subset; eauto;\n    (etransitivity; [apply forget_stack_Subset | apply forget_memory_Subset]).\nQed.\n\nLemma step_wf_lc\n      conf st0 st1 evt\n      cmd cmds\n      (WF_LC: MemProps.wf_lc st0.(Mem) st0.(EC).(Locals))\n      (STEP: sInsn conf st0 st1 evt)\n      (CMDS: st0.(EC).(CurCmds) = cmd :: cmds)\n      (NONCALL: Instruction.isCallInst cmd = false)\n      (NONMALLOC: isMallocInst cmd = false)\n      gmax public assnmem0\n      (MEM: AssnMem.Unary.sem conf gmax public st0.(Mem) assnmem0)\n  : <<WF_LOCAL: MemProps.wf_lc st1.(Mem) st1.(EC).(Locals)>> /\\\n    <<WF_MEM: MemProps.wf_Mem gmax conf.(CurTargetData) st1.(Mem)>>.\nProof.\n  inv MEM.\n  clear PRIVATE_PARENT MEM_PARENT UNIQUE_PARENT_MEM UNIQUE_PARENT_GLOBALS UNIQUE_PRIVATE_PARENT.\n  inv STEP; destruct cmd; ss;\n    try (split; [apply MemProps.updateAddAL__wf_lc; eauto; [] | by auto]); clarify.\n  -\n    eapply opsem_props.OpsemProps.BOP_inversion in H.\n    des.\n    eapply MemProps.mbop_preserves_valid_ptrs; eauto.\n  -\n    eapply opsem_props.OpsemProps.FBOP_inversion in H.\n    des.\n    eapply MemProps.mfbop_preserves_valid_ptrs; eauto.\n  -\n    eapply MemProps.extractGenericValue_preserves_valid_ptrs; eauto.\n    (* unfold MemProps.wf_Mem in *. *)\n    (* des. clear WF. *)\n    eapply get_operand_valid_ptr; eauto.\n  -\n    eapply MemProps.insertGenericValue_preserves_valid_ptrs; eauto.\n    + eapply get_operand_valid_ptr; eauto.\n    + eapply get_operand_valid_ptr; eauto.\n  - split. (* free *)\n    + eapply MemProps.free_preserves_wf_lc; eauto.\n    + eapply MemProps.free_preserves_wf_Mem; eauto.\n  - split. (* alloca *)\n    + exploit alloca_result; eauto. i. des.\n      ii. destruct (id_dec id0 id5).\n      * subst.\n        rewrite lookupAL_updateAddAL_eq in *. clarify. ss.\n        split; auto.\n        rewrite NEXT_BLOCK. apply Plt_succ.\n      * rewrite <- lookupAL_updateAddAL_neq in *; eauto.\n        eapply MemProps.alloca_preserves_wf_lc_in_tail; eauto.\n    + eapply MemProps.alloca_preserves_wf_Mem; eauto.\n  - unfold MemProps.wf_Mem in *. des.\n    eapply WF; eauto.\n  - (* store *)\n    assert(WF_LC2: MemProps.wf_lc Mem' lc).\n    { eapply MemProps.mstore_preserves_wf_lc; eauto. }\n    splits; eauto.\n    red.\n    (* exploit mstore_aux_valid_ptrs_preserves_wf_Mem; eauto. *)\n    unfold MemProps.wf_Mem in *.\n    des.\n    eapply mstore_inversion in H1. des. clarify.\n    exploit MemProps.nextblock_mstore_aux; eauto; []; intros NEXTBLOCK_SAME; des.\n    splits; cycle 1.\n    *\n      rewrite <- NEXTBLOCK_SAME.\n      ss.\n    *\n      ii.\n      apply mload_inv in H1. des. clarify.\n      exploit MemProps.mstore_aux_preserves_mload_aux_inv; eauto; []; ii; des.\n      eapply MemProps.valid_ptrs_overlap; eauto.\n      { eapply get_operand_valid_ptr; eauto.\n        exploit mstore_aux_valid_ptrs_preserves_wf_Mem; eauto.\n        { instantiate (1:= {| CurSystem := S;\n                              CurTargetData := TD;\n                              CurProducts := Ps;\n                              Globals := gl;\n                              FunTable := fs|}). ss.\n          instantiate (1:= gmax). ss. }\n        { eapply get_operand_valid_ptr; eauto. splits; ss. }\n        ii; ss. }\n      {\n        rewrite <- NEXTBLOCK_SAME.\n        eapply WF; eauto.\n        Check ([(Values.Vptr b0 ofs0, cm)]): mptr.\n        instantiate (3:= ([(Values.Vptr b0 ofs0, cm)])).\n        cbn.\n        erewrite H4. ss. }\n  -\n    eapply dopsem.GEP_inv in H1. des.\n    + eapply MemProps.undef_valid_ptrs; eauto.\n    + clarify.\n      exploit get_operand_valid_ptr; eauto.\n  -\n    eapply opsem_props.OpsemProps.TRUNC_inversion in H.\n    des.\n    eapply MemProps.mtrunc_preserves_valid_ptrs; eauto.\n  -\n    eapply opsem_props.OpsemProps.EXT_inversion in H.\n    des.\n    eapply MemProps.mext_preserves_valid_ptrs; eauto.\n  -\n    eapply opsem_props.OpsemProps.CAST_inversion in H.\n    des.\n    eapply MemProps.mcast_preserves_valid_ptrs; eauto.\n    eapply get_operand_valid_ptr; eauto.\n  -\n    eapply opsem_props.OpsemProps.ICMP_inversion in H.\n    des.\n    eapply MemProps.micmp_preserves_valid_ptrs; eauto.\n  -\n    eapply opsem_props.OpsemProps.FCMP_inversion in H.\n    des.\n    eapply MemProps.mfcmp_preserves_valid_ptrs; eauto.\n  - unfold SELECT in *. des_ifs.\n    unfold mselect, fit_chunk_gv in *.\n    des_ifs; try (by eapply get_operand_valid_ptr; eauto);\n      try (by eapply MemProps.undef_valid_ptrs; eauto).\nUnshelve.\nss.\nQed.\n\nLemma disjoint_allocas_private_parent\n      conf_unary st0_unary cmd_unary cmds_unary unary unary0 gmax evt\n      st1_unary unary1 gmax0 inv public_unary0 public_unary\n      (NONCALL_UNARY: Instruction.isCallInst cmd_unary = false)\n      (CMDS_UNARY: CurCmds (EC st0_unary) = cmd_unary :: cmds_unary)\n      (STEP_UNARY: sInsn conf_unary st0_unary st1_unary evt)\n      (STATE_FORGET_MEMORY_UNARY: AssnState.Unary.sem conf_unary\n                                                     (mkState (EC st0_unary) (ECS st0_unary) (Mem st1_unary))\n                                                     unary unary1 gmax0 public_unary0 inv)\n      (MEMLE_UNARY: AssnMem.Unary.le unary0 unary1)\n      (UNARY: AssnMem.Unary.sem conf_unary gmax public_unary (Mem st0_unary) unary0)\n  :\n    <<DISJOINT: list_disjoint (Allocas (EC st1_unary)) (AssnMem.Unary.private_parent unary1)>>\n.\nProof.\n  inv STEP_UNARY; try apply STATE_FORGET_MEMORY_UNARY; cbn.\n  - (* return *)\n    clarify.\n  - (* return_void *)\n    clarify.\n  - ss.\n    assert(PARENT: list_disjoint (als) (AssnMem.Unary.private_parent unary1)).\n    { apply STATE_FORGET_MEMORY_UNARY. }\n    apply list_disjoint_cons_l; eauto.\n    {\n      ss. expl alloca_result. clarify. ss.\n      intro MB_PRIVATE_PARENT0.\n      assert(MB_PRIVATE_PARENT1: In (Memory.Mem.nextblock Mem0)\n                                    (AssnMem.Unary.private_parent unary0)).\n      {\n        inv MEMLE_UNARY. rewrite PRIVATE_PARENT_EQ. ss.\n      }\n      clear - UNARY MB_PRIVATE_PARENT1.\n      inv UNARY. ss.\n      expl PRIVATE_PARENT.\n      unfold AssnMem.private_block in PRIVATE_PARENT0.\n      des.\n      expl Pos.lt_irrefl.\n    }\n  - ss. (* call *)\nQed.\n\nLemma sublist_app_inv\n      A\n      (xs ys zs: list A)\n      (SUB: sublist (zs ++ xs) ys)\n  :\n    <<SUB: sublist xs ys>>\n.\nProof.\n  ginduction ys; ii; ss.\n  - inv SUB. expl nil_eq_app. clarify. econs; eauto.\n  - inv SUB.\n    + expl nil_eq_app. clarify. econs; eauto.\n    + destruct zs; ss.\n      { clarify. econs; eauto. }\n      { clarify. econs; eauto. eapply IHys; eauto. }\n    + econs; eauto. eapply IHys; eauto.\nQed.\n\nLemma sublist_cons_inv\n      A\n      (xs ys: list A)\n      x\n      (SUB: sublist (x :: xs) ys)\n  :\n    <<SUB: sublist xs ys>>\n.\nProof.\n  eapply sublist_app_inv.\n  instantiate (1:= [x]).\n  ss.\nQed.\n\nLemma step_wf_EC\n      st0\n      (WF: OpsemAux.wf_EC st0.(EC))\n      cmd cmds\n      (CMDS: st0.(EC).(CurCmds) = cmd :: cmds)\n      (NONCALL: Instruction.isCallInst cmd = false)\n      conf st1 tr\n      (STEP: sInsn conf st0 st1 tr)\n  :\n    <<WF: OpsemAux.wf_EC st1.(EC)>>\n.\nProof.\n  inv WF.\n  inv STEP; ss; try (by econs; ss; eauto; [eapply sublist_cons_inv; eauto]).\n  - des_ifs.\nQed.\n\nLemma postcond_cmd_sound\n      m_src conf_src st0_src cmd_src cmds_src\n      m_tgt conf_tgt st0_tgt cmd_tgt cmds_tgt\n      invst0 assnmem0 inv0\n      st1_tgt evt inv1\n      (WF_CONF_SRC: opsem_wf.OpsemPP.wf_Config conf_src)\n      (WF_CONF_TGT: opsem_wf.OpsemPP.wf_Config conf_tgt)\n      (WF_STATE_PREV_SRC: opsem_wf.OpsemPP.wf_State conf_src st0_src)\n      (WF_STATE_PREV_TGT: opsem_wf.OpsemPP.wf_State conf_tgt st0_tgt)\n      (CONF: AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (POSTCOND: Postcond.postcond_cmd cmd_src cmd_tgt inv0 = Some inv1)\n      (STATE: AssnState.Rel.sem conf_src conf_tgt st0_src st0_tgt invst0 assnmem0 inv0)\n      (MEM: AssnMem.Rel.sem conf_src conf_tgt st0_src.(Mem) st0_tgt.(Mem) assnmem0)\n      (STEP_TGT: sInsn conf_tgt st0_tgt st1_tgt evt)\n      (CMDS_SRC: st0_src.(EC).(CurCmds) = cmd_src :: cmds_src)\n      (CMDS_TGT: st0_tgt.(EC).(CurCmds) = cmd_tgt :: cmds_tgt)\n      (NONCALL_SRC: Instruction.isCallInst cmd_src = false)\n      (NONCALL_TGT: Instruction.isCallInst cmd_tgt = false)\n      (NERROR_SRC: ~ error_state conf_src st0_src):\n  exists st1_src invst1 assnmem1,\n    <<STEP_SRC: sInsn conf_src st0_src st1_src evt>> /\\\n    <<STATE: AssnState.Rel.sem conf_src conf_tgt st1_src st1_tgt invst1 assnmem1 inv1>> /\\\n    <<MEM: AssnMem.Rel.sem conf_src conf_tgt st1_src.(Mem) st1_tgt.(Mem) assnmem1>> /\\\n    <<MEMLE: AssnMem.Rel.le assnmem0 assnmem1>>.\nProof.\n  assert(NONMALLOC_SRC: isMallocInst cmd_src = false).\n  { destruct cmd_src; ss.\n    unfold postcond_cmd in *. ss.\n    unfold postcond_cmd_check in *. ss.\n    des_ifs. }\n  assert(NONMALLOC_TGT: isMallocInst cmd_tgt = false).\n  { destruct cmd_tgt; ss.\n    unfold postcond_cmd in *. ss.\n    unfold postcond_cmd_check in *. ss.\n    unfold postcond_cmd_inject_event in *. des_ifs. }\n  exploit postcond_cmd_is_call; eauto. i.\n  unfold postcond_cmd in *. simtac.\n  match goal with\n  | [H: Instruction.isCallInst cmd_src = false |- _] =>\n    rename H into NONCALL_SRC\n  end.\n\n  destruct (s_isFinalState conf_src st0_src) eqn:FINAL.\n  { unfold s_isFinalState in FINAL. des_ifs. }\n  exploit nerror_nfinal_nstuck; eauto. intros [st1_src [evt_src STEP_SRC]].\n  replace evt_src with evt in *; cycle 1.\n  { unfold postcond_cmd_check in COND. simtac.\n    exploit (@noncall_event conf_src); eauto. i.\n    exploit (@noncall_event conf_tgt); eauto. i.\n    subst. ss.\n  }\n  exploit postcond_cmd_check_forgets_Subset; eauto. intro COND_INIT.\n\n  (* forget-memory *)\n  exploit forget_memory_sound; eauto.\n  { unfold postcond_cmd_check in COND_INIT.\n    des_ifs. des_bool. eauto. }\n  i. des.\n  rename STATE0 into STATE_FORGET_MEMORY.\n  rename MEM0 into MEM_FORGET_MEMORY.\n\n  (* forget *)\n  exploit forget_stack_sound.\n  instantiate (5 := {| EC := EC st0_src; ECS := ECS st0_src; Mem := Mem st1_src |}).\n  instantiate (4 := {| EC := EC st0_tgt; ECS := ECS st0_tgt; Mem := Mem st1_tgt |}).\n  { eauto. }\n  { hexploit step_state_equiv_except; try exact CMDS_SRC; eauto. }\n  { hexploit step_state_equiv_except; try exact CMDS_TGT; eauto. }\n  { inv STATE_FORGET_MEMORY. inv MEM_FORGET_MEMORY.\n    eapply step_unique_preserved_except; try exact CMDS_SRC; eauto.\n    apply STATE.\n    inv MEMLE. inv SRC1.\n    rewrite <- PRIVATE_PARENT_EQ. ss.\n    apply MEM. }\n  { inv STATE_FORGET_MEMORY. inv MEM_FORGET_MEMORY.\n    eapply step_unique_preserved_except; try exact CMDS_TGT; eauto.\n    apply STATE.\n    inv MEMLE. inv TGT1.\n    rewrite <- PRIVATE_PARENT_EQ. ss.\n    apply MEM. }\n  { eapply step_wf_lc; try exact STEP_SRC; eauto.\n    - apply STATE.\n    - apply MEM. }\n  { eapply step_wf_lc; try exact STEP_TGT; eauto.\n    - apply STATE.\n    - apply MEM. }\n  { ss. inv STEP_SRC; ss. clarify. }\n  { ss. inv STEP_TGT; ss. clarify. }\n  { Ltac apply_goal H := apply H.\n    hexploit disjoint_allocas_private_parent; try apply CMDS_SRC;\n      try (all apply_goal); eauto.\n  }\n  {\n    hexploit disjoint_allocas_private_parent; try apply CMDS_TGT;\n      try (all apply_goal); eauto.\n  }\n  { ss. }\n  { ss. }\n  { ss. }\n  { eapply step_wf_EC; try apply STEP_SRC; eauto. apply STATE. }\n  { eapply step_wf_EC; try apply STEP_TGT; eauto. apply STATE. }\n  i. des.\n\n  hexploit postcond_cmd_add_sound; try apply CONF; try eapply STEP_SRC; try eapply MEMLE;\n    try eapply STEP_TGT; try apply x1; (* needed to prohibit applying STATE *) eauto; []; ii; des.\n  esplits; eauto.\n  etransitivity; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "crellvm", "sha": "668249b88756233f96b3ef21f12993501a348afc", "save_path": "github-repos/coq/snu-sf-crellvm", "path": "github-repos/coq/snu-sf-crellvm/crellvm-668249b88756233f96b3ef21f12993501a348afc/coq/proof/SoundPostcondCmd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22113554882770903}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Bool.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import ZArith NArith Nnat Ndec Ndigits.\nFrom IntMap Require Import Allmaps.\nRequire Import Wf_nat.\n\nRequire Import BDDvar_ad_nat.\nRequire Import bdd1.\nRequire Import bdd2.\nRequire Import bdd3.\nRequire Import bdd4.\nRequire Import bdd5_1.\nRequire Import bdd5_2.\nRequire Import bdd6.\nRequire Import bdd7.\nRequire Import BDDdummy_lemma_2.\nRequire Import BDDdummy_lemma_3.\nRequire Import BDDdummy_lemma_4.\nRequire Import bdd8.\nRequire Import bdd9.\nRequire Import bdd10.\nRequire Import bdd11.\n\nDefinition is_tauto (be : bool_expr) :=\n  N.eqb BDDone\n    (fst\n       (snd (BDDof_bool_expr initBDDconfig initBDDneg_memo initBDDor_memo be))).\n\nDefinition is_valid (be : bool_expr) :=\n  forall vb : var_binding, bool_fun_of_bool_expr be vb = true.\n\nLemma initBDDor_memo_OK : BDDor_memo_OK initBDDconfig initBDDor_memo.\nProof.\n  unfold BDDor_memo_OK in |- *. intros. discriminate H.\nQed.\n\nLemma initBDDneg_memo_OK : BDDneg_memo_OK initBDDconfig initBDDneg_memo.\nProof.\n  unfold BDDneg_memo_OK in |- *. intros. discriminate H.\nQed.\n\nLemma initBDDneg_memo_OK_2 : BDDneg_memo_OK_2 initBDDconfig initBDDneg_memo.\nProof.\n  unfold BDDneg_memo_OK_2 in |- *. intros. discriminate H.\nQed.\n\nLemma is_tauto_is_correct :\n forall be : bool_expr, is_tauto be = true -> is_valid be.\nProof.\n  unfold is_tauto, is_valid in |- *. intros.\n  elim\n   (BDDof_bool_expr_correct be initBDDconfig initBDDneg_memo initBDDor_memo\n      initBDDconfig_OK initBDDneg_memo_OK_2 initBDDor_memo_OK).\n  intros. elim H1. intros. elim H3. intros. elim H5. intros. elim H7. intros.\n  rewrite <- (Neqb_complete _ _ H) in H9.\n  exact\n   (bool_fun_eq_trans _ _ _ (bool_fun_eq_symm _ _ H9)\n      (bool_fun_of_BDDone _ H0) vb).\nQed.\n\nLemma is_tauto_is_complete :\n forall be : bool_expr, is_valid be -> is_tauto be = true.\nProof.\n  unfold is_tauto, is_valid in |- *. intros.\n  elim\n   (BDDof_bool_expr_correct be initBDDconfig initBDDneg_memo initBDDor_memo\n      initBDDconfig_OK initBDDneg_memo_OK_2 initBDDor_memo_OK).\n  intros. elim H1. intros. elim H3. intros. elim H5. intros. elim H7. intros.\n  rewrite <-\n   (BDDunique\n      (fst (BDDof_bool_expr initBDDconfig initBDDneg_memo initBDDor_memo be))\n      H0 BDDone\n      (fst\n         (snd\n            (BDDof_bool_expr initBDDconfig initBDDneg_memo initBDDor_memo be))))\n   .\n  reflexivity.\n  unfold config_node_OK in |- *. unfold node_OK in |- *. right. left. reflexivity.\n  exact H2.\n  apply bool_fun_eq_symm.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_bool_expr be). exact H9.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_one). exact H.\n  apply bool_fun_eq_symm. exact (bool_fun_of_BDDone _ H0).\nQed.", "meta": {"author": "coq-contribs", "repo": "bdds", "sha": "2a66529afca7c780fa18d21ecd4f6c8d55182a6d", "save_path": "github-repos/coq/coq-contribs-bdds", "path": "github-repos/coq/coq-contribs-bdds/bdds-2a66529afca7c780fa18d21ecd4f6c8d55182a6d/tauto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22113554882770903}}
{"text": "Require Coq.Classes.EquivDec.\nRequire Coq.Lists.List.\nImport List.ListNotations.\nRequire Import Coq.Program.Program.\n\nRequire Import Leapfrog.Syntax.\nRequire Import Leapfrog.FinType.\nRequire Import Leapfrog.Sum.\nRequire Import Leapfrog.ConfRel.\nRequire Import Leapfrog.Notations.\nRequire Import Leapfrog.BisimChecker.\n\nOpen Scope p4a.\n\nNotation eth_size := 112.\nNotation ip_size := 160.\nNotation vlan_size := 32.\nNotation udp_size := 64.\n\n(*\nThis example is an undefined-value example inspired by the running\nexample in the SafeP4 paper (https://arxiv.org/pdf/1906.07223.pdf).\n*)\n\nModule ReadUndef.\n  Inductive state :=\n  | ParseEth\n  | DefaultVLAN\n  | ParseVLAN\n  | ParseIP\n  | ParseUDP.\n\n  Scheme Equality for state.\n  Global Instance state_eqdec: EquivDec.EqDec state eq := state_eq_dec.\n  Global Instance state_finite: @Finite state _ state_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Inductive header :=\n  | HdrEth\n  | HdrIP\n  | HdrVLAN\n  | HdrUDP.\n\n  Definition sz (h: header) : nat :=\n    match h with\n    | HdrEth => 112\n    | HdrIP => 160\n    | HdrVLAN => 32\n    | HdrUDP => 64\n    end.\n\n  Scheme Equality for header.\n  Global Instance header_eqdec: EquivDec.EqDec header eq := header_eq_dec.\n  Global Instance header_finite: @Finite header _ header_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Definition states (s: state) : P4A.state state sz :=\n    match s with\n    | ParseEth =>\n      {| st_op := extract(HdrEth);\n         st_trans := transition select (| (EHdr (Hdr_sz := sz) HdrEth)[0 -- 0] |) {{\n                                    [| exact #b|0 |] ==> inl DefaultVLAN ;;;\n                                    [| exact #b|1 |] ==> inl ParseVLAN ;;;\n                                    reject\n                                }}\n      |}\n    | DefaultVLAN =>\n      {| st_op := HdrVLAN <- ELit _ (Ntuple.n_tuple_repeat _ false) ;;\n                  extract(HdrIP);\n         st_trans := transition (inl ParseUDP)\n      |}\n    | ParseIP =>\n      {| st_op := extract(HdrIP);\n         st_trans := transition (inl ParseUDP)\n      |}\n    | ParseVLAN =>\n      {| st_op := extract(HdrVLAN);\n         st_trans := transition (inl ParseIP)\n      |}\n    | ParseUDP =>\n      {| st_op := extract(HdrUDP);\n         st_trans := transition select (| (EHdr (Hdr_sz := sz) HdrVLAN)[3--0] |) {{\n                                    [| exact #b|1|1|1|1 |] ==> reject ;;;\n                                    accept\n                                }}\n      |}\n    end.\n\n  Program Definition aut: Syntax.t state _ :=\n    {| t_states := states |}.\n  Solve Obligations with (destruct s || destruct h; cbv; Lia.lia).\n\nEnd ReadUndef.\n\n\nModule ReadUndefIncorrect.\n  Inductive state :=\n  | ParseEth\n  | DefaultVLAN\n  | ParseVLAN\n  | ParseIP\n  | ParseUDP.\n\n  Scheme Equality for state.\n  Global Instance state_eqdec: EquivDec.EqDec state eq := state_eq_dec.\n  Global Instance state_finite: @Finite state _ state_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Inductive header :=\n  | HdrEth\n  | HdrIP\n  | HdrVLAN\n  | HdrUDP.\n\n  Definition sz (h: header) : nat :=\n    match h with\n    | HdrEth => 112\n    | HdrIP => 160\n    | HdrVLAN => 32\n    | HdrUDP => 64\n    end.\n\n  Scheme Equality for header.\n  Global Instance header_eqdec: EquivDec.EqDec header eq := header_eq_dec.\n  Global Instance header_finite: @Finite header _ header_eq_dec.\n  Proof.\n    solve_finiteness.\n  Defined.\n\n  Definition states (s: state) : P4A.state state sz :=\n    match s with\n    | ParseEth =>\n      {| st_op := extract(HdrEth);\n         st_trans := transition select (| (EHdr (Hdr_sz := sz) HdrEth)[0 -- 0] |) {{\n                                    [| exact #b|0 |] ==> inl DefaultVLAN ;;;\n                                    [| exact #b|1 |] ==> inl ParseVLAN ;;;\n                                    reject\n                                }}\n      |}\n    | DefaultVLAN =>\n      {| st_op := extract(HdrIP);\n         st_trans := transition (inl ParseUDP)\n      |}\n    | ParseIP =>\n      {| st_op := extract(HdrIP);\n         st_trans := transition (inl ParseUDP)\n      |}\n    | ParseVLAN =>\n      {| st_op := extract(HdrVLAN);\n         st_trans := transition (inl ParseIP)\n      |}\n    | ParseUDP =>\n      {| st_op := extract(HdrUDP);\n         st_trans := transition select (| (EHdr (Hdr_sz := sz) HdrVLAN)[3--0] |) {{\n                                    [| exact #b|1|1|1|1 |] ==> reject ;;;\n                                    accept\n                                }}\n      |}\n    end.\n\n  Program Definition aut: Syntax.t state _ :=\n    {| t_states := states |}.\n  Solve Obligations with (destruct s || destruct h; cbv; Lia.lia).\n\nEnd ReadUndefIncorrect.\n", "meta": {"author": "verified-network-toolchain", "repo": "leapfrog", "sha": "fe8c4e60c9d1c2660ca2a199909bef04c81e5634", "save_path": "github-repos/coq/verified-network-toolchain-leapfrog", "path": "github-repos/coq/verified-network-toolchain-leapfrog/leapfrog-fe8c4e60c9d1c2660ca2a199909bef04c81e5634/lib/Benchmarks/SelfComparison.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22113554882770903}}
{"text": "Require Import VST.msl.ghost.\nRequire Import VST.msl.ghost_seplog.\nRequire Import VST.msl.sepalg_generators.\nRequire Import VST.veric.compcert_rmaps.\nRequire Import VST.progs.ghosts.\nRequire Import VST.progs.conclib.\nRequire Import VST.progs.invariants.\nImport Ensembles.\n\n(* Where should this sit? *)\n\nSection Timeless.\n\nDefinition except0 P := P || |>FF.\n\nDefinition timeless P := |>P |-- except0 P.\n\nDefinition timeless' (P : mpred) := forall (a a' : rmap),\n  predicates_hered.app_pred P a' -> age a a' ->\n  predicates_hered.app_pred P a.\n\nLemma timeless'_timeless : forall P, timeless' P -> timeless P.\nProof.\n  unfold timeless; intros.\n  change (_ |-- _) with (predicates_hered.derives (|>P) (P || |>FF)); intros ? HP.\n  destruct (level a) eqn: Ha.\n  - right; intros ? ?%laterR_level; omega.\n  - left.\n    destruct (levelS_age a n) as [b [Hb]]; auto.\n    specialize (HP _ (semax_lemmas.age_laterR Hb)).\n    eapply H; eauto.\nQed.\n\nLemma except0_mono : forall P Q, P |-- Q -> except0 P |-- except0 Q.\nProof.\n  intros; unfold except0.\n  apply orp_left; [apply orp_right1 | apply orp_right2]; auto.\nQed.\n\nLemma except0_intro : forall P, P |-- except0 P.\nProof.\n  intros; unfold except0.\n  apply orp_right1; auto.\nQed.\n\nLemma except0_trans : forall P, except0 (except0 P) |-- except0 P.\nProof.\n  intros; unfold except0.\n  apply orp_left; [|apply orp_right2]; auto.\nQed.\n\nLemma except0_timeless : forall P Q, P |-- except0 Q -> timeless P -> |> P |-- except0 Q.\nProof.\n  intros.\n  eapply derives_trans; eauto.\n  eapply derives_trans, except0_trans.\n  apply except0_mono; auto.\nQed.\n\nLemma except0_frame_r : forall P Q, except0 P * Q |-- except0 (P * Q).\nProof.\n  intros; unfold except0.\n  rewrite distrib_orp_sepcon.\n  apply orp_left; [apply orp_right1 | apply orp_right2]; auto.\n  eapply derives_trans; [apply sepcon_derives, now_later; apply derives_refl|].\n  rewrite <- later_sepcon; apply later_derives.\n  rewrite FF_sepcon; auto.\nQed.\n\nLemma except0_frame_l : forall P Q, P * except0 Q |-- except0 (P * Q).\nProof.\n  intros; rewrite sepcon_comm, (sepcon_comm _ Q); apply except0_frame_r.\nQed.\n\nLemma except0_bupd_elim : forall P, except0 (|==> except0 P) |-- |==> except0 P.\nProof.\n  intros; unfold except0.\n  apply orp_left; auto.\n  eapply derives_trans, bupd_intro.\n  apply orp_right2; auto.\nQed.\n\nLemma except0_bupd : forall P, except0 (|==> P) = |==> (except0 P).\nProof.\n  intro; apply pred_ext.\n  - eapply derives_trans, except0_bupd_elim.\n    apply except0_mono, bupd_mono, except0_intro.\n  - change (predicates_hered.derives (own.bupd (except0 P)) (except0 (own.bupd P))).\n    intros ??; simpl in H.\n    destruct (level a) eqn: Hl.\n    + right.\n      change ((|> FF)%pred a).\n      intros ??%laterR_level; omega.\n    + left.\n      rewrite <- Hl in *.\n      intros ? J; specialize (H _ J) as (? & ? & a' & ? & ? & ? & HP); subst.\n      do 2 eexists; eauto; do 2 eexists; eauto; repeat split; auto.\n      destruct HP as [|Hfalse]; auto.\n      destruct (levelS_age a' n) as (a'' & Hage & ?); [omega|].\n      exfalso; apply (Hfalse a'').\n      constructor; auto.\nQed.\n\nLemma except0_sepcon : forall P Q, except0 (P * Q) = except0 P * except0 Q.\nProof.\n  intros; unfold except0.\n  rewrite distrib_orp_sepcon, !distrib_orp_sepcon2.\n  apply pred_ext.\n  - apply orp_left.\n    + apply orp_right1, orp_right1; auto.\n    + apply orp_right2, orp_right2.\n      rewrite <- later_sepcon, FF_sepcon; auto.\n  - apply orp_left; apply orp_left.\n    + apply orp_right1; auto.\n    + apply orp_right2.\n      eapply derives_trans; [apply sepcon_derives, derives_refl; apply now_later|].\n      rewrite <- later_sepcon; apply later_derives; rewrite sepcon_FF; auto.\n    + apply orp_right2.\n      eapply derives_trans; [apply sepcon_derives, now_later; apply derives_refl|].\n      rewrite <- later_sepcon; apply later_derives; rewrite FF_sepcon; auto.\n    + apply orp_right2.\n      rewrite <- later_sepcon, FF_sepcon; auto.\nQed.\n\nLemma except0_andp : forall P Q, except0 (P && Q) = except0 P && except0 Q.\nProof.\n  intros; unfold except0.\n  rewrite distrib_orp_andp.\n  rewrite 2(andp_comm _ (_ || _)), !distrib_orp_andp.\n  apply pred_ext.\n  - apply orp_left.\n    + apply orp_right1, orp_right1.\n      rewrite andp_comm; auto.\n    + apply orp_right2, orp_right2.\n      rewrite <- later_andp, FF_andp; auto.\n  - apply orp_left; apply orp_left.\n    + apply orp_right1.\n      rewrite andp_comm; auto.\n    + apply orp_right2.\n      rewrite andp_comm.\n      eapply derives_trans; [apply andp_derives, derives_refl; apply now_later|].\n      rewrite <- later_andp; apply later_derives; rewrite andp_FF; auto.\n    + apply orp_right2.\n      rewrite andp_comm.\n      eapply derives_trans; [apply andp_derives, now_later; apply derives_refl|].\n      rewrite <- later_andp; apply later_derives; rewrite FF_andp; auto.\n    + apply orp_right2.\n      rewrite <- later_andp, FF_andp; auto.\nQed.\n\nLemma except0_exp : forall {A} (x : A) P, except0 (EX x : A, P x) = EX x : A, except0 (P x).\nProof.\n  intros; unfold except0; apply pred_ext.\n  - apply orp_left.\n    + Intro y; Exists y; apply orp_right1; auto.\n    + Exists x; apply orp_right2; auto.\n  - Intro y; apply orp_left; [apply orp_right1; Exists y | apply orp_right2]; auto.\nQed.\n\nLemma timeless_sepcon : forall P Q, timeless P -> timeless Q -> timeless (P * Q).\nProof.\n  unfold timeless; intros.\n  rewrite later_sepcon, except0_sepcon.\n  apply sepcon_derives; auto.\nQed.\n\nLemma timeless_andp : forall P Q, timeless P -> timeless Q -> timeless (P && Q).\nProof.\n  unfold timeless; intros.\n  rewrite later_andp, except0_andp.\n  apply andp_derives; auto.\nQed.\n\nLemma own_timeless : forall {P : Ghost} g (a : G), timeless (own g a NoneP).\nProof.\n  intros; apply timeless'_timeless.\n  intros ?? (v & ? & Hg) ?.\n  exists v; simpl in *.\n  split.\n  + intros; eapply age1_resource_at_identity; eauto.\n  + erewrite age1_ghost_of in Hg by eauto.\n    rewrite own.ghost_fmap_singleton in *.\n    apply own.ghost_fmap_singleton_inv in Hg as ([] & -> & Heq).\n    inv Heq.\n    destruct p; inv H3.\n    simpl; repeat f_equal.\n    extensionality l.\n    destruct (_f l); auto.\nQed.\n\nLemma timeless_exp : forall {A} (x : A) P, (forall x, timeless (P x)) -> timeless (EX x : A, P x).\nProof.\n  unfold timeless; intros.\n  rewrite later_exp' by auto.\n  Intro y.\n  eapply derives_trans; eauto.\n  apply except0_mono.\n  Exists y; auto.\nQed.\n\nLemma timeless_prop : forall P, timeless (!! P).\nProof.\n  intro; apply timeless'_timeless.\n  intro; auto.\nQed.\n\nLemma address_mapsto_timeless : forall m v sh p, timeless (res_predicates.address_mapsto m v sh p).\nProof.\n  intros; apply timeless'_timeless.\n  repeat intro.\n  simpl in *.\n  destruct H as (b & [? HYES] & ?); exists b; split; [split|]; auto.\n  intro b'; specialize (HYES b').\n  if_tac.\n  - destruct HYES as (rsh & Ha'); exists rsh.\n    erewrite age_to_resource_at.age_resource_at in Ha' by eauto.\n    destruct (a @ b'); try discriminate; inv Ha'.\n    destruct p0; inv H6; simpl.\n    f_equal.\n    apply proof_irr.\n  - rewrite age1_resource_at_identity; eauto.\n  - rewrite age1_ghost_of_identity; eauto.\nQed.\n\nLemma timeless_FF : timeless FF.\nProof.\n  unfold timeless, except0.\n  apply orp_right2; auto.\nQed.\n\nLemma timeless_emp : timeless emp.\nProof.\n  apply timeless'_timeless; intros ????.\n  apply all_resource_at_identity.\n  - intro.\n    eapply age1_resource_at_identity; eauto.\n    eapply resource_at_identity; eauto.\n  - eapply age1_ghost_of_identity; eauto.\n    eapply ghost_of_identity; eauto.\nQed.\n\nLemma nonlock_permission_bytes_timeless : forall sh l z,\n  timeless (res_predicates.nonlock_permission_bytes sh l z).\nProof.\n  intros; apply timeless'_timeless.\n  repeat intro.\n  simpl in *.\n  destruct H; split.\n  intro b'; specialize (H b').\n  if_tac.\n  - erewrite age1_resource_at in H by (rewrite ?resource_at_approx; eauto).\n    destruct (a @ b'); auto.\n  - rewrite age1_resource_at_identity; eauto.\n  - rewrite age1_ghost_of_identity; eauto.\nQed.\n\nLemma timeless_orp : forall P Q, timeless P -> timeless Q -> timeless (P || Q).\nProof.\n  unfold timeless, except0; intros.\n  rewrite later_orp.\n  apply orp_left; eapply derives_trans; try eassumption; apply orp_left.\n  - apply orp_right1, orp_right1; auto.\n  - apply orp_right2; auto.\n  - apply orp_right1, orp_right2; auto.\n  - apply orp_right2; auto.\nQed.\n\nLemma mapsto_timeless : forall sh t v p, timeless (mapsto sh t p v).\nProof.\n  intros; unfold mapsto.\n  destruct (access_mode t); try apply timeless_FF.\n  destruct (type_is_volatile); try apply timeless_FF.\n  destruct p; try apply timeless_FF.\n  if_tac.\n  - apply timeless_orp.\n    + apply timeless_andp; [apply timeless_prop | apply address_mapsto_timeless].\n    + apply timeless_andp; [apply timeless_prop|].\n      apply (timeless_exp Vundef); intro; apply address_mapsto_timeless.\n  - apply timeless_andp; [apply timeless_prop | apply nonlock_permission_bytes_timeless].\nQed.\n\nLemma memory_block'_timeless : forall sh n b z,\n  timeless (mapsto_memory_block.memory_block' sh n b z).\nProof.\n  induction n; simpl; intros.\n  - apply timeless_emp.\n  - apply timeless_sepcon, IHn.\n    apply mapsto_timeless.\nQed.\n\nLemma memory_block_timeless : forall sh n p,\n  timeless (memory_block sh n p).\nProof.\n  intros.\n  destruct p; try apply timeless_FF.\n  apply timeless_andp; [apply timeless_prop | apply memory_block'_timeless].\nQed.\n\nLemma struct_pred_timeless : forall {CS : compspecs} sh m f t off\n  (IH : Forall (fun it : ident * type =>\n        forall (v : reptype (t it)) (p : val),\n        timeless (data_at_rec sh (t it) v p)) m) v p,\n  timeless (struct_pred m (fun (it : ident * type) v =>\n      withspacer sh (f it + sizeof (t it)) (off it)\n        (at_offset (data_at_rec sh (t it) v) (f it))) v p).\nProof.\n  induction m; intros.\n  - apply timeless_emp.\n  - destruct a; inv IH.\n    destruct m.\n    + unfold withspacer, at_offset; simpl.\n      if_tac; auto.\n      apply timeless_sepcon; auto.\n      unfold spacer.\n      if_tac.\n      * apply timeless_emp.\n      * unfold at_offset; apply memory_block_timeless.\n    + rewrite struct_pred_cons2.\n      apply timeless_sepcon; auto.\n      unfold withspacer, at_offset; simpl.\n      if_tac; auto.\n      apply timeless_sepcon; auto.\n      unfold spacer.\n      if_tac.\n      * apply timeless_emp.\n      * unfold at_offset; apply memory_block_timeless.\nQed.\n\nLemma union_pred_timeless : forall {CS : compspecs} sh m t off\n  (IH : Forall (fun it : ident * type =>\n        forall (v : reptype (t it)) (p : val),\n        timeless (data_at_rec sh (t it) v p)) m) v p,\n  timeless (union_pred m (fun (it : ident * type) v =>\n      withspacer sh (sizeof (t it)) (off it)\n        (data_at_rec sh (t it) v)) v p).\nProof.\n  induction m; intros.\n  - apply timeless_emp.\n  - destruct a; inv IH.\n    destruct m.\n    + unfold withspacer, at_offset; simpl.\n      if_tac; auto.\n      apply timeless_sepcon; auto.\n      unfold spacer.\n      if_tac.\n      * apply timeless_emp.\n      * unfold at_offset; apply memory_block_timeless.\n    + rewrite union_pred_cons2.\n      destruct v; auto.\n      unfold withspacer, at_offset; simpl.\n      if_tac; auto.\n      apply timeless_sepcon; auto.\n      unfold spacer.\n      if_tac.\n      * apply timeless_emp.\n      * unfold at_offset; apply memory_block_timeless.\nQed.\n\nLemma data_at_rec_timeless : forall {CS : compspecs} sh t v p,\n  timeless (data_at_rec sh t v p).\nProof.\n  intros ???.\n  type_induction.type_induction t; intros; rewrite data_at_rec_eq; try apply timeless_FF.\n  - simple_if_tac; [apply memory_block_timeless | apply mapsto_timeless].\n  - simple_if_tac; [apply memory_block_timeless | apply mapsto_timeless].\n  - simple_if_tac; [apply memory_block_timeless | apply mapsto_timeless].\n  - simple_if_tac; [apply memory_block_timeless | apply mapsto_timeless].\n  - apply timeless_andp; [apply timeless_prop|].\n    rewrite Z.sub_0_r.\n    forget (Z.to_nat (Z.max 0 z)) as n.\n    set (lo := 0) at 1.\n    clearbody lo.\n    revert lo; induction n; simpl; intros.\n    + apply timeless_emp.\n    + apply timeless_sepcon, IHn.\n      unfold at_offset; apply IH.\n  - apply struct_pred_timeless; auto.\n  - apply union_pred_timeless; auto.\nQed.\n\nLemma data_at_timeless : forall {CS : compspecs} sh t v p, timeless (data_at sh t v p).\nProof.\n  intros; apply timeless_andp; [apply timeless_prop | apply data_at_rec_timeless].\nQed.\n\nEnd Timeless.\n\nSection FancyUpdates.\n\nContext {inv_names : invG}.\n\nDefinition fupd (E1 E2 : Ensemble iname) P :=\n  (wsat * ghost_set g_en E1) -* |==> except0 (wsat * ghost_set g_en E2 * P).\n\nNotation \"|={ E1 , E2 }=> P\" := (fupd E1 E2 P) (at level 62): logic.\nNotation \"|={ E }=> P\" := (fupd E E P) (at level 62): logic.\n\nLemma fupd_mono : forall E1 E2 P Q, P |-- Q -> |={E1, E2}=> P |-- |={E1, E2}=> Q.\nProof.\n  intros; unfold fupd.\n  rewrite <- wand_sepcon_adjoint.\n  rewrite sepcon_comm; eapply derives_trans; [apply modus_ponens_wand|].\n  apply bupd_mono, except0_mono; cancel.\nQed.\n\nLemma bupd_fupd : forall E P, |==> P |-- |={E}=> P.\nProof.\n  intros; unfold fupd.\n  rewrite <- wand_sepcon_adjoint.\n  eapply derives_trans; [apply bupd_frame_r|].\n  rewrite sepcon_comm; apply bupd_mono, except0_intro.\nQed.\n\nLemma fupd_frame_r : forall E1 E2 P Q, (|={E1,E2}=> P) * Q |-- |={E1,E2}=> (P * Q).\nProof.\n  intros; unfold fupd.\n  rewrite <- wand_sepcon_adjoint.\n  rewrite sepcon_comm, <- sepcon_assoc.\n  eapply derives_trans; [apply sepcon_derives, derives_refl; apply modus_ponens_wand|].\n  eapply derives_trans; [apply bupd_frame_r|].\n  apply bupd_mono.\n  rewrite <- sepcon_assoc.\n  apply except0_frame_r.\nQed.\n\nLemma fupd_intro_mask : forall E1 E2 P (Hdec : forall a, In E2 a \\/ ~In E2 a),\n  Included E2 E1 -> P |-- |={E1,E2}=> |={E2,E1}=> P.\nProof.\n  intros; unfold fupd.\n  rewrite <- wand_sepcon_adjoint.\n  eapply derives_trans, bupd_intro.\n  eapply derives_trans, except0_intro.\n  rewrite ghost_set_subset with (s' := E2) by auto.\n  cancel.\n  rewrite <- wand_sepcon_adjoint.\n  eapply derives_trans, bupd_intro.\n  eapply derives_trans, except0_intro; cancel.\nQed.\n\nLemma fupd_trans : forall E1 E2 E3 P, (|={E1,E2}=> |={E2,E3}=> P) |-- |={E1,E3}=> P.\nProof.\n  intros; unfold fupd.\n  rewrite <- wand_sepcon_adjoint.\n  rewrite sepcon_comm.\n  eapply derives_trans; [apply modus_ponens_wand|].\n  eapply derives_trans; [apply bupd_mono, except0_mono, modus_ponens_wand|].\n  eapply derives_trans, bupd_trans; apply bupd_mono.\n  apply except0_bupd_elim.\nQed.\n\nLemma fupd_timeless : forall E P, timeless P -> |> P |-- |={E}=> P.\nProof.\n  intros; unfold fupd.\n  eapply derives_trans; [apply except0_timeless; auto; apply except0_intro|].\n  rewrite <- wand_sepcon_adjoint.\n  eapply derives_trans; [apply except0_frame_r|].\n  rewrite sepcon_comm.\n  apply bupd_intro.\nQed.\n\nLemma fupd_frame_l : forall E1 E2 P Q, P * (|={E1,E2}=> Q) |-- |={E1,E2}=> (P * Q).\nProof.\n  intros; rewrite sepcon_comm, (sepcon_comm P Q); apply fupd_frame_r.\nQed.\n\n(* This is a generally useful pattern. *)\nLemma fupd_mono' : forall E1 E2 P Q (a : rmap) (Himp : (P >=> Q) (level a)),\n  app_pred (fupd E1 E2 P) a -> app_pred (fupd E1 E2 Q) a.\nProof.\n  intros.\n  assert (app_pred ((|={E1,E2}=> P * approx (S (level a)) emp)) a) as HP'.\n  { apply (fupd_frame_r _ _ _ _ a).\n    do 3 eexists; [apply join_comm, core_unit | split; auto].\n    split; [|apply core_identity].\n    rewrite level_core; auto. }\n  eapply fupd_mono in HP'; eauto.\n  change (predicates_hered.derives (P * approx (S (level a)) emp) Q).\n  intros a0 (? & ? & J & HP & [? Hemp]).\n  destruct (join_level _ _ _ J).\n  apply join_comm, Hemp in J; subst.\n  eapply Himp in HP; try apply necR_refl; auto; omega.\nQed.\n\nLemma fupd_bupd : forall E1 E2 P Q, P |-- |==> (|={E1,E2}=> Q) -> P |-- |={E1,E2}=> Q.\nProof.\n  intros; eapply derives_trans, fupd_trans; eapply derives_trans, bupd_fupd; auto.\nQed.\n\nLemma fupd_bupd_elim : forall E1 E2 P Q, P |-- |={E1,E2}=> Q -> |==> P |-- |={E1,E2}=> Q.\nProof.\n  intros; apply fupd_bupd, bupd_mono; auto.\nQed.\n\nLemma fupd_intro : forall E P, P |-- |={E}=> P.\nProof.\n  intros; eapply derives_trans, bupd_fupd; apply bupd_intro.\nQed.\n\nLemma fupd_timeless' : forall E1 E2 P Q, timeless P -> P |-- |={E1,E2}=> Q ->\n  |> P |-- |={E1,E2}=> Q.\nProof.\n  intros.\n  eapply derives_trans; [apply fupd_timeless; auto|].\n  eapply derives_trans, fupd_trans.\n  apply fupd_mono; eauto.\nQed.\n\nLemma fupd_except0_elim : forall E1 E2 P Q, P |-- |={E1,E2}=> Q -> except0 P |-- |={E1,E2}=> Q.\nProof.\n  intros.\n  unfold except0.\n  apply orp_left; auto.\n  unfold fupd.\n  rewrite <- wand_sepcon_adjoint.\n  eapply derives_trans, bupd_intro.\n  unfold except0.\n  apply orp_right2.\n  eapply derives_trans; [apply sepcon_derives, now_later; apply derives_refl|].\n  rewrite <- later_sepcon; apply later_derives.\n  rewrite FF_sepcon; auto.\nQed.\n\nLemma wsat_fupd_elim : forall P, wsat * (|={Empty_set _,Empty_set _}=> P) |-- |==> except0 (wsat * P).\nProof.\n  intros; unfold fupd.\n  rewrite <- wsat_empty_eq; apply modus_ponens_wand.\nQed.\n\nLemma fupd_prop' : forall E1 E2 E2' P Q, Included E1 E2 -> (forall a, In E1 a \\/ ~ In E1 a) ->\n  Q |-- |={E1,E2'}=> !!P ->\n  |={E1, E2}=> Q |-- |={E1}=> !!P && (|={E1, E2}=> Q).\nProof.\n  unfold fupd; intros ??????? HQ.\n  rewrite <- wand_sepcon_adjoint in *.\n  rewrite sepcon_comm; eapply derives_trans; [apply modus_ponens_wand|].\n  apply bupd_mono.\n  eapply derives_trans, except0_trans; apply except0_mono.\n  rewrite ghost_set_subset with (s' := E1) by auto.\n  rewrite (add_andp (_ * _ * Q) (except0 (!! P))) at 1.\n- eapply derives_trans; [apply andp_derives, derives_refl; apply except0_intro|].\n  rewrite <- except0_andp; apply except0_mono.\n  Intros.\n  apply andp_right; [apply prop_right; auto | cancel].\n  rewrite <- wand_sepcon_adjoint.\n  eapply derives_trans, bupd_intro; eapply derives_trans, except0_intro; cancel.\n- rewrite sepcon_comm, <- !sepcon_assoc.\n  eapply derives_trans; [apply sepcon_derives, derives_refl; rewrite sepcon_assoc; apply HQ|].\n  setoid_rewrite <- (own.bupd_prop P) at 2.\n  rewrite except0_bupd.\n  eapply derives_trans; [apply bupd_frame_r | apply bupd_mono].\n  eapply derives_trans; [apply except0_frame_r | apply except0_mono].\n  rewrite (sepcon_comm _ (!!P)), !sepcon_assoc.\n  apply derives_left_sepcon_right_corable, derives_refl.\n  change (!!P)%pred with (!!P); apply corable_prop.\nQed.\n\nLemma fupd_prop : forall E1 E2 P Q, Included E1 E2 -> (forall a, In E1 a \\/ ~ In E1 a) ->\n  Q |-- !!P ->\n  |={E1, E2}=> Q |-- |={E1}=> !!P && (|={E1, E2}=> Q).\nProof.\n  intros; eapply fupd_prop'; auto.\n  eapply derives_trans; eauto.\n  apply fupd_intro.\nQed.\n\nLemma inv_alloc : forall E P, |> P |-- |={E}=> EX i : _, invariant i P.\nProof.\n  intros; unfold fupd.\n  rewrite <- wand_sepcon_adjoint.\n  rewrite <- sepcon_assoc, (sepcon_comm _ wsat).\n  eapply derives_trans; [apply sepcon_derives, derives_refl; apply wsat_alloc|].\n  eapply derives_trans; [apply bupd_frame_r|].\n  apply bupd_mono.\n  rewrite sepcon_assoc, (sepcon_comm _ (ghost_set _ _)), <- sepcon_assoc.\n  apply except0_intro.\nQed.\n\nLemma make_inv : forall E P Q, P |-- Q -> P |-- |={E}=> EX i : _, invariant i Q.\nProof.\n  intros.\n  eapply derives_trans, inv_alloc; auto.\n  eapply derives_trans, now_later; auto.\nQed.\n\nLemma inv_close_aux : forall E (i : iname) P,\n  ghost_list(P := token_PCM) g_dis (list_singleton i (Some tt)) * invariant i P * |> P *\n  (wsat * ghost_set g_en (Subtract E i))\n  |-- |==> except0 (wsat * (ghost_set g_en (Singleton i) * ghost_set g_en (Subtract E i))).\nProof.\n  intros.\n  sep_apply (wsat_close i P).\n  eapply derives_trans; [apply bupd_frame_r | apply bupd_mono].\n  rewrite <- sepcon_assoc; apply except0_intro.\nQed.\n\nLemma inv_open : forall E i P, In E i ->\n  invariant i P |-- |={E, Subtract E i}=> (|> P) * (|>P -* |={Subtract E i, E}=> emp).\nProof.\n  intros; unfold fupd.\n  rewrite <- wand_sepcon_adjoint.\n  erewrite ghost_set_remove; eauto.\n  rewrite invariant_dup.\n  sep_apply (wsat_open i P).\n  eapply derives_trans; [apply bupd_frame_r | apply bupd_mono].\n  eapply derives_trans, except0_intro.\n  cancel.\n  rewrite <- !wand_sepcon_adjoint.\n  apply inv_close_aux.\n  { intro; omega. }\nQed.\n\n(* these last two are probably redundant *)\nLemma inv_close : forall E i P, In E i ->\n  invariant i P * |> P * ghost_list(P := exclusive_PCM _) g_dis (list_singleton i (Some tt)) |--\n  |={Subtract E i, E}=> TT.\nProof.\n  intros; unfold fupd.\n  rewrite <- !wand_sepcon_adjoint.\n  rewrite (sepcon_comm _ (ghost_list _ _)), <- 2sepcon_assoc, sepcon_assoc.\n  eapply derives_trans; [apply inv_close_aux|].\n  erewrite (ghost_set_remove _ _ E); eauto.\n  apply bupd_mono, except0_mono; cancel.\n  { intro; omega. }\nQed.\n\nLemma inv_access : forall E i P, In E i ->\n  invariant i P |-- |={E, Subtract E i}=> |> P * (|> P -* |={Subtract E i, E}=> TT).\nProof.\n  intros.\n  eapply derives_trans; [apply inv_open; eauto|].\n  apply fupd_mono; cancel.\n  apply wand_derives; auto.\n  apply fupd_mono; auto.\nQed.\n\n(* Consider putting rules for invariants and fancy updates in msl (a la ghost_seplog), and proofs\n   in veric (a la own). *)\n\nEnd FancyUpdates.\n\nNotation \"|={ E1 , E2 }=> P\" := (fupd E1 E2 P) (at level 62): logic.\nNotation \"|={ E }=> P\" := (fupd E E P) (at level 62): logic.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/progs/fupd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.221135548827709}}
{"text": "(*Require Export CatSem.PCF_order_comp.RPCF_syntax.*)\nRequire Export CatSem.PCF.PCF_RMonad.\nRequire Export CatSem.PCF_order_comp.RPCF_rep.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Transparent Obligations.\nUnset Automatic Introduction.\n\n\nProgram Instance PCFE_rep_struct : \n       PCFPO_rep_struct PCFEM (fun t => t) := {\n  app r s := PCFApp r s;\n  abs r s := PCFAbs r s;\n  rec t := PCFRec t ;\n  tttt := PCFconsts ttt ;\n  ffff := PCFconsts fff;\n  Succ := PCFconsts succ;\n  Pred := PCFconsts preds;\n  CondN := PCFconsts condN;\n  CondB := PCFconsts condB;\n  Zero := PCFconsts zero ;\n  nats m := PCFconsts (Nats m);\n  bottom t := PCFbottom t\n}.\nNext Obligation.\nProof.\n  unfold Rsubst_star_map.\n  simpl.\n  apply clos_refl_trans_1n_contains.\n  apply relorig.\n  apply app_abs.\nQed.\nNext Obligation.\nProof.\n  apply clos_refl_trans_1n_contains.\n  apply relorig.\n  constructor.\nQed.\nNext Obligation.\nProof.\n  apply clos_refl_trans_1n_contains.\n  apply relorig.\n  constructor.\nQed.\nNext Obligation.\nProof.\n  apply clos_refl_trans_1n_contains.\n  apply relorig.\n  constructor.\nQed.\nNext Obligation.\nProof.\n  apply clos_refl_trans_1n_contains.\n  apply relorig.\n  constructor.\nQed.\nNext Obligation.\nProof.\n  apply clos_refl_trans_1n_contains.\n  apply relorig.\n  constructor.\nQed.\nNext Obligation.\nProof.\n  apply clos_refl_trans_1n_contains.\n  apply relorig.\n  constructor.\nQed.\nNext Obligation.\nProof.\n  apply clos_refl_trans_1n_contains.\n  apply relorig.\n  constructor.\nQed.\nNext Obligation.\nProof.\n  apply clos_refl_trans_1n_contains.\n  apply relorig.\n  constructor.\nQed.\nNext Obligation.\nProof.\n  apply clos_refl_trans_1n_contains.\n  apply relorig.\n  constructor.\nQed.\nNext Obligation.\nProof.\n  apply clos_refl_trans_1n_contains.\n  apply relorig.\n  constructor.\nQed.\n\nDefinition PCFE_rep : PCFPO_rep := Build_PCFPO_rep PCFE_rep_struct.\n\n\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "JasonGross", "repo": "benediktahrens-coq-fossil", "sha": "834bc904a07549ac3f659e68d94a3f1c73c5b72a", "save_path": "github-repos/coq/JasonGross-benediktahrens-coq-fossil", "path": "github-repos/coq/JasonGross-benediktahrens-coq-fossil/benediktahrens-coq-fossil-834bc904a07549ac3f659e68d94a3f1c73c5b72a/PCF_order_comp/RPCF_syntax_rep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22113554882770897}}
{"text": "Require Import VST.msl.seplog.\nRequire Import VST.msl.log_normalize.\nRequire Import CertiGraph.lib.Coqlib.\nRequire Import CertiGraph.lib.Ensembles_ext.\nRequire Import CertiGraph.lib.EquivDec_ext.\nRequire Import CertiGraph.lib.List_ext.\nRequire Import CertiGraph.lib.relation_list.\nRequire Import CertiGraph.lib.Morphisms_ext.\nRequire Import CertiGraph.msl_ext.log_normalize.\nRequire Import CertiGraph.msl_ext.iter_sepcon.\nRequire Import CertiGraph.msl_ext.ramification_lemmas.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.path_lemmas.\nRequire Import CertiGraph.graph.reachable_computable.\nRequire Import CertiGraph.graph.reachable_ind.\nRequire Import CertiGraph.graph.graph_gen.\nRequire Import CertiGraph.graph.graph_relation.\nRequire Import CertiGraph.graph.subgraph2.\nRequire Import CertiGraph.graph.dag.\nRequire Import CertiGraph.graph.weak_mark_lemmas.\nRequire Import CertiGraph.graph.graph_morphism.\nRequire Import CertiGraph.graph.local_graph_copy.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import Coq.Logic.Classical.\n\nLocal Open Scope logic.\n\nClass CompactCopySetting V E M := {\n  default_v: V;\n  default_e: E;\n  default_g: M\n}.\n\nSection PointwiseGraph_Copy.\n\nContext {V E M: Type}.\nContext {SGBA: PointwiseGraphBasicAssum V E}.\nContext {CCS: CompactCopySetting V E M}.\n\nInstance MGS: WeakMarkGraph.MarkGraphSetting V.\nProof.\n  apply (WeakMarkGraph.Build_MarkGraphSetting _ (fun x => default_v <> x)).\n  intros; destruct_eq_dec default_v x; [right | left]; simpl; congruence.\nDefined.\n\nGlobal Existing Instance MGS.\n\nInstance GMS: GraphMorphismSetting V E M V E V E M :=\n  Build_GraphMorphismSetting _ _ _ _ _ _ _ _ (fun v => v) (fun e => e) default_v default_e default_g.\n\nGlobal Existing Instance GMS.\n\nNotation Graph := (LabeledGraph V E V E M).\nNotation SGraph := (PointwiseGraph V E V E).\n\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nDefinition vcopy1 x (g1 g2 g2': Graph) :=\n  g1 ~=~ g2 /\\\n  WeakMarkGraph.mark1 x g1 g2 /\\\n  LocalGraphCopy.vcopy1 x g1 g2 g2'.\n\nDefinition ecopy1 e (p1 p2: Graph * Graph) :=\n  let (g1, g1') := p1 in\n  let (g2, g2') := p2 in\n  g1 ~=~ g2 /\\\n  WeakMarkGraph.nothing (src g1 e) g1 g2 /\\\n  LocalGraphCopy.ecopy1 e (g1, g1') (g2, g2').\n\nDefinition copy x (g1 g2: Graph) (g2': Graph) :=\n  g1 ~=~ g2 /\\\n  WeakMarkGraph.mark x g1 g2 /\\\n  LocalGraphCopy.copy (WeakMarkGraph.marked g1) x g1 g2 g2'.\n\nDefinition extended_copy x (p1 p2: Graph * Graph) :=\n  let (g1, g1') := p1 in\n  let (g2, g2') := p2 in\n  g1 ~=~ g2 /\\\n  WeakMarkGraph.mark x g1 g2 /\\\n  LocalGraphCopy.extended_copy (WeakMarkGraph.marked g1) x (g1, g1') (g2, g2').\n\nDefinition edge_copy g e := relation_list ((extended_copy (dst g e)) :: (ecopy1 e) :: nil).\n\nDefinition edge_copy_list g es := relation_list (map (edge_copy g) es).\n\nLemma copy_invalid_refl: forall (g: Graph) (root: V) (src0 dst0: E -> V) (default_v: V) (default_e: E) (default_g : M),\n  ~ vvalid g root ->\n  copy root g g (empty_labeledgraph src0 dst0 default_v default_e default_g).\nProof.\n  intros.\n  split; [| split].\n  + reflexivity.\n  + apply WeakMarkGraph.mark_invalid_refl; auto.\n  + apply LocalGraphCopy.copy_invalid_refl; auto.\nQed.\n\nLemma marked_root_copy_refl: forall (g: Graph) (root: V) (src0 dst0: E -> V) (default_v: V) (default_e: E) (default_g : M),\n  WeakMarkGraph.marked g root ->\n  copy root g g (empty_labeledgraph src0 dst0 default_v default_e default_g).\nProof.\n  intros.\n  split; [| split].\n  + reflexivity.\n  + apply WeakMarkGraph.mark_marked_root_refl; auto.\n  + apply LocalGraphCopy.copy_marked_root_refl; auto.\nQed.\n\nLemma copy_vvalid_weak_eq: forall (g1 g2 g2'': Graph) x x0,\n  ~ vvalid g1 x /\\ ~ vvalid g2'' x0 \\/ x0 = LocalGraphCopy.vmap g2 x ->\n  copy x g1 g2 g2'' ->\n  Same_set (vvalid g2'') (reachable g2'' x0).\nProof.\n  intros.\n  eapply (LocalGraphCopy.copy_vvalid_weak_eq g1 g2 g2'' _ x x0); auto.\n  destruct H0 as [_ [_ ?]]; eauto.\nQed.\n\nLemma vcopy1_copied_root_valid: forall (G G1 G1': Graph) x x0,\n  vcopy1 x G G1 G1' ->\n  x0 = LocalGraphCopy.vmap G1 x ->\n  vvalid G1' x0.\nProof.\n  intros.\n  apply (LocalGraphCopy.vcopy1_copied_root_valid G G1 G1' x x0); auto.\n  destruct H as [_ [_ ?]]; eauto.\nQed.\n\nLemma extended_copy_vvalid_mono: forall (G1 G2 G1' G2': Graph) x x0,\n  extended_copy x (G1, G1') (G2, G2') ->\n  vvalid G1' x0 ->\n  vvalid G2' x0.\nProof.\n  intros.\n  eapply (LocalGraphCopy.extended_copy_vvalid_mono G1 G2 G1' G2' _ x x0); auto.\n  destruct H as [_ [_ ?]]; eauto.\nQed.\n\nLemma extended_copy_evalid_mono: forall (G1 G2 G1' G2': Graph) x e,\n  extended_copy x (G1, G1') (G2, G2') ->\n  evalid G1' e ->\n  evalid G2' e.\nProof.\n  intros.\n  eapply (LocalGraphCopy.extended_copy_evalid_mono G1 G2 G1' G2' _ x e); auto.\n  destruct H as [_ [_ ?]]; eauto.\nQed.\n\nLemma ecopy1_vvalid_mono: forall (G1 G2 G1' G2': Graph) e x0,\n  ecopy1 e (G1, G1') (G2, G2') ->\n  vvalid G1' x0 ->\n  vvalid G2' x0.\nProof.\n  intros.\n  eapply (LocalGraphCopy.ecopy1_vvalid_mono G1 G2 G1' G2' e x0); auto.\n  destruct H as [_ [_ ?]]; eauto.\nQed.\n\nLemma ecopy1_evalid_mono: forall (G1 G2 G1' G2': Graph) e e0,\n  ecopy1 e (G1, G1') (G2, G2') ->\n  evalid G1' e0 ->\n  evalid G2' e0.\nProof.\n  intros.\n  eapply (LocalGraphCopy.ecopy1_evalid_mono G1 G2 G1' G2' e e0); auto.\n  destruct H as [_ [_ ?]]; eauto.\nQed.\n\nLemma edge_copy_si: forall (g g1 g2 g1' g2': Graph) (e0: E),\n  edge_copy g e0 (g1, g1') (g2, g2') ->\n  g1 ~=~ g2.\nProof.\n  intros.\n  unfold edge_copy in H.\n  destruct_relation_list GG in H.\n  destruct GG as [G G'].\n  destruct H0 as [? _].\n  destruct H as [? _].\n  transitivity G; auto.\nQed.\n\nLemma edge_copy_spec: forall (g g1 g2 g1' g2': Graph) (root: V) (es_done: list E) (e0: E),\n  edge_copy g e0 (g1, g1') (g2, g2') ->\n  evalid g1 e0 ->\n  src g1 e0 = root ->\n  Same_set\n    (WeakMarkGraph.marked g1)\n    (let M0 := Union _ (WeakMarkGraph.marked g) (eq root) in\n     let PV1 := reachable_by_through_set g (map (dst g) es_done) (Complement _ M0) in\n     let M_rec := Union _ M0 PV1 in\n     M_rec) ->\n  LocalGraphCopy.edge_copy g root (WeakMarkGraph.marked g) (es_done, e0) (g1, g1') (g2, g2') /\\\n  WeakMarkGraph.componded root (WeakMarkGraph.mark (dst g e0)) g1 g2.\nProof.\n  intros.\n  unfold edge_copy in H.\n  destruct_relation_list gg in H; destruct gg as [g3 g3'].\n  destruct H as [? [? ?]], H3 as [? [? ?]].\n  split.\n  + cbv iota zeta in H2.\n    unfold LocalGraphCopy.edge_copy.\n    erewrite app_same_relation by (rewrite <- H2; reflexivity).\n    split_relation_list ((g3, g3') :: nil); auto.\n  + unfold WeakMarkGraph.componded.\n    apply compond_intro with g3.\n    2: {\n      erewrite <- si_src1 in H4; [| exact H3 | exact H0].\n      rewrite <- H1; auto.\n    }\n    apply compond_intro with g1; [apply WeakMarkGraph.eq_do_nothing; auto |].\n    auto.\nQed.\n\nLemma edge_copy_spec': forall root es e0 es_done es_later (g g1 g2 g3 g1' g2' g3': Graph),\n  vvalid g root ->\n  WeakMarkGraph.unmarked g root ->\n  es = es_done ++ e0 :: es_later ->\n  (forall e, In e es <-> out_edges g root e) ->\n  NoDup es ->\n  vcopy1 root g g1 g1' ->\n  relation_list\n   (map (LocalGraphCopy.edge_copy g root (WeakMarkGraph.marked g))\n     (cprefix es_done)) (g1, g1') (g2, g2') ->\n  relation_list\n   (map (fun v => WeakMarkGraph.componded root (WeakMarkGraph.mark v)) (map (dst g) es_done))\n      g1 g2->\n  edge_copy g e0 (g2, g2') (g3, g3') ->\n  LocalGraphCopy.edge_copy g root (WeakMarkGraph.marked g) (es_done, e0) (g2, g2') (g3, g3') /\\\n  WeakMarkGraph.componded root (WeakMarkGraph.mark (dst g e0)) g2 g3.\nProof.\n  intros.\n  destruct H4 as [_ [? ?]].\n  pose proof WeakMarkGraph.triple_mark1_componded_mark_list root (map (dst g) es_done) (map (dst g) (e0 :: es_later)) (map (dst g) es) g g2 H H0.\n  spec H9; [apply out_edges_step_list; auto |].\n  spec H9; [rewrite <- map_app; f_equal; auto |].\n  spec H9; [split_relation_list (g :: g1 :: g1 :: nil) |].\n    1: apply WeakMarkGraph.eq_do_nothing; auto.\n    1: auto.\n    1: apply WeakMarkGraph.eq_do_nothing; auto.\n    1: auto.\n  cbv iota zeta in H9.\n\n  pose proof LocalGraphCopy.triple_vcopy1_edge_copy_list g g1 g2 g1' g2' root es es_done (e0 :: es_later) (WeakMarkGraph.marked g) H H0 H2 H3 H1.\n  spec H10; [intro v; destruct (node_pred_dec (WeakMarkGraph.marked g) v); auto |].\n  specialize (H10 H8 H5).\n  cbv iota zeta in H10.\n\n  assert (evalid g2 e0 /\\ src g e0 = root).\n  1: {\n    destruct H10 as [_ [? _]].\n    rewrite <- (proj1 (proj2 H10)); auto.\n    assert (In e0 es) by (rewrite H1, in_app_iff; simpl; auto).\n    rewrite H2 in H11. auto.\n  }\n\n  apply edge_copy_spec; auto.\n  + tauto.\n  + destruct H10 as [_ [? _]], H11 as [? ?].\n    erewrite <- si_src2 by eauto.\n    auto.\n  + destruct H9 as [_ ?]; auto.\nQed.\n\nLemma vcopy1_edge_copy_list_spec: forall root es es_done es_later (g g1 g2 g1' g2': Graph),\n  vvalid g root ->\n  WeakMarkGraph.unmarked g root ->\n  es = es_done ++ es_later ->\n  (forall e, In e es <-> out_edges g root e) ->\n  NoDup es ->\n  vcopy1 root g g1 g1' ->\n  edge_copy_list g es_done (g1, g1') (g2, g2') ->\n  LocalGraphCopy.edge_copy_list g root es_done (WeakMarkGraph.marked g) (g1, g1') (g2, g2') /\\\n  WeakMarkGraph.componded_mark_list root (map (dst g) es_done) g1 g2.\nProof.\n  intros.\n  unfold edge_copy_list in H5.\n  rewrite map_snd_cprefix' in H5.\n  eapply relation_list_weaken_ind' with\n    (R' := fun (p: list E * E) =>\n           relation_conjunction\n            (LocalGraphCopy.edge_copy g root (WeakMarkGraph.marked g) p)\n            (fst_relation (WeakMarkGraph.componded root (WeakMarkGraph.mark (dst g (snd p))))))\n     in H5.\n  + apply relation_list_conjunction in H5.\n    destruct H5.\n    split; auto.\n    rewrite <- map_map in H6.\n    unfold fst_relation in H6.\n    apply respectful_relation_list in H6.\n    unfold respectful_relation in H6; simpl in H6.\n    unfold WeakMarkGraph.componded_mark_list.\n    rewrite map_map.\n    rewrite map_snd_cprefix'.\n    auto.\n  + clear g2 g2' H5.\n    intros.\n    clear H6.\n    unfold relation_conjunction, predicate_intersection; simpl.\n    destruct a2 as [g2 g2'], a3 as [g3 g3'].\n    unfold fst_relation, respectful_relation; simpl.\n    pose proof in_cprefix _ _ _ H5.\n    apply in_cprefix_cprefix in H5.\n    subst bs_done.\n    destruct b0 as [es_done0 e0]; simpl in H7 |- *.\n    pose proof in_cprefix' _ _ _ H6.\n    destruct H5 as [es_later0 ?].\n    apply relation_list_conjunction in H7.\n    destruct H7.\n    rewrite <- (map_map (snd) (fun e => fst_relation\n               (WeakMarkGraph.componded root\n                  (WeakMarkGraph.mark (dst g e))))) in H9.\n    rewrite map_snd_cprefix in H9.\n    rewrite <- map_map in H9.\n    unfold fst_relation in H9.\n    apply respectful_relation_list in H9.\n    unfold respectful_relation in H9; simpl in H9.\n    subst es_done.\n    rewrite <- app_assoc in H1.\n    eapply edge_copy_spec'; try eassumption.\n    rewrite map_map; auto.\nQed.\n\nLemma vcopy1_edge_copy_list_copy: forall root es (g1 g2 g3 g2' g3': Graph),\n  vvalid g1 root ->\n  WeakMarkGraph.unmarked g1 root ->\n  (forall e, In e es <-> out_edges g1 root e) ->\n  NoDup es ->\n  vcopy1 root g1 g2 g2' ->\n  edge_copy_list g1 es (g2, g2') (g3, g3') ->\n  copy root g1 g3 g3'.\nProof.\n  intros.\n  pose proof vcopy1_edge_copy_list_spec root es es nil g1 g2 g3 g2' g3' H H0 (eq_sym (app_nil_r _)) H1 H2 H3 H4.\n  destruct H5.\n  split; [| split].\n  + pose proof LocalGraphCopy.triple_vcopy1_edge_copy_list g1 g2 g3 g2' g3' root es es nil (WeakMarkGraph.marked g1) H H0 H1 H2 (eq_sym (app_nil_r _)).\n    spec H7; [intro v; destruct (node_pred_dec (WeakMarkGraph.marked g1) v); auto |].\n    destruct H3 as [_ [_ ?]].\n    specialize (H7 H3 H5).\n    destruct H7 as [_ [? _]]; auto.\n  + pose proof WeakMarkGraph.mark1_componded_mark_list_mark root (map (dst g1) es) g1 g3 H H0.\n    apply H7.\n    - apply out_edges_step_list; auto.\n    - destruct H3 as [_ [? _]].\n      split_relation_list (g1 :: g2 :: g2 :: g3 :: nil); auto; apply WeakMarkGraph.eq_do_nothing; auto.\n  + destruct H3 as [_ [_ ?]].\n    apply (LocalGraphCopy.vcopy1_edge_copy_list_copy g1 g2 g3 g2' g3' root es (WeakMarkGraph.marked g1)); auto.\n    intro v; destruct (node_pred_dec (WeakMarkGraph.marked g1) v); auto.\nQed.\n\nLemma extend_copy_emap_root: forall (g g1 g2 g3 g1' g2' g3' : Graph) root es es_done e0 es_later,\n  vvalid g root ->\n  WeakMarkGraph.unmarked g root ->\n  es = es_done ++ e0 :: es_later ->\n  (forall e : E, In e es <-> out_edges g root e) ->\n  NoDup es ->\n  vcopy1 root g g1 g1' ->\n  edge_copy_list g es_done (g1, g1') (g2, g2') ->\n  extended_copy (dst g e0) (g2, g2') (g3, g3') ->\n  map (LocalGraphCopy.emap g2) es_done = map (LocalGraphCopy.emap g3) es_done.\nProof.\n  intros.\n  destruct (vcopy1_edge_copy_list_spec root es es_done _ g g1 g2 g1' g2' H H0 H1 H2 H3 H4 H5).\n  pose proof WeakMarkGraph.triple_mark1_componded_mark_list root (map (dst g) es_done) (map (dst g) (e0 :: es_later)) (map (dst g) es) g g2 H H0.\n  spec H9; [apply out_edges_step_list; auto |].\n  spec H9; [rewrite <- map_app; f_equal; auto |].\n  spec H9; [split_relation_list (g :: g1 :: g1 :: nil) |].\n    1: apply WeakMarkGraph.eq_do_nothing; auto.\n    1: destruct H4 as [? [? ?]]; auto.\n    1: apply WeakMarkGraph.eq_do_nothing; auto.\n    1: auto.\n  cbv iota zeta in H9.\n  destruct H9 as [_ ?].\n\n  eapply LocalGraphCopy.extend_copy_emap_root; eauto.\n  + intros; destruct (node_pred_dec (WeakMarkGraph.marked g) v); auto.\n  + destruct H4 as [_ [_ ?]]; auto.\n  + intros; rewrite <- (app_same_set H9).\n    destruct (node_pred_dec (WeakMarkGraph.marked g2) v); auto.\n  + rewrite <- H9.\n    destruct H6 as [_ [_ ?]]. exact e.\nQed.\n\nLemma extended_copy_vmap_root: forall (g1 g2 g1' g2': Graph) x x0,\n  WeakMarkGraph.marked g1 x0 ->\n  extended_copy x (g1, g1') (g2, g2') ->\n  LocalGraphCopy.vmap g1 x0 = LocalGraphCopy.vmap g2 x0.\nProof.\n  intros.\n  destruct H0 as [_ [_ ?]]; eapply (LocalGraphCopy.extended_copy_vmap_root g1 g2 g1' g2' x x0); eauto.\nQed.\n\nLemma ecopy1_vmap_root: forall (g1 g2 g1' g2': Graph) e x0,\n  ecopy1 e (g1, g1') (g2, g2') ->\n  LocalGraphCopy.vmap g1 x0 = LocalGraphCopy.vmap g2 x0.\nProof.\n  intros.\n  destruct H as [_ [_ ?]].\n  apply (LocalGraphCopy.ecopy1_vmap_root g1 g2 g1' g2' e x0); auto.\nQed.\n\n\n(*\n(* might be useful for non-bigraph cases *)\nLemma vcopy1_edge_copy_list_vmap_root: forall root es es_done es_later (g g1 g2 g1' g2': Graph),\n  vvalid g root ->\n  WeakMarkGraph.unmarked g root ->\n  es = es_done ++ es_later ->\n  (forall e, In e es <-> out_edges g root e) ->\n  NoDup es ->\n  vcopy1 root g g1 g1' ->\n  edge_copy_list g es_done (g1, g1') (g2, g2') ->\n  LocalGraphCopy.vmap g1 root = LocalGraphCopy.vmap g2 root.\nProof.\n  intros.\n  destruct (vcopy1_edge_copy_list_spec root es es_done _ g g1 g2 g1' g2' H H0 H1 H2 H3 H4 H5).\n  pose proof WeakMarkGraph.triple_mark1_componded_mark_list root (map (dst g) es_done) (map (dst g) es_later) (map (dst g) es) g g2 H H0.\n  spec H8; [apply out_edges_step_list; auto |].\n  spec H8; [rewrite <- map_app; f_equal; auto |].\n  spec H8; [split_relation_list (g :: g1 :: g1 :: nil) |].\n    1: apply WeakMarkGraph.eq_do_nothing; auto.\n    1: destruct H4 as [? [? ?]]; auto.\n    1: apply WeakMarkGraph.eq_do_nothing; auto.\n    1: auto.\n  cbv iota zeta in H8.\n  destruct H8 as [_ ?].\n\n  pose proof LocalGraphCopy.triple_vcopy1_edge_copy_list g g1 g2 g1' g2' root es es_done es_later (WeakMarkGraph.marked g) H H0 H2 H3 H1.\n  spec H9; [intro v; destruct (node_pred_dec (WeakMarkGraph.marked g) v); auto |].\n  specialize (H9 (proj2 (proj2 H4)) H6).\n\n  destruct H9 as [_ [_ [_ [? _]]]].\n\nLemma vcopy1_edge_copy_list_extended_copy_vmap_root: forall root es es_done e0 es_later (g1 g2 g3 g2' g3' g4 g4'': Graph),\n  vvalid g1 root ->\n  WeakMarkGraph.unmarked g1 root ->\n  es = es_done ++ e0 :: es_later ->\n  (forall e, In e es <-> out_edges g1 root e) ->\n  NoDup es ->\n  vcopy1 root g1 g2 g2' ->\n  edge_copy_list g1 es_done (g2, g2') (g3, g3') ->\n  copy (dst g1 e0) g3 g4 g4'' ->\n  disjointed_guard (vvalid g4'') (vvalid g3') (evalid g4'') (evalid g3') ->\n  exists g4': Graph,\n  extended_copy (dst g1 e0) (g3, g3') (g4, g4') /\\\n*)\nLemma vcopy1_edge_copy_list_copy_extended_copy: forall root es es_done e0 es_later (g1 g2 g3 g2' g3' g4 g4'': Graph),\n  vvalid g1 root ->\n  WeakMarkGraph.unmarked g1 root ->\n  es = es_done ++ e0 :: es_later ->\n  (forall e, In e es <-> out_edges g1 root e) ->\n  NoDup es ->\n  vcopy1 root g1 g2 g2' ->\n  edge_copy_list g1 es_done (g2, g2') (g3, g3') ->\n  copy (dst g1 e0) g3 g4 g4'' ->\n  disjointed_guard (vvalid g4'') (vvalid g3') (evalid g4'') (evalid g3') ->\n  exists g4': Graph,\n  extended_copy (dst g1 e0) (g3, g3') (g4, g4') /\\\n  guarded_labeled_graph_equiv (vvalid g4'') (evalid g4'') g4'' g4' /\\\n  guarded_labeled_graph_equiv (vvalid g3') (evalid g3') g3' g4'.\nProof.\n  intros.\n  unfold reachable_vertices_at.\n  pose proof vcopy1_edge_copy_list_spec root es es_done _ g1 g2 g3 g2' g3' H H0 H1 H2 H3 H4 H5.\n  destruct H8.\n  pose proof LocalGraphCopy.copy_extend_copy g1 g3 g4 g3' g4'' root es es_done e0 es_later (WeakMarkGraph.marked g1) H H0 H2 H3 H1.\n  spec H10; [intro v; destruct (node_pred_dec (WeakMarkGraph.marked g1) v); auto |].\n  cbv zeta in H10.\n  pose proof WeakMarkGraph.triple_mark1_componded_mark_list root (map (dst g1) es_done) (map (dst g1) (e0 :: es_later)) (map (dst g1) es) g1 g3 H H0.\n  spec H11; [apply out_edges_step_list; auto |].\n  spec H11; [rewrite <- map_app; f_equal; auto |].\n  spec H11; [split_relation_list (g1 :: g2 :: g2 :: nil) |].\n    1: apply WeakMarkGraph.eq_do_nothing; auto.\n    1: destruct H4 as [? [? ?]]; auto.\n    1: apply WeakMarkGraph.eq_do_nothing; auto.\n    1: auto.\n  cbv iota zeta in H11.\n  destruct H11 as [_ ?].\n\n  rewrite <- H11 in H10.\n  spec H10; [destruct H6 as [? [? ?]]; auto |].\n  spec H10; [auto |].\n  spec H10; [intros v; rewrite <- (app_same_set H11); destruct (node_pred_dec (WeakMarkGraph.marked g3) v); auto |].\n  destruct H10 as [g4' [? [? ?]]].\n  rewrite <- H11 in H10.\n  exists g4'.\n  split; [| split]; auto.\n  destruct H6 as [? [? ?]]; split; [| split]; auto.\nQed.\n\nLemma copy_and_extended_copy: forall g1 g1' g2 g2' g2'' x0,\n  copy x0 g1 g2 g2'' ->\n  extended_copy x0 (g1, g1') (g2, g2') ->\n  Prop_join (vvalid g1') (vvalid g2'') (vvalid g2').\nProof.\n  intros.\n  destruct H as [_ [_ ?]].\n  destruct H0 as [_ [_ ?]].\n  destruct H as [_ [_ [_ [? [? _]]]]].\n  destruct H0 as [_ [_ [_ [? _]]]].\n  destruct H0 as [? [? _]].\n  rewrite <- H in H0.\n  rewrite <- H1 in H2.\n  auto.\nQed.\n(*\nLemma vcopy1_edge_copy_list_copy_extended_copy': forall root es es_done e0 es_later (g1 g2 g3 g2' g3' g4 g4'': Graph),\n  vvalid g1 root ->\n  WeakMarkGraph.unmarked g1 root ->\n  es = es_done ++ e0 :: es_later ->\n  (forall e, In e es <-> out_edges g1 root e) ->\n  NoDup es ->\n  vcopy1 root g1 g2 g2' ->\n  edge_copy_list g1 es_done (g2, g2') (g3, g3') ->\n  copy (dst g1 e0) g3 g4 g4'' ->\n  disjointed_guard (vvalid g4'') (vvalid g3') (evalid g4'') (evalid g3') ->\n  exists g4': Graph,\n  extended_copy (dst g1 e0) (g3, g3') (g4, g4') /\\\n  (Included (vvalid g4'') (vguard g4'') -> Included (vvalid g4'') (vguard g4') -> vertices_identical (vvalid g4'') (Graph_PointwiseGraph g4'') (Graph_PointwiseGraph g4')) /\\\n  (Included\n     (Intersection _ (vvalid g3') (fun x1 => LocalGraphCopy.vmap g2 root <> x1)) \n     (vguard g3') -> Included\n     (Intersection _ (vvalid g3') (fun x1 => LocalGraphCopy.vmap g2 root <> x1)) \n     (vguard g4') -> vertices_identical\n     (Intersection _ (vvalid g3') (fun x1 => LocalGraphCopy.vmap g2 root <> x1)) (Graph_PointwiseGraph g3') (Graph_PointwiseGraph g4')).\nProof.\n  intros.\n  unfold reachable_vertices_at.\n  pose proof vcopy1_edge_copy_list_spec root es es_done _ g1 g2 g3 g2' g3' H H0 H1 H2 H3 H4 H5.\n  destruct H8.\n  pose proof LocalGraphCopy.copy_extend_copy' g1 g3 g4 g3' g4'' root es es_done e0 es_later (WeakMarkGraph.marked g1) H H0 H2 H3 H1.\n  spec H10; [intro v; destruct (node_pred_dec (WeakMarkGraph.marked g1) v); auto |].\n  cbv zeta in H10.\n  pose proof WeakMarkGraph.triple_mark1_componded_mark_list root (map (dst g1) es_done) (map (dst g1) (e0 :: es_later)) (map (dst g1) es) g1 g3 H H0.\n  spec H11; [apply out_edges_step_list; auto |].\n  spec H11; [rewrite <- map_app; f_equal; auto |].\n  spec H11; [split_relation_list (g1 :: g2 :: g2 :: nil) |].\n    1: apply WeakMarkGraph.eq_do_nothing; auto.\n    1: destruct H4 as [? [? ?]]; auto.\n    1: apply WeakMarkGraph.eq_do_nothing; auto.\n    1: auto.\n  cbv iota zeta in H11.\n  destruct H11 as [_ ?].\n\n  rewrite <- H11 in H10.\n  spec H10; [destruct H6 as [? [? ?]]; auto |].\n  spec H10; [auto |].\n  spec H10; [intros v; rewrite <- (app_same_set H11); destruct (node_pred_dec (WeakMarkGraph.marked g3) v); auto |].\n  destruct H10 as [g4' [? [? ?]]].\n  rewrite <- H11 in H10.\n  exists g4'.\n  assert (extended_copy (dst g1 e0) (g3, g3') (g4, g4')) by (destruct H6 as [? [? ?]]; split; [| split]; auto).\n  split; [| split]; auto.\n  + intros; apply GSG_PartialGraphPreserve; auto.\n    - apply Included_refl.\n    - pose proof copy_and_extended_copy _ _ _ _ _ _ H6 H14.\n      unfold Included, Ensembles.In; intros.\n      rewrite (proj1 H17); auto.\n  + intros; apply GSG_PartialGraphPreserve; auto.\n    - apply Intersection1_Included, Included_refl.\n    - apply Intersection1_Included.\n      pose proof copy_and_extended_copy _ _ _ _ _ _ H6 H14.\n      unfold Included, Ensembles.In; intros.\n      rewrite (proj1 H17); auto.\n    - eapply si_stronger_partial_labeledgraph_simple; [| exact H13].\n      apply Intersection1_Included, Included_refl.\nQed.\n*)\nLemma vcopy1_edge_copy_list_weak_copy_extended_copy: forall {P: Graph -> Type} {NP: NormalGeneralGraph P},\n  forall root es es_done e0 es_later (g1 g2 g3 g2' g3' g4 g4'': Graph) (root0: V),\n  vvalid g1 root ->\n  WeakMarkGraph.unmarked g1 root ->\n  es = es_done ++ e0 :: es_later ->\n  (forall e, In e es <-> out_edges g1 root e) ->\n  NoDup es ->\n  vcopy1 root g1 g2 g2' ->\n  edge_copy_list g1 es_done (g2, g2') (g3, g3') ->\n  root0 = LocalGraphCopy.vmap g2 root ->\n  copy (dst g1 e0) g3 g4 g4'' ->\n  disjointed_guard (vvalid g4'') (vvalid g3') (evalid g4'') (evalid g3') ->\n  (exists Pg3': P (gpredicate_sub_labeledgraph\n                    (fun v' => root0 <> v')\n                    (fun e' => ~ In e' (map (LocalGraphCopy.emap g3) es_done)) g3'), True) ->\n  (exists Pg4'': P g4'', True) ->\n  exists g4': Graph,\n  extended_copy (dst g1 e0) (g3, g3') (g4, g4') /\\\n  (exists Pg4': P (gpredicate_sub_labeledgraph\n                    (fun v' => root0 <> v')\n                    (fun e' => ~ In e' (map (LocalGraphCopy.emap g4) es_done)) g4'), True) /\\\n  guarded_labeled_graph_equiv (vvalid g4'') (evalid g4'') g4'' g4' /\\\n  guarded_labeled_graph_equiv (vvalid g3') (evalid g3') g3' g4'.\nProof.\n  intros.\n  pose proof vcopy1_edge_copy_list_copy_extended_copy root es es_done e0 es_later g1 g2 g3 g2' g3' g4 g4''.\n  repeat (spec H11; [auto |]).\n  destruct H11 as [g4' [? [? ?]]].\n  exists g4'; split; [| split; [| split]]; auto.\n  destruct H9 as [? _], H10 as [? _].\n  apply (lge_preserved _\n          (gpredicate_sub_labeledgraph\n            (Intersection _ (vvalid g3') (fun v' : V => root0 <> v'))\n            (Intersection _ (evalid g3') (fun e' : E => ~ In e' (map (LocalGraphCopy.emap g3) es_done))) g4')) in x.\n  2: {\n    etransitivity.\n    + apply gpredicate_sub_labeledgraph_equiv.\n      - symmetry; apply Intersection_absort_left.\n        apply Intersection1_Included, Included_refl.\n      - symmetry; apply Intersection_absort_left.\n        apply Intersection1_Included, Included_refl.\n    + eapply stronger_gpredicate_sub_labeledgraph_simple; [| | eauto].\n      - apply Intersection1_Included, Included_refl.\n      - apply Intersection1_Included, Included_refl.\n  }\n  apply (lge_preserved _ (gpredicate_sub_labeledgraph (vvalid g4'') (evalid g4'') g4')) in x0.\n  2: {\n    etransitivity.\n    + symmetry; apply gpredicate_sub_labeledgraph_self.\n    + eapply stronger_gpredicate_sub_labeledgraph_simple; [| | eauto].\n      - apply Included_refl.\n      - apply Included_refl.\n  }\n  eexists; auto.\n  apply (lge_preserved\n          (gpredicate_sub_labeledgraph\n            (Intersection _ (vvalid g4') (fun v' : V => root0 <> v'))\n            (Intersection _ (evalid g4') (fun e' : E => ~ In e' (map (LocalGraphCopy.emap g4) es_done))) g4')).\n  1: {\n    apply gpredicate_sub_labeledgraph_equiv.\n    + apply Intersection_absort_left.\n      apply Intersection1_Included, Included_refl.\n    + apply Intersection_absort_left.\n      apply Intersection1_Included, Included_refl.\n  }\n  eapply join_preserved; [| | exact x | exact x0].\n  + destruct H11 as [_ [_ HH]].\n    destruct HH as [_ [_ [_ [HH _]]]].\n    destruct H7 as [_ [_ ?]].\n    destruct HH as [? _].\n    destruct H7 as [_ [_ [_ [? _]]]].\n    rewrite <- H7 in H9.\n    apply Prop_join_shrink1; auto.\n    destruct (vcopy1_edge_copy_list_spec root _ _ _ _ _ _ _ _ H H0 H1 H2 H3 H4 H5).\n    eapply LocalGraphCopy.edge_copy_list_vvalid_mono in H10; [exact H10 |].\n    destruct H4 as [_ [_ ?]].\n    eapply LocalGraphCopy.vcopy1_copied_root_valid in H4; eauto.\n  + replace (map (@LocalGraphCopy.emap V E V E (@SGBA_VE V E SGBA)\n                    (@SGBA_EE V E SGBA) V E M V E M GMS g4) es_done) with (map (LocalGraphCopy.emap g3) es_done)\n      by (apply (extend_copy_emap_root g1 g2 g3 g4 g2' g3' g4' root es es_done e0 es_later); auto).\n    destruct H11 as [_ [_ HH]].\n    destruct HH as [_ [_ [_ [HH _]]]].\n    destruct H7 as [_ [_ ?]].\n    destruct HH as [_ [? _]].\n    destruct H7 as [_ [_ [_ [_ [? _]]]]].\n    rewrite <- H7 in H9.\n    apply Prop_join_shrink; auto.\n    unfold Included, Ensembles.In.\n    intros e ? ?.\n    destruct H9 as [_ ?].\n    apply (H9 e); auto.\n    destruct (vcopy1_edge_copy_list_spec root _ _ _ _ _ _ _ _ H H0 H1 H2 H3 H4 H5).\n    eapply (LocalGraphCopy.vcopy1_edge_copy_list_mapped_root_edge_evalid g1 g2 g3 g2' g3'); eauto.\n      1: intros; destruct (node_pred_dec (WeakMarkGraph.marked g1) v); auto.\n      1: destruct H4 as [? [? ?]]; auto.\nQed.\n\nContext {GV GE: Type}.\nContext {SGC: PointwiseGraphConstructor V E V E M GV GE}.\nContext {L_SGC: Local_PointwiseGraphConstructor V E V E M GV GE}.\n\nLemma vcopy1_edge_copy_list_weak_copy_extended_copy': forall {P: Graph -> Type} {NP: NormalGeneralGraph P},\n  forall root es es_done e0 es_later (g1 g2 g3 g2' g3' g4 g4'': Graph) (root0: V),\n  vvalid g1 root ->\n  WeakMarkGraph.unmarked g1 root ->\n  es = es_done ++ e0 :: es_later ->\n  (forall e, In e es <-> out_edges g1 root e) ->\n  NoDup es ->\n  vcopy1 root g1 g2 g2' ->\n  edge_copy_list g1 es_done (g2, g2') (g3, g3') ->\n  root0 = LocalGraphCopy.vmap g2 root ->\n  copy (dst g1 e0) g3 g4 g4'' ->\n  disjointed_guard (vvalid g4'') (vvalid g3') (evalid g4'') (evalid g3') ->\n  (exists Pg3': P (gpredicate_sub_labeledgraph\n                    (fun v' => root0 <> v')\n                    (fun e' => ~ In e' (map (LocalGraphCopy.emap g3) es_done)) g3'), True) ->\n  (exists Pg4'': P g4'', True) ->\n  exists g4': Graph,\n  extended_copy (dst g1 e0) (g3, g3') (g4, g4') /\\\n  (exists Pg4': P (gpredicate_sub_labeledgraph\n                    (fun v' => root0 <> v')\n                    (fun e' => ~ In e' (map (LocalGraphCopy.emap g4) es_done)) g4'), True) /\\\n  (Included (vvalid g4'') (vguard g4'') -> Included (vvalid g4'') (vguard g4') -> vertices_identical (vvalid g4'') (Graph_PointwiseGraph g4'') (Graph_PointwiseGraph g4')) /\\\n  (Included\n     (Intersection _ (vvalid g3') (fun x1 => LocalGraphCopy.vmap g2 root <> x1)) \n     (vguard g3') -> Included\n     (Intersection _ (vvalid g3') (fun x1 => LocalGraphCopy.vmap g2 root <> x1)) \n     (vguard g4') -> vertices_identical\n     (Intersection _ (vvalid g3') (fun x1 => LocalGraphCopy.vmap g2 root <> x1)) (Graph_PointwiseGraph g3') (Graph_PointwiseGraph g4')).\nProof.\n  intros.\n  pose proof vcopy1_edge_copy_list_copy_extended_copy root es es_done e0 es_later g1 g2 g3 g2' g3' g4 g4''.\n  repeat (spec H11; [auto |]).\n  destruct H11 as [g4' [? [? ?]]].\n  exists g4'; split; [| split]; auto.\n  1: {\n    destruct H9 as [? _], H10 as [? _].\n    apply (lge_preserved _\n            (gpredicate_sub_labeledgraph\n              (Intersection _ (vvalid g3') (fun v' : V => root0 <> v'))\n              (Intersection _ (evalid g3') (fun e' : E => ~ In e' (map (LocalGraphCopy.emap g3) es_done))) g4')) in x.\n    2: {\n      etransitivity.\n      + apply gpredicate_sub_labeledgraph_equiv.\n        - symmetry; apply Intersection_absort_left.\n          apply Intersection1_Included, Included_refl.\n        - symmetry; apply Intersection_absort_left.\n          apply Intersection1_Included, Included_refl.\n      + eapply stronger_gpredicate_sub_labeledgraph_simple; [| | eauto].\n        - apply Intersection1_Included, Included_refl.\n        - apply Intersection1_Included, Included_refl.\n    }\n    apply (lge_preserved _ (gpredicate_sub_labeledgraph (vvalid g4'') (evalid g4'') g4')) in x0.\n    2: {\n      etransitivity.\n      + symmetry; apply gpredicate_sub_labeledgraph_self.\n      + eapply stronger_gpredicate_sub_labeledgraph_simple; [| | eauto].\n        - apply Included_refl.\n        - apply Included_refl.\n    }\n    eexists; auto.\n    apply (lge_preserved\n            (gpredicate_sub_labeledgraph\n              (Intersection _ (vvalid g4') (fun v' : V => root0 <> v'))\n              (Intersection _ (evalid g4') (fun e' : E => ~ In e' (map (LocalGraphCopy.emap g4) es_done))) g4')).\n    1: {\n      apply gpredicate_sub_labeledgraph_equiv.\n      + apply Intersection_absort_left.\n        apply Intersection1_Included, Included_refl.\n      + apply Intersection_absort_left.\n        apply Intersection1_Included, Included_refl.\n    }\n    eapply join_preserved; [| | exact x | exact x0].\n    + destruct H11 as [_ [_ HH]].\n      destruct HH as [_ [_ [_ [HH _]]]].\n      destruct H7 as [_ [_ ?]].\n      destruct HH as [? _].\n      destruct H7 as [_ [_ [_ [? _]]]].\n      rewrite <- H7 in H9.\n      apply Prop_join_shrink1; auto.\n      destruct (vcopy1_edge_copy_list_spec root _ _ _ _ _ _ _ _ H H0 H1 H2 H3 H4 H5).\n      eapply LocalGraphCopy.edge_copy_list_vvalid_mono in H10; [exact H10 |].\n      destruct H4 as [_ [_ ?]].\n      eapply LocalGraphCopy.vcopy1_copied_root_valid in H4; eauto.\n    + replace (map (@LocalGraphCopy.emap V E V E (@SGBA_VE V E SGBA)\n                      (@SGBA_EE V E SGBA) V E M V E M GMS g4) es_done) with (map (LocalGraphCopy.emap g3) es_done)\n        by (apply (extend_copy_emap_root g1 g2 g3 g4 g2' g3' g4' root es es_done e0 es_later); auto).\n      destruct H11 as [_ [_ HH]].\n      destruct HH as [_ [_ [_ [HH _]]]].\n      destruct H7 as [_ [_ ?]].\n      destruct HH as [_ [? _]].\n      destruct H7 as [_ [_ [_ [_ [? _]]]]].\n      rewrite <- H7 in H9.\n      apply Prop_join_shrink; auto.\n      unfold Included, Ensembles.In.\n      intros e ? ?.\n      destruct H9 as [_ ?].\n      apply (H9 e); auto.\n      destruct (vcopy1_edge_copy_list_spec root _ _ _ _ _ _ _ _ H H0 H1 H2 H3 H4 H5).\n      eapply (LocalGraphCopy.vcopy1_edge_copy_list_mapped_root_edge_evalid g1 g2 g3 g2' g3'); eauto.\n        1: intros; destruct (node_pred_dec (WeakMarkGraph.marked g1) v); auto.\n        1: destruct H4 as [? [? ?]]; auto.\n  }\n  1: {\n    intros.\n    pose proof vcopy1_edge_copy_list_spec root es es_done (e0 :: es_later) g1 g2 g3 g2' g3' H H0 H1 H2 H3 H4 H5.\n    destruct H14.\n    pose proof WeakMarkGraph.triple_mark1_componded_mark_list root (map (dst g1) es_done) (map (dst g1) (e0 :: es_later)) (map (dst g1) es) g1 g3 H H0.\n    spec H16; [apply out_edges_step_list; auto |].\n    spec H16; [rewrite <- map_app; f_equal; auto |].\n    spec H16; [split_relation_list (g1 :: g2 :: g2 :: nil) |].\n      1: apply WeakMarkGraph.eq_do_nothing; auto.\n      1: destruct H4 as [? [? ?]]; auto.\n      1: apply WeakMarkGraph.eq_do_nothing; auto.\n      1: auto.\n    cbv iota zeta in H16.\n    destruct H16 as [_ ?].\n\n    pose proof LocalGraphCopy.vcopy1_edge_copy_list_copy_and_copy_extend g1 g2 g3 g4 g2' g3' g4'' g4' root es es_done e0 es_later (WeakMarkGraph.marked g1) H H0 H2 H3 H1.\n    spec H17; [intros; apply decidable_prop_decidable; apply node_pred_dec |].\n    spec H17; [destruct H4 as [? [? ?]]; auto |].\n    spec H17; [auto |].\n    cbv zeta in H17.\n    rewrite <- H16 in H17.\n    spec H17; [destruct H7 as [? [? ?]]; auto |].\n    spec H17; [auto |].\n    spec H17; [intros; rewrite <- (app_same_set H16); apply decidable_prop_decidable; apply node_pred_dec |].\n    spec H17; [destruct H11 as [? [? ?]]; auto |].\n    spec H17; [auto |].\n    spec H17; [auto |].\n    destruct H17 as [? [? [? ?]]].\n    split; intros; apply GSG_PartialGraphPreserve; auto.\n    + apply Included_refl.\n    + destruct H17.\n      intros ? ?; unfold Ensembles.In; rewrite H17; tauto.\n    + apply Intersection1_Included, Included_refl.\n    + apply Intersection1_Included.\n      destruct H17.\n      intros ? ?; unfold Ensembles.In; rewrite H17; tauto.\n    + eapply si_stronger_partial_labeledgraph_simple; [| eassumption].\n      apply Intersection1_Included, Included_refl.\n  }\nQed.\n\nEnd PointwiseGraph_Copy.\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/msl_application/Graph_Copy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22113554882770897}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.client_lemmas.\nImport LiftNotation.\nLocal Open Scope logic.\n\n(*\nLemma gvar_globals_only:\n  forall i v rho, gvar i v rho -> gvar i v (globals_only rho).\nProof.\nunfold gvar; intros.\nunfold Map.get in *.\ndestruct (ve_of rho i) as [[? ?]|] eqn:?; try contradiction.\nunfold globals_only.\nsimpl. auto.\nQed.\n#[export] Hint Resolve gvar_globals_only.\n*)\n\nLtac safe_auto_with_closed :=\n   (* won't instantiate evars by accident *)\n match goal with |- ?A =>\n          solve [first [has_evar A | auto 50 with closed]]\n end.\n\nLemma closed_env_set:\n forall {B} i v (P: environ -> B) rho,\n     closed_wrt_vars (eq i) P ->\n     P (env_set rho i v) = P rho.\nProof.\n intros. hnf in H.\n symmetry; destruct rho; apply H.\n intros; simpl; destruct (ident_eq i i0). left; auto.\n right; rewrite Map.gso; auto.\nQed.\nHint Rewrite @closed_env_set using safe_auto_with_closed : norm2.\n\nLemma subst_eval_id_eq:\n forall id v, subst id v (eval_id id) = v.\nProof. unfold subst, eval_id; intros. extensionality rho.\n    unfold force_val, env_set; simpl. rewrite Map.gss; auto.\nQed.\n\nLemma subst_eval_id_neq:\n  forall id v j, id<>j -> subst id v (eval_id j) = eval_id j.\nProof.\n    unfold subst, eval_id; intros. extensionality rho.\n    unfold force_val, env_set; simpl. rewrite Map.gso; auto.\nQed.\n\nHint Rewrite subst_eval_id_eq : subst.\nHint Rewrite subst_eval_id_neq using safe_auto_with_closed : subst.\n\n(*\nLemma subst_temp_eq:\n  forall i v w, subst i `v (temp i w) = `(eq w v).\nProof.\nunfold temp; intros; autorewrite with subst.\nextensionality rho; unfold_lift. reflexivity.\nQed.\n\nLemma subst_temp_neq:\n  forall i j v w, i<>j -> subst i v (temp j w) = temp j w.\nProof.\nunfold temp; intros. autorewrite with subst.\nf_equal. apply subst_eval_id_neq; auto.\nQed.\n\nLemma subst_var:\n   forall i j v t w,  subst i v (var j t w) = var j t w.\nProof.\nunfold var; intros; autorewrite with subst; auto.\nQed.\n\nHint Rewrite subst_var : subst.\nHint Rewrite subst_temp_eq : subst.\nHint Rewrite subst_temp_neq using safe_auto_with_closed : subst.\n*)\n\nFixpoint subst_eval_expr  {cs: compspecs}  (j: ident) (v: environ -> val) (e: expr) : environ -> val :=\n match e with\n | Econst_int i ty => `(Vint i)\n | Econst_long i ty => `(Vlong i)\n | Econst_float f ty => `(Vfloat f)\n | Econst_single f ty => `(Vsingle f)\n | Etempvar id ty => if eqb_ident j id then v else eval_id id\n | Eaddrof a ty => subst_eval_lvalue j v a\n | Eunop op a ty =>  `(eval_unop op (typeof a)) (subst_eval_expr j v a)\n | Ebinop op a1 a2 ty =>\n                  `(eval_binop op (typeof a1) (typeof a2)) (subst_eval_expr j v a1) (subst_eval_expr j v a2)\n | Ecast a ty => `(eval_cast (typeof a) ty) (subst_eval_expr j v a)\n | Evar id ty => eval_var id ty\n | Ederef a ty => subst_eval_expr j v a\n | Efield a i ty => `(eval_field (typeof a) i) (subst_eval_lvalue j v a)\n | Esizeof t ty => `(if complete_type cenv_cs t\n                             then Vptrofs (Ptrofs.repr (sizeof t))\n                             else Vundef)\n | Ealignof t ty => `(if complete_type cenv_cs t\n                              then Vptrofs (Ptrofs.repr (alignof t))\n                              else Vundef)\n end\n\n with subst_eval_lvalue {cs: compspecs} (j: ident) (v: environ -> val) (e: expr) : environ -> val :=\n match e with\n | Evar id ty => eval_var id ty\n | Ederef a ty => subst_eval_expr j v a\n | Efield a i ty => `(eval_field (typeof a) i) (subst_eval_lvalue j v a)\n | _  => `Vundef\n end.\n\nLemma subst_eval_expr_eq:\n    forall {cs: compspecs} j v e, subst j v (eval_expr e) = subst_eval_expr j v e\nwith subst_eval_lvalue_eq:\n    forall {cs: compspecs} j v e, subst j v (eval_lvalue e) = subst_eval_lvalue j v e.\nProof.\n-\nintros cs j v; clear subst_eval_expr_eq; induction e; intros; simpl; try auto.\n + unfold eqb_ident.\n     unfold subst, eval_id, env_set, te_of. extensionality rho.\n     pose proof (Pos.eqb_spec j i).\n     destruct H. subst. rewrite Map.gss. reflexivity.\n     rewrite Map.gso; auto.\n  + \n     rewrite <- IHe; clear IHe.\n     unfold_lift.\n     extensionality rho; unfold subst.\n     reflexivity.\n  + \n     unfold_lift.\n     extensionality rho; unfold subst.\n     rewrite <- IHe1, <- IHe2; reflexivity.\n   +\n      unfold_lift.\n      extensionality rho; unfold subst.\n      rewrite <- IHe; reflexivity.\n   +\n      unfold_lift.\n      rewrite <- subst_eval_lvalue_eq.\n      extensionality rho; unfold subst.\n      auto.\n-\nintros Delta j v; clear subst_eval_lvalue_eq; induction e; intros; simpl; try auto.\nunfold_lift.\nextensionality rho; unfold subst.\nrewrite <- IHe.\nf_equal.\nQed.\n\nHint Rewrite @subst_eval_expr_eq @subst_eval_lvalue_eq : subst.\n\n\nLemma closed_wrt_subst:\n  forall {A} id e (P: environ -> A), closed_wrt_vars (eq id) P -> subst id e P = P.\nProof.\nintros.\nunfold subst, closed_wrt_vars in *.\nextensionality rho.\nsymmetry.\napply H.\nintros.\ndestruct (eq_dec id i); auto.\nright.\nrewrite Map.gso; auto.\nQed.\n\nLemma closed_wrt_map_subst:\n   forall {A: Type} id e (Q: list (environ -> A)),\n         Forall (closed_wrt_vars (eq id)) Q ->\n         map (subst id e) Q = Q.\nProof.\ninduction Q; intros.\nsimpl; auto.\ninv H.\nsimpl; f_equal; auto.\napply closed_wrt_subst; auto.\nQed.\nHint Rewrite @closed_wrt_map_subst using safe_auto_with_closed : subst.\nHint Rewrite @closed_wrt_subst using safe_auto_with_closed : subst.\n\nLemma closed_wrt_map_subst':\n   forall {A: Type} id e (Q: list (environ -> A)),\n         Forall (closed_wrt_vars (eq id)) Q ->\n         @map (LiftEnviron A) _ (subst id e) Q = Q.\nProof.\napply @closed_wrt_map_subst.\nQed.\n\n(*Hint Rewrite @closed_wrt_map_subst' using safe_auto_with_closed : norm.*)\nHint Rewrite @closed_wrt_map_subst' using safe_auto_with_closed : subst.\nLemma closed_wrt_subst_eval_expr:\n  forall {cs: compspecs} j v e,\n   closed_wrt_vars (eq j) (eval_expr e) ->\n   subst_eval_expr j v e = eval_expr e.\nProof.\nintros; rewrite <- subst_eval_expr_eq.\napply closed_wrt_subst; auto.\nQed.\nLemma closed_wrt_subst_eval_lvalue:\n  forall {cs: compspecs} j v e,\n   closed_wrt_vars (eq j) (eval_lvalue e) ->\n   subst_eval_lvalue j v e = eval_lvalue e.\nProof.\nintros; rewrite <- subst_eval_lvalue_eq.\napply closed_wrt_subst; auto.\nQed.\nHint Rewrite @closed_wrt_subst_eval_expr using solve [auto 50 with closed] : subst.\nHint Rewrite @closed_wrt_subst_eval_lvalue using solve [auto 50 with closed] : subst.\n\n#[export] Hint Unfold closed_wrt_modvars : closed.\n\nLemma closed_wrt_local: forall S P, closed_wrt_vars S P -> closed_wrt_vars S (local P).\nProof.\nintros.\nhnf in H|-*; intros.\nspecialize (H _ _ H0).\nunfold local, lift1.\nf_equal; auto.\nQed.\n\nLemma closed_wrtl_local: forall S P, closed_wrt_lvars S P -> closed_wrt_lvars S (local P).\nProof.\nintros.\nhnf in H|-*; intros.\nspecialize (H _ _ H0).\nunfold local, lift1.\nf_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_local closed_wrtl_local : closed.\n\nLemma closed_wrt_lift0: forall {A} S (Q: A), closed_wrt_vars S (lift0 Q).\nProof.\nintros.\nintros ? ? ?.\nunfold lift0; auto.\nQed.\nLemma closed_wrtl_lift0: forall {A} S (Q: A), closed_wrt_lvars S (lift0 Q).\nProof.\nintros.\nintros ? ? ?.\nunfold lift0; auto.\nQed.\n#[export] Hint Resolve closed_wrt_lift0 closed_wrtl_lift0 : closed.\n\nLemma closed_wrt_lift0C: forall {B} S (Q: B),\n   closed_wrt_vars S (@liftx (LiftEnviron B) Q).\nProof.\nintros.\nintros ? ? ?.\nunfold_lift; auto.\nQed.\nLemma closed_wrtl_lift0C: forall {B} S (Q: B),\n   closed_wrt_lvars S (@liftx (LiftEnviron B) Q).\nProof.\nintros.\nintros ? ? ?.\nunfold_lift; auto.\nQed.\n#[export] Hint Resolve closed_wrt_lift0C closed_wrtl_lift0C: closed.\n\nLemma closed_wrt_lift1: forall {A}{B} S (f: A -> B) P,\n        closed_wrt_vars S P ->\n        closed_wrt_vars S (lift1 f P).\nProof.\nintros.\nintros ? ? ?. specialize (H _ _ H0).\nunfold lift1; f_equal; auto.\nQed.\nLemma closed_wrtl_lift1: forall {A}{B} S (f: A -> B) P,\n        closed_wrt_lvars S P ->\n        closed_wrt_lvars S (lift1 f P).\nProof.\nintros.\nintros ? ? ?. specialize (H _ _ H0).\nunfold lift1; f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_lift1 closed_wrtl_lift1 : closed.\n\nLemma closed_wrt_lift1C: forall {A}{B} S (f: A -> B) P,\n        closed_wrt_vars S P ->\n        closed_wrt_vars S (@liftx (Tarrow A (LiftEnviron B)) f P).\nProof.\nintros.\nintros ? ? ?. specialize (H _ _ H0).\nunfold_lift; f_equal; auto.\nQed.\nLemma closed_wrtl_lift1C: forall {A}{B} S (f: A -> B) P,\n        closed_wrt_lvars S P ->\n        closed_wrt_lvars S (@liftx (Tarrow A (LiftEnviron B)) f P).\nProof.\nintros.\nintros ? ? ?. specialize (H _ _ H0).\nunfold_lift; f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_lift1C closed_wrtl_lift1C : closed.\n\nLemma closed_wrt_lift2: forall {A1 A2}{B} S (f: A1 -> A2 -> B) P1 P2,\n        closed_wrt_vars S P1 ->\n        closed_wrt_vars S P2 ->\n        closed_wrt_vars S (lift2 f P1 P2).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H1).\nspecialize (H0 _ _ H1).\nunfold lift2; f_equal; auto.\nQed.\nLemma closed_wrtl_lift2: forall {A1 A2}{B} S (f: A1 -> A2 -> B) P1 P2,\n        closed_wrt_lvars S P1 ->\n        closed_wrt_lvars S P2 ->\n        closed_wrt_lvars S (lift2 f P1 P2).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H1).\nspecialize (H0 _ _ H1).\nunfold lift2; f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_lift2 closed_wrtl_lift2 : closed.\n\nLemma closed_wrt_lift2C: forall {A1 A2}{B} S (f: A1 -> A2 -> B) P1 P2,\n        closed_wrt_vars S P1 ->\n        closed_wrt_vars S P2 ->\n        closed_wrt_vars S (@liftx (Tarrow A1 (Tarrow A2 (LiftEnviron B))) f P1 P2).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H1).\nspecialize (H0 _ _ H1).\nunfold_lift; f_equal; auto.\nQed.\nLemma closed_wrtl_lift2C: forall {A1 A2}{B} S (f: A1 -> A2 -> B) P1 P2,\n        closed_wrt_lvars S P1 ->\n        closed_wrt_lvars S P2 ->\n        closed_wrt_lvars S (@liftx (Tarrow A1 (Tarrow A2 (LiftEnviron B))) f P1 P2).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H1).\nspecialize (H0 _ _ H1).\nunfold_lift; f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_lift2C closed_wrtl_lift2C : closed.\n\nLemma closed_wrt_lift3: forall {A1 A2 A3}{B} S (f: A1 -> A2 -> A3 -> B) P1 P2 P3,\n        closed_wrt_vars S P1 ->\n        closed_wrt_vars S P2 ->\n        closed_wrt_vars S P3 ->\n        closed_wrt_vars S (lift3 f P1 P2 P3).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H2).\nspecialize (H0 _ _ H2).\nspecialize (H1 _ _ H2).\nunfold lift3; f_equal; auto.\nQed.\nLemma closed_wrtl_lift3: forall {A1 A2 A3}{B} S (f: A1 -> A2 -> A3 -> B) P1 P2 P3,\n        closed_wrt_lvars S P1 ->\n        closed_wrt_lvars S P2 ->\n        closed_wrt_lvars S P3 ->\n        closed_wrt_lvars S (lift3 f P1 P2 P3).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H2).\nspecialize (H0 _ _ H2).\nspecialize (H1 _ _ H2).\nunfold lift3; f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_lift3 closed_wrtl_lift3 : closed.\n\nLemma closed_wrt_lift3C: forall {A1 A2 A3}{B} S (f: A1 -> A2 -> A3 -> B) P1 P2 P3,\n        closed_wrt_vars S P1 ->\n        closed_wrt_vars S P2 ->\n        closed_wrt_vars S P3 ->\n        closed_wrt_vars S (@liftx (Tarrow A1 (Tarrow A2 (Tarrow A3 (LiftEnviron B)))) f P1 P2 P3).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H2).\nspecialize (H0 _ _ H2).\nspecialize (H1 _ _ H2).\nunfold_lift. f_equal; auto.\nQed.\n\nLemma closed_wrtl_lift3C: forall {A1 A2 A3}{B} S (f: A1 -> A2 -> A3 -> B) P1 P2 P3,\n        closed_wrt_lvars S P1 ->\n        closed_wrt_lvars S P2 ->\n        closed_wrt_lvars S P3 ->\n        closed_wrt_lvars S (@liftx (Tarrow A1 (Tarrow A2 (Tarrow A3 (LiftEnviron B)))) f P1 P2 P3).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H2).\nspecialize (H0 _ _ H2).\nspecialize (H1 _ _ H2).\nunfold_lift. f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_lift3C closed_wrtl_lift3C : closed.\n\nLemma closed_wrt_lift4: forall {A1 A2 A3 A4}{B} S (f: A1 -> A2 -> A3 -> A4 -> B)\n       P1 P2 P3 P4,\n        closed_wrt_vars S P1 ->\n        closed_wrt_vars S P2 ->\n        closed_wrt_vars S P3 ->\n        closed_wrt_vars S P4 ->\n        closed_wrt_vars S (lift4 f P1 P2 P3 P4).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H3).\nspecialize (H0 _ _ H3).\nspecialize (H1 _ _ H3).\nspecialize (H2 _ _ H3).\nunfold lift4; f_equal; auto.\nQed.\nLemma closed_wrtl_lift4: forall {A1 A2 A3 A4}{B} S (f: A1 -> A2 -> A3 -> A4 -> B)\n       P1 P2 P3 P4,\n        closed_wrt_lvars S P1 ->\n        closed_wrt_lvars S P2 ->\n        closed_wrt_lvars S P3 ->\n        closed_wrt_lvars S P4 ->\n        closed_wrt_lvars S (lift4 f P1 P2 P3 P4).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H3).\nspecialize (H0 _ _ H3).\nspecialize (H1 _ _ H3).\nspecialize (H2 _ _ H3).\nunfold lift4; f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_lift4  closed_wrtl_lift4 : closed.\n\nLemma closed_wrt_lift4C: forall {A1 A2 A3 A4}{B} S (f: A1 -> A2 -> A3 -> A4 -> B) P1 P2 P3 P4,\n        closed_wrt_vars S P1 ->\n        closed_wrt_vars S P2 ->\n        closed_wrt_vars S P3 ->\n        closed_wrt_vars S P4 ->\n        closed_wrt_vars S (@liftx (Tarrow A1 (Tarrow A2 (Tarrow A3 (Tarrow A4 (LiftEnviron B))))) f P1 P2 P3 P4).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H3).\nspecialize (H0 _ _ H3).\nspecialize (H1 _ _ H3).\nspecialize (H2 _ _ H3).\nunfold liftx; simpl.\nunfold lift. f_equal; auto.\nQed.\nLemma closed_wrtl_lift4C: forall {A1 A2 A3 A4}{B} S (f: A1 -> A2 -> A3 -> A4 -> B) P1 P2 P3 P4,\n        closed_wrt_lvars S P1 ->\n        closed_wrt_lvars S P2 ->\n        closed_wrt_lvars S P3 ->\n        closed_wrt_lvars S P4 ->\n        closed_wrt_lvars S (@liftx (Tarrow A1 (Tarrow A2 (Tarrow A3 (Tarrow A4 (LiftEnviron B))))) f P1 P2 P3 P4).\nProof.\nintros.\nintros ? ? ?.\nspecialize (H _ _ H3).\nspecialize (H0 _ _ H3).\nspecialize (H1 _ _ H3).\nspecialize (H2 _ _ H3).\nunfold liftx; simpl.\nunfold lift. f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_lift4C closed_wrtl_lift4C : closed.\n\nLemma closed_wrt_const:\n forall A (P: A) S, closed_wrt_vars S (fun rho: environ => P).\nProof.\nintros. hnf; intros.\nsimpl. auto.\nQed.\nLemma closed_wrtl_const:\n forall A (P: A) S, closed_wrt_lvars S (fun rho: environ => P).\nProof.\nintros. hnf; intros.\nsimpl. auto.\nQed.\n#[export] Hint Resolve closed_wrt_const closed_wrtl_const : closed.\n\nLemma closed_wrt_eval_var:\n  forall S id t, closed_wrt_vars S (eval_var id t).\nProof.\nunfold closed_wrt_vars, eval_var; intros.\nsimpl.\nauto.\nQed.\n#[export] Hint Resolve closed_wrt_eval_var : closed.\nLemma closed_wrtl_eval_var:\n  forall S id t, ~ S id -> closed_wrt_lvars S (eval_var id t).\nProof.\nunfold closed_wrt_lvars, eval_var; intros.\nsimpl.\ndestruct (H0 id); [contradiction | ].\nrewrite <- H1; auto.\nQed.\n#[export] Hint Resolve closed_wrtl_eval_var : closed.\n\n(*\nLemma closed_wrt_var:\n  forall S id t v, closed_wrt_vars S (var id t v).\nProof.\nunfold var; intros.\nauto with closed.\nQed.\n#[export] Hint Resolve closed_wrt_var : closed.\n\nLemma closed_wrtl_var:\n forall S id t v, ~ S id -> closed_wrt_lvars S (var id t v).\nProof.\nunfold var; intros; auto with closed.\nQed.\n#[export] Hint Resolve closed_wrtl_var : closed.\n*)\n\nLemma closed_wrt_lvar:\n  forall S id t v, closed_wrt_vars S (locald_denote (lvar id t v)).\nProof.\nintros.\nhnf; intros; simpl.\ndestruct (Map.get (ve_of rho) id); auto.\nQed.\n#[export] Hint Resolve closed_wrt_lvar : closed.\n\nLemma closed_wrt_gvars:\n  forall S gv, closed_wrt_vars S (locald_denote (gvars gv)).\nProof.\nintros.\nhnf; intros; simpl. reflexivity.\nQed.\n#[export] Hint Resolve closed_wrt_gvars : closed.\n\nLemma closed_wrtl_gvars:\n  forall S gv, closed_wrt_lvars S (locald_denote (gvars gv)).\nProof.\nintros.\nhnf; intros; simpl. reflexivity.\nQed.\n#[export] Hint Resolve closed_wrtl_gvars : closed.\n\nLemma closed_wrtl_lvar:\n forall  {cs: compspecs} S id t v,\n    ~ S id -> closed_wrt_lvars S (locald_denote (lvar id t v)).\nProof.\nintros.\nhnf; intros; simpl.\nunfold lvar_denote.\ndestruct (H0 id); try contradiction.\nrewrite H1; auto.\nQed.\n#[export] Hint Resolve closed_wrtl_lvar : closed.\n\nDefinition expr_closed_wrt_lvars (S: ident -> Prop) (e: expr) : Prop :=\n  forall (cs: compspecs) rho ve',\n     (forall i, S i \\/ Map.get (ve_of rho) i = Map.get ve' i) ->\n     eval_expr e rho = eval_expr e (mkEnviron (ge_of rho) ve' (te_of rho)).\n\nDefinition lvalue_closed_wrt_lvars (S: ident -> Prop) (e: expr) : Prop :=\n  forall (cs: compspecs) rho ve',\n     (forall i, S i \\/ Map.get (ve_of rho) i = Map.get ve' i) ->\n     eval_lvalue e rho = eval_lvalue e (mkEnviron (ge_of rho) ve'  (te_of rho)).\n\nLemma closed_wrt_cmp_ptr : forall {cs: compspecs} S e1 e2 c,\n  expr_closed_wrt_vars S e1 ->\n  expr_closed_wrt_vars S e2 ->\n  closed_wrt_vars S (`(cmp_ptr_no_mem c) (eval_expr e1) (eval_expr e2)).\nProof.\nintros.\nunfold closed_wrt_vars. intros.\nsuper_unfold_lift.\nunfold expr_closed_wrt_vars in *.\nspecialize (H rho te' H1).\nspecialize (H0 rho te' H1).\nunfold cmp_ptr_no_mem. rewrite H0. rewrite H.\nreflexivity.\nQed.\nLemma closed_wrtl_cmp_ptr : forall {cs: compspecs} S e1 e2 c,\n  expr_closed_wrt_lvars S e1 ->\n  expr_closed_wrt_lvars S e2 ->\n  closed_wrt_lvars S (`(cmp_ptr_no_mem c) (eval_expr e1) (eval_expr e2)).\nProof.\nintros.\nunfold closed_wrt_lvars. intros.\nsuper_unfold_lift.\nunfold expr_closed_wrt_lvars in *.\nspecialize (H cs rho ve' H1).\nspecialize (H0 cs rho ve' H1).\nunfold cmp_ptr_no_mem. rewrite H0. rewrite H.\nreflexivity.\nQed.\n#[export] Hint Resolve closed_wrt_cmp_ptr closed_wrtl_cmp_ptr: closed.\n\nLemma closed_wrt_eval_id: forall S i,\n    ~ S i -> closed_wrt_vars S (eval_id i).\nProof.\nintros.\nintros ? ? ?.\nunfold eval_id, force_val.\nsimpl.\ndestruct (H0 i).\ncontradiction.\nrewrite H1; auto.\nQed.\nLemma closed_wrtl_eval_id: forall S i,\n    closed_wrt_lvars S (eval_id i).\nProof.\nintros.\nintros ? ? ?.\nunfold eval_id, force_val.\nsimpl. auto.\nQed.\n#[export] Hint Resolve closed_wrt_eval_id closed_wrtl_eval_id : closed.\n\nLemma closed_wrt_temp: forall S i v,\n    ~ S i -> closed_wrt_vars S (locald_denote (temp i v)).\nProof.\nintros.\nhnf; simpl; intros.\nunfold_lift.\nunfold eval_id; simpl.\ndestruct (H0 i).\ncontradiction.\nrewrite H1; auto.\nQed.\n\nLemma closed_wrtl_temp: forall S i v,\n    closed_wrt_lvars S (locald_denote (temp i v)).\nProof.\nintros.\nunfold locald_denote.\nhnf; intros. simpl.\nunfold eval_id; simpl. auto.\nQed.\n#[export] Hint Resolve closed_wrt_temp closed_wrtl_temp : closed.\n\nLemma closed_wrt_get_result1 :\n  forall (S: ident -> Prop) i , ~ S i -> closed_wrt_vars S (get_result1 i).\nProof.\nintros. unfold get_result1. simpl.\n hnf; intros.\n simpl. f_equal.\napply (closed_wrt_eval_id _ _ H); auto.\nQed.\nLemma closed_wrtl_get_result1 :\n  forall (S: ident -> Prop) i , closed_wrt_lvars S (get_result1 i).\nProof.\nintros. unfold get_result1. simpl.\n hnf; intros.\n simpl. f_equal.\nQed.\n#[export] Hint Resolve closed_wrt_get_result1 closed_wrtl_get_result1 : closed.\n\nLemma closed_wrt_tc_FF:\n forall {cs: compspecs} S e, closed_wrt_vars S (denote_tc_assert (tc_FF e)).\nProof.\n intros. hnf; intros. reflexivity.\nQed.\nLemma closed_wrtl_tc_FF:\n forall {cs: compspecs} S e, closed_wrt_lvars S (denote_tc_assert (tc_FF e)).\nProof.\n intros. hnf; intros. reflexivity.\nQed.\n#[export] Hint Resolve closed_wrt_tc_FF closed_wrtl_tc_FF : closed.\n\nLemma closed_wrt_tc_TT:\n forall {cs: compspecs} S, closed_wrt_vars S (denote_tc_assert (tc_TT)).\nProof.\n intros. hnf; intros. reflexivity.\nQed.\nLemma closed_wrtl_tc_TT:\n forall {cs: compspecs} S, closed_wrt_lvars S (denote_tc_assert (tc_TT)).\nProof.\n intros. hnf; intros. reflexivity.\nQed.\n#[export] Hint Resolve closed_wrt_tc_TT closed_wrtl_tc_TT : closed.\n\nLemma closed_wrt_andp: forall S (P Q: environ->mpred),\n  closed_wrt_vars S P -> closed_wrt_vars S Q ->\n  closed_wrt_vars S (P && Q).\nProof.\nintros; hnf in *; intros.\nsimpl. f_equal; eauto.\nQed.\nLemma closed_wrtl_andp: forall S (P Q: environ->mpred),\n  closed_wrt_lvars S P -> closed_wrt_lvars S Q ->\n  closed_wrt_lvars S (P && Q).\nProof.\nintros; hnf in *; intros.\nsimpl. f_equal; eauto.\nQed.\n#[export] Hint Resolve closed_wrt_andp closed_wrtl_andp : closed.\n\nLemma closed_wrt_exp: forall {A} S (P: A -> environ->mpred),\n  (forall a, closed_wrt_vars S (P a)) ->\n  closed_wrt_vars S (exp P).\nProof.\nintros; hnf in *; intros.\nsimpl. apply exp_congr. intros a.\nspecialize (H a).\nhnf in H.\neauto.\nQed.\n\nLemma closed_wrtl_exp: forall {A} S (P: A -> environ->mpred),\n  (forall a, closed_wrt_lvars S (P a)) ->\n  closed_wrt_lvars S (exp P).\nProof.\nintros; hnf in *; intros.\nsimpl. apply exp_congr. intros a.\nspecialize (H a).\nhnf in H.\neauto.\nQed.\n#[export] Hint Resolve closed_wrt_exp closed_wrtl_exp : closed.\n\nLemma closed_wrt_imp: forall S (P Q: environ->mpred),\n  closed_wrt_vars S P -> closed_wrt_vars S Q ->\n  closed_wrt_vars S (P --> Q).\nProof.\nintros; hnf in *; intros.\nsimpl. f_equal; eauto.\nQed.\nLemma closed_wrtl_imp: forall S (P Q: environ->mpred),\n  closed_wrt_lvars S P -> closed_wrt_lvars S Q ->\n  closed_wrt_lvars S (P --> Q).\nProof.\nintros; hnf in *; intros.\nsimpl. f_equal; eauto.\nQed.\n#[export] Hint Resolve closed_wrt_imp closed_wrtl_imp : closed.\n\nLemma closed_wrt_sepcon: forall S (P Q: environ->mpred),\n  closed_wrt_vars S P -> closed_wrt_vars S Q ->\n  closed_wrt_vars S (P * Q).\nProof.\nintros; hnf in *; intros.\nsimpl. f_equal; eauto.\nQed.\nLemma closed_wrtl_sepcon: forall S (P Q: environ->mpred),\n  closed_wrt_lvars S P -> closed_wrt_lvars S Q ->\n  closed_wrt_lvars S (P * Q).\nProof.\nintros; hnf in *; intros.\nsimpl. f_equal; eauto.\nQed.\n#[export] Hint Resolve closed_wrt_sepcon closed_wrtl_sepcon : closed.\n\nLemma closed_wrt_emp {A} {ND: NatDed A} {SL: SepLog A}:\n  forall S, closed_wrt_vars S emp.\nProof. repeat intro. reflexivity. Qed.\nLemma closed_wrtl_emp {A} {ND: NatDed A} {SL: SepLog A}:\n  forall S, closed_wrt_lvars S emp.\nProof. repeat intro. reflexivity. Qed.\n\nDefinition closed_wrt_emp_mpred := @closed_wrt_emp mpred Nveric Sveric.\nDefinition closed_wrtl_emp_mpred := @closed_wrtl_emp mpred Nveric Sveric.\n#[export] Hint Resolve closed_wrt_emp_mpred closed_wrtl_emp_mpred  : closed.\n\nLemma closed_wrt_allp: forall A S P,\n  (forall x: A, closed_wrt_vars S (P x)) ->\n  closed_wrt_vars S (allp P).\nProof.\nintros; hnf in *; intros.\nsimpl.\napply pred_ext; apply allp_right; intro x; apply (allp_left _ x);\nspecialize (H x rho te' H0);\napply derives_refl'; congruence.\nQed.\nLemma closed_wrtl_allp: forall A S P,\n  (forall x: A, closed_wrt_lvars S (P x)) ->\n  closed_wrt_lvars S (allp P).\nProof.\nintros; hnf in *; intros.\nsimpl.\napply pred_ext; apply allp_right; intro x; apply (allp_left _ x);\nspecialize (H x rho ve' H0);\napply derives_refl'; congruence.\nQed.\n#[export] Hint Resolve closed_wrt_allp closed_wrtl_allp : closed.\n(*DEAD CODE?\nLemma closed_wrt_globvars:\n  forall S gv v, closed_wrt_vars S (globvars2pred gv v).\nProof.\nintros.\nunfold globvars2pred.\nhnf; intros. unfold lift2. f_equal.\ninduction v; simpl map; auto with closed.\nsimpl.\nf_equal; auto.\nunfold globvar2pred; destruct a; simpl.\ndestruct (gvar_volatile g) eqn:?; auto.\nforget (readonly2share (gvar_readonly g)) as sh.\nforget (gv i) as j.\nrevert j; induction (gvar_init g); intros; simpl; f_equal; auto.\nQed.\n\nLemma closed_wrtl_globvars:\n  forall S gv v, closed_wrt_lvars S (globvars2pred gv v).\nProof.\nintros.\nunfold globvars2pred.\nhnf; intros. unfold lift2. f_equal.\ninduction v; simpl map; auto with closed.\nsimpl.\nf_equal; auto.\nunfold globvar2pred; destruct a; simpl.\ndestruct (gvar_volatile g) eqn:?; auto.\nforget (readonly2share (gvar_readonly g)) as sh.\nforget (gv i) as j.\nrevert j; induction (gvar_init g); intros; simpl; f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_globvars closed_wrtl_globvars: closed.\n\n\nLemma closed_wrt_main_pre:\n  forall {Z} prog (z : Z) v S, closed_wrt_vars S (main_pre prog z v).\nProof.\nintros. unfold main_pre. apply closed_wrt_sepcon; [apply closed_wrt_globvars | apply closed_wrt_const].\nQed.\nLemma closed_wrtl_main_pre:\n  forall {Z} prog (z : Z) v S, closed_wrt_lvars S (main_pre prog z v).\nProof.\nintros. unfold main_pre. apply closed_wrtl_sepcon; [apply closed_wrtl_globvars | apply closed_wrtl_const].\nQed.\n#[export] Hint Resolve closed_wrt_main_pre closed_wrtl_main_pre : closed.\n*)\nLemma closed_wrt_not1:\n  forall (i j: ident),\n   i<>j ->\n   not (eq i j).\nProof.\nintros.\nhnf.\nintros; subst; congruence.\nQed.\n#[export] Hint Resolve closed_wrt_not1 : closed.\n\nLemma closed_wrt_tc_andp:\n  forall {cs: compspecs} S a b,\n  closed_wrt_vars S (denote_tc_assert a) ->\n  closed_wrt_vars S (denote_tc_assert b) ->\n  closed_wrt_vars S (denote_tc_assert (tc_andp a b)).\nProof.\n intros.\n hnf; intros.\n repeat rewrite denote_tc_assert_andp; simpl; f_equal; auto.\nQed.\n\n\nLemma closed_wrt_tc_orp:\n  forall {cs: compspecs} S a b,\n  closed_wrt_vars S (denote_tc_assert a) ->\n  closed_wrt_vars S (denote_tc_assert b) ->\n  closed_wrt_vars S (denote_tc_assert (tc_orp a b)).\nProof.\n intros.\n hnf; intros.\n repeat rewrite denote_tc_assert_orp; simpl.\n f_equal; auto.\nQed.\n\nLemma closed_wrt_tc_bool:\n  forall {cs: compspecs} S b e, closed_wrt_vars S (denote_tc_assert (tc_bool b e)).\nProof.\n intros.\n hnf; intros.\n destruct b; simpl; auto.\nQed.\n\nLemma closed_wrt_tc_int_or_ptr_type:\n  forall {cs: compspecs} S t, \n  closed_wrt_vars S (denote_tc_assert (tc_int_or_ptr_type t)).\nProof.\n intros.\n apply closed_wrt_tc_bool.\nQed.\n\n#[export] Hint Resolve closed_wrt_tc_andp closed_wrt_tc_orp closed_wrt_tc_bool\n              closed_wrt_tc_int_or_ptr_type : closed.\n\nLemma closed_wrtl_tc_andp:\n  forall {cs: compspecs} S a b,\n  closed_wrt_lvars S (denote_tc_assert a) ->\n  closed_wrt_lvars S (denote_tc_assert b) ->\n  closed_wrt_lvars S (denote_tc_assert (tc_andp a b)).\nProof.\n intros.\n hnf; intros.\n repeat rewrite denote_tc_assert_andp; simpl; f_equal; auto.\nQed.\n\n\nLemma closed_wrtl_tc_orp:\n  forall {cs: compspecs} S a b,\n  closed_wrt_lvars S (denote_tc_assert a) ->\n  closed_wrt_lvars S (denote_tc_assert b) ->\n  closed_wrt_lvars S (denote_tc_assert (tc_orp a b)).\nProof.\n intros.\n hnf; intros.\n repeat rewrite denote_tc_assert_orp; simpl.\n f_equal; auto.\nQed.\nLemma closed_wrtl_tc_bool:\n  forall {cs: compspecs} S b e, closed_wrt_lvars S (denote_tc_assert (tc_bool b e)).\nProof.\n intros.\n hnf; intros.\n destruct b; simpl; auto.\nQed.\n#[export] Hint Resolve closed_wrtl_tc_andp closed_wrtl_tc_orp closed_wrtl_tc_bool : closed.\n\nLemma closed_wrt_tc_test_eq:\n  forall {cs: compspecs} S e e',\n          expr_closed_wrt_vars S e ->\n          expr_closed_wrt_vars S e' ->\n  closed_wrt_vars S\n     (denote_tc_assert\n        (tc_test_eq e e')).\nProof.\nintros.\nhnf; intros.\nrewrite !binop_lemmas2.denote_tc_assert_test_eq'.\nsimpl. unfold_lift. rewrite H, H0; auto.\nQed.\nLemma closed_wrtl_tc_test_eq:\n  forall {cs: compspecs} S e e',\n          expr_closed_wrt_lvars S e ->\n          expr_closed_wrt_lvars S e' ->\n  closed_wrt_lvars S\n     (denote_tc_assert\n        (tc_test_eq e e')).\nProof.\nintros.\nhnf; intros.\nrewrite !binop_lemmas2.denote_tc_assert_test_eq'.\nsimpl. unfold_lift. rewrite H, H0; auto.\nQed.\n#[export] Hint Resolve  closed_wrt_tc_test_eq  closed_wrtl_tc_test_eq : closed.\n\nLemma closed_wrt_tc_test_order:\n  forall {cs: compspecs} S e e',\n          expr_closed_wrt_vars S e ->\n          expr_closed_wrt_vars S e' ->\n  closed_wrt_vars S\n     (denote_tc_assert\n        (tc_test_order e e')).\nProof.\nintros.\nhnf; intros.\nrewrite !binop_lemmas2.denote_tc_assert_test_order'.\nsimpl. unfold_lift. rewrite H, H0; auto.\nQed.\nLemma closed_wrtl_tc_test_order:\n  forall {cs: compspecs} S e e',\n          expr_closed_wrt_lvars S e ->\n          expr_closed_wrt_lvars S e' ->\n  closed_wrt_lvars S\n     (denote_tc_assert\n        (tc_test_order e e')).\nProof.\nintros.\nhnf; intros.\nrewrite !binop_lemmas2.denote_tc_assert_test_order'.\nsimpl. unfold_lift. rewrite H, H0; auto.\nQed.\n#[export] Hint Resolve  closed_wrt_tc_test_order  closed_wrtl_tc_test_order : closed.\n\nLemma expr_closed_const_int:\n  forall {cs: compspecs} S i t, expr_closed_wrt_vars S (Econst_int i t).\nProof.\nintros. unfold expr_closed_wrt_vars. simpl; intros.\nsuper_unfold_lift. auto.\nQed.\nLemma expr_closedl_const_int:\n  forall S i t, expr_closed_wrt_lvars S (Econst_int i t).\nProof.\nintros. unfold expr_closed_wrt_lvars. simpl; intros.\nsuper_unfold_lift. auto.\nQed.\n#[export] Hint Resolve expr_closed_const_int expr_closedl_const_int : closed.\n\n\nLemma closed_wrt_tc_iszero:\n  forall {cs: compspecs}  S e, expr_closed_wrt_vars S e ->\n    closed_wrt_vars S (expr2.denote_tc_assert (tc_iszero e)).\nProof.\nintros.\nrewrite binop_lemmas2.denote_tc_assert_iszero'.\nsimpl.\nhnf; intros. hnf in H. specialize (H _ _ H0).\nunfold_lift. rewrite <- H. auto.\nQed.\n#[export] Hint Resolve closed_wrt_tc_iszero : closed.\n\nLemma closed_wrtl_tc_iszero:\n  forall {cs: compspecs}  S e, expr_closed_wrt_lvars S e ->\n    closed_wrt_lvars S (expr2.denote_tc_assert (tc_iszero e)).\nProof.\nintros.\nrewrite binop_lemmas2.denote_tc_assert_iszero'.\nhnf; intros. specialize (H _ _ _ H0).\nsimpl. unfold_lift; simpl. rewrite <- H; auto.\nQed.\n#[export] Hint Resolve closed_wrtl_tc_iszero : closed.\n\nLemma closed_wrt_tc_isptr:\n forall {cs: compspecs} S e,\n     expr_closed_wrt_vars S e ->\n     closed_wrt_vars S (denote_tc_assert (tc_isptr e)).\nProof.\n intros.\n hnf; intros.\n specialize (H _ _ H0).\n simpl. unfold_lift. f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_tc_isptr : closed.\n\nLemma closed_wrtl_tc_isptr:\n forall {cs: compspecs} S e,\n     expr_closed_wrt_lvars S e ->\n     closed_wrt_lvars S (denote_tc_assert (tc_isptr e)).\nProof.\n intros.\n hnf; intros. specialize (H _ _ _ H0).\n simpl. unfold_lift; simpl. rewrite <- H; auto.\nQed.\n#[export] Hint Resolve closed_wrtl_tc_isptr : closed.\n\nLemma closed_wrt_tc_isint:\n forall {cs: compspecs} S e,\n     expr_closed_wrt_vars S e ->\n     closed_wrt_vars S (denote_tc_assert (tc_isint e)).\nProof.\n intros.\n hnf; intros.\n specialize (H _ _ H0).\n simpl. unfold_lift. f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_tc_isint : closed.\n\nLemma closed_wrtl_tc_isint:\n forall {cs: compspecs} S e,\n     expr_closed_wrt_lvars S e ->\n     closed_wrt_lvars S (denote_tc_assert (tc_isint e)).\nProof.\n intros.\n hnf; intros.\n specialize (H _ _ _ H0).\n simpl. unfold_lift. f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrtl_tc_isint : closed.\n\nLemma closed_wrt_tc_islong:\n forall {cs: compspecs} S e,\n     expr_closed_wrt_vars S e ->\n     closed_wrt_vars S (denote_tc_assert (tc_islong e)).\nProof.\n intros.\n hnf; intros.\n specialize (H _ _ H0).\n simpl. unfold_lift. f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_tc_islong : closed.\n\nLemma closed_wrtl_tc_islong:\n forall {cs: compspecs} S e,\n     expr_closed_wrt_lvars S e ->\n     closed_wrt_lvars S (denote_tc_assert (tc_islong e)).\nProof.\n intros.\n hnf; intros.\n specialize (H _ _ _ H0).\n simpl. unfold_lift. f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrtl_tc_islong : closed.\n\nLemma closed_wrt_isCastResultType:\n  forall {cs: compspecs} S e t t0,\n          expr_closed_wrt_vars S e ->\n          closed_wrt_vars S\n                 (denote_tc_assert (isCastResultType (implicit_deref t) t0 e)).\nProof.\n intros.\nrewrite expr_lemmas3.isCastR.\ndestruct (classify_cast (implicit_deref t) t0) eqn:?;\n  simpl; auto with closed;\n try solve [destruct t0 as [ | [ | | | ] [|] | [|] | [ | ] |  | | | | ]; simpl;\n                auto with closed; try reflexivity];\n  auto with closed;\n repeat simple_if_tac; try destruct si2; simpl; auto with closed.\n apply closed_wrt_tc_test_eq; auto with closed.\n hnf; intros. reflexivity.\nQed.\n\nLemma closed_wrtl_tc_Zge:\n  forall  {cs: compspecs} S e i,\n   expr_closed_wrt_lvars S e ->\n   closed_wrt_lvars S  (denote_tc_assert (tc_Zge e i)).\nProof.\nintros.\nhnf; intros. simpl. unfold_lift. rewrite (H _ _ _ H0). auto.\nQed.\n\nLemma closed_wrtl_tc_Zle:\n  forall  {cs: compspecs} S e i,\n   expr_closed_wrt_lvars S e ->\n   closed_wrt_lvars S  (denote_tc_assert (tc_Zle e i)).\nProof.\nintros.\nhnf; intros. simpl. unfold_lift. rewrite (H _ _ _ H0). auto.\nQed.\n#[export] Hint Resolve closed_wrtl_tc_Zge closed_wrtl_tc_Zle : closed.\n\nLemma closed_wrtl_isCastResultType:\n  forall {cs: compspecs} S e t t0,\n          expr_closed_wrt_lvars S e ->\n          closed_wrt_lvars S\n                 (denote_tc_assert (isCastResultType (implicit_deref t) t0 e)).\nProof.\n intros.\nrewrite expr_lemmas3.isCastR.\n\nchange expr2.denote_tc_assert with denote_tc_assert.\ndestruct (classify_cast (implicit_deref t) t0) eqn:?;\n  auto with closed;\n try solve [destruct t0 as [ | [ | | | ] [|] | [|] | [ | ] |  | | | | ]; simpl;\n                auto with closed; try reflexivity];\nrepeat simple_if_tac;  auto with closed;\n try destruct si2; auto with closed.\n apply closed_wrtl_tc_test_eq; auto with closed.\n hnf; intros. reflexivity.\nQed.\n\n#[export] Hint Resolve closed_wrt_isCastResultType closed_wrtl_isCastResultType : closed.\n\nLemma closed_wrt_tc_temp_id :\n  forall {cs: compspecs} Delta S e id t, expr_closed_wrt_vars S e ->\n                         expr_closed_wrt_vars S (Etempvar id t) ->\n             closed_wrt_vars S (tc_temp_id id t Delta e).\nProof.\nintros.\nunfold tc_temp_id.\nunfold typecheck_temp_id.\ndestruct ( (temp_types Delta) ! id) eqn:?; try destruct p; simpl; auto with closed.\nQed.\n\nLemma closed_wrtl_tc_temp_id :\n  forall {cs: compspecs} Delta S e id t, expr_closed_wrt_lvars S e ->\n                         expr_closed_wrt_lvars S (Etempvar id t) ->\n             closed_wrt_lvars S (tc_temp_id id t Delta e).\nProof.\nintros.\nunfold tc_temp_id.\nunfold typecheck_temp_id.\ndestruct ( (temp_types Delta) ! id) eqn:?; try destruct p; simpl; auto with closed.\nQed.\n\n#[export] Hint Resolve closed_wrt_tc_temp_id closed_wrtl_tc_temp_id : closed.\n\nLemma expr_closed_tempvar:\n forall {cs: compspecs} S i t, ~ S i -> expr_closed_wrt_vars S (Etempvar i t).\nProof.\nintros.\nhnf; intros.\nsimpl. unfold eval_id. f_equal.\ndestruct (H0 i); auto.\ncontradiction.\nQed.\nLemma expr_closedl_tempvar:\n forall S i t, expr_closed_wrt_lvars S (Etempvar i t).\nProof.\nintros.\nhnf; intros.\nsimpl. unfold eval_id. f_equal.\nQed.\n#[export] Hint Resolve expr_closed_tempvar expr_closedl_tempvar : closed.\n\n#[export] Hint Extern 1 (not (@eq ident _ _)) => (let Hx := fresh in intro Hx; inversion Hx) : closed.\n\nLemma expr_closed_cast: forall {cs: compspecs} S e t,\n     expr_closed_wrt_vars S e ->\n     expr_closed_wrt_vars S (Ecast e t).\nProof.\n unfold expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift.\n destruct (H rho te' H0); auto.\nQed.\nLemma expr_closedl_cast: forall S e t,\n     expr_closed_wrt_lvars S e ->\n     expr_closed_wrt_lvars S (Ecast e t).\nProof.\n unfold expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift.\n destruct (H cs rho ve' H0); auto.\nQed.\n#[export] Hint Resolve expr_closed_cast expr_closedl_cast : closed.\n\nLemma expr_closed_field: forall {cs: compspecs} S e f t,\n  lvalue_closed_wrt_vars S e ->\n  expr_closed_wrt_vars S (Efield e f t).\nProof.\n unfold lvalue_closed_wrt_vars, expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift.\n f_equal.\n apply H.  auto.\nQed.\nLemma expr_closedl_field: forall S e f t,\n  lvalue_closed_wrt_lvars S e ->\n  expr_closed_wrt_lvars S (Efield e f t).\nProof.\n unfold lvalue_closed_wrt_lvars, expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift.\n f_equal.\n apply H.  auto.\nQed.\n#[export] Hint Resolve expr_closed_field expr_closedl_field : closed.\n\nLemma expr_closed_binop: forall {cs: compspecs} S op e1 e2 t,\n     expr_closed_wrt_vars S e1 ->\n     expr_closed_wrt_vars S e2 ->\n     expr_closed_wrt_vars S (Ebinop op e1 e2 t).\nProof.\n unfold expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift. f_equal; auto.\nQed.\nLemma expr_closedl_binop: forall S op e1 e2 t,\n     expr_closed_wrt_lvars S e1 ->\n     expr_closed_wrt_lvars S e2 ->\n     expr_closed_wrt_lvars S (Ebinop op e1 e2 t).\nProof.\n unfold expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift. f_equal; auto.\nQed.\n#[export] Hint Resolve expr_closed_binop expr_closedl_binop : closed.\n\nLemma expr_closed_unop: forall {cs: compspecs} S op e t,\n     expr_closed_wrt_vars S e ->\n     expr_closed_wrt_vars S (Eunop op e t).\nProof.\n unfold expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift. f_equal; auto.\nQed.\nLemma expr_closedl_unop: forall S op e t,\n     expr_closed_wrt_lvars S e ->\n     expr_closed_wrt_lvars S (Eunop op e t).\nProof.\n unfold expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift. f_equal; auto.\nQed.\n#[export] Hint Resolve expr_closed_unop expr_closedl_unop : closed.\n\nLemma closed_wrt_stackframe_of:\n  forall {cs: compspecs} S f, closed_wrt_vars S (stackframe_of f).\nProof.\nintros.\nunfold stackframe_of.\ninduction (fn_vars f); auto.\napply closed_wrt_emp.\napply closed_wrt_sepcon; [ | apply IHl].\nclear. destruct a; unfold var_block.\nhnf; intros. reflexivity.\nQed.\n#[export] Hint Resolve closed_wrt_stackframe_of : closed.\n\nDefinition included {U} (S S': U -> Prop) := forall x, S x -> S' x.\n\nLemma closed_wrt_TT:\n forall  (S: ident -> Prop),\n  closed_wrt_vars S (@TT (environ -> mpred) _).\nProof.\nintros. hnf; intros. reflexivity.\nQed.\nLemma closed_wrtl_TT:\n forall  (S: ident -> Prop),\n  closed_wrt_lvars S (@TT (environ -> mpred) _).\nProof.\nintros. hnf; intros. reflexivity.\nQed.\n#[export] Hint Resolve closed_wrt_TT closed_wrtl_TT : closed.\n\nLemma closed_wrt_subset:\n  forall (S S': ident -> Prop) (H: included S' S) B (f: environ -> B),\n       closed_wrt_vars S f -> closed_wrt_vars S' f.\nProof.\nintros. hnf. intros. specialize (H0 rho te').\napply H0.\nintro i; destruct (H1 i); auto.\nQed.\nLemma closed_wrtl_subset:\n  forall (S S': ident -> Prop) (H: included S' S) B (f: environ -> B),\n       closed_wrt_lvars S f -> closed_wrt_lvars S' f.\nProof.\nintros. hnf. intros. specialize (H0 rho ve').\napply H0.\nintro i; destruct (H1 i); auto.\nQed.\n#[export] Hint Resolve closed_wrt_subset closed_wrtl_subset : closed.\n\nLemma closed_wrt_Forall_subset:\n  forall S S' (H: included S' S) B (f: list (environ -> B)),\n Forall (closed_wrt_vars S) f ->\n Forall (closed_wrt_vars S') f.\nProof.\ninduction f; simpl; auto.\nintro.\ninv H0.\nconstructor.\napply (closed_wrt_subset _ _ H). auto.\nauto.\nQed.\nLemma closed_wrtl_Forall_subset:\n  forall S S' (H: included S' S) B (f: list (environ -> B)),\n Forall (closed_wrt_lvars S) f ->\n Forall (closed_wrt_lvars S') f.\nProof.\ninduction f; simpl; auto.\nintro.\ninv H0.\nconstructor.\napply (closed_wrtl_subset _ _ H). auto.\nauto.\nQed.\n\nLemma lvalue_closed_tempvar:\n forall {cs: compspecs} S i t, ~ S i -> lvalue_closed_wrt_vars S (Etempvar i t).\nProof.\nsimpl; intros.\nhnf; intros.\nsimpl. reflexivity.\nQed.\nLemma lvalue_closedl_tempvar:\n forall S i t, lvalue_closed_wrt_lvars S (Etempvar i t).\nProof.\nsimpl; intros.\nhnf; intros.\nsimpl. reflexivity.\nQed.\n#[export] Hint Resolve lvalue_closed_tempvar lvalue_closedl_tempvar : closed.\n\nLemma expr_closed_addrof: forall {cs: compspecs} S e t,\n     lvalue_closed_wrt_vars S e ->\n     expr_closed_wrt_vars S (Eaddrof e t).\nProof.\n unfold lvalue_closed_wrt_vars, expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift. apply H.  auto.\nQed.\nLemma expr_closedl_addrof: forall S e t,\n     lvalue_closed_wrt_lvars S e ->\n     expr_closed_wrt_lvars S (Eaddrof e t).\nProof.\n unfold lvalue_closed_wrt_lvars, expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift. apply H.  auto.\nQed.\n#[export] Hint Resolve expr_closed_addrof expr_closedl_addrof : closed.\n\nLemma lvalue_closed_field: forall {cs: compspecs} S e f t,\n  lvalue_closed_wrt_vars S e ->\n  lvalue_closed_wrt_vars S (Efield e f t).\nProof.\n unfold lvalue_closed_wrt_vars, expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift. f_equal; apply H.  auto.\nQed.\nLemma lvalue_closedl_field: forall S e f t,\n  lvalue_closed_wrt_lvars S e ->\n  lvalue_closed_wrt_lvars S (Efield e f t).\nProof.\n unfold lvalue_closed_wrt_lvars, expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift. f_equal; apply H.  auto.\nQed.\n#[export] Hint Resolve lvalue_closed_field lvalue_closedl_field : closed.\n\nLemma lvalue_closed_deref: forall {cs: compspecs} S e t,\n  expr_closed_wrt_vars S e ->\n  lvalue_closed_wrt_vars S (Ederef e t).\nProof.\n unfold lvalue_closed_wrt_vars, expr_closed_wrt_vars; intros.\n simpl.\n super_unfold_lift. apply H.  auto.\nQed.\nLemma lvalue_closedl_deref: forall S e t,\n  expr_closed_wrt_lvars S e ->\n  lvalue_closed_wrt_lvars S (Ederef e t).\nProof.\n unfold lvalue_closed_wrt_lvars, expr_closed_wrt_lvars; intros.\n simpl.\n super_unfold_lift. apply H.  auto.\nQed.\n#[export] Hint Resolve lvalue_closed_deref lvalue_closedl_deref: closed.\n\nFixpoint closed_eval_expr (j: ident) (e: expr) : bool :=\n match e with\n | Econst_int i ty => true\n | Econst_long i ty => true\n | Econst_float f ty => true\n | Econst_single f ty => true\n | Etempvar id ty => negb (eqb_ident j id)\n | Eaddrof a ty => closed_eval_lvalue j a\n | Eunop op a ty =>  closed_eval_expr j a\n | Ebinop op a1 a2 ty =>  andb (closed_eval_expr j a1) (closed_eval_expr j a2)\n | Ecast a ty => closed_eval_expr j a\n | Evar id ty => true\n | Ederef a ty => closed_eval_expr j a\n | Efield a i ty => closed_eval_lvalue j a\n | Esizeof _ _ => true\n | Ealignof _ _ => true\n end\n\n with closed_eval_lvalue (j: ident) (e: expr) : bool :=\n match e with\n | Evar id ty => true\n | Ederef a ty => closed_eval_expr j a\n | Efield a i ty => closed_eval_lvalue j a\n | _  => false\n end.\n\nLemma closed_eval_expr_e:\n    forall {cs: compspecs} j e, closed_eval_expr j e = true -> closed_wrt_vars (eq j) (eval_expr e)\nwith closed_eval_lvalue_e:\n    forall {cs: compspecs} j e, closed_eval_lvalue j e = true -> closed_wrt_vars (eq j) (eval_lvalue e).\nProof.\nintros cs j e; clear closed_eval_expr_e; induction e; intros; simpl; auto with closed.\nsimpl in H. destruct (eqb_ident j i) eqn:?; inv H.\napply Pos.eqb_neq in Heqb. auto with closed.\nsimpl in H.\nrewrite andb_true_iff in H. destruct H.\nauto with closed.\nintros Delta j e; clear closed_eval_lvalue_e; induction e; intros; simpl; auto with closed.\nQed.\n\n#[export] Hint Extern 2 (closed_wrt_vars (eq _) (@eval_expr _ _)) => (apply closed_eval_expr_e; reflexivity) : closed.\n#[export] Hint Extern 2 (closed_wrt_vars (eq _) (@eval_lvalue _ _)) => (apply closed_eval_lvalue_e; reflexivity) : closed.\n\nLemma closed_wrt_eval_expr: forall {cs: compspecs} S e,\n  expr_closed_wrt_vars S e ->\n  closed_wrt_vars S (eval_expr e).\nProof.\nunfold expr_closed_wrt_vars, closed_wrt_vars.\nintros.\napply H; auto.\nQed.\n(* #[export] Hint Resolve closed_wrt_eval_expr : closed. *)\n\nLemma closed_wrt_lvalue: forall {cs: compspecs} S e,\n  access_mode (typeof e) = By_reference ->\n  closed_wrt_vars S (eval_expr e) -> closed_wrt_vars S (eval_lvalue e).\nProof.\nintros.\ndestruct e; simpl in *; auto with closed;\nunfold closed_wrt_vars in *;\nintros; specialize (H0 _ _ H1); clear H1; super_unfold_lift;\nauto.\nQed.\n(* #[export] Hint Resolve closed_wrt_lvalue : closed. *)\n\nLemma closed_wrt_ideq: forall {cs: compspecs} a b e,\n  a <> b ->\n  closed_eval_expr a e = true ->\n  closed_wrt_vars (eq a) (fun rho => !! (eval_id b rho = eval_expr e rho)).\nProof.\nintros.\nhnf; intros.\nsimpl. f_equal.\nf_equal.\nspecialize (H1 b).\ndestruct H1; [contradiction | ].\nunfold eval_id; simpl. rewrite H1. auto.\nclear b H.\neapply closed_eval_expr_e in H0.\napply H0; auto.\nQed.\n\n#[export] Hint Extern 2 (closed_wrt_vars (eq _) _) =>\n      (apply closed_wrt_ideq; [solve [let Hx := fresh in (intro Hx; inv Hx)] | reflexivity]) : closed.\n\nLemma closed_wrt_tc_nonzero:\n forall {cs: compspecs} S e,\n     closed_wrt_vars S (eval_expr e) ->\n     closed_wrt_vars S (denote_tc_assert (tc_nonzero e)).\nProof.\n intros.\n hnf; intros.\n specialize (H _ _ H0).\n repeat rewrite binop_lemmas2.denote_tc_assert_nonzero.\n rewrite <- H; auto.\nQed.\n#[export] Hint Resolve closed_wrt_tc_nonzero : closed.\n\nLemma closed_wrt_binarithType:\n  forall {cs: compspecs} S t1 t2 t a b,\n  closed_wrt_vars S (denote_tc_assert (binarithType t1 t2 t a b)).\nProof.\n intros.\n unfold binarithType.\n destruct (Cop.classify_binarith t1 t2); simpl; auto with closed.\nQed.\n#[export] Hint Resolve closed_wrt_binarithType : closed.\n\nLemma closed_wrt_tc_samebase :\n forall {cs: compspecs} S e1 e2,\n closed_wrt_vars S (eval_expr e1) ->\n closed_wrt_vars S (eval_expr e2) ->\n closed_wrt_vars S (denote_tc_assert (tc_samebase e1 e2)).\nProof.\n intros;  hnf; intros. simpl. unfold_lift. f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_tc_samebase : closed.\n\nLemma closed_wrt_tc_ilt:\n  forall {cs: compspecs} S e n,\n    closed_wrt_vars S (eval_expr e) ->\n    closed_wrt_vars S (denote_tc_assert (tc_ilt e n)).\nProof.\n intros; hnf; intros.\n repeat rewrite binop_lemmas2.denote_tc_assert_ilt'.\n simpl. unfold_lift. f_equal. auto.\nQed.\n#[export] Hint Resolve closed_wrt_tc_ilt : closed.\n\nLemma closed_wrt_tc_llt:\n  forall {cs: compspecs} S e n,\n    closed_wrt_vars S (eval_expr e) ->\n    closed_wrt_vars S (denote_tc_assert (tc_llt e n)).\nProof.\n intros; hnf; intros.\n repeat rewrite binop_lemmas2.denote_tc_assert_llt'.\n simpl. unfold_lift. f_equal. auto.\nQed.\n#[export] Hint Resolve closed_wrt_tc_llt : closed.\n\nLemma closed_wrt_tc_Zge:\n  forall {cs: compspecs} S e n,\n    closed_wrt_vars S (eval_expr e) ->\n    closed_wrt_vars S (denote_tc_assert (tc_Zge e n)).\nProof.\n intros; hnf; intros.\n simpl. unfold_lift; f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_tc_Zge : closed.\nLemma closed_wrt_tc_Zle:\n  forall {cs: compspecs} S e n,\n    closed_wrt_vars S (eval_expr e) ->\n    closed_wrt_vars S (denote_tc_assert (tc_Zle e n)).\nProof.\n intros; hnf; intros.\n simpl. unfold_lift; f_equal; auto.\nQed.\n#[export] Hint Resolve closed_wrt_tc_Zle : closed.\n\nLemma closed_wrt_replace_nth:\n  forall {B} S n R (R1: environ -> B),\n    closed_wrt_vars S R1 ->\n    Forall (closed_wrt_vars S) R ->\n    Forall (closed_wrt_vars S) (replace_nth n R R1).\nProof.\nintros.\nrevert R H0; induction n; destruct R; simpl; intros; auto with closed;\ninv H0; constructor; auto with closed.\nQed.\n#[export] Hint Resolve closed_wrt_replace_nth : closed.\n\nLemma closed_wrt_tc_nodivover :\n forall {cs: compspecs} S e1 e2,\n closed_wrt_vars S (eval_expr e1) ->\n closed_wrt_vars S (eval_expr e2) ->\n closed_wrt_vars S (denote_tc_assert (tc_nodivover e1 e2)).\nProof.\n intros;  hnf; intros.\n repeat rewrite binop_lemmas2.denote_tc_assert_nodivover.\n rewrite <- H0; auto. rewrite <- H; auto.\nQed.\n#[export] Hint Resolve closed_wrt_tc_nodivover : closed.\n\nLemma closed_wrt_tc_nosignedover:\n  forall op {CS: compspecs} S e1 e2,\n  closed_wrt_vars S (eval_expr e1) ->\n  closed_wrt_vars S (eval_expr e2) ->\n  closed_wrt_vars S (denote_tc_assert (tc_nosignedover op e1 e2)).\nProof.\nintros; hnf; intros.\nsimpl. unfold_lift.\nrewrite <- H; auto.\nrewrite <- H0; auto.\nQed.\n#[export] Hint Resolve closed_wrt_tc_nosignedover : closed.\n\nLemma closed_wrt_tc_nobinover:\n  forall op {CS: compspecs} S e1 e2,\n  closed_wrt_vars S (eval_expr e1) ->\n  closed_wrt_vars S (eval_expr e2) ->\n  closed_wrt_vars S (denote_tc_assert (tc_nobinover op e1 e2)).\nProof.\nintros.\nunfold tc_nobinover.\nunfold if_expr_signed.\ndestruct (typeof e1); auto with closed.\ndestruct s; auto with closed.\ndestruct (eval_expr e1 any_environ); auto with closed;\ndestruct (eval_expr e2 any_environ); auto with closed.\nall: repeat simple_if_tac; auto with closed.\ndestruct (eval_expr e1 any_environ); auto with closed;\ndestruct (eval_expr e2 any_environ); auto with closed.\nall: try destruct s; repeat simple_if_tac; auto with closed.\nQed.\n\n#[export] Hint Resolve closed_wrt_tc_nobinover : closed.\n\nLemma closed_wrt_tc_expr:\n  forall {cs: compspecs} Delta j e, closed_eval_expr j e = true ->\n             closed_wrt_vars (eq j) (tc_expr Delta e)\n with closed_wrt_tc_lvalue:\n  forall {cs: compspecs} Delta j e, closed_eval_lvalue j e = true ->\n             closed_wrt_vars (eq j) (tc_lvalue Delta e).\nProof.\n* clear closed_wrt_tc_expr.\nunfold tc_expr.\ninduction e; simpl; intros;\ntry solve [destruct t  as [ | [ | | | ] [ | ] | | [ | ] | | | | | ]; simpl; auto with closed].\n+\n  destruct (access_mode t);  simpl; auto with closed;\n  destruct (get_var_type Delta i); simpl; auto with closed.\n+\n  destruct ((temp_types Delta) ! i); simpl; auto with closed.\n  destruct (is_neutral_cast t0 t || same_base_type t0 t)%bool; simpl; auto with closed.\n  clear -  H.\n  hnf; intros.\n  specialize (H0 i).\n  pose proof (eqb_ident_spec j i).\n  destruct (eqb_ident j i); inv H.\n  destruct H0. apply H1 in H; inv H.\n  unfold denote_tc_initialized;  simpl.\n  f_equal.\n  apply exists_ext; intro v.\n  f_equal. rewrite H; auto.\n+ destruct (access_mode t) eqn:?H; simpl; auto with closed.\n  apply closed_wrt_tc_andp; auto with closed.\n  apply closed_wrt_tc_isptr; auto with closed.\n  apply closed_eval_expr_e; auto.\n+\n apply closed_wrt_tc_andp; auto with closed.\n apply closed_wrt_tc_lvalue; auto.\n+\n specialize (IHe H).\n apply closed_eval_expr_e in H.\n repeat apply closed_wrt_tc_andp; auto with closed.\n unfold isUnOpResultType.\n destruct u;\n destruct (typeof e) as   [ | [ | | | ] [ | ] | [ | ] | [ | ] | | | | | ];\n   simpl; repeat apply closed_wrt_tc_andp; auto 50 with closed;\n  rewrite binop_lemmas2.denote_tc_assert_test_eq';\n  simpl; unfold_lift;\n  hnf; intros ? ? H8; simpl;\n  rewrite <- (H _ _ H8); auto.\n+\n  rewrite andb_true_iff in H. destruct H.\n specialize (IHe1 H). specialize (IHe2 H0).\n apply closed_eval_expr_e in H; apply closed_eval_expr_e in H0.\n repeat apply closed_wrt_tc_andp; auto with closed.\n unfold isBinOpResultType.\n destruct b; auto 50 with closed;\n try solve [destruct (Cop.classify_binarith (typeof e1) (typeof e2));\n                try destruct s;  auto with closed];\n try solve [destruct (Cop.classify_cmp (typeof e1) (typeof e2));\n                 simpl; auto 50 with closed].\n destruct (Cop.classify_add (typeof e1) (typeof e2)); auto 50 with closed.\n destruct (Cop.classify_sub (typeof e1) (typeof e2)); auto 50 with closed.\n destruct (Cop.classify_shift (typeof e1) (typeof e2)); auto 50 with closed.\n destruct (Cop.classify_shift (typeof e1) (typeof e2)); auto 50 with closed.\n\n+\n apply closed_wrt_tc_andp; auto with closed.\n specialize (IHe H).\n apply closed_eval_expr_e in H.\n unfold isCastResultType.\n destruct (classify_cast (typeof e) t); auto with closed;\n   try solve [ destruct t as [ | [ | | | ] [ | ]| [ | ] | [ | ] | | | | | ]; auto with closed].\nall: repeat simple_if_tac; try destruct si2; auto with closed.\n apply closed_wrt_tc_test_eq; auto with closed.\n hnf; intros; reflexivity.\n hnf; intros; reflexivity.\n+\n clear IHe.\n destruct (access_mode t); simpl; auto with closed.\n repeat apply closed_wrt_tc_andp; auto with closed.\n apply closed_wrt_tc_lvalue; auto.\n destruct (typeof e); simpl; auto with closed;\n destruct (cenv_cs ! i0); simpl; auto with closed.\n destruct (field_offset cenv_cs i (co_members c)); simpl; auto with closed.\n*\n clear closed_wrt_tc_lvalue.\n unfold tc_lvalue.\n induction e; simpl; intros; auto with closed.\n +\n destruct (get_var_type Delta i); simpl; auto with closed.\n +\n specialize (closed_wrt_tc_expr cs Delta _ _ H).\n apply closed_eval_expr_e in H.\n auto 50 with closed.\n +\n specialize (IHe H).\n apply closed_eval_lvalue_e  in H.\n repeat apply closed_wrt_tc_andp; auto with closed.\n destruct (typeof e); simpl; auto with closed;\n destruct (cenv_cs ! i0); simpl; auto with closed.\n destruct (field_offset cenv_cs i (co_members c)); simpl; auto with closed.\nQed.\n\n#[export] Hint Resolve closed_wrt_tc_expr : closed.\n#[export] Hint Resolve closed_wrt_tc_lvalue : closed.\n\n\nLemma closed_wrt_lift1':\n      forall (A B : Type) (S : ident -> Prop) (f : A -> B)\n         (P : environ -> A),\n       closed_wrt_vars S P -> closed_wrt_vars S (`f P).\nProof.\nintros.\napply closed_wrt_lift1.\nhnf; intros. simpl. f_equal.\napply H. auto.\nQed.\n#[export] Hint Resolve closed_wrt_lift1' : closed.\n\nLemma closed_wrt_Econst_int:\n  forall {cs: compspecs} S i t, closed_wrt_vars S (eval_expr (Econst_int i t)).\nProof.\nsimpl; intros.\nauto with closed.\nQed.\n#[export] Hint Resolve closed_wrt_Econst_int : closed.\n\nLemma closed_wrt_PROPx:\n forall S P Q, closed_wrt_vars S Q -> closed_wrt_vars S (PROPx P Q).\nProof.\nintros.\napply closed_wrt_andp; auto.\nhnf; intros. reflexivity.\nQed.\nLemma closed_wrtl_PROPx:\n forall S P Q, closed_wrt_lvars S Q -> closed_wrt_lvars S (PROPx P Q).\nProof.\nintros.\napply closed_wrtl_andp; auto.\nhnf; intros. reflexivity.\nQed.\n#[export] Hint Resolve closed_wrt_PROPx closed_wrtl_PROPx: closed.\n\n\nLemma closed_wrt_LOCALx:\n forall S Q R, Forall (closed_wrt_vars S) (map locald_denote Q) ->\n                    closed_wrt_vars S R ->\n                    closed_wrt_vars S (LOCALx Q R).\nProof.\nintros.\napply closed_wrt_andp; auto.\nclear - H.\ninduction Q; simpl; intros.\nauto with closed.\nnormalize. autorewrite with norm1 norm2; normalize.\ninv H.\napply closed_wrt_andp; auto with closed.\nQed.\n\n\nLemma closed_wrtl_LOCALx:\n forall S Q R, Forall (closed_wrt_lvars S) (map locald_denote Q) ->\n                    closed_wrt_lvars S R ->\n                    closed_wrt_lvars S (LOCALx Q R).\nProof.\nintros.\napply closed_wrtl_andp; auto.\nclear - H.\ninduction Q; simpl; intros.\nauto with closed.\nnormalize. autorewrite with norm1 norm2; normalize.\ninv H.\napply closed_wrtl_andp; auto with closed.\nQed.\n(*\nLemma closed_wrt_LOCALx:\n forall S Q R, Forall (fun q => closed_wrt_vars S (local q)) Q ->\n                    closed_wrt_vars S R ->\n                    closed_wrt_vars S (LOCALx Q R).\nProof.\nintros.\napply closed_wrt_andp; auto.\nclear - H.\ninduction Q; simpl; intros.\nauto with closed.\nnormalize.\ninv H.\napply closed_wrt_andp; auto with closed.\nQed.\n*)\n\n#[export] Hint Resolve closed_wrt_LOCALx closed_wrtl_LOCALx: closed.\n\nLemma closed_wrt_SEPx: forall S P,\n     closed_wrt_vars S (SEPx P).\nProof.\nintros.\nunfold SEPx.\nauto with closed.\nQed.\n\nLemma closed_wrtl_SEPx: forall S P,\n     closed_wrt_lvars S (SEPx P).\nProof.\nintros.\nunfold SEPx.\nauto with closed.\nQed.\n#[export] Hint Resolve closed_wrt_SEPx closed_wrtl_SEPx: closed.\n\nLemma not_not_a_param_i:\n  forall (L: list (ident * type)) i,\n   In i (map (@fst _ _) L) ->\n   ~ not_a_param L i.\nProof.\nintros.\nintro. apply H0; auto.\nQed.\n#[export] Hint Resolve not_not_a_param_i : closed.\n\nLemma in_map_fst1:\n forall (i: ident) (t: type) L,\n   In i (map (@fst _ _) ((i,t)::L)).\nProof.\nintros. left. reflexivity.\nQed.\n#[export] Hint Resolve in_map_fst1 : closed.\n\nLemma in_map_fst2:\n forall (i: ident) a (L: list (ident*type)),\n   In i (map (@fst _ _) L) ->\n   In i (map (@fst _ _) (a::L)).\nProof.\nintros; right; auto.\nQed.\n#[export] Hint Resolve in_map_fst2 : closed.\n\nLemma Forall_map_cons:\n  forall {A B} (F: A -> Prop) (g: B -> A) b bl,\n  F (g b) -> Forall F (map g bl) ->\n  Forall F (map g (b::bl)).\nProof.\nsimpl.\nintros.\nconstructor; auto.\nQed.\n\nLemma Forall_map_nil:\n  forall {A B} (F: A -> Prop) (g: B -> A),\n  Forall F (map g nil).\nProof.\nsimpl.\nintros.\nconstructor; auto.\nQed.\n#[export] Hint Resolve Forall_map_cons Forall_map_nil : closed.\n#[export] Hint Resolve Forall_cons Forall_nil : closed.\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/floyd/closed_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.22113554300614696}}
{"text": "Require Import AutoSep Bags Malloc ThreadQueue Misc.\nImport W_Bag.\n\nSet Implicit Arguments.\n\n\nModule Type S.\n  Variable world : Type.\n\n  Variable evolve : world -> world -> Prop.\n  Axiom evolve_refl : forall w, evolve w w.\n  Axiom evolve_trans : forall w1 w2 w3, evolve w1 w2 -> evolve w2 w3 -> evolve w1 w3.\n\n  Variable globalInv : bag -> world -> HProp.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nModule M'.\n  Open Scope Sep_scope.\n\n  Definition world := (bag * M.world)%type.\n  Definition evolve (w1 w2 : world) :=\n    fst w1 %<= fst w2\n    /\\ M.evolve (snd w1) (snd w2).\n\n  Local Hint Resolve M.evolve_refl M.evolve_trans.\n\n  Theorem evolve_refl : forall w, evolve w w.\n    unfold evolve; auto.\n  Qed.\n\n  Theorem evolve_trans : forall w1 w2 w3, evolve w1 w2 -> evolve w2 w3 -> evolve w1 w3.\n    unfold evolve; intuition eauto.\n  Qed.\n\n  Definition globalInv (w : world) (p : W) : hpropB (tq_args world :: nil) :=\n    starB (fun p' stn sm => Var0 {| World := w; Pointer := p'; Settings := stn; Mem := sm |}) (fst w %- p) * ^[M.globalInv (fst w) (snd w)].\nEnd M'.\n\nModule Q := ThreadQueue.Make(M').\nImport M' Q.\n\nModule Type TQS.\n  Parameter tqs' : world -> bag -> HProp.\n\n  Axiom tqs'_eq : tqs' = fun w => starB (tq w).\n\n  Parameter tqs : bag -> M.world -> HProp.\n\n  Axiom tqs_eq : tqs = fun b w => tqs' (b, w) b.\n\n  Definition tqs'_pick_this_one (_ : W) := tqs'.\n\n  Axiom tqs'_empty_bwd : forall w, Emp ===> tqs' w empty.\n  Axiom tqs'_add_bwd : forall w ts t, tqs' w ts * tq w t ===> tqs' w (ts %+ t).\n  Axiom tqs'_del_fwd : forall w ts t, t %in ts -> tqs'_pick_this_one t w ts ===> tq w t * tqs' w (ts %- t).\n  Axiom tqs'_del_bwd : forall w ts t, t %in ts -> tqs' w (ts %- t) * tq w t ===> tqs' w ts.\n\n  Axiom tqs'_weaken : forall w w' b, evolve w w' -> tqs' w b ===>* tqs' w' b.\nEnd TQS.\n\nModule Tqs : TQS.\n  Open Scope Sep_scope.\n\n  Definition tqs' w := starB (tq w).\n\n  Theorem tqs'_eq : tqs' = fun w => starB (tq w).\n    auto.\n  Qed.\n\n  Definition tqs b w := tqs' (b, w) b.\n\n  Theorem tqs_eq : tqs = fun b w => tqs' (b, w) b.\n    auto.\n  Qed.\n\n  Definition tqs'_pick_this_one (_ : W) := tqs'.\n\n  Theorem tqs'_empty_bwd : forall w, Emp ===> tqs' w empty.\n    intros; apply starB_empty_bwd.\n  Qed.\n\n  Theorem tqs'_add_bwd : forall w ts t, tqs' w ts * tq w t ===> tqs' w (ts %+ t).\n    intros; apply (starB_add_bwd (tq w)).\n  Qed.\n\n  Theorem tqs'_del_fwd : forall w ts t, t %in ts -> tqs'_pick_this_one t w ts ===> tq w t * tqs' w (ts %- t).\n    intros; apply (starB_del_fwd (tq w)); auto.\n  Qed.\n\n  Theorem tqs'_del_bwd : forall w ts t, t %in ts -> tqs' w (ts %- t) * tq w t ===> tqs' w ts.\n    intros; eapply Himp_trans; [ | apply (starB_del_bwd (tq w)); eauto ].\n    eapply Himp_trans; [ apply Himp_star_comm | ].\n    apply Himp_refl.\n  Qed.\n\n  Theorem tqs'_weaken : forall w w' b, evolve w w' -> tqs' w b ===>* tqs' w' b.\n    intros; apply starB_weaken_weak; intros.\n    apply tq_weaken; unfold evolve in *; simpl in *; intuition.\n  Qed.\nEnd Tqs.\n\nImport Tqs.\nExport Tqs.\n\nTheorem tqs_empty_bwd : forall w, Emp ===> tqs empty w.\n  intros; rewrite tqs_eq; apply tqs'_empty_bwd.\nQed.\n\nDefinition exitize_me a b c d := locals a b c d.\n\nLemma exitize_locals : forall xx yy ns vs res sp,\n  exitize_me (\"rp\" :: xx :: yy :: ns) vs res sp ===> Ex vs', locals (\"rp\" :: \"sc\" :: \"ss\" :: nil) (upd vs' \"ss\" (sel vs yy)) (res + length ns) sp.\n  unfold exitize_me, locals; intros.\n  simpl; unfold upd; simpl.\n  apply Himp_ex_c; exists (fun x => if string_dec x \"rp\" then vs \"rp\" else vs xx).\n  eapply Himp_trans.\n  eapply Himp_star_frame.\n  eapply Himp_star_frame.\n  apply Himp_refl.\n  change (vs \"rp\" :: vs xx :: vs yy :: toArray ns vs)\n    with (toArray ((\"rp\" :: xx :: yy :: nil) ++ ns) vs).\n  apply ptsto32m_split.\n  apply Himp_refl.\n  destruct (string_dec \"rp\" \"rp\"); intuition.\n  destruct (string_dec \"sc\" \"rp\"); intuition.\n  unfold array, toArray in *.\n  simpl map in *.\n  simpl length in *.\n\n  Lemma switchedy : forall P Q R S : HProp,\n    (P * (Q * R)) * S ===> P * (Q * (R * S)).\n    sepLemma.\n  Qed.\n\n  eapply Himp_trans; [ apply switchedy | ].\n  \n  Lemma swatchedy : forall P Q R : HProp,\n    P * (Q * R) ===> P * Q * R.\n    sepLemma.\n  Qed.\n\n  eapply Himp_trans; [ | apply swatchedy ].\n  apply Himp_star_frame.\n  sepLemma; NoDup.\n  apply Himp_star_frame.\n  apply Himp_refl.\n  eapply Himp_trans; [ | apply allocated_join ].\n  apply Himp_star_frame.\n  eapply Himp_trans; [ | apply allocated_shift_base ].\n  apply ptsto32m_allocated.\n  simpl.\n  words.\n  eauto.\n  apply allocated_shift_base.\n  rewrite map_length.\n  repeat rewrite <- wplus_assoc.\n  repeat rewrite <- natToW_plus.\n  f_equal.\n  f_equal.\n  omega.\n  rewrite map_length; omega.\n  rewrite map_length; omega.\nQed.\n\nDefinition hints : TacPackage.\n  prepare (tqs'_del_fwd, create_stack, exitize_locals) (tqs'_empty_bwd, tqs'_add_bwd).\nDefined.\n\nDefinition starting (ts : bag) (w : M.world) (pc : W) (ss : nat) : HProp := fun s m =>\n  (ExX (* pre *) : settings * state, Cptr pc #0\n    /\\ [| semp m |]\n    /\\ Al st : settings * state, Al vs, Al ts', Al w',\n      [| ts %<= ts' |]\n      /\\ [| M.evolve w w' |]\n      /\\ [| st#Sp <> 0 /\\ freeable st#Sp (1 + ss) |]\n      /\\ ![ ^[locals (\"rp\" :: nil) vs ss st#Sp * tqs ts' w' * M.globalInv ts' w' * mallocHeap 0] ] st\n      ---> #0 st)%PropX.\n\nLemma starting_elim : forall specs ts w pc ss P stn st,\n  interp specs (![ starting ts w pc ss * P ] (stn, st))\n  -> (exists pre, specs pc = Some (fun x => pre x)\n    /\\ interp specs (![ P ] (stn, st))\n    /\\ forall stn_st vs ts' w', interp specs ([| ts %<= ts' |]\n      /\\ [| M.evolve w w' |]\n      /\\ [| stn_st#Sp <> 0 /\\ freeable stn_st#Sp (1 + ss) |]\n      /\\ ![ locals (\"rp\" :: nil) vs ss stn_st#Sp\n      * tqs ts' w' * M.globalInv ts' w' * mallocHeap 0 ] stn_st\n    ---> pre stn_st)%PropX).\n  cptr.\n  generalize (split_semp _ _ _ H0 H); intros; subst; auto.\n  rewrite <- sepFormula_eq; descend; step auto_ext.\n  eauto.\n  eauto.\n  eauto.\n  step auto_ext.\nQed.\n\n\nDefinition allocS : spec := SPEC reserving 14\n  Al ts, Al w,\n  PRE[_] tqs ts w * mallocHeap 0\n  POST[R] tqs (ts %+ R) w * mallocHeap 0.\n\nDefinition isEmptyS : spec := SPEC(\"sc\") reserving 4\n  Al ts, Al w,\n  PRE[V] [| V \"sc\" %in ts |] * tqs ts w * mallocHeap 0\n  POST[_] tqs ts w * mallocHeap 0.\n\nDefinition spawnS : spec := SPEC(\"sc\", \"pc\", \"ss\") reserving 18\n  Al ts, Al w, Al w',\n  PRE[V] [| V \"sc\" %in ts |] * [| V \"ss\" >= $2 |] * [| M.evolve w w' |]\n    * tqs ts w * starting ts w' (V \"pc\") (wordToNat (V \"ss\") - 1) * mallocHeap 0\n  POST[_] tqs ts w' * mallocHeap 0.\n\nDefinition exitS : spec := SPEC(\"sc\", \"ss\") reserving 0\n  Al ts, Al w, Al w',\n  PREexit[V] [| V \"ss\" >= $3 |] * [| V \"sc\" %in ts |] * [| M.evolve w w' |]\n    * tqs ts w * M.globalInv ts w' * mallocHeap 0.\n\nDefinition yieldS : spec := SPEC(\"enq\", \"deq\") reserving 22\n  Al ts, Al w, Al w',\n  PRE[V] [| V \"enq\" %in ts |] * [| V \"deq\" %in ts |] * [| M.evolve w w' |]\n    * tqs ts w * M.globalInv ts w' * mallocHeap 0\n  POST[_] Ex ts', Ex w'', [| ts %<= ts' |] * [| M.evolve w' w'' |]\n    * tqs ts' w'' * M.globalInv ts' w'' * mallocHeap 0.\n\nNotation \"'balias' name () [ p ] l 'end'\" :=\n  (let p' := p in\n   let vars := nil in\n    {| FName := name;\n      FPrecondition := Precondition p' None;\n      FBody := Goto l%SP;\n      FVars := vars;\n      FReserved := Reserved p' |})\n  (no associativity, at level 95, name at level 0, p at level 0, only parsing) : SPfuncs_scope.\n\nLocal Notation \"'PREy' [ vs ] pre\" := (yieldInvariantCont (fun vs _ => pre%qspec%Sep))\n  (at level 89).\n\nDefinition stackSize := 25.\n\nLemma stackSize_bound : natToW stackSize >= natToW 2.\n  unfold stackSize; auto.\nQed.\n\nHint Immediate stackSize_bound.\n\nLemma stackSize_split : stackSize = length (\"rp\" :: \"enq\" :: \"deq\" :: \"sp\" :: nil) + 21.\n  reflexivity.\nQed.\n\nOpaque stackSize.\n\nDefinition localsInvariantYieldy (pre : vals -> W -> qspec) (rpStashed : bool) (adjustSp : W -> W)\n  (ns : list string) (res : nat) : assert :=\n  st ~> let sp := adjustSp st#Sp in\n    [| sp <> 0 |] /\\ [| freeable sp stackSize |]\n    /\\ Ex vs, qspecOut (pre (sel vs) st#Rv) (fun pre =>\n        ![ locals (\"rp\" :: ns) vs res sp * pre ] st).\n\nLocal Notation \"'PREyy' [ vs ] pre\" := (localsInvariantYieldy (fun vs _ => pre%qspec%Sep))\n  (at level 89).\n\nDefinition m := bimport [[ \"malloc\"!\"malloc\" @ [mallocS],\n                           \"threadq\"!\"init\" @ [Q.initS], \"threadq\"!\"isEmpty\" @ [Q.isEmptyS],\n                           \"threadq\"!\"spawn\" @ [Q.spawnS], \"threadq\"!\"spawnWithStack\" @ [Q.spawnWithStackS],\n                           \"threadq\"!\"exit\" @ [Q.exitS], \"threadq\"!\"yield\" @ [Q.yieldS] ]]\n  bmodule \"threadqs\" {{\n    bfunction \"alloc\"(\"r\") [allocS]\n      \"r\" <-- Call \"threadq\"!\"init\"()\n      [Al ts, Al w,\n        PRE[_, R] tq (ts, w) R * tqs ts w\n        POST[R'] tqs (ts %+ R') w ];;\n      Return \"r\"\n    end with balias \"isEmpty\"() [isEmptyS]\n      \"threadq\"!\"isEmpty\"\n    end with balias \"spawn\"() [spawnS]\n      \"threadq\"!\"spawn\"\n    end with balias \"exit\"() [exitS]\n      \"threadq\"!\"exit\"\n    end with bfunction \"yield\"(\"enq\", \"deq\", \"sp\") [yieldS]\n      If (\"enq\" = \"deq\") {\n        Call \"threadq\"!\"yield\"(\"enq\")\n        [PRE[_] Emp\n         POST[_] Emp];;\n        Return 0\n      } else {\n        \"sp\" <-- Call \"malloc\"!\"malloc\"(0, stackSize)\n        [Al ts, Al w,\n          PRE[V, R] [| V \"enq\" %in ts |] * [| V \"deq\" %in ts |] * [| V \"enq\" <> V \"deq\" |]\n            * tqs ts w * M.globalInv ts w * mallocHeap 0\n            * R =?> stackSize * [| R <> 0 |] * [| freeable R stackSize |]\n          POST[_] Ex ts', Ex w', [| ts %<= ts' |] * [| M.evolve w w' |]\n            * tqs ts' w' * M.globalInv ts' w' * mallocHeap 0];;\n\n        Assert [Al ts, Al w,\n          PRE[V] [| V \"enq\" %in ts |] * [| V \"deq\" %in ts |] * [| V \"enq\" <> V \"deq\" |]\n            * tqs ts w * M.globalInv ts w * mallocHeap 0\n            * Ex vs, locals (\"rp\" :: \"enq\" :: \"deq\" :: \"sp\" :: nil) vs 21 (V \"sp\")\n            * [| V \"sp\" <> 0 |] * [| freeable (V \"sp\") stackSize |]\n          POST[_] Ex ts', Ex w', [| ts %<= ts' |] * [| M.evolve w w' |]\n            * tqs ts' w' * M.globalInv ts' w' * mallocHeap 0];;\n\n        \"sp\"+0 *<- $[Sp+0];;\n        \"sp\"+4 *<- \"enq\";;\n        \"sp\"+8 *<- \"deq\";;\n        \"sp\"+12 *<- Sp;;\n        Sp <- \"sp\";;\n        Call \"threadq\"!\"spawnWithStack\"(\"enq\", $[Sp+0], \"sp\")\n        [Al ts, Al w,\n          PREyy[V] [| V \"deq\" %in ts |]\n            * tqs ts w * M.globalInv ts w * mallocHeap 0];;\n\n        \"enq\" <- \"deq\";;\n        \"deq\" <- 25;;\n        Goto \"threadq\"!\"exit\"\n      }\n   end\n  }}.\n\nLocal Hint Extern 1 (@eq W _ _) => words.\n\nLtac t := abstract (sep hints; auto).\n\nLocal Hint Immediate M.evolve_refl.\n\nLemma eq_neq_0 : forall u v : W,\n  u <> 0\n  -> v = 0\n  -> u = v\n  -> False.\n  congruence.\nQed.\n\nLemma freeable_cong : forall (u v : W) n,\n  freeable v n\n  -> v = u\n  -> freeable u n.\n  congruence.\nQed.\n\nLtac words_rewr := repeat match goal with\n                            | [ H : _ = ?X |- _ ] =>\n                              match X with\n                                | natToW 0 => fail 1\n                                | _ => rewrite H\n                              end\n                          end; words.\n\nHint Extern 1 (freeable _ _) => eapply freeable_cong; [ eassumption | words_rewr ].\n\nTheorem ok : moduleOk m.\n  vcgen.\n\n  t.\n  t.\n  t.\n  t.\n  t.\n  t.\n  t.\n\n  post; evaluate hints.\n  rewrite tqs_eq in *.\n  toFront ltac:(fun P => match P with\n                           | tqs' _ _ => idtac\n                         end) H6.\n  eapply use_HimpWeak in H6; [ | apply (tqs'_weaken (w' := (x1 %+ Regs x0 Rv, x2))); (red; intuition) ].\n  toFront ltac:(fun P => match P with\n                           | tq _ _ => idtac\n                         end) H6.\n  eapply use_HimpWeak in H6; [ | apply (tq_weaken (w' := (x1 %+ Regs x0 Rv, x2))); (red; simpl; intuition) ].\n  descend.\n  step hints.\n  step hints.\n  descend; step hints.\n  rewrite H5; step hints.\n  simpl; auto.\n\n  t.\n\n  post; evaluate hints.\n  rewrite tqs_eq in *.\n  toFront ltac:(fun P => match P with\n                           | tqs' _ _ => idtac\n                         end) H4.\n  change (tqs' (x, x0) x) with (tqs'_pick_this_one (sel x2 \"sc\") (x, x0) x) in H4.\n  Hint Extern 1 (_ %in _) => eapply incl_mem; eassumption.\n  Local Hint Extern 1 (himp _ _ _) => apply tqs'_del_bwd.\n  t.\n\n  t.\n\n  post; evaluate hints.\n  rewrite tqs_eq in *.\n  toFront ltac:(fun P => match P with\n                           | tqs' _ _ => idtac\n                         end) H4.\n  eapply use_HimpWeak in H4; [ | apply (tqs'_weaken (w' := (x, x1))); (red; intuition) ].\n  change (tqs' (x, x1) x) with (tqs'_pick_this_one (sel x3 \"sc\") (x, x1) x) in H4.\n  toFront ltac:(fun P => match P with\n                           | starting _ _ _ _ => idtac\n                         end) H4; apply starting_elim in H4; post.\n  evaluate hints.\n  descend.\n  toFront_conc ltac:(fun P => match P with\n                                | Q.starting _ _ _ _ => idtac\n                              end); apply Q.starting_intro; descend.\n  2: step hints.\n  step hints.\n  step hints.\n  step hints.\n  destruct w'; simpl in *.\n  destruct H; simpl in *.\n  eapply Imply_trans; [ | eapply (H4 _ _ b0 w) ]; clear H4.\n  repeat (apply andR; [ apply injR; assumption | ]).\n  repeat (apply andR; [ apply injR; auto | ]).\n\n  Lemma switchy : forall P Q R S T R',\n    R ===> R'\n    -> P * Q * (R * S) * T ===> P * Q * R' * S * T.\n    sepLemma.\n  Qed.\n\n  make_Himp.\n  unfold ginv, globalInv.\n  autorewrite with sepFormula; simpl.\n  eapply Himp_trans; [ eapply switchy; apply starB_substH_fwd | ].\n  unfold substH; simpl.\n  match goal with\n    | [ |- (_ * _ * ?P * _ * _ ===> _)%Sep ] =>\n      replace P with (tqs' (b0, w) (b0 %- sel x3 \"sc\")) by (rewrite tqs'_eq; reflexivity)\n  end.\n  rewrite tqs_eq.\n\n  hnf; intros; step hints.\n  step hints.\n  t.\n\n  t.\n\n  post; evaluate hints.\n  rewrite tqs_eq in *.\n  toFront ltac:(fun P => match P with\n                           | tqs' _ _ => idtac\n                         end) H4.\n  eapply use_HimpWeak in H4; [ | apply (tqs'_weaken (w' := (x, x1))); (red; intuition) ].\n  change (tqs' (x, x1) x) with (tqs'_pick_this_one (sel x2 \"sc\") (x, x1) x) in H4.\n  evaluate hints.\n  descend.\n  eauto.\n  step hints.\n  unfold ginv, globalInv.\n  autorewrite with sepFormula; simpl.\n  make_Himp.\n\n  eapply Himp_trans; [ | apply Himp_star_comm ].\n  apply Himp_star_frame; try apply Himp_refl.\n  eapply Himp_trans; [ | apply starB_substH_bwd ].\n  unfold substH; simpl.\n  match goal with\n    | [ |- (?P ===> ?Q)%Sep ] => \n      replace P with Q; try apply Himp_refl\n  end.\n  rewrite tqs'_eq; reflexivity.\n\n  t.\n  t.\n  t.\n  t.\n  t.\n\n  post; evaluate hints.\n  rewrite tqs_eq in *.\n  toFront ltac:(fun P => match P with\n                           | tqs' _ _ => idtac\n                         end) H8.\n  eapply use_HimpWeak in H8; [ | apply (tqs'_weaken (w' := (x0, x2))); (red; intuition) ].\n  change (tqs' (x0, x2) x0) with (tqs'_pick_this_one (sel x4 \"enq\") (x0, x2) x0) in H8.\n  evaluate hints.\n  descend.\n  step hints.\n  unfold ginv, globalInv.\n  autorewrite with sepFormula; simpl.\n  make_Himp.\n\n  Lemma swatchy : forall P Q Q' R S,\n    Q' ===> Q\n    -> P * (Q' * R * S) ===> P * (Q * R * S).\n    sepLemma.\n  Qed.\n\n  eapply Himp_trans; [ | apply swatchy; apply starB_substH_bwd ].\n  unfold substH; simpl.\n  match goal with\n    | [ |- (_ ===> _ * (?P * _ * _))%Sep ] => \n      replace P with (tqs' (x0, x2) (x0 %- sel x4 \"enq\"))\n        by (rewrite tqs'_eq; instantiate (1 := (x0, x2)); reflexivity)\n  end.\n  sepLemma.\n  step hints.\n  descend; step hints.\n  descend; step hints.\n  step hints.\n  descend; step hints.\n  descend; step hints.\n  descend; step hints.\n  words.\n  unfold ginv, globalInv.\n  autorewrite with sepFormula; simpl.\n  instantiate (1 := snd x8).\n  instantiate (1 := fst x8).\n  make_Himp.\n\n  Lemma swotchy : forall P Q R S T U S',\n    S ===> S'\n    -> P * star Q (star R (star (S * T) U)) ===> P * Q * R * S' * T * U.\n    sepLemma.\n  Qed.\n\n  eapply Himp_trans; [ apply swotchy; apply starB_substH_fwd | ].\n  unfold substH; simpl.\n  match goal with\n    | [ |- (_ * _ * _ * ?P * _ * _ ===> _)%Sep ] => \n      replace P with (tqs' (fst x8, snd x8) (fst x8 %- sel x4 \"enq\"))\n  end.\n  sepLemma.\n  destruct x8; destruct H19; simpl in *; auto.\n  destruct x8; destruct H19; simpl in *; auto.\n  destruct x8; destruct H19; simpl in *; auto.\n  make_Himp.\n  rewrite tqs'_eq.\n  apply starB_del_bwd.\n  auto.\n  rewrite tqs'_eq.\n  destruct x8; reflexivity.\n\n  t.\n  t.\n  t.\n  t.\n\n  (* Now the hard part of yield(), with two different queues. *)\n  post; evaluate hints.\n  rewrite tqs_eq in *.\n  toFront ltac:(fun P => match P with\n                           | tqs' _ _ => idtac\n                         end) H8.\n  eapply use_HimpWeak in H8; [ | apply (tqs'_weaken (w' := (x0, x2))); (red; intuition) ].\n  t.\n\n  t.\n\n  post; evaluate hints.\n  rewrite stackSize_split in *.\n  assert (NoDup (\"rp\" :: \"enq\" :: \"deq\" :: \"sp\" :: nil)) by NoDup.\n  evaluate hints.\n  t.\n\n  propxFo.\n  autorewrite with sepFormula in *; unfold substH in *; simpl in *.\n  generalize dependent H0; evaluate hints; intro.\n  change (locals (\"rp\" :: \"enq\" :: \"deq\" :: \"sp\" :: nil) x4 21 (sel x2 \"sp\"))\n    with (locals_call (\"rp\" :: \"enq\" :: \"deq\" :: \"sp\" :: nil) x4 21 (sel x2 \"sp\")\n      (\"rp\" :: \"sc\" :: \"pc\" :: \"sp\" :: nil) 0 16) in H4.\n  assert (ok_call (\"rp\" :: \"enq\" :: \"deq\" :: \"sp\" :: nil) (\"rp\" :: \"sc\" :: \"pc\" :: \"sp\" :: nil) 21 0 16)%nat\n    by (split; [ simpl; omega\n      | split; [ simpl; omega\n        | split; [ NoDup\n          | reflexivity ] ] ]).\n  evaluate hints.\n\n  propxFo.\n  autorewrite with sepFormula in *; unfold substH in *; simpl in *.\n  generalize dependent H2; evaluate hints; intro.\n  change (locals (\"rp\" :: \"enq\" :: \"deq\" :: \"sp\" :: nil) x5 21 (sel x3 \"sp\"))\n    with (locals_call (\"rp\" :: \"enq\" :: \"deq\" :: \"sp\" :: nil) x5 21 (sel x3 \"sp\")\n      (\"rp\" :: \"sc\" :: \"pc\" :: \"sp\" :: nil) 14 16) in H5.\n  assert (ok_call (\"rp\" :: \"enq\" :: \"deq\" :: \"sp\" :: nil) (\"rp\" :: \"sc\" :: \"pc\" :: \"sp\" :: nil) 21 14 16)%nat\n    by (split; [ simpl; omega\n      | split; [ simpl; omega\n        | split; [ NoDup\n          | reflexivity ] ] ]).\n  rewrite tqs_eq in *.\n  change (tqs' (x0, x1) x0) with (tqs'_pick_this_one (sel x3 \"enq\") (x0, x1) x0) in H5.\n  evaluate hints.\n  descend.\n  toFront_conc ltac:(fun P => match P with\n                                | susp' _ _ _ _ => idtac\n                              end); apply susp'_intro.\n  descend.\n  2: step hints.\n  step hints.\n  step hints.\n  instantiate (2 := (locals (\"rp\" :: \"enq\" :: \"deq\" :: \"sp\" :: nil) x3 21 (Regs x Sp)\n    * (fun x y => x2 (x, y)))%Sep).\n  step hints.\n  descend; step hints.\n  descend; step hints.\n  descend; step hints.\n  instantiate (1 := snd w').\n  instantiate (1 := fst w').\n  destruct w'; destruct H13; simpl in *.\n  descend; step hints.\n  etransitivity; [ | apply himp_star_frame; [ reflexivity | apply tqs'_del_bwd ] ].\n  step hints.\n  unfold ginv, globalInv.\n  autorewrite with sepFormula; simpl.\n  make_Himp.\n  eapply Himp_trans; [ apply Himp_star_frame; [ apply starB_substH_fwd | apply Himp_refl ] | ].\n  unfold substH; simpl.\n  match goal with\n    | [ |- (star ?P _ ===> _)%Sep ] =>\n      replace P with (tqs' (b, w) (b %- sel x3 \"enq\")) by (rewrite tqs'_eq; reflexivity)\n  end.\n  sepLemma.\n  auto.\n  step hints.\n  unfold localsInvariantYieldy; descend; step hints.\n\n  descend; step hints.\n  intros.\n  eapply eq_neq_0; try eassumption.\n  words_rewr.\n  auto.\n  descend; step hints.\n\n  t.\n  t.\n\n  post.\n  match goal with\n    | [ H : context[locals ?a ?b ?c ?d] |- _ ] => change (locals a b c d)\n      with (exitize_me a b c d) in H\n  end.\n  rewrite tqs_eq in H3.\n  change (tqs' (x1, x2) x1) with (tqs'_pick_this_one (sel x3 \"deq\") (x1, x2) x1) in H3.\n  evaluate hints.\n  descend.\n  3: instantiate (1 := upd (upd (upd x4 \"ss\" (sel x3 \"deq\")) \"sc\" (sel x3 \"deq\")) \"ss\" 25).\n  eapply eq_neq_0; try eassumption; words_rewr.\n  descend.\n  auto.\n  descend; step hints.\n  unfold ginv, globalInv.\n  autorewrite with sepFormula; simpl.\n  make_Himp.\n  eapply Himp_trans; [ | apply Himp_star_frame; [ apply starB_substH_bwd | apply Himp_refl ] ].\n  unfold substH; simpl.\n  match goal with\n    | [ |- (_ ===> star ?P _)%Sep ] =>\n      replace P with (tqs' (x1, x2) (x1 %- sel x3 \"deq\")) by (rewrite tqs'_eq; reflexivity)\n  end.\n  sepLemma.\nQed.\n\nTransparent stackSize.\n\nEnd Make.\n", "meta": {"author": "gmalecha", "repo": "bedrock-mirror-shard", "sha": "ea7e5ad56a1d6392468b6823e0457dd44524bca7", "save_path": "github-repos/coq/gmalecha-bedrock-mirror-shard", "path": "github-repos/coq/gmalecha-bedrock-mirror-shard/bedrock-mirror-shard-ea7e5ad56a1d6392468b6823e0457dd44524bca7/platform/ThreadQueues.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.3593641588823762, "lm_q1q2_score": 0.221040524765062}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation, either version 2 of the License, or  *)\n(*  (at your option) any later version.  This file is also distributed *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Dynamic semantics for the Compcert C language *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import AST.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Csyntax.\nRequire Import Smallstep.\n\n(** * Semantics of type-dependent operations *)\n\n(** Semantics of casts.  [sem_cast v1 t1 t2 = Some v2] if value [v1],\n  viewed with static type [t1], can be cast to type [t2],\n  resulting in value [v2].  *)\n\nDefinition cast_int_int (sz: intsize) (sg: signedness) (i: int) : int :=\n  match sz, sg with\n  | I8, Signed => Int.sign_ext 8 i\n  | I8, Unsigned => Int.zero_ext 8 i\n  | I16, Signed => Int.sign_ext 16 i\n  | I16, Unsigned => Int.zero_ext 16 i \n  | I32, _ => i\n  | IBool, _ => if Int.eq i Int.zero then Int.zero else Int.one\n  end.\n\nDefinition cast_int_float (si : signedness) (i: int) : float :=\n  match si with\n  | Signed => Float.floatofint i\n  | Unsigned => Float.floatofintu i\n  end.\n\nDefinition cast_float_int (si : signedness) (f: float) : option int :=\n  match si with\n  | Signed => Float.intoffloat f\n  | Unsigned => Float.intuoffloat f\n  end.\n\nDefinition cast_float_float (sz: floatsize) (f: float) : float :=\n  match sz with\n  | F32 => Float.singleoffloat f\n  | F64 => f\n  end.\n\nFunction sem_cast (v: val) (t1 t2: type) : option val :=\n  match classify_cast t1 t2 with\n  | cast_case_neutral =>\n      match v with\n      | Vint _ | Vptr _ _ => Some v\n      | _ => None\n      end\n  | cast_case_i2i sz2 si2 =>\n      match v with\n      | Vint i => Some (Vint (cast_int_int sz2 si2 i))\n      | _ => None\n      end\n  | cast_case_f2f sz2 =>\n      match v with\n      | Vfloat f => Some (Vfloat (cast_float_float sz2 f))\n      | _ => None\n      end\n  | cast_case_i2f si1 sz2 =>\n      match v with\n      | Vint i => Some (Vfloat (cast_float_float sz2 (cast_int_float si1 i)))\n      | _ => None\n      end\n  | cast_case_f2i sz2 si2 =>\n      match v with\n      | Vfloat f =>\n          match cast_float_int si2 f with\n          | Some i => Some (Vint (cast_int_int sz2 si2 i))\n          | None => None\n          end\n      | _ => None\n      end\n  | cast_case_ip2bool =>\n      match v with\n      | Vint i => Some (Vint (cast_int_int IBool Signed i))\n      | Vptr _ _ => Some (Vint Int.one)\n      | _ => None\n      end\n  | cast_case_f2bool =>\n      match v with\n      | Vfloat f =>\n          Some(Vint(if Float.cmp Ceq f Float.zero then Int.zero else Int.one))\n      | _ => None\n      end\n  | cast_case_struct id1 fld1 id2 fld2 =>\n      if ident_eq id1 id2 && fieldlist_eq fld1 fld2 then Some v else None\n  | cast_case_union id1 fld1 id2 fld2 =>\n      if ident_eq id1 id2 && fieldlist_eq fld1 fld2 then Some v else None\n  | cast_case_void =>\n      Some v\n  | cast_case_default =>\n      None\n  end.\n\n(** Interpretation of values as truth values.\n  Non-zero integers, non-zero floats and non-null pointers are\n  considered as true.  The integer zero (which also represents\n  the null pointer) and the float 0.0 are false. *)\n\nFunction bool_val (v: val) (t: type) : option bool :=\n  match v, t with\n  | Vint n, (Tint _ _ _ | Tpointer _ _ | Tarray _ _ _ | Tfunction _ _) => Some (negb (Int.eq n Int.zero))\n  | Vptr b ofs, (Tint _ _ _ | Tpointer _ _ | Tarray _ _ _ | Tfunction _ _) => Some true\n  | Vfloat f, Tfloat sz _ => Some (negb(Float.cmp Ceq f Float.zero))\n  | _, _ => None\n  end.\n\n(** The following [sem_] functions compute the result of an operator\n  application.  Since operators are overloaded, the result depends\n  both on the static types of the arguments and on their run-time values.\n  For binary operations, the \"usual binary conversions\", adapted to a 32-bit\n  platform, state that:\n- If both arguments are of integer type, an integer operation is performed.\n  For operations that behave differently at unsigned and signed types\n  (e.g. division, modulus, comparisons), the unsigned operation is selected\n  if at least one of the arguments is of type \"unsigned int32\", otherwise\n  the signed operation is performed.\n- If both arguments are of float type, a float operation is performed.\n  We choose to perform all float arithmetic in double precision,\n  even if both arguments are single-precision floats.\n- If one argument has integer type and the other has float type,\n  we convert the integer argument to float, then perform the float operation.\n *)\n\nFunction sem_neg (v: val) (ty: type) : option val :=\n  match classify_neg ty with\n  | neg_case_i sg =>\n      match v with\n      | Vint n => Some (Vint (Int.neg n))\n      | _ => None\n      end\n  | neg_case_f =>\n      match v with\n      | Vfloat f => Some (Vfloat (Float.neg f))\n      | _ => None\n      end\n  | neg_default => None\n  end.\n\nFunction sem_notint (v: val) (ty: type): option val :=\n  match classify_notint ty with\n  | notint_case_i sg =>\n      match v with\n      | Vint n => Some (Vint (Int.xor n Int.mone))\n      | _ => None\n      end\n  | notint_default => None\n  end.\n\nFunction sem_notbool (v: val) (ty: type) : option val :=\n  match classify_bool ty with\n  | bool_case_ip =>\n      match v with\n      | Vint n => Some (Val.of_bool (Int.eq n Int.zero))\n      | Vptr _ _ => Some Vfalse\n      | _ => None\n      end\n  | bool_case_f =>\n      match v with\n      | Vfloat f => Some (Val.of_bool (Float.cmp Ceq f Float.zero))\n      | _ => None\n      end\n  | bool_default => None\n  end.\n\nFunction sem_add (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_add t1 t2 with \n  | add_case_ii sg =>                   (**r integer addition *)\n      match v1, v2 with\n      | Vint n1, Vint n2 => Some (Vint (Int.add n1 n2))\n      | _,  _ => None\n      end\n  | add_case_ff =>                      (**r float addition *)\n      match v1, v2 with\n      | Vfloat n1, Vfloat n2 => Some (Vfloat (Float.add n1 n2))\n      | _,  _ => None\n      end\n  | add_case_if sg =>                   (**r int plus float *)\n      match v1, v2 with\n      | Vint n1, Vfloat n2 => Some (Vfloat (Float.add (cast_int_float sg n1) n2))\n      | _, _ => None\n      end\n  | add_case_fi sg =>                   (**r float plus int *)\n      match v1, v2 with\n      | Vfloat n1, Vint n2 => Some (Vfloat (Float.add n1 (cast_int_float sg n2)))\n      | _, _ => None\n      end\n  | add_case_pi ty _ =>                 (**r pointer plus integer *)\n      match v1,v2 with\n      | Vptr b1 ofs1, Vint n2 => \n        Some (Vptr b1 (Int.add ofs1 (Int.mul (Int.repr (sizeof ty)) n2)))\n      | _,  _ => None\n      end   \n  | add_case_ip ty _ =>                 (**r integer plus pointer *)\n      match v1,v2 with\n      | Vint n1, Vptr b2 ofs2 => \n        Some (Vptr b2 (Int.add ofs2 (Int.mul (Int.repr (sizeof ty)) n1)))\n      | _,  _ => None\n      end   \n  | add_default => None\nend.\n\nFunction sem_sub (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_sub t1 t2 with\n  | sub_case_ii sg =>            (**r integer subtraction *)\n      match v1,v2 with\n      | Vint n1, Vint n2 => Some (Vint (Int.sub n1 n2))\n      | _,  _ => None\n      end \n  | sub_case_ff =>               (**r float subtraction *)\n      match v1,v2 with\n      | Vfloat f1, Vfloat f2 => Some (Vfloat(Float.sub f1 f2))\n      | _,  _ => None\n      end\n  | sub_case_if sg =>            (**r int minus float *)\n      match v1, v2 with\n      | Vint n1, Vfloat n2 => Some (Vfloat (Float.sub (cast_int_float sg n1) n2))\n      | _, _ => None\n      end\n  | sub_case_fi sg =>            (**r float minus int *)\n      match v1, v2 with\n      | Vfloat n1, Vint n2 => Some (Vfloat (Float.sub n1 (cast_int_float sg n2)))\n      | _, _ => None\n      end\n  | sub_case_pi ty =>            (**r pointer minus integer *)\n      match v1,v2 with\n      | Vptr b1 ofs1, Vint n2 => \n            Some (Vptr b1 (Int.sub ofs1 (Int.mul (Int.repr (sizeof ty)) n2)))\n      | _,  _ => None\n      end\n  | sub_case_pp ty =>          (**r pointer minus pointer *)\n      match v1,v2 with\n      | Vptr b1 ofs1, Vptr b2 ofs2 =>\n          if zeq b1 b2 then\n            if Int.eq (Int.repr (sizeof ty)) Int.zero then None\n            else Some (Vint (Int.divu (Int.sub ofs1 ofs2) (Int.repr (sizeof ty))))\n          else None\n      | _, _ => None\n      end\n  | sub_default => None\n  end.\n \nFunction sem_mul (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n match classify_mul t1 t2 with\n  | mul_case_ii sg =>\n      match v1,v2 with\n      | Vint n1, Vint n2 => Some (Vint (Int.mul n1 n2))\n      | _,  _ => None\n      end\n  | mul_case_ff =>\n      match v1,v2 with\n      | Vfloat f1, Vfloat f2 => Some (Vfloat (Float.mul f1 f2))\n      | _,  _ => None\n      end\n  | mul_case_if sg =>\n      match v1, v2 with\n      | Vint n1, Vfloat n2 => Some (Vfloat (Float.mul (cast_int_float sg n1) n2))\n      | _, _ => None\n      end\n  | mul_case_fi sg =>\n      match v1, v2 with\n      | Vfloat n1, Vint n2 => Some (Vfloat (Float.mul n1 (cast_int_float sg n2)))\n      | _, _ => None\n      end\n  | mul_default =>\n      None\nend.\n\nFunction sem_div (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n   match classify_div t1 t2 with\n  | div_case_ii Unsigned =>\n      match v1,v2 with\n      | Vint n1, Vint n2 =>\n          if Int.eq n2 Int.zero then None else Some (Vint (Int.divu n1 n2))\n      | _,_ => None\n      end\n  | div_case_ii Signed =>\n      match v1,v2 with\n       | Vint n1, Vint n2 =>\n          if Int.eq n2 Int.zero\n          || Int.eq n1 (Int.repr Int.min_signed) && Int.eq n2 Int.mone\n          then None else Some (Vint(Int.divs n1 n2))\n      | _,_ => None\n      end\n  | div_case_ff =>\n      match v1,v2 with\n      | Vfloat f1, Vfloat f2 => Some (Vfloat(Float.div f1 f2))\n      | _,  _ => None\n      end \n  | div_case_if sg =>\n      match v1, v2 with\n      | Vint n1, Vfloat n2 => Some (Vfloat (Float.div (cast_int_float sg n1) n2))\n      | _, _ => None\n      end\n  | div_case_fi sg =>\n      match v1, v2 with\n      | Vfloat n1, Vint n2 => Some (Vfloat (Float.div n1 (cast_int_float sg n2)))\n      | _, _ => None\n      end\n  | div_default =>\n      None\nend.\n\nFunction sem_mod (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_binint t1 t2 with\n  | binint_case_ii Unsigned =>\n      match v1, v2 with\n      | Vint n1, Vint n2 =>\n          if Int.eq n2 Int.zero then None else Some (Vint (Int.modu n1 n2))\n      | _, _ => None\n      end\n  | binint_case_ii Signed =>\n      match v1,v2 with\n      | Vint n1, Vint n2 =>\n          if Int.eq n2 Int.zero\n          || Int.eq n1 (Int.repr Int.min_signed) && Int.eq n2 Int.mone\n          then None else Some (Vint (Int.mods n1 n2))\n      | _, _ => None\n      end\n  | binint_default =>\n      None\n  end.\n\nFunction sem_and (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_binint t1 t2 with\n  | binint_case_ii sg =>\n      match v1, v2 with\n      | Vint n1, Vint n2 => Some (Vint(Int.and n1 n2))\n      | _, _ => None\n      end\n  | binint_default => None\n  end.\n\nFunction sem_or (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_binint t1 t2 with\n  | binint_case_ii sg =>\n      match v1, v2 with\n      | Vint n1, Vint n2 => Some (Vint(Int.or n1 n2))\n      | _, _ => None\n      end\n  | binint_default => None\n  end.\n\nFunction sem_xor (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_binint t1 t2 with\n  | binint_case_ii sg =>\n      match v1, v2 with\n      | Vint n1, Vint n2 => Some (Vint(Int.xor n1 n2))\n      | _, _ => None\n      end\n  | binint_default => None\n  end.\n\nFunction sem_shl (v1:val) (t1:type) (v2: val) (t2:type) : option val :=\n  match classify_shift t1 t2 with\n  | shift_case_ii sg =>\n      match v1, v2 with\n      | Vint n1, Vint n2 =>\n         if Int.ltu n2 Int.iwordsize then Some (Vint(Int.shl n1 n2)) else None\n      | _, _ => None\n      end\n  | shift_default => None\n  end.\n\nFunction sem_shr (v1: val) (t1: type) (v2: val) (t2: type): option val :=\n  match classify_shift t1 t2 with \n  | shift_case_ii Unsigned =>\n      match v1,v2 with \n      | Vint n1, Vint n2 =>\n          if Int.ltu n2 Int.iwordsize then Some (Vint (Int.shru n1 n2)) else None\n      | _,_ => None\n      end\n   | shift_case_ii Signed =>\n      match v1,v2 with\n      | Vint n1,  Vint n2 =>\n          if Int.ltu n2 Int.iwordsize then Some (Vint (Int.shr n1 n2)) else None\n      | _,  _ => None\n      end\n   | shift_default =>\n      None\n   end.\n\nFunction sem_cmp_mismatch (c: comparison): option val :=\n  match c with\n  | Ceq =>  Some Vfalse\n  | Cne =>  Some Vtrue\n  | _   => None\n  end.\n\nFunction sem_cmp (c:comparison)\n                  (v1: val) (t1: type) (v2: val) (t2: type)\n                  (m: mem): option val :=\n  match classify_cmp t1 t2 with\n  | cmp_case_ii Signed =>\n      match v1,v2 with\n      | Vint n1, Vint n2 => Some (Val.of_bool (Int.cmp c n1 n2))\n      | _,  _ => None\n      end\n  | cmp_case_ii Unsigned =>\n      match v1,v2 with\n      | Vint n1, Vint n2 => Some (Val.of_bool (Int.cmpu c n1 n2))\n      | _,  _ => None\n      end\n  | cmp_case_pp =>\n      match v1,v2 with\n      | Vint n1, Vint n2 => Some (Val.of_bool (Int.cmpu c n1 n2))\n      | Vptr b1 ofs1,  Vptr b2 ofs2  =>\n          if Mem.valid_pointer m b1 (Int.unsigned ofs1)\n          && Mem.valid_pointer m b2 (Int.unsigned ofs2) then\n            if zeq b1 b2\n            then Some (Val.of_bool (Int.cmpu c ofs1 ofs2))\n            else sem_cmp_mismatch c\n          else None\n      | Vptr b ofs, Vint n =>\n          if Int.eq n Int.zero then sem_cmp_mismatch c else None\n      | Vint n, Vptr b ofs =>\n          if Int.eq n Int.zero then sem_cmp_mismatch c else None\n      | _,  _ => None\n      end\n  | cmp_case_ff =>\n      match v1,v2 with\n      | Vfloat f1, Vfloat f2 => Some (Val.of_bool (Float.cmp c f1 f2))  \n      | _,  _ => None\n      end\n  | cmp_case_if sg =>\n      match v1, v2 with\n      | Vint n1, Vfloat n2 => Some (Val.of_bool (Float.cmp c (cast_int_float sg n1) n2))\n      | _, _ => None\n      end\n  | cmp_case_fi sg =>\n      match v1, v2 with\n      | Vfloat n1, Vint n2 => Some (Val.of_bool (Float.cmp c n1 (cast_int_float sg n2)))\n      | _, _ => None\n      end\n  | cmp_default => None\n  end.\n\nDefinition sem_unary_operation\n            (op: unary_operation) (v: val) (ty: type): option val :=\n  match op with\n  | Onotbool => sem_notbool v ty\n  | Onotint => sem_notint v ty\n  | Oneg => sem_neg v ty\n  end.\n\nDefinition sem_binary_operation\n    (op: binary_operation)\n    (v1: val) (t1: type) (v2: val) (t2:type)\n    (m: mem): option val :=\n  match op with\n  | Oadd => sem_add v1 t1 v2 t2\n  | Osub => sem_sub v1 t1 v2 t2 \n  | Omul => sem_mul v1 t1 v2 t2\n  | Omod => sem_mod v1 t1 v2 t2\n  | Odiv => sem_div v1 t1 v2 t2 \n  | Oand => sem_and v1 t1 v2 t2\n  | Oor  => sem_or v1 t1 v2 t2\n  | Oxor  => sem_xor v1 t1 v2 t2\n  | Oshl => sem_shl v1 t1 v2 t2\n  | Oshr  => sem_shr v1 t1 v2 t2   \n  | Oeq => sem_cmp Ceq v1 t1 v2 t2 m\n  | One => sem_cmp Cne v1 t1 v2 t2 m\n  | Olt => sem_cmp Clt v1 t1 v2 t2 m\n  | Ogt => sem_cmp Cgt v1 t1 v2 t2 m\n  | Ole => sem_cmp Cle v1 t1 v2 t2 m\n  | Oge => sem_cmp Cge v1 t1 v2 t2 m\n  end.\n\nDefinition sem_incrdecr (id: incr_or_decr) (v: val) (ty: type) :=\n  match id with\n  | Incr => sem_add v ty (Vint Int.one) type_int32s\n  | Decr => sem_sub v ty (Vint Int.one) type_int32s\n  end.\n\n(** Common-sense relations between boolean operators *)\n\nLemma cast_bool_bool_val:\n  forall v t,\n  sem_cast v t (Tint IBool Signed noattr) =\n  match bool_val v t with None => None | Some b => Some(Val.of_bool b) end.\nProof.\n  intros. unfold sem_cast, bool_val. destruct t; simpl; destruct v; auto.\n  destruct (Int.eq i0 Int.zero); auto. \n  destruct (Float.cmp Ceq f0 Float.zero); auto.\n  destruct (Int.eq i Int.zero); auto. \n  destruct (Int.eq i Int.zero); auto. \n  destruct (Int.eq i Int.zero); auto. \nQed.\n\nLemma notbool_bool_val:\n  forall v t,\n  sem_notbool v t =\n  match bool_val v t with None => None | Some b => Some(Val.of_bool (negb b)) end.\nProof.\n  assert (CB: forall i s a, classify_bool (Tint i s a) = bool_case_ip).\n    intros. destruct i; auto. destruct s; auto. \n  intros. unfold sem_notbool, bool_val. destruct t; try rewrite CB; simpl; destruct v; auto.\n  destruct (Int.eq i0 Int.zero); auto. \n  destruct (Float.cmp Ceq f0 Float.zero); auto.\n  destruct (Int.eq i Int.zero); auto. \n  destruct (Int.eq i Int.zero); auto. \n  destruct (Int.eq i Int.zero); auto. \nQed.\n\n(** * Operational semantics *)\n\n(** The semantics uses two environments.  The global environment\n  maps names of functions and global variables to memory block references,\n  and function pointers to their definitions.  (See module [Globalenvs].) *)\n\nDefinition genv := Genv.t fundef type.\n\n(** The local environment maps local variables to block references and types.\n  The current value of the variable is stored in the associated memory\n  block. *)\n\nDefinition env := PTree.t (block * type). (* map variable -> location & type *)\n\nDefinition empty_env: env := (PTree.empty (block * type)).\n\n(** [deref_loc ty m b ofs t v] computes the value of a datum\n  of type [ty] residing in memory [m] at block [b], offset [ofs].\n  If the type [ty] indicates an access by value, the corresponding\n  memory load is performed.  If the type [ty] indicates an access by\n  reference, the pointer [Vptr b ofs] is returned.  [v] is the value\n  returned, and [t] the trace of observables (nonempty if this is\n  a volatile access). *)\n\nInductive deref_loc {F V: Type} (ge: Genv.t F V) (ty: type) (m: mem) (b: block) (ofs: int) : trace -> val -> Prop :=\n  | deref_loc_value: forall chunk v,\n      access_mode ty = By_value chunk ->\n      type_is_volatile ty = false ->\n      Mem.loadv chunk m (Vptr b ofs) = Some v ->\n      deref_loc ge ty m b ofs E0 v\n  | deref_loc_volatile: forall chunk t v,\n      access_mode ty = By_value chunk -> type_is_volatile ty = true ->\n      volatile_load ge chunk m b ofs t v ->\n      deref_loc ge ty m b ofs t v\n  | deref_loc_reference:\n      access_mode ty = By_reference ->\n      deref_loc ge ty m b ofs E0 (Vptr b ofs)\n  | deref_loc_copy:\n      access_mode ty = By_copy ->\n      deref_loc ge ty m b ofs E0 (Vptr b ofs).\n\n(** Symmetrically, [assign_loc ty m b ofs v t m'] returns the\n  memory state after storing the value [v] in the datum\n  of type [ty] residing in memory [m] at block [b], offset [ofs].\n  This is allowed only if [ty] indicates an access by value or by copy.\n  [m'] is the updated memory state and [t] the trace of observables\n  (nonempty if this is a volatile store). *)\n\nInductive assign_loc {F V: Type} (ge: Genv.t F V) (ty: type) (m: mem) (b: block) (ofs: int):\n                                            val -> trace -> mem -> Prop :=\n  | assign_loc_value: forall v chunk m',\n      access_mode ty = By_value chunk ->\n      type_is_volatile ty = false ->\n      Mem.storev chunk m (Vptr b ofs) v = Some m' ->\n      assign_loc ge ty m b ofs v E0 m'\n  | assign_loc_volatile: forall v chunk t m',\n      access_mode ty = By_value chunk -> type_is_volatile ty = true ->\n      volatile_store ge chunk m b ofs v t m' ->\n      assign_loc ge ty m b ofs v t m'\n  | assign_loc_copy: forall b' ofs' bytes m',\n      access_mode ty = By_copy ->\n      (alignof ty | Int.unsigned ofs') -> (alignof ty | Int.unsigned ofs) ->\n      b' <> b \\/ Int.unsigned ofs' = Int.unsigned ofs\n              \\/ Int.unsigned ofs' + sizeof ty <= Int.unsigned ofs\n              \\/ Int.unsigned ofs + sizeof ty <= Int.unsigned ofs' ->\n      Mem.loadbytes m b' (Int.unsigned ofs') (sizeof ty) = Some bytes ->\n      Mem.storebytes m b (Int.unsigned ofs) bytes = Some m' ->\n      assign_loc ge ty m b ofs (Vptr b' ofs') E0 m'.\n\n(** Allocation of function-local variables.\n  [alloc_variables e1 m1 vars e2 m2] allocates one memory block\n  for each variable declared in [vars], and associates the variable\n  name with this block.  [e1] and [m1] are the initial local environment\n  and memory state.  [e2] and [m2] are the final local environment\n  and memory state. *)\n\nInductive alloc_variables: env -> mem ->\n                           list (ident * type) ->\n                           env -> mem -> Prop :=\n  | alloc_variables_nil:\n      forall e m,\n      alloc_variables e m nil e m\n  | alloc_variables_cons:\n      forall e m id ty vars m1 b1 m2 e2,\n      Mem.alloc m 0 (sizeof ty) = (m1, b1) ->\n      alloc_variables (PTree.set id (b1, ty) e) m1 vars e2 m2 ->\n      alloc_variables e m ((id, ty) :: vars) e2 m2.\n\n(** Initialization of local variables that are parameters to a function.\n  [bind_parameters e m1 params args m2] stores the values [args]\n  in the memory blocks corresponding to the variables [params].\n  [m1] is the initial memory state and [m2] the final memory state. *)\n\nInductive bind_parameters {F V: Type} (ge: Genv.t F V) (e: env):\n                           mem -> list (ident * type) -> list val ->\n                           mem -> Prop :=\n  | bind_parameters_nil:\n      forall m,\n      bind_parameters ge e m nil nil m\n  | bind_parameters_cons:\n      forall m id ty params v1 vl b m1 m2,\n      PTree.get id e = Some(b, ty) ->\n      assign_loc ge ty m b Int.zero v1 E0 m1 ->\n      bind_parameters ge e m1 params vl m2 ->\n      bind_parameters ge e m ((id, ty) :: params) (v1 :: vl) m2.\n\n(** Return the list of blocks in the codomain of [e], with low and high bounds. *)\n\nDefinition block_of_binding (id_b_ty: ident * (block * type)) :=\n  match id_b_ty with (id, (b, ty)) => (b, 0, sizeof ty) end.\n\nDefinition blocks_of_env (e: env) : list (block * Z * Z) :=\n  List.map block_of_binding (PTree.elements e).\n\n(** Selection of the appropriate case of a [switch], given the value [n]\n  of the selector expression. *)\n\nFixpoint select_switch (n: int) (sl: labeled_statements)\n                       {struct sl}: labeled_statements :=\n  match sl with\n  | LSdefault _ => sl\n  | LScase c s sl' => if Int.eq c n then sl else select_switch n sl'\n  end.\n\n(** Turn a labeled statement into a sequence *)\n\nFixpoint seq_of_labeled_statement (sl: labeled_statements) : statement :=\n  match sl with\n  | LSdefault s => s\n  | LScase c s sl' => Ssequence s (seq_of_labeled_statement sl')\n  end.\n\nSection SEMANTICS.\n\nVariable ge: genv.\n\n(** [type_of_global b] returns the type of the global variable or function\n  at address [b]. *)\n\nDefinition type_of_global (b: block) : option type :=\n  match Genv.find_var_info ge b with\n  | Some gv => Some gv.(gvar_info)\n  | None =>\n      match Genv.find_funct_ptr ge b with\n      | Some fd => Some(type_of_fundef fd)\n      | None => None\n      end\n  end.\n\n(** ** Reduction semantics for expressions *)\n\nSection EXPR.\n\nVariable e: env.\n\n(** The semantics of expressions follows the popular Wright-Felleisen style.\n  It is a small-step semantics that reduces one redex at a time.\n  We first define head reductions (at the top of an expression, then\n  use reduction contexts to define reduction within an expression. *)\n\n(** Head reduction for l-values. *)\n\nInductive lred: expr -> mem -> expr -> mem -> Prop :=\n  | red_var_local: forall x ty m b,\n      e!x = Some(b, ty) ->\n      lred (Evar x ty) m\n           (Eloc b Int.zero ty) m\n  | red_var_global: forall x ty m b,\n      e!x = None ->\n      Genv.find_symbol ge x = Some b ->\n      type_of_global b = Some ty ->\n      lred (Evar x ty) m\n           (Eloc b Int.zero ty) m\n  | red_deref: forall b ofs ty1 ty m,\n      lred (Ederef (Eval (Vptr b ofs) ty1) ty) m\n           (Eloc b ofs ty) m\n  | red_field_struct: forall b ofs id fList a f ty m delta,\n      field_offset f fList = OK delta ->\n      lred (Efield (Eval (Vptr b ofs) (Tstruct id fList a)) f ty) m\n           (Eloc b (Int.add ofs (Int.repr delta)) ty) m\n  | red_field_union: forall b ofs id fList a f ty m,\n      lred (Efield (Eval (Vptr b ofs) (Tunion id fList a)) f ty) m\n           (Eloc b ofs ty) m.\n\n(** Head reductions for r-values *)\n\nInductive rred: expr -> mem -> trace -> expr -> mem -> Prop :=\n  | red_rvalof: forall b ofs ty m t v,\n      deref_loc ge ty m b ofs t v ->\n      rred (Evalof (Eloc b ofs ty) ty) m\n         t (Eval v ty) m\n  | red_addrof: forall b ofs ty1 ty m,\n      rred (Eaddrof (Eloc b ofs ty1) ty) m\n        E0 (Eval (Vptr b ofs) ty) m\n  | red_unop: forall op v1 ty1 ty m v,\n      sem_unary_operation op v1 ty1 = Some v ->\n      rred (Eunop op (Eval v1 ty1) ty) m\n        E0 (Eval v ty) m\n  | red_binop: forall op v1 ty1 v2 ty2 ty m v,\n      sem_binary_operation op v1 ty1 v2 ty2 m = Some v ->\n      rred (Ebinop op (Eval v1 ty1) (Eval v2 ty2) ty) m\n        E0 (Eval v ty) m\n  | red_cast: forall ty v1 ty1 m v,\n      sem_cast v1 ty1 ty = Some v ->\n      rred (Ecast (Eval v1 ty1) ty) m\n        E0 (Eval v ty) m\n  | red_condition: forall v1 ty1 r1 r2 ty b m,\n      bool_val v1 ty1 = Some b ->\n      rred (Econdition (Eval v1 ty1) r1 r2 ty) m\n        E0 (Eparen (if b then r1 else r2) ty) m\n  | red_sizeof: forall ty1 ty m,\n      rred (Esizeof ty1 ty) m\n        E0 (Eval (Vint (Int.repr (sizeof ty1))) ty) m\n  | red_alignof: forall ty1 ty m,\n      rred (Ealignof ty1 ty) m\n        E0 (Eval (Vint (Int.repr (alignof ty1))) ty) m\n  | red_assign: forall b ofs ty1 v2 ty2 m v t m',\n      sem_cast v2 ty2 ty1 = Some v ->\n      assign_loc ge ty1 m b ofs v t m' ->\n      rred (Eassign (Eloc b ofs ty1) (Eval v2 ty2) ty1) m\n         t (Eval v ty1) m'\n  | red_assignop: forall op b ofs ty1 v2 ty2 tyres m t v1,\n      deref_loc ge ty1 m b ofs t v1 ->\n      rred (Eassignop op (Eloc b ofs ty1) (Eval v2 ty2) tyres ty1) m\n         t (Eassign (Eloc b ofs ty1)\n                    (Ebinop op (Eval v1 ty1) (Eval v2 ty2) tyres) ty1) m\n  | red_postincr: forall id b ofs ty m t v1 op,\n      deref_loc ge ty m b ofs t v1 ->\n      op = match id with Incr => Oadd | Decr => Osub end ->\n      rred (Epostincr id (Eloc b ofs ty) ty) m\n         t (Ecomma (Eassign (Eloc b ofs ty) \n                           (Ebinop op (Eval v1 ty) (Eval (Vint Int.one) type_int32s) (typeconv ty))\n                           ty)\n                   (Eval v1 ty) ty) m\n  | red_comma: forall v ty1 r2 ty m,\n      typeof r2 = ty ->\n      rred (Ecomma (Eval v ty1) r2 ty) m\n        E0 r2 m\n  | red_paren: forall v1 ty1 ty m v,\n      sem_cast v1 ty1 ty = Some v ->\n      rred (Eparen (Eval v1 ty1) ty) m\n        E0 (Eval v ty) m.\n\n(** Head reduction for function calls.\n    (More exactly, identification of function calls that can reduce.) *)\n\nInductive cast_arguments: exprlist -> typelist -> list val -> Prop :=\n  | cast_args_nil:\n      cast_arguments Enil Tnil nil\n  | cast_args_cons: forall v ty el targ1 targs v1 vl,\n      sem_cast v ty targ1 = Some v1 -> cast_arguments el targs vl ->\n      cast_arguments (Econs (Eval v ty) el) (Tcons targ1 targs) (v1 :: vl).\n\nInductive callred: expr -> fundef -> list val -> type -> Prop :=\n  | red_Ecall: forall vf tyf tyargs tyres el ty fd vargs,\n      Genv.find_funct ge vf = Some fd ->\n      cast_arguments el tyargs vargs ->\n      type_of_fundef fd = Tfunction tyargs tyres ->\n      classify_fun tyf = fun_case_f tyargs tyres ->\n      callred (Ecall (Eval vf tyf) el ty)\n              fd vargs ty.\n\n(** Reduction contexts.  In accordance with C's nondeterministic semantics,\n  we allow reduction both to the left and to the right of a binary operator.\n  To enforce C's notion of sequence point, reductions within a conditional\n  [a ? b : c] can only take place in [a], not in [b] nor [c];\n  and reductions within a sequence [a, b] can only take place in [a], not in [b].\n\n  Reduction contexts are represented by functions [C] from expressions to expressions,\n  suitably constrained by the [context from to C] predicate below.\n  Contexts are \"kinded\" with respect to l-values and r-values:\n  [from] is the kind of the hole in the context and [to] is the kind of\n  the term resulting from filling the hole.\n*)\n\nInductive kind : Type := LV | RV.\n\nInductive context: kind -> kind -> (expr -> expr) -> Prop :=\n  | ctx_top: forall k,\n      context k k (fun x => x)\n  | ctx_deref: forall k C ty,\n      context k RV C -> context k LV (fun x => Ederef (C x) ty)\n  | ctx_field: forall k C f ty,\n      context k RV C -> context k LV (fun x => Efield (C x) f ty)\n  | ctx_rvalof: forall k C ty,\n      context k LV C -> context k RV (fun x => Evalof (C x) ty)\n  | ctx_addrof: forall k C ty,\n      context k LV C -> context k RV (fun x => Eaddrof (C x) ty)\n  | ctx_unop: forall k C op ty,\n      context k RV C -> context k RV (fun x => Eunop op (C x) ty)\n  | ctx_binop_left: forall k C op e2 ty,\n      context k RV C -> context k RV (fun x => Ebinop op (C x) e2 ty)\n  | ctx_binop_right: forall k C op e1 ty,\n      context k RV C -> context k RV (fun x => Ebinop op e1 (C x) ty)\n  | ctx_cast: forall k C ty,\n      context k RV C -> context k RV (fun x => Ecast (C x) ty)\n  | ctx_condition: forall k C r2 r3 ty,\n      context k RV C -> context k RV (fun x => Econdition (C x) r2 r3 ty)\n  | ctx_assign_left: forall k C e2 ty,\n      context k LV C -> context k RV (fun x => Eassign (C x) e2 ty)\n  | ctx_assign_right: forall k C e1 ty,\n      context k RV C -> context k RV (fun x => Eassign e1 (C x) ty)\n  | ctx_assignop_left: forall k C op e2 tyres ty,\n      context k LV C -> context k RV (fun x => Eassignop op (C x) e2 tyres ty)\n  | ctx_assignop_right: forall k C op e1 tyres ty,\n      context k RV C -> context k RV (fun x => Eassignop op e1 (C x) tyres ty)\n  | ctx_postincr: forall k C id ty,\n      context k LV C -> context k RV (fun x => Epostincr id (C x) ty)\n  | ctx_call_left: forall k C el ty,\n      context k RV C -> context k RV (fun x => Ecall (C x) el ty)\n  | ctx_call_right: forall k C e1 ty,\n      contextlist k C -> context k RV (fun x => Ecall e1 (C x) ty)\n  | ctx_comma: forall k C e2 ty,\n      context k RV C -> context k RV (fun x => Ecomma (C x) e2 ty)\n  | ctx_paren: forall k C ty,\n      context k RV C -> context k RV (fun x => Eparen (C x) ty)\n\nwith contextlist: kind -> (expr -> exprlist) -> Prop :=\n  | ctx_list_head: forall k C el,\n      context k RV C -> contextlist k (fun x => Econs (C x) el)\n  | ctx_list_tail: forall k C e1,\n      contextlist k C -> contextlist k (fun x => Econs e1 (C x)).\n\n(** In a nondeterministic semantics, expressions can go wrong according\n  to one reduction order while being defined according to another.\n  Consider for instance [(x = 1) + (10 / x)] where [x] is initially [0].\n  This expression goes wrong if evaluated right-to-left, but is defined\n  if evaluated left-to-right.  Since our compiler is going to pick one\n  particular evaluation order, we must make sure that all orders are safe,\n  i.e. never evaluate a subexpression that goes wrong.\n\n  Being safe is a stronger requirement than just not getting stuck during\n  reductions.  Consider [f() + (10 / x)], where [f()] does not terminate.\n  This expression is never stuck because the evaluation of [f()] can make\n  infinitely many transitions.  Yet it contains a subexpression [10 / x]\n  that can go wrong if [x = 0], and the compiler may choose to evaluate\n  [10 / x] first, before calling [f()].  \n\n  Therefore, we must make sure that not only an expression cannot get stuck,\n  but none of its subexpressions can either.  We say that a subexpression\n  is not immediately stuck if it is a value (of the appropriate kind)\n  or it can reduce (at head or within). *)\n\nInductive imm_safe: kind -> expr -> mem -> Prop :=\n  | imm_safe_val: forall v ty m,\n      imm_safe RV (Eval v ty) m\n  | imm_safe_loc: forall b ofs ty m,\n      imm_safe LV (Eloc b ofs ty) m\n  | imm_safe_lred: forall to C e m e' m',\n      lred e m e' m' ->\n      context LV to C ->\n      imm_safe to (C e) m\n  | imm_safe_rred: forall to C e m t e' m',\n      rred e m t e' m' ->\n      context RV to C ->\n      imm_safe to (C e) m\n  | imm_safe_callred: forall to C e m fd args ty,\n      callred e fd args ty ->\n      context RV to C ->\n      imm_safe to (C e) m.\n\n(* An expression is not stuck if none of the potential redexes contained within\n   is immediately stuck. *)\n(*\nDefinition not_stuck (e: expr) (m: mem) : Prop :=\n  forall k C e' , \n  context k RV C -> e = C e' -> not_imm_stuck k e' m.\n*)\nEnd EXPR. \n\n(** ** Transition semantics. *)\n\n(** Continuations describe the computations that remain to be performed\n    after the statement or expression under consideration has\n    evaluated completely. *)\n\nInductive cont: Type :=\n  | Kstop: cont\n  | Kdo: cont -> cont       (**r [Kdo k] = after [x] in [x;] *)\n  | Kseq: statement -> cont -> cont    (**r [Kseq s2 k] = after [s1] in [s1;s2] *)\n  | Kifthenelse: statement -> statement -> cont -> cont     (**r [Kifthenelse s1 s2 k] = after [x] in [if (x) { s1 } else { s2 }] *)\n  | Kwhile1: expr -> statement -> cont -> cont      (**r [Kwhile1 x s k] = after [x] in [while(x) s] *)\n  | Kwhile2: expr -> statement -> cont -> cont      (**r [Kwhile x s k] = after [s] in [while (x) s] *)\n  | Kdowhile1: expr -> statement -> cont -> cont    (**r [Kdowhile1 x s k] = after [s] in [do s while (x)] *)\n  | Kdowhile2: expr -> statement -> cont -> cont    (**r [Kdowhile2 x s k] = after [x] in [do s while (x)] *)\n  | Kfor2: expr -> statement -> statement -> cont -> cont   (**r [Kfor2 e2 e3 s k] = after [e2] in [for(e1;e2;e3) s] *)\n  | Kfor3: expr -> statement -> statement -> cont -> cont   (**r [Kfor3 e2 e3 s k] = after [s] in [for(e1;e2;e3) s] *)\n  | Kfor4: expr -> statement -> statement -> cont -> cont   (**r [Kfor3 e2 e3 s k] = after [e3] in [for(e1;e2;e3) s] *)\n  | Kswitch1: labeled_statements -> cont -> cont     (**r [Kswitch1 ls k] = after [e] in [switch(e) { ls }] *)\n  | Kswitch2: cont -> cont       (**r catches [break] statements arising out of [switch] *)\n  | Kreturn: cont -> cont        (**r [Kreturn k] = after [e] in [return e;] *)\n  | Kcall: function ->           (**r calling function *)\n           env ->                (**r local env of calling function *)\n           (expr -> expr) ->     (**r context of the call *)\n           type ->               (**r type of call expression *)\n           cont -> cont.\n\n(** Pop continuation until a call or stop *)\n\nFixpoint call_cont (k: cont) : cont :=\n  match k with\n  | Kstop => k\n  | Kdo k => k\n  | Kseq s k => call_cont k\n  | Kifthenelse s1 s2 k => call_cont k\n  | Kwhile1 e s k => call_cont k\n  | Kwhile2 e s k => call_cont k\n  | Kdowhile1 e s k => call_cont k\n  | Kdowhile2 e s k => call_cont k\n  | Kfor2 e2 e3 s k => call_cont k\n  | Kfor3 e2 e3 s k => call_cont k\n  | Kfor4 e2 e3 s k => call_cont k\n  | Kswitch1 ls k => call_cont k\n  | Kswitch2 k => call_cont k\n  | Kreturn k => call_cont k\n  | Kcall _ _ _ _ _ => k\n  end.\n\nDefinition is_call_cont (k: cont) : Prop :=\n  match k with\n  | Kstop => True\n  | Kcall _ _ _ _ _ => True\n  | _ => False\n  end.\n\n(** Execution states of the program are grouped in 4 classes corresponding\n  to the part of the program we are currently executing.  It can be\n  a statement ([State]), an expression ([ExprState]), a transition\n  from a calling function to a called function ([Callstate]), or\n  the symmetrical transition from a function back to its caller\n  ([Returnstate]). *)\n\nInductive state: Type :=\n  | State                               (**r execution of a statement *)\n      (f: function)\n      (s: statement)\n      (k: cont)\n      (e: env)\n      (m: mem) : state\n  | ExprState                           (**r reduction of an expression *)\n      (f: function)\n      (r: expr)\n      (k: cont)\n      (e: env)\n      (m: mem) : state\n  | Callstate                           (**r calling a function *)\n      (fd: fundef)\n      (args: list val)\n      (k: cont)\n      (m: mem) : state\n  | Returnstate                         (**r returning from a function *)\n      (res: val)\n      (k: cont)\n      (m: mem) : state\n  | Stuckstate.                         (**r undefined behavior occurred *)\n                 \n(** Find the statement and manufacture the continuation \n  corresponding to a label. *)\n\nFixpoint find_label (lbl: label) (s: statement) (k: cont) \n                    {struct s}: option (statement * cont) :=\n  match s with\n  | Ssequence s1 s2 =>\n      match find_label lbl s1 (Kseq s2 k) with\n      | Some sk => Some sk\n      | None => find_label lbl s2 k\n      end\n  | Sifthenelse a s1 s2 =>\n      match find_label lbl s1 k with\n      | Some sk => Some sk\n      | None => find_label lbl s2 k\n      end\n  | Swhile a s1 =>\n      find_label lbl s1 (Kwhile2 a s1 k)\n  | Sdowhile a s1 =>\n      find_label lbl s1 (Kdowhile1 a s1 k)\n  | Sfor a1 a2 a3 s1 =>\n      match find_label lbl a1 (Kseq (Sfor Sskip a2 a3 s1) k) with\n      | Some sk => Some sk\n      | None =>\n          match find_label lbl s1 (Kfor3 a2 a3 s1 k) with\n          | Some sk => Some sk\n          | None => find_label lbl a3 (Kfor4 a2 a3 s1 k)\n          end\n      end\n  | Sswitch e sl =>\n      find_label_ls lbl sl (Kswitch2 k)\n  | Slabel lbl' s' =>\n      if ident_eq lbl lbl' then Some(s', k) else find_label lbl s' k\n  | _ => None\n  end\n\nwith find_label_ls (lbl: label) (sl: labeled_statements) (k: cont) \n                    {struct sl}: option (statement * cont) :=\n  match sl with\n  | LSdefault s => find_label lbl s k\n  | LScase _ s sl' =>\n      match find_label lbl s (Kseq (seq_of_labeled_statement sl') k) with\n      | Some sk => Some sk\n      | None => find_label_ls lbl sl' k\n      end\n  end.\n\n(** We separate the transition rules in two groups:\n- one group that deals with reductions over expressions;\n- the other group that deals with everything else: statements, function calls, etc.\n\nThis makes it easy to express different reduction strategies for expressions:\nthe second group of rules can be reused as is. *)\n\nInductive estep: state -> trace -> state -> Prop :=\n\n  | step_lred: forall C f a k e m a' m',\n      lred e a m a' m' ->\n      context LV RV C ->\n      estep (ExprState f (C a) k e m)\n         E0 (ExprState f (C a') k e m')\n\n  | step_rred: forall C f a k e m t a' m',\n      rred a m t a' m' ->\n      context RV RV C ->\n      estep (ExprState f (C a) k e m)\n          t (ExprState f (C a') k e m')\n\n  | step_call: forall C f a k e m fd vargs ty,\n      callred a fd vargs ty ->\n      context RV RV C ->\n      estep (ExprState f (C a) k e m)\n         E0 (Callstate fd vargs (Kcall f e C ty k) m)\n\n  | step_stuck: forall C f a k e m K,\n      context K RV C -> ~(imm_safe e K a m) ->\n      estep (ExprState f (C a) k e m)\n         E0 Stuckstate.\n\nInductive sstep: state -> trace -> state -> Prop :=\n\n  | step_do_1: forall f x k e m,\n      sstep (State f (Sdo x) k e m)\n         E0 (ExprState f x (Kdo k) e m)\n  | step_do_2: forall f v ty k e m,\n      sstep (ExprState f (Eval v ty) (Kdo k) e m)\n         E0 (State f Sskip k e m)\n\n  | step_seq:  forall f s1 s2 k e m,\n      sstep (State f (Ssequence s1 s2) k e m)\n         E0 (State f s1 (Kseq s2 k) e m)\n  | step_skip_seq: forall f s k e m,\n      sstep (State f Sskip (Kseq s k) e m)\n         E0 (State f s k e m)\n  | step_continue_seq: forall f s k e m,\n      sstep (State f Scontinue (Kseq s k) e m)\n         E0 (State f Scontinue k e m)\n  | step_break_seq: forall f s k e m,\n      sstep (State f Sbreak (Kseq s k) e m)\n         E0 (State f Sbreak k e m)\n\n  | step_ifthenelse_1: forall f a s1 s2 k e m,\n      sstep (State f (Sifthenelse a s1 s2) k e m)\n         E0 (ExprState f a (Kifthenelse s1 s2 k) e m)\n  | step_ifthenelse_2:  forall f v ty s1 s2 k e m b,\n      bool_val v ty = Some b ->\n      sstep (ExprState f (Eval v ty) (Kifthenelse s1 s2 k) e m)\n         E0 (State f (if b then s1 else s2) k e m)\n\n  | step_while: forall f x s k e m,\n      sstep (State f (Swhile x s) k e m)\n        E0 (ExprState f x (Kwhile1 x s k) e m)\n  | step_while_false: forall f v ty x s k e m,\n      bool_val v ty = Some false ->\n      sstep (ExprState f (Eval v ty) (Kwhile1 x s k) e m)\n        E0 (State f Sskip k e m)\n  | step_while_true: forall f v ty x s k e m ,\n      bool_val v ty = Some true ->\n      sstep (ExprState f (Eval v ty) (Kwhile1 x s k) e m)\n        E0 (State f s (Kwhile2 x s k) e m)\n  | step_skip_or_continue_while: forall f s0 x s k e m,\n      s0 = Sskip \\/ s0 = Scontinue ->\n      sstep (State f s0 (Kwhile2 x s k) e m)\n        E0 (State f (Swhile x s) k e m)\n  | step_break_while: forall f x s k e m,\n      sstep (State f Sbreak (Kwhile2 x s k) e m)\n        E0 (State f Sskip k e m)\n\n  | step_dowhile: forall f a s k e m,\n      sstep (State f (Sdowhile a s) k e m)\n        E0 (State f s (Kdowhile1 a s k) e m)\n  | step_skip_or_continue_dowhile: forall f s0 x s k e m,\n      s0 = Sskip \\/ s0 = Scontinue ->\n      sstep (State f s0 (Kdowhile1 x s k) e m)\n         E0 (ExprState f x (Kdowhile2 x s k) e m)\n  | step_dowhile_false: forall f v ty x s k e m,\n      bool_val v ty = Some false ->\n      sstep (ExprState f (Eval v ty) (Kdowhile2 x s k) e m)\n         E0 (State f Sskip k e m)\n  | step_dowhile_true: forall f v ty x s k e m,\n      bool_val v ty = Some true ->\n      sstep (ExprState f (Eval v ty) (Kdowhile2 x s k) e m)\n         E0 (State f (Sdowhile x s) k e m)\n  | step_break_dowhile: forall f a s k e m,\n      sstep (State f Sbreak (Kdowhile1 a s k) e m)\n         E0 (State f Sskip k e m)\n\n  | step_for_start: forall f a1 a2 a3 s k e m,\n      a1 <> Sskip ->\n      sstep (State f (Sfor a1 a2 a3 s) k e m)\n         E0 (State f a1 (Kseq (Sfor Sskip a2 a3 s) k) e m)\n  | step_for: forall f a2 a3 s k e m,\n      sstep (State f (Sfor Sskip a2 a3 s) k e m)\n         E0 (ExprState f a2 (Kfor2 a2 a3 s k) e m)\n  | step_for_false: forall f v ty a2 a3 s k e m,\n      bool_val v ty = Some false ->\n      sstep (ExprState f (Eval v ty) (Kfor2 a2 a3 s k) e m)\n         E0 (State f Sskip k e m)\n  | step_for_true: forall f v ty a2 a3 s k e m,\n      bool_val v ty = Some true ->\n      sstep (ExprState f (Eval v ty) (Kfor2 a2 a3 s k) e m)\n         E0 (State f s (Kfor3 a2 a3 s k) e m)\n  | step_skip_or_continue_for3: forall f x a2 a3 s k e m,\n      x = Sskip \\/ x = Scontinue ->\n      sstep (State f x (Kfor3 a2 a3 s k) e m)\n         E0 (State f a3 (Kfor4 a2 a3 s k) e m)\n  | step_break_for3: forall f a2 a3 s k e m,\n      sstep (State f Sbreak (Kfor3 a2 a3 s k) e m)\n         E0 (State f Sskip k e m)\n  | step_skip_for4: forall f a2 a3 s k e m,\n      sstep (State f Sskip (Kfor4 a2 a3 s k) e m)\n         E0 (State f (Sfor Sskip a2 a3 s) k e m)\n\n  | step_return_0: forall f k e m m',\n      Mem.free_list m (blocks_of_env e) = Some m' ->\n      sstep (State f (Sreturn None) k e m)\n         E0 (Returnstate Vundef (call_cont k) m')\n  | step_return_1: forall f x k e m,\n      sstep (State f (Sreturn (Some x)) k e m)\n         E0 (ExprState f x (Kreturn k) e  m)\n  | step_return_2:  forall f v1 ty k e m v2 m',\n      sem_cast v1 ty f.(fn_return) = Some v2 ->\n      Mem.free_list m (blocks_of_env e) = Some m' ->\n      sstep (ExprState f (Eval v1 ty) (Kreturn k) e m)\n         E0 (Returnstate v2 (call_cont k) m')\n  | step_skip_call: forall f k e m m',\n      is_call_cont k ->\n      f.(fn_return) = Tvoid ->\n      Mem.free_list m (blocks_of_env e) = Some m' ->\n      sstep (State f Sskip k e m)\n         E0 (Returnstate Vundef k m')\n\n  | step_switch: forall f x sl k e m,\n      sstep (State f (Sswitch x sl) k e m)\n         E0 (ExprState f x (Kswitch1 sl k) e m)\n  | step_expr_switch: forall f n ty sl k e m,\n      sstep (ExprState f (Eval (Vint n) ty) (Kswitch1 sl k) e m)\n         E0 (State f (seq_of_labeled_statement (select_switch n sl)) (Kswitch2 k) e m)\n  | step_skip_break_switch: forall f x k e m,\n      x = Sskip \\/ x = Sbreak ->\n      sstep (State f x (Kswitch2 k) e m)\n         E0 (State f Sskip k e m)\n  | step_continue_switch: forall f k e m,\n      sstep (State f Scontinue (Kswitch2 k) e m)\n         E0 (State f Scontinue k e m)\n\n  | step_label: forall f lbl s k e m,\n      sstep (State f (Slabel lbl s) k e m)\n         E0 (State f s k e m)\n\n  | step_goto: forall f lbl k e m s' k',\n      find_label lbl f.(fn_body) (call_cont k) = Some (s', k') ->\n      sstep (State f (Sgoto lbl) k e m)\n         E0 (State f s' k' e m)\n\n  | step_internal_function: forall f vargs k m e m1 m2,\n      list_norepet (var_names (fn_params f) ++ var_names (fn_vars f)) ->\n      alloc_variables empty_env m (f.(fn_params) ++ f.(fn_vars)) e m1 ->\n      bind_parameters ge e m1 f.(fn_params) vargs m2 ->\n      sstep (Callstate (Internal f) vargs k m)\n         E0 (State f f.(fn_body) k e m2)\n\n  | step_external_function: forall ef targs tres vargs k m vres t m',\n      external_call ef  ge vargs m t vres m' ->\n      sstep (Callstate (External ef targs tres) vargs k m)\n          t (Returnstate vres k m')\n\n  | step_returnstate: forall v f e C ty k m,\n      sstep (Returnstate v (Kcall f e C ty k) m)\n         E0 (ExprState f (C (Eval v ty)) k e m).\n\nDefinition step (S: state) (t: trace) (S': state) : Prop :=\n  estep S t S' \\/ sstep S t S'.\n\nEnd SEMANTICS.\n\n(** * Whole-program semantics *)\n\n(** Execution of whole programs are described as sequences of transitions\n  from an initial state to a final state.  An initial state is a [Callstate]\n  corresponding to the invocation of the ``main'' function of the program\n  without arguments and with an empty continuation. *)\n\nInductive initial_state (p: program): state -> Prop :=\n  | initial_state_intro: forall b f m0,\n      let ge := Genv.globalenv p in\n      Genv.init_mem p = Some m0 ->\n      Genv.find_symbol ge p.(prog_main) = Some b ->\n      Genv.find_funct_ptr ge b = Some f ->\n      type_of_fundef f = Tfunction Tnil type_int32s ->\n      initial_state p (Callstate f nil Kstop m0).\n\n(** A final state is a [Returnstate] with an empty continuation. *)\n\nInductive final_state: state -> int -> Prop :=\n  | final_state_intro: forall r m,\n      final_state (Returnstate (Vint r) Kstop m) r.\n\n(** Wrapping up these definitions in a small-step semantics. *)\n\nDefinition semantics (p: program) :=\n  Semantics step (initial_state p) final_state (Genv.globalenv p).\n\n(** This semantics has the single-event property. *)\n\nLemma semantics_single_events: \n  forall p, single_events (semantics p).\nProof.\n  intros; red; intros. destruct H. \n  set (ge := globalenv (semantics p)) in *.\n  assert (DEREF: forall chunk m b ofs t v, deref_loc ge chunk m b ofs t v -> (length t <= 1)%nat).\n    intros. inv H0; simpl; try omega. inv H3; simpl; try omega.\n  assert (ASSIGN: forall chunk m b ofs t v m', assign_loc ge chunk m b ofs v t m' -> (length t <= 1)%nat).\n    intros. inv H0; simpl; try omega. inv H3; simpl; try omega.\n  inv H; simpl; try omega. inv H0; eauto; simpl; try omega.\n  inv H; simpl; try omega. eapply external_call_trace_length; eauto.\nQed.\n", "meta": {"author": "Ptival", "repo": "compcert-alias", "sha": "c839efb9cd2a4c27add46a1868fe0444d1dfdd9e", "save_path": "github-repos/coq/Ptival-compcert-alias", "path": "github-repos/coq/Ptival-compcert-alias/compcert-alias-c839efb9cd2a4c27add46a1868fe0444d1dfdd9e/cfrontend/Csem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.22104051717568945}}
{"text": "Require Export\n        Fiat.QueryStructure.Specification.Representation.QueryStructureNotations\n        Fiat.QueryStructure.Specification.Operations.Query.\nRequire Import Coq.Lists.List\n        Coq.Arith.Compare_dec\n        Coq.Bool.Bool\n        Coq.Strings.String\n        Fiat.Common.BoolFacts\n        Fiat.Common.List.PermutationFacts\n        Fiat.Common.List.ListMorphisms\n        Fiat.QueryStructure.Specification.Operations.FlattenCompList\n        Fiat.Common.Ensembles.EnsembleListEquivalence\n        Fiat.QueryStructure.Implementation.Operations.General.QueryRefinements\n        Fiat.Common.IterateBoundedIndex\n        Fiat.Common.List.ListFacts\n        Fiat.Common.LogicFacts\n        Fiat.Common.DecideableEnsembles\n        Fiat.Computation.Refinements.Iterate_Decide_Comp\n        Fiat.Computation.Refinements.General\n        Fiat.QueryStructure.Specification.Constraints.tupleAgree\n        Fiat.QueryStructure.Specification.Operations.Mutate.\n\nImport Lists.List.ListNotations.\n\nUnset Implicit Arguments.\n\nLocal Transparent Count Query_For.\n\nSection ConstraintCheckRefinements.\n  Hint Resolve crossConstr.\n  Hint Unfold SatisfiesCrossRelationConstraints\n       SatisfiesAttributeConstraints\n       SatisfiesTupleConstraints.\n\n  Fixpoint List_Query_eqT\n           (attrlist : list Type)\n    : Type\n    := match attrlist with\n       | [ ] => unit\n       | attr :: attrlist' =>\n         prod (Query_eq attr) (List_Query_eqT attrlist')\n       end.\n\n  Fixpoint Tuple_Agree_eq'\n           {h : RawHeading}\n           {attrlist : list (Attributes h)}\n           (attr_eq_dec : List_Query_eqT (map (Domain h) attrlist))\n           (tup tup' : @RawTuple h)\n    : bool :=\n    match attrlist return List_Query_eqT (map (Domain h) attrlist) ->\n                          bool with\n    | [ ] => fun _ => true\n    |  attr :: attrlist' =>\n       fun attr_eq_dec' =>\n         if @A_eq_dec _ (fst attr_eq_dec') (GetAttributeRaw tup attr) (GetAttributeRaw tup' attr)\n         then Tuple_Agree_eq' (snd attr_eq_dec') tup tup'\n         else false\n    end attr_eq_dec.\n\n  Class List_Query_eq (As : list Type) :=\n    { As_Query_eq : List_Query_eqT As}.\n\n  Definition Tuple_Agree_eq {h} (attrlist : list (Attributes h))\n          (attr_eq_dec : List_Query_eq (map (Domain h) attrlist)) tup tup' :=\n    @Tuple_Agree_eq' h attrlist (@As_Query_eq _ attr_eq_dec) tup tup'.\n\n  Lemma Tuple_Agree_eq_dec h attrlist attr_eq_dec (tup tup' : @RawTuple h) :\n    tupleAgree tup tup' attrlist <->\n    Tuple_Agree_eq attrlist attr_eq_dec tup tup' = true.\n  Proof.\n    destruct attr_eq_dec.\n    induction attrlist; unfold tupleAgree in *; simpl in *; simpl;\n    intuition;\n    unfold Tuple_Agree_eq in *; simpl in *; find_if_inside; simpl; subst; eauto;\n    try (eapply IHattrlist; eauto; fail);\n    discriminate.\n  Qed.\n\n  Lemma Tuple_Agree_eq_dec' h attrlist attr_eq_dec (tup tup' : @RawTuple h) :\n    ~ tupleAgree tup tup' attrlist <->\n    Tuple_Agree_eq attrlist attr_eq_dec tup tup' = false.\n  Proof.\n    destruct attr_eq_dec.\n    induction attrlist; unfold tupleAgree in *; simpl in *; simpl;\n    intuition;\n    unfold Tuple_Agree_eq in *; simpl in *; intuition;\n    find_if_inside; simpl; subst; eauto.\n    try (eapply IHattrlist; intros; eapply H).\n    intros; intuition; subst; auto.\n    eapply IHattrlist; intros; eauto.\n  Qed.\n\n  Definition Tuple_Agree_dec h attrlist\n             (attr_eq_dec : List_Query_eq (map (Domain h) attrlist)) (tup tup' : @RawTuple h)\n    : {tupleAgree tup tup' attrlist} + {~ tupleAgree tup tup' attrlist}.\n  Proof.\n    case_eq (Tuple_Agree_eq attrlist attr_eq_dec tup tup').\n    left; eapply Tuple_Agree_eq_dec; eauto.\n    right; eapply Tuple_Agree_eq_dec'; eauto.\n  Defined.\n\n\n  Lemma tupleAgree_sym :\n    forall (heading: Heading) tup1 tup2 attrs,\n      @tupleAgree heading tup1 tup2 attrs <-> @tupleAgree heading tup2 tup1 attrs.\n  Proof.\n    intros; unfold tupleAgree;\n    split; intros; rewrite H; eauto.\n  Qed.\n\n  (* Consequences of ith_replace_BoundIndex_neq and ith_replace_BoundIndex_eq on updates *)\n\n  Lemma refine_SatisfiesAttributeConstraints_self\n    : forall (qsSchema : RawQueryStructureSchema)\n             (Ridx : Fin.t _)\n             (tup : @RawTuple (rawSchemaHeading (GetNRelSchema (qschemaSchemas qsSchema) Ridx))),\n      refine {b | decides b (SatisfiesAttributeConstraints Ridx tup )}\n             match (attrConstraints (GetNRelSchema (qschemaSchemas qsSchema) _)) with\n               Some Constr => {b | decides b (Constr tup) }\n             | None => ret true\n             end.\n  Proof.\n    unfold SatisfiesAttributeConstraints.\n    intros; match goal with\n              |- context [attrConstraints ?A] => destruct (attrConstraints A)\n            end;\n    eauto using decides_True.\n    reflexivity.\n  Qed.\n\n  Lemma refine_SatisfiesTupleConstraints_self\n    : forall (qsSchema : RawQueryStructureSchema)\n             (Ridx : Fin.t _)\n             (tup tup' : @RawTuple (rawSchemaHeading (GetNRelSchema (qschemaSchemas qsSchema) Ridx))),\n      refine {b | decides b (SatisfiesTupleConstraints Ridx tup tup')}\n             match (tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) _)) with\n               Some Constr => {b | decides b (Constr tup tup') }\n             | None => ret true\n             end.\n  Proof.\n    unfold SatisfiesTupleConstraints.\n    intros; match goal with\n              |- context [tupleConstraints ?A] => destruct (tupleConstraints A)\n            end;\n    eauto using decides_True.\n    reflexivity.\n  Qed.\n\n  Lemma refine_SatisfiesTupleConstraints_Constr\n    : forall (qsSchema : QueryStructureSchema)\n             (qs : QueryStructure qsSchema)\n             (Ridx : Fin.t _)\n             (tup : @RawTuple (rawSchemaHeading (GetNRelSchema (qschemaSchemas qsSchema) Ridx))),\n      refine {b | decides\n                    b\n                    (forall tup',\n                        GetRelation qs Ridx tup'\n                        -> SatisfiesTupleConstraints\n                             Ridx\n                             tup\n                             (indexedElement tup'))}\n             match (tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) _)) with\n               Some Constr =>\n               {b | decides b (forall tup',\n                                  GetRelation qs Ridx tup'\n                                  -> Constr tup (indexedElement tup'))}\n             | None => ret true\n             end.\n  Proof.\n    unfold SatisfiesTupleConstraints.\n    intros; match goal with\n              |- context [tupleConstraints ?A] => destruct (tupleConstraints A)\n            end;\n    eauto using decides_True.\n    reflexivity.\n    apply decides_2_True.\n  Qed.\n\n  Lemma refine_SatisfiesTupleConstraints_Constr'\n    : forall (qsSchema : QueryStructureSchema)\n             (qs : QueryStructure qsSchema)\n             (Ridx : Fin.t _)\n             (tup : @RawTuple (rawSchemaHeading (GetNRelSchema (qschemaSchemas qsSchema) Ridx))),\n      refine {b | decides b\n                          (forall tup',\n                              GetRelation qs Ridx tup'\n                              -> SatisfiesTupleConstraints Ridx (indexedElement tup') tup)}\n             match tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) _) with\n               Some Constr =>\n               {b | decides b (forall tup',\n                                  GetRelation qs Ridx tup'\n                                  -> Constr (indexedElement tup') tup)}\n             | None => ret true\n             end.\n  Proof.\n    unfold SatisfiesTupleConstraints.\n    intros; match goal with\n              |- context [tupleConstraints ?A] => destruct (tupleConstraints A)\n            end;\n    eauto using decides_True.\n    reflexivity.\n    apply decides_2_True.\n  Qed.\n\n  Lemma refine_SatisfiesCrossConstraints_Constr\n    : forall (qsSchema : QueryStructureSchema)\n             (qs : QueryStructure qsSchema)\n             (Ridx : Fin.t _)\n             (tup : @RawTuple (rawSchemaHeading (GetNRelSchema (qschemaSchemas qsSchema) Ridx))),\n      refine\n        (@Iterate_Decide_Comp _\n                              (fun Ridx' =>\n                                 SatisfiesCrossRelationConstraints\n                                   Ridx Ridx' tup\n                                   (GetRelation qs Ridx')))\n        (@Iterate_Decide_Comp_opt _ (fun Ridx' =>\n                                      match (BuildQueryStructureConstraints qsSchema Ridx Ridx') with\n                                      | Some CrossConstr =>\n                                        Some (CrossConstr tup (GetRelation qs Ridx'))\n                                      | None => None\n                                      end)) .\n  Proof.\n    intros.\n    setoid_rewrite <- refine_Iterate_Decide_Comp.\n    unfold SatisfiesCrossRelationConstraints; f_equiv.\n    apply functional_extensionality; intros.\n    destruct BuildQueryStructureConstraints; reflexivity.\n  Qed.\n\n  Lemma refine_SatisfiesTupleConstraints\n    : forall (qsSchema : RawQueryStructureSchema)\n             (qs : UnConstrQueryStructure qsSchema)\n             (Ridx : Fin.t _)\n             (tup : @RawTuple (rawSchemaHeading (GetNRelSchema (qschemaSchemas qsSchema) Ridx))),\n      refine {b | decides\n                    b\n                    (forall tup',\n                        GetUnConstrRelation qs Ridx tup'\n                        -> SatisfiesTupleConstraints\n                             Ridx\n                             tup\n                             (indexedElement tup'))}\n             match (tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) _)) with\n               Some Constr =>\n               {b | decides b (forall tup',\n                                  GetUnConstrRelation qs Ridx tup'\n                                  -> Constr tup (indexedElement tup'))}\n             | None => ret true\n             end.\n  Proof.\n    unfold SatisfiesTupleConstraints.\n    intros; match goal with\n              |- context [tupleConstraints ?A] => destruct (tupleConstraints A)\n            end;\n    eauto using decides_True.\n    reflexivity.\n    apply decides_2_True.\n  Qed.\n\n  Lemma refine_SatisfiesTupleConstraints'\n    : forall (qsSchema : RawQueryStructureSchema)\n             (qs : UnConstrQueryStructure qsSchema)\n             (Ridx : Fin.t _)\n             (tup : @RawTuple (rawSchemaHeading (GetNRelSchema (qschemaSchemas qsSchema) Ridx))),\n      refine {b | decides b\n                          (forall tup',\n                              GetUnConstrRelation qs Ridx tup'\n                              -> SatisfiesTupleConstraints Ridx (indexedElement tup') tup)}\n             match tupleConstraints (GetNRelSchema (qschemaSchemas qsSchema) _) with\n               Some Constr =>\n               {b | decides b (forall tup',\n                                  GetUnConstrRelation qs Ridx tup'\n                                  -> Constr (indexedElement tup') tup)}\n             | None => ret true\n             end.\n  Proof.\n    unfold SatisfiesTupleConstraints.\n    intros; match goal with\n              |- context [tupleConstraints ?A] => destruct (tupleConstraints A)\n            end;\n    eauto using decides_True.\n    reflexivity.\n    apply decides_2_True.\n  Qed.\n\n  Lemma refine_SatisfiesCrossConstraints\n    : forall (qsSchema : RawQueryStructureSchema)\n             (qs : UnConstrQueryStructure qsSchema)\n             (Ridx : Fin.t _)\n             (tup : @RawTuple (rawSchemaHeading (GetNRelSchema (qschemaSchemas qsSchema) Ridx))),\n      refine\n        (@Iterate_Decide_Comp _\n                              (fun Ridx' =>\n                                 SatisfiesCrossRelationConstraints\n                                   Ridx Ridx' tup\n                                   (GetUnConstrRelation qs Ridx')))\n        (@Iterate_Decide_Comp_opt _ (fun Ridx' =>\n                                      match (BuildQueryStructureConstraints qsSchema Ridx Ridx') with\n                                      | Some CrossConstr =>\n                                        Some (CrossConstr tup (GetUnConstrRelation qs Ridx'))\n                                      | None => None\n                                      end)) .\n  Proof.\n    intros.\n    setoid_rewrite <- refine_Iterate_Decide_Comp.\n    unfold SatisfiesCrossRelationConstraints; f_equiv.\n    apply functional_extensionality; intros.\n    destruct BuildQueryStructureConstraints; reflexivity.\n  Qed.\n\n  Lemma refine_SatisfiesCrossConstraints'_Constr\n    : forall (qsSchema : QueryStructureSchema)\n             (qs : QueryStructure qsSchema)\n             (Ridx : Fin.t _)\n             tup idx,\n      refine\n        (@Iterate_Decide_Comp _\n                              (fun Ridx' =>\n                Ridx' <> Ridx\n                -> forall tup',\n                     (GetRelation qs Ridx') tup'\n                     -> SatisfiesCrossRelationConstraints\n                          Ridx' Ridx (indexedElement tup')\n                          (EnsembleInsert\n                             {| elementIndex := idx;\n                                indexedElement := tup |}\n                             (GetRelation qs Ridx))))\n             (@Iterate_Decide_Comp_opt _\n                                        (fun Ridx' =>\n                                           if (fin_eq_dec Ridx Ridx') then\n                                             None\n                                           else\n                                             match (BuildQueryStructureConstraints qsSchema Ridx' Ridx) with\n                                               | Some CrossConstr =>\n                                                 Some (\n                                                     forall tup',\n                                                       (GetRelation qs Ridx') tup'\n                                                       -> CrossConstr (indexedElement tup') (\n                                                                        (EnsembleInsert\n                                                                           {| elementIndex := idx;\n                                                                              indexedElement := tup |}\n                                                                           (GetRelation qs Ridx))))\n                                               | None => None\n                                      end)).\n  Proof.\n    intros.\n    setoid_rewrite <- refine_Iterate_Decide_Comp.\n    unfold SatisfiesCrossRelationConstraints.\n    apply refine_Iterate_Decide_Comp_equiv; simpl; intros.\n    simpl in *; destruct (fin_eq_dec Ridx idx0); subst.\n    congruence.\n    destruct (BuildQueryStructureConstraints qsSchema idx0 Ridx); eauto.\n    simpl in *; destruct (fin_eq_dec Ridx idx0); subst; eauto.\n    destruct (BuildQueryStructureConstraints qsSchema idx0 Ridx); eauto.\n  Qed.\n\n  Lemma refine_SatisfiesCrossConstraints'\n  : forall qsSchema qs Ridx tup,\n    forall idx,\n      refine\n        (@Iterate_Decide_Comp _\n                              (fun Ridx' =>\n                Ridx' <> Ridx\n                -> forall tup',\n                     (GetUnConstrRelation qs Ridx') tup'\n                     -> SatisfiesCrossRelationConstraints\n                          Ridx' Ridx (indexedElement tup')\n                          (EnsembleInsert\n                             {| elementIndex := idx;\n                                indexedElement := tup |}\n                             (GetUnConstrRelation qs Ridx))))\n             (@Iterate_Decide_Comp_opt _\n                                        (fun Ridx' =>\n                                           if (fin_eq_dec Ridx Ridx') then\n                                             None\n                                           else\n                                             match (BuildQueryStructureConstraints qsSchema Ridx' Ridx) with\n                                               | Some CrossConstr =>\n                                                 Some (\n                                                     forall tup',\n                                                       (GetUnConstrRelation qs Ridx') tup'\n                                                       -> CrossConstr (indexedElement tup') (\n                                                                        (EnsembleInsert\n                                                                           {| elementIndex := idx;\n                                                                              indexedElement := tup |}\n                                                                           (GetUnConstrRelation qs Ridx))))\n                                               | None => None\n                                      end)).\n  Proof.\n    intros.\n    setoid_rewrite <- refine_Iterate_Decide_Comp.\n    unfold SatisfiesCrossRelationConstraints.\n    apply refine_Iterate_Decide_Comp_equiv; simpl; intros.\n    destruct (fin_eq_dec Ridx idx0); subst.\n    congruence.\n    destruct (BuildQueryStructureConstraints qsSchema idx0 Ridx); eauto.\n    intro; eapply H.\n    destruct (fin_eq_dec Ridx idx0); subst; eauto.\n    destruct (BuildQueryStructureConstraints qsSchema idx0 Ridx); eauto.\n  Qed.\n\n  Lemma tupleAgree_refl :\n    forall (h : RawHeading)\n           (tup : @RawTuple h)\n           (attrlist : list (Attributes h)),\n      tupleAgree tup tup attrlist.\n  Proof.\n    unfold tupleAgree; auto.\n  Qed.\n\n  Lemma refine_tupleAgree_refl_True :\n    forall (h : RawHeading)\n           (tup : @RawTuple h)\n           (attrlist attrlist' : list (Attributes h)),\n      refine {b |\n              decides b (tupleAgree tup tup attrlist'\n                         -> tupleAgree tup tup attrlist)}\n             (ret true).\n  Proof.\n    unfold refine; intros;  computes_to_inv.\n    subst; computes_to_econstructor; simpl; auto using tupleAgree_refl.\n  Qed.\n\n  Lemma refine_SatisfiesCrossConstraints_Pre (Q : Prop)\n    : forall (qsSchema : RawQueryStructureSchema) qs\n             (Ridx :Fin.t _)\n             (tup : @RawTuple _),\n      refine\n        (@Iterate_Decide_Comp_Pre _\n                                  (fun Ridx' =>\n                                     SatisfiesCrossRelationConstraints\n                                       Ridx Ridx' tup\n                                       (GetUnConstrRelation qs Ridx')) Q)\n        (@Iterate_Decide_Comp_opt_Pre _\n                                       (fun Ridx' =>\n                                          match (BuildQueryStructureConstraints qsSchema Ridx Ridx') with\n                                          | Some CrossConstr =>\n                                            Some (CrossConstr tup (GetUnConstrRelation qs Ridx'))\n                                          | None => None\n                                          end) Q) .\n  Proof.\n    intros.\n    setoid_rewrite <- refine_Iterate_Decide_Comp_Pre.\n    unfold SatisfiesCrossRelationConstraints; f_equiv.\n    apply functional_extensionality; intros.\n    destruct BuildQueryStructureConstraints; reflexivity.\n  Qed.\n\n  Lemma DeletePrimaryKeysOK {qsSchema}\n    : forall (qs : UnConstrQueryStructure qsSchema)\n             (Ridx :Fin.t _)\n             DeletedTuples\n             attrlist1 attrlist2,\n      refine {b | (forall tup tup',\n                      elementIndex tup <> elementIndex tup'\n                      -> GetUnConstrRelation qs Ridx tup\n                      -> GetUnConstrRelation qs Ridx tup'\n                      -> (FunctionalDependency_P attrlist1 attrlist2 (indexedElement tup) (indexedElement tup')))\n                  -> decides b (Mutate.MutationPreservesTupleConstraints\n                                  (EnsembleDelete (GetUnConstrRelation qs Ridx) DeletedTuples)\n                                  (FunctionalDependency_P attrlist1 attrlist2)\n             )}\n             (ret true).\n  Proof.\n    unfold Mutate.MutationPreservesTupleConstraints, FunctionalDependency_P;\n    intros * v Comp_v;  computes_to_inv; subst.\n    computes_to_constructor; simpl.\n    intros.\n    unfold EnsembleDelete in *; destruct H1; destruct H2; eauto.\n  Qed.\n\n  Local Transparent Count.\n\n  Lemma In_UnConstrQuery_In {qsSchema} {A}\n    : forall (qs : UnConstrQueryStructure qsSchema) Ridx bod results,\n      UnConstrQuery_In qs Ridx bod ↝ results\n      -> forall (a : A), List.In a results ->\n                         exists (tup' : IndexedRawTuple) results',\n                           Ensembles.In _ (GetUnConstrRelation qs Ridx) tup'\n                           /\\ bod (indexedElement tup') ↝ results'\n                           /\\ List.In a results'.\n  Proof.\n    unfold UnConstrQuery_In, QueryResultComp; intros;\n    computes_to_inv.\n    unfold UnIndexedEnsembleListEquivalence in *; destruct_ex; intuition; subst.\n    rewrite map_map in H'.\n    remember (GetUnConstrRelation qs Ridx); clear Heqi;\n    revert i a results H0 H' H H3;\n    induction x; simpl in *; intros;\n    computes_to_inv; subst.\n    - simpl in H0; intuition.\n    - apply in_app_or in H0; intuition.\n      exists a; exists v; intuition; try eapply H; eauto.\n      inversion H3; subst.\n      destruct (IHx (fun tup => tup <> a /\\ i tup) _ _ H1 H''); eauto.\n      unfold Ensembles.In; intros; intuition; subst; eauto.\n      eapply H in H6; intuition.\n      apply H4; apply in_map; auto.\n      apply H; intuition.\n      destruct_ex; intuition.\n      eexists x0, x1; intuition.\n      apply H2.\n  Qed.\n\n  Lemma In_UnConstrQuery_In' {qsSchema} {A}\n    : forall (qs : UnConstrQueryStructure qsSchema) Ridx\n             (bod : RawTuple -> Comp (list A))\n             results\n             (a : A) (tup' : IndexedRawTuple),\n      Ensembles.In _ (GetUnConstrRelation qs Ridx) tup'\n      -> (forall results', bod (indexedElement tup') ↝ results'\n                           -> List.In a results')\n      -> UnConstrQuery_In qs Ridx bod ↝ results\n      -> List.In a results.\n  Proof.\n    unfold UnConstrQuery_In, QueryResultComp, Ensembles.In; intros.\n    computes_to_inv.\n    unfold UnIndexedEnsembleListEquivalence in *; destruct_ex; intuition; subst.\n    rewrite map_map in H1'.\n    remember (GetUnConstrRelation qs Ridx); clear Heqi;\n    revert i a results H H0 H1 H1' H4;\n    induction x; simpl in *; intros;\n    computes_to_inv; subst.\n    - simpl in *; intuition; eapply H1; eauto.\n    - apply H1 in H; intuition; subst; apply in_or_app; eauto.\n      right; inversion H4; subst.\n      eapply (IHx (fun tup => tup <> a /\\ i tup)); eauto.\n      intuition; subst; eauto.\n      apply H5; eauto using in_map.\n      apply H1; eauto.\n      unfold Ensembles.In; intuition; intros; eauto.\n      rewrite H1 in H7; intuition.\n      subst; eauto using in_map.\n      apply H1; eauto.\n  Qed.\n\n  Lemma DeleteForeignKeysCheck {qsSchema}\n    : forall (qs : UnConstrQueryStructure qsSchema)\n             (Ridx Ridx' :Fin.t _)\n             (DeletedTuples : Ensemble (RawTuple ))\n             (Delete_dec : DecideableEnsemble DeletedTuples)\n             (attr : Attributes _)\n             (attr' : Attributes _)\n             (tupmap : Domain _ attr\n                       -> Domain _ attr')\n             (AgreeDelete : forall tup tup',\n                 tupleAgree tup tup' [attr] ->\n                 DeletedTuples tup ->\n                 DeletedTuples tup')\n             (attr_eq_dec : Query_eq (Domain _ attr))\n             (P : Prop)\n             (ForeignKey_P_P :\n                P -> (forall tup' : IndexedRawTuple,\n                         GetUnConstrRelation qs Ridx' tup' ->\n                         ForeignKey_P attr' attr tupmap (indexedElement tup')\n                                      (GetUnConstrRelation qs Ridx)))\n             (tup_map_inj : forall a a', tupmap a = tupmap a' -> a = a'),\n      refine {b' |\n              P ->\n              decides b'\n                      (MutationPreservesCrossConstraints\n                         (GetUnConstrRelation qs Ridx')\n                         (EnsembleDelete (GetUnConstrRelation qs Ridx) DeletedTuples)\n                         (ForeignKey_P attr' attr tupmap))}\n             (x <- Count (For (UnConstrQuery_In\n                                 qs Ridx'\n                                 (fun tup' =>\n                                    UnConstrQuery_In\n                                      qs Ridx\n                                      (fun tup =>\n                                         Where (DeletedTuples tup)\n                                               Where (tupmap (GetAttributeRaw tup attr) = GetAttributeRaw tup' attr')\n                                               Return ()))));\n              ret (match x with\n                     0  => true\n                   | S _ => false\n                   end)).\n  Proof.\n    simpl; unfold ForeignKey_P; intros.\n    intros v Comp_v.\n    computes_to_inv; destruct_ex; split_and.\n    unfold Count in *;  computes_to_inv.\n    destruct v0; simpl in *; subst;  computes_to_inv; subst;\n    computes_to_constructor; simpl; unfold not;\n    unfold MutationPreservesCrossConstraints; intros.\n    - destruct (ForeignKey_P_P H _ H0) as [tup2 [In_tup2 Agree_tup2] ].\n      eexists; intuition eauto.\n      unfold EnsembleDelete; constructor; unfold In; intros; eauto.\n      unfold Complement, Ensembles.In, not; intros.\n      unfold Query_For in *;  computes_to_inv.\n      rewrite Permutation_nil in Comp_v; symmetry in Comp_v'0; eauto.\n      apply (fun x => In_UnConstrQuery_In' _ _ _ _ () _ H0 x Comp_v).\n      intros results' H3;\n        apply (fun x => In_UnConstrQuery_In' _ _ _ _ () _ In_tup2 x H3).\n      intros results'0 H5.\n      unfold Query_Where in H5; computes_to_inv;\n      simpl in *; intuition.\n      computes_to_inv; split_and.\n      simpl in H4.\n      unfold QSGetNRelSchema, GetNRelSchema in Agree_tup2; simpl in *.\n      rewrite Agree_tup2 in H4; pose proof (H4 (refl_equal _)) as H';\n      computes_to_inv; simpl in *; subst; simpl; eauto.\n      apply Return_inv in H'; subst; simpl; intuition.\n      rewrite Comp_v'; destruct v1; try discriminate; reflexivity.\n    - unfold Query_For in *;  computes_to_inv.\n      eapply In_UnConstrQuery_In with (a := tt) in Comp_v; destruct_ex;\n      intuition.\n      pose proof (H3 _ H2); pose proof (H0 _ H2); destruct_ex;\n      intuition.\n      eapply In_UnConstrQuery_In with (a := tt) in H1; destruct_ex;\n      intuition.\n      unfold EnsembleDelete in *; inversion H5; subst;\n      unfold Ensembles.In, Complement, In in *.\n      unfold Query_Where in H1; computes_to_inv;  intuition.\n      case_eq (@dec _ _ Delete_dec (indexedElement x3)); intros.\n      + apply Delete_dec in H1; pose proof (H13 H1) as H'.\n        computes_to_inv; split_and.\n        unfold indexedTuple in *.\n        destruct (A_eq_dec (GetAttributeRaw (indexedElement x3) attr)\n                           (GetAttributeRaw (indexedElement x1) attr)).\n        * rewrite e in *; setoid_rewrite <- H9 in H15; subst;\n          pose proof (H15 (refl_equal _)) as e'; computes_to_inv; simpl in *; subst.\n          apply H12; eapply AgreeDelete; eauto.\n          unfold tupleAgree; simpl; intros attr'' In_attr''; destruct In_attr'';\n          [rewrite H17 in *; eauto | intuition ].\n        * rewrite H16 in H11; simpl in *; eauto.\n          intros;\n            unfold QSGetNRelSchema, GetNRelSchema in *; simpl in *;\n            setoid_rewrite <- H17 in H9; eauto.\n      + rewrite H14 in H11; simpl in *; eauto.\n        intros H'; apply dec_decides_P in H'; congruence.\n      + eapply Permutation_in; symmetry in Comp_v'; simpl; eauto.\n        destruct v1; simpl in *;\n        [ discriminate | destruct u; eauto].\n  Qed.\n\n  Lemma InsertForeignKeysCheck {qsSchema}\n    : forall\n      (qs : UnConstrQueryStructure qsSchema)\n      (Ridx Ridx' :Fin.t _)\n      (attr : Attributes _)\n      (attr' : Attributes _)\n      (tupmap : Domain _ attr' -> Domain _ attr)\n      tup\n      (ForeignKey_P_P :\n         (forall tup' : IndexedRawTuple,\n             GetUnConstrRelation qs Ridx tup' ->\n             ForeignKey_P attr attr' tupmap (indexedElement tup')\n                          (GetUnConstrRelation qs Ridx'))),\n      Ridx <> Ridx'\n      -> refine {b' |\n                 decides b'\n                         (forall tup',\n                             (GetUnConstrRelation qs Ridx) tup' ->\n                             ForeignKey_P attr attr' tupmap\n                                          (indexedElement tup')\n                                          (EnsembleInsert tup (GetUnConstrRelation qs Ridx')))}\n                (ret true).\n  Proof.\n    intros; apply refine_pick_val; simpl; intros.\n    unfold ForeignKey_P in *.\n    destruct (ForeignKey_P_P _ H0) as [tup'' [In_tup'' ?] ];\n      exists tup''; unfold EnsembleInsert; intuition.\n  Qed.\n\nEnd ConstraintCheckRefinements.\n\nLemma In_flatten_CompList {A} :\n  forall (P : Ensemble A)\n         (P_dec : forall a, P a \\/ ~ P a)\n         (il : list (@IndexedElement A))\n         (l : list A)\n         (a : A),\n    List.In a l\n    -> flatten_CompList\n         (map\n            (fun x1 : IndexedElement =>\n               Where (P (indexedElement x1))\n                     Return (indexedElement x1) ) il) ↝ l\n    -> exists a', List.In a' il /\\ indexedElement a' = a.\nProof.\n  induction il; simpl; intros;  computes_to_inv; subst; simpl in *; intuition.\n  apply in_app_or in H; intuition.\n  unfold Query_Where in H0; computes_to_inv; intuition.\n  destruct (P_dec (indexedElement a)).\n  apply H in H0; unfold Query_Return in *; computes_to_inv; subst;\n  simpl in H; exists a; simpl in H1; intuition; eauto.\n  apply H2 in H0; subst; simpl in *; contradiction.\n  destruct (IHil _ _ H1 H0') as [a' [In_a' a'_eq] ]; exists a'; split; eauto.\nQed.\n\nLemma For_computes_to_In :\n  forall {heading} P,\n    (forall a, P a \\/ ~ P a) ->\n    forall seq ens,\n      computes_to (For (QueryResultComp (heading := heading) ens\n                                        (fun tup => Where (P tup) Return tup))) seq ->\n      forall x,\n        List.In x seq -> (P x /\\ (exists x0, ens x0 /\\ indexedRawTuple x0 = x)).\nProof.\n  unfold refine, decides;\n  unfold Query_For, QueryResultComp; intros * excl;\n  induction seq as [ | head seq' IH ]; intros.\n\n  exfalso; intuition.\n\n  computes_to_inv.\n\n  pose proof (permutation_cons_in H') as in_x0.\n  apply in_split in in_x0.\n  destruct in_x0 as [ x0_before [ x0_after ? ] ]; subst.\n  symmetry in H'. apply Permutation_cons_app_inv in H'.\n\n  unfold UnIndexedEnsembleListEquivalence in H; destruct_ex; intuition; subst.\n\n  rewrite map_map in H'0.\n  destruct (flatten_CompList_app_cons_inv _ excl _ _ _ _ H'0) as [ x1_before [ x1_middle [ head' [ x1_after (_eq & in_orig & before & middle & after) ] ] ] ]; subst.\n\n  unfold boxed_option in middle; simpl in middle.\n  eapply Bind_inv in middle.\n  destruct middle as [head'' (middle1 & middle2)].\n  apply Pick_inv in middle1.\n  apply Bind_inv in middle2.\n  destruct middle1 as ( spec1 & spec2 ).\n  destruct middle2 as [ nil' (ret_nil & ret_cons) ].\n  apply Return_inv in ret_nil; subst.\n  rewrite app_nil_r in *; subst.\n  apply Return_inv in ret_cons; subst.\n\n\n\n  rewrite singleton_neq_nil in spec2.\n  destruct (excl (indexedRawTuple head')) as [ H'' | H'' ]; try solve [exfalso; intuition].\n  specialize (spec1 H'').\n\n  apply Return_inv in spec1.\n  injection spec1; intros; subst.\n\n  destruct H0.\n\n  - subst x; eauto.\n  - pose proof (flatten_CompList_app _ _ _ _ before after) as flatten_app.\n    eapply IH; try assumption.\n    computes_to_econstructor; [ | computes_to_constructor; symmetry; eassumption ].\n    computes_to_econstructor.\n    pose proof (EnsembleListEquivalence_slice x1_before x1_middle x1_after).\n    instantiate (2 := (fun x0 : IndexedRawTuple => ens x0 /\\ ~ List.In x0 x1_middle)).\n    eapply PickComputes with (a := map indexedElement (x1_before ++ x1_after)).\n    econstructor; split; eauto; intuition.\n    destruct (H1 ens).\n    unfold EnsembleListEquivalence; split; eauto using NoDup_IndexedElement.\n    eapply H5; eauto.\n    unfold Ensembles.In; split.\n    eapply H; apply in_app_or in H2; intuition.\n    intros; apply NoDup_IndexedElement in H3; eapply NoDup_app_inv'; eauto using in_app_or.\n    repeat rewrite map_app in *; eauto using NoDup_slice.\n    unfold boxed_option in *.\n    rewrite !map_app, !map_map.\n    apply flatten_app.\n\n  - rewrite map_map in H'0.\n    destruct (In_flatten_CompList P excl x0 (x0_before ++ head :: x0_after) x) as [x1 [In_x1 x1_eq] ];\n      eauto.\n    eapply Permutation_in with (l := head :: (x0_before ++ x0_after)).\n    eapply Permutation_middle.\n    simpl in *; intuition; right; eauto using Permutation_in.\n    exists x1; split; eauto.\n    apply H; eauto.\nQed.\n\nLemma UnIndexedEnsembleListEquivalence_eqv {A}\n  : forall ens l,\n    @UnIndexedEnsembleListEquivalence A ens l ->\n    exists l',\n      EnsembleListEquivalence ens l' /\\ l = map indexedElement l'.\nProof.\n  unfold UnIndexedEnsembleListEquivalence, EnsembleListEquivalence; intros.\n  destruct_ex; intuition.\n  exists x; intuition; eauto using NoDup_IndexedElement.\nQed.\n\nLemma For_computes_to_nil :\n  forall {heading} P,\n  forall ens,\n    computes_to (For (QueryResultComp (heading := heading) ens\n                                      (fun tup => Where (P tup) Return tup))) [] ->\n    forall x,\n      ens x -> ~ (P (indexedRawTuple x)).\nProof.\n  unfold refine, decides, Count, Query_For, QueryResultComp; intros **.\n  computes_to_inv.\n  symmetry in H'; apply Permutation_nil in H'; subst.\n  apply UnIndexedEnsembleListEquivalence_eqv in H; destruct_ex; intuition; subst.\n\n  apply H2 in H0.\n  apply in_split in H0.\n  destruct H0 as [ x1_before [ x1_after _eq ] ]; subst.\n  rewrite map_map in H'0.\n  eapply (@FlattenCompList.flatten_CompList_nil _ P); unfold boxed_option; eauto; intuition.\nQed.\n\nLemma decidable_excl :\n  forall {A : Type} (P : Ensemble A) (P_dec : DecideableEnsemble P),\n    (forall (a: A), P a \\/ ~ P a).\nProof.\n  intros ??? a.\n  destruct (dec a) eqn:eqdec;\n    [ rewrite dec_decides_P in eqdec | rewrite Decides_false in eqdec ]; intuition.\nQed.\n\nLemma refine_constraint_check_into_QueryResultComp :\n  forall heading R P' P\n         (P_dec : DecideableEnsemble P),\n    Same_set _ (fun tup => P (indexedElement tup)) P'\n    -> refine\n         (Pick (fun (b : bool) =>\n                  decides b\n                          (exists tup2: @IndexedRawTuple heading,\n                              (R tup2 /\\ P' tup2))))\n         (Bind\n            (Count (For (QueryResultComp R (fun tup => Where (P tup) Return tup))))\n            (fun count => ret (negb (beq_nat count 0)))).\nProof.\n  Local Transparent Count.\n  unfold refine, Count, UnConstrQuery_In;\n    intros * excl * P_iff_P' pick_comp ** .\n  computes_to_inv; subst.\n\n  computes_to_constructor.\n\n  destruct (Datatypes.length v0) eqn:eq_length;\n    destruct v0 as [ | head tail ]; simpl in *; try discriminate; simpl.\n\n  pose proof (For_computes_to_nil _ R H).\n  rewrite not_exists_forall; intro a; rewrite not_and_implication; intros.\n  unfold not; intros; eapply H0; eauto; apply P_iff_P'; eauto.\n\n  apply For_computes_to_In with (x := head) in H; try solve [intuition].\n  destruct H as ( p & [ x0 ( in_ens & _eq ) ] ); subst.\n  eexists; split; eauto; apply P_iff_P'; eauto.\n\n  apply decidable_excl; assumption.\nQed.\n\nLemma refine_constraint_check_into_query' :\n  forall {schm tbl} (c : UnConstrQueryStructure schm) P' P\n         (P_dec : DecideableEnsemble P),\n    Same_set _ (fun tup => P (indexedElement tup)) P'\n    -> refine\n         (Pick (fun (b : bool) =>\n                  decides b\n                          (exists tup2: @IndexedRawTuple _,\n                              (GetUnConstrRelation c tbl tup2 /\\ P' tup2))))\n         (Bind\n            (Count (For (UnConstrQuery_In c tbl (fun tup => Where (P tup) Return tup))))\n            (fun count => ret (negb (beq_nat count 0)))).\nProof.\n  intros; rewrite refine_constraint_check_into_QueryResultComp; eauto.\n  reflexivity.\nQed.\n\nCorollary refine_constraint_check_into_query :\n  forall {schm tbl} P (c : UnConstrQueryStructure schm)\n         (P_dec : DecideableEnsemble P),\n    refine\n      (Pick (fun (b : bool) =>\n               decides b\n                       (exists tup2: @IndexedRawTuple _,\n                           (GetUnConstrRelation c tbl tup2 /\\ P (indexedRawTuple tup2)))))\n      (Bind\n         (Count (For (UnConstrQuery_In c tbl (fun tup => Where (P tup) Return tup))))\n         (fun count => ret (negb (beq_nat count 0)))).\nProof.\n  intros.\n  setoid_rewrite refine_constraint_check_into_query'; eauto.\n  reflexivity.\n  unfold Same_set, Included; intuition.\nQed.\n\nLemma refine_constraint_check_into_query'' :\n  forall heading R P' P\n         (P_dec : DecideableEnsemble P),\n    Same_set _ (fun tup => P (indexedElement tup)) P'\n    -> refine\n         (Pick (fun (b : bool) =>\n                  decides b\n                          (exists tup2: @IndexedRawTuple heading,\n                              (R tup2 /\\ P' tup2))))\n         (Bind\n            (Count (For (QueryResultComp R (fun tup => Where (P tup) Return tup))))\n            (fun count => ret (negb (beq_nat count 0)))).\nProof.\n  Local Transparent Count.\n  unfold refine, Count, UnConstrQuery_In;\n    intros * excl * P_iff_P' pick_comp ** .\n  computes_to_inv; subst.\n\n  computes_to_constructor.\n\n  destruct (Datatypes.length v0) eqn:eq_length;\n    destruct v0 as [ | head tail ]; simpl in *; try discriminate; simpl.\n\n  pose proof (For_computes_to_nil _ R H).\n  rewrite not_exists_forall; intro a; rewrite not_and_implication; intros.\n  unfold not; intros; eapply H0; eauto; apply P_iff_P'; eauto.\n\n  apply For_computes_to_In with (x := head) in H; try solve [intuition].\n  destruct H as ( p & [ x0 ( in_ens & _eq ) ] ); subst.\n  eexists; split; eauto; apply P_iff_P'; eauto.\n\n  apply decidable_excl; assumption.\nQed.\n\nDefinition refine_foreign_key_check_into_query {schm tbl} :=\n  @refine_constraint_check_into_query schm tbl.\n\nLemma refine_functional_dependency_check_into_query :\n  forall {schm : RawQueryStructureSchema}\n         {tbl}\n         (ref : @RawTuple (@GetNRelSchemaHeading _ (qschemaSchemas schm) tbl))\n         args1\n         args2\n         (c : UnConstrQueryStructure schm),\n    DecideableEnsemble (fun x : RawTuple => tupleAgree_computational ref x args1 /\\\n                                            ~ tupleAgree_computational ref x args2) ->\n    ((forall tup' : IndexedRawTuple,\n         GetUnConstrRelation c tbl tup'\n         -> FunctionalDependency_P args2 args1 ref (indexedElement tup'))\n     <-> (forall tup',\n             ~ (GetUnConstrRelation c tbl tup'\n                /\\ tupleAgree ref (indexedElement tup') args1\n                /\\ ~ tupleAgree ref (indexedElement tup') args2))) ->\n    refine\n      (Pick (fun (b : bool) =>\n               decides b\n                       (forall tup',\n                           GetUnConstrRelation c tbl tup' ->\n                           FunctionalDependency_P args2 args1 ref (indexedElement tup'))))\n      (Bind (Count\n               For (UnConstrQuery_In c tbl\n                                     (fun tup =>\n                                        Where (tupleAgree_computational ref tup args1 /\\\n                                               ~ tupleAgree_computational ref tup args2)\n                                              Return tup)))\n            (fun count => ret (beq_nat count 0))).\nProof.\n  intros * is_dec ** .\n\n  setoid_replace (forall tup', GetUnConstrRelation c tbl tup' ->\n                               tupleAgree ref (indexedElement tup') args1\n                               -> tupleAgree ref (indexedElement tup') args2)\n  with           (forall tup', ~ (GetUnConstrRelation c tbl tup' /\\\n                                  tupleAgree ref (indexedElement tup') args1 /\\\n                                  ~ tupleAgree ref (indexedElement tup') args2)); eauto.\n\n  setoid_rewrite refine_decide_negation.\n  setoid_rewrite (tupleAgree_equivalence ref).\n\n  setoid_rewrite (@refine_constraint_check_into_query _ _\n                                                      (fun x => tupleAgree_computational ref x args1 /\\\n                                                                          ~ tupleAgree_computational ref x args2)); try assumption.\n\n  Opaque Query_For Count.\n  simplify with monad laws.\n  setoid_rewrite negb_involutive.\n  reflexivity.\nQed.\n\nLemma refine_functional_dependency_check_into_query' :\n  forall {schm : RawQueryStructureSchema}\n         {tbl}\n         ref\n         args1\n         args2\n         (c : UnConstrQueryStructure schm),\n    DecideableEnsemble (fun x => tupleAgree_computational x ref args1 /\\\n                                         ~ tupleAgree_computational x ref args2) ->\n    ((forall tup' ,\n         GetUnConstrRelation c tbl tup'\n         -> FunctionalDependency_P args2 args1 (indexedElement tup') ref)\n     <-> (forall tup',\n             ~ (GetUnConstrRelation c tbl tup'\n                /\\ tupleAgree (indexedElement tup') ref args1\n                /\\ ~ tupleAgree (indexedElement tup') ref args2))) ->\n    refine\n      (Pick (fun (b : bool) =>\n               decides b\n                       (forall tup',\n                           GetUnConstrRelation c tbl tup' ->\n                           FunctionalDependency_P args2 args1 (indexedElement tup') ref)))\n      (Bind (Count\n               For (UnConstrQuery_In c tbl\n                                     (fun tup =>\n                                        Where (tupleAgree_computational tup ref args1 /\\\n                                               ~ tupleAgree_computational tup ref args2)\n                                              Return tup)))\n            (fun count => ret (beq_nat count 0))).\nProof.\n  intros * is_dec ** .\n\n  setoid_replace (forall tup', GetUnConstrRelation c tbl tup' ->\n                               tupleAgree (indexedElement tup') ref args1\n                               -> tupleAgree (indexedElement tup') ref args2)\n  with           (forall tup', ~ (GetUnConstrRelation c tbl tup' /\\\n                                  tupleAgree (indexedElement tup') ref args1 /\\\n                                  ~ tupleAgree (indexedElement tup') ref args2)); eauto.\n\n  setoid_rewrite refine_decide_negation.\n  setoid_rewrite tupleAgree_equivalence.\n  setoid_rewrite (@refine_constraint_check_into_query _ _\n                                                      (fun x => tupleAgree_computational x ref args1 /\\\n                                                                          ~ tupleAgree_computational x ref args2)); try assumption.\n\n  Opaque Query_For Count.\n  simplify with monad laws.\n  setoid_rewrite negb_involutive.\n  reflexivity.\nQed.\n\n Theorem FunctionalDependency_symmetry\n  : forall A H (f : _ -> _ -> Comp A) (P : _ -> Prop) attrlist1 attrlist2 n,\n    refine (x1 <- {b | decides b\n                               (forall tup' : @IndexedRawTuple H,\n                                   P tup'\n                                   -> FunctionalDependency_P attrlist1 attrlist2 n (indexedElement tup'))};\n            x2 <- {b | decides b (forall tup' : @IndexedRawTuple H,\n                                     P tup'\n                                     -> FunctionalDependency_P attrlist1 attrlist2 (indexedElement tup') n)};\n            f x1 x2)\n           (x1 <- {b | decides b (forall tup' : @IndexedRawTuple H,\n                                     P tup'\n                                     -> FunctionalDependency_P attrlist1 attrlist2 n (indexedElement tup'))};\n            f x1 x1).\nProof.\n  unfold refine, FunctionalDependency_P; intros.\n  computes_to_inv; firstorder.\n  computes_to_inv; firstorder.\n  repeat (computes_to_econstructor; eauto).\n  destruct v0; simpl in *; unfold tupleAgree in *; intros; eauto.\n  erewrite H0; eauto; intros; rewrite H2; eauto.\n  unfold not; intros; eapply H0; intros.\n  rewrite H1; eauto; intros; rewrite H3; eauto.\nQed.\n\n\nTheorem FunctionalDependency_symmetry'\n  : forall H P attrlist1 attrlist2 n b',\n    decides b'\n            (forall tup' : @IndexedRawTuple H,\n                P tup'\n                -> FunctionalDependency_P attrlist1 attrlist2 n (indexedElement tup'))\n    -> refine {b | decides b (forall tup' : @IndexedRawTuple H,\n                                 P tup'\n                                 -> FunctionalDependency_P attrlist1 attrlist2 (indexedElement tup') n)}\n                  (ret b').\nProof.\n  unfold FunctionalDependency_P; intros.\n  refine pick val b'.\n  reflexivity.\n  destruct b'; simpl in *; unfold tupleAgree in *; intros; eauto.\n  erewrite H0; eauto; intros; rewrite H1; eauto.\n  unfold not; intros; eapply H0; intros.\n  rewrite H1; eauto; intros; rewrite H2; eauto.\nQed.\n\n\nLemma if_duplicate_cond_eq {A}\n  : forall (i : bool) (t e : A),\n    (if i then (if i then t else e) else e) = if i then t else e.\nProof.\n  destruct i; reflexivity.\nQed.\n\nGlobal Instance nil_List_Query_eq :\n  List_Query_eq [] :=\n  { As_Query_eq := tt  }.\n\nGlobal Instance cons_List_Query_eq\n       {A : Type}\n       {As : list Type}\n       {A_Query_eq : Query_eq A}\n       {As_Query_eq' : List_Query_eq As}\n  :\n    List_Query_eq (A :: As) :=\n  { As_Query_eq := (A_Query_eq, As_Query_eq) }.\n\nTheorem UniqueAttribute_symmetry\n  : forall A (f : _ -> _ -> Comp A) H (P : _ -> Prop) attr n,\n    refine (b1 <- {b | decides b\n                               (forall tup' : @IndexedRawTuple H,\n                                   P tup'\n                                   -> UniqueAttribute' attr n (indexedElement tup'))};\n           b2 <- {b | decides b (forall tup' : @IndexedRawTuple H,\n                                     P tup'\n                                     -> UniqueAttribute' attr (indexedElement tup') n)}; f b1 b2)\n           (b1 <- {b | decides b\n                               (forall tup' : @IndexedRawTuple H,\n                                   P tup'\n                                   -> UniqueAttribute' attr n (indexedElement tup'))}; f b1 b1).\nProof.\n  unfold refine, UniqueAttribute'; intros.\n  computes_to_inv; firstorder.\n  repeat (computes_to_econstructor; eauto).\n  destruct v0; simpl in *; unfold not in *; intros; eauto.\nQed.\n\nLemma refine_uniqueness_check_into_query' :\n  forall {schm : RawQueryStructureSchema}\n         idx\n         tup\n         attr\n         (c : UnConstrQueryStructure schm),\n    Query_eq (Domain (GetNRelSchemaHeading (qschemaSchemas schm) idx) attr)\n    -> refine\n      {b | decides b\n                   (forall tup' : @IndexedRawTuple _,\n                       GetUnConstrRelation c idx tup'\n                       -> UniqueAttribute' attr tup (indexedElement tup'))}\n      (c <- (Count\n               For (UnConstrQuery_In c idx\n                                     (fun tup' =>\n                                        Where (GetAttributeRaw tup attr\n                                               = GetAttributeRaw tup' attr)\n                                              Return tup')));\n            (ret (beq_nat c 0))).\nProof.\n  intros.\n  setoid_replace (forall tup', GetUnConstrRelation c idx tup' ->\n                               UniqueAttribute' attr tup (indexedElement tup'))\nwith           (forall tup', ~ (GetUnConstrRelation c idx tup' /\\\n                                GetAttributeRaw tup attr = GetAttributeRaw  (indexedElement tup') attr)) by\n      (unfold UniqueAttribute'; intuition eauto).\n  setoid_rewrite refine_decide_negation.\n  rewrite (@refine_constraint_check_into_query _ _\n                                                      (fun tup' => GetAttributeRaw tup attr = GetAttributeRaw tup' attr)) by eauto with typeclass_instances.\n  simplify with monad laws.\n  setoid_rewrite negb_involutive.\n  reflexivity.\nQed.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/QueryStructure/Implementation/Constraints/ConstraintChecksRefinements.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2208994865352764}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RVIC2.Spec.\nRequire Import RVIC.Spec.\nRequire Import AbsAccessor.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition validate_and_lookup_target_spec0 (rec: Pointer) (target: Z64) (intid: Z64) (adt: RData) : option (RData * Z64) :=\n    match rec, target, intid with\n    | (_rec_base, _rec_ofst), VZ64 _target, VZ64 _intid =>\n      rely is_int64 _target;\n      when _target_valid == rvic_target_is_valid_spec (VZ64 _target) adt;\n      rely is_int _target_valid;\n      if (_target_valid =? 0) then\n        Some (adt, (VZ64 1))\n      else\n        rely is_int64 _intid;\n        when _t'4 == is_trusted_intid_spec (VZ64 _intid) adt;\n        rely is_int _t'4;\n        if (_t'4 =? 0) then\n          when _t'6 == is_untrusted_intid_spec (VZ64 _intid) adt;\n          rely is_int _t'6;\n          let _t'5 := (_t'6 =? 0) in\n          if _t'5 then\n            Some (adt, (VZ64 1))\n          else\n            when adt == find_lock_map_target_rec_spec (_rec_base, _rec_ofst) (VZ64 _target) adt;\n            when'' _t'2_base, _t'2_ofst == get_target_rec_spec  adt;\n            rely is_int _t'2_ofst;\n            when _t'3 == is_null_spec (_t'2_base, _t'2_ofst) adt;\n            rely is_int _t'3;\n            if (_t'3 =? 1) then\n              Some (adt, (VZ64 1))\n            else\n              Some (adt, (VZ64 0))\n        else\n          let _t'5 := 0 in\n          when adt == find_lock_map_target_rec_spec (_rec_base, _rec_ofst) (VZ64 _target) adt;\n          when'' _t'2_base, _t'2_ofst == get_target_rec_spec  adt;\n          rely is_int _t'2_ofst;\n          when _t'3 == is_null_spec (_t'2_base, _t'2_ofst) adt;\n          rely is_int _t'3;\n          if (_t'3 =? 1) then\n            Some (adt, (VZ64 1))\n          else\n            Some (adt, (VZ64 0))\n     end\n    .\n\nEnd SpecLow.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RVIC3/LowSpecs/validate_and_lookup_target.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.3775406617944891, "lm_q1q2_score": 0.22089947697460735}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssrZ ZArith_ext ssrnat_ext seq_ext machine_int multi_int uniq_tac.\nImport MachineInt.\nRequire Import mips_seplog mips_frame mips_contrib mips_tactics mapstos.\nRequire Import mont_mul_strict_prg multi_zero_u_prg multi_zero_u_triple.\nRequire Import mont_square_strict_triple.\nImport expr_m.\nImport assert_m.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope eqmod_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope mips_expr_scope.\nLocal Open Scope mips_assert_scope.\nLocal Open Scope mips_cmd_scope.\nLocal Open Scope mips_hoare_scope.\nLocal Open Scope multi_int_scope.\nLocal Open Scope zarith_ext_scope.\n\nSection mont_square_strict_init.\n\nVariables k alpha x z m one ext int_ X_ Y_ M_ Z_ quot C t s_ : reg.\n\nLemma mont_square_strict_init_triple :\n  uniq(k, alpha, x, z, m, one, ext, int_, X_, Y_, M_, Z_, quot, C, t, s_, r0) ->\n  forall nk valpha vx vm vz X M,\n  u2Z (M `32_ 0) * u2Z valpha =m -1 {{ \\B^1 }} ->\n  size X = nk -> size M = nk ->\n  u2Z vz + 4 * Z_of_nat nk.+1 < \\B^1 ->\n  \\S_{ nk } X < \\S_{ nk } M ->\n  {{ fun s h => exists Z, size Z = nk /\\\n    [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n    (var_e x |--> X ** var_e z |--> Z ++ zero32 :: nil ** var_e m |--> M ++ zero32 :: nil) s h }}\n  mont_mul_strict_init k alpha x x z m one ext int_ X_ Y_ M_ Z_ quot C t s_\n  {{fun s h => exists Z, size Z = nk /\\\n    [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\\n    u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n    (var_e x |--> X ** var_e z |--> Z ++ zero32::nil ** var_e m |--> M ++ zero32::nil) s h /\\\n    \\B^nk * \\S_{ nk } Z =m \\S_{ nk } X * \\S_{ nk } X {{ \\S_{ nk } M }} /\\ \\S_{ nk } Z < \\S_{ nk } M }}.\nProof.\nmove=> Hset nk valpha vx vm vz X M Halpha HlenX HlenM Hnz HXM.\nrewrite /mont_mul_strict_init.\n\n(**  multi_zero ext k Z_ z ; *)\n\napply pull_out_exists => Z.\n\napply (hoare_prop_m.hoare_stren (!(fun s => size Z = nk) **\n  (fun s h => [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\\n    u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n    ((var_e x |--> X ** var_e z |--> Z ++ zero32 :: nil) ** var_e m |--> M ++ zero32 :: nil) s h))).\n\nmove=> s h [HlenZ [Hrx [Hrz [Hrm_ [Hrk [Hralpha Hmem]]]]]].\nexists heap.emp, h; repeat (split => //).\nby map_tac_m.Disj.\nby map_tac_m.Equal.\nby rewrite conAE.\n\napply pull_out_bang => HlenZ.\n\napply (hoare_prop_m.hoare_stren\n  ((fun s h => [z]_s = vz /\\ u2Z [k]_s = Z_of_nat nk /\\ (var_e z |--> Z) s h) **\n    (fun s h => [x]_s = vx /\\ [m]_s = vm /\\ [alpha]_s = valpha /\\\n      (var_e x |--> X ** var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32 **\n        var_e m |--> M ++ zero32 :: nil) s h))).\n\nmove=> s h [Hrx [Hrz [Hrm_ [Hrk [Hralpha Hmem]]]]].\n\nrewrite decompose_last_equiv HlenZ !assert_m.conAE assert_m.conCE !assert_m.conAE in Hmem.\ncase: Hmem => h1 [h2 [Hdisj [Hunion [Hmem1 Hmem2]]]].\nexists h1, h2; repeat (split; trivial).\nby assoc_comm Hmem2.\n\napply while.hoare_seq with (\n  (fun s h => [z]_s = vz /\\ u2Z [k]_s = Z_of_nat nk /\\ (var_e z |--> nseq nk zero32) s h) **\n  (fun s h => [x]_s = vx /\\ [m]_s = vm /\\ [alpha]_s = valpha /\\\n    (var_e x |--> X ** var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk))) |~> int_e zero32 **\n      var_e m |--> M ++ zero32 :: nil) s h)).\n\napply frame_rule_R.\n- eapply multi_zero_u_triple; eauto.\n  + by Uniq_uniq r0.\n  + rewrite Z_S in Hnz; lia.\n- by Inde_frame.\n- move=> ?; by Inde_mult.\n\napply while.hoare_seq with (fun s h => [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> nseq nk zero32 ++ zero32 :: nil ** var_e m |--> M ++ zero32 :: nil) s h /\\\n  store.multi_null s).\n\n(**  (mflhxu r0 ; *)\n\napply hoare_mflhxu with (fun s h =>[x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> nseq nk zero32 ++ zero32 :: nil ** var_e m |--> M ++ zero32 :: nil) s h /\\\n  store.acx s = Z2u store.acx_size 0).\n\nmove=> s h [h1 [h2 [Hdisj [Hunion [[Hrz [Hrk Hmem1]] [Hrx [Hrm_ [Hralpha Hmem2]]]]]]]].\nrewrite /wp_mflhxu.\nrepeat Reg_upd; repeat (split; trivial).\nmove: {Hmem1 Hmem2}(assert_m.con_cons _ _ _ _ _ Hdisj Hmem1 Hmem2) => Hmem.\nrewrite Hunion decompose_last_equiv size_nseq store.upd_r0.\nAssert_upd; by assoc_comm Hmem.\n\nby apply store.acx_mflhxu_op.\n\n(**  mthi r0 ; *)\n\napply hoare_mthi with (fun s h => [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> nseq nk zero32 ++ zero32 :: nil ** var_e m |--> M ++ zero32 :: nil) s h /\\\n  store.acx s = Z2u store.acx_size 0 /\\ store.hi s = zero32).\n\nmove=> {Z HlenZ} s h [Hrx [Hrz [Hrm_ [Hrk [Hralpha [Hmem Hacx]]]]]].\nrewrite /wp_mthi.\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite store.acx_mthi_op.\nby rewrite store.hi_mthi_op.\n\n(**  mtlo r0) ; *)\n\napply hoare_mtlo'.\n\nmove=> {Z HlenZ} s h [Hrx [Hrz [Hrm_ [Hrk [Hralpha [Hmem [Hacx Hhi]]]]]]].\nrewrite /wp_mtlo.\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\napply store.utoZ_multi_null.\nby rewrite store.utoZ_def store.hi_mtlo_op store.acx_mtlo_op store.lo_mtlo_op Hacx Hhi /zero32 !Z2uK.\n\n(**  mont_mul_strict k alpha x y z m_ one ext int_ X_ Y_ M_ Z_ quot C t s_. *)\n\nby eapply mont_square_strict_verif; eauto.\nQed.\n\nEnd mont_square_strict_init.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/cryptoasm/mont_square_strict_init_triple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22081578044557915}}
{"text": "Require Import PArith Setoid.\nFrom hahn Require Import Hahn.\nRequire Import PromisingLib.\nFrom Promising2 Require Import Time.\n\nFrom imm Require Import Events Execution.\nFrom imm Require Import imm_s_hb.\nFrom imm Require Import imm_s.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nSection FtoCoherent.\nVariable G : execution.\nVariable WF : Wf G.\nVariable sc : relation actid.\nVariable IMMCON : imm_consistent G sc.\nVariable I : actid -> Prop.\n\nNotation \"'acts'\" := G.(acts).\nNotation \"'co'\" := G.(co).\nNotation \"'coi'\" := G.(coi).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rf'\" := G.(rf).\nNotation \"'rfe'\" := G.(rfe).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'lab'\" := G.(lab).\n\nNotation \"'E'\" := G.(acts_set).\nNotation \"'R'\" := (fun a => is_true (is_r lab a)).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\nNotation \"'Loc_' l\" := (fun x => loc lab x = Some l) (at level 1). (* , format \"'Loc_'  l\"). *)\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'W_'\" := (fun l => W ∩₁ Loc_ l).\n(* Notation \"'RW'\" := (fun x => R x \\/ W x). *)\nNotation \"'FR'\" := (fun x => F x \\/ R x).\nNotation \"'FW'\" := (fun x => F x \\/ W x).\n\nNotation \"'Pln'\" := (fun a => is_true (is_only_pln lab a)).\nNotation \"'Rlx'\" := (is_rlx lab).\nNotation \"'Rel'\" := (is_rel lab).\nNotation \"'Acq'\" := (is_acq lab).\nNotation \"'Acqrel'\" := (is_acqrel lab).\nNotation \"'Sc'\" := (fun a => is_true (is_sc lab a)).\n\nNotation \"'W_ex'\" := G.(W_ex).\nNotation \"'W_ex_acq'\" := (W_ex ∩₁ (fun a => is_true (is_xacq lab a))).\n  \nVariable IE : I ⊆₁ E ∩₁ W.\nVariable INITINI: is_init ∩₁ E ⊆₁ I. Variables f_to f_from : actid -> Time.t.\n\nDefinition f_to_coherent :=\n  (* ⟪ NW  : forall a, ~ is_w lab a -> f_to a = tid_init ⟫ /\\ *)\n  ⟪ TINITTO : forall x, (is_init ∩₁ E) x -> f_to x = tid_init ⟫ /\\\n  ⟪ TINITFROM : forall x, (is_init ∩₁ E) x -> f_from x = tid_init ⟫ /\\\n  ⟪ TTOFROM : forall x,\n      I x -> ~ is_init x -> Time.lt (f_from x) (f_to x) ⟫ /\\\n  ⟪ TCO : forall x y,\n      I x -> I y ->\n      co x y -> Time.le (f_to x) (f_from y) ⟫ /\\\n  ⟪ TRMW : forall x y,\n      I x -> I y -> (rf ⨾ rmw) x y -> f_to x = f_from y ⟫\n.\n\nSection Props.\n\nVariable FCOH : f_to_coherent.\n\nLemma f_to_co_mon e e' (CO : co e e') (ISS : I e) (ISS' : I e') :\n  Time.lt (f_to e) (f_to e').\nProof using WF IMMCON FCOH.\n  eapply TimeFacts.le_lt_lt.\n  2: eapply FCOH; auto.\n  { by apply FCOH. }\n  apply Execution_eco.no_co_to_init in CO; auto.\n  { apply seq_eqv_r in CO. desf. }\n  apply coherence_sc_per_loc.\n  apply IMMCON.\nQed.\n\nLemma f_from_co_mon e e' (NINIT : ~ is_init e) (CO : co e e') (ISS : I e) (ISS' : I e') :\n  Time.lt (f_from e) (f_from e').\nProof using FCOH.\n  eapply TimeFacts.lt_le_lt.\n  { eapply FCOH; eauto. }\n    by apply FCOH.\nQed.\n\nLemma f_to_coherent_strict x y z (ISSX : I x) (ISSY : I y) (ISSZ : I z)\n      (COXY: co x y) (COYZ: co y z) :\n  Time.lt (f_to x) (f_from z).\nProof using WF IMMCON FCOH.\n  eapply TimeFacts.le_lt_lt.\n  { apply FCOH.\n    3: by apply COXY.\n    all: eauto. }\n  eapply f_from_co_mon; eauto.\n  apply Execution_eco.no_co_to_init in COXY; auto.\n  { apply seq_eqv_r in COXY. desf. }\n  apply coherence_sc_per_loc.\n  apply IMMCON.\nQed.\n\nLemma lt_init_ts e (EE : E e) (WW : W e) (ISS : I e) (NINIT : ~ is_init e) :\n  Time.lt tid_init (f_to e).\nProof using WF IMMCON IE INITINI FCOH.\n  unfold is_w in *.\n  destruct e; desf.\n  cdes FCOH.\n  assert (E (InitEvent l)) as EL.\n  { apply WF.(wf_init). eexists.\n    split; eauto. unfold loc. desf. }\n  assert ((is_init ∩₁ E) (InitEvent l)) as LL.\n  { by split; eauto. }\n  erewrite <- TINITTO; eauto.\n  eapply f_to_co_mon; eauto.\n  eapply init_co_w; eauto.\n  { unfold is_w. desf. }\n  red. unfold loc. rewrite WF.(wf_init_lab).\n  desf.\nQed.\n\nLemma le_init_ts e (EE : E e) (WW : W e) (ISS : I e) :\n  Time.le tid_init (f_to e).\nProof using WF IMMCON IE INITINI FCOH.\n  unfold is_w in *.\n  destruct e; desf.\n  { apply Time.le_lteq. right.\n    symmetry. cdes FCOH. apply TINITTO.\n    split; auto. }\n  apply Time.le_lteq. left.\n  eapply lt_init_ts; eauto.\n  unfold is_w. desf.\nQed.\n\nLemma le_init_ts_from e (EE : E e) (WW : W e) (ISS : I e) (NINIT : ~ is_init e) :\n  Time.le tid_init (f_from e).\nProof using WF IMMCON IE INITINI FCOH.\n  unfold is_w in *.\n  destruct e; desf.\n  cdes FCOH.\n  assert (E (InitEvent l)) as EL.\n  { apply WF.(wf_init). eexists.\n    split; eauto. unfold loc. desf. }\n  assert ((is_init ∩₁ E) (InitEvent l)) as LL.\n  { by split; eauto. }\n  erewrite <- TINITTO; eauto.\n  apply FCOH; eauto.\n  eapply init_co_w; eauto.\n  { unfold is_w. desf. }\n  red. unfold loc. rewrite WF.(wf_init_lab).\n  desf.\nQed.\n\nLemma f_to_eq e e' (SAME_LOC : same_loc lab e e') (ISS : I e) (ISS' : I e')\n      (FEQ : f_to e = f_to e') :\n  e = e'.\nProof using WF IMMCON IE FCOH.\n  assert (E e /\\ E e') as [EE EE']. \n  { by split; apply IE. }\n  assert (W e /\\ W e') as [WE WE']. \n  { by split; apply IE. }\n  destruct (classic (e = e')) as [|NEQ]; auto.\n  exfalso.\n  edestruct (wf_co_total WF); eauto.\n  1,2: split; [split|]; eauto.\n  { assert (Time.lt (f_to e) (f_to e')) as HH.\n    { eapply f_to_co_mon; eauto. }\n    rewrite FEQ in *.\n      by apply DenseOrder.lt_strorder in HH. }\n  assert (Time.lt (f_to e') (f_to e)) as HH.\n  { eapply f_to_co_mon; eauto. }\n  rewrite FEQ in *.\n    by apply DenseOrder.lt_strorder in HH.\nQed.\n\nLemma f_from_eq e e' (SAME_LOC : same_loc lab e e') (ISS : I e) (ISS' : I e')\n      (NINIT : ~ is_init e) (NINIT' : ~ is_init e')\n      (FEQ : f_from e = f_from e') :\n  e = e'.\nProof using WF IMMCON IE FCOH.\n  assert (E e /\\ E e') as [EE EE']. \n  { by split; apply IE. }\n  assert (W e /\\ W e') as [WE WE']. \n  { by split; apply IE. }\n  destruct (classic (e = e')) as [|NEQ]; auto.\n  exfalso.\n  edestruct (wf_co_total WF); eauto.\n  1,2: split; [split|]; eauto.\n  { assert (Time.lt (f_from e) (f_from e')) as HH.\n    { eapply f_from_co_mon; eauto. }\n    rewrite FEQ in *.\n      by apply DenseOrder.lt_strorder in HH. }\n  assert (Time.lt (f_from e') (f_from e)) as HH.\n  { eapply f_from_co_mon; eauto. }\n  rewrite FEQ in *.\n    by apply DenseOrder.lt_strorder in HH.\nQed.\n\nLemma co_S_f_to_le w w'\n      (SW  : I w)\n      (SW' : I w')\n      (CO  : co^? w w') :\n  Time.le (f_to w) (f_to w').\nProof using WF IMMCON FCOH.\n  destruct CO as [|CO]; [subst; reflexivity|].\n  apply Time.le_lteq; left.\n  eapply f_to_co_mon; eauto.\nQed.\n\nLemma co_S_f_from_le w w'\n      (NINIT : ~ is_init w)\n      (SW  : I w)\n      (SW' : I w')\n      (CO  : co^? w w') :\n  Time.le (f_from w) (f_from w').\nProof using WF FCOH.\n  destruct CO as [|CO]; [subst; reflexivity|].\n  apply Time.le_lteq; left.\n  eapply f_from_co_mon; eauto.\nQed.\n\nLemma to_from_disjoint_to w w'\n      (NEQ : w <> w')\n      (NINIT : ~ is_init w)\n      (SW  : I w)\n      (SW' : I w')\n      (SL  : same_loc lab w w') :\n  Time.le (f_to w') (f_from w) \\/ Time.lt (f_to w) (f_to w').\nProof using WF IMMCON IE FCOH.\n  edestruct is_w_loc as [l LL].\n  { apply IE. apply SW. }\n  edestruct WF.(wf_co_total) with (a:=w) (b:=w'); eauto.\n  1,2: split; [by apply IE|]; eauto.\n  { by rewrite <- SL. }\n  { right. by apply f_to_co_mon. }\n  left. by apply FCOH.\nQed.\n\nLemma to_from_disjoint_from w w'\n      (NEQ : w <> w')\n      (NINIT : ~ is_init w')\n      (SW  : I w)\n      (SW' : I w')\n      (SL  : same_loc lab w w') :\n  Time.lt (f_from w') (f_from w) \\/ Time.le (f_to w) (f_from w').\nProof using WF IMMCON IE FCOH.\n  edestruct is_w_loc as [l LL].\n  { apply IE. apply SW. }\n  edestruct WF.(wf_co_total) with (a:=w) (b:=w'); eauto.\n  1,2: split; [by apply IE|]; eauto.\n  { by rewrite <- SL. }\n  { right. by apply FCOH. }\n  left. apply f_from_co_mon; auto.\nQed.\n\nEnd Props.\n\nEnd FtoCoherent.\n\nAdd Parametric Morphism : f_to_coherent with signature\n  eq ==> set_equiv ==> eq ==> eq ==> iff as f_to_coherent_more.\nProof using.\n  ins. split; intros HH.\n  all: red; splits; ins; try apply HH; auto; by apply H.\nQed.\n\nLemma f_to_coherent_mori G S S' f_to f_from\n      (IN : S' ⊆₁ S)\n      (FCOH : f_to_coherent G S f_to f_from) :\n  f_to_coherent G S' f_to f_from.\nProof using.\n  cdes FCOH.\n  red. splits; auto.\nQed.\n", "meta": {"author": "weakmemory", "repo": "promising2ToImm", "sha": "8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c", "save_path": "github-repos/coq/weakmemory-promising2ToImm", "path": "github-repos/coq/weakmemory-promising2ToImm/promising2ToImm-8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c/src/simulation/FtoCoherent.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.22081468744401217}}
{"text": "Require Import floyd.proofauto.\nRequire Import progs.odd.\nRequire Import progs.verif_evenodd_spec.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\n\nDefinition Gprog : funspecs :=\n     ltac:(with_library prog [odd_spec; even_spec]).\n\nLemma body_odd : semax_body Vprog Gprog f_odd odd_spec.\nProof.\nstart_function.\nchange even._n with _n.\nforward_if (PROP (z > 0) LOCAL (temp _n (Vint (Int.repr z))) SEP ()).\n*\n forward.\n*\n forward. entailer!.\n*\n  normalize.\n  forward_call (z-1).\n  omega.\n  forward.\n  entailer!.\n  rewrite Z.even_sub; simpl.\n  case_eq (Z.odd z); rewrite Zodd_even_bool;\n   destruct (Z.even z); simpl; try (intros; congruence).\nQed.\nLocate augment_funspecs'.\n\n(* The Espec for odd is different from the Espec for even;\n  the former has only \"even\" as an external function, and vice versa. *)\nDefinition Espec := add_funspecs NullExtension.Espec (ext_link_prog odd.prog) Gprog.\nExisting Instance Espec.\n\nLemma all_funcs_correct:\n  semax_func Vprog Gprog (prog_funct prog) Gprog.\nProof.\n(*unfold Gprog at 2, prog, prog_funct; simpl. *)\nrepeat (apply semax_func_cons_ext_vacuous; [reflexivity | reflexivity | ]).\nsemax_func_cons_ext.\nsemax_func_cons body_odd.\nQed.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/progs/verif_odd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2207858048116584}}
{"text": "Require Import Thread0.\n\n\nModule Make(M : S).\nImport M.\n\nModule T := Thread0.Make(M).\nImport T.\n\nDefinition handlerS := SPEC reserving 49\n  Al fs, PREmain[_] sched fs * mallocHeap 0.\n\nDefinition mainS := SPEC reserving 49\n  PREmain[_] globalSched =?> 1 * mallocHeap 0.\n\nDefinition m := bimport [[ \"scheduler\"!\"init\" @ [initS], \"scheduler\"!\"exit\" @ [exitS],\n                           \"scheduler\"!\"spawn\" @ [spawnS] ]]\n  bmodule \"test\" {{\n    bfunctionNoRet \"handler\"(\"xx\", \"yy\") [handlerS]\n      Exit 50\n    end with bfunctionNoRet \"main\"(\"xx\", \"yy\") [mainS]\n      Init\n      [Al fs, PREmain[_] sched fs * mallocHeap 0];;\n\n      Spawn(\"test\"!\"handler\", 50)\n      [Al fs, PREmain[_] sched fs * mallocHeap 0];;\n\n      Spawn(\"test\"!\"handler\", 50)\n      [Al fs, PREmain[_] sched fs * mallocHeap 0];;\n\n      Exit 50\n    end\n  }}.\n\nTheorem ok : moduleOk m.\n  vcgen; abstract (sep_auto; auto).\nQed.\n\nEnd Make.\n", "meta": {"author": "gmalecha", "repo": "bedrock-mirror-shard", "sha": "ea7e5ad56a1d6392468b6823e0457dd44524bca7", "save_path": "github-repos/coq/gmalecha-bedrock-mirror-shard", "path": "github-repos/coq/gmalecha-bedrock-mirror-shard/bedrock-mirror-shard-ea7e5ad56a1d6392468b6823e0457dd44524bca7/platform/tests/BabyThread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22078579859121047}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.SpecLemmas.\n\nRequire Import VerdiRaft.NoAppendEntriesToSelfInterface.\n\nSection NoAppendEntriesToSelf.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Lemma doLeader_no_messages_to_self :\n    forall st h os st' ms m,\n      doLeader st h = (os, st', ms) ->\n      In m ms ->\n      fst m <> h.\n  Proof using. \n    intros.\n    unfold doLeader in *.\n    repeat break_match; try solve [find_inversion; simpl in *; congruence].\n    find_inversion.\n    do_in_map.\n    subst. simpl in *.\n    find_apply_lem_hyp filter_In.\n    intuition. subst.\n    break_match; congruence.\n  Qed.\n\n  Lemma no_append_entries_to_self_do_leader :\n    raft_net_invariant_do_leader no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    do_in_map.\n    subst. simpl in *.\n    find_eapply_lem_hyp doLeader_no_messages_to_self; eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_do_generic_server :\n    raft_net_invariant_do_generic_server no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    do_in_map.\n    subst. simpl in *.\n    find_eapply_lem_hyp doGenericServer_packets. subst. simpl in *. intuition.\n  Qed.\n\n  Lemma no_append_entries_to_self_append_entries :\n    raft_net_invariant_append_entries no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    subst. simpl in *. subst.\n    find_apply_lem_hyp handleAppendEntries_not_append_entries.\n    intuition. find_false. repeat eexists; eauto.\n  Qed.\n  \n  Lemma no_append_entries_to_self_append_entries_reply :\n    raft_net_invariant_append_entries_reply no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    do_in_map. subst. simpl in *.\n    find_apply_lem_hyp handleAppendEntriesReply_packets.\n    subst. intuition.\n  Qed.\n  \n  Lemma no_append_entries_to_self_request_vote :\n    raft_net_invariant_request_vote no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    subst. simpl in *. subst.\n    find_apply_lem_hyp handleRequestVote_no_append_entries.\n    intuition. find_false. repeat eexists; eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_request_vote_reply :\n    raft_net_invariant_request_vote_reply no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_client_request :\n    raft_net_invariant_client_request no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    do_in_map. subst. simpl in *.\n    find_eapply_lem_hyp handleClientRequest_no_append_entries; eauto.\n    intuition. find_false. repeat eexists; eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_timeout :\n    raft_net_invariant_timeout no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n    do_in_map. subst. simpl in *.\n    find_eapply_lem_hyp handleTimeout_not_is_append_entries; eauto.\n    intuition. find_false. repeat eexists; eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_state_same_packet_subset :\n    raft_net_invariant_state_same_packet_subset no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_apply_hyp_hyp. intuition eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_reboot :\n    raft_net_invariant_reboot no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *.\n    find_reverse_rewrite. intuition eauto.\n  Qed.\n\n  Lemma no_append_entries_to_self_init :\n    raft_net_invariant_init no_append_entries_to_self.\n  Proof using. \n    red. red. intros. simpl in *. intuition.\n  Qed.\n\n\n  Theorem no_append_entries_to_self_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      no_append_entries_to_self net.\n  Proof using. \n    intros.\n    apply raft_net_invariant; auto.\n    - apply no_append_entries_to_self_init.\n    - apply no_append_entries_to_self_client_request.\n    - apply no_append_entries_to_self_timeout.\n    - apply no_append_entries_to_self_append_entries.\n    - apply no_append_entries_to_self_append_entries_reply.\n    - apply no_append_entries_to_self_request_vote.\n    - apply no_append_entries_to_self_request_vote_reply.\n    - apply no_append_entries_to_self_do_leader.\n    - apply no_append_entries_to_self_do_generic_server.\n    - apply no_append_entries_to_self_state_same_packet_subset.\n    - apply no_append_entries_to_self_reboot.\n  Qed.    \n  \n  Instance noaetsi : no_append_entries_to_self_interface.\n  split. exact no_append_entries_to_self_invariant.\n  Qed.\n\nEnd NoAppendEntriesToSelf.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft-proofs/NoAppendEntriesToSelfProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22078579859121045}}
{"text": "From Coq Require Import List.\n\nFrom compcert Require Import common.Errors.\nFrom Velus Require Import Common.\nFrom Velus Require Import Environment.\nFrom Velus Require Import Operators.\nFrom Velus Require Import Clocks.\n\nFrom Velus Require Import Lustre.LSyntax.\nFrom Velus Require Import Lustre.LCausality.\nFrom Velus Require Import Lustre.Normalization.Normalization.\n\nFrom Velus Require Import CoreExpr.CESyntax.\nFrom Velus Require Import NLustre.NLSyntax.\nFrom Velus Require Import Transcription.Tr.\n\nModule Type COMPLETENESS\n       (Import Ids : IDS)\n       (Import Op : OPERATORS)\n       (Import OpAux : OPERATORS_AUX Op)\n       (Import LSyn : LSYNTAX Ids Op)\n       (Import LCau : LCAUSALITY Ids Op LSyn)\n       (Import Norm : NORMALIZATION Ids Op OpAux LSyn LCau)\n       (Import CE : CESYNTAX Op)\n       (NL : NLSYNTAX Ids Op CE)\n       (Import TR : TR Ids Op OpAux LSyn CE NL).\n\n  Fact to_constant_complete : forall c,\n    normalized_constant c ->\n    exists e', to_constant c = OK e'.\n  Proof with eauto.\n    intros c Hnorm. induction Hnorm.\n    - eexists; simpl...\n    - destruct IHHnorm as [e' He'].\n      eexists; simpl...\n  Qed.\n\n  Fact to_lexp_complete : forall e,\n    normalized_lexp e ->\n    exists e', to_lexp e = OK e'.\n  Proof with eauto.\n    intros e Hnorm.\n    induction e using exp_ind2; inv Hnorm.\n    - (* const *) eexists; simpl...\n    - (* var *) eexists; simpl...\n    - (* unop *)\n      apply IHe in H0 as [e' He'].\n      eexists; simpl.\n      rewrite He'; simpl...\n    - (* binop *)\n      apply IHe1 in H1 as [e1' He1].\n      apply IHe2 in H4 as [e2' He2].\n      eexists; simpl.\n      rewrite He1. rewrite He2. simpl...\n    - (* when *)\n      inv H. apply H3 in H1 as [e' He'].\n      eexists; simpl.\n      rewrite He'. simpl...\n  Qed.\n\n  Corollary mmap_to_lexp_complete : forall es,\n      Forall normalized_lexp es ->\n      exists es', mmap to_lexp es = OK es'.\n  Proof with eauto.\n    intros es Hf.\n    induction Hf.\n    - eexists; simpl...\n    - apply to_lexp_complete in H as [e' He'].\n      destruct IHHf as [es' Hes'].\n      eexists; simpl.\n      rewrite He'; rewrite Hes'. simpl...\n  Qed.\n\n  Fact to_cexp_complete : forall e,\n      normalized_cexp e ->\n      exists e', to_cexp e = OK e'.\n  Proof with eauto.\n    intros e Hnorm.\n    induction e using exp_ind2; inv Hnorm;\n      try (eapply to_lexp_complete in H as [e' He'];\n           exists (Eexp e'); unfold to_cexp; rewrite He'; simpl; eauto);\n      try (solve [inv H1]).\n    - (* when *)\n      eapply to_lexp_complete in H0 as [e' He'].\n      exists (Eexp e'). unfold to_cexp. rewrite He'; simpl...\n    - (* merge *)\n      inv H. inv H0.\n      apply H4 in H3 as [et' Het'].\n      apply H2 in H6 as [ef' Hef'].\n      eexists. simpl.\n      rewrite Het'. rewrite Hef'. simpl...\n    - (* ite *)\n      inv H. inv H0.\n      apply to_lexp_complete in H4 as [e' He'].\n      apply H3 in H6 as [et' Het'].\n      apply H2 in H7 as [ef' Hef'].\n      eexists; simpl.\n      rewrite He'. rewrite Het'. rewrite Hef'. simpl...\n  Qed.\n\n  Fact to_equation_complete : forall G xs es out env envo,\n      normalized_equation G out (xs, es) ->\n      Forall (fun x => exists cl, find_clock env x = OK cl) xs ->\n      (forall x e, envo x = Error e -> PS.In x out) ->\n      exists eq', to_equation env envo (xs, es) = OK eq'.\n  Proof with eauto.\n    intros * Hnorm Hfind Henvo.\n    inv Hnorm.\n    - apply mmap_to_lexp_complete in H1 as [es' Hes'].\n      eexists; simpl. rewrite Hes'; simpl...\n    - apply mmap_to_lexp_complete in H1 as [es' Hes'].\n      destruct cl.\n      eexists; simpl. rewrite Hes'. simpl...\n    - apply to_constant_complete in H3 as [e0' He0'].\n      apply to_lexp_complete in H4 as [e' He'].\n      inv Hfind. destruct H2 as [cl Hcl].\n      eexists; simpl.\n      rewrite He0'. rewrite He'. rewrite Hcl.\n      simpl.\n      specialize (Henvo x).\n      destruct (envo x); simpl...\n      exfalso...\n    - specialize (to_cexp_complete _ H1) as [e' He'].\n      inv Hfind. destruct H2 as [cl Hcl].\n      eexists; simpl.\n      destruct e; try (rewrite Hcl; rewrite He'; simpl; eauto).\n      inv He'.\n      inv He'.\n  Qed.\n\n  Corollary mmap_to_equation_complete : forall G eqs out env envo,\n      Forall (normalized_equation G out) eqs ->\n      Forall (fun x => exists cl, find_clock env x = OK cl) (vars_defined eqs) ->\n      (forall x e, envo x = Error e -> PS.In x out) ->\n      exists eqs', mmap (to_equation env envo) eqs = OK eqs'.\n  Proof.\n    induction eqs; intros * Hnorm Hfind Henvo; simpl.\n    - eexists; eauto.\n    - inv Hnorm. destruct a.\n      simpl in Hfind. rewrite Forall_app in Hfind. destruct Hfind as [Hfind1 Hfind2].\n      specialize (to_equation_complete _ _ _ _ _ _ H1 Hfind1 Henvo) as [eq' Heq'].\n      eapply IHeqs in H2; eauto. destruct H2 as [eqs' Heqs'].\n      rewrite Heqs'; rewrite Heq'; eexists; simpl; eauto.\n  Qed.\n\n  Corollary mmap_to_equation_complete' : forall G n out env envo,\n      Forall (normalized_equation G out) (n_eqs n) ->\n      Forall (fun x => exists cl, find_clock env x = OK cl) (vars_defined (n_eqs n)) ->\n      (forall x e, envo x = Error e -> PS.In x out) ->\n      exists eqs', mmap_to_equation env envo n = OK eqs'.\n  Proof.\n    intros * Hnorm Hfind Henvo.\n    eapply mmap_to_equation_complete in Hnorm; eauto.\n    destruct Hnorm as [eqs' Heqs'].\n    exists (exist (fun neqs : list NL.equation => _) eqs' Heqs').\n    unfold mmap_to_equation. rewrite Heqs'. reflexivity.\n  Qed.\n\n  Lemma to_node_complete : forall G n Hpref,\n      normalized_node G n ->\n      exists n', to_node n Hpref = OK n'.\n  Proof.\n    intros * Hnorm.\n    unfold to_node.\n    edestruct mmap_to_equation_complete' as [[? ?] H].\n    4: (rewrite H; eauto).\n    - unfold normalized_node in Hnorm. eassumption.\n    - specialize (n_defd n) as Hperm.\n      rewrite Forall_forall. intros x Hin.\n      eapply Permutation.Permutation_in in Hperm; eauto. clear Hin.\n      rewrite in_map_iff in Hperm; destruct Hperm as [[? [? ?]] [? Hin]]; simpl in H; subst.\n      erewrite envs_eq_find with (ck:=c); simpl; eauto.\n      + apply envs_eq_node.\n      + rewrite In_idck_exists.\n        exists t. repeat rewrite in_app_iff in *.\n        destruct Hin; auto.\n    - intros x e Hmem; simpl in Hmem.\n      rewrite ps_from_list_In.\n      rewrite <- fst_InMembers. rewrite <- Env.In_from_list.\n      apply Env.mem_2.\n      destruct (Env.mem x (Env.from_list (n_out n))); congruence.\n  Qed.\n\n  Lemma to_global_complete : forall G Hprefs,\n      normalized_global G ->\n      exists G', to_global G Hprefs = OK G'.\n  Proof.\n    induction G; intros * Hnormed; inv Hnormed.\n    - exists nil. reflexivity.\n    - unfold to_global; simpl.\n      eapply to_node_complete in H1 as (hd'&Hton). erewrite Hton; clear Hton; simpl.\n      eapply IHG in H2 as (tl'&HtoG). erewrite HtoG; clear HtoG; simpl.\n      eauto.\n  Qed.\n\n  Theorem normalize_global_complete : forall G G' Hwl Hprefs Hprefs',\n      normalize_global G Hwl Hprefs = OK G' ->\n      exists G'', to_global G' Hprefs' = OK G''.\n  Proof.\n    intros * Hnorm.\n    eapply to_global_complete.\n    eapply normalize_global_normalized_global; eauto.\n  Qed.\nEnd COMPLETENESS.\n\nModule CompletenessFun\n       (Ids : IDS)\n       (Op : OPERATORS)\n       (OpAux : OPERATORS_AUX Op)\n       (LSyn : LSYNTAX Ids Op)\n       (LCau : LCAUSALITY Ids Op LSyn)\n       (Norm : NORMALIZATION Ids Op OpAux LSyn LCau)\n       (CE : CESYNTAX Op)\n       (NL : NLSYNTAX Ids Op CE)\n       (TR : TR Ids Op OpAux LSyn CE NL)\n       <: COMPLETENESS Ids Op OpAux LSyn LCau Norm CE NL TR.\n  Include COMPLETENESS Ids Op OpAux LSyn LCau Norm CE NL TR.\nEnd CompletenessFun.\n", "meta": {"author": "INRIA", "repo": "velus", "sha": "116a88bc71f3608ff43ed967895743e8b9a340e0", "save_path": "github-repos/coq/INRIA-velus", "path": "github-repos/coq/INRIA-velus/velus-116a88bc71f3608ff43ed967895743e8b9a340e0/src/Transcription/Completeness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22078579859121045}}
{"text": "From RecordUpdate Require Import RecordSet.\n\nFrom Perennial.Helpers Require Import CountableTactics Transitions.\nFrom Perennial.goose_lang Require Import lang lifting slice typing spec_assert.\nFrom Perennial.goose_lang Require ffi.disk.\nFrom Perennial.algebra Require Import gen_heap_names.\n\nFrom iris.algebra Require Import auth agree excl csum.\nFrom Perennial.base_logic Require Import ghost_var.\n\nSet Default Proof Using \"Type\".\n\n(* TODO: move this out, it's completely general *)\n(* Generalize life cycle of object state *)\nSection recoverable.\n  Context {Σ:Type}.\n  Inductive RecoverableState :=\n    | UnInit\n    | Initing\n    | Closed (s:Σ)\n    | Opening (s:Σ)\n    | Opened (s:Σ) (l:loc)\n  .\n\n  Definition recoverable_model : ffi_model :=\n    mkFfiModel (RecoverableState) () (populate UnInit) _.\n\n  Local Existing Instance recoverable_model.\n\n  Context {ext:ffi_syntax}.\n\n  Definition openΣ : transition (state*global_state) (Σ*loc) :=\n    bind (reads id) (λ '(rs,g), match rs.(world) with\n                           | Opened s l => ret (s,l)\n                           | _ => undefined\n                           end).\n\n  Definition modifyΣ (f:Σ -> Σ) : transition (state*global_state) unit :=\n    bind openΣ (λ '(s, l), modify (λ '(σ,g), (set world (λ _, Opened (f s) l) σ, g))).\n\n  (* TODO: generalize to a transition to construct the initial value, using a zoom *)\n  Definition initTo (init:Σ) (l:loc) : transition (state*global_state) unit :=\n    bind (reads id) (λ '(rs,g), match rs.(world) with\n                           | UnInit => modify (λ '(σ,g), (set world (fun _ => Opened init l) σ, g))\n                           | _ => undefined\n                           end).\n\n  Definition open (l:loc) : transition (state*global_state) Σ :=\n    bind (reads id) (λ '(rs,g), match rs.(world) with\n                           | Closed s => bind (modify (λ '(σ,g), (set world (fun _ => Opened s l) σ, g)))\n                                             (fun _ => ret s)\n                           | _ => undefined\n                           end).\n\n  Definition close : transition (RecoverableState) unit :=\n    bind (reads id) (fun s => match s with\n                           | Opened s _ | Closed s => modify (fun _ => Closed s)\n                           | UnInit => modify (fun _ => UnInit)\n                           | _ => undefined\n                           end).\n\n  Global Instance Recoverable_inhabited : Inhabited RecoverableState := populate UnInit.\nEnd recoverable.\n\nArguments RecoverableState Σ : clear implicits.\nArguments recoverable_model Σ : clear implicits.\n\nDefinition ty_ := forall (val_ty:val_types), @ty val_ty.\n(* TODO: slice should not require an entire ext_ty *)\nDefinition sliceT_ (t: ty_) : ty_ := λ val_ty, prodT (arrayT (t _)) uint64T.\nDefinition blockT_: ty_ := sliceT_ (λ val_ty, byteT).\n\nInductive KvsOp :=\n  | OpenOp (* both open and init map to the same function (makeKVS) *)\n  | InitOp\n  | GetOp\n  | MultiPutMarkOp\n  | MultiPutCommitOp\n.\n\nInstance eq_KvsOp : EqDecision KvsOp.\nProof.\n  solve_decision.\nDefined.\n\nInstance KvsOp_fin : Countable KvsOp.\nProof.\n  solve_countable KvsOp_rec 5%nat.\nQed.\n\nDefinition kvs_op : ffi_syntax.\nProof.\n  refine (mkExtOp KvsOp _ _ Empty_set _ _).\nDefined.\n\nInductive Kvs_ty := KvsT.\n\nInstance kvs_val_ty: val_types :=\n  {| ext_tys := Kvs_ty; |}.\n\nSection kvs.\n  Parameter kvs_sz : nat.\n\n  Fixpoint init_keys (keys: list u64) (sz: nat) : list u64 :=\n  match sz with\n  | O => keys\n  | S n => init_keys ((U64 (Z.of_nat n)) :: keys) n\n  end.\n  Definition kvs_keys_all : list u64 := init_keys [] kvs_sz.\n\n  Definition kvs_state_typ := gmap u64 disk.Block.\n  Fixpoint init_kvs (kvs: kvs_state_typ) (sz: nat) : kvs_state_typ :=\n  match sz with\n  | O => kvs\n  | S n => <[(U64 (Z.of_nat n)) := (inhabitant disk.Block0)]> (init_kvs kvs n)\n  end.\n  Definition kvs_init_s : gmap u64 disk.Block := init_kvs ∅ kvs_sz.\n\n  Definition KVPairT : ty := structRefT [uint64T; prodT (arrayT (uint64T)) uint64T].\n  Existing Instances kvs_op kvs_val_ty.\n\n  Inductive kvs_ext_tys : @val kvs_op -> (ty * ty) -> Prop :=\n  | KvsOpType op :\n      kvs_ext_tys (λ: \"v\", ExternalOp op (Var \"v\"))%V\n       (match op with\n         (* pair where first comp is type of inputs, sec is type of outputs *)\n           (* have make take no arguments, initialize super + txn -- assume specs? *)\n           (* kvs type should be opaque, but kvpair should be known by client *)\n         | OpenOp => (unitT, extT KvsT)\n         | InitOp => (unitT, extT KvsT)\n         | GetOp => (prodT (extT KvsT) uint64T, prodT (KVPairT) boolT)\n         | MultiPutMarkOp => (prodT (extT KvsT) (prodT (arrayT KVPairT) uint64T), unitT)\n         | MultiPutCommitOp => (prodT (extT KvsT) (prodT (arrayT KVPairT) uint64T), boolT)\n         end).\n\n  Instance kvs_ty: ext_types kvs_op :=\n    {| val_tys := kvs_val_ty;\n       get_ext_tys := kvs_ext_tys |}.\n\n  Definition kvs_state := RecoverableState (gmap u64 disk.Block).\n\n  Instance kvs_model : ffi_model := recoverable_model (gmap u64 disk.Block).\n\n  Existing Instances r_mbind r_fmap.\n\n  Definition mark_slice {state} (t:ty) (v:val): transition state () :=\n    match v with\n    | PairV (#(LitLoc l)) (PairV #(LitInt sz) #(LitInt cap)) =>\n      (* TODO: implement , mark as being read *)\n      ret ()\n    | _ => undefined\n    end.\n\n  Definition read_slice {state} (t:ty) (v:val): transition state (list val) :=\n    match v with\n    | PairV (#(LitLoc l)) (PairV #(LitInt sz) #(LitInt cap)) =>\n      (* TODO: implement , return contents *)\n      ret []\n    | _ => undefined\n    end.\n\n  Definition read_kvpair_key {state} (t:ty) (v:val): transition state u64:=\n    match v with\n    | PairV #(LitInt key) #(LitLoc _) => ret key\n    | _ => undefined\n    end.\n\n  Definition read_kvpair_dataslice {state} (t:ty) (v:val): transition state val :=\n    match v with\n    | PairV #(LitInt _) #(LitLoc dataloc) =>ret #(LitLoc dataloc)\n    | _ => undefined\n    end.\n\n  Fixpoint update_keys (kvs : gmap u64 disk.Block) (keys : list u64) (data: list disk.Block)\n    : gmap u64 disk.Block\n    :=\n    match keys, data with\n    | k::ks, d::ds => update_keys (<[k := d]> kvs) ks ds\n    | [], [] => kvs\n    | _, _ => kvs\n    end.\n\n  Fixpoint tmapM {Σ A B} (f: A -> transition Σ B) (l: list A) : transition Σ (list B) :=\n    match l with\n    | [] => ret []\n    | x::xs => b ← f x;\n             bs ← tmapM f xs;\n             ret (b :: bs)\n    end.\n\n  (* TODO: implement *)\n  Definition to_block (l: list val): option disk.Block := None.\n\n  Definition allocIdent: transition (state*global_state) loc :=\n    l ← allocateN;\n    modify (λ '(σ, g), (set heap <[l := Free #()]> σ, g));;\n           ret l.\n\n  Definition kvs_step (op:KvsOp) (v:val) : transition (state*global_state) val :=\n    match op, v with\n    | InitOp, LitV LitUnit =>\n      kvsPtr ← allocIdent;\n      initTo (kvs_init_s) kvsPtr;;\n      ret $ (LitV $ LitLoc kvsPtr)\n    | OpenOp, LitV LitUnit =>\n      logPtr ← allocIdent;\n      s ← open logPtr;\n      ret $ LitV $ LitLoc logPtr\n    | GetOp, PairV (LitV (LitLoc kvsPtr)) (LitV (LitInt key)) =>\n      openΣ ≫= λ '(kvs, kvsPtr_), (*kvs is the state *)\n      check (kvsPtr = kvsPtr_);;\n      b ← unwrap (kvs !! key);\n      l ← allocateN;\n      modify (λ '(σ,g), (state_insert_list l (disk.Block_to_vals b) σ, g));;\n             ret $ (PairV #(LitLoc l) #true) (*This could return false?*) \n    | MultiPutMarkOp, PairV (LitV (LitLoc kvsPtr)) v => mark_slice KVPairT v;; ret $ #()\n    | MultiPutCommitOp, PairV (LitV (LitLoc kvsPtr)) v =>\n      (*convert goose representations of kvpair to coq pair of key and value, *)\n      (*given list of updates, inserts into gmap *)\n      (*to define spec effect of operation*)\n      openΣ ≫= λ '(_, kvsPtr_),\n      check (kvsPtr = kvsPtr_);;\n      (* FIXME: append should be non-atomic in the spec because it needs to read\n         an input slice (and the slices the input points to). *)\n      (* need to mark that everything is being read so no concurrent modifications *)\n      (* LYT: we might just need to check no other writers? Might need to split into two steps *)\n      block_slices ← read_slice KVPairT v;\n      block_keys ← tmapM (read_kvpair_key KVPairT) block_slices;\n      block_dataslices ← tmapM (read_kvpair_dataslice KVPairT) block_slices;\n      block_vals ← tmapM (read_slice (@slice.T _ kvs_ty byteT)) block_dataslices;\n      new_blocks ← tmapM (unwrap ∘ to_block) block_vals;\n      modifyΣ (λ s, update_keys s block_keys new_blocks);;\n      ret $ #true (*TODO can this return false if commit_wait fails? *)\n    | _, _ => undefined\n    end.\n\n  Instance kvs_semantics : ffi_semantics kvs_op kvs_model :=\n    {| ffi_step := kvs_step;\n       ffi_crash_step := fun s s' => relation.denote close s s' tt; |}. (* everything is durable *)\nEnd kvs.\n\nInductive kvs_unopen_status := UnInit' | Closed'.\n\n(* resource alg: append log has two: *)\n(* (1) tracks status of append log (open/closed) --> anything with recoverable state*)\nDefinition openR := csumR (prodR fracR (agreeR (leibnizO kvs_unopen_status))) (agreeR (leibnizO loc)).\n\nDefinition Kvs_Opened (l: loc) : openR := Cinr (to_agree l).\n\n(* Type class defn, define which algebras are available *)\nClass kvsG Σ :=\n  { kvsG_open_inG :> inG Σ openR; (* inG --> which resources are available in type class *)\n    (* implicitly insert names for elements, used to tag which generation *)\n    kvsG_open_name : gname;\n    (* (2) exlusive/etc. algebra for disk blocks --> allows for ownership of blocks *)\n    kvsG_state_inG :> gen_heap.gen_heapGS u64 disk.Block Σ;\n  }.\n\n(* without names: e.g. disk names stay same, memory ones are forgotten *)\nClass kvs_preG Σ :=\n  { kvsG_preG_open_inG :> inG Σ openR;\n    kvsG_preG_state_inG :> gen_heap.gen_heapGpreS u64 disk.Block Σ;\n  }.\n\nDefinition kvsΣ : gFunctors :=\n  #[GFunctor openR; gen_heapΣ u64 disk.Block].\n\nInstance subG_kvsG Σ: subG kvsΣ Σ → kvs_preG Σ.\nProof. solve_inG. Qed.\n\n(* Helpers to manipulate names *)\nRecord kvs_names :=\n  { kvs_names_open: gname;\n    kvs_names_state: gen_heap_names; }.\n\nDefinition kvs_get_names {Σ} (kvs: kvsG Σ) :=\n  {| kvs_names_open := kvsG_open_name; kvs_names_state := gen_heapG_get_names kvsG_state_inG|}.\n\nDefinition kvs_update {Σ} (kvs: kvsG Σ) (names: kvs_names) :=\n  {| kvsG_open_inG := kvsG_open_inG;\n     kvsG_open_name := (kvs_names_open names);\n     kvsG_state_inG := gen_heapG_update kvsG_state_inG names.(kvs_names_state);\n  |}.\n\nDefinition kvs_update_pre {Σ} (kvsG: kvs_preG Σ) (names: kvs_names) :=\n  {| kvsG_open_inG := kvsG_preG_open_inG;\n     kvsG_open_name := (kvs_names_open names);\n     kvsG_state_inG := gen_heapG_update_pre kvsG_preG_state_inG names.(kvs_names_state);\n  |}.\n\n(* assert have resource that tell us that kvs is opened at l, persistent + duplicable *)\nDefinition kvs_open {Σ} {kvsG :kvsG Σ} (l: loc) :=\n  own (kvsG_open_name) (Kvs_Opened l).\nDefinition kvs_closed_frag {Σ} {kvsG :kvsG Σ} :=\n  own (kvsG_open_name) (Cinl ((1/2)%Qp, to_agree (Closed' : leibnizO kvs_unopen_status))).\nDefinition kvs_closed_auth {Σ} {kvsG :kvsG Σ} :=\n  own (kvsG_open_name) (Cinl ((1/2)%Qp, to_agree (Closed' : leibnizO kvs_unopen_status))).\nDefinition kvs_uninit_frag {Σ} {ksG :kvsG Σ} :=\n  own (kvsG_open_name) (Cinl ((1/2)%Qp, to_agree (UnInit' : leibnizO kvs_unopen_status))).\nDefinition kvs_uninit_auth {Σ} {kvsG :kvsG Σ} :=\n  own (kvsG_open_name) (Cinl ((1/2)%Qp, to_agree (UnInit' : leibnizO kvs_unopen_status))).\n\n(* what blocks are in the kvs *)\n(* kvs: more fine-grained lock? or lock entire map? (more/less useful for clients?) *)\n(* precondition in spec --> assert have points-to facts (no state RA), gen_heap *)\nDefinition kvs_auth {Σ} {kvs :kvsG Σ} (s: gmap u64 disk.Block) := gen_heap.gen_heap_interp s.\nDefinition kvs_frag {Σ} {kvsG :kvsG Σ} (k : u64) (v : disk.Block) : iProp Σ :=\n   (gen_heap.mapsto (L:=u64) (V:=disk.Block) k (DfracOwn 1) v)%I.\n\nSection kvs_interp.\n  Existing Instances kvs_op kvs_model kvs_val_ty.\n\n  (* ctx assertions map physical state to which resource assertions should be true, *)\n  (* stores auth copy of fact*)\n  Definition kvs_ctx {Σ} {kvsG: kvsG Σ} (kvs: @ffi_state kvs_model) : iProp Σ :=\n    match kvs with\n    | Opened s l => kvs_open l ∗ kvs_auth s\n    | Closed s => kvs_closed_auth ∗ kvs_auth s\n    | UnInit => kvs_uninit_auth ∗ kvs_auth (∅ : gmap u64 disk.Block) (*  XXXX kvs_init_s *)\n    | _ => False%I\n    end.\n\n  (* When first start program, what initial resources assertions do you get *)\n  Definition kvs_start {Σ} {kvsG: kvsG Σ} (kvs: @ffi_state kvs_model) : iProp Σ :=\n    match kvs with\n    | Opened s l => kvs_open l ∗ ([∗ list] k ∈ kvs_keys_all, (∃ v, kvs_frag k v)%I)\n    | Closed s => kvs_closed_frag ∗ ([∗ list] k ∈ kvs_keys_all, (∃ v, kvs_frag k v)%I)\n    | UnInit => kvs_uninit_frag\n    | _ => False%I\n    end.\n\n(* get access to whether open/closed status *)\n  Definition kvs_restart {Σ} (kvsG: kvsG Σ) (kvs: @ffi_state kvs_model) :=\n    match kvs with\n    | Opened s l => kvs_open l\n    | Closed s => kvs_closed_frag\n    | UnInit => kvs_uninit_frag\n    | _ => False%I\n    end.\n  (*how to interpret physical state as ghost resources*)\n  Program Instance kvs_interp : ffi_interp kvs_model :=\n    {| ffiGS := kvsG;\n       ffi_local_names := kvs_names;\n       ffi_global_names := unit;\n       ffi_get_local_names := @kvs_get_names;\n       ffi_get_global_names := (λ _ _, tt);\n       ffi_update_local := @kvs_update;\n       ffi_get_update := _;\n       ffi_ctx := @kvs_ctx;\n       ffi_global_ctx _ _ _ := True%I;\n       ffi_start Σ G w _ := @kvs_start Σ G w;\n       ffi_restart := @kvs_restart;\n       ffi_crash_rel := λ Σ hF1 σ1 hF2 σ2, ⌜ @kvsG_state_inG _ hF1 = @kvsG_state_inG _ hF2 ∧\n                                           kvs_names_state (kvs_get_names hF1) =\n                                           kvs_names_state (kvs_get_names hF2) ⌝%I;\n    |}.\n  Next Obligation.\n    intros.\n    destruct hF.\n    destruct names.\n    unfold kvs_update. simpl.\n    destruct kvsG_state_inG0; simpl. unfold kvs_get_names; simpl.\n    unfold gen_heapG_get_names; simpl.\n    destruct kvs_names_state0; simpl; auto.\n    Qed.\n  Next Obligation. intros ? [[]] => //=. Qed.\n  Next Obligation. intros ? [[]] => //=.\n                   unfold kvs_update; simpl.\n                   destruct kvsG_state_inG0; simpl.\n                   unfold kvs_get_names; simpl.\n                   unfold gen_heapG_get_names; simpl.\n                   auto.\n  Qed.\n  Next Obligation. intros ? [[]] => //=. Qed.\n  Next Obligation. intros ? [[]] => //=. Qed.\nEnd kvs_interp.\n\nSection misc_lemmas.\n  Context `{kvsG_ctx: inG Σ openR}.\n\n  Theorem openR_frac_split γ (q1 q2 : Qp) x :\n    own γ (Cinl ((q1 + q2)%Qp, x) : openR) ⊣⊢ own γ (Cinl (q1, x)) ∗ own γ (Cinl (q2, x)).\n  Proof.\n    rewrite -own_op.\n    f_equiv.\n    apply Cinl_equiv.\n    apply pair_proper; simpl.\n    - rewrite frac_op //.\n    - rewrite agree_idemp //.\n  Qed.\nEnd misc_lemmas.\n\nSection kvs_lemmas.\n  Context `{kvsG_ctx: kvsG Σ}.\n\n\n  Global Instance kvs_ctx_Timeless kvs: Timeless (kvs_ctx kvs).\n  Proof. destruct kvs; apply _. Qed.\n\n  Global Instance kvs_start_Timeless kvs: Timeless (kvs_start kvs).\n  Proof. destruct kvs; apply _. Qed.\n\n  Global Instance kvs_restart_Timeless kvs: Timeless (kvs_restart _ kvs).\n  Proof. destruct kvs; apply _. Qed.\n\n  Global Instance kvs_open_Persistent (l: loc) : Persistent (kvs_open l).\n  Proof. rewrite /kvs_open/Kvs_Opened. apply own_core_persistent. rewrite /CoreId//=. Qed.\n\n  Lemma kvs_closed_auth_uninit_frag:\n    kvs_closed_auth -∗ kvs_uninit_frag -∗ False.\n  Proof.\n    iIntros \"Hauth Huninit_frag\".\n    iDestruct (own_valid_2 with \"Hauth Huninit_frag\") as %Hval.\n    inversion Hval as [? Heq%to_agree_op_inv].\n    inversion Heq.\n  Qed.\n\n  Lemma kvs_uninit_auth_closed_frag:\n    kvs_uninit_auth -∗ kvs_closed_frag -∗ False.\n  Proof.\n    iIntros \"Hauth Huninit_frag\".\n    iDestruct (own_valid_2 with \"Hauth Huninit_frag\") as %Hval.\n    inversion Hval as [? Heq%to_agree_op_inv].\n    inversion Heq.\n  Qed.\n\n  Lemma kvs_uninit_auth_opened l:\n    kvs_uninit_auth -∗ kvs_open l -∗ False.\n  Proof.\n    iIntros \"Huninit_auth Hopen\".\n    iDestruct (own_valid_2 with \"Huninit_auth Hopen\") as %Hval.\n    inversion Hval.\n  Qed.\n\n  Lemma kvs_closed_auth_opened l:\n    kvs_closed_auth -∗ kvs_open l -∗ False.\n  Proof.\n    iIntros \"Huninit_auth Hopen\".\n    iDestruct (own_valid_2 with \"Huninit_auth Hopen\") as %Hval.\n    inversion Hval.\n  Qed.\n\n  (* know that we're closed + know value at a particular key *)\n  Notation \"l k↦ v\" := (gen_heap.mapsto (L:=u64) (V:=disk.Block) l (DfracOwn 1) v%V)\n                              (at level 20, format \"l  k↦ v\") : bi_scope.\n  Notation \"l k↦{ q } v\" := (gen_heap.mapsto (L:=u64) (V:=disk.Block) l (DfracOwn q) v%V)\n                              (at level 20, q at level 50, format \"l  k↦{ q }  v\") : bi_scope.\n  Lemma kvs_ctx_unify_closed kvs (key: u64) (val: disk.Block):\n    kvs_closed_frag -∗ key k↦ val -∗ kvs_ctx kvs -∗ ∃ s, ⌜s !! key = Some val ∧ kvs = Closed s ⌝.\n  Proof.\n    destruct kvs; try eauto; iIntros \"Hclosed_frag Hstate_frag Hctx\".\n    - iDestruct \"Hctx\" as \"(Huninit_auth&Hstate_auth)\".\n      iDestruct (kvs_closed_auth_uninit_frag with \"[$] [$]\") as %[].\n    - iExists s.\n      iDestruct \"Hctx\" as \"(Hclosed_auth&Hstate_auth)\".\n      iPoseProof (gen_heap_valid with \"Hstate_auth Hstate_frag\") as \"H\".\n      iSplit; auto.\n      - iDestruct \"Hctx\" as \"(Huninit_auth&Hstate_auth)\".\n        iDestruct (own_valid_2 with \"Huninit_auth Hclosed_frag\") as %Hval.\n        inversion Hval.\n  Qed.\n\n  Lemma kvs_ctx_unify_closed' kvs:\n    kvs_closed_frag -∗ kvs_ctx kvs -∗ ⌜∃ s, kvs = Closed s ⌝.\n  Proof.\n    destruct kvs; try eauto; iIntros \"Hclosed_frag Hctx\".\n    - iDestruct \"Hctx\" as \"(Huninit_auth&Hstate_auth)\".\n      iDestruct (kvs_closed_auth_uninit_frag with \"[$] [$]\") as %[].\n    - iDestruct \"Hctx\" as \"(Huninit_auth&Hstate_auth)\".\n        iDestruct (own_valid_2 with \"Huninit_auth Hclosed_frag\") as %Hval.\n        inversion Hval.\n  Qed.\n\n  Lemma kvs_auth_frag_unif (s : gmap u64 disk.Block) (k: u64) (v: disk.Block):\n    kvs_auth s -∗ k k↦ v -∗ ∃ s', ⌜s' !! k = Some v ∧ s = s'⌝.\n  Proof.\n    rewrite /kvs_auth/kvs_frag. iIntros \"H1 H2\".\n    iExists s.\n    iPoseProof (gen_heap_valid with \"H1 H2\") as \"H\".\n    iSplit; auto.\n  Qed.\n\n  Lemma kvs_open_unif l l':\n    kvs_open l -∗ kvs_open l' -∗ ⌜ l = l' ⌝.\n  Proof.\n    rewrite /kvs_auth/kvs_frag.\n    iIntros \"H1 H2\".\n    iDestruct (own_valid_2 with \"H1 H2\") as %Hval.\n    rewrite /Kvs_Opened -Cinr_op in Hval.\n    assert (l ≡ l') as Heq.\n    { eapply to_agree_op_inv. eauto. }\n    inversion Heq. by subst.\n  Qed.\n\n  Lemma kvs_ctx_unify_uninit kvs:\n    kvs_uninit_frag -∗ kvs_ctx kvs -∗ ⌜ kvs = UnInit ⌝.\n  Proof.\n    destruct kvs; try eauto; iIntros \"Huninit_frag Hctx\".\n    - iDestruct \"Hctx\" as \"(Huninit_auth&Hstate_auth)\".\n      iDestruct (own_valid_2 with \"Huninit_auth Huninit_frag\") as %Hval.\n      inversion Hval as [? Heq%to_agree_op_inv].\n      inversion Heq.\n    - iDestruct \"Hctx\" as \"(Hauth&Hstate_auth)\".\n      iDestruct (own_valid_2 with \"Hauth Huninit_frag\") as %Hval.\n      inversion Hval.\n  Qed.\n\n  Lemma kvs_ctx_unify_opened l kvs:\n    kvs_open l -∗ kvs_ctx kvs -∗ ⌜ ∃ vs, kvs = Opened vs l ⌝.\n  Proof.\n      destruct kvs as [| | | | vs' l']; try eauto; iIntros \"Hopen Hctx\".\n    - iDestruct \"Hctx\" as \"(Huninit_auth&Hstate_auth)\".\n      iDestruct (own_valid_2 with \"Huninit_auth Hopen\") as %Hval.\n      inversion Hval.\n    - iDestruct \"Hctx\" as \"(Huninit_auth&Hstate_auth)\".\n      iDestruct (own_valid_2 with \"Huninit_auth Hopen\") as %Hval.\n      inversion Hval.\n    - iDestruct \"Hctx\" as \"(Huninit_auth&Hstate_auth)\".\n      iDestruct (kvs_open_unif with \"[$] [$]\") as %Heq.\n      subst. eauto.\n  Qed.\n\n  Lemma kvs_uninit_token_open (l: loc):\n    kvs_uninit_auth -∗ kvs_uninit_frag ==∗ kvs_open l.\n  Proof.\n    iIntros \"Hua Huf\".\n    iCombine \"Hua Huf\" as \"Huninit\".\n    rewrite -Cinl_op.\n    iMod (own_update _ _ (Kvs_Opened l) with \"Huninit\") as \"$\"; last done.\n    { apply: cmra_update_exclusive.\n      { apply Cinl_exclusive. rewrite -pair_op frac_op Qp.half_half.\n        simpl. apply pair_exclusive_l. apply _.\n      }\n      { econstructor. }\n    }\n  Qed.\n\n  Lemma kvs_closed_token_open (l: loc):\n    kvs_closed_auth -∗ kvs_closed_frag ==∗ kvs_open l.\n  Proof.\n    iIntros \"Hua Huf\".\n    iCombine \"Hua Huf\" as \"Huninit\".\n    rewrite -Cinl_op.\n    (*Print cmra_update. can transform facts to another fact that is compatible w/others' facts*)\n    iMod (own_update _ _ (Kvs_Opened l) with \"Huninit\") as \"$\"; last done.\n    { apply: cmra_update_exclusive.\n      { apply Cinl_exclusive. rewrite -pair_op frac_op Qp.half_half.\n        simpl. apply pair_exclusive_l. apply _.\n      }\n      { econstructor. }\n    }\n  Qed.\n\n  (* insert updated keyval *)\n  Lemma kvs_state_update s k v1 v2:\n    kvs_auth s -∗ k k↦v1 ==∗ kvs_auth (<[k := v2]>s)∗ k k↦ v2.\n  Proof.\n    unfold kvs_auth. apply gen_heap_update.\n  Qed.\n\n(* Not related to physical state yet, just updates to ghost vars*)\nEnd kvs_lemmas.\n\nFrom Perennial.goose_lang Require Import adequacy.\n\n(* when crashes, ffi_crash_rel: hF[] = instance of type class kvsG *)\n(* Program Instance --> define instance of type class, don't need to fill in all fields (craete goal, obligation) *)Program Instance kvs_interp_adequacy:\n  @ffi_interp_adequacy kvs_model kvs_interp kvs_op kvs_semantics :=\n  {| ffi_preG := kvs_preG;\n     ffiΣ := kvsΣ;\n     subG_ffiPreG := subG_kvsG;\n     ffi_initP := λ σ _, σ = UnInit;\n     ffi_update_pre := (λ _ hP names _, @kvs_update_pre _ hP names)\n  |}.\nNext Obligation. rewrite //=. Qed.\nNext Obligation. rewrite //=. intros ?? [] [] => //=. Qed.\nNext Obligation.\n  intros.\n  unfold ffi_get_names; simpl.\n  unfold kvs_get_names; unfold kvs_update_pre.\n  unfold gen_heapG_get_names; simpl.\n  destruct names; simpl.\n  destruct kvs_names_state0; simpl; auto.\nQed.\nNext Obligation.\n  (*if in uninit state, can initialize algebra and give ffi start, show that ffi start can be created*)\n  (* first part: status *)\n  rewrite //=.\n  iIntros (Σ hPre σ g ->). simpl.\n  rewrite /kvs_uninit_auth/kvs_uninit_frag/kvs_frag/kvs_auth.\n  iMod (own_alloc (Cinl (1%Qp, to_agree UnInit') : openR)) as (γ1) \"H\".\n  { repeat econstructor => //=. }\n  iMod (gen_heap_name_strong_init ∅) as (names) \"(Hctx&Hpts)\".\n  iFrame. iModIntro.\n  iExists {| kvs_names_open := γ1; kvs_names_state := names |}.\n  iPoseProof (openR_frac_split γ1 (1/2) (1/2) (to_agree UnInit')) as \"HOpen\".\n  iEval (rewrite -Qp.half_half) in \"H\".\n  iEval (rewrite -frac_op) in \"H\".\n  iDestruct \"HOpen\" as \"[H1 H2]\".\n  iDestruct (\"H1\" with \"H\") as \"[H1' H2']\".\n  iSplitR \"H1'\"; auto.\n  iSplitL \"H2'\"; auto.\nQed.\n\nNext Obligation. (* restart, crashed to new ffi_state, Hold = old ffiGS, ffi_update plugs in new names *)\n  iIntros (Σ σ σ' g Hcrash Hold) \"Hinterp _\".\n  inversion Hcrash; subst.\n  monad_inv. inversion H. subst. inversion H1. subst.\n  destruct x; monad_inv.\n  - inversion Hcrash. subst. inversion H1. subst. inversion H3. subst.\n    inversion H2. subst. inversion H4. subst.\n    (* XXX: monad_inv should handle *)\n    iMod (own_alloc (Cinl (1%Qp, to_agree UnInit') : openR)) as (γ1) \"H\".\n    (*γ1 is new name, plug into new config name *)\n    { repeat econstructor => //=. }\n    iExists {| kvs_names_open := γ1; kvs_names_state := kvs_names_state (kvs_get_names _) |}.\n    iDestruct \"Hinterp\" as \"(?&?)\". rewrite //=/kvs_restart//=.\n    iFrame. rewrite left_id comm -assoc. iSplitL \"\"; first eauto.\n    * destruct kvsG_state_inG; simpl.\n      unfold gen_heapG_update; simpl.\n      unfold gen_heapG_get_names; simpl.\n      auto.\n    * rewrite /kvs_uninit_auth/kvs_uninit_frag/kvs_frag/kvs_auth.\n    iModIntro. by rewrite -own_op -Cinl_op -pair_op frac_op Qp.half_half agree_idemp.\n  - inversion Hcrash. subst. inversion H1. subst. inversion H3. subst.\n    inversion H2. subst. inversion H4. subst.\n    (* XXX: monad_inv should handle *)\n    iMod (own_alloc (Cinl (1%Qp, to_agree Closed') : openR)) as (γ1) \"H\".\n    { repeat econstructor => //=. }\n    iExists {| kvs_names_open := γ1; kvs_names_state := kvs_names_state (kvs_get_names _) |}.\n    iDestruct \"Hinterp\" as \"(?&?)\". rewrite //=/kvs_restart//=.\n    iFrame. rewrite left_id comm -assoc. iSplitL \"\"; first eauto.\n   * destruct kvsG_state_inG; simpl.\n      unfold gen_heapG_update; simpl.\n      unfold gen_heapG_get_names; simpl.\n      auto.\n  *\n    rewrite /kvs_uninit_auth/kvs_uninit_frag/kvs_frag/kvs_auth.\n    iModIntro. by rewrite -own_op -Cinl_op -pair_op frac_op Qp.half_half agree_idemp.\n  - inversion Hcrash. subst. inversion H1. subst. inversion H3. subst.\n    inversion H2. subst. inversion H4. subst.\n    (* XXX: monad_inv should handle *)\n    iMod (own_alloc (Cinl (1%Qp, to_agree Closed') : openR)) as (γ1) \"H\".\n    { repeat econstructor => //=. }\n    iExists {| kvs_names_open := γ1; kvs_names_state := kvs_names_state (kvs_get_names _) |}.\n    iDestruct \"Hinterp\" as \"(?&?)\". rewrite //=/kvs_restart//=.\n    iFrame. rewrite left_id comm -assoc. iSplitL \"\"; first eauto.\n   * destruct kvsG_state_inG; simpl.\n      unfold gen_heapG_update; simpl.\n      unfold gen_heapG_get_names; simpl.\n      auto.\n   *\n    rewrite /kvs_uninit_auth/kvs_uninit_frag/kvs_frag/kvs_auth.\n    iModIntro. by rewrite -own_op -Cinl_op -pair_op frac_op Qp.half_half agree_idemp.\nQed.\n\nFrom Perennial.program_proof Require Import proof_prelude.\nFrom Perennial.goose_lang Require Import refinement_adequacy.\nSection spec.\n\nInstance kvs_spec_ext : spec_ffi_op := {| spec_ffi_op_field := kvs_op |}.\nInstance kvs_spec_ffi_model : spec_ffi_model := {| spec_ffi_model_field := kvs_model |}.\nInstance kvs_spec_ext_semantics : spec_ext_semantics (kvs_spec_ext) (kvs_spec_ffi_model) :=\n  {| spec_ext_semantics_field := kvs_semantics |}.\nInstance kvs_spec_ffi_interp : spec_ffi_interp kvs_spec_ffi_model :=\n  {| spec_ffi_interp_field := kvs_interp |}.\nInstance kvs_spec_ty : ext_types (spec_ffi_op_field) := kvs_ty.\nInstance kvs_spec_interp_adequacy : spec_ffi_interp_adequacy (spec_ffi := kvs_spec_ffi_interp) :=\n  {| spec_ffi_interp_adequacy_field := kvs_interp_adequacy |}.\n\nContext `{invGS Σ}.\nContext `{crashGS Σ}.\nContext `{!refinement_heapG Σ}.\n\nExisting Instance spec_ffi_interp_field.\nExisting Instance spec_ext_semantics_field.\nExisting Instance spec_ffi_op_field.\nExisting Instance spec_ffi_model_field.\n\nImplicit Types K: spec_lang.(language.expr) → spec_lang.(language.expr).\nInstance kvsG0 : kvsG Σ := refinement_spec_ffiG.\n\n  Ltac inv_head_step :=\n    repeat match goal with\n        | _ => progress simplify_map_eq/= (* simplify memory stuff *)\n        | H : to_val _ = Some _ |- _ => apply of_to_val in H\n        | H : head_step ?e _ _ _ _ _ _ _ |- _ =>\n          try (is_var e; fail 1); (* inversion yields many goals if [e] is a variable\n     and can thus better be avoided. *)\n          inversion H; subst; clear H\n        | H : ffi_step _ _ _ _ _ |- _ =>\n          inversion H; subst; clear H\n        | [ H1: context[ match world ?σ with | _ => _ end ], Heq: world ?σ = _ |- _ ] =>\n          rewrite Heq in H1\n        end.\n\nLemma ghost_step_init_stuck E j K {HCTX: LanguageCtx K} σ g:\n  nclose sN_inv ⊆ E →\n  (σ.(@world _ kvs_spec_ffi_model.(@spec_ffi_model_field)) ≠ UnInit) →\n  j ⤇ K (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) InitOp #()) -∗\n  source_ctx (CS := spec_crash_lang) -∗\n  source_state σ g -∗\n  |NC={E}=> False.\nProof.\n  iIntros (??) \"Hj Hctx H\".\n  iMod (ghost_step_stuck with \"Hj Hctx H\") as \"[]\".\n  { eapply stuck_ExternalOp; first (by eauto).\n    apply head_irreducible_not_atomically; [ by inversion 1 | ].\n    intros ????? Hstep.\n    repeat (inv_head_step; simpl in *; repeat monad_inv).\n    destruct (σ.(world)); try congruence;\n    repeat (inv_head_step; simpl in *; repeat monad_inv).\n  }\n  { solve_ndisj. }\nQed.\n\nLemma ghost_step_open_stuck E j K {HCTX: LanguageCtx K} σ g:\n  nclose sN_inv ⊆ E →\n  (∀ vs, σ.(@world _ kvs_spec_ffi_model.(@spec_ffi_model_field)) ≠ Closed vs) →\n  j ⤇ K (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) OpenOp #()) -∗\n  source_ctx (CS := spec_crash_lang) -∗\n  source_state σ g -∗\n  |NC={E}=> False.\nProof.\n  iIntros (??) \"Hj Hctx H\".\n  iMod (ghost_step_stuck with \"Hj Hctx H\") as \"[]\".\n  { eapply stuck_ExternalOp; first (by eauto).\n    apply head_irreducible_not_atomically; [ by inversion 1 | ].\n    intros ??????.\n    repeat (inv_head_step; simpl in *; repeat monad_inv).\n    destruct (σ.(world)); try congruence;\n    repeat (inv_head_step; simpl in *; repeat monad_inv); eauto.\n    eapply H2; eauto.\n  }\n  { solve_ndisj. }\nQed.\n\nLemma kvs_closed_init_false E j K {HCTX: LanguageCtx K}:\n  nclose sN ⊆ E →\n  spec_ctx -∗\n  kvs_closed_frag -∗\n  j ⤇ K (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) InitOp #()) -∗ |NC={E}=>\n  False.\nProof.\n  iIntros (?) \"(#Hctx&#Hstate) Hclosed_frag Hj\".\n  iInv \"Hstate\" as (σ g) \"(>H&Hinterp)\" \"Hclo\".\n  iDestruct \"Hinterp\" as \"(>Hσ&>Hffi&Hrest)\".\n  iDestruct (kvs_ctx_unify_closed' with \"[$] [$]\") as %Heq; subst.\n  iMod (ghost_step_init_stuck with \"[$] [$] [$]\") as \"[]\".\n  { solve_ndisj. }\n  destruct Heq; subst; auto. congruence.\nQed.\n\nLemma kvs_opened_init_false l E j K {HCTX: LanguageCtx K}:\n  nclose sN ⊆ E →\n  spec_ctx -∗\n  kvs_open l -∗\n  j ⤇ K (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) InitOp #()) -∗ |NC={E}=>\n  False.\nProof.\n  iIntros (?) \"(#Hctx&#Hstate) Hopened Hj\".\n  iInv \"Hstate\" as (σ g) \"(>H&Hinterp)\" \"Hclo\".\n  iDestruct \"Hinterp\" as \"(>Hσ&>Hffi&Hrest)\".\n  iDestruct (kvs_ctx_unify_opened with \"[$] [$]\") as %Heq; subst.\n  iMod (ghost_step_init_stuck with \"[$] [$] [$]\") as \"[]\".\n  { solve_ndisj. }\n  { destruct Heq as (?&Heq). by rewrite Heq. }\nQed.\n\nLemma kvs_init_init_false E j K {HCTX: LanguageCtx K} j' K' {HCTX': LanguageCtx K'}:\n  nclose sN ⊆ E →\n  spec_ctx -∗\n  j ⤇ K (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) InitOp #()) -∗\n  j' ⤇ K' (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) InitOp #()) -∗ |NC={E}=>\n  False.\nProof.\n  iIntros (?) \"(#Hctx&#Hstate) Hj Hj'\".\n  iInv \"Hstate\" as (σ g) \"(>H&Hinterp)\" \"Hclo\".\n  iDestruct \"Hinterp\" as \"(>Hσ&>Hffi&Hrest)\".\n  iEval (simpl) in \"Hffi\".\n  destruct σ.(world) eqn:Heq; rewrite Heq; try (iDestruct \"Hffi\" as %[]).\n  - iMod (ghost_step_lifting with \"Hj Hctx H\") as \"(Hj&H&_)\". (* step one thread *)\n    { apply head_prim_step. simpl. constructor 1. econstructor.\n      * eexists _ (fresh_locs (dom σ.(heap))); repeat econstructor.\n        ** apply fresh_locs_non_null; lia.\n        ** hnf; intros. apply (not_elem_of_dom (D := gset loc)). by apply fresh_locs_fresh.\n        ** econstructor.\n        ** simpl. rewrite Heq. repeat econstructor.\n      * repeat econstructor.\n    }\n    { solve_ndisj. }\n    iMod (ghost_step_init_stuck with \"Hj' [$] [$]\") as \"[]\".\n    { solve_ndisj. }\n    { simpl. congruence. }\n  - iMod (ghost_step_init_stuck with \"Hj' [$] [$]\") as \"[]\".\n    { solve_ndisj. }\n    { congruence. }\n  - iMod (ghost_step_init_stuck with \"Hj' [$] [$]\") as \"[]\".\n    { solve_ndisj. }\n    { congruence. }\nQed.\n\nLemma kvs_init_open_false E j K {HCTX: LanguageCtx K} j' K' {HCTX': LanguageCtx K'}:\n  nclose sN ⊆ E →\n  spec_ctx -∗\n  j ⤇ K (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) InitOp #()) -∗\n  j' ⤇ K' (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) OpenOp #()) -∗ |NC={E}=>\n  False.\nProof.\n  iIntros (?) \"(#Hctx&#Hstate) Hj Hj'\".\n  iInv \"Hstate\" as (σ g) \"(>H&Hinterp)\" \"Hclo\".\n  iDestruct \"Hinterp\" as \"(>Hσ&>Hffi&Hrest)\".\n  iEval (simpl) in \"Hffi\".\n  destruct σ.(world) eqn:Heq; rewrite Heq; try (iDestruct \"Hffi\" as %[]).\n  - iMod (ghost_step_stuck with \"Hj' Hctx H\") as \"[]\".\n    { eapply stuck_ExternalOp; first (by eauto).\n      apply head_irreducible_not_atomically; [ by inversion 1 | ].\n      intros ??????. by repeat (inv_head_step; simpl in *; repeat monad_inv).\n    }\n    { solve_ndisj. }\n  - iMod (ghost_step_init_stuck with \"Hj [$] [$]\") as \"[]\".\n    { solve_ndisj. }\n    { congruence. }\n  - iMod (ghost_step_init_stuck with \"Hj [$] [$]\") as \"[]\".\n    { solve_ndisj. }\n    { congruence. }\nQed.\n\nLemma ghost_step_kvs_init E j K {HCTX: LanguageCtx K}:\n  nclose sN ⊆ E →\n  spec_ctx -∗\n  kvs_uninit_frag -∗\n  j ⤇ K (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) InitOp #())\n  -∗ |NC={E}=>\n  ∃ (l: loc), j ⤇ K (#l)%V ∗ kvs_open l.\nProof.\n  iIntros (?) \"(#Hctx&#Hstate) Hvals Hj\".\n  iInv \"Hstate\" as (σ g) \"(>H&Hinterp)\" \"Hclo\".\n  iDestruct \"Hinterp\" as \"(>Hσ&>Hffi&Hrest)\".\n  iDestruct (kvs_ctx_unify_uninit with \"[$] [$]\") as %Heq.\n  iMod (ghost_step_lifting with \"Hj Hctx H\") as \"(Hj&H&_)\".\n  { apply head_prim_step. simpl. constructor 1. econstructor.\n    * eexists _ (fresh_locs (dom σ.(heap))); repeat econstructor.\n      ** apply fresh_locs_non_null; lia.\n      ** hnf; intros. apply (not_elem_of_dom (D := gset loc)). by apply fresh_locs_fresh.\n      ** econstructor.\n      ** simpl. rewrite Heq. repeat econstructor.\n    * repeat econstructor.\n  }\n  { solve_ndisj. }\n  simpl. rewrite Heq.\n  iDestruct \"Hffi\" as \"(Huninit_auth&Hvals_auth)\".\n  iMod (kvs_uninit_token_open ((fresh_locs (dom σ.(heap)))) with \"[$] [$]\") as \"#Hopen\".\n  iMod (na_heap_alloc _ σ.(heap) (fresh_locs (dom σ.(heap))) (#()) (Reading O) with \"Hσ\") as \"(Hσ&?)\".\n  { rewrite //=. }\n  { apply (not_elem_of_dom (D := gset loc)). by apply fresh_locs_fresh. }\n  { apply (not_elem_of_dom (D := gset loc)). by apply fresh_locs_fresh. }\n  { auto. }\n  iMod (gen_heap_alloc_big ∅ kvs_init_s with \"Hvals_auth\") as \"Hgh\".\n  { apply map_disjoint_empty_r. }\n  { iMod (\"Hclo\" with \"[Hσ H Hrest Hgh]\") as \"_\".\n    - iNext. iExists _, _. iFrame \"H\".  iFrame. iFrame \"Hopen\".\n      iDestruct \"Hgh\" as \"[Hgh Hmap]\". simpl in *.\n      rewrite right_id; auto. rewrite fresh_alloc_equiv_null_non_alloc; iFrame.\n    - iModIntro. iExists _. iFrame \"Hopen\". iFrame.\n  }\nQed.\n\nLemma kvs_uninit_open_false E j K {HCTX: LanguageCtx K}:\n  nclose sN ⊆ E →\n  spec_ctx -∗\n  kvs_uninit_frag -∗\n  j ⤇ K (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) OpenOp #()) -∗ |NC={E}=>\n  False.\nProof.\n  iIntros (?) \"(#Hctx&#Hstate) Hclosed_frag Hj\".\n  iInv \"Hstate\" as (σ g) \"(>H&Hinterp)\" \"Hclo\".\n  iDestruct \"Hinterp\" as \"(>Hσ&>Hffi&Hrest)\".\n  iDestruct (kvs_ctx_unify_uninit with \"[$] [$]\") as %Heq; subst.\n  iMod (ghost_step_open_stuck with \"[$] [$] [$]\") as \"[]\".\n  { solve_ndisj. }\n  { congruence. }\nQed.\n\nLemma kvs_opened_open_false l E j K {HCTX: LanguageCtx K}:\n  nclose sN ⊆ E →\n  spec_ctx -∗\n  kvs_open l -∗\n  j ⤇ K (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) OpenOp #()) -∗ |NC={E}=>\n  False.\nProof.\n  iIntros (?) \"(#Hctx&#Hstate) Hopened Hj\".\n  iInv \"Hstate\" as (σ g) \"(>H&Hinterp)\" \"Hclo\".\n  iDestruct \"Hinterp\" as \"(>Hσ&>Hffi&Hrest)\".\n  simpl.\n  iDestruct (kvs_ctx_unify_opened with \"[$] [$]\") as %Heq; subst.\n  iMod (ghost_step_open_stuck with \"[$] [$] [$]\") as \"[]\".\n  { solve_ndisj. }\n  { destruct Heq as (?&Heq). by rewrite Heq. }\nQed.\n\nLemma kvs_open_open_false E j K {HCTX: LanguageCtx K} j' K' {HCTX': LanguageCtx K'}:\n  nclose sN ⊆ E →\n  spec_ctx -∗\n  j ⤇ K (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) OpenOp #()) -∗\n  j' ⤇ K' (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) OpenOp #()) -∗ |NC={E}=>\n  False.\nProof.\n  iIntros (?) \"(#Hctx&#Hstate) Hj Hj'\".\n  iInv \"Hstate\" as (σ g) \"(>H&Hinterp)\" \"Hclo\".\n  iDestruct \"Hinterp\" as \"(>Hσ&>Hffi&Hrest)\".\n  iEval (simpl) in \"Hffi\".\n  destruct σ.(world) eqn:Heq; rewrite Heq; try (iDestruct \"Hffi\" as %[]).\n  - iMod (ghost_step_open_stuck with \"Hj' [$] [$]\") as \"[]\".\n    { solve_ndisj. }\n    { congruence. }\n  - iMod (ghost_step_lifting with \"Hj Hctx H\") as \"(Hj&H&_)\".\n    { apply head_prim_step. simpl. constructor 1. econstructor.\n      * eexists _ (fresh_locs (dom σ.(heap))); repeat econstructor.\n        ** apply fresh_locs_non_null; lia.\n        ** hnf; intros. apply (not_elem_of_dom (D := gset loc)). by apply fresh_locs_fresh.\n        ** econstructor.\n        ** simpl. rewrite Heq. repeat econstructor.\n      * repeat econstructor.\n    }\n    { solve_ndisj. }\n    iMod (ghost_step_open_stuck with \"Hj' [$] [$]\") as \"[]\".\n    { solve_ndisj. }\n    { simpl. congruence. }\n  - iMod (ghost_step_open_stuck with \"Hj' [$] [$]\") as \"[]\".\n    { solve_ndisj. }\n    { congruence. }\nQed.\n\nLemma ghost_step_kvs_open E j K {HCTX: LanguageCtx K}:\n  nclose sN ⊆ E →\n  spec_ctx -∗\n  kvs_closed_frag -∗\n  j ⤇ K (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) OpenOp #())\n  -∗ |NC={E}=>\n  ∃ (l: loc), j ⤇ K #l%V ∗ kvs_open l.\nProof.\n  iIntros (?) \"(#Hctx&#Hstate) Huninit_frag Hj\".\n  iInv \"Hstate\" as (σ g) \"(>H&Hinterp)\" \"Hclo\".\n  iDestruct \"Hinterp\" as \"(>Hσ&>Hffi&Hrest)\".\n  iDestruct (kvs_ctx_unify_closed' with \"[$] [$]\") as %Heq.\n  destruct Heq as [s Heq].\n  iMod (ghost_step_lifting with \"Hj Hctx H\") as \"(Hj&H&_)\".\n  { apply head_prim_step. simpl. constructor 1. econstructor.\n    * eexists _ (fresh_locs (dom σ.(heap))); repeat econstructor.\n      ** apply fresh_locs_non_null; lia.\n      ** hnf; intros. apply (not_elem_of_dom (D := gset loc)). by apply fresh_locs_fresh.\n      ** econstructor.\n      ** simpl. rewrite Heq. repeat econstructor.\n    * repeat econstructor.\n  }\n  { solve_ndisj. }\n  simpl. rewrite Heq.\n  iDestruct \"Hffi\" as \"(Huninit_auth&Hvals_auth)\".\n  iMod (kvs_closed_token_open ((fresh_locs (dom σ.(heap)))) with \"[$] [$]\") as \"#Hopen\".\n  iMod (na_heap_alloc _ σ.(heap) (fresh_locs (dom σ.(heap))) (#()) (Reading O) with \"Hσ\") as \"(Hσ&?)\".\n  { rewrite //=. }\n  { apply (not_elem_of_dom (D := gset loc)). by apply fresh_locs_fresh. }\n  { apply (not_elem_of_dom (D := gset loc)). by apply fresh_locs_fresh. }\n  { auto. }\n  iMod (\"Hclo\" with \"[Hσ Hvals_auth H Hrest]\") as \"_\".\n  { iNext. iExists _, _. iFrame \"H\".  iFrame. iFrame \"Hopen\". rewrite fresh_alloc_equiv_null_non_alloc. iFrame. }\n  iModIntro. iExists _. iFrame \"Hopen\". iFrame.\nQed.\n\n(* XXX TODO how to return block?\nLemma ghost_step_kvs_get E j K {HCTX: LanguageCtx K} l k v :\n  nclose sN ⊆ E →\n  spec_ctx -∗\n  kvs_open l -∗\n  j ⤇ K (ExternalOp (ext := @spec_ffi_op_field kvs_spec_ext) GetOp #l #(LitInt k))\n  ={E}=∗\n  j ⤇ K #(LitLoc l)%V ∗ l ↦ v ∗ kvs_frag k v.\nProof.\n  iIntros (?) \"(#Hctx&#Hstate) #Hopen Hj\".\n  iInv \"Hstate\" as (σ) \"(>H&Hinterp)\" \"Hclo\".\n  iDestruct \"Hinterp\" as \"(>Hσ&>Hffi&Hrest)\".\n  iDestruct (kvs_ctx_unify_opened with \"[$] [$]\") as %Heq.\n  destruct Heq as (vs'&Heq).\n  iMod (ghost_step_lifting with \"Hj Hctx H\") as \"(Hj&H&_)\".\n  { apply head_prim_step. repeat (eauto || monad_simpl || rewrite Heq || econstructor). }\n  { solve_ndisj. }\n  simpl. rewrite Heq.\n  iDestruct \"Hffi\" as \"(Huninit_auth&Hvals_auth)\".\n  iMod (kvs_state_update [] with \"[$] [$]\") as \"(Hvals_auth&?)\".\n  iMod (\"Hclo\" with \"[Hσ Hvals_auth H Hrest]\") as \"_\".\n  { iNext. iExists _. iFrame \"H\". iFrame. iFrame \"Hopen\". }\n  iModIntro. iFrame.\nQed.*)\n\nEnd spec.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/goose_lang/ffi/kvs_ffi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2206453958135237}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n  Copyright 2018 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Export Quorum.\nRequire Export Process.\n\n\nSection PBFTheader.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc : @DTimeContext }.\n\n\n  (* ===============================================================\n     Parameters\n     =============================================================== *)\n\n  Class PBFTcontext :=\n    MkPBFTcontext\n      {\n        (* maximum number of requests that can be handled at the same time *)\n        PBFTmax_in_progress : nat;\n\n        (* This number has to be big enough so that replicas do not stall waiting\n         for a checkpoint to become stable *)\n        PBFTwater_mark_range : nat; (* this should be SeqNum type *)\n\n        (* usually half of the water-mark range *)\n        PBFTcheckpoint_period : nat;\n\n        PBFTdigest : Set;\n        PBFTdigestdeq : Deq PBFTdigest;\n\n        PBFTtoken    : Set;\n        PBFTtokendeq : Deq PBFTtoken;\n\n        PBFTsending_key   : Set;\n        PBFTreceiving_key : Set;\n\n        (* number of faults *)\n        F : nat;\n\n        (* ++++++++ Nodes (Replicas & Clients) ++++++++ *)\n        num_replicas := (3 * F) + 1;\n\n        (* We have 3F+1 replicas *)\n        Rep : Set;\n        rep_deq : Deq Rep;\n        reps2nat : Rep -> nat_n num_replicas;\n        reps_bij : bijective reps2nat;\n\n        num_clients : nat;\n\n        Client : Set;\n        client_deq : Deq Client;\n        clients2nat : Client -> nat_n num_clients;\n        clients_bij : bijective clients2nat;\n\n        (* ++++++++ replicated service ++++++++ *)\n        PBFToperation : Set;\n        PBFTopdeq : Deq PBFToperation;\n\n        PBFTresult : Set;\n        PBFTresdeq : Deq PBFTresult;\n\n        PBFTsm_state : Set;\n        PBFTsm_initial_state : PBFTsm_state;\n        PBFTsm_update : Client -> PBFTsm_state -> PBFToperation -> PBFTresult * PBFTsm_state;\n\n        PBFTtimer_delay : nat;\n      }.\n\n  Context { pbft_context : PBFTcontext }.\n\n\n\n  (* ===============================================================\n     No trusted component\n     =============================================================== *)\n\n  Global Instance PBFT_I_IOTrustedFun : IOTrustedFun := MkIOTrustedFun (fun _ => MkIOTrusted unit unit tt).\n\n\n\n  (* ===============================================================\n     Nodes\n     =============================================================== *)\n\n  Inductive PBFTnode :=\n  | PBFTreplica (n : Rep)\n  | PBFTclient (n : Client).\n\n  Definition node2rep (n : PBFTnode) : option Rep :=\n    match n with\n    | PBFTreplica n => Some n\n    | _ => None\n    end.\n\n  Definition node2client (n : PBFTnode) : option Client :=\n    match n with\n    |PBFTclient nn => Some nn\n    | _ => None\n    end.\n\n  Lemma PBFTnodeDeq : Deq PBFTnode.\n  Proof.\n    introv; destruct x as [r1|c1], y as [r2|c2].\n    - destruct (rep_deq r1 r2);[left|right]; subst; auto.\n      intro xx; inversion xx; subst; tcsp.\n    - right; intro xx; inversion xx; subst; tcsp.\n    - right; intro xx; inversion xx; subst; tcsp.\n    - destruct (client_deq c1 c2);[left|right]; subst; auto.\n      intro xx; inversion xx; subst; tcsp.\n  Defined.\n\n  Global Instance PBFT_I_Node : Node := MkNode PBFTnode PBFTnodeDeq.\n\n\n\n  (* ===============================================================\n     Quorum\n     =============================================================== *)\n\n  Lemma PBFTreplica_inj : injective PBFTreplica.\n  Proof.\n    introv h; ginv; auto.\n  Qed.\n\n  Definition node2replica (n : PBFTnode) : option Rep :=\n    match n with\n    | PBFTreplica r => Some r\n    | _ => None\n    end.\n\n  Lemma replica2node_cond :\n    forall n : Rep, node2replica (PBFTreplica n) = Some n.\n  Proof.\n    tcsp.\n  Qed.\n\n  Lemma node2replica_cond :\n    forall (n : Rep) (m : name), node2replica m = Some n -> PBFTreplica n = m.\n  Proof.\n    introv h; destruct m; simpl in *; ginv; auto.\n  Qed.\n\n  Global Instance PBFT_I_Quorum : Quorum_context :=\n    MkQuorumContext\n      Rep\n      num_replicas\n      rep_deq\n      reps2nat\n      reps_bij\n      PBFTreplica\n      node2replica\n      replica2node_cond\n      node2replica_cond\n      PBFTreplica_inj.\n\n  (* can we have something like this? *)\n  Definition rep2node := Rep -> node_type.\n\n\n  (* ===============================================================\n     More about Nodes\n     =============================================================== *)\n\n  (* 0 is less than 2*F+1 *)\n  Definition nat_n_2Fp1_0 : nat_n num_replicas.\n  Proof.\n    exists 0.\n    apply leb_correct.\n    unfold num_replicas.\n    omega.\n  Defined.\n\n  Definition replica0 : Rep := bij_inv reps_bij nat_n_2Fp1_0.\n\n  (*Eval simpl in (name_dec (PBFTreplica replica0) (PBFTreplica replica0)).*)\n\n  (* We'll return the node as given by our bijection if n < num_nodes,\n     otherwise we return a default value (replica0)\n   *)\n  Definition nat2rep (n : nat) : Rep.\n  Proof.\n    destruct reps_bij as [f a b].\n    destruct (lt_dec n num_replicas) as [d|d].\n    - exact (f (mk_nat_n d)). (* here we now that n < num_replicas so we can use our bijection *)\n    - exact replica0. (* here num_replicas <= n, so we return a default value: replica0 *)\n  Defined.\n\n\n  Definition reps : list Rep := nodes.\n(*    mapin\n      (seq 0 num_replicas)\n      (fun n i => bij_inv reps_bij (mk_nat_n (seq_0_lt i))).*)\n\n  Definition nreps : list name := map PBFTreplica reps.\n\n  Lemma reps_prop : forall (x : Rep), In x reps.\n  Proof.\n    exact nodes_prop.\n  Qed.\n\n  Definition clients : list Client :=\n    mapin\n      (seq 0 num_clients)\n      (fun n i => bij_inv clients_bij (mk_nat_n (seq_0_lt i))).\n\n  Definition nclients : list name := map PBFTclient clients.\n\n  Lemma clients_prop : forall (x : Client), In x clients.\n  Proof.\n    introv.\n    unfold clients.\n    apply in_mapin.\n\n    remember (clients2nat x) as nx.\n    destruct nx as [nx condnx].\n\n    pose proof (leb_complete _ _ condnx) as c.\n\n    assert (In nx (seq O num_clients)) as i.\n    { apply in_seq; omega. }\n\n    exists nx i; simpl.\n\n    unfold mk_nat_n.\n    unfold bij_inv.\n    destruct clients_bij.\n    pose proof (bij_id1 x) as h.\n    rewrite <- Heqnx in h; subst; simpl.\n\n    f_equal; f_equal.\n    apply UIP_dec; apply bool_dec.\n  Qed.\n\n  (*\n  (* @Ivana: in case we ave clients coming and leaving, I am not sure if this is going to be convenient *)\n  Definition clients : list Client :=\n    mapin\n      (seq 0 num_clients)\n      (fun n i => bij_inv client_bij (mk_nat_n (seq_0_lt i))).\n\n    Definition nclients : list name := map PBFTclient clients.\n\n    Lemma client_prop : forall (x : Client), In x clients.\n    Proof.\n      introv.\n      unfold clients.\n      apply in_mapin.\n\n      remember (client2nat x) as nx.\n      destruct nx as [nx condnx].\n\n      pose proof (leb_complete _ _ condnx) as c.\n\n      assert (In nx (seq O num_clients)) as i.\n      { apply in_seq; omega. }\n\n      exists nx i; simpl.\n\n      unfold mk_nat_n.\n      unfold bij_inv.\n      destruct client_bij.\n      pose proof (bij_id3 x) as h.\n      rewrite <- Heqnx in h; subst; simpl.\n\n      f_equal; f_equal.\n      apply UIP_dec; apply bool_dec.\n    Qed.\n   *)\n\n\n\n  (* ===============================================================\n     Views\n     =============================================================== *)\n\n  Inductive View :=\n  | view (n : nat).\n\n  Definition view2nat (v : View) : nat :=\n    match v with\n    | view n => n\n    end.\n  Coercion view2nat : View >-> nat.\n\n  Definition next_view (v : View): View := view (S v).\n\n  Definition pred_view (v : View): View := view (pred v).\n\n  Lemma ViewDeq : Deq View.\n  Proof.\n    introv; destruct x, y; prove_dec.\n    destruct (deq_nat n n0); prove_dec.\n  Defined.\n\n  Definition initial_view := view 0.\n\n\n  Definition ViewLe (vn1 vn2 : View) : bool :=\n    view2nat vn1 <=? view2nat vn2.\n\n  Definition ViewLt (vn1 vn2 : View) : bool :=\n    view2nat vn1 <? view2nat vn2.\n\n  Definition max_view (v1 v2 : View) : View :=\n    if ViewLe v1 v2 then v2 else v1.\n\n\n  (* ===============================================================\n     Timestamps\n     =============================================================== *)\n\n  Inductive Timestamp :=\n  | time_stamp (q : nat).\n  Coercion time_stamp : nat >-> Timestamp.\n\n  Definition timestamp2nat (t : Timestamp) : nat :=\n    match t with\n    | time_stamp n => n\n    end.\n  Coercion timestamp2nat : Timestamp >-> nat.\n\n  Definition timestamp0 := time_stamp 0.\n\n\n  (* ===============================================================\n     Sequence numbers\n     =============================================================== *)\n\n  Inductive SeqNum :=\n  | seq_num (n : nat).\n  Coercion seq_num : nat >-> SeqNum.\n\n  Definition seqnum2nat (s : SeqNum) : nat :=\n    match s with\n    | seq_num n => n\n    end.\n  Coercion seqnum2nat : SeqNum >-> nat.\n\n  Definition SeqNumLe (sn1 sn2 : SeqNum) : bool :=\n    seqnum2nat sn1 <=? seqnum2nat sn2.\n\n  Definition SeqNumLt (sn1 sn2 : SeqNum) : bool :=\n    seqnum2nat sn1 <? seqnum2nat sn2.\n\n  Definition next_seq (n : SeqNum): SeqNum := seq_num (S n).\n\n  Lemma SeqNumDeq : Deq SeqNum.\n  Proof.\n    introv; destruct x, y; prove_dec.\n    destruct (deq_nat n n0); prove_dec.\n  Defined.\n\n  Definition initial_sequence_number : SeqNum := seq_num 0.\n\n  Definition min_seq_num (s1 s2 : SeqNum) : SeqNum :=\n    if SeqNumLe s1 s2 then s1 else s2.\n\n  Definition max_seq_num (s1 s2 : SeqNum) : SeqNum :=\n    if SeqNumLe s1 s2 then s2 else s1.\n\n\n\n  (* ===============================================================\n     Primary\n     =============================================================== *)\n\n  (* @Ivnote: mod is already part of Coq standard library, and it's used as follows: a mod b *)\n  (* primary p = v mod R, where v is number of current view and |R| is 2f+1 *)\n  Definition PBFTprimary_nat (v : View) : nat := v mod num_replicas. (* here we should return replica, not nat!!!*)\n\n  Definition PBFTprimary (v : View) : Rep := nat2rep (PBFTprimary_nat v).\n\n  Definition is_primary (v : View) (r : Rep) : bool :=\n    if rep_deq r (PBFTprimary v) then true else false.\n\n\n\n  (* ===============================================================\n     Authentication\n     =============================================================== *)\n\n  Definition PBFTtokens := list PBFTtoken.\n\n  Global Instance PBFT_I_AuthTok : AuthTok :=\n    MkAuthTok\n      PBFTtoken\n      PBFTtokendeq.\n\n\n\n  (* ===============================================================\n     Bare messages\n     =============================================================== *)\n\n  Inductive Bare_Request : Set :=\n  | null_req\n  | bare_req\n      (o : PBFToperation)\n      (t : Timestamp)\n      (c : Client).\n\n  Inductive Bare_Reply :=\n  | bare_reply\n      (v : View)\n      (t : Timestamp)\n      (c : Client)\n      (i : Rep)\n      (r : PBFTresult).\n\n  Inductive Bare_Prepare :=\n  | bare_prepare\n      (v : View)\n      (s : SeqNum)\n      (d : PBFTdigest)\n      (i : Rep).\n\n  Inductive Bare_Commit :=\n  | bare_commit\n      (v : View)\n      (s : SeqNum)\n      (d : PBFTdigest)\n      (i : Rep).\n\n  Inductive Bare_Checkpoint :=\n  | bare_checkpoint\n      (v : View) (* see technical report and PhD thesis*)\n      (n : SeqNum)\n      (d : PBFTdigest)\n      (i : Rep).\n\n\n\n  (* ===============================================================\n     Authenticated messages\n     =============================================================== *)\n\n  Inductive Request :=\n  | req\n      (b : Bare_Request)\n      (a : Tokens).  (* [a] authenticate the client *)\n\n  Inductive Reply :=\n  | reply\n      (b : Bare_Reply)\n      (a : Tokens).  (* [a] authenticate the replica *)\n\n  Inductive Prepare :=\n  | prepare\n      (b : Bare_Prepare)\n      (a : Tokens).  (* [a] authenticate the replica (the leader here) *)\n\n  Inductive Commit :=\n  | commit\n      (b : Bare_Commit)\n      (a : Tokens).  (* [a] authenticate the replica *)\n\n  Inductive Checkpoint :=\n  | checkpoint\n      (b : Bare_Checkpoint)\n      (a : Tokens).  (* [a] authenticate the replica *)\n\n  Inductive Debug :=\n  | debug\n      (r : Rep)\n      (s : String.string).\n\n  Inductive CheckReady :=\n  | check_ready.\n\n  Inductive CheckStableChkPt :=\n  | check_stable_checkpoint.\n\n  Inductive StartTimer :=\n  | start_timer\n      (r : Bare_Request)\n      (v : View).\n\n  Inductive ExpiredTimer :=\n  | expired_timer\n      (r : Bare_Request)\n      (v : View).\n\n\n\n  (* ===============================================================\n     Messages depending on authenticated messages\n     =============================================================== *)\n\n  (* reconsider n, maybe it should have some type *)\n  Inductive Bare_Pre_prepare :=\n  | bare_pre_prepare\n      (v : View)\n      (s : SeqNum)\n      (d : list Request). (* this is a list because we buffer requests *)\n\n(*  Record Pre_prepare_data :=\n    MkPrePrepareData\n      {\n        ppd_bare : Bare_Pre_prepare;\n        ppd_toks : Tokens;  (* [a] authenticate the replica (the leader here) *)\n      }.\n*)\n\n  Inductive Pre_prepare :=\n  | pre_prepare\n      (b : Bare_Pre_prepare)\n      (a : Tokens).\n\n  Record PreparedInfo :=\n    MkPreparedInfo\n      {\n        prepared_info_pre_prepare : Pre_prepare;\n        prepared_info_digest      : PBFTdigest;\n        prepared_info_prepares    : list Prepare;\n      }.\n\n  Definition CheckpointCert := list Checkpoint.\n\n  Record LastReplyEntry :=\n    MkLastReplyEntry\n      {\n        lre_client    : Client;\n        lre_timestamp : Timestamp;    (* initially 0 *)\n        lre_reply     : option PBFTresult; (* None is the initial value *)\n      }.\n\n  Definition LastReplyState := list LastReplyEntry.\n\n  (* This is meant to be the last stable checkpoint *)\n  Record StableChkPt :=\n    MkStableChkPt\n      {\n        si_state : PBFTsm_state;\n        si_lastr : LastReplyState;\n      }.\n\n  Inductive Bare_ViewChange :=\n  | bare_view_change\n      (v : View)\n      (n : SeqNum)\n      (* FIX: technical report has an extra field here: p.24 *)\n      (s : StableChkPt)\n      (C : CheckpointCert)\n      (P : list PreparedInfo)\n      (i : Rep).\n\n  Inductive ViewChange :=\n  | view_change\n      (v : Bare_ViewChange)\n      (a : Tokens).\n\n  Definition ViewChangeCert := list ViewChange.\n\n  Inductive Bare_NewView :=\n  | bare_new_view\n      (v : View)\n      (V : ViewChangeCert)\n      (* pre-prepare for which we have a request *)\n      (OP : list Pre_prepare)\n      (* pre-prepare for which we don't have a request *)\n      (NP : list Pre_prepare).\n\n  Inductive NewView :=\n  | new_view\n      (v : Bare_NewView)\n      (a : Tokens).\n\n  Record PBFTviewChangeEntry :=\n    MkViewChangeEntry\n      {\n        (* view number of the entry---all the view-change messages in the entry\n           are meant to be for this view *)\n        vce_view         : View;\n\n        (* view-change message created locally *)\n        vce_view_change  : option ViewChange;\n\n        (* list of view change messages received so far *)\n        vce_view_changes : list ViewChange;\n\n        (* new-view message sent in response to enough view-change messages *)\n        vce_new_view     : option NewView;\n      }.\n\n  Inductive CheckBCastNewView :=\n  | check_bcast_new_view (i : nat) (* position of the [PBFTviewChangeEntry] to check *).\n\n\n\n  (* ===============================================================\n     Bare message type\n     =============================================================== *)\n\n  Inductive PBFTBare_Msg : Set :=\n  | PBFTmsg_bare_request              (r : Bare_Request)\n  | PBFTmsg_bare_reply                (r : Bare_Reply)\n  | PBFTmsg_bare_pre_prepare          (p : Bare_Pre_prepare)\n  | PBFTmsg_bare_prepare              (p : Bare_Prepare)\n  | PBFTmsg_bare_commit               (c : Bare_Commit)\n  | PBFTmsg_bare_checkpoint           (c : Bare_Checkpoint)\n\n  (* This is to keep on checking whether there are more requests that are\n     ready to be executed *)\n  | PBFTmsg_bare_check_ready          (t : CheckReady)\n\n  (* This is to check whether it's time to broadcast a new-view message *)\n  | PBFTmsg_bare_check_bcast_new_view (e : CheckBCastNewView)\n\n  (* These are sent to the component in charge of handling timers to start a new\n     timer in case of a new request *)\n  | PBFTmsg_bare_start_timer          (t : StartTimer)\n\n  (* These are received from the component in charge of handling timers when\n     timers have expired *)\n  | PBFTmsg_bare_expired_timer        (t : ExpiredTimer)\n\n  | PBFTmsg_bare_view_change          (v : Bare_ViewChange)\n\n  | PBFTmsg_bare_new_view             (v : Bare_NewView).\n\n\n\n  (* ===============================================================\n     Crypto\n     =============================================================== *)\n\n  Global Instance PBFT_I_Data : Data := MkData PBFTBare_Msg.\n\n  Global Instance PBFT_I_Key : Key := MkKey PBFTsending_key PBFTreceiving_key.\n\n  Class PBFTauth :=\n    MkPBFTauth\n      {\n        PBFTcreate : data -> sending_keys -> PBFTtokens;\n        PBFTverify : data -> name -> receiving_key -> PBFTtoken -> bool\n      }.\n  Context { pbft_auth : PBFTauth }.\n\n  Global Instance PBFT_I_AuthFun : AuthFun :=\n    MkAuthFun\n      PBFTcreate\n      PBFTverify.\n\n  Class PBFTinitial_keys :=\n    MkPBFTinitial_keys {\n        initial_keys : key_map;\n      }.\n\n  Context { pbft_initial_keys : PBFTinitial_keys }.\n\n\n\n  (* Should we create a Coercion for each of following statements??? *)\n\n  (* ============ extract sender ==============*)\n\n  Definition bare_request2sender (r : Bare_Request) : option Client :=\n    match r with\n    | null_req => None\n    | bare_req o t c => Some c\n    end.\n\n  Definition request2sender (r : Request) : option Client :=\n    match r with\n    | req b _ => bare_request2sender b\n    end.\n\n  Definition bare_reply2sender (r : Bare_Reply) :  Rep :=\n    match r with\n    | bare_reply v t c i r => i\n    end.\n\n  Definition reply2sender (r : Reply) :  Rep :=\n    match r with\n    | reply b _ => bare_reply2sender b\n    end.\n\n  Definition bare_pre_prepare2sender (p : Bare_Pre_prepare) : Rep :=\n    match p with\n    | bare_pre_prepare v n d => PBFTprimary v\n    end.\n\n(*  Definition pre_prepare_data2sender (p : Pre_prepare_data) : Rep :=\n    match p with\n    | MkPrePrepareData b _ => bare_pre_prepare2sender b\n    end.*)\n\n  Definition pre_prepare2sender (p : Pre_prepare) : Rep :=\n    match p with\n    | pre_prepare b _ => bare_pre_prepare2sender b\n    end.\n\n  Definition bare_prepare2sender (p : Bare_Prepare) : Rep :=\n    match p with\n    | bare_prepare v n d i => i\n    end.\n\n  Definition prepare2sender (p : Prepare) : Rep :=\n    match p with\n    | prepare b _ => bare_prepare2sender b\n    end.\n\n  Definition bare_commit2sender (c : Bare_Commit) : Rep :=\n    match c with\n    | bare_commit v n d i => i\n    end.\n\n  Definition commit2sender (c : Commit) : Rep :=\n    match c with\n    | commit b _ => bare_commit2sender b\n    end.\n\n  Definition bare_checkpoint2sender (c : Bare_Checkpoint) : Rep :=\n    match c with\n    | bare_checkpoint v n d i => i\n    end.\n\n  Definition checkpoint2sender (c : Checkpoint) : Rep :=\n    match c with\n    | checkpoint b _ => bare_checkpoint2sender b\n    end.\n\n  Definition debug2sender (d : Debug) :  Rep :=\n    match d with\n    | debug s _ => s\n    end.\n\n  Definition bare_view_change2sender (v : Bare_ViewChange) :  Rep :=\n    match v with\n    | bare_view_change v n s C P i => i\n    end.\n\n  Definition view_change2sender (v : ViewChange) : Rep :=\n    match v with\n    | view_change bv _ => bare_view_change2sender bv\n    end.\n\n  Definition bare_new_view2sender (b : Bare_NewView) : Rep :=\n    match b with\n    | bare_new_view v V OP NP => PBFTprimary v\n    end.\n\n  Definition new_view2sender (v : NewView) : Rep :=\n    match v with\n    | new_view b _ => bare_new_view2sender b\n    end.\n\n  Definition prepared_info2senders (nfo : PreparedInfo) : list Rep :=\n    map prepare2sender (prepared_info_prepares nfo).\n\n  Definition prepared_info2pp_sender (nfo : PreparedInfo) : Rep :=\n    pre_prepare2sender (prepared_info_pre_prepare nfo).\n\n\n\n  (* ============ extract signature ==============*)\n\n  Definition request2sign (r : Request) : Tokens :=\n    match r with\n    | req _ a => a\n    end.\n\n  Definition reply2sign (r : Reply) : Tokens :=\n    match r with\n    | reply _ a => a\n    end.\n\n(*  Definition pre_prepare_data2sign (p : Pre_prepare_data) : Tokens :=\n    match p with\n    | MkPrePrepareData _ a => a\n    end.*)\n\n  Definition pre_prepare2sign (p : Pre_prepare) : Tokens :=\n    match p with\n    | pre_prepare _ a => a\n    end.\n\n  Definition prepare2sign (p : Prepare) : Tokens :=\n    match p with\n    | prepare _ a => a\n    end.\n\n  Definition commit2sign (c : Commit) : Tokens :=\n    match c with\n    | commit _ a => a\n    end.\n\n  Definition checkpoint2sign (c : Checkpoint) : Tokens :=\n    match c with\n    | checkpoint _ a => a\n    end.\n\n  (* ============  extract sequence number ============== *)\n\n  Definition bare_pre_prepare2seq (p : Bare_Pre_prepare) : SeqNum :=\n    match p with\n    | bare_pre_prepare v n d => n\n    end.\n\n(*  Definition pre_prepare_data2seq (p : Pre_prepare_data) : SeqNum :=\n    match p with\n    | MkPrePrepareData b _ => bare_pre_prepare2seq b\n    end.*)\n\n  Definition pre_prepare2seq (p : Pre_prepare) : SeqNum :=\n    match p with\n    | pre_prepare b _ => bare_pre_prepare2seq b\n    end.\n\n  Definition bare_prepare2seq (p : Bare_Prepare) : SeqNum :=\n    match p with\n    | bare_prepare v n d i => n\n    end.\n\n  Definition prepare2seq (p : Prepare) : SeqNum :=\n    match p with\n    | prepare b _ => bare_prepare2seq b\n    end.\n\n  Definition bare_commit2seq (c : Bare_Commit) : SeqNum :=\n    match c with\n    | bare_commit v n d i => n\n    end.\n\n  Definition commit2seq (c : Commit) : SeqNum :=\n    match c with\n    | commit b _ => bare_commit2seq b\n    end.\n\n  Definition bare_checkpoint2seq (c : Bare_Checkpoint) : SeqNum :=\n    match c with\n    | bare_checkpoint v n d i => n\n    end.\n\n  Definition checkpoint2seq (c : Checkpoint) : SeqNum :=\n    match c with\n    | checkpoint b _ => bare_checkpoint2seq b\n    end.\n\n  Definition bare_view_change2seq (bvc : Bare_ViewChange) : SeqNum :=\n    match bvc with\n    | bare_view_change v n s C P i => n\n    end.\n\n  Definition view_change2seq (vc : ViewChange) : SeqNum :=\n    match vc with\n    | view_change bvc _ => bare_view_change2seq bvc\n    end.\n\n  Definition prepared_info2seq (p : PreparedInfo) : SeqNum :=\n    pre_prepare2seq (prepared_info_pre_prepare p).\n\n\n  (* =========== extract operation =========== *)\n\n  Definition bare_request2operation (r : Bare_Request) : option PBFToperation :=\n    match r with\n    | null_req => None\n    | bare_req o t c => Some o\n    end.\n\n  Definition request2operation (r : Request) : option PBFToperation :=\n    match r with\n    | req b _ => bare_request2operation b\n    end.\n\n  (*\n  Definition pre_prepare2operation (pp : Pre_prepare) : PBFToperation :=\n    match pp with\n    | pre_prepare _ _ r => request2operation r\n    end.\n*)\n\n\n  (* =========== extract timestamp =========== *)\n\n  Definition bare_request2timestamp (r : Bare_Request) : Timestamp :=\n    match r with\n    | null_req => timestamp0\n    | bare_req o t c => t\n    end.\n\n  Definition request2timestamp (r : Request) : Timestamp :=\n    match r with\n    | req b _ => bare_request2timestamp b\n    end.\n\n  Definition bare_reply2timestamp (r : Bare_Reply) :=\n    match r with\n    | bare_reply v t c i r => t\n    end.\n\n  Definition reply2timestamp (r : Reply) :=\n    match r with\n    | reply b _ => bare_reply2timestamp b\n    end.\n\n\n  (* =========== extract receiver =========== *)\n\n  Definition bare_reply2client (r : Bare_Reply) : Client :=\n    match r with\n    | bare_reply v t c i r => c\n    end.\n\n  Definition reply2client (r : Reply) : Client :=\n    match r with\n    | reply b _ => bare_reply2client b\n    end.\n\n\n  (* =========== extract result =========== *)\n\n  Definition bare_reply2result (r : Bare_Reply) :=\n    match r with\n    | bare_reply v t c i r => r\n    end.\n\n  Definition reply2result (r : Reply) :=\n    match r with\n    | reply b _ => bare_reply2result b\n    end.\n\n\n  (* =========== extracts bare message =========== *)\n\n  Definition reply2bare (r : Reply) :  Bare_Reply :=\n    match r with\n    | reply b _ => b\n    end.\n\n  Definition request2bare (r : Request) :  Bare_Request :=\n    match r with\n    | req b _ => b\n    end.\n\n(*  Definition pre_prepare_data2bare (pp : Pre_prepare_data) : Bare_Pre_prepare :=\n    match pp with\n    | MkPrePrepareData bp _ => bp\n    end.*)\n\n  Definition pre_prepare2bare (pp : Pre_prepare) : Bare_Pre_prepare :=\n    match pp with\n    | pre_prepare bp _ => bp\n    end.\n\n  (* FIX: We cannot do these anymore because pre-prepare messages\n          contain requests and not digests*)\n\n(*  Definition bare_prepare2bare_pre_prepare (bp : Bare_Prepare) : Bare_Pre_prepare :=\n    match bp with\n    | bare_prepare v s d _ => bare_pre_prepare v s d\n    end.*)\n\n(*  Definition prepare2bare_pre_prepare (p : Prepare) : Bare_Pre_prepare :=\n    match p with\n    | prepare bp _ => bare_prepare2bare_pre_prepare bp\n    end.*)\n\n(*  Definition bare_commit2bare_pre_prepare (bc : Bare_Commit) : Bare_Pre_prepare :=\n    match bc with\n    | bare_commit v s d _ => bare_pre_prepare v s d\n    end.*)\n\n(*  Definition commit2bare_pre_prepare (c : Commit) : Bare_Pre_prepare :=\n    match c with\n    | commit bc _ => bare_commit2bare_pre_prepare bc\n    end.*)\n\n  Definition bare_pre_prepare2bare_prepare\n             (bpp : Bare_Pre_prepare)\n             (d   : PBFTdigest)\n             (r   : Rep) : Bare_Prepare :=\n    match bpp with\n    | bare_pre_prepare v s _ => bare_prepare v s d r\n    end.\n\n(*  Definition pre_prepare_data2bare_prepare (bp : Pre_prepare_data) (r : Rep) : Bare_Prepare :=\n    match bp with\n    | MkPrePrepareData b _ => bare_pre_prepare2bare_prepare b r\n    end.*)\n\n  Definition pre_prepare2bare_prepare\n             (p : Pre_prepare)\n             (d : PBFTdigest)\n             (r : Rep) : Bare_Prepare :=\n    match p with\n    | pre_prepare b _ => bare_pre_prepare2bare_prepare b d r\n    end.\n\n  Definition bare_prepare2bare_commit (slf : Rep) (bp : Bare_Prepare) : Bare_Commit :=\n    match bp with\n    | bare_prepare v s d i => bare_commit v s d slf\n    end.\n\n  Definition prepare2bare_commit (slf : Rep) (p : Prepare) : Bare_Commit :=\n    match p with\n    | prepare b a => bare_prepare2bare_commit slf b\n    end.\n\n  Definition bare_commit2bare_reply\n             (bc : Bare_Commit)\n             (t : Timestamp)\n             (c : Client)\n             (r : PBFTresult) : Bare_Reply :=\n    match bc with\n    | bare_commit v s d i=> bare_reply v t c i r\n    end.\n\n  Definition commit2bare_reply\n             (c : Commit)\n             (t : Timestamp)\n             (cl : Client)\n             (r : PBFTresult) : Bare_Reply :=\n    match c with\n    | commit b a => bare_commit2bare_reply b t cl r\n    end.\n\n  Definition bare_request2bare_reply\n             (br : Bare_Request)\n             (v  : View)\n             (i  : Rep)\n             (r  : PBFTresult) : option Bare_Reply :=\n    match br with\n    | null_req => None\n    | bare_req opr t c => Some (bare_reply v t c i r)\n    end.\n\n  Definition request2bare_reply\n             (req : Request)\n             (v   : View)\n             (i   : Rep)\n             (r   : PBFTresult) : option Bare_Reply :=\n    match req with\n    | req b _ => bare_request2bare_reply b v i r\n    end.\n\n  Definition bare_request2info (br : Bare_Request) : option (PBFToperation * Timestamp * Client) :=\n    match br with\n    | null_req => None\n    | bare_req opr t c => Some (opr, t, c)\n    end.\n\n  Definition request2info (req : Request) : option (PBFToperation * Timestamp * Client) :=\n    match req with\n    | req b _ => bare_request2info b\n    end.\n\n  Definition bare_pre_prepare2bare_commit\n             (slf : Rep)\n             (b   : Bare_Pre_prepare)\n             (d   : PBFTdigest) : Bare_Commit :=\n    match b with\n    | bare_pre_prepare v s _ => bare_commit v s d slf\n    end.\n\n(*  Definition pre_prepare_data2bare_commit (slf : Rep) (pp : Pre_prepare_data) : Bare_Commit :=\n    match pp with\n    | MkPrePrepareData bpp a => bare_pre_prepare2bare_commit slf bpp\n    end.*)\n\n  Definition pre_prepare2bare_commit\n             (slf : Rep)\n             (pp  : Pre_prepare)\n             (d   : PBFTdigest) : Bare_Commit :=\n    match pp with\n    | pre_prepare b _ => bare_pre_prepare2bare_commit slf b d\n    end.\n\n  Definition view_change2bare (vc : ViewChange) : Bare_ViewChange :=\n    match vc with\n    | view_change v _ => v\n    end.\n\n(*  Definition pre_prepare_data2bare_pre_prepare (p : Pre_prepare_data) : Bare_Pre_prepare :=\n    match p with\n    | MkPrePrepareData b _ => b\n    end.*)\n\n\n\n  (* =========== extract view ===============*)\n\n  Definition bare_reply2view (r : Bare_Reply) :=\n    match r with\n    | bare_reply v t c i r => v\n    end.\n\n  Definition reply2view (r : Reply) :=\n    match r with\n    | reply b _ => bare_reply2view b\n    end.\n\n  Definition bare_pre_prepare2view (p : Bare_Pre_prepare) :=\n    match p with\n    | bare_pre_prepare v n d =>  v\n    end.\n\n(*  Definition pre_prepare_data2view (p : Pre_prepare_data) :=\n    match p with\n    | MkPrePrepareData b _ =>  bare_pre_prepare2view b\n    end.*)\n\n  Definition pre_prepare2view (p : Pre_prepare) :=\n    match p with\n    | pre_prepare b _ => bare_pre_prepare2view b\n    end.\n\n  Definition bare_prepare2view (p : Bare_Prepare) :=\n    match p with\n    | bare_prepare v n d i => v\n    end.\n\n  Definition prepare2view (p : Prepare) :=\n    match p with\n    | prepare b _ => bare_prepare2view b\n    end.\n\n  Definition bare_commit2view (c : Bare_Commit) :=\n    match c with\n    | bare_commit v n d i => v\n    end.\n\n  Definition commit2view (c : Commit) :=\n    match c with\n    | commit b _ => bare_commit2view b\n    end.\n\n  Definition bare_checkpoint2view (c : Bare_Checkpoint) :=\n    match c with\n    | bare_checkpoint v n d i => v\n    end.\n\n  Definition checkpoint2view (c : Checkpoint) :=\n    match c with\n    | checkpoint b _ => bare_checkpoint2view b\n    end.\n\n  Definition bare_new_view2view (v : Bare_NewView) :=\n    match v with\n    | bare_new_view v V OP NP => v\n    end.\n\n  Definition new_view2view (v : NewView) :=\n    match v with\n    | new_view b _ => bare_new_view2view b\n    end.\n\n  Definition expired_timer2view (e : ExpiredTimer) :=\n    match e with\n    | expired_timer r v => v\n    end.\n\n  Definition bare_view_change2view (bvc : Bare_ViewChange) : View :=\n    match bvc with\n    | bare_view_change v n s C P i => v\n    end.\n\n  Definition view_change2view (vc : ViewChange) : View :=\n    bare_view_change2view (view_change2bare vc).\n\n  Definition prepared_info2view (p : PreparedInfo) : View :=\n    pre_prepare2view (prepared_info_pre_prepare p).\n\n  Definition start_timer2view (b : StartTimer) : View :=\n    match b with\n    | start_timer _ v => v\n    end.\n\n\n\n  (* =========== timer extraction =========== *)\n\n  Definition start_timer2req (b : StartTimer) : Bare_Request :=\n    match b with\n    | start_timer r _ => r\n    end.\n\n  Definition start_timer2expired_timer (b : StartTimer) : ExpiredTimer :=\n    match b with\n    | start_timer r v => expired_timer r v\n    end.\n\n\n\n  (* =========== extract prepared info =========== *)\n\n  Definition bare_view_change2prep (bvc : Bare_ViewChange) : list PreparedInfo :=\n    match bvc with\n    | bare_view_change v n s C P i => P\n    end.\n\n  Definition view_change2prep (vc : ViewChange) : list PreparedInfo :=\n    bare_view_change2prep (view_change2bare vc).\n\n\n\n  (* =========== extract original msg that client send =========== *)\n\n  Definition bare_pre_prepare2requests (p : Bare_Pre_prepare) : list Request :=\n    match p with\n    | bare_pre_prepare _ _ m => m\n    end.\n\n  Definition pre_prepare2requests (p : Pre_prepare) : list Request :=\n    match p with\n    | pre_prepare bpp _ => bare_pre_prepare2requests bpp\n    end.\n\n  Definition prepared_info2requests (p : PreparedInfo) : list Request :=\n    pre_prepare2requests (prepared_info_pre_prepare p).\n\n\n  (* =========== extract digest of msg that client sent ===========*)\n\n(*  Definition bare_pre_prepare2digest (p : Bare_Pre_prepare) : PBFTdigest :=\n    match p with\n    | bare_pre_prepare v n d => d\n    end.*)\n\n(*  Definition pre_prepare_data2digest (p : Pre_prepare_data) : PBFTdigest :=\n    match p with\n    | MkPrePrepareData b _ => bare_pre_prepare2digest b\n    end.*)\n\n(*  Definition pre_prepare2digest (p : Pre_prepare) : PBFTdigest :=\n    match p with\n    | pre_prepare b _ => pre_prepare_data2digest b\n    end.*)\n\n  Definition bare_prepare2digest (p : Bare_Prepare) : PBFTdigest  :=\n    match p with\n    | bare_prepare v n d i => d\n    end.\n\n  Definition prepare2digest (p : Prepare) : PBFTdigest  :=\n    match p with\n    | prepare b _ => bare_prepare2digest b\n    end.\n\n  Definition bare_commit2digest (c : Bare_Commit) : PBFTdigest :=\n    match c with\n    | bare_commit v n d i => d\n    end.\n\n  Definition commit2digest (c : Commit) : PBFTdigest :=\n    match c with\n    | commit b _ => bare_commit2digest b\n    end.\n\n\n  Definition bare_checkpoint2digest (c : Bare_Checkpoint) : PBFTdigest :=\n    match c with\n    | bare_checkpoint v n d i => d\n    end.\n\n  Definition checkpoint2digest (c : Checkpoint) : PBFTdigest :=\n    match c with\n    | checkpoint b _ => bare_checkpoint2digest b\n    end.\n\n  Definition prepared_info2digest (p : PreparedInfo) : PBFTdigest :=\n    prepared_info_digest p.\n\n\n  (* =========== Msg type =========== *)\n\n  Inductive PBFTmsg :=\n  | PBFTrequest              (r : Request)\n  | PBFTpre_prepare          (p : Pre_prepare)\n  | PBFTprepare              (p : Prepare)\n  | PBFTcommit               (c : Commit)\n  | PBFTreply                (r : Reply)\n  | PBFTcheckpoint           (c : Checkpoint)\n  | PBFTcheck_ready          (c : CheckReady)\n  | PBFTcheck_stable         (c : CheckStableChkPt)\n  | PBFTcheck_bcast_new_view (c : CheckBCastNewView)\n  | PBFTstart_timer          (c : StartTimer)\n  | PBFTexpired_timer        (t : ExpiredTimer)\n  | PBFTview_change          (v : ViewChange)\n  | PBFTnew_view             (v : NewView)\n  | PBFTdebug                (d : Debug).\n\n  Global Instance PBFT_I_Msg : Msg := MkMsg PBFTmsg.\n\n  Definition PBFTmsg2status (m : PBFTmsg) : msg_status :=\n    match m with\n    | PBFTrequest              _ => MSG_STATUS_EXTERNAL\n    | PBFTpre_prepare          _ => MSG_STATUS_PROTOCOL\n    | PBFTprepare              _ => MSG_STATUS_PROTOCOL\n    | PBFTcommit               _ => MSG_STATUS_PROTOCOL\n    | PBFTcheckpoint           _ => MSG_STATUS_PROTOCOL\n    | PBFTreply                _ => MSG_STATUS_PROTOCOL\n    | PBFTcheck_ready          _ => MSG_STATUS_INTERNAL\n    | PBFTcheck_stable         _ => MSG_STATUS_INTERNAL\n    | PBFTcheck_bcast_new_view _ => MSG_STATUS_INTERNAL\n    | PBFTstart_timer          _ => MSG_STATUS_INTERNAL\n    | PBFTexpired_timer        _ => MSG_STATUS_INTERNAL\n    | PBFTview_change          _ => MSG_STATUS_PROTOCOL\n    | PBFTnew_view             _ => MSG_STATUS_PROTOCOL\n    | PBFTdebug                _ => MSG_STATUS_INTERNAL\n    end.\n\n  Global Instance PBFT_I_get_msg_status : MsgStatus := MkMsgStatus PBFTmsg2status.\n\n\n\n  (* =========== Receive functions and state machines =========== *)\n\n  Definition receive_request (m : PBFTmsg) : option Request :=\n    match m with\n    | PBFTrequest r => Some r\n    | _ => None\n    end.\n\n  Definition PBFTreceiveRequest : StateMachine _ PBFTmsg (option Request) :=\n    mkSSM (fun state m _ => (state, receive_request m)) tt.\n\n  Definition receive_pre_prepare (m : PBFTmsg) : option Pre_prepare :=\n    match m with\n    | PBFTpre_prepare p => Some p\n    | _ => None\n    end.\n\n  Definition PBFTreceivePre_prepare : StateMachine _ PBFTmsg (option Pre_prepare) :=\n    mkSSM (fun state m _ => (state, receive_pre_prepare m)) tt.\n\n  Definition receive_prepare (m : PBFTmsg) : option Prepare :=\n    match m with\n    | PBFTprepare p => Some p\n    | _ => None\n    end.\n\n  Definition PBFTreceivePrepare : StateMachine _ PBFTmsg (option Prepare) :=\n    mkSSM (fun state m _ => (state, receive_prepare m)) tt.\n\n  Definition receive_commit (m : PBFTmsg) : option Commit :=\n    match m with\n    | PBFTcommit c => Some c\n    | _ => None\n    end.\n\n  Definition PBFTreceiveCommit : StateMachine _ PBFTmsg (option Commit) :=\n    mkSSM (fun state m _ => (state, receive_commit m)) tt.\n\n\n  Definition receive_checkpoint (m : PBFTmsg) : option Checkpoint :=\n    match m with\n    | PBFTcheckpoint c => Some c\n    | _ => None\n    end.\n\n  Definition PBFTreceiveCheckpoint : StateMachine _ PBFTmsg (option Checkpoint) :=\n    mkSSM (fun state m _ => (state, receive_checkpoint m)) tt.\n\n  Definition receive_reply (m : PBFTmsg) : option Reply :=\n    match m with\n    | PBFTreply r => Some r\n    | _ => None\n    end.\n\n  Definition PBFTreceiveReply : StateMachine _ PBFTmsg (option Reply) :=\n    mkSSM (fun state m _ => (state, receive_reply m)) tt.\n\n\n  (* ===============================================================\n     Authenticated Messages\n     =============================================================== *)\n\n  Definition option_client2name (cop : option Client) (n : name) : name :=\n    match cop with\n    | Some c => PBFTclient c\n    | None => n\n    end.\n\n  (* we are here extracting the sender of the message *)\n  Definition PBFTmsg_auth (n : name) (m : msg) : option name :=\n    match m with\n    | PBFTrequest              r => Some (option_client2name (request2sender r) n)\n    | PBFTpre_prepare          p => Some (PBFTreplica (pre_prepare2sender p))\n    | PBFTprepare              p => Some (PBFTreplica (prepare2sender p))\n    | PBFTcommit               c => Some (PBFTreplica (commit2sender c))\n    | PBFTcheckpoint           c => Some (PBFTreplica (checkpoint2sender c))\n    | PBFTreply                r => Some (PBFTreplica (reply2sender r))\n    | PBFTcheck_ready          c => Some n (* local message *)\n    | PBFTcheck_stable         c => Some n (* local message *)\n    | PBFTcheck_bcast_new_view c => Some n (* local message *)\n    | PBFTstart_timer          t => Some n (* local message *)\n    | PBFTexpired_timer        t => Some n (* local message *)\n    | PBFTview_change          v => Some (PBFTreplica (view_change2sender v))\n    (* FIX: is the sender of a new-view message always the primary of the previous view?  *)\n    | PBFTnew_view             v => Some (PBFTreplica (new_view2sender v))\n    | PBFTdebug                d => Some (PBFTreplica (debug2sender d))\n    end.\n\n  Definition PBFTdata_auth (n : name) (m : data) : option name :=\n    match m with\n    | PBFTmsg_bare_request              r => Some (option_client2name (bare_request2sender r) n)\n    | PBFTmsg_bare_pre_prepare          p => Some (PBFTreplica (bare_pre_prepare2sender p))\n    | PBFTmsg_bare_prepare              p => Some (PBFTreplica (bare_prepare2sender p))\n    | PBFTmsg_bare_commit               c => Some (PBFTreplica (bare_commit2sender c))\n    | PBFTmsg_bare_checkpoint           c => Some (PBFTreplica (bare_checkpoint2sender c))\n    | PBFTmsg_bare_reply                r => Some (PBFTreplica (bare_reply2sender r))\n    | PBFTmsg_bare_check_ready          _ => Some n (* local message *)\n    | PBFTmsg_bare_check_bcast_new_view _ => Some n (* local message *)\n    | PBFTmsg_bare_start_timer          _ => Some n (* local message *)\n    | PBFTmsg_bare_expired_timer        _ => Some n (* local message *)\n    | PBFTmsg_bare_view_change          v => Some (PBFTreplica (bare_view_change2sender v))\n    (* FIX: is the sender of a new-view message always the primary of the previous view?  *)\n    | PBFTmsg_bare_new_view             v => Some (PBFTreplica (PBFTprimary ((*pred_view*) (bare_new_view2view v))))\n    end.\n\n  Global Instance PBFT_I_DataAuth : DataAuth := MkDataAuth PBFTdata_auth.\n\n  Definition request2auth_data (r : Request) : AuthenticatedData :=\n    match r with\n    | req b a => MkAuthData (PBFTmsg_bare_request b) a\n    end.\n\n  Definition reply2auth_data (r : Reply) : AuthenticatedData :=\n    match r with\n    | reply b a => MkAuthData (PBFTmsg_bare_reply b) a\n    end.\n\n  Definition pre_prepare_data2auth_data_pre (p : Pre_prepare) : AuthenticatedData :=\n    match p with\n    | pre_prepare b a => MkAuthData (PBFTmsg_bare_pre_prepare b) a\n    end.\n\n  Definition pre_prepare2auth_data_req (p : Pre_prepare) : list AuthenticatedData :=\n    map request2auth_data (pre_prepare2requests p).\n\n  Definition pre_prepare2auth_data (p : Pre_prepare) : list AuthenticatedData :=\n    pre_prepare_data2auth_data_pre p :: pre_prepare2auth_data_req p.\n    (*match p with\n    | pre_prepare b a => MkAuthData (PBFTmsg_bare_pre_prepare b) a\n    end.*)\n\n  Definition prepare2auth_data (p : Prepare) : AuthenticatedData :=\n    match p with\n    | prepare b a => MkAuthData (PBFTmsg_bare_prepare b) a\n    end.\n\n  Definition commit2auth_data (c : Commit) : AuthenticatedData :=\n    match c with\n    | commit b a => MkAuthData (PBFTmsg_bare_commit b) a\n    end.\n\n  Definition checkpoint2auth_data (c : Checkpoint) : AuthenticatedData :=\n    match c with\n    | checkpoint b a => MkAuthData (PBFTmsg_bare_checkpoint b) a\n    end.\n\n  Definition prepares2auth_data (l : list Prepare): list AuthenticatedData :=\n    map prepare2auth_data l.\n\n  Definition prepared_info2auth_data (p : PreparedInfo) : list AuthenticatedData :=\n    (pre_prepare2auth_data (prepared_info_pre_prepare p))\n      ++ (prepares2auth_data (prepared_info_prepares p)).\n\n  Definition prepared_infos2auth_data (P : list PreparedInfo) : list AuthenticatedData :=\n    flat_map prepared_info2auth_data P.\n\n  Definition checkpoints2auth_data (l : list Checkpoint) : list AuthenticatedData :=\n    map checkpoint2auth_data l.\n\n  Definition view_change2auth_data (v : ViewChange) : list AuthenticatedData :=\n    match v with\n    | view_change (bare_view_change v n s C P i) a =>\n      (MkAuthData (PBFTmsg_bare_view_change (bare_view_change v n s C P i)) a)\n        :: checkpoints2auth_data C\n        ++ prepared_infos2auth_data P\n    end.\n\n  Definition view_changes2auth_data (l : list ViewChange) : list AuthenticatedData :=\n    flat_map view_change2auth_data l.\n\n  Definition pre_prepares2auth_data (l : list Pre_prepare) : list AuthenticatedData :=\n    flat_map pre_prepare2auth_data l.\n\n  Definition new_view2auth_data (v : NewView) : list AuthenticatedData :=\n    match v with\n    | new_view (bare_new_view v V OP NP) a =>\n      (MkAuthData (PBFTmsg_bare_new_view (bare_new_view v V OP NP)) a)\n        :: view_changes2auth_data V\n        ++ pre_prepares2auth_data OP\n        ++ pre_prepares2auth_data NP\n    end.\n\n  Definition PBFTget_contained_auth_data (m : msg) : list AuthenticatedData :=\n    match m with\n    | PBFTrequest              r => [request2auth_data r]\n    | PBFTreply                r => [reply2auth_data r]\n    | PBFTpre_prepare          p => pre_prepare2auth_data p\n    | PBFTprepare              p => [prepare2auth_data p]\n    | PBFTcommit               p => [commit2auth_data p]\n    | PBFTcheckpoint           p => [checkpoint2auth_data p]\n    | PBFTcheck_ready          _ => [] (* internal message *)\n    | PBFTcheck_stable         _ => [] (* internal message *)\n    | PBFTcheck_bcast_new_view _ => [] (* internal message *)\n    | PBFTstart_timer          _ => [] (* internal message *)\n    | PBFTexpired_timer        _ => [] (* internal message *)\n    | PBFTview_change          v => view_change2auth_data v\n    | PBFTnew_view             v => new_view2auth_data v\n    | PBFTdebug                _ => [] (* internal message *)\n    end.\n\n  (*\n  Definition PBFTauthMsg2Msg (a : AuthenticatedData) : PBFTmsg :=\n    match a with\n    | MkAuthData d t =>\n      match d with\n      | PBFTmsg_bare_request r     => PBFTrequest (req r t)\n      | PBFTmsg_bare_reply r       => PBFTreply (reply r t)\n      | PBFTmsg_bare_pre_prepare p => exists r, PBFTpre_prepare (pre_prepare p t r) (* and digest or r is equal to d*)\n      | PBFTmsg_bare_prepare p     => PBFTprepare (prepare p t)\n      | PBFTmsg_bare_commit c      => PBFTcommit (commit c t)\n      end\n    end.\n*)\n\n  Global Instance PBFT_I_ContainedAuthData : ContainedAuthData :=\n    MkContainedAuthData PBFTget_contained_auth_data.\n\n\n\n  (*\n  (* ===============================================================\n     Assumptions about keys\n     =============================================================== *)\n\n  Definition PBFThold_keys (eo : EventOrdering) : Prop :=\n    forall (e : Event),\n      match loc e with\n      | PBFTreplica n => forall m, has_key (keys e) (PBFTreplica m)\n      | _ => True\n      end.*)\n\n\n\n  (* ===============================================================\n     Sending functions\n     =============================================================== *)\n\n  Definition send_request (r : Request) (n : list name) : DirectedMsg :=\n    MkDMsg (PBFTrequest r) n ('0).\n\n  Definition send_reply (r : Reply) : DirectedMsg :=\n    MkDMsg (PBFTreply r) [PBFTclient (reply2client r)] ('0).\n\n  Definition send_pre_prepare (p : Pre_prepare) (n : list name) : DirectedMsg :=\n    MkDMsg (PBFTpre_prepare p) n ('0).\n\n  Definition send_prepare (p : Prepare) (n : list name) : DirectedMsg :=\n    MkDMsg (PBFTprepare p) n ('0).\n\n  Definition send_commit (c : Commit) (n : list name) : DirectedMsg :=\n    MkDMsg (PBFTcommit c) n ('0).\n\n  Definition send_checkpoint (c : Checkpoint) (n : list name) : DirectedMsg :=\n    MkDMsg (PBFTcheckpoint c) n ('0).\n\n  Definition send_debug (n : Rep) (s : String.string) : DirectedMsg :=\n    MkDMsg (PBFTdebug (debug n s)) [PBFTreplica n] ('0).\n\n  Definition send_view_change (v : ViewChange) (n : list name) : DirectedMsg :=\n    MkDMsg (PBFTview_change v) n ('0).\n\n  Definition send_new_view (v : NewView) (n : list name) : DirectedMsg :=\n    MkDMsg (PBFTnew_view v) n ('0).\n\n  Definition send_check_ready (n : Rep) : DirectedMsg :=\n    MkDMsg (PBFTcheck_ready check_ready) [PBFTreplica n] ('0).\n\n  Definition send_check_stable (n : Rep) : DirectedMsg :=\n    MkDMsg (PBFTcheck_stable check_stable_checkpoint) [PBFTreplica n] ('0).\n\n  Definition send_check_bcast_new_view (c : CheckBCastNewView) (n : list name) : DirectedMsg :=\n    MkDMsg (PBFTcheck_bcast_new_view c) n ('0).\n\n  Definition send_start_timer (t : StartTimer) (n : Rep) : DirectedMsg :=\n    MkDMsg (PBFTstart_timer t) [PBFTreplica n] ('PBFTtimer_delay).\n\n  Definition send_expired_timer (t : ExpiredTimer) (n : Rep) : DirectedMsg :=\n    MkDMsg (PBFTexpired_timer t) [PBFTreplica n] ('0).\n\n\n\n  (* ===============================================================\n     Verify functions\n     =============================================================== *)\n\n  Definition verify_request (slf : Rep) (km : local_key_map) (r : Request) : bool :=\n    match r with\n    | req b a =>\n      verify_authenticated_data\n        (PBFTreplica slf) (*(PBFTclient (request2sender r))*)\n        (MkAuthData (PBFTmsg_bare_request b) a)\n        km\n    end.\n\n  Definition verify_requests (slf : Rep) (km : local_key_map) (rs : list Request) : bool :=\n    forallb (verify_request slf km) rs.\n\n(*  Definition verify_pre_prepare_data (slf : Rep) (km : local_key_map) (p : Pre_prepare_data) : bool :=\n    match p with\n    | MkPrePrepareData b a =>\n      verify_authenticated_data\n        (PBFTreplica slf) (*(PBFTreplica (bare_pre_prepare2sender b))*)\n        (MkAuthData (PBFTmsg_bare_pre_prepare b) a)\n        km\n    end.*)\n\n  Definition verify_pre_prepare (slf : Rep) (km : local_key_map) (p : Pre_prepare) : bool :=\n    verify_list_auth_data (PBFTreplica slf) km (pre_prepare2auth_data p).\n\n  Definition verify_prepare (slf : Rep) (km : local_key_map) (p : Prepare) : bool :=\n    verify_authenticated_data\n      (PBFTreplica slf)\n      (prepare2auth_data p)\n      km.\n\n  Definition verify_commit (slf : Rep) (km : local_key_map) (c : Commit) : bool :=\n    verify_authenticated_data\n      (PBFTreplica slf)\n      (commit2auth_data c)\n      km.\n\n  Definition verify_checkpoint (slf : Rep) (km : local_key_map) (c : Checkpoint) : bool :=\n    verify_authenticated_data\n      (PBFTreplica slf)\n      (checkpoint2auth_data c)\n      km.\n\n  Definition verify_view_change (slf : Rep) (km : local_key_map) (vc : ViewChange) : bool :=\n    verify_list_auth_data (PBFTreplica slf) km (view_change2auth_data vc).\n\n  Definition verify_new_view (slf : Rep) (km : local_key_map) (nv : NewView) : bool :=\n    verify_list_auth_data (PBFTreplica slf) km (new_view2auth_data nv).\n\n\n  (* ===============================================================\n     Creation of authenticated messages\n     =============================================================== *)\n\n  Definition mk_auth_pre_prepare\n             (v : View)\n             (s : SeqNum)\n             (d : list Request)\n             (keys : local_key_map) : Pre_prepare :=\n    let bpp  := bare_pre_prepare v s d in\n    (* we authenticate the unsigned pre-prepare message *)\n    let toks := authenticate (PBFTmsg_bare_pre_prepare bpp) keys in\n    (* we create an authenticated pre-prepare message *)\n    pre_prepare bpp toks.\n\n  Definition mk_auth_new_view\n             (v : View)\n             (V : ViewChangeCert)\n             (OP NP : list Pre_prepare)\n             (keys : local_key_map) : NewView :=\n    let bnv  := bare_new_view v V OP NP in\n    let toks := authenticate (PBFTmsg_bare_new_view bnv) keys in\n    new_view bnv toks.\n\n  Definition mk_auth_reply\n             (v : View)\n             (t : Timestamp)\n             (c : Client)\n             (i : Rep)\n             (r : PBFTresult)\n             (keys : local_key_map) : Reply :=\n    let brep := bare_reply v t c i r in\n    (* we authenticate the unsigned reply message *)\n    let toks := authenticate (PBFTmsg_bare_reply brep) keys in\n    (* we create an authenticated reply message *)\n    reply brep toks.\n\n  Definition mk_auth_checkpoint\n             (v : View)\n             (n : SeqNum)\n             (d : PBFTdigest)\n             (i : Rep)\n             (keys : local_key_map) : Checkpoint :=\n    let bcp    := bare_checkpoint v n d i in\n    (* we authenticate the unsigned checkpoint message *)\n    let toks   := authenticate (PBFTmsg_bare_checkpoint bcp) keys in\n    (* we create an authenticated checkpoint message *)\n    checkpoint bcp toks.\n\n  Definition mk_auth_view_change\n             (v : View)\n             (n : SeqNum)\n             (s : StableChkPt)\n             (C : CheckpointCert)\n             (P : list PreparedInfo)\n             (i : Rep)\n             (keys : local_key_map) : ViewChange :=\n    let bvc  := bare_view_change v n s C P i in\n    let toks := authenticate (PBFTmsg_bare_view_change bvc) keys in\n    view_change bvc toks.\n\n  Definition prepare2commit (slf : Rep) (keys : local_key_map) (p : Prepare) : Commit :=\n    (* we create a commit message *)\n    let bc   := prepare2bare_commit slf p in\n    (* we authenticate the unsigned commit message *)\n    let toks := authenticate (PBFTmsg_bare_commit bc) keys in\n    (* we create an authenticated prepare message *)\n    commit bc toks.\n\n  Definition pre_prepare2prepare\n             (n    : Rep)\n             (keys : local_key_map)\n             (pp   : Pre_prepare)\n             (d    : PBFTdigest) : Prepare :=\n    let bp := pre_prepare2bare_prepare pp d n in\n    let a  := authenticate (PBFTmsg_bare_prepare bp) keys in\n    prepare bp a.\n\n  Definition pre_prepare2commit\n             (slf  : Rep)\n             (keys : local_key_map)\n             (pp   : Pre_prepare)\n             (d    : PBFTdigest) : Commit :=\n    (* we create a commit message *)\n    let bc   := pre_prepare2bare_commit slf pp d in\n    (* we authenticate the unsigned commit message *)\n    let toks := authenticate (PBFTmsg_bare_commit bc) keys in\n    (* we create an authenticated prepare message *)\n    commit bc toks.\n\n  Definition mk_auth_null_req (keys : local_key_map) : Request :=\n    req null_req (authenticate (PBFTmsg_bare_request null_req) keys).\n\n\n\n  (* ===============================================================\n     Hashing\n     =============================================================== *)\n\n  (* FIX: These should really hash something like a list of bytes,\n       but for that we need to convert messages/states to bytes. *)\n  Class PBFThash :=\n    MkPBFThash\n      {\n        create_hash_messages : list PBFTmsg -> PBFTdigest;\n        verify_hash_messages : list PBFTmsg -> PBFTdigest -> bool;\n\n        create_hash_state_last_reply  : PBFTsm_state -> LastReplyState -> PBFTdigest;\n        verify_hash_state_last_reply  : PBFTsm_state -> LastReplyState -> PBFTdigest -> bool;\n      }.\n\n  Context { pbft_hash : PBFThash }.\n\n(* (* To bring in later when we actually need it *)\n  Class PBFThash_axioms :=\n    {\n      create_hash_messages_collision_resistant :\n        forall msgs1 msgs2,\n          create_hash_messages msgs1 = create_hash_messages msgs2\n          -> msgs1 = msgs2;\n\n      create_hash_state_last_reply_collision_resistant :\n        forall sm1 sm2 last1 last2,\n          create_hash_state_last_reply sm1 last1 = create_hash_state_last_reply sm2 last2\n          -> sm1 = sm2 /\\ last1 = last2\n    }.\n\n  Context { pbft_hash_axioms : PBFThash_axioms }.*)\n\nEnd PBFTheader.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/PBFT/PBFTheader.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22064539581352363}}
{"text": "(*! End-to-end correctness theorem !*)\nRequire Import Koika.CompilerCorrectness.CircuitCorrectness Koika.CompilerCorrectness.LoweringCorrectness.\nRequire Import Koika.Common Koika.Types Koika.Environments Koika.Logs.\nRequire Import Koika.Lowering Koika.CircuitGeneration Koika.CircuitOptimization Koika.Compiler.\n\nSection Thm.\n  Context {pos_t var_t fn_name_t rule_name_t reg_t ext_fn_t: Type}.\n  Context {eq_dec_var_t: EqDec var_t}.\n\n  Context {R: reg_t -> type}.\n  Context {Sigma: ext_fn_t -> ExternalSignature}.\n  Context {FiniteType_reg_t: FiniteType reg_t}.\n  Context {Show_var_t : Show var_t}.\n  Context {Show_rule_name_t : Show rule_name_t}.\n\n  Context (r: ContextEnv.(env_t) R).\n  Context (sigma: forall f, Sig_denote (Sigma f)).\n\n  Notation CR := (lower_R R).\n  Notation CSigma := (lower_Sigma Sigma).\n\n  Notation cr := (lower_r r).\n  Notation csigma := (lower_sigma sigma).\n\n  Context (lco: (@local_circuit_optimizer\n                   rule_name_t reg_t ext_fn_t\n                   CR CSigma\n                   (rwdata (rule_name_t := rule_name_t) CR CSigma)\n                   (lower_sigma sigma))).\n\n  Section Standalone.\n    Context (s: Syntax.scheduler pos_t rule_name_t).\n    Context (rules: rule_name_t -> TypedSyntax.rule pos_t var_t fn_name_t R Sigma).\n    Context (external: rule_name_t -> bool).\n\n    Theorem compiler_correct:\n      let spec_results := TypedSemantics.interp_cycle sigma rules s r in\n      let circuits := compile_scheduler lco rules external s in\n      forall reg,\n        interp_circuit cr csigma (ContextEnv.(getenv) circuits reg) =\n        bits_of_value (ContextEnv.(getenv) spec_results reg).\n    Proof.\n      cbv zeta; intros.\n      setoid_rewrite compile_scheduler'_correct.\n      - rewrite cycle_lowering_correct.\n        unfold lower_r, lower_log; rewrite getenv_map; reflexivity.\n      - apply circuit_env_equiv_CReadRegister.\n    Qed.\n  End Standalone.\nEnd Thm.\n", "meta": {"author": "mit-plv", "repo": "koika", "sha": "c758c7b0092186f76ed858f4137366cc62f7a04a", "save_path": "github-repos/coq/mit-plv-koika", "path": "github-repos/coq/mit-plv-koika/koika-c758c7b0092186f76ed858f4137366cc62f7a04a/coq/CompilerCorrectness/Correctness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22064538985245477}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Strings.Ascii.\nRequire Char.\nRequire Import Comparison.\nRequire Import LString.\n\nImport ListNotations.\nImport LString.\nLocal Open Scope char.\n\n(** Test if the string contains only ASCII characters. *)\nDefinition is_ascii (s : t) : bool :=\n  List.forallb Char.is_ascii s.\n\n(** Test if the string is empty. *)\nDefinition is_empty (s : t) : bool :=\n  match s with\n  | [] => true\n  | _ :: _ => false\n  end.\n\n(** Repeat a string [n] times. *)\nFixpoint repeat (s : t) (n : nat) : t :=\n  match n with\n  | O => []\n  | S n => s ++ repeat s n\n  end.\n\n(** Center a string on a line of width [width], with white space paddings. *)\nDefinition center (s : t) (width : nat) : t :=\n  let l := List.length s in\n  let l_left := Nat.div2 (width - l) in\n  let l_right := (width - l) - l_left in\n  repeat [\" \"] l_left ++ s ++ repeat [\" \"] l_right.\n\n(** Concatenate the list of strings [l] with the separator [separator]. *)\nFixpoint join (separator : t) (l : list t) : t :=\n  match l with\n  | [] => []\n  | [s] => s\n  | s :: l => s ++ separator ++ join separator l\n  end.\n\nFixpoint split_aux (s : t) (c : ascii) (beginning : t) : list t :=\n  match s with\n  | [] => [List.rev' beginning]\n  | c' :: s =>\n    if Char.eqb c c' then\n      List.rev' beginning :: split_aux s c []\n    else\n      split_aux s c (c' :: beginning)\n  end.\n\n(** Split a string at each occurrence of a given character. *)\nDefinition split (s : t) (c : ascii) : list t :=\n  split_aux s c [].\n\nFixpoint split_limit_aux (s : t) (c : ascii) (beginning : t) (limit : nat)\n  : list t :=\n  match limit with\n  | O => []\n  | S O => [List.rev' beginning ++ s]\n  | S limit =>\n    match s with\n    | [] => [List.rev' beginning]\n    | c' :: s =>\n      if Char.eqb c c' then\n        List.rev' beginning :: split_limit_aux s c [] limit\n      else\n        split_limit_aux s c (c' :: beginning) (S limit)\n    end\n  end.\n\n(** Split a string at each occurrence of a given character in a list of up to\n    [limit] elements. *)\nDefinition split_limit (s : t) (c : ascii) (limit : nat) : list t :=\n  split_limit_aux s c [] limit.\n\n(** Escape the string to generate correct HTML. *)\nFixpoint escape_html (s : t) : t :=\n  match s with\n  | [] => []\n  | c :: s =>\n    match c with\n    | \"'\" => [\"&\"; \"a\"; \"p\"; \"o\"; \"s\"; \";\"]\n    | \"\"\"\" => [\"&\"; \"q\"; \"u\"; \"o\"; \"t\"; \";\"]\n    | \"&\" => [\"&\"; \"a\"; \"m\"; \"p\"; \";\"]\n    | \"<\" => [\"&\"; \"l\"; \"t\"; \";\"]\n    | \">\" => [\"&\"; \"g\"; \"t\"; \";\"]\n    | _ => [c]\n    end ++ escape_html s\n  end.\n", "meta": {"author": "clarus", "repo": "coq-list-string", "sha": "522973cd3e3c270974b8b92a3cec13b13fd4bc11", "save_path": "github-repos/coq/clarus-coq-list-string", "path": "github-repos/coq/clarus-coq-list-string/coq-list-string-522973cd3e3c270974b8b92a3cec13b13fd4bc11/src/Etc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.22062196280627977}}
{"text": "(************************************************************************)\n(*         *   The Coq Proof Assistant / The Coq Development Team       *)\n(*  v      *         Copyright INRIA, CNRS and contributors             *)\n(* <O___,, * (see version control and CREDITS file for authors & dates) *)\n(*   \\VV/  **************************************************************)\n(*    //   *    This file is distributed under the terms of the         *)\n(*         *     GNU Lesser General Public License Version 2.1          *)\n(*         *     (see LICENSE file for the text of the license)         *)\n(************************************************************************)\n\n(** Extraction to OCaml of native 63-bit machine integers. *)\n\nFrom Coq Require Uint63 Sint63 Extraction.\n\n(** Basic data types used by some primitive operators. *)\n\nExtract Inductive bool => bool [ true false ].\nExtract Inductive prod => \"( * )\" [ \"\" ].\nExtract Inductive DoubleType.carry => \"MCUint63.carry\" [ \"MCUint63.C0\" \"MCUint63.C1\" ].\n\n(** Primitive types and operators. *)\nExtract Constant Uint63.int => \"MCUint63.t\".\nExtraction Inline Uint63.int.\n(* Otherwise, the name conflicts with the primitive OCaml type [int] *)\n\nExtract Constant Uint63.lsl => \"MCUint63.l_sl\".\nExtract Constant Uint63.lsr => \"MCUint63.l_sr\".\nExtract Constant Sint63.asr => \"MCUint63.a_sr\".\nExtract Constant Uint63.land => \"MCUint63.l_and\".\nExtract Constant Uint63.lor => \"MCUint63.l_or\".\nExtract Constant Uint63.lxor => \"MCUint63.l_xor\".\n\nExtract Constant Uint63.add => \"MCUint63.add\".\nExtract Constant Uint63.sub => \"MCUint63.sub\".\nExtract Constant Uint63.mul => \"MCUint63.mul\".\nExtract Constant Uint63.mulc => \"MCUint63.mulc\".\nExtract Constant Uint63.div => \"MCUint63.div\".\nExtract Constant Uint63.mod => \"MCUint63.rem\".\nExtract Constant Sint63.div => \"MCUint63.divs\".\nExtract Constant Sint63.rem => \"MCUint63.rems\".\n\n\nExtract Constant Uint63.eqb => \"MCUint63.equal\".\nExtract Constant Uint63.ltb => \"MCUint63.lt\".\nExtract Constant Uint63.leb => \"MCUint63.le\".\nExtract Constant Sint63.ltb => \"MCUint63.lts\".\nExtract Constant Sint63.leb => \"MCUint63.les\".\n\nExtract Constant Uint63.addc => \"MCUint63.addc\".\nExtract Constant Uint63.addcarryc => \"MCUint63.addcarryc\".\nExtract Constant Uint63.subc => \"MCUint63.subc\".\nExtract Constant Uint63.subcarryc => \"MCUint63.subcarryc\".\n\nExtract Constant Uint63.diveucl => \"MCUint63.diveucl\".\nExtract Constant Uint63.diveucl_21 => \"MCUint63.div21\".\nExtract Constant Uint63.addmuldiv => \"MCUint63.addmuldiv\".\n\nExtract Constant Uint63.compare =>\n  \"fun x y -> match MCUint63.compare x y with 0 -> Eq | c when c < 0 -> Lt | _ -> Gt\".\nExtract Constant Sint63.compare =>\n  \"fun x y -> match MCUint63.compares x y with 0 -> Eq | c when c < 0 -> Lt | _ -> Gt\".\n\nExtract Constant Uint63.head0 => \"MCUint63.head0\".\nExtract Constant Uint63.tail0 => \"MCUint63.tail0\".\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/utils/theories/MC_ExtrOCamlInt63.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.22062196280627977}}
{"text": "(** Experiments on encoding concurrency in Coq. *)\nRequire Import Arith.\nRequire Import List.\nRequire Import Streams.\nRequire Import String.\n\nImport ListNotations.\nLocal Open Scope string_scope.\n\nSet Implicit Arguments.\n\nModule Result.\n  Inductive t (A B C : Type) : Type :=\n  | Val : A -> t A B C\n  | Err : B -> t A B C\n  | Mon : C -> t A B C.\n\n  Arguments Val [A] [B] [C] _.\n  Arguments Err [A] [B] [C] _.\n  Arguments Mon [A] [B] [C] _.\nEnd Result.\n\nImport Result.\n\n(** Definition of a computation. *)\nModule C.\n  Inductive t (S : Type) (E : Type) (A : Type) : Type :=\n  | make : (S -> Result.t A E (t S E A) * S) -> t S E A.\n\n  Definition open S E A (x : t S E A) :=\n    match x with\n    | make x' => x'\n    end.\nEnd C.\n\n(** Monadic return. *)\nDefinition ret {S E A} (x : A) : C.t S E A :=\n  C.make (fun s => (Val x, s)).\n\n(** Monadic bind. *)\nFixpoint bind S E A B (x : C.t S E A) (f : A -> C.t S E B) : C.t S E B :=\n  C.make (fun s =>\n    match C.open x s with\n    | (Val x, s) => (Mon (f x), s)\n    | (Err e, s) => (Err e, s)\n    | (Mon x, s) => (Mon (bind x f), s)\n    end).\n\nNotation \"'let!' X ':=' A 'in' B\" := (bind A (fun X => B))\n  (at level 200, X ident, A at level 100, B at level 200).\n\n(** Raw evaluation. *)\nFixpoint eval S E A (x : C.t S E A) (s : S) : (A + E) * S :=\n  match C.open x s with\n  | (Val x, s) => (inl x, s)\n  | (Err e, s) => (inr e, s)\n  | (Mon x, s) => eval x s\n  end.\n\n(** Augment the state. *)\nFixpoint lift_state S1 S2 E A (x : C.t S1 E A) : @C.t (S1 * S2) E A :=\n  C.make (fun (s : S1 * S2) =>\n    let (s1, s2) := s in\n    match C.open x s1 with\n    | (Val x, s1) => (Val x, (s1, s2))\n    | (Err e, s1) => (Err e, (s1, s2))\n    | (Mon x, s1) => (Mon (lift_state _ x), (s1, s2))\n    end).\n\n(** Apply an isomorphism to the state. *)\nFixpoint map_state S1 S2 E A (f : S1 -> S2) (g : S2 -> S1) (x : C.t S1 E A)\n  : C.t S2 E A :=\n  C.make (fun (s2 : S2) =>\n    let s1 := g s2 in\n    let (r, s1) := C.open x s1 in\n    (match r with\n    | Val x => Val x\n    | Err e => Err e\n    | Mon x => Mon (map_state f g x)\n    end, f s1)).\n\nModule Option.\n  Definition none A : C.t unit unit A :=\n    C.make (fun _ => (Err tt, tt)).\nEnd Option.\n\nModule Error.\n  Definition raise E A (e : E) : C.t unit E A :=\n    C.make (fun _ => (Err e, tt)).\nEnd Error.\n\nModule Log.\n  Definition t := list.\n\n  Definition log A (x : A) : C.t (t A) Empty_set unit :=\n    C.make (fun s => (Val tt, x :: s)).\nEnd Log.\n\nModule State.\n  Definition read (S : Type) (_ : unit) : C.t S Empty_set S :=\n    C.make (fun s => (Val s, s)).\n\n  Definition write (S : Type) (x : S) : C.t S Empty_set unit :=\n    C.make (fun _ => (Val tt, x)).\nEnd State.\n\n(** A source of information for a concurrent scheduler. *)\nModule Entropy.\n  Require Import BinNat.\n\n  Definition t := Stream bool.\n\n  Definition left : t := Streams.const true.\n\n  Definition right : t := Streams.const false.\n\n  Definition inverse (e : t) : t :=\n    Streams.map negb e.\n\n  Definition half : t :=\n    let cofix aux b :=\n      Streams.Cons b (aux (negb b)) in\n    aux true.\n\n  CoFixpoint random_naturals (n : N) : Stream N :=\n    let n' := N.modulo (137 * n + 187) 256 in\n    Streams.Cons n (random_naturals n').\n\n  Definition random (seed : N) : t :=\n    Streams.map (fun n => N.even (N.div n 64)) (random_naturals seed).\n\n  Module Test.\n    Fixpoint hds A (n : nat) (e : Stream A) : list A :=\n      match n with\n      | O => []\n      | S n => Streams.hd e :: hds n (Streams.tl e)\n      end.\n\n    Compute hds 20 (random_naturals 0).\n    Compute hds 20 (random 0).\n    Compute hds 20 (random 12).\n    Compute hds 20 (random 23).\n  End Test.\nEnd Entropy.\n\nModule Concurrency.\n  (** Executes [x] and [y] concurrently, using a boolean stream as source of entropy. *)\n  Fixpoint par S E A B\n    (x : C.t (S * Entropy.t) E A) (y : C.t (S * Entropy.t) E B) {struct x}\n    : C.t (S * Entropy.t) E (A * B) :=\n    let fix par_aux y {struct y} : C.t (S * Entropy.t) E (A * B) :=\n      C.make (fun (s : S * Entropy.t) =>\n        match s with\n        | (s, Streams.Cons b bs) =>\n          if b then\n            let (r, ss) := C.open x (s, bs) in\n            (match r with\n            | Val x => Mon (let! y := y in ret (x, y))\n            | Err e => Err e\n            | Mon x => Mon (par x y)\n            end, ss)\n          else\n            let (r, ss) := C.open y (s, bs) in\n            (match r with\n            | Val y => Mon (let! x := x in ret (x, y))\n            | Err e => Err e\n            | Mon y => Mon (par_aux y)\n            end, ss)\n        end) in\n    C.make (fun (s : S * Entropy.t) =>\n      match s with\n      | (s, Streams.Cons b bs) =>\n        if b then\n          let (r, ss) := C.open x (s, bs) in\n          (match r with\n          | Val x => Mon (let! y := y in ret (x, y))\n          | Err e => Err e\n          | Mon x => Mon (par x y)\n          end, ss)\n        else\n          let (r, ss) := C.open y (s, bs) in\n          (match r with\n          | Val y => Mon (let! x := x in ret (x, y))\n          | Err e => Err e\n          | Mon y => Mon (par_aux y)\n          end, ss)\n      end).\n\n  Definition par_unit S E (x : C.t (S * Entropy.t) E unit) (y : C.t (S * Entropy.t) E unit)\n    : C.t (S * Entropy.t) E unit :=\n    let! _ := par x y in\n    ret tt.\n\n  (** Make [x] atomic. *)\n  Fixpoint atomic S E A (x : C.t S E A) : C.t S E A :=\n    C.make (fun (s : S) =>\n      match C.open x s with\n      | (Val _, _) as y | (Err _, _) as y => y\n      | (Mon x, s) => C.open (atomic x) s\n      end).\nEnd Concurrency.\n\nModule List.\n  Fixpoint iter_seq S E A (f : A -> C.t S E unit) (l : list A) : C.t S E unit :=\n    match l with\n    | [] => ret tt\n    | x :: l =>\n      let! _ := f x in\n      iter_seq f l\n    end.\n\n  Fixpoint iter_par S E A (f : A -> C.t (S * Entropy.t) E unit) (l : list A)\n    : C.t (S * Entropy.t) E unit :=\n    match l with\n    | [] => ret tt\n    | x :: l => Concurrency.par_unit (f x) (iter_par f l)\n    end.\nEnd List.\n\nModule Event.\n  Definition t := list.\n\n  Definition loop_seq S E A (f : A -> C.t S E unit) : C.t (S * t A) E unit :=\n    C.make (fun (s : S * t A) =>\n      let (s, events) := s in\n      (Mon (lift_state (t A) (List.iter_seq f events)), (s, []))).\n\n  Definition loop_par S E A (f : A -> C.t (S * Entropy.t) E unit)\n    : C.t (S * t A * Entropy.t) E unit :=\n    C.make (fun (s : S * t A * Entropy.t) =>\n      match s with\n      | (s, events, entropy) =>\n        let c := List.iter_par f events in\n        let c := lift_state (t A) c in\n        let c := map_state\n          (fun ss => match ss with (s1, s2, s3) => (s1, s3, s2) end)\n          (fun ss => match ss with (s1, s2, s3) => (s1, s3, s2) end)\n          c in\n        (Mon c, (s, [], entropy))\n      end).\n\n  Module Test.\n    Definition log_all (_ : unit) : C.t (Log.t nat * t nat * Entropy.t) Empty_set unit :=\n      loop_par (fun n =>\n        lift_state _ (Log.log n)).\n\n    Definition eval (inputs : list nat) (entropy : Entropy.t) : list nat :=\n      match snd (eval (log_all tt) ([], inputs, entropy)) with\n      | (output, _, _) => output\n      end.\n\n    Compute eval [] Entropy.left.\n    Compute eval [1; 2; 3] Entropy.left.\n    Compute eval [1; 2; 3] Entropy.right.\n  End Test.\nEnd Event.\n\nModule Test.\n  Definition eval_seq (x : C.t (list nat) Empty_set unit) : list nat :=\n    snd (eval x []).\n\n  Definition eval_par (x : C.t (list nat * Entropy.t) Empty_set unit) (e : Entropy.t) : list nat :=\n    fst (snd (eval x ([], e))).\n\n  (** Two threads are printing concurrently two lists of numbers. *)\n  Module PrintList.\n    Fixpoint print_before (n : nat) : C.t (Log.t nat) Empty_set unit :=\n      match n with\n      | O => ret tt\n      | S n =>\n        let! _ := Log.log n in\n        print_before n\n      end.\n\n    Definition two_prints_seq (n : nat) : C.t (Log.t nat) Empty_set unit :=\n      let! _ := print_before n in\n      print_before (2 * n).\n\n    Definition print_before_par (n : nat) : C.t (Log.t nat * Entropy.t) Empty_set unit :=\n      lift_state (Entropy.t) (print_before n).\n\n    Definition two_prints_par (n : nat) : C.t (Log.t nat * Entropy.t) Empty_set unit :=\n      Concurrency.par_unit (print_before_par n) (print_before_par (2 * n)).\n\n    Compute eval_seq (print_before 12).\n    Compute eval_seq (two_prints_seq 12).\n\n    Compute eval_par (print_before_par 12) Entropy.half.\n    Compute eval_par (two_prints_par 12) Entropy.left.\n    Compute eval_par (two_prints_par 12) Entropy.right.\n    Compute eval_par (two_prints_par 12) Entropy.half.\n    Compute eval_par (two_prints_par 12) (Entropy.random 0).\n  End PrintList.\n\n  (** A list of threads are printing a number each. *)\n  Module ListOfPrints.\n    Definition print_seq_seq (n k : nat) : C.t (Log.t nat) Empty_set unit :=\n      List.iter_seq (Log.log (A := nat)) (List.seq n k).\n\n    Definition print_seq_par (n k : nat) : C.t (Log.t nat * Entropy.t) Empty_set unit :=\n      List.iter_par (fun n => lift_state _ (Log.log n)) (List.seq n k).\n\n    Compute eval_seq (print_seq_seq 10 20).\n    Compute eval_par (print_seq_par 10 20) Entropy.left.\n    Compute eval_par (print_seq_par 10 20) Entropy.right.\n    Compute eval_par (print_seq_par 10 20) (Entropy.random 12).\n  End ListOfPrints.\n\n  (** Simple manager for a list of things to do, with a UI saving data on a server. *)\n  Module TodoManager.\n    (** Event from the UI. *)\n    Module UiInput.\n      Inductive t : Set :=\n      | Add : string -> t\n      | Remove : nat -> t.\n    End UiInput.\n\n    (** Message to the UI. *)\n    Module UiOutput.\n      Inductive t :=\n      | Make : list string -> t.\n    End UiOutput.\n\n    (** Event from the server. *)\n    Module ServerInput.\n      Inductive t :=\n      | Make : list string -> t.\n    End ServerInput.\n\n    (** Message to the server. *)\n    Module ServerOutput.\n      Inductive t :=\n      | Make : list string -> t.\n    End ServerOutput.\n\n    Module Model.\n      (** The model is a list of tasks. *)\n      Inductive t :=\n      | Make : list string -> t.\n\n      Definition add (task : string) : C.t Model.t Empty_set unit :=\n        Concurrency.atomic (\n          let! model := State.read Model.t tt in\n          match model with\n          | Model.Make tasks => State.write (Model.Make (task :: tasks))\n          end).\n\n      Definition remove (id : nat) : C.t Model.t Empty_set unit :=\n        Concurrency.atomic (\n          let! model := State.read Model.t tt in\n          match model with\n          | Model.Make tasks => State.write (Model.Make tasks) (* TODO *)\n          end).\n\n      Definition get (_ : unit) : C.t Model.t Empty_set Model.t :=\n        State.read Model.t tt.\n\n      Definition set (model : t) : C.t Model.t Empty_set unit :=\n        State.write model.\n    End Model.\n\n    (** Send an update to the UI system. *)\n    Definition push_ui (_ : unit) : C.t (Model.t * Log.t UiOutput.t) Empty_set unit :=\n      let! model := lift_state (Log.t UiOutput.t) (Model.get tt) in\n      match model with\n      | Model.Make tasks =>\n        map_state\n          (fun ss => match ss with (s1, s2) => (s2, s1) end)\n          (fun ss => match ss with (s1, s2) => (s2, s1) end)\n          (lift_state Model.t (Log.log (UiOutput.Make tasks)))\n      end.\n\n    (** Send an update to the server. *)\n    Definition push_server (_ : unit) : C.t (Model.t * Log.t ServerOutput.t) Empty_set unit :=\n      let! model := lift_state (Log.t ServerOutput.t) (Model.get tt) in\n      match model with\n      | Model.Make tasks =>\n        map_state\n          (fun ss => match ss with (s1, s2) => (s2, s1) end)\n          (fun ss => match ss with (s1, s2) => (s2, s1) end)\n          (lift_state Model.t (Log.log (ServerOutput.Make tasks)))\n      end.\n\n    (** Update the UI and the server. *)\n    Definition broadcast_model (_ : unit)\n      : C.t (Model.t * Log.t UiOutput.t * Log.t ServerOutput.t * Entropy.t) Empty_set unit :=\n      let c_ui := lift_state Entropy.t (lift_state (Log.t ServerOutput.t) (push_ui tt)) in\n      let c_server := lift_state Entropy.t (map_state\n        (fun ss => match ss with (s1, s2, s3) => (s1, s3, s2) end)\n        (fun ss => match ss with (s1, s2, s3) => (s1, s3, s2) end)\n        (lift_state (Log.t UiOutput.t) (push_server tt))) in\n      Concurrency.par_unit c_ui c_server.\n\n    (** Handle an event from the UI. *)\n    Definition handle_ui (event : UiInput.t)\n      : C.t (Model.t * Log.t UiOutput.t * Log.t ServerOutput.t * Entropy.t) Empty_set unit :=\n      let lift c :=\n        lift_state Entropy.t (lift_state (Log.t ServerOutput.t) (lift_state (Log.t UiOutput.t) c)) in\n      match event with\n      | UiInput.Add task =>\n        let! _ := lift (Model.add task) in\n        broadcast_model tt\n      | UiInput.Remove id =>\n        let! _ := lift (Model.remove id) in\n        broadcast_model tt\n      end.\n\n    Definition eval_handle_ui (inputs : list UiInput.t) (entropy : Entropy.t)\n      : list UiOutput.t * list ServerOutput.t :=\n      match snd (eval (Event.loop_par handle_ui) (Model.Make [], [], [], inputs, entropy)) with\n      | (_, ui_outputs, server_outputs, _, _) => (ui_outputs, server_outputs)\n      end.\n\n    Compute eval_handle_ui [] Entropy.left.\n    Compute eval_handle_ui [UiInput.Add \"task1\"; UiInput.Add \"task2\"] Entropy.left.\n    Compute eval_handle_ui [UiInput.Add \"task1\"; UiInput.Add \"task2\"] Entropy.right.\n\n    (** Handle an event from the server. *)\n    Definition handle_server (event : ServerInput.t)\n      : C.t (Model.t * Log.t UiOutput.t) Empty_set unit :=\n      match event with\n      | ServerInput.Make tasks =>\n        let! _ := lift_state (Log.t UiOutput.t) (Model.set (Model.Make tasks)) in\n        push_ui tt\n      end.\n\n    Definition eval_handle_server (inputs : list ServerInput.t) (entropy : Entropy.t) : list UiOutput.t :=\n      let c := Event.loop_par (fun event => lift_state Entropy.t (handle_server event)) in\n      match snd (eval c (Model.Make [], [], inputs, entropy)) with\n      | (_, outputs, _, _) => outputs\n      end.\n\n    Compute eval_handle_server [] Entropy.left.\n    Compute eval_handle_server [ServerInput.Make [\"task1\"]; ServerInput.Make [\"task2\"]] Entropy.left.\n    Compute eval_handle_server [ServerInput.Make [\"task1\"]; ServerInput.Make [\"task2\"]] Entropy.right.\n\n    Definition lifted_handle_server (event : ServerInput.t)\n      : C.t (Model.t * Log.t UiOutput.t * Log.t ServerOutput.t * Entropy.t) Empty_set unit :=\n      lift_state Entropy.t (lift_state (Log.t ServerOutput.t) (handle_server event)).\n\n    Definition State : Type :=\n      (Model.t * Log.t UiOutput.t * Log.t ServerOutput.t * Event.t UiInput.t * Event.t ServerInput.t * Entropy.t)%type.\n\n    (** The TODO manager client. *)\n    Definition todo (_ : unit) : C.t State Empty_set unit :=\n      let c_ui : C.t State Empty_set unit :=\n        (* Handle events concurrently. *)\n        let c := Event.loop_par handle_ui in\n        let c := lift_state (Event.t ServerInput.t) c in\n        map_state\n          (fun ss => match ss with (s1, s2, s3) => (s1, s3, s2) end)\n          (fun ss => match ss with (s1, s2, s3) => (s1, s3, s2) end)\n          c in\n      let c_server : C.t State Empty_set unit :=\n        (* Handle events concurrently. *)\n        let c := Event.loop_par lifted_handle_server in\n        let c := lift_state (Event.t UiInput.t) c in\n        map_state\n          (fun ss => match ss with (s1, s2, s3, s4) => (s1, s4, s2, s3) end)\n          (fun ss => match ss with (s1, s2, s3, s4) => (s1, s3, s4, s2) end)\n          c in\n      Concurrency.par_unit c_ui c_server.\n\n    Definition eval (ui_inputs : list UiInput.t) (server_inputs : list ServerInput.t) (entropy : Entropy.t)\n      : list UiOutput.t * list ServerOutput.t :=\n      match snd (eval (todo tt) (Model.Make [], [], [], ui_inputs, server_inputs, entropy)) with\n      | (_, ui_outputs, server_outputs, _, _, _) => (ui_outputs, server_outputs)\n      end.\n\n    Compute eval [] [] (Entropy.random 12).\n    Compute eval [UiInput.Add \"task1\"] [] (Entropy.random 12).\n    Compute eval [UiInput.Add \"task1\"; UiInput.Add \"task2\"] [] Entropy.left.\n    Compute eval [UiInput.Add \"task1\"; UiInput.Add \"task2\"] [] Entropy.right.\n    Compute eval [UiInput.Add \"task1\"; UiInput.Add \"task2\"; UiInput.Add \"task3\"] [] Entropy.left.\n    Compute eval [UiInput.Add \"task1\"; UiInput.Add \"task2\"; UiInput.Add \"task3\"] [] Entropy.right.\n    Compute eval [UiInput.Add \"task1\"; UiInput.Add \"task2\"; UiInput.Add \"task3\"] [] (Entropy.random 10).\n    Compute eval [UiInput.Add \"task1\"; UiInput.Add \"task2\"] [ServerInput.Make [\"task3\"]] Entropy.left.\n    Compute eval [UiInput.Add \"task1\"; UiInput.Add \"task2\"] [ServerInput.Make [\"task3\"]] Entropy.right.\n    Compute eval [UiInput.Add \"task1\"; UiInput.Add \"task2\"] [ServerInput.Make [\"task3\"]] (Entropy.random 10).\n  End TodoManager.\nEnd Test.\n", "meta": {"author": "clarus", "repo": "phd-experiments", "sha": "159d2cae72c363caa39202a7172356c3c47c2e0a", "save_path": "github-repos/coq/clarus-phd-experiments", "path": "github-repos/coq/clarus-phd-experiments/phd-experiments-159d2cae72c363caa39202a7172356c3c47c2e0a/composable-monads/Main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.22062196280627977}}
{"text": "Set Implicit Arguments.\n\nRequire Import ADT.\n\nModule Make (Import E : ADT).\n\n  Require Import AutoSep.\n\n  Require Import Transit.\n  Module Import TransitMake := Make E.\n  Require Import Semantics.\n  Module Import SemanticsMake := Make E.\n\n  Section TopSection.\n\n    Require Import Syntax.\n    Require Import GLabel.\n\n    Definition Env := ((glabel -> option W) * (W -> option Callee))%type.\n\n    Require Import SemanticsExpr.\n  \n    Definition strengthen_op_ax (spec_op : InternalFuncSpec) spec_ax env_ax :=\n      let args := ArgVars spec_op in\n      let rvar := RetVar spec_op in\n      let s := Body spec_op in\n      (forall ins, \n         PreCond spec_ax ins ->\n         length args = length ins) /\\\n      (forall v,\n         TransitSafe spec_ax (map (sel (fst v)) args) (snd v) ->\n         Safe env_ax s v) /\\\n      forall v v', \n        RunsTo env_ax s v v' -> \n        TransitSafe spec_ax (map (sel (fst v)) args) (snd v) ->\n        TransitTo spec_ax (map (sel (fst v)) args) (snd v) (sel (fst v') rvar) (snd v').\n\n    Definition strengthen (env_op env_ax : Env) := \n      (forall lbl, fst env_op lbl = fst env_ax lbl) /\\ \n      let fs_op := snd env_op in\n      let fs_ax := snd env_ax in\n      forall w,\n        fs_op w = fs_ax w \\/\n        exists spec_op spec_ax,\n          fs_op w = Some (Internal spec_op) /\\\n          fs_ax w = Some (Foreign spec_ax) /\\\n          strengthen_op_ax spec_op spec_ax env_ax.\n\n    Hint Unfold RunsTo.\n    Hint Constructors Semantics.RunsTo.\n    Hint Unfold Safe.\n    Hint Constructors Semantics.Safe.\n\n    Require Import GeneralTactics GeneralTactics3.\n\n    Lemma strengthen_runsto : forall env_op s v v', RunsTo env_op s v v' -> forall env_ax, strengthen env_op env_ax -> Safe env_ax s v -> RunsTo env_ax s v v'.\n      induction 1; simpl; intros; unfold_all.\n\n      Focus 7.\n      (* call internal *)\n      generalize H2; intro.\n      unfold strengthen, strengthen_op_ax in H2; openhyp.\n      destruct (H5 (eval (fst v) f)); clear H5.\n\n      eapply RunsToCallInternal; eauto.\n      destruct env_ax; destruct env_op; simpl in *.\n      congruence.\n      eapply IHRunsTo; eauto.\n\n      destruct env_ax; destruct env_op; simpl in *.\n      inv_clear H3; simpl in *.\n      rewrite H6 in H.\n      rewrite H9 in H; injection H; intros; subst.\n      eapply H12.\n      eauto.\n      rewrite H6 in H.\n      rewrite H9 in H; discriminate.\n\n      openhyp.\n      destruct env_ax; destruct env_op; simpl in *.\n      rewrite H in H5; injection H5; intros; subst.\n      eapply IHRunsTo in H4.\n      eapply H9 in H4; clear H9.\n      simpl in *.\n      eapply TransitTo_RunsTo; eauto.\n      simpl in *.\n      rewrite <- H0.\n      eauto.\n      simpl.\n      eauto.\n\n      simpl in *.\n      rewrite H0.\n      eapply Safe_TransitSafe.\n      instantiate (2 := (_, _)).\n      simpl.\n      eauto.\n      eauto.\n      eapply H8.\n      simpl.\n      rewrite H0.\n      eapply Safe_TransitSafe.\n      instantiate (2 := (_, _)).\n      simpl.\n      eauto.\n      eauto.\n\n      Focus 7.\n      (* call foreign *)\n      generalize H6; intro.\n      unfold strengthen, strengthen_op_ax in H6; openhyp.\n      destruct (H9 (eval (fst v) f)); clear H9.\n      eapply RunsToCallForeign; eauto.\n      destruct env_ax; destruct env_op; simpl in *.\n      congruence.\n\n      openhyp.\n      destruct env_ax; destruct env_op; simpl in *.\n      rewrite H in H9; discriminate.\n\n      (* skip *)\n      eauto.\n\n      (* seq *)\n      inv_clear H2.\n      econstructor; eauto.\n      eapply IHRunsTo1; eauto.\n      eapply IHRunsTo2; eauto.\n      eapply H7; eapply IHRunsTo1; eauto.\n\n      (* if true *)\n      inv_clear H2.\n      openhyp.\n      eapply RunsToIfTrue; eauto.\n      eapply IHRunsTo; eauto.\n      rewrite H2 in H; discriminate.\n\n      (* if false *)\n      inv_clear H2.\n      openhyp.\n      rewrite H2 in H; discriminate.\n      eapply RunsToIfFalse; eauto.\n      eapply IHRunsTo; eauto.\n\n      (* while true *)\n      inv_clear H3.\n      eapply RunsToWhileTrue; eauto.\n      eapply IHRunsTo1; eauto.\n      eapply IHRunsTo2; eauto.\n      eapply H9; eapply IHRunsTo1; eauto.\n      rewrite H7 in H; discriminate.\n      \n      (* while false *)\n      eauto.\n\n      (* label *)\n      econstructor.\n      destruct H0.\n      rewrite <- H0.\n      eauto.\n\n      (* assign *)\n      eauto.\n    Qed.\n\n    Lemma strengthen_safe : forall env_ax s v, Safe env_ax s v -> forall env_op, strengthen env_op env_ax -> Safe env_op s v.\n      intros.\n      eapply (Safe_coind (fun s v => Safe env_ax s v)); [ .. | eauto ]; generalize H0; clear; intros.\n\n      Focus 4.\n      inversion H; unfold_all; subst; simpl in *.\n      (* call internal *)\n      generalize H0; intro.\n      unfold strengthen, strengthen_op_ax in H0; openhyp.\n      destruct (H2 (eval (fst v) f)); clear H2.\n      left; descend; eauto.\n      destruct env_ax; destruct env_op; simpl in *.\n      rewrite H3; eauto.\n\n      openhyp.\n      destruct env_ax; destruct env_op; simpl in *.\n      destruct v; simpl in *.\n      rewrite H4 in H3; discriminate.\n\n      (* call foreign *)\n      generalize H0; intro.\n      unfold strengthen, strengthen_op_ax in H0; openhyp.\n      destruct (H2 (eval (fst v) f)); clear H2.\n      right; descend; eauto.\n      destruct env_ax; destruct env_op; simpl in *.\n      rewrite H3; eauto.\n\n      openhyp.\n      destruct env_ax; destruct env_op; simpl in *.\n      destruct v; simpl in *.\n      rewrite H4 in H3; injection H3; intros; subst.\n      left; descend; eauto.\n      Focus 2.\n      eapply H9; simpl; eauto.\n      rewrite H11.\n      unfold TransitSafe.\n      descend; eauto.\n      erewrite H6; eauto.\n      eapply f_equal with (f := @length _) in H5.\n      repeat rewrite map_length in *.\n      eauto.\n      \n      (* seq *)\n      inversion H; unfold_all; subst.\n      descend; eauto.\n      eapply H5; eauto.\n      eapply strengthen_runsto; eauto.\n\n      (* if *)\n      inversion H; unfold_all; subst.\n      eauto.\n\n      (* while *)\n      unfold_all.\n      inversion H; unfold_all; subst.\n      left; descend; eauto.\n      eapply H6; eauto.\n      eapply strengthen_runsto; eauto.\n\n      right; eauto.\n\n      (* label *)\n      inversion H; unfold_all; subst.\n      destruct H0.\n      rewrite H0; eauto.\n\n    Qed.\n\n  End TopSection.\n\nEnd Make.", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/cito/SemanticsFacts4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.22062196280627977}}
{"text": "Require Import erasure.   \nRequire Import SpecImpliesNonSpec.\nRequire Import stepWF. \nRequire Import IndependenceCommon.\nRequire Import nonspeculativeImpliesSpeculative. \n\nTheorem raw_eraseFull : forall H x N tid ds,\n                          raw_heap_lookup x H = Some(sfull COMMIT ds COMMIT tid N) ->\n                          raw_heap_lookup x (raw_eraseHeap H) = Some(pfull (eraseTerm N)). \nProof.\n  induction H; intros. \n  {inv H. }\n  {simpl in *. destruct a. destruct (beq_nat x i) eqn:eq. \n   {inv H0. simpl. rewrite eq. auto. }\n   {apply IHlist in H0. destruct i0. destruct s; eauto. simpl. rewrite eq. eauto. \n    destruct s; eauto. destruct s0; simpl; rewrite eq; eauto. }\n  }\nQed. \n\nTheorem eraseFull : forall H x N tid ds,\n                      heap_lookup x H = Some(sfull COMMIT ds COMMIT tid N) ->\n                      heap_lookup x (eraseHeap H) = Some(pfull (eraseTerm N)). \nProof.\n  intros. destruct H. simpl in *. eapply raw_eraseFull; eauto. \nQed. \n  \n\nLtac existTac e := let n := fresh in\n                   try(assert(n:exists e', eraseTerm e' = e) by apply eTerm; inv n);\n                   try(assert(n:exists e', eraseCtxt e' = e) by apply eCtxt; inv n). \n\nTheorem specErrorParError : forall H T t, \n                       step H T t Error -> \n                       pstep (eraseHeap H) (erasePool T) (erasePool t) pError. \nProof.\n  intros. inv H0. eapply eraseFull in H2. simpl. eapply PPutError.\n  erewrite <- decomposeErase in H1; eauto. simpl. auto. eauto. \nQed. \n\nTheorem ParErrorSpecError : forall H T t H' T' t',\n                              pstep H T t pError -> specHeap H H' -> speculate T T' ->\n                              speculate t t' -> multistep H' (tUnion T' t') None.  \nProof.\n  intros. inv H0. inv H3. inv H7. copy H4. apply decomposeSpec in H4. \n  unfoldTac. eapply specHeapLookupFull in H5; eauto. invertHyp. \n  rewrite Union_associative. eapply Spec.smulti_error. eapply ErrorWrite. \n  simpl in *. eauto. eauto. \nQed.                          \n \nTheorem pmulti_trans : forall H T H' T' c, \n                         pmultistep H T (Some(H', T')) ->\n                         pmultistep H' T' c -> \n                         pmultistep H T c. \nProof.\n  intros. dependent induction H0; eauto. \n  {econstructor. eauto. eauto. }\nQed. \n\nTheorem specErrorParErrorStar : forall H T, \n                              wellFormed H T -> \n                              multistep H T None -> \n                              pmultistep (eraseHeap H) (erasePool T) None. \nProof.\n  intros. remember (@None (sHeap * pool)). induction H1; intros. \n  {inv Heqo. }\n  {subst. copy H1. eapply specImpliesNonSpec in H1; eauto. invertHyp.  \n   rewrite eraseUnionComm. eapply pmulti_trans. eassumption.\n   eapply stepWF in H3; eauto. rewrite <- eraseUnionComm. eapply IHmultistep; eauto. }\n  {eapply specErrorParError in H1; eauto. rewrite eraseUnionComm. \n   eapply pmulti_error. eauto. }\nQed. \n\nTheorem multi_trans : forall H T H' T' c, multistep H T (Some(H', T')) ->  \n                                          multistep H' T' c ->\n                                          multistep H T c. \nProof.\n  intros. remember (Some(H',T')). induction H0. \n  {inv Heqo. auto. }\n  {subst. econstructor. eauto. eauto. }\n  {inv Heqo. }\nQed. \n\nTheorem ParErrorSpecErrorStar : forall H T H' T',\n                                  pmultistep H T None -> specHeap H H' -> heapWF H -> PoolWF T ->\n                                  speculate T T' -> multistep H' T' None. \nProof.\n  intros. genDeps{H'; T'}. dependent induction H0; intros. \n  {copy H0. eapply nonspecImpliesSpec in H0; eauto. invertHyp. \n   eapply pstepWF in H6; eauto. invertHyp. inv H7. econstructor. \n   eauto. eapply multi_trans. eassumption. eapply IHpmultistep; eauto. }\n  {apply specUnionComm in H4. invertHyp. eapply ParErrorSpecError in H0; eauto. }\nQed. \n\n\n\n\n", "meta": {"author": "lexxx320", "repo": "PersonalProjects", "sha": "bc83fb250467b013d9db9fe535ff7bd314632d4c", "save_path": "github-repos/coq/lexxx320-PersonalProjects", "path": "github-repos/coq/lexxx320-PersonalProjects/PersonalProjects-bc83fb250467b013d9db9fe535ff7bd314632d4c/newest/errorIFF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22062196280627974}}
{"text": "Require Import GhostSimulations.\nRequire Import Raft.\n\nRequire Import RaftRefinementInterface.\n\nSection RaftMsgRefinementInterface.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Definition ghost_log : Type := list entry.\n\n  Lemma ghost_log_eq_dec : forall x y : ghost_log, {x = y} + {x <> y}.\n  Proof using. \n    decide equality.\n    apply entry_eq_dec.\n  Qed.\n\n  Definition write_ghost_log (h : name) (st : @data raft_refined_base_params) : ghost_log := log (snd st).\n\n  Instance ghost_log_params : MsgGhostFailureParams raft_refined_failure_params :=\n    {| ghost_msg := ghost_log ;\n       ghost_msg_eq_dec := ghost_log_eq_dec ;\n       ghost_msg_default := [] ;\n       write_ghost_msg := write_ghost_log\n    |}.\n\n  Definition raft_msg_refined_base_params := mgv_refined_base_params.\n  Definition raft_msg_refined_multi_params := mgv_refined_multi_params.\n  Definition raft_msg_refined_failure_params := mgv_refined_failure_params.\n\n  Hint Extern 3 (@BaseParams) => apply raft_msg_refined_base_params : typeclass_instances.\n  Hint Extern 3 (@MultiParams _) => apply raft_msg_refined_multi_params : typeclass_instances.\n  Hint Extern 3 (@FailureParams _ _) => apply raft_msg_refined_failure_params : typeclass_instances.\n\n  Inductive msg_refined_raft_intermediate_reachable : network -> Prop :=\n  | MRRIR_init : msg_refined_raft_intermediate_reachable step_m_init\n  | MRRIR_step_f :\n      forall failed net failed' net' out,\n        msg_refined_raft_intermediate_reachable net ->\n        step_f (failed, net) (failed', net') out ->\n        msg_refined_raft_intermediate_reachable net'\n  | MRRIR_handleInput :\n      forall net h inp gd out d l ps' st',\n        msg_refined_raft_intermediate_reachable net ->\n        handleInput h inp (snd (nwState net h)) = (out, d, l) ->\n        update_elections_data_input h inp (nwState net h) = gd ->\n        (forall h', st' h' = update (nwState net) h (gd, d) h') ->\n        (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                           In p' (send_packets h (add_ghost_msg h (gd, d) l))) ->\n        msg_refined_raft_intermediate_reachable (mkNetwork ps' st')\n  | MRRIR_handleMessage :\n      forall p net xs ys st' ps' gd d l,\n        msg_refined_raft_intermediate_reachable net ->\n        handleMessage (pSrc p) (pDst p) (snd (pBody p)) (snd (nwState net (pDst p))) = (d, l) ->\n        update_elections_data_net (pDst p) (pSrc p) (snd (pBody p)) (nwState net (pDst p)) = gd ->\n        nwPackets net = xs ++ p :: ys ->\n        (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n        (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                           In p' (send_packets (pDst p) (@add_ghost_msg _ _ _ ghost_log_params (pDst p) (gd, d) l))) ->\n        msg_refined_raft_intermediate_reachable (mkNetwork ps' st')\n  | MRRIR_doLeader :\n      forall net st' ps' h os gd d d' ms,\n        msg_refined_raft_intermediate_reachable net ->\n        doLeader d h = (os, d', ms) ->\n        nwState net h = (gd, d) ->\n        (forall h', st' h' = update (nwState net) h (gd, d') h') ->\n        (forall p, In p ps' -> In p (nwPackets net) \\/\n                         In p (send_packets h (add_ghost_msg h (gd, d') ms))) ->\n        msg_refined_raft_intermediate_reachable (mkNetwork ps' st')\n  | MRRIR_doGenericServer :\n      forall net st' ps' os gd d d' ms h,\n        msg_refined_raft_intermediate_reachable net ->\n        doGenericServer h d = (os, d', ms) ->\n        nwState net h = (gd, d) ->\n        (forall h', st' h' = update (nwState net) h (gd, d') h') ->\n        (forall p, In p ps' -> In p (nwPackets net) \\/\n                         In p (send_packets h (add_ghost_msg h (gd, d') ms))) ->\n        msg_refined_raft_intermediate_reachable (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_client_request (P : network -> Prop) :=\n    forall h net st' ps' gd out d l client id c,\n      handleClientRequest h (snd (nwState net h)) client id c = (out, d, l) ->\n      gd = update_elections_data_client_request h (nwState net h) client id c ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      (forall h', st' h' = update (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                         In p' (send_packets h (add_ghost_msg h (gd, d) l))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_timeout (P : network -> Prop) :=\n    forall net h st' ps' gd out d l,\n      handleTimeout h (snd (nwState net h)) = (out, d, l) ->\n      gd = update_elections_data_timeout h (nwState net h) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      (forall h', st' h' = update (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                               In p' (send_packets h (add_ghost_msg h (gd, d) l))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_append_entries (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t n pli plt es ci,\n      handleAppendEntries (pDst p) (snd (nwState net (pDst p))) t n pli plt es ci = (d, m) ->\n      gd = update_elections_data_appendEntries (pDst p) (nwState net (pDst p)) t n pli plt es ci ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         p' = mkPacket (pDst p) (pSrc p) (write_ghost_log (pDst p) (gd, d), m)) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_append_entries_reply (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t es res,\n      handleAppendEntriesReply (pDst p) (snd (nwState net (pDst p))) (pSrc p) t es res = (d, m) ->\n      gd = (fst (nwState net (pDst p))) ->\n      snd (pBody p) = AppendEntriesReply t es res ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         In p' (send_packets (pDst p) (@add_ghost_msg _ _ _ ghost_log_params (pDst p) (gd, d) m))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_request_vote (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t cid lli llt,\n      handleRequestVote (pDst p) (snd (nwState net (pDst p))) t (pSrc p) lli llt  = (d, m) ->\n      gd = update_elections_data_requestVote (pDst p) (pSrc p) t (pSrc p) lli llt (nwState net (pDst p)) ->\n      snd (pBody p) = RequestVote t cid lli llt ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         p' = mkPacket (pDst p) (pSrc p) (write_ghost_log (pDst p) (gd, d), m)) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_request_vote_reply (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d t v,\n      handleRequestVoteReply (pDst p) (snd (nwState net (pDst p))) (pSrc p) t v = d ->\n      gd = update_elections_data_requestVoteReply (pDst p) (pSrc p) t v (nwState net (pDst p)) ->\n      snd (pBody p) = RequestVoteReply t v ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys)) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_do_leader (P : network -> Prop) :=\n    forall net st' ps' gd d h os d' ms,\n      doLeader d h = (os, d', ms) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwState net h = (gd, d) ->\n      (forall h', st' h' = update (nwState net) h (gd, d') h') ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/\n                             In p (send_packets h (add_ghost_msg h (gd, d') ms))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_do_generic_server (P : network -> Prop) :=\n    forall net st' ps' gd d os d' ms h,\n      doGenericServer h d = (os, d', ms) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwState net h = (gd, d) ->\n      (forall h', st' h' = update (nwState net) h (gd, d') h') ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/\n                             In p (send_packets h (add_ghost_msg h (gd, d') ms))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_state_same_packet_subset (P : network -> Prop) :=\n    forall net net',\n      (forall h, nwState net h = nwState net' h) ->\n      (forall p, In p (nwPackets net') -> In p (nwPackets net)) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      P net'.\n\n  Definition msg_refined_raft_net_invariant_reboot (P : network -> Prop) :=\n    forall net net' gd d h d',\n      reboot d = d' ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      nwState net h = (gd, d) ->\n      (forall h', nwState net' h' = update (nwState net) h (gd, d') h') ->\n      nwPackets net = nwPackets net' ->\n      P net'.\n\n  Definition msg_refined_raft_net_invariant_init (P : network -> Prop) :=\n    P step_m_init.\n  \n  Definition msg_refined_raft_net_invariant_client_request' (P : network -> Prop) :=\n    forall h net st' ps' gd out d l client id c,\n      handleClientRequest h (snd (nwState net h)) client id c = (out, d, l) ->\n      gd = update_elections_data_client_request h (nwState net h) client id c ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      (forall h', st' h' = update (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                         In p' (send_packets h (add_ghost_msg h (gd, d) l))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_timeout' (P : network -> Prop) :=\n    forall net h st' ps' gd out d l,\n      handleTimeout h (snd (nwState net h)) = (out, d, l) ->\n      gd = update_elections_data_timeout h (nwState net h) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      (forall h', st' h' = update (nwState net) h (gd, d) h') ->\n      (forall p', In p' ps' -> In p' (nwPackets net) \\/\n                               In p' (send_packets h (add_ghost_msg h (gd, d) l))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_append_entries' (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t n pli plt es ci,\n      handleAppendEntries (pDst p) (snd (nwState net (pDst p))) t n pli plt es ci = (d, m) ->\n      gd = update_elections_data_appendEntries (pDst p) (nwState net (pDst p)) t n pli plt es ci ->\n      snd (pBody p) = AppendEntries t n pli plt es ci ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         p' = mkPacket (pDst p) (pSrc p) (write_ghost_log (pDst p) (gd, d), m)) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_append_entries_reply' (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t es res,\n      handleAppendEntriesReply (pDst p) (snd (nwState net (pDst p))) (pSrc p) t es res = (d, m) ->\n      gd = (fst (nwState net (pDst p))) ->\n      snd (pBody p) = AppendEntriesReply t es res ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         In p' (send_packets (pDst p) (@add_ghost_msg _ _ _ ghost_log_params (pDst p) (gd, d) m))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_request_vote' (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d m t cid lli llt,\n      handleRequestVote (pDst p) (snd (nwState net (pDst p))) t (pSrc p) lli llt  = (d, m) ->\n      gd = update_elections_data_requestVote (pDst p) (pSrc p) t (pSrc p) lli llt (nwState net (pDst p)) ->\n      snd (pBody p) = RequestVote t cid lli llt ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys) \\/\n                         p' = mkPacket (pDst p) (pSrc p) (write_ghost_log (pDst p) (gd, d), m)) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_request_vote_reply' (P : network -> Prop) :=\n    forall xs p ys net st' ps' gd d t v,\n      handleRequestVoteReply (pDst p) (snd (nwState net (pDst p))) (pSrc p) t v = d ->\n      gd = update_elections_data_requestVoteReply (pDst p) (pSrc p) t v (nwState net (pDst p)) ->\n      snd (pBody p) = RequestVoteReply t v ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      nwPackets net = xs ++ p :: ys ->\n      (forall h, st' h = update (nwState net) (pDst p) (gd, d) h) ->\n      (forall p', In p' ps' -> In p' (xs ++ ys)) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_do_leader' (P : network -> Prop) :=\n    forall net st' ps' gd d h os d' ms,\n      doLeader d h = (os, d', ms) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      nwState net h = (gd, d) ->\n      (forall h', st' h' = update (nwState net) h (gd, d') h') ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/\n                             In p (send_packets h (add_ghost_msg h (gd, d') ms))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_do_generic_server' (P : network -> Prop) :=\n    forall net st' ps' gd d os d' ms h,\n      doGenericServer h d = (os, d', ms) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable (mkNetwork ps' st') ->\n      nwState net h = (gd, d) ->\n      (forall h', st' h' = update (nwState net) h (gd, d') h') ->\n      (forall p, In p ps' -> In p (nwPackets net) \\/\n                             In p (send_packets h (add_ghost_msg h (gd, d') ms))) ->\n      P (mkNetwork ps' st').\n\n  Definition msg_refined_raft_net_invariant_state_same_packet_subset' (P : network -> Prop) :=\n    forall net net',\n      (forall h, nwState net h = nwState net' h) ->\n      (forall p, In p (nwPackets net') -> In p (nwPackets net)) ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      P net'.\n\n  Definition msg_refined_raft_net_invariant_reboot' (P : network -> Prop) :=\n    forall net net' gd d h d',\n      reboot d = d' ->\n      P net ->\n      msg_refined_raft_intermediate_reachable net ->\n      msg_refined_raft_intermediate_reachable net' ->\n      nwState net h = (gd, d) ->\n      (forall h', nwState net' h' = update (nwState net) h (gd, d') h') ->\n      nwPackets net = nwPackets net' ->\n      P net'.\n\n  Lemma msg_refined_raft_net_invariant_client_request'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_client_request net ->\n      msg_refined_raft_net_invariant_client_request' net.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_client_request, msg_refined_raft_net_invariant_client_request'.\n    intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_timeout'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_timeout net ->\n      msg_refined_raft_net_invariant_timeout' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_timeout, msg_refined_raft_net_invariant_timeout'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_append_entries'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_append_entries net ->\n      msg_refined_raft_net_invariant_append_entries' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_append_entries, msg_refined_raft_net_invariant_append_entries'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_append_entries_reply'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_append_entries_reply net ->\n      msg_refined_raft_net_invariant_append_entries_reply' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_append_entries_reply, msg_refined_raft_net_invariant_append_entries_reply'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_request_vote'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_request_vote net ->\n      msg_refined_raft_net_invariant_request_vote' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_request_vote, msg_refined_raft_net_invariant_request_vote'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_request_vote_reply'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_request_vote_reply net ->\n      msg_refined_raft_net_invariant_request_vote_reply' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_request_vote_reply, msg_refined_raft_net_invariant_request_vote_reply'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_do_leader'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_do_leader net ->\n      msg_refined_raft_net_invariant_do_leader' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_do_leader, msg_refined_raft_net_invariant_do_leader'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_do_generic_server'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_do_generic_server net ->\n      msg_refined_raft_net_invariant_do_generic_server' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_do_generic_server, msg_refined_raft_net_invariant_do_generic_server'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_reboot'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_reboot net ->\n      msg_refined_raft_net_invariant_reboot' net.\n    Proof using. \n      unfold msg_refined_raft_net_invariant_reboot, msg_refined_raft_net_invariant_reboot'.\n      intuition eauto.\n  Qed.\n\n  Lemma msg_refined_raft_net_invariant_subset'_weak :\n    forall net,\n      msg_refined_raft_net_invariant_state_same_packet_subset net ->\n      msg_refined_raft_net_invariant_state_same_packet_subset' net.\n  Proof using. \n    unfold msg_refined_raft_net_invariant_state_same_packet_subset, msg_refined_raft_net_invariant_state_same_packet_subset'.\n    intuition eauto.\n  Qed.\n\n\n  Class raft_msg_refinement_interface : Prop :=\n    {\n      msg_refined_raft_net_invariant :\n        forall P net,\n          msg_refined_raft_net_invariant_init P ->\n          msg_refined_raft_net_invariant_client_request P ->\n          msg_refined_raft_net_invariant_timeout P ->\n          msg_refined_raft_net_invariant_append_entries P ->\n          msg_refined_raft_net_invariant_append_entries_reply P ->\n          msg_refined_raft_net_invariant_request_vote P ->\n          msg_refined_raft_net_invariant_request_vote_reply P ->\n          msg_refined_raft_net_invariant_do_leader P ->\n          msg_refined_raft_net_invariant_do_generic_server P ->\n          msg_refined_raft_net_invariant_state_same_packet_subset P ->\n          msg_refined_raft_net_invariant_reboot P ->\n          msg_refined_raft_intermediate_reachable net ->\n          P net;\n      msg_refined_raft_net_invariant' :\n        forall P net,\n          msg_refined_raft_net_invariant_init P ->\n          msg_refined_raft_net_invariant_client_request' P ->\n          msg_refined_raft_net_invariant_timeout' P ->\n          msg_refined_raft_net_invariant_append_entries' P ->\n          msg_refined_raft_net_invariant_append_entries_reply' P ->\n          msg_refined_raft_net_invariant_request_vote' P ->\n          msg_refined_raft_net_invariant_request_vote_reply' P ->\n          msg_refined_raft_net_invariant_do_leader' P ->\n          msg_refined_raft_net_invariant_do_generic_server' P ->\n          msg_refined_raft_net_invariant_state_same_packet_subset' P ->\n          msg_refined_raft_net_invariant_reboot' P ->\n          msg_refined_raft_intermediate_reachable net ->\n          P net;\n      msg_lift_prop :\n        forall (P : _ -> Prop),\n          (forall net, refined_raft_intermediate_reachable net -> P net) ->\n          (forall net, msg_refined_raft_intermediate_reachable net -> P (mgv_deghost net));\n      msg_lift_prop_all_the_way :\n        forall (P : _ -> Prop),\n          (forall net, raft_intermediate_reachable net -> P net) ->\n          (forall (net : @network _ raft_msg_refined_multi_params), msg_refined_raft_intermediate_reachable net -> P (deghost (mgv_deghost net)));\n      msg_lower_prop :\n        forall P : _ -> Prop,\n          (forall net, msg_refined_raft_intermediate_reachable net -> P (mgv_deghost net)) ->\n          (forall net, refined_raft_intermediate_reachable net -> P net);\n      msg_lower_prop_all_the_way :\n        forall P : _ -> Prop,\n          (forall (net : @network _ raft_msg_refined_multi_params), msg_refined_raft_intermediate_reachable net -> P (deghost (mgv_deghost net))) ->\n          (forall net, raft_intermediate_reachable net -> P net);\n      msg_deghost_spec :\n        forall (net : @network _ raft_msg_refined_multi_params) h,\n          nwState (mgv_deghost net) h = nwState net h;\n      msg_simulation_1 :\n        forall net,\n          msg_refined_raft_intermediate_reachable net ->\n          refined_raft_intermediate_reachable (mgv_deghost net)\n    }.\n\n\nEnd RaftMsgRefinementInterface.\n\nHint Extern 3 (@BaseParams) => apply raft_msg_refined_base_params : typeclass_instances.\nHint Extern 3 (@MultiParams _) => apply raft_msg_refined_multi_params : typeclass_instances.\nHint Extern 3 (@FailureParams _ _) => apply raft_msg_refined_failure_params : typeclass_instances.", "meta": {"author": "ahmet-celik", "repo": "pverdi", "sha": "dc88c4a5fd7d90b5bb48e583bd8286097f983f81", "save_path": "github-repos/coq/ahmet-celik-pverdi", "path": "github-repos/coq/ahmet-celik-pverdi/pverdi-dc88c4a5fd7d90b5bb48e583bd8286097f983f81/raft/RaftMsgRefinementInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.607663184043154, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.22056301894827596}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\nRequire Import Setoid.\nRequire Import ZArith.\nRequire Import Psatz.\n\n\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith. \n\nLocal Open Scope struct_scope.\n\nRequire Import FinProof.CommonProofs.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolClass.\nRequire Import depoolContract.SolidityNotations.\n\nRequire Import depoolContract.NewProofs.ProofHelpers.\nRequire Import depoolContract.DePoolFunc.\n\n(* Set Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100. *)\n\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\nRequire Import depoolContract.Lib.CommonCommon.\n\n(* Require Import MultiSigWallet.Proofs.tvmFunctionsProofs. *)\n\nImport DePoolSpec.LedgerClass.SolidityNotations. \n\nRequire Import depoolContract.Lib.CommonStateProofs.\n\nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope solidity_scope.\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\n\nRequire Import depoolContract.DePoolConsts.\nModule DePoolContract_Ф_sendAcceptAndReturnChange (dc : DePoolConstsTypesSig XTypesSig StateMonadSig).\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig dc.\nModule ProofHelpers := ProofHelpers dc.\n\nImport dc.\nImport ProofHelpers.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\n\n\nOpaque Z.eqb Z.add Z.sub Z.div Z.mul hmapLookup hmapInsert Z.ltb Z.geb Z.leb Z.gtb Z.modulo deleteListPair.\n\n(* function sendAcceptAndReturnChange() private { \n  IParticipant(msg.sender).receiveAnswer{value: 0, bounce: false, flag: 64}(STATUS_SUCCESS, 0); \n} *) \n\nLemma DePoolContract_Ф_sendAcceptAndReturnChange_exec : forall (l: Ledger) ,\nlet oldMessages := eval_state ( ↑16 ε VMState_ι_messages) l in\nlet newMessage  := {| contractAddress  := eval_state msg_sender l ;\n                      contractFunction := IParticipant_И_receiveAnswerF DePool_ι_STATUS_SUCCESS 0 ;\n                      contractMessage  := {$ default with (messageValue , 0) ;\n                                                          (messageBounce , false) ;\n                                                          (messageFlag , 64) $} |}  in \nexec_state ( ↓ DePoolContract_Ф_sendAcceptAndReturnChange ) l =  {$ l With VMState_ι_messages := newMessage :: oldMessages $} .  \n\nProof.\n  intros. destruct l. auto. \nQed. \n\nLemma DePoolContract_Ф_sendAcceptAndReturnChange_eval : forall ( l: Ledger ) ,\neval_state ( ↓ DePoolContract_Ф_sendAcceptAndReturnChange ) l = I .\nProof.\n  intros. destruct l. auto. \nQed. \n\n\n\nEnd DePoolContract_Ф_sendAcceptAndReturnChange.", "meta": {"author": "Pruvendo", "repo": "depool_contract", "sha": "6afe23011d62f65921ac2493df691ab888ffeb95", "save_path": "github-repos/coq/Pruvendo-depool_contract", "path": "github-repos/coq/Pruvendo-depool_contract/depool_contract-6afe23011d62f65921ac2493df691ab888ffeb95/src/NewProofs/DePoolContract_sendAcceptAndReturnChange.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.22056254635197062}}
{"text": "From ITree Require Import ITree.\nFrom Paco Require Import paco.\nFrom compcert Require Import Integers.\n\nRequire Import sflib.\n\nRequire Import StdlibExt.\nRequire Import IntegersExt.\nRequire Import ConvC2ITree.\nRequire Import SyncSysModel.\n\nRequire Import Executable.\nRequire Import PALSSystem.\n\nRequire master worker.\n\nFrom Coq Require Extraction ExtrOcamlBasic ExtrOcamlString.\n\nRequire Import ZArith List Lia.\n\nDefinition resize_bytes: bytes -> bytes? :=\n  (fun bs => Some (RTSysEnv.resize_bytes 2 bs)).\n\nDefinition max_num_tasks: nat := 16.\nDefinition msg_size_k: Z := 1.\nDefinition msg_size: Z := 2.\n\nDefinition oapp_mast: AppMod.t ? :=\n  cprog2app master.prog max_num_tasks msg_size_k msg_size.\nDefinition oapp_work (tid: Z): AppMod.t ? :=\n  cprog2app (worker.prog tid) max_num_tasks msg_size_k msg_size.\n\nDefinition JobDistr_period: Z := 1000000000.\n\nDefinition app_system : ExecutableSpec.t :=\n  let apps :=\n      match deopt_list\n              [oapp_mast; oapp_work 1; oapp_work 2;\n              oapp_work 3; oapp_work 4; oapp_work 5;\n              oapp_work 6; oapp_work 7; oapp_work 8] with\n      | None => []\n      | Some apps => apps\n      end\n  in\n  ExecutableSpec.mk _ _ JobDistr_period\n                    apps [[0;1;2;3;4;5;6;7;8]]\n                    resize_bytes.\n\nDefinition app_system_itree: Z -> option Z -> itree _ unit :=\n  @ExecutableSpec.sys_itree _ _ app_system.\n\nCd \"./extr/job_assn_c2itree\".\nExtraction \"AppSystem.ml\" app_system app_system_itree.\nCd \"../..\".\n", "meta": {"author": "kim-yoonseung", "repo": "pals-thesis-dev", "sha": "1a165028f5461ed4d00a1e2720b3b1e4542f5dc2", "save_path": "github-repos/coq/kim-yoonseung-pals-thesis-dev", "path": "github-repos/coq/kim-yoonseung-pals-thesis-dev/pals-thesis-dev-1a165028f5461ed4d00a1e2720b3b1e4542f5dc2/extr/job_assn_c2itree/ExtractJobAssn_C2ITree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2205625463519706}}
{"text": "(* -------------------------------------------------------------------- *)\nFrom mathcomp Require Import all_ssreflect all_algebra.\nFrom mathcomp Require Import word_ssrZ.\nRequire Import utils oseq strings word memory_model global Utf8 Relation_Operators sem_type syscall label.\nRequire Import\n  flag_combination\n  shift_kind.\n\nSet   Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* -------------------------------------------------------------------- *)\n(* String representation of architecture components.\n * ToString is a class for types that have a string representation and a\n * particular stype, such as registers (represented as \"RAX\", \"RSP\", etc.\n * with sword U64 being the associated stype) or flags (represented as \"CF\",\n * \"ZF\", with sbool the associated stype).\n *)\nClass ToString (t: stype) (T: Type) :=\n  { category      : string    (* Name of the \"register\" used to print errors. *)\n  ; _finC         :> finTypeC T\n  ; to_string     : T -> string\n  ; strings       : list (string * T)\n  ; inj_to_string : injective to_string\n  ; stringsE      : strings = [seq (to_string x, x) | x <- enum cfinT_finType]\n  }.\n\nDefinition rtype {t T} `{ToString t T} := t.\n\n\n(* -------------------------------------------------------------------- *)\n(* Basic architecture declaration.\n * Parameterized by types for registers, extra registers, flags, and conditions.\n *)\nClass arch_decl (reg regx xreg rflag cond : Type) :=\n  { reg_size : wsize     (* Register size. Also used as pointer size. *)\n  ; xreg_size : wsize    (* Extended registers size. *)\n  ; cond_eqC :> eqTypeC cond\n  ; toS_r :> ToString (sword reg_size) reg\n  ; toS_rx :> ToString (sword reg_size) regx\n  ; toS_x :> ToString (sword xreg_size) xreg\n  ; toS_f :> ToString sbool rflag\n  ; reg_size_neq_xreg_size : reg_size != xreg_size\n  ; ad_rsp : reg\n  ; inj_toS_reg_regx : forall (r:reg) (rx:regx), to_string r <> to_string rx\n  ; ad_fcp :> FlagCombinationParams\n  }.\n\n#[global]\nInstance arch_pd `{arch_decl} : PointerData := { Uptr := reg_size }.\n\nDefinition mk_ptr `{arch_decl} name :=\n  {| vtype := sword Uptr; vname := name; |}.\n\n(* FIXME ARM : Try to not use this projection *)\nDefinition reg_t   {reg regx xreg rflag cond} `{arch : arch_decl reg regx xreg rflag cond} := reg.\nDefinition regx_t  {reg regx xreg rflag cond} `{arch : arch_decl reg regx xreg rflag cond} := regx.\nDefinition xreg_t  {reg regx xreg rflag cond} `{arch : arch_decl reg regx xreg rflag cond} := xreg.\nDefinition rflag_t {reg regx xreg rflag cond} `{arch : arch_decl reg regx xreg rflag cond} := rflag.\nDefinition cond_t  {reg regx xreg rflag cond} `{arch : arch_decl reg regx xreg rflag cond} := cond.\n\nSection DECL.\n\nContext {reg regx xreg rflag cond} `{arch : arch_decl reg regx xreg rflag cond}.\n\nDefinition sreg := sword reg_size.\nDefinition wreg := sem_t sreg.\nDefinition sxreg := sword xreg_size.\nDefinition wxreg := sem_t sxreg.\n\nLemma sword_reg_neq_xreg :\n  sreg != sxreg.\nProof.\n  apply/eqP. move=> []. apply/eqP. exact: reg_size_neq_xreg_size.\nQed.\n\n(* -------------------------------------------------------------------- *)\n(* Addresses.\n * An address consists of\n *   - A displacement (an immediate value).\n *   - A base (a register).\n *   - A scale.\n *   - An offset (a register).\n * The effective address is displacement + base + offset * scale.\n *)\nRecord reg_address : Type := mkAddress\n  { ad_disp   : pointer\n  ; ad_base   : option reg_t\n  ; ad_scale  : nat\n  ; ad_offset : option reg_t\n  }.\n\nVariant address :=\n| Areg of reg_address (* Absolute address. *)\n| Arip of pointer.    (* Address relative to instruction pointer. *)\n\nDefinition oeq_reg (x y:option reg_t) :=\n  @eq_op (option_eqType ceqT_eqType) x y.\n\nDefinition reg_address_beq (addr1: reg_address) addr2 :=\n  match addr1, addr2 with\n  | mkAddress d1 b1 s1 o1, mkAddress d2 b2 s2 o2 =>\n    [&& d1 == d2, oeq_reg b1 b2, s1 == s2 & oeq_reg o1 o2]\n  end.\n\nLemma reg_address_eq_axiom : Equality.axiom reg_address_beq.\nProof.\ncase=> [d1 b1 s1 o1] [d2 b2 s2 o2]; apply: (iffP idP) => /=.\n+ by case/and4P ; do 4! move/eqP=> ->.\nby case; do 4! move=> ->; rewrite /oeq_reg !eqxx.\nQed.\n\nDefinition reg_address_eqMixin := Equality.Mixin reg_address_eq_axiom.\nCanonical reg_address_eqType := EqType reg_address reg_address_eqMixin.\n\n(* -------------------------------------------------------------------- *)\n\nDefinition address_beq (addr1: address) addr2 :=\n  match addr1, addr2 with\n  | Areg ra1, Areg ra2 => ra1 == ra2\n  | Arip p1, Arip p2   => p1 == p2\n  | _, _ => false\n  end.\n\nLemma address_eq_axiom : Equality.axiom address_beq.\nProof.\n  by case=> []? []? /=; (constructor || apply: reflect_inj eqP => ?? []).\nQed.\n\nDefinition address_eqMixin := Equality.Mixin address_eq_axiom.\nCanonical address_eqType := EqType address address_eqMixin.\n\n(* -------------------------------------------------------------------- *)\n(* Arguments to assembly instructions. *)\nVariant asm_arg : Type :=\n| Condt  of cond_t\n| Imm ws of word ws\n| Reg    of reg_t\n| Regx   of regx_t\n| Addr   of address\n| XReg   of xreg_t.\n\nDefinition asm_args := (seq asm_arg).\n\nDefinition is_Condt (a : asm_arg) : option cond_t :=\n  if a is Condt c then Some c else None.\n\nDefinition asm_arg_beq (a1 a2:asm_arg) :=\n  match a1, a2 with\n  | Condt t1, Condt t2 => t1 == t2 ::>\n  | Imm sz1 w1, Imm sz2 w2 => (sz1 == sz2) && (wunsigned w1 == wunsigned w2)\n  | Reg r1, Reg r2     => r1 == r2 ::>\n  | Regx r1, Regx r2   => r1 == r2 ::>\n  | Addr a1, Addr a2   => a1 == a2\n  | XReg r1, XReg r2   => r1 == r2 ::>\n  | _, _ => false\n  end.\n\nDefinition Imm_inj sz sz' w w' (e: @Imm sz w = @Imm sz' w') :\n  ∃ e : sz = sz', eq_rect sz (λ s, (word s)) w sz' e = w' :=\n  let 'Logic.eq_refl := e in (ex_intro _ erefl erefl).\n\nLemma asm_arg_eq_axiom : Equality.axiom asm_arg_beq.\nProof.\n  case => [t1 | sz1 w1 | r1 | r1 | a1 | xr1] [t2 | sz2 w2 | r2 | r2 | a2 | xr2] /=;\n    try by (constructor || apply: reflect_inj eqP => ?? []).\n  apply: (iffP idP) => //=.\n  + by move=> /andP [] /eqP ? /eqP; subst => /wunsigned_inj ->.\n  by move=> /Imm_inj [? ];subst => /= ->;rewrite !eqxx.\nQed.\n\nDefinition asm_arg_eqMixin := Equality.Mixin asm_arg_eq_axiom.\nCanonical asm_arg_eqType := EqType asm_arg asm_arg_eqMixin.\n\n(* -------------------------------------------------------------------- *)\n(* Writing a large word to register or memory\n * When writing to a register, depending on the instruction,\n * the most significant bits are either preserved or cleared.\n *)\nVariant msb_flag : Type :=\n| MSB_CLEAR\n| MSB_MERGE.\n\nScheme Equality for msb_flag.\n\nLemma msb_flag_eq_axiom : Equality.axiom msb_flag_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_msb_flag_dec_bl.\n  by apply: internal_msb_flag_dec_lb.\nQed.\n\nDefinition msb_flag_eqMixin := Equality.Mixin msb_flag_eq_axiom.\nCanonical msb_flag_eqType := EqType msb_flag msb_flag_eqMixin.\n\n(* -------------------------------------------------------------------- *)\n(* Implicit arguments.\n * Assembly instructions may have implicit arguments, such as flags if\n * they are set by the instruction.\n *)\nVariant implicit_arg : Type :=\n| IArflag of rflag_t  (* Implicit flag. *)\n| IAreg   of reg_t.   (* Implicit register. *)\n\nDefinition implicit_arg_beq (i1 i2 : implicit_arg) :=\n  match i1, i2 with\n  | IArflag f1, IArflag f2 => f1 == f2 ::>\n  | IAreg r1, IAreg r2 => r1 == r2 ::>\n  | _, _ => false\n  end.\n\nLemma implicit_arg_eq_axiom : Equality.axiom implicit_arg_beq.\nProof.\n  by case=> []? []? /=; (constructor || apply: reflect_inj eqP => ?? []).\nQed.\n\nDefinition implicit_arg_eqMixin := Equality.Mixin implicit_arg_eq_axiom.\nCanonical implicit_arg_eqType := EqType _ implicit_arg_eqMixin.\n\n(* -------------------------------------------------------------------- *)\n(* Address kinds.\n * An address argument may be used in two ways:\n * - To compute the effective address (such as in LEA in x86, or ADR in ARMv7).\n * - To load data from memory.\n *)\nVariant addr_kind : Type :=\n| AK_compute (* Only compute the address. *)\n| AK_mem.    (* Compute the address and load from memory. *)\n\nScheme Equality for addr_kind.\n\nLemma addr_kind_eq_axiom : Equality.axiom addr_kind_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_addr_kind_dec_bl.\n  by apply: internal_addr_kind_dec_lb.\nQed.\n\nDefinition addr_kind_eqMixin := Equality.Mixin addr_kind_eq_axiom.\nCanonical addr_kind_eqType := EqType _ addr_kind_eqMixin.\n\n(* -------------------------------------------------------------------- *)\n(* Argument description.\n * An argument may be either implicit or explicit.\n *)\nVariant arg_desc :=\n| ADImplicit of implicit_arg\n| ADExplicit\n    of addr_kind      (* If argument is an address, should it be loaded? *)\n     & nat            (* Position of the argument in assembly syntax. *)\n     & option reg_t.  (* Set if there is only one valid register. *)\n\nDefinition arg_desc_beq (d1 d2 : arg_desc) :=\n  match d1, d2 with\n  | ADImplicit i1, ADImplicit i2 => i1 == i2\n  | ADExplicit k1 n1 or1, ADExplicit k2 n2 or2 =>\n    (k1 == k2) && (n1 == n2) && (or1 == or2 :> option_eqType ceqT_eqType)\n  | _, _ => false\n  end.\n\nLemma arg_desc_eq_axiom : Equality.axiom arg_desc_beq.\nProof.\n  case=> [i1|k1 n1 or1] [i2|k2 n2 or2] /=;\n    try by (constructor || apply: reflect_inj eqP => ?? []).\n  do! (case: eqP; try by constructor; congruence).\nQed.\n\nDefinition arg_desc_eqMixin := Equality.Mixin arg_desc_eq_axiom.\nCanonical  arg_desc_eqType  := EqType arg_desc arg_desc_eqMixin.\n\nDefinition F  f   := ADImplicit (IArflag f).\nDefinition R  r   := ADImplicit (IAreg   r).\nDefinition E  n   := ADExplicit AK_mem n None.\nDefinition Ec n   := ADExplicit AK_compute n None.\nDefinition Ef n r := ADExplicit AK_mem n (Some  r).\n\nDefinition check_oreg or ai :=\n  match or, ai with\n  | Some r, Reg r'  => r == r' ::>\n  | Some _, Imm _ _ => true\n  | Some _, _       => false\n  | None, _         => true\n  end.\n\n(* -------------------------------------------------------------------- *)\n(* Argument kinds.\n * Types for arguments of assembly instructions.\n *)\nVariant arg_kind :=\n| CAcond\n| CAreg\n| CAregx\n| CAxmm\n| CAmem of bool (* true if Global is allowed *)\n| CAimm of wsize.\n\nScheme Equality for arg_kind.\n\nLemma arg_kind_eq_axiom : Equality.axiom arg_kind_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_arg_kind_dec_bl.\n  by apply: internal_arg_kind_dec_lb.\nQed.\n\nDefinition arg_kind_eqMixin := Equality.Mixin arg_kind_eq_axiom.\nCanonical  arg_kind_eqType  := EqType _ arg_kind_eqMixin.\n\n\n(* An argument position where different argument kinds are allowed is\n * represented by a list of these kinds.\n * For instance, a position taking a register or an immediate is represented\n * by [:: CAreg; CAimm ] : arg_kinds.\n * This is a disjunction of the possible kinds for a position.\n*)\nDefinition arg_kinds := seq arg_kind.\n\n(* Each argument position has a description.\n * For instance [:: a0; a1; a2 ] is a description where the first argument\n * is described by the arg_kind a0, the second by a1 and the third by a2.\n * This is a conjunction of argument descriptions.\n *)\nDefinition args_kinds := seq arg_kinds.\n\n(* An assembly instruction may take different number of arguments.\n * For instance, an instruction may take two registers, add their values\n * and write to the first, or take three registers, add two and store the\n * result to the third.\n * This is a disjunction of these signatures.\n *)\nDefinition i_args_kinds := seq args_kinds.\n\nDefinition check_arg_kind (a:asm_arg) (cond: arg_kind) :=\n  match a, cond with\n  | Condt _, CAcond => true\n  | Imm sz _, CAimm sz' => sz == sz'\n  | Reg _ , CAreg => true\n  | Regx _, CAregx => true\n  | Addr _, CAmem _ => true\n  | XReg _, CAxmm   => true\n  | _, _ => false\n  end.\n\nDefinition check_arg_kinds (a:asm_arg) (cond:arg_kinds) :=\n  has (check_arg_kind a) cond.\n\nDefinition check_args_kinds (a:asm_args) (cond:args_kinds) :=\n all2 check_arg_kinds a cond.\n\nDefinition check_i_args_kinds (cond:i_args_kinds) (a:asm_args) :=\n  has (check_args_kinds a) cond.\n\nDefinition check_arg_dest (ad:arg_desc) (ty:stype) :=\n  match ad with\n  | ADImplicit _ => true\n  | ADExplicit _ _ _ => ty != sbool\n  end.\n\n(* -------------------------------------------------------------------- *)\nVariant pp_asm_op_ext :=\n  | PP_error\n  | PP_name\n  | PP_iname   of wsize\n  | PP_iname2  of string & wsize & wsize\n  | PP_viname  of velem & bool (* long *)\n  | PP_viname2 of velem & velem (* source and target element sizes *)\n  | PP_ct      of asm_arg.\n\nRecord pp_asm_op := mk_pp_asm_op {\n  pp_aop_name : string;\n  pp_aop_ext  : pp_asm_op_ext;\n  pp_aop_args : seq (wsize * asm_arg);\n}.\n\n(* -------------------------------------------------------------------- *)\n(* Instruction descriptions. *)\nRecord instr_desc_t := {\n  (* Info for architecture semantics. *)\n  (* When writing a smaller value to a register, keep or clear old bits? *)\n  id_msb_flag   : msb_flag;\n  (* Types of input arguments. *)\n  id_tin        : seq stype;\n  (* Description of input arguments. *)\n  id_in         : seq arg_desc;\n  (* Types of output arguments. *)\n  id_tout       : seq stype;\n  (* Description of output arguments. *)\n  id_out        : seq arg_desc;\n  (* Semantics (only deals with values). *)\n  id_semi       : sem_prod id_tin (exec (sem_tuple id_tout));\n  (* Possible signatures for an instruction. *)\n  id_args_kinds : i_args_kinds;\n  (* Number of explicit arguments in assembly syntax. *)\n  id_nargs      : nat;\n  (* Info for jasmin *)\n  id_eq_size    : (size id_in == size id_tin) && (size id_out == size id_tout);\n  id_tin_narr   : all is_not_sarr id_tin;\n  id_tout_narr  : all is_not_sarr id_tout;\n  id_str_jas    : unit -> string;\n  id_check_dest : all2 check_arg_dest id_out id_tout;\n  id_safe       : seq safe_cond;\n  id_pp_asm     : asm_args -> pp_asm_op;\n}.\n\n\n(* -------------------------------------------------------------------- *)\n\nVariant prim_constructor (asm_op:Type) :=\n  | PrimP of wsize & (wsize -> asm_op)\n  | PrimM of asm_op\n  | PrimV of (velem -> wsize -> asm_op)\n  | PrimSV of (signedness -> velem -> wsize -> asm_op)\n  | PrimX of (wsize -> wsize -> asm_op)\n  | PrimVV of (velem → wsize → velem → wsize → asm_op)\n  | PrimARM of\n    (bool                 (* set_flags *)\n     -> bool              (* is_conditional *)\n     -> option shift_kind (* has_shift *)\n     -> asm_op).\n\n\n(* -------------------------------------------------------------------- *)\n(* Architecture operand declaration. *)\nClass asm_op_decl (asm_op: Type) :=\n  { _eqT          :> eqTypeC asm_op\n  ; instr_desc_op : asm_op -> instr_desc_t\n  ; prim_string   : list (string * prim_constructor asm_op)\n  }.\n\nDefinition asm_op_t' {asm_op} {asm_op_d : asm_op_decl asm_op} := asm_op.\n(* We extend [asm_op] in order to deal with msb flags *)\nDefinition asm_op_msb_t {asm_op} {asm_op_d : asm_op_decl asm_op} := (option wsize * asm_op)%type.\n\nContext `{asm_op_d : asm_op_decl}.\n\nDefinition extend_size (ws: wsize) (t:stype) :=\n  match t with\n  | sword ws' => if (ws' <= ws)%CMP then sword ws else sword ws'\n  | _ => t\n  end.\n\nDefinition wextend_size (ws: wsize) (t:stype) : sem_ot t -> sem_ot (extend_size ws t) :=\n  match t return sem_ot t -> sem_ot (extend_size ws t) with\n  | sword ws' =>\n    fun (w: word ws') =>\n    match (ws' <= ws)%CMP as b return sem_ot (if b then sword ws else sword ws') with\n    | true => zero_extend ws w\n    | false => w\n    end\n  | _ => fun x => x\n  end.\n\nFixpoint extend_tuple (ws:wsize) (id_tout : list stype) (t: sem_tuple id_tout) :\n   sem_tuple (map (extend_size ws) id_tout) :=\n match id_tout return sem_tuple id_tout -> sem_tuple (map (extend_size ws) id_tout) with\n | [::] => fun _ => tt\n | t :: ts =>\n   match ts return\n     (sem_tuple ts -> sem_tuple (map (extend_size ws) ts)) ->\n     sem_tuple (t::ts) -> sem_tuple (map (extend_size ws) (t::ts)) with\n   | [::] => fun rec_ x => wextend_size ws x\n   | t'::ts'    => fun rec_ p => (wextend_size ws p.1, rec_ p.2)\n   end (@extend_tuple ws ts)\n end t.\n\nFixpoint apply_lprod (A B : Type) (f : A -> B) (ts:list Type) : lprod ts A -> lprod ts B :=\n  match ts return lprod ts A -> lprod ts B with\n  | [::] => fun a => f a\n  | t :: ts' => fun g x => apply_lprod f (g x)\n  end.\n\nLemma instr_desc_aux1 ws (id_in id_out : list arg_desc) (id_tin id_tout : list stype) :\n  is_true ((size id_in == size id_tin) && (size id_out == size id_tout)) ->\n  is_true ((size id_in == size id_tin) && (size id_out == size (map (extend_size ws) id_tout))).\nProof. by rewrite size_map. Qed.\n\nLemma instr_desc_aux2 ws (id_out : list arg_desc) (id_tout : list stype) :\n  is_true (all2 check_arg_dest id_out id_tout) ->\n  is_true (all2 check_arg_dest id_out (map (extend_size ws) id_tout)).\nProof.\n  rewrite /is_true => <-.\n  elim: id_out id_tout => [ | a id_out hrec] [ | t id_tout] //=.\n  rewrite hrec; case: t => // ws'.\n  by rewrite /extend_size /check_arg_dest; case: a => //; case: ifP.\nQed.\n\nDefinition is_not_CAmem (cond : arg_kind) :=\n  match cond with\n  | CAmem _ => false\n  | _ => true\n  end.\n\nDefinition exclude_mem_args_kinds (d : arg_desc) (cond : args_kinds) :=\n  match d with\n  | ADExplicit _ i _ =>\n    mapi (fun k c => if k == i then filter is_not_CAmem c else c) cond\n  | _ => cond\n  end.\n\nDefinition exclude_mem_i_args_kinds (d : arg_desc) (cond : i_args_kinds) : i_args_kinds :=\n  map (exclude_mem_args_kinds d) cond.\n\n(* Remark: if the cast is explicit and do nothing then this code will reject store in memory\n   while assembly accepts it.\n   It is our choice... *)\n\nDefinition exclude_mem_aux (cond : i_args_kinds) (d : seq arg_desc) :=\n  foldl (fun cond d => exclude_mem_i_args_kinds d cond) cond d.\n\nDefinition exclude_mem (cond : i_args_kinds) (d : seq arg_desc) : i_args_kinds :=\n  filter (fun c => [::] \\notin c) (exclude_mem_aux cond d).\n\nLemma instr_desc_tout_narr ws xs :\n  all is_not_sarr xs -> all is_not_sarr (map (extend_size ws) xs).\nProof.\n  move=> h.\n  rewrite all_map.\n  apply: (sub_all _ h).\n  move=> [] //= ws'.\n  by case: (ws' <= ws)%CMP.\nQed.\n\n(* An extension of [instr_desc] that deals with msb flags *)\nDefinition instr_desc (o:asm_op_msb_t) : instr_desc_t :=\n  let (ws, o) := o in\n  let d := instr_desc_op o in\n  if ws is Some ws then\n    if d.(id_msb_flag) == MSB_CLEAR then\n    {| id_msb_flag   := d.(id_msb_flag);\n       id_tin        := d.(id_tin);\n       id_in         := d.(id_in);\n       id_tout       := map (extend_size ws) d.(id_tout);\n       id_out        := d.(id_out);\n       id_semi       :=\n         apply_lprod (Result.map (@extend_tuple ws d.(id_tout))) d.(id_semi);\n       id_args_kinds := exclude_mem d.(id_args_kinds) d.(id_out) ;\n       id_nargs      := d.(id_nargs);\n       id_eq_size    := instr_desc_aux1 ws d.(id_eq_size);\n       id_tin_narr   := d.(id_tin_narr);\n       id_tout_narr  := instr_desc_tout_narr _ d.(id_tout_narr);\n       id_str_jas    := d.(id_str_jas);\n       id_check_dest := instr_desc_aux2 ws d.(id_check_dest);\n       id_safe       := d.(id_safe);\n       id_pp_asm     := d.(id_pp_asm); |}\n    else d (* FIXME do the case for MSB_KEEP *)\n  else\n    d.\n\n(* -------------------------------------------------------------------- *)\n(* Assembly language. *)\nVariant asm_i : Type :=\n  | ALIGN\n  | LABEL of label_kind & label\n  | STORELABEL of reg_t & label (* Store the address of a local label *)\n  (* Jumps *)\n  | JMP    of remote_label (* Direct jump *)\n  | JMPI   of asm_arg (* Indirect jump, arm : BX *)\n  | Jcc    of label & cond_t  (* Conditional jump *)\n  (* Functions *)\n  | JAL of reg_t & remote_label (* Direct jump; return address is saved in a register *)\n  | CALL of remote_label (* Direct jump; return address is saved at the top of the stack *)\n  | POPPC (* Pop a destination from the stack and jump there, arm : POP PC, x86 : RET *)\n  (* Instructions exposed at source-level *)\n  | AsmOp  of asm_op_t' & asm_args\n  | SysCall of syscall_t.\n\nDefinition asm_code := seq asm_i.\n\n(* Any register, used for function arguments and returned values. *)\nVariant asm_typed_reg :=\n  | ARReg of reg_t\n  | ARegX of regx_t\n  | AXReg of xreg_t\n  | ABReg of rflag_t.\nNotation asm_typed_regs := (seq asm_typed_reg).\n\nDefinition asm_typed_reg_beq r1 r2 := \n  match r1, r2 with\n  | ARReg r1, ARReg r2 => r1 == r2 ::>\n  | ARegX r1, ARegX r2 => r1 == r2 ::>\n  | AXReg r1, AXReg r2 => r1 == r2 ::>\n  | ABReg r1, ABReg r2 => r1 == r2 ::>\n  | _       , _        => false\n  end.\n\nLemma asm_typed_reg_eq_axiom : Equality.axiom asm_typed_reg_beq.\nProof. case => r1 [] r2 /=; try by (constructor || apply: reflect_inj eqP => ?? []). Qed.\n\nDefinition asm_typed_reg_eqMixin := Equality.Mixin asm_typed_reg_eq_axiom.\nCanonical asm_typed_reg_eqType := EqType asm_typed_reg asm_typed_reg_eqMixin.\n\n(* -------------------------------------------------------------------- *)\n(* Function declaration                                                 *)\n\nRecord asm_fundef := XFundef\n  { asm_fd_align : wsize\n  ; asm_fd_arg   : asm_typed_regs\n  ; asm_fd_body  : asm_code\n  ; asm_fd_res   : asm_typed_regs\n  ; asm_fd_export: bool\n  ; asm_fd_total_stack: Z\n  }.\n\nRecord asm_prog : Type :=\n  { asm_globs : seq u8\n  ; asm_funcs : seq (funname * asm_fundef)\n  }.\n\n(* -------------------------------------------------------------------- *)\n(* Calling Convention                                                   *)\n\nDefinition is_ABReg r := \n  match r with\n  | ABReg _ => true\n  | _ => false\n  end.\n\nClass calling_convention := \n  { callee_saved   : seq asm_typed_reg\n  ; callee_saved_not_bool : all (fun r => ~~is_ABReg r) callee_saved\n  ; call_reg_args  : seq reg_t\n  ; call_xreg_args : seq xreg_t\n  ; call_reg_ret   : seq reg_t \n  ; call_xreg_ret  : seq xreg_t\n  ; call_reg_ret_uniq : uniq (T:= @ceqT_eqType _ _) call_reg_ret\n  }.\n\nDefinition get_ARReg (a:asm_typed_reg) := \n  match a with\n  | ARReg r => Some r\n  | _ => None\n  end.\n\nDefinition get_ARegX (a:asm_typed_reg) := \n  match a with\n  | ARegX r => Some r\n  | _ => None\n  end.\n\nDefinition get_AXReg (a:asm_typed_reg) := \n  match a with\n  | AXReg r => Some r\n  | _ => None\n  end.\n\nDefinition check_list {T} {eqc : eqTypeC T} (get : asm_typed_reg -> option T) (l:asm_typed_regs) (expected:seq T) := \n  let r := pmap get l in\n  (r : seq (@ceqT_eqType T eqc)) == take (size r) expected.\n\nDefinition check_call_conv {call_conv:calling_convention} (fd:asm_fundef) :=\n  implb fd.(asm_fd_export) \n    [&& check_list get_ARReg fd.(asm_fd_arg) call_reg_args,\n        check_list get_AXReg fd.(asm_fd_arg) call_xreg_args,\n        check_list get_ARReg fd.(asm_fd_res) call_reg_ret &\n        check_list get_AXReg fd.(asm_fd_res) call_xreg_ret].\n\nEnd DECL.\n\nSection ENUM.\n  Context `{arch : arch_decl}.\n\n  Definition registers : seq reg_t := cenum.\n\n  Definition registerxs : seq regx_t := cenum.\n\n  Definition xregisters : seq xreg_t := cenum.\n\n  Definition rflags : seq rflag_t := cenum.\nEnd ENUM.\n\n(* -------------------------------------------------------------------- *)\n(* Flag values. *)\nVariant rflagv := Def of bool | Undef.\nScheme Equality for rflagv.\n\nLemma rflagv_eq_axiom : Equality.axiom rflagv_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_rflagv_dec_bl.\n  by apply: internal_rflagv_dec_lb.\nQed.\n\nDefinition rflagv_eqMixin := Equality.Mixin rflagv_eq_axiom.\nCanonical rflagv_eqType := EqType _ rflagv_eqMixin.\n\n(* -------------------------------------------------------------------- *)\n(* Assembly declaration. *)\n\nClass asm (reg regx xreg rflag cond asm_op: Type) :=\n  { _arch_decl   :> arch_decl reg regx xreg rflag cond\n  ; _asm_op_decl :> asm_op_decl asm_op\n  ; eval_cond   : (rflag_t -> exec bool) -> cond_t -> exec bool\n  }.\n", "meta": {"author": "jasmin-lang", "repo": "jasmin", "sha": "3c783b662000c371ba924a953d444fd80b860d9f", "save_path": "github-repos/coq/jasmin-lang-jasmin", "path": "github-repos/coq/jasmin-lang-jasmin/jasmin-3c783b662000c371ba924a953d444fd80b860d9f/proofs/arch/arch_decl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2205625463519706}}
{"text": "(* This file is part of the LLIR Semantics project. *)\n(* Licensing information is available in the LICENSE file. *)\n(* (C) 2020 Nandor Licker. All rights reserved. *)\n\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Init.Nat.\n\nRequire Import LLIR.LLIR.\nRequire Import LLIR.Maps.\nRequire Import LLIR.Typing.\nRequire Import LLIR.Dom.\nRequire Import LLIR.Frame.\nRequire Import LLIR.State.\n\nImport ListNotations.\n\nDefinition set_frame (st: state) (fr: frame): state :=\n  let stk := st.(st_stack) in\n  {| st_stack :=\n    {| stk_fr := stk.(stk_fr)\n     ; stk_frs := stk.(stk_frs)\n     ; stk_next := stk.(stk_next)\n     ; stk_frames := PTrie.set stk.(stk_frames) stk.(stk_fr) fr\n     ; stk_init := stk.(stk_init)\n     |}\n   ; st_heap := st.(st_heap)\n   |}.\n\nAxiom argext: ty -> value -> option value.\n\nDefinition step_inst (fr: frame) (st: state) (i: inst): option state :=\n  match i with\n  | LLArg (ty, dst) next idx =>\n    match nth_error fr.(fr_args) idx  with\n    | None => None\n    | Some v =>\n      match argext ty v with\n      | None => None\n      | Some v' =>\n        let fr' := set_vreg_pc fr dst v' next in\n        Some (set_frame st fr')\n      end\n    end\n\n  | LLInt dst next val =>\n    let fr' := set_vreg_pc fr dst (VInt val) next in\n    Some (set_frame st fr')\n\n  | LLUnop (ty, dst) next op arg =>\n    match fr.(fr_regs) ! arg with\n    | Some varg =>\n      match step_unop op ty varg with\n      | Some r =>\n        let fr' := set_vreg_pc fr dst r next in\n        Some (set_frame st fr')\n      | None => None\n      end\n    | None => None\n    end\n\n  | LLBinop (ty, dst) next op lhs rhs =>\n    match fr.(fr_regs) ! lhs with\n    | Some vl =>\n      match fr.(fr_regs) ! rhs with\n      | Some vr =>\n        match step_binop op ty vl vr with\n        | None => None\n        | Some r =>\n          let fr' := set_vreg_pc fr dst r next in\n          Some (set_frame st fr')\n        end\n      | None => None\n      end\n    | None => None\n    end\n\n  | LLJcc cond bt bf =>\n    match fr.(fr_regs) ! cond with\n    | Some vc =>\n      match is_true vc with\n      | true =>\n        Some (set_frame st (set_pc fr bt))\n      | false =>\n        Some (set_frame st (set_pc fr bf))\n      end\n    | None => None\n    end\n\n  | LLJmp target =>\n    Some (set_frame st (set_pc fr target))\n\n  | LLRet val =>\n    None\n\n  (* TODO *)\n  | _ => None\n  end.\n\nDefinition step (p: prog) (st: state): option state :=\n  match (st.(st_stack).(stk_frames)) ! (st.(st_stack).(stk_fr)) with\n  | Some fr =>\n    match p ! (fr.(fr_func)) with\n    | Some fn =>\n      match fn.(fn_insts) ! (fr.(fr_pc)) with\n      | Some inst =>\n        step_inst fr st inst\n      | None =>\n        None\n      end\n    | _ => None\n    end\n  | _ => None\n  end.\n", "meta": {"author": "nandor", "repo": "llir-semantics", "sha": "0edb7dfdbea45d2dc5416522341dbd2c75abc20c", "save_path": "github-repos/coq/nandor-llir-semantics", "path": "github-repos/coq/nandor-llir-semantics/llir-semantics-0edb7dfdbea45d2dc5416522341dbd2c75abc20c/Eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2203981558891963}}
{"text": "Set Implicit Arguments.\nRequire Import LibLogic LibHeap.\nRequire Export JsSemanticsDefs JsSemanticsRules.\nImplicit Type h : heap.\nImplicit Type l : loc.\nImplicit Type f : field.\n\n\n(**************************************************************)\n(**************************************************************)\n(** * Auxiliary lemmas *)\n\n\n(**************************************************************)\n(** * Checking the type of fields *)\n\n(** Express whether a field is a user field *)\n\nDefinition is_field_normal f :=\n    exists y, f = field_normal y.\n\n\n(**************************************************************)\n(** * Comparison of references *)\n\nLemma ref_neq : forall l l' f f',\n  (Ref l f <> Ref l' f') = (l <> l' \\/ f <> f').\nProof.\n  intros. extens. iff H.\n  rewrite <- not_and. intros [? ?]. subst. apply~ H.\n  intros M. inverts M. destruct H; congruence.\nQed.\n\nLemma ref_neq_inv : forall l l' f f',\n  (Ref l f <> Ref l' f') -> (l <> l' \\/ f <> f').\nProof. intros. rewrite~ <- ref_neq. Qed.\n\nLemma ref_neq_prove : forall l l' f f',\n  (l <> l' \\/ f <> f') -> (Ref l f <> Ref l' f').\nProof. intros. rewrite~ ref_neq. Qed.\n\n\n(**************************************************)\n(** * Induction principle for [red_expr], [red_stat] and [red_prog] *)\n\nSection Red_induct.\n\nScheme red_expr_ind' := Induction for red_expr Sort Prop\n  with red_expr_lazy_binary_op_ind' := Induction for red_expr_lazy_binary_op Sort Prop\n  with red_stat_ind' := Induction for red_stat Sort Prop\n  with red_prog_ind' := Induction for red_prog Sort Prop.\n\nEnd Red_induct.\n\n\n(**************************************************************)\n(** ** Expressing properties of extended expressions. *)\n\nSection ExpressPropertiesOfExtented.\n\nVariable Pout_expr : heap -> out_expr -> Prop.\nVariable Pout_prog : heap -> out_prog -> Prop.\nVariable Pextends : heap -> heap -> Prop.\n\nVariable Pscope : heap -> scope -> Prop.\nVariable Pvalue : heap -> value -> Prop.\nVariable Pref : heap -> ref -> Prop.\nVariable Ploc : heap -> loc -> Prop.\nVariable Pbody_or_primitive : heap -> body_or_primitive -> Prop.\nVariable Punary_op : unary_op -> Prop.\nVariable Pbinary_op : binary_op -> Prop.\n\nDefinition extract_heap_from_output_expr default o :=\n  match o with\n  | out_expr_div => default\n  | out_expr_ter h _ => h\n  end.\n\nDefinition extract_heap_from_output_prog default o :=\n  match o with\n  | out_prog_div => default\n  | out_prog_ter h _ => h\n  end.\n\nFixpoint correct_ext_prog (h : heap) (P : ext_prog) : Prop :=\n  match P with\n    | ext_prog_prog _ =>\n      True\n    | ext_prog_seq_1 o _ =>\n      Pout_prog h o\n  end.\n\nFixpoint correct_ext_expr (h : heap) (e : ext_expr) : Prop :=\n  let Pvalue' o := Pvalue (extract_heap_from_output_expr h o) in\n  let Ploc' o := Ploc (extract_heap_from_output_expr h o) in\n  let Pref' o := Pref (extract_heap_from_output_expr h o) in\n  let correct_ext_expr' o := correct_ext_expr (extract_heap_from_output_expr h o) in\n  match e with\n    | ext_expr_expr _ =>\n      True\n    | ext_res_prog_res_expr o =>\n      Pout_prog h o\n    | ext_expr_prog P =>\n      correct_ext_prog h P\n    | ext_list_then k _ => (* FIXME:  Do we need the fact that [lv] has the same length than the list of expression? *)\n      forall h' lv, Pextends h h' -> Forall (Pvalue h') lv -> correct_ext_expr h' (k lv)\n    | ext_list_then_1 k lv _ =>\n      Forall (Pvalue h) lv /\\ forall h' lv', Pextends h h' -> Forall (Pvalue h') lv' -> correct_ext_expr h' (k (lv ++ lv'))\n    | ext_list_then_2 k lv o _ =>\n      Pout_expr h o /\\ Forall (Pvalue' o) lv /\\ forall h' lv', Pextends h h' -> Forall (Pvalue h') lv' -> correct_ext_expr h' (k (lv ++ lv'))\n    | ext_expr_object_1 l _ lv =>\n      Ploc h l /\\ Forall (Pvalue h) lv\n    | ext_expr_access_1 o _ =>\n      Pout_expr h o\n    | ext_expr_access_2 l o =>\n      Pvalue h l /\\ Pout_expr h o\n    | ext_expr_new_1 o _ =>\n      Pout_expr h o\n    | ext_expr_new_2 l bp lv =>\n      Ploc h l /\\ Pbody_or_primitive h bp /\\ Forall (Pvalue h) lv\n    | ext_expr_new_3 l o =>\n      Ploc' o l /\\ Pout_expr h o\n    | ext_expr_call_1 o _ =>\n      Pout_expr h o\n    | ext_expr_call_2 l1 l2 _ =>\n      Ploc h l1 /\\ Ploc h l2\n    | ext_expr_call_3 l bp lv =>\n      Ploc h l /\\ Pbody_or_primitive h bp /\\ Forall (Pvalue h) lv\n    | ext_expr_call_4 o =>\n      Pout_expr h o\n    | ext_expr_unary_op_1 op o =>\n      Punary_op op /\\ Pout_expr h o\n    | ext_expr_binary_op_1 o op _ =>\n      Pout_expr h o /\\ Pbinary_op op\n    | ext_expr_binary_op_2 (Some o) _ _ _ =>\n      Pout_expr h o\n    | ext_expr_binary_op_2 None v op _ =>\n      Pvalue h v /\\ Pbinary_op op\n    | ext_expr_binary_op_3 v op o =>\n      Pvalue' o v /\\ Pbinary_op op /\\ Pout_expr h o\n    | ext_expr_assign_1 o (Some op) _ =>\n      Pout_expr h o /\\ Pbinary_op op\n    | ext_expr_assign_1 o None _ =>\n      Pout_expr h o\n    | ext_expr_assign_2 r o =>\n      Pref' o r /\\ Pout_expr h o\n    | ext_expr_assign_2_op r v op o =>\n      Pref' o r /\\ Pvalue' o v /\\ Pbinary_op op /\\ Pout_expr h o\n  end.\n\nFixpoint correct_ext_stat (h : heap) (p : ext_stat) : Prop :=\n  match p with\n    | ext_stat_stat _ =>\n      True\n    | ext_res_expr_res_prog o =>\n      Pout_expr h o\n    | ext_stat_expr e =>\n      correct_ext_expr h e\n    | ext_stat_seq_1 o _ =>\n      Pout_prog h o\n    | ext_stat_var_decl_expr_1 o =>\n      Pout_prog h o\n    | ext_stat_if_1 o _ _ =>\n      Pout_prog h o\n    | ext_stat_while_1 _ o _ =>\n      Pout_prog h o\n    | ext_stat_while_2 _ _ o =>\n      Pout_prog h o\n    | ext_stat_with_1 o _ =>\n      Pout_prog h o\n    | ext_stat_throw_1 o =>\n      Pout_prog h o\n    | ext_stat_try_1 o _ _ =>\n      Pout_prog h o\n    | ext_stat_try_2 s _ _ =>\n      Pscope h s\n    | ext_stat_try_3 o _ =>\n      Pout_prog h o\n    | ext_stat_try_4 r o =>\n      Pout_prog h o /\\ Pout_prog h (out_prog_ter h r)\n  end.\n\nEnd ExpressPropertiesOfExtented.\n\n\n(**************************************************************)\n(** ** Corrolaries for [obj_of_value] *)\n\nDefinition value_not_loc v :=\n  forall l, v <> value_loc l.\n\nLemma value_loc_or_not : forall v,\n  (exists l, v = value_loc l) \\/ (value_not_loc v).\nProof.\n  intros. applys classic_right. introv M.\n  rew_logic in M. auto.\nQed.\n\nLemma obj_of_value_not_loc : forall v l',\n  value_not_loc v ->\n  obj_of_value v l' = l'.\nProof. introv H. destruct* v. false* H. Qed.\n\n\n(**************************************************************)\n(** ** Corrolaries for [obj_or_glob_of_value_not_loc] *)\n\nDefinition not_scope_or_body f :=\n  f <> field_scope /\\ f <> field_body.\n\nHint Unfold not_scope_or_body.\n\nLemma obj_or_glob_of_value_not_loc : forall v,\n  value_not_loc v ->\n  obj_or_glob_of_value v = loc_obj_proto.\nProof. introv H. destruct* v. simpl. false* H. Qed.\n\n\n\n(**************************************************************)\n(**************************************************************)\n(** * Properties of heaps *)\n\n(**************************************************************)\n(** * Properties of heaps (adapted from module [Heap]) *)\n\nSection Properties.\nHint Resolve ref_neq_inv ref_neq_prove.\n\n(** DO NOT REORDER THE LEMMAS *)\n\nLemma binds_equiv_read : forall h l f,\n  indom h l f -> (forall v, (binds h l f v) = (read h l f = v)).\nProof. intros. apply* @Heap.binds_equiv_read. Qed.\n\nLemma indom_equiv_binds : forall h l f,\n  indom h l f = (exists v, binds h l f v).\nProof. intros. apply Heap.indom_equiv_binds. Qed.\n\nLemma binds_write_eq : forall h l f v,\n  binds (write h l f v) l f v.\nProof. intros. apply Heap.binds_write_eq. Qed.\n\nLemma binds_write_neq : forall h l f v l' f' v',\n  binds h l f v -> (l <> l' \\/ f <> f') ->\n  binds (write h l' f' v') l f v.\nProof.\n  introv B N. applys @Heap.binds_write_neq B.\n  destruct N; congruence.\nQed.\n\nLemma binds_write_inv : forall h l f v l' f' v',\n  binds (write h l' f' v') l f v ->\n     (l = l' /\\ f = f' /\\ v = v')\n  \\/ ((l <> l' \\/ f <> f') /\\ binds h l f v).\nProof.\n  introv B. forwards [[E ?]|[E ?]]: @Heap.binds_write_inv B.\n  inverts E. left*.\n  right*.\nQed.\n\nLemma binds_rem : forall h l f l' f' v,\n  binds h l f v -> (l <> l' \\/ f <> f') -> binds (rem h l' f') l f v.\nProof. introv B N. applys* @Heap.binds_rem B. Qed.\n\nLemma binds_rem_inv : forall h l f v l' f',\n  binds (rem h l' f') l f v -> (l <> l' \\/ f <> f') /\\ binds h l f v.\nProof. introv B. forwards* [? ?]: @Heap.binds_rem_inv B. Qed.\n\nLemma not_indom_rem : forall h l f,\n  ~ indom (rem h l f) l f.\nProof. intros. apply Heap.not_indom_rem. Qed.\n\nLemma indom_binds : forall h l f,\n  indom h l f -> exists v, binds h l f v.\nProof. intros. apply* @LibHeap.indom_binds. Qed.\n\nLemma binds_indom : forall h l f v,\n  binds h l f v -> indom h l f.\nProof. intros. apply* @LibHeap.binds_indom. Qed.\n\nLemma binds_func : forall h l f v v',\n  binds h l f v -> binds h l f v' -> v = v'.\nProof. intros. applys* @LibHeap.binds_func; typeclass. Qed.\n\nLemma binds_read : forall h l f v,\n  binds h l f v -> read h l f = v.\nProof. intros. apply* @LibHeap.binds_read. Qed.\n\nLemma read_binds : forall h l f v,\n  read h l f = v -> indom h l f -> binds h l f v.\nProof. intros. apply* @LibHeap.read_binds. Qed.\n\nLemma read_write_eq : forall h l f v,\n  read (write h l f v) l f = v.\nProof. intros. apply* @LibHeap.read_write_eq. Qed.\n\nLemma read_write_neq : forall h l f l' f' v',\n  indom h l f -> (l <> l' \\/ f <> f') -> read (write h l' f' v') l f = read h l f.\nProof. intros. apply* @LibHeap.read_write_neq. Qed.\n\nLemma indom_write_eq : forall h l f v,\n  indom (write h l f v) l f.\nProof. intros. apply* @LibHeap.indom_write_eq. Qed.\n\nLemma indom_write : forall h l f l' f' v',\n  indom h l f -> indom (write h l' f' v') l f.\nProof. intros. apply* @LibHeap.indom_write. Qed.\n\nLemma indom_write_inv : forall h l f l' f' v',\n  indom (write h l' f' v') l f -> (l <> l' \\/ f <> f') -> indom h l f.\nProof. intros. apply* @LibHeap.indom_write_inv. Qed.\n\nLemma binds_write_eq_inv : forall h l f v v',\n  binds (write h l f v') l f v -> v = v'.\nProof. intros. apply* @LibHeap.binds_write_eq_inv. Qed.\n\nLemma binds_write_neq_inv : forall h l f v l' f' v',\n  binds (write h l' f' v') l f v -> (l <> l' \\/ f <> f') -> binds h l f v.\nProof. intros. apply* @LibHeap.binds_write_neq_inv. Qed.\n\nLemma indom_rem : forall h l f l' f',\n  indom h l f -> (l <> l' \\/ f <> f') -> indom (rem h l' f') l f.\nProof. intros. apply* @LibHeap.indom_rem. Qed.\n\nLemma indom_rem_inv : forall h l f l' f',\n  indom (rem h l f) l' f' -> (l <> l' \\/ f <> f') /\\ indom h l' f'.\nProof. intros. forwards* [? ?]: @LibHeap.indom_rem_inv H. Qed.\n\nLemma read_rem_neq : forall h l f l' f',\n  indom h l f -> (l <> l' \\/ f <> f') -> read (rem h l' f') l f = read h l f.\nProof. intros. apply* @LibHeap.read_rem_neq. Qed.\n\nLemma not_indom_empty : forall l f,\n  ~ indom empty_heap l f.\nProof. intros. apply* @LibHeap.not_indom_empty. Qed.\n\nLemma not_binds_empty : forall l f v,\n  ~ binds empty_heap l f v.\nProof. intros. apply* @LibHeap.not_binds_empty. Qed.\n\nEnd Properties.\n\n\n(**************************************************************)\n(** * Other results *)\n\n(** [binds] on location is functional *)\n\nLemma binds_func_loc : forall h f l l1 l2,\n  binds h l f (value_loc l1) ->\n  binds h l f (value_loc l2) ->\n  l1 = l2.\nProof. introv B1 B2. forwards E: binds_func B1 B2. inverts~ E. Qed.\n\n\n(** [binds] on location is functional *)\n\nLemma binds_func_scope : forall h f l s1 s2,\n  binds h l f (value_scope s1) ->\n  binds h l f (value_scope s2) ->\n  s1 = s2.\nProof. introv B1 B2. forwards E: binds_func B1 B2. inverts~ E. Qed.\n\n(** Checking if a location l is bound to a given value in the heap\n    is decidable. *)\n\nGlobal Instance indom_decidable : forall h l f,\n  Decidable (indom h l f).\nProof. intros. apply Heap.indom_decidable. Qed.\n\n\n\n(**************************************************************)\n(** * Properties of write_fields *)\n\nLemma write_fields_nil : forall h l,\n  write_fields h l nil = h.\nProof. auto. Qed.\n\nLemma write_fields_cons : forall h l f v fvs,\n  write_fields h l ((f,v)::fvs) = write_fields (write h l f v) l fvs.\nProof. auto. Qed.\n\nHint Rewrite write_fields_nil write_fields_cons : rew_write_fields.\nLtac rew_write_fields := autorewrite with rew_write_fields.\n\n(** An induction principle for proving facts about [write_fields] *)\n\nLemma write_fields_ind : forall (P : list(field*value)->heap->heap->Prop), forall l h,\n  (P nil h h) ->\n  (forall f v fvs, P fvs h (write_fields h l fvs) -> P (fvs&(f,v)) h (write (write_fields h l fvs) l f v)) ->\n  (forall fvs, P fvs h (write_fields h l fvs)).\nProof.\n  introv MN MC. intros. unfold write_fields. induction fvs using list_ind_last; rew_list.\n  auto. destruct a as [f' v']. apply~ MC.\nQed.\n\nLemma binds_write_fields_neq : forall h l f v l' fvs',\n  binds h l f v -> l <> l' ->\n  binds (write_fields h l' fvs') l f v.\nProof. intros. lets: binds_write_neq. apply* write_fields_ind. Qed.\n\nLemma binds_write_fields_neq_inv : forall h l l' fvs' f v,\n  binds (write_fields h l' fvs') l f v -> l <> l' -> binds h l f v.\nProof. introv B N. gen B. lets: binds_write_neq_inv. apply* write_fields_ind. Qed.\n\nLemma indom_write_fields : forall h l f l' fvs',\n  indom h l f -> indom (write_fields h l' fvs') l f.\nProof. introv D. lets: indom_write. apply* write_fields_ind. Qed.\n\n\n(**************************************************************)\n(** * Properties of bound *)\n\nLemma binds_bound : forall h l f v,\n  binds h l f v -> bound h l.\nProof. intros. exists f. apply* binds_indom. Qed.\n\nLemma indom_bound : forall h l f,\n  indom h l f -> bound h l.\nProof. intros. exists* f. Qed.\n\nLemma not_bound_indom : forall h l f,\n  (~ bound h l) -> indom h l f -> False.\nProof. introv N D. apply N. apply* indom_bound. Qed.\n\nLemma not_bound_binds : forall h l f v,\n  (~ bound h l) -> binds h l f v -> False.\nProof. introv N D. apply N. apply* binds_bound. Qed.\n\nLemma bound_binds : forall h l,\n  bound h l -> exists f v, binds h l f v.\nProof. introv [f D]. rewrite* indom_equiv_binds in D. Qed.\n\n\n(**************************************************************)\n(** * Properties of freshness *)\n\nLemma fresh_not_null : forall h l,\n  fresh h l -> l <> loc_null.\nProof. introv [N _]. auto. Qed.\n\nHint Resolve fresh_not_null.\n\n(** Elimination of fresh *)\n\nLemma fresh_not_bound : forall h l,\n  fresh h l -> bound h l -> False.\nProof. introv [_ N] D. false. Qed.\n\nLemma fresh_bound_neq : forall h l l',\n  fresh h l' -> bound h l -> l <> l'.\nProof. introv B F E. subst. apply* fresh_not_bound. Qed.\n\nLemma fresh_not_indom : forall h l f,\n  fresh h l -> indom h l f -> False.\nProof. intros. apply* fresh_not_bound. apply* indom_bound. Qed.\n\nLemma fresh_indom_neq : forall h l l' f,\n  fresh h l' -> indom h l f -> l <> l'.\nProof. introv B F E. subst. apply* fresh_not_indom. Qed.\n\nLemma fresh_not_binds : forall h l f v,\n  fresh h l -> binds h l f v -> False.\nProof. intros. apply* fresh_not_indom. applys* binds_indom. Qed.\n\nLemma fresh_binds_neq : forall h l l' f v,\n  fresh h l' -> binds h l f v -> l <> l'.\nProof. introv B F E. subst. apply* fresh_not_binds. Qed.\n\n(** Preservation of fresh *)\n\nLemma fresh_write : forall l' h l f v,\n  fresh h l' -> l <> l' -> fresh (write h l f v) l'.\nProof.\n  introv [L B] N. split. auto.\n  intros B'. lets (f'&v'&R): bound_binds B'.\n  lets [(?&?&?)|(?&?)]: binds_write_inv R.\n    false.\n    apply* not_bound_binds.\nQed.\n\nLemma fresh_write_weaken : forall l' h l f v,\n  fresh (write h l f v) l' -> fresh h l'.\nProof.\n  introv [L B]. split. auto.\n  intros [f' B']. apply B. eapply indom_bound.\n  apply* indom_write.\nQed.\n\n\n(**************************************************************)\n(** ** Hints for proving freshness goals *)\n\nHint Extern 1 (fresh _ ?l) =>\n  match goal with H: fresh _ ?l |- _ =>\n    apply (fresh_write_weaken H) end.\n\nHint Resolve fresh_binds_neq.\n\nHint Extern 1 (_ <> _ :> ref) => congruence.\n\n\n(**************************************************************)\n(** * Properties of abort *)\n\nLemma not_abort_prog_ret_expr : forall o,\n  ~ abort_prog o ->\n  exists h, exists r, o = out_prog_ter h r.\nProof.\n  introv nA.\n  cases* o.\n   false nA. constructors.\n(* LATER:cleanup\n   cases* r; try (false nA; constructors).\n*)\nQed.\n\nLemma not_abort_expr_ret_expr : forall o,\n  ~ abort_expr o ->\n  exists h, exists r, o = out_expr_ter h r.\nProof.\n  introv nA.\n  cases* o.\n   false nA. constructors.\n(* LATER: cleanup\n   cases* r; try (false nA; constructors).\n*)\nQed.\n\nLemma not_abort_prog_ter : forall h (r : ret_expr),\n  ~ abort_prog (out_prog_ter h r).\nProof.\n  introv A. inverts* A.\nQed.\n\nLemma not_abort_expr_ter : forall h (r : ret_expr),\n  ~ abort_expr (out_expr_ter h r).\nProof.\n  introv A. inverts* A.\nQed.\n\n(**************************************************************)\n(** ** Tactics *)\n\n(*--------------------------------------------------------------*)\n\n(** The following tactic strengthens [congruence] by making it\n    able to bruteforce a goal that concludes on a disjunction *)\n\nLtac congruence_on_disjunction :=\n  let rec go tt :=\n    match goal with\n    | |- _ \\/ _ => first [ left; go tt | right; go tt ]\n    | |- _ => congruence\n    end in\n  go tt.\n\nLemma congruence_on_disjunction_demo : forall (l l' : nat),\n  l <> l' -> (l <> l' \\/ l' <> l \\/ l <> l').\nProof. intros. try congruence. congruence_on_disjunction. Qed.\n\n(*--------------------------------------------------------------*)\n\n(** The tactic [indom_simpl_step] simplifies a goal of the\n    form [indom (write h l f v) l' f'] by handling the case\n    where [l'] is syntactically [l] and [f'] is syntactically [f],\n    and otherwise turning the goal into [indom h l' f'].\n    It also handles the [write_fields]. Note that you might\n    need to do a case analysis on [l = l'] and [f = f'] before\n    calling this tactic. It also handles the empty heap.  *)\n\nLtac indom_simpl_step :=\n  match goal with\n  | |- indom (write ?h ?l ?f _) ?l ?f =>\n     apply indom_write_eq\n  | |- indom (write_fields _ _ nil) _ _ =>\n     rewrite write_fields_nil; indom_simpl_step\n  | |- indom (write_fields _ _ (_::_)) _ _ =>\n     rewrite write_fields_cons; indom_simpl_step\n  | |- indom (write ?h ?l' ?f' _) ?l ?f =>\n     apply indom_write\n  | |- indom ?h _ _ =>\n     let P := get_head h in progress (unfold P); indom_simpl_step\n  | |- _ =>\n     progress (unfolds); indom_simpl_step\n  end.\n\n(** The tactic [indom_simpl] iterates [indom_simpl_step]. *)\n\nTactic Notation \"indom_simpl\" :=\n  repeat indom_simpl_step.\nTactic Notation \"indom_simpl\" \"~\" :=\n  indom_simpl; auto_tilde.\nTactic Notation \"indom_simpl\" \"*\" :=\n  indom_simpl; auto_star.\n\n\n(*--------------------------------------------------------------*)\n\n(** The tactic [binds_simpl_step] simplifies goal of the form\n    [binds (write h l f v) f' l' v'] by handling the case where\n    [l'] is syntactically [l] and [f'] is syntactically [f],\n    and otherwise discarding the write, producing [l <> l' \\/ f <> f']\n    as subgoal and trying to prove it using [congruence].\n    The tactic also handles [write_fields] in the case where [l <> l']. *)\n\nLtac binds_simpl_step :=\n  match goal with\n  | |- binds (write ?h ?l ?f _) ?l ?f _ =>\n     apply binds_write_eq\n  | |- binds (write_fields ?h ?l' ?fvs') ?l _ _ =>\n     let F := fresh in\n     assert (F : l <> l');\n       [ try congruence\n       | apply binds_write_fields_neq; [ clear F | apply F ]]\n  | |- binds (write ?h ?l' ?f' _) ?l ?f _ =>\n     let F := fresh in\n     assert (F : l <> l' \\/ f <> f');\n       [ try congruence_on_disjunction\n       | apply binds_write_neq; [ clear F | apply F ]]\n  | |- binds ?h _ _ _ =>\n     let P := get_head h in progress (unfold P); binds_simpl_step\n  | |- _ =>\n     progress (unfolds); binds_simpl_step\n  end.\n\n(** The tactic [binds_simpl] iterates [binds_simpl_step]. *)\n\nTactic Notation \"binds_simpl\" :=\n  repeat binds_simpl_step.\nTactic Notation \"binds_simpl\" \"~\" :=\n  binds_simpl; auto_tilde.\nTactic Notation \"binds_simpl\" \"*\" :=\n  binds_simpl; auto_star.\n\n\n(*--------------------------------------------------------------*)\n\n(** The tactic [binds_case H] helps extracting information from an\n    assumption [H] of the form [binds (write h l' f' v') l f v].\n    If [l'] is syntactically [l] and [f'] is syntactically [f],\n    then the tactic simplifies [H] to [v' = v]. Otherwise, if\n    [l' <> l] or [f' <> f] is provable using [congruence], then\n    the tactic simplifies [H] to [binds h l f v]. Otherwise, the\n    tactic performs the case analysis and generates two subgoals,\n    one corresponding to each case.\n    The tactic also handles [write_fields] by unfolding the head\n    write in write_fields, if any. It also handles the empty heap. *)\n\nLtac binds_case_step H :=\n  match type of H with\n  | binds (write ?h ?l ?f _) ?l ?f _ =>\n     apply binds_write_eq_inv in H (*; try solve [ congruence ] *)\n  | binds (write ?h ?l' ?f' ?v') ?l ?f ?v =>\n     first [\n       let F := fresh in let H' := fresh in\n       assert (F : l <> l' \\/ f <> f');\n         [ congruence_on_disjunction\n         | rename H into H';\n           lets H: (binds_write_neq_inv H' F); clear F H' ]\n     | let H' := fresh in rename H into H';\n       let N := fresh \"N\" in let E1 := fresh \"E1\" in\n       let E2 := fresh \"E2\" in let E3 := fresh \"E3\" in\n       destruct (binds_write_inv H') as [(E1&E2&E3)|(N&H)];\n         [ clear H'; try solve [ false; congruence ];\n           try subst_hyp E1; try subst_hyp E2; try subst_hyp E3\n         | clear H' ]\n     ]\n  | binds (write_fields _ _ nil) _ _ _ =>\n     rewrite write_fields_nil in H\n  | binds (write_fields _ _ (_::_)) _ _ _ =>\n     rewrite write_fields_cons in H; binds_case_step H\n  | binds (write_fields _ _ _) _ _ _ =>\n     fail 2 \"list given to write_fields should not be abstract\"\n  | binds empty_heap _ _ _ =>\n     false (not_binds_empty H)\n  | binds ?h _ _ _ =>\n     let P := get_head h in progress (unfold P in H); binds_case_step H\n  end.\n\nTactic Notation \"binds_case\" hyp(H) :=\n  binds_case_step H.\nTactic Notation \"binds_case\" \"~\" hyp(H) :=\n  binds_case H; auto_tilde.\nTactic Notation \"binds_case\" \"*\" hyp(H) :=\n  binds_case H; auto_star.\n\n(** The tactic [binds_cases] iterates [binds_case] *)\n\nTactic Notation \"binds_cases\" hyp(H) :=\n  repeat (binds_case H).\nTactic Notation \"binds_cases\" \"~\" hyp(H) :=\n  binds_cases H; auto_tilde.\nTactic Notation \"binds_cases\" \"*\" hyp(H) :=\n  binds_cases H; auto_star.\n\n", "meta": {"author": "resource-reasoning", "repo": "jscert_dev", "sha": "61d917913c17f111383f2fba1bcf5aeff3911d26", "save_path": "github-repos/coq/resource-reasoning-jscert_dev", "path": "github-repos/coq/resource-reasoning-jscert_dev/jscert_dev-61d917913c17f111383f2fba1bcf5aeff3911d26/coq/JsSemanticsAux.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22038093670468767}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nRequire Export Coq.Strings.String.\nRequire Import Coq.Classes.RelationClasses.\n\nFrom Fairness Require Export ITreeLib FairBeh Mod.\nFrom Fairness Require Import pind.\nFrom Fairness Require Import LPCM.\n\nSet Implicit Arguments.\n\n\n\nSection PRIMIVIESIM.\n  Context `{M: URA.t}.\n\n  Variable state_src: Type.\n  Variable state_tgt: Type.\n\n  Variable _ident_src: ID.\n  Definition ident_src := sum_tid _ident_src.\n  Variable _ident_tgt: ID.\n  Definition ident_tgt := sum_tid _ident_tgt.\n\n  Variable wf_src: WF.\n  Variable wf_tgt: WF.\n\n  Let srcE := programE _ident_src state_src.\n  Let tgtE := programE _ident_tgt state_tgt.\n\n  Definition shared :=\n    (TIdSet.t *\n       (@imap ident_src wf_src) *\n       (@imap ident_tgt wf_tgt) *\n       state_src *\n       state_tgt)%type.\n\n  Let shared_rel: Type := shared -> Prop.\n\n  Variable I: shared -> URA.car -> Prop.\n\n  Variant __lsim\n          (tid: thread_id)\n          (lsim: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          (_lsim: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel),bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n  | lsim_ret\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      r_src r_tgt\n      (LSIM: RR r_src r_tgt r_ctx (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (Ret r_src) (Ret r_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_tauL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (Tau itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_chooseL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X ktr_src itr_tgt\n      (LSIM: exists x, _lsim _ _ RR true f_tgt r_ctx (ktr_src x) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Choose X) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_rmwL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X rmw ktr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src (snd (rmw st_src) : X)) itr_tgt (ths, im_src, im_tgt, fst (rmw st_src), st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Rmw rmw) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_tidL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src tid) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (GetTid) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_UB\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Undefined) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_fairL\n      f_src f_tgt r_ctx\n      ths im_src0 im_tgt st_src st_tgt\n      f ktr_src itr_tgt\n      (LSIM: exists im_src1,\n          (<<FAIR: fair_update im_src0 im_src1 (prism_fmap inrp f)>>) /\\\n            (<<LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src tt) itr_tgt (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Fair f) >>= ktr_src) itr_tgt (ths, im_src0, im_tgt, st_src, st_tgt)\n\n  | lsim_tauR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: _lsim _ _ RR f_src true r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (Tau itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_chooseR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X itr_src ktr_tgt\n      (LSIM: forall x, _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt x) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (Choose X) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_rmwR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X rmw itr_src ktr_tgt\n      (LSIM: _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt (snd (rmw st_tgt) : X)) (ths, im_src, im_tgt, st_src, fst (rmw st_tgt)))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (Rmw rmw) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_tidR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src ktr_tgt\n      (LSIM: _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt tid) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (GetTid) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_fairR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt0 st_src st_tgt\n      f itr_src ktr_tgt\n      (LSIM: forall im_tgt1\n                   (FAIR: fair_update im_tgt0 im_tgt1 (prism_fmap inrp f)),\n          (<<LSIM: _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt tt) (ths, im_src, im_tgt1, st_src, st_tgt)>>))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (Fair f) >>= ktr_tgt) (ths, im_src, im_tgt0, st_src, st_tgt)\n\n  | lsim_observe\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src ktr_tgt\n      (LSIM: forall ret,\n          lsim _ _ RR true true r_ctx (ktr_src ret) (ktr_tgt ret) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Observe fn args) >>= ktr_src) (trigger (Observe fn args) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_call\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src itr_tgt\n    : __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Call fn args) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_yieldL\n      f_src f_tgt r_ctx\n      ths im_src0 im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (LSIM: exists im_src1,\n          (<<FAIR: fair_update im_src0 im_src1 (prism_fmap inlp (tids_fmap tid ths))>>) /\\\n            (<<LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src tt) (trigger (Yield) >>= itr_tgt) (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= itr_tgt) (ths, im_src0, im_tgt, st_src, st_tgt)\n  | lsim_yieldR\n      f_src f_tgt r_ctx0\n      ths0 im_src0 im_tgt0 st_src0 st_tgt0\n      r_own r_shared\n      ktr_src ktr_tgt\n      (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared)\n      (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx0))\n      (LSIM: forall ths1 im_src1 im_tgt1 st_src1 st_tgt1 r_shared1 r_ctx1\n                    (INV: I (ths1, im_src1, im_tgt1, st_src1, st_tgt1) r_shared1)\n                    (VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx1))\n                    im_tgt2\n                    (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths1))),\n          _lsim _ _ RR f_src true r_ctx1 (trigger (Yield) >>= ktr_src) (ktr_tgt tt) (ths1, im_src1, im_tgt2, st_src1, st_tgt1))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx0 (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n  | lsim_sync\n      f_src f_tgt r_ctx0\n      ths0 im_src0 im_tgt0 st_src0 st_tgt0\n      r_own r_shared\n      ktr_src ktr_tgt\n      (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared)\n      (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx0))\n      (LSIM: forall ths1 im_src1 im_tgt1 st_src1 st_tgt1 r_shared1 r_ctx1\n               (INV: I (ths1, im_src1, im_tgt1, st_src1, st_tgt1) r_shared1)\n               (VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx1))\n               im_tgt2\n               (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths1))),\n          (exists im_src2,\n              (<<FAIR: fair_update im_src1 im_src2 (prism_fmap inlp (tids_fmap tid ths1))>>) /\\\n                (<<LSIM: lsim _ _ RR true true r_ctx1 (ktr_src tt) (ktr_tgt tt) (ths1, im_src2, im_tgt2, st_src1, st_tgt1)>>)))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx0 (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n\n  | lsim_progress\n      r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: lsim _ _ RR false false r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR true true r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  .\n\n  Definition lsim (tid: thread_id)\n             R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel):\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n    paco9 (fun r => pind9 (__lsim tid r) top9) bot9 R_src R_tgt RR.\n\n  Lemma __lsim_mon tid:\n    forall r r' (LE: r <9= r'), (__lsim tid r) <10= (__lsim tid r').\n  Proof.\n    ii. inv PR; try (econs; eauto; fail).\n    eapply lsim_sync; eauto. i. hexploit LSIM. eapply INV0. eapply VALID0. all: eauto. i; des. esplits; eauto.\n  Qed.\n\n  Lemma _lsim_mon tid: forall r, monotone9 (__lsim tid r).\n  Proof.\n    ii. inv IN; try (econs; eauto; fail).\n    { des. econs; eauto. }\n    { des. econs; eauto. }\n    { econs. i. eapply LE. eapply LSIM. eauto. }\n    { des. econs; esplits; eauto. }\n  Qed.\n\n  Lemma lsim_mon tid: forall q, monotone9 (fun r => pind9 (__lsim tid r) q).\n  Proof.\n    ii. eapply pind9_mon_gen; eauto.\n    ii. eapply __lsim_mon; eauto.\n  Qed.\n\n  Variant lsim_resetC\n          (r: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n    | lsim_resetC_intro\n        src tgt shr r_ctx\n        ps0 pt0 ps1 pt1\n        (REL: r _ _ RR ps1 pt1 r_ctx src tgt shr)\n        (SRC: ps1 = true -> ps0 = true)\n        (TGT: pt1 = true -> pt0 = true)\n      :\n      lsim_resetC r RR ps0 pt0 r_ctx src tgt shr\n  .\n\n  Lemma lsim_resetC_spec tid\n    :\n    lsim_resetC <10= gupaco9 (fun r => pind9 (__lsim tid r) top9) (cpn9 (fun r => pind9 (__lsim tid r) top9)).\n  Proof.\n    eapply wrespect9_uclo; eauto with paco.\n    { eapply lsim_mon. }\n    econs.\n    { ii. inv IN. econs; eauto. }\n    i. inv PR. eapply GF in REL.\n    eapply pind9_acc in REL.\n    instantiate (1:= (fun R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel) ps1 pt1 r_ctx src tgt shr =>\n                        forall ps0 pt0,\n                          (ps1 = true -> ps0 = true) ->\n                          (pt1 = true -> pt0 = true) ->\n                          pind9 (__lsim tid (rclo9 lsim_resetC r)) top9 R0 R1 RR ps0 pt0 r_ctx src tgt shr)) in REL; eauto.\n    ss. i. eapply pind9_unfold in PR.\n    2:{ eapply _lsim_mon. }\n    rename PR into LSIM. inv LSIM.\n\n    { eapply pind9_fold. econs; eauto. }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind9_fold. eapply lsim_tauL. split; ss.\n      hexploit IH; eauto.\n    }\n\n    { des. eapply pind9_fold. eapply lsim_chooseL. esplits; eauto. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_rmwL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_tidL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_UB. }\n\n    { des. eapply pind9_fold. eapply lsim_fairL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind9_fold. eapply lsim_tauR. split; ss.\n      hexploit IH. eauto. all: eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_chooseR. i. split; ss. specialize (LSIM0 x).\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_rmwR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_tidR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_fairR. i. split; ss. specialize (LSIM0 _ FAIR).\n      des. destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_observe. i. eapply rclo9_base. auto. }\n\n    { eapply pind9_fold. eapply lsim_call. }\n\n    { des. eapply pind9_fold. eapply lsim_yieldL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_yieldR; eauto. i.\n      hexploit LSIM0; eauto. clear LSIM0. intros LSIM0.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. split; ss; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_sync; eauto. i.\n      hexploit LSIM0. eapply INV0. eapply VALID0. all: eauto. i; des. esplits; eauto.\n      eapply rclo9_base. auto.\n    }\n\n    { pclearbot. hexploit H; ss; i. hexploit H0; ss; i. clarify.\n      eapply pind9_fold. eapply lsim_progress. eapply rclo9_base. auto. }\n  Qed.\n\n  Lemma lsim_reset_prog\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        src tgt shr\n        ps0 pt0 ps1 pt1 r_ctx\n        (LSIM: lsim tid RR ps1 pt1 r_ctx src tgt shr)\n        (SRC: ps1 = true -> ps0 = true)\n        (TGT: pt1 = true -> pt0 = true)\n    :\n    lsim tid RR ps0 pt0 r_ctx src tgt shr.\n  Proof.\n    ginit.\n    { eapply lsim_mon. }\n    { eapply cpn9_wcompat. eapply lsim_mon. }\n    guclo lsim_resetC_spec.\n    { eapply lsim_mon. }\n    econs; eauto. gfinal.\n    { eapply lsim_mon. }\n    right. auto.\n  Qed.\n\n  Lemma lsim_set_prog\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        r_ctx src tgt shr\n        (LSIM: lsim tid RR true true r_ctx src tgt shr)\n    :\n    forall ps pt, lsim tid RR ps pt r_ctx src tgt shr.\n  Proof.\n    i. revert_until tid. pcofix CIH. i.\n    remember true as ps0 in LSIM at 1. remember true as pt0 in LSIM at 1.\n    move LSIM before CIH. revert_until LSIM. punfold LSIM.\n    2:{ eapply lsim_mon. }\n    eapply pind9_acc in LSIM.\n\n    { instantiate (1:= (fun R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel) ps0 pt0 r_ctx src tgt shr =>\n                          ps0 = true ->\n                          pt0 = true ->\n                          forall ps pt,\n                            paco9\n                              (fun r0 =>\n                                 pind9 (__lsim tid r0) top9) r R0 R1 RR ps pt r_ctx src tgt shr)) in LSIM; auto. }\n\n    ss. clear ps0 pt0 r_ctx src tgt shr LSIM.\n    intros rr DEC IH R0' R1' RR' gps gpt r_ctx src tgt shr LSIM. clear DEC.\n    intros Egps Egpt ps pt.\n    eapply pind9_unfold in LSIM.\n    2:{ eapply _lsim_mon. }\n    inv LSIM.\n\n    { pfold. eapply pind9_fold. econs; eauto. }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      pfold. eapply pind9_fold. eapply lsim_tauL. split; ss.\n      hexploit IH. eauto. all: eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { des. pfold. eapply pind9_fold. eapply lsim_chooseL. esplits; eauto. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_rmwL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_tidL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_UB. }\n\n    { des. pfold. eapply pind9_fold. eapply lsim_fairL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      pfold. eapply pind9_fold. eapply lsim_tauR. split; ss.\n      hexploit IH. eauto. all: eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_chooseR. i. split; ss. specialize (LSIM0 x).\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_rmwR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_tidR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_fairR. i. split; ss. specialize (LSIM0 _ FAIR).\n      des. destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_observe. i. eapply upaco9_mon_bot; eauto. }\n\n    { pfold. eapply pind9_fold. eapply lsim_call. }\n\n    { des. pfold. eapply pind9_fold. eapply lsim_yieldL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto. i. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_yieldR; eauto. i.\n      hexploit LSIM0; eauto. clear LSIM0. intros LSIM0.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. split; ss. punfold H. eapply lsim_mon.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_sync; eauto. i.\n      hexploit LSIM0. eapply INV0. eapply VALID0. all: eauto. i; des. esplits; eauto.\n      eapply upaco9_mon_bot; eauto.\n    }\n\n    { pclearbot. eapply paco9_mon_bot. eapply lsim_reset_prog. eauto. all: ss. }\n\n  Qed.\n\n  Variant lsim_rrC\n          (r: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n    | lsim_rrC_intro\n        (RR0: R_src -> R_tgt -> URA.car -> shared_rel)\n        src tgt shr r_ctx ps pt\n        (REL: r _ _ RR0 ps pt r_ctx src tgt shr)\n        (IMPL: forall r0 r1 r_ctx shr, (RR0 r0 r1 r_ctx shr) -> (RR r0 r1 r_ctx shr))\n      :\n      lsim_rrC r RR ps pt r_ctx src tgt shr\n  .\n\n  Lemma lsim_rrC_spec tid\n    :\n    lsim_rrC <10= gupaco9 (fun r => pind9 (__lsim tid r) top9) (cpn9 (fun r => pind9 (__lsim tid r) top9)).\n  Proof.\n    eapply wrespect9_uclo; eauto with paco.\n    { eapply lsim_mon. }\n    econs.\n    { ii. inv IN. econs; eauto. }\n    i. inv PR. eapply GF in REL.\n    rename REL into LSIM.\n    move LSIM before GF. revert_until LSIM.\n    pattern x0, x1, RR0, x3, x4, x5, x6, x7, x8.\n    revert x0 x1 RR0 x3 x4 x5 x6 x7 x8 LSIM. apply pind9_acc.\n    intros rr _ IH. intros R0 R1 RR0 ps pt r_ctx src tgt shr LSIM.\n    intros RR1. i.\n    eapply pind9_unfold in LSIM.\n    2:{ eapply _lsim_mon. }\n    inv LSIM.\n\n    { eapply pind9_fold. econs; eauto. }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind9_fold. eapply lsim_tauL. split; ss.\n      hexploit IH; eauto.\n    }\n\n    { des. eapply pind9_fold. eapply lsim_chooseL. esplits; eauto. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_rmwL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_tidL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_UB. }\n\n    { des. eapply pind9_fold. eapply lsim_fairL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind9_fold. eapply lsim_tauR. split; ss.\n      hexploit IH. eauto. all: eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_chooseR. i. split; ss. specialize (LSIM0 x).\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_rmwR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_tidR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_fairR. i. split; ss. specialize (LSIM0 _ FAIR).\n      des. destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_observe. i.\n      eapply rclo9_clo. econs; eauto. eapply rclo9_base; auto. }\n\n    { eapply pind9_fold. eapply lsim_call. }\n\n    { des. eapply pind9_fold. eapply lsim_yieldL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_yieldR; eauto. i.\n      hexploit LSIM0; eauto. clear LSIM0. intros LSIM0.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. split; ss; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_sync; eauto. i.\n      hexploit LSIM0. eapply INV0. eapply VALID0. all: eauto. i; des. esplits; eauto.\n      eapply rclo9_clo. econs; eauto. eapply rclo9_base; auto.\n    }\n\n    { eapply pind9_fold. eapply lsim_progress.\n      eapply rclo9_clo. econs; eauto. eapply rclo9_base; eauto.\n    }\n\n  Qed.\n\n  Definition local_RR {R0 R1} (RR: R0 -> R1 -> Prop) tid:\n    R0 -> R1 -> URA.car -> shared_rel :=\n    fun (r_src: R0) (r_tgt: R1) (r_ctx: URA.car) '(ths2, im_src1, im_tgt1, st_src1, st_tgt1) =>\n      (exists ths3 r_own r_shared,\n          (<<THS: NatMap.remove tid ths2 = ths3>>) /\\\n            (<<VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx)>>) /\\\n            (<<INV: I (ths3, im_src1, im_tgt1, st_src1, st_tgt1) r_shared>>) /\\\n            (<<RET: RR r_src r_tgt>>)).\n\n  Definition local_sim {R0 R1} (RR: R0 -> R1 -> Prop) src tgt :=\n    forall ths0 im_src0 im_tgt0 st_src0 st_tgt0 r_shared0 r_ctx0\n           (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared0)\n           tid ths1\n           (THS: TIdSet.add_new tid ths0 ths1)\n           (VALID: URA.wf (r_shared0 ⋅ r_ctx0)),\n    forall im_tgt0'\n      (UPD: fair_update im_tgt0 im_tgt0' (prism_fmap inlp (fun t => if (tid_dec t tid) then Flag.success else Flag.emp))),\n    exists r_shared1 r_own im_src0',\n      (<<INV: I (ths1, im_src0', im_tgt0', st_src0, st_tgt0) r_shared1>>) /\\\n        (<<VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx0)>>) /\\\n        (forall ths im_src1 im_tgt1 st_src st_tgt r_shared2 r_ctx2\n                (INV: I (ths, im_src1, im_tgt1, st_src, st_tgt) r_shared2)\n                (VALID: URA.wf (r_shared2 ⋅ r_own ⋅ r_ctx2)),\n          forall im_tgt2 (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths))),\n          exists im_src2,\n            (<<SRC: fair_update im_src1 im_src2 (prism_fmap inlp (tids_fmap tid ths))>>) /\\\n              (<<LSIM: forall fs ft,\n                  lsim\n                    tid\n                    (@local_RR R0 R1 RR tid)\n                    fs ft\n                    r_ctx2\n                    src tgt\n                    (ths, im_src2, im_tgt2, st_src, st_tgt)\n                    >>)).\n\n  Definition local_sim_init {R0 R1} (RR: R0 -> R1 -> Prop) (r_own: URA.car) tid src tgt :=\n    forall ths im_src im_tgt st_src st_tgt r_shared r_ctx\n      (INV: I (ths, im_src, im_tgt, st_src, st_tgt) r_shared)\n      (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx)),\n    forall im_tgt1 (FAIR: fair_update im_tgt im_tgt1 (prism_fmap inlp (tids_fmap tid ths))),\n    exists im_src1,\n      (<<SRC: fair_update im_src im_src1 (prism_fmap inlp (tids_fmap tid ths))>>) /\\\n        forall fs ft,\n          lsim\n            tid\n            (@local_RR R0 R1 RR tid)\n            fs ft\n            r_ctx\n            src tgt\n            (ths, im_src1, im_tgt1, st_src, st_tgt).\n\nEnd PRIMIVIESIM.\n#[export] Hint Constructors __lsim: core.\n#[export] Hint Unfold lsim: core.\n#[export] Hint Resolve __lsim_mon: paco.\n#[export] Hint Resolve _lsim_mon: paco.\n#[export] Hint Resolve lsim_mon: paco.\n\n\n\nModule ModSim.\n  Section MODSIM.\n\n    Variable md_src: Mod.t.\n    Variable md_tgt: Mod.t.\n\n    Record mod_sim: Prop :=\n      mk {\n          wf_src : WF;\n          wf_tgt : WF;\n          wf_tgt_inhabited: inhabited wf_tgt.(T);\n          wf_tgt_open: forall (o0: wf_tgt.(T)), exists o1, wf_tgt.(lt) o0 o1;\n\n          world: URA.t;\n\n          (* I: (@shared md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt) -> world -> Prop; *)\n          init: forall im_tgt,\n          exists (I: (@shared md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt) -> world -> Prop),\n          (exists im_src r_shared,\n            (I (NatSet.empty, im_src, im_tgt, md_src.(Mod.st_init), md_tgt.(Mod.st_init)) r_shared) /\\\n              (URA.wf r_shared)) /\\\n          (forall fn args, match md_src.(Mod.funs) fn, md_tgt.(Mod.funs) fn with\n                           | Some ktr_src, Some ktr_tgt => local_sim I (@eq Any.t) (ktr_src args) (ktr_tgt args)\n                           | None        , None         => True\n                           | _           , _            => False\n                           end);\n        }.\n  End MODSIM.\nEnd ModSim.\n\n\nFrom Fairness Require Import Concurrency.\n\nModule UserSim.\n  Section MODSIM.\n\n    Variable md_src: Mod.t.\n    Variable md_tgt: Mod.t.\n\n    Record sim (p_src: Th.t _) (p_tgt: Th.t _) : Prop :=\n      mk {\n          wf_src : WF;\n          wf_tgt : WF;\n          wf_tgt_inhabited: inhabited wf_tgt.(T);\n          wf_tgt_open: forall (o0: wf_tgt.(T)), exists o1, wf_tgt.(lt) o0 o1;\n\n          world: URA.t;\n\n          (* I: (@shared md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt) -> world -> Prop; *)\n          funs: forall im_tgt,\n          exists (I: (@shared md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt) -> world -> Prop),\n          exists im_src rs r_shared,\n            (<<INIT: I (key_set p_src, im_src, im_tgt, md_src.(Mod.st_init), md_tgt.(Mod.st_init)) r_shared>>) /\\\n              (<<SIM: Forall3\n                        (fun '(t1, src) '(t2, tgt) '(t3, r) =>\n                           t1 = t2 /\\ t1 = t3 /\\\n                           @local_sim_init _ md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt I _ _ (@eq Any.t) r t1 src tgt)\n                        (Th.elements p_src) (Th.elements p_tgt) (NatMap.elements rs)>>) /\\\n              (<<WF: URA.wf (r_shared ⋅ NatMap.fold (fun _ r s => r ⋅ s) rs ε)>>)\n        }.\n  End MODSIM.\nEnd UserSim.\n", "meta": {"author": "damhiya", "repo": "fairness", "sha": "279dcc679bd18b85666b97d6b540d94299c5d66e", "save_path": "github-repos/coq/damhiya-fairness", "path": "github-repos/coq/damhiya-fairness/fairness-279dcc679bd18b85666b97d6b540d94299c5d66e/src/simulation/ModSimStid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.22015253817522581}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import Omega.\n\nRequire Import VerdiTactics.\nRequire Import Util.\nRequire Import Net.\nRequire Import Raft.\nRequire Import RaftRefinement.\n\nRequire Import CommonTheorems.\nRequire Import CroniesCorrect.\nRequire Import VotesCorrect.\nRequire Import TermSanity.\nRequire Import CroniesTerm.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nSection CandidateEntries.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Definition candidateEntries e (sigma : name -> _) :=\n    exists h,\n      wonElection (dedup name_eq_dec (cronies (fst (sigma h)) (eTerm e))) = true /\\\n      (currentTerm (snd (sigma h)) = eTerm e ->\n       type (snd (sigma h)) <> Candidate).\n\n  Lemma candidateEntries_ext :\n    forall e sigma sigma',\n      (forall h, sigma' h = sigma h) ->\n      candidateEntries e sigma ->\n      candidateEntries e sigma'.\n  Proof.\n    unfold candidateEntries.\n    firstorder.\n    exists x; intuition;\n    repeat find_higher_order_rewrite; auto.\n  Qed.\n\n  Definition candidateEntries_host_invariant sigma :=\n    (forall h e, In e (log (snd (sigma h))) ->\n                 candidateEntries e sigma).\n\n  Definition candidateEntries_nw_invariant net :=\n    forall p t leaderId prevLogIndex prevLogTerm entries leaderCommit,\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm\n                              entries leaderCommit ->\n      forall e,\n        In e entries ->\n        candidateEntries e (nwState net).\n\n  Definition CandidateEntries net : Prop :=\n    candidateEntries_host_invariant (nwState net) /\\ candidateEntries_nw_invariant net.\n\n  Lemma handleClientRequest_spec :\n    forall h d id c out d' l,\n      handleClientRequest h d id c = (out, d', l) ->\n      currentTerm d' = currentTerm d /\\\n      type d' = type d /\\\n      l = [] /\\\n      (forall e, In e (log d') ->\n            (In e (log d) \\/ (e = (mkEntry\n                                     h\n                                     id\n                                     (S (maxIndex (log d)))\n                                     (currentTerm d)\n                                     c) /\\ log d' = e :: log d /\\ type d' = Leader))).\n  Proof.\n    intros. unfold handleClientRequest in *.\n    break_match; find_inversion; intuition.\n    simpl in *. intuition. subst. auto.\n  Qed.\n\n  Lemma candidateEntries_same :\n    forall (st st' : name -> _) e,\n      candidateEntries e st ->\n      (forall h, cronies (fst (st' h)) = cronies (fst (st h))) ->\n      (forall h, currentTerm (snd (st' h)) = currentTerm (snd (st h))) ->\n      (forall h, type (snd (st' h)) = type (snd (st h))) ->\n      candidateEntries e st'.\n  Proof.\n    unfold candidateEntries.\n    firstorder. eexists.\n    repeat find_higher_order_rewrite.\n    eauto.\n  Qed.\n\n  Lemma candidate_entries_client_request :\n    refined_raft_net_invariant_client_request CandidateEntries.\n  Proof.\n    unfold refined_raft_net_invariant_client_request, CandidateEntries.\n    intros. subst.\n    intuition.\n    - unfold candidateEntries_host_invariant in *.\n      intros; simpl in *.\n      eapply candidateEntries_ext; try eassumption.\n      repeat find_higher_order_rewrite.\n\n      destruct (name_eq_dec h0 h); subst.\n      + rewrite_update.\n        simpl in *.\n        find_apply_lem_hyp handleClientRequest_spec; intuition eauto.\n        find_apply_hyp_hyp.\n        intuition.\n        * rewrite_update.\n          eapply candidateEntries_same; eauto; intuition;\n          destruct (name_eq_dec h0 h); subst; rewrite_update; auto.\n        * find_apply_lem_hyp cronies_correct_invariant.\n          unfold candidateEntries. exists h.\n          intuition; rewrite_update; simpl in *; try congruence.\n          repeat find_rewrite. simpl in *.\n          eauto using won_election_cronies.\n      + rewrite_update.\n        find_apply_lem_hyp handleClientRequest_spec.\n        eapply candidateEntries_same; eauto; intuition;\n        destruct (name_eq_dec h1 h); subst; rewrite_update; auto.\n    - unfold candidateEntries_nw_invariant in *.\n      intros. simpl in *.\n      eapply candidateEntries_ext; try eassumption.\n      find_apply_lem_hyp handleClientRequest_spec.\n      intuition.\n      subst. simpl in *.\n\n      eapply_prop_hyp candidateEntries AppendEntries; eauto.\n      + eapply candidateEntries_same; eauto; intuition;\n        destruct (name_eq_dec h h0); subst; rewrite_update; auto.\n      + find_apply_hyp_hyp. intuition.\n  Qed.\n\n  Lemma update_elections_data_timeout_leader_cronies_same :\n    forall sigma h,\n      type (snd (sigma h)) = Leader ->\n      cronies (update_elections_data_timeout h (sigma h)) =\n      cronies (fst (sigma h)).\n  Proof.\n    unfold update_elections_data_timeout.\n    intros.\n    repeat break_match; subst; simpl in *; auto.\n    unfold handleTimeout, tryToBecomeLeader in *.\n    repeat break_match; try congruence; repeat find_inversion; simpl in *;\n    unfold raft_data in *;\n    congruence.\n  Qed.\n\n  Ltac update_destruct :=\n    match goal with\n    | [ |- context [ update _ ?y _ ?x ] ] => destruct (name_eq_dec y x)\n    end.\n\n  Lemma handleTimeout_only_sends_RequestVotes :\n    forall h d out d' l p,\n      handleTimeout h d = (out, d', l) ->\n      In p l ->\n      exists t h' maxi maxt,\n        snd p = RequestVote t h' maxi maxt.\n  Proof.\n    unfold handleTimeout, tryToBecomeLeader.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; intuition;\n    do_in_map; subst; simpl; eauto.\n  Qed.\n\n  Lemma handleTimeout_log_same :\n    forall h d out d' l,\n      handleTimeout h d = (out, d', l) ->\n      log d' = log d.\n  Proof.\n    unfold handleTimeout, tryToBecomeLeader.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Ltac find_rewrite_lem lem :=\n    match goal with\n    | [ H : _ |- _ ] =>\n      rewrite lem in H; [idtac]\n    end.\n\n  Ltac find_rewrite_lem_by lem t :=\n    match goal with\n    | [ H : _ |- _ ] =>\n      rewrite lem in H by t\n    end.\n\n  Lemma handleTimeout_not_leader_inc_term :\n    forall h d out d' l,\n      handleTimeout h d = (out, d', l) ->\n      type d <> Leader ->\n      currentTerm d' = S (currentTerm d).\n  Proof.\n    unfold handleTimeout, tryToBecomeLeader.\n    intros. simpl in *.\n    repeat break_match; try congruence; repeat find_inversion; auto.\n  Qed.\n\n  Lemma update_elections_data_timeout_cronies :\n    forall h d out d' l t,\n      handleTimeout h (snd d) = (out, d', l) ->\n      cronies (update_elections_data_timeout h d) t = cronies (fst d) t \\/\n      (t = currentTerm d' /\\\n       cronies (update_elections_data_timeout h d) t = votesReceived d').\n  Proof.\n    unfold update_elections_data_timeout.\n    intros.\n    repeat break_match; repeat find_inversion; simpl; auto.\n    break_match; auto.\n  Qed.\n\n  Lemma handleTimeout_preserves_candidateEntries :\n    forall net h e out d l,\n      refined_raft_intermediate_reachable net ->\n      handleTimeout h (snd (nwState net h)) = (out, d, l) ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update (nwState net) h (update_elections_data_timeout h (nwState net h), d)).\n  Proof.\n    intros.\n    destruct (serverType_eq_dec (type (snd (A:=electionsData) (B:=raft_data) (nwState net h))) Leader).\n      + (* Leader case *)\n        unfold handleTimeout, tryToBecomeLeader in *. simpl in *.\n        find_rewrite. find_inversion.\n\n        eapply candidateEntries_same; eauto;\n        intros;\n        repeat (rewrite update_fun_comm; simpl in * );\n        update_destruct; subst; rewrite_update;\n        auto using update_elections_data_timeout_leader_cronies_same.\n      + (* non-Leader case *)\n\n        unfold candidateEntries in *.\n        break_exists. break_and.\n        exists x.\n        rewrite update_fun_comm; simpl.\n        rewrite update_fun_comm; simpl.\n        rewrite update_fun_comm; simpl.\n        rewrite update_fun_comm; simpl.\n        rewrite update_fun_comm with (f := type); simpl.\n        update_destruct; subst; rewrite_update; auto.\n        split.\n        * match goal with\n          | [ H : handleTimeout _ _ = _ |- _ ] =>\n            pose proof H;\n              apply update_elections_data_timeout_cronies with (t := eTerm e) in H\n          end.\n          intuition; find_rewrite; auto.\n          find_apply_lem_hyp wonElection_exists_voter.\n          break_exists.\n          find_apply_lem_hyp in_dedup_was_in.\n          find_copy_apply_lem_hyp cronies_term_invariant; auto.\n          find_copy_apply_lem_hyp handleTimeout_not_leader_inc_term; auto.\n          simpl in *.\n          omega.\n        * intros.\n          find_apply_lem_hyp wonElection_exists_voter.\n          break_exists.\n          find_apply_lem_hyp in_dedup_was_in.\n          find_copy_apply_lem_hyp cronies_term_invariant; auto.\n          find_copy_apply_lem_hyp handleTimeout_not_leader_inc_term; auto.\n          simpl in *.\n          omega.\n  Qed.\n\n  Lemma candidate_entries_timeout :\n    refined_raft_net_invariant_timeout CandidateEntries.\n  Proof.\n    unfold refined_raft_net_invariant_timeout, CandidateEntries.\n    intros. subst.\n    intuition; simpl in *.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      eapply candidateEntries_ext; try eassumption.\n      repeat find_higher_order_rewrite.\n\n        find_rewrite_lem update_fun_comm. simpl in *.\n        find_rewrite_lem update_fun_comm. simpl in *.\n        erewrite handleTimeout_log_same in * by eauto.\n\n        find_rewrite_lem_by update_nop_ext' auto.\n        find_apply_hyp_hyp.\n        eauto using handleTimeout_preserves_candidateEntries.\n    - unfold candidateEntries_nw_invariant in *.\n      intros.\n      simpl in *.\n      eapply candidateEntries_ext; eauto.\n      find_apply_hyp_hyp.\n      break_or_hyp.\n      + eapply_prop_hyp pBody pBody; eauto.\n        eauto using handleTimeout_preserves_candidateEntries.\n      + do_in_map. subst. simpl in *.\n        eapply handleTimeout_only_sends_RequestVotes in H8; eauto.\n        break_exists. congruence.\n  Qed.\n\n  Lemma update_elections_data_appendEntries_cronies_same :\n    forall h d t n pli plt es ci,\n      cronies (update_elections_data_appendEntries h d t n pli plt es ci) =\n      cronies (fst d).\n  Proof.\n    unfold update_elections_data_appendEntries.\n    intros.\n    repeat break_match; auto.\n  Qed.\n\n  Lemma handleAppendEntries_spec :\n    forall h st t n pli plt es ci st' m,\n      handleAppendEntries h st t n pli plt es ci = (st', m) ->\n      (currentTerm st <= currentTerm st' /\\\n       (forall e,\n          In e (log st') ->\n          In e (log st) \\/\n          In e es /\\ currentTerm st' = t) /\\\n       ~ is_append_entries m).\n  Proof.\n    intros.\n    unfold handleAppendEntries, advanceCurrentTerm in *.\n    repeat break_match; try find_inversion; subst; simpl in *; intuition;\n    do_bool; intuition; try solve [break_exists; congruence];\n    in_crush; eauto using removeAfterIndex_in.\n  Qed.    \n\n\n  Lemma handleAppendEntries_term_same_or_type_follower :\n    forall h t n pli plt es ci d m st,\n      handleAppendEntries h st t n pli plt es ci = (d, m) ->\n      (currentTerm d = currentTerm st /\\ type d = type st) \\/ type d = Follower.\n  Proof.\n    unfold handleAppendEntries in *.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto; try congruence.\n  Qed.\n\n  Lemma handleAppendEntries_preserves_candidate_entries :\n    forall net h t n pli plt es ci d m e,\n      handleAppendEntries h (snd (nwState net h)) t n pli plt es ci = (d, m) ->\n      refined_raft_intermediate_reachable net ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update (nwState net) h\n                                 (update_elections_data_appendEntries\n                                    h\n                                    (nwState net h) t n pli plt es ci, d)).\n  Proof.\n    unfold candidateEntries.\n    intros. break_exists. break_and.\n    exists x.\n    split.\n    - rewrite update_fun_comm. simpl.\n      rewrite update_fun_comm. simpl.\n      rewrite update_elections_data_appendEntries_cronies_same.\n      destruct (name_eq_dec x h); subst; rewrite_update; auto.\n    - intros.\n      rewrite update_fun_comm. simpl.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      destruct (name_eq_dec x h); subst; rewrite_update; auto.\n      find_apply_lem_hyp handleAppendEntries_term_same_or_type_follower.\n      intro; intuition;\n      repeat find_rewrite; auto; discriminate.\n  Qed.\n\n  Ltac my_update_destruct :=\n    match goal with\n    | [ |- context [ update _ ?y _ ?x ] ] => destruct (name_eq_dec y x)\n    | [ H : context [ update _ ?y _ ?x ] |- _ ] => destruct (name_eq_dec y x)\n    end.\n\n  Lemma is_append_entries_intro :\n    forall t n plt pli es ci,\n      is_append_entries (AppendEntries t n pli plt es ci).\n  Proof.\n    eauto 20.\n  Qed.\n\n  Lemma candidate_entries_append_entries :\n    refined_raft_net_invariant_append_entries CandidateEntries.\n  Proof.\n    red. unfold CandidateEntries.\n    intros. subst.\n    intuition; simpl in *.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      my_update_destruct; subst; rewrite_update;\n      eapply handleAppendEntries_preserves_candidate_entries; eauto.\n      find_copy_apply_lem_hyp handleAppendEntries_spec. break_and.\n      find_apply_hyp_hyp. intuition eauto.\n    - unfold candidateEntries_nw_invariant in *.\n      intros. simpl in *.\n      eapply candidateEntries_ext; eauto.\n      find_apply_hyp_hyp.\n      intuition.\n      + eapply handleAppendEntries_preserves_candidate_entries; eauto.\n      + subst. simpl in *. find_apply_lem_hyp handleAppendEntries_spec.\n        break_and.\n        subst.\n        exfalso.\n        eauto using is_append_entries_intro.\n  Qed.\n\n  Lemma handleAppendEntriesReply_spec :\n    forall h st h' t es r st' ms,\n      handleAppendEntriesReply h st h' t es r = (st', ms) ->\n      log st' = log st /\\\n      ((currentTerm st' = currentTerm st /\\ type st' = type st)\n       \\/ type st' = Follower) /\\\n      (forall m, In m ms -> ~ is_append_entries (snd m)).\n  Proof.\n    intros.\n    unfold handleAppendEntriesReply, advanceCurrentTerm in *.\n    repeat break_match; try find_inversion; subst; simpl in *; intuition;\n    do_bool; intuition.\n  Qed.\n\n\n  Lemma handleAppendEntriesReply_preserves_candidate_entries :\n    forall net h h' t es r st' ms e,\n      handleAppendEntriesReply h (snd (nwState net h)) h' t es r = (st', ms) ->\n      refined_raft_intermediate_reachable net ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update (nwState net) h (fst (nwState net h), st')).\n  Proof.\n    unfold candidateEntries.\n    intros. break_exists. break_and.\n    exists x.\n    split.\n    - rewrite update_fun_comm. simpl.\n      rewrite update_fun_comm. simpl.\n      my_update_destruct; subst; rewrite_update; auto.\n    - intros. my_update_destruct; subst; rewrite_update; auto.\n      simpl in *.\n      find_apply_lem_hyp handleAppendEntriesReply_spec.\n      intuition; repeat find_rewrite; intuition.\n      congruence.\n  Qed.\n\n\n  Ltac prove_in :=\n    match goal with\n      | [ _ : nwPackets ?net = _,\n              _ : In (?p : packet) _ |- _] =>\n        assert (In p (nwPackets net)) by (repeat find_rewrite; do_in_app; intuition)\n      | [ _ : nwPackets ?net = _,\n              _ : pBody ?p = _ |- _] =>\n        assert (In p (nwPackets net)) by (repeat find_rewrite; intuition)\n    end.\n  \n  Lemma candidate_entries_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply CandidateEntries.\n  Proof.\n    red. unfold CandidateEntries. intros. intuition.\n    - unfold candidateEntries_host_invariant in *.\n      intros. simpl in *. eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      my_update_destruct.\n      + subst. rewrite_update.\n        unfold candidateEntries in *.\n        find_apply_lem_hyp handleAppendEntriesReply_spec. break_and.\n        repeat find_rewrite.\n        find_apply_hyp_hyp.\n        break_exists; exists x; eauto.\n        my_update_destruct; intuition; subst; rewrite_update; simpl in *; auto;\n        repeat find_rewrite; intuition; congruence.\n      + rewrite_update. find_apply_hyp_hyp.\n        eauto using handleAppendEntriesReply_preserves_candidate_entries.\n    - unfold candidateEntries_nw_invariant in *. intros. simpl in *.\n      find_apply_hyp_hyp. intuition.\n      + (* packet already in nw *)\n        prove_in.\n        eapply candidateEntries_ext; eauto.\n        find_eapply_lem_hyp handleAppendEntriesReply_preserves_candidate_entries; eauto.\n        subst. auto.\n      + exfalso.\n        do_in_map.\n        find_eapply_lem_hyp handleAppendEntriesReply_spec; eauto.\n        subst. simpl in *. find_rewrite.\n        match goal with\n          | H : ~ is_append_entries _ |- _ => apply H\n        end.\n        repeat eexists; eauto.\n  Qed.\n\n  Lemma update_elections_data_requestVote_cronies_same :\n    forall h h' t lli llt st,\n      cronies (update_elections_data_requestVote h h' t h' lli llt st) =\n      cronies (fst st).\n  Proof.\n    unfold update_elections_data_requestVote.\n    intros.\n    repeat break_match; auto.\n  Qed.\n\n  Lemma advanceCurrentTerm_same_or_type_follower :\n    forall st t,\n      advanceCurrentTerm st t = st \\/\n      type (advanceCurrentTerm st t) = Follower.\n  Proof.\n    unfold advanceCurrentTerm.\n    intros. repeat break_match; auto.\n  Qed.\n\n  Lemma handleRV_advanceCurrentTerm_preserves_candidateEntries :\n    forall net h h' t lli llt e,\n      candidateEntries e (nwState net) ->\n      candidateEntries e\n                       (update (nwState net) h\n                               (update_elections_data_requestVote h h' t h' lli llt (nwState net h),\n                                advanceCurrentTerm (snd (nwState net h)) t)).\n  Proof.\n    intros.\n    unfold candidateEntries in *.\n    break_exists.  break_and.\n    exists x.\n    split; update_destruct; subst; rewrite_update; auto; simpl.\n    + rewrite update_elections_data_requestVote_cronies_same. auto.\n    + intros.\n      match goal with\n      | [ |- context [advanceCurrentTerm ?st ?t] ] =>\n        pose proof advanceCurrentTerm_same_or_type_follower st t\n      end.\n      intuition; try congruence.\n      repeat find_rewrite. auto.\n  Qed.\n\n  Lemma handleRequestVote_preserves_candidateEntries :\n    forall net h h' t lli llt d e m,\n      handleRequestVote h (snd (nwState net h)) t h' lli llt = (d, m) ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update (nwState net) h\n                                 (update_elections_data_requestVote\n                                    h h' t h' lli llt (nwState net h), d)).\n  Proof.\n    unfold handleRequestVote.\n    intros.\n    repeat break_match; repeat find_inversion;\n    auto using handleRV_advanceCurrentTerm_preserves_candidateEntries.\n    - eapply candidateEntries_same; eauto;\n        intros;\n        repeat (rewrite update_fun_comm; simpl in * );\n        update_destruct; subst; rewrite_update;\n        auto using update_elections_data_requestVote_cronies_same.\n    - unfold candidateEntries in *. break_exists. break_and. exists x.\n      simpl.\n      split.\n      + rewrite update_fun_comm with (f := fst). simpl.\n        rewrite update_fun_comm with (f := cronies). simpl.\n        rewrite update_elections_data_requestVote_cronies_same.\n        update_destruct; subst; rewrite_update; auto.\n      + rewrite update_fun_comm with (f := snd). simpl.\n        rewrite update_fun_comm with (f := currentTerm). simpl.\n        rewrite update_fun_comm with (f := type). simpl.\n        update_destruct; subst; rewrite_update; auto.\n        match goal with\n        | [ |- context [advanceCurrentTerm ?st ?t] ] =>\n          pose proof advanceCurrentTerm_same_or_type_follower st t\n        end.\n        intuition; try congruence.\n        repeat find_rewrite. auto.\n  Qed.\n\n  Lemma handleRequestVote_only_sends_RVR :\n    forall d h h' t lli llt d' m,\n      handleRequestVote h d t h' lli llt = (d', m) ->\n      is_request_vote_reply m.\n  Proof.\n    unfold handleRequestVote.\n    intros.\n    repeat break_match; repeat find_inversion; eauto.\n  Qed.\n\n  Ltac find_erewrite_lem lem :=\n    match goal with\n    | [ H : _ |- _] => erewrite lem in H by eauto\n    end.\n\n  Lemma candidate_entries_request_vote :\n    refined_raft_net_invariant_request_vote CandidateEntries.\n  Proof.\n    red. unfold CandidateEntries.\n    intros. subst.\n    intuition; simpl in *.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      my_update_destruct; subst; rewrite_update; simpl in *;\n      try find_erewrite_lem handleRequestVote_same_log;\n      eapply handleRequestVote_preserves_candidateEntries; eauto.\n    - unfold candidateEntries_nw_invariant in *.\n      intros. simpl in *.\n      eapply candidateEntries_ext; eauto.\n      find_apply_hyp_hyp. intuition.\n      + eauto using handleRequestVote_preserves_candidateEntries.\n      + subst. simpl in *.\n        find_apply_lem_hyp handleRequestVote_only_sends_RVR.\n        subst. break_exists. discriminate.\n  Qed.\n\n  Lemma handleRequestVoteReply_spec :\n    forall h st h' t r st',\n      st' = handleRequestVoteReply h st h' t r ->\n      log st' = log st /\\\n      (forall v, In v (votesReceived st) -> In v (votesReceived st')) /\\\n      ((currentTerm st' = currentTerm st /\\ type st' = type st)\n       \\/ type st' <> Candidate) /\\\n      (type st <> Leader /\\ type st' = Leader ->\n       (type st = Candidate /\\ wonElection (dedup name_eq_dec\n                                                  (votesReceived st')) = true)).\n  Proof.\n    intros.\n    unfold handleRequestVoteReply, advanceCurrentTerm in *.\n    repeat break_match; try find_inversion; subst; simpl in *; intuition;\n    do_bool; intuition; try right; congruence.\n  Qed.\n\n  Lemma handleRequestVoteReply_preserves_candidate_entries :\n    forall net h h' t r st' e,\n      st' = handleRequestVoteReply h (snd (nwState net h)) h' t r ->\n      refined_raft_intermediate_reachable net ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update (nwState net) h\n                               (update_elections_data_requestVoteReply h h' t r (nwState net h),\n                                st')).\n  Proof. \n  unfold candidateEntries.\n    intros. break_exists. break_and.\n    exists x.\n    split.\n    - rewrite update_fun_comm. simpl.\n      rewrite update_fun_comm. simpl.\n      my_update_destruct; subst; rewrite_update; auto.\n      unfold update_elections_data_requestVoteReply in *.\n      repeat break_match; simpl in *; auto.\n      + break_if; simpl in *; repeat find_rewrite; auto.\n         match goal with\n          | |- context [handleRequestVoteReply ?h ?st ?h' ?t ?r] =>\n            remember (handleRequestVoteReply h st h' t r) as new_state\n         end. find_apply_lem_hyp handleRequestVoteReply_spec. intuition.\n         repeat find_rewrite. intuition.\n      + break_if; simpl in *; find_rewrite; auto.\n        match goal with\n          | |- context [handleRequestVoteReply ?h ?st ?h' ?t ?r] =>\n            remember (handleRequestVoteReply h st h' t r) as new_state\n        end. find_apply_lem_hyp handleRequestVoteReply_spec. intuition.\n        repeat find_rewrite. intuition.\n      +  break_if; simpl in *; find_rewrite; auto.\n        match goal with\n          | |- context [handleRequestVoteReply ?h ?st ?h' ?t ?r] =>\n            remember (handleRequestVoteReply h st h' t r) as new_state\n        end. find_apply_lem_hyp handleRequestVoteReply_spec. intuition.\n        repeat find_rewrite. intuition.\n        * find_apply_lem_hyp cronies_correct_invariant.\n          unfold cronies_correct in *. intuition.\n          unfold votes_received_leaders in *.\n          match goal with\n            | H :  Leader = _ |- _ =>\n              symmetry in H\n          end. find_apply_hyp_hyp.\n          eapply wonElection_no_dup_in;\n            eauto using NoDup_dedup, in_dedup_was_in, dedup_In.\n        * destruct (serverType_eq_dec (type (snd (nwState net x))) Leader); intuition.\n          find_apply_lem_hyp cronies_correct_invariant; auto.\n          eapply wonElection_no_dup_in;\n            eauto using NoDup_dedup, in_dedup_was_in, dedup_In.\n    - rewrite update_fun_comm. simpl.\n      rewrite update_fun_comm. simpl.\n      my_update_destruct; subst; rewrite_update; auto.\n      match goal with\n          | |- context [handleRequestVoteReply ?h ?st ?h' ?t ?r] =>\n            remember (handleRequestVoteReply h st h' t r) as new_state\n      end. find_apply_lem_hyp handleRequestVoteReply_spec. intuition.\n      repeat find_rewrite. intuition.\n  Qed.\n  \n  Lemma candidate_entries_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply CandidateEntries.\n    red. unfold CandidateEntries. intros. intuition.\n    - unfold candidateEntries_host_invariant in *.\n      intros. simpl in *. eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      my_update_destruct.\n      + subst. rewrite_update.\n        match goal with\n          | |- context [handleRequestVoteReply ?h ?st ?h' ?t ?r] =>\n            remember (handleRequestVoteReply h st h' t r) as new_state\n        end.\n        find_copy_apply_lem_hyp handleRequestVoteReply_spec. break_and.\n        match goal with\n          | H : log _ = log _ |- _ => rewrite H in *\n        end.\n        find_apply_hyp_hyp.\n        eapply handleRequestVoteReply_preserves_candidate_entries; eauto.\n      + rewrite_update.\n        eapply handleRequestVoteReply_preserves_candidate_entries; eauto.\n    - unfold candidateEntries_nw_invariant in *.\n      intros. simpl in *. eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      eapply handleRequestVoteReply_preserves_candidate_entries; eauto.\n  Qed.\n\n\n  Lemma doLeader_preserves_candidateEntries :\n    forall net gd d h os d' ms e,\n      nwState net h = (gd, d) ->\n      doLeader d h = (os, d', ms) ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update (nwState net) h (gd, d')).\n  Proof.\n    intros.\n    eapply candidateEntries_same; eauto;\n    intros;\n    repeat (rewrite update_fun_comm; simpl in * );\n    update_destruct; subst; rewrite_update; auto;\n    repeat find_rewrite; simpl; auto;\n    find_apply_lem_hyp doLeader_st; intuition.\n  Qed.\n\n  Lemma doLeader_in_entries :\n    forall (h : name) d h os d' ms m t li pli plt es ci e,\n      doLeader d h = (os, d', ms) ->\n      snd m = AppendEntries t li pli plt es ci ->\n      In m ms ->\n      In e es ->\n      In e (log d).\n  Proof.\n    unfold doLeader.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; intuition.\n    do_in_map.\n\n    unfold replicaMessage in *. simpl in *. subst. simpl in *.\n    find_inversion.\n    eauto using findGtIndex_in.\n  Qed.\n\n  Lemma candidate_entries_do_leader :\n    refined_raft_net_invariant_do_leader CandidateEntries.\n  Proof.\n    red. unfold CandidateEntries.\n    intros.\n    intuition; simpl in *.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      my_update_destruct; subst; rewrite_update.\n      + simpl in *.\n        find_erewrite_lem doLeader_same_log.\n        repeat match goal with\n        | [ H : nwState ?net ?h = (_, ?d), H' : context [ log ?d ] |- _ ] =>\n          replace (log d) with (log (snd (nwState net h))) in H' by (repeat find_rewrite; auto)\n        end.\n        eauto using doLeader_preserves_candidateEntries.\n      + eauto using doLeader_preserves_candidateEntries.\n    - unfold candidateEntries_nw_invariant in *.\n      intros. simpl in *.\n      eapply candidateEntries_ext; eauto.\n      find_apply_hyp_hyp.\n      intuition.\n      + eauto using doLeader_preserves_candidateEntries.\n      + do_in_map. subst. simpl in *.\n        eapply doLeader_preserves_candidateEntries; eauto.\n        eapply_prop candidateEntries_host_invariant.\n        match goal with\n        | [ H : _ |- _ ] => rewrite H\n        end.\n        simpl.\n        eauto using doLeader_in_entries.\n  Qed.\n\n  Lemma doGenericServer_same_type :\n    forall h d os d' ms,\n      doGenericServer h d = (os, d', ms) ->\n      type d' = type d.\n  Proof.\n    unfold doGenericServer.\n    intros.\n    repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma doGenericServer_preserves_candidateEntries :\n    forall net gd d h os d' ms e,\n      nwState net h = (gd, d) ->\n      doGenericServer h d = (os, d', ms) ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update (nwState net) h (gd, d')).\n  Proof.\n    intros.\n    eapply candidateEntries_same; eauto;\n    intros;\n    repeat (rewrite update_fun_comm; simpl in * );\n    update_destruct; subst; rewrite_update; auto;\n    repeat find_rewrite; simpl; auto.\n    - find_copy_apply_lem_hyp TermSanity.doGenericServer_spec. break_and. auto.\n    - eauto using doGenericServer_same_type.\n  Qed.\n\n  Lemma candidate_entries_do_generic_server :\n    refined_raft_net_invariant_do_generic_server CandidateEntries.\n  Proof.\n    red. unfold CandidateEntries.\n    intros.\n    intuition; simpl in *.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      eapply candidateEntries_ext; eauto.\n      repeat find_higher_order_rewrite.\n      my_update_destruct; subst; rewrite_update.\n      + simpl in *.\n        find_copy_apply_lem_hyp TermSanity.doGenericServer_spec. break_and.\n        find_rewrite.\n        repeat match goal with\n        | [ H : nwState ?net ?h = (_, ?d), H' : context [ log ?d ] |- _ ] =>\n          replace (log d) with (log (snd (nwState net h))) in H' by (repeat find_rewrite; auto)\n        end.\n        eauto using doGenericServer_preserves_candidateEntries.\n      + eauto using doGenericServer_preserves_candidateEntries.\n    - unfold candidateEntries_nw_invariant in *.\n      intros. simpl in *.\n      eapply candidateEntries_ext; eauto.\n      find_apply_hyp_hyp.\n      intuition.\n      + eauto using doGenericServer_preserves_candidateEntries.\n      + do_in_map.\n        find_copy_apply_lem_hyp TermSanity.doGenericServer_spec. break_and.\n        subst. simpl in *.\n        find_apply_hyp_hyp.\n        exfalso.\n        find_rewrite. eauto 20.\n  Qed.\n\n  Lemma candidate_entries_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset CandidateEntries.\n  Proof.\n    red. unfold CandidateEntries.\n    intros.\n    intuition.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      repeat find_reverse_higher_order_rewrite.\n      apply candidateEntries_ext with (sigma := nwState net); eauto.\n    - unfold candidateEntries_nw_invariant in *.\n      intros.\n      find_apply_hyp_hyp.\n      eapply_prop_hyp In In; eauto.\n      apply candidateEntries_ext with (sigma := nwState net); eauto.\n  Qed.\n\n  Lemma reboot_log_same :\n    forall d,\n      log (reboot d) = log d.\n  Proof.\n    unfold reboot.\n    auto.\n  Qed.\n\n  Lemma reboot_preservers_candidateEntries :\n    forall net h d gd e,\n      nwState net h = (gd, d) ->\n      candidateEntries e (nwState net) ->\n      candidateEntries e (update (nwState net) h (gd, reboot d)).\n  Proof.\n    unfold reboot, candidateEntries.\n    intros.\n    break_exists.\n    exists x.\n    break_and.\n    rewrite update_fun_comm. simpl in *.\n    my_update_destruct; subst; rewrite_update; auto.\n    repeat find_rewrite. simpl in *. intuition. discriminate.\n  Qed.\n\n  Lemma candidate_entries_reboot :\n    refined_raft_net_invariant_reboot CandidateEntries.\n  Proof.\n    red. unfold CandidateEntries.\n    intros.\n    intuition.\n    - unfold candidateEntries_host_invariant in *.\n      intros.\n      repeat find_higher_order_rewrite.\n      eapply candidateEntries_ext; eauto.\n      subst.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      find_rewrite_lem update_fun_comm. simpl in *.\n      my_update_destruct; subst; rewrite_update.\n      + repeat match goal with\n        | [ H : nwState ?net ?h = (_, ?d), H' : context [ log ?d ] |- _ ] =>\n          replace (log d) with (log (snd (nwState net h))) in H' by (repeat find_rewrite; auto)\n        end.\n        find_apply_hyp_hyp.\n        eauto using reboot_preservers_candidateEntries.\n      + eauto using reboot_preservers_candidateEntries.\n    - unfold candidateEntries_nw_invariant in *.\n      intros.\n      repeat find_reverse_rewrite.\n      eapply_prop_hyp In In; eauto.\n      eapply candidateEntries_ext; eauto.\n      eauto using reboot_preservers_candidateEntries.\n  Qed.\n\n  Lemma candidate_entries_init :\n    refined_raft_net_invariant_init CandidateEntries.\n  Proof.\n    red.\n    unfold CandidateEntries.\n    unfold candidateEntries_host_invariant, candidateEntries_nw_invariant.\n    intuition;\n     repeat match goal with\n            | [ H : In _ _ |- _ ] => compute in H\n            end;\n    intuition.\n  Qed.\n\n  Theorem candidate_entries_invariant :\n    forall (net : network),\n      refined_raft_intermediate_reachable net ->\n      CandidateEntries net.\n  Proof.\n    intros.\n    eapply refined_raft_net_invariant; eauto.\n    - apply candidate_entries_init.\n    - apply candidate_entries_client_request.\n    - apply candidate_entries_timeout.\n    - apply candidate_entries_append_entries.\n    - apply candidate_entries_append_entries_reply.\n    - apply candidate_entries_request_vote.\n    - apply candidate_entries_request_vote_reply.\n    - apply candidate_entries_do_leader.\n    - apply candidate_entries_do_generic_server.\n    - apply candidate_entries_state_same_packet_subset.\n    - apply candidate_entries_reboot.\n  Qed.\nEnd CandidateEntries.\n", "meta": {"author": "andres-erbsen", "repo": "notary", "sha": "a2bd24db19a19642480fe17d3ee83e75ae8df61f", "save_path": "github-repos/coq/andres-erbsen-notary", "path": "github-repos/coq/andres-erbsen-notary/notary-a2bd24db19a19642480fe17d3ee83e75ae8df61f/raft/CandidateEntries.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.22014653947244145}}
{"text": "Require Import List.\nRequire Import Bool.\nRequire Import BinNat.\nRequire Import Omega.\nRequire Import sflib.\n\nRequire Import Common.\nRequire Import Memory.\nRequire Import Value.\nRequire Import Lang.\nRequire Import State.\nRequire Import LoadStore.\nRequire Import Behaviors.\nRequire Import SmallStep.\nRequire Import SmallStepAux.\n\nImport SmallStep.\nImport Ir.\nImport Ir.SmallStep.\nImport SmallStepAux.\nImport Ir.\nImport Ir.SmallStep.\n\nModule Ir.\n\nModule SmallStep.\n\n(****************************************************\n        Theorems about sstep of instruction.\n ****************************************************)\n\nLemma incrpc_wf:\n  forall md c c'\n         (HWF:Ir.Config.wf md c)\n         (HC':c' = incrpc md c),\n    Ir.Config.wf md c'.\nProof.\n  (* High-level proof: incrpc changes stack frame only, and\n     next_trivial_pc satisfies valid_pc. *) \n  intros.\n  unfold incrpc in HC'.\n  destruct (Ir.Config.cur_fdef_pc md c) eqn:HC.\n  - destruct p as [fdef pc0].\n    remember (Ir.IRFunction.next_trivial_pc pc0 fdef) as pc_next.\n    destruct pc_next as [pc_next | ].\n    unfold Ir.Config.update_pc in HC'.\n    remember (Ir.Config.s c) as s'.\n    destruct s' as [ | [cid [pc0' r0']] st] .\n    + congruence.\n    + (* show that pc0' = pc0 *)\n      unfold Ir.Config.cur_fdef_pc in HC.\n      rewrite <- Heqs' in HC.\n      remember (Ir.Config.get_funid c cid) as ofunid.\n      destruct ofunid as [funid | ]; try (inversion HC; fail).\n      remember (Ir.IRModule.getf funid md) as ofdef'.\n      destruct ofdef' as [fdef' | ]; try (inversion HC; fail).\n      inversion HC.\n      rewrite H0, H1 in *.\n      clear H0 H1 HC.\n      (* Now prove Ir.Config.wf c' *)\n      rewrite HC'.\n      inversion HWF.\n      split.\n      * assumption.\n      * assumption.\n      * assumption.\n      * simpl.\n        intros.\n        rewrite <- Heqs' in wf_stack.\n        simpl in wf_stack.\n        destruct HIN.\n        -- inversion H. rewrite H1, H2, H3 in *. clear H H1 H2 H3.\n           apply Ir.IRFunction.next_trivial_pc_valid with (pc1 := pc0).\n           apply wf_stack with (curcid0 := curcid) (funid := funid0) (curregfile0 := curregfile).\n           left. reflexivity.\n           eassumption. assumption.\n           assert (HINCID:Some funid0 = Ir.Config.get_funid c curcid).\n           { eapply Ir.Config.cid_to_f_In_get_funid. eassumption. assumption. }\n           rewrite <- Heqofunid in HINCID.\n           inversion HINCID.\n           rewrite H0 in HF. rewrite <- HF in Heqofdef'.\n           inversion Heqofdef'. rewrite <- H1. congruence.\n         -- apply wf_stack with (curcid := curcid) (funid := funid0) (curregfile := curregfile).\n            right. assumption. assumption. assumption.\n      * simpl. intros.\n        eapply wf_ptr. erewrite <- get_val_incrpc with (md := md).\n        unfold incrpc. unfold Ir.Config.cur_fdef_pc. rewrite <- Heqs'.\n        rewrite <- Heqofunid. rewrite <- Heqofdef'.\n        rewrite <- Heqpc_next. unfold Ir.Config.update_pc.\n        rewrite <- Heqs'. eassumption.\n      * simpl. intros. eapply wf_ptr_mem.\n        eassumption. eassumption. eassumption.\n    + congruence.\n  - congruence.\nQed.\n\nLemma update_rval_wf:\n  forall md c c' r v\n         (HWF:Ir.Config.wf md c)\n         (HC':c' = Ir.Config.update_rval c r v)\n         (HPTRWF:forall p, v = Ir.ptr p -> Ir.Config.ptr_wf p (Ir.Config.m c)),\n    Ir.Config.wf md c'.\nProof.\n  intros.\n  inversion HWF.\n  unfold Ir.Config.update_rval in HC'.\n  rewrite HC'. clear HC'.\n  destruct (Ir.Config.s c) as [ | [cid0 [pc0 reg0]] s'] eqn:Hs.\n  { split; try assumption.\n    intros. rewrite Hs in HIN. inversion HIN. }\n  { split; try (simpl; assumption).\n    simpl. intros.\n    destruct HIN.\n    - inversion H.\n      destruct curregfile; inversion H3.\n      rewrite H1, H2 in *. clear H1 H2.\n      eapply wf_stack with (curcid0 := curcid). simpl. left. reflexivity.\n      eassumption. assumption.\n    - eapply wf_stack.\n      simpl. right. eassumption. eassumption. assumption.\n    - simpl. intros.\n      unfold Ir.Config.get_val in HGETVAL.\n      unfold Ir.Config.get_rval in HGETVAL.\n      simpl in HGETVAL.\n      destruct op eqn:Hop.\n      + eapply wf_ptr with (op := op). unfold Ir.Config.get_val. \n        des_ifs.\n      + destruct (Nat.eqb r r0) eqn:Hreg.\n        { apply HPTRWF with (p := p).\n          rewrite Nat.eqb_eq in Hreg. subst r0.\n          rewrite Ir.Regfile.get_update in HGETVAL. congruence. }\n        { rewrite Nat.eqb_neq in Hreg.\n          rewrite Ir.Regfile.get_update2 in HGETVAL; try congruence.\n          eapply wf_ptr with (op := Ir.opreg r0).\n          unfold Ir.Config.get_val. unfold Ir.Config.get_rval.\n          des_ifs. }\n  }\nQed.\n\nLemma update_reg_and_incrpc_wf:\n  forall md c c' v r\n         (HWF:Ir.Config.wf md c)\n         (HC':c' = update_reg_and_incrpc md c r v)\n         (HPTRWF:forall p, v = Ir.ptr p -> Ir.Config.ptr_wf p (Ir.Config.m c)),\n    Ir.Config.wf md c'.\nProof.\n  intros.\n  unfold update_reg_and_incrpc in HC'.\n  assert (Ir.Config.wf md (Ir.Config.update_rval c r v)).\n  { eapply update_rval_wf. eassumption. reflexivity.  eassumption. }\n  rewrite HC'.\n  eapply incrpc_wf.\n  eapply H. reflexivity.\nQed.\n\n\n(* terminator small step preserves wellformedness. *)\nLemma t_step_wf:\n  forall md c c' e\n         (HWF:Ir.Config.wf md c)\n         (HSTEP:t_step md c = sr_success e c'),\n    Ir.Config.wf md c'.\nProof.\n  intros.\n  inv HWF.\n  unfold t_step in HSTEP.\n  des_ifs.\n  { unfold br in HSTEP.\n    des_ifs.\n    split; try (unfold Ir.Config.update_pc; des_ifs; done).\n    { unfold Ir.Config.update_pc.\n      simpl in wf_stack. simpl.\n      intros.\n      destruct (Ir.Config.s c) eqn:HS.\n      { rewrite HS in HIN. inv HIN. }\n      destruct p1. destruct p1. simpl in *.\n      destruct HIN.\n      { inv H.\n        unfold Ir.Config.cur_fdef_pc in Heq0.\n        rewrite HS in Heq0.\n        unfold Ir.Config.get_funid in Heq0.\n        des_ifs.\n        apply list_find_key_In in HIN2.\n        rewrite Heq0 in HIN2.\n        assert (List.length (p::l) < 2).\n        { eapply list_find_key_NoDup.\n          eapply wf_cid_to_f.\n          rewrite Heq0. reflexivity. }\n        destruct l.\n        { inv HIN2; try inv H0.\n          simpl in Heq3. rewrite Heq3 in HF. inv HF.\n          eapply Ir.IRFunction.get_begin_pc_bb_valid.\n          eassumption.\n        }\n        { simpl in H. omega. }\n      }\n      { eapply wf_stack.\n        { right. eassumption. }\n        { eassumption. }\n        { eassumption. }\n      }\n    }\n    { simpl. intros.\n      rewrite Ir.Config.m_update_pc. rewrite Ir.Config.get_val_update_pc in HGETVAL.\n      eapply wf_ptr. eassumption. }\n  }\n  { unfold br in HSTEP.\n    des_ifs.\n    split; try (unfold Ir.Config.update_pc; des_ifs; done).\n    { unfold Ir.Config.update_pc.\n      simpl in wf_stack. simpl.\n      intros.\n      destruct (Ir.Config.s c) eqn:HS.\n      { rewrite HS in HIN. inv HIN. }\n      destruct p1. destruct p1. simpl in *.\n      destruct HIN.\n      { inv H.\n        unfold Ir.Config.cur_fdef_pc in Heq0.\n        rewrite HS in Heq0.\n        unfold Ir.Config.get_funid in Heq0.\n        des_ifs.\n        apply list_find_key_In in HIN2.\n        rewrite Heq0 in HIN2.\n        assert (List.length (p::l) < 2).\n        { eapply list_find_key_NoDup.\n          eapply wf_cid_to_f.\n          rewrite Heq0. reflexivity. }\n        destruct l.\n        { inv HIN2; try inv H0.\n          simpl in Heq5. rewrite Heq5 in HF. inv HF.\n          eapply Ir.IRFunction.get_begin_pc_bb_valid.\n          eassumption.\n        }\n        { simpl in H. omega. }\n      }\n      { eapply wf_stack.\n        { right. eassumption. }\n        { eassumption. }\n        { eassumption. }\n      }\n    }\n    { simpl. intros.\n      rewrite Ir.Config.m_update_pc. rewrite Ir.Config.get_val_update_pc in HGETVAL.\n      eapply wf_ptr. eassumption. }\n  }\n  { unfold br in HSTEP.\n    des_ifs.\n    split; try (unfold Ir.Config.update_pc; des_ifs; done).\n    { unfold Ir.Config.update_pc.\n      simpl in wf_stack. simpl.\n      intros.\n      destruct (Ir.Config.s c) eqn:HS.\n      { rewrite HS in HIN. inv HIN. }\n      destruct p1. destruct p1. simpl in *.\n      destruct HIN.\n      { inv H.\n        unfold Ir.Config.cur_fdef_pc in Heq0.\n        rewrite HS in Heq0.\n        unfold Ir.Config.get_funid in Heq0.\n        des_ifs.\n        apply list_find_key_In in HIN2.\n        rewrite Heq0 in HIN2.\n        assert (List.length (p::l) < 2).\n        { eapply list_find_key_NoDup.\n          eapply wf_cid_to_f.\n          rewrite Heq0. reflexivity. }\n        destruct l.\n        { inv HIN2; try inv H0.\n          simpl in Heq5. rewrite Heq5 in HF. inv HF.\n          eapply Ir.IRFunction.get_begin_pc_bb_valid.\n          eassumption.\n        }\n        { simpl in H. omega. }\n      }\n      { eapply wf_stack.\n        { right. eassumption. }\n        { eassumption. }\n        { eassumption. }\n      }\n    }\n    { simpl. intros.\n      rewrite Ir.Config.m_update_pc. rewrite Ir.Config.get_val_update_pc in HGETVAL.\n      eapply wf_ptr. eassumption. }\n  }\nQed.\n\nLtac thats_it := eapply update_reg_and_incrpc_wf; eauto.\nLtac des_op c op op' HINV :=\n  destruct (Ir.Config.get_val c op) as [op' | ]; try (inversion HINV; fail).\nLtac des_inv v HINV :=\n  destruct (v); try (inversion HINV; fail).\nLtac try_wf :=\n  des_ifs; try (eapply update_reg_and_incrpc_wf; try eassumption;\n                try reflexivity; try congruence; fail).\n\nLemma gep_wf:\n  forall p n t m inb p0\n         (HGEP:gep p n t m inb = Ir.ptr p0)\n         (HMWF:Ir.Memory.wf m)\n         (HPWF:Ir.Config.ptr_wf p m),\n    Ir.Config.ptr_wf p0 m.\nProof.\n  intros.\n  unfold gep in HGEP.\n  inv HPWF.\n  des_ifs.\n  { exploit H. ss. intros HH. inv HH. inv H2.\n    rewrite Heq in H3. inv H3.\n    split.\n    { intros. inv H2.\n      split.\n      apply twos_compl_add_lt.\n      eauto.\n    }\n    { intros. ss. }\n  }\n  { exploit H. ss. intros HH. inv HH. inv H2.\n    split.\n    { intros. inv H2. split.\n      apply twos_compl_add_lt.\n      eauto. }\n    { intros. ss. }\n  }\n  { exploit H0. ss. intros HH.\n    split.\n    { intros. ss. }\n    { intros. inv H1.\n      apply twos_compl_add_lt. }\n  }\n  { exploit H0. ss. intros HH.\n    split.\n    { intros. ss. }\n    { intros. inv H1.\n      apply twos_compl_add_lt. }\n  }\n  { exploit H0. ss. intros HH.\n    split.\n    { intros. ss. }\n    { intros. inv H1.\n      apply twos_compl_add_lt. }\n  }\nQed.\n\nLemma getpbits_ptr_in_byte:\n  forall x p n\n    (HPBITS:Ir.Byte.getpbits x = Some (p, n)),\n    Ir.Config.ptr_in_byte p n x.\nProof.\n  intros.\n  unfold Ir.Byte.getpbits in HPBITS.\n  unfold Ir.Config.ptr_in_byte.\n  des_ifs.\n  eauto.\nQed.\n\nLemma load_val_ptr_wf:\n  forall md st p retty p0\n         (HLOAD:Ir.load_val (Ir.Config.m st) p retty = Ir.ptr p0)\n         (HWF:Ir.Config.wf md st)\n         (HPWF:Ir.Config.ptr_wf p (Ir.Config.m st)),\n    Ir.Config.ptr_wf p0 (Ir.Config.m st).\nProof.\n  intros.\n  unfold Ir.load_val in HLOAD.\n  des_ifs.\n  unfold Ir.Byte.getptr in Heq.\n  unfold Ir.ty_bytesz in Heq.\n  unfold Ir.ty_bitsz in Heq.\n  rewrite Ir.PTRSZ_def in Heq.\n  simpl in Heq.\n  des_ifs.\n  unfold Ir.load_bytes in Heq1.\n  des_ifs.\n  dup Heq.\n  apply Ir.get_deref_singleton in Heq4. inv Heq4; try congruence.\n  inv H. inv H0. inv H. simpl in H1.\n  assert (exists x, l = x::nil).\n  { \n    destruct l; simpl in Heq0; try( inv Heq0; fail).\n    rewrite Nat.eqb_eq in Heq0.\n    destruct l. simpl in Heq0. eexists. reflexivity.\n    simpl in Heq0. omega.\n  }\n  inv H. simpl in Heq0.\n  simpl in Heq3. des_ifs.\n  inv HWF.\n  exploit wf_ptr_mem.\n  { rewrite H1.  reflexivity. }\n  { eapply Ir.MemBlock.bytes_In_c. eassumption.\n    assert (In t0 [t0;x]). left. ss. eapply H. }\n  { eapply getpbits_ptr_in_byte. eassumption. }\n  intros. ss.\n  { inv HWF. ss. }\n  omega.\nQed.\n\nLemma store_val_ptr_wf:\n  forall md p0 c p v valty\n         (HWF:Ir.Config.wf md c)\n         (HPWF:Ir.Config.ptr_wf p0 (Ir.Config.m c)),\n  Ir.Config.ptr_wf p0 (Ir.store_val (Ir.Config.m c) p v valty).\nProof.\n  intros.\n  inv HPWF.\n  destruct p0.\n  { exploit H. ss. intros HH. inv HH. inv H2.\n    split.\n    { intros. inv H2. split. ss.\n      unfold Ir.store_val. des_ifs; eauto.\n      { unfold Ir.store_bytes.\n        des_ifs; eauto.\n        destruct (b =? l) eqn:HEQ.\n        { rewrite Nat.eqb_eq in HEQ. subst b.\n          erewrite Ir.Memory.get_set_id_short; try eassumption.\n          eexists. ss. inv HWF. ss. }\n        { rewrite Ir.Memory.get_set_diff_short. eexists. eassumption.\n          inv HWF. ss. rewrite Nat.eqb_neq in HEQ. congruence. }\n      }\n      { unfold Ir.store_bytes.\n        des_ifs; eauto.\n        destruct (b =? l) eqn:HEQ.\n        { rewrite Nat.eqb_eq in HEQ. subst b.\n          erewrite Ir.Memory.get_set_id_short; try eassumption.\n          eexists. ss. inv HWF. ss. }\n        { rewrite Ir.Memory.get_set_diff_short. eexists. eassumption.\n          inv HWF. ss. rewrite Nat.eqb_neq in HEQ. congruence. }\n      }\n    }\n    { intros. congruence. }\n  }\n  { exploit H0. ss. intros HH.\n    split.\n    { intros. congruence. }\n    { intros. inv H1. ss. }\n  }\nQed.\n\nLemma In_ofint_not_ptr_in_byte:\n  forall n1 len b p0 ofs\n         (HIN:In b (Ir.Byte.ofint n1 len)),\n    ~ Ir.Config.ptr_in_byte p0 ofs b.\nProof.\n  intros.\n  unfold Ir.Byte.ofint in HIN.\n  remember (Ir.Bit.add_hzerobits (Ir.Bit.N_to_bits n1) (len - length (Ir.Bit.N_to_bits n1)))\n           as bits.\n  assert (List.Forall (fun b => forall p ofs, b <> Ir.Bit.baddr p ofs) bits).\n  { rewrite Heqbits.\n    eapply Ir.Byte.add_hzerobits_notbaddr.\n    rewrite Forall_forall.\n    intros.\n    eapply Ir.Byte.N_to_bits_notbaddr. eassumption.\n  }\n  eapply Ir.Byte.from_bits_notbaddr in H.\n  rewrite Forall_forall in H.\n  apply H with (p := p0) (ofs := ofs) in HIN.\n  intros HH.\n  unfold Ir.Config.ptr_in_byte in HH.\n  intuition.\nQed.\n\nLemma ptr_wf_set:\n  forall p1 c b mb'\n    (HMWF:Ir.Memory.wf (Ir.Config.m c))\n    (HPTRWF:Ir.Config.ptr_wf p1 (Ir.Config.m c)),\n    Ir.Config.ptr_wf p1 (Ir.Memory.set (Ir.Config.m c) b mb').\nProof.\n  intros.\n  destruct p1.\n  { inv HPTRWF. exploit H. ss. intros HH. inv HH.\n    inv H2.\n    split.\n    { intros. inv H2. split. ss.\n      destruct (l =? b) eqn:HEQ.\n      { rewrite Nat.eqb_eq in HEQ. subst l.\n        erewrite Ir.Memory.get_set_id_short. eexists. ss.\n        ss. eassumption. }\n      { erewrite Ir.Memory.get_set_diff_short. eexists. eassumption.\n        ss. rewrite Nat.eqb_neq in HEQ. congruence.\n      }\n    }\n    { intros. congruence. }\n  }\n  { inv HPTRWF. exploit H0. ss. intros HH.\n    split.\n    { intros. congruence. }\n    { intros. inv H1. eauto. }\n  }\nQed.\n\nLemma store_val_ptr_mem_wf:\n  forall md c opptr mb p v valty bid byt p0 ofs mb0\n         (HWF:Ir.Config.wf md c)\n         (HOPVAL:Ir.Config.get_val c opptr = Some v)\n         (HGET0:Some mb0 = Ir.Memory.get (Ir.Config.m c) bid)\n         (HGET:Some mb = Ir.Memory.get (Ir.store_val (Ir.Config.m c) p v valty) bid)\n         (HIN:In byt (Ir.MemBlock.c mb))\n         (HPTR:Ir.Config.ptr_in_byte p0 ofs byt),\n    Ir.Config.ptr_wf p0 (Ir.store_val (Ir.Config.m c) p v valty).\nProof.\n  intros.\n  unfold Ir.store_val in *.\n  des_ifs; try (inv HWF; eapply wf_ptr_mem; eassumption).\n  { unfold Ir.store_bytes in *.\n    des_ifs;\n      try (inv HWF; eapply wf_ptr_mem; eassumption).\n    eapply Ir.get_deref_singleton in Heq0.\n    destruct Heq0; try congruence.\n    destruct H. destruct H. inv H. simpl in H0.\n    destruct (b =? bid) eqn:HBID.\n    { rewrite Nat.eqb_eq in HBID. subst bid.\n      erewrite Ir.Memory.get_set_id in HGET.\n      3: rewrite <- HGET0; reflexivity.\n      3: reflexivity.\n      inv HGET.\n      unfold Ir.MemBlock.set_bytes in HIN.\n      simpl in HIN.\n      apply List.in_app_or in HIN.\n      destruct HIN.\n      { (* unchanged part *)\n        inv HWF.\n        eapply ptr_wf_set. ss. eapply wf_ptr_mem.\n        rewrite H0. ss.\n        eapply firstn_In. ss. eassumption. eassumption.\n      }\n      apply List.in_app_or in H.\n      destruct H.\n      { (* changed part! but it's integer. *)\n        eapply In_ofint_not_ptr_in_byte in H.\n        eapply H in HPTR. inv HPTR.\n      }\n      { (* unchanged part. *)\n        inv HWF.\n        eapply ptr_wf_set. ss. eapply wf_ptr_mem.\n        rewrite H0. ss.\n        eapply skipn_In. ss. eassumption. eassumption.\n      }\n      { inv HWF. ss. }\n    }\n    { (* b <> bid *)\n      rewrite Ir.Memory.get_set_diff_short in HGET.\n      inv HWF.\n      eapply ptr_wf_set. ss. eapply wf_ptr_mem.\n      rewrite HGET. ss. eassumption. eassumption.\n      inv HWF. ss.\n      rewrite Nat.eqb_neq in HBID. congruence.\n    }\n    inv HWF. ss.\n    rewrite Nat.eqb_eq in Heq. rewrite <- Heq.\n    apply Ir.ty_bytesz_pos.\n  }\n  { (* stored value is ptr. *)\n    unfold Ir.store_bytes in *.\n    des_ifs; try (inv HWF; eauto; fail).\n    eapply Ir.get_deref_singleton in Heq0.\n    destruct Heq0; try congruence.\n    inv H. inv H0. inv H. simpl in H1.\n    destruct (b =? bid) eqn:HBID.\n    { rewrite Nat.eqb_eq in HBID. subst bid.\n      erewrite Ir.Memory.get_set_id in HGET.\n      3: eapply H1. 3: reflexivity.\n      inv HGET.\n      unfold Ir.MemBlock.set_bytes in *.\n      simpl in *.\n      eapply List.in_app_or in HIN.\n      destruct HIN.\n      { (* unchangd part *)\n        inv HWF.\n        eapply ptr_wf_set. ss. eapply wf_ptr_mem.\n        rewrite H1. ss. eapply firstn_In. ss. eassumption. eassumption.\n      }\n      unfold Ir.Byte.ofptr in H.\n      rewrite Ir.PTRSZ_def in H.\n      simpl in H.      \n      destruct H.\n      { (* changed part 1 *)\n        (* should use ptr_wf *)\n        rewrite <- H in HPTR.\n        unfold Ir.Config.ptr_in_byte in HPTR. simpl in HPTR.\n        inv HWF. dup HOPVAL.\n        apply wf_ptr in HOPVAL.\n        assert (HP0P1:p0 = p1).\n        { destruct HPTR. congruence.\n          repeat (destruct H; try congruence). }\n        subst p0.\n        eapply ptr_wf_set. ss. eapply wf_ptr. eassumption.\n      }\n      destruct H. (* one more time *)\n      { \n        (* should use ptr_wf *)\n        rewrite <- H in HPTR.\n        unfold Ir.Config.ptr_in_byte in HPTR. simpl in HPTR.\n        inv HWF. dup HOPVAL.\n        apply wf_ptr in HOPVAL.\n        assert (HP0P1:p0 = p1).\n        { destruct HPTR. congruence.\n          repeat (destruct H; try congruence). }\n        subst p0.\n        eapply ptr_wf_set. ss. eapply wf_ptr. eassumption.\n      }\n      (* unchanged part *)\n      inv HWF.\n      eapply ptr_wf_set. ss. eapply wf_ptr_mem. rewrite H1. ss.\n      eapply skipn_In. ss. eassumption. eassumption.\n      inv HWF. ss.\n    }\n    { (* b <> bid *)\n      rewrite Ir.Memory.get_set_diff_short in HGET.\n      inv HWF.\n      eapply ptr_wf_set. ss. eapply wf_ptr_mem.\n      rewrite HGET. ss. eassumption. eassumption.\n      inv HWF. ss.\n      rewrite Nat.eqb_neq in HBID. congruence.\n    }\n    inv HWF. ss.\n    rewrite Nat.eqb_eq in Heq. rewrite <- Heq.\n    apply Ir.ty_bytesz_pos.\n  }\nQed.\n\nLemma free_ptr_wf:\n  forall c b t p\n    (HMWF:Ir.Memory.wf (Ir.Config.m c))\n    (HFREE: Ir.Memory.free (Ir.Config.m c) b = Some t)\n    (HWF:Ir.Config.ptr_wf p (Ir.Config.m c)),\n    Ir.Config.ptr_wf p t.\nProof.\n  intros.\n  inv HWF.\n  unfold Ir.Memory.free in HFREE.\n  des_ifs.\n  destruct p.\n  { exploit H. ss. intros HH. inv HH. inv H2.\n    split.\n    { intros. inv H2. split. ss.\n      destruct (b =? l) eqn:HEQ.\n      { rewrite Nat.eqb_eq in HEQ.  subst b.\n        erewrite Ir.Memory.get_set_id_short. eexists. ss.\n        eapply Ir.Memory.incr_time_wf. eassumption.\n        ss.\n        rewrite Ir.Memory.get_incr_time_id. eassumption.\n      }\n      { rewrite Ir.Memory.get_set_diff_short.\n        rewrite Ir.Memory.get_incr_time_id. eexists. eassumption.\n        eapply Ir.Memory.incr_time_wf. eassumption. ss.\n        rewrite Nat.eqb_neq in HEQ. congruence.\n      }\n    }\n    { intros. congruence. }\n  }\n  { exploit H0. ss. intros HH.\n    split.\n    { intros. congruence. }\n    { intros. inv H1. ss. }\n  }\nQed.\n\n\n(* Lemma: inst_det_step preserves well-formedness of configuration. *)\nLemma inst_det_step_wf:\n  forall md c c' i e\n         (HWF:Ir.Config.wf md c)\n         (HCUR:Some i = Ir.Config.cur_inst md c)\n         (HNEXT:Some (sr_success e c') = inst_det_step md c),\n    Ir.Config.wf md c'.\nProof.\n    intros.\n    unfold inst_det_step in HNEXT. (* ibinop. *)\n    rewrite <- HCUR in HNEXT.\n    destruct i as [r retty bopc op1 op2 (* ibinop *)\n                  |r op1 retty (* ifreeze *)\n                  |r opcond condty op1 op2 opty (* iselect *)\n                  |r retty ptrty opptr1 opptr2 (* ipsub *)\n                  |r retty opptr opidx inb (* igep *)\n                  |r retty opptr (* iload *)\n                  |valty opval opptr (* istore *)\n                  |(* imalloc *)\n                  |opptr (* ifree *)\n                  |r opval retty (* ibitcast *)\n                  |r opptr retty (* iptrtoint *)\n                  |r opint retty (* iinttoptr *)\n                  |opval (* ievent *)\n                  |r opty op1 op2 (* iicmp_eq *)\n                  |r opty op1 op2 (* iicmp_ule *)\n                  ] eqn:HINST; try (inversion HNEXT; fail).\n    + destruct bopc; try_wf.\n    + (* ifreeze. *) try_wf.\n    + (* iselect. *) try_wf.\n      eapply update_reg_and_incrpc_wf. eassumption. ss. inv HWF.\n      intros. destruct v; try discriminate. inv H. eapply wf_ptr. eassumption.\n      eapply update_reg_and_incrpc_wf. eassumption. ss. inv HWF.\n      intros. destruct v0; try discriminate. inv H. eapply wf_ptr. eassumption.\n    + (* ipsub. *) unfold psub in HNEXT. try_wf.\n    + (* igep. *) try_wf.\n      eapply update_reg_and_incrpc_wf; try reflexivity.\n      eassumption.\n      intros. eapply gep_wf; try eassumption.\n      inv HWF. assumption. inv HWF. eapply wf_ptr; eassumption.\n    + (* iload. *) try_wf.\n      eapply update_reg_and_incrpc_wf. eassumption. reflexivity.\n      intros. dup HWF. inv HWF.\n      eapply load_val_ptr_wf. eassumption. eassumption.\n      eapply wf_ptr. eassumption.\n    + (* istore. *) try_wf; try (eapply incrpc_wf; try eassumption; try reflexivity; fail).\n      apply incrpc_wf with (c := Ir.Config.update_m c (Ir.store_val (Ir.Config.m c) p v valty)).\n      dup HWF. destruct HWF.\n      split; simpl; try assumption. eapply Ir.store_val_wf. eassumption.\n      eapply Ir.ty_bytesz_pos. congruence.\n      * intros. rewrite Ir.Config.get_val_update_m in HGETVAL.\n        eapply store_val_ptr_wf. eassumption.\n        eapply wf_ptr in HGETVAL. ss.\n      * (* wf_ptr_mem *)\n        intros.\n        assert (exists mb', Some mb' = Ir.Memory.get (Ir.Config.m c) bid).\n        { unfold Ir.store_val in HBLK. unfold Ir.store_bytes in HBLK.\n          des_ifs; try (eexists; rewrite HBLK; reflexivity).\n          eapply Ir.Memory.get_set_exists. eassumption.\n          eapply Ir.Memory.get_set_exists. eassumption.\n        }\n        inv H.\n        eapply store_val_ptr_mem_wf; try eassumption.\n      * ss.\n    + (* ifree *) try_wf; try (eapply incrpc_wf; try eassumption; try reflexivity; fail).\n      apply incrpc_wf with (c := Ir.Config.update_m c t); try reflexivity.\n      unfold free in Heq0.\n      destruct HWF.\n      des_ifs.\n      * split.\n        -- eapply Ir.Memory.free_wf. eassumption.\n           rewrite Heq0. unfold Ir.Config.update_m. reflexivity.\n        -- unfold Ir.Config.cid_to_f in *. des_ifs.\n        -- intros. apply wf_cid_to_f2. unfold Ir.Config.cid_to_f in *. des_ifs.\n        -- intros. rewrite Ir.Config.s_update_m in HIN. eauto.\n        -- intros.\n           rewrite Ir.Config.get_val_update_m in HGETVAL.\n           rewrite Ir.Config.m_update_m.\n           apply wf_ptr in HGETVAL.\n           eapply free_ptr_wf; eassumption.\n        -- intros. rewrite Ir.Config.m_update_m in *.\n           dup HBLK. symmetry in HBLK.\n           eapply Ir.Memory.get_free_some_inv in HBLK; try eauto.\n           inv HBLK.\n           erewrite <- Ir.Memory.get_free_c in HBYTE.\n           3: eauto. 4: eauto. 3: eauto. 2: eauto.\n           eapply free_ptr_wf. eassumption. eauto.\n           eapply wf_ptr_mem. rewrite H. eauto. eauto. eauto.\n      * split.\n        -- eapply Ir.Memory.free_wf. eassumption.\n           rewrite Heq0. unfold Ir.Config.update_m. reflexivity.\n        -- unfold Ir.Config.cid_to_f in *. des_ifs.\n        -- intros. apply wf_cid_to_f2. unfold Ir.Config.cid_to_f in *. des_ifs.\n        -- intros.\n           apply wf_stack with (curcid := curcid) (funid := funid) (curregfile := curregfile).\n           assumption. unfold Ir.Config.cid_to_f in *.\n           unfold Ir.Config.update_m in HIN2. destruct c. simpl in *. assumption.\n           assumption.\n        -- intros.\n           rewrite Ir.Config.get_val_update_m in HGETVAL.\n           rewrite Ir.Config.m_update_m.\n           apply wf_ptr in HGETVAL.\n           eapply free_ptr_wf; eassumption.\n        -- intros. rewrite Ir.Config.m_update_m in *.\n           dup HBLK. symmetry in HBLK.\n           eapply Ir.Memory.get_free_some_inv in HBLK; try eauto.\n           inv HBLK.\n           eapply free_ptr_wf. eassumption. eassumption.\n           eapply wf_ptr_mem.\n           3: eapply HBIT.\n           rewrite H. reflexivity.\n           erewrite <- Ir.Memory.get_free_c in HBYTE. 3:eauto. 4:eauto. 3:eauto. 2:eauto.\n           eauto.\n    + (* ibitcast. *) try_wf.\n      eapply update_reg_and_incrpc_wf. eassumption.\n      reflexivity.\n      intros. inv H.\n      inv HWF. eapply wf_ptr. eassumption.\n    + (* iptrtoint. *) try_wf.\n    + (* iinttoptr *) try_wf.\n      eapply update_reg_and_incrpc_wf; try eassumption.\n      reflexivity.\n      intros. inv H.\n      split. intros. congruence.\n      intros. inv H.\n      eapply twos_compl_lt.\n    + (* ievent *)\n      rename HNEXT into H2. simpl in H2.\n      des_op c opval opv H2. des_inv opv H2.\n      inversion H2. eapply incrpc_wf. eassumption. reflexivity.\n    + (* iicmp_eq, det *)\n      rename HNEXT into HC'. simpl in HC'.\n      des_op c op1 op1v HC'.\n      { des_ifs;\n        try (eapply update_reg_and_incrpc_wf;\n             [ eassumption | ss | intros H1 H2; unfold to_num in H2; congruence ]).\n      }\n      { des_ifs;\n        try (eapply update_reg_and_incrpc_wf;\n             [ eassumption | ss | intros H1 H2; unfold to_num in H2; congruence ]).\n      }\n    + (* iicmp_ule, det *)\n      rename HNEXT into HC'. simpl in HC'.\n      des_op c op1 op1v HC'.\n      { des_inv op1v HC';\n          des_op c op2 op2v HC'; try (inv HC'; try_wf).\n        try (eapply update_reg_and_incrpc_wf;\n             [ eassumption | ss | intros H1 H2; unfold to_num in H2; congruence ]).\n        try (eapply update_reg_and_incrpc_wf;\n             [ eassumption | ss | intros H1 H2; unfold to_num in H2; congruence ]).\n      }\n      { des_ifs; try_wf. }\nQed.\n\nLemma new_ptr_wf:\n  forall md c p m' nsz contents P l\n         (HWF:Ir.Config.wf md c)\n         (HSZ:nsz > 0)\n         (HGET:Ir.Config.ptr_wf p (Ir.Config.m c))\n         (HDISJ:Ir.Memory.allocatable (Ir.Config.m c)\n                                      (map (fun addr : nat => (addr, nsz)) P) = true)\n         (HMBWF : forall begt : Ir.time,\n          Ir.MemBlock.wf\n            {|\n            Ir.MemBlock.bt := Ir.heap;\n            Ir.MemBlock.r := (begt, None);\n            Ir.MemBlock.n := nsz;\n            Ir.MemBlock.a := Ir.SYSALIGN;\n            Ir.MemBlock.c := contents;\n            Ir.MemBlock.P := P |})\n         (HNEW:(m', l) = Ir.Memory.new (Ir.Config.m c) Ir.heap nsz Ir.SYSALIGN contents P),\n    Ir.Config.ptr_wf p m'.\nProof.\n  intros.\n  inv HGET.\n  destruct p.\n  { exploit H. ss. intros HH. inv HH. inv H2.\n    split.\n    { intros. inv H2. split. ss.\n      eapply Ir.Memory.get_new in HNEW. rewrite HNEW. eexists. eassumption.\n      inv HWF. ss. ss. ss.\n      ss.\n      exploit H. ss. intros HH. inv HH.\n      inv HWF. inv wf_m.\n      eapply forallb_In in wf_newid.\n      rewrite Nat.ltb_lt in wf_newid. eassumption.\n      inv H4. symmetry in H5. eapply Ir.Memory.get_In_key in H5. eassumption.\n      ss.\n    }\n    { intros. congruence. }\n  }\n  { exploit H0. ss. intros HH.\n    split.\n    { intros. congruence. }\n    { intros. inv H1. omega. }\n  }\nQed.\n\nLemma poison_not_ptr_in_byte:\n  forall nsz byt ofs p\n         (HIN:In byt (repeat Ir.Byte.poison nsz)),\n    ~Ir.Config.ptr_in_byte p ofs byt.\nProof.\n  intros.\n  intros HH.\n  unfold Ir.Config.ptr_in_byte in HH.\n  assert (byt = Ir.Byte.poison).\n  { apply repeat_spec in HIN. subst.\n    unfold Ir.Byte.poison in *.\n    simpl in *. reflexivity.\n  }\n  subst byt.\n  unfold Ir.Byte.poison. simpl in *.\n  repeat (destruct HH as [Ha | HH]; try inv Ha).\n  inv HH.\nQed.\n\n(* Lemma: inst_step preserves well-formedness of configuration. *)\nLemma inst_step_wf:\n  forall md c c' e\n         (HWF:Ir.Config.wf md c)\n         (HSTEP:inst_step md c (sr_success e c')),\n    Ir.Config.wf md c'.\nProof.\n  intros.\n  inversion HSTEP.\n  - unfold inst_det_step in HNEXT.\n    destruct (Ir.Config.cur_inst md c) as [i0|] eqn:Hcur.\n    eapply inst_det_step_wf. eassumption.\n    rewrite Hcur. reflexivity. unfold inst_det_step.\n    rewrite Hcur. eassumption.\n    inversion HNEXT.\n  - (* freeze *)\n    thats_it. intros. ss.\n  - (* imalloc returning null *)\n    thats_it. unfold Ir.NULL.\n    intros. inv H0.\n    split. intros. congruence.\n    intros. inv H. apply Ir.MEMSZ_pos.\n  - (* imalloc, succeed *)\n    eapply update_reg_and_incrpc_wf with (c := Ir.Config.update_m c m').\n    + inversion HWF.\n      split; try (simpl; assumption).\n      * simpl. eapply Ir.Memory.new_wf.\n        eapply wf_m.\n        eassumption.\n        eassumption.\n        eassumption.\n      * intros.\n        rewrite Ir.Config.get_val_update_m in HGETVAL.\n        rewrite Ir.Config.m_update_m.\n        apply wf_ptr in HGETVAL.\n        eapply new_ptr_wf; eassumption.\n      * intros. rewrite Ir.Config.m_update_m in *.\n        destruct (bid =? l) eqn:HEQ.\n        { (* the newly allocated block - all poison. *)\n          rewrite Nat.eqb_eq in HEQ.\n          subst.\n          eapply Ir.Memory.get_new_c_poison in HBLK; try eassumption.\n          rewrite HBLK in HBYTE.\n          eapply poison_not_ptr_in_byte in HBYTE.\n          eapply HBYTE in HBIT. inv HBIT.\n        }\n        { (* old blocks *)\n          assert (bid < l).\n          { eapply Ir.Memory.get_In_key in HBLK; try reflexivity.\n            assert (wf':Ir.Memory.wf m').\n            { eapply Ir.Memory.new_wf. eapply wf_m. eassumption.\n              ss. eassumption. }\n            inv wf'.\n            eapply forallb_In with (i := bid) in wf_newid; try assumption.\n            unfold Ir.Memory.new in HNEW.\n            inv HNEW.\n            simpl in *.\n            rewrite Nat.ltb_lt in wf_newid.\n            rewrite Nat.eqb_neq in HEQ.\n            omega.\n          }\n          assert (HBLK':Some mb = Ir.Memory.get (Ir.Config.m c) bid).\n          { unfold Ir.Memory.new in HNEW.\n            inv HNEW.\n            unfold Ir.Memory.get in HBLK.\n            simpl in HBLK.\n            rewrite Nat.eqb_sym in HEQ.\n            rewrite HEQ in HBLK.\n            unfold Ir.Memory.get.\n            ss.\n          }\n          exploit wf_ptr_mem.\n          eapply HBLK'. eassumption. eassumption.\n          intros HH. \n          eapply new_ptr_wf; eassumption.\n        }\n    + reflexivity.\n    + intros. inv H0.\n      split.\n      { intros. inv H. split. apply Ir.MEMSZ_pos.\n        unfold Ir.Memory.new in HNEW. inv HNEW.\n        simpl. unfold Ir.Memory.get. simpl. rewrite Nat.eqb_refl.\n        eexists. ss.\n      }\n      { intros. congruence. }\n  - (* iicmp_eq, nondet *)\n    eapply update_reg_and_incrpc_wf.\n    eassumption.\n    reflexivity.\n    intros. congruence.\n  - (* icmp_ule, nondet *)\n    eapply update_reg_and_incrpc_wf. eassumption. reflexivity.\n    intros. congruence.\nQed.\n\nLemma phi_step_wf:\n  forall md c c' bef_bbid\n         (HWF:Ir.Config.wf md c)\n         (HSTEP:phi_step md bef_bbid c = Some c'),\n    Ir.Config.wf md c'.\nProof.\n  intros.\n  unfold phi_step in HSTEP.\n  des_ifs.\n  eapply update_reg_and_incrpc_wf. eassumption.\n  ss.\n  intros.\n  inv HWF.\n  eapply wf_ptr. eassumption.\nQed.\n\nLemma phi_bigstep_wf:\n  forall md c c' bef_bbid\n         (HWF:Ir.Config.wf md c)\n         (HSTEP:phi_bigstep md bef_bbid c c'),\n    Ir.Config.wf md c'.\nProof.\n  intros.\n  induction HSTEP.\n  { eapply phi_step_wf; eassumption. }\n  { apply IHHSTEP in HWF.\n    eapply phi_step_wf. eassumption. eassumption.\n  }\nQed.\n\n\n(* Theorem: small step preserves well-formedness of configuration. *)\nTheorem sstep_wf:\n  forall md c c' e\n         (HWF:Ir.Config.wf md c)\n         (HSTEP:sstep md c (sr_success e c')),\n    Ir.Config.wf md c'.\nProof.\n  intros.\n  inv HSTEP.\n  { eapply inst_step_wf. eassumption. eassumption. }\n  { assert (Ir.Config.wf md st').\n    { eapply t_step_wf. eassumption. eassumption. }\n    eapply phi_bigstep_wf; eassumption.\n  }\nQed.\n\n\n(****************************************************\n   Theorems regarding categorization of instruction.\n ****************************************************)\n\nLemma no_mem_change_after_incrpc:\n  forall md c,\n    Ir.Config.m c = Ir.Config.m (incrpc md c).\nProof.\n  intros.\n  unfold incrpc.\n  destruct (Ir.Config.cur_fdef_pc md c).\n  destruct p.\n  { des_ifs. unfold Ir.Config.update_pc.\n    des_ifs. }\n  reflexivity.\nQed.\n\nLemma no_mem_change_after_update:\n  forall md c r v,\n    Ir.Config.m c = Ir.Config.m (update_reg_and_incrpc md c r v).\nProof.\n  intros.\n  unfold update_reg_and_incrpc.\n  rewrite <- no_mem_change_after_incrpc.\n  unfold Ir.Config.update_rval.\n  des_ifs.\nQed.\n\n(* Lemma: inst_det_step preserves well-formedness of configuration. *)\nLtac thats_it2 := apply no_mem_change_after_update.\n\nLemma changes_mem_spec_det:\n  forall md c c' i e\n         (HWF:Ir.Config.wf md c)\n         (HCUR:Some i = Ir.Config.cur_inst md c)\n         (HNOMEMCHG:changes_mem i = false)\n         (HNEXT:Some (sr_success e c') = inst_det_step md c),\n    c.(Ir.Config.m) = c'.(Ir.Config.m).\nProof.\n    intros.\n    unfold inst_det_step in HNEXT. (* ibinop. *)\n    rewrite <- HCUR in HNEXT.\n    destruct i as [r retty bopc op1 op2 (* ibinop *)\n                  |r op1 retty (* ifreeze *)\n                  |r opcond condty op1 op2 opty (* iselect *)\n                  |r retty ptrty opptr1 opptr2 (* ipsub *)\n                  |r retty opptr opidx inb (* igep *)\n                  |r retty opptr (* iload *)\n                  |valty opval opptr (* istore *)\n                  |(* imalloc *)\n                  |opptr (* ifree *)\n                  |r opval retty (* ibitcast *)\n                  |r opptr retty (* iptrtoint *)\n                  |r opint retty (* iinttoptr *)\n                  |opval (* ievent *)\n                  |r opty op1 op2 (* iicmp_eq *)\n                  |r opty op1 op2 (* iicmp_ule *)\n                  ] eqn:HINST; try (inversion HNEXT; fail);\n      try (inversion HNOMEMCHG; fail);\n      try (des_ifs; thats_it2; fail).\n    + (* ievent *)\n      rename HNEXT into H2. simpl in H2.\n      des_op c opval opv H2. des_inv opv H2.\n      inversion H2. eapply no_mem_change_after_incrpc.\nQed.\n\n(* Theorem: if changes_mem returns false, memory isn't\n   changed after inst_step.\n   This includes ptrtoint/inttoptr/psub/gep/icmp. *)\nTheorem changes_mem_spec:\n  forall md c i c' e\n         (HWF:Ir.Config.wf md c)\n         (HCUR:Some i = Ir.Config.cur_inst md c)\n         (HNOMEMCHG:changes_mem i = false)\n         (HSTEP:inst_step md c (sr_success e c')),\n    c.(Ir.Config.m) = c'.(Ir.Config.m).\nProof.\n  intros.\n  inversion HSTEP.\n  - eapply changes_mem_spec_det. eassumption.\n    eassumption. assumption. eassumption.\n  - (* freeze *)\n    apply no_mem_change_after_update.\n  - (* malloc, NULL *)\n    apply no_mem_change_after_update.\n  - (* malloc *)\n    rewrite <- HCUR in HCUR0. inversion HCUR0. rewrite H3 in HINST.\n    rewrite HINST in HNOMEMCHG. inversion HNOMEMCHG.\n  - (* iicmp_eq, nondet *) apply no_mem_change_after_update.\n  - (* icmp_ule, nondet *) apply no_mem_change_after_update.\nQed.\n\n\nEnd SmallStep.\n\nEnd Ir.", "meta": {"author": "aqjune", "repo": "twinsem", "sha": "c9cc45994bbc7545d32cad0a918492666e6bb69f", "save_path": "github-repos/coq/aqjune-twinsem", "path": "github-repos/coq/aqjune-twinsem/twinsem-c9cc45994bbc7545d32cad0a918492666e6bb69f/SmallStepWf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22013924011468547}}
{"text": "Require Import CSPEC.\nRequire Import MailServerAPI.\nRequire Import MailboxTmpAbsAPI.\nRequire Import DeliverListTidAPI.\nRequire Import MailFSAPI.\n\n\nModule MailFSImpl' <:\n  LayerImplMoversT\n    MailboxTmpAbsState\n    MailFSOp  MailFSAPI\n    DeliverListTidOp DeliverListTidAPI.\n\n  (* START CODE *)\n\n  Definition same_tid (tid : nat) (fn : nat * nat) : bool :=\n    if tid == fst fn then\n      true\n    else\n      false.\n\n  Definition listtid_core :=\n    tid <- Call (MailFSOp.GetTID);\n    l <- Call (MailFSOp.List);\n    Ret (map snd (filter (same_tid tid) l)).\n\n  Definition createwrite_core data :=\n    ok1 <- Call (MailFSOp.CreateTmp);\n    if (ok1 : bool) then Call (MailFSOp.WriteTmp data) else Ret ok1.\n\n  Definition compile_op T (op : DeliverListTidOp.Op T) : proc _ T :=\n    match op with\n    | DeliverListTidOp.LinkMail m => Call (MailFSOp.LinkMail m)\n    | DeliverListTidOp.List => Call (MailFSOp.List)\n    | DeliverListTidOp.ListTid => listtid_core\n    | DeliverListTidOp.Read fn => Call (MailFSOp.Read fn)\n    | DeliverListTidOp.Delete fn => Call (MailFSOp.Delete fn)\n    | DeliverListTidOp.CreateWriteTmp data => createwrite_core data\n    | DeliverListTidOp.UnlinkTmp => Call (MailFSOp.UnlinkTmp)\n    | DeliverListTidOp.Lock => Call (MailFSOp.Lock)\n    | DeliverListTidOp.Unlock => Call (MailFSOp.Unlock)\n    | DeliverListTidOp.Ext extop => Call (MailFSOp.Ext extop)\n    end.\n\n  (* END CODE *)\n\n  Theorem compile_op_no_atomics :\n    forall `(op : _ T),\n      no_atomics (compile_op op).\n  Proof.\n    destruct op; compute; eauto.\n\n    constructor; eauto.\n    destruct x; eauto.\n  Qed.\n\n  Ltac step_inv :=\n    match goal with\n    | H : MailFSAPI.step _ _ _ _ _ _ |- _ =>\n      inversion H; clear H; subst; repeat sigT_eq\n    | H : MailFSAPI.xstep _ _ _ _ _ _ |- _ =>\n      inversion H; clear H; subst; repeat sigT_eq\n    | H : DeliverListTidAPI.step _ _ _ _ _ _ |- _ =>\n      inversion H; clear H; subst; repeat sigT_eq\n    end; intuition idtac.\n\n  Hint Extern 1 (MailFSAPI.step _ _ _ _ _ _) => econstructor.\n  Hint Extern 1 (DeliverListTidAPI.step _ _ _ _ _ _) => econstructor.\n  Hint Constructors MailFSAPI.xstep.\n\n  Lemma gettid_right_mover :\n    right_mover\n      MailFSAPI.step\n      (MailFSOp.GetTID).\n  Proof.\n    unfold right_mover; intros.\n    repeat step_inv; eauto 10.\n\n    eexists; split; econstructor; eauto.\n  Qed.\n\n  Hint Resolve gettid_right_mover.\n\n  Lemma fmap_mapsto_tid_ne :\n    forall (tid0 tid1 : nat) (x y : nat) TV (v v0 : TV) m,\n      tid0 <> tid1 ->\n      FMap.MapsTo (tid0, x) v0 (FMap.add (tid1, y) v m) ->\n      FMap.MapsTo (tid0, x) v0 m.\n  Proof.\n    intros.\n    eapply FMap.mapsto_add_ne; eauto.\n    congruence.\n  Qed.\n\n  Hint Resolve fmap_mapsto_tid_ne.\n\n  Lemma createtmp_right_mover :\n    right_mover\n      MailFSAPI.step\n      (MailFSOp.CreateTmp).\n  Proof.\n    unfold right_mover; intros.\n    repeat step_inv; eauto 10.\n\n    all: unfold MailFSAPI.step.\n    all: try solve [ rewrite FMap.add_add_ne by congruence; eauto 10 ].\n\n    rewrite FMap.add_add_ne by congruence.\n      eexists. split. 2: eauto. eauto.\n\n    rewrite <- FMap.add_remove_ne by congruence.\n      eexists. split. 2: eauto. eauto.\n\n    eexists. split. 2: eauto. eauto.\n  Qed.\n\n  Hint Resolve createtmp_right_mover.\n\n  Theorem ysa_movers_listtid_core:\n    ysa_movers MailFSAPI.step listtid_core.\n  Proof.\n    econstructor; eauto 20.\n  Qed.\n\n  Hint Resolve ysa_movers_listtid_core.\n\n  Theorem ysa_movers_createwrite_core:\n    forall data,\n      ysa_movers MailFSAPI.step (createwrite_core data).\n  Proof.\n    econstructor; eauto 20.\n    destruct r; eauto 20.\n  Qed.\n\n  Hint Resolve ysa_movers_createwrite_core.\n\n  Theorem ysa_movers : forall `(op : _ T),\n    ysa_movers MailFSAPI.step (compile_op op).\n  Proof.\n    destruct op; simpl; eauto 20.\n  Qed.\n\n  Theorem compile_correct :\n    compile_correct compile_op MailFSAPI.step DeliverListTidAPI.step.\n  Proof.\n    unfold compile_correct; intros.\n    destruct op.\n\n    all: try solve [ repeat atomic_exec_inv; repeat step_inv; eauto ].\n\n    - repeat atomic_exec_inv; repeat step_inv; eauto.\n      rewrite FMap.add_add; eauto.\n      rewrite FMap.add_add; eauto.\n\n    - repeat atomic_exec_inv.\n      repeat step_inv; eauto.\n      econstructor; intros.\n\n      eapply in_map_iff.\n      exists (v1, fn); intuition eauto.\n      eapply filter_In; intuition eauto.\n      eapply FMap.is_permutation_in'; eauto.\n      unfold same_tid; simpl.\n      destruct (v1 == v1); congruence.\n  Qed.\n\n  Definition initP_compat : forall s, MailFSAPI.initP s ->\n                                 DeliverListTidAPI.initP s :=\n    ltac:(auto).\n\nEnd MailFSImpl'.\n\nModule MailFSImpl :=\n  LayerImplMovers\n    MailboxTmpAbsState\n    MailFSOp MailFSAPI\n    DeliverListTidOp DeliverListTidAPI\n    MailFSImpl'.\n\nModule MailFSImplH' :=\n  LayerImplMoversHT\n    MailboxTmpAbsState\n    MailFSOp MailFSAPI\n    DeliverListTidOp DeliverListTidAPI\n    MailFSImpl'\n    UserIdx.\n\nModule MailFSImplH :=\n  LayerImplMovers\n    MailboxTmpAbsHState\n    MailFSHOp MailFSHAPI\n    DeliverListTidHOp DeliverListTidHAPI\n    MailFSImplH'.\n", "meta": {"author": "mit-pdos", "repo": "cspec", "sha": "074e11f5c7758fd0f5624f0466dd23244f9112c4", "save_path": "github-repos/coq/mit-pdos-cspec", "path": "github-repos/coq/mit-pdos-cspec/cspec-074e11f5c7758fd0f5624f0466dd23244f9112c4/src/Mail/MailFSImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22013922832143556}}
{"text": "Require Export Coercion_Infrastructure.\nRequire Import Classical.\nSet Undo 100000.\n\nDefinition WF_no_fun_pair r sigma := forall pi pi' t1 t2 s1 s2 a m1 m2, \n  (In (typ_fun t1 t2) pi) -> \n  (In (typ_pair s1 s2) pi') -> \n  ((~ (coercion sigma pi a (typ_fun t1 t2) r (typ_pair s1 s2)) m1) /\\\n   (~ (coercion sigma pi' a (typ_pair s1 s2) r (typ_fun t1 t2)) m2)).\n\nDefinition no_unnecessary_fun_subtyping_path (sigma:Sigma) : Prop := forall t t' t1 t2 C C' theta a, \n  In t theta ->\n  (coercion sigma theta a t RelPrim t' C) ->\n  (coercion sigma theta a t RelPrim (typ_fun t1 t2) C') -> \n  (forall s1 s2, \n    (typ_fun t1 t2) <> (typ_fun s1 s2) -> \n    (not ((exists C1, coerciongen sigma (typ_fun s1 s2) RelPrim t' C1) /\\\n      (exists C2, coerciongen sigma (typ_fun t1 t2) RelSub (typ_fun s1 s2) C2)))).\n\nDefinition no_unnecessary_pair_subtyping_path (sigma:Sigma) : Prop := forall t t' t1 t2 C C' theta a, \n  In t theta ->\n  (coercion sigma theta a t RelPrim t' C) ->\n  (coercion sigma theta a t RelPrim (typ_pair t1 t2) C') -> \n  (forall s1 s2, \n    (typ_pair t1 t2) <> (typ_pair s1 s2) -> \n    (not ((exists C1, coerciongen sigma (typ_pair s1 s2) RelPrim t' C1) /\\\n      (exists C2, coerciongen sigma (typ_pair t1 t2) RelSub (typ_pair s1 s2) C2)))).\n\nDefinition no_multiple_fun_subtyping_paths (sigma:Sigma) : Prop := forall t t1 t2 s1 s2 s1' s2' C1 C2 C3 C4, \n  (coerciongen sigma (typ_fun s1 s2) RelPrim t C1) ->\n  (coerciongen sigma (typ_fun s1' s2') RelPrim t C2) -> \n  (coerciongen sigma (typ_fun t1 t2) RelSub (typ_fun s1 s2) C3) -> \n  (coerciongen sigma (typ_fun t1 t2) RelSub (typ_fun s1' s2') C4) -> \n  (typ_fun s1 s2) = (typ_fun s1' s2').\n\nDefinition no_multiple_pair_subtyping_paths (sigma:Sigma) : Prop := forall t t1 t2 s1 s2 s1' s2' C1 C2 C3 C4, \n  (coerciongen sigma (typ_pair s1 s2) RelPrim t C1) ->\n  (coerciongen sigma (typ_pair s1' s2') RelPrim t C2) -> \n  (coerciongen sigma (typ_pair t1 t2) RelSub (typ_pair s1 s2) C3) -> \n  (coerciongen sigma (typ_pair t1 t2) RelSub (typ_pair s1' s2') C4) -> \n  (typ_pair s1 s2) = (typ_pair s1' s2').\n\nDefinition no_fun_and_pair_subtyping_paths (sigma:Sigma) : Prop := forall t p1 p2 s1 s2 f1 f2 g1 g2 C1 C2 C3 C4, \n  (coerciongen sigma (typ_pair p1 p2) RelPrim t C1) ->\n  (coerciongen sigma (typ_fun f1 f2) RelPrim t C2) -> \n  (coerciongen sigma (typ_pair s1 s2) RelSub (typ_pair p1 p2) C3) -> \n  (coerciongen sigma (typ_fun g1 g2) RelSub (typ_fun f1 f2) C4) -> \n  False.\n\n\n(* Structural properties of coercion *)\nLemma coercion_sub_rel : forall sigma theta t t' C a, \n  coercion sigma theta a t RelPrim t' C -> \n  coercion sigma theta a t RelSub t' C.\nProof.\nintros until 1. rename H into D_1. \ninduction D_1.\nintros.\n  eapply coercion_Id.\nintros.\n   eauto using coercion_PrimTrans.\nintros.\n   eauto using coercion_FunTrans.\nintros.\n   eauto using coercion_PairTrans.\nQed.\n\nLemma altnosub_to_altsub : forall sigma pi d t t' m a, \n  coercion sigma pi a t d t' m -> \n  coercion sigma pi AltSub t d t' m.\nProof.\nintros. rename H into C_nosub.\ninduction C_nosub; eauto || discriminate.\nQed.\n\n(* Cycle detection lemmas *)\nLemma cycles_are_identity : forall sigma theta t t' C a r,\n  In t' theta -> \n  coercion sigma theta a t r t' C ->\n  (t = t' /\\ C = (exp_lam t (exp_bvar 0))).\nintros until 1. intro D.\ninduction D.\nCase \"Id\".\n  auto.\nCase \"PrimTrans\".\ndestruct (IHD (in_cons _ _ _ H)) as [inTheta Ceq].\nsubst t2. contradiction.\nCase \"FunTrans\".\ndestruct (IHD3 (in_cons _ _ _ H)) as [inTheta Ceq].\nsubst t'. contradiction.\nCase \"PairTrans\".\ndestruct (IHD3 (in_cons _ _ _ H)) as [inTheta Ceq].\nsubst t'. contradiction.\nQed.\n\nHint Resolve in_eq in_cons in_inv in_nil insingleton.\n\nLemma coercion_between_distinct_types : \n  forall sigma pi1 pi2 a a' t1 t2 s1 s2 m1 m2 d, \n    (ok sigma) ->\n    (coercion sigma pi1 a t1 d s1 m1) -> \n    (In t1 pi1) -> \n    (coercion sigma pi2 a' t2 d s2 m2) -> \n    (In t2 pi2) -> \n    ((t1 <> t2) \\/ (s1 <> s2)) -> \n    (m1 <> m2).\nProof.\nintros until 1. rename H into ok_sigma. intros Cgen1 In_pi1 Cgen2 In_pi2 neq_disj.\ngeneralize dependent pi2.\ngeneralize dependent t2. \ngeneralize dependent s2.\ngeneralize dependent m2.\ngeneralize dependent a'.\ninduction Cgen1.\nCase \"identity 1\".\n  intros. induction Cgen2; destruct neq_disj; try injection; eauto || discriminate.\nCase \"trans 1\".\n  intros.\n  induction Cgen2; try solve [unfold compose; unfold funcompose; unfold paircompose; unfold not; intro; discriminate].\n  SCase \"trans 2\". \n    destruct neq_disj as [t1_neq_t0 | t3_neq_t5].\n    SSCase \"t1_neq_t0\".\n      assert (f <> f0). eauto.\n      unfold compose. injection; intros; eauto.\n    SSCase \"t3 neq t5\".\n      assert (C<>C0). \n        eapply IHCgen1; try apply (in_eq t4 pi0); eauto. \n      unfold compose. injection; intros; eauto.\nCase \"funcompose\". intros.\n  induction Cgen2; try solve [unfold compose; unfold funcompose; unfold paircompose; unfold not; intro; discriminate].\n    SSCase \"funcompose\".\n    destruct neq_disj as [fneq | t'_neq_t'0].\n       SSSCase \"fneq\".\n         unfold compose; unfold not; intro. injection H1. intros. subst. eauto.\n       SSSCase \"t' <> t'0\".\n         clear IHCgen2_1 IHCgen2_2 IHCgen2_3.\n         assert (C' <> C'0) as C'_neq.\n             eapply IHCgen1_3. eauto. eauto. right. apply t'_neq_t'0. apply Cgen2_3. eauto.\n         unfold compose; unfold not; intro. injection H1. intros. subst. eauto.\nCase \"pair\". intros.\n  induction Cgen2; try solve [unfold compose; unfold funcompose; unfold paircompose; unfold not; intro; discriminate].\n    SSCase \"funcompose\".\n    destruct neq_disj as [fneq | t'_neq_t'0].\n       SSSCase \"fneq\".\n         unfold compose; unfold not; intro. injection H1. intros. subst. eauto.\n       SSSCase \"t' <> t'0\".\n         clear IHCgen2_1 IHCgen2_2 IHCgen2_3.\n         assert (C' <> C'0) as C'_neq.\n             eapply IHCgen1_3. eauto. eauto. right. apply t'_neq_t'0. apply Cgen2_3. eauto.\n         unfold compose; unfold not; intro. injection H1. intros. subst. eauto.\nQed.\n\nLemma identity_coercions_equate_types : forall sigma pi a d t1 t2 t3, \n  coercion sigma pi a t1 d t2 (id t3) -> \n  t1 = t2 /\\ t2 = t3.\nProof.\n  intros.\nremember (id t3) as id_t3.\ninduction H; unfold id in Heqid_t3; try discriminate; injection Heqid_t3; intros; subst. eauto.\nQed.\n\n\nLemma identity_implies_equality : forall sigma pi a t d t' C, \n  (In t pi) -> \n  (coercion sigma pi a t d t' C) -> \n  (C = id t) -> \n  t = t'.\nProof.\nintros. rename H into inPi. rename H0 into Cgen. rename H1 into Ceq. \ninduction Cgen; try solve [unfold id; unfold compose; unfold funcompose; unfold paircompose; simpl; eauto || discriminate].\nQed.\n\nLemma nonidentity_implies_inequality: forall sigma theta t t' C a d, \n  (In t theta) -> \n  (coercion sigma theta a t d t' C) -> \n  C <> (id t) -> \n  t <> t'.\nProof. \nintros until 1. rename H into inTheta. intros D Cneq.\nunfold id in Cneq.\ninduction D.\nCase \"coercion_Id\".\ndestruct Cneq. auto.\nCase \"coercion_PrimTrans\".\nunfold not. intro t1eq.\nsubst t1.\ndestruct (cycles_are_identity _ _ _ _ _ _ _ (in_cons _ _ _ inTheta) D) as [t2Eqt3 CeqId].\nsubst t2. contradiction.\nCase \"funtrans\".\ndestruct (classic (C1 = (id t1'))).\n  SCase \"C1 = id t1'\".\n    assert (t1' = t1). eauto using identity_implies_equality.\n    subst.\n    destruct (classic (C2 = (id t2))).\n      SSCase \"C2 = id t2\".\n        assert (t2=t2'). eauto using identity_implies_equality.\n        subst. eauto. (* contradicts not in *)\n      SSCase \"C2 <> id\".\n        assert (t2 <> t2'). unfold id in *; eauto.\n        unfold not. intro. subst.\n        assert (In (typ_fun t1 t2) (typ_fun t1 t2'::pi)) as in_ext. eauto.\n        destruct (cycles_are_identity _ _ _ _ _ _ _ in_ext D3) as [feq Ceq'].\n        injection feq; intros. eauto.\n   SCase \"C2 <> id\".\n      assert (t1' <> t1). unfold id in *; eauto.\n        unfold not. intro. subst.\n        assert (In (typ_fun t1 t2) (typ_fun t1' t2'::pi)) as in_ext. eauto.\n        destruct (cycles_are_identity _ _ _ _ _ _ _ in_ext D3) as [feq Ceq'].\n        injection feq; intros. eauto.\nCase \"pairtrans\".\ndestruct (classic (C1 = (id t1))).\n  SCase \"C1 = id t1'\".\n    assert (t1 = t1'). eauto using identity_implies_equality.\n    subst.\n    destruct (classic (C2 = (id t2))).\n      SSCase \"C2 = id t2\".\n        assert (t2=t2'). eauto using identity_implies_equality.\n        subst. eauto. (* contradicts not in *)\n      SSCase \"C2 <> id\".\n        assert (t2 <> t2'). unfold id in *; eauto.\n        unfold not. intro. subst.\n        assert (In (typ_pair t1' t2) (typ_pair t1' t2'::pi)) as in_ext. eauto.\n        destruct (cycles_are_identity _ _ _ _ _ _ _ in_ext D3) as [feq Ceq'].\n        injection feq; intros. eauto.\n   SCase \"C2 <> id\".\n      assert (t1 <> t1'). unfold id in *; eauto.\n        unfold not. intro. subst.\n        assert (In (typ_pair t1 t2) (typ_pair t1' t2'::pi)) as in_ext. eauto.\n        destruct (cycles_are_identity _ _ _ _ _ _ _ in_ext D3) as [feq Ceq'].\n        injection feq; intros. eauto.\nQed.\n\nLemma inequality_implies_nonidentity: forall sigma theta t t' C a d, \n  (In t theta) ->\n  (t <> t') -> \n  (coercion sigma theta a t d t' C) -> \n  (forall s, C <> id s).\nProof.\nintros until 1. rename H into inTheta. intros t_neq_t' Cgen.\ninduction Cgen; intros; try eauto; unfold compose; unfold id; discriminate.\nQed.\n\n\n(* Other structural properties *)\n\nLemma relsub_derivations_use_subtyping_atmost_once:  forall sigma t t' C pi a, \n  (WF_to_uniquefunc RelPrim sigma) -> \n  (WF_to_uniquepair RelPrim sigma) -> \n  (WF_no_fun_pair RelPrim sigma) -> \n  (In t pi) -> \n  (coercion sigma pi a t RelSub t' C) -> \n  ((coercion sigma pi a t RelPrim t' C) \\/\n    (exists t1, exists t2, exists s1, exists s2, exists C1, exists C2, exists C3, exists pi', \n      (typ_fun t1 t2) <> (typ_fun s1 s2) /\\\n      (In (typ_fun s1 s2) pi') /\\\n      (C1 = (id t) -> a = AltSub) /\\ (* needed to strengthen IH *)\n      (coercion sigma pi a t RelPrim (typ_fun t1 t2) C1) /\\\n      (coerciongen sigma (typ_fun t1 t2) RelSub (typ_fun s1 s2) C2) /\\\n      (coercion sigma pi' AltNoSub (typ_fun s1 s2) RelPrim t' C3)) \\/\n    (exists t1, exists t2, exists s1, exists s2, exists C1, exists C2, exists C3, exists pi', \n      (typ_pair t1 t2) <> (typ_pair s1 s2) /\\\n      (In (typ_pair s1 s2) pi') /\\\n      (C1 = (id t) -> a = AltSub) /\\ (* needed to strengthen IH *)\n      (coercion sigma pi a t RelPrim (typ_pair t1 t2) C1) /\\\n      (coerciongen sigma (typ_pair t1 t2) RelSub (typ_pair s1 s2) C2) /\\\n      (coercion sigma pi' AltNoSub (typ_pair s1 s2) RelPrim t' C3))).\nProof.\nintros until 1. rename H into WF_ufunc. intros WF_upair WF_no_fp tInPi cgenSub. \ninduction cgenSub.\nCase \"cgenSub is C-Id\". \nleft. unfold coerciongen. eapply coercion_Id.\nCase \"cgenSub is C-PrimTrans\".\nassert (In t2 (t2::pi)) as inT2.  eapply in_eq.\npose proof (IHcgenSub WF_ufunc WF_upair WF_no_fp inT2) as fromIH.  \nclear IHcgenSub.\ndestruct fromIH as [relprim | [relsubFun | relsubPair]].\n  SCase \"relprim\".\n  left. \n  eapply coercion_PrimTrans; eauto.\n  SCase \"relsub fun\".\n  right. left.\n  destruct relsubFun as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [aalt [Ineq [ inTheta [D2_2_1 [D2_2_2 D2_2_3]]]]]]]]]]]]].\n  exists T1. exists T2. exists S1. exists S2.\n  exists (compose t1 B1 (exp_base f)).\n  exists B2.\n  exists B3.\n  exists theta'.\n  split. \n    SSCase \"t1 -> t2 <> s1 -> s2\".\n    eauto.\n  split.\n    SSCase \"s1 -> s2 in Theta'\".\n    eauto.\n  split.\n    SSCase \"id t1 -> AltSub\".\n    intros. unfold compose in H1. discriminate.\n  split.\n    SSCase \"prim\".\n    eapply coercion_PrimTrans; eauto.\n    repeat (split; eauto).\n  SCase \"relsub pair (similar)\".\n  right. right.\n  destruct relsubPair as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [aalt [Ineq [ inTheta [D2_2_1 [D2_2_2 D2_2_3]]]]]]]]]]]]].\n  exists T1. exists T2. exists S1. exists S2.\n  exists (compose t1 B1 (exp_base f)).\n  exists B2.\n  exists B3.\n  exists theta'.\n  split. \n    SSCase \"t1 -> t2 <> s1 -> s2\".\n    eauto.\n  split.\n    SSCase \"s1 -> s2 in Theta'\".\n    eauto.\n  split.\n    SSCase \"id t1 -> AltSub\".\n    intros. unfold compose in H1. discriminate.\n  split.\n    eapply coercion_PrimTrans; eauto.\n    repeat (split; eauto).\nCase \"D2 is C-FunTrans\".\nright. left.\nclear IHcgenSub1 IHcgenSub2.\nexists t1. exists t2.\nexists t1'. exists t2'.\nexists (id (typ_fun t1 t2)).\nexists (compose (typ_fun t1 t2) (id (typ_fun t1' t2')) (funcompose (typ_fun t1 t2) t1' C1 C2)).\nexists C'.\nexists (typ_fun t1' t2'::pi).\nsplit.\n  SCase \"t1 -> t2 <> t1' -> t2'\".\n     Lemma inequality_from_list_membership : forall T (a:T) (b:T) l, \n         (In a l) -> (~In b l) -> a <> b.\n       intros. unfold not. intros. subst b. contradiction.\n     Qed.\n  eapply inequality_from_list_membership; eauto.\n  split.\n  SCase \"In theta\".\n    eapply in_eq.\n  split.\n  SCase \"id t => AltSub\".\n    intro. auto.\n  split.\n  SCase \"Left Streak 1\".\n  unfold id.\n  eapply coercion_Id; eauto.\n  split.\n  SCase \"Middle Fun Trans\".\n  unfold coerciongen.\n  eapply coercion_FunTrans. \n    SSCase \"Premise NotIn singleton\".\n    pose proof (inequality_from_list_membership _ _ _ _ tInPi H) as ineq.\n    unfold not. intros.\n    destruct (in_inv H0) as [teq | innil].\n    unfold not in ineq. \n    apply ineq; apply teq.\n    contradiction.\n    SSCase \"Premise D2_1\".\n    auto.\n    SSCase \"Premise D2_2\".\n    auto.\n    SSCase \"Premise Id tail\".\n    unfold id.\n    eapply coercion_Id.\n  SCase \"Right Streak 1\".\n    destruct (IHcgenSub3 WF_ufunc WF_upair WF_no_fp (in_eq _ _)) as [relprim | [relsubfun | relsubpair]].\n    SSCase \"sfx is prim\".\n      assumption.\n    SSCase \"sfx is relsub fun (violates to_unique_func)\".\n      clear IHcgenSub3.\n      destruct relsubfun as [s1 [s2 [u1 [u2 [D1 [D2 [D3 [pi' [tneq [in_pi [altsub_imp [pfx [sub sfx]]]]]]]]]]]]].\n      clear - altsub_imp WF_ufunc pfx case subcase subsubcase.\n      assert (typ_fun t1' t2' = typ_fun s1 s2) as teq.\n        pose proof (coercion_Id sigma (typ_fun t1' t2'::pi) AltNoSub RelPrim (typ_fun t1' t2')) as tfun_id.\n        unfold WF_to_uniquefunc in WF_ufunc.\n        destruct (WF_ufunc _ _ _ _ _ _ _ _ (typ_fun t1' t2'::pi) (in_eq _ _) tfun_id pfx) as [AA [BB CC]].\n        subst. auto.\n      rewrite <- teq in pfx.\n      destruct (cycles_are_identity _ _ _ _ _ _ _ (in_eq _ _) pfx).\n      subst D1. \n      unfold id in altsub_imp.\n      pose proof (altsub_imp (refl_equal _)). discriminate.\n    SSCase \"sfx is relsub pair (violates no_func_pair)\".\n      clear IHcgenSub3.\n      destruct relsubpair as [s1 [s2 [u1 [u2 [D1 [D2 [D3 [pi' [tneq [in_pi [altsub_imp [pfx [sub sfx]]]]]]]]]]]]].\n      clear - WF_no_fp pfx case subcase subsubcase.\n      unfold WF_no_fun_pair in WF_no_fp.\n      destruct (WF_no_fp  (typ_fun t1' t2'::pi) (typ_pair s1 s2::pi) t1' t2' s1 s2 AltNoSub D1 D1 (in_eq _ _) (in_eq _ _)).\n      contradiction.\n\nCase \"D2 is C-PairTrans (similar)\".\nright. right.\nclear IHcgenSub1 IHcgenSub2.\nexists t1. exists t2.\nexists t1'. exists t2'.\nexists (id (typ_pair t1 t2)).\nexists (compose (typ_pair t1 t2) (id (typ_pair t1' t2')) (paircompose t1 t2 C1 C2)).\nexists C'.\nexists (typ_pair t1' t2'::pi).\nsplit.\n  SCase \"t1 * t2 <> t1' * t2'\".\n  eapply inequality_from_list_membership; eauto.\n  split.\n  SCase \"In theta\".\n    eapply in_eq.\n  split.\n  SCase \"id t => AltSub\".\n    intro. auto.\n  split.\n  SCase \"Left Streak 1\".\n  unfold id.\n  eapply coercion_Id; eauto.\n  split.\n  SCase \"Middle Pair Trans\".\n  unfold coerciongen.\n  eapply coercion_PairTrans. \n    SSCase \"Premise NotIn singleton\".\n    pose proof (inequality_from_list_membership _ _ _ _ tInPi H) as ineq.\n    unfold not. intros.\n    destruct (in_inv H0) as [teq | innil].\n    unfold not in ineq. \n    apply ineq; apply teq.\n    contradiction.\n    SSCase \"Premise D2_1\".\n    auto.\n    SSCase \"Premise D2_2\".\n    auto.\n    SSCase \"Premise Id tail\".\n    unfold id.\n    eapply coercion_Id.\n  SCase \"Right Streak 1\".\n    destruct (IHcgenSub3 WF_ufunc WF_upair WF_no_fp (in_eq _ _)) as [relprim | [relsubfun | relsubpair]].\n    SSCase \"sfx is prim\".\n      assumption.\n    SSCase \"sfx is relsub fun (violates no_pair_func)\".\n      clear IHcgenSub3.\n      destruct relsubfun as [s1 [s2 [u1 [u2 [D1 [D2 [D3 [pi' [tneq [in_pi [altsub_imp [pfx [sub sfx]]]]]]]]]]]]].\n      clear - WF_no_fp pfx case subcase subsubcase.\n      unfold WF_no_fun_pair in WF_no_fp.\n      destruct (WF_no_fp  (typ_fun s1 s2::pi) (typ_pair t1' t2'::pi) s1 s2 t1' t2' AltNoSub D1 D1 (in_eq _ _) (in_eq _ _)).\n      contradiction.\n    SSCase \"sfx is relsub pair (violates to_unique_pair)\".\n      clear IHcgenSub3.\n      destruct relsubpair as [s1 [s2 [u1 [u2 [D1 [D2 [D3 [pi' [tneq [in_pi [altsub_imp [pfx [sub sfx]]]]]]]]]]]]].\n      clear - altsub_imp WF_upair pfx case subcase subsubcase.\n      assert (typ_pair t1' t2' = typ_pair s1 s2) as teq.\n        pose proof (coercion_Id sigma (typ_pair t1' t2'::pi) AltNoSub RelPrim (typ_pair t1' t2')) as tpair_id.\n        unfold WF_to_uniquepair in WF_upair.\n        destruct (WF_upair _ _ _ _ _ _ _ _ (typ_pair t1' t2'::pi) (in_eq _ _) tpair_id pfx) as [AA [BB CC]].\n        subst. auto.\n      rewrite <- teq in pfx.\n      destruct (cycles_are_identity _ _ _ _ _ _ _ (in_eq _ _) pfx).\n      subst D1. \n      unfold id in altsub_imp.\n      pose proof (altsub_imp (refl_equal _)). discriminate.\nQed.\n\n\n\nLemma from_uniquefunc_implies_nomul : forall sigma, \n  WF_from_uniquefunc RelPrim sigma -> \n  no_multiple_fun_subtyping_paths sigma.\nProof.\nintros.\nunfold WF_from_uniquefunc in H.\nunfold no_multiple_fun_subtyping_paths; intros.\nassert (C1 = C2 /\\ s1 = s1' /\\ s2 = s2'). \n  eapply H; eauto.\ndestruct H4 as [A [B C]]; subst; auto.\nQed.\n\n\nLemma relprim_sub_alt_ix : forall sigma pi a a' t t' m, \n  (coercion sigma pi a t RelPrim t' m) -> \n  (coercion sigma pi a' t RelPrim t' m).\nProof.\n  intros.\n  remember RelPrim as rp.\n  induction H.\n  eapply coercion_Id; eauto.\n  eapply coercion_PrimTrans; eauto.\n  discriminate. discriminate.\nQed.\n\n\nLemma wf_uniquepath_2 : forall sigma, \n  (ok sigma) -> \n  (WF_to_uniquefunc RelPrim sigma) -> \n  (WF_to_uniquepair RelPrim sigma) -> \n  (WF_uniquepath RelPrim sigma) -> \n  (WF_no_fun_pair RelPrim sigma) ->\n  (no_unnecessary_fun_subtyping_path sigma) -> \n  (no_unnecessary_pair_subtyping_path sigma) -> \n  (no_multiple_fun_subtyping_paths sigma) ->\n  (no_multiple_pair_subtyping_paths sigma) ->\n  (no_fun_and_pair_subtyping_paths sigma) ->\n  (forall t t' theta C C' a a', In t theta -> \n    coercion sigma theta a t RelSub t' C -> \n    coercion sigma theta a' t RelSub t' C' -> \n    C = C').\nintros sigma okSigma WF_f_1 WF_p_1 WF_up_1 WF_no_fp No_un_f No_un_p No_mul_f No_mul_p No_f_and_p.\nintros until 1. intros D1 D2.\nremember RelSub as rs.\ngeneralize dependent C'.\ngeneralize dependent a'.\ninduction D1.\nCase \"D1 is C-Id\".\nintros a' C' D2.\ninduction D2.\n SCase \"D2 is C-Id\".\n  auto.\n SCase \"D2 is C-PrimTrans\".\n  destruct (cycles_are_identity _ _ _ _ _ _ _ (in_cons _ _ _ H) D2) as [C1 C2].\n   subst t2. contradiction.\n SCase \"D2 is FunTrans\".\n  destruct (cycles_are_identity _ _ _ _ _ _ _ (in_cons _ _ _ H) D2_3) as [Eq1 Eq2].\n  subst t'. contradiction.\n SCase \"D2 is PairTrans\".\n  destruct (cycles_are_identity _ _ _ _ _ _ _ (in_cons _ _ _ H) D2_3) as [Eq1 Eq2].\n  subst t'. contradiction.\nCase \"D1 is C-PrimTrans\".\nintros.\ninduction D2.\n SCase \"Symmetric D2 is C-Id\".\n  destruct (cycles_are_identity _ _ _ _ _ _ _ (in_cons _ _ _ H) D1) as [C1 C2].\n   subst t2. contradiction.\n SCase \"D2 is C-PrimTrans\".\n  subst r.\n  pose proof (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D1) as D1_LR.\n  destruct D1_LR as [D1prim | [D1_fun | D1_pair]].\n  SSCase \"D1 is a level 1 derivation\".\n  assert (coercion sigma pi a t1 RelPrim t3 (compose t1 C (exp_base f))) as D1_L1.\n    eapply coercion_PrimTrans; eauto.\n\n  pose proof (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D2) as D2_LR.\n  destruct D2_LR as [D2prim | [D2_fun | D2_pair]].\n  SSSCase \"D2 is a level 1 derivation\". \n  unfold WF_uniquepath, coerciongen in WF_p_1. \n  assert (coercion sigma pi a t1 RelPrim t3 (compose t1 C0 (exp_base f0))) as D2_L1.\n    eauto using coercion_PrimTrans.\n  eapply WF_up_1; eauto using in_eq.\n  SSSCase \"D2 uses fun subtyping\".\n    destruct D2_fun as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [D2_Ineq [InTheta' [altsub_imp [D2_R_Pfx [D2_R_FunSub D2_R_Sfx]]]]]]]]]]]]].\n    unfold no_unnecessary_fun_subtyping_path, coerciongen in No_un_f.\n    rename f0 into g.\n    assert (coercion sigma pi a t1 RelPrim (typ_fun T1 T2) (compose t1 B1 (exp_base g))) as D2_R_Pfx_g.\n      eapply coercion_PrimTrans; eauto.\n    pose proof (No_un_f _ _ _ _ _ _ _ _ H D1_L1 D2_R_Pfx_g S1 S2 D2_Ineq) as from_No_Un.\n    unfold not in from_No_Un.\n    assert ((exists C1, coercion sigma [typ_fun S1 S2] AltSub  (typ_fun S1 S2) RelPrim t3 C1) /\\\n            (exists C2, coercion sigma [typ_fun T1 T2] AltSub  \n                       (typ_fun T1 T2) RelSub (typ_fun S1 S2) C2)) as forContra.\n    split.\n    SSSSCase \"Assertion Left\". \n      exists B3.\n      eapply coercion_pi_strengthening.\n      eauto using D2_R_Sfx, relprim_sub_alt_ix.\n      apply (insingleton typ (typ_fun S1 S2) theta' InTheta').\n    SSSSCase \"Assertion Right\". \n      exists B2.\n      unfold coerciongen in D2_R_FunSub; eauto.\n    destruct (from_No_Un forContra).\n  SSSCase \"D2 uses pair subtyping\".\n    destruct D2_pair as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [D2_Ineq [InTheta' [altsub_imp [D2_R_Pfx [D2_R_PairSub D2_R_Sfx]]]]]]]]]]]]].\n    unfold no_unnecessary_pair_subtyping_path, coerciongen in No_un_p.\n    rename f0 into g.\n    assert (coercion sigma pi a t1 RelPrim (typ_pair T1 T2) (compose t1 B1 (exp_base g))) as D2_R_Pfx_g.\n      eapply coercion_PrimTrans; eauto.\n    pose proof (No_un_p _ _ _ _ _ _ _ _ H D1_L1 D2_R_Pfx_g S1 S2 D2_Ineq) as from_No_Un.\n    unfold not in from_No_Un.\n    assert ((exists C1, coercion sigma [typ_pair S1 S2] AltSub  (typ_pair S1 S2) RelPrim t3 C1) /\\\n            (exists C2, coercion sigma [typ_pair T1 T2] AltSub  \n                       (typ_pair T1 T2) RelSub (typ_pair S1 S2) C2)) as forContra.\n    split.\n    SSSSCase \"Assertion Left\". \n      exists B3.\n      eapply coercion_pi_strengthening.\n      eauto using D2_R_Sfx, relprim_sub_alt_ix.\n      apply (insingleton typ (typ_pair S1 S2) theta' InTheta').\n    SSSSCase \"Assertion Right\". \n      exists B2.\n      unfold coerciongen in D2_R_PairSub; eauto.\n    destruct (from_No_Un forContra).\n SSCase \"D1 uses fun subtyping\".\n  destruct D1_fun as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [D1_Ineq [InTheta' [altsub_imp [D1_R_Pfx [D1_R_FunSub D1_R_Sfx]]]]]]]]]]]]].\n  assert (coercion sigma pi a t1 RelPrim (typ_fun T1 T2) (compose t1 B1 (exp_base f))) as D1_R_Pfx_f.\n    eapply coercion_PrimTrans; eauto.\n  pose proof (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D2) as D2_LR.\n  destruct D2_LR as [D2_prim | [D2_fun | D2_pair]].\n SSSCase \"D2 is a level 1 derivation (Symmetric)\".\n    unfold no_unnecessary_fun_subtyping_path, coerciongen in No_un_f.\n    rename f0 into g.\n    assert (coercion sigma pi a t1 RelPrim t3 (compose t1 C0 (exp_base g))) as D2_L1.\n      eapply coercion_PrimTrans; eauto.\n    pose proof (No_un_f _ _ _ _ _ _ _ _ H D2_L1 D1_R_Pfx_f S1 S2 D1_Ineq) as from_No_Un.\n    unfold not in from_No_Un.\n    assert ((exists C1, coercion sigma [typ_fun S1 S2] AltSub (typ_fun S1 S2) RelPrim t3 C1) /\\\n           (exists C2, coercion sigma [typ_fun T1 T2] AltSub\n                       (typ_fun T1 T2) RelSub (typ_fun S1 S2) C2)) as forContra.\n      split.\n      SSSSCase \"Assertion Left\". \n        exists B3.\n        eapply coercion_pi_strengthening.\n        eauto using D1_R_Sfx, relprim_sub_alt_ix.\n        apply (insingleton typ (typ_fun S1 S2) theta' InTheta').\n      SSSSCase \"Assertion Right\". \n        exists B2.\n        unfold coerciongen in D1_R_FunSub; eauto.\n        destruct (from_No_Un forContra).\n      SSSCase \"D2 is a fun sub\".\n        destruct D2_fun as [T1' [T2' [S1' [S2' [B1' [B2' [B3' [theta'' [D2_Ineq [InTheta'' [altsub_imp' [D2_R_Pfx [D2_R_FunSub D2_R_Sfx]]]]]]]]]]]]].\n        unfold WF_to_uniquefunc in WF_f_1.\n        rename f0 into g.\n        assert (coercion sigma pi a t1 RelPrim (typ_fun T1' T2') (compose t1 B1' (exp_base g))) as D2_R_Pfx_g.\n          eauto using coercion_PrimTrans.\n        pose proof (WF_f_1  _ _ _ _ _ _ _ _ _ H D1_R_Pfx_f D2_R_Pfx_g) as eq.\n        destruct eq as [e1 [e2 e3]]. subst T1'. subst T2'. unfold compose in e1. injection e1. intros. subst g. subst B1'. \n        assert (t0 = t2) as t0eqt2.\n         assert ((typ_fun t1 t0) = (typ_fun t1 t2)) as inj.\n          eapply binds_id; eauto.\n          injection inj; intros; auto.\n        subst t2.\n        assert (C=C0) as Ceq.\n         eapply IHD1; eauto using in_eq, relprim_sub_alt_ix.\n        subst. auto.\n      SSSCase \"D2 is a pair sub (violates no fun and pair subtyping paths)\".\n        destruct D2_pair as [T1' [T2' [S1' [S2' [B1' [B2' [B3' [theta'' [D2_Ineq [InTheta'' [altsub_imp' [D2_R_Pfx [D2_R_PairSub D2_R_Sfx]]]]]]]]]]]]].\n        unfold no_fun_and_pair_subtyping_paths, coerciongen in No_f_and_p.\n        unfold coerciongen in D2_R_PairSub, D1_R_FunSub.\n        assert False as ff.\n          eapply (No_f_and_p t3 S1' S2' T1' T2' S1 S2 T1 T2 B3' B3 B2' B2).\n            eapply coercion_pi_strengthening. eapply relprim_sub_alt_ix. apply D2_R_Sfx. eauto using insingleton.\n            eapply coercion_pi_strengthening. eapply relprim_sub_alt_ix. apply D1_R_Sfx. eauto using insingleton.\n            apply D2_R_PairSub.\n            apply D1_R_FunSub.\n        destruct ff.\n SSCase \"D1 is pair sub\".\n  destruct D1_pair as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [D1_Ineq [InTheta' [altsub_imp [D1_R_Pfx [D1_R_PairSub D1_R_Sfx]]]]]]]]]]]]].\n  assert (coercion sigma pi a t1 RelPrim (typ_pair T1 T2) (compose t1 B1 (exp_base f))) as D1_R_Pfx_f.\n    eapply coercion_PrimTrans; eauto.\n  pose proof (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D2) as D2_LR.\n  destruct D2_LR as [D2_prim | [D2_fun | D2_pair]].\n  SSSCase \"D2 is a level 1 derivation (Symmetric)\".\n    unfold no_unnecessary_pair_subtyping_path, coerciongen in No_un_p.\n    rename f0 into g.\n    assert (coercion sigma pi a t1 RelPrim t3 (compose t1 C0 (exp_base g))) as D2_L1.\n      eapply coercion_PrimTrans; eauto.\n    pose proof (No_un_p _ _ _ _ _ _ _ _ H D2_L1 D1_R_Pfx_f S1 S2 D1_Ineq) as from_No_Un.\n    unfold not in from_No_Un.\n    assert ((exists C1, coercion sigma [typ_pair S1 S2] AltSub (typ_pair S1 S2) RelPrim t3 C1) /\\\n           (exists C2, coercion sigma [typ_pair T1 T2] AltSub\n                       (typ_pair T1 T2) RelSub (typ_pair S1 S2) C2)) as forContra.\n      split.\n      SSSSCase \"Assertion Left\". \n        exists B3.\n        eapply coercion_pi_strengthening.\n        eauto using D1_R_Sfx, relprim_sub_alt_ix.\n        apply (insingleton typ (typ_pair S1 S2) theta' InTheta').\n      SSSSCase \"Assertion Right\". \n        exists B2.\n        unfold coerciongen in D1_R_PairSub; eauto.\n    destruct (from_No_Un forContra).\n  SSSCase \"D2 is a fun sub (violates no fun and pair subtyping paths)\".\n        destruct D2_fun as [T1' [T2' [S1' [S2' [B1' [B2' [B3' [theta'' [D2_Ineq [InTheta'' [altsub_imp' [D2_R_Pfx [D2_R_FunSub D2_R_Sfx]]]]]]]]]]]]].\n        unfold no_fun_and_pair_subtyping_paths, coerciongen in No_f_and_p.\n        unfold coerciongen in D2_R_FunSub, D1_R_PairSub.\n        assert False as ff.\n          eapply (No_f_and_p t3 S1 S2 T1 T2 S1' S2' T1' T2').\n            eapply coercion_pi_strengthening. eapply relprim_sub_alt_ix. apply D1_R_Sfx. eauto using insingleton.\n            eapply coercion_pi_strengthening. eapply relprim_sub_alt_ix. apply D2_R_Sfx. eauto using insingleton.\n            apply D1_R_PairSub.\n            apply D2_R_FunSub.\n        destruct ff.\n  SSSCase \"D2 is a pair sub(violates no fun and pair subtyping paths)\".\n    destruct D2_pair as [T1' [T2' [S1' [S2' [B1' [B2' [B3' [theta'' [D2_Ineq [InTheta'' [altsub_imp' [D2_R_Pfx [D2_R_PairSub D2_R_Sfx]]]]]]]]]]]]].\n    unfold WF_to_uniquepair in WF_p_1.\n    rename f0 into g.\n    assert (coercion sigma pi a t1 RelPrim (typ_pair T1' T2') (compose t1 B1' (exp_base g))) as D2_R_Pfx_g.\n      eauto using coercion_PrimTrans.\n    pose proof (WF_p_1  _ _ _ _ _ _ _ _ _ H D1_R_Pfx_f D2_R_Pfx_g) as eq.\n    destruct eq as [e1 [e2 e3]]. subst T1'. subst T2'. unfold compose in e1. injection e1. intros. subst g. subst B1'. \n    assert (t0 = t2) as t0eqt2.\n      assert ((typ_fun t1 t0) = (typ_fun t1 t2)) as inj.\n        eapply binds_id; eauto.\n    injection inj; intros; auto.\n    subst t2.\n    assert (C=C0) as Ceq.\n      eapply IHD1; eauto using in_eq, relprim_sub_alt_ix.\n    subst. auto.\n  SCase \"D2 is C-FunTrans\".\n  clear IHD2_1 IHD2_2 IHD2_3 IHD1.\n  rename D1 into D1_2.\n  rename t' into t_final.\n  rename t2 into t_mid_1.\n  rename t1' into t2.\n  rename t0 into t1'.\n  assert (typ_fun t1 t1' <> typ_fun t2 t2') as fneq.\n  unfold not; intro feq. rewrite <- feq in H2. contradiction.\n(*   pose proof (coercion_FunTrans _ _ _ _ _ _ _ _ _ _ H2 D2_1 D2_2 D2_3) as D2. *)\n  assert (coercion sigma (typ_fun t2 t2'::pi) AltNoSub (typ_fun t2 t2') RelPrim t_final C') as alreadyUsedSubtyping.\n    destruct (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D2_3) as [D2_3_prim | [D2_3_fun | D2_3_pair]].\n      SSCase \"Assertion: D2_3 prim\".\n        auto.\n      SSCase \"Assertoin: D2_3 is funsub (impos violates to_uniquefunc)\".\n        destruct D2_3_fun as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_to_fun XX]]]]]]]]]]]].\n        assert (E1 <> (id (typ_fun t2 t2'))) as E1_neq.\n          unfold not; intro. subst E1. pose proof (alt_imp (refl_equal _)). discriminate.\n          assert (typ_fun t2 t2' <> typ_fun T1 T3).\n            eauto using nonidentity_implies_inequality, in_eq.\n          pose proof (coercion_Id sigma (typ_fun t2 t2'::pi) AltNoSub RelPrim (typ_fun t2 t2')) as forcontra.\n          destruct (WF_f_1  _ _ _ _ _ _ _ _ _ (in_eq _ _) cfun_to_fun forcontra).\n          unfold id in E1_neq. contradiction.\n      SSCase \"Assertion: D2_3 is pair sub (violates no_fun_pair)\".\n        destruct D2_3_pair as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_fun_to_pair XX]]]]]]]]]]]].\n        unfold WF_no_fun_pair in WF_no_fp.\n        destruct (WF_no_fp  (typ_fun t2 t2'::pi) (typ_pair T1 T3::pi) t2 t2' T1 T3 AltNoSub E1 E1 (in_eq _ _) (in_eq _ _)).\n        contradiction.\n  destruct (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D1_2) as [D1_prim | [D1_fun | D1_pair]].\n  SSCase \"D1_prim ... D1 is level1\".\n  assert (coercion sigma pi a (typ_fun t1 t1') RelPrim  t_final (compose (typ_fun t1 t1') C (exp_base f))) as D1_Contra.\n    eapply coercion_PrimTrans; eauto.\n  unfold no_unnecessary_fun_subtyping_path, coerciongen in No_un_f.\n    pose proof (No_un_f _ _ _ _ _ _ _ _ H D1_Contra (coercion_Id _ _ _ _ _) t2 t2' fneq) as from_Noun.\n    assert ((exists C1, coercion sigma [typ_fun t2 t2'] AltSub (typ_fun t2 t2') RelPrim t_final C1) /\\\n            (exists C2 : exp,  coercion sigma [typ_fun t1 t1'] AltSub \n                    (typ_fun t1 t1') RelSub (typ_fun t2 t2') C2)) as forContra.\n  split.\n     SSSCase \"Assertion Conj left\".\n     exists C'.\n         eapply coercion_pi_strengthening.\n         eapply relprim_sub_alt_ix.\n         eapply alreadyUsedSubtyping.\n         eauto using insingleton, in_eq.\n     SSSCase \"Assertion Conj right\".\n     exists (compose (typ_fun t1 t1') (id (typ_fun t2 t2')) (funcompose (typ_fun t1 t1') t2 C1 C2)).\n     eapply coercion_FunTrans.\n     SSSSCase \"Premise not in\". \n     unfold not. intros.\n       destruct (in_inv H3) as [fEq | inNil]. \n       rewrite fEq in fneq. eapply fneq. reflexivity.\n       contradiction.\n     SSSSCase \"Premise Farg\".\n       auto.\n     SSSSCase \"Premise Fret\".\n       auto.\n     SSSSCase \"Streak right\".\n       unfold id. eapply coercion_Id. \n  contradiction.\n  SSCase \"D1_2_R ... D1 is fun sub\".\n  destruct D1_fun as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [D1_2_Ineq [InTheta' [alt_imp [D1_2_R_Pfx [D1_2_R_FunSub D1_2_R_Sfx]]]]]]]]]]]]].\n  assert (coercion sigma pi a (typ_fun t1 t1') RelPrim (typ_fun T1 T2) (compose (typ_fun t1 t1') B1 (exp_base f))) as D1_Contra.\n   SSSCase \"Assertion D1_Contra\".\n    eapply coercion_PrimTrans; eauto.\n   assert (typ_fun t1 t1' <> typ_fun T1 T2) as Tfun_ineq.\n    SSSCase \"Assertion Tfun_ineq\".\n     eapply nonidentity_implies_inequality; eauto.\n       unfold compose, id. discriminate.\n   assert (coercion sigma pi a (typ_fun t1 t1') RelPrim (typ_fun t1 t1') (exp_lam (typ_fun t1 t1') (exp_bvar 0))) as D1_Contra_2.\n     eapply coercion_Id;eauto. \n  unfold WF_to_uniquefunc in WF_f_1.\n  assert (typ_fun t1 t1' = typ_fun T1 T2) as Contra.\n    destruct (WF_f_1 _ _ _ _ _ _ _ _ _ H D1_Contra_2 D1_Contra) as [A1 [A2 A3]].\n    subst. auto.\n  contradiction.\n  SSCase \"D1_2_R ... D1 is pair sub\".\n  destruct D1_pair as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [D1_2_Ineq [InTheta' [alt_imp [D1_2_R_fun_to_pair [D1_2_R_PairSub D1_2_R_Sfx]]]]]]]]]]]]].\n  assert (coercion sigma pi a (typ_fun t1 t1') RelPrim (typ_pair T1 T2) (compose (typ_fun t1 t1') B1 (exp_base f))) as fun_to_pair.\n    eauto using coercion_PrimTrans, in_eq.\n  unfold WF_no_fun_pair in WF_no_fp.\n  destruct (WF_no_fp  pi [typ_pair T1 T2] t1 t1' T1 T2 a (compose (typ_fun t1 t1') B1 (exp_base f)) B1 H (in_eq _ _)).\n  contradiction.  \n\n  SCase \"D2 is C-PairTrans\".\n  clear IHD2_1 IHD2_2 IHD2_3 IHD1.\n  rename D1 into D1_2.\n  rename t' into t_final.\n  rename t2 into t_mid_1.\n  rename t1' into t2.\n  rename t0 into t1'.\n  assert (typ_pair t1 t1' <> typ_pair t2 t2') as fneq.\n  unfold not; intro feq. rewrite <- feq in H2. contradiction.\n(*   pose proof (coercion_FunTrans _ _ _ _ _ _ _ _ _ _ H2 D2_1 D2_2 D2_3) as D2. *)\n  assert (coercion sigma (typ_pair t2 t2'::pi) AltNoSub (typ_pair t2 t2') RelPrim t_final C') as alreadyUsedSubtyping.\n    destruct (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D2_3) as [D2_3_prim | [D2_3_fun | D2_3_pair]].\n      SSCase \"Assertion: D2_3 prim\".\n        auto.\n      SSCase \"Assertoin: D2_3 is funsub (impos violates no_pair_fun)\".\n        destruct D2_3_fun as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_pair_to_fun XX]]]]]]]]]]]].\n        unfold WF_no_fun_pair in WF_no_fp.\n        destruct (WF_no_fp  (typ_fun T1 T3::pi) (typ_pair t2 t2'::pi) T1 T3 t2 t2' AltNoSub E1 E1 (in_eq _ _) (in_eq _ _)).\n        contradiction.\n      SSCase \"Assertion: D2_3 is pair sub (violates to_uniquepair)\".\n        destruct D2_3_pair as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cpair_to_pair XX]]]]]]]]]]]].\n        assert (E1 <> (id (typ_pair t2 t2'))) as E1_neq.\n          unfold not; intro. subst E1. pose proof (alt_imp (refl_equal _)). discriminate.\n          assert (typ_pair t2 t2' <> typ_pair T1 T3).\n            eauto using nonidentity_implies_inequality, in_eq.\n          pose proof (coercion_Id sigma (typ_pair t2 t2'::pi) AltNoSub RelPrim (typ_pair t2 t2')) as forcontra.\n          destruct (WF_p_1  _ _ _ _ _ _ _ _ _ (in_eq _ _) cpair_to_pair forcontra).\n          unfold id in E1_neq. contradiction.\n  destruct (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D1_2) as [D1_prim | [D1_fun | D1_pair]].\n  SSCase \"D1_prim ... D1 is level1\".\n  assert (coercion sigma pi a (typ_pair t1 t1') RelPrim  t_final (compose (typ_pair t1 t1') C (exp_base f))) as D1_Contra.\n    eapply coercion_PrimTrans; eauto.\n  unfold no_unnecessary_pair_subtyping_path, coerciongen in No_un_f.\n    pose proof (No_un_p _ _ _ _ _ _ _ _ H D1_Contra (coercion_Id _ _ _ _ _) t2 t2' fneq) as from_Noun.\n    assert ((exists C1, coercion sigma [typ_pair t2 t2'] AltSub (typ_pair t2 t2') RelPrim t_final C1) /\\\n            (exists C2 : exp,  coercion sigma [typ_pair t1 t1'] AltSub \n                    (typ_pair t1 t1') RelSub (typ_pair t2 t2') C2)) as forContra.\n  split.\n     SSSCase \"Assertion Conj left\".\n     exists C'.\n         eapply coercion_pi_strengthening.\n         eapply relprim_sub_alt_ix.\n         eapply alreadyUsedSubtyping.\n         eauto using insingleton, in_eq.\n     SSSCase \"Assertion Conj right\".\n     exists (compose (typ_pair t1 t1') (id (typ_pair t2 t2')) (paircompose t1 t1' C1 C2)).\n     eapply coercion_PairTrans.\n     SSSSCase \"Premise not in\". \n     unfold not. intros.\n       destruct (in_inv H3) as [fEq | inNil]. \n       rewrite fEq in fneq. eapply fneq. reflexivity.\n       contradiction.\n     SSSSCase \"Premise Farg\".\n       auto.\n     SSSSCase \"Premise Fret\".\n       auto.\n     SSSSCase \"Streak right\".\n       unfold id. eapply coercion_Id. \n  contradiction.\n  SSCase \"D1_2_R ... D1 is fun sub\".\n  destruct D1_fun as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [D1_2_Ineq [InTheta' [alt_imp [D1_2_R_pair_to_fun [D1_2_R_PairSub D1_2_R_Sfx]]]]]]]]]]]]].\n  assert (coercion sigma pi a (typ_pair t1 t1') RelPrim (typ_fun T1 T2) (compose (typ_pair t1 t1') B1 (exp_base f))) as pair_to_fun.\n    eauto using coercion_PrimTrans, in_eq.\n  unfold WF_no_fun_pair in WF_no_fp.\n  destruct (WF_no_fp [typ_fun T1 T2] pi T1 T2 t1 t1' a B1 (compose (typ_pair t1 t1') B1 (exp_base f)) (in_eq _ _) H).\n  contradiction.  \n  SSCase \"D1_2_R ... D1 is pair sub\".\n  destruct D1_pair as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [D1_2_Ineq [InTheta' [alt_imp [D1_2_R_Pfx [D1_2_R_PairSub D1_2_R_Sfx]]]]]]]]]]]]].\n  assert (coercion sigma pi a (typ_pair t1 t1') RelPrim (typ_pair T1 T2) (compose (typ_pair t1 t1') B1 (exp_base f))) as D1_Contra.\n   SSSCase \"Assertion D1_Contra\".\n    eapply coercion_PrimTrans; eauto.\n   assert (typ_pair t1 t1' <> typ_pair T1 T2) as Tpair_ineq.\n    SSSCase \"Assertion Tpair_ineq\".\n     eapply nonidentity_implies_inequality; eauto.\n       unfold compose, id. discriminate.\n   assert (coercion sigma pi a (typ_pair t1 t1') RelPrim (typ_pair t1 t1') (exp_lam (typ_pair t1 t1') (exp_bvar 0))) as D1_Contra_2.\n     eapply coercion_Id;eauto. \n  unfold WF_to_uniquepair in WF_p_1.\n  assert (typ_pair t1 t1' = typ_pair T1 T2) as Contra.\n    destruct (WF_p_1 _ _ _ _ _ _ _ _ _ H D1_Contra_2 D1_Contra) as [A1 [A2 A3]].\n    subst. auto.\n  contradiction.\nCase \"D1 is FunTrans\".\nintros.\nremember (typ_fun t1 t2) as tinitial.\nremember RelSub as rs.\ninduction D2.\n SCase \"D2 is C-Id (Symmetric)\". \n  destruct (cycles_are_identity _ _ _ _ _ _ _ (in_cons _ _ _ H) D1_3) as [Eq1 Eq2].\n  rewrite <- Eq1 in H. \n  contradiction.\n SCase \"D2 is PrimTrans (Symmetric)\".\n  rename D2 into D2_2.\n  clear IHD1_1 IHD1_2 IHD1_3 IHD2.\n  rename t4 into t_final.\n  rename t3 into t_mid_2.\n  rename t1' into temp.\n  rename t2 into t1'.\n  rename temp into t2.\n  subst t0.\n  subst r.\n  assert (typ_fun t1 t1' <> typ_fun t2 t2') as fneq.\n  unfold not; intro feq. rewrite <- feq in H0. contradiction.\n  assert (coercion sigma (typ_fun t2 t2'::pi) AltNoSub (typ_fun t2 t2') RelPrim t_final C') as alreadyUsedSubtyping.\n    destruct (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D1_3) as [D2_3_prim | [D2_3_fun | D2_3_pair]].\n      SSCase \"Assertion: D2_3 prim\".\n        auto.\n      SSCase \"Assertoin: D2_3 is funsub (impos violates to_uniquefunc)\".\n        destruct D2_3_fun as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_to_fun XX]]]]]]]]]]]].\n        assert (E1 <> (id (typ_fun t2 t2'))) as E1_neq.\n          unfold not; intro. subst E1. pose proof (alt_imp (refl_equal _)). discriminate.\n          assert (typ_fun t2 t2' <> typ_fun T1 T3).\n            eauto using nonidentity_implies_inequality, in_eq.\n          pose proof (coercion_Id sigma (typ_fun t2 t2'::pi) AltNoSub RelPrim (typ_fun t2 t2')) as forcontra.\n          destruct (WF_f_1  _ _ _ _ _ _ _ _ _ (in_eq _ _) cfun_to_fun forcontra).\n          unfold id in E1_neq. contradiction.\n      SSCase \"Assertion: D2_3 is pair sub (violates no_fun_pair)\".\n        destruct D2_3_pair as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_fun_to_pair XX]]]]]]]]]]]].\n        unfold WF_no_fun_pair in WF_no_fp.\n        destruct (WF_no_fp  (typ_fun t2 t2'::pi) (typ_pair T1 T3::pi) t2 t2' T1 T3 AltNoSub E1 E1 (in_eq _ _) (in_eq _ _)).\n        contradiction.\n  pose proof (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D2_2) as D2_2_LR.\n  destruct D2_2_LR as [D2_2_prim | [D2_2_fun | D2_2_pair]].\n  SSCase \"D2_2_prim ... D2 is level1\".\n  assert (coercion sigma pi a (typ_fun t1 t1') RelPrim t_final (compose (typ_fun t1 t1') C (exp_base f))) as D2_Contra.\n    eapply coercion_PrimTrans; eauto.\n  unfold no_unnecessary_fun_subtyping_path, coerciongen in No_un_f.\n    pose proof (No_un_f _ _ _ _ _ _ _ _ H D2_Contra (coercion_Id _ _ _ _ _) t2 t2' fneq) as from_Noun.\n    assert ((exists C1, coercion sigma [typ_fun t2 t2'] AltSub (typ_fun t2 t2') RelPrim t_final C1) /\\\n            (exists C2 : exp,  coercion sigma [typ_fun t1 t1'] AltSub\n                    (typ_fun t1 t1') RelSub (typ_fun t2 t2') C2)) as forContra.\n  split.\n     SSSCase \"Assertion Conj left\".\n     exists C'.\n        eapply coercion_pi_strengthening.\n        eapply relprim_sub_alt_ix.\n        apply alreadyUsedSubtyping.\n        eauto using insingleton, in_eq.\n     SSSCase \"Assertion Conj right\".\n     exists (compose (typ_fun t1 t1') (id (typ_fun t2 t2')) (funcompose (typ_fun t1 t1') t2 C1 C2)).\n     eapply coercion_FunTrans.\n       SSSSCase \"Premise not in\". \n       unfold not. intros.\n         destruct (in_inv H3) as [fEq | inNil]. \n         rewrite fEq in fneq. eapply fneq. reflexivity.\n         contradiction.\n       SSSSCase \"Premise Farg\".\n         auto.\n       SSSSCase \"Premise Fret\".\n         auto.\n       SSSSCase \"Streak right\".\n         unfold id. eapply coercion_Id. \n  contradiction.\n  SSCase \"D1_2_fun ... D2 is level 2\".\n  destruct D2_2_fun as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [D1_2_Ineq [InTheta' [alt_imp [D2_2_R_Pfx [D2_2_R_FunSub D2_2_R_Sfx]]]]]]]]]]]]].\n  assert (coercion sigma pi a (typ_fun t1 t1') RelPrim (typ_fun T1 T2) (compose (typ_fun t1 t1') B1 (exp_base f))) as D2_Contra.\n   SSSCase \"Assertion D1_Contra\".\n    eapply coercion_PrimTrans; eauto.\n  assert (typ_fun t1 t1' <> typ_fun T1 T2) as Tfun_ineq.\n   SSSCase \"Assertion Tfun_ineq\".\n   eapply nonidentity_implies_inequality; eauto.\n     unfold compose, id. discriminate.\n  assert (coercion sigma pi a (typ_fun t1 t1') RelPrim (typ_fun t1 t1') (exp_lam (typ_fun t1 t1') (exp_bvar 0))) as D2_Contra_2.\n    eapply coercion_Id;eauto.\n  unfold WF_to_uniquefunc in WF_f_1.\n  assert (typ_fun t1 t1' = typ_fun T1 T2) as Contra.\n    destruct (WF_f_1 _ _ _ _ _ _ _ _ _ H D2_Contra_2 D2_Contra) as [A1 [A2 A3]].\n    subst. auto.\n  contradiction.\n\n  SSCase \"D2_2_R ... D2 is pair sub\".\n  destruct D2_2_pair as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [D1_2_Ineq [InTheta' [alt_imp [D1_2_R_fun_to_pair [D1_2_R_PairSub D1_2_R_Sfx]]]]]]]]]]]]].\n  assert (coercion sigma pi a (typ_fun t1 t1') RelPrim (typ_pair T1 T2) (compose (typ_fun t1 t1') B1 (exp_base f))) as fun_to_pair.\n    eauto using coercion_PrimTrans, in_eq.\n  unfold WF_no_fun_pair in WF_no_fp.\n  destruct (WF_no_fp  pi [typ_pair T1 T2] t1 t1' T1 T2 a (compose (typ_fun t1 t1') B1 (exp_base f)) B1 H (in_eq _ _)).\n  contradiction.  \n\n SCase \"D2 is FunTrans\".\n  rename t' into t_final.\n  injection Heqtinitial. intros. subst t0. subst t3. clear Heqtinitial.\n  rename t1' into s1.\n  rename t2' into s1'.\n  rename t1'0 into s2.\n  rename t2'0 into s2'.\n  rename t2 into t1'.\n  rename C' into C_Sfx_1.\n  rename C'0 into C_Sfx_2.\n\n\n  assert (coercion sigma (typ_fun s1 s1'::pi) AltNoSub (typ_fun s1 s1') RelPrim t_final C_Sfx_1) as alreadyUsedSubtyping1.\n    destruct (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D1_3) as [D2_3_prim | [D2_3_fun | D2_3_pair]].\n      SSCase \"Assertion: D2_3 prim\".\n        auto.\n      SSCase \"Assertoin: D2_3 is funsub (impos violates to_uniquefunc)\".\n        destruct D2_3_fun as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_to_fun XX]]]]]]]]]]]].\n        assert (E1 <> (id (typ_fun s1 s1'))) as E1_neq.\n          unfold not; intro. subst E1. pose proof (alt_imp (refl_equal _)). discriminate.\n          assert (typ_fun s1 s1' <> typ_fun T1 T3).\n            eauto using nonidentity_implies_inequality, in_eq.\n          pose proof (coercion_Id sigma (typ_fun s1 s1'::pi) AltNoSub RelPrim (typ_fun s1 s1')) as forcontra.\n          destruct (WF_f_1  _ _ _ _ _ _ _ _ _ (in_eq _ _) cfun_to_fun forcontra).\n          unfold id in E1_neq. contradiction.\n      SSCase \"Assertion: D2_3 is pair sub (violates no_fun_pair)\".\n        destruct D2_3_pair as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_fun_to_pair XX]]]]]]]]]]]].\n        unfold WF_no_fun_pair in WF_no_fp.\n        destruct (WF_no_fp  (typ_fun s1 s1'::pi) (typ_pair T1 T3::pi) s1 s1' T1 T3 AltNoSub E1 E1 (in_eq _ _) (in_eq _ _)).\n        contradiction.\n\n\n  assert (coercion sigma (typ_fun s2 s2'::pi) AltNoSub (typ_fun s2 s2') RelPrim t_final C_Sfx_2) as alreadyUsedSubtyping2.\n    destruct (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D2_3) as [D2_3_prim | [D2_3_fun | D2_3_pair]].\n      SSCase \"Assertion: D2_3 prim\".\n        auto.\n      SSCase \"Assertoin: D2_3 is funsub (impos violates to_uniquefunc)\".\n        destruct D2_3_fun as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_to_fun XX]]]]]]]]]]]].\n        assert (E1 <> (id (typ_fun s2 s2'))) as E1_neq.\n          unfold not; intro. subst E1. pose proof (alt_imp (refl_equal _)). discriminate.\n          assert (typ_fun s2 s2' <> typ_fun T1 T3).\n            eauto using nonidentity_implies_inequality, in_eq.\n          pose proof (coercion_Id sigma (typ_fun s2 s2'::pi) AltNoSub RelPrim (typ_fun s2 s2')) as forcontra.\n          destruct (WF_f_1  _ _ _ _ _ _ _ _ _ (in_eq _ _) cfun_to_fun forcontra).\n          unfold id in E1_neq. contradiction.\n      SSCase \"Assertion: D2_3 is pair sub (violates no_fun_pair)\".\n        destruct D2_3_pair as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_fun_to_pair XX]]]]]]]]]]]].\n        unfold WF_no_fun_pair in WF_no_fp.\n        destruct (WF_no_fp  (typ_fun s2 s2'::pi) (typ_pair T1 T3::pi) s2 s2' T1 T3 AltNoSub E1 E1 (in_eq _ _) (in_eq _ _)).\n        contradiction.\n\n  assert (typ_fun s1 s1' = typ_fun s2 s2') as fun_eq.\n    unfold no_multiple_fun_subtyping_paths, coerciongen in No_mul_f.\n    eapply (No_mul_f t_final).\n      eapply coercion_pi_strengthening. eapply relprim_sub_alt_ix. apply alreadyUsedSubtyping1. eauto using insingleton, in_eq.\n      eapply coercion_pi_strengthening. eapply relprim_sub_alt_ix. apply alreadyUsedSubtyping2. eauto using insingleton, in_eq.\n    eapply coercion_pi_strengthening.\n      eapply coercion_FunTrans.\n        apply H0.\n        apply D1_1. apply D1_2. eapply coercion_Id. eauto using insingleton, in_eq.\n    eapply coercion_pi_strengthening.\n      eapply coercion_FunTrans.\n        apply H1.\n        apply D2_1. apply D2_2. eapply coercion_Id. eauto using insingleton, in_eq.\n  injection fun_eq; intros; subst s2; subst s2'. clear fun_eq.\n  assert (C_Sfx_1 = C_Sfx_2) as sfx_eq.\n    unfold WF_uniquepath in WF_up_1.\n    eapply (WF_up_1 _ _ _ _ _ (typ_fun s1 s1'::pi) (in_eq _ _) alreadyUsedSubtyping1 alreadyUsedSubtyping2).\n  subst C_Sfx_2.\n  clear IHD2_1 IHD2_2 IHD2_3 IHD1_3.\n  assert (C1 = C0) as eq_10.\n    eapply IHD1_1; eauto using in_eq.\n  assert (C2 = C3) as eq_23.\n    eapply IHD1_2; eauto using in_eq.\n  subst C0. subst C3. auto.\n\n SCase \"D2 is PairTrans\".\n subst. discriminate.\n\nCase \"D1 is PairTrans\".\nintros.\nremember (typ_pair t1 t2) as tinitial.\nremember RelSub as rs.\ninduction D2.\n SCase \"D2 is C-Id (Symmetric)\". \n  destruct (cycles_are_identity _ _ _ _ _ _ _ (in_cons _ _ _ H) D1_3) as [Eq1 Eq2].\n  rewrite <- Eq1 in H. \n  contradiction.\n SCase \"D2 is PrimTrans (Symmetric)\".\n  rename D2 into D2_2.\n  clear IHD1_1 IHD1_2 IHD1_3 IHD2.\n  rename t4 into t_final.\n  rename t3 into t_mid_2.\n  rename t1' into temp.\n  rename t2 into t1'.\n  rename temp into t2.\n  subst t0.\n  subst r.\n  assert (typ_pair t1 t1' <> typ_pair t2 t2') as fneq.\n  unfold not; intro feq. rewrite <- feq in H0. contradiction.\n  assert (coercion sigma (typ_pair t2 t2'::pi) AltNoSub (typ_pair t2 t2') RelPrim t_final C') as alreadyUsedSubtyping.\n    destruct (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D1_3) as [D2_3_prim | [D2_3_fun | D2_3_pair]].\n      SSCase \"Assertion: D2_3 prim\".\n        auto.\n      SSCase \"Assertoin: D2_3 is funsub (impos violates no fun pair)\".\n        destruct D2_3_fun as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_fun_to_pair XX]]]]]]]]]]]].\n        unfold WF_no_fun_pair in WF_no_fp.\n        destruct (WF_no_fp  (typ_fun T1 T3::pi) (typ_pair t2 t2'::pi) T1 T3 t2 t2' AltNoSub E1 E1 (in_eq _ _) (in_eq _ _)).\n        contradiction.\n      SSCase \"Assertion: D2_3 is pair sub (violates unique_pair)\".\n        destruct D2_3_pair as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_to_fun XX]]]]]]]]]]]].\n        assert (E1 <> (id (typ_pair t2 t2'))) as E1_neq.\n          unfold not; intro. subst E1. pose proof (alt_imp (refl_equal _)). discriminate.\n          assert (typ_pair t2 t2' <> typ_pair T1 T3).\n            eauto using nonidentity_implies_inequality, in_eq.\n          pose proof (coercion_Id sigma (typ_pair t2 t2'::pi) AltNoSub RelPrim (typ_pair t2 t2')) as forcontra.\n          destruct (WF_p_1  _ _ _ _ _ _ _ _ _ (in_eq _ _) cfun_to_fun forcontra).\n          unfold id in E1_neq. contradiction.\n  pose proof (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D2_2) as D2_2_LR.\n  destruct D2_2_LR as [D2_2_prim | [D2_2_fun | D2_2_pair]].\n  SSCase \"D2_2_prim ... D2 is level1\".\n  assert (coercion sigma pi a (typ_pair t1 t1') RelPrim t_final (compose (typ_pair t1 t1') C (exp_base f))) as D2_Contra.\n    eapply coercion_PrimTrans; eauto.\n  unfold no_unnecessary_pair_subtyping_path, coerciongen in No_un_p.\n    pose proof (No_un_p _ _ _ _ _ _ _ _ H D2_Contra (coercion_Id _ _ _ _ _) t2 t2' fneq) as from_Noun.\n    assert ((exists C1, coercion sigma [typ_pair t2 t2'] AltSub (typ_pair t2 t2') RelPrim t_final C1) /\\\n            (exists C2 : exp,  coercion sigma [typ_pair t1 t1'] AltSub\n                    (typ_pair t1 t1') RelSub (typ_pair t2 t2') C2)) as forContra.\n  split.\n     SSSCase \"Assertion Conj left\".\n     exists C'.         \n         eapply coercion_pi_strengthening. eapply relprim_sub_alt_ix. apply alreadyUsedSubtyping. eauto using insingleton, in_eq.\n     SSSCase \"Assertion Conj right\".\n     exists (compose (typ_pair t1 t1') (id (typ_pair t2 t2')) (paircompose  t1 t1' C1 C2)).\n     eapply coercion_PairTrans.\n       SSSSCase \"Premise not in\". \n       unfold not. intros.\n         destruct (in_inv H3) as [fEq | inNil]. \n         rewrite fEq in fneq. eapply fneq. reflexivity.\n         contradiction.\n       SSSSCase \"Premise Farg\".\n         auto.\n       SSSSCase \"Premise Fret\".\n         auto.\n       SSSSCase \"Streak right\".\n         unfold id. eapply coercion_Id. \n  contradiction.\n  SSCase \"D1_2_fun ... D2 is level 2\".\n  destruct D2_2_fun as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [D1_2_Ineq [InTheta' [alt_imp [D1_2_R_fun_to_pair [D1_2_R_PairSub D1_2_R_Sfx]]]]]]]]]]]]].\n  assert (coercion sigma pi a (typ_pair t1 t1') RelPrim (typ_fun T1 T2) (compose (typ_pair t1 t1') B1 (exp_base f))) as fun_to_pair.\n    eauto using coercion_PrimTrans, in_eq.\n  unfold WF_no_fun_pair in WF_no_fp.\n  destruct (WF_no_fp [typ_fun T1 T2] pi T1 T2 t1 t1'  a B1 (compose (typ_pair t1 t1') B1 (exp_base f)) (in_eq _ _) H).\n  contradiction.  \n  SSCase \"D2_2_R ... D2 is pair sub\".\n  destruct D2_2_pair as [T1 [T2 [S1 [S2 [B1 [B2 [B3 [theta' [D1_2_Ineq [InTheta' [alt_imp [D2_2_R_Pfx [D2_2_R_PairSub D2_2_R_Sfx]]]]]]]]]]]]].\n  assert (coercion sigma pi a (typ_pair t1 t1') RelPrim (typ_pair T1 T2) (compose (typ_pair t1 t1') B1 (exp_base f))) as D2_Contra.\n   SSSCase \"Assertion D1_Contra\".\n    eapply coercion_PrimTrans; eauto.\n  assert (typ_pair t1 t1' <> typ_pair T1 T2) as Tfun_ineq.\n   SSSCase \"Assertion Tfun_ineq\".\n   eapply nonidentity_implies_inequality; eauto.\n     unfold compose, id. discriminate.\n  assert (coercion sigma pi a (typ_pair t1 t1') RelPrim (typ_pair t1 t1') (exp_lam (typ_pair t1 t1') (exp_bvar 0))) as D2_Contra_2.\n    eapply coercion_Id;eauto.\n  unfold WF_to_uniquepair in WF_p_1.\n  assert (typ_pair t1 t1' = typ_pair T1 T2) as Contra.\n    destruct (WF_p_1 _ _ _ _ _ _ _ _ _ H D2_Contra_2 D2_Contra) as [A1 [A2 A3]].\n    subst. auto.\n  contradiction.\n\n SCase \"D2 is FunTrans\".\nsubst. discriminate.\n\nSCase \"D2 is PairTrans\".\n  rename t' into t_final.\n  injection Heqtinitial. intros. subst t0. subst t3. clear Heqtinitial.\n  rename t1' into s1.\n  rename t2' into s1'.\n  rename t1'0 into s2.\n  rename t2'0 into s2'.\n  rename t2 into t1'.\n  rename C' into C_Sfx_1.\n  rename C'0 into C_Sfx_2.\n\n  assert (coercion sigma (typ_pair s1 s1'::pi) AltNoSub (typ_pair s1 s1') RelPrim t_final C_Sfx_1) as alreadyUsedSubtyping1.\n    destruct (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D1_3) as [D2_3_prim | [D2_3_fun | D2_3_pair]].\n      SSCase \"Assertion: D2_3 prim\".\n        auto.\n      SSCase \"Assertoin: D2_3 is funsub (impos violates no_fp)\".\n        destruct D2_3_fun as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_fun_to_pair XX]]]]]]]]]]]].\n        unfold WF_no_fun_pair in WF_no_fp.\n        destruct (WF_no_fp  (typ_fun T1 T3::pi) (typ_pair s1 s1'::pi) T1 T3 s1 s1' AltNoSub E1 E1 (in_eq _ _) (in_eq _ _)).\n        contradiction.\n      SSCase \"Assertion: D2_3 is pair sub (violates to unique pair)\".\n        destruct D2_3_pair as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_to_fun XX]]]]]]]]]]]].\n        assert (E1 <> (id (typ_pair s1 s1'))) as E1_neq.\n          unfold not; intro. subst E1. pose proof (alt_imp (refl_equal _)). discriminate.\n          assert (typ_pair s1 s1' <> typ_pair T1 T3).\n            eauto using nonidentity_implies_inequality, in_eq.\n          pose proof (coercion_Id sigma (typ_pair s1 s1'::pi) AltNoSub RelPrim (typ_pair s1 s1')) as forcontra.\n          destruct (WF_p_1  _ _ _ _ _ _ _ _ _ (in_eq _ _) cfun_to_fun forcontra).\n          unfold id in E1_neq. contradiction.\n  assert (coercion sigma (typ_pair s2 s2'::pi) AltNoSub (typ_pair s2 s2') RelPrim t_final C_Sfx_2) as alreadyUsedSubtyping2.\n    destruct (relsub_derivations_use_subtyping_atmost_once _ _ _ _ _ _ WF_f_1 WF_p_1 WF_no_fp (in_eq _ _) D2_3) as [D2_3_prim | [D2_3_fun | D2_3_pair]].\n      SSCase \"Assertion: D2_3 prim\".\n       auto.\n      SSCase \"Assertoin: D2_3 is funsub (impos violates no_fp)\".\n        destruct D2_3_fun as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_fun_to_pair XX]]]]]]]]]]]].\n        unfold WF_no_fun_pair in WF_no_fp.\n        destruct (WF_no_fp  (typ_fun T1 T3::pi) (typ_pair s2 s2'::pi) T1 T3 s2 s2' AltNoSub E1 E1 (in_eq _ _) (in_eq _ _)).\n        contradiction.\n      SSCase \"Assertion: D2_3 is pair sub (violates to unique pair)\".\n        destruct D2_3_pair as [T1 [T3 [S1 [S2 [E1 [E2 [E3 [theta'' [tneq [notintheta'' [alt_imp [cfun_to_fun XX]]]]]]]]]]]].\n        assert (E1 <> (id (typ_pair s2 s2'))) as E1_neq.\n          unfold not; intro. subst E1. pose proof (alt_imp (refl_equal _)). discriminate.\n          assert (typ_pair s2 s2' <> typ_pair T1 T3).\n            eauto using nonidentity_implies_inequality, in_eq.\n          pose proof (coercion_Id sigma (typ_pair s2 s2'::pi) AltNoSub RelPrim (typ_pair s2 s2')) as forcontra.\n          destruct (WF_p_1  _ _ _ _ _ _ _ _ _ (in_eq _ _) cfun_to_fun forcontra).\n          unfold id in E1_neq. contradiction.\n  assert (typ_pair s1 s1' = typ_pair s2 s2') as fun_eq.\n    unfold no_multiple_pair_subtyping_paths, coerciongen in No_mul_p.\n    eapply (No_mul_p t_final t1 t1' s1 s1' s2 s2' C_Sfx_1 C_Sfx_2).\n     eapply coercion_pi_strengthening.\n        eapply relprim_sub_alt_ix. apply alreadyUsedSubtyping1. eauto using insingleton, in_eq.\n     eapply coercion_pi_strengthening.\n        eapply relprim_sub_alt_ix. apply alreadyUsedSubtyping2. eauto using insingleton, in_eq.\n    eapply coercion_pi_strengthening.\n      eapply coercion_PairTrans.\n        apply H0.\n        apply D1_1. apply D1_2. eapply coercion_Id. eauto using insingleton, in_eq.\n    eapply coercion_pi_strengthening.\n      eapply coercion_PairTrans.\n        apply H1.\n        apply D2_1. apply D2_2. eapply coercion_Id. eauto using insingleton, in_eq.\n  injection fun_eq; intros; subst s2; subst s2'. clear fun_eq.\n  assert (C_Sfx_1 = C_Sfx_2) as sfx_eq.\n    unfold WF_uniquepath in WF_up_1.\n    eapply (WF_up_1 _ _ _ _ _ (typ_pair s1 s1'::pi) (in_eq _ _) alreadyUsedSubtyping1 alreadyUsedSubtyping2).\n  subst C_Sfx_2.\n  clear IHD2_1 IHD2_2 IHD2_3 IHD1_3.\n  assert (C1 = C0) as eq_10.\n    eapply IHD1_1; eauto using in_eq.\n  assert (C2 = C3) as eq_23.\n    eapply IHD1_2; eauto using in_eq.\n  subst C0. subst C3. auto.\nQed.\n   \n", "meta": {"author": "jeapostrophe", "repo": "redex", "sha": "8e5810e452878a4ab5153d19725cfc4cf2b0bf46", "save_path": "github-repos/coq/jeapostrophe-redex", "path": "github-repos/coq/jeapostrophe-redex/redex-8e5810e452878a4ab5153d19725cfc4cf2b0bf46/icfp09-atotcaia/coercions/Coercion_WF_Coerciongen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2201135407408466}}
{"text": "(** * Adversary.v : Well-formedness conditions for adversaries *)\n\nSet Implicit Arguments.\n\nRequire Export Fundamental.\n\n\nModule Make (SemO:SEM_OPT).\n \n Module Fund := Fundamental.Make_Fundamental_Lemma SemO.\n Export Fund.\n\n Module BProc.\n\n  Record bproc : Type := \n   mkP {\n    p_type : T.type;\n    p_name : Proc.proc p_type\n   }.\n\n  Definition t := bproc.\n  Definition eqb p1 p2 := Proc.eqb (p_name p1) (p_name p2).\n\n  Lemma eqb_spec : forall p1 p2, if eqb p1 p2 then p1 = p2 else p1 <> p2.   \n  Proof.\n   intros (t1,f1) (t2,f2); generalize (Proc.eqb_spec_dep f1 f2); unfold eqb.\n   simpl; destruct (Proc.eqb f1 f2); intros.\n   inversion H; trivial.\n   intros Heq; apply H; inversion Heq; trivial.\n  Qed.\n \n End BProc.    \n \n Module ProcD  := MkEqBool_Leibniz BProc.\n Module PrSet  := MkListSet ProcD.\n Module PrSetP := MkSet_Theory PrSet.\n\n Section WF_ADV.\n\n  Variables PrOrcl PrPriv: PrSet.t.\n\n  Variables Gadv Gcomm : Vset.t.\n\n  Hypothesis Ga_global : forall x, Vset.mem x Gadv -> Var.is_global x.\n  Hypothesis Gc_global : forall x, Vset.mem x Gcomm -> Var.is_global x.\n\n  Definition WFWrite x :=\n   Var.is_global x -> Vset.mem x Gadv.\n\n  Definition WFRead t (e:E.expr t) I :=\n   forall x, Vset.mem x (fv_expr e) -> \n    Vset.mem x I \\/ Vset.mem x Gadv \\/ Vset.mem x Gcomm.\n \n  Definition WFReadD t (d:DE.support t) I :=\n   forall x, Vset.mem x (fv_distr d) -> \n     Vset.mem x I \\/ Vset.mem x Gadv \\/ Vset.mem x Gcomm.\n\n  Section DEF.\n\n   Variable E : env.\n\n   Definition add_read x I := if Var.is_global x then I else Vset.add x I.\n\n   Inductive WFAdv_i : Vset.t -> I.t -> Vset.t -> Prop :=\n   | GA_assign : forall I x e,\n     WFWrite x ->\n     WFRead e I ->\n     WFAdv_i I (x <- e) (add_read x I)\n   | GA_random : forall I x d,\n     WFWrite x ->\n     WFReadD d I ->\n     WFAdv_i I (I.Instr (I.Random x d)) (add_read x I)\n   | GA_cond : forall I e c1 c2 O1 O2,\n     WFRead e I ->\n     WFAdv_c I c1 O1 ->\n     WFAdv_c I c2 O2 ->\n     WFAdv_i I (If e then c1 else c2) (Vset.inter O1 O2)\n   | GA_while : forall I e c O,\n     WFRead e I ->\n     WFAdv_c I c O ->\n     WFAdv_i I (while e do c) I\n   | GA_call_orcl : forall t (x:Var.var t) (f:Proc.proc t) (args:E.args (Proc.targs f)) I,\n     PrSet.mem (BProc.mkP f) PrOrcl ->\n     (forall t (e:E.expr t), DIn (P:=E.expr) t e args -> WFRead e I) ->\n     WFWrite x ->\n     WFAdv_i I (x <c- f with args) (add_read x I)\n   | GA_call_adv : forall t (x:Var.var t) (f:Proc.proc t) (args:E.args (Proc.targs f)) I O,\n     ~PrSet.mem (BProc.mkP f) PrOrcl -> \n     ~PrSet.mem (BProc.mkP f) PrPriv ->\n     WFAdv_c (Vset_of_var_decl (proc_params E f)) (proc_body E f) O ->\n     WFRead (proc_res E f) O ->\n     (forall t (e:E.expr t), DIn (P:=E.expr) t e args -> WFRead e I) ->\n     WFWrite x ->\n     WFAdv_i I (x <c- f with args) (add_read x I)\n     \n   with WFAdv_c : Vset.t -> cmd -> Vset.t -> Prop :=\n   | GA_nil : forall I, WFAdv_c I nil I\n   | GA_cons : forall I IO O i c,\n     WFAdv_i I i IO ->\n     WFAdv_c IO c O ->\n     WFAdv_c I (i::c) O.\n\n   Scheme WFAdv_c_prop := Induction for WFAdv_c Sort Prop\n    with WFAdv_i_prop := Induction for WFAdv_i Sort Prop.\n\n   Definition WFAdv t (f:Proc.proc t) :=\n    exists O, \n     WFAdv_c  (Vset_of_var_decl (proc_params E f)) (proc_body E f) O /\\\n     WFRead (proc_res E f) O.\n\n   Lemma add_read_subset : forall x I, I [<=] add_read x I.\n   Proof. \n    unfold add_read; intros x I; destruct (Var.is_global x); auto with set. \n   Qed.\n\n   Lemma add_read_local : forall x I, \n    (forall y, Vset.mem y I -> Var.is_local y) ->\n    forall y, Vset.mem y (add_read x I) -> Var.is_local y.\n   Proof.\n    unfold add_read; intros x I H y; case_eq (Var.is_global x); auto.\n    rewrite VsetP.add_spec; intros Heq [H1 | H1]; auto.\n    rewrite <- (H1:x=y); unfold Var.is_local; rewrite Heq; trivial.\n   Qed.\n\n   Lemma WFAdv_i_subset : forall I i O, WFAdv_i I i O -> I [<=] O.\n   Proof.\n    induction 1 using WFAdv_i_prop with \n     (P:=fun I (c:cmd) O (H:WFAdv_c I c O) => I [<=] O);\n    auto using add_read_subset with set.\n    apply VsetP.subset_trans with IO; trivial.\n    rewrite <- (VsetP.inter_idem I); auto with set.\n    apply VsetP.subset_inter_ctxt; trivial.\n   Qed.\n   \n   Lemma WFAdv_c_subset :  forall I c O, WFAdv_c I c O -> I [<=] O.\n   Proof.\n    induction 1; auto with set.\n    apply VsetP.subset_trans with IO; trivial.\n    apply WFAdv_i_subset with (1:= H).\n   Qed.\n\n   Lemma WFAdv_i_local : forall I i O, WFAdv_i I i O ->\n    (forall x, Vset.mem x I -> Var.is_local x) -> \n    forall x, Vset.mem x O -> Var.is_local x.\n   Proof.\n    induction 1 using WFAdv_i_prop with \n     (P:=fun I (c:cmd) O (H:WFAdv_c I c O) =>\n      (forall x, Vset.mem x I -> Var.is_local x) -> \n      forall x, Vset.mem x O -> Var.is_local x);\n     eauto using add_read_local; intros.\n    rewrite VsetP.inter_spec in H0; destruct H0; eauto.\n   Qed.\n\n   Lemma WFAdv_c_local : forall I c O, WFAdv_c I c O ->\n    (forall x, Vset.mem x I -> Var.is_local x) -> \n    forall x, Vset.mem x O -> Var.is_local x.\n   Proof.\n    induction 1; auto; intros.\n    apply IHWFAdv_c; trivial.\n    intros; apply WFAdv_i_local with (1:= H); trivial.\n   Qed.\n  \n  End DEF.\n\n \n  Section TRANS.\n\n   Variable E1 E2 : env.\n  \n   Definition Eq_orcl_params := forall t (o:Proc.proc t), \n    PrSet.mem (BProc.mkP o) PrOrcl -> proc_params E1 o = proc_params E2 o.\n\n   Definition Eq_adv_decl :=\n    forall t (f:Proc.proc t),\n     ~ PrSet.mem (BProc.mkP f) PrOrcl -> \n     ~ PrSet.mem (BProc.mkP f) PrPriv ->\n     proc_params E1 f = proc_params E2 f /\\\n     proc_body E1 f = proc_body E2 f /\\\n     proc_res E1 f = proc_res E2 f.\n\n   Lemma WFAdv_c_trans : \n    Eq_orcl_params -> \n    Eq_adv_decl ->\n    forall I c O,\n     WFAdv_c E1 I c O -> WFAdv_c E2 I c O.\n   Proof.\n    intros Ho Ha; induction 1 using WFAdv_c_prop with\n     (P0:=fun I i O (_:WFAdv_i E1 I i O) => WFAdv_i E2 I i O);\n     try (econstructor; eauto; fail).\n    destruct (Ha _ _ n n0) as (H1,(H2,H3)). \n    apply GA_call_adv with O; auto. \n    rewrite <- H1, <-H2; auto. \n    rewrite <- H3; auto.\n   Qed.\n\n   Lemma WFAdv_trans : \n    Eq_orcl_params -> \n    Eq_adv_decl ->\n    forall t (adv:Proc.proc t),\n     ~PrSet.mem (BProc.mkP adv) PrOrcl -> \n     ~PrSet.mem (BProc.mkP adv) PrPriv ->\n     WFAdv E1 adv -> WFAdv E2 adv.\n   Proof.\n    intros Ho Ha t adv Hm1 Hm2  (O, (H1, H2));\n     destruct (Ha _ _ Hm1 Hm2) as (H3, (H4,H5));\n      exists O; split; trivial. \n    rewrite <- H3,<-H4; apply WFAdv_c_trans; trivial.\n    rewrite <- H5; trivial.\n   Qed.\n\n  End TRANS.\n\n\n  Section REFL_INFO.\n\n   Variable E : env.\n   Variable pi : eq_refl_info E.\n\n   Definition mod_adv :=\n    PrSet.fold (fun f res =>\n     match res, pi (BProc.p_name f) with\n     | Some res, Some pif => Some (Vset.union (pi_mod pif) res)\n     | _, _ => None\n     end) PrOrcl (Some Gadv).\n   \n   Lemma mod_adv_global : forall X,\n    mod_adv = Some X ->\n    forall x, Vset.mem x X -> Var.is_global x.\n   Proof. \n    unfold mod_adv; rewrite PrSet.fold_spec.\n    generalize (PrSet.elements PrOrcl) Gadv Ga_global.\n    induction l; simpl; intros.\n    inversion H; clear H; subst; auto.\n    destruct (pi (BProc.p_name a)) as [pif | _ ].\n    apply IHl with (2:= H); trivial.\n    intros x0; rewrite VsetP.union_spec; intros [H1 | H1]; \n     auto using (mod_global pif).      \n    generalize l H.\n    induction l0; simpl; intros; auto; try discriminate.\n   Qed.\n\n   Lemma mod_adv_incl : forall X,\n    mod_adv = Some X ->\n    Gadv [<=] X /\\ \n    forall f, PrSet.mem f PrOrcl -> \n     exists pif, pi (BProc.p_name f) = Some pif /\\ (pi_mod pif) [<=] X.\n   Proof. \n    unfold mod_adv; rewrite PrSet.fold_spec. \n    intros X; assert (forall l R, \n     fold_left\n     (fun (x : option Vset.t) (a : ProcD.t) =>\n      match x with\n      | Some res => \n        match pi (BProc.p_name a) with\n        | Some pif => Some (Vset.union (pi_mod pif) res)\n        | None => None \n        end\n      | None => None\n      end) l (Some R) = Some X ->\n     R [<=] X /\\\n     (forall f, InA (@eq _) f l -> \n      exists pif, pi  (BProc.p_name f) = Some pif /\\ (pi_mod pif) [<=] X)).\n    induction l; simpl; intros.\n    injection H; clear H; intros; subst; split; intros; auto with set.\n    inversion H.\n    case_eq (pi (BProc.p_name a)); \n     [intros pia Heq | intros Heq]; rewrite Heq in H.\n    destruct (IHl _ H); split; auto.\n    apply VsetP.subset_trans with (2:= H0); auto with set.\n    intros f Hin; inversion Hin; clear Hin; intros; subst.\n    exists pia; split; auto.\n    apply VsetP.subset_trans with (2:= H0); auto with set.\n    eapply H1; eauto.\n    elimtype False. \n    generalize l H; clear IHl H l Heq.\n    induction l; simpl; intros; try discriminate; auto.\n    intros H1; destruct (H _ _ H1); split; auto.\n    intros; apply H2; auto.\n    apply PrSet.elements_correct; auto.\n   Qed.\n   \n   Lemma mod_adv_write : forall x X,  \n    mod_adv = Some X ->\n    WFWrite x ->\n    Var.is_global x ->\n    Vset.singleton x [<=] X.\n   Proof.\n    intros x X Heq; destruct (mod_adv_incl Heq).\n    unfold WFWrite,add_read; intros.\n    apply VsetP.subset_trans with Gadv; trivial.\n    apply Vset.subset_complete; intros.\n    apply Vset.singleton_complete in H3; rewrite <- (H3:x = x0); auto.\n   Qed.\n \n   Lemma union_union_same : forall X Li Lc,\n    Vset.union (Vset.union X Li) (Vset.union X Lc) [=]\n    Vset.union X (Vset.union Li Lc).\n   Proof.\n    intros; rewrite VsetP.union_assoc. \n    rewrite (VsetP.union_sym X Lc), <- (VsetP.union_assoc Li).\n    rewrite (VsetP.union_sym (Vset.union Li Lc)), <- VsetP.union_assoc.\n    rewrite VsetP.union_idem; auto with set.\n   Qed.\n\n   Lemma get_global_union : forall X Lf,\n    mod_adv = Some X ->\n    (forall x : VarP.Edec.t, Vset.mem x Lf -> Var.is_local x) ->\n    get_globals (Vset.union Lf X) [=] X.\n   Proof.\n    intros X Lf Heq HL.\n    assert (W:= mod_adv_global Heq).\n    rewrite VsetP.eq_spec; split; apply Vset.subset_complete; intros.\n    assert (W1:=Vset.subset_correct (get_globals_subset (Vset.union Lf X)) _ H).\n    rewrite VsetP.union_spec in W1; destruct W1; trivial.\n    absurd (Var.is_global x).\n    assert (W1:= HL _ H0).\n    unfold Var.is_local in W1; intro H1; rewrite H1 in W1; discriminate.\n    apply (get_globals_spec _ _ H).\n    apply get_globals_complete; auto with set.\n   Qed.\n\n   Lemma mod_adv_correct : forall X, \n    mod_adv = Some X ->\n    forall I c O, WFAdv_c E I c O -> \n     exists L, (forall x, Vset.mem x L -> Var.is_local x) /\\ \n      Modify E (Vset.union L X) c. \n   Proof.\n    intros X Heq; destruct (mod_adv_incl Heq).\n    induction 1 using WFAdv_c_prop with\n     (P0:=fun I i O (_:WFAdv_i E I i O) =>\n      exists L, (forall x, Vset.mem x L -> Var.is_local x) /\\ \n       Modify E (Vset.union L X) [i]).\n    exists Vset.empty; split.\n    intros x W; elim (Vset.empty_spec W).\n    eapply Modify_weaken;[apply Modify_nil|]; auto with set.\n    destruct IHWFAdv_c as (Li, (H2,H3)); destruct IHWFAdv_c0 as [Lc [H4 H5] ].\n    exists (Vset.union Lc Li); split; intros.\n    rewrite VsetP.union_spec in H6; destruct H6; auto.\n    rewrite VsetP.union_sym, <- union_union_same, VsetP.union_sym.\n    repeat rewrite (VsetP.union_sym X).\n    apply Modify_cons with (1:= H3) (2:= H5).\n    case_eq (Var.is_global x); intros; \n     [exists Vset.empty | exists (Vset.singleton x)]; split; intros.\n    elim (Vset.empty_spec H2).\n    eapply Modify_weaken;[apply Modify_assign|].\n    apply VsetP.subset_trans with X; auto with set.\n    destruct x; simpl Var.btype ; auto using mod_adv_write with set.\n    apply Vset.singleton_complete in H2; \n     rewrite <- (H2: x = x0); unfold Var.is_local; rewrite H1; trivial.\n    eapply Modify_weaken;\n     [apply Modify_assign|]; destruct x; simpl Var.btype; auto with set.\n    case_eq (Var.is_global x); intros;\n     [exists Vset.empty | exists (Vset.singleton x)]; split; intros.\n    elim (Vset.empty_spec H2).\n    eapply Modify_weaken;[apply Modify_random|].\n    destruct x; simpl Var.btype.\n    apply VsetP.subset_trans with X; auto using mod_adv_write with set.\n    apply Vset.singleton_complete in H2; \n     rewrite <- (H2: x = x0); unfold Var.is_local; rewrite H1; trivial.\n    eapply Modify_weaken;\n     [apply Modify_random | ]; destruct x; simpl Var.btype; auto with set.\n    destruct IHWFAdv_c1 as (L1, (H2,H3)); destruct IHWFAdv_c2 as [L2 [H4 H5] ].\n    exists (Vset.union L1 L2); split; intros.\n    rewrite VsetP.union_spec in H1; destruct H1; auto.\n    rewrite VsetP.union_sym, <- union_union_same.\n    repeat rewrite (VsetP.union_sym X).\n    apply Modify_cond with (1:= H3) (2:= H5).\n    destruct IHWFAdv_c as (L, (H2,H3)).\n    exists L; split; auto.\n    apply Modify_while; trivial.\n\n    (* Call Orcl *)\n    destruct (H0 _ i) as (pif, (Hpif, Hsub)).\n    case_eq (Var.is_global x); intros;\n     [exists Vset.empty | exists (Vset.singleton x)]; split; intros.\n    elim (Vset.empty_spec H2).\n    eapply Modify_weaken;[apply (mod_spec_call pif)|].\n    apply VsetP.subset_trans with (Vset.add x X).\n    apply VsetP.subset_add_ctxt; trivial.\n    rewrite VsetP.add_idem; auto with set.\n    apply Vset.subset_correct with (1:=mod_adv_write Heq w0 H1); auto with set.\n    apply Vset.singleton_complete in H2; \n     rewrite <- (H2: Var.mkV x = x0); unfold Var.is_local; rewrite H1; trivial.\n    rewrite VsetP.union_sym.\n    eapply Modify_weaken;[apply (mod_spec_call pif)|].\n    rewrite VsetP.union_sym.\n    apply VsetP.subset_trans with (Vset.add x X); \n     auto using VsetP.subset_add_ctxt with set.\n\n    (* Call Adv *)\n    destruct IHWFAdv_c as (Lf,(H2,H3)).\n    case_eq (Var.is_global x); intros;\n     [exists Vset.empty | exists (Vset.singleton x)]; split; intros.\n    elim (Vset.empty_spec H5).\n    eapply Modify_weaken;[apply Modify_call with (1:= H3)|].\n    rewrite get_global_union; trivial.\n    apply VsetP.subset_trans with (Vset.add x X).\n    apply VsetP.subset_add_ctxt; auto with set.\n    rewrite VsetP.add_idem; auto with set.\n    apply Vset.subset_correct with (1:=mod_adv_write Heq w1 H4); auto with set.\n    apply Vset.singleton_complete in H5; \n     rewrite <- (H5: Var.mkV x = x0); unfold Var.is_local; rewrite H4; trivial.\n    rewrite VsetP.union_sym.\n    eapply Modify_weaken;[apply Modify_call with (1:= H3)|].\n    rewrite get_global_union; trivial.\n    rewrite VsetP.union_sym.\n    apply VsetP.subset_trans with (Vset.add x X); \n     auto using VsetP.subset_add_ctxt with set.\n   Qed.\n   \n   Lemma mod_adv_spec : forall X, \n    mod_adv = Some X ->\n    forall t (f:Proc.proc t), WFAdv E f -> \n     forall (x:Var.var t) args, Modify E (Vset.add x X) [x <c- f with args].\n   Proof.\n    intros X Heq t f [O [H H0] ] x args.\n    destruct (mod_adv_correct Heq H) as [L [H1 H2] ].\n    eapply Modify_weaken;[apply Modify_call with (1:= H2)|].\n    rewrite get_global_union; auto with set.\n   Qed.\n   \n   Definition input_Adv :=\n    PrSet.fold (fun f res =>\n     match res, pi (BProc.p_name f) with\n     | Some res, Some pif => Some (Vset.union (pi_input pif) res)\n     | _, _ => None\n     end) PrOrcl (Some (Vset.union Gadv Gcomm)).\n   \n   Section EQ_OBS.\n    \n    Variable IA : Vset.t.\n  \n    Hypothesis IA_def : input_Adv = Some IA.\n\n    Lemma input_Adv_global : forall x, Vset.mem x IA -> Var.is_global x.\n    Proof.\n     generalize IA_def; unfold input_Adv.\n     rewrite PrSet.fold_spec.\n     assert (forall x, Vset.mem x (Vset.union Gadv Gcomm) -> Var.is_global x).\n     intros x; rewrite VsetP.union_spec; intros [H | H]; auto.\n     generalize (PrSet.elements PrOrcl) (Vset.union Gadv Gcomm) H; clear H.\n     induction l; simpl; intros.\n     apply H; inversion IA_def0; trivial.\n     destruct (pi (BProc.p_name a)).\n     apply IHl with (2:= IA_def0); trivial.\n     intros x0; rewrite VsetP.union_spec; intros [H1 | H1]; \n      auto using (input_global p).\n     generalize l IA_def0; clear IHl IA_def0 l.\n     induction l; simpl; intros; try discriminate; auto.\n    Qed.\n\n    Lemma input_Adv_subset : \n     Gcomm [<=] IA /\\\n     Gadv [<=] IA /\\\n     forall t (f:Proc.proc t) pif, \n      PrSet.mem (BProc.mkP f) PrOrcl -> \n      pi f = Some pif ->\n      (pi_input pif) [<=] IA.\n    Proof.\n     unfold input_Adv in IA_def.\n     rewrite PrSet.fold_spec in IA_def. \n     assert (forall l X,\n      fold_left\n      (fun x a =>\n       match x with\n       | Some res =>\n         match pi (BProc.p_name a) with\n         | Some pif => Some (Vset.union (pi_input pif) res)\n         | None => None (A:=Vset.t)\n         end\n       | None => None (A:=Vset.t)\n       end) l (Some X) = Some IA ->\n      X [<=] IA /\\ \n      forall (f : ProcD.t) (pif : proc_eq_refl_info E (BProc.p_name f)),\n       InA (@eq _) f l -> \n       pi (BProc.p_name f) = Some pif -> pi_input pif [<=] IA).\n     induction l; simpl; intros; trivial.\n     inversion H; split; intros; auto with set.\n     inversion H0.\n     generalize H; clear H; case_eq (pi (BProc.p_name a)); intros.\n     destruct (IHl _ H0); split.\n     apply VsetP.subset_trans with (2 := H1); auto with set.\n     intros f pif Hin; inversion Hin; intros; auto; subst.\n     rewrite H in H6; inversion H6; subst.\n     apply VsetP.subset_trans with (2 := H1); auto with set.\n     elimtype False; generalize l H0; clear IHl H0 l.\n     induction l; simpl; intros; try discriminate; auto.\n     destruct (H _ _ IA_def).\n     split.\n     apply VsetP.subset_trans with (2:= H0); auto with set.\n     split.\n     apply VsetP.subset_trans with (2:= H0); auto with set.\n     intros; apply H1 with (f := BProc.mkP f); trivial.\n     apply PrSet.elements_correct; trivial.\n    Qed.\n\n    Hypothesis pi_def : forall o, \n     PrSet.mem o PrOrcl -> exists pio, pi (BProc.p_name o) = Some pio.\n    \n    Hypothesis input_orcl_pre : forall o pio, \n     PrSet.mem o PrOrcl -> pi (BProc.p_name o) = Some pio ->\n     forall x, Vset.mem x IA -> \n      Vset.mem x (pi_mod pio) -> Vset.mem x (pi_output pio).\n    \n    Lemma equiv_WFRead : forall t (e:E.expr t) I k (m1 m2:Mem.t k), \n     WFRead e I -> \n     Gcomm[<=]IA ->\n     Gadv[<=]IA -> \n     m1 =={ Vset.union IA I}m2 ->\n     E.eval_expr e m1 = E.eval_expr e m2.\n    Proof.\n     intros; apply EqObs_e_fv_expr.\n     apply req_mem_weaken with (2:= H2).\n     unfold WFRead in H; apply Vset.subset_complete; intros.\n     apply Vset.subset_correct with (Vset.union (Vset.union Gadv Gcomm) I).\n     rewrite <- (VsetP.union_idem IA); \n      repeat apply VsetP.subset_union_ctxt; auto with set.\n     repeat rewrite VsetP.union_spec; destruct (H _ H3); tauto.\n    Qed.\n\n    Lemma equiv_WFWrite : forall k t (x:Var.var t) v I (m1 m2:Mem.t k), \n     m1 =={ Vset.union IA I} m2 ->\n     m1 {!x <-- v!} =={ Vset.union IA (add_read x I)} m2 {!x <-- v!}.\n    Proof.\n     intros k t x; unfold add_read.\n     case_eq (Var.is_global x); intros; red; intros.\n     destruct (Var.eq_dec x x0).\n     inversion e; simpl; repeat rewrite Mem.get_upd_same; trivial.\n     repeat rewrite Mem.get_upd_diff; trivial; auto.\n     destruct (Var.eq_dec x x0).\n     inversion e; simpl; repeat rewrite Mem.get_upd_same; trivial.\n     repeat rewrite Mem.get_upd_diff; trivial; auto.\n     rewrite VsetP.union_spec, VsetP.add_spec in H1; destruct H1; auto with set.\n     destruct H1; auto with set.\n     elim (n H1).\n    Qed.\n\n    Lemma get_arg_some : forall t (x:Var.var t) e tv (lv:var_decl tv) \n     te (le:E.args te), get_arg x lv le = Some e -> DIn t e le.\n    Proof.\n     induction lv; simpl; intros; try discriminate.\n     destruct le; try discriminate.\n     case_eq (get_arg x lv le); intros.\n     rewrite H0 in H; inversion H; simpl; subst; auto.\n     rewrite H0 in H. \n     generalize H; clear H; case_eq (Var.veqb x p).\n     case_eq (T.eq_dec a0 t); try (intros; discriminate).\n     intros e1; generalize e1 e e0; rewrite e1.\n     intros e2; rewrite (T.UIP_refl e2); intros.\n     injection H2; intros.\n     rewrite H3; constructor; trivial.\n     intros; discriminate.\n    Qed.\n\n    Lemma WFAdv_c_EqObs : forall I c O, \n     WFAdv_c E I c O -> \n     (forall x, Vset.mem x I -> Var.is_local x) -> \n     EqObs (Vset.union IA I) E c E c (Vset.union IA O).\n    Proof.\n     destruct input_Adv_subset as (Hcomm,(Hadv, Horcl)).\n     induction 1 using WFAdv_c_prop with\n      (P0:= fun I i O (_:WFAdv_i E I i O) =>\n       (forall x, \n        Vset.mem x I -> \n        Var.is_local x) -> \n       EqObs (Vset.union IA I) E [i] E [i] (Vset.union IA O));\n      unfold EqObs in *; intros.\n     apply equiv_nil.\n     apply equiv_cons with (1:= IHWFAdv_c H0); eauto using WFAdv_i_local.\n     eapply equiv_strengthen;[ | apply equiv_assign].\n     unfold upd_para, kreq_mem; intros; simpl.\n     rewrite (equiv_WFRead w0 Hcomm Hadv H0).\n     destruct x; apply equiv_WFWrite; trivial.\n     eapply equiv_strengthen;[ | apply equiv_random].\n     unfold forall_random,kreq_mem; intros; simpl; split.\n     unfold eq_support.\n     apply EqObs_d_fv_expr.\n     apply req_mem_weaken with (2:= H0).\n     unfold WFReadD in w0; apply Vset.subset_complete; intros.\n     apply Vset.subset_correct with (Vset.union (Vset.union Gadv Gcomm) I).\n     rewrite <- (VsetP.union_idem IA); \n      repeat apply VsetP.subset_union_ctxt; auto with set.\n     repeat rewrite VsetP.union_spec; destruct (w0 _ H1); tauto.\n     destruct x; intros; apply equiv_WFWrite; trivial.\n     apply equiv_cond.\n     eapply equiv_strengthen; \n      [ | eapply equiv_weaken; [ | apply (IHWFAdv_c1 H1)] ].\n     unfold kreq_mem; intros k m1 m2 (W, _); trivial.\n     unfold kreq_mem; intros k m1 m2 W; apply req_mem_weaken with (2:= W).\n     apply VsetP.subset_union_ctxt; auto with set.\n     eapply equiv_strengthen; \n      [ | eapply equiv_weaken; [ | apply (IHWFAdv_c2 H1)] ].\n     unfold kreq_mem; intros k m1 m2 (W, _); trivial.\n     unfold kreq_mem; intros k m1 m2 W; apply req_mem_weaken with (2:= W).\n     apply VsetP.subset_union_ctxt; auto with set.\n     unfold kreq_mem; intros k m1 m2 W.\n     rewrite  (equiv_WFRead w Hcomm Hadv W); trivial.\n     eapply equiv_weaken; [ | apply equiv_while].\n     unfold kreq_mem; intros k m1 m2 (W, _); trivial.\n     unfold kreq_mem; intros k m1 m2 W.\n     rewrite  (equiv_WFRead w Hcomm Hadv W); trivial.\n     eapply equiv_strengthen;[ | apply equiv_weaken with (2:=IHWFAdv_c H0)].\n     unfold kreq_mem; intros k m1 m2 (W, _); trivial.\n     unfold kreq_mem; intros k m1 m2 W; apply req_mem_weaken with (2:= W).\n     apply VsetP.subset_union_ctxt; auto with set.\n     apply WFAdv_c_subset with E c; trivial.\n\n     (* Call Orcl *)\n     destruct (pi_def _ i) as (pif, Hdef).\n     eapply equiv_weaken;[ | apply pi_spec_call with (pi:=pif)].\n     unfold kreq_mem; red; intros.\n     rewrite VsetP.union_spec in H1; destruct H1. \n     apply H0; rewrite VsetP.union_spec, VsetP.diff_spec.\n     rewrite VsetP.union_spec; \n      destruct (VsetP.mem_dec x0 (pi_mod pif)); try tauto.\n     left; rewrite VsetP.add_spec; right; eapply input_orcl_pre; eauto.\n     generalize H1; unfold add_read; clear H1.\n     case_eq (Var.is_global x); intros.\n     apply H0; rewrite VsetP.union_spec, VsetP.diff_spec.\n     rewrite VsetP.union_spec; \n      destruct (VsetP.mem_dec x0 (pi_mod pif)); try tauto.\n     apply H in H2; unfold Var.is_local in H2.\n     apply mod_global in i0; rewrite i0 in H2; discriminate.\n     apply H0; rewrite VsetP.add_spec in H2; \n      rewrite VsetP.union_spec, VsetP.add_spec; destruct H2; try tauto.\n     rewrite VsetP.diff_spec, VsetP.union_spec.\n     destruct (VsetP.mem_dec x0 (pi_mod pif)); try tauto.\n     apply H in H2; unfold Var.is_local in H2.\n     apply mod_global in i0; rewrite i0 in H2; discriminate.\n     red; intros.\n     assert (forall ta (args0:E.args ta), \n      ta = (Proc.targs f) -> \n      exists e, get_arg x0 (proc_params E f) args0 = Some e).\n     apply  Vset_of_var_decl_ind with (P:= fun t0 x0 => \n      forall ta (args0:E.args ta), ta = (Proc.targs f) ->\n       exists e0 : E.expr t0, get_arg x0 (proc_params E f) args0 = Some e0)\n     (lv:= proc_params E f) .\n     generalize (Proc.targs f) (proc_params E f). \n     induction v; simpl; intros.\n     elim H1.\n     destruct args0; try discriminate.\n     injection H2; clear H2; intros; subst.\n     destruct H1.\n     inversion H1; subst.\n     assert (W:= T.inj_pair2 H5); clear H1 H4 H5; subst.\n     destruct (get_arg p v args0); eauto.\n     generalize (Var.veqb_spec p p); destruct (Var.veqb p p); intros.\n     case_eq (T.eq_dec a a); intros.\n     rewrite (T.UIP_refl e0); eauto.\n     elim (T.eq_dec_r H2); trivial.\n     elim H1; trivial.\n     destruct (IHv _ _ H1 _ args0 (refl_equal _)).\n     rewrite H2; eauto.\n     apply Vset.subset_correct with (2:= H0).\n     apply params_subset.\n     simpl; destruct (H1 _ args (refl_equal _)) as (e0, Heq); rewrite Heq.\n     red; intros.\n     assert (W:= get_arg_some _ _ _ Heq).   \n     apply equiv_WFRead with (1:= w _ _ W); auto.\n     apply VsetP.subset_trans with (1:= Horcl _ _ _ i Hdef); auto with set.\n\n     (* Call Adv *)\n     assert (W:forall t (x:Var.var t), \n      Vset.mem x (Vset_of_var_decl (proc_params E f)) -> Var.is_local x).\n     intros; apply Vset_of_var_decl_ind with \n      (P:= fun t (x:Var.var t) => Var.is_local x) (lv:= proc_params E f); auto.\n     intros; change (Var.vis_local x1).\n     apply proc_params_local with E t f; trivial.\n     assert (forall x, \n      Vset.mem x (Vset_of_var_decl (proc_params E f)) -> Var.is_local x). \n     intros (t0,x0); auto.\n     clear W.\n     apply  equiv_call with (3:= IHWFAdv_c H1).\n     unfold kreq_mem; red; intros.\n     rewrite VsetP.union_spec in H3; destruct H3. \n     repeat rewrite init_mem_global; auto using input_Adv_global.\n     apply H2; auto with set.\n     apply init_mem_local; auto.\n     generalize args w0.\n     generalize (Proc.targs f). induction args0; simpl; auto; intros.\n     rewrite IHargs0; auto.\n     rewrite (@equiv_WFRead a p I k m1 m2); auto.\n     unfold kreq_mem; red; intros. \n     destruct (Var.eq_dec x x0).\n     inversion e; simpl.\n     repeat rewrite return_mem_dest.\n     apply equiv_WFRead with (1 := w); auto.\n     rewrite VsetP.union_spec in H4; destruct H4. \n     repeat rewrite return_mem_global; auto using input_Adv_global.\n     apply H3; auto with set.\n     assert (Vset.mem x0 I). \n     unfold add_read in H4; destruct (Var.is_global x); auto.\n     rewrite VsetP.add_spec in H4; destruct H4; trivial.\n     elim (n1 H4).\n     repeat rewrite return_mem_local; auto. \n     apply H2; auto with set.\n    Qed.\n\n    Variable MA : Vset.t.\n  \n    Hypothesis MA_def : mod_adv = Some MA. \n    \n    Definition output_adv := Vset.inter IA MA.\n    \n    Lemma WFAdv_EqObs : forall t (f:Proc.proc t), WFAdv E f ->\n     exists ls, \n      (forall x, Vset.mem x ls -> Var.is_local x) /\\ \n      EqObs (Vset.union IA (Vset_of_var_decl (proc_params E f)))\n      E (proc_body E f) E (proc_body E f) (Vset.union ls output_adv) /\\ \n      EqObs_e (Vset.union (Vset.union ls output_adv) (Vset.diff IA MA))\n      (proc_res E f) (proc_res E f).\n    Proof.\n     intros t f (O,(H1,H2)).\n     exists O; split.\n     intros; apply WFAdv_c_local with (1:= H1); trivial.\n     intros (t0, x0) H0.\n     apply  Vset_of_var_decl_ind with \n      (P:=fun t (x:Var.var t) => Var.is_local x) (lv:=proc_params E f); trivial.\n     intros; change (Var.vis_local x1).\n     apply proc_params_local with E t f; trivial.\n     split.\n     unfold EqObs; eapply equiv_weaken;[ | apply WFAdv_c_EqObs with (1:=H1)].\n     unfold kreq_mem; intros; rewrite VsetP.union_sym.\n     apply req_mem_weaken with (2:= H).\n     apply VsetP.subset_union_ctxt; unfold output_adv; auto with set.\n     intros (t0, x0) H0.\n     apply  Vset_of_var_decl_ind with \n      (P:=fun t (x:Var.var t) => Var.is_local x) (lv:=proc_params E f); trivial.\n     intros; change (Var.vis_local x).\n     apply proc_params_local with E t f; trivial.\n     red; intros.\n     destruct input_Adv_subset as (Hcomm,(Hadv, Horcl)).\n     apply equiv_WFRead with (1 := H2); auto.\n     apply req_mem_weaken with (2:= H).\n     rewrite VsetP.union_assoc, VsetP.union_sym.\n     apply VsetP.subset_union_ctxt; auto with set.\n     unfold output_adv; apply Vset.subset_complete; intros.\n     rewrite VsetP.union_spec,VsetP.diff_spec, VsetP.inter_spec.\n     destruct (VsetP.mem_dec x MA); auto with set.\n    Qed.\n\n   End EQ_OBS.\n\n  End REFL_INFO.\n\n\n  Section INFO.\n\n   Variable inv : mem_rel.\n   Variables E1 E2 : env.\n   Variables X1 X2 : Vset.t.\n   Variable pii : eq_inv_info_o inv E1 E2.\n   \n   Hypothesis inv_dep : depend_only_rel inv X1 X2.\n\n   Hypothesis inv_global : forall x, \n    Vset.mem x (Vset.union X1 X2) -> Var.is_global x.\n\n   Hypothesis inv_dec : forall k (m1 m2:Mem.t k), sumbool (inv m1 m2) (~inv m1 m2).\n\n   Hypothesis disjoint_Orcl1 : Vset.disjoint X1 Gadv.\n\n   Hypothesis disjoint_Orcl2 : Vset.disjoint X2 Gadv.\n\n   Hypothesis Eq_adv_decl_12 : Eq_adv_decl E1 E2.\n\n   Hypothesis Eq_orcl_params_12: Eq_orcl_params E1 E2.\n\n   Definition iinput_Adv :=\n    PrSet.fold (fun f res =>\n     match res, pii (BProc.p_name f) with\n     | Some res, Some pif => Some (Vset.union (pii_input pif) res)\n     | _, _ => None\n     end) PrOrcl (Some (Vset.union Gadv Gcomm)).\n\n\n   Section EQ_OBS_INV.\n    \n    Variable IA : Vset.t.\n\n    Hypothesis IA_def : iinput_Adv = Some IA.\n\n    Lemma iinput_Adv_global : forall x, Vset.mem x IA -> Var.is_global x.\n    Proof.\n     generalize IA_def; unfold iinput_Adv.\n     rewrite PrSet.fold_spec.\n     assert (forall x, Vset.mem x (Vset.union Gadv Gcomm) -> Var.is_global x).\n     intros x; rewrite VsetP.union_spec; intros [H | H]; auto.\n     generalize (PrSet.elements PrOrcl) (Vset.union Gadv Gcomm) H; clear H.\n     induction l; simpl; intros.\n     apply H; inversion IA_def0; trivial.\n     destruct (pii (BProc.p_name a)).\n     apply IHl with (2:= IA_def0); trivial.\n     intros x0; rewrite VsetP.union_spec; intros [H1 | H1]; \n      auto using (iinput_global p).\n     generalize l IA_def0; clear IHl IA_def0 l.\n     induction l; simpl; intros; try discriminate; auto.\n    Qed.\n  \n    Lemma iinput_Adv_subset : \n     Gcomm [<=] IA /\\\n     Gadv [<=] IA /\\\n     forall t (f:Proc.proc t) pif, \n      PrSet.mem (BProc.mkP f) PrOrcl -> \n      pii f = Some pif -> \n      (pii_input pif) [<=] IA.\n    Proof.\n     unfold iinput_Adv in IA_def.\n     rewrite PrSet.fold_spec in IA_def. \n     assert (forall l X,\n      fold_left\n      (fun (x : option Vset.t) (a : ProcD.t) =>\n       match x with\n       | Some res =>\n         match pii (BProc.p_name a) with\n         | Some pif => Some (Vset.union (pii_input pif) res)\n         | None => None (A:=Vset.t)\n         end\n       | None => None (A:=Vset.t)\n       end) l (Some X) = Some IA ->\n      X [<=] IA /\\ \n      forall (f : ProcD.t) (pif : proc_eq_inv_info inv E1 E2 (BProc.p_name f)),\n       InA (@eq _) f l -> \n       pii (BProc.p_name f) = Some pif -> \n       pii_input pif [<=] IA).\n     induction l; simpl; intros; trivial.\n     inversion H; split; intros; auto with set.\n     inversion H0.\n     generalize H; clear H; case_eq (pii (BProc.p_name a)); intros.\n     destruct (IHl _ H0); split.\n     apply VsetP.subset_trans with (2 := H1); auto with set.\n     intros f pif Hin; inversion Hin; intros; auto; subst.\n     rewrite H in H6; inversion H6; subst.\n     apply VsetP.subset_trans with (2 := H1); auto with set.\n     elimtype False; generalize l H0; clear IHl H0 l.\n     induction l; simpl; intros; try discriminate; auto.\n     destruct (H _ _ IA_def).\n     split.\n     apply VsetP.subset_trans with (2:= H0); auto with set.\n     split.\n     apply VsetP.subset_trans with (2:= H0); auto with set.\n     intros; apply H1 with (f := BProc.mkP f); trivial.\n     apply PrSet.elements_correct; trivial.\n    Qed.\n\n    Hypothesis pi_def : forall o, \n     PrSet.mem o PrOrcl -> exists pio, pii (BProc.p_name o) = Some pio.\n\n    Hypothesis input_orcl_pre : \n     forall o pio, PrSet.mem o PrOrcl -> pii (BProc.p_name o) = Some pio ->\n      forall x, Vset.mem x IA -> \n       Vset.mem x (pi_mod (pi_eq_refl1 pio)) \\/\n       Vset.mem x (pi_mod (pi_eq_refl2 pio)) -> Vset.mem x (pii_output pio).\n\n    Lemma WFAdv_c_EqObsInv : forall I c O,  \n     WFAdv_c E1 I c O ->\n     (forall x, Vset.mem x I -> Var.is_local x) -> \n     EqObsInv inv (Vset.union IA I) E1 c E2 c (Vset.union IA O).\n    Proof.\n     destruct iinput_Adv_subset as (Hcomm,(Hadv, Horcl)).\n     induction 1 using WFAdv_c_prop with\n      (P0:= fun I i O (_:WFAdv_i E1 I i O) =>\n       (forall x, Vset.mem x I -> Var.is_local x) -> \n       EqObsInv inv (Vset.union IA I) E1 [i] E2 [i] (Vset.union IA O));\n      unfold EqObsInv in *; intros.\n     apply equiv_nil.\n     apply equiv_cons with (1:= IHWFAdv_c H0); eauto using WFAdv_i_local.\n     eapply equiv_strengthen;[ | apply equiv_assign].\n     intros k m1 m2 (H1, H2); split; unfold kreq_mem in *.\n     rewrite (equiv_WFRead w0 Hcomm Hadv H1).\n     destruct x; apply equiv_WFWrite; trivial.\n     apply inv_dep with m1 m2; trivial;\n     red; intros; rewrite Mem.get_upd_diff; trivial; intro.\n     assert (W: Var.is_global x0) by auto with set.\n     contradict H0. \n     apply VsetP.disjoint_mem_not_mem with \n      (1:=VsetP.disjoint_sym disjoint_Orcl1).\n     generalize W; rewrite <- H3; auto; destruct x; auto.\n     assert (W: Var.is_global x0) by auto with set.\n     contradict H0. \n     apply VsetP.disjoint_mem_not_mem with \n      (1:=VsetP.disjoint_sym disjoint_Orcl2).\n     generalize W; rewrite <- H3; auto; destruct x; auto.\n\n     eapply equiv_strengthen;[ | apply equiv_random].\n     intros k m1 m2 (H1, H2); split; unfold kreq_mem in *.\n     unfold eq_support.\n     apply EqObs_d_fv_expr.\n     apply req_mem_weaken with (2:= H1).\n     unfold WFReadD in w0; apply Vset.subset_complete; intros.\n     apply Vset.subset_correct with (Vset.union (Vset.union Gadv Gcomm) I).\n     rewrite <- (VsetP.union_idem IA); \n      repeat apply VsetP.subset_union_ctxt; auto with set.\n     repeat rewrite VsetP.union_spec; destruct (w0 _ H0); tauto.\n     destruct x; intros; split; unfold kreq_mem.\n     apply equiv_WFWrite; trivial.\n     apply inv_dep with m1 m2; trivial;\n     red; intros; rewrite Mem.get_upd_diff; trivial; intro.\n     assert (W: Var.is_global x) by auto with set.\n     contradict H3. \n     apply VsetP.disjoint_mem_not_mem with \n      (1:=VsetP.disjoint_sym disjoint_Orcl1).\n     generalize W; rewrite <- H4; auto.\n     assert (W: Var.is_global x) by auto with set.\n     contradict H3. \n     apply VsetP.disjoint_mem_not_mem with \n      (1:=VsetP.disjoint_sym disjoint_Orcl2).\n     generalize W; rewrite <- H4; auto.\n\n     (* Cond *)\n     apply equiv_cond.\n     eapply equiv_strengthen; \n      [ | eapply equiv_weaken; [ | apply (IHWFAdv_c1 H1)] ].\n     intros k m1 m2 (W, _); trivial.\n     intros k m1 m2 W; apply req_mem_rel_weaken with (3:= W); auto with set.\n     apply VsetP.subset_union_ctxt; auto with set.\n     unfold Basics.flip; trivial.\n     eapply equiv_strengthen; \n      [ | eapply equiv_weaken; [ | apply (IHWFAdv_c2 H1)] ].\n     intros k m1 m2 (W, _); trivial.\n     intros k m1 m2 W; apply req_mem_rel_weaken with (3:= W); auto with set.\n     apply VsetP.subset_union_ctxt; auto with set.\n     unfold Basics.flip; trivial.\n     intros k m1 m2 (W, Wi); rewrite  (equiv_WFRead w Hcomm Hadv W); trivial.\n\n     (* While *)  \n     eapply equiv_weaken;[ | apply equiv_while].\n     intros k m1 m2 (W, _); trivial.\n     intros k m1 m2 (W,_); rewrite  (equiv_WFRead w Hcomm Hadv W); trivial.\n     eapply equiv_strengthen;[ | apply equiv_weaken with (2:= IHWFAdv_c H0)].\n     intros k m1 m2 (W, _); trivial.\n     intros k m1 m2 W; apply req_mem_rel_weaken with (3:= W); auto.\n     apply VsetP.subset_union_ctxt; auto with set.\n     apply WFAdv_c_subset with E1 c; trivial.\n     unfold Basics.flip; trivial.\n     \n     (* Call Orcl *)\n     destruct (pi_def _ i) as (pif, Hdef).\n     apply equiv_call with \n       (Pf:= req_mem_rel (Vset.union (pii_params pif) IA) inv)\n       (Qf :=  \n        (req_mem_rel (Vset.union (pii_output pif) \n         (Vset.diff IA \n          (Vset.union (pi_mod (pi_eq_refl1 pif)) \n           (pi_mod (pi_eq_refl2 pif))))) inv) /-\\\n        fun k m1 m2 => \n         E.eval_expr (proc_res E1 f) m1 = E.eval_expr (proc_res E2 f) m2). \n\n     (* Init *)\n     unfold req_mem_rel, kreq_mem, andR; simpl; intros k m1 m2 (W3, W4).\n     assert (init_mem E1 f args m1 =={ Vset.union (pii_params pif) IA} \n             init_mem E2 f args m2).\n     apply req_mem_weaken with \n      (Vset.union (pii_params pif) (get_globals (Vset.union IA I))).\n     apply VsetP.subset_union_ctxt; auto with set. \n     apply Vset.subset_complete; intros. \n     apply get_globals_complete; auto with set.\n     apply iinput_Adv_global; trivial.\n     eapply EqObs_args_correct; eauto.\n     red; intros.\n     rewrite <- (Eq_orcl_params_12 _ i).\n     assert (forall ta (args0:E.args ta), ta = (Proc.targs f) -> \n      exists e, get_arg x0 (proc_params E1 f) args0 = Some e).\n     apply Vset_of_var_decl_ind with (P:= fun t0 x0 => \n      forall ta (args0:E.args ta), ta = (Proc.targs f) ->\n       exists e0 : E.expr t0, get_arg x0 (proc_params E1 f) args0 = Some e0)\n     (lv:= proc_params E1 f) .\n     generalize (Proc.targs f) (proc_params E1 f). \n     induction v; simpl; intros.\n     elim H1.\n     destruct args0; try discriminate.\n     injection H2; clear H2; intros; subst.\n     destruct H1.\n     inversion H1; subst.\n     assert (W:= T.inj_pair2 H5); clear H1 H4 H5; subst.\n     destruct (get_arg p v args0); eauto.\n     generalize (Var.veqb_spec p p); destruct (Var.veqb p p); intros.\n     case_eq (T.eq_dec a a); intros.\n     rewrite (T.UIP_refl e0); eauto.\n     elim (T.eq_dec_r H2); trivial.\n     elim H1; trivial.\n     destruct (IHv _ _ H1 _ args0 (refl_equal _)).\n     rewrite H2; eauto.\n     apply Vset.subset_correct with (2:= H0).\n     apply params_subset1.\n     simpl; destruct (H1 _ args (refl_equal _)) as (e0, Heq); rewrite Heq.\n     red; intros.\n     assert (W:= get_arg_some _ _ _ Heq).   \n     apply equiv_WFRead with (IA:=IA) (1:= w _ _ W); auto.\n     split; trivial.\n     unfold depend_only_rel in inv_dep.\n     apply inv_dep with m1 m2; trivial; red; intros;\n     rewrite init_mem_global; trivial; apply inv_global; \n      rewrite VsetP.union_spec; auto.\n\n     (* Post *)\n     unfold req_mem_rel, kreq_mem, andR; simpl.\n     intros k m1 m1' m2 m2' (W3, W4) ((W5, W6), W7); split.\n     red; intros.\n     destruct (Vset.ET.eq_dec x x0).\n     inversion e; subst; simpl.\n     repeat rewrite return_mem_dest; trivial.\n     change (Var.mkV x <> x0) in n.\n     case_eq (Var.is_global x0); intros.\n     repeat rewrite return_mem_global; trivial.\n     apply W5.\n     rewrite VsetP.union_spec, VsetP.diff_spec.\n     case_eq (Vset.mem x0 (pii_output pif)); intros; auto.\n     right.\n     rewrite VsetP.union_spec in H0; destruct H0.\n     split; trivial; rewrite VsetP.union_spec; intro.\n     rewrite (input_orcl_pre _ i Hdef _ H0 H3) in H2; discriminate.\n     assert (XX:= add_read_local _ _ H _ H0); unfold Var.is_local in XX;\n      rewrite H1 in XX; discriminate.\n     assert (Var.is_local x0) by (unfold Var.is_local; rewrite H1; trivial).\n     repeat rewrite return_mem_local; trivial.\n     apply W3.\n     rewrite VsetP.union_spec in H0 |- *; destruct H0; auto.\n     unfold add_read in H0.\n     destruct (Var.is_global x); auto.\n     rewrite VsetP.add_spec in H0; destruct H0; auto.\n     elim (n H0).\n     red in inv_dep.\n     apply inv_dep with m1' m2'; trivial; red; intros; \n      rewrite return_mem_global; trivial.\n     intros Heq; rewrite <-Heq in H0.\n     assert (W: Var.is_global x) by auto with set.\n     contradict H0. \n     apply VsetP.disjoint_mem_not_mem with \n      (1:= VsetP.disjoint_sym disjoint_Orcl1); auto.\n     auto with set.\n     intros Heq; rewrite <-Heq in H0.\n     assert (W: Var.is_global x) by auto with set.\n     contradict H0. \n     apply VsetP.disjoint_mem_not_mem with \n      (1:= VsetP.disjoint_sym disjoint_Orcl2); auto.\n     auto with set.\n\n     (* Body *)\n     destruct (mod_spec (pi_eq_refl1 pif)) as (L1, (T1,T2)).\n     destruct (mod_spec (pi_eq_refl2 pif)) as (L2, (T3,T4)).\n     destruct (pii_spec pif) as (ls, (H3,(H4,H5))).\n     apply Modify_Modify_pre with (P := fun _ _ => True)in T2.\n     apply Modify_Modify_pre with (P := fun _ _ => True)in T4.\n     apply equiv_union_Modify_pre2 with (4:= T2) (5:= T4) \n      (Q:= req_mem_rel (Vset.union ls (pii_output pif)) inv); intros.\n     auto.\n     tauto.\n     destruct H0; destruct H1; unfold kreq_mem in *.\n     assert (m1' =={Vset.diff IA \n      (Vset.union (pi_mod (pi_eq_refl1 pif)) (pi_mod (pi_eq_refl2 pif)))} m2').\n     red; intros.\n     rewrite VsetP.diff_spec, VsetP.union_spec in H9.\n     destruct H9.\n     rewrite <- H2.\n     rewrite <- H6.\n     apply H0; rewrite VsetP.union_spec; tauto.\n     rewrite VsetP.union_spec; intros [W | W]; try tauto.\n     assert (V1 := T3 _ W); unfold Var.is_local in V1.\n     rewrite (iinput_Adv_global _ H9) in V1; discriminate.\n     rewrite VsetP.union_spec; intros [W | W]; try tauto.\n     assert (V1 := T1 _ W); unfold Var.is_local in V1;\n      rewrite (iinput_Adv_global _ H9) in V1; discriminate.\n     split.\n     split; unfold kreq_mem; trivial.\n     apply req_mem_union; trivial.\n     apply req_mem_weaken with (2:= H1); auto with set.\n     apply H5.\n     apply req_mem_union; trivial.\n     apply req_mem_weaken with (2:= H9). \n     apply VsetP.diff_le_compat; auto with set.\n     eapply equiv_strengthen;[ | apply H4].\n     intros k m1 m2 (W3, W4); split; trivial.\n     unfold kreq_mem; rewrite VsetP.union_sym.\n     apply req_mem_weaken with (2:= W3).\n     apply VsetP.subset_union_ctxt; auto with set.\n\n     (* Call Adv *)\n     destruct (Eq_adv_decl_12 f) as (Heq1, (Heq2, Heq3)); trivial.\n\n     assert (W:forall t (x:Var.var t),  Vset.mem x \n      (Vset_of_var_decl (proc_params E1 f)) -> Var.is_local x).\n     intros; apply Vset_of_var_decl_ind with \n      (P:= fun t (x:Var.var t) => Var.is_local x) (lv:= proc_params E1 f); auto.\n     intros; change (Var.vis_local x1).\n     apply proc_params_local with E1 t f; trivial.\n     assert (forall x, Vset.mem x \n      (Vset_of_var_decl (proc_params E1 f)) -> Var.is_local x). \n     intros (t0,x0); auto.\n     clear W.\n     generalize (IHWFAdv_c H1).\n     pattern (proc_body E1 f) at 2; rewrite Heq2; intros.\n     apply  equiv_call with (3:= H2).\n     intros k m1 m2 (W1, W2); split.\n     unfold kreq_mem; red; intros.\n     rewrite (init_mem_eq2 E1 E2 f args args m1 Heq1); trivial.\n     rewrite VsetP.union_spec in H3; destruct H3. \n     repeat rewrite init_mem_global; auto using iinput_Adv_global.\n     apply W1; auto with set.\n     apply init_mem_local; auto.\n     generalize args w0.\n     generalize (Proc.targs f). induction args0; simpl; auto; intros.\n     rewrite IHargs0; auto.\n     rewrite (@equiv_WFRead IA a p I k m1 m2); auto.\n     unfold depend_only_rel in inv_dep.\n     apply inv_dep with m1 m2; trivial; red; intros;\n      rewrite init_mem_global; trivial; \n      apply inv_global; rewrite VsetP.union_spec; auto.\n     intros k m1 m1' m2 m2' (W1, W2) (W3, W4); split; unfold kreq_mem in *.\n     red; intros. \n     destruct (Var.eq_dec x x0).\n     inversion e; simpl.\n     repeat rewrite return_mem_dest.\n     rewrite <- Heq3.\n     apply equiv_WFRead with (IA:= IA) (1 := w); auto.\n     rewrite VsetP.union_spec in H3; destruct H3. \n     repeat rewrite return_mem_global; auto using iinput_Adv_global.\n     apply W3; auto with set.\n     assert (Vset.mem x0 I). \n     unfold add_read in H3; destruct (Var.is_global x); auto.\n     rewrite VsetP.add_spec in H3; destruct H3; trivial.\n     elim (n1 H3).\n     repeat rewrite return_mem_local; auto. \n     apply W1; auto with set.\n     unfold depend_only_rel in inv_dep.\n     apply inv_dep with m1' m2'; trivial; red; \n      intros; rewrite return_mem_global; trivial.\n     intros Heq; rewrite <-Heq in H3.\n     assert (W: Var.is_global x) by auto with set.\n     contradict H3. \n     apply VsetP.disjoint_mem_not_mem with \n      (1:=VsetP.disjoint_sym disjoint_Orcl1); auto.\n     auto with set.\n     intros Heq; rewrite <-Heq in H3.\n     assert (W: Var.is_global x) by auto with set.\n     contradict H3. \n     apply VsetP.disjoint_mem_not_mem with \n      (1:=VsetP.disjoint_sym disjoint_Orcl2); auto.\n     auto with set.\n    Qed.\n\n    (* TODO: Move these 2 definitions *)\n    Definition eq_refl_i1 t (f:Proc.proc t) :=\n     match pii f with\n     | Some pif => Some (pi_eq_refl1 pif)\n     | None => None\n     end.\n\n    Definition eq_refl_i2 t (f:Proc.proc t) :=\n     match pii f with\n     | Some pif => Some (pi_eq_refl2 pif)\n     | None => None\n     end.\n\n    Variable MA1 MA2 : Vset.t.\n\n    Hypothesis MA1_def : mod_adv eq_refl_i1 = Some MA1. \n\n    Hypothesis MA2_def : mod_adv eq_refl_i2 = Some MA2.\n\n    Definition ioutput_adv := Vset.inter IA (Vset.union MA1 MA2).\n\n    Lemma WFAdv_EqObsInv : forall t (f:Proc.proc t), WFAdv E1 f ->\n     ~ PrSet.mem (BProc.mkP f) PrOrcl -> \n     ~ PrSet.mem (BProc.mkP f) PrPriv -> \n     exists ls, \n      (forall x, Vset.mem x ls -> Var.is_local x) /\\ \n      EqObsInv inv (Vset.union IA (Vset_of_var_decl (proc_params E1 f)))\n      E1 (proc_body E1 f) E2 (proc_body E2 f) (Vset.union ls ioutput_adv) /\\ \n      EqObs_e (Vset.union (Vset.union ls ioutput_adv) \n       (Vset.diff IA (Vset.union MA1 MA2)))\n      (proc_res E1 f) (proc_res E2 f).\n    Proof.\n     intros t f (O,(H1,H2)) XX1 XX2.\n     exists O; split.\n     intros; apply WFAdv_c_local with (1:= H1); trivial.\n     intros (t0, x0) H0.\n     apply Vset_of_var_decl_ind with \n      (P:=fun t (x:Var.var t) => Var.is_local x) (lv:=proc_params E1 f); trivial.\n     intros; change (Var.vis_local x1).\n     apply proc_params_local with E1 t f; trivial.\n     destruct (Eq_adv_decl_12 f) as (Heq1, (Heq2, Heq3)); trivial.\n     rewrite <- Heq3, <- Heq2.\n     split.\n     unfold EqObsInv; eapply equiv_weaken; \n      [ | apply WFAdv_c_EqObsInv with (1:= H1)].\n     intros; eapply req_mem_rel_weaken; eauto.\n     rewrite VsetP.union_sym.\n     apply VsetP.subset_union_ctxt; unfold ioutput_adv; auto with set.\n     unfold Basics.flip; trivial.\n     intros (t0, x0) H0.\n     apply Vset_of_var_decl_ind with \n      (P:=fun t (x:Var.var t) => Var.is_local x) (lv:=proc_params E1 f); trivial.\n     intros; change (Var.vis_local x).\n     apply proc_params_local with E1 t f; trivial.\n     red; intros.\n     destruct iinput_Adv_subset as (Hcomm,(Hadv, Horcl)).\n     apply equiv_WFRead with (IA:= IA) (1 := H2); auto.\n     apply req_mem_weaken with (2:= H).\n     rewrite VsetP.union_assoc, VsetP.union_sym.\n     apply VsetP.subset_union_ctxt; auto with set.\n     unfold ioutput_adv; apply Vset.subset_complete; intros.\n     rewrite VsetP.union_spec,VsetP.diff_spec, VsetP.inter_spec.\n     destruct (VsetP.mem_dec x (Vset.union MA1 MA2)); auto with set.\n    Qed.\n\n   End EQ_OBS_INV.\n\n  End INFO.\n\n\n  Section UPTO.\n\n   Variable bad : Var.var T.Bool.\n  \n   Variable Gbad : Var.is_global bad.\n\n   Definition check_adv_upto_info (pi:forall t (p:Proc.proc t), bool) :=\n    (negb (Vset.mem bad Gadv) &&\n     (PrSet.forallb (fun p => pi _ p.(BProc.p_name)) PrOrcl))%bool.\n\n   Lemma upto_adv_preserves : forall E (pi:forall t (p:Proc.proc t), bool) I c O,\n    check_adv_upto_info pi ->\n    prbad_spec bad E pi ->\n    WFAdv_c E I c O -> \n    forall k (m:Mem.t k) f,\n     EP k bad m ->\n     mu ([[ c ]] E m) f ==\n     mu ([[ c ]] E m) (restr (EP k bad) f).\n   Proof.\n    intros E pi I c O Hadv Hpi Hwf.\n    unfold check_adv_upto_info in Hadv; rewrite is_true_andb in Hadv.\n    destruct Hadv as (W1, W2).\n    assert (forall x y : PrSet.E.t, PrSet.E.eq x y -> \n     (fun p : PrSet.E.t => pi (BProc.p_type p) (BProc.p_name p)) x = \n     (fun p : PrSet.E.t => pi (BProc.p_type p) (BProc.p_name p)) y).\n    intros x y Heq; rewrite (Heq:x = y); trivial.\n    assert (W:= PrSet.forallb_correct _ H _ W2); clear W2 H.\n    rewrite is_true_negb in W1.\n    intros k;\n    refine (WFAdv_c_prop\n    (fun _ c _ _ =>\n     forall m f,\n      EP k bad m ->\n      mu ([[ c ]] E m) f ==\n      mu ([[ c ]] E m) (restr (EP k bad) f))\n    (fun _ i _ _ =>\n     forall m f,\n      EP k bad m ->\n      mu ([[ [i] ]] E m) f ==\n      mu ([[ [i] ]] E m) (restr (EP k bad) f))\n    _ _ _ _ _ _ _ _ Hwf); unfold restr; intros.\n\n    repeat rewrite deno_nil_elim; rewrite H; trivial.\n\n    intros; repeat rewrite deno_cons_elim; repeat rewrite Mlet_simpl.\n    rewrite H; trivial.\n    symmetry; rewrite H; trivial.\n    apply mu_stable_eq; refine (ford_eq_intro _); intro m'.   \n    case_eq (EP k bad m'); [ | trivial]; intro Hm'.\n    symmetry; rewrite H0; trivial.\n\n    intros; repeat rewrite deno_assign_elim.\n    unfold EP in H |- *; simpl in H |- *.\n    rewrite Mem.get_upd_diff.\n    rewrite H; trivial.  \n    intro Hx; elim W1.  \n    rewrite <- Hx in Gbad |- *; destruct x; simpl; apply w; trivial.\n\n    intros; repeat rewrite deno_random_elim.\n    apply mu_stable_eq; refine (ford_eq_intro _); intro.\n    unfold EP in H |- *; simpl in H |- *.\n    rewrite Mem.get_upd_diff.\n    rewrite H; trivial.  \n    intro Hx; elim W1.  \n    rewrite <- Hx in Gbad |- *; destruct x; simpl; apply w; trivial.\n\n    intros; repeat rewrite deno_cond_elim.\n    case (E.eval_expr e m); auto.\n\n    intros; apply range_eq with (fun m => is_true (EP k bad m)).\n    eapply range_weaken with (fun m => EP k bad m /\\ E.eval_expr e m = false).\n    intros; tauto.\n    apply while_ind0; intros;[ | trivial].\n    intros g Hg.\n    rewrite H; trivial.\n    transitivity (mu ([[ c0 ]] E m0) (fzero _)).\n    symmetry; apply mu_zero.\n    apply mu_stable_eq.\n    refine (ford_eq_intro _); intro m'.\n    generalize (Hg m'); case (EP k bad m'); auto.\n    intros a Heq; rewrite Heq; trivial.\n\n    intros; repeat rewrite deno_call_elim.\n    rewrite (Hpi _ f (W _ i)).\n    apply mu_stable_eq; refine (ford_eq_intro _); intro m'.\n    unfold restr; case_eq (EP k bad m'); intro Hm'.\n    unfold EP; simpl; rewrite return_mem_global; trivial.\n    unfold EP in Hm'; simpl in Hm'; rewrite Hm'; trivial.  \n    intro Hx; elim W1.\n    rewrite <- Hx in Gbad |- *; destruct x; simpl; apply w0; trivial.\n    unfold EP; simpl; rewrite return_mem_global; trivial.\n    unfold EP in Hm'; simpl in Hm'; rewrite Hm'; trivial. \n    intro Hx; elim W1.\n    rewrite <- Hx in Gbad |- *; destruct x; simpl; apply w0; trivial.\n    unfold EP; simpl; rewrite init_mem_global; trivial.\n\n    intros; repeat rewrite deno_call_elim.\n    rewrite (H (init_mem E f args m)).\n    apply mu_stable_eq; refine (ford_eq_intro _); intro m'.\n    unfold restr; case_eq (EP k bad m'); intro Hm'.\n    unfold EP; simpl; rewrite return_mem_global; trivial.\n    unfold EP in Hm'; simpl in Hm'; rewrite Hm'; trivial.  \n    intro Hx; elim W1.\n    rewrite <- Hx in Gbad |- *; destruct x; simpl; apply w2; trivial.\n    unfold EP; simpl; rewrite return_mem_global; trivial.\n    unfold EP in Hm'; simpl in Hm'; rewrite Hm'; trivial. \n    intro Hx; elim W1.\n    rewrite <- Hx in Gbad |- *; destruct x; simpl; apply w2; trivial.\n    unfold EP; simpl; rewrite init_mem_global; trivial.\n   Qed.\n\n   Lemma  upto_adv_upto : forall E1 E2 (pi:upto_info bad E1 E2) I c O,\n    check_adv_upto_info pi ->\n    Eq_adv_decl E1 E2 -> Eq_orcl_params E1 E2 ->\n    WFAdv_c E1 I c O ->\n    (forall k (m:Mem.t k) f,\n     mu ([[c]] E1 m) (restr (negP (EP k bad)) f) ==\n     mu ([[c]] E2 m) (restr (negP (EP k bad)) f)).\n   Proof.\n    intros E1 E2 pi I c O Hadv HEq HeqO Hwf k; generalize Hadv.\n    unfold check_adv_upto_info in Hadv; rewrite is_true_andb in Hadv.\n    destruct Hadv as (W1, W2).\n    assert (forall x y : PrSet.E.t, PrSet.E.eq x y -> \n     (fun p : PrSet.E.t => pi (BProc.p_type p) (BProc.p_name p)) x = \n     (fun p : PrSet.E.t => pi (BProc.p_type p) (BProc.p_name p)) y).\n    intros x y Heq; rewrite (Heq:x = y); trivial.\n    assert (W:= PrSet.forallb_correct _ H _ W2); clear W2 H.\n    rewrite is_true_negb in W1.\n    intros Hadv; refine (WFAdv_c_prop\n     (fun _ c _ _ => \n      forall m f,\n       mu ([[ c ]] E1 m) (restr (negP (EP k bad)) f) ==\n       mu ([[ c ]] E2 m) (restr (negP (EP k bad)) f))\n     (fun _ i _ _ =>\n      forall m f,\n       mu ([[ [i] ]] E1 m) (restr (negP (EP k bad)) f) ==\n       mu ([[ [i] ]] E2 m) (restr (negP (EP k bad)) f))\n     _ _ _ _ _ _ _ _ Hwf); clear Hwf c; unfold restr; intros.\n    repeat rewrite deno_nil_elim; trivial.\n\n    (* cons *)\n    rewrite deno_cons_elim, Mlet_simpl.\n    rewrite (deno_cons_elim E2 i c m), Mlet_simpl.\n    rewrite (mu_restr_split (([[ [i] ]]) E1 m) (EP k bad)).\n    unfold restr; rewrite (mu_restr_split (([[ [i] ]]) E2 m) (EP k bad)).\n    apply Uplus_eq_compat.\n\n    transitivity (mu (([[ [i] ]]) E1 m) (fzero _)).\n    apply mu_stable_eq; refine (ford_eq_intro _); intros m'.\n    case_eq (EP k bad m'); intros;[ | trivial].\n    rewrite (@upto_adv_preserves E1 pi IO c O0); trivial.\n    transitivity (mu (([[ c ]]) E1 m') (fzero _)).\n    apply mu_stable_eq; refine (ford_eq_intro _); intros m''.\n    unfold restr, negP; destruct (EP k bad m''); trivial.\n    symmetry; rewrite mu_zero; trivial.\n    apply upto_pr1. \n\n    transitivity (mu (([[ [i] ]]) E2 m) (fzero _)).\n    repeat rewrite mu_zero; trivial.\n    apply mu_stable_eq; refine (ford_eq_intro _); intros m'.\n    unfold restr; case_eq (EP k bad m'); intros;[ | trivial].\n    rewrite (@upto_adv_preserves E2 pi IO c O0); trivial.\n    transitivity (mu (([[ c ]]) E2 m') (fzero _)).\n    rewrite mu_zero; trivial.\n    apply mu_stable_eq; refine (ford_eq_intro _); intros m''.\n    unfold restr, negP; destruct (EP k bad m''); trivial.\n    apply upto_pr2. \n    apply WFAdv_c_trans with E1; trivial.\n\n    unfold restr; rewrite H.\n    apply mu_stable_eq; refine (ford_eq_intro _); intros m'.\n    unfold negP; case_eq (EP k bad m'); intros; unfold negb; trivial.\n\n    (* Assign *)\n    repeat rewrite deno_assign_elim; trivial.\n\n    (* Random *)\n    repeat rewrite deno_random_elim; trivial.\n\n    (* Cond *)\n    repeat rewrite deno_cond_elim.\n    destruct (E.eval_expr e m); trivial.\n\n    (* While *)\n    transitivity\n     (mu (lub (unroll_while_sem E1 e c m)) (restr (negP (EP k bad)) f));\n     [ refine (eq_distr_elim _ _); apply deno_while_unfold | ].\n    transitivity\n     (mu (lub (unroll_while_sem E2 e c m)) (restr (negP (EP k bad)) f));\n     [ | refine (eq_distr_elim _ _); symmetry; apply deno_while_unfold ].\n    simpl; apply lub_eq_compat.\n    refine (ford_eq_intro _); intro n; simpl.\n    generalize m; clear m; induction n; intro m; simpl;\n     repeat rewrite (deno_cond_elim (k:=k)).\n    case (E.eval_expr e m); repeat rewrite deno_nil_elim; trivial.\n    case (E.eval_expr e m); repeat rewrite deno_app_elim.\n    rewrite (mu_restr_split ([[c]] E1 m) (EP k bad)).\n    unfold restr; rewrite (mu_restr_split ([[c]] E2 m) (EP k bad)).\n    apply Uplus_eq_compat. \n\n    transitivity (mu ([[c]] E1 m) (fzero _)).\n    apply mu_stable_eq; refine (ford_eq_intro _); intro m'; unfold restr.\n    case_eq (EP k bad m'); intro Heq; [ | trivial].\n    assert (PR:= upto_adv_preserves Hadv pi.(upto_pr1) w0).\n    rewrite (fun f => unroll_while_preserves_bad2 E1 e c n (PR k) f Heq).\n    transitivity (mu (([[ unroll_while e c n ]]) E1 m') (fzero _)).\n    apply mu_stable_eq; refine (ford_eq_intro _); intros m''; unfold restr, negP.\n    case_eq (EP k bad m''); intros; trivial.\n    case (E.eval_expr e m''); trivial; simpl; rewrite H0; trivial.\n    apply mu_zero.\n    transitivity (mu ([[c]] E2 m) (fzero _)).\n    repeat rewrite mu_zero; trivial.\n    apply mu_stable_eq; refine (ford_eq_intro _); intro m'; unfold restr.\n    case_eq (EP k bad m'); intro Heq; [ | trivial].\n    assert (PR:= upto_adv_preserves Hadv pi.(upto_pr2) \n     (WFAdv_c_trans HeqO HEq w0)).\n    rewrite (fun f => unroll_while_preserves_bad2 E2 e c n (PR k) f Heq).\n    transitivity (mu (([[ unroll_while e c n ]]) E2 m') (fzero _)).\n    rewrite mu_zero; trivial.\n    apply mu_stable_eq; refine (ford_eq_intro _); intros m''; unfold restr, negP.\n    case_eq (EP k bad m''); intros; trivial.\n    case (E.eval_expr e m''); trivial; simpl; rewrite H0; trivial.\n\n    unfold restr; rewrite H.\n    apply mu_stable_eq; refine (ford_eq_intro _); intro m'.\n    destruct (negP (EP k bad) m'); trivial.\n    repeat rewrite deno_nil_elim; trivial.\n\n    (* Call Orcl *)\n    repeat rewrite deno_call_elim.\n    destruct (pi.(supto) _ (W _ i))as (H0, (H1, H2)).\n    transitivity\n     (mu ([[proc_body E1 f]] E1 (init_mem E1 f args m))\n      (restr (negP (EP k bad)) (fun m' => f0 (return_mem E1 x f m m')))).\n    apply mu_stable_eq.\n    unfold restr, negP, EP; refine (ford_eq_intro _); intro m'.\n    simpl; rewrite return_mem_global; trivial.\n    intro Hx; elim W1.\n    rewrite <- Hx in Gbad |- *; destruct x; simpl; apply w0; trivial.\n    rewrite H0; unfold BProc.p_name.\n    rewrite (init_mem_eq2 E1 (k:=k) E2 f args args); trivial.\n    apply mu_stable_eq.\n    unfold restr, negP, EP; refine (ford_eq_intro _); intro m'.\n    simpl; rewrite (return_mem_eq E1 E2 f x m m' H1).\n    rewrite return_mem_global; trivial.\n    intro Hx; elim W1.\n    rewrite <- Hx in Gbad |- *; destruct x; simpl; apply w0; trivial.\n\n    (* Call Adv *)\n    repeat rewrite deno_call_elim.\n    destruct (HEq _ f n n0) as (H0, (H1, H2)).\n    transitivity\n     (mu ([[proc_body E1 f]] E1 (init_mem E1 f args m))\n      (restr (negP (EP k bad)) (fun m' => f0 (return_mem E1 x f m m')))).\n    apply mu_stable_eq.\n    unfold restr, negP, EP; refine (ford_eq_intro _); intro m'.\n    simpl; rewrite return_mem_global; trivial.\n    intro Hx; elim W1.\n    rewrite <- Hx in Gbad |- *; destruct x; simpl; apply w2; trivial.\n    unfold restr; rewrite H.\n    rewrite <- H1.\n    rewrite (init_mem_eq2 E1 (k:=k) E2 f args args); trivial.\n    apply mu_stable_eq.\n    unfold restr, negP, EP; refine (ford_eq_intro _); intro m'.\n    simpl; rewrite (return_mem_eq E1 E2 f x m m' H2).\n    rewrite return_mem_global; trivial.\n    intro Hx; elim W1.\n    rewrite <- Hx in Gbad |- *; destruct x; simpl; apply w2; trivial.\n   Qed.\n\n  End UPTO.\n\n\n  Section UPTO2.\n\n   Variable Inv : mem_rel.\n\n   Variables E1 E2 : env.\n\n   Variables X1 X2 : Vset.t.\n  \n   Hypothesis inv_dep : depend_only_rel Inv X1 X2.\n\n   Hypothesis inv_global : forall x,\n    Vset.mem x (Vset.union X1 X2) -> Var.is_global x.\n   \n   Hypothesis disjoint_Orcl1 : Vset.disjoint X1 Gadv.\n   Hypothesis disjoint_Orcl2 : Vset.disjoint X2 Gadv.\n\n   Hypothesis Eq_adv_decl_12 : Eq_adv_decl E1 E2.\n\n   Hypothesis Eq_orcl_params_12: Eq_orcl_params E1 E2.\n\n   Section EQ_OBS_INV.\n     \n    (* TODO: Move this to WP.v *) \n    Definition mem_pred := forall k : nat, Mem.t k -> Prop.\n    \n    Definition andp (P1 P2:mem_pred) k (m:Mem.t k) := P1 k m /\\ P2 k m.\n    Definition orp (P1 P2:mem_pred) k (m:Mem.t k) := P1 k m \\/ P2 k m.\n    Definition impp (P1 P2:mem_pred) k (m:Mem.t k) := P1 k m -> P2 k m.\n    Definition eqp (P1 P2:mem_pred) k (m:Mem.t k) := P1 k m <-> P2 k m.\n    Definition notp (P:mem_pred) k (m:Mem.t k) := ~ P k m.\n    Definition falsep:mem_pred := fun k (m:Mem.t k), False.\n    Definition truep:mem_pred := fun k (m:Mem.t k), True.\n    Definition EPp (e:E.expr T.Bool) k (m:Mem.t k) := is_true (E.eval_expr e m).\n\n    Definition upd_pred \n     (P:mem_pred) (t:T.type) (x:Var.var t) (e:E.expr t) : mem_pred :=\n     fun k (m:Mem.t k) => P k (m {!x <-- E.eval_expr e m!}).\n\n    Definition eqR (P1 P2:mem_rel) := andR (impR P1 P2) (impR P2 P1).\n    \n    Definition rel_pred1 (P:mem_pred) : mem_rel := fun k m1 m2 => P k m1.\n\n    Definition rel_pred2 (P:mem_pred) : mem_rel := fun k m1 m2 => P k m2.\n\n    Lemma rel_pred1_spec k (m1 m2:Mem.t k) P :\n     (rel_pred1 P) k m1 m2 -> P k m1.\n    Proof. \n     auto. \n    Qed.\n\n    Lemma rel_pred2_spec k (m1 m2:Mem.t k) P :\n      (rel_pred2 P) k m1 m2 -> P k m2.\n    Proof.\n     auto.\n    Qed.\n   \n \n    Section HOARE_RULES.\n      \n     Variable k : nat.\n      \n     Definition Hoare \n      (m:Mem.t k) (E:env) (P:mem_pred) (c:cmd) (Q:mem_pred) : Prop :=\n      P k m -> range (Q k) ([[ c ]] E m).\n\n     Lemma range_Munit k (Q:mem_pred) (m:Mem.t k) : Q k m -> range (Q k) (Munit m).\n     Proof.\n      intros; unfold range, mu; simpl; intros; auto.\n     Qed.\n\n     Lemma Hoare_nil (m:Mem.t k) E (P Q:mem_pred) : \n      (forall k (m:Mem.t k), P k m -> Q k m) ->\n      Hoare m E P nil Q.\n     Proof.\n      intros; unfold Hoare; rewrite deno_nil; intros;  apply range_Munit; auto.\n     Qed.\n      \n     Lemma Hoare_assign (m:Mem.t k) E P t (x:Var.var t) (e:E.expr t) :\n      Hoare m E (upd_pred P x e) [ x <- e ] P.\n     Proof.\n      intros; unfold Hoare, upd_pred; rewrite deno_assign; apply range_Munit.\n     Qed.\n\n     Lemma Hoare_random (m:Mem.t k) E (P Q:mem_pred) \n      t (x:Var.var t) (d:DE.support t) :\n      (forall x0:T.interp k t, P k m -> Q k (m {!x <-- x0!})) ->\n      Hoare m E P [ x <$- d ] Q.\n     Proof.\n      unfold Hoare; intros.\n      rewrite deno_random.\n      eapply range_Mlet.\n      apply range_True.\n      intros.\n      apply range_Munit.\n      auto.\n     Qed.\n      \n     Lemma Hoare_cons m E P Q R i c:\n      Hoare m E P [i] R ->\n      (forall m, Hoare m E R c Q) ->\n      Hoare m E P (i :: c) Q.\n     Proof.\n      unfold Hoare; intros; rewrite deno_cons; eapply range_Mlet; auto.\n     Qed.\n     \n     Lemma Hoare_false m E c Q : Hoare m E falsep c Q.\n     Proof.\n      intros; unfold Hoare; intros; elim H.\n     Qed.\n      \n     Lemma Hoare_cond m E b c1 c2 P Q :\n      Hoare m E (andp P (EPp b)) c1 Q ->\n      Hoare m E (andp P (notp (EPp b))) c2 Q ->\n      Hoare m E P [If b then c1 else c2] Q.\n     Proof.\n      unfold Hoare, andp, notp, EPp; intros; rewrite deno_cond.\n      case_eq (E.eval_expr b m); intros; [ | apply not_is_true_false in H2]; auto.\n     Qed.\n\n     Lemma Hoare_case m E c (P Q R:mem_pred) :\n      sumbool (R k m) (~R k m) ->\n      Hoare m E (andp P (notp R)) c Q ->\n      Hoare m E (andp P R) c Q ->\n      Hoare m E P c Q.\n     Proof.\n      intros; intro.\n      destruct H.\n      apply H1; unfold andp; auto.\n      apply H0; unfold andp; auto.\n     Qed.\n\n     Lemma Hoare_call (m:Mem.t k) E (P Q:mem_pred) t (x:Var.var t) f la :\n      (P k m -> P k (init_mem E f la m)) ->\n      (forall m0, Q k m0 ->  Q k (return_mem E x f m m0)) ->\n      Hoare (init_mem E f la m) E P (proc_body E f) Q ->\n      Hoare m E P [x <c- f with la] Q.\n     Proof.\n      unfold Hoare; intros.\n      rewrite deno_call.\n      eapply range_Mlet.\n      apply (H1 (H H2)).\n      intros; apply range_Munit; auto.     \n     Qed.\n\n     Lemma Hoare_app m E c1 c2 P Q R :\n      Hoare m E P c1 R -> \n      (forall m, Hoare m E R c2 Q) ->\n      Hoare m E P (c1 ++ c2) Q.\n     Proof.\n      unfold Hoare; intros; rewrite deno_app.\n      eapply range_Mlet; intros.\n      apply H; trivial.\n      apply H0; trivial.\n     Qed.\n     \n     Lemma Hoare_strengthen (m:Mem.t k) E c (P Q R:mem_pred) :\n      (P k m -> R k m) ->\n      Hoare m E R c Q ->\n      Hoare m E P c Q.\n     Proof.\n      unfold Hoare; intros; eapply range_weaken; eauto.\n     Qed.\n     \n     Lemma Hoare_weaken (m:Mem.t k) E c (P Q R:mem_pred) :\n      (forall m, R k m -> Q k m) ->\n      Hoare m E P c R ->\n      Hoare m E P c Q.\n     Proof.\n      unfold Hoare; intros; eapply range_weaken; eauto.\n     Qed.\n     \n     Lemma Hoare_while m E e c (P:mem_pred) :\n      (forall m, Hoare m E (andp P (EPp e)) c P) ->\n      Hoare m E P [while e do c] (andp P (notp (EPp e))).\n     Proof.\n      intros; unfold Hoare; intros.\n      unfold andp, notp, EPp in *.\n      eapply range_weaken with (fun m0:Mem.t k => P k m0 /\\ E.eval_expr e m0 = false).\n      intros; rewrite not_is_true_false; split; try tauto.\n      apply while_ind0; intros; trivial.\n      apply H; tauto.\n     Qed.\n    \n    End HOARE_RULES.\n\n    Variables bad1_expr bad2_expr : E.expr T.Bool.\n\n    Definition bad1 := EPp bad1_expr.\n    Definition bad2 := EPp bad2_expr.\n\n    Hypothesis Gbad1 : forall x, Vset.mem x (fv_expr bad1_expr) -> Var.is_global x.\n    Hypothesis Gbad2 : forall x, Vset.mem x (fv_expr bad2_expr) -> Var.is_global x. \n    Hypothesis bad1_adv : Vset.disjoint (fv_expr bad1_expr) Gadv.\n    Hypothesis bad2_adv : Vset.disjoint (fv_expr bad2_expr) Gadv.\n\n    Hypothesis bad1_dec : forall k (m1 m2:Mem.t k), \n     sumbool ((rel_pred1 bad1) k m1 m2) (~(rel_pred1 bad1) k m1 m2).\n\n    Hypothesis bad2_dec : forall k (m1 m2:Mem.t k), \n     sumbool ((rel_pred2 bad2) k m1 m2) (~(rel_pred2 bad2) k m1 m2).\n\n    Hypothesis Gcomm_empty : Gcomm [=] Vset.empty.\n   \n    Lemma equiv_rel_pred : forall (P1 P2 Q1 Q2: mem_pred) (P: mem_rel) c1 E1 c2 E2,\n     lossless E1 c1 -> lossless E2 c2 -> \n     (forall k (m:Mem.t k), Hoare m E1 P1 c1 Q1) ->\n     (forall k (m:Mem.t k), Hoare m E2 P2 c2 Q2) ->\n     (forall k (m1 m2:Mem.t k), P k m1 m2 -> (P1 k m1 /\\ P2 k m2)) ->\n     (forall k (m1:Mem.t k), sumbool (Q1 k m1) (~ Q1 k m1)) ->\n     (forall k (m2:Mem.t k), sumbool (Q2 k m2) (~ Q2 k m2)) ->\n     (equiv P E1 c1 E2 c2 ((rel_pred1 Q1) /-\\ (rel_pred2 Q2))).\n    Proof.\n    intros.\n    intro k.\n     exists (fun m1 m2 => prod_distr ([[ c1 ]] E0 m1) ([[ c2 ]] E3 m2)); intros.\n     apply H3 in H4; destruct H4.\n     constructor; intros.\n     rewrite prod_distr_fst; unfold lossless in H0; rewrite H0; auto.\n     rewrite prod_distr_snd; unfold lossless in H; rewrite H; auto.\n     unfold range, prod_distr; intros.\n     rewrite Mlet_simpl.\n     rewrite (@range_cover _ (Q1 k)  (([[ c1 ]]) E0 m1) (carac (X k))); auto.\n     rewrite <- mu_0.\n     apply mu_stable_eq.\n     refine (@ford_eq_intro _ _ _ _ _); intros.\n     unfold carac.\n     case (X k n); intros; Usimpl; trivial.\n     rewrite Mlet_simpl.\n     rewrite (@range_cover _ (Q2 k)  (([[ c2 ]]) E3 m2) (carac (X0 k))); auto.\n     rewrite <- mu_0.\n     apply mu_stable_eq.\n     refine (@ford_eq_intro _ _ _ _ _); intros.\n     unfold carac.\n     case (X0 k n0); intros; Usimpl; trivial.\n     simpl.\n     apply H6.\n     split; trivial.\n     apply H2; trivial.\n     apply cover_dec.\n     apply H1; trivial.\n     apply cover_dec.\n    Qed.\n\n    Definition depend_only_pred (P:mem_pred) (X:Vset.t) :=\n     forall (k:nat) (m m':Mem.t k), m =={X}m' -> P k m -> P k m'.\n\n    Lemma depend_only_rel_pred1 I X1 X2 :\n     depend_only_pred I X1 <->\n     depend_only_rel (rel_pred1 I) X1 X2.\n    Proof.\n     unfold depend_only_pred, depend_only_rel, rel_pred1; split; intros.\n     eapply H; eauto.\n     apply H with m m m; auto with set.\n    Qed.\n\n    Lemma depend_only_rel_pred2 I X1 X2 :\n     depend_only_pred I X2 <->\n     depend_only_rel (rel_pred2 I) X1 X2.\n    Proof.\n     unfold depend_only_pred, depend_only_rel, rel_pred2; split; intros.\n     eapply H; eauto.\n     apply H with m m m; auto with set.\n    Qed.\n\n\n    Section ADV_PRESERVES_BAD.\n\n     Variables X : Vset.t.\n\n     Variables E : env.\n\n     Variables bad : mem_pred.\n\n     Hypothesis bad_dep : depend_only_pred bad X.\n\n     Hypothesis X_global : forall x : VarP.Edec.t,\n      Vset.mem x X -> Var.is_global x.\n\n     Hypothesis disjoint_Orcl : Vset.disjoint X Gadv.\n\n     Hypothesis o_preserve_bad : forall k (m:Mem.t k) (t:T.type) (f:Proc.proc t),\n      PrSet.mem {| BProc.p_type := t; BProc.p_name := f |} PrOrcl ->\n      Hoare m E bad (proc_body E f) bad.\n\n     Lemma a_preserve_bad :forall I c O,\n      WFAdv_c E I c O ->\n      (forall k (m:Mem.t k), Hoare m E bad c bad).\n     Proof.\n      induction 1 using WFAdv_c_prop with \n       (P0 := fun I i O (_:WFAdv_i E I i O) =>\n        (forall k (m:Mem.t k) , Hoare m E bad [i] bad)); intros.\n      apply Hoare_nil; intros; trivial.\n      eapply Hoare_cons; eauto.\n      eapply Hoare_strengthen;[ | apply Hoare_assign].\n      intros.\n      unfold upd_pred.\n      eapply bad_dep; [ | eauto ].\n      red; intros; destruct x.\n      rewrite Mem.get_upd_diff; trivial; intro.\n      assert (W:Var.is_global x0) by auto with set.\n      contradict H0.\n      apply VsetP.disjoint_mem_not_mem with (1:=VsetP.disjoint_sym disjoint_Orcl).\n      generalize w; rewrite <- H1 in *; destruct x0; auto.\n\n      apply Hoare_random; intros.\n      eapply bad_dep;[ | eauto ].\n      red; intros; destruct x.\n      rewrite Mem.get_upd_diff; trivial; intro.\n      assert (W:Var.is_global x1) by auto with set.\n      contradict H0.\n      apply VsetP.disjoint_mem_not_mem with\n       (1:=VsetP.disjoint_sym disjoint_Orcl).\n      generalize w; rewrite <- H1 in *; destruct x1; auto.\n\n      apply Hoare_cond.\n      eapply Hoare_strengthen; [ | apply IHWFAdv_c1 ].\n      unfold andp; tauto.\n      eapply Hoare_strengthen; [ | apply IHWFAdv_c2 ].\n      unfold andp; tauto.\n\n      eapply Hoare_weaken; [ |  apply Hoare_while ].\n      intros m0 (H1, _); trivial.\n      intros m0 (H1, _).\n      apply IHWFAdv_c; trivial.\n\n      apply Hoare_call; auto; intros.\n      eapply bad_dep; [ | eauto ].\n      red; intros; rewrite init_mem_global; trivial.\n      auto with set.\n      eapply bad_dep; [ | eauto ].\n      red; intros; rewrite return_mem_global; trivial.\n      intro.\n      eapply VsetP.disjoint_mem_not_mem with \n       (1 := VsetP.disjoint_sym disjoint_Orcl).\n      apply w0.\n      rewrite H1; auto with set.\n      rewrite H1; auto with set.\n      auto with set.\n\n      apply Hoare_call; auto; intros.\n      eapply bad_dep; [ | eauto ].\n      red; intros; rewrite init_mem_global; auto with set.\n      eapply bad_dep; [ | eauto ].\n      red; intros; rewrite return_mem_global; trivial.\n      intro.\n      eapply VsetP.disjoint_mem_not_mem with (1:=VsetP.disjoint_sym disjoint_Orcl).\n      apply w1.\n      rewrite H2; auto with set.\n      rewrite H2; auto with set.\n      auto with set.\n     Qed.\n\n    End ADV_PRESERVES_BAD.\n\n\n    Hypothesis o_preserve_bad1 : forall k (m:Mem.t k) (t:T.type) (f:Proc.proc t),\n     PrSet.mem {| BProc.p_type := t; BProc.p_name := f |} PrOrcl ->\n     Hoare m E1 bad1 (proc_body E1 f) bad1.\n\n    Hypothesis o_preserve_bad2 : forall k (m:Mem.t k) (t:T.type) (f:Proc.proc t),\n     PrSet.mem {| BProc.p_type := t; BProc.p_name := f |} PrOrcl ->\n     Hoare m E2 bad2 (proc_body E2 f) bad2.\n\n    Inductive slossless_i : env -> I.t -> Prop :=\n    | slossless_assign : forall E t (x:Var.var t) e,\n      lossless E [x <- e] ->\n      slossless_i E (x <- e)\n    | slossless_random : forall E t (x:Var.var t) d,\n      lossless E [x <$- d] ->\n      slossless_i E (x <$- d)\n    | slossless_cond : forall E e c1 c2,\n      slossless_c E c1 ->\n      slossless_c E c2 ->\n      slossless_i E (If e then c1 else c2)\n    | slossless_while : forall E e c,\n      lossless E [while e do c] ->\n      slossless_c E c ->\n      slossless_i E (while e do c)\n    | slossless_call_adv : forall E t (x:Var.var t) f args,\n      slossless_c E (proc_body E f) ->\n      slossless_i E (x <c- f with args)\n    with slossless_c : env -> cmd -> Prop :=\n    | slossless_nil : forall E, lossless E nil -> slossless_c E nil\n    | slossless_cons : forall E i c,\n      slossless_i E i ->\n      slossless_c E c ->\n      slossless_c E (i::c).\n\n    Scheme slossless_c_prop := Induction for slossless_c Sort Prop\n     with slossless_i_prop := Induction for slossless_i Sort Prop.\n\n    Lemma slossless_lossless E c :\n     slossless_c E c ->\n     lossless E c.\n    Proof.\n     induction 1 using slossless_c_prop with \n      (P0 := fun E i (_:slossless_i E i) => lossless E [i]); trivial.\n     apply lossless_cons; trivial.\n     apply lossless_cond; trivial.\n     apply lossless_call; trivial.\n    Qed.  \n\n    Lemma slossless_app : forall E c1 c2,\n     slossless_c E c1 ->\n     slossless_c E c2 ->\n     slossless_c E (c1 ++ c2).\n    Proof.\n     intro E'; induction c1.\n     intros; simpl; trivial.\n     intros; inversion_clear H.\n     rewrite <-app_comm_cons.\n     apply slossless_cons; auto.\n    Qed.\n\n    Lemma local_global : forall v, \n     Var.is_local v <-> ~Var.is_global v.\n    Proof.  \n     intros (tx, x); destruct x; unfold Var.is_local, Var.is_global; \n      split; simpl; intro; trivialb.\n    Qed.\n\n    Variable e_bad : E.expr T.Bool.\n\n    Lemma equiv_while_ind : forall (P:mem_rel) E1 E2 e1 e2 c1 c2,\n     (forall k (m1 m2:Mem.t k), P k m1 m2 -> \n      E.eval_expr e1 m1 = E.eval_expr e2 m2 ) ->\n     equiv (P /-\\ EP1 e1) E1 c1 E2 c2 P ->\n     equiv P E1 [while e1 do c1] E2 [while e2 do c2] \n     (fun k (m1 m2:Mem.t k) => P k m1 m2 /\\ \n      E.eval_expr e1 m1 = false).\n    Proof.\n     intros P ? ? e1 e2 c1 c2 H1 H2 k.\n     destruct (H2 k).\n     destruct (@while_indR k (P k) x E0 e1 c1 E3 e2 c2).\n     intros; apply H1; trivial.\n     intros.\n     apply H.\n     split; trivial.\n     exists x0; intros.\n     apply H0; trivial.\n    Qed.\n\n    Lemma equiv_deno_eq : forall (P Q:mem_rel) c1 c2 c1' c2',\n     (forall k (m:Mem.t k), ([[ c1 ]]) E1 m == ([[ c1' ]]) E1 m) ->\n     (forall k (m:Mem.t k), ([[ c2 ]]) E2 m == ([[ c2' ]]) E2 m) ->\n     equiv P E1 c1' E2 c2' Q ->\n     equiv P E1 c1 E2 c2 Q.\n    Proof.\n     intros.\n     eapply equiv_trans_eq_mem_l with (P1 := Meq).\n     2: eapply equiv_trans_eq_mem_r with (P2 := Meq).\n     3: apply H1.\n     eapply equiv_strengthen.\n     2: apply equiv_eq_sem; intros; auto.\n     intros k m1 m2 (W1, W2); trivial.\n     eapply equiv_strengthen.\n     2: apply equiv_eq_sem; intros; auto.\n     intros k m1 m2 (W1, W2); trivial.\n     unfold refl_supMR2; intros; auto.\n     unfold refl_supMR2; intros; auto.\n    Qed.\n\n    Lemma equiv_while_false : forall (P Q:mem_rel) (e:E.expr T.Bool)  c,\n     (forall k (m1 m2:Mem.t k), P k m1 m2 -> \n      (Q k m1 m2 /\\ E.eval_expr e m1 = false /\\ \n       E.eval_expr e m2 = false)) ->\n     equiv P E1 [while e do c] E2 [while e do c] Q.\n    Proof.\n     intros.\n     apply equiv_deno_eq with \n      (c1' := [If e _then c ++ [while e do c] ]) \n      (c2' := [If e _then c ++ [while e do c] ]).\n     intros; apply deno_while.\n     intros; apply deno_while.\n     apply equiv_cond.\n     intro.\n     exists (fun m1 m2 => Munit (m1, m2)); intros.\n     destruct H0 as (H0 & H1 & H2).\n     apply H in H0.\n     decompose [and] H0.\n     rewrite H1 in H5.\n     discriminate.\n     eapply equiv_strengthen;[ | apply equiv_nil ].\n     intros.\n     apply H.\n     destruct H0 as (W1, _); trivial.\n     intros.\n     apply H in H0.\n     decompose [and] H0.\n     rewrite H3, H4; trivial.\n    Qed.\n\n    Lemma unroll_while_false : forall E (e:E.expr T.Bool) c k (m:Mem.t k) f n,\n     E.eval_expr e m = false ->\n     mu ([[ unroll_while e c n ]] E m) f == mu ([[ nil ]] E m) f.\n    Proof.\n     clear.\n     induction n; simpl; intros.\n     rewrite (deno_cond_elim E e nil nil m f).\n     rewrite H; simpl; trivial.\n     rewrite (deno_cond_elim E e _ _  m f).  \n     rewrite H; simpl; trivial.\n    Qed.\n\n    Lemma unroll_while_plus : forall E (e:E.expr T.Bool) c k (m:Mem.t k) f n1 n2,\n     mu ([[ unroll_while e c (n1 + n2) ]] E m) f == \n     mu ([[ (unroll_while e c n1) ++ (unroll_while e c n2) ]] E m) f.\n    Proof.\n     clear; split.\n     revert m.\n     induction n1; simpl; intros.\n     rewrite (deno_cons_elim E _ _ m).\n     rewrite Mlet_simpl.\n     rewrite (deno_cond_elim E e nil nil m _).\n     case_eq (E.eval_expr e m); intros;\n      rewrite deno_nil_elim; trivial.\n\n     rewrite (deno_cond_elim E e _ _ m _).\n     rewrite (deno_cons_elim E _ _ m).\n     rewrite Mlet_simpl.\n     rewrite (deno_cond_elim E e _ _ m _).\n     case_eq (E.eval_expr e m); intros.\n     rewrite deno_app_elim.\n     rewrite deno_app_elim.\n     apply mu_le_compat; trivial.\n     intro.\n     rewrite <- deno_app_elim; trivial.\n     rewrite deno_nil_elim.\n     rewrite deno_nil_elim.\n     clear IHn1.\n     destruct n2; simpl;\n      rewrite (deno_cond_elim E _ _ _ m), H, deno_nil_elim; trivial.\n\n     revert m.\n     induction n1; simpl; intros.\n     rewrite (deno_cons_elim E _ _ m).\n     rewrite Mlet_simpl.\n     rewrite (deno_cond_elim E e nil nil m _).\n     case_eq (E.eval_expr e m); intros;\n      rewrite deno_nil_elim; trivial.\n\n     rewrite (deno_cond_elim E e _ _ m _).\n     rewrite (deno_cons_elim E _ _ m).\n     rewrite Mlet_simpl.\n     rewrite (deno_cond_elim E e _ _ m _).\n     case_eq (E.eval_expr e m); intros.\n     rewrite deno_app_elim.\n     rewrite deno_app_elim.\n     apply mu_le_compat; trivial.\n     intro.\n     rewrite <- deno_app_elim; trivial.\n     rewrite deno_nil_elim.\n     rewrite deno_nil_elim.\n     clear IHn1.\n     destruct n2; simpl;\n      rewrite (deno_cond_elim E _ _ _ m), H, deno_nil_elim; trivial.\n    Qed.\n\n\n    Lemma deno_while_bad : forall e e' c E (k:nat) (m:Mem.t k),\n     ([[ [while e do c] ]]) E m ==\n     ([[ [while E.Eop O.Oand {e, !e'} do c; while e do c] ]]) E m.\n    Proof.\n     intros.\n     case_eq ( E.eval_expr (!e') m); intros.\n\n     split.\n\n     rewrite deno_while_unfold.\n\n     apply lub_le with (c:=cDistr (Mem.t k)); intros.\n\n     revert m H.\n     induction n; intros; simpl; intros. \n     rewrite (deno_cond_elim E e nil nil m).\n     unfold negP, negb.\n     case_eq ( E.eval_expr e m); intros; \n      rewrite deno_nil_elim, H0; simpl; trivial.\n     rewrite (deno_cons_elim E _ _  m x), Mlet_simpl, \n      deno_while_elim, deno_cond_elim.\n     simpl; unfold O.eval_op; simpl.\n     rewrite H0; simpl.\n     rewrite (deno_nil_elim E m), (deno_while_elim E e c m), \n      deno_cond_elim, H0, (deno_nil_elim E m); trivial.\n     rewrite (deno_cond_elim E e _ nil m).\n     case_eq ( E.eval_expr e m); intros.\n\n     rewrite (deno_cons_elim E _ _  m), Mlet_simpl,\n      (deno_while_elim E _ c m), deno_cond_elim.\n     simpl  E.eval_expr in *; unfold O.eval_op in *; simpl in *.\n     unfold negP; rewrite H, H0; simpl.\n\n     rewrite (deno_app_elim E c _ m ), (deno_app_elim E c _ m ).\n     apply mu_le_compat; trivial; intro m'.\n     case_eq ( negb (E.eval_expr e' m')); intros.\n     assert (W := IHn m' H1 x).\n     rewrite (deno_cons_elim E _ [while e do c] m') in W; trivial.\n\n     rewrite deno_while_elim, deno_cond_elim.\n     simpl  E.eval_expr in *; unfold O.eval_op in *; simpl in *.\n     rewrite H1, andb_false_r, (deno_nil_elim E m'), \n      (deno_while_unfold_elim E e c m').\n     eapply Ole_trans;[ | apply le_lub ].\n     simpl; trivial.\n\n     rewrite deno_nil_elim, (deno_cons_elim E _ _ m), Mlet_simpl,\n      deno_while_elim, deno_cond_elim.\n     simpl E.eval_expr; unfold O.eval_op; simpl; unfold negP.\n     rewrite H0; simpl.\n     rewrite (deno_nil_elim E m), (deno_while_elim E e c m), \n      deno_cond_elim, H0; simpl.\n     rewrite (deno_nil_elim E m); trivial.\n\n     Focus 2.\n     split; simpl; intros.\n     rewrite (deno_cons_elim E _ [while e do c]  m), Mlet_simpl, \n      (deno_while_elim E _ c m), (deno_cond_elim E _ _ _ m).\n     simpl  E.eval_expr in *; unfold O.eval_op in *; simpl in *.\n     rewrite H, andb_false_r, (deno_nil_elim E m); trivial.\n     rewrite (deno_cons_elim E _ [while e do c]  m), Mlet_simpl, \n      (deno_while_elim E _ c m), (deno_cond_elim E _ _ _ m).\n     simpl  E.eval_expr in *; unfold O.eval_op in *; simpl in *.\n     rewrite H, andb_false_r, (deno_nil_elim E m); trivial.\n\n     simpl; intros. \n     rewrite (deno_cons_elim E _ _  m), Mlet_simpl, \n      (deno_while_unfold_elim E _ c m).\n     apply lub_le; intros; simpl.\n     revert m H.\n     induction n; simpl; intros.\n     rewrite (deno_cond_elim E _ _ _ m).\n     simpl  E.eval_expr in *; unfold O.eval_op in *; simpl in *.\n     rewrite H; simpl.\n     rewrite (deno_while_elim E _ c m), (deno_cond_elim E _ _ _ m).\n     case_eq ( E.eval_expr e m); intros; simpl;\n      rewrite (deno_nil_elim E m);\n       unfold negP; rewrite H0, H; simpl; auto.\n     rewrite (deno_while_elim E _ c m), (deno_cond_elim E _ _ _ m), H0; auto.\n\n     rewrite (deno_while_elim E _ c m), (deno_cond_elim E _ _ _ m), \n      (deno_cond_elim E _ _ _ m).\n     simpl  E.eval_expr in *; unfold O.eval_op in *; simpl in *.\n     rewrite H; simpl.\n     case_eq ( E.eval_expr e m); intros; simpl.\n     rewrite (deno_app_elim E _ _ m), (deno_app_elim E _ _ m).\n     apply mu_le_compat; trivial; intro m'.\n     case_eq ( negb (E.eval_expr e' m')); intros. \n     apply IHn; auto.\n     rewrite unroll_while_false, deno_nil_elim.\n     unfold negP; rewrite H1; simpl.\n     rewrite andb_false_r; simpl; auto.\n     simpl  E.eval_expr in *; unfold O.eval_op in *; simpl in *.\n     rewrite H1, andb_false_r; trivial.\n     rewrite (deno_nil_elim E m), (deno_nil_elim E m).\n     unfold negP; rewrite H, H0; simpl.\n     rewrite (deno_while_elim E _ c m), (deno_cond_elim E _ _ _ m), H0, \n      (deno_nil_elim E m); trivial.\n    Qed.\n\n    Hypothesis bad_orcl : forall (t:T.type) (f:Proc.proc t),\n     PrSet.mem {| BProc.p_type := t; BProc.p_name := f |} PrOrcl ->\n     slossless_c E1 (proc_body E1 f) ->\n     slossless_c E2 (proc_body E2 f) ->\n     proc_params E1 f = proc_params E2 f ->\n     equiv ((notR (rel_pred1 bad1) /-\\ notR (rel_pred2 bad2)) /-\\ Inv /-\\ \n      (fun k m1 m2 =>  m1 =={ Vset_of_var_decl (proc_params E1 f) } m2))\n     E1 (proc_body E1 f) E2 (proc_body E2 f)\n     ((eqR (rel_pred1 bad1) (rel_pred2 bad2)) /-\\\n      ((notR (rel_pred1 bad1)) |-> \n       (Inv /-\\ kreq_mem Gadv /-\\ \n        (fun k m1 m2 =>\n         E.eval_expr (proc_res E1 f) m1 = E.eval_expr (proc_res E2 f) m2)))).\n\n    Lemma equiv_bad_inv : forall I c O,\n     WFAdv_c E1 I c O ->\n     (forall x, Vset.mem x I -> Var.is_local x) ->\n     slossless_c E1 c ->\n     slossless_c E2 c ->\n     equiv ((eqR (rel_pred1 bad1) (rel_pred2 bad2)) /-\\ \n      ((notR (rel_pred1 bad1)) |-> (Inv /-\\ (kreq_mem (Vset.union Gadv I)))))\n     E1 c E2 c \n     ((eqR (rel_pred1 bad1) (rel_pred2 bad2)) /-\\ \n      ((notR (rel_pred1 bad1)) |-> (Inv /-\\ kreq_mem (Vset.union Gadv O)))).\n    Proof.\n     induction 1 using WFAdv_c_prop with \n      (P0 := fun I i O (_:WFAdv_i E1 I i O)  =>\n       (forall x, Vset.mem x I -> Var.is_local x) ->\n       slossless_i E1 i -> slossless_i E2 i ->\n       equiv ((eqR (rel_pred1 bad1) (rel_pred2 bad2)) /-\\ \n        ((notR (rel_pred1 bad1)) |->\n         (Inv /-\\ kreq_mem (Vset.union Gadv I))))\n       E1 [i] E2 [i] \n       ((eqR (rel_pred1 bad1) (rel_pred2 bad2)) /-\\ \n        ((notR (rel_pred1 bad1)) |-> \n         (Inv /-\\ kreq_mem (Vset.union Gadv O))))); \n      intros I_local lossless1 lossless2; intros.\n\n     (* nil *)\n     apply equiv_nil.\n\n     (* cons *)\n     inversion lossless1.\n     inversion lossless2.\n     eapply equiv_cons; eauto using WFAdv_i_local.\n\n     (* assign *)\n     eapply equiv_strengthen;[ | apply equiv_assign].\n     intros k m1 m2 ((H1,H2),H3); unfold kreq_mem in *.\n     destruct x.\n\n     assert (HX1:m1 =={ X1}m1 {!v <-- E.eval_expr e m1!}).\n     red; intros; rewrite Mem.get_upd_diff; trivial; intro.\n     assert (W: Var.is_global x) by auto with set.\n     contradict H.\n     apply VsetP.disjoint_mem_not_mem with\n      (1:=VsetP.disjoint_sym disjoint_Orcl1).\n     generalize w; rewrite <- H0 in *; destruct x; auto.\n\n     assert (HX2:m2 =={ X2}m2 {!v <-- E.eval_expr e m2!}).\n     red; intros; rewrite Mem.get_upd_diff; trivial; intro.\n     assert (W: Var.is_global x) by auto with set.\n     contradict H.\n     apply VsetP.disjoint_mem_not_mem with\n      (1:=VsetP.disjoint_sym disjoint_Orcl2).\n     generalize w; rewrite <- H0 in *; destruct x; auto.\n\n     unfold eqR, impR, andR in *; split.\n     split; intros.\n     revert H.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     case_eq (Var.is_global v); intro.\n     apply w in H.\n     intros.\n     rewrite depend_only_fv_expr_subset with (m2 := m2) (X :=  fv_expr bad2_expr).\n     apply H1.\n     unfold rel_pred1, bad1, EPp.\n     rewrite depend_only_fv_expr_subset with (m2 :=  (m1 {!v <-- E.eval_expr e m1!})) (X :=  fv_expr bad1_expr); auto with set.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H5 in H4.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H4.\n     auto.\n     auto with set.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H5 in H4.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad2_adv.\n     apply H4.\n     auto.\n     auto with set.\n     unfold bad1, bad2, EPp; simpl.\n     intros.\n     rewrite depend_only_fv_expr_subset with (m2 := m2) (X :=  fv_expr bad2_expr).\n     apply H1.\n     unfold rel_pred1, bad1, EPp.\n     rewrite depend_only_fv_expr_subset with (m2 :=  (m1 {!v <-- E.eval_expr e m1!})) (X :=  fv_expr bad1_expr); auto with set.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H5 in H4.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H4.\n     auto.\n     auto with set.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H5 in H4.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad2_adv.\n     apply H4.\n     auto.\n     revert H.\n     unfold rel_pred1, rel_pred2.\n     case_eq (Var.is_global v); intro.\n     apply w in H.\n     unfold bad1, bad2, EPp; simpl.\n     intros.\n     rewrite depend_only_fv_expr_subset with (m2 := m1) (X :=  fv_expr bad1_expr).\n     apply H2.\n     unfold rel_pred2, bad2, EPp.\n     rewrite depend_only_fv_expr_subset with (m2 := (m2 {!v <-- E.eval_expr e m2!})) (X :=  fv_expr bad2_expr); auto with set.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H5 in H4.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad2_adv.\n     apply H4.\n     auto.\n     auto with set.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H5 in H4.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H4.\n     auto.\n     auto with set.\n     unfold bad1, bad2, EPp; simpl.\n     intros.\n     rewrite depend_only_fv_expr_subset with (m2 := m1) (X :=  fv_expr bad1_expr).\n     apply H2.\n     unfold rel_pred2, bad2, EPp.\n     rewrite depend_only_fv_expr_subset with (m2 := (m2 {!v <-- E.eval_expr e m2!})) (X :=  fv_expr bad2_expr); auto with set.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H5 in H4.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad2_adv.\n     apply H4.\n     auto.\n     auto with set.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H5 in H4.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H4.\n     auto.\n\n     intros.\n     destruct H3.\n     intro; elim H.\n     revert H0.\n     unfold rel_pred1.\n     unfold bad1, EPp; simpl.\n     case_eq (Var.is_global v); intro.\n     apply w in H0.\n     intros.\n     rewrite depend_only_fv_expr_subset with (m2 := m1) (X :=  fv_expr bad1_expr).\n     apply H3.\n     auto with set.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H5 in H4.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H4.\n     auto.\n     intros.\n     rewrite depend_only_fv_expr_subset with (m2 := m1) (X :=  fv_expr bad1_expr).\n     apply H3.\n     auto with set.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H5 in H4.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H4.\n     auto.\n     split.\n     apply inv_dep with m1 m2; auto.\n     erewrite equiv_WFRead;[ | | | | apply H3 ]; trivial; \n      auto with set.\n     destruct v; apply equiv_WFWrite; trivial.\n     rewrite Gcomm_empty; auto with set.\n\n     (* random *)\n     apply equiv_case1 with (rel_pred1 bad1); auto.\n     apply equiv_weaken with \n      ((rel_pred1 bad1) /-\\ (rel_pred2 bad2)).\n     intros k m1 m2 (H1, H2); split.\n     split; intro; tauto.\n     intro; elim H; trivial.\n     apply equiv_rel_pred with bad1 bad2; trivial; intros.\n     apply slossless_lossless     .\n     constructor; auto.\n     apply slossless_nil.\n     apply lossless_nil.\n     apply slossless_lossless     .\n     constructor; auto.\n     apply slossless_nil.\n     apply lossless_nil.\n     eapply a_preserve_bad; auto.\n     3: apply bad1_adv.\n     red; intros.\n     unfold bad1, EPp in *.\n     rewrite depend_only_fv_expr_subset with (m2 := m0) (X :=  fv_expr bad1_expr); eauto.\n     auto with set.\n     auto.\n     eapply GA_cons.\n     apply GA_random; eauto.\n     apply GA_nil.\n     eapply a_preserve_bad; auto.\n     3: apply bad2_adv.\n     red; intros.\n     unfold bad2, EPp in *.\n     rewrite depend_only_fv_expr_subset with (m2 := m0) (X :=  fv_expr bad2_expr); eauto.\n     auto with set.\n     auto.\n     eapply WFAdv_c_trans; eauto.\n     eapply GA_cons.\n     apply GA_random; eauto.\n     apply GA_nil.\n     destruct H as (((H1, H2) , H3), H4).\n     split; auto.\n     apply H1; auto.\n     destruct (bad1_dec m1 m1); auto.\n     destruct (bad2_dec m2 m2); auto.\n     eapply equiv_strengthen;[ | apply equiv_random].\n     intros k m1 m2 ((H1, H2),H4); unfold kreq_mem in *.\n     split. \n     unfold eq_support.\n     apply EqObs_d_fv_expr.\n     red.\n     unfold WFReadD in w0; intros.\n     destruct (w0 _ H); auto with set.\n     destruct H2; auto with set.\n     destruct H0.\n     destruct H2; auto with set.\n     rewrite Gcomm_empty in H0. \n     elimtype False; apply (Vset.empty_spec H0).\n\n     intros ? ?.\n     destruct x.\n     assert (HX1:m1 =={X1}m1 {!v <-- D_points (DE.discrete_support d m1) i!}).\n     red; intros; rewrite Mem.get_upd_diff; trivial; intro.\n     assert (W:Var.is_global x) by auto with set.\n     contradict H0.\n     apply VsetP.disjoint_mem_not_mem with\n      (1:=VsetP.disjoint_sym disjoint_Orcl1).\n     generalize w; rewrite <- H3 in *; destruct x; auto.\n\n     assert (HX2:m2 =={X2}m2 {!v <-- D_points (DE.discrete_support d m1) i!}).  \n     red; intros; rewrite Mem.get_upd_diff; trivial; intro.\n     assert (W:Var.is_global x) by auto with set.\n     contradict H0.\n     apply VsetP.disjoint_mem_not_mem with\n      (1:=VsetP.disjoint_sym disjoint_Orcl2).\n     generalize w; rewrite <- H3 in *; destruct x; auto.\n     unfold eqR, impR, andR in *; split.\n     destruct H1.\n     split; intros.\n     case_eq (Var.is_global v); intro.\n     apply w in H5.\n     unfold rel_pred1, rel_pred2, bad1, bad2, EPp in *.\n     erewrite depend_only_fv_expr_subset.\n     apply H0.\n     erewrite depend_only_fv_expr_subset.\n     apply H3.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H7 in H6.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H6.\n     auto.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H7 in H6.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad2_adv.\n     apply H6.\n     auto.\n     unfold rel_pred1, rel_pred2, bad1, bad2, EPp in *.\n     erewrite depend_only_fv_expr_subset.\n     apply H0.\n     erewrite depend_only_fv_expr_subset.\n     apply H3.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H7 in H6.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H6.\n     auto.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H7 in H6.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad2_adv.\n     apply H6.\n     auto.\n     case_eq (Var.is_global v); intro.\n     apply w in H5.\n     unfold rel_pred1, rel_pred2, bad1, bad2, EPp in *.\n     erewrite depend_only_fv_expr_subset.\n     apply H1.\n     erewrite depend_only_fv_expr_subset.\n     apply H3.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H7 in H6.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad2_adv.\n     apply H6.\n     auto.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H7 in H6.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H6.\n     auto.\n     unfold rel_pred1, rel_pred2, bad1, bad2, EPp in *.\n     erewrite depend_only_fv_expr_subset.\n     apply H1.\n     erewrite depend_only_fv_expr_subset.\n     apply H3.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H7 in H6.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad2_adv.\n     apply H6.\n     auto.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite Mem.get_upd_diff; trivial.\n     intro.\n     rewrite <- H7 in H6.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H6.\n     auto.\n     intros.\n     revert H.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     intros.\n     split.\n     apply inv_dep with m1 m2; auto.\n     apply H2; auto.\n     destruct v; apply equiv_WFWrite; trivial.\n     apply H2; auto.\n     apply H2; auto.\n\n     (* cond *)\n     apply equiv_case1 with (rel_pred1 bad1); auto.\n     apply equiv_weaken with ((rel_pred1 bad1) /-\\ (rel_pred2 bad2)).\n     intros k m1 m2 (H1, H2); split.\n     split; intro; tauto.\n     intro; elim H3; trivial.\n     apply equiv_rel_pred with bad1 bad2; trivial; intros.\n     apply slossless_lossless     .\n     constructor; auto.\n     apply slossless_nil.\n     apply lossless_nil.\n     apply slossless_lossless     .\n     constructor; auto.\n     apply slossless_nil.\n     apply lossless_nil.\n     eapply a_preserve_bad; auto.\n     rewrite depend_only_rel_pred1 with (X2 := Vset.empty); eauto.\n     3: apply bad1_adv.\n     red; intros.\n     unfold rel_pred1, bad1, EPp in *.\n     erewrite depend_only_fv_expr_subset with (m2 := m1) (X :=  fv_expr bad1_expr); eauto.\n     auto with set.\n     auto.\n     eapply GA_cons.\n     apply GA_cond; eauto.\n     apply GA_nil.\n     eapply a_preserve_bad; auto.\n     rewrite depend_only_rel_pred2 with (X1 := Vset.empty); eauto.\n     3: apply bad2_adv.\n     red; intros.\n     unfold rel_pred2, bad2, EPp in *.\n     rewrite depend_only_fv_expr_subset with (m2 := m2) (X :=  fv_expr bad2_expr); eauto.\n     auto with set.\n     auto.\n     auto with set.     \n     eapply WFAdv_c_trans; eauto.\n     eapply GA_cons.\n     apply GA_cond; eauto.\n     apply GA_nil.\n     destruct H1 as (((H1, H2) , H3), H4).\n     split; auto.\n     apply H1; auto.\n     destruct (bad1_dec m1 m1); auto.\n     destruct (bad2_dec m2 m2); auto.\n     apply equiv_cond.\n     eapply equiv_strengthen; \n      [ | eapply equiv_weaken; [ | apply IHWFAdv_c1] ]; trivial.\n     intros k m1 m2 ((W1,W2) , _); trivial.\n     intros.\n     destruct H1.\n     split; trivial.\n     intro.\n     destruct H2; trivial.\n     split; trivial.\n     eapply req_mem_weaken; eauto.\n     apply VsetP.subset_union_ctxt; auto with set.     \n     inversion lossless1; trivial.\n     inversion lossless2; trivial.\n     eapply equiv_strengthen; \n      [ | eapply equiv_weaken; [ | apply IHWFAdv_c2] ]; trivial.\n     intros k m1 m2 ((W1,W2) , _); trivial.\n     intros.\n     destruct H1.\n     split; trivial.\n     intro.\n     destruct H2; trivial.\n     split; trivial.\n     eapply req_mem_weaken; eauto.\n     apply VsetP.subset_union_ctxt; auto with set.\n     inversion lossless1; trivial.\n     inversion lossless2; trivial.\n     intros k m1 m2 ((H1, H2), H3).\n     destruct H2 as [H4 H5]; trivial.\n     eapply equiv_WFRead;[ apply w | | | apply H5 ]; auto with arith.\n     rewrite Gcomm_empty; auto with set.\n     auto with set.\n\n     (* while *)\n     apply equiv_deno_eq with \n      (c1' := [while (E.Eop O.Oand {e, ! bad1_expr}) do c; \n       while e do c])\n      (c2' := [while (E.Eop O.Oand {e, ! bad2_expr}) do c; \n       while e do c] ).\n     intros; rewrite deno_while_bad; trivial.\n     intros; rewrite deno_while_bad; trivial.\n\n     apply equiv_cons with \n      ((eqR (rel_pred1 bad1) (rel_pred2 bad2) /-\\\n       (~- rel_pred1 bad1 |-> \n        Inv /-\\ kreq_mem (Vset.union Gadv I))) /-\\ \n      (fun k m1 m2 => \n       E.eval_expr ( E.Eop O.Oand {e, !bad1_expr} ) m1 = false)).\n\n     eapply equiv_weaken;[ | apply equiv_while_ind ].\n\n     intros.\n     revert H0.\n     simpl; unfold O.eval_op; simpl.\n     intros ((H0, H1), H2). \n     split; trivial.\n     split; trivial.\n\n     intros k m1 m2 ((H0, H1), H2).\n     simpl; unfold O.eval_op; simpl.\n     destruct (decMR_EP1 bad1_expr m1 m2).\n     rewrite e0.\n     apply H0 in e0.\n     rewrite e0.\n     simpl.\n     repeat rewrite andb_false_r; trivial.\n\n     destruct H2; trivial.\n     assert ((~- rel_pred2 bad2) k m1 m2).\n     intro; apply n; auto.\n     apply H1; trivial.\n     apply is_true_negb in n.\n     apply is_true_negb in H4.\n     rewrite n, H4.\n     repeat rewrite andb_true_r.\n     erewrite equiv_WFRead.\n     reflexivity.\n     apply w.\n     2: apply VsetP.subset_refl.\n     rewrite Gcomm_empty; auto with set.\n     apply H3.\n\n     eapply equiv_strengthen; \n      [ | eapply equiv_weaken; [ | apply IHWFAdv_c ] ]; auto.\n     intros k m1 m2 (W1, W2); trivial.\n     intros k m1 m2 (W1, W2); trivial.\n     split; trivial.\n     intro; split.\n     apply W2; trivial.\n     red; intros.\n     eapply req_mem_weaken.\n     2: apply W2; trivial.\n     apply VsetP.subset_union_ctxt; auto with set.\n     eapply WFAdv_c_subset; eauto.\n     inversion lossless1; trivial.\n     inversion lossless2; trivial.\n\n     simpl; unfold O.eval_op; simpl.\n     apply equiv_case1 with (EP1 bad1_expr); auto.\n\n     eapply equiv_weaken with ((rel_pred1 bad1) /-\\ (rel_pred2 bad2)).\n     intros k m1 m2 (W1, W2).\n     split.\n     split; intro; auto.\n     intro.\n     elim H0; trivial.\n\n     apply equiv_rel_pred with bad1 bad2.\n     inversion lossless1; trivial.\n     inversion lossless2; trivial.\n\n     intros.\n     eapply a_preserve_bad; auto.\n     rewrite depend_only_rel_pred1 with (X2 := Vset.empty); eauto.\n     3: apply bad1_adv.\n     red; intros.\n     unfold rel_pred1, bad1, EPp in *.\n     rewrite depend_only_fv_expr_subset with (m2 := m1) (X :=  fv_expr bad1_expr); eauto.\n     auto with set.\n     auto.\n     eapply GA_cons.\n     eapply GA_while; eauto.\n     apply GA_nil.\n     eapply a_preserve_bad; auto.\n     rewrite depend_only_rel_pred2 with (X1 := Vset.empty); eauto.\n     3: apply bad2_adv.\n     red; intros.\n     unfold rel_pred2, bad2, EPp in *.\n     rewrite depend_only_fv_expr_subset with (m2 := m2) (X :=  fv_expr bad2_expr); eauto.\n     auto with set.\n     auto.\n     eapply WFAdv_c_trans; eauto.\n     eapply GA_cons.\n     eapply GA_while; eauto.\n     apply GA_nil.\n\n     intros k m1 m2 (((W1, _) , _), W2).\n     split.\n     apply W2.\n     apply W1.\n     apply W2.\n     intros.\n     apply bad1_dec with (m2 := m1).\n     intros.\n     apply bad2_dec with (m1 := m2).\n\n     apply equiv_while_false.\n     intros k m1 m2 ((W1, W2), W3).\n     split; trivial.\n\n     assert (  E.eval_expr e m1 = E.eval_expr e m2).\n     eapply equiv_WFRead;[ apply w | | | apply W1 ]; \n      auto with arith.\n     rewrite Gcomm_empty; auto with set.\n     auto with set.\n     rewrite <- H0.\n     apply andb_false_elim in W2.\n     destruct W2.\n     auto.\n     unfold notR, EP1 in W3.\n     apply is_true_negb in W3.\n     rewrite e0 in W3.\n     discriminate.\n\n     (* Call Orcl *)\n     apply equiv_case1 with (rel_pred1 bad1); auto.\n     apply equiv_weaken with \n      ((rel_pred1 bad1) /-\\ (rel_pred2 bad2)).\n     intros k m1 m2 (H1, H2); split.\n     split; intro; tauto.\n     intro H3; elim H3; trivial.\n     apply equiv_rel_pred with bad1 bad2; trivial; intros.\n     apply slossless_lossless.\n     constructor; auto.\n     apply slossless_nil.\n     apply lossless_nil.\n     apply slossless_lossless.\n     constructor; auto.\n     apply slossless_nil.\n     apply lossless_nil.\n     eapply a_preserve_bad; auto.\n     3: apply bad1_adv.\n     red; intros.\n     unfold rel_pred1, bad1, EPp in *.\n     rewrite depend_only_fv_expr_subset with (m2 := m0) (X :=  fv_expr bad1_expr); eauto.\n     auto with set.\n     auto.\n     eapply GA_cons.\n     eapply GA_call_orcl; eauto.\n     apply GA_nil.\n     eapply a_preserve_bad; auto.\n     3: apply bad2_adv.\n     red; intros.\n     unfold rel_pred2, bad2, EPp in *.\n     rewrite depend_only_fv_expr_subset with (m2 := m0) (X := fv_expr bad2_expr); eauto.\n     auto with set.\n     auto.\n     eapply WFAdv_c_trans; eauto.\n     eapply GA_cons.\n     eapply GA_call_orcl; eauto.\n     apply GA_nil.\n     destruct H as (((H1, H2) , H3), H4).\n     split; auto.\n     apply H1; auto.\n     destruct (bad1_dec m1 m1); auto.\n     destruct (bad2_dec m2 m2); auto.\n     eapply equiv_call; intros;[ | | apply bad_orcl; trivial].\n\n     (** Init *)\n     assert (W:forall t (x:Var.var t),  Vset.mem x \n      (Vset_of_var_decl (proc_params E1 f)) -> Var.is_local x).\n     intros; apply Vset_of_var_decl_ind with \n      (P:= fun t (x:Var.var t) => Var.is_local x) (lv:= proc_params E1 f); auto.\n     intros; change (Var.vis_local x1).\n     apply proc_params_local with E1 t f; trivial.\n     destruct H as (((H1,H2) & H3) & H4).\n     assert (HX1:m1 =={ X1}init_mem E1 f args m1).\n     red; intros; rewrite init_mem_global; trivial.\n     apply inv_global; rewrite VsetP.union_spec; auto.\n     assert (HX2:m2 =={ X2}init_mem E2 f args m2).\n     red; intros; rewrite init_mem_global; trivial.\n     apply inv_global; rewrite VsetP.union_spec; auto.\n     split.\n     split.\n     intro.\n     elim H4.\n     revert H.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     intros.\n     erewrite depend_only_fv_expr_subset.\n     apply H.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite init_mem_global; trivial.\n     auto.\n     intro Heq; elim H4.\n     revert Heq.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     erewrite depend_only_fv_expr_subset.\n     intros.\n     apply H2.\n     apply Heq.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite init_mem_global; trivial.\n     auto.\n     split.\n     eapply inv_dep; [ | | apply H3]; auto.\n     red; intros.\n\n     rewrite init_mem_eq2 with (E2 := E2) (a2 := args); trivial.\n     apply init_mem_local; auto.\n     generalize args w.\n     generalize (Proc.targs f). induction args0; simpl; auto; intros.\n     rewrite IHargs0; auto.\n     rewrite (@equiv_WFRead Gadv a p I k m1 m2); auto.\n     rewrite Gcomm_empty; auto with set.\n     auto with set.\n     apply H3; trivial.\n     apply Eq_orcl_params_12; auto.\n\n     (** Post *)\n     destruct H as (((H1,H2) & H3) & H4).\n     destruct H0 as ((H5, H6), H7).\n\n     assert (HX1:m1' =={ X1}return_mem E1 x f m1 m1').\n     red; intros; rewrite return_mem_global; trivial.\n     assert (W: Var.is_global x0) by auto with set.\n     contradict H.\n     apply VsetP.disjoint_mem_not_mem with\n      (1:=VsetP.disjoint_sym disjoint_Orcl1).\n     generalize w; rewrite <- H in *; destruct x; auto.\n     auto with set.\n\n     assert (HX2:m2' =={ X2}return_mem E2 x f m2 m2').\n     red; intros; rewrite return_mem_global; trivial.\n     assert (W: Var.is_global x0) by auto with set.\n     contradict H.\n     apply VsetP.disjoint_mem_not_mem with\n      (1:=VsetP.disjoint_sym disjoint_Orcl2).\n     generalize w; rewrite <- H in *; destruct x; auto.\n     auto with set.\n\n     split.\n     split; intro.\n\n     revert H.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     intros.\n     erewrite depend_only_fv_expr_subset.\n     apply H5.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     erewrite depend_only_fv_expr_subset.\n     apply H.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite return_mem_global; trivial.\n     intro.\n     rewrite <- H8 in H0.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H0.\n     auto.\n     auto with set.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite return_mem_global; trivial.\n     intro.\n     rewrite <- H8 in H0.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad2_adv.\n     apply H0.\n     auto.\n     auto with set.\n\n     revert H.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     intros.\n     erewrite depend_only_fv_expr_subset.\n     apply H6.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     erewrite depend_only_fv_expr_subset.\n     apply H.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite return_mem_global; trivial.\n     intro.\n     rewrite <- H8 in H0.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad2_adv.\n     apply H0.\n     auto.\n     auto with set.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite return_mem_global; trivial.\n     intro.\n     rewrite <- H8 in H0.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H0.\n     auto.\n     auto with set.\n\n     intro.\n     destruct H7.\n     intro; elim H.\n     revert H0.\n     unfold rel_pred1.\n     unfold bad1, EPp; simpl.\n     intros.\n     erewrite depend_only_fv_expr_subset.\n     apply H0.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite return_mem_global; trivial.\n     intro.\n     rewrite <- H8 in H7.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H7.\n     auto.\n     auto with set.\n     split.\n     eapply inv_dep; [ | | apply H0]; auto.\n     red; intros.\n     red; intros.\n     destruct (Vset.ET.eq_dec x x0).\n     inversion e.\n     repeat rewrite return_mem_dest.\n     apply H7.\n     apply Vset.union_correct in H8; destruct H8.\n     repeat rewrite return_mem_global; auto with set.\n     apply H7; auto.\n\n     assert (Vset.mem x0 I).\n     unfold add_read in H8; destruct (Var.is_global x); auto.\n     rewrite VsetP.add_spec in H8; destruct H8; trivial.\n     elim (n H8).\n     repeat rewrite return_mem_local; auto.\n     apply H3; auto with set.\n     inversion lossless1.\n     inversion H3.\n     trivial.\n     inversion lossless2.\n     inversion H3.\n     trivial.\n     apply Eq_orcl_params_12.\n     trivial.\n\n     (* Call Adv *)\n     apply equiv_case1 with (rel_pred1 bad1); auto.\n     apply equiv_weaken with ((rel_pred1 bad1) /-\\ (rel_pred2 bad2)).\n     intros k m1 m2 (H1, H2); split.\n     split; intro; tauto.\n     intro H3; elim H3; trivial.\n     apply equiv_rel_pred with bad1 bad2; trivial; intros.\n     apply slossless_lossless     .\n     constructor; auto.\n     apply slossless_nil.\n     apply lossless_nil.\n     apply slossless_lossless     .\n     constructor; auto.\n     apply slossless_nil.\n     apply lossless_nil.\n     eapply a_preserve_bad; auto.\n     rewrite depend_only_rel_pred1 with (X2 := Vset.empty); eauto.\n     3: apply bad1_adv.\n     red; intros.\n     unfold rel_pred1, bad1, EPp in *.\n     rewrite depend_only_fv_expr_subset with (m2 := m1) (X :=  fv_expr bad1_expr); eauto.\n     auto with set.\n     auto.\n     auto with set.\n     eapply GA_cons.\n     eapply GA_call_adv; eauto.\n     apply GA_nil.\n     eapply a_preserve_bad; auto.\n     rewrite depend_only_rel_pred2 with (X1 := Vset.empty); eauto.\n     3: apply bad2_adv.\n     red; intros.\n     unfold rel_pred2, bad2, EPp in *.\n     rewrite depend_only_fv_expr_subset with (m2 := m2) (X :=  fv_expr bad2_expr); eauto.\n     auto with set.\n     auto.\n     auto with set.\n     eapply WFAdv_c_trans; eauto.\n     eapply GA_cons.\n     eapply GA_call_adv; eauto.\n     apply GA_nil.\n     destruct H0 as (((H1, H2) , H3), H4).\n     split; auto.\n     apply H1; auto.\n     destruct (bad1_dec m1 m1); auto.\n     destruct (bad2_dec m2 m2); auto.\n\n     destruct (Eq_adv_decl_12 f) as (Heq1, (Heq2, Heq3)); trivial.\n\n     assert (W:forall t (x:Var.var t),  Vset.mem x \n      (Vset_of_var_decl (proc_params E1 f)) -> Var.is_local x).\n     intros; apply Vset_of_var_decl_ind with \n      (P:= fun t (x:Var.var t) => Var.is_local x) (lv:= proc_params E1 f); auto.\n     intros; change (Var.vis_local x1).\n     apply proc_params_local with E1 t f; trivial.\n     assert (W0:forall x, Vset.mem x \n      (Vset_of_var_decl (proc_params E1 f)) -> Var.is_local x). \n     intros (t0,x0); auto.\n\n     eapply equiv_call.\n     3: rewrite <- Heq2; apply IHWFAdv_c; auto.\n     intros.\n     destruct H0 as (((H1,H2) & H3) & H4).\n     assert (HX1:m1 =={ X1}init_mem E1 f args m1).\n     red; intros; rewrite init_mem_global; trivial.\n     apply inv_global; rewrite VsetP.union_spec; auto.\n     assert (HX2:m2 =={ X2}init_mem E2 f args m2).\n     red; intros; rewrite init_mem_global; trivial.\n     apply inv_global; rewrite VsetP.union_spec; auto.\n     split.\n     split.\n     intro.\n     elim H4.\n     revert H.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     intros.\n     erewrite depend_only_fv_expr_subset.\n     apply H0.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite init_mem_global; trivial.\n     auto.\n     intro Heq; elim H4.\n     revert Heq.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     erewrite depend_only_fv_expr_subset.\n     intros.\n     apply H2.\n     apply Heq.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite init_mem_global; trivial.\n     auto.\n     split.\n     eapply inv_dep; [ | | apply H3]; auto.\n     red; red; intros.\n     rewrite (init_mem_eq2 E1 E2 f args args m1 Heq1); trivial.\n     rewrite VsetP.union_spec in H5; destruct H5.\n     repeat rewrite init_mem_global; auto with set.\n     apply H3; trivial; auto with set.\n     apply init_mem_local; auto.\n     generalize args w0.\n     generalize (Proc.targs f). induction args0; simpl; auto; intros.\n     rewrite IHargs0; auto.\n     rewrite (@equiv_WFRead Gadv a p I k m1 m2); auto with set.\n     rewrite Gcomm_empty; auto with set.\n     apply H3; trivial.\n\n     intros k m1 m1' m2 m2' (((H1, H2), H3), H4) ((H5, H6), H7).\n\n     assert (HX1:m1' =={ X1}return_mem E1 x f m1 m1').\n     red; intros; rewrite return_mem_global; trivial.\n     assert (Var.is_global x0) by auto with set.\n     contradict H0.\n     apply VsetP.disjoint_mem_not_mem with\n      (1:=VsetP.disjoint_sym disjoint_Orcl1).\n     generalize w; rewrite <- H0 in *; destruct x; auto.\n     auto with set.\n     assert (HX2:m2' =={ X2}return_mem E2 x f m2 m2').\n     red; intros; rewrite return_mem_global; trivial.\n     assert (Var.is_global x0) by auto with set.\n     contradict H0.\n     apply VsetP.disjoint_mem_not_mem with\n      (1:=VsetP.disjoint_sym disjoint_Orcl2).\n     generalize w; rewrite <- H0 in *; destruct x; auto.\n     auto with set.\n\n     split.\n     split; intro.\n\n     revert H.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     intros.\n     erewrite depend_only_fv_expr_subset.\n     apply H5.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     erewrite depend_only_fv_expr_subset.\n     apply H0.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite return_mem_global; trivial.\n     intro.\n     rewrite <- H9 in H8.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H8.\n     auto.\n     auto with set.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite return_mem_global; trivial.\n     intro.\n     rewrite <- H9 in H8.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad2_adv.\n     apply H8.\n     auto.\n     auto with set.\n\n     revert H0.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     intros.\n     erewrite depend_only_fv_expr_subset.\n     apply H6.\n     unfold rel_pred1, rel_pred2.\n     unfold bad1, bad2, EPp; simpl.\n     erewrite depend_only_fv_expr_subset.\n     apply H0.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite return_mem_global; trivial.\n     intro.\n     rewrite <- H9 in H8.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad2_adv.\n     apply H8.\n     auto.\n     auto with set.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite return_mem_global; trivial.\n     intro.\n     rewrite <- H9 in H8.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H8.\n     auto.\n     auto with set.\n\n     intro.\n     destruct H7.\n     intro; elim H0.\n     revert H7.\n     unfold rel_pred1.\n     unfold bad1, EPp; simpl.\n     intros.\n     erewrite depend_only_fv_expr_subset.\n     apply H7.\n     apply VsetP.subset_refl.\n     red; intros.\n     rewrite return_mem_global; trivial.\n     intro.\n     rewrite <- H9 in H8.\n     eapply VsetP.disjoint_mem_not_mem.\n     apply bad1_adv.\n     apply H8.\n     auto.\n     auto with set.\n     split.\n     eapply inv_dep; [ | | apply H7]; auto.\n     red; red; intros.\n\n     destruct (Var.eq_dec x x0).\n     inversion e; simpl.\n     repeat rewrite return_mem_dest.\n     rewrite <- Heq3.\n     apply equiv_WFRead with (IA:= Gadv) (1 := w); auto with set.\n     rewrite Gcomm_empty; auto with set.\n     rewrite VsetP.union_spec in H9; destruct H9.\n     repeat rewrite return_mem_global; auto with set.\n     assert (Vset.mem x0 I). \n     unfold add_read in H9; destruct (Var.is_global x); auto.\n     rewrite VsetP.add_spec in H9; destruct H9; trivial.\n     elim (n1 H9).\n     repeat rewrite return_mem_local; auto. \n     apply H3; auto with set.\n\n     inversion lossless1; subst.\n     apply inj_pair2_eq_dec in H4; subst; trivial.\n     intros.\n     generalize (T.eqb_spec x0 y).\n     case (T.eqb x0 y); auto.\n     rewrite Heq2.\n     inversion lossless2; subst.\n     apply inj_pair2_eq_dec in H4; subst; trivial.\n     intros.\n     generalize (T.eqb_spec x0 y).\n     case (T.eqb x0 y); auto.\n    Qed.\n\n   End EQ_OBS_INV.\n\n  End UPTO2.\n\n End WF_ADV.\n\n Hint Constructors WFAdv_c WFAdv_i.\n \n Lemma WFAdv_subset : forall PrOrcl PrPriv X Y Gcomm E I c O,\n  X [<=] Y ->\n  WFAdv_c PrOrcl PrPriv X Gcomm E I c O ->\n  WFAdv_c PrOrcl PrPriv Y Gcomm E I c O.\n Proof.\n  intros; induction H0 using WFAdv_c_prop with\n   (P0:=fun I i O H => WFAdv_i PrOrcl PrPriv Y Gcomm E I i O).\n  auto.\n  eauto.\n\n  constructor.\n  intro; apply Vset.subset_correct with X; auto.\n  intros y Hy; decompose [or] (w0 y Hy); auto.\n  right; left; apply Vset.subset_correct with X; auto.\n\n  constructor.\n  intro; apply Vset.subset_correct with X; auto.\n  intros y Hy; decompose [or] (w0 y Hy); auto.\n  right; left; apply Vset.subset_correct with X; auto.\n \n  constructor; auto.\n  intros y Hy; decompose [or] (w y Hy); auto.\n  right; left; apply Vset.subset_correct with X; auto.\n\n  apply GA_while with O.\n  intros y Hy; decompose [or] (w y Hy); auto.\n  right; left; apply Vset.subset_correct with X; auto.\n  trivial.\n\n  apply GA_call_orcl; trivial.\n  intros t0 e H0 y Hy; decompose [or] (w t0 e H0 y Hy); auto.\n  right; left; apply Vset.subset_correct with X; auto.\n  intro; apply Vset.subset_correct with X; auto.\n\n  apply GA_call_adv with O; eauto.\n  intros y Hy; decompose [or] (w y Hy); auto.\n  right; left; apply Vset.subset_correct with X; auto.\n  intros t0 e H1 y Hy; decompose [or] (w0 t0 e H1 y Hy); auto.\n  right; left; apply Vset.subset_correct with X; auto.\n  intro; apply Vset.subset_correct with X; auto.  \n Qed.\n \nEnd Make.\n", "meta": {"author": "initc3", "repo": "certipriv", "sha": "95e089a46715ebb5931eb54e0828dd20e70dcd58", "save_path": "github-repos/coq/initc3-certipriv", "path": "github-repos/coq/initc3-certipriv/certipriv-95e089a46715ebb5931eb54e0828dd20e70dcd58/Semantics/Adversary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2201135407408466}}
{"text": "(**\nSimSoC-Cert, a toolkit for generating certified processor simulators.\n\nSee the COPYRIGHTS and LICENSE files.\n\nFormalization of the ARM architecture version 6 following the:\n\nARM Architecture Reference Manual, Issue I, July 2005.\n\nPage numbers refer to ARMv6.pdf.\n\nConfiguration of a ARM processor (IMPLEMENTATION DEFINED parameters).\n*)\n\nSet Implicit Arguments.\n\nRequire Import Integers Bitvec ZArith.\nImport Int.\n\n(****************************************************************************)\n(** Architecture versions (p. 13) *)\n(****************************************************************************)\n\nInductive version : Type :=\n(* All architecture names prior to ARMv4 are now OBSOLETE *)\n| ARMv4 | ARMv4T\n| ARMv5T | ARMv5TExP (*for legacy reasons only*) | ARMv5TE | ARMv5TEJ\n| ARMv6.\n\n(****************************************************************************)\n(** A2.4.3 Reading the program counter (p. 47) *)\n(****************************************************************************)\n\nInductive store_PC_offset_value : Type := O8 | O12.\n\nDefinition word_of_store_PC_offset_value (v : store_PC_offset_value) : word :=\n  match v with\n    | O8 => repr 8\n    | O12 => repr 12\n  end.\n \n(****************************************************************************)\n(** A2.6.5 Abort models (p. 61) *)\n(****************************************************************************)\n\nInductive abort_model : Type := Restored | Updated.\n\n(****************************************************************************)\n(** IMPLEMENTATION DEFINED parameters *)\n(****************************************************************************)\n\nModule Type CONFIG.\n\n(*WARNING: only ARMv6 is supported currently\n\n  (* Architecture versions (p. 13) *)\n  Variable version : version.*)\n\n(*WARNING: only O8 is supported currently\n\n  (* A2.4.3 Reading the program counter (p. 47) *)\n  Variable store_PC_offset : store_PC_offset_value.*)\n\n(*WARNING: vectorized interrupts are not supported *)\n  (* A2.6 Exceptions (p. 54) *)\n  Variable VE_IRQ_address : word.\n  Variable VE_FIQ_address : word.\n\n(*WARNING: data aborts are not supported\n\n  (* A2.6.5 Abort models (p. 61) *)\n  (*Variable abort_model : abort_model.*)\n\n  (* A2.6.7 Imprecise data aborts (p. 61) *)\n  Variable imprecise_aborts_max : Z.*)\n\n(*WARNING: high vectors are always supported in ARMv6\n\n  (* A2.6.11 High Vectors (p. 64) *)\n  Variable high_vectors_supported : bool.*)\n\n(*WARNING: not supported\n\n  (* A2.7.3 Endian configuration and control (p. 72) *)\n  Variable BE32_support : bool.*)\n\n(*WARNING: should be set to true, otherwise BKPT leaves the state\nunchanged in the current semantics*)\n  (* A4.1.7 BKPT (p. 164) *)\n  Variable not_overridden_by_debug_hardware : bool.\n\n(*WARNING: Jazelle instruction set not supported*)\n  (* A4.1.11 BXJ (p. 172) *)\n  Variable JE_bit_of_Main_Configuration_register : bool.\n  Variable CV_bit_of_Jazelle_OS_Control_register : bool.\n  Variable jpc_SUB_ARCHITECTURE_DEFINED_value : word.\n  Variable invalidhandler_SUB_ARCHITECTURE_DEFINED_value : word.\n  Variable Jazelle_Extension_accepts_opcode_at : word -> bool.\n  Variable IMPLEMENTATION_DEFINED_CONDITION : bool.\n\nEnd CONFIG.\n", "meta": {"author": "git-inria", "repo": "simsoc-cert", "sha": "2a2d45c3d94745fb33d91ed75ca91de083b4cebd", "save_path": "github-repos/coq/git-inria-simsoc-cert", "path": "github-repos/coq/git-inria-simsoc-cert/simsoc-cert-2a2d45c3d94745fb33d91ed75ca91de083b4cebd/arm6/coq/Arm6_Config.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.22002290067161528}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool eqtype seq.\nRequire Import ssrZ ZArith_ext seq_ext.\nRequire Import machine_int.\nImport MachineInt.\nRequire Import mips_cmd mips_tactics mips_contrib uniq_tac.\nImport expr_m.\nRequire Import multi_zero_u_prg.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope mips_expr_scope.\nLocal Open Scope mips_cmd_scope.\n\nLemma multi_zero_u_termination s h k z ext M_ :\n  uniq (k :: z :: ext :: M_ :: r0 :: nil) ->\n  { si | Some (s, h) -- multi_zero_u k z ext M_ ---> si }.\nProof.\nmove=> Hset; rewrite /multi_zero_u.\napply exists_addiu_seq.\nrewrite sext_0 addi0.\napply exists_addiu_seq.\nrewrite sext_0 addi0.\nrepeat Reg_upd.\nset s0 := store.upd _ _ _.\nhave [next Hext] : { kext | u2Z [ext]_s0 = Z_of_nat kext }.\n  have [zext Hext] : { zext | u2Z ([ext]_s0) = zext} by eapply exist; reflexivity.\n  have : 0 <= zext by rewrite -Hext; apply min_u2Z.\n  case/Z_of_nat_complete_inf => next Hzext.\n  by exists next; rewrite -Hzext.\nmove: next s0 Hext h; elim.\n- move=> s0 Hext h.\n  eapply exist.\n  apply while.exec_while_false => /=.\n  by rewrite negbK store.get_r0 Z2uK // Hext.\n- move=> next IH s0 Hext h; apply exists_while.\n  + by rewrite /= store.get_r0 Z2uK // Hext.\n  + apply exists_seq_P2 with (fun st => u2Z [ext]_(fst st) = Z_of_nat next).\n    * exists_sw_P l Hl z0 Hz0.\n      apply exists_addiu_seq_P.\n      apply exists_addiu_P.\n      rewrite /=.\n      repeat Reg_upd.\n      rewrite sext_Z2s // u2Z_add_Z2s // Hext Z_S -addZA /= addZC //=; by apply Zle_0_nat.\n    * move=> [ si hi ] Hsi.\n      by apply IH.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/cryptoasm/multi_zero_u_termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21998478011745345}}
{"text": "Require Import Coq.Program.Basics. \nRequire Import Coq.Strings.String. \nRequire Import Setoid.\nRequire Import ZArith.\nRequire Import Psatz.\nRequire Import Coq.Program.Equality.\n\n(* Require Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import seq ssreflect ssrbool ssrnat eqtype.\n *)\nRequire Import FinProof.Common. \nRequire Import FinProof.MonadTransformers21.\nRequire Import FinProof.Common.\nRequire Import FinProof.StateMonad21.\nRequire Import FinProof.StateMonad21Instances.\nRequire Import FinProof.Types.IsoTypes.\nRequire Import FinProof.ProgrammingWith.\n\nRequire Import UMLang.UrsusLib.\n\nRequire Import UrsusStdLib.Cpp.stdTypes.\nRequire Import UrsusStdLib.Cpp.stdErrors. \nRequire Import UrsusStdLib.Cpp.stdFunc.\nRequire Import UrsusStdLib.Cpp.stdNotations.\nRequire Import UrsusStdLib.Cpp.stdUFunc.\n\nRequire Import UrsusTVM.Cpp.tvmTypes.\nRequire Import UrsusTVM.Cpp.tvmFunc.\nRequire Import UrsusTVM.Cpp.tvmNotations.\n\nRequire Import Project.CommonConstSig.\nRequire Import Project.CommonTypes.\n\n(*Fully qualified name are mandatory in multi-contract environment*)\nRequire Import DFromGiver.Ledger.\nRequire Import DFromGiver.ClassTypesNotations.\nRequire Import DFromGiver.ClassTypes.\nRequire Import DFromGiver.Functions.FuncSig.\nRequire Import DFromGiver.Functions.FuncNotations.\nRequire Import DFromGiver.Functions.Funcs.\n\n(* Require Import Blank.ClassTypesNotations. *)\n\nSet Typeclasses Iterative Deepening.\n(* Set Typeclasses Depth 100. *)\n\nImport UrsusNotations.\nLocal Open Scope ursus_scope.\nLocal Open Scope ucpp_scope.\nLocal Open Scope struct_scope.\nLocal Open Scope N_scope.\nLocal Open Scope string_scope.\nLocal Open Scope xlist_scope.\n\n(* Require Import Logic.FunctionalExtensionality.\nFrom QuickChick Require Import QuickChick.\nImport QcDefaultNotation. Open Scope qc_scope.\nImport GenLow GenHigh.\nSet Warnings \"-extraction-opaque-accessed,-extraction\".\n *)\nRequire Import Project.CommonQCEnvironment.\n(* Require Import DFromGiver.QuickChicks.QCEnvironment.\n *)\nDefinition UinterpreterL := @Uinterpreter XBool XUInteger XMaybe XList XProd XHMap _ _ _ _ _ _\n                             LedgerLRecord ContractLRecord LocalStateLRecord VMStateLRecord\n                             MessagesAndEventsLRecord GlobalParamsLRecord\n                             OutgoingMessageParamsLRecord ledgerClass .\nArguments UinterpreterL {_} {_} {_}.\n\nDefinition ledger_prop1 (l: LedgerLRecord) := true.\n\n(* Set Typeclasses Debug. *)\n\n(* Time QuickChick ledger_prop1.*)\n\nImport FinProof.Common.  (*for eqb!!!*)\nRequire Import FinProof.CommonInstances.\n\n(* \nDefinition implb (a b: bool) := orb (negb a) b.\n\n(* ---------------------------------------------*)\nNotation ControlResult := (@ControlResultL) .\nDefinition isError {R b} (cr : ControlResult R b) : bool :=\n match cr with\n | ControlValue _ _ => false\n | _ => true\n end.\n *)(* ---------------------------------------------*)\n(* constructor *)\n(* #[global]\nInstance addressEq_Dec (a b: address): Dec (a = b).\ndestruct a,b.\nesplit.\nunfold decidable.\neapply prod_Dec.\nesplit.\nunfold decidable.\ndecide equality.\ndecide equality.\ndecide equality.\nesplit.\nunfold decidable.\ndecide equality.\ndecide equality.\ndecide equality.\nDefined.\n *)\nDefinition MessagesAndEventsDefault : MessagesAndEventsLRecord:= Eval compute in default.\nDefinition VMStateDefault : VMStateLRecord  := Eval compute in default. \n\nDefinition constructor_requires  (GFM :  uint128)\n(lock_time :  XUInteger32 ) (unlock_time :  XUInteger32 ) \n                           ( l: LedgerLRecord )  : Prop :=\nlet fund_address := toValue (eval_state (sRReader || fund_address_  || ) l) in\nlet intS := toValue (eval_state (sRReader || int_sender () || ) l) in\nlet tn := toValue (eval_state (sRReader || tvm_now () || ) l) in\nlet require1 := ( intS) <> ( fund_address) in\nlet require2 := ( fund_address = default ) in\nlet require3 :=  (uint2N tn >= uint2N lock_time)  in\nlet require4 :=  (uint2N lock_time >= uint2N unlock_time)  in\n require1 \\/ require2  \\/ require3 \\/ require4.\n\nDefinition constructor_isError_prop (GFM :  uint128)\n(lock_time :  XUInteger32 ) (unlock_time :  XUInteger32 ) \n                           ( l: LedgerLRecord )  : Prop :=\nisError (eval_state (UinterpreterL (constructor_   (KWMessages_ι_GAS_FOR_FUND_MESSAGE_:= GFM) lock_time unlock_time )) l)\n<-> constructor_requires GFM lock_time unlock_time l.\n\n Definition constructor_exec_prop\n (GFM :  uint128)\n (lock_time :  XUInteger32 ) (unlock_time :  XUInteger32 ) \n ( l: LedgerLRecord )  : Prop :=\nlet l' := exec_state (UinterpreterL (constructor_   (KWMessages_ι_GAS_FOR_FUND_MESSAGE_:= GFM) lock_time unlock_time)) l in  \nlet mm := toValue (eval_state (sRReader IBlankPtr_messages_right ) l') in\nlet a := toValue (eval_state (sRReader || fund_address_ || ) l) in\nlet non := toValue (eval_state (sRReader || nonce_ || ) l) in\nlet giver_address := toValue (eval_state (sRReader || giver_address_ || ) l) in\nlet params:InternalMessageParamsLRecord := (GFM, (true, Build_XUBInteger 1)) in \nlet func: Interfaces.IBlank.IBlank.Interface.IBlank :=\n          Interfaces.IBlank.IBlank.Interface.IacknowledgeDeploy giver_address non in\nlet message := OutgoingInternalMessage params func in \nlet ms := isMessageSent message a 0 mm             in  \n( ~ (constructor_requires GFM lock_time unlock_time l)  ) ->  \n(uint2N (toValue (eval_state (sRReader || balance_ || ) l')) =  0  /\\ \n (toValue (eval_state (sRReader || fund_ready_flag_ || ) l')) =  false /\\\nuint2N (toValue (eval_state (sRReader || lock_time_ || ) l')) =  uint2N  lock_time /\\\nuint2N (toValue (eval_state (sRReader || unlock_time_ || ) l')) =  uint2N  unlock_time \n /\\ VMState_ι_accepted (Ledger_VMState l') = true \n /\\ ms = true ).\n \n Definition constructor_noexec_prop \n (GFM :  uint128)\n (lock_time :  XUInteger32 ) (unlock_time :  XUInteger32 ) \n (l: LedgerLRecord )  : Prop :=\nlet l' := exec_state (UinterpreterL (constructor_  (KWMessages_ι_GAS_FOR_FUND_MESSAGE_:= GFM) lock_time unlock_time)) l in\nconstructor_requires GFM lock_time unlock_time l -> \nLedger_MainState l = Ledger_MainState l'.\n\n\n(* ---------------------------------- *)\n(* receive *)\nDefinition receive_requires (MB : uint128) ( GFM  : uint128) (  EB : uint128)\n                           ( l: LedgerLRecord )  : Prop :=\nlet mv := toValue (eval_state (sRReader || int_value() || ) l) in\nlet intS := toValue (eval_state (sRReader || int_sender() || ) l) in\nlet tb := toValue (eval_state (sRReader || tvm_balance() || ) l) in\nlet tn := toValue (eval_state (sRReader || tvm_now() || ) l) in\nlet lock_time := toValue (eval_state (sRReader || lock_time_ || ) l) in\nlet giver_address := toValue (eval_state (sRReader || giver_address_ || ) l) in\nlet balance := toValue (eval_state (sRReader || balance_ || ) l) in\n\nlet if1 := uint2N mv > uint2N MB in\nlet require1 := intS <> giver_address in\nlet require2 :=  uint2N tn >= uint2N lock_time in\nlet require3 :=  uint2N tb <= uint2N mv + uint2N balance + (uint2N GFM + uint2N EB) in\nif1 /\\ (require1 \\/ require2 \\/ require3).\n\nDefinition receive_isError_prop (MB : uint128) ( GFM  : uint128) (  EB : uint128)\n                           ( l: LedgerLRecord )  : Prop :=\nisError (eval_state (UinterpreterL (receive_ ( KWMessages_ι_FG_MIN_BALANCE_ := MB) (KWMessages_ι_GAS_FOR_FUND_MESSAGE_ := GFM) (KWMessages_ι_EPSILON_BALANCE_ := EB) )) l)\n <->  (receive_requires MB GFM EB l) .\n\nDefinition receive_exec_prop\n(MB : uint128) ( GFM  : uint128) (  EB : uint128)\n                             ( l: LedgerLRecord )  : Prop :=\nlet l' := exec_state (UinterpreterL (receive_  ( KWMessages_ι_FG_MIN_BALANCE_ := MB) (KWMessages_ι_GAS_FOR_FUND_MESSAGE_ := GFM) (KWMessages_ι_EPSILON_BALANCE_ := EB) )) l in  \n\nlet mv := toValue (eval_state (sRReader || int_value() || ) l) in\nlet balance := toValue (eval_state (sRReader || balance_ || ) l) in\nlet mm := toValue (eval_state (sRReader IBlankPtr_messages_right ) l') in\nlet a := toValue (eval_state (sRReader || fund_address_ || ) l) in\nlet non := toValue (eval_state (sRReader || nonce_ || ) l) in\nlet giver_address := toValue (eval_state (sRReader || giver_address_ || ) l) in\nlet params:InternalMessageParamsLRecord := (GFM, (true, Build_XUBInteger 1)) in \nlet func: Interfaces.IBlank.IBlank.Interface.IBlank :=\n          Interfaces.IBlank.IBlank.Interface.InotifyRight giver_address non balance mv in\nlet message := OutgoingInternalMessage params func in \nlet ms := isMessageSent message a 0 mm             in  \n\n\n( uint2N mv > uint2N MB ) /\\ (~ (receive_requires  MB GFM EB l)) ->\nVMState_ι_accepted (Ledger_VMState l') = true \n /\\ ms = true\n /\\ uint2N (toValue (eval_state (sRReader || balance_ || ) l')) = uint2N balance + uint2N mv. \n\nDefinition receive_noexec_prop\n(MB : uint128) ( GFM  : uint128) (  EB : uint128)\n                             ( l: LedgerLRecord )  : Prop :=\nlet l' := exec_state (UinterpreterL (receive_  ( KWMessages_ι_FG_MIN_BALANCE_ := MB) (KWMessages_ι_GAS_FOR_FUND_MESSAGE_ := GFM) (KWMessages_ι_EPSILON_BALANCE_ := EB) )) l in \n(receive_requires MB GFM EB l) ->\nLedger_MainState l = Ledger_MainState l'.\n\n(* ---------------------------------- *)\n(* notifyParticipant *)\nDefinition notifyParticipant_requires (  EB : uint128)  (giveup :  boolean  ) (investors_adj_summa_ :  uint128 ) (summa_givers :  uint128 )\n                           ( l: LedgerLRecord )  : Prop :=\nlet ms := toValue (eval_state (sRReader || int_sender() || ) l) in\nlet tn := toValue (eval_state (sRReader || tvm_now () || ) l) in\nlet fa := toValue (eval_state (sRReader || fund_address_ || ) l) in\nlet lock_time := toValue (eval_state (sRReader || lock_time_ || ) l) in\nlet unlock_time := toValue (eval_state (sRReader || unlock_time_ || ) l) in\nlet fund_ready_flag := toValue (eval_state (sRReader || fund_ready_flag_ || ) l) in\nlet balance := toValue (eval_state (sRReader || balance_ || ) l) in\nlet intValue := toValue (eval_state (sRReader || int_value() || ) l) in\nlet tb := toValue (eval_state (sRReader || tvm_balance() || ) l) in\n\nlet require1 := ms <> fa in\nlet require2 :=  (((uint2N tn) < (uint2N lock_time)) \\/ ((uint2N tn) > (uint2N unlock_time))) in \nlet require3 := fund_ready_flag = true in \nlet require4 :=  (uint2N tb) < (( uint2N intValue) + (uint2N balance) + (uint2N EB)) in \nrequire1 \\/ require2 \\/ require3 \\/ require4.\n\nDefinition notifyParticipant_isError_prop (  EB : uint128)  (giveup :  boolean  ) (investors_adj_summa_ :  uint128 ) (summa_givers :  uint128 )\n                           ( l: LedgerLRecord )  : Prop :=\nisError (eval_state (UinterpreterL (notifyParticipant_ (KWMessages_ι_EPSILON_BALANCE_ := EB)  giveup investors_adj_summa_ summa_givers )) l)\n <->  (notifyParticipant_requires EB giveup investors_adj_summa_ summa_givers l) .\n\nDefinition notifyParticipant_exec_prop\n(  EB : uint128)  (giveup :  boolean  ) (investors_adj_summa_ :  uint128 ) (summa_givers :  uint128 ) \n                             ( l: LedgerLRecord )  : Prop :=\nlet l' := exec_state (UinterpreterL (notifyParticipant_  (KWMessages_ι_EPSILON_BALANCE_ := EB)  giveup investors_adj_summa_ summa_givers )) l in  \nlet mm := toValue (eval_state (sRReader IBlankPtr_messages_right ) l') in\nlet intValue := toValue (eval_state (sRReader || int_value() || ) l) in \nlet fund_address := toValue (eval_state (sRReader || fund_address_ || ) l) in \nlet giver_address := toValue (eval_state (sRReader || giver_address_ || ) l) in \nlet non := toValue (eval_state (sRReader || nonce_ || ) l) in \nlet balance := toValue (eval_state (sRReader || balance_ || ) l) in \nlet balance' := toValue (eval_state (sRReader || balance_ || ) l') in \nlet dead_giver := ( (* giveup  \\\\ *) (N.eqb (uint2N balance)   0 ) ) in  \nlet params:InternalMessageParamsLRecord := (intValue, (true, Build_XUBInteger 1)) in \nlet func: Interfaces.IBlank.IBlank.Interface.IBlank :=\n          Interfaces.IBlank.IBlank.Interface.IacknowledgeFinalizeRight giver_address non dead_giver in\nlet message := OutgoingInternalMessage params func in  \nlet ms := isMessageSent message fund_address 0 mm             in  \nlet mm2 : XHMap address (XQueue (OutgoingMessage PhantomType)) := toValue (eval_state (sRReader IDefaultPtr_messages_right ) l') in \nlet params2 : InternalMessageParamsLRecord := ( balance, (true, Build_XUBInteger 1)) in\nlet message2 := EmptyMessage PhantomType params2 in \nlet ms2 := isMessageSent message2 giver_address 0 mm2 in\nlet flag := N.lor (N.lor (N.lor (uint2N SEND_ALL_GAS) (uint2N SENDER_WANTS_TO_PAY_FEES_SEPARATELY))\n                 (uint2N DELETE_ME_IF_I_AM_EMPTY))\n\t\t\t\t\t\t     (uint2N IGNORE_ACTION_ERRORS) in\nlet params3:InternalMessageParamsLRecord := (Build_XUBInteger 0, (false, Build_XUBInteger flag)) in\nlet message3 := EmptyMessage _ params3 in\nlet ms3 := isMessageSent message3 fund_address 0 mm2 in \nlet extra := (* Build_XUBInteger *) ((uint2N balance) * ((uint2N  summa_givers) - (uint2N investors_adj_summa_)) / (uint2N summa_givers) ) in\nlet params4 : InternalMessageParamsLRecord := ( (Build_XUBInteger extra), (true, Build_XUBInteger 1)) in\nlet message4 := EmptyMessage PhantomType params4 in \nlet ms4 := isMessageSent message4 giver_address 0 mm2 in \n\n\n(~ (notifyParticipant_requires  EB giveup investors_adj_summa_ summa_givers l)) ->\nVMState_ι_accepted (Ledger_VMState l') = true \n/\\ ms = true\n/\\ ((giveup = true) -> \n               ((uint2N  balance > 0)  -> (ms2 = true)) \n               /\\  VMState_ι_isTVMExited (Ledger_VMState l') = true\n                                                /\\ ms3 = true)\n/\\ ((giveup  = false ) -> \n               (toValue (eval_state (sRReader || fund_ready_flag_ || ) l') = true) \n               /\\ (((uint2N summa_givers) > (uint2N  investors_adj_summa_) )  -> \n                                                                        (* (let extra := (* Build_XUBInteger *) ((uint2N balance) * ((uint2N investors_adj_summa_) - (uint2N summa_givers)) / (uint2N investors_adj_summa_) ) in *)                                                                          \n                                                                      (((uint2N balance') = (uint2N balance) - ( extra) )\n                                                                      /\\ ms4 = true\n                                                                      /\\ ((  ( uint2N balance) = 0  ) -> ms3 =true)\n                                                                      ))).\n                                                                   \nDefinition notifyParticipant_noexec_prop\n(  EB : uint128)  (giveup :  boolean  ) (investors_adj_summa_ :  uint128 ) (summa_givers :  uint128 )\n                             ( l: LedgerLRecord )  : Prop :=\nlet l' := exec_state (UinterpreterL (notifyParticipant_  (KWMessages_ι_EPSILON_BALANCE_ := EB)  giveup investors_adj_summa_ summa_givers )) l in \n(notifyParticipant_requires EB giveup investors_adj_summa_ summa_givers l) ->\nLedger_MainState l = Ledger_MainState l'.\n                   \n(* ---------------------------------- *)\n(* returnFunds *)\nDefinition returnFunds_requires (  EB : uint128) \n                           ( l: LedgerLRecord )  : Prop :=\nlet tb := toValue (eval_state (sRReader || tvm_balance () || ) l) in\nlet tn := toValue (eval_state (sRReader || tvm_now() || ) l) in\nlet unlock_time := toValue (eval_state (sRReader || unlock_time_ || ) l) in\nlet require1 := ((uint2N tn) <= (uint2N unlock_time))  in\nlet require2 := (uint2N tb < uint2N EB) in\nrequire1 \\/ require2.\n\nDefinition returnFunds_isError_prop (  EB : uint128) \n                           ( l: LedgerLRecord )  : Prop :=\nisError (eval_state (UinterpreterL (returnFunds_  (KWMessages_ι_EPSILON_BALANCE_ := EB)   )) l)\n <->  (returnFunds_requires  EB   l) .\n\nDefinition returnFunds_exec_prop\n(  EB : uint128) \n                             ( l: LedgerLRecord )  : Prop :=\nlet l' := exec_state (UinterpreterL (returnFunds_   (KWMessages_ι_EPSILON_BALANCE_ := EB)   )) l in  \nlet balance := toValue (eval_state (sRReader || balance_ || ) l) in\nlet giver_address := toValue (eval_state (sRReader || giver_address_ || ) l) in\nlet fund_address := toValue (eval_state (sRReader || fund_address_ || ) l) in\nlet mm : XHMap address (XQueue (OutgoingMessage PhantomType)) := toValue (eval_state (sRReader IDefaultPtr_messages_right ) l') in\nlet params : InternalMessageParamsLRecord := ( balance, (true, Build_XUBInteger 1)) in\nlet message := EmptyMessage PhantomType params in \nlet ms := isMessageSent message giver_address 0 mm in\nlet flag := N.lor (N.lor (N.lor (uint2N SEND_ALL_GAS) (uint2N SENDER_WANTS_TO_PAY_FEES_SEPARATELY))\n                 (uint2N DELETE_ME_IF_I_AM_EMPTY))\n\t\t\t\t\t\t     (uint2N IGNORE_ACTION_ERRORS) in\nlet params2:InternalMessageParamsLRecord := (Build_XUBInteger 0, (false, Build_XUBInteger flag)) in\nlet message2 := EmptyMessage _ params2 in\nlet ms2 := isMessageSent message2 fund_address 0 mm in \n(~ (returnFunds_requires   EB   l)) -> \nVMState_ι_accepted (Ledger_VMState l') = true \n/\\ ms2 = true\n/\\ ((uint2N balance > 0) -> ms = true).\n\nDefinition returnFunds_noexec_prop\n(  EB : uint128) \n                             ( l: LedgerLRecord )  : Prop :=\nlet l' := exec_state (UinterpreterL (returnFunds_   (KWMessages_ι_EPSILON_BALANCE_ := EB)   )) l in \n(returnFunds_requires  EB   l) ->\nLedger_MainState l = Ledger_MainState l'.\n\n(* ---------------------------------- *)\n(* acknowledgeFunds *)\nDefinition acknowledgeFunds_requires \n                           ( l: LedgerLRecord )  : Prop :=\nlet ms := toValue (eval_state (sRReader || int_sender() || ) l) in\nlet fa := toValue (eval_state (sRReader || fund_address_ || ) l) in\nlet require := ms <> fa in \nrequire.\n\nDefinition acknowledgeFunds_isError_prop \n                           ( l: LedgerLRecord )  : Prop :=\nisError (eval_state (UinterpreterL (acknowledgeFunds_    )) l)\n <->  (acknowledgeFunds_requires    l) .\n\nDefinition acknowledgeFunds_exec_prop\n                             ( l: LedgerLRecord )  : Prop :=\nlet l' := exec_state (UinterpreterL (acknowledgeFunds_     )) l in  \nlet intS := toValue (eval_state (sRReader || int_sender() || ) l) in\nlet intV := toValue (eval_state (sRReader || int_value() || ) l) in\nlet fund_address := toValue (eval_state (sRReader || fund_address_ || ) l) in\nlet mm : XHMap address (XQueue (OutgoingMessage PhantomType)) := toValue (eval_state (sRReader IDefaultPtr_messages_right ) l') in\nlet params : InternalMessageParamsLRecord := ( intV, (false, Build_XUBInteger 1)) in\nlet message := EmptyMessage PhantomType params in \nlet ms := isMessageSent message intS 0 mm in\nlet flag := N.lor (N.lor (N.lor (uint2N SEND_ALL_GAS) (uint2N SENDER_WANTS_TO_PAY_FEES_SEPARATELY))\n                 (uint2N DELETE_ME_IF_I_AM_EMPTY))\n\t\t\t\t\t\t     (uint2N IGNORE_ACTION_ERRORS) in\nlet params2:InternalMessageParamsLRecord := (Build_XUBInteger 0, (false, Build_XUBInteger flag)) in\nlet message2 := EmptyMessage _ params2 in\nlet ms2 := isMessageSent message2 fund_address 0 mm in \n(~ (acknowledgeFunds_requires    l)) ->\n(VMState_ι_accepted (Ledger_VMState l') = true \n/\\ ms = true\n/\\ ms2 = true).\n\nDefinition acknowledgeFunds_noexec_prop\n                             ( l: LedgerLRecord )  : Prop :=\nlet l' := exec_state (UinterpreterL (acknowledgeFunds_     )) l in \n(acknowledgeFunds_requires    l) ->\nLedger_MainState l = Ledger_MainState l'.\n\n(* ---------------------------------- *)\n(* sendFunds *)\nDefinition sendFunds_requires (EB: uint128) (NO_NAME0 :  cell_  )\n                           ( l: LedgerLRecord )  : Prop :=\n\nlet ms := toValue (eval_state (sRReader || int_sender() || ) l) in\nlet fa := toValue (eval_state (sRReader || fund_address_ || ) l) in\nlet myaddr := toValue (eval_state (sRReader || tvm_myaddr() || ) l) in\nlet fund_ready_flag := toValue (eval_state (sRReader || fund_ready_flag_ || ) l) in\nlet tb := toValue (eval_state (sRReader || tvm_balance() || ) l) in\nlet intV := toValue (eval_state (sRReader || int_value() || ) l) in\nlet balance := toValue (eval_state (sRReader || balance_ || ) l) in\n\nlet require1 := ms <> fa in \n(* let require2 := address_to = myaddr in \n *)let require3 := fund_ready_flag = false in \nlet require4 := (uint2N tb) <  (uint2N intV) + (uint2N balance) + (uint2N EB) in \nrequire1 (* \\/ require2 *) \\/ require3 \\/ require4.\nDefinition sendFunds_isError_prop (EB: uint128) (NO_NAME0 :  cell_  )\n                           ( l: LedgerLRecord )  : Prop :=\nisError (eval_state (UinterpreterL (sendFunds_  (KWMessages_ι_EPSILON_BALANCE_ := EB) NO_NAME0 )) l)\n <->  (sendFunds_requires  EB NO_NAME0  l) .\n\nDefinition sendFunds_exec_prop (EB: uint128) (NO_NAME0 :  cell_  )\n                             ( l: LedgerLRecord )  : Prop :=\nlet l' := exec_state (UinterpreterL (sendFunds_  (KWMessages_ι_EPSILON_BALANCE_ := EB) NO_NAME0   )) l in  \nlet intV := toValue (eval_state (sRReader || int_value() || ) l) in\nlet balance := toValue (eval_state (sRReader || balance_ || ) l) in\nlet non := toValue (eval_state (sRReader || nonce_ || ) l) in\nlet giver_address := toValue (eval_state (sRReader || giver_address_ || ) l) in\n\nlet mm := toValue (eval_state (sRReader IKWFundPtr_messages_right ) l') in\nlet fund_address := toValue (eval_state (sRReader || fund_address_ || ) l) in\nlet packParams_eval := toValue (eval_state (Uinterpreter ( packParams_  ) ) l) in\nlet mvalue := Build_XUBInteger ((uint2N balance) + (uint2N intV)) in\nlet params:InternalMessageParamsLRecord := (mvalue, (true, Build_XUBInteger 1)) in \nlet func: Interfaces.IKWFund.IKWFund.Interface.IKWFund :=\n          Interfaces.IKWFund.IKWFund.Interface.IsendFromGiverParams giver_address non packParams_eval in\nlet message := OutgoingInternalMessage params func in \nlet ms := isMessageSent message fund_address 0 mm             in \n(~ (sendFunds_requires  EB  NO_NAME0 l)) ->\n(VMState_ι_accepted (Ledger_VMState l') = true \n /\\ ms = true ).\n\nDefinition sendFunds_noexec_prop (EB: uint128) (NO_NAME0 :  cell_  )\n                             ( l: LedgerLRecord )  : Prop :=\nlet l' := exec_state (UinterpreterL (sendFunds_  (KWMessages_ι_EPSILON_BALANCE_ := EB) NO_NAME0   )) l in \n(sendFunds_requires EB  NO_NAME0  l) ->\nLedger_MainState l = Ledger_MainState l'.\n\n\n", "meta": {"author": "kwpc-io", "repo": "kwf_contracts", "sha": "3c4030ba73392bb76431d1880b383b816b3bf1e2", "save_path": "github-repos/coq/kwpc-io-kwf_contracts", "path": "github-repos/coq/kwpc-io-kwf_contracts/kwf_contracts-3c4030ba73392bb76431d1880b383b816b3bf1e2/src/Contracts/FromGiver/DFromGiver/QuickChicks/Props.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.2197087601991489}}
{"text": "Require Import Leapfrog.Benchmarks.ProofHeader.\nRequire Import Leapfrog.Benchmarks.Timestamp.\n\nNotation H := (TimestampRefZeroSingle.header + TimestampSpecSingle.header).\nNotation A := (Sum.sum TimestampRefZeroSingle.aut TimestampSpecSingle.aut).\nNotation conf := (P4automaton.configuration (P4A.interp A)).\nNotation start_left := TimestampRefZeroSingle.Start.\nNotation start_right := TimestampSpecSingle.Start.\n\nDefinition r_states : {r : Reachability.state_pairs A & Reachability.reachable_states_wit start_left start_right r}.\n  econstructor.\n  unfold Reachability.reachable_states_wit.\n  solve_fp_wit.\nDefined.\n\n(* Definition r_len := Eval vm_compute in (length r_states).\n\nPrint r_len. *)\n\nDeclare ML Module \"mirrorsolve\".\n\n(*\nRegisterEnvCtors\n  (TimestampRefZeroSingle.Typ, FirstOrderConfRelSimplified.Bits 8)\n  (TimestampRefZeroSingle.Len, FirstOrderConfRelSimplified.Bits 8)\n  (TimestampRefZeroSingle.Value, FirstOrderConfRelSimplified.Bits 48)\n  (TimestampRefZeroSingle.Scratch8, FirstOrderConfRelSimplified.Bits 8)\n  (TimestampRefZeroSingle.Scratch16, FirstOrderConfRelSimplified.Bits 16)\n  (TimestampRefZeroSingle.Scratch24, FirstOrderConfRelSimplified.Bits 24)\n  (TimestampRefZeroSingle.Scratch32, FirstOrderConfRelSimplified.Bits 32)\n  (TimestampRefZeroSingle.Scratch40, FirstOrderConfRelSimplified.Bits 40)\n  (TimestampSpecSingle.Typ, FirstOrderConfRelSimplified.Bits 8)\n  (TimestampSpecSingle.Len, FirstOrderConfRelSimplified.Bits 8)\n  (TimestampSpecSingle.Scratch8, FirstOrderConfRelSimplified.Bits 8)\n  (TimestampSpecSingle.Scratch16, FirstOrderConfRelSimplified.Bits 16)\n  (TimestampSpecSingle.Scratch24, FirstOrderConfRelSimplified.Bits 24)\n  (TimestampSpecSingle.Scratch32, FirstOrderConfRelSimplified.Bits 32)\n  (TimestampSpecSingle.Scratch40, FirstOrderConfRelSimplified.Bits 40)\n  (TimestampSpecSingle.Scratch48, FirstOrderConfRelSimplified.Bits 48)\n  (TimestampSpecSingle.Pointer, FirstOrderConfRelSimplified.Bits 8)\n  (TimestampSpecSingle.Overflow, FirstOrderConfRelSimplified.Bits 4)\n  (TimestampSpecSingle.Flag, FirstOrderConfRelSimplified.Bits 4)\n  (TimestampSpecSingle.Timestamp, FirstOrderConfRelSimplified.Bits 32).\n*)\n\n  Lemma prebisim_incremental_sep:\n  forall q1 q2,\n    interp_conf_rel' {| cr_st := {|\n                        cs_st1 := {|\n                          st_state := inl (inl (start_left));\n                          st_buf_len := 0;\n                        |};\n                        cs_st2 := {|\n                          st_state := inl (inr (start_right));\n                          st_buf_len := 0;\n                        |};\n                      |};\n                      cr_ctx := BCEmp;\n                      cr_rel := btrue;\n                   |} q1 q2 ->\n  pre_bisimulation A\n                   (projT1 r_states)\n                   (wp (a := A))\n                   []\n                   (mk_init _ _ _ _ A start_left start_right)\n                   q1 q2.\nProof.\n  idtac \"running timestamp single bisimulation\".\n\n  intros.\n  set (a := A).\n  set (rel0 := (mk_init _ _ _ _ _ _ _ _)).\n  vm_compute in rel0.\n  subst rel0.\n\n  set (eight := 8).\n  assert (H8 : 8 = eight); [subst eight; reflexivity|].\n  set (sixteen := (Datatypes.S( Datatypes.S( Datatypes.S( Datatypes.S( Datatypes.S( Datatypes.S( Datatypes.S( Datatypes.S eight))))))))).\n  assert (H16 : (Datatypes.S( Datatypes.S( Datatypes.S( Datatypes.S( Datatypes.S( Datatypes.S( Datatypes.S( Datatypes.S eight)))))))) = sixteen); [subst sixteen; reflexivity|].\n\n\n  try rewrite H8;\n  try rewrite H16;\n\n\n  match goal with\n  | |- pre_bisimulation _ _ _ _ ?R _ _ =>\n    hashcons_list R\n  end.\n\n  time \"build phase\" repeat (run_bisim top top' r_states;\n    try rewrite H8;\n    try rewrite H16;\n    try match goal with\n    | |- pre_bisimulation _ _ _ (?N :: ?N' :: ?T) _ _ _  =>\n      let rs := fresh \"rs\" in\n      set (rs := N' :: T);\n      let r := fresh \"r\" in\n      set (r := N)\n\n    | |- pre_bisimulation _ _ _ (?N :: nil) _ _ _  =>\n      let r := fresh \"r\" in\n      set (r := N)\n    end\n  ).\n  time \"close phase\" close_bisim top'.\n\nTime Admitted.\n", "meta": {"author": "verified-network-toolchain", "repo": "leapfrog", "sha": "fe8c4e60c9d1c2660ca2a199909bef04c81e5634", "save_path": "github-repos/coq/verified-network-toolchain-leapfrog", "path": "github-repos/coq/verified-network-toolchain-leapfrog/leapfrog-fe8c4e60c9d1c2660ca2a199909bef04c81e5634/lib/Benchmarks/TimestampSingleZeroProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21960810030999173}}
{"text": "(* This code is copyrighted by its authors; it is distributed under  *)\n(* the terms of the LGPL license (see LICENSE and description files) *)\n\n(****************************************************************************)\n(*                                                                          *)\n(*                                                                          *)\n(*                Solange Coupet-Grimal & Line Jakubiec-Jamet               *)\n(*                                                                          *)\n(*                                                                          *)\n(*             Laboratoire d'Informatique Fondamentale de Marseille         *)\n(*                   CMI et Faculté des Sciences de Luminy                  *)\n(*                                                                          *)\n(*           e-mail:{Solange.Coupet,Line.Jakubiec}@lif.univ-mrs.fr          *)\n(*                                                                          *)\n(*                                                                          *)\n(*                            Developped in Coq v6                          *)\n(*                            Ported to Coq v7                              *)\n(*                            Translated to Coq v8                          *)\n(*                                                                          *)\n(*                             July 12nd 2005                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                          Lemmas_Comb_Behaviour.v                         *)\n(****************************************************************************)\n\n\nRequire Export ElementComb_Behaviour.\nRequire Export SuccessfulInput.\nRequire Export Base_Struct.\nRequire Export Lemmas_on_fcts.\nRequire Export Lemmas_Struct.\nRequire Export ElementComb.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n\nDefinition Grant_for_Out (ltReq : d_list bool 4) (last : d_list bool 2) :=\n  Convert_port_list2 (SuccessfulInput ltReq (Convert_list2_port last)).\n\n\nLemma Arbiter_last_tt :\n forall l : d_list bool 4,\n Ackor l = true ->\n Fst_of_l2 (Grant_for_Out l (List2 true true)) =\n Jk (Arb_xel (Scd_of_l4 l) true (Fth_of_l4 l) (Thd_of_l4 l))\n   (Scd_of_l2 (Arbx true l)) true /\\\n Scd_of_l2 (Grant_for_Out l (List2 true true)) =\n Jk (J_Arby true l) (Scd_of_l2 (Arby true l)) true.\nintros l H.\nunfold Grant_for_Out in |- *.\nunfold SuccessfulInput in |- *.\nrewrite RoundRobinArbiter_simpl.\nunfold RoundRobin in |- *.\nunfold Convert_list2_port in |- *; simpl in |- *.\nelim\n (In_or_not eq_nat_dec\n    (no_in (SUC_MODN (exist (fun p : nat => p < 4) 3 lt_3_4)))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintros H'.\nunfold SUC_MODN in |- *;\n elim (less_or_eq (exist (fun p : nat => p < 4) 3 lt_3_4)); \n simpl in |- *; auto.\nintros Abs; absurd (4 < 4); auto with arith.\nintros y'.\nunfold Arbx in |- *.\nunfold Arby in |- *.\nunfold K_Arby in |- *.\nunfold Scd_of_l2 in |- *; unfold List2 in |- *; unfold Arb_xel in |- *;\n simpl in |- *.\nunfold Arb_yel in |- *.\nrewrite d_In_SUC_SSSO_l4.\nunfold AO in |- *; simpl in |- *.\nelim orb_sym; auto.\nauto.\nintro non.\nunfold Arbx in |- *.\nunfold Arby in |- *.\nunfold K_Arby in |- *.\nunfold Scd_of_l2 in |- *; unfold List2 in |- *; unfold Arb_xel in |- *;\n simpl in |- *.\nunfold Arb_yel in |- *.\nrewrite not_d_In_SUC_SSSO_l4.\nunfold AO in |- *; simpl in |- *.\nelim orb_sym; simpl in |- *.\nclear non.\nelim\n (In_or_not eq_nat_dec\n    (no_in (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 3 lt_3_4))))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintro H'.\nunfold SUC_MODN in |- *;\n elim (less_or_eq (exist (fun p : nat => p < 4) 3 lt_3_4)); \n simpl in |- *; auto.\nintros Abs; absurd (4 < 4); auto with arith.\nintro y'.\nunfold SUC_MODN in |- *;\n elim (less_or_eq (exist (fun n : nat => n < 4) 0 (Ex_n_lt_gen y')));\n simpl in |- *; auto.\nintro y''.\nrewrite d_In_SUCSUC_SSSO_l4.\nsimpl in |- *; auto.\nauto.\nintro Abs; absurd (1 = 4); auto.\nintro non.\nrewrite not_d_In_SUCSUC_SSSO_l4.\nclear non.\nelim\n (In_or_not eq_nat_dec\n    (no_in\n       (SUC_MODN\n          (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 3 lt_3_4)))))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintros H'.\nunfold SUC_MODN at 3 6 in |- *;\n elim (less_or_eq (exist (fun p : nat => p < 4) 3 lt_3_4)); \n simpl in |- *; auto.\nintro Abs; absurd (4 < 4); auto with arith.\nintro y'.\nunfold SUC_MODN at 2 4 in |- *;\n elim (less_or_eq (exist (fun n : nat => n < 4) 0 (Ex_n_lt_gen y')));\n simpl in |- *; auto.\nintro y''.\nunfold SUC_MODN in |- *;\n elim (less_or_eq (exist (fun n : nat => n < 4) 1 y'')); \n simpl in |- *; auto.\nrewrite d_In_SUCSUCSUC_SSSO_l4.\nintro y.\nelim (less_or_eq (exist (fun p : nat => p < 4) 3 lt_3_4)); simpl in |- *.\nintro Abs; absurd (4 < 4); auto with arith.\nintro b.\nelim (less_or_eq (exist (fun n : nat => n < 4) 0 (Ex_n_lt_gen b)));\n simpl in |- *.\nintro a; elim (less_or_eq (exist (fun n : nat => n < 4) 1 a)); simpl in |- *.\nauto.\nintro Abs; absurd (2 = 4); auto.\nintro Abs; absurd (1 = 4); auto.\ntrivial.\nintro Abs; absurd (2 = 4); auto.\nintro Abs; absurd (1 = 4); auto.\nintros.\nrewrite not_d_In_SUCSUCSUC_SSSO_l4.\nsimpl in |- *.\nelim\n (In_or_not eq_nat_dec\n    (no_in\n       (SUC_MODN\n          (SUC_MODN\n             (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 3 lt_3_4))))))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintros H'.\nunfold Convert_port_list2 in |- *.\ngeneralize eq_n_SM4_4_times; unfold SM4 in |- *; intros Sm4.\nelim (Sm4 (exist (fun p : nat => p < 4) 3 lt_3_4)).\nauto.\nunfold SUC_MODN at 4 8 12 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun p : nat => p < 4) 3 lt_3_4)); simpl in |- *.\nintro Abs; absurd (4 < 4); auto with arith.\nintro b0.\nintro.\nunfold SUC_MODN at 3 6 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 0 (Ex_n_lt_gen b0)));\n simpl in |- *.\nintro a.\nunfold SUC_MODN at 2 4 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 1 a)); simpl in |- *.\nintro a0.\nunfold SUC_MODN in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 2 a0)); simpl in |- *.\nauto.\nintro Abs; absurd (3 = 4); auto.\nintro Abs; absurd (2 = 4); auto.\nintro Abs; absurd (1 = 4); auto.\nauto.\nauto.\nauto.\nauto.\nQed.\n\n\n\n\nLemma Arbiter_last_tf :\n forall l : d_list bool 4,\n Ackor l = true ->\n Fst_of_l2 (Grant_for_Out l (List2 true false)) =\n Jk (Arb_xel (Scd_of_l4 l) false (Fth_of_l4 l) (Thd_of_l4 l))\n   (Scd_of_l2 (Arbx false l)) true /\\\n Scd_of_l2 (Grant_for_Out l (List2 true false)) =\n Jk (J_Arby true l) (Scd_of_l2 (Arby true l)) false.\nintros l H.\nunfold Grant_for_Out in |- *.\nunfold SuccessfulInput in |- *.\nrewrite RoundRobinArbiter_simpl.\nunfold RoundRobin in |- *.\nunfold Convert_list2_port in |- *; simpl in |- *.\nelim\n (In_or_not eq_nat_dec\n    (no_in (SUC_MODN (exist (fun p : nat => p < 4) 2 lt_2_4)))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintro H'.\nunfold SUC_MODN in |- *;\n elim (less_or_eq (exist (fun p : nat => p < 4) 2 lt_2_4)); \n simpl in |- *; auto.\nintro y'.\n  unfold Arbx in |- *; unfold J_Arby in |- *.\nrewrite d_In_SUC_SSO_l4.\nauto.\nauto.\nintro Abs; absurd (3 = 4); auto.\nintro non.\n  unfold Arbx in |- *; unfold J_Arby in |- *.\nrewrite not_d_In_SUC_SSO_l4.\nclear non.\nelim\n (In_or_not eq_nat_dec\n    (no_in (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 2 lt_2_4))))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintro H'.\nunfold SUC_MODN at 2 4 in |- *.\n elim (less_or_eq (exist (fun p : nat => p < 4) 2 lt_2_4)); \n simpl in |- *; auto.\nintro y'.\nunfold SUC_MODN in |- *.\n elim (less_or_eq (exist (fun p : nat => p < 4) 3 y')); \n simpl in |- *; auto.\nintro Abs; absurd (4 < 4); auto with arith.\nrewrite d_In_SUCSUC_SSO_l4; simpl in |- *; auto with arith.\nintro b; absurd (3 = 4); auto with arith.\nintro b.\nelim\n (In_or_not eq_nat_dec\n    (no_in\n       (SUC_MODN\n          (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 2 lt_2_4)))))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintro H'.\nunfold SUC_MODN at 3 6 in |- *;\n elim (less_or_eq (exist (fun p : nat => p < 4) 2 lt_2_4)); \n simpl in |- *; auto.\nintro y'.\nunfold SUC_MODN at 2 4 in |- *;\n elim (less_or_eq (exist (fun n : nat => n < 4) 3 y')); \n simpl in |- *; auto.\nintro Abs; absurd (4 < 4); auto with arith.\nintro y''.\nunfold SUC_MODN in |- *;\n elim (less_or_eq (exist (fun n : nat => n < 4) 0 (Ex_n_lt_gen y'')));\n simpl in |- *; auto.\nclear y''; intro y''.\nrewrite d_In_SUCSUCSUC_SSO_l4.\nelim (less_or_eq (exist (fun p : nat => p < 4) 2 lt_2_4)); simpl in |- *.\nintro a.\nelim (less_or_eq (exist (fun n : nat => n < 4) 3 a)); simpl in |- *.\nintro Abs; absurd (4 < 4); auto with arith.\nintro a'.\nunfold SUC_MODN in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 0 (Ex_n_lt_gen a')));\n simpl in |- *.\nintro a0.\nrewrite not_d_In_SUCSUC_SSO_l4.  \nauto.\nauto.\nintro Abs; absurd (1 = 4); auto.\nintro Abs; absurd (3 = 4); auto.\nauto.\nintro Abs; absurd (1 = 4); auto.\nintro Abs; absurd (3 = 4); auto.\nintro H'.\nrewrite not_d_In_SUCSUCSUC_SSO_l4. \nelim\n (In_or_not eq_nat_dec\n    (no_in\n       (SUC_MODN\n          (SUC_MODN\n             (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 2 lt_2_4))))))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l)))).\nintro H''.\nunfold Convert_port_list2 in |- *.\ngeneralize eq_n_SM4_4_times; unfold SM4 in |- *; intros Sm4.\nelim (Sm4 (exist (fun p : nat => p < 4) 2 lt_2_4)).\nsimpl in |- *.\nrewrite not_d_In_SUCSUC_SSO_l4.\nsimpl in |- *; auto.\nauto.\nintro H''.\nunfold SUC_MODN at 4 8 in |- *; simpl in |- *.\nunfold Convert_port_list2 in |- *.\nelim (less_or_eq (exist (fun p : nat => p < 4) 2 lt_2_4)); simpl in |- *. \nintro a0.\nunfold SUC_MODN at 3 6 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 3 a0)); simpl in |- *.\nintro a1.\nunfold SUC_MODN at 2 4 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 4 a1)); simpl in |- *.\nintro Abs; absurd (5 < 4); auto with arith.\nintro Abs; absurd (5 = 4); auto.\nintro b0.\nunfold SUC_MODN at 2 4 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 0 (Ex_n_lt_gen b0)));\n simpl in |- *.\nunfold SUC_MODN at 1 2 in |- *; simpl in |- *.\nintro a1.\nelim (less_or_eq (exist (fun n : nat => n < 4) 1 a1)); simpl in |- *.\nrewrite not_d_In_SUCSUC_SSO_l4.\nauto.\nauto.\nintro Abs; absurd (2 = 4); auto.\nintro Abs; absurd (1 = 4); auto.\nintro Abs; absurd (3 = 4); auto.\nauto.\nauto.\nauto.\nQed.\n\n\n\n\nLemma Arbiter_last_ft :\n forall l : d_list bool 4,\n Ackor l = true ->\n Fst_of_l2 (Grant_for_Out l (List2 false true)) =\n Jk (Arb_xel (Scd_of_l4 l) true (Fth_of_l4 l) (Thd_of_l4 l))\n   (Scd_of_l2 (Arbx true l)) false /\\\n Scd_of_l2 (Grant_for_Out l (List2 false true)) =\n Jk (J_Arby false l) (Scd_of_l2 (Arby false l)) true.\n\nintros l H.\nunfold Grant_for_Out in |- *.\nunfold SuccessfulInput in |- *.\nrewrite RoundRobinArbiter_simpl.\nunfold RoundRobin in |- *.\nunfold Convert_list2_port in |- *; simpl in |- *.\nelim\n (In_or_not eq_nat_dec\n    (no_in (SUC_MODN (exist (fun p : nat => p < 4) 1 lt_1_4)))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintro H'.\nunfold SUC_MODN in |- *;\n elim (less_or_eq (exist (fun p : nat => p < 4) 1 lt_1_4)); \n simpl in |- *; auto.\nunfold Arby in |- *; unfold K_Arby in |- *.\nrewrite d_In_SUC1_l4.\nelim orb_sym; auto.\nauto.\nintro Abs; absurd (2 = 4); auto.\nintro non.\nunfold Arby in |- *; unfold K_Arby in |- *.\nrewrite not_d_In_SUC1_l4.\nclear non.\nelim\n (In_or_not eq_nat_dec\n    (no_in (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 1 lt_1_4))))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintro H'.\nunfold SUC_MODN at 2 4 in |- *;\n elim (less_or_eq (exist (fun p : nat => p < 4) 1 lt_1_4)); \n simpl in |- *; auto.\nintro y'.\nunfold SUC_MODN in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 2 y')); simpl in |- *.\nintro a0.\nrewrite d_In_SUCSUC1_l4.\nauto.\nauto.\nintro Abs; absurd (3 = 4); auto.\nintro Abs; absurd (2 = 4); auto.\nintro non.\nrewrite not_d_In_SUCSUC1_l4.\nelim\n (In_or_not eq_nat_dec\n    (no_in\n       (SUC_MODN\n          (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 1 lt_1_4)))))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintro H'.\nrewrite d_In_SUCSUCSUC_SO_l4.\nauto.\nunfold SUC_MODN at 3 6 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun p : nat => p < 4) 1 lt_1_4)); simpl in |- *.\nintro a; unfold SUC_MODN at 2 4 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 2 a)); simpl in |- *.\nunfold SUC_MODN in |- *; intro a0.\nelim (less_or_eq (exist (fun n : nat => n < 4) 3 a0)); simpl in |- *.\nintro Abs; absurd (4 < 4); auto with arith.\nauto.\nintro Abs; absurd (3 = 4); auto.\nintro Abs; absurd (2 = 4); auto.\nauto.\nintro H'.\nunfold Convert_port_list2 in |- *; simpl in |- *.\nelim\n (In_or_not eq_nat_dec\n    (no_in\n       (SUC_MODN\n          (SUC_MODN\n             (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 1 lt_1_4))))))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintro H''.\nsimpl in |- *.\nunfold SUC_MODN at 4 8 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun p : nat => p < 4) 1 lt_1_4)); simpl in |- *.\nintro a.\nunfold SUC_MODN at 3 6 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 2 a)); simpl in |- *.\nintro a0.\nunfold SUC_MODN at 2 4 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 3 a0)); simpl in |- *.\nintro Abs; absurd (4 < 4); auto with arith.\nintro b; unfold SUC_MODN in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 0 (Ex_n_lt_gen b)));\n simpl in |- *.\nintro b0.\nrewrite not_d_In_SUCSUCSUC_SO_l4.\nauto.\nauto.\nintro Abs; absurd (1 = 4); auto.\nintro Abs; absurd (3 = 4); auto.\nintro Abs; absurd (2 = 4); auto.\nintro H''.\nunfold SUC_MODN at 4 8 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun p : nat => p < 4) 1 lt_1_4)); simpl in |- *.\nintro a.\nunfold SUC_MODN at 3 6 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 2 a)); simpl in |- *.\nintro a0.\nunfold SUC_MODN at 2 4 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 3 a0)); simpl in |- *.\nintro Abs; absurd (4 < 4); auto with arith.\nintro b; unfold SUC_MODN in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 0 (Ex_n_lt_gen b)));\n simpl in |- *.\nintro b0.\nrewrite not_d_In_SUCSUCSUC_SO_l4.\nauto.\nauto.\nintro Abs; absurd (1 = 4); auto.\nintro Abs; absurd (3 = 4); auto.\nintro Abs; absurd (2 = 4); auto.\nauto.\nauto.\nauto.\nQed.\n\n\n\n\n\nLemma Arbiter_last_ff :\n forall l : d_list bool 4,\n Ackor l = true ->\n Fst_of_l2 (Grant_for_Out l (List2 false false)) =\n Jk (Arb_xel (Scd_of_l4 l) false (Fth_of_l4 l) (Thd_of_l4 l))\n   (Scd_of_l2 (Arbx false l)) false /\\\n Scd_of_l2 (Grant_for_Out l (List2 false false)) =\n Jk (J_Arby false l) (Scd_of_l2 (Arby false l)) false.\nintros l H.\nunfold Grant_for_Out in |- *.\nunfold SuccessfulInput in |- *.\nrewrite RoundRobinArbiter_simpl.\nunfold RoundRobin in |- *.\nunfold Convert_list2_port in |- *; simpl in |- *.\nelim\n (In_or_not eq_nat_dec\n    (no_in (SUC_MODN (exist (fun p : nat => p < 4) 0 lt_O_4)))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintros H'.\nunfold Convert_port_list2 in |- *.\nreplace (no_in (SUC_MODN (exist (fun p : nat => p < 4) 0 lt_O_4))) with 1;\n simpl in |- *; auto.\nunfold J_Arby in |- *.\nrewrite d_In_SUC0_l2.\nunfold Arb_yel in |- *; unfold Arb_xel in |- *; unfold AO in |- *;\n simpl in |- *.\nelim orb_sym; auto.\nauto.\nunfold SUC_MODN in |- *;\n elim (less_or_eq (exist (fun p : nat => p < 4) 0 lt_O_4)); \n simpl in |- *; auto.\nintros Abs; absurd (1 = 4); auto.\nintro non.\nunfold J_Arby in |- *.\nrewrite not_d_In_SUC0_l2.\nclear non.\nelim\n (In_or_not eq_nat_dec\n    (no_in (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 0 lt_O_4))))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintro H'.\nunfold Convert_port_list2 in |- *.\nreplace (no_in (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 0 lt_O_4))))\n with 2; simpl in |- *; auto.\nrewrite d_In_SUC1_l3.\nelim orb_sym; auto.\nauto.\nunfold SUC_MODN at 2 in |- *;\n elim (less_or_eq (exist (fun p : nat => p < 4) 0 lt_O_4)); \n simpl in |- *; auto.\nintro y'.\nunfold SUC_MODN in |- *;\n elim (less_or_eq (exist (fun n : nat => n < 4) 1 y')); \n simpl in |- *; auto. \nintro Abs; absurd (2 = 4); auto with arith.\nintro Abs; absurd (1 = 4); auto.\nintro non.\nrewrite not_d_In_SUC1_l3.\nclear non.\nelim\n (In_or_not eq_nat_dec\n    (no_in\n       (SUC_MODN\n          (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 0 lt_O_4)))))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintro H'.\nunfold SUC_MODN at 3 6 in |- *;\n elim (less_or_eq (exist (fun p : nat => p < 4) 0 lt_O_4)); \n simpl in |- *; auto.\nintro a.\nunfold SUC_MODN at 2 4 in |- *; simpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 1 a)); simpl in |- *.\nintro a0.\nunfold SUC_MODN in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 2 a0)); simpl in |- *.\nintro a1.\nunfold Convert_port_list2 in |- *; simpl in |- *.\nrewrite d_In_SUC2_l4.\nauto.\nauto.\nintro Abs; absurd (3 = 4); auto.\nintro Abs; absurd (2 = 4); auto.\nintro Abs; absurd (1 = 4); auto.\nintro non.\nelim\n (In_or_not eq_nat_dec\n    (no_in\n       (SUC_MODN\n          (SUC_MODN\n             (SUC_MODN (SUC_MODN (exist (fun p : nat => p < 4) 0 lt_O_4))))))\n    (d_map (no_in (i:=4)) (list_dlist (RequestsToArbitrate l))));\n simpl in |- *.\nintro H'.\nunfold Convert_port_list2 in |- *.\ngeneralize eq_n_SM4_4_times; unfold SM4 in |- *; intros Sm4.\nunfold SUC_MODN at 4 8 in |- *.\nsimpl in |- *.\nelim (less_or_eq (exist (fun p : nat => p < 4) 0 lt_O_4)); simpl in |- *.\nintro a.\nunfold SUC_MODN at 3 6 in |- *.\nsimpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 1 a)); simpl in |- *.\nintro a0.\nunfold SUC_MODN at 2 4 in |- *.\nsimpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 2 a0)); simpl in |- *.\nintro a1.\nunfold SUC_MODN in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 3 a1)); simpl in |- *.\nintro Abs; absurd (4 < 4); auto with arith.\nintro H0.\nrewrite not_d_In_SUC2_l4.\nauto.\nauto.\nintro Abs; absurd (3 = 4); auto.\nintro Abs; absurd (2 = 4); auto.\nintro Abs; absurd (1 = 4); auto.\nintro H'.\nunfold Convert_port_list2 in |- *.\nunfold SUC_MODN at 4 8 in |- *.\nsimpl in |- *.\nelim (less_or_eq (exist (fun p : nat => p < 4) 0 lt_O_4)); simpl in |- *.\nintro a.\nunfold SUC_MODN at 3 6 in |- *.\nsimpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 1 a)); simpl in |- *.\nintro a0.\nunfold SUC_MODN at 2 4 in |- *.\nsimpl in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 2 a0)); simpl in |- *.\nintro a1.\nunfold SUC_MODN in |- *.\nelim (less_or_eq (exist (fun n : nat => n < 4) 3 a1)); simpl in |- *.\nintro Abs; absurd (4 < 4); auto with arith.\nintro H0.\nrewrite not_d_In_SUC2_l4.\nauto.\nauto.\nintro Abs; absurd (3 = 4); auto.\nintro Abs; absurd (2 = 4); auto.\nintro Abs; absurd (1 = 4); auto.\nauto.\nauto.\nauto.\nQed.\n\n\n\nLemma Arbiter_last :\n forall (l : d_list bool 4) (b1 b2 : bool),\n Ackor l = true ->\n Fst_of_l2 (Grant_for_Out l (List2 b1 b2)) =\n Jk (Arb_xel (Scd_of_l4 l) b2 (Fth_of_l4 l) (Thd_of_l4 l))\n   (Scd_of_l2 (Arbx b2 l)) b1 /\\\n Scd_of_l2 (Grant_for_Out l (List2 b1 b2)) =\n Jk (J_Arby b1 l) (Scd_of_l2 (Arby b1 l)) b2.\nintros l b1 b2 H.\nelim b1; elim b2.\napply Arbiter_last_tt; try trivial.\napply Arbiter_last_tf; try trivial.\napply Arbiter_last_ft; try trivial.\napply Arbiter_last_ff; try trivial.\nQed.\n\n\n\n\nLemma Ackor_ltReq_false :\n forall (l : d_list bool 4) (g1 g2 : bool),\n Ackor l = false ->\n Jk (Arb_xel (Scd_of_l4 l) g2 (Fth_of_l4 l) (Thd_of_l4 l))\n   (Scd_of_l2 (Arbx g2 l)) g1 = g1 /\\\n Jk (J_Arby g1 l) (Scd_of_l2 (Arby g1 l)) g2 = g2.\nintros l g1 g2 H.\nunfold Arbx in |- *; unfold Arby in |- *; unfold J_Arby in |- *;\n unfold Arb_xel in |- *; unfold Arb_yel in |- *; unfold K_Arby in |- *;\n unfold Scd_of_l2 in |- *; unfold List2 in |- *; simpl in |- *.\nunfold Arb_yel in |- *; unfold AO in |- *; unfold AND2 in |- *;\n unfold OR2 in |- *.\nrewrite (Ackor_false_fst H).\nrewrite (Ackor_false_scd H).\nrewrite (Ackor_false_thd H).\nrewrite (Ackor_false_fth H); simpl in |- *.\nelim g1; elim g2; simpl in |- *; auto.\nQed.\n\n\nLemma Ackor_false :\n forall l : d_list bool 4,\n Ackor l = false ->\n Fst_of_l4 l = false /\\\n Scd_of_l4 l = false /\\ Thd_of_l4 l = false /\\ Fth_of_l4 l = false.\nintro l.\nelim (non_empty l).\nintros a H; elim H; clear H.\nintros t H; rewrite H; simpl in |- *.\nelim (non_empty t).\nintros b H0; elim H0; clear H0.\nintros t0 H0; rewrite H0; simpl in |- *.\nelim (non_empty t0).\nintros c H'; elim H'; clear H'.\nintros t' H'; rewrite H'; simpl in |- *.\nelim (non_empty t').\nintros d H''; elim H''; clear H''.\nintros t'' H''; rewrite H''; simpl in |- *.\nreplace t'' with (d_nil bool); auto.\nunfold Ackor in |- *; simpl in |- *.\nelim a; elim b; elim c; elim d; simpl in |- *; auto.\nQed.\n\n", "meta": {"author": "coq-contribs", "repo": "fairisle", "sha": "e36087a6b7e52ef3c6dcfdeba1298e8fde1260a0", "save_path": "github-repos/coq/coq-contribs-fairisle", "path": "github-repos/coq/coq-contribs-fairisle/fairisle-e36087a6b7e52ef3c6dcfdeba1298e8fde1260a0/Fairisle/PROOFS/Lemmas_Comb_Behaviour.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.21954587388326444}}
{"text": "Require Import List Bool.\nRequire Import ExtLib.Tactics.Consider.\nRequire MirrorShard.CancelTacBedrock.\nRequire MirrorShard.ExprUnify.\nRequire Import MirrorShard.Expr.\nRequire Import MirrorShard.Provers.\nRequire Import MirrorShard.SepExprTac.\nRequire Import ILEnv SepIL TacPackIL.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nModule CANCEL_TAC := \n  CancelTacBedrock.Make SepIL.ST SepIL.SEP SepIL.SH\n                        TacPackIL.SEP_LEMMA\n                        SUBST\n                        UNIFY\n                        UNF.\n\nModule SEP_TAC := MirrorShard.SepExprTac.Make SepIL.ST SepIL.SEP.\n\nSection canceller.\n  Variable ts : list Expr.type.\n  Let types := Env.repr BedrockCoreEnv.core ts.\n\n  Definition nexistsSubst (not : Prop -> Prop) (types : list type) (funcs : functions types) (sub : SUBST.Subst types) :=\n    fix existsSubst (meta vars : env types) (from : nat) \n    (vals : list tvar) (ret : env types -> Prop) {struct vals} : Prop :=\n    match vals with\n      | nil => ret meta\n      | t :: ts =>\n        match SUBST.Subst_lookup from sub with\n          | Some v =>\n            match exprD funcs meta vars v t with\n              | Some v0 =>\n                existsSubst (meta ++ existT (tvarD types) t v0 :: nil) vars\n                (S from) ts ret\n              | None =>\n                exists x : tvarD types t,\n                  existsSubst (meta ++ existT (tvarD types) t x :: nil) vars\n                  (S from) ts\n                  (fun g : env types =>\n                    match exprD funcs g vars v t with\n                      | Some y => x = y /\\ ret g\n                      | None => False\n                    end)\n            end\n          | None =>\n            exists x : tvarD types t,\n              existsSubst (meta ++ existT (tvarD types) t x :: nil) vars\n              (S from) ts ret\n        end\n    end.\n\n  Theorem nexistsSubst_existsSubst : nexistsSubst not = CANCEL_TAC.INS.existsSubst. \n  Proof. reflexivity. Qed.\n\n  Definition nSubst_equations_to (not : Prop -> Prop) (types : list type) (funcs : functions types) (uenv venv : env types)\n    (subst : SUBST.Subst types) from ls (rr : Prop) :=\n    (fix Subst_equations_to (from : nat) (ls : env types) {struct ls} : Prop :=\n    match ls with\n      | nil => rr\n      | l :: ls0 =>\n        match SUBST.Subst_lookup from subst with\n          | Some e =>\n            match ExprTac.nexprD not types funcs uenv venv e (projT1 l) with\n              | Some v => projT2 l = v\n              | None => False\n            end\n          | None => True\n        end /\\ Subst_equations_to (S from) ls0\n    end) from ls.\n  \n  Theorem nSubst_equations_to_Subst_equations_to : forall ts fs u v s r ls from,\n    @nSubst_equations_to not ts fs u v s from ls r <-> @SUBST.Subst_equations_to ts fs u v s from ls /\\ r.\n  Proof. \n    induction ls; simpl.\n    { intuition. }\n    { intros. rewrite IHls. intuition. }\n  Qed.\n  \n  Definition cancel (himp : hprop -> hprop -> Prop) (emp : hprop) (star : hprop -> hprop -> hprop) \n    (ex : forall T : Type, (T -> hprop) -> hprop) (inj : Prop -> hprop) (not : Prop -> Prop)\n    (boundf boundb : nat)\n    (ts : list Expr.type)\n    (funcs : Expr.functions (Env.repr ILEnv.BedrockCoreEnv.core ts))\n    (preds : SEP.predicates (Env.repr ILEnv.BedrockCoreEnv.core ts))\n    (algos : TacPackIL.ILAlgoTypes.AllAlgos (Env.repr ILEnv.BedrockCoreEnv.core ts))\n    (uvars : Expr.env (Env.repr ILEnv.BedrockCoreEnv.core ts))\n    (lhs rhs : SEP.sexpr (Env.repr ILEnv.BedrockCoreEnv.core ts))\n    (hyps : Expr.exprs (Env.repr ILEnv.BedrockCoreEnv.core ts)) : Prop :=\n    let types := Env.repr ILEnv.BedrockCoreEnv.core ts in\n    let hints :=\n      match TacPackIL.ILAlgoTypes.Hints algos with\n        | Some x => x\n        | None =>\n          {| TacPackIL.UNF.Forward := nil\n           ; TacPackIL.UNF.Backward := nil |}\n      end in\n    let prover :=\n      match TacPackIL.ILAlgoTypes.Prover algos with\n        | Some x => x\n        | None =>\n          Provers.trivialProver (Env.repr ILEnv.BedrockCoreEnv.core ts)\n      end in\n    let tfuncs := typeof_funcs funcs in\n    let tpreds := SEP.typeof_preds preds in\n    if SEP.WellTyped_sexpr tfuncs tpreds (typeof_env uvars) nil rhs then\n      match CANCEL_TAC.canceller tpreds (TacPackIL.UNF.Forward hints) (TacPackIL.UNF.Backward hints) prover boundf boundb (typeof_env uvars) hyps lhs rhs with\n        | None => \n          himp (SEP_TAC.nsexprD not emp star ex inj types funcs preds uvars nil lhs)\n               (SEP_TAC.nsexprD not emp star ex inj types funcs preds uvars nil rhs)\n        | Some {| CANCEL_TAC.AllExt := new_vars\n                ; CANCEL_TAC.ExExt := new_uvars\n                ; CANCEL_TAC.Lhs := lhs'\n                ; CANCEL_TAC.Rhs := rhs'\n                ; CANCEL_TAC.Subst := subst |} =>\n          forallEach new_vars (fun nvs : env types =>\n             let var_env := nvs in\n             ExprTac.nAllProvable_impl not _ funcs uvars var_env\n               (nexistsSubst not funcs subst uvars var_env (length uvars) new_uvars\n                 (fun meta_env0 : env types =>\n                    nSubst_equations_to not funcs meta_env0 var_env subst 0 uvars \n                      (ExprTac.nAllProvable_and not _ funcs meta_env0 var_env\n                        (himp\n                           (SEP_TAC.nsexprD not emp star ex inj types funcs preds meta_env0 var_env\n                              (SH.sheapD\n                                 {| SH.impures := SH.impures lhs'\n                                  ; SH.pures := nil\n                                  ; SH.other := SH.other lhs' |}))\n                           (SEP_TAC.nsexprD not emp star ex inj types funcs preds meta_env0 var_env\n                              (SH.sheapD\n                                 {| SH.impures := SH.impures rhs'\n                                  ; SH.pures := nil\n                                  ; SH.other := SH.other rhs' |})))\n                        (SH.pures rhs')))) (SH.pures lhs'))\n\n        end\n    else\n      himp (SEP_TAC.nsexprD not emp star ex inj types funcs preds uvars nil lhs)\n           (SEP_TAC.nsexprD not emp star ex inj types funcs preds uvars nil rhs).\n\n  Theorem ApplyCancelSep_slice (boundf boundb : nat) : forall (ts : list Expr.type)\n      (funcs : Expr.functions (Env.repr ILEnv.BedrockCoreEnv.core ts))\n      (preds : SEP.predicates (Env.repr ILEnv.BedrockCoreEnv.core ts))\n      (algos : TacPackIL.ILAlgoTypes.AllAlgos\n        (Env.repr ILEnv.BedrockCoreEnv.core ts)),\n      TacPackIL.ILAlgoTypes.AllAlgos_correct (types := Env.repr ILEnv.BedrockCoreEnv.core ts) funcs preds algos ->\n      forall (uvars : Expr.env (Env.repr ILEnv.BedrockCoreEnv.core ts))\n        (lhs rhs : SEP.sexpr (Env.repr ILEnv.BedrockCoreEnv.core ts))\n        (hyps : Expr.exprs (Env.repr ILEnv.BedrockCoreEnv.core ts)),\n        Expr.AllProvable funcs uvars nil hyps ->\n        (cancel himp emp star ex inj not boundf boundb funcs preds algos uvars lhs rhs hyps) ->\n        SEP.himp funcs preds uvars nil lhs rhs.\n  Proof.\n    Opaque Env.repr.\n    intros. unfold cancel in *; simpl in *.    \n    consider (SEP.WellTyped_sexpr (typeof_funcs funcs) (SEP.typeof_preds preds) (typeof_env uvars) nil rhs); intros; eauto.\n    consider (CANCEL_TAC.canceller (SEP.typeof_preds preds)\n           (UNF.Forward\n              match ILAlgoTypes.Hints algos with\n              | Some x => x\n              | None => {| UNF.Forward := nil; UNF.Backward := nil |}\n              end)\n           (UNF.Backward\n              match ILAlgoTypes.Hints algos with\n              | Some x => x\n              | None => {| UNF.Forward := nil; UNF.Backward := nil |}\n              end)\n           match ILAlgoTypes.Prover algos with\n           | Some x => x\n           | None => trivialProver (Env.repr BedrockCoreEnv.core ts0)\n           end boundf boundb (typeof_env uvars) hyps lhs rhs); intros.\n    { eapply CANCEL_TAC.ApplyCancelSep_with_eq in H1; eauto. \n      { destruct X. destruct (ILAlgoTypes.Hints algos); eauto using UNF.ForwardOk.\n        simpl. constructor. }\n      { destruct X. destruct (ILAlgoTypes.Hints algos); eauto using UNF.BackwardOk.\n        simpl. constructor. }\n      { destruct X. destruct (ILAlgoTypes.Prover algos); eauto using trivialProver_correct. }\n      { eapply typeof_funcs_WellTyped_funcs. } \n      { rewrite nexistsSubst_existsSubst in *. \n        destruct c. apply forallEach_sem. intros.\n        eapply forallEach_sem in H2; eauto.\n        rewrite ExprTac.nAllProvable_impl_AllProvable_impl in H2.\n        apply AllProvable_impl_sem; intros.\n        apply AllProvable_impl_sem in H2; eauto.\n        eapply CANCEL_TAC.INS.existsSubst_sem in H2. eapply existsEach_sem in H2. destruct H2; intuition.\n        eapply CANCEL_TAC.INS.existsSubst_sem. eapply existsEach_sem. exists x.\n        change (fun A : Prop => A -> False) with not in *.\n        rewrite nSubst_equations_to_Subst_equations_to in *. intuition.\n        rewrite ExprTac.nAllProvable_and_AllProvable_and in H8. intuition. } }\n    { apply H2. }\n  Qed.\n\nEnd canceller.\n", "meta": {"author": "gmalecha", "repo": "bedrock-mirror-shard", "sha": "ea7e5ad56a1d6392468b6823e0457dd44524bca7", "save_path": "github-repos/coq/gmalecha-bedrock-mirror-shard", "path": "github-repos/coq/gmalecha-bedrock-mirror-shard/bedrock-mirror-shard-ea7e5ad56a1d6392468b6823e0457dd44524bca7/src/CancelTacIL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.21954586785042035}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Coq.Classes.RelationClasses.\nRequire Import Program.\n\nFrom Fairness Require Import Axioms.\nFrom Fairness Require Export ITreeLib FairBeh FairSim NatStructsLarge.\nFrom Fairness Require Import pind PCMLarge World WFLibLarge ThreadsURA.\nFrom Fairness Require Import Mod ModSimYOrd ModSimStid.\n\nSet Implicit Arguments.\n\nSection PROOF.\n\n  Context `{M: URA.t}.\n\n  Variable state_src: Type.\n  Variable state_tgt: Type.\n\n  Variable ident_src: ID.\n  Variable _ident_tgt: ID.\n  Let ident_tgt := sum_tid _ident_tgt.\n\n  Variable wf_src: WF.\n  Variable wf_tgt: WF.\n\n  Hypothesis wf_tgt_inhabited: inhabited wf_tgt.(T).\n  Hypothesis wf_tgt_open: forall (o0: wf_tgt.(T)), exists o1, wf_tgt.(lt) o0 o1.\n\n  Let srcE := ((@eventE ident_src +' cE) +' sE state_src).\n  Let tgtE := ((@eventE _ident_tgt +' cE) +' sE state_tgt).\n\n  Let shared :=\n        (TIdSet.t *\n           (@imap ident_src wf_src) *\n           (@imap ident_tgt wf_tgt) *\n           state_src *\n           state_tgt)%type.\n  Let shared_rel: Type := shared -> Prop.\n  Variable I: shared -> URA.car -> Prop.\n\n  Variable wf_stt: Type -> Type -> WF.\n  Variable wf_stt0: forall R0 R1, (wf_stt R0 R1).(T).\n\n\n  Let ident_src2 := sum_tid ident_src.\n\n  Let wf_src_th {R0 R1}: WF := clos_trans_WF (prod_WF (prod_WF (wf_stt R0 R1) wf_tgt) (nmo_wf (wf_stt R0 R1))).\n  Let wf_src2 {R0 R1}: WF := sum_WF (@wf_src_th R0 R1) wf_src.\n\n  Let srcE2 := ((@eventE ident_src2 +' cE) +' sE state_src).\n  Let shared2 {R0 R1} :=\n        (TIdSet.t *\n           (@imap ident_src2 (@wf_src2 R0 R1)) *\n           (@imap ident_tgt wf_tgt) *\n           state_src *\n           state_tgt)%type.\n  Let shared2_rel {R0 R1}: Type := (@shared2 R0 R1) -> Prop.\n\n  Let M2 {R0 R1}: URA.t := URA.prod (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)) M.\n\n  Definition shared_thsRA {R0 R1}\n             (ost: NatMap.t (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T))\n    : @thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T) :=\n    (fun tid => match NatMap.find tid ost with\n             | Some osot => ae_black osot\n             | None => ae_black (wf_stt0 R0 R1, wf_stt0 R0 R1) ⋅ ae_white (wf_stt0 R0 R1, wf_stt0 R0 R1)\n             end).\n\n  Definition Is {R0 R1}:\n    (TIdSet.t * (@imap thread_id (@wf_src_th R0 R1)) * (@imap ident_tgt wf_tgt))%type ->\n    (@URA.car (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T))) -> Prop :=\n    fun '(ths, im_src, im_tgt) ths_r =>\n      exists (ost: NatMap.t (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)),\n        (<<WFOST: nm_wf_pair ths ost>>) /\\\n          (<<TRES: ths_r = shared_thsRA ost>>) /\\\n          (<<IMSRC: forall tid (IN: NatMap.In tid ths)\n                      os ot (FIND: NatMap.find tid ost = Some (os, ot)),\n              wf_src_th.(lt) ((ot, im_tgt (inl tid)), nm_proj_v1 ost) (im_src tid)>>).\n\n  Definition I2 {R0 R1}: (@shared2 R0 R1) -> (@URA.car (@M2 R0 R1)) -> Prop :=\n    fun '(ths, im_src, im_tgt, st_src, st_tgt) '(ths_r, r) =>\n      exists im_src_th im_src_us,\n        (<<ICOMB: im_src = imap_comb im_src_th im_src_us>>) /\\\n          (<<INV: I (ths, im_src_us, im_tgt, st_src, st_tgt) r>>) /\\\n          (<<INVS: Is (ths, im_src_th, im_tgt) ths_r>>).\n\n\n  Lemma shared_thsRA_th_has_wf_find\n        tid\n        R0 R1\n        ost os ot\n        (ctx_r: (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)))\n        (VALS: URA.wf ((shared_thsRA ost) ⋅ (th_has tid (os, ot)) ⋅ ctx_r))\n    :\n    NatMap.find tid ost = Some (os, ot).\n  Proof.\n    ur in VALS. specialize (VALS tid). eapply URA.wf_mon in VALS.\n    unfold shared_thsRA in VALS. rewrite th_has_hit in VALS.\n    des_ifs.\n    - ur in VALS. des. rewrite URA.unit_idl in VALS.\n      unfold URA.extends in VALS. des. ur in VALS. des_ifs.\n    - rewrite <- URA.add_assoc in VALS. rewrite URA.add_comm in VALS. eapply URA.wf_mon in VALS.\n      ur in VALS. ur in VALS. ss.\n  Qed.\n\n  Lemma shared_thsRA_th_has_wf_update\n        tid\n        R0 R1\n        ost os ot\n        (ctx_r: (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)))\n        (VALS: URA.wf ((shared_thsRA ost) ⋅ (th_has tid (os, ot)) ⋅ ctx_r))\n        os1 ot1\n    :\n    URA.wf ((shared_thsRA (NatMap.add tid (os1, ot1) ost)) ⋅ (th_has tid (os1, ot1)) ⋅ ctx_r).\n  Proof.\n    hexploit shared_thsRA_th_has_wf_find; eauto. intro FIND.\n    ur. ur in VALS. i. specialize (VALS k).\n    destruct (tid_dec k tid); clarify.\n    - rewrite th_has_hit in *. unfold shared_thsRA in *.\n      rewrite nm_find_add_eq. rewrite FIND in VALS.\n      ur. ur in VALS. des_ifs. des. split.\n      + rewrite URA.unit_idl in VALS. unfold URA.extends in *. des.\n        r_solve. ss. exists ctx. ur in VALS. ur. des_ifs.\n      + ur. ss.\n    - rewrite th_has_miss in *; auto. rewrite URA.unit_id in VALS. r_solve.\n      unfold shared_thsRA in *. rewrite nm_find_add_neq; auto.\n  Qed.\n\n  Lemma shared_thsRA_th_has_wf_wf_pair\n        tid\n        R0 R1\n        (ths: TIdSet.t)\n        ost os ot\n        (ctx_r: (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)))\n        (VALS: URA.wf ((shared_thsRA ost) ⋅ (th_has tid (os, ot)) ⋅ ctx_r))\n        (WFP: nm_wf_pair ths ost)\n        os1 ot1\n    :\n    nm_wf_pair ths (NatMap.add tid (os1, ot1) ost).\n  Proof.\n    replace ths with (NatMap.add tid tt ths). apply nm_wf_pair_add; auto.\n    apply nm_eq_is_equal. ii. destruct (tid_dec y tid); clarify.\n    2:{ rewrite nm_find_add_neq; auto. }\n    rewrite nm_find_add_eq. symmetry.\n    destruct (NatMap.find tid ths) eqn:FIND; ss. destruct u; auto.\n    hexploit shared_thsRA_th_has_wf_find. eapply VALS. i.\n    hexploit nm_wf_pair_find_cases; eauto. i; des. eapply H0 in FIND.\n    ss. clarify.\n  Qed.\n\n\n  Lemma local_RR_impl\n        tid\n        R0 R1 (RR: R0 -> R1 -> Prop)\n        ths\n        (im_src: @imap ident_src2 (@wf_src2 R0 R1))\n        im_src_th im_src_us\n        (ICOMB: im_src = imap_comb im_src_th im_src_us)\n        (im_tgt: @imap ident_tgt wf_tgt)\n        st_src st_tgt r_ctx\n        r0 r1\n        (LRR: ModSimYOrd.local_RR I RR tid r0 r1 r_ctx (ths, im_src_us, im_tgt, st_src, st_tgt))\n        (ths_r ctx_r: (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)))\n        os ot\n        (INVS: Is (ths, im_src_th, im_tgt) ths_r)\n        (VALS: URA.wf (ths_r ⋅ (th_has tid (os, ot)) ⋅ ctx_r))\n    :\n    ModSimStid.local_RR I2 RR tid r0 r1 (ctx_r, r_ctx) (ths, im_src, im_tgt, st_src, st_tgt).\n  Proof.\n    unfold ModSimYOrd.local_RR in LRR. des. unfold local_RR.\n    unfold Is in INVS. des. set (ost':=NatMap.remove tid ost).\n    clarify. esplits; eauto.\n    - instantiate (1:=(ε, r_own)). instantiate (1:=(shared_thsRA ost', r_shared)).\n      ur. split; auto. hexploit shared_thsRA_th_has_wf_find; eauto. intro FIND.\n      r_solve. ur. ur in VALS. i. specialize (VALS k).\n      destruct (tid_dec k tid); clarify.\n      + rewrite th_has_hit in VALS. unfold shared_thsRA in *.\n        subst ost'. rewrite nm_find_rm_eq. rewrite FIND in VALS.\n        ur. ur in VALS. des_ifs. des. split.\n        * rewrite URA.unit_idl in VALS. unfold URA.extends in *. des.\n          r_solve. ss. exists ctx. ur in VALS. ur. des_ifs.\n        * ur. ss.\n      + rewrite th_has_miss in VALS; auto. rewrite URA.unit_id in VALS.\n        unfold shared_thsRA in *. subst ost'. rewrite nm_find_rm_neq; auto.\n\n    - unfold I2. esplits; eauto. unfold Is. exists ost'. splits; auto.\n      { subst ost'. eapply nm_wf_pair_rm; auto. }\n      i. specialize (IMSRC tid0). destruct (tid_dec tid0 tid); clarify.\n      { exfalso. apply NatMap.remove_1 in IN; auto. }\n      hexploit IMSRC; clear IMSRC.\n      { eapply NatMapP.F.remove_neq_in_iff; eauto. }\n      { subst ost'. rewrite nm_find_rm_neq in FIND; eauto. }\n      i. ss. eapply clos_trans_n1_trans. 2: eapply H.\n      econs 1. econs 2. auto.\n      subst ost'. econs. instantiate (1:=tid).\n      { unfold nm_proj_v1. rewrite <- nm_map_rm_comm_eq. rewrite nm_find_rm_eq.\n        assert (FINDOST: NatMap.find tid ost = Some (os, ot)).\n        { eapply shared_thsRA_th_has_wf_find. eapply VALS. }\n        rewrite NatMapP.F.map_o. rewrite FINDOST. ss. econs.\n      }\n      { i. unfold nm_proj_v1. rewrite <- nm_map_rm_comm_eq. rewrite nm_find_rm_neq; auto. }\n  Qed.\n\n\n  Let St: wf_tgt.(T) -> wf_tgt.(T) := fun o0 => @epsilon _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) o0 o1).\n  Let lt_succ_diag_r_tgt: forall (t: wf_tgt.(T)), wf_tgt.(lt) t (St t).\n  Proof.\n    i. unfold St. hexploit (@epsilon_spec _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) t o1)); eauto.\n  Qed.\n\n  Lemma yord_implies_stid\n        tid\n        R0 R1 (RR: R0 -> R1 -> Prop)\n        ths\n        (im_src: @imap ident_src2 (@wf_src2 R0 R1))\n        im_src_th im_src_us\n        (ICOMB: im_src = imap_comb im_src_th im_src_us)\n        (im_tgt: @imap ident_tgt wf_tgt)\n        st_src st_tgt\n        ps pt r_ctx src tgt\n        os ot\n        (LSIM: ModSimYOrd.lsim I wf_stt tid (ModSimYOrd.local_RR I RR tid)\n                               ps pt r_ctx (os, src) (ot, tgt)\n                               (ths, im_src_us, im_tgt, st_src, st_tgt))\n        (ths_r ctx_r: (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)))\n        (INVS: Is (ths, im_src_th, im_tgt) ths_r)\n        (VALS: URA.wf (ths_r ⋅ (th_has tid (os, ot)) ⋅ ctx_r))\n    :\n    ModSimStid.lsim I2 tid (ModSimStid.local_RR I2 RR tid) ps pt (ctx_r, r_ctx) src tgt\n                    (ths, im_src, im_tgt, st_src, st_tgt).\n  Proof.\n    revert_until R1. pcofix CIH; i.\n    match type of LSIM with ModSimYOrd.lsim _ _ _ ?_LRR0 _ _ _ ?_osrc ?_otgt ?_shr => remember _LRR0 as LRR0 in LSIM; remember _osrc as osrc; remember _otgt as otgt; remember _shr as shr end.\n    move LSIM before CIH. punfold LSIM. revert_until LSIM.\n    revert LRR0 ps pt r_ctx osrc otgt shr LSIM.\n    pinduction 7. i. clear LE. clarify.\n    rename x1 into ps, x2 into pt, x3 into r_ctx, PR into LSIM.\n    eapply pind9_unfold in LSIM; eauto with paco.\n    rename INVS into INVS0; assert (INVS:Is (ths, im_src_th, im_tgt) ths_r).\n    { auto. }\n    clear INVS0.\n    inv LSIM.\n\n    { pfold. eapply pind9_fold. econs 1. eapply local_RR_impl; eauto. }\n\n    { pfold. eapply pind9_fold. econs 2; eauto.\n      split; [|ss]. destruct LSIM0 as [LSIM IND].\n      eapply IH in IND. punfold IND.\n      { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. }\n      all: eauto.\n    }\n    { pfold. eapply pind9_fold. econs 3; eauto.\n      des. exists x.\n      split; [|ss]. destruct LSIM0 as [LSIM IND].\n      eapply IH in IND. punfold IND.\n      { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. }\n      all: eauto.\n    }\n    { pfold. eapply pind9_fold. econs 4; eauto.\n      split; [|ss]. destruct LSIM0 as [LSIM IND].\n      eapply IH in IND. punfold IND.\n      { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. }\n      all: eauto.\n    }\n    { pfold. eapply pind9_fold. econs 5; eauto.\n      split; [|ss]. destruct LSIM0 as [LSIM IND].\n      eapply IH in IND. punfold IND.\n      { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. }\n      all: eauto.\n    }\n    { pfold. eapply pind9_fold. econs 6; eauto. }\n\n    { pfold. eapply pind9_fold. econs 7; eauto.\n      des.\n      exists (fun idx => match idx with\n                 | inl t => inl (im_src_th t)\n                 | inr i => inr (im_src1 i)\n                 end).\n      esplits.\n      { clear - FAIR. ii. destruct i; ss. specialize (FAIR i). unfold prism_fmap in *; ss. des_ifs.\n        - econs 2. auto.\n        - rewrite FAIR. auto.\n      }\n      split; [|ss]. destruct LSIM as [LSIM IND].\n      eapply IH in IND. punfold IND.\n      { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. }\n      all: ss; eauto.\n    }\n\n    { pfold. eapply pind9_fold. econs 8; eauto.\n      split; [|ss]. destruct LSIM0 as [LSIM IND].\n      eapply IH in IND. punfold IND.\n      { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. }\n      all: eauto.\n    }\n    { pfold. eapply pind9_fold. econs 9; eauto.\n      i. specialize (LSIM0 x).\n      split; [|ss]. destruct LSIM0 as [LSIM IND].\n      eapply IH in IND. punfold IND.\n      { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. }\n      all: eauto.\n    }\n    { pfold. eapply pind9_fold. econs 10; eauto.\n      split; [|ss]. destruct LSIM0 as [LSIM IND].\n      eapply IH in IND. punfold IND.\n      { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. }\n      all: eauto.\n    }\n    { pfold. eapply pind9_fold. econs 11; eauto.\n      split; [|ss]. destruct LSIM0 as [LSIM IND].\n      eapply IH in IND. punfold IND.\n      { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. }\n      all: eauto.\n    }\n\n    { pfold. eapply pind9_fold. econs 12; eauto.\n      i. specialize (LSIM0 _ FAIR).\n      split; [|ss]. destruct LSIM0 as [LSIM IND].\n      eapply IH in IND. punfold IND.\n      { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. }\n      all: eauto.\n      clear - FAIR INVS. unfold Is in INVS. des. esplits; eauto. i. hexploit IMSRC; eauto; i.\n      replace (im_tgt1 (inl tid)) with (im_tgt (inl tid)); auto.\n      clear - FAIR. specialize (FAIR (inl tid)). ss.\n    }\n\n    { pfold. eapply pind9_fold. econs 13; eauto.\n      i. specialize (LSIM0 ret). pclearbot.\n      right. eapply CIH; eauto.\n    }\n\n    { pfold. eapply pind9_fold. econs 14. }\n\n    { pfold. eapply pind9_fold. econs 15; eauto.\n      des. unfold Is in INVS. des. subst.\n      set (ost':= NatMap.add tid (os1, ot1) ost).\n      assert (WFOST': nm_wf_pair ths ost').\n      { eapply shared_thsRA_th_has_wf_wf_pair; eauto. }\n      exists (fun idx => match idx with\n                 | inl t =>\n                     if (NatMapP.F.In_dec ths t)\n                     then match (NatMap.find t ost') with\n                          | None => inl (im_src_th t)\n                          | Some (_, ot) => inl ((ot, im_tgt (inl t)), nm_proj_v1 ost)\n                          end\n                     else inl (im_src_th t)\n                 | inr i => inr (im_src_us i)\n                 end).\n      splits.\n      { clear - LT IMSRC VALS WFOST WFOST'.\n        ii. unfold prism_fmap in *; ss. destruct i; ss. destruct (tids_fmap tid ths n) eqn:FM; auto.\n        - unfold tids_fmap in FM. destruct (Nat.eq_dec n tid) eqn:EQ; ss. destruct (NatMapP.F.In_dec ths n) eqn:INDEC; ss.\n          des_ifs.\n          2:{ exfalso. eapply NatMapP.F.in_find_iff; eauto.\n              apply nm_wf_pair_sym in  WFOST'. eapply nm_wf_pair_find_cases in WFOST'. des.\n              eapply WFOST' in Heq. auto.\n          }\n          hexploit IMSRC; clear IMSRC.\n          3:{ instantiate (1:=n). instantiate (1:=t0). i. econs 1. auto. }\n          auto.\n          subst ost'. rewrite nm_find_add_neq in Heq; eauto.\n        - unfold tids_fmap in FM. destruct (Nat.eq_dec n tid) eqn:EQ; ss. destruct (NatMapP.F.In_dec ths n) eqn:INDEC; ss.\n      }\n\n      split; [|ss]. destruct LSIM as [LSIM IND].\n      eapply IH in IND. punfold IND.\n      { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. }\n      6: instantiate (2:=shared_thsRA ost'). all: eauto.\n      - instantiate (1:= fun t => if NatMapP.F.In_dec ths t\n                               then\n                                 match NatMap.find t ost' with\n                                 | Some (_, ot0) => (ot0, im_tgt (inl t), nm_proj_v1 ost)\n                                 | None => (im_src_th t)\n                                 end\n                               else (im_src_th t)).\n        unfold imap_comb. clear. extensionality idx. des_ifs.\n      - exists ost'; splits; auto.\n        clear - LT IMSRC VALS WFOST WFOST'.\n        i. econs 1.\n        des_ifs. ss. econs 2; auto. econs. instantiate (1:=tid).\n        + unfold nm_proj_v1. rewrite !NatMapP.F.map_o.\n          replace (NatMap.find tid ost) with (Some (os, ot)).\n          subst ost'. rewrite nm_find_add_eq. ss. econs. auto.\n          symmetry. eapply shared_thsRA_th_has_wf_find; eauto.\n        + i. unfold nm_proj_v1. rewrite !NatMapP.F.map_o. subst ost'. rewrite nm_find_add_neq; auto.\n      - eapply shared_thsRA_th_has_wf_update; eauto.\n    }\n\n    { pfold. eapply pind9_fold. econs 16; eauto. instantiate (1:=(ths_r, r_shared)).\n      { unfold I2. esplits; eauto. }\n      instantiate (1:=(tid |-> (os, ot) , r_own)).\n      { ur. auto. }\n      clear - LSIM0 IH; i. unfold I2 in INV. destruct r_shared1 as [shared_r r_shared], r_ctx1 as [ctx_r r_ctx].\n      ur in VALID. des. specialize (LSIM0 _ _ _ _ _ _ _ INV VALID0 _ TGT). des.\n      unfold Is in INVS. des. subst. set (ost':= NatMap.add tid (os1, ot1) ost). clarify.\n      assert (WFOST': nm_wf_pair ths1 ost').\n      { eapply shared_thsRA_th_has_wf_wf_pair; eauto. }\n      split; [|ss]. destruct LSIM as [LSIM IND].\n      eapply IH in IND. punfold IND.\n      { ii. eapply pind9_mon_gen; eauto. ii. eapply __lsim_mon; eauto. }\n      all: eauto. instantiate (1:=shared_thsRA ost').\n\n      - exists ost'. splits; auto. i. specialize (IMSRC _ IN). unfold prism_fmap in *; ss. destruct (tid_dec tid0 tid); clarify.\n        + hexploit IMSRC. eapply shared_thsRA_th_has_wf_find; eauto.\n          i. subst ost'. rewrite nm_find_add_eq in FIND. clarify.\n          eapply clos_trans_n1_trans. 2: eapply H. econs 1. econs 1. econs 1. auto.\n        + subst ost'. rewrite nm_find_add_neq in FIND; auto.\n          hexploit IMSRC. eauto. i.\n          eapply clos_trans_n1_trans. 2: eapply H. econs 1. econs 1. econs 2; auto.\n          clear - n IN TGT. specialize (TGT (inl tid0)). ss. unfold tids_fmap in TGT. des_ifs.\n      - eapply shared_thsRA_th_has_wf_update; eauto.\n    }\n\n    { pfold. eapply pind9_fold. econs 17; eauto. instantiate (1:=(ths_r, r_shared)).\n      { unfold I2. esplits; eauto. }\n      instantiate (1:=(tid |-> (os, ot) , r_own)).\n      { ur. auto. }\n      revert LSIM0. clear_upto IH. i.\n      unfold I2 in INV. destruct r_shared1 as [shared_r r_shared], r_ctx1 as [ctx_r r_ctx].\n      ur in VALID. des. specialize (LSIM0 _ _ _ _ _ _ _ INV VALID0 _ TGT). des.\n      unfold Is in INVS. des. subst. set (ost':= NatMap.add tid (os1, ot1) ost).\n      assert (WFOST': nm_wf_pair ths1 ost').\n      { eapply shared_thsRA_th_has_wf_wf_pair; eauto. }\n      exists (fun idx => match idx with\n                 | inl t =>\n                     if (tid_dec t tid)\n                     then inl ((ot1, St (im_tgt2 (inl t))), nm_proj_v1 ost)\n                     else\n                       if (NatMapP.F.In_dec ths1 t)\n                       then match (NatMap.find t ost') with\n                            | None => inl (im_src_th t)\n                            | Some (_, ot) =>\n                                inl ((ot, im_tgt1 (inl t)), nm_proj_v1 ost)\n                            end\n                       else inl (im_src_th t)\n                 | inr i => inr (im_src_us i)\n                 end).\n      splits.\n\n      { clear - IMSRC VALID TGT WFOST WFOST'.\n        ii. unfold prism_fmap in *; ss. destruct i; ss. destruct (tids_fmap tid ths1 n) eqn:FM; auto.\n        - unfold tids_fmap in FM. destruct (Nat.eq_dec n tid) eqn:EQ; ss. destruct (NatMapP.F.In_dec ths1 n) eqn:INDEC; ss.\n          des_ifs.\n          2:{ exfalso. eapply NatMapP.F.in_find_iff; eauto.\n              apply nm_wf_pair_sym in  WFOST'. eapply nm_wf_pair_find_cases in WFOST'. des.\n              eapply WFOST' in Heq. auto.\n          }\n          hexploit IMSRC; clear IMSRC.\n          3:{ instantiate (1:=n). instantiate (1:=t0). i. econs 1. auto. }\n          auto.\n          subst ost'. rewrite nm_find_add_neq in Heq; eauto.\n        - unfold tids_fmap in FM. destruct (Nat.eq_dec n tid) eqn:EQ; ss. destruct (NatMapP.F.In_dec ths1 n) eqn:INDEC; ss.\n          des_ifs.\n      }\n\n      pclearbot. right. eapply CIH. 2:eauto.\n      3: instantiate (1:=shared_thsRA ost').\n      - instantiate (1:= fun t => if tid_dec t tid\n                               then (ot1, St (im_tgt2 (inl t)), nm_proj_v1 ost)\n                               else\n                                 if NatMapP.F.In_dec ths1 t\n                                 then\n                                   match NatMap.find t ost' with\n                                   | Some (_, ot0) => (ot0, im_tgt1 (inl t), nm_proj_v1 ost)\n                                   | None => (im_src_th t)\n                                   end\n                                 else (im_src_th t)).\n        unfold imap_comb. extensionality idx. des_ifs.\n      - exists ost'; splits; auto.\n        revert IMSRC VALID TGT WFOST WFOST'. clear_upto tid. i. subst.\n        i. econs 1. des_ifs; ss.\n        + subst ost'. rewrite nm_find_add_eq in FIND. clarify. econs 1. econs 2; auto.\n        + unfold prism_fmap in *; ss. rewrite FIND in Heq. clarify. econs 1. econs 2; auto.\n          clear - n IN TGT. specialize (TGT (inl tid0)). ss. unfold tids_fmap in TGT. des_ifs.\n        + rewrite FIND in Heq. ss.\n      - eapply shared_thsRA_th_has_wf_update; eauto.\n    }\n\n    { pfold. eapply pind9_fold. econs 18; eauto. pclearbot. right. eapply CIH; eauto. }\n\n  Qed.\n\n  Lemma init_src_inv\n        tid\n        R0 R1\n        ths\n        (im_src1: @imap ident_src2 (@wf_src2 R0 R1))\n        im_src_th1 im_src_us\n        (ICOMB: im_src1 = imap_comb im_src_th1 im_src_us)\n        (im_tgt1 im_tgt2: @imap ident_tgt wf_tgt)\n        (ths_r ctx_r: (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)))\n        os ot\n        (INVS: Is (ths, im_src_th1, im_tgt1) ths_r)\n        (VALS: URA.wf (ths_r ⋅ (th_has tid (os, ot)) ⋅ ctx_r))\n        (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths)))\n    :\n    exists im_src_th2,\n      (<<SRC: fair_update im_src1 (imap_comb im_src_th2 im_src_us) (prism_fmap inlp (tids_fmap tid ths))>>) /\\\n        (<<INVS: Is (ths, im_src_th2, im_tgt2) ths_r>>).\n  Proof.\n    unfold Is in INVS. des. clarify.\n    exists (fun t => if (tid_dec t tid)\n             then ((ot, St (im_tgt2 (inl t))), nm_proj_v1 ost)\n             else\n               if (NatMapP.F.In_dec ths t)\n               then match (NatMap.find t ost) with\n                    | None => (im_src_th1 t)\n                    | Some (_, ot) =>\n                        ((ot, im_tgt1 (inl t)), nm_proj_v1 ost)\n                    end\n               else (im_src_th1 t)).\n    splits.\n\n    - ii. destruct i; ss. unfold tids_fmap, prism_fmap in *; ss. destruct (Nat.eq_dec n tid) eqn:EQT; clarify.\n      destruct (NatMapP.F.In_dec ths n) eqn:INT; ss; clarify.\n      2:{ des_ifs; ss. }\n      clear EQT INT.\n      destruct (NatMap.find n ost) eqn:FIND.\n      2:{ exfalso. eapply NatMapP.F.in_find_iff in i.\n          eapply nm_wf_pair_sym in WFOST. hexploit nm_wf_pair_find_cases; eauto. i. des.\n          eapply H in FIND; clarify.\n      }\n      des_ifs. specialize (IMSRC _ i _ _ FIND). econs 1. eapply IMSRC.\n\n    - exists ost. splits; auto. i. unfold prism_fmap in *; ss. des_ifs.\n      + ss. hexploit shared_thsRA_th_has_wf_find. eapply VALS. intro FIND2.\n        ss; rewrite FIND in FIND2; clarify.\n        econs 1. econs 1. econs 2; auto.\n      + ss. econs 1. econs 1. econs 2; auto. clear - n i TGT.\n        specialize (TGT (inl tid0)). ss. unfold tids_fmap in TGT. des_ifs.\n  Qed.\n\nEnd PROOF.\n\nSection MODSIM.\n\n  Lemma yord_implies_stid_mod\n        md_src md_tgt\n        (MDSIM: ModSimYOrd.ModSim.mod_sim md_src md_tgt)\n    :\n    ModSimStid.ModSim.mod_sim md_src md_tgt.\n  Proof.\n    inv MDSIM.\n    set (ident_src := Mod.ident md_src). set (_ident_tgt := Mod.ident md_tgt).\n    set (state_src := Mod.state md_src). set (state_tgt := Mod.state md_tgt).\n    set (srcE := ((@eventE ident_src +' cE) +' sE state_src)).\n    set (tgtE := ((@eventE _ident_tgt +' cE) +' sE state_tgt)).\n    set (ident_tgt := @ident_tgt _ident_tgt).\n    set (shared := (TIdSet.t * (@imap ident_src wf_src) * (@imap ident_tgt wf_tgt) * state_src * state_tgt)%type).\n    set (ident_src2 := sum_tid ident_src).\n    set (wf_src_th := fun R0 R1 => clos_trans_WF (prod_WF (prod_WF (wf_stt R0 R1) wf_tgt) (nmo_wf (wf_stt R0 R1)))).\n    set (wf_src2 := fun R0 R1 => sum_WF (@wf_src_th R0 R1) wf_src).\n    (* set (I2 := fun R0 R1 => (I2 I wf_stt wf_stt0 (R0:=R0) (R1:=R1))). *)\n    set (M2 := fun R0 R1 => URA.prod (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)) world).\n    set (St := fun o0 => @epsilon _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) o0 o1)).\n    assert (lt_succ_diag_r_tgt: forall (t: wf_tgt.(T)), wf_tgt.(lt) t (St t)).\n    { i. unfold St. hexploit (@epsilon_spec _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) t o1)); eauto. }\n    ss.\n    (* eapply (@ModSim.mk _ _ (wf_src2 Any.t Any.t) _ wf_tgt_inhabited wf_tgt_open (M2 Any.t Any.t) (I2 Any.t Any.t)). *)\n    eapply (@ModSim.mk _ _ (wf_src2 Any.t Any.t) _ wf_tgt_inhabited wf_tgt_open (M2 Any.t Any.t)).\n    i. specialize (init im_tgt). des. rename init0 into funs.\n    set (I2 := fun R0 R1 => (I2 I wf_stt wf_stt0 (R0:=R0) (R1:=R1))).\n    exists (I2 Any.t Any.t). split.\n    (* assert (im_src_th: imap thread_id (@wf_src_th Any.t Any.t)). *)\n    (* { exact (fun t => ((wf_stt0 Any.t Any.t, im_tgt (inl t)), nm_proj_v1 ost)). } *)\n    (* exists (imap_comb im_src_th im_src). exists (shared_thsRA wf_stt wf_stt0 ost, r_shared). *)\n    { i.\n      (* move init after im_tgt. specialize (init im_tgt). des. *)\n      set (ost:= @NatMap.empty (prod (wf_stt Any.t Any.t).(T) (wf_stt Any.t Any.t).(T))).\n      assert (im_src_th: imap thread_id (@wf_src_th Any.t Any.t)).\n      { exact (fun t => ((wf_stt0 Any.t Any.t, im_tgt (inl t)), nm_proj_v1 ost)). }\n      exists (imap_comb im_src_th im_src). exists (shared_thsRA wf_stt wf_stt0 ost, r_shared).\n      unfold I2. unfold YOrd2Stid.I2. esplits; eauto.\n      - unfold Is. exists ost. splits; auto.\n        { subst ost. eapply nm_wf_pair_empty_empty_eq. }\n        i. eapply NatMapP.F.empty_in_iff in IN. ss.\n      - ur. split; auto. subst ost. ur. i. ur. split; ur; ss. des_ifs. unfold URA.extends.\n        exists ε. r_solve.\n    }\n\n    i. specialize (funs fn args). des_ifs.\n    unfold ModSimYOrd.local_sim in funs.\n    ii. unfold I2 in INV. unfold YOrd2Stid.I2 in INV.\n    rename r_shared into r_shared1.\n    destruct r_shared0 as [shared_r r_shared], r_ctx0 as [ctx_r r_ctx].\n    ur in VALID. des.\n    specialize (funs _ _ _ _ _ _ _ INV tid _ THS VALID0 _ UPD).\n    move funs after UPD. des. rename funs1 into LSIM. move LSIM before M2.\n    unfold Is in INVS. des. clarify.\n    set (ost':= NatMap.add tid (os, ot) ost).\n    exists (shared_thsRA wf_stt wf_stt0 ost', r_shared0), (tid |-> (os, ot), r_own).\n    set (im_src_th':= fun t => match (NatMap.find t ost') with\n                            | None => (im_src_th t)\n                            | Some (_, ot) => ((ot, St (im_tgt0' (inl t))), nm_proj_v1 ost')\n                            end).\n    remember (fun ti => match ti with | inl t => inl (im_src_th' t) | inr i => inr (im_src_us i) end) as im_src_tot. exists im_src_tot.\n    splits.\n\n    - unfold I2, YOrd2Stid.I2.  exists im_src_th', im_src_us. splits; auto.\n      exists ost'. splits; auto.\n      { subst ost'. clear - THS WFOST. inv THS. eapply nm_wf_pair_add. auto. }\n      i. inv THS. subst im_src_th'. ss. rewrite FIND.\n      econs 1. econs 1. econs 2; auto.\n    - ur; split; auto. subst ost'. ur. ur in VALID. i.\n      unfold shared_thsRA in *. specialize (VALID k1). destruct (tid_dec k1 tid); clarify.\n      + rewrite nm_find_add_eq. assert (NatMap.find tid ost = None).\n        { inv THS. eapply nm_wf_pair_find_cases in WFOST. des. eapply WFOST in NEW. auto. }\n        rewrite H in VALID. clear - VALID. rewrite th_has_hit.\n        ur. ur in VALID. des_ifs. des; split. 2: ur; ss.\n        unfold URA.extends in *. des. exists ctx. rewrite URA.unit_idl in VALID.\n        ur in VALID. r_solve. des_ifs; ur; auto.\n      + rewrite nm_find_add_neq; auto. rewrite th_has_miss. r_solve. des_ifs; auto. ii. clarify.\n    - subst. i. destruct r_shared2 as [shared_r2 r_shared2], r_ctx2 as [ctx_r2 r_ctx2].\n      unfold I2, YOrd2Stid.I2 in INV1. ur in VALID2. des.\n      move LSIM after TGT. specialize (LSIM _ _ _ _ _ _ _ INV1 VALID3 _ TGT).\n      des. hexploit init_src_inv. 1,2: eauto. 2: eapply INVS. 2: eapply VALID2. 2: eapply TGT.\n      instantiate (1:=im_src_us0). reflexivity. i. des.\n      subst im_src1. esplits. eapply SRC.\n      i. eapply yord_implies_stid; eauto.\n  Qed.\n\nEnd MODSIM.\n\n\nRequire Import List.\n\nSection AUX.\n\n  Import NatMap.\n  Import NatMapP.\n\n  Lemma nm_fold_prod_res\n        (world: URA.t) X pw rsost\n    :\n    NatMap.fold (fun (_ : NatMap.key) (r s : URA.prod (@thsRA (prod X X)) world) => r ⋅ s)\n                (NatMap.mapi (fun (t : NatMap.key) (rst : world * (X * X)) => (t |-> snd rst, fst rst)) rsost) pw\n    =\n      (NatMap.fold (fun (_ : NatMap.key) (r s : _) => r ⋅ s)\n                   (NatMap.mapi (fun (t : NatMap.key) (rst : world * (X * X)) => (t |-> snd rst)) rsost) (fst pw),\n        NatMap.fold (fun (_ : NatMap.key) (r s : _) => r ⋅ s)\n                    (NatMap.mapi (fun (t : NatMap.key) (rst : world * (X * X)) => (fst rst)) rsost) (snd pw)).\n  Proof.\n    rewrite ! NatMap.fold_1. ss. remember (NatMap.this rsost) as l. clear Heql rsost.\n    revert pw. induction l; ss.\n    { i. destruct pw. ss. }\n    i. des_ifs. ss. destruct p as [r [xs xt]]. ss.\n    rewrite IHl. destruct pw as [p w]. ss. f_equal.\n    - f_equal. repeat ur. des_ifs; ss.\n    - f_equal. repeat ur. des_ifs; ss.\n  Qed.\n\n  Lemma list_map_elements_nm_mapi\n    : forall (elt : Type) (m : NatMap.t elt) (elt1 : Type) (f: NatMap.key -> elt -> elt1),\n      List.map (fun '(k, e) => (k, f k e)) (NatMap.elements m) = NatMap.elements (NatMap.mapi f m).\n  Proof.\n    i. ss. unfold NatMap.elements. unfold NatMap.Raw.elements. destruct m. ss. clear sorted0.\n    rename this0 into l. induction l; ss. des_ifs. f_equal; auto.\n  Qed.\n\n  Lemma list_fold_left_resource_aux2\n        (world : URA.t) c X l\n    :\n    fold_left\n      (fun (a : world)\n         (p : NatMap.key * (world * X)) =>\n         (let '(r, _) := snd p in fun s : world => r ⋅ s) a) l ε ⋅ c =\n      fold_left\n        (fun (a : world)\n           (p : NatMap.key * (world * X)) =>\n           (let '(r, _) := snd p in fun s : world => r ⋅ s) a) l c.\n  Proof.\n    revert c. induction l; i; ss. r_solve. des_ifs. destruct a; ss. clarify; ss. rewrite <- (IHl (c0 ⋅ ε)). r_solve.\n    rewrite <- (IHl (c0 ⋅ c)). r_solve.\n  Qed.\n\n  Lemma nm_map_empty\n        e0 e1 (f: e0 -> e1)\n    :\n    NatMap.map f (NatMap.empty e0) = (NatMap.empty e1).\n  Proof.\n    eapply nm_empty_eq. eapply nm_map_empty1. apply NatMap.empty_1.\n  Qed.\n\n  Lemma nm_mapi_empty1\n    : forall (elt1 : Type) (m : NatMap.t elt1) (elt2 : Type) (f: NatMap.key -> elt1 -> elt2),\n      NatMap.Empty m -> NatMap.Empty (NatMap.mapi f m).\n  Proof.\n    i. rewrite elements_Empty in *. ss. unfold elements, Raw.elements in *. rewrite H. ss.\n  Qed.\n\n  Lemma nm_mapi_empty\n        e0 e1 f\n    :\n    NatMap.mapi f (NatMap.empty e0) = (NatMap.empty e1).\n  Proof.\n    eapply nm_empty_eq. eapply nm_mapi_empty1. apply NatMap.empty_1.\n  Qed.\n\n  Lemma nm_mapi_add_comm_equal\n        elt (m: t elt) elt' (f: key -> elt -> elt') k e\n    :\n    Equal (add k (f k e) (mapi f m)) (mapi f (add k e m)).\n  Proof.\n    eapply F.Equal_mapsto_iff. i. split; i.\n    - eapply F.add_mapsto_iff in H. des; clarify.\n      + assert (H: MapsTo k0 e (add k0 e m)).\n        { eapply add_1; auto. }\n        eapply mapi_1 in H. des; clarify; eauto.\n      + eapply F.mapi_mapsto_iff in H0. 2: i; clarify; eauto.\n        des; clarify.\n        assert (H2: MapsTo k0 a (add k e m)).\n        { eapply add_2; auto. }\n        eapply mapi_1 in H2. des; clarify; eauto.\n    - eapply F.mapi_mapsto_iff in H. 2: i; clarify; eauto.\n      des; clarify. eapply F.add_mapsto_iff in H0. des; clarify.\n      + eapply add_1; auto.\n      + eapply add_2; auto. eapply mapi_1 in H1. des; clarify; eauto.\n  Qed.\n  Lemma nm_mapi_add_comm_eq\n        elt (m: t elt) elt' (f: key -> elt -> elt') k e\n    :\n    (add k (f k e) (mapi f m)) = (mapi f (add k e m)).\n  Proof. eapply nm_eq_is_equal, nm_mapi_add_comm_equal. Qed.\n\n\n  Lemma nm_map_mapi_equal\n        elt (m: t elt) elt1 (f: key -> elt -> elt1) elt2 (g: elt1 -> elt2)\n    :\n    Equal (map g (mapi f m)) (mapi (fun k e => (g (f k e))) m).\n  Proof.\n    eapply F.Equal_mapsto_iff. i. split; i.\n    - rewrite F.map_mapsto_iff in H. des; clarify.\n      rewrite F.mapi_mapsto_iff in H0. 2: i; clarify. des; clarify.\n      eapply mapi_1 in H1. des; clarify. instantiate (1:= (fun k e => g (f k e))) in H0. ss.\n    - rewrite F.mapi_mapsto_iff in H. 2: i; clarify. des; clarify.\n      eapply map_1. eapply mapi_1 in H0. des; clarify. eauto.\n  Qed.\n  Lemma nm_map_mapi_eq\n        elt (m: t elt) elt1 (f: key -> elt -> elt1) elt2 (g: elt1 -> elt2)\n    :\n    (map g (mapi f m)) = (mapi (fun k e => (g (f k e))) m).\n  Proof. eapply nm_eq_is_equal, nm_map_mapi_equal. Qed.\n\n  Lemma mapi_unit1_map_equal\n        elt (m: t elt) elt1 (f: key -> elt -> elt1)\n    :\n    Equal (mapi (fun k e => unit1 (f k e)) m) (map unit1 m).\n  Proof.\n    rewrite <- nm_map_mapi_eq. eapply F.Equal_mapsto_iff. i. split; i.\n    - rewrite F.map_mapsto_iff in H. des; clarify.\n      rewrite F.mapi_mapsto_iff in H0. 2: i; clarify. des; clarify.\n      unfold unit1. eapply map_1 in H1. instantiate (1:= (fun _ => tt)) in H1. ss.\n    - rewrite F.map_mapsto_iff in H. des; clarify.\n      rewrite nm_map_mapi_eq. eapply mapi_1 in H0. des; clarify. instantiate (1:=fun k a => tt) in H1. ss.\n  Qed.\n  Lemma mapi_unit1_map_eq\n        elt (m: t elt) elt1 (f: key -> elt -> elt1)\n    :\n    (mapi (fun k e => unit1 (f k e)) m) = (map unit1 m).\n  Proof. eapply nm_eq_is_equal, mapi_unit1_map_equal. Qed.\n\n  Lemma nm_mapi_unit1_map_equal\n        elt (m: t elt) elt' (f: key -> elt -> elt')\n    :\n    Equal (map unit1 (mapi f m)) (map unit1 m).\n  Proof.\n    rewrite nm_map_mapi_equal. rewrite mapi_unit1_map_equal. ss.\n  Qed.\n  Lemma nm_mapi_unit1_map_eq\n        elt (m: t elt) elt' (f: key -> elt -> elt')\n    :\n    (map unit1 (mapi f m)) = (map unit1 m).\n  Proof. eapply nm_eq_is_equal, nm_mapi_unit1_map_equal. Qed.\n\n  Lemma fold_left_pointwise_none\n        X l k e\n        (NONE : SetoidList.findA (NatMapP.F.eqb k) l = None)\n    :\n    fold_left\n      (fun (a : @thsRA X) (p : NatMap.key * X) (k0 : nat) => (fst p |-> snd p) k0 ⋅ a k0) l e k = (e k).\n  Proof.\n    revert_until l. induction l; i; ss. des_ifs. ss. rewrite IHl; auto. rewrite th_has_miss; auto. r_solve.\n    ii. clarify. unfold F.eqb in Heq. des_ifs.\n  Qed.\n\nEnd AUX.\n\nSection USERSIM.\n\n  Lemma yord_implies_stid_user\n        md_src md_tgt\n        p_src p_tgt\n        (MDSIM: ModSimYOrd.UserSim.sim md_src md_tgt p_src p_tgt)\n    :\n    ModSimStid.UserSim.sim md_src md_tgt p_src p_tgt.\n  Proof.\n    inv MDSIM.\n    set (ident_src := Mod.ident md_src). set (_ident_tgt := Mod.ident md_tgt).\n    set (state_src := Mod.state md_src). set (state_tgt := Mod.state md_tgt).\n    set (srcE := ((@eventE ident_src +' cE) +' sE state_src)).\n    set (tgtE := ((@eventE _ident_tgt +' cE) +' sE state_tgt)).\n    set (ident_tgt := @ident_tgt _ident_tgt).\n    set (shared := (TIdSet.t * (@imap ident_src wf_src) * (@imap ident_tgt wf_tgt) * state_src * state_tgt)%type).\n    set (ident_src2 := sum_tid ident_src).\n    set (wf_src_th := fun R0 R1 => clos_trans_WF (prod_WF (prod_WF (wf_stt R0 R1) wf_tgt) (nmo_wf (wf_stt R0 R1)))).\n    set (wf_src2 := fun R0 R1 => sum_WF (@wf_src_th R0 R1) wf_src).\n    set (M2 := fun R0 R1 => URA.prod (@thsRA (prod_WF (wf_stt R0 R1) (wf_stt R0 R1)).(T)) world).\n    set (St := fun o0 => @epsilon _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) o0 o1)).\n    assert (lt_succ_diag_r_tgt: forall (t: wf_tgt.(T)), wf_tgt.(lt) t (St t)).\n    { i. unfold St. hexploit (@epsilon_spec _ wf_tgt_inhabited (fun o1 => wf_tgt.(lt) t o1)); eauto. }\n    eapply (@UserSim.mk _ _ _ _ (wf_src2 Any.t Any.t) _ wf_tgt_inhabited wf_tgt_open (M2 Any.t Any.t)).\n    i. specialize (funs im_tgt). des.\n    set (ost:= NatMap.map snd rsost). set (rs:= NatMap.map fst rsost).\n    set (im_src_th:= fun t => match (NatMap.find t ost) with\n                           | None => ((wf_stt0 Any.t Any.t, St (im_tgt (inl t))), nm_proj_v1 ost)\n                           | Some (_, ot) => ((ot, St (im_tgt (inl t))), nm_proj_v1 ost)\n                           end).\n    exists (@I2 _ _ _ _ _ _ _ I wf_stt wf_stt0 Any.t Any.t).\n    exists (@imap_comb _ _ (wf_src_th Any.t Any.t) _ im_src_th im_src).\n    set (rowns:= NatMap.mapi (fun t rst => (t |-> (snd rst), fst rst)) rsost).\n    exists rowns. exists (shared_thsRA wf_stt wf_stt0 ost, r_shared).\n    (* instantiate (1:=@I2 _ _ _ _ _ _ _ I wf_stt wf_stt0 Any.t Any.t). *)\n\n    esplits.\n    { unfold I2. esplits; eauto. unfold Is. exists ost. splits; auto.\n      { subst ost. unfold nm_wf_pair. unfold key_set. rewrite ! nm_map_unit1_map_eq.\n        eapply nm_forall2_wf_pair. eapply list_forall3_implies_forall2_3 in SIM; eauto. i. des_ifs; des; clarify.\n      }\n      i. subst im_src_th. econs 1. ss. rewrite FIND. econs 1. econs 2; auto.\n    }\n    { eapply nm_find_some_implies_forall3.\n      { eapply nm_forall2_wf_pair. eapply list_forall3_implies_forall2_2 in SIM; eauto. i. des_ifs; des; clarify. }\n      { subst rowns. unfold nm_wf_pair. unfold key_set. rewrite ! nm_mapi_unit1_map_eq.\n        eapply nm_forall2_wf_pair. eapply list_forall3_implies_forall2_3 in SIM; eauto. i. des_ifs; des; clarify.\n      }\n      i. subst rowns. rewrite NatMapP.F.mapi_o in FIND3. unfold option_map in FIND3. des_ifs.\n      2:{ i; clarify. }\n      destruct p. ss.\n      eapply nm_forall3_implies_find_some in SIM; eauto.\n      unfold ModSimYOrd.local_sim_init in SIM. des_ifs. ii.\n      unfold I2 in INV. des_ifs. des. destruct p as [os ot]. ur in VALID. des_ifs. des.\n      hexploit init_src_inv. 1,2: eauto. 2: eapply INVS. 2: eapply VALID. 2: eapply FAIR.\n      instantiate (1:=im_src_us). reflexivity. i. des.\n      esplits. eapply SRC.\n      i. simpl in Heq0. clarify. eapply yord_implies_stid; eauto.\n    }\n    { subst rowns. subst ost. clear - WF. subst M2. ss.\n      setoid_rewrite (@nm_fold_prod_res world (wf_stt Any.t Any.t).(T) (ε, ε) rsost).\n      try rewrite ! URA.unfold_wf; try rewrite ! URA.unfold_add. ss. split.\n      { clear.\n        assert (RW:\n                 (NatMap.mapi (fun (t : NatMap.key) (rst : world * (T (wf_stt Any.t Any.t) * T (wf_stt Any.t Any.t))) => t |-> snd rst) rsost)\n                 =\n                   (NatMap.mapi (fun t st => t |-> st) (NatMap.map snd rsost))).\n        { induction rsost using nm_ind.\n          { rewrite nm_map_empty. rewrite ! nm_mapi_empty. auto. }\n          rewrite <- nm_map_add_comm_eq. rewrite <- ! nm_mapi_add_comm_eq. f_equal. auto.\n        }\n        setoid_rewrite RW. clear RW.\n        remember (NatMap.map snd rsost) as ost. clear Heqost. clear.\n        replace\n       (@NatMap.fold (forall _ : nat, @Auth.car (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t)))))\n          (forall _ : nat, @Auth.car (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t)))))\n          (fun (_ : NatMap.key)\n             (f0 f1 : forall _ : nat, @Auth.car (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) \n             (k : nat) => @URA.add (Auth.t (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) (f0 k) (f1 k))\n          (@NatMap.mapi (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t)))\n             (@URA.car (@thsRA (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t)))))\n             (fun (t : NatMap.key) (st : prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))) =>\n              @th_has (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))) t st) ost)\n          (@URA.unit (@thsRA (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))))\n       with\n          (fun n => match NatMap.find n ost with\n                 | Some st => ae_white st\n                 | None => ε\n                 end\n          ).\n        { unfold shared_thsRA. ur. i. des_ifs.\n          { repeat ur. des_ifs. split; r_solve. ss. }\n          { r_solve. ur. split; r_solve. ur. ss. }\n        }\n        replace\n    (@NatMap.fold (forall _ : nat, @Auth.car (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t)))))\n       (forall _ : nat, @Auth.car (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t)))))\n       (fun (_ : NatMap.key) (f0 f1 : forall _ : nat, @Auth.car (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t)))))\n          (k : nat) => @URA.add (Auth.t (Excl.t (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))) (f0 k) (f1 k))\n       (@NatMap.mapi (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t)))\n          (@URA.car (@thsRA (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t)))))\n          (fun (t : NatMap.key) (st : prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))) =>\n           @th_has (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))) t st) ost)\n       (@URA.unit (@thsRA (prod (T (wf_stt Any.t Any.t)) (T (wf_stt Any.t Any.t))))))\n          with\n          (NatMap.fold (fun t st r => (t |-> st) ⋅ r) ost ε).\n        2:{ rewrite ! NatMap.fold_1. rewrite <- list_map_elements_nm_mapi. remember (NatMap.elements ost) as l. clear.\n            remember ε as r. clear. revert r. induction l; ss. i.\n            rewrite IHl. f_equal. extensionality x. des_ifs. ss. repeat ur. des_ifs; ss.\n        }\n        induction ost using nm_ind; ss.\n        rewrite NatMapP.fold_add; try typeclasses eauto; ss.\n        2:{ ii. r_solve. }\n        2:{ ii. apply NatMapP.F.in_find_iff in H. clarify. }\n        extensionality x. destruct (tid_dec x k) eqn:DEC.\n        - clarify. rewrite nm_find_add_eq. rewrite NatMap.fold_1. rewrite NatMapP.F.elements_o in NONE. \n          remember (NatMap.elements ost) as l. ur. setoid_rewrite fold_left_pointwise_none; auto.\n          rewrite th_has_hit. repeat ur; ss. \n        - rewrite nm_find_add_neq; auto. eapply equal_f in IHost. erewrite IHost. ur. rewrite th_has_miss; auto. r_solve.\n      }\n      { replace \n          (NatMap.fold (fun _ : NatMap.key => URA._add)\n                       (NatMap.mapi (fun (_ : NatMap.key) (rst : world * (T (wf_stt Any.t Any.t) * T (wf_stt Any.t Any.t))) => fst rst) rsost) ε)\n          with (NatMap.fold (fun (_ : NatMap.key) '(r, _) (s : world) => r ⋅ s) rsost ε); auto.\n        rewrite ! NatMap.fold_1. rewrite <- list_map_elements_nm_mapi.\n        remember (NatMap.elements rsost) as l. clear.\n        replace\n          (fold_left (fun (a : world) (p : NatMap.key * world) => URA._add (snd p) a) (map (fun '(k, e) => (k, fst e)) l) ε) with\n          (fold_left (fun (a : world) (p : NatMap.key * world) => (snd p) ⋅ a) (map (fun '(k, e) => (k, fst e)) l) ε).\n        2:{ ur. auto. }\n        induction l; ss. des_ifs. ss. clarify.\n        ss. r_solve. rewrite resources_fold_left_base. rewrite <- IHl. symmetry. eapply list_fold_left_resource_aux2.\n      }\n    }\n  Qed.\n\nEnd USERSIM.\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/src/simulation/YOrd2Stid.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.21954586785042035}}
{"text": "Require Import Blech.Defaults.\n\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Classes.SetoidClass.\n\nRequire Import Blech.Proset.\n\nImport ProsetNotations.\n\n#[program]\nDefinition Trv: Proset := {|\n  T := True ;\n  preorder _ _ := True ;\n|}.\n\nNext Obligation.\nProof.\n  exists.\n  all: exists.\nDefined.\n", "meta": {"author": "mstewartgallus", "repo": "category-fun", "sha": "436a90c0f9e8a729da6416a2c0e54611ca5e4575", "save_path": "github-repos/coq/mstewartgallus-category-fun", "path": "github-repos/coq/mstewartgallus-category-fun/category-fun-436a90c0f9e8a729da6416a2c0e54611ca5e4575/theories/Proset/Trv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21954586785042032}}
{"text": "(** Refinement rules for disjoint rules *)\nRequire Import Coq.Lists.List.\nRequire Import Fiat.Parsers.Refinement.PreTactics.\nRequire Import Fiat.Computation.Refinements.General.\nRequire Import Fiat.Parsers.StringLike.Properties.\nRequire Import Fiat.Parsers.StringLike.FirstCharSuchThat.\nRequire Import Fiat.Parsers.StringLike.FirstChar.\nRequire Import Fiat.Common.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.ContextFreeGrammar.ValidReflective.\nRequire Import Fiat.Parsers.Refinement.DisjointLemmas.\nRequire Import Fiat.Parsers.ParserInterface.\nRequire Import Fiat.Parsers.StringLike.Core.\n\nSet Implicit Arguments.\n\nDefinition search_for_condition\n           {HSLM : StringLikeMin Ascii.ascii}\n           {HSL : StringLike Ascii.ascii}\n           {HSI : StringIso Ascii.ascii}\n           (G : pregrammar Ascii.ascii)\n           str its (n : nat)\n  := is_first_char_such_that\n       (might_be_empty (possible_first_terminals_of_production G its))\n       str\n       n\n       (fun ch => list_bin ascii_beq ch (possible_first_terminals_of_production G its)).\n\nLemma refine_disjoint_search_for'\n      {HSLM : StringLikeMin Ascii.ascii}\n      {HSL : StringLike Ascii.ascii}\n      {HSI : StringIso Ascii.ascii}\n      {HSLP : StringLikeProperties Ascii.ascii}\n      {HSIP : StringIsoProperties Ascii.ascii}\n      (G : pregrammar Ascii.ascii)\n      (Hvalid : grammar_rvalid G)\n      {str offset len nt its}\n      (H_disjoint : disjoint ascii_beq\n                             (possible_terminals_of G nt)\n                             (possible_first_terminals_of_production G its))\n: refine {splits : list nat\n         | split_list_is_complete\n             G str offset len\n             (NonTerminal nt::its) splits}\n         (n <- { n : nat | n <= length (substring offset len str)\n                           /\\ ((exists n', search_for_condition G (substring offset len str) its n')\n                               -> search_for_condition G (substring offset len str) its n) };\n          ret [n]).\nProof.\n  intros ls H.\n  computes_to_inv; subst.\n  destruct H as [H0 H1].\n  apply PickComputes.\n  hnf; cbv zeta.\n  intros Hlen it' its' Heq n ? H_reachable pit pits.\n  inversion Heq; subst it' its'; clear Heq.\n  left.\n  pose proof (terminals_disjoint_search_for Hvalid _ H_disjoint pit pits H_reachable) as H'.\n  specialize (H1 (ex_intro _ n H')).\n  pose proof (is_first_char_such_that_eq_nat_iff H1 H') as H''.\n  destruct_head or; destruct_head and; subst;\n  rewrite ?Min.min_r, ?Min.min_l by assumption;\n  omega.\nQed.\n\nDefinition search_for_not_condition\n           {HSLM : StringLikeMin Ascii.ascii}\n           {HSL : StringLike Ascii.ascii}\n           {HSI : StringIso Ascii.ascii}\n           (G : pregrammar Ascii.ascii)\n           str nt its n\n  := is_first_char_such_that\n       (might_be_empty (possible_first_terminals_of_production G its))\n       str\n       n\n       (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of G nt))).\n\nLemma refine_disjoint_search_for_not'\n      {HSLM : StringLikeMin Ascii.ascii}\n      {HSL : StringLike Ascii.ascii}\n      {HSI : StringIso Ascii.ascii}\n      {HSLP : StringLikeProperties Ascii.ascii}\n      {HSIP : StringIsoProperties Ascii.ascii}\n      {G : pregrammar Ascii.ascii}\n      (Hvalid : grammar_rvalid G)\n      {str offset len nt its}\n      (H_disjoint : disjoint ascii_beq\n                             (possible_terminals_of G nt)\n                             (possible_first_terminals_of_production G its))\n: refine {splits : list nat\n         | split_list_is_complete\n             G str offset len\n             (NonTerminal nt::its)\n             splits}\n         (n <- { n : nat | n <= length (substring offset len str)\n                           /\\ ((exists n', search_for_not_condition G (substring offset len str) nt its n')\n                               -> search_for_not_condition G (substring offset len str) nt its n) };\n          ret [n]).\nProof.\n  intros ls H.\n  computes_to_inv; subst.\n  destruct H as [H0 H1].\n  apply PickComputes.\n  hnf; cbv zeta.\n  intros Hlen it' its' Heq n ? H_reachable pit pits.\n  inversion Heq; subst it' its'; clear Heq.\n  left.\n  pose proof (terminals_disjoint_search_for_not Hvalid _ H_disjoint pit pits H_reachable) as H'.\n  specialize (H1 (ex_intro _ n H')).\n  pose proof (is_first_char_such_that_eq_nat_iff H1 H') as H''.\n  destruct_head or; destruct_head and; subst;\n  rewrite ?Min.min_r by assumption;\n  omega.\nQed.\n\nLemma find_first_char_such_that'_short {Char HSLM HSL}\n      str P len\n: @find_first_char_such_that' Char HSLM HSL P len str <= len.\nProof.\n  revert str; induction len; simpl; intros; [ reflexivity | ].\n  destruct (get (length str - S len) str) eqn:H.\n  { edestruct P; try omega.\n    apply Le.le_n_S, IHlen. }\n  { apply Le.le_n_S, IHlen. }\nQed.\n\nLemma find_first_char_such_that_short {Char HSLM HSL}\n      str P\n: @find_first_char_such_that Char HSLM HSL str P <= length str.\nProof.\n  apply find_first_char_such_that'_short.\nQed.\n\nLemma is_first_char_such_that__find_first_char_such_that {Char} {HSLM HSL} {HSLP : @StringLikeProperties Char HSLM HSL} str P\n      might_be_empty\n      (H : exists n, is_first_char_such_that might_be_empty str n (fun ch => is_true (P ch)))\n: is_first_char_such_that might_be_empty str (@find_first_char_such_that Char HSLM HSL str P) (fun ch => is_true (P ch)).\nProof.\n  unfold find_first_char_such_that.\n  destruct H as [n H].\n  set (len := length str).\n  setoid_replace str with (drop (length str - len) str) at 1\n    by (subst; rewrite Minus.minus_diag, drop_0; reflexivity).\n  setoid_replace str with (drop (length str - len) str) in H\n    by (subst; rewrite Minus.minus_diag, drop_0; reflexivity).\n  assert (len <= length str) by reflexivity.\n  clearbody len.\n  generalize dependent str; revert n.\n  induction len; simpl; intros n str IH Hlen.\n  { apply first_char_such_that_0.\n    rewrite drop_length.\n    rewrite NPeano.Nat.sub_0_r in IH |- *.\n    rewrite Minus.minus_diag.\n    split.\n    { apply for_first_char_nil.\n      rewrite drop_length; omega. }\n    { generalize dependent str.\n      induction n; intros str H Hlen.\n      { apply first_char_such_that_0 in H.\n        rewrite drop_length, Minus.minus_diag in H.\n        destruct_head and; trivial. }\n      { apply first_char_such_that_past_end in H; [ | rewrite drop_length; omega ].\n        left; assumption. } } }\n  { pose proof (singleton_exists (take 1 (drop (length str - S len) str))) as H'.\n    rewrite take_length, drop_length in H'.\n    destruct H' as [ch H']; [ apply Min.min_case_strong; intros; omega | ].\n    rewrite get_drop.\n    rewrite (proj1 (get_0 _ _) H').\n    destruct (P ch) eqn:H''.\n    { apply first_char_such_that_0.\n      rewrite drop_length.\n      split; [ | right; omega ].\n      apply (for_first_char__take 0).\n      rewrite <- for_first_char_singleton by eassumption; trivial. }\n    { apply is_first_char_such_that_drop.\n      destruct n.\n      { apply first_char_such_that_0 in IH.\n        destruct IH as [IH _].\n        apply (for_first_char__take 0) in IH.\n        rewrite <- for_first_char_singleton in IH by eassumption; unfold is_true in *; congruence. }\n      { apply is_first_char_such_that_drop in IH.\n        destruct IH as [IH _].\n        rewrite drop_drop in IH |- *; simpl in IH |- *.\n        replace (S (length str - S len)) with (length str - len) in IH |- * by omega.\n        split.\n        { eapply IHlen; try eassumption; [].\n          omega. }\n        { apply (for_first_char__take 0).\n          rewrite <- for_first_char_singleton by eassumption; congruence. } } } }\nQed.\n\nLemma refine_find_first_char_such_that {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char}\n      (str : String)\n      (P : Char -> bool)\n      might_be_empty\n: refine { n : nat | n <= length str\n                     /\\ ((exists n', is_first_char_such_that might_be_empty str n' P)\n                         -> is_first_char_such_that might_be_empty str n P) }\n         (ret (find_first_char_such_that str P)).\nProof.\n  intros v H.\n  computes_to_inv; subst.\n  apply PickComputes.\n  split; [ apply find_first_char_such_that_short | ].\n  apply is_first_char_such_that__find_first_char_such_that.\nQed.\n\nLemma refine_disjoint_search_for\n      {HSLM : StringLikeMin Ascii.ascii}\n      {HSL : StringLike Ascii.ascii}\n      {HSI : StringIso Ascii.ascii}\n      {HSLP : StringLikeProperties Ascii.ascii}\n      {HSIP : StringIsoProperties Ascii.ascii}\n      {G : pregrammar Ascii.ascii}\n      {str offset len nt its}\n      (Hvalid : grammar_rvalid G)\n      (H_disjoint : disjoint ascii_beq\n                             (possible_terminals_of G nt)\n                             (possible_first_terminals_of_production G its))\n: refine {splits : list nat\n         | split_list_is_complete\n             G str offset len\n             (NonTerminal nt::its)\n             splits}\n         (ret [find_first_char_such_that (substring offset len str) (fun ch => list_bin ascii_beq ch (possible_first_terminals_of_production G its))]).\nProof.\n  rewrite refine_disjoint_search_for' by assumption.\n  setoid_rewrite refine_find_first_char_such_that.\n  simplify with monad laws; reflexivity.\nQed.\n\nLemma refine_disjoint_search_for_not\n      {HSLM : StringLikeMin Ascii.ascii}\n      {HSL : StringLike Ascii.ascii}\n      {HSI : StringIso Ascii.ascii}\n      {HSLP : StringLikeProperties Ascii.ascii}\n      {HSIP : StringIsoProperties Ascii.ascii}\n      {G : pregrammar Ascii.ascii}\n      {str offset len nt its}\n      (Hvalid : grammar_rvalid G)\n      (H_disjoint : disjoint ascii_beq\n                             (possible_terminals_of G nt)\n                             (possible_first_terminals_of_production G its))\n: refine {splits : list nat\n         | split_list_is_complete\n             G str offset len\n             (NonTerminal nt::its)\n             splits}\n         (ret [find_first_char_such_that (substring offset len str) (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of G nt)))]).\nProof.\n  rewrite refine_disjoint_search_for_not' by assumption.\n  setoid_rewrite refine_find_first_char_such_that.\n  simplify with monad laws; reflexivity.\nQed.\n\nLemma refine_disjoint_search_for_idx\n      {HSLM : StringLikeMin Ascii.ascii}\n      {HSL : StringLike Ascii.ascii}\n      {HSI : StringIso Ascii.ascii}\n      {HSLP : StringLikeProperties Ascii.ascii}\n      {HSIP : StringIsoProperties Ascii.ascii}\n      {G : pregrammar Ascii.ascii}\n      {str offset len nt its idx}\n      (Hvalid : grammar_rvalid G)\n      (Heq : default_to_production (G := G) idx = NonTerminal nt :: its)\n      (H_disjoint : disjoint ascii_beq\n                             (possible_terminals_of G nt)\n                             (possible_first_terminals_of_production G its))\n: refine {splits : list nat\n         | split_list_is_complete_idx\n             G str offset len\n             idx\n             splits}\n         (ret [find_first_char_such_that (substring offset len str) (fun ch => list_bin ascii_beq ch (possible_first_terminals_of_production G its))]).\nProof.\n  unfold split_list_is_complete_idx.\n  erewrite <- refine_disjoint_search_for by eassumption.\n  rewrite Heq.\n  apply refine_pick_pick; intro; trivial.\nQed.\n\nLemma refine_disjoint_search_for_not_idx\n      {HSLM : StringLikeMin Ascii.ascii}\n      {HSL : StringLike Ascii.ascii}\n      {HSI : StringIso Ascii.ascii}\n      {HSLP : StringLikeProperties Ascii.ascii}\n      {HSIP : StringIsoProperties Ascii.ascii}\n      {G : pregrammar Ascii.ascii}\n      {str offset len nt its idx}\n      (Hvalid : grammar_rvalid G)\n      (Heq : default_to_production (G := G) idx = NonTerminal nt :: its)\n      (H_disjoint : disjoint ascii_beq\n                             (possible_terminals_of G nt)\n                             (possible_first_terminals_of_production G its))\n: refine {splits : list nat\n         | split_list_is_complete_idx\n             G str offset len\n             idx\n             splits}\n         (ret [find_first_char_such_that (substring offset len str) (fun ch => negb (list_bin ascii_beq ch (possible_terminals_of G nt)))]).\nProof.\n  unfold split_list_is_complete_idx.\n  erewrite <- refine_disjoint_search_for_not by eassumption.\n  rewrite Heq.\n  apply refine_pick_pick; intro; trivial.\nQed.\n\nLtac solve_disjoint_side_conditions :=\n  idtac;\n  lazymatch goal with\n  | [ |- Carriers.default_to_production (G := ?G) ?k = ?e ]\n    => try cbv delta [G];\n       cbv beta iota zeta delta [Carriers.default_to_production Lookup_idx fst snd List.map pregrammar_productions List.length List.nth minus Operations.List.drop];\n       try reflexivity\n  | [ |- is_true (Operations.List.disjoint _ _ _) ]\n    => vm_compute; try reflexivity\n  end.\n\nLtac pose_disjoint_search_for lem :=\n  idtac;\n  let G := match goal with |- appcontext[ParserInterface.split_list_is_complete_idx ?G ?str ?offset ?len ?idx] => G end in\n  let HSLM := match goal with |- appcontext[@ParserInterface.split_list_is_complete_idx ?Char ?G ?HSLM ?HSL] => HSLM end in\n  let HSL := match goal with |- appcontext[@ParserInterface.split_list_is_complete_idx ?Char ?G ?HSLM ?HSL] => HSL end in\n  let lem' := constr:(@refine_disjoint_search_for_idx HSLM HSL _ _ _ G) in\n  let H' := fresh in\n  assert (H' : ValidReflective.grammar_rvalid G) by (vm_compute; reflexivity);\n  let lem' := match goal with\n              | [ |- appcontext[ParserInterface.split_list_is_complete_idx ?G ?str ?offset ?len ?idx] ]\n                => constr:(fun idx' nt its => lem' str offset len nt its idx' H')\n              end in\n  pose proof lem' as lem;\n  clear H'.\nLtac rewrite_once_disjoint_search_for_specialize lem lem' :=\n  idtac;\n  let G := (lazymatch goal with\n             | [ |- appcontext[ParserInterface.split_list_is_complete_idx ?G ?str ?offset ?len ?idx] ]\n               => G\n             end) in\n  match goal with\n  | [ |- appcontext[ParserInterface.split_list_is_complete_idx ?G ?str ?offset ?len ?idx] ]\n    => pose proof (lem idx) as lem';\n       do 2 (lazymatch type of lem' with\n              | forall a : ?T, _ => idtac; let x := fresh in evar (x : T); specialize (lem' x); subst x\n              end);\n       let T := match type of lem' with forall a : ?T, _ => T end in\n       let H' := fresh in\n       assert (H' : T) by solve_disjoint_side_conditions;\n       specialize (lem' H'); clear H';\n       let x := match type of lem' with\n                | context[DisjointLemmas.actual_possible_first_terminals ?ls]\n                  => constr:(DisjointLemmas.actual_possible_first_terminals ls)\n                end in\n       replace_with_vm_compute_in x lem';\n       unfold Equality.list_bin in lem';\n       change (orb false) with (fun bv : bool => bv) in lem';\n       cbv beta in lem';\n       let T := match type of lem' with forall a : ?T, _ => T end in\n       let H' := fresh in\n       assert (H' : T) by solve_disjoint_side_conditions;\n       specialize (lem' H'); clear H'\n  end.\nLtac rewrite_once_disjoint_search_for lem :=\n  let lem' := fresh \"lem'\" in\n  rewrite_once_disjoint_search_for_specialize lem lem';\n  setoid_rewrite lem'; clear lem'.\nLtac rewrite_disjoint_search_for_no_clear lem :=\n  pose_disjoint_search_for lem;\n  progress repeat rewrite_once_disjoint_search_for lem.\nLtac rewrite_disjoint_search_for :=\n  idtac;\n  let lem := fresh \"lem\" in\n  rewrite_disjoint_search_for_no_clear lem;\n  clear lem.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_simpl_example/src/Parsers/Refinement/DisjointRules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21954586785042032}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\nRequire Import\n        Coq.ZArith.ZArith\n        Coq.Strings.String\n        Coq.Vectors.Vector.\n\nRequire Import\n        Fiat.Computation\n        Fiat.Narcissus.Common.Specs\n        Fiat.Narcissus.Formats.Base.FMapFormat.\n\nRequire Import Fiat.Computation.FixComp.\nImport Fiat.Computation.FixComp.LeastFixedPointFun.\n\nSection FixFormat.\n\n  Context {S : Type}. (* Source Type *)\n  Context {T : Type}. (* Target Type *)\n  Context {cache : Cache}. (* State Type *)\n\n  Definition Fix_Format\n             (format_body : FormatM S T -> FormatM S T)\n    := LeastFixedPoint (fDom := [S; CacheFormat]%type)\n                       (fCod := T * CacheFormat) format_body.\n\n  Fixpoint FueledFix' {A B C}\n           (f : (B -> C -> option A) -> B -> C -> option A)\n           (n : nat)\n    : B -> C -> option A :=\n    match n with\n    | Datatypes.S n' => f (FueledFix' f n')\n    | _ => fun _ _ => None\n    end.\n\n\n  Theorem FueledFix_continuous {A B C} (F : (B -> C -> option A) -> B -> C -> option A)\n    : (forall n a b c,\n          FueledFix' F n b c = Some a ->\n          FueledFix' F (Datatypes.S n) b c = Some a) ->\n      forall n n',\n        n <= n' ->\n        forall a b c,\n          FueledFix' F n b c = Some a ->\n          FueledFix' F n' b c = Some a.\n  Proof.\n    intros; induction H0; eauto.\n  Qed.\n\n  Definition Fix_Decode\n             {monoid : Monoid T}\n             (decode_body : DecodeM S T -> DecodeM S T)\n    : DecodeM S T :=\n    fun t env => FueledFix' decode_body (Datatypes.S (bin_measure t)) t env.\n\n  Definition Compose_Target\n             (P : T -> Prop)\n             (format : FormatM S T)\n    : FormatM S T :=\n    fun s env tenv' =>\n      format s env ∋ tenv'\n       /\\ P (fst tenv').\n\n  (* Lemma CorrectDecoder_Fix' *)\n  (*       (decode_body : DecodeM S T -> DecodeM S T) *)\n  (*       (format_body : FormatM S T -> FormatM S T) *)\n  (*       (format_body_OK : Frame.monotonic_function (format_body : funType [S; CacheFormat] (T * CacheFormat) -> *)\n  (*                                                                 funType [S; CacheFormat] (T * CacheFormat))) *)\n  (*       (bound : T -> nat) *)\n  (*       (decode_body_correct : *)\n  (*          forall n, *)\n  (*            (CorrectDecoder_simpl *)\n  (*               (Compose_Target (fun t => bound t < n)  (Fix_Format format_body)) *)\n  (*               (FueledFix' decode_body n)) -> *)\n  (*            CorrectDecoder_simpl *)\n  (*              (Compose_Target (fun t => bound t < Datatypes.S n) *)\n  (*                           (format_body (Fix_Format format_body))) *)\n  (*              (decode_body (FueledFix' decode_body n))) *)\n  (*   : forall n, *)\n  (*     CorrectDecoder_simpl *)\n  (*       (Compose_Target (fun t => bound t < n) (Fix_Format format_body)) *)\n  (*       (FueledFix' decode_body n). *)\n  (* Proof. *)\n  (*   induction n; simpl; intros. *)\n  (*   - split; unfold Compose_Target; intros. *)\n  (*     + rewrite @unfold_computes in H0; omega. *)\n  (*     + discriminate. *)\n  (*   - split; unfold Compose_Target in *; intros. *)\n  (*     + rewrite @unfold_computes in H0; split_and. *)\n  (*       apply_in_hyp (unroll_LeastFixedPoint format_body_OK). *)\n  (*       eapply decode_body_correct; eauto. *)\n  (*       apply unfold_computes; intuition eauto. *)\n  (*     + eapply decode_body_correct in H0; eauto. *)\n  (*       destruct_ex; split_and. *)\n  (*       eexists; intuition eauto. *)\n  (*       apply unfold_computes. *)\n  (*       rewrite @unfold_computes in H1. *)\n  (*       intuition. *)\n  (*       eapply (unroll_LeastFixedPoint' format_body_OK). *)\n  (*       apply unfold_computes; eauto. *)\n  (* Qed. *)\n\n  (* Lemma CorrectDecoder_Fix *)\n  (*       {monoid : Monoid T} *)\n  (*       (decode_body : DecodeM S T -> DecodeM S T) *)\n  (*       (format_body : FormatM S T -> FormatM S T) *)\n  (*       (format_body_OK : Frame.monotonic_function (format_body : funType [S; CacheFormat] (T * CacheFormat) -> *)\n  (*                                                                 funType [S; CacheFormat] (T * CacheFormat))) *)\n  (*       (decode_body_correct : *)\n  (*          forall n, *)\n  (*            (CorrectDecoder_simpl *)\n  (*               (Compose_Target (fun t => bin_measure t < n) *)\n  (*                            (Fix_Format format_body)) *)\n  (*               (FueledFix' decode_body n)) -> *)\n  (*            CorrectDecoder_simpl *)\n  (*              (Compose_Target (fun t => bin_measure t < Datatypes.S n) *)\n  (*                           (format_body (Fix_Format format_body))) *)\n  (*              (decode_body (FueledFix' decode_body n))) *)\n  (*       (decode_body_continuous : *)\n  (*          forall decode, *)\n  (*            (forall t env s env', *)\n  (*                decode t env = Some (s, env') -> *)\n  (*                decode_body decode t env = Some (s, env')) -> *)\n  (*            forall t env s env', *)\n  (*              decode_body decode t env = Some (s, env') -> *)\n  (*              decode_body (decode_body decode) t env = Some (s, env')) *)\n  (*   : CorrectDecoder_simpl *)\n  (*       (Fix_Format format_body) *)\n  (*       (Fix_Decode decode_body). *)\n  (* Proof. *)\n  (*   split; intros. *)\n  (*   - destruct (CorrectDecoder_Fix' *)\n  (*                 decode_body format_body format_body_OK bin_measure *)\n  (*                 decode_body_correct (Datatypes.S (bin_measure bin))) as [? _]; eauto. *)\n  (*     eapply H1 in H; *)\n  (*       try solve [unfold Compose_Target; apply unfold_computes; split; eauto]. *)\n  (*     destruct_ex; split_and;  eexists; intuition eauto. *)\n  (*   - destruct (CorrectDecoder_Fix' *)\n  (*                 decode_body format_body format_body_OK bin_measure *)\n  (*                 decode_body_correct (Datatypes.S (bin_measure bin))) as [_ ?]; eauto. *)\n  (*     eapply H1 in H; *)\n  (*       try solve [simpl; unfold Fix_Decode in H0; eauto]. *)\n  (*     destruct_ex; split_and;  eexists; intuition eauto. *)\n  (*     unfold Compose_Target in H2; rewrite @unfold_computes in H2; intuition. *)\n  (* Qed. *)\n\n  Definition Fix_Encode\n             (measure : S -> nat)\n             (encode_body : EncodeM S T -> EncodeM S T)\n    : EncodeM S T :=\n    fun s env => FueledFix' encode_body (Datatypes.S (measure s)) s env.\n\n    Lemma CorrectEncoder_Fix'\n        (encode_body : EncodeM S T -> EncodeM S T)\n        (format_body : FormatM S T -> FormatM S T)\n        (format_body_OK : Frame.monotonic_function (format_body : funType [S; CacheFormat] (T * CacheFormat) ->\n                                                                  funType [S; CacheFormat] (T * CacheFormat)))\n        (measure : S -> nat)\n        (encode_body_correct :\n           forall n encode,\n             (CorrectEncoder\n                (Restrict_Format (fun s => measure s < n) (Fix_Format format_body))\n                encode) ->\n             CorrectEncoder\n               (Restrict_Format (fun s => measure s < Datatypes.S n)\n                                (format_body (Fix_Format format_body)))\n               (encode_body encode))\n    : forall n,\n      CorrectEncoder\n        (Restrict_Format (fun s => measure s < n) (Fix_Format format_body))\n        (FueledFix' encode_body n).\n    Proof.\n    induction n; simpl; intros.\n    - split; unfold Restrict_Format, Compose_Format; intros.\n      + discriminate.\n      + intro H'; rewrite @unfold_computes in H';\n          destruct_ex; omega.\n    - split; unfold Restrict_Format, Compose_Format in *; intros.\n      + apply unfold_computes; intuition eauto.\n        eapply encode_body_correct in H; eauto.\n        rewrite @unfold_computes in H; destruct_ex; split_and.\n        apply_in_hyp (unroll_LeastFixedPoint' format_body_OK); eauto.\n      + intro H'; rewrite unfold_computes in H'.\n        eapply encode_body_correct in H; eauto; eapply H.\n        destruct_ex; split_and.\n        apply unfold_computes.\n        eexists; subst; intuition eauto.\n        eapply (unroll_LeastFixedPoint format_body_OK); eauto.\n  Qed.\n\n    Lemma CorrectEncoder_Fix\n          (encode_body : EncodeM S T -> EncodeM S T)\n        (format_body : FormatM S T -> FormatM S T)\n        (format_body_OK : Frame.monotonic_function (format_body : funType [S; CacheFormat] (T * CacheFormat) ->\n                                                                  funType [S; CacheFormat] (T * CacheFormat)))\n        (measure : S -> nat)\n        (encode_body_correct :\n           forall n encode,\n             (CorrectEncoder\n                (Restrict_Format (fun s => measure s < n) (Fix_Format format_body))\n                encode) ->\n             CorrectEncoder\n               (Restrict_Format (fun s => measure s < Datatypes.S n)\n                                (format_body (Fix_Format format_body)))\n               (encode_body encode))\n        (*\n          (encode_body_continuous :\n          forall encode,\n          (forall t env s env',\n          encode t env = Some (s, env') ->\n          encode_body encode t env = Some (s, env')) ->\n          forall t env s env',\n          encode_body encode t env = Some (s, env') ->\n                      encode_body (encode_body encode) t env = Some (s, env'))\n\n         *)\n    : CorrectEncoder\n        (Fix_Format format_body)\n        (Fix_Encode measure encode_body).\n  Proof.\n    split; intros.\n    - destruct (CorrectEncoder_Fix'\n                  encode_body format_body format_body_OK measure\n                  encode_body_correct (Datatypes.S (measure a))) as [? _]; eauto.\n      eapply H0 in H;\n        try solve [unfold Compose_Target; apply unfold_computes; split; eauto].\n      unfold Restrict_Format, Compose_Format in H.\n      rewrite  @unfold_computes in H.\n      destruct_ex; split_and; subst; eauto.\n    - destruct (CorrectEncoder_Fix'\n                  encode_body format_body format_body_OK measure\n                  encode_body_correct (Datatypes.S (measure a))) as [_ ?]; eauto.\n      eapply H0 in H;\n        try solve [simpl; unfold Fix_Encode in H0; eauto].\n      intro; eapply H.\n      unfold Restrict_Format, Compose_Format; apply unfold_computes.\n      eexists; split_and; eauto.\n  Qed.\n\nEnd FixFormat.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Narcissus/Formats/Base/FixFormat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.21954586785042032}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*          Sandrine Blazy, ENSIIE and INRIA Paris-Rocquencourt        *)\n(*          with contributions from Andrew Appel, Rob Dockins,         *)\n(*          and Gordon Stewart (Princeton University)                  *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation, either version 2 of the License, or  *)\n(*  (at your option) any later version.  This file is also distributed *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file provide a concrete instance for the memory model specified\n  in Memtype.v. *)\n\nRequire Import Zwf.\nRequire Import Axioms.\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Export Memdata.\nRequire Export Memtype.\n\n(* To avoid useless definitions of inductors in extracted code. *)\nLocal Unset Elimination Schemes.\nLocal Unset Case Analysis Schemes.\n\nLocal Notation \"a # b\" := (ZMap.get b a) (at level 1).\n\nDefinition perm_order' (po: option permission) (p: permission) := \n  match po with\n  | Some p' => perm_order p' p\n  | None => False\n end.\n\nDefinition perm_order'' (po1 po2: option permission) := \n  match po1, po2 with\n  | Some p1, Some p2 => perm_order p1 p2\n  | _, None => True\n  | None, Some _ => False\n end.\n\nRecord mem' : Type := mkmem {\n  mem_contents: ZMap.t (ZMap.t memval);  (**r [block -> offset -> memval] *)\n  mem_access: ZMap.t (Z -> perm_kind -> option permission);\n                                         (**r [block -> offset -> kind -> option permission] *)\n  nextblock: block;\n  nextblock_pos: nextblock > 0;\n  access_max: \n    forall b ofs, perm_order'' (mem_access#b ofs Max) (mem_access#b ofs Cur);\n  nextblock_noaccess:\n    forall b ofs k, b >= nextblock -> mem_access#b ofs k = None\n}.\n\nDefinition mem := mem'.\n\nLemma mkmem_ext:\n forall cont1 cont2 acc1 acc2 next1 next2 a1 a2 b1 b2 c1 c2,\n  cont1=cont2 -> acc1=acc2 -> next1=next2 ->\n  mkmem cont1 acc1 next1 a1 b1 c1 = mkmem cont2 acc2 next2 a2 b2 c2.\nProof.\n  intros. subst. f_equal; apply proof_irr.\nQed.\n\n(** * Validity of blocks and accesses *)\n\n(** A block address is valid if it was previously allocated. It remains valid\n  even after being freed. *)\n\nDefinition valid_block (m: mem) (b: block) :=\n  b < nextblock m.\n\nTheorem valid_not_valid_diff:\n  forall m b b', valid_block m b -> ~(valid_block m b') -> b <> b'.\nProof.\n  intros; red; intros. subst b'. contradiction.\nQed.\n\nHint Local Resolve valid_not_valid_diff: mem.\n\n(** Permissions *)\n\nDefinition perm (m: mem) (b: block) (ofs: Z) (k: perm_kind) (p: permission) : Prop :=\n   perm_order' (m.(mem_access)#b ofs k) p.\n\nTheorem perm_implies:\n  forall m b ofs k p1 p2, perm m b ofs k p1 -> perm_order p1 p2 -> perm m b ofs k p2.\nProof.\n  unfold perm, perm_order'; intros.\n  destruct (m.(mem_access)#b ofs k); auto.\n  eapply perm_order_trans; eauto.\nQed.\n\nHint Local Resolve perm_implies: mem.\n\nTheorem perm_cur_max:\n  forall m b ofs p, perm m b ofs Cur p -> perm m b ofs Max p.\nProof.\n  assert (forall po1 po2 p,\n          perm_order' po2 p -> perm_order'' po1 po2 -> perm_order' po1 p).\n  unfold perm_order', perm_order''. intros. \n  destruct po2; try contradiction.\n  destruct po1; try contradiction. \n  eapply perm_order_trans; eauto.\n  unfold perm; intros.\n  generalize (access_max m b ofs). eauto. \nQed.\n\nTheorem perm_cur:\n  forall m b ofs k p, perm m b ofs Cur p -> perm m b ofs k p.\nProof.\n  intros. destruct k; auto. apply perm_cur_max. auto.\nQed.\n\nTheorem perm_max:\n  forall m b ofs k p, perm m b ofs k p -> perm m b ofs Max p.\nProof.\n  intros. destruct k; auto. apply perm_cur_max. auto.\nQed.\n\nHint Local Resolve perm_cur perm_max: mem.\n\nTheorem perm_valid_block:\n  forall m b ofs k p, perm m b ofs k p -> valid_block m b.\nProof.\n  unfold perm; intros. \n  destruct (zlt b m.(nextblock)).\n  auto.\n  assert (m.(mem_access)#b ofs k = None).\n  eapply nextblock_noaccess; eauto. \n  rewrite H0 in H.\n  contradiction.\nQed.\n\nHint Local Resolve perm_valid_block: mem.\n\nRemark perm_order_dec:\n  forall p1 p2, {perm_order p1 p2} + {~perm_order p1 p2}.\nProof.\n  intros. destruct p1; destruct p2; (left; constructor) || (right; intro PO; inversion PO).\nDefined.\n\nRemark perm_order'_dec:\n  forall op p, {perm_order' op p} + {~perm_order' op p}.\nProof.\n  intros. destruct op; unfold perm_order'.\n  apply perm_order_dec.\n  right; tauto.\nDefined.\n\nTheorem perm_dec:\n  forall m b ofs k p, {perm m b ofs k p} + {~ perm m b ofs k p}.\nProof.\n  unfold perm; intros.\n  apply perm_order'_dec.\nDefined.\n\nDefinition range_perm (m: mem) (b: block) (lo hi: Z) (k: perm_kind) (p: permission) : Prop :=\n  forall ofs, lo <= ofs < hi -> perm m b ofs k p.\n\nTheorem range_perm_implies:\n  forall m b lo hi k p1 p2,\n  range_perm m b lo hi k p1 -> perm_order p1 p2 -> range_perm m b lo hi k p2.\nProof.\n  unfold range_perm; intros; eauto with mem.\nQed.\n\nTheorem range_perm_cur:\n  forall m b lo hi k p,\n  range_perm m b lo hi Cur p -> range_perm m b lo hi k p.\nProof.\n  unfold range_perm; intros; eauto with mem.\nQed.\n\nTheorem range_perm_max:\n  forall m b lo hi k p,\n  range_perm m b lo hi k p -> range_perm m b lo hi Max p.\nProof.\n  unfold range_perm; intros; eauto with mem.\nQed.\n\nHint Local Resolve range_perm_implies range_perm_cur range_perm_max: mem.\n\nLemma range_perm_dec:\n  forall m b lo hi k p, {range_perm m b lo hi k p} + {~ range_perm m b lo hi k p}.\nProof.\n  intros. \n  induction lo using (well_founded_induction_type (Zwf_up_well_founded hi)).\n  destruct (zlt lo hi).\n  destruct (perm_dec m b lo k p).\n  destruct (H (lo + 1)). red. omega. \n  left; red; intros. destruct (zeq lo ofs). congruence. apply r. omega. \n  right; red; intros. elim n. red; intros; apply H0; omega.\n  right; red; intros. elim n. apply H0. omega. \n  left; red; intros. omegaContradiction.\nDefined.\n\n(** [valid_access m chunk b ofs p] holds if a memory access\n    of the given chunk is possible in [m] at address [b, ofs]\n    with current permissions [p].\n    This means:\n- The range of bytes accessed all have current permission [p].\n- The offset [ofs] is aligned.\n*)\n\nDefinition valid_access (m: mem) (chunk: memory_chunk) (b: block) (ofs: Z) (p: permission): Prop :=\n  range_perm m b ofs (ofs + size_chunk chunk) Cur p\n  /\\ (align_chunk chunk | ofs).\n\nTheorem valid_access_implies:\n  forall m chunk b ofs p1 p2,\n  valid_access m chunk b ofs p1 -> perm_order p1 p2 ->\n  valid_access m chunk b ofs p2.\nProof.\n  intros. inv H. constructor; eauto with mem.\nQed.\n\nTheorem valid_access_freeable_any:\n  forall m chunk b ofs p,\n  valid_access m chunk b ofs Freeable ->\n  valid_access m chunk b ofs p.\nProof.\n  intros.\n  eapply valid_access_implies; eauto. constructor.\nQed.\n\nHint Local Resolve valid_access_implies: mem.\n\nTheorem valid_access_valid_block:\n  forall m chunk b ofs,\n  valid_access m chunk b ofs Nonempty ->\n  valid_block m b.\nProof.\n  intros. destruct H.\n  assert (perm m b ofs Cur Nonempty).\n    apply H. generalize (size_chunk_pos chunk). omega.\n  eauto with mem.\nQed.\n\nHint Local Resolve valid_access_valid_block: mem.\n\nLemma valid_access_perm:\n  forall m chunk b ofs k p,\n  valid_access m chunk b ofs p ->\n  perm m b ofs k p.\nProof.\n  intros. destruct H. apply perm_cur. apply H. generalize (size_chunk_pos chunk). omega.\nQed.\n\nLemma valid_access_compat:\n  forall m chunk1 chunk2 b ofs p,\n  size_chunk chunk1 = size_chunk chunk2 ->\n  align_chunk chunk2 <= align_chunk chunk1 ->\n  valid_access m chunk1 b ofs p->\n  valid_access m chunk2 b ofs p.\nProof.\n  intros. inv H1. rewrite H in H2. constructor; auto.\n  eapply Zdivide_trans; eauto. eapply align_le_divides; eauto.\nQed.\n\nLemma valid_access_dec:\n  forall m chunk b ofs p,\n  {valid_access m chunk b ofs p} + {~ valid_access m chunk b ofs p}.\nProof.\n  intros. \n  destruct (range_perm_dec m b ofs (ofs + size_chunk chunk) Cur p).\n  destruct (Zdivide_dec (align_chunk chunk) ofs (align_chunk_pos chunk)).\n  left; constructor; auto.\n  right; red; intro V; inv V; contradiction.\n  right; red; intro V; inv V; contradiction.\nDefined.\n\n(** [valid_pointer m b ofs] returns [true] if the address [b, ofs]\n  is nonempty in [m] and [false] if it is empty. *)\nDefinition valid_pointer (m: mem) (b: block) (ofs: Z): bool :=\n  perm_dec m b ofs Cur Nonempty.\n\nTheorem valid_pointer_nonempty_perm:\n  forall m b ofs,\n  valid_pointer m b ofs = true <-> perm m b ofs Cur Nonempty.\nProof.\n  intros. unfold valid_pointer. \n  destruct (perm_dec m b ofs Cur Nonempty); simpl;\n  intuition congruence.\nQed.\n\nTheorem valid_pointer_valid_access:\n  forall m b ofs,\n  valid_pointer m b ofs = true <-> valid_access m Mint8unsigned b ofs Nonempty.\nProof.\n  intros. rewrite valid_pointer_nonempty_perm. \n  split; intros.\n  split. simpl; red; intros. replace ofs0 with ofs by omega. auto.\n  simpl. apply Zone_divide. \n  destruct H. apply H. simpl. omega.\nQed.\n\n(** C allows pointers one past the last element of an array.  These are not\n  valid according to the previously defined [valid_pointer]. The property\n  [weak_valid_pointer m b ofs] holds if address [b, ofs] is a valid pointer\n  in [m], or a pointer one past a valid block in [m].  *)\n\nDefinition weak_valid_pointer (m: mem) (b: block) (ofs: Z) :=\n  valid_pointer m b ofs || valid_pointer m b (ofs - 1).\n\nLemma weak_valid_pointer_spec:\n  forall m b ofs,\n  weak_valid_pointer m b ofs = true <->\n    valid_pointer m b ofs = true \\/ valid_pointer m b (ofs - 1) = true.\nProof.\n  intros. unfold weak_valid_pointer. now rewrite orb_true_iff.\nQed.\nLemma valid_pointer_implies:\n  forall m b ofs,\n  valid_pointer m b ofs = true -> weak_valid_pointer m b ofs = true.\nProof.\n  intros. apply weak_valid_pointer_spec. auto.\nQed.\n\n(** * Operations over memory stores *)\n\n(** The initial store *)\n\nProgram Definition empty: mem :=\n  mkmem (ZMap.init (ZMap.init Undef))\n        (ZMap.init (fun ofs k => None))\n        1 _ _ _.\nNext Obligation.\n  omega.\nQed.\nNext Obligation.\n  repeat rewrite ZMap.gi. red; auto.\nQed.\nNext Obligation.\n  rewrite ZMap.gi. auto.\nQed.\n\nDefinition nullptr: block := 0.\n\n(** Allocation of a fresh block with the given bounds.  Return an updated\n  memory state and the address of the fresh block, which initially contains\n  undefined cells.  Note that allocation never fails: we model an\n  infinite memory. *)\n\nProgram Definition alloc (m: mem) (lo hi: Z) :=\n  (mkmem (ZMap.set m.(nextblock) \n                   (ZMap.init Undef)\n                   m.(mem_contents))\n         (ZMap.set m.(nextblock)\n                   (fun ofs k => if zle lo ofs && zlt ofs hi then Some Freeable else None)\n                   m.(mem_access))\n         (Zsucc m.(nextblock))\n         _ _ _,\n   m.(nextblock)).\nNext Obligation.\n  generalize (nextblock_pos m). omega. \nQed.\nNext Obligation.\n  repeat rewrite ZMap.gsspec. destruct (ZIndexed.eq b (nextblock m)). \n  subst b. destruct (zle lo ofs && zlt ofs hi); red; auto with mem. \n  apply access_max. \nQed.\nNext Obligation.\n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b (nextblock m)). \n  subst b. generalize (nextblock_pos m). intros. omegaContradiction.\n  apply nextblock_noaccess. omega.\nQed.\n\n(** Freeing a block between the given bounds.\n  Return the updated memory state where the given range of the given block\n  has been invalidated: future reads and writes to this\n  range will fail.  Requires freeable permission on the given range. *)\n\nProgram Definition unchecked_free (m: mem) (b: block) (lo hi: Z): mem :=\n  mkmem m.(mem_contents)\n        (ZMap.set b \n                (fun ofs k => if zle lo ofs && zlt ofs hi then None else m.(mem_access)#b ofs k)\n                m.(mem_access))\n        m.(nextblock) _ _ _.\nNext Obligation.\n  apply nextblock_pos. \nQed.\nNext Obligation.\n  repeat rewrite ZMap.gsspec. destruct (ZIndexed.eq b0 b).\n  destruct (zle lo ofs && zlt ofs hi). red; auto. apply access_max. \n  apply access_max.\nQed.\nNext Obligation.\n  repeat rewrite ZMap.gsspec. destruct (ZIndexed.eq b0 b). subst.\n  destruct (zle lo ofs && zlt ofs hi). auto. apply nextblock_noaccess; auto.\n  apply nextblock_noaccess; auto.\nQed.\n\nDefinition free (m: mem) (b: block) (lo hi: Z): option mem :=\n  if range_perm_dec m b lo hi Cur Freeable \n  then Some(unchecked_free m b lo hi)\n  else None.\n\nFixpoint free_list (m: mem) (l: list (block * Z * Z)) {struct l}: option mem :=\n  match l with\n  | nil => Some m\n  | (b, lo, hi) :: l' =>\n      match free m b lo hi with\n      | None => None\n      | Some m' => free_list m' l'\n      end\n  end.\n\n(** Memory reads. *)\n\n(** Reading N adjacent bytes in a block content. *)\n\nFixpoint getN (n: nat) (p: Z) (c: ZMap.t memval) {struct n}: list memval :=\n  match n with\n  | O => nil\n  | S n' => c#p :: getN n' (p + 1) c\n  end.\n\n(** [load chunk m b ofs] perform a read in memory state [m], at address\n  [b] and offset [ofs].  It returns the value of the memory chunk\n  at that address.  [None] is returned if the accessed bytes\n  are not readable. *)\n\nDefinition load (chunk: memory_chunk) (m: mem) (b: block) (ofs: Z): option val :=\n  if valid_access_dec m chunk b ofs Readable\n  then Some(decode_val chunk (getN (size_chunk_nat chunk) ofs (m.(mem_contents)#b)))\n  else None.\n\n(** [loadv chunk m addr] is similar, but the address and offset are given\n  as a single value [addr], which must be a pointer value. *)\n\nDefinition loadv (chunk: memory_chunk) (m: mem) (addr: val) : option val :=\n  match addr with\n  | Vptr b ofs => load chunk m b (Int.unsigned ofs)\n  | _ => None\n  end.\n\n(** [loadbytes m b ofs n] reads [n] consecutive bytes starting at\n  location [(b, ofs)].  Returns [None] if the accessed locations are\n  not readable. *)\n\nDefinition loadbytes (m: mem) (b: block) (ofs n: Z): option (list memval) :=\n  if range_perm_dec m b ofs (ofs + n) Cur Readable\n  then Some (getN (nat_of_Z n) ofs (m.(mem_contents)#b))\n  else None.\n\n(** Memory stores. *)\n\n(** Writing N adjacent bytes in a block content. *)\n\nFixpoint setN (vl: list memval) (p: Z) (c: ZMap.t memval) {struct vl}: ZMap.t memval :=\n  match vl with\n  | nil => c\n  | v :: vl' => setN vl' (p + 1) (ZMap.set p v c)\n  end.\n\nRemark setN_other:\n  forall vl c p q,\n  (forall r, p <= r < p + Z_of_nat (length vl) -> r <> q) ->\n  (setN vl p c)#q = c#q.\nProof.\n  induction vl; intros; simpl.\n  auto. \n  simpl length in H. rewrite inj_S in H.\n  transitivity ((ZMap.set p a c)#q).\n  apply IHvl. intros. apply H. omega.\n  apply ZMap.gso. apply not_eq_sym. apply H. omega. \nQed.\n\nRemark setN_outside:\n  forall vl c p q,\n  q < p \\/ q >= p + Z_of_nat (length vl) ->\n  (setN vl p c)#q = c#q.\nProof.\n  intros. apply setN_other. \n  intros. omega. \nQed.\n\nRemark getN_setN_same:\n  forall vl p c,\n  getN (length vl) p (setN vl p c) = vl.\nProof.\n  induction vl; intros; simpl.\n  auto.\n  decEq. \n  rewrite setN_outside. apply ZMap.gss. omega. \n  apply IHvl. \nQed.\n\nRemark getN_exten:\n  forall c1 c2 n p,\n  (forall i, p <= i < p + Z_of_nat n -> c1#i = c2#i) ->\n  getN n p c1 = getN n p c2.\nProof.\n  induction n; intros. auto. rewrite inj_S in H. simpl. decEq. \n  apply H. omega. apply IHn. intros. apply H. omega.\nQed.\n\nRemark getN_setN_outside:\n  forall vl q c n p,\n  p + Z_of_nat n <= q \\/ q + Z_of_nat (length vl) <= p ->\n  getN n p (setN vl q c) = getN n p c.\nProof.\n  intros. apply getN_exten. intros. apply setN_outside. omega. \nQed.\n\n(** [store chunk m b ofs v] perform a write in memory state [m].\n  Value [v] is stored at address [b] and offset [ofs].\n  Return the updated memory store, or [None] if the accessed bytes\n  are not writable. *)\n\nDefinition store (chunk: memory_chunk) (m: mem) (b: block) (ofs: Z) (v: val): option mem :=\n  if valid_access_dec m chunk b ofs Writable then\n    Some (mkmem (ZMap.set b \n                          (setN (encode_val chunk v) ofs (m.(mem_contents)#b))\n                          m.(mem_contents))\n                m.(mem_access)\n                m.(nextblock)\n                m.(nextblock_pos)\n                m.(access_max)\n                m.(nextblock_noaccess))\n  else\n    None.\n\n(** [storev chunk m addr v] is similar, but the address and offset are given\n  as a single value [addr], which must be a pointer value. *)\n\nDefinition storev (chunk: memory_chunk) (m: mem) (addr v: val) : option mem :=\n  match addr with\n  | Vptr b ofs => store chunk m b (Int.unsigned ofs) v\n  | _ => None\n  end.\n\n(** [storebytes m b ofs bytes] stores the given list of bytes [bytes]\n  starting at location [(b, ofs)].  Returns updated memory state\n  or [None] if the accessed locations are not writable. *)\n\nDefinition storebytes (m: mem) (b: block) (ofs: Z) (bytes: list memval) : option mem :=\n  if range_perm_dec m b ofs (ofs + Z_of_nat (length bytes)) Cur Writable then\n    Some (mkmem\n             (ZMap.set b (setN bytes ofs (m.(mem_contents)#b)) m.(mem_contents))\n             m.(mem_access)\n             m.(nextblock)\n             m.(nextblock_pos)\n             m.(access_max)\n             m.(nextblock_noaccess))\n  else\n    None.\n\n(** [drop_perm m b lo hi p] sets the max permissions of the byte range\n    [(b, lo) ... (b, hi - 1)] to [p].  These bytes must have current permissions\n    [Freeable] in the initial memory state [m].\n    Returns updated memory state, or [None] if insufficient permissions. *)\n\nProgram Definition drop_perm (m: mem) (b: block) (lo hi: Z) (p: permission): option mem :=\n  if range_perm_dec m b lo hi Cur Freeable then\n    Some (mkmem m.(mem_contents)\n                (ZMap.set b\n                        (fun ofs k => if zle lo ofs && zlt ofs hi then Some p else m.(mem_access)#b ofs k)\n                        m.(mem_access))\n                m.(nextblock) _ _ _)\n  else None.\nNext Obligation.\n  apply nextblock_pos.\nQed.\nNext Obligation.\n  repeat rewrite ZMap.gsspec. destruct (ZIndexed.eq b0 b). subst b0.\n  destruct (zle lo ofs && zlt ofs hi). red; auto with mem. apply access_max. \n  apply access_max.\nQed.\nNext Obligation.\n  specialize (nextblock_noaccess m b0 ofs k H0). intros. \n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b0 b). subst b0.\n  destruct (zle lo ofs). destruct (zlt ofs hi).\n  assert (perm m b ofs k Freeable). apply perm_cur. apply H; auto. \n  unfold perm in H2. rewrite H1 in H2. contradiction.\n  auto. auto. auto. \nQed.\n\n(** * Properties of the memory operations *)\n\n(** Properties of the empty store. *)\n\nTheorem nextblock_empty: nextblock empty = 1.\nProof. reflexivity. Qed.\n\nTheorem perm_empty: forall b ofs k p, ~perm empty b ofs k p.\nProof. \n  intros. unfold perm, empty; simpl. rewrite ZMap.gi. simpl. tauto. \nQed.\n\nTheorem valid_access_empty: forall chunk b ofs p, ~valid_access empty chunk b ofs p.\nProof.\n  intros. red; intros. elim (perm_empty b ofs Cur p). apply H. \n  generalize (size_chunk_pos chunk); omega.\nQed.\n\n(** ** Properties related to [load] *)\n\nTheorem valid_access_load:\n  forall m chunk b ofs,\n  valid_access m chunk b ofs Readable ->\n  exists v, load chunk m b ofs = Some v.\nProof.\n  intros. econstructor. unfold load. rewrite pred_dec_true; eauto.  \nQed.\n\nTheorem load_valid_access:\n  forall m chunk b ofs v,\n  load chunk m b ofs = Some v ->\n  valid_access m chunk b ofs Readable.\nProof.\n  intros until v. unfold load. \n  destruct (valid_access_dec m chunk b ofs Readable); intros.\n  auto. \n  congruence.\nQed.\n\nLemma load_result:\n  forall chunk m b ofs v,\n  load chunk m b ofs = Some v ->\n  v = decode_val chunk (getN (size_chunk_nat chunk) ofs (m.(mem_contents)#b)).\nProof.\n  intros until v. unfold load. \n  destruct (valid_access_dec m chunk b ofs Readable); intros.\n  congruence.\n  congruence.\nQed.\n\nHint Local Resolve load_valid_access valid_access_load: mem.\n\nTheorem load_type:\n  forall m chunk b ofs v,\n  load chunk m b ofs = Some v ->\n  Val.has_type v (type_of_chunk chunk).\nProof.\n  intros. exploit load_result; eauto; intros. rewrite H0. \n  apply decode_val_type. \nQed.\n\nTheorem load_cast:\n  forall m chunk b ofs v,\n  load chunk m b ofs = Some v ->\n  match chunk with\n  | Mint8signed => v = Val.sign_ext 8 v\n  | Mint8unsigned => v = Val.zero_ext 8 v\n  | Mint16signed => v = Val.sign_ext 16 v\n  | Mint16unsigned => v = Val.zero_ext 16 v\n  | Mfloat32 => v = Val.singleoffloat v\n  | _ => True\n  end.\nProof.\n  intros. exploit load_result; eauto.\n  set (l := getN (size_chunk_nat chunk) ofs m.(mem_contents)#b).\n  intros. subst v. apply decode_val_cast. \nQed.\n\nTheorem load_int8_signed_unsigned:\n  forall m b ofs,\n  load Mint8signed m b ofs = option_map (Val.sign_ext 8) (load Mint8unsigned m b ofs).\nProof.\n  intros. unfold load.\n  change (size_chunk_nat Mint8signed) with (size_chunk_nat Mint8unsigned).\n  set (cl := getN (size_chunk_nat Mint8unsigned) ofs m.(mem_contents)#b).\n  destruct (valid_access_dec m Mint8signed b ofs Readable).\n  rewrite pred_dec_true; auto. unfold decode_val. \n  destruct (proj_bytes cl); auto.\n  simpl. decEq. decEq. rewrite Int.sign_ext_zero_ext. auto. compute; auto.\n  rewrite pred_dec_false; auto.\nQed.\n\nTheorem load_int16_signed_unsigned:\n  forall m b ofs,\n  load Mint16signed m b ofs = option_map (Val.sign_ext 16) (load Mint16unsigned m b ofs).\nProof.\n  intros. unfold load.\n  change (size_chunk_nat Mint16signed) with (size_chunk_nat Mint16unsigned).\n  set (cl := getN (size_chunk_nat Mint16unsigned) ofs m.(mem_contents)#b).\n  destruct (valid_access_dec m Mint16signed b ofs Readable).\n  rewrite pred_dec_true; auto. unfold decode_val. \n  destruct (proj_bytes cl); auto.\n  simpl. decEq. decEq. rewrite Int.sign_ext_zero_ext. auto. compute; auto.\n  rewrite pred_dec_false; auto.\nQed.\n\nTheorem load_float64al32:\n  forall m b ofs v,\n  load Mfloat64 m b ofs = Some v -> load Mfloat64al32 m b ofs = Some v.\nProof.\n  unfold load; intros. destruct (valid_access_dec m Mfloat64 b ofs Readable); try discriminate.\n  rewrite pred_dec_true. assumption. \n  apply valid_access_compat with Mfloat64; auto. simpl; omega. \nQed.\n\nTheorem loadv_float64al32:\n  forall m a v,\n  loadv Mfloat64 m a = Some v -> loadv Mfloat64al32 m a = Some v.\nProof.\n  unfold loadv; intros. destruct a; auto. apply load_float64al32; auto.\nQed.\n\n(** ** Properties related to [loadbytes] *)\n\nTheorem range_perm_loadbytes:\n  forall m b ofs len,\n  range_perm m b ofs (ofs + len) Cur Readable ->\n  exists bytes, loadbytes m b ofs len = Some bytes.\nProof.\n  intros. econstructor. unfold loadbytes. rewrite pred_dec_true; eauto. \nQed.\n\nTheorem loadbytes_range_perm:\n  forall m b ofs len bytes,\n  loadbytes m b ofs len = Some bytes ->\n  range_perm m b ofs (ofs + len) Cur Readable.\nProof.\n  intros until bytes. unfold loadbytes.\n  destruct (range_perm_dec m b ofs (ofs + len) Cur Readable). auto. congruence.\nQed.\n\nTheorem loadbytes_load:\n  forall chunk m b ofs bytes,\n  loadbytes m b ofs (size_chunk chunk) = Some bytes ->\n  (align_chunk chunk | ofs) ->\n  load chunk m b ofs = Some(decode_val chunk bytes).\nProof.\n  unfold loadbytes, load; intros. \n  destruct (range_perm_dec m b ofs (ofs + size_chunk chunk) Cur Readable);\n  try congruence.\n  inv H. rewrite pred_dec_true. auto. \n  split; auto.\nQed.\n\nTheorem load_loadbytes:\n  forall chunk m b ofs v,\n  load chunk m b ofs = Some v ->\n  exists bytes, loadbytes m b ofs (size_chunk chunk) = Some bytes\n             /\\ v = decode_val chunk bytes.\nProof.\n  intros. exploit load_valid_access; eauto. intros [A B].\n  exploit load_result; eauto. intros. \n  exists (getN (size_chunk_nat chunk) ofs m.(mem_contents)#b); split.\n  unfold loadbytes. rewrite pred_dec_true; auto. \n  auto.\nQed.\n\nLemma getN_length:\n  forall c n p, length (getN n p c) = n.\nProof.\n  induction n; simpl; intros. auto. decEq; auto.\nQed.\n\nTheorem loadbytes_length:\n  forall m b ofs n bytes,\n  loadbytes m b ofs n = Some bytes ->\n  length bytes = nat_of_Z n.\nProof.\n  unfold loadbytes; intros.\n  destruct (range_perm_dec m b ofs (ofs + n) Cur Readable); try congruence.\n  inv H. apply getN_length.\nQed.\n\nTheorem loadbytes_empty:\n  forall m b ofs n,\n  n <= 0 -> loadbytes m b ofs n = Some nil.\nProof.\n  intros. unfold loadbytes. rewrite pred_dec_true. rewrite nat_of_Z_neg; auto.\n  red; intros. omegaContradiction.\nQed.\n  \nLemma getN_concat:\n  forall c n1 n2 p,\n  getN (n1 + n2)%nat p c = getN n1 p c ++ getN n2 (p + Z_of_nat n1) c.\nProof.\n  induction n1; intros.\n  simpl. decEq. omega.\n  rewrite inj_S. simpl. decEq.\n  replace (p + Zsucc (Z_of_nat n1)) with ((p + 1) + Z_of_nat n1) by omega.\n  auto. \nQed.\n\nTheorem loadbytes_concat:\n  forall m b ofs n1 n2 bytes1 bytes2,\n  loadbytes m b ofs n1 = Some bytes1 ->\n  loadbytes m b (ofs + n1) n2 = Some bytes2 ->\n  n1 >= 0 -> n2 >= 0 ->\n  loadbytes m b ofs (n1 + n2) = Some(bytes1 ++ bytes2).\nProof.\n  unfold loadbytes; intros.\n  destruct (range_perm_dec m b ofs (ofs + n1) Cur Readable); try congruence.\n  destruct (range_perm_dec m b (ofs + n1) (ofs + n1 + n2) Cur Readable); try congruence.\n  rewrite pred_dec_true. rewrite nat_of_Z_plus; auto.\n  rewrite getN_concat. rewrite nat_of_Z_eq; auto.\n  congruence.\n  red; intros. \n  assert (ofs0 < ofs + n1 \\/ ofs0 >= ofs + n1) by omega.\n  destruct H4. apply r; omega. apply r0; omega.\nQed.\n\nTheorem loadbytes_split:\n  forall m b ofs n1 n2 bytes,\n  loadbytes m b ofs (n1 + n2) = Some bytes ->\n  n1 >= 0 -> n2 >= 0 ->\n  exists bytes1, exists bytes2,\n     loadbytes m b ofs n1 = Some bytes1 \n  /\\ loadbytes m b (ofs + n1) n2 = Some bytes2\n  /\\ bytes = bytes1 ++ bytes2.\nProof.\n  unfold loadbytes; intros. \n  destruct (range_perm_dec m b ofs (ofs + (n1 + n2)) Cur Readable);\n  try congruence.\n  rewrite nat_of_Z_plus in H; auto. rewrite getN_concat in H.\n  rewrite nat_of_Z_eq in H; auto. \n  repeat rewrite pred_dec_true.\n  econstructor; econstructor.\n  split. reflexivity. split. reflexivity. congruence.\n  red; intros; apply r; omega.\n  red; intros; apply r; omega.\nQed.\n\nTheorem load_rep:\n forall ch m1 m2 b ofs v1 v2, \n  (forall z, 0 <= z < size_chunk ch -> m1.(mem_contents)#b#(ofs+z) = m2.(mem_contents)#b#(ofs+z)) ->\n  load ch m1 b ofs = Some v1 ->\n  load ch m2 b ofs = Some v2 ->\n  v1 = v2.\nProof.\n  intros.\n  apply load_result in H0.\n  apply load_result in H1.\n  subst.\n  f_equal.\n  rewrite size_chunk_conv in H.\n  remember (size_chunk_nat ch) as n; clear Heqn.\n  revert ofs H; induction n; intros; simpl; auto.\n  f_equal.\n  rewrite inj_S in H.\n  replace ofs with (ofs+0) by omega.\n  apply H; omega.\n  apply IHn.\n  intros.\n  rewrite <- Zplus_assoc.\n  apply H.\n  rewrite inj_S. omega.\nQed.\n\n(** ** Properties related to [store] *)\n\nTheorem valid_access_store:\n  forall m1 chunk b ofs v,\n  valid_access m1 chunk b ofs Writable ->\n  { m2: mem | store chunk m1 b ofs v = Some m2 }.\nProof.\n  intros.\n  unfold store. \n  destruct (valid_access_dec m1 chunk b ofs Writable).\n  eauto.\n  contradiction.\nDefined.\n\nHint Local Resolve valid_access_store: mem.\n\nSection STORE.\nVariable chunk: memory_chunk.\nVariable m1: mem.\nVariable b: block.\nVariable ofs: Z.\nVariable v: val.\nVariable m2: mem.\nHypothesis STORE: store chunk m1 b ofs v = Some m2.\n\nLemma store_access: mem_access m2 = mem_access m1.\nProof.\n  unfold store in STORE. destruct ( valid_access_dec m1 chunk b ofs Writable); inv STORE.\n  auto.\nQed.\n\nLemma store_mem_contents: \n  mem_contents m2 = ZMap.set b (setN (encode_val chunk v) ofs m1.(mem_contents)#b) m1.(mem_contents).\nProof.\n  unfold store in STORE. destruct ( valid_access_dec m1 chunk b ofs Writable); inv STORE.\n  auto.\nQed.\n\nTheorem perm_store_1:\n  forall b' ofs' k p, perm m1 b' ofs' k p -> perm m2 b' ofs' k p.\nProof.\n  intros. \n unfold perm in *. rewrite store_access; auto.\nQed.\n\nTheorem perm_store_2:\n  forall b' ofs' k p, perm m2 b' ofs' k p -> perm m1 b' ofs' k p.\nProof.\n  intros. unfold perm in *.  rewrite store_access in H; auto.\nQed.\n\nLocal Hint Resolve perm_store_1 perm_store_2: mem.\n\nTheorem nextblock_store:\n  nextblock m2 = nextblock m1.\nProof.\n  intros.\n  unfold store in STORE. destruct ( valid_access_dec m1 chunk b ofs Writable); inv STORE.\n  auto.\nQed.\n\nTheorem store_valid_block_1:\n  forall b', valid_block m1 b' -> valid_block m2 b'.\nProof.\n  unfold valid_block; intros. rewrite nextblock_store; auto.\nQed.\n\nTheorem store_valid_block_2:\n  forall b', valid_block m2 b' -> valid_block m1 b'.\nProof.\n  unfold valid_block; intros. rewrite nextblock_store in H; auto.\nQed.\n\nLocal Hint Resolve store_valid_block_1 store_valid_block_2: mem.\n\nTheorem store_valid_access_1:\n  forall chunk' b' ofs' p,\n  valid_access m1 chunk' b' ofs' p -> valid_access m2 chunk' b' ofs' p.\nProof.\n  intros. inv H. constructor; try red; auto with mem.\nQed.\n\nTheorem store_valid_access_2:\n  forall chunk' b' ofs' p,\n  valid_access m2 chunk' b' ofs' p -> valid_access m1 chunk' b' ofs' p.\nProof.\n  intros. inv H. constructor; try red; auto with mem.\nQed.\n\nTheorem store_valid_access_3:\n  valid_access m1 chunk b ofs Writable.\nProof.\n  unfold store in STORE. destruct (valid_access_dec m1 chunk b ofs Writable).\n  auto. \n  congruence.\nQed.\n\nLocal Hint Resolve store_valid_access_1 store_valid_access_2 store_valid_access_3: mem.\n\nTheorem load_store_similar:\n  forall chunk',\n  size_chunk chunk' = size_chunk chunk ->\n  align_chunk chunk' <= align_chunk chunk ->\n  exists v', load chunk' m2 b ofs = Some v' /\\ decode_encode_val v chunk chunk' v'.\nProof.\n  intros.\n  exploit (valid_access_load m2 chunk').\n    eapply valid_access_compat. symmetry; eauto. auto. eauto with mem. \n  intros [v' LOAD].\n  exists v'; split; auto.\n  exploit load_result; eauto. intros B. \n  rewrite B. rewrite store_mem_contents; simpl. \n  rewrite ZMap.gss.\n  replace (size_chunk_nat chunk') with (length (encode_val chunk v)).\n  rewrite getN_setN_same. apply decode_encode_val_general. \n  rewrite encode_val_length. repeat rewrite size_chunk_conv in H. \n  apply inj_eq_rev; auto.\nQed.\n\nTheorem load_store_similar_2:\n  forall chunk',\n  size_chunk chunk' = size_chunk chunk ->\n  align_chunk chunk' <= align_chunk chunk ->\n  type_of_chunk chunk' = type_of_chunk chunk ->\n  load chunk' m2 b ofs = Some (Val.load_result chunk' v).\nProof.\n  intros. destruct (load_store_similar chunk') as [v' [A B]]; auto.\n  rewrite A. decEq. eapply decode_encode_val_similar with (chunk1 := chunk); eauto.\nQed.\n\nTheorem load_store_same:\n  load chunk m2 b ofs = Some (Val.load_result chunk v).\nProof.\n  apply load_store_similar_2; auto. omega.\nQed.\n\nTheorem load_store_other:\n  forall chunk' b' ofs',\n  b' <> b\n  \\/ ofs' + size_chunk chunk' <= ofs\n  \\/ ofs + size_chunk chunk <= ofs' ->\n  load chunk' m2 b' ofs' = load chunk' m1 b' ofs'.\nProof.\n  intros. unfold load. \n  destruct (valid_access_dec m1 chunk' b' ofs' Readable).\n  rewrite pred_dec_true. \n  decEq. decEq. rewrite store_mem_contents; simpl.\n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b' b). subst b'.\n  apply getN_setN_outside. rewrite encode_val_length. repeat rewrite <- size_chunk_conv.\n  intuition.\n  auto.\n  eauto with mem.\n  rewrite pred_dec_false. auto.\n  eauto with mem. \nQed.\n\nTheorem loadbytes_store_same:\n  loadbytes m2 b ofs (size_chunk chunk) = Some(encode_val chunk v).\nProof.\n  intros.\n  assert (valid_access m2 chunk b ofs Readable) by eauto with mem.\n  unfold loadbytes. rewrite pred_dec_true. rewrite store_mem_contents; simpl. \n  rewrite ZMap.gss.\n  replace (nat_of_Z (size_chunk chunk)) with (length (encode_val chunk v)).\n  rewrite getN_setN_same. auto.\n  rewrite encode_val_length. auto.\n  apply H. \nQed.\n\nTheorem loadbytes_store_other:\n  forall b' ofs' n,\n  b' <> b\n  \\/ n <= 0\n  \\/ ofs' + n <= ofs\n  \\/ ofs + size_chunk chunk <= ofs' ->\n  loadbytes m2 b' ofs' n = loadbytes m1 b' ofs' n.\nProof.\n  intros. unfold loadbytes. \n  destruct (range_perm_dec m1 b' ofs' (ofs' + n) Cur Readable).\n  rewrite pred_dec_true. \n  decEq. rewrite store_mem_contents; simpl.\n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b' b). subst b'.\n  destruct H. congruence.\n  destruct (zle n 0) as [z | n0].\n  rewrite (nat_of_Z_neg _ z). auto.\n  destruct H. omegaContradiction.\n  apply getN_setN_outside. rewrite encode_val_length. rewrite <- size_chunk_conv.\n  rewrite nat_of_Z_eq. auto. omega. \n  auto.\n  red; intros. eauto with mem.\n  rewrite pred_dec_false. auto.\n  red; intro; elim n0; red; intros; eauto with mem.\nQed.\n\nLemma setN_property:\n  forall (P: memval -> Prop) vl p q c,\n  (forall v, In v vl -> P v) ->\n  p <= q < p + Z_of_nat (length vl) ->\n  P((setN vl p c)#q).\nProof.\n  induction vl; intros.\n  simpl in H0. omegaContradiction.\n  simpl length in H0. rewrite inj_S in H0. simpl. \n  destruct (zeq p q). subst q. rewrite setN_outside. rewrite ZMap.gss. \n  auto with coqlib. omega.\n  apply IHvl. auto with coqlib. omega.\nQed.\n\nLemma getN_in:\n  forall c q n p,\n  p <= q < p + Z_of_nat n ->\n  In (c#q) (getN n p c).\nProof.\n  induction n; intros.\n  simpl in H; omegaContradiction.\n  rewrite inj_S in H. simpl. destruct (zeq p q).\n  subst q. auto.\n  right. apply IHn. omega. \nQed.\n\nTheorem load_pointer_store:\n  forall chunk' b' ofs' v_b v_o,\n  load chunk' m2 b' ofs' = Some(Vptr v_b v_o) ->\n  (chunk = Mint32 /\\ v = Vptr v_b v_o /\\ chunk' = Mint32 /\\ b' = b /\\ ofs' = ofs)\n  \\/ (b' <> b \\/ ofs' + size_chunk chunk' <= ofs \\/ ofs + size_chunk chunk <= ofs').\nProof.\n  intros. exploit load_result; eauto. rewrite store_mem_contents; simpl. \n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b' b); auto. subst b'. intro DEC.\n  destruct (zle (ofs' + size_chunk chunk') ofs); auto.\n  destruct (zle (ofs + size_chunk chunk) ofs'); auto.\n  destruct (size_chunk_nat_pos chunk) as [sz SZ].\n  destruct (size_chunk_nat_pos chunk') as [sz' SZ'].\n  exploit decode_pointer_shape; eauto. intros [CHUNK' PSHAPE]. clear CHUNK'.\n  generalize (encode_val_shape chunk v). intro VSHAPE.  \n  set (c := m1.(mem_contents)#b) in *.\n  set (c' := setN (encode_val chunk v) ofs c) in *.\n  destruct (zeq ofs ofs').\n\n(* 1.  ofs = ofs':  must be same chunks and same value *)\n  subst ofs'. inv VSHAPE. \n  exploit decode_val_pointer_inv; eauto. intros [A B].\n  subst chunk'. simpl in B. inv B.\n  generalize H4. unfold c'. rewrite <- H0. simpl. \n  rewrite setN_outside; try omega. rewrite ZMap.gss. intros.\n  exploit (encode_val_pointer_inv chunk v v_b v_o). \n  rewrite <- H0. subst mv1. eauto. intros [C [D E]].\n  left; auto.\n\n  destruct (zlt ofs ofs').\n\n(* 2. ofs < ofs':\n\n      ofs   ofs'   ofs+|chunk|\n       [-------------------]       write\n            [-------------------]  read\n\n   The byte at ofs' satisfies memval_valid_cont (consequence of write).\n   For the read to return a pointer, it must satisfy ~memval_valid_cont. \n*)\n  elimtype False.\n  assert (~memval_valid_cont (c'#ofs')).\n    rewrite SZ' in PSHAPE. simpl in PSHAPE. inv PSHAPE. auto.\n  assert (memval_valid_cont (c'#ofs')).\n    inv VSHAPE. unfold c'. rewrite <- H1. simpl. \n    apply setN_property. auto.\n    assert (length mvl = sz). \n      generalize (encode_val_length chunk v). rewrite <- H1. rewrite SZ. \n      simpl; congruence.\n    rewrite H4. rewrite size_chunk_conv in *. omega.\n  contradiction.\n\n(* 3. ofs > ofs':\n\n      ofs'   ofs   ofs'+|chunk'|\n              [-------------------]  write\n        [----------------]           read\n\n   The byte at ofs satisfies memval_valid_first (consequence of write).\n   For the read to return a pointer, it must satisfy ~memval_valid_first.\n*)\n  elimtype False.\n  assert (memval_valid_first (c'#ofs)).\n    inv VSHAPE. unfold c'. rewrite <- H0. simpl. \n    rewrite setN_outside. rewrite ZMap.gss. auto. omega.\n  assert (~memval_valid_first (c'#ofs)).\n    rewrite SZ' in PSHAPE. simpl in PSHAPE. inv PSHAPE. \n    apply H4. apply getN_in. rewrite size_chunk_conv in *.\n    rewrite SZ' in *. rewrite inj_S in *. omega.\n  contradiction.\nQed.\n\nEnd STORE.\n\nLocal Hint Resolve perm_store_1 perm_store_2: mem.\nLocal Hint Resolve store_valid_block_1 store_valid_block_2: mem.\nLocal Hint Resolve store_valid_access_1 store_valid_access_2\n             store_valid_access_3: mem.\n\nTheorem load_store_pointer_overlap:\n  forall chunk m1 b ofs v_b v_o m2 chunk' ofs' v,\n  store chunk m1 b ofs (Vptr v_b v_o) = Some m2 ->\n  load chunk' m2 b ofs' = Some v ->\n  ofs' <> ofs ->\n  ofs' + size_chunk chunk' > ofs ->\n  ofs + size_chunk chunk > ofs' ->\n  v = Vundef.\nProof.\n  intros.\n  exploit store_mem_contents; eauto. intro ST.\n  exploit load_result; eauto. intro LD.\n  rewrite LD; clear LD.\nOpaque encode_val.\n  rewrite ST; simpl.\n  rewrite ZMap.gss.\n  set (c := m1.(mem_contents)#b).\n  set (c' := setN (encode_val chunk (Vptr v_b v_o)) ofs c).\n  destruct (decode_val_shape chunk' (getN (size_chunk_nat chunk') ofs' c'))\n  as [OK | VSHAPE].\n  apply getN_length. \n  exact OK.\n  elimtype False.\n  destruct (size_chunk_nat_pos chunk) as [sz SZ]. \n  destruct (size_chunk_nat_pos chunk') as [sz' SZ']. \n  assert (ENC: encode_val chunk (Vptr v_b v_o) = list_repeat (size_chunk_nat chunk) Undef\n               \\/ pointer_encoding_shape (encode_val chunk (Vptr v_b v_o))).\n  destruct chunk; try (left; reflexivity). \n  right. apply encode_pointer_shape. \n  assert (GET: getN (size_chunk_nat chunk) ofs c' = encode_val chunk (Vptr v_b v_o)).\n  unfold c'. rewrite <- (encode_val_length chunk (Vptr v_b v_o)). \n  apply getN_setN_same.\n  destruct (zlt ofs ofs').\n\n(* ofs < ofs':\n\n      ofs   ofs'   ofs+|chunk|\n       [-------------------]       write\n            [-------------------]  read\n\n   The byte at ofs' is Undef or not memval_valid_first (because write of pointer).\n   The byte at ofs' must be memval_valid_first and not Undef (otherwise load returns Vundef).\n*)\n  assert (memval_valid_first (c'#ofs') /\\ c'#ofs' <> Undef).\n    rewrite SZ' in VSHAPE. simpl in VSHAPE. inv VSHAPE. auto.\n  assert (~memval_valid_first (c'#ofs') \\/ c'#ofs' = Undef).\n    unfold c'. destruct ENC.\n    right. apply setN_property. rewrite H5. intros. eapply in_list_repeat; eauto.\n    rewrite encode_val_length. rewrite <- size_chunk_conv. omega.\n    left. revert H5. rewrite <- GET. rewrite SZ. simpl. intros. inv H5.\n    apply setN_property. apply H9. rewrite getN_length.\n    rewrite size_chunk_conv in H3. rewrite SZ in H3. rewrite inj_S in H3. omega. \n  intuition. \n\n(* ofs > ofs':\n\n      ofs'   ofs   ofs'+|chunk'|\n              [-------------------]  write\n        [----------------]           read\n\n   The byte at ofs is Undef or not memval_valid_cont (because write of pointer).\n   The byte at ofs must be memval_valid_cont and not Undef (otherwise load returns Vundef).\n*)\n  assert (memval_valid_cont (c'#ofs) /\\ c'#ofs <> Undef).\n    rewrite SZ' in VSHAPE. simpl in VSHAPE. inv VSHAPE. \n    apply H8. apply getN_in. rewrite size_chunk_conv in H2. \n    rewrite SZ' in H2. rewrite inj_S in H2. omega. \n  assert (~memval_valid_cont (c'#ofs) \\/ c'#ofs = Undef).\n    elim ENC. \n    rewrite <- GET. rewrite SZ. simpl. intros. right; congruence.\n    rewrite <- GET. rewrite SZ. simpl. intros. inv H5. auto.\n  intuition.\nQed.\n\nTheorem load_store_pointer_mismatch:\n  forall chunk m1 b ofs v_b v_o m2 chunk' v,\n  store chunk m1 b ofs (Vptr v_b v_o) = Some m2 ->\n  load chunk' m2 b ofs = Some v ->\n  chunk <> Mint32 \\/ chunk' <> Mint32 ->\n  v = Vundef.\nProof.\n  intros.\n  exploit store_mem_contents; eauto. intro ST.\n  exploit load_result; eauto. intro LD.\n  rewrite LD; clear LD.\nOpaque encode_val.\n  rewrite ST; simpl.\n  rewrite ZMap.gss. \n  set (c1 := m1.(mem_contents)#b).\n  set (e := encode_val chunk (Vptr v_b v_o)).\n  destruct (size_chunk_nat_pos chunk) as [sz SZ].\n  destruct (size_chunk_nat_pos chunk') as [sz' SZ'].\n  assert (match e with\n          | Undef :: _ => True\n          | Pointer _ _ _ :: _ => chunk = Mint32\n          | _ => False\n          end).\nTransparent encode_val.\n  unfold e, encode_val. rewrite SZ. destruct chunk; simpl; auto.\n  destruct e as [ | e1 el]. contradiction.\n  rewrite SZ'. simpl. rewrite setN_outside. rewrite ZMap.gss. \n  destruct e1; try contradiction. \n  destruct chunk'; auto. \n  destruct chunk'; auto. intuition.\n  omega.\nQed.\n\nLemma store_similar_chunks:\n  forall chunk1 chunk2 v1 v2 m b ofs,\n  encode_val chunk1 v1 = encode_val chunk2 v2 ->\n  align_chunk chunk1 = align_chunk chunk2 ->\n  store chunk1 m b ofs v1 = store chunk2 m b ofs v2.\nProof.\n  intros. unfold store. \n  assert (size_chunk chunk1 = size_chunk chunk2).\n    repeat rewrite size_chunk_conv.\n    rewrite <- (encode_val_length chunk1 v1).\n    rewrite <- (encode_val_length chunk2 v2).\n    congruence.\n  unfold store.\n  destruct (valid_access_dec m chunk1 b ofs Writable).\n  rewrite pred_dec_true. \n  f_equal. apply mkmem_ext; auto. congruence.\n  apply valid_access_compat with chunk1; auto. omega.\n  destruct (valid_access_dec m chunk2 b ofs Writable); auto.\n  elim n. apply valid_access_compat with chunk2; auto. omega.\nQed.\n\nTheorem store_signed_unsigned_8:\n  forall m b ofs v,\n  store Mint8signed m b ofs v = store Mint8unsigned m b ofs v.\nProof. intros. apply store_similar_chunks. apply encode_val_int8_signed_unsigned. auto. Qed.\n\nTheorem store_signed_unsigned_16:\n  forall m b ofs v,\n  store Mint16signed m b ofs v = store Mint16unsigned m b ofs v.\nProof. intros. apply store_similar_chunks. apply encode_val_int16_signed_unsigned. auto. Qed.\n\nTheorem store_int8_zero_ext:\n  forall m b ofs n,\n  store Mint8unsigned m b ofs (Vint (Int.zero_ext 8 n)) =\n  store Mint8unsigned m b ofs (Vint n).\nProof. intros. apply store_similar_chunks. apply encode_val_int8_zero_ext. auto. Qed.\n\nTheorem store_int8_sign_ext:\n  forall m b ofs n,\n  store Mint8signed m b ofs (Vint (Int.sign_ext 8 n)) =\n  store Mint8signed m b ofs (Vint n).\nProof. intros. apply store_similar_chunks. apply encode_val_int8_sign_ext. auto. Qed.\n\nTheorem store_int16_zero_ext:\n  forall m b ofs n,\n  store Mint16unsigned m b ofs (Vint (Int.zero_ext 16 n)) =\n  store Mint16unsigned m b ofs (Vint n).\nProof. intros. apply store_similar_chunks. apply encode_val_int16_zero_ext. auto. Qed.\n\nTheorem store_int16_sign_ext:\n  forall m b ofs n,\n  store Mint16signed m b ofs (Vint (Int.sign_ext 16 n)) =\n  store Mint16signed m b ofs (Vint n).\nProof. intros. apply store_similar_chunks. apply encode_val_int16_sign_ext. auto. Qed.\n\nTheorem store_float32_truncate:\n  forall m b ofs n,\n  store Mfloat32 m b ofs (Vfloat (Float.singleoffloat n)) =\n  store Mfloat32 m b ofs (Vfloat n).\nProof.\n  intros. apply store_similar_chunks. simpl. decEq.\n  repeat rewrite encode_float32_eq. rewrite Float.bits_of_singleoffloat. auto.\n  auto.\nQed.\n\nTheorem store_float64al32:\n  forall m b ofs v m',\n  store Mfloat64 m b ofs v = Some m' -> store Mfloat64al32 m b ofs v = Some m'.\nProof.\n  unfold store; intros. \n  destruct (valid_access_dec m Mfloat64 b ofs Writable); try discriminate.\n  rewrite pred_dec_true. rewrite <- H. auto. \n  apply valid_access_compat with Mfloat64; auto. simpl; omega.\nQed.\n\nTheorem storev_float64al32:\n  forall m a v m',\n  storev Mfloat64 m a v = Some m' -> storev Mfloat64al32 m a v = Some m'.\nProof.\n  unfold storev; intros. destruct a; auto. apply store_float64al32; auto.\nQed.\n\n(** ** Properties related to [storebytes]. *)\n\nTheorem range_perm_storebytes:\n  forall m1 b ofs bytes,\n  range_perm m1 b ofs (ofs + Z_of_nat (length bytes)) Cur Writable ->\n  { m2 : mem | storebytes m1 b ofs bytes = Some m2 }.\nProof.\n  intros. econstructor. unfold storebytes.\n  destruct (range_perm_dec m1 b ofs (ofs + Z_of_nat (length bytes)) Cur Writable).\n  reflexivity. \n  contradiction.\nDefined.\n\nTheorem storebytes_store:\n  forall m1 b ofs chunk v m2,\n  storebytes m1 b ofs (encode_val chunk v) = Some m2 ->\n  (align_chunk chunk | ofs) ->\n  store chunk m1 b ofs v = Some m2.\nProof.\n  unfold storebytes, store. intros. \n  destruct (range_perm_dec m1 b ofs (ofs + Z_of_nat (length (encode_val chunk v))) Cur Writable); inv H.\n  destruct (valid_access_dec m1 chunk b ofs Writable).\n  auto.\n  elim n. constructor; auto. \n  rewrite encode_val_length in r. rewrite size_chunk_conv. auto.\nQed.\n\nTheorem store_storebytes:\n  forall m1 b ofs chunk v m2,\n  store chunk m1 b ofs v = Some m2 ->\n  storebytes m1 b ofs (encode_val chunk v) = Some m2.\nProof.\n  unfold storebytes, store. intros. \n  destruct (valid_access_dec m1 chunk b ofs Writable); inv H.\n  destruct (range_perm_dec m1 b ofs (ofs + Z_of_nat (length (encode_val chunk v))) Cur Writable).\n  auto.\n  destruct v0.  elim n. \n  rewrite encode_val_length. rewrite <- size_chunk_conv. auto.\nQed.\n  \nSection STOREBYTES.\nVariable m1: mem.\nVariable b: block.\nVariable ofs: Z.\nVariable bytes: list memval.\nVariable m2: mem.\nHypothesis STORE: storebytes m1 b ofs bytes = Some m2.\n\nLemma storebytes_access: mem_access m2 = mem_access m1.\nProof.\n  unfold storebytes in STORE. \n  destruct (range_perm_dec m1 b ofs (ofs + Z_of_nat (length bytes)) Cur Writable);\n  inv STORE.\n  auto.\nQed.\n\nLemma storebytes_mem_contents:\n   mem_contents m2 = ZMap.set b (setN bytes ofs m1.(mem_contents)#b) m1.(mem_contents).\nProof.\n  unfold storebytes in STORE. \n  destruct (range_perm_dec m1 b ofs (ofs + Z_of_nat (length bytes)) Cur Writable);\n  inv STORE.\n  auto.\nQed.\n\nTheorem perm_storebytes_1:\n  forall b' ofs' k p, perm m1 b' ofs' k p -> perm m2 b' ofs' k p.\nProof.\n  intros. unfold perm in *. rewrite storebytes_access; auto.\nQed.\n\nTheorem perm_storebytes_2:\n  forall b' ofs' k p, perm m2 b' ofs' k p -> perm m1 b' ofs' k p.\nProof.\n  intros. unfold perm in *. rewrite storebytes_access in H; auto.\nQed.\n\nLocal Hint Resolve perm_storebytes_1 perm_storebytes_2: mem.\n\nTheorem storebytes_valid_access_1:\n  forall chunk' b' ofs' p,\n  valid_access m1 chunk' b' ofs' p -> valid_access m2 chunk' b' ofs' p.\nProof.\n  intros. inv H. constructor; try red; auto with mem.\nQed.\n\nTheorem storebytes_valid_access_2:\n  forall chunk' b' ofs' p,\n  valid_access m2 chunk' b' ofs' p -> valid_access m1 chunk' b' ofs' p.\nProof.\n  intros. inv H. constructor; try red; auto with mem.\nQed.\n\nLocal Hint Resolve storebytes_valid_access_1 storebytes_valid_access_2: mem.\n\nTheorem nextblock_storebytes:\n  nextblock m2 = nextblock m1.\nProof.\n  intros.\n  unfold storebytes in STORE. \n  destruct (range_perm_dec m1 b ofs (ofs + Z_of_nat (length bytes)) Cur Writable);\n  inv STORE.\n  auto.\nQed.\n\nTheorem storebytes_valid_block_1:\n  forall b', valid_block m1 b' -> valid_block m2 b'.\nProof.\n  unfold valid_block; intros. rewrite nextblock_storebytes; auto.\nQed.\n\nTheorem storebytes_valid_block_2:\n  forall b', valid_block m2 b' -> valid_block m1 b'.\nProof.\n  unfold valid_block; intros. rewrite nextblock_storebytes in H; auto.\nQed.\n\nLocal Hint Resolve storebytes_valid_block_1 storebytes_valid_block_2: mem.\n\nTheorem storebytes_range_perm:\n  range_perm m1 b ofs (ofs + Z_of_nat (length bytes)) Cur Writable.\nProof.\n  intros. \n  unfold storebytes in STORE. \n  destruct (range_perm_dec m1 b ofs (ofs + Z_of_nat (length bytes)) Cur Writable);\n  inv STORE.\n  auto.\nQed.\n\nTheorem loadbytes_storebytes_same:\n  loadbytes m2 b ofs (Z_of_nat (length bytes)) = Some bytes.\nProof.\n  intros. unfold storebytes in STORE. unfold loadbytes. \n  destruct (range_perm_dec m1 b ofs (ofs + Z_of_nat (length bytes)) Cur Writable);\n  try discriminate.\n  rewrite pred_dec_true. \n  decEq. inv STORE; simpl. rewrite ZMap.gss. rewrite nat_of_Z_of_nat. \n  apply getN_setN_same. \n  red; eauto with mem. \nQed.\n\nTheorem loadbytes_storebytes_other:\n  forall b' ofs' len,\n  len >= 0 ->\n  b' <> b\n  \\/ ofs' + len <= ofs\n  \\/ ofs + Z_of_nat (length bytes) <= ofs' ->\n  loadbytes m2 b' ofs' len = loadbytes m1 b' ofs' len.\nProof.\n  intros. unfold loadbytes.\n  destruct (range_perm_dec m1 b' ofs' (ofs' + len) Cur Readable).\n  rewrite pred_dec_true. \n  rewrite storebytes_mem_contents. decEq. \n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b' b). subst b'. \n  apply getN_setN_outside. rewrite nat_of_Z_eq; auto. intuition congruence.\n  auto.\n  red; auto with mem.\n  apply pred_dec_false. \n  red; intros; elim n. red; auto with mem.\nQed.\n\nTheorem load_storebytes_other:\n  forall chunk b' ofs',\n  b' <> b\n  \\/ ofs' + size_chunk chunk <= ofs\n  \\/ ofs + Z_of_nat (length bytes) <= ofs' ->\n  load chunk m2 b' ofs' = load chunk m1 b' ofs'.\nProof.\n  intros. unfold load.\n  destruct (valid_access_dec m1 chunk b' ofs' Readable).\n  rewrite pred_dec_true. \n  rewrite storebytes_mem_contents. decEq.\n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b' b). subst b'.\n  rewrite getN_setN_outside. auto. rewrite <- size_chunk_conv. intuition congruence.\n  auto.\n  destruct v; split; auto. red; auto with mem.\n  apply pred_dec_false. \n  red; intros; elim n. destruct H0. split; auto. red; auto with mem.\nQed.\n\nEnd STOREBYTES.\n\nLemma setN_concat:\n  forall bytes1 bytes2 ofs c,\n  setN (bytes1 ++ bytes2) ofs c = setN bytes2 (ofs + Z_of_nat (length bytes1)) (setN bytes1 ofs c).\nProof.\n  induction bytes1; intros.\n  simpl. decEq. omega.\n  simpl length. rewrite inj_S. simpl. rewrite IHbytes1. decEq. omega.\nQed.\n\nTheorem storebytes_concat:\n  forall m b ofs bytes1 m1 bytes2 m2,\n  storebytes m b ofs bytes1 = Some m1 ->\n  storebytes m1 b (ofs + Z_of_nat(length bytes1)) bytes2 = Some m2 ->\n  storebytes m b ofs (bytes1 ++ bytes2) = Some m2.\nProof.\n  intros. generalize H; intro ST1. generalize H0; intro ST2.\n  unfold storebytes; unfold storebytes in ST1; unfold storebytes in ST2.\n  destruct (range_perm_dec m b ofs (ofs + Z_of_nat(length bytes1)) Cur Writable); try congruence.\n  destruct (range_perm_dec m1 b (ofs + Z_of_nat(length bytes1)) (ofs + Z_of_nat(length bytes1) + Z_of_nat(length bytes2)) Cur Writable); try congruence.\n  destruct (range_perm_dec m b ofs (ofs + Z_of_nat (length (bytes1 ++ bytes2))) Cur Writable).\n  inv ST1; inv ST2; simpl. decEq. apply mkmem_ext; auto.\n  rewrite ZMap.gss.  rewrite setN_concat. symmetry. apply ZMap.set2.\n  elim n.   \n  rewrite app_length. rewrite inj_plus. red; intros.\n  destruct (zlt ofs0 (ofs + Z_of_nat(length bytes1))).\n  apply r. omega. \n  eapply perm_storebytes_2; eauto. apply r0. omega.\nQed.\n\nTheorem storebytes_split:\n  forall m b ofs bytes1 bytes2 m2,\n  storebytes m b ofs (bytes1 ++ bytes2) = Some m2 ->\n  exists m1,\n     storebytes m b ofs bytes1 = Some m1\n  /\\ storebytes m1 b (ofs + Z_of_nat(length bytes1)) bytes2 = Some m2.\nProof.\n  intros. \n  destruct (range_perm_storebytes m b ofs bytes1) as [m1 ST1].\n  red; intros. exploit storebytes_range_perm; eauto. rewrite app_length. \n  rewrite inj_plus. omega.\n  destruct (range_perm_storebytes m1 b (ofs + Z_of_nat (length bytes1)) bytes2) as [m2' ST2].\n  red; intros. eapply perm_storebytes_1; eauto. exploit storebytes_range_perm. \n  eexact H. instantiate (1 := ofs0). rewrite app_length. rewrite inj_plus. omega.\n  auto.\n  assert (Some m2 = Some m2').\n  rewrite <- H. eapply storebytes_concat; eauto.\n  inv H0.\n  exists m1; split; auto. \nQed.\n\n(** ** Properties related to [alloc]. *)\n\nSection ALLOC.\n\nVariable m1: mem.\nVariables lo hi: Z.\nVariable m2: mem.\nVariable b: block.\nHypothesis ALLOC: alloc m1 lo hi = (m2, b).\n\nTheorem nextblock_alloc:\n  nextblock m2 = Zsucc (nextblock m1).\nProof.\n  injection ALLOC; intros. rewrite <- H0; auto.\nQed.\n\nTheorem alloc_result:\n  b = nextblock m1.\nProof.\n  injection ALLOC; auto.\nQed.\n\nTheorem valid_block_alloc:\n  forall b', valid_block m1 b' -> valid_block m2 b'.\nProof.\n  unfold valid_block; intros. rewrite nextblock_alloc. omega.\nQed.\n\nTheorem fresh_block_alloc:\n  ~(valid_block m1 b).\nProof.\n  unfold valid_block. rewrite alloc_result. omega.\nQed.\n\nTheorem valid_new_block:\n  valid_block m2 b.\nProof.\n  unfold valid_block. rewrite alloc_result. rewrite nextblock_alloc. omega.\nQed.\n\nLocal Hint Resolve valid_block_alloc fresh_block_alloc valid_new_block: mem.\n\nTheorem valid_block_alloc_inv:\n  forall b', valid_block m2 b' -> b' = b \\/ valid_block m1 b'.\nProof.\n  unfold valid_block; intros. \n  rewrite nextblock_alloc in H. rewrite alloc_result. \n  unfold block; omega.\nQed.\n\nTheorem perm_alloc_1:\n  forall b' ofs k p, perm m1 b' ofs k p -> perm m2 b' ofs k p.\nProof.\n  unfold perm; intros. injection ALLOC; intros. rewrite <- H1; simpl.\n  subst b. rewrite ZMap.gsspec. destruct (ZIndexed.eq b' (nextblock m1)); auto.\n  rewrite nextblock_noaccess in H. contradiction. omega. \nQed.\n\nTheorem perm_alloc_2:\n  forall ofs k, lo <= ofs < hi -> perm m2 b ofs k Freeable.\nProof.\n  unfold perm; intros. injection ALLOC; intros. rewrite <- H1; simpl.\n  subst b. rewrite ZMap.gss. unfold proj_sumbool. rewrite zle_true.\n  rewrite zlt_true. simpl. auto with mem. omega. omega.\nQed.\n\nTheorem perm_alloc_inv:\n  forall b' ofs k p, \n  perm m2 b' ofs k p ->\n  if zeq b' b then lo <= ofs < hi else perm m1 b' ofs k p.\nProof.\n  intros until p; unfold perm. inv ALLOC. simpl. \n  rewrite ZMap.gsspec. unfold ZIndexed.eq. destruct (zeq b' (nextblock m1)); intros.\n  destruct (zle lo ofs); try contradiction. destruct (zlt ofs hi); try contradiction.\n  split; auto. \n  auto.\nQed.\n\nTheorem perm_alloc_3:\n  forall ofs k p, perm m2 b ofs k p -> lo <= ofs < hi.\nProof.\n  intros. exploit perm_alloc_inv; eauto. rewrite zeq_true; auto.\nQed.\n\nTheorem perm_alloc_4:\n  forall b' ofs k p, perm m2 b' ofs k p -> b' <> b -> perm m1 b' ofs k p.\nProof.\n  intros. exploit perm_alloc_inv; eauto. rewrite zeq_false; auto.\nQed.\n\nLocal Hint Resolve perm_alloc_1 perm_alloc_2 perm_alloc_3 perm_alloc_4: mem.\n\nTheorem valid_access_alloc_other:\n  forall chunk b' ofs p,\n  valid_access m1 chunk b' ofs p ->\n  valid_access m2 chunk b' ofs p.\nProof.\n  intros. inv H. constructor; auto with mem.\n  red; auto with mem.\nQed.\n\nTheorem valid_access_alloc_same:\n  forall chunk ofs,\n  lo <= ofs -> ofs + size_chunk chunk <= hi -> (align_chunk chunk | ofs) ->\n  valid_access m2 chunk b ofs Freeable.\nProof.\n  intros. constructor; auto with mem.\n  red; intros. apply perm_alloc_2. omega. \nQed.\n\nLocal Hint Resolve valid_access_alloc_other valid_access_alloc_same: mem.\n\nTheorem valid_access_alloc_inv:\n  forall chunk b' ofs p,\n  valid_access m2 chunk b' ofs p ->\n  if eq_block b' b\n  then lo <= ofs /\\ ofs + size_chunk chunk <= hi /\\ (align_chunk chunk | ofs)\n  else valid_access m1 chunk b' ofs p.\nProof.\n  intros. inv H.\n  generalize (size_chunk_pos chunk); intro.\n  unfold eq_block. destruct (zeq b' b). subst b'.\n  assert (perm m2 b ofs Cur p). apply H0. omega. \n  assert (perm m2 b (ofs + size_chunk chunk - 1) Cur p). apply H0. omega. \n  exploit perm_alloc_inv. eexact H2. rewrite zeq_true. intro.\n  exploit perm_alloc_inv. eexact H3. rewrite zeq_true. intro. \n  intuition omega. \n  split; auto. red; intros. \n  exploit perm_alloc_inv. apply H0. eauto. rewrite zeq_false; auto. \nQed.\n\nTheorem load_alloc_unchanged:\n  forall chunk b' ofs,\n  valid_block m1 b' ->\n  load chunk m2 b' ofs = load chunk m1 b' ofs.\nProof.\n  intros. unfold load.\n  destruct (valid_access_dec m2 chunk b' ofs Readable).\n  exploit valid_access_alloc_inv; eauto. destruct (eq_block b' b); intros.\n  subst b'. elimtype False. eauto with mem.\n  rewrite pred_dec_true; auto.\n  injection ALLOC; intros. rewrite <- H2; simpl.\n  rewrite ZMap.gso. auto. rewrite H1. apply sym_not_equal; eauto with mem.\n  rewrite pred_dec_false. auto.\n  eauto with mem.\nQed.\n\nTheorem load_alloc_other:\n  forall chunk b' ofs v,\n  load chunk m1 b' ofs = Some v ->\n  load chunk m2 b' ofs = Some v.\nProof.\n  intros. rewrite <- H. apply load_alloc_unchanged. eauto with mem.\nQed.\n\nTheorem load_alloc_same:\n  forall chunk ofs v,\n  load chunk m2 b ofs = Some v ->\n  v = Vundef.\nProof.\n  intros. exploit load_result; eauto. intro. rewrite H0. \n  injection ALLOC; intros. rewrite <- H2; simpl. rewrite <- H1.\n  rewrite ZMap.gss. destruct chunk; simpl; repeat rewrite ZMap.gi; reflexivity.\nQed.\n\nTheorem load_alloc_same':\n  forall chunk ofs,\n  lo <= ofs -> ofs + size_chunk chunk <= hi -> (align_chunk chunk | ofs) ->\n  load chunk m2 b ofs = Some Vundef.\nProof.\n  intros. assert (exists v, load chunk m2 b ofs = Some v).\n    apply valid_access_load. constructor; auto.\n    red; intros. eapply perm_implies. apply perm_alloc_2. omega. auto with mem.\n  destruct H2 as [v LOAD]. rewrite LOAD. decEq.\n  eapply load_alloc_same; eauto.\nQed.\n\nEnd ALLOC.\n\nLocal Hint Resolve valid_block_alloc fresh_block_alloc valid_new_block: mem.\nLocal Hint Resolve valid_access_alloc_other valid_access_alloc_same: mem.\n\n(** ** Properties related to [free]. *)\n\nTheorem range_perm_free:\n  forall m1 b lo hi,\n  range_perm m1 b lo hi Cur Freeable ->\n  { m2: mem | free m1 b lo hi = Some m2 }.\nProof.\n  intros; unfold free. rewrite pred_dec_true; auto. econstructor; eauto.\nDefined.\n\nSection FREE.\n\nVariable m1: mem.\nVariable bf: block.\nVariables lo hi: Z.\nVariable m2: mem.\nHypothesis FREE: free m1 bf lo hi = Some m2.\n\nTheorem free_range_perm:\n  range_perm m1 bf lo hi Cur Freeable.\nProof.\n  unfold free in FREE. destruct (range_perm_dec m1 bf lo hi Cur Freeable); auto.\n  congruence.\nQed.\n\nLemma free_result:\n  m2 = unchecked_free m1 bf lo hi.\nProof.\n  unfold free in FREE. destruct (range_perm_dec m1 bf lo hi Cur Freeable).\n  congruence. congruence.\nQed.\n\nTheorem nextblock_free:\n  nextblock m2 = nextblock m1.\nProof.\n  rewrite free_result; reflexivity.\nQed.\n\nTheorem valid_block_free_1:\n  forall b, valid_block m1 b -> valid_block m2 b.\nProof.\n  intros. rewrite free_result. assumption.\nQed.\n\nTheorem valid_block_free_2:\n  forall b, valid_block m2 b -> valid_block m1 b.\nProof.\n  intros. rewrite free_result in H. assumption.\nQed.\n\nLocal Hint Resolve valid_block_free_1 valid_block_free_2: mem.\n\nTheorem perm_free_1:\n  forall b ofs k p,\n  b <> bf \\/ ofs < lo \\/ hi <= ofs ->\n  perm m1 b ofs k p ->\n  perm m2 b ofs k p.\nProof.\n  intros. rewrite free_result. unfold perm, unchecked_free; simpl.\n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b bf). subst b.\n  destruct (zle lo ofs); simpl. \n  destruct (zlt ofs hi); simpl.\n  elimtype False; intuition.\n  auto. auto.\n  auto.\nQed.\n\nTheorem perm_free_2:\n  forall ofs k p, lo <= ofs < hi -> ~ perm m2 bf ofs k p.\nProof.\n  intros. rewrite free_result. unfold perm, unchecked_free; simpl.\n  rewrite ZMap.gss. unfold proj_sumbool. rewrite zle_true. rewrite zlt_true. \n  simpl. tauto. omega. omega.\nQed.\n\nTheorem perm_free_3:\n  forall b ofs k p,\n  perm m2 b ofs k p -> perm m1 b ofs k p.\nProof.\n  intros until p. rewrite free_result. unfold perm, unchecked_free; simpl.\n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b bf). subst b.\n  destruct (zle lo ofs); simpl. \n  destruct (zlt ofs hi); simpl. tauto. \n  auto. auto. auto. \nQed.\n\nTheorem perm_free_inv:\n  forall b ofs k p,\n  perm m1 b ofs k p ->\n  (b = bf /\\ lo <= ofs < hi) \\/ perm m2 b ofs k p.\nProof.\n  intros. rewrite free_result. unfold perm, unchecked_free; simpl.\n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b bf); auto. subst b.\n  destruct (zle lo ofs); simpl; auto.\n  destruct (zlt ofs hi); simpl; auto.\nQed.\n\nTheorem valid_access_free_1:\n  forall chunk b ofs p,\n  valid_access m1 chunk b ofs p -> \n  b <> bf \\/ lo >= hi \\/ ofs + size_chunk chunk <= lo \\/ hi <= ofs ->\n  valid_access m2 chunk b ofs p.\nProof.\n  intros. inv H. constructor; auto with mem.\n  red; intros. eapply perm_free_1; eauto.\n  destruct (zlt lo hi). intuition. right. omega. \nQed.\n\nTheorem valid_access_free_2:\n  forall chunk ofs p,\n  lo < hi -> ofs + size_chunk chunk > lo -> ofs < hi ->\n  ~(valid_access m2 chunk bf ofs p).\nProof.\n  intros; red; intros. inv H2. \n  generalize (size_chunk_pos chunk); intros.\n  destruct (zlt ofs lo).\n  elim (perm_free_2 lo Cur p).\n  omega. apply H3. omega. \n  elim (perm_free_2 ofs Cur p).\n  omega. apply H3. omega. \nQed.\n\nTheorem valid_access_free_inv_1:\n  forall chunk b ofs p,\n  valid_access m2 chunk b ofs p ->\n  valid_access m1 chunk b ofs p.\nProof.\n  intros. destruct H. split; auto. \n  red; intros. generalize (H ofs0 H1). \n  rewrite free_result. unfold perm, unchecked_free; simpl. \n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b bf). subst b.\n  destruct (zle lo ofs0); simpl.\n  destruct (zlt ofs0 hi); simpl.\n  tauto. auto. auto. auto. \nQed.\n\nTheorem valid_access_free_inv_2:\n  forall chunk ofs p,\n  valid_access m2 chunk bf ofs p ->\n  lo >= hi \\/ ofs + size_chunk chunk <= lo \\/ hi <= ofs.\nProof.\n  intros.\n  destruct (zlt lo hi); auto. \n  destruct (zle (ofs + size_chunk chunk) lo); auto.\n  destruct (zle hi ofs); auto.\n  elim (valid_access_free_2 chunk ofs p); auto. omega.\nQed.\n\nTheorem load_free:\n  forall chunk b ofs,\n  b <> bf \\/ lo >= hi \\/ ofs + size_chunk chunk <= lo \\/ hi <= ofs ->\n  load chunk m2 b ofs = load chunk m1 b ofs.\nProof.\n  intros. unfold load.\n  destruct (valid_access_dec m2 chunk b ofs Readable).\n  rewrite pred_dec_true. \n  rewrite free_result; auto.\n  eapply valid_access_free_inv_1; eauto. \n  rewrite pred_dec_false; auto.\n  red; intro; elim n. eapply valid_access_free_1; eauto. \nQed.\n\nEnd FREE.\n\nLocal Hint Resolve valid_block_free_1 valid_block_free_2\n             perm_free_1 perm_free_2 perm_free_3 \n             valid_access_free_1 valid_access_free_inv_1: mem.\n\n(** ** Properties related to [drop_perm] *)\n\nTheorem range_perm_drop_1:\n  forall m b lo hi p m', drop_perm m b lo hi p = Some m' -> range_perm m b lo hi Cur Freeable.\nProof.\n  unfold drop_perm; intros. \n  destruct (range_perm_dec m b lo hi Cur Freeable). auto. discriminate.\nQed.\n\nTheorem range_perm_drop_2:\n  forall m b lo hi p,\n  range_perm m b lo hi Cur Freeable -> {m' | drop_perm m b lo hi p = Some m' }.\nProof.\n  unfold drop_perm; intros. \n  destruct (range_perm_dec m b lo hi Cur Freeable). econstructor. eauto. contradiction.\nDefined.\n\nSection DROP.\n\nVariable m: mem.\nVariable b: block.\nVariable lo hi: Z.\nVariable p: permission.\nVariable m': mem.\nHypothesis DROP: drop_perm m b lo hi p = Some m'.\n\nTheorem nextblock_drop:\n  nextblock m' = nextblock m.\nProof.\n  unfold drop_perm in DROP. destruct (range_perm_dec m b lo hi Cur Freeable); inv DROP; auto.\nQed.\n\nTheorem drop_perm_valid_block_1:\n  forall b', valid_block m b' -> valid_block m' b'.\nProof.\n  unfold valid_block; rewrite nextblock_drop; auto.\nQed.\n\nTheorem drop_perm_valid_block_2:\n  forall b', valid_block m' b' -> valid_block m b'.\nProof.\n  unfold valid_block; rewrite nextblock_drop; auto.\nQed.\n\nTheorem perm_drop_1:\n  forall ofs k, lo <= ofs < hi -> perm m' b ofs k p.\nProof.\n  intros.\n  unfold drop_perm in DROP. destruct (range_perm_dec m b lo hi Cur Freeable); inv DROP.\n  unfold perm. simpl. rewrite ZMap.gss. unfold proj_sumbool. \n  rewrite zle_true. rewrite zlt_true. simpl. constructor.\n  omega. omega. \nQed.\n  \nTheorem perm_drop_2:\n  forall ofs k p', lo <= ofs < hi -> perm m' b ofs k p' -> perm_order p p'.\nProof.\n  intros.\n  unfold drop_perm in DROP. destruct (range_perm_dec m b lo hi Cur Freeable); inv DROP.\n  revert H0. unfold perm; simpl. rewrite ZMap.gss. unfold proj_sumbool. \n  rewrite zle_true. rewrite zlt_true. simpl. auto. \n  omega. omega. \nQed.\n\nTheorem perm_drop_3:\n  forall b' ofs k p', b' <> b \\/ ofs < lo \\/ hi <= ofs -> perm m b' ofs k p' -> perm m' b' ofs k p'.\nProof.\n  intros.\n  unfold drop_perm in DROP. destruct (range_perm_dec m b lo hi Cur Freeable); inv DROP.\n  unfold perm; simpl. rewrite ZMap.gsspec. destruct (ZIndexed.eq b' b). subst b'. \n  unfold proj_sumbool. destruct (zle lo ofs). destruct (zlt ofs hi). \n  byContradiction. intuition omega.\n  auto. auto. auto.\nQed.\n\nTheorem perm_drop_4:\n  forall b' ofs k p', perm m' b' ofs k p' -> perm m b' ofs k p'.\nProof.\n  intros.\n  unfold drop_perm in DROP. destruct (range_perm_dec m b lo hi Cur Freeable); inv DROP.\n  revert H. unfold perm; simpl. rewrite ZMap.gsspec. destruct (ZIndexed.eq b' b).\n  subst b'. unfold proj_sumbool. destruct (zle lo ofs). destruct (zlt ofs hi).\n  simpl. intros. apply perm_implies with p. apply perm_implies with Freeable. apply perm_cur.\n  apply r. tauto. auto with mem. auto.\n  auto. auto. auto.\nQed.\n\nLemma valid_access_drop_1:\n  forall chunk b' ofs p', \n  b' <> b \\/ ofs + size_chunk chunk <= lo \\/ hi <= ofs \\/ perm_order p p' ->\n  valid_access m chunk b' ofs p' -> valid_access m' chunk b' ofs p'.\nProof.\n  intros. destruct H0. split; auto. \n  red; intros.\n  destruct (zeq b' b). subst b'.\n  destruct (zlt ofs0 lo). eapply perm_drop_3; eauto. \n  destruct (zle hi ofs0). eapply perm_drop_3; eauto.\n  apply perm_implies with p. eapply perm_drop_1; eauto. omega. \n  generalize (size_chunk_pos chunk); intros. intuition.\n  eapply perm_drop_3; eauto.\nQed.\n\nLemma valid_access_drop_2:\n  forall chunk b' ofs p', \n  valid_access m' chunk b' ofs p' -> valid_access m chunk b' ofs p'.\nProof.\n  intros. destruct H; split; auto. \n  red; intros. eapply perm_drop_4; eauto. \nQed.\n\n(*\nLemma valid_access_drop_3:\n  forall chunk b' ofs p',\n  valid_access m' chunk b' ofs p' ->\n  b' <> b \\/ Intv.disjoint (lo, hi) (ofs, ofs + size_chunk chunk) \\/ perm_order p p'.\nProof.\n  intros. destruct H. \n  destruct (zeq b' b); auto. subst b'.\n  destruct (Intv.disjoint_dec (lo, hi) (ofs, ofs + size_chunk chunk)); auto. \n  exploit intv_not_disjoint; eauto. intros [x [A B]]. \n  right; right. apply perm_drop_2 with x. auto. apply H. auto. \nQed.\n*)\n\nTheorem load_drop:\n  forall chunk b' ofs, \n  b' <> b \\/ ofs + size_chunk chunk <= lo \\/ hi <= ofs \\/ perm_order p Readable ->\n  load chunk m' b' ofs = load chunk m b' ofs.\nProof.\n  intros.\n  unfold load.\n  destruct (valid_access_dec m chunk b' ofs Readable).\n  rewrite pred_dec_true.\n  unfold drop_perm in DROP. destruct (range_perm_dec m b lo hi Cur Freeable); inv DROP. simpl. auto.\n  eapply valid_access_drop_1; eauto. \n  rewrite pred_dec_false. auto.\n  red; intros; elim n. eapply valid_access_drop_2; eauto.\nQed.\n\nEnd DROP.\n\n(** * Generic injections *)\n\n(** A memory state [m1] generically injects into another memory state [m2] via the\n  memory injection [f] if the following conditions hold:\n- each access in [m2] that corresponds to a valid access in [m1]\n  is itself valid;\n- the memory value associated in [m1] to an accessible address\n  must inject into [m2]'s memory value at the corersponding address.\n*)\n\nRecord mem_inj (f: meminj) (m1 m2: mem) : Prop :=\n  mk_mem_inj {\n    mi_perm:\n      forall b1 b2 delta ofs k p,\n      f b1 = Some(b2, delta) ->\n      perm m1 b1 ofs k p ->\n      perm m2 b2 (ofs + delta) k p;\n    mi_access:\n      forall b1 b2 delta chunk ofs p,\n      f b1 = Some(b2, delta) ->\n      valid_access m1 chunk b1 ofs p ->\n      valid_access m2 chunk b2 (ofs + delta) p;\n    mi_memval:\n      forall b1 ofs b2 delta,\n      f b1 = Some(b2, delta) ->\n      perm m1 b1 ofs Cur Readable ->\n      memval_inject f (m1.(mem_contents)#b1#ofs) (m2.(mem_contents)#b2#(ofs + delta))\n  }.\n\n(** Preservation of permissions *)\n\nLemma perm_inj:\n  forall f m1 m2 b1 ofs k p b2 delta,\n  mem_inj f m1 m2 ->\n  perm m1 b1 ofs k p ->\n  f b1 = Some(b2, delta) ->\n  perm m2 b2 (ofs + delta) k p.\nProof.\n  intros. eapply mi_perm; eauto. \nQed.\n\nLemma range_perm_inj:\n  forall f m1 m2 b1 lo hi k p b2 delta,\n  mem_inj f m1 m2 ->\n  range_perm m1 b1 lo hi k p ->\n  f b1 = Some(b2, delta) ->\n  range_perm m2 b2 (lo + delta) (hi + delta) k p.\nProof.\n  intros; red; intros.\n  replace ofs with ((ofs - delta) + delta) by omega.\n  eapply perm_inj; eauto. apply H0. omega.\nQed.\n\n(** Preservation of loads. *)\n\nLemma getN_inj:\n  forall f m1 m2 b1 b2 delta,\n  mem_inj f m1 m2 ->\n  f b1 = Some(b2, delta) ->\n  forall n ofs,\n  range_perm m1 b1 ofs (ofs + Z_of_nat n) Cur Readable ->\n  list_forall2 (memval_inject f) \n               (getN n ofs (m1.(mem_contents)#b1))\n               (getN n (ofs + delta) (m2.(mem_contents)#b2)).\nProof.\n  induction n; intros; simpl.\n  constructor.\n  rewrite inj_S in H1. \n  constructor. \n  eapply mi_memval; eauto.\n  apply H1. omega.  \n  replace (ofs + delta + 1) with ((ofs + 1) + delta) by omega.\n  apply IHn. red; intros; apply H1; omega. \nQed.\n\nLemma load_inj:\n  forall f m1 m2 chunk b1 ofs b2 delta v1,\n  mem_inj f m1 m2 ->\n  load chunk m1 b1 ofs = Some v1 ->\n  f b1 = Some (b2, delta) ->\n  exists v2, load chunk m2 b2 (ofs + delta) = Some v2 /\\ val_inject f v1 v2.\nProof.\n  intros.\n  exists (decode_val chunk (getN (size_chunk_nat chunk) (ofs + delta) (m2.(mem_contents)#b2))).\n  split. unfold load. apply pred_dec_true.  \n  eapply mi_access; eauto with mem. \n  exploit load_result; eauto. intro. rewrite H2. \n  apply decode_val_inject. apply getN_inj; auto. \n  rewrite <- size_chunk_conv. exploit load_valid_access; eauto. intros [A B]. auto.\nQed.\n\nLemma loadbytes_inj:\n  forall f m1 m2 len b1 ofs b2 delta bytes1,\n  mem_inj f m1 m2 ->\n  loadbytes m1 b1 ofs len = Some bytes1 ->\n  f b1 = Some (b2, delta) ->\n  exists bytes2, loadbytes m2 b2 (ofs + delta) len = Some bytes2\n              /\\ list_forall2 (memval_inject f) bytes1 bytes2.\nProof.\n  intros. unfold loadbytes in *. \n  destruct (range_perm_dec m1 b1 ofs (ofs + len) Cur Readable); inv H0.\n  exists (getN (nat_of_Z len) (ofs + delta) (m2.(mem_contents)#b2)).\n  split. apply pred_dec_true.  \n  replace (ofs + delta + len) with ((ofs + len) + delta) by omega.\n  eapply range_perm_inj; eauto with mem. \n  apply getN_inj; auto. \n  destruct (zle 0 len). rewrite nat_of_Z_eq; auto. omega. \n  rewrite nat_of_Z_neg. simpl. red; intros; omegaContradiction. omega.\nQed.\n\n(** Preservation of stores. *)\n\nLemma setN_inj:\n  forall (access: Z -> Prop) delta f vl1 vl2,\n  list_forall2 (memval_inject f) vl1 vl2 ->\n  forall p c1 c2,\n  (forall q, access q -> memval_inject f (c1#q) (c2#(q + delta))) ->\n  (forall q, access q -> memval_inject f ((setN vl1 p c1)#q) \n                                         ((setN vl2 (p + delta) c2)#(q + delta))).\nProof.\n  induction 1; intros; simpl. \n  auto.\n  replace (p + delta + 1) with ((p + 1) + delta) by omega.\n  apply IHlist_forall2; auto. \n  intros. rewrite ZMap.gsspec at 1. destruct (ZIndexed.eq q0 p). subst q0.\n  rewrite ZMap.gss. auto. \n  rewrite ZMap.gso. auto. unfold ZIndexed.t in *. omega.\nQed.\n\nDefinition meminj_no_overlap (f: meminj) (m: mem) : Prop :=\n  forall b1 b1' delta1 b2 b2' delta2 ofs1 ofs2,\n  b1 <> b2 ->\n  f b1 = Some (b1', delta1) ->\n  f b2 = Some (b2', delta2) ->\n  perm m b1 ofs1 Max Nonempty ->\n  perm m b2 ofs2 Max Nonempty ->\n  b1' <> b2' \\/ ofs1 + delta1 <> ofs2 + delta2.\n\nLemma store_mapped_inj:\n  forall f chunk m1 b1 ofs v1 n1 m2 b2 delta v2,\n  mem_inj f m1 m2 ->\n  store chunk m1 b1 ofs v1 = Some n1 ->\n  meminj_no_overlap f m1 ->\n  f b1 = Some (b2, delta) ->\n  val_inject f v1 v2 ->\n  exists n2,\n    store chunk m2 b2 (ofs + delta) v2 = Some n2\n    /\\ mem_inj f n1 n2.\nProof.\n  intros.\n  assert (valid_access m2 chunk b2 (ofs + delta) Writable).\n    eapply mi_access; eauto with mem.\n  destruct (valid_access_store _ _ _ _ v2 H4) as [n2 STORE]. \n  exists n2; split. auto.\n  constructor.\n(* perm *)\n  intros. eapply perm_store_1; [eexact STORE|].\n  eapply mi_perm; eauto.\n  eapply perm_store_2; eauto. \n(* access *)\n  intros. eapply store_valid_access_1; [apply STORE |].\n  eapply mi_access; eauto.\n  eapply store_valid_access_2; eauto.\n(* mem_contents *)\n  intros.\n  rewrite (store_mem_contents _ _ _ _ _ _ H0).\n  rewrite (store_mem_contents _ _ _ _ _ _ STORE).\n  repeat rewrite ZMap.gsspec. \n  destruct (ZIndexed.eq b0 b1). subst b0.\n  (* block = b1, block = b2 *)\n  assert (b3 = b2) by congruence. subst b3.\n  assert (delta0 = delta) by congruence. subst delta0.\n  rewrite zeq_true.\n  apply setN_inj with (access := fun ofs => perm m1 b1 ofs Cur Readable).\n  apply encode_val_inject; auto. intros. eapply mi_memval; eauto. eauto with mem. \n  destruct (ZIndexed.eq b3 b2). subst b3.\n  (* block <> b1, block = b2 *)\n  rewrite setN_other. eapply mi_memval; eauto. eauto with mem. \n  rewrite encode_val_length. rewrite <- size_chunk_conv. intros. \n  assert (b2 <> b2 \\/ ofs0 + delta0 <> (r - delta) + delta).\n    eapply H1; eauto. eauto 6 with mem.\n    exploit store_valid_access_3. eexact H0. intros [A B].\n    eapply perm_implies. apply perm_cur_max. apply A. omega. auto with mem.\n  destruct H8. congruence. omega.\n  (* block <> b1, block <> b2 *)\n  eapply mi_memval; eauto. eauto with mem. \nQed.\n\nLemma store_unmapped_inj:\n  forall f chunk m1 b1 ofs v1 n1 m2,\n  mem_inj f m1 m2 ->\n  store chunk m1 b1 ofs v1 = Some n1 ->\n  f b1 = None ->\n  mem_inj f n1 m2.\nProof.\n  intros. constructor.\n(* perm *)\n  intros. eapply mi_perm; eauto with mem.\n(* access *)\n  intros. eapply mi_access; eauto with mem.\n(* mem_contents *)\n  intros. \n  rewrite (store_mem_contents _ _ _ _ _ _ H0).\n  rewrite ZMap.gso. eapply mi_memval; eauto with mem. \n  congruence.\nQed.\n\nLemma store_outside_inj:\n  forall f m1 m2 chunk b ofs v m2',\n  mem_inj f m1 m2 ->\n  (forall b' delta ofs',\n    f b' = Some(b, delta) ->\n    perm m1 b' ofs' Cur Readable -> \n    ofs <= ofs' + delta < ofs + size_chunk chunk -> False) ->\n  store chunk m2 b ofs v = Some m2' ->\n  mem_inj f m1 m2'.\nProof.\n  intros. inv H. constructor.\n(* perm *)\n  eauto with mem.\n(* access *)\n  eauto with mem.\n(* mem_contents *)\n  intros. \n  rewrite (store_mem_contents _ _ _ _ _ _ H1).\n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b2 b). subst b2. \n  rewrite setN_outside. auto. \n  rewrite encode_val_length. rewrite <- size_chunk_conv. \n  destruct (zlt (ofs0 + delta) ofs); auto.\n  destruct (zle (ofs + size_chunk chunk) (ofs0 + delta)). omega. \n  byContradiction. eapply H0; eauto. omega. \n  eauto with mem.\nQed.\n\nLemma storebytes_mapped_inj:\n  forall f m1 b1 ofs bytes1 n1 m2 b2 delta bytes2,\n  mem_inj f m1 m2 ->\n  storebytes m1 b1 ofs bytes1 = Some n1 ->\n  meminj_no_overlap f m1 ->\n  f b1 = Some (b2, delta) ->\n  list_forall2 (memval_inject f) bytes1 bytes2 ->\n  exists n2,\n    storebytes m2 b2 (ofs + delta) bytes2 = Some n2\n    /\\ mem_inj f n1 n2.\nProof.\n  intros. inversion H. \n  assert (range_perm m2 b2 (ofs + delta) (ofs + delta + Z_of_nat (length bytes2)) Cur Writable).\n    replace (ofs + delta + Z_of_nat (length bytes2))\n       with ((ofs + Z_of_nat (length bytes1)) + delta).\n    eapply range_perm_inj; eauto with mem. \n    eapply storebytes_range_perm; eauto.\n    rewrite (list_forall2_length H3). omega.\n  destruct (range_perm_storebytes _ _ _ _ H4) as [n2 STORE]. \n  exists n2; split. eauto.\n  constructor.\n(* perm *)\n  intros.\n  eapply perm_storebytes_1; [apply STORE |].\n  eapply mi_perm0; eauto.\n  eapply perm_storebytes_2; eauto.\n(* access *)\n  intros.\n  eapply storebytes_valid_access_1; [apply STORE |].\n  eapply mi_access0; eauto.\n  eapply storebytes_valid_access_2; eauto.\n(* mem_contents *)\n  intros.\n  assert (perm m1 b0 ofs0 Cur Readable). eapply perm_storebytes_2; eauto. \n  rewrite (storebytes_mem_contents _ _ _ _ _ H0).\n  rewrite (storebytes_mem_contents _ _ _ _ _ STORE).\n  repeat rewrite ZMap.gsspec. destruct (ZIndexed.eq b0 b1). subst b0.\n  (* block = b1, block = b2 *)\n  assert (b3 = b2) by congruence. subst b3.\n  assert (delta0 = delta) by congruence. subst delta0.\n  rewrite zeq_true.\n  apply setN_inj with (access := fun ofs => perm m1 b1 ofs Cur Readable); auto.\n  destruct (ZIndexed.eq b3 b2). subst b3.\n  (* block <> b1, block = b2 *)\n  rewrite setN_other. auto.\n  intros.\n  assert (b2 <> b2 \\/ ofs0 + delta0 <> (r - delta) + delta).\n    eapply H1; eauto 6 with mem.\n    exploit storebytes_range_perm. eexact H0. \n    instantiate (1 := r - delta). \n    rewrite (list_forall2_length H3). omega.\n    eauto 6 with mem.\n  destruct H9. congruence. omega.\n  (* block <> b1, block <> b2 *)\n  eauto.\nQed.\n\nLemma storebytes_unmapped_inj:\n  forall f m1 b1 ofs bytes1 n1 m2,\n  mem_inj f m1 m2 ->\n  storebytes m1 b1 ofs bytes1 = Some n1 ->\n  f b1 = None ->\n  mem_inj f n1 m2.\nProof.\n  intros. inversion H.\n  constructor.\n(* perm *)\n  intros. eapply mi_perm0; eauto. eapply perm_storebytes_2; eauto. \n(* access *)\n  intros. eapply mi_access0; eauto. eapply storebytes_valid_access_2; eauto. \n(* mem_contents *)\n  intros. \n  rewrite (storebytes_mem_contents _ _ _ _ _ H0).\n  rewrite ZMap.gso. eapply mi_memval0; eauto. eapply perm_storebytes_2; eauto.\n  congruence.\nQed.\n\nLemma storebytes_outside_inj:\n  forall f m1 m2 b ofs bytes2 m2',\n  mem_inj f m1 m2 ->\n  (forall b' delta ofs',\n    f b' = Some(b, delta) ->\n    perm m1 b' ofs' Cur Readable -> \n    ofs <= ofs' + delta < ofs + Z_of_nat (length bytes2) -> False) ->\n  storebytes m2 b ofs bytes2 = Some m2' ->\n  mem_inj f m1 m2'.\nProof.\n  intros. inversion H. constructor.\n(* perm *)\n  intros. eapply perm_storebytes_1; eauto with mem.\n(* access *)\n  intros. eapply storebytes_valid_access_1; eauto with mem.\n(* mem_contents *)\n  intros. \n  rewrite (storebytes_mem_contents _ _ _ _ _ H1).\n  rewrite ZMap.gsspec. destruct (ZIndexed.eq b2 b). subst b2.\n  rewrite setN_outside. auto. \n  destruct (zlt (ofs0 + delta) ofs); auto.\n  destruct (zle (ofs + Z_of_nat (length bytes2)) (ofs0 + delta)). omega. \n  byContradiction. eapply H0; eauto. omega. \n  eauto with mem.\nQed.\n\n(** Preservation of allocations *)\n\nLemma alloc_right_inj:\n  forall f m1 m2 lo hi b2 m2',\n  mem_inj f m1 m2 ->\n  alloc m2 lo hi = (m2', b2) ->\n  mem_inj f m1 m2'.\nProof.\n  intros. injection H0. intros NEXT MEM.\n  inversion H. constructor.\n(* perm *)\n  intros. eapply perm_alloc_1; eauto. \n(* access *)\n  intros. eapply valid_access_alloc_other; eauto. \n(* mem_contents *)\n  intros.\n  assert (perm m2 b0 (ofs + delta) Cur Readable). \n    eapply mi_perm0; eauto.\n  assert (valid_block m2 b0) by eauto with mem.\n  rewrite <- MEM; simpl. rewrite ZMap.gso. eauto with mem.\n  rewrite NEXT. eauto with mem. \nQed.\n\nLemma alloc_left_unmapped_inj:\n  forall f m1 m2 lo hi m1' b1,\n  mem_inj f m1 m2 ->\n  alloc m1 lo hi = (m1', b1) ->\n  f b1 = None ->\n  mem_inj f m1' m2.\nProof.\n  intros. inversion H. constructor.\n(* perm *)\n  intros. exploit perm_alloc_inv; eauto. intros. \n  destruct (zeq b0 b1). congruence. eauto. \n(* access *)\n  intros. exploit valid_access_alloc_inv; eauto. unfold eq_block. intros. \n  destruct (zeq b0 b1). congruence. eauto.\n(* mem_contents *)\n  injection H0; intros NEXT MEM. intros. \n  rewrite <- MEM; simpl. rewrite NEXT.\n  exploit perm_alloc_inv; eauto. intros.\n  rewrite ZMap.gsspec. unfold ZIndexed.eq. destruct (zeq b0 b1). \n  rewrite ZMap.gi. constructor. eauto. \nQed.\n\nDefinition inj_offset_aligned (delta: Z) (size: Z) : Prop :=\n  forall chunk, size_chunk chunk <= size -> (align_chunk chunk | delta).\n\nLemma alloc_left_mapped_inj:\n  forall f m1 m2 lo hi m1' b1 b2 delta,\n  mem_inj f m1 m2 ->\n  alloc m1 lo hi = (m1', b1) ->\n  valid_block m2 b2 ->\n  inj_offset_aligned delta (hi-lo) ->\n  (forall ofs k p, lo <= ofs < hi -> perm m2 b2 (ofs + delta) k p) ->\n  f b1 = Some(b2, delta) ->\n  mem_inj f m1' m2.\nProof.\n  intros. inversion H. constructor.\n(* perm *)\n  intros. \n  exploit perm_alloc_inv; eauto. intros. destruct (zeq b0 b1). subst b0.\n  rewrite H4 in H5; inv H5. eauto. eauto. \n(* access *)\n  intros. \n  exploit valid_access_alloc_inv; eauto. unfold eq_block. intros.\n  destruct (zeq b0 b1). subst b0. rewrite H4 in H5. inv H5. \n  split. red; intros. \n  replace ofs0 with ((ofs0 - delta0) + delta0) by omega. \n  apply H3. omega. \n  destruct H6. apply Zdivide_plus_r. auto. apply H2. omega.\n  eauto.\n(* mem_contents *)\n  injection H0; intros NEXT MEM. \n  intros. rewrite <- MEM; simpl. rewrite NEXT.\n  exploit perm_alloc_inv; eauto. intros.\n  rewrite ZMap.gsspec. unfold ZIndexed.eq. \n  destruct (zeq b0 b1). rewrite ZMap.gi. constructor. eauto.\nQed.\n\nLemma free_left_inj:\n  forall f m1 m2 b lo hi m1',\n  mem_inj f m1 m2 ->\n  free m1 b lo hi = Some m1' ->\n  mem_inj f m1' m2.\nProof.\n  intros. exploit free_result; eauto. intro FREE. inversion H. constructor.\n(* perm *)\n  intros. eauto with mem.\n(* access *)\n  intros. eauto with mem. \n(* mem_contents *)\n  intros. rewrite FREE; simpl. eauto with mem.\nQed.\n\nLemma free_right_inj:\n  forall f m1 m2 b lo hi m2',\n  mem_inj f m1 m2 ->\n  free m2 b lo hi = Some m2' ->\n  (forall b' delta ofs k p,\n    f b' = Some(b, delta) ->\n    perm m1 b' ofs k p -> lo <= ofs + delta < hi -> False) ->\n  mem_inj f m1 m2'.\nProof.\n  intros. exploit free_result; eauto. intro FREE. inversion H.\n  assert (PERM:\n    forall b1 b2 delta ofs k p,\n    f b1 = Some (b2, delta) ->\n    perm m1 b1 ofs k p -> perm m2' b2 (ofs + delta) k p).\n  intros. \n  intros. eapply perm_free_1; eauto. \n  destruct (zeq b2 b); auto. subst b. right. \n  assert (~ (lo <= ofs + delta < hi)). red; intros; eapply H1; eauto. \n  omega.\n  constructor.\n(* perm *)\n  auto.\n(* access *)\n  intros. exploit mi_access0; eauto. intros [RG AL]. split; auto.\n  red; intros. replace ofs0 with ((ofs0 - delta) + delta) by omega. \n  eapply PERM. eauto. apply H3. omega. \n(* mem_contents *)\n  intros. rewrite FREE; simpl. eauto. \nQed.\n\n(** Preservation of [drop_perm] operations. *)\n\nLemma drop_unmapped_inj:\n  forall f m1 m2 b lo hi p m1',\n  mem_inj f m1 m2 ->\n  drop_perm m1 b lo hi p = Some m1' ->\n  f b = None ->\n  mem_inj f m1' m2.\nProof.\n  intros. inv H. constructor. \n(* perm *)\n  intros. eapply mi_perm0; eauto. eapply perm_drop_4; eauto. \n(* access *)\n  intros. eapply mi_access0. eauto.\n  eapply valid_access_drop_2; eauto.\n(* contents *)\n  intros.\n  replace (m1'.(mem_contents)#b1#ofs) with (m1.(mem_contents)#b1#ofs).\n  apply mi_memval0; auto. eapply perm_drop_4; eauto. \n  unfold drop_perm in H0; destruct (range_perm_dec m1 b lo hi Cur Freeable); inv H0; auto.\nQed.\n\nLemma drop_mapped_inj:\n  forall f m1 m2 b1 b2 delta lo hi p m1',\n  mem_inj f m1 m2 ->\n  drop_perm m1 b1 lo hi p = Some m1' ->\n  meminj_no_overlap f m1 ->\n  f b1 = Some(b2, delta) ->\n  exists m2',\n      drop_perm m2 b2 (lo + delta) (hi + delta) p = Some m2'\n   /\\ mem_inj f m1' m2'.\nProof.\n  intros. \n  assert ({ m2' | drop_perm m2 b2 (lo + delta) (hi + delta) p = Some m2' }).\n  apply range_perm_drop_2. red; intros. \n  replace ofs with ((ofs - delta) + delta) by omega.\n  eapply perm_inj; eauto. eapply range_perm_drop_1; eauto. omega. \n  destruct X as [m2' DROP]. exists m2'; split; auto.\n  inv H.\n  assert (PERM: forall b0 b3 delta0 ofs k p0,\n                f b0 = Some (b3, delta0) ->\n                perm m1' b0 ofs k p0 -> perm m2' b3 (ofs + delta0) k p0).\n    intros.\n    assert (perm m2 b3 (ofs + delta0) k p0).\n      eapply mi_perm0; eauto. eapply perm_drop_4; eauto. \n    destruct (zeq b1 b0).\n    (* b1 = b0 *)\n    subst b0. rewrite H2 in H; inv H.\n    destruct (zlt (ofs + delta0) (lo + delta0)). eapply perm_drop_3; eauto.\n    destruct (zle (hi + delta0) (ofs + delta0)). eapply perm_drop_3; eauto.\n    assert (perm_order p p0).\n      eapply perm_drop_2.  eexact H0. instantiate (1 := ofs). omega. eauto. \n    apply perm_implies with p; auto. \n    eapply perm_drop_1. eauto. omega.\n    (* b1 <> b0 *)\n    eapply perm_drop_3; eauto.\n    destruct (zeq b3 b2); auto.\n    destruct (zlt (ofs + delta0) (lo + delta)); auto.\n    destruct (zle (hi + delta) (ofs + delta0)); auto.\n    exploit H1; eauto.\n    instantiate (1 := ofs + delta0 - delta). \n    apply perm_cur_max. apply perm_implies with Freeable.\n    eapply range_perm_drop_1; eauto. omega. auto with mem. \n    eapply perm_drop_4; eauto. eapply perm_max. apply perm_implies with p0. eauto.  \n    eauto with mem.\n    unfold block. omega.\n  constructor.\n(* perm *)\n  auto.\n(* access *)\n  intros. exploit mi_access0; eauto. eapply valid_access_drop_2; eauto.\n  intros [A B]. split; auto. red; intros.\n  replace ofs0 with ((ofs0 - delta0) + delta0) by omega.\n  eapply PERM; eauto. apply H3. omega. \n(* memval *)\n  intros.\n  replace (m1'.(mem_contents)#b0) with (m1.(mem_contents)#b0).\n  replace (m2'.(mem_contents)#b3) with (m2.(mem_contents)#b3).\n  apply mi_memval0; auto. eapply perm_drop_4; eauto. \n  unfold drop_perm in DROP; destruct (range_perm_dec m2 b2 (lo + delta) (hi + delta) Cur Freeable); inv DROP; auto.\n  unfold drop_perm in H0; destruct (range_perm_dec m1 b1 lo hi Cur Freeable); inv H0; auto.\nQed.\n\nLemma drop_outside_inj: forall f m1 m2 b lo hi p m2',\n  mem_inj f m1 m2 -> \n  drop_perm m2 b lo hi p = Some m2' -> \n  (forall b' delta ofs' k p,\n    f b' = Some(b, delta) ->\n    perm m1 b' ofs' k p -> \n    lo <= ofs' + delta < hi -> False) ->\n  mem_inj f m1 m2'.\nProof.\n  intros. inv H. \n  assert (PERM: forall b0 b3 delta0 ofs k p0,\n                f b0 = Some (b3, delta0) ->\n                perm m1 b0 ofs k p0 -> perm m2' b3 (ofs + delta0) k p0).\n    intros. eapply perm_drop_3; eauto. \n    destruct (zeq b3 b); auto. subst b3. right. \n    destruct (zlt (ofs + delta0) lo); auto.\n    destruct (zle hi (ofs + delta0)); auto.\n    byContradiction. exploit H1; eauto. omega.\n  constructor.\n  (* perm *)\n  auto.\n  (* access *)\n  intros. exploit mi_access0; eauto. intros [A B]. split; auto.\n  red; intros.\n  replace ofs0 with ((ofs0 - delta) + delta) by omega.\n  eapply PERM; eauto. apply H2. omega.\n  (* contents *)\n  intros. \n  replace (m2'.(mem_contents)#b2) with (m2.(mem_contents)#b2).\n  apply mi_memval0; auto.\n  unfold drop_perm in H0; destruct (range_perm_dec m2 b lo hi Cur Freeable); inv H0; auto.\nQed.\n\n(** * Memory extensions *)\n\n(**  A store [m2] extends a store [m1] if [m2] can be obtained from [m1]\n  by increasing the sizes of the memory blocks of [m1] (decreasing\n  the low bounds, increasing the high bounds), and replacing some of\n  the [Vundef] values stored in [m1] by more defined values stored\n  in [m2] at the same locations. *)\n\nRecord extends' (m1 m2: mem) : Prop :=\n  mk_extends {\n    mext_next: nextblock m1 = nextblock m2;\n    mext_inj:  mem_inj inject_id m1 m2\n  }.\n\nDefinition extends := extends'.\n\nTheorem extends_refl:\n  forall m, extends m m.\nProof.\n  intros. constructor. auto. constructor.\n  intros. unfold inject_id in H; inv H. replace (ofs + 0) with ofs by omega. auto.\n  intros. unfold inject_id in H; inv H. replace (ofs + 0) with ofs by omega. auto.\n  intros. unfold inject_id in H; inv H. replace (ofs + 0) with ofs by omega. \n  apply memval_lessdef_refl.\nQed.\n\nTheorem load_extends:\n  forall chunk m1 m2 b ofs v1,\n  extends m1 m2 ->\n  load chunk m1 b ofs = Some v1 ->\n  exists v2, load chunk m2 b ofs = Some v2 /\\ Val.lessdef v1 v2.\nProof.\n  intros. inv H. exploit load_inj; eauto. unfold inject_id; reflexivity. \n  intros [v2 [A B]]. exists v2; split.\n  replace (ofs + 0) with ofs in A by omega. auto.\n  rewrite val_inject_id in B. auto.\nQed.\n\nTheorem loadv_extends:\n  forall chunk m1 m2 addr1 addr2 v1,\n  extends m1 m2 ->\n  loadv chunk m1 addr1 = Some v1 ->\n  Val.lessdef addr1 addr2 ->\n  exists v2, loadv chunk m2 addr2 = Some v2 /\\ Val.lessdef v1 v2.\nProof.\n  unfold loadv; intros. inv H1. \n  destruct addr2; try congruence. eapply load_extends; eauto. \n  congruence.\nQed.\n\nTheorem loadbytes_extends:\n  forall m1 m2 b ofs len bytes1,\n  extends m1 m2 ->\n  loadbytes m1 b ofs len = Some bytes1 ->\n  exists bytes2, loadbytes m2 b ofs len = Some bytes2\n              /\\ list_forall2 memval_lessdef bytes1 bytes2.\nProof.\n  intros. inv H.\n  replace ofs with (ofs + 0) by omega. eapply loadbytes_inj; eauto. \nQed.\n\nTheorem store_within_extends:\n  forall chunk m1 m2 b ofs v1 m1' v2,\n  extends m1 m2 ->\n  store chunk m1 b ofs v1 = Some m1' ->\n  Val.lessdef v1 v2 ->\n  exists m2',\n     store chunk m2 b ofs v2 = Some m2'\n  /\\ extends m1' m2'.\nProof.\n  intros. inversion H.\n  exploit store_mapped_inj; eauto. \n    unfold inject_id; red; intros. inv H3; inv H4. auto.\n    unfold inject_id; reflexivity.\n    rewrite val_inject_id. eauto.\n  intros [m2' [A B]].\n  exists m2'; split.\n  replace (ofs + 0) with ofs in A by omega. auto.\n  split; auto.\n  rewrite (nextblock_store _ _ _ _ _ _ H0).\n  rewrite (nextblock_store _ _ _ _ _ _ A).\n  auto.\nQed.\n\nTheorem store_outside_extends:\n  forall chunk m1 m2 b ofs v m2',\n  extends m1 m2 ->\n  store chunk m2 b ofs v = Some m2' ->\n  (forall ofs', perm m1 b ofs' Cur Readable -> ofs <= ofs' < ofs + size_chunk chunk -> False) ->\n  extends m1 m2'.\nProof.\n  intros. inversion H. constructor.\n  rewrite (nextblock_store _ _ _ _ _ _ H0). auto.\n  eapply store_outside_inj; eauto.\n  unfold inject_id; intros. inv H2. eapply H1; eauto. omega. \nQed.\n\nTheorem storev_extends:\n  forall chunk m1 m2 addr1 v1 m1' addr2 v2,\n  extends m1 m2 ->\n  storev chunk m1 addr1 v1 = Some m1' ->\n  Val.lessdef addr1 addr2 ->\n  Val.lessdef v1 v2 ->\n  exists m2',\n     storev chunk m2 addr2 v2 = Some m2'\n  /\\ extends m1' m2'.\nProof.\n  unfold storev; intros. inv H1. \n  destruct addr2; try congruence. eapply store_within_extends; eauto. \n  congruence.\nQed.\n\nTheorem storebytes_within_extends:\n  forall m1 m2 b ofs bytes1 m1' bytes2,\n  extends m1 m2 ->\n  storebytes m1 b ofs bytes1 = Some m1' ->\n  list_forall2 memval_lessdef bytes1 bytes2 ->\n  exists m2',\n     storebytes m2 b ofs bytes2 = Some m2'\n  /\\ extends m1' m2'.\nProof.\n  intros. inversion H.\n  exploit storebytes_mapped_inj; eauto. \n    unfold inject_id; red; intros. inv H3; inv H4. auto.\n    unfold inject_id; reflexivity.\n  intros [m2' [A B]].\n  exists m2'; split.\n  replace (ofs + 0) with ofs in A by omega. auto.\n  split; auto.\n  rewrite (nextblock_storebytes _ _ _ _ _ H0).\n  rewrite (nextblock_storebytes _ _ _ _ _ A).\n  auto.\nQed.\n\nTheorem storebytes_outside_extends:\n  forall m1 m2 b ofs bytes2 m2',\n  extends m1 m2 ->\n  storebytes m2 b ofs bytes2 = Some m2' ->\n  (forall ofs', perm m1 b ofs' Cur Readable -> ofs <= ofs' < ofs + Z_of_nat (length bytes2) -> False) ->\n  extends m1 m2'.\nProof.\n  intros. inversion H. constructor.\n  rewrite (nextblock_storebytes _ _ _ _ _ H0). auto.\n  eapply storebytes_outside_inj; eauto.\n  unfold inject_id; intros. inv H2. eapply H1; eauto. omega. \nQed.\n\nTheorem alloc_extends:\n  forall m1 m2 lo1 hi1 b m1' lo2 hi2,\n  extends m1 m2 ->\n  alloc m1 lo1 hi1 = (m1', b) ->\n  lo2 <= lo1 -> hi1 <= hi2 ->\n  exists m2',\n     alloc m2 lo2 hi2 = (m2', b)\n  /\\ extends m1' m2'.\nProof.\n  intros. inv H. \n  case_eq (alloc m2 lo2 hi2); intros m2' b' ALLOC. \n  assert (b' = b).\n    rewrite (alloc_result _ _ _ _ _ H0). \n    rewrite (alloc_result _ _ _ _ _ ALLOC).\n    auto.\n  subst b'.\n  exists m2'; split; auto.\n  constructor. \n  rewrite (nextblock_alloc _ _ _ _ _ H0).\n  rewrite (nextblock_alloc _ _ _ _ _ ALLOC). \n  congruence.\n  eapply alloc_left_mapped_inj with (m1 := m1) (m2 := m2') (b2 := b) (delta := 0); eauto.\n  eapply alloc_right_inj; eauto.\n  eauto with mem.\n  red. intros. apply Zdivide_0.\n  intros.\n  eapply perm_implies with Freeable; auto with mem.\n  eapply perm_alloc_2; eauto.\n  omega.\nQed.\n\nTheorem free_left_extends:\n  forall m1 m2 b lo hi m1',\n  extends m1 m2 ->\n  free m1 b lo hi = Some m1' ->\n  extends m1' m2.\nProof.\n  intros. inv H. constructor.\n  rewrite (nextblock_free _ _ _ _ _ H0). auto.\n  eapply free_left_inj; eauto.\nQed.\n\nTheorem free_right_extends:\n  forall m1 m2 b lo hi m2',\n  extends m1 m2 ->\n  free m2 b lo hi = Some m2' ->\n  (forall ofs k p, perm m1 b ofs k p -> lo <= ofs < hi -> False) ->\n  extends m1 m2'.\nProof.\n  intros. inv H. constructor.\n  rewrite (nextblock_free _ _ _ _ _ H0). auto.\n  eapply free_right_inj; eauto.\n  unfold inject_id; intros. inv H. eapply H1; eauto. omega.\nQed. \n\nTheorem free_parallel_extends:\n  forall m1 m2 b lo hi m1',\n  extends m1 m2 ->\n  free m1 b lo hi = Some m1' ->\n  exists m2',\n     free m2 b lo hi = Some m2'\n  /\\ extends m1' m2'.\nProof.\n  intros. inversion H. \n  assert ({ m2': mem | free m2 b lo hi = Some m2' }).\n    apply range_perm_free. red; intros. \n    replace ofs with (ofs + 0) by omega.\n    eapply perm_inj with (b1 := b); eauto.\n    eapply free_range_perm; eauto.\n  destruct X as [m2' FREE]. exists m2'; split; auto.\n  inv H. constructor.\n  rewrite (nextblock_free _ _ _ _ _ H0).\n  rewrite (nextblock_free _ _ _ _ _ FREE). auto.\n  eapply free_right_inj with (m1 := m1'); eauto. \n  eapply free_left_inj; eauto. \n  unfold inject_id; intros. inv H.\n  eapply perm_free_2. eexact H0. instantiate (1 := ofs); omega. eauto. \nQed.\n\nTheorem valid_block_extends:\n  forall m1 m2 b,\n  extends m1 m2 ->\n  (valid_block m1 b <-> valid_block m2 b).\nProof.\n  intros. inv H. unfold valid_block. rewrite mext_next0. omega. \nQed.\n\nTheorem perm_extends:\n  forall m1 m2 b ofs k p,\n  extends m1 m2 -> perm m1 b ofs k p -> perm m2 b ofs k p.\nProof.\n  intros. inv H. replace ofs with (ofs + 0) by omega. \n  eapply perm_inj; eauto. \nQed.\n\nTheorem valid_access_extends:\n  forall m1 m2 chunk b ofs p,\n  extends m1 m2 -> valid_access m1 chunk b ofs p -> valid_access m2 chunk b ofs p.\nProof.\n  intros. inv H. replace ofs with (ofs + 0) by omega. \n  eapply mi_access; eauto. auto. \nQed.\n\nTheorem valid_pointer_extends:\n  forall m1 m2 b ofs,\n  extends m1 m2 -> valid_pointer m1 b ofs = true -> valid_pointer m2 b ofs = true.\nProof.\n  intros. \n  rewrite valid_pointer_valid_access in *. \n  eapply valid_access_extends; eauto.\nQed.\n\nTheorem weak_valid_pointer_extends:\n  forall m1 m2 b ofs,\n  extends m1 m2 ->\n  weak_valid_pointer m1 b ofs = true -> weak_valid_pointer m2 b ofs = true.\nProof.\n  intros until 1. unfold weak_valid_pointer. rewrite !orb_true_iff.\n  intros []; eauto using valid_pointer_extends.\nQed.\n\n(** * Memory injections *)\n\n(** A memory state [m1] injects into another memory state [m2] via the\n  memory injection [f] if the following conditions hold:\n- each access in [m2] that corresponds to a valid access in [m1]\n  is itself valid;\n- the memory value associated in [m1] to an accessible address\n  must inject into [m2]'s memory value at the corersponding address;\n- unallocated blocks in [m1] must be mapped to [None] by [f];\n- if [f b = Some(b', delta)], [b'] must be valid in [m2];\n- distinct blocks in [m1] are mapped to non-overlapping sub-blocks in [m2];\n- the sizes of [m2]'s blocks are representable with unsigned machine integers;\n- pointers that could be represented using unsigned machine integers remain\n  representable after the injection.\n*)\n\nRecord inject' (f: meminj) (m1 m2: mem) : Prop :=\n  mk_inject {\n    mi_inj:\n      mem_inj f m1 m2;\n    mi_freeblocks:\n      forall b, ~(valid_block m1 b) -> f b = None;\n    mi_mappedblocks:\n      forall b b' delta, f b = Some(b', delta) -> valid_block m2 b';\n    mi_no_overlap:\n      meminj_no_overlap f m1;\n    mi_representable:\n      forall b b' delta ofs,\n      f b = Some(b', delta) ->\n      weak_valid_pointer m1 b (Int.unsigned ofs) = true ->\n      delta >= 0 /\\ 0 <= Int.unsigned ofs + delta <= Int.max_unsigned\n  }.\nDefinition inject := inject'.\n\nLocal Hint Resolve mi_mappedblocks: mem.\n\n(** Preservation of access validity and pointer validity *)\n\nTheorem valid_block_inject_1:\n  forall f m1 m2 b1 b2 delta,\n  f b1 = Some(b2, delta) ->\n  inject f m1 m2 ->\n  valid_block m1 b1.\nProof.\n  intros. inv H. destruct (zlt b1 (nextblock m1)). auto. \n  assert (f b1 = None). eapply mi_freeblocks; eauto. congruence.\nQed.\n\nTheorem valid_block_inject_2:\n  forall f m1 m2 b1 b2 delta,\n  f b1 = Some(b2, delta) ->\n  inject f m1 m2 ->\n  valid_block m2 b2.\nProof.\n  intros. eapply mi_mappedblocks; eauto. \nQed.\n\nLocal Hint Resolve valid_block_inject_1 valid_block_inject_2: mem.\n\nTheorem perm_inject:\n  forall f m1 m2 b1 b2 delta ofs k p,\n  f b1 = Some(b2, delta) ->\n  inject f m1 m2 ->\n  perm m1 b1 ofs k p -> perm m2 b2 (ofs + delta) k p.\nProof.\n  intros. inv H0. eapply perm_inj; eauto. \nQed.\n\nTheorem range_perm_inject:\n  forall f m1 m2 b1 b2 delta lo hi k p,\n  f b1 = Some(b2, delta) ->\n  inject f m1 m2 ->\n  range_perm m1 b1 lo hi k p -> range_perm m2 b2 (lo + delta) (hi + delta) k p.\nProof.\n  intros. inv H0. eapply range_perm_inj; eauto.\nQed.\n\nTheorem valid_access_inject:\n  forall f m1 m2 chunk b1 ofs b2 delta p,\n  f b1 = Some(b2, delta) ->\n  inject f m1 m2 ->\n  valid_access m1 chunk b1 ofs p ->\n  valid_access m2 chunk b2 (ofs + delta) p.\nProof.\n  intros. eapply mi_access; eauto. apply mi_inj; auto. \nQed.\n\nTheorem valid_pointer_inject:\n  forall f m1 m2 b1 ofs b2 delta,\n  f b1 = Some(b2, delta) ->\n  inject f m1 m2 ->\n  valid_pointer m1 b1 ofs = true ->\n  valid_pointer m2 b2 (ofs + delta) = true.\nProof.\n  intros. \n  rewrite valid_pointer_valid_access in H1.\n  rewrite valid_pointer_valid_access.\n  eapply valid_access_inject; eauto.\nQed.\n\nTheorem weak_valid_pointer_inject:\n  forall f m1 m2 b1 ofs b2 delta,\n  f b1 = Some(b2, delta) ->\n  inject f m1 m2 ->\n  weak_valid_pointer m1 b1 ofs = true ->\n  weak_valid_pointer m2 b2 (ofs + delta) = true.\nProof.\n  intros until 2. unfold weak_valid_pointer. rewrite !orb_true_iff.\n  replace (ofs + delta - 1) with ((ofs - 1) + delta) by omega.\n  intros []; eauto using valid_pointer_inject.\nQed.\n\n(** The following lemmas establish the absence of machine integer overflow\n  during address computations. *)\n\n(*\nLemma address_no_overflow:\n  forall f m1 m2 b1 b2 delta ofs1 k p,\n  inject f m1 m2 ->\n  perm m1 b1 (Int.unsigned ofs1) k p ->\n  f b1 = Some (b2, delta) ->\n  0 <= Int.unsigned ofs1 + Int.unsigned (Int.repr delta) <= Int.max_unsigned.\nProof.\n  intros. exploit mi_representable; eauto. intros [A | [A B]].\n  subst delta. change (Int.unsigned (Int.repr 0)) with 0. \n  rewrite Zplus_0_r. apply Int.unsigned_range_2.\n  rewrite Int.unsigned_repr; auto. \nQed.\n*)\n\nLemma address_inject:\n  forall f m1 m2 b1 ofs1 b2 delta p,\n  inject f m1 m2 ->\n  perm m1 b1 (Int.unsigned ofs1) Cur p ->\n  f b1 = Some (b2, delta) ->\n  Int.unsigned (Int.add ofs1 (Int.repr delta)) = Int.unsigned ofs1 + delta.\nProof.\n  intros. apply (perm_implies _ _ _ _ _ Nonempty) in H0; [| constructor].\n  rewrite <-valid_pointer_nonempty_perm in H0.\n  apply valid_pointer_implies in H0.\n  exploit mi_representable; eauto. intros [A B].\n  assert (0 <= delta <= Int.max_unsigned).\n    generalize (Int.unsigned_range ofs1). omega.\n  unfold Int.add. repeat rewrite Int.unsigned_repr; omega.\nQed.\n\nLemma address_inject':\n  forall f m1 m2 chunk b1 ofs1 b2 delta,\n  inject f m1 m2 ->\n  valid_access m1 chunk b1 (Int.unsigned ofs1) Nonempty ->\n  f b1 = Some (b2, delta) ->\n  Int.unsigned (Int.add ofs1 (Int.repr delta)) = Int.unsigned ofs1 + delta.\nProof.\n  intros. destruct H0. eapply address_inject; eauto. \n  apply H0. generalize (size_chunk_pos chunk). omega. \nQed.\n\nTheorem weak_valid_pointer_inject_no_overflow:\n  forall f m1 m2 b ofs b' delta,\n  inject f m1 m2 ->\n  weak_valid_pointer m1 b (Int.unsigned ofs) = true ->\n  f b = Some(b', delta) ->\n  0 <= Int.unsigned ofs + Int.unsigned (Int.repr delta) <= Int.max_unsigned.\nProof.\n  intros. exploit mi_representable; eauto. intros.\n  pose proof (Int.unsigned_range ofs).\n  rewrite Int.unsigned_repr; omega.\nQed.\n\nTheorem valid_pointer_inject_no_overflow:\n  forall f m1 m2 b ofs b' delta,\n  inject f m1 m2 ->\n  valid_pointer m1 b (Int.unsigned ofs) = true ->\n  f b = Some(b', delta) ->\n  0 <= Int.unsigned ofs + Int.unsigned (Int.repr delta) <= Int.max_unsigned.\nProof.\n  eauto using weak_valid_pointer_inject_no_overflow, valid_pointer_implies.\nQed.\n\nTheorem valid_pointer_inject_val:\n  forall f m1 m2 b ofs b' ofs',\n  inject f m1 m2 ->\n  valid_pointer m1 b (Int.unsigned ofs) = true ->\n  val_inject f (Vptr b ofs) (Vptr b' ofs') ->\n  valid_pointer m2 b' (Int.unsigned ofs') = true.\nProof.\n  intros. inv H1.\n  erewrite address_inject'; eauto. \n  eapply valid_pointer_inject; eauto.\n  rewrite valid_pointer_valid_access in H0. eauto.\nQed.\n\nTheorem weak_valid_pointer_inject_val:\n  forall f m1 m2 b ofs b' ofs',\n  inject f m1 m2 ->\n  weak_valid_pointer m1 b (Int.unsigned ofs) = true ->\n  val_inject f (Vptr b ofs) (Vptr b' ofs') ->\n  weak_valid_pointer m2 b' (Int.unsigned ofs') = true.\nProof.\n  intros. inv H1. exploit mi_representable; try eassumption. intros.\n  pose proof (Int.unsigned_range ofs).\n  exploit weak_valid_pointer_inject; eauto.\n  unfold Int.add. repeat rewrite Int.unsigned_repr; auto; omega.\nQed.\n\nTheorem inject_no_overlap:\n  forall f m1 m2 b1 b2 b1' b2' delta1 delta2 ofs1 ofs2,\n  inject f m1 m2 ->\n  b1 <> b2 ->\n  f b1 = Some (b1', delta1) ->\n  f b2 = Some (b2', delta2) ->\n  perm m1 b1 ofs1 Max Nonempty ->\n  perm m1 b2 ofs2 Max Nonempty ->\n  b1' <> b2' \\/ ofs1 + delta1 <> ofs2 + delta2.\nProof.\n  intros. inv H. eapply mi_no_overlap0; eauto.\nQed.\n\nTheorem different_pointers_inject:\n  forall f m m' b1 ofs1 b2 ofs2 b1' delta1 b2' delta2,\n  inject f m m' ->\n  b1 <> b2 ->\n  valid_pointer m b1 (Int.unsigned ofs1) = true ->\n  valid_pointer m b2 (Int.unsigned ofs2) = true ->\n  f b1 = Some (b1', delta1) ->\n  f b2 = Some (b2', delta2) ->\n  b1' <> b2' \\/\n  Int.unsigned (Int.add ofs1 (Int.repr delta1)) <>\n  Int.unsigned (Int.add ofs2 (Int.repr delta2)).\nProof.\n  intros. \n  rewrite valid_pointer_valid_access in H1. \n  rewrite valid_pointer_valid_access in H2. \n  rewrite (address_inject' _ _ _ _ _ _ _ _ H H1 H3). \n  rewrite (address_inject' _ _ _ _ _ _ _ _ H H2 H4). \n  inv H1. simpl in H5. inv H2. simpl in H1.\n  eapply mi_no_overlap; eauto.\n  apply perm_cur_max. apply (H5 (Int.unsigned ofs1)). omega.\n  apply perm_cur_max. apply (H1 (Int.unsigned ofs2)). omega.\nQed.\n\nRequire Intv.\n\nTheorem disjoint_or_equal_inject:\n  forall f m m' b1 b1' delta1 b2 b2' delta2 ofs1 ofs2 sz,\n  inject f m m' ->\n  f b1 = Some(b1', delta1) ->\n  f b2 = Some(b2', delta2) ->\n  range_perm m b1 ofs1 (ofs1 + sz) Max Nonempty ->\n  range_perm m b2 ofs2 (ofs2 + sz) Max Nonempty ->\n  sz > 0 ->\n  b1 <> b2 \\/ ofs1 = ofs2 \\/ ofs1 + sz <= ofs2 \\/ ofs2 + sz <= ofs1 ->\n  b1' <> b2' \\/ ofs1 + delta1 = ofs2 + delta2\n             \\/ ofs1 + delta1 + sz <= ofs2 + delta2 \n             \\/ ofs2 + delta2 + sz <= ofs1 + delta1.\nProof.\n  intros. \n  destruct (eq_block b1 b2).\n  assert (b1' = b2') by congruence. assert (delta1 = delta2) by congruence. subst.\n  destruct H5. congruence. right. destruct H5. left; congruence. right. omega.\n  destruct (eq_block b1' b2'); auto. subst. right. right. \n  set (i1 := (ofs1 + delta1, ofs1 + delta1 + sz)).\n  set (i2 := (ofs2 + delta2, ofs2 + delta2 + sz)).\n  change (snd i1 <= fst i2 \\/ snd i2 <= fst i1).\n  apply Intv.range_disjoint'; simpl; try omega.\n  unfold Intv.disjoint, Intv.In; simpl; intros. red; intros. \n  exploit mi_no_overlap; eauto. \n  instantiate (1 := x - delta1). apply H2. omega.\n  instantiate (1 := x - delta2). apply H3. omega.\n  unfold block; omega. \nQed.\n\nTheorem aligned_area_inject:\n  forall f m m' b ofs al sz b' delta,\n  inject f m m' ->\n  al = 1 \\/ al = 2 \\/ al = 4 \\/ al = 8 -> sz > 0 ->\n  (al | sz) ->\n  range_perm m b ofs (ofs + sz) Cur Nonempty ->\n  (al | ofs) ->\n  f b = Some(b', delta) ->\n  (al | ofs + delta).\nProof.\n  intros. \n  assert (P: al > 0) by omega.\n  assert (Q: Zabs al <= Zabs sz). apply Zdivide_bounds; auto. omega.\n  rewrite Zabs_eq in Q; try omega. rewrite Zabs_eq in Q; try omega.\n  assert (R: exists chunk, al = align_chunk chunk /\\ al = size_chunk chunk).\n    destruct H0. subst; exists Mint8unsigned; auto.\n    destruct H0. subst; exists Mint16unsigned; auto.\n    destruct H0. subst; exists Mint32; auto.\n    subst; exists Mfloat64; auto.\n  destruct R as [chunk [A B]].\n  assert (valid_access m chunk b ofs Nonempty).\n    split. red; intros; apply H3. omega. congruence.\n  exploit valid_access_inject; eauto. intros [C D]. \n  congruence.\nQed.\n\n(** Preservation of loads *)\n\nTheorem load_inject:\n  forall f m1 m2 chunk b1 ofs b2 delta v1,\n  inject f m1 m2 ->\n  load chunk m1 b1 ofs = Some v1 ->\n  f b1 = Some (b2, delta) ->\n  exists v2, load chunk m2 b2 (ofs + delta) = Some v2 /\\ val_inject f v1 v2.\nProof.\n  intros. inv H. eapply load_inj; eauto. \nQed.\n\nTheorem loadv_inject:\n  forall f m1 m2 chunk a1 a2 v1,\n  inject f m1 m2 ->\n  loadv chunk m1 a1 = Some v1 ->\n  val_inject f a1 a2 ->\n  exists v2, loadv chunk m2 a2 = Some v2 /\\ val_inject f v1 v2.\nProof.\n  intros. inv H1; simpl in H0; try discriminate.\n  exploit load_inject; eauto. intros [v2 [LOAD INJ]].\n  exists v2; split; auto. unfold loadv. \n  replace (Int.unsigned (Int.add ofs1 (Int.repr delta)))\n     with (Int.unsigned ofs1 + delta).\n  auto. symmetry. eapply address_inject'; eauto with mem.\nQed.\n\nTheorem loadbytes_inject:\n  forall f m1 m2 b1 ofs len b2 delta bytes1,\n  inject f m1 m2 ->\n  loadbytes m1 b1 ofs len = Some bytes1 ->\n  f b1 = Some (b2, delta) ->\n  exists bytes2, loadbytes m2 b2 (ofs + delta) len = Some bytes2\n              /\\ list_forall2 (memval_inject f) bytes1 bytes2.\nProof.\n  intros. inv H. eapply loadbytes_inj; eauto. \nQed.\n\n(** Preservation of stores *)\n\nTheorem store_mapped_inject:\n  forall f chunk m1 b1 ofs v1 n1 m2 b2 delta v2,\n  inject f m1 m2 ->\n  store chunk m1 b1 ofs v1 = Some n1 ->\n  f b1 = Some (b2, delta) ->\n  val_inject f v1 v2 ->\n  exists n2,\n    store chunk m2 b2 (ofs + delta) v2 = Some n2\n    /\\ inject f n1 n2.\nProof.\n  intros. inversion H.\n  exploit store_mapped_inj; eauto. intros [n2 [STORE MI]].\n  exists n2; split. eauto. constructor.\n(* inj *)\n  auto.\n(* freeblocks *)\n  eauto with mem. \n(* mappedblocks *)\n  eauto with mem.\n(* no overlap *)\n  red; intros. eauto with mem.\n(* representable *)\n  intros. eapply mi_representable; try eassumption.\n  rewrite weak_valid_pointer_spec in *.\n  rewrite !valid_pointer_nonempty_perm in H4 |- *.\n  destruct H4; eauto with mem.\nQed.\n\nTheorem store_unmapped_inject:\n  forall f chunk m1 b1 ofs v1 n1 m2,\n  inject f m1 m2 ->\n  store chunk m1 b1 ofs v1 = Some n1 ->\n  f b1 = None ->\n  inject f n1 m2.\nProof.\n  intros. inversion H.\n  constructor.\n(* inj *)\n  eapply store_unmapped_inj; eauto.\n(* freeblocks *)\n  eauto with mem. \n(* mappedblocks *)\n  eauto with mem.\n(* no overlap *)\n  red; intros. eauto with mem.\n(* representable *)\n  intros. eapply mi_representable; try eassumption.\n  rewrite weak_valid_pointer_spec in *.\n  rewrite !valid_pointer_nonempty_perm in H3 |- *.\n  destruct H3; eauto with mem.\nQed.\n\nTheorem store_outside_inject:\n  forall f m1 m2 chunk b ofs v m2',\n  inject f m1 m2 ->\n  (forall b' delta ofs',\n    f b' = Some(b, delta) ->\n    perm m1 b' ofs' Cur Readable ->\n    ofs <= ofs' + delta < ofs + size_chunk chunk -> False) ->\n  store chunk m2 b ofs v = Some m2' ->\n  inject f m1 m2'.\nProof.\n  intros. inversion H. constructor.\n(* inj *)\n  eapply store_outside_inj; eauto.\n(* freeblocks *)\n  auto.\n(* mappedblocks *)\n  eauto with mem.\n(* no overlap *)\n  auto.\n(* representable *)\n  eauto with mem.\nQed.\n\nTheorem storev_mapped_inject:\n  forall f chunk m1 a1 v1 n1 m2 a2 v2,\n  inject f m1 m2 ->\n  storev chunk m1 a1 v1 = Some n1 ->\n  val_inject f a1 a2 ->\n  val_inject f v1 v2 ->\n  exists n2,\n    storev chunk m2 a2 v2 = Some n2 /\\ inject f n1 n2.\nProof.\n  intros. inv H1; simpl in H0; try discriminate.\n  unfold storev.\n  replace (Int.unsigned (Int.add ofs1 (Int.repr delta)))\n    with (Int.unsigned ofs1 + delta).\n  eapply store_mapped_inject; eauto.\n  symmetry. eapply address_inject'; eauto with mem.\nQed.\n\nTheorem storebytes_mapped_inject:\n  forall f m1 b1 ofs bytes1 n1 m2 b2 delta bytes2,\n  inject f m1 m2 ->\n  storebytes m1 b1 ofs bytes1 = Some n1 ->\n  f b1 = Some (b2, delta) ->\n  list_forall2 (memval_inject f) bytes1 bytes2 ->\n  exists n2,\n    storebytes m2 b2 (ofs + delta) bytes2 = Some n2\n    /\\ inject f n1 n2.\nProof.\n  intros. inversion H.\n  exploit storebytes_mapped_inj; eauto. intros [n2 [STORE MI]].\n  exists n2; split. eauto. constructor.\n(* inj *)\n  auto.\n(* freeblocks *)\n  intros. apply mi_freeblocks0. red; intros; elim H3; eapply storebytes_valid_block_1; eauto.\n(* mappedblocks *)\n  intros. eapply storebytes_valid_block_1; eauto. \n(* no overlap *)\n  red; intros. eapply mi_no_overlap0; eauto; eapply perm_storebytes_2; eauto. \n(* representable *)\n  intros. eapply mi_representable0; eauto.\n  rewrite weak_valid_pointer_spec in *.\n  rewrite !valid_pointer_nonempty_perm in H4 |- *.\n  destruct H4; eauto using perm_storebytes_2. \nQed.\n\nTheorem storebytes_unmapped_inject:\n  forall f m1 b1 ofs bytes1 n1 m2,\n  inject f m1 m2 ->\n  storebytes m1 b1 ofs bytes1 = Some n1 ->\n  f b1 = None ->\n  inject f n1 m2.\nProof.\n  intros. inversion H.\n  constructor.\n(* inj *)\n  eapply storebytes_unmapped_inj; eauto.\n(* freeblocks *)\n  intros. apply mi_freeblocks0. red; intros; elim H2; eapply storebytes_valid_block_1; eauto.\n(* mappedblocks *)\n  eauto with mem.\n(* no overlap *)\n  red; intros. eapply mi_no_overlap0; eauto; eapply perm_storebytes_2; eauto. \n(* representable *)\n  intros. eapply mi_representable0; eauto.\n  rewrite weak_valid_pointer_spec in *.\n  rewrite !valid_pointer_nonempty_perm in H3 |- *.\n  destruct H3; eauto using perm_storebytes_2.\nQed.\n\nTheorem storebytes_outside_inject:\n  forall f m1 m2 b ofs bytes2 m2',\n  inject f m1 m2 ->\n  (forall b' delta ofs',\n    f b' = Some(b, delta) ->\n    perm m1 b' ofs' Cur Readable ->\n    ofs <= ofs' + delta < ofs + Z_of_nat (length bytes2) -> False) ->\n  storebytes m2 b ofs bytes2 = Some m2' ->\n  inject f m1 m2'.\nProof.\n  intros. inversion H. constructor.\n(* inj *)\n  eapply storebytes_outside_inj; eauto.\n(* freeblocks *)\n  auto.\n(* mappedblocks *)\n  intros. eapply storebytes_valid_block_1; eauto. \n(* no overlap *)\n  auto.\n(* representable *)\n  auto.\nQed.\n\n(* Preservation of allocations *)\n\nTheorem alloc_right_inject:\n  forall f m1 m2 lo hi b2 m2',\n  inject f m1 m2 ->\n  alloc m2 lo hi = (m2', b2) ->\n  inject f m1 m2'.\nProof.\n  intros. injection H0. intros NEXT MEM.\n  inversion H. constructor.\n(* inj *)\n  eapply alloc_right_inj; eauto.\n(* freeblocks *)\n  auto.\n(* mappedblocks *)\n  eauto with mem.\n(* no overlap *)\n  auto.\n(* representable *)\n  auto.\nQed.\n\nTheorem alloc_left_unmapped_inject:\n  forall f m1 m2 lo hi m1' b1,\n  inject f m1 m2 ->\n  alloc m1 lo hi = (m1', b1) ->\n  exists f',\n     inject f' m1' m2\n  /\\ inject_incr f f'\n  /\\ f' b1 = None\n  /\\ (forall b, b <> b1 -> f' b = f b).\nProof.\n  intros. inversion H.\n  set (f' := fun b => if zeq b b1 then None else f b).\n  assert (inject_incr f f').\n    red; unfold f'; intros. destruct (zeq b b1). subst b.\n    assert (f b1 = None). eauto with mem. congruence.\n    auto.\n  assert (mem_inj f' m1 m2).\n    inversion mi_inj0; constructor; eauto with mem.\n    unfold f'; intros. destruct (zeq b0 b1). congruence. eauto.\n    unfold f'; intros. destruct (zeq b0 b1). congruence. eauto.\n    unfold f'; intros. destruct (zeq b0 b1). congruence. \n    apply memval_inject_incr with f; auto. \n  exists f'; split. constructor.\n(* inj *)\n  eapply alloc_left_unmapped_inj; eauto. unfold f'; apply zeq_true. \n(* freeblocks *)\n  intros. unfold f'. destruct (zeq b b1). auto. \n  apply mi_freeblocks0. red; intro; elim H3. eauto with mem. \n(* mappedblocks *)\n  unfold f'; intros. destruct (zeq b b1). congruence. eauto. \n(* no overlap *)\n  unfold f'; red; intros.\n  destruct (zeq b0 b1); destruct (zeq b2 b1); try congruence.\n  eapply mi_no_overlap0. eexact H3. eauto. eauto.\n  exploit perm_alloc_inv. eauto. eexact H6. rewrite zeq_false; auto. \n  exploit perm_alloc_inv. eauto. eexact H7. rewrite zeq_false; auto. \n(* representable *)\n  unfold f'; intros.\n  destruct (zeq b b1); try discriminate.\n  eapply mi_representable0; try eassumption.\n  rewrite weak_valid_pointer_spec in *.\n  rewrite !valid_pointer_nonempty_perm in H4 |- *.\n  destruct H4; eauto using perm_alloc_4.\n(* incr *)\n  split. auto. \n(* image *)\n  split. unfold f'; apply zeq_true. \n(* incr *)\n  intros; unfold f'; apply zeq_false; auto.\nQed.\n\nTheorem alloc_left_mapped_inject:\n  forall f m1 m2 lo hi m1' b1 b2 delta,\n  inject f m1 m2 ->\n  alloc m1 lo hi = (m1', b1) ->\n  valid_block m2 b2 ->\n  0 <= delta <= Int.max_unsigned ->\n  (forall ofs k p, perm m2 b2 ofs k p -> delta = 0 \\/ 0 <= ofs < Int.max_unsigned) ->\n  (forall ofs k p, lo <= ofs < hi -> perm m2 b2 (ofs + delta) k p) ->\n  inj_offset_aligned delta (hi-lo) ->\n  (forall b delta' ofs k p,\n   f b = Some (b2, delta') -> \n   perm m1 b ofs k p ->\n   lo + delta <= ofs + delta' < hi + delta -> False) ->\n  exists f',\n     inject f' m1' m2\n  /\\ inject_incr f f'\n  /\\ f' b1 = Some(b2, delta)\n  /\\ (forall b, b <> b1 -> f' b = f b).\nProof.\n  intros. inversion H.\n  set (f' := fun b => if zeq b b1 then Some(b2, delta) else f b).\n  assert (inject_incr f f').\n    red; unfold f'; intros. destruct (zeq b b1). subst b.\n    assert (f b1 = None). eauto with mem. congruence.\n    auto.\n  assert (mem_inj f' m1 m2).\n    inversion mi_inj0; constructor; eauto with mem.\n    unfold f'; intros. destruct (zeq b0 b1).\n      inversion H8. subst b0 b3 delta0. \n      elim (fresh_block_alloc _ _ _ _ _ H0). eauto with mem.\n      eauto.\n    unfold f'; intros. destruct (zeq b0 b1).\n      inversion H8. subst b0 b3 delta0. \n      elim (fresh_block_alloc _ _ _ _ _ H0). eauto with mem.\n      eauto.\n    unfold f'; intros. destruct (zeq b0 b1).\n      inversion H8. subst b0 b3 delta0. \n      elim (fresh_block_alloc _ _ _ _ _ H0). eauto with mem.\n      apply memval_inject_incr with f; auto. \n  exists f'. split. constructor.\n(* inj *)\n  eapply alloc_left_mapped_inj; eauto. unfold f'; apply zeq_true. \n(* freeblocks *)\n  unfold f'; intros. destruct (zeq b b1). subst b. \n  elim H9. eauto with mem.\n  eauto with mem.\n(* mappedblocks *)\n  unfold f'; intros. destruct (zeq b b1). congruence. eauto.\n(* overlap *)\n  unfold f'; red; intros.\n  exploit perm_alloc_inv. eauto. eexact H12. intros P1.\n  exploit perm_alloc_inv. eauto. eexact H13. intros P2.\n  destruct (zeq b0 b1); destruct (zeq b3 b1).\n  congruence.\n  inversion H10; subst b0 b1' delta1. \n    destruct (zeq b2 b2'); auto. subst b2'. right; red; intros.\n    eapply H6; eauto. omega.\n  inversion H11; subst b3 b2' delta2. \n    destruct (zeq b1' b2); auto. subst b1'. right; red; intros.\n    eapply H6; eauto. omega.\n  eauto.\n(* representable *)\n  unfold f'; intros.\n  rewrite weak_valid_pointer_spec in *.\n  rewrite !valid_pointer_nonempty_perm in H10.\n  destruct (zeq b b1).\n   subst. injection H9; intros; subst b' delta0. destruct H10.\n    exploit perm_alloc_inv; eauto; rewrite zeq_true; intro.\n    exploit H3. apply H4 with (k := Cur) (p := Nonempty); eauto.\n    generalize (Int.unsigned_range_2 ofs). omega.\n   exploit perm_alloc_inv; eauto; rewrite zeq_true; intro.\n   exploit H3. apply H4 with (k := Cur) (p := Nonempty); eauto.\n   generalize (Int.unsigned_range_2 ofs). omega.\n  eapply mi_representable0; try eassumption.\n  rewrite !weak_valid_pointer_spec, !valid_pointer_nonempty_perm.\n  destruct H10; eauto using perm_alloc_4.\n(* incr *)\n  split. auto.\n(* image of b1 *)\n  split. unfold f'; apply zeq_true. \n(* image of others *)\n  intros. unfold f'; apply zeq_false; auto. \nQed.\n\nTheorem alloc_parallel_inject:\n  forall f m1 m2 lo1 hi1 m1' b1 lo2 hi2,\n  inject f m1 m2 ->\n  alloc m1 lo1 hi1 = (m1', b1) ->\n  lo2 <= lo1 -> hi1 <= hi2 ->\n  exists f', exists m2', exists b2,\n  alloc m2 lo2 hi2 = (m2', b2)\n  /\\ inject f' m1' m2'\n  /\\ inject_incr f f'\n  /\\ f' b1 = Some(b2, 0)\n  /\\ (forall b, b <> b1 -> f' b = f b).\nProof.\n  intros.\n  case_eq (alloc m2 lo2 hi2). intros m2' b2 ALLOC.\n  exploit alloc_left_mapped_inject. \n  eapply alloc_right_inject; eauto.\n  eauto.\n  instantiate (1 := b2). eauto with mem.\n  instantiate (1 := 0). unfold Int.max_unsigned. generalize Int.modulus_pos; omega.\n  auto.\n  intros. apply perm_implies with Freeable; auto with mem.\n  eapply perm_alloc_2; eauto. omega.\n  red; intros. apply Zdivide_0.\n  intros. apply (valid_not_valid_diff m2 b2 b2); eauto with mem.\n  intros [f' [A [B [C D]]]].\n  exists f'; exists m2'; exists b2; auto.\nQed.\n\n(** Preservation of [free] operations *)\n\nLemma free_left_inject:\n  forall f m1 m2 b lo hi m1',\n  inject f m1 m2 ->\n  free m1 b lo hi = Some m1' ->\n  inject f m1' m2.\nProof.\n  intros. inversion H. constructor.\n(* inj *)\n  eapply free_left_inj; eauto.\n(* freeblocks *)\n  eauto with mem.\n(* mappedblocks *)\n  auto.\n(* no overlap *)\n  red; intros. eauto with mem. \n(* representable *)\n  intros. eapply mi_representable0; try eassumption.\n  rewrite weak_valid_pointer_spec in *.\n  rewrite !valid_pointer_nonempty_perm in H2 |- *.\n  destruct H2; eauto with mem.\nQed.\n\nLemma free_list_left_inject:\n  forall f m2 l m1 m1',\n  inject f m1 m2 ->\n  free_list m1 l = Some m1' ->\n  inject f m1' m2.\nProof.\n  induction l; simpl; intros. \n  inv H0. auto.\n  destruct a as [[b lo] hi]. generalize H0. case_eq (free m1 b lo hi); intros.\n  apply IHl with m; auto. eapply free_left_inject; eauto.\n  congruence.\nQed.\n\nLemma free_right_inject:\n  forall f m1 m2 b lo hi m2',\n  inject f m1 m2 ->\n  free m2 b lo hi = Some m2' ->\n  (forall b1 delta ofs k p,\n    f b1 = Some(b, delta) -> perm m1 b1 ofs k p ->\n    lo <= ofs + delta < hi -> False) ->\n  inject f m1 m2'.\nProof.\n  intros. inversion H. constructor.\n(* inj *)\n  eapply free_right_inj; eauto.\n(* freeblocks *)\n  auto.\n(* mappedblocks *)\n  eauto with mem.\n(* no overlap *)\n  auto.\n(* representable *)\n  auto.\nQed.\n\nLemma perm_free_list:\n  forall l m m' b ofs k p,\n  free_list m l = Some m' ->\n  perm m' b ofs k p ->\n  perm m b ofs k p /\\ \n  (forall lo hi, In (b, lo, hi) l -> lo <= ofs < hi -> False).\nProof.\n  induction l; intros until p; simpl.\n  intros. inv H. split; auto. \n  destruct a as [[b1 lo1] hi1].\n  case_eq (free m b1 lo1 hi1); intros; try congruence.\n  exploit IHl; eauto. intros [A B].\n  split. eauto with mem.\n  intros. destruct H2. inv H2.\n  elim (perm_free_2 _ _ _ _ _ H ofs k p). auto. auto.\n  eauto.\nQed.\n\nTheorem free_inject:\n  forall f m1 l m1' m2 b lo hi m2',\n  inject f m1 m2 ->\n  free_list m1 l = Some m1' ->\n  free m2 b lo hi = Some m2' ->\n  (forall b1 delta ofs k p,\n    f b1 = Some(b, delta) -> \n    perm m1 b1 ofs k p -> lo <= ofs + delta < hi ->\n    exists lo1, exists hi1, In (b1, lo1, hi1) l /\\ lo1 <= ofs < hi1) ->\n  inject f m1' m2'.\nProof.\n  intros. \n  eapply free_right_inject; eauto. \n  eapply free_list_left_inject; eauto.\n  intros. exploit perm_free_list; eauto. intros [A B].\n  exploit H2; eauto. intros [lo1 [hi1 [C D]]]. eauto.\nQed.\n\nLemma drop_outside_inject: forall f m1 m2 b lo hi p m2',\n  inject f m1 m2 -> \n  drop_perm m2 b lo hi p = Some m2' -> \n  (forall b' delta ofs k p,\n    f b' = Some(b, delta) ->\n    perm m1 b' ofs k p -> lo <= ofs + delta < hi -> False) ->\n  inject f m1 m2'.\nProof.\n  intros. destruct H. constructor; eauto.\n  eapply drop_outside_inj; eauto.\n  intros. unfold valid_block in *. erewrite nextblock_drop; eauto. \nQed.\n\n(** Composing two memory injections. *)\n\nLemma mem_inj_compose:\n  forall f f' m1 m2 m3,\n  mem_inj f m1 m2 -> mem_inj f' m2 m3 -> mem_inj (compose_meminj f f') m1 m3.\nProof.\n  intros. unfold compose_meminj. inv H; inv H0; constructor; intros.\n  (* perm *)\n  destruct (f b1) as [[b' delta'] |] eqn:?; try discriminate.\n  destruct (f' b') as [[b'' delta''] |] eqn:?; inv H. \n  replace (ofs + (delta' + delta'')) with ((ofs + delta') + delta'') by omega.\n  eauto.\n  (* valid access *)\n  destruct (f b1) as [[b' delta'] |] eqn:?; try discriminate.\n  destruct (f' b') as [[b'' delta''] |] eqn:?; inv H. \n  replace (ofs + (delta' + delta'')) with ((ofs + delta') + delta'') by omega.\n  eauto.\n  (* memval *)\n  destruct (f b1) as [[b' delta'] |] eqn:?; try discriminate.\n  destruct (f' b') as [[b'' delta''] |] eqn:?; inv H. \n  replace (ofs + (delta' + delta'')) with ((ofs + delta') + delta'') by omega.\n  eapply memval_inject_compose; eauto.\nQed. \n\nTheorem inject_compose:\n  forall f f' m1 m2 m3,\n  inject f m1 m2 -> inject f' m2 m3 ->\n  inject (compose_meminj f f') m1 m3.\nProof.\n  unfold compose_meminj; intros.\n  inv H; inv H0. constructor.\n(* inj *)\n  eapply mem_inj_compose; eauto. \n(* unmapped *)\n  intros. erewrite mi_freeblocks0; eauto. \n(* mapped *)\n  intros. \n  destruct (f b) as [[b1 delta1] |] eqn:?; try discriminate.\n  destruct (f' b1) as [[b2 delta2] |] eqn:?; inv H. \n  eauto.\n(* no overlap *)\n  red; intros. \n  destruct (f b1) as [[b1x delta1x] |] eqn:?; try discriminate.\n  destruct (f' b1x) as [[b1y delta1y] |] eqn:?; inv H0. \n  destruct (f b2) as [[b2x delta2x] |] eqn:?; try discriminate.\n  destruct (f' b2x) as [[b2y delta2y] |] eqn:?; inv H1.\n  exploit mi_no_overlap0; eauto. intros A.\n  destruct (eq_block b1x b2x). \n  subst b1x. destruct A. congruence. \n  assert (delta1y = delta2y) by congruence. right; omega.\n  exploit mi_no_overlap1. eauto. eauto. eauto.\n    eapply perm_inj. eauto. eexact H2. eauto. \n    eapply perm_inj. eauto. eexact H3. eauto. \n  unfold block; omega.\n(* representable *)\n  intros. \n  destruct (f b) as [[b1 delta1] |] eqn:?; try discriminate.\n  destruct (f' b1) as [[b2 delta2] |] eqn:?; inv H. \n  exploit mi_representable0; eauto. intros [A B].\n  set (ofs' := Int.repr (Int.unsigned ofs + delta1)).\n  assert (Int.unsigned ofs' = Int.unsigned ofs + delta1). \n    unfold ofs'; apply Int.unsigned_repr. auto.\n  exploit mi_representable1. eauto. instantiate (1 := ofs').\n  rewrite H.\n  rewrite weak_valid_pointer_spec, !valid_pointer_nonempty_perm in *.\n  replace (Int.unsigned ofs + delta1 - 1) with\n    ((Int.unsigned ofs - 1) + delta1) by omega.\n  destruct H0; eauto using perm_inj.\n  rewrite H. omega.\nQed.\n\nLemma val_lessdef_inject_compose:\n  forall f v1 v2 v3,\n  Val.lessdef v1 v2 -> val_inject f v2 v3 -> val_inject f v1 v3.\nProof.\n  intros. inv H. auto. auto.\nQed.\n\nLemma val_inject_lessdef_compose:\n  forall f v1 v2 v3,\n  val_inject f v1 v2 -> Val.lessdef v2 v3 -> val_inject f v1 v3.\nProof.\n  intros. inv H0. auto. inv H. auto.\nQed.\n\nLemma extends_inject_compose:\n  forall f m1 m2 m3,\n  extends m1 m2 -> inject f m2 m3 -> inject f m1 m3.\nProof.\n  intros. inversion H; inv H0. constructor; intros.\n(* inj *)\n  replace f with (compose_meminj inject_id f). eapply mem_inj_compose; eauto.\n  apply extensionality; intros. unfold compose_meminj, inject_id. \n  destruct (f x) as [[y delta] | ]; auto.\n(* unmapped *)\n  eapply mi_freeblocks0. erewrite <- valid_block_extends; eauto. \n(* mapped *)\n  eauto.\n(* no overlap *)\n  red; intros. eapply mi_no_overlap0; eauto; eapply perm_extends; eauto.\n(* representable *)\n  eapply mi_representable0; eauto.\n  rewrite weak_valid_pointer_spec, !valid_pointer_nonempty_perm in *.\n  destruct H1; eauto using perm_extends.\nQed.\n\nLemma inject_extends_compose:\n  forall f m1 m2 m3,\n  inject f m1 m2 -> extends m2 m3 -> inject f m1 m3.\nProof.\n  intros. inv H; inversion H0. constructor; intros.\n(* inj *)\n  replace f with (compose_meminj f inject_id). eapply mem_inj_compose; eauto.\n  apply extensionality; intros. unfold compose_meminj, inject_id. \n  destruct (f x) as [[y delta] | ]; auto. decEq. decEq. omega.\n(* unmapped *)\n  eauto.\n(* mapped *)\n  erewrite <- valid_block_extends; eauto. \n(* no overlap *)\n  red; intros. eapply mi_no_overlap0; eauto.\n(* representable *)\n  eapply mi_representable0; eauto.\nQed.\n\nLemma extends_extends_compose:\n  forall m1 m2 m3,\n  extends m1 m2 -> extends m2 m3 -> extends m1 m3.\nProof.\n  intros. inv H; inv H0; constructor; intros.\n  (* nextblock *)\n  congruence.\n  (* meminj *)\n  replace inject_id with (compose_meminj inject_id inject_id).\n  eapply mem_inj_compose; eauto. \n  apply extensionality; intros. unfold compose_meminj, inject_id. auto.\nQed.\n\n(** Injecting a memory into itself. *)\n\nDefinition flat_inj (thr: block) : meminj :=\n  fun (b: block) => if zlt b thr then Some(b, 0) else None.\n\nDefinition inject_neutral (thr: block) (m: mem) :=\n  mem_inj (flat_inj thr) m m.\n\nRemark flat_inj_no_overlap:\n  forall thr m, meminj_no_overlap (flat_inj thr) m.\nProof.\n  unfold flat_inj; intros; red; intros.\n  destruct (zlt b1 thr); inversion H0; subst.\n  destruct (zlt b2 thr); inversion H1; subst.\n  auto.\nQed.\n\nTheorem neutral_inject:\n  forall m, inject_neutral (nextblock m) m -> inject (flat_inj (nextblock m)) m m.\nProof.\n  intros. constructor.\n(* meminj *)\n  auto.\n(* freeblocks *)\n  unfold flat_inj, valid_block; intros.\n  apply zlt_false. omega.\n(* mappedblocks *)\n  unfold flat_inj, valid_block; intros. \n  destruct (zlt b (nextblock m)); inversion H0; subst. auto.\n(* no overlap *)\n  apply flat_inj_no_overlap.\n(* range *)\n  unfold flat_inj; intros.\n  destruct (zlt b (nextblock m)); inv H0. generalize (Int.unsigned_range_2 ofs); omega.\nQed.\n\nTheorem empty_inject_neutral:\n  forall thr, inject_neutral thr empty.\nProof.\n  intros; red; constructor.\n(* perm *)\n  unfold flat_inj; intros. destruct (zlt b1 thr); inv H.\n  replace (ofs + 0) with ofs by omega; auto.\n(* access *)\n  unfold flat_inj; intros. destruct (zlt b1 thr); inv H.\n  replace (ofs + 0) with ofs by omega; auto.\n(* mem_contents *)\n  intros; simpl. repeat rewrite ZMap.gi. constructor.\nQed.\n\nTheorem alloc_inject_neutral:\n  forall thr m lo hi b m',\n  alloc m lo hi = (m', b) ->\n  inject_neutral thr m ->\n  nextblock m < thr ->\n  inject_neutral thr m'.\nProof.\n  intros; red. \n  eapply alloc_left_mapped_inj with (m1 := m) (b2 := b) (delta := 0). \n  eapply alloc_right_inj; eauto. eauto. eauto with mem. \n  red. intros. apply Zdivide_0. \n  intros.\n  apply perm_implies with Freeable; auto with mem.\n  eapply perm_alloc_2; eauto. omega. \n  unfold flat_inj. apply zlt_true. \n  rewrite (alloc_result _ _ _ _ _ H). auto.\nQed.\n\nTheorem store_inject_neutral:\n  forall chunk m b ofs v m' thr,\n  store chunk m b ofs v = Some m' ->\n  inject_neutral thr m ->\n  b < thr ->\n  val_inject (flat_inj thr) v v ->\n  inject_neutral thr m'.\nProof.\n  intros; red.\n  exploit store_mapped_inj. eauto. eauto. apply flat_inj_no_overlap. \n  unfold flat_inj. apply zlt_true; auto. eauto.\n  replace (ofs + 0) with ofs by omega.  \n  intros [m'' [A B]]. congruence.\nQed. \n\nTheorem drop_inject_neutral:\n  forall m b lo hi p m' thr,\n  drop_perm m b lo hi p = Some m' ->\n  inject_neutral thr m ->\n  b < thr ->\n  inject_neutral thr m'.\nProof.\n  unfold inject_neutral; intros.\n  exploit drop_mapped_inj; eauto. apply flat_inj_no_overlap. \n  unfold flat_inj. apply zlt_true; eauto. \n  repeat rewrite Zplus_0_r. intros [m'' [A B]]. congruence.\nQed.\n\nInstance mem_ops: Mem.MemoryOps mem := {\n  empty := empty;\n  alloc := alloc;\n  free := free;\n  load := load;\n  store := store;\n  loadbytes := loadbytes;\n  storebytes := storebytes;\n  drop_perm := drop_perm;\n  nextblock := nextblock;\n  perm := perm;\n  valid_pointer := valid_pointer;\n  extends := extends\n}.\n\nLocal Instance mem_spec: Mem.MemoryStates mem := {\n  nextblock_pos := nextblock_pos;\n  valid_not_valid_diff := valid_not_valid_diff;\n  perm_implies := perm_implies;\n  perm_cur_max := perm_cur_max;\n  perm_cur := perm_cur;\n  perm_max := perm_max;\n  perm_valid_block := perm_valid_block;\n  perm_dec := perm_dec;\n  range_perm_implies := range_perm_implies;\n  range_perm_cur := range_perm_cur;\n  range_perm_max := range_perm_max;\n  valid_access_implies := valid_access_implies;\n  valid_access_valid_block := valid_access_valid_block;\n  valid_access_perm := valid_access_perm;\n  valid_pointer_nonempty_perm := valid_pointer_nonempty_perm;\n  valid_pointer_valid_access := valid_pointer_valid_access;\n  weak_valid_pointer_spec := weak_valid_pointer_spec;\n  valid_pointer_implies := valid_pointer_implies;\n  nextblock_empty := nextblock_empty;\n  perm_empty := perm_empty;\n  valid_access_empty := valid_access_empty;\n  valid_access_load := valid_access_load;\n  load_valid_access := load_valid_access;\n  load_type := load_type;\n  load_cast := load_cast;\n  load_int8_signed_unsigned := load_int8_signed_unsigned;\n  load_int16_signed_unsigned := load_int16_signed_unsigned;\n  load_float64al32 := load_float64al32;\n  loadv_float64al32 := loadv_float64al32;\n  range_perm_loadbytes := range_perm_loadbytes;\n  loadbytes_range_perm := loadbytes_range_perm;\n  loadbytes_load := loadbytes_load;\n  load_loadbytes := load_loadbytes;\n  loadbytes_length := loadbytes_length;\n  loadbytes_empty := loadbytes_empty;\n  loadbytes_concat := loadbytes_concat;\n  loadbytes_split := loadbytes_split;\n  nextblock_store := nextblock_store;\n  store_valid_block_1 := store_valid_block_1;\n  store_valid_block_2 := store_valid_block_2;\n  perm_store_1 := perm_store_1;\n  perm_store_2 := perm_store_2;\n  valid_access_store := valid_access_store;\n  store_valid_access_1 := store_valid_access_1;\n  store_valid_access_2 := store_valid_access_2;\n  store_valid_access_3 := store_valid_access_3;\n  load_store_similar := load_store_similar;\n  load_store_same := load_store_same;\n  load_store_other := load_store_other;\n  load_store_pointer_overlap := load_store_pointer_overlap;\n  load_store_pointer_mismatch := load_store_pointer_mismatch;\n  load_pointer_store := load_pointer_store;\n  loadbytes_store_same := loadbytes_store_same;\n  loadbytes_store_other := loadbytes_store_other;\n  store_signed_unsigned_8 := store_signed_unsigned_8;\n  store_signed_unsigned_16 := store_signed_unsigned_16;\n  store_int8_zero_ext := store_int8_zero_ext;\n  store_int8_sign_ext := store_int8_sign_ext;\n  store_int16_zero_ext := store_int16_zero_ext;\n  store_int16_sign_ext := store_int16_sign_ext;\n  store_float32_truncate := store_float32_truncate;\n  store_float64al32 := store_float64al32;\n  storev_float64al32 := storev_float64al32;\n  range_perm_storebytes := range_perm_storebytes;\n  storebytes_range_perm := storebytes_range_perm;\n  perm_storebytes_1 := perm_storebytes_1;\n  perm_storebytes_2 := perm_storebytes_2;\n  storebytes_valid_access_1 := storebytes_valid_access_1;\n  storebytes_valid_access_2 := storebytes_valid_access_2;\n  nextblock_storebytes := nextblock_storebytes;\n  storebytes_valid_block_1 := storebytes_valid_block_1;\n  storebytes_valid_block_2 := storebytes_valid_block_2;\n  storebytes_store := storebytes_store;\n  store_storebytes := store_storebytes;\n  loadbytes_storebytes_same := loadbytes_storebytes_same;\n  loadbytes_storebytes_other := loadbytes_storebytes_other;\n  load_storebytes_other := load_storebytes_other;\n  storebytes_concat := storebytes_concat;\n  storebytes_split := storebytes_split;\n  alloc_result := alloc_result;\n  nextblock_alloc := nextblock_alloc;\n  valid_block_alloc := valid_block_alloc;\n  fresh_block_alloc := fresh_block_alloc;\n  valid_new_block := valid_new_block;\n  valid_block_alloc_inv := valid_block_alloc_inv;\n  perm_alloc_1 := perm_alloc_1;\n  perm_alloc_2 := perm_alloc_2;\n  perm_alloc_3 := perm_alloc_3;\n  perm_alloc_4 := perm_alloc_4;\n  perm_alloc_inv := perm_alloc_inv;\n  valid_access_alloc_other := valid_access_alloc_other;\n  valid_access_alloc_same := valid_access_alloc_same;\n  valid_access_alloc_inv := valid_access_alloc_inv;\n  load_alloc_unchanged := load_alloc_unchanged;\n  load_alloc_other := load_alloc_other;\n  load_alloc_same := load_alloc_same;\n  load_alloc_same' := load_alloc_same';\n  range_perm_free := range_perm_free;\n  free_range_perm := free_range_perm;\n  nextblock_free := nextblock_free;\n  valid_block_free_1 := valid_block_free_1;\n  valid_block_free_2 := valid_block_free_2;\n  perm_free_1 := perm_free_1;\n  perm_free_2 := perm_free_2;\n  perm_free_3 := perm_free_3;\n  valid_access_free_1 := valid_access_free_1;\n  valid_access_free_2 := valid_access_free_2;\n  valid_access_free_inv_1 := valid_access_free_inv_1;\n  valid_access_free_inv_2 := valid_access_free_inv_2;\n  load_free := load_free;\n  nextblock_drop := nextblock_drop;\n  drop_perm_valid_block_1 := drop_perm_valid_block_1;\n  drop_perm_valid_block_2 := drop_perm_valid_block_2;\n  range_perm_drop_1 := range_perm_drop_1;\n  range_perm_drop_2 := range_perm_drop_2;\n  perm_drop_1 := perm_drop_1;\n  perm_drop_2 := perm_drop_2;\n  perm_drop_3 := perm_drop_3;\n  perm_drop_4 := perm_drop_4;\n  load_drop := load_drop;\n  extends_refl := extends_refl;\n  load_extends := load_extends;\n  loadv_extends := loadv_extends;\n  loadbytes_extends := loadbytes_extends;\n  store_within_extends := store_within_extends;\n  store_outside_extends := store_outside_extends;\n  storev_extends := storev_extends;\n  storebytes_within_extends := storebytes_within_extends;\n  storebytes_outside_extends := storebytes_outside_extends;\n  alloc_extends := alloc_extends;\n  free_left_extends := free_left_extends;\n  free_right_extends := free_right_extends;\n  free_parallel_extends := free_parallel_extends;\n  valid_block_extends := valid_block_extends;\n  perm_extends := perm_extends;\n  valid_access_extends := valid_access_extends;\n  valid_pointer_extends := valid_pointer_extends;\n  weak_valid_pointer_extends := weak_valid_pointer_extends;\n  perm_free_list := perm_free_list;\n\n  ugly_workaround_dependee := unit;\n  ugly_workaround_depender := tt\n}.\n\nInstance inj_ops: Mem.InjectOps mem mem := {\n  inject := inject\n}.\n\nLocal Instance inj_spec: Mem.MemoryInjections mem mem := {\n  mi_freeblocks := mi_freeblocks;\n  valid_block_inject_1 := valid_block_inject_1;\n  valid_block_inject_2 := valid_block_inject_2;\n  perm_inject := perm_inject;\n  range_perm_inject := range_perm_inject;\n  valid_access_inject := valid_access_inject;\n  valid_pointer_inject := valid_pointer_inject;\n  weak_valid_pointer_inject := weak_valid_pointer_inject;\n  address_inject := address_inject;\n  valid_pointer_inject_no_overflow := valid_pointer_inject_no_overflow;\n  weak_valid_pointer_inject_no_overflow := weak_valid_pointer_inject_no_overflow;\n  valid_pointer_inject_val := valid_pointer_inject_val;\n  weak_valid_pointer_inject_val := weak_valid_pointer_inject_val;\n  inject_no_overlap := inject_no_overlap;\n  different_pointers_inject := different_pointers_inject;\n  disjoint_or_equal_inject := disjoint_or_equal_inject;\n  aligned_area_inject := aligned_area_inject;\n  load_inject := load_inject;\n  loadv_inject := loadv_inject;\n  loadbytes_inject := loadbytes_inject;\n  store_mapped_inject := store_mapped_inject;\n  store_unmapped_inject := store_unmapped_inject;\n  store_outside_inject := store_outside_inject;\n  storev_mapped_inject := storev_mapped_inject;\n  storebytes_mapped_inject := storebytes_mapped_inject;\n  storebytes_unmapped_inject := storebytes_unmapped_inject;\n  storebytes_outside_inject := storebytes_outside_inject;\n  alloc_right_inject := alloc_right_inject;\n  alloc_left_unmapped_inject := alloc_left_unmapped_inject;\n  alloc_left_mapped_inject := alloc_left_mapped_inject;\n  alloc_parallel_inject := alloc_parallel_inject;\n  free_left_inject := free_left_inject;\n  free_list_left_inject := free_list_left_inject;\n  free_right_inject := free_right_inject;\n  free_inject := free_inject;\n  drop_outside_inject := drop_outside_inject\n}.\n\nInstance mem_mm_ops: Mem.ModelOps mem := {\n  inject_neutral := inject_neutral\n}.\n\nInstance mem_mm_spec: Mem.MemoryModel mem := {\n  empty_inject_neutral := empty_inject_neutral;\n  alloc_inject_neutral := alloc_inject_neutral;\n  store_inject_neutral := store_inject_neutral;\n  drop_inject_neutral := drop_inject_neutral;\n  neutral_inject := neutral_inject\n}.\n", "meta": {"author": "jeremie-koenig", "repo": "compcert", "sha": "e58b5a076931637f2e7b13f6e9ba7a47e2cdc437", "save_path": "github-repos/coq/jeremie-koenig-compcert", "path": "github-repos/coq/jeremie-koenig-compcert/compcert-e58b5a076931637f2e7b13f6e9ba7a47e2cdc437/common/Memimpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.21954586785042032}}
{"text": "Require Import CContext.\nRequire Import String.\nRequire Import Maps.\n\nDefinition struct_table := partial_map (partial_map nat).\n\n(* TODO - must fix **)\nInductive context :=\n| space (s: cstack) (st: stack sym_tbl) (h: cheap) (ht: sym_tbl)\n        (H: valid_state s st) (s_tbl: struct_table).\n\nDefinition smart_lookup ctx var :=\n  let '(space s st h ht _ _) := ctx in\n  match lookup_s s st var with\n  | Some val => Some val\n  | None => match lookup_h h ht var with\n            | Some val => Some val\n            | None => None\n            end\n  end.\n\nDefinition decode_struct ctx s_name s_var :=\n  let '(space _ _ _ _ _ s_tbl) := ctx in\n  match s_tbl s_name with\n  | Some s_map => match s_map s_var with\n                  | Some offset => \n\n(* Internally translate each s_var to a pointer offset**)\nDefinition query_struct_space (ctx: context) (s_name s_var s_field: string) :=\n  smart_lookup ctx (decode_struct ctx s_name s_var).\n\n(* HOW DO I DEAL WITH TYPING DISTINCTIONS HERE? **)\n                  \nHint Unfold query_struct_space.\n", "meta": {"author": "abrassel", "repo": "CzechSea", "sha": "d6c7388346eb4b0c07605b40077e76186bd877a5", "save_path": "github-repos/coq/abrassel-CzechSea", "path": "github-repos/coq/abrassel-CzechSea/CzechSea-d6c7388346eb4b0c07605b40077e76186bd877a5/CContextManipulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2195001664095534}}
{"text": "Set Warnings \"-notation-overridden,-parsing\".\nRequire Import Tweetnacl_verif.init_tweetnacl.\nRequire Import Tweetnacl_verif.spec_A.\nRequire Import Tweetnacl.Libs.Export.\nRequire Import Tweetnacl.ListsOp.Export.\nRequire Import Tweetnacl.Low.A.\n\nOpen Scope Z.\n\nDefinition Gprog : funspecs :=\n      ltac:(with_library prog [A_spec]).\n\nImport Low.\n\nLemma body_A: semax_body Vprog Gprog f_A A_spec.\nProof.\nstart_function.\nunfold nm_overlap_array_sep_3, nm_overlap_array_sep_3' in *.\nassert(HA: Zlength (A a b) = 16). rewrite A_Zlength ; omega.\nassert(HmA: Zlength (mVI64 (A a b)) = 16). rewrite ?Zlength_map //.\nassert(Forall (fun x : ℤ => amin + bmin < x < amax + bmax) (A a b)).  apply A_bound_Zlength_lt ; trivial ; omega.\nassert(Htkdp: tkdp 16 (mVI64 (A a b)) o = mVI64 (A a b)). rewrite -HmA tkdp_all ; trivial ; rewrite ?Zlength_map; omega.\nassert(Haux1: forall i, 0 <= i < 16 -> exists aux1, Vlong aux1 = Znth i (mVI64 a) Vundef). intros; erewrite (Znth_map Int64.zero) ; [eexists ; reflexivity | rewrite Zlength_map; omega].\nassert(Haux2: forall i, 0 <= i < 16 -> exists aux2, Vlong aux2 = Znth i (mVI64 b) Vundef). intros; erewrite (Znth_map Int64.zero) ; [eexists ; reflexivity | rewrite Zlength_map; omega].\nassert(Haux3: forall i, 0 <= i < 16 -> exists aux3, Vlong aux3 = Znth i (tkdp i (mVI64 (A a b)) (mVI64 a)) Vundef).\n  intros ; rewrite /tkdp -?map_firstn -?map_skipn -?map_app ;\n  erewrite (Znth_map Int64.zero);[eexists ; reflexivity | rewrite ?Zlength_map];\n  change (firstn (nat_of_Z i) (A a b) ++ skipn (nat_of_Z i) a) with (tkdp i (A a b) a);\n  rewrite tkdp_Zlength HA ; omega.\nassert(Haux4: forall i, 0 <= i < 16 -> exists aux4, Vlong aux4 = Znth i (tkdp i (mVI64 (A a b)) (mVI64 b)) Vundef).\n  intros ; rewrite /tkdp -?map_firstn -?map_skipn -?map_app ;\n  erewrite (Znth_map Int64.zero);[eexists ; reflexivity | rewrite ?Zlength_map];\n  change (firstn (nat_of_Z i) (A a b) ++ skipn (nat_of_Z i) a) with (tkdp i (A a b) a);\n  rewrite tkdp_Zlength HA ; omega.\n\nflatten ; Intros.\n1: subst o v_a.\n2: subst o v_b.\n3: subst b v_b.\n4: subst o a v_o v_a.\n\n1: forward_for_simple_bound 16 (A_Inv sho sha shb v_o v_o v_b (mVI64 a) a amin amax b bmin bmax 0);\n[ unfold nm_overlap_array_sep_3' ; entailer!| |\n  rewrite Htkdp; forward; unfold nm_overlap_array_sep_3' ; entailer!].\n2: forward_for_simple_bound 16 (A_Inv sho sha shb v_o v_a v_o (mVI64 b) a amin amax b bmin bmax 1);\n[ unfold nm_overlap_array_sep_3' ; entailer! | |\n  rewrite Htkdp; forward; unfold nm_overlap_array_sep_3' ; entailer!].\n3: forward_for_simple_bound 16 (A_Inv sho sha shb v_o v_a v_a o a amin amax a amin amax 2);\n[ unfold nm_overlap_array_sep_3' ; entailer!| |\n  rewrite Htkdp; forward; unfold nm_overlap_array_sep_3' ; entailer!].\n4: forward_for_simple_bound 16 (A_Inv sho sha shb v_b v_b v_b (mVI64 b) b bmin bmax b bmin bmax 3);\n[ unfold nm_overlap_array_sep_3' ; entailer!| |\n  rewrite Htkdp; forward; unfold nm_overlap_array_sep_3' ; entailer!].\n5: forward_for_simple_bound 16 (A_Inv sho sha shb v_o v_a v_b o a amin amax b bmin bmax 4);\n[ unfold nm_overlap_array_sep_3' ; entailer!| |\n  rewrite Htkdp; forward; unfold nm_overlap_array_sep_3' ; entailer!].\nall: unfold nm_overlap_array_sep_3' ; simpl ; Intros.\nall: specialize Haux1 with i ; destruct (Haux1 H7) as [aux1 HHaux1].\nall: specialize Haux2 with i ; destruct (Haux2 H7) as [aux2 HHaux2].\nall: specialize Haux3 with i ; destruct (Haux3 H7) as [aux3 HHaux3].\nall: specialize Haux4 with i ; destruct (Haux4 H7) as [aux4 HHaux4].\nall: forward.\n3,4,5,6,9,10: rewrite -HHaux1.\n1,2,9,10: rewrite -HHaux3.\n1,3,5,7,9: entailer!.\nall: forward.\n7,8: rewrite -HHaux1.\n1,2,9,10: rewrite -HHaux2.\n5,6: rewrite -HHaux3.\n7,8: rewrite -HHaux4.\n1,3,5,7,9: entailer!.\nall: forward.\nall: entailer!.\nall: rewrite map_map in HHaux1.\nall: rewrite map_map in HHaux2.\nall: rewrite (Znth_map 0) in HHaux1; [ | omega ].\nall: rewrite (Znth_map 0) in HHaux2; [ | omega ].\nall: rewrite Znth_tkdp in HHaux3 ; [ | omega].\nall: rewrite Znth_tkdp in HHaux4 ; [ | omega].\nall: rewrite map_map in HHaux4.\nall: rewrite map_map in HHaux3.\nall: try (rewrite (Znth_map 0) in HHaux3; [ | omega ]).\nall: try (rewrite (Znth_map 0) in HHaux4; [ | omega ]).\n1,3,5,7,9: inversion HHaux1.\n1,2,3,4,5: inversion HHaux2.\n1,2,3,4,5: inversion HHaux3.\n1,2,3,4,5: inversion HHaux4.\nall: try assert(-2^62 < (Znth i a 0) < 2 ^ 62) by (solve_bounds_by_values_ H).\nall: try assert(-2^62 < (Znth i b 0) < 2 ^ 62) by (solve_bounds_by_values_ H0).\nall: try assert((-2^62) + (-2^62) <= Znth i a 0 + Znth i b 0 <= 2^62 + 2^62) by omega.\nall: try assert((-2^62) + (-2^62) <= Znth i a 0 + Znth i a 0 <= 2^62 + 2^62) by omega.\nall: try assert((-2^62) + (-2^62) <= Znth i b 0 + Znth i b 0 <= 2^62 + 2^62) by omega.\n1,2,3,4,5: rewrite ?Int64.signed_repr ; solve_bounds_by_values.\nall: unfold nm_overlap_array_sep_3' ; simpl ; data_atify ; cancel ; replace_cancel.\nall: unfold A.\n  (* postcond |-- loop invariant *)\nall: clean_context_from_VST.\nall: rewrite /tkdp -?map_firstn -?map_skipn -?map_app in HHaux3.\nall: rewrite /tkdp -?map_firstn -?map_skipn -?map_app in HHaux4.\nall: inv HHaux1 ; inv HHaux2 ; inv HHaux3 ; inv HHaux4.\nall: rewrite add64_repr /nat_of_Z.\nall: rewrite ?Znth_nth; try omega.\nall: rewrite <- ZsubList_nth_Zlength ; try omega.\nall: rewrite /tkdp ?simple_S_i ; try omega.\nall: rewrite /A in HA, HmA.\nall: rewrite (upd_Znth_app_step_Zlength _ _ _ Vundef); try omega.\nall: f_equal ; rewrite map_map (Znth_map 0) ?Znth_nth ; try reflexivity.\nall: omega.\nQed.\n\n\nClose Scope Z.", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/proofs/vst/proofs/verif_A.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2195001664095534}}
{"text": "From fae_gtlc_mu.refinements.static_gradual Require Export compat_cast.defs.\nFrom fae_gtlc_mu.backtranslation Require Export general_def_lemmas.\nFrom fae_gtlc_mu.cast_calculus Require Export lang.\n\nSection compat_cast_tau_star.\n  Context `{!implG Σ,!specG Σ}.\n  Local Hint Resolve to_of_val : core.\n\n  Lemma back_cast_ar_tau_star:\n    ∀ (A : list (type * type)) (τ τG : type) (pτnG : Ground τ → False) (pτnStar : τ ≠ ⋆) (pτSτG : get_shape τ = Some τG) (pC1 : alternative_consistency A τ τG) (pC2 : alternative_consistency A τG ⋆),\n      back_cast_ar pC1 → back_cast_ar pC2 → back_cast_ar (factorUp_Ground A τ τG pτnG pτnStar pτSτG pC1 pC2).\n  Proof.\n    intros A τ τG pτnG pτnStar pτSτG pC1 pC2 IHpC1 IHpC2.\n    rewrite /back_cast_ar /𝓕c /𝓕. fold (𝓕 pC1). fold (𝓕 pC2).\n    iIntros (ei' K' v v' fs) \"(#Hfs & #Hvv' & #Hei' & Hv')\".\n    (* get small lemma about length fs *)\n    iDestruct \"Hfs\" as \"[% Hfs']\"; iAssert (rel_cast_functions A fs) with \"[Hfs']\" as \"Hfs\". iSplit; done. iClear \"Hfs'\".\n    (* step in wp *)\n    wp_head. asimpl.\n    fold (𝓕c pC1 fs). fold (𝓕c pC2 fs). do 2 rewrite 𝓕c_rewrite.\n    (* step in gradual side *)\n    iApply (wp_bind (ectx_language.fill $ [stlc_mu.lang.AppRCtx _])).\n    iApply (wp_wand with \"[-]\").\n    iMod (step_pure _ ei' K'\n                    (Cast v' τ ⋆)\n                    (Cast (Cast v' τ τG) τG ⋆) with \"[Hv']\") as \"Hv'\"; auto.\n    { eapply UpFactorization; auto. }\n    (* apply first IH *)\n    rewrite -𝓕c_rewrite.\n    iApply (IHpC1 ei' (CastCtx τG ⋆ :: K') with \"[Hv']\"); auto.\n    iIntros (w) \"blaa\".  iDestruct \"blaa\" as (w') \"[Hw' #Hww']\".\n    simpl.\n    rewrite -𝓕c_rewrite.\n    (* apply second IH *)\n    iApply (IHpC2 ei' K' with \"[Hw']\"); auto.\n  Qed.\n\nEnd compat_cast_tau_star.\n", "meta": {"author": "scaup", "repo": "fae-gtlc-mu", "sha": "6c6e64f0844327d55059b97c7aefab023385973e", "save_path": "github-repos/coq/scaup-fae-gtlc-mu", "path": "github-repos/coq/scaup-fae-gtlc-mu/fae-gtlc-mu-6c6e64f0844327d55059b97c7aefab023385973e/theories/refinements/static_gradual/compat_cast/tau_star.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.219465557616283}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import TableAux.Spec.\nRequire Import AbsAccessor.Spec.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef3.Spec.\nRequire Import TableAux.Specs.granule_fill_table.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition create_table (llt_gidx: Z) (idx: Z) (rtt_addr: Z) (rtt_gidx: Z) (rd_gidx: Z) (level: Z) (map_addr: Z) (adt: RData) :=\n    let gn_llt := (gs (share adt)) @ llt_gidx in\n    let gn_rtt := (gs (share adt)) @ rtt_gidx in\n    rely (g_tag (ginfo gn_llt) =? GRANULE_STATE_TABLE);\n    rely (gtype gn_llt =? GRANULE_STATE_TABLE);\n    rely (gtype gn_rtt =? GRANULE_STATE_DELEGATED);\n    rely prop_dec (glock gn_rtt = Some CPU_ID);\n    rely (tbl_level (gaux gn_rtt) =? 0);\n    let llt_pte := (g_data (gnorm gn_llt)) @ idx in\n    rely is_int64 llt_pte;\n    if __entry_is_table llt_pte then\n      Some (adt {log: EVT CPU_ID (REL llt_gidx gn_llt {glock: Some CPU_ID}) :: log adt}, VZ64 1)\n    else\n      let ipa_state := PTE_TO_IPA_STATE llt_pte in\n      if (ipa_state =? IPA_STATE_VACANT) || (ipa_state =? IPA_STATE_DESTROYED) then\n        let pte_val := IPA_STATE_TO_PTE ipa_state in\n        match fill_table (Z.to_nat PGTES_PER_TABLE) (g_data (gnorm gn_rtt)) 0 pte_val 0 with\n        | (tbl', _, _) =>\n          let llt' := (g_data (gnorm gn_llt)) # idx == (Z.lor rtt_addr PGTE_S2_TABLE) in\n          let grtt' := gn_rtt {ginfo: (ginfo gn_rtt) {g_tag: GRANULE_STATE_TABLE} {g_rd: rd_gidx} {g_refcount: (g_refcount (ginfo (gn_rtt))) + 1}}\n                              {gnorm : (gnorm gn_rtt) {g_data : tbl'}} {gaux: mkAuxillaryVars level idx llt_gidx} in\n          let gllt' := gn_llt {ginfo : (ginfo gn_llt) {g_refcount : g_refcount (ginfo gn_llt) + 1}}\n                             {gnorm: (gnorm gn_llt) {g_data: llt'}} in\n          Some (adt {log: EVT CPU_ID (REL llt_gidx gllt' {glock: Some CPU_ID}) :: log adt}\n                    {share : (share adt) {gs : ((gs (share adt)) # rtt_gidx == grtt') # llt_gidx == gllt'}},\n                VZ64 0)\n        end\n      else\n        if ipa_state =? IPA_STATE_ABSENT then\n          rely (level =? RTT_PAGE_LEVEL);\n          let pa := __entry_to_phys llt_pte 2 in\n          let pte_val := Z.lor (IPA_STATE_TO_PTE IPA_STATE_ABSENT) pa in\n          match fill_table (Z.to_nat PGTES_PER_TABLE) (g_data (gnorm gn_rtt)) 0 pte_val GRANULE_SIZE with\n          | (tbl', _, _) =>\n            let llt' := (g_data (gnorm gn_llt)) # idx == (Z.lor rtt_addr PGTE_S2_TABLE) in\n            let grtt' := gn_rtt {ginfo: (ginfo gn_rtt) {g_tag: GRANULE_STATE_TABLE} {g_rd: rd_gidx}\n                                                       {g_refcount: (g_refcount (ginfo (gn_rtt))) + PGTES_PER_TABLE + 1}}\n                                {gnorm : (gnorm gn_rtt) {g_data : tbl'}} {gaux: mkAuxillaryVars level idx llt_gidx} in\n            let gllt' := gn_llt {gnorm: (gnorm gn_llt) {g_data: llt'}} in\n            Some (adt {log: EVT CPU_ID (REL llt_gidx gllt' {glock: Some CPU_ID}) :: log adt}\n                      {share : (share adt) {gs : ((gs (share adt)) # rtt_gidx == grtt') # llt_gidx == gllt'}},\n                  VZ64 0)\n          end\n        else if ipa_state =? IPA_STATE_PRESENT then\n               rely (level =? RTT_PAGE_LEVEL);\n               let pa := __entry_to_phys llt_pte 2 in\n               let pte_val := Z.lor (Z.lor (IPA_STATE_TO_PTE IPA_STATE_PRESENT) pa) PGTE_S2_PAGE in\n               match fill_table (Z.to_nat PGTES_PER_TABLE) (g_data (gnorm gn_rtt)) 0 pte_val GRANULE_SIZE with\n               | (tbl', _, _) =>\n                 let llt' := (g_data (gnorm gn_llt)) # idx == (Z.lor rtt_addr PGTE_S2_TABLE) in\n                 let grtt' := gn_rtt {ginfo: (ginfo gn_rtt) {g_tag: GRANULE_STATE_TABLE} {g_rd: rd_gidx}\n                                                             {g_refcount: (g_refcount (ginfo (gn_rtt))) + PGTES_PER_TABLE + 1}}\n                                     {gnorm : (gnorm gn_rtt) {g_data : tbl'}} {gaux: mkAuxillaryVars level idx llt_gidx} in\n                 let gllt' := gn_llt {gnorm: (gnorm gn_llt) {g_data: llt'}} in\n                 let ipa_gidx := __addr_to_gidx map_addr in\n                 let tlbs' := fun cpu gidx => if gidx =? ipa_gidx then 0 else tlbs (share adt) cpu gidx in\n                 Some (adt {log: EVT CPU_ID (REL llt_gidx gllt' {glock: Some CPU_ID}) :: log adt}\n                           {share : (share adt) {gs : ((gs (share adt)) # rtt_gidx == grtt') # llt_gidx == gllt'} {tlbs: tlbs'}},\n                       VZ64 0)\n               end\n             else None.\n\n\n  Definition smc_rtt_create_spec (rtt_addr: Z64) (rd_addr: Z64) (map_addr: Z64) (level: Z64) (adt: RData) : option (RData * Z64) :=\n    match rtt_addr, rd_addr, map_addr, level with\n    | VZ64 rtt_addr, VZ64 rd_addr, VZ64 map_addr, VZ64 level =>\n      rely is_int64 rtt_addr; rely is_int64 rd_addr; rely is_int64 map_addr; rely is_int64 level;\n      if (level >=? 1) && (level <=? 3) && __addr_is_level_aligned map_addr 3 then\n        let rtt_gidx := __addr_to_gidx rtt_addr in\n        let rd_gidx := __addr_to_gidx rd_addr in\n        rely GRANULE_ALIGNED rtt_addr; rely GRANULE_ALIGNED rd_addr;\n       rely is_gidx rtt_gidx; rely is_gidx rd_gidx;\n        when adt == query_oracle adt;\n        let gn_rtt := (gs (share adt)) @ rtt_gidx in\n        let gn_rd := (gs (share adt)) @ rd_gidx in\n        rely prop_dec (glock gn_rtt = None);\n        rely prop_dec (glock gn_rd = None);\n        rely (g_tag (ginfo gn_rtt) =? GRANULE_STATE_DELEGATED);\n        rely (g_tag (ginfo gn_rd) =? GRANULE_STATE_RD);\n        rely (gtype gn_rd =? GRANULE_STATE_RD);\n        let adt := adt {log: EVT CPU_ID (ACQ rd_gidx) :: EVT CPU_ID (ACQ rtt_gidx) :: log adt} in\n        rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n        rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n        rely prop_dec ((buffer (priv adt)) @ SLOT_DELEGATED = None);\n        let root_gidx := (g_rtt (gnorm gn_rd)) in\n        rely is_gidx root_gidx;\n        let idx0 := __addr_to_idx map_addr 0 in\n        let idx1 := __addr_to_idx map_addr 1 in\n        let idx2 := __addr_to_idx map_addr 2 in\n        let idx3 := __addr_to_idx map_addr 3 in\n        let ret_idx := (if level =? 1 then idx0 else if level =? 2 then idx1 else if level =? 3 then idx2 else idx3) in\n        (* hold root lock *)\n        let groot := (gs (share adt)) @ root_gidx in\n        rely (tbl_level (gaux groot) =? 0);\n        rely prop_dec (glock groot = None);\n        if level =? 1 then\n          (* walk until root *)\n          let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 0) :: log adt} in\n          let adt :=  adt {priv: (priv adt) {wi_llt: root_gidx} {wi_index: idx0}} in\n          create_table root_gidx idx0 rtt_addr rtt_gidx rd_gidx 1 map_addr adt\n        else\n          (* walk deeper root *)\n          rely (level >? 1);\n          rely (g_tag (ginfo groot) =? GRANULE_STATE_TABLE);\n          rely (gtype groot =? GRANULE_STATE_TABLE);\n          let entry0 := (g_data (gnorm groot)) @ idx0 in\n          rely is_int64 entry0;\n          let phys0 := __entry_to_phys entry0 3 in\n          let lv1_gidx := __addr_to_gidx phys0 in\n          rely (__entry_is_table entry0) && (GRANULE_ALIGNED phys0) && (is_gidx lv1_gidx);\n          (* level 1 valid, hold level 1 lock *)\n          let glv1 := (gs (share adt)) @ lv1_gidx in\n          rely prop_dec (glock glv1 = None);\n          rely (tbl_level (gaux glv1) =? 1);\n          if level =? 2 then\n            (* walk until level 1 *)\n            let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 1) :: log adt} in\n            let adt :=  adt {priv: (priv adt) {wi_llt: lv1_gidx} {wi_index: idx1}} in\n            create_table lv1_gidx idx1 rtt_addr rtt_gidx rd_gidx 2 map_addr adt\n          else\n            (* walk deeper level 1 *)\n            rely (level >? 2);\n            rely (g_tag (ginfo glv1) =? GRANULE_STATE_TABLE);\n            rely (gtype glv1 =? GRANULE_STATE_TABLE);\n            let entry1 := (g_data (gnorm glv1)) @ idx1 in\n            rely is_int64 entry1;\n            let phys1 := __entry_to_phys entry1 3 in\n            let lv2_gidx := __addr_to_gidx phys1 in\n            rely (__entry_is_table entry1) && (GRANULE_ALIGNED phys1) && (is_gidx lv2_gidx);\n            (* level 2 valid, hold level 2 lock *)\n            let glv2 := (gs (share adt)) @ lv2_gidx in\n            rely (tbl_level (gaux glv2) =? 2);\n            rely prop_dec (glock glv2 = None);\n            if level =? 3 then\n              (* walk until level 2 *)\n              let adt := adt {log: EVT CPU_ID (RTT_WALK root_gidx map_addr 2) :: log adt} in\n              let adt :=  adt {priv: (priv adt) {wi_llt: lv2_gidx} {wi_index: idx2}} in\n              create_table lv2_gidx idx2 rtt_addr rtt_gidx rd_gidx 3 map_addr adt\n            else None\n      else Some (adt, VZ64 0)\n    end.\n\nEnd Spec.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataSMC/Specs/smc_rtt_create.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.2194202328827719}}
{"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\nRequire Import Tactics.\nRequire Import Sequence.\nRequire Import Relation.\nRequire Import Syntax.\nRequire Import Subst.\nRequire Import SimpSub.\nRequire Import Dynamic.\nRequire Import Promote.\nRequire Import Hygiene.\nRequire Import Rules.\nRequire Import DerivedRules.\nRequire Defs.\nRequire Import Equivalence.\nRequire Import Equivalences.\nRequire Import DefsEquiv.\nRequire Import Dots.\nRequire Import Morphism.\n\nRequire Import Defined.\nRequire Import SumLemmas.\nRequire Import PageType.\n\n\n\nDefinition natcase {object} m n p : term object :=\n  sumcase m (subst sh1 n) p.\n\n\nLemma def_nat : eq Defs.nat nattp.\nProof.\nauto.\nQed.\n\n\nLemma def_succ :\n  forall n,\n    equiv (app Defs.succ n) (nsucc n).\nProof.\nintros n.\nunfold Defs.succ.\nrewrite -> equiv_beta.\nsimpsub.\nunfold Defs.inr.\nsimpsub.\nrewrite -> equiv_beta.\nsimpsub.\napply equiv_refl.\nQed.\n\n\nLemma def_zero :\n  equiv Defs.zero nzero.\nProof.\nunfold Defs.zero.\nunfold Defs.inl.\nrewrite -> equiv_beta.\nsimpsub.\napply equiv_refl.\nQed.\n\n\nLemma def_natcase :\n  forall m n p,\n    equiv (app (app (app Defs.natcase m) n) (lam p)) (natcase m n p).\nProof.\nintros m n p.\nunfold Defs.natcase.\nrewrite -> equiv_beta.\nsimpsub.\nrewrite -> equiv_beta.\nsimpsub.\nrewrite -> equiv_beta.\nsimpsub.\nrewrite -> def_sumcase.\nrewrite -> equiv_beta.\nsimpsub.\nrewrite -> subst_var0_sh1.\napply equiv_refl.\nQed.\n\n\n\nLemma tr_positive_nattp_body :\n  forall G, tr G (deq triv triv (ispositive (sumtype unittp (var 0)))).\nProof.\nintros G.\napply (tr_positive_algorithm _ _ nil nil).\n  {\n  unfold sumtype.\n  apply hpositive_sigma.\n    {\n    replace booltp with (@subst obj (under 0 sh1) booltp) by (simpsub; auto).\n    apply hpositive_const.\n    }\n  replace (var 0) with (@subst obj (under 1 sh1) (var 0)) by (simpsub; auto).\n  apply hpositive_bite.\n    {\n    simpsub.\n    replace unittp with (@subst obj (under 1 sh1) unittp) by (simpsub; auto).\n    apply hpositive_const.\n    }\n\n    {\n    simpsub.\n    cbn.\n    apply hpositive_var.\n    }\n  }\n\n  {\n  intros x H.\n  destruct H.\n  }\n\n  {\n  intros x H.\n  destruct H.\n  }\nQed.\n\n\nLemma tr_nattp_formation :\n  forall G, tr G (deqtype nattp nattp).\nProof.\nintros G.\nunfold nattp.\napply tr_mu_formation; auto using tr_positive_nattp_body.\napply tr_sumtype_formation.\n  {\n  apply tr_unittp_istype.\n  }\n\n  {\n  apply tr_hyp_tp.\n  apply index_0.\n  }\nQed.\n\n\nLemma tr_nzero_nattp :\n  forall G, tr G (deq nzero nzero nattp).\nProof.\nintros G.\nunfold nzero, nattp.\neapply tr_subtype_elim.\n  {\n  apply tr_mu_roll.\n    {\n    apply tr_sumtype_formation.\n      {\n      apply tr_unittp_istype.\n      }\n    \n      {\n      apply tr_hyp_tp.\n      apply index_0.\n      }\n    }\n\n    {\n    apply tr_positive_nattp_body.\n    }\n  }\nsimpsub.\napply tr_sumtype_intro1.\n  {\n  apply tr_unittp_intro.\n  }\n\n  {\n  apply tr_nattp_formation.\n  }\nQed.\n\n\nLemma tr_nsucc_nattp :\n  forall G m n,\n    tr G (deq m n nattp)\n    -> tr G (deq (nsucc m) (nsucc n) nattp).\nProof.\nintros G m n Hmn.\napply (tr_subtype_elim _ (sumtype unittp nattp)).\n  {\n  replace (@sumtype obj unittp nattp) with (@subst1 obj nattp (sumtype unittp (var 0))) by (simpsub; auto).\n  apply tr_mu_roll.\n    {\n    apply tr_sumtype_formation.\n      {\n      apply tr_unittp_istype.\n      }\n\n      {\n      eapply tr_hyp_tp; eauto using index_0.\n      }\n    }\n\n    {\n    apply tr_positive_nattp_body.\n    }\n  }\n\n  {\n  unfold nsucc.\n  apply tr_sumtype_intro2; auto.\n  apply tr_unittp_istype.\n  }\nQed.\n\n\nLemma tr_nattp_formation_univ :\n  forall G, tr G (deq nattp nattp (univ nzero)).\nProof.\nintros G.\nunfold nattp.\napply tr_mu_formation_univ.\n  {\n  unfold pagetp.\n  apply tr_nzero_nattp.\n  }\n\n  {\n  simpsub.\n  apply tr_sumtype_formation_univ.\n    {\n    apply tr_unittp_formation_univ.\n    }\n  \n    {\n    eapply hypothesis; eauto using index_0.\n    }\n  }\n\n  {\n  apply tr_positive_nattp_body.\n  }\n\n  {\n  apply tr_positive_nattp_body.\n  }\nQed.\n\n\nLemma tr_nattp_eta_hyp_triv :\n  forall G1 G2 c,\n    tr (substctx (dot nzero id) G2 ++ G1) \n      (deq triv triv (subst (under (length G2) (dot nzero id)) c))\n    -> tr (substctx (dot (nsucc (var 0)) sh1) G2 ++ hyp_tm nattp :: G1) \n         (deq triv triv (subst (under (length G2) (dot (nsucc (var 0)) sh1)) c))\n    -> tr (G2 ++ hyp_tm nattp :: G1) (deq triv triv c).\nProof.\nintros G1 G2 c Hz Hs.\napply (tr_subtype_convert_hyp _ _ _ (sumtype unittp nattp)).\n  {\n  simpsub.\n  apply (weakening _ [_] []).\n    {\n    simpsub.\n    auto.\n    }\n\n    {\n    cbn [length unlift].\n    simpsub.\n    auto.\n    }\n  cbn [length unlift].\n  simpsub.\n  cbn [List.app].\n  unfold nattp.\n  apply tr_mu_unroll.\n    {\n    apply tr_sumtype_formation.\n      {\n      apply tr_unittp_istype.\n      }\n    \n      {\n      apply tr_hyp_tp.\n      apply index_0.\n      }\n    }\n  \n    {\n    apply tr_positive_nattp_body.\n    }\n  }\n\n  {\n  simpsub.\n  apply (weakening _ [_] []).\n    {\n    simpsub.\n    auto.\n    }\n\n    {\n    cbn [length unlift].\n    simpsub.\n    auto.\n    }\n  cbn [length unlift].\n  simpsub.\n  cbn [List.app].\n  unfold nattp.\n  replace (sumtype unittp (mu (sumtype unittp (var 0)))) with (@subst1 obj (mu (sumtype unittp (var 0))) (sumtype unittp (var 0))) by (simpsub; auto).\n  apply tr_mu_roll.\n    {\n    apply tr_sumtype_formation.\n      {\n      apply tr_unittp_istype.\n      }\n    \n      {\n      apply tr_hyp_tp.\n      apply index_0.\n      }\n    }\n  \n    {\n    apply tr_positive_nattp_body.\n    }\n  }\napply tr_sumtype_eta_hyp_triv; auto.\napply tr_unittp_eta_hyp_triv.\nrewrite <- substctx_compose.\nrewrite -> length_substctx.\nrewrite <- subst_compose.\nrewrite <- compose_under.\nsimpsub.\nauto.\nQed.\n\n\nLemma tr_nsucc_nattp_invert :\n  forall G m n,\n    tr G (deq (nsucc m) (nsucc n) nattp)\n    -> tr G (deq m n nattp).\nProof.\nintros G m n Hsucc.\ncut (tr G (deq (app (lam (sumcase (var 0) nzero (var 0))) (nsucc m)) (app (lam (sumcase (var 0) nzero (var 0))) (nsucc n)) nattp)).\n  {\n  intro H.\n  rewrite -> !equiv_beta in H.\n  simpsubin H.\n  unfold nsucc in H.\n  rewrite -> !sumcase_right in H.\n  simpsubin H.\n  exact H.\n  }\napply (tr_pi_elim' _ nattp nattp); auto.\napply tr_pi_intro; auto using tr_nattp_formation.\napply tr_equal_elim.\neapply (tr_nattp_eta_hyp_triv _ []).\n  {\n  cbn [length].\n  simpsub.\n  cbn [List.app].\n  apply tr_equal_intro.\n  unfold nzero at 1 3.\n  rewrite -> sumcase_left.\n  simpsub.\n  apply tr_nzero_nattp.\n  }\n\n  {\n  cbn [length].\n  simpsub.\n  cbn [List.app].\n  apply tr_equal_intro.\n  unfold nsucc.\n  rewrite -> sumcase_right.\n  simpsub.\n  eapply hypothesis; eauto using index_0.\n  }\nQed.\n\n\nLemma nat_case :\n  forall G b m c,\n    tr G (deq triv triv (subst1 nzero b))\n    -> tr (hyp_tm nattp :: G) (deq triv triv (subst (dot (nsucc (var 0)) (sh 1)) b))\n    -> tr G (deq m m nattp)\n    -> c = subst1 m b\n    -> tr G (deq triv triv c).\nProof.\nintros G b m c Hzero Hsucc Hm ->.\napply (sum_case _ unittp nattp b m).\n  {\n  replace (@triv obj) with (@subst obj (under 0 sh1) triv) by (simpsub; auto).\n  apply (tr_unittp_eta_hyp _ []).\n  simpsub.\n  cbn [List.app].\n  exact Hzero.\n  }\n\n  {\n  exact Hsucc.\n  }\n\n  {\n  apply (tr_subtype_elim _ nattp); auto.\n  apply tr_mu_unroll.\n    {\n    apply tr_sumtype_formation.\n      {\n      apply tr_unittp_istype.\n      }\n\n      {\n      eapply tr_hyp_tp; eauto using index_0.\n      }\n    }\n\n    {\n    apply tr_positive_nattp_body.\n    }\n  }\n\n  {\n  reflexivity.\n  }\nQed.\n\n\nLemma nat_induction :\n  forall G b m c,\n    tr G (deq triv triv (subst1 nzero b))\n    -> tr\n         (hyp_tm (pi (var 2) (subst (under 1 (sh 3)) b)) ::\n          hyp_tm (subtype (var 1) nattp) ::\n          hyp_tm (var 0) ::\n          hyp_tp :: \n          G)\n         (deq triv triv (subst (dot (nsucc (var 2)) (sh 4)) b))\n    -> tr G (deq m m nattp)\n    -> c = subst1 m b\n    -> tr G (deq triv triv c).\nProof.\nintros G b m c Hzero Hsucc Hm ->.\napply (tr_mu_ind _ (sumtype unittp (var 0))).\n  {\n  apply tr_sumtype_formation.\n    {\n    apply tr_unittp_istype.\n    }\n  \n    {\n    apply tr_hyp_tp.\n    apply index_0.\n    }\n  }\n\n  {\n  apply tr_positive_nattp_body.\n  }\n\n2:{\n  exact Hm.\n  }\nreplace (mu (subst (under 1 (sh 2)) (sumtype unittp (var 0)))) with (@nattp obj) by (simpsub; auto).\napply (tr_sumtype_eta_hyp_triv _ [_; _]).\n  {\n  cbn [length].\n  simpsub.\n  cbn [length Nat.add List.app].\n  simpsub.\n  cbn [Nat.add].\n  replace triv with (@subst obj (under 2 sh1) triv) by (simpsub; auto).\n  apply (tr_unittp_eta_hyp _ [_; _]).\n  cbn [length].\n  simpsub.\n  cbn [length Nat.add List.app].\n  simpsub.\n  cbn [Nat.add].\n  fold (@nzero obj).\n  apply (weakening _ [_; _; _] []).\n    {\n    cbn [unlift length].\n    simpsub.\n    auto.\n    }\n\n    {\n    cbn [unlift length].\n    simpsub.\n    auto.\n    }\n  cbn [unlift length].\n  simpsub.\n  cbn [List.app].\n  exact Hzero.\n  }\n\n  {\n  cbn [length].\n  simpsub.\n  cbn [length Nat.add List.app].\n  simpsub.\n  cbn [Nat.add].\n  exact Hsucc.\n  }\nQed.\n\n\nLemma tr_leqtp_type :\n  forall G, tr G (deq leqtp leqtp (pi nattp (pi nattp (univ nzero)))).\nProof.\nintros G.\neapply tr_pi_of_ext.\n  {\n  apply tr_nattp_formation.\n  }\n\n2:{\n  unfold leqtp.\n  rewrite -> theta_equiv.\n  apply steps_equiv.\n  eapply star_step.\n    {\n    apply step_app2.\n    }\n  simpsub.\n  apply star_refl.\n  }\nsimpsub.\napply tr_equal_elim.\nmatch goal with\n| |- tr _ (deq _ _ ?X) => eapply (nat_induction _ (subst (dot (var 0) (sh 2)) X))\nend.\n3:{\n  eapply (hypothesis _ 0); eauto using index_0.\n  }\n\n  {\n  simpsub.\n  apply tr_equal_intro.\n  eapply tr_pi_of_ext.\n    {\n    apply tr_nattp_formation.\n    }\n  \n  2:{\n    unfold leqtp.\n    apply steps_equiv.\n    eapply star_trans.\n      {\n      apply (star_map' _ _ (fun z => app z _)); eauto using step_app1.\n      cbn [Nat.add].\n      apply theta_fix.\n      }\n    eapply star_trans.\n      {\n      apply (star_map' _ _ (fun z => app z _)); eauto using step_app1.\n      apply star_one.\n      apply step_app2.\n      }\n    simpsub.\n    cbn [Nat.add].\n    eapply star_step.\n      {\n      apply step_app2.\n      }\n    simpsub.\n    apply star_refl.\n    }\n  simpsub.\n  rewrite -> unroll_leqtp.\n  unfold nzero at 1 2.\n  rewrite -> sumcase_left.\n  simpsub.\n  apply tr_unittp_formation_univ.\n  }\n\n  {\n  simpsub.\n  cbn [Nat.add].\n  apply tr_equal_intro.\n  eapply tr_pi_of_ext.\n    {\n    apply tr_nattp_formation.\n    }\n  \n  2:{\n    unfold leqtp.\n    apply steps_equiv.\n    eapply star_trans.\n      {\n      apply (star_map' _ _ (fun z => app z _)); eauto using step_app1.\n      cbn [Nat.add].\n      apply theta_fix.\n      }\n    eapply star_trans.\n      {\n      apply (star_map' _ _ (fun z => app z _)); eauto using step_app1.\n      apply star_one.\n      apply step_app2.\n      }\n    simpsub.\n    cbn [Nat.add].\n    eapply star_step.\n      {\n      apply step_app2.\n      }\n    simpsub.\n    apply star_refl.\n    }\n  simpsub.\n  cbn [Nat.add].\n  setoid_rewrite -> unroll_leqtp.\n  unfold nsucc.\n  rewrite -> sumcase_right.\n  simpsub.\n  cbn [Nat.add].\n  apply tr_equal_elim.\n  apply (tr_nattp_eta_hyp_triv _ []).\n    {\n    cbn [length].\n    simpsub.\n    cbn [Nat.add length List.app].\n    apply tr_equal_intro.\n    unfold nzero at 2 3.\n    rewrite -> sumcase_left.\n    simpsub.\n    apply tr_voidtp_formation_univ.\n    }\n\n    {\n    cbn [length].\n    simpsub.\n    cbn [Nat.add List.app].\n    unfold nsucc.\n    rewrite -> sumcase_right.\n    simpsub.\n    cbn [Nat.add].\n    apply tr_equal_intro.\n    eapply tr_pi_elim'.\n    2:{\n      eapply hypothesis; eauto using index_0.\n      }\n\n      {\n      apply tr_equal_elim.\n      apply (tr_equal_eta2 _#4 (app (var 1) (var 3)) (app (var 1) (var 3))).\n      eapply tr_pi_elim'.\n        {\n        eapply hypothesis; eauto using index_0, index_S.\n        simpsub.\n        cbn [Nat.add].\n        eauto.\n        }\n      \n        {\n        eapply hypothesis; eauto using index_0, index_S.\n        }\n\n        {\n        simpsub.\n        eauto.\n        }\n      }\n    \n      {\n      simpsub.\n      eauto.\n      }\n    }\n  }\n\n  {\n  simpsub.\n  eauto.\n  }\nQed.\n\n\nLemma tr_leqtp_formation_univ :\n  forall G m m' n n',\n    tr G (deq m m' nattp)\n    -> tr G (deq n n' nattp)\n    -> tr G (deq (app (app leqtp m) n) (app (app leqtp m') n') (univ nzero)).\nProof.\nintros G m m' n n' Hm Hn.\neapply tr_pi_elim'.\n  {\n  eapply tr_pi_elim'.\n    {\n    apply tr_leqtp_type.\n    }\n\n    {\n    auto.\n    }\n\n    {\n    simpsub; eauto.\n    }\n  }\n\n  {\n  auto.\n  }\n\n  {\n  simpsub; eauto.\n  }\nQed.\n\n\nLemma tr_leqtp_formation :\n  forall G m m' n n',\n    tr G (deq m m' nattp)\n    -> tr G (deq n n' nattp)\n    -> tr G (deqtype (app (app leqtp m) n) (app (app leqtp m') n')).\nProof.\nintros G m m' n n' Hm Hn.\napply (tr_formation_weaken _ nzero).\napply tr_leqtp_formation_univ; auto.\nQed.\n\n\nLemma tr_leqtp_eta2 :\n  forall G m n p q,\n    tr G (deq m m nattp)\n    -> tr G (deq n n nattp)\n    -> tr G (deq p q (app (app leqtp m) n))\n    -> tr G (deq triv triv (app (app leqtp m) n)).\nProof.\nintros G m n p q Hm Hn Hleqtp.\napply tr_equal_elim.\napply (tr_equal_eta2 _#4 \n         (app (app (lam (lam triv)) n) p)\n         (app (app (lam (lam triv)) n) q)).\napply (tr_pi_elim2' _\n         nattp \n         (app (app leqtp (subst sh1 m)) (var 0))\n         (equal (app (app leqtp (subst (sh 2) m)) (var 1)) triv triv)); auto.\n2:{\n  simpsub.\n  unfold subst1.\n  auto.\n  }\n\n2:{\n  simpsub.\n  reflexivity.\n  }\napply tr_equal_elim.\napply (nat_induction _\n         (equal\n            (pi nattp \n               (pi (app (app leqtp (var 1)) (var 0))\n                  (equal (app (app leqtp (var 2)) (var 1)) triv triv)))\n            (lam (lam triv))\n            (lam (lam triv)))\n         m); auto.\n3:{\n  simpsub.\n  reflexivity.\n  }\n\n(* 0 *)\n{\nsimpsub.\ncbn [Nat.add].\napply tr_equal_intro.\napply tr_pi_intro.\n  {\n  apply tr_nattp_formation.\n  }\napply tr_pi_intro.\n  {\n  apply tr_leqtp_formation.\n    {\n    apply tr_nzero_nattp.\n    }\n\n    {\n    eapply hypothesis; eauto using index_0.\n    }\n  }\napply tr_equal_intro.\nsetoid_rewrite -> unroll_leqtp at 2.\nunfold nzero at 2.\nrewrite -> sumcase_left.\nsimpsub.\napply tr_unittp_intro.\n}\n\n(* S *)\n{\nsimpsub.\ncbn [Nat.add].\napply tr_equal_intro.\napply tr_pi_intro.\n  {\n  apply tr_nattp_formation.\n  }\napply tr_pi_intro.\n  {\n  apply tr_leqtp_formation.\n    {\n    apply tr_nsucc_nattp.\n    apply (tr_subtype_elim _ (var 4)).\n      {\n      apply (tr_subtype_eta2 _ _ _ (var 2) (var 2)).\n      eapply hypothesis; eauto using index_S, index_0.\n      }\n    eapply hypothesis; eauto using index_S, index_0.\n    }\n  \n    {\n    eapply hypothesis; eauto using index_0.\n    }\n  }\napply tr_equal_intro.\nsetoid_rewrite -> unroll_leqtp at 4.\nunfold nsucc at 2.\nrewrite -> sumcase_right.\nsimpsub.\ncbn [Nat.add].\napply (tr_nattp_eta_hyp_triv _ [_]).\n  {\n  cbn [length].\n  simpsub.\n  cbn [Nat.add List.app].\n  unfold subst1.\n  apply (tr_voidtp_elim _ (var 0) (var 0)).\n  rewrite -> unroll_leqtp.\n  unfold nsucc at 1.\n  rewrite -> sumcase_right.\n  simpsub.\n  unfold nzero at 1.\n  rewrite -> sumcase_left.\n  simpsub.\n  eapply hypothesis; eauto using index_0.\n  }\n\n  {\n  cbn [length].\n  simpsub.\n  cbn [Nat.add List.app].\n  unfold nsucc.\n  rewrite -> unroll_leqtp at 1.\n  rewrite -> !sumcase_right.\n  simpsub.\n  cbn [Nat.add].\n  rewrite -> sumcase_right.\n  simpsub.\n  cbn [Nat.add].\n  unfold subst1.\n  apply tr_equal_elim.\n  apply (tr_equal_eta2 _#4 \n           (app (app (lam (lam triv)) (var 1)) (var 0)) \n           (app (app (lam (lam triv)) (var 1)) (var 0))).\n  apply (tr_pi_elim2' _ nattp (app (app leqtp (var 5)) (var 0))\n           (equal (app (app leqtp (var 6)) (var 1)) triv triv)).\n    {\n    apply tr_equal_elim.\n    apply (tr_equal_eta2 _#4\n             (app (var 2) (var 4))\n             (app (var 2) (var 4))).\n    eapply (tr_pi_elim' _ (var 5) _).\n      {\n      eapply hypothesis; eauto using index_S, index_0.\n      simpsub.\n      cbn [Nat.add].\n      reflexivity.\n      }\n\n      {\n      eapply hypothesis; eauto using index_S, index_0.\n      }\n      \n      {\n      simpsub.\n      cbn [Nat.add].\n      reflexivity.\n      }\n    }\n\n    {\n    eapply hypothesis; eauto using index_S, index_0.\n    }\n\n    {\n    eapply hypothesis; eauto using index_0.\n    }\n    \n    {\n    simpsub.\n    reflexivity.\n    }\n  }\n}\nQed.\n\n\nLemma equiv_lttp :\n  forall i j, @equiv obj (app (app lttp i) j) (app (app leqtp (nsucc i)) j).\nProof.\nintros i j.\nunfold lttp.\napply equiv_app; auto using equiv_refl.\napply steps_equiv.\neapply star_step.\n  {\n  apply step_app2.\n  }\nsimpsub.\nunfold subst1.\napply star_refl.  \nQed.\n\n\nLemma tr_leqtp_refl :\n  forall G n,\n    tr G (deq n n nattp)\n    -> tr G (deq triv triv (app (app leqtp n) n)).\nProof.\nintros G n H.\napply (nat_induction _ (app (app leqtp (var 0)) (var 0)) n); auto.\n3:{\n  simpsub.\n  unfold subst1.\n  reflexivity.\n  }\n\n  {\n  simpsub.\n  unfold subst1.\n  rewrite -> unroll_leqtp.\n  unfold nzero.\n  rewrite -> sumcase_left.\n  simpsub.\n  apply tr_unittp_intro.\n  }\n\n  {\n  simpsub.\n  unfold nsucc.\n  setoid_rewrite -> unroll_leqtp at 2.\n  rewrite -> sumcase_right.\n  simpsub.\n  rewrite -> sumcase_right.\n  simpsub.\n  cbn [Nat.add].\n  apply (tr_leqtp_eta2 _#3 (app (var 0) (var 2)) (app (var 0) (var 2))).\n    {\n    apply (tr_subtype_elim _ (var 3)).\n      {\n      apply (tr_subtype_eta2 _#3 (var 1) (var 1)).\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n\n      {\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n    }\n\n    {\n    apply (tr_subtype_elim _ (var 3)).\n      {\n      apply (tr_subtype_eta2 _#3 (var 1) (var 1)).\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n\n      {\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n    }\n  eapply tr_pi_elim'.\n    {\n    eapply hypothesis; eauto using index_0.\n    simpsub.\n    cbn [Nat.add].\n    reflexivity.\n    }\n    \n    {\n    eapply hypothesis; eauto using index_0, index_S.\n    }\n\n    {\n    simpsub.\n    unfold subst1.\n    reflexivity.\n    }\n  }\nQed.\n\n\nLemma tr_leqtp_succ :\n  forall G n,\n    tr G (deq n n nattp)\n    -> tr G (deq triv triv (app (app leqtp n) (nsucc n))).\nProof.\nintros G n Hn.\napply (nat_induction _ (app (app leqtp (var 0)) (nsucc (var 0))) n); auto.\n3:{\n  simpsub.\n  unfold subst1.\n  reflexivity.\n  }\n\n  {\n  simpsub.\n  unfold subst1.\n  rewrite -> unroll_leqtp.\n  unfold nzero.\n  rewrite -> sumcase_left.\n  simpsub.\n  apply tr_unittp_intro.\n  }\n\n  {\n  simpsub.\n  unfold nsucc at 2 3.\n  setoid_rewrite -> unroll_leqtp at 2.\n  rewrite -> sumcase_right.\n  simpsub.\n  cbn [Nat.add].\n  rewrite -> sumcase_right.\n  fold (@nsucc obj (var 2)).\n  simpsub.\n  cbn [Nat.add].\n  apply (tr_leqtp_eta2 _#3 (app (var 0) (var 2)) (app (var 0) (var 2))).\n    {\n    apply (tr_subtype_elim _ (var 3)).\n      {\n      apply (tr_subtype_eta2 _#3 (var 1) (var 1)).\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n\n      {\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n    }\n\n    {\n    apply tr_nsucc_nattp.\n    apply (tr_subtype_elim _ (var 3)).\n      {\n      apply (tr_subtype_eta2 _#3 (var 1) (var 1)).\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n\n      {\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n    }\n  eapply tr_pi_elim'.\n    {\n    eapply hypothesis; eauto using index_0.\n    simpsub.\n    cbn [Nat.add].\n    reflexivity.\n    }\n    \n    {\n    eapply hypothesis; eauto using index_0, index_S.\n    }\n\n    {\n    simpsub.\n    unfold subst1.\n    reflexivity.\n    }\n  }\nQed.\n\n\nLemma tr_leqtp_trans :\n  forall G m n p,\n    tr G (deq m m nattp)\n    -> tr G (deq n n nattp)\n    -> tr G (deq p p nattp)\n    -> tr G (deq triv triv (app (app leqtp m) n))\n    -> tr G (deq triv triv (app (app leqtp n) p))\n    -> tr G (deq triv triv (app (app leqtp m) p)).\nProof.\nintros G m n p Hm Hn Hp Hmn Hnp.\napply (tr_leqtp_eta2 _ _ _ (app (app (app (app (lam (lam (lam (lam triv)))) n) p) triv) triv) (app (app (app (app (lam (lam (lam (lam triv)))) n) p) triv) triv)); auto.\napply (tr_pi_elim4' _ nattp nattp (app (app leqtp (subst (sh 2) m)) (var 1)) (app (app leqtp (var 2)) (var 1)) (app (app leqtp (subst (sh 4) m)) (var 2))); auto.\n4:{\n  simpsub.\n  auto.\n  }\n\n2:{\n  simpsub.\n  auto.\n  }\n\n2:{\n  simpsub.\n  auto.\n  }\napply tr_equal_elim.\napply (nat_induction _ (equal (pi nattp (pi nattp (pi (app (app leqtp (var 2)) (var 1)) (pi (app (app leqtp (var 2)) (var 1)) (app (app leqtp (var 4)) (var 2)))))) (lam (lam (lam (lam triv)))) (lam (lam (lam (lam triv))))) m); auto.\n3:{\n  simpsub.\n  cbn [Nat.add].\n  auto.\n  }\n\n  {\n  simpsub.\n  cbn [Nat.add].\n  apply tr_equal_intro.\n  apply tr_pi_intro; auto using tr_nattp_formation.\n  apply tr_pi_intro; auto using tr_nattp_formation.\n  apply tr_pi_intro.\n    {\n    apply tr_leqtp_formation.\n      {\n      apply tr_nzero_nattp.\n      }\n\n      {\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n    }\n  apply tr_pi_intro.\n    {\n    apply tr_leqtp_formation.\n      {\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n\n      {\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n    }\n  setoid_rewrite -> unroll_leqtp at 3.\n  unfold nzero at 2.\n  rewrite -> sumcase_left.\n  simpsub.\n  apply tr_unittp_intro.\n  }\n\n  {\n  simpsub.\n  cbn [Nat.add].\n  apply tr_equal_intro.\n  apply tr_pi_intro; auto using tr_nattp_formation.\n  apply tr_pi_intro; auto using tr_nattp_formation.\n  apply tr_pi_intro.\n    {\n    apply tr_leqtp_formation.\n      {\n      apply tr_nsucc_nattp.\n      apply (tr_subtype_elim _ (var 5)).\n        {\n        apply (tr_subtype_eta2 _#3 (var 3) (var 3)).\n        eapply hypothesis; eauto using index_0, index_S.\n        }\n\n        {\n        eapply hypothesis; eauto using index_0, index_S.\n        }\n      }\n\n      {\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n    }\n  apply tr_pi_intro.\n    {\n    apply tr_leqtp_formation.\n      {\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n\n      {\n      eapply hypothesis; eauto using index_0, index_S.\n      }\n    }\n  setoid_rewrite -> unroll_leqtp at 6.\n  unfold nsucc at 2.\n  rewrite -> sumcase_right.\n  simpsub.\n  cbn [Nat.add].\n  eapply (tr_nattp_eta_hyp_triv _ [_; _; _]).\n    {\n    simpsub.\n    cbn [length].\n    simpsub.\n    cbn [Nat.add List.app].\n    setoid_rewrite -> unroll_leqtp at 2.\n    unfold nsucc at 1.\n    rewrite -> sumcase_right.\n    simpsub.\n    unfold nzero at 2.\n    rewrite -> sumcase_left.\n    simpsub.\n    apply (tr_voidtp_elim _ (var 1) (var 1)).\n    eapply hypothesis; eauto using index_0, index_S.\n    }\n  cbn [length].\n  simpsub.\n  cbn [length].\n  simpsub.\n  cbn [Nat.add List.app].\n  setoid_rewrite -> unroll_leqtp at 2.\n  unfold nsucc at 2.\n  rewrite -> sumcase_right.\n  simpsub.\n  rewrite -> sumcase_right.\n  simpsub.\n  cbn [Nat.add].\n  eapply (tr_nattp_eta_hyp_triv _ [_; _]).\n    {\n    simpsub.\n    cbn [length].\n    simpsub.\n    cbn [Nat.add List.app].\n    setoid_rewrite -> unroll_leqtp at 1.\n    unfold nsucc at 1.\n    rewrite -> sumcase_right.\n    simpsub.\n    unfold nzero at 1.\n    rewrite -> sumcase_left.\n    simpsub.\n    apply (tr_voidtp_elim _ (var 0) (var 0)).\n    eapply hypothesis; eauto using index_0.\n    }\n  cbn [length].\n  simpsub.\n  cbn [length].\n  simpsub.\n  cbn [Nat.add List.app].\n  setoid_rewrite -> unroll_leqtp at 1.\n  unfold nsucc.\n  rewrite -> sumcase_right.\n  simpsub.\n  rewrite -> sumcase_right.\n  simpsub.\n  cbn [Nat.add].\n  rewrite -> sumcase_right.\n  simpsub.\n  cbn [Nat.add].\n  apply (tr_leqtp_eta2 _#3 (app (app (app (app (lam (lam (lam (lam triv)))) (var 3)) (var 2)) (var 1)) (var 0)) (app (app (app (app (lam (lam (lam (lam triv)))) (var 3)) (var 2)) (var 1)) (var 0))).\n    {\n    apply (tr_subtype_elim _ (var 7)).\n      {\n      apply (tr_subtype_eta2 _#3 (var 5) (var 5)).\n      eapply hypothesis; eauto 7 using index_0, index_S.\n      }\n    eapply hypothesis; eauto 7 using index_0, index_S.\n    }\n  \n    {\n    eapply hypothesis; eauto using index_0, index_S.\n    }\n  eapply tr_pi_elim4'; eauto.\n    {\n    apply tr_equal_elim.\n    eapply (tr_equal_eta2 _#4 (app (var 4) (var 6)) (app (var 4) (var 6))).\n    eapply tr_pi_elim'; eauto.\n      {\n      eapply hypothesis; eauto using index_0, index_S.\n      simpsub.\n      cbn [Nat.add].\n      reflexivity.\n      }\n\n      {\n      eapply hypothesis; eauto 7 using index_0, index_S.\n      }\n\n      {\n      simpsub.\n      cbn [Nat.add].\n      reflexivity.\n      }\n    }\n\n    {\n    eapply hypothesis; eauto using index_0, index_S.\n    }\n\n    {\n    eapply hypothesis; eauto using index_0, index_S.\n    }\n\n    {\n    eapply hypothesis; eauto using index_0, index_S.\n    }\n\n    {\n    eapply hypothesis; eauto using index_0, index_S.\n    }\n\n    {\n    simpsub.\n    auto.\n    }\n  }\nQed.\n\n\nDefinition natmax {object} m n : term object :=\n  app (app (app theta\n              (lam (lam (lam (natcase (var 1) \n                                (var 0)\n                                (natcase (var 1)\n                                   (var 2)\n                                   (nsucc\n                                      (app (app (var 4) (var 1)) (var 0)))))))))\n         m)\n    n.\n\n\nLemma subst_natmax :\n  forall object s m n,\n    @subst object s (natmax m n) = natmax (subst s m) (subst s n).\nProof.\nintros object s m n.\nunfold natmax.\nsimpsub.\nreflexivity.\nQed.\n\n\nLemma subst_natcase :\n  forall object s m n p,\n    @subst object s (natcase m n p) = natcase (subst s m) (subst s n) (subst (under 1 s) p).\nProof.\nintros object s m n p.\nunfold natcase.\nsimpsub.\nreflexivity.\nQed.\n\n\nHint Rewrite subst_natcase subst_natmax : subst.\n\n\nLemma natcase_zero :\n  forall n p,\n    @equiv obj (natcase nzero n p) n.\nProof.\nintros n p.\nunfold natcase, nzero.\nrewrite -> sumcase_left.\nsimpsub.\napply equiv_refl.\nQed.\n\n\nLemma natcase_succ :\n  forall m n p,\n    @equiv obj (natcase (nsucc m) n p) (subst1 m p).\nProof.\nintros m n p.\nunfold natcase, nsucc.\nrewrite -> sumcase_right.\napply equiv_refl.\nQed.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/NatLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.2194202328827719}}
{"text": "From iris.algebra Require Import agree auth excl gmap dfrac max_prefix_list.\nFrom iris.algebra Require Import updates local_updates.\nFrom iris.algebra.lib Require Import mono_list.\nFrom iris.base_logic Require Import invariants.\nFrom iris.bi.lib Require Import fractional.\nFrom iris.proofmode Require Import tactics.\nFrom aneris.lib Require Import gen_heap_light.\nFrom aneris.aneris_lang Require Import lang resources inject tactics proofmode.\nFrom aneris.aneris_lang.lib Require Import\n     list_proof monitor_proof lock_proof map_proof assert_proof.\nFrom aneris.examples.reliable_communication.lib.repdb\n     Require Export log_code.\nFrom aneris.examples.reliable_communication.lib.repdb.resources\n     Require Import log_resources.\n\nImport lock_proof.\n\nSection Log.\n  Context `{!anerisG Mdl Σ, !lockG Σ}.\n  Context {Aty : Type}.\n  Notation A := (leibnizO Aty).\n  Context `{inG Σ (mono_listUR A)}.\n  Context `[!Inject A val].\n\n  Lemma wp_log_create ip :\n    {{{ True }}}\n      log_create #() @[ip]\n    {{{ logL logV, RET #logL; logL ↦[ip] logV ∗ ⌜is_log [] logV⌝}}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\".\n    wp_rec. wp_pures.\n    wp_alloc l as \"Hl\".\n    iApply \"HΦ\". iFrame. iPureIntro.\n    by eexists.\n    Qed.\n\n  Lemma wp_log_add_entry ip logL logV logM (x : A) :\n    {{{ ⌜is_log logM logV⌝ ∗ logL ↦[ip] logV }}}\n      log_add_entry #logL $x @[ip]\n    {{{ logV', RET #();\n        ⌜is_log (logM ++ [x]) logV'⌝ ∗ logL ↦[ip] logV' }}}.\n  Proof.\n    iIntros (Φ) \"(%Hl & Hp) HΦ\".\n    destruct Hl as (lV & -> & Hlst).\n    wp_lam. wp_pures.\n    wp_load. wp_pures.\n    wp_apply (wp_list_cons _ []); first done.\n    iIntros (v) \"%Hl2\".\n    wp_apply wp_list_append; first done.\n    iIntros (v') \"%Hl'\".\n    wp_pures.\n    wp_store.\n    iApply \"HΦ\".\n    iFrame.\n    iPureIntro.\n    eexists; rewrite app_length /=; split; last done.\n    do 3 f_equal; lia.\n  Qed.\n\n\n  Lemma wp_log_next ip logL logV logM q :\n    {{{ ⌜is_log logM logV⌝ ∗ logL ↦[ip]{q} logV }}}\n      log_next #logL @[ip]\n    {{{ n, RET #n;\n        ⌜n = List.length logM⌝ ∗ ⌜is_log (logM) logV⌝ ∗ logL ↦[ip]{q} logV}}}.\n  Proof.\n    iIntros (Φ) \"(%Hl & Hp) HΦ\".\n    destruct Hl as (lV & -> & Hlst).\n    wp_lam.\n    wp_load.\n    wp_pures.\n    iApply \"HΦ\".\n    iFrame.\n    iPureIntro.\n    split; by eexists.\n  Qed.\n\n  Lemma wp_log_length ip logL logV logM q :\n    {{{ ⌜is_log logM logV⌝ ∗ logL ↦[ip]{q} logV }}}\n      log_length #logL @[ip]\n    {{{ n, RET #n;\n        ⌜n = List.length logM⌝ ∗ ⌜is_log (logM) logV⌝ ∗ logL ↦[ip]{q} logV}}}.\n  Proof.\n    iIntros (Φ) \"(%Hl & Hp) HΦ\".\n    destruct Hl as (lV & -> & Hlst).\n    wp_lam.\n    wp_load.\n    wp_pures.\n    iApply \"HΦ\".\n    iFrame.\n    iPureIntro.\n    split; by eexists.\n  Qed.\n\nLemma wp_log_get ip logL logV logM i q :\n    {{{ ⌜i < List.length logM⌝ ∗\n        ⌜is_log logM logV⌝ ∗ logL ↦[ip]{q} logV }}}\n      log_get #logL #i @[ip]\n    {{{ x, RET (SOMEV $x);\n        ⌜List.nth_error logM i = Some x⌝ ∗\n        ⌜is_log (logM) logV⌝ ∗ logL ↦[ip]{q} logV}}}.\n  Proof.\n    iIntros (Φ) \"(%Hi & %Hl & Hp) HΦ\".\n    destruct Hl as (lV & -> & Hlst).\n    wp_lam.\n    wp_pures.\n    wp_load.\n    wp_pures.\n    wp_apply wp_list_nth_some; [eauto with lia|].\n    iIntros (v (x & -> & Hsome)).\n    iApply \"HΦ\".\n    iFrame.\n    iPureIntro.\n    split; eauto; last by eexists.\n  Qed.\n\n  Lemma wp_log_wait_until ip\n    γlog q logM (* created at the logical setup *)\n    monN monγ monV monR logL logV i (* created at the allocation of physical data *):\n    {{{ ⌜i ≤ List.length logM⌝ ∗ ⌜is_log logM logV⌝ ∗\n        is_monitor monN ip monγ monV (log_monitor_inv_def ip γlog q logL monR) ∗\n        locked monγ ∗ (monR logM) ∗ logL ↦[ip] logV ∗ own_log_auth γlog q logM }}}\n      log_wait_until #logL monV #i @[ip]\n    {{{ logV' logM', RET #();\n        ⌜i < List.length logM'⌝ ∗ ⌜is_log logM' logV'⌝ ∗\n        locked monγ ∗ (monR logM') ∗ logL ↦[ip] logV' ∗ own_log_auth γlog q logM' }}}.\n  Proof.\n    iIntros (Φ) \"(%Hi & %Hl & #Hmon & Hlocked & Hres & Hp & Hown) HΦ\".\n    wp_lam.\n    wp_pures.\n    case_bool_decide as Hi2 ; first by lia.\n    wp_pures.\n    wp_apply (wp_log_next with \"[$Hp //]\").\n    iIntros (n) \"(-> & _ & Hp)\".\n    wp_pures.\n    case_bool_decide as Hiz; first by lia.\n    wp_pure _.\n    clear Hiz Hi2.\n    iDestruct (get_obs with \"Hown\") as \"#Hobs\".\n    iLöb as \"IH\" forall (logV logM Hl Hi) \"Hres Hp Hown Hobs\".\n    wp_pures.\n    wp_apply (wp_log_next with \"[$Hp //]\").\n    iIntros (n) \"(-> & _ & Hp)\".\n    wp_pures.\n    case_bool_decide as Hiz2.\n    - wp_pure _.\n      wp_apply (monitor_wait_spec with \"[$Hmon Hres $Hlocked Hp Hown]\").\n      iExists _, _. iFrame. eauto.\n      iIntros (v) \"(-> & Hlocked & Hres)\".\n      iDestruct \"Hres\" as (logV' logM' Hlog') \"(Hp & Hown & Hres)\".\n      do 2 wp_pure _.\n      iDestruct (own_obs_prefix with \"[$Hown][$Hobs]\") as \"%Hpre\".\n      assert (i ≤ length logM') as Hi'.\n      list_simplifier.\n      by apply prefix_length.\n      iSpecialize (\"IH\" $! logV' logM' Hlog' Hi').\n      iDestruct (get_obs with \"Hown\") as \"#Hobs'\".\n      iApply (\"IH\" with \"[$Hlocked][$HΦ][$Hres][$Hp][$Hown][$Hobs']\").\n    - wp_pure _.\n      wp_apply wp_assert.\n       wp_pures.\n      iSplitR.\n      iPureIntro.\n      f_equal.\n      case_bool_decide; eauto with lia.\n      iNext.\n      iApply \"HΦ\".\n      iFrame.\n      eauto with lia.\n  Qed.\n\n  End Log.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/reliable_communication/lib/repdb/proof/log_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.2194202299735823}}
{"text": "Require Import Fiat.Common Fiat.Computation.Core Fiat.ADT.Core Coq.Sets.Ensembles.\n\nSection HideADT.\n\n  Context {extSig : ADTSig}.\n  (* The extended signature *)\n\n  Context {resConstructorIndex : Type}.\n  (* The restricted set of constructor indices *)\n\n  Context {resMethodIndex : Type}.\n  (* The restricted set of method indices *)\n\n  Variable constructorMap : resConstructorIndex -> ConstructorIndex extSig.\n  (* Map from restricted to extended constructor indices *)\n\n  Variable methodMap : resMethodIndex -> MethodIndex extSig.\n  (* Map from restricted to extended method indices *)\n\n  Definition resSig :=\n    {| ConstructorIndex := resConstructorIndex;\n       MethodIndex := resMethodIndex;\n       ConstructorDom idx := ConstructorDom extSig (constructorMap idx);\n       MethodDomCod idx := MethodDomCod extSig (methodMap idx)\n    |}.\n  (* The signature of the ADT with restricted constructor and method indices *)\n\n  Definition HideADT (extADT : ADT extSig) : ADT resSig :=\n    match extADT with\n        {| Rep := rep;\n           Constructors := extConstructors;\n           Methods := extMethods\n        |} =>\n        Build_ADT resSig\n          (fun idx => extConstructors (constructorMap idx))\n          (fun idx => extMethods (methodMap idx))\n    end.\n\nEnd HideADT.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/ADT/ADTHide.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21934320609567867}}
{"text": "From fae_gtlc_mu.refinements.gradual_static Require Export compat_cast.defs.\nFrom fae_gtlc_mu.backtranslation Require Export general_def_lemmas.\nFrom fae_gtlc_mu.cast_calculus Require Export types.\nFrom fae_gtlc_mu.stlc_mu Require Export lang.\n\nSection compat_cast_arrow_arrow.\n  Context `{!implG Σ,!specG Σ}.\n\n  Hint Extern 5 (AsVal _) => eexists; simpl; try done; eapply cast_calculus.lang.of_to_val; fast_done : typeclass_instances.\n\n  (** The case `throughArrow` in our proof by induction on the alternative consistency relation. *)\n  Lemma back_cast_ar_arrow_arrow:\n    ∀ (A : list (type * type)) (τ1 τ1' τ2 τ2' : type) (pC1 : alternative_consistency A τ1' τ1) (pC2 : alternative_consistency A τ2 τ2')\n      (IHpC1 : back_cast_ar pC1) (IHpC2 : back_cast_ar pC2),\n      back_cast_ar (throughArrow A τ1 τ1' τ2 τ2' pC1 pC2).\n  Proof.\n    intros A τ1 τ1' τ2 τ2' pC1 pC2 IHpC1 IHpC2.\n    rewrite /back_cast_ar. iIntros (ei' K' v v' fs) \"(#Hfs & #Hvv' & #Hei' & Hv')\".\n    iDestruct \"Hfs\" as \"[% Hfs']\"; iAssert (rel_cast_functions A fs) with \"[Hfs']\" as \"Hfs\". iSplit; done. iClear \"Hfs'\".\n    rewrite /𝓕c /𝓕. fold (𝓕 pC1) (𝓕 pC2). rewrite between_TArrow_subst_rewrite.\n    rename v into f. rename v' into f'. iDestruct \"Hv'\" as \"Hf'\". iDestruct \"Hvv'\" as \"Hff'\".\n    fold (𝓕c pC1 fs) (𝓕c pC2 fs).\n    unfold between_TArrow.\n    iMod ((step_lam _ ei' K') with \"[Hf']\") as \"Hf'\"; auto. asimpl.\n    iApply wp_value.\n    iExists (LamV _). iFrame \"Hf'\".\n    do 2 rewrite interp_rw_TArrow. simpl.\n    iModIntro.\n    (** actual thing to prove *)\n    (** ===================== *)\n    iIntros ((a , a')) \"#Haa'\". simpl. clear K'.\n    iIntros (K') \"Hf'\".\n    simpl in *.\n    (** implementation *)\n    wp_head.\n    (** specification *)\n    iMod ((step_lam _ ei' K') with \"[Hf']\") as \"Hf'\"; auto. asimpl.\n    (** IH for arguments *)\n    iApply (wp_bind [cast_calculus.lang.AppRCtx f ; cast_calculus.lang.CastCtx _ _]).\n    rewrite 𝓕c_rewrite.\n    iApply (wp_wand with \"[Hf']\").\n    iApply (IHpC1 ei' (AppRCtx f' :: AppRCtx _ :: K')); auto.\n    (** ... *)\n    iIntros (b) \"HHH\".\n    iDestruct \"HHH\" as (b') \"[Hb' #Hbb']\". simpl.\n    (** use relatedness of functions *)\n    iApply (wp_bind [CastCtx _ _]).\n    iApply (wp_wand with \"[Hb']\").\n    iDestruct (\"Hff'\" with \"Hbb'\") as \"Hfbf'b'/=\".\n    iApply (\"Hfbf'b'\" $! (AppRCtx _ :: K')). iFrame \"Hb'\".\n    (** ... *)\n    iIntros (r) \"HHH\". iDestruct \"HHH\" as (r') \"[Hr' Hrr']\". simpl.\n    iApply (wp_wand with \"[-]\").\n    rewrite -𝓕c_rewrite.\n    (** second IH for the results *)\n    iApply (IHpC2 ei' K' r r' with \"[-]\"). auto.\n    (** ... *)\n    iIntros; auto.\n  Qed.\n\nEnd compat_cast_arrow_arrow.\n", "meta": {"author": "scaup", "repo": "fae-gtlc-mu", "sha": "6c6e64f0844327d55059b97c7aefab023385973e", "save_path": "github-repos/coq/scaup-fae-gtlc-mu", "path": "github-repos/coq/scaup-fae-gtlc-mu/fae-gtlc-mu-6c6e64f0844327d55059b97c7aefab023385973e/theories/refinements/gradual_static/compat_cast/arrow_arrow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21934320609567867}}
{"text": "(* Copyright (c) 2014, Robert Dockins *)\n\nRequire Import Setoid.\n\nRequire Import Domains.basics.\nRequire Import Domains.preord.\nRequire Import Domains.categories.\nRequire Import Domains.sets.\nRequire Import Domains.finsets.\nRequire Import Domains.esets.\nRequire Import Domains.effective.\nRequire Import Domains.plotkin.\nRequire Import Domains.embed.\nRequire Import Domains.joinable.\nRequire Import Domains.approx_rels.\nRequire Import Domains.profinite.\nRequire Import Domains.profinite_adj.\nRequire Import Domains.cont_functors.\n\n(**  * Continuous adjoint functors\n\n     Here we lift the lifting and forgetful adjoint functors into the\n     category of embeddings and prove that they are continuous.\n  *)\n\nDefinition forgetEMBED_map (A B:ob PLT) (f:A ⇀ B) : forgetPLT_ob A ⇀ forgetPLT_ob B :=\n  Embedding true (forgetPLT_ob A) (forgetPLT_ob B) \n    (@embed_map false A B f)\n    (@embed_mono false A B f)\n    (@embed_reflects false A B f)\n    (fun _ => I)\n    (@embed_directed2 false A B f).\n\nProgram Definition forgetEMBED : functor (EMBED false) (EMBED true) :=\n  Functor (EMBED false) (EMBED true) forgetPLT_ob forgetEMBED_map _ _ _.\nSolve Obligations of forgetEMBED using auto.\n\nProgram Definition liftEMBED_map (A B:ob ∂PLT) (f:A ⇀ B) : liftPPLT_ob A ⇀ liftPPLT_ob B :=\n  Embedding false (liftPPLT_ob A) (liftPPLT_ob B)\n    (fun x => match x with None => None | Some a => Some (f a) end)\n    _ _ _ _.\nNext Obligation.\n  simpl. intros.\n  destruct a; destruct a'; simpl; auto.\n  apply embed_mono. auto.\nQed.\nNext Obligation.\n  simpl. intros.\n  destruct a; destruct a'; simpl; auto.\n  apply embed_reflects with B f; auto.\nQed.\nNext Obligation.\n  intros. exists None. hnf. auto.\nQed.\nNext Obligation.\n  simpl. intros. \n  destruct a; destruct b.\n  destruct y. \n  destruct embed_directed2 with true A B f c1 c c0 as [q [?[??]]]; auto.\n  exists (Some q); auto.\n  elim H.\n  exists (Some c). auto.\n  exists (Some c). auto.\n  exists None. auto.\nQed.\n\nProgram Definition liftEMBED : functor (EMBED true) (EMBED false) :=\n  Functor (EMBED true) (EMBED false) liftPPLT_ob liftEMBED_map _ _ _.\nNext Obligation.\n  intros. split; hnf; simpl; intros.\n  destruct x; simpl.\n  destruct H. apply H. auto.\n  destruct x; simpl.\n  destruct H. apply H0. auto.\nQed.\nNext Obligation.\n  intros. split; hnf; simpl; intros.\n  destruct x. destruct H. apply H. auto.\n  destruct x. destruct H. apply H0. auto.\nQed.\nNext Obligation.\n  intros. split; hnf; simpl; intros.\n  destruct x. destruct H. apply H. auto.\n  destruct x. destruct H. apply H0. auto.\nQed.\n\nRequire Import bilimit.\n\nLemma forgetEMBED_continuous : continuous_functor forgetEMBED.\nProof.\n  hnf; intros.\n  apply decompose_is_colimit; simpl.\n  intros.\n  destruct (colimit_decompose _ I DS CC X x) as [i [s H]].\n  exists i. exists s. auto.\nQed.\n\nLemma liftEMBED_continuous : continuous_functor liftEMBED.\nProof.\n  hnf; intros.\n  apply decompose_is_colimit; simpl.\n  intros.\n  destruct x.\n  destruct (colimit_decompose _ I DS CC X c) as [i [s H]].\n  exists i. exists (Some s). auto.\n  destruct (directed.choose_ub_set I nil) as [i0 ?].\n  exists i0. exists None. auto.\nQed.\n\n", "meta": {"author": "lastland", "repo": "DomainTheory", "sha": "e7bf598569efaafe9499a9334edc43c9659f82fa", "save_path": "github-repos/coq/lastland-DomainTheory", "path": "github-repos/coq/lastland-DomainTheory/DomainTheory-e7bf598569efaafe9499a9334edc43c9659f82fa/cont_adj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21934320609567867}}
{"text": "Require Import progs.conclib.\nRequire Import progs.conc_queue.\nRequire Import progs.conc_queue_specs.\nRequire Import floyd.library.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nDefinition acquire_spec := DECLARE _acquire acquire_spec.\nDefinition release_spec := DECLARE _release release_spec.\nDefinition makelock_spec := DECLARE _makelock (makelock_spec _).\nDefinition freelock_spec := DECLARE _freelock (freelock_spec _).\nDefinition makecond_spec := DECLARE _makecond (makecond_spec _).\nDefinition freecond_spec := DECLARE _freecond (freecond_spec _).\nDefinition wait_spec := DECLARE _waitcond (wait2_spec _).\nDefinition signal_spec := DECLARE _signalcond (signal_spec _).\n\nDefinition surely_malloc_spec := DECLARE _surely_malloc surely_malloc_spec'.\nDefinition q_new_spec := DECLARE _q_new q_new_spec'.\nDefinition q_del_spec := DECLARE _q_del q_del_spec'.\nDefinition q_add_spec := DECLARE _q_add q_add_spec'.\nDefinition q_remove_spec := DECLARE _q_remove q_remove_spec'.\nDefinition q_tryremove_spec := DECLARE _q_tryremove q_tryremove_spec'.\n\nDefinition Gprog : funspecs := ltac:(with_library prog\n  [surely_malloc_spec; acquire_spec; release_spec; makelock_spec; freelock_spec;\n   makecond_spec; freecond_spec; wait_spec; signal_spec;\n   q_new_spec; q_del_spec; q_add_spec; q_remove_spec; q_tryremove_spec]).\n\nLemma body_surely_malloc: semax_body Vprog Gprog f_surely_malloc surely_malloc_spec.\nProof.\n  unfold surely_malloc_spec, surely_malloc_spec'; start_function.\n  forward_call (* p = malloc(n); *)\n     n.\n  Intros p.\n  forward_if\n  (PROP ( )\n   LOCAL (temp _p p)\n   SEP (malloc_token Tsh n p * memory_block Tsh n p)).\n*\n  if_tac.\n    subst p. entailer!.\n    entailer!.\n*\n    forward_call tt.\n    contradiction.\n*\n    if_tac.\n    + forward. subst p. inv H0.\n    + Intros. forward. entailer!.\n*\n  forward. Exists p; entailer!.\nQed.\n\nLemma body_q_new : semax_body Vprog Gprog f_q_new q_new_spec.\nProof.\n  unfold q_new_spec, q_new_spec'; start_function.\n  forward_call (sizeof tqueue_t).\n  { simpl; computable. }\n  Intros p.\n  assert (alignof tqueue_t | natural_alignment).\n  { simpl; unfold align_attr; simpl.\n    exists 2; auto. }\n  rewrite malloc_compat; auto; Intros.\n  rewrite memory_block_data_at_; auto.\n  forward.\n  Intros.\n  assert (field_compatible tqueue [] p /\\ field_compatible (tptr tlock) [] (offset_val 60 p)) as (? & ?).\n  { unfold field_compatible in *; repeat match goal with H : _ /\\ _ |- _ => destruct H end.\n    destruct p as [| | | | | b o]; try contradiction.\n    assert (Int.unsigned (Int.add o (Int.repr 60)) = Int.unsigned o + 60) as Ho.\n    { rewrite Int.unsigned_add_carry.\n      unfold Int.add_carry.\n      rewrite Int.unsigned_repr, Int.unsigned_zero; [|computable].\n      destruct (zlt _ Int.modulus); simpl in *; omega. }\n    repeat split; auto; simpl in *; try omega.\n    rewrite Ho; unfold align_attr in *; simpl in *.\n    apply Z.divide_add_r; auto.\n    exists 15; auto. }\n  forward_for_simple_bound MAX (EX i : Z, PROP () LOCAL (temp _q p; temp _newq p)\n    SEP (malloc_token Tsh (sizeof tqueue_t) p;\n         @data_at CompSpecs Tsh tqueue (repeat (vint 0) (Z.to_nat i) ++ repeat Vundef (Z.to_nat (MAX - i)),\n           (Vundef, (Vundef, (Vundef, (Vundef, Vundef))))) p;\n         @data_at_ CompSpecs Tsh (tptr tlock) (offset_val 60 p))).\n  { unfold MAX; computable. }\n  { unfold MAX; computable. }\n  { entailer!.\n    unfold data_at_, field_at_; unfold_field_at 1%nat.\n    unfold data_at, field_at, at_offset; simpl; entailer. }\n  { forward.\n    go_lower.\n    apply andp_right; [apply prop_right; split; auto; omega|].\n    apply andp_right; [apply prop_right; auto|].\n    cancel.\n    rewrite upd_Znth_app2; repeat rewrite Zlength_repeat; repeat rewrite Z2Nat.id; try omega.\n    rewrite Zminus_diag, upd_Znth0, sublist_repeat; try rewrite Zlength_repeat, Z2Nat.id; try omega.\n    rewrite Z2Nat.inj_add, repeat_plus; try omega; simpl.\n    rewrite <- app_assoc; replace (MAX - i - 1) with (MAX - (i + 1)) by omega; cancel. }\n  rewrite Zminus_diag, app_nil_r.\n  forward.\n  forward.\n  forward.\n  forward_call (sizeof tint).\n  { simpl; computable. }\n  Intros addc.\n  rewrite malloc_compat with (p0 := addc); auto; Intros.\n  rewrite memory_block_data_at_; auto.\n  forward_call (addc, Tsh).\n  { unfold tcond; cancel. }\n  forward.\n  forward_call (sizeof tint).\n  { simpl; computable. }\n  Intros remc.\n  rewrite malloc_compat with (p0 := remc); auto; Intros.\n  rewrite memory_block_data_at_; auto.\n  forward_call (remc, Tsh).\n  { unfold tcond; cancel. }\n  forward.\n  forward_call (sizeof tlock).\n  { admit. } (* lock size broken *)\n  { simpl; computable. }\n  Intros lock.\n  rewrite malloc_compat with (p0 := lock); auto; Intros.\n  rewrite memory_block_data_at_; auto.\n  destruct Q as (t, P).\n  forward_call (lock, Tsh, q_lock_pred t P p lock gsh2).\n  gather_SEP 7 8; replace_SEP 0 (data_at Tsh tqueue_t (repeat (vint 0) (Z.to_nat MAX),\n           (vint 0, (vint 0, (vint 0, (addc, remc)))), Vundef) p).\n  { go_lowerx.\n    unfold_data_at 1%nat.\n    unfold data_at_, field_at_, field_at, at_offset; simpl.\n    rewrite !sem_cast_neutral_ptr; auto.\n    rewrite !field_compatible_cons; simpl; Intros.\n    apply andp_right; [apply prop_right; unfold in_members; simpl; split; [|split; [|split]]; auto|].\n    rewrite sepcon_emp, !isptr_offset_val_zero; auto. }\n  apply new_ghost with (t' := reptype t).\n  forward.\n  forward_call (lock, Tsh, q_lock_pred t P p lock gsh2).\n  { lock_props.\n    unfold q_lock_pred, q_lock_pred'; simpl.\n    Exists ([] : list (val * reptype t)) 0 addc remc ([] : hist (reptype t)).\n    rewrite Zlength_nil; simpl; cancel.\n    rewrite sepcon_andp_prop'.\n    apply andp_right; [apply prop_right|].\n    { repeat split; auto; unfold MAX; try omega; try computable. }\n    cancel.\n    subst Frame; instantiate (1 := [field_at Tsh tqueue_t [StructField _lock] lock p; ghost gsh1 (Tsh, []) p]);\n      simpl.\n    unfold_field_at 1%nat.\n    erewrite <- ghost_share_join with (h1 := []); eauto.\n    simpl; cancel.\n    rewrite (sepcon_comm _ (@ghost _ (reptype t) _ _)), !sepcon_assoc; apply sepcon_derives; auto.\n    unfold data_at, field_at; simpl.\n    rewrite !field_compatible_cons; simpl; Intros.\n    apply andp_right; [apply prop_right; unfold in_members; simpl; split; [|split]; auto|].\n    rewrite sem_cast_neutral_ptr; auto. }\n  forward.\n  Exists p lock.\n  unfold lqueue; simpl; entailer!; auto.\nAdmitted.\n\nLemma body_q_del : semax_body Vprog Gprog f_q_del q_del_spec.\nProof.\n  unfold q_del_spec, q_del_spec'; start_function.\n  destruct Q as (t, (P, h)).\n  unfold lqueue; rewrite lock_inv_isptr; Intros.\n  forward.\n  forward_call (lock, Tsh, q_lock_pred t P p lock gsh2).\n  forward_call (lock, Tsh, q_lock_pred t P p lock gsh2).\n  { lock_props. }\n  unfold q_lock_pred, q_lock_pred'; Intros vals head addc remc h'.\n  forward_call (lock, sizeof tlock).\n  { simpl; cancel.\n    rewrite !sepcon_assoc; apply sepcon_derives; [apply data_at__memory_block_cancel | cancel]. }\n  forward.\n  rewrite data_at_isptr, (cond_var_isptr _ addc), (cond_var_isptr _ remc); Intros.\n  rewrite isptr_offset_val_zero; auto.\n  forward.\n  forward_call (addc, Tsh).\n  forward_call (addc, sizeof tcond).\n  { simpl; cancel.\n    rewrite !sepcon_assoc; apply sepcon_derives; [apply data_at__memory_block_cancel | cancel]. }\n  forward.\n  forward_call (remc, Tsh).\n  forward_call (remc, sizeof tcond).\n  { simpl; cancel.\n    repeat rewrite sepcon_assoc; apply sepcon_derives; [apply data_at__memory_block_cancel | cancel]. }\n  gather_SEP 2 5; rewrite sepcon_comm.\n  replace_SEP 0 (!!(h' = h) && ghost Tsh (Tsh, h) p).\n  { go_lower.\n    eapply derives_trans; [apply prop_and_same_derives, ghost_inj_Tsh|].\n    Intros; subst.\n    rewrite ghost_share_join; auto; entailer!. }\n  Intros; subst.\n  exploit (consistent_inj h [] [] vals); auto; intro; subst; simpl.\n  rewrite Zlength_nil.\n  gather_SEP 1 4; replace_SEP 0 (data_at Tsh tqueue_t (rotate (complete MAX []) head MAX,\n     (vint 0, (vint head, (vint ((head + 0) mod MAX), (addc, remc)))), lock) p).\n  { unfold_data_at 2%nat; entailer!.\n    unfold data_at, field_at; Intros; simpl.\n    apply andp_right; [|simple apply derives_refl].\n    rewrite field_compatible_cons; unfold in_members; simpl; entailer!. }\n  forward_call (p, sizeof tqueue_t).\n  { rewrite (sepcon_comm (malloc_token _ _ _)).\n    rewrite !sepcon_assoc; apply sepcon_derives; [apply data_at_memory_block | simpl; cancel]. }\n  forward.\n  (* Do we want to deallocate the ghost? *)\nAdmitted.\n\nLemma body_q_add : semax_body Vprog Gprog f_q_add q_add_spec.\nProof.\n  unfold q_add_spec, q_add_spec'.\n  start_function.\n  destruct Q as (t, ((P, h), v)).\n  unfold lqueue; rewrite lock_inv_isptr; Intros.\n  forward.\n  forward_call (lock, sh, q_lock_pred t P p lock gsh2).\n  unfold q_lock_pred at 2; unfold q_lock_pred'; Intros vals head addc remc h'.\n  forward.\n  rewrite data_at_isptr; Intros; rewrite isptr_offset_val_zero; auto.\n  forward.\n  forward_while (EX vals : _, EX head : Z, EX addc : val, EX remc : val, EX h' : hist (reptype t),\n   PROP ()\n   LOCAL (temp _len (vint (Zlength vals)); temp _q p; temp _l lock; temp _tgt p; temp _r e)\n   SEP (lock_inv sh lock (q_lock_pred t P p lock gsh2);\n        q_lock_pred' t P p vals head addc remc lock gsh2 h';\n        @field_at CompSpecs sh tqueue_t [StructField _lock] lock p;\n        @data_at CompSpecs Tsh t v e; malloc_token Tsh (sizeof t) e; ghost gsh1 (sh, h) p)).\n  { Exists vals head addc remc h'.\n    unfold q_lock_pred'; entailer!.\n    apply derives_refl. }\n  { go_lower; entailer'. }\n  { unfold q_lock_pred'; Intros.\n    forward.\n    { go_lower.\n      rewrite cond_var_isptr; Intros; entailer'. }\n    forward_call (addc0, lock, Tsh, sh, q_lock_pred t P p lock gsh2).\n    { unfold q_lock_pred; unfold q_lock_pred'; simpl.\n      Exists vals0 head0 addc0 remc0 h'0.\n      subst Frame; instantiate (1 := [field_at sh tqueue_t [StructField _lock] lock p;\n        data_at Tsh t v e; malloc_token Tsh (sizeof t) e; ghost gsh1 (sh, h) p]); simpl.\n      repeat rewrite sepcon_assoc; repeat (apply sepcon_derives; [apply derives_refl|]).\n      entailer!.\n      apply andp_right; cancel. }\n    unfold q_lock_pred at 2; unfold q_lock_pred'; Intros vals1 head1 addc1 remc1 h'1.\n    forward.\n    Exists (vals1, head1, addc1, remc1, h'1).\n    unfold q_lock_pred'; entailer!. }\n  unfold q_lock_pred'; Intros.\n  rewrite Int.signed_repr, Zlength_correct in HRE.\n  freeze [0; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13] FR; forward.\n  exploit (Z_mod_lt (head0 + Zlength vals0) MAX); [omega | intro].\n  forward.\n  forward.\n  { go_lower.\n    repeat apply andp_right; apply prop_right; auto.\n    rewrite andb_false_intro2; simpl; auto. }\n  forward.\n  thaw FR.\n  rewrite (cond_var_isptr _ remc0); Intros.\n  forward.\n  freeze [0; 1; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13] FR; forward_call (remc0, Tsh).\n  thaw FR.\n  rewrite upd_rotate; auto; try rewrite Zlength_complete; try rewrite Zlength_map; auto.\n  rewrite Zminus_mod_idemp_l, Z.add_simpl_l, (Zmod_small (Zlength vals0));\n    [|rewrite Zlength_correct; unfold MAX; omega].\n  erewrite <- Zlength_map, upd_complete; [|rewrite Zlength_map, Zlength_correct; auto].\n  gather_SEP 7 12.\n  rewrite sepcon_comm; replace_SEP 0 (!!(list_incl h h'0) && ghost Tsh (Tsh, h'0) p).\n  { go_lower.\n    eapply derives_trans; [apply prop_and_same_derives, ghost_inj|].\n    Intros; rewrite ghost_share_join; auto; entailer!. }\n  exploit (consistent_snoc_add h'0 [] vals0 e v); auto; intro.\n  Intros; apply hist_add with (e0 := QAdd e v); [eauto|].\n  erewrite <- ghost_share_join with (h1 := h ++ [QAdd e v])(sh := sh); try eassumption.\n  time forward_call (lock, sh, q_lock_pred t P p lock gsh2). (* 37s *)\n  { lock_props.\n    unfold q_lock_pred, q_lock_pred'.\n    Exists (vals0 ++ [(e, v)]) head0 addc0 remc0 (h'0 ++ [QAdd e v]).\n    rewrite data_at_isptr; Intros.\n    rewrite map_app, Zlength_app, Zlength_cons, Zlength_nil.\n    unfold sem_mod; simpl sem_binarith.\n    unfold both_int; simpl force_val.\n    rewrite andb_false_intro2; [|simpl; auto].\n    simpl force_val.\n    rewrite !add_repr, mods_repr; try computable.\n    repeat match goal with H : _ /\\ _ |- _ => destruct H end.\n    simpl; apply andp_right.\n    { apply prop_right; split; [rewrite Zlength_correct; unfold MAX; omega|].\n      split; [omega | auto]. }\n    rewrite Zplus_mod_idemp_l, Z.add_assoc, Zlength_map.\n    repeat rewrite map_app; repeat rewrite sepcon_app; simpl.\n    rewrite sem_cast_neutral_ptr; auto; simpl.\n    rewrite sepcon_andp_prop', !sepcon_andp_prop, sepcon_andp_prop'; apply andp_right;\n      [apply prop_right; auto | cancel].\n    { pose proof (Z_mod_lt (head0 + Zlength vals0) MAX).\n      rewrite Zlength_map; split; try omega.\n      transitivity MAX; simpl in *; [omega | unfold MAX; computable]. } }\n  forward.\n  { unfold lqueue; simpl; entailer!; auto. }\n  { apply list_incl_app; auto. }\n  { pose proof Int.min_signed_neg; split; [rewrite Zlength_correct; omega|].\n    transitivity MAX; [auto | unfold MAX; computable]. }\nAdmitted.\n\nLemma body_q_remove : semax_body Vprog Gprog f_q_remove q_remove_spec.\nProof.\n  unfold q_remove_spec, q_remove_spec'; start_function.\n  destruct Q as (t, (P, h)).\n  unfold lqueue; rewrite lock_inv_isptr; Intros.\n  forward.\n  forward_call (lock, sh, q_lock_pred t P p lock gsh2).\n  unfold q_lock_pred at 2; unfold q_lock_pred'; Intros vals head addc remc h'.\n  forward.\n  rewrite data_at_isptr; Intros; rewrite isptr_offset_val_zero; auto.\n  forward.\n  forward_while (EX vals : list _, EX head : Z, EX addc : val, EX remc : val, EX h' : hist (reptype t), PROP ()\n   LOCAL (temp _len (vint (Zlength vals)); temp _q p; temp _l lock; temp _tgt p)\n   SEP (lock_inv sh lock (q_lock_pred t P p lock gsh2);\n        q_lock_pred' t P p vals head addc remc lock gsh2 h';\n        @field_at CompSpecs sh tqueue_t [StructField _lock] lock p; ghost gsh1 (sh, h) p)).\n  { Exists vals head addc remc h'; unfold q_lock_pred'; entailer!. }\n  { go_lower; entailer'. }\n  { unfold q_lock_pred'; rewrite (cond_var_isptr _ remc0); Intros.\n    forward.\n    forward_call (remc0, lock, Tsh, sh, q_lock_pred t P p lock gsh2).\n    { unfold q_lock_pred; unfold q_lock_pred'; simpl.\n      Exists vals0 head0 addc0 remc0 h'0.\n      subst Frame; instantiate (1 := [field_at sh tqueue_t [StructField _lock] lock p;\n        ghost gsh1 (sh, h) p]); simpl.\n      repeat rewrite sepcon_assoc; repeat (apply sepcon_derives; [apply derives_refl|]).\n      entailer!.\n      apply andp_right; [Intros; entailer! | entailer!]. }\n    unfold q_lock_pred at 2; unfold q_lock_pred'; Intros vals1 head1 addc1 remc1 h'1.\n    forward.\n    Exists (vals1, head1, addc1, remc1, h'1).\n    unfold q_lock_pred'; entailer!. }\n  unfold q_lock_pred'; Intros.\n  assert (Zlength vals0 > 0).\n  { rewrite Zlength_correct in *.\n    destruct (length vals0); [|rewrite Nat2Z.inj_succ; omega].\n    contradiction HRE; auto. }\n  evar (R : mpred).\n  replace_SEP 9 (!!(Forall isptr (map fst vals0)) && R); subst R.\n  { go_lower; apply prop_and_same_derives, all_ptrs. }\n  forward.\n  forward.\n  { go_lower; Intros.\n    rewrite Znth_head; try rewrite Zlength_map; try omega.\n    repeat apply andp_right; apply prop_right; auto.\n    apply Forall_Znth; [rewrite Zlength_map; omega|].\n    eapply Forall_impl; [|eauto].\n    destruct a; auto. }\n  forward.\n  forward.\n  { go_lower; simpl.\n    repeat apply andp_right; apply prop_right; auto.\n    rewrite andb_false_intro2; simpl; auto. }\n  forward.\n  rewrite cond_var_isptr; Intros.\n  forward.\n  freeze [0; 1; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12] FR; forward_call (addc0, Tsh).\n  thaw FR.\n  rewrite upd_rotate; try rewrite Zlength_complete; try rewrite Zlength_map; auto.\n  rewrite Zminus_diag, Zmod_0_l.\n  destruct vals0; [contradiction HRE; auto|].\n  rewrite Zlength_cons in *.\n  simpl; rewrite rotate_1; try rewrite Zlength_map; try omega.\n  unfold sem_mod; simpl sem_binarith.\n  unfold both_int; simpl force_val.\n  rewrite andb_false_intro2; [|simpl; auto].\n  simpl force_val.\n  rewrite !add_repr, mods_repr; try computable.\n  destruct p0 as (e, v).\n  exploit (consistent_cons_rem(t := reptype t)); eauto; intro.\n  gather_SEP 8 11.\n  rewrite sepcon_comm; replace_SEP 0 (!!(list_incl h h'0) && ghost Tsh (Tsh, h'0) p).\n  { go_lower.\n    eapply derives_trans; [apply prop_and_same_derives, ghost_inj|].\n    Intros; rewrite ghost_share_join; auto; entailer!. }\n  Intros; apply hist_add with (e0 := QRem e v); [eauto|].\n  erewrite <- ghost_share_join with (h1 := h ++ [QRem e v])(sh := sh); try eassumption; try apply list_incl_app;\n    auto.\n  forward_call (lock, sh, q_lock_pred t P p lock gsh2).\n  { lock_props.\n    unfold q_lock_pred, q_lock_pred'; Exists vals0 ((head0 + 1) mod MAX) addc0 remc0 (h'0 ++ [QRem e v]).\n    unfold Z.succ; rewrite sub_repr, Z.add_simpl_r, (Z.add_comm (Zlength vals0)), Z.add_assoc,\n      Zplus_mod_idemp_l.\n    simpl; entailer!.\n    apply Z_mod_lt; omega. }\n  forward.\n  Exists e v; unfold lqueue; simpl; entailer!; auto.\n  rewrite Znth_head; auto; rewrite Zlength_cons, Zlength_map; omega.\n  { split; try omega.\n    transitivity MAX; [omega | unfold MAX; computable]. }\nQed.\n\nLemma body_q_tryremove : semax_body Vprog Gprog f_q_tryremove q_tryremove_spec.\nProof.\n  unfold q_tryremove_spec, q_tryremove_spec'; start_function.\n  destruct Q as (t, (P, h)).\n  unfold lqueue; rewrite lock_inv_isptr; Intros.\n  forward.\n  forward_call (lock, sh, q_lock_pred t P p lock gsh2).\n  unfold q_lock_pred at 2; unfold q_lock_pred'; Intros vals head addc remc h'.\n  forward.\n  rewrite data_at_isptr; Intros; rewrite isptr_offset_val_zero; auto.\n  forward.\n  forward_if (PROP (Zlength vals <> 0)\n   LOCAL (temp _len (vint (Zlength vals)); temp _q p; temp _l lock; temp _tgt p)\n   SEP (lock_inv sh lock (q_lock_pred t P p lock gsh2);\n   data_at Tsh tqueue\n     (rotate (complete MAX (map fst vals)) head MAX,\n     (vint (Zlength vals), (vint head, (vint ((head + Zlength vals) mod MAX), (addc, remc))))) p;\n   cond_var Tsh addc; cond_var Tsh remc; malloc_token Tsh (sizeof tqueue_t) p;\n   malloc_token Tsh (sizeof tcond) addc; malloc_token Tsh (sizeof tcond) remc;\n   malloc_token Tsh (sizeof tlock) lock; ghost gsh2 (Tsh, h') p;\n   fold_right sepcon emp (map (fun x => let '(p, v) := x in\n     !!(P v) && (data_at Tsh t v p * malloc_token Tsh (sizeof t) p)) vals);\n   field_at sh tqueue_t [StructField _lock] lock p; ghost gsh1 (sh, h) p)).\n  { forward_call (lock, sh, q_lock_pred t P p lock gsh2).\n    { simpl; lock_props.\n      unfold q_lock_pred, q_lock_pred'; Exists vals head addc remc h'; simpl; entailer!. }\n    forward.\n    Exists (vint 0); entailer!.\n    destruct (Memory.EqDec_val (vint 0) nullval); [|contradiction n; auto].\n    unfold lqueue; simpl; entailer!. }\n  { forward.\n    entailer!.\n    congruence. }\n  Intros.\n  assert (Zlength vals > 0).\n  { rewrite Zlength_correct in *.\n    destruct (length vals); [omega | rewrite Nat2Z.inj_succ; omega]. }\n  evar (R : mpred).\n  replace_SEP 9 (!!(Forall isptr (map fst vals)) && R); subst R.\n  { go_lower; apply prop_and_same_derives, all_ptrs. }\n  forward.\n  forward.\n  { go_lower; Intros.\n    rewrite Znth_head; try rewrite Zlength_map; try omega.\n    repeat apply andp_right; apply prop_right; auto.\n    apply Forall_Znth; [rewrite Zlength_map; omega|].\n    eapply Forall_impl; [|eauto].\n    destruct a; auto. }\n  forward.\n  forward.\n  { go_lower; simpl.\n    repeat apply andp_right; apply prop_right; auto.\n    rewrite andb_false_intro2; simpl; auto. }\n  forward.\n  rewrite cond_var_isptr; Intros.\n  forward.\n  freeze [0; 1; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12] FR; forward_call (addc, Tsh).\n  thaw FR.\n  rewrite upd_rotate; try rewrite Zlength_complete; try rewrite Zlength_map; auto.\n  rewrite Zminus_diag, Zmod_0_l.\n  destruct vals; [rewrite Zlength_nil in *; omega|].\n  rewrite Zlength_cons in *.\n  simpl; rewrite rotate_1; try rewrite Zlength_map; try omega.\n  unfold sem_mod; simpl sem_binarith.\n  unfold both_int; simpl force_val.\n  rewrite andb_false_intro2; [|simpl; auto].\n  simpl force_val.\n  rewrite !add_repr, mods_repr; try computable.\n  destruct p0 as (e, v).\n  exploit (consistent_cons_rem(t := reptype t)); eauto; intro.\n  gather_SEP 8 11.\n  rewrite sepcon_comm; replace_SEP 0 (!!(list_incl h h') && ghost Tsh (Tsh, h') p).\n  { go_lower.\n    eapply derives_trans; [apply prop_and_same_derives, ghost_inj|].\n    Intros; rewrite ghost_share_join; auto; entailer!. }\n  Intros; apply hist_add with (e0 := QRem e v); [eauto|].\n  erewrite <- ghost_share_join with (h1 := h ++ [QRem e v])(sh := sh); try eassumption; try apply list_incl_app;\n    auto.\n  forward_call (lock, sh, q_lock_pred t P p lock gsh2).\n  { lock_props.\n    unfold q_lock_pred, q_lock_pred'; Exists vals ((head + 1) mod MAX) addc remc (h' ++ [QRem e v]).\n    unfold Z.succ; rewrite sub_repr, Z.add_simpl_r, (Z.add_comm (Zlength vals)), Z.add_assoc,\n      Zplus_mod_idemp_l.\n    simpl; entailer!.\n    apply Z_mod_lt; omega. }\n  forward.\n  Exists e; entailer!.\n  { rewrite Znth_head; auto; rewrite Zlength_cons, Zlength_map; omega. }\n  destruct (Memory.EqDec_val e nullval).\n  { rewrite data_at_isptr; Intros.\n    subst; contradiction. }\n  Exists v; unfold lqueue; simpl; entailer!; auto.\n  { split; try omega.\n    transitivity MAX; [omega | unfold MAX; computable]. }\nQed.\n\nDefinition extlink := ext_link_prog prog.\n\nDefinition Espec := add_funspecs (Concurrent_Espec unit _ extlink) extlink Gprog.\nExisting Instance Espec.\n\nLemma all_funcs_correct:\n  semax_func Vprog Gprog (prog_funct prog) Gprog.\nProof.\nunfold Gprog, prog, prog_funct; simpl.\nsemax_func_cons body_exit.\nsemax_func_cons body_free.\nsemax_func_cons body_malloc. apply semax_func_cons_malloc_aux.\nrepeat semax_func_cons_ext.\nsemax_func_cons body_surely_malloc.\nsemax_func_cons body_q_new.\nsemax_func_cons body_q_del.\nsemax_func_cons body_q_add.\nsemax_func_cons body_q_tryremove.\nsemax_func_cons body_q_remove.\nQed.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/progs/verif_conc_queue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.2193432060956786}}
{"text": "Require Import\n        List.\n\nRequire Import\n        Events\n        LibModel\n        Maps\n        Messages\n        States\n        Types.\n\nRequire Import\n        ERC20.\n\n(** Tier definition *)\nDefinition TIER1 : uint := 3.\nDefinition TIER2 : uint := 2.\nDefinition TIER3 : uint := 1.\nDefinition TIER4 : uint := 0.\n\n(** * Constants *)\nDefinition BURN_BASE_PERCENTAGE : uint := 100 * 10. (* 100% *)\n(* Cost of upgrading the tier level of a token in a percentage of the total LRC supply *)\nDefinition TIER_UPGRADE_COST_PERCENTAGE : uint := 5. (* 0.5% *)\n(* Burn rates *)\nDefinition BURN_MATCHING_TIER1 : uint := 5 * 10. (* 5% *)\nDefinition BURN_MATCHING_TIER2 : uint := 20 * 10. (* 20% *)\nDefinition BURN_MATCHING_TIER3 : uint := 40 * 10. (* 40% *)\nDefinition BURN_MATCHING_TIER4 : uint := 60 * 10. (* 60% *)\n(* P2P *)\nDefinition BURN_P2P_TIER1 : uint := 5. (* 0.5% *)\nDefinition BURN_P2P_TIER2 : uint := 2 * 10. (* 2% *)\nDefinition BURN_P2P_TIER3 : uint := 3 * 10. (* 3% *)\nDefinition BURN_P2P_TIER4 : uint := 6 * 10. (* 6% *)\n\n(* Defining 0x10000 in nat causes stack overflow... *)\nParameter x10000 : uint.\n\nParameter YEAR_TO_SECONDS : uint.\n\n(** Here I assumed the BurnRateTable is constructed using correct LRC and WETH addresses *)\n(* LRC address, WETH address *)\nParameter lrcAddress : address.\nParameter wethAddress : address.\n\n(** * Auxiliary definitions *)\n\n(** It seems the [BurnRateTableState] should be added to WorldState. *)\nDefinition get_state (wst : WorldState) : BurnRateTableState :=\n  wst_burn_rate_table_state wst.\n\nDefinition set_state : WorldState -> BurnRateTableState -> WorldState :=\n  wst_update_burn_rate_table.\n\nDefinition this : WorldState -> address := wst_burn_rate_table_addr.\n\n(** * Method call specs *)\n\nSection getTokenTier_SPEC.\n\n  Variable (sender: address).\n  Variable (token: address).\n\n  (* function body:\n     function getTokenTier(\n        address token\n        )\n        public\n        view\n        returns (uint tier)\n    {\n        TokenData storage tokenData = tokens[token];\n        // Fall back to lowest tier\n        tier = (now > tokenData.validUntil) ? TIER_4 : tokenData.tier;\n    }\n   *)\n\n  Definition getTIER (wst: WorldState) : uint :=\n    let tokens := (burnratetable_tokens (get_state wst)) in\n    let data := TokenDataMap.get tokens token in\n    if Nat.ltb data.(validUntil) (block_timestamp (wst_block_state wst))\n    then TIER4\n    else data.(tier).\n\n  Definition getTokenTier_require : WorldState -> Prop := fun _ => True.\n\n  Inductive getTokenTier_trans : WorldState -> WorldState -> RetVal -> Prop :=\n  | getTokenTierTrans: forall wst, getTokenTier_trans wst wst (RetUint (getTIER wst)).\n\n  Inductive getTokenTier_events : WorldState -> list Event -> Prop :=\n  | getTokenTierEvents: forall wst, getTokenTier_events wst nil.\n\n  Definition getTokenTier_spec : FSpec :=\n    mk_fspec getTokenTier_require getTokenTier_trans getTokenTier_events.\n\nEnd getTokenTier_SPEC.\n\n\nSection getBurnRate_SPEC.\n  Variable (sender: address).\n  Variable (token: address).\n\n  (* function body:\n     function getBurnRate(\n        address token\n        )\n        external\n        view\n        returns (uint32 burnRate)\n    {\n        uint tier = getTokenTier(token);\n        if (tier == TIER_1) {\n            burnRate = uint32(BURN_P2P_TIER1) * 0x10000 + BURN_MATCHING_TIER1;\n        } else if (tier == TIER_2) {\n            burnRate = uint32(BURN_P2P_TIER2) * 0x10000 + BURN_MATCHING_TIER2;\n        } else if (tier == TIER_3) {\n            burnRate = uint32(BURN_P2P_TIER3) * 0x10000 + BURN_MATCHING_TIER3;\n        } else {\n            burnRate = uint32(BURN_P2P_TIER4) * 0x10000 + BURN_MATCHING_TIER4;\n        }\n    }\n   *)\n  Definition getRate (TIER: uint) : uint :=\n    match TIER with\n    (* TIER 4 *)\n    | O => BURN_P2P_TIER4 * x10000 + BURN_MATCHING_TIER4\n    (* TIER 3 *)\n    | S O => BURN_P2P_TIER3 * x10000 + BURN_MATCHING_TIER3\n    (* TIER 2 *)\n    | S (S O) => BURN_P2P_TIER2 * x10000 + BURN_MATCHING_TIER2\n    (* TIER 1 *)\n    | S (S (S O)) => BURN_P2P_TIER1 * x10000 + BURN_MATCHING_TIER1\n    (* other cases *)\n    | _ => BURN_P2P_TIER4 * x10000 + BURN_MATCHING_TIER4\n    end.\n\n  Definition getBurnRate_require : WorldState -> Prop := fun _ => True.\n\n  Inductive getBurnRate_trans : WorldState -> WorldState -> RetVal -> Prop :=\n  | getBurnRateTrans: forall wst,\n      getBurnRate_trans wst wst (RetUint (getRate (getTIER token wst))).\n\n  Inductive getBurnRate_events : WorldState -> list Event -> Prop :=\n  | getBurnRateEvents: forall wst, getBurnRate_events wst nil.\n\n  Definition getBurnRate_spec : FSpec :=\n    mk_fspec getBurnRate_require getBurnRate_trans getBurnRate_events.\n\nEnd getBurnRate_SPEC.\n\n\nSection upgradeTokenTier_SPEC.\n\n  Variable (sender: address).\n  Variable (token: address).\n  (* function body\n     function upgradeTokenTier(\n        address token\n        )\n        external\n        returns (bool)\n    {\n        require(token != 0x0, ZERO_ADDRESS);\n        require(token != lrcAddress, BURN_RATE_FROZEN);\n        require(token != wethAddress, BURN_RATE_FROZEN);\n\n        uint currentTier = getTokenTier(token);\n\n        // Can't upgrade to a higher level than tier 1\n        require(currentTier != TIER_1, BURN_RATE_MINIMIZED);\n\n        // Burn TIER_UPGRADE_COST_PERCENTAGE of total LRC supply\n        BurnableERC20 LRC = BurnableERC20(lrcAddress);\n        uint totalSupply = LRC.totalSupply();\n        uint amount = totalSupply.mul(TIER_UPGRADE_COST_PERCENTAGE) / BURN_BASE_PERCENTAGE;\n        bool success = LRC.burnFrom(msg.sender, amount);\n        require(success, BURN_FAILURE);\n\n        // Upgrade tier\n        TokenData storage tokenData = tokens[token];\n        tokenData.validUntil = now.add(2 * YEAR_TO_SECONDS);\n        tokenData.tier = currentTier + 1;\n\n        emit TokenTierUpgraded(token, tokenData.tier);\n\n        return true;\n    }\n   *)\n\n\n  Definition burnamount (totalSupply: uint) : uint :=\n    Nat.div (totalSupply * TIER_UPGRADE_COST_PERCENTAGE) BURN_BASE_PERCENTAGE.\n\n  Definition upgradetier (wst: WorldState) : WorldState * uint :=\n    let tokens := burnratetable_tokens (get_state wst) in\n    let data := TokenDataMap.get tokens token in\n    let NOW := (block_timestamp (wst_block_state wst)) in\n    let data' := mk_token_data (data.(tier) + 1) (NOW + 2 * YEAR_TO_SECONDS) in\n    let tokens' := TokenDataMap.upd tokens token data' in\n    (set_state wst (mk_burn_rate_table_state tokens'), data.(tier) + 1) .\n\n  Definition upgradeTokenTier_require (wst: WorldState) : Prop :=\n    exists totalSupply wst' evts,\n      token <> 0\n      /\\ token <> lrcAddress\n      /\\ token <> wethAddress\n      /\\ getTIER token wst <> TIER1\n      /\\ ERC20s.model wst (msg_totalSupply sender lrcAddress)\n                     wst (RetUint totalSupply) nil\n      /\\ ERC20s.model wst (msg_burnFrom (this wst) lrcAddress sender (burnamount totalSupply))\n                     wst' (RetBool true) evts.\n\n  Inductive upgradeTokenTier_trans (wst : WorldState) : WorldState -> RetVal -> Prop :=\n  | upgradeTokenTier_TRANS: forall totalSupply wst' evts TIER wst'' ,\n      ERC20s.model wst (msg_totalSupply sender lrcAddress)\n                   wst (RetUint totalSupply) nil ->\n      ERC20s.model wst (msg_burnFrom (this wst) lrcAddress sender (burnamount totalSupply))\n                   wst' (RetBool true) evts ->\n      upgradetier wst' = (wst'', TIER) ->\n      upgradeTokenTier_trans wst wst'' (RetBool true).\n\n  Inductive upgradeTokenTier_events (wst : WorldState) : list Event -> Prop :=\n  | upgradeTokenTier_EVENTS: forall totalSupply wst' evts TIER wst'' ,\n      ERC20s.model wst (msg_totalSupply sender lrcAddress)\n                   wst (RetUint totalSupply) nil ->\n      ERC20s.model wst (msg_burnFrom (this wst) lrcAddress sender (burnamount totalSupply))\n                   wst' (RetBool true) evts ->\n      upgradetier wst' = (wst'', TIER) ->\n      upgradeTokenTier_events wst (evts ++ EvtTokenTierUpgraded token TIER :: nil).\n\n  Definition upgradeTokenTier_spec : FSpec :=\n    mk_fspec upgradeTokenTier_require upgradeTokenTier_trans upgradeTokenTier_events.\n\nEnd upgradeTokenTier_SPEC.\n\n\nDefinition get_spec (msg: BurnRateTableMsg) : FSpec :=\n  match msg with\n  | msg_getBurnRate sender token => getBurnRate_spec token\n  | msg_getTokenTier sender token => getTokenTier_spec token\n  | msg_upgradeTokenTier sender token => upgradeTokenTier_spec sender token\n  end.\n\nDefinition model\n           (wst: WorldState)\n           (msg: BurnRateTableMsg)\n           (wst': WorldState)\n           (retval: RetVal)\n           (events: list Event)\n  : Prop :=\n  fspec_sat (get_spec msg) wst wst' retval events.", "meta": {"author": "sec-bit", "repo": "loopring-protocol2-verification", "sha": "bfb2101faccbefd592a8f63d42e01aae41b06930", "save_path": "github-repos/coq/sec-bit-loopring-protocol2-verification", "path": "github-repos/coq/sec-bit-loopring-protocol2-verification/loopring-protocol2-verification-bfb2101faccbefd592a8f63d42e01aae41b06930/Models/BurnRateTable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.21920866305048528}}
{"text": "From Coq Require Import ssreflect.\nFrom stdpp Require Import base gmap.\nFrom iris.proofmode Require Import tactics.\nFrom aneris.prelude Require Import time.\nFrom aneris.aneris_lang.lib.serialization Require Import serialization_proof.\nFrom aneris.aneris_lang Require Import aneris_lifting proofmode.\nFrom aneris.examples.crdt.spec Require Import crdt_base crdt_time crdt_events crdt_denot crdt_resources.\nFrom aneris.examples.crdt.oplib Require Import oplib_code.\nFrom aneris.examples.crdt.oplib.spec Require Import model spec.\nFrom aneris.examples.crdt.oplib.examples.lwwreg Require Import lwwreg_code.\nFrom aneris.aneris_lang.lib Require Import inject list_proof.\nFrom aneris.aneris_lang.lib.vector_clock Require Import vector_clock_proof.\nFrom aneris.examples.crdt.oplib.proof Require Import time.\n\n(** Last-writer-wins register. Ties broken by Lamport timestamp plus origin id. *)\nSection LWWRegister.\n\n  Context `{PayloadT : Type}.\n  Context `{!EqDecision PayloadT, !Countable PayloadT}.\n\n  Inductive LWWOp : Type :=\n  | Write (v : PayloadT) : LWWOp.\n\n  Definition lww_payload (op : LWWOp) : PayloadT :=\n    match op with\n    | Write v => v\n    end.\n\n  Global Instance lww_op_eqdecision : EqDecision LWWOp.\n  Proof. solve_decision. Qed.\n\n  Global Instance lww_op_countable : Countable LWWOp.\n  Proof.\n    refine {|\n      encode op := match op with Write v => encode v end;\n      decode n := Write <$> @decode _ _ _ n;\n    |}.\n    intros []. rewrite decode_encode /=. done.\n  Qed.\n\n  (* TODO: make the denotation more generic by not depending on vector clocks.\n     (Needed if we want to implement with state-based CRDTs). *)\n\n  Fixpoint to_lamport (vc : vector_clock) : nat :=\n    match vc with\n    | nil => 0\n    | h :: t => h + to_lamport t\n    end.\n\n  Lemma vector_clock_le_to_lamport_le vc vc' :\n    vector_clock_le vc vc' -> to_lamport vc <= to_lamport vc'.\n  Proof.\n    intros Hle.\n    rewrite /vector_clock_le in Hle.\n    induction Hle; [done | simpl; lia].\n  Qed.\n\n  Lemma vector_clock_lt_to_lamport_lt vc vc' :\n    vector_clock_lt vc vc' -> to_lamport vc < to_lamport vc'.\n  Proof.\n    intros [Hle Hlt].\n    induction Hle; [by inversion Hlt |].\n    simpl.\n    destruct (decide (x = y)) as [-> | Hne].\n    - simpl in Hlt.\n      inversion Hlt as [ | ? ? Htail]; subst; [exfalso; simpl in *; lia |].\n      apply IHHle in Htail; lia.\n    - assert (x < y) as ? by lia.\n      apply vector_clock_le_to_lamport_le in Hle; lia.\n  Qed.\n\n  Definition lww_lt (e e' : Event LWWOp) : Prop :=\n    let ts := to_lamport (EV_Time e) in\n    let ts' := to_lamport (EV_Time e') in\n    (ts < ts') ∨ (ts = ts' ∧ (EV_Orig e) < (EV_Orig e')).\n\n  Global Instance lwwlt_strict : StrictOrder lww_lt.\n  Proof.\n    constructor.\n    - intros e [Hl | [_ Hr]]; [lia | destruct e; lia].\n    - intros a b c [Hlt | [Heq Ho]] [Hlt' | [Heq' Ho']]; try (left; lia).\n      right; split; lia.\n  Qed.\n\n  Definition lww_max (e : Event LWWOp) (s : gset (Event LWWOp)) : Prop :=\n    e ∈ s ∧ (∀ e', e' ∈ s -> e' ≠ e -> lww_lt e' e).\n\n  Definition LWWSt : Type := option (Event LWWOp).\n\n  Definition lww_denot (s : gset (Event LWWOp)) (st : LWWSt) : Prop :=\n    (s = ∅ ∧ st = None) ∨ (∃ e, st = Some e ∧ events_ext s ∧ lww_max e s).\n\n  Global Instance lww_denot_fun : Rel2__Fun lww_denot.\n  Proof.\n    constructor; unfold lww_denot.\n    intros s b b'.\n    intros [[-> ->] |[e [Hbeq [Hext [Hein Hmax]]]]] [[Heq Hb] | [e' (-> & _ & [Hein' Hmax'])]].\n    - done.\n    - exfalso; set_solver.\n    - exfalso.\n      rewrite Heq in Hein.\n      set_solver.\n    - destruct (decide (e = e')) as [-> | Hne]; [done|].\n      assert (e' ≠ e) as Hne'; [done|].\n      pose proof Hein as Hlwwlt.\n      pose proof Hein' as Hlwwlt'.\n      apply Hmax in Hlwwlt'; auto.\n      apply Hmax' in Hlwwlt; auto.\n      destruct Hlwwlt as [He1 | He2]; destruct Hlwwlt' as [He1' | He2'].\n     + exfalso; lia.\n     + destruct He2' as [Heqt _].\n       exfalso; lia.\n     + destruct He2 as [? ?].\n       exfalso; lia.\n     + destruct He2 as [_ Horig].\n       destruct He2' as [_ Horig'].\n       exfalso; lia.\n  Qed.\n\n  Global Instance lww_denot_instance : CrdtDenot LWWOp LWWSt :=\n    { crdt_denot := lww_denot }.\n\nEnd LWWRegister.\n\nGlobal Arguments LWWOp : clear implicits.\n\nSection OpLWWRegister.\n\n  Context (PT : Type). (* payload type *)\n  Context `{!EqDecision PT, !Countable PT}.\n\n  Definition op_lww_register_effect (st : LWWSt) (ev : Event (LWWOp PT)) (st' : LWWSt) : Prop :=\n    (st = None ∧ st' = Some ev) ∨\n      (∃ e, st = Some e ∧\n            ((st' = Some e ∧ lww_lt ev e) ∨\n             (st' = Some ev ∧ lww_lt e ev))).\n\n  Lemma op_lww_register_effect_fun st : Rel2__Fun (op_lww_register_effect st).\n  Proof.\n    constructor.\n    unfold op_lww_register_effect.\n    intros a b b' [Hl | Hr] [Hl' | Hr'].\n    - destruct Hl as [_ ->].\n      destruct Hl' as [_ ->].\n      done.\n    - destruct Hl as [-> ->].\n      destruct Hr' as [e [Heq _]].\n      exfalso.\n      inversion Heq.\n    - destruct Hr as [e [-> Hlt]].\n      destruct Hl' as [Heq _].\n      exfalso.\n      inversion Heq.\n    - destruct Hr as [e [-> [[-> Hltl] | [Heq Hlt]]]];\n      destruct Hr' as [e' [Heqe [[-> Hltl'] | [Heq' Hlt']]]].\n      + done.\n      + assert (e = e') as ->; [inversion Heqe; done|].\n        exfalso.\n        apply (irreflexivity lww_lt a).\n        eapply transitivity; eauto.\n      + assert (e = e') as ->; [inversion Heqe; done|].\n        exfalso.\n        apply (irreflexivity lww_lt a).\n        eapply transitivity; eauto.\n      + rewrite Heq Heq'; done.\n  Qed.\n\n  Lemma lww_max_singleton (ev : Event (LWWOp PT)) : lww_max ev {[ev]}.\n  Proof.\n    split; [set_solver|].\n    intros e' ->%elem_of_singleton Hne.\n    exfalso.\n    by apply Hne.\n  Qed.\n\n  Lemma lww_max_singleton' (e e' : Event (LWWOp PT)) : lww_max e {[e']} -> e = e'.\n  Proof.\n    intros [->%elem_of_singleton _]; done.\n  Qed.\n\n  Hint Resolve lww_max_singleton : core.\n  Hint Resolve events_ext_singleton : core.\n\n  Instance op_lww_register_effect_coh : OpCrdtEffectCoh op_lww_register_effect.\n  Proof.\n    intros s ev st st' [[-> ->] | [e [Heq [_ Hlww]]]] Hnotin Hmax Hevs_ext Htot.\n    - split.\n      + intros [[_ ->] | [e [He _]]].\n        * right; exists ev.\n          assert (∅ ∪ {[ev]} = {[ev]}) as ->; [set_solver|].\n          eauto.\n        * exfalso; inversion He.\n      + intros [[Heq _] | [e [Heq [Hext Hmax']]]].\n        * exfalso; set_solver.\n        * left.\n          rewrite Heq.\n          assert (∅ ∪ {[ev]} = ({[ev]} : gset (Event (LWWOp PT)))) as Hset.\n          { set_solver. }\n          rewrite Hset in Hmax'.\n          apply lww_max_singleton' in Hmax' as ->.\n          done.\n    - split.\n      + intros [[-> ->] | [e' [-> [[-> Hlt] | [-> Hlt]]]]].\n        * exfalso.\n          inversion Heq.\n        * inversion Heq; subst.\n          right.\n          assert (lww_max e (s ∪ {[ev]})) as ?; [ | by eauto].\n          destruct Hlww as [Hein Hemax].\n          split; [set_solver|].\n          intros e' [Hein' | ->%elem_of_singleton]%elem_of_union Hne; [|done].\n          apply Hemax; done.\n        * right.\n          assert (lww_max ev (s ∪ {[ev]})) as ?; [ | by eauto].\n          split; [set_solver|].\n          intros e'' [Hein' | ->%elem_of_singleton]%elem_of_union Hne; [|done].\n          inversion Heq; subst.\n          destruct (decide (e'' = e)) as [-> | Hne']; [done|].\n          destruct Hlww as [_ Hemax].\n          apply Hemax in Hein'; [|done].\n          eapply transitivity; eauto.\n      + intros [[Hnone _] | Hsome]; [set_solver|].\n        destruct Hsome as [e' (-> & Hext' & Hmax')].\n        rewrite Heq.\n        destruct Hmax' as [[Hein' | ->%elem_of_singleton]%elem_of_union Hmax'].\n        * destruct (decide (e = e')) as [-> | Hne].\n          ** right.\n             exists e'. split; [done|].\n             left; split; [done|].\n             apply Hmax'; [set_solver|].\n             intros ->.\n             apply Hnotin; done.\n          ** exfalso.\n             apply (irreflexivity lww_lt e).\n             destruct Hlww as [Hin Hlww].\n             apply Hlww in Hein'; [|done].\n             assert (e ∈ s ∪ {[ev]}) as Hein; [set_solver|].\n             apply Hmax' in Hein; [|done].\n             eapply transitivity; eauto.\n        * right; exists e.\n          split; [done|].\n          right.\n          destruct Hlww as [Hin Hlww].\n          assert (e ∈ s ∪ {[ev]}) as Hein; [set_solver|].\n          split; [done|].\n          apply Hmax'; [set_solver|].\n          intros ->.\n          apply Hnotin; done.\n  Qed.\n\n  Definition op_lww_register_init_st : @LWWSt PT := None.\n\n  Lemma op_lww_register_init_st_coh : ⟦ (∅ : gset (Event (LWWOp PT))) ⟧ ⇝ op_lww_register_init_st.\n  Proof. by left. Qed.\n\n  Global Instance op_lww_register_model_instance : OpCrdtModel (LWWOp PT) LWWSt := {\n    op_crdtM_effect := op_lww_register_effect;\n    op_crdtM_effect_fun := op_lww_register_effect_fun;\n    op_crdtM_effect_coh := op_lww_register_effect_coh;\n    op_crdtM_init_st := op_lww_register_init_st;\n    op_crdtM_init_st_coh := op_lww_register_init_st_coh\n  }.\n\nEnd OpLWWRegister.\n\n\nSection LWWreg_proof.\n  Context `{PayloadT : Type}.\n  Context `{!EqDecision PayloadT, !Countable PayloadT}.\n  Context `{!Inject PayloadT val}.\n  Context `{!∀ p : PayloadT, Serializable vl_serialization $ p}.\n  Context `{!anerisG M Σ}.\n\n  (* TODO: generalize the payload type *)\n  Notation LWWOp' := (LWWOp PayloadT).\n  Notation LWWSt' := (@LWWSt PayloadT).\n  Notation Event' := (Event LWWOp').\n\n  Context `{!CRDT_Params, !OpLib_Res LWWOp'}.\n\n  Definition lww_register_OpLib_Op_Coh := λ (op : LWWOp') v, match op with Write z => v = $z end.\n\n  Lemma lww_register_OpLib_Op_Coh_Inj (o1 o2 : LWWOp') (v : val) :\n    lww_register_OpLib_Op_Coh o1 v → lww_register_OpLib_Op_Coh o2 v → o1 = o2.\n  Proof. destruct o1; destruct o2; simpl; intros ? ?; simplify_eq; done. Qed.\n\n  Lemma lww_register_OpLib_Coh_Ser (op : LWWOp') (v : val) :\n    lww_register_OpLib_Op_Coh op v → Serializable vl_serialization v.\n  Proof.\n    destruct op; rewrite /lww_register_OpLib_Op_Coh; intros ?; simplify_eq; apply _.\n  Qed.\n\n  (* TODO: move to the right place. *)\n  Global Instance vector_clock_inject : Inject vector_clock val :=\n    { inject := vector_clock_to_val }.\n\n  Definition lww_register_OpLib_State_Coh (st : LWWSt') (v : val) : Prop :=\n    (v = NONEV ∧ st = None) ∨\n    (∃ w ev, v = SOMEV w ∧\n             st = Some ev ∧\n             w = PairV (PairV $(lww_payload (EV_Op ev)) $(EV_Time ev)) #(EV_Orig ev)).\n\n  Global Instance LWW_OpLib_Params : OpLib_Params LWWOp' LWWSt' :=\n  {|\n    OpLib_Serialization := vl_serialization;\n    OpLib_State_Coh := lww_register_OpLib_State_Coh;\n    OpLib_Op_Coh := lww_register_OpLib_Op_Coh;\n    OpLib_Op_Coh_Inj := lww_register_OpLib_Op_Coh_Inj;\n    OpLib_Coh_Ser := lww_register_OpLib_Coh_Ser\n  |}.\n\n  Lemma lww_register_init_st_fn_spec : ⊢ init_st_fn_spec lwwreg_init_st.\n  Proof.\n    iIntros (addr).\n    iIntros \"!#\" (Φ) \"_ HΦ\".\n    rewrite /lwwreg_init_st.\n    wp_pures.\n    iApply \"HΦ\".\n    iPureIntro.\n    left; done.\n  Qed.\n\n  Lemma wp_vc_to_lamport addr vcv vc :\n    {{{ ⌜is_vc vcv vc⌝ }}}\n      vc_to_lamport vcv @[ip_of_address addr]\n    {{{ l, RET #l; ⌜l = to_lamport vc⌝ }}}.\n  Proof.\n    generalize dependent vcv.\n    induction vc as [ | h t IH]; iIntros (vcv Φ) \"%Hvc HΦ\"; rewrite /vc_to_lamport;\n      inversion Hvc; subst.\n    - wp_pures; iApply (\"HΦ\" $! 0); done.\n    - match goal with\n      | [ H : vcv = _ ∧ _ |- _ ] => destruct H as [-> Hislist]\n      end.\n      do 10 wp_pure _.\n      wp_apply IH; [done|].\n      iIntros (l) \"%Htolamp\"; wp_pures.\n      assert ((Z.add (Z.of_nat h) (Z.of_nat l)) = Z.of_nat (h + l)) as -> by lia.\n      iApply \"HΦ\"; iPureIntro.\n      rewrite Htolamp; simpl; done.\n  Qed.\n\n  (* TODO: move to vector clock file *)\n  Lemma wp_vect_eq vcv1 vcv2 vc1 vc2 addr :\n    {{{ ⌜is_vc vcv1 vc1⌝ ∗ ⌜is_vc vcv2 vc2⌝ }}}\n      vect_eq vcv1 vcv2 @[ip_of_address addr]\n    {{{ (b : bool), RET #b; ⌜b = true <-> vc1 = vc2⌝}}}.\n  Proof.\n    iIntros (Φ) \"[%Hvc1 %Hvc2] HΦ\"; rewrite /vect_eq; wp_pures.\n    wp_apply wp_vect_leq; [done|].\n    iIntros (v) \"->\".\n    destruct (bool_decide_reflect (vector_clock_le vc1 vc2)) as [Hle | Hne]; wp_pures.\n    - wp_apply wp_vect_leq; [done|].\n      iIntros (v') \"->\".\n      destruct (bool_decide_reflect (vector_clock_le vc2 vc1)) as [Hle' | Hne'];\n        wp_pures; iApply \"HΦ\"; iPureIntro; split; intros Heq; [| done | done | ].\n      + apply (@anti_symm _ _ vector_clock_le); [apply _| done | done].\n      + exfalso; apply Hne'; rewrite Heq; apply reflexivity.\n    - iApply \"HΦ\"; iPureIntro; split; [done|];\n        intros Heq; exfalso; apply Hne; rewrite Heq; apply reflexivity.\n  Qed.\n\n  Lemma wp_vect_lt vcv1 vcv2 vc1 vc2 addr :\n    {{{ ⌜is_vc vcv1 vc1⌝ ∗ ⌜is_vc vcv2 vc2⌝ }}}\n      vect_lt vcv1 vcv2 @[ip_of_address addr]\n    {{{ (b : bool), RET #b; ⌜b = true <-> vector_clock_lt vc1 vc2⌝ }}}.\n  Proof.\n    iIntros (Φ) \"[%Hvc1 %Hvc2] HΦ\"; rewrite /vect_lt; wp_pures.\n    wp_apply wp_vect_leq; [done |].\n    iIntros (v) \"->\".\n    destruct (bool_decide_reflect (vector_clock_le vc1 vc2)) as [Hle | Hne]; wp_pures.\n    - wp_apply wp_vect_eq; [done|].\n      iIntros (b) \"%Hb\".\n      destruct b; wp_pures; iApply \"HΦ\"; iPureIntro; split; intros Harg.\n      + inversion Harg.\n      + pose proof ((iffLR Hb) eq_refl) as ->.\n        apply vector_clock_lt_irreflexive in Harg; done.\n      + apply vector_clock_le_eq_or_lt in Hle as [-> | Hne]; [ | done].\n        exfalso; pose proof ((iffRL Hb) eq_refl) as ?; done.\n      + done.\n    - iApply \"HΦ\"; iPureIntro; split; [done| intros Hlt].\n      exfalso; apply Hne; by apply vector_clock_lt_le.\n  Qed.\n\n  Definition is_ts (vc : vector_clock) (orig : nat) (v : val) :=\n    ∃ vcv, v = PairV vcv #orig ∧ is_vc vcv vc.\n\n  Definition ts_lt vc1 orig1 vc2 orig2 :=\n    let l1 := to_lamport vc1 in\n    let l2 := to_lamport vc2 in\n    (l1 < l2) ∨ (l1 = l2 ∧ orig1 < orig2).\n\n  Lemma ts_lt_lww_lt (ev1 ev2 : Event') :\n    ts_lt (EV_Time ev1) (EV_Orig ev1) (EV_Time ev2) (EV_Orig ev2) -> lww_lt ev1 ev2.\n  Proof.\n    intros [Hlt1 | Hlt2]; [left | right]; done.\n  Qed.\n\n  Lemma wp_tstamp_lt vc1 orig1 vc2 orig2 tsv1 tsv2 addr :\n    {{{ ⌜is_ts vc1 orig1 tsv1⌝ ∗ ⌜is_ts vc2 orig2 tsv2⌝ }}}\n      tstamp_lt tsv1 tsv2 @[ip_of_address addr]\n    {{{ b, RET #b; ⌜b = true <-> ts_lt vc1 orig1 vc2 orig2⌝ }}}.\n  Proof.\n    iIntros (Φ) \"[%Hvc1 %Hvc2] HΦ\"; rewrite /tstamp_lt; wp_pures.\n    destruct Hvc1 as [vcv1 [-> Hvc1]]; destruct Hvc2 as [vcv2 [-> Hvc2]]; wp_pures.\n    wp_apply wp_vc_to_lamport; [done |]; iIntros (l1) \"%Hl1\"; wp_pures.\n    wp_apply wp_vc_to_lamport; [done |]; iIntros (l2) \"%Hl2\"; wp_pures.\n    destruct (bool_decide_reflect (l1 < l2)%Z) as [Hle | Hnle]; wp_pures.\n    - iApply \"HΦ\"; iPureIntro; split; [ | done].\n      intros _; left; lia.\n    - destruct (bool_decide_reflect (@eq Z l1 l2)%Z) as [Heq | Hne]; wp_pures.\n      + destruct (bool_decide_reflect (orig1 < orig2)%Z) as [Hlo | Hnlo]; iApply \"HΦ\";\n          iPureIntro.\n        * split; [|done].\n          intros _; right.\n          rewrite <- Hl1, <- Hl2; auto with lia.\n        * split; [done| intros [Hlt1 | [_ Hlt2]]]; lia.\n      + iApply \"HΦ\"; iPureIntro; split; [done | intros [Hlt1 | Hlt2]]; lia.\n  Qed.\n\n  Lemma lww_register_effect_spec : ⊢ effect_spec lwwreg_effect.\n  Proof.\n    iIntros (addr ev st s log_ev log_st).\n    iIntros \"!#\" (Φ) \"(%Hev & %Hst & %Hs & %Hevs) HΦ\".\n    rewrite /lwwreg_effect.\n    destruct log_ev as [[op] orig vc].\n    destruct Hev as (evpl&evvc&evorig&?&Hevpl&Hisvc&?).\n    destruct Hevs as (Hev & Hmax & Hext & Htot).\n    simplify_eq/=.\n    wp_pures.\n    destruct Hst as [[-> ->] | Hsome].\n    - wp_pures.\n      iApply \"HΦ\".\n      iPureIntro.\n      set ev := (@Build_Event vc_time LWWOp' (Write op) orig vc).\n      exists (Some ev).\n      split.\n      + right.\n        eexists _, ev.\n        split; [eauto|].\n        apply is_vc_vector_clock_to_val in Hisvc.\n        assert (time {| EV_Op := Write op; EV_Orig := orig; EV_Time := vc |} = vc) as Heq.\n        { compute. done. }\n        rewrite Heq in Hisvc.\n        rewrite <- Hisvc.\n        done.\n      + by left.\n    - destruct Hsome as [w [ev (-> & -> & ->)]].\n      wp_pures.\n      rewrite /assert.\n      wp_apply wp_tstamp_lt; [iPureIntro|].\n      { split; last first.\n        + rewrite /is_ts; eexists; eauto.\n        +  rewrite /is_ts; eexists; split; [eauto| eapply vector_clock_to_val_is_vc]. }\n      iIntros (b) \"%Hts\".\n      destruct b; wp_pures.\n      + iApply \"HΦ\"; iPureIntro.\n        set new_ev := (@Build_Event vc_time LWWOp' (Write op) orig vc).\n        exists (Some new_ev).\n        split.\n        * right.\n          exists (PairV (PairV $op evvc) #orig), new_ev.\n          repeat split; try eauto.\n          subst new_ev; simpl.\n          apply is_vc_vector_clock_to_val in Hisvc.\n          assert (time {| EV_Op := Write op; EV_Orig := orig; EV_Time := vc |} = vc) as Heq.\n          { compute; done. }\n          rewrite Heq in Hisvc; rewrite Hisvc; done.\n        * right; exists ev; split; [done|]; right; split; [done|].\n          apply ts_lt_lww_lt.\n          apply Hts; done.\n      + wp_apply wp_tstamp_lt; [iPureIntro|].\n        { split; last first.\n          +  rewrite /is_ts; eexists; split; [eauto| eapply vector_clock_to_val_is_vc].\n          + rewrite /is_ts; eexists; eauto. }\n        iIntros (b') \"%Hts'\".\n        destruct b'; wp_pures.\n        * iApply \"HΦ\".\n          iPureIntro. exists (Some ev); split.\n          ** right. exists (PairV (PairV $(lww_payload (EV_Op ev)) (vector_clock_to_val (EV_Time ev))) #(EV_Orig ev)).\n             eauto.\n          ** right. exists ev. split; [done|]. left. split; [done|].\n             apply ts_lt_lww_lt.\n             simpl in *.\n             assert (time {| EV_Op := Write op; EV_Orig := orig; EV_Time := vc |} = vc) as Heq.\n             { compute; done. }\n             rewrite Heq in Hts'.\n             by apply Hts'.\n        * exfalso.\n          assert (time {| EV_Op := Write op; EV_Orig := orig; EV_Time := vc |} = vc) as Heq.\n          { compute; done. }\n          rewrite Heq in Hts. rewrite Heq in Hts'.\n          destruct (decide (to_lamport (EV_Time ev) < to_lamport vc)) as [Hlt | Hnlt].\n          ** assert (ts_lt (EV_Time ev) (EV_Orig ev) vc orig) as Hcontra.\n             { left; done. }\n             apply Hts in Hcontra.\n             inversion Hcontra.\n          ** destruct (decide (to_lamport vc < to_lamport (EV_Time ev))) as [Hlt' | Hnlt'].\n             { assert (ts_lt vc orig (EV_Time ev) (EV_Orig ev)) as Hcontra.\n               { left; done. }\n               apply Hts' in Hcontra.\n               inversion Hcontra. }\n             assert (to_lamport (EV_Time ev) = to_lamport vc) as Hleq by lia.\n             destruct (decide (orig < (EV_Orig ev))) as [Holt | Honlt].\n             { assert (ts_lt vc orig (EV_Time ev) (EV_Orig ev)) as Hcontra.\n               { right; done. }\n               apply Hts' in Hcontra.\n               inversion Hcontra. }\n             destruct (decide ((EV_Orig ev) < orig)) as [Holt' | Honlt'].\n             { assert (ts_lt (EV_Time ev) (EV_Orig ev) vc orig ) as Hcontra.\n               { right; done. }\n               apply Hts in Hcontra.\n               inversion Hcontra. }\n             assert (orig = (EV_Orig ev)) as Hoeq by lia.\n             set new_ev := (@Build_Event vc_time LWWOp' (Write op) orig vc).\n             destruct Hs as [[_ Hnone] | [e [Heeq [_ [Hein Hemax]]]]]; [inversion Hnone; done|].\n             simplify_eq /=.\n             assert (e ∈ s ∪ {[{| EV_Op := Write op; EV_Orig := EV_Orig e; EV_Time := vc |}]}) as Hin1; [set_solver|].\n             assert (new_ev ∈ s ∪ {[{| EV_Op := Write op; EV_Orig := EV_Orig e; EV_Time := vc |}]}) as Hin2; [set_solver|].\n             assert (e ≠ new_ev) as Hne.\n             { intros contra.\n               apply Hev.\n               subst new_ev. rewrite <- contra.\n               done. }\n             pose proof (Htot e new_ev Hin1 Hin2 Hne eq_refl) as\n               [Hlt1%vector_clock_lt_to_lamport_lt | Hlt2%vector_clock_lt_to_lamport_lt].\n             *** rewrite /time /Event_Timed in Hlt1; simpl in Hlt1; done.\n             *** rewrite /time /Event_Timed in Hlt2; simpl in Hlt2; done.\n  Qed.\n\n  Lemma lww_register_crdt_fun_spec : ⊢ crdt_fun_spec lwwreg_crdt.\n  Proof.\n    iIntros (addr).\n    iIntros \"!#\" (Φ) \"_ HΦ\".\n    rewrite /lwwreg_crdt.\n    wp_pures.\n    iApply \"HΦ\".\n    iExists _, _; iSplit; first done.\n    iSplit; [iApply lww_register_init_st_fn_spec|iApply lww_register_effect_spec].\n  Qed.\n\n  Lemma lww_init_spec :\n    init_spec (oplib_init\n               (s_ser (s_serializer OpLib_Serialization))\n               (s_deser (s_serializer OpLib_Serialization))) -∗\n    init_spec_for_specific_crdt \n    (lwwreg_init (s_ser (s_serializer vl_serialization)) (s_deser (s_serializer vl_serialization))).\n  Proof.\n    iIntros \"#Hinit\" (repId addr addrs_val).\n    iIntros (Φ) \"!# (%Haddrs & %Hrepid & Hprotos & Hskt & Hfr & Htoken) HΦ\".\n    rewrite /lwwreg_init.\n    wp_pures.\n    wp_apply (\"Hinit\" with \"[$Hprotos $Htoken $Hskt $Hfr]\").\n    { do 2 (iSplit; first done). iApply lww_register_crdt_fun_spec; done. }\n    iIntros (get update) \"(HLS & #Hget & #Hupdate)\".\n    wp_pures.\n    iApply \"HΦ\"; eauto.\n  Qed.\n\nEnd LWWreg_proof.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/crdt/oplib/examples/lwwreg/lwwreg_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.21920866203719214}}
{"text": "(** * Theorems for [ITree.Interp.Handler] *)\n\n(* begin hide *)\nFrom Coq Require Import\n     Setoid\n     Morphisms\n     RelationClasses.\n\nFrom Paco Require Import paco.\n\nFrom ITree Require Import\n     Basics.Basics\n     Basics.Category\n     Core.ITreeDefinition\n     Eq.Eq\n     Eq.UpToTaus\n     Indexed.Sum\n     Interp.Interp\n     Interp.Handler\n     Interp.TranslateFacts\n     Interp.InterpFacts\n     Interp.RecursionFacts.\n\nImport ITreeNotations.\nImport ITree.Basics.Basics.Monads.\n\nLocal Open Scope itree_scope.\n\n(* end hide *)\n\nSection HandlerCategory.\n\nLocal Opaque eutt ITree.bind interp ITree.trigger.\n\nInstance Proper_Cat_Handler {A B C}\n  : @Proper (Handler A B -> Handler B C -> Handler A C)\n            (eq2 ==> eq2 ==> eq2)\n            cat.\nProof.\n  cbv; intros.\n  apply eutt_interp; auto.\nQed.\n\nInstance CatIdR_Handler : CatIdR Handler.\nProof.\n  cbv; intros.\n  rewrite interp_trigger_h. reflexivity.\nQed.\n\nInstance CatIdL_Handler : CatIdL Handler.\nProof.\n  cbv; intros.\n  rewrite interp_trigger.\n  reflexivity.\nQed.\n\nInstance CatAssoc_Handler : CatAssoc Handler.\nProof.\n  cbv; intros.\n  rewrite interp_interp.\n  reflexivity.\nQed.\n\nGlobal Instance Category_Handler : Category Handler.\nProof.\n  split; typeclasses eauto.\nQed.\n\nGlobal Instance InitialObject_Handler : InitialObject Handler void1.\nProof.\n  cbv; contradiction.\nQed.\n\nInstance Proper_Case_Handler {A B C}\n  : @Proper (Handler A C -> Handler B C -> Handler (A +' B) C)\n            (eq2 ==> eq2 ==> eq2)\n            case_.\nProof.\n  cbv; intros.\n  destruct (_ : sum1 _ _ _); auto.\nQed.\n\nInstance CaseInl_Handler : CaseInl Handler sum1.\nProof.\n  cbv; intros.\n  rewrite interp_trigger.\n  reflexivity.\nQed.\n\nInstance CaseInr_Handler : CaseInr Handler sum1.\nProof.\n  cbv; intros.\n  rewrite interp_trigger.\n  reflexivity.\nQed.\n\nInstance CaseUniversal_Handler : CaseUniversal Handler sum1.\nProof.\n  cbv; intros.\n  destruct (_ : sum1 _ _ _).\n  - rewrite <- H, interp_trigger. reflexivity.\n  - rewrite <- H0, interp_trigger. reflexivity.\nQed.\n\nGlobal Instance Coproduct_Handler : Coproduct Handler sum1.\nProof.\n  split; typeclasses eauto.\nQed.\n\nLocal Opaque Recursion.interp_mrec.\n\nInstance Proper_Iter_Handler {A B}\n  : @Proper (Handler A (A +' B) -> Handler A B)\n            (eq2 ==> eq2)\n            iter.\nProof.\n  repeat intro.\n  apply Proper_interp_mrec; auto.\nQed.\n\nInstance IterUnfold_Handler : IterUnfold Handler sum1.\nProof.\n  cbv; intros.\n  rewrite interp_mrec_as_interp.\n  reflexivity.\nQed.\n\nInstance IterNatural_Handler : IterNatural Handler sum1.\nProof.\n  cbv; intros.\n  pattern f.\n  match goal with\n  | [ |- ?G ?f ] =>\n    enough (HHH : G (fun T e => Tau (f T e))); cbn in *\n  end.\n  { etransitivity; [etransitivity; [|eapply HHH] |]; clear.\n    - symmetry. apply euttge_sub_eutt, euttge_interp.\n      + reflexivity.\n      + apply euttge_interp_mrec; repeat intro; apply tau_euttge.\n    - apply euttge_sub_eutt, euttge_interp_mrec.\n      + intros ? ?. apply euttge_interp.\n        * reflexivity.\n        * apply tau_euttge.\n      + rewrite tau_euttge. reflexivity.\n  }\n  match goal with\n  | [ |- _ _ (_ _ _ (_ ?h0 _ _)) ] =>\n    remember h0 as h eqn:EQh\n    (* h is pretty big and duplicating it slows down the display of the goal,\n       so we try to rewrite with EQh only when necessary. *)\n  end.\n  remember (Tau (f T a0)) as t eqn:tmp_t. clear tmp_t.\n  revert t; einit; ecofix CIH; intros t.\n  rewrite (itree_eta t).\n  destruct (observe t).\n  - rewrite unfold_interp_mrec; cbn.\n    rewrite 2 interp_ret.\n    rewrite unfold_interp_mrec.\n    reflexivity.\n  - rewrite unfold_interp_mrec; cbn.\n    rewrite 2 interp_tau.\n    rewrite (unfold_interp_mrec _ _ (Tau _)); cbn.\n    estep.\n  - rewrite unfold_interp_mrec; cbn.\n    rewrite interp_vis.\n    destruct e; cbn.\n    + rewrite interp_tau.\n      rewrite 2 interp_mrec_bind, interp_bind.\n      subst h; cbn.\n      rewrite interp_trigger.\n      rewrite unfold_interp_mrec; cbn.\n      rewrite interp_mrec_trigger; cbn.\n      unfold Recursion.mrec.\n      rewrite !interp_tau.\n      rewrite (unfold_interp_mrec _ _ (Tau _)); cbn.\n      rewrite !bind_tau.\n      etau. rewrite tau_euttge, <- interp_bind, <- 2 interp_mrec_bind.\n      setoid_rewrite (tau_euttge (interp _ _)).\n      rewrite <- interp_bind.\n      auto with paco.\n    + rewrite interp_vis.\n      rewrite interp_mrec_bind.\n      subst h; cbn.\n      Local Transparent eutt.\n      ebind. apply (pbc_intro_h _ _ _ _ _ eq).\n      { rewrite interp_mrec_as_interp, interp_interp.\n        rewrite <- interp_id_h at 1.\n        eapply eutt_interp; try reflexivity.\n        intros ? ?.\n        rewrite interp_trigger; cbn.\n        reflexivity. }\n      intros ? _ [].\n      rewrite (unfold_interp_mrec _ _ (Tau _)); cbn.\n      etau.\n      rewrite tau_euttge.\n      auto with paco.\nQed.\n\nSection DinatSimulation.\n\nContext {A B C : Type -> Type}.\nContext (f0 : A ~> itree (B +' C)) (g0 : B ~> itree (A +' C)).\nContext {R : Type}.\n\nContext (f := fun T e => Tau (f0 T e)) (g := fun T e => Tau (g0 T e)).\n\nInductive interleaved\n  : itree (A +' C) R -> itree (B +' C) R -> Prop :=\n| interleaved_Ret r : interleaved (Ret r) (Ret r)\n| interleaved_Left {U} (t : itree _ U) k1 k2 :\n    (forall (x : U), interleaved (k1 x) (k2 x)) ->\n    interleaved (interp (handle (case_ g inr_)) t >>= k1) (t >>= k2)\n| interleaved_Right {U} (t : itree _ U) k1 k2 :\n    (forall (x : U), interleaved (k1 x) (k2 x)) ->\n    interleaved (t >>= k1) (interp (handle (case_ f inr_)) t >>= k2)\n.\nHint Constructors interleaved: core.\n\nLet hg := @case_ _ Handler _ _ _ _ _ g inr_.\nLet hf := @case_ _ Handler _ _ _ _ _ f inr_.\n\nTheorem interleaved_mrec : forall t1 t2,\n    interleaved t1 t2 ->\n    Recursion.interp_mrec (cat f (case_ g inr_)) t1\n  ≈ Recursion.interp_mrec (cat g (case_ f inr_)) t2.\nProof.\n  einit; ecofix CIH; intros.\n  induction H0.\n  - rewrite 2 unfold_interp_mrec; cbn. estep.\n  - rewrite (itree_eta t); destruct (observe t).\n    + rewrite interp_ret, 2 bind_ret_l. auto.\n    + rewrite interp_tau, 2 bind_tau, 2 unfold_interp_mrec; cbn.\n      estep.\n    + rewrite interp_vis, bind_vis.\n      rewrite bind_bind.\n      rewrite (unfold_interp_mrec _ _ (Vis _ _)); cbn.\n      destruct e; cbn. setoid_rewrite (tau_euttge (interp _ _)).\n      * unfold cat at 3, Cat_Handler at 3, Handler.cat.\n        change (g X b) with (Tau (g0 X b)).\n        rewrite bind_tau, unfold_interp_mrec; cbn.\n        etau. rewrite tau_euttge. ebase.\n      * unfold inr_, Inr_sum1_Handler, Handler.inr_, Handler.htrigger.\n        rewrite bind_trigger.\n        rewrite unfold_interp_mrec; cbn.\n        evis; intros; etau. rewrite tau_euttge. ebase.\n  - rewrite (itree_eta t); destruct (observe t).\n    + rewrite interp_ret, 2 bind_ret_l. auto.\n    + rewrite interp_tau, 2 bind_tau, 2 unfold_interp_mrec; cbn.\n      estep.\n    + rewrite interp_vis, bind_vis.\n      rewrite bind_bind.\n      rewrite (unfold_interp_mrec _ _ (Vis _ _)); cbn.\n      destruct e; cbn. setoid_rewrite (tau_euttge (interp _ _)).\n      * unfold cat at 2, Cat_Handler at 2, Handler.cat.\n        change (f X a) with (Tau (f0 X a)).\n        rewrite !bind_tau, (unfold_interp_mrec _ _ (Tau _)); cbn.\n        etau. rewrite tau_euttge. ebase.\n      * unfold inr_, Inr_sum1_Handler, Handler.inr_, Handler.htrigger.\n        rewrite bind_trigger.\n        rewrite unfold_interp_mrec; cbn.\n        evis; intros; etau. rewrite tau_euttge. ebase.\nQed.\n\nEnd DinatSimulation.\n\nLocal Opaque eutt.\nLocal Transparent ITree.trigger.\n\nInstance IterDinatural_Handler : IterDinatural Handler sum1.\nProof.\n  cbv; intros a b c f0 g0 T a0.\n  pose (f := fun T e => Tau (f0 T e)). pose (g := fun T e => Tau (g0 T e)).\n  enough (\n      Recursion.interp_mrec (cat f (case_ g inr_))\n                            (interp (case_ g inr_) (f _ a0))\n    ≈ interp (mrecursive (cat g (case_ f inr_))) (f _ a0)).\n  { cbv in H. etransitivity; [etransitivity; [|apply H]|]; clear H.\n    - symmetry. apply euttge_sub_eutt, euttge_interp_mrec.\n      1: intros ? ?.\n      1,2: rewrite tau_euttge; apply euttge_interp; try reflexivity.\n      1,2: intros ? []; [apply tau_euttge| reflexivity].\n    - apply euttge_sub_eutt, euttge_interp; [ | apply tau_euttge].\n      intros ? []; try reflexivity.\n      rewrite tau_euttge. apply euttge_interp_mrec.\n      intros ? ?.\n      rewrite tau_euttge.\n      all: apply euttge_interp; try reflexivity.\n      all: intros ? []; [apply tau_euttge | reflexivity].\n  }\n  rewrite <- interp_mrec_as_interp.\n\n  rewrite <- (bind_ret_r (interp _ _)).\n  rewrite <- (bind_ret_r (f _ a0)) at 2.\n\n  apply interleaved_mrec.\n  do 2 constructor.\nQed.\n\nLocal Opaque ITree.trigger.\n\nImport Recursion.\n\nInstance IterCodiagonal_Handler : IterCodiagonal Handler sum1.\nProof.\n  cbv; intros a b f0 T x.\n  remember (f0 T x) as t eqn:EQt; clear.\n  pose (f := fun T e => Tau (f0 T e)).\n  enough (interp_mrec (fun _ d => interp_mrec f (f _ d))\n                      (interp_mrec f t)\n          ≈ interp_mrec (fun _ e => interp (fun _ ab =>\n                                              match ab with\n                                              | inl1 x => ITree.trigger (inl1 x)\n                                              | inr1 y => ITree.trigger y\n                                              end) (f _ e))\n                        (interp (fun _ ab =>\n                                   match ab with\n                                   | inl1 x => ITree.trigger (inl1 x)\n                                   | inr1 y => ITree.trigger y\n                                   end) t)).\n  { subst f. etransitivity; [etransitivity; [| apply H] |]; clear H.\n    - symmetry. apply euttge_sub_eutt, euttge_interp_mrec.\n      + intros ? ?. apply euttge_interp_mrec; try apply tau_euttge.\n        intros ? ?. apply tau_euttge.\n      + apply euttge_interp_mrec; repeat intro; reflexivity + rewrite tau_euttge.\n        reflexivity.\n    - apply euttge_sub_eutt, euttge_interp_mrec; repeat intro;\n        apply euttge_interp; try reflexivity.\n      apply tau_euttge.\n  }\n  revert t. einit; ecofix CIH. intros.\n  rewrite (itree_eta t); destruct (observe t); cbn.\n  all: rewrite (unfold_interp_mrec _ _ (go _)), unfold_interp; cbn.\n  1,2: rewrite unfold_interp_mrec; cbn.\n  1,2: rewrite (unfold_interp_mrec _ _ (go _)); estep.\n  destruct e.\n  - rewrite (interp_mrec_bind _ (ITree.trigger _)).\n    rewrite interp_mrec_trigger; cbn.\n    unfold Recursion.mrec.\n    remember (f X a0) as fxa eqn:Hfxa; unfold f in Hfxa; subst fxa.\n    rewrite interp_tau, unfold_interp_mrec; cbn.\n    rewrite (unfold_interp_mrec _ _ (Tau _)); cbn.\n    rewrite !bind_tau.\n    etau.\n    rewrite tau_euttge. setoid_rewrite tau_euttge.\n    rewrite <- interp_mrec_bind, <- interp_bind.\n    auto with paco.\n  - rewrite bind_trigger.\n    setoid_rewrite tau_euttge.\n    rewrite 2 unfold_interp_mrec; cbn.\n    destruct s; estep.\n    rewrite <- interp_mrec_bind, <- interp_bind.\n    auto with paco.\nQed.\n\nGlobal Instance Iterative_Handler : Iterative Handler sum1.\nProof.\n  split; typeclasses eauto.\nQed.\n\nEnd HandlerCategory.\n", "meta": {"author": "euisuny", "repo": "icfp22-layered-monadic-interpreters", "sha": "c3998f90613d1213585aaddf265fd463b77e4f8a", "save_path": "github-repos/coq/euisuny-icfp22-layered-monadic-interpreters", "path": "github-repos/coq/euisuny-icfp22-layered-monadic-interpreters/icfp22-layered-monadic-interpreters-c3998f90613d1213585aaddf265fd463b77e4f8a/src/theories/Interp/HandlerFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.36296919173767833, "lm_q1q2_score": 0.21920864955216507}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import qsort3.\nRequire Import spec_qsort3.\nRequire Import float_lemmas.\nRequire Import Permutation.\nRequire Import qsort3_aux.\nRequire Import verif_qsort3_part1.\nRequire Import verif_qsort3_part2.\n\nLemma body_quicksort_while_part2:\nforall (Espec : OracleKind) (base : val) (al : list val) \n  (lo mid hi : Z) (bl : list val),\nForall def_float al ->\nlet N := Zlength al in\n0 < N <= Z.min Int.max_signed (Ptrofs.max_signed / 8) ->\nisptr base ->\n0 <= lo <= mid ->\nmid < hi < N ->\nf_cmp Cle (Znth lo bl) (Znth mid bl) ->\nf_cmp Cle (Znth mid bl) (Znth hi bl) ->\nPermutation al bl ->\nsorted (f_cmp Cle) (sublist 0 lo bl) ->\nsorted (f_cmp Cle) (sublist (hi + 1) N bl) ->\n(0 < lo ->\n Forall (f_cmp Cle (Znth (lo - 1) bl)) (sublist lo N bl)) ->\n(hi + 1 < N ->\n Forall (f_cmp Cge (Znth (hi + 1) bl))\n   (sublist 0 (hi + 1) bl)) ->\nsemax (func_tycontext f_quicksort Vprog Gprog [])\n  (PROP ( )\n   LOCAL (temp _mid (dnth base mid); temp _lo (dnth base lo);\n   temp _hi (dnth base hi))\n   SEP (data_at Ews (tarray tdouble N) bl base))\n  quicksort_while_body_part2\n  (normal_ret_assert\n     (EX a : Z * Z * list val,\n      PROP (0 <= fst (fst a) < N; 0 <= snd (fst a) < N;\n      Permutation al (snd a);\n      sorted (f_cmp Cle) (sublist 0 (fst (fst a)) (snd a));\n      sorted (f_cmp Cle)\n        (sublist (snd (fst a) + 1) N (snd a));\n      0 < fst (fst a) ->\n      Forall (f_cmp Cle (Znth (fst (fst a) - 1) (snd a)))\n        (sublist (fst (fst a)) N (snd a));\n      snd (fst a) + 1 < N ->\n      Forall (f_cmp Cge (Znth (snd (fst a) + 1) (snd a)))\n        (sublist 0 (snd (fst a) + 1) (snd a));\n      fst (fst a) <= snd (fst a) + 1)\n      LOCAL (temp _lo (dnth base (fst (fst a)));\n      temp _hi (dnth base (snd (fst a))))\n      SEP (data_at Ews (tarray tdouble N) (snd a) base))%assert).\nProof.\nintros.\nassert_PROP (field_compatible (tarray tdouble N) [] base) as FC by entailer!. \nset (s := quicksort_while_body_part2); hnf in s; subst s.\nabbreviate_semax.\nset (M := Z.min _ _) in H0; compute in M; subst M.\npose_dnth_base lo.\npose_dnth_base mid.\npose_dnth_base hi.\npose proof (Permutation_Zlength H6).\nforward.\nforward.\nrewrite dbase_add by (auto; rep_lia).\nrewrite dbase_sub by (auto; rep_lia).\napply f_cmp_swap in H4; simpl in H4.\neapply semax_seq'.\napply forward_quicksort_do_loop; auto.\ndestruct H2 as [H2 H2'].\ndestruct H3 as [H3' H3].\nclear dependent mid.\nclear dependent bl.\nIntros left mid right bl.\nsubst MORE_COMMANDS; unfold abbreviate.\nassert (Hlen := Permutation_Zlength H10).\nassert (Hdef_bl: Forall def_float bl) by (apply Forall_perm with al; auto).\nforward_if.\n-\napply andp_right; apply denote_tc_samebase_dnth; auto.\n-\nclear H17.  (* we don't actually care! *)\nforward_call (dnth base left, hi-left+1, sublist left (hi+1) bl).\nrewrite (sum_sub_pp_base N) by (try assumption; lia).\napply andp_right.\napply prop_right; prove_it_now.\napply denote_tc_samebase_dnth; auto.\napply prop_right; simpl.\nrewrite (sum_sub_pp_base N) by (try assumption; lia).\nsimpl. f_equal. f_equal. normalize.\n{\nerewrite (split3_data_at_Tarray Ews tdouble (Zlength al) left (hi+1) bl bl);\n try reflexivity; \n change (@reptype CompSpecs tdouble) with val in *;\n  try rep_lia.\n2: compute; auto.\n2: autorewrite with sublist; auto.\nsep_apply data_at_dnth; try lia.\nset (s := Ptrofs.max_signed / 8) in *; compute in s; subst s.\nrep_lia.\nsep_apply data_at_dnth; try lia.\nset (s := Ptrofs.max_signed / 8) in *; compute in s; subst s.\nrep_lia.\nunfold tarray.\nreplace (hi-left+1) with (hi+1-left) by lia.\ncancel.\n}\nset (M := Z.min _ _); compute in M; subst M.\nautorewrite with sublist.\nsplit3; try lia.\napply Forall_sublist; auto.\nIntros bl'.\nassert (Hlen_bl' := Permutation_Zlength H17);\n  autorewrite with sublist in Hlen_bl'.\nforward.\nreplace base with (dnth base 0) at 1\n by (make_Vptr base; unfold dnth; simpl; normalize).\nrewrite dbase_add by (auto; rep_lia). rewrite Z.add_0_l.\nExists (lo, right,\n       (sublist 0 left bl ++ bl' ++ sublist (hi+1) N bl)).\nunfold fst, snd.\nentailer!.\n+\nclear H31 H30 H29 H28 H27 H26 H25 H24 H23 H22 H21 H20 H19.\nclear Delta_specs FC H1 H11 H13 base.\nclear H0 Espec.\nsplit.\neapply Permutation_trans; [apply H10|].\napply Permutation_trans with\n (sublist 0 left bl ++ sublist left (hi+1) bl ++ sublist (hi+1) N bl).\nautorewrite with sublist. auto.\napply Permutation_app_head.\napply Permutation_app_tail.\nauto.\nsubst N; rewrite Hlen in *; set (N := Zlength bl) in *.\nclear al H H10 Hlen.\neapply justify_quicksort_call1; eassumption.\n+\nerewrite (split3_data_at_Tarray Ews tdouble N left (hi+1));\n try reflexivity; try lia.\n2: compute; auto.\n3:{ rewrite (sublist_same 0 N). reflexivity. lia. list_solve. }\n2: list_solve.\nautorewrite with sublist.\nreplace (hi-left+1) with (hi+1-left) by (clear; lia).\nfold N.\nfold (tarray tdouble N).\nrewrite <- !dnth_base_field_address0 by (auto; lia).\nreplace  (hi + 1 - left - Zlength bl' + (hi + 1))\n  with (hi+1) by lia.\nreplace (N - left - Zlength bl' + (hi + 1)) with N by lia.\ncancel.\nautorewrite with sublist.\ncancel.\n-\nclear H17.  (* we don't actually care! *)\nforward_call (dnth base lo, right-lo+1, sublist lo (right+1) bl).\nrewrite (sum_sub_pp_base N) by (try assumption; lia).\napply andp_right.\napply prop_right; prove_it_now.\napply denote_tc_samebase_dnth; auto.\napply prop_right; simpl.\nrewrite (sum_sub_pp_base N) by (try assumption; lia).\nsimpl. f_equal. f_equal. normalize.\n{\nerewrite (split3_data_at_Tarray Ews tdouble (Zlength al) lo (right+1) bl bl);\n try reflexivity; \n change (@reptype CompSpecs tdouble) with val in *;\n  try rep_lia.\n2: compute; auto.\n2: autorewrite with sublist; auto.\nsep_apply data_at_dnth; try lia.\nset (s := Ptrofs.max_signed / 8) in *; compute in s; subst s.\nrep_lia.\nsep_apply data_at_dnth; try lia.\nset (s := Ptrofs.max_signed / 8) in *; compute in s; subst s.\nrep_lia.\nunfold tarray.\nreplace (right-lo+1) with (right+1-lo) by lia.\ncancel.\n}\nset (M := Z.min _ _); compute in M; subst M.\nautorewrite with sublist.\nsplit3; try lia.\napply Forall_sublist; auto.\nIntros bl'.\nassert (Hlen_bl' := Permutation_Zlength H17);\n  autorewrite with sublist in Hlen_bl'.\nforward.\nreplace base with (dnth base 0) at 1\n by (make_Vptr base; unfold dnth; simpl; normalize).\nrewrite dbase_add by (auto; rep_lia). rewrite Z.add_0_l.\nExists (left, hi,\n       (sublist 0 lo bl ++ bl' ++ sublist (right+1) N bl)).\nunfold fst, snd.\nentailer!.\n+\nclear H31 H30 H29 H28 H27 H26 H25 H24 H23 H22 H21 H20 H19.\nclear Delta_specs FC H1 H11 H13 base.\nclear H0 Espec.\nsplit.\neapply Permutation_trans; [apply H10|].\napply Permutation_trans with\n (sublist 0 lo bl ++ sublist lo (right+1) bl ++ sublist (right+1) N bl).\nautorewrite with sublist. auto.\napply Permutation_app_head.\napply Permutation_app_tail.\nauto.\nsubst N; rewrite Hlen in *; set (N := Zlength bl) in *.\nclear al H H10 Hlen.\neapply justify_quicksort_call2; eassumption.\n+\nerewrite (split3_data_at_Tarray Ews tdouble N lo (right+1));\n try reflexivity; try lia.\n2: compute; auto.\n3:{ rewrite (sublist_same 0 N). reflexivity. lia. list_solve. }\n2: list_solve.\nautorewrite with sublist.\nreplace (right-lo+1) with (right+1-lo) by (clear; lia).\nfold N.\nfold (tarray tdouble N).\nrewrite <- !dnth_base_field_address0 by (auto; lia).\nreplace  (right + 1 - lo - Zlength bl' + (right + 1))\n  with (right+1) by lia.\nreplace (N - lo - Zlength bl' + (right + 1)) with N by lia.\ncancel.\nautorewrite with sublist.\ncancel.\nQed.\n\nLemma calculate_midpoint:\n  forall N base lo hi,\n0 < N <= 268435455 ->\nisptr base ->\n0 <= lo < N ->\n0 <= hi < N ->\nlo < hi ->\nforce_val\n  (sem_binary_operation' Oadd (tptr tdouble) tint\n     (dnth base lo)\n     (eval_binop Oshr tint tint\n        (eval_binop Osub (tptr tdouble) (tptr tdouble)\n           (dnth base hi) (dnth base lo)) \n        (Vint (Int.repr 1)))) = dnth base (lo + (hi - lo) / 2).\nProof.\nintros.\n symmetry.\n simpl. unfold dnth, sem_shift_ii, sem_sub_pp, sem_add_ptr_int. simpl.\n    unfold sem_add_ptr_int, Cop.sem_add_ptr_int. simpl.\n    make_Vptr base; simpl. rewrite if_true by auto. simpl.\n    f_equal. rewrite Ptrofs.add_assoc. f_equal.\n    normalize. f_equal.\n    rewrite <- Z.mul_add_distr_l. f_equal.\n    unfold Int.shr.\n    rewrite !(Ptrofs.add_commut i), Ptrofs.sub_shifted.\n    normalize.\n    unfold Ptrofs.divs. normalize.\n    rewrite <- Z.mul_sub_distr_l.\n    rewrite (Int.signed_repr hi) by rep_lia.\n    rewrite (Int.signed_repr lo) by rep_lia.\n    rewrite (Ptrofs.signed_repr 8) by rep_lia.\n    rewrite (Ptrofs.signed_repr) by rep_lia.\n    rewrite Z.mul_comm, Z.quot_mul by lia.\n    rewrite Int.signed_repr. f_equal.\n    rewrite (Int.signed_repr (hi-lo)) by rep_lia.\n    rewrite Z.shiftr_div_pow2 by lia. change (2^1) with 2.\n    rewrite Int.signed_repr. auto.\n    split.\n    assert (0 <= (hi-lo)/2); [|rep_lia].\n    apply Z.div_pos; rep_lia.\n    apply Z.div_le_upper_bound; rep_lia.\n    split.\n    assert (0 <= (hi-lo)/2); [|rep_lia].\n    apply Z.div_pos; rep_lia.\n    pose proof (mid_in_range lo hi); rep_lia.\nQed.\n\nLemma body_quicksort_while:\nforall (Espec : OracleKind) (base : val) (al : list val) \n  (lo hi : Z) (bl : list val),\nForall def_float al ->\nlet N := Zlength al in\n0 < N <= Z.min Int.max_signed (Ptrofs.max_signed/8) ->\nisptr base ->\n0 <= lo < N ->\n0 <= hi < N ->\nPermutation al bl ->\nsorted (f_cmp Cle) (sublist 0 lo bl) ->\nsorted (f_cmp Cle) (sublist (hi + 1) N bl) ->\n(0 < lo -> Forall (f_cmp Cle (Znth (lo - 1) bl)) (sublist lo N bl)) ->\n(hi + 1 < N ->\n Forall (f_cmp Cge (Znth (hi + 1) bl)) (sublist 0 (hi + 1) bl)) ->\nlo < hi ->\nlo <= hi+1 ->\nsemax (func_tycontext f_quicksort Vprog Gprog [])\n  (PROP ( )\n   LOCAL (temp _lo (dnth base lo); temp _hi (dnth base hi))\n   SEP (data_at Ews (tarray tdouble N) bl base)) \n  quicksort_while_body\n  (normal_ret_assert\n     (EX a : Z * Z * list val,\n      PROP (0 <= fst (fst a) < N; 0 <= snd (fst a) < N;\n      Permutation al (snd a);\n      sorted (f_cmp Cle) (sublist 0 (fst (fst a)) (snd a));\n      sorted (f_cmp Cle) (sublist (snd (fst a) + 1) N (snd a));\n      0 < fst (fst a) ->\n      Forall (f_cmp Cle (Znth (fst (fst a) - 1) (snd a)))\n        (sublist (fst (fst a)) N (snd a));\n      snd (fst a) + 1 < N ->\n      Forall (f_cmp Cge (Znth (snd (fst a) + 1) (snd a)))\n        (sublist 0 (snd (fst a) + 1) (snd a));\n      fst (fst a) <= snd (fst a) + 1)\n      LOCAL (temp _lo (dnth base (fst (fst a)));\n      temp _hi (dnth base (snd (fst a))))\n      SEP (data_at Ews (tarray tdouble N) (snd a) base))).\nProof.\nintros.\nabbreviate_semax.\nset (M := Z.min _ _) in H0.\ncompute in M. subst M.\nassert (Hdef_bl: Forall def_float bl) by (apply Forall_perm with al; auto).\nunfold quicksort_while_body.\nsimpl.\nabbreviate_semax.\nforward.\nentailer!.\nauto.\nrewrite (calculate_midpoint N) by assumption.\npose proof (mid_in_range lo hi). spec H11; [lia|].\nforget (lo+(hi-lo)/2) as mid.\npose_dnth_base mid.\nassert (Hlen := Permutation_Zlength H4).\nforward.\napply tc_val_tdouble_Znth; auto; lia.\npose_dnth_base lo.\nforward.\napply tc_val_tdouble_Znth; auto; lia.\nforward_if (EX bl: list val, \n   PROP (f_cmp Cle (Znth lo bl) (Znth mid bl); Permutation al bl;\n   sorted (f_cmp Cle) (sublist 0 lo bl);\n   sorted (f_cmp Cle) (sublist (hi + 1) N bl);\n   0 < lo -> Forall (f_cmp Cle (Znth (lo - 1) bl)) (sublist lo N bl);\n   hi + 1 < N -> Forall (f_cmp Cge (Znth (hi + 1) bl))  (sublist 0 (hi + 1) bl))\n   LOCAL (temp _mid (dnth base mid); temp _lo (dnth base lo);\n   temp _hi (dnth base hi))\n   SEP (data_at Ews (tarray tdouble N) bl base)).\n- (* then-clause *)\nmatch goal with |- semax _ ?Pre _ ?Post => \nforward_loop Pre continue:Post.(RA_normal) end;\n  [solve [auto] | | forward; apply ENTAIL_refl ].\napply typed_true_cmp in H14.\nassert (lo<mid). {\n destruct (zeq lo mid); try lia.\n clear - H14 e. subst lo. apply f_lt_irrefl in H14. contradiction.\n}\nforward.\nforward.\nforward.\nforward.\nrewrite !def_float_f2f by (apply Forall_Znth; auto; lia).\nchange (upd_Znth lo _ _) with (swap_in_list lo mid bl).\nExists (swap_in_list lo mid bl).\nentailer!.\nclear H22 H21 H20 H19 H18.\nautorewrite with sublist.\nsplit.\nrewrite Znth_swap_in_list1 by lia.\nrewrite Znth_swap_in_list2 by lia.\nrewrite f_cmp_le_lt_eq. auto.\nsplit.\neapply Permutation_trans; [eassumption| apply Permutation_swap2; lia].\nrewrite !sublist_swap_in_list by lia.\nsplit3; auto.\nsplit; intro.\n+\nrewrite Znth_swap_in_list_other by lia.\neapply Forall_perm; [ | apply (H7 H18)].\nrewrite sublist_swap_in_list' by lia.\napply Permutation_swap2; try list_solve.\n+\nrewrite Znth_swap_in_list_other by lia.\neapply Forall_perm; [ | apply (H8 H18)].\nrewrite sublist_swap_in_list' by lia.\napply Permutation_swap2; try list_solve.\n-\nforward.\nExists bl.\nentailer!.\napply typed_false_cmp in H14.\nsimpl in H14.\napply f_cmp_swap in H14. auto.\napply Forall_Znth; auto; lia.\napply Forall_Znth; auto; lia.\n-\nclear dependent bl.\nIntros bl.\nassert (Hdef_bl: Forall def_float bl) by (apply Forall_perm with al; auto).\npose proof (Permutation_Zlength H5).\npose_dnth_base hi.\nforward.\napply tc_val_tdouble_Znth; auto; lia.\nforward.\napply tc_val_tdouble_Znth; auto; lia.\nforward_if (EX bl: list val, \n   PROP (f_cmp Cle (Znth lo bl) (Znth mid bl); \n             f_cmp Cle (Znth mid bl) (Znth hi bl); \n             Permutation al bl;\n   sorted (f_cmp Cle) (sublist 0 lo bl);\n   sorted (f_cmp Cle) (sublist (hi + 1) N bl);\n   0 < lo -> Forall (f_cmp Cle (Znth (lo - 1) bl)) (sublist lo N bl);\n   hi + 1 < N -> Forall (f_cmp Cge (Znth (hi + 1) bl))  (sublist 0 (hi + 1) bl))\n   LOCAL (temp _mid (dnth base mid); temp _lo (dnth base lo);\n   temp _hi (dnth base hi))\n   SEP (data_at Ews (tarray tdouble N) bl base)).\n+\napply typed_true_cmp in H17.\napply semax_seq' with (EX bl: list val, \n   PROP (f_cmp Cle (Znth mid bl) (Znth hi bl); \n             f_cmp Cle (Znth lo bl) (Znth mid bl) \\/\n             f_cmp Cle (Znth lo bl) (Znth hi bl);\n             Permutation al bl;\n   sorted (f_cmp Cle) (sublist 0 lo bl);\n   sorted (f_cmp Cle) (sublist (hi + 1) N bl);\n   0 < lo -> Forall (f_cmp Cle (Znth (lo - 1) bl)) (sublist lo N bl);\n   hi + 1 < N -> Forall (f_cmp Cge (Znth (hi + 1) bl))  (sublist 0 (hi + 1) bl))\n   LOCAL (temp _mid (dnth base mid); temp _lo (dnth base lo);\n   temp _hi (dnth base hi))\n   SEP (data_at Ews (tarray tdouble N) bl base)).\n*\nabbreviate_semax.\nmatch goal with |- semax _ ?Pre _ ?Post => \nforward_loop Pre continue:Post.(RA_normal) end;\n  [solve [auto] | | forward; apply ENTAIL_refl ].\nforward.\nforward.\nforward.\nforward.\nrewrite !def_float_f2f by (apply Forall_Znth; auto; lia).\nExists (swap_in_list hi mid bl).\nentailer!.\nclear H24 H23 H22 H21 H20 H19 H18.\nsplit3.\nrewrite Znth_swap_in_list1 by lia.\nrewrite Znth_swap_in_list2 by lia.\nrewrite f_cmp_le_lt_eq. auto.\nrewrite Znth_swap_in_list1 by lia.\nrewrite Znth_swap_in_list2 by lia.\ndestruct (zeq lo mid).\nsubst.\nrewrite Znth_swap_in_list2 by lia.\nleft.\napply f_le_refl; auto. apply Forall_Znth; auto; lia.\nrewrite Znth_swap_in_list_other by lia.\nauto.\nsplit3; [ | | split]; auto.\neapply Permutation_trans; [eassumption| ].\napply Permutation_swap2; lia.\nrewrite sublist_swap_in_list by lia; auto.\nrewrite sublist_swap_in_list by lia; auto.\nsplit; intro.\nrewrite Znth_swap_in_list_other by lia.\neapply Forall_perm; try apply (H8 H18).\nrewrite sublist_swap_in_list' by lia.\napply Permutation_swap2; try list_solve.\nrewrite Znth_swap_in_list_other by lia.\neapply Forall_perm; try apply (H14 H18).\nrewrite sublist_swap_in_list' by lia.\napply Permutation_swap2; try list_solve.\n*\nclear dependent bl.\nIntros bl.\nrename H5 into H4'.\nrename H6 into H5. rename H7 into H6. rename H8 into H7.\nassert (Hdef_bl: Forall def_float bl) by (apply Forall_perm with al; auto).\npose proof (Permutation_Zlength H5).\nabbreviate_semax.\nforward.\napply tc_val_tdouble_Znth; auto; lia.\nforward.\napply tc_val_tdouble_Znth; auto; lia.\nforward_if.\n--\napply typed_true_cmp in H17.\nmatch goal with |- semax _ ?Pre _ ?Post => \nforward_loop Pre continue:Post.(RA_normal) end;\n  [solve [auto] | | forward; apply ENTAIL_refl ].\nforward.\nforward.\nforward.\nforward.\nrewrite !def_float_f2f by (apply Forall_Znth; auto; lia).\nExists (swap_in_list lo mid bl).\nentailer!.\nclear H24 H23 H22 H21 H20 H18 H19.\nassert (lo<mid). {\n destruct (zeq lo mid); try lia.\n clear - H17 e. subst lo. apply f_lt_irrefl in H17. contradiction.\n}\nrewrite Znth_swap_in_list1 by lia.\nrewrite Znth_swap_in_list2 by lia.\nrewrite Znth_swap_in_list_other by lia.\nsplit3; auto.\nrewrite f_cmp_le_lt_eq. auto.\ndestruct H4'; auto.\neapply f_cmp_le_trans; try eassumption.\nsplit3; [ | | split]; auto.\neapply Permutation_trans; [eassumption| ].\napply Permutation_swap2; try lia.\nrewrite sublist_swap_in_list by lia; auto.\nrewrite sublist_swap_in_list by lia; auto.\nsplit; intro.\n++\nrewrite Znth_swap_in_list_other by lia.\neapply Forall_perm; try apply (H14 H19).\nrewrite sublist_swap_in_list' by lia.\napply Permutation_swap2; try list_solve.\n++\nrewrite Znth_swap_in_list_other by lia.\neapply Forall_perm; try apply (H15 H19).\nrewrite sublist_swap_in_list' by lia.\napply Permutation_swap2; try list_solve.\n--\nforward.\nExists bl.\nentailer!.\napply typed_false_cmp in H17.\nsimpl in H17.\napply f_cmp_swap in H17. auto.\napply Forall_Znth; auto; lia.\napply Forall_Znth; auto; lia.\n+\nforward.\nExists bl.\nentailer!.\napply typed_false_cmp in H17.\nsimpl in H17.\napply f_cmp_swap in H17. auto.\napply Forall_Znth; auto; lia.\napply Forall_Znth; auto; lia.\n+\nclear dependent bl.\nIntros bl.\napply body_quicksort_while_part2; auto; lia.\nQed.\n\nLemma body_quicksort:  semax_body Vprog Gprog f_quicksort quicksort_spec.\nProof.\nstart_function.\nrename H0 into H0''.\nassert (H0' := Z.min_glb_r _ _ _ H0'').\nassert (H0 := Z.min_glb_l _ _ _ H0'').\nforward_if.\nforward.\nExists al.\nentailer!.\ndestruct al; autorewrite with sublist in H2; try rep_lia.\nconstructor.\nassert (0 < N <= Int.max_signed) by rep_lia.\nclear H0 H2.\nassert_PROP (isptr base) by entailer!.\nforward.\nforward.\nreplace  (force_val\n               (sem_binary_operation' Osub (tptr tdouble) tint\n                  (eval_binop Oadd (tptr tdouble) tint base\n                     (Vint (Int.repr N))) (Vint (Int.repr 1))))\n  with (dnth base (N-1)).\n2:{\n  make_Vptr base.\n  unfold dnth.\n  simpl. f_equal. rewrite ptrofs_of_ints_unfold.\n  rewrite Ptrofs.sub_add_opp.\n  normalize.\n  rewrite Ptrofs.add_assoc. f_equal.\n  change (Ptrofs.neg (Ptrofs.repr 8)) with (Ptrofs.repr (-8)).\n  normalize. f_equal. lia.\n}\ndeadvars!.\nsubst N.\nset (N := Zlength al) in *.\nforward_while (EX lo:Z, EX hi:Z, EX bl: list val,\n                       PROP(0 <= lo < N; 0 <= hi < N;Permutation al bl;\n                                sorted (f_cmp Cle) (sublist 0 lo bl);\n                                sorted (f_cmp Cle) (sublist (hi+1) N bl);\n                                0<lo -> Forall (f_cmp Cle (Znth (lo-1) bl))\n                                                    (sublist lo N bl);\n                                hi+1<N -> Forall (f_cmp Cge (Znth (hi+1) bl))\n                                                    (sublist 0 (hi+1) bl);\n                                lo <= hi+1)\n                       LOCAL(temp _lo (dnth base lo); temp _hi (dnth base hi))\n                       SEP(data_at Ews (tarray tdouble N) bl base)).\n-\nExists 0 (N-1) al.\nentailer!.\nautorewrite with sublist.\nsplit3.\nconstructor.\nconstructor.\nunfold dnth. clear - H0. make_Vptr base. simpl. f_equal.\n  rewrite ptrofs_of_ints_unfold. normalize.\n-\nentailer!.\nassert (0 <= lo <= Zlength al) by lia.\nassert (0 <= hi <= Zlength al) by lia.\nauto with valid_pointer.\n-\npose_dnth_base lo. rename H10 into Hlo.\npose_dnth_base hi. rename H10 into Hhi.\nrewrite <- (force_sem_cmp_pp Clt) in HRE\n  by (apply isptr_dnth; auto).\neapply typed_true_pp with (N:=N) in HRE; \n  eauto; try split; try assumption; try lia; simpl in HRE.\nrename HRE into H10.\nchange Delta with (func_tycontext f_quicksort Vprog Gprog nil).\nchange (Ssequence _ _) with quicksort_while_body.\nmake_sequential.\nsubst POSTCONDITION; unfold abbreviate.\nautorewrite with ret_assert.\napply body_quicksort_while; auto.\nsplit. lia.\napply Z.min_glb; auto. lia.\n-\nforward.\nassert_PROP (lo >= hi). {\nentailer!.\nunfold compare_pp, dnth in HRE.\ndestruct base; simpl in HRE; try solve [inv HRE].\nrewrite if_true in HRE by auto.\nrewrite !ptrofs_of_ints_unfold in HRE.\nnormalize in HRE.\nunfold Ptrofs.ltu in HRE.\ndestruct (zlt _ _) in HRE; inv HRE.\nrewrite <- H13 in *.\nclear H13 al H1 H4 H13 H9 H10 H7 H8 H5 H6 H0.\nrewrite <- (Ptrofs.repr_unsigned i) in g.\nnormalize in g.\ndestruct H12 as [? [? [? [? ?]]]].\nred in H4.\nsimpl  sizeof in H4.\nrewrite Z.max_r in H4 by rep_lia.\nrewrite !Ptrofs.unsigned_repr in g by rep_lia.\nlia.\n} clear HRE.\nExists bl.\nentailer!.\nassert (lo=hi \\/ lo=hi+1) by lia.\nassert (Zlength al = Zlength bl) \n  by (rewrite !Zlength_correct; f_equal; apply Permutation_length; auto).\nrewrite H17 in *. \nassert (Hdef_bl: Forall def_float bl). {eapply Forall_perm; try eassumption. }\nclear - H16 H7 H8 H5 H6 H H2 Hdef_bl.\ndestruct H16; subst.\n+\nassert (hi=0 \\/ 0<hi) by lia.\ndestruct H0.\n *\nsubst.\nautorewrite with sublist in *.\ndestruct (zlt 1 (Zlength bl)).\nspecialize (H8 l).\nrewrite sublist_one in H8 by lia.\ninv H8.\nrewrite <- (sublist_same 0 (Zlength bl) bl) by lia.\nrewrite (sublist_split _ 1) by lia.\nrewrite sublist_one by lia.\napply sorted_app with (Znth 1 bl); auto.\napply f_cmp_le_trans.\nconstructor.\nconstructor.\napply (f_cmp_swap _ _ _ H3).\nconstructor.\n{\n clear - H6 l Hdef_bl.\n destruct bl. inv l.\n inv Hdef_bl. clear H1.\n rewrite Zlength_cons in *. change (v::bl) with ([v]++bl) in *.\n autorewrite with sublist in *.\n assert (0 < Zlength bl) by lia. clear l.\n revert H H2; induction H6; intros. \n constructor. repeat constructor. inv H2.  apply f_le_refl; auto.\n change (Znth 0 (x::y::l)) with x. inv H2.\n constructor.  apply f_le_refl; auto.\n spec IHsorted.\n rewrite Zlength_cons. rep_lia.\n spec IHsorted; auto.\n change (Znth 0 (y::l)) with y in IHsorted.\n clear - H IHsorted.\n forget (y::l) as zl.\n induction IHsorted. constructor. constructor; auto.\n eapply f_cmp_le_trans; eassumption.\n}\ndestruct bl.\nconstructor.\ndestruct bl.\nconstructor.\nrewrite !Zlength_cons in g.\nrep_lia.\n *\nspecialize (H7 H0).\ndestruct (zlt (hi+1) (Zlength bl)).\n2:{ assert (hi=Zlength bl \\/ hi+1 = Zlength bl) by lia.\n    destruct H1. subst. autorewrite with sublist in *. auto.\n    autorewrite with sublist in *.\n    clear g H6 H2 H H8.\n    rewrite sublist_one in H7 by lia. inv H7. clear H4.\n    rewrite (sublist_split 0 (hi-1)) in H5 by lia.\n    rewrite (sublist_one (hi-1)) in H5 by lia.\n    rewrite <- (sublist_same 0 (hi+1)) by lia.\n    rewrite (sublist_split 0 (hi-1)) by lia.\n    rewrite (sublist_split (hi-1) hi) by lia.\n    rewrite (sublist_one (hi-1)) by lia.\n    rewrite (sublist_one hi) by lia.\n    clear - H5 H3.\n    induction (sublist 0 (hi-1) bl). constructor; auto. constructor; auto.\n    inv H5. destruct l; inv H1. destruct l; inv H0.\n    simpl in IHl. spec IHl; auto. constructor; auto.\n    simpl in *. spec IHl; auto. constructor; auto.\n}\nspecialize (H8 l).\nrewrite <- (sublist_same 0 (Zlength bl) bl) by lia.\nrewrite (sublist_split 0 (hi-1)) by lia.\napply sorted_app with (Znth (hi-1) bl); auto.\napply f_cmp_le_trans.\n{\nclear - H0 l H5.\nrewrite (sublist_split 0 (hi-1)) in H5 by list_solve.\nforget (sublist 0 (hi - 1) bl) as al.\ninduction al. constructor.\nsimpl in H5.\ninv H5.\ndestruct al. constructor.\ninv H2.\ndestruct al; inv H1.\nconstructor.\nconstructor; auto.\n}\n{\nrewrite (sublist_split (hi-1) hi) by rep_lia.\nrewrite sublist_one by lia.\nrewrite (sublist_split hi (hi+1)) by rep_lia.\nrewrite sublist_one by lia.\nsimpl.\nconstructor.\nrewrite (sublist_split hi (hi+1)) in H7 by rep_lia.\nrewrite sublist_one in H7 by rep_lia.\ninv H7.\nauto.\nrewrite (sublist_split 0 (hi-1)) in H8 by lia.\nrewrite Forall_app in H8. destruct H8.\nrewrite (sublist_split _ hi) in H3 by lia.\nrewrite Forall_app in H3. destruct H3.\nrewrite sublist_one in H4 by lia.\ninv H4. clear H11.\napply f_cmp_swap in H10. simpl in H10.\nrewrite (sublist_split _ (hi+2)) in H6|-* by lia.\nrewrite sublist_one in * by lia.\nclear - H10 H6.\nsimpl in *.\nconstructor; auto.\n}\nrewrite (sublist_split 0 (hi-1)) in H8 by lia.\n{\nclear - H5 H0 l Hdef_bl.\nrewrite (sublist_split 0 (hi-1)) in H5 by lia.\nrewrite (sublist_one (hi-1)) in H5 by lia.\nclear - H5.\ninduction (sublist 0 (hi - 1) bl). constructor.\ninv H5. destruct l; inv H1.\ndestruct l; inv H0.\nconstructor; auto.\nconstructor; auto.\nspec IHl; auto. inv IHl; auto.\napply f_cmp_le_trans with v; auto.\n}\nrewrite (sublist_split _ hi) by lia.\nrewrite Forall_app. split; auto.\nrewrite sublist_one by lia. repeat constructor.\napply f_le_refl.\napply Forall_Znth; auto. lia.\n+\nspec H7; [ lia|].\nrewrite Z.add_simpl_r in H7.\ndestruct (zlt (hi+1) (Zlength bl)).\nspecialize (H8 l).\nrewrite <- (sublist_same 0 (Zlength bl) bl) by lia.\nrewrite (sublist_split 0 (hi+1)) by lia.\napply sorted_app with (Znth (hi+1) bl); auto.\napply f_cmp_le_trans.\neapply Forall_impl; try apply H8.\nclear; intros; apply (f_cmp_swap _ _ _ H).\n{\nclear - H6 l H2 Hdef_bl.\nrewrite (sublist_split (hi+1) (hi+2)) in H6|-* by lia.\nrewrite sublist_one in H6|-* by lia.\ninduction (sublist (hi + 2) (Zlength bl) bl).\nconstructor; auto.\napply f_le_refl.\napply Forall_Znth; try lia.\napply Hdef_bl.\nconstructor.\napply f_le_refl.\napply Forall_Znth; auto. lia.\ninv H6.\nspec IHl0.\ndestruct l0; inv H4; constructor; auto.\neapply f_cmp_le_trans; eassumption.\nconstructor; auto.\ninv IHl0; auto.\n}\nassert (hi+1=Zlength bl) by lia.\nautorewrite with sublist in *.\nauto.\nQed.\n\n\n\n\n\n\n\n\n\n", "meta": {"author": "cverified", "repo": "cbench-vst", "sha": "b3119729b39c4f5439dee78c633a9d2e3257df41", "save_path": "github-repos/coq/cverified-cbench-vst", "path": "github-repos/coq/cverified-cbench-vst/cbench-vst-b3119729b39c4f5439dee78c633a9d2e3257df41/qsort/verif_qsort3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.3629691917376782, "lm_q1q2_score": 0.21920864437719623}}
{"text": "Require Import Coq.Strings.String.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Data.Fun.\nRequire Import ExtLib.Data.String.\nRequire Import ExtLib.Tactics.Consider.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.Lambda.Ptrns.\nRequire Import MirrorCore.Views.FuncView.\nRequire Import MirrorCore.Views.Ptrns.\n\nSet Implicit Arguments.\nSet Strict Implicit.\nSet Maximal Implicit Insertion.\n\nInductive stringFunc : Set  :=\n| pString  : string -> stringFunc%type.\n\nSection StringFuncInst.\n  Context {typ func : Set} {RType_typ : RType typ}.\n  Context {Heq : RelDec (@eq typ)} {HC : RelDec_Correct Heq}.\n\n  Context {Typ0_tyString : Typ0 _ string}.\n\n  Let tyString : typ := @typ0 _ _ _ Typ0_tyString.\n\n  Definition typeofStringFunc (nf : stringFunc) : option typ :=\n    match nf with\n    | pString _ => Some tyString\n    end.\n\n  Definition stringFuncEq (a b : stringFunc) : option bool :=\n    match a , b with\n    | pString s, pString t => Some (s ?[ eq ] t)\n    end.\n\n  Definition stringR (s : string) : typD tyString :=\n    castR id string s.\n\n  Definition string_func_symD bf :=\n    match bf as bf return match typeofStringFunc bf return Type with\n\t\t\t  | Some t => typD t\n\t\t\t  | None => unit\n\t\t\t  end with\n    | pString s => stringR s\n    end.\n\n  Global Instance RSym_StringFunc\n  : SymI.RSym stringFunc :=\n  { typeof_sym := typeofStringFunc;\n    symD := string_func_symD ;\n    sym_eqb := stringFuncEq\n  }.\n\n  Global Instance RSymOk_StringFunc : SymI.RSymOk RSym_StringFunc.\n  Proof.\n    split; intros.\n    destruct a, b; simpl; try reflexivity.\n    consider (s ?[ eq ] s0); intros; subst; congruence.\n  Qed.\n\nEnd StringFuncInst.\n\nSection MakeString.\n  Polymorphic Context {func : Set}.\n  Polymorphic Context {FV : PartialView func stringFunc}.\n\n  Polymorphic Definition fString s := f_insert (pString s).\n\n  Polymorphic Definition fptrnString@{V L R} {T : Type@{V}} (p : Ptrns.ptrn@{Set V L R} string T)\n  : ptrn@{Set V L R} stringFunc T :=\n    fun f U good bad =>\n      match f with\n      | pString s => p s U good (fun x => bad f)\n      end.\n\n  Global Polymorphic Instance fptrnString_ok {T : Type} {p : ptrn string T} {Hok : ptrn_ok p} :\n    ptrn_ok (fptrnString p).\n  Proof.\n    red; intros; try (right; unfold Fails; reflexivity).\n    destruct x; simpl; destruct (Hok s).\n    { left. destruct H; exists x. revert H. compute; intros.\n      rewrite H. reflexivity. }\n    { right; unfold Fails in *; intros; simpl; rewrite H; reflexivity. }\n  Qed.\n\n  Polymorphic Lemma Succeeds_fptrnString {T : Type} (f : stringFunc) (p : ptrn string T) (res : T)\n        {pok : ptrn_ok p} (H : Succeeds f (fptrnString p) res) :\n    exists s, Succeeds s p res /\\ f = pString s.\n  Proof.\n    unfold Succeeds, fptrnString in H.\n    unfold ptrn_ok in pok.\n    specialize (H (option T) Some (fun _ => None)).\n    destruct f; try congruence.\n    specialize (pok s).\n    destruct pok; [|rewrite H0 in H; congruence].\n    destruct H0.\n    rewrite H0 in H; inv_all; subst.\n    exists s; split; [assumption | reflexivity].\n  Qed.\n\n  Global Polymorphic Instance fptrnString_SucceedsE {T : Type} {f : stringFunc}\n         {p : ptrn string T} {res : T} {pok : ptrn_ok p}\n  : SucceedsE f (fptrnString p) res :=\n  { s_result := exists s, Succeeds s p res /\\ f = pString s;\n    s_elim := @Succeeds_fptrnString T f p res pok\n  }.\n\nEnd MakeString.\n\nSection mkString.\n  Polymorphic Context {typ func : Set}.\n  Polymorphic Context {FV : PartialView func stringFunc}.\n\n  Polymorphic Definition mkString (s : string) := Inj (typ:=typ) (fString s).\n\nEnd mkString.\n\nSection PtrnString.\n  Context {typ func : Set}.\n  Context {FV : PartialView func stringFunc}.\n\n(* Putting this in the previous sectioun caused universe inconsistencies\n  when calling '@mkString typ func' in JavaFunc (with typ and func instantiated) *)\n\n  Definition ptrnString@{V L R} {T : Type@{V}} (p : ptrn@{Set V L R} string T)\n  : ptrn@{Set V L R} (expr typ func) T :=\n    inj (ptrn_view FV (fptrnString p)).\n\nEnd PtrnString.\n\nRequire Import MirrorCore.Reify.ReifyClass.\n\nSection ReifyString.\n  Context {typ func : Set} {FV : PartialView func stringFunc}.\n\n  Definition reify_cstring : Command (expr typ func) :=\n    CPattern (ls := (string:Type)::nil) (RHasType string (RGet 0 RIgnore)) (fun x => Inj (fString x)).\n\n  Definition reify_string : Command (expr typ func) :=\n    CFirst (reify_cstring :: nil).\n\nEnd ReifyString.\n\nArguments reify_string _ _ {_}.", "meta": {"author": "gmalecha", "repo": "mirror-core", "sha": "b962fbca15b0b5a4653f66d29d7115bb04ebd4f3", "save_path": "github-repos/coq/gmalecha-mirror-core", "path": "github-repos/coq/gmalecha-mirror-core/mirror-core-b962fbca15b0b5a4653f66d29d7115bb04ebd4f3/theories/Lib/StringView.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.21915447616813266}}
{"text": "Require Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import AST.\nRequire Import Cltypes.\nRequire Import Cop.\nRequire Import Lident.\n\nInductive expr : Type :=\n  | Econst_int: int -> type -> expr       (**r integer literal *)\n  | Econst_float: float -> type -> expr   (**r float literal *)\n  | Econst_single: float32 -> type -> expr (**r single float literal *)\n  | Evar: ident -> type -> expr           (**r variable *)\n  | Etempvar: ident -> type -> expr       (**r temporary variable *)\n  | Ederef: expr -> type -> expr          (**r pointer dereference (unary [*]) *)\n  | Eaddrof: expr -> type -> expr         (**r address-of operator ([&]) *)  \n  | Eunop: unary_operation -> expr -> type -> expr  (**r unary operation *)\n  | Ebinop: binary_operation -> expr -> expr -> type -> expr (**r binary operation *)\n  | Ecast: expr -> type -> expr   (**r type cast ([(ty) e]) *)\n  | Efield: expr -> ident -> type -> expr. (**r access to a member of a struct or union *)\n\nDefinition typeof (e: expr) : type :=\n  match e with\n  | Econst_int _ ty => ty\n  | Econst_float _ ty => ty\n  | Econst_single _ ty => ty\n  | Evar _ ty => ty\n  | Etempvar _ ty => ty\n  | Ederef _ ty => ty\n  | Eaddrof _ ty => ty\n  | Eunop _ _ ty => ty\n  | Ebinop _ _ _ ty => ty\n  | Ecast _ ty => ty\n  | Efield _ _ ty => ty\n  end.\n\nInductive statement : Type :=\n  | Sskip : statement                   (**r do nothing *)\n  | Sassign : expr -> expr -> statement (**r assignment [lvalue = rvalue] *)\n  | Sset : ident -> expr -> statement   (**r assignment [tempvar = rvalue] *)\n  | Scall: option ident  -> expr -> list expr -> statement (**r function call *)\n  | Ssequence : statement -> statement -> statement  (**r sequence *)\n  | Sifthenelse : expr  -> statement -> statement -> statement (**r conditional *)\n  | Swhile : expr -> statement -> statement (* while *)\n.\n\nRecord function : Type := mkfunction {\n  fn_return: type;\n  fn_params: list (ident * type);\n  fn_vars: list (ident * type);\n  fn_temps: list (ident * type);\n  fn_body: statement\n}.\n\nDefinition type_of_function (f: function) : type :=\n  Tfunction (type_of_params (fn_params f)) (fn_return f).\n\nInductive fundef : Type :=\n  | Internal: function -> fundef\n  | External: external_function -> typelist -> type -> fundef.\n\nDefinition type_of_fundef (f: fundef) : type :=\n  match f with\n  | Internal fd => type_of_function fd\n  | External id args res => Tfunction args res\n  end.\n\nDefinition program : Type := AST.program fundef type.\n", "meta": {"author": "linusboyle", "repo": "L2CDisplay", "sha": "4eb5b4dbb01da56534c0b0a1560dec8c715a68a4", "save_path": "github-repos/coq/linusboyle-L2CDisplay", "path": "github-repos/coq/linusboyle-L2CDisplay/L2CDisplay-4eb5b4dbb01da56534c0b0a1560dec8c715a68a4/display/Csim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.21915447616813263}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import SimMemory.\n\nSet Implicit Arguments.\n\n\nSection Simulation.\n  Definition SIM :=\n    forall (ths1_src:Threads.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n      (ths1_tgt:Threads.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t), Prop.\n\n  Definition _sim\n             (sim: SIM)\n             (ths1_src:Threads.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n             (ths1_tgt:Threads.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t): Prop :=\n    forall sc1_src mem1_src\n      sc1_tgt mem1_tgt\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY1: sim_memory mem1_src mem1_tgt)\n      (WF_SRC: Configuration.wf (Configuration.mk ths1_src sc1_src mem1_src))\n      (WF_TGT: Configuration.wf (Configuration.mk ths1_tgt sc1_tgt mem1_tgt))\n      (SC_FUTURE_SRC: TimeMap.le sc0_src sc1_src)\n      (SC_FUTURE_TGT: TimeMap.le sc0_tgt sc1_tgt)\n      (MEM_FUTURE_SRC: Memory.future mem0_src mem1_src)\n      (MEM_FUTURE_TGT: Memory.future mem0_tgt mem1_tgt),\n      <<TERMINAL:\n        forall (TERMINAL_TGT: Threads.is_terminal ths1_tgt),\n          <<FAILURE: Configuration.steps_failure (Configuration.mk ths1_src sc1_src mem1_src)>> \\/\n          exists ths2_src sc2_src mem2_src,\n            <<STEPS_SRC: rtc Configuration.tau_step (Configuration.mk ths1_src sc1_src mem1_src) (Configuration.mk ths2_src sc2_src mem2_src)>> /\\\n            <<SC: TimeMap.le sc2_src sc1_tgt>> /\\\n            <<MEMORY: sim_memory mem2_src mem1_tgt>> /\\\n            <<TERMINAL_SRC: Threads.is_terminal ths2_src>>>> /\\\n      <<STEP:\n        forall e tid_tgt ths3_tgt sc3_tgt mem3_tgt\n          (STEP_TGT: Configuration.step e tid_tgt (Configuration.mk ths1_tgt sc1_tgt mem1_tgt) (Configuration.mk ths3_tgt sc3_tgt mem3_tgt)),\n          <<FAILURE: Configuration.steps_failure (Configuration.mk ths1_src sc1_src mem1_src)>> \\/\n          exists tid_src ths2_src sc2_src mem2_src ths3_src sc3_src mem3_src,\n            <<STEPS_SRC: rtc Configuration.tau_step (Configuration.mk ths1_src sc1_src mem1_src) (Configuration.mk ths2_src sc2_src mem2_src)>> /\\\n            <<STEP_SRC: Configuration.opt_step e tid_src (Configuration.mk ths2_src sc2_src mem2_src) (Configuration.mk ths3_src sc3_src mem3_src)>> /\\\n            <<SC3: TimeMap.le sc3_src sc3_tgt>> /\\\n            <<MEMORY3: sim_memory mem3_src mem3_tgt>> /\\\n            <<SIM: sim ths3_src sc3_src mem3_src ths3_tgt sc3_tgt mem3_tgt>>>>.\n\n  Lemma _sim_mon: monotone6 _sim.\n  Proof.\n    ii. exploit IN; try apply SC1; eauto. i. des.\n    splits; eauto. i.\n    exploit STEP; eauto. i. des; eauto.\n    right. esplits; eauto.\n  Qed.\n  Hint Resolve _sim_mon: paco.\n\n  Definition sim: SIM := paco6 _sim bot6.\nEnd Simulation.\n#[export] Hint Resolve _sim_mon: paco.\n\n\nLemma sim_future\n      ths_src sc1_src sc2_src mem1_src mem2_src\n      ths_tgt sc1_tgt sc2_tgt mem1_tgt mem2_tgt\n      (SIM: sim ths_src sc1_src mem1_src ths_tgt sc1_tgt mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc1_src sc2_src)\n      (SC_FUTURE_TGT: TimeMap.le sc1_tgt sc2_tgt)\n      (MEM_FUTURE_SRC: Memory.future mem1_src mem2_src)\n      (MEM_FUTURE_TGT: Memory.future mem1_tgt mem2_tgt):\n  sim ths_src sc2_src mem2_src ths_tgt sc2_tgt mem2_tgt.\nProof.\n  pfold. ii.\n  punfold SIM. exploit SIM; (try by etrans; eauto); eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/transformation/Simulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.21908162719838364}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation, either version 2 of the License, or  *)\n(*  (at your option) any later version.  This file is also distributed *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file defines a number of data types and operations used in\n  the abstract syntax trees of many of the intermediate languages. *)\n\nRequire Import Coqlib.\nRequire String.\nRequire Import Errors.\nRequire Import Integers.\nRequire Import Floats.\n\nSet Implicit Arguments.\n\n(** * Syntactic elements *)\n\n(** Identifiers (names of local variables, of global symbols and functions,\n  etc) are represented by the type [positive] of positive integers. *)\n\nDefinition ident := positive.\n\nDefinition ident_eq := peq.\n\nParameter ident_of_string : String.string -> ident.\n\n(** The intermediate languages are weakly typed, using the following types: *)\n\nInductive typ : Type :=\n  | Tint                (**r 32-bit integers or pointers *)\n  | Tfloat              (**r 64-bit double-precision floats *)\n  | Tsingle.             (**r 32-bit single-precision floats *)\n\nLemma typ_eq: forall (t1 t2: typ), {t1=t2} + {t1<>t2}.\nProof. decide equality. Defined.\nGlobal Opaque typ_eq.\n\nDefinition opt_typ_eq: forall (t1 t2: option typ), {t1=t2} + {t1<>t2}\n                     := option_eq typ_eq.\n\nDefinition list_typ_eq: forall (l1 l2: list typ), {l1=l2} + {l1<>l2}\n                     := list_eq_dec typ_eq.\n\nDefinition typesize (ty: typ) : Z :=\n  match ty with\n  | Tint => 8\n  | Tfloat => 8\n  | Tsingle => 4\n  end.\n\nLemma typesize_pos: forall ty, typesize ty > 0.\nProof. destruct ty; simpl; omega. Qed.\n\n(** All values of size 32 bits are also of type [Tany32].  All values\n  are of type [Tany64].  This corresponds to the following subtyping\n  relation over types. *)\n\nDefinition subtype (ty1 ty2: typ) : bool :=\n  match ty1, ty2 with\n  | Tint, Tint => true\n  | Tfloat, Tfloat => true\n  | Tsingle, Tsingle => true\n  | _, _ => false\n  end.\n\nFixpoint subtype_list (tyl1 tyl2: list typ) : bool :=\n  match tyl1, tyl2 with\n  | nil, nil => true\n  | ty1::tys1, ty2::tys2 => subtype ty1 ty2 && subtype_list tys1 tys2\n  | _, _ => false\n  end.\n\n(** Additionally, function definitions and function calls are annotated\n  by function signatures indicating:\n- the number and types of arguments;\n- the type of the returned value, if any;\n- additional information on which calling convention to use.\n\nThese signatures are used in particular to determine appropriate\ncalling conventions for the function. *)\n\nRecord calling_convention : Type := mkcallconv {\n  cc_vararg: bool;\n  cc_structret: bool\n}.\n\nDefinition cc_default :=\n  {| cc_vararg := false; cc_structret := false |}.\n\nRecord signature : Type := mksignature {\n  sig_args: list typ;\n  sig_res: option typ;\n  sig_cc: calling_convention\n}.\n\nDefinition proj_sig_res (s: signature) : typ :=\n  match s.(sig_res) with\n  | None => Tint\n  | Some t => t\n  end.\n\nDefinition signature_eq: forall (s1 s2: signature), {s1=s2} + {s1<>s2}.\nProof.\n  generalize opt_typ_eq, list_typ_eq; intros; decide equality.\n  generalize bool_dec; intros. decide equality. \nDefined.\nGlobal Opaque signature_eq.\n\nDefinition signature_main :=\n  {| sig_args := nil; sig_res := Some Tint; sig_cc := cc_default |}.\n\n(** Memory accesses (load and store instructions) are annotated by\n  a ``memory chunk'' indicating the type, size and signedness of the\n  chunk of memory being accessed.\n  fixed: signedness is not used in vellvm *)\n\nInductive memory_chunk : Type :=\n  | Mint: nat -> memory_chunk    (**r integer or pointer *)\n  | Mfloat32                     (**r 32-bit single-precision float *)\n  | Mfloat64                     (**r 64-bit double-precision float *)\n.\n\nDefinition memory_chunk_eq (c1 c2: memory_chunk) : bool := \n  match c1, c2 with\n  | Mint n1, Mint n2 => beq_nat n1 n2\n  | Mfloat32, Mfloat32 => true\n  | Mfloat64, Mfloat64 => true\n  | _, _ => false\n  end.\n\nDefinition chunk_eq: forall (c1 c2: memory_chunk), {c1=c2} + {c1<>c2}.\nProof. decide equality. apply eq_nat_dec. Defined.\nGlobal Opaque chunk_eq.\n\n(** The type (integer/pointer or float) of a chunk. *)\n\nDefinition type_of_chunk (c: memory_chunk) : typ :=\n  match c with\n  | Mint _ => Tint\n  | Mfloat32 => Tsingle\n  | Mfloat64 => Tfloat\n  end.\n\n(** The chunk that is appropriate to store and reload a value of\n  the given type, without losing information. *)\n\nDefinition chunk_of_type (ty: typ) :=\n  match ty with\n  | Tint => Mint 31\n  | Tfloat => Mfloat64\n  | Tsingle => Mfloat32\n  end.\n\n(** Initialization data for global variables. *)\n\nInductive init_data: Type :=\n  | Init_int8: int32 -> init_data\n  | Init_int16: int32 -> init_data\n  | Init_int32: int32 -> init_data\n  | Init_int64: int64 -> init_data\n  | Init_float32: float32 -> init_data\n  | Init_float64: float -> init_data\n  | Init_space: Z -> init_data\n  | Init_addrof: ident -> int32 -> init_data.  (**r address of symbol + offset *)\n\n(** Information attached to global variables. *)\n\nRecord globvar (V: Type) : Type := mkglobvar {\n  gvar_info: V;                    (**r language-dependent info, e.g. a type *)\n  gvar_init: list init_data;       (**r initialization data *)\n  gvar_readonly: bool;             (**r read-only variable? (const) *)\n  gvar_volatile: bool              (**r volatile variable? *)\n}.\n\n(** Whole programs consist of:\n- a collection of global definitions (name and description);\n- the name of the ``main'' function that serves as entry point in the program.\n\nA global definition is either a global function or a global variable.\nThe type of function descriptions and that of additional information\nfor variables vary among the various intermediate languages and are\ntaken as parameters to the [program] type.  The other parts of whole\nprograms are common to all languages. *)\n\nInductive globdef (F V: Type) : Type :=\n  | Gfun (f: F)\n  | Gvar (v: globvar V).\n\nImplicit Arguments Gfun [F V].\nImplicit Arguments Gvar [F V].\n\nRecord program (F V: Type) : Type := mkprogram {\n  prog_defs: list (ident * globdef F V);\n  prog_main: ident\n}.\n\nDefinition prog_defs_names (F V: Type) (p: program F V) : list ident :=\n  List.map (@fst ident (globdef F V)) p.(prog_defs).\n\n(** * Generic transformations over programs *)\n\n(** We now define a general iterator over programs that applies a given\n  code transformation function to all function descriptions and leaves\n  the other parts of the program unchanged. *)\n\nSection TRANSF_PROGRAM.\n\nVariable A B V: Type.\nVariable transf: A -> B.\n\nDefinition transform_program_globdef (idg: ident * globdef A V) : ident * globdef B V :=\n  match idg with\n  | (id, Gfun f) => (id, Gfun (transf f))\n  | (id, Gvar v) => (id, Gvar v)\n  end.\n\nDefinition transform_program (p: program A V) : program B V :=\n  mkprogram\n    (List.map transform_program_globdef p.(prog_defs))\n    p.(prog_main).\n\nLemma transform_program_function:\n  forall p i tf,\n  In (i, Gfun tf) (transform_program p).(prog_defs) ->\n  exists f, In (i, Gfun f) p.(prog_defs) /\\ transf f = tf.\nProof.\n  simpl. unfold transform_program. intros.\n  exploit list_in_map_inv; eauto. \n  intros [[i' gd] [EQ IN]]. simpl in EQ. destruct gd; inv EQ. \n  exists f; auto.\nQed.\n\nEnd TRANSF_PROGRAM.\n\n(** The following is a more general presentation of [transform_program] where \n  global variable information can be transformed, in addition to function\n  definitions.  Moreover, the transformation functions can fail and\n  return an error message. *)\n\nOpen Local Scope error_monad_scope.\nOpen Local Scope string_scope.\n\nSection TRANSF_PROGRAM_GEN.\n\nVariables A B V W: Type.\nVariable transf_fun: A -> res B.\nVariable transf_var: V -> res W.\n\nDefinition transf_globvar (g: globvar V) : res (globvar W) :=\n  do info' <- transf_var g.(gvar_info);\n  OK (mkglobvar info' g.(gvar_init) g.(gvar_readonly) g.(gvar_volatile)).\n\nFixpoint transf_globdefs (l: list (ident * globdef A V)) : res (list (ident * globdef B W)) :=\n  match l with\n  | nil => OK nil\n  | (id, Gfun f) :: l' =>\n      match transf_fun f with\n      | Error msg => Error (MSG \"In function \" :: CTX id :: MSG \": \" :: msg)\n      | OK tf =>\n          do tl' <- transf_globdefs l'; OK ((id, Gfun tf) :: tl')\n      end\n  | (id, Gvar v) :: l' =>\n      match transf_globvar v with\n      | Error msg => Error (MSG \"In variable \" :: CTX id :: MSG \": \" :: msg)\n      | OK tv =>\n          do tl' <- transf_globdefs l'; OK ((id, Gvar tv) :: tl')\n      end\n  end.\n\nDefinition transform_partial_program2 (p: program A V) : res (program B W) :=\n  do gl' <- transf_globdefs p.(prog_defs); OK(mkprogram gl' p.(prog_main)).\n\nLemma transform_partial_program2_function:\n  forall p tp i tf,\n  transform_partial_program2 p = OK tp ->\n  In (i, Gfun tf) tp.(prog_defs) ->\n  exists f, In (i, Gfun f) p.(prog_defs) /\\ transf_fun f = OK tf.\nProof.\n  intros. monadInv H. simpl in H0. \n  revert x EQ H0. induction (prog_defs p); simpl; intros.\n  inv EQ. contradiction.\n  destruct a as [id [f|v]].\n  destruct (transf_fun f) as [tf1|msg] eqn:?; monadInv EQ.\n  simpl in H0; destruct H0. inv H. exists f; auto. \n  exploit IHl; eauto. intros [f' [P Q]]; exists f'; auto.\n  destruct (transf_globvar v) as [tv1|msg] eqn:?; monadInv EQ.\n  simpl in H0; destruct H0. inv H.\n  exploit IHl; eauto. intros [f' [P Q]]; exists f'; auto.\nQed.\n\nLemma transform_partial_program2_variable:\n  forall p tp i tv,\n  transform_partial_program2 p = OK tp ->\n  In (i, Gvar tv) tp.(prog_defs) ->\n  exists v,\n     In (i, Gvar(mkglobvar v tv.(gvar_init) tv.(gvar_readonly) tv.(gvar_volatile))) p.(prog_defs)\n  /\\ transf_var v = OK tv.(gvar_info).\nProof.\n  intros. monadInv H. simpl in H0. \n  revert x EQ H0. induction (prog_defs p); simpl; intros.\n  inv EQ. contradiction.\n  destruct a as [id [f|v]].\n  destruct (transf_fun f) as [tf1|msg] eqn:?; monadInv EQ.\n  simpl in H0; destruct H0. inv H.\n  exploit IHl; eauto. intros [v' [P Q]]; exists v'; auto.\n  destruct (transf_globvar v) as [tv1|msg] eqn:?; monadInv EQ.\n  simpl in H0; destruct H0. inv H.\n  monadInv Heqr. simpl. exists (gvar_info v). split. left. destruct v; auto. auto.\n  exploit IHl; eauto. intros [v' [P Q]]; exists v'; auto.\nQed.\n\nLemma transform_partial_program2_succeeds:\n  forall p tp i g,\n  transform_partial_program2 p = OK tp ->\n  In (i, g) p.(prog_defs) ->\n  match g with\n  | Gfun fd => exists tfd, transf_fun fd = OK tfd\n  | Gvar gv => exists tv, transf_var gv.(gvar_info) = OK tv\n  end.\nProof.\n  intros. monadInv H. \n  revert x EQ H0. induction (prog_defs p); simpl; intros.\n  contradiction.\n  destruct a as [id1 g1]. destruct g1.\n  destruct (transf_fun f) eqn:TF; try discriminate. monadInv EQ. \n  destruct H0. inv H. econstructor; eauto. eapply IHl; eauto.\n  destruct (transf_globvar v) eqn:TV; try discriminate. monadInv EQ.\n  destruct H0. inv H. monadInv TV. econstructor; eauto. eapply IHl; eauto.\nQed.\n\nLemma transform_partial_program2_main:\n  forall p tp,\n  transform_partial_program2 p = OK tp ->\n  tp.(prog_main) = p.(prog_main).\nProof.\n  intros. monadInv H. reflexivity.\nQed.\n\n(** Additionally, we can also \"augment\" the program with new global definitions\n  and a different \"main\" function. *)\n\nSection AUGMENT.\n\nVariable new_globs: list(ident * globdef B W).\nVariable new_main: ident.\n\nDefinition transform_partial_augment_program (p: program A V) : res (program B W) :=\n  do gl' <- transf_globdefs p.(prog_defs);\n  OK(mkprogram (gl' ++ new_globs) new_main).\n\nLemma transform_partial_augment_program_main:\n  forall p tp,\n  transform_partial_augment_program p = OK tp ->\n  tp.(prog_main) = new_main.\nProof.\n  intros. monadInv H. reflexivity.\nQed.\n\nEnd AUGMENT.\n\nRemark transform_partial_program2_augment:\n  forall p,\n  transform_partial_program2 p =\n  transform_partial_augment_program nil p.(prog_main) p.\nProof.\n  unfold transform_partial_program2, transform_partial_augment_program; intros.\n  destruct (transf_globdefs (prog_defs p)); auto.\n  simpl. f_equal. f_equal. rewrite <- app_nil_end. auto.\nQed.\n\nEnd TRANSF_PROGRAM_GEN.\n\n(** The following is a special case of [transform_partial_program2],\n  where only function definitions are transformed, but not variable definitions. *)\n\nSection TRANSF_PARTIAL_PROGRAM.\n\nVariable A B V: Type.\nVariable transf_partial: A -> res B.\n\nDefinition transform_partial_program (p: program A V) : res (program B V) :=\n  transform_partial_program2 transf_partial (fun v => OK v) p.\n\nLemma transform_partial_program_main:\n  forall p tp,\n  transform_partial_program p = OK tp ->\n  tp.(prog_main) = p.(prog_main).\nProof.\n  apply transform_partial_program2_main.\nQed.\n\nLemma transform_partial_program_function:\n  forall p tp i tf,\n  transform_partial_program p = OK tp ->\n  In (i, Gfun tf) tp.(prog_defs) ->\n  exists f, In (i, Gfun f) p.(prog_defs) /\\ transf_partial f = OK tf.\nProof.\n  apply transform_partial_program2_function. \nQed.\n\nLemma transform_partial_program_succeeds:\n  forall p tp i fd,\n  transform_partial_program p = OK tp ->\n  In (i, Gfun fd) p.(prog_defs) ->\n  exists tfd, transf_partial fd = OK tfd.\nProof.\n  unfold transform_partial_program; intros. \n  exploit transform_partial_program2_succeeds; eauto. \nQed.\n\nEnd TRANSF_PARTIAL_PROGRAM.\n\nLemma transform_program_partial_program:\n  forall (A B V: Type) (transf: A -> B) (p: program A V),\n  transform_partial_program (fun f => OK(transf f)) p = OK(transform_program transf p).\nProof.\n  intros.\n  unfold transform_partial_program, transform_partial_program2, transform_program; intros.\n  replace (transf_globdefs (fun f => OK (transf f)) (fun v => OK v) p.(prog_defs))\n     with (OK (map (transform_program_globdef transf) p.(prog_defs))).\n  auto. \n  induction (prog_defs p); simpl.\n  auto.\n  destruct a as [id [f|v]]; rewrite <- IHl.\n    auto.\n    destruct v; auto.\nQed.\n\n(** The following is a relational presentation of \n  [transform_partial_augment_preogram].  Given relations between function\n  definitions and between variable information, it defines a relation\n  between programs stating that the two programs have appropriately related\n  shapes (global names are preserved and possibly augmented, etc) \n  and that identically-named function definitions\n  and variable information are related. *)\n\nSection MATCH_PROGRAM.\n\nVariable A B V W: Type.\nVariable match_fundef: A -> B -> Prop.\nVariable match_varinfo: V -> W -> Prop.\n\nInductive match_globdef: ident * globdef A V -> ident * globdef B W -> Prop :=\n  | match_glob_fun: forall id f1 f2,\n      match_fundef f1 f2 ->\n      match_globdef (id, Gfun f1) (id, Gfun f2)\n  | match_glob_var: forall id init ro vo info1 info2,\n      match_varinfo info1 info2 ->\n      match_globdef (id, Gvar (mkglobvar info1 init ro vo)) (id, Gvar (mkglobvar info2 init ro vo)).\n\nDefinition match_program (new_globs : list (ident * globdef B W))\n                         (new_main : ident)\n                         (p1: program A V)  (p2: program B W) : Prop :=\n  (exists tglob, list_forall2 match_globdef p1.(prog_defs) tglob /\\\n                 p2.(prog_defs) = tglob ++ new_globs) /\\\n  p2.(prog_main) = new_main.\n\nEnd MATCH_PROGRAM.\n\nLemma transform_partial_augment_program_match:\n  forall (A B V W: Type)\n         (transf_fun: A -> res B)\n         (transf_var: V -> res W)\n         (p: program A V) \n         (new_globs : list (ident * globdef B W))\n         (new_main : ident)\n         (tp: program B W),\n  transform_partial_augment_program transf_fun transf_var new_globs new_main p = OK tp ->\n  match_program \n    (fun fd tfd => transf_fun fd = OK tfd)\n    (fun info tinfo => transf_var info = OK tinfo)\n    new_globs new_main\n    p tp.\nProof.\n  unfold transform_partial_augment_program; intros. monadInv H. \n  red; simpl. split; auto. exists x; split; auto.\n  revert x EQ. generalize (prog_defs p). induction l; simpl; intros.\n  monadInv EQ. constructor.\n  destruct a as [id [f|v]]. \n  (* function *)\n  destruct (transf_fun f) as [tf|?] eqn:?; monadInv EQ. \n  constructor; auto. constructor; auto.\n  (* variable *)\n  unfold transf_globvar in EQ.\n  destruct (transf_var (gvar_info v)) as [tinfo|?] eqn:?; simpl in EQ; monadInv EQ.\n  constructor; auto. destruct v; simpl in *. constructor; auto.\nQed.\n\n(** * External functions *)\n\n(** For most languages, the functions composing the program are either\n  internal functions, defined within the language, or external functions,\n  defined outside.  External functions include system calls but also\n  compiler built-in functions.  We define a type for external functions\n  and associated operations. *)\n\nInductive external_function : Type :=\n  | EF_external (name: ident) (sg: signature)\n     (** A system call or library function.  Produces an event\n         in the trace. *)\n  | EF_builtin (name: ident) (sg: signature)\n     (** A compiler built-in function.  Behaves like an external, but\n         can be inlined by the compiler. *)\n  | EF_vload (chunk: memory_chunk)\n     (** A volatile read operation.  If the adress given as first argument\n         points within a volatile global variable, generate an\n         event and return the value found in this event.  Otherwise,\n         produce no event and behave like a regular memory load. *)\n  | EF_vstore (chunk: memory_chunk)\n     (** A volatile store operation.   If the adress given as first argument\n         points within a volatile global variable, generate an event.\n         Otherwise, produce no event and behave like a regular memory store. *)\n  | EF_vload_global (chunk: memory_chunk) (id: ident) (ofs: int32)\n     (** A volatile load operation from a global variable. \n         Specialized version of [EF_vload]. *)\n  | EF_vstore_global (chunk: memory_chunk) (id: ident) (ofs: int32)\n     (** A volatile store operation in a global variable. \n         Specialized version of [EF_vstore]. *)\n  | EF_malloc\n     (** Dynamic memory allocation.  Takes the requested size in bytes\n         as argument; returns a pointer to a fresh block of the given size.\n         Produces no observable event. *)\n  | EF_free\n     (** Dynamic memory deallocation.  Takes a pointer to a block\n         allocated by an [EF_malloc] external call and frees the\n         corresponding block.\n         Produces no observable event. *)\n  | EF_memcpy (sz: Z) (al: Z)\n     (** Block copy, of [sz] bytes, between addresses that are [al]-aligned. *)\n  | EF_annot (text: ident) (targs: list annot_arg)\n     (** A programmer-supplied annotation.  Takes zero, one or several arguments,\n         produces an event carrying the text and the values of these arguments,\n         and returns no value. *)\n  | EF_annot_val (text: ident) (targ: typ)\n     (** Another form of annotation that takes one argument, produces\n         an event carrying the text and the value of this argument,\n         and returns the value of the argument. *)\n  | EF_inline_asm (text: ident)\n     (** Inline [asm] statements.  Semantically, treated like an\n         annotation with no parameters ([EF_annot text nil]).  To be\n         used with caution, as it can invalidate the semantic\n         preservation theorem.  Generated only if [-finline-asm] is\n         given. *)\n\nwith annot_arg : Type :=\n  | AA_arg (ty: typ)\n  | AA_int (n: int32)\n  | AA_float (n: float).\n\n(** The type signature of an external function. *)\n\nFixpoint annot_args_typ (targs: list annot_arg) : list typ :=\n  match targs with\n  | nil => nil\n  | AA_arg ty :: targs' => ty :: annot_args_typ targs'\n  | _ :: targs' => annot_args_typ targs'\n  end.\n\nDefinition ef_sig (ef: external_function): signature :=\n  match ef with\n  | EF_external name sg => sg\n  | EF_builtin name sg => sg\n  | EF_vload chunk => mksignature (Tint :: nil) (Some (type_of_chunk chunk)) cc_default\n  | EF_vstore chunk => mksignature (Tint :: type_of_chunk chunk :: nil) None cc_default\n  | EF_vload_global chunk _ _ => mksignature nil (Some (type_of_chunk chunk)) cc_default\n  | EF_vstore_global chunk _ _ => mksignature (type_of_chunk chunk :: nil) None cc_default\n  | EF_malloc => mksignature (Tint :: nil) (Some Tint) cc_default\n  | EF_free => mksignature (Tint :: nil) None cc_default\n  | EF_memcpy sz al => mksignature (Tint :: Tint :: nil) None cc_default\n  | EF_annot text targs => mksignature (annot_args_typ targs) None cc_default\n  | EF_annot_val text targ => mksignature (targ :: nil) (Some targ) cc_default\n  | EF_inline_asm text => mksignature nil None cc_default\n  end.\n\n(** Whether an external function should be inlined by the compiler. *)\n\nDefinition ef_inline (ef: external_function) : bool :=\n  match ef with\n  | EF_external name sg => false\n  | EF_builtin name sg => true\n  | EF_vload chunk => true\n  | EF_vstore chunk => true\n  | EF_vload_global chunk id ofs => true\n  | EF_vstore_global chunk id ofs => true\n  | EF_malloc => false\n  | EF_free => false\n  | EF_memcpy sz al => true\n  | EF_annot text targs => true\n  | EF_annot_val text targ => true\n  | EF_inline_asm text => true\n  end.\n\n(** Whether an external function must reload its arguments. *)\n\nDefinition ef_reloads (ef: external_function) : bool :=\n  match ef with\n  | EF_annot text targs => false\n  | _ => true\n  end.\n\n(** Equality between external functions.  Used in module [Allocation]. *)\n\nDefinition external_function_eq: forall (ef1 ef2: external_function), {ef1=ef2} + {ef1<>ef2}.\nProof.\n  generalize ident_eq signature_eq chunk_eq typ_eq zeq Int.eq_dec; intros.\n  decide equality.\n  apply list_eq_dec. decide equality. apply Float.eq_dec. \nDefined.\nGlobal Opaque external_function_eq.\n\n(** Function definitions are the union of internal and external functions. *)\n\nInductive fundef (F: Type): Type :=\n  | Internal: F -> fundef F\n  | External: external_function -> fundef F.\n\nImplicit Arguments External [F].\n\nSection TRANSF_FUNDEF.\n\nVariable A B: Type.\nVariable transf: A -> B.\n\nDefinition transf_fundef (fd: fundef A): fundef B :=\n  match fd with\n  | Internal f => Internal (transf f)\n  | External ef => External ef\n  end.\n\nEnd TRANSF_FUNDEF.\n\nSection TRANSF_PARTIAL_FUNDEF.\n\nVariable A B: Type.\nVariable transf_partial: A -> res B.\n\nDefinition transf_partial_fundef (fd: fundef A): res (fundef B) :=\n  match fd with\n  | Internal f => do f' <- transf_partial f; OK (Internal f')\n  | External ef => OK (External ef)\n  end.\n\nEnd TRANSF_PARTIAL_FUNDEF.\n", "meta": {"author": "snu-sf", "repo": "crellvm-vellvm", "sha": "54c7cc88ab5b4aec4c327f501cac4d9a667ca057", "save_path": "github-repos/coq/snu-sf-crellvm-vellvm", "path": "github-repos/coq/snu-sf-crellvm-vellvm/crellvm-vellvm-54c7cc88ab5b4aec4c327f501cac4d9a667ca057/lib/compcert-2.4/common/AST.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21908162719838362}}
{"text": "Require Export Fiat.Common.Coq__8_4__8_5__Compat.\n(** * A general [fold] over grammars *)\nRequire Import Coq.Lists.List.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Carriers.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Import Fiat.Parsers.BaseTypesLemmas.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Precompute.\nRequire Import Fiat.Common.\nRequire Import Fiat.Common.List.Operations.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.OptionFacts.\n\nSet Implicit Arguments.\n\nSection general_fold.\n  Context {Char : Type} {T : Type}.\n\n  Class fold_grammar_data :=\n    { on_terminal : (Char -> bool) -> T;\n      on_redundant_nonterminal : String.string -> T;\n      on_nonterminal : String.string -> T -> T;\n      on_nil_production : T;\n      combine_production : T -> T -> T;\n      on_nil_productions : T;\n      combine_productions : T -> T -> T }.\n  Context `{fold_grammar_data} (G : pregrammar' Char).\n\n  Global Instance compile_item_data_of_fold_grammar_data : opt.compile_item_data Char T\n    := {| opt.on_terminal := on_terminal;\n          opt.nonterminal_names := pregrammar_nonterminals G;\n          opt.invalid_nonterminal := Gensym.gensym (pregrammar_nonterminals G) |}.\n\n  Section with_compiled_productions.\n    Context (compiled_productions : list (opt.productions T))\n            (Hcompiled_productions : List.map opt.compile_productions (List.map snd (pregrammar_productions G)) = compiled_productions).\n\n    Definition opt_Lookup_idx (n : nat) : opt.productions T\n      := List.nth n compiled_productions nil.\n    Lemma eq_opt_Lookup_idx n\n      : opt_Lookup_idx n = opt.compile_productions (Lookup_idx G n).\n    Proof.\n      unfold opt_Lookup_idx, Lookup_idx; subst compiled_productions.\n      change nil with (opt.compile_productions nil) at 1.\n      rewrite map_nth.\n      reflexivity.\n    Qed.\n\n    Definition fold_production' (fold_nt : String.string -> default_nonterminal_carrierT -> T)\n               (its : opt.production T)\n      := fold_right\n           combine_production\n           on_nil_production\n           (map\n              (fun it =>\n                 match it with\n                 | opt.Terminal ch => ch\n                 | opt.NonTerminal nt nt_idx => on_nonterminal nt (fold_nt nt nt_idx)\n                 end)\n              its).\n\n    Lemma fold_production'_ext {f g} (ext : forall b b', f b b' = g b b') b\n      : fold_production' f b = fold_production' g b.\n    Proof.\n      unfold fold_production'.\n      induction b as [ | x ]; try reflexivity; simpl.\n      destruct x; rewrite ?IHb, ?ext; reflexivity.\n    Qed.\n\n    Definition fold_productions' (fold_nt : String.string -> default_nonterminal_carrierT -> T)\n               (its : opt.productions T)\n      := fold_right\n           combine_productions\n           on_nil_productions\n           (map\n              (fold_production' fold_nt)\n              its).\n\n    Lemma fold_productions'_ext {f g} (ext : forall b b', f b b' = g b b') b\n      : fold_productions' f b = fold_productions' g b.\n    Proof.\n      unfold fold_productions'.\n      induction b as [ | x ]; try reflexivity; simpl.\n      rewrite IHb, (fold_production'_ext ext); reflexivity.\n    Qed.\n\n    Definition fold_nt_step\n               (predata := @rdp_list_predata _ G)\n               (valid0_len : nat)\n               (fold_nt : forall valid_len : nat,\n                   nonterminals_listT\n                   -> String.string -> default_nonterminal_carrierT -> T)\n               (valid0 : nonterminals_listT)\n               (nt : String.string)\n               (nt_idx : default_nonterminal_carrierT)\n      : T.\n    Proof.\n      refine match valid0_len with\n             | 0 => on_redundant_nonterminal nt\n             | S valid0_len'\n               => if is_valid_nonterminal valid0 nt_idx\n                  then fold_productions'\n                         (@fold_nt valid0_len' (remove_nonterminal valid0 nt_idx))\n                         (opt_Lookup_idx nt_idx)\n                  else on_redundant_nonterminal nt\n             end.\n    Defined.\n\n    Lemma fold_nt_step_ext\n          {x0 x0' f g}\n          (ext : forall y p b b', f y p b b' = g y p b b')\n          b b'\n      : @fold_nt_step x0 f x0' b b' = @fold_nt_step x0 g x0' b b'.\n    Proof.\n      unfold fold_nt_step.\n      repeat match goal with\n             | [ |- context[match ?x with _ => _ end] ]\n               => destruct x eqn:?\n             | _ => reflexivity\n             end.\n      apply fold_productions'_ext; eauto.\n    Qed.\n\n    Fixpoint fold_cnt' initial : nonterminals_listT -> String.string -> default_nonterminal_carrierT -> T\n      := @fold_nt_step initial (@fold_cnt').\n\n    Lemma unfold_fold_cnt' initial\n      : @fold_cnt' initial = @fold_nt_step initial (@fold_cnt').\n    Proof. destruct initial; reflexivity. Qed.\n\n    Definition fold_cnt : String.string -> default_nonterminal_carrierT -> T\n      := let predata := @rdp_list_predata _ G in\n         @fold_cnt' (nonterminals_length initial_nonterminals_data) initial_nonterminals_data.\n    Definition fold_nt' initial (valid0 : nonterminals_listT) (nt : String.string) : T\n      := @fold_cnt' initial valid0 nt (opt.compile_nonterminal nt).\n\n    Definition fold_nt : String.string -> T\n      := let predata := @rdp_list_predata _ G in\n         @fold_nt' (nonterminals_length initial_nonterminals_data) initial_nonterminals_data.\n\n    Definition fold_production (pat : production Char) : T\n      := @fold_production' (@fold_cnt) (opt.compile_production pat).\n\n    Definition fold_productions (pats : productions Char) : T\n      := @fold_productions' (@fold_cnt) (opt.compile_productions pats).\n  End with_compiled_productions.\n\n  Definition compiled_productions : list (opt.productions T)\n    := List.map opt.compile_productions (List.map snd (pregrammar_productions G)).\nEnd general_fold.\nGlobal Hint Immediate compile_item_data_of_fold_grammar_data : typeclass_instances.\n\nGlobal Arguments fold_grammar_data : clear implicits.\n\nSection fold_correctness.\n  Context {Char : Type} {T : Type}.\n  Context {FGD : fold_grammar_data Char T}\n          (G : pregrammar' Char).\n\n  Let predata := @rdp_list_predata _ G.\n  Local Existing Instance predata.\n\n  Class fold_grammar_correctness_computational_data :=\n    { Pnt : nonterminals_listT -> String.string -> T -> Type;\n      Ppat : nonterminals_listT -> production Char -> T -> Type;\n      Ppats : nonterminals_listT -> productions Char -> T -> Type }.\n  Class fold_grammar_correctness_data :=\n    { fgccd :> fold_grammar_correctness_computational_data;\n      Pnt_lift : forall valid0 nt value,\n                   sub_nonterminals_listT valid0 initial_nonterminals_data\n                   -> is_valid_nonterminal valid0 (of_nonterminal nt)\n                   -> Ppats (remove_nonterminal valid0 (of_nonterminal nt)) (G nt) value\n                   -> Pnt valid0 nt value;\n      Pnt_redundant : forall valid0 nt,\n                        sub_nonterminals_listT valid0 initial_nonterminals_data\n                        -> is_valid_nonterminal valid0 (of_nonterminal nt) = false\n                        -> Pnt valid0 nt (on_redundant_nonterminal nt);\n      Ppat_nil : forall valid0, Ppat valid0 nil on_nil_production;\n      Ppat_cons_nt : forall valid0 nt xs p ps,\n                       sub_nonterminals_listT valid0 initial_nonterminals_data\n                       -> Pnt valid0 nt p\n                       -> Ppat valid0 xs ps\n                       -> Ppat valid0\n                               (NonTerminal nt::xs)\n                               (combine_production (on_nonterminal nt p) ps);\n      Ppat_cons_t : forall valid0 ch xs ps,\n                      sub_nonterminals_listT valid0 initial_nonterminals_data\n                      -> Ppat valid0 xs ps\n                      -> Ppat valid0\n                              (Terminal ch::xs)\n                              (combine_production (on_terminal ch) ps);\n      Ppats_nil : forall valid0, Ppats valid0 nil on_nil_productions;\n      Ppats_cons : forall valid0 x xs p ps,\n                     sub_nonterminals_listT valid0 initial_nonterminals_data\n                     -> Ppat valid0 x p\n                     -> Ppats valid0 xs ps\n                     -> Ppats valid0 (x::xs) (combine_productions p ps) }.\n  Context {FGCD : fold_grammar_correctness_data}.\n\n  Lemma fold_production'_correct\n        valid0\n        f\n        (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n        (IHf : forall nt nt_idx, of_nonterminal nt = nt_idx -> Pnt valid0 nt (f nt nt_idx))\n        pat\n  : Ppat valid0 pat (fold_production' f (opt.compile_production pat)).\n  Proof.\n    unfold fold_production'.\n    induction pat; simpl.\n    { apply Ppat_nil. }\n    { edestruct (_ : item _).\n      { apply Ppat_cons_t; trivial. }\n      { apply Ppat_cons_nt; eauto. } }\n  Qed.\n\n  Lemma fold_productions'_correct\n        valid0\n        f\n        (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n        (IHf : forall nt nt_idx, of_nonterminal nt = nt_idx -> Pnt valid0 nt (f nt nt_idx))\n        pats\n  : Ppats valid0 pats (fold_productions' f (opt.compile_productions pats)).\n  Proof.\n    unfold fold_productions'.\n    induction pats as [ | x xs IHxs ]; intros.\n    { simpl; apply Ppats_nil. }\n    { simpl; apply Ppats_cons; trivial; [].\n      { apply fold_production'_correct; trivial. } }\n  Qed.\n\n  Section step.\n    Context (fold_nt : forall valid_len : nat,\n                         nonterminals_listT\n                         -> String.string -> default_nonterminal_carrierT -> T).\n\n    Lemma fold_nt_step_correct0\n          (valid0 : nonterminals_listT)\n          (Hlen : nonterminals_length valid0 <= 0)\n          (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n      : forall nt nt_idx,\n        of_nonterminal nt = nt_idx\n        -> Pnt valid0 nt (fold_nt_step (compiled_productions G) 0 fold_nt valid0 nt nt_idx).\n    Proof.\n      assert (Hlen' : nonterminals_length valid0 = 0) by omega; clear Hlen.\n      simpl; intros nt nt_idx Hnt.\n      apply Pnt_redundant; [ assumption | ].\n      destruct (is_valid_nonterminal valid0 (of_nonterminal nt)) eqn:Hvalid; trivial.\n      assert (nonterminals_length (remove_nonterminal valid0 (of_nonterminal nt)) < nonterminals_length valid0)\n        by (apply remove_nonterminal_dec; assumption).\n      omega.\n    Qed.\n  End step.\n\n  Local Opaque rdp_list_predata.\n\n  Lemma fold_cnt'_correct\n        (valid0 : nonterminals_listT)\n        (valid0_len : nat)\n        (Hlen : nonterminals_length valid0 <= valid0_len)\n        (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n    : forall nt nt_idx,\n      of_nonterminal nt = nt_idx\n      -> Pnt valid0 nt (fold_cnt' (compiled_productions G) valid0_len valid0 nt nt_idx).\n  Proof.\n    revert valid0 Hsub Hlen.\n    induction valid0_len as [|valid0_len IH].\n    { intros; apply fold_nt_step_correct0; assumption. }\n    { simpl.\n      intros valid0 Hsub Hlen nt nt_idx Hnt.\n      match goal with\n        | [ |- context[if ?e then _ else _] ] => destruct e eqn:Hvalid\n      end.\n      { apply Pnt_lift; [ subst; assumption.. | ].\n        rewrite (eq_opt_Lookup_idx G), <- list_to_productions_to_nonterminal by reflexivity.\n        change (Lookup_string G) with (Lookup G); subst.\n        change default_to_nonterminal with to_nonterminal.\n        rewrite to_of_nonterminal\n          by (apply initial_nonterminals_correct, Hsub; assumption).\n        apply fold_productions'_correct.\n        { apply sub_nonterminals_listT_remove_2; assumption. }\n        { apply IH.\n          { apply sub_nonterminals_listT_remove_2; assumption. }\n          { apply Le.le_S_n.\n            etransitivity; [ | exact Hlen ].\n            apply (remove_nonterminal_dec valid0 (of_nonterminal nt) Hvalid). } } }\n      { apply Pnt_redundant; subst; assumption. } }\n  Qed.\n\n  Lemma fold_cnt_correct\n        nt nt_idx\n        (Hnt : of_nonterminal nt = nt_idx)\n  : Pnt initial_nonterminals_data nt (fold_cnt G (compiled_productions G) nt nt_idx).\n  Proof.\n    unfold fold_cnt.\n    apply fold_cnt'_correct; subst; reflexivity.\n  Qed.\n\n  Lemma fold_nt'_correct\n        (valid0 : nonterminals_listT)\n        (valid0_len : nat)\n        (Hlen : nonterminals_length valid0 <= valid0_len)\n        (Hsub : sub_nonterminals_listT valid0 initial_nonterminals_data)\n    : forall nt, Pnt valid0 nt (fold_nt' (compiled_productions G) valid0_len valid0 nt).\n  Proof.\n    intro nt; apply fold_cnt'_correct; auto.\n  Qed.\n\n  Lemma fold_nt_correct\n        nt\n  : Pnt initial_nonterminals_data nt (fold_nt G (compiled_productions G) nt).\n  Proof.\n    unfold fold_nt.\n    apply fold_nt'_correct;\n    reflexivity.\n  Qed.\n\n  Lemma fold_production_correct\n        pat\n  : Ppat initial_nonterminals_data pat (fold_production G (compiled_productions G) pat).\n  Proof.\n    unfold fold_production.\n    apply fold_production'_correct, fold_cnt_correct.\n    reflexivity.\n  Qed.\n\n  Lemma fold_productions_correct\n        pats\n  : Ppats initial_nonterminals_data pats (fold_productions G (compiled_productions G) pats).\n  Proof.\n    unfold fold_productions.\n    apply fold_productions'_correct, fold_cnt_correct.\n    reflexivity.\n  Qed.\nEnd fold_correctness.\n\nModule compile.\n  Section semantics.\n    Context {Char : Type} {T : Type}.\n    Context `{@fold_grammar_data Char T} (G : pregrammar' Char).\n\n    Local Notation productions_def precompiled_productions\n      := (List.map (fun nt_idx_nt => fold_cnt G precompiled_productions (snd nt_idx_nt) (fst nt_idx_nt)) (enumerate (List.map fst (pregrammar_productions G)) 0)).\n\n    Definition productions : list T\n      := productions_def (compiled_productions G).\n\n    Section with_compiled_productions.\n      Context (precompiled_productions : list (opt.productions T))\n              (Hprecompiled_productions : List.map opt.compile_productions (List.map snd (pregrammar_productions G)) = precompiled_productions).\n      Context (compiled_productions : list T)\n              (Hcompiled_productions : productions_def precompiled_productions = compiled_productions).\n\n      Definition fold_cnt : String.string -> default_nonterminal_carrierT -> T\n        := fun nt nt_idx => List.nth nt_idx compiled_productions (on_redundant_nonterminal nt).\n      Definition fold_nt : String.string -> T\n        := fun nt => fold_cnt nt (opt.compile_nonterminal nt).\n      Definition fold_production (pat : Core.production Char) : T\n        := fold_production' fold_cnt (opt.compile_production pat).\n      Definition fold_productions (pats : Core.productions Char) : T\n        := fold_productions' fold_cnt (opt.compile_productions pats).\n    End with_compiled_productions.\n\n  End semantics.\n\n  Section fold_correctness.\n    Context {Char : Type} {T : Type}.\n    Context {FGD : fold_grammar_data Char T}\n            (G : pregrammar' Char)\n            {FGCD : fold_grammar_correctness_data G}.\n\n    Let predata := @rdp_list_predata _ G.\n    Local Existing Instance predata.\n\n    Lemma fold_cnt_correct\n          nt nt_idx\n          (Hnt : of_nonterminal nt = nt_idx)\n      : Pnt initial_nonterminals_data nt (fold_cnt (productions G) nt nt_idx).\n    Proof.\n      unfold fold_cnt, productions.\n      repeat match goal with\n             | _ => progress subst\n             | _ => rewrite ListFacts.nth_error_nth\n             | _ => progress unfold option_map in *\n             | _ => progress break_innermost_match_step\n             | _ => progress break_innermost_match_hyps_step\n             | _ => progress inversion_option\n             | _ => progress destruct_head' sig\n             | _ => progress destruct_head' and\n             | _ => progress cbn [fst snd plus] in *\n             | [ H : nth_error (map _ _) _ = Some _ |- _ ] => apply ListFacts.nth_error_map'_strong in H\n             | [ H : nth_error (enumerate _ _) _ = _ |- _ ]\n               => rewrite ListFacts.nth_error_enumerate in H\n             | [ H : nth_error (map ?f ?ls) ?idx = None |- _ ]\n               => let H' := fresh in\n                  destruct (nth_error ls idx) eqn:H';\n                    [ eapply map_nth_error in H'; rewrite H in H'; congruence\n                    | clear H ]\n             end.\n      { match goal with\n        | [ H : nth_error _ (of_nonterminal ?nt) = Some ?x |- _ ]\n          => assert (fst x = nt);\n               [ pose proof H as H'; rewrite nth_error_default_to_nonterminal in H'\n               | subst nt ]\n        end.\n        { break_innermost_match_hyps; try congruence; inversion_option; subst.\n          cbn [fst].\n          change default_to_nonterminal with (rdp_list_to_nonterminal (G:=G)).\n          unfold of_nonterminal, predata, rdp_list_predata.\n          rewrite rdp_list_to_of_nonterminal; [ reflexivity | ].\n          apply initial_nonterminals_correct, rdp_list_is_valid_nonterminal_nth_error.\n          congruence. }\n        { apply fold_cnt_correct; reflexivity. } }\n      { apply Pnt_redundant; [ reflexivity | ].\n        match goal with |- ?x = false => destruct x eqn:Hb end;\n          [ | reflexivity ].\n        exfalso.\n        eapply rdp_list_is_valid_nonterminal_nth_error; try eassumption; assumption. }\n    Qed.\n\n    Lemma fold_nt_correct nt\n      : Pnt initial_nonterminals_data nt (fold_nt G (productions G) nt).\n    Proof. unfold fold_nt; apply fold_cnt_correct; reflexivity. Qed.\n\n    Lemma fold_production_correct pat\n      : Ppat initial_nonterminals_data pat (fold_production G (productions G) pat).\n    Proof.\n      unfold fold_production.\n      apply fold_production'_correct; [ reflexivity | apply fold_cnt_correct ].\n    Qed.\n\n    Lemma fold_productions_correct pats\n      : Ppats initial_nonterminals_data pats (fold_productions G (productions G) pats).\n    Proof.\n      unfold fold_productions.\n      apply fold_productions'_correct; [ reflexivity | apply fold_cnt_correct ].\n    Qed.\n  End fold_correctness.\nEnd compile.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/ContextFreeGrammar/Fold.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.21905224315426988}}
{"text": "(* Do not edit this file, it was generated automatically *)\nRequire Import VST.floyd.proofauto.\nRequire Import VST.floyd.library.\nRequire Import VST.progs64.object.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nLocal Open Scope Z.\nLocal Open Scope logic.\n\nDefinition object_invariant := list Z -> val -> mpred.\n\nDefinition tobject := tptr (Tstruct _object noattr).\n\nDefinition reset_spec (instance: object_invariant) :=\n  WITH self: val, history: list Z\n  PRE [ _self OF tobject]\n          PROP ()\n          LOCAL (temp _self self)\n          SEP (instance history self)\n  POST [ tvoid ]\n          PROP() LOCAL () SEP(instance nil self).\n\nDefinition twiddle_spec (instance: object_invariant) :=\n  WITH self: val, i: Z, history: list Z\n  PRE [ _self OF tobject, _i OF tint]\n          PROP (0 < i <= Int.max_signed / 4;\n                0 <= fold_right Z.add 0 history <= Int.max_signed / 4)\n          LOCAL (temp _self self; temp _i (Vint (Int.repr i)))\n          SEP (instance history self)\n  POST [ tint ]\n      EX v: Z, \n          PROP(2* fold_right Z.add 0 history < v <= 2* fold_right Z.add 0 (i::history))\n          LOCAL (temp ret_temp (Vint (Int.repr v))) \n          SEP(instance (i::history) self).\n\nDefinition object_methods (instance: object_invariant) (mtable: val) : mpred :=\n  EX sh: share, EX reset: val, EX twiddle: val,\n  !! readable_share sh && \n  func_ptr' (reset_spec instance) reset *\n  func_ptr' (twiddle_spec instance) twiddle *\n  data_at sh (Tstruct _methods noattr) (reset,twiddle) mtable.\n\nLemma object_methods_local_facts: forall instance p,\n  object_methods instance p |-- !! isptr p.\nProof.\nintros.\nunfold object_methods.\nIntros sh reset twiddle.\nentailer!.\nQed.\nHint Resolve object_methods_local_facts : saturate_local.\n\nDefinition object_mpred (history: list Z) (self: val) : mpred :=\n  EX instance: object_invariant, EX mtable: val, \n       (object_methods instance mtable *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable self*\n     instance history self).\n\nDefinition foo_invariant : object_invariant :=\n  (fun (history: list Z) p =>\n    withspacer Ews (sizeof size_t + sizeof tint) (2 * sizeof size_t) (field_at Ews (Tstruct _foo_object noattr) \n            [StructField _data] (Vint (Int.repr (2*fold_right Z.add 0 history)))) p\n      *  malloc_token Ews (Tstruct _foo_object noattr) p).\n\nDefinition foo_reset_spec :=\n DECLARE _foo_reset (reset_spec foo_invariant).\n\nDefinition foo_twiddle_spec :=\n DECLARE _foo_twiddle  (twiddle_spec foo_invariant).\n\nDefinition make_foo_spec :=\n DECLARE _make_foo\n WITH gv: globals\n PRE [ ]\n    PROP () LOCAL (gvars gv) \n    SEP (mem_mgr gv; object_methods foo_invariant (gv _foo_methods))\n POST [ tobject ]\n    EX p: val, PROP () LOCAL (temp ret_temp p)\n     SEP (mem_mgr gv; object_mpred nil p; object_methods foo_invariant (gv _foo_methods)).\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv: globals\n  PRE  [] main_pre prog nil gv\n  POST [ tint ]\n     EX i:Z, PROP(0<=i<=6) LOCAL (temp ret_temp (Vint (Int.repr i))) SEP(TT).\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [\n    foo_reset_spec; foo_twiddle_spec; make_foo_spec; main_spec]).\n\nLemma object_mpred_i:\n  forall (history: list Z) (self: val) (instance: object_invariant) (mtable: val),\n    object_methods instance mtable *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable self *\n     instance history self \n    |-- object_mpred history self.\nProof.\nintros. unfold object_mpred. Exists instance mtable; auto.\nQed.\n\nLemma body_foo_reset: semax_body Vprog Gprog f_foo_reset foo_reset_spec.\nProof.\nunfold foo_reset_spec, foo_invariant, reset_spec.\nstart_function.\nunfold withspacer; simpl; Intros.\nforward.  (* self->data=0; *)\nforward.  (* return; *)\nall: unfold withspacer; simpl; entailer!.  (* needed if Archi.ptr64=true *)\nQed.\n\nLemma body_foo_twiddle: semax_body Vprog Gprog f_foo_twiddle foo_twiddle_spec.\nProof.\nunfold foo_twiddle_spec, foo_invariant, twiddle_spec.\nstart_function.\nunfold withspacer; simpl.\nIntros.\nforward.  (* d = self->data; *)\nforward.  (* self -> data = d+2*i; *) \n set (j:= Int.max_signed / 4) in *; compute in j; subst j.\n forget (fold_right Z.add 0 history) as h.\n entailer!.\nforward.  (* return d+i; *)\nsimpl.\n set (j:= Int.max_signed / 4) in *; compute in j; subst j.\n forget (fold_right Z.add 0 history) as h.\n entailer!.\nExists (2 * fold_right Z.add 0 history + i).\nsimpl;\nentailer!.\nrewrite Z.mul_add_distr_l, Z.add_comm.\nunfold withspacer; simpl.\nentailer!.\nQed.\n\nLemma split_object_methods:\n  forall instance m, \n    object_methods instance m |-- object_methods instance m * object_methods instance m.\nProof.\nintros.\nunfold object_methods.\nIntros sh reset twiddle.\n\nExists (fst (slice.cleave sh)) reset twiddle.\nExists (snd (slice.cleave sh)) reset twiddle.\nrewrite (split_func_ptr' (reset_spec instance) reset) at 1.\nrewrite (split_func_ptr' (twiddle_spec instance) twiddle) at 1.\nentailer!.\nsplit.\napply slice.cleave_readable1; auto.\napply slice.cleave_readable2; auto.\nrewrite (data_at_share_join (fst (slice.cleave sh)) (snd (slice.cleave sh)) sh).\nauto.\napply slice.cleave_join.\nQed.\n\nLemma body_make_foo: semax_body Vprog Gprog f_make_foo make_foo_spec.\nProof.\nunfold make_foo_spec.\nstart_function.\nforward_call (Tstruct _foo_object noattr, gv).\n   split3; simpl; auto; computable.\nIntros p.\nforward_if\n  (PROP ( )\n   LOCAL (temp _p p; gvars gv)\n   SEP (mem_mgr gv;\n          malloc_token Ews (Tstruct _foo_object noattr) p;\n          data_at_ Ews (Tstruct _foo_object noattr) p;\n          object_methods foo_invariant (gv _foo_methods))).\n*\nchange (Memory.EqDec_val p nullval) with (eq_dec p nullval).\nif_tac; entailer!.\n*\nforward_call tt.\ncontradiction.\n*\nrewrite if_false by auto.\nIntros.\nforward.  (*  /*skip*/;  *)\nentailer!.\n*\nunfold data_at_, field_at_, default_val; simpl.\nforward. (* p->mtable = &foo_methods; *)\nforward. (* p->data = 0; *)\nforward. (* return (struct object * ) p; *)\nExists p.\nunfold object_mpred.\nExists foo_invariant (gv _foo_methods).\nsep_apply (split_object_methods foo_invariant (gv _foo_methods)).\nunfold foo_invariant at 4.\nentailer!.\nsimpl.\nunfold_data_at (field_at _ _ nil _ p).\ncancel.\nunfold withspacer; simpl.\nrewrite !field_at_data_at.\nsimpl.\napply derives_refl'.\nrewrite <- ?sepcon_assoc. (* needed if Archi.ptr64=true *)\nrewrite !field_compatible_field_address; auto with field_compatible.\nclear - H.\n(* TODO: simplify the following proof. *)\ndestruct p; try contradiction.\ndestruct H as [AL SZ].\nrepeat split; auto.\nsimpl in *; omega.\neapply align_compatible_rec_Tstruct; [reflexivity |].\nsimpl co_members; intros.\nsimpl in H.\nif_tac in H; [| inv H].\ninv H. inv H0.\neapply align_compatible_rec_by_value.\nreflexivity.\nrewrite Z.add_0_r.\nsimpl.\nunfold natural_alignment in AL.\neapply Z.divide_trans; [ | apply AL].\napply prove_Zdivide.\nreflexivity.\nleft; auto.\nQed.\n\n\nLemma make_object_methods:\n  forall sh instance reset twiddle mtable,\n  readable_share sh ->\n  func_ptr' (reset_spec instance) reset *\n  func_ptr' (twiddle_spec instance) twiddle *\n  data_at sh (Tstruct _methods noattr) (reset, twiddle) mtable\n  |-- object_methods instance mtable.\nProof.\n  intros.\n  unfold object_methods.\n  Exists sh reset twiddle.\n  entailer!.\nQed.\n\nLtac method_call witness hist' result :=\nrepeat apply seq_assoc1;\nmatch goal with \n   |- semax _ (PROPx _ (LOCALx ?Q (SEPx ?R))) \n            (Ssequence (Sset ?mt (Efield (Ederef (Etempvar ?x _)  _) _ _))\n                 _) _  =>\n    match Q with context [temp ?x ?x'] =>\n     match R with context [object_mpred _ x'] =>\n          let instance := fresh \"instance\" in let mtable := fresh \"mtable\" in\n          unfold object_mpred; Intros instance mtable;\n          forward;\n          unfold object_methods at 1; \n          let sh := fresh \"sh\" in let r := fresh \"r\" in let t := fresh \"t\" in\n          Intros sh r t;\n          forward;\n          forward_call witness;\n          [ .. | try Intros result;\n                  sep_apply (make_object_methods sh instance r t mtable); [ auto .. | ];\n                  sep_apply (object_mpred_i hist' x' instance mtable);\n                  deadvars; try clear dependent sh; try clear r; try clear t\n           ]\n    end end\nend.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nsep_apply (create_mem_mgr gv).\n(* assert_gvar _foo_methods. (* TODO: this is needed for a field_compatible later on *) *)\nfold noattr cc_default.\n(* 0. This part should be handled automatically by start_function *)\ngather_SEP 1 2;\nreplace_SEP 0 (data_at Ews (Tstruct _methods noattr) \n   (gv _foo_reset, gv _foo_twiddle) (gv _foo_methods)). {\n  entailer!.\n  unfold_data_at (data_at _ (Tstruct _methods _) _ (gv _foo_methods)).\n  rewrite <- mapsto_field_at with (gfs := [StructField _twiddle]) (v:= (gv _foo_twiddle))\n  by  auto with field_compatible.\n  rewrite field_at_data_at.  rewrite !field_compatible_field_address by auto with field_compatible.\n  rewrite !isptr_offset_val_zero by auto.\n  cancel.\n}\n\n(* 1. Prove that [mtable] is a proper method-table for foo-objects *)\n\nmake_func_ptr _foo_twiddle.\nmake_func_ptr _foo_reset.\nsep_apply (make_object_methods Ews foo_invariant(gv _foo_reset) (gv _foo_twiddle) (gv _foo_methods)); auto.\n\n(* 2. Build an instance of class [foo], called [p] *)\nforward_call (* p = make_foo(); *)\n        gv.\nIntros p.\n\n(* 3. Done with object_methods for the foreseeable future *)\nfreeze [2]  MT.\n gather_SEP 1.\n\n(* Illustration of an alternate method to prove the method calls.\n   Method 1:  comment out lines AA and BB and the entire range CC-DD.\n   Method 2:  comment out lines AA-BB, inclusive.\n*)\n\n(* AA *) try (tryif \n  (method_call (p, @nil Z) (@nil Z) whatever;\n   method_call (p, 3, @nil Z) [3%Z] i;\n     [simpl; computable | ])\n(* BB *)  then fail else fail 99)\n  .\n\n(* CC *)\n(* 4. first method-call *)\nunfold object_mpred.\nIntros instance mtable0.\nforward. (*  mtable = p->mtable; *)\nunfold object_methods at 1.\nIntros sh r0 t0.\nforward. (* p_reset = mtable->reset; *)\nforward_call (* p_reset(p); *)\n      (p, @nil Z).\n(* Finish the method-call by regathering the object p back together *)\nsep_apply (make_object_methods sh instance r0 t0 mtable0); auto.\nsep_apply (object_mpred_i [] p instance mtable0).\ndeadvars!. clear.\n\n(* 5. second method-call *)\nunfold object_mpred.\nIntros instance mtable0.\nforward.  (* mtable = p->mtable; *)\nunfold object_methods at 1.\nIntros sh r0 t0.\nforward.   (* p_twiddle = mtable->twiddle; *)\nforward_call (* i = p_twiddle(p,3); *)\n      (p, 3, @nil Z).\n  simpl. computable.\nIntros i.\nsimpl in H0.\nsep_apply (make_object_methods sh instance r0 t0 mtable0); auto.\nsep_apply (object_mpred_i [3] p instance mtable0).\ndeadvars!. clear - H0.\n\n(* DD *)\n\n(* 6. return *)\nforward.  (* return i; *)\nExists i; entailer!.\nQed.\n\n\n\n\n\n", "meta": {"author": "anshumanmohan", "repo": "RamifyCoq_VST", "sha": "0517a39b069f79f50a45321db6ca81c48397b73d", "save_path": "github-repos/coq/anshumanmohan-RamifyCoq_VST", "path": "github-repos/coq/anshumanmohan-RamifyCoq_VST/RamifyCoq_VST-0517a39b069f79f50a45321db6ca81c48397b73d/VST/progs64/verif_object.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.21905224315426988}}
{"text": "Require Import GhostSimulations.\n\nRequire Import Raft.\nRequire Import RaftRefinementInterface.\nRequire Import CommonTheorems.\nRequire Import SpecLemmas.\nRequire Import RefinementSpecLemmas.\nRequire Import RefinementCommonTheorems.\n\nRequire Import UpdateLemmas.\nLocal Arguments update {_} {_} {_} _ _ _ _ : simpl never.\n\nRequire Import LeaderLogsVotesWithLogInterface.\nRequire Import VotesCorrectInterface.\nRequire Import CroniesCorrectInterface.\nRequire Import VotesVotesWithLogCorrespondInterface.\nRequire Import LeaderLogsTermSanityInterface.\nRequire Import OneLeaderLogPerTermInterface.\n\nSection OneLeaderLogPerTerm.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n  Context {rri : raft_refinement_interface}.\n\n  Context {llvwli : leaderLogs_votesWithLog_interface}.\n  Context {vci : votes_correct_interface}.\n  Context {cci : cronies_correct_interface}.\n  Context {vvci : votes_votesWithLog_correspond_interface}.\n  Context {lltsi : leaderLogs_term_sanity_interface}.\n\n  Ltac update_destruct :=\n    match goal with\n      | [ |- context [ update _ ?y _ ?x ] ] => destruct (name_eq_dec y x)\n      | [ H : context [ update _ ?y _ ?x ] |- _ ] => destruct (name_eq_dec y x)\n    end.\n\n  Ltac start :=\n    red; unfold one_leaderLog_per_term; simpl; intros.\n\n  Ltac start_update :=\n    start;\n    repeat find_higher_order_rewrite;\n    repeat (update_destruct; subst; rewrite_update);\n    [| | |eauto].\n\n  Lemma one_leaderLog_per_term_init :\n    refined_raft_net_invariant_init one_leaderLog_per_term.\n  Proof using. \n    start. contradiction.\n  Qed.\n\n  Lemma one_leaderLog_per_term_unchanged :\n    forall net st' ps' h gd d,\n      one_leaderLog_per_term net ->\n      (forall h' : Net.name, st' h' = update (nwState net) h (gd, d) h') ->\n      leaderLogs gd = leaderLogs (fst (nwState net h)) ->\n      one_leaderLog_per_term {| nwPackets := ps'; nwState := st' |}.\n  Proof using. \n    unfold one_leaderLog_per_term. intros.\n    repeat find_higher_order_rewrite;\n    repeat (update_destruct; subst; rewrite_update);\n    simpl in *; repeat find_rewrite; eauto.\n  Qed.\n\n  Ltac start_unchanged :=\n    red; intros; eapply one_leaderLog_per_term_unchanged; eauto; subst.\n\n  (* solve invariant by lemma which shows leader logs do not change *)\n  Ltac unchanged lem :=\n    start_unchanged; apply lem.\n\n  Lemma one_leaderLog_per_term_client_request :\n    refined_raft_net_invariant_client_request one_leaderLog_per_term.\n  Proof using. \n    unchanged update_elections_data_client_request_leaderLogs.\n  Qed.\n\n  Lemma one_leaderLog_per_term_timeout :\n    refined_raft_net_invariant_timeout one_leaderLog_per_term.\n  Proof using. \n    unchanged update_elections_data_timeout_leaderLogs.\n  Qed.\n\n  Lemma one_leaderLog_per_term_append_entries :\n    refined_raft_net_invariant_append_entries one_leaderLog_per_term.\n  Proof using. \n    unchanged update_elections_data_appendEntries_leaderLogs.\n  Qed.\n\n  Lemma one_leaderLog_per_term_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply one_leaderLog_per_term.\n  Proof using. \n    start_unchanged. auto.\n  Qed.\n\n  Lemma one_leaderLog_per_term_request_vote :\n    refined_raft_net_invariant_request_vote one_leaderLog_per_term.\n  Proof using. \n    unchanged leaderLogs_update_elections_data_requestVote.\n  Qed.\n\n  Lemma update_elections_data_requestVoteReply_leaderLogs' :\n    forall h h' t st t' ll' r,\n      In (t', ll') (leaderLogs (update_elections_data_requestVoteReply h h' t r st)) ->\n      In (t', ll') (leaderLogs (fst st))\n      \\/ (r = true\n          /\\ t = currentTerm (snd st)\n          /\\ ll' = log (snd st)\n          /\\ t' = currentTerm (snd st)\n          /\\ type (snd st) = Candidate\n          /\\ wonElection (dedup name_eq_dec (h' :: votesReceived (snd st))) = true).\n  Proof using. \n    unfold update_elections_data_requestVoteReply.\n    intros.\n    repeat break_match; auto.\n    simpl in *. intuition.\n    find_inversion. right.\n    unfold handleRequestVoteReply in *.\n    repeat break_match; simpl in *; intuition; try congruence;\n    break_if; try congruence; do_bool; eauto using le_antisym.\n  Qed.\n\n  Lemma wonElection_length :\n    forall votes,\n      wonElection votes = true ->\n      length votes > div2 (length nodes).\n  Proof using. \n    unfold wonElection. intros. find_apply_lem_hyp leb_true_le. omega.\n  Qed.\n\n  Lemma pigeon_nodes :\n    forall (q1 q2 : list name),\n      NoDup q1 ->\n      NoDup q2 ->\n      length q1 > div2 (length nodes) ->\n      length q2 > div2 (length nodes) ->\n      exists v, In v q1 /\\ In v q2.\n  Proof using one_node_params. \n    intros. eapply pigeon with (l := nodes).\n    - apply name_eq_dec.\n    - intros. apply (@all_names_nodes _ multi_params).\n    - intros. apply (@all_names_nodes _ multi_params).\n    - apply (@no_dup_nodes _ multi_params).\n    - assumption.\n    - assumption.\n    - apply div2_correct; assumption.\n  Qed.\n\n  (* two different hosts cannot both have the same term in their leader logs *)\n  Lemma contradiction_case :\n    forall (net : network ) t ll ll' (h h' : name) (p : packet (params := refined_multi_params (multi_params := multi_params))) t0 v xs ys,\n      refined_raft_intermediate_reachable net ->\n      pBody p = RequestVoteReply (raft_params := raft_params) t0 v ->\n      nwPackets net = xs ++ p :: ys ->\n      In (t, ll) (leaderLogs (fst (nwState net h))) ->\n      In (t, ll') (leaderLogs (update_elections_data_requestVoteReply (pDst p) (pSrc p) t0 v (nwState net (pDst p)))) ->\n      pDst p = h' ->\n      pDst p <> h ->\n      False.\n  Proof using vvci cci vci llvwli. \n    intros. unfold not in *. find_false.\n    simpl in *. find_apply_lem_hyp update_elections_data_requestVoteReply_leaderLogs'.\n    intro_refined_invariant leaderLogs_votesWithLog_invariant.\n    break_or_hyp; repeat (apply_prop_hyp leaderLogs_votesWithLog In; break_exists).\n    - assert (exists h, In h x /\\ In h x0) by (apply pigeon_nodes; intuition).\n      break_exists; break_and.\n      do 2 (find_apply_hyp_hyp; break_exists; break_and).\n      intro_refined_invariant votes_votesWithLog_correspond_invariant.\n      do 2 (apply_prop_hyp votes_votesWithLog In).\n      intro_refined_invariant votes_correct_invariant.\n      eauto.\n    - assert (exists h, In h x /\\ In h (dedup name_eq_dec (pSrc p :: votesReceived (snd (nwState net (pDst p)))))).\n      { eapply pigeon_nodes.\n        - intuition.\n        - apply NoDup_dedup.\n        - intuition.\n        - apply wonElection_length; intuition. }\n      break_exists. break_and.\n      find_apply_hyp_hyp; break_exists; break_and.\n      intro_refined_invariant votes_votesWithLog_correspond_invariant.\n      apply_prop_hyp votes_votesWithLog In.\n      find_apply_lem_hyp in_dedup_was_in.\n      simpl in *.\n      intro_refined_invariant cronies_correct_invariant.\n      intro_refined_invariant votes_correct_invariant.\n      break_or_hyp; eauto.\n  Qed.\n\n  Lemma one_leaderLog_per_term_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply one_leaderLog_per_term.\n  Proof using lltsi vvci cci vci llvwli. \n    start. repeat find_higher_order_rewrite. repeat (update_destruct; rewrite_update).\n    - split; [subst; auto|].\n      find_copy_eapply_lem_hyp leaderLogs_update_elections_data_RVR; [|eauto].\n      pose proof H.\n      eapply leaderLogs_update_elections_data_RVR with (ll0 := ll) in H; [|eauto].\n      intro_refined_invariant leaderLogs_currentTerm_sanity_candidate_invariant.\n      intuition.\n      + match goal with\n        | [ h: _ |- _ ] => solve[eapply h; eauto]\n        end.\n      + apply_prop_hyp leaderLogs_currentTerm_sanity_candidate nwState; auto.\n        find_copy_apply_lem_hyp handleRequestVoteReply_type. intuition; unfold raft_data in *; simpl in *.\n        * subst. repeat find_rewrite. discriminate.\n        * find_apply_lem_hyp lt_asym. congruence.\n        * subst. repeat find_rewrite. find_apply_lem_hyp lt_irrefl. contradiction.\n      + apply_prop_hyp leaderLogs_currentTerm_sanity_candidate nwState; auto.\n        find_copy_apply_lem_hyp handleRequestVoteReply_type. intuition; unfold raft_data in *; simpl in *.\n        * subst. repeat find_rewrite. discriminate.\n        * find_apply_lem_hyp lt_asym. congruence.\n        * subst. repeat find_rewrite. find_apply_lem_hyp lt_irrefl. contradiction.\n      + subst. auto.\n    - exfalso. eapply contradiction_case; eauto.\n    - exfalso. eapply contradiction_case; eauto.\n    - eauto.\n  Qed.\n\n  Lemma one_leaderLog_per_term_do_leader :\n    refined_raft_net_invariant_do_leader one_leaderLog_per_term.\n  Proof using. \n    start_unchanged. find_rewrite. auto.\n  Qed.\n\n  Lemma one_leaderLog_per_term_do_generic_server :\n    refined_raft_net_invariant_do_generic_server one_leaderLog_per_term.\n  Proof using. \n    start_unchanged. find_rewrite. auto.\n  Qed.\n\n  Lemma one_leaderLog_per_term_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset one_leaderLog_per_term.\n  Proof using. \n    start. repeat find_reverse_higher_order_rewrite. eauto.\n  Qed.\n\n  Lemma one_leaderLog_per_term_reboot :\n    refined_raft_net_invariant_reboot one_leaderLog_per_term.\n  Proof using. \n    start_update; eapply H0; unfold reboot in *; try find_rewrite; simpl in *; eauto.\n  Qed.\n\n  Lemma one_leaderLog_per_term_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      one_leaderLog_per_term net.\n  Proof using lltsi vvci cci vci llvwli rri. \n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply one_leaderLog_per_term_init.\n    - apply one_leaderLog_per_term_client_request.\n    - apply one_leaderLog_per_term_timeout.\n    - apply one_leaderLog_per_term_append_entries.\n    - apply one_leaderLog_per_term_append_entries_reply.\n    - apply one_leaderLog_per_term_request_vote.\n    - apply one_leaderLog_per_term_request_vote_reply.\n    - apply one_leaderLog_per_term_do_leader.\n    - apply one_leaderLog_per_term_do_generic_server.\n    - apply one_leaderLog_per_term_state_same_packet_subset.\n    - apply one_leaderLog_per_term_reboot.\n  Qed.\n\n  Instance ollpti : one_leaderLog_per_term_interface.\n  Proof.\n    split; intros; intro_refined_invariant one_leaderLog_per_term_invariant;\n      red; eapply_prop one_leaderLog_per_term.\n  Qed.\n\nEnd OneLeaderLogPerTerm.", "meta": {"author": "ahmet-celik", "repo": "pverdi", "sha": "dc88c4a5fd7d90b5bb48e583bd8286097f983f81", "save_path": "github-repos/coq/ahmet-celik-pverdi", "path": "github-repos/coq/ahmet-celik-pverdi/pverdi-dc88c4a5fd7d90b5bb48e583bd8286097f983f81/raft-proofs/OneLeaderLogPerTermProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21905223738755256}}
{"text": "From iris.algebra Require Import auth agree excl gmap frac.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.base_logic Require Import invariants.\nFrom iris.program_logic Require Import adequacy.\nRequire Import Eqdep_dec.\nFrom cap_machine Require Import\n     stdpp_extra iris_extra\n     rules logrel fundamental.\nFrom cap_machine.examples Require Import\n     macros malloc counter_preamble disjoint_regions_tactics mkregion_helpers.\n\nInstance DisjointList_list_Addr : DisjointList (list Addr).\nProof. exact (@disjoint_list_default _ _ app []). Defined.\n\nClass memory_layout `{MachineParameters} := {\n  (* awkward example: preamble & body *)\n  counter_region_start : Addr;\n  counter_preamble_start : Addr;\n  counter_body_start : Addr;\n  counter_region_end : Addr;\n\n  (* pointer to the linking table, at the beginning of the region *)\n  counter_linking_ptr_size :\n    (counter_region_start + 1)%a = Some counter_preamble_start;\n\n  (* preamble code, that allocates the closure *)\n  counter_preamble_size :\n    (counter_preamble_start + counter_preamble_instrs_length)%a\n    = Some counter_body_start;\n\n  (* code of the body, wrapped in the closure allocated by the preamble *)\n  counter_body_size :\n    (counter_body_start + counter_instrs_length)%a\n    = Some counter_region_end;\n\n  (* adversary code *)\n  adv_start : Addr;\n  adv_end : Addr;\n\n  (* malloc routine *)\n  malloc_start : Addr;\n  malloc_memptr : Addr;\n  malloc_mem_start : Addr;\n  malloc_end : Addr;\n\n  malloc_code_size :\n    (malloc_start + length malloc_subroutine_instrs)%a\n    = Some malloc_memptr;\n\n  malloc_memptr_size :\n    (malloc_memptr + 1)%a = Some malloc_mem_start;\n\n  malloc_mem_size :\n    (malloc_mem_start <= malloc_end)%a;\n\n  (* fail routine *)\n  assert_start : Addr;\n  assert_cap : Addr;\n  assert_flag : Addr;\n  assert_end : Addr;\n\n  assert_code_size :\n    (assert_start + length assert_subroutine_instrs)%a = Some assert_cap;\n  assert_cap_size :\n    (assert_cap + 1)%a = Some assert_flag;\n  assert_flag_size :\n    (assert_flag + 1)%a = Some assert_end;\n\n  (* link table *)\n  link_table_start : Addr;\n  link_table_end : Addr;\n\n  link_table_size :\n    (link_table_start + 2)%a = Some link_table_end;\n\n  (* disjointness of all the regions above *)\n  regions_disjoint :\n    ## [\n        finz.seq_between link_table_start link_table_end;\n        [assert_flag];\n        [assert_cap];\n        finz.seq_between assert_start assert_cap;\n        finz.seq_between malloc_mem_start malloc_end;\n        [malloc_memptr];\n        finz.seq_between malloc_start malloc_memptr;\n        finz.seq_between adv_start adv_end;\n        finz.seq_between counter_body_start counter_region_end;\n        finz.seq_between counter_preamble_start counter_body_start;\n        [counter_region_start]\n       ];\n}.\n\nDefinition offset_to_awkward `{memory_layout} : Z :=\n  (* in this setup, the body of the counter comes just after the code\n     of the preamble *)\n  (counter_preamble_instrs_length - counter_preamble_move_offset)%Z.\n\nDefinition mk_initial_memory `{memory_layout} (adv_val: list Word) : gmap Addr Word :=\n  (* pointer to the linking table *)\n    list_to_map [(counter_region_start,\n                  WCap RO link_table_start link_table_end link_table_start)]\n  ∪ mkregion counter_preamble_start counter_body_start\n       (* preamble: code that creates the awkward example closure *)\n      (counter_preamble_instrs 0%Z (* offset to malloc in linking table *)\n         offset_to_awkward (* offset to the body of the example *))\n  ∪ mkregion counter_body_start counter_region_end\n       (* body of the counter, that will be encapsulated in the closure\n          created by the preamble *)\n      (counter_instrs 1) (* offset to fail in the linking table *)\n\n  ∪ mkregion adv_start adv_end\n      (* adversarial code: any code or data, but no capabilities (see condition below) except for malloc *)\n      (adv_val ++ [WCap E malloc_start malloc_end malloc_start])\n  ∪ mkregion malloc_start malloc_memptr\n      (* code for the malloc subroutine *)\n      malloc_subroutine_instrs\n  ∪ list_to_map\n      (* Capability to malloc's memory pool, used by the malloc subroutine *)\n      [(malloc_memptr, WCap RWX malloc_memptr malloc_end malloc_mem_start)]\n  ∪ mkregion malloc_mem_start malloc_end\n      (* Malloc's memory pool, initialized to zero *)\n      (region_addrs_zeroes malloc_mem_start malloc_end)\n  ∪ mkregion assert_start assert_cap\n      (* code for the failure subroutine *)\n      assert_subroutine_instrs\n  ∪ list_to_map [(assert_cap, WCap RW assert_flag assert_end assert_flag)]\n      (* pointer to the \"assert\" flag, set to 1 by the routine *)\n  ∪ list_to_map [(assert_flag, WInt 0%Z)]\n      (* assert flag, initialized to 0 *)\n  ∪ mkregion link_table_start link_table_end\n      (* link table, with pointers to the malloc and failure subroutines *)\n      [WCap E malloc_start malloc_end malloc_start;\n       WCap E assert_start assert_end assert_start]\n.\n\nDefinition is_initial_memory `{memory_layout} (m: gmap Addr Word) :=\n  ∃ (adv_val: list Word),\n  m = mk_initial_memory adv_val\n  ∧\n  (* the adversarial region in memory must only contain instructions, no\n     capabilities (it can thus only access capabilities the awkward preamble\n     passes it through the registers) *)\n  Forall (λ w, is_z w = true) adv_val\n  ∧\n  (adv_start + (length adv_val + 1)%nat)%a = Some adv_end.\n\nDefinition is_initial_registers `{memory_layout} (reg: gmap RegName Word) :=\n  reg !! PC = Some (WCap RX counter_region_start counter_region_end counter_preamble_start) ∧\n  reg !! r_t0 = Some (WCap RWX adv_start adv_end adv_start) ∧\n  (∀ (r: RegName), r ∉ ({[ PC; r_t0 ]} : gset RegName) →\n    ∃ (w:Word), reg !! r = Some w ∧ is_z w = true).\n\nLemma initial_registers_full_map `{MachineParameters, memory_layout} reg :\n  is_initial_registers reg →\n  (∀ r, is_Some (reg !! r)).\nProof.\n  intros (HPC & Hr0 & Hothers) r.\n  destruct (decide (r = PC)) as [->|]. by eauto.\n  destruct (decide (r = r_t0)) as [->|]. by eauto.\n  destruct (Hothers r) as (w & ? & ?); [| eauto]. set_solver.\nQed.\n\nSection Adequacy.\n  Context (Σ: gFunctors).\n  Context {inv_preg: invGpreS Σ}.\n  Context {mem_preg: gen_heapGpreS Addr Word Σ}.\n  Context {reg_preg: gen_heapGpreS RegName Word Σ}.\n  Context {seal_store_preg: sealStorePreG Σ}.\n  Context {na_invg: na_invG Σ}.\n  Context `{MP: MachineParameters}.\n\n  Definition assertN : namespace := nroot .@ \"lib\" .@ \"assert\".\n  Definition flagN : namespace := nroot .@ \"lib\" .@ \"assert_flag\".\n  Definition mallocN : namespace := nroot .@ \"lib\" .@ \"malloc\".\n\n  Lemma counter_adequacy' `{memory_layout} (m m': Mem) (reg reg': Reg) (es: list cap_lang.expr):\n    is_initial_memory m →\n    is_initial_registers reg →\n    rtc erased_step ([Seq (Instr Executable)], (reg, m)) (es, (reg', m')) →\n    m' !! assert_flag = Some (WInt 0%Z).\n  Proof.\n    intros Hm Hreg Hstep.\n    pose proof (@wp_invariance Σ cap_lang _ NotStuck) as WPI. cbn in WPI.\n    pose (fun (c: ExecConf) => c.2 !! assert_flag = Some (WInt 0%Z)) as state_is_good.\n    specialize (WPI (Seq (Instr Executable)) (reg, m) es (reg', m') (state_is_good (reg', m'))).\n    eapply WPI. 2: assumption. intros Hinv κs. clear WPI.\n\n    destruct Hm as (adv_val & Hm & Hadv_val & adv_size).\n    iMod (gen_heap_init (m:Mem)) as (mem_heapg) \"(Hmem_ctx & Hmem & _)\".\n    iMod (gen_heap_init (reg:Reg)) as (reg_heapg) \"(Hreg_ctx & Hreg & _)\".\n    iMod (seal_store_init) as (seal_storeg) \"Hseal_store\".\n    iMod (@na_alloc Σ na_invg) as (logrel_nais) \"Hna\".\n\n    pose memg := MemG Σ Hinv mem_heapg.\n    pose regg := RegG Σ Hinv reg_heapg.\n    pose logrel_na_invs := Build_logrel_na_invs _ na_invg logrel_nais.\n    \n    pose proof (\n      @counter_preamble_spec Σ memg regg seal_storeg logrel_na_invs\n    ) as Spec.\n\n    (* Extract points-to for the various regions in memory *)\n\n    pose proof regions_disjoint as Hdisjoint.\n    rewrite {2}Hm.\n    rewrite disjoint_list_cons in Hdisjoint |- *. destruct Hdisjoint as (Hdisj_link_table & Hdisjoint).\n    (* iDestruct (big_sepM_union with \"Hmem\") as \"[Hmem Hfail_flag]\". *)\n    (* { disjoint_map_to_list. set_solver +Hdisj_fail_flag. } *)\n    (* iDestruct (big_sepM_insert with \"Hfail_flag\") as \"[Hfail_flag _]\". *)\n    (*   by apply lookup_empty. cbn [fst snd]. *)\n    (* rewrite disjoint_list_cons in Hdisjoint |- *. intros (Hdisj_link_table & Hdisjoint). *)\n    iDestruct (big_sepM_union with \"Hmem\") as \"[Hmem Hlink_table]\".\n    { disjoint_map_to_list. set_solver+ Hdisj_link_table. }\n    rewrite disjoint_list_cons in Hdisjoint |- *. destruct Hdisjoint as (Hdisj_assert_flag & Hdisjoint).\n    iDestruct (big_sepM_union with \"Hmem\") as \"[Hmem Hassert_flag]\".\n    { disjoint_map_to_list. set_solver +Hdisj_assert_flag. }\n    iDestruct (big_sepM_insert with \"Hassert_flag\") as \"[Hassert_flag _]\".\n      by apply lookup_empty. cbn [fst snd].\n    rewrite disjoint_list_cons in Hdisjoint |- *. destruct Hdisjoint as (Hdisj_assert_cap & Hdisjoint).\n    iDestruct (big_sepM_union with \"Hmem\") as \"[Hmem Hassert_cap]\".\n    { disjoint_map_to_list. set_solver +Hdisj_assert_cap. }\n    iDestruct (big_sepM_insert with \"Hassert_cap\") as \"[Hassert_cap _]\".\n      by apply lookup_empty. cbn [fst snd].\n    rewrite disjoint_list_cons in Hdisjoint |- *. destruct Hdisjoint as (Hdisj_assert & Hdisjoint).\n    iDestruct (big_sepM_union with \"Hmem\") as \"[Hmem Hassert]\".\n    { disjoint_map_to_list. set_solver +Hdisj_assert. }\n    rewrite disjoint_list_cons in Hdisjoint |- *. destruct Hdisjoint as (Hdisj_malloc_mem & Hdisjoint).\n    iDestruct (big_sepM_union with \"Hmem\") as \"[Hmem Hmalloc_mem]\".\n    { disjoint_map_to_list. set_solver +Hdisj_malloc_mem. }\n    rewrite disjoint_list_cons in Hdisjoint |- *. destruct Hdisjoint as (Hdisj_malloc_memptr & Hdisjoint).\n    iDestruct (big_sepM_union with \"Hmem\") as \"[Hmem Hmalloc_memptr]\".\n    { disjoint_map_to_list. set_solver +Hdisj_malloc_memptr. }\n    iDestruct (big_sepM_insert with \"Hmalloc_memptr\") as \"[Hmalloc_memptr _]\".\n      by apply lookup_empty. cbn [fst snd].\n    rewrite disjoint_list_cons in Hdisjoint |- *. destruct Hdisjoint as (Hdisj_malloc_code & Hdisjoint).\n    iDestruct (big_sepM_union with \"Hmem\") as \"[Hmem Hmalloc_code]\".\n    { disjoint_map_to_list. set_solver +Hdisj_malloc_code. }\n    rewrite disjoint_list_cons in Hdisjoint |- *. destruct Hdisjoint as (Hdisj_adv & Hdisjoint).\n    iDestruct (big_sepM_union with \"Hmem\") as \"[Hmem Hadv]\".\n    { disjoint_map_to_list. set_solver +Hdisj_adv. }\n    rewrite disjoint_list_cons in Hdisjoint |- *. destruct Hdisjoint as (Hdisj_counter_body & Hdisjoint).\n    iDestruct (big_sepM_union with \"Hmem\") as \"[Hmem Hcounter_body]\".\n    { disjoint_map_to_list. set_solver +Hdisj_counter_body. }\n    rewrite disjoint_list_cons in Hdisjoint |- *. destruct Hdisjoint as (Hdisj_counter_preamble & _).\n    iDestruct (big_sepM_union with \"Hmem\") as \"[Hcounter_link Hcounter_preamble]\".\n    { disjoint_map_to_list. set_solver +Hdisj_counter_preamble. }\n    iDestruct (big_sepM_insert with \"Hcounter_link\") as \"[Hcounter_link _]\". by apply lookup_empty.\n    cbn [fst snd].\n    clear Hdisj_link_table Hdisj_assert_flag Hdisj_assert_cap Hdisj_assert Hdisj_malloc_mem\n          Hdisj_malloc_memptr Hdisj_malloc_code Hdisj_adv Hdisj_counter_body Hdisj_counter_preamble.\n\n    (* Massage points-to into sepL2s with permission-pointsto *)\n\n    iDestruct (mkregion_prepare with \"[$Hlink_table]\") as \">Hlink_table\". by apply link_table_size.\n    iDestruct (mkregion_prepare with \"[$Hassert]\") as \">Hassert\". by apply assert_code_size.\n    iDestruct (mkregion_prepare with \"[$Hmalloc_mem]\") as \">Hmalloc_mem\".\n    { rewrite replicate_length /finz.dist. clear.\n      generalize malloc_mem_start malloc_end malloc_mem_size. solve_addr. }\n    iDestruct (mkregion_prepare with \"[$Hmalloc_code]\") as \">Hmalloc_code\".\n      by apply malloc_code_size.\n    iDestruct (mkregion_prepare with \"[$Hadv]\") as \">Hadv\". rewrite app_length /=. by apply adv_size.\n    iDestruct (mkregion_prepare with \"[$Hcounter_preamble]\") as \">Hcounter_preamble\".\n      by apply counter_preamble_size.\n    iDestruct (mkregion_prepare with \"[$Hcounter_body]\") as \">Hcounter_body\". by apply counter_body_size.\n    rewrite -/(counter _ _) -/(counter_preamble _ _).\n\n    (* Split the link table *)\n\n    rewrite (finz_seq_between_cons link_table_start link_table_end).\n    2: { generalize link_table_size; clear; solve_addr. }\n    set link_entry_fail := (link_table_start ^+ 1)%a.\n    rewrite (finz_seq_between_cons link_entry_fail link_table_end).\n    2: { generalize link_table_size; clear. subst link_entry_fail.\n         generalize link_table_start link_table_end. solve_addr. }\n    rewrite (_: (link_entry_fail ^+ 1)%a = link_table_end).\n    2: { generalize link_table_size; clear. subst link_entry_fail.\n         generalize link_table_start link_table_end. solve_addr. }\n    iDestruct (big_sepL2_cons with \"Hlink_table\") as \"[Hlink1 Hlink_table]\".\n    iDestruct (big_sepL2_cons with \"Hlink_table\") as \"[Hlink2 _]\".\n\n    (* Allocate relevant invariants *)\n\n    iMod (inv_alloc flagN ⊤ (assert_flag ↦ₐ WInt 0%Z) with \"Hassert_flag\")%I as \"#Hinv_assert_flag\".\n    iMod (na_inv_alloc logrel_nais ⊤ assertN (assert_inv assert_start assert_flag assert_end)\n            with \"[Hassert Hassert_cap]\") as \"#Hinv_assert\".\n    { iNext. rewrite /assert_inv. iExists assert_cap. iFrame. rewrite /proofmode.codefrag.\n      rewrite (_: (assert_start ^+ length assert_subroutine_instrs)%a = assert_cap).\n       2: { generalize assert_code_size. solve_addr. } iFrame.\n       iPureIntro. generalize assert_code_size, assert_cap_size, assert_flag_size. cbn. done. }\n    iMod (na_inv_alloc logrel_nais ⊤ mallocN (malloc_inv malloc_start malloc_end)\n            with \"[Hmalloc_code Hmalloc_memptr Hmalloc_mem]\") as \"#Hinv_malloc\".\n    { iNext. rewrite /malloc_inv. iExists malloc_memptr, malloc_mem_start.\n      iFrame. rewrite /proofmode.codefrag.\n      rewrite (_: (malloc_start ^+ length malloc_subroutine_instrs)%a = malloc_memptr).\n      2: { generalize malloc_code_size. solve_addr. } iFrame.\n      iPureIntro. generalize malloc_code_size malloc_mem_size malloc_memptr_size. cbn.\n      clear; unfold malloc_subroutine_instrs_length; intros; repeat split; solve_addr. }\n    iDestruct (simple_malloc_subroutine_valid with \"[$Hinv_malloc]\") as \"Hmalloc_val\".\n\n    (* Show validity of the adversary capability *)\n    assert (contiguous_between (finz.seq_between adv_start adv_end) adv_start adv_end) as Hcont.\n    { apply contiguous_between_region_addrs. clear -adv_size. solve_addr. }\n    iDestruct (contiguous_between_program_split with \"Hadv\") as (adv_words malloc_word adv_end') \"(Hadv & Hmalloc & #Hcont)\";[eauto|]. \n    iDestruct \"Hcont\" as %(Hcontadv & Hcontmalloc & Heqapp & Hlink).\n    iDestruct (big_sepL2_length with \"Hmalloc\") as %Hlen1. simpl in Hlen1.\n    iDestruct (big_sepL2_length with \"Hadv\") as %Hlen2. simpl in Hlen2.\n      \n    iMod (region_inv_alloc _ (adv_words ++ malloc_word)\n                           (adv_val ++ [WCap E malloc_start malloc_end malloc_start])\n            with \"[Hadv Hmalloc]\") as \"Hadv\".\n    { iApply (big_sepL2_app');[auto|]. \n      iSplitL \"Hadv\". \n      - iApply (big_sepL2_mono with \"Hadv\").\n        intros k v1 v2 Hv1 Hv2. cbn. iIntros. iFrame.\n        pose proof (Forall_lookup_1 _ _ _ _ Hadv_val Hv2) as Hncap.\n        destruct v2; [| by inversion Hncap..].\n        rewrite fixpoint_interp1_eq /=. done.\n      - destruct malloc_word;[inversion Hlen1|]. destruct malloc_word;[|inversion Hlen1].\n        iDestruct \"Hmalloc\" as \"[Hmalloc _]\". iFrame \"∗ #\". done. \n    }\n    iDestruct \"Hadv\" as \"#Hadv\".\n    \n    (* Apply the spec, obtain that the PC is in the expression relation *)\n\n    iAssert ((interp_expr interp reg) (WCap RX counter_region_start counter_region_end counter_preamble_start))\n      with \"[Hcounter_preamble Hcounter_body Hinv_malloc Hcounter_link Hlink1 Hlink2]\" as \"HE\".\n    { assert (isCorrectPC_range RX counter_region_start counter_region_end\n                                counter_preamble_start counter_body_start).\n      { intros a [Ha1 Ha2]. constructor; auto.\n        generalize counter_linking_ptr_size counter_preamble_size counter_body_size. revert Ha1 Ha2. clear.\n        unfold counter_instrs_length, counter_preamble_instrs_length. solve_addr. }\n      set counter_preamble_move_addr := (counter_preamble_start ^+ counter_preamble_move_offset)%a.\n      assert ((counter_preamble_start + counter_preamble_move_offset)%a = Some counter_preamble_move_addr).\n      { clear. subst counter_preamble_move_addr.\n        generalize counter_preamble_size.\n        unfold counter_preamble_instrs_length, counter_preamble_move_offset.\n        generalize counter_preamble_start counter_body_start. solve_addr. }\n      assert (counter_preamble_move_addr + offset_to_awkward = Some counter_body_start)%a.\n      { generalize counter_preamble_size.\n        unfold counter_preamble_move_addr, offset_to_awkward, counter_preamble_instrs_length.\n        unfold counter_preamble_move_offset. clear.\n        generalize counter_preamble_start counter_body_start. solve_addr. }\n      assert (isCorrectPC_range RX counter_region_start counter_region_end\n                                counter_body_start counter_region_end).\n      { intros a [Ha1 Ha2]. constructor; auto.\n        generalize counter_linking_ptr_size counter_preamble_size counter_body_size. revert Ha1 Ha2; clear.\n        unfold counter_instrs_length, counter_preamble_instrs_length. solve_addr. }\n\n      iApply (Spec with \"[$Hinv_malloc $Hinv_assert $Hcounter_body $Hcounter_preamble $Hcounter_link $Hlink1 $Hlink2]\");\n        try eassumption.\n      - apply contiguous_between_region_addrs. generalize counter_preamble_size; clear.\n        unfold counter_preamble_instrs_length. solve_addr.\n      - apply le_addr_withinBounds. clear; solve_addr.\n        generalize link_table_size; clear; solve_addr.\n      - subst link_entry_fail. apply le_addr_withinBounds.\n        generalize link_table_start; clear; solve_addr.\n        generalize link_table_start link_table_end link_table_size. clear; solve_addr.\n      - clear; generalize link_table_start; solve_addr.\n      - clear; subst link_entry_fail;\n        generalize link_table_start link_table_end link_table_size; solve_addr.\n      - apply contiguous_between_region_addrs. generalize counter_body_size; clear.\n        unfold counter_instrs_length. solve_addr.\n      - solve_ndisj.\n      - solve_ndisj. }\n\n    clear Hm Spec. rewrite /interp_expr /=.\n\n    (* prepare registers *)\n\n    unfold is_initial_registers in Hreg.\n    destruct Hreg as (HPC & Hstk & Hrothers).\n\n    (* Specialize the expression relation, showing that registers are valid *)\n\n    iSpecialize (\"HE\" with \"[Hreg Hna]\").\n    { iFrame. iSplit; cycle 1.\n      { iFrame. rewrite /registers_mapsto. by rewrite insert_id. }\n      { iSplit. iPureIntro; intros; by apply initial_registers_full_map.\n        (* All capabilities in registers are valid! *)\n        iIntros (r v HrnPC Hsv).\n        (* r0 (return pointer to the adversary) is valid. Prove it using the\n           fundamental theorem. *)\n        destruct (decide (r = r_t0)) as [ -> |].\n        { rewrite Hsv in Hstk. inversion Hstk; subst v.\n          rewrite !fixpoint_interp1_eq /=.\n          iDestruct (big_sepL2_length with \"Hadv\") as %Hadvlength. \n          iDestruct (big_sepL2_to_big_sepL_l with \"Hadv\") as \"Hadv'\";auto. rewrite -Heqapp. \n          iApply (big_sepL_mono with \"Hadv'\"). iIntros (k v Hkv). cbn.\n          iIntros \"H\". iExists (interp). iFrame.\n          iSplit;auto. \n        }\n\n        (* Other registers *)\n        destruct (Hrothers r) as [rw [Hrw Hncap] ]. set_solver.\n        destruct rw; [| by inversion Hncap..]. simplify_map_eq.\n        by rewrite !fixpoint_interp1_eq /=. } }\n\n    (* We get a WP; conclude using the rest of the Iris adequacy theorem *)\n\n    iModIntro.\n    (* Same as the state_interp of [memG_irisG] in rules_base.v *)\n    iExists (fun σ κs _ => ((gen_heap_interp σ.1) ∗ (gen_heap_interp σ.2)))%I.\n    iExists (fun _ => True)%I. cbn. iFrame.\n    iSplitL \"HE\". { iApply (wp_wand with \"HE\"). eauto. }\n    iIntros \"[Hreg' Hmem']\". iExists (⊤ ∖ ↑flagN).\n    iInv flagN as \">Hflag\" \"Hclose\".\n    iDestruct (gen_heap_valid with \"Hmem' Hflag\") as %Hm'_flag.\n    iModIntro. iPureIntro. apply Hm'_flag.\n    Unshelve.\n  Qed.\n\nEnd Adequacy.\n\nTheorem counter_adequacy `{MachineParameters} `{memory_layout}\n        (m m': Mem) (reg reg': Reg) (es: list cap_lang.expr):\n  is_initial_memory m →\n  is_initial_registers reg →\n  rtc erased_step ([Seq (Instr Executable)], (reg, m)) (es, (reg', m')) →\n  m' !! assert_flag = Some (WInt 0%Z).\nProof.\n  set (Σ := #[invΣ; gen_heapΣ Addr Word; gen_heapΣ RegName Word; sealStorePreΣ;\n              na_invΣ]).\n  eapply (@counter_adequacy' Σ); typeclasses eauto.\nQed.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/examples/counter_adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2190522373875525}}
{"text": "From Coq Require Import String Arith ZArith PropExtensionality.\n\nFrom Vyper Require Import Config Calldag.\nFrom Vyper.L10 Require Import Base.\nFrom Vyper.L40 Require Import AST Descend Expr Callset Descend.\nFrom Vyper.L40Metered Require Import Interpret.\n\n(** The expression interpreter is in L40Metered.Interpret.\n    This is the proof that both interpreters of L40 work the same on expressions.\n *)\n\nLemma expr_metering_ok {C: VyperConfig}\n                       {bigger_call_depth_bound smaller_call_depth_bound: nat}\n                       (Ebound: bigger_call_depth_bound = S smaller_call_depth_bound)\n                       {cd: calldag}\n                       (fc: fun_ctx cd bigger_call_depth_bound)\n                       (do_call: forall\n                                     (fc': fun_ctx cd smaller_call_depth_bound)\n                                     (world: world_state)\n                                     (arg_values: list uint256),\n                                   world_state * expr_result uint256)\n                       (do_call_metered: forall\n                                           (decl: L40.AST.decl)\n                                           (world: world_state)\n                                           (arg_values: list uint256),\n                                         world_state * option (expr_result uint256))\n                       (DoCallOk: forall (fc': fun_ctx cd smaller_call_depth_bound)\n                                         (world: world_state)\n                                         (arg_values: list uint256),\n                                    let '(world', result) := do_call fc' world arg_values in\n                                      do_call_metered (fun_decl fc') world arg_values\n                                       =\n                                      (world', Some result))\n                       (builtins: string -> option builtin)\n                       (world: world_state)\n                       (loc: memory)\n                       (loops: list loop_ctx)\n                       (e: expr)\n                       (CallOk: let _ := string_set_impl in \n                                  FSet.is_subset (expr_callset e)\n                                                 (decl_callset (fun_decl fc))\n                                  = true):\n  let '(world', result) := interpret_expr Ebound fc do_call builtins world loc loops e CallOk in\n    interpret_expr_metered (cd_decls cd) do_call_metered builtins world loc loops e\n     =\n    (world', Some result).\nProof.\nrevert world loc loops. induction e using expr_ind'; try easy; intros; cbn.\n{ (* PrivateCall *)\n  unfold fun_ctx_descend.\n  unfold cd_declmap.\n  unfold map_lookup.\n  refine (match Map.lookup (cd_decls cd) name as z return _ = z -> _ with\n          | Some d => fun E => _\n          | None => fun NotFound => _\n          end eq_refl).\n  2:{\n    remember (fun d (Edecl : Map.lookup (cd_decls cd) name = Some d) =>\n               Descend.fun_ctx_descend_inner fc CallOk Ebound eq_refl Edecl) as branch_not_taken.\n    clear Heqbranch_not_taken.\n    revert branch_not_taken.\n    now rewrite NotFound.\n  }\n  replace (match\n             Map.lookup (cd_decls cd) name as maybe_decl\n             return (Map.lookup (cd_decls cd) name = maybe_decl -> option (fun_ctx cd smaller_call_depth_bound))\n           with\n           | Some d0 =>\n               fun Edecl : Map.lookup (cd_decls cd) name = Some d0 =>\n               Descend.fun_ctx_descend_inner fc CallOk Ebound eq_refl Edecl\n           | None => fun _ : Map.lookup (cd_decls cd) name = None => None\n           end eq_refl) with (Descend.fun_ctx_descend_inner fc CallOk Ebound eq_refl E).\n  2:{\n    remember (@Descend.fun_ctx_descend_inner C bigger_call_depth_bound smaller_call_depth_bound cd\n               (@PrivateCall C name args) fc CallOk Ebound name args\n               (@eq_refl (@expr C) (@PrivateCall C name args))) as foo.\n    clear Heqfoo.\n    unfold cd_declmap in foo.\n    destruct (Map.lookup (cd_decls cd) name). 2:discriminate.\n    inversion E; subst.\n    f_equal.\n    apply proof_irrelevance.\n  }\n  unfold Descend.fun_ctx_descend_inner.\n  assert (DepthmapOk := cd_depthmap_ok cd name).\n  rewrite E in DepthmapOk.\n  refine (match cd_depthmap cd name as z return _ = z -> _ with\n          | Some depth => fun Edepth => _\n          | None => fun NotFound => _\n          end eq_refl).\n  2: now rewrite NotFound in DepthmapOk.\n  rewrite Edepth in DepthmapOk.\n  rewrite FSet.for_all_ok in DepthmapOk.\n  replace (match\n             cd_depthmap cd name as maybe_depth\n             return (cd_depthmap cd name = maybe_depth -> option (fun_ctx cd smaller_call_depth_bound))\n           with\n           | Some depth0 =>\n               fun Edepth0 : cd_depthmap cd name = Some depth0 =>\n               Some\n                 {|\n                   fun_name := name;\n                   fun_depth := depth0;\n                   fun_depth_ok := Edepth0;\n                   fun_decl := d;\n                   fun_decl_ok := E;\n                   fun_bound_ok := Descend.call_descend' fc CallOk Ebound eq_refl E Edepth0\n                 |}\n           | None => _\n           end eq_refl)\n  with (Some\n           {|\n             fun_name := name;\n             fun_depth := depth;\n             fun_depth_ok := Edepth;\n             fun_decl := d;\n             fun_decl_ok := E;\n             fun_bound_ok := Descend.call_descend' fc CallOk Ebound eq_refl E Edepth\n           |}).\n  2:{\n    remember (fun Edepth0 : cd_depthmap cd name = None =>\n                False_rect (option (fun_ctx cd smaller_call_depth_bound)) (Descend.fun_ctx_descend_helper E Edepth0))\n      as bad. clear Heqbad.\n    remember (fun depth0 (Edepth0 : cd_depthmap cd name = Some depth0) =>\n    Some\n      {|\n        fun_name := name;\n        fun_depth := depth0;\n        fun_depth_ok := Edepth0;\n        fun_decl := d;\n        fun_decl_ok := E;\n        fun_bound_ok := Descend.call_descend' fc CallOk Ebound eq_refl E Edepth0\n      |}) as f.\n    replace (Some\n              {|\n                fun_name := name;\n                fun_depth := depth;\n                fun_depth_ok := Edepth;\n                fun_decl := d;\n                fun_decl_ok := E;\n                fun_bound_ok := Descend.call_descend' fc CallOk Ebound eq_refl E Edepth\n              |})\n    with (f depth Edepth)\n    by now subst.\n    clear Heqf.\n    destruct (cd_depthmap cd name). 2:discriminate.\n    inversion Edepth. subst.\n    f_equal.\n    apply proof_irrelevance.\n  }\n\n  remember (fix interpret_expr_list\n      (world0 : world_state) (loc0 : memory) (e : list expr)\n      (CallOk0 : FSet.is_subset (expr_list_callset e) (decl_callset (fun_decl fc)) = true) {struct e} :\n        world_state * expr_result (list uint256) := _) as interpret_expr_list.\n  remember (fix interpret_expr_list (world0 : world_state) (loc0 : memory) (e : list expr) {struct e} :\n            world_state * option (expr_result (list uint256)) := _) as interpret_expr_list_metered.\n\n  assert (ArgsOk: forall w l COk,\n                  let '(w', result) := interpret_expr_list w l args COk\n                  in interpret_expr_list_metered w l args = (w', Some result)).\n  {\n    induction args. { now subst. }\n    rewrite Heqinterpret_expr_list. rewrite Heqinterpret_expr_list_metered.\n    cbn.\n    rewrite<- Heqinterpret_expr_list. rewrite<- Heqinterpret_expr_list_metered.\n    clear Heqinterpret_expr_list Heqinterpret_expr_list_metered.\n    intros.\n    assert (CallOk': let _ := string_set_impl in\n                     FSet.is_subset (expr_callset (PrivateCall name args))\n                                    (decl_callset (fun_decl fc))\n                      = true).\n    {\n      cbn. cbn in CallOk.\n      rewrite FSet.add_subset_and.\n      rewrite FSet.add_subset_and in CallOk.\n      rewrite Bool.andb_true_iff.\n      rewrite Bool.andb_true_iff in CallOk.\n      destruct CallOk as (CallOk, HasFun).\n      split. 2:assumption. clear HasFun.\n      rewrite FSet.union_subset_and in CallOk.\n      rewrite Bool.andb_true_iff in CallOk.\n      tauto.\n    }  \n    assert (IH := IHargs CallOk' (List.Forall_inv_tail H) w l (callset_descend_tail eq_refl COk)).\n    clear IHargs.\n    destruct (interpret_expr_list w l args (callset_descend_tail eq_refl COk)) as (world', result).\n    rewrite IH. clear IH.\n    destruct result. 2:trivial.\n    assert (HeadOk := List.Forall_inv H (callset_descend_head eq_refl COk) world' l loops).\n    cbn in HeadOk. clear H.\n    destruct (interpret_expr Ebound fc do_call builtins world' l loops a (callset_descend_head eq_refl COk))\n      as (ww, ll).\n    rewrite HeadOk.\n    now destruct ll.\n  }\n\n  assert (DoCallMeteredFinishes:\n            forall (fc' : fun_ctx cd smaller_call_depth_bound) (w: world_state)\n                   (arg_values : list uint256),\n              snd (do_call_metered (fun_decl fc') w arg_values) <> None).\n  {\n    intros.\n    assert (D := DoCallOk fc' w arg_values).\n    destruct (do_call fc' w arg_values).\n    intro HH.\n    rewrite D in HH.\n    inversion HH.\n  }\n  assert (DFinishes: forall (w: world_state)\n                            (arg_values : list uint256),\n            snd (do_call_metered d w arg_values) <> None).\n  {\n    apply (DoCallMeteredFinishes {|\n                   fun_name := name;\n                   fun_depth := depth;\n                   fun_depth_ok := Edepth;\n                   fun_decl := d;\n                   fun_decl_ok := E;\n                   fun_bound_ok := Descend.call_descend' fc CallOk Ebound eq_refl E Edepth\n                 |}).\n  }\n  assert (DoCallRewrite: forall (w: world_state)\n                                (arg_values : list uint256),\n           do_call {|\n                   fun_name := name;\n                   fun_depth := depth;\n                   fun_depth_ok := Edepth;\n                   fun_decl := d;\n                   fun_decl_ok := E;\n                   fun_bound_ok := Descend.call_descend' fc CallOk Ebound eq_refl E Edepth\n                 |} w arg_values\n            =\n           match snd (do_call_metered d w arg_values) as z return _ = z -> _ with\n           | Some result => fun _ => (fst (do_call_metered d w arg_values), result)\n           | None => fun Bad => False_rect _ (DFinishes _ _ Bad)\n           end eq_refl).\n  {\n    intros.\n    remember {|\n                   fun_name := name;\n                   fun_depth := depth;\n                   fun_depth_ok := Edepth;\n                   fun_decl := d;\n                   fun_decl_ok := E;\n                   fun_bound_ok := Descend.call_descend' fc CallOk Ebound eq_refl E Edepth\n             |} as fc'.\n    assert (D := DoCallOk fc' w arg_values).\n    destruct (do_call fc' w arg_values) as (w', r').\n    remember (fun Bad : snd (do_call_metered d w arg_values) = None =>\n                False_rect (world_state * expr_result uint256) (DFinishes w arg_values Bad))\n      as foo. clear Heqfoo.\n    remember (snd (do_call_metered d w arg_values)) as s.\n    destruct s.\n    {\n      subst fc'. cbn in D.\n      rewrite D in *.\n      cbn in *.\n      f_equal.\n      now inversion Heqs.\n    }\n    subst fc'. cbn in D.\n    rewrite D in *.\n    cbn in Heqs.\n    discriminate.\n  }\n  clear H Heqinterpret_expr_list Heqinterpret_expr_list_metered.\n  assert (A := ArgsOk world loc (callset_descend_args eq_refl CallOk)). clear ArgsOk.\n  destruct (interpret_expr_list world loc args (callset_descend_args eq_refl CallOk))\n    as (world', result_args).\n  rewrite A.\n  unfold cd_declmap in *.\n  destruct result_args. 2:{ now rewrite E. }\n  rewrite DoCallRewrite. clear DoCallRewrite.\n  rewrite E.\n  assert (Ok := DFinishes world' value).\n  remember (fun Bad : snd (do_call_metered d world' value) = None =>\n             False_rect (world_state * expr_result uint256) (DFinishes world' value Bad))\n    as bad. clear Heqbad.\n  remember (snd (do_call_metered d world' value)) as x. destruct x.\n  { rewrite Heqx. now destruct (do_call_metered d world' value). }\n  symmetry in Heqx. contradiction.\n}\n(* BuiltinCall *)\nremember (fix interpret_expr_list\n    (world0 : world_state) (loc0 : memory) (e : list expr)\n    (CallOk0 : FSet.is_subset (expr_list_callset e) (decl_callset (fun_decl fc)) = true) {struct e} :\n      world_state * expr_result (list uint256) := _) as interpret_expr_list.\nremember (fix interpret_expr_list (world0 : world_state) (loc0 : memory) (e : list expr) {struct e} :\n          world_state * option (expr_result (list uint256)) := _) as interpret_expr_list_metered.\nassert (ArgsOk: forall w l COk,\n                let '(w', result) := interpret_expr_list w l args COk\n                in interpret_expr_list_metered w l args = (w', Some result)).\n{\n  induction args. { now subst. }\n  rewrite Heqinterpret_expr_list. rewrite Heqinterpret_expr_list_metered.\n  cbn.\n  rewrite<- Heqinterpret_expr_list. rewrite<- Heqinterpret_expr_list_metered.\n  clear Heqinterpret_expr_list Heqinterpret_expr_list_metered.\n  intros.\n  assert (CallOk': let _ := string_set_impl in\n                   FSet.is_subset (expr_callset (BuiltinCall name args))\n                                  (decl_callset (fun_decl fc))\n                    = true).\n  {\n    cbn. cbn in CallOk.\n    rewrite FSet.union_subset_and in CallOk.\n    rewrite Bool.andb_true_iff in CallOk.\n    tauto.\n  }\n  assert (IH := IHargs CallOk' (List.Forall_inv_tail H) w l (callset_descend_tail eq_refl COk)).\n  clear IHargs.\n  destruct (interpret_expr_list w l args (callset_descend_tail eq_refl COk)) as (world', result).\n  rewrite IH. clear IH.\n  destruct result. 2:trivial.\n  assert (HeadOk := List.Forall_inv H (callset_descend_head eq_refl COk) world' l loops).\n  cbn in HeadOk. clear H.\n  destruct (interpret_expr Ebound fc do_call builtins world' l loops a (callset_descend_head eq_refl COk))\n    as (ww, ll).\n  rewrite HeadOk.\n  now destruct ll.\n}\nclear H Heqinterpret_expr_list Heqinterpret_expr_list_metered.\nassert (A := ArgsOk world loc (callset_descend_builtin_args eq_refl CallOk)). clear ArgsOk.\ndestruct (interpret_expr_list world loc args (callset_descend_builtin_args eq_refl CallOk))\n  as (world', result_args).\nrewrite A. clear A.\ndestruct result_args. 2:reflexivity.\ndestruct (builtins name). 2:reflexivity.\ndestruct b as (arity, b).\nremember (fun Earity : (arity =? Datatypes.length value) = true => call_builtin value Earity (b world'))\n  as good_branch_1.\nremember (fun Earity : (arity =? Datatypes.length value) = true =>\n   let '(world'', result0) := call_builtin value Earity (b world') in (world'', Some result0))\n  as good_branch_2.\nenough (Q: forall E, let '(w, result) := good_branch_1 E in\n           good_branch_2 E = (w, Some result)).\n{\n  clear Heqgood_branch_1 Heqgood_branch_2.\n  destruct (arity =? Datatypes.length value).\n  { apply Q. }\n  trivial.\n}\nsubst. intro E. now destruct (call_builtin value E (b world')) as (w, result).\nQed.", "meta": {"author": "formalize", "repo": "coq-vyper", "sha": "8996c1534b9d56696f92b60031ff1523b3593690", "save_path": "github-repos/coq/formalize-coq-vyper", "path": "github-repos/coq/formalize-coq-vyper/coq-vyper-8996c1534b9d56696f92b60031ff1523b3593690/L40Metered/Expr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.32082129433083023, "lm_q1q2_score": 0.2189841889503902}}
{"text": "(** * Push-Button Synthesis of Saturated Reduction *)\nRequire Import Coq.Strings.String.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.MSets.MSetPositive.\nRequire Import Coq.Lists.List.\nRequire Import Coq.QArith.QArith_base Coq.QArith.Qround.\nRequire Import Coq.derive.Derive.\nRequire Import Crypto.Util.ErrorT.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.ListUtil.FoldBool.\nRequire Import Crypto.Util.Strings.Decimal.\nRequire Import Crypto.Util.Strings.Show.\nRequire Import Crypto.Util.ZRange.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Zselect.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.Tactics.HasBody.\nRequire Import Crypto.Util.Tactics.Head.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Rewriter.Language.Wf.\nRequire Import Rewriter.Language.Language.\nRequire Import Crypto.Language.API.\nRequire Import Crypto.AbstractInterpretation.AbstractInterpretation.\nRequire Import Crypto.Stringification.Language.\nRequire Import Crypto.Arithmetic.Core.\nRequire Import Crypto.Arithmetic.ModOps.\nRequire Import Crypto.Arithmetic.Saturated.\nRequire Import Crypto.Arithmetic.SolinasReduction.\nRequire Import Crypto.BoundsPipeline.\nRequire Import Crypto.COperationSpecifications.\nRequire Import Crypto.PushButtonSynthesis.ReificationCache.\nRequire Import Crypto.PushButtonSynthesis.Primitives.\nRequire Import Crypto.PushButtonSynthesis.SaturatedSolinasReificationCache.\nRequire Import Crypto.PushButtonSynthesis.SolinasReductionReificationCache.\nRequire Import Crypto.Assembly.Equivalence.\nImport ListNotations.\nLocal Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope list_scope. Local Open Scope bool_scope.\n\nImport\n  Language.Wf.Compilers\n  Language.Compilers\n  AbstractInterpretation.Compilers\n  Stringification.Language.Compilers.\nImport Compilers.API.\n\nImport COperationSpecifications.Primitives.\nImport COperationSpecifications.Solinas.\nImport COperationSpecifications.SolinasReduction.\n\nImport Associational Positional.\nImport SolinasReduction.\n\nLocal Coercion Z.of_nat : nat >-> Z.\nLocal Coercion QArith_base.inject_Z : Z >-> Q.\nLocal Coercion Z.pos : positive >-> Z.\n\nLocal Set Keyed Unification. (* needed for making [autorewrite] fast, c.f. COQBUG(https://github.com/coq/coq/issues/9283) *)\n\nLocal Opaque reified_mul_gen. (* needed for making [autorewrite] not take a very long time *)\nLocal Opaque reified_square_gen.\n(* needed for making [autorewrite] with [Set Keyed Unification] fast *)\nLocal Opaque expr.Interp.\n\nSection __.\n  Context {output_language_api : ToString.OutputLanguageAPI}\n          {pipeline_opts : PipelineOptions}\n          {pipeline_to_string_opts : PipelineToStringOptions}\n          {synthesis_opts : SynthesisOptions}\n          (s : Z)\n          (c : list (Z * Z)).\n  Context (machine_wordsize : machine_wordsize_opt).\n\n  Local Instance override_pipeline_opts : PipelineOptions\n    := {| widen_bytes := true (* true, because we don't allow byte-sized things anyway, so we should not expect carries to be widened to byte-size when emitting C code *)\n       |}.\n\n  (* We include [0], so that even after bounds relaxation, we can\n       notice where the constant 0s are, and remove them. *)\n  Definition possible_values_of_machine_wordsize\n    := prefix_with_carry [machine_wordsize].\n\n  Definition n : nat := Z.to_nat (Qceiling (Z.log2_up s / machine_wordsize)).\n  Definition m := s - Associational.eval c.\n  Definition weight := UniformWeight.uweight machine_wordsize.\n  Definition up_bound := 2 ^ (machine_wordsize / 4).\n  Definition base : Z := 2 ^ machine_wordsize.\n\n  Local Notation possible_values := possible_values_of_machine_wordsize.\n  Local Notation boundsn := (saturated_bounds n machine_wordsize).\n  Local Notation bounds4 := (saturated_bounds 4 machine_wordsize).\n\n  Local Existing Instance default_translate_to_fancy.\n  Local Instance no_select_size : no_select_size_opt := no_select_size_of_no_select machine_wordsize.\n  Local Instance split_mul_to : split_mul_to_opt := split_mul_to_of_should_split_mul machine_wordsize possible_values.\n  Local Instance split_multiret_to : split_multiret_to_opt := split_multiret_to_of_should_split_multiret machine_wordsize possible_values.\n\n  (** Note: If you change the name or type signature of this\n        function, you will need to update the code in CLI.v *)\n  Definition check_args {T} (requests : list string) (res : Pipeline.ErrorT T)\n    : Pipeline.ErrorT T\n    := check_args_of_list\n         (List.map\n            (fun v => (true, v))\n            [((0 <? s)%Z, Pipeline.Value_not_ltZ \"0 < s\" 0 s)\n             ; ((0 <? Associational.eval c)%Z, Pipeline.Value_not_ltZ \"0 < Associational.eval c\" 0 (Associational.eval c))\n             ; ((0 <? s - Associational.eval c)%Z, Pipeline.Value_not_ltZ \"0 < s - Associational.eval c\" 0 (s - Associational.eval c))\n             ; (negb (s =? 0)%Z, Pipeline.Values_not_provably_distinctZ \"s ≠ 0\" s 0)\n             ; (negb (n =? 0)%nat, Pipeline.Values_not_provably_distinctZ \"n ≠ 0\" n 0)\n             ; ((n =? 4)%Z, Pipeline.Values_not_provably_equalZ \"n = 4\" n 4)\n             ; (0 <? machine_wordsize, Pipeline.Value_not_ltZ \"0 < machine_wordsize\" 0 machine_wordsize)\n             ; (machine_wordsize =? 64, Pipeline.Values_not_provably_equalZ \"machine_wordsize = 64\" machine_wordsize 64)\n             ; ((1 <? n)%nat, Pipeline.Value_not_ltZ \"1 < n\" 1 n)\n             ; (fst (Rows.adjust_s weight (S (S n)) s) =? weight n, Pipeline.Values_not_provably_equalZ \"fst (Rows.adjust_s weight (S (S n)) s) = weight n\" (fst (Rows.adjust_s weight (S (S n)) s)) (weight n))\n             ; (snd (Rows.adjust_s weight (S (S n)) s), Pipeline.Invalid_argument \"tmp\")\n             ; (weight n / s * Associational.eval c <? up_bound, Pipeline.Value_not_ltZ \"weight n / s * Associational.eval c < up_bound\" (weight n / s * Associational.eval c) up_bound)\n         ])\n         res.\n\n  Local Ltac use_curve_good_t :=\n    repeat first [ use_requests_to_prove_curve_good_t_step\n                 | assumption\n                 | lia\n                 | progress autorewrite with distr_length\n                 | progress distr_length ].\n\n  Context (requests : list string)\n          (curve_good : check_args requests (Success tt) = Success tt).\n\n  Lemma use_curve_good\n    : (n > 1)%nat /\\\n        s > 0 /\\\n        Associational.eval c > 0 /\\\n        s - Associational.eval c <> 0 /\\\n        machine_wordsize = 64 /\\\n        base <> 0 /\\\n        Rows.adjust_s weight (S (S n)) s = (weight n, true) /\\\n        weight n / s * Associational.eval c < up_bound.\n  Proof using curve_good.\n    prepare_use_curve_good ().\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { unfold base.\n      apply Z.pow_nonzero; use_curve_good_t. }\n    { lazymatch goal with\n      | |- ?x = _ => rewrite surjective_pairing with (p:=x)\n      end.\n      congruence. }\n  Qed.\n\n  Local Notation evalf := (eval weight n).\n  Local Notation weightf := weight.\n  Local Notation notations_for_docstring\n    := (CorrectnessStringification.dyn_context.cons\n          weightf \"weight\"\n          (CorrectnessStringification.dyn_context.cons\n             evalf \"eval\"\n             CorrectnessStringification.dyn_context.nil))%string.\n  Local Notation \"'docstring_with_summary_from_lemma!' summary correctness\"\n    := (docstring_with_summary_from_lemma_with_ctx!\n          notations_for_docstring\n          summary\n          correctness)\n         (only parsing, at level 10, summary at next level, correctness at next level).\n\n  Definition mul\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values\n         (reified_mul_gen\n            @ GallinaReify.Reify base\n            @ GallinaReify.Reify s\n            @ GallinaReify.Reify c\n            @ GallinaReify.Reify n)\n         (Some boundsn, (Some boundsn, tt))\n         (Some boundsn).\n\n  Definition square\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values\n         (reified_square_gen\n            @ GallinaReify.Reify base\n            @ GallinaReify.Reify s\n            @ GallinaReify.Reify c\n            @ GallinaReify.Reify n)\n         (Some boundsn, tt)\n         (Some boundsn).\n\n  Definition smul (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"mul\" mul\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" multiplies two field elements.\"]%string)\n             (mul_correct weightf n m boundsn)).\n\n  Definition ssquare (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"square\" square\n          (docstring_with_summary_from_lemma!\n             (fun fname : string => [text_before_function_name ++ fname ++ \" squares a field element.\"]%string)\n             (sqr_correct weightf n m boundsn)).\n\n  Local Ltac solve_extra_bounds_side_conditions :=\n    cbn [lower upper fst snd] in *; Bool.split_andb; Z.ltb_to_lt; lia.\n\n  Local Ltac prove_correctness _ := Primitives.prove_correctness use_curve_good.\n\n  Lemma mul_correct res\n        (Hres : mul = Success res)\n    : mul_correct weight n m boundsn (Interp res).\n  Proof using curve_good.\n    prove_correctness ().\n    cbv [evalf weightf weight up_bound] in *.\n    match goal with\n    | H : machine_wordsize = _ |- _ => rewrite H in *\n    end.\n    apply (fun pf => @SolinasReduction.SolinasReduction.mulmod_correct (@wprops _ _ pf)); auto; lia.\n  Qed.\n\n  Lemma Wf_mul res (Hres : mul = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma square_correct res\n        (Hres : square = Success res)\n    : sqr_correct weight n m boundsn (Interp res).\n  Proof using curve_good.\n\n    prove_correctness ().\n    cbv [evalf weightf weight up_bound] in *.\n    match goal with\n    | H : machine_wordsize = _ |- _ => rewrite H in *\n    end.\n    apply (fun pf => @SolinasReduction.SolinasReduction.squaremod_correct (@wprops _ _ pf)); auto; lia.\n  Qed.\n\n  Lemma Wf_square res (Hres : square = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Section for_stringification.\n    Local Open Scope string_scope.\n    Local Open Scope list_scope.\n\n    Definition known_functions\n      := [(\"mul\", wrap_s smul); (\"square\", wrap_s ssquare)].\n\n    Definition valid_names : string := Eval compute in String.concat \", \" (List.map (@fst _ _) known_functions).\n\n    (** Note: If you change the name or type signature of this\n          function, you will need to update the code in CLI.v *)\n    Definition Synthesize (comment_header : list string) (function_name_prefix : string) (requests : list string)\n      : list (synthesis_output_kind * string * Pipeline.M (list string))\n      := Primitives.Synthesize\n           machine_wordsize valid_names known_functions (fun _ => nil) all_typedefs!\n           check_args\n           ((ToString.comment_file_header_block\n               (comment_header\n                  ++ [\"\";\n                     \"Computed values:\";\n                     \"\"]%string)))\n           function_name_prefix requests.\n  End for_stringification.\nEnd __.\n\nModule Export Hints.\n#[global]\n  Hint Opaque\n       mul\n  : wf_op_cache.\n#[global]\n  Hint Immediate\n       Wf_mul\n  : wf_op_cache.\n\n#[global]\n  Hint Opaque\n       square\n  : wf_op_cache.\n#[global]\n  Hint Immediate\n       Wf_square\n  : wf_op_cache.\nEnd Hints.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/PushButtonSynthesis/SolinasReduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.2188328162977558}}
{"text": "Require Export VST.concurrency.paco.src.paconotation VST.concurrency.paco.src.pacotac VST.concurrency.paco.src.pacodef VST.concurrency.paco.src.pacotacuser.\nSet Implicit Arguments.\n\n(** ** Predicates of Arity 3\n*)\n\n(** 1 Mutual Coinduction *)\n\nSection Arg3_1.\n\nDefinition monotone3 T0 T1 T2 (gf: rel3 T0 T1 T2 -> rel3 T0 T1 T2) :=\n  forall x0 x1 x2 r r' (IN: gf r x0 x1 x2) (LE: r <3= r'), gf r' x0 x1 x2.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable gf : rel3 T0 T1 T2 -> rel3 T0 T1 T2.\nImplicit Arguments gf [].\n\nTheorem paco3_acc: forall\n  l r (OBG: forall rr (INC: r <3= rr) (CIH: l <_paco_3= rr), l <_paco_3= paco3 gf rr),\n  l <3= paco3 gf r.\nProof.\n  intros; assert (SIM: paco3 gf (r \\3/ l) x0 x1 x2) by eauto.\n  clear PR; repeat (try left; do 4 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco3_mon: monotone3 (paco3 gf).\nProof. paco_cofix_auto; repeat (left; do 4 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco3_mult_strong: forall r,\n  paco3 gf (upaco3 gf r) <3= paco3 gf r.\nProof. paco_cofix_auto; repeat (left; do 4 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco3_mult: forall r,\n  paco3 gf (paco3 gf r) <3= paco3 gf r.\nProof. intros; eapply paco3_mult_strong, paco3_mon; eauto. Qed.\n\nTheorem paco3_fold: forall r,\n  gf (upaco3 gf r) <3= paco3 gf r.\nProof. intros; econstructor; [ |eauto]; eauto. Qed.\n\nTheorem paco3_unfold: forall (MON: monotone3 gf) r,\n  paco3 gf r <3= gf (upaco3 gf r).\nProof. unfold monotone3; intros; destruct PR; eauto. Qed.\n\nEnd Arg3_1.\n\nHint Unfold monotone3.\nHint Resolve paco3_fold.\n\nImplicit Arguments paco3_acc            [ T0 T1 T2 ].\nImplicit Arguments paco3_mon            [ T0 T1 T2 ].\nImplicit Arguments paco3_mult_strong    [ T0 T1 T2 ].\nImplicit Arguments paco3_mult           [ T0 T1 T2 ].\nImplicit Arguments paco3_fold           [ T0 T1 T2 ].\nImplicit Arguments paco3_unfold         [ T0 T1 T2 ].\n\nInstance paco3_inst  T0 T1 T2 (gf : rel3 T0 T1 T2->_) r x0 x1 x2 : paco_class (paco3 gf r x0 x1 x2) :=\n{ pacoacc    := paco3_acc gf;\n  pacomult   := paco3_mult gf;\n  pacofold   := paco3_fold gf;\n  pacounfold := paco3_unfold gf }.\n\n(** 2 Mutual Coinduction *)\n\nSection Arg3_2.\n\nDefinition monotone3_2 T0 T1 T2 (gf: rel3 T0 T1 T2 -> rel3 T0 T1 T2 -> rel3 T0 T1 T2) :=\n  forall x0 x1 x2 r_0 r_1 r'_0 r'_1 (IN: gf r_0 r_1 x0 x1 x2) (LE_0: r_0 <3= r'_0)(LE_1: r_1 <3= r'_1), gf r'_0 r'_1 x0 x1 x2.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable gf_0 gf_1 : rel3 T0 T1 T2 -> rel3 T0 T1 T2 -> rel3 T0 T1 T2.\nImplicit Arguments gf_0 [].\nImplicit Arguments gf_1 [].\n\nTheorem paco3_2_0_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_0 <3= rr) (CIH: l <_paco_3= rr), l <_paco_3= paco3_2_0 gf_0 gf_1 rr r_1),\n  l <3= paco3_2_0 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco3_2_0 gf_0 gf_1 (r_0 \\3/ l) r_1 x0 x1 x2) by eauto.\n  clear PR; repeat (try left; do 4 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco3_2_1_acc: forall\n  l r_0 r_1 (OBG: forall rr (INC: r_1 <3= rr) (CIH: l <_paco_3= rr), l <_paco_3= paco3_2_1 gf_0 gf_1 r_0 rr),\n  l <3= paco3_2_1 gf_0 gf_1 r_0 r_1.\nProof.\n  intros; assert (SIM: paco3_2_1 gf_0 gf_1 r_0 (r_1 \\3/ l) x0 x1 x2) by eauto.\n  clear PR; repeat (try left; do 4 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco3_2_0_mon: monotone3_2 (paco3_2_0 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 4 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco3_2_1_mon: monotone3_2 (paco3_2_1 gf_0 gf_1).\nProof. paco_cofix_auto; repeat (left; do 4 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco3_2_0_mult_strong: forall r_0 r_1,\n  paco3_2_0 gf_0 gf_1 (upaco3_2_0 gf_0 gf_1 r_0 r_1) (upaco3_2_1 gf_0 gf_1 r_0 r_1) <3= paco3_2_0 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 4 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco3_2_1_mult_strong: forall r_0 r_1,\n  paco3_2_1 gf_0 gf_1 (upaco3_2_0 gf_0 gf_1 r_0 r_1) (upaco3_2_1 gf_0 gf_1 r_0 r_1) <3= paco3_2_1 gf_0 gf_1 r_0 r_1.\nProof. paco_cofix_auto; repeat (left; do 4 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco3_2_0_mult: forall r_0 r_1,\n  paco3_2_0 gf_0 gf_1 (paco3_2_0 gf_0 gf_1 r_0 r_1) (paco3_2_1 gf_0 gf_1 r_0 r_1) <3= paco3_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco3_2_0_mult_strong, paco3_2_0_mon; eauto. Qed.\n\nCorollary paco3_2_1_mult: forall r_0 r_1,\n  paco3_2_1 gf_0 gf_1 (paco3_2_0 gf_0 gf_1 r_0 r_1) (paco3_2_1 gf_0 gf_1 r_0 r_1) <3= paco3_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; eapply paco3_2_1_mult_strong, paco3_2_1_mon; eauto. Qed.\n\nTheorem paco3_2_0_fold: forall r_0 r_1,\n  gf_0 (upaco3_2_0 gf_0 gf_1 r_0 r_1) (upaco3_2_1 gf_0 gf_1 r_0 r_1) <3= paco3_2_0 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco3_2_1_fold: forall r_0 r_1,\n  gf_1 (upaco3_2_0 gf_0 gf_1 r_0 r_1) (upaco3_2_1 gf_0 gf_1 r_0 r_1) <3= paco3_2_1 gf_0 gf_1 r_0 r_1.\nProof. intros; econstructor; [ | |eauto]; eauto. Qed.\n\nTheorem paco3_2_0_unfold: forall (MON: monotone3_2 gf_0) (MON: monotone3_2 gf_1) r_0 r_1,\n  paco3_2_0 gf_0 gf_1 r_0 r_1 <3= gf_0 (upaco3_2_0 gf_0 gf_1 r_0 r_1) (upaco3_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone3_2; intros; destruct PR; eauto. Qed.\n\nTheorem paco3_2_1_unfold: forall (MON: monotone3_2 gf_0) (MON: monotone3_2 gf_1) r_0 r_1,\n  paco3_2_1 gf_0 gf_1 r_0 r_1 <3= gf_1 (upaco3_2_0 gf_0 gf_1 r_0 r_1) (upaco3_2_1 gf_0 gf_1 r_0 r_1).\nProof. unfold monotone3_2; intros; destruct PR; eauto. Qed.\n\nEnd Arg3_2.\n\nHint Unfold monotone3_2.\nHint Resolve paco3_2_0_fold.\nHint Resolve paco3_2_1_fold.\n\nImplicit Arguments paco3_2_0_acc            [ T0 T1 T2 ].\nImplicit Arguments paco3_2_1_acc            [ T0 T1 T2 ].\nImplicit Arguments paco3_2_0_mon            [ T0 T1 T2 ].\nImplicit Arguments paco3_2_1_mon            [ T0 T1 T2 ].\nImplicit Arguments paco3_2_0_mult_strong    [ T0 T1 T2 ].\nImplicit Arguments paco3_2_1_mult_strong    [ T0 T1 T2 ].\nImplicit Arguments paco3_2_0_mult           [ T0 T1 T2 ].\nImplicit Arguments paco3_2_1_mult           [ T0 T1 T2 ].\nImplicit Arguments paco3_2_0_fold           [ T0 T1 T2 ].\nImplicit Arguments paco3_2_1_fold           [ T0 T1 T2 ].\nImplicit Arguments paco3_2_0_unfold         [ T0 T1 T2 ].\nImplicit Arguments paco3_2_1_unfold         [ T0 T1 T2 ].\n\nInstance paco3_2_0_inst  T0 T1 T2 (gf_0 gf_1 : rel3 T0 T1 T2->_) r_0 r_1 x0 x1 x2 : paco_class (paco3_2_0 gf_0 gf_1 r_0 r_1 x0 x1 x2) :=\n{ pacoacc    := paco3_2_0_acc gf_0 gf_1;\n  pacomult   := paco3_2_0_mult gf_0 gf_1;\n  pacofold   := paco3_2_0_fold gf_0 gf_1;\n  pacounfold := paco3_2_0_unfold gf_0 gf_1 }.\n\nInstance paco3_2_1_inst  T0 T1 T2 (gf_0 gf_1 : rel3 T0 T1 T2->_) r_0 r_1 x0 x1 x2 : paco_class (paco3_2_1 gf_0 gf_1 r_0 r_1 x0 x1 x2) :=\n{ pacoacc    := paco3_2_1_acc gf_0 gf_1;\n  pacomult   := paco3_2_1_mult gf_0 gf_1;\n  pacofold   := paco3_2_1_fold gf_0 gf_1;\n  pacounfold := paco3_2_1_unfold gf_0 gf_1 }.\n\n(** 3 Mutual Coinduction *)\n\nSection Arg3_3.\n\nDefinition monotone3_3 T0 T1 T2 (gf: rel3 T0 T1 T2 -> rel3 T0 T1 T2 -> rel3 T0 T1 T2 -> rel3 T0 T1 T2) :=\n  forall x0 x1 x2 r_0 r_1 r_2 r'_0 r'_1 r'_2 (IN: gf r_0 r_1 r_2 x0 x1 x2) (LE_0: r_0 <3= r'_0)(LE_1: r_1 <3= r'_1)(LE_2: r_2 <3= r'_2), gf r'_0 r'_1 r'_2 x0 x1 x2.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable gf_0 gf_1 gf_2 : rel3 T0 T1 T2 -> rel3 T0 T1 T2 -> rel3 T0 T1 T2 -> rel3 T0 T1 T2.\nImplicit Arguments gf_0 [].\nImplicit Arguments gf_1 [].\nImplicit Arguments gf_2 [].\n\nTheorem paco3_3_0_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_0 <3= rr) (CIH: l <_paco_3= rr), l <_paco_3= paco3_3_0 gf_0 gf_1 gf_2 rr r_1 r_2),\n  l <3= paco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco3_3_0 gf_0 gf_1 gf_2 (r_0 \\3/ l) r_1 r_2 x0 x1 x2) by eauto.\n  clear PR; repeat (try left; do 4 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco3_3_1_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_1 <3= rr) (CIH: l <_paco_3= rr), l <_paco_3= paco3_3_1 gf_0 gf_1 gf_2 r_0 rr r_2),\n  l <3= paco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco3_3_1 gf_0 gf_1 gf_2 r_0 (r_1 \\3/ l) r_2 x0 x1 x2) by eauto.\n  clear PR; repeat (try left; do 4 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco3_3_2_acc: forall\n  l r_0 r_1 r_2 (OBG: forall rr (INC: r_2 <3= rr) (CIH: l <_paco_3= rr), l <_paco_3= paco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 rr),\n  l <3= paco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof.\n  intros; assert (SIM: paco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 (r_2 \\3/ l) x0 x1 x2) by eauto.\n  clear PR; repeat (try left; do 4 paco_revert; paco_cofix_auto).\nQed.\n\nTheorem paco3_3_0_mon: monotone3_3 (paco3_3_0 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 4 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco3_3_1_mon: monotone3_3 (paco3_3_1 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 4 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco3_3_2_mon: monotone3_3 (paco3_3_2 gf_0 gf_1 gf_2).\nProof. paco_cofix_auto; repeat (left; do 4 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco3_3_0_mult_strong: forall r_0 r_1 r_2,\n  paco3_3_0 gf_0 gf_1 gf_2 (upaco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <3= paco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 4 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco3_3_1_mult_strong: forall r_0 r_1 r_2,\n  paco3_3_1 gf_0 gf_1 gf_2 (upaco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <3= paco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 4 paco_revert; paco_cofix_auto). Qed.\n\nTheorem paco3_3_2_mult_strong: forall r_0 r_1 r_2,\n  paco3_3_2 gf_0 gf_1 gf_2 (upaco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <3= paco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. paco_cofix_auto; repeat (left; do 4 paco_revert; paco_cofix_auto). Qed.\n\nCorollary paco3_3_0_mult: forall r_0 r_1 r_2,\n  paco3_3_0 gf_0 gf_1 gf_2 (paco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <3= paco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco3_3_0_mult_strong, paco3_3_0_mon; eauto. Qed.\n\nCorollary paco3_3_1_mult: forall r_0 r_1 r_2,\n  paco3_3_1 gf_0 gf_1 gf_2 (paco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <3= paco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco3_3_1_mult_strong, paco3_3_1_mon; eauto. Qed.\n\nCorollary paco3_3_2_mult: forall r_0 r_1 r_2,\n  paco3_3_2 gf_0 gf_1 gf_2 (paco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (paco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <3= paco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; eapply paco3_3_2_mult_strong, paco3_3_2_mon; eauto. Qed.\n\nTheorem paco3_3_0_fold: forall r_0 r_1 r_2,\n  gf_0 (upaco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <3= paco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco3_3_1_fold: forall r_0 r_1 r_2,\n  gf_1 (upaco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <3= paco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco3_3_2_fold: forall r_0 r_1 r_2,\n  gf_2 (upaco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2) <3= paco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2.\nProof. intros; econstructor; [ | | |eauto]; eauto. Qed.\n\nTheorem paco3_3_0_unfold: forall (MON: monotone3_3 gf_0) (MON: monotone3_3 gf_1) (MON: monotone3_3 gf_2) r_0 r_1 r_2,\n  paco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 <3= gf_0 (upaco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone3_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco3_3_1_unfold: forall (MON: monotone3_3 gf_0) (MON: monotone3_3 gf_1) (MON: monotone3_3 gf_2) r_0 r_1 r_2,\n  paco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 <3= gf_1 (upaco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone3_3; intros; destruct PR; eauto. Qed.\n\nTheorem paco3_3_2_unfold: forall (MON: monotone3_3 gf_0) (MON: monotone3_3 gf_1) (MON: monotone3_3 gf_2) r_0 r_1 r_2,\n  paco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 <3= gf_2 (upaco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2) (upaco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2).\nProof. unfold monotone3_3; intros; destruct PR; eauto. Qed.\n\nEnd Arg3_3.\n\nHint Unfold monotone3_3.\nHint Resolve paco3_3_0_fold.\nHint Resolve paco3_3_1_fold.\nHint Resolve paco3_3_2_fold.\n\nImplicit Arguments paco3_3_0_acc            [ T0 T1 T2 ].\nImplicit Arguments paco3_3_1_acc            [ T0 T1 T2 ].\nImplicit Arguments paco3_3_2_acc            [ T0 T1 T2 ].\nImplicit Arguments paco3_3_0_mon            [ T0 T1 T2 ].\nImplicit Arguments paco3_3_1_mon            [ T0 T1 T2 ].\nImplicit Arguments paco3_3_2_mon            [ T0 T1 T2 ].\nImplicit Arguments paco3_3_0_mult_strong    [ T0 T1 T2 ].\nImplicit Arguments paco3_3_1_mult_strong    [ T0 T1 T2 ].\nImplicit Arguments paco3_3_2_mult_strong    [ T0 T1 T2 ].\nImplicit Arguments paco3_3_0_mult           [ T0 T1 T2 ].\nImplicit Arguments paco3_3_1_mult           [ T0 T1 T2 ].\nImplicit Arguments paco3_3_2_mult           [ T0 T1 T2 ].\nImplicit Arguments paco3_3_0_fold           [ T0 T1 T2 ].\nImplicit Arguments paco3_3_1_fold           [ T0 T1 T2 ].\nImplicit Arguments paco3_3_2_fold           [ T0 T1 T2 ].\nImplicit Arguments paco3_3_0_unfold         [ T0 T1 T2 ].\nImplicit Arguments paco3_3_1_unfold         [ T0 T1 T2 ].\nImplicit Arguments paco3_3_2_unfold         [ T0 T1 T2 ].\n\nInstance paco3_3_0_inst  T0 T1 T2 (gf_0 gf_1 gf_2 : rel3 T0 T1 T2->_) r_0 r_1 r_2 x0 x1 x2 : paco_class (paco3_3_0 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2) :=\n{ pacoacc    := paco3_3_0_acc gf_0 gf_1 gf_2;\n  pacomult   := paco3_3_0_mult gf_0 gf_1 gf_2;\n  pacofold   := paco3_3_0_fold gf_0 gf_1 gf_2;\n  pacounfold := paco3_3_0_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco3_3_1_inst  T0 T1 T2 (gf_0 gf_1 gf_2 : rel3 T0 T1 T2->_) r_0 r_1 r_2 x0 x1 x2 : paco_class (paco3_3_1 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2) :=\n{ pacoacc    := paco3_3_1_acc gf_0 gf_1 gf_2;\n  pacomult   := paco3_3_1_mult gf_0 gf_1 gf_2;\n  pacofold   := paco3_3_1_fold gf_0 gf_1 gf_2;\n  pacounfold := paco3_3_1_unfold gf_0 gf_1 gf_2 }.\n\nInstance paco3_3_2_inst  T0 T1 T2 (gf_0 gf_1 gf_2 : rel3 T0 T1 T2->_) r_0 r_1 r_2 x0 x1 x2 : paco_class (paco3_3_2 gf_0 gf_1 gf_2 r_0 r_1 r_2 x0 x1 x2) :=\n{ pacoacc    := paco3_3_2_acc gf_0 gf_1 gf_2;\n  pacomult   := paco3_3_2_mult gf_0 gf_1 gf_2;\n  pacofold   := paco3_3_2_fold gf_0 gf_1 gf_2;\n  pacounfold := paco3_3_2_unfold gf_0 gf_1 gf_2 }.\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/concurrency/paco/src/paco3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.34158251284363395, "lm_q1q2_score": 0.218830000426653}}
{"text": "(* An attempt at a value type for generalized environments. *)\n\n(**************************************************************************\n* TLC: A library for Coq                                                  *\n* Keys for environment signature. \n**************************************************************************)\n\nSet Implicit Arguments.\nRequire Import TLC.LibTactics TLC.LibList TLC.LibLogic TLC.LibNat TLC.LibEpsilon TLC.LibReflect TLC.LibFset.\n\n(** * Abstract Definition of value for an environment. *)\nModule Type ValueType.\nParameter value : Set.\nParameter value_inhab : Inhab value.\nParameter value_comp : Comparable value.\nInstance  value_comparable : Comparable value := value_comp.\nDefinition values := fset value.\n\n(* How do I get var without too much ? \nFunction fv (v : value) := VariablesType.vars.\n*)\n\nEnd ValueType.", "meta": {"author": "briangmilnes", "repo": "CycloneCoqSemantics", "sha": "190c0fc57d5aebfde244efb06a119f108de7a150", "save_path": "github-repos/coq/briangmilnes-CycloneCoqSemantics", "path": "github-repos/coq/briangmilnes-CycloneCoqSemantics/CycloneCoqSemantics-190c0fc57d5aebfde244efb06a119f108de7a150/4.4/genenv/LibValueType.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.21875518492415738}}
{"text": "From iris.program_logic Require Export weakestpre.\nFrom fae_gtlc_mu.cast_calculus Require Export lang lang_lemmas.\nFrom fae_gtlc_mu.cast_calculus Require Import types_notations.\n\n(* Iris resources for invariants *)\nClass implG Σ := ImplG {\n  implG_invG : invG Σ;\n}.\n\n(* Iris resources gradual side for weakest preconditions... *)\nInstance implG_irisG `{implG Σ} : irisG lang Σ := {\n  iris_invG := implG_invG;\n  state_interp σ κs _ := True%I;\n  fork_post _ := True%I;\n}.\nGlobal Opaque iris_invG.\n\nFrom iris.program_logic Require Export ectx_lifting.\nFrom iris.proofmode Require Export tactics.\nFrom fae_gtlc_mu.cast_calculus Require Export lang_lemmas.\n\n(* some WP lemmas *)\nSection wps.\n  Context `{implG Σ}.\n\n  Lemma wp_CastError' E Φ :\n    ⊢ WP CastError @ MaybeStuck; E {{Φ}}.\n  Proof. simpl. iApply wp_lift_pure_stuck. intro σ. destruct σ. exact CastError_stuck. done. Qed.\n\n  Lemma wp_CastError (K : ectx) E Φ :\n    ⊢ WP fill K CastError @ MaybeStuck; E {{Φ}}.\n  Proof.\n    destruct K.\n    - by iApply wp_CastError'.\n    - iApply (wp_pure_step_later MaybeStuck _ _ CastError True 1 _).\n      intros _. apply nsteps_once. by apply cast_error_step. done.\n      iApply wp_lift_pure_stuck. intro σ. destruct σ. exact CastError_stuck. done.\n  Qed.\n\n  (* a bind lemma for WP *)\n  Lemma wp_bind (K : ectx) E e Φ :\n    WP e @ MaybeStuck; E {{ v, WP fill K (of_val v) @ MaybeStuck; E {{ Φ }} }} ⊢ WP fill K e @ MaybeStuck; E {{ Φ }}.\n  Proof.\n    destruct (decide (e = CastError)) as [-> | eNeqCE].\n    { iIntros \"_\". iApply wp_CastError. }\n    iIntros \"H\". iLöb as \"IH\" forall (E e eNeqCE Φ). rewrite wp_unfold /wp_pre.\n    assert (language.to_val e = to_val e) as ->; first done.\n    destruct (to_val e) as [v|] eqn:He.\n    { apply of_to_val in He as <-. by iApply fupd_wp. }\n    rewrite wp_unfold /wp_pre.\n    assert (language.to_val (fill K  e) = to_val (fill K e)) as ->; first done.\n    rewrite fill_not_val //.\n    iIntros (σ1 κ κs n) \"Hσ\". iMod (\"H\" $! tt [] [] 0 with \"[$]\") as \"[% H]\". iModIntro; iSplit.\n    { eauto using reducible_fill. }\n    iIntros (e2 σ2 efs Hstep).\n    destruct (decide (e2 = CastError)).\n    - rewrite e0.\n      iMod (\"H\" $! CastError σ2 efs with \"[]\") as \"H\".\n      simpl. iPureIntro. cut (prim_step e [] CastError []). inversion Hstep; done.\n      { assert (prim_step (fill K e) [] e2 []). inversion Hstep; simplify_eq; by econstructor. eapply fill_step_CastError_inv; eauto. by simplify_eq. }\n      iIntros \"!>!>\".\n      iMod \"H\" as \"(Hσ' & H & Hefs)\".\n      iModIntro. iFrame \"Hσ Hefs\". assert (CastError = fill [] CastError) as ->. done. iApply wp_CastError.\n    - destruct (fill_step_inv K e κ e2 efs) as (e2'&->&?); auto.\n      iMod (\"H\" $! e2' σ2 efs with \"[]\") as \"H\".\n      simpl. inversion H1; by simplify_eq.\n      iIntros \"!>!>\".\n      iMod \"H\" as \"(Hσ' & H & Hefs)\".\n      iModIntro. iFrame \"Hσ Hefs\".\n      destruct K as [|Ki K]. simpl. iApply wp_fupd. iApply (wp_wand with \"H\"). iIntros (v) \"Hwpv\". iMod (wp_value_inv with \"Hwpv\"). by iModIntro.\n      destruct (decide (e2' = CastError)) as [-> | neq]. iApply wp_CastError.\n      by iApply \"IH\".\n  Qed.\n\nEnd wps.\n\nLtac wp_head := iApply wp_pure_step_later; auto; iNext.\nLtac wp_value := iApply wp_value.\n", "meta": {"author": "scaup", "repo": "fae-gtlc-mu", "sha": "6c6e64f0844327d55059b97c7aefab023385973e", "save_path": "github-repos/coq/scaup-fae-gtlc-mu", "path": "github-repos/coq/scaup-fae-gtlc-mu/fae-gtlc-mu-6c6e64f0844327d55059b97c7aefab023385973e/theories/refinements/gradual_static/resources_left.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.21875517676023384}}
{"text": "Require Import VST.msl.seplog.\nRequire Import VST.msl.log_normalize.\nRequire Import RamifyCoq.lib.Coqlib.\nRequire Import RamifyCoq.lib.Ensembles_ext.\nRequire Import RamifyCoq.lib.EquivDec_ext.\nRequire Import RamifyCoq.lib.List_ext.\nRequire Import RamifyCoq.lib.relation_list.\nRequire Import RamifyCoq.msl_ext.log_normalize.\nRequire Import RamifyCoq.msl_ext.iter_sepcon.\nRequire Import RamifyCoq.msl_ext.ramification_lemmas.\nRequire Import RamifyCoq.graph.graph_model.\nRequire Import RamifyCoq.graph.path_lemmas.\nRequire Import RamifyCoq.graph.reachable_computable.\nRequire Import RamifyCoq.graph.reachable_ind.\nRequire Import RamifyCoq.graph.subgraph2.\nRequire Import RamifyCoq.graph.graph_gen.\nRequire Import RamifyCoq.graph.dag.\nRequire Import RamifyCoq.graph.weak_mark_lemmas.\nRequire Import RamifyCoq.msl_application.Graph.\nRequire Import Coq.Logic.Classical.\n\nLocal Open Scope logic.\n\nSection PointwiseGraph_Mark.\n\nContext {V E: Type}.\nContext {GV GE Pred: Type}.\nContext {SGBA: PointwiseGraphBasicAssum V E}.\nContext {SGC: PointwiseGraphConstructor V E bool unit unit GV GE}.\nContext {L_SGC: Local_PointwiseGraphConstructor V E bool unit unit GV GE}.\nContext {SGP: PointwiseGraphPred V E GV GE Pred}.\nContext {SGA: PointwiseGraphAssum SGP}.\n\nInstance MGS: WeakMarkGraph.MarkGraphSetting bool.\nProof.\n  apply (WeakMarkGraph.Build_MarkGraphSetting _ (eq true)).\n  intros; destruct x; [left | right]; congruence.\nDefined.\n\nGlobal Existing Instance MGS.\n\nNotation Graph := (LabeledGraph V E bool unit unit).\nNotation SGraph := (PointwiseGraph V E GV GE).\n\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nDefinition mark1 x (G1: Graph) (G2: Graph) := WeakMarkGraph.mark1 x G1 G2.\nDefinition mark x (G1: Graph) (G2: Graph) := WeakMarkGraph.mark x G1 G2 /\\ G1 ~=~ G2.\n\nDefinition mark_list xs g1 g2 := relation_list (map mark xs) g1 g2.\n\nLemma mark_invalid_refl: forall (g: Graph) root, ~ vvalid g root -> mark root g g.\nProof.\n  intros.\n  split.\n  + apply WeakMarkGraph.mark_invalid_refl; auto.\n  + reflexivity.\nQed.\n\nLemma mark_marked_root_refl: forall (g: Graph) root, WeakMarkGraph.marked g root -> mark root g g.\nProof.\n  intros.\n  split.\n  + apply WeakMarkGraph.mark_marked_root_refl; auto.\n  + reflexivity.\nQed.\n\nLemma mark_list_eq: forall root xs g1 g2,\n  mark_list xs g1 g2 ->\n  WeakMarkGraph.componded_mark_list root xs g1 g2 /\\ g1 ~=~ g2.\nProof.\n  intros.\n  change (mark_list xs g1 g2) with\n    (relation_list (map (fun x => relation_conjunction (WeakMarkGraph.mark x) (respectful_relation pg_lg structurally_identical)) xs) g1 g2) in H.\n  eapply relation_list_conjunction in H.\n  rewrite relation_conjunction_iff in H.\n  split.\n  + destruct H as [? _].\n    eapply relation_list_inclusion; [| exact H].\n    intros ? _.\n    clear.\n    intros g1 g2 ?.\n    exists g2; [| apply WeakMarkGraph.eq_do_nothing; auto].\n    exists g1; [apply WeakMarkGraph.eq_do_nothing; auto |].\n    auto.\n  + eapply si_list.\n    exact (proj2 H).\nQed.\n\nLemma mark1_mark_list_mark: forall root l (g g': Graph),\n  vvalid g root ->\n  (WeakMarkGraph.unmarked g) root ->\n  step_list g root l ->\n  relation_list (mark1 root :: mark_list l :: nil) g g' ->\n  mark root g g'.\nProof.\n  intros.\n  destruct_relation_list g0 in H2.\n  eapply (mark_list_eq root) in H2.\n  destruct H2; simpl in H2.\n  split.\n  + eapply WeakMarkGraph.mark1_componded_mark_list_mark; eauto.\n    split_relation_list (g :: g0 :: g0 :: g' :: nil); auto;\n    apply WeakMarkGraph.eq_do_nothing; auto.\n  + destruct H3 as [? _].\n    rewrite H3; auto.\nQed.\n\nLemma mark_partial_labeled_graph_equiv: forall x (g g': Graph),\n  mark x g g' ->\n  ((predicate_partial_labeledgraph g (Complement _ (reachable g x))) ~=~\n  (predicate_partial_labeledgraph g' (Complement _ (reachable g x))))%LabeledGraph.\nProof.\n  intros.\n  split; [| split].\n  + destruct H.\n    simpl;\n    rewrite <- H0.\n    reflexivity.\n  + destruct H as [[? ?] _].\n    simpl in *; intros.\n    specialize (H0 v).\n    assert (~ g |= x ~o~> v satisfying (WeakMarkGraph.unmarked g)).\n    1: {\n      destruct H1.\n      intro; apply H3.\n      apply reachable_by_is_reachable in H4; auto.\n    }\n    clear - H0 H3.\n    destruct (vlabel g v), (vlabel g' v).\n    - auto.\n    - rewrite H0; auto.\n    - symmetry; tauto.\n    - auto.\n  + intros; simpl.\n    destruct (elabel g e), (elabel g' e); auto.\nQed.\n\nLemma root_stable_ramify: forall (g: Graph) (x: V) (gx: GV),\n  vgamma (Graph_PointwiseGraph g) x = gx ->\n  vvalid g x ->\n  @derives Pred _\n    (reachable_vertices_at x g)\n    (vertex_at x gx * (vertex_at x gx -* reachable_vertices_at x g)).\nProof. apply va_reachable_root_stable_ramify. Qed.\n\nLemma root_update_ramify: forall (g: Graph) (x: V) (lx: bool) (gx gx': GV),\n  vvalid g x ->\n  vgamma (Graph_PointwiseGraph g) x = gx ->\n  vgamma (Graph_PointwiseGraph (labeledgraph_vgen g x lx)) x = gx' ->\n  Included (Intersection V (reachable g x) (Complement V (eq x))) (vguard g) ->\n  Included (Intersection V (reachable g x) (Complement V (eq x))) (vguard (labeledgraph_vgen g x lx)) ->\n  @derives Pred _\n    (reachable_vertices_at x g)\n    (vertex_at x gx *\n      (vertex_at x gx' -* reachable_vertices_at x (labeledgraph_vgen g x lx))).\nProof. apply va_reachable_root_update_ramify. Qed.\n\n(* TODO: remove this lemma? *)\nLemma exp_mark1: forall (g: Graph) (x: V) (lx: bool),\n  WeakMarkGraph.label_marked lx ->\n  @derives Pred _ (reachable_vertices_at x (labeledgraph_vgen g x lx)) (EX g': Graph, !! (mark1 x g g') && reachable_vertices_at x g').\nProof.\n  intros.\n  apply (exp_right (labeledgraph_vgen g x lx)).\n  apply andp_right; [apply prop_right | auto].\n  apply WeakMarkGraph.vertex_update_mark1; auto.\nQed.\n\nLemma mark_neighbor_ramify: forall {A} (g1: Graph) (g2: A -> Graph) x y,\n  (forall (g: Graph) x y, reachable g x y \\/ ~ reachable g x y) ->\n  vvalid g1 x ->\n  step g1 x y ->\n  Included (Intersection V (reachable g1 x) (Complement V (reachable g1 y)))\n     (vguard g1) ->\n  (forall a, mark y g1 (g2 a) -> Included (Intersection V (reachable g1 x) (Complement V (reachable g1 y))) (vguard (g2 a))) ->\n  @derives Pred _\n    (reachable_vertices_at x g1)\n    (reachable_vertices_at y g1 *\n      (ALL a: A, !! mark y g1 (g2 a) -->\n        (reachable_vertices_at y (g2 a) -*\n         reachable_vertices_at x (g2 a)))).\nProof.\n  intros.\n  assert (Included (reachable g1 y) (reachable g1 x)).\n  1: {\n    hnf; unfold Ensembles.In; intros.\n    apply step_reachable with y; auto.\n  }  \n  apply vertices_at_ramif_xQ. eexists. split; [|split].\n  + apply Ensemble_join_Intersection_Complement; auto. \n  + intros. destruct H5 as [_ ?].\n    rewrite <- H5; clear H5.\n    apply Ensemble_join_Intersection_Complement; auto.\n  + intros.\n    apply GSG_PartialGraphPreserve; auto.\n    - unfold Included, Ensembles.In; intros.\n      rewrite Intersection_spec in H6; destruct H6 as [? _].\n      apply reachable_foot_valid in H6; auto.\n    - destruct H5.\n      rewrite H6; clear H6.\n      unfold Included, Ensembles.In; intros.\n      rewrite Intersection_spec in H6; destruct H6 as [? _].\n      apply reachable_foot_valid in H6; auto.\n    - apply mark_partial_labeled_graph_equiv in H5.\n      eapply si_stronger_partial_labeledgraph_simple; [| eassumption].\n      unfold Included, Ensembles.In; intros.\n      rewrite Intersection_spec in H6.\n      tauto.\nQed.\n\nLemma mark_list_mark_ramify: forall {A} (g1 g2: Graph) (g3: A -> Graph) x l y l',\n  (forall (g: Graph) x y, reachable g x y \\/ ~ reachable g x y) ->\n  vvalid g1 x ->\n  step_list g1 x (l ++ y :: l') ->\n  relation_list (mark1 x :: mark_list l :: nil) g1 g2 ->\n  Included (Intersection V (reachable g2 x) (Complement V (reachable g2 y)))\n     (vguard g2) ->\n  (forall a, mark y g2 (g3 a) -> Included (Intersection V (reachable g2 x) (Complement V (reachable g2 y))) (vguard (g3 a))) ->\n  @derives Pred _\n    (reachable_vertices_at x g2)\n    (reachable_vertices_at y g2 *\n      (ALL a: A, !! mark y g2 (g3 a) -->\n        (reachable_vertices_at y (g3 a) -*\n         reachable_vertices_at x (g3 a)))).\nProof.\n  intros. \n  destruct_relation_list g1' in H2.\n  destruct H5 as [? _].\n  apply (mark_list_eq x) in H2.\n  destruct H2 as [_ ?].\n  rewrite <- H5 in H2; clear g1' H5.\n  apply mark_neighbor_ramify; auto.\n  + destruct H2. rewrite <- (H2 x). auto.\n  + rewrite <- (step_si g1); auto. hnf in H1. rewrite <- H1.\n    rewrite in_app_iff. right. apply in_eq.\nQed.\n\nEnd PointwiseGraph_Mark.\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/msl_application/Graph_Mark.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.21875517543240236}}
{"text": "From fae_gtlc_mu.refinements.static_gradual Require Export logical_relation compat_easy.\nFrom fae_gtlc_mu.embedding Require Import expressions types types_lemmas.\nFrom fae_gtlc_mu.stlc_mu Require Export typing.\nFrom fae_gtlc_mu.cast_calculus Require Export types consistency_lemmas.\nFrom fae_gtlc_mu.refinements.static_gradual Require Import compat_cast.all.\nFrom fae_gtlc_mu.backtranslation Require Import expressions well_typedness.\nFrom fae_gtlc_mu.stlc_mu Require Export contexts.\nFrom fae_gtlc_mu.cast_calculus Require Export contexts.\nFrom fae_gtlc_mu.backtranslation Require Import contexts.\nFrom fae_gtlc_mu Require Export embedding.contexts.\n\n\nSection relation_for_specification_lemma.\n  Context `{!implG Σ, !specG Σ}.\n\n  (** Static terms are related to their embeddings *)\n  (** Proof by induction on the type derivation of expression and application of boring compatibility lemmas. *)\n  Theorem embedding_relates (Γ : list stlc_mu.types.type) (e : stlc_mu.lang.expr) (τ : stlc_mu.types.type) :\n    Γ ⊢ₛ e : τ → map embed_type Γ ⊨ e ≤log≤ [[e]] : [| τ |].\n  Proof.\n    induction 1; simpl.\n    - apply bin_log_related_var. by rewrite list_lookup_fmap H.\n    - by apply bin_log_related_unit.\n    - by apply bin_log_related_pair.\n    - by eapply bin_log_related_fst.\n    - by eapply bin_log_related_snd.\n    - by apply bin_log_related_injl.\n    - by apply bin_log_related_injr.\n    - by eapply bin_log_related_case.\n    - by apply bin_log_related_lam.\n    - by eapply bin_log_related_app.\n    - apply bin_log_related_fold. by rewrite -embd_unfold_comm.\n    - rewrite embd_unfold_comm. apply bin_log_related_unfold. by simpl in IHtyped.\n  Qed.\n\n  (** Gradual terms are related to their backtranslation *)\n  (** Proof by induction on the type derivation of expression and application of all compatibility lemmas (including compatibility lemma for casts now). *)\n  Theorem back_relates (Γ : list cast_calculus.types.type) (e : cast_calculus.lang.expr) (τ : cast_calculus.types.type) :\n    Γ ⊢ₜ e : τ → Γ ⊨ <<<e>>> ≤log≤ e : τ.\n  Proof.\n    induction 1; simpl.\n    - by apply bin_log_related_var.\n    - by apply bin_log_related_unit.\n    - by apply bin_log_related_pair.\n    - by eapply bin_log_related_fst.\n    - by eapply bin_log_related_snd.\n    - by apply bin_log_related_injl.\n    - by apply bin_log_related_injr.\n    - by eapply bin_log_related_case.\n    - by apply bin_log_related_lam.\n    - by eapply bin_log_related_app.\n    - by apply bin_log_related_fold.\n    - by apply bin_log_related_unfold.\n    - assert (pτi : Closed τi). apply (cast_calculus.typing.typed_closed H).\n      destruct (consistency_open_dec τi τf);\n                destruct (decide (Closed τi));\n                destruct (decide (Closed τf)); try by contradiction.\n      by apply bin_log_related_back_cast.\n    - apply bin_log_related_omega.\n  Qed.\n\n  (** Gradual contexts (of depth 1) are related to their backtranslations *)\n  Lemma back_ctx_item_relates (Γ : list cast_calculus.types.type) (e : stlc_mu.lang.expr) (e' : cast_calculus.lang.expr) (τ : cast_calculus.types.type) (pτ : Closed τ)\n        (Γ' : list cast_calculus.types.type) (τ' : cast_calculus.types.type) (C : cast_calculus.contexts.ctx_item) :\n      cast_calculus.contexts.typed_ctx_item C Γ τ Γ' τ' →\n      Γ ⊨ e ≤log≤ e' : τ →\n      Γ' ⊨ stlc_mu.contexts.fill_ctx_item (backtranslate_ctx_item C) e ≤log≤ cast_calculus.contexts.fill_ctx_item C e' : τ'.\n  Proof.\n    destruct C; intros; inversion H; simplify_eq; simpl.\n    - by apply bin_log_related_lam.\n    - eapply bin_log_related_app; eauto using back_relates.\n    - eapply bin_log_related_app; eauto using back_relates.\n    - eapply bin_log_related_pair; eauto using back_relates.\n    - eapply bin_log_related_pair; eauto using back_relates.\n    - by eapply bin_log_related_fst.\n    - by eapply bin_log_related_snd.\n    - by apply bin_log_related_injl.\n    - by apply bin_log_related_injr.\n    - eapply bin_log_related_case; try apply back_relates; try done.\n    - eapply bin_log_related_case; try apply back_relates; try done.\n    - eapply bin_log_related_case; try apply back_relates; try done.\n    - by apply bin_log_related_fold.\n    - by apply bin_log_related_unfold.\n    - destruct (consistency_open_dec τ τ');\n                destruct (decide (Closed τ));\n                destruct (decide (Closed τ')); try by contradiction.\n      by apply bin_log_related_back_cast.\n  Qed.\n\n  (** Gradual contexts are related to their backtranslation *)\n  Lemma back_ctx_relates (Γ : list cast_calculus.types.type) (e : stlc_mu.lang.expr) (e' : cast_calculus.lang.expr) (τ : cast_calculus.types.type) (pτ : Closed τ)\n        (Γ' : list cast_calculus.types.type) (τ' : cast_calculus.types.type) (C : cast_calculus.contexts.ctx) :\n      cast_calculus.contexts.typed_ctx C Γ τ Γ' τ' →\n      Γ ⊨ e ≤log≤ e' : τ →\n      Γ' ⊨ stlc_mu.contexts.fill_ctx (backtranslate_ctx C) e ≤log≤ cast_calculus.contexts.fill_ctx C e' : τ'.\n  Proof.\n    revert Γ τ pτ Γ' τ' e e'.\n    induction C; intros Γ τ pτ Γ' τ' e e' H.\n    - by inversion H.\n    - inversion_clear H. intro Hee'. simpl.\n      apply back_ctx_item_relates with (Γ := Γ2) (τ := τ2). by eapply typed_ctx_closedness. auto. by eapply IHC.\n  Qed.\n\n  (** Static contexts (of depth 1) are related to their embeddings *)\n  Lemma embed_ctx_item_relates (Γ : list stlc_mu.types.type) (e : stlc_mu.lang.expr) (e' : cast_calculus.lang.expr) (τ : stlc_mu.types.type) (pτ : Closed τ)\n        (Γ' : list stlc_mu.types.type) (τ' : stlc_mu.types.type) (C : stlc_mu.contexts.ctx_item) :\n      stlc_mu.contexts.typed_ctx_item C Γ τ Γ' τ' →\n      (map embed_type Γ) ⊨ e ≤log≤ e' : (embed_type τ) →\n      (map embed_type Γ') ⊨ stlc_mu.contexts.fill_ctx_item C e ≤log≤ cast_calculus.contexts.fill_ctx_item (embed_ctx_item C) e' : (embed_type τ').\n  Proof.\n    destruct C; intros; inversion H; simplify_eq; simpl.\n    - by apply bin_log_related_lam.\n    - eapply bin_log_related_app; eauto using embedding_relates.\n    - eapply bin_log_related_app; eauto.\n      assert (TArrow [|τ|] [|τ'|] = embed_type (stlc_mu.types.TArrow τ τ')) as ->; try done.\n      eauto using embedding_relates.\n    - eapply bin_log_related_pair; eauto using embedding_relates.\n    - eapply bin_log_related_pair; eauto using embedding_relates.\n    - by eapply bin_log_related_fst.\n    - by eapply bin_log_related_snd.\n    - by apply bin_log_related_injl.\n    - by apply bin_log_related_injr.\n    - eapply bin_log_related_case; try apply embedding_relates; try done.\n      fold (embed_type τ1). assert ([|τ1|] :: map embed_type Γ' = map embed_type (τ1 :: Γ')) as ->; try done.\n      eauto using embedding_relates.\n      fold (embed_type τ2). assert ([|τ2|] :: map embed_type Γ' = map embed_type (τ2 :: Γ')) as ->; try done.\n      eauto using embedding_relates.\n    - eapply (bin_log_related_case _ _ _ _ _ _ _ _ (embed_type τ2)); try apply embedding_relates; try done.\n      assert (TSum [|τ1|] [|τ2|] = embed_type (stlc_mu.types.TSum τ1 τ2)) as ->; try done.\n      eauto using embedding_relates.\n      assert ([|τ2|] :: map embed_type Γ' = map embed_type (τ2 :: Γ')) as ->; try done.\n      eauto using embedding_relates.\n    - eapply (bin_log_related_case _ _ _ _ _ _ _ (embed_type τ1)); try apply embedding_relates; try done.\n      assert (TSum [|τ1|] [|τ2|] = embed_type (stlc_mu.types.TSum τ1 τ2)) as ->; try done.\n      eauto using embedding_relates.\n      assert ([|τ1|] :: map embed_type Γ' = map embed_type (τ1 :: Γ')) as ->; try done.\n      eauto using embedding_relates.\n    - apply bin_log_related_fold. by rewrite -embd_unfold_comm.\n    - rewrite embd_unfold_comm. by apply bin_log_related_unfold.\n  Qed.\n\n  (** Static contexts are related to their embeddings *)\n  Lemma embed_ctx_relates (Γ : list stlc_mu.types.type) (e : stlc_mu.lang.expr) (e' : cast_calculus.lang.expr) (τ : stlc_mu.types.type) (pτ : Closed τ)\n        (Γ' : list stlc_mu.types.type) (τ' : stlc_mu.types.type) (C : stlc_mu.contexts.ctx) :\n      stlc_mu.contexts.typed_ctx C Γ τ Γ' τ' →\n      (map embed_type Γ) ⊨ e ≤log≤ e' : (embed_type τ) →\n      (map embed_type Γ') ⊨ stlc_mu.contexts.fill_ctx C e ≤log≤ cast_calculus.contexts.fill_ctx (embed_ctx C) e' : (embed_type τ').\n  Proof.\n    revert Γ τ pτ Γ' τ' e e'.\n    induction C; intros Γ τ pτ Γ' τ' e e' H.\n    - by inversion H.\n    - inversion_clear H. intro Hee'. simpl.\n      apply embed_ctx_item_relates with (Γ := Γ2) (τ := τ2). by eapply stlc_mu.contexts.typed_ctx_closedness. auto. by eapply IHC.\n  Qed.\n\nEnd relation_for_specification_lemma.\n", "meta": {"author": "scaup", "repo": "fae-gtlc-mu", "sha": "6c6e64f0844327d55059b97c7aefab023385973e", "save_path": "github-repos/coq/scaup-fae-gtlc-mu", "path": "github-repos/coq/scaup-fae-gtlc-mu/fae-gtlc-mu-6c6e64f0844327d55059b97c7aefab023385973e/theories/refinements/static_gradual/rel_ref_specs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2186974336595646}}
{"text": "Require Import RelationClasses.\nRequire Import Bool.\nRequire Import List.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Event.\nRequire Import Time.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import FulfillStep.\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\n\nInductive sim_localF (none_for:SimPromises.t) (lc_src lc_tgt:Local.t): Prop :=\n| sim_localF_intro\n    (TVIEW_CUR: View.le lc_src.(Local.tview).(TView.cur) lc_tgt.(Local.tview).(TView.cur))\n    (TVIEW_ACQ: View.le lc_src.(Local.tview).(TView.acq) lc_tgt.(Local.tview).(TView.acq))\n    (PROMISES: SimPromises.sem none_for SimPromises.bot lc_src.(Local.promises) lc_tgt.(Local.promises))\n.\n\nLemma sim_localF_nonsynch_loc\n      none_for loc lc_src lc_tgt\n      (SIM: sim_localF none_for lc_src lc_tgt)\n      (NONSYNCH: Memory.nonsynch_loc loc lc_tgt.(Local.promises)):\n  Memory.nonsynch_loc loc lc_src.(Local.promises).\nProof.\n  inv SIM. inv PROMISES. ii. destruct msg.\n  destruct (Memory.get loc t lc_tgt.(Local.promises)) as [[? []]|] eqn:X.\n  - exploit NONSYNCH; eauto. s. i. subst.\n    exploit LE; eauto. rewrite GET. i. inv x.\n    unfold SimPromises.none_if. condtac; ss.\n  - exploit COMPLETE; eauto. rewrite SimPromises.bot_spec. congr.\nQed.\n\nLemma sim_localF_nonsynch\n      none_for lc_src lc_tgt\n      (SIM: sim_localF none_for lc_src lc_tgt)\n      (NONSYNCH: Memory.nonsynch lc_tgt.(Local.promises)):\n  Memory.nonsynch lc_src.(Local.promises).\nProof.\n  ii. eapply sim_localF_nonsynch_loc; eauto.\nQed.\n\nLemma sim_localF_memory_bot\n      none_for lc_src lc_tgt\n      (SIM: sim_localF none_for lc_src lc_tgt)\n      (BOT: lc_tgt.(Local.promises) = Memory.bot):\n  lc_src.(Local.promises) = Memory.bot.\nProof.\n  apply Memory.ext. i. rewrite Memory.bot_get.\n  destruct (Memory.get loc ts lc_src.(Local.promises)) as [[? []]|] eqn:X; ss.\n  inv SIM.  inv PROMISES. exploit COMPLETE; eauto.\n  { rewrite BOT, Memory.bot_get. ss. }\n  rewrite SimPromises.bot_spec. ss.\nQed.\n\nLemma sim_localF_promise\n      none_for\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt mem2_tgt\n      loc from to val released kind\n      (STEP_TGT: Local.promise_step lc1_tgt mem1_tgt loc from to val released lc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_localF none_for lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src mem2_src,\n    <<STEP_SRC: Local.promise_step lc1_src mem1_src loc from to val (SimPromises.none_if loc to none_for released) lc2_src mem2_src (SimPromises.kind_transf loc to none_for kind)>> /\\\n    <<LOCAL2: sim_localF none_for lc2_src lc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit SimPromises.promise; eauto.\n  { apply WF1_SRC. }\n  { apply WF1_TGT. }\n  i. des.\n  exploit sim_memory_closed_opt_view; eauto. i.\n  exploit Memory.promise_future; try apply PROMISE_SRC; eauto.\n  { apply WF1_SRC. }\n  { apply WF1_SRC. }\n  { unfold SimPromises.none_if. condtac; viewtac. }\n  i. des.\n  esplits; eauto.\n  - econs; eauto.\n    unfold SimPromises.none_if. condtac; viewtac.\n  - econs; eauto.\nQed.\n\nLemma read_tview_mon'\n      tview1 tview2 loc ts released1 released2 ord1 ord2\n      (TVIEW_CUR: View.le tview1.(TView.cur) tview2.(TView.cur))\n      (TVIEW_ACQ: View.le tview1.(TView.acq) tview2.(TView.acq))\n      (REL: View.opt_le released1 released2)\n      (WF2: TView.wf tview2)\n      (WF_REL2: View.opt_wf released2)\n      (ORD: Ordering.le ord1 ord2):\n  <<CUR: View.le\n           (TView.read_tview tview1 loc ts released1 ord1).(TView.cur)\n           (TView.read_tview tview2 loc ts released2 ord2).(TView.cur)>> /\\\n  <<ACQ: View.le\n           (TView.read_tview tview1 loc ts released1 ord1).(TView.acq)\n           (TView.read_tview tview2 loc ts released2 ord2).(TView.acq)>>.\nProof.\n  splits.\n  - unfold TView.read_tview, View.singleton_ur_if.\n    repeat (condtac; aggrtac);\n      (try by etrans; [apply TVIEW|aggrtac]);\n      (try by rewrite <- ? View.join_r; econs; aggrtac);\n      (try apply WF2).\n  - unfold TView.read_tview, View.singleton_ur_if.\n    repeat (condtac; aggrtac);\n      (try by etrans; [apply TVIEW|aggrtac]);\n      (try by rewrite <- ? View.join_r; econs; aggrtac);\n      (try apply WF2).\nQed.\n\nLemma sim_localF_read\n      none_for\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt\n      loc ts val released_tgt ord_src ord_tgt\n      (STEP_TGT: Local.read_step lc1_tgt mem1_tgt loc ts val released_tgt ord_tgt lc2_tgt)\n      (LOCAL1: sim_localF none_for lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt):\n  exists released_src lc2_src,\n    <<REL: View.opt_le released_src released_tgt>> /\\\n    <<STEP_SRC: Local.read_step lc1_src mem1_src loc ts val released_src ord_src lc2_src>> /\\\n    <<LOCAL2: sim_localF none_for lc2_src lc2_tgt>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit sim_memory_get; try apply MEM1; eauto. i. des.\n  esplits; eauto.\n  - econs; eauto. eapply TViewFacts.readable_mon; eauto.\n  - exploit read_tview_mon'; eauto.\n    { apply WF1_TGT. }\n    { eapply MEM1_TGT. eauto. }\n    i. des. econs; eauto.\nQed.\n\nLemma write_tview_mon'\n      tview1 tview2 sc1 sc2 loc ts ord1 ord2\n      (TVIEW_CUR: View.le tview1.(TView.cur) tview2.(TView.cur))\n      (TVIEW_ACQ: View.le tview1.(TView.acq) tview2.(TView.acq))\n      (SC: TimeMap.le sc1 sc2)\n      (WF2: TView.wf tview2)\n      (ORD: Ordering.le ord1 ord2):\n  <<CUR: View.le\n           (TView.write_tview tview1 sc1 loc ts ord1).(TView.cur)\n           (TView.write_tview tview2 sc2 loc ts ord2).(TView.cur)>> /\\\n  <<ACQ: View.le\n           (TView.write_tview tview1 sc1 loc ts ord1).(TView.acq)\n           (TView.write_tview tview2 sc2 loc ts ord2).(TView.acq)>>.\nProof.\n  splits.\n  - unfold TView.write_tview.\n    repeat (condtac; aggrtac);\n      (try by etrans; [apply TVIEW|aggrtac]);\n      (try by rewrite <- ? View.join_r; econs; aggrtac);\n      (try apply WF2).\n  - unfold TView.write_tview.\n    repeat (condtac; aggrtac);\n      (try by etrans; [apply TVIEW|aggrtac]);\n      (try by rewrite <- ? View.join_r; econs; aggrtac);\n      (try apply WF2).\nQed.\n\nLemma sim_localF_fulfill\n      none_for\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      loc from to val releasedm_src releasedm_tgt released ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF: View.opt_wf releasedm_src)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (WF_RELM_TGT: View.opt_wf releasedm_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (NONEFOR: (Ordering.le Ordering.acqrel ord_tgt /\\ SimPromises.mem loc to none_for = false) \\/\n                Ordering.le ord_tgt Ordering.plain)\n      (STEP_TGT: fulfill_step lc1_tgt sc1_tgt loc from to val releasedm_tgt released ord_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_localF none_for lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: fulfill_step lc1_src sc1_src loc from to val releasedm_src (SimPromises.none_if loc to none_for released) ord_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_localF (SimPromises.unset loc to none_for) lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  guardH NONEFOR.\n  inv STEP_TGT.\n  assert (RELT_LE:\n   View.opt_le\n     (TView.write_released lc1_src.(Local.tview) sc1_src loc to releasedm_src ord_src)\n     (TView.write_released lc1_tgt.(Local.tview) sc2_tgt loc to releasedm_tgt ord_tgt)).\n  { unguardH NONEFOR. des.\n    - unfold TView.write_released.\n      condtac; [|by econs].\n      condtac; cycle 1.\n      { by destruct ord_tgt; inv NONEFOR; inv COND0. }\n      econs. unfold TView.write_tview. s.\n      repeat (condtac; aggrtac); try by apply WF1_TGT.\n      + rewrite <- View.join_r. rewrite <- ? View.join_l. apply LOCAL1.\n      + rewrite <- View.join_r. rewrite <- ? View.join_l.\n        etrans; [|apply LOCAL1]. apply WF1_SRC.\n    - unfold TView.write_released. repeat (condtac; viewtac). refl.\n  }\n  assert (RELT_WF:\n   View.opt_wf (TView.write_released lc1_src.(Local.tview) sc1_src loc to releasedm_src ord_src)).\n  { unfold TView.write_released. condtac; econs.\n    repeat (try condtac; viewtac; try apply WF1_SRC).\n  }\n  exploit SimPromises.remove; try exact REMOVE;\n    try exact MEM1; try apply LOCAL1; eauto.\n  { apply WF1_SRC. }\n  { apply WF1_TGT. }\n  { apply WF1_TGT. }\n  i. des. esplits.\n  - econs; eauto.\n    + unfold SimPromises.none_if. destruct (SimPromises.mem loc to none_for) eqn:X.\n      * unguardH NONEFOR. des; [congr|]. unfold TView.write_released. condtac; [|refl].\n        destruct ord_src, ord_tgt; inv ORD; inv NONEFOR; inv COND.\n      * etrans; eauto.\n    + unfold SimPromises.none_if. condtac; viewtac.\n    + eapply TViewFacts.writable_mon; try exact WRITABLE; eauto. apply LOCAL1.\n  - exploit write_tview_mon'; eauto.\n    { apply LOCAL1. }\n    { apply LOCAL1. }\n    { apply WF1_TGT. }\n    i. des. econs; eauto.\n  - ss.\nQed.\n\nLemma sim_localF_write\n      none_for\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt mem2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt kind\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_SRC_WF: View.opt_wf releasedm_src)\n      (RELM_SRC_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT_WF: View.opt_wf releasedm_tgt)\n      (RELM_TGT_CLOSED: Memory.closed_opt_view releasedm_tgt mem1_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (ORD_TGT: Ordering.le ord_tgt Ordering.plain \\/ Ordering.le Ordering.acqrel ord_tgt)\n      (STEP_TGT: Local.write_step lc1_tgt sc1_tgt mem1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt sc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_localF none_for lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists released_src lc2_src sc2_src mem2_src,\n    <<STEP_SRC: Local.write_step lc1_src sc1_src mem1_src loc from to val releasedm_src released_src ord_src lc2_src sc2_src mem2_src (SimPromises.kind_transf loc to none_for kind)>> /\\\n    <<REL2: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_localF (SimPromises.unset loc to none_for) lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  guardH ORD_TGT.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit sim_localF_promise; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  assert (NONEFOR: __guard__ ((Ordering.le Ordering.acqrel ord_tgt /\\ SimPromises.mem loc to none_for = false) \\/\n                              Ordering.le ord_tgt Ordering.plain)).\n  { destruct (Ordering.le ord_tgt Ordering.strong_relaxed) eqn:X.\n    - right. unguardH ORD_TGT. destruct ord_tgt; des; ss.\n    - left. splits.\n      { by destruct ord_tgt; inv X. }\n      exploit ORD0.\n      { by destruct ord_tgt; inv X. }\n      i. des. subst.\n      destruct (SimPromises.mem loc to none_for) eqn:Y; ss.\n      inv LOCAL1. inv PROMISES. exploit NONEFOR; eauto. i. des.\n      inv STEP1. inv PROMISE. exploit Memory.add_get0; try exact PROMISES; eauto. congr.\n  }\n  exploit sim_localF_fulfill; try apply STEP2;\n    try apply LOCAL2; try apply MEM2; eauto.\n  { eapply Memory.future_closed_opt_view; eauto. }\n  i. des.\n  exploit promise_fulfill_write; try exact STEP_SRC; try exact STEP_SRC0; eauto.\n  { i. exploit ORD0; eauto.\n    - etrans; eauto.\n    - i. des. subst. splits; auto. eapply sim_localF_nonsynch_loc; eauto.\n  }\n  i. des. esplits; eauto.\n  - unguardH NONEFOR. des.\n    + unfold SimPromises.none_if in *. rewrite NONEFOR0 in *. ss.\n    + subst. unfold TView.write_released at 1. condtac; [|by econs].\n      destruct ord_src, ord_tgt; inv ORD; inv NONEFOR; inv COND.\n  - etrans; eauto.\nQed.\n\nLemma sim_localF_update\n      none_for\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt\n      lc3_tgt sc3_tgt mem3_tgt\n      loc ts1 val1 released1_tgt ord1_src ord1_tgt\n      from2 to2 val2 released2_tgt ord2_src ord2_tgt kind\n      (STEP1_TGT: Local.read_step lc1_tgt mem1_tgt loc ts1 val1 released1_tgt ord1_tgt lc2_tgt)\n      (STEP2_TGT: Local.write_step lc2_tgt sc1_tgt mem1_tgt loc from2 to2 val2 released1_tgt released2_tgt ord2_tgt lc3_tgt sc3_tgt mem3_tgt kind)\n      (LOCAL1: sim_localF none_for lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt)\n      (ORD1: Ordering.le ord1_src ord1_tgt)\n      (ORD2: Ordering.le ord2_src ord2_tgt)\n      (ORD2_TGT: Ordering.le ord2_tgt Ordering.plain \\/ Ordering.le Ordering.acqrel ord2_tgt):\n  exists released1_src released2_src lc2_src lc3_src sc3_src mem3_src,\n    <<REL1: View.opt_le released1_src released1_tgt>> /\\\n    <<REL2: View.opt_le released2_src released2_tgt>> /\\\n    <<STEP1_SRC: Local.read_step lc1_src mem1_src loc ts1 val1 released1_src ord1_src lc2_src>> /\\\n    <<STEP2_SRC: Local.write_step lc2_src sc1_src mem1_src loc from2 to2 val2 released1_src released2_src ord2_src lc3_src sc3_src mem3_src (SimPromises.kind_transf loc to2 none_for kind)>> /\\\n    <<LOCAL3: sim_localF (SimPromises.unset loc to2 none_for) lc3_src lc3_tgt>> /\\\n    <<SC3: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEM3: sim_memory mem3_src mem3_tgt>>.\nProof.\n  guardH ORD2_TGT.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit sim_localF_read; eauto. i. des.\n  exploit Local.read_step_future; eauto. i. des.\n  hexploit sim_localF_write; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_localF_fence\n      none_for\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      ordr_src ordw_src\n      ordr_tgt ordw_tgt\n      (STEP_TGT: Local.fence_step lc1_tgt sc1_tgt ordr_tgt ordw_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_localF none_for lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (ORDR: Ordering.le ordr_src ordr_tgt)\n      (ORDW: Ordering.le ordw_src ordw_tgt)\n      (ORDR_TGT: Ordering.le ordr_tgt Ordering.acqrel)\n      (ORDW_TGT: Ordering.le ordw_tgt Ordering.relaxed):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: Local.fence_step lc1_src sc1_src ordr_src ordw_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_localF none_for lc2_src lc2_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  inv STEP_TGT. esplits; eauto.\n  - econs; eauto. i. eapply sim_localF_nonsynch; eauto.\n    apply RELEASE. etrans; eauto.\n  - econs; try apply LOCAL1.\n    + s. repeat (condtac; aggrtac).\n      * apply LOCAL1.\n      * etrans; [|apply LOCAL1]. apply WF1_SRC.\n      * apply LOCAL1.\n    + s. repeat (condtac; aggrtac).\n      rewrite View.join_comm, View.join_bot_l. apply LOCAL1.\n  - unfold TView.write_fence_sc.\n    repeat (condtac; viewtac).\nQed.\n\nLemma sim_localF_introduction\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      (LOCAL1: sim_local lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt):\n  <<LOCAL2: sim_localF SimPromises.bot lc1_src lc1_tgt>>.\nProof.\n  esplits. econs; apply LOCAL1.\nQed.\n\nLemma sim_localF_lower_src\n      none_for1\n      lc1_src sc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_src mem2_src\n      loc from to val released\n      (LOCAL1: sim_localF none_for1 lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (STEP_SRC: Local.promise_step lc1_src mem1_src loc from to val None lc2_src mem2_src (Memory.op_kind_lower released)):\n  <<LOCAL2: exists none_for2, sim_localF none_for2 lc2_src lc1_tgt>> /\\\n  <<MEM2: sim_memory mem2_src mem1_tgt>> /\\\n  <<WF2_SRC: Local.wf lc2_src mem2_src>>.\nProof.\n  splits.\n  - inv STEP_SRC. inv PROMISE.\n    exists (match Memory.get loc to lc1_tgt.(Local.promises) with\n       | Some _ => SimPromises.set loc to none_for1\n       | None => none_for1\n       end).\n    inv LOCAL1. econs; ss. inv PROMISES0. econs; ss.\n    + ii.\n      exploit LE; eauto. i.\n      exploit Memory.lower_get0; try exact PROMISES; eauto. i.\n      erewrite Memory.lower_o; eauto.\n      unfold SimPromises.none_if.\n      destruct (Memory.get loc to (Local.promises lc1_tgt)) eqn:TGT.\n      * rewrite SimPromises.set_o. condtac; ss.\n        { des. subst. condtac; ss; cycle 1.\n          { revert COND0. condtac; ss. des; congr. }\n          rewrite x in x1. inv x1. ss.\n        }\n        { guardH o. condtac.\n          { revert COND0. condtac; ss.\n            { des. subst. unguardH o. des; congr. }\n            guardH o0. i.\n            rewrite x. repeat f_equal. unfold SimPromises.none_if. condtac; ss.\n          }\n          rewrite x. repeat f_equal. unfold SimPromises.none_if. condtac; ss.\n          revert COND0. condtac; ss.\n        }\n      * condtac; ss. des. subst. congr.\n    + i. revert MEM0. condtac; ss; cycle 1.\n      { eapply NONEFOR. }\n      rewrite SimPromises.set_o. condtac; ss; cycle 1.\n      { eapply NONEFOR. }\n      i. des. subst. destruct p. eauto.\n    + i. revert SRC. erewrite Memory.lower_o; eauto. condtac; ss.\n      * i. des. inv SRC. eapply COMPLETE; eauto. eapply Memory.lower_get0. eauto.\n      * i. eapply COMPLETE; eauto.\n  - etrans; [|eauto]. inv STEP_SRC. inv PROMISE. eapply lower_sim_memory. eauto.\n  - eapply Local.promise_step_future; eauto.\nQed.\n\nLemma sim_localF_nonsynch_src\n      none_for\n      lang st sc\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      (LOCAL1: sim_localF none_for lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (LOCAL1_SRC: Local.wf lc1_src mem1_src)\n      (LOCAL2_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists none_for2 lc2_src mem2_src,\n    <<STEP_SRC: rtc (@Thread.tau_step lang)\n                    (Thread.mk lang st lc1_src sc mem1_src)\n                    (Thread.mk lang st lc2_src sc mem2_src)>> /\\\n    <<NONSYNCH2: Memory.nonsynch lc2_src.(Local.promises)>> /\\\n    <<LOCAL2: sim_localF none_for2 lc2_src lc1_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem1_tgt>>.\nProof.\n  inversion LOCAL1_SRC. unfold Memory.finite in *. des.\n  assert (FINITE' : forall (loc : Loc.t) (from to : Time.t) (msg : Message.t),\n             Memory.get loc to (Local.promises lc1_src) =\n             Some (from, msg) -> msg.(Message.released) <> None -> In (loc, to) dom).\n  { ii. eapply FINITE. eauto. }\n  clear FINITE. move dom after lc1_src. revert_until dom. revert none_for.\n  induction dom.\n  { esplits; eauto. ii. destruct (Message.released msg) eqn:X; ss.\n    exfalso. eapply FINITE'; eauto. congr.\n  }\n  destruct a as [loc to]. i.\n  destruct (Memory.get loc to lc1_src.(Local.promises)) as [[? []]|] eqn:X; cycle 1.\n  { eapply IHdom; eauto. i. exploit FINITE'; eauto. i. inv x; ss.\n    inv H1. congr.\n  }\n  destruct released; cycle 1.\n  { eapply IHdom; eauto. i. exploit FINITE'; eauto. i. inv x; ss.\n    inv H1. rewrite H in X. inv X. ss.\n  }\n  exploit MemoryFacts.promise_exists_None; eauto.\n  { eapply MemoryFacts.some_released_time_lt; [by apply MEM1_SRC|]. apply LOCAL1_SRC. eauto. }\n  i. des.\n  exploit Memory.promise_future; try apply LOCAL1_SRC; eauto; try by econs. i. des.\n  exploit sim_localF_lower_src; eauto.\n  { econs; eauto. econs. }\n  i. des.\n  exploit IHdom; eauto.\n  { eapply Memory.future_closed_timemap; eauto. }\n  { eapply TView.future_closed; eauto. }\n  { s. i. inv x0. revert H.\n    erewrite Memory.lower_o; eauto. condtac; ss.\n    - i. des. inv H. ss.\n    - guardH o. i. exploit FINITE'; eauto. i. des; ss.  inv x.\n      unguardH o. des; congr.\n  }\n  i. des. esplits; try exact NONSYNCH2; eauto.\n  econs 2; eauto. econs.\n  - econs. econs 1. econs; eauto. econs; eauto. econs.\n  - ss.\nQed.\n\nLemma sim_localF_fence_src\n      none_for\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      (NONSYNCH: Memory.nonsynch lc1_src.(Local.promises))\n      (LOCAL1: sim_localF none_for lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: Local.fence_step lc1_src sc1_src Ordering.plain Ordering.acqrel lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_localF none_for lc2_src lc1_tgt>> /\\\n    <<SC2: TimeMap.le sc2_src sc1_tgt>>.\nProof.\n  esplits; ss. econs; s.\n  - repeat (condtac; aggrtac). apply LOCAL1.\n  - repeat (condtac; aggrtac). apply LOCAL1.\n  - apply LOCAL1.\nQed.\n\nLemma sim_localF_elimination\n      none_for\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      (STEP_TGT: Local.fence_step lc1_tgt sc1_tgt Ordering.plain Ordering.acqrel lc2_tgt sc2_tgt)\n      (LOCAL1: sim_localF none_for lc1_src lc1_tgt)\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt):\n  <<LOCAL2: sim_local lc1_src lc2_tgt>> /\\\n  <<SC2: TimeMap.le sc1_src sc2_tgt>>.\nProof.\n  inv LOCAL1. inv STEP_TGT. esplits; ss.\n  econs; s.\n  - unfold TView.read_fence_tview. condtac; ss.\n    unfold TView.write_fence_tview. econs; repeat (condtac; aggrtac).\n    etrans; [|apply TVIEW_CUR]. apply WF1_SRC.\n  - econs; try by apply PROMISES.\n    + inv PROMISES. ii. exploit LE; eauto.\n      unfold SimPromises.none_if. condtac; ss.\n      exploit RELEASE; eauto. s. i. subst. ss.\n    + i. rewrite SimPromises.bot_spec in *. congr.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-coq", "sha": "bff53239c51681ea653745cebf3b30ddd38f97ba", "save_path": "github-repos/coq/snu-sf-promising-coq", "path": "github-repos/coq/snu-sf-promising-coq/promising-coq-bff53239c51681ea653745cebf3b30ddd38f97ba/src/opt/SimLocalF.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.21869742810229936}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.Classes.EquivDec.\nRequire Import Leapfrog.FinType.\nRequire Leapfrog.Syntax.\nRequire Leapfrog.Reachability.\nModule P4A := Leapfrog.Syntax.\nRequire Import Leapfrog.ConfRel.\nImport ListNotations.\n\nSection WP.\n  Set Implicit Arguments.\n\n  (* State identifiers. *)\n  Variable (St1: Type).\n  Context `{St1_eq_dec: EquivDec.EqDec St1 eq}.\n  Context `{St1_finite: @Finite St1 _ St1_eq_dec}.\n\n  Variable (St2: Type).\n  Context `{St2_eq_dec: EquivDec.EqDec St2 eq}.\n  Context `{St2_finite: @Finite St2 _ St2_eq_dec}.\n\n  Notation St := (St1 + St2)%type.\n\n  (* Header identifiers. *)\n  Variable (Hdr: Type).\n  Context `{Hdr_eq_dec: EquivDec.EqDec Hdr eq}.\n  Context `{Hdr_finite: @Finite Hdr _ Hdr_eq_dec}.\n  Variable (Hdr_sz: Hdr -> nat).\n\n  Variable (a: P4A.t St Hdr_sz).\n  Variable (reachable_states: list (state_template a * state_template a)).\n\n  Fixpoint be_subst {c} (be: bit_expr Hdr c) (e: bit_expr Hdr c) (x: bit_expr Hdr c) : bit_expr Hdr c :=\n    match be with\n    | BELit _ _ l => BELit _ _ l\n    | BEBuf _ _ _\n    | BEHdr _ _ _\n    | BEVar _ _ =>\n      if bit_expr_eq_dec be x then e else be\n    | BESlice be hi lo => beslice (be_subst be e x) hi lo\n    | BEConcat e1 e2 => beconcat (be_subst e1 e x) (be_subst e2 e x)\n    end.\n\n  Fixpoint sr_subst {c} (sr: store_rel Hdr c) (e: bit_expr Hdr c) (x: bit_expr Hdr c) : store_rel Hdr c :=\n  match sr with\n  | BRTrue _ _\n  | BRFalse _ _ => sr\n  | BREq e1 e2 => BREq (be_subst e1 e x) (be_subst e2 e x)\n  | BRAnd r1 r2 => brand (sr_subst r1 e x) (sr_subst r2 e x)\n  | BROr r1 r2 => bror (sr_subst r1 e x) (sr_subst r2 e x)\n  | BRImpl r1 r2 => brimpl (sr_subst r1 e x) (sr_subst r2 e x)\n  end.\n\n  Inductive lkind :=\n  | Jump\n  | Read.\n\n  Definition leap_kind (pred cur: state_template a) : lkind :=\n    match cur.(st_buf_len) with\n    | 0 => Jump\n    | _ => Read\n    end.\n\n  Fixpoint expr_to_bit_expr {c n} (s: side) (e: P4A.expr Hdr_sz n) : bit_expr Hdr c :=\n    match e with\n    | P4A.EHdr h => BEHdr c s (P4A.HRVar h)\n    | P4A.ELit _ bs => BELit _ c (Ntuple.t2l bs)\n    | P4A.ESlice _ e hi lo => BESlice (expr_to_bit_expr s e) hi lo\n    | P4A.EConcat l r => BEConcat (expr_to_bit_expr s l) (expr_to_bit_expr s r)\n    end.\n\n  Definition val_to_bit_expr {c n} (value: P4A.v n) : bit_expr Hdr c :=\n    match value with\n    | P4A.VBits _ bs => BELit _ c (Ntuple.t2l bs)\n    end.\n\n  Fixpoint wp_op' {c} (s: side) (o: P4A.op Hdr_sz) : nat * store_rel Hdr c -> nat * store_rel Hdr c :=\n    fun '(buf_hi_idx, phi) =>\n      match o with\n      | P4A.OpNil _ => (buf_hi_idx, phi)\n      | P4A.OpSeq o1 o2 =>\n        wp_op' s o1 (wp_op' s o2 (buf_hi_idx, phi))\n      | P4A.OpExtract _ hdr =>\n        let new_idx := buf_hi_idx - Hdr_sz hdr in\n        let slice := beslice (BEBuf _ _ s) (buf_hi_idx - 1) new_idx in\n        (new_idx, sr_subst phi slice (BEHdr _ s (P4A.HRVar hdr)))\n      | P4A.OpAsgn lhs rhs =>\n        (buf_hi_idx, sr_subst phi (expr_to_bit_expr s rhs) (BEHdr _ s (P4A.HRVar lhs)))\n      end.\n\n  Definition wp_op {c} (s: side) (o: P4A.op Hdr_sz) (phi: store_rel Hdr c) : store_rel Hdr c :=\n    snd (wp_op' s o (P4A.op_size o, phi)).\n\n  Equations pat_cond {ctx: bctx} {ty: P4A.typ} (si: side) (p: P4A.pat ty) (c: P4A.cond Hdr_sz ty) : store_rel Hdr ctx :=\n    { pat_cond si (P4A.PExact val) (P4A.CExpr e) :=\n        BREq (expr_to_bit_expr si e) (val_to_bit_expr val);\n      pat_cond _ (P4A.PAny _) _ :=\n        BRTrue _ _;\n      pat_cond si (P4A.PPair p1 p2) (P4A.CPair e1 e2) :=\n        BRAnd (pat_cond si p1 e1) (pat_cond si p2 e2) }.\n\n  Fixpoint cases_cond\n    {ctx: bctx}\n    {ty: Syntax.typ}\n    (si: side)\n    (cond: Syntax.cond Hdr_sz ty)\n    (target: P4A.state_ref St)\n    (cases: list (P4A.sel_case St ty))\n    (default: P4A.state_ref St)\n    : store_rel Hdr ctx\n  :=\n    match cases with\n    | nil =>\n      if target == default then (BRTrue _ _) else (BRFalse _ _)\n    | case :: cases =>\n      if target == P4A.sc_st case\n      then bror (pat_cond si case.(P4A.sc_pat) cond)\n                (cases_cond si cond target cases default)\n      else brand (brimpl (pat_cond si case.(P4A.sc_pat) cond) (BRFalse _ _))\n                 (cases_cond si cond target cases default)\n    end.\n\n  Definition trans_cond\n             {c: bctx}\n             (s: side)\n             (t: P4A.transition St Hdr_sz)\n             (st': P4A.state_ref St)\n    : store_rel Hdr c :=\n    match t with\n    | P4A.TGoto _ r =>\n      if r == st'\n      then BRTrue _ _\n      else BRFalse _ _\n    | P4A.TSel cond cases default =>\n      cases_cond s cond st' cases default\n    end.\n\n  Definition jump_cond\n             {c}\n             (si: side)\n             (prev cur: state_template a)\n    : store_rel Hdr c :=\n    match prev.(st_state) with\n    | inl cand =>\n      let st := a.(P4A.t_states) cand in\n      trans_cond si (P4A.st_trans st) cur.(st_state)\n    | inr cand =>\n      match cur.(st_state) with\n      | inr false => BRTrue _ _\n      | _ => BRFalse _ _\n      end\n    end.\n\n  (* Left- and right weakest precondition operators. *)\n  Definition wp_lpred {c: bctx}\n             (si: side)\n             (b: bvar c)\n             (prev cur: state_template a)\n             (k: lkind)\n             (phi: store_rel Hdr c)\n    : store_rel Hdr c :=\n    let phi' :=\n    match k with\n    | Read =>\n      phi\n    | Jump =>\n      match prev.(st_state) with\n      | inl s =>\n        let cond := jump_cond si prev cur in\n        let phi'' := sr_subst phi (BELit _ _ []) (BEBuf _ _ si) in\n        wp_op si (a.(P4A.t_states) s).(P4A.st_op) (brimpl cond phi'')\n      | inr s =>\n        sr_subst phi (BELit _ _ []) (BEBuf _ _ si)\n      end\n    end in\n    sr_subst phi' (beconcat (BEBuf _ _ si) (BEVar _ b)) (BEBuf _ _ si).\n\n  Definition wp_pred_pair\n             (phi: conf_rel a)\n             (preds: nat * (state_template a * state_template a))\n    : conf_rel a :=\n    let '(size, (prev_l, prev_r)) := preds in\n    let phi_rel := phi.(cr_rel) in\n    let cur_l := phi.(cr_st).(cs_st1) in\n    let cur_r := phi.(cr_st).(cs_st2) in\n    let leap_l := leap_kind prev_l cur_l in\n    let leap_r := leap_kind prev_r cur_r in\n    let b := BVarTop phi.(cr_ctx) size in\n    let phi_rel := weaken_store_rel size phi_rel in\n    {| cr_st := {| cs_st1 := prev_l;\n                   cs_st2 := prev_r |};\n       cr_rel := wp_lpred Left b prev_l cur_l leap_l\n                          (wp_lpred Right b prev_r cur_r leap_r phi_rel) |}.\n\n  (* Weakest precondition operator. *)\n  Definition wp (phi: conf_rel a) : list (conf_rel a) :=\n    let cur_st_left  := phi.(cr_st).(cs_st1) in\n    let cur_st_right := phi.(cr_st).(cs_st2) in\n    let pred_pairs := List.flat_map (Reachability.reaches (cur_st_left, cur_st_right)) reachable_states in\n    List.map (wp_pred_pair phi) pred_pairs.\n\nEnd WP.\n\nGlobal Hint Unfold wp_lpred: wp.\nGlobal Hint Unfold wp_pred_pair: wp.\n", "meta": {"author": "verified-network-toolchain", "repo": "leapfrog", "sha": "fe8c4e60c9d1c2660ca2a199909bef04c81e5634", "save_path": "github-repos/coq/verified-network-toolchain-leapfrog", "path": "github-repos/coq/verified-network-toolchain-leapfrog/leapfrog-fe8c4e60c9d1c2660ca2a199909bef04c81e5634/lib/WP.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.21868593800993347}}
{"text": "(** * Reflective notations for context free grammars *)\nRequire Import Coq.Strings.Ascii.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Import Fiat.Common.Equality.\n\nGlobal Arguments N_of_ascii !_ / .\nGlobal Arguments Compare_dec.leb !_ !_ / .\nGlobal Arguments BinNat.N.leb !_ !_ / .\nGlobal Arguments BinNat.N.compare !_ !_ / .\nGlobal Arguments BinPos.Pos.to_nat !_ / .\n\nModule opt.\n  Local Arguments N_of_ascii / _ .\n  Local Arguments N_of_digits / _ .\n  Local Arguments BinNat.N.add !_ !_ / .\n  Local Arguments BinNat.N.mul !_ !_ / .\n  Definition N_of_ascii ch\n    := Eval simpl in N_of_ascii ch.\nEnd opt.\n\nGlobal Arguments opt.N_of_ascii !_ / .\n\nDelimit Scope rchar_scope with rchar.\n\nSection syntax.\n  Context {Char : Type}.\n\n  Inductive RCharExpr :=\n  | rbeq (ch : Char)\n  | ror (_ _ : RCharExpr)\n  | rand (_ _ : RCharExpr)\n  | rneg (_ : RCharExpr)\n  | rcode_le_than (code : BinNums.N)\n  | rcode_ge_than (code : BinNums.N).\n\n  Bind Scope rchar_scope with RCharExpr.\n\n  Inductive ritem :=\n  | RTerminal (_ : RCharExpr)\n  | RNonTerminal (_ : String.string).\n\n  Definition rproduction := list ritem.\n  Definition rproductions := list rproduction.\nEnd syntax.\n\nScheme Minimality for ritem Sort Type.\nScheme Minimality for ritem Sort Set.\nScheme Minimality for ritem Sort Prop.\n\nScheme Equality for RCharExpr.\nScheme Equality for ritem.\nGlobal Instance RCharExpr_BoolDecR {Char} {Char_beq : BoolDecR Char} : BoolDecR (@RCharExpr Char)\n  := RCharExpr_beq Char_beq.\nGlobal Instance RCharExpr_BoolDec_bl {Char} {Char_beq : BoolDecR Char} {Char_bl : BoolDec_bl eq} : BoolDec_bl (@eq (@RCharExpr Char))\n  := internal_RCharExpr_dec_bl Char_beq Char_bl.\nGlobal Instance RCharExpr_BoolDec_lb {Char} {Char_beq : BoolDecR Char} {Char_lb : BoolDec_lb eq} : BoolDec_lb (@eq (@RCharExpr Char))\n  := internal_RCharExpr_dec_lb Char_beq Char_lb.\nGlobal Instance ritem_BoolDecR {Char} {Char_beq : BoolDecR Char} : BoolDecR (@ritem Char)\n  := ritem_beq Char_beq.\nGlobal Instance ritem_BoolDec_bl {Char} {Char_beq : BoolDecR Char} {Char_bl : BoolDec_bl eq} : BoolDec_bl (@eq (@ritem Char))\n  := internal_ritem_dec_bl Char_beq Char_bl.\nGlobal Instance ritem_BoolDec_lb {Char} {Char_beq : BoolDecR Char} {Char_lb : BoolDec_lb eq} : BoolDec_lb (@eq (@ritem Char))\n  := internal_ritem_dec_lb Char_beq Char_lb.\n\nGlobal Arguments RCharExpr : clear implicits.\nGlobal Arguments ritem : clear implicits.\nGlobal Arguments rproduction : clear implicits.\nGlobal Arguments rproductions : clear implicits.\nGlobal Arguments rbeq {Char%type_scope} _.\nGlobal Arguments ror {Char%type_scope} (_ _)%rchar_scope.\nGlobal Arguments rand {Char%type_scope} (_ _)%rchar_scope.\nGlobal Arguments rneg {Char%type_scope} (_)%rchar_scope.\nGlobal Arguments rcode_le_than {Char%type_scope} (_)%N_scope.\nGlobal Arguments rcode_ge_than {Char%type_scope} (_)%N_scope.\n\nInfix \"||\" := ror : rchar_scope.\nInfix \"&&\" := rand : rchar_scope.\nNotation \"~ x\" := (rneg x) : rchar_scope.\n\nSection semantics.\n  Context {Char : Type}.\n\n  Class interp_RCharExpr_data :=\n    { irbeq : Char -> Char -> bool;\n      irN_of : Char -> BinNums.N }.\n\n  Context {idata : interp_RCharExpr_data}.\n\n  Fixpoint interp_RCharExpr (expr : RCharExpr Char) : Char -> bool\n    := match expr with\n       | rbeq ch => irbeq ch\n       | ror a b => fun ch => interp_RCharExpr a ch || interp_RCharExpr b ch\n       | rand a b => fun ch => interp_RCharExpr a ch && interp_RCharExpr b ch\n       | rneg x => fun ch => negb (interp_RCharExpr x ch)\n       | rcode_le_than code => fun ch => BinNat.N.leb (irN_of ch) code\n       | rcode_ge_than code => fun ch => BinNat.N.leb code (irN_of ch)\n       end%bool.\n\n  (*Global Coercion interp_RCharExpr : RCharExpr >-> Funclass.*)\n\n  Definition interp_ritem (expr : ritem Char) : item Char\n    := match expr with\n       | RTerminal x => Terminal (interp_RCharExpr x)\n       | RNonTerminal x => NonTerminal x\n       end.\n\n  Definition interp_rproduction (expr : rproduction Char) : production Char\n    := List.map interp_ritem expr.\n\n  Definition interp_rproductions (expr : rproductions Char) : productions Char\n    := List.map interp_rproduction expr.\nEnd semantics.\n\nGlobal Arguments interp_RCharExpr_data : clear implicits.\n\nGlobal Instance ascii_interp_RCharExpr_data : interp_RCharExpr_data Ascii.ascii\n  := { irbeq := Equality.ascii_beq;\n       irN_of := opt.N_of_ascii }.\n\n(** Alternative that isn't higher order *)\nDefinition char_at_matches_interp {Char} {HSLM : StringLikeMin Char}\n           {_ : interp_RCharExpr_data Char} n str P\n  := char_at_matches n str (interp_RCharExpr P).\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/ContextFreeGrammar/Reflective.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.21868593800993344}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import ssreflect ssrbool.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils\n  PCUICReduction\n  PCUICClosed PCUICTyping PCUICWcbvEval PCUICLiftSubst PCUICInversion PCUICArities\n  PCUICSR PCUICGeneration PCUICSubstitution PCUICElimination\n  PCUICWeakeningEnv PCUICWeakeningEnvTyp\n  PCUICWellScopedCumulativity\n  PCUICContextConversion PCUICConversion PCUICCanonicity\n  PCUICSpine PCUICInductives PCUICInductiveInversion PCUICConfluence\n  PCUICArities PCUICPrincipality.\n\nFrom MetaCoq.Erasure Require Import Extract.\n\nNotation \"Σ ⊢p s ▷ t\" := (eval Σ s t) (at level 50, s, t at next level) : type_scope.\n\nRequire Import Program.\nFrom Equations Require Import Equations.\n\nLocal Existing Instance extraction_checker_flags.\n\nImplicit Types (cf : checker_flags) (Σ : global_env_ext).\n\n(* TODO move *)\n#[global] Existing Instance extends_refl.\n\nLemma isErasable_Proof Σ Γ t :\n  Is_proof Σ Γ t -> isErasable Σ Γ t.\nProof.\n  intros. destruct X as (? & ? & ? & ? & ?). exists x. split. eauto. right.\n  eauto.\nQed.\n\nLemma isType_isErasable Σ Γ T : isType Σ Γ T -> isErasable Σ Γ T.\nProof.\n  intros [s Hs].\n  exists (tSort s). intuition auto. left; simpl; auto.\nQed.\n\nLemma isType_red:\n  forall (Σ : global_env_ext) (Γ : context) (T : term), wf Σ -> wf_local Σ Γ ->\n    isType Σ Γ T -> forall x5 : term, red Σ Γ T x5 -> isType Σ Γ x5.\nProof.\n  intros. destruct X1 as [].\n  eexists. eapply subject_reduction ; eauto.\nQed.\n\nLemma it_mkProd_isArity:\n  forall (l : list context_decl) A,\n    isArity A ->\n    isArity (it_mkProd_or_LetIn l A).\nProof.\n  induction l; cbn; intros; eauto.\n  eapply IHl. destruct a, decl_body; cbn; eauto.\nQed.\n\nLemma isArity_ind_type (Σ : global_env_ext) mind ind idecl :\n  wf Σ ->\n  declared_inductive (fst Σ) ind mind idecl ->\n  isArity (ind_type idecl).\nProof.\n  intros.\n  eapply (declared_inductive_inv weaken_env_prop_typing) in H; eauto.\n  - inv H. rewrite ind_arity_eq.\n    change PCUICEnvironment.it_mkProd_or_LetIn with it_mkProd_or_LetIn.\n    rewrite <- it_mkProd_or_LetIn_app.\n    clear.\n    eapply it_mkProd_isArity. econstructor.\nQed.\n\nLemma isWfArity_prod_inv (Σ : global_env_ext) (Γ : context) (x : aname) (x0 x1 : term) :\n    wf Σ ->\n    isWfArity Σ Γ (tProd x x0 x1) -> (isType Σ Γ x0 × isWfArity Σ (Γ,, vass x x0) x1).\nProof.\n  intros wfΣ (? & ? & ? & ?). cbn in e.\n  eapply isType_tProd in i as [dom codom]; auto.\n  split; auto.\n  split; auto.\n  clear dom codom.\n  eapply destArity_app_Some in e as (? & ? & ?); subst.\n  eexists. eexists; eauto.\nQed.\n\nLemma inds_nth_error ind u l n t :\n  nth_error (inds ind u l) n = Some t -> exists n, t = tInd {| inductive_mind := ind ; inductive_ind := n |} u.\nProof.\n  unfold inds in *. generalize (#|l|). clear. revert t.\n  induction n; intros.\n  - destruct n. cbn in H. congruence. cbn in H. inv H.\n    eauto.\n  - destruct n0. cbn in H. congruence. cbn in H.\n    eapply IHn. eauto.\nQed.\n\nLemma it_mkProd_arity :\n  forall (l : list context_decl) (A : term), isArity (it_mkProd_or_LetIn l A) -> isArity A.\nProof.\n  induction l; cbn; intros.\n  - eauto.\n  - eapply IHl in H. destruct a, decl_body; cbn in *; eauto.\nQed.\n\nLemma isArity_mkApps t L : isArity (mkApps t L) -> isArity t /\\ L = [].\nProof.\n  revert t; induction L; cbn; intros.\n  - eauto.\n  - eapply IHL in H. cbn in H. tauto.\nQed.\n\nLemma typing_spine_red (Σ : global_env_ext) Γ (args args' : list PCUICAst.term)\n  (X : All2 (red Σ Γ) args args') (wfΣ : wf Σ)\n  (T x x0 : PCUICAst.term)\n  (t0 : typing_spine Σ Γ x args x0)\n  (c : Σ;;; Γ ⊢ x0 ≤ T) x1\n  (c0 : Σ;;; Γ ⊢ x1 ≤ x) :\n  isType Σ Γ x1 ->\n  isType Σ Γ T ->\n  typing_spine Σ Γ x1 args' T.\nProof.\n  intros ? ?. revert args' X.\n  dependent induction t0; intros.\n  - inv X. econstructor; eauto. transitivity ty => //.\n    now transitivity ty'.\n  - inv X. econstructor; tea.\n    + transitivity ty => //.\n    + eapply subject_reduction; eauto.\n    + eapply IHt0; eauto.\n      eapply red_ws_cumul_pb_inv.\n      unfold subst1.\n      eapply isType_tProd in i0 as [dom codom].\n      eapply (closed_red_red_subst (Δ := [vass na A]) (Γ' := [])); auto.\n      simpl. eapply isType_wf_local in codom. fvs.\n      constructor; auto. eapply into_closed_red; auto. fvs. fvs.\n      repeat constructor. eapply isType_is_open_term in codom; fvs.\n      eapply isType_apply in i0; tea.\n      eapply subject_reduction; tea.\nQed.\n\nLemma it_mkProd_red_Arity {Σ : global_env_ext} {Γ c0 i u l} {wfΣ : wf Σ} :\n  ~ Is_conv_to_Arity Σ Γ (it_mkProd_or_LetIn c0 (mkApps (tInd i u) l)).\nProof.\n  intros (? & [] & ?). eapply red_it_mkProd_or_LetIn_mkApps_Ind in X as (? & ? & ?). subst.\n  eapply it_mkProd_arity in H. eapply isArity_mkApps in H as [[] ].\nQed.\n\nLemma invert_it_Ind_eq_prod:\n  forall (u : Instance.t) (i : inductive) (x : aname) (x0 x1 : term) (x2 : context) (x3 : list term),\n    tProd x x0 x1 = it_mkProd_or_LetIn x2 (mkApps (tInd i u) x3) -> exists (L' : context) (l' : list term), x1 = it_mkProd_or_LetIn L' (mkApps (tInd i u) l').\nProof.\n  intros u i x x0 x1 x2 x3 H0.\n  revert x0 x3 x1 x H0. induction x2 using rev_ind; intros.\n  - cbn. assert (decompose_app (tProd x x0 x1) = decompose_app (mkApps (tInd i u) x3)) by now rewrite H0.\n    rewrite decompose_app_mkApps in H; cbn; eauto. cbn in H. inv H.\n  - rewrite it_mkProd_or_LetIn_app in H0. cbn in *.\n    destruct x, decl_body; cbn in H0; try now inv H0.\nQed.\n\n(* if a constructor is a type or proof, it is a proof *)\n\nLemma declared_constructor_type_not_arity {Σ : global_env_ext} {wfΣ : wf Σ} {Γ} {ind n mdecl idecl cdecl u} :\n  declared_constructor Σ (ind, n) mdecl idecl cdecl ->\n  ~ Is_conv_to_Arity Σ Γ (type_of_constructor mdecl cdecl (ind, n) u).\nProof.\n  intros decl; sq.\n  unfold type_of_constructor.\n  destruct (on_declared_constructor decl) as [XX [s [XX1 Ht]]].\n  rewrite (cstr_eq Ht). clear -wfΣ decl.\n  rewrite !PCUICUnivSubst.subst_instance_it_mkProd_or_LetIn !subst_it_mkProd_or_LetIn.\n  rewrite /cstr_concl.\n  rewrite /cstr_concl_head. len.\n  rewrite subst_cstr_concl_head.\n  destruct decl as [[] ?]. now eapply nth_error_Some_length in H0.\n  rewrite -it_mkProd_or_LetIn_app.\n  now eapply it_mkProd_red_Arity.\nQed.\n\nLemma conv_to_arity_cumul {Σ : global_env_ext} {wfΣ : wf Σ} :\n  forall (Γ : context) (C : term) T,\n    Is_conv_to_Arity Σ Γ T ->\n    Σ;;; Γ ⊢ C ≤ T ->\n    Is_conv_to_Arity Σ Γ C.\nProof.\n  intros Γ C T [? []] cum. sq.\n  eapply invert_cumul_arity_r_gen; tea.\n  exists x. split; auto. now sq.\nQed.\n\nLemma typing_spine_mkApps_Ind_ex {Σ : global_env_ext} {wfΣ : wf Σ} Γ Δ ind u args args' T' :\n  typing_spine Σ Γ (it_mkProd_or_LetIn Δ (mkApps (tInd ind u) args)) args' T' ->\n  ∑ Δ' args', Σ ;;; Γ ⊢ it_mkProd_or_LetIn Δ' (mkApps (tInd ind u) args') ≤ T'.\nProof.\n  induction Δ in args, args' |- * using PCUICInduction.ctx_length_rev_ind.\n  - simpl. intros sp.\n    dependent elimination sp as [spnil i i' e|spcons i i' e e' c].\n    * now exists [], args.\n    * now eapply invert_cumul_ind_prod in e.\n  - rewrite it_mkProd_or_LetIn_app /=; destruct d as [na [b|] ty].\n    * rewrite /mkProd_or_LetIn /=. simpl => /= sp.\n      eapply typing_spine_letin_inv in sp; eauto.\n      rewrite /subst1 subst_it_mkProd_or_LetIn Nat.add_0_r subst_mkApps /= in sp.\n      apply (X (subst_context [b] 0 Γ0) ltac:(now len) _ _ sp).\n    * rewrite /mkProd_or_LetIn /=. simpl => /= sp.\n      simpl.\n      dependent elimination sp as [spnil i i' e|spcons i i' e e' sp].\n      { exists (Γ0 ++ [vass na ty]).\n        exists args. now rewrite it_mkProd_or_LetIn_app. }\n      eapply ws_cumul_pb_Prod_Prod_inv in e as [eqna dom codom]; pcuic.\n      eapply (substitution0_ws_cumul_pb (t:=hd0)) in codom; eauto.\n      eapply typing_spine_strengthen in sp. 3:tea.\n      rewrite /subst1 subst_it_mkProd_or_LetIn Nat.add_0_r subst_mkApps /= in sp.\n      apply (X (subst_context [hd0] 0 Γ0) ltac:(len; reflexivity) _ _ sp).\n      eapply isType_apply in i; tea.\n      eapply (type_ws_cumul_pb (pb:=Conv)); tea. 2:now symmetry.\n      now eapply isType_tProd in i as [].\nQed.\n\nLemma typing_spine_Is_conv_to_Arity {Σ : global_env_ext} {wfΣ : wf Σ} {Γ Δ ind u args args' T'} :\n  typing_spine Σ Γ (it_mkProd_or_LetIn Δ (mkApps (tInd ind u) args)) args' T' ->\n  ~ Is_conv_to_Arity Σ Γ T'.\nProof.\n  move/typing_spine_mkApps_Ind_ex => [Δ' [args'' cum]].\n  intros iscv.\n  eapply invert_cumul_arity_r_gen in iscv; tea.\n  now eapply it_mkProd_red_Arity in iscv.\nQed.\n\nLemma declared_constructor_typing_spine_not_arity {Σ : global_env_ext} {wfΣ : wf Σ} {Γ} {ind n mdecl idecl cdecl u args' T'} :\n  declared_constructor Σ (ind, n) mdecl idecl cdecl ->\n  typing_spine Σ Γ (type_of_constructor mdecl cdecl (ind, n) u) args' T' ->\n  ~ Is_conv_to_Arity Σ Γ T'.\nProof.\n  intros decl; sq.\n  unfold type_of_constructor.\n  destruct (on_declared_constructor decl) as [XX [s [XX1 Ht]]].\n  rewrite (cstr_eq Ht). clear -wfΣ decl.\n  rewrite !PCUICUnivSubst.subst_instance_it_mkProd_or_LetIn !subst_it_mkProd_or_LetIn.\n  rewrite /cstr_concl.\n  rewrite /cstr_concl_head. len.\n  rewrite subst_cstr_concl_head.\n  destruct decl as [[] ?]. now eapply nth_error_Some_length in H0.\n  rewrite -it_mkProd_or_LetIn_app.\n  apply typing_spine_Is_conv_to_Arity.\nQed.\n\nLemma type_mkApps_tConstruct_n_conv_arity (Σ : global_env_ext) Γ ind c u x1 T : wf Σ ->\n  Σ ;;; Γ |- mkApps (tConstruct ind c u) x1 : T ->\n  ~ Is_conv_to_Arity Σ Γ T.\nProof.\n  intros.\n  eapply PCUICValidity.inversion_mkApps in X0 as (? & ? & ?); eauto.\n  eapply inversion_Construct in t as (? & ? & ? & ? & ? & ? & ?) ; auto.\n  eapply typing_spine_strengthen in t0. 3:tea.\n  eapply declared_constructor_typing_spine_not_arity in t0; tea.\n  eapply PCUICValidity.validity. econstructor; eauto.\nQed.\n\nLemma nIs_conv_to_Arity_nArity {Σ : global_env_ext} {wfΣ : wf Σ} {Γ T} :\n  isType Σ Γ T ->\n  ~ Is_conv_to_Arity Σ Γ T -> ~ isArity T.\nProof.\n  intros isty nisc isa. apply nisc.\n  exists T. split => //. sq.\n  destruct isty as [s Hs].\n  eapply wt_closed_red_refl; tea.\nQed.\n\nLemma tConstruct_no_Type (Σ : global_env_ext) Γ ind c u x1 : wf Σ ->\n  isErasable Σ Γ (mkApps (tConstruct ind c u) x1) ->\n  Is_proof Σ Γ (mkApps (tConstruct ind c u) x1).\nProof.\n  intros wfΣ (? & ? & [ | (? & ? & ?)]).\n  - exfalso.\n    eapply nIs_conv_to_Arity_nArity; tea.\n    eapply PCUICValidity.validity; tea.\n    eapply type_mkApps_tConstruct_n_conv_arity in t; auto.\n  - exists x, x0. eauto.\nQed.\n\n(* if a cofixpoint is a type or proof, it is a proof *)\n\nLemma tCoFix_no_Type (Σ : global_env_ext) Γ mfix idx x1 : wf Σ ->\n  isErasable Σ Γ (mkApps (tCoFix mfix idx) x1) ->\n  Is_proof Σ Γ (mkApps (tCoFix mfix idx) x1).\nProof.\n  intros wfΣ (? & ? & [ | (? & ? & ?)]).\n  - exfalso.\n    eapply PCUICValidity.inversion_mkApps in t as (? & ? & ?); eauto.\n    pose proof (typing_spine_isType_codom t0).\n    assert(c0 : Σ ;;; Γ ⊢ x ≤ x) by now eapply (isType_ws_cumul_pb_refl).\n    revert c0 t0 i. generalize x at 1 3.\n    intros x2 c0 t0 i.\n    assert (HWF : isType Σ Γ x2).\n    { eapply PCUICValidity.validity.\n      eapply type_mkApps. 2:eauto. eauto.\n    }\n    eapply inversion_CoFix in t as (? & ? & ? & ? & ? & ? & ?) ; auto.\n    eapply invert_cumul_arity_r in c0; eauto.\n    eapply typing_spine_strengthen in t0. 3:eauto.\n    eapply wf_cofixpoint_spine in i0; eauto.\n    2-3:eapply nth_error_all in a; eauto; simpl in a; eauto.\n    destruct i0 as (Γ' & T & DA & ind & u & indargs & (eqT & ck) & cum).\n    destruct (Nat.ltb #|x1| (context_assumptions Γ')).\n    eapply invert_cumul_arity_r_gen in c0; eauto.\n    destruct c0. destruct H as [[r] isA].\n    move: r; rewrite subst_it_mkProd_or_LetIn eqT; autorewrite with len.\n    rewrite PCUICSigmaCalculus.expand_lets_mkApps subst_mkApps /=.\n    move/red_it_mkProd_or_LetIn_mkApps_Ind => [ctx' [args' eq]].\n    subst x4. now eapply it_mkProd_arity, isArity_mkApps in isA.\n    move: cum => [] Hx1; rewrite eqT PCUICSigmaCalculus.expand_lets_mkApps subst_mkApps /= => cum.\n    eapply invert_cumul_arity_r_gen in c0; eauto.\n    now eapply Is_conv_to_Arity_ind in c0.\n  - eexists _, _; intuition eauto.\nQed.\n\nLemma typing_spine_wat (Σ : global_env_ext) (Γ : context) (L : list term)\n  (x x0 : term) :\n    wf Σ ->\n    typing_spine Σ Γ x L x0 ->\n    isType Σ Γ x0.\nProof.\n  intros wfΣ; induction 1; auto.\nQed.\n\nSection Elim'.\n\nContext `{cf : checker_flags}.\nContext {Σ : global_env_ext} {wfΣ : wf_ext Σ}.\nVariable Hcf : prop_sub_type = false.\nVariable Hcf' : check_univs.\n\nLemma cumul_prop1 Γ A B u :\n  Universe.is_prop u ->\n  isType Σ Γ A ->\n  Σ ;;; Γ |- B : tSort u ->\n  Σ ;;; Γ ⊢ A ≤ B ->\n  Σ ;;; Γ |- A : tSort u.\nProof using Hcf Hcf' wfΣ.\n  intros; eapply cumul_prop1; tea.\n  now apply ws_cumul_pb_forget in X1.\nQed.\n\nLemma cumul_prop2 Γ A B u :\n  Universe.is_prop u ->\n  isType Σ Γ B ->\n  Σ ;;; Γ ⊢ A ≤ B ->\n  Σ ;;; Γ |- A : tSort u ->\n  Σ ;;; Γ |- B : tSort u.\nProof using Hcf Hcf' wfΣ.\n  intros. eapply cumul_prop2; tea.\n  now apply ws_cumul_pb_forget in X0.\nQed.\n\nLemma cumul_sprop1 Γ A B u :\n  Universe.is_sprop u ->\n  isType Σ Γ A ->\n  Σ ;;; Γ |- B : tSort u ->\n  Σ ;;; Γ ⊢ A ≤ B ->\n  Σ ;;; Γ |- A : tSort u.\nProof using Hcf Hcf' wfΣ.\n  intros. eapply cumul_sprop1; tea.\n  now apply ws_cumul_pb_forget in X1.\nQed.\n\nLemma cumul_sprop2 Γ A B u :\n  Universe.is_sprop u ->\n  isType Σ Γ B ->\n  Σ ;;; Γ ⊢ A ≤ B ->\n  Σ ;;; Γ |- A : tSort u ->\n  Σ ;;; Γ |- B : tSort u.\nProof using Hcf Hcf' wfΣ.\n  intros. eapply cumul_sprop2; tea.\n  now apply ws_cumul_pb_forget in X0.\nQed.\nEnd Elim'.\n\nLemma cumul_propositional (Σ : global_env_ext) Γ A B u :\n  wf_ext Σ ->\n  is_propositional u ->\n  isType Σ Γ B ->\n  Σ ;;; Γ ⊢ A ≤ B ->\n  Σ ;;; Γ |- A : tSort u ->\n  Σ ;;; Γ |- B : tSort u.\nProof.\n  intros wf.\n  destruct u => //.\n  intros _ [s Hs] cum Ha.\n  eapply cumul_prop2; eauto. now exists s.\n  intros _ [s Hs] cum Ha.\n  eapply cumul_sprop2; eauto. now exists s.\nQed.\n\nLemma sort_typing_spine:\n  forall (Σ : global_env_ext) (Γ : context) (L : list term) (u : Universe.t) (x x0 : term),\n    wf_ext Σ ->\n    is_propositional u ->\n    typing_spine Σ Γ x L x0 ->\n    Σ;;; Γ |- x : tSort u ->\n    ∑ u', Σ;;; Γ |- x0 : tSort u' × is_propositional u'.\nProof.\n  intros Σ Γ L u x x0 HΣ ? t1 c0.\n  assert (X : wf Σ) by apply HΣ.\n  revert u H c0.\n  induction t1; intros.\n  - destruct u => //. eapply cumul_prop2 in c0; eauto.\n    eapply cumul_sprop2 in c0; eauto.\n  - eapply cumul_propositional in c0; auto. 2-3: tea.\n    eapply inversion_Prod in c0 as (? & ? & ? & ? & e0) ; auto.\n    eapply ws_cumul_pb_Sort_inv in e0.\n    unfold is_propositional in H.\n    destruct (Universe.is_prop u) eqn:isp => //.\n    eapply leq_universe_prop_r in e0 as H0; cbn; eauto.\n    eapply is_prop_sort_prod in H0. eapply IHt1; [unfold is_propositional; now rewrite -> H0|].\n    change (tSort x0) with ((tSort x0) {0 := hd}).\n    eapply substitution0; eauto.\n    eapply leq_universe_sprop_r in e0 as H0; cbn; eauto.\n    eapply is_sprop_sort_prod in H0. eapply IHt1; [unfold is_propositional; now rewrite -> H0, orb_true_r|].\n    change (tSort x0) with ((tSort x0) {0 := hd}).\n    eapply substitution0; eauto.\nQed.\n\nLemma arity_type_inv (Σ : global_env_ext) Γ t T1 T2 : wf_ext Σ -> wf_local Σ Γ ->\n  Σ ;;; Γ |- t : T1 -> isArity T1 -> Σ ;;; Γ |- t : T2 -> Is_conv_to_Arity Σ Γ T2.\nProof.\n  intros wfΣ wfΓ. intros.\n  destruct (common_typing _ _ X X0) as (? & e & ? & ?).\n  eapply invert_cumul_arity_l_gen; tea.\n  eapply invert_cumul_arity_r_gen. 2:exact e.\n  exists T1. split; auto. sq.\n  eapply PCUICValidity.validity in X as [s Hs].\n  eapply wt_closed_red_refl; eauto.\nQed.\n\nLemma cumul_prop1' (Σ : global_env_ext) Γ A B u :\n  check_univs ->\n  wf_ext Σ ->\n  isType Σ Γ A ->\n  is_propositional u ->\n  Σ ;;; Γ |- B : tSort u ->\n  Σ ;;; Γ ⊢ A ≤ B ->\n  Σ ;;; Γ |- A : tSort u.\nProof.\n  intros.\n  destruct X0 as [s Hs].\n  destruct u => //.\n  eapply cumul_prop1 in X2; eauto. now exists s.\n  eapply cumul_sprop1 in X2; eauto. now exists s.\nQed.\n\nLemma cumul_prop2' (Σ : global_env_ext) Γ A B u :\n  check_univs ->\n  wf_ext Σ ->\n  isType Σ Γ A ->\n  is_propositional u ->\n  Σ ;;; Γ |- B : tSort u ->\n  Σ ;;; Γ ⊢ B ≤ A ->\n  Σ ;;; Γ |- A : tSort u.\nProof.\n  intros.\n  destruct X0 as [s Hs].\n  destruct u => //.\n  eapply cumul_prop2 in X2; eauto. now exists s.\n  eapply cumul_sprop2 in X2; eauto. now exists s.\nQed.\n\nLemma leq_term_propositional_sorted_l {Σ Γ v v' u u'} :\n  wf_ext Σ ->\n  PCUICEquality.leq_term Σ (global_ext_constraints Σ) v v' ->\n  Σ;;; Γ |- v : tSort u ->\n  Σ;;; Γ |- v' : tSort u' -> is_propositional u ->\n  leq_universe (global_ext_constraints Σ) u' u.\nProof.\n  intros wf leq Hv Hv' isp.\n  unfold is_propositional in isp.\n  destruct u => //.\n  eapply leq_term_prop_sorted_l; eauto.\n  eapply leq_term_sprop_sorted_l; eauto.\nQed.\n\nLemma leq_term_propopositional_sorted_r {Σ Γ v v' u u'} :\n  wf_ext Σ ->\n  PCUICEquality.leq_term Σ (global_ext_constraints Σ) v v' ->\n  Σ;;; Γ |- v : tSort u ->\n  Σ;;; Γ |- v' : tSort u' -> is_propositional u' ->\n  leq_universe (global_ext_constraints Σ) u u'.\nProof.\n  intros wfΣ leq hv hv' isp.\n  unfold is_propositional in isp.\n  destruct u' => //.\n  eapply leq_term_prop_sorted_r; eauto.\n  eapply leq_term_sprop_sorted_r; eauto.\nQed.\n\nLemma Is_type_app (Σ : global_env_ext) Γ t L T :\n  wf_ext Σ ->\n  wf_local Σ Γ ->\n  Σ ;;; Γ |- mkApps t L : T ->\n  isErasable Σ Γ t ->\n  ∥isErasable Σ Γ (mkApps t L)∥.\nProof.\n  intros wfΣ wfΓ ? ?.\n  assert (HW : isType Σ Γ T). eapply PCUICValidity.validity; eauto.\n  eapply PCUICValidity.inversion_mkApps in X as (? & ? & ?); auto.\n  destruct X0 as (? & ? & [ | [u]]).\n  - eapply common_typing in t2 as (? & e & e0 & ?). 2:eauto. 2:exact t0.\n    eapply invert_cumul_arity_r in e0; eauto.\n    destruct e0 as (? & ? & ?). destruct H as [].\n    eapply ws_cumul_pb_red_l_inv in e. 2:exact X.\n    eapply type_reduction_closed in t2; tea.\n    eapply typing_spine_strengthen in t1. 3:tea.\n    unshelve epose proof (isArity_typing_spine wfΓ t1).\n    2:{ eapply PCUICValidity.validity in t2; tea; pcuic. }\n    forward H. eapply arity_type_inv; tea.\n    destruct H as [T' [[]]].\n    sq. exists T'. split. eapply type_mkApps; tea.\n    eapply typing_spine_weaken_concl; tea.\n    now eapply red_conv.\n    eapply isType_red; tea; pcuic. exact X0.\n    now left.\n  - destruct p.\n    eapply PCUICPrincipality.common_typing in t2 as (? & e & e0 & ?). 2:eauto. 2:exact t0.\n    eapply cumul_prop1' in e0; eauto.\n    eapply cumul_propositional in e; eauto.\n    econstructor. exists T. split. eapply type_mkApps. 2:eassumption. eassumption. right.\n    eapply sort_typing_spine in t1; eauto.\n    now eapply PCUICValidity.validity in t0.\n    now apply PCUICValidity.validity in t2.\nQed.\n\nLemma leq_universe_propositional_r {cf : checker_flags} (ϕ : ConstraintSet.t) (u1 u2 : Universe.t_) :\n  check_univs ->\n  consistent ϕ ->\n  leq_universe ϕ u1 u2 -> is_propositional u2 -> is_propositional u1.\nProof.\n  intros cu cons leq; unfold is_propositional.\n  destruct u2 => //.\n  apply leq_universe_prop_r in leq => //.\n  now rewrite leq.\n  intros _.\n  apply leq_universe_sprop_r in leq => //.\n  now rewrite leq orb_true_r.\nQed.\n\nLemma leq_universe_propositional_l {cf : checker_flags} (ϕ : ConstraintSet.t) (u1 u2 : Universe.t_) :\n  check_univs ->\n  prop_sub_type = false ->\n  consistent ϕ ->\n  leq_universe ϕ u1 u2 -> is_propositional u1 -> is_propositional u2.\nProof.\n  intros cu ps cons leq; unfold is_propositional.\n  destruct u1 => //.\n  eapply leq_universe_prop_no_prop_sub_type in leq => //.\n  now rewrite leq.\n  intros _.\n  apply leq_universe_sprop_l in leq => //.\n  now rewrite leq orb_true_r.\nQed.\n\nLemma is_propositional_sort_prod x2 x3 :\n  is_propositional (Universe.sort_of_product x2 x3) -> is_propositional x3.\nProof.\n  unfold is_propositional.\n  destruct (Universe.is_prop (Universe.sort_of_product x2 x3)) eqn:eq => //.\n  simpl.\n  intros _.\n  apply is_prop_sort_prod in eq. now rewrite eq.\n  destruct (Universe.is_sprop (Universe.sort_of_product x2 x3)) eqn:eq' => //.\n  apply is_sprop_sort_prod in eq'. now rewrite eq' !orb_true_r.\nQed.\n\nLemma Is_type_lambda (Σ : global_env_ext) Γ na T1 t :\n  wf_ext Σ ->\n  wf_local Σ Γ ->\n  isErasable Σ Γ (tLambda na T1 t) ->\n  ∥isErasable Σ (vass na T1 :: Γ) t∥.\nProof.\n  intros ? ? (T & ? & ?).\n  eapply inversion_Lambda in t0 as (? & ? & ? & ? & e); auto.\n  destruct s as [ | (u & ? & ?)].\n  - eapply invert_cumul_arity_r in e; eauto. destruct e as (? & [] & ?).\n    eapply invert_red_prod in X1 as (? & ? & []); eauto; subst. cbn in H.\n    econstructor. exists x3. econstructor.\n    eapply type_reduction_closed; eauto. econstructor; eauto.\n  - sq. eapply cumul_prop1' in e; eauto.\n    eapply inversion_Prod in e as (? & ? & ? & ? & e) ; auto.\n    eapply ws_cumul_pb_Sort_inv in e.\n    eapply leq_universe_propositional_r in e as H0; cbn; eauto.\n    eexists. split. eassumption. right. eexists. split. eassumption.\n    eapply is_propositional_sort_prod in H0; eauto.\n    eapply type_Lambda in t1; eauto.\n    now apply PCUICValidity.validity in t1.\nQed.\n\nLemma Is_type_red (Σ : global_env_ext) Γ t v:\n  wf Σ ->\n  red Σ Γ t v ->\n  isErasable Σ Γ t ->\n  isErasable Σ Γ v.\nProof.\n  intros ? ? (T & ? & ?).\n  exists T. split.\n  - eapply subject_reduction; eauto.\n  - eauto.\nQed.\n\nLemma Is_type_eval (Σ : global_env_ext) t v:\n  wf Σ ->\n  eval Σ t v ->\n  isErasable Σ [] t ->\n  isErasable Σ [] v.\nProof.\n  intros; eapply Is_type_red. eauto.\n  red in X1. destruct X1 as [T [HT _]].\n  eapply wcbeval_red; eauto. assumption.\nQed.\n\n(* Thanks to the restriction to Prop </= Type, erasability is also closed by expansion\n  on well-typed terms. *)\n\nLemma Is_type_eval_inv (Σ : global_env_ext) t v:\n  wf_ext Σ ->\n  welltyped Σ [] t ->\n  PCUICWcbvEval.eval Σ t v ->\n  isErasable Σ [] v ->\n  ∥ isErasable Σ [] t ∥.\nProof.\n  intros wfΣ [T HT] ev [vt [Ht Hp]].\n  eapply wcbeval_red in ev; eauto.\n  pose proof (subject_reduction _ _ _ _ _ wfΣ.1 HT ev).\n  pose proof (common_typing _ wfΣ Ht X) as [P [Pvt [Pt vP]]].\n  destruct Hp.\n  eapply arity_type_inv in X. 5:eauto. all:eauto.\n  red in X. destruct X as [T' [[red] isA]].\n  eapply type_reduction_closed in HT; eauto.\n  sq. exists T'; intuition auto.\n  sq. exists T. intuition auto. right.\n  destruct s as [u [vtu isp]].\n  exists u; intuition auto.\n  eapply cumul_propositional; eauto. now eapply PCUICValidity.validity in HT.\n  eapply cumul_prop1'; eauto. now eapply PCUICValidity.validity in vP.\nQed.\n\nLemma isType_closed_red_refl {Σ} {wfΣ : wf Σ} {Γ T} :\n  isType Σ Γ T -> Σ ;;; Γ ⊢ T ⇝ T.\nProof.\n  intros [s hs]; eapply wt_closed_red_refl; tea.\nQed.\n\nLemma nIs_conv_to_Arity_isWfArity_elim {Σ} {wfΣ : wf Σ} {Γ x} :\n  ~ Is_conv_to_Arity Σ Γ x ->\n  isWfArity Σ Γ x ->\n  False.\nProof.\n  intros nis [isTy [ctx [s da]]]. apply nis.\n  red. exists (it_mkProd_or_LetIn ctx (tSort s)).\n  split. sq. apply destArity_spec_Some in da.\n  simpl in da. subst x.\n  eapply isType_closed_red_refl; pcuic.\n  now eapply it_mkProd_isArity.\nQed.\n\nDefinition isErasable_Type (Σ : global_env_ext) Γ T :=\n  (Is_conv_to_Arity Σ Γ T +\n    (∑ u : Universe.t, Σ;;; Γ |- T : tSort u × is_propositional u))%type.\n\nLemma isErasable_any_type {Σ} {wfΣ : wf_ext Σ} {Γ t T} :\n  isErasable Σ Γ t ->\n  Σ ;;; Γ |- t : T ->\n  isErasable_Type Σ Γ T.\nProof.\n  intros [T' [Ht Ha]].\n  intros HT.\n  destruct (PCUICPrincipality.common_typing _ wfΣ Ht HT) as [P [le [le' tC]]]. sq.\n  destruct Ha.\n  left. eapply arity_type_inv. 3:exact Ht. all:eauto using typing_wf_local.\n  destruct s as [u [Hu isp]].\n  right.\n  exists u; split; auto.\n  eapply cumul_propositional; eauto. eapply PCUICValidity.validity; eauto.\n  eapply cumul_prop1'; eauto. eapply PCUICValidity.validity; eauto.\nQed.\n\nLemma Is_proof_ty Σ Γ t :\n  wf_ext Σ ->\n  Is_proof Σ Γ t ->\n  forall t' ty,\n  Σ ;;; Γ |- t : ty ->\n  Σ ;;; Γ |- t' : ty ->\n  Is_proof Σ Γ t'.\nProof.\n  intros wfΣ [ty [u [Hty isp]]].\n  intros t' ty' Hty'.\n  epose proof (PCUICPrincipality.common_typing _ wfΣ Hty Hty') as [C [Cty [Cty' Ht'']]].\n  intros Ht'.\n  exists ty', u; intuition auto.\n  eapply PCUICValidity.validity in Hty; eauto.\n  eapply PCUICValidity.validity in Hty'; eauto.\n  eapply PCUICValidity.validity in Ht''; eauto.\n  eapply cumul_prop1' in Cty; eauto.\n  eapply cumul_propositional in Cty'; eauto.\nQed.\n\n\nLemma is_propositional_bottom {Σ Γ T s s'} :\n  wf_ext Σ ->\n  check_univs ->\n  prop_sub_type = false ->\n  Σ ;;; Γ ⊢ T ≤ tSort s ->\n  Σ ;;; Γ ⊢ T ≤ tSort s' ->\n  PCUICCumulProp.eq_univ_prop s s'.\nProof.\n  intros wf cu pst h h'; rewrite /PCUICCumulProp.eq_univ_prop.\n  split. split; eapply PCUICCumulProp.is_prop_bottom; tea.\n  split; eapply PCUICCumulProp.is_sprop_bottom; tea.\nQed.\n\nImport PCUICGlobalEnv PCUICUnivSubst PCUICValidity PCUICCumulProp.\n\nNotation \" Σ ;;; Γ |- t ~~ u \" := (cumul_prop Σ Γ t u)  (at level 50, Γ, t, u at next level) : type_scope.\n\nLemma is_propositional_bottom' {Σ Γ T s s'} :\n  wf_ext Σ ->\n  check_univs ->\n  prop_sub_type = false ->\n  Σ ;;; Γ |- T ~~ tSort s ->\n  Σ ;;; Γ |- T ~~ tSort s' ->\n  PCUICCumulProp.eq_univ_prop s s'.\nProof.\n  intros wf cu pst h h'; rewrite /PCUICCumulProp.eq_univ_prop.\n  pose proof (cumul_prop_trans _ _ _ _ _ _ (cumul_prop_sym _ _ _ _ _ h') h).\n  split. split; intros; eapply PCUICCumulProp.cumul_prop_props; tea. now symmetry.\n  split; intros; eapply PCUICCumulProp.cumul_sprop_props; tea. now symmetry.\nQed.\n\nLemma is_propositional_lower {Σ s u u'} :\n  consistent Σ ->\n  leq_universe Σ s u ->\n  leq_universe Σ s u' ->\n  PCUICCumulProp.eq_univ_prop u u'.\nProof.\n  intros wf leu leu'.\n  unfold eq_univ_prop; split.\n  - split. intros pu. eapply leq_universe_prop_r in leu; tea => //.\n    eapply leq_universe_prop_no_prop_sub_type in leu'; trea => //.\n    intros pu'. eapply leq_universe_prop_r in leu'; tea => //.\n    eapply leq_universe_prop_no_prop_sub_type in leu; tea => //.\n  - split. intros pu. eapply leq_universe_sprop_r in leu; tea => //.\n    eapply leq_universe_sprop_l in leu'; tea => //.\n    intros pu'. eapply leq_universe_sprop_r in leu'; tea => //.\n    eapply leq_universe_sprop_l in leu; tea => //.\nQed.\n\nLemma typing_spine_inj {Σ Γ Δ s args args' u u'} :\n  wf_ext Σ ->\n  check_univs ->\n  prop_sub_type = false ->\n  let T := it_mkProd_or_LetIn Δ (tSort s) in\n  typing_spine Σ Γ T args (tSort u) ->\n  typing_spine Σ Γ T args' (tSort u') ->\n  PCUICCumulProp.eq_univ_prop u u'.\nProof.\n  intros wf cu ips T.\n  move/typing_spine_it_mkProd_or_LetIn_full_inv => su.\n  move/typing_spine_it_mkProd_or_LetIn_full_inv => su'.\n  eapply is_propositional_lower; tea. apply wf.\nQed.\n\nLemma Is_proof_ind Σ Γ t :\n  wf_ext Σ ->\n  Is_proof Σ Γ t ->\n  forall t' ind u args args',\n  Σ ;;; Γ |- t : mkApps (tInd ind u) args ->\n  Σ ;;; Γ |- t' : mkApps (tInd ind u) args' ->\n  Is_proof Σ Γ t'.\nProof.\n  intros wfΣ [ty [u [Hty isp]]].\n  intros t' ind u' args args' Hty' Hty''.\n  epose proof (PCUICPrincipality.common_typing _ wfΣ Hty Hty') as [C [Cty [Cty' Ht'']]].\n  destruct isp.\n  assert (Σ ;;; Γ |- C : tSort u).\n  eapply cumul_prop1'; tea => //. now eapply validity.\n  assert (Σ ;;; Γ |- mkApps (tInd ind u') args : tSort u).\n  eapply cumul_prop2'; tea => //. now eapply validity.\n  eapply inversion_mkApps in X0 as x1. destruct x1 as [? []].\n  eapply inversion_Ind in t1 as [mdecl [idecl [wf [decli ?]]]]; eauto.\n  destruct (validity Hty'') as [u'' tyargs'].\n  eapply inversion_mkApps in X0 as x1. destruct x1 as [? []].\n  eapply invert_type_mkApps_ind in X0 as [sp cum]; eauto.\n  eapply invert_type_mkApps_ind in tyargs' as f; tea. destruct f as [sp' cum']; eauto.\n  do 2 eexists. split => //. tea. instantiate (1 := u'').\n  split => //.\n  rewrite (declared_inductive_type decli) in sp, sp'.\n  rewrite subst_instance_it_mkProd_or_LetIn /= in sp, sp'.\n  eapply typing_spine_inj in sp. 5:exact sp'. all:eauto.\n  destruct sp as [H H0]. apply/orP. rewrite H H0. now apply/orP.\nQed.\n\n\nLemma red_case_isproof {Σ : global_env_ext} {Γ ip p discr discr' brs T} {wfΣ : wf_ext Σ} :\n  PCUICReduction.red Σ Γ (tCase ip p discr brs) (tCase ip p discr' brs) ->\n  Σ ;;; Γ |- tCase ip p discr brs : T ->\n  Is_proof Σ Γ discr -> Is_proof Σ Γ discr'.\nProof.\n  intros hr hc.\n  eapply subject_reduction in hr; tea; eauto.\n  eapply inversion_Case in hc as [mdecl [idecl [isdecl [indices ?]]]]; eauto.\n  eapply inversion_Case in hr as [mdecl' [idecl' [isdecl' [indices' ?]]]]; eauto.\n  pose proof (wfΣ' := wfΣ.1).\n  unshelve eapply declared_inductive_to_gen in isdecl, isdecl'; eauto.\n  destruct (declared_inductive_inj isdecl isdecl'). subst mdecl' idecl'.\n  intros hp.\n  epose proof (Is_proof_ind _ _ _ wfΣ hp).\n  destruct p0 as [[] ?]. destruct p1 as [[] ?].\n  exact (X _ _ _ _ _ scrut_ty scrut_ty0).\nQed.\n\nLemma Is_proof_app {Σ Γ t args ty} {wfΣ : wf_ext Σ} :\n  Is_proof Σ Γ t ->\n  Σ ;;; Γ |- mkApps t args : ty ->\n  Is_proof Σ Γ (mkApps t args).\nProof.\n  intros [ty' [u [Hty [isp pu]]]] Htargs.\n  eapply PCUICValidity.inversion_mkApps in Htargs as [A [Ht sp]].\n  pose proof (PCUICValidity.validity Hty).\n  pose proof (PCUICValidity.validity Ht).\n  epose proof (PCUICPrincipality.common_typing _ wfΣ Hty Ht) as [C [Cty [Cty' Ht'']]].\n  eapply PCUICSpine.typing_spine_strengthen in sp. 3:tea.\n  edestruct (sort_typing_spine _ _ _ u _ _ _ pu sp) as [u' [Hty' isp']].\n  eapply cumul_prop1'. 5:tea. all:eauto.\n  eapply validity; eauto.\n  exists ty, u'; split; auto.\n  eapply PCUICSpine.type_mkApps; tea; eauto.\n  now eapply validity.\nQed.\n\nLemma isErasable_Propositional {Σ : global_env_ext} {Γ ind n u args} :\n  wf_ext Σ ->\n  isErasable Σ Γ (mkApps (tConstruct ind n u) args) -> isPropositional Σ ind true.\nProof.\n  intros wfΣ ise.\n  eapply tConstruct_no_Type in ise; eauto.\n  destruct ise as [T [s [HT [Ts isp]]]].\n  unfold isPropositional.\n  eapply PCUICValidity.inversion_mkApps in HT as (? & ? & ?); auto.\n  eapply inversion_Construct in t as (? & ? & ? & ? & ? & ? & ?); auto.\n  pose proof (wfΣ' := wfΣ.1).\n  unshelve epose proof (d_ := declared_constructor_to_gen d); eauto.\n  unfold lookup_inductive. rewrite (declared_inductive_lookup_gen d_.p1).\n  destruct (on_declared_constructor d).\n  destruct p as [onind oib].\n  rewrite oib.(ind_arity_eq).\n  rewrite /isPropositionalArity !destArity_it_mkProd_or_LetIn /=.\n  eapply PCUICSpine.typing_spine_strengthen in t0; eauto.\n  unfold type_of_constructor in t0.\n  destruct s0 as [indctors [nthcs onc]].\n  rewrite onc.(cstr_eq) in t0.\n  rewrite !subst_instance_it_mkProd_or_LetIn !PCUICLiftSubst.subst_it_mkProd_or_LetIn in t0.\n  len in t0.\n  rewrite subst_cstr_concl_head in t0. destruct d as [decli declc].\n  destruct decli as [declm decli]. now eapply nth_error_Some_length.\n  rewrite -it_mkProd_or_LetIn_app in t0.\n  eapply PCUICElimination.typing_spine_proofs in Ts; eauto.\n  destruct Ts as [_ Hs].\n  specialize (Hs _ _ d c) as [Hs _].\n  specialize (Hs isp). subst s. move: isp.\n  now destruct (ind_sort x1).\n  eapply validity. econstructor; tea.\nQed.\n\nLemma nisErasable_Propositional {Σ : global_env_ext} {Γ ind n u} :\n  wf_ext Σ ->\n  welltyped Σ Γ (tConstruct ind n u) ->\n  (isErasable Σ Γ (tConstruct ind n u) -> False) -> isPropositional Σ ind false.\nProof.\n  intros wfΣ wt ise.\n  destruct wt as [T HT].\n  epose proof HT as HT'.\n  eapply inversion_Construct in HT' as (? & ? & ? & ? & ? & ? & e); auto.\n  pose proof (declared_constructor_valid_ty _ _ _ _ _ _ _ _ wfΣ a d c).\n  pose proof d as [decli ?].\n  destruct (on_declared_constructor d).\n  destruct p as [onind oib].\n  red. unfold lookup_inductive.\n  pose proof (wfΣ' := wfΣ.1).\n  unshelve epose proof (decli_ := declared_inductive_to_gen decli); eauto.\n  rewrite (declared_inductive_lookup_gen decli_).\n  rewrite oib.(ind_arity_eq).\n  rewrite /isPropositionalArity !destArity_it_mkProd_or_LetIn /=.\n  destruct (is_propositional (ind_sort x0)) eqn:isp; auto.\n  elimtype False; eapply ise.\n  red. eexists; intuition eauto. right.\n  unfold type_of_constructor in e, X.\n  destruct s as [indctors [nthcs onc]].\n  rewrite onc.(cstr_eq) in e, X.\n  rewrite !subst_instance_it_mkProd_or_LetIn !PCUICLiftSubst.subst_it_mkProd_or_LetIn in e, X.\n  len in e; len in X.\n  rewrite subst_cstr_concl_head in e, X.\n  destruct decli. eapply nth_error_Some_length in H1; eauto.\n  rewrite -it_mkProd_or_LetIn_app in e, X.\n  exists (subst_instance_univ u (ind_sort x0)).\n  rewrite is_propositional_subst_instance => //.\n  split; auto.\n  eapply cumul_propositional; eauto.\n  rewrite is_propositional_subst_instance => //.\n  eapply PCUICValidity.validity; eauto.\n  destruct X as [cty ty].\n  eapply type_Cumul_alt; eauto.\n  eapply isType_Sort. 2:eauto.\n  destruct (ind_sort x0) => //.\n  eapply PCUICSpine.inversion_it_mkProd_or_LetIn in ty; eauto.\n  epose proof (typing_spine_proofs _ _ [] _ _ _ [] _ _ eq_refl wfΣ ty).\n  forward H0 by constructor. eexists; eauto.\n  simpl. now exists cty. eapply PCUICConversion.ws_cumul_pb_eq_le_gen, PCUICSR.wt_cumul_pb_refl; eauto.\n  destruct H0 as [_ sorts].\n  specialize (sorts _ _ decli c) as [sorts sorts'].\n  forward sorts' by constructor.\n  do 2 constructor.\n  rewrite is_propositional_subst_instance in sorts, sorts' |- *.\n  specialize (sorts' isp). rewrite -sorts'. reflexivity.\nQed.\n\nLemma isPropositional_propositional Σ {wfΣ: wf Σ} (Σ' : E.global_context) ind mdecl idecl mdecl' idecl' :\n  PCUICAst.declared_inductive Σ ind mdecl idecl ->\n  EGlobalEnv.declared_inductive Σ' ind mdecl' idecl' ->\n  erases_mutual_inductive_body mdecl mdecl' ->\n  erases_one_inductive_body idecl idecl' ->\n  forall b, isPropositional Σ ind b -> EGlobalEnv.inductive_isprop_and_pars Σ' ind = Some (b, mdecl.(ind_npars)).\nProof.\n  intros decli decli' [_ indp] [] b.\n  unfold isPropositional, EGlobalEnv.inductive_isprop_and_pars.\n  unfold lookup_inductive.\n  unshelve epose proof (decli_ := declared_inductive_to_gen decli); eauto.\n  rewrite (declared_inductive_lookup_gen decli_).\n  rewrite (EGlobalEnv.declared_inductive_lookup decli') /=\n    /isPropositionalArity.\n  destruct H0 as [_ [_ [_ isP]]]. red in isP.\n  destruct destArity as [[ctx s]|] eqn:da => //.\n  rewrite isP. intros ->. f_equal. f_equal. now rewrite indp.\nQed.\n\nLemma isPropositional_propositional_cstr Σ (Σ' : E.global_context) ind c mdecl idecl cdecl mdecl' idecl' :\n  wf Σ ->\n  PCUICAst.declared_constructor Σ (ind, c) mdecl idecl cdecl ->\n  EGlobalEnv.declared_inductive Σ' ind mdecl' idecl' ->\n  erases_mutual_inductive_body mdecl mdecl' ->\n  erases_one_inductive_body idecl idecl' ->\n  forall b, isPropositional Σ ind b ->\n  EGlobalEnv.constructor_isprop_pars_decl Σ' ind c =\n  Some (b, mdecl.(ind_npars), EAst.mkConstructor cdecl.(cstr_name) (context_assumptions cdecl.(cstr_args))).\nProof.\n  intros wfΣ declc decli' em ei b isp.\n  pose proof declc as [decli'' _].\n  eapply isPropositional_propositional in decli''; tea.\n  move: decli''.\n  rewrite /EGlobalEnv.inductive_isprop_and_pars.\n  unfold EGlobalEnv.constructor_isprop_pars_decl.\n  unfold EGlobalEnv.lookup_constructor.\n  rewrite (EGlobalEnv.declared_inductive_lookup decli') /=.\n  intros [= <- <-].\n  destruct ei. clear H0.\n  eapply Forall2_nth_error_Some in H as [cdecl' []]; tea. 2:apply declc.\n  rewrite H //. f_equal. f_equal.\n  destruct cdecl'. cbn in *. destruct H0. subst. f_equal.\n  destruct (on_declared_constructor declc) as [[] [? []]].\n  now eapply cstr_args_length in o1.\nQed.\n\nLemma eval_tCase {cf : checker_flags} {Σ : global_env_ext}  ci p discr brs res T :\n  wf Σ ->\n  Σ ;;; [] |- tCase ci p discr brs : T ->\n  eval Σ (tCase ci p discr brs) res ->\n  ∑ c u args, PCUICReduction.red Σ [] (tCase ci p discr brs) (tCase ci p ((mkApps (tConstruct ci.(ci_ind) c u) args)) brs).\nProof.\n  intros wf wt H. depind H; try now (cbn in *; congruence).\n  - eapply inversion_Case in wt as (? & ? & ? & ? & cinv & ?); eauto.\n    eexists _, _, _. eapply PCUICReduction.red_case_c. eapply wcbeval_red. 2: eauto. eapply cinv.\n  - eapply inversion_Case in wt as wt'; eauto. destruct wt' as (? & ? & ? & ? & cinv & ?).\n    assert (Hred1 : PCUICReduction.red Σ [] (tCase ip p discr brs) (tCase ip p (mkApps fn args) brs)). {\n      etransitivity. { eapply PCUICReduction.red_case_c. eapply wcbeval_red. 2: eauto. eapply cinv. }\n      econstructor. econstructor.\n      rewrite closed_unfold_cofix_cunfold_eq. eauto.\n      enough (closed (mkApps (tCoFix mfix idx) args)) as Hcl by (rewrite closedn_mkApps in Hcl; solve_all).\n      eapply eval_closed. eauto.\n      2: eauto. eapply @PCUICClosedTyp.subject_closed with (Γ := []); eauto. eapply cinv. eauto.\n    }\n    edestruct IHeval2 as (c & u & args0 & IH); eauto using subject_reduction.\n    exists c, u, args0. etransitivity; eauto.\nQed.\n\nLemma Informative_cofix v ci p brs T (Σ : global_env_ext) :\n   wf_ext Σ ->\n   forall (mdecl : mutual_inductive_body) (idecl : one_inductive_body) mfix idx,\n   declared_inductive Σ.1 ci.(ci_ind) mdecl idecl ->\n   forall (args : list term), Informative Σ ci.(ci_ind) ->\n   Σ ;;; [] |- tCase ci p (mkApps (tCoFix mfix idx) args) brs : T ->\n   Σ ⊢p tCase ci p (mkApps (tCoFix mfix idx) args) brs ▷ v ->\n   Is_proof Σ [] (mkApps (tCoFix mfix idx) args) ->\n   #|ind_ctors idecl| <= 1.\nProof.\n  intros. destruct Σ as [Σ1 Σ2]. cbn in *.\n  eapply eval_tCase in X0 as X2'; eauto. destruct X2' as (? & ? & ? & ?).\n  eapply subject_reduction in X0 as X2'; eauto.\n  eapply inversion_Case in X2' as (? & ? & ? & ? & [] & ?); eauto.\n  eapply inversion_Case in X0 as (? & ? & ? & ? & [] & ?); eauto.\n  pose (X' := X.1). unshelve eapply declared_inductive_to_gen in x8, x4, H; eauto.\n  destruct (declared_inductive_inj x8 x4); subst.\n  destruct (declared_inductive_inj x8 H); subst.\n  eapply H0; eauto. apply declared_inductive_from_gen; eauto.\n  reflexivity.\n  eapply Is_proof_ind; tea.\nQed.\n\nLemma isErasable_unfold_cofix {Σ : global_env_ext} {Γ mfix idx} {wfΣ : wf Σ} decl :\n  isErasable Σ Γ (tCoFix mfix idx) ->\n  nth_error mfix idx = Some decl ->\n  isErasable Σ Γ (subst0 (cofix_subst mfix) (dbody decl)).\nProof.\n  intros [Tty []] hred.\n  exists Tty. split => //.\n  eapply type_tCoFix_inv in t as t''; eauto.\n  destruct t'' as [decl' [[[] h'] h'']].\n  rewrite e in hred. noconf hred.\n  eapply type_ws_cumul_pb; tea.\n  now eapply validity.\nQed.\n\nLemma isErasable_red {Σ : global_env_ext} {Γ T U} {wfΣ : wf Σ} :\n  isErasable Σ Γ T -> PCUICReduction.red Σ Γ T U -> isErasable Σ Γ U.\nProof.\n  intros [Tty []] hred.\n  exists Tty. split => //. eapply subject_reduction; tea.\nQed.\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/erasure/theories/EArities.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.21868593800993344}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import fastpile.\nRequire Import spec_stdlib.\nGlobal Open Scope funspec_scope.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition tpile := Tstruct _pile noattr.\n\nDefinition sumlist : list Z -> Z := List.fold_right Z.add 0.\n\nDefinition pilerep (sigma: list Z) (p: val) : mpred :=\n EX s:Z, !! (0 <= s <= Int.max_signed /\\\n   Forall (Z.le 0) sigma /\\\n  (0 <= sumlist sigma <= Int.max_signed -> s=sumlist sigma))\n   &&  data_at Ews tpile (Vint (Int.repr s)) p.\n\nDefinition pile_freeable (p: val) : mpred :=\n            malloc_token Ews tpile p.\n\nLemma pilerep_local_facts:\n  forall sigma p,\n   pilerep sigma p |-- !! (isptr p /\\ Forall (Z.le 0) sigma).\nProof.\nintros.\nunfold pilerep.\nIntros q.\nentailer!.\nQed.\n\nHint Resolve pilerep_local_facts : saturate_local.\n\nLemma pilerep_valid_pointer:\n  forall sigma p,\n   pilerep sigma p |-- valid_pointer p.\nProof. \n intros.\n unfold pilerep. Intros x.\n entailer!; auto with valid_pointer.\nQed.\nHint Resolve pilerep_valid_pointer : valid_pointer.\n\nLocal Open Scope assert.\n\nDefinition surely_malloc_spec :=\n  DECLARE _surely_malloc\n   WITH t:type, gv: globals\n   PRE [ tuint ]\n       PROP (0 <= sizeof t <= Int.max_unsigned;\n                complete_legal_cosu_type t = true;\n                natural_aligned natural_alignment t = true)\n       PARAMS (Vint (Int.repr (sizeof t))) GLOBALS (gv)\n       SEP (mem_mgr gv)\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (mem_mgr gv; malloc_token Ews t p * data_at_ Ews t p).\n\nDefinition Pile_new_spec :=\n DECLARE _Pile_new\n WITH gv: globals\n PRE [ ] PROP() PARAMS () GLOBALS (gv) SEP(mem_mgr gv)\n POST[ tptr tpile ]\n   EX p: val,\n     PROP() LOCAL(temp ret_temp p)\n     SEP(pilerep nil p; pile_freeable p; mem_mgr gv).\n\nDefinition Pile_add_spec :=\n DECLARE _Pile_add\n WITH p: val, n: Z, sigma: list Z, gv: globals\n PRE [ tptr tpile, tint  ]\n    PROP(0 <= n <= Int.max_signed)\n    PARAMS (p; Vint (Int.repr n)) GLOBALS (gv)\n    SEP(pilerep sigma p; mem_mgr gv)\n POST[ tvoid ]\n    PROP() LOCAL()\n    SEP(pilerep (n::sigma) p; mem_mgr gv).\n\nDefinition Pile_count_spec :=\n DECLARE _Pile_count\n WITH p: val, sigma: list Z\n PRE [ tptr tpile ]\n    PROP(0 <= sumlist sigma <= Int.max_signed)\n    PARAMS (p) GLOBALS ()\n    SEP(pilerep sigma p)\n POST[ tint ]\n      PROP() \n      LOCAL(temp ret_temp (Vint (Int.repr (sumlist sigma))))\n      SEP(pilerep sigma p).\n\nDefinition Pile_free_spec :=\n DECLARE _Pile_free\n WITH p: val, sigma: list Z, gv: globals\n PRE [ tptr tpile  ]\n    PROP()\n    PARAMS (p) GLOBALS (gv)\n    SEP(pilerep sigma p; pile_freeable p; mem_mgr gv)\n POST[ tvoid ]\n      PROP() LOCAL() SEP(mem_mgr gv).\n\nDefinition ispecs := [surely_malloc_spec].\nDefinition specs := [Pile_new_spec; Pile_add_spec; Pile_count_spec; Pile_free_spec].\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/pile/fast/spec_fastpile.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.2186859380099334}}
{"text": "(*\n * Copyright (c) 2020-21 BedRock Systems, Inc.\n * This software is distributed under the terms of the BedRock Open-Source License.\n * See the LICENSE-BedRock file in the repository root for details.\n *)\nFrom iris.proofmode Require Import proofmode.\nFrom bedrock.lang.bi Require Import fractional.\n\nFrom bedrock.lang.cpp Require Import\n  bi.cfractional\n  semantics ast logic.pred logic.path_pred.\n\nExport bedrock.lang.cpp.logic.pred.\n(* ^^ Should this be exported? this file is supposed to provide wrappers\n   so that clients do not work directly with [pred.v] *)\nExport bedrock.lang.cpp.algebra.cfrac.\n\n#[local] Set Printing Coercions.\n\nImplicit Types (σ resolve : genv) (p : ptr) (o : offset).\n\nSection defs.\n  Context `{Σ : cpp_logic}.\n\n  (** object identity *)\n  Definition identityR {σ : genv} (cls : globname) (mdc : list globname)\n             (q : cQp.t) : Rep :=\n    as_Rep (identity cls mdc q).\n\n  Definition validR_def : Rep := as_Rep valid_ptr.\n  Definition validR_aux : seal (@validR_def). Proof. by eexists. Qed.\n  Definition validR := validR_aux.(unseal).\n  Definition validR_eq : @validR = _ := validR_aux.(seal_eq).\n\n  Definition svalidR_def : Rep := as_Rep strict_valid_ptr.\n  Definition svalidR_aux : seal (@svalidR_def). Proof. by eexists. Qed.\n  Definition svalidR := svalidR_aux.(unseal).\n  Definition svalidR_eq : @svalidR = _ := svalidR_aux.(seal_eq).\n\n  Definition type_ptrR_def σ (t : type) : Rep := as_Rep (@type_ptr _ _ σ t).\n  Definition type_ptrR_aux : seal (@type_ptrR_def). Proof. by eexists. Qed.\n  Definition type_ptrR := type_ptrR_aux.(unseal).\n  Definition type_ptrR_eq : @type_ptrR = _ := type_ptrR_aux.(seal_eq).\n\nEnd defs.\n\nArguments type_ptrR {_ Σ σ} _.\n\nSection with_cpp.\n  Context `{Σ : cpp_logic}.\n\n  (** [varargsR ts_ps] is the ownership of a group of variadic arguments.\n      The [type] is the type of the argument and the [ptr] is the location\n      of the argument. *)\n  Parameter varargsR : list (type * ptr) -> Rep.\n\n  (** [primR ty q v]: the argument pointer points to an initialized value [v] of C++ type [ty].\n   *\n   * NOTE [ty] *must* be a primitive type.\n   *)\n  Definition primR_def {resolve:genv} (ty : type) (q : cQp.t) (v : val) : Rep :=\n    as_Rep (fun p : ptr => tptsto ty q p v **\n             [| not(exists raw, v = Vraw raw) |] **\n             [| has_type v (drop_qualifiers ty) |]).\n  Definition primR_aux : seal (@primR_def). Proof. by eexists. Qed.\n  Definition primR := primR_aux.(unseal).\n  Definition primR_eq : @primR = _ := primR_aux.(seal_eq).\n  #[global] Arguments primR {resolve} ty q v : rename.\n\n  #[global] Instance primR_proper :\n    Proper (genv_eq ==> (=) ==> (=) ==> (=) ==> (⊣⊢)) (@primR).\n  Proof.\n    intros σ1 σ2 Hσ ??-> ??-> ??->.\n    rewrite primR_eq/primR_def. by setoid_rewrite Hσ.\n  Qed.\n  #[global] Instance primR_mono :\n    Proper (genv_leq ==> (=) ==> (=) ==> (=) ==> (⊢)) (@primR).\n  Proof.\n    intros σ1 σ2 Hσ ??-> ??-> ??->.\n    rewrite primR_eq/primR_def. by setoid_rewrite Hσ.\n  Qed.\n\n  #[global] Instance primR_timeless resolve ty q v\n    : Timeless (primR ty q v).\n  Proof. rewrite primR_eq. apply _. Qed.\n\n\n  #[global] Instance primR_cfractional resolve ty :\n    CFractional1 (primR ty).\n  Proof. rewrite primR_eq. apply _. Qed.\n  #[global] Instance primR_as_cfractional resolve ty :\n    AsCFractional1 (primR ty).\n  Proof. solve_as_cfrac. Qed.\n\n  #[global] Instance primR_observe_cfrac_valid resolve ty :\n    CFracValid1 (primR ty).\n  Proof. rewrite primR_eq. solve_cfrac_valid. Qed.\n\n  Section TEST.\n    Context {σ : genv} (p : ptr).\n\n    Goal\n        p |-> primR Tint (cQp.m (1/2)) 0\n        |-- p |-> primR Tint (cQp.m (1/2)) 0 -* p |-> primR Tint (cQp.m 1) 0.\n    Proof.\n      iIntros \"H1 H2\".\n      iCombine \"H1 H2\" as \"$\".\n    Abort.\n\n    Goal\n        p |-> primR Tint (cQp.c 1) 0 |-- p |-> primR Tint (cQp.c (1/2)) 0 ** p |-> primR Tint (cQp.c (1/2)) 0.\n    Proof.\n      iIntros \"H\".\n      iDestruct \"H\" as \"[H1 H2]\".\n    Abort.\n\n    Goal p |-> primR Tint (cQp.c 1) 1 |-- True.\n    Proof.\n      iIntros \"H\".\n      iDestruct (observe [| 1 ≤ 1 |]%Qp with \"H\") as %? (* ; [] << FAILS *).\n    Abort.\n  End TEST.\n\n  #[global] Instance primR_observe_agree resolve ty q1 q2 v1 v2 :\n    Observe2 [| v1 = v2 |]\n      (primR ty q1 v1)\n      (primR ty q2 v2).\n  Proof.\n    rewrite primR_eq/primR_def; apply: as_Rep_only_provable_observe_2=> p.\n    iIntros \"(Htptsto1 & %Hnotraw1 & %Hhas_type1)\n             (Htptsto2 & %Hnotraw2 & %Hhas_type2)\".\n    iApply (observe_2 with \"Htptsto1 Htptsto2\").\n    iApply observe_2_derive_only_provable => Hvs.\n    induction Hvs; subst; auto; exfalso;\n        [apply Hnotraw1 | apply Hnotraw2];\n        eauto.\n  Qed.\n\n  (* Typical [f] are [Vint], [Vn] etc; this gives agreement for [u64R] etc. *)\n  #[global] Instance primR_observe_agree_constr resolve ty q1 q2 {A} f `{!Inj eq eq f} (v1 v2 : A) :\n    Observe2 [| v1 = v2 |]\n      (primR ty q1 (f v1))\n      (primR ty q2 (f v2)).\n  Proof. apply (observe2_inj f), _. Qed.\n\n  #[global] Instance primR_observe_has_type resolve ty q v :\n    Observe [| has_type v (drop_qualifiers ty) |] (primR ty q v).\n  Proof. rewrite primR_eq. apply _. Qed.\n\n  Lemma primR_has_type {σ} ty q v :\n    primR (resolve:=σ) ty q v |--\n    primR (resolve:=σ) ty q v ** [| has_type v (drop_qualifiers ty) |].\n  Proof. apply: observe_elim. Qed.\n\n  (**\n     [uninitR ty q]: the argument pointer points to an uninitialized value [Vundef] of C++ type [ty].\n     Unlike [primR], does not imply [has_type].\n\n     NOTE the [ty] argument *must* be a primitive type.\n\n     TODO is it possible to generalize this to support aggregate types? structures seem easy enough\n          but unions seem more difficult, possibly we can achieve that through the use of disjunction?\n   *)\n  Definition uninitR_def {resolve:genv} (ty : type) (q : cQp.t) : Rep :=\n    as_Rep (fun addr => @tptsto _ _ resolve ty q addr Vundef).\n  Definition uninitR_aux : seal (@uninitR_def). Proof. by eexists. Qed.\n  Definition uninitR := uninitR_aux.(unseal).\n  Definition uninitR_eq : @uninitR = _ := uninitR_aux.(seal_eq).\n  #[global] Arguments uninitR {resolve} ty q : rename.\n\n  #[global] Instance uninitR_proper\n    : Proper (genv_eq ==> (=) ==> (=) ==> (≡)) (@uninitR).\n  Proof.\n    intros σ1 σ2 Hσ ??-> ??->     .\n    rewrite uninitR_eq/uninitR_def. by setoid_rewrite Hσ.\n  Qed.\n  #[global] Instance uninitR_mono\n    : Proper (genv_leq ==> (=) ==> (=) ==> (⊢)) (@uninitR).\n  Proof.\n    intros σ1 σ2 Hσ ??-> ??->     .\n    rewrite uninitR_eq/uninitR_def. by setoid_rewrite Hσ.\n  Qed.\n\n  #[global] Instance uninitR_timeless resolve ty q\n    : Timeless (uninitR ty q).\n  Proof. rewrite uninitR_eq. apply _. Qed.\n\n  #[global] Instance uninitR_cfractional resolve ty :\n    CFractional (uninitR ty).\n  Proof. rewrite uninitR_eq. apply _. Qed.\n  #[global] Instance unintR_as_fractional resolve ty :\n    AsCFractional0 (uninitR ty).\n  Proof. solve_as_cfrac. Qed.\n\n  #[global] Instance uninitR_observe_frac_valid resolve ty :\n    CFracValid0 (uninitR ty).\n  Proof. rewrite uninitR_eq. solve_cfrac_valid. Qed.\n\n  Lemma test:\n    forall σ ty v v',\n      v' = Vundef ->\n      val_related σ ty v v' ->\n      v = Vundef.\n  Proof.\n    intros * Hv' Hval_related; induction Hval_related;\n      try (by inversion Hv'); auto.\n  Qed.\n\n  (** This seems odd, but it's relevant to the (former) proof that [anyR] is\n  fractional; currently unused. *)\n  Lemma primR_uninitR {resolve} ty q1 q2 v :\n    primR ty q1 v |--\n    uninitR ty q2 -*\n    primR ty (q1 ⋅ q2) Vundef.\n  Proof.\n    rewrite primR_eq/primR_def uninitR_eq/uninitR_def. constructor=>p /=.\n    rewrite monPred_at_wand. iIntros \"[T1 [%Hnotraw %Hty]]\" (? <-%ptr_rel_elim) \"/= T2\".\n    iDestruct (observe_2 [| val_related resolve ty v Vundef |] with \"T1 T2\") as \"%Hrelated\".\n    assert (v = Vundef)\n      by (remember Vundef as v'; induction Hrelated;\n          try (by inversion Heqv'); auto); subst.\n    iCombine \"T1 T2\" as \"T\"; by iFrame \"∗%\".\n  Qed.\n\n  (** [anyR] The argument pointers points to a value of C++ type [ty] that might be\n      uninitialized. *)\n  Parameter anyR : ∀ {resolve} (ty : type) (q : cQp.t), Rep.\n  #[global] Arguments anyR {resolve} ty q : rename.\n  #[global] Declare Instance anyR_timeless : ∀ resolve ty q, Timeless (anyR ty q).\n  #[global] Declare Instance anyR_cfractional : ∀ resolve ty, CFractional (anyR ty).\n  #[global] Declare Instance anyR_observe_frac_valid resolve ty : CFracValid0 (anyR ty).\n\n  Axiom primR_anyR : ∀ resolve t q v, primR t q v |-- anyR t q.\n  Axiom uninitR_anyR : ∀ resolve t q, uninitR t q |-- anyR t q.\n  Axiom tptsto_raw_anyR : forall resolve p q r, tptsto Tu8 q p (Vraw r) |-- p |-> anyR Tu8 q.\n  #[global] Declare Instance anyR_type_ptr_observe σ ty q : Observe (type_ptrR ty) (anyR ty q).\n\n  #[global] Instance anyR_as_fractional resolve ty : AsCFractional0 (anyR ty).\n  Proof. solve_as_cfrac. Qed.\n\n  Axiom _at_anyR_ptr_congP_transport : forall {σ} p p' ty q,\n    ptr_congP σ p p' ** type_ptr ty p' |-- p |-> anyR ty q -* p' |-> anyR ty q.\nEnd with_cpp.\n\n#[global] Typeclasses Opaque primR.\n#[global] Opaque primR.\n\nSection with_cpp.\n  Context `{Σ : cpp_logic} {σ : genv}.\n\n  (********************* DERIVED CONCEPTS ****************************)\n  #[global] Instance validR_persistent : Persistent validR.\n  Proof. rewrite validR_eq; refine _. Qed.\n  #[global] Instance validR_timeless : Timeless validR.\n  Proof. rewrite validR_eq; refine _. Qed.\n  #[global] Instance validR_affine : Affine validR.\n  Proof. rewrite validR_eq; refine _. Qed.\n\n  Import heap_notations.INTERNAL.\n\n  Lemma monPred_at_validR p : validR p -|- valid_ptr p.\n  Proof. by rewrite validR_eq. Qed.\n  Lemma _at_validR (p : ptr) : _at p validR -|- valid_ptr p.\n  Proof. by rewrite validR_eq _at_eq /_at_def. Qed.\n\n  #[global] Instance svalidR_persistent : Persistent svalidR.\n  Proof. rewrite svalidR_eq; refine _. Qed.\n  #[global] Instance svalidR_timeless : Timeless svalidR.\n  Proof. rewrite svalidR_eq; refine _. Qed.\n  #[global] Instance svalidR_affine : Affine svalidR.\n  Proof. rewrite svalidR_eq; refine _. Qed.\n\n  Lemma monPred_at_svalidR p : svalidR p -|- strict_valid_ptr p.\n  Proof. by rewrite svalidR_eq. Qed.\n  Lemma _at_svalidR (p : ptr) : _at p svalidR -|- strict_valid_ptr p.\n  Proof. by rewrite svalidR_eq _at_eq. Qed.\n\n  #[global] Instance type_ptrR_persistent t : Persistent (type_ptrR t).\n  Proof. rewrite type_ptrR_eq; refine _. Qed.\n  #[global] Instance type_ptrR_timeless t : Timeless (type_ptrR t).\n  Proof. rewrite type_ptrR_eq; refine _. Qed.\n  #[global] Instance type_ptrR_affine t : Affine (type_ptrR t).\n  Proof. rewrite type_ptrR_eq; refine _. Qed.\n\n  Lemma monPred_at_type_ptrR ty p : type_ptrR ty p -|- type_ptr ty p.\n  Proof. by rewrite type_ptrR_eq. Qed.\n  Lemma _at_type_ptrR (p : ptr) ty : _at p (type_ptrR ty) -|- type_ptr ty p.\n  Proof. by rewrite type_ptrR_eq _at_eq. Qed.\n\n\n\n  Lemma svalidR_validR : svalidR |-- validR.\n  Proof.\n    rewrite validR_eq/validR_def svalidR_eq/svalidR_def.\n    constructor =>p /=. by apply strict_valid_valid.\n  Qed.\n  Lemma type_ptrR_svalidR ty : type_ptrR ty |-- svalidR.\n  Proof.\n    rewrite type_ptrR_eq/type_ptrR_def svalidR_eq/svalidR_def.\n    constructor =>p /=. by apply type_ptr_strict_valid.\n  Qed.\n  Lemma type_ptrR_validR ty : type_ptrR ty |-- validR.\n  Proof. by rewrite type_ptrR_svalidR svalidR_validR. Qed.\n\n  #[global] Instance svalidR_validR_observe : Observe validR svalidR.\n  Proof. rewrite svalidR_validR. red; iIntros \"#$\". Qed.\n  #[global] Instance type_ptrR_svalidR_observe t : Observe svalidR (type_ptrR t).\n  Proof. rewrite type_ptrR_svalidR; red; iIntros \"#$\". Qed.\n\n  Definition nullR_def : Rep :=\n    as_Rep (fun addr => [| addr = nullptr |]).\n  Definition nullR_aux : seal (@nullR_def). Proof. by eexists. Qed.\n  Definition nullR := nullR_aux.(unseal).\n  Definition nullR_eq : @nullR = _ := nullR_aux.(seal_eq).\n\n  #[global] Hint Opaque nullR : typeclass_instances.\n\n  #[global] Instance nullR_persistent : Persistent nullR.\n  Proof. rewrite nullR_eq. apply _. Qed.\n  #[global] Instance nullR_affine : Affine nullR.\n  Proof. rewrite nullR_eq. apply _. Qed.\n  #[global] Instance nullR_timeless : Timeless nullR.\n  Proof. rewrite nullR_eq. apply _. Qed.\n  #[global] Instance nullR_fractional : Fractional (λ _, nullR).\n  Proof. apply _. Qed.\n  #[global] Instance nullR_as_fractional q : AsFractional nullR (λ _, nullR) q.\n  Proof. exact: Build_AsFractional. Qed.\n  #[global] Instance nullR_cfractional : CFractional (λ _, nullR).\n  Proof. apply _. Qed.\n  #[global] Instance nullR_as_cfractional q : AsCFractional nullR (λ _, nullR) q.\n  Proof. solve_as_cfrac. Qed.\n\n  Definition nonnullR_def : Rep :=\n    as_Rep (fun addr => [| addr <> nullptr |]).\n  Definition nonnullR_aux : seal (@nonnullR_def). Proof. by eexists. Qed.\n  Definition nonnullR := nonnullR_aux.(unseal).\n  Definition nonnullR_eq : @nonnullR = _ := nonnullR_aux.(seal_eq).\n\n  #[global] Hint Opaque nonnullR : typeclass_instances.\n\n  #[global] Instance nonnullR_persistent : Persistent nonnullR.\n  Proof. rewrite nonnullR_eq. apply _. Qed.\n  #[global] Instance nonnullR_affine : Affine nonnullR.\n  Proof. rewrite nonnullR_eq. apply _. Qed.\n  #[global] Instance nonnullR_timeless : Timeless nonnullR.\n  Proof. rewrite nonnullR_eq. apply _. Qed.\n\n  Definition alignedR_def (al : N) : Rep := as_Rep (λ p, [| aligned_ptr al p |]).\n  Definition alignedR_aux : seal (@alignedR_def). Proof. by eexists. Qed.\n  Definition alignedR := alignedR_aux.(unseal).\n  Definition alignedR_eq : @alignedR = _ := alignedR_aux.(seal_eq).\n  #[global] Instance alignedR_persistent {al} : Persistent (alignedR al).\n  Proof. rewrite alignedR_eq. apply _. Qed.\n  #[global] Instance alignedR_affine {al} : Affine (alignedR al).\n  Proof. rewrite alignedR_eq. apply _. Qed.\n  #[global] Instance alignedR_timeless {al} : Timeless (alignedR al).\n  Proof. rewrite alignedR_eq. apply _. Qed.\n\n  #[global] Instance alignedR_divide_mono :\n    Proper (flip N.divide ==> bi_entails) alignedR.\n  Proof.\n    intros m n ?.\n    rewrite alignedR_eq /alignedR_def. constructor=>p/=. iIntros \"!%\".\n    exact: aligned_ptr_divide_weaken.\n  Qed.\n\n  #[global] Instance alignedR_divide_flip_mono :\n    Proper (N.divide ==> flip bi_entails) alignedR.\n  Proof. solve_proper. Qed.\n\n  Lemma alignedR_divide_weaken m n :\n    (n | m)%N ->\n    alignedR m ⊢ alignedR n.\n  Proof. by move->. Qed.\n\n  Lemma null_nonnull (R : Rep) : nullR |-- nonnullR -* R.\n  Proof.\n    rewrite nullR_eq /nullR_def nonnullR_eq /nonnullR_def.\n    constructor=>p /=. rewrite monPred_at_wand/=.\n    by iIntros \"->\" (? <-%ptr_rel_elim) \"%\".\n  Qed.\n\n  Lemma null_validR : nullR |-- validR.\n  Proof.\n    rewrite nullR_eq /nullR_def validR_eq /validR_def.\n    constructor => p /=. iIntros \"->\". iApply valid_ptr_nullptr.\n  Qed.\n\n\n  (** [blockR sz q] represents [q] ownership of a contiguous chunk of\n      [sz] bytes without any C++ structure on top of it. *)\n  Definition blockR_def {σ} sz (q : cQp.t) : Rep :=\n    _offsetR (o_sub σ Tu8 (Z.of_N sz)) validR **\n    (* ^ Encodes valid_ptr (this .[ Tu8 ! sz]). This is\n    necessary to get [l |-> blockR n -|- l |-> blockR n ** l .[ Tu8 ! m] |-> blockR 0]. *)\n    [∗list] i ∈ seq 0 (N.to_nat sz),\n      _offsetR (o_sub σ Tu8 (Z.of_nat i)) (anyR (resolve:=σ) Tu8 q).\n  Definition blockR_aux : seal (@blockR_def). Proof. by eexists. Qed.\n  Definition blockR := blockR_aux.(unseal).\n  Definition blockR_eq : @blockR = _ := blockR_aux.(seal_eq).\n  #[global] Arguments blockR {_} _%N _%Qp.\n\n  #[global] Instance blockR_timeless {resolve : genv} sz q :\n    Timeless (blockR sz q).\n  Proof. rewrite blockR_eq /blockR_def. unfold_at. apply _. Qed.\n  #[global] Instance blockR_cfractional resolve sz :\n    CFractional (blockR sz).\n  Proof. rewrite blockR_eq. apply _. Qed.\n  #[global] Instance blockR_as_cfractional {resolve : genv} sz :\n    AsCFractional0 (blockR sz).\n  Proof. solve_as_cfrac. Qed.\n\n  #[global] Instance blockR_observe_frac_valid {resolve : genv} sz :\n    TCLt (0 ?= sz)%N ->\n    CFracValid0 (blockR sz).\n  Proof.\n    rewrite TCLt_N blockR_eq/blockR_def. intros.\n    destruct (N.to_nat sz) eqn:?; [ lia | ] => /=.\n    solve_cfrac_valid.\n  Qed.\n\n  (* [tblockR ty] is a [blockR] that is the size of [ty] and properly aligned.\n   * it is a convenient short-hand since it happens frequently, but there is nothing\n   * special about it.\n   *)\n  Definition tblockR {σ} (ty : type) (q : cQp.t) : Rep :=\n    match size_of σ ty , align_of ty with\n    | Some sz , Some al => blockR (σ:=σ) sz q ** alignedR al\n    | _ , _  => False\n    end.\n\n  #[global] Instance tblockR_timeless ty q :\n    Timeless (tblockR ty q).\n  Proof. rewrite/tblockR. case_match; apply _. Qed.\n  #[global] Instance tblockR_cfractional ty :\n    CFractional (tblockR ty).\n  Proof.\n    rewrite/tblockR. do 2!(case_match; last by apply _).\n    apply _.\n  Qed.\n  #[global] Instance tblockR_as_cfractional ty : AsCFractional0 (tblockR ty).\n  Proof. solve_as_cfrac. Qed.\n  #[global] Instance tblockR_observe_frac_valid ty n :\n    SizeOf ty n -> TCLt (0 ?= n)%N ->\n    CFracValid0 (tblockR ty).\n  Proof.\n    rewrite/tblockR=>-> ?. case_match; solve_cfrac_valid.\n  Qed.\n\n  #[global] Instance identityR_timeless cls mdc q : Timeless (identityR cls mdc q) := _.\n  #[global] Instance identityR_cfractional cls mdc : CFractional (identityR cls mdc) := _.\n  #[global] Instance identityR_as_frac cls mdc :\n    AsCFractional0 (identityR cls mdc).\n  Proof. solve_as_cfrac. Qed.\n\n  #[global] Instance identityR_strict_valid cls mdc q : Observe svalidR (identityR cls mdc q).\n  Proof.\n    red. eapply Rep_entails_at. intros.\n    rewrite _at_as_Rep _at_pers svalidR_eq _at_as_Rep.\n    apply identity_strict_valid.\n  Qed.\n  #[global] Instance identity_not_null p cls path q : Observe [| p <> nullptr |] (p |-> identityR cls path q).\n  Proof.\n    red.\n    iIntros \"X\".\n    destruct (decide (p = nullptr)); eauto.\n    iDestruct (observe (p |-> svalidR) with \"X\") as \"#SV\".\n    subst; rewrite _at_svalidR not_strictly_valid_ptr_nullptr.\n    iDestruct \"SV\" as \"[]\".\n  Qed.\n\n  (** Observing [type_ptr] *)\n  #[global]\n  Instance primR_type_ptr_observe ty q v : Observe (type_ptrR ty) (primR ty q v).\n  Proof.\n    red. rewrite primR_eq/primR_def.\n    apply Rep_entails_at => p. rewrite _at_as_Rep _at_pers _at_type_ptrR.\n    apply: observe.\n  Qed.\n  #[global]\n  Instance uninitR_type_ptr_observe ty q : Observe (type_ptrR ty) (uninitR ty q).\n  Proof.\n    red. rewrite uninitR_eq/uninitR_def.\n    apply Rep_entails_at => p. rewrite _at_as_Rep _at_pers _at_type_ptrR.\n    apply: observe.\n  Qed.\n\n  (** Observing [valid_ptr] *)\n  #[global]\n  Instance primR_valid_observe {ty q v} : Observe validR (primR ty q v).\n  Proof. rewrite -svalidR_validR -type_ptrR_svalidR; refine _. Qed.\n  #[global]\n  Instance anyR_valid_observe {ty q} : Observe validR (anyR ty q).\n  Proof. rewrite -svalidR_validR -type_ptrR_svalidR; refine _. Qed.\n  #[global]\n  Instance uninitR_valid_observe {ty q} : Observe validR (uninitR ty q).\n  Proof. rewrite -svalidR_validR -type_ptrR_svalidR; refine _. Qed.\n\n  #[global]\n  Instance observe_type_ptr_pointsto (p : ptr) ty (R : Rep) :\n    Observe (type_ptrR ty) R -> Observe (type_ptr ty p) (_at p R).\n  Proof. rewrite -_at_type_ptrR. apply _at_observe. Qed.\n\n  #[global] Instance type_ptrR_size_observe ty :\n    Observe [| is_Some (size_of σ ty) |] (type_ptrR ty).\n  Proof.\n    apply monPred_observe_only_provable => p.\n    rewrite monPred_at_type_ptrR. apply _.\n  Qed.\n\n  #[global]\n  Instance null_valid_observe : Observe validR nullR.\n  Proof. rewrite -null_validR. refine _. Qed.\n\n  Lemma off_validR o\n    (Hv : ∀ p, valid_ptr (p ,, o) |-- valid_ptr p) :\n    _offsetR o validR |-- validR.\n  Proof.\n    apply Rep_entails_at => p. by rewrite _at_offsetR !_at_validR.\n  Qed.\n\n  Lemma _field_validR f : _offsetR (_field f) validR |-- validR.\n  Proof. apply off_validR => p. apply _valid_ptr_field. Qed.\n\n  (** Observation of [nonnullR] *)\n  #[global]\n  Instance primR_nonnull_observe {ty q v} :\n    Observe nonnullR (primR ty q v).\n  Proof.\n    rewrite nonnullR_eq primR_eq. apply monPred_observe=>p /=. apply _.\n  Qed.\n  #[global]\n  Instance uninitR_nonnull_observe {ty q} :\n    Observe nonnullR (uninitR ty q).\n  Proof.\n    rewrite nonnullR_eq uninitR_eq. apply monPred_observe=>p /=. apply _.\n  Qed.\n  Axiom anyR_nonnull_observe : ∀ {ty q}, Observe nonnullR (anyR ty q).\n  #[global] Existing Instance anyR_nonnull_observe.\n\n  #[global] Instance blockR_nonnull n q :\n    TCLt (0 ?= n)%N -> Observe nonnullR (blockR n q).\n  Proof.\n    rewrite TCLt_N blockR_eq/blockR_def.\n    destruct (N.to_nat n) eqn:Hn; [ lia | ] => {Hn} /=.\n    rewrite o_sub_0 ?_offsetR_id; [ | by eauto].\n    apply _.\n  Qed.\n  #[global] Instance blockR_valid_ptr sz q : Observe validR (blockR sz q).\n  Proof.\n    rewrite blockR_eq/blockR_def.\n    destruct sz.\n    { iIntros \"[#A _]\".\n      rewrite o_sub_0; last by econstructor.\n      rewrite _offsetR_id. eauto. }\n    { iIntros \"[_ X]\".\n      simpl. destruct (Pos.to_nat p) eqn:?; first lia.\n      simpl. iDestruct \"X\" as \"[X _]\".\n      rewrite o_sub_0; last by econstructor. rewrite _offsetR_id.\n      iApply (observe with \"X\"). }\n  Qed.\n\n  #[global] Instance tblockR_nonnull n ty q :\n    SizeOf ty n -> TCLt (0 ?= n)%N ->\n    Observe nonnullR (tblockR ty q).\n  Proof.\n    intros Heq ?. rewrite/tblockR {}Heq.\n    case_match; by apply _.\n  Qed.\n\n  #[global] Instance tblockR_valid_ptr ty q : Observe validR (tblockR ty q).\n  Proof.\n    rewrite /tblockR. case_match; refine _.\n    case_match; refine _.\n  Qed.\n\n  #[global] Instance type_ptrR_observe_nonnull ty :\n    Observe nonnullR (type_ptrR ty).\n  Proof.\n    apply monPred_observe=>p /=.\n    rewrite monPred_at_type_ptrR nonnullR_eq /=. refine _.\n  Qed.\nEnd with_cpp.\n\n#[global] Typeclasses Opaque identityR.\n#[global] Typeclasses Opaque type_ptrR validR svalidR alignedR.\n\n#[deprecated(note=\"since 2022-04-07; use `nonnullR` instead\")]\nNotation is_nonnull := nonnullR (only parsing).\n#[deprecated(note=\"since 2022-04-07; use `nonnullR_eq` instead\")]\nNotation is_nonnull_eq := nonnullR_eq (only parsing).\n#[deprecated(note=\"since 2022-04-07; use `nonnullR_def` instead\")]\nNotation is_nonnull_def := nonnullR_def (only parsing).\n\n#[deprecated(note=\"since 2022-04-07; use `nullR` instead\")]\nNotation is_null := nullR (only parsing).\n#[deprecated(note=\"since 2022-04-07; use `nullR_eq` instead\")]\nNotation is_null_eq := nullR_eq (only parsing).\n#[deprecated(note=\"since 2022-04-07; use `nullR_def` instead\")]\nNotation is_null_def := nullR_def (only parsing).\n", "meta": {"author": "bedrocksystems", "repo": "BRiCk", "sha": "23d7e64cc53706de608dbff0be75d1c4b8c3a7ec", "save_path": "github-repos/coq/bedrocksystems-BRiCk", "path": "github-repos/coq/bedrocksystems-BRiCk/BRiCk-23d7e64cc53706de608dbff0be75d1c4b8c3a7ec/theories/lang/cpp/logic/heap_pred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.21864626982294527}}
{"text": "\nFrom Coq Require Import ZArith List.\nFrom mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq ssrfun.\nFrom BitBlasting Require Import QFBV CNF BBCommon.\nFrom ssrlib Require Import ZAriths Seqs Tactics.\nFrom nbits Require Import NBits.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(* auxiliary lemmas *)\n\nLemma enc_bits_drop E n ls bs :\n  enc_bits E ls bs -> enc_bits E (drop n ls) (drop n bs) .\nProof .\n  move => Hlsbs .\n  move : (enc_bits_size Hlsbs) => Hsize .\n  move : ls bs Hsize Hlsbs n .\n  apply : seq_ind2 => [|ls_hd bs_hd ls_tl bs_tl Hsize IH] .\n  - by rewrite /= .\n  - rewrite enc_bits_cons => /andP [Hlsbshd Hlsbstl] .\n    case => [|n] .\n    + by rewrite /= enc_bits_cons Hlsbshd Hlsbstl .\n    + by rewrite /= (IH Hlsbstl) .\nQed .\n\nLemma newer_than_lits_drop g n ls :\n  newer_than_lits g ls -> newer_than_lits g (drop n ls) .\nProof .\n  elim : ls n => [|ls_hd ls_tl IH] n .\n  - by rewrite /= .\n  - rewrite newer_than_lits_cons => /andP [Hlshd Hlstl] .\n    case : n => [|n] .\n    + rewrite /=; apply /andP; split; assumption .\n    + by rewrite /= (IH n) .\nQed .\n\n(* ===== bit_blast_high ===== *)\n\nDefinition bit_blast_high g n ls : generator * cnf * word :=\n  (g, [::], copy (n - size ls) lit_ff ++ drop (size ls - n) ls) .\n\nDefinition mk_env_high E g n ls : env * generator * cnf * word :=\n  (E, g, [::], copy (n - size ls) lit_ff ++ drop (size ls - n) ls) .\n\nLemma bit_blast_high_correct E g n bs ls g' cs lrs :\n  bit_blast_high g n ls = (g', cs, lrs) ->\n  enc_bits E ls bs -> interp_cnf E (add_prelude cs) ->\n  enc_bits E lrs (high n bs) .\nProof .\n  rewrite /bit_blast_high /high; case => _ <- <- Hlsbs Hcnf .\n  rewrite (enc_bits_size Hlsbs) /zeros /b0 enc_bits_cat; first done .\n  - apply: enc_bits_copy. exact: (add_prelude_enc_bit_ff Hcnf).\n  - exact : (enc_bits_drop (size bs - n) Hlsbs) .\nQed .\n\nLemma mk_env_high_is_bit_blast_high E g n ls E' g' cs lrs :\n  mk_env_high E g n ls = (E', g', cs, lrs) ->\n  bit_blast_high g n ls = (g', cs, lrs) .\nProof .\n  by rewrite /mk_env_high /bit_blast_high; case => _ <- <- <- .\nQed .\n\nLemma mk_env_high_newer_gen E g n ls E' g' cs lrs :\n  mk_env_high E g n ls = (E', g', cs, lrs) -> (g <=? g')%positive .\nProof .\n  rewrite /mk_env_high; by t_auto_newer .\nQed .\n\nLemma mk_env_high_newer_res E g n ls E' g' cs lrs :\n  mk_env_high E g n ls = (E', g', cs, lrs) ->\n  newer_than_lit g lit_tt -> newer_than_lits g ls -> newer_than_lits g' lrs .\nProof .\n  rewrite /mk_env_high; case => _ <- _ <- Htt Hls .\n  rewrite newer_than_lits_cat .\n  apply /andP; split .\n  - exact : newer_than_lits_copy .\n  - exact : newer_than_lits_drop .\nQed .\n\nLemma mk_env_high_newer_cnf E g n ls E' g' cs lrs :\n  mk_env_high E g n ls = (E', g', cs, lrs) ->\n  newer_than_lit g lit_tt -> newer_than_lits g ls ->\n  newer_than_cnf g' cs .\nProof .\n  by rewrite /mk_env_high; case => _ <- <- _ .\nQed .\n\nLemma mk_env_high_preserve E g n ls E' g' cs lrs :\n  mk_env_high E g n ls = (E', g', cs, lrs) -> env_preserve E E' g .\nProof .\n  by rewrite /mk_env_high; case => <- _ _ _ .\nQed .\n\nLemma mk_env_high_sat E g n ls E' g' cs lrs :\n  mk_env_high E g n ls = (E', g', cs, lrs) ->\n  newer_than_lits g ls -> interp_cnf E' cs .\nProof .\n  by rewrite /mk_env_high; case => <- _ <- _ _ .\nQed .\n\nLemma mk_env_high_env_equal E1 E2 g n ls E1' E2' g1 g2 cs1 cs2 lrs1 lrs2 :\n  env_equal E1 E2 ->\n  mk_env_high E1 g n ls = (E1', g1, cs1, lrs1) ->\n  mk_env_high E2 g n ls = (E2', g2, cs2, lrs2) ->\n  env_equal E1' E2' /\\ g1 = g2 /\\ cs1 = cs2 /\\ lrs1 = lrs2.\nProof.\n  rewrite /mk_env_high => Heq.\n  case=> ? ? ? ?; case=> ? ? ? ?; subst. done.\nQed.\n", "meta": {"author": "fmlab-iis", "repo": "coq-qfbv", "sha": "0e9521febd1564747723a773d25e54781e81b762", "save_path": "github-repos/coq/fmlab-iis-coq-qfbv", "path": "github-repos/coq/fmlab-iis-coq-qfbv/coq-qfbv-0e9521febd1564747723a773d25e54781e81b762/src/BBHigh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2185922716944111}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Compile-time evaluation of initializers for global C variables. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import AST.\nRequire Import Memory.\nRequire Import Ctypes.\nRequire Import Cop.\nRequire Import Csyntax.\n\nOpen Scope error_monad_scope.\n\n(** * Evaluation of compile-time constant expressions *)\n\n(** To evaluate constant expressions at compile-time, we use the same [value]\n  type and the same [sem_*] functions that are used in CompCert C's semantics\n  (module [Csem]).  However, we interpret pointer values symbolically:\n  [Vptr (Zpos id) ofs] represents the address of global variable [id]\n  plus byte offset [ofs]. *)\n\n(** [constval a] evaluates the constant expression [a].\n\nIf [a] is a r-value, the returned value denotes:\n- [Vint n], [Vfloat f]: the corresponding number\n- [Vptr id ofs]: address of global variable [id] plus byte offset [ofs]\n- [Vundef]: erroneous expression\n\nIf [a] is a l-value, the returned value denotes:\n- [Vptr id ofs]: global variable [id] plus byte offset [ofs]\n*)\n\nDefinition do_cast (v: val) (t1 t2: type) : res val :=\n  match sem_cast v t1 t2 with\n  | Some v' => OK v'\n  | None => Error(msg \"undefined cast\")\n  end.\n\nFixpoint constval (a: expr) : res val :=\n  match a with\n  | Eval v ty =>\n      match v with\n      | Vint _ | Vfloat _ => OK v\n      | Vptr _ _ | Vundef => Error(msg \"illegal constant\")\n      end\n  | Evalof l ty =>\n      match access_mode ty with\n      | By_reference | By_copy => constval l\n      | _ => Error(msg \"dereferencing of an l-value\")\n      end\n  | Eaddrof l ty =>\n      constval l\n  | Eunop op r1 ty =>\n      do v1 <- constval r1;\n      match sem_unary_operation op v1 (typeof r1) with\n      | Some v => OK v\n      | None => Error(msg \"undefined unary operation\")\n      end\n  | Ebinop op r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match sem_binary_operation op v1 (typeof r1) v2 (typeof r2) Mem.empty with\n      | Some v => OK v\n      | None => Error(msg \"undefined binary operation\")\n      end\n  | Ecast r ty =>\n      do v1 <- constval r; do_cast v1 (typeof r) ty\n  | Esizeof ty1 ty =>\n      OK (Vint (Int.repr (sizeof ty1)))\n  | Ealignof ty1 ty =>\n      OK (Vint (Int.repr (alignof ty1)))\n  | Eseqand r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match bool_val v1 (typeof r1) with\n      | Some true => do v3 <- do_cast v2 (typeof r2) type_bool; do_cast v3 type_bool ty\n      | Some false => OK (Vint Int.zero)\n      | None => Error(msg \"undefined && operation\")\n      end\n  | Eseqor r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match bool_val v1 (typeof r1) with\n      | Some false => do v3 <- do_cast v2 (typeof r2) type_bool; do_cast v3 type_bool ty\n      | Some true => OK (Vint Int.one)\n      | None => Error(msg \"undefined || operation\")\n      end\n  | Econdition r1 r2 r3 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      do v3 <- constval r3;\n      match bool_val v1 (typeof r1) with\n      | Some true => do_cast v2 (typeof r2) ty\n      | Some false => do_cast v3 (typeof r3) ty\n      | None => Error(msg \"condition is undefined\")\n      end\n  | Ecomma r1 r2 ty =>\n      do v1 <- constval r1; constval r2\n  | Evar x ty =>\n      OK(Vptr (Zpos x) Int.zero)\n  | Ederef r ty =>\n      constval r\n  | Efield l f ty =>\n      match typeof l with\n      | Tstruct id fList _ =>\n          do delta <- field_offset f fList;\n          do v <- constval l;\n          OK (Val.add v (Vint (Int.repr delta)))\n      | Tunion id fList _ =>\n          constval l\n      | _ =>\n          Error(msg \"ill-typed field access\")\n      end\n  | Eparen r ty =>\n      do v <- constval r; do_cast v (typeof r) ty\n  | _ =>\n    Error(msg \"not a compile-time constant\")\n  end.\n\n(** * Translation of initializers *)\n\nInductive initializer :=\n  | Init_single (a: expr)\n  | Init_compound (il: initializer_list)\nwith initializer_list :=\n  | Init_nil\n  | Init_cons (i: initializer) (il: initializer_list).\n\n(** Translate an initializing expression [a] for a scalar variable\n  of type [ty].  Return the corresponding initialization datum. *)\n\nDefinition transl_init_single (ty: type) (a: expr) : res init_data :=\n  do v1 <- constval a;\n  do v2 <- do_cast v1 (typeof a) ty;\n  match v2, ty with\n  | Vint n, Tint I8 sg _ => OK(Init_int8 n)\n  | Vint n, Tint I16 sg _ => OK(Init_int16 n)\n  | Vint n, Tint I32 sg _ => OK(Init_int32 n)\n  | Vint n, Tpointer _ _ => OK(Init_int32 n)\n  | Vfloat f, Tfloat F32 _ => OK(Init_float32 f)\n  | Vfloat f, Tfloat F64 _ => OK(Init_float64 f)\n  | Vptr (Zpos id) ofs, Tint I32 sg _ => OK(Init_addrof id ofs)\n  | Vptr (Zpos id) ofs, Tpointer _ _ => OK(Init_addrof id ofs)\n  | Vundef, _ => Error(msg \"undefined operation in initializer\")\n  | _, _ => Error (msg \"type mismatch in initializer\")\n  end.\n\n(** Translate an initializer [i] for a variable of type [ty].\n  Return the corresponding list of initialization data. *)\n\nDefinition padding (frm to: Z) : list init_data :=\n  let n := to - frm in\n  if zle n 0 then nil else Init_space n :: nil.\n\nFixpoint transl_init (ty: type) (i: initializer)\n                     {struct i} : res (list init_data) :=\n  match i, ty with\n  | Init_single a, _ =>\n      do d <- transl_init_single ty a; OK (d :: nil)\n  | Init_compound il, Tarray tyelt sz _ =>\n      if zle sz 0\n      then OK (Init_space(sizeof tyelt) :: nil)\n      else transl_init_array tyelt il sz\n  | Init_compound il, Tstruct _ Fnil _ =>\n      OK (Init_space (sizeof ty) :: nil)\n  | Init_compound il, Tstruct id fl _ =>\n      transl_init_struct id ty fl il 0\n  | Init_compound il, Tunion _ Fnil _ =>\n      OK (Init_space (sizeof ty) :: nil)\n  | Init_compound il, Tunion id (Fcons _ ty1 _) _ =>\n      transl_init_union id ty ty1 il\n  | _, _ =>\n      Error (msg \"wrong type for compound initializer\")\n  end\n\nwith transl_init_array (ty: type) (il: initializer_list) (sz: Z)\n                       {struct il} : res (list init_data) :=\n  match il with\n  | Init_nil =>\n      if zeq sz 0\n      then OK nil\n      else Error (msg \"wrong number of elements in array initializer\")\n  | Init_cons i1 il' =>\n      do d1 <- transl_init ty i1;\n      do d2 <- transl_init_array ty il' (sz - 1);\n      OK (d1 ++ d2)\n  end\n\nwith transl_init_struct (id: ident) (ty: type)\n                        (fl: fieldlist) (il: initializer_list) (pos: Z)\n                        {struct il} : res (list init_data) :=\n  match il, fl with\n  | Init_nil, Fnil =>\n      OK (padding pos (sizeof ty))\n  | Init_cons i1 il', Fcons _ ty1 fl' =>\n      let pos1 := align pos (alignof ty1) in\n      do d1 <- transl_init (unroll_composite id ty ty1) i1;\n      do d2 <- transl_init_struct id ty fl' il' (pos1 + sizeof ty1);\n      OK (padding pos pos1 ++ d1 ++ d2)\n  | _, _ =>\n      Error (msg \"wrong number of elements in struct initializer\")\n  end\n\nwith transl_init_union (id: ident) (ty ty1: type) (il: initializer_list)\n                       {struct il} : res (list init_data) :=\n  match il with\n  | Init_nil =>\n      Error (msg \"empty union initializer\")\n  | Init_cons i1 _ =>\n      do d <- transl_init (unroll_composite id ty ty1) i1;\n      OK (d ++ padding (sizeof ty1) (sizeof ty))\n  end.\n\n\n", "meta": {"author": "academic-archive", "repo": "pldi14-veristack", "sha": "9edcd8752ae2e1e6377bfb33589a377cc39c04ca", "save_path": "github-repos/coq/academic-archive-pldi14-veristack", "path": "github-repos/coq/academic-archive-pldi14-veristack/pldi14-veristack-9edcd8752ae2e1e6377bfb33589a377cc39c04ca/qcompcert/cfrontend/Initializers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21847192243463784}}
{"text": "Require Import Vars.\nRequire Import PhaserMap.\nRequire Import Phaser.\nRequire Import Syntax.\nRequire Import TaskMap.\n\n(** A state pairs the state of all phasers and the state of all tasks. *)\n\nDefinition state := (phasermap * taskmap) % type.\n\nDefinition get_tasks (s:state) :taskmap := snd s.\nDefinition get_phasers (s:state) : phasermap := fst s.\n\nImport Syntax.CST.\n\n(** Control-flow reduction: *)\n\nModule ControlFlow.\nInductive Reduces : cflow -> prog -> prog -> Prop :=\n  | r_skip:\n    forall p,\n    Reduces skip p p\n  | r_iter:\n    forall p q,\n    Reduces (loop p) q (concat p (LOOP(p);; q))\n  | r_elide:\n    forall p q,\n    Reduces (loop p) q q.\nEnd ControlFlow.\n\n(** Small step semantics for states. *)\n\nInductive Reduces: state -> state -> Prop :=\n  | r_new_task:\n  (** Creates a new task. Task id [t'] must not be present in\n      defined in the task map. *)\n    forall (t t':tid) (p:prog) (pm:phasermap) (tm:taskmap),\n    TaskMap.MapsTo t (t' <- NEW_TID;; p) tm -> \n    ~ TaskMap.In t' tm ->\n    Reduces (pm, tm) (pm, newTask tm t')\n  | r_fork:\n    (** Fork assigns a program to an \"empty\" task. *)\n    forall (t t':tid) (p p':prog) (pm:phasermap) (tm:taskmap),\n    TaskMap.MapsTo t (FORK(t', p');; p) tm ->\n    TaskMap.MapsTo t' pnil tm ->\n    Reduces (pm, tm) (pm, (TaskMap.add t p (TaskMap.add t' p' tm)))\n  | r_phaser:\n    (** Invokes a phaser operation on a given phaser identifier. *)\n    forall (o:PhaserMap.op) (t:tid) (p:prog) (pm:phasermap) (tm:taskmap),\n    TaskMap.MapsTo t ((pm_op o) ;; p) tm ->\n    Reduces (pm, tm) ((PhaserMap.eval pm t o), (TaskMap.add t p tm))\n  | r_cflow:\n    (** Runs a control-flow operation. *)\n    forall t c p q pm tm,\n    TaskMap.MapsTo t (CFLOW c;; p) tm ->\n    ControlFlow.Reduces c p q ->\n    Reduces (pm, tm) (pm, (TaskMap.add t q tm)).\n\n(** Creates a new state from a given program. *)\n\nDefinition load (t:tid) (b:prog) := (PhaserMap.make, TaskMap.add t b TaskMap.make).\n\n(* begin hide *)\n\n(* Naive substitution, does not replace names in newphaser. *)\n\nFixpoint phid_subst (o_ph:phid) (n_ph:phid) (b:prog) :=\n  let subst := phid_subst o_ph n_ph in\n  match b with\n    | pcons i b' =>\n      let rest := subst b' in\n      let same := i ;; rest in\n      match i with\n        | pm_op mo => \n          match mo with\n            | PhaserMap.NEW ph =>\n              if PHID.eq_dec o_ph ph\n              then b\n              else same\n            | PhaserMap.APP ph o =>\n              if PHID.eq_dec o_ph ph\n              then pm_op (PhaserMap.APP n_ph o) ;; rest\n              else same\n          end\n        | fork t p => fork t (subst p) ;; rest\n        | c_op c =>\n          match c with\n            | loop p => LOOP (subst p) ;; rest\n            | skip => same\n          end\n        | _ => same\n      end\n    | END => END\n  end.\n\nFixpoint tid_subst (o_t:tid) (n_t:tid) (b:prog) := \n  let subst := tid_subst o_t n_t in\n  match b with\n    | pcons i b' =>\n      let kont := subst b' in\n      let same := i ;; kont in\n      match i with\n        | new_tid t =>\n          if TID.eq_dec o_t t\n          then b (* no substitution *)\n          else same\n        | fork t p => \n          if TID.eq_dec o_t t\n          then fork n_t (subst p) ;; kont\n          else fork t (subst p) ;; kont\n        | pm_op po =>\n          match po with\n            | PhaserMap.APP p o =>\n              match o with\n                | Phaser.REG t =>\n                  if TID.eq_dec o_t t\n                  then REG(p, n_t) ;; kont\n                  else same\n                | _ => same\n              end\n            | _ => same\n          end\n        | c_op c =>\n          match c with\n            | loop p => LOOP (subst p) ;; kont\n            | skip => same\n          end\n        | _ => same\n      end\n    | END => END\n  end.\n\n(* end hide *)", "meta": {"author": "cogumbreiro", "repo": "brenner-coq", "sha": "76bb34c9784396b0a40cfd52e266ce2cec4c0ccf", "save_path": "github-repos/coq/cogumbreiro-brenner-coq", "path": "github-repos/coq/cogumbreiro-brenner-coq/brenner-coq-76bb34c9784396b0a40cfd52e266ce2cec4c0ccf/src/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.21847192243463776}}
{"text": "(* Copyright (c) 2008, Harvard University\n * All rights reserved.\n *\n * Author: Greg Morrisett\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n *   this list of conditions and the following disclaimer.\n * - Redistributions in binary form must reproduce the above copyright notice,\n *   this list of conditions and the following disclaimer in the documentation\n *   and/or other materials provided with the distribution.\n * - The names of contributors may not be used to endorse or promote products\n *   derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *)\n\nRequire Import String.\nRequire Import List. \nRequire Import Ascii.\nRequire Import Omega.\n(*Require Import Eqdep.*)\nRequire Import Data.Stream.\n\nSet Implicit Arguments.\n\n(* This section defines grammars and parsers -- should be turned into a\n * functor over the char and char_eq variables. \n *)\nSection PARSE.\n  Variable char : Set.\n  Variable char_eq : forall (c1 c2:char), {c1 = c2} + {c1 <> c2}.\n\n  Section GRAMMAR.\n  (* We describe the syntax of grammars using Adam's approach from ltamer *)\n  Section VARS.\n    Variable var : Set -> Type.\n\n    Inductive term: Set -> Type := \n    | GVar     : forall t:Set, var t -> term t\n    | GEpsilon : forall t:Set, t -> term t\n    | GSatisfy : (char -> bool) -> term char\n    | GCat     : forall (t1 t2:Set), term t1 -> term t2 -> term (t1 * t2)\n    | GAlt     : forall t, term t -> term t -> term t\n    | GTry     : forall t, term t -> term t\n    | GRec     : forall t:Set, (var t -> term t) -> term t\n    | GMap     : forall (t1 t2:Set), (t1 -> t2) -> term t1 -> term t2.\n\n    (* A relational definition of substitution for terms -- used in the definition\n     * of the semantics below, in particular for the rec case *)\n    Inductive Subst :\n    forall (t1 t2:Set), (var t1->term t2)->(term t1)->(term t2)->Type := \n    | SEpsilon : forall (t1 t2:Set) (v:t2) (e:term t1), \n      Subst (fun _ => GEpsilon v) e (GEpsilon v)\n    | SSatisfy : forall t1 (f:char->bool) (e:term t1), \n      Subst (fun _ => GSatisfy f) e (GSatisfy f)\n    | SCat : \n      forall t1 t2 t3 (f1:var t1 -> term t2) (f2:var t1 -> term t3) (e:term t1)\n        (e1:term t2)(e2:term t3),\n        Subst f1 e e1 -> Subst f2 e e2 -> \n        Subst (fun v => GCat (f1 v) (f2 v)) e (GCat e1 e2)\n    | SAlt : \n      forall t1 t2 (f1 f2:var t1 -> term t2) (e:term t1)(e1 e2:term t2),\n        Subst f1 e e1 -> Subst f2 e e2 -> \n        Subst (fun v => GAlt (f1 v) (f2 v)) e (GAlt e1 e2)\n    | SMap : \n      forall (t1 t2 t3:Set) \n        (f:var t1 -> term t2) (e:term t1) (g:t2->t3) (e1:term t2),\n        Subst f e e1 -> \n        Subst (fun v => GMap g (f v)) e (GMap g e1)\n    | STry : \n      forall t1 t2 (f1:var t1 -> term t2) (e : term t1) (e1:term t2), \n        Subst f1 e e1 -> Subst (fun v => GTry (f1 v)) e (GTry e1)\n    | SVarEq : \n      forall t (e:term t), Subst (@GVar t) e e\n    | SVarNeq : \n      forall t1 t2 (v:var t2) (e:term t1), Subst (fun _ => GVar v) e (GVar v)\n    | SRec : \n      forall t1 t2 (f1:var t1->var t2->term t2) (f2:var t2->term t2)(e:term t1), \n        (forall v', Subst (fun v => f1 v v') e (f2 v')) -> \n        Subst (fun v => GRec (f1 v)) e (GRec f2).\n  End VARS.\n\n  Definition Term t := forall V, term V t.\n  Implicit Arguments GVar     [var t].\n  Implicit Arguments GEpsilon [var t].\n  Implicit Arguments GSatisfy [var].\n  Implicit Arguments GCat     [var t1 t2].\n  Implicit Arguments GAlt     [var t].\n  Implicit Arguments GTry     [var t].\n  Implicit Arguments GRec     [var t].\n  Implicit Arguments GMap     [var t1 t2].\n\n  Fixpoint flatten(V:Set->Type)(t:Set)(e: term (term V) t) {struct e} : term V t := \n    match e in (term _ t) return (term V t) with\n    | GVar _ v => v\n    | GEpsilon t v => GEpsilon v\n    | GSatisfy f => GSatisfy f\n    | GCat t1 t2 e1 e2 => GCat (flatten e1) (flatten e2)\n    | GAlt t e1 e2 => GAlt (flatten e1) (flatten e2)\n    | GMap t1 t2 f e => GMap f (flatten e)\n    | GTry t e => GTry (flatten e)\n    | GRec t f => GRec (fun (v:V t) => flatten (f (GVar v)))\n    end.\n\n  Definition unroll(t:Set)(f:forall V, V t -> term V t) : Term t := \n    fun V => flatten (f (term V) (GRec (f V))).\n\n  Inductive empty_set : Set := .\n  Definition empvar := (fun _:Set => empty_set).\n\n  (* It would be nice if we could prove the following axiom so that the definition\n   * of Gfix was simpler: \n  Axiom Unroll : forall (t:Set)(f:forall var, var t -> term var t), \n    Subst (f empvar) (GRec (f empvar)) (unroll f empvar).\n  *)\n\n  Inductive consumed_t : Set := Consumed | NotConsumed.\n\n  Inductive reply_t(a:Set) : Set := \n  | Okay : consumed_t -> a -> list char -> reply_t a\n  | Error : consumed_t -> reply_t a.\n\n  Implicit Arguments Error [a].\n\n  Definition join_cons (nc1 nc2 : consumed_t) : consumed_t := \n    match (nc1, nc2) with\n    | (Consumed, _) => Consumed\n    | (_, Consumed) => Consumed\n    | (_, _) => NotConsumed\n    end.\n\n  (* We give meaning to grammars here, following the style of Parsec combinators. \n   * In particular, note that we only try the second grammar of an alternation when\n   * the first one does not consume input.  The presentation here is slightly different\n   * from Parsec in that (a) we don't worry about space leaks since this is intended\n   * for specification only, and (b) instead of representing concatenation with a\n   * bind-like construct, we simply return a pair of the results.  We have a separate \n   * operation GMap that allows us to transform a t1 grammar to a t2 grammar.  The\n   * intention here is that grammars should use a minimum of meta-level stuff in\n   * revealing their structure, so that we can potentially analyze and transform them.\n   *)\n\n  Section DENOTE.\n\n  (* What I'm doing here is defining a denotational semantics that maps grammar terms\n   * down to a simpler language with a monadic structure.  Then we give an operational\n   * semantics to the monadic structure.  Note that I've instantiated the var in the\n   * phoas so that it always yields an empty set.  This ensures that the term does not\n   * have a free variable.  *)\n  Inductive M: Set -> Type := \n  | MReturn : forall t, reply_t t -> M t\n  | MBind : forall t1 t2, M t1 -> (reply_t t1 -> M t2) -> M t2\n  | MFix : forall t (f:empvar t -> term empvar t), list char -> M t.\n\n  Notation \"'Return' x\" := (MReturn x) (at level 75) : gdenote_scope.\n  Notation \"x <- c1 ; c2\" := (MBind c1 (fun x => c2)) \n    (right associativity, at level 84, c1 at next level) : gdenote_scope.\n\n  Definition wfCoerce (t:Set)(v:empvar t) : M t := match v with end.\n\n  Open Local Scope gdenote_scope.\n\n  (* here we map a term e to a computation over lists of characters -- this is\n   * essentially the same as with Parsec-style combinators, though I've chosen\n   * slightly different combinators that are closer to arrows than the monadic\n   * interpretation.  *)\n  Fixpoint denote(t:Set)(e:term empvar t)(s:list char) {struct e} : M t := \n    match e in term _ t return M t with\n      | GVar _ v => wfCoerce v\n      | GEpsilon _ x => Return Okay NotConsumed x s\n      | GSatisfy test => \n        Return match s with\n                 | c :: cs => if (test c) then Okay Consumed c cs else \n                   Error NotConsumed\n                 | nil => Error NotConsumed\n               end\n      | GMap t1 t2 f e => \n        r <- denote e s ;\n        Return match r with \n                 | Okay nc v s2 => Okay nc (f v) s2\n                 | Error nc => Error nc\n               end\n      | GTry t e => \n        r <- denote e s ;\n        Return match r with\n                 | Error Consumed => Error NotConsumed\n                 | Okay Consumed v s2 => Okay NotConsumed v s2\n                 | _ => r\n               end\n      | GCat t1 t2 e1 e2 => \n        r1 <- denote e1 s ;\n        match r1 with \n          | Error nc => Return Error nc\n          | Okay nc1 v1 s1 => \n            r2 <- denote e2 s1 ;\n            Return match r2 with \n                     | Error nc2 => Error (join_cons nc1 nc2)\n                     | Okay nc2 v2 s2 => Okay (join_cons nc1 nc2) (v1,v2) s2\n                   end\n        end\n      | GAlt t e1 e2 => \n        r1 <- denote e1 s ; \n        match r1 with\n          | Error Consumed => Return Error Consumed\n          | Error NotConsumed => denote e2 s\n          | Okay NotConsumed v s2 => \n            r2 <- denote e2 s ;\n            Return match r2 with \n                     | Error NotConsumed => Okay NotConsumed v s2\n                     | Okay NotConsumed _ _ => Okay NotConsumed v s2\n                     | r2 => r2\n                   end\n          | Okay Consumed v s2 => Return Okay Consumed v s2\n        end\n      | GRec t f => MFix f s\n    end.\n  \n  (* We now give an operational semantics to the monadic terms generated by the\n   * denotation function.  Note that in essence, we just delay unrolling the \n   * fix operator.  *)\n  Inductive evals : forall t, M t -> reply_t t -> Prop := \n  | eMReturn : forall t (r:reply_t t), evals (MReturn r) r\n  | eMBind : forall t1 t2 (c:M t1) (r1:reply_t t1) (f:reply_t t1 -> M t2) r2, \n    evals c r1 -> evals (f r1) r2 -> evals (MBind c f) r2\n  | eMFix : \n    forall t (f:empvar t -> term empvar t) (s:list char) (e:term empvar t) (r:reply_t t), \n      Subst f (GRec f) e -> evals (denote e s) r -> evals (MFix f s) r.\n\n  (* Then we say that a term t parses string s yielding result r if the following\n   * if evaluating the denotation of e, when applied to s yields r. *)\n  Definition parses(t:Set)(e:Term t)(s:list char)(r:reply_t t) := \n    evals (denote (e empvar) s) r.\n\n  End DENOTE.\n  End GRAMMAR.\n\n  Require Import Ynot.\n\n  Inductive parse_reply_t(t:Set) : Set := \n  | OKAY : consumed_t -> nat -> t -> parse_reply_t t\n  | ERROR : consumed_t -> string -> parse_reply_t t.\n\n  Fixpoint nthtail(A:Type)(cs:list A)(n:nat) {struct n} : list A := \n    match (n,cs) with\n    | (0,cs) => cs\n    | (S n, c::cs) => nthtail cs n\n    | (S n, nil) => nil\n    end.\n\n  Definition okay(t:Set)(n:[nat])(i:instream_t char)(e:Term t)(c:consumed_t)(m:nat)(v:t) :=\n    (n ~~ let elts := stream_elts i in\n          elts ~~ [parses e (nthtail elts n) (Okay c v (nthtail elts (m+n)))])%hprop.\n\n  Definition okaystr(t:Set)(n:[nat])(i:instream_t char)(e:Term t)(c:consumed_t)(m:nat)(v:t) :=\n    (okay n i e c m v * (n ~~ rep i (m+n)))%hprop.\n\n  Definition error(t:Set)(n:[nat])(i:instream_t char)(e:Term t)(c:consumed_t) := \n    (n ~~ let elts := stream_elts i in\n          elts ~~ [parses e (nthtail elts n) (Error t c)])%hprop.\n\n  Definition errorstr(t:Set)(n:[nat])(i:instream_t char)(e:Term t)(c:consumed_t) := \n    (error n i e c * (Exists m :@ nat, rep i m))%hprop.\n\n  Definition ans_correct(t:Set)(n:[nat])(i:instream_t char)(e:Term t)(ans:parse_reply_t t) :=\n    match ans with \n    | OKAY c m v => okay n i e c m v\n    | ERROR c _ => error n i e c\n    end.\n\n  Definition ans_str_correct(t:Set)(n:[nat])(i:instream_t char)(e:Term t)(ans:parse_reply_t t) :=\n    match ans with \n    | OKAY c m v => okaystr n i e c m v\n    | ERROR c _ => errorstr n i e c\n    end.\n\n  Definition parser_t(t:Set)(e:Term t) := \n    forall (ins:instream_t char)(n:[nat]), STsep (n ~~ rep ins n) (ans_str_correct n ins e).\n  Implicit Arguments parser_t [t].\n\n  Open Local Scope stsep_scope. \n\n  Lemma EmpImpInj(P:Prop) : \n    P -> __ ==> [P].\n  Proof.\n    intros. sep fail auto.\n  Qed.\n\n  Lemma NthErrorNoneNthTail(A:Type)(i:nat)(vs:list A) : \n   nth_error vs i = None -> nthtail vs i = nil.\n  Proof.\n    induction i ; destruct vs ; auto ; simpl ; intros. unfold value in H. congruence.\n    apply IHi. auto.\n  Qed.\n\n  Lemma NthErrorSomeNthTail(A:Type)(i:nat)(vs:list A)(v:A) : \n    nth_error vs i = Some v -> \n      exists vs1, exists vs2, vs = vs1 ++ v::vs2 /\\ nthtail vs i = v::vs2.\n  Proof.\n    induction i ; destruct vs ; auto ; simpl ; intros. unfold Specif.error in H. congruence.\n    unfold value in H. inversion H. subst. exists (nil(A:=A)). simpl. eauto.\n    unfold Specif.error in H. congruence. pose (IHi _ _ H). destruct e as [vs1 [vs2 [H1 H2]]].\n    exists (a::vs1). exists vs2. split. rewrite H1. simpl. auto. auto.\n  Qed.\n\n  Lemma NthTailSucc(A:Type)(i:nat)(vs vs2:list A)(v:A) : \n    nthtail vs i = v::vs2 -> nthtail vs (S i) = vs2.\n  Proof.\n    induction i ; simpl ; intros. rewrite H. auto. destruct vs. congruence. \n    pose (IHi _ _ _ H). apply e.\n  Qed.\n\n  Lemma PlusAssoc(n m p:nat) : n + (m + p) = n + m + p. intros ; omega. Qed.\n\n  Ltac mysep := \n    match goal with\n    | [ |- (__ ==> [ _ ])%hprop ] => apply EmpImpInj\n    | [ |- evals (MReturn ?r) ?r ] => constructor\n    | [ |- evals (MBind _ _) _] => econstructor\n    | [ |- context[?n + (?m + ?p)]] => rewrite (PlusAssoc n m p)\n    | [ |- context[if (?f ?c) then _ else _] ] => \n      let H := fresh \"H\" in\n      assert (H: f c = true \\/ f c = false) ; [ destruct (f c) ; tauto | \n              destruct H ; [ rewrite H ; simpl | rewrite H ; simpl ]]\n    | _ => auto\n    end.\n\n  Definition gsatisfy(f:char -> bool) vars := GSatisfy vars f.\n  Definition gepsilon(t:Set)(v:t) vars := GEpsilon vars v.\n  Definition galt(t:Set)(e1 e2:Term t) vars := GAlt (e1 vars) (e2 vars).\n  Definition gmap(t1 t2:Set)(f:t1 -> t2)(e:Term t1) vars := GMap f (e vars).\n  Definition gcat(t1 t2:Set)(e1:Term t1)(e2:Term t2) vars := GCat (e1 vars) (e2 vars).\n  Definition gtry(t:Set)(e:Term t) vars := GTry (e vars).\n  Definition grec(t:Set)(f:forall (var:Set->Type), var t -> term var t)(var:Set -> Type) :=\n    GRec (f var).\n\n  Ltac myunfold := unfold ans_str_correct, ans_correct, okaystr, okay, errorstr, error, \n    parses, gsatisfy, gepsilon, galt, gmap, gcat, gtry, grec.\n\n  Ltac psimp := (myunfold ; sep fail auto ; mysep ; simpl ; eauto).\n\n  Ltac rsimp := psimp ; \n    match goal with \n    | [ |- context[match ?a with | OKAY c m v => _ | ERROR c _ => _ end] ] => destruct a\n    | [ |- context[match ?c with | Consumed => _ | NotConsumed => _ end] ] => destruct c\n    | _ => idtac\n    end.\n\n  Lemma NthError(x:list char)(n:nat) : \n    (nth_error x n = None \\/ exists c, nth_error x n = Some c).\n  Proof.  intros. destruct (nth_error x n). right. eauto. left. eauto.\n  Qed.\n\n  Lemma EvalsMReturn(t:Set)(r1 r2:reply_t t) : r1 = r2 -> evals (MReturn r1) r2.\n  Proof. intros. rewrite <- H. constructor. Qed.\n\n  (* the parser for a single character *)\n  Definition satisfy(f:char -> bool) : parser_t (gsatisfy f).\n    intros f instream n.\n    refine (copt <- next instream n ; \n            Return (match copt with\n                    | None => ERROR char NotConsumed \"bad character\"\n                    | Some c => if f c then OKAY Consumed 1 c\n                                else ERROR char NotConsumed \"bad character\"\n                    end) <@>\n              match copt with \n              | None => errorstr n instream (gsatisfy f) NotConsumed\n              | Some c => if f c then okaystr n instream (gsatisfy f) Consumed 1 c\n                          else errorstr n instream (gsatisfy f) NotConsumed \n              end @> _) ; psimp ; \n    match goal with \n      [ |- _ ==> match nth_error ?x ?n with | Some c => _ | None => _ end] => \n      let H := fresh in pose (H := NthError x n) ; destruct H ; [ rewrite H ; psimp ; \n        rewrite (NthErrorNoneNthTail _ _ H) ; psimp | destruct H ; rewrite H ; psimp ; psimp ;\n          let H1 := fresh in let v1 := fresh in let v2 := fresh in \n            let H2 := fresh in let H3 := fresh in \n          pose (H1 := NthErrorSomeNthTail _ _ H) ; destruct H1 as [v1 [v2 [H1 H2]]] ; \n          rewrite H2 ; psimp ; pose (H3 := (NthTailSucc _ _ H2)) ; \n          simpl in H3 ; eapply EvalsMReturn ; congruence]\n      | [ |- match ?copt with | Some c => _ | None => _ end ==> _] => destruct copt ;\n        repeat psimp \n    end.\n  Defined.\n            \n  (* the parser for the empty string *)\n  Definition epsilon(t:Set)(v:t) : parser_t (gepsilon v).\n    intros t v instream n.\n    refine ({{Return (OKAY NotConsumed 0 v) <@> (n ~~ rep instream n)}}) ; \n    repeat psimp. \n  Defined.\n    \n  (* left-biased alternation -- need to fix error message propagation here *)\n  Definition alt(t:Set)(e1 e2:Term t)(p1:parser_t e1)(p2:parser_t e2) : parser_t (galt e1 e2).\n    intros t e1 e2 p1 p2 instream n.\n    unfold galt.\n    refine (n0 <- position instream n @> (fun n0 => n ~~ rep instream n * [n0=n])%hprop ; \n            ans1 <- p1 instream n <@> (n ~~ [n0=n])%hprop @> \n               (fun ans1 => ans_str_correct n instream e1 ans1 * (n ~~ [n0=n]))%hprop ;\n            let frame := fun ans => ((n ~~ [n0=n]) * ans_correct n instream e1 ans)%hprop in\n            match ans1 as ans1' \n              return STsep (ans_str_correct n instream e1 ans1' * (n ~~ [n0=n]))%hprop\n                           (ans_str_correct n instream (galt e1 e2))\n            with\n            | ERROR NotConsumed msg1 => \n                seek instream n0 <@> frame (ERROR t NotConsumed msg1) ;; \n                p2 instream n <@> frame  (ERROR t NotConsumed msg1) @> _\n            | OKAY NotConsumed m1 v1 => \n                seek instream n0 <@> frame (OKAY NotConsumed m1 v1) ;; \n                ans2 <- p2 instream n <@> frame (OKAY NotConsumed m1 v1) ;\n                match ans2 as ans2' \n                  return STsep (frame (OKAY NotConsumed m1 v1) * \n                                   ans_str_correct n instream e2 ans2')\n                               (ans_str_correct n instream (galt e1 e2))\n                with\n                | ERROR NotConsumed msg2 => \n                    (* interestingly, I forgot to do the seek here and in the next\n                       case and then got stuck doing the proof! *)\n                    seek instream (m1 + n0) <@> \n                        frame (OKAY NotConsumed m1 v1) *\n                        ans_correct n instream e2 (ERROR t NotConsumed msg2) ;;\n                    Return OKAY NotConsumed m1 v1 <@> \n                        frame (OKAY NotConsumed m1 v1) * \n                        rep instream (m1 + n0) * \n                        ans_correct n instream e2 (ERROR t NotConsumed msg2) @> _\n                | OKAY NotConsumed m2 v2 => \n                    seek instream (m1 + n0) <@> \n                        frame (OKAY NotConsumed m1 v1) *\n                        ans_correct n instream e2 (OKAY NotConsumed m2 v2) ;;\n                    Return OKAY NotConsumed m1 v1 <@> \n                        frame (OKAY NotConsumed m1 v1) * \n                        rep instream (m1 + n0) * \n                        ans_correct n instream e2 (OKAY NotConsumed m2 v2) @> _\n                | ans => \n                    {{Return ans <@> \n                        frame (OKAY NotConsumed m1 v1) * ans_str_correct n instream e2 ans}}\n                end\n          | ans => \n              {{Return ans <@> \n                 ((n ~~ [n0=n]) * ans_str_correct n instream e1 ans)%hprop}}\n          end) ; (try unfold frame) ; repeat rsimp.\n  Defined.\n\n  (* the parser for (gmap f e) given f and a parser p for e *)\n  Definition map(t1 t2:Set)(f:t1->t2)(e:Term t1)(p:parser_t e) : parser_t (gmap f e).\n    intros t1 t2 f e p instream n.\n    refine (ans <- p instream n;\n            Return (match ans with \n                    | OKAY c m v => OKAY c m (f v)\n                    | ERROR c msg => ERROR t2 c msg \n                    end) <@> ans_str_correct n instream e ans @> _) ; psimp.\n    destruct ans ; repeat psimp. \n  Defined.\n\n  (* parser for concatenation *)\n  Definition cat(t1 t2:Set)(e1:Term t1)(e2:Term t2)(p1:parser_t e1)(p2:parser_t e2) : \n    parser_t (gcat e1 e2).\n    intros t1 t2 e1 e2 p1 p2 instream n.\n    refine (n0 <- position instream n ;\n            ans1 <- p1 instream n <@> (n ~~ [n0 = n])%hprop ; \n            match ans1 as ans1' return \n              STsep (ans_str_correct n instream e1 ans1' * (n ~~ [n0 = n])%hprop)\n                    (ans_str_correct n instream (gcat e1 e2))\n            with \n            | OKAY c1 m1 v1 => \n                ans2 <- p2 instream (inhabits (m1+n0))<@> \n                   (ans_correct n instream e1 (OKAY c1 m1 v1) * (n ~~ [n0=n]))%hprop; \n                Return match ans2 with\n                       | OKAY c2 m2 v2 => OKAY (join_cons c1 c2) (m2 + m1) (v1,v2)\n                       | ERROR c2 msg => ERROR (t1*t2)%type (join_cons c1 c2) msg\n                       end <@>\n                  (ans_correct n instream e1 (OKAY c1 m1 v1) * (n ~~ [n0=n]) *\n                   ans_str_correct (inhabits (m1+n0)) instream e2 ans2)%hprop @> _\n            | ERROR c1 msg => \n                {{Return ERROR (t1*t2) c1 msg <@> \n                  (ans_str_correct n instream e1 (ERROR t1 c1 msg) * (n ~~ [n0 = n]))%hprop}}\n            end) ; repeat rsimp.\n  Defined.\n\n  (* try combinator *)\n  Definition try(t:Set)(e:Term t)(p:parser_t e) : parser_t (gtry e).\n    intros t e p instream n.\n    refine (ans <- p instream n ; \n            Return match ans with\n                   | ERROR Consumed msg => ERROR t NotConsumed msg\n                   | OKAY Consumed m v => OKAY NotConsumed m v\n                   | ans => ans\n                   end <@> ans_str_correct n instream e ans @> _) ; psimp.\n    destruct ans ; destruct c ; repeat psimp.\n  Defined.\n\n  (* used in construction of fixed-point *)\n  Definition coerce_parse_fn(t:Set)(f:forall var, var t -> term var t)(e:Term t)\n                            (H:Subst (f empvar) (GRec (f empvar)) (e empvar))\n                            (F:parser_t (grec f) -> parser_t e) : \n                       parser_t (grec f) -> parser_t (grec f).\n    intros t f e H1 F p instream n.\n    refine ((F p instream n) @> _). destruct v ; psimp ; econstructor ; eauto.\n  Qed. \n\n  Definition parser_t'(t:Set)(e:Term t)(p:(instream_t char * [nat])) := \n    let ins := fst p in\n    let n := snd p in\n      STsep (n ~~ rep ins n) (ans_str_correct n ins e).\n\n  (* Alas, note that we need H here -- can't easily prove this once and for all *)\n  Definition Gfix(t:Set)(f:forall V, V t -> term V t)\n                  (F:parser_t (grec f) -> parser_t (unroll f))\n                  (H: Subst (f empvar) (GRec (f empvar)) (unroll f empvar)) : \n                  parser_t (grec f) :=\n    (* coerce F so that its result is re-rolled *)\n    let Fc : parser_t (grec f) -> parser_t (grec f) := coerce_parse_fn H F in\n    (* Grrr. To call SepFix, I have to uncurry Fc *)\n    let Fu : (forall p, parser_t' (grec f) p) -> (forall p, parser_t' (grec f) p) := \n       fun f arg => Fc (fun ins n => f (ins,n)) (fst arg) (snd arg) in\n    fun instream n => (SepFix _ _ Fu) (instream,n).\n  Implicit Arguments Gfix [t f].\nEnd PARSE.\n\n\nSection Examples.\n  Delimit Scope grammar_scope with grammar.\n\n  Notation \"!!!! v\" := (GVar _ _ _ v) (at level 1) : grammar_scope.\n  Notation \"# c\" := (GSatisfy(char:=ascii) _ \n                     (fun c2 => if ascii_dec (c%char) c2 then true else false)) \n  (at level 1) : grammar_scope.\n  Notation \"e1 ^ e2\" := (GCat e1 e2) \n     (right associativity, at level 30) : grammar_scope.\n  Notation \"e @ f\" := (GMap f e)\n     (left associativity, at level 78) : grammar_scope.\n  Notation \"e1 '|||' e2\" := (GAlt e1 e2)\n    (right associativity, at level 79) : grammar_scope.\n  Notation \"% v\" := (GEpsilon ascii _ v) (at level 1) : grammar_scope.\n\n  Delimit Scope parser_scope with parser.\n\n  Notation \"e1 ^ e2\" := (cat e1 e2) \n     (right associativity, at level 30) : parser_scope.\n  Notation \"e @ f\" := (map f e)\n     (left associativity, at level 78) : parser_scope.\n  Notation \"e1 '|||' e2\" := (alt e1 e2)\n    (right associativity, at level 79) : parser_scope.\n  Notation \"# c\" := (satisfy (fun c2 => if ascii_dec (c%char) c2 then true else false)) \n    (at level 1) : parser_scope.\n  Notation \"% v\" := (epsilon(char:=ascii) v) : parser_scope.\n  Notation \"'gfix' e\" := (Gfix e _) (at level 70).\n\n  Ltac gtac := unfold unroll, grec ; simpl ; repeat (progress constructor).\n\n  (* Example grammar :  N -> a | b N b *)                \n  Definition g : Term ascii unit := \n    grec (fun var N => #\"a\"             @ (fun _ => tt)  \n                    ||| #\"b\" ^ !!!!N ^ #\"b\" @ (fun _ => tt))%grammar.\n\n  (* Example parser for grammar g *)\n  Definition g_parser : parser_t g.\n      refine (gfix (fun (p:parser_t g) => \n                      #\"a\"            @ (fun _ => tt) \n                   ||| #\"b\" ^ p ^ #\"b\" @ (fun _ => tt))%parser) ;\n      gtac.\n  Defined.\n\n  (* A grammar for digits *)  \n  Definition is_digit(c:ascii):bool := \n    if le_lt_dec (nat_of_ascii \"0\"%char) (nat_of_ascii c) then\n      (if le_lt_dec (nat_of_ascii c) (nat_of_ascii \"9\"%char) then true else false)\n    else false.\n\n  Definition digit : Term ascii ascii := gsatisfy is_digit.\n\n  (* A parser for digits *)\n  Definition digit_p : parser_t digit := satisfy is_digit.\n\n  (* A grammar for numbers:  note that this computes the value of the number *)\n  Definition number :=\n    grec (fun V number => \n              digit _           @ nat_of_ascii  \n           ||| !!!!number ^ digit _ @ (fun p => 10 * fst p + nat_of_ascii (snd p)))%grammar.\n\n  (* A parser for numbers:  number := digit | number digit *)\n  Definition number_p : parser_t number.\n    refine (gfix (fun (number:parser_t number) => \n                digit_p          @ nat_of_ascii\n             ||| number ^ digit_p @ (fun p => 10 * fst p + nat_of_ascii (snd p)))%parser).\n    unfold digit, gsatisfy. gtac. \n  Defined.\n\n  Definition tab : ascii := ascii_of_nat 9.\n  Definition cr : ascii := ascii_of_nat 10.\n\n  (* whitespace *)\n  Definition ws := \n    grec (fun V ws => \n              % tt\n          |||  (#\" \" ^ !!!!ws ||| #tab ^ !!!!ws ||| #cr ^ !!!!ws) @ (fun _ => tt))%grammar.\n\n  Definition ws_p : parser_t ws.\n    refine (gfix (fun (ws_p:parser_t ws) => \n                 % tt \n              ||| (#\" \" ^ ws_p ||| #tab ^ ws_p ||| #cr ^ ws_p) @ (fun _ => tt))%parser).\n    gtac.\n  Defined.\n      \n  (* A grammar for expressions that computes the result of evaluating the expression: \n     expr := number | expr + expr | expr - expr *)\n  Definition expr := \n    grec (fun V expr => \n              ws _ ^ number _ ^ ws _   @ (fun t => fst (snd t)) \n           ||| !!!!expr ^ #\"+\" ^ !!!!expr     @ (fun t => fst t + (snd (snd t)))\n           ||| !!!!expr ^ #\"-\" ^ !!!!expr     @ (fun t => fst t - (snd (snd t))))%grammar.\n\n  (* A parser for expressions *)\n  Definition expr_p : parser_t expr.\n    refine (gfix (fun (expr_p:parser_t expr) =>\n               ws_p ^ number_p ^ ws_p    @ (fun t => fst (snd t))\n            ||| expr_p ^ #\"+\" ^ expr_p    @ (fun t => fst t + (snd (snd t)))\n            ||| expr_p ^ #\"-\" ^ expr_p    @ (fun t => fst t - (snd (snd t))))%parser).\n    unfold number, digit, ws, gsatisfy ; gtac.\n  Defined.\n\nEnd Examples.\n", "meta": {"author": "Ptival", "repo": "ynot", "sha": "cd6f28816c41bbef7464b644edeba099d397a01e", "save_path": "github-repos/coq/Ptival-ynot", "path": "github-repos/coq/Ptival-ynot/ynot-cd6f28816c41bbef7464b644edeba099d397a01e/examples/Data/Parse2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.21843392700013367}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.floyd.VSU.\nRequire Import fastapile.\nRequire Import spec_stdlib.\nRequire Import spec_fastpile.\nRequire Import spec_fastpile_private.\nRequire Import spec_apile.\n\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\n\nSection Apile_VSU.\nVariable M: MallocFreeAPD.\nVariable PILEPRIV: FastpilePrivateAPD. (*apile is parametric in a PRIVATE pile predicate structure*)\n\nDefinition apile (sigma: list Z) (gv: globals) : mpred :=\n  pilerep PILEPRIV sigma (gv _a_pile).\n(*We define apile in terms of pilerep and then,\n  in the proof of make_apile below, use the axiom\n  spec_pile_private.pile_rep_exposed \n  to exploit the representation exposure*)\n\nLemma make_apile: forall gv, \n  globals_ok gv ->\n  data_at Ews tuint (Vint (Int.repr 0)) (gv apile._a_pile) |-- apile nil gv.\nProof.\nintros. unfold apile. rewrite pile_rep_exposed. (*HERE*) \nunfold fastprep.\n Exists 0.\n assert_PROP (headptr (gv _a_pile)) by entailer!.\n entailer!. \n unfold_data_at (data_at _ tpile _ _).\n rewrite field_at_data_at. simpl.\n rewrite field_compatible_field_address\n   by auto with field_compatible.\n simpl. normalize. rewrite data_at_tuint_tint.\nassert (change_composite_env CompSpecs FastpileCompSpecs).\n{ make_cs_preserve CompSpecs FastpileCompSpecs. }\nchange_compspecs FastpileCompSpecs.\napply derives_refl.\nQed.\n\nLemma apile_Init: VSU_initializer prog (apile nil).\n  Proof. \n    InitGPred_tac.  rewrite sepcon_emp.\n    apply make_apile; auto.\nQed.\n\n\nDefinition APILE: APileAPD := Build_APileAPD apile (*APileCompSpecs make_apile*).\n\nDefinition Apile_ASI: funspecs := ApileASI M APILE.\n\nDefinition apile_imported_specs:funspecs := \n     [ Pile_add_spec M PILEPRIV; Pile_count_spec PILEPRIV].\n\nDefinition apile_internal_specs: funspecs := Apile_ASI.\n\nDefinition ApileVprog: varspecs. mk_varspecs prog. Defined.\nDefinition ApileGprog: funspecs := apile_imported_specs ++ apile_internal_specs.\n\nLemma body_Apile_add: semax_body ApileVprog ApileGprog f_Apile_add (Apile_add_spec M APILE).\nProof.\nstart_function. \nsimpl spec_apile.apile. unfold apile.\nforward_call (gv _a_pile, n,sigma,gv).\nentailer!.\nQed.\n\nLemma body_Apile_count: semax_body ApileVprog ApileGprog f_Apile_count (Apile_count_spec M APILE).\nProof.\nstart_function.\nsimpl spec_apile.apile. unfold apile in *.\nforward_call (gv _a_pile, sigma).\nforward.\nQed.\n\nDefinition ApileVSU: @VSU NullExtension.Espec \n      nil apile_imported_specs ltac:(QPprog prog) Apile_ASI (apile nil).\n  Proof. \n    mkVSU prog apile_internal_specs.\n    + solve_SF_internal body_Apile_add.\n    + solve_SF_internal body_Apile_count.\n    + apply apile_Init.\n  Qed.\n\nEnd Apile_VSU.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/VSUpile/fast/verif_fastapile.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21838595333412192}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.client_lemmas.\nRequire Import VST.floyd.nested_field_lemmas.\nRequire Import VST.floyd.type_induction.\nRequire Import VST.floyd.reptype_lemmas.\nRequire Import VST.floyd.aggregate_type.\nRequire Import VST.floyd.sublist.\n\nSection PROJ_REPTYPE.\n\nContext {cs: compspecs}.\n\nDefinition proj_gfield_reptype (t: type) (gf: gfield) (v: reptype t): reptype (gfield_type t gf) :=\n  match t, gf return (REPTYPE t -> reptype (gfield_type t gf))\n  with\n  | Tarray t0 hi a, ArraySubsc i => fun v => Znth i v (default_val _)\n  | Tstruct id _, StructField i => fun v => proj_struct i (co_members (get_co id)) v (default_val _)\n  | Tunion id _, UnionField i => fun v => proj_union i (co_members (get_co id)) v (default_val _)\n  | _, _ => fun _ => default_val _\n  end (unfold_reptype v).\n\nFixpoint proj_reptype (t: type) (gfs: list gfield) (v: reptype t) : reptype (nested_field_type t gfs) :=\n  let res :=\n  match gfs as gfs'\n    return reptype (match gfs' with\n                    | nil => t\n                    | gf :: gfs0 => gfield_type (nested_field_type t gfs0) gf\n                    end)\n  with\n  | nil => v\n  | gf :: gfs0 => proj_gfield_reptype _ gf (proj_reptype t gfs0 v)\n  end\n  in eq_rect_r reptype res (nested_field_type_ind t gfs).\n\nEnd PROJ_REPTYPE.\n\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/floyd/proj_reptype_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21838594723196023}}
{"text": "From exercises Require Export safety.\n\n(** * Parametricity *)\nSection parametricity.\n  Context `{!heapG Σ}.\n\n  (** * The polymorphic identity function *)\n  Lemma identity_param `{!heapPreG Σ} e (v : val) σ w es σ' :\n    (∀ `{!heapG Σ}, ⊢ ∅ ⊨ e : ∀ A, A → A) →\n    rtc erased_step ([e <_> v]%E, σ) (of_val w :: es, σ') → w = v.\n  Proof.\n    intros He.\n    apply sem_gen_type_safety with (φ := λ u, u = v)=> ?.\n    pose (T := SemTy (λ w, ⌜w = v⌝)%I : sem_ty Σ).\n    exists T. split.\n    { by iIntros (?) \"?\". }\n    iIntros (vs) \"!# #Hvs\".\n    iPoseProof (He with \"Hvs\") as \"He /=\".\n    wp_apply (wp_wand with \"He\").\n    iIntros (u) \"#Hu\".\n    iSpecialize (\"Hu\" $! T).\n    wp_apply (wp_wand with \"Hu\"). iIntros (w') \"Hw'\". by iApply \"Hw'\".\n  Qed.\n\n  (** * Exercise (empty_type_param, easy) *)\n  Lemma empty_type_param `{!heapPreG Σ} e (v : val) σ w es σ' :\n    (∀ `{!heapG Σ}, ⊢ ∅ ⊨ e : ∀ A, A) →\n    rtc erased_step ([e <_>]%E, σ) (of_val w :: es, σ') →\n    False.\n  Proof.\n    (* exercise *)\n  Admitted.\n\n  (** * Exercise (boolean_param, moderate) *)\n  Lemma boolean_param `{!heapPreG Σ} e (v1 v2 : val) σ w es σ' :\n    (∀ `{!heapG Σ}, ⊢ ∅ ⊨ e : ∀ A, A → A → A) →\n    rtc erased_step ([e <_> v1 v2]%E, σ) (of_val w :: es, σ') → w = v1 ∨ w = v2.\n  Proof.\n    (* exercise *)\n  Admitted.\n\n  (** * Exercise (nat_param, hard) *)\n  Lemma nat_param `{!heapPreG Σ} e σ w es σ' :\n    (∀ `{!heapG Σ}, ⊢ ∅ ⊨ e : ∀ A, (A → A) → A → A) →\n    rtc erased_step ([e <_> (λ: \"n\", \"n\" + #1)%V #0]%E, σ)\n      (of_val w :: es, σ') → ∃ n : nat, w = #n.\n  Proof.\n    (* exercise *)\n  Admitted.\n\n  (** * Exercise (strong_nat_param, hard) *)\n  Lemma strong_nat_param `{!heapPreG Σ} e σ w es σ' (vf vz : val) φ :\n    (∀ `{!heapG Σ}, ∃ Φ : sem_ty Σ,\n      (⊢ ∅ ⊨ e : ∀ A, (A → A) → A → A) ∧\n      (∀ w, ⊢ {{{ Φ w }}} vf w {{{ w', RET w'; Φ w' }}}) ∧\n      (⊢ Φ vz) ∧\n      (∀ w, Φ w -∗ ⌜φ w⌝)) →\n    rtc erased_step ([e <_> vf vz]%E, σ) (of_val w :: es, σ') → φ w.\n  Proof.\n    (* exercise *)\n  Admitted.\nEnd parametricity.\n", "meta": {"author": "DKXXXL", "repo": "tutorial-popl20", "sha": "2f62762e179d3e0356ab89cd0d00fd10d6fbc3f1", "save_path": "github-repos/coq/DKXXXL-tutorial-popl20", "path": "github-repos/coq/DKXXXL-tutorial-popl20/tutorial-popl20-2f62762e179d3e0356ab89cd0d00fd10d6fbc3f1/exercises/parametricity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21838594723196023}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.field_loadstore.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nLocal Open Scope logic.\n\nLemma Znth_map: forall {A B} n xs d (f: A -> B),\n  Znth n (map f xs) (f d) = f (Znth n xs d).\nProof.\n  intros.\n  unfold Znth.\n  if_tac.\n  + reflexivity.\n  + apply map_nth.\nQed.\n\nLemma legal_Znth_map: forall {A B} n xs dA dB (f: A -> B),\n  0 <= n < Zlength xs ->\n  Znth n (map f xs) dB = f (Znth n xs dA).\nProof.\n  intros.\n  unfold Znth.\n  if_tac.\n  + omega.\n  + apply nth_map'.\n    rewrite Zlength_correct in H.\n    destruct H.\n    apply Z2Nat.inj_lt in H1; [ | omega | omega].\n    rewrite Nat2Z.id in H1.\n    exact H1.\nQed.\n\nDefinition t_struct_b := Tstruct _b noattr.\n\nDefinition sub_spec (sub_id: ident) :=\n DECLARE sub_id\n  WITH v : val * list (val*val) , p: val\n  PRE  []\n        PROP  (is_int I8 Signed (snd (nth 1%nat (snd v) (Vundef, Vundef))))\n        LOCAL (gvar _p p)\n        SEP   (data_at Ews t_struct_b v p)\n  POST [ tvoid ]\n        PROP() LOCAL()\n        SEP(data_at Ews t_struct_b (snd (nth 1%nat (snd v) (Vundef, Vundef)), snd v) p).\n\nDefinition sub_spec' (sub_id: ident) :=\n DECLARE sub_id\n  WITH v : reptype t_struct_b, p: val\n  PRE  []\n        PROP  (is_int I8 Signed (proj_reptype _ (DOT _y2 SUB 1 DOT _x2) v))\n        LOCAL (gvar _p p)\n        SEP   (data_at Ews t_struct_b v p)\n  POST [ tvoid ]\n        PROP() LOCAL()\n        SEP(data_at Ews t_struct_b\n           (upd_reptype t_struct_b (DOT _y1) v\n             (proj_reptype t_struct_b (StructField _x2 :: ArraySubsc 1 :: StructField _y2 :: nil) v))\n           p).\n\nLemma spec_coincide: sub_spec' = sub_spec.\nProof.\n(*reflexivity.*)\nAbort.\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [\n    sub_spec _sub1; sub_spec _sub2; sub_spec _sub3]).\n\nLemma body_sub1:  semax_body Vprog Gprog f_sub1 (sub_spec _sub1).\nProof.\n  unfold sub_spec.\n  start_function.\n  forward.\n  forward.\n  forward.\nQed.\n\nLemma body_sub2:  semax_body Vprog Gprog f_sub2 (sub_spec _sub2).\nProof.\n  unfold sub_spec.\n  start_function.\n  forward.\n  forward.\n  forward.\n  forward.\nQed.\n\nLemma body_sub3:  semax_body Vprog Gprog f_sub3 (sub_spec _sub3).\nProof.\n  unfold sub_spec.\n  start_function.\n  forward.\n  forward.\n  forward.\n  forward.\n  forward.\nQed.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/progs/verif_field_loadstore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21838594723196023}}
{"text": "(**\nCoLoR, a Coq library on rewriting and termination.\nSee the COPYRIGHTS and LICENSE files.\n\n- Adam Koprowski, 2006-04-27\n\nSome results concerning typing of terms of simply typed\nlambda-calculus are introduced in this file.\n*)\n\nSet Implicit Arguments.\n\nFrom Coq Require Import Eqdep_dec.\nFrom CoLoR Require Import RelExtras ListExtras LogicUtil.\nFrom CoLoR Require TermsDef.\n\nModule TermsTyping (Sig : TermsSig.Signature).\n\n  Module Export TD := TermsDef.TermsDef Sig.\n\n  Lemma baseType_dec : forall A, {isBaseType A} + {isArrowType A}.\n\n  Proof. destruct A; fo. Qed.\n\n  Lemma type_discr : forall A B, ~A = A --> B.\n\n  Proof.\n    induction A; unfold not; simpl; intros. discr.\n    unfold not in *. inversion H. eapply IHA1. apply H1.\n  Qed.\n\n  Lemma type_discr2 : forall A B C, ~A = (A --> B) --> C.\n\n  Proof.\n    induction A; unfold not; simpl; intros. discr.\n    unfold not in *. inversion H. eapply IHA1. apply H1.\n  Qed.\n\n(*Section Equality_Decidable.*)\n\n(* FIXME: eq_nat_dec has to be redefined here for the following Hint\nResolve, otherwise it does not work! *)\n  Lemma eq_nat_dec : forall (m n: nat), {m=n}+{m<>n}.\n\n  Proof. decide equality. Qed.\n\n  #[global] Hint Resolve eq_nat_dec : terms.\n\n  Lemma eq_SimpleType_dec : forall (A B: SimpleType), {A=B} + {A<>B}.\n\n  Proof. decide equality; auto with terms. Defined.\n\n  #[global] Hint Resolve eq_SimpleType_dec : terms.\n\n  Lemma eq_Env_dec : forall (E1 E2 : Env), {E1=E2} + {E1<>E2}.\n\n  Proof.\n    decide equality; generalize a o; decide equality; apply eq_SimpleType_dec.\n  Defined.\n\n  #[global] Hint Resolve eq_Env_dec : terms.\n\n  Lemma eq_Preterm_dec : forall (F G: Preterm), {F=G}+{F<>G}.\n\n  Proof. decide equality; auto with terms. Defined.\n\n  #[global] Hint Resolve eq_Preterm_dec : terms.\n\n  Lemma isVarDecl_dec : forall E x,\n    {A: SimpleType | E |= x := A} + {E |= x :!}.\n\n  Proof.\n    intros; unfold VarUD.\n    destruct (nth_error_In E x) as [[A ExA] | Exn].\n    destruct A.\n    left; exists s; trivial.\n    right; auto.\n    right; auto.\n  Defined.\n\n  Lemma eq_EPS_dec :\n    forall (a b : Env * Preterm * SimpleType), {a=b} + {a<>b}.\n\n  Proof.\n    decide equality.\n    apply eq_SimpleType_dec.\n    generalize a p; decide equality.\n    apply eq_Preterm_dec.\n    apply eq_Env_dec.\n  Defined.\n\n(*Section Typing.*)\n\n  Lemma VarD_unique : forall E x A (v1 v2 : VarD E x A), v1 = v2.\n\n  Proof.\n    unfold VarD; intros; generalize v1 v2; rewrite v1.\n    intros; apply K_dec_type; \n      [idtac |  pattern v0; apply K_dec_type]; \n      auto; decide equality; generalize a o; decide equality; \n      apply eq_SimpleType_dec.\n  Qed.\n\n  Lemma Type_unique : forall Pt E T1 T2 (d1 : Typing E Pt T1)\n    (d2 : Typing E Pt T2), T1 = T2.\n\n  Proof.\n    induction Pt; intros; inversion d1; \n      inversion d2; trivial.\n    unfold  VarD in * .\n    assert(Some (Some T1) = Some (Some T2)).\n    trans (nth_error E x); auto.\n    injection H7; trivial.\n    rewrite(@IHPt _ _ _ X X0); auto.\n    set(e0 := IHPt1 _ _ _ X X1); injection e0; auto.\n  Qed.\n\n  Lemma typing_unique : forall E Pt T (d1 d2 : Typing E Pt T), d1 = d2.\n\n  Proof.\n    refine(\n      fix Deriv_unique e t T (d1 d2 : Typing e t T) {struct d1}\n       : d1 = d2 :=\n      match d1 as d1' in Typing e1 t1 T1, \n\t    d2 as d2' in Typing e2 t2 T2 \n      return \n        forall (cast : (e1,t1,T1) = (e2,t2,T2)), \n          (e1,t1,T1) = (e,t,T) ->\n          eq_rect (e1,t1,T1) \n\t  (fun etT => \n\t     match etT with \n\t    (e,t,T) => Typing e t T \n\t    end) \n\t  d1' _ cast = d2'\n      with\n      | TVar _, TVar _ => _\n      | TFun _ _, TFun _ _ => _\n      | TAbs _, TAbs _ => _\n      | TApp _ _, TApp _ _ => _\n      | _, _ => _\n      end (eq_refl _) (eq_refl _));\n    intros; destruct t; try discr;\n    try discr cast; try discr dis;\n    injection cast; intros; gen cast; clear cast.\n\n    revert v v0.\n    rewrite H0; rewrite H1; rewrite H2.\n    intros; pattern cast; apply (K_dec_type eq_EPS_dec).\n    rewrite (VarD_unique v v0); apply eq_refl.\n\n    rewrite H1; rewrite H2.\n    intros; pattern cast; apply (K_dec_type eq_EPS_dec); \n      apply eq_refl.\n\n    revert t1.\n    rewrite <- H0; rewrite <- H1; rewrite <- H2; rewrite <- H4.\n    intros; pattern cast; apply (K_dec_type eq_EPS_dec).\n    rewrite(Deriv_unique _ _ _ t0 t1); apply eq_refl.\n\n    revert t2 t3.\n    rewrite <- H0; rewrite <- H1; rewrite <- H2; rewrite <- H3.\n    intros t2 t3.\n    intros; pattern cast; apply (K_dec_type eq_EPS_dec).\n    set(h1 := Type_unique t0 t2); injection h1; intro H7.\n    clear h1. revert t2 t3. rewrite <- H7.\n    intros; rewrite(Deriv_unique _ _ _ t0 t2); \n      rewrite(Deriv_unique _ _ _ t1 t3);\n    apply eq_refl.\n  Qed.\n\n  Lemma deriv_uniq : forall M N, env M = env N -> term M = term N ->\n    type M = type N -> M = N.\n\n  Proof.\n    intros [??? typingM] [??? typingN] H H0 H1; simpl in *.\n    revert typingM.\n    rewrite H; rewrite H0; rewrite H1.\n    intros.\n    rewrite(typing_unique typingM typingN).\n    apply eq_refl.\n  Qed.\n\n  Lemma typing_uniq : forall M N, env M = env N -> term M = term N ->\n    type M = type N.\n\n  Proof.\n    intros; destruct M as [??? typingM]; destruct N as [??? typingN]; simpl in *.\n    revert typingM.\n    rewrite H; rewrite H0; intros.\n    apply (Type_unique typingM typingN).\n  Qed.\n\n  Lemma term_eq : forall M N, env M = env N -> term M = term N -> M = N.\n\n  Proof.\n    intros; apply deriv_uniq; auto.\n    apply typing_uniq; auto.\n  Qed.\n\n  Lemma eq_Term_dec : forall (M N: Term), {M=N} + {M<>N}.\n\n  Proof.\n     intros M N.\n     case (eq_Env_dec M.(env) N.(env)); \n       case (eq_Preterm_dec M.(term) N.(term));\n       case (eq_SimpleType_dec M.(type) N.(type));\n       try solve [right; congruence].\n     left; apply deriv_uniq; trivial.\n  Qed.\n\n  #[global] Hint Resolve typing_uniq deriv_uniq term_eq : terms.\n\n(*Section Auto_Typing.*)\n  \n  Definition autoType : forall E Pt, {N: Term | env N = E & term N = Pt} + \n    {~exists N: Term, env N = E /\\ term N = Pt}.\n\n  Proof.\n    intros E Pt. revert Pt E. induction Pt; intro E.\n     (* -) variable *)\n    destruct (isVarDecl_dec E x) as [[A xt] | xut].\n     (*   - variable declared *)\n    left.\n    exists (buildT (TVar xt)); trivial. \n     (*   - variable undeclared *)\n    right.\n    intro abs; destruct abs as [T [T_env T_term]].\n    term_inv T.\n    unfold VarD in T0.\n    destruct xut; congruence.\n     (* -) function symbol *)\n    left.\n    assert (t: E |- ^f := f_type f).\n    constructor.\n    exists (buildT t); trivial.\n     (* -) abstraction *)\n    destruct (IHPt (decl A E)) as [[T T_env T_term] | Tne].\n     (*   - typable *)\n    left.\n    assert (t: E |- \\A => Pt := A --> type T).\n    constructor.\n    rewrite <- T_env.\n    rewrite <- T_term.\n    exact (typing T).\n    exists (buildT t); trivial.\n     (*   - no-typable *)\n    right.\n    intro Nt.\n    destruct Nt as [T [T_env T_term]].\n    absurd (exists N, env N = decl A E /\\ term N = Pt); trivial.\n    destruct T as [TE TPt TA TT].\n    inversion TT; simpl in *; try congruence.\n    exists (buildT X); split; simpl; congruence.\n     (* -) application *)\n    destruct (IHPt1 E) as [[Tl Tl_env Tl_term] | Tln].\n    destruct (IHPt2 E) as [[Tr Tr_env Tr_term] | Trn].\n    destruct Tl as [EL PtL AL TypL].\n    destruct Tr as [ER PtR AR TypR].\n    simpl in *.\n    destruct AL.\n     (*   - bad: left argument of simple type *)\n    right.\n    intro Tl; destruct Tl as [Tl [envL termL]].\n    destruct Tl as [EL' PtL' AL TypL'].\n    simpl in *.\n    rewrite termL in TypL'.\n    inversion TypL'.\n    assert (buildT X = buildT TypL).\n    apply term_eq; simpl; congruence.\n    absurd (A --> AL = #T).\n    discr.\n    eapply Type_unique. apply X.\n    rewrite envL; rewrite <- Tl_env; rewrite <- Tl_term; hyp.\n    destruct (eq_SimpleType_dec AL1 AR) as [AL1_AR | AL1_ne_AR].\n     (*   - all ok *)\n    left.\n    assert (t: E |- PtL @@ PtR := AL2).\n    constructor 4 with AL1.\n    rewrite <- Tl_env; trivial.\n    rewrite <- Tr_env; rewrite AL1_AR; trivial.\n    exists (buildT t); trivial.\n    simpl; congruence.\n     (*   - bad: types do not match *)\n    right.\n    intro Tl; destruct Tl as [Tl [envL termL]].\n    destruct Tl as [EL' PtL' AL TypL'].\n    simpl in *.\n    rewrite termL in TypL'.\n    inversion TypL'.\n    absurd (AL1 = AR).\n    trivial.\n    assert (type (buildT TypL) = type (buildT X)).\n    apply typing_uniq; simpl; congruence.\n    assert (type (buildT TypR) = type (buildT X0)).\n    apply typing_uniq; simpl; congruence.\n    simpl in *; congruence.\n     (*   - bad: right argument not typable *)\n    right.\n    intro Tr; destruct Tr as [Tr [envR termR]].\n    destruct Tr as [ER PtR AR TypR].\n    simpl in *.\n    rewrite termR in TypR.\n    inversion TypR.\n    apply Trn.\n    exists (buildT X0); auto.\n     (*   - bad: left argument not typable *)\n    right.\n    intro Tl; destruct Tl as [Tl [envL termL]].\n    destruct Tl as [EL PtL AL TypL].\n    simpl in *.\n    rewrite termL in TypL.\n    inversion TypL.\n    apply Tln.\n    exists (buildT X); auto.\n  Defined.\n\n  Definition typeTerm (E: Env) (Pt: Preterm) (T: SimpleType) : option Term.\n\n  Proof.\n     intros.\n     destruct (autoType E Pt) as [[W Wenv Wterm] | x].\n     destruct (eq_SimpleType_dec (type W) T).\n     exact (Some W).\n     exact None.\n     exact None.\n  Defined.\n\nModule TermsSet <: SetA.\n  Definition A := Term.\nEnd TermsSet.\n\nModule TermsEqset <: Eqset := Eqset_def TermsSet.\n\nModule TermsEqset_dec <: Eqset_dec.\n\n  Module Export Eq := TermsEqset.\n\n  Definition eqA_dec := eq_Term_dec.\n\nEnd TermsEqset_dec.\n\nLtac infer_tt :=\n  compute;\n    match goal with\n    | |- _ |- ?t := _ =>\n      match t with\n      | App _ _ => eapply TApp; infer_tt\n      | Abs _ _ => eapply TAbs; infer_tt\n      | Fun _ => intuition\n      | Var _ => eapply TVar; compute; trivial\n      end\n    end.\n\nEnd TermsTyping.\n", "meta": {"author": "fblanqui", "repo": "color", "sha": "f2ef98f7d13c5d71dd2a614ed2e6721703a34532", "save_path": "github-repos/coq/fblanqui-color", "path": "github-repos/coq/fblanqui-color/color-f2ef98f7d13c5d71dd2a614ed2e6721703a34532/Term/SimpleType/TermsTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21838594723196023}}
{"text": "From Perennial.goose_lang Require Import prelude.\nFrom Perennial.goose_lang Require Export ffi.grove_prelude.\nFrom Perennial.program_proof Require Import proof_prelude.\nFrom iris.algebra Require Export mono_nat.\nFrom Perennial.program_proof.grove_shared Require Import urpc_spec urpc_proof.\nFrom Perennial.program_proof Require Import marshal_proof.\nFrom Perennial.base_logic Require Import lib.ghost_map lib.saved_spec.\n\nSection interface.\n\nContext `{!inG Σ mono_natUR}.\n\nDefinition localhost : chan := U64 53021371269120.\n\nDefinition counter_lb γ (x:nat) : iProp Σ := own γ (◯MN x).\nDefinition counter_own γ (x:nat) : iProp Σ := own γ (●MN x).\n\nContext `{!urpcregG Σ}.\n\nContext `{HPRE: !gooseGlobalGS Σ}.\n\n(* HOCAP-style spec *)\nProgram Definition FAISpec (γ:gname) : savedSpecO Σ (list u8) (list u8) :=\n  λ reqData, λne (Φ : list u8 -d> iPropO Σ),\n  (\n      ∀ (x:nat), counter_own γ x ={⊤}=∗ counter_own γ (x + 1) ∗\n                                    (∀ l, ⌜has_encoding l [EncUInt64 x]⌝ -∗ Φ l)\n    )%I\n.\nNext Obligation.\n  solve_proper.\nDefined.\n\n(* TaDa-style spec *)\nProgram Definition FAISpec_tada (γ:gname) : savedSpecO Σ (list u8) (list u8) :=\n  λ reqData, λne (Φ : list u8 -d> iPropO Σ),\n  (\n       ∃ Eo Ei,\n       |={Eo,Ei}=> ∃ x, counter_own γ x ∗\n                      (counter_own γ (x+1) ={Ei,Eo}=∗ (∀ l, ⌜has_encoding l [EncUInt64 x]⌝ -∗ Φ l))\n    )%I\n.\n\nNext Obligation.\n  solve_proper.\nDefined.\n\nDefinition is_CtrServer_urpc γurpc_gn γ : iProp Σ :=\n  handler_spec γurpc_gn localhost 0 (FAISpec γ) ∗\n  handlers_dom (γurpc_gn) {[ U64 0 ]}.\n\nEnd interface.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/ctrexample/interface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.21837234723375448}}
{"text": "Require Import Classical Peano_dec Setoid PeanoNat.\nFrom hahn Require Import Hahn.\nRequire Import Lia.\n\nRequire Import Events.\nRequire Import Execution.\nRequire Import Execution_eco.\nRequire Import imm_bob.\nRequire Import imm_s.\nRequire Import imm_s_ppo.\nRequire Import imm_s_rfppo.\nRequire Import AuxDef.\nRequire Import SetSize.\nRequire Import FairExecution.\nRequire Import AuxRel2.\nRequire Import travorder.TraversalOrder.\nRequire Import travorder.TLSCoherency.\nRequire Import travorder.IordCoherency.\nRequire Import travorder.SimClosure.\nRequire Import AuxRel2.\nRequire Import ImmFair.\nRequire Import EnumPrefix.\nRequire Import FinThreads. \n\nImport ListNotations.\n\nSet Implicit Arguments.\n\nSection IordTraversal. \n  Variable (G: execution) (sc: relation actid). \n  Implicit Types (WF : Wf G) (COMP : complete G)\n         (WFSC : wf_sc G sc) (CONS : imm_consistent G sc)\n         (MF : mem_fair G).\n\n  Notation \"'sb'\" := (sb G).\n  Notation \"'rmw'\" := (rmw G).\n  Notation \"'data'\" := (data G).\n  Notation \"'addr'\" := (addr G).\n  Notation \"'ctrl'\" := (ctrl G).\n  Notation \"'rf'\" := (rf G).\n  Notation \"'co'\" := (co G).\n  Notation \"'coe'\" := (coe G).\n  Notation \"'fr'\" := (fr G).\n\n  Notation \"'fwbob'\" := (fwbob G).\n  Notation \"'ppo'\" := (ppo G).\n  Notation \"'ar'\" := (ar G sc).\n  Notation \"'fre'\" := (fre G).\n  Notation \"'rfi'\" := (rfi G).\n  Notation \"'rfe'\" := (rfe G).\n  Notation \"'deps'\" := (deps G).\n  Notation \"'detour'\" := (detour G).\n\n  Notation \"'lab'\" := (lab G).\n  Notation \"'loc'\" := (loc lab).\n  Notation \"'val'\" := (val lab).\n  Notation \"'mod'\" := (Events.mod lab).\n  Notation \"'same_loc'\" := (same_loc lab).\n  \n  Notation \"'E'\" := (acts_set G).\n  Notation \"'R'\" := (fun x => is_true (is_r lab x)).\n  Notation \"'W'\" := (fun x => is_true (is_w lab x)).\n  Notation \"'F'\" := (fun x => is_true (is_f lab x)).\n  Notation \"'Sc'\" := (fun x => is_true (is_sc lab x)).\n  Notation \"'RW'\" := (R ∪₁ W).\n  Notation \"'FR'\" := (F ∪₁ R).\n  Notation \"'FW'\" := (F ∪₁ W).\n  Notation \"'R_ex'\" := (fun a => is_true (R_ex lab a)).\n  Notation \"'W_ex'\" := (W_ex G).\n  Notation \"'W_ex_acq'\" := (W_ex ∩₁ (fun a => is_true (is_xacq lab a))).\n\n  Notation \"'iord'\" := (iord G sc). \n  Notation \"'SB'\" := (SB G sc). \n  Notation \"'RF'\" := (RF G). \n  Notation \"'AR'\" := (AR G sc). \n  Notation \"'FWBOB'\" := (FWBOB G).\n\n  Section IordEnum.\n    (* This generalization is used to support traversal \n       of both complete exec_tls and its parts *)\n\n  Variable (steps: nat -> trav_label).\n  Variable (dom: trav_label -> Prop).\n  Hypothesis (IORD_DOM: iord ⊆ dom × dom).\n  Hypothesis (DOM_EXEC: dom ⊆₁ exec_tls G). \n  Hypothesis (ENUM: enumerates steps dom).\n  Hypothesis (RESP: respects_rel steps iord⁺ dom).\n\n  Lemma trav_prefix_in_exec_tls i\n        (DOMi: NOmega.le (NOnum i) (set_size dom)):\n    trav_prefix steps i ⊆₁ exec_tls G. \n  Proof using ENUM DOM_EXEC. \n    apply enumeratesE' in ENUM. cdes ENUM. \n    unfold trav_prefix. apply set_subset_bunion_l. intros.\n    rewrite <- DOM_EXEC. apply set_subset_single_l. apply INSET.\n    liaW (set_size dom). \n  Qed.\n\n  Lemma trav_prefix_step\n        i (DOMsi: NOmega.lt_nat_l i (set_size dom)):\n    iord_step G sc (trav_prefix steps i) (trav_prefix steps (S i)).\n  Proof using RESP ENUM IORD_DOM.\n    red. exists (steps i). do 2 red.\n    splits; try by (red; eapply trav_prefix_r_closed; eauto; liaW (set_size dom)).\n    apply seq_eqv_l. split.\n    { eapply prefix_border; eauto. }\n    eapply trav_prefix_ext; eauto.\n  Qed.\n\n  Definition tc_enum (i: nat): trav_label -> Prop  :=\n    sim_clos G (trav_prefix steps i) ∪₁ init_tls G. \n  \n  (* TODO: group similar lemmas about union with init_tls *)\n  Lemma trav_prefix_init_tls_iord_coherent i\n        (DOMi : NOmega.le (NOnum i) (set_size dom)):\n    iord_coherent G sc (trav_prefix steps i ∪₁ init_tls G).\n  Proof using RESP IORD_DOM ENUM.\n    red. rewrite id_union, seq_union_r, dom_union.\n    apply set_subset_union_l. split.\n    { apply set_subset_union_r. left. eapply trav_prefix_r_closed; eauto. }\n    unfold \"iord\". rewrite init_tls_EI at 1. basic_solver.\n  Qed.\n\n  Lemma tc_enum_tls_coherent WF i\n      (DOMi: NOmega.le (NOnum i) (set_size dom)):\n    tls_coherent G (tc_enum i). \n  Proof using ENUM DOM_EXEC.\n    unfold tc_enum. split; [basic_solver| ].\n    apply set_subset_union_l. split; [| basic_solver].\n    erewrite sim_clos_mori.\n    2: { apply trav_prefix_in_exec_tls; eauto. }\n    pose proof (exec_tls_sim_coh WF). red in H. rewrite <- H. basic_solver. \n  Qed.\n\n  Lemma trav_prefix_union_init_tls_coherent WF i\n      (DOMi: NOmega.le (NOnum i) (set_size dom)):\n    tls_coherent G (trav_prefix steps i ∪₁ init_tls G). \n  Proof using ENUM DOM_EXEC. \n    apply tls_coherent_defs_equiv. exists (trav_prefix steps i).\n    split; [| basic_solver]. now apply trav_prefix_in_exec_tls.\n  Qed. \n\n  Lemma trav_prefix_step_ext\n        i (DOMsi: NOmega.lt_nat_l i (set_size dom)):\n    iord_step G sc (trav_prefix steps i ∪₁ init_tls G)\n              (trav_prefix steps (S i) ∪₁ init_tls G). \n  Proof using RESP IORD_DOM ENUM DOM_EXEC. \n    forward eapply trav_prefix_step as [l STEP]; eauto.\n    red. exists l. do 2 red.\n    splits; try by (apply trav_prefix_init_tls_iord_coherent; liaW (set_size dom)).\n    do 2 red in STEP. desc. apply seq_eqv_l in STEP. desc.  \n    apply seq_eqv_l. split.\n    2: { rewrite STEP2. basic_solver. }\n    apply set_compl_union. split; auto.\n    apply set_disjoint_eq_r. eapply set_disjoint_mori; [reflexivity| ..].\n    2: by apply init_exec_tls_disjoint.\n    red. rewrite <- DOM_EXEC.\n    forward eapply @trav_prefix_in_dom with (i := S i) as XX; eauto.\n    rewrite <- XX. rewrite STEP2. basic_solver. \n  Qed. \n\n  Lemma sim_traversal_next WF CONS:\n    forall i (DOMi: NOmega.lt_nat_l i (set_size dom)),\n      (sim_clos_step G sc)^* (tc_enum i) (tc_enum (1 + i)). \n  Proof using RESP ENUM IORD_DOM DOM_EXEC.\n    ins. unfold tc_enum.\n    forward eapply init_tls_sim_coh as INIT_SCOH; eauto. red in INIT_SCOH.\n    rewrite INIT_SCOH, <- !sim_clos_dist; auto.  \n    apply iord_step_implies_sim_clos_step; auto.\n    red. splits; try by (apply trav_prefix_union_init_tls_coherent; liaW (set_size dom)). \n    apply trav_prefix_step_ext; auto. \n  Qed.\n\n  End IordEnum. \n\n  Lemma iord_enum_exists WF COMP WFSC CONS MF\n        (IMM_FAIR: imm_s_fair G sc)\n        (TB: fin_threads G)\n        dom:\n  exists (steps: nat -> trav_label),\n    enumerates steps dom /\\\n    respects_rel steps iord⁺ dom. \n  Proof using.\n    edestruct countable_ext with (s := dom) (r := ⦗event ↓₁ (set_compl is_init)⦘ ⨾ iord⁺)\n      as [| [steps [ENUM RESP]]].\n    { eapply countable_subset; [| by apply set_subset_full_r].\n      apply trav_label_countable. }\n    { red. split.\n      { rewrite inclusion_seq_eqv_l. by apply iord_acyclic. }\n      red. intros ? ? ? ?%seq_eqv_l  ?%seq_eqv_l. desc.\n      apply seq_eqv_l. split; auto. eapply transitive_ct; eauto. }\n    { eapply iord_ct_fsupp; eauto. }\n    { edestruct H. constructor. econstructor; vauto. }\n    exists steps. splits; eauto.\n    red. ins. apply RESP; auto.\n    1, 2: by apply set_lt_size.\n    apply seq_eqv_l. split; auto.\n    apply enumeratesE' in ENUM. desc. apply INSET in DOMi.\n    apply ct_begin in Rij. generalize Rij. unfold iord. basic_solver. \n  Qed.\n\n  Lemma sim_traversal_inf WF CONS\n        (FAIR: mem_fair G)\n        (IMM_FAIR: imm_s_fair G sc)\n        (TB: fin_threads G)\n        (dom: trav_label -> Prop)\n        (IORD_DOM: iord ⊆ dom × dom)\n        (DOM_EXEC: dom ⊆₁ exec_tls G)\n        (DOM_COVERS: eq ta_cover <*> (E \\₁ is_init) ⊆₁ dom)\n        (DOM_SIM_CLOSURE: forall (S: trav_label -> Prop) (S_DOM: S ⊆₁ dom),\n            (@sim_clos G S) ⊆₁ dom):\n    exists (sim_enum: nat -> (trav_label -> Prop)),\n      ⟪INIT: sim_enum 0 ≡₁ init_tls G ⟫ /\\\n      ⟪COH: forall i (DOMi: NOmega.le (NOnum i) (set_size dom)),\n          tls_coherent G (sim_enum i)⟫ /\\\n      ⟪STEPS: forall i (DOMi: NOmega.lt_nat_l i (set_size dom)),\n          (sim_clos_step G sc)^* (sim_enum i) (sim_enum (1 + i)) ⟫ /\\\n      ⟪ENUM: forall e (Ee: (E \\₁ is_init) e), exists i,\n           NOmega.le (NOnum i) (set_size dom) /\\\n             (sim_enum i) (mkTL ta_cover e)⟫ /\\\n      ⟪DOM: forall i (DOMi: NOmega.le (NOnum i) (set_size dom)),\n          sim_enum i ⊆₁ init_tls G ∪₁ dom⟫.\n  Proof using.\n    edestruct iord_enum_exists as [steps_enum [ENUM RESP]]; eauto.\n    1, 2: by apply CONS.\n    exists (tc_enum steps_enum). splits.\n    { unfold tc_enum. rewrite trav_prefix_init.\n      rewrite sim_clos_empty. basic_solver. }\n    { apply tc_enum_tls_coherent; eauto. }\n    { apply sim_traversal_next; auto. }\n    { intros e Ee.\n      pose proof ENUM as ENUM'. apply enumeratesE' in ENUM. desc.\n      specialize (IND (mkTL ta_cover e)). specialize_full IND. \n      { apply DOM_COVERS. vauto. } \n      desc. exists (S i). split; [by vauto| ].  \n      eapply set_equiv_exp. \n      { unfold tc_enum. rewrite trav_prefix_ext; eauto. }\n      rewrite IND0. unfold sim_clos. basic_solver 10.  }\n    ins. unfold tc_enum. rewrite set_unionC. apply set_subset_union; [done| ]. \n    rewrite <- DOM_SIM_CLOSURE; [reflexivity| ]. \n    eapply trav_prefix_in_dom; eauto.\n  Qed.\n\n  Lemma sim_traversal_inf_cip WF CONS\n        (FAIR: mem_fair G)\n        (IMM_FAIR: imm_s_fair G sc)\n        (TB: fin_threads G) :\n    exists (sim_enum: nat -> (trav_label -> Prop)),\n      ⟪INIT: sim_enum 0 ≡₁ init_tls G ⟫ /\\\n      ⟪COH: forall i (DOMi: NOmega.le (NOnum i) (set_size (exec_tls_cip G))),\n          tls_coherent G (sim_enum i)⟫ /\\\n      ⟪STEPS: forall i (DOMi: NOmega.lt_nat_l i (set_size (exec_tls_cip G))),\n          (sim_clos_step G sc)^* (sim_enum i) (sim_enum (1 + i)) ⟫ /\\\n      ⟪ENUM: forall e (Ee: (E \\₁ is_init) e), exists i,\n           NOmega.le (NOnum i) (set_size (exec_tls_cip G)) /\\\n             (sim_enum i) (mkTL ta_cover e)⟫ /\\\n      ⟪DOM: forall i (DOMi: NOmega.le (NOnum i) (set_size (exec_tls_cip G))),\n          sim_enum i ⊆₁ init_tls G ∪₁ exec_tls_cip G⟫.\n  Proof using.\n    forward eapply sim_traversal_inf with (dom := exec_tls_cip G) as TRAV; eauto.\n    { apply dom_helper_3. rewrite <- restr_relE. apply iord_exec_tls_cip. }\n    { unfold exec_tls_cip, exec_tls. rewrite !set_pair_alt. basic_solver 10. }\n    { unfold exec_tls_cip, exec_tls. rewrite !set_pair_alt. basic_solver 10. }\n    ins. rewrite exec_tls_cip_alt, set_minusE. apply set_subset_inter_r. split.\n    { apply sim_clos_exec_tls; auto. rewrite S_DOM.\n      rewrite exec_tls_cip_alt. basic_solver. }\n    unfold sim_clos. repeat (apply set_subset_union_l; split).\n    2, 3: unfold rmw_clos, rel_clos; iord_dom_solver. \n    rewrite S_DOM, exec_tls_cip_alt. basic_solver. \n  Qed.\n\n  Lemma sim_traversal_inf_full WF CONS\n        (FAIR: mem_fair G)\n        (IMM_FAIR: imm_s_fair G sc)\n        (TB: fin_threads G) :\n    exists (sim_enum: nat -> (trav_label -> Prop)),\n      ⟪INIT: sim_enum 0 ≡₁ init_tls G ⟫ /\\\n      ⟪COH: forall i (DOMi: NOmega.le (NOnum i) (set_size (exec_tls G))),\n          tls_coherent G (sim_enum i)⟫ /\\\n      ⟪STEPS: forall i (DOMi: NOmega.lt_nat_l i (set_size (exec_tls G))),\n          (sim_clos_step G sc)^* (sim_enum i) (sim_enum (1 + i)) ⟫ /\\\n       ⟪ENUM: forall e (Ee: (E \\₁ is_init) e), exists i,\n           NOmega.le (NOnum i) (set_size (exec_tls G)) /\\\n             (sim_enum i) (mkTL ta_cover e)⟫.\n  Proof using.\n    forward eapply sim_traversal_inf with (dom := exec_tls G) as TRAV; eauto.\n    { rewrite iord_exec_tls. basic_solver. }\n    { unfold exec_tls. basic_solver. }\n    { ins. apply sim_clos_exec_tls; auto. }\n    desc. eexists. splits; eauto. \n  Qed.\n\nEnd IordTraversal.\n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/travorder/SimIordTraversal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241911813149, "lm_q2_score": 0.34864514210180597, "lm_q1q2_score": 0.21829515760778787}}
{"text": "(*\n  This file is part of the verified smart contract project of SECBIT Labs.\n\n  Copyright 2018 SECBIT Labs\n\n  This program is free software: you can redistribute it and/or\n  modify it under the terms of the GNU Lesser General Public License\n  as published by the Free Software Foundation, either version 3 of\n  the License, or (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public License\n  along with this program.  If not, see <https://www.gnu.org/licenses/>.\n*)\n\nRequire Export Lists.List.\nRequire Import Model.\nRequire Import Spec.\nRequire Export Arith.\n\n(*\n  High-level properties implied by the ERC20 spec in Spec.v.\n\n  1) Fixed total supply: in any step of any execution, the sum of all balances\n     always equal to totalSupply:\n\nTheorem Property_totalSupply_fixed :\n  forall env0 env msg ml C E C' E',\n    create env0 msg C E\n    -> env_step env0 env\n    -> run env C ml C' E'\n    -> Sum (st_balances (w_st C')) (st_totalSupply (w_st C')).\n\n *)\n\n(* Definition of sum of mapping *)\nInductive Sum : (@tmap address value) -> value -> Prop :=\n | Sum_emp : Sum tmap_emp 0\n | Sum_add : forall m v a' v',\n     Sum m v\n     -> m a' = 0\n     -> Sum (m $+ {a' <- v'}) (v + v')\n | Sum_del : forall m v a',\n     Sum m v\n     -> Sum (m $+ {a' <- 0}) (v - (m a')).\n\nFixpoint sum (m: @tmap address value) (al: list address) : value :=\n  match al with\n  | nil => 0\n  | cons a al' => (m a) + sum m al'\n  end.\n\nOpen Scope list_scope.\n\nSection List.\n\n  Context  `{A: Type}.\n\n  Context `{BEq A}.\n\n  Fixpoint list_in (a: A) (al: list A) : bool :=\n    match al with\n    | nil => false\n    | cons a' al' => if beq a a' then true\n                     else list_in a al'\n  end.\n\nFixpoint no_repeat (al: list A) : bool :=\n  match al with\n  | nil => true\n  | cons a' al' => andb (negb (list_in a' al')) (no_repeat al')\n  end.\n\nEnd List.\nOpaque beq.\n\nLemma sum_emp : forall al,\n    sum $0 al  = 0.\nProof.\n  intros.\n  induction al.\n  simpl. trivial.\n  simpl. apply IHal.\nQed.\n\nLemma sum_del_none : forall al m a,\n    list_in a al = false\n    -> no_repeat al = true\n    -> sum (m $+ {a <- 0}) al  = sum m al.\nProof.\n  induction al.\n    intros m a Hin Hnr.\n    simpl.\n    trivial.\n  intros m a' Hin' Hnr.\n  simpl in Hin'.\n  simpl.\n  decbeq a a'; tmap_simpl.\n  simpl in Hnr.\n  desb Hnr as [Hnr1 Hnr2].\n  rewrite (IHal m a' Hin' Hnr2).\n  trivial.\nQed.\n\nLemma sum_del_any : forall al m a,\n    list_in a al = true\n    -> no_repeat al = true\n    -> m a + sum (m $+ {a <- 0}) al  = sum m al.\nProof.\n  induction al.\n    intros m a Hin Hnr.\n    simpl in Hin.\n    discriminate.\n  intros m a' Hin' Hnr.\n  simpl in Hin'.\n  destruct (beq_dec a a').\n    simplbeq.\n    simpl.\n    simpl in Hnr.\n    desb Hnr as [Hnr1 Hnr2].\n    simpltm.\n    assert (a = a').\n      beq_elimH H.\n      trivial.\n    subst a'.\n    simplb.\n    rewrite sum_del_none; trivial.\n  simpl.\n  simplbeq.\n  tmap_simpl.\n  simpl in Hnr.\n  desb Hnr as [Hnr1 Hnr2].\n  rewrite <- (IHal m a' Hin' Hnr2).\n  omega.\nQed.\n\nLemma minus_minus: forall t a b,\n      t - a - b = t - (a + b).\nProof.\n  intros.\n  omega.\nQed.\n\nLemma sum_add_not_in : forall al m a v,\n    list_in a al = false\n    -> no_repeat al = true\n    -> sum (m $+ {a <- v}) al  = sum m al.\nProof.\n  induction al.\n    intros m a v Hin Hnr.\n    simpl.\n    trivial.\n  intros m a' v' Hin' Hnr.\n  simpl in Hin'.\n  simpl in Hnr.\n  desb Hnr as [Hnr1 Hnr2].\n  simplb.\n  decbeq a a'; tmap_simpl.\n  simpl.\n  simpltm.\nQed.\n\nLemma sum_add_in : forall al m a v,\n    list_in a al = true\n    -> no_repeat al = true\n    -> m a = 0\n    -> sum (m $+ {a <- v}) al  = sum m al + v.\nProof.\n  induction al.\n    intros m a v Hin Hnr Hma.\n    simpl in Hin.\n    discriminate.\n  intros m a' v' Hin' Hnr Hma.\n  simpl in Hin'.\n  simpl in Hnr.\n  desb Hnr as [Hnr1 Hnr2].\n  decbeq a a'; simpl; simpltm.\n    simplb.\n    beq_elimH Hb.\n    subst a'.\n    rewrite sum_add_not_in; auto.\n    rewrite Hma; simpl; trivial.\n    auto with arith.\n  simplb.\n  rewrite (IHal m a' v' Hin' Hnr2 Hma).\n  auto with arith.\nQed.\n\nLemma Sum_ge_strong : forall m t,\n    Sum m t\n    -> forall a al,\n      list_in a al = false\n      -> no_repeat al = true\n      -> t >= m a + sum m al.\nProof.\n  intros m t H.\n  induction H.\n  - intros a al Hal Hnr.\n    simpltm.\n    rewrite sum_emp.\n    auto with arith.\n  - intros a al Hal Hnr.\n    decbeq a a'.\n      simpltm.\n      substH IHSum with (IHSum a al Hal Hnr).\n      beq_elimH Hb.\n      subst a'.\n      rewrite H0 in IHSum.\n      rewrite (sum_add_not_in _ _ _ _ Hal Hnr).\n      omega.\n    simpltm.\n    substH IHSum with (IHSum a al Hal Hnr).\n    assert (Hx: list_in a' al = true \\/ list_in a' al = false).\n      destruct (list_in a' al); [left | right]; trivial.\n    destruct Hx as [Hx | Hx].\n      rewrite (sum_add_in _ _ _ _ Hx Hnr H0).\n      omega.\n    rewrite (sum_add_not_in _ _ _ _ Hx Hnr).\n    omega.\n  - intros a al' Hnin Hnr.\n    decbeq a a'.\n      tmap_simpl.\n      beq_elimH Hb.\n      subst a'.\n      rewrite (sum_add_not_in _ _ _ _ Hnin Hnr).\n      substH IHSum with (IHSum a al' Hnin Hnr).\n      omega.\n    assert (Hx: list_in a' al' = true \\/ list_in a' al' = false).\n      destruct (list_in a' al'); [left | right]; trivial.\n    destruct Hx as [Hx | Hx].\n      tmap_simpl.\n      assert (Hy:=sum_del_any al' m a' Hx Hnr).\n      substH IHSum with (IHSum a al' Hnin Hnr).\n      rewrite <- Hy in IHSum.\n      assert (Hxx: forall a b c d,\n          a >= b + (c + d)\n          -> a - c >=  b + d).\n        clear.\n        intros.\n        omega.\n      apply Hxx; trivial.\n    tmap_simpl.\n    rewrite sum_del_none; auto.\n    assert (Hy: v >= m a + sum m (a' :: al')).\n      apply IHSum; trivial.\n        simpl.\n        simplbeq.\n        trivial.\n      simpl.\n      rewrite Hx.\n      simpl.\n      trivial.\n    simpl in Hy.\n    omega.\nQed.\n\nLemma Sum_ge : forall m a t,\n        Sum m t\n        -> t >= m a.\nProof.\n  intros.\n  assert (Hx:= Sum_ge_strong _ _ H a nil).\n  simpl in Hx.\n  substH Hx with (Hx (eq_refl _) (eq_refl _)).\n  omega.\nQed.\n\nLemma Sum_ge_2 : forall m a a' t,\n        Sum m t\n        -> beq a a' = false\n        -> t >= m a + m a'.\nProof.\n  intros.\n  assert (Hx:= Sum_ge_strong _ _ H a (a'::nil)).\n  simpl in Hx.\n  rewrite H0 in Hx.\n  assert (m a + m a' =m a + (m a' + 0)). omega.\n  rewrite <- H1 in Hx.\n  apply Hx.\n  trivial. trivial.\nQed.\n\nLemma Sum_sig :\n  forall m a t,\n    m = $0 $+ { a <- t }\n    -> Sum m t.\nProof.\n  intros m a t Hm.\n  rewrite Hm.\n  assert (t = 0 + t).\n    auto with arith.\n  rewrite H at 2.\n  constructor 2.\n    constructor 1.\n  simpltm.\n  trivial.\nQed.\n\n\nLtac arith_rewrite t :=\n  let H := fresh \"Harith\" in\n  match t with\n  | ?x = ?y => assert (H: t); [auto with arith; try omega | rewrite H; clear H]\n  end.\n\nLemma Sum_dec : forall m t a (v: value),\n        Sum m t\n        -> m a >= v\n        -> Sum  (m $+ {a <- -= v}) (t - v).\nProof.\n  unfold a2v_upd_dec.\n  intros m t a v H.\n  generalize dependent v.\n  generalize dependent a.\n  induction H.\n  + intros.\n    simpl in H.\n    assert (v = 0).\n      unfold value in * .\n      omega.\n    simpl.\n    assert ($0 $+ {a <- (0:value)} = $0).\n      simpl.\n      apply tmap_extensionality.\n      intro a'.\n      decbeq a a'.\n      rewrite (tmap_get_upd_eq2 $0 a a' (0:value)); auto.\n      tmap_simpl.\n      assert(Ht: minus_with_underflow 0 v = 0 - v).\n      apply minus_safe; trivial.\n      rewrite Ht.\n      rewrite H0.\n      assert(Hm: 0 - 0 = 0);auto.\n      rewrite Hm.\n    rewrite H1.\n    constructor 1.\n  + intros a v2 H1.\n    decbeq a a'.\n      tmap_simpl.\n      beq_elimH Hb.\n      subst a'.\n      assert(Ht: minus_with_underflow v' v2 = v' - v2).\n      apply minus_safe; trivial.\n      rewrite Ht.\n      arith_rewrite (v + v' - v2 = v + (v' - v2)).\n      constructor 2; trivial.\n    simpltm.\n    rewrite (tmap_upd_upd_ne); simplbeq; auto.\n    assert (Hx : v + v' - v2 = v - v2 + v').\n       assert (v >= m a). apply Sum_ge. apply H.\n       assert (v >= v2). omega.\n       unfold value in *. omega.\n    rewrite Hx.\n    constructor; trivial.\n      apply IHSum; trivial.\n    simpltm.\n  + intros a v0 H1.\n    decbeq a a'.\n      simpltm.\n      assert (v0 = 0).\n        unfold value in *. omega.\n      subst v0.\n      simpl.\n      simpltm.\n      beq_elimH Hb.\n      subst a'.\n      assert (Hx: v - m a - 0 = v - m a).\n        unfold value in *. omega.\n      rewrite Hx.\n      constructor; trivial.\n    simpltm.\n    rewrite (tmap_upd_upd_ne); simplbeq; auto.\n    assert (Hx: v - m a' - v0 = v - v0 - m a').\n       unfold value in *. omega.\n    rewrite Hx.\n    assert (Hm: m a' = (m $+ {a <- minus_with_underflow (m a) v0}) a').\n    simpltm.\n    rewrite Hm.\n    constructor 3.\n    apply IHSum; trivial.\nQed.\n\nLemma Sum_inc : forall m t a (v: value),\n        Sum m t\n        -> m a <= MAX_UINT256 - v\n        -> Sum  (m $+ {a <- += v}) (t + v).\nProof.\n  unfold a2v_upd_inc.\n  intros m t a v H Hlt.\n  generalize dependent v.\n  generalize dependent a.\n  induction H.\n  +  intros.\n     simpltm.\n     assert (plus_with_overflow TMap.zero v = v).\n     apply plus_safe_lhs0; auto.\n     rewrite H.\n     constructor 2; auto; try constructor.\n  + intros a v2 Hlt.\n    decbeq a a'.\n      tmap_simpl.\n      beq_elimH Hb.\n      subst a'.\n      arith_rewrite (v + v' + v2 = v + (v' + v2)).\n      rewrite (plus_safe_lt v' v2); trivial.\n      constructor 2; trivial.\n    simpltm.\n    substH IHSum with (IHSum a v2).\n    rewrite (tmap_upd_upd_ne); simplbeq; auto.\n    arith_rewrite (v + v' + v2 = v + v2 + v').\n    constructor 2; auto.\n    simpltm.\n  + intros a v0.\n    decbeq a a'.\n      beq_elimH Hb.\n      subst a'.\n      assert (plus_with_overflow ((m $+ {a <- 0}) a)  v0 = v0).\n        rewrite tmap_get_upd_eq.\n        rewrite plus_safe_lhs0; trivial.\n      rewrite H0.\n      constructor 2.\n      constructor 3.\n      trivial.\n      simpltm.\n  simpltm.\n  rewrite (tmap_upd_upd_ne); simplbeq; auto.\n  assert (Hx: v - m a' + v0 = v + v0 - m a').\n    assert (Hy: v >= m a').\n      apply (Sum_ge m a' v); trivial.\n    omega.\n  rewrite Hx.\n  assert (m a' = m $+ {a <- plus_with_overflow (m a) v0} a').\n    simpltm.\n  rewrite H0.\n  constructor 3.\n  apply IHSum; trivial.\nQed.\n\nLemma a2v_upd_inc_zero : forall m a,\n        m $+ {a <- += 0} = m.\nProof.\n  unfold a2v_upd_inc.\n  intros.\n  rewrite(plus_safe_rhs0 (m a) 0); trivial.\n  assert (Hx : m a + 0 = m a).\n    unfold value in *. omega.\n  rewrite Hx.\n  tmap_simpl.\nQed.\n\nLemma a2v_upd_dec_zero : forall m a,\n        m $+ {a <- -= 0} = m.\nProof.\n  unfold a2v_upd_dec.\n  intros.\n  rewrite(minus_safe (m a) 0).\n  assert (Hx : m a - 0 = m a).\n    unfold value in *. omega.\n  rewrite Hx.\n  tmap_simpl.\n  omega.\nQed.\n\nLemma ge_sub_inc: forall a b,\n    a >= b -> a = a - b + b.\nProof.\n  intros.\n  omega.\nQed.\n\nLemma Sum_transfer : forall m t a1 a2 v m',\n        Sum m t\n        -> m a1 >= v\n        -> m a2 <= MAX_UINT256 - v\n        -> m' = m $+{a1 <- -= v} $+{a2 <- += v}\n        -> Sum m' t.\nProof.\n  intros.\n  decbeq a1 a2.\n  + beq_elimH Hb.\n    subst a2.\n    rewrite H2.\n    assert (Ht: t = t - v + v).\n      assert (Ht1 : t >= m a1).\n        apply Sum_ge; trivial.\n      assert (Ht2 : t >= v).\n        omega.\n      clear - Ht2.\n      unfold value in t.\n      eapply ge_sub_inc; eauto.\n    rewrite Ht.\n    eapply Sum_inc; eauto.\n    eapply Sum_dec; eauto.\n    unfold a2v_upd_dec.\n    rewrite (tmap_get_upd_eq m a1 _).\n    rewrite(minus_safe (m a1) v); auto.\n    omega.\n  + remember (m a1) as Ha1.\n    remember (m a2) as Ha2.\n    rewrite HeqHa1 in H0.\n    destruct Ha1.\n      assert (Hv : v = 0).\n        rewrite <- HeqHa1 in H0.\n        auto with arith.\n      subst v.\n      rewrite a2v_upd_dec_zero in H2.\n      rewrite a2v_upd_inc_zero in H2.\n      rewrite H2; trivial.\n    assert (Hx := Sum_ge _ a1 _ H).\n    assert (Ht : t = t - v - (m $+ {a1 <- -= v} a2) + (m $+ {a1 <- -= v} a2) + v).\n      unfold a2v_upd_dec.\n      simpltm.\n      assert (Ht2 : t >= v).\n        omega.\n      assert (Ht3: t >= m a1 + m a2).\n        apply Sum_ge_2; trivial.\n      rewrite minus_minus.\n      arith_rewrite (t - (v + m a2) + m a2 + v = t - (v + m a2) + (v + m a2)).\n      rewrite <- ge_sub_inc; trivial.\n      omega.\n    rewrite Ht.\n    rewrite H2.\n    unfold a2v_upd_dec in * .\n    unfold a2v_upd_inc in * .\n    apply Sum_inc.\n    simpltm.\n    assert (Ht3: t >= m a1 + m a2).\n      apply Sum_ge_2; trivial.\n    arith_rewrite (t - v - m a2 + m a2 = t - v).\n    apply Sum_dec; trivial.\n    simpltm.\n    omega.\nQed.\n\nDefinition assert_genesis_event (e: event) (E: eventlist) : Prop :=\n  match E with\n    | nil => False\n    | cons e' E => e = e'\n  end.\n\nLemma assert_genesis_event_app : forall e E E',\n        assert_genesis_event e E\n        -> assert_genesis_event e (E ++ E').\nProof.\n  intros.\n  destruct E.\n  + simpl in H.  inversion H.\n  + simpl in H. auto.\nQed.\n\n(* Invariant *)\nDefinition INV (env: env) (S: state) (E: eventlist) : Prop :=\n  let blncs := st_balances S in\n  (* balances not overflow *)\n  (forall a, blncs a <= MAX_UINT256) /\\\n  (* totalSupply preserves *)\n  exists total,\n    total = st_totalSupply S\n    /\\ Sum blncs total\n    /\\ exists creator,\n              assert_genesis_event (ev_constructor creator) E.\n\n(* step evaluation maintains invariant *)\nTheorem step_INV: forall this env msg S E env' S' E',\n    step env (mk_contract this S) msg (mk_contract this S') E'\n    -> env_step env env'\n    -> INV env S E\n    -> INV env' S' (E ++ E').\nProof.\n  intros this env msg S E env' S' E'.\n  intros Hstep Henv' HI.\n  destruct HI as [Hblncs [total [Htotal [Htv [creator Hassert]]]]].\n  inversion_clear Hstep.\n\n  (* case: totalSupply *)\n  - unfold funcspec_totalSupply in H1.\n    subst spec preP evP postP.\n    simpl in *.\n    destruct H5 as [Hx1 [Hx2 Hx3]].\n    subst S.\n    split; auto.\n    exists total.\n    split; auto.\n    split; auto.\n    exists creator.\n    apply assert_genesis_event_app; auto.\n\n\n  (* case: transfer *)\n  - unfold funcspec_transfer in H1.\n    subst spec preP evP postP.\n    simpl in *.\n    subst msg.\n    simpl in H5.\n    destruct H5 as [[Hx1a Hx1b] [Hx2 [Hx3 [Hx4 [Hx5 [Hx6 [Hx7 Hx8]]]]]]].\n    destruct Hx1b as [ Hsender [Hx1b2 Hof]].\n    split.\n    + rewrite Hx7. intros.\n      destruct (beq_dec to sender).\n      * rewrite Nat.eqb_eq in H0. rewrite H0.\n        rewrite <- (a2v_dec_inc_id _ _ _ (Hblncs sender) Hx1b2).\n        auto.\n      * destruct (beq_dec a to).\n        {\n          (* a == to *)\n          rewrite Nat.eqb_eq in H1.\n          subst a.\n          unfold a2v_upd_inc, a2v_upd_dec.\n          apply beq_sym in H0.\n          rewrite (tmap_upd_upd_ne _ _ _ _ _ H0).\n          rewrite (tmap_get_upd_ne _ _ _ _ H0).\n          rewrite (tmap_get_upd_eq _ _ _).\n          rewrite (tmap_get_upd_ne _ _ _ _ H0).\n          rewrite (plus_safe_lt _ _ Hof).\n          generalize(Hblncs sender). intros. omega.\n        }\n        {\n          (* a <> to *)\n          unfold a2v_upd_inc, a2v_upd_dec.\n          apply beq_sym in H1.\n          rewrite (tmap_get_upd_ne _ _ _ _ H1).\n          destruct (beq_dec a sender).\n          - (* a == sender *)\n            rewrite Nat.eqb_eq in H2.\n            subst a.\n            rewrite (tmap_get_upd_eq _ _ _).\n            rewrite (minus_safe _ _ Hx1b2).\n            generalize (Hblncs sender). intros. omega.\n          - (* a <> sender *)\n            apply beq_sym in H2.\n            rewrite (tmap_get_upd_ne _ _ _ _ H2).\n            generalize (Hblncs a). intros. omega.\n        }\n    + exists total. split.\n      *  rewrite Htotal. auto.\n      *  split.\n         {\n           apply (Sum_transfer (st_balances S) total\n                               sender to v (st_balances S'));\n           auto with arith.\n         }\n         {\n           exists creator. apply assert_genesis_event_app; auto.\n         }\n\n  (* case: balanceOf *)\n  - unfold funcspec_balanceOf in H1.\n    subst spec. simpl in *.\n    destruct H2 as [Hx1 [Hx2 Hx3]].\n    subst S.\n    split; auto.\n    exists total.\n    simpl.\n    repeat split; auto.\n    exists creator.\n    apply assert_genesis_event_app; auto.\n\n  (* case: transferFrom *)\n  - unfold funcspec_transferFrom in H1.\n    subst spec.\n    simpl in *.\n    destruct H2 as [[Hx1a [Hx1b [Hx1c [Hx1d Hx1e]]]] [Hx2 [Hx3 [Hx4 [Hx5 [Hx6 [Hx7 Hx8]]]]]]].\n    split.\n    + rewrite Hx7. intros.\n      destruct (beq_dec to from).\n      * rewrite Nat.eqb_eq in H1. rewrite H1.\n        rewrite <- (a2v_dec_inc_id _ _ _ (Hblncs from) Hx1c).\n        auto.\n      * destruct (beq_dec a to).\n        {\n          (* a == to *)\n          rewrite Nat.eqb_eq in H2. rewrite H2.\n          subst a.\n          unfold a2v_upd_inc, a2v_upd_dec.\n          apply beq_sym in H1.\n          rewrite (tmap_upd_upd_ne _ _ _ _ _ H1).\n          rewrite (tmap_get_upd_ne _ _ _ _ H1).\n          rewrite (tmap_get_upd_eq _ _ _).\n          rewrite (tmap_get_upd_ne _ _ _ _ H1).\n          rewrite (plus_safe_lt _ _ Hx1d).\n          generalize(Hblncs from). intros. omega.\n        }\n        {\n          (* a <> to *)\n          unfold a2v_upd_inc, a2v_upd_dec.\n          apply beq_sym in H2.\n          rewrite (tmap_get_upd_ne _ _ _ _ H2).\n          destruct (beq_dec a from).\n          - (* a == from *)\n            rewrite Nat.eqb_eq in H3.\n            subst a.\n            rewrite (tmap_get_upd_eq _ _ _).\n            rewrite (minus_safe _ _ Hx1c).\n            generalize (Hblncs from). intros. omega.\n          - (* a <> from *)\n            apply beq_sym in H3.\n            rewrite (tmap_get_upd_ne _ _ _ _ H3).\n            generalize (Hblncs a). intros. omega.\n        }\n     + exists total. split.\n      *  rewrite Htotal. auto.\n      *  split.\n         {\n           apply (Sum_transfer (st_balances S) total\n                               from to v (st_balances S'));\n           auto with arith.\n         }\n         {\n           exists creator. apply assert_genesis_event_app; auto.\n         }\n\n  (* case: approve *)\n  - unfold funcspec_approve in H1.\n    subst spec.\n    simpl in *.\n    destruct H2 as [Hx1 [Hx2 [Hx3 [Hx4 [Hx5 [Hx6 [Hx7 Hx8]]]]]]].\n    rewrite <- Hx7 in *.\n    split; auto.\n    exists total.\n    rewrite Hx3 in *.\n    rewrite Hx7 in *.\n    repeat split; auto.\n    exists creator.\n    apply assert_genesis_event_app; auto.\n\n  (* case: allowance *)\n  - unfold funcspec_allowance in H1.\n    subst spec.\n    simpl in *.\n    destruct H2 as [Hx1 [Hx2 Hx3]].\n    subst S'.\n    split; auto.\n    exists total.\n    simpl.\n    repeat split; auto.\n    exists creator.\n    apply assert_genesis_event_app; auto.\n\n  (* case: increaseApproval *)\n  - unfold funcspec_increaseApproval in H1.\n    subst spec.\n    simpl in *.\n    destruct H2 as [Hx1 [Hx2 [Hx3 [Hx4 [Hx5 [Hx6 [Hx7 Hx8]]]]]]].\n    rewrite <- Hx7 in *.\n    split; auto.\n    exists total.\n    rewrite Hx3 in *.\n    rewrite Hx7 in *.\n    repeat split; auto.\n    exists creator.\n    apply assert_genesis_event_app; auto.\n\n   (* case: decreaseApproval_1 *)\n  - unfold funcspec_decreaseApproval_1 in H1.\n    subst spec.\n    simpl in *.\n    destruct H2 as [Hx1 [Hx2 [Hx3 [Hx4 [Hx5 [Hx6 [Hx7 Hx8]]]]]]].\n    rewrite <- Hx7 in *.\n    split; auto.\n    exists total.\n    rewrite Hx3 in *.\n    rewrite Hx7 in *.\n    repeat split; auto.\n    exists creator.\n    apply assert_genesis_event_app; auto.\n\n    (* case: decreaseApprova_2 *)\n  - unfold funcspec_decreaseApproval_2 in H1.\n    subst spec.\n    simpl in *.\n    destruct H2 as [Hx1 [Hx2 [Hx3 [Hx4 [Hx5 [Hx6 [Hx7 Hx8]]]]]]].\n    rewrite <- Hx7 in *.\n    split; auto.\n    exists total.\n    rewrite Hx3 in *.\n    rewrite Hx7 in *.\n    repeat split; auto.\n    exists creator.\n    apply assert_genesis_event_app; auto.\n\n    (* case: transferOwnership *)\n  - unfold funcspec_transferOwnership in H1.\n    subst spec.\n    simpl in *.\n    destruct H2 as [[Hx1 Hx2] [Hx3 [Hx4 [Hx5 [Hx6 [Hx7 [Hx8 [Hx9 [Hx10 Hx11]]]]]]]]].\n    rewrite <- Hx8 in *.\n    split; auto.\n    exists total.\n    rewrite Hx4.\n    repeat split; auto.\n    exists creator.\n    apply assert_genesis_event_app; auto.\n\n    (* case: renounceOwnership *)\n  - unfold funcspec_renounceOwnership in H1.\n    subst spec.\n    simpl in *.\n    destruct H2 as [Hx1 [Hx2 [Hx3 [Hx4 [Hx5 [Hx6 [Hx7 [Hx8 [Hx9 Hx10]]]]]]]]].\n    split; auto.\n    rewrite Hx7. auto.\n    exists total.\n    rewrite Hx3.  rewrite Hx7.\n    repeat split; auto.\n    exists creator.\n    apply assert_genesis_event_app; auto.\n\n    (* case: pause*)\n  -  unfold funcspec_pause in H1.\n     subst spec.\n     simpl in *.\n     destruct H2 as [[Hx1 Hx2] [Hx3 [Hx4 [Hx5 [Hx6 [Hx7 [Hx8 [Hx9 [Hx10 Hx11]]]]]]]]].\n     rewrite <- Hx8 in *.\n     split; auto.\n     exists total.\n     rewrite Hx4.\n     repeat split; auto.\n     exists creator.\n     apply assert_genesis_event_app; auto.\n\n    (* case: unpause*)\n  -  unfold funcspec_unpause in H1.\n     subst spec.\n     simpl in *.\n     destruct H2 as [[Hx1 Hx2] [Hx3 [Hx4 [Hx5 [Hx6 [Hx7 [Hx8 [Hx9 [Hx10 Hx11]]]]]]]]].\n     rewrite <- Hx8 in *.\n     split; auto.\n     exists total.\n     rewrite Hx4.\n     repeat split; auto.\n     exists creator.\n     apply assert_genesis_event_app; auto.\n\nQed.\n\n(* create evaluation maintains invariant *)\nTheorem create_INV : forall env0 env msg C E,\n    create env0 msg C E\n    -> INITIAL_SUPPLY <= MAX_UINT256\n    -> env_step env0 env\n    -> INV env (w_st C) E.\nProof.\n  intros.\n  inversion_clear H.\n  subst spec preP evP postP; simpl.\n  unfold funcspec_constructor in H7.\n  simpl in H7.\n  destruct H7 as [Hx1 [Hx2 [Hx3 [Hx4 [Hx5 [Hx6 [Hx7 [Hx8 Hx9]]]]]]]].\n  unfold INV.\n  split.\n\n  - (* no overflow initially *)\n    subst.\n    rewrite Hx6. clear Hx6. simpl.\n    intros a.\n    destruct (beq_dec sender a).\n    + (* a = sender *)\n      apply Nat.eqb_eq in H. subst a.\n      rewrite (tmap_get_upd_eq _ _ _).\n      auto.\n    + (* a <> sender *)\n      rewrite (tmap_get_upd_ne _ _ _ _ H).\n      rewrite (tmap_emp_zero _).\n      unfold TMap.zero.\n      unfold value_Range.\n      omega.\n  - (* totalSupply preserves *)\n    exists INITIAL_SUPPLY.\n    repeat split; auto.\n    + apply Sum_sig in Hx6.\n      trivial.\n    + exists sender.\n      unfold assert_genesis_event.\n      rewrite Hx1.\n      rewrite H2.\n      simpl.\n      trivial.\nQed.\n\nLemma step_contract_address_constant : forall env C msg C' E',\n      step env C msg C' E'\n      -> w_a C = w_a C'.\nProof.\n  intros.\n  destruct C as [a S].\n  destruct C' as [a' S'].\n  induction H; simpl; auto; intuition.\nQed.\n\nLemma steps_INV: forall ml env C E,\n    INV env (w_st C) E\n    -> forall env' C' E', steps env C ml env' C' E'\n    -> INV env' (w_st C') (E ++ E').\nProof.\n  induction ml.\n\n  - (* nil *)\n    intros.\n    inversion_clear H0.\n    destruct H2.\n    subst.\n    rewrite app_nil_r.\n    trivial.\n\n  - (* a :: ml *)\n    intros.\n    inversion_clear H0.\n    rename x into envx.\n    rename a into msg.\n    destruct H1 as [Cx [Ex [Ey [H1 [H2 [H3 H4]]]]]].\n    subst E'.\n    assert (Hx : INV envx (w_st Cx) (E ++ Ex)).\n    {\n      assert (w_a C = w_a Cx).\n      {\n        apply step_contract_address_constant with env msg Ex. apply H1.\n      }\n      destruct C as [C_a C_st].\n      destruct Cx as [Cx_a Cx_st].\n      simpl. simpl in H. simpl in H0. generalize H. generalize H4.\n      apply step_INV with C_a msg.\n      subst Cx_a. apply H1.\n    }\n    substH IHml with (IHml envx Cx (E ++ Ex) Hx).\n    rewrite app_assoc.\n    apply IHml; trivial.\nQed.\n\nLemma INV_implies_totalSupply_fixed :\n  forall env S E,\n    INV env S E\n    -> Sum (st_balances S) (st_totalSupply S).\nProof.\n  intros env S E HI.\n  unfold INV in HI.\n  destruct HI as [_ [total [Ht [HT HI]]]].\n  rewrite Ht in HT.\n  trivial.\nQed.\n\n(* Prop #1: total supply is equal to sum of balances *)\nTheorem Property_totalSupply_equal_to_sum_balances :\n  forall env0 env msg ml C E C' E',\n    create env0 msg C E\n    -> INITIAL_SUPPLY <= MAX_UINT256\n    -> env_step env0 env\n    -> run env C ml C' E'\n    -> Sum (st_balances (w_st C')) (st_totalSupply (w_st C')).\nProof.\n  intros env0 env msg il C E C' E' Hc Hi Hs Hr.\n  unfold run in Hr.\n  destruct Hr as [env' Hsteps].\n  apply INV_implies_totalSupply_fixed with env' (E++E').\n  substH Hc with (create_INV _ _ _ _ _ Hc Hi Hs).\n  eapply steps_INV; eauto.\nQed.\n\n(* Prop #2: total supply is fixed with transfer *)\nTheorem Property_totalSupply_fixed_transfer:\n  forall env C C' E'  msg to v spec preP evP postP,\n    spec = funcspec_transfer to v (w_a C) env msg\n    -> preP = spec_require spec\n    -> evP = spec_events spec\n    -> postP = spec_trans spec\n    -> preP (w_st C) /\\ evP (w_st C) E' /\\ postP (w_st C) (w_st C')\n    -> (st_totalSupply (w_st C)) =  (st_totalSupply (w_st C')).\nProof.\n  intros.\n  rewrite H in H2. simpl in H2.\n  destruct H3 as [H31 [H32 H33]].\n  rewrite H2 in H33.\n  destruct H33.\n  auto.\nQed.\n\n\nLemma INV_step_total_Supply_fixed:\n   forall env C C' E'  msg ,\n    step env C msg C' E'\n    -> (st_totalSupply (w_st C)) =  (st_totalSupply (w_st C')).\nProof.\n  intros.\n  inversion H.\n  - subst spec.\n    destruct H6 as [H61 [H62 H63]].\n    rewrite H5 in H63.\n    destruct H63.  auto.\n  - subst spec.\n    destruct H6 as [H61 [H62 H63]].\n    rewrite H5 in H63.\n    destruct H63.  auto.\n  - subst spec.\n    destruct H3 as [H31 [H32 H33]].\n    rewrite H1 in H33. simpl in H33.\n    rewrite H33. auto.\n  - subst spec.\n    destruct H3 as [H31 [H32 H33]].\n    rewrite H1 in H33. simpl in H33.\n    destruct H33. auto.\n  - subst spec.\n    destruct H3 as [H31 [H32 H33]].\n    rewrite H1 in H33. simpl in H33.\n    destruct H33. auto.\n  - subst spec.\n    destruct H3 as [H31 [H32 H33]].\n    rewrite H1 in H33. simpl in H33.\n    destruct H33. auto.\n  - subst spec.\n    destruct H3 as [H31 [H32 H33]].\n    rewrite H1 in H33. simpl in H33.\n    destruct H33. auto.\n  - subst spec.\n    destruct H3 as [H31 [H32 H33]].\n    rewrite H1 in H33. simpl in H33.\n    destruct H33. auto.\n  - subst spec.\n    destruct H3 as [H31 [H32 H33]].\n    rewrite H1 in H33. simpl in H33.\n    destruct H33. auto.\n  - subst spec.\n    destruct H3 as [H31 [H32 H33]].\n    rewrite H1 in H33. simpl in H33.\n    destruct H33. auto.\n  - subst spec.\n    destruct H3 as [H31 [H32 H33]].\n    rewrite H1 in H33. simpl in H33.\n    destruct H33. auto.\n  - subst spec.\n    destruct H3 as [H31 [H32 H33]].\n    rewrite H1 in H33. simpl in H33.\n    destruct H33. auto.\n  - subst spec.\n    destruct H3 as [H31 [H32 H33]].\n    rewrite H1 in H33. simpl in H33.\n    destruct H33. auto.\nQed.\n\n\n(* Prop #3: total supply is fixed after initialization *)\nTheorem Property_totalSupply_fixed_after_initialization:\n  forall env0 env msg C E C' E',\n    create env0 msg C E\n    -> step env C msg C' E'\n    -> (st_totalSupply (w_st C)) =  (st_totalSupply (w_st C')).\nProof.\n  intros.\n  apply INV_step_total_Supply_fixed with env E' msg.\n  auto.\nQed.\n\nLemma  INV_steps_total_supply_fixed:\nforall ml env0 C0 C E env,\n  steps env0 C0 ml env C E\n  -> (st_totalSupply (w_st C0)) =  (st_totalSupply (w_st C)).\nProof.\n  intros ml.\n  induction ml.\n  + intros. unfold steps in H. destruct H.\n    rewrite H. trivial.\n  + intros.\n    inversion_clear H.\n    rename x into envx.\n    inversion H0 as [C'' [E'' [E' [Hs1 [Hs2 [Hs3 Hs4]]]]]].\n    apply INV_step_total_Supply_fixed in Hs1.\n    apply IHml in Hs2.\n    rewrite Hs1. auto.\n Qed.\n\nTheorem Property_totalSupply_fixed_after_initialization1:\n   forall env0 env msg ml C E C' E',\n    create env0 msg C E\n    -> run env C ml C' E'\n    -> (st_totalSupply (w_st C)) =  (st_totalSupply (w_st C')).\nProof.\n  intros.\n  unfold run in H0.\n  inversion H0 as [env' H0'].\n  apply INV_steps_total_supply_fixed in H0'.\n  auto.\nQed.\n\n(* Prop #4: total supply is fixed with delegate transfer *)\nTheorem Property_totalSupply_fixed_delegate_transfer:\n   forall env C C' E' from  msg to v spec,\n    spec = funcspec_transferFrom from to v (w_a C) env msg\n    -> (spec_require spec) (w_st C) /\\ (spec_events spec) (w_st C) E' /\\ (spec_trans spec) (w_st C) (w_st C')\n    -> (st_totalSupply (w_st C)) =  (st_totalSupply (w_st C')).\nProof.\n  intros.\n  destruct H0 as [H01 [H02 H03]]. rewrite H in H03. simpl in H03.\n  destruct H03.\n  auto.\nQed.\n\n\n(* Prop #5: balances of from and to changed by transfer*)\nTheorem Property_from_to_balances_change:\n  forall env C C' E' to addr msg v spec,\n    spec = funcspec_transfer to v (w_a C) env msg\n    -> (spec_require spec) (w_st C) /\\\n       (spec_events spec) (w_st C) E' /\\\n       (spec_trans spec) (w_st C) (w_st C')\n    -> m_sender msg <> to\n    -> m_sender msg <> addr\n    -> to <> addr\n    -> (st_balances (w_st C') to = (st_balances (w_st C) to) + v)\n       /\\ (st_balances (w_st C') (m_sender msg) = (st_balances (w_st C) (m_sender msg)) - v)\n       /\\ st_balances (w_st C') addr = st_balances (w_st C) addr.\nProof.\n  intros env C C' E' to addr  msg v spec Hspec_def Hspec Hsender HsenderA HtoA.\n  unfold funcspec_transfer in Hspec_def.\n  subst spec. simpl in Hspec.\n  destruct Hspec as [Hof [_ [_ [_ [_ [_ [Hblncs _]]]]]]].\n  rewrite Hblncs in *. clear Hblncs.\n  apply neq_beq_false in Hsender.\n  apply neq_beq_false in HsenderA.\n  apply neq_beq_false in HtoA.\n  unfold a2v_upd_dec. unfold a2v_upd_inc.\n  destruct Hof as [Hlo [Hs [Hhi Hm]]].\n\n  split.\n\n  - rewrite (tmap_get_upd_eq _ _ _).\n    rewrite (tmap_get_upd_ne _ _ _ _ Hsender).\n    apply plus_safe_lt; auto.\n\n  - split.\n    + apply beq_sym in Hsender.\n      rewrite (tmap_get_upd_ne _ _ _ _ Hsender).\n      rewrite (tmap_get_upd_eq _ _ _).\n      apply minus_safe; auto.\n\n    + apply beq_sym in Hsender.\n      rewrite (tmap_get_upd_ne _ _ _ _ HtoA).\n      rewrite (tmap_get_upd_ne _ _ _ _ HsenderA).\n      auto.\nQed.\n\n(* Prop #6: only owner can pause *)\nTheorem Property_pause_only_by_owner:\n  forall this env msg spec C C' E',\n    spec = funcspec_pause this env msg\n    -> (spec_require spec) (w_st C) /\\\n       (spec_events spec) (w_st C) E' /\\\n       (spec_trans spec) (w_st C) (w_st C')\n    -> m_sender msg = st_owner (w_st C).\nProof.\n  intros this env msg spec C C' E' Hspec H0.\n  destruct H0 as [Hreq [Henv Htrans]].\n  unfold funcspec_pause in Hspec.\n  rewrite Hspec in *.\n  simpl in *.\n  destruct Hreq as [Hmsg Hpause].\n  auto.\nQed.\n\n(* Prop #7: only owner can unpause *)\nTheorem Property_unpause_only_by_owner:\n  forall this env msg spec C C' E',\n    spec = funcspec_unpause this env msg\n    -> (spec_require spec) (w_st C) /\\\n       (spec_events spec) (w_st C) E' /\\\n       (spec_trans spec) (w_st C) (w_st C')\n    -> m_sender msg = st_owner (w_st C).\nProof.\n  intros this env msg spec C C' E' Hspec H0.\n  destruct H0 as [Hreq [Henv Htrans]].\n  unfold funcspec_unpause in Hspec.\n  rewrite Hspec in *.\n  simpl in *.\n  destruct Hreq as [Hmsg Hpause].\n  auto.\nQed.\n\n(* Prop #8: owner cannot transfer tokens in arbitrary account *)\nTheorem Property_restricted_owner_for_transfer:\n  forall to value this env msg spec C C' E' owner,\n    spec = funcspec_transfer to value this env msg\n    -> (spec_require spec) (w_st C) /\\\n       (spec_events spec) (w_st C) E' /\\\n       (spec_trans spec) (w_st C) (w_st C')\n    -> owner = st_owner (w_st C)\n    -> m_sender msg = owner\n    -> (forall acct,\n           acct <> owner /\\ acct <> to\n           -> st_balances (w_st C) acct = st_balances (w_st C') acct).\nProof.\n  intros to value this env msg spec C C' E' owner Hspec H0 Hw Hmw acct Ha.\n  destruct H0 as [Hreq [Henv Htrans]].\n  unfold funcspec_transfer in Hspec.\n  rewrite Hspec in *.\n  simpl in *.\n  destruct Htrans as [Hto [Hna [Hdec [Hsym [Hblns [Halw [How Hpa]]]]]]].\n  rewrite Hblns.\n  destruct Ha as [Hao Hat].\n  apply neq_beq_false in Hao.\n  apply neq_beq_false in Hat.\n  unfold a2v_upd_dec. unfold a2v_upd_inc.\n\n  apply beq_sym in Hat.\n  rewrite (tmap_get_upd_ne _ _ _ _ Hat).\n  apply beq_sym in Hao.\n  rewrite Hmw.\n  rewrite (tmap_get_upd_ne _ _ _ _ Hao).\n  auto.\nQed.\n\n(* Prop #9: owner cannot delegating transfer tokens in arbitrary account *)\nTheorem Property_restricted_owner_for_transferFrom:\n  forall from to value this env msg spec C C' E' owner,\n    spec = funcspec_transferFrom from to value this env msg\n    -> (spec_require spec) (w_st C) /\\\n       (spec_events spec) (w_st C) E' /\\\n       (spec_trans spec) (w_st C) (w_st C')\n    -> owner = st_owner (w_st C)\n    -> m_sender msg = owner\n    -> (forall acct,\n           acct <> owner /\\ acct <> from /\\ acct <> to\n           -> st_balances (w_st C) acct = st_balances (w_st C') acct).\nProof.\n  intros from to value this env msg spec C C' E' owner Hspec H0 Hw Hmw acct Ha.\n  unfold funcspec_transferFrom in Hspec.\n  rewrite Hspec in *. simpl in *.\n  destruct H0 as [H1 [Hev [Hto [Hna [Hdec [Hsym [Hblns [Halw [How Hpa]]]]]]]]].\n  rewrite Hblns.\n  destruct Ha as [Hao [Haf Hat]].\n  apply neq_beq_false in Hao.\n  apply neq_beq_false in Hat.\n  apply neq_beq_false in Haf.\n  unfold a2v_upd_dec. unfold a2v_upd_inc.\n  apply beq_sym in Hat.\n  rewrite (tmap_get_upd_ne _ _ _ _ Hat).\n  apply beq_sym in Haf.\n  rewrite (tmap_get_upd_ne _ _ _ _ Haf).\n  auto.\nQed.\n", "meta": {"author": "sec-bit", "repo": "calculus-token-with-proof", "sha": "a1c33cdfb543f198e7432fa1c5e33f1c87142caa", "save_path": "github-repos/coq/sec-bit-calculus-token-with-proof", "path": "github-repos/coq/sec-bit-calculus-token-with-proof/calculus-token-with-proof-a1c33cdfb543f198e7432fa1c5e33f1c87142caa/proof/Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166195971441, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.21815584419967277}}
{"text": "Require Import\n        CertifiedExtraction.Extraction.Internal\n        CertifiedExtraction.Extraction.External.Core\n        CertifiedExtraction.Extraction.External.Loops\n        CertifiedExtraction.Extraction.External.GenericADTMethods\n        CertifiedExtraction.Extraction.External.FacadeADTs.\n\nLtac loop_unify_with_nil_t :=\n  match goal with\n  | [  |- context[Cons (T := list ?A) _ (ret ?val) _] ] => is_evar val; unify val (@nil A)\n  end.\n\nLtac loop_t :=\n  repeat (intros || unfold Fold || solve [PreconditionSet_t; Lifted_t] || compile_do_side_conditions || clean_DropName_in_ProgOk || rewrite Propagate_ret || eapply CompileSeq || eauto 2).\n\nLemma CompileLoopBase :\n  forall `{FacadeWrapper (Value av) A} `{FacadeWrapper (Value av) A'} `{FacadeWrapper av (list A)}\n    lst init vhead vtest vlst vret fpop fempty fdealloc facadeBody env (ext: StringMap.t (Value av)) tenv (f: Comp A' -> A -> Comp A'),\n    GLabelMap.MapsTo fpop (Axiomatic (List_pop A)) env ->\n    GLabelMap.MapsTo fempty (Axiomatic (List_empty A)) env ->\n    GLabelMap.MapsTo fdealloc (Axiomatic (FacadeImplementationOfDestructor (list A))) env ->\n    PreconditionSet tenv ext [[[vhead; vtest; vlst; vret]]] ->\n    (forall head (acc: Comp A') (s: list A),\n        {{ [[`vret ~~> acc as _]] :: [[`vhead ->> head as _]] :: tenv }}\n          facadeBody\n        {{ [[`vret ~~> (f acc head) as _]] :: tenv }} ∪\n        {{ [vtest |> wrap (bool2w false)] :: [vlst |> wrap s] :: ext }} // env) ->\n    {{ [[`vret ~~> init as _]] :: [[`vlst ->> lst as _]] :: tenv }}\n      (Seq (Fold vhead vtest vlst fpop fempty facadeBody) (Call (DummyArgument vtest) fdealloc (vlst :: nil)))\n    {{ [[`vret ~~> (fold_left f lst init) as _]] :: tenv }} ∪ {{ ext }} // env.\nProof.\n  unfold DummyArgument; loop_t.\n\n  rewrite TelEq_swap by loop_t;\n    eapply CompileCallEmpty_spec; loop_t.\n\n  2:eapply CompileCallFacadeImplementationOfDestructor; loop_t.\n\n  loop_unify_with_nil_t.\n\n  loop_t.\n  generalize dependent init;\n  induction lst; loop_t.\n\n  move_to_front vtest;\n  apply CompileWhileFalse_Loop; loop_t.\n\n  eapply CompileWhileTrue; [ loop_t.. | ].\n\n  apply generalized @CompileCallPop; loop_t.\n\n  move_to_front vlst; apply ProgOk_Chomp_Some; loop_t.\n  move_to_front vtest; apply ProgOk_Chomp_Some; loop_t.\n  computes_to_inv; subst; defunctionalize_evar; eauto.\n\n  rewrite TelEq_swap; eauto.\n  apply CompileCallEmpty_spec; loop_t.\n\n  loop_t.\nQed.\n\nLemma CompileLoop :\n  forall `{FacadeWrapper (Value av) A} `{FacadeWrapper (Value av) A'} `{FacadeWrapper av (list A)}\n    lst init vhead vtest vlst vret fpop fempty fdealloc facadeBody facadeConclude\n    env (ext: StringMap.t (Value av)) tenv tenv' (f: Comp A' -> A -> Comp A'),\n    GLabelMap.MapsTo fpop (Axiomatic (List_pop A)) env ->\n    GLabelMap.MapsTo fempty (Axiomatic (List_empty A)) env ->\n    GLabelMap.MapsTo fdealloc (Axiomatic (FacadeImplementationOfDestructor (list A))) env ->\n    PreconditionSet tenv ext [[[vhead; vtest; vlst; vret]]] ->\n    {{ [[`vret ~~> (fold_left f lst init) as _]] :: tenv }}\n      facadeConclude\n    {{ [[`vret ~~> (fold_left f lst init) as _]] :: tenv' }} ∪ {{ ext }} // env ->\n    (forall head (acc: Comp A') (s: list A),\n        {{ [[`vret ~~> acc as _]] :: [[`vhead ->> head as _]] :: tenv }}\n          facadeBody\n        {{ [[`vret ~~> (f acc head) as _]] :: tenv }} ∪\n        {{ [vtest |> wrap (bool2w false)] :: [vlst |> wrap s] :: ext }} // env) ->\n    {{ [[`vret ~~> init as _]] :: [[`vlst ->> lst as _]] :: tenv }}\n      (Seq (Seq (Fold vhead vtest vlst fpop fempty facadeBody) (Call (DummyArgument vtest) fdealloc (vlst :: nil))) facadeConclude)\n    {{ [[`vret ~~> (fold_left f lst init) as _]] :: tenv' }} ∪ {{ ext }} // env.\nProof.\n  eauto using @CompileSeq, @CompileLoopBase.\nQed.\n\nLemma CompileLoopAlloc :\n  forall `{FacadeWrapper (Value av) A} `{FacadeWrapper (Value av) A'} `{FacadeWrapper av (list A)}\n    lst init vhead vtest vlst vret fpop fempty fdealloc facadeInit facadeBody facadeConclude\n    env (ext: StringMap.t (Value av)) tenv tenv' (f: Comp A' -> A -> Comp A'),\n    GLabelMap.MapsTo fpop (Axiomatic (List_pop A)) env ->\n    GLabelMap.MapsTo fempty (Axiomatic (List_empty A)) env ->\n    GLabelMap.MapsTo fdealloc (Axiomatic (FacadeImplementationOfDestructor (list A))) env ->\n    PreconditionSet tenv ext [[[vhead; vtest; vlst; vret]]] ->\n    {{ [[`vlst ->> lst as _]] :: tenv }}\n      facadeInit\n    {{ [[`vret ~~> init as _]] :: [[`vlst ->> lst as _]] :: tenv }} ∪ {{ ext }} // env ->\n    {{ [[`vret ~~> (fold_left f lst init) as _]] :: tenv }}\n      facadeConclude\n    {{ [[`vret ~~> (fold_left f lst init) as _]] :: tenv' }} ∪ {{ ext }} // env ->\n    (forall head (acc: Comp A') (s: list A),\n        {{ [[`vret ~~> acc as _]] :: [[`vhead ->> head as _]] :: tenv }}\n          facadeBody\n        {{ [[`vret ~~> (f acc head) as _]] :: tenv }} ∪\n        {{ [vtest |> wrap (bool2w false)] :: [vlst |> wrap s] :: ext }} // env) ->\n    {{ [[`vlst ->> lst as _]] :: tenv }}\n      (Seq facadeInit (Seq (Seq (Fold vhead vtest vlst fpop fempty facadeBody) (Call (DummyArgument vtest) fdealloc (vlst :: nil))) facadeConclude))\n    {{ [[`vret ~~> (fold_left f lst init) as _]] :: tenv' }} ∪ {{ ext }} // env.\nProof.\n  eauto using @CompileSeq, @CompileLoop.\nQed.\n\nDefinition revmap {A B} f := fun seq => @map A B f (rev seq).\n\nOpen Scope list_scope.\n\nLemma revmap_fold_helper:\n  forall (A A' : Type) (f : A -> A') (a : A) (vv : list A) (base : list A'),\n    revmap f (a :: vv) ++ base = revmap f vv ++ f a :: base.\nProof.\n  unfold revmap; intros; simpl.\n  rewrite map_rev.\n  rewrite map_app.\n  simpl.\n  rewrite <- app_assoc.\n  simpl.\n  rewrite <- map_rev.\n  reflexivity.\nQed.\n\nLemma revmap_fold_generalized :\n  forall {A B} (f: A -> B) (seq: list A) (base: list B),\n    fold_left (fun acc elem => f elem :: acc) seq base = (@revmap A B f seq) ++ base.\nProof.\n  induction seq; simpl; intros.\n  - reflexivity.\n  - rewrite revmap_fold_helper; eauto.\nQed.\n\nLemma revmap_fold :\n  forall {A B} (f: A -> B) (seq: list A),\n    fold_left (fun acc elem => f elem :: acc) seq nil = @revmap A B f seq.\nProof.\n  intros.\n  rewrite <- (app_nil_r (revmap f seq)).\n  apply revmap_fold_generalized.\nQed.\n\nLemma revmap_fold_comp_generalized :\n  forall {A B} (f: A -> B) (seq: list A) base,\n    Monad.equiv\n      (fold_left (fun cacc elem => (acc <- cacc; ret (f elem :: acc))%comp) seq base)\n      ( b <- base;\n        ret ((@revmap A B f seq) ++ b)).\nProof.\n  intros; etransitivity.\n  2: apply Monad.computes_under_bind; intros; rewrite <- revmap_fold_generalized; apply SetoidMorphisms.equiv_refl.\n\n  generalize dependent base; induction seq; simpl;\n  [ | setoid_rewrite IHseq ];\n  split; intros; computes_to_inv; subst; eauto using BindComputes.\nQed.\n\nLemma revmap_fold_comp :\n  forall {A B} (f: A -> B) (seq: list A),\n    Monad.equiv\n      (fold_left (fun cacc elem => (acc <- cacc; ret (f elem :: acc))%comp) seq (ret nil))\n      (ret (@revmap A B f seq)).\nProof.\n  intros.\n  rewrite <- (app_nil_r (revmap f seq)).\n  rewrite revmap_fold_comp_generalized.\n  split; intros; computes_to_inv; subst; eauto using BindComputes.\nQed.\n\nLemma CompileMap_ADT :\n  forall {av A A'} `{FacadeWrapper av (list A)} `{FacadeWrapper av (list A')} `{FacadeWrapper (Value av) A} `{FacadeWrapper av A'}\n    (lst: list A) vhead vhead' vtest vlst vret vtmp fpop fempty falloc fdealloc fcons facadeBody facadeCoda env (ext: StringMap.t (Value av)) tenv tenv' (f: A -> A'),\n    GLabelMap.MapsTo fpop (Axiomatic (List_pop A)) env ->\n    GLabelMap.MapsTo fempty (Axiomatic (List_empty A)) env ->\n    GLabelMap.MapsTo falloc (Axiomatic (FacadeImplementationOfConstructor (list A') nil)) env ->\n    GLabelMap.MapsTo fdealloc (Axiomatic (FacadeImplementationOfDestructor (list A))) env ->\n    GLabelMap.MapsTo fcons (Axiomatic (FacadeImplementationOfMutation_ADT A' (list A') cons)) env ->\n    (* GLabelMap.MapsTo fdealloc_one (Axiomatic (FacadeImplementationOfDestructor A)) env -> *)\n    PreconditionSet tenv ext [[[vhead; vhead'; vtest; vlst; vret; vtmp]]] ->\n    {{ [[`vret ->> (revmap f lst) as _]] :: tenv }}\n      facadeCoda\n    {{ [[`vret ->> (revmap f lst) as _]] :: tenv' }} ∪ {{ ext }} // env ->\n    (forall head (s: list A) (s': list A'),\n        {{ [[`vhead ->> head as _]] :: tenv }}\n          facadeBody\n        {{ [[`vhead' ->> f head as _]] :: tenv }} ∪\n        {{ [vret |> wrap s'] :: [vtest |> wrap (bool2w false)] :: [vlst |> wrap s] :: ext }} // env) ->\n    {{ [[`vlst ->> lst as _]] :: tenv }}\n      (Seq\n         (Call vret falloc nil)\n         (Seq\n            (Seq\n               (Fold vhead vtest vlst fpop fempty\n                     (Seq facadeBody\n                          (Call vtmp fcons (vret :: vhead' :: nil))))\n               (Call vtest fdealloc (vlst :: nil)))\n            facadeCoda))\n    {{ [[`vret ->> (revmap f lst) as _]] :: tenv' }} ∪ {{ ext }} // env.\nProof.\n  intros.\n  setoid_rewrite <- revmap_fold_comp.\n  apply CompileLoopAlloc; eauto.\n  PreconditionSet_t; eauto.\n  eapply (CompileCallFacadeImplementationOfConstructor (A := list A')); loop_t.\n  setoid_rewrite revmap_fold_comp; eassumption.\n  intros.\n  rewrite SameValues_Fiat_Bind_TelEq.\n  move_to_front vret.\n  apply miniChomp'; intros.\n  hoare.\n  apply ProgOk_Chomp_Some; loop_t; defunctionalize_evar; eauto.\n  apply CompileCallFacadeImplementationOfMutation_ADT; compile_do_side_conditions.\nQed.\n\nLemma CompileMap_SCA :\n  forall {av A} `{FacadeWrapper av (list A)} `{FacadeWrapper av (list W)} `{FacadeWrapper (Value av) A}\n    (lst: list A) vhead vhead' vtest vlst vret vtmp fpop fempty falloc fdealloc fcons facadeBody facadeCoda env (ext: StringMap.t (Value av)) tenv tenv' (f: A -> W),\n    GLabelMap.MapsTo fpop (Axiomatic (List_pop A)) env ->\n    GLabelMap.MapsTo fempty (Axiomatic (List_empty A)) env ->\n    GLabelMap.MapsTo falloc (Axiomatic (FacadeImplementationOfConstructor (list W) nil)) env ->\n    GLabelMap.MapsTo fdealloc (Axiomatic (FacadeImplementationOfDestructor (list A))) env ->\n    GLabelMap.MapsTo fcons (Axiomatic (FacadeImplementationOfMutation_SCA (list W) cons)) env ->\n    (* GLabelMap.MapsTo fdealloc_one (Axiomatic (FacadeImplementationOfDestructor A)) env -> *)\n    PreconditionSet tenv ext [[[vhead; vhead'; vtest; vlst; vret; vtmp]]] ->\n    {{ [[`vret ->> (revmap f lst) as _]] :: tenv }}\n      facadeCoda\n    {{ [[`vret ->> (revmap f lst) as _]] :: tenv' }} ∪ {{ ext }} // env ->\n    (forall head (s: list A) (s': list W),\n        {{ [[`vhead ->> head as _]] :: tenv }}\n          facadeBody\n        {{ [[`vhead' ->> f head as _]] :: tenv }} ∪\n        {{ [vret |> wrap s'] :: [vtest |> wrap (bool2w false)] :: [vlst |> wrap s] :: ext }} // env) ->\n    {{ [[`vlst ->> lst as _]] :: tenv }}\n      (Seq\n         (Call vret falloc nil)\n         (Seq\n            (Seq\n               (Fold vhead vtest vlst fpop fempty\n                     (Seq facadeBody\n                          (Call vtmp fcons (vret :: vhead' :: nil))))\n               (Call vtest fdealloc (vlst :: nil)))\n            facadeCoda))\n    {{ [[`vret ->> (revmap f lst) as _]] :: tenv' }} ∪ {{ ext }} // env.\nProof.\n  intros.\n  setoid_rewrite <- revmap_fold_comp.\n  apply CompileLoopAlloc; eauto.\n  PreconditionSet_t; eauto.\n  eapply (CompileCallFacadeImplementationOfConstructor (A := list W)); loop_t.\n  setoid_rewrite revmap_fold_comp; eassumption.\n  intros.\n  rewrite SameValues_Fiat_Bind_TelEq.\n  move_to_front vret.\n  apply miniChomp'; intros.\n  hoare.\n  apply ProgOk_Chomp_Some; loop_t; defunctionalize_evar; eauto.\n  apply CompileCallFacadeImplementationOfMutation_SCA; unfold DummyArgument; compile_do_side_conditions.\nQed.\n\n(* NOTE: Could prove lemma for un-reved map using temp variable *)\n\nLemma ret_fold_fold_ret_lemma :\n  forall {TElem TAcc} (f: TAcc -> TElem -> TAcc) lst (init: TAcc) init_comp,\n    Monad.equiv (ret init) init_comp ->\n    Monad.equiv (ret (fold_left f lst init))\n                (fold_left (fun (acc: Comp TAcc) x => (a <- acc; ret (f a x))%comp) lst init_comp).\nProof.\n  induction lst; simpl; intros.\n  - trivial.\n  - etransitivity; [ apply IHlst | reflexivity ].\n    unfold Monad.equiv in *; repeat (cleanup_pure || computes_to_inv || subst).\n    + eapply BindComputes; try rewrite <- H; apply ReturnComputes.\n    + rewrite <- H in *; computes_to_inv; subst; apply ReturnComputes.\nQed.\n\nLemma ret_fold_fold_ret :\n  forall {TElem TAcc} (f: TAcc -> TElem -> TAcc) lst (init: TAcc),\n    Monad.equiv (ret (fold_left f lst init))\n                (fold_left (fun (acc: Comp TAcc) x => (a <- acc; ret (f a x))%comp) lst (ret init)).\nProof.\n  intros; apply ret_fold_fold_ret_lemma; apply SetoidMorphisms.equiv_refl.\nQed.\n\nLemma CompileLoop_ret :\n  forall {av A} `{FacadeWrapper (Value av) A} `{FacadeWrapper (Value av) A'} `{FacadeWrapper av (list A)}\n    lst init facadeBody facadeConclude vhead vtest vlst vret env (ext: StringMap.t (Value av)) tenv tenv' fpop fempty fdealloc (f: A' -> A -> A'),\n    GLabelMap.MapsTo fpop (Axiomatic (List_pop A)) env ->\n    GLabelMap.MapsTo fempty (Axiomatic (List_empty A)) env ->\n    GLabelMap.MapsTo fdealloc (Axiomatic (FacadeImplementationOfDestructor (list A))) env ->\n    PreconditionSet tenv ext [[[vhead; vtest; vlst; vret]]] ->\n    (forall head acc (s: list A),\n        {{ [[`vret ->> acc as _]] :: [[`vhead ->> head as _]] :: tenv }}\n          facadeBody\n        {{ [[`vret ->> (f acc head) as _]] :: tenv }} ∪ {{ [vtest |> wrap (bool2w false)] :: [vlst |> wrap s] :: ext }} // env) ->\n    {{ [[`vret ->> (fold_left f lst init) as _]] :: tenv }}\n      facadeConclude\n    {{ [[`vret ->> (fold_left f lst init) as _]] :: tenv' }} ∪ {{ ext }} // env ->\n    {{ [[`vret ->> init as _]] :: [[`vlst ->> lst as _]] :: tenv }}\n      (Seq (Seq (Fold vhead vtest vlst fpop fempty facadeBody) (Call (DummyArgument vtest) fdealloc (vlst :: nil))) facadeConclude)\n    {{ [[`vret ->> (fold_left f lst init) as _]] :: tenv' }} ∪ {{ ext }} // env.\nProof.\n  intros.\n  setoid_rewrite ret_fold_fold_ret.\n  eapply CompileSeq.\n  apply CompileLoopBase; eauto.\n  2: apply ProkOk_specialize_to_ret; intros * h; apply ret_fold_fold_ret in h; computes_to_inv; subst; eauto.\n  intros; rewrite SameValues_Fiat_Bind_TelEq.\n  apply miniChomp'; intros; eauto.\nQed.\n\nLemma CompileLoopAlloc_ret :\n  forall {av A} `{FacadeWrapper (Value av) A} `{FacadeWrapper (Value av) A'} `{FacadeWrapper av (list A)}\n    lst init facadeInit facadeBody facadeConclude vhead vtest vlst vret env (ext: StringMap.t (Value av)) tenv tenv' fpop fempty fdealloc (f: A' -> A -> A'),\n    GLabelMap.MapsTo fpop (Axiomatic (List_pop A)) env ->\n    GLabelMap.MapsTo fempty (Axiomatic (List_empty A)) env ->\n    GLabelMap.MapsTo fdealloc (Axiomatic (FacadeImplementationOfDestructor (list A))) env ->\n    PreconditionSet tenv ext [[[vhead; vtest; vlst; vret]]] ->\n    {{ [[`vlst ->> lst as _]] :: tenv }}\n      facadeInit\n    {{ [[`vret ->> init as _]] :: [[`vlst ->> lst as _]] :: tenv }} ∪ {{ ext }} // env ->\n    (forall head acc (s: list A),\n        {{ [[`vret ->> acc as _]] :: [[`vhead ->> head as _]] :: tenv }}\n          facadeBody\n        {{ [[`vret ->> (f acc head) as _]] :: tenv }} ∪ {{ [vtest |> wrap (bool2w false)] :: [vlst |> wrap s] :: ext }} // env) ->\n    {{ [[`vret ->> (fold_left f lst init) as _]] :: tenv }}\n      facadeConclude\n    {{ [[`vret ->> (fold_left f lst init) as _]] :: tenv' }} ∪ {{ ext }} // env ->\n    {{ [[`vlst ->> lst as _]] :: tenv }}\n      (Seq facadeInit (Seq (Seq (Fold vhead vtest vlst fpop fempty facadeBody) (Call (DummyArgument vtest) fdealloc (vlst :: nil))) facadeConclude))\n    {{ [[`vret ->> (fold_left f lst init) as _]] :: tenv' }} ∪ {{ ext }} // env.\nProof.\n  eauto using @CompileSeq, @CompileLoop_ret.\nQed.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/CertifiedExtraction/Extraction/External/FacadeLoops.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.21815583785047438}}
{"text": "(** * OR instruction *)\nRequire Import x86proved.x86.instrrules.core.\nImport x86.instrrules.core.instrruleconfig.\n\n(** ** Generic OR *)\nLemma OR_rule s (ds:DstSrc s) (v1: VWORD s) :\n   |-- specAtDstSrc ds (fun D v2 =>\n       basic (D v1 ** OSZCP?)\n             (BOP _ OP_OR ds) \n             (let v := orB v1 v2 in\n              D v ** OSZCP false (msb v) (v == #0) false (lsb v))).\nProof. do_instrrule_triple. Qed.\n\n(** We make this rule an instance of the typeclass, and leave\n    unfolding things like [specAtDstSrc] to the getter tactic\n    [get_instrrule_of]. *)\nGlobal Instance: forall s (ds : DstSrc s), instrrule (BOP s OP_OR ds) := @OR_rule.\n\n", "meta": {"author": "nbenton", "repo": "x86proved", "sha": "7a58960f6456ee09dd46c990204a30c2fdd7fa1a", "save_path": "github-repos/coq/nbenton-x86proved", "path": "github-repos/coq/nbenton-x86proved/x86proved-7a58960f6456ee09dd46c990204a30c2fdd7fa1a/src/x86/instrrules/or.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.21815583785047438}}
{"text": "Require Import Utils.\nRequire Import Maps.\nRequire Import PropertyGraph.\nRequire Import Cypher.\nRequire Import BindingTable.\nRequire Import Semantics.\nRequire Import PatternE.\nRequire Import ExecutionPlan.\nRequire TraverseOpImpl.\n\nImport PartialMap.Notations.\nImport TotalMap.Notations.\nImport PropertyGraph.\nImport ExecutionPlan.\nImport FilterMode.\nImport ExpandMode.\nImport MatchMode.\nImport UpdateNotations.\n\nModule ExecutionPlanImpl : ExecutionPlan.Spec.\n\n  Definition scan_vertices (n : Name.t)\n                           (graph : PropertyGraph.t) :\n    option BindingTable.t :=\n    Some (map (fun v => n |-> Value.GVertex v) (vertices graph)).\n\n  Section filter_by_label.\n    Variable mode : FilterMode.t.\n    Variable n : Name.t.\n    Variable l : PropertyGraph.label.\n    Variable graph : PropertyGraph.t.\n    Variable table : BindingTable.t.\n\n    Definition vertex_has_label (r : Rcd.t) : bool :=\n      match r n with\n      | Some (Value.GVertex v) => In_decb l (vlabels graph v)\n      | _ => false\n      end.\n\n    Definition edge_has_label (r : Rcd.t) : bool :=\n      match r n with\n      | Some (Value.GEdge e) => elabel graph e ==b l\n      | _ => false\n      end.\n\n    Definition has_label : Rcd.t -> bool :=\n      match mode with\n      | Vertices => vertex_has_label\n      | Edges => edge_has_label\n      end.\n\n    Definition filter_by_label : option BindingTable.t :=\n      Some (filter has_label table).\n  End filter_by_label.\n\n  #[local]\n  Hint Unfold filter_by_label has_label vertex_has_label edge_has_label : filter_by_label_db.\n\n  Section expand.\n    Variable mode : ExpandMode.t.\n    Variable n_from n_edge n_to : Name.t.\n    Variable d : Pattern.direction.\n    Variable graph : PropertyGraph.t.\n    Variable table : BindingTable.t.\n\n    Definition expand_all_single (r : Rcd.t) : option BindingTable.t :=\n      match r n_from, r n_edge, r n_to with\n      | Some (Value.GVertex v_from), None, None =>\n        Some (map (fun '(e, v_to) => n_to   |-> Value.GVertex v_to;\n                                     n_edge |-> Value.GEdge e; r)\n          match d with\n          | Pattern.OUT  => out_edges graph v_from\n          | Pattern.IN   => in_edges  graph v_from\n          | Pattern.BOTH => out_edges graph v_from ++\n                            in_edges  graph v_from\n          end)\n      | _, _, _ => None\n      end.\n\n    Definition expand_into_single (r : Rcd.t) : option BindingTable.t :=\n      match r n_from, r n_edge, r n_to with\n      | Some (Value.GVertex v_from), None, Some (Value.GVertex v_to) =>\n          Some (map (fun e => n_to   |-> Value.GVertex v_to;\n                              n_edge |-> Value.GEdge e; r)\n          match d with\n          | Pattern.OUT  => edges_between graph v_from v_to\n          | Pattern.IN   => edges_between graph v_to   v_from\n          | Pattern.BOTH => edges_between graph v_from v_to ++\n                            edges_between graph v_to   v_from\n          end)\n      | _, _, _ => None\n      end.\n\n    Definition expand_single (r : Rcd.t) : option BindingTable.t :=\n      match mode with\n      | All => expand_all_single r\n      | Into => expand_into_single r\n      end.\n\n    Definition expand : option BindingTable.t :=\n      option_map (@List.concat Rcd.t) (fold_option (map expand_single table)).\n  End expand.\n\n  #[local]\n  Hint Unfold expand expand_single expand_all_single expand_into_single : expand_db.\n\n  Definition return_all (graph : PropertyGraph.t) (table : BindingTable.t) :=\n    Some (map Rcd.explicit_proj table).\n\n  (** If the inputs are well-formed then the operation will return the result *)\n\n  Theorem scan_vertices_wf graph n (Hwf : PropertyGraph.wf graph) :\n    exists table', scan_vertices n graph = Some table'.\n  Proof using. now eexists. Qed.\n\n  Theorem filter_by_label_wf graph table ty mode n l\n                             (Hwf : PropertyGraph.wf graph)\n                             (Htype : BindingTable.of_type table ty)\n                             (Hty : match mode with\n                                    | Vertices => ty n = Some Value.GVertexT\n                                    | Edges    => ty n = Some Value.GEdgeT\n                                    end) :\n    exists table', filter_by_label mode n l graph table = Some table'.\n  Proof using.\n    autounfold with filter_by_label_db.\n    all: induction table as [| r table IH]; ins; eauto.\n  Qed.\n\n  Theorem filter_vertices_by_label_wf graph table ty n l\n                                    (Hwf : PropertyGraph.wf graph)\n                                    (Htype : BindingTable.of_type table ty)\n                                    (Hty : ty n = Some Value.GVertexT) :\n    exists table', filter_by_label Vertices n l graph table = Some table'.\n  Proof using. eapply filter_by_label_wf with (mode := Vertices); eassumption. Qed.\n\n  Theorem filter_edges_by_label_wf graph table ty n l\n                                 (Hwf : PropertyGraph.wf graph)\n                                 (Htype : BindingTable.of_type table ty)\n                                 (Hty : ty n = Some Value.GEdgeT) :\n    exists table', filter_by_label Edges n l graph table = Some table'.\n  Proof using. eapply filter_by_label_wf with (mode := Edges); eassumption. Qed.\n\n  Theorem expand_wf graph table ty mode n_from n_edge n_to d\n                    (Hwf : PropertyGraph.wf graph)\n                    (Htype : BindingTable.of_type table ty)\n                    (Hty_from : ty n_from = Some Value.GVertexT)\n                    (Hty_edge : ty n_edge = None)\n                    (Hty_to   : match mode with\n                                | All => ty n_to = None\n                                | Into => ty n_to = Some Value.GVertexT \n                                end) :\n    exists table', expand mode n_from n_edge n_to d graph table = Some table'.\n  Proof using.\n    all: autounfold with expand_db.\n    \n    eenough (exists t, fold_option _ = Some t) as [t Hfold].\n    { rewrite Hfold. now eexists. }\n\n    apply fold_option_some; intros a HIn; simpls.\n    apply in_map_iff in HIn as [r [? ?]]; subst.\n\n    edestruct BindingTable.type_of_GVertexT with (k := n_from) as [v_from Hv_from];\n      try eassumption.\n    rewrite Hv_from.\n\n    destruct mode.\n    2: edestruct BindingTable.type_of_GVertexT with (k := n_to) as [v_to Hv_to];\n        try eassumption.\n    2: rewrite Hv_to.\n    all: repeat erewrite BindingTable.type_of_None; try eassumption.\n    all: now eexists.\n  Qed.\n\n  Theorem expand_all_wf graph table ty n_from n_edge n_to d\n                  (Hwf : PropertyGraph.wf graph)\n                  (Htype : BindingTable.of_type table ty)\n                  (Hty_from : ty n_from = Some Value.GVertexT)\n                  (Hty_edge : ty n_edge = None)\n                  (Hty_to   : ty n_to   = None) :\n    exists table', expand All n_from n_edge n_to d graph table = Some table'.\n  Proof using. eapply expand_wf with (mode := All); eassumption. Qed.\n\n  Theorem expand_into_wf graph table ty n_from n_edge n_to d\n                  (Hwf : PropertyGraph.wf graph)\n                  (Htype : BindingTable.of_type table ty)\n                  (Hty_from : ty n_from = Some Value.GVertexT)\n                  (Hty_edge : ty n_edge = None)\n                  (Hty_to   : ty n_to   = Some Value.GVertexT) :\n    exists table', expand Into n_from n_edge n_to d graph table = Some table'.\n  Proof using. eapply expand_wf with (mode := Into); eassumption. Qed.\n\n  Theorem return_all_wf graph table :\n    exists table', return_all graph table = Some table'.\n  Proof using. now eexists. Qed.\n\n  (** If the operation returned some table then the type of the table is correct *)\n  \n  Theorem scan_vertices_type graph table' n \n                           (Hres : scan_vertices n graph = Some table') :\n    BindingTable.of_type table' (n |-> Value.GVertexT).\n  Proof using.\n    unfold scan_vertices in Hres.\n    injection Hres as Hres. subst. intros r' HIn.\n    apply in_map_iff in HIn as [r [Heq HIn]].\n    subst.\n    solve_type_of.\n  Qed.\n  \n  Theorem filter_by_label_type graph table table' ty mode n l\n                             (Hres : filter_by_label mode n l graph table = Some table')\n                             (Htype : BindingTable.of_type table ty) :\n    BindingTable.of_type table' ty.\n  Proof using.\n    generalize dependent table'.\n    destruct mode.\n    all: autounfold with filter_by_label_db.\n    all: induction table; ins; desf; eauto with type_of_db.\n  Qed.\n\n  Theorem expand_single_type graph r table' mode n_from n_edge n_to d\n    (Hres : expand_single mode n_from n_edge n_to d graph r = Some table') :\n      BindingTable.of_type table'\n        (n_to |-> Value.GVertexT; n_edge |-> Value.GEdgeT; Rcd.type_of r).\n  Proof using.\n    autounfold with expand_db in *.\n    desf.\n    all: intros r' HIn'.\n    all: apply in_map_iff in HIn'; desf.\n    all: solve_type_of_extension r (Rcd.type_of r).\n  Qed.\n\n  Theorem expand_type graph table table' ty mode n_from n_edge n_to d\n                          (Hres : expand mode n_from n_edge n_to d graph table = Some table')\n                          (Htype : BindingTable.of_type table ty) :\n    BindingTable.of_type table'\n      (n_to |-> Value.GVertexT; n_edge |-> Value.GEdgeT; ty).\n  Proof using.\n    unfold expand in *.\n    unfold option_map in Hres; desf.\n    destruct mode.\n\n    all: apply BindingTable.of_type_concat; intros table' HIn_tables'.\n    all: eassert (Hmap : In (Some table') (map _ table))\n          by (eapply fold_option_In; eauto).\n\n    all: apply in_map_iff in Hmap as [r ?]; desf.\n    all: assert (Rcd.type_of r = ty) as Hty by auto; subst.\n    all: eauto using expand_single_type.\n  Qed.\n\n  Theorem return_all_type graph table table' ty\n                          (Hres : return_all graph table = Some table')\n                          (Htype : BindingTable.of_type table ty) :\n    BindingTable.of_type table' (Rcd.explicit_projT ty).\n  Proof using.\n    intros r' HIn.\n    unfold return_all in Hres.\n    injection Hres as ?; subst.\n    apply in_map_iff in HIn as [r [? HIn]]; subst.\n    rewrite Rcd.type_of_explicit_proj.\n    now rewrite Htype with r.\n  Qed.\n\n  (** scan_vertices specification *)\n\n  \n  Theorem scan_vertices_spec graph table' n v\n    (Hres : scan_vertices n graph = Some table')\n    (HIn : In v (vertices graph)) :\n      In (n |-> Value.GVertex v) table'.\n  Proof using.\n    unfold scan_vertices in Hres.\n    inj_subst.\n    apply in_map_iff.\n    exists v. auto.\n  Qed.\n\n  Theorem scan_vertices_spec' graph table' n r'\n    (Hres : scan_vertices n graph = Some table')\n    (HIn : In r' table') :\n      exists v, r' = (n |-> Value.GVertex v) /\\ In v (vertices graph).\n  Proof using.\n    unfold scan_vertices in Hres.\n    inj_subst.\n    apply in_map_iff in HIn as [v [Heq HIn]].\n    subst. exists v. auto.\n  Qed.\n\n  (** filter_by_label specification *)\n\n  Theorem vertex_has_label_true_iff graph n l r :\n    vertex_has_label n l graph r = true <->\n      exists v, r n = Some (Value.GVertex v) /\\ In l (vlabels graph v).\n  Proof using.\n    split; ins.\n    all: unfold vertex_has_label in *.\n    all: desf; normalize_bool.\n    { eexists. split; eauto. }\n    now rewrite -> In_decb_true_iff.\n  Qed.\n\n  Theorem edge_has_label_true_iff graph n l r :\n    edge_has_label n l graph r = true <->\n      exists e, r n = Some (Value.GEdge e) /\\ elabel graph e = l.\n  Proof using.\n    split; ins.\n    all: unfold edge_has_label in *.\n    all: desf.\n    { eexists. split. { eauto. }\n      now rewrite <- equiv_decb_true_iff. }\n    now rewrite -> equiv_decb_true_iff.\n  Qed.\n\n  Theorem filter_by_label_spec graph table table' mode n l r \n    (Hres : filter_by_label mode n l graph table = Some table') :\n      match mode with\n      | Vertices => In r table' <-> In r table /\\\n          (exists v, r n = Some (Value.GVertex v) /\\ In l (vlabels graph v))\n      | Edges    => In r table' <-> In r table /\\\n          (exists e, r n = Some (Value.GEdge e) /\\ elabel graph e = l)\n      end.\n  Proof using.\n    unfold filter_by_label, has_label in Hres.\n    inj_subst.\n    destruct mode; ins.\n    all: rewrite filter_In.\n    1: rewrite -> vertex_has_label_true_iff; try eassumption.\n    2: rewrite -> edge_has_label_true_iff; try eassumption.\n    all: reflexivity.\n  Qed.\n\n  Theorem filter_vertices_by_label_spec graph table table' n l v r \n    (Hres : filter_by_label Vertices n l graph table = Some table')\n    (Hval : r n = Some (Value.GVertex v)) (Hlabel : In l (vlabels graph v))\n    (HIn : In r table) : In r table'.\n  Proof using.\n    rewrite -> filter_by_label_spec with (mode := Vertices); eauto.\n  Qed.\n  \n  Theorem filter_vertices_by_label_spec' graph table table' n l r' \n    (Hres : filter_by_label Vertices n l graph table = Some table')\n    (HIn : In r' table') : In r' table /\\\n        exists v, r' n = Some (Value.GVertex v) /\\ In l (vlabels graph v).\n  Proof using.\n    rewrite <- filter_by_label_spec with (mode := Vertices); eauto.\n  Qed.\n\n  Theorem filter_edges_by_label_spec graph table table' n l e r \n    (Hres : filter_by_label Edges n l graph table = Some table')\n    (Hval : r n = Some (Value.GEdge e)) (Hlabel : elabel graph e = l)\n    (HIn : In r table) : In r table'.\n  Proof using.\n    rewrite -> filter_by_label_spec with (mode := Edges); eauto.\n  Qed.\n  \n  Theorem filter_edges_by_label_spec' graph table table' n l r' \n    (Hres : filter_by_label Edges n l graph table = Some table')\n    (HIn : In r' table') : In r' table /\\\n        exists e, r' n = Some (Value.GEdge e) /\\ elabel graph e = l.\n  Proof using.\n    rewrite <- filter_by_label_spec with (mode := Edges); eauto.\n  Qed.\n  \n  (** expand specification *)\n\n  Theorem expand_single_spec graph table' r r' mode n_from n_edge n_to d\n    (Hres : expand_single mode n_from n_edge n_to d graph r = Some table') :\n      expansion_of graph r' r mode n_from n_edge n_to d <-> In r' table'.\n  Proof using.\n    split; ins.\n    all: unfold expansion_of, expansion_of', Path.matches_direction in *.\n\n    - destruct mode; desf.\n      all: autounfold with expand_db in Hres.\n      all: rewrite Hval_from, Hval_to in Hres; desf.\n      all: apply in_map_iff.\n      all: try exists (e, v_to).\n      all: try exists e.\n      all: split; [ reflexivity | ].\n      all: try apply in_or_app.\n      all: try rewrite -> in_edges_In.\n      all: try rewrite -> out_edges_In.\n      all: repeat rewrite -> edges_between_In.\n      all: unfold e_from, e_to; destruct (ends graph e); desf.\n      all: auto.\n\n    - all: autounfold with expand_db in Hres.\n      destruct mode; desf.\n      all: match goal with\n           | [ H : In _ (map _ _) |- _ ] => apply in_map_iff in H; desf\n           end.\n      all: try match goal with\n           | [ H : In _ (_ ++ _) |- _ ] => apply in_app_or in H\n           end; desf.\n      all: match goal with\n           | [ H : In _ (out_edges       _ _) |- _ ] =>\n               apply out_edges_In in H\n           | [ H : In _ (in_edges        _ _) |- _ ] =>\n               apply in_edges_In in H\n           | [ H : In _ (edges_between _ _ _) |- _ ] =>\n               apply edges_between_In in H\n           end; desf.\n      all: do 3 eexists.\n      all: splits; eauto.\n\n      all: unfold e_from, e_to in *; edestruct (ends graph _); desf; simpls.\n      all: auto.\n  Qed.\n\n  Theorem expand_spec graph table table' r r' mode n_from n_edge n_to d\n      (Hres : expand mode n_from n_edge n_to d graph table = Some table')\n      (Hexp : expansion_of graph r' r mode n_from n_edge n_to d)\n      (HIn : In r table) : In r' table'.\n  Proof using.\n    unfold expand in *.\n\n    edestruct (fold_option _) as [tables' | ] eqn:Hfold.\n    2: now inv Hres.\n    simpls; inj_subst.\n\n    eassert (Hmap : In (_ r) (map _ table)) by (now eapply in_map).\n\n    eassert (exists table', _ r = Some table') as [table' Hres].\n    { eapply fold_option_some_inv in Hfold as [table' Heq]; eauto. }\n\n    apply in_concat. exists table'. split.\n    2: now eapply expand_single_spec; eauto.\n    eapply fold_option_In; eauto.\n    unfold BindingTable.t in *.\n    now rewrite <- Hres.\n  Qed.\n\n  Theorem expand_spec' graph table table' r' mode n_from n_edge n_to d\n    (Hres : expand mode n_from n_edge n_to d graph table = Some table')\n    (HIn : In r' table') :\n      exists r, In r table /\\\n                expansion_of graph r' r mode n_from n_edge n_to d.\n  Proof using.\n    unfold expand in *.\n    edestruct (fold_option _) as [tables' | ] eqn:?.\n    2: now inv Hres.\n    simpls; inj_subst.\n\n    apply in_concat in HIn as [table' ?]; desf.\n    eassert (Hmap : In (Some table') (map _ table)).\n    { eapply fold_option_In; eassumption. }\n\n    apply in_map_iff in Hmap as [r ?]; desf.\n    exists r. split.\n    { assumption. }\n    eapply expand_single_spec; eassumption.\n  Qed.\n\n  (* return_all specification *)\n\n  Theorem return_all_spec graph table table' r\n    (Hres : return_all graph table = Some table')\n    (HIn : In r table) :\n      In (Rcd.explicit_proj r) table'.\n  Proof using.\n    unfold return_all in *.\n    injection Hres as ?; subst.\n    eapply in_map in HIn.\n    eassumption.\n  Qed.\n\n  Theorem return_all_spec' graph table table' r'\n    (Hres : return_all graph table = Some table')\n    (HIn : In r' table') :\n      exists r, In r table /\\ r' = Rcd.explicit_proj r.\n  Proof using.\n    unfold return_all in *.\n    injection Hres as ?; subst.\n    apply in_map_iff in HIn as [r ?]; desf.\n    eauto.\n  Qed.\n\n  (* traversion *)\n\n  Definition traverse := TraverseOpImpl.traverse.\n  Definition traverse_wf := TraverseOpImpl.traverse_wf.\n  Definition traverse_type := TraverseOpImpl.traverse_type.\n  Definition traverse_spec := TraverseOpImpl.traverse_spec.\n  Definition traverse_spec' := TraverseOpImpl.traverse_spec'.\nEnd ExecutionPlanImpl.\n", "meta": {"author": "cyphercert", "repo": "opencypher-coq", "sha": "ca533547e36376cda9f78b53f6a4a2b1e55e3fdc", "save_path": "github-repos/coq/cyphercert-opencypher-coq", "path": "github-repos/coq/cyphercert-opencypher-coq/opencypher-coq-ca533547e36376cda9f78b53f6a4a2b1e55e3fdc/src/ExecutionPlanImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.21815583785047438}}
{"text": "(** Heaps for code/packages\n\n  This module introduces the notion of heap for storing memory in packages.\n*)\n\n\nFrom Coq Require Import Utf8.\nFrom Relational Require Import OrderEnrichedCategory\n  OrderEnrichedRelativeMonadExamples.\nSet Warnings \"-ambiguous-paths,-notation-overridden,-notation-incompatible-format\".\nFrom mathcomp Require Import ssrnat ssreflect ssrfun ssrbool ssrnum eqtype\n  choice reals distr seq all_algebra fintype realsum.\nSet Warnings \"ambiguous-paths,notation-overridden,notation-incompatible-format\".\nFrom extructures Require Import ord fset fmap.\nFrom Mon Require Import SPropBase.\nFrom Crypt Require Import Prelude Axioms ChoiceAsOrd SubDistr Couplings\n  RulesStateProb UniformStateProb UniformDistrLemmas StateTransfThetaDens\n  StateTransformingLaxMorph chUniverse pkg_core_definition pkg_notation\n  pkg_tactics pkg_composition.\nRequire Import Equations.Prop.DepElim.\nFrom Equations Require Import Equations.\n\n(* Must come after importing Equations.Equations, who knows why. *)\nFrom Crypt Require Import FreeProbProg.\n\nSet Equations With UIP.\nSet Equations Transparent.\n\nImport SPropNotations.\nImport PackageNotation.\nImport RSemanticNotation.\n\nSet Bullet Behavior \"Strict Subproofs\".\nSet Default Goal Selector \"!\".\nSet Primitive Projections.\n\nDefinition pointed_value := ∑ (t : chUniverse), t.\n\nDefinition raw_heap := {fmap Location -> pointed_value}.\nDefinition raw_heap_choiceType := [choiceType of raw_heap].\n\nDefinition check_loc_val (l : Location) (v : pointed_value) :=\n  l.π1 == v.π1.\n\nDefinition valid_location (h : raw_heap) (l : Location) :=\n  match h l with\n  | None => false\n  | Some v => check_loc_val l v\n  end.\n\nDefinition valid_heap : pred raw_heap :=\n  λ h, domm h == fset_filter (valid_location h) (domm h).\n\nDefinition heap_defaults := ∀ a : chUniverse, a.\n\nDefinition heap_init : heap_defaults.\nProof.\n  intros a. induction a.\n  - exact tt.\n  - exact 0.\n  - exact false.\n  - exact (IHa1, IHa2).\n  - exact emptym.\n  - exact None.\n  - exact (fintype.Ordinal n.(cond_pos)).\nDefined.\n\nDefinition heap := { h : raw_heap | valid_heap h }.\n\nDefinition heap_choiceType := [choiceType of heap].\n\nLemma heap_ext :\n  ∀ (h₀ h₁ : heap),\n    h₀ ∙1 = h₁ ∙1 →\n    h₀ = h₁.\nProof.\n  intros [h₀ v₀] [h₁ v₁] e. simpl in e. subst.\n  f_equal. apply eq_irrelevance.\nQed.\n\nDefinition cast_pointed_value {A} (p : pointed_value) (e : A = p.π1) : Value A.\nProof.\n  subst. exact p.π2.\nDefined.\n\nLemma cast_pointed_value_K :\n  ∀ p e,\n    cast_pointed_value p e = p.π2.\nProof.\n  intros p e.\n  assert (e = erefl).\n  { apply eq_irrelevance. }\n  subst. reflexivity.\nQed.\n\nLemma cast_pointed_value_ext :\n  ∀ A p e1 q e2,\n    p = q →\n    @cast_pointed_value A p e1 = @cast_pointed_value A q e2.\nProof.\n  intros A p e1 q e2 e. subst.\n  cbn.\n  assert (ee : e2 = erefl).\n  { apply eq_irrelevance. }\n  rewrite ee. reflexivity.\nQed.\n\nLemma get_heap_helper :\n  ∀ h ℓ p,\n    valid_heap h →\n    h ℓ = Some p →\n    ℓ.π1 = p.π1.\nProof.\n  intros h ℓ p vh e.\n  assert (hℓ : exists v, h ℓ = Some v).\n  { eexists. eauto. }\n  move: hℓ => /dommP hℓ.\n  unfold valid_heap in vh.\n  move: vh => /eqP vh.\n  rewrite vh in hℓ.\n  rewrite in_fset_filter in hℓ.\n  move: hℓ => /andP [vℓ hℓ].\n  unfold valid_location in vℓ.\n  rewrite e in vℓ.\n  unfold check_loc_val in vℓ.\n  move: vℓ => /eqP. auto.\nQed.\n\nEquations? get_heap (map : heap) (ℓ : Location) : Value ℓ.π1 :=\n  get_heap map ℓ with inspect (map ∙1 ℓ) := {\n  | @exist (Some p) e => cast_pointed_value p _\n  | @exist None e => heap_init (ℓ.π1)\n  }.\nProof.\n  destruct map as [h vh]. simpl in e.\n  eapply get_heap_helper. all: eauto.\nDefined.\n\nProgram Definition set_heap (map : heap) (l : Location) (v : Value l.π1)\n: heap :=\n  setm map l (l.π1 ; v).\nNext Obligation.\n  intros map l v.\n  unfold valid_heap.\n  destruct map as [rh valid_rh].\n  cbn - [\"_ == _\"].\n  apply /eqP.\n  apply eq_fset.\n  move => x.\n  rewrite domm_set.\n  rewrite in_fset_filter.\n  destruct ((x \\in l |: domm rh)) eqn:Heq.\n  - rewrite andbC. cbn.\n    symmetry. apply /idP.\n    unfold valid_location.\n    rewrite setmE.\n    destruct (x == l) eqn:H.\n    + cbn. move: H. move /eqP => H. subst. apply chUniverse_refl.\n    + move: Heq. move /idP /fsetU1P => Heq.\n      destruct Heq.\n      * move: H. move /eqP => H. contradiction.\n      * destruct x, l. rewrite mem_domm in H0.\n        unfold isSome in H0.\n        destruct (rh (x; s)) eqn:Hrhx.\n        ** cbn. unfold valid_heap in valid_rh.\n            move: valid_rh. move /eqP /eq_fset => valid_rh.\n            specialize (valid_rh (x; s)).\n            rewrite in_fset_filter in valid_rh.\n            rewrite mem_domm in valid_rh.\n            assert (valid_location rh (x;s)) as Hvl.\n            { rewrite Hrhx in valid_rh. cbn in valid_rh.\n              rewrite andbC in valid_rh. cbn in valid_rh.\n              rewrite -valid_rh. auto. }\n            unfold valid_location in Hvl.\n            rewrite Hrhx in Hvl.\n            cbn in Hvl.\n            assumption.\n        ** assumption.\n  - rewrite andbC. auto.\nQed.\n\n#[program] Definition empty_heap : heap := emptym.\nNext Obligation.\n  by rewrite /valid_heap domm0 /fset_filter -fset0E.\nQed.\n\nLemma get_empty_heap :\n  ∀ ℓ,\n    get_heap empty_heap ℓ = heap_init (ℓ.π1).\nProof.\n  intros ℓ. reflexivity.\nQed.\n\nLemma get_set_heap_eq :\n  ∀ h ℓ v,\n    get_heap (set_heap h ℓ v) ℓ = v.\nProof.\n  intros h ℓ v.\n  funelim (get_heap (set_heap h ℓ v) ℓ).\n  2:{\n    pose proof e as ep. simpl in ep.\n    rewrite setmE in ep. rewrite eqxx in ep. noconf ep.\n  }\n  rewrite -Heqcall. clear Heqcall.\n  pose proof e as ep. simpl in ep.\n  rewrite setmE in ep. rewrite eqxx in ep. noconf ep.\n  rewrite (cast_pointed_value_K (ℓ0.π1 ; v)).\n  reflexivity.\nQed.\n\nLemma get_set_heap_neq :\n  ∀ h ℓ v ℓ',\n    ℓ' != ℓ →\n    get_heap (set_heap h ℓ v) ℓ' = get_heap h ℓ'.\nProof.\n  intros h ℓ v ℓ' ne.\n  funelim (get_heap (set_heap h ℓ v) ℓ').\n  - rewrite -Heqcall. clear Heqcall.\n    pose proof e as ep. simpl in ep.\n    rewrite setmE in ep.\n    eapply negbTE in ne. rewrite ne in ep.\n    funelim (get_heap h ℓ).\n    2:{\n      rewrite -e in ep. noconf ep.\n    }\n    rewrite -Heqcall. clear Heqcall.\n    apply cast_pointed_value_ext.\n    rewrite -e in ep. noconf ep. reflexivity.\n  - rewrite -Heqcall. clear Heqcall.\n    clear H. simpl in e. rewrite setmE in e.\n    eapply negbTE in ne. rewrite ne in e.\n    funelim (get_heap h ℓ).\n    1:{\n      rewrite -e in e0. noconf e0.\n    }\n    rewrite -Heqcall. reflexivity.\nQed.\n\nLemma set_heap_contract :\n  ∀ s ℓ v v',\n    set_heap (set_heap s ℓ v) ℓ v' = set_heap s ℓ v'.\nProof.\n  intros s ℓ v v'.\n  apply heap_ext. destruct s as [h vh]. simpl.\n  apply setmxx.\nQed.\n\nLemma get_heap_set_heap :\n  ∀ s ℓ ℓ' v,\n    ℓ != ℓ' →\n    get_heap s ℓ = get_heap (set_heap s ℓ' v) ℓ.\nProof.\n  intros s ℓ ℓ' v ne.\n  rewrite get_set_heap_neq. 2: auto.\n  reflexivity.\nQed.\n\nLemma set_heap_commut :\n  ∀ s ℓ v ℓ' v',\n    ℓ != ℓ' →\n    set_heap (set_heap s ℓ v) ℓ' v' =\n    set_heap (set_heap s ℓ' v') ℓ v.\nProof.\n  intros s ℓ v ℓ' v' ne.\n  apply heap_ext. destruct s as [h vh]. simpl.\n  apply setmC. auto.\nQed.", "meta": {"author": "Nsidorenco", "repo": "OpenVoteNetwork", "sha": "be771d7b74908c11d83a6cfd66542b51dfb318ab", "save_path": "github-repos/coq/Nsidorenco-OpenVoteNetwork", "path": "github-repos/coq/Nsidorenco-OpenVoteNetwork/OpenVoteNetwork-be771d7b74908c11d83a6cfd66542b51dfb318ab/theories/Crypt/package/pkg_heap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.21815583785047435}}
{"text": "Require Import Coq.Sorting.Permutation.\nRequire Import Coq.Sorting.Sorting.\nRequire Import Coq.Structures.Orders.\nRequire Import VST.veric.base.\nImport compcert.lib.Maps.\n\nRequire Import compcert.cfrontend.Ctypes. \n\n(* TODO: This is obviously true. Ask Xavior to remove the definition list_norepet.*)\nLemma list_norepet_NoDup: forall {A: Type} (l: list A), list_norepet l <-> NoDup l.\nProof.\nintros; split; intro;\ninduction H; constructor; auto.\nQed.\n\nLemma PTree_In_fst_elements {A: Type}: forall (T: PTree.t A) i,\n  In i (map fst (PTree.elements T)) <-> exists a, PTree.get i T = Some a.\nProof.\n  intros.\n  split; intros.\n  + apply list_in_map_inv in H.\n    destruct H as [[i0 a] [? ?]].\n    simpl in H; subst i0.\n    apply PTree.elements_complete in H0.\n    eauto.\n  + destruct H as [a ?].\n    apply PTree.elements_correct in H.\n    apply (in_map fst) in H.\n    auto.\nQed.\n\nLemma PTree_gs {A: Type}: forall (T: PTree.t A) i j x,\n  (exists a, PTree.get i T= Some a) ->\n  exists a, PTree.get i (PTree.set j x T) = Some a.\nProof.\n  intros.\n  destruct H.\n  destruct (Pos.eq_dec i j).\n  + subst.\n    rewrite PTree.gss; eauto.\n  + rewrite PTree.gso; eauto.\nQed.\n\nLemma PTree_gs_equiv {A: Type}: forall (T: PTree.t A) i j x,\n  (exists a, PTree.get i T= Some a) \\/ i = j <->\n  exists a, PTree.get i (PTree.set j x T) = Some a.\nProof.\n  intros.\n  split; intros.\n  + destruct H; [apply PTree_gs; auto |].\n    subst; rewrite PTree.gss; eauto.\n  + destruct (Pos.eq_dec i j); auto.\n    rewrite PTree.gso in H by auto.\n    auto.\nQed.\n\nLemma PTree_set_In_fst_elements {A: Type}: forall (T: PTree.t A) i i' a',\n  In i (map fst (PTree.elements T)) ->\n  In i (map fst (PTree.elements (PTree.set i' a' T))).\nProof.\n  intros.\n  rewrite PTree_In_fst_elements in H |- *.\n  apply PTree_gs; auto.\nQed.\n  \nFixpoint relative_defined_type {A: Type} (l: list (ident * A)) (t: type): Prop :=\n  match t with\n  | Tarray t' _ _ => relative_defined_type l t'\n  | Tstruct id _ => In id (map fst l)\n  | Tunion id _ => In id (map fst l)\n  | _ => True\n  end.\n\nLemma relative_defined_type_mono: forall {A B: Type} (l1: list (ident * A)) (l2: list (ident * B)) (t: type),\n  (forall i, In i (map fst l1) -> In i (map fst l2)) ->\n  relative_defined_type l1 t ->\n  relative_defined_type l2 t.\nProof.\n  intros.\n  induction t; auto.\n  + simpl in *.\n    firstorder.\n  + simpl in *.\n    firstorder.\nQed.\n\nLemma relative_defined_type_equiv: forall {A B: Type} (l1: list (ident * A)) (l2: list (ident * B)) (t: type),\n  (forall i, In i (map fst l1) <-> In i (map fst l2)) ->\n  (relative_defined_type l1 t <-> relative_defined_type l2 t).\nProof.\n  intros.\n  split; apply relative_defined_type_mono;\n  firstorder.\nQed.\n\nInductive ordered_composite: list (positive * composite) -> Prop :=\n| ordered_composite_nil: ordered_composite nil\n| ordered_composite_cons: forall i co l,\n    Forall (relative_defined_type l) (map type_member (co_members co)) ->\n    ordered_composite l ->\n    ordered_composite ((i, co) :: l).\n\nModule composite_reorder.\n\n(* Use merge sort instead *)\n(* Sort rank from higher to lower *)\nModule CompositeRankOrder <: TotalLeBool.\n  Definition t := (positive * composite)%type.\n  Definition leb (x y: t) := Nat.leb (co_rank (snd y)) (co_rank (snd x)).\n\n  Theorem leb_total : forall a1 a2, leb a1 a2 = true \\/ leb a2 a1 = true.\n  Proof.\n    intros.\n    unfold leb.\n    rewrite !Nat.leb_le.\n    lia.\n  Qed.\n\n  Theorem leb_trans: Transitive (fun x y => is_true (leb x y)).\n  Proof.\n    hnf; intros; unfold leb, is_true in *.\n    rewrite !Nat.leb_le in *.\n    lia.\n  Qed.\n\nEnd CompositeRankOrder.\n\nModule CompositeRankSort := Sort CompositeRankOrder.\n\nSection composite_reorder.\n\nContext (cenv: composite_env)\n        (cenv_consistent: composite_env_consistent cenv).\n\nDefinition rebuild_composite_elements := CompositeRankSort.sort (PTree.elements cenv).\n\nInductive ordered_and_complete: list (positive * composite) -> Prop :=\n| ordered_and_complete_nil: ordered_and_complete nil\n| ordered_and_complete_cons: forall i co l,\n    (forall i' co',\n        cenv ! i' = Some co' ->\n        (co_rank co' < co_rank co)%nat ->\n        In (i', co') l) ->\n    ordered_and_complete l ->\n    ordered_and_complete ((i, co) :: l).\n\nTheorem RCT_Permutation: Permutation rebuild_composite_elements (PTree.elements cenv).\nProof.\n  symmetry.\n  apply CompositeRankSort.Permuted_sort.\nQed.\n\nLemma RCT_ordered_and_complete: ordered_and_complete rebuild_composite_elements.\nProof.\n  pose proof RCT_Permutation.\n  assert (forall i co, cenv ! i = Some co -> In (i, co) rebuild_composite_elements).\n  {\n    intros.\n    eapply Permutation_in.\n    + symmetry; apply RCT_Permutation.\n    + apply PTree.elements_correct; auto.\n  } \n  clear H.\n  pose proof CompositeRankSort.StronglySorted_sort (PTree.elements cenv) CompositeRankOrder.leb_trans.\n  pose proof app_nil_l rebuild_composite_elements.\n  unfold rebuild_composite_elements in *.\n  set (l := (CompositeRankSort.sort (PTree.elements cenv))) in H1 at 1 |- *.\n  revert H1; generalize (@nil (positive * composite)).\n  clearbody l.\n  induction l; intros.\n  + constructor.\n  + specialize (IHl (l0 ++ a :: nil)).\n    rewrite <- app_assoc in IHl.\n    specialize (IHl H1).\n    destruct a as [i co]; constructor; auto.\n    intros.\n    apply H0 in H2.\n    rewrite <- H1 in H2, H.\n    clear - H2 H3 H.\n    induction l0.\n    - destruct H2; auto.\n      exfalso; inv H0.\n      lia.\n    - inv H.\n      destruct H2.\n      * exfalso.\n        subst.\n        rewrite Forall_forall in H5.\n        specialize (H5 (i, co)).\n        rewrite in_app in H5.\n        specialize (H5 (or_intror (or_introl eq_refl))).\n        unfold is_true in H5.\n        rewrite Nat.leb_le in H5; simpl in H5.\n        lia.\n      * apply IHl0; auto.\nQed.\n\nTheorem RCT_ordered: ordered_composite rebuild_composite_elements.\nProof.\n  pose proof RCT_ordered_and_complete.\n  assert (forall i co, In (i, co) rebuild_composite_elements -> complete_members cenv (co_members co) = true /\\ co_rank co = rank_members cenv (co_members co)).\n  {\n    intros.\n    eapply Permutation_in in H0; [| exact RCT_Permutation].\n    apply PTree.elements_complete in H0; auto.\n    split.\n    + apply co_consistent_complete.\n      eapply cenv_consistent; eauto.\n    + apply co_consistent_rank.\n      eapply cenv_consistent; eauto.\n  }\n  induction H.\n  + constructor.\n  + specialize (IHordered_and_complete (fun i co HH => H0 i co (or_intror HH))).\n    constructor; auto.\n    clear IHordered_and_complete H1.\n    specialize (H0 _ _ (or_introl eq_refl)).\n    assert (rank_members cenv (co_members co) <= co_rank co)%nat by lia.\n    destruct H0 as [? _].\n    induction (co_members co) as [| [i0 t0 |]].\n    - constructor.\n    - simpl in H0; rewrite andb_true_iff in H0; destruct H0.\n      simpl in H1; pose proof Nat.max_lub_r _ _ _ H1.\n      apply Nat.max_lub_l in H1.\n      constructor; auto; clear IHm H2 H3.\n      simpl.\n      induction t0; try solve [simpl; auto].\n      * (* array *)\n        spec IHt0; auto.\n        spec IHt0; [simpl in H1; lia |].\n        auto.\n      * (* struct *)\n        simpl in H0, H1 |- *.\n        destruct (cenv ! i1) eqn:?H; [| inv H0].\n        specialize (H _ _ H2).\n        spec H; [lia |].\n        apply (in_map fst) in H; auto.\n      * (* union *)\n        simpl in H0, H1 |- *.\n        destruct (cenv ! i1) eqn:?H; [| inv H0].\n        specialize (H _ _ H2).\n        spec H; [lia |].\n        apply (in_map fst) in H; auto.\n    - constructor. simpl; auto.\n       auto.\nQed.\n\nEnd composite_reorder.\n\nEnd composite_reorder.\n\nModule type_func.\nSection type_func.\n\nContext {A: Type}\n        (f_default: type -> A)\n        (f_array: A -> type -> Z -> attr -> A)\n        (f_struct: A -> ident -> attr -> A)\n        (f_union: A -> ident -> attr -> A)\n        (f_member: struct_or_union -> list (member * A) -> A).\n\nFixpoint F (env: PTree.t A) (t: type): A :=\n  match t with\n  | Tarray t n a => f_array (F env t) t n a\n  | Tstruct id a =>\n      match env ! id with\n      | Some v => f_struct v id a\n      | None => f_default t\n      end\n  | Tunion id a =>\n      match env ! id with\n      | Some v => f_union v id a\n      | None => f_default t\n      end\n  | _ => f_default t\n  end.\n\nDefinition Complete (cenv: composite_env) (env: PTree.t A): Prop :=\n  forall i,\n    (exists co, PTree.get i cenv = Some co) <->\n    (exists a, PTree.get i env = Some a).\n\nDefinition f_members (co: composite) (env: PTree.t A) : A :=\n  f_member (co_su co)\n            (map (fun m => (m, F env (type_member m))) (co_members co)).\n\n\nDefinition Consistent (cenv: composite_env) (env: PTree.t A): Prop :=\n  forall i co a,\n    PTree.get i cenv = Some co ->\n    PTree.get i env = Some a ->\n    a = f_members co env.\n\nDefinition Env (l: list (positive * composite)): PTree.t A :=\n  fold_right\n    (fun (ic: positive * composite) env =>\n       let (i, co) := ic in PTree.set i (f_members co env) env)\n    (PTree.empty A)\n    l.\n\nLemma F_PTree_set: forall t env i a,\n  ~ In i (map fst (PTree.elements env)) ->\n  relative_defined_type (PTree.elements env) t ->\n  F env t = F (PTree.set i a env) t.\nProof.\n  intros.\n  induction t; auto.\n  + simpl.\n    apply IHt in H0.\n    rewrite H0; auto.\n  + simpl in H0 |- *.\n    rewrite PTree.gso; auto.\n    intro; subst; tauto.\n  + simpl in H0 |- *.\n    rewrite PTree.gso; auto.\n    intro; subst; tauto.\nQed.\n\nLemma relative_defined_type_PTree_set: forall t (env: PTree.t A) i a,\n  relative_defined_type (PTree.elements env) t ->\n  relative_defined_type (PTree.elements (PTree.set i a env)) t.\nProof.\n  intros.\n  revert H; apply relative_defined_type_mono.\n  intros; apply PTree_set_In_fst_elements; auto.\nQed.\n\nSection Consistency_Induction_Step.\n\nContext (cenv: composite_env)\n        (env: PTree.t A)\n        (l: list (positive * composite))\n        (i0: positive)\n        (co0: composite).\n\nHypothesis NOT_IN_LIST: ~ In i0 (map fst l).\n\nHypothesis RDT_list: Forall (relative_defined_type l) (map type_member (co_members co0)).\n\nHypothesis CENV0: PTree.get i0 cenv = Some co0.\n\nHypothesis IH_In_equiv: forall i, In i (map fst l) <-> In i (map fst (PTree.elements env)).\n\nHypothesis IH_RDT:\n  forall i co a,\n    PTree.get i cenv = Some co ->\n    PTree.get i env = Some a ->\n    Forall (relative_defined_type (PTree.elements env)) (map type_member (co_members co)).\n\nHypothesis IH_main:\n  Consistent cenv env.\n\nLemma NOT_IN: ~ In i0 (map fst (PTree.elements env)).\nProof.\n  intros.\n  rewrite <- IH_In_equiv; auto.\nQed.\n\nLemma RDT_PTree: Forall (relative_defined_type (PTree.elements env)) (map type_member (co_members co0)).\nProof.\n  intros.\n  revert RDT_list; apply Forall_impl.\n  intros t.\n  apply relative_defined_type_mono.\n  firstorder.\nQed.\n\nLemma establish_In_equiv:\n  forall i, In i (map fst ((i0, co0) :: l)) <-> In i (map fst (PTree.elements (PTree.set i0 (f_members co0 env) env))).\nProof.\n  intros.\n  specialize (IH_In_equiv i).\n  rewrite PTree_In_fst_elements in IH_In_equiv |- *.\n  rewrite <- PTree_gs_equiv.\n  simpl In.\n  assert (i0 = i <-> i = i0) by (split; intros; congruence).\n  tauto.\nQed.\n\nLemma establish_RDT:\n  forall i co a,\n    PTree.get i cenv = Some co ->\n    PTree.get i (PTree.set i0 (f_members co0 env) env) = Some a ->\n    Forall (relative_defined_type (PTree.elements (PTree.set i0 (f_members co0 env) env))) (map type_member (co_members co)).\nProof.\n  pose proof RDT_PTree as RDT_PTree.\n  intros i co a CENV ENV.\n  destruct (Pos.eq_dec i i0).\n  + subst i0; rewrite CENV in CENV0; inversion CENV0; subst co0; clear CENV0.\n    rewrite PTree.gss in ENV.\n    inversion ENV; clear a ENV H0.\n    revert RDT_PTree.\n    apply Forall_impl; intros t.\n    apply relative_defined_type_PTree_set.\n  + rewrite PTree.gso in ENV by auto.\n    specialize (IH_RDT _ _ _ CENV ENV).\n    revert IH_RDT.\n    apply Forall_impl; intros t.\n    apply relative_defined_type_PTree_set.\nQed.\n\nLemma establish_main:\n  Consistent cenv (PTree.set i0 (f_members co0 env) env).\nProof.\n  pose proof NOT_IN as NOT_IN.\n  pose proof RDT_PTree as RDT_PTree.\n  intros i co a CENV ENV.\n  destruct (Pos.eq_dec i i0).\n  + subst i0; rewrite CENV in CENV0; inversion CENV0; subst co0; clear CENV0.\n    rewrite PTree.gss in ENV.\n    inversion ENV; clear a ENV H0.\n    unfold f_members.\n    f_equal.\n    apply map_ext_in.\n    intros. simpl.\n    f_equal.\n    apply F_PTree_set; auto.\n    rewrite Forall_forall in RDT_PTree; apply RDT_PTree.\n    apply (in_map type_member) in H; auto.\n  + rewrite PTree.gso in ENV by auto.\n    specialize (IH_main _ _ _ CENV ENV).\n    subst a.\n    unfold f_members.\n    f_equal.\n    apply map_ext_in.\n    intros. simpl.\n    f_equal.\n    apply F_PTree_set; auto.\n    specialize (IH_RDT _ _ _ CENV ENV).\n    rewrite Forall_forall in IH_RDT; apply IH_RDT.\n    apply (in_map type_member) in H; auto.\nQed.\n\nEnd Consistency_Induction_Step.\n\nLemma Consistency: forall cenv l,\n  Permutation l (PTree.elements cenv) ->\n  ordered_composite l ->\n  Consistent cenv (Env l).\nProof.\n  intros.\n  assert (forall i co, In (i, co) l -> PTree.get i cenv = Some co).\n  {\n    intros.\n    apply PTree.elements_complete.\n    eapply Permutation_in; eauto.\n  }\n  assert (NoDup (map fst l)).\n  {\n    eapply Permutation_NoDup; [symmetry; apply Permutation_map; eassumption |].\n    rewrite <- list_norepet_NoDup.\n    apply PTree.elements_keys_norepet.\n  }\n  clear H.\n  assert (\n    (forall i, In i (map fst l) <-> In i (map fst (PTree.elements (Env l)))) /\\\n    (forall i co a,\n      PTree.get i cenv = Some co ->\n      PTree.get i (Env l) = Some a ->\n      Forall (relative_defined_type (PTree.elements (Env l))) (map type_member (co_members co))) /\\\n    Consistent cenv (Env l)); [| tauto].\n  induction l as [| [i0 co0] l].\n  + split; [| split]; hnf; intros.\n    - simpl; tauto.\n    - unfold Env in H3; simpl in H3.\n      rewrite PTree.gempty in H3; inv H3.\n    - unfold Env in H3; simpl in H3.\n      rewrite PTree.gempty in H3; inv H3.\n  + inv H0.\n    rename H4 into RDT_list; specialize (IHl H6); clear H6.\n    assert (CENV0: PTree.get i0 cenv = Some co0).\n    { apply H1; left; auto. }\n    spec IHl; [| clear H1].\n    { intros; apply H1; right; auto. } \n    inv H2.\n    rename H1 into NOT_IN_LIST; specialize (IHl H3); clear H3.\n    destruct IHl as [IH_In_equiv [IH_RDT IH_main]].\n    split; [| split].\n    - apply establish_In_equiv; auto.\n    - eapply establish_RDT; eauto.\n    - eapply establish_main; eauto.\nQed.\n\nLemma Completeness: forall cenv l,\n  Permutation l (PTree.elements cenv) ->\n  Complete cenv (Env l).\nProof.\n  intros.\n  intro.\n  rewrite <- !PTree_In_fst_elements.\n  pose proof PTree.elements_keys_norepet cenv.\n  rewrite list_norepet_NoDup in H0.\n  rewrite <- H in H0 |- *; clear H.\n  induction l.\n  + simpl; tauto.\n  + destruct a as [i0 co0].\n    inv H0.\n    specialize (IHl H3).\n    simpl.\n    rewrite PTree_In_fst_elements, <- PTree_gs_equiv, <- PTree_In_fst_elements.\n    assert (i = i0 <-> i0 = i) by (split; intros; congruence).\n    tauto.\nQed.\n\nEnd type_func.\n\nEnd type_func.\n\nCorollary composite_reorder_consistent {A: Type}:\n  forall cenv f_default f_array f_struct f_union f_members,\n    composite_env_consistent cenv ->\n    type_func.Consistent f_default f_array f_struct f_union f_members cenv (@type_func.Env A f_default f_array f_struct f_union f_members (composite_reorder.rebuild_composite_elements cenv)).\nProof.\n  intros.\n  apply type_func.Consistency.\n  + apply composite_reorder.RCT_Permutation.\n  + apply composite_reorder.RCT_ordered; auto.\nQed.\n\nCorollary composite_reorder_complete {A: Type}:\n  forall cenv f_default f_array f_struct f_union f_members,\n    type_func.Complete cenv (@type_func.Env A f_default f_array f_struct f_union f_members (composite_reorder.rebuild_composite_elements cenv)).\nProof.\n  intros.\n  apply type_func.Completeness.\n  apply composite_reorder.RCT_Permutation.\nQed.\n\nFixpoint plain_members (m: members) : bool :=\n match m with\n | Member_plain i t :: m' => plain_members m'\n | _ :: _ => false\n | nil => true\n end.\n\nSection cuof.\n\nContext (cenv: composite_env).\n\nFixpoint complete_legal_cosu_type t :=\n  match t with\n  | Tarray t' _ _ => complete_legal_cosu_type t'\n  | Tstruct id _ => match cenv ! id with\n                    | Some co => match co_su co with\n                                 | Struct => plain_members (co_members co)\n                                 | Union => false\n                                 end\n                    | _ => false\n                    end\n  | Tunion id _ => match cenv ! id with\n                   | Some co => match co_su co with\n                                | Struct => false\n                                | Union => plain_members (co_members co)\n                                end\n                   | _ => false\n                   end\n  | Tfunction _ _ _\n  | Tvoid => false\n  | _ => true\n  end.\n\nFixpoint composite_complete_legal_cosu_type (m: members): bool :=\n  match m with\n  | nil => true\n  | m1 :: m' => complete_legal_cosu_type (type_member m1) && composite_complete_legal_cosu_type m'\n  end.\n\nDefinition composite_env_complete_legal_cosu_type: Prop :=\n  forall (id : positive) (co : composite),\n    cenv ! id = Some co -> composite_complete_legal_cosu_type (co_members co) = true.\n  \nEnd cuof.\n\nLemma complete_legal_cosu_type_complete_type: forall cenv: composite_env,\n  forall t,\n    complete_legal_cosu_type cenv t = true ->\n    complete_type cenv t = true.\nProof.\n  intros.\n  induction t; auto.\n  + simpl in *.\n    destruct (cenv ! i); auto.\n  + simpl in *.\n    destruct (cenv ! i); auto.\nQed.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/veric/composite_compute.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21807804960452362}}
{"text": "Require Import ABS.Rel.Definitions.\nRequire Import ABS.Rel.Adequacy.\nRequire Import ABS.Rel.Compat.\nRequire Import ABS.Rel.Parametricity.\nRequire Import ABS.Lang.BindingsFacts.\nRequire Import ABS.Lang.Static.\nRequire Import ABS.Lang.StaticFacts.\nRequire Import ABS.Lang.Context.\nRequire Import FunctionalExtensionality.\n\nImplicit Types EV HV V L : Set.\n\nSection section_congruence.\n\nHint Resolve ok_wf_lbl ok_wf_ty ok_wf_eff ok_wf_tm ok_wf_hd.\nHint Resolve XLEnv_inv_wf_XEnv.\nHint Resolve EV_map_XLEnv HV_map_XLEnv LEnv_lookup_inv_binds.\nHint Constructors ok_lbl.\nHint Unfold compose.\n\nFixpoint\ncongruence_tm n EV HV V L (t₁ t₂ : tm EV HV V L)\n(Π : LEnv EV HV L) (P : HV → F) (Γ : V → ty EV HV L)\n(T : ty EV HV L) (𝓔 : eff EV HV L) (T0 : ty0)\nC (OK_C : ok_ctx C P Γ Π T 𝓔 T0) {struct OK_C} :\nn ⊨ 【 Π P Γ ⊢ t₁ ≼ˡᵒᵍ t₂ : T # 𝓔 】 →\nn ⊨ 【 LEnv_empty ∅→ ∅→ ⊢ (ctx_plug C t₁) ≼ˡᵒᵍ (ctx_plug C t₂) : T0 # [] 】\n.\nProof.\nintro H.\ndestruct OK_C as [\n  |\n  |\n  |\n  ???? C s ??????? OK_C OK_s |\n  ???? C s ??????? OK_C OK_s |\n  ???? C ????? OK_C |\n  ???? C P Γ Π 𝔽 T T'' OK_C |\n  ???? C P Γ Π S T E T'' OK_C |\n  ???? C E P Γ Π T ? T'' OK_C OK_E |\n  ???? C h P Γ Π 𝔽 T 𝓔 T'' OK_C OK_h |\n  ???? C t 𝔽 β P Γ Π T 𝓔 T' T'' h ? OK_C OK_t |\n  ???? C s P Γ Π S T E T'' OK_C OK_s |\n  ???? C t P Γ Π S T E T'' OK_C OK_t |\n  ???? C P Γ Π T1 E1 T2 E2 T'' OK_C\n] ; simpl ctx_plug.\n+ apply H ; rewrite empty_def ; try rewrite keys_def ;\n    try rewrite map_nil ; simpl ; shelve.\n+ eapply congruence_tm ; try exact OK_C.\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ ; simpl.\n  eapply compat_tm_down ; [intro;eauto|eauto|eauto|eauto|].\n  intros X FrX.\n  ispecialize H (Ξ & X ~ (L_bind_ty f T, L_bind_eff f E)).\n  ispecialize H (env_ext f (lid_f X)).\n  ispecialize H.\n  { iintro_prop ; constructor ; eauto. }\n  simpl in H.\n  unshelve erewrite L_bind_map_ty, L_map_ty_id in H ; [eauto|eauto| |eauto|].\n  unshelve erewrite L_bind_map_eff, L_map_eff_id in H ; [eauto|eauto| |eauto|].\n  repeat erewrite L_bind_bind_tm with (g := env_ext f (lid_f X)).\n  match goal with\n  | [ H : ?n ⊨ ⟦ _ _ ?Γ ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ |- ?n ⊨ ⟦ _ _ ?Γ' ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ ] =>\n    replace Γ' with Γ ; [ exact H | ]\n  end.\n  { extensionality x ; unfold compose.\n    unshelve erewrite L_bind_map_ty, L_map_ty_id ; eauto.\n    intro ; erewrite L_map_lid_id ; eauto.\n  }\n  { intro α ; destruct α ; simpl ; [auto|].\n    unshelve erewrite L_bind_map_lid, L_map_lid_id, L_bind_lid_id ; auto.\n  }\n  { intro α ; destruct α ; simpl ; [auto|].\n    unshelve erewrite L_bind_map_lid, L_map_lid_id, L_bind_lid_id ; auto.\n  }\n  { intro ; erewrite L_map_lid_id ; auto. }\n  { intro ; erewrite L_map_lid_id ; auto. }\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl ; eapply compat_tm_val.\n  repeat unshelve erewrite L_bind_map_ty, L_bind_ty_id, L_map_ty_id ;\n    [auto|auto|auto|auto| |auto|auto|auto|auto|auto|auto].\n  eapply compat_val_up ; [reflexivity|reflexivity|reflexivity|eauto|].\n  destruct (f β) as [|X] eqn:EQ_fβ ; simpl ; [auto|].\n  eapply compat_hd_def ; [eauto|eauto|].\n  match goal with\n  | [ H : ?n ⊨ ⟦ _ _ ?Γ ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ |- ?n ⊨ ⟦ _ _ ?Γ' ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ ] =>\n    replace Γ' with Γ ; [ exact H | ]\n  end.\n  extensionality x ; unfold compose.\n  destruct x as [|[|x]] ; simpl.\n  - unshelve erewrite L_bind_map_ty, L_bind_ty_id, L_map_ty_id ; eauto.\n  - unshelve erewrite L_bind_map_ty, L_bind_ty_id, L_map_ty_id ; eauto.\n  - auto.\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl ; eapply compat_tm_let ; [|exact H].\n  apply parametricity_tm_n ; [ eauto | intro ; eauto | ].\n  eapply ok_wf_tm in OK_s ; [|eauto].\n  match goal with\n  | [ H : wf_tm ?Ξ ?P ?Γ ?t ?T ?E |- wf_tm ?Ξ ?P ?Γ' ?t ?T ?E ] =>\n    replace Γ' with Γ ; [ exact H | ]\n  end.\n  extensionality x ; crush.\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl ; apply compat_tm_let with (S := L_bind_ty f S).\n  { match goal with\n    | [ H : ?n ⊨ ⟦ _ _ ?Γ ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ |- ?n ⊨ ⟦ _ _ ?Γ' ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ ] =>\n      replace Γ' with Γ ; [ exact H | ]\n    end.\n    extensionality x ; crush.\n  }\n  apply parametricity_tm_n ; [ eauto | intro ; eauto | eauto ].\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl in H|-* ; apply compat_tm_val ; apply compat_val_efun.\n  match goal with\n  | [ H : ?n ⊨ ⟦ _ _ ?Γ ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ |- ?n ⊨ ⟦ _ _ ?Γ' ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ ] =>\n    replace Γ' with Γ ; [ exact H | ]\n  end.\n  extensionality x ; unfold compose.\n  rewrite L_bind_EV_map_ty ; auto.\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl in H|-* ; apply compat_tm_val ; apply compat_val_hfun.\n  match goal with\n  | [ H : ?n ⊨ ⟦ _ _ ?Γ ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ |- ?n ⊨ ⟦ _ _ ?Γ' ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ ] =>\n    replace Γ' with Γ ; [ exact H | ]\n  end.\n  extensionality x ; unfold compose.\n  rewrite L_bind_HV_map_ty ; auto.\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl in H|-* ; apply compat_tm_val ; apply compat_val_fun.\n  match goal with\n  | [ H : ?n ⊨ ⟦ _ _ ?Γ ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ |- ?n ⊨ ⟦ _ _ ?Γ' ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ ] =>\n    replace Γ' with Γ ; [ exact H | ]\n  end.\n  extensionality x ; auto.\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl in H|-*.\n  erewrite <- EV_L_bind_ty ; [ eapply compat_tm_eapp ; eauto | auto ].\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl in H|-*.\n  erewrite <- HV_L_bind_ty with (g₂ := HV_substfun _) ; [|auto].\n  eapply compat_tm_happ ; [reflexivity|reflexivity| |exact H|].\n  - rewrite lbl_L_bind_hd.\n    eapply ok_wf_lbl ; [ eauto | ].\n    inversion OK_h ; crush.\n  - eapply parametricity_hd_n ; [eauto|intro ; eauto|eauto].\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  destruct (f β) as [|X] eqn:EQ_fβ ; simpl ; [auto|].\n  erewrite <- HV_L_bind_ty with (g₂ := HV_substfun _) ; [|auto].\n  rewrite EQ_fβ.\n  erewrite HV_bind_ty_eq\n    with (g := HV_substfun (hd_def 𝔽 (lid_f X) (L_bind_tm f t₁))) ;\n  [ | destruct p ; simpl ; [ rewrite lbl_L_bind_hd | ] ; crush ].\n  match goal with\n  | [ H : LEnv_lookup β _ = _ |- _ ] =>\n    eapply LEnv_lookup_inv_binds in H as Binds ; eauto\n  end.\n  eapply compat_tm_happ ; [reflexivity|reflexivity| | |].\n  - constructor.\n    eauto using get_some_inv.\n  - eapply parametricity_tm_n ; [eauto|intro ; eauto|].\n    eapply ok_wf_tm in OK_t ; eauto.\n  - eapply compat_hd_def ; [eauto|eauto|].\n    match goal with\n    | [ H : ?n ⊨ ⟦ _ _ ?Γ ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ |- ?n ⊨ ⟦ _ _ ?Γ' ⊢ _ ≼ˡᵒᵍ _ : _ # _ ⟧ ] =>\n      replace Γ' with Γ ; [ exact H | ]\n    end.\n    extensionality x ; unfold compose.\n    destruct x as [|[|x]] ; simpl ; [| |auto].\n    * unshelve erewrite L_bind_map_ty, L_bind_ty_id, L_map_ty_id ; eauto.\n    * unshelve erewrite L_bind_map_ty, L_bind_ty_id, L_map_ty_id ; eauto.\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl in H|-* ; eapply compat_tm_app ; [exact H|].\n  eapply parametricity_tm_n ; [eauto|intro ; eauto|eauto].\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  simpl in H|-* ; eapply compat_tm_app ; [|exact H].\n  eapply parametricity_tm_n ; [eauto|intro ; eauto|].\n  eapply ok_wf_tm in OK_t ; eauto.\n+ eapply congruence_tm ; [exact OK_C|].\n  iintro Ξ ; iintro f ; iintro HΞΠ ; ielim_prop HΞΠ.\n  iespecialize H ; ispecialize H ; [eauto|].\n  eapply compat_sub with (𝓔 := L_bind_eff f E1) ; eauto using subty_st, L_bind_se.\nQed.\n\nEnd section_congruence.\n\nSection section_soundness.\n\nHint Rewrite dom_empty union_empty_l Xs_ctx_plug.\n\nTheorem soundness EV HV V L (t₁ t₂ : tm EV HV V L) (Closed_t₁ : Xs_tm t₁ = \\{})\n(Π : LEnv EV HV L) (P : HV → F) (Γ : V → ty EV HV L)\n(T : ty EV HV L) (𝓔 : eff EV HV L) :\n⊨ 【 Π P Γ ⊢ t₁ ≼ˡᵒᵍ t₂ : T # 𝓔 】 →\n【 Π P Γ ⊢ t₁ ≼ᶜᵗˣ t₂ : T # 𝓔 】.\nProof.\nintro Ht.\nintros C T0 OK_C Closed_C.\neapply adequacy ; [ | crush ].\nintro n.\neapply congruence_tm with (n := n) in Ht as HCt ; [|exact OK_C].\niespecialize HCt.\nispecialize HCt ; [ iintro_prop ; constructor | ].\nerewrite L_bind_tm_id, L_bind_tm_id, L_bind_ty_id, L_bind_eff_id in HCt ;\n  [|auto|auto|auto|auto].\nreplace (L_bind_ty ∅→ ∘ ∅→) with (∅→ : ∅ → ty0) in HCt ; [|extensionality x ; auto].\nexact HCt.\nQed.\n\nEnd section_soundness.\n", "meta": {"author": "yizhouzhang", "repo": "abseff-coq", "sha": "129c08fde2b4e41b5348db397c8a8f0e30f14cb5", "save_path": "github-repos/coq/yizhouzhang-abseff-coq", "path": "github-repos/coq/yizhouzhang-abseff-coq/abseff-coq-129c08fde2b4e41b5348db397c8a8f0e30f14cb5/coq-src/ABS/Rel/Soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.21802798640008061}}
{"text": "From mathcomp\nRequire Import ssreflect ssrfun fingroup.\n\nRequire Import commfingroup.\nRequire Import Cheerios.Cheerios.\nRequire Import serializable.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nImport GroupScope.\n\nModule SerializableCommFinGroup.\n\nStructure mixin_of (gT : commFinGroupType) := Mixin {\n  ser_gT : gT -> IOStreamWriter.t ;\n  deser_gT : ByteListReader.t gT ;\n  _ : serialize_deserialize_id_spec ser_gT deser_gT\n}.\n\nStructure type : Type := Pack {\n  sort : commFinGroupType;\n  _ : mixin_of sort\n}.\n\nDefinition mixin T :=\n  let: Pack _ m := T return mixin_of (sort T) in m.\n\nModule Import Exports.\nCoercion sort : type >-> commFinGroupType.\nCoercion mixin : type >-> mixin_of.\nNotation serializableCommFinGroupType := type.\nNotation SerializableCommFinGroupMixin := Mixin.\nNotation SerializableCommFinGroupType T m := (@Pack T m).\nEnd Exports.\n\nEnd SerializableCommFinGroup.\nExport SerializableCommFinGroup.Exports.\n\nSection SerializableCommGroupDefs.\n\nVariable gT : serializableCommFinGroupType.\n\nLemma ser_gT_deser_gT_id : \n  serialize_deserialize_id_spec (SerializableCommFinGroup.ser_gT gT) (SerializableCommFinGroup.deser_gT gT).\nProof. by case: gT => ? []. Qed.\n\nDefinition serCFG_serializableMixin := SerializableMixin ser_gT_deser_gT_id.\n\nCanonical serCFG_serializableType := Eval hnf in SerializableType gT serCFG_serializableMixin.\n\nEnd SerializableCommGroupDefs.\n", "meta": {"author": "DistributedComponents", "repo": "verdi-aggregation", "sha": "c81681555d63d4a3db225119600833868caf4607", "save_path": "github-repos/coq/DistributedComponents-verdi-aggregation", "path": "github-repos/coq/DistributedComponents-verdi-aggregation/verdi-aggregation-c81681555d63d4a3db225119600833868caf4607/lib/serializablecommfingroup.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3775406617944891, "lm_q1q2_score": 0.21802798235550153}}
{"text": "(* Copyright (c) 2011. Greg Morrisett, Gang Tan, Joseph Tassarotti, \n   Jean-Baptiste Tristan, and Edward Gan.\n\n   This file is part of RockSalt.\n\n   This file is free software; you can redistribute it and/or\n   modify it under the terms of the GNU General Public License as\n   published by the Free Software Foundation; either version 2 of\n   the License, or (at your option) any later version.\n*)\n\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Strings.String.\nRequire Import Coq.omega.Omega.\n\nRequire Import Coqlib.\nRequire Import CommonTacs.\nRequire Import Parser.\nRequire Import Decode.\nRequire Import Recognizer.\nRequire Import X86Semantics.\nRequire Import X86Lemmas.\nRequire Import X86Model.Monad.\n\nRequire Import Int32.\nRequire Import VerifierDFA.\nRequire Import FastVerifier.\n\n(* todo: add them back when they are up-to-date*)\n(* Require Import DFACorrectness. *)\n(* Require Import NACLjmp. *)\n\nImport ParserArg.X86_PARSER_ARG.\n(* Import X86_PARSER. *)\n(* Import X86_BASE_PARSER. *)\nImport X86_RTL.\nImport X86_MACHINE.\nImport X86_Compile.\nRequire Import RTL.\n\nDefinition emptyPrefix := mkPrefix None None false false.\n\nModule Int32SetFacts := Coq.MSets.MSetFacts.Facts FastVerifier.Int32Set.\n\n(* The following definitions and theorems are from DFACorrectness.v; \n  they should be removed once that file is up-to-date *)\n\nFixpoint simple_parse' (ps:ParseState_t) (bytes:list int8) : \n  option ((prefix * instr) * list int8) := \n  match bytes with \n    | nil => None\n    | b::bs => match parse_byte ps b with \n                 | (ps',nil) => simple_parse' ps' bs\n                 | (_, v::_) => Some (v,bs)\n               end\n  end.\n\nImport ABSTRACT_INI_DECODER_STATE.\nDefinition simple_parse (bytes:list int8) : option ((prefix * instr) * list int8) := \n  simple_parse' abs_ini_decoder_state bytes.\n\nModule Type ABSTRACT_MAKE_RECOGNIZER_SIG.\n  Parameter abstract_make_recognizer : \n    forall t, grammar t -> Recognizer.DFA.\n  Parameter make_recognizer_eq : abstract_make_recognizer = make_recognizer.\nEnd ABSTRACT_MAKE_RECOGNIZER_SIG.\n\nModule ABSTRACT_MAKE_RECOGNIZER : ABSTRACT_MAKE_RECOGNIZER_SIG.\n  Definition abstract_make_recognizer := make_recognizer.\n  Definition make_recognizer_eq := eq_refl make_recognizer.\nEnd ABSTRACT_MAKE_RECOGNIZER.\n\nDefinition nat_to_byte(n:nat) : int8 := Word.repr (Z_of_nat n).\n\nLocal Open Scope list_scope.\n\nImport ABSTRACT_MAKE_RECOGNIZER.\n\nLemma non_cflow_dfa_length : \n  forall (d:DFA), \n    (* Need to use abstract_build_dfa for the same reason as above I believe *)\n    abstract_make_recognizer _ non_cflow_grammar = d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize d (List.map byte2token bytes) = Some (n, nats2) -> \n        (n <= 15)%nat. \nAdmitted.\n\nLemma non_cflow_dfa_corr : \n  forall (d:DFA), \n    abstract_make_recognizer _ non_cflow_grammar = d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize d (List.map byte2token bytes) = Some (n, nats2) -> \n      exists bytes1, exists pfx:prefix, exists ins:instr, \n        simple_parse bytes = Some ((pfx,ins), List.map nat_to_byte nats2) /\\\n        non_cflow_instr pfx ins = true /\\\n        n = length bytes1 /\\ \n        bytes = bytes1 ++ (List.map nat_to_byte nats2).\nAdmitted.\n\nLemma dir_cflow_dfa_corr : \n  forall (d:DFA),\n    abstract_make_recognizer _ (alts dir_cflow) = d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize d (List.map byte2token bytes) = Some (n, nats2) -> \n      exists bytes1, exists pfx:prefix, exists ins:instr,\n        simple_parse bytes = Some ((pfx,ins), List.map nat_to_byte nats2) /\\\n        dir_cflow_instr pfx ins = true /\\\n        n = length bytes1 /\\ \n        bytes = bytes1 ++ (List.map nat_to_byte nats2).\nAdmitted.\n\nLemma dir_cflow_dfa_length : \n  forall (d:DFA), \n    (* Need to use abstract_build_dfa for the same reason as above I believe *)\n    abstract_make_recognizer _ (alts dir_cflow) = d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize d (List.map byte2token bytes) = Some (n, nats2) -> \n        (n <= 15)%nat. \nAdmitted.\n\nLemma nacljmp_dfa_corr : \n  forall (d:DFA),\n    abstract_make_recognizer _ (alts nacljmp_mask) = d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize d (List.map byte2token bytes) = Some (n, nats2) -> \n      exists bytes1, exists pfx1:prefix, exists ins1:instr, exists bytes2,\n        exists pfx2:prefix, exists ins2:instr,\n        simple_parse bytes = Some ((pfx1,ins1), bytes2 ++ List.map nat_to_byte nats2)\n        /\\\n        simple_parse (bytes2 ++ List.map nat_to_byte nats2) = \n            Some ((pfx2,ins2), List.map nat_to_byte nats2) /\\\n        nacljmp_mask_instr pfx1 ins1 pfx2 ins2 = true /\\\n        n = length (bytes1 ++ bytes2) /\\ \n        bytes = bytes1 ++ bytes2 ++ (List.map nat_to_byte nats2).\nAdmitted.\n\nLemma nacljmp_mask_dfa_length : \n  forall (d:DFA), \n    (* Need to use abstract_build_dfa for the same reason as above I believe *)\n    abstract_make_recognizer _ (alts nacljmp_mask) = d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize d (List.map byte2token bytes) = Some (n, nats2) -> \n        (n <= 15)%nat. \nAdmitted.\n\n(* The above definitions and theorems are from DFACorrectness.v; \n  they should be removed once that file is up-to-date *)\n\nOpen Scope Z_scope.\n\n(** * Misc. lemmas *)\n\n(** ** Properties of chunkSize *)\nLemma chunkSize_gt_0 : chunkSize > 0.\nProof. unfold chunkSize. apply Coqlib.two_power_nat_pos. Qed.\n\nLemma chunkSize_divide_modulus : Znumtheory.Zdivide chunkSize (Word.modulus 31).\nProof. unfold chunkSize, Word.modulus. apply two_power_nat_divide.\n  unfold wordsize. unfold logChunkSize. omega.\nQed.\n\nLemma Zmod_mod_modulus_chunkSize :\n  forall x:Z, x mod chunkSize = (x mod (Word.modulus 31)) mod chunkSize.\nProof. intros; apply Znumtheory.Zmod_div_mod.\n  apply Zgt_lt. apply chunkSize_gt_0.\n    apply Zgt_lt. apply modulus_pos.\n    apply chunkSize_divide_modulus.\nQed.\n\n(** ** Properties of aligned *)\n\nLemma aligned_plus :\n  forall a b:int32, aligned a -> aligned b -> aligned (a +32 b).\nProof. unfold aligned, aligned_bool. intros a b H1 H2.\n  apply Zeq_is_eq_bool in H1; apply Zeq_is_eq_bool in H2; \n    apply Zeq_is_eq_bool.\n  unfold unsigned in * |- *.\n  destruct a as [a' Ha]. destruct b as [b' Hb].\n  simpl in * |- *. \n  rewrite <- Zmod_mod_modulus_chunkSize.\n  rewrite Zplus_mod. rewrite H1, H2. simpl. apply Zmod_0_l.\nQed.\n\nLemma aligned_neg :\n  forall a:int32, aligned a -> aligned (-32 a).\nProof. unfold aligned, aligned_bool. intros a H.\n  apply Zeq_is_eq_bool in H; apply Zeq_is_eq_bool.\n  unfold unsigned in * |- *.\n  destruct a as [a' Ha]. simpl in * |- *. \n  rewrite <- Zmod_mod_modulus_chunkSize.\n  apply Z_mod_zero_opp_full. trivial.\nQed.\n\nLemma aligned_sub :\n  forall a b:int32, aligned a -> aligned b -> aligned (a -32 b).\nProof. intros a b H1 H2. unfold w32sub. rewrite sub_add_opp.\n  apply aligned_plus. trivial. apply aligned_neg. trivial.\nQed.\n\nLemma aligned_chunkSize : aligned (repr chunkSize).\nProof. unfold aligned, aligned_bool.\n  apply Zeq_is_eq_bool. simpl.\n  rewrite <- Zmod_mod_modulus_chunkSize.\n  apply Z_mod_same_full.\nQed.\n\nLemma aligned_0 : aligned int32_zero.\nProof. unfold aligned, aligned_bool.\n  apply Zeq_is_eq_bool. simpl.\n  rewrite <- Zmod_mod_modulus_chunkSize.\n  apply Zmod_0_l.\nQed.\n\nLtac aligned_tac := \n  match goal with\n    | [ |- aligned (?a +32 ?b)] => \n      apply aligned_plus; (assumption || aligned_tac)\n    | [ |- aligned (?a -32 ?b)] => \n      apply aligned_sub; (assumption || aligned_tac)\n    | [ |- aligned (-32 ?b)] => \n      apply aligned_neg; (assumption || aligned_tac)\n    | [ |- aligned (repr chunkSize)] => apply aligned_chunkSize\n    | [ |- aligned int32_zero] => apply aligned_0\n    | _ => idtac\n  end.\n\nLemma aligned_zdivide :\n  forall z:Z, aligned (repr z) ->  Znumtheory.Zdivide chunkSize z.\nProof. unfold aligned, aligned_bool. intros a H; apply Zeq_is_eq_bool in H.\n  apply Znumtheory.Zmod_divide. generalize chunkSize_gt_0. lia. \n  simpl in H. rewrite <- Zmod_mod_modulus_chunkSize in H. trivial.\nQed.\n\nLemma signed_safemask_eq :\n  signed (safeMask) =  - 32.\nProof. compute. trivial. Qed.\n\nLemma and_safeMask_aligned : forall (v wd: int32),\n  signed wd = signed safeMask -> aligned (Word.and v wd).\nProof. intros.\n  assert (signed wd < 0).\n    rewrite H. rewrite signed_safemask_eq. omega.\n  assert (signed wd = unsigned wd - w32modulus).\n    unfold signed in *.\n    destruct_head. generalize (unsigned_range wd). omega.\n      trivial.\n  assert (unsigned wd = signed wd + w32modulus) by omega.\n  assert (unsigned wd = 4294967264).\n    rewrite H2. rewrite H. rewrite signed_safemask_eq. compute. trivial.\n  assert (low_bits_zero 31 (unsigned wd) (Z_of_nat 5)). \n    apply multiple_low_bits_zero. unfold wordsize. omega.\n    rewrite H3. compute. trivial.\n  unfold aligned, aligned_bool.\n  apply Zeq_is_eq_bool.\n  apply low_bits_zero_multiple with (wordsize_minus_one:=31%nat).  \n    unfold logChunkSize. compute. omega.\n    apply and_low_bits_zero.\n      apply inj_le. unfold logChunkSize. compute. omega.\n      assumption.\nQed.\n\n(** ** Proving the correctness of [checkAligned] *)\nLemma checkAligned_aux_unfold (startAddrs:Int32Set.t)(next:Z)(len:nat) :\n    checkAligned_aux (startAddrs, next, len) = \n    match len with\n      | 0%nat => true\n      | _ => \n        (Int32Set.mem (repr next) startAddrs &&\n         checkAligned_aux ((startAddrs, (next + chunkSize)), \n                          (len - Zabs_nat chunkSize)%nat))\n    end.\nProof. \n  rewrite checkAligned_aux_equation.\n  destruct len; trivial. \nQed.\n\nLemma checkAligned_aux_corr : forall len addr startAddrs x,\n  checkAligned_aux (startAddrs, addr, len) = true\n    -> Zmod addr chunkSize = 0\n    -> addr <= x < addr + Z_of_nat len\n    -> Zmod x chunkSize = 0\n    -> Int32Set.In (repr x) startAddrs.\nProof. induction len using lt_wf_ind. \n  destruct len. \n  Case \"len = 0\". crush.\n  Case \"len > 0\". intros.\n    rewrite checkAligned_aux_unfold in H0.\n    bool_elim_tac.\n    destruct H2.\n    apply Zle_lt_or_eq in H2.\n    destruct H2.\n    SCase \"addr < x\". \n      generalize (chunkSize_gt_0); intro.\n      assert (x >= addr + chunkSize).\n        use_lemma (Z_div_exact_2 addr) by eassumption.\n        use_lemma (Z_div_exact_2 x) by eassumption.\n        assert (H10: chunkSize * (addr / chunkSize) < chunkSize * (x / chunkSize))\n          by omega.\n        rewrite (Zmult_comm chunkSize (addr/chunkSize)) in H10.\n        rewrite (Zmult_comm chunkSize (x/chunkSize)) in H10.\n        use_lemma (Zmult_lt_reg_r (addr/chunkSize) (x/chunkSize) chunkSize) \n          by omega.\n        assert (x/chunkSize >= addr/chunkSize + 1) by omega.\n        rewrite H7. rewrite H8.  \n        eapply Zge_trans.\n          eapply Zmult_ge_compat_l. eassumption. omega.\n          ring_simplify. omega.\n     assert (H20:Z_of_nat (S len) >= chunkSize) by omega.\n     rewrite <- (Zabs_eq chunkSize) in H20 by omega.\n     rewrite <- inj_Zabs_nat in H20.\n     apply inj_ge_rev in H20.\n     assert (x < (addr + chunkSize) + Z_of_nat (S len - Zabs_nat chunkSize)%nat).\n       rewrite inj_minus1 by assumption.\n       rewrite inj_Zabs_nat.\n       rewrite (Zabs_eq chunkSize) by omega.\n       ring_simplify. trivial.\n     eapply H; try eassumption.\n       apply lt_minus. omega. apply inj_lt_rev. simpl. omega.\n       rewrite Zplus_mod. rewrite H1. \n         rewrite Z_mod_same_full. simpl. apply Zmod_0_l.\n       omega.\n    SCase \"addr = x\". subst x; apply Int32Set.mem_spec; assumption.\nQed.\n\nLemma checkAligned_corr : forall len startAddrs x,\n  checkAligned startAddrs len = true\n    -> 0 <= x < Z_of_nat len\n    -> Zmod x chunkSize = 0\n    -> Int32Set.In (repr x) startAddrs.\nProof. unfold checkAligned. intros.\n  eapply checkAligned_aux_corr; try eassumption.\n  apply Zmod_0_l.\nQed.\n\n(** * The main verifier-correctness proof *)\n\n(** Basic ideas of developing correctness proof of the fast verifier:\n     - Define a pseudo instruction to be either a non-control-flow instruction, \n         a direct-jump instruction, or a nacljmp (which corresponds\n         to two real instructions);\n     - Formalize the invariant that should be satisfied between pseudo\n         instructions: safeState, which says that pc is one of the\n         start addresses of pseudo instructions.\n     - Introduce a notion of safeInK (k, s, code), which means s will\n         reach a safe state within k steps and it won't fail before reaching\n         a safe state.\n     - Show that any safe state also satifies safeInK(k,s,code) for some k>0.\n         This proof is by case analysis over the current pseudo instruction. \n         If it is a non-control-flow or direct-jump instruction, then \n         safeInK(1,s,code). If it's a nacljmp, then safeInK(2,s,code). \n     - Show the initial state is a safe state. Then using the previous\n         step, we know the initial state will reach a safe state s1;\n         similarly, s1 will reach a safe state s2; ... By def of safeInK,\n         none of these states (and the intermediate states) will fail.\n\n     Note the above framework is general in that (i) it accommodates other\n     pseudo instructions, not just nacljmp; (ii) it acccommodates trampolines;\n     we just need an axiom assuming after jumping to a trampoline, the machine\n     will come back to a safe state in a finite number of steps (that is,\n     safeInK for some k).\n*)\nSection VERIFIER_CORR.\n\n  Variable non_cflow_dfa : Recognizer.DFA.\n  Variable dir_cflow_dfa : Recognizer.DFA.\n  Variable nacljmp_dfa : Recognizer.DFA.\n  Variable initial_state : ParseState_t.\n\n  (* The trampoline region is a blessed region in the code segment. \n     It's inserted there by the loader and never checked by the validator.\n     The idea is that if we jump into the trampoline region and the PC is aligned,\n     then that is a safe state.\n     This variable marks the limit of the trampoline region *)\n  Variable trampoline_limit : int32.\n\n  Definition checkProgram :=\n    FastVerifier.checkProgram non_cflow_dfa dir_cflow_dfa nacljmp_dfa\n      initial_state.\n  Definition process_buffer_aux :=\n    FastVerifier.process_buffer_aux non_cflow_dfa dir_cflow_dfa nacljmp_dfa\n      initial_state.\n  Definition process_buffer :=\n    FastVerifier.process_buffer non_cflow_dfa dir_cflow_dfa nacljmp_dfa\n      initial_state.\n\n  (* Checks whether the memory of s starting at addr_offset is equal\n     to buffer *)\n  Definition eqMemBuffer (buffer: list int8) (s: rtl_state) (addr_offset: int32) :=\n    Z_of_nat (length buffer) <= w32modulus /\\\n    (forall i, (i < length buffer)%nat\n      -> nth i buffer Word.zero = (AddrMap.get (addr_offset +32_n i) (rtl_memory s))).\n\n  (* note: needed adjustments if consider the trampoline area *)\n  (* note: the range of addresses in the code segment is [CStart s, CStart s + Climit s],\n     the length of the code segment is CLimit s + 1 *)\n  Definition codeLoaded (buffer: list int8) (s:rtl_state) := \n    eqMemBuffer buffer s (CStart s) /\\ \n    Z_of_nat (length buffer) = unsigned (CLimit s) + 1.\n\n  (* todo: deal with trampolines\n  (* Checks if the buffer agrees with the code regon in the state*)\n  Definition eqCode_after_trampoline (buffer: list int8) (r: rtl_state) :=\n    eqMemBuffer buffer r ((Word.add (CStart r) trampoline_limit)) /\\\n      ltu trampoline_limit (CLimit r) = true /\\\n      trampoline_limit +32_n (length buffer) = CLimit r.\n  *)\n\n  (** Check (1) segments do not wrap around the 32-bit address space;\n      (2) code segment is disjoint from stack and data segments; *)\n  Definition checkSegments (s: rtl_state) := \n    (checkNoOverflow (CStart s) (CLimit s) &&\n      checkNoOverflow (DStart s) (DLimit s) &&\n      checkNoOverflow (SStart s) (SLimit s) &&\n      checkNoOverflow (EStart s) (ELimit s) &&\n      checkNoOverflow (GStart s) (GLimit s) &&\n      disjointRegions (CStart s) (CLimit s) (DStart s) (DLimit s) &&\n      disjointRegions (CStart s) (CLimit s) (SStart s) (SLimit s) &&\n      disjointRegions (CStart s) (CLimit s) (EStart s) (ELimit s) &&\n      disjointRegions (CStart s) (CLimit s) (GStart s) (GLimit s))%bool.\n\n  (** Invariants include the segment register starts and limits, and the code *)\n  Definition Inv := \n     (fmap segment_register int32 * fmap segment_register int32 * list int8)%type.\n\n  (** An appropriate state is one that segment registers are the same as the initial\n     state and code is the same as the initial state *)\n  Definition appropState (s:rtl_state) (inv:Inv) :=\n    let (sregs, code) := inv in \n    let (sregs_starts, sregs_limits) := sregs in\n      seg_regs_starts (get_core_state s) = sregs_starts /\\\n      seg_regs_limits (get_core_state s) = sregs_limits /\\\n      codeLoaded code s /\\\n      checkSegments s = true.\n\n  (** The invariant that should be satisfied between pseudo instructions*)\n  Definition safeState (s:rtl_state) (inv:Inv) :=\n    let (sregs, code) := inv in \n    let cpRes := checkProgram code in\n      appropState s inv /\\\n      fst cpRes = true /\\\n      (Int32Set.In (PC s) (snd cpRes) \\/ ~ inBoundCodeAddr (PC s) s).\n\n  (** State s does not step to a failed state *)\n  Definition nextStepNoFail (s: rtl_state) := \n    forall s', step s <> (Fail_ans, s').\n\n  (** The initial state can reach a safe state within k steps; the\n     definition does not assume the step relation is\n     deterministic; so the initial state may reach a safe state\n     in different number of steps along different paths *)\n  Fixpoint safeInK (k:nat) (s:rtl_state) (inv:Inv) := \n    match k with \n      | O => False\n      | S k => appropState s inv /\\ nextStepNoFail s /\\\n        forall s', s ==> s' -> safeState s' inv \\/ safeInK k s' inv\n    end.\n\n  Definition safeInSomeK (s:rtl_state) (inv:Inv) := \n    exists k, safeInK k s inv.\n\n  (** An equivalence relation between states that says the code\n     region is immutable *)\n  Definition eqCodeRegion (s s':rtl_state) :=\n    CStart s = CStart s' /\\ CLimit s = CLimit s' /\\\n    noOverflow ((CStart s)::(CLimit s)::nil) /\\\n    agree_over_addr_region (segAddrs CS s) s s'.\n\n  (** Check region [start1, start1+limit1] is a subset of\n     [start2, start2+limit2]; For simplicity, neither region can wrap\n     around the 32-bit address space. *)\n  Definition subsetRegion (start1 limit1 start2 limit2:int32) : bool :=\n    andb (int32_lequ_bool start2 start1)\n      (int32_lequ_bool (start1 +32 limit1) (start2 +32 limit2)).\n\n  Definition goodDefaultPC (default_pc:int32) \n    (startAddrs: Int32Set.t) (codeSize:nat) :=\n    Int32Set.In default_pc startAddrs \\/ default_pc = int32_of_nat codeSize.\n\n  Definition goodJmpTarget (target:int32) (startAddrs: Int32Set.t) :=\n    Int32Set.mem target startAddrs  || aligned_bool target.\n\n  Definition goodJmp (ins:instr) (default_pc:int32) (startAddrs: Int32Set.t) := \n    match ins with\n      | JMP true false (Imm_op disp) None => \n        goodJmpTarget (default_pc +32 disp) startAddrs\n      | Jcc ct disp => goodJmpTarget (default_pc +32 disp) startAddrs\n      | CALL true false (Imm_op disp) None => \n        goodJmpTarget (default_pc +32 disp) startAddrs\n      | _ => false\n    end.\n\n  (** ** Fast verifier correctness proof *)\n  \n  (** *** Properties of codeLoaded *)\n  Lemma codeLoaded_length : forall code s,\n    codeLoaded code s -> Z_of_nat (length code) <= w32modulus.\n  Proof. unfold codeLoaded. intros.\n    destruct H. int32_prover.\n  Qed.\n\n  Lemma codeLoaded_lookup : forall code s i,\n    codeLoaded code s -> (i < length code)%nat\n      -> nth i code Word.zero = AddrMap.get (CStart s +32_n i) (rtl_memory s).\n  Proof. unfold codeLoaded, eqMemBuffer. intros.\n    destruct H as [[H10 H11] H12].    \n    apply H11. trivial.\n  Qed.\n\n\n  (** *** Properties of dfa_recognize *)\n\n  Lemma dfa_loop_inv : forall dfa ts s count count1 ts1,\n      dfa_loop dfa s count ts = Some (count1, ts1) ->\n        ts1 = List.skipn (count1-count) ts /\\ (count1 >= count)%nat /\\\n        (length ts = count1 - count + length ts1)%nat.\n  Proof. induction ts; intros; simpl in H.\n        Case \"ts=nil\".\n          destruct_head in H; [crush' minus_diag fail | discriminate].\n        Case \"a::ts\".\n          destruct_head in H.\n            crush' minus_diag fail.\n            apply IHts in H.\n            assert (count1 - S count = count1 - count - 1)%nat by intuition.\n            rewrite Coqlib.skipn_gt_0; crush.\n  Qed.\n\n  Lemma dfa_recognize_inv : forall dfa ts len ts',\n      dfa_recognize dfa ts = Some (len, ts')\n        -> (ts' = List.skipn len ts /\\ length ts = len + length ts')%nat.\n  Proof. unfold dfa_recognize.\n        intros. apply dfa_loop_inv in H.\n        rewrite <- minus_n_O in H. crush.\n  Qed.\n\n  (** *** Properties of safeInK and safeInSomeK *)\n  Lemma safeInSomeK_no_fail : forall s inv,\n    safeInSomeK s inv -> nextStepNoFail s.\n  Proof. unfold safeInSomeK. intros. destruct H as [k H]. destruct k; crush. Qed.\n\n  Lemma safeInK_step_dichotomy : forall k s inv s',\n    safeInK k s inv -> s ==> s' -> safeState s' inv \\/ safeInSomeK s' inv.\n  Proof. destruct k. crush.\n    intros. simpl in H.\n    assert (safeState s' inv \\/ safeInK k s' inv) by crush.\n    destruct H1. crush.\n      right. unfold safeInSomeK. exists k; assumption.\n  Qed.\n\n  Lemma safeInK_intro_one : forall s inv,\n    appropState s inv -> nextStepNoFail s \n      -> (forall s', s ==> s' -> safeState s' inv)\n      -> safeInK 1%nat s inv.\n  Proof. crush. Qed.\n\n  (** *** Properties of subsetRegion *)\n  Ltac subsetRegion_intro_tac :=\n    unfold subsetRegion; bool_intro_tac.\n\n  Lemma subsetRegion_sound : forall start1 limit1 start2 limit2,\n    noOverflow (start1::limit1::nil) -> noOverflow (start2::limit2::nil)\n      -> subsetRegion start1 limit1 start2 limit2 = true\n      -> Ensembles.Included _ (addrRegion start1 limit1)\n           (addrRegion start2 limit2).\n  Proof. unfold subsetRegion, Ensembles.Included. intros.\n   unfold Ensembles.In, addrRegion in *.\n   bool_elim_tac.\n   destruct H2 as [i [H6 H8]].\n   exists (start1 -32 start2 +32 i).\n   split. unfold w32add. rewrite <- add_assoc. \n     rewrite <- add_sub_assoc. rewrite sub_add_l.\n     rewrite sub_idem. rewrite zero_add. assumption.\n   int32_prover.\n  Qed.\n\n  (** *** Properties of checkSegments *)\n  Lemma checkSegments_inv : forall (s s':rtl_state),\n    Same_Seg_Regs_Rel.brel s s'\n      -> checkSegments s = true\n      -> checkSegments s' = true.\n  Proof. unfold Same_Seg_Regs_Rel.brel, checkSegments.  intros.\n    bool_elim_tac. sim.\n    rewrite <- H. rewrite <- H9.\n    bool_intro_tac; crush.\n  Qed.\n\n  Lemma checkSegments_inv2 : forall (A:Type) (c:RTL A) (s s':rtl_state) (v':A),\n    same_seg_regs c\n      -> c s = (Okay_ans v', s')\n      -> checkSegments s = true\n      -> checkSegments s' = true.\n  Proof. unfold same_seg_regs.  intros.\n    eapply checkSegments_inv; try eassumption. eauto.\n  Qed.\n\n  Ltac checkSegments_backward :=\n    match goal with\n      | [H: ?c1 ?s = (Okay_ans _, ?s') |- checkSegments ?s' = true] => \n        eapply checkSegments_inv2 with (c:=c1); \n          [same_seg_regs_tac | eassumption | idtac]\n    end.\n\n  Lemma checkSegments_disj_code_data : forall s,\n    checkSegments s = true\n      -> Ensembles.Disjoint _ (segAddrs CS s) (segAddrs DS s).\n  Proof. intros. unfold checkSegments in H. repeat bool_elim_tac.\n    apply disjointRegions_sound; try assumption.\n  Qed.\n\n  Lemma checkSegments_disj_code_stack : forall s,\n    checkSegments s = true\n      -> Ensembles.Disjoint _ (segAddrs CS s) (segAddrs SS s).\n  Proof. intros. unfold checkSegments in H. repeat bool_elim_tac.\n    apply disjointRegions_sound; try assumption.\n  Qed.\n\n  Lemma checkSegments_disj_code_eseg : forall s,\n    checkSegments s = true\n      -> Ensembles.Disjoint _ (segAddrs CS s) (segAddrs ES s).\n  Proof. intros. unfold checkSegments in H. bool_elim_tac.\n    apply disjointRegions_sound; try assumption.\n  Qed.\n\n  Lemma checkSegments_disj_code_gseg : forall s,\n    checkSegments s = true\n      -> Ensembles.Disjoint _ (segAddrs CS s) (segAddrs GS s).\n  Proof. intros. unfold checkSegments in H. bool_elim_tac.\n    apply disjointRegions_sound; try assumption.\n  Qed.\n\n  (** ** Properties about eqCodeRegion *)\n  Lemma eqCodeRegion_intro : forall s s',\n      Same_Seg_Regs_Rel.brel s s'\n        -> checkSegments s = true\n        -> (agree_outside_addr_region (segAddrs DS s) s s' \\/\n            agree_outside_addr_region (segAddrs SS s) s s' \\/\n            agree_outside_addr_region (segAddrs GS s) s s' \\/\n            agree_outside_addr_region (segAddrs ES s) s s')\n        -> eqCodeRegion s s'. \n  Proof. unfold eqCodeRegion. intros. dupHyp H0.\n    unfold checkSegments in H0.\n    bool_elim_tac.\n    unfold Same_Seg_Regs_Rel.brel in H.\n    split. crush.\n    split. crush.\n    split. apply checkNoOverflow_equiv_noOverflow. trivial.\n    destruct H1.\n      Case \"agree_outside_seg DS c\".\n        eapply agree_over_outside. \n          apply checkSegments_disj_code_data; assumption.\n          trivial.\n      destruct H1.\n      Case \"agree_outside_seg SS c\".\n        eapply agree_over_outside. \n          apply checkSegments_disj_code_stack; assumption.\n          trivial.\n      destruct H1.\n      Case \"agree_outside_seg GS c\".\n        eapply agree_over_outside. \n          apply checkSegments_disj_code_gseg; assumption.\n          trivial.\n      Case \"agree_outside_seg ES c\".\n        eapply agree_over_outside. \n          apply checkSegments_disj_code_eseg; assumption.\n          trivial.\n  Qed.\n    \n  Lemma eqCodeRegion_intro2 : \n    forall (A:Type) (c:RTL A) (s s':rtl_state) (v':A),\n      checkSegments s = true -> c s = (Okay_ans v', s')\n        -> same_seg_regs c\n        -> (agree_outside_seg DS c \\/ agree_outside_seg SS c \\/\n            agree_outside_seg GS c \\/ agree_outside_seg ES c)\n        -> eqCodeRegion s s'. \n  Proof. intros.\n    apply eqCodeRegion_intro.\n    eauto using H1. assumption.\n    destruct H2. left. eapply H2. eassumption.\n    destruct H2. right. left. eapply H2. eassumption.\n    destruct H2. right. right. left. eapply H2. eassumption.\n      right. right. right. eapply H2. eassumption.\n  Qed.\n\n  Lemma eqCodeRegion_refl : forall s,\n    checkSegments s = true -> eqCodeRegion s s.\n  Proof. intros. unfold eqCodeRegion. repeat split; try congruence.\n    unfold checkSegments in H. bool_elim_tac.\n    apply checkNoOverflow_equiv_noOverflow. assumption.\n  Qed.\n\n  Lemma eqCodeRegion_trans : forall s1 s2 s3,\n    eqCodeRegion s1 s2 -> eqCodeRegion s2 s3\n      -> eqCodeRegion s1 s3.\n  Proof. unfold eqCodeRegion; intros. \n    crush.\n    assert (segAddrs CS s1 = segAddrs CS s2) as H10.\n      unfold segAddrs. congruence.\n    rewrite H10 in *.\n    eapply agree_over_addr_region_trans; eassumption.\n  Qed.\n\n  (** *** Properties about parse_instr *)\n  Opaque Decode.parse_byte.\n\n  Lemma parse_instr_aux_same_state : forall n pc len ps,\n    same_rtl_state (parse_instr_aux n pc len ps).\n  Proof. unfold same_rtl_state.\n    induction n. intros. discriminate.\n    intros. simpl in H.\n    remember_destruct_head in H as pr.\n    destruct l. eauto. crush.\n  Qed.\n\n  Lemma parse_instr_same_state : forall pc, same_rtl_state (parse_instr pc).\n  Proof. unfold same_rtl_state, parse_instr, parse_instr'. intros.\n    rtl_okay_elim. destruct (abs_ini_decoder_state); try discriminate.\n    eapply parse_instr_aux_same_state. eassumption.\n  Qed.\n\n  Lemma parse_instr_aux_len : forall n pc len ps s pi len' s',\n    parse_instr_aux n pc len ps s = (Okay_ans (pi, len'), s')\n      -> Zpos len <= Zpos len' < Zpos len + Z_of_nat n.\n  Proof. induction n. discriminate.\n    intros. simpl in H.\n    remember_destruct_head  in H as pr.\n    destruct l. \n    Case \"l=nil\". \n      use_lemma IHn by eassumption. \n      rewrite Zpos_plus_distr in H0. \n      rewrite inj_S. omega.\n    Case \"l>>nil\". inversion_clear H. \n      rewrite inj_S. omega.\n  Qed.  \n\n  Lemma parse_instr_len : forall pc s pi len s',\n    parse_instr pc s = (Okay_ans (pi, len), s') -> 1 <= Zpos len < 16.\n  Proof. unfold parse_instr, parse_instr'. intros.\n    rtl_okay_elim. destruct (abs_ini_decoder_state); try discriminate.\n    apply parse_instr_aux_len in H. simpl in H. omega.\n  Qed.\n\n  Lemma parse_instr_aux_same_seg_regs : forall n loc len ps,\n     same_seg_regs (parse_instr_aux n loc len ps).\n  Proof. unfold parse_instr_aux.\n    induction n; intros. same_seg_regs_tac.\n      fold parse_instr in *. same_seg_regs_tac.\n  Qed.\n\n  Hint Immediate parse_instr_aux_same_seg_regs : same_seg_regs_db.\n\n(*\n  Lemma parse_instr_aux_no_fail : forall n loc len ps,\n     no_fail (parse_instr_aux n loc len ps).\n  Proof. unfold parse_instr_aux.\n    induction n; intros. no_fail_tac.\n      fold parse_instr in *. no_fail_tac.\n  Qed.\n\n  Hint Immediate parse_instr_aux_no_fail : no_fail_db.\n*)\n\n  Lemma parse_instr_aux_code_inv : forall s1 s1' s2 n pc len len' pi ps,\n    eqCodeRegion s1 s2\n      -> parse_instr_aux n pc len ps s1 = (Okay_ans (pi, len'), s1')\n      -> Ensembles.Included _ (addrRegion pc (repr (Zpos len' - Zpos len)))\n           (segAddrs CS s1)\n      -> noOverflow (pc :: repr (Zpos len' - Zpos len) ::nil)\n      -> Zpos len' - Zpos len < w32modulus\n      -> parse_instr_aux n pc len ps s2 = (Okay_ans (pi, len'), s2).\n  Proof. induction n; intros.\n    Case \"n=0\". discriminate.\n    Case \"S n\". simpl in H0. simpl.\n      assert (AddrMap.get pc (rtl_memory s1)\n                = AddrMap.get pc (rtl_memory s2)) as H10.\n        unfold eqCodeRegion in H. sim.\n        apply H6. apply H1. apply addrRegion_start_in.\n      rewrite <- H10.\n      remember_destruct_head as pr.\n      destruct l. \n      SCase \"l=nil\".\n        use_lemma parse_instr_aux_len by eassumption.\n        assert (noOverflow (add pc (repr 1)::repr (Zpos len' - (Zpos len + 1))::nil))\n          by int32_prover.\n        eapply IHn; try eassumption.\n        apply included_trans with (r2:= addrRegion pc (repr (Zpos len' - Zpos len))).\n          apply subsetRegion_sound; try assumption.\n            subsetRegion_intro_tac; int32_prover.\n            assumption.\n          rewrite Zpos_plus_distr; lia.\n      SCase \"l<>nil\". crush.\n  Qed.\n\n  (* this can be proved as a corollary of the above lemma, given that\n     n -1 < Zpos len' - Zpos len\n  Lemma parse_instr_aux_code_inv_2 : forall s1 s1' s2 n pc len res ps,\n    eqCodeRegion s1 s2\n      -> Ensembles.Included _ (addrRegion pc (int32_of_nat (n-1)))\n           (segAddrs CS s1)\n      -> noOverflow (pc::int32_of_nat (n-1)::nil)\n      -> Z_of_nat n <= w32modulus\n      -> parse_instr n pc len ps s1 = (Okay_ans res, s1')\n      -> parse_instr n pc len ps s2 = (Okay_ans res, s2).\n  *)\n\n  Lemma parse_instr_code_inv : forall s1 s1' s2 pc len' pi,\n    eqCodeRegion s1 s2\n      -> parse_instr pc s1 = (Okay_ans (pi, len'), s1')\n      -> Ensembles.Included _ \n           (addrRegion (CStart s1 +32 pc) (repr (Zpos len' - 1)))\n           (segAddrs CS s1)\n      -> noOverflow ((CStart s1 +32 pc) :: repr (Zpos len' - 1) ::nil)\n      -> Zpos len' - 1 < w32modulus\n      -> parse_instr pc s2 = (Okay_ans (pi, len'), s2).\n  Proof. unfold parse_instr, parse_instr'. intros.\n    dupHyp H. unfold eqCodeRegion in H. sim.\n    rtl_okay_elim. rtl_okay_intro.\n    compute [get_location look]. rewrite  <- H. \n    destruct (abs_ini_decoder_state); try discriminate.\n    eapply parse_instr_aux_code_inv; eassumption.\n  Qed.\n\n  Transparent Decode.parse_byte.\n\n  (** *** Misc. lemmas *)\n\n  Lemma Int32Set_in_dichotomy : forall x y A B,\n    Int32Set.In x (Int32Set.diff A B)\n      -> (x=y \\/ Int32Set.In x (Int32Set.diff A (Int32Set.add y B))).\n  Proof. intros. destruct (eq_dec x y). crush.\n      rewrite Int32Set.diff_spec in *. rewrite Int32Set.add_spec.\n      right. unfold Logic.not.\n      int32_to_Z_tac. crush.\n  Qed.\n\n  (** *** Properties of process_buffer *)\n\n  (* process buffer prover *)\n  (* Local Ltac pbprover := *)\n  (*   simtuition ltac:(auto with arith zarith); autorewrite with pbDB in *;  *)\n  (*     rewriter; simtuition ltac:(auto with arith zarith). *)\n  Local Ltac pbprover := autorewrite with pbDB in *; crush.\n  \n  Hint Rewrite Int32Set.diff_spec : pbDB.\n  Hint Rewrite Int32SetFacts.empty_iff : pbDB.\n\n  Lemma process_buffer_aux_nil: forall start n currStartAddrs currJmpTargets,\n    process_buffer_aux start n nil (currStartAddrs, currJmpTargets) = \n    Some (currStartAddrs, currJmpTargets).\n  Proof. destruct n; auto. Qed.\n  Hint Rewrite process_buffer_aux_nil : pbDB.\n\n(*\n  Lemma process_buffer_aux_nil_contra :\n    forall start n currStartAddrs currJmpTargets allStartAddrs allJmpTargets pc\n      (p:Prop),\n    process_buffer_aux start n nil (currStartAddrs, currJmpTargets) =\n      Some(allStartAddrs, allJmpTargets)\n      -> Int32Set.In pc (Int32Set.diff allStartAddrs currStartAddrs)\n      -> p.\n  Proof. intros. pbprover. Qed.\n*)\n\n  (** a special tactic for performing case analysis over process_buffer_aux *)\n  Ltac process_buffer_aux_Sn_tac := \n    match goal with\n      | [H: process_buffer_aux ?start (S ?n) ?tokens (?cSA, ?cJT)\n          = Some (?aSA, ?aJT) |- _] =>\n        simpl in H;\n        repeat match goal with\n           | [ H: match ?X with Some _ => _ | None => _ end = _ |- _] =>\n                 match X with\n                   | dfa_recognize non_cflow_dfa ?T => \n                     let dfa := fresh \"d1\" in let len := fresh \"len1\" in \n                       let remaining := fresh \"remaining1\" in\n                         remember_rev X as dfa; destruct dfa as [(len, remaining)|]\n                   | dfa_recognize dir_cflow_dfa ?T => \n                     let dfa := fresh \"d2\" in let len := fresh \"len2\" in \n                       let remaining := fresh \"remaining2\" in\n                         remember_rev X as dfa; destruct dfa as [(len, remaining)|]\n                   | dfa_recognize nacljmp_dfa ?T => \n                     let dfa := fresh \"d3\" in let len := fresh \"len3\" in \n                       let remaining := fresh \"remaining3\" in\n                         remember_rev X as dfa; destruct dfa as [(len, remaining)|]\n                 end\n               end; try (discriminate H)\n    end.\n\n  Ltac process_buffer_aux_tac := \n    match goal with\n      | [H: process_buffer_aux ?start ?n ?tokens (?cSA, ?cJT)\n          = Some (?aSA, ?aJT) |- _] =>\n      let t := fresh \"t1\" in let tokens' := fresh \"tokens1\" in\n        destruct tokens as [| t tokens'];\n          [idtac | process_buffer_aux_Sn_tac]\n    end.\n\n\n  (* Some arithmetic facts used many times in the proofs about process_buffer *)\n  Lemma process_buffer_arith_facts : \n    forall start len (tokens remaining:list token_id),\n    noOverflow (start :: int32_of_nat (length tokens -1)%nat :: nil)\n      -> Z_of_nat (length tokens) <= w32modulus\n      -> (length tokens >=1)%nat\n      -> (length remaining >=1)%nat\n      -> (length tokens = len + length remaining)%nat\n      -> noOverflow (start :: int32_of_nat len :: nil) /\\\n         noOverflow ((start +32_n len)\n           :: int32_of_nat (length remaining - 1) :: nil) /\\\n         Z_of_nat (length remaining) <= w32modulus.\n  Proof. intros. int32_simplify. lia. Qed.\n\n  Lemma process_buffer_aux_addrRange :\n   forall n start tokens currStartAddrs currJmpTargets allStartAddrs allJmpTargets pc,\n    process_buffer_aux start n tokens (currStartAddrs, currJmpTargets) =\n      Some(allStartAddrs, allJmpTargets)\n      -> noOverflow (start :: int32_of_nat (length tokens - 1) :: nil)\n      -> Z_of_nat (length tokens) <= w32modulus\n      -> Int32Set.In pc (Int32Set.diff allStartAddrs currStartAddrs)\n      -> unsigned start <= unsigned pc < unsigned start + Z_of_nat (length tokens).\n  Proof. induction n. intros.\n    Case \"n=0\". intros. destruct tokens; pbprover.\n    Case \"S n\". intros.\n      destruct tokens as [| t tokens']. pbprover.\n      SCase \"tokens<>nil\".\n        assert (length (t::tokens') >= 1)%nat by (simpl; omega).\n        destruct (@Int32Set_in_dichotomy pc start _ _ H2). \n        SSCase \"pc=start\".  rewrite H4. omega.\n        SSCase \"pc in (allStartAddrs - ({start} \\/ currStartAddrs)\".\n         process_buffer_aux_Sn_tac.\n         SSSCase \"nacljmp_dfa matches\". clear Hd1 Hd2.\n           assert (length remaining3 > 0)%nat by (destruct remaining3; pbprover).\n           use_lemma dfa_recognize_inv by eassumption. break_hyp.\n           use_lemma process_buffer_arith_facts by eassumption. break_hyp.\n           apply IHn with (pc:=pc) in H; try (assumption || omega). clear IHn. \n           int32_simplify. lia.\n        SSSCase \"non_cflow_dfa matches\". clear Hd2 Hd3.\n           assert (length remaining1 > 0)%nat by (destruct remaining1; pbprover).\n           use_lemma dfa_recognize_inv by eassumption. break_hyp.\n           use_lemma process_buffer_arith_facts by eassumption. break_hyp.\n           apply IHn with (pc:=pc) in H; try (assumption || omega). clear IHn.\n           int32_simplify. lia.\n        SSSCase \"dir_cflow_dfa matches\". clear Hd1 Hd3.\n           destruct_head in H; try discriminate.\n           assert (length remaining2 > 0)%nat by (destruct remaining2; pbprover).\n           use_lemma dfa_recognize_inv by eassumption. break_hyp.\n           use_lemma process_buffer_arith_facts by eassumption. break_hyp.\n           apply IHn with (pc:=pc) in H; try (assumption || omega). clear IHn.\n           int32_simplify. lia.\n  Qed.\n\n  Lemma process_buffer_addrRange : forall buffer startAddrs jmpTargets pc,\n    process_buffer buffer = Some (startAddrs, jmpTargets)\n      -> Z_of_nat (length buffer) <= w32modulus\n      -> Int32Set.In pc startAddrs\n      -> 0 <= unsigned pc < Z_of_nat (length buffer).\n  Proof. intros. unfold process_buffer, FastVerifier.process_buffer in H.\n    assert (length (List.map byte2token buffer) = length buffer) as H10\n      by (apply list_length_map).\n    assert (noOverflow (repr 0 ::\n      int32_of_nat (Datatypes.length (List.map byte2token buffer) - 1) :: nil)).\n      rewrite H10. \n      destruct buffer as [| b buffer']. simpl. \n        int32_simplify. simpl. rewrite int32_modulus_constant. omega.\n        assert (length (b::buffer') >= 1)%nat by (simpl; omega).\n        int32_prover.\n    apply process_buffer_aux_addrRange with (pc:=pc) in H;\n      [idtac | assumption | (rewrite list_length_map; trivial) | pbprover].\n    rewrite list_length_map in *; int32_prover.\n  Qed.\n\n  Hint Rewrite Zminus_diag:pbDB.\n  \n  Lemma Int32Set_subset_add : forall x s,\n    Int32Set.Subset s (Int32Set.add x s).\n  Proof. unfold Int32Set.Subset.\n    generalize Int32Set.add_spec. crush.\n  Qed.\n\n  Lemma process_buffer_aux_subset : \n    forall n start tokens currStartAddrs currJmpTargets allStartAddrs allJmpTargets,\n      process_buffer_aux start n tokens (currStartAddrs, currJmpTargets) =\n        Some (allStartAddrs, allJmpTargets)\n        -> Int32Set.Subset currStartAddrs allStartAddrs /\\\n           Int32Set.Subset currJmpTargets allJmpTargets.\n  Proof. induction n. intros.\n    Case \"n=0\". intros. destruct tokens; pbprover.\n    Case \"S n\". intros.\n      destruct tokens as [| t tokens']. pbprover.\n      SCase \"tokens<>nil\".\n        assert (length (t::tokens') >= 1)%nat by (simpl; omega).\n        process_buffer_aux_Sn_tac.\n        SSCase \"nacljmp_dfa matches\". clear Hd1 Hd2.\n          use_lemma IHn by eassumption.\n          break_hyp.\n          split.\n            eapply Int32SetFacts.Subset_trans; [idtac | eassumption].\n              apply Int32Set_subset_add.\n            eapply Int32SetFacts.Subset_trans; [idtac | eassumption].\n              apply Int32SetFacts.Subset_refl.\n        SSCase \"non_cflow_dfa matches\". clear Hd2 Hd3.\n          use_lemma IHn by eassumption.\n          break_hyp.\n          split.\n            eapply Int32SetFacts.Subset_trans; [idtac | eassumption].\n              apply Int32Set_subset_add.\n            eapply Int32SetFacts.Subset_trans; [idtac | eassumption].\n              apply Int32SetFacts.Subset_refl.\n        SSCase \"dir_cflow_dfa matches\". clear Hd1 Hd3.\n          destruct_head in H; try discriminate.\n          use_lemma IHn by eassumption.\n          break_hyp.\n          split.\n            eapply Int32SetFacts.Subset_trans; [idtac | eassumption].\n              apply Int32Set_subset_add.\n            eapply Int32SetFacts.Subset_trans; [idtac | eassumption].\n              apply Int32Set_subset_add.\n  Qed.\n\n  Lemma process_buffer_aux_start_in : \n    forall n start tokens currStartAddrs currJmpTargets allStartAddrs allJmpTargets,\n      process_buffer_aux start n tokens (currStartAddrs, currJmpTargets) =\n        Some(allStartAddrs, allJmpTargets)\n        -> (length (tokens) > 0)%nat\n        -> Int32Set.In start allStartAddrs.\n  Proof. intros. destruct tokens as [| t tokens']. \n    Case \"tokens=nil\". simpl in H0. contradict H0. omega.\n    Case \"tokens<>nil\".\n      assert (length (t::tokens') >= 1)%nat by (simpl; omega).\n      destruct n.\n      SCase \"n=0\". discriminate.\n      SCase \"S n\".\n        process_buffer_aux_Sn_tac.\n        SSCase \"nacljmp_dfa matches\". clear Hd1 Hd2.\n          use_lemma process_buffer_aux_subset by eassumption.\n          unfold Int32Set.Subset in *.\n          apply H2. apply Int32SetFacts.add_1. apply int_eq_refl.\n        SSCase \"non_cflow_dfa matches\". clear Hd2 Hd3.\n          use_lemma process_buffer_aux_subset by eassumption.\n          unfold Int32Set.Subset in *.\n          apply H2. apply Int32SetFacts.add_1. apply int_eq_refl.\n        SSCase \"dir_cflow_dfa matches\". clear Hd1 Hd3.\n          destruct_head in H; try discriminate.\n          use_lemma process_buffer_aux_subset by eassumption.\n          unfold Int32Set.Subset in *.\n          apply H2. apply Int32SetFacts.add_1. apply int_eq_refl.\n  Qed.\n\n  Lemma process_buffer_start_in : forall code startAddrs jmpTargets,\n      process_buffer code =  Some (startAddrs, jmpTargets)\n        -> (length (code) > 0)%nat\n        -> Int32Set.In int32_zero startAddrs.\n  Proof. unfold process_buffer, FastVerifier.process_buffer; intros.\n    eapply process_buffer_aux_start_in. eassumption.\n      rewrite list_length_map. assumption.\n  Qed.\n\n\n  Definition goodDefaultPC_aux (default_pc start:int32) \n    (startAddrs: Int32Set.t) (codeSize:nat) :=\n    Int32Set.In default_pc startAddrs \\/ default_pc = start +32_n codeSize.\n\n  (* Capture the notion that all indirect-jmp targets are in jmpTargets *)\n  Definition includeAllJmpTargets (start:int32) (len:nat) \n    (tokens:list token_id) (jmpTargets:Int32Set.t) := \n    match (parseloop initial_state \n            (List.map token2byte (firstn len tokens))) with\n      | Some ((_, JMP true false (Imm_op disp) None), _) => \n        Int32Set.In (start +32_n len +32 disp) jmpTargets\n      | Some ((_, Jcc ct disp), _) => \n        Int32Set.In (start +32_n len +32 disp) jmpTargets\n      | Some ((_, CALL true false (Imm_op disp) None), _) => \n        Int32Set.In (start +32_n len +32 disp) jmpTargets\n      | _ => True\n    end.\n\n  Lemma extract_disp_include : forall start len tokens disp S,\n    extract_disp initial_state \n      (List.map token2byte (firstn len tokens)) = Some disp\n      -> Int32Set.In (start +32_n len +32 disp) S\n      -> includeAllJmpTargets start len tokens S.\n  Proof. unfold extract_disp, includeAllJmpTargets; intros.\n    destruct_head. destruct p as [[pre ins] _].\n    destruct ins; try trivial.\n      Case \"JMP\".\n        destruct near; try congruence.\n        destruct absolute; try congruence.\n        destruct op1; try congruence.\n        destruct sel; congruence.\n      Case \"Jcc\". congruence.\n      Case \"Call\".\n        destruct near; try congruence.\n        destruct absolute; try congruence.\n        destruct op1; try congruence.\n        destruct sel; congruence.\n      trivial.\n  Qed.  \n\n  Lemma Int32Set_in_subset : forall x s s',\n    Int32Set.In x s -> Int32Set.Subset s s' -> Int32Set.In x s'.\n  Proof. unfold Int32Set.Subset. intros. auto. Qed.\n\n  Lemma process_buffer_aux_inversion :\n   forall n start tokens currStartAddrs currJmpTargets allStartAddrs allJmpTargets,\n    process_buffer_aux start n tokens (currStartAddrs, currJmpTargets) =\n      Some (allStartAddrs, allJmpTargets)\n      -> noOverflow (start :: int32_of_nat (length tokens - 1) :: nil)\n      -> Z_of_nat (length tokens) <= w32modulus\n      -> forall pc:int32, Int32Set.In pc (Int32Set.diff allStartAddrs currStartAddrs)\n           -> exists tokens', exists len, exists remaining,\n                tokens' = (List.skipn (Zabs_nat (unsigned pc - unsigned start)) \n                             tokens) /\\\n                goodDefaultPC_aux (pc +32_n len) start allStartAddrs \n                  (length tokens) /\\\n                (dfa_recognize non_cflow_dfa tokens' = Some (len, remaining) \\/\n                 (dfa_recognize dir_cflow_dfa tokens' = Some (len, remaining) /\\\n                  includeAllJmpTargets pc len tokens' allJmpTargets) \\/\n                 dfa_recognize nacljmp_dfa tokens' = Some (len, remaining)).\n  (* Admitted. *)\n  Proof. induction n. intros.\n    Case \"n=0\". intros. destruct tokens; pbprover.\n    Case \"S n\". intros.\n      process_buffer_aux_tac.\n      SCase \"tokens = nil\". pbprover.\n      SCase \"tokens<>nil; nacljmp_dfa matches\". clear Hd1 Hd2.\n        use_lemma dfa_recognize_inv by eassumption. sim.\n        destruct (@Int32Set_in_dichotomy pc start _ _ H2).\n        SSCase \"pc=start\". subst pc.\n          assert (goodDefaultPC_aux (start +32_n len3) start allStartAddrs\n                    (length (t1::tokens1))).\n            destruct remaining3.\n            SSSCase \"remaining3=nil\".\n              assert (len3 = length (t1 ::tokens1)) by crush.\n              right. congruence.\n            SSSCase \"remaining3<>nil\".\n              left. eapply process_buffer_aux_start_in.\n              eassumption. simpl. omega.\n          exists (t1::tokens1), len3, remaining3. pbprover.\n        SSCase \"pc in (allStartAddrs - ({start} \\/ currStartAddrs)\".\n          assert (length (t1::tokens1) >= 1)%nat by (simpl; omega).\n          assert (length remaining3 > 0)%nat by (destruct remaining3; pbprover).\n          use_lemma (process_buffer_arith_facts start len3 (t1::tokens1) remaining3)\n            by assumption.\n          break_hyp.\n          use_lemma process_buffer_aux_addrRange by eassumption.\n          use_lemma IHn by eassumption.\n          destruct H12 as [tokens'' [len [remaining [H20 [H21 H22]]]]].\n          subst tokens''. rewrite H3 in H22. rewrite skipn_twice_eq in H22.\n          int32_simplify.\n          assert (Zabs_nat (unsigned pc - (unsigned start + Z_of_nat len3)) + len3 =\n                  Zabs_nat (unsigned pc - unsigned start))%nat as H30.\n            apply inj_eq_rev; int32_simplify_in_goal; ring.\n          rewrite H30 in H22.\n          assert (goodDefaultPC_aux (pc +32_n len) start allStartAddrs\n                    (length (t1 :: tokens1))).\n            destruct H21. left. assumption.\n              right. rewrite H4. rewrite <- add_repr.\n                unfold w32add at 2. rewrite <- add_assoc.\n              assumption.\n          exists (skipn (Zabs_nat (unsigned pc -unsigned start)) (t1::tokens1)).\n            exists len, remaining.\n              split. trivial.\n              split. assumption. assumption.\n      SCase \"tokens<>nil; non_cflow_dfa matches\". clear Hd2 Hd3.\n        use_lemma dfa_recognize_inv by eassumption. sim.\n        destruct (@Int32Set_in_dichotomy pc start _ _ H2).\n        SSCase \"pc=start\". subst pc.\n          assert (goodDefaultPC_aux (start +32_n len1) start allStartAddrs\n                    (length (t1::tokens1))).\n            destruct remaining1.\n            SSSCase \"remaining1=nil\".\n              assert (len1 = length (t1 ::tokens1)) by crush.\n              right. congruence.\n            SSSCase \"remaining3<>nil\".\n              left. eapply process_buffer_aux_start_in.\n              eassumption. simpl. omega.\n          exists (t1::tokens1), len1, remaining1. pbprover.\n        SSCase \"pc in (allStartAddrs - ({start} \\/ currStartAddrs)\".\n          assert (length (t1::tokens1) >= 1)%nat by (simpl; omega).\n          assert (length remaining1 > 0)%nat by (destruct remaining1; pbprover).\n          use_lemma (process_buffer_arith_facts start len1 (t1::tokens1) remaining1)\n            by assumption.\n          break_hyp.\n          use_lemma process_buffer_aux_addrRange by eassumption.\n          use_lemma IHn by eassumption.\n          destruct H12 as [tokens'' [len [remaining [H20 [H21 H22]]]]].\n          subst tokens''. rewrite H3 in H22. rewrite skipn_twice_eq in H22.\n          int32_simplify.\n          assert (Zabs_nat (unsigned pc - (unsigned start + Z_of_nat len1)) + len1 =\n                  Zabs_nat (unsigned pc - unsigned start))%nat as H30.\n            apply inj_eq_rev; int32_simplify_in_goal; ring.\n          rewrite H30 in H22. break_hyp.\n          assert (goodDefaultPC_aux (pc +32_n len) start allStartAddrs\n                    (length (t1 :: tokens1))).\n            destruct H21. left. assumption.\n              right. rewrite H4. rewrite <- add_repr.\n                unfold w32add at 2. rewrite <- add_assoc.\n              assumption.\n          exists (skipn (Zabs_nat (unsigned pc -unsigned start)) (t1::tokens1)).\n            exists len, remaining.\n              split. trivial. split; assumption.\n      SCase \"tokens<>nil; dir_cflow_dfa matches\". clear Hd1 Hd3.\n        remember_destruct_head in H as ed; try discriminate.\n        use_lemma dfa_recognize_inv by eassumption. sim.\n        destruct (@Int32Set_in_dichotomy pc start _ _ H2).\n        SSCase \"pc=start\". subst pc.\n          assert (goodDefaultPC_aux (start +32_n len2) start allStartAddrs\n                    (length (t1::tokens1))).\n            destruct remaining2.\n            SSSCase \"remaining2=nil\".\n              assert (len2 = length (t1 ::tokens1)) by crush.\n              right. congruence.\n            SSSCase \"remaining2<>nil\".\n              left. eapply process_buffer_aux_start_in.\n              eassumption. simpl. omega.\n          use_lemma process_buffer_aux_subset by eassumption.\n          assert (Int32Set.In (start +32_n len2 +32 i) allJmpTargets).\n            apply Int32Set_in_subset\n              with (s:=(Int32Set.add (start +32_n len2 +32 i) currJmpTargets)).\n            eapply Int32Set.add_spec. left. apply int_eq_refl.\n            crush.\n          exists (t1::tokens1), len2, remaining2.\n            split. pbprover.\n            split. assumption.\n              right; left. split. assumption.\n              eapply extract_disp_include; eassumption.\n        SSCase \"pc in (allStartAddrs - ({start} \\/ currStartAddrs)\".\n          assert (length (t1::tokens1) >= 1)%nat by (simpl; omega).\n          assert (length remaining2 > 0)%nat by (destruct remaining2; pbprover).\n          use_lemma (process_buffer_arith_facts start len2 (t1::tokens1) remaining2)\n            by assumption.\n          break_hyp.\n          use_lemma process_buffer_aux_addrRange by eassumption.\n          use_lemma IHn by eassumption.\n          destruct H12 as [tokens'' [len [remaining [H20 [H21 H22]]]]].\n          subst tokens''. rewrite H3 in H22. rewrite skipn_twice_eq in H22.\n          int32_simplify.\n          assert (Zabs_nat (unsigned pc - (unsigned start + Z_of_nat len2)) + len2 =\n                  Zabs_nat (unsigned pc - unsigned start))%nat as H30.\n            apply inj_eq_rev; int32_simplify_in_goal; ring.\n          rewrite H30 in H22.\n          assert (goodDefaultPC_aux (pc +32_n len) start allStartAddrs\n                    (length (t1 :: tokens1))).\n            destruct H21. left. assumption.\n              right. rewrite H4. rewrite <- add_repr.\n                unfold w32add at 2. rewrite <- add_assoc.\n              assumption.\n          exists (skipn (Zabs_nat (unsigned pc -unsigned start)) (t1::tokens1)).\n            exists len, remaining.\n              split. trivial. split; assumption.\n  Qed.\n\n  Hint Rewrite Zminus_0_r : pbDB.\n\n  Lemma process_buffer_inversion :\n   forall buffer startAddrs jmpTargets,\n    process_buffer buffer = Some(startAddrs, jmpTargets)\n      -> Z_of_nat (length buffer) <= w32modulus\n      -> forall pc:int32, Int32Set.In pc startAddrs\n           -> exists tokens', exists len, exists remaining,\n                tokens' = (List.skipn (Zabs_nat (unsigned pc)) \n                             (List.map byte2token buffer)) /\\\n                goodDefaultPC (pc +32_n len) startAddrs (length buffer) /\\\n                (dfa_recognize non_cflow_dfa tokens' = Some (len, remaining) \\/\n                 (dfa_recognize dir_cflow_dfa tokens' = Some (len, remaining) /\\\n                  includeAllJmpTargets pc len tokens' jmpTargets) \\/\n                 dfa_recognize nacljmp_dfa tokens' = Some (len, remaining)).\n  Proof. unfold process_buffer; intros.\n    assert (length (List.map byte2token buffer) = length buffer) as H10\n      by (apply list_length_map).\n    assert (noOverflow (repr 0 ::\n      int32_of_nat (length (List.map byte2token buffer) - 1) :: nil)).\n      rewrite H10. \n      destruct buffer as [| b buffer'].\n        simpl. int32_simplify. rewrite int32_modulus_constant. simpl. lia.\n        assert (length (b::buffer') >= 1)%nat by (simpl; omega).\n        int32_prover.\n    apply process_buffer_aux_inversion with (pc:=pc) in H;\n      [idtac | assumption | (rewrite list_length_map; omega) | pbprover].\n    destruct H as [tokens' [len [remaining H]]].\n    break_hyp.\n    assert (goodDefaultPC (pc +32_n len) startAddrs (length buffer)).\n      unfold goodDefaultPC, goodDefaultPC_aux in *.\n      destruct H3. left. trivial.\n        right. unfold w32add in H3. rewrite zero_add in H3.\n          rewrite <- H10. assumption.\n    exists tokens', len, remaining. int32_simplify. pbprover.\n  Qed.\n\n  (** *** Properties of simple_parse *)\n  Lemma simple_parse'_len_pos : forall bytes ps pre ins bytes1,\n    simple_parse' ps bytes = Some ((pre,ins), bytes1)\n      -> (length bytes > length bytes1)%nat.\n  Proof. induction bytes. crush.\n    intros. compute [simple_parse'] in H. fold simple_parse' in H.\n      remember_destruct_head in H as pb.\n      destruct l.\n        use_lemma IHbytes by eassumption. crush.\n        crush.\n  Qed.\n\n  Lemma simple_parse'_ext : forall bytes bytes1 ps pre ins rem len,\n    simple_parse' ps bytes = Some ((pre,ins), rem)\n      -> len = (length bytes - length rem)%nat\n      -> firstn len bytes = firstn len bytes1\n      -> exists rem1, simple_parse' ps bytes1 = Some ((pre,ins), rem1).\n  Proof. induction bytes as [ | b bytes']. crush.\n    Case \"bytes = b :: bytes'\".\n      intros. dupHyp H.\n      compute [simple_parse'] in H. fold simple_parse' in H.\n      use_lemma simple_parse'_len_pos by eassumption.\n      assert (len >= 1)%nat by omega.\n      destruct len. contradict H4. omega.\n      destruct bytes1. simpl in H1. congruence.\n      simpl in H1.\n      inversion H1. subst i.\n      compute [simple_parse']. fold simple_parse'.\n      destruct (parse_byte ps b).\n      destruct l.\n      SCase \"parse_byte returns nil\".\n        assert (len = length bytes' - length rem)%nat.\n          simpl length at 1 in H0. omega.\n        eapply IHbytes'; eassumption.\n      SCase \"parse_byte returns some val\".\n        exists bytes1. crush.\n  Qed.\n\n  (** *** A theorem about immutable code region *)\n  Section FETCH_INSTR_CODE_INV.\n\n  Opaque parse_instr.\n  Ltac clear_parse_instr := \n    match goal with\n      | [H: parse_instr _ _ = _ |- _ ] => clear H\n    end. \n\n  Remark fetchSize_lt_modulus : 15 <= w32modulus.\n  Proof. rewrite int32_modulus_constant. lia. Qed.\n\n  Theorem fetch_instr_code_inv : forall s1 s2 s1' pc pre i len,\n    eqCodeRegion s1 s2\n      -> fetch_instruction pc s1 = (Okay_ans (pre, i, len), s1')\n      -> fetch_instruction pc s2 = (Okay_ans (pre, i, len), s2).\n  Proof. unfold fetch_instruction. intros.\n    repeat rtl_okay_elim.\n    destruct v as [pi' len'].\n    rtl_okay_elim.\n    remember_destruct_head in H0 as bchk; try discriminate H0.\n    inversion H0. subst pi' len' s1'.\n    assert (s1 = s).\n      eapply parse_instr_same_state. \n      eapply H1.\n    subst s.\n    bool_elim_tac.\n    dupHyp H; unfold eqCodeRegion in H. destruct H as [H10 [H11 [H12 H13]]].\n    assert (H14:1 <= Zpos len < 16).\n      eapply parse_instr_len. \n      eapply H1.\n    assert (Zpos len - 1 < w32modulus). \n      apply Zlt_le_trans with (m:=15). omega.\n      apply fetchSize_lt_modulus.\n    assert (noOverflow (pc :: repr (Zpos len - 1) :: nil)).\n      apply checkNoOverflow_equiv_noOverflow. trivial.\n    assert (noOverflow (CStart s1 +32 pc :: repr (Zpos len - 1) :: nil))\n        by int32_prover.\n    assert (H20: Ensembles.Included int32\n              (addrRegion (CStart s1 +32 pc) (repr (Zpos len - 1)))\n              (segAddrs CS s1)).\n      apply subsetRegion_sound. assumption. assumption.\n        subsetRegion_intro_tac; int32_prover.\n    assert (parse_instr pc s2 = (Okay_ans (pre, i, len), s2)).\n      eapply parse_instr_code_inv. \n      eassumption. eapply H1.\n      eassumption. eassumption. eassumption.\n    assert (H22: AddrMap.get (CStart s1 +32 pc) (rtl_memory s1)\n                = AddrMap.get (CStart s1 +32 pc) (rtl_memory s2)).\n      apply H13. apply H20. apply addrRegion_start_in.\n   (* all useful hypotheses from fetch_instruction pc s1 = ... \n      are now in the context *)\n    eapply rtl_bind_okay_intro. eassumption.\n    remember_destruct_head as pl. \n    inversion Hpl. subst p p0. \n    rtl_okay_intro.\n    rewrite <- H11. \n    rewrite H2. rewrite H3. simpl.\n    reflexivity.\n  Qed.\n  Transparent parse_instr.\n  End FETCH_INSTR_CODE_INV.\n\n  Lemma codeLoaded_inv : forall s1 s2 code,\n    eqCodeRegion s1 s2 -> codeLoaded code s1 -> codeLoaded code s2.\n  Proof. unfold eqCodeRegion, codeLoaded.\n    intros. split; [idtac | crush].\n    unfold eqMemBuffer in *. split. crush.\n    intros. sim.\n    generalize (H3 i); intros.\n    rewrite H7 by assumption. \n    rewrite <- H. apply H6.\n    unfold Ensembles.In. unfold segAddrs, addrRegion.\n    exists (int32_of_nat i). split; [trivial | int32_prover].\n  Qed.\n\n  Lemma list_eq_exten :\n    forall (A:Type) (l1 l2:list A),\n      length l1 = length l2 \n        -> (forall n:nat, \n             (0<=n<length l1)%nat -> nth_error l1 n = nth_error l2 n)\n        -> l1 = l2.\n  Proof. induction l1; destruct l2; intros.\n    trivial. \n    simpl in H. discriminate. \n    simpl in H. discriminate.\n    simpl in H0.\n      use_lemma (H0 O) by omega.\n      simpl in H1. inversion H1.\n      assert (l1 = l2).\n        apply IHl1. crush.\n        intros. generalize (H0 (S n)).\n        intros. use_lemma H4 by omega.\n        simpl in H5. trivial.\n      congruence.\n  Qed.\n\n  Lemma fetch_n_sub_list : forall n1 n2 loc s,\n    (n2 <= n1)%nat\n      -> fetch_n n2 loc s = firstn n2 (fetch_n n1 loc s).\n  Proof. induction n1; intros.\n    Case \"n1=0\". assert (n2=0)%nat by omega. subst n2. crush.\n    Case \"S n1\".\n      destruct n2. crush.\n      SCase \"S n2\". simpl. f_equal. \n        clear initial_state. eapply IHn1. lia.\n  Qed.\n\n  Lemma codeLoaded_fetch_n : forall code s k pc code' gSize guardZone,\n    codeLoaded code s\n      -> (pc < length code)%nat\n      -> code' = skipn pc code\n      -> fetch_n gSize (CStart s +32_n (length code)) s = guardZone\n      -> (k < gSize)%nat\n      -> fetch_n k (CStart s +32_n pc) s = firstn k (code' ++ guardZone).\n  Proof. induction k.\n    Case \"k=0\". crush.\n    Case \"S k\". intros.\n      destruct code' as [| byte code''].\n      SCase \"code'=nil\".\n        assert (length (skipn pc code) + pc = length code)%nat as H10.\n          apply skipn_length.  trivial.\n        rewrite <- H1 in H10. simpl in H10. subst pc. \n        contradict H0. omega.\n      SCase \"code'<>nil\".\n        rewrite <- app_comm_cons. simpl.\n        f_equal.\n        SSCase \"byte = AddrMap.get (CStart s +32_n pc) (rtl_memory s))\".\n          erewrite <- codeLoaded_lookup by eassumption.\n          rewrite <- (plus_0_l pc).\n          rewrite <- skipn_nth. rewrite <- H1. crush.\n        SSCase \"fetch_n k ... = firstn k ...\".\n          rewrite add_assoc. rewrite add_repr.\n          assert (H10:Z_of_nat pc + 1 = Z_of_nat (pc + 1)).\n            rewrite inj_plus. ring.\n          rewrite H10.\n          assert (H12: (pc+1 <= length code)%nat) by omega.\n          apply le_lt_or_eq in H12.\n          destruct H12.\n          SSSCase \"pc+1<length code\".\n            eapply IHk; try eassumption.\n              rewrite plus_comm.\n                rewrite <- skipn_twice_eq. rewrite <- H1. trivial.\n              omega.\n          SSSCase \"pc+1=length code\".\n            assert (length (skipn pc code) + pc = length code)%nat.\n              apply skipn_length. trivial.\n            assert (H20:(length (skipn pc code) = length code - pc)%nat).\n              omega.\n            assert (H22:length (byte :: code'') = 1%nat).\n              rewrite H1. rewrite H20. rewrite <- H4. omega.\n            destruct code''. \n              simpl. rewrite H4. subst guardZone.\n              apply fetch_n_sub_list. omega.\n              crush.\n  Qed.\n\n  Lemma codeLoaded_fetch_n_2 : forall code s k pc code' gSize guardZone,\n    codeLoaded code s\n      -> unsigned pc < Z_of_nat (length code)\n      -> code' = skipn (nat_of_int32 pc) code\n      -> fetch_n gSize (CStart s +32_n (length code)) s = guardZone\n      -> (k < gSize)%nat\n      -> fetch_n k (CStart s +32 pc) s = firstn k (code' ++ guardZone).\n  Proof. intros. \n    rewrite <- (int32_of_nat_of_int32 pc).\n    assert (nat_of_int32 pc < Datatypes.length code)%nat.\n      apply inj_lt_rev. rewrite inj_Zabs_nat.\n      rewrite Zabs_eq by int32_prover.\n      assumption.\n    eapply codeLoaded_fetch_n; eassumption.\n  Qed.\n\n  Lemma Zdiv_eucl_mult : forall a b c,\n    b > 0 -> a = b * c -> Zdiv_eucl a b = (c, 0).\n  Proof. intros. \n    assert (a mod b = 0).\n      rewrite H0. rewrite (Zmult_comm b c).\n      apply Z_mod_mult.\n    unfold Zmod in H1.\n    case_eq (Zdiv_eucl a b). intros q r. intro.\n    use_lemma (Z_div_mod a b) by omega.\n    rewrite H2 in *. subst r.\n    sim. ring_simplify in H1.\n    assert (c = q). \n      apply Zmult_reg_l with (p:=b). omega. \n      congruence.\n    crush.\n  Qed.\n\n  Lemma codeLoaded_pc_inbound: forall code s (tokens remaining: list token_id) len,\n    codeLoaded code s \n      -> (length tokens + nat_of_int32 (PC s) = length code)%nat\n      -> length tokens = (len + length remaining)%nat\n      -> (len > 0)%nat\n      -> in_seg_bounds_rng CS (PC s) (repr (Z_of_nat len - 1)) s \n           = (Okay_ans true, s).\n  Proof. intros. unfold in_seg_bounds_rng. simpl.\n     generalize (le_0_n (length remaining)); intros.\n     f_equal. f_equal.\n     use_lemma codeLoaded_length by eassumption.\n     bool_intro_tac. int32_prover.\n       unfold codeLoaded in H. sim.\n       unfold look. int32_prover.\n  Qed.\n\n  Lemma skipn_byte2token_len : forall tokens n code,\n    tokens = skipn n (List.map byte2token code)\n      -> (n < length code)%nat\n      -> (length tokens + n = length code)%nat.\n  Proof. intros. rewrite H.\n    rewrite skipn_length. apply list_length_map.\n    rewrite list_length_map. omega.\n  Qed.\n\n  (** *** Properties of run_dep *)\n  Lemma run_rep_same_seg_regs : forall pre ins dpc,\n    same_seg_regs (RTL_step_list (instr_to_rtl pre ins))\n      -> same_seg_regs (run_rep pre ins dpc).\n  Proof. intros.\n    unfold run_rep, check_rep_instr.\n    destruct ins; (discriminate || (simpl in H; same_seg_regs_tac)).\n  Qed.\n\n  Hint Resolve run_rep_same_seg_regs : same_seg_regs_db.\n\n  Lemma run_rep_aoes_nci : forall pre ins dpc,\n    non_cflow_instr pre ins = true\n      -> agree_outside_seg ES (run_rep pre ins dpc).\n  Proof. unfold run_rep, check_rep_instr. intros.\n    Local Ltac rep_ins_aoes_tac := \n      agree_outside_seg_tac;\n      unfold instr_to_rtl, check_prefix; prove_instr.\n    destruct ins; (discriminate || rep_ins_aoes_tac).\n  Qed.\n\n  Hint Resolve run_rep_aoes_nci : agree_outside_seg_db.\n\n  Lemma run_rep_same_mem_dci : forall pre ins dpc,\n    dir_cflow_instr pre ins = true\n      -> same_mem (run_rep pre ins dpc).\n  Proof. unfold run_rep, check_rep_instr. intros.\n    destruct ins; discriminate.\n  Qed.\n  \n  Hint Resolve run_rep_same_mem_dci : same_mem_db.\n\n  Lemma run_rep_same_mem_nacljmp_snd : forall pre1 ins1 pre2 ins2 dpc,\n    nacljmp_mask_instr pre1 ins1 pre2 ins2 = true\n      -> same_mem (run_rep pre2 ins2 dpc).\n  Proof. unfold nacljmp_mask_instr. intros.\n    destruct ins1; bool_elim_tac; try discriminate.\n    destruct_head in H0; try discriminate.\n    destruct op1; try discriminate.\n    destruct op2; try discriminate.\n    bool_elim_tac.\n    destruct ins2; try discriminate.\n  Qed.\n\n  Hint Resolve run_rep_same_mem_nacljmp_snd : same_mem_db.\n\n  Lemma run_rep_PC : forall s v' s' pre ins default_pc,\n    run_rep pre ins default_pc s = (Okay_ans v', s')\n      -> PC s' = default_pc \\/ PC s' = PC s.\n  Proof. unfold run_rep; intros.\n    repeat rtl_okay_break.\n    destruct (eq v0 zero); [unfold set_loc in *; crush | idtac].\n    repeat rtl_okay_break.\n    destruct ins; try discriminate;\n    match goal with\n      | [H: RTL_step_list ?R ?S1 = (_, ?S2) |- _] => \n        let HX := fresh \"H\" in\n        assert (HX:same_pc (RTL_step_list R)) by \n            (unfold instr_to_rtl, check_prefix, conv_CMPS, conv_MOVS, conv_STOS;\n             prove_instr);\n        assert (PC S1 = PC S2) by (eapply HX; eassumption)\n    end;\n    repeat match goal with \n      | [H: (if ?X then _ else _) _ = _ |- _] => destruct X\n      | _ => rtl_okay_elim\n    end; unfold set_loc in *; crush.\n  Qed.\n\n\n  (** ** Proving that any non-cflow-instr reaches a safe state in one step *)\n  Ltac step_tac :=\n   match goal with\n    | [H1: step_immed ?s ?s' |- _] =>\n       unfold step_immed, step in H1; \n       do 2 rtl_okay_elim; unfold get_location in H1;\n       match goal with\n         | [H2: context[if ?X then _ else _]|- _] =>\n           destruct X; [idtac | discriminate ]; \n           rtl_okay_elim\n       end\n   end.\n\n  Ltac dup_fetch_instr_elim := \n    match goal with \n      | [H1: fetch_instruction _ _ = (Okay_ans (?Pre, ?Ins, ?Len), _),\n             H2: fetch_instruction _ ?S = (Okay_ans ?V, ?S0) |- _]\n        => assert (V = (Pre, Ins, Len)) by congruence;\n          assert (S0 = S) by congruence;\n          subst V S; clear H2\n    end.\n\n  Lemma nci_eqCodeRegion: forall pre ins s v' s',\n    non_cflow_instr pre ins = true\n      -> checkSegments s = true\n      -> RTL_step_list (instr_to_rtl pre ins) s = (Okay_ans v', s')\n      -> eqCodeRegion s s'.\n  Proof. intros.\n    eapply eqCodeRegion_intro2; try eassumption.\n    eapply nci_same_seg_regs; try eassumption.\n    eapply nci_aos; try eassumption.\n  Qed.\n\n  Ltac safestate_unfold_tac := \n    match goal with\n      | [H:safeState ?s ?inv |- _] => \n        unfold safeState, appropState in H; \n        destruct inv as [[sregs_st sregs_lm] code];\n        break_hyp\n    end.\n\n  Ltac same_seg_regs_rel_tac := \n      match goal with\n        | [H: ?C ?s = (Okay_ans _, ?s') |- Same_Seg_Regs_Rel.brel ?s ?s']\n          => let H:= fresh \"H\" in\n              assert (same_seg_regs C) as H by same_seg_regs_tac;\n              eauto using H\n      end.\n\n\n  Lemma nci_step_same_seg_regs : forall s s' inv pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> non_cflow_instr pre ins = true\n      -> safeState s inv\n      -> s ==> s'\n      -> Same_Seg_Regs_Rel.brel s s'.\n  Proof. intros.\n    safestate_unfold_tac.\n    step_tac. dup_fetch_instr_elim.\n    assert (same_seg_regs (RTL_step_list (instr_to_rtl pre ins))).\n      auto using nci_same_seg_regs.\n    same_seg_regs_rel_tac.\n  Qed.\n\n  Ltac aoar_tac := \n      match goal with\n        | [H: ?C ?s = (Okay_ans _, ?s') |- \n            agree_outside_addr_region (segAddrs ?Seg ?s) ?s ?s']\n          => let H:= fresh \"H\" in\n              assert (agree_outside_seg Seg C) as H \n                by agree_outside_seg_tac;\n              eapply H; eassumption\n      end.\n\n  Lemma nci_step_aos : forall s s' inv pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> non_cflow_instr pre ins = true\n      -> safeState s inv\n      -> s ==> s'\n      -> (agree_outside_addr_region (segAddrs DS s) s s' \\/\n          agree_outside_addr_region (segAddrs SS s) s s' \\/\n          agree_outside_addr_region (segAddrs GS s) s s' \\/\n          agree_outside_addr_region (segAddrs ES s) s s').\n  Proof. intros. safestate_unfold_tac.\n    step_tac.\n    dup_fetch_instr_elim.\n    remember (RTL_step_list (instr_to_rtl pre ins)) as comp.\n    assert (H20: agree_outside_seg DS comp \\/ agree_outside_seg SS comp \\/\n                 agree_outside_seg GS comp \\/ agree_outside_seg ES comp).\n      subst comp.\n      eauto using nci_aos.\n    destruct (lock_rep pre). destruct l. \n    Local Ltac nci_step_aos_helper := repeat match goal with\n           | [H: agree_outside_seg _ _ \\/ _ |- _] => destruct H\n           | [H: agree_outside_seg ?Seg _ |- \n              agree_outside_addr_region (segAddrs ?Seg _) _ _ \\/ _ ] => left\n           | [ |- agree_outside_addr_region _ _ _ \\/ _ ] => right\n           | [ |- agree_outside_addr_region _ _ _] => aoar_tac\n         end.\n    nci_step_aos_helper.\n    Case \"rep\".\n      right; right; right. aoar_tac.\n    Case \"repn\".  nci_step_aos_helper.\n    Case \"None\". nci_step_aos_helper.\n  Qed.\n\n  Lemma nci_checkSegments_inv : forall s s' inv pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> non_cflow_instr pre ins = true\n      -> safeState s inv\n      -> s ==> s'\n      -> checkSegments s' = true.\n  Proof.  intros. dupHyp H1. safestate_unfold_tac.\n    eapply checkSegments_inv.\n    eapply nci_step_same_seg_regs; eassumption.\n    assumption.\n  Qed.\n\n  Lemma nci_step_eqCodeRegion : forall s s' inv pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> non_cflow_instr pre ins = true\n      -> safeState s inv\n      -> s ==> s'\n      -> eqCodeRegion s s'.\n  Proof. intros. dupHyp H1.\n    safestate_unfold_tac.\n    eapply eqCodeRegion_intro.\n      eapply nci_step_same_seg_regs; eassumption.\n      assumption.\n      eapply nci_step_aos; eassumption.\n  Qed.\n\n  Lemma nci_code_inv : forall s s' inv pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> non_cflow_instr pre ins = true\n      -> safeState s inv\n      -> s ==> s'\n      -> codeLoaded (snd inv) s'.\n  Proof. intros. dupHyp H1.\n    safestate_unfold_tac.\n    eapply codeLoaded_inv; try eassumption.\n      eapply nci_step_eqCodeRegion; eassumption.\n  Qed.\n\n  Lemma nci_appropState : forall s s' inv pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> non_cflow_instr pre ins = true\n      -> safeState s inv\n      -> s ==> s'\n      -> appropState s' inv.\n  Proof. intros. dupHyp H1.\n    safestate_unfold_tac.\n    unfold appropState.\n    use_lemma nci_step_same_seg_regs by eassumption.\n    use_lemma nci_code_inv by eassumption.\n    use_lemma nci_checkSegments_inv by eassumption.\n    unfold Same_Seg_Regs_Rel.brel in *.\n    crush.\n  Qed.\n\n  Lemma filter_prefix_no_lock_or_rep:\n    forall pre seg_filter op_filter cs_filter,\n      filter_prefix ft_no_lock_or_rep seg_filter op_filter cs_filter pre = true\n        -> lock_rep pre = None.\n  Proof. unfold filter_prefix, ft_no_lock_or_rep; intros.\n    bool_elim_tac.\n    destruct (lock_rep pre); congruence.\n  Qed.\n\n  Lemma filter_prefix_only_lock:\n    forall pre seg_filter op_filter cs_filter,\n      filter_prefix ft_only_lock seg_filter op_filter cs_filter pre = true\n        -> lock_rep pre = Some lock \\/ lock_rep pre = None.\n  Proof. unfold filter_prefix, ft_only_lock; intros.\n    bool_elim_tac.\n    destruct (lock_rep pre) as [lr|]; [destruct lr|]; crush.\n  Qed.\n\n  Lemma same_pc_same_mem_fetch_equal : forall n loc len ps s s' s0,\n       rtl_memory s = rtl_memory s0\n    -> seg_regs_starts (get_core_state s) = seg_regs_starts (get_core_state s0)\n    -> seg_regs_limits (get_core_state s) = seg_regs_limits (get_core_state s0)\n    -> parse_instr_aux n loc len ps s = Fail _ s' \n    -> (exists s0', parse_instr_aux n loc len ps s0 = Fail _ s0').\n  Proof.\n    induction n; intros.\n    simpl. auto. exists s0. auto. unfold parse_instr_aux in *.\n    Opaque parse_byte. simpl in *.\n    rewrite <-H. destruct (parse_byte ps (AddrMap.get loc0 (rtl_memory s))).\n    destruct l. eapply IHn; eauto.\n    discriminate H2.\n  Qed.\n\n  Lemma nci_nextStepNoFail : forall s pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> checkSegments s = true\n      -> non_cflow_instr pre ins = true\n      -> nextStepNoFail s.\n  Proof. unfold nextStepNoFail, step, in_seg_bounds_rng.\n    intros. intro Hc.\n    rtl_fail_break. discriminate Hc.\n    do 2 rtl_comp_elim.\n    destruct_head in Hc; [idtac | discriminate].\n    rtl_fail_break; [congruence | idtac].\n    assert (v = (pre, ins, len)) by congruence.\n    assert (s0 = s) by crush.\n    subst v s.\n    assert (no_fail (RTL_step_list (instr_to_rtl pre ins)))\n      by (eauto using nci_no_fail).\n    remember_destruct_head in Hc as lr; [destruct l | idtac]; \n      try (unfold Trap in *; congruence).\n    Case \"Some rep\".\n        destruct ins; simpl in H1; bool_elim_tac; unfold_prefix_filters_tac;\n        match goal with\n          | [H: false = true |- _] => congruence\n          | [H: filter_prefix ft_no_lock_or_rep _ _ _ _ = true |- _]\n            => apply filter_prefix_no_lock_or_rep in H; congruence\n          | [H: filter_prefix ft_only_lock _ _ _ _ = true |- _]\n            => apply filter_prefix_only_lock in H; destruct H; congruence\n          | _ => (* CMPS/STOS/MOVS*)\n            unfold run_rep, check_rep_instr in *;\n            contradict Hc;\n            (match goal with\n               | [|-?c _ <> (Fail_ans, _)] => \n                 let H:= fresh \"H\" in\n                   cut (no_fail c); [intro H; apply H | idtac]\n             end);\n            unfold instr_to_rtl; no_fail_tac; fail\n          | _ => idtac\n        end.\n        SCase \"LEA\".\n          destruct op2; try congruence.\n          bool_elim_tac.\n          apply filter_prefix_no_lock_or_rep in H1; congruence.\n      Case \"None\".\n        destruct ins; simpl in H1; bool_elim_tac;\n        match goal with\n          | _ =>\n            contradict Hc;\n            (match goal with\n               | [|-?c _ <> (Fail_ans, _)] => \n                 let H:= fresh \"H\" in\n                   cut (no_fail c); [intro H; apply H | idtac]\n             end);\n            no_fail_tac\n        end.\n  Qed.\n\n  Lemma nci_step_defaultPC : forall s s' pre ins len inv,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> non_cflow_instr pre ins = true\n      -> safeState s inv\n      -> s ==> s'\n         (* the case of \"PC s' = PC s\" is for the case of MOVS/STOS/CMPS with a\n            repeat prefix *)\n      -> PC s' = PC s +32_p len \\/ PC s' = PC s.\n  Proof. intros.\n    safestate_unfold_tac.\n    step_tac. dup_fetch_instr_elim.\n    assert (H20:same_pc (RTL_step_list (instr_to_rtl pre ins))).\n      eapply nci_same_pc; eassumption.\n    destruct (lock_rep pre). destruct l.\n    Case \"lock\". discriminate.\n    Case \"rep\".\n      eapply run_rep_PC. eassumption.\n    Case \"repn\". discriminate.\n    Case \"none\". left.\n      rtl_okay_break.\n      assert (PC s = PC s'). eapply H20; eassumption.\n      unfold set_loc in *;\n      crush.\n  Qed.\n\n  Lemma pc_at_end_is_safe : forall s code pc startAddrs,\n    codeLoaded code s\n      -> checkProgram code = (true, startAddrs)\n      -> pc = int32_of_nat (length code)\n      -> Int32Set.In pc startAddrs \\/ ~inBoundCodeAddr pc s.\n  Proof. unfold codeLoaded; intros.\n    break_hyp.\n    generalize (unsigned_range (CLimit s)); intro.\n    assert (H20:unsigned (CLimit s) + 1 <= w32modulus) by omega.\n    apply Zle_lt_or_eq in H20.\n    destruct H20.\n    Case \"unsigned (CLimit s) + 1 < w32modulus\". right.\n      unfold inBoundCodeAddr.  \n      rewrite H1. rewrite H2. int32_simplify. omega.\n    Case \"unsigned (CLimit s') + 1 = w32modulus\". left.\n      assert (pc = int32_zero).\n        rewrite H1. rewrite H2. rewrite H4.\n        apply mkint_eq. apply Z_mod_same_full.\n      generalize (unsigned_range (CLimit s)); intro.\n      assert ((length code) > 0)%nat. omega.\n      unfold checkProgram, FastVerifier.checkProgram in H0.\n      remember_destruct_head in H0 as pb; try discriminate H0.\n      destruct p. inversion H0; subst.\n      apply process_buffer_start_in in Hpb. crush. assumption.\n  Qed.\n\n  Lemma nci_safeInSomeK : forall s pre ins len inv startAddrs,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> non_cflow_instr pre ins = true\n      -> safeState s inv\n      -> checkProgram (snd inv) = (true, startAddrs)\n      -> goodDefaultPC ((PC s) +32_p len) startAddrs (length (snd inv))\n      -> safeInSomeK s inv.\n  Proof. unfold safeInSomeK. intros. \n    dupHyp H1. safestate_unfold_tac.\n    exists 1%nat.\n    apply safeInK_intro_one. \n      unfold safeState in H1. crush.\n      eapply nci_nextStepNoFail; try eassumption.\n      intros. unfold safeState. \n        assert (Int32Set.In (PC s) (snd (checkProgram code))).\n          destruct H6. trivial.\n          use_lemma step_immed_pc_inBound by eassumption.\n            contradiction.\n        assert (Same_Seg_Regs_Rel.brel s s').\n          eapply nci_step_same_seg_regs; eassumption.\n        assert (CLimit s = CLimit s'). \n          unfold Same_Seg_Regs_Rel.brel in *. crush.\n        assert (unsigned (CLimit s') + 1 = Z_of_nat (length code)).\n          unfold codeLoaded in H8. crush.\n        assert (Int32Set.In (PC s') (snd (checkProgram code)) \\/\n                ~ inBoundCodeAddr (PC s') s').\n          use_lemma nci_step_defaultPC by eassumption.\n          destruct H15.\n          Case \"PC s' = PC s +32_p len\".\n            unfold goodDefaultPC in *.\n            destruct H3.\n              SCase \"Int32Set.In (PC s +32_p len) startAddrs\".\n                left. crush.\n              SCase \"PC s +32_p len = length code\".\n                unfold inBoundCodeAddr. rewrite <- H13.\n                use_lemma pc_at_end_is_safe by eassumption.\n                rewrite H15. simpl in H2. rewrite H2. simpl.\n                assumption.\n          Case \"PC s' = PC s\".\n            left. crush.\n        split. eapply nci_appropState; eassumption.\n        split. trivial. trivial.\n  Qed.\n\n  (** *** Proving that dir_cflow_instr can reach safe state in one step *)\n  Lemma dci_eqCodeRegion: forall pre ins s v' s',\n    dir_cflow_instr pre ins = true\n      -> checkSegments s = true\n      -> RTL_step_list (instr_to_rtl pre ins) s = (Okay_ans v', s')\n      -> eqCodeRegion s s'.\n  Proof. intros.\n    eapply eqCodeRegion_intro2; try eassumption.\n    eapply dci_same_seg_regs; try eassumption.\n    right. left. eauto using dci_aoss.\n  Qed.\n\n  Lemma dci_step_same_seg_regs : forall s s' inv pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> dir_cflow_instr pre ins = true\n      -> safeState s inv\n      -> s ==> s'\n      -> Same_Seg_Regs_Rel.brel s s'.\n  Proof. intros.\n    safestate_unfold_tac.\n    step_tac. dup_fetch_instr_elim.\n    assert (same_seg_regs (RTL_step_list (instr_to_rtl pre ins))).\n      auto using dci_same_seg_regs.\n    same_seg_regs_rel_tac.\n  Qed.\n\n  Lemma dci_step_aoss : forall s s' inv pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> dir_cflow_instr pre ins = true\n      -> safeState s inv\n      -> s ==> s'\n      -> agree_outside_addr_region (segAddrs SS s) s s'.\n  Proof. intros. safestate_unfold_tac.\n    step_tac. dup_fetch_instr_elim.\n    remember (RTL_step_list (instr_to_rtl pre ins)) as comp.\n    assert (H20: agree_outside_seg SS comp).\n      subst comp.\n      eauto using dci_aoss.\n    destruct (lock_rep pre).\n      destruct l.\n        discriminate. aoar_tac.\n        discriminate. aoar_tac.\n  Qed.\n\n  Lemma dci_checkSegments_inv : forall s s' inv pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> dir_cflow_instr pre ins = true\n      -> safeState s inv\n      -> s ==> s'\n      -> checkSegments s' = true.\n  Proof.  intros. dupHyp H1.\n    safestate_unfold_tac.\n    eapply checkSegments_inv.\n    eapply dci_step_same_seg_regs; eassumption.\n    assumption.\n  Qed.\n\n  Lemma dci_code_inv : forall s s' inv pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> dir_cflow_instr pre ins = true\n      -> safeState s inv\n      -> s ==> s'\n      -> codeLoaded (snd inv) s'.\n  Proof. intros. dupHyp H1.\n    safestate_unfold_tac.\n    eapply codeLoaded_inv; try eassumption.\n    eapply eqCodeRegion_intro.\n      eapply dci_step_same_seg_regs; eassumption.\n      assumption.\n      right. left. eapply dci_step_aoss; eassumption.\n  Qed.\n\n  Lemma dci_appropState : forall s s' inv pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> dir_cflow_instr pre ins = true\n      -> safeState s inv\n      -> s ==> s'\n      -> appropState s' inv.\n  Proof. intros. dupHyp H1.\n    safestate_unfold_tac.\n    unfold appropState.\n    use_lemma dci_step_same_seg_regs by eassumption.\n    use_lemma dci_code_inv by eassumption.\n    use_lemma dci_checkSegments_inv by eassumption.\n    unfold Same_Seg_Regs_Rel.brel in *.\n    crush.\n  Qed. \n\n  Lemma no_prefix_no_lock_rep : forall pre,\n    no_prefix pre = true -> lock_rep pre = None.\n  Proof. unfold no_prefix, filter_prefix, ft_no_lock_or_rep. intros.\n    bool_elim_tac. destruct (lock_rep pre); congruence.\n  Qed.\n\n  Lemma dci_lock_rep_prefix : forall pre ins,\n    dir_cflow_instr pre ins = true -> lock_rep pre = None.\n  Proof. intros.\n    destruct ins; simpl in H; bool_elim_tac; try congruence.\n    Case \"CALL\".\n      do 2 (destruct_head in H; try congruence).\n      destruct op1; try congruence.\n      destruct_head in H; try congruence.\n      unfold no_prefix in *.\n      apply filter_prefix_no_lock_or_rep in H. assumption.\n    Case \"Jcc\".\n      unfold no_prefix in *.\n      apply filter_prefix_no_lock_or_rep in H. assumption.\n    Case \"Jmp\".\n      do 2 (destruct_head in H; try congruence).\n      destruct op1; try congruence.\n      destruct_head in H; try congruence.\n      unfold no_prefix in *.\n      apply filter_prefix_no_lock_or_rep in H. assumption.\n  Qed.\n\n  Lemma dci_nextStepNoFail : forall s pre ins len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> checkSegments s = true\n      -> dir_cflow_instr pre ins = true\n      -> nextStepNoFail s.\n  Proof. unfold nextStepNoFail, step, in_seg_bounds_rng.\n    intros. intro Hc.\n    rtl_fail_break. discriminate Hc.\n    do 2 rtl_comp_elim.\n    destruct_head in Hc; [idtac | discriminate].\n    rtl_fail_break; [congruence | idtac].\n    assert (v = (pre, ins, len)) by congruence.\n    assert (s0 = s) by congruence.\n    subst v s.\n    assert (no_fail (RTL_step_list (instr_to_rtl pre ins)))\n        by (eauto using dci_no_fail).\n    contradict Hc.\n    (match goal with\n       | [|-?c _ <> (Fail_ans, _)] => \n         cut (no_fail c)\n     end).\n    intro H10. apply H10.\n    use_lemma dci_lock_rep_prefix by eassumption.\n    rewrite H4. no_fail_tac.\n  Qed.\n\n  Lemma conv_JMP_relative_imm_PC : forall pre disp cs r cs' s v' s',\n    conv_JMP pre true false (Imm_op disp) None cs = (r, cs') \n      -> same_pc (RTL_step_list (List.rev (c_rev_i cs)))\n      -> RTL_step_list (List.rev (c_rev_i cs')) s = (Okay_ans v', s')\n      -> (PC s') = (PC s) +32 disp.\n  Proof. intros.\n    unfold conv_JMP in H.\n    simpl in H. \n    inv H. simpl in H1.\n    autorewrite with step_list_db in H1.\n    repeat rtl_okay_elim. removeUnit.\n    inv H2. simpl.\n    assert (H10:PC s = PC s2). eapply H0; eassumption.\n    crush.\n  Qed.\n\n  Lemma conv_JMP_relative_imm_step_PC : forall s s' pre disp len,\n    fetch_instruction (PC s) s = \n      (Okay_ans (pre, (JMP true false (Imm_op disp) None), len), s)\n      -> no_prefix pre = true\n      -> s ==> s'\n      -> checkSegments s = true\n      -> (PC s') = (PC s) +32_p len +32 disp.\n  Proof. intros.\n    step_tac. dup_fetch_instr_elim.\n    unfold no_prefix, filter_prefix, ft_no_lock_or_rep, ft_bool_no in *.\n    bool_elim_tac.\n    destruct (lock_rep pre); try congruence.\n    rtl_okay_break.\n    unfold instr_to_rtl, runConv in H1.\n    remember_rev \n       (Bind unit (check_prefix pre)\n              (fun _ : unit => conv_JMP pre true false (Imm_op disp) None)\n              {| c_rev_i := nil |}) as cv.\n    destruct cv.\n    unfold check_prefix in Hcv.\n    destruct (addr_override pre); try congruence.\n    conv_elim.\n    assert (H10:PC s' = PC s +32 disp).\n      eapply conv_JMP_relative_imm_PC; try eassumption.\n      inv H7. crush.\n    unfold set_loc in *. rtl_okay_elim. \n    crush.\n  Qed.\n\n  Opaque set_mem_n. (* without this, the QED would take forever *)\n  Lemma conv_CALL_relative_imm_step_PC : forall s s' pre disp len,\n    fetch_instruction (PC s) s = \n      (Okay_ans (pre, (CALL true false (Imm_op disp) None), len), s)\n      -> no_prefix pre = true\n      -> s ==> s'\n      -> checkSegments s = true\n      -> (PC s') = (PC s) +32_p len +32 disp.\n  Proof. intros.\n    step_tac. dup_fetch_instr_elim.\n    unfold no_prefix, filter_prefix, ft_no_lock_or_rep, ft_bool_no in *.\n    bool_elim_tac.\n    destruct (lock_rep pre); try congruence.\n    rtl_okay_break.\n    unfold instr_to_rtl, runConv in H1.\n    remember_rev \n       (Bind unit (check_prefix pre)\n              (fun _ : unit => conv_CALL pre true false (Imm_op disp) None)\n              {| c_rev_i := nil |}) as cv.\n    destruct cv.\n    unfold conv_CALL, check_prefix in Hcv.\n    destruct (addr_override pre); try congruence.\n    repeat conv_elim.\n    assert (H20:PC s' = PC s +32 disp).\n      eapply conv_JMP_relative_imm_PC; try eassumption.\n      unfold set_mem32 in *.\n      repeat conv_backward_same_pc.\n      simpl. unfold same_pc. crush.\n    assert (H22:PC s = PC s0 +32_p len).\n      unfold set_loc in *. crush.\n    crush.\n  Qed.\n  Transparent set_mem_n.\n\n  Lemma conv_Jcc_PC : forall pre ct disp cs r cs' s v' s',\n    conv_Jcc pre ct disp cs = (r, cs') \n      -> same_pc (RTL_step_list (List.rev (c_rev_i cs)))\n      -> RTL_step_list (List.rev (c_rev_i cs')) s = (Okay_ans v', s')\n      -> (PC s' = (PC s) \\/ (PC s') = (PC s) +32 disp).\n  Proof. intros.\n    unfold conv_Jcc in H. \n    repeat conv_elim.\n    inv H. simpl in H1.\n    autorewrite with step_list_db in H1.\n    repeat rtl_okay_break.\n    inv H1.\n    assert (H10: PC s' = PC s0 \\/ PC s' = (interp_rtl_exp v2 s0)).\n      simpl in H6.\n      destruct_head in H6. right. unfold set_loc in H6. crush.\n        left. crush.\n    assert (H12: same_pc (RTL_step_list (rev (c_rev_i cs3)))).\n      unfold compute_cc, not in *.\n      repeat conv_backward_same_pc. assumption.\n    assert (H14: PC s = PC s0). eapply H12; eassumption.\n    clear H12 H6.\n    destruct H10. \n      Case \"fall through case\". left. crush.\n      Case \"the branch is taken\". right.\n        inv H5. simpl in *.\n        autorewrite with step_list_db in H.\n        repeat rtl_okay_break.\n        inv H2. inv H. \n        inv H4. simpl in *.\n        inv H6. simpl in *.\n        inv H3. simpl in *. removeUnit.\n        assert (H20: same_pc (RTL_step_list (rev (c_rev_i cs3)))).\n          unfold compute_cc, not in *.\n          repeat conv_backward_same_pc. assumption.\n        assert (H22: PC s = PC s0). eapply H20; eassumption.\n        rewrite H1. rewrite H22.\n        crush.\n  Qed.\n\n  Lemma conv_Jcc_step_PC : forall s s' pre ct disp len,\n    fetch_instruction (PC s) s = (Okay_ans (pre, (Jcc ct disp), len), s)\n      -> no_prefix pre = true\n      -> s ==> s'\n      -> checkSegments s = true\n      -> (PC s' = (PC s) +32_p len \\/ (PC s') = (PC s) +32_p len +32 disp).\n  Proof. intros.\n    step_tac. dup_fetch_instr_elim.\n    unfold no_prefix, filter_prefix, ft_no_lock_or_rep, ft_bool_no in *.\n    bool_elim_tac.\n    destruct (lock_rep pre); try congruence.\n    rtl_okay_break.\n    unfold instr_to_rtl, runConv in H1.\n    remember_rev \n       (Bind unit (check_prefix pre)\n              (fun _ : unit => conv_Jcc pre ct disp)\n              {| c_rev_i := nil|}) as cv.\n    destruct cv.\n    unfold check_prefix in Hcv.\n    destruct (addr_override pre); try congruence.\n    repeat conv_elim.\n    assert (H20:PC s' = PC s \\/ PC s' = PC s +32 disp).\n      eapply conv_Jcc_PC; try eassumption.\n      repeat conv_backward_same_pc.\n      simpl. unfold same_pc. crush.\n    assert (H22:PC s = PC s0 +32_p len). \n      extended_rtl_okay_elim. crush.\n    crush.\n  Qed.\n\n  (* any aligned address is a safe program counter *)\n  Lemma aligned_addr_safePC : forall s inv pc,\n    safeState s inv -> aligned pc\n      -> Int32Set.In pc (snd (checkProgram (snd inv))) \\/ ~ inBoundCodeAddr pc s.\n  Proof. intros. safestate_unfold_tac.\n    unfold checkProgram in *. simpl.\n    remember_rev (FastVerifier.checkProgram non_cflow_dfa dir_cflow_dfa nacljmp_dfa initial_state\n                  code) as cp.\n    destruct cp as [b startAddrs].\n    unfold FastVerifier.checkProgram in Hcp.\n    destruct_head in Hcp; [idtac | crush].\n    destruct p. inversion Hcp. subst. \n    simpl in H1. bool_elim_tac.\n    remember_rev (int32_lequ_bool pc (CLimit s)) as cmp.\n    destruct cmp.\n    Case \"pc <= (CLimit s)\". left. simpl.\n      unfold codeLoaded in *.\n      break_hyp.\n      assert (0 <= unsigned pc < Z_of_nat (length code)) by int32_prover.\n      rewrite <- (repr_unsigned _ pc).\n      eapply checkAligned_corr; try eassumption.\n        unfold aligned, aligned_bool in H0.\n        apply Zeq_is_eq_bool in H0.\n        assumption.\n    Case \"pc > (CLimit s)\". right. crush.\n  Qed.\n\n  Lemma dci_step_safePC : forall s s' pre ins len inv,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> dir_cflow_instr pre ins = true\n      -> safeState s inv\n      -> goodDefaultPC ((PC s) +32_p len) (snd (checkProgram (snd inv))) (length (snd inv))\n      -> goodJmp ins ((PC s) +32_p len) (snd (checkProgram (snd inv))) = true\n      -> s ==> s'\n      -> Int32Set.In (PC s') (snd (checkProgram (snd inv))) \\/ \n         ~ inBoundCodeAddr (PC s') s'.\n  Proof. unfold inBoundCodeAddr. intros.\n    use_lemma dci_step_same_seg_regs by eassumption.\n    assert (CLimit s = CLimit s').\n       unfold Same_Seg_Regs_Rel.brel in *. crush.\n    rewrite <- H6.\n    dupHyp H1. safestate_unfold_tac.\n    destruct ins; try discriminate H0.\n    Case \"CALL\".\n      destruct near; try discriminate H0.\n      destruct absolute; try discriminate H0.\n      destruct op1; try discriminate H0.\n      destruct sel; try discriminate H0.\n      use_lemma conv_CALL_relative_imm_step_PC by eassumption.\n      unfold goodJmp, goodJmpTarget in H3.\n      bool_elim_tac.\n        left. rewrite H13. apply Int32Set.mem_spec. crush.\n        eapply aligned_addr_safePC. assumption. crush.\n   Case \"Jcc\".\n      use_lemma conv_Jcc_step_PC by eassumption.\n      unfold goodJmp, goodJmpTarget in H3.\n      unfold goodDefaultPC in H2.\n      destruct H13.\n      SCase \"PC s' = PC s +32_p len\".\n        destruct H2. left. crush.\n          remember_rev (checkProgram code) as cp.\n          destruct cp as [t startAddrs].\n          simpl in H8. subst t.\n          use_lemma pc_at_end_is_safe by eassumption.\n          simpl. rewrite H13. rewrite Hcp. crush.\n      SCase \"PC s' = PC s +32_p len +32 disp\".\n      bool_elim_tac.\n        left. rewrite H13. apply Int32Set.mem_spec. assumption.\n        eapply aligned_addr_safePC. assumption. crush.\n    Case \"JMP\".\n      destruct near; try discriminate H0.\n      destruct absolute; try discriminate H0.\n      destruct op1; try discriminate H0.\n      destruct sel; try discriminate H0.\n      use_lemma conv_JMP_relative_imm_step_PC by eassumption.\n      unfold goodJmp, goodJmpTarget in H3.\n      bool_elim_tac.\n        left. rewrite H13. apply Int32Set.mem_spec. assumption.\n        eapply aligned_addr_safePC. assumption. crush.\n  Qed.        \n\n  Lemma dci_safeInSomeK : forall s pre ins len inv startAddrs,\n    fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n      -> dir_cflow_instr pre ins = true\n      -> safeState s inv\n      -> checkProgram (snd inv) = (true, startAddrs)\n      -> goodDefaultPC ((PC s) +32_p len) startAddrs (length (snd inv))\n      -> goodJmp ins ((PC s) +32_p len) (snd (checkProgram (snd inv))) = true\n      -> safeInSomeK s inv.\n  Proof. unfold safeInSomeK. intros. \n    dupHyp H1. safestate_unfold_tac.\n    exists 1%nat.\n    apply safeInK_intro_one. \n      unfold safeState in H1. crush.\n      eapply dci_nextStepNoFail; try eassumption.\n      intros. unfold safeState. \n        split. eapply dci_appropState; eassumption.\n        split. trivial. \n          change code with (snd ((sregs_st, sregs_lm, code))).\n          eapply dci_step_safePC; try eassumption. crush.\n  Qed. \n\n\n  (** *** Proving that nacljmp is safe in two steps *)\n  Lemma no_prefix_lock_or_gs_or_op: forall pre,\n    no_prefix pre = true -> lock_or_gs_or_op pre = true.\n  Proof. unfold_prefix_filters_tac. unfold filter_prefix; intros.\n     bool_elim_tac. bool_intro_tac; try trivial.\n     unfold ft_only_lock, ft_no_lock_or_rep in *. \n       destruct_head; congruence.\n     unfold ft_only_gs_seg, ft_no_seg in *. \n       destruct_head; congruence.\n  Qed.\n  \n  Lemma nacljmp_first_non_cflow_instr : forall pre1 ins1 pre2 ins2,\n    nacljmp_mask_instr pre1 ins1 pre2 ins2 = true \n      -> non_cflow_instr pre1 ins1 = true.\n  Proof. intros.\n    unfold nacljmp_mask_instr in H.\n    destruct ins1; bool_elim_tac; try discriminate.\n    apply no_prefix_lock_or_gs_or_op in H.\n    destruct op1; try (destruct w; discriminate).\n    simpl. crush.\n  Qed.\n\n  Lemma nacljmp_no_prefix : forall pre1 ins1 pre2 ins2,\n    nacljmp_mask_instr pre1 ins1 pre2 ins2 = true \n      -> no_prefix pre1 = true /\\ no_prefix pre2 = true.\n  Proof. unfold nacljmp_mask_instr; intros. bool_elim_tac.\n    crush.\n  Qed.\n\n  Lemma nacljmp_mask_PC : forall s s' pre1 ins1 len1 pre2 ins2 inv,\n    fetch_instruction (PC s) s = (Okay_ans (pre1, ins1, len1), s)\n      -> nacljmp_mask_instr pre1 ins1 pre2 ins2 = true\n      -> safeState s inv\n      -> s ==> s'\n      -> PC s' = PC s +32_p len1.\n  Proof. intros. safestate_unfold_tac.\n    step_tac. dup_fetch_instr_elim.\n    use_lemma nacljmp_first_non_cflow_instr by eassumption.\n    assert (H20:same_pc (RTL_step_list (instr_to_rtl pre1 ins1))).\n      eapply nci_same_pc; eassumption.\n    use_lemma nacljmp_no_prefix by eassumption.\n    break_hyp. \n    assert (H21:lock_rep pre1 = None).\n      eauto using filter_prefix_no_lock_or_rep.\n    rewrite H21 in *.\n    rtl_okay_break.\n    assert (H22:PC s = PC s'). eapply H20; eassumption.\n    rewrite <- H22. unfold set_loc in *. crush.\n  Qed.\n\n  Lemma nacljmp_snd_no_fail : forall pre1 ins1 pre2 ins2,\n    nacljmp_mask_instr pre1 ins1 pre2 ins2 = true \n      -> no_fail (RTL_step_list (instr_to_rtl pre2 ins2)).\n  Proof. unfold nacljmp_mask_instr; intros. \n    destruct ins1; bool_elim_tac; try discriminate.\n    (destruct_head in H0; try discriminate H0).\n    destruct op1; try discriminate H0.\n    destruct op2; try discriminate H0.\n    bool_elim_tac.\n    destruct ins2; try discriminate.\n    Case \"Call\".\n      unfold instr_to_rtl in *.\n      do 2 (destruct_head in H2; try discriminate).\n      destruct op1; try discriminate.\n      prove_instr.\n    Case \"Jmp\".\n      unfold instr_to_rtl in *.\n      do 2 (destruct_head in H2; try discriminate).\n      destruct op1; try discriminate.\n      prove_instr.\n  Qed.\n  \n  Lemma nacljmp_snd_nextStepNoFail : forall s pre1 ins1 pre2 ins2 len2,\n    fetch_instruction (PC s) s = (Okay_ans (pre2, ins2, len2), s)\n      -> checkSegments s = true\n      -> nacljmp_mask_instr pre1 ins1 pre2 ins2 = true \n      -> nextStepNoFail s.\n  Proof. unfold nextStepNoFail, step, in_seg_bounds_rng.\n    intros. intro Hc.\n    rtl_fail_break. discriminate Hc.\n    do 2 rtl_comp_elim.\n    destruct_head in Hc; [idtac | discriminate].\n    rtl_fail_break; [congruence | idtac].\n      assert (v = (pre2, ins2, len2)) by congruence.\n      assert (s0 = s) by crush.\n      subst v s.\n      assert (no_fail (RTL_step_list (instr_to_rtl pre2 ins2))) \n        by (eauto using nacljmp_snd_no_fail).\n      contradict Hc.\n      (match goal with\n         | [|-?c _ <> (Fail_ans, _)] => \n           cut (no_fail c)\n         end).\n      intro H10. apply H10.\n      remember_rev (lock_rep pre2) as lr.\n      destruct lr. destruct l.\n        Case \"lock\". \n          apply nacljmp_no_prefix in H1. break_hyp. \n          crush' no_prefix_no_lock_rep fail.\n        Case \"rep\". \n          apply nacljmp_no_prefix in H1. break_hyp. \n          crush' no_prefix_no_lock_rep fail.\n        Case \"repn\". \n          apply nacljmp_no_prefix in H1. break_hyp. \n          crush' no_prefix_no_lock_rep fail.\n        Case \"none\". no_fail_tac.\n  Qed.\n\n  Lemma no_prefix_no_op_override : forall pre,\n    no_prefix pre = true -> op_override pre = false.\n  Proof. unfold no_prefix, filter_prefix, ft_bool_no. intros.\n    bool_elim_tac. trivial.\n  Qed.\n\n  (* A tactic useful when doing proofs that requires detailed reasoning of\n     instruction semantics *)\n  Local Ltac conv_backward_roll := \n    conv_backward; repeat rtl_okay_elim;\n    repeat match goal with\n      | [H: set_loc _ _ _ = (Okay_ans _, _) |- _] => inv H; simpl\n      | [H: advance_oracle _ = (Okay_ans _, _) |- _] => inv H; simpl\n    end.\n\n  Lemma nacljmp_mask_reg_aligned: forall pre r1 wd cs r cs' s v' s',\n    conv_AND pre true (Reg_op r1) (Imm_op wd) cs = (r, cs')\n      -> no_prefix pre = true\n      -> signed wd = signed safeMask\n      -> RTL_step_list (List.rev (c_rev_i cs')) s = (Okay_ans v', s')\n      -> aligned (get_location (reg_loc r1) (rtl_mach_state s')).\n  Proof. unfold conv_AND, conv_logical_op. intros.\n    assert (op_override pre = false).\n      eauto using no_prefix_no_op_override.\n    unfold  load_op, set_op, compute_parity in H.\n    rewrite H3 in H.\n    compute [opsize] in H.\n    repeat conv_elim. removeUnit.\n    conv_backward_roll.\n    unfold look, upd.\n    destruct_head; [idtac | contradict n; trivial].\n    repeat conv_backward_roll.\n    simpl.\n    unfold look.\n    eapply and_safeMask_aligned. assumption.\n  Qed.\n\n  Lemma nacljmp_snd_same_seg_regs : forall pre1 ins1 pre2 ins2,\n    nacljmp_mask_instr pre1 ins1 pre2 ins2 = true\n      -> same_seg_regs (RTL_step_list (instr_to_rtl pre2 ins2)).\n  Proof. unfold nacljmp_mask_instr. intros.\n      destruct ins1; bool_elim_tac; try discriminate H0.\n      destruct_head in H0; try discriminate.\n      destruct op1; try discriminate.\n      destruct op2; try discriminate.\n      bool_elim_tac.\n      destruct ins2; try discriminate H2.\n      unfold instr_to_rtl, check_prefix. prove_instr.\n      unfold instr_to_rtl, check_prefix. prove_instr.\n  Qed.\n\n  Lemma nacljmp_snd_step_same_seg_regs : \n   forall s s' code pre1 ins1 pre2 ins2 len2,\n    fetch_instruction (PC s) s = (Okay_ans (pre2, ins2, len2), s)\n      -> nacljmp_mask_instr pre1 ins1 pre2 ins2 = true \n      -> codeLoaded code s\n      -> checkSegments s = true\n      -> s ==> s'\n      -> Same_Seg_Regs_Rel.brel s s'.\n  Proof. unfold safeState. intros.\n    step_tac. dup_fetch_instr_elim.\n    unfold nacljmp_mask_instr in H0.\n    assert (same_seg_regs (RTL_step_list (instr_to_rtl pre2 ins2))).\n      eauto using nacljmp_snd_same_seg_regs.\n    same_seg_regs_rel_tac.\n  Qed.\n\n  (* todo: a tactic for unfolding nacljmp_mask_instr *)\n  Lemma nacljmp_snd_aoss : forall pre1 ins1 pre2 ins2,\n    nacljmp_mask_instr pre1 ins1 pre2 ins2 = true\n      -> agree_outside_seg SS (RTL_step_list (instr_to_rtl pre2 ins2)).\n  Proof. unfold nacljmp_mask_instr; intros.\n      destruct ins1; bool_elim_tac; try discriminate H0.\n      destruct_head in H0; try discriminate.\n      destruct op1; try discriminate.\n      destruct op2; try discriminate.\n      bool_elim_tac.\n      destruct ins2; try discriminate.\n      unfold instr_to_rtl, check_prefix. prove_instr.\n      unfold instr_to_rtl, check_prefix. prove_instr.\n  Qed.\n\n  (* todo : maybe use a step lemma to parametrize over the property of ins2 *)\n  Lemma nacljmp_snd_step_aoss : forall s s' code pre1 ins1 pre2 ins2 len2,\n    fetch_instruction (PC s) s = (Okay_ans (pre2, ins2, len2), s)\n      -> nacljmp_mask_instr pre1 ins1 pre2 ins2 = true\n      -> codeLoaded code s\n      -> checkSegments s = true\n      -> s ==> s'\n      -> agree_outside_addr_region (segAddrs SS s) s s'.\n  Proof. intros.\n    step_tac. dup_fetch_instr_elim.\n    assert (H20: agree_outside_seg SS (RTL_step_list (instr_to_rtl pre2 ins2))).\n      eauto using nacljmp_snd_aoss.\n    destruct (lock_rep pre2); [idtac | aoar_tac].\n      destruct l; [aoar_tac | idtac | aoar_tac].\n        assert (H32: agree_outside_seg SS \n                   (run_rep pre2 ins2 (add (PC s0) (repr (Zpos len2))))).\n          apply same_mem_agree_outside_seg.\n          eapply run_rep_same_mem_nacljmp_snd; eassumption.\n          eapply run_rep_same_seg_regs.\n          eauto using nacljmp_snd_same_seg_regs.\n        eapply H32; eassumption.\n  Qed.\n\n  Lemma conv_JMP_absolute_reg_PC : forall pre reg cs r cs' s v' s',\n    conv_JMP pre true true (Reg_op reg) None cs = (r, cs') \n      -> (forall s1 s2, \n           RTL_step_list (List.rev (c_rev_i cs)) s1 = (Okay_ans tt, s2)\n             -> get_location (reg_loc reg) (rtl_mach_state s1)\n                = get_location (reg_loc reg) (rtl_mach_state s2))\n      -> RTL_step_list (List.rev (c_rev_i cs')) s = (Okay_ans v', s')\n      -> (PC s') = (get_location (reg_loc reg) (rtl_mach_state s)).\n  Proof. intros.\n    unfold conv_JMP in H. \n    simpl in H. inv H.\n    simpl in H1.\n    autorewrite with step_list_db in H1.\n    repeat rtl_okay_elim. removeUnit.\n    inv H2.\n    rewrite zero_add.\n    apply eq_sym.\n    crush.\n  Qed.\n\n  Lemma conv_JMP_absolute_reg_step_PC : forall s s' pre r len,\n    fetch_instruction (PC s) s = \n      (Okay_ans (pre, (JMP true true (Reg_op r) None), len), s)\n      -> no_prefix pre = true\n      -> s ==> s'\n      -> checkSegments s = true\n      -> (PC s') = (get_location (reg_loc r) (rtl_mach_state s)).\n  Proof. intros.\n    step_tac. dup_fetch_instr_elim.\n    unfold no_prefix, filter_prefix, ft_no_lock_or_rep, ft_bool_no in *.\n    bool_elim_tac.\n    destruct (lock_rep pre); try congruence.\n    rtl_okay_elim.\n    unfold instr_to_rtl, runConv in H1.\n    remember_rev \n       (Bind unit (check_prefix pre)\n              (fun _ : unit => conv_JMP pre true true (Reg_op r) None)\n              {| c_rev_i := nil |}) as cv.\n    destruct cv.\n    unfold check_prefix in Hcv.\n    destruct (addr_override pre); try congruence.\n    conv_elim.\n    assert (H10: gp_regs (get_core_state s) = gp_regs (get_core_state s0)).\n      unfold set_loc in *. crush.\n    unfold get_location.\n    rewrite <- H10.\n    eapply conv_JMP_absolute_reg_PC; try eassumption.\n      intros. extended_rtl_okay_elim. crush.\n  Qed.\n\n  Opaque set_mem_n. (* without this, the QED would take forever *)\n  Lemma conv_CALL_absolute_reg_step_PC : forall s s' pre r len,\n    fetch_instruction (PC s) s = \n      (Okay_ans (pre, (CALL true true (Reg_op r) None), len), s)\n      -> ESP <> r\n      -> no_prefix pre = true\n      -> s ==> s'\n      -> checkSegments s = true\n      -> (PC s') = (get_location (reg_loc r) (rtl_mach_state s)).\n  Proof. intros.\n    step_tac. dup_fetch_instr_elim.\n    unfold no_prefix, filter_prefix, ft_no_lock_or_rep, ft_bool_no in *.\n    bool_elim_tac.\n    destruct (lock_rep pre); try congruence.\n    rtl_okay_break.\n    unfold instr_to_rtl, runConv in H2.\n    remember_rev \n       (Bind unit (check_prefix pre)\n              (fun _ : unit => conv_CALL pre true true (Reg_op r) None)\n              {| c_rev_i := nil |}) as cv.\n    destruct cv.\n    unfold conv_CALL, check_prefix in Hcv.\n    destruct (addr_override pre); try congruence.\n    repeat conv_elim.\n    removeUnit.\n    assert (H20:gp_regs (get_core_state s) = gp_regs (get_core_state s0)).\n      unfold set_loc in *. crush.\n    unfold get_location.\n    rewrite <- H20.\n    eapply conv_JMP_absolute_reg_PC; try eassumption.\n      intros.\n      conv_backward_roll.\n      conv_backward_roll. simpl in *.\n      unfold look, upd.\n      destruct (register_eq_dec ESP r).\n        contradict e; assumption.\n        unfold set_mem32 in *.\n        assert (same_mach_state (RTL_step_list (rev (c_rev_i cs4)))).\n          do 5 conv_backward_sms. extended_rtl_okay_elim. crush.\n        crush.\n  Qed.\n  Transparent set_mem_n.\n\n  Lemma nacljmp_step_safePC : forall s s' s'' pre1 ins1 len1 pre2 ins2 len2 inv,\n    fetch_instruction (PC s) s = (Okay_ans (pre1, ins1, len1), s)\n      -> fetch_instruction (PC s +32_p len1) s' = (Okay_ans (pre2, ins2, len2), s')\n      -> nacljmp_mask_instr pre1 ins1 pre2 ins2 = true \n      -> safeState s inv\n      -> s ==> s'\n      -> s'==> s''\n      -> aligned (PC s'').\n  Proof. intros.\n    dupHyp H1; unfold nacljmp_mask_instr in H1.\n    dupHyp H2; safestate_unfold_tac.  break_hyp.\n    destruct ins1; bool_elim_tac; try congruence.\n    destruct w; try congruence.\n    destruct op1; try congruence.\n    destruct op2; try congruence.\n    bool_elim_tac.\n    assert (aligned (get_location (reg_loc r) (rtl_mach_state s'))).\n      clear H14 H0 H4.\n      step_tac. dup_fetch_instr_elim.\n      rewrite no_prefix_no_lock_rep in H3 by assumption.\n      repeat rtl_okay_elim.\n      unfold instr_to_rtl, check_prefix in H3.\n      dupHyp H1. \n      unfold no_prefix, filter_prefix, ft_bool_no in H1. bool_elim_tac.\n      destruct (addr_override pre1); try congruence.\n      simpl in H3.\n      compute [runConv] in H3. simpl in H3.\n      remember_destruct_head in H3 as ca.\n      eapply nacljmp_mask_reg_aligned; try eassumption.\n        destruct (zeq (signed i) (signed safeMask)). congruence.\n          discriminate H12.\n    assert (H20: PC s' = PC s +32_p len1).\n      eapply nacljmp_mask_PC. \n        eapply H. eassumption. eassumption. eassumption.\n    rewrite <- H20 in *.\n    assert (non_cflow_instr pre1 (AND true (Reg_op r) (Imm_op i)) = true).\n      eapply nacljmp_first_non_cflow_instr; eassumption.\n    assert (H22: checkSegments s' = true).\n      eapply nci_checkSegments_inv. eapply H. assumption.\n        eassumption. assumption.\n    destruct ins2; bool_elim_tac; try congruence.\n    Case \"CALL\".\n      destruct (register_eq_dec r ESP); try congruence.\n      destruct near; try congruence.\n      destruct absolute; try congruence.\n      destruct op1; try congruence.\n      destruct sel; try congruence.\n      clear H.\n      assert (r = r0).\n        destruct_head in H14; congruence.\n      subst r0.\n      assert (H30: PC s'' = get_location (reg_loc r) (rtl_mach_state s')).\n        eapply conv_CALL_absolute_reg_step_PC.\n          eassumption. congruence. assumption. assumption. \n          assumption.\n      rewrite H30. assumption.\n    Case \"JMP\".\n      destruct near; try congruence.\n      destruct absolute; try congruence.\n      destruct op1; try congruence.\n      destruct sel; try congruence.\n      clear H.\n      assert (r = r0).\n        destruct_head in H14; congruence.\n      subst r0.\n      assert (H30: PC s'' = get_location (reg_loc r) (rtl_mach_state s')).\n        eapply conv_JMP_absolute_reg_step_PC.\n          eassumption. congruence. assumption. assumption. \n      rewrite H30. assumption.\n  Qed.\n\n  Lemma nacljmp_safeInSomeK : forall s code pre1 ins1 len1 pre2 ins2 len2,\n    fetch_instruction (PC s) s = (Okay_ans (pre1, ins1, len1), s)\n      -> fetch_instruction (PC s +32_p len1) s = (Okay_ans (pre2, ins2, len2), s)\n      -> nacljmp_mask_instr pre1 ins1 pre2 ins2 = true \n      -> safeState s code\n      -> safeInSomeK s code.\n  Proof. unfold safeInSomeK. intros. \n    dupHyp H2. safestate_unfold_tac.\n    exists 2%nat.\n    assert (non_cflow_instr pre1 ins1 = true).\n      eapply nacljmp_first_non_cflow_instr; eassumption.\n    unfold safeInK.\n      split. unfold safeState in H2. crush.\n      split. eapply nci_nextStepNoFail. eapply H. assumption. assumption.\n      intros. right.\n        assert (Same_Seg_Regs_Rel.brel s s').\n          eapply nci_step_same_seg_regs. eapply H. assumption.\n          eassumption. assumption.\n        assert (eqCodeRegion s s').\n          eapply nci_step_eqCodeRegion. \n            eapply H. assumption. eassumption. assumption.\n        assert (PC s' = PC s +32_p len1).\n          eapply nacljmp_mask_PC. \n            eapply H. eassumption. eassumption. assumption.\n        assert (fetch_instruction (PC s') s' = (Okay_ans (pre2, ins2, len2), s')).\n          rewrite H13.\n          eapply fetch_instr_code_inv. eassumption. eassumption.\n        assert (codeLoaded code s').\n          eapply codeLoaded_inv; eassumption.\n        assert (checkSegments s' = true).\n          eapply nci_checkSegments_inv. eapply H. assumption.\n            eassumption. assumption.\n        split. \n          eapply nci_appropState. eapply H. assumption. assumption. assumption.\n        split.\n          eapply nacljmp_snd_nextStepNoFail; eassumption.\n          intro s''. intros. left.\n            use_lemma nacljmp_snd_step_same_seg_regs by eassumption.\n            assert (H20: CLimit s = CLimit s'').\n              unfold Same_Seg_Regs_Rel.brel in *.\n              break_hyp. crush.\n            assert (eqCodeRegion s' s'').\n              eapply eqCodeRegion_intro; try eassumption.\n              right; left. \n                eapply nacljmp_snd_step_aoss; eassumption.\n            use_lemma codeLoaded_inv by eassumption.\n            use_lemma checkSegments_inv by eassumption.\n            assert (appropState s'' ((sregs_st, sregs_lm), code)).\n              unfold appropState. unfold Same_Seg_Regs_Rel.brel in *.\n              crush.\n            split. assumption.\n            split. trivial.\n              assert (aligned (PC s'')).\n                eapply nacljmp_step_safePC. eapply H. \n                  rewrite <- H13. eapply H14.\n                  assumption. eassumption. assumption. assumption.\n              unfold inBoundCodeAddr.\n              rewrite <- H20.\n              change code with (snd ((sregs_st, sregs_lm), code)).\n              eapply aligned_addr_safePC. assumption. assumption.\n  Qed.                  \n\n\n  (** *** The interface theorem between the verifier correctness proof and the\n     proofs about the parser *)\n\n  Lemma eqMemBuffer_succ : forall b buffer s lc,\n    eqMemBuffer (b::buffer) s lc -> eqMemBuffer buffer s (lc +32_z 1).\n  Proof. unfold eqMemBuffer. intros.\n    break_hyp.\n    simpl in H.\n    split. int32_prover.\n    intros.\n      assert (S i < length (b::buffer))%nat.\n        simpl. omega.\n      use_lemma (H0 (S i)) by eassumption.\n      rewrite cons_nth in H3 by omega.\n      assert (S i - 1 = i)%nat by omega.\n      assert (lc +32_n S i = lc +32_p 1 +32_n i).\n        unfold w32add. rewrite add_assoc. rewrite add_repr.\n        cut (Z_of_nat (S i) = 1 + Z_of_nat i).  crush.\n        nat_to_Z_tac. omega.\n      crush.\n  Qed.\n\n  Lemma simple_parse_aux_corr_parse_instr_aux : \n   forall bytes ps pre ins len bytes1 s lc k consumed_len,\n    simple_parse' ps bytes = Some ((pre,ins), bytes1)\n      -> len = (length bytes - length bytes1)%nat\n      -> eqMemBuffer (firstn len bytes) s lc\n      -> (k >= len)%nat\n      -> exists pos,\n           parse_instr_aux k lc consumed_len ps s = (Okay_ans (pre, ins, pos), s) /\\\n           Zpos pos + 1 = Zpos consumed_len + Z_of_nat len.\n  Proof. induction bytes as [ | b bytes']; intros.\n    Case \"nil\". crush.\n    Case \"bytes = b::bytes'\".\n      use_lemma simple_parse'_len_pos by eassumption.\n      assert (len <= length (b::bytes'))%nat by omega.\n      assert (len > 0)%nat as H8 by omega.\n      destruct len as [ | len]; [contradict H8; omega | idtac].\n      compute [simple_parse'] in H. fold simple_parse' in H.\n      remember_destruct_head in H as pb.\n      destruct k; [contradict H2; omega | idtac].\n      dupHyp H1; unfold eqMemBuffer in H1.\n      destruct H1 as [H10 H12].\n      simpl firstn in H12.\n      assert (H20:b = AddrMap.get lc (rtl_memory s)).\n        apply eq_trans with (y:= nth 0 (b::bytes') Word.zero).\n          trivial.\n          generalize (H12 O). simpl. intro H14.\n            unfold w32add in H14.\n            rewrite add_zero in H14.\n          apply H14. omega.\n      destruct l.\n      SCase \"parse_byte returns nil\".\n        assert (len = length bytes' - length bytes1)%nat.\n          simpl length in H0. omega.\n        assert (len <= length bytes')%nat by omega.\n        assert (eqMemBuffer (firstn len bytes') s (lc +32_p 1)).\n          eapply eqMemBuffer_succ; eassumption.\n        assert (k >= len)%nat by omega.\n        use_lemma IHbytes' by eassumption.\n        destruct H11 as [pos [H30 H32]].\n        exists pos.\n        split.\n          compute [parse_instr_aux]. fold parse_instr_aux.\n          rtl_okay_intro.\n          rewrite <- H20. rewrite Hpb.\n          eassumption.\n        rewrite Zpos_plus_distr in H32.\n        rewrite inj_S. omega.\n      SCase \"parse_byte returns some v\".\n        exists consumed_len.\n        split.\n          SSCase \"subgoal 1\".\n          compute [parse_instr_aux]. fold parse_instr_aux.\n          rtl_okay_intro.\n          rewrite <- H20. rewrite Hpb. crush.\n          SSCase \"subgoal 2\".\n          inv H.\n          assert (len = 0)%nat. \n            simpl length in H0. omega.\n          rewrite H. nat_to_Z_tac. omega.\n  Qed.\n\n  Lemma simple_parse_corr_parse_instr : \n   forall bytes pre ins len bytes1 s pc,\n    simple_parse bytes = Some ((pre,ins), bytes1)\n      -> len = (length bytes - length bytes1)%nat\n      -> eqMemBuffer (firstn len bytes) s (CStart s +32 pc)\n      -> (15 >= len)%nat\n      -> exists pos,\n           parse_instr pc s = (Okay_ans (pre, ins, pos), s) /\\\n           Zpos pos = Z_of_nat len.\n  Proof. unfold simple_parse. intros.\n    use_lemma simple_parse_aux_corr_parse_instr_aux by eassumption.\n    destruct H3 as [pos [H10 H12]].\n    exists pos. split.\n      unfold parse_instr, parse_instr'. \n      rtl_okay_intro. eassumption. omega.\n  Qed.\n\n  Lemma eqMemBuffer_skipn : forall n ls s lc,\n    eqMemBuffer ls s lc -> eqMemBuffer (skipn n ls) s (lc +32_n n).\n  Proof. unfold eqMemBuffer. intros. break_hyp.\n    split.\n      eapply Zle_trans. eapply inj_le. eapply skipn_length_leq. assumption.\n      intros.\n        destruct (le_or_lt (length ls) n).\n        Case \"length ls <= n\".\n          assert (n >= length ls)%nat by omega.\n          apply skipn_nil in H3. \n          rewrite H3 in H1. simpl in H1. contradict H1. omega.\n        Case \"n < lenth ls\".\n          assert (length (skipn n ls) + n = length ls)%nat.\n             eapply skipn_length. omega.\n          assert (i + n < length ls)%nat by omega.\n          eapply H0 in H4.\n          rewrite skipn_nth. \n          assert (lc +32_n (i+n) = lc +32_n n +32_n i).\n            unfold w32add. rewrite add_assoc. rewrite add_repr.\n            rewrite inj_plus. rewrite Zplus_comm. trivial.\n          crush.\n  Qed.\n\n  Lemma eqMemBuffer_firstn : forall n ls s lc,\n    eqMemBuffer ls s lc -> eqMemBuffer (firstn n ls) s lc.\n  Proof. unfold eqMemBuffer. intros. break_hyp.\n    assert (length (firstn n ls) <= length ls)%nat.\n      rewrite firstn_length. apply Min.le_min_r.\n    split. omega.\n      intros.\n        assert (i<n)%nat. rewrite firstn_length in H2.\n          eapply lt_le_trans. eassumption. \n          eapply Min.le_min_l.\n        rewrite nth_firstn by assumption.\n        eapply H0.  omega.\n  Qed.\n\n  Lemma simple_parse_parseloop_same : forall bytes ps,\n    simple_parse' ps bytes = parseloop ps bytes.\n  Proof. induction bytes; crush. Qed.\n\n  Lemma token2byte_inv_byte2token : forall b,\n    token2byte (byte2token b) = b.\n  Proof. unfold token2byte, byte2token. intros.\n    rewrite inj_Zabs_nat. rewrite Zabs_eq. rewrite repr_unsigned. trivial.\n    generalize (unsigned_range b). crush.\n  Qed.\n\n  Lemma list_map_token_byte : forall bytes,\n    List.map (fun x  => token2byte (byte2token x)) bytes\n      = bytes.\n  Proof. induction bytes. crush.\n    simpl. rewrite token2byte_inv_byte2token. crush.\n  Qed.\n\n  Lemma parse_instr_imp_fetch_instr : \n    forall pc pre ins pos s,\n      parse_instr pc s = (Okay_ans (pre, ins, pos), s)\n        -> unsigned pc + Zpos pos <= unsigned (CLimit s) + 1\n        -> fetch_instruction pc s = (Okay_ans (pre, ins, pos), s).\n  Proof. intros.\n    int32_simplify.\n    assert (noOverflow (pc :: (repr (Zpos pos - 1)) :: nil)).\n      int32_simplify. omega.\n    assert (pc <=32 (pc +32_z (Zpos pos - 1))).\n      apply checkNoOverflow_equiv_noOverflow. assumption.\n    assert (pc +32_z (Zpos pos - 1) <=32 (CLimit s)).\n      int32_simplify. omega.\n    unfold fetch_instruction. \n    eapply rtl_bind_okay_intro; [eassumption | idtac].\n    remember_destruct_head as pl. inversion Hpl. subst p0 p.\n    rtl_okay_intro. crush.\n  Qed.\n\n  Remark aligned_bool_proper:\n   Morphisms.Proper\n     (Morphisms.respectful (fun x y : Int32_OT.t => eq x y = true) Logic.eq)\n     aligned_bool.\n  Proof. unfold Morphisms.Proper, Morphisms.respectful.\n    intros. apply int_eq_true_iff2 in H. crush.\n  Qed.\n\n  (** The correctness proof is parametrized over the hypotheses about the\n     sucess of building of the three DFAs and the parser. They can be\n     easily discharged by performing evaluation in Coq. However, it would\n     take a long time. We actually extract ML code to do the evaluation.\n  *)\n  Hypothesis non_cflow_dfa_built:\n    abstract_make_recognizer _ non_cflow_grammar = non_cflow_dfa.\n\n  Hypothesis dir_cflow_dfa_built:\n    abstract_make_recognizer _ (alts dir_cflow) = dir_cflow_dfa.\n\n  Hypothesis nacljmp_dfa_built:\n    abstract_make_recognizer _ (alts nacljmp_mask) = nacljmp_dfa.\n\n  Hypothesis initial_state_built:\n    abs_ini_decoder_state =initial_state.\n\n  (* Including the above hypotheses in the context will make some tactics *)\n  (*    such as discriminate extremely slow since they will try to evaluate *)\n  (*    terms such as opt_dir_cflow_dfa, which are huge terms.*)\n  Ltac clean :=\n    clear non_cflow_dfa_built; clear dir_cflow_dfa_built; clear nacljmp_dfa_built;\n    clear initial_state_built.\n\n  Lemma goodJmp_lemma : forall pc len bytes jmpTargets startAddrs pre ins rem,\n    dir_cflow_instr pre ins = true\n      -> simple_parse bytes = Some (pre, ins, rem)\n      -> len = (length bytes - length rem)%nat\n      -> includeAllJmpTargets pc len (List.map byte2token bytes) jmpTargets\n      -> checkJmpTargets jmpTargets startAddrs = true\n      -> goodJmp ins (pc +32_n len) startAddrs = true.\n  Proof. intros.\n    assert (firstn len bytes = firstn len (firstn len bytes)).\n      rewrite firstn_twice_eq by omega. trivial.\n    unfold simple_parse in *.\n    (* remember_destruct_head in H0 as ds; try congruence. *)\n    use_lemma simple_parse'_ext by eassumption.\n    destruct H5 as [rem1 H10].\n    rewrite simple_parse_parseloop_same in H10.\n    rewrite <- (list_map_token_byte bytes) in H10.\n    rewrite <- list_map_compose in H10.\n    rewrite firstn_map in H10.\n    unfold goodJmp, checkJmpTargets in *.\n    assert (abs_ini_decoder_state=initial_state) by congruence.\n    destruct ins; simpl in H; try congruence.\n    Case \"CALL\".\n      destruct near; try congruence.\n      destruct absolute; try congruence.\n      destruct op1; try congruence.\n      destruct sel; try congruence.\n      unfold includeAllJmpTargets in H2.\n      subst initial_state.\n      rewrite H10 in H2.\n      unfold goodJmpTarget.\n      remember_rev (Int32Set.mem (pc +32_n len +32 i) startAddrs) as ab.\n      destruct ab. crush.\n        apply orb_true_intro. right.\n        assert (Int32Set.In (pc +32_n len +32 i)\n                  (Int32Set.diff jmpTargets startAddrs)).\n          apply Int32Set.diff_spec. split. assumption.\n          apply Int32SetFacts.not_mem_iff. assumption.\n        apply Int32Set.for_all_spec in H3. auto. apply aligned_bool_proper.\n    Case \"Jcc\".\n      unfold includeAllJmpTargets in H2.\n      subst initial_state.\n      rewrite H10 in H2.\n      unfold goodJmpTarget.\n      remember_rev (Int32Set.mem (pc +32_n len +32 disp) startAddrs) as ab.\n      destruct ab. crush.\n        apply orb_true_intro. right.\n        assert (Int32Set.In (pc +32_n len +32 disp)\n                  (Int32Set.diff jmpTargets startAddrs)).\n          apply Int32Set.diff_spec. split. assumption.\n          apply Int32SetFacts.not_mem_iff. assumption.\n        apply Int32Set.for_all_spec in H3. auto. apply aligned_bool_proper.\n    Case \"Jmp\".\n      destruct near; try congruence.\n      destruct absolute; try congruence.\n      destruct op1; try congruence.\n      destruct sel; try congruence.\n      unfold includeAllJmpTargets in H2.\n      subst initial_state.\n      rewrite H10 in H2.\n      unfold goodJmpTarget.\n      remember_rev (Int32Set.mem (pc +32_n len +32 i) startAddrs) as ab.\n      destruct ab. crush.\n        apply orb_true_intro. right.\n        assert (Int32Set.In (pc +32_n len +32 i)\n                  (Int32Set.diff jmpTargets startAddrs)).\n          apply Int32Set.diff_spec. split. assumption.\n          apply Int32SetFacts.not_mem_iff. assumption.\n        apply Int32Set.for_all_spec in H3. auto. apply aligned_bool_proper.\n  Qed.\n\n  (* The three cases when the current state is a safe state *)\n  (* The proof theorem needs the interface lemmas from the parser;\n     will prove this theorem when the lemmmas become stable *)\n  Theorem safeState_next_instr : forall s code startAddrs,\n    codeLoaded code s\n      -> checkProgram code = (true, startAddrs)\n      -> Int32Set.In (PC s) startAddrs\n      -> (exists pre, exists ins, exists len, \n           fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n           /\\ non_cflow_instr pre ins = true\n           /\\ goodDefaultPC ((PC s) +32_p len) startAddrs (length code))\n         \\/\n         (exists pre, exists ins, exists len, \n           fetch_instruction (PC s) s = (Okay_ans (pre, ins, len), s)\n           /\\ dir_cflow_instr pre ins = true\n           /\\ goodDefaultPC ((PC s) +32_p len) startAddrs (length code)\n           /\\ goodJmp ins ((PC s) +32_p len) startAddrs = true)\n         \\/ \n         (exists pre1, exists ins1, exists len1, \n          exists pre2, exists ins2, exists len2,\n          fetch_instruction (PC s) s = (Okay_ans (pre1, ins1, len1), s) /\\\n          fetch_instruction (PC s +32_p len1) s = (Okay_ans (pre2, ins2, len2), s) /\\\n          nacljmp_mask_instr pre1 ins1 pre2 ins2 = true).\n  Proof. unfold checkProgram, FastVerifier.checkProgram; intros.\n    remember_destruct_head in H0 as pb; try congruence.\n    destruct p as [startAddrs' checkAddrs].\n    assert (startAddrs = startAddrs') by congruence.\n    subst startAddrs'. \n    use_lemma codeLoaded_length by eassumption.\n    use_lemma process_buffer_inversion by eassumption.\n    destruct H3 as [tokens [len [remaining [H20 [H22 H24]]]]].\n    rewrite <- skipn_map in H20.\n    remember (skipn (nat_of_int32 (PC s)) code) as code'.\n    assert (PC s = repr (Z_of_nat (Zabs_nat (unsigned (PC s))))).\n      rewrite inj_Zabs_nat. \n      generalize (unsigned_range (PC s)). intros.\n      rewrite Zabs_eq by omega.\n      rewrite repr_unsigned. trivial.\n    assert (eqMemBuffer (firstn len code') s (CStart s +32 (PC s))).\n      eapply eqMemBuffer_firstn. \n      subst code'. rewrite H3 at 2.\n      apply eqMemBuffer_skipn. unfold codeLoaded in *. \n      break_hyp. assumption.\n    use_lemma process_buffer_addrRange by eassumption.\n    assert ((nat_of_int32 (PC s)) + length tokens = length code)%nat.\n      rewrite H20. rewrite list_length_map. rewrite plus_comm.\n      apply skipn_length. apply inj_lt_rev. clean. int32_prover.\n    destruct H24 as [H24 | [H24 | H24]].\n    Case \"non_cflow_dfa matches\". left. \n      use_lemma non_cflow_dfa_corr by (subst tokens; eassumption).\n      destruct H7 as [insBytes [pre [ins [H30 [H32 [H34 H36]]]]]].\n      assert (len = length code' - length (List.map nat_to_byte remaining))%nat.\n        apply plus_minus.  subst code'.\n        rewrite H34. rewrite plus_comm.\n        rewrite <- app_length. rewrite <- H36. trivial.\n      assert (len <= 15)%nat. \n        eapply non_cflow_dfa_length. apply non_cflow_dfa_built.\n          subst tokens. eassumption.\n      subst code'.\n      use_lemma simple_parse_corr_parse_instr by eassumption.\n      destruct H9 as [pos [H40 H42]].\n      assert (unsigned (PC s) + Zpos pos <= unsigned (CLimit s) + 1).\n        use_lemma dfa_recognize_inv by eassumption. break_hyp.\n        unfold codeLoaded in *. break_hyp. clean.\n        int32_simplify. omega.\n      use_lemma parse_instr_imp_fetch_instr by eassumption.\n      exists pre. exists ins. exists pos.\n      split. assumption.\n      split. assumption. \n        rewrite H42. assumption.\n    Case \"dir_cflow_dfa matches\". right; left.\n      break_hyp.\n      use_lemma dir_cflow_dfa_corr by (subst tokens; eassumption).\n      destruct H10 as [insBytes [pre [ins [H30 [H32 [H34 H36]]]]]].\n      assert (len = length code' - length (List.map nat_to_byte remaining))%nat.\n        apply plus_minus.  subst code'.\n        rewrite H34. rewrite plus_comm.\n        rewrite <- app_length. rewrite <- H36. trivial.\n      assert (len <= 15)%nat. \n        eapply dir_cflow_dfa_length. apply dir_cflow_dfa_built.\n          subst tokens. eassumption.\n      subst code'.\n      use_lemma simple_parse_corr_parse_instr by eassumption.\n      destruct H12 as [pos [H40 H42]].\n      assert (unsigned (PC s) + Zpos pos <= unsigned (CLimit s) + 1).\n        use_lemma dfa_recognize_inv by eassumption. break_hyp.\n        unfold codeLoaded in *. break_hyp.\n        clean. int32_simplify. omega.\n      use_lemma parse_instr_imp_fetch_instr by eassumption.\n      exists pre. exists ins. exists pos.\n      split. assumption.\n      split. assumption.  \n      split. rewrite H42. assumption.\n        injection H0. intros. bool_elim_tac.\n        subst tokens.\n        rewrite H42.\n        eapply goodJmp_lemma; eassumption.\n    Case \"nacljmp_dfa matches\". right; right.\n      break_hyp.\n      use_lemma nacljmp_dfa_corr by (subst tokens; eassumption).\n      destruct H8 as \n        [bytes1 [pre1 [ins1 [bytes [pre2 [ins2 [H30 [H32 [H34 [H36 H38]]]]]]]]]].\n      rewrite app_length in H36.\n      assert (len <= 15)%nat.\n        eapply nacljmp_mask_dfa_length. eassumption.\n          subst tokens. eassumption.\n      assert (length bytes1 = \n                (length code' - length (bytes ++ List.map nat_to_byte remaining)))%nat.\n        subst code'. apply plus_minus. rewrite plus_comm.\n        rewrite <- app_length. rewrite <- H38. trivial.\n      assert (eqMemBuffer (firstn (length bytes1) code') s (CStart s +32 (PC s))).\n        rewrite <- firstn_twice_eq with (m:=len) by omega.\n        apply eqMemBuffer_firstn. assumption.\n      assert (15 >= length (bytes1))%nat by omega.\n      generalize H32; clear H32. (* hide H32 for now *)\n      use_lemma simple_parse_corr_parse_instr by (subst code'; eassumption).\n      destruct H12 as [pos1 [H40 H42]].\n\n      assert (unsigned (PC s) + Zpos pos1 <= unsigned (CLimit s) + 1).\n        use_lemma dfa_recognize_inv by eassumption. break_hyp.\n        unfold codeLoaded in *. break_hyp. clean.\n        int32_simplify. omega.\n      use_lemma parse_instr_imp_fetch_instr by eassumption.\n\n      intro H32. clear H30.\n      assert (length bytes = \n                (length (bytes ++ List.map nat_to_byte remaining) - \n                 length (List.map nat_to_byte remaining)))%nat.\n        apply plus_minus. rewrite plus_comm.\n        rewrite <- app_length. trivial.\n      assert (eqMemBuffer \n                (firstn (length bytes) (bytes ++ List.map nat_to_byte remaining))\n                s (CStart s +32 (PC s) +32_n (length bytes1))).\n        rewrite firstn_list_app by trivial.\n        assert (bytes = skipn (length bytes1) (bytes1 ++ bytes)).\n          rewrite skipn_list_app by trivial. trivial.\n        rewrite H15 at 1.\n        apply eqMemBuffer_skipn. \n        assert (firstn len code' = bytes1 ++ bytes)%list.\n          subst code'.\n          rewrite <- firstn_list_app with (n:=len) \n            (l2:= List.map nat_to_byte remaining).\n          rewrite <- app_assoc. rewrite <- H38. trivial.\n          rewrite app_length. omega.\n        rewrite <- H16. assumption.\n      unfold w32add in H15.\n      rewrite add_assoc in H15.\n      assert (15 >= length (bytes))%nat by omega.\n      use_lemma simple_parse_corr_parse_instr by (subst code'; eassumption).\n      destruct H17 as [pos2 [H50 H52]].\n\n      use_lemma dfa_recognize_inv by eassumption. break_hyp.\n      unfold codeLoaded in *. break_hyp.\n      generalize (Zgt_pos_0 pos1) (Zgt_pos_0 pos2). intros.\n      assert (Z_of_nat (length bytes1) < w32modulus). \n        clean. int32_simplify. omega.\n      assert (noOverflow (PC s :: int32_of_nat (length bytes1) :: nil)).\n        clean. int32_simplify.  omega.\n      assert (unsigned (PC s +32 (int32_of_nat (length bytes1)))\n                + Zpos pos2 <= unsigned (CLimit s) + 1).\n        clean. int32_simplify. omega.\n      use_lemma parse_instr_imp_fetch_instr by eassumption.\n      exists pre1. exists ins1. exists pos1. \n      exists pre2. exists ins2. exists pos2.\n      split. assumption. \n      split. rewrite H42. assumption.\n        assumption.\n  Qed.\n\n  (** *** Proving that any safeState is safe for in some k *)\n\n  Lemma pc_out_bound_safeInSomeK : forall s inv,\n    ~ inBoundCodeAddr (PC s) s -> safeState s inv -> safeInSomeK s inv.\n  Proof. unfold safeInSomeK. intros.\n    exists (S O). simpl.\n    split. \n      unfold safeState in *. destruct inv. break_hyp. assumption.\n    split.\n      unfold nextStepNoFail. intros. contradict H.\n        eapply step_fail_pc_inBound; eassumption.\n      intros. left. contradict H.\n        eapply step_immed_pc_inBound; eassumption.\n  Qed.\n\n  Lemma fetch_instruction_dichotomy : forall pc s pre ins len,\n    parse_instr pc s = (Okay_ans (pre, ins, len), s)\n      -> fetch_instruction pc s = (Okay_ans (pre, ins, len), s) \\/\n         fetch_instruction pc s = (Trap_ans, s).\n  Proof. intros.\n    remember_rev (andb (int32_lequ_bool pc (pc +32 repr (Zpos len - 1)))\n                    (int32_lequ_bool (pc +32 repr (Zpos len - 1)) (CLimit s)))\n      as rb.\n    destruct rb; unfold fetch_instruction.\n    left. \n      eapply rtl_bind_okay_intro; [eassumption | idtac].\n      remember_destruct_head as pl. inv Hpl.\n      rtl_okay_intro. rewrite Hrb. reflexivity.\n    right. \n      eapply rtl_bind_trap_intro1. eassumption.\n      remember_destruct_head as pl. inv Hpl.\n      unfold Bind at 1; unfold RTL_monad at 1.\n      rewrite in_seg_bounds_rng_equation.\n      rewrite Hrb. trivial.\n  Qed.   \n\n\n  Ltac unroll_bind := unfold Bind at 1; unfold RTL_monad at 1.\n\n(*\n  Lemma step_fetch_instr_safefail : forall s,\n    fetch_instruction (PC s) s = (SafeFail_ans _, s)\n      -> inBoundCodeAddr (PC s) s\n      -> exists s', step s = (SafeFail_ans _, s').\n  Proof. intros. unfold step.\n    unroll_bind.\n    remember_destruct_head as fe.\n    destruct r; try discriminate Hfe.\n    rename r0 into s1.\n    exists s1.\n    unroll_bind. compute [get_loc].\n    unroll_bind. rewrite in_seg_bounds_equation.\n    compute [get_location].\n    assert (int32_lequ_bool (PC s1) (CLimit s1) = true).\n      unfold flush_env in Hfe. inv Hfe.\n      simpl. unfold inBoundCodeAddr in H0. assumption.\n    rewrite H1.\n    unroll_bind.\n*)    \n\n  Lemma in_seg_bounds_rng_dichotomy : forall sreg a offset s,\n    in_seg_bounds_rng sreg a offset s = (Okay_ans true, s) \\/\n    in_seg_bounds_rng sreg a offset s = (Okay_ans false, s).\n  Proof. intros.\n    rewrite in_seg_bounds_rng_equation.\n    remember_rev (andb (int32_lequ_bool a (a +32 offset))\n                    (int32_lequ_bool (a +32 offset) (SegLimit s sreg)))\n      as rb.\n    destruct rb. left. trivial.\n      right. trivial.\n  Qed.\n\n  Lemma fetch_instruction_intro : forall pc s pre ins len,\n    parse_instr pc s = (Okay_ans (pre, ins, len), s)\n      -> in_seg_bounds_rng CS pc (repr (Zpos len - 1)) s = (Okay_ans true, s)\n      -> fetch_instruction pc s = (Okay_ans (pre, ins, len), s).\n  Proof. unfold fetch_instruction. intros.\n    eapply rtl_bind_okay_intro; [eassumption | idtac].\n    remember_destruct_head as pl. inv Hpl.\n    unroll_bind. rewrite H0.\n    reflexivity.\n  Qed.\n\n  Opaque Decode.parse_byte.\n  Lemma parse_instr_aux_code_inv2 : forall n pc len ps s1 s1' pi len' s2,\n    Same_Mem_Rel.brel s1 s2\n      -> parse_instr_aux n pc len ps s1 = (Okay_ans (pi, len'), s1')\n      -> parse_instr_aux n pc len ps s2 = (Okay_ans (pi, len'), s2).\n  Proof. clean. induction n; intros.\n    Case \"n=0\". discriminate.\n    Case \"S n\". simpl in H0. simpl.\n      rewrite <- H.\n      remember_destruct_head as pr.\n      destruct l. \n      SCase \"l=nil\". eauto.\n      SCase \"l<>nil\". crush.\n  Qed.\n\n  Lemma parse_instr_code_inv2 : forall pc s1 s1' pi len' s2,\n    Same_Mem_Rel.brel s1 s2\n      -> Same_Mach_State_Rel.brel s1 s2\n      -> parse_instr pc s1 = (Okay_ans (pi, len'), s1')\n      -> parse_instr pc s2 = (Okay_ans (pi, len'), s2).\n  Proof. clean. unfold parse_instr, parse_instr'. intros.\n    rtl_okay_elim.\n    rtl_okay_intro.\n    eapply parse_instr_aux_code_inv2. eassumption.\n      rewrite <- H0. eassumption.\n  Qed.\n  Transparent Decode.parse_byte.\n\n\n  (* The proof of this theorem needs to perform case analysis over\n     the current pseudo instruction *)\n  Theorem safeState_safeInK: \n    forall s inv, safeState s inv -> safeInSomeK s inv.\n  Proof. intros. dupHyp H.\n    safestate_unfold_tac.\n    remember (snd (checkProgram code)) as startAddrs.\n    destruct H2.\n    Case \"pc in startAddrs\".\n      assert (checkProgram code = (true, startAddrs)).\n        destruct (checkProgram code); crush.\n      use_lemma safeState_next_instr by eassumption.\n      destruct H7; clean.\n      SCase \"Next: non_cflow_instr\".\n        destruct H7 as [pre [ins [len [H20 [H22 H24]]]]].\n        eapply nci_safeInSomeK; eassumption.\n      destruct H7.\n      SCase \"Next: dir_cflow_instr\".\n        destruct H7 as [pre [ins [len [H20 [H22 [H24 H26]]]]]].\n          eapply dci_safeInSomeK; try eassumption. crush.\n      SCase \"Next: nacljmp\".\n        destruct H7 as [pre1 [ins1 [len1 [pre2 [ins2 [len2 [H20 [H22 H24]]]]]]]].\n            eapply nacljmp_safeInSomeK. eapply H20. eapply H22. eassumption.\n              assumption.\n    Case \"pc is out of bound\".\n      apply pc_out_bound_safeInSomeK. assumption. assumption.\n  Qed.\n\n  Lemma safeInSomeK_preservation : forall s s' inv,\n    s ==>* s' -> safeInSomeK s inv -> safeInSomeK s' inv.\n  Proof. intros s s' inv Heval. induction Heval as [s s'| | s s1 s']; intros.\n    Case \"s ==> s'\". unfold safeInSomeK in H0. destruct H0 as [k H0].\n      use_lemma safeInK_step_dichotomy by eassumption.\n      destruct H1. apply safeState_safeInK; assumption. assumption.\n    Case \"s' = s\". assumption.\n    Case \"s ==>* s1 ==>* s'\". tauto.\n  Qed.\n\n  Theorem safeState_no_fail : forall s s' inv,\n    safeState s inv -> s ==>* s' -> nextStepNoFail s'.\n  Proof. intros. eapply safeInSomeK_no_fail.\n    eapply safeInSomeK_preservation. eassumption.\n     apply safeState_safeInK in H; eassumption.\n  Qed.\n\n\n  Theorem safeState_appropState : forall s s' inv,\n    safeState s inv -> s ==>* s' -> appropState s' inv.\n  Proof. intros.\n    use_lemma safeState_safeInK by eassumption.\n    use_lemma safeInSomeK_preservation by eassumption.\n    unfold safeInSomeK in H2.\n    destruct H2 as [k H10]. \n    destruct k. simpl in H10. contradict H10.\n      simpl in H10. crush.\n  Qed.\n\nEnd VERIFIER_CORR.\n", "meta": {"author": "gangtan", "repo": "CPUmodels", "sha": "a6decc3085e1f8d8d4875e67f9ad9c7663910f8a", "save_path": "github-repos/coq/gangtan-CPUmodels", "path": "github-repos/coq/gangtan-CPUmodels/CPUmodels-a6decc3085e1f8d8d4875e67f9ad9c7663910f8a/x86model/RockSalt/VerifierCorrectness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980404, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.2180217149762239}}
{"text": "Require Import VST.floyd.base.\nRequire Import VST.floyd.val_lemmas.\nRequire Import VST.floyd.typecheck_lemmas.\nRequire Import compcert.cfrontend.Ctypes.\n\nDefinition const_only_isUnOpResultType {CS: compspecs} op (typeof_a:type) valueof_a ty : bool :=\nmatch op with\n  | Cop.Onotbool => match typeof_a with\n                    | Tint _ _ _\n                    | Tlong _ _\n                    | Tfloat _ _ => is_int_type ty\n                    | Tpointer _ _ =>\n                        if Archi.ptr64 \n                        then match valueof_a with\n                             | Vlong v =>\n                                andb (negb (eqb_type (typeof_a) int_or_ptr_type))\n                                     (andb (is_int_type ty) (Z.eqb 0 (Int64.unsigned v)))\n                             | _ => false\n                             end\n                        else match valueof_a with\n                             | Vint v => \n                                andb (negb (eqb_type typeof_a int_or_ptr_type))\n                                     (andb (is_int_type ty) (Z.eqb 0 (Int.unsigned v)))\n                             | _ => false\n                             end\n                    | _ => false\n                    end\n  | Cop.Onotint => match Cop.classify_notint (typeof_a) with\n                   | Cop.notint_default => false\n                   | Cop.notint_case_i _ => (is_int32_type ty)\n                   | Cop.notint_case_l _ => (is_long_type ty)\n                   end\n  | Cop.Oneg => match Cop.classify_neg (typeof_a) with\n                    | Cop.neg_case_i sg => \n                          andb (is_int32_type ty)\n                          match (typeof_a) with\n                          | Tint _ Signed _ =>\n                            match valueof_a with\n                            | Vint v => negb (Z.eqb (Int.signed v) Int.min_signed)\n                            | _ => false\n                            end\n                          | Tlong Signed _ =>\n                            match valueof_a with\n                            | Vlong v => negb (Z.eqb (Int64.signed v) Int64.min_signed)\n                            | _ => false\n                            end\n                          | _ => true\n                          end\n                    | Cop.neg_case_f => is_float_type ty\n                    | Cop.neg_case_s => is_single_type ty\n                    | _ => false\n                    end\n  | Cop.Oabsfloat =>match Cop.classify_neg (typeof_a) with\n                    | Cop.neg_case_i sg => is_float_type ty\n                    | Cop.neg_case_l _ => is_float_type ty\n                    | Cop.neg_case_f => is_float_type ty\n                    | Cop.neg_case_s => is_float_type ty\n                    | _ => false\n                    end\nend.\n\n(* TODO: binarithType would better be bool type *)\nDefinition const_only_isBinOpResultType {CS: compspecs} op typeof_a1 valueof_a1 typeof_a2 valueof_a2 ty : bool :=\n  match op with\n  | Cop.Oadd =>\n      match Cop.classify_add (typeof_a1) (typeof_a2) with\n      | Cop.add_case_pi t _ | Cop.add_case_pl t =>\n        andb\n          (andb\n             (andb (match valueof_a1 with Vptr _ _ => true | _ => false end) (complete_type cenv_cs t))\n             (negb (eqb_type (typeof_a1) int_or_ptr_type)))\n          (is_pointer_type ty)\n    | Cop.add_case_ip _ t | Cop.add_case_lp t =>\n        andb\n          (andb\n             (andb (match valueof_a2 with Vptr _ _ => true | _ => false end) (complete_type cenv_cs t))\n             (negb (eqb_type (typeof_a2) int_or_ptr_type)))\n          (is_pointer_type ty)\n    | Cop.add_default => false\n      end\n  | _ => false (* TODO *)\n  end.\n\nDefinition const_only_isCastResultType {CS: compspecs} (t1 t2: type) (valueof_a: val)  : bool := \n  is_neutral_cast t1 t2 ||\n  match t1, t2 with\n  | Tint _ _ _, Tlong _ _ => true\n  | _, _ => false\n  end.\n\nFixpoint const_only_eval_expr {cs: compspecs} (e: Clight.expr): option val :=\n  match e with\n  | Econst_int i (Tint I32 _ _) => Some (Vint i)\n  | Econst_int _ _ => None\n  | Econst_long i ty => None\n  | Econst_float f (Tfloat F64 _) => Some (Vfloat f)\n  | Econst_float _ _ => None\n  | Econst_single f (Tfloat F32 _) => Some (Vsingle f)\n  | Econst_single _ _ => None\n  | Etempvar id ty => None\n  | Evar _ _ => None\n  | Eaddrof a ty => None\n  | Eunop op a ty =>\n      match const_only_eval_expr a with\n      | Some v => if const_only_isUnOpResultType op (typeof a) v ty\n                  then Some (eval_unop op (typeof a) v)\n                  else None\n      | None => None\n      end\n  | Ebinop op a1 a2 ty =>\n      match (const_only_eval_expr a1), (const_only_eval_expr a2) with\n      | Some v1, Some v2 =>\n          if const_only_isBinOpResultType op (typeof a1) v1 (typeof a2) v2 ty\n          then Some (eval_binop op (typeof a1) (typeof a2) v1 v2)\n          else None\n      | _, _ => None\n      end\n  | Ecast a ty =>\n      match const_only_eval_expr a with\n      | Some v => if const_only_isCastResultType (typeof a) ty v\n                  then Some (eval_cast (typeof a) ty v)\n                  else None\n      | None => None\n      end\n  | Ederef a ty => None\n  | Efield a i ty => None\n  | Esizeof t t0 =>\n    if andb (complete_type cenv_cs t) (eqb_type t0 size_t)\n    then Some (Vptrofs (Ptrofs.repr (sizeof t)))\n    else None\n  | Ealignof t t0 =>\n    if andb (complete_type cenv_cs t) (eqb_type t0 size_t)\n    then Some (Vptrofs (Ptrofs.repr (alignof t)))\n    else None\n  end.\n\nLemma const_only_isUnOpResultType_spec: forall {cs: compspecs} rho u e t P,\n  const_only_isUnOpResultType u (typeof e) (eval_expr e rho) t = true ->\n  P |-- denote_tc_assert (isUnOpResultType u e t) rho.\nProof.\n  intros.\n  unfold isUnOpResultType.\n  unfold const_only_isUnOpResultType in H.\n  destruct u.\n  + destruct (typeof e);\n      try solve [inv H | rewrite H; exact (@prop_right mpred _ True _ I)].\n    rewrite !denote_tc_assert_andp.\n    match goal with\n    | |- context [denote_tc_assert (tc_test_eq ?a ?b)] =>\n      change (denote_tc_assert (tc_test_eq a b)) with (expr2.denote_tc_assert (tc_test_eq a b))\n    end.\n    rewrite binop_lemmas2.denote_tc_assert_test_eq'.\n    simpl expr2.denote_tc_assert.\n    unfold_lift. simpl.\n    unfold tc_int_or_ptr_type.\n    destruct Archi.ptr64 eqn:HH.\n    - destruct (eval_expr e rho); try solve [inv H].\n      rewrite !andb_true_iff in H.\n      destruct H as [? [? ?]].\n      rewrite H, H0.\n      rewrite Z.eqb_eq in H1.\n      apply andp_right; [exact (@prop_right mpred _ True _ I) |].\n      apply andp_right; [exact (@prop_right mpred _ True _ I) |].\n      simpl.\n      rewrite HH.\n      change (P |-- (!! (i = Int64.zero)) && (!! (Int64.zero = Int64.zero)))%logic.\n      apply andp_right; apply prop_right; auto.\n      rewrite <- (Int64.repr_unsigned i), <- H1.\n      auto.\n    - destruct (eval_expr e rho); try solve [inv H].\n      rewrite !andb_true_iff in H.\n      destruct H as [? [? ?]].\n      rewrite H, H0.\n      rewrite Z.eqb_eq in H1.\n      apply andp_right; [exact (@prop_right mpred _ True _ I) |].\n      apply andp_right; [exact (@prop_right mpred _ True _ I) |].\n      simpl.\n      rewrite HH.\n      change (P |-- (!! (i = Int.zero)) && (!! (Int.zero = Int.zero)))%logic.\n      apply andp_right; apply prop_right; auto.\n      rewrite <- (Int.repr_unsigned i), <- H1.\n      auto.\n  + destruct (Cop.classify_notint (typeof e));\n      try solve [inv H | rewrite H; exact (@prop_right mpred _ True _ I)].\n  + destruct (Cop.classify_neg (typeof e));\n      try solve [inv H | rewrite H; exact (@prop_right mpred _ True _ I)].\n    rewrite !andb_true_iff in H.\n    destruct H.\n    rewrite H; simpl.\n    destruct (typeof e) as [| ? [|] | [|] | | | | | |];\n      try solve [exact (@prop_right mpred _ True _ I)].\n    - simpl.\n      unfold_lift.\n      unfold denote_tc_nosignedover.\n      destruct (eval_expr e rho); try solve [inv H0].\n      rewrite negb_true_iff in H0.\n      rewrite Z.eqb_neq in H0.\n      apply prop_right.\n      change (Int.signed Int.zero) with 0.\n      rep_lia.\n    - simpl.\n      unfold_lift.\n      unfold denote_tc_nosignedover.\n      destruct (typeof e) as [ | _ [ | ] _ | | | | | | | ];\n      destruct (eval_expr e rho); try solve [inv H0];\n      rewrite negb_true_iff in H0;\n      rewrite Z.eqb_neq in H0;\n      apply prop_right;\n      change (Int64.signed Int64.zero) with 0;\n      rep_lia.\n  + destruct (Cop.classify_neg (typeof e)); try solve [inv H | rewrite H; exact (@prop_right mpred _ True _ I)].\nQed.\n\nLemma const_only_isBinOpResultType_spec: forall {cs: compspecs} rho b e1 e2 t P,\n  const_only_isBinOpResultType b (typeof e1) (eval_expr e1 rho) (typeof e2) (eval_expr e2 rho) t = true ->\n  P |-- denote_tc_assert (isBinOpResultType b e1 e2 t) rho.\nProof.\n  intros.\n  unfold isBinOpResultType.\n  unfold const_only_isBinOpResultType in H.\n  destruct b.\n  + destruct (Cop.classify_add (typeof e1) (typeof e2)).\n    - rewrite !denote_tc_assert_andp; simpl.\n      unfold_lift.\n      unfold tc_int_or_ptr_type, denote_tc_isptr.\n      destruct (eval_expr e1 rho); inv H.\n      rewrite !andb_true_iff in H1.\n      destruct H1 as [[? ?] ?].\n      rewrite H, H0, H1.\n      simpl.\n      repeat apply andp_right; apply prop_right; auto.\n    - rewrite !denote_tc_assert_andp; simpl.\n      unfold_lift.\n      unfold tc_int_or_ptr_type, denote_tc_isptr.\n      destruct (eval_expr e1 rho); inv H.\n      rewrite !andb_true_iff in H1.\n      destruct H1 as [[? ?] ?].\n      rewrite H, H0, H1.\n      simpl.\n      repeat apply andp_right; apply prop_right; auto.\n    - rewrite !denote_tc_assert_andp; simpl.\n      unfold_lift.\n      unfold tc_int_or_ptr_type, denote_tc_isptr.\n      destruct (eval_expr e2 rho); inv H.\n      rewrite !andb_true_iff in H1.\n      destruct H1 as [[? ?] ?].\n      rewrite H, H0, H1.\n      simpl.\n      repeat apply andp_right; apply prop_right; auto.\n    - rewrite !denote_tc_assert_andp; simpl.\n      unfold_lift.\n      unfold tc_int_or_ptr_type, denote_tc_isptr.\n      destruct (eval_expr e2 rho); inv H.\n      rewrite !andb_true_iff in H1.\n      destruct H1 as [[? ?] ?].\n      rewrite H, H0, H1.\n      simpl.\n      repeat apply andp_right; apply prop_right; auto.\n    - inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\nQed.\n\nLemma const_only_isCastResultType_spec: forall {cs: compspecs} rho e t P,\n  const_only_isCastResultType (typeof e) t (eval_expr e rho) = true ->\n  P |-- denote_tc_assert (isCastResultType (typeof e) t e) rho.\nProof.\n  intros.\n  unfold const_only_isCastResultType in H.\n  rewrite orb_true_iff in H.\n  destruct H.\n  apply neutral_isCastResultType; auto.\n  destruct (typeof e); inv H.\n  destruct t; inv H1.\n  simpl. apply TT_right.\nQed.\n\nLemma const_only_eval_expr_eq: forall {cs: compspecs} rho e v,\n  const_only_eval_expr e = Some v ->\n  eval_expr e rho = v.  \nProof.\n  intros.\n  revert v H; induction e; try solve [intros; inv H; auto].\n  + intros.\n    simpl in *.\n    destruct t as [| [| | |] | | | | | | |]; inv H.\n    auto.\n  + intros.\n    simpl in *.\n    destruct t as [| | | [|] | | | | |]; inv H.\n    auto.\n  + intros.\n    simpl in *.\n    destruct t as [| | | [|] | | | | |]; inv H.\n    auto.\n  + intros.\n    simpl in *.\n    unfold option_map in H.\n    destruct (const_only_eval_expr e); inv H.\n    destruct (const_only_isUnOpResultType u (typeof e) v0 t); inv H1.\n    specialize (IHe _ eq_refl).\n    unfold_lift.\n    rewrite IHe; auto.\n  + intros.\n    simpl in *.\n    unfold option_map in H.\n    destruct (const_only_eval_expr e1); inv H.\n    destruct (const_only_eval_expr e2); inv H1.\n    destruct (const_only_isBinOpResultType b (typeof e1) v0 (typeof e2) v1 t); inv H0.\n    specialize (IHe1 _ eq_refl).\n    specialize (IHe2 _ eq_refl).\n    unfold_lift.\n    rewrite IHe1, IHe2; auto.\n  + intros.\n    simpl in *.\n    unfold option_map in H.\n    destruct (const_only_eval_expr e); inv H.\n    destruct (const_only_isCastResultType (typeof e) t v0) eqn:?H; inv H1.\n    unfold_lift. erewrite IHe by reflexivity. auto.\n  + intros.\n    simpl in *.\n    destruct (complete_type cenv_cs t); inv H.\n    destruct (eqb_type t0 size_t); inv H1.\n    auto.\n  + intros.\n    simpl in *.\n    destruct (complete_type cenv_cs t); inv H.\n    destruct (eqb_type t0 size_t); inv H1.\n    auto.\nQed.\n\nLemma const_only_eval_expr_tc: forall {cs: compspecs} Delta e v P,\n  const_only_eval_expr e = Some v ->\n  P |-- tc_expr Delta e.\nProof.\n  intros.\n  intro rho.\n  revert v H; induction e; try solve [intros; inv H].\n  + intros.\n    inv H.\n    destruct t as [| [| | |] | | | | | | |]; inv H1.\n    exact (@prop_right mpred _ True _ I).\n  + intros.\n    inv H.\n    destruct t as [| | | [|] | | | | |]; inv H1.\n    exact (@prop_right mpred _ True _ I).\n  + intros.\n    inv H.\n    destruct t as [| | | [|] | | | | |]; inv H1.\n    exact (@prop_right mpred _ True _ I).\n  + intros.\n    unfold tc_expr in *.\n    simpl in *.\n    unfold option_map in H.\n    destruct (const_only_eval_expr e) eqn:HH; inv H.\n    specialize (IHe _ eq_refl).\n    unfold_lift.\n    rewrite denote_tc_assert_andp; simpl; apply andp_right; auto.\n    apply const_only_isUnOpResultType_spec.\n    apply (const_only_eval_expr_eq rho) in HH.\n    rewrite HH.\n    destruct (const_only_isUnOpResultType u (typeof e) v0 t); inv H1; auto.\n  + intros.\n    unfold tc_expr in *.\n    simpl in *.\n    unfold option_map in H.\n    destruct (const_only_eval_expr e1) eqn:HH1; inv H.\n    destruct (const_only_eval_expr e2) eqn:HH2; inv H1.\n    specialize (IHe1 _ eq_refl).\n    specialize (IHe2 _ eq_refl).\n    unfold_lift.\n    rewrite !denote_tc_assert_andp; simpl; repeat apply andp_right; auto.\n    apply const_only_isBinOpResultType_spec.\n    apply (const_only_eval_expr_eq rho) in HH1.\n    apply (const_only_eval_expr_eq rho) in HH2.\n    rewrite HH1, HH2.\n    destruct (const_only_isBinOpResultType b (typeof e1) v0 (typeof e2) v1 t); inv H0; auto.\n  + intros.\n    unfold tc_expr in *.\n    simpl in *.\n    unfold option_map in H.\n    destruct (const_only_eval_expr e) eqn:HH; inv H.\n    destruct (const_only_isCastResultType (typeof e) t v0) eqn:?H; inv H1.\n    rewrite denote_tc_assert_andp.\n    simpl.\n    apply andp_right; eauto.\n    apply const_only_isCastResultType_spec; auto.\n  + intros.\n    inv H.\n    unfold tc_expr.\n    simpl typecheck_expr.\n    simpl.\n    destruct (complete_type cenv_cs t && eqb_type t0 size_t) eqn:HH; inv H1.\n    rewrite andb_true_iff in HH.\n    unfold tuint in HH; destruct HH.\n    rewrite H, H0.\n    exact (@prop_right mpred _ True _ I).\n  + intros.\n    inv H.\n    unfold tc_expr.\n    simpl typecheck_expr.\n    simpl.\n    destruct (complete_type cenv_cs t && eqb_type t0 size_t) eqn:HH; inv H1.\n    rewrite andb_true_iff in HH.\n    unfold tuint in HH; destruct HH.\n    rewrite H, H0.\n    exact (@prop_right mpred _ True _ I).\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/floyd/const_only_eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.21802171497622386}}
{"text": "Require Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Logic.Classical_Prop.\nRequire Import Coq.Logic.Classical_Pred_Type.\nRequire Import Logic.lib.Bijection.\nRequire Import Logic.lib.Countable.\nRequire Import Logic.lib.EnsemblesProperties.\nRequire Import Logic.GeneralLogic.Base.\nRequire Import Logic.GeneralLogic.ProofTheory.BasicSequentCalculus.\nRequire Import Logic.GeneralLogic.Complete.Lindenbaum.\nRequire Import Logic.GeneralLogic.Complete.Lindenbaum_Kripke.\nRequire Import Logic.GeneralLogic.Complete.ContextProperty.\nRequire Import Logic.GeneralLogic.Complete.ContextProperty_Kripke.\nRequire Import Logic.GeneralLogic.Complete.ContextProperty_Trivial.\nRequire Import Logic.MinimumLogic.Syntax.\nRequire Import Logic.MinimumLogic.ProofTheory.Minimum.\nRequire Import Logic.MinimumLogic.Complete.Lindenbaum_Kripke.\nRequire Import Logic.MinimumLogic.Complete.ContextProperty_Kripke.\nRequire Import Logic.PropositionalLogic.ProofTheory.Intuitionistic.\nRequire Import Logic.PropositionalLogic.ProofTheory.Classical.\nRequire Import Logic.PropositionalLogic.Syntax.\nRequire Import Logic.PropositionalLogic.Complete.Lindenbaum_Kripke.\nRequire Import Logic.PropositionalLogic.Complete.ContextProperty_Kripke.\nRequire Import Logic.PropositionalLogic.Complete.ContextProperty_Trivial.\n\nLocal Open Scope logic_base.\nLocal Open Scope syntax.\nImport PropositionalLanguageNotation.\n\nSection Lindenbaum_Trivial.\n\nContext {L: Language}\n        {minL: MinimumLanguage L}\n        {andpL: AndLanguage L}\n        {orpL: OrLanguage L}\n        {falsepL: FalseLanguage L}\n        {negpL: NegLanguage L}\n        {iffpL: IffLanguage L}\n        {truepL: TrueLanguage L}\n        {GammaP: Provable L}\n        {GammaD: Derivable L}\n        {GammaPD: ProvableDerivable L GammaP GammaD}\n        {bSC: BasicSequentCalculus L GammaD}\n        {fwSC: FiniteWitnessedSequentCalculus L GammaD}\n        {minSC: MinimumSequentCalculus L GammaD}\n        {andpSC: AndSequentCalculus L GammaD}\n        {orpSC: OrSequentCalculus L GammaD}\n        {falsepSC: FalseSequentCalculus L GammaD}\n        {inegpSC: IntuitionisticNegSequentCalculus L GammaD}\n        {iffpSC: IffSequentCalculus L GammaD}\n        {truepSC: TrueSequentCalculus L GammaD}\n        {cpSC: ClassicalSequentCalculus L GammaD}\n        {minAX: MinimumAxiomatization L GammaP}\n        {andpAX: AndAxiomatization L GammaP}\n        {orpAX: OrAxiomatization L GammaP}\n        {falsepAX: FalseAxiomatization L GammaP}\n        {inegpAX: IntuitionisticNegAxiomatization L GammaP}\n        {iffpAX: IffAxiomatization L GammaP}\n        {truepAX: TrueAxiomatization L GammaP}.\n\nLemma Lindenbaum_for_max_consistent: forall P,\n  Lindenbaum_ensures P derivable_closed ->\n  Lindenbaum_ensures P orp_witnessed ->\n  Lindenbaum_ensures P consistent ->\n  Lindenbaum_ensures P (maximal consistent).\nProof.\n  intros.\n  hnf; intros.\n  apply DDCS_MCS; auto.\nQed.\n\nLemma Lindenbaum_cannot_derive_ensures_max_consistent\n      {GammaDP: DerivableProvable L GammaP GammaD}:\n  forall x, Lindenbaum_ensures (cannot_derive x) (maximal consistent).\nProof.\n  intros.\n  apply Lindenbaum_for_max_consistent.\n  - apply Lindenbaum_cannot_derive_ensures_derivable_closed.\n  - apply Lindenbaum_cannot_derive_ensures_orp_witnessed.\n  - apply Lindenbaum_cannot_derive_ensures_consistent.\nQed.\n\nEnd Lindenbaum_Trivial.\n", "meta": {"author": "QinxiangCao", "repo": "LOGIC", "sha": "d1476d57345c87447ea500b3d5ea99ee6d0f6863", "save_path": "github-repos/coq/QinxiangCao-LOGIC", "path": "github-repos/coq/QinxiangCao-LOGIC/LOGIC-d1476d57345c87447ea500b3d5ea99ee6d0f6863/PropositionalLogic/Complete/Lindenbaum_Trivial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.2180216961073769}}
{"text": "Require Import Coq.Init.Wf Coq.Numbers.BinNums.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.FSets.FMapPositive.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Carriers.\nRequire Import Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Import Fiat.Parsers.Splitters.RDPList.\nRequire Import Fiat.Parsers.BaseTypes.\nRequire Export Fiat.Parsers.ContextFreeGrammar.Fix.Definitions.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Fix.Properties.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Fix.Fix.\nRequire Import Fiat.Common.FMapExtensions.Wf.\nRequire Import Fiat.Common.\nRequire Import Fiat.Common.OptionFacts.\nRequire Import Fiat.Common.SetoidInstances.\n\nSet Implicit Arguments.\nLocal Open Scope grammar_fixedpoint_scope.\n\nSection grammar_fixedpoint.\n  Context {Char : Type}.\n  Context {gdata0 gdata1 : grammar_fixedpoint_data}\n          (R : grammar_fixedpoint_lattice_data_relation gdata0 gdata1).\n\n  Definition aggregate_state_relation\n    : aggregate_state gdata0 -> aggregate_state gdata1 -> Prop\n    := PositiveMapExtensions.lift_relation_hetero\n         (state_relation R) ⊤ ⊤.\n\n  Lemma related_aggregate_state_max\n        initial_nonterminals_data\n        (HRbot : R ⊥ ⊥)\n    : aggregate_state_relation\n        (aggregate_state_max gdata0 initial_nonterminals_data)\n        (aggregate_state_max gdata1 initial_nonterminals_data).\n  Proof.\n    unfold aggregate_state_relation.\n    rewrite PositiveMapExtensions.lift_relation_hetero_iff; intro k.\n    rewrite !find_aggregate_state_max_exact.\n    break_match; trivial.\n  Qed.\n\n  Section with_grammar.\n    Context (G : pregrammar' Char).\n\n    Let predata := @rdp_list_predata _ G.\n    Local Existing Instance predata.\n\n    Global Instance lift_relation_hetero_Proper_aggregate_state_beq_flip_impl\n      : Proper (PositiveMapExtensions.lift_eqb state_beq ⊤ ==> PositiveMapExtensions.lift_eqb state_beq ⊤ ==> flip impl)\n               (PositiveMapExtensions.lift_relation_hetero R ⊤ ⊤) | 2.\n    Proof.\n      apply PositiveMapExtensions.lift_relation_hetero_Proper_Proper_lift_brelation_subrelation_flip_impl; try exact _.\n      apply top_state_related.\n    Qed.\n\n    Global Instance lift_relation_hetero_Proper_aggregate_state_eq_flip_impl\n      : Proper (aggregate_state_eq (gdata:=_) ==> aggregate_state_eq (gdata:=_) ==> flip impl)\n               (PositiveMapExtensions.lift_relation_hetero R ⊤ ⊤) | 2\n      := _.\n\n    Lemma related_pre_Fix_grammar_gen\n          (HRtop : R ⊤ ⊤)\n          (HRbot : R ⊥ ⊥)\n          (HRtopR : forall x y, R x ⊤ -> R (x ⊔ y) ⊤)\n          (HRtopL : forall x y, R ⊤ x -> R ⊤ (x ⊔ y))\n          (HRstep : forall st st' k,\n              aggregate_state_relation st st'\n              -> R (lookup_state st k ⊔ step_constraints gdata0 (lookup_state st) k (lookup_state st k))\n                   (lookup_state st' k ⊔ step_constraints gdata1 (lookup_state st') k (lookup_state st' k)))\n          (R_Proper : Proper (state_beq ==> state_beq ==> iff) R)\n      : aggregate_state_relation\n          (pre_Fix_grammar gdata0 initial_nonterminals_data)\n          (pre_Fix_grammar gdata1 initial_nonterminals_data).\n    Proof.\n      pose proof (related_aggregate_state_max initial_nonterminals_data HRbot) as H.\n      unfold aggregate_state_relation in *.\n      rewrite PositiveMapExtensions.lift_relation_hetero_iff in *.\n      rewrite <- ?PositiveMapExtensions.lift_relation_hetero_iff in H. (* undo power of econstr *)\n      (*pose proof (@find_pre_Fix_grammar _ gdata0 G) as H0.\n      pose proof (@find_pre_Fix_grammar _ gdata1 G) as H1.\n      pose proof (fun nt => transitivity (symmetry (H0 nt)) (H1 nt)) as H01; clear H0 H1.\n      setoid_rewrite find_pre_Fix_grammar_to_lookup_state' in H01.\n      progress repeat setoid_rewrite nonterminal_to_positive_to_nonterminal in H01.*)\n      intro k.\n      rewrite !find_pre_Fix_grammar_to_lookup_state' in *.\n      fold predata.\n      destruct (@is_valid_nonterminal _ predata (@initial_nonterminals_data _ predata) (positive_to_nonterminal k)) eqn:Hv; [ | exact I ].\n      unfold pre_Fix_grammar, pre_Fix_grammar_helper in *.\n      fold predata.\n      (*fold predata in H01 |- *.*)\n      assert (Hfind : forall k, PositiveMap.find k (aggregate_state_max gdata0 initial_nonterminals_data) = None\n                                <-> PositiveMap.find k (aggregate_state_max gdata1 initial_nonterminals_data) = None).\n      { intro; rewrite !find_aggregate_state_max_exact.\n        break_match; split; congruence. }\n      generalize dependent (aggregate_state_max gdata0 initial_nonterminals_data).\n      generalize dependent (aggregate_state_max gdata1 initial_nonterminals_data).\n      intro a; induction (aggregate_state_lt_wf a) as [st' Hacc IH].\n      intro st.\n      intros H' Hfind; revert H'.\n      rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n      set (FIX := Fix) at 1.\n      rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n      subst FIX.\n      assert (Hfind_all\n              : forall k, (PositiveMap.find k st = None <-> PositiveMap.find k (aggregate_step st') = None)\n                          /\\ (PositiveMap.find k (aggregate_step st) = None <-> PositiveMap.find k st' = None)\n                          /\\ (PositiveMap.find k (aggregate_step st) = None <-> PositiveMap.find k (aggregate_step st') = None)\n                          /\\ (PositiveMap.find k (aggregate_step (aggregate_step st)) = None <-> PositiveMap.find k st' = None)\n                          /\\ (PositiveMap.find k (aggregate_step (aggregate_step st)) = None <-> PositiveMap.find k (aggregate_step st') = None)).\n      { let k := fresh in\n        intro k; specialize (Hfind k).\n        rewrite !find_aggregate_step; unfold option_map; break_match; intuition congruence. }\n      assert (forall k, PositiveMap.find k st = None <-> PositiveMap.find k (aggregate_step st') = None) by apply Hfind_all.\n      assert (forall k, PositiveMap.find k (aggregate_step st) = None <-> PositiveMap.find k st' = None) by apply Hfind_all.\n      assert (forall k, PositiveMap.find k (aggregate_step st) = None <-> PositiveMap.find k (aggregate_step st') = None) by apply Hfind_all.\n      assert (forall k, PositiveMap.find k (aggregate_step (aggregate_step st)) = None <-> PositiveMap.find k st' = None) by apply Hfind_all.\n      assert (forall k, PositiveMap.find k (aggregate_step (aggregate_step st)) = None <-> PositiveMap.find k (aggregate_step st') = None) by apply Hfind_all.\n      do 2 edestruct dec.\n      { rewrite PositiveMapExtensions.lift_relation_hetero_iff.\n        unfold lookup_state, PositiveMapExtensions.find_default.\n        intro Hfind'.\n        let k := match goal with |- context[PositiveMap.find ?k _] => k end in\n        specialize (Hfind' k).\n        do 2 edestruct PositiveMap.find; simpl; assumption. }\n      { specialize (fun y Hy => IH y Hy st).\n        rewrite Init.Wf.Fix_eq in IH by (intros; edestruct dec; trivial).\n        edestruct dec; [ | congruence ].\n        intro Hfind'; apply IH; clear IH; auto using step_lt; [].\n\n        unfold aggregate_state_eq in *.\n        unfold PositiveMapExtensions.lift_eqb in *.\n        match goal with\n        | [ H : PositiveMapExtensions.lift_brelation state_beq ⊤ ?x ?y = true |- PositiveMapExtensions.lift_relation_hetero _ _ _ ?x _ ]\n          => change (is_true (PositiveMapExtensions.lift_brelation state_beq ⊤ x y)) in H;\n               rewrite H\n        end.\n\n        rewrite PositiveMapExtensions.lift_relation_hetero_iff.\n        unfold lookup_state, PositiveMapExtensions.find_default.\n        intro k'; specialize (Hfind k'); rewrite !find_aggregate_step.\n\n        unfold option_map; break_innermost_match; auto;\n          try solve [ intuition congruence ]; [].\n        repeat match goal with\n               | [ |- context[?s ⊔ step_constraints ?data ?lookup ?k ?s] ]\n                 => is_var s;\n                      replace s with (lookup k)\n                      by (unfold lookup_state, PositiveMapExtensions.find_default, option_rect;\n                          rewrite positive_to_nonterminal_to_positive; rewrite_hyp; reflexivity)\n               end.\n        auto. }\n      { clear IH Hfind_all Hacc.\n        intro Hrel.\n        assert (Hrel' : PositiveMapExtensions.lift_relation_hetero R ⊤ ⊤ (aggregate_step st) st').\n        { unfold aggregate_state_eq, PositiveMapExtensions.lift_eqb in *.\n          match goal with\n          | [ H : PositiveMapExtensions.lift_brelation state_beq ⊤ ?x ?y = true |- PositiveMapExtensions.lift_relation_hetero _ _ _ _ ?x ]\n            => change (is_true (PositiveMapExtensions.lift_brelation state_beq ⊤ x y)) in H;\n                 rewrite H\n          end.\n          pose proof Hrel as Hrel'.\n          rewrite PositiveMapExtensions.lift_relation_hetero_iff in Hrel' |- *.\n          unfold lookup_state, PositiveMapExtensions.find_default.\n          intro k'; pose proof (Hrel' k'); rewrite !find_aggregate_step.\n\n          unfold option_map; break_innermost_match; auto;\n            try solve [ intuition congruence ]; [].\n          repeat match goal with\n                 | [ |- context[?s ⊔ step_constraints ?data ?lookup ?k ?s] ]\n                   => is_var s;\n                        replace s with (lookup k)\n                        by (unfold lookup_state, PositiveMapExtensions.find_default, option_rect;\n                            rewrite positive_to_nonterminal_to_positive; rewrite_hyp; reflexivity)\n                 end.\n          auto. }\n\n        revert dependent st'.\n        generalize dependent (aggregate_step st); intros a _.\n        intros; clear dependent st; revert dependent st'.\n        induction (aggregate_state_lt_wf a) as [st Hacc IH].\n        intro st'.\n        intros.\n        rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n\n        edestruct dec.\n        { unfold lookup_state, PositiveMapExtensions.find_default.\n          rewrite positive_to_nonterminal_to_positive.\n          lazymatch goal with\n          | [ H : PositiveMapExtensions.lift_relation_hetero _ _ _ _ _ |- _ ]\n            => revert H\n          end.\n          rewrite PositiveMapExtensions.lift_relation_hetero_iff.\n          intro Hrel.\n          repeat match goal with\n                 | [ H : forall k : PositiveMap.key, _ |- context[PositiveMap.find ?k' _] ]\n                   => specialize (H k')\n                 end.\n          unfold state in *.\n          unfold option_map, option_rect; break_match; auto;\n            intuition congruence. }\n        { specialize (fun y Hy => IH y Hy st').\n          specialize (IH (aggregate_step st)).\n          apply IH; clear IH; auto using step_lt;\n            [ let k := fresh in\n              intro k;\n              repeat match goal with\n                     | [ H : forall k' : PositiveMap.key, _ |- _ ] => specialize (H k)\n                     end;\n              rewrite !find_aggregate_step; unfold option_map; break_innermost_match;\n              intuition congruence..\n            | ].\n          { unfold aggregate_state_eq, PositiveMapExtensions.lift_eqb, state in *.\n            lazymatch goal with\n            | [ H : PositiveMapExtensions.lift_brelation state_beq ⊤ ?x ?y = true |- PositiveMapExtensions.lift_relation_hetero _ _ _ _ ?x ]\n              => change (is_true (PositiveMapExtensions.lift_brelation state_beq ⊤ x y)) in H;\n                   rewrite H\n            end.\n            lazymatch goal with\n            | [ H : PositiveMapExtensions.lift_relation_hetero _ _ _ _ _ |- _ ]\n              => generalize H\n            end.\n            rewrite !PositiveMapExtensions.lift_relation_hetero_iff.\n            let k := fresh in intros Hrel k; specialize (Hrel k); revert Hrel.\n            rewrite !find_aggregate_step; unfold option_map, state;\n              break_innermost_match; auto.\n            repeat match goal with\n                   | [ |- context[?s ⊔ step_constraints ?data ?lookup ?k ?s] ]\n                     => is_var s;\n                          replace s with (lookup k)\n                          by (unfold lookup_state, PositiveMapExtensions.find_default, option_rect;\n                              rewrite positive_to_nonterminal_to_positive; rewrite_hyp; reflexivity)\n                   end.\n            auto. } } }\n      { intro Hfind'; apply IH; clear IH; auto using step_lt; [].\n        pose proof Hfind' as Hfind''.\n        rewrite PositiveMapExtensions.lift_relation_hetero_iff in Hfind' |- *.\n        intro k'; specialize (Hfind' k').\n        rewrite !find_aggregate_step.\n        unfold option_map; break_innermost_match; auto.\n        repeat match goal with\n               | [ |- context[?s ⊔ step_constraints ?data ?lookup ?k ?s] ]\n                 => is_var s;\n                      replace s with (lookup k)\n                      by (unfold lookup_state, PositiveMapExtensions.find_default, option_rect;\n                          rewrite positive_to_nonterminal_to_positive; rewrite_hyp; reflexivity)\n               end.\n        auto. }\n    Qed.\n\n    Lemma related_pre_Fix_grammar\n          (HRtop : R ⊤ ⊤)\n          (HRbot : R ⊥ ⊥)\n          (HRtopR : forall x y, R x ⊤ -> R (x ⊔ y) ⊤)\n          (HRtopL : forall x y, R ⊤ x -> R ⊤ (x ⊔ y))\n          (HRlub : forall x y, R x y -> forall x' y', R x' y' -> R (x ⊔ x') (y ⊔ y'))\n          (step_constraints_Proper\n           : forall f g,\n              (forall k, R (f k) (g k))\n              -> forall k st st',\n                R st st'\n                -> R (step_constraints gdata0 f k st) (step_constraints gdata1 g k st'))\n          (R_Proper : Proper (state_beq ==> state_beq ==> iff) R)\n      : aggregate_state_relation\n          (pre_Fix_grammar gdata0 initial_nonterminals_data)\n          (pre_Fix_grammar gdata1 initial_nonterminals_data).\n    Proof.\n      apply related_pre_Fix_grammar_gen; try assumption.\n      { intros ?? k H.\n        unfold aggregate_state_relation, lookup_state, PositiveMapExtensions.find_default in *.\n        rewrite PositiveMapExtensions.lift_relation_hetero_iff in H.\n        unfold option_rect, state in *; simpl in *.\n        apply HRlub; [ | apply step_constraints_Proper ];\n          repeat match goal with\n                 | _ => intro\n                 | [ H : forall k : PositiveMap.key, _ |- context[PositiveMap.find ?k _] ]\n                   => specialize (H k)\n                 | _ => assumption\n                 | _ => progress break_innermost_match\n                 end. }\n    Qed.\n(*\n\n  Local Notation default_value := ⊤ (only parsing).\n\n  Definition lookup_state (st : aggregate_state) (nt : default_nonterminal_carrierT)\n    : state gdata\n    := PositiveMapExtensions.find_default default_value (nonterminal_to_positive nt) st.\n\n  Notation from_aggregate_state := lookup_state (only parsing).\n\n  Definition aggregate_state_le : aggregate_state -> aggregate_state -> bool\n    := PositiveMapExtensions.lift_leb state_le default_value.\n  Definition aggregate_state_eq : aggregate_state -> aggregate_state -> bool\n    := PositiveMapExtensions.lift_eqb state_beq default_value.\n  Definition aggregate_state_lt (v1 v2 : aggregate_state) : bool\n    := PositiveMapExtensions.lift_ltb state_beq state_le default_value v1 v2.\n\n  Lemma PositiveMap_elements_iff {A m k v}\n    : @PositiveMap.find A k m = Some v <-> In (k, v) (PositiveMap.elements m).\n  Proof.\n    rewrite PositiveMapExtensions.elements_iff_find.\n    rewrite InA_alt; unfold PositiveMap.eq_key_elt, PositiveMap.E.eq; simpl.\n    split; [ intros [[? ?] [[? ?] ?]] | intro H; exists (k, v) ];\n      subst; repeat split; assumption.\n  Qed.\n\n  Lemma PositiveMap_elements_iff' {A m kv}\n    : @PositiveMap.find A (fst kv) m = Some (snd kv) <-> In kv (PositiveMap.elements m).\n  Proof.\n    destruct kv; apply PositiveMap_elements_iff.\n  Qed.\n\n  Create HintDb aggregate_step_db discriminated.\n  Hint Rewrite PositiveMap.fold_1 PositiveMap.gmapi nonterminal_to_positive_to_nonterminal positive_to_nonterminal_to_positive PositiveMap.gempty PositiveMapAdditionalFacts.gsspec (@state_beq_refl _ gdata) orb_true_iff orb_true_r orb_false_iff (@state_le_bottom_eq_bottom _ gdata) (@no_state_lt_bottom _ gdata) (@state_le_bottom_eq_bottom _ gdata) (@state_ge_top_eq_top _ gdata) (@bottom_lub_r _ gdata) (@bottom_lub_l _ gdata) (@top_lub_r _ gdata) (@top_lub_l _ gdata) (fun a b => @least_upper_bound_correct_l _ gdata a b : _ = true) (fun a b => @least_upper_bound_correct_r _ gdata a b : _ = true) (fun s => @bottom_bottom _ gdata s : _ = true) (fun s => @top_top _ gdata s : _ = true) beq_nat_true_iff @PositiveMapExtensions.lift_brelation_iff : aggregate_step_db.\n  Hint Rewrite <- beq_nat_refl : aggregate_step_db.\n  Hint Rewrite PositiveMapExtensions.map2_1bis_for_rewrite using reflexivity : aggregate_step_db.\n  Hint Rewrite PositiveMapExtensions.fold_andb_true : aggregate_step_db.\n\n  Local Ltac fold_andb_t_step :=\n    idtac;\n    match goal with\n    | _ => progress intros\n    | _ => progress subst\n    | _ => congruence\n    | _ => progress unfold PositiveMap.key in *\n    | [ H : Some _ = Some _ |- _ ] => inversion H; clear H\n    | [ H : Some ?b <> Some false |- _ ] => destruct b eqn:?; [ clear H | congruence ]\n    | [ H : (⊥ =b ?s) = false, H' : (⊥ < ?s) = false |- _ ]\n      => let H'' := fresh in\n         pose proof (bottom_bottom s) as H''; setoid_rewrite orb_true_iff in H''; destruct H''; congruence\n    | [ H : context[PositiveMap.fold _ _ _ = true] |- _ ]\n      => setoid_rewrite PositiveMapExtensions.fold_andb_true in H\n    | [ |- context[PositiveMap.fold _ _ _ = true] ]\n      => setoid_rewrite PositiveMapExtensions.fold_andb_true\n    | [ |- true = false ] => symmetry\n    | [ H : PositiveMap.fold _ _ _ = false |- false = true ]\n      => rewrite <- H; clear H\n    | [ H : context[PositiveMap.find _ (PositiveMap.map2 ?f _ _)] |- _ ]\n      => setoid_rewrite (@PositiveMapExtensions.map2_1bis_for_rewrite _ _ _ f eq_refl) in H\n    | [ |- context[PositiveMap.find _ (PositiveMap.map2 ?f _ _)] ]\n      => setoid_rewrite (@PositiveMapExtensions.map2_1bis_for_rewrite _ _ _ f eq_refl)\n    | [ H : context[PositiveMapExtensions.lift_brelation] |- _ ]\n      => setoid_rewrite PositiveMapExtensions.lift_brelation_iff in H\n    | [ |- context[PositiveMapExtensions.lift_brelation] ]\n      => setoid_rewrite PositiveMapExtensions.lift_brelation_iff\n    | [ H : ?x = _, H' : context[?x] |- _ ] => setoid_rewrite H in H'\n    | [ H : ?x = _ |- context[?x] ] => setoid_rewrite H\n    | [ H : and _ _ |- _ ] => destruct H\n    | [ H : pointwise_relation _ eq ?x ?y, H' : context[step_constraints _ ?x] |- _ ]\n      => rewrite H in H'\n    | _ => progress autorewrite with aggregate_step_db in *\n    | [ H : forall k : positive, _ |- _ ]\n      => repeat match goal with\n                | [ k' : positive |- _ ]\n                  => unique pose proof (H k')\n                | [ |- context[PositiveMap.find ?k' _] ]\n                  => unique pose proof (H k')\n                | [ _ : context[PositiveMap.find ?k' _] |- _ ]\n                  => unique pose proof (H k')\n                end;\n         clear H\n    | _ => progress simpl in *\n    | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n    | [ H : context[match ?e with _ => _ end] |- _ ] => destruct e eqn:?\n    | [ |- _ <> _ ] => intro\n    | [ H : or _ _ |- _ ] => destruct H\n    | [ |- and _ _ ] => split\n    | [ H : (?x < ?y) = true, H' : (?y < ?z) = true |- _ ]\n      => unique pose proof (state_lt_Transitive H H' : (x < z) = true)\n    | [ H : is_true (?x =b ?y) |- _ ]\n      => rewrite H in *; clear x H\n    | [ H : is_true (?x =b ?y) |- _ ]\n      => rewrite <- H in *; clear x H\n    | [ H : ?R ?x ?y |- _ ]\n      => is_var x; rewrite H in *; clear x H\n    | [ H : ?R ?x ?y |- _ ]\n      => is_var y; rewrite <- H in *; clear y H\n    end.\n  Local Ltac fold_andb_t := repeat fold_andb_t_step.\n\n  Global Instance aggregate_state_eq_Reflexive : Reflexive aggregate_state_eq | 1 := _.\n  Global Instance aggregate_state_eq_Symmetric : Symmetric aggregate_state_eq | 1 := _.\n  Global Instance aggregate_state_eq_Transitive : Transitive aggregate_state_eq | 1 := _.\n  Global Instance aggregate_state_le_Reflexive : Reflexive aggregate_state_le | 1 := _.\n  Global Instance aggregate_state_le_Transitive : Transitive aggregate_state_le | 1 := _.\n  Global Instance aggregate_state_eq_Proper_Equal\n    : Proper (@PositiveMap.Equal _ ==> @PositiveMap.Equal _ ==> eq) aggregate_state_eq | 100\n    := _.\n  Global Instance aggregate_state_le_Proper_Equal\n    : Proper (@PositiveMap.Equal _ ==> @PositiveMap.Equal _ ==> eq) aggregate_state_le | 100\n    := _.\n  Global Instance aggregate_state_lt_Proper_Equal\n    : Proper (@PositiveMap.Equal _ ==> @PositiveMap.Equal _ ==> eq) aggregate_state_lt | 100\n    := _.\n  Global Instance aggregate_state_le_Proper\n    : Proper (aggregate_state_eq ==> aggregate_state_eq ==> eq) aggregate_state_le | 1\n    := _.\n  Global Instance aggregate_state_lt_Proper\n    : Proper (aggregate_state_eq ==> aggregate_state_eq ==> eq) aggregate_state_lt | 1\n    := _.\n\n  Definition aggregate_state_lub_f : option (state gdata) -> option (state gdata) -> option (state gdata)\n      := PositiveMapExtensions.defaulted_f default_value default_value least_upper_bound.\n\n  Definition aggregate_state_lub (v1 v2 : aggregate_state) : aggregate_state\n    := PositiveMap.map2 aggregate_state_lub_f v1 v2.\n\n  Definition aggregate_prestep (v : aggregate_state) : aggregate_state\n    := let helper := step_constraints gdata (from_aggregate_state v) in\n       PositiveMap.mapi (fun nt => helper (positive_to_nonterminal nt)) v.\n\n  Definition aggregate_step (v : aggregate_state) : aggregate_state\n    := aggregate_state_lub v (aggregate_prestep v).\n\n  Definition aggregate_state_lub_correct (v1 v2 : aggregate_state)\n    : aggregate_state_le v1 (aggregate_state_lub v1 v2)\n      /\\ aggregate_state_le v2 (aggregate_state_lub v1 v2).\n  Proof.\n    unfold aggregate_state_le, aggregate_state_lub, aggregate_state_lub_f.\n    setoid_rewrite PositiveMapExtensions.lift_brelation_iff.\n    unfold PositiveMapExtensions.defaulted_f.\n    repeat match goal with\n           | [ |- and _ _ ] => split\n           | _ => intro\n           | _ => progress subst\n           | [ H : ?x = _ |- context[?x] ] => setoid_rewrite H\n           | [ H : ?x = _, H' : context[?x] |- _ ] => setoid_rewrite H in H'\n           | [ H : Some _ = Some _ |- _ ] => inversion H; clear H\n           | [ H : context[match ?e with _ => _ end] |- _ ] => destruct e eqn:?\n           | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:?\n           | [ |- is_true (?R ?x ?x) ] => reflexivity\n           | _ => apply top_top\n           | _ => apply least_upper_bound_correct_l\n           | _ => apply least_upper_bound_correct_r\n           | _ => congruence\n           | [ H : _ |- _ ] => setoid_rewrite PositiveMapExtensions.map2_1bis_for_rewrite in H; [ | reflexivity.. ]\n           end.\n  Qed.\n\n  Lemma find_aggregate_state_lub a b k\n    : PositiveMap.find k (aggregate_state_lub a b)\n      = aggregate_state_lub_f (PositiveMap.find k a) (PositiveMap.find k b).\n  Proof.\n    unfold aggregate_state_lub.\n    fold_andb_t.\n  Qed.\n\n  Lemma nothing_empty_lt v : ~aggregate_state_lt (PositiveMap.empty _) v.\n  Proof.\n    setoid_rewrite PositiveMapExtensions.empty_ltb_nothing; [ congruence | ].\n    setoid_rewrite state_ge_top_eq_top.\n    intros; symmetry; assumption.\n  Qed.\n\n  Lemma aggregate_state_lt_wf : well_founded (Basics.flip aggregate_state_lt).\n  Proof.\n    apply PositiveMapExtensions.well_founded_lift_gtb.\n    { eapply Wf.well_founded_subrelation; [ | eexact (@state_gt_wf _ gdata) ].\n      unfold flip, state_le; intros x y H.\n      destruct (y < x); [ reflexivity | simpl in * ].\n      destruct (y =b x) eqn:Heqb; simpl in *; assumption. }\n    { apply top_top. }\n    { exact _. }\n    { exact _. }\n    { exact _. }\n    { exact _. }\n  Defined.\n\n  Section wrap_wf.\n    Context {A R} (Rwf : @well_founded A R).\n\n    Definition lt_wf_idx_step\n               (lt_wf_idx : nat -> well_founded R)\n               (n : nat)\n      : well_founded R.\n    Proof.\n      destruct n.\n      { clear -Rwf; abstract apply Rwf. }\n      { constructor; intros; apply lt_wf_idx; assumption. }\n    Defined.\n\n    Fixpoint lt_wf_idx (n : nat) : well_founded R\n      := lt_wf_idx_step (@lt_wf_idx) n.\n  End wrap_wf.\n\n  Definition aggregate_state_lt_wf_idx (n : nat) : well_founded (Basics.flip aggregate_state_lt)\n    := lt_wf_idx aggregate_state_lt_wf n.\n\n  Definition step_lt {st}\n    : aggregate_state_eq st (aggregate_step st) = false -> Basics.flip aggregate_state_lt (aggregate_step st) st.\n  Proof.\n    unfold Basics.flip.\n    intros pf.\n    destruct (aggregate_state_lt st (aggregate_step st)) eqn:H; [ reflexivity | exfalso ].\n    unfold aggregate_step in *.\n    pose proof (proj1 (aggregate_state_lub_correct st (aggregate_prestep st))) as H'.\n    unfold aggregate_state_lt, PositiveMapExtensions.lift_ltb in *.\n    fold aggregate_state_le in *.\n    fold aggregate_state_eq in *.\n    generalize dependent (aggregate_state_le st (aggregate_state_lub st (aggregate_prestep st))).\n    generalize dependent (aggregate_state_eq st (aggregate_state_lub st (aggregate_prestep st))).\n    clear.\n    abstract (\n        intros [] ? []; simpl; intros; congruence\n      ).\n  Defined.\n\n  Global Instance aggregate_state_lub_Proper\n    : Proper (aggregate_state_eq ==> aggregate_state_eq ==> aggregate_state_eq) aggregate_state_lub | 1.\n  Proof.\n    unfold aggregate_state_eq, aggregate_state_lub, aggregate_state_lub_f.\n    refine PositiveMapExtensions.map2_defaulted_Proper_lift_brelation.\n  Qed.\n\n  Global Instance from_aggregate_state_Proper\n    : Proper (aggregate_state_eq ==> eq ==> state_beq) from_aggregate_state | 1.\n  Proof.\n    unfold aggregate_state_eq, PositiveMapExtensions.lift_eqb, from_aggregate_state, PositiveMapExtensions.find_default, option_rect; repeat intro; fold_andb_t.\n  Qed.\n\n  Global Instance aggregate_step_Proper\n    : Proper (aggregate_state_eq ==> aggregate_state_eq) aggregate_step | 1.\n  Proof.\n    intros x y H.\n    assert (H' : pointwise_relation _ state_beq (from_aggregate_state x) (from_aggregate_state y)) by (intro; setoid_rewrite H; reflexivity).\n    unfold aggregate_state_eq, PositiveMapExtensions.lift_eqb, aggregate_step, aggregate_state_lub, aggregate_prestep in *.\n    setoid_rewrite PositiveMapExtensions.lift_brelation_iff in H.\n    setoid_rewrite PositiveMapExtensions.lift_brelation_iff.\n    repeat setoid_rewrite fold_option_rect_nodep.\n    first [ setoid_rewrite (PositiveMapExtensions.map2_1bis_for_rewrite _ _ _ _ eq_refl)\n          | setoid_rewrite (PositiveMapExtensions.map2_1bis_for_rewrite _ _ _ _ _); [ | reflexivity.. ] ].\n    setoid_rewrite PositiveMap.gmapi.\n    unfold option_rect_nodep, option_map.\n    intro k; specialize (H k).\n    generalize dependent (lookup_state x); generalize dependent (lookup_state y); intros;\n      do 2 edestruct PositiveMap.find;\n      fold_andb_t.\n  Qed.\n\n  Lemma lookup_state_aggregate_state_lub a b nt\n    : lookup_state (aggregate_state_lub a b) nt = (lookup_state a nt ⊔ lookup_state b nt).\n  Proof.\n    unfold lookup_state, PositiveMapExtensions.find_default.\n    rewrite find_aggregate_state_lub.\n    unfold option_rect, aggregate_state_lub_f.\n    fold_andb_t.\n  Qed.\n\n  Global Instance lookup_state_Proper\n    : Proper (aggregate_state_eq ==> eq ==> state_beq) lookup_state | 1.\n  Proof.\n    unfold aggregate_state_eq, PositiveMapExtensions.lift_eqb, lookup_state, PositiveMapExtensions.find_default, option_rect; repeat intro; fold_andb_t.\n  Qed.\n\n  Lemma find_aggregate_prestep st nt\n    : PositiveMap.find nt (aggregate_prestep st)\n      = option_map (step_constraints gdata (lookup_state st) (positive_to_nonterminal nt))\n                   (PositiveMap.find nt st).\n  Proof.\n    unfold aggregate_prestep.\n    autorewrite with aggregate_step_db.\n    unfold from_aggregate_state, option_rect, option_map.\n    edestruct PositiveMap.find; reflexivity.\n  Qed.\n\n  Lemma find_aggregate_step st nt\n    : PositiveMap.find nt (aggregate_step st)\n      = option_map (fun v => v ⊔ step_constraints gdata (lookup_state st) (positive_to_nonterminal nt) v)\n                   (PositiveMap.find nt st).\n  Proof.\n    unfold aggregate_step.\n    rewrite find_aggregate_state_lub, find_aggregate_prestep.\n    edestruct PositiveMap.find; reflexivity.\n  Qed.\n\n  Lemma lookup_state_aggregate_prestep st nt\n    : lookup_state (aggregate_prestep st) nt\n      = option_rect (fun _ => _)\n                    (fun _ => step_constraints gdata (lookup_state st) nt (lookup_state st nt))\n                    default_value\n                    (PositiveMap.find (nonterminal_to_positive nt) st).\n  Proof.\n    unfold lookup_state.\n    unfold PositiveMapExtensions.find_default.\n    rewrite find_aggregate_prestep.\n    unfold lookup_state.\n    rewrite nonterminal_to_positive_to_nonterminal.\n    unfold PositiveMapExtensions.find_default.\n    unfold state in *; simpl in *.\n    edestruct PositiveMap.find; reflexivity.\n  Qed.\n\n  Lemma lookup_state_aggregate_step st nt\n    : lookup_state (aggregate_step st) nt\n      = option_rect (fun _ => _)\n                    (fun s => s ⊔ step_constraints gdata (lookup_state st) nt (lookup_state st nt))\n                    default_value\n                    (PositiveMap.find (nonterminal_to_positive nt) st).\n  Proof.\n    unfold lookup_state, PositiveMapExtensions.find_default.\n    rewrite find_aggregate_step.\n    unfold lookup_state, PositiveMapExtensions.find_default.\n    rewrite nonterminal_to_positive_to_nonterminal.\n    unfold state in *; simpl in *.\n    edestruct PositiveMap.find; reflexivity.\n  Qed.\n\n  Section with_initial.\n    Context (initial_nonterminals_data : list default_nonterminal_carrierT).\n\n    Definition aggregate_state_max : aggregate_state\n      := List.fold_right\n           (fun nt st => PositiveMap.add (nonterminal_to_positive nt) ⊥ st)\n           (PositiveMap.empty _)\n           initial_nonterminals_data.\n\n    Definition pre_Fix_grammar_helper : aggregate_state -> aggregate_state\n      := Fix\n           (aggregate_state_lt_wf_idx (10 * List.length initial_nonterminals_data))\n           (fun _ => aggregate_state)\n           (fun st Fix_grammar_internal\n            => match Sumbool.sumbool_of_bool (aggregate_state_eq st (aggregate_step st)) with\n               | left pf => st\n               | right pf => Fix_grammar_internal (aggregate_step st) (step_lt pf)\n               end).\n\n    Definition pre_Fix_grammar : aggregate_state\n      := pre_Fix_grammar_helper aggregate_state_max.\n\n    Lemma pre_Fix_grammar_helper_fixed st (H : aggregate_state_eq st (aggregate_step st))\n      : aggregate_state_eq st (pre_Fix_grammar_helper st).\n    Proof.\n      unfold pre_Fix_grammar_helper.\n      rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n      edestruct dec; [ | congruence ].\n      reflexivity.\n    Qed.\n\n    Lemma pre_Fix_grammar_helper_commute v\n      : aggregate_state_eq (pre_Fix_grammar_helper (aggregate_step v))\n                           (aggregate_step (pre_Fix_grammar_helper v)).\n    Proof.\n      unfold pre_Fix_grammar_helper.\n      induction (aggregate_state_lt_wf v) as [v H IHv].\n      rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial);\n        symmetry;\n        rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial);\n        symmetry.\n      do 2 edestruct dec; try reflexivity;\n        repeat match goal with\n               | [ H : ?x = true |- _ ] => change (is_true x) in H\n               end.\n      { fold @pre_Fix_grammar_helper in *.\n        rewrite <- pre_Fix_grammar_helper_fixed by assumption.\n        assumption. }\n      { match goal with\n        | [ H : is_true (aggregate_state_eq ?x ?y), H' : context[?x] |- _ ]\n          => rewrite <- H in H'\n        end.\n        congruence. }\n      { apply IHv.\n        apply step_lt; assumption. }\n    Qed.\n\n    Global Instance aggregate_state_eq_Proper_eq\n      : Proper (eq ==> eq ==> eq) aggregate_state_eq\n      := _.\n    Global Instance aggregate_step_Proper_eq\n      : Proper (eq ==> eq) aggregate_step\n      := _.\n\n    Lemma pre_Fix_grammar_fixedpoint\n      : aggregate_state_eq pre_Fix_grammar (aggregate_step pre_Fix_grammar).\n    Proof.\n      unfold pre_Fix_grammar, pre_Fix_grammar_helper.\n      generalize aggregate_state_max; intro a.\n      rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n      edestruct dec as [pf|pf].\n      { rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n        edestruct dec; [ | congruence ].\n        assumption. }\n      { induction (aggregate_state_lt_wf a) as [?? IH].\n        rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n        symmetry;\n          rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial);\n          symmetry.\n        rewrite pf; simpl.\n        edestruct dec as [pf'|pf'].\n        { rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n          rewrite pf'; simpl.\n          assumption. }\n        { apply IH; try assumption; []; clear IH.\n          unfold Basics.flip, aggregate_state_lt, PositiveMapExtensions.lift_ltb.\n          setoid_rewrite pf; simpl; rewrite andb_true_r.\n          pose proof (fun x => aggregate_state_lub_correct x (aggregate_prestep x)) as H'.\n          unfold aggregate_step in *.\n          edestruct H'; eassumption. } }\n    Qed.\n  End with_initial.\n\n  Section with_grammar.\n    Context (G : pregrammar' Char).\n\n    Let predata := @rdp_list_predata _ G.\n    Local Existing Instance predata.\n\n    Lemma find_aggregate_state_max_spec k v\n      : PositiveMap.find k (aggregate_state_max initial_nonterminals_data) = Some v\n        <-> (v = ⊥ /\\ is_valid_nonterminal initial_nonterminals_data (positive_to_nonterminal k)).\n    Proof.\n      unfold aggregate_state_max in *.\n      generalize dependent (@initial_nonterminals_data _ _); intros ls.\n      induction ls as [|x xs IHxs].\n      { simpl in *.\n        autorewrite with aggregate_step_db in *.\n        intuition (tauto || congruence || eauto). }\n      { simpl in *.\n        autorewrite with aggregate_step_db in *.\n        edestruct PositiveMap.E.eq_dec; subst;\n          autorewrite with aggregate_step_db in *;\n          auto using eq_refl with nocore.\n        { repeat intuition (congruence || subst || eauto). }\n        { intuition (congruence || subst || eauto).\n          { apply orb_true_iff; intuition. }\n          { do 2 match goal with\n                 | [ H : is_true (orb _ _) |- _ ] => apply orb_true_iff in H\n                 | [ H : _ |- _ ] => setoid_rewrite beq_nat_true_iff in H\n                 end.\n            repeat intuition (congruence || subst || (autorewrite with aggregate_step_db in * ) || eauto). } } }\n    Qed.\n\n    Lemma find_aggregate_state_max k v\n      : PositiveMap.find k (aggregate_state_max initial_nonterminals_data) = Some v\n        -> PositiveMap.find k (aggregate_state_max initial_nonterminals_data) = Some ⊥.\n    Proof.\n      setoid_rewrite find_aggregate_state_max_spec.\n      tauto.\n    Qed.\n\n    Hint Rewrite find_aggregate_state_max_spec : aggregate_step_db.\n\n    Lemma lookup_state_aggregate_state_max nt\n      : lookup_state (aggregate_state_max initial_nonterminals_data) nt\n        = if is_valid_nonterminal initial_nonterminals_data nt\n          then ⊥\n          else default_value.\n    Proof.\n      unfold lookup_state, PositiveMapExtensions.find_default, option_rect.\n      destruct (PositiveMap.find (nonterminal_to_positive nt) (aggregate_state_max (@initial_nonterminals_data _ predata))) eqn:H; [ | ];\n        setoid_rewrite H.\n      { simpl in *.\n        apply find_aggregate_state_max_spec in H.\n        rewrite nonterminal_to_positive_to_nonterminal in H.\n        destruct H as [? H']; subst; simpl in *; rewrite H'; intuition. }\n      { match goal with |- context[if ?e then _ else _] => destruct e eqn:H' end;\n        [ | reflexivity ].\n        pose proof (find_aggregate_state_max_spec (nonterminal_to_positive nt) ⊥) as H''.\n        rewrite nonterminal_to_positive_to_nonterminal, H' in H''.\n        destruct H'' as [_ H''].\n        rewrite H'' in H by intuition.\n        congruence. }\n    Qed.\n\n    Lemma find_pre_Fix_grammar (nt : default_nonterminal_carrierT)\n      : is_valid_nonterminal initial_nonterminals_data nt\n        <-> PositiveMap.find (nonterminal_to_positive nt) (pre_Fix_grammar initial_nonterminals_data) <> None.\n    Proof.\n      unfold pre_Fix_grammar, pre_Fix_grammar_helper.\n      assert (H : PositiveMap.find (nonterminal_to_positive nt) (aggregate_state_max initial_nonterminals_data) <> None\n                  <-> is_valid_nonterminal initial_nonterminals_data nt).\n      { pose proof (find_aggregate_state_max_spec (nonterminal_to_positive nt)) as H.\n        rewrite nonterminal_to_positive_to_nonterminal in H.\n        edestruct PositiveMap.find.\n        { edestruct H as [H0 H1]; clear H.\n          intuition congruence. }\n        { specialize (H ⊥).\n          intuition congruence. } }\n      rewrite <- H; clear H.\n      generalize dependent (aggregate_state_max initial_nonterminals_data); intro a; intros.\n      induction (aggregate_state_lt_wf a) as [?? IH].\n      rewrite Init.Wf.Fix_eq at 1 by (intros; edestruct dec; trivial).\n      edestruct dec as [pf|pf]; [ reflexivity | ].\n      rewrite <- IH by (apply step_lt; assumption).\n      rewrite find_aggregate_step.\n      unfold option_map; split; fold_andb_t.\n    Qed.\n\n    Lemma find_pre_Fix_grammar_to_lookup_state (nt : default_nonterminal_carrierT)\n      : PositiveMap.find (nonterminal_to_positive nt) (pre_Fix_grammar initial_nonterminals_data)\n        = if is_valid_nonterminal initial_nonterminals_data nt\n          then Some (lookup_state (pre_Fix_grammar initial_nonterminals_data) nt)\n          else None.\n    Proof.\n      let v := match goal with |- context[if ?v then _ else _] => v end in\n      destruct v eqn:Hvalid.\n      { apply find_pre_Fix_grammar in Hvalid.\n        unfold lookup_state, PositiveMapExtensions.find_default, state in *; simpl in *.\n        edestruct PositiveMap.find;\n          [ reflexivity | congruence ]. }\n      { destruct (PositiveMap.find (nonterminal_to_positive nt) (pre_Fix_grammar (@initial_nonterminals_data _ predata))) eqn:H; [ | reflexivity ].\n        rewrite (proj2 (find_pre_Fix_grammar _)) in Hvalid; congruence. }\n    Qed.\n\n    Lemma lookup_state_invalid_pre_Fix_grammar (nt : default_nonterminal_carrierT)\n          (Hinvalid : is_valid_nonterminal initial_nonterminals_data nt = false)\n      : lookup_state (pre_Fix_grammar initial_nonterminals_data) nt = default_value.\n    Proof.\n      unfold lookup_state, PositiveMapExtensions.find_default.\n      pose proof (find_pre_Fix_grammar nt).\n      rewrite Hinvalid in H; destruct H.\n      unfold state in *; simpl in *.\n      edestruct PositiveMap.find.\n      { intuition congruence. }\n      { reflexivity. }\n    Qed.*)\n  End with_grammar.\nEnd grammar_fixedpoint.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/ContextFreeGrammar/Fix/FixRelated.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.21793647339876898}}
{"text": "Require Import Rel.Definitions.\nRequire Import Lang.BindingsFacts.\nRequire Import Wf_natnat.\nSet Implicit Arguments.\n\nImplicit Types EV HV V L : Set.\n\nSection section_HV_map_aux.\n\nHint Extern 1 => match goal with\n| [ x : ?V |- ∃ _ : ?V, _ ] => exists x ; crush\nend.\n\nLocal Hint Extern 0 => match goal with\n| [ |- ?n ⊨ ?X ⇔ ?X ] => apply auto_contr_id\n| [ |- ?n ⊨ ?X ≈ᵢ ?X ] => repeat iintro ; apply auto_contr_id\n| [ |- Acc lt' (_, _) ] => try lt'_solve\nend.\n\nFixpoint\n  HV_map_𝓥_aux\n  n EV HV HV'\n  (Ξ : XEnv EV HV)\n  (f : HV → HV')\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : HV → hd0) (ρ : HV → IRel 𝓣_Sig)\n  (ρ₁' ρ₂' : HV' → hd0) (ρ' : HV' → IRel 𝓣_Sig)\n  (Hρ₁ : ∀ β : HV, ρ₁ β = ρ₁' (f β))\n  (Hρ₂ : ∀ β : HV, ρ₂ β = ρ₂' (f β))\n  (Hρ : n ⊨ ∀ᵢ β : HV, ρ β ≈ᵢ ρ' (f β))\n  (ξ₁ ξ₂ : list var)\n  (v₁ v₂ : val0) (T : ty EV HV ∅)\n  (W : Acc lt' (n, size_ty T))\n  {struct W} :\n  (n ⊨\n    𝓥⟦ Ξ ⊢ T ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ ⇔\n    𝓥⟦ (HV_map_XEnv f Ξ) ⊢ HV_map_ty f T ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ v₁ v₂)\nwith\n  HV_map_𝓾_aux\n  n EV HV HV'\n  (Ξ : XEnv EV HV)\n  (f : HV → HV')\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : HV → hd0) (ρ : HV → IRel 𝓣_Sig)\n  (ρ₁' ρ₂' : HV' → hd0) (ρ' : HV' → IRel 𝓣_Sig)\n  (Hρ₁ : ∀ β : HV, ρ₁ β = ρ₁' (f β))\n  (Hρ₂ : ∀ β : HV, ρ₂ β = ρ₂' (f β))\n  (Hρ : n ⊨ ∀ᵢ β : HV, ρ β ≈ᵢ ρ' (f β))\n  (ξ₁ ξ₂ : list var)\n  (t₁ t₂ : tm0) (ψ : IRel 𝓣_Sig) l₁ l₂ (ε : ef EV HV ∅)\n  (W : Acc lt' (n, 0))\n  {struct W} :\n  (n ⊨\n    𝓾⟦ Ξ ⊢ ε ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂ ⇔\n    𝓾⟦ (HV_map_XEnv f Ξ) ⊢ HV_map_ef f ε ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂)\nwith\n  HV_map_𝓤_aux\n  n EV HV HV'\n  (Ξ : XEnv EV HV)\n  (f : HV → HV')\n  (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig)\n  (ρ₁ ρ₂ : HV → hd0) (ρ : HV → IRel 𝓣_Sig)\n  (ρ₁' ρ₂' : HV' → hd0) (ρ' : HV' → IRel 𝓣_Sig)\n  (Hρ₁ : ∀ β : HV, ρ₁ β = ρ₁' (f β))\n  (Hρ₂ : ∀ β : HV, ρ₂ β = ρ₂' (f β))\n  (Hρ : n ⊨ ∀ᵢ β : HV, ρ β ≈ᵢ ρ' (f β))\n  (ξ₁ ξ₂ : list var)\n  (t₁ t₂ : tm0) (ψ : IRel 𝓣_Sig) l₁ l₂ (𝓔 : eff EV HV ∅)\n  (W : Acc lt' (n, size_eff 𝓔))\n  {struct W} :\n  (n ⊨\n    𝓤⟦ Ξ ⊢ 𝓔 ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂ ⇔\n    𝓤⟦ (HV_map_XEnv f Ξ) ⊢ HV_map_eff f 𝓔 ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ t₁ t₂ ψ l₁ l₂)\n.\n\nProof.\n{\ndestruct T eqn:HT.\n+ crush.\n+ simpl 𝓥_Fun ; auto_contr.\n  - apply HV_map_𝓥_aux ; auto.\n  - apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro ; auto.\n+ simpl 𝓥_Fun ; auto_contr.\n  replace (EV_shift_XEnv (HV_map_XEnv f Ξ))\n    with (HV_map_XEnv f (EV_shift_XEnv Ξ))\n    by (erewrite EV_HV_map_XEnv ; crush).\n  apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro ; auto.\n+ simpl 𝓥_Fun ; auto_contr.\n  replace (HV_shift_XEnv (HV_map_XEnv f Ξ))\n    with (HV_map_XEnv (map_inc f) (HV_shift_XEnv Ξ))\n    by (repeat erewrite HV_map_map_XEnv ; crush).\n  apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro ; [ |auto].\n  repeat iintro ; apply HV_map_𝓥_aux ; [auto|auto| |auto].\n  iintro β ; destruct β ; simpl ; repeat iintro ; [auto|].\n  iespecialize Hρ ; apply Hρ.\n}\n\n{\ndestruct ε as [ α | [ p | [ | X ] ] ] ; simpl.\n+ auto.\n+ auto_contr.\n  - rewrite Hρ₁, Hρ₂ ; reflexivity.\n  - rewrite Hρ₁, Hρ₂ ; reflexivity.\n  - apply 𝓗_Fun'_nonexpansive ; repeat iintro ; [auto|].\n    iespecialize Hρ ; apply Hρ.\n+ auto.\n+ auto_contr.\n  isplit ; iintro' H.\n  - idestruct H as T H ; idestruct H as 𝓔 H ; idestruct H as HX H.\n    ielim_prop HX ; eapply binds_HV_map in HX.\n    repeat ieexists ; repeat isplit ; [ eauto | ].\n    later_shift.\n    erewrite <- I_iff_elim_M ; [ apply H |].\n    apply 𝓗_Fun'_nonexpansive ; repeat iintro ; [auto|].\n    apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro.\n    { erewrite <- 𝓥_roll_unroll_iff ; auto. }\n    { erewrite <- 𝓤_roll_unroll_iff ; auto. }\n  - idestruct H as T' H ; idestruct H as 𝓔' H ; idestruct H as HX H.\n    ielim_prop HX ; apply binds_HV_map_inv in HX.\n    destruct HX as [ T [ 𝓔 [ HT [ H𝓔 HX ] ] ] ] ; subst.\n    repeat ieexists ; repeat isplit ; [ eauto | ].\n    later_shift.\n    erewrite I_iff_elim_M ; [ apply H | ].\n    apply 𝓗_Fun'_nonexpansive ; repeat iintro ; [auto|].\n    apply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro.\n    { erewrite <- 𝓥_roll_unroll_iff ; auto. }\n    { erewrite <- 𝓤_roll_unroll_iff ; auto. }\n}\n\n{\ndestruct 𝓔 ; simpl.\n+ auto.\n+ auto_contr ; auto.\n}\n\nQed.\n\nEnd section_HV_map_aux.\n\n\nSection section_HV_map.\nContext (n : nat).\nContext (EV HV HV' : Set).\nContext (Ξ : XEnv EV HV).\nContext (f : HV → HV').\nContext (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig).\nContext (ρ₁ ρ₂ : HV → hd0) (ρ : HV → IRel 𝓣_Sig).\nContext (ρ₁' ρ₂' : HV' → hd0) (ρ' : HV' → IRel 𝓣_Sig).\nContext (Hρ₁ : ∀ β : HV, ρ₁ β = ρ₁' (f β)).\nContext (Hρ₂ : ∀ β : HV, ρ₂ β = ρ₂' (f β)).\nContext (Hρ : n ⊨ ∀ᵢ β : HV, ρ β ≈ᵢ ρ' (f β)).\n\nHint Resolve lt'_wf.\n\nLemma HV_map_𝓥 T ξ₁ ξ₂ v₁ v₂ :\nn ⊨\n  𝓥⟦ Ξ ⊢ T ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ ⇔\n  𝓥⟦ (HV_map_XEnv f Ξ) ⊢ HV_map_ty f T ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ v₁ v₂.\nProof.\napply HV_map_𝓥_aux ; auto.\nQed.\n\nLemma HV_map_𝓤 𝓔 ξ₁ ξ₂ t₁ t₂ ψ L₁ L₂ :\nn ⊨\n  𝓤⟦ Ξ ⊢ 𝓔 ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ψ L₁ L₂ ⇔\n  𝓤⟦ (HV_map_XEnv f Ξ) ⊢ HV_map_eff f 𝓔 ⟧ δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ t₁ t₂ ψ L₁ L₂.\nProof.\napply HV_map_𝓤_aux ; auto.\nQed.\n\nHint Resolve HV_map_𝓥 HV_map_𝓤.\n\nLemma HV_map_𝓣 T 𝓔 ξ₁ ξ₂ t₁ t₂ :\nn ⊨\n  𝓣⟦ Ξ ⊢ T # 𝓔 ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ ⇔\n  𝓣⟦ (HV_map_XEnv f Ξ) ⊢ (HV_map_ty f T) # (HV_map_eff f 𝓔) ⟧\n    δ₁ δ₂ δ ρ₁' ρ₂' ρ' ξ₁ ξ₂ t₁ t₂.\nProof.\napply 𝓣_Fun_Fix'_nonexpansive ; repeat iintro ; auto.\nQed.\n\nEnd section_HV_map.\n", "meta": {"author": "yizhouzhang", "repo": "abseff-coq", "sha": "129c08fde2b4e41b5348db397c8a8f0e30f14cb5", "save_path": "github-repos/coq/yizhouzhang-abseff-coq", "path": "github-repos/coq/yizhouzhang-abseff-coq/abseff-coq-129c08fde2b4e41b5348db397c8a8f0e30f14cb5/coq-src/ABS/Rel/Compat_map_HV.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.21793557220554113}}
{"text": "Require Import Coq.Arith.Arith Coq.NArith.BinNat Coq.micromega.Lia Coq.Strings.String\n        Coq.Lists.List Structures.OrdersEx micromega.Lia.\nRequire Import Common.Common.\nRequire Import LambdaBoxLocal.expression.\nRequire Import LambdaANF.algebra LambdaANF.tactics.\n\nOpen Scope alg_scope.\n\n(* Environment semantics values *)\nInductive value :=\n| Con_v : dcon -> list value -> value \n(* | Prf_v : value *)\n| Clos_v : list value -> name -> expression.exp -> value\n| ClosFix_v : list value -> efnlst -> N -> value.\n\nLemma value_ind' (P : value -> Prop) :\n  (forall dcon vs, Forall P vs -> P (Con_v dcon vs)) ->\n  (forall vs na e, Forall P vs -> P (Clos_v vs na e)) ->\n  (forall vs fnl n, Forall P vs -> P (ClosFix_v vs fnl n)) ->\n  (forall v,  P v).\nProof.\n  intros H1 H2 H3.\n  fix IHv 1; intros v. destruct v.\n  - eapply H1. induction l.\n    constructor.\n    constructor. eapply IHv. eassumption.\n  - eapply H2. induction l.\n    constructor.\n    constructor. eapply IHv. eassumption. \n  - eapply H3. induction l.\n    constructor.\n    constructor. eapply IHv. eassumption. \nQed.\n\n(* Definition of env *)\nDefinition env := list value.\n\nInductive result :=\n| Val : value -> result\n| OOT : result.\n\n\n\nFixpoint max_binders_branches (br : branches_e) : nat :=\n  match br with\n  | brnil_e => 0\n  | brcons_e _ (m, _) _ br =>\n    max (N.to_nat m) (max_binders_branches br)\n  end.    \n\n  \nSection LambdaBoxLocal_fuel.\n        \n  Class LambdaBoxLocal_resource {A} :=\n  { HRes :> @resource exp A; }. \n\nEnd LambdaBoxLocal_fuel.\n\nSection Util.\n\n  (** Helper functions for going between exps and lists *)\n\n  Definition make_rec_env_rev_order (fnlst : efnlst) (rho : env) : env :=\n    let fix make_env_aux l :=\n        match l with\n        | nil => rho\n        | cons n l' =>\n          let env' := make_env_aux l' in\n          ((ClosFix_v rho fnlst (N.of_nat n)) :: env')\n        end\n    in\n    make_env_aux (list_to_zero (efnlength fnlst)).\n\n  Lemma enthopt_inlist_Forall (P : exp -> Prop) :\n    forall efnl n e,\n      Forall (fun (p : name * exp) => let (_, e) := p in P e) (efnlst_as_list efnl) ->\n      enthopt (N.to_nat n) efnl = Some e ->\n      P e.\n  Proof.\n    intros efnl n.\n    generalize (N.to_nat n). induction efnl; intros n' e' Hall Hnth.\n    - destruct n'; simpl in Hnth; inv Hnth.\n    - destruct  n'. inv Hnth.\n      + inv Hall. eassumption.\n      + inv Hall. simpl in Hnth. eapply IHefnl.\n        eassumption. eassumption.\n  Qed.\n  \n  Lemma make_rec_env_rev_order_app fns vs :\n    exists vs', make_rec_env_rev_order fns vs = vs' ++ vs /\\\n                List.length vs' = efnlength fns /\\\n                forall n, (n < efnlength fns)%nat ->\n                          nth_error vs' n = Some (ClosFix_v vs fns (N.of_nat (efnlength fns - n - 1))).\n  Proof.\n    unfold make_rec_env_rev_order. generalize (efnlength fns) as m. \n    induction m.\n    - simpl. eexists []. split. reflexivity. split.\n      compute. reflexivity.\n      intros. lia.\n    - destructAll.\n      eexists (ClosFix_v vs fns (N.of_nat (Datatypes.length x)) :: x). simpl.\n      split; [ | split ].\n      + rewrite H. reflexivity.\n      + reflexivity.\n      + intros. destruct n.\n        * simpl. rewrite Nat.sub_0_r. reflexivity.\n        * simpl. eapply H1. lia.\n  Qed.\n  \nEnd Util. \n\nFixpoint add_list {fuel : Type} {Hf : @LambdaBoxLocal_resource fuel} (l : list fuel) : fuel :=\n  match l with\n  | nil => <0>\n  | cons f fs => f <+> add_list fs\n  end.\n\n\nSection FUEL_SEM.\n\n  Inductive Forall3 {A B C : Type} (R : A -> B -> C -> Prop) : list A -> list B -> list C -> Prop :=\n    Forall3_nil : Forall3 R [] [] []\n  | Forall3_cons :\n      forall (x : A) (y : B) (z : C) (l : list A) (l' : list B) (l'' : list C),\n        R x y z -> Forall3 R l l' l'' -> Forall3 R (x :: l) (y :: l') (z :: l'').\n\n  Context {trace : Type} {Hf : @LambdaBoxLocal_resource nat} {Ht : @LambdaBoxLocal_resource trace}.\n\n  \n  (** * {Nat,environment}-based semantics for LambdaBoxLocal *)\n  Inductive eval_env_step: env -> exp -> result -> nat -> trace -> Prop :=\n  | eval_Con_step:\n      forall (es : expression.exps) (vs : list value) (rho: env) (dc: dcon) fs ts,\n        eval_fuel_many rho es vs fs ts ->\n        eval_env_step rho (Con_e dc es) (Val (Con_v dc vs)) fs ts\n  | eval_Con_step_OOT:\n      forall (es es1 es2: expression.exps) (e : exp) (vs : list value) (rho: env) (dc: dcon) fs f t ts,\n        exps_as_list es = exps_as_list es1 ++ e :: exps_as_list es2 ->\n        eval_fuel_many rho es1 vs fs ts ->\n        eval_env_fuel rho e OOT f t ->\n        eval_env_step rho (Con_e dc es) OOT  (fs <+> f) (ts <+> t)\n\n  | eval_App_step:\n      forall (e1 e2 e1': expression.exp) v2 r (na : name) (rho rho': env)\n             f1 f2 f3 t1 t2 t3,\n        eval_env_fuel rho e1 (Val (Clos_v rho' na e1')) f1 t1 ->\n        eval_env_fuel rho e2 (Val v2) f2 t2 ->\n        eval_env_fuel (v2::rho') e1' r f3 t3 ->\n        eval_env_step rho (App_e e1 e2) r (f1 <+> f2 <+> f3) (t1 <+> t2 <+> t3)\n  | eval_App_step_OOT1 :\n      forall (e1 e2 : expression.exp) (rho : env) f1 t1,\n        eval_env_fuel rho e1 OOT f1 t1 ->\n        eval_env_step rho (App_e e1 e2) OOT f1 t1\n  | eval_App_step_OOT2 :\n      forall (e1 e2 : expression.exp) (v : value) (rho : env) f1 f2 t1 t2,\n        eval_env_fuel rho e1 (Val v) f1 t1 ->\n        eval_env_fuel rho e2 OOT f2 t2 ->\n        eval_env_step rho (App_e e1 e2) OOT (f1 <+> f2) (t1 <+> t2)\n\n                      \n  | eval_Let_step:\n      forall (e1 e2 : expression.exp) (v1 : value) (r : result) (rho: env) (na: name) f1 f2 t1 t2,\n        eval_env_fuel rho e1 (Val v1) f1 t1 ->\n        eval_env_fuel (v1::rho) e2 r f2 t2 ->\n        eval_env_step rho (Let_e na e1 e2) r (f1 <+> f2) (t1 <+> t2)\n  | eval_Let_step_OOT:\n      forall (e1 e2 : expression.exp) (rho: env) (na: name) f1 t1,\n        eval_env_fuel rho e1 OOT f1 t1 ->\n        eval_env_step rho (Let_e na e1 e2) OOT f1 t1\n                      \n  | eval_FixApp_step: \n      forall (e1 e2 e': expression.exp) (rho rho' rho'': env) (n: N) (na : name)\n             (fnlst: efnlst) (v2 : value) r f1 f2 f3 t1 t2 t3,\n        eval_env_fuel rho e1 (Val (ClosFix_v rho' fnlst n)) f1 t1 ->\n        enthopt (N.to_nat n) fnlst = Some (Lam_e na e') ->\n        make_rec_env_rev_order fnlst rho' = rho'' ->\n        eval_env_fuel rho e2 (Val v2) f2 t2 ->\n        eval_env_fuel (v2 :: rho'') e' r f3 t3 ->\n        eval_env_step rho (App_e e1 e2) r (f1 <+> f2 <+> f3) (t1 <+> t2 <+> t3)\n                      \n  | eval_Match_step:\n      forall (e1 e': expression.exp) (rho: env) (dc: dcon) (vs: list value)\n             (n: N) (brnchs: branches_e) (r: result) f1 f2 t1 t2,\n        eval_env_fuel rho e1 (Val (Con_v dc vs)) f1 t1 ->\n        find_branch dc (N.of_nat (List.length vs)) brnchs = Some e' ->\n        eval_env_fuel ((List.rev vs) ++ rho) e' r f2 t2 ->\n        eval_env_step rho (Match_e e1 n brnchs) r (f1 <+> f2) (t1 <+> t2)\n  | eval_Match_step_OOT:\n      forall (e1 : expression.exp) (rho: env) (n: N) (br: branches_e) f1 t1,\n        eval_env_fuel rho e1 OOT f1 t1 ->\n        eval_env_step rho (Match_e e1 n br) OOT f1 t1\n\n  with eval_fuel_many: env -> exps -> list value -> nat -> trace -> Prop :=\n  | eval_many_enil :\n      forall rho,\n        eval_fuel_many rho enil [] <0> <0>\n  | eval_many_econs :\n      forall rho e es v vs f fs t ts,\n        eval_env_fuel rho e (Val v) f t ->\n        eval_fuel_many rho es vs fs ts ->\n        eval_fuel_many rho (econs e es) (v :: vs) (f <+> fs) (t <+> ts)\n                      \n  with eval_env_fuel: env -> exp -> result -> nat -> trace -> Prop :=\n  (* Values *) \n  | eval_Var_fuel:\n      forall (x: N) (rho: env) (v: value),\n        nth_error rho (N.to_nat x) = Some v ->\n        eval_env_fuel rho (Var_e x) (Val v) <0> <0>\n  | eval_Lam_fuel:\n      forall (e: expression.exp) (rho:env) (na: name),\n        eval_env_fuel rho (Lam_e na e) (Val (Clos_v rho na e)) <0> (one_i (Lam_e na e))\n  | eval_Fix_fuel:\n      forall (n: N) (rho: env) (fnlst: efnlst),\n        eval_env_fuel rho (Fix_e fnlst n) (Val (ClosFix_v rho fnlst n)) <0> (one_i (Fix_e fnlst n))\n  (* OOT *)\n  | eval_OOT :\n      forall rho (e : exp) f t,\n        (f < one_i e)%nat ->\n        eval_env_fuel rho e OOT f t\n  (* STEP *)\n  | eval_step : (* take a step *)\n      forall rho e r (f : nat) t,\n        eval_env_step rho e r f t ->\n        eval_env_fuel rho e r (f <+> (one_i e)) (t <+> (one_i e)).\n\n  Set Printing All. \n\n  Scheme eval_env_step_ind' := Minimality for eval_env_step Sort Prop\n    with eval_fuel_many_ind' :=  Minimality for eval_fuel_many Sort Prop\n    with eval_env_fuel_ind' := Minimality for eval_env_fuel Sort Prop.\n\n\n  Section WF. \n  \n    Definition well_formed_in_env (e : exp) (rho : list value) :=\n      exp_wf (N.of_nat (length rho)) e.\n\n    \n    Inductive well_formed_val : value -> Prop :=\n    | Wf_Con :\n        forall dc vs,\n          Forall well_formed_val vs ->\n          well_formed_val (Con_v dc vs)\n    | Wf_Clos :\n        forall vs n e,\n          Forall well_formed_val vs -> \n          (forall x, well_formed_in_env e (x :: vs)) ->\n          well_formed_val (Clos_v vs n e)\n    | Wf_ClosFix :\n        forall vs n efns,\n          Forall well_formed_val vs ->\n          n < efnlst_length efns ->\n          Forall (fun (p : name * exp) =>\n                    let (n, e) := p in\n                    isLambda e /\\\n                    exp_wf (efnlst_length efns + (N.of_nat (length vs))) e) (efnlst_as_list efns) ->\n          well_formed_val (ClosFix_v vs efns n).\n\n    \n\n    Definition well_formed_exps_in_env (es : exps) (rho : list value) :=\n      exps_wf (N.of_nat (length rho)) es.\n    \n    Definition well_formed_env (rho : list value) : Prop :=\n      Forall well_formed_val rho.\n\n    Lemma well_formed_in_env_Match_branches:\n      forall e e' bs rho i dc vs f t,\n        eval_env_fuel rho e (Val (Con_v dc vs)) f t ->\n        well_formed_in_env (Match_e e i bs) rho ->\n        find_branch dc (N.of_nat (Datatypes.length vs)) bs = Some e' ->\n        well_formed_in_env e' (rev vs ++ rho).\n    Proof.\n      intros e e' bs rho i d vs f t Heval Hwf H.\n      inv Hwf.\n      unfold well_formed_in_env.\n      rewrite app_length. rewrite Nnat.Nat2N.inj_add.\n      rewrite rev_length. eapply find_branch_preserves_wf; eassumption.\n    Qed.\n\n    Lemma well_formed_envmake_rec_env_rev_order fnlst rho rho' : \n      make_rec_env_rev_order fnlst rho = rho' ->\n      well_formed_env rho ->\n      Forall\n        (fun p : name * exp =>\n           let (_, e) := p in\n           isLambda e /\\\n           exp_wf (efnlst_length fnlst + N.of_nat (Datatypes.length rho)) e)\n        (efnlst_as_list fnlst) ->\n      well_formed_env rho'.\n    Proof.\n      unfold make_rec_env_rev_order.\n      assert (Hlen : N.of_nat (efnlength fnlst) <= efnlst_length fnlst).\n      { rewrite efnlength_efnlst_length. lia. } \n      revert Hlen. generalize fnlst at 2 3 5 6. revert rho rho'.\n      induction fnlst; intros rho rho' fnlst' Hlen Heq Henv Hall; eauto.\n      - simpl in *. subst; eauto.\n      - simpl in *. subst. \n        constructor; eauto.\n        constructor; eauto.\n\n        lia.\n\n        eapply IHfnlst; eauto. lia.\n    Qed.\n           \n\n    Lemma efnlst_wf_isLambda :\n      forall n es e,\n        efnlst_wf n es -> In e (efnlst_as_list es) ->\n        isLambda (snd e) /\\ exp_wf n (snd e).\n    Proof.\n      intros n es e H1 H2.\n      induction es.\n      - inv H2.\n      - inv H1. inv H2.\n        split; eassumption.\n        eapply IHes; try eassumption.\n    Qed.\n\n    \n    Lemma eval_env_step_preserves_wf :\n      forall vs e r f t,\n        eval_env_fuel vs e r f t ->\n        forall v, r = Val v ->\n                  well_formed_env vs ->\n                  well_formed_in_env e vs ->\n                  well_formed_val v.\n    Proof.\n      pose (P := fun (vs : env) (e : exp) (r : result) (f : nat) (t : trace) => \n                   forall v,\n                     r = Val v ->\n                     well_formed_env vs ->\n                     well_formed_in_env e vs ->\n                     well_formed_val v).\n\n      pose (P1 := fun (vs : env) (es : exps) (vs' : list value) (f : nat) (t : trace) => \n                    well_formed_env vs ->\n                    well_formed_exps_in_env es vs ->\n                    Forall well_formed_val vs').\n\n      pose (P2 := fun (vs : env) (e : exp) (r : result) (f : nat) (t : trace) => \n                    forall v,\n                      r = Val v ->\n                      well_formed_env vs ->\n                      well_formed_in_env e vs ->\n                      well_formed_val v).\n\n      intros vs e r f t Heval. \n      eapply eval_env_fuel_ind' with (P := P) (P0 := P1) (P1 := P2);\n      unfold P, P1, P2; intros; try congruence.\n      \n      - inv H1. constructor. inv H3. eapply H0; eauto.\n\n      - subst. inv H7.\n        specialize (H0 _ ltac:(reflexivity) H6 H10).\n        inv H0. eapply H4; eauto.\n        constructor; eauto.\n\n      - subst. inv H5.\n        eapply H2; eauto. constructor; eauto.\n        unfold well_formed_in_env.\n        simpl List.length.\n        replace (N.of_nat (S (Datatypes.length rho))) with (1 + N.of_nat (Datatypes.length rho)) by lia.\n        eassumption.\n\n      - subst. inv H9.\n        specialize (H0 _ ltac:(reflexivity) H8 H11). inv H0.\n        \n        eapply H6; eauto. constructor; eauto.\n        now eapply well_formed_envmake_rec_env_rev_order; eauto.\n        \n        eapply enthopt_inlist_Forall in H14; eauto.\n        inv H14. inv H2.\n\n        unfold well_formed_in_env. simpl List.length.\n        replace (N.of_nat (S (Datatypes.length (make_rec_env_rev_order fnlst rho'))))\n          with (1 + N.of_nat (Datatypes.length (make_rec_env_rev_order fnlst rho'))) by lia.\n\n        edestruct make_rec_env_rev_order_app. destructAll. rewrite H2.\n        rewrite app_length. rewrite Nnat.Nat2N.inj_add.\n        rewrite H7. rewrite efnlength_efnlst_length. eassumption. \n\n      - subst. \n        inv H6. specialize (H0 _ ltac:(reflexivity) H5 H9). inv H0.\n        eapply H3; eauto.\n        eapply Forall_app. split; eauto.\n        eapply Forall_rev; eauto.\n        eapply well_formed_in_env_Match_branches; eauto.\n        constructor; eauto.\n\n      - now constructor.\n\n      - inv H4. constructor; eauto.\n\n      - inv H2. inv H0; eauto.\n        eapply Forall_forall in H1. eassumption.\n        eapply nth_error_In. eassumption.\n\n      - inv H1. inv H. constructor; eauto.\n        intros x. unfold well_formed_in_env.\n        simpl List.length.\n        replace (N.of_nat (S (Datatypes.length rho))) with (1 + N.of_nat (Datatypes.length rho)) by lia.\n        eassumption.\n\n      - inv H. inv H1.\n        constructor; eauto.\n\n        eapply Forall_forall. intros. destruct x. \n        eapply efnlst_wf_isLambda in H. \n        eassumption. eassumption.\n\n      - subst; eauto.\n\n      - eassumption.\n\n        Unshelve. eassumption.\n    Qed. \n\n\n  End WF.\n\n\n  Lemma exps_as_list_append e1 e2 :\n    exps_as_list (exps_append e1 e2) = exps_as_list e1 ++ exps_as_list e2.\n  Proof.\n    induction e1. reflexivity.\n    simpl. rewrite IHe1. reflexivity.\n  Qed.\n\n  (* \n  Lemma fuel_sem_OOT vs e r f f' :\n    eval_env_fuel vs e r f ->\n    lt f' f -> \n    eval_env_fuel vs e OOT f'.\n  Proof.   \n    pose (P := fun (vs : env) (e : exp) (r : result) (f : nat) => \n                 forall f',\n                   lt f' f -> \n                   eval_env_step vs e OOT f').\n    \n    pose (P1 := fun (vs : env) (e : exp) (r : result) (f : nat) => \n                  forall f',\n                    lt f' f -> \n                    eval_env_fuel vs e OOT f').\n    \n    pose (P2 := fun (vs : env) (es : exps) (vs' : list value) (f : nat) =>\n                  forall f',\n                    lt f' f -> \n                    exists es1 e es2 vs1 fs f'',\n                      exps_to_list es = exps_to_list es1 ++ e :: exps_to_list es2 /\\\n                      f' = (fs <+> f'') /\\\n                      eval_fuel_many vs es1 vs1 fs /\\ eval_env_fuel vs e OOT f'').\n    \n    intros Heval. revert f'.\n    eapply eval_env_fuel_ind' with (P := P) (P0 := P2) (P1 := P1);\n      unfold P, P1, P2; intros; try congruence.\n\n    - edestruct H0. eassumption. destructAll. \n      econstructor; eassumption.\n\n    - edestruct (lt_all_dec f' fs).\n      + edestruct H1. eassumption. destructAll. \n        rewrite H6, <- app_assoc in H. simpl in H. \n        econstructor.\n        rewrite H. f_equal. f_equal.\n        replace (e0 :: exps_to_list es2) with (exps_to_list (econs e0 es2)) by reflexivity.\n        rewrite <- exps_to_list_append. reflexivity.\n        eassumption.\n        eassumption.\n\n      + destructAll. rewrite (plus_comm fs) in H4.\n        eapply plus_stable in H4. rewrite plus_comm.\n        econstructor. eassumption. eassumption. \n        eapply H3; eauto.\n\n    - edestruct (lt_all_dec f' f1).\n\n      + eapply eval_App_step_OOT1; eauto.\n\n      + destructAll.\n        rewrite plus_assoc in H5.\n        rewrite !(plus_comm f1) in H5.\n        eapply plus_stable in H5.\n\n        edestruct (lt_all_dec x f2).\n\n        * rewrite plus_comm. eapply eval_App_step_OOT2; eauto.\n\n        * destructAll.\n          rewrite !(plus_comm f2) in H5.\n          eapply plus_stable in H5.\n\n          rewrite plus_assoc. \n          rewrite (plus_comm f2 f1), (plus_comm x0).\n\n          eapply eval_App_step; eauto.\n\n    - eapply eval_App_step_OOT1; eauto.\n\n    - edestruct (lt_all_dec f' f1).\n\n      + eapply eval_App_step_OOT1; eauto.\n\n      + destructAll. rewrite (plus_comm f1) in H3.\n        eapply plus_stable in H3.\n        rewrite plus_comm. \n        eapply eval_App_step_OOT2; eauto.\n\n    - edestruct (lt_all_dec f' f1).\n\n      + eapply eval_Let_step_OOT; eauto.\n\n      + destructAll. rewrite (plus_comm f1) in H3.\n        eapply plus_stable in H3.\n        rewrite plus_comm. \n        eapply eval_Let_step; eauto.\n\n    - eapply eval_Let_step_OOT; eauto.\n\n    - edestruct (lt_all_dec f' f1).\n\n      + eapply eval_App_step_OOT1; eauto.\n\n      + destructAll.\n        rewrite plus_assoc in H7.\n        rewrite !(plus_comm f1) in H7.\n        eapply plus_stable in H7.\n\n        edestruct (lt_all_dec x f2).\n\n        * rewrite plus_comm. eapply eval_App_step_OOT2; eauto.\n\n        * destructAll.\n          rewrite !(plus_comm f2) in H7.\n          eapply plus_stable in H7.\n          \n          rewrite plus_assoc. \n          rewrite (plus_comm f2 f1), (plus_comm x0).\n\n          eapply eval_FixApp_step; eauto.\n\n    - edestruct (lt_all_dec f' f1).\n\n      + eapply eval_Match_step_OOT; eauto.\n\n      + destructAll. \n        rewrite !(plus_comm f1) in H4.\n        eapply plus_stable in H4.\n        rewrite plus_comm. eapply eval_Match_step; eauto.\n\n    - eapply eval_Match_step_OOT; eauto.\n\n    - exfalso. eapply lt_zero; eauto.\n\n    - edestruct (lt_all_dec f' f0).\n\n      + exists enil. do 5 eexists.\n        split. simpl. reflexivity.\n        split. rewrite plus_zero. reflexivity.\n        split. constructor.\n        eauto.\n\n      + destructAll.\n        rewrite !(plus_comm f0) in H3.\n        eapply plus_stable in H3.\n        edestruct H2. eassumption. destructAll.\n\n        exists (econs e0 x0). do 5 eexists. split.\n\n        simpl. rewrite H4. reflexivity. split.\n\n        \n        rewrite (plus_comm _ f0), plus_assoc. reflexivity.\n        split. econstructor; eauto.  eassumption.\n\n    - exfalso. eapply lt_zero; eauto.\n\n    - exfalso. eapply lt_zero; eauto.\n\n    - exfalso. eapply lt_zero; eauto.\n\n    - eapply lt_one in H. subst.\n      exfalso; eapply lt_zero; eauto.\n\n    - edestruct (lt_all_dec f' (one_i e0)).\n\n      + econstructor. eassumption.\n\n      + destructAll.\n        eapply plus_stable in H1.\n        eapply eval_step. eauto.\n\n    - eassumption.\n  Qed. \n\n      \n      \n  Lemma fuel_sem_monotonic vs e f f' :\n    eval_env_fuel vs e OOT f ->\n    lt f' f -> \n    eval_env_fuel vs e OOT f'.\n  Proof.\n    eapply fuel_sem_OOT.\n  Qed.      \n*)     \n  \nEnd FUEL_SEM.\n\n", "meta": {"author": "CertiCoq", "repo": "certicoq", "sha": "2405e1012e9c0a58e49002d9779bb65527d6c323", "save_path": "github-repos/coq/CertiCoq-certicoq", "path": "github-repos/coq/CertiCoq-certicoq/certicoq-2405e1012e9c0a58e49002d9779bb65527d6c323/theories/LambdaBoxLocal/fuel_sem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21785180419547523}}
{"text": "From Coq Require Import Arith ZArith OrderedType.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq.\nFrom nbits Require Import NBits.\nFrom ssrlib Require Import Types SsrOrder Var Nats ZAriths Tactics.\nFrom BitBlasting Require Import Typ TypEnv State QFBV CNF BBCommon AdhereConform.\nFrom BBCache Require Import CompCache Cache.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n\nDefinition init_vm := SSAVM.empty word.\nDefinition init_gen := (var_tt + 1)%positive.\nDefinition init_env : env := fun _ => true.\nDefinition init_ccache : compcache := CompCache.empty.\nDefinition init_cache : cache := Cache.empty.\n\nLemma init_newer_than_vm :\n  newer_than_vm init_gen init_vm.\nProof.\n  done.\nQed.\n\nLemma init_newer_than_tt :\n  newer_than_lit init_gen lit_tt.\nProof.\n  done.\nQed.\n\nLemma init_tt :\n  interp_lit init_env lit_tt.\nProof.\n  done.\nQed.\n\nLemma init_consistent :\n  forall s, consistent init_vm init_env s.\nProof.\n  move=> s x. rewrite /consistent1 /init_vm. rewrite SSAVM.Lemmas.empty_o. done.\nQed.\n\nLemma init_vm_adhere :\n  forall te, AdhereConform.adhere init_vm te .\nProof.\n  done.\nQed.\n\nLemma init_ccache_well_formed :\n  CompCache.well_formed init_ccache.\nProof.\n  done.\nQed.\n\nLemma init_newer_than_cache :\n  newer_than_cache init_gen init_ccache.\nProof.\n  done.\nQed.\n\nLemma init_interp_cache :\n  CompCache.interp_cache init_env init_ccache.\nProof.\n  done.\nQed.\n\nLemma init_correct :\n  forall m, correct m init_ccache.\nProof.\n  done.\nQed.\n\nLemma init_bound_cache :\n  CompCache.bound init_ccache init_vm.\nProof.\n  done.\nQed.\n\nLemma init_interp_cache_ct :\n  forall E, interp_cache_ct E init_ccache.\nProof.\n  done.\nQed.\n\nLemma init_compatible :\n  compatible init_cache init_ccache.\nProof.\n  done.\nQed.\n", "meta": {"author": "fmlab-iis", "repo": "coq-qfbv", "sha": "0e9521febd1564747723a773d25e54781e81b762", "save_path": "github-repos/coq/fmlab-iis-coq-qfbv", "path": "github-repos/coq/fmlab-iis-coq-qfbv/coq-qfbv-0e9521febd1564747723a773d25e54781e81b762/src/bbcache/BitBlastingInit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21753919042074682}}
{"text": "Add LoadPath \"/home/user/0my/GITHUB/VerifiedMathFoundations/library\".\nRequire Import Coq.Structures.Equalities.\nRequire PredicateCalculus.\nRequire Terms.\n\n(*UsualDecidableTypeFull)*)\nModule nat_is_UDTF .\nDefinition t :=nat.\nDefinition SetVars:=nat.\nEnd nat_is_UDTF.\n\nModule SetVars := PeanoNat.Nat.\nModule FuncSymb := PeanoNat.Nat.\nModule PredSymb := PeanoNat.Nat.\nModule eexampl := \nPredicateCalculus.Soundness_mod SetVars FuncSymb PredSymb.\n(*Module eexampl := \nPredicateCalculus.Soundness_mod PeanoNat.Nat PeanoNat.Nat PeanoNat.Nat.*)\n\nModule counterexample.\nExport eexampl.\n(*\nPrint SetVars.\nPrint FuncSymb.\nCheck FSV.\n*)\n(*Print eexampl.FSV.*)\n\n(*Module example1 : Terms.terms_mod PeanoNat.Nat (*nat_is_UDTF*).*)\n(*Definition FuncSymb := nat.\nRecord FSV := {\n fs : FuncSymb;\n fsv : nat;\n}.*)\n(*Definition SetVars:=nat.*)\n(*Notation  SetVars:=nat.\nCheck PeanoNat.Nat.t.\nNotation SetVars := SetVars.t.\nCheck example0.t.\n(*Notation SetVars := PeanoNat.Nat.t.*)\nUnset Elimination Schemes.\nInductive Terms : Type :=\n| FVC :> SetVars -> Terms\n| FSC (f:FSV) : (Vector.t Terms (fsv f)) -> Terms.\nSet Elimination Schemes.\n*)\n\n(* TODO: add *)\n\n(* OK!\nPrint Fo.\nCheck Atom.\nPrint PSV.\nCheck Atom (MPSV 0 2).\nPrint Terms.\nCheck Atom (MPSV 0 2).\nPrint Vector.t.\nCheck Vector.cons _ (FVC 1) _ (Vector.cons _ (FVC 0) _ (Vector.nil _ )).\nCheck Atom (MPSV 0 2)\n(Vector.cons _ (FVC 1) _ (Vector.cons _ (FVC 0) _ (Vector.nil _ ))).\n*)\n\nDefinition xeqy := Atom (MPSV 0 2) \n(Vector.cons _ (FVC 1) _ (Vector.cons _ (FVC 0) _ (Vector.nil _ ))).\n\nTheorem upr : PREPR (xeqy::nil) (Fora 2 xeqy).\nProof.\napply GEN_E.\napply hyp_E.\nsimpl.\napply inl.\nreflexivity.\nDefined.\n(* COUNTEREXAMPLE*)\n(* PR is from provability, but it is better to call it derivability.*)\nSection cor.\nContext (X:Type).\nContext (fsI:forall(q:FSV),(Vector.t X (fsv q))->X).\nContext (prI:forall(q:PSV),(Vector.t X (psv q))->Omega).\n(*Arguments foI X fsI prI .\nPrint Implicit foI.\nCheck foI.*)\nDefinition foIn := @foI X fsI prI.\nTheorem badcorrect (x1 x2 : X) (nequ : ~(x1=x2))\n(f:Fo) (l:list Fo) (m : PREPR l f) :\n~ (forall(val:SetVars.t->X) (lfi : forall h:Fo, (InL h l)->(foIn val h)), foIn val f).\nProof.\nintro H.\nassert (val:SetVars.t->X).\n intro n. destruct n eqn:nn. exact x1.\n(*          destruct s eqn:ss. exact x2. exact x2.*)\nAbort.\nEnd cor.\n\nEnd counterexample.\n\n(* IT IS NOT POSSIBLE TO PROVE THIS THEOREM:\nFixpoint correct (f:Fo) (l:list Fo) (val:SetVars->X) (m:PR l f) \n(lfi : forall h:Fo, (InL h l)->(foI val h)) {struct m}: foI val f.\nProof.\nrevert val lfi.\ninduction m (* eqn: meq *); intros val lfi.\n+ exact (lfi A i).\n+ simpl.\n  intros a b.\n  exact a.\n+ simpl.\n  intros a b c.\n  exact (a c (b c)).\n+ simpl in *|-*.\n  destruct (substF t xi ph) eqn: j.\n  apply (UnivInst ph val xi t f j).\n  simpl. firstorder.\n+ simpl in *|-*.\n  unfold OImp.\n  intros H0 H1 m.\n  apply H0.\n  rewrite -> (NPthenNCACVF xi ps0 m val H).\n  exact H1.\n+ simpl in * |- *.\n  unfold OImp in IHm2.\napply IHm2.\napply lfi.\napply IHm1.\napply lfi. (*  exact (IHm2 IHm1).*)\n+ simpl in * |- *.\n  intro m0.\napply IHm.\nintros h B.\nunfold InL in B.\n(*Check correct A l val m lfi.*)\nCheck NPthenNCACVF xi ps0 m val H.\n  destruct (substF t xi ph) eqn: j.\n  apply (UnivInst ph val xi t f j).\n  simpl. firstorder.\n\n*)\n\n\n(* old trash\nunfold InL in B.\n(*Check correct A l val m lfi.*)\nCheck NPthenNCACVF xi ps0 m val H.\n  destruct (substF t xi ph) eqn: j.\n  apply (UnivInst ph val xi t f j).\n  simpl. firstorder.\n\n\n\n  2 : { simpl. trivial. unfold OImp. firstorder. }\n  apply (correct _ l).\n  2 : {assumption. }\n  simpl.\nCheck fun pi => UnivInst ph pi xi t f j. \n(*forall pi : SetVars -> X, foI pi (Impl (Fora xi ph) f)*)\nShow Proof.\nCheck PR.\npose (Z:=(@Ded (Fora xi ph) f l )).\nsimple refine (Z _ _ ).\nCheck correct.\napply correct.\n2 : { \nintros.\nCheck notGenWith.\nsimpl.\n(*\n  pose (W:= lfi f).\n  destruct (Nat.eqb r xi).\n  simpl in H.\n  exact H.\n  unfold foI. \n  simpl.\n*)\nAbort. *)\n\n(*TRASH\nModule Type exVS (X: Terms.terms_mod).\nCheck X.FuncSymb.\nPrint X.FSV.\nEnd exVS.\n\nModule example2 : exVS example1.\n\nCheck example1.FuncSymb.\nPrint Fo.\n\n(*Check newt.PR.*)\n\nEnd example2.\n\n\nModule example2_1 : exVS.\nModule X := example1.\nImport X.\nEnd example2_1.\n\n\nModule Type newt (v:PredicateCalculus.VS).\n\n*)", "meta": {"author": "georgydunaev", "repo": "VerifiedMathFoundations", "sha": "784e295591e3f36164732aa65a8a42a5ac0ca827", "save_path": "github-repos/coq/georgydunaev-VerifiedMathFoundations", "path": "github-repos/coq/georgydunaev-VerifiedMathFoundations/VerifiedMathFoundations-784e295591e3f36164732aa65a8a42a5ac0ca827/cexamp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2175391846438568}}
{"text": "Require Import floyd.proofauto.\nImport ListNotations.\nLocal Open Scope logic.\n\nRequire Import hmacdrbg.hmac_drbg.\nRequire Import hmacdrbg.HMAC256_DRBG_functional_prog.\nRequire Import hmacdrbg.DRBG_functions.\nRequire Import hmacdrbg.HMAC_DRBG_algorithms.\nRequire Import hmacdrbg.entropy.\nRequire Import sha.protocol_spec_hmac. \nRequire Import sha.general_lemmas.\nRequire Import sha.HMAC256_functional_prog.\n\n(* mocked_md *)\nRequire Import sha.spec_sha.\nRequire Import floyd.library.\n\nRequire Import hmacdrbg.hmac_drbg_compspecs.\n\nDeclare Module UNDER_SPEC : HMAC_ABSTRACT_SPEC.\nDefinition mdstate: Type := (val * (val * val))%type.\n\nDefinition md_info_state: Type := val%type.\n\nDefinition t_struct_md_ctx_st := Tstruct _mbedtls_md_context_t noattr.\n\nDefinition md_relate (h: UNDER_SPEC.HABS) (r:mdstate) :=\n  UNDER_SPEC.REP h (snd (snd r)).\n\nDefinition md_full (key: list Z) (r:mdstate) :=\n  UNDER_SPEC.FULL key (snd (snd r)).\n\nDefinition md_empty (r:mdstate) := \n  UNDER_SPEC.EMPTY (snd (snd r)).\n\nLemma FULL_isptr k q:\n  UNDER_SPEC.FULL k q = !!isptr q && UNDER_SPEC.FULL k q.\nProof.\napply pred_ext.\n+ apply andp_right; trivial. apply UNDER_SPEC.FULL_isptr.\n+ entailer!.\nQed.\n\nLemma EMPTY_isptr q:\n  UNDER_SPEC.EMPTY q = !!isptr q && UNDER_SPEC.EMPTY q.\nProof.\napply pred_ext.\n+ apply andp_right; trivial. apply UNDER_SPEC.EMPTY_isptr.\n+ entailer!.\nQed.\n\nLemma REP_isptr abs q:\n  UNDER_SPEC.REP abs q = !!isptr q && UNDER_SPEC.REP abs q.\nProof.\ndestruct abs.\napply pred_ext.\n+ apply andp_right; trivial. apply UNDER_SPEC.REP_isptr.\n+ entailer!.\nQed. \n\nDefinition md_free_spec :=\n DECLARE _mbedtls_md_free\n  WITH ctx:val, r:mdstate\n  PRE  [ _ctx OF tptr (Tstruct _mbedtls_md_context_t noattr) ]\n       PROP() \n       LOCAL(temp _ctx ctx) \n       SEP (data_at Tsh t_struct_md_ctx_st r ctx;\n            UNDER_SPEC.EMPTY (snd (snd r)); \n            malloc_token Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) (snd (snd r)))\n  POST [ tvoid ] \n    SEP (data_at Tsh t_struct_md_ctx_st r ctx).\n\nDefinition mbedtls_zeroize_spec :=\n  DECLARE _mbedtls_zeroize\n   WITH n: Z, v:val\n    PRE [_v OF tptr tvoid, _n OF tuint ] \n       PROP (0<=n<= Int.max_unsigned)\n       LOCAL (temp _n (Vint (Int.repr n)); temp _v v)\n       SEP (data_at_ Tsh (tarray tuchar n ) v)\n    POST [ tvoid ]\n       SEP (data_block Tsh (list_repeat (Z.to_nat n) 0) v).\n\nDefinition drbg_memcpy_spec :=\n  DECLARE _memcpy\n   WITH sh : share*share, p: val, q: val, n: Z, contents: list int \n   PRE [ 1%positive OF tptr tvoid, 2%positive OF tptr tvoid, 3%positive OF tuint ]\n       PROP (readable_share (fst sh); writable_share (snd sh); 0 <= n <= Int.max_unsigned)\n       LOCAL (temp 1%positive p; temp 2%positive q; temp 3%positive (Vint (Int.repr n)))\n       SEP (data_at (fst sh) (tarray tuchar n) (map Vint contents) q;\n              memory_block (snd sh) n p)\n    POST [ tptr tvoid ]\n       PROP() LOCAL(temp ret_temp p)\n       SEP(data_at (fst sh) (tarray tuchar n) (map Vint contents) q;\n             data_at (snd sh) (tarray tuchar n) (map Vint contents) p).\n\nDefinition drbg_memset_spec :=\n  DECLARE _memset\n   WITH sh : share, p: val, n: Z, c: int \n   PRE [ 1%positive OF tptr tvoid, 2%positive OF tint, 3%positive OF tuint ]\n       PROP (writable_share sh; 0 <= n <= Int.max_unsigned)\n       LOCAL (temp 1%positive p; temp 2%positive (Vint c);\n                   temp 3%positive (Vint (Int.repr n)))\n       SEP (memory_block sh n p)\n    POST [ tptr tvoid ]\n       PROP() LOCAL(temp ret_temp p)\n       SEP(data_at sh (tarray tuchar n) (list_repeat (Z.to_nat n) (Vint c)) p).\n(*This results in using sha's compspecs\nDefinition drbg_memset_spec := (_memset, snd spec_sha.memset_spec). \nDefinition drbg_memcpy_spec := (_memcpy, snd spec_sha.memcpy_spec). \n*)\n\nDefinition md_get_size_spec :=\n  DECLARE _mbedtls_md_get_size\n   WITH u:unit\n   PRE [ _md_info OF tptr (Tstruct _mbedtls_md_info_t noattr)]\n         PROP ()\n         LOCAL ()\n         SEP ()\n  POST [ tuchar ] \n     PROP ()\n     LOCAL (temp ret_temp (Vint (Int.repr (32 (*Z.of_nat SHA256.DigestLength*)))))\n     SEP ().\n\nDefinition md_reset_spec :=\n  DECLARE _mbedtls_md_hmac_reset\n   WITH c : val, r: mdstate, key:list Z, kv:val\n   PRE [ _ctx OF tptr (Tstruct _mbedtls_md_context_t noattr)]\n         PROP ()\n         LOCAL (temp _ctx c; gvar sha._K256 kv)\n         SEP (UNDER_SPEC.FULL key (snd (snd r)); \n              data_at Tsh (Tstruct _mbedtls_md_context_t noattr) r c; K_vector kv)\n  POST [ tint ] \n     PROP ()\n     LOCAL (temp ret_temp (Vint (Int.zero)))\n     SEP (md_relate (UNDER_SPEC.hABS key nil) r;\n          data_at Tsh (Tstruct _mbedtls_md_context_t noattr) r c;\n          K_vector kv).\n\nDefinition md_starts_spec :=\n  DECLARE _mbedtls_md_hmac_starts\n   WITH c : val, r: mdstate, l:Z, key:list Z, kv:val, b:block, i:Int.int\n   PRE [ _ctx OF tptr t_struct_md_ctx_st,\n         _key OF tptr tuchar,\n         _keylen OF tuint ]\n         PROP (sha.spec_hmac.has_lengthK l key; Forall isbyteZ key)\n         LOCAL (temp _ctx c; temp _key (Vptr b i); temp _keylen (Vint (Int.repr l));\n                gvar sha._K256 kv)\n         SEP (UNDER_SPEC.EMPTY (snd (snd r));\n              data_at Tsh t_struct_md_ctx_st r c;\n              data_at Tsh (tarray tuchar (Zlength key)) (map Vint (map Int.repr key)) (Vptr b i); K_vector kv)\n  POST [ tint ] \n     PROP (Forall isbyteZ key)\n     LOCAL (temp ret_temp (Vint (Int.zero)))\n     SEP (md_relate (UNDER_SPEC.hABS key nil) r;\n          data_at Tsh t_struct_md_ctx_st r c;\n          data_at Tsh (tarray tuchar (Zlength key)) (map Vint (map Int.repr key)) (Vptr b i);\n          K_vector kv).\n\nDefinition md_update_spec :=\n  DECLARE _mbedtls_md_hmac_update\n   WITH key: list Z, c : val, r:mdstate, d:val, data:list Z, data1:list Z, kv:val\n   PRE [ _ctx OF tptr t_struct_md_ctx_st, \n         _input OF tptr tuchar, \n         _ilen OF tuint]\n         PROP (0 <= Zlength data1 <= Int.max_unsigned;\n               Zlength data1 + Zlength data + 64 < two_power_pos 61;\n               Forall isbyteZ data1)\n         LOCAL (temp _ctx c; temp _input d; temp  _ilen (Vint (Int.repr (Zlength data1)));\n                gvar sha._K256 kv)\n         SEP(md_relate (UNDER_SPEC.hABS key data) r;\n             data_at Tsh t_struct_md_ctx_st r c;\n             data_at Tsh (tarray tuchar (Zlength data1)) (map Vint (map Int.repr data1)) d; K_vector kv)\n  POST [ tint ] \n          PROP (Forall isbyteZ data1) \n          LOCAL (temp ret_temp (Vint (Int.zero)))\n          SEP(md_relate (UNDER_SPEC.hABS key (data ++ data1)) r;\n              data_at Tsh t_struct_md_ctx_st r c; \n              data_at Tsh (tarray tuchar (Zlength data1)) (map Vint (map Int.repr data1)) d; K_vector kv).\n\nDefinition md_final_spec :=\n  DECLARE _mbedtls_md_hmac_finish\n   WITH data:list Z, key:list Z, c : val, r:mdstate, md:val, shmd: share, kv:val\n   PRE [ _ctx OF tptr t_struct_md_ctx_st,\n         _output OF tptr tuchar ]\n       PROP (writable_share shmd) \n       LOCAL (temp _output md; temp _ctx c;\n              gvar sha._K256 kv)\n       SEP((md_relate (UNDER_SPEC.hABS key data) r);\n           (data_at Tsh t_struct_md_ctx_st r c);\n           (K_vector kv);\n           (memory_block shmd 32 md))\n  POST [ tint ] \n          PROP (Forall isbyteZ (HMAC256 data key)) \n          LOCAL (temp ret_temp (Vint (Int.zero)))\n          SEP(K_vector kv;\n              UNDER_SPEC.FULL key (snd (snd r));\n              data_at Tsh t_struct_md_ctx_st r c;\n              data_at shmd (tarray tuchar (Zlength (HMAC256 data key))) (map Vint (map Int.repr (HMAC256 data key))) md).\n\nDefinition md_setup_spec :=\n  DECLARE _mbedtls_md_setup\n   WITH md_ctx : mdstate, c:val, h:val, info:val\n   PRE [ _ctx OF tptr (Tstruct _mbedtls_md_context_t noattr),\n         _md_info OF tptr (Tstruct _mbedtls_md_info_t noattr),\n         _hmac OF tint]\n       PROP () \n       LOCAL (temp _md_info info; temp _ctx c; temp _hmac h)\n       SEP(data_at Tsh (Tstruct _mbedtls_md_context_t noattr) md_ctx c)\n  POST [ tint ] EX r:_,\n          PROP (r=0 \\/ r=-20864) \n          LOCAL (temp ret_temp (Vint (Int.repr r)))\n          SEP( \n              if zeq r 0\n              then (EX p:_, !!malloc_compatible (sizeof (Tstruct _hmac_ctx_st noattr)) p && \n                              memory_block Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n                              malloc_token Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n                              data_at Tsh (Tstruct _mbedtls_md_context_t noattr) (info, (fst(snd md_ctx), p)) c)\n              else data_at Tsh (Tstruct _mbedtls_md_context_t noattr) md_ctx c).\n(* end mocked_md *)\n\nInductive hmac256drbgabs :=\n  HMAC256DRBGabs: forall (key: list Z) (V: list Z) (reseed_counter entropy_len: Z) (prediction_resistance: bool) (reseed_interval: Z), hmac256drbgabs.\n\nDefinition hmac256drbgstate: Type := (mdstate * (list val * (val * (val * (val * val)))))%type.\n\nDefinition hmac256drbg_relate (a: hmac256drbgabs) (r: hmac256drbgstate) : mpred :=\n  match a with HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval =>\n               match r with (md_ctx', (V', (reseed_counter', (entropy_len', (prediction_resistance', reseed_interval'))))) =>\n                            md_full key md_ctx'\n                                      && !! (\n                                        map Vint (map Int.repr V) = V'\n                                        /\\ Zlength V = 32 /\\ Forall isbyteZ V\n                                        /\\ Vint (Int.repr reseed_counter) = reseed_counter'\n                                        /\\ Vint (Int.repr entropy_len) = entropy_len'\n                                        /\\ Vint (Int.repr reseed_interval) = reseed_interval'\n                                        /\\ Val.of_bool prediction_resistance = prediction_resistance'\n                                      )\n               end\n  end.\n\nDefinition hmac256drbgstate_md_FULL key (r: hmac256drbgstate) : mpred :=\n  md_full key (fst r).\n\nDefinition hmac256drbgabs_entropy_len (a: hmac256drbgabs): Z :=\n  match a with HMAC256DRBGabs _ _ _ entropy_len _ _ => entropy_len end.\n\nDefinition hmac256drbgabs_value (a: hmac256drbgabs): list Z :=\n  match a with HMAC256DRBGabs _ V _ _ _ _ => V end.\n\nDefinition hmac256drbgabs_key (a: hmac256drbgabs): list Z :=\n  match a with HMAC256DRBGabs key _ _ _ _ _ => key end.\n\nDefinition hmac256drbgabs_prediction_resistance (a: hmac256drbgabs): bool :=\n  match a with HMAC256DRBGabs _ _ _ _ pr _ => pr end.\n\nDefinition hmac256drbgabs_reseed_counter (a: hmac256drbgabs): Z :=\n  match a with HMAC256DRBGabs _ _ reseed_counter _ _ _ => reseed_counter end.\n\nDefinition hmac256drbgabs_reseed_interval (a: hmac256drbgabs): Z :=\n  match a with HMAC256DRBGabs _ _ _ _ _ reseed_interval => reseed_interval end.\n\nDefinition hmac256drbgabs_increment_reseed_counter (a: hmac256drbgabs): hmac256drbgabs :=\n  match a with HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval => HMAC256DRBGabs key V (reseed_counter + 1) entropy_len prediction_resistance reseed_interval end.\n\nDefinition hmac256drbgabs_update_value (a: hmac256drbgabs) (new_value: list Z): hmac256drbgabs :=\n  match a with HMAC256DRBGabs key _ reseed_counter entropy_len prediction_resistance reseed_interval => HMAC256DRBGabs key new_value reseed_counter entropy_len prediction_resistance reseed_interval end.\n\nDefinition hmac256drbgabs_update_key (a: hmac256drbgabs) (new_key: list Z): hmac256drbgabs :=\n  match a with HMAC256DRBGabs _ V reseed_counter entropy_len prediction_resistance reseed_interval => HMAC256DRBGabs new_key V reseed_counter entropy_len prediction_resistance reseed_interval end.\n\nDefinition hmac256drbgabs_update_reseed_counter (a: hmac256drbgabs) (new_counter: Z): hmac256drbgabs :=\n  match a with HMAC256DRBGabs key V _ entropy_len prediction_resistance reseed_interval => HMAC256DRBGabs key V new_counter entropy_len prediction_resistance reseed_interval end.\n\nDefinition hmac256drbgabs_metadata_same (a: hmac256drbgabs) (b: hmac256drbgabs): Prop :=\n  match a with HMAC256DRBGabs _ _ reseed_counter entropy_len prediction_resistance reseed_interval =>\n               match b with HMAC256DRBGabs _ _ reseed_counter' entropy_len' prediction_resistance' reseed_interval' =>\n                            reseed_counter = reseed_counter'\n                            /\\ entropy_len = entropy_len'\n                            /\\ prediction_resistance = prediction_resistance'\n                            /\\ reseed_interval = reseed_interval'\n               end\n  end.\n\nDefinition hmac256drbgabs_of_state_handle (a: DRBG_state_handle) entropy_len reseed_interval: hmac256drbgabs :=\n  match a with ((V, key, reseed_counter),_, prediction_resistance) =>\n               HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval\n  end.\n\nDefinition hmac256drbgabs_to_state_handle (a: hmac256drbgabs): DRBG_state_handle :=\n  match a with HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval =>\n               ((V, key, reseed_counter), 32(*256*) (* security strength, not used *), prediction_resistance)\n  end.\n\nDefinition hmac256drbgstate_md_info_pointer (a: hmac256drbgstate): val := fst (fst a).\n\nDefinition t_struct_mbedtls_md_info := Tstruct _mbedtls_md_info_t noattr.\n\nDefinition t_struct_hmac256drbg_context_st := Tstruct _mbedtls_hmac_drbg_context noattr.\n\nDefinition hmac256drbgabs_to_state (a: hmac256drbgabs) (old: hmac256drbgstate):hmac256drbgstate :=\n  match a with HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval =>\n               match old with (md_ctx', _) =>\n                            (md_ctx', (map Vint (map Int.repr V), (Vint (Int.repr reseed_counter), (Vint (Int.repr entropy_len), (Val.of_bool prediction_resistance, Vint (Int.repr reseed_interval))))))\n               end\n  end.\n\nDefinition hmac256drbgabs_common_mpreds (final_state_abs: hmac256drbgabs) (old_state: hmac256drbgstate) (ctx: val) (info_contents: reptype t_struct_mbedtls_md_info): mpred :=\n                  let st := hmac256drbgabs_to_state final_state_abs old_state in\n                  (data_at Tsh t_struct_hmac256drbg_context_st st ctx) *\n                  (data_at Tsh t_struct_mbedtls_md_info info_contents (hmac256drbgstate_md_info_pointer st)) *\n                  (hmac256drbg_relate final_state_abs st).\n\nDefinition hmac256drbgabs_hmac_drbg_update (a:hmac256drbgabs) (additional_data: list Z): hmac256drbgabs :=\n  match a with HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval =>\n               let (key', V') := HMAC256_DRBG_update additional_data key V in\n               HMAC256DRBGabs key' V' reseed_counter entropy_len prediction_resistance reseed_interval\n  end.\n\nDefinition da_emp sh t v p := !! (p = nullval) && emp || \n                              !!(sizeof t > 0) && data_at sh t v p. (*in particular: weak_valid_ptr p in RHS case*)\n\n\nDefinition contents_with_add additional add_len contents:list Z := \n  if (andb (negb (eq_dec additional nullval)) (negb (eq_dec add_len 0))) then contents else [].\n\nDefinition hmac_drbg_update_spec :=\n  DECLARE _mbedtls_hmac_drbg_update\n   WITH contents: list Z,\n        additional: val, add_len: Z,\n        ctx: val, initial_state: hmac256drbgstate,\n        initial_state_abs: hmac256drbgabs,\n        kv: val, info_contents: md_info_state\n     PRE [ _ctx OF (tptr t_struct_hmac256drbg_context_st),\n           _additional OF (tptr tuchar), _add_len OF tuint ]\n       PROP (\n         0 <= add_len <= Int.max_unsigned;\n         Zlength (hmac256drbgabs_value initial_state_abs) = 32 (*Z.of_nat SHA256.DigestLength*);\n         add_len = Zlength contents \\/ add_len = 0;\n         Forall isbyteZ (hmac256drbgabs_value initial_state_abs);\n         Forall isbyteZ contents\n       )\n       LOCAL (temp _ctx ctx;\n              temp _additional additional;\n              temp _add_len (Vint (Int.repr add_len));\n              gvar sha._K256 kv)\n       SEP (\n         da_emp Tsh (tarray tuchar (Zlength contents)) (map Vint (map Int.repr contents)) additional;\n         data_at Tsh t_struct_hmac256drbg_context_st initial_state ctx;\n         hmac256drbg_relate initial_state_abs initial_state;\n         data_at Tsh t_struct_mbedtls_md_info\n                  info_contents (hmac256drbgstate_md_info_pointer initial_state);\n         K_vector kv)\n    POST [ tvoid ]\n       PROP (\n         )\n       LOCAL ()\n       SEP (\n         hmac256drbgabs_common_mpreds\n            (hmac256drbgabs_hmac_drbg_update initial_state_abs \n               (contents_with_add additional add_len contents))\n            initial_state ctx info_contents;\n         da_emp Tsh (tarray tuchar (Zlength contents)) (map Vint (map Int.repr contents)) additional;\n         K_vector kv).\n\nDefinition mbedtls_HMAC256_DRBG_reseed_function (entropy_stream: ENTROPY.stream) (a:hmac256drbgabs)\n           (additional_input: list Z): ENTROPY.result DRBG_state_handle :=\n  match a with HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval =>\n               let sec_strength:Z := 32 (*not used -- measured in bytes, since that's how the calculations in DRBG_instantiate_function work *) in\n               let state_handle: DRBG_state_handle := ((V, key, reseed_counter), sec_strength, prediction_resistance) in\n               let max_additional_input_length := 256 \n               in HMAC256_DRBG_reseed_function entropy_len entropy_len max_additional_input_length \n                     entropy_stream state_handle prediction_resistance additional_input\n  end.\n\nDefinition hmac256drbgabs_reseed (a: hmac256drbgabs) (s: ENTROPY.stream) (additional_data: list Z) : hmac256drbgabs :=\n  match a with HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval =>\n               match (mbedtls_HMAC256_DRBG_reseed_function s a additional_data) with\n                 | ENTROPY.success ((V', key', reseed_counter'), _, pr') _ =>\n                   HMAC256DRBGabs key' V' reseed_counter' entropy_len pr' reseed_interval\n                 | ENTROPY.error _ _ => a\n               end\n  end.\n\nDefinition get_stream_result {X} (result: ENTROPY.result X): ENTROPY.stream :=\n  match result with\n    | ENTROPY.success _ s => s\n    | ENTROPY.error _ s => s\n  end.\n\nDefinition result_success {X} (result: ENTROPY.result X): Prop :=\n  match result with\n    | ENTROPY.success _ _ => True\n    | ENTROPY.error _ _ => False\n  end.\n\nParameter ENT_GenErr: Z.\nParameter ENT_GenErrAx: Vzero <> Vint (Int.repr ENT_GenErr)  /\\ Int.repr ENT_GenErr <> Int.repr (-20864).\n\nDefinition return_value_relate_result {X} (result: ENTROPY.result X) (ret_value: val): Prop :=\n  match result with\n    | ENTROPY.error e _ => match e with\n                             | ENTROPY.generic_error => ret_value = Vint (Int.repr ENT_GenErr) (*WAS: ret_value <> Vzero*)\n                             | ENTROPY.catastrophic_error => ret_value = Vint (Int.repr (-9))\n                           end\n    | ENTROPY.success _ _ => ret_value = Vzero\n  end.\n\nParameter Stream: ENTROPY.stream -> mpred.\n\nDefinition reseedPOST rv contents additional add_len s\n          initial_state_abs ctx\n          info_contents kv (initial_state: reptype t_struct_hmac256drbg_context_st):=\n  if ((zlt 256 add_len) || (zlt 384 (hmac256drbgabs_entropy_len initial_state_abs + add_len)))%bool\n  then (!!(rv = Vint (Int.neg (Int.repr 5))) &&\n       (da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional *\n         data_at Tsh t_struct_hmac256drbg_context_st initial_state ctx *\n         hmac256drbg_relate initial_state_abs initial_state *\n         data_at Tsh t_struct_mbedtls_md_info info_contents (hmac256drbgstate_md_info_pointer initial_state) *\n         Stream s * K_vector kv))\n  else (!!(return_value_relate_result (mbedtls_HMAC256_DRBG_reseed_function s initial_state_abs \n            (contents_with_add additional add_len contents)) rv)\n        && (hmac256drbgabs_common_mpreds (hmac256drbgabs_reseed initial_state_abs s \n             (contents_with_add additional add_len contents)) initial_state ctx info_contents *\n         da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional *\n         Stream (get_stream_result (mbedtls_HMAC256_DRBG_reseed_function s initial_state_abs (contents_with_add additional add_len contents))) *\n         spec_sha.K_vector kv)).\n\n(*384 equals MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT*)\n\nDefinition hmac_drbg_reseed_spec :=\n  DECLARE _mbedtls_hmac_drbg_reseed\n   WITH contents: list Z,\n        additional: val, add_len: Z,\n        ctx: val, initial_state: hmac256drbgstate,\n        initial_state_abs: hmac256drbgabs,\n        kv: val, info_contents: md_info_state,\n        s: ENTROPY.stream\n    PRE [ _ctx OF (tptr t_struct_hmac256drbg_context_st), _additional OF (tptr tuchar), _len OF tuint ]\n       PROP (\n         0 <= add_len <= Int.max_unsigned;\n         Zlength (hmac256drbgabs_value initial_state_abs) = 32 (*Z.of_nat SHA256.DigestLength*);\n         add_len = Zlength contents;\n         0 <= hmac256drbgabs_entropy_len initial_state_abs; \n         hmac256drbgabs_entropy_len initial_state_abs+ Zlength contents < Int.modulus;\n         0 < hmac256drbgabs_entropy_len initial_state_abs + Zlength (contents_with_add additional add_len contents) < Int.modulus;\n         Forall isbyteZ (hmac256drbgabs_value initial_state_abs);\n         Forall isbyteZ contents\n       )\n       LOCAL (temp _ctx ctx; temp _additional additional; temp _len (Vint (Int.repr add_len)); gvar sha._K256 kv)\n       SEP (\n         da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional;\n         data_at Tsh t_struct_hmac256drbg_context_st initial_state ctx;\n         hmac256drbg_relate initial_state_abs initial_state;\n         data_at Tsh t_struct_mbedtls_md_info info_contents (hmac256drbgstate_md_info_pointer initial_state);\n         Stream s;\n         K_vector kv)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp ret_value)\n       SEP (reseedPOST ret_value contents additional add_len s\n          initial_state_abs ctx\n          info_contents kv initial_state).\n\nDefinition mbedtls_HMAC256_DRBG_generate_function (entropy_stream: ENTROPY.stream) (a:hmac256drbgabs) \n            (requested_number_of_bytes: Z) (additional_input: list Z): ENTROPY.result (list Z * DRBG_state_handle) :=\n  match a with HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval =>\n               HMAC256_DRBG_generate_function (HMAC256_DRBG_reseed_function entropy_len entropy_len 256) \n                      10000(* reseed_interval *) \n                      1024 (*max_number_of_bytes_per_request*)\n                      256 (*max_additional_input_length*) \n                      entropy_stream\n                      ((V, key, reseed_counter), \n                        32(*256*) (*max security strength in bytes, not used *), \n                        prediction_resistance) \n                      requested_number_of_bytes \n                      32 (*requested security strength, not used *)\n                      prediction_resistance additional_input\n  end.\n\nDefinition hmac256drbgabs_generate (a: hmac256drbgabs) (s: ENTROPY.stream) (bytes: Z) (additional_data: list Z) : hmac256drbgabs :=\n  match a with HMAC256DRBGabs key V reseed_counter entropy_len prediction_resistance reseed_interval =>\n               match (mbedtls_HMAC256_DRBG_generate_function s a bytes additional_data) with\n                 | ENTROPY.success (_, ((V', key', reseed_counter'), _, pr')) _ =>\n                   HMAC256DRBGabs key' V' reseed_counter' entropy_len pr' reseed_interval\n                 | ENTROPY.error _ _ => a\n               end\n  end.\n\nDefinition generatePOST ret_value contents additional add_len output out_len ctx initial_state initial_state_abs kv info_contents s :=\nif out_len >? 1024\nthen (!!(ret_value = Vint (Int.neg (Int.repr 3))) &&\n       (data_at_ Tsh (tarray tuchar out_len) output *\n         da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional *\n         data_at Tsh t_struct_hmac256drbg_context_st initial_state ctx *\n         hmac256drbg_relate initial_state_abs initial_state *\n         data_at Tsh t_struct_mbedtls_md_info info_contents (hmac256drbgstate_md_info_pointer initial_state) *\n         Stream s *\n         K_vector kv))\nelse\n  if (add_len >? 256)\n  then (!!(ret_value = Vint (Int.neg (Int.repr 5))) &&\n       (data_at_ Tsh (tarray tuchar out_len) output *\n         da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional *\n         data_at Tsh t_struct_hmac256drbg_context_st initial_state ctx *\n         hmac256drbg_relate initial_state_abs initial_state *\n         data_at Tsh t_struct_mbedtls_md_info info_contents (hmac256drbgstate_md_info_pointer initial_state) *\n         Stream s *\n         K_vector kv))\n  else let g := (mbedtls_HMAC256_DRBG_generate_function s initial_state_abs out_len (*contents*)(contents_with_add additional add_len contents))\n       in (!!(return_value_relate_result g ret_value)) &&\n          (match g with\n            | ENTROPY.error _ _ => (data_at_ Tsh (tarray tuchar out_len) output)\n            | ENTROPY.success (bytes, _) _ => (data_at Tsh (tarray tuchar out_len) (map Vint (map Int.repr bytes)) output)\n          end *\n          hmac256drbgabs_common_mpreds (hmac256drbgabs_generate initial_state_abs s out_len (*contents*)(contents_with_add additional add_len contents)) initial_state ctx info_contents *\n          da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional *\n          Stream (get_stream_result g) *\n          K_vector kv).\n\nDefinition hmac_drbg_generate_spec :=\n  DECLARE _mbedtls_hmac_drbg_random_with_add\n   WITH contents: list Z,\n        additional: val, add_len: Z,\n        output: val, out_len: Z,\n        ctx: val, initial_state: hmac256drbgstate,\n        initial_state_abs: hmac256drbgabs,\n        kv: val, info_contents: md_info_state,\n        s: ENTROPY.stream\n    PRE [ _p_rng OF (tptr tvoid), _output OF (tptr tuchar), _out_len OF tuint, _additional OF (tptr tuchar), _add_len OF tuint ]\n       PROP (\n         0 <= add_len <= Int.max_unsigned;\n         0 <= out_len <= Int.max_unsigned;\n         Zlength (hmac256drbgabs_value initial_state_abs) = 32 (*Z.of_nat SHA256.DigestLength*);\n         add_len = Zlength contents;\n         0 < hmac256drbgabs_entropy_len initial_state_abs; \n         hmac256drbgabs_entropy_len initial_state_abs + Zlength contents <= 384;\n         hmac256drbgabs_reseed_interval initial_state_abs = 10000;\n         0 <= hmac256drbgabs_reseed_counter initial_state_abs <= Int.max_signed;\n         Forall isbyteZ (hmac256drbgabs_value initial_state_abs);\n         Forall isbyteZ contents\n       )\n       LOCAL (temp _p_rng ctx; temp _output output; temp _out_len (Vint (Int.repr out_len)); \n              temp _additional additional; temp _add_len (Vint (Int.repr add_len)); gvar sha._K256 kv)\n       SEP (\n         data_at_ Tsh (tarray tuchar out_len) output;\n         da_emp Tsh (tarray tuchar add_len) (map Vint (map Int.repr contents)) additional;\n         data_at Tsh t_struct_hmac256drbg_context_st initial_state ctx;\n         hmac256drbg_relate initial_state_abs initial_state;\n         data_at Tsh t_struct_mbedtls_md_info info_contents (hmac256drbgstate_md_info_pointer initial_state);\n         Stream s;\n         K_vector kv)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp ret_value)\n       SEP (generatePOST ret_value contents additional add_len output out_len ctx initial_state initial_state_abs kv info_contents s).\n\nDefinition hmac_drbg_seed_buf_spec :=\n  DECLARE _mbedtls_hmac_drbg_seed_buf\n   WITH ctx: val, info:val, d_len: Z, data:val, Data: list Z,\n        Ctx: hmac256drbgstate,\n        CTX: hmac256drbgabs,\n        kv: val, Info: md_info_state\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _md_info OF (tptr (Tstruct _mbedtls_md_info_t noattr)),\n         _data OF tptr tuchar, _data_len OF tuint ]\n       PROP ( (d_len = Zlength Data \\/ d_len=0) /\\\n              0 <= d_len <= Int.max_unsigned /\\ Forall isbyteZ Data)\n       LOCAL (temp _ctx ctx; temp _md_info info;\n              temp _data_len (Vint (Int.repr d_len)); temp _data data; gvar sha._K256 kv)\n       SEP (\n         data_at Tsh t_struct_hmac256drbg_context_st Ctx ctx;\n         hmac256drbg_relate CTX Ctx;\n         data_at Tsh t_struct_mbedtls_md_info Info info;\n         da_emp Tsh (tarray tuchar (Zlength Data)) (map Vint (map Int.repr Data)) data;\n         K_vector kv)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp ret_value)\n       SEP (data_at Tsh t_struct_mbedtls_md_info Info info *\n            da_emp Tsh (tarray tuchar (Zlength Data)) (map Vint (map Int.repr Data)) data *\n            K_vector kv;\n            orp ( !!(ret_value = Vint (Int.repr (-20864))) &&\n                  data_at Tsh t_struct_hmac256drbg_context_st Ctx ctx *\n                  hmac256drbg_relate CTX Ctx)\n                ( !!(ret_value <> Vint (Int.repr (-20864))) &&\n                  match Ctx, CTX\n                  with (mds, (V', (RC', (EL', (PR', RI'))))),\n                              HMAC256DRBGabs key V RC EL PR RI\n                     => EX KEY:list Z, EX VAL:list Z, EX p:val,\n                          !!(HMAC256_DRBG_update (contents_with_add data d_len Data) V (list_repeat 32 1) = (KEY, VAL))\n                          && md_full key mds * malloc_token Tsh (sizeof (Tstruct _hmac_ctx_st noattr)) p *\n                             data_at Tsh t_struct_hmac256drbg_context_st ((info, (fst(snd mds), p)), (map Vint (map Int.repr VAL), (RC', (EL', (PR', RI'))))) ctx *\n                             hmac256drbg_relate (HMAC256DRBGabs KEY VAL RC EL PR RI) ((info, (fst(snd mds), p)), (map Vint (map Int.repr VAL), (RC', (EL', (PR', RI')))))\n                  end)\n       ).\n\n\nDefinition get_entropy_spec :=\n  DECLARE _get_entropy\n   WITH\n        sh: share,\n        s: ENTROPY.stream,\n        buf: val, len: Z\n    PRE [ 1%positive OF (tptr tuchar), 2%positive OF tuint ]\n       PROP (\n         0 <= len <= Int.max_unsigned;\n         writable_share sh\n       )\n       LOCAL (temp 1%positive buf; temp 2%positive (Vint (Int.repr len)))\n       SEP (\n         memory_block sh len buf;\n         (Stream s)\n           )\n    POST [ tint ]\n       EX ret_value:_,\n       PROP (\n           return_value_relate_result (get_entropy 0 len len false s) ret_value\n         )\n       LOCAL (temp ret_temp ret_value)\n       SEP (\n         Stream (get_stream_result (get_entropy 0 len len false s));\n         (match ENTROPY.get_bytes (Z.to_nat len) s with\n            | ENTROPY.error _ _ => memory_block sh len buf\n            | ENTROPY.success bytes _ =>\n              data_at sh (tarray tuchar len) (map Vint (map Int.repr (bytes))) buf\n                 end)\n       ).\n\nDefinition size_of_HMACDRBGCTX:Z:= sizeof (Tstruct _mbedtls_hmac_drbg_context noattr).\n\nDefinition hmac_drbg_init_spec :=\n  DECLARE _mbedtls_hmac_drbg_init\n   WITH c : val\n   PRE [ _ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr) ]\n         PROP () \n         LOCAL (temp _ctx c)\n         SEP(memory_block Tsh size_of_HMACDRBGCTX c)\n  POST [ tvoid ]  \n          PROP () \n          LOCAL ()\n          SEP(data_at Tsh (tarray tuchar size_of_HMACDRBGCTX)\n                (list_repeat (Z.to_nat size_of_HMACDRBGCTX) (Vint Int.zero)) c).\n\nDefinition hmac_drbg_random_spec :=\n  DECLARE _mbedtls_hmac_drbg_random\n   WITH output: val, out_len: Z,\n        ctx: val, initial_state: hmac256drbgstate,\n        initial_state_abs: hmac256drbgabs,\n        kv: val, info_contents: md_info_state,\n        s: ENTROPY.stream\n    PRE [_p_rng OF tptr tvoid, _output OF tptr tuchar, _out_len OF tuint ]\n       PROP ( \n         0 <= out_len <= Int.max_unsigned;\n         Zlength (hmac256drbgabs_value initial_state_abs) = 32 (*Z.of_nat SHA256.DigestLength*);\n         0 < hmac256drbgabs_entropy_len initial_state_abs <= 384;\n         hmac256drbgabs_reseed_interval initial_state_abs = 10000;\n         0 <= hmac256drbgabs_reseed_counter initial_state_abs <= Int.max_signed;\n         Forall isbyteZ (hmac256drbgabs_value initial_state_abs))\n       LOCAL (temp _p_rng ctx; temp _output output;\n              temp _out_len (Vint (Int.repr out_len)); gvar sha._K256 kv)\n       SEP (\n         data_at_ Tsh (tarray tuchar out_len) output;\n         data_at Tsh t_struct_hmac256drbg_context_st initial_state ctx;\n         hmac256drbg_relate initial_state_abs initial_state;\n         data_at Tsh t_struct_mbedtls_md_info info_contents (hmac256drbgstate_md_info_pointer initial_state);\n         Stream s;\n         K_vector kv)\n    POST [ tint ]\n       EX ret_value:_,\n       PROP ()\n       LOCAL (temp ret_temp ret_value)\n       SEP (generatePOST ret_value nil nullval 0 output out_len ctx initial_state initial_state_abs kv info_contents s).\n\nDefinition setPR_ABS res (a: hmac256drbgabs): hmac256drbgabs :=\n  match a with HMAC256DRBGabs key V x el r reseed_interval => \n               HMAC256DRBGabs key V x el res reseed_interval\n  end.\n\nDefinition setPR_CTX res (r: hmac256drbgstate): hmac256drbgstate :=\n  match r with (md_ctx, (V, (rc, (el, (r, ri))))) => \n               (md_ctx, (V, (rc, (el, (res, ri))))) \n  end.\n\nDefinition hmac_drbg_setPredictionResistance_spec :=\n  DECLARE _mbedtls_hmac_drbg_set_prediction_resistance \n   WITH ctx:val, CTX:hmac256drbgstate, ABS:_, r:bool\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _resistance OF tint ]\n       PROP ( )\n       LOCAL (temp _ctx ctx; temp _resistance (Val.of_bool r))\n       SEP (data_at Tsh t_struct_hmac256drbg_context_st CTX ctx;\n            hmac256drbg_relate ABS CTX)\n    POST [ tvoid ]\n       SEP (data_at Tsh t_struct_hmac256drbg_context_st (setPR_CTX (Val.of_bool r) CTX) ctx;\n            hmac256drbg_relate (setPR_ABS r ABS) (setPR_CTX (Val.of_bool r) CTX)).\n\nDefinition setEL_ABS el (a: hmac256drbgabs): hmac256drbgabs :=\n  match a with HMAC256DRBGabs key V x _ pr reseed_interval => \n               HMAC256DRBGabs key V x el pr reseed_interval\n  end.\n\nDefinition setEL_CTX el (r: hmac256drbgstate): hmac256drbgstate :=\n  match r with (md_ctx, (V, (rc, (_, (pr, ri))))) => \n               (md_ctx, (V, (rc, (el, (pr, ri))))) \n  end.\n\nDefinition hmac_drbg_setEntropyLen_spec :=\n  DECLARE _mbedtls_hmac_drbg_set_entropy_len\n   WITH ctx:val, CTX:hmac256drbgstate, ABS:_, l:_\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _len OF tuint ]\n       PROP ( )\n       LOCAL (temp _ctx ctx; temp _len (Vint (Int.repr l)))\n       SEP (data_at Tsh t_struct_hmac256drbg_context_st CTX ctx;\n            hmac256drbg_relate ABS CTX)\n    POST [ tvoid ]\n       SEP (data_at Tsh t_struct_hmac256drbg_context_st (setEL_CTX (Vint (Int.repr l)) CTX) ctx;\n            hmac256drbg_relate (setEL_ABS l ABS) (setEL_CTX (Vint (Int.repr l)) CTX)).\n\nDefinition setRI_ABS ri (a: hmac256drbgabs): hmac256drbgabs :=\n  match a with HMAC256DRBGabs key V x el pr _ => \n               HMAC256DRBGabs key V x el pr ri\n  end.\n\nDefinition setRI_CTX ri (r: hmac256drbgstate): hmac256drbgstate :=\n  match r with (md_ctx, (V, (rc, (el, (pr, _))))) => \n               (md_ctx, (V, (rc, (el, (pr, ri))))) \n  end.\n\nDefinition hmac_drbg_setReseedInterval_spec :=\n  DECLARE _mbedtls_hmac_drbg_set_reseed_interval\n   WITH ctx:val, CTX:hmac256drbgstate, ABS:_, l:_\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr),\n         _interval OF tint ]\n       PROP ( )\n       LOCAL (temp _ctx ctx; temp _interval (Vint (Int.repr l)))\n       SEP (data_at Tsh t_struct_hmac256drbg_context_st CTX ctx;\n            hmac256drbg_relate ABS CTX)\n    POST [ tvoid ]\n       SEP (data_at Tsh t_struct_hmac256drbg_context_st (setRI_CTX (Vint (Int.repr l)) CTX) ctx;\n            hmac256drbg_relate (setRI_ABS l ABS) (setRI_CTX (Vint (Int.repr l)) CTX)).\n\n\nDefinition hmac_drbg_free_spec :=\n  DECLARE _mbedtls_hmac_drbg_free\n   WITH ctx:val, CTX:hmac256drbgstate, ABS:_\n    PRE [_ctx OF tptr (Tstruct _mbedtls_hmac_drbg_context noattr) ]\n       PROP ( )\n       LOCAL (temp _ctx ctx)\n       SEP (da_emp Tsh t_struct_hmac256drbg_context_st CTX ctx;\n            if Val.eq ctx nullval then emp else\n                 (hmac256drbg_relate ABS CTX *\n                  malloc_token Tsh 324 (snd(snd (fst CTX)))))\n    POST [ tvoid ] \n      EX vret:unit, PROP ()\n       LOCAL ()\n       SEP (if Val.eq ctx nullval then emp else data_block Tsh (list_repeat (Z.to_nat size_of_HMACDRBGCTX) 0) ctx).\n\nDefinition HmacDrbgVarSpecs : varspecs := (sha._K256, tarray tuint 64)::nil.\n\nDefinition ndfs_merge fA cA A PA QA FSA (HFSA: FSA = NDmk_funspec fA cA A PA QA) \n                    fB cB B PB QB FSB (HFSB: FSB = NDmk_funspec fB cB B PB QB): option funspec.\ndestruct (eq_dec fA fB); subst.\n+ destruct (eq_dec cA cB); subst.\n  - apply Some. eapply (NDmk_funspec fB cB (A+B) \n         (fun x => match x with inl a => PA a | inr b => PB b end)\n         (fun x => match x with inl a => QA a | inr b => QB b end)).\n  - apply None.\n+ apply None.\nDefined.\n(*\nDefinition fs_merge (fA fB: funspec): option funspec :=\n match fA, fB with (mk_funspec sgA ccA A PreA PostA), (mk_funspec sgB ccB B PreB PostB) =>\n  if eq_dec sgA sgB \n  then if eq_dec ccA ccB\n       then Some (mk_funspec sgB ccB (A+B)\n                   (fun x => match x with inl a => PreA a | inr b => PreB b end)\n                   (fun x => match x with inl a => PostA a | inr b => PostB b end))\n       else None\n  else None\n end.\n*)\n\nDefinition hmac_init_funspec:=\n    (WITH x : val * Z * list Z * val + val * Z * list Z * val * block * int PRE\n     [(hmac._ctx, tptr spec_hmac.t_struct_hmac_ctx_st), (hmac._key, tptr tuchar),\n     (hmac._len, tint)] match x with\n                        | inl (c, l, key, kv) =>\n                            PROP ( )\n                            LOCAL (temp hmac._ctx c; temp hmac._key nullval;\n                            temp hmac._len (Vint (Int.repr l)); \n                            gvar sha._K256 kv)\n                            SEP (UNDER_SPEC.FULL key c;\n                            spec_sha.K_vector kv)\n                        | inr (c, l, key, kv, b0, i) =>\n                            PROP (spec_hmac.has_lengthK l key)\n                            LOCAL (temp hmac._ctx c; temp hmac._key (Vptr b0 i);\n                            temp hmac._len (Vint (Int.repr l)); \n                            gvar sha._K256 kv)\n                            SEP (UNDER_SPEC.EMPTY c;\n                            spec_sha.data_block Tsh key (Vptr b0 i); \n                            spec_sha.K_vector kv)\n                        end\n     POST [tvoid] match x with\n                  | inl (c, _, key, kv) =>\n                      PROP ( )\n                      LOCAL ()\n                      SEP (UNDER_SPEC.REP\n                             (UNDER_SPEC.hABS key []) c;\n                      spec_sha.K_vector kv)\n                  | inr (c, _, key, kv, b0, i) =>\n                      PROP ( )\n                      LOCAL ()\n                      SEP (UNDER_SPEC.REP\n                             (UNDER_SPEC.hABS key []) c;\n                      spec_sha.data_block Tsh key (Vptr b0 i); \n                      spec_sha.K_vector kv)\n                  end).\n(*\nLemma hmac_init_merge: \n  fs_merge (snd UNDER_SPEC.hmac_reset_spec)\n           (snd UNDER_SPEC.hmac_starts_spec)\n  = Some hmac_init_funspec.\nProof. simpl. rewrite if_true; trivial. Qed.*)\n\nLemma hmac_init_merge: \n  ndfs_merge _ _ _ _ _ (snd UNDER_SPEC.hmac_reset_spec) (eq_refl _)\n             _ _ _ _ _ (snd UNDER_SPEC.hmac_starts_spec) (eq_refl _)\n  = Some hmac_init_funspec.\nProof. unfold ndfs_merge. simpl. rewrite if_true; trivial. Qed. \n\nDefinition HmacDrbgFunSpecs : funspecs :=  ltac:(with_library prog (\n  md_free_spec ::hmac_drbg_free_spec::mbedtls_zeroize_spec::\n  hmac_drbg_setReseedInterval_spec::hmac_drbg_setEntropyLen_spec::\n  hmac_drbg_setPredictionResistance_spec::hmac_drbg_random_spec::hmac_drbg_init_spec::\n  hmac_drbg_update_spec::\n  hmac_drbg_reseed_spec::\n  hmac_drbg_generate_spec::hmac_drbg_seed_buf_spec ::\n  get_entropy_spec::\n  md_reset_spec::md_final_spec::md_update_spec::\n  md_starts_spec::md_setup_spec::md_get_size_spec::\n\n  UNDER_SPEC.hmac_update_spec::\n  UNDER_SPEC.hmac_final_spec:: \n  (hmac._HMAC_Init,hmac_init_funspec)::\n\n  drbg_memcpy_spec:: drbg_memset_spec::\n  sha.spec_hmac.sha256init_spec::sha.spec_hmac.sha256update_spec::sha.spec_hmac.sha256final_spec::nil)).\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/hmacdrbg/spec_hmac_drbg.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2175391846438568}}
{"text": "From cap_machine Require Import rules_base.\nFrom iris.base_logic Require Export invariants gen_heap.\nFrom iris.program_logic Require Export weakestpre ectx_lifting.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import frac.\n\nSection cap_lang_rules.\n  Context `{memG Σ, regG Σ}.\n  Context `{MachineParameters}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types σ : ExecConf.\n  Implicit Types c : cap_lang.expr.\n  Implicit Types a b : Addr.\n  Implicit Types r : RegName.\n  Implicit Types v : cap_lang.val.\n  Implicit Types w : Word.\n  Implicit Types reg : gmap RegName Word.\n  Implicit Types ms : gmap Addr Word.\n\n  Inductive Jnz_spec (regs: Reg) (dst src: RegName) : Reg → cap_lang.val → Prop :=\n  | Jnz_spec_failure w:\n      regs !! src = Some w →\n      nonZero w = false →\n      incrementPC regs = None →\n      Jnz_spec regs dst src regs FailedV\n  | Jnz_spec_success1 w regs':\n      regs !! src = Some w →\n      nonZero w = false →\n      incrementPC regs = Some regs' →\n      Jnz_spec regs dst src regs' NextIV\n  | Jnz_spec_success2 w w':\n      regs !! src = Some w →\n      regs !! dst = Some w' →\n      nonZero w = true →\n      Jnz_spec regs dst src (<[PC := updatePcPerm w' ]> regs) NextIV.\n\n  Lemma wp_Jnz Ep pc_p pc_g pc_b pc_e pc_a w dst src regs :\n    decodeInstrW w = Jnz dst src ->\n\n    isCorrectPC (inr ((pc_p, pc_g), pc_b, pc_e, pc_a)) →\n    regs !! PC = Some (inr ((pc_p, pc_g), pc_b, pc_e, pc_a)) →\n    regs_of (Jnz dst src) ⊆ dom _ regs →\n    {{{ ▷ pc_a ↦ₐ w ∗\n        ▷ [∗ map] k↦y ∈ regs, k ↦ᵣ y }}}\n      Instr Executable @ Ep\n    {{{ regs' retv, RET retv;\n        ⌜ Jnz_spec regs dst src regs' retv ⌝ ∗\n        pc_a ↦ₐ w ∗\n        [∗ map] k↦y ∈ regs', k ↦ᵣ y }}}.\n  Proof.\n    iIntros (Hinstr Hvpc HPC Dregs φ) \"(>Hpc_a & >Hmap) Hφ\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 l1 l2 n) \"Hσ1 /=\". destruct σ1 as [r m]; simpl.\n    iDestruct \"Hσ1\" as \"[Hr Hm]\".\n    iDestruct (gen_heap_valid_inclSepM with \"Hr Hmap\") as %Hregs.\n    have HPC' := regs_lookup_eq _ _ _ HPC.\n    have ? := lookup_weaken _ _ _ _ HPC Hregs.\n    iDestruct (@gen_heap_valid with \"Hm Hpc_a\") as %Hpc_a; auto.\n    iModIntro. iSplitR. by iPureIntro; apply normal_always_head_reducible.\n    iNext. iIntros (e2 σ2 efs Hpstep).\n    apply prim_step_exec_inv in Hpstep as (-> & -> & (c & -> & Hstep)).\n    iSplitR; auto. eapply step_exec_inv in Hstep; eauto.\n\n    specialize (indom_regs_incl _ _ _ Dregs Hregs) as Hri.\n    unfold regs_of in Hri, Dregs.\n    destruct (Hri src) as [wsrc [H'src Hsrc]]. by set_solver+.\n    destruct (Hri dst) as [wdst [H'dst Hdst]]. by set_solver+.\n\n    destruct (nonZero wsrc) eqn:Hnz; pose proof Hnz as H'nz;\n      cbn in Hstep; rewrite /RegLocate Hsrc Hdst Hnz in Hstep.\n    { inv Hstep. simplify_pair_eq.\n      iMod ((gen_heap_update_inSepM _ _ PC) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n      iFrame. iApply \"Hφ\". iFrame. iPureIntro. econstructor 3; eauto. }\n\n    destruct (incrementPC regs) eqn:HX; pose proof HX as H'X; cycle 1.\n    { apply incrementPC_fail_updatePC with (m:=m) in HX.\n      eapply updatePC_fail_incl with (m':=m) in HX; eauto. simplify_pair_eq.\n      inv Hstep. iFrame. iApply \"Hφ\". iFrame. iPureIntro; econstructor; eauto. }\n\n    destruct (incrementPC_success_updatePC _ m _ HX)\n      as (p' & g' & b' & e' & a'' & a_pc' & HPC'' & Ha_pc' & HuPC & -> & ?).\n    eapply updatePC_success_incl with (m':=m) in HuPC; eauto. simplify_pair_eq.\n    iMod ((gen_heap_update_inSepM _ _ PC) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n    iFrame. iApply \"Hφ\". iFrame. iPureIntro. econstructor 2; eauto.\n  Qed.\n\n  Lemma wp_jnz_success_jmp E r1 r2 pc_p pc_g pc_b pc_e pc_a w w1 w2 :\n    decodeInstrW w = Jnz r1 r2 →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    w2 ≠ inl 0%Z →\n\n    {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ ▷ pc_a ↦ₐ w\n        ∗ ▷ r1 ↦ᵣ w1\n        ∗ ▷ r2 ↦ᵣ w2 }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ updatePcPerm w1\n          ∗ pc_a ↦ₐ w\n          ∗ r1 ↦ᵣ w1\n          ∗ r2 ↦ᵣ w2 }}}.\n  Proof.\n    iIntros (Hinstr Hvpc Hne ϕ) \"(>HPC & >Hpc_a & >Hr1 & >Hr2) Hφ\".\n    iDestruct (map_of_regs_3 with \"HPC Hr1 Hr2\") as \"[Hmap (%&%&%)]\".\n    iApply (wp_Jnz with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by unfold regs_of; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    assert (nonZero w2 = true).\n    { unfold nonZero, Zneq_bool in *.\n      repeat case_match; try congruence; subst. exfalso.\n      apply Hne. f_equal. by apply Z.compare_eq. }\n\n   destruct Hspec as [ | | ].\n   { exfalso. simplify_map_eq. congruence. }\n   { exfalso. simplify_map_eq. congruence. }\n   { iApply \"Hφ\". iFrame. simplify_map_eq. rewrite insert_insert.\n     iDestruct (regs_of_map_3 with \"Hmap\") as \"(?&?&?)\"; eauto; iFrame. }\n  Qed.\n\n  Lemma wp_jnz_success_jmp2 E r2 pc_p pc_g pc_b pc_e pc_a w w2 :\n    decodeInstrW w = Jnz r2 r2 →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    w2 ≠ inl 0%Z →\n\n    {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ ▷ pc_a ↦ₐ w\n        ∗ ▷ r2 ↦ᵣ w2 }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ updatePcPerm w2\n          ∗ pc_a ↦ₐ w\n          ∗ r2 ↦ᵣ w2 }}}.\n  Proof.\n    iIntros (Hinst Hvpc Hne ϕ) \"(>HPC & >Hpc_a & >Hr2) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hr2\") as \"[Hmap %]\".\n    iApply (wp_Jnz with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by unfold regs_of; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    assert (nonZero w2 = true).\n    { unfold nonZero, Zneq_bool in *.\n      repeat case_match; try congruence; subst. exfalso.\n      apply Hne. f_equal. by apply Z.compare_eq. }\n\n   destruct Hspec as [ | | ].\n   { exfalso. simplify_map_eq. congruence. }\n   { exfalso. simplify_map_eq. congruence. }\n   { iApply \"Hφ\". iFrame. simplify_map_eq. rewrite insert_insert.\n     iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n  Qed.\n\n  Lemma wp_jnz_success_jmpPC E pc_p pc_g pc_b pc_e pc_a w  :\n    decodeInstrW w = Jnz PC PC →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n\n    {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ ▷ pc_a ↦ₐ w }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ updatePcPerm (inr ((pc_p,pc_g),pc_b,pc_e,pc_a))\n          ∗ pc_a ↦ₐ w }}}.\n  Proof.\n    iIntros (Hinstr Hvpc ϕ) \"(>HPC & >Hpc_a) Hφ\".\n    iDestruct (map_of_regs_1 with \"HPC\") as \"Hmap\".\n    iApply (wp_Jnz with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by unfold regs_of; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n   destruct Hspec as [ | | ]; [ by simplify_map_eq .. | ].\n   { iApply \"Hφ\". iFrame. simplify_map_eq. rewrite insert_insert.\n     iDestruct (regs_of_map_1 with \"Hmap\") as \"?\"; eauto; iFrame. }\n  Qed.\n\n  Lemma wp_jnz_success_jmpPC1 E r2 pc_p pc_g pc_b pc_e pc_a w w2 :\n    decodeInstrW w = Jnz PC r2 →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    w2 ≠ inl 0%Z →\n\n    {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ ▷ pc_a ↦ₐ w\n        ∗ ▷ r2 ↦ᵣ w2 }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ updatePcPerm (inr ((pc_p,pc_g),pc_b,pc_e,pc_a))\n          ∗ pc_a ↦ₐ w\n          ∗ r2 ↦ᵣ w2 }}}.\n  Proof.\n    iIntros (Hinstr Hvpc Hne ϕ) \"(>HPC & >Hpc_a & >Hr2) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hr2\") as \"[Hmap %]\".\n    iApply (wp_Jnz with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by unfold regs_of; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    assert (nonZero w2 = true).\n    { unfold nonZero, Zneq_bool in *.\n      repeat case_match; try congruence; subst. exfalso.\n      apply Hne. f_equal. by apply Z.compare_eq. }\n\n   destruct Hspec as [ | | ].\n   { exfalso. simplify_map_eq. congruence. }\n   { exfalso. simplify_map_eq. congruence. }\n   { iApply \"Hφ\". iFrame. simplify_map_eq. rewrite insert_insert.\n     iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n  Qed.\n\n  Lemma wp_jnz_success_jmpPC2 E r1 pc_p pc_g pc_b pc_e pc_a w w1 :\n    decodeInstrW w = Jnz r1 PC →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n\n    {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ ▷ pc_a ↦ₐ w\n        ∗ ▷ r1 ↦ᵣ w1 }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ updatePcPerm w1\n          ∗ pc_a ↦ₐ w\n          ∗ r1 ↦ᵣ w1 }}}.\n  Proof.\n    iIntros (Hinstr Hvpc ϕ) \"(>HPC & >Hpc_a & >Hr1) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hr1\") as \"[Hmap %]\".\n    iApply (wp_Jnz with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by unfold regs_of; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n   destruct Hspec as [ | | ]; [ by simplify_map_eq .. | ].\n   { iApply \"Hφ\". iFrame. simplify_map_eq. rewrite insert_insert.\n     iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n  Qed.\n\n  Lemma wp_jnz_success_next E r1 r2 pc_p pc_g pc_b pc_e pc_a pc_a' w w1 :\n    decodeInstrW w = Jnz r1 r2 →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (pc_a + 1)%a = Some pc_a' →\n\n    {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ ▷ pc_a ↦ₐ w\n        ∗ ▷ r1 ↦ᵣ w1\n        ∗ ▷ r2 ↦ᵣ inl 0%Z }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ r1 ↦ᵣ w1\n          ∗ r2 ↦ᵣ inl 0%Z }}}.\n  Proof.\n    iIntros (Hinstr Hvpc Hpc_a' ϕ) \"(>HPC & >Hpc_a & >Hr1 & >Hr2) Hφ\".\n    iDestruct (map_of_regs_3 with \"HPC Hr1 Hr2\") as \"[Hmap (%&%&%)]\".\n    iApply (wp_Jnz with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by unfold regs_of; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n   destruct Hspec as [ | | ]; try incrementPC_inv; simplify_map_eq; eauto.\n   { destruct H7; try congruence. inv Hvpc. naive_solver. }\n   { iApply \"Hφ\". iFrame. rewrite insert_insert.\n     iDestruct (regs_of_map_3 with \"Hmap\") as \"(?&?&?)\"; eauto; iFrame. }\n  Qed.\n\nEnd cap_lang_rules.\n", "meta": {"author": "logsem", "repo": "cerise-stack-monotone", "sha": "dff1909f6abc6de99c28d8f12e903b98dd76fb41", "save_path": "github-repos/coq/logsem-cerise-stack-monotone", "path": "github-repos/coq/logsem-cerise-stack-monotone/cerise-stack-monotone-dff1909f6abc6de99c28d8f12e903b98dd76fb41/theories/rules/rules_Jnz.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.21753918464385677}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Export DistributedReferenceCounting.machine4.machine.\nRequire Export DistributedReferenceCounting.machine4.cardinal.\nRequire Export DistributedReferenceCounting.machine4.comm.\n\nUnset Standard Proposition Elimination Names.\n\nSection IN_Q_BEFORE.\n\nVariable data : Set.\n\n(* This predicate tells us if we can find a data d\n   - before the first occurrence of d1, if d1 belongs to q,\n   - otherwise it returns true when d1 does not belong to q.\n*)\n  \nHypothesis eq_data_dec : eq_dec data.\n\nFixpoint In_queue_before_data (d d1 : data) (q : queue data) {struct q} :\n Prop :=\n  match q with\n  | empty => True\n  | input d' q' =>\n      if eq_data_dec d' d1\n      then False\n      else d' = d \\/ In_queue_before_data d d1 q'\n  end.\n\n(* same except that I pass a predicate to recognise d1 *)\n\nFixpoint In_queue_before (d : data) (f1 : data -> bool) \n (q : queue data) {struct q} : Prop :=\n  match q with\n  | empty => True\n  | input d' q' =>\n      if eq_bool_dec (f1 d')\n      then False\n      else d' = d \\/ In_queue_before d f1 q'\n  end.\n\n\nEnd IN_Q_BEFORE.\n\nSection ALTERNATE.\n\nDefinition is_inc_dec (m : Message) :=\n  match m with\n  | inc_dec _ => true\n  | _ => false\n  end.\n\n\n\nInductive alternate : queue Message -> Prop :=\n  | alt_null : alternate (empty Message)\n  | alt_any_alt :\n      forall (qm : queue Message) (m : Message),\n      (forall s : Site, m <> inc_dec s) ->\n      alternate qm -> alternate (input Message m qm)\n  | alt_inc_dec :\n      forall (qm : queue Message) (s0 : Site),\n      alternate qm ->\n      In_queue_before Message dec is_inc_dec qm ->\n      alternate (input Message (inc_dec s0) qm).\n\nLemma dec_is_not_inc : forall s : Site, dec <> inc_dec s.\nProof.\n intro; discriminate.\nQed.\n\nInductive D_queue : queue Message -> Prop :=\n  | D_empty : D_queue (empty Message)\n  | D_dec :\n      forall qm : queue Message,\n      alternate qm -> In_queue_before Message dec is_inc_dec qm -> D_queue qm.\n\nLemma not_D_queue :\n forall (q0 : queue Message) (m : Message),\n ~ D_queue q0 -> m <> dec -> ~ D_queue (input Message m q0).\nProof.\n  intros; red in |- *; intro.\n  inversion H1.\n  elim H.\n  generalize H3.\n  generalize H2.\n  generalize H0.\n  case q0.\n  intros.\n  apply D_empty.\n  \n  simpl in |- *.\n  intros.\n  apply D_dec.\n  inversion H6.\n  auto.\n  \n  auto.\n  \n  simpl in |- *.\n  generalize H5 H7.\n  case m.\n  intro.\n  elim H8; auto.\n  \n  intro.\n  case (eq_bool_dec (is_inc_dec (inc_dec s))).\n  intros; contradiction.\n  \n  intros.\n  elim H9; intro.\n  elim H8; auto.\n  \n  auto.\n  \n  case (eq_bool_dec (is_inc_dec copy)).\n  intros; contradiction.\n  \n  intros.\n  elim H9; intro.\n  elim H8; auto.\n  \n  auto.\nQed.\n\nLemma D_queue_is_alternate :\n forall q0 : queue Message, D_queue q0 -> alternate q0.\nProof.\n  intros.\n  elim H.\n  apply alt_null.\n  intros.\n  auto.\nQed.\n\t\n\nLemma in_q_before_first_out :\n forall q : queue Message,\n In_queue_before Message dec is_inc_dec q ->\n In_queue_before Message dec is_inc_dec (first_out Message q).\nProof.\n  simple induction q.\n  simpl in |- *.\n  auto.\n  \n  simpl in |- *.\n  intro.\n  case d.\n  case (eq_bool_dec (is_inc_dec dec)).\n  simpl in |- *.\n  intro; discriminate.\n  \n  intro; intro.\n  case q0.\n  simpl in |- *.\n  auto.\n  \n  simpl in |- *.\n  intros.\n  case (eq_bool_dec false).\n  intro; discriminate.\n  \n  auto.\n  \n  intro.\n  case (eq_bool_dec (is_inc_dec (inc_dec s))).\n  intros; contradiction.\n  \n  simpl in |- *; intro.\n  discriminate.\n  \n  simpl in |- *.\n  case (eq_bool_dec false).\n  intro; discriminate.\n  \n  intro; intro.\n  case q0.\n  simpl in |- *.\n  auto.\n  \n  intros.\n  elim H0.\n  intro; discriminate.\n  \n  intro.\n  generalize (H H1).\n  simpl in |- *.\n  intros.\n  case (eq_bool_dec false); intro.\n  discriminate.\n  \n  right; auto.\nQed.\n\n\nLemma alt_first_out :\n forall q0 : queue Message, alternate q0 -> alternate (first_out Message q0).\nProof.\n  intros; elim H; simpl in |- *.\n  apply alt_null.\n  \n  intros qm m; intro.\n  case qm.\n  intros; apply alt_null.\n  \n  simpl in |- *.\n  generalize H0.\n  case m.\n  auto.\n  intros.\n  apply alt_any_alt.\n  auto.\n  \n  auto.\n  \n  intros.\n  apply alt_any_alt.\n  auto.\n  \n  auto.\n  \n  intros.\n  apply alt_any_alt.\n  auto.\n  \n  auto.\n  \n  intro.\n  intro.\n  case qm.\n  auto.\n  \n  intros.\n  apply alt_inc_dec.\n  auto.\n  \n  apply in_q_before_first_out.\n  auto.\nQed.\n\n\n\nLemma D_first_out :\n forall q0 : queue Message, D_queue q0 -> D_queue (first_out Message q0).\nProof.\n  intros.\n  elim H.\n  simpl in |- *.\n  apply D_empty.\n  \n  simple destruct qm.\n  simpl in |- *.\n  intros.\n  apply D_empty.\n  \n  intros.\n  apply D_dec.\n  apply alt_first_out.\n  auto.\n  \n  apply in_q_before_first_out.\n  auto.\nQed.\n\nLemma D_input :\n forall q : queue Message, D_queue (input Message copy q) -> D_queue q.\nProof.\n  intros.\n  inversion H.\n  inversion H0.\n  apply D_dec.\n  auto.\n  generalize H1; simpl in |- *.\n  case (eq_bool_dec false); intro.\n  discriminate.\n  intro.\n  elim H7; intro.\n  discriminate.\n  \n  auto.\nQed.\t\n\nEnd ALTERNATE.\n\nSection MESS_ALT.\n\n(* consequence sur la structure alternee *)\n\nVariable b0 : Bag_of_Data Message.\n\nVariable s0 : Site.\n\nLemma D_collect :\n forall s1 s2 : Site,\n D_queue (b0 s0 owner) -> D_queue (Collect_message Message b0 s1 s2 s0 owner).\nProof.\n intros; case (eq_queue_dec s1 s0 s2 owner); intro.\n decompose [and] a; rewrite H0; rewrite H1.\n rewrite collect_here; apply D_first_out; trivial.\n\n rewrite collect_elsewhere; auto.\nQed.\n\nLemma D_post_elsewhere :\n forall (s1 s2 : Site) (m : Message),\n s1 <> s0 \\/ s2 <> owner ->\n D_queue (b0 s0 owner) -> D_queue (Post_message Message m b0 s1 s2 s0 owner).\nProof.\n intros; rewrite post_elsewhere; trivial.\nQed.\n\nLemma D_post_dec :\n alternate (b0 s0 owner) ->\n D_queue (Post_message Message dec b0 s0 owner s0 owner).\nProof.\n  intros; rewrite post_here.\n  apply D_dec.\n  apply alt_any_alt.\n  intro; discriminate.\n  auto.\n  simpl in |- *.\n  case (eq_bool_dec false); intro.\n  discriminate.\n  auto.\nQed.\n\nLemma alt_collect :\n forall s1 s2 : Site,\n alternate (b0 s0 owner) ->\n alternate (Collect_message Message b0 s1 s2 s0 owner).\nProof.\n intros; case (eq_queue_dec s1 s0 s2 owner); intro.\n decompose [and] a; rewrite H0; rewrite H1.\n rewrite collect_here; apply alt_first_out; trivial.\n\n rewrite collect_elsewhere; auto.\nQed.\n\nLemma alt_post_elsewhere :\n forall (s1 s2 : Site) (m : Message),\n s1 <> s0 \\/ s2 <> owner ->\n alternate (b0 s0 owner) ->\n alternate (Post_message Message m b0 s1 s2 s0 owner).\nProof.\n intros; rewrite post_elsewhere; trivial.\nQed.\n\nLemma alt_post_any :\n forall m : Message,\n (forall s : Site, m <> inc_dec s) ->\n alternate (b0 s0 owner) ->\n alternate (Post_message Message m b0 s0 owner s0 owner).\nProof.\n intros; rewrite post_here; apply alt_any_alt; auto.\nQed.\n\n\n\nLemma alt_post_inc :\n forall s1 : Site,\n alternate (b0 s0 owner) ->\n In_queue_before Message dec is_inc_dec (b0 s0 owner) ->\n alternate (Post_message Message (inc_dec s1) b0 s0 owner s0 owner).\nProof.\n  intros s1 H; rewrite post_here.\n  inversion H; intros.\n  apply alt_inc_dec.\n  apply alt_null.\n  \n  auto.\n  \n  generalize H1 H2 H3.\n  case m.\n  intros.\n  apply alt_inc_dec.\n  apply alt_any_alt.\n  intro; discriminate.\n  \n  auto.\n  \n  auto.\n  \n  intros.\n  elim (H4 s); auto.\n  \n  intros.\n  apply alt_inc_dec.\n  apply alt_any_alt.\n  auto.\n  \n  auto.\n  \n  auto.\n  \n  generalize H3.\n  simpl in |- *.\n  case (eq_bool_dec true); intro.\n  intro; contradiction.\n  \n  discriminate.\nQed.\n\n(* no longer useful 'cos copy is out of band and could be last *)\n\nLemma alt_post_inc_old :\n forall s1 : Site,\n alternate (b0 s0 owner) ->\n b0 s0 owner = empty Message \\/\n last Message (b0 s0 owner) = value Message dec ->\n alternate (Post_message Message (inc_dec s1) b0 s0 owner s0 owner).\nProof.\n  intros s1 H; rewrite post_here.\n  inversion H; simpl in |- *; intros.\n  apply alt_inc_dec.\n  apply alt_null.\n  simpl in |- *.\n  auto.\n  replace m with dec.\n  apply alt_inc_dec.\n  apply alt_any_alt.\n  intro; discriminate.\n  auto.\n  simpl in |- *.\n  case (eq_bool_dec false); intro.\n  discriminate.\n  auto.\n  elim H3; intro.\n  discriminate.\n  inversion H4.\n  auto.\n  elim H3; intro.\n  discriminate.\n  discriminate.\nQed.\n\n\nLemma in_q_before_append :\n forall q1 q2 : queue Message,\n In_queue_before Message dec is_inc_dec (append Message q1 q2) ->\n In_queue_before Message dec is_inc_dec\n   (append Message q1 (input Message copy q2)).\nProof.\n  simple induction q1; simpl in |- *.\n  case (eq_bool_dec false); intro.\n  discriminate.\n  intros.\n  right; auto.\n  intro.\n  case d.\n  simpl in |- *.\n  case (eq_bool_dec false); intro.\n  discriminate.\n  intros.\n  auto.\n  intro.\n  simpl in |- *.\n  case (eq_bool_dec true).\n  auto.\n  intro; discriminate.\n  simpl in |- *.\n  case (eq_bool_dec false); intro.\n  discriminate.\n  intros.\n  right.\n  apply H.\n  elim H0; intro.\n  discriminate.\n  auto.\nQed.\n\nLemma in_q_before_append2 :\n forall q1 q2 : queue Message,\n In_queue_before Message dec is_inc_dec\n   (append Message q1 (input Message copy q2)) ->\n In_queue_before Message dec is_inc_dec (append Message q1 q2).\nProof.\n  simple induction q1; simpl in |- *.\n  intros.\n  elim H; intro.\n  discriminate.\n  \n  auto.\n  \n  intro.\n  case d.\n  simpl in |- *.\n  intros.\n  auto.\n  \n  intro.\n  simpl in |- *.\n  auto.\n  \n  simpl in |- *.\n  intros.\n  right.\n  elim H0; intro.\n  discriminate.\n  \n  auto.\nQed.\n\nLemma alt_shuffle_copy1 :\n forall q1 q2 : queue Message,\n alternate (input Message copy (append Message q1 q2)) ->\n alternate (append Message q1 (input Message copy q2)).\nProof.\n  intros q1 q2.\n  elim q1.\n  simpl in |- *.\n  auto.\n  \n  simpl in |- *.\n  intro.\n  case d; intros.\n  apply alt_any_alt.\n  intro; discriminate.\n  \n  apply H.\n  inversion H0.\n  apply alt_any_alt.\n  intro; discriminate.\n  \n  inversion H4; auto.\n  \n  inversion H0.\n  apply alt_inc_dec.\n  apply H.\n  inversion H4.\n  apply alt_any_alt.\n  intro; discriminate.\n  \n  auto.\n  \n  inversion H4.\n  elim (H11 s); auto.\n  \n  apply alt_any_alt.\n  intro; discriminate; auto.\n  \n  auto.\n  \n  inversion H4.\n  elim (H7 s); auto.\n  \n  apply in_q_before_append.\n  auto.\n  \n  apply alt_any_alt.\n  intro; discriminate.\n  \n  apply H.\n  inversion H0.\n  auto.\nQed.\n\nLemma alt_shuffle_copy2 :\n forall q1 q2 : queue Message,\n alternate (append Message q1 (input Message copy q2)) ->\n alternate (append Message q1 q2).\nProof.\n  intros q1 q2.\n  elim q1.\n  simpl in |- *.\n  auto.\n  intro.\n  inversion H.\n  auto.\n  \n  simpl in |- *.\n  intro.\n  case d; intros.\n  apply alt_any_alt.\n  intro; discriminate.\n  \n  apply H.\n  inversion H0.\n  auto.\n  \n  inversion H0.\n  apply alt_inc_dec.\n  apply H.\n  auto.\n  \n  elim (H3 s); auto.\n  \n  apply alt_inc_dec.\n  apply H.\n  auto.\n  \n  apply in_q_before_append2.\n  auto.\n  \n  apply alt_any_alt.\n  intro; discriminate.\n  \n  inversion H0.\n  apply H.\n  auto.\nQed.\n\n\n\n\nLemma alt_shuffle_copy :\n forall q1 q2 q3 q4 : queue Message,\n append Message q1 q2 = append Message q3 q4 ->\n alternate (append Message q1 (input Message copy q2)) ->\n alternate (append Message q3 (input Message copy q4)).\nProof.\n  intros.\n  apply alt_shuffle_copy1.\n  rewrite <- H.\n  apply alt_any_alt.\n  intro; discriminate.\n  \n  generalize H0.\n  elim q1; simpl in |- *.\n  intro.\n  inversion H1; auto.\n  \n  intro.\n  case d; intros.\n  apply alt_any_alt.\n  intro; discriminate.\n  \n  apply H1.\n  inversion H2; auto.\n  \n  inversion H2.\n  elim (H5 s); auto.\n  \n  apply alt_inc_dec.\n  apply H1.\n  auto.\n  \n  apply in_q_before_append2.\n  auto.\n  \n  apply alt_any_alt.\n  intro; discriminate.\n  \n  apply H1.\n  inversion H2.\n  auto.\nQed.\n\n\nLemma D_shuffle_copy1 :\n forall q1 q2 : queue Message,\n D_queue (input Message copy (append Message q1 q2)) ->\n D_queue (append Message q1 (input Message copy q2)).\nProof.\n  intros q1 q2.\n  elim q1.\n  simpl in |- *.\n  auto.\n  \n  simpl in |- *.\n  intro.\n  case d; intros.\n  apply D_dec.\n  apply alt_any_alt.\n  intro; discriminate.\n  \n  apply alt_shuffle_copy1.\n  inversion H0.\n  inversion H1.\n  inversion H7.\n  apply alt_any_alt.\n  intro; discriminate.\n  \n  auto.\n  \n  simpl in |- *.\n  case (eq_bool_dec false); intro.\n  discriminate.\n  \n  auto.\n  \n  inversion H0.\n  generalize H2.\n  simpl in |- *.\n  case (eq_bool_dec false); intro.\n  discriminate.\n  \n  case (eq_bool_dec true); intro.\n  intro.\n  elim H4; intro.\n  discriminate.\n  \n  contradiction.\n  \n  discriminate.\n  \n  apply D_dec.\n  apply alt_any_alt.\n  intro; discriminate.\n  \n  apply alt_shuffle_copy1.\n  inversion H0.\n  inversion H1.\n  inversion H7.\n  apply alt_any_alt.\n  intro; discriminate.\n  \n  auto.\n  \n  simpl in |- *.\n  case (eq_bool_dec false); intro.\n  discriminate.\n  \n  right.\n  inversion H0.\n  generalize H2.\n  simpl in |- *.\n  case (eq_bool_dec false); intro.\n  discriminate.\n  \n  intro.\n  elim H4; intro.\n  discriminate.\n  \n  elim H5; intro.\n  discriminate.\n  \n  apply in_q_before_append.\n  auto.\nQed.\n\n\n\nLemma D_shuffle_copy :\n forall q1 q2 q3 q4 : queue Message,\n append Message q1 q2 = append Message q3 q4 ->\n D_queue (append Message q1 (input Message copy q2)) ->\n D_queue (append Message q3 (input Message copy q4)).\nProof.\n  intros.\n  apply D_shuffle_copy1.\n  apply D_dec.\n  inversion H0.\n  generalize H2.\n  case q1; simpl in |- *.\n  intro; discriminate.\n  \n  intros; discriminate.\n  \n  apply alt_any_alt.\n  intro; discriminate.\n  \n  apply alt_shuffle_copy2.\n  apply alt_shuffle_copy with (q1 := q1) (q2 := q2).\n  auto.\n  \n  auto.\n  \n  inversion H0.\n  generalize H2.\n  case q1; simpl in |- *; intros; discriminate.\n  \n  rewrite <- H.\n  simpl in |- *.\n  case (eq_bool_dec false); intro.\n  discriminate.\n  \n  right.\n  apply in_q_before_append2.\n  auto.\nQed.\n\n\n\n\nEnd MESS_ALT.\n\n", "meta": {"author": "coq-contribs", "repo": "distributed-reference-counting", "sha": "6552f14cce0ea374c98adcbee0476ae268d64a7e", "save_path": "github-repos/coq/coq-contribs-distributed-reference-counting", "path": "github-repos/coq/coq-contribs-distributed-reference-counting/distributed-reference-counting-6552f14cce0ea374c98adcbee0476ae268d64a7e/machine4/alternate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.21753918464385677}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import CtxtSwitchAux.Spec.\nRequire Import AbsAccessor.Spec.\nRequire Import CtxtSwitch.Specs.save_ns_state.\nRequire Import CtxtSwitch.LowSpecs.save_ns_state.\nRequire Import CtxtSwitch.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       save_ns_state_sysreg_state_spec\n       sysreg_read_spec\n       set_ns_state_spec\n    .\n\n  Lemma save_ns_state_spec_exists:\n    forall habd habd'  labd\n      (Hspec: save_ns_state_spec  habd = Some habd')\n      (Hrel: relate_RData habd labd),\n    exists labd', save_ns_state_spec0  labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque ptr_eq.\n    intros. destruct Hrel.\n    unfold save_ns_state_spec, save_ns_state_spec0 in *.\n    repeat autounfold in *. simpl in *.\n    hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec;\n      repeat destruct_con; bool_rel; simpl in *; srewrite;\n        repeat (simpl_htarget; grewrite; simpl in * ).\n    destruct regs_is_int64_dec in *. autounfold in e. repeat rewrite e.\n    repeat simpl_update_reg.\n    eexists; split. reflexivity. constructor. reflexivity.\n    inv C.\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/CtxtSwitch/RefProof/save_ns_state.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.21753918464385677}}
{"text": "Require Import ExtLib.Data.Fun.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.SymI.\nRequire Import MirrorCore.SubstI.\nRequire Import MirrorCore.EnvI.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.ExprSem.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.Lambda.AppN.\nRequire Import ILogic BILogic Pure.\nRequire Import MirrorCharge.BILNormalize.\nRequire Import MirrorCharge.SynSepLog.\nRequire Import MirrorCharge.OrderedCanceller.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection better_ordering.\n  Variable typ : Type.\n  Variable RType_typ : RType typ.\n  Variable Typ2_Fun : Typ2 _ Fun.\n  Variable func : Type.\n  Variable RSym_func : RSym func.\n\n  Variable tySL : typ.\n  Variable ILogicOps_SL : ILogicOps (typD tySL).\n  Variable BILOperators_SL : BILOperators (typD tySL).\n  Hypothesis ILogic_SL : @ILogic _ ILogicOps_SL.\n  Hypothesis BILogic_SL : @BILogic _ ILogicOps_SL BILOperators_SL.\n\n  (** dependencies are like [a -> b] **)\n  (** put things in as soon as they are solvable **)\n\n  (** NOTE: These are like a functor **)\n  Variable dependency : Type.\n  Variable dep_satisfied : dependency -> dependency -> option dependency.\n  Variable dep_for : expr typ func -> dependency.\n\n  Inductive Decorated :=\n  | DPure (_ : dependency) (_ : expr typ func) (_ : Decorated)\n  | DImpure (_ : dependency) (f : expr typ func) (xs : list (expr typ func)) (_ : Decorated)\n  | DFrame (_ : dependency) (_ : expr typ func) (xs : list (expr typ func)) (_ : Decorated)\n  | DEmp\n  | DTru.\n\n  Fixpoint forget_Decorated (d : Decorated) : Conjuncts typ func :=\n    match d with\n      | DPure _ p d => Pure p (forget_Decorated d)\n      | DImpure _ f xs d => Impure f xs (forget_Decorated d)\n      | DFrame _ f xs d => Frame f xs (forget_Decorated d)\n      | DEmp => Emp _ _\n      | DTru => Tru _ _\n    end.\n\n  Fixpoint insert_into (d : dependency) (dec : Decorated)\n           (here : Decorated -> Decorated)\n  : Decorated :=\n    match dec with\n      | DEmp => here DEmp\n      | DTru => here DTru\n      | DFrame d' xs ys rst => here (DFrame d' xs ys rst)\n      | DPure d' P rst =>\n        match dep_satisfied d' d with\n          | None => here (DPure d' P rst)\n          | Some d => DPure d' P (insert_into d rst here)\n        end\n      | DImpure d' f xs rst =>\n        match dep_satisfied d' d with\n          | None => here (DImpure d' f xs rst)\n          | Some d => DImpure d' f xs (insert_into d rst here)\n        end\n    end.\n\n  Definition better_order_decorated (c : conjunctives typ func)\n  : Decorated :=\n    List.fold_right (fun x acc =>\n                       match fst x with\n                         | UVar _ =>\n                           let d := dep_for (apps (fst x) (snd x)) in\n                           insert_into d acc (DFrame d (fst x) (snd x))\n                         | _ =>\n                           let d := dep_for (apps (fst x) (snd x)) in\n                           insert_into d acc (DImpure d (fst x) (snd x))\n                       end)\n                    (List.fold_right (fun x acc =>\n                                        let d := dep_for x in\n                                        insert_into d acc (DPure d x))\n                                     (if c.(star_true) then DTru else DEmp)\n                                     c.(pure))\n                    c.(spatial).\n\n\n  Definition better_order (c : conjunctives typ func) : Conjuncts typ func :=\n    forget_Decorated (better_order_decorated c).\n\n  Variable SSL : SynSepLog typ func.\n  Variable SSLO : SynSepLogOk _ _ _ _ _ SSL.\n\n  Variable PureOp_SL : @Pure.PureOp (typD tySL).\n  Variable Pure_SL : Pure.Pure PureOp_SL.\n  Hypothesis Pure_ltrue : Pure.pure ltrue.\n  Hypothesis Pure_land : forall a b,\n                           Pure.pure a -> Pure.pure b -> Pure.pure (a //\\\\ b).\n\n(*\n  Theorem simple_orderOk\n  : @order_spec ts func _ tySL ILogicOps_SL SSL _ simple_order.\n  Proof.\n    red.\n    intros; destruct c; simpl.\n    unfold conjunctives_to_expr_star, simple_order; simpl.\n    match goal with\n      | |- match ?X with _ => _ end =>\n        consider X; intros\n    end.\n    { repeat go_crazy SSL SSLO.\n      revert H0. generalize dependent x1.\n      induction spatial.\n     { simpl. admit. }\n      { simpl. intros.\n        eapply exprD'_iterated_base_cons_Some in H0; eauto.\n        destruct H0 as [ ? [ ? [ ? [ ? ? ] ] ] ].\n        assert (forall us vs,\n                  x0 us vs -|- x4 us vs ** x2 us vs).\n        { intros. rewrite H3. rewrite H5.\n          specialize (fun z => IHspatial _ z H4).\n          admit. }\n        { admit. } } }\n    { forward.\n(*      repeat go_crazy SSL SSLO. *)\n      admit. }\n  Qed.\n*)\nEnd better_ordering.\n", "meta": {"author": "jesper-bengtson", "repo": "MirrorCharge", "sha": "cb0fe1da80be70ba4b744d4178a4e6e3afa38e62", "save_path": "github-repos/coq/jesper-bengtson-MirrorCharge", "path": "github-repos/coq/jesper-bengtson-MirrorCharge/MirrorCharge-cb0fe1da80be70ba4b744d4178a4e6e3afa38e62/MirrorCharge!/src/MirrorCharge/DependencyOrder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.21753918464385677}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Relations.Relations.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Classes.RelationPairs.\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Events.\nRequire Import Lens.\nRequire Import LiftMem.\nRequire Import PowersetMonad.\n\nSection LIFTEXTCALL.\n  Context `{Hlm: LiftModel}.\n  Context `{ef_ops: ExtFunOps}.\n  Context `{ec_ops: !ExtCallOps bmem external_function}.\n  Context `{Hec: !ExternalCalls bmem external_function}.\n\n  Global Instance liftmem_ec_ops: ExtCallOps mem external_function := {\n    external_call ef F V ge args m tr ret m' :=\n      lift (fun m => external_call ef ge args m tr ret) m m'\n  }.\n\n  Lemma lift_mem_unchanged_on P m1 m2:\n    mem_unchanged_on P m1 m2 <->\n    mem_unchanged_on P (get π m1) (get π m2).\n  Proof.\n    tauto.\n  Qed.\n\n  Lemma lift_loc_out_of_reach f m1:\n    loc_out_of_reach f m1 = lift (loc_out_of_reach f) m1.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma lift_loc_out_of_bounds m:\n    loc_out_of_bounds m = lift loc_out_of_bounds m.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Hint Rewrite\n      @lift_mem_unchanged_on\n      @lift_loc_out_of_reach\n      @lift_loc_out_of_bounds\n    using typeclasses eauto : lift.\n\n  Hint Resolve\n    lens_same_context_eq : lift.\n\n  Global Instance liftmem_ec_spec: ExternalCalls mem external_function := {}.\n  Proof.\n    intro ef; split.\n    lift (ec_well_typed (external_call_spec ef)).\n    lift (ec_arity (external_call_spec ef)).\n    lift (ec_symbols_preserved (external_call_spec ef)).\n    lift (ec_valid_block (external_call_spec ef)).\n    lift (ec_max_perm (external_call_spec ef)).\n    lift (ec_readonly (external_call_spec ef)).\n    lift (ec_mem_extends (external_call_spec ef)).\n    lift_partial (ec_mem_inject (external_call_spec ef)).\n      split.\n      assumption.\n      eapply liftmem_inject_same_context_2; eassumption || congruence.\n    lift (ec_trace_length (external_call_spec ef)).\n    lift (ec_receptive (external_call_spec ef)).\n    lift (ec_determ (external_call_spec ef)).\n  Qed.\nEnd LIFTEXTCALL.\n", "meta": {"author": "jeremie-koenig", "repo": "compcert", "sha": "e58b5a076931637f2e7b13f6e9ba7a47e2cdc437", "save_path": "github-repos/coq/jeremie-koenig-compcert", "path": "github-repos/coq/jeremie-koenig-compcert/compcert-e58b5a076931637f2e7b13f6e9ba7a47e2cdc437/liblayers/LiftExtCall.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21753917886696678}}
{"text": "Require Import Relations RelationClasses.\nRequire Import List.\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.common.LanguageInterface.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Smallstep.\nRequire Import models.Coherence.\n\nUnset Program Cases.\nLocal Obligation Tactic := cbn.\n\n\n(** * Coherence spaces for CompCertO semantics *)\n\n(** ** Language interfaces *)\n\nCoercion li_space (li : language_interface) : space :=\n  input (query li) ;; output (reply li).\n\n(** ** CompCert events *)\n\n(*\nInductive ev_coh : relation event :=\n  | Event_syscall_coh s1 s2 args1 args2 res1 res2 :\n      (s1 = s2 -> args1 = args2 -> res1 = res2) ->\n      ev_coh (Event_syscall s1 args1 res1) (Event_syscall s2 args2 res2)\n  | Event_vload_coh ...\n\nProgram Definition Ev :=\n  {|\n    token := event;\n    coh e1 e2 := \n*)\n\n\n(** * CompCert semantics *)\n\n(** Note that Reddy's object semantics have a rather coarse-grained\n  handling of undefined behaviors, which is inherited by our CompCert\n  semantics. Silent divergence and undefined behaviors are also\n  conflated.\n\n  The preliminary definition below loses information about the domains\n  of component, which would make it impossible to define mutually\n  recursive horizontal composition in a satisfactory way. However for\n  now we don't need it so we don't care. Ultimately we could\n  incoroporate it in the type of the semantics by using\n  [input (query li) ;; (1 + output (reply li)] instead of [li_space]\n  for the codomain.\n\n  Finally, everything in CompCertO happens in the context of a global\n  symbol table, so we need to specify one to get the component's\n  semantics. Again this could be an [input Genv.symtbl ;; ...] component\n  in the interaction but for now this is the simpler approach. *)\n\n(** ** Semantics of transition systems *)\n\nSection LTS.\n  Context {liA liB S} (L : lts liA liB S).\n\n  (** [lts_trace s t r] asserts that the transition system [L] reaches\n    a final state with reply [r] from the state [s], with the sequence\n    of external calls encoded by the trace [t]. *)\n\n  Inductive lts_trace : S -> token !liA -> reply liB -> Prop :=\n    | lts_trace_final (s : S) (r : reply liB) :\n        final_state L s r ->\n        lts_trace s nil r\n    | lts_trace_step (s s' : S) (t : token !liA) (r : reply liB) :\n        Step L s E0 s' ->\n        lts_trace s' t r ->\n        lts_trace s t r\n    | lts_trace_external s qx rx s' t r :\n        at_external L s qx ->\n        after_external L s rx s' ->\n        lts_trace s' t r ->\n        lts_trace s ((qx, rx) :: t) r.\n\n  Inductive lts_lmaps : token !liA -> token liB -> Prop :=\n    | lts_lmaps_intro q s t r :\n        valid_query L q = true ->\n        initial_state L q s ->\n        lts_trace s t r ->\n        lts_lmaps t (q, r).\n\nEnd LTS.\n\nLtac determ_solve' :=\n  auto ||\n       match goal with\n       | [ |- False -> _ ] => inversion 1\n       | [ |- _ = _ -> _ ] => intros <-\n       | [ |- _ = _ /\\ _ = _ -> _ ] => intros [<- <-]\n       | [ |- _ = _ /\\ _ = _ /\\ _ = _ -> _ ] => intros [<- [<- <-]]\n       | [ |- _ -> _ ] => intros\n       end.\n\nLtac determ_solve determ :=\n  match goal with\n  | [ P : _ , Q : _ |- _ ] =>\n    exploit determ;\n    [ exact P | exact Q | determ_solve' ]\n  | _ => fail\n  end.\n\nSection SEMANTICS.\n  Context {liA liB} (L : semantics liA liB) (HL : determinate L).\n\n  Lemma trace_determ se s es es' r r' :\n    list_coh liA es es' ->\n    lts_trace (L se) s es r ->\n    lts_trace (L se) s es' r' ->\n    es = es' /\\ r = r'.\n  Proof.\n    intros coh h h'.\n    revert es' coh h'.\n    induction h; intros es' coh lts; inversion lts; subst.\n    + determ_solve (sd_final_determ (HL se)).\n    + determ_solve (sd_final_nostep (HL se)).\n    + determ_solve (sd_final_noext (HL se)).\n    + determ_solve (sd_final_nostep (HL se)).\n    + determ_solve (sd_determ_2 (HL se)).\n      eapply IHh. apply coh. apply H1.\n    + determ_solve (sd_at_external_nostep (HL se)).\n    + determ_solve (sd_final_noext (HL se)).\n    + determ_solve (sd_at_external_nostep (HL se)).\n    + specialize (IHh t0).\n      determ_solve (sd_at_external_determ (HL se)).\n      inversion coh as [ | | ? ? ? ? cohx cohxs]; subst.\n      destruct cohx as [cohq cohr].\n      exploit cohr. auto. intros <-.\n      determ_solve (sd_after_external_determ (HL se)).\n      split; f_equal; apply IHh; try apply cohxs; auto.\n  Qed.\n\n  Program Definition compcerto_lmap se : !liA --o liB :=\n    {|\n      has '(t, u) := lts_lmaps (L se) t u;\n    |}.\n  Next Obligation.\n    intros se [eas [qb rb]] [eas' [qb' rb']] lmap lmap' coheas.\n    split.\n    - split; auto.\n      intros <-.\n      inversion lmap as [? ? ? ? valid_q init_q transition_q]. subst.\n      inversion lmap' as [? ? ? ? valid_q' init_q' transition_q']. subst.\n      determ_solve (sd_initial_determ (HL se)).\n      exploit trace_determ.\n      exact coheas. exact transition_q. exact transition_q'.\n      intuition.\n    - intros h. destruct h.\n      inversion lmap as [? ? ? ? valid_q init_q transition_q]. subst.\n      inversion lmap' as [? ? ? ? valid_q' init_q' transition_q']. subst.\n      determ_solve (sd_initial_determ (HL se)).\n      exploit trace_determ.\n      exact coheas. exact transition_q. exact transition_q'.\n      intuition.\n  Qed.\nEnd SEMANTICS.\n\n(** ** Clight semantics *)\n\n(** As an example, here is the semantics of Clight programs in terms\n  of linear maps. *)\n\nRequire Clight.\n\n(** *** Proof of determinism *)\n\nSection EXPR_DETERM.\n  Variable ge: Clight.genv.\n  Variable e: Clight.env.\n  Variable le: Clight.temp_env.\n  Variable m: Memory.Mem.mem.\n\n  Lemma deref_loc_determ t mem loc ofs v1 v2:\n    Clight.deref_loc t mem loc ofs v1 ->\n    Clight.deref_loc t mem loc ofs v2 ->\n    v1 = v2.\n  Proof.\n    induction 1; inversion 1; subst; congruence.\n  Qed.\n\n  Ltac find_specialize :=\n    match goal with\n    | [ H : forall x, ?P x -> _, X : _, H1 : ?P ?X |- _ ] => specialize (H _ H1)\n    | [ H : forall x y, ?P x y -> _, X : _, Y : _,  H1 : ?P ?X ?Y |- _ ] => specialize (H _ _ H1)\n    | _ => idtac\n    end.\n\n  Ltac expr_determ_solve :=\n    repeat find_specialize; try split; f_equal; congruence || easy.\n\n  Lemma expr_determ:\n    (forall a v1,\n        Clight.eval_expr ge e le m a v1 ->\n        forall v2,\n          Clight.eval_expr ge e le m a v2 ->\n          v1 = v2)\n    /\\\n    (forall a b1 ofs1,\n        Clight.eval_lvalue ge e le m a b1 ofs1 ->\n        forall b2 ofs2,\n          Clight.eval_lvalue ge e le m a b2 ofs2 ->\n          b1 = b2 /\\ ofs1 = ofs2).\n  Proof.\n    apply Clight.eval_expr_lvalue_ind.\n    - inversion 1; expr_determ_solve.\n    - inversion 1; expr_determ_solve.\n    - inversion 1; expr_determ_solve.\n    - inversion 1; expr_determ_solve.\n    - inversion 2; expr_determ_solve.\n    - intros. inversion H1; expr_determ_solve.\n    - intros. inversion H2; expr_determ_solve.\n    - intros. inversion H4; expr_determ_solve.\n    - intros. inversion H2; expr_determ_solve.\n    - inversion 1; expr_determ_solve.\n    - inversion 1; expr_determ_solve.\n    - intros. inversion H2; subst; try easy.\n      exploit H0. exact H3.\n      intros [<- <-].\n      determ_solve deref_loc_determ.\n    - inversion 2; expr_determ_solve.\n    - inversion 3; expr_determ_solve.\n    - inversion 3; expr_determ_solve.\n    - intros. inversion H4; expr_determ_solve.\n    - intros. inversion H3; expr_determ_solve.\n  Qed.\n\n  Lemma eval_expr_determ:\n    forall a v1,\n      Clight.eval_expr ge e le m a v1 ->\n        forall v2,\n          Clight.eval_expr ge e le m a v2 ->\n          v1 = v2.\n  Proof.\n    intros. eapply expr_determ; eauto.\n  Qed.\n\n  Lemma eval_lvalue_determ:\n    forall a b1 ofs1,\n      Clight.eval_lvalue ge e le m a b1 ofs1 ->\n      forall b2 ofs2,\n        Clight.eval_lvalue ge e le m a b2 ofs2 ->\n        b1 = b2 /\\ ofs1 = ofs2.\n  Proof.\n    intros. eapply expr_determ; eauto.\n  Qed.\n\n  Lemma eval_exprlist_determ es ty vs1 vs2:\n    Clight.eval_exprlist ge e le m es ty vs1 ->\n    Clight.eval_exprlist ge e le m es ty vs2 ->\n    vs1 = vs2.\n  Proof.\n    intros eval1. revert vs2.\n    induction eval1.\n    - inversion 1. auto.\n    - intros vs2 eval2.\n      inversion eval2; subst.\n      determ_solve eval_expr_determ.\n      exploit IHeval1.\n      exact H8. congruence.\n  Qed.\nEnd EXPR_DETERM.\n\nLemma assign_loc_determ ge t m loc ofs v m1 m2:\n    Clight.assign_loc ge t m loc ofs v m1 ->\n    Clight.assign_loc ge t m loc ofs v m2 ->\n    m1 = m2.\nProof.\n  inversion 1; inversion 1; congruence.\nQed.\n\nLemma alloc_variables_determ ge e m vars e1 e2 m1 m2:\n    Clight.alloc_variables ge e m vars e1 m1 ->\n    Clight.alloc_variables ge e m vars e2 m2 ->\n    e1 = e2 /\\ m1 = m2.\nProof.\n  intros alloc1. revert e2 m2.\n  induction alloc1.\n  - inversion 1. auto.\n  - inversion 1; subst.\n    rewrite H in H8. injection H8. intros <- <-.\n    exploit IHalloc1. exact H9. auto.\nQed.\n\nLemma bind_parameters_determ ge e m params vargs m1 m2:\n  Clight.bind_parameters ge e m params vargs m1 ->\n  Clight.bind_parameters ge e m params vargs m2 ->\n  m1 = m2.\nProof.\n  intros bind1. revert m2.\n  induction bind1.\n  - inversion 1. auto.\n  - inversion 1; subst.\n    assert (b = b0) by congruence. subst.\n    determ_solve assign_loc_determ.\n    exploit IHbind1. exact H11. auto.\nQed.\n\nLemma func_entry1_determ ge f vargs m e1 le1 m1 e2 le2 m2:\n  Clight.function_entry1 ge f vargs m e1 le1 m1 ->\n  Clight.function_entry1 ge f vargs m e2 le2 m2 ->\n  e1 = e2 /\\ le1 = le2 /\\ m1 = m2.\nProof.\n  inversion 1. inversion 1.\n  determ_solve alloc_variables_determ.\n  firstorder. congruence.\n  determ_solve bind_parameters_determ.\nQed.\n\nLtac false_solve :=\n  match goal with\n  | [ H : _ \\/ _ |- _ ] => inversion H; easy\n  | _ => idtac\n  end.\n\nHint Constructors match_traces.\nLtac autoc := auto || congruence || easy.\n\nLemma step_determ p se s t1 s1 t2 s2:\n  Step ((Clight.semantics1 p) se) s t1 s1 ->\n  Step ((Clight.semantics1 p) se) s t2 s2 ->\n  match_traces se t1 t2 /\\ (t1 = t2 -> s1 = s2).\nProof.\n  intros step1 step2.\n  inversion step1; subst;\n    inversion step2; subst; false_solve;\n      try (split; autoc).\n  + determ_solve eval_expr_determ.\n    determ_solve eval_lvalue_determ.\n    assert (v = v1) as <- by congruence.\n    determ_solve assign_loc_determ.\n    split; autoc.\n  + determ_solve eval_expr_determ.\n    split; auto.\n  + determ_solve eval_expr_determ.\n    assert (tyargs0 = tyargs) by congruence. subst.\n    determ_solve eval_exprlist_determ.\n    split; auto.\n  + determ_solve eval_exprlist_determ.\n    determ_solve external_call_determ.\n    split. apply H1.\n    intros. exploit (proj2 H1).\n    auto. intros [<- <-]. auto.\n  + determ_solve eval_expr_determ.\n    split. auto.\n    assert (b = b0) by congruence. subst; auto.\n  + split; try autoc.\n    determ_solve eval_expr_determ. autoc.\n  + determ_solve eval_expr_determ. split; autoc.\n  + assert (f = f0) by congruence. subst.\n    determ_solve func_entry1_determ.\n    split; autoc.\n  + assert (ef = ef0) by congruence. subst.\n    determ_solve external_call_determ.\n    split. apply H0.\n    intros. exploit (proj2 H0). auto.\n    intros [<- <-]. auto.\nQed.\n\nLemma clight_single_event p se:\n  single_events ((Clight.semantics1 p) se).\nProof.\n  unfold single_events. intros.\n  inversion H; auto; eapply external_call_trace_length; eauto.\nQed.\n\nHint Unfold globalenv.\nHint Unfold Clight.globalenv.\n\nLemma clight_determinate p :\n  determinate (Clight.semantics1 p).\nProof.\n  split.\n  - apply step_determ.\n  - apply clight_single_event.\n  - inversion 1; inversion 1; congruence.\n  - inversion 1.\n    replace (Clight.globalenv se p) with (globalenv ((Clight.semantics1 p) se)) in H0 by auto.\n    inversion 1; subst; rewrite H0 in FIND; subst f.\n    + easy.\n    + injection FIND. intros <- <- <- <-.\n      easy.\n  - inversion 1; inversion 1; subst. f_equal.\n    assert (f = f0) by congruence.\n    subst f f0. congruence.\n  - inversion 1; inversion 1; subst. auto.\n  - inversion 1; inversion 1.\n  - inversion 1; inversion 1.\n  - inversion 1; inversion 1; subst. auto.\nQed.\n\n(** *** Coherence space Clight semantics *)\n\nDefinition clight (p : Clight.program) se : !li_c --o li_c :=\n  compcerto_lmap (Clight.semantics1 p) (clight_determinate p) se.\n\n(** ** Soundness of forward simulations *)\n\n(** Since for now, our model doesn't support abstraction, we can only\n  consider simulations which use the [cc_id] simulation convention. *)\n\nSection FSIM.\n  Context {liA liB} (L1 L2 : semantics liA liB).\n  Context (H1 : determinate L1).\n  Context (H2 : determinate L2).\n  Context (FSIM : forward_simulation 1 1 L1 L2).\n  Context (se : Genv.symtbl) (Hse : Genv.valid_for (skel L1) se).\n\n  (** XXX: we need a notion of refinement on linear maps themselves,\n    or perhaps just define linear maps as cliques in the function\n    space. *)\n\n  Lemma fsim_sound :\n    ref (compcerto_lmap L1 H1 se) (compcerto_lmap L2 H2 se).\n  Proof.\n    intros [t u] Ht. cbn in *.\n    destruct FSIM as [[ind ord match_states _ H _]]. cbn in *.\n    specialize (H se se tt eq_refl Hse).\n    destruct Ht as [q s1 t1 r Hq1 Hs1 Ht1].\n    edestruct @fsim_match_initial_states as (i & s2 & Hs2 & Hs);\n      eauto; try reflexivity.\n    econstructor.\n    - erewrite fsim_match_valid_query; eauto. reflexivity.\n    - eauto.\n    - clear - H Hs Ht1. revert i s2 Hs.\n      induction Ht1; cbn; intros.\n      + (* final state *)\n        edestruct @fsim_match_final_states as (xr & Hs2 & Hxr); eauto.\n        destruct Hxr.\n        constructor; auto.\n      + (* step *)\n        edestruct @simulation_star as (j & s2' & Hs2' & Hs'); eauto using star_one.\n        revert Hs'. pattern s2, s2'.\n        eapply star_E0_ind; eauto using lts_trace_step.\n      + (* external interaction *)\n        edestruct @fsim_match_external as (w & xq & Hq2 & Hxq & _ & Hrx); eauto.\n        destruct Hxq.\n        edestruct Hrx as (j & s2' & Hs2' & Hs'); cbn; eauto using lts_trace_external.\n  Qed.\nEnd FSIM.\n", "meta": {"author": "CertiKOS", "repo": "rbgs", "sha": "2802704c2ee0068a78874b7424aad09d69ce34b0", "save_path": "github-repos/coq/CertiKOS-rbgs", "path": "github-repos/coq/CertiKOS-rbgs/rbgs-2802704c2ee0068a78874b7424aad09d69ce34b0/examples/CompCertSem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.21753917886696675}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Import terms2.\n\n\nLemma deq_nvar_refl :\n  forall v, deq_nvar v v = left eq_refl.\nProof.\n  introv.\n  destruct (deq_nvar v v); sp.\n  generalize (@UIPReflDeq NVar deq_nvar v e); intro k.\n  rw k; auto.\nQed.\n\nLtac boolvar_step :=\n  match goal with\n    | [ |- context[beq_var ?v ?v] ] => rewrite <- beq_var_refl\n    | [ |- context[deq_nvar ?v ?v] ] => rewrite deq_nvar_refl\n    | [ |- context[deq_nvar ?v1 ?v2] ] =>\n      destruct (deq_nvar v1 v2);[try(subst v1)|];try(complete auto)\n    | [ |- context[memvar ?v ?s] ] =>\n        let name := fresh \"b\" in\n          remember (memvar v s) as name;\n        match goal with\n          | [ H : name = memvar v s |- _ ] =>\n              symmetry in H;\n              destruct name;\n              [ rewrite fold_assert in H;\n                  trw_h assert_memvar H;\n                  simpl in H\n              | trw_h not_of_assert H;\n                  trw_h assert_memvar H;\n                  simpl in H\n              ]\n        end\n    | [ |- context[beq_var ?v1 ?v2] ] =>\n        let name := fresh \"b\" in\n          remember (beq_var v1 v2) as name;\n        match goal with\n          | [ H : name = beq_var v1 v2 |- _ ] =>\n            destruct name;\n              [ apply beq_var_true in H; try subst\n              | apply beq_var_false in H\n              ]\n        end\n\n    | [ H : context[beq_var ?v ?v] |- _ ] => rewrite <- beq_var_refl in H\n    | [ H : context[deq_nvar ?v ?v] |- _ ] => rewrite deq_nvar_refl in H\n    | [ H : context[deq_nvar ?v1 ?v2] |- _ ] =>\n      destruct (deq_nvar v1 v2);[try(subst v1)|];try(complete auto)\n    | [ H : context[memvar ?v ?s] |- _ ] =>\n      let name := fresh \"b\" in\n      remember (memvar v s) as name;\n        match goal with\n          | [ J : name = memvar v s |- _ ] =>\n            symmetry in J;\n              destruct name;\n              [ rewrite fold_assert in J;\n                trw_h assert_memvar J;\n                simpl in J\n              | trw_h not_of_assert J;\n                trw_h assert_memvar J;\n                simpl in J\n              ]\n        end\n    | [ H : context[beq_var ?v1 ?v2] |- _ ] =>\n        let name := fresh \"b\" in\n        remember (beq_var v1 v2) as name;\n          match goal with\n            | [ J : name = beq_var v1 v2 |- _ ] =>\n              destruct name;\n                [ apply beq_var_true in J; try subst\n                | apply beq_var_false in J\n                ]\n          end\n\n    | [ |- context[if ?x then _ else _] ] =>\n      match type of x with\n        | {_} + {_} => destruct x\n      end\n    | [ |- context[if ?x then _ else _] ] =>\n      match type of x with\n        | sum _ _ => destruct x\n      end\n    | [ |- context[if ?x then _ else _] ] =>\n      match type of x with\n        | decidable _ => destruct x\n      end\n    | [ |- context[d2b ?x] ] =>\n      match type of x with\n        | decidable _ => destruct x\n      end\n\n    | [H : context[if ?x then _ else _] |- _ ] =>\n      match type of x with\n        | {_} + {_} => destruct x\n      end\n    | [H : context[if ?x then _ else _] |- _ ] =>\n      match type of x with\n        | sum _ _ => destruct x\n      end\n    | [H : context[if ?x then _ else _] |- _ ] =>\n      match type of x with\n        | decidable _ => destruct x\n      end\n    | [H : context[d2b ?x] |- _ ] =>\n      match type of x with\n        | decidable _ => destruct x\n      end\n\n    | [ |- context[deq_nat           ?x ?y] ] => destruct (deq_nat           x y)\n    | [ |- context[String.string_dec ?x ?y] ] => destruct (String.string_dec x y)\n    | [ |- context[opsign_dec        ?x ?y] ] => destruct (opsign_dec        x y)\n    | [ |- context[Z_noteq_dec       ?x ?y] ] => destruct (Z_noteq_dec       x y)\n    | [ |- context[parameter_dec     ?x ?y] ] => destruct (parameter_dec     x y)\n    | [ |- context[parameters_dec    ?x ?y] ] => destruct (parameters_dec    x y)\n\n    | [ H : context[deq_nat           ?x ?y] |- _ ] => destruct (deq_nat           x y)\n    | [ H : context[String.string_dec ?x ?y] |- _ ] => destruct (String.string_dec x y)\n    | [ H : context[opsign_dec        ?x ?y] |- _ ] => destruct (opsign_dec        x y)\n    | [ H : context[Z_noteq_dec       ?x ?y] |- _ ] => destruct (Z_noteq_dec       x y)\n    | [ H : context[parameter_dec     ?x ?y] |- _ ] => destruct (parameter_dec     x y)\n    | [ H : context[parameters_dec    ?x ?y] |- _ ] => destruct (parameters_dec    x y)\n\n    | [ H : context[if memberb _ _ _ then _ else _] |- _ ] => rewrite memberb_din in H\n    | [ |- context[if memberb _ _ _ then _ else _] ] => rewrite memberb_din\n  end.\n\nLtac boolvar := repeat boolvar_step.\n\n\nLemma fold_mk_prod {o} :\n  forall (a : @NTerm o) v b,\n    v = newvar b\n    -> mk_product a v b = mk_prod a b.\nProof.\n  introv e; subst; sp.\nQed.\n\nLemma fold_mk_fun {o} :\n  forall (a : @NTerm o) v b,\n    v = newvar b\n    -> mk_function a v b = mk_fun a b.\nProof.\n  introv e; subst; sp.\nQed.\n\nLemma fold_mk_ufun {o} :\n  forall (a : @NTerm o) v b,\n    v = newvar b\n    -> mk_isect a v b = mk_ufun a b.\nProof.\n  introv e; subst; sp.\nQed.\n\nLemma int_zero {o} :\n  @mk_integer o 0 = mk_zero.\nProof. sp. Qed.\n\nDefinition absolute_value {o} (t : @NTerm o) :=\n  mk_less t mk_zero (mk_minus t) t.\n\nLtac fold_terms_step :=\n  match goal with\n    | [ |- context[@oterm ?p (Can NAxiom) []] ] => fold (@mk_axiom p)\n    | [ |- context[@oterm ?p (Can NInt) []] ] => fold (@mk_int p)\n    | [ |- context[@oterm ?p (Can (NUTok ?a)) []] ] => fold (@mk_utoken p a)\n    | [ |- context[@oterm ?p (Can (NTok ?a)) []] ] => fold (@mk_token p a)\n    | [ |- context[@mk_approx ?p mk_axiom mk_axiom] ] => fold (@mk_true p)\n    | [ |- context[@mk_approx ?p mk_axiom mk_bot] ] => fold (@mk_false p)\n    | [ |- context[@mk_lam ?p nvarx (mk_var nvarx)] ] => fold (@mk_id p)\n    | [ |- context[@mk_fix ?p mk_id] ] => fold (@mk_bottom p)\n    | [ |- context[@mk_bottom ?p] ] => fold (@mk_bot p)\n    | [ |- context[@bterm ?p [] ?x] ] => fold (@nobnd p x)\n    | [ |- context[@vterm ?p ?v] ] => fold (@mk_var p v)\n    | [ |- context[@oterm ?p (Can (Nint ?z)) []] ] => fold (@mk_integer p z)\n    | [ |- context[@mk_integer ?p (Z.of_nat ?n)] ] => fold (@mk_nat p n)\n    | [ |- context[@mk_nat ?p 0] ] => fold (@mk_zero p)\n    | [ |- context[@oterm ?p (Can (Nseq ?f)) []] ] => fold (@mk_nseq p f)\n    | [ |- context[oterm (Can NLambda) [bterm [?v] ?t]] ] => fold (mk_lam v t)\n    | [ |- context[oterm (Can NApprox) [nobnd ?a, nobnd ?b]] ] => fold (mk_approx a b)\n    | [ |- context[oterm (Can NEquality) [nobnd ?a, nobnd ?b, nobnd ?c]] ] => fold (mk_equality a b c)\n    | [ |- context[oterm (Can NREquality) [nobnd ?a, nobnd ?b, nobnd ?c]] ] => fold (mk_requality a b c)\n    | [ |- context[oterm (Can NFreeFromAtom) [nobnd ?a, nobnd ?b, nobnd ?c]] ] => fold (mk_free_from_atom a b c)\n    | [ |- context[oterm (Can NEFreeFromAtom) [nobnd ?a, nobnd ?b, nobnd ?c]] ] => fold (mk_efree_from_atom a b c)\n    | [ |- context[oterm (Can NFreeFromAtoms) [nobnd ?a, nobnd ?b]] ] => fold (mk_free_from_atoms a b)\n    | [ |- context[oterm (Can NFunction) [nobnd ?a, bterm [?v] ?b]] ] => fold (mk_function a v b)\n    | [ |- context[oterm (Can NProduct) [nobnd ?a, bterm [?v] ?b]] ] => fold (mk_product a v b)\n    | [ |- context[oterm (Can NUnion) [nobnd ?x, nobnd ?y]] ] => fold (mk_union x y)\n    | [ |- context[oterm (Can NEUnion) [nobnd ?x, nobnd ?y]] ] => fold (mk_eunion x y)\n    | [ |- context[oterm (Can NTExc) [nobnd ?x, nobnd ?y]] ] => fold (mk_texc x y)\n    | [ |- context[oterm (NCan NApply) [nobnd ?x, nobnd ?y]] ] => fold (mk_apply x y)\n    | [ |- context[oterm (NCan NEApply) [nobnd ?x, nobnd ?y]] ] => fold (mk_eapply x y)\n(*    | [ |- context[oterm (NCan (NApseq ?f)) [nobnd ?x] ] ] => fold (mk_apseq f x)*)\n    | [ |- context[oterm (NCan NDecide) [nobnd ?d, bterm [?x] ?f, bterm [?y] ?g]] ] => fold (mk_decide d x f y g)\n    | [ |- context[oterm (NCan NSpread) [nobnd ?p, bterm [?x,?y] ?f]] ] => fold (mk_spread p x y f)\n    | [ |- context[oterm (NCan NTryCatch) [nobnd ?a, nobnd ?b, bterm [?v] ?c]] ] => fold (mk_try a b v c)\n    | [ |- context[oterm (NCan NFix) [nobnd ?x]] ] => unfold nobnd; fold (mk_fix x); try (fold nobnd)\n    | [ |- context[oterm (NCan NCbv) [nobnd ?a, bterm [?v] ?b]] ] => fold (mk_cbv a v b)\n    | [ |- context[oterm (NCan NFresh) [bterm [?v] ?b]] ] => fold (mk_fresh v b)\n    | [ |- context[oterm (NCan (NCompOp CompOpLess)) [nobnd ?a, nobnd ?b, nobnd ?c, nobnd ?d]] ] => fold (mk_less a b c d)\n    | [ |- context[oterm Exc [nobnd ?a, nobnd ?x]] ] => fold (mk_exception a x)\n    | [ |- context[oterm (Can NIsect) [nobnd ?a, bterm [?v] ?b] ] ] => fold (mk_isect a v b)\n    | [ |- context[oterm (Can NSet) [nobnd ?a, bterm [?v] ?b] ] ] => fold (mk_set a v b)\n    | [ |- context[oterm (NCan NMinus) [nobnd ?a] ] ] => fold (mk_minus a)\n    | [ |- context[mk_equality ?t ?t ?T] ] => fold (mk_member t T)\n    | [ |- context[mk_less ?t mk_zero (mk_minus ?t) ?t] ] => fold (absolute_value t)\n    | [ |- context[mk_less ?a ?b mk_true mk_false] ] => fold (mk_less_than a b)\n    | [ |- context[@mk_integer ?o 0] ] => rewrite (@int_zero o)\n    | [ |- context[@mk_false ?o] ] => fold (@mk_void o)\n    | [ |- context[mk_fun ?a mk_void] ] => fold (mk_not a)\n    | [ |- context[mk_not (mk_less_than ?b ?a)] ] => fold (mk_le a b)\n\n    | [ H : ?v = newvar ?b |- context[mk_product ?a ?v ?b] ] => rewrite (fold_mk_prod a v b H)\n    | [ H : ?v = newvar ?b |- context[mk_function ?a ?v ?b] ] => rewrite (fold_mk_fun a v b H); auto\n    | [ H : ?v = newvar ?b |- context[mk_isect ?a ?v ?b] ] => rewrite (fold_mk_ufun a v b H); auto\n\n    | [ H : context[@oterm ?p (Can NAxiom) []] |- _ ] => fold (@mk_axiom p) in H\n    | [ H : context[@oterm ?p (Can NInt) []] |- _ ] => fold (@mk_int p) in H\n    | [ H : context[@oterm ?p (Can (NUTok ?a)) []] |- _ ] => fold (@mk_utoken p a) in H\n    | [ H : context[@oterm ?p (Can (NTok ?a)) []] |- _ ] => fold (@mk_token p a) in H\n    | [ H : context[@mk_approx ?p mk_axiom mk_axiom] |- _ ] => fold (@mk_true p) in H\n    | [ H : context[@mk_approx ?p mk_axiom mk_bot] |- _ ] => fold (@mk_false p) in H\n    | [ H : context[@mk_lam ?p nvarx (mk_var nvarx)] |- _ ] => fold (@mk_id p) in H\n    | [ H : context[@mk_fix ?p mk_id] |- _ ] => fold (@mk_bottom p) in H\n    | [ H : context[@mk_bottom ?p] |- _ ] => fold (@mk_bot p) in H\n    | [ H : context[@bterm ?p [] ?x] |- _ ] => fold (@nobnd p x) in H\n    | [ H : context[@vterm ?p ?v] |- _ ] => fold (@mk_var p v) in H\n    | [ H : context[@oterm ?p (Can (Nint ?z)) []] |- _ ] => fold (@mk_integer p z) in H\n    | [ H : context[@mk_integer ?p (Z.of_nat ?n)] |- _ ] => fold (@mk_nat p n) in H\n    | [ H : context[@mk_nat ?p 0] |- _ ] => fold (@mk_zero p) in H\n    | [ H : context[@oterm ?p (Can (Nseq ?f)) []] |- _ ] => fold (@mk_nseq p f) in H\n    | [ H : context[oterm (Can NLambda) [bterm [?v] ?t]] |- _ ] => fold (mk_lam v t) in H\n    | [ H : context[oterm (Can NApprox) [nobnd ?a, nobnd ?b]] |- _ ] => fold (mk_approx a b) in H\n    | [ H : context[oterm (Can NEquality) [nobnd ?a, nobnd ?b, nobnd ?c]] |- _ ] => fold (mk_equality a b c) in H\n    | [ H : context[oterm (Can NREquality) [nobnd ?a, nobnd ?b, nobnd ?c]] |- _ ] => fold (mk_requality a b c) in H\n    | [ H : context[oterm (Can NFreeFromAtom) [nobnd ?a, nobnd ?b, nobnd ?c]] |- _ ] => fold (mk_free_from_atom a b c) in H\n    | [ H : context[oterm (Can NEFreeFromAtom) [nobnd ?a, nobnd ?b, nobnd ?c]] |- _ ] => fold (mk_efree_from_atom a b c) in H\n    | [ H : context[oterm (Can NFreeFromAtoms) [nobnd ?a, nobnd ?b]] |- _ ] => fold (mk_free_from_atoms a b) in H\n    | [ H : context[oterm (Can NFunction) [nobnd ?a, bterm [?v] ?b]] |- _ ] => fold (mk_function a v b) in H\n    | [ H : context[oterm (Can NProduct) [nobnd ?a, bterm [?v] ?b]] |- _ ] => fold (mk_product a v b) in H\n    | [ H : context[oterm (Can NUnion) [nobnd ?x, nobnd ?y]] |- _ ] => fold (mk_union x y) in H\n    | [ H : context[oterm (Can NEUnion) [nobnd ?x, nobnd ?y]] |- _ ] => fold (mk_eunion x y) in H\n    | [ H : context[oterm (Can NTExc) [nobnd ?x, nobnd ?y]] |- _ ] => fold (mk_texc x y) in H\n    | [ H : context[oterm (NCan NApply) [nobnd ?x, nobnd ?y]] |- _ ] => fold (mk_apply x y) in H\n    | [ H : context[oterm (NCan NEApply) [nobnd ?x, nobnd ?y]] |- _ ] => fold (mk_eapply x y) in H\n(*    | [ H : context[oterm (NCan (NApseq ?f)) [nobnd ?x] ] |- _ ] => fold (mk_apseq f x) in H*)\n    | [ H : context[oterm (NCan NDecide) [nobnd ?d, bterm [?x] ?f, bterm [?y] ?g]] |- _ ] => fold (mk_decide d x f y g) in H\n    | [ H : context[oterm (NCan NSpread) [nobnd ?p, bterm [?x,?y] ?f]] |- _ ] => fold (mk_spread p x y f) in H\n    | [ H : context[oterm (NCan NTryCatch) [nobnd ?a, nobnd ?b, bterm [?v] ?c]] |- _ ] => fold (mk_try a b v c) in H\n    | [ H : context[oterm (NCan NFix) [nobnd ?x]] |- _ ] => unfold nobnd in H; fold (mk_fix x) in H; try (fold nobnd in H)\n    | [ H : context[oterm (NCan NCbv) [nobnd ?a, bterm [?v] ?b]] |- _ ] => fold (mk_cbv a v b) in H\n    | [ H : context[oterm (NCan NFresh) [bterm [?v] ?b]] |- _ ] => fold (mk_fresh v b) in H\n    | [ H : context[oterm (NCan (NCompOp CompOpLess)) [nobnd ?a, nobnd ?b, nobnd ?c, nobnd ?d]] |- _ ] => fold (mk_less a b c d) in H\n    | [ H : context[oterm Exc [nobnd ?a, nobnd ?x]] |- _ ] => fold (mk_exception a x) in H\n    | [ H : context[oterm (Can NIsect) [nobnd ?a, bterm [?v] ?b] ] |- _ ] => fold (mk_isect a v b) in H\n    | [ H : context[oterm (Can NSet) [nobnd ?a, bterm [?v] ?b] ] |- _ ] => fold (mk_set a v b) in H\n    | [ H : context[oterm (NCan NMinus) [nobnd ?a] ] |- _ ] => fold (mk_minus a) in H\n    | [ H : context[mk_equality ?t ?t ?T] |- _ ] => fold (mk_member t T) in H\n    | [ H : context[mk_less ?t mk_zero (mk_minus ?t) ?t] |- _ ] => fold (absolute_value t) in H\n    | [ H : context[mk_less ?a ?b mk_true mk_false] |- _ ] => fold (mk_less_than a b) in H\n    | [ H : context[@mk_integer ?o 0] |- _ ] => rewrite (@int_zero o) in H\n    | [ H : context[@mk_false ?o] |- _ ] => fold (@mk_void o) in H\n    | [ H : context[mk_fun ?a mk_void] |- _ ] => fold (mk_not a) in H\n    | [ H : context[mk_not (mk_less_than ?b ?a)] |- _ ] => fold (mk_le a b) in H\n\n    | [ H : ?v = newvar ?b, J : context[mk_product ?a ?v ?b] |- _ ] => rewrite (fold_mk_prod a v b H) in J; auto\n    | [ H : ?v = newvar ?b, J : context[mk_function ?a ?v ?b] |- _ ] => rewrite (fold_mk_fun a v b H) in J; auto\n    | [ H : ?v = newvar ?b, J : context[mk_isect ?a ?v ?b] |- _ ] => rewrite (fold_mk_ufun a v b H) in J; auto\n\n  end.\n\nLtac fold_terms := repeat fold_terms_step.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/terms/terms_tacs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.217521971845722}}
{"text": "\nRequire Import String. Import StringSyntax.       \nFrom Ling Require Import BS. \nImport Ling.\n\n(* Is this relevant? *)   \n\nAdd LoadPath  \"/local/res/josh/coq\" as Ling.\n\n(* First compile BS.v as follows.\n /Applications/CoqIDE_8.13.1.app/Contents/Resources/bin/coqc -Q . Ling -vos BS.v\n\nJosh has put in changes from BSm.v.\n*)\n\n\n\n(* muddy, copulatives *)\n\nDefinition muddy : AP := ET \"muddy\".\nDefinition is : (DP \\ S) / AP := fun x y => x y.\n \n\n(* Generalized bind *)\nDefinition gbind {a b c : Cat} (x : a || b -- c) : a || (c >> b) -- c :=\n  fun k => x (fun e => k e e).\n\n(* This is going to be thhe type of a structured antecedent. *)\n\nNotation \"x [ y ]\" := (Focus y x) (at level 30, format \"x [ y ]\").\n\nDefinition bought := mkTV \"bought\".\nDefinition lunch : DP := Ec \"lunch\".\nDefinition alice : DP := Ec \"alice\".\n(* Definition focus (x : DP) : DP[DP] := (x, id). *)\nDefinition focus {a : Cat} (x : a) : a[a] := (x, id).\n\n\nDefinition fextract {a b c d : Cat} (x : a || b -- (c[d])) : a || b -- c := fmap (fun (s : c[d]) => (snd s) (fst s)) x.\n\nDefinition fappf {a b c : Cat} (y : a / b) (x : b[c]) : a[c] :=\n  (fst x, fun a => y (snd x a)).\nDefinition fappb {a b c : Cat} (x : b[c]) (y : b \\ a) : a[c] := \n  (fst x, fun a => y (snd x a)).\n\nNotation \"x :f> y\" := (fappf x y) (at level 40).\nNotation \"x <f: y\" := (fappb x y) (at level 40).\n\nDefinition contrast {a} (f : S || S -- (S[a])) : (S[a] >> S) || S -- S := (fun k old => k (f (fun new => (snd new) (fst new) /\\ (snd new) = (snd old) /\\ (fst new) <> (fst old)))).\n\nDefinition ALICE_bought_lunch : S || (S[DP] >> S) -- S := \n    fextract (gbind (lift (focus alice <f: (bought :> lunch)))).\n\nDefinition JOHN_bought_lunch := \n    contrast (lift (focus john <f: (bought :> lunch))).\n\n\nCheck ALICE_bought_lunch.\nEval compute in ALICE_bought_lunch.\n(*\n     = fun k : Prop -> E * (E -> Prop) -> Prop =>\n       k (EET \"bought\" (Ec \"lunch\") (Ec \"alice\"))\n         (Ec \"alice\",\n         fun a : E => EET \"bought\" (Ec \"lunch\") a)\n     : \nS || S[DP] >> S\n--\nS\n*)\n\nCheck bought :> lunch.\nCheck focus (bought :> lunch).\nCheck geach alice.\nCheck (geach alice) :f> (focus (bought :> lunch)).\n\nCheck fextract (gbind (lift ((geach alice) :f> (focus (bought :> lunch))))).\n\n(*\nDefinition ALICE_bought_lunch : S || (S[DP] >> S) -- S := \n    fextract (gbind (lift (focus alice <f: (bought :> lunch)))).\n*)\n\n(* Structured VP-proposition antecedent. NB this does not have to do with focus. *)\n\nDefinition alice_BOUGHT_LUNCH : S || (S[DP \\ S] >> S) -- S := \n    fextract (gbind (lift ((geach alice) :f> (focus (bought :> lunch))))). \n\nCheck alice_BOUGHT_LUNCH. \n(*\nS || S[DP \\ S] >> S\n--\nS\n*)\n\nEval compute in alice_BOUGHT_LUNCH.\n\n\n(*\n     = fun\n         k : Prop ->\n             (E -> Prop) * ((E -> Prop) -> Prop) -> Prop\n       =>\n       k (EET \"bought\" (Ec \"lunch\") (Ec \"alice\"))\n         (EET \"bought\" (Ec \"lunch\"),               VP antecedent\n         fun a : E -> Prop => a (Ec \"alice\"))      Abstract of the rest of the sentence.\n\n(E -> Prop) * ((E -> Prop) -> Prop) is the type of the structured antecedent.  It's a pair of\na property and a proposition with a property hole.\n\n\nThe category of the structured binder is\n\nS || S[DP \\ S] >> S\n--\nS\n\nindicating power to bind a S[DP \\ S] pronoun. The category of [BEN did ---] should be\n\nS[DP \\ S] >> S || S\n--\nS\n\nindicating a S[DP \\ S] pronoun that is seeking an antecedent.\n\nThis is the type of [BEN is muddy] in the analysis from focus.v.  It indicates an unbound pronoun of \npropositional type.\n\nlower (focus ben <| lift (is :> muddy))\n     : \n(S >> S) || S\n--\nS\n\nAnd this is the semantics.\n\n\nfun (f : Prop -> Prop) (p : Prop) =>\n       f (alt p (fun x : E => ET \"muddy\" x) (Ec \"ben\")) /\\\n       ET \"muddy\" (Ec \"ben\"\n*)\n\n(* Comment out stuff from older version.\n\nEval compute in (lower (ALICE_bought_lunch <| (lift and |> JOHN_bought_lunch))).\n\n\n How is this related to focus? \n\nDefinition only {b : Cat} (x : b) : S || S -- (b).\n  simpl.\n  refine (fun k => k x /\\ forall z, k z -> z = x).\nDefined.\n\nEval compute in (lower (only john <| (lift (bought :> lunch)))). *)\n\n(* Individuals *)\nDefinition ari : DP := Ec \"ari\".\nDefinition ben : DP := Ec \"ben\".\n\n(* Copied from focus.v renaming focus to foc. *)\n\nParameter (alt : Prop -> ((interp DP) -> Prop) -> (interp DP) -> Prop).\n\nDefinition foc (x : DP) : ((S >> S) || S -- S)|| S -- DP :=\n  fun k => (fun f => (fun p => (f (alt p k x)) /\\ k x)).\n\n\n(* Example with focus anaphora. This should be modified to parasitic focus-vp anaphora. *)\n\nCheck lower ((gbind (lift (ari <: (is :> muddy)))) <| \n      ((lift and) |> (lower ((foc ben)  <| (lift (is :> muddy)))))).\n\n\nEval compute in lower ((gbind (lift (ari <: (is :> muddy)))) <| \n      ((lift and) |> (lower ((foc ben)  <| (lift (is :> muddy)))))).\n\n(* \nFirst conjunct of the focus example. It donates the antecedent using gbind. \n\nS || S >> S\n--\nS\n*)\n\nCheck gbind (lift (ari <: (is :> muddy))) : S || S >> S -- S.\nCheck alice_BOUGHT_LUNCH.\n\n(*\nIt is comparable to this, which binds S[DP\\S] rather than S.\nS || S[DP \\ S] >> S\n--\nS\n\n*)\n\n(* The semantics for the first clauses compare as follows. The first function plugs in\nthe left conjunct proposition twice.\n\nfun k : Prop -> Prop -> Prop =>\n    k (ET \"muddy\" (Ec \"ari\"))\n      (ET \"muddy\" (Ec \"ari\"))\n\nThe function for the structured antecedent ...\n\nfun\n  k : Prop ->                              Bound variable in position of left S.\n      (E -> Prop) * ((E -> Prop) -> Prop)  Bound for a structured proposition.\n          -> Prop\n       =>\n       k\n         (EET \"bought\" (Ec \"lunch\")        Locally plug in the propistion 'alice bought lunch'\n            (Ec \"alice\"))\n         (EET \"bought\" (Ec \"lunch\"),       Distally plug in the structured proposition.\n         fun a : E -> Prop => a (Ec \"alice\"))\n\n*)\n\nEval compute in gbind (lift (ari <: (is :> muddy))) : S || S >> S -- S.\n\nEval compute in alice_BOUGHT_LUNCH.\n\n(*\nLook at the right conjunct for the focus case, to try to figure out what the right conjunct\nfor the ellipsis case should be.\n\n(S >> S) || S\n--\nS\n\nfun (f : Prop -> Prop)  Rest of the tree, with an argument for the local proposition position.\n    (p : Prop)          Antecedent proposition.\n    => f\n         (alt p (fun x : E => ET \"muddy\" x)\n            (Ec \"ben\")) /\\\n       ET \"muddy\" (Ec \"ben\")\n\nGuess the semantics of BEN_F_did.\n\nfun (f : Prop -> Prop)  Rest of the tree, maybe this is the same.\n    (x : (E -> Prop) * ((E -> Prop) -> Prop)) antecedent structured proposition, it is a pair, use fst, snd.\n    => f\n         (alt ((snd x) (fst x)) (fun y : E => (fst x) y)\n            (Ec \"ben\")) /\\\n       (fst x) (Ec \"ben\")\n*) \n\nCheck lower ((foc ben)  <| (lift (is :> muddy))). \nEval compute in lower ((foc ben)  <| (lift (is :> muddy))).\n\nDefinition BEN_F_is_muddy : ((S >> S) || S -- S) := lower ((foc (ben : DP))  <| (lift (is :> muddy))).\n\nCheck BEN_F_is_muddy.\n\nDefinition BEN_F_did : ((S[DP \\ S] >> S) || S -- S) :=\n      fun (f : Prop -> Prop)   \n      (x : (E -> Prop) * ((E -> Prop) -> Prop))  \n    => f\n         (alt ((snd x) (fst x)) (fun y : E => (fst x) y)\n            (Ec \"ben\")) /\\\n       (fst x) (Ec \"ben\").\n\nCheck BEN_F_did.\n(*\n(S[DP \\ S] >> S) || S\n--\nS\n*)\n\nEval compute in alice_BOUGHT_LUNCH.\nCheck lower ((alice_BOUGHT_LUNCH <| ((lift and) |> BEN_F_did))).\n\nEval compute in lower ((alice_BOUGHT_LUNCH <| ((lift and) |> BEN_F_did))).\n\n(*\n(EET \"bought\" (Ec \"lunch\") (Ec \"alice\") /\\\n        alt\n          (EET \"bought\" (Ec \"lunch\")\n             (Ec \"alice\"))\n          (fun y : E =>\n           EET \"bought\" (Ec \"lunch\") y)\n          (Ec \"ben\")) /\\\n       EET \"bought\" (Ec \"lunch\") (Ec \"ben\")\n     : S\nThis looks good.\nThe conjunct in the middle is the focus presupposition.\n\n*)\n\n\n", "meta": {"author": "gancherj", "repo": "lingstuff", "sha": "6ec8fa606caa4d08046f29b0f7f6a55f1a51683e", "save_path": "github-repos/coq/gancherj-lingstuff", "path": "github-repos/coq/gancherj-lingstuff/lingstuff-6ec8fa606caa4d08046f29b0f7f6a55f1a51683e/SFocus.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.217521971845722}}
{"text": "Require Import FP.Data.Function.\nRequire Import FP.Data.List.\nRequire Import FP.Data.Option.\nRequire Import FP.Structures.Alternative.\nRequire Import FP.Structures.Applicative.\nRequire Import FP.Structures.Eqv.\nRequire Import FP.Structures.Functor.\nRequire Import FP.Structures.MonadFix.\n\nImport AlternativeNotation.\nImport ApplicativeNotation.\nImport FunctionNotation.\nImport FunctorNotation.\nImport ListNotation.\n\nClass LLParser T p :=\n  { ll_parser_Applicative :> Applicative p\n  ; ll_parser_Alternative :> Alternative p\n  ; parse_refine : forall {A}, (T -> option A) -> p A\n  }.\n\nSection LLParser.\n  Context {p T} {pP:LLParser T p}.\n\n  Context {tE:EqvDec T}.\n\n  Context {MF:MonadFix p}.\n\n  Definition parse_predicate (f:T -> bool) : p T :=\n    parse_refine (fun x => if f x then Some x else None).\n  Definition parse_token (t:T) : p T := parse_predicate (eqv_dec t).\n  Fixpoint parse_sequence (ts:list T) : p (list T) :=\n    match ts with\n    | nil => fret nil\n    | t::ts' => cons <$> parse_token t <@> parse_sequence ts'\n    end.\n\n  Fixpoint count {A} (i:nat) (aP:p A) : p (list A) :=\n    match i with\n    | O => fret nil\n    | S i' => cons <$> aP <@> count i' aP\n    end.\n\n  Definition optional {A} (aP:p A) : p (option A) :=\n    Some <$> aP <|> fret None.\n\n  Definition between {O C A} (open:p O) (close:p C) (aP:p A) : p A :=\n    open @> aP <@ close.\n\n\n  Definition many {A} : p A -> p (list A) :=\n    mfix $ fun many a =>\n      cons <$> a <@> many a\n      <|>\n      fret nil.\n\n  Definition many1 {A} (aP:p A) : p (list A) :=\n    cons <$> aP <@> many aP.\n\n  Definition sep_by {A B} (aP:p A) (sep:p B) : p (list A) :=\n    cons <$> aP <@> many (const id <$> sep <@> aP).\n\n  Definition sep_opt_begin_by {A B} (aP:p A) (sep:p B) : p (list A) :=\n    optional sep @> sep_by aP sep.\n\n  Definition many_till {A B} : p A -> p B -> p (list A) :=\n    mfix2 $ fun many_till aP nd =>\n      const nil <$> nd\n      <|>\n      cons <$> aP <@> many_till aP nd.\nEnd LLParser.\n", "meta": {"author": "davdar", "repo": "coq-fp", "sha": "d0b752d9ea9592ba0bc7b067b46a63740fcff056", "save_path": "github-repos/coq/davdar-coq-fp", "path": "github-repos/coq/davdar-coq-fp/coq-fp-d0b752d9ea9592ba0bc7b067b46a63740fcff056/tmp/Structures/LLParser.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.21752197184572197}}
{"text": "From distris Require Export lang network.\nFrom stdpp Require Export strings.\nSet Default Proof Using \"Type\".\n\nImport Network.\n\nNotation \"½\" := (1/2)%Qp.\nNotation \"¼\" := (1/4)%Qp.\nNotation \"¾\" := (3/4)%Qp.\n\nCoercion LitInt : Z >-> base_lit.\nCoercion LitBool : bool >-> base_lit.\nCoercion LitLoc : loc >-> base_lit.\nCoercion LitAddressFamily : address_family >-> base_lit.\nCoercion LitSocketType : socket_type >-> base_lit.\nCoercion LitProtocol : protocol >-> base_lit.\nCoercion LitSocketAddress : socket_address >-> base_lit.\nCoercion LitString : string >-> base_lit.\n\nCoercion App : ground_lang.expr >-> Funclass.\nCoercion of_val : val >-> expr.\nCoercion ground_lang.of_val : ground_lang.val >-> ground_lang.expr.\n\nCoercion Var : string >-> ground_lang.expr.\n\nCoercion BNamed : string >-> binder.\nNotation \"<>\" := BAnon : binder_scope.\n\n(* Definition mkExpr (n : node) (e : ground_lang.expr) := (n,e) : expr. *)\n(* Definition mkVal (n : node) (v : ground_lang.val) := (n,v) : val. *)\n\n(* Note that the scope for expressions and values are NOT the same:\n   Expressions have brackets that comes from the sequence \\<, with name\n   MATHEMATICAL LEFT ANGLE BRACKET where as values has brackets\n   that come from \\〈 (name: LEFT-POINTING ANGLE BRACKET) *)\nNotation \"⟨ n ; e ⟩\" := (mkExpr n e)\n                      (at level 0, right associativity). \nNotation \"〈 n ; v 〉\" := (mkVal n v%V).\n\n(* No scope for the values, does not conflict and scope is often not inferred\nproperly. *)\nNotation \"# l\" := (LitV l%Z%V) (at level 8, format \"# l\").\nNotation \"# l\" := (Lit l%Z%V) (at level 8, format \"# l\") : expr_scope.\n\n(** Syntax inspired by Coq/Ocaml. Constructions with higher precedence come\n    first. *)\nNotation \"( e1 , e2 , .. , en )\" := (Pair .. (Pair e1 e2) .. en) : expr_scope.\nNotation \"( e1 , e2 , .. , en )\" := (PairV .. (PairV e1 e2) .. en) : val_scope.\n\n(*\nUsing the '[hv' ']' printing box, we make sure that when the notation for match\ndoes not fit on a single line, line breaks will be inserted for *each* breaking\npoint '/'. Note that after each breaking point /, one can put n spaces (for\nexample '/  '). That way, when the breaking point is turned into a line break,\nindentation of n spaces will appear after the line break. As such, when the\nmatch does not fit on one line, it will print it like:\n\n  match: e0 with\n    InjL x1 => e1\n  | InjR x2 => e2\n  end\n\nMoreover, if the branches do not fit on a single line, it will be printed as:\n\n  match: e0 with\n    InjL x1 =>\n\n  | InjR x2 =>\n    even more stuff bla bla bla bla bla bla bla bla\n  end\n*)\nNotation \"'match:' e0 'with' 'InjL' x1 => e1 | 'InjR' x2 => e2 'end'\" :=\n  (Match e0 x1%bind e1 x2%bind e2)\n  (e0, x1, e1, x2, e2 at level 200,\n   format \"'[hv' 'match:'  e0  'with'  '/  ' '[' 'InjL'  x1  =>  '/  ' e1 ']'  '/' '[' |  'InjR'  x2  =>  '/  ' e2 ']'  '/' 'end' ']'\") : expr_scope.\nNotation \"'match:' e0 'with' 'InjR' x1 => e1 | 'InjL' x2 => e2 'end'\" :=\n  (Match e0 x2%bind e2 x1%bind e1)\n  (e0, x1, e1, x2, e2 at level 200, only parsing) : expr_scope.\n\nNotation \"()\" := LitUnit : val_scope.\nNotation \"! e\" := (Load e%E) (at level 9, right associativity) : expr_scope.\nNotation \"'ref' e\" := (Alloc e%E)\n  (at level 30, right associativity) : expr_scope.\nNotation \"- e\" := (UnOp MinusUnOp e%E)\n  (at level 35, right associativity) : expr_scope.\nNotation \"e1 + e2\" := (BinOp PlusOp e1%E e2%E)\n  (at level 50, left associativity) : expr_scope.\nNotation \"e1 - e2\" := (BinOp MinusOp e1%E e2%E)\n  (at level 50, left associativity) : expr_scope.\nNotation \"e1 ≤ e2\" := (BinOp LeOp e1%E e2%E) (at level 70) : expr_scope.\nNotation \"e1 < e2\" := (BinOp LtOp e1%E e2%E) (at level 70) : expr_scope.\nNotation \"e1 = e2\" := (BinOp EqOp e1%E e2%E) (at level 70) : expr_scope.\nNotation \"e1 ^^ e2\" := (BinOp StringApp e1%E e2%E) (at level 70) : expr_scope.\nNotation \"e1 ≠ e2\" := (UnOp NegOp (BinOp EqOp e1%E e2%E)) (at level 70) : expr_scope.\nNotation \"~ e\" := (UnOp NegOp e%E) (at level 75, right associativity) : expr_scope.\n(* The unicode ← is already part of the notation \"_ ← _; _\" for bind. *)\nNotation \"e1 <- e2\" := (Store e1%E e2%E) (at level 80) : expr_scope.\n\n(* The breaking point '/  ' makes sure that the body of the rec is indented\nby two spaces in case the whole rec does not fit on a single line. *)\nNotation \"'rec:' f x := e\" := (Rec f%bind x%bind e%E)\n  (at level 102, f at level 1, x at level 1, e at level 200,\n   format \"'[' 'rec:'  f  x  :=  '/  ' e ']'\") : expr_scope.\nNotation \"'rec:' f x := e\" := (locked (RecV f%bind x%bind e%E))\n  (at level 102, f at level 1, x at level 1, e at level 200,\n   format \"'[' 'rec:'  f  x  :=  '/  ' e ']'\") : val_scope.\nNotation \"'if:' e1 'then' e2 'else' e3\" := (If e1%E e2%E e3%E)\n  (at level 200, e1, e2, e3 at level 200) : expr_scope.\n\n(** Derived notions, in order of declaration. The notations for let and seq\nare stated explicitly instead of relying on the Notations Let and Seq as\ndefined above. This is needed because App is now a coercion, and these\nnotations are otherwise not pretty printed back accordingly. *)\nNotation \"'rec:' f x y .. z := e\" := (Rec f%bind x%bind (Lam y%bind .. (Lam z%bind e%E) ..))\n  (at level 102, f, x, y, z at level 1, e at level 200,\n   format \"'[' 'rec:'  f  x  y  ..  z  :=  '/  ' e ']'\") : expr_scope.\nNotation \"'rec:' f x y .. z := e\" := (locked (RecV f%bind x%bind (Lam y%bind .. (Lam z%bind e%E) ..)))\n  (at level 102, f, x, y, z at level 1, e at level 200,\n   format \"'[' 'rec:'  f  x  y  ..  z  :=  '/  ' e ']'\") : val_scope.\n\n(* The breaking point '/  ' makes sure that the body of the λ: is indented\nby two spaces in case the whole λ: does not fit on a single line. *)\nNotation \"λ: x , e\" := (Lam x%bind e%E)\n  (at level 102, x at level 1, e at level 200,\n   format \"'[' 'λ:'  x ,  '/  ' e ']'\") : expr_scope.\nNotation \"λ: x y .. z , e\" := (Lam x%bind (Lam y%bind .. (Lam z%bind e%E) ..))\n  (at level 102, x, y, z at level 1, e at level 200,\n   format \"'[' 'λ:'  x  y  ..  z ,  '/  ' e ']'\") : expr_scope.\n\n(* When parsing lambdas, we want them to be locked (so as to avoid needless\nunfolding by tactics and unification). However, unlocked lambda-values sometimes\nappear as part of compound expressions, in which case we want them to be pretty\nprinted too. We achieve that by first defining the non-locked notation, and then\nthe locked notation. Both will be used for pretty-printing, but only the last\nwill be used for parsing. *)\nNotation \"λ: x , e\" := (LamV x%bind e%E)\n  (at level 102, x at level 1, e at level 200,\n   format \"'[' 'λ:'  x ,  '/  ' e ']'\") : val_scope.\nNotation \"λ: x , e\" := (locked (LamV x%bind e%E))\n  (at level 102, x at level 1, e at level 200,\n   format \"'[' 'λ:'  x ,  '/  ' e ']'\") : val_scope.\nNotation \"λ: x y .. z , e\" := (LamV x%bind (Lam y%bind .. (Lam z%bind e%E) .. ))\n  (at level 102, x, y, z at level 1, e at level 200,\n   format \"'[' 'λ:'  x  y  ..  z ,  '/  ' e ']'\") : val_scope.\nNotation \"λ: x y .. z , e\" := (locked (LamV x%bind (Lam y%bind .. (Lam z%bind e%E) .. )))\n  (at level 102, x, y, z at level 1, e at level 200,\n   format \"'[' 'λ:'  x  y  ..  z ,  '/  ' e ']'\") : val_scope.\n\n\nNotation \"'let:' x := e1 'in' e2\" := (Lam x%bind e2%E e1%E)\n  (at level 102, x at level 1, e1, e2 at level 200,\n   format \"'[' 'let:'  x  :=  '[' e1 ']'  'in'  '/' e2 ']'\") : expr_scope.\nNotation \"e1 ;; e2\" := (Lam BAnon e2%E e1%E)\n  (at level 100, e2 at level 200,\n   format \"'[' '[hv' '[' e1 ']'  ;;  ']' '/' e2 ']'\") : expr_scope.\n\n(* Shortcircuit Boolean connectives *)\nNotation \"e1 && e2\" :=\n  (If e1%E e2%E (Lit (LitBool false))) (only parsing) : expr_scope.\nNotation \"e1 || e2\" :=\n  (If e1%E (Lit (LitBool true)) e2%E) (only parsing) : expr_scope.\n\n(** Notations for option *)\nNotation NONE := (InjL #()) (only parsing).\nNotation SOME x := (InjR x) (only parsing).\n\nNotation NONEV := (InjLV #()) (only parsing).\nNotation SOMEV x := (InjRV x) (only parsing).\n\nNotation \"'match:' e0 'with' 'NONE' => e1 | 'SOME' x => e2 'end'\" :=\n  (Match e0 BAnon e1 x%bind e2)\n  (e0, e1, x, e2 at level 200, only parsing) : expr_scope.\nNotation \"'match:' e0 'with' 'SOME' x => e2 | 'NONE' => e1 'end'\" :=\n  (Match e0 BAnon e1 x%bind e2)\n    (e0, e1, x, e2 at level 200, only parsing) : expr_scope.\n", "meta": {"author": "mkroghj", "repo": "aneris", "sha": "b2be05891029578fd6e4e22705a73567b5897af3", "save_path": "github-repos/coq/mkroghj-aneris", "path": "github-repos/coq/mkroghj-aneris/aneris-b2be05891029578fd6e4e22705a73567b5897af3/dist_lang/notation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.21752197184572197}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation, either version 2 of the License, or  *)\n(*  (at your option) any later version.  This file is also distributed *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file defines a number of data types and operations used in\n  the abstract syntax trees of many of the intermediate languages. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import ClassesAndNotations.\nSet Implicit Arguments.\n\n(** * Syntactic elements *)\n\n(** Identifiers (names of local variables, of global symbols and functions,\n  etc) are represented by the type [positive] of positive integers. *)\n\n(*c2t* super short *)\nDefinition ident := positive.\n\nDefinition ident_eq := peq.\n\n(** The intermediate languages are weakly typed, using only two types:\n  [Tint] for integers and pointers, and [Tfloat] for floating-point\n  numbers. *)\n\nInductive typ : Type :=\n  | Tint : typ\n  | Tfloat : typ.\n\nDefinition typesize (ty: typ) : Z :=\n  match ty with Tint => 4 | Tfloat => 8 end.\n\nLemma typesize_pos: forall ty, typesize ty > 0.\nProof. destruct ty; simpl; omega. Qed.\n\nLemma typ_eq: forall (t1 t2: typ), {t1=t2} + {t1<>t2}.\nProof. decide equality. Qed.\n\n\nModule TypEqDec <: EQUALITY_TYPE.\n  Definition t := typ.\n  Global Instance EqDec_t: EqDec typ :=\n  { eq_dec := typ_eq}.\nEnd TypEqDec.\n\n\nLemma opt_typ_eq: forall (t1 t2: option typ), {t1=t2} + {t1<>t2}.\nProof. decide equality. apply typ_eq. Qed.\n\n(** Additionally, function definitions and function calls are annotated\n  by function signatures indicating the number and types of arguments,\n  as well as the type of the returned value if any.  These signatures\n  are used in particular to determine appropriate calling conventions\n  for the function. *)\n\nRecord signature : Type := mksignature {\n  sig_args: list typ;\n  sig_res: option typ\n}.\n\nDefinition proj_sig_res (s: signature) : typ :=\n  match s.(sig_res) with\n  | None => Tint\n  | Some t => t\n  end.\n\n(** Memory accesses (load and store instructions) are annotated by\n  a ``memory chunk'' indicating the type, size and signedness of the\n  chunk of memory being accessed. *)\n\nInductive memory_chunk : Type :=\n  | Mint8signed : memory_chunk     (**r 8-bit signed integer *)\n  | Mint8unsigned : memory_chunk   (**r 8-bit unsigned integer *)\n  | Mint16signed : memory_chunk    (**r 16-bit signed integer *)\n  | Mint16unsigned : memory_chunk  (**r 16-bit unsigned integer *)\n  | Mint32 : memory_chunk          (**r 32-bit integer, or pointer *)\n  | Mfloat32 : memory_chunk        (**r 32-bit single-precision float *)\n  | Mfloat64 : memory_chunk.       (**r 64-bit double-precision float *)\n\n(** The type (integer/pointer or float) of a chunk. *)\n\nDefinition type_of_chunk (c: memory_chunk) : typ :=\n  match c with\n  | Mint8signed => Tint\n  | Mint8unsigned => Tint\n  | Mint16signed => Tint\n  | Mint16unsigned => Tint\n  | Mint32 => Tint\n  | Mfloat32 => Tfloat\n  | Mfloat64 => Tfloat\n  end.\n\n(** Initialization data for global variables. *)\n\nInductive init_data: Type :=\n  | Init_int8: int -> init_data\n  | Init_int16: int -> init_data\n  | Init_int32: int -> init_data\n  | Init_float32: float -> init_data\n  | Init_float64: float -> init_data\n  | Init_space: Z -> init_data\n  | Init_addrof: ident -> int -> init_data.  (**r address of symbol + offset *)\n\n(** Information attached to global variables. *)\n\nRecord globvar (V: Type) : Type := mkglobvar {\n  gvar_info: V;                    (**r language-dependent info, e.g. a type *)\n  gvar_init: list init_data;       (**r initialization data *)\n  gvar_readonly: bool;             (**r read-only variable? (const) *)\n  gvar_volatile: bool              (**r volatile variable? *)\n}.\n\n(** Whole programs consist of:\n- a collection of function definitions (name and description);\n- the name of the ``main'' function that serves as entry point in the program;\n- a collection of global variable declarations (name and information).\n\nThe type of function descriptions and that of additional information\nfor variables vary among the various intermediate languages and are\ntaken as parameters to the [program] type.  The other parts of whole\nprograms are common to all languages. *)\n\nRecord program (F V: Type) : Type := mkprogram {\n  prog_funct: list (ident * F);\n  prog_main: ident;\n  prog_vars: list (ident * globvar V)\n}.\n\nDefinition prog_funct_names (F V: Type) (p: program F V) : list ident :=\n  map (@fst ident F) p.(prog_funct).\n\nDefinition prog_var_names (F V: Type) (p: program F V) : list ident :=\n  map (@fst ident (globvar V)) p.(prog_vars).\n\n(** * Generic transformations over programs *)\n\n(** We now define a general iterator over programs that applies a given\n  code transformation function to all function descriptions and leaves\n  the other parts of the program unchanged. *)\n\nSection TRANSF_PROGRAM.\n\nVariable A B V: Type.\nVariable transf: A -> B.\n\nDefinition transf_program (l: list (ident * A)) : list (ident * B) :=\n  List.map (fun id_fn => (fst id_fn, transf (snd id_fn))) l.\n\nDefinition transform_program (p: program A V) : program B V :=\n  mkprogram\n    (transf_program p.(prog_funct))\n    p.(prog_main)\n    p.(prog_vars).\n\nLemma transform_program_function:\n  forall p i tf,\n  In (i, tf) (transform_program p).(prog_funct) ->\n  exists f, In (i, f) p.(prog_funct) /\\ transf f = tf.\nProof.\n  simpl. unfold transf_program. intros.\n  exploit list_in_map_inv; eauto. \n  intros [[i' f] [EQ IN]]. simpl in EQ. inversion EQ; subst. \n  exists f; split; auto.\nQed.\n\nEnd TRANSF_PROGRAM.\n\n(** The following is a variant of [transform_program] where the\n  code transformation function can fail and therefore returns an\n  option type. *)\n\n\nOpen Local Scope string_scope.\n\nSection MAP_PARTIAL.\n\nVariable A B C: Type.\nVariable prefix_errmsg: A -> errmsg.\nVariable f: B -> res C.\n\nFixpoint map_partial (l: list (A * B)) : res (list (A * C)) :=\n  match l with\n  | nil => OK nil\n  | (a, b) :: rem =>\n      match f b with\n      | Error msg => Error (prefix_errmsg a ++ msg)%list\n      | OK c =>\n          do rem' <- map_partial rem; \n          OK ((a, c) :: rem')\n      end\n  end.\n\nRemark In_map_partial:\n  forall l l' a c,\n  map_partial l = OK l' ->\n  In (a, c) l' ->\n  exists b, In (a, b) l /\\ f b = OK c.\nProof.\n  induction l; simpl.\n  intros. inv H. elim H0.\n  intros until c. destruct a as [a1 b1].\n  caseEq (f b1); try congruence.\n  intro c1; intros. monadInv H0. \n  elim H1; intro. inv H0. exists b1; auto. \n  exploit IHl; eauto. intros [b [P Q]]. exists b; auto.\nQed.\n\nRemark map_partial_forall2:\n  forall l l',\n  map_partial l = OK l' ->\n  list_forall2\n    (fun (a_b: A * B) (a_c: A * C) =>\n       fst a_b = fst a_c /\\ f (snd a_b) = OK (snd a_c))\n    l l'.\nProof.\n  induction l; simpl.\n  intros. inv H. constructor.\n  intro l'. destruct a as [a b].\n  caseEq (f b). 2: congruence. intro c; intros. monadInv H0.  \n  constructor. simpl. auto. auto. \nQed.\n\nEnd MAP_PARTIAL.\n\nRemark map_partial_total:\n  forall (A B C: Type) (prefix: A -> errmsg) (f: B -> C) (l: list (A * B)),\n  map_partial prefix (fun b => OK (f b)) l =\n  OK (List.map (fun a_b => (fst a_b, f (snd a_b))) l).\nProof.\n  induction l; simpl.\n  auto.\n  destruct a as [a1 b1]. rewrite IHl. reflexivity.\nQed.\n\nRemark map_partial_identity:\n  forall (A B: Type) (prefix: A -> errmsg) (l: list (A * B)),\n  map_partial prefix (fun b => OK b) l = OK l.\nProof.\n  induction l; simpl.\n  auto.\n  destruct a as [a1 b1]. rewrite IHl. reflexivity.\nQed.\n\nSection TRANSF_PARTIAL_PROGRAM.\n\nVariable A B V: Type.\nVariable transf_partial: A -> res B.\n\nDefinition prefix_name (id: ident) : errmsg :=\n  MSG \"In function \" :: CTX id :: MSG \": \" :: nil.\n\nDefinition transform_partial_program (p: program A V) : res (program B V) :=\n  do fl <- map_partial prefix_name transf_partial p.(prog_funct);\n  OK (mkprogram fl p.(prog_main) p.(prog_vars)).\n\n\nLemma transform_partial_program_function:\n  forall p tp i tf,\n  transform_partial_program p = OK tp ->\n  In (i, tf) tp.(prog_funct) ->\n  exists f, In (i, f) p.(prog_funct) /\\ transf_partial f = OK tf.\nProof.\n  intros. monadInv H. simpl in H0.  \n  eapply In_map_partial; eauto.\nQed.\n\nLemma transform_partial_program_main:\n  forall p tp,\n  transform_partial_program p = OK tp ->\n  tp.(prog_main) = p.(prog_main).\nProof.\n  intros. monadInv H. reflexivity.\nQed.\n\nLemma transform_partial_program_vars:\n  forall p tp,\n  transform_partial_program p = OK tp ->\n  tp.(prog_vars) = p.(prog_vars).\nProof.\n  intros. monadInv H. reflexivity.\nQed.\n\nEnd TRANSF_PARTIAL_PROGRAM.\n\n\n(** The following is a variant of [transform_program_partial] where\n  both the program functions and the additional variable information\n  are transformed by functions that can fail. *)\n\nSection TRANSF_PARTIAL_PROGRAM2.\n\nVariable A B V W: Type.\nVariable transf_partial_function: A -> res B.\nVariable transf_partial_variable: V -> res W.\n\nDefinition transf_globvar (g: globvar V) : res (globvar W) :=\n  do info' <- transf_partial_variable g.(gvar_info);\n  OK (mkglobvar info' g.(gvar_init) g.(gvar_readonly) g.(gvar_volatile)).\n\nDefinition transform_partial_program2 (p: program A V) : res (program B W) :=\n  do fl <- map_partial prefix_name transf_partial_function p.(prog_funct);\n  do vl <- map_partial prefix_name transf_globvar p.(prog_vars);\n  OK (mkprogram fl p.(prog_main) vl).\n\n\nLemma transform_partial_program2_function:\n  forall p tp i tf,\n  transform_partial_program2 p = OK tp ->\n  In (i, tf) tp.(prog_funct) ->\n  exists f, In (i, f) p.(prog_funct) /\\ transf_partial_function f = OK tf.\nProof.\n  intros. monadInv H.\n  eapply In_map_partial; eauto. \nQed.\n\nLemma transform_partial_program2_variable:\n  forall p tp i tg,\n  transform_partial_program2 p = OK tp ->\n  In (i, tg) tp.(prog_vars) ->\n  exists v,\n     In (i, mkglobvar v tg.(gvar_init) tg.(gvar_readonly) tg.(gvar_volatile)) p.(prog_vars)\n  /\\ transf_partial_variable v = OK tg.(gvar_info).\nProof.\n  intros. monadInv H. exploit In_map_partial; eauto. intros [g [P Q]].\n  monadInv Q. simpl in *. exists (gvar_info g); split. destruct g; auto. auto.\n Qed.\n\nLemma transform_partial_program2_main:\n  forall p tp,\n  transform_partial_program2 p = OK tp ->\n  tp.(prog_main) = p.(prog_main).\nProof.\n  intros. monadInv H. reflexivity.\nQed.\n\nEnd TRANSF_PARTIAL_PROGRAM2.\n\n(** The following is a relational presentation of \n  [transform_program_partial2].  Given relations between function\n  definitions and between variable information, it defines a relation\n  between programs stating that the two programs have the same shape\n  (same global names, etc) and that identically-named function definitions \n  are variable information are related. *)\n\nSection MATCH_PROGRAM.\n\nVariable A B V W: Type.\nVariable match_fundef: A -> B -> Prop.\nVariable match_varinfo: V -> W -> Prop.\n\nInductive match_funct_entry: ident * A -> ident * B -> Prop :=\n  | match_funct_entry_intro: forall id fn1 fn2,\n      match_fundef fn1 fn2 ->\n      match_funct_entry (id, fn1) (id, fn2).\n\nInductive match_var_entry: ident * globvar V -> ident * globvar W -> Prop :=\n  | match_var_entry_intro: forall id info1 info2 init ro vo,\n      match_varinfo info1 info2 ->\n      match_var_entry (id, mkglobvar info1 init ro vo)\n                      (id, mkglobvar info2 init ro vo).\n\nDefinition match_program (p1: program A V) (p2: program B W) : Prop :=\n  list_forall2 match_funct_entry p1.(prog_funct) p2.(prog_funct)\n  /\\ p1.(prog_main) = p2.(prog_main)\n  /\\ list_forall2 match_var_entry p1.(prog_vars) p2.(prog_vars).\n\nEnd MATCH_PROGRAM.\n\nRemark transform_partial_program2_match:\n  forall (A B V W: Type)\n         (transf_partial_function: A -> res B)\n         (transf_partial_variable: V -> res W)\n         (p: program A V) (tp: program B W),\n  transform_partial_program2 transf_partial_function transf_partial_variable p = OK tp ->\n  match_program \n    (fun fd tfd => transf_partial_function fd = OK tfd)\n    (fun info tinfo => transf_partial_variable info = OK tinfo)\n    p tp.\nProof.\n  intros. monadInv H. split.\n  apply list_forall2_imply with\n    (fun (ab: ident * A) (ac: ident * B) =>\n       fst ab = fst ac /\\ transf_partial_function (snd ab) = OK (snd ac)).\n  eapply map_partial_forall2. eauto. \n  intros. destruct v1; destruct v2; simpl in *. destruct H1; subst. constructor. auto.\n  split. auto.\n  apply list_forall2_imply with\n    (fun (ab: ident * globvar V) (ac: ident * globvar W) =>\n       fst ab = fst ac /\\ transf_globvar transf_partial_variable (snd ab) = OK (snd ac)).\n  eapply map_partial_forall2. eauto. \n  intros. destruct v1; destruct v2; simpl in *. destruct H1; subst. \n  monadInv H2. destruct g; simpl in *. constructor. auto.\nQed.\n\n(** * External functions *)\n\n(** For most languages, the functions composing the program are either\n  internal functions, defined within the language, or external functions\n  (a.k.a. system calls) that emit an event when applied.  We define\n  a type for such functions and some generic transformation functions. *)\n\nRecord external_function : Type := mkextfun {\n  ef_id: ident;\n  ef_sig: signature;\n  ef_inline: bool\n}.\n\n(** Function definitions are the union of internal and external functions. *)\n\nInductive fundef (F: Type): Type :=\n  | Internal: F -> fundef F\n  | External: external_function -> fundef F.\n\nImplicit Arguments External [F].\n\nSection TRANSF_FUNDEF.\n\nVariable A B: Type.\nVariable transf: A -> B.\n\nDefinition transf_fundef (fd: fundef A): fundef B :=\n  match fd with\n  | Internal f => Internal (transf f)\n  | External ef => External ef\n  end.\n\nEnd TRANSF_FUNDEF.\n\nSection TRANSF_PARTIAL_FUNDEF.\n\nVariable A B: Type.\nVariable transf_partial: A -> res B.\n\nDefinition transf_partial_fundef (fd: fundef A): res (fundef B) :=\n  match fd with\n  | Internal f => do f' <- transf_partial f; OK (Internal f')\n  | External ef => OK (External ef)\n  end.\n\nEnd TRANSF_PARTIAL_FUNDEF.\n\n", "meta": {"author": "pilki", "repo": "s2sLoop", "sha": "821528456333c518788df2834c674e850d7e7291", "save_path": "github-repos/coq/pilki-s2sLoop", "path": "github-repos/coq/pilki-s2sLoop/s2sLoop-821528456333c518788df2834c674e850d7e7291/from_compcert/AST.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21751576258908772}}
{"text": "From aneris.aneris_lang Require Import lang resources.\nFrom stdpp Require Import gmap.\nFrom aneris.prelude Require Import misc.\nFrom aneris.examples.ccddb.spec Require Import base.\nFrom aneris.examples.ccddb.model Require Import model_update_prelude\n     model_lhst model_update_lsec.\n\nSection Lhst_udpate.\n  Context `{!anerisG Mdl Σ, !DB_params}.\n\n  Lemma lhst_add_ext i s e :\n    DBM_lhst_valid i s →\n    (∀ e', e' ∈ s → ae_time e' = ae_time e → False) →\n    DBM_lhst_ext (s ∪ {[e]}).\n  Proof.\n    intros ? ? e1 e2\n           [He1| ->%elem_of_singleton]%elem_of_union\n           [He2| ->%elem_of_singleton]%elem_of_union;\n      [by eapply DBM_LHV_ext| set_solver .. ].\n  Qed.\n\n  Lemma DBM_lhst_ext_update e i t s :\n    DBM_lhst_valid i s →\n    (∀ e, e ∈ s → vector_clock_le e.(ae_time) t) →\n    update_condition i e t →\n    DBM_lhst_ext (s ∪ {[e]}).\n  Proof.\n    intros His Ht Hcnd.\n    eapply lhst_add_ext; first done.\n    intros e1 He1 He1t.\n    specialize (Ht e1 He1). rewrite He1t in Ht.\n    assert (vector_clock_lt (ae_time e) t) as Hlt.\n    { apply vector_clock_le_eq_or_lt in Ht as [ | ]; last done.\n      subst. by eapply update_condition_absurd in Hcnd. }\n    eapply update_condition_time; eauto.\n  Qed.\n\n\n  Lemma DBM_lhst_seqids_update e i t s :\n    DBM_lhst_valid i s →\n    e.(ae_seqid) = (S (size s)) →\n    update_condition i e t →\n    DBM_lhst_seqids (s ∪ {[e]}).\n  Proof.\n    intros Hvl Hseq Hcnd.\n    pose proof Hcnd as\n        (Hi & Htlen & Hetlen & Hkey & Heorig & Het & Het' & Het'').\n    intros e' [ He' | ->%elem_of_singleton]%elem_of_union.\n    + pose proof (DBM_LHV_seqids Hvl e' He').\n      apply (Nat.le_trans _ (size s)); first done.\n      by apply subseteq_size; set_solver.\n    + rewrite size_union_alt.\n      rewrite Hseq difference_disjoint_L;\n          first by rewrite size_singleton; lia.\n      apply elem_of_disjoint; intros ? ->%elem_of_singleton He.\n        by pose proof (DBM_LHV_seqids Hvl e He); lia.\n  Qed.\n\n  Lemma DBM_lhst_origs_times_update e i t s :\n    DBM_lhst_valid i s →\n    update_condition i e t →\n    let s' := (s ∪ {[e]}) in\n    DBM_lhst_times s' ∧\n    DBM_lhst_origs i s' ∧\n    DBM_lhst_keys s'.\n  Proof.\n    simpl; intros Hvl Hcnd.\n    destruct Hcnd as (Hi & Htlen & Hetlen & Hkey & Heorig & Het & Het' & Het'').\n    repeat split; intros e' [ | ?%elem_of_singleton_1]%elem_of_union.\n    - by eapply DBM_LHV_times.\n    - set_solver.\n    - by eapply DBM_LHV_origs.\n    - set_solver.\n    - by eapply DBM_LHV_keys.\n    - set_solver.\n  Qed.\n\n  Lemma DBM_lhst_update e i t s :\n    DBM_lhst_valid i s →\n    update_condition i e t →\n    e.(ae_seqid) = (S (size s)) →\n    (∀ e : apply_event, e ∈ s → vector_clock_le (ae_time e) t) →\n    t !! ae_orig e = Some (length (elements (DBM_lsec (ae_orig e) s))) →\n    (ae_orig e = i\n     → ∀ j, j < strings.length DB_addresses\n            → t !! j = Some (length (elements (DBM_lsec j s)))) →\n     (∀ j, j < length DB_addresses →\n          default O (t !! j) <= (length (elements (DBM_lsec j s)))) →\n     DBM_lhst_valid i (s ∪ {[ e ]}).\n  Proof.\n    intros Hvl Hcnd He Ht.\n    pose proof Hcnd as (Hi & _).\n    split; try eapply (DBM_lhst_origs_times_update e i t); eauto.\n    - eapply DBM_lhst_ext_update; eauto.\n    - eapply DBM_lhst_lsec_update; eauto.\n    - eapply DBM_lhst_seqids_update; eauto.\n  Qed.\n\nEnd Lhst_udpate.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/ccddb/model/model_update_lhst.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21751576258908767}}
{"text": "From hahn Require Import Hahn.\nFrom hahn Require Import HahnOmega.\nRequire Import PropExtensionality.\nRequire Import AuxRel.\nRequire Import Lia.\nRequire Import Labels.\nRequire Import Events.\nRequire Import Execution.\nRequire Import AuxProp.\nRequire Import TraceWf.\nRequire Import SetSize.\nRequire Import IndefiniteDescription.\nRequire Import Backport.\nRequire Import List.\nImport ListNotations.\nRequire Import TerminationDecl.\nRequire Import RAop. \n\nRequire Import TSO.\nRequire Import SC.\nRequire Import RAop.\nRequire Import ModelsRelationships.\n\nNotation \"'E' G\" := (acts G) (at level 1). \nNotation \"'Loc_' l\" := (fun x => loc x = l) (at level 1).\nNotation \"'Locs_' locs\" := (fun x => In (loc x) locs) (at level 1).\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'Valr_' v\" := (fun x => valr x = v) (at level 1).\nNotation \"'Valw_' v\" := (fun x => valw x = v) (at level 1).\n\nSet Implicit Arguments. \n\nLtac unfolder' := unfold trace_finite, set_compl, cross_rel, set_minus, set_inter, set_union, is_r, is_r_l, is_w, is_w_l, is_rmw, is_rmw_l, is_init, same_loc, loc, loc_l, valr, valr_l, valw, valw_l, lab, tid in *.\n\nDefinition d_ := InitEvent 0.\n\nSection FenceTrace.\n  (** Currently fence traces are defined as empty which is enough to prove properties not related to RC11 ***)\n  \n  Definition release_fence (tr: trace Event) :=\n    tr = trace_fin [].\n  \n  Lemma release_fence_no_write (tr: trace Event) (REL: release_fence tr):\n    trace_elems tr ∩₁ is_w ⊆₁ ∅.\n  Proof. red in REL. subst tr. basic_solver. Qed. \n  \n  Lemma rel_fin tr  (REL: release_fence tr):\n    trace_finite tr.\n  Proof. red in REL. subst tr. by exists []. Qed.\n\n  Opaque release_fence. \n\n  \n  Definition acquire_fence (tr: trace Event) :=\n    tr = trace_fin [].\n  \n  Lemma acquire_fence_no_write (tr: trace Event) (ACQ: acquire_fence tr):\n    trace_elems tr ∩₁ is_w ⊆₁ ∅.\n  Proof. red in ACQ. subst tr. basic_solver. Qed. \n  \n  Lemma acq_fin tr (ACQ: acquire_fence tr):\n    trace_finite tr.\n  Proof. red in ACQ. subst tr. by exists []. Qed.\n\n  Opaque acquire_fence. \n\n\n  Lemma rel_not_inf_length tr (REL: release_fence tr):\n    trace_length tr <> NOinfinity.\n  Proof. edestruct rel_fin, tr; vauto. Qed.\n  \n  Lemma acq_not_inf_length tr (ACQ: acquire_fence tr):\n    trace_length tr <> NOinfinity.\n  Proof. edestruct acq_fin, tr; vauto. Qed.\n\nEnd FenceTrace. \n\nSection HMCS.\n\n  Definition hmcs_acquire_end lock (statuses nexts: list Loc) (thread: Tid) tr :=\n    (* exists pred index0 index1 , *)\n    exists index pred tr_acq_end,\n      let swap := trace_fin [ThreadEvent thread index (Armw lock pred thread)] in\n      tr = trace_app swap tr_acq_end /\\\n      (if (NPeano.Nat.eq_dec pred 0)\n       then\n         (exists index0,\n             let w := ThreadEvent thread index0 (Astore (nth thread statuses 0) 0) in\n             tr_acq_end = trace_fin [w])\n       else\n         (exists index0 tr_acq_wait,\n             let w_pred := ThreadEvent thread index0 (Astore (nth pred nexts 0) thread) in\n             tr_acq_end = trace_app (trace_fin [w_pred]) tr_acq_wait /\\\n             busywait (nth thread statuses 0) tr_acq_wait (eq 0))\n      ).\n\n  \n\n  Definition hmcs_acquire_real lock (statuses nexts: list Loc) thread tr :=\n    exists index tr_acq_end tr_relf,\n      let writes := trace_fin\n          [ThreadEvent thread index (Astore (nth thread statuses 0) 1);\n           ThreadEvent thread (index + 1) (Astore (nth thread nexts 0) 0)] in\n      tr = trace_app (trace_app writes tr_relf) tr_acq_end /\\\n      release_fence tr_relf /\\\n      hmcs_acquire_end lock statuses nexts thread tr_acq_end. \n             \n  \n  Definition hmcs_acquire lock statuses nexts thread tr :=\n    exists tr_acqr tr_acqf,\n      tr = trace_app tr_acqr tr_acqf /\\\n      hmcs_acquire_real lock statuses nexts thread tr_acqr /\\\n      acquire_fence tr_acqf.\n\n  Definition trace_last {A: Type} (tr: trace A) (d: A) :=\n    match tr with\n    | trace_fin l => last l d\n    | trace_inf _ => d\n    end. \n\n  Definition hmcs_lock_pass (statuses: list Loc) tr succ :=\n    exists thread index,\n      let w := Astore (nth succ statuses 0) 0 in\n      tr = trace_fin [ThreadEvent thread index w].\n\n  Definition no_succ_release lock thread tr :=\n    exists index, let rmw := ThreadEvent thread index (Armw lock thread 0) in\n             tr = trace_fin [rmw]. \n  \n  Definition succ_wait_release lock (nexts: list Loc) thread tr :=\n    exists index other tr_succ_wait,\n      let r_late := ThreadEvent thread index (Aload lock other) in\n      tr = trace_app (trace_fin [r_late]) tr_succ_wait /\\\n      other <> thread /\\\n      busywait (nth thread nexts 0) tr_succ_wait (set_compl (eq 0)).\n  \n  Definition hmcs_release_real lock (statuses nexts: list Loc) thread tr :=\n    exists index succ tr_acqf tr_rel_end,\n      let r_succ := ThreadEvent thread index (Aload (nth thread nexts 0) succ) in\n      tr = trace_app (trace_app (trace_fin [r_succ]) tr_acqf) tr_rel_end /\\\n      acquire_fence tr_acqf /\\\n      if (NPeano.Nat.eq_dec succ 0)\n      then (no_succ_release lock thread tr_rel_end \\/\n            (exists tr_wait tr_pass,\n                tr_rel_end = trace_app tr_wait tr_pass /\\\n                succ_wait_release lock nexts thread tr_wait /\\\n                hmcs_lock_pass statuses tr_pass (valr (trace_last tr_wait d_))))\n      else hmcs_lock_pass statuses tr_rel_end succ.\n           \n  Definition hmcs_release lock statuses nexts thread tr :=\n    exists tr_relf tr_relr,\n      tr = trace_app tr_relf tr_relr /\\\n      release_fence tr_relf /\\\n      hmcs_release_real lock statuses nexts thread tr_relr. \n\n  (* HMCS lock's lock and unlock calls with 'Lock' at lock.\n     QNode.locked and QNode.next are represented by \n     'statuses' and 'nexts' arrays. *)\n  Definition hmcs_acqiure_release (lock: Loc) (statuses nexts: list Loc)\n             (thread: Tid) (tr: trace Event) :=\n    exists tr_acq tr_rel,\n      ⟪APP: tr = trace_app tr_acq tr_rel ⟫ /\\\n      ⟪ACQ: hmcs_acquire lock statuses nexts thread tr_acq ⟫ /\\\n      ⟪REL: hmcs_release lock statuses nexts thread tr_rel ⟫.\n\nEnd HMCS.\n\nSection HMCSClient.\n  Variable n_threads: nat.\n    \n  Definition hmcs_thread lock statuses nexts G tr thread :=\n    let (Gt, _) := restrict G thread in\n    ⟪HMCS: hmcs_acqiure_release lock statuses nexts thread tr ⟫ /\\\n    ⟪TR_E: trace_elems tr ≡₁ E Gt ⟫ /\\\n    ⟪TR_WF: trace_wf tr ⟫.\n  \n  Definition hmcs_client lock statuses nexts G :=\n    forall thread (NINIT: thread <> 0) (CNT: thread < n_threads),\n    exists tr, hmcs_thread lock statuses nexts G tr thread.\n\nEnd HMCSClient.\n\n\nSection HMCSClientTermination.\n  Variable n_threads: nat. \n  Variables (lock: Loc) (statuses nexts: list Loc). \n  Hypothesis DISJ_LOC: NoDup (lock :: statuses ++ nexts).\n  Hypothesis (STATUSES_LEN: ⟪STATUSES_LEN: length statuses = n_threads⟫)\n             (NEXTS_LEN: ⟪NEXTS_LEN: length nexts = n_threads⟫).\n  Hypothesis LOCS_NO0: ~ In 0 (lock :: statuses ++ nexts). \n\n  Variable G: execution. \n  Hypothesis HMCS_CLIENT: hmcs_client n_threads lock statuses nexts G. \n  Hypothesis FAIR: mem_fair G.\n  Hypothesis SCpL: SCpL G.\n  Hypothesis WF: Wf G.\n  Hypothesis RFC: rf_complete G.\n  Hypothesis BOUNDED_THREADS: (fun thread => exists e, (E G ∩₁ Tid_ thread) e)\n                                ≡₁ (fun thread => thread < n_threads).\n\n  Hypothesis MODEL: ⟪MODEL: sc_consistent G \\/ TSO_consistent G \\/ ra_consistent G⟫.\n\n  Lemma ra_no_cycle (RA: ra_consistent G):\n    ~ exists e, (sb G ⨾ co G ⨾ sb G ⨾ ((restr_rel is_rmw (rf G))^* ⨾ rf G)) e e.\n  Proof.\n    intros CYCLE. desc. destruct CYCLE as [w1 [SB1 [w2 [CO HB]]]]. \n    red in RA. desc. destruct (RA w2).\n    exists w1. split; [| basic_solver].\n    red. apply ct_unit. exists e. split; [| basic_solver].\n    eapply hahn_inclusion_exp in HB.\n    2: { rewrite inclusion_restr, <- ct_end. apply inclusion_refl. }\n    apply ct_begin. destruct HB. desc. exists x. split; [basic_solver 10| ].\n    eapply clos_refl_trans_mori; [apply inclusion_union_r2| by apply inclusion_t_rt].\n  Qed.\n\n  Lemma no_cycle: ~ exists e, (sb G ⨾ co G ⨾ sb G ⨾ ((restr_rel is_rmw (rf G))^* ⨾ rf G)) e e.\n  Proof.\n    enough (ra_consistent G) as RA; [by apply ra_no_cycle| ].\n    cdes MODEL.\n    des; [eapply sc_implies_tso, tso_implies_ra in MODEL0 | apply tso_implies_ra in MODEL0|]; auto. \n  Qed. \n    \n  Lemma tid0_init: E G ∩₁ Tid_ 0 ≡₁ E G ∩₁ is_init.\n  Proof.\n    enough (forall e (Ee: E G e), Tid_ 0 e <-> is_init e) as EQUIV.\n    { unfolder. split; ins; desc; split; try apply EQUIV; auto. } \n    ins. eapply wf_tid_init; eauto.\n  Qed.\n\n  Ltac by_subst := by (subst; unfolder'; simpl in *; (lia || des; (vauto || lia))).\n  Ltac by_destruct x := by (destruct x as [| t_ ind_ l_]; [| destruct l_]; by_subst). \n  \n  Definition lock_order: relation Tid :=\n    fun t1 t2 => exists w1 w2,\n        (E G ∩₁ Tid_ t1 ∩₁ is_rmw ∩₁ Loc_ lock ∩₁ Valw_ t1) w1 /\\\n        (E G ∩₁ Tid_ t2 ∩₁ is_rmw ∩₁ Loc_ lock ∩₁ Valw_ t2) w2 /\\\n        co G w1 w2.\n\n  Lemma NoDup_disj_elems {A: Type} (l1 l2: list A) (NODUP: NoDup (l1 ++ l2)):\n    (fun a => In a l1) ∩₁ (fun a => In a l2) ⊆₁ ∅.\n  Proof.\n    remember (l1 ++ l2) as l. generalize dependent l1. generalize dependent l2.\n    induction l.\n    { ins. destruct l1, l2; basic_solver. }\n    ins. destruct l1; [basic_solver| ].\n    simpl in *. inversion Heql. subst. clear Heql.\n    inversion NODUP. subst.\n    specialize (IHl H2 _ _ eq_refl).\n    arewrite ((fun a => a0 = a \\/ In a l1) ≡₁ eq a0 ∪₁ (fun a => In a l1)) by basic_solver.\n    rewrite set_inter_union_l. apply set_subset_union_l. split; auto.\n    red. ins. apply H1. apply in_app_r. by_subst.\n  Qed.            \n    \n  Ltac trace_app_elems_exh :=\n    match goal with\n    | H: trace_elems (trace_app ?t1 ?t2) ?e |- _ =>\n      apply trace_in_app in H; destruct H as [H | H]; desc; trace_app_elems_exh\n    | H: trace_elems (trace_fin ?l) ?e |- _ =>\n      simpl in H; des; try done\n    | _ => auto\n    end. \n\n  Ltac unfold_acquire := unfold hmcs_acquire, hmcs_acquire_real, hmcs_acquire_end in *.\n  Ltac unfold_release := unfold hmcs_release, hmcs_release_real, no_succ_release, succ_wait_release, hmcs_lock_pass in *.\n\n  Lemma disj_locs thread (BOUND: thread < n_threads):\n    nth thread statuses 0 <> lock /\\ nth thread nexts 0 <> lock /\\\n    nth thread statuses 0 <> nth thread nexts 0. \n  Proof.\n    remember (lock :: statuses ++ nexts) as locs.\n    replace lock with (nth 0 locs 0) by by_subst.\n    replace (nth thread statuses 0) with (nth (thread + 1) locs 0).\n    2: { subst locs. rewrite PeanoNat.Nat.add_1_r. simpl.\n         apply app_nth1. congruence. }\n    replace (nth thread nexts 0) with (nth (thread + 1 + n_threads) locs 0).\n    2: { subst locs. rewrite PeanoNat.Nat.add_1_r. simpl.\n         rewrite <- STATUSES_LEN, NPeano.Nat.add_comm. apply app_nth2_plus. }\n    splits; red; intros EQ; apply NoDup_nth in EQ; try by_subst; subst locs; simpl; rewrite app_length, STATUSES_LEN, NEXTS_LEN; lia. \n  Qed.     \n\n  Lemma nexts0_iff_overflow thread:\n    nth thread nexts 0 = 0 <-> n_threads <= thread. \n  Proof.\n    split.\n    2: { ins. rewrite nth_overflow; congruence. }\n    intros EQ0.\n    destruct (PeanoNat.Nat.lt_ge_cases thread n_threads); auto.\n    forward eapply (@nth_In _ thread nexts 0) as IN; [congruence| ].\n    rewrite EQ0 in IN. destruct LOCS_NO0.\n    simpl. right. apply in_app_iff. tauto.  \n  Qed. \n\n  Lemma statuses0_iff_overflow thread:\n    nth thread statuses 0 = 0 <-> n_threads <= thread. \n  Proof.\n    split.\n    2: { ins. rewrite nth_overflow; congruence. }\n    intros EQ0.\n    destruct (PeanoNat.Nat.lt_ge_cases thread n_threads); auto.\n    forward eapply (@nth_In _ thread statuses 0) as IN; [congruence| ].\n    rewrite EQ0 in IN. destruct LOCS_NO0.\n    simpl. right. apply in_app_iff. tauto.  \n  Qed. \n\n  Lemma lock_writes:\n    E G ∩₁ is_w ∩₁ Loc_ lock \\₁ is_init ⊆₁ is_rmw ∩₁ (fun e => valw e = tid e \\/ valw e = 0 /\\ valr e = tid e).\n  Proof.\n    red. intros rmw RMW.\n    remember (tid rmw) as thread. assert (⟪TID: Tid_ thread rmw⟫) by by_subst. clear Heqthread. \n    cdes HMCS_CLIENT. specialize (HMCS_CLIENT0 thread). specialize_full HMCS_CLIENT0.\n    { red. ins. subst thread. eapply wf_tid_init in H; by_subst. }\n    { apply BOUNDED_THREADS. by_subst. }\n    desc. red in HMCS_CLIENT0. destruct (restrict G thread) as [Gt [TRE]]. desc.\n    assert (trace_elems tr rmw) as TRrmw.\n    { apply TR_E, TRE. by_subst. }\n    forward eapply (@disj_locs thread) as LOC; [apply BOUNDED_THREADS; by_subst|].\n    red in HMCS. desc. unfold_acquire. unfold_release. desc. subst.\n    trace_app_elems_exh; try by_subst. \n    { edestruct (@release_fence_no_write tr_relf0); by_subst. }\n    { destruct (NPeano.Nat.eq_dec pred 0); desc; subst.\n      { simpl in TRrmw0; des; by_subst. }\n      { trace_app_elems_exh.\n        { destruct (PeanoNat.Nat.lt_ge_cases pred n_threads).\n          { forward eapply (@disj_locs pred) as LOC'; auto. \n            desc. destruct LOC'0. by_subst. }\n          { apply nexts0_iff_overflow in H0.\n            by_subst. }\n        }\n        eapply wait_trace_reads in TRrmw2; eauto. by_subst. }\n    }\n    { edestruct (@acquire_fence_no_write tr_acqf); by_subst. }\n    { edestruct (@release_fence_no_write tr_relf); by_subst. }\n    { edestruct (@acquire_fence_no_write tr_acqf0); by_subst. }\n    { destruct (NPeano.Nat.eq_dec succ 0).\n      { des.\n        { subst. trace_app_elems_exh. by_subst. } \n        { subst tr_rel_end tr_wait. trace_app_elems_exh; try by_subst. \n          { eapply wait_trace_reads in TRrmw3; try by_subst. }\n          subst tr_pass.\n          remember (valr (trace_last (trace_app (trace_fin [ThreadEvent thread index3 (Aload lock other)]) tr_succ_wait) d_)) as addr.\n          simpl in TRrmw3. des; [| done].\n          destruct (PeanoNat.Nat.lt_ge_cases addr n_threads).\n          { forward eapply (@disj_locs addr); auto. ins. desc. by_subst. }\n          { apply statuses0_iff_overflow in H0.\n            rewrite H0 in TRrmw3. by_subst. }\n        }\n      }            \n      desc. subst. trace_app_elems_exh; try by_subst. \n      forward eapply (@disj_locs succ) as LOC'.\n      { destruct (PeanoNat.Nat.lt_ge_cases succ n_threads); auto.\n        apply statuses0_iff_overflow in H0. by_subst. }\n      by_subst. }\n  Qed.\n\n  Lemma trace_app_not_inf {A: Type} (tr1 tr2: trace A):\n    trace_length (trace_app tr1 tr2) <> NOinfinity <->\n    (trace_length tr1 <> NOinfinity /\\ trace_length tr2 <> NOinfinity).\n  Proof using.\n    clear dependent n_threads. clear dependent lock.\n    destruct tr1, tr2; try by_subst; tauto. \n  Qed.\n\n  Ltac trace_length_not_inf :=\n    match goal with\n    | |- trace_length (trace_app ?t1 ?t2) <> NOinfinity =>\n      apply trace_app_not_inf; split; trace_length_not_inf\n    | H: trace_finite ?t |- trace_length ?t <> NOinfinity =>\n      destruct t; by_subst\n    | |- trace_length ?t <> NOinfinity =>\n        by ((by apply rel_not_inf_length) || (by apply acq_not_inf_length) || by_subst)\n    | |- _ => auto\n    end. \n  \n  Ltac fin_trace_solver :=\n    match goal with\n    | |- trace_finite (trace_app ?t1 ?t2) => apply trace_app_finite; split; fin_trace_solver\n    | |- trace_length ?t <> NOinfinity => trace_length_not_inf\n    | |- _ => by_subst || by auto using rel_fin, acq_fin\n    end. \n  \n  Ltac trace_elems_solver :=\n    match goal with\n    | |- trace_elems (trace_app ?t1 ?t2) ?e => apply trace_in_app; ((left; trace_elems_solver) || (right; split; [trace_length_not_inf| ]; trace_elems_solver))\n    | |- _ => by_subst\n    end.\n\n  Lemma lock_write_unique thread (NINIT: thread <> 0) (CNT: thread < n_threads):\n    exists! rmw, (E G ∩₁ is_rmw ∩₁ Loc_ lock ∩₁ Valw_ thread) rmw.\n  Proof.\n    cdes HMCS_CLIENT. specialize_full HMCS_CLIENT0; eauto. desc.\n    red in HMCS_CLIENT0. destruct (restrict G thread) as [Gt [TRE]]. desc.\n    red in HMCS. desc. red in ACQ. desc. red in ACQ0. desc. red in ACQ3. desc.\n    remember (ThreadEvent thread index0 (Armw lock pred thread)) as rmw. exists rmw.\n\n    red. split.\n    { assert (trace_elems tr rmw) as TRrmw.\n      { subst tr tr_acq tr_acqr tr_acq_end.\n        do 2 (apply trace_in_app; left). apply trace_in_app.\n        right. split; [fin_trace_solver| ]. \n        apply trace_in_app. left. by_subst. } \n      apply TR_E, TRE in TRrmw. by_subst. }\n    { intros rmw' RMW'.\n      forward eapply (@lock_writes rmw') as RMW'_; [by_destruct rmw'| ].\n      assert (trace_elems tr rmw') as TRrmw'.\n      { apply TR_E, TRE. by_subst. }\n      subst tr. apply trace_in_app in TRrmw'. des.\n      { subst tr_acq. apply trace_in_app in TRrmw'. des.\n        2: { edestruct acquire_fence_no_write; eauto. by_destruct rmw'. }\n        subst tr_acqr. apply trace_in_app in TRrmw'. des.\n        { apply trace_in_app in TRrmw'. des.\n          { simpl in TRrmw'. des; by_subst. }\n          { edestruct (@release_fence_no_write tr_relf); auto. by_destruct rmw'. }\n        }\n        subst tr_acq_end. apply trace_in_app in TRrmw'0. des; [by_subst| ].\n        destruct (NPeano.Nat.eq_dec pred 0); desc; subst tr_acq_end0. \n        { simpl in TRrmw'1. des; by_subst. }\n        { apply trace_in_app in TRrmw'1. des; [simpl in TRrmw'1; des; by_subst| ].\n          eapply wait_trace_reads in TRrmw'2; eauto.\n          forward eapply (NoDup_disj_elems [lock] statuses) as DISJ.\n          { simpl. eapply nodup_append_left.\n            erewrite <- app_comm_cons; eauto. }\n          destruct (DISJ lock). split; [by_subst| ].\n          replace lock with (nth thread statuses 0); [| by_subst]. \n          apply nth_In. rewrite STATUSES_LEN. by_subst. }\n      }\n      red in REL. desc. subst tr_rel. apply trace_in_app in TRrmw'0. des.      \n      { edestruct (@release_fence_no_write tr_relf0); eauto. by_destruct rmw'. }\n      red in REL1. desc. subst tr_relr. apply trace_in_app in TRrmw'1. des.\n      { apply trace_in_app in TRrmw'1. des; [simpl in *; des; by_subst| ].\n        edestruct acquire_fence_no_write; eauto. by_destruct rmw'. }\n      destruct (NPeano.Nat.eq_dec succ 0).\n      { des. \n        { red in REL3. desc. subst tr_rel_end.        \n          red in TRrmw'2. simpl in TRrmw'2. des; by_subst. }\n        subst tr_rel_end.\n        apply trace_in_app in TRrmw'2.\n        des; [| red in REL4; desc; by_subst].\n        red in REL1. desc. subst tr_wait.\n        apply trace_in_app in TRrmw'2. des; [simpl in *; des; by_subst| ].\n        eapply wait_trace_reads in REL5; eauto.\n        forward eapply NoDup_disj_elems as DISJ. \n        { erewrite <- app_comm_cons; eauto. }\n        destruct (DISJ lock). split; [by_subst| ].\n        replace lock with (nth thread nexts 0).\n        2: { specialize (REL5 _ TRrmw'3). by_subst. } \n        apply nth_In. rewrite NEXTS_LEN. by_subst. \n      }\n      red in REL3. desc. subst tr_rel_end. simpl in *. des; by_subst. }\n  Qed.\n\n\n  Lemma unique_eq {A: Type} (S: A -> Prop) x y\n        (UNIQUIE: exists! z, S z)\n        (Sx: S x) (Sy: S y):\n    x = y.\n  Proof. destruct UNIQUIE. transitivity x0; [symmetry| ]; apply H; auto. Qed.\n\n  Lemma unique_rmw_helper thread (NINIT: thread <> 0):\n    (E G ∩₁ Tid_ thread ∩₁ is_rmw ∩₁ Loc_ lock ∩₁ Valw_ thread) ≡₁\n    (E G ∩₁ is_rmw ∩₁ Loc_ lock ∩₁ Valw_ thread).\n  Proof.\n    split; [basic_solver| ].\n    red. ins.\n    forward eapply (@lock_writes x) as L; [by_destruct x| ]. \n    destruct L. des; by_subst.\n  Qed.\n\n  Lemma rmws_atomicity_violation_helper w rmw1 rmw2\n        (RF1: rf G w rmw1) (RF2: rf G w rmw2)\n        (RMW1: is_rmw rmw1) (RMW2: is_rmw rmw2)\n        (CO: co G rmw1 rmw2):\n    False.\n  Proof.\n    forward eapply rmw_atom as ATOM_G; eauto. \n    forward eapply (@ATOM_G w rmw2) as ATOM.\n    { destruct rmw2; [| destruct l]; by_subst. }\n    red in ATOM. desc. apply ATOM0.\n    exists rmw1. split; eauto.\n    apply rf_co_helper; eauto. destruct rmw1; [| destruct l]; by_subst. \n  Qed.\n\n  Lemma rmws_atomicity_violation w rmw1 rmw2\n        (RF1: rf G w rmw1) (RF2: rf G w rmw2)\n        (RMW1: is_rmw rmw1) (RMW2: is_rmw rmw2):\n    rmw1 = rmw2.\n  Proof.\n    contra NEQ. \n    forward eapply (@wf_co_total _ WF (loc w)) with (a := rmw1) (b := rmw2)\n      as CO; auto.\n    { apply exploit_rf in RF1; auto. destruct rmw1; [| destruct l]; by_subst. }\n    { apply exploit_rf in RF2; auto. destruct rmw2; [| destruct l]; by_subst. }\n    des.\n      all: eapply rmws_atomicity_violation_helper; [.. | apply CO]; eauto.\n  Qed.\n  \n  Lemma lock_write_unique_reads rmw1 rmw2\n        (RMW1: (E G ∩₁ is_rmw ∩₁ Loc_ lock) rmw1)\n        (RMW2: (E G ∩₁ is_rmw ∩₁ Loc_ lock) rmw2)\n        (VALR_EQ: valr rmw1 = valr rmw2)\n        (VALR_N0: valr rmw1 <> 0):\n    rmw1 = rmw2.\n  Proof.\n    forward eapply (@RFC rmw1) as [rmw' RF1]; [by_destruct rmw1 |].\n    forward eapply (@RFC rmw2) as [rmw'' RF2]; [by_destruct rmw2 |].\n    apply exploit_rf in RF1; auto. apply exploit_rf in RF2; auto.\n    destruct (classic (is_init rmw')); [by_destruct rmw'| ].\n    destruct (classic (is_init rmw'')); [by_destruct rmw''| ].\n    forward eapply (@lock_writes rmw') as RMW'; [by_subst| ].\n    forward eapply (@lock_writes rmw'') as RMW''; [by_destruct rmw''| ].\n    \n    assert (rmw'' = rmw'); [| subst rmw''].\n    { eapply unique_eq.\n      { apply (@lock_write_unique (valr rmw1)); auto.\n        destruct RMW'. des; [| lia].\n        rewrite <- RF13, H2. apply BOUNDED_THREADS. exists rmw'. by_subst. }\n      { by_destruct rmw''. }\n      { by_subst. }\n    }\n    eapply rmws_atomicity_violation; by_subst.  \n  Qed.\n  \n  Lemma lock_order_dom:\n    lock_order ⊆ ⦗gt n_threads \\₁ eq 0⦘ ⨾ lock_order ⨾ ⦗gt n_threads \\₁ eq 0⦘. \n  Proof.\n    red. ins.\n    assert (forall rmw, (E G ∩₁ is_rmw) rmw -> (gt n_threads \\₁ eq 0) (tid rmw))\n           as TID_HELPER.\n    { ins. split.\n      { eapply BOUNDED_THREADS. by_subst. }\n      intros T0. symmetry in T0. \n      eapply wf_tid_init in T0; eauto; [| by_subst].\n      eapply init_w in T0; by_subst. }\n    cdes H.     \n    forward eapply (TID_HELPER w1); [by_subst| ].\n    forward eapply (TID_HELPER w2); [by_subst| ].\n    replace (tid w1) with x by by_subst. replace (tid w2) with y by by_subst.\n    basic_solver 10.\n  Qed.\n\n  Lemma unique_equiv {A: Type} (S1 S2: A -> Prop) (EQUIV: S1 ≡₁ S2)\n        (UNIQUE: exists! x, S1 x):\n    exists! x, S2 x.\n  Proof.\n    destruct UNIQUE. exists x. destruct H. split; [by apply EQUIV| ].\n    ins. apply H0. by apply EQUIV.\n  Qed.\n    \n  Lemma lock_order_spo: strict_partial_order lock_order.\n  Proof.    \n    red. split.\n    { red. intros thread ORD.      \n      cdes ORD. cut (w1 = w2).\n      { intros. subst. eapply co_irr; eauto. }\n      eapply unique_eq; eauto.\n      apply lock_order_dom, seq_eqv_lr in ORD. desc. \n      eapply unique_equiv; [symmetry; apply unique_rmw_helper| ].\n      { by_subst. }\n      apply lock_write_unique; by_subst. }\n    { red. ins. cdes H. cdes H0. \n      cut (w2 = w0).\n      { ins. subst. exists w1. exists w3. splits; auto.\n        eapply co_trans; eauto. }\n      eapply unique_eq. \n      { apply lock_order_dom, seq_eqv_lr in H. desc. \n        apply (@lock_write_unique (tid w2)); by_subst. }\n      all: by_subst. }\n  Qed. \n          \n  Lemma lock_order_wf: well_founded lock_order.\n  Proof.\n    apply wf_finite with (l := seq 0 n_threads). \n    { destruct lock_order_spo. apply trans_irr_acyclic; auto. }\n    red. ins.\n    apply in_seq0_iff. eapply BOUNDED_THREADS.          \n    red in REL. desc. exists w1. by_subst. \n  Qed.\n\n  Lemma no_excessive_events thread\n        (OVER: thread >= n_threads):\n    E G ∩₁ Tid_ thread ≡₁ ∅.\n  Proof.\n    split; [| basic_solver].\n    red. ins. \n    destruct BOUNDED_THREADS. specialize (H0 thread).\n    specialize_full H0; by_subst.\n  Qed.\n\n  Lemma events_separation_inter (M: Event -> Prop)\n        (THREAD_FIN: forall thread (BOUND: thread < n_threads),\n            set_finite (E G ∩₁ Tid_ thread ∩₁ M)):\n    set_finite (E G ∩₁ M).\n  Proof.\n    rewrite events_separation, <- set_bunion_inter_compat_r.\n    arewrite ((fun _ : nat => True) ≡₁ (fun i => i < n_threads) ∪₁ (fun i => i >= n_threads)).\n    { unfolder. split; lia. }\n    rewrite set_bunion_union_l. apply set_finite_union. split.\n    2: { rewrite set_subset_bunion_l with (sb := ∅); [exists []; auto| ].\n         intros thread BOUND. \n         destruct (restrict G thread) as [Gt [TRE]]. simpl. \n         rewrite TRE, no_excessive_events; basic_solver. }\n    apply set_finite_bunion; [by apply set_finite_lt| ].\n    intros thread BOUND.\n    destruct (restrict G thread) as [Gt [TRE]]. simpl.\n    rewrite TRE. by apply THREAD_FIN.\n  Qed.\n  \n\n  Ltac fin_subtrace_filtered :=\n    match goal with\n    | |- set_finite (trace_elems (trace_app ?t1 ?t2) ∩₁ ?M) =>\n      rewrite trace_elems_app, set_inter_union_l; apply set_finite_unionI;\n      [| destruct (excluded_middle_informative _)]; fin_subtrace_filtered\n    | |- set_finite (trace_elems (trace_fin ?l) ∩₁ ?M) =>\n      exists l; ins; by_subst\n    | |- set_finite (trace_elems ?t ∩₁ ?M) =>\n      try ((by exists []; ins; by_subst) ||\n           (edestruct (@rel_fin t) as [?l L]; eauto; rewrite L; eexists; ins; by_subst) ||\n           (edestruct (@acq_fin t) as [?l L]; eauto; rewrite L; eexists; ins; by_subst)\n          )\n    | _ => try (by exists []; ins; by_subst)\n    end.\n\n  Lemma fin_ninit_writes:\n    set_finite (E G ∩₁ is_w \\₁ is_init).\n  Proof.\n    rewrite set_minusE, set_interA. apply events_separation_inter.    \n    ins.\n    destruct (PeanoNat.Nat.eq_0_gt_0_cases thread).\n    { subst thread. rewrite tid0_init. exists []. basic_solver. }\n    cdes HMCS_CLIENT. specialize (HMCS_CLIENT0 thread).\n    specialize_full HMCS_CLIENT0; try by_subst. desc.\n    red in HMCS_CLIENT0. destruct (restrict G thread) as [Gt [TRE]]. desc.\n    rewrite <- TRE, <- TR_E.\n    eapply set_finite_mori.\n    { red. rewrite <- set_interA. red. ins. eapply proj1. eauto. }\n    red in HMCS. desc.\n    rewrite APP, trace_elems_app, set_inter_union_l. apply set_finite_unionI.\n    { unfold_acquire. desc. subst.\n      fin_subtrace_filtered.\n      destruct (NPeano.Nat.eq_dec pred 0); desc; subst; fin_subtrace_filtered.\n      erewrite wait_trace_reads; eauto. fin_subtrace_filtered. }\n    { destruct (excluded_middle_informative _); [| exists []; ins; by_subst].\n      unfold_release.\n      desc. destruct (NPeano.Nat.eq_dec succ 0); des; desc; subst; fin_subtrace_filtered.\n      erewrite wait_trace_reads; eauto. fin_subtrace_filtered. }\n  Qed.\n\n  Lemma fin_l_writes l:\n    set_finite (E G ∩₁ is_w ∩₁ Loc_ l). \n  Proof.\n    rewrite set_union_minus_alt with (s' := is_init).\n    apply set_finite_union. split.\n    { pose proof (wf_initE WF). exists [InitEvent l]. ins. destruct x; by_subst. }\n    eapply set_finite_mori; [| apply fin_ninit_writes]. red. basic_solver.\n  Qed.\n  \n  Lemma wait_latest_read_helper l tr cond\n        (WAIT: busywait l tr cond)\n        (INF: ~ trace_finite tr)\n        (IN_G: trace_elems tr ⊆₁ E G)\n        (TWF: trace_wf tr):\n    exists i, forall j w,\n        i <= j -> rf G w (trace_nth j tr w) -> mo_max G w. \n  Proof.\n    eapply inf_reads_latest_full with (locs := [l]); eauto.\n    { intros FIN. apply INF.\n      apply nodup_trace_elems; [by apply trace_wf_nodup| ].\n      eapply set_finite_more; [| apply FIN].\n      symmetry. rewrite set_interC. eapply set_inter_absorb_l.\n      rewrite wait_trace_reads; eauto. basic_solver. }\n    { exists n_threads. ins. apply BOUNDED_THREADS. by_subst. }\n    { rewrite wait_trace_reads; basic_solver. }\n    { by apply trace_wf_nodup. }\n    { eapply set_finite_mori; [| apply (fin_l_writes l)]. red. basic_solver. }\n  Qed.\n\n  Lemma mo_max_co w w' (MAXw: mo_max G w) (W': (E G ∩₁ is_w ∩₁ Loc_ (loc w)) w'):\n    (co G)^? w' w.\n  Proof.\n    destruct (classic (w' = w)) as [| NEQ]; [basic_solver| right]. \n    forward eapply wf_co_total with (a := w) (b := w') as CO; eauto.\n    { red in MAXw. by_subst. }\n    des; [| done].\n    red in MAXw. desc. destruct (MAXw0 w'). by_subst. \n  Qed.\n\n  Lemma disj_statuses_nexts thread1 thread2:\n    nth thread1 statuses 0 = nth thread2 nexts 0 ->\n    n_threads <= thread1 /\\ n_threads <= thread2.\n  Proof.\n    intros EQ. \n    destruct (PeanoNat.Nat.lt_ge_cases thread1 n_threads),\n    (PeanoNat.Nat.lt_ge_cases thread2 n_threads); auto. \n    { rewrite app_comm_cons in DISJ_LOC. apply nodup_app in DISJ_LOC. cdes DISJ_LOC.\n      destruct (DISJ_LOC2 (nth thread1 statuses 0)).\n      { right. apply nth_In. congruence. }\n      { rewrite EQ. apply nth_In. congruence. }\n    }\n    { apply nexts0_iff_overflow in H0. rewrite H0 in EQ.\n      apply statuses0_iff_overflow in EQ. lia. }\n    { apply statuses0_iff_overflow in H. rewrite H in EQ.\n      symmetry in EQ. apply nexts0_iff_overflow in EQ. lia. }\n  Qed. \n  \n  Lemma unique_nexts thread1 thread2        \n        (EQ: nth thread1 nexts 0 = nth thread2 nexts 0):\n    thread1 = thread2 \\/ n_threads <= thread1 /\\ n_threads <= thread2. \n  Proof.\n    rewrite app_comm_cons in DISJ_LOC. apply nodup_app in DISJ_LOC.\n    cdes DISJ_LOC.\n    destruct (PeanoNat.Nat.lt_ge_cases thread1 n_threads),\n    (PeanoNat.Nat.lt_ge_cases thread2 n_threads); auto.\n    { left. eapply NoDup_nth; eauto; congruence. }\n    { apply nexts0_iff_overflow in H0. rewrite H0 in EQ.\n      apply nexts0_iff_overflow in EQ. lia. }\n    { apply nexts0_iff_overflow in H. rewrite H in EQ.\n      symmetry in EQ. apply nexts0_iff_overflow in EQ. lia. }\n  Qed. \n\n  Lemma unique_statuses thread1 thread2\n        (EQ: nth thread1 statuses 0 = nth thread2 statuses 0):\n    thread1 = thread2 \\/ n_threads <= thread1 /\\ n_threads <= thread2. \n  Proof.\n    rewrite app_comm_cons in DISJ_LOC. apply nodup_app in DISJ_LOC.\n    cdes DISJ_LOC.\n    destruct (PeanoNat.Nat.lt_ge_cases thread1 n_threads),\n    (PeanoNat.Nat.lt_ge_cases thread2 n_threads); auto.\n    { inversion DISJ_LOC0. subst. \n      left. eapply NoDup_nth; eauto; congruence. }\n    { apply statuses0_iff_overflow in H0. rewrite H0 in EQ.\n      apply statuses0_iff_overflow in EQ. lia. }\n    { apply statuses0_iff_overflow in H. rewrite H in EQ.\n      symmetry in EQ. apply statuses0_iff_overflow in EQ. lia. }\n  Qed. \n\n  Lemma release_no_next_writes tr pred thread\n        (RELEASE: hmcs_release lock statuses nexts thread tr)\n        (NINIT: pred <> 0) (BOUND: pred < n_threads):\n    trace_elems tr ∩₁ is_w ∩₁ Loc_ (nth pred nexts 0) ⊆₁ ∅.\n  Proof.\n    desc. red. intros w W.\n    unfolder in W. desc. \n    unfold_release. desc. subst. trace_app_elems_exh.\n    { edestruct (@release_fence_no_write tr_relf); by_subst. }\n    { by_subst. }\n    { edestruct (@acquire_fence_no_write tr_acqf); by_subst. }\n    forward eapply (@disj_locs pred) as DISJ_LOCS.\n    { auto. }\n    destruct (NPeano.Nat.eq_dec succ 0).\n    { des.\n      { by_subst. }\n      subst. trace_app_elems_exh; try by_subst.\n      { eapply wait_trace_reads in W4; by_subst. }\n      forward eapply disj_statuses_nexts with (thread2 := pred); by_subst. }\n    desc. subst tr_rel_end.\n    forward eapply disj_statuses_nexts with (thread2 := pred); by_subst. \n  Qed. \n\n  Lemma thread_next_write_unique thread tr w1 w2 pred\n        (NINIT: 0 < pred) (BOUND: pred < n_threads)\n        (HMCS: hmcs_acqiure_release lock statuses nexts thread tr)\n        (W1: (trace_elems tr ∩₁ is_w ∩₁ Loc_ (nth pred nexts 0) \\₁ Valw_ 0) w1)\n        (W2: (trace_elems tr ∩₁ is_w ∩₁ Loc_ (nth pred nexts 0) \\₁ Valw_ 0) w2):\n    w1 = w2.\n  Proof.\n    eapply set_equiv_exp in W1; [eapply set_equiv_exp in W2| ]. \n    2, 3: rewrite <- set_inter_minus_r, set_interA; apply set_equiv_refl.\n    destruct W1 as [TR1 W1], W2 as [TR2 W2].\n    pose proof (@disj_statuses_nexts thread pred) as DISJ1.\n    forward eapply (@disj_locs pred) as DISJ1'; auto. \n    red in HMCS. desc.\n    rewrite APP in TR1. apply trace_in_app in TR1. des.\n    2: { edestruct release_no_next_writes with (pred := pred); by_subst. }    \n    unfold_acquire. desc. subst tr_acq tr_acqr tr_acq_end.\n    trace_app_elems_exh; try by_subst. \n    { edestruct (@release_fence_no_write tr_relf); by_subst. }\n    2: { edestruct (@acquire_fence_no_write tr_acqf); by_subst. }\n    destruct (NPeano.Nat.eq_dec pred0 0); desc; subst tr_acq_end0. \n    { trace_app_elems_exh. by_subst. }\n    trace_app_elems_exh.\n    2: { eapply wait_trace_reads in TR4; by_subst. }\n\n    subst. move TR2 at bottom. trace_app_elems_exh; try by_subst. \n    { edestruct (@release_fence_no_write tr_relf); by_subst. }\n    { eapply wait_trace_reads in TR5; by_subst. } \n    { edestruct (@acquire_fence_no_write tr_acqf); by_subst. }\n    { edestruct release_no_next_writes with (pred := pred); by_subst. }     \n  Qed. \n  \n  Lemma rmw_of_next_write_exists w pred\n        (NINIT: pred <> 0) (BOUND: pred < n_threads)\n        (W: (E G ∩₁ is_w ∩₁ Loc_ (nth pred nexts 0) \\₁ Valw_ 0) w):\n    exists rmw, (E G ∩₁ Loc_ lock ∩₁ is_rmw ∩₁ Valr_ pred) rmw /\\ same_tid w rmw.  \n  Proof.\n    remember (tid w) as thread.\n    cdes HMCS_CLIENT. specialize (HMCS_CLIENT0 thread). specialize_full HMCS_CLIENT0.\n    { red. ins. subst thread. eapply wf_tid_init in H; [destruct w; by_subst| ..]; by_subst. }\n    { apply BOUNDED_THREADS. exists w. by_subst. }\n      desc. red in HMCS_CLIENT0. destruct (restrict G thread) as [Gt [TRE]]. desc.\n    red in HMCS. desc. unfold_acquire. desc. \n    remember (ThreadEvent thread index0 (Armw lock pred0 thread)) as rmw.\n    exists rmw.\n    enough ((trace_elems tr ∩₁ Loc_ lock ∩₁ is_w ∩₁ Valr_ pred) rmw).\n    { eapply set_equiv_exp in H.\n      2: { rewrite TR_E, TRE. apply set_equiv_refl. }\n      by_subst. }\n    split.\n    { unfolder. splits; try by_subst.\n      subst. trace_elems_solver. } \n    \n    assert (trace_elems tr w) as TRw.\n    { apply TR_E, TRE. by_subst. }\n    rewrite APP in TRw. apply trace_in_app in TRw. des.\n    2: { forward eapply release_no_next_writes with (x := w); eauto; by_subst. }\n    forward eapply (@disj_locs thread) as DISJ_LOCS.\n    { apply BOUNDED_THREADS. exists w. by_subst. }\n    pose proof (@disj_statuses_nexts thread pred) as DISJ_LOCS'.\n    forward eapply (@disj_locs pred) as DISJ_LOCS''.\n    { auto. }\n    subst tr_acq tr_acqr tr_acq_end. move TRw at bottom.\n    trace_app_elems_exh.\n    { specialize_full DISJ_LOCS'; by_destruct w. }\n    { by_destruct w. }\n    { edestruct (@release_fence_no_write tr_relf); by_subst. }\n    { by_destruct w. }\n    2: { edestruct (@acquire_fence_no_write tr_acqf); by_subst. }\n    destruct (NPeano.Nat.eq_dec pred0 0); desc; subst tr_acq_end0. \n    { trace_app_elems_exh. by_destruct w. }\n    trace_app_elems_exh.\n    2: { eapply wait_trace_reads in TRw2; by_subst. }\n    rewrite TRw1 in *.\n    forward eapply (@unique_nexts pred pred0).\n    { by_destruct w. }\n    by_subst. \n  Qed. \n      \n  Lemma next_write_unique pred (NINIT: 0 < pred) (BOUND: pred < n_threads):\n    let next_writes := E G ∩₁ is_w ∩₁ Loc_ (nth pred nexts 0) \\₁ Valw_ 0 in\n    forall w1 w2 (W1: next_writes w1) (W2: next_writes w2),\n      w1 = w2.\n  Proof.\n    remember (E G ∩₁ is_w ∩₁ Loc_ (nth pred nexts 0) \\₁ Valw_ 0) as NW.\n    ins. \n    forward eapply (@rmw_of_next_write_exists w1 pred) as [rmw RMW]; try by_subst.\n    forward eapply (@rmw_of_next_write_exists w2 pred) as [rmw' RMW']; try by_subst.\n    assert (rmw' = rmw); [| subst rmw']. \n    { apply lock_write_unique_reads; by_subst. }\n\n    remember (tid rmw) as thread.\n    pose proof (@HMCS_CLIENT thread) as HMCS. specialize_full HMCS.\n    { red. intros. subst thread. eapply wf_tid_init in H; by_destruct rmw. }\n    { apply BOUNDED_THREADS. by_subst. }\n    desc. red in HMCS. destruct (restrict G thread) as [Gt [TRE]]. desc.     \n\n    eapply (@thread_next_write_unique thread tr w1 w2 pred); auto.\n    1, 2: eapply set_equiv_exp; [rewrite TR_E, TRE; apply set_equiv_refl| by_subst].\n  Qed.\n  \n  Lemma mo_max_unique_helper w1 w2 (MAX1: mo_max G w1) (MAX2: mo_max G w2)\n        (LOC: same_loc w1 w2):\n    w1 = w2.\n  Proof.\n    unfold mo_max in *.\n    eapply max_elt_unique.\n    { apply co_sto with (l := (loc w1)). eauto. }\n    1, 2: by_subst.\n    1, 2:  desc; eapply set_subset_max_elt; eauto; basic_solver.\n  Qed. \n                                                    \n  Lemma fin_traces_app {A: Type} (l1 l2: list A):\n    trace_app (trace_fin l1) (trace_fin l2) = trace_fin (l1 ++ l2).\n  Proof. done. Qed.\n\n  Lemma trace_wf_app_both tr1 tr2 (FIN1: trace_finite tr1)\n        (WF_APP: trace_wf (trace_app tr1 tr2)):\n    trace_wf tr1 /\\ trace_wf tr2.\n  Proof.\n    split; [eapply trace_wf_app; eauto| ].\n    destruct tr1; [| by_subst].\n    eapply trace_wf_fin_app; eauto.\n  Qed. \n    \n    Lemma trace_last_app {A: Type} (tr1 tr2: trace A)\n          (FIN1: trace_finite tr1) (NEMPTY2: ~ tr2 = trace_fin []):\n      forall d, trace_last (trace_app tr1 tr2) d = trace_last tr2 d.\n    Proof.\n      destruct tr1, tr2; try by_subst. simpl.\n      ins. destruct l0; [by_subst| ]. \n      apply last_app.\n    Qed. \n      \n      \n    Lemma wait_last_read l tr cond (WAIT: busywait l tr cond)\n          (FIN: trace_finite tr):\n      forall d, cond (valr (trace_last tr d)) /\\ (trace_elems tr (trace_last tr d)).\n    Proof.\n      ins. red in WAIT. desc. subst tr. apply trace_app_finite in FIN. desc.\n      destruct tr_fail, tr_ok; try by_subst. simpl.\n      inversion BW_trace. subst l1. rewrite last_last.\n      unfolder. splits; try by_subst. by apply in_app_r.\n    Qed.\n          \n\n  Section InsideThread.\n    Variable thread: Tid. \n    Variables tr_acqr tr_acqf tr_relf tr_relr: trace Event.\n    \n    Hypothesis (NINIT : 0 < thread).\n    Hypothesis (LT : thread < n_threads).\n    Hypothesis (ACQ0 : hmcs_acquire_real lock statuses nexts thread tr_acqr).\n    Hypothesis (ACQ1 : acquire_fence tr_acqf).\n    Hypothesis (REL0 : release_fence tr_relf).\n    Hypothesis (REL1 : hmcs_release_real lock statuses nexts thread tr_relr).\n\n    Let tr := trace_app (trace_app tr_acqr tr_acqf) (trace_app tr_relf tr_relr). \n\n    Hypothesis (TR_E : trace_elems tr ≡₁ E G ∩₁ Tid_ thread).\n    Hypothesis (TR_WF : trace_wf tr).\n\n    Hypothesis (IND: forall thread' (ORD: lock_order thread' thread),\n                   set_finite (E G ∩₁ Tid_ thread')).\n\n    Lemma hmcs_tr: hmcs_acqiure_release lock statuses nexts thread tr.\n    Proof.\n      subst tr. red. do 2 eexists. \n      splits; eauto; red; eauto.\n    Qed. \n        \n    Ltac exploit_trace_app_finite :=\n      match goal with\n      | H: trace_finite (trace_app ?t1 ?t2) |- _ =>\n        apply trace_app_finite in H; desc\n      end.\n\n    Lemma tr_acqr_elemsET: trace_elems tr_acqr ⊆₁ E G ∩₁ Tid_ thread.\n    Proof.\n      rewrite <- TR_E. subst tr. do 2 rewrite trace_elems_app. basic_solver.\n    Qed.\n\n    Lemma lock_co_rf_imm:\n      immediate (restr_rel (Loc_ lock \\₁ is_init) (co G))\n                ⊆ restr_rel is_rmw (rf G).\n    Proof.\n      red. intros rmw1 rmw2 CO. red in CO. desc.      \n      red in CO. desc. apply exploit_co in CO; auto. \n      forward eapply (@lock_writes rmw1) as RMW1; [by_subst| ].\n      forward eapply (@lock_writes rmw2) as RMW2; [by_subst| ]. \n      red. splits; try by_subst.\n      forward eapply (@RFC rmw2) as [w' RF]; [by_destruct rmw2| ].\n      destruct (classic (w' = rmw1)) as [| NEQ]; [congruence| ].\n      forward eapply (@wf_co_total _ WF lock)with (a := rmw1) (b := w') as CO'; auto.\n      { by_subst. }\n      { apply exploit_rf in RF; auto. by_destruct w'. }\n      des.\n      { eapply co_ninit, seq_eqv_r in CO'; eauto.\n        apply exploit_rf in RF; auto. \n        destruct (CO0 w').\n        { red. splits; by_destruct w'. }\n        { red. splits; try by_destruct w'. desc. apply rf_co_helper; auto. }\n      }\n      destruct (cycle_helper2 _ rmw2 rmw1 SCpL).\n      2: { basic_solver. }\n      right. red. split.\n      { eexists. split; eauto. }\n      red. ins. red in H. desc. eapply co_irr; vauto. \n    Qed. \n\n    Lemma lock_co_rf: restr_rel (Loc_ lock \\₁ is_init) (co G) ⊆ (restr_rel is_rmw (rf G))^+.\n    Proof.\n      rewrite (@fsupp_imm_t _ (restr_rel (Loc_ lock \\₁ is_init) (co G))).\n      { apply clos_trans_mori, lock_co_rf_imm. }\n      { forward eapply (fin_l_writes lock) as [dom DOM].\n        exists dom. ins. apply DOM.\n        red in REL. desc. apply exploit_co in REL; by_subst. }\n      { apply irreflexive_restr, co_irr; auto. }\n      { apply transitive_restr, co_trans; auto. }      \n    Qed.\n\n    Lemma rmw_rf_chain rmw rmw' r\n          (LOCK: (E G ∩₁ Loc_ lock ∩₁ is_rmw) rmw)\n          (RF: rf G rmw' rmw)\n          (R: (E G ∩₁ Loc_ lock ∩₁ is_r) r)\n          (SB: sb G rmw' r)\n        (NEQ_VAL: valr r <> valw rmw'):\n      ((restr_rel is_rmw (rf G))＊ ⨾ rf G) rmw r.\n    Proof.\n      forward eapply (@RFC r) as [w RFr]; [by_subst| ].\n      destruct (classic (w = rmw)) as [| NEQ'].\n      { subst w. exists rmw. split; auto. apply rt_refl. }\n      forward eapply (@wf_co_total _ WF lock) with (a := rmw) (b := w) as CO'; eauto.\n      { by_destruct rmw. }\n      { apply exploit_rf in RFr; auto. by_destruct w. }\n      des.\n      2: { destruct (classic (w = rmw')) as [| NEQ]. \n           { apply exploit_rf in RFr; by_subst. } \n           forward eapply (@wf_co_total _ WF lock) with (a := w) (b := rmw') as CO; eauto.\n           { apply exploit_rf in RFr; auto. by_destruct w. }\n           { apply exploit_rf in RF; auto. by_destruct rmw'. }\n           des.\n           { destruct (cycle_helper2 _ rmw' r SCpL).\n             { repeat left. apply exploit_rf in RF; auto. red. splits; by_subst. }\n             { right. red. split.\n               2: { red. ins. red in H. desc. subst rmw'. eapply sb_irr; eauto. }\n               eexists. split; eauto. }\n           }\n           destruct (cycle_helper2 _ rmw w SCpL).\n           2: { basic_solver. }\n           right. red. split.\n           { eexists. eauto. }\n           red. intros. red in H. desc. subst rmw. eapply co_irr; eauto. }\n      exists w. split; auto.\n\n      apply inclusion_t_rt. apply lock_co_rf.\n      apply exploit_co in CO'; auto. desc.\n      red. splits; auto.\n      { by_destruct rmw. }\n      { apply co_ninit, seq_eqv_r in CO'; auto. by_destruct w. }       \n    Qed. \n      \n    Lemma prev_release_events_succ0 rmw pred\n          w_next rmw'\n          index index0 index1 index2 index4\n          pred0\n          tr_acq_end tr_relf0 tr_acq_end0 tr_acq_wait\n          tr0 tr_acq tr_rel tr_acqr0 tr_acqf0 tr_acq_end1 tr_relf1 tr_acq_end2 tr_relf2 tr_relr0 tr_acqf1 tr_rel_end\n          Gt'\n          (APP : tr0 = trace_app tr_acq tr_rel)\n          (LOCK: (trace_elems tr_acqr ∩₁ Loc_ lock ∩₁ is_rmw ∩₁\n                              Valr_ pred ∩₁ Valw_ thread) rmw)\n          (PRED: pred <> 0)\n          (ACQ2 : tr_acqr =\n                  trace_app\n                    (trace_app\n                       (trace_fin\n                          [ThreadEvent thread index (Astore (nth thread statuses 0) 1);\n                          ThreadEvent thread (index + 1) (Astore (nth thread nexts 0) 0)])\n                       tr_relf0) tr_acq_end)\n          (ACQ3 : release_fence tr_relf0)\n          (Heqw_next : w_next =\n              ThreadEvent thread index1 (Astore (nth pred nexts 0) thread))\n          (ACQ5 : tr_acq_end0 = trace_app (trace_fin [w_next]) tr_acq_wait)\n          (ACQ6 : busywait (nth thread statuses 0) tr_acq_wait (eq 0))\n          (ACQ4 : tr_acq_end = trace_app (trace_fin [rmw]) tr_acq_end0)\n          (ETrmw : (E G ∩₁ Tid_ thread) rmw)\n          (RMW : rmw = ThreadEvent thread index0 (Armw lock pred thread))\n          (RFlock : rf G rmw' rmw)\n          (RMW' : ((fun a : Event => is_rmw a)\n                     ∩₁ (fun e : Event => valw e = tid e \\/ valw e = 0)) rmw')\n          (ETw_next : (E G ∩₁ Tid_ thread) w_next)\n          (PRED_TID : tid rmw' = pred)\n          (ETrmw' : (E G ∩₁ Tid_ pred) rmw')\n          (BOUNDS'0 : pred < n_threads)\n          (TRE' : E Gt' ≡₁ E G ∩₁ Tid_ pred)\n          (ACQ : tr_acq = trace_app tr_acqr0 tr_acqf0)\n  (ACQ7 : tr_acqr0 =\n         trace_app\n           (trace_app\n              (trace_fin\n                 [ThreadEvent pred index2 (Astore (nth pred statuses 0) 1);\n                 ThreadEvent pred (index2 + 1) (Astore (nth pred nexts 0) 0)])\n              tr_relf1) tr_acq_end1)\n  (ACQ9 : release_fence tr_relf1)\n  (ACQ10 : tr_acq_end1 = trace_app (trace_fin [rmw']) tr_acq_end2)\n  (ACQ11 : if NPeano.Nat.eq_dec pred0 0\n          then\n           exists index0 : nat,\n             tr_acq_end2 =\n             trace_fin\n               [ThreadEvent pred index0 (Astore (nth pred statuses 0) 0)]\n          else\n           exists (index0 : nat) (tr_acq_wait : trace Event),\n             tr_acq_end2 =\n             trace_app\n               (trace_fin\n                  [ThreadEvent pred index0 (Astore (nth pred0 nexts 0) pred)])\n               tr_acq_wait /\\ busywait (nth pred statuses 0) tr_acq_wait (eq 0))\n  (ACQ8 : acquire_fence tr_acqf0)\n  (REL : tr_rel = trace_app tr_relf2 tr_relr0)\n  (REL2 : release_fence tr_relf2)\n  (REL3 : tr_relr0 =\n         trace_app\n           (trace_app\n              (trace_fin\n                 [ThreadEvent pred index4 (Aload (nth pred nexts 0) 0)])\n              tr_acqf1) tr_rel_end)\n  (REL4 : acquire_fence tr_acqf1)\n  (REL5 : (exists index : nat,\n            tr_rel_end = trace_fin [ThreadEvent pred index (Armw lock pred 0)]) \\/\n         (exists tr_wait tr_pass : trace Event,\n            tr_rel_end = trace_app tr_wait tr_pass /\\\n            (exists (index : nat) (other : Val) (tr_succ_wait : trace Event),\n               tr_wait =\n               trace_app\n                 (trace_fin [ThreadEvent pred index (Aload lock other)])\n                 tr_succ_wait /\\\n               other <> pred /\\\n               busywait (nth pred nexts 0) tr_succ_wait (set_compl (eq 0))) /\\\n            (exists (thread : Tid) (index : nat),\n               tr_pass =\n               trace_fin\n                 [ThreadEvent thread index\n                    (Astore (nth (valr (trace_last tr_wait d_)) statuses 0) 0)])))\n  (TR_E0 : trace_elems tr0 ≡₁ E Gt')\n  (TR_WF0 : trace_wf tr0)\n  (FIN' : trace_finite tr0):\n      \n  exists r'_lock w'_st : Event,\n    (is_r ∩₁ Loc_ lock) r'_lock /\\\n    (is_w ∩₁ Loc_ (nth thread statuses 0) ∩₁ Valw_ 0)\n      w'_st /\\\n    sb G r'_lock w'_st /\\\n    ((restr_rel is_rmw (rf G))＊ ⨾ rf G) rmw r'_lock.\n    Proof.\n      des.\n      { remember (ThreadEvent pred index3 (Armw lock pred 0)) as rmw''.\n        enough (rf G rmw' rmw'') as RF'.\n        { forward eapply (rmws_atomicity_violation rmw' rmw rmw''); try by_subst.            \n          ins.\n          (* by_subst.  - stopped working as is*)\n          enough (valw rmw = 0); by_subst. }\n        assert ((E G ∩₁ Tid_ pred) rmw'') as ETrmw''.\n        { apply TRE', TR_E0.\n          subst tr0. apply trace_elems_app. rewrite emiT.\n          2: { apply trace_app_finite in FIN'. by desc. }\n          right. subst. trace_elems_solver. }\n        forward eapply (@RFC rmw'') as [rmw'_ RF']; [by_subst| ].\n        replace rmw' with rmw'_; auto.\n        eapply unique_eq; [by apply (@lock_write_unique pred) | ..].\n        { apply exploit_rf in RF'; auto. unfolder. splits; try by_subst. \n          forward eapply (@lock_writes rmw'_); [by_destruct rmw'_| ].\n          ins. by_subst. }\n        { apply exploit_rf in RFlock; auto. by_destruct rmw'. }          \n      }\n      remember (ThreadEvent pred index5 (Aload lock other)) as r'_lock.\n      assert (trace_elems tr0 r'_lock) as TR0r'_lock.\n      { (* It works as is, but too slowly. You may want to skip it during WiP *)\n        subst. repeat exploit_trace_app_finite. trace_elems_solver. } \n      remember (ThreadEvent thread0 index3 (Astore (nth (valr (trace_last tr_wait d_)) statuses 0) 0)) as w'_st.\n      assert (trace_elems tr0 w'_st) as TR0w'_st.\n      { (* It works as is, but too slowly. You may want to skip it during WiP *)\n        subst. repeat exploit_trace_app_finite. trace_elems_solver. }\n      exists r'_lock, w'_st.\n      assert ((E G ∩₁ Tid_ pred) r'_lock) as EPr'_lock.\n      { apply TRE', TR_E0. subst.\n        (* It works as is, but too slowly. You may want to skip it during WiP *)\n        trace_elems_solver. }\n      assert ((E G ∩₁ Tid_ pred) w'_st) as EPw'_st.\n      { apply TRE', TR_E0. subst.\n        (* It works as is, but too slowly. You may want to skip it during WiP *)\n        trace_elems_solver. }\n      \n      splits; [by_subst| ..]. \n      { enough (valr (trace_last tr_wait d_) = thread) as LOC_THREAD.\n        { by_subst. }\n        remember (trace_last tr_wait d_) as r_last.\n        forward eapply wait_last_read with (d := d_) as [N0 TRwait]; eauto. \n        { subst. repeat exploit_trace_app_finite. auto. }\n        subst tr_wait. rewrite trace_last_app in Heqr_last; [| by_subst |].\n        2: { eapply wait_nonempty; eauto. } \n        forward eapply wait_trace_reads with (x := r_last) as R_LAST; try by vauto.\n        rewrite PRED_TID in *. \n        forward eapply (@RFC r_last) as [w RFlast].\n        { enough (trace_elems tr0 r_last) as TR0. \n          { apply TR_E0, TRE' in TR0. by_subst. }\n          forward eapply wait_last_read with (d := d_) as [_ TRswait]; eauto.\n          { subst. repeat exploit_trace_app_finite. auto. }\n          (* It works as is, but too slowly. You may want to skip it during WiP *)\n          subst. repeat exploit_trace_app_finite. trace_elems_solver. }\n        replace thread with (valw w).\n        { apply exploit_rf in RFlast; by_subst. }\n        rewrite <- Heqr_last in *.\n        \n        replace w with w_next; [by_subst| ].\n        eapply (@next_write_unique pred); eauto.\n        { lia. }\n        { unfolder. splits; by_subst. }\n        { apply exploit_rf in RFlast; auto.          \n          unfolder. splits; by_subst. }\n      }\n      { apply seq_eqv_lr. splits.\n        1, 3: by_subst. \n        apply (trace_wf_app_sb tr_wait tr_pass).\n        { subst. repeat exploit_trace_app_finite.\n          repeat (match goal with\n                  | H: trace_wf (trace_app ?t1 ?t2) |- _ =>\n                    apply trace_wf_app_both in H; [| fin_trace_solver]; desc; try by auto\n                  end). }\n        { subst. repeat (exploit_trace_app_finite; auto). }\n        1, 2: subst; trace_elems_solver. \n        by_subst. }\n      \n      eapply rmw_rf_chain; eauto.\n      1, 2:  by_subst.\n      { apply seq_eqv_lr. splits; try by_subst.\n        eapply trace_wf_app_sb.\n        { subst tr0. eauto. }\n        { subst tr0. apply trace_app_finite in FIN'. by desc. }\n        { subst. trace_elems_solver. }\n        { subst. trace_elems_solver. }\n        by_subst. }\n      apply exploit_rf in RFlock; auto. by_subst.\n    Qed. \n\n    Lemma prev_release_events rmw pred\n          (LOCK: (trace_elems tr_acqr ∩₁ Loc_ lock ∩₁ is_rmw ∩₁ Valr_ pred ∩₁ Valw_ thread) rmw)\n          (PRED: pred <> 0):\n      exists w'_st r,\n        (is_w ∩₁ Loc_ (nth thread statuses 0) ∩₁ Valw_ 0) w'_st /\\\n        sb G r w'_st /\\\n        ((is_r ∩₁ Loc_ lock) r /\\\n         (((restr_rel is_rmw (rf G))^* ⨾ rf G) rmw r)\n         \\/\n         (is_r ∩₁ Loc_ (nth pred nexts 0) \\₁ Valr_ 0) r\n        ).\n    Proof.\n      unfold_acquire. cdes ACQ0.\n      forward eapply (@tr_acqr_elemsET rmw) as ETrmw; [by_subst| ]. \n      \n      assert (rmw = ThreadEvent thread index0 (Armw lock pred0 thread)) as RMW.\n      { eapply unique_eq.\n        { eapply unique_equiv. \n          2: { apply (@lock_write_unique thread); lia. }\n          symmetry. apply unique_rmw_helper. lia. }\n        { by_subst. } \n        eapply set_equiv_exp.\n        { do 2 rewrite set_interA. apply set_equiv_refl2. }\n        split; [| by_subst]. apply tr_acqr_elemsET. subst. trace_elems_solver. }\n      assert (pred0 = pred); [by_subst | subst pred0]. rewrite <- RMW in *. \n            \n      assert (exists rmw', rf G rmw' rmw) as [rmw' RFlock].\n      { apply RFC. by_destruct rmw. }\n      forward eapply (@lock_writes rmw') as RMW'.\n      { apply exploit_rf in RFlock; auto. unfolder. splits; try by_subst.\n        by_destruct rmw'. }\n      destruct (NPeano.Nat.eq_dec pred O); [lia| ]. desc.\n      remember (ThreadEvent thread index1 (Astore (nth pred nexts 0) thread)) as w_next.\n      forward eapply (@tr_acqr_elemsET w_next) as ETw_next; [subst; trace_elems_solver| ].\n\n      assert (tid rmw' = pred) as PRED_TID.\n      { forward eapply (@unique_rmw_helper pred) as [_ RMW'_].\n        { lia. }\n        specialize (RMW'_ rmw'). specialize_full RMW'_; [| by_subst].\n        apply exploit_rf in RFlock; auto. by_destruct rmw'. }\n\n      assert ((E G ∩₁ Tid_ pred) rmw') as ETrmw'.\n      { apply exploit_rf in RFlock; by_subst. }\n      \n      assert (pred <> 0 /\\ pred < n_threads) as BOUNDS'. \n      { split.\n        2: { apply BOUNDED_THREADS. by_subst. }\n        subst pred. red. intros. eapply wf_tid_init in H; eauto; [| by_subst]. \n        destruct rmw'; by_subst. }\n      cdes HMCS_CLIENT. specialize (HMCS_CLIENT0 pred).\n      specialize_full HMCS_CLIENT0; auto. desc.\n      red in HMCS_CLIENT0. destruct (restrict G pred) as [Gt' [TRE']]. desc.\n      red in HMCS. desc. unfold_acquire. desc.\n      assert (rmw' = ThreadEvent pred index3 (Armw lock pred0 pred)).\n      { eapply unique_eq.\n        { eapply unique_equiv. \n          2: by apply (@lock_write_unique pred).\n          symmetry. by apply unique_rmw_helper. }\n        { apply exploit_rf in RFlock; auto. unfolder. splits; by_subst. }\n        eapply set_equiv_exp.\n        { rewrite <- TRE', <- TR_E0, !set_interA; apply set_equiv_refl2. }\n        split; [| by_subst]. subst. trace_elems_solver. }\n      rewrite <- H in *. clear H.\n\n      assert (trace_finite tr0) as FIN'.\n      { apply nodup_trace_elems; [by apply trace_wf_nodup| ].\n        rewrite TR_E0, TRE'. apply IND. exists rmw'. exists rmw.\n        splits; [| by_subst| ]. \n        { apply exploit_rf in RFlock; auto. unfolder. splits; try by_subst. }\n        apply rf_co_helper; auto. by_destruct rmw. }\n\n      unfold_release. desc.\n      destruct (NPeano.Nat.eq_dec succ 0).\n      { subst succ. \n        forward eapply prev_release_events_succ0 with (tr0 := tr0); eauto.\n        { by_subst. }\n        ins. desc. exists w'_st, r'_lock. auto. }\n\n      desc. \n      remember (ThreadEvent pred index4 (Aload (nth pred nexts 0) succ)) as r'.\n      assert ((E G ∩₁ Tid_ pred) r') as EPr'.\n      { apply TRE', TR_E0. subst tr0. apply trace_in_app. right. split.\n        { exploit_trace_app_finite. fin_trace_solver. }\n        subst. trace_elems_solver. }\n      remember (ThreadEvent thread0 index5 (Astore (nth succ statuses 0) 0)) as w'_st.\n      assert ((E G ∩₁ Tid_ pred) w'_st) as EPw'_st.\n      { apply TRE', TR_E0. subst tr0. apply trace_in_app. right. split.\n        { exploit_trace_app_finite. fin_trace_solver. }\n        subst. trace_elems_solver. }\n      assert (succ = thread); [| subst succ].\n      { replace succ with (valr r') by by_subst.\n        forward eapply (@RFC r') as [w' RF']; [by_subst| ].\n        assert (w' = w_next); [| subst w'].\n        { apply (@next_write_unique pred); try lia.\n          { apply exploit_rf in RF'; auto. by_subst. }\n          { unfolder. splits; by_subst. }\n        }\n        apply exploit_rf in RF'; auto. by_subst. } \n        \n      exists w'_st, r'. splits.\n      { unfolder. splits; by_subst. }\n      { apply seq_eqv_lr. splits.\n        1, 3: by_subst.\n        subst tr0.\n        apply trace_wf_app_sb with (tr1 := trace_fin [r'])\n                                   (tr2 := trace_app tr_acqf1 tr_rel_end).\n        { rewrite trace_app_assoc.\n          subst. \n          exploit_trace_app_finite.\n          repeat (match goal with\n                  | H: trace_wf (trace_app ?t1 ?t2) |- _ =>\n                    apply trace_wf_app_both in H; [| fin_trace_solver]; desc; auto\n                  end). }\n        { by_subst. }\n        { by_subst. }\n        { subst. trace_elems_solver. }\n        { by_subst. }\n      }\n      right. by_subst. \n    Qed.\n\n    Lemma status_write_thread:\n      (E G ∩₁ is_w ∩₁ Loc_ (nth thread statuses 0) \\₁ Valw_ 0) ⊆₁ Tid_ thread.\n    Proof.\n      red. intros w W.\n      assert (0 < tid w < n_threads) as TID.\n      { split.\n        { cut (tid w <> 0); [lia| ].\n          red. intros EQ0. eapply wf_tid_init in EQ0; by_destruct w. }\n        { apply BOUNDED_THREADS. by_subst. }\n      }          \n      forward eapply (@HMCS_CLIENT (tid w)); try lia. ins. desc. red in H.\n      destruct (restrict G (tid w)) as [Gt' [TRE']]. desc.\n      assert (trace_elems tr0 w) as TRw.\n      { apply TR_E0, TRE'. by_subst. }\n      red in HMCS. desc. red in ACQ, REL. desc.\n      subst tr0 tr_acq tr_rel. trace_app_elems_exh.\n      2: { edestruct (@acquire_fence_no_write tr_acqf0); by_subst. }\n      2: { edestruct (@release_fence_no_write tr_relf0); by_subst. }\n      2: { unfold_release. cdes REL1. subst.\n           move TRw1 at bottom. trace_app_elems_exh.\n           { forward eapply (@disj_statuses_nexts (tid w) (tid w)); [by_destruct w| ].\n             lia. }\n           { edestruct (@acquire_fence_no_write tr_acqf2); by_subst. }\n           destruct (NPeano.Nat.eq_dec succ0 0); desc; des; subst. \n           { trace_app_elems_exh. by_destruct w. }\n           { trace_app_elems_exh; try by_destruct w.\n             eapply wait_trace_reads in TRw3; eauto. by_subst. }\n           { trace_app_elems_exh. by_subst. }\n      }\n      unfold_acquire. desc. subst.\n      move TRw at bottom. trace_app_elems_exh.\n      { forward eapply (@unique_statuses (tid w) thread); [by_destruct w| ]. \n        ins. des; by_subst. }\n      { forward eapply (@disj_locs (tid w)); [lia| ].\n        ins. desc. destruct H. by_destruct w. }\n      { edestruct (@release_fence_no_write tr_relf1); by_subst. }\n      { forward eapply (@disj_locs thread); [lia| ].\n        ins. desc. destruct H. by_destruct w. } \n      { destruct (NPeano.Nat.eq_dec pred 0); desc; subst.\n        { trace_app_elems_exh. by_destruct w. }\n        { trace_app_elems_exh.\n          { forward eapply (@disj_statuses_nexts thread pred); by_destruct w. }\n          { eapply wait_trace_reads in TRw2; by_subst. }\n        }\n      }\n    Qed.\n      \n\n    Lemma status_writes:\n      exists! w, (E G ∩₁ is_w ∩₁ Loc_ (nth thread statuses 0) \\₁ Valw_ 0) w.\n    Proof.\n      cdes ACQ0. \n      remember (ThreadEvent thread index (Astore (nth thread statuses 0) 1)) as w.\n      exists w. split.\n      { unfolder. splits; try by_subst. apply tr_acqr_elemsET.\n        subst. trace_elems_solver. }\n      intros w' W'. \n      assert (tid w' = thread) as TID. \n      { rewrite (@status_write_thread w'); by_subst. }\n      assert (trace_elems tr w') as TRw'.\n      { apply TR_E. by_subst. }\n      subst tr. trace_app_elems_exh.\n      2: { edestruct (@acquire_fence_no_write tr_acqf); by_subst. }\n      2: { edestruct (@release_fence_no_write tr_relf); by_subst. }\n      2: { unfold_release. cdes REL1. subst.\n           move TRw'1 at bottom. trace_app_elems_exh.\n           { forward eapply (@disj_statuses_nexts (tid w') (tid w')); [by_destruct w'| ].\n             lia. }\n           { edestruct (@acquire_fence_no_write tr_acqf0); by_subst. }\n           destruct (NPeano.Nat.eq_dec succ 0); desc; des; subst. \n           { trace_app_elems_exh. by_destruct w'. }\n           { trace_app_elems_exh; try by_destruct w'.\n             eapply wait_trace_reads in TRw'3; eauto. by_subst. }\n           { trace_app_elems_exh. by_subst. }\n      }\n      unfold_acquire. desc. subst.\n      move TRw' at bottom. trace_app_elems_exh.\n      { forward eapply (@disj_statuses_nexts (tid w') (tid w')); [by_destruct w'| ].\n        lia. }\n      { edestruct (@release_fence_no_write tr_relf0); by_subst. }\n      { forward eapply (@disj_locs (tid w')); [lia| ].\n        ins. desc. destruct H. by_destruct w'. }\n      { destruct (NPeano.Nat.eq_dec pred 0); desc; subst.\n        { trace_app_elems_exh. by_destruct w'. }\n        { trace_app_elems_exh.\n          { forward eapply (@disj_statuses_nexts (tid w') pred); by_destruct w'. }\n          { eapply wait_trace_reads in TRw'2; by_subst. }\n        }\n      }\n    Qed.\n\n    Lemma rmw_valw_bounded w (W: (E G ∩₁ is_w ∩₁ Loc_ lock) w):\n      valw w < n_threads.\n    Proof.\n      destruct (classic (is_init w)); [by_destruct w| ].\n      (* apply exploit_rf in RF; auto.  *)\n      forward eapply (@lock_writes w) as W_; [by_destruct w| ]. \n      red in W_. desc. des; [| by_subst].\n      rewrite W_0. apply BOUNDED_THREADS. exists w. by_subst. \n    Qed.\n\n    Lemma rmw_valr_bounded rmw (RMW: (E G ∩₁ is_w ∩₁ Loc_ lock \\₁ is_init) rmw):\n      valr rmw < n_threads. \n    Proof.\n      forward eapply (@lock_writes rmw) as RMW_; [by_subst| ]. \n      forward eapply (@RFC rmw) as [w RF]; [by_destruct rmw| ].\n      erewrite <- wf_rfv; eauto.\n      apply exploit_rf in RF; auto. \n      apply rmw_valw_bounded. unfolder. splits; by_subst.\n    Qed. \n    \n    Lemma acquire_real_fin:\n      trace_finite tr_acqr.\n    Proof.\n      cdes ACQ0.\n      enough (trace_finite tr_acq_end); [subst; fin_trace_solver| ].\n      cdes ACQ4. destruct (NPeano.Nat.eq_dec pred 0); [by_subst| ]. desc.\n      enough (trace_finite tr_acq_wait); [subst; fin_trace_solver| ].\n      contra INF.\n\n      remember (nth thread statuses 0) as st.\n      remember (ThreadEvent thread index0 (Armw lock pred thread)) as rmw.\n      remember (ThreadEvent thread index (Astore st 1)) as w1.\n\n      assert (trace_elems tr_acq_wait ⊆₁ E G) as ACQ_E.\n      { transitivity (trace_elems tr_acqr).\n        { subst. repeat (rewrite trace_elems_app, emiT; [| fin_trace_solver]).\n          basic_solver. }\n        etransitivity; [apply tr_acqr_elemsET| ]. basic_solver. }\n      \n      forward eapply (fin_w_max G st) as [wmax [MAX LOC]];\n        [done| by apply fin_l_writes| ].\n\n      (* forward eapply (@status_writes wmax) as MAX'; [red in MAX; by_subst| ]. *)\n      pose proof (classic (Valw_ 0 wmax)) as MAX'. \n\n      (* red in MAX'. *)\n      des.\n      \n      { apply INF. eapply wait_fin_iff_cond; eauto.\n        forward eapply (wait_latest_read_helper ACQ7) as [i LATEST]; try by_subst.\n        { subst tr. edestruct rel_fin; eauto. edestruct acq_fin; eauto.\n          subst. move TR_WF at bottom. \n          rewrite <- !trace_app_assoc in TR_WF.\n          repeat (apply trace_wf_app_both in TR_WF as [_ TR_WF]; [| fin_trace_solver]).\n          eapply trace_wf_app; eauto. }\n        remember (trace_nth i tr_acq_wait d_) as r. exists r.\n        assert (NOmega.lt_nat_l i (trace_length tr_acq_wait)) as DOMi.\n        { destruct tr_acq_wait; [edestruct INF; vauto | by_subst]. }\n        split.\n        { subst r. by apply trace_nth_in. }\n        forward eapply (@RFC r) as [w RFwr].\n        { apply hahn_subset_exp with (s := trace_elems tr_acq_wait).\n          2: { subst r. by apply trace_nth_in. }\n          apply set_subset_inter_r. split; auto. \n          erewrite wait_trace_reads; eauto. basic_solver. }\n        specialize (LATEST i w). specialize_full LATEST; [lia| ..].\n        { erewrite trace_nth_indep; [by_subst| ].\n          destruct tr_acq_wait; by_subst. }\n        rewrite <- MAX'.\n        rewrite (@mo_max_unique_helper wmax w); try by_subst.  \n        { apply exploit_rf in RFwr; by_subst. }\n        { apply wait_trace_reads in ACQ7.\n          specialize (ACQ7 r). specialize_full ACQ7.\n          { subst r. by apply trace_nth_in. }\n          apply exploit_rf in RFwr; auto. by_subst. }\n      }\n      \n      assert (wmax = w1); [| subst wmax].\n      { eapply unique_eq; [apply status_writes| ..].\n        { red in MAX. by_subst. }\n        { unfolder. splits; try by_subst.\n          apply tr_acqr_elemsET. subst. trace_elems_solver. }\n      }\n\n      forward eapply (@prev_release_events rmw pred) as [w'_st [r' PROPS']]; eauto.\n      { unfolder. splits; try by_subst. subst. trace_elems_solver. }\n      \n      desc.  \n      forward eapply (@mo_max_co w1 w'_st) as CO; try by_subst.\n      { desc. apply seq_eqv_lr in PROPS'0. by_subst. }\n      destruct CO as [| CO]; [by_subst| ].\n      assert (E G w1) as Ew1.\n      { red in MAX. by_subst. }\n\n      assert (E G rmw) as Ermw.\n      { apply hahn_subset_exp with (s := trace_elems tr); [rewrite TR_E; basic_solver| ].\n        subst tr. subst. trace_elems_solver. }\n      \n      des.\n      { assert (sb G w1 rmw) as SBw1rmw. \n        { apply seq_eqv_lr. splits; auto.\n          move TR_WF at bottom. subst tr. do 2 apply trace_wf_app in TR_WF.\n          rewrite ACQ2 in TR_WF.\n          edestruct rel_fin; eauto. rewrite H, fin_traces_app in TR_WF.\n          eapply trace_wf_app_sb; eauto; try by_subst. \n          subst. trace_elems_solver. }\n        apply no_cycle. exists r'. repeat (eexists; split; eauto). }\n      { remember (ThreadEvent thread index1 (Astore (nth pred nexts 0) thread)) as w_next. \n        assert (rf G w_next r') as RF'.\n        { forward eapply (@RFC r') as [w' RF']; [apply seq_eqv_lr in PROPS'0; by_subst| ].\n          replace w_next with w'; [done| ].\n          apply (@next_write_unique pred); try lia.\n          { replace pred with (valr rmw) by by_subst.\n            apply rmw_valr_bounded. by_subst. }\n          { apply exploit_rf in RF'; auto. unfolder. splits; by_subst. }\n          { eapply set_equiv_exp; [rewrite !set_interA, <- set_inter_minus_r; apply set_equiv_refl| ].\n            split; [| unfolder; splits; by_subst].\n            forward eapply (@tr_acqr_elemsET w_next); [| ins; by_subst].\n            subst. trace_elems_solver. }\n        }\n        assert (sb G w1 w_next) as SB.\n        { apply seq_eqv_lr. splits; try by_subst.\n          2: { apply exploit_rf in RF'; by_subst. }\n          do 2 apply trace_wf_app in TR_WF. subst tr_acqr. \n          eapply trace_wf_app_sb; eauto; subst;\n            [fin_trace_solver | trace_elems_solver | trace_elems_solver | by_subst]. }\n        apply no_cycle. exists r'. repeat (eexists; split; eauto).\n        apply rt_refl. \n      }\n    Qed.\n\n    Lemma acquire_real_events:\n      exists w_next rmw,\n        (trace_elems tr_acqr ∩₁ is_w ∩₁ Loc_ (nth thread nexts 0) ∩₁ Valw_ 0) w_next /\\\n        (trace_elems tr_acqr ∩₁ is_w ∩₁ Loc_ lock ∩₁ Valw_ thread) rmw /\\\n        sb G w_next rmw.\n    Proof.\n      unfold_acquire. cdes ACQ0.\n      remember (ThreadEvent thread (index + 1) (Astore (nth thread nexts 0) 0)) as w_next.\n      remember (ThreadEvent thread index0 (Armw lock pred thread)) as rmw.\n      exists w_next, rmw.\n      splits.\n      1, 2:  eapply set_equiv_exp;\n        [rewrite !set_interA; apply set_equiv_refl|\n         split; [subst; trace_elems_solver| by_subst]].\n      apply seq_eqv_lr. splits.\n      1, 3: apply tr_acqr_elemsET; subst; trace_elems_solver.\n      subst tr. do 2 apply trace_wf_app in TR_WF. subst tr_acqr. \n      eapply trace_wf_app_sb; eauto.\n      { fin_trace_solver. }\n      { trace_elems_solver. }\n      { subst. trace_elems_solver. }\n      { by_subst. }\n    Qed. \n\n    Lemma tr_relr_elemsET: trace_elems tr_relr ⊆₁ E G ∩₁ Tid_ thread.\n    Proof.\n      rewrite <- TR_E. unfold tr. rewrite trace_elems_app, emiT.\n      2: { apply trace_app_finite. split; [apply acquire_real_fin| fin_trace_solver]. }\n      apply set_subset_union_r. right.\n      rewrite trace_elems_app, emiT; [basic_solver | fin_trace_solver]. \n    Qed.\n\n    (* Lemma co_wf: well_founded (co G). *)\n    (* Proof. *)\n\n    Lemma next_rmw_exists rmw r_lock\n          (RMW : (trace_elems tr_acqr ∩₁ is_w ∩₁ Loc_ lock\n                              ∩₁ Valw_ thread) rmw)\n          (Ermw : (E G ∩₁ Tid_ thread) rmw)\n          (RLOCK: (trace_elems tr_relr ∩₁ is_r ∩₁ Loc_ lock \\₁ Valr_ thread) r_lock):\n      exists rmw', rf G rmw rmw' /\\ co G rmw rmw'\n              (* /\\ *)\n              (* (Valw_ 0 rmw' /\\ trace_elems *)\n                                .\n    Proof. \n      forward eapply (@tr_relr_elemsET r_lock) as ETr_lock; [by_subst| ]. \n      assert (sb G rmw r_lock) as SB.\n      { apply seq_eqv_lr. splits; try by_subst.\n        eapply trace_wf_app_sb; eauto.\n        { apply trace_app_finite. split; [apply acquire_real_fin | fin_trace_solver]. }\n        { trace_elems_solver. }\n        { subst. trace_elems_solver. }\n        forward eapply (@tr_relr_elemsET r_lock); [by_subst| ]. \n        by_destruct r_lock. }\n      \n      forward eapply (@RFC r_lock) as [w_lock RFlock]; [by_subst| ].\n      destruct (classic (w_lock = rmw)) as [| NEQ].\n      { subst w_lock.\n        red in RLOCK. desc. destruct RLOCK0. \n        erewrite <- wf_rfv; by_subst. }\n      forward eapply (@wf_co_total _ WF lock) with (a := w_lock) (b := rmw) as CO; eauto.\n      { apply exploit_rf in RFlock; auto. unfolder. splits; by_subst. }\n      { by_subst. }\n      des.\n      { destruct (cycle_helper2 _ rmw r_lock SCpL).\n        { repeat left. red. split; by_subst. }\n        right. split.\n        2: { unfolder. red. ins. desc. subst r_lock.\n             eapply sb_irr; eauto. }\n        eexists. split; eauto. }\n      \n      apply fsupp_imm_t in CO;\n        [| cdes FAIR | eapply co_irr | eapply co_trans]; eauto.      \n      apply ct_begin in CO as [rmw' [IMM_CO CO']].\n      \n      exists rmw'. split; [| red in IMM_CO; by desc].\n      apply lock_co_rf_imm.\n      red in IMM_CO. desc. red. split.\n      { red. splits; auto.\n        { by_destruct rmw. }\n        { apply exploit_co in IMM_CO; auto. red. split; by_subst. }\n      }\n      { ins. red in R1, R2. apply (IMM_CO0 c); by_subst. }\n    Qed.\n\n    Lemma next_write_of_rmw rmw\n        (RMW : (E G ∩₁ is_w ∩₁ Loc_ lock ∩₁ Valr_ thread \\₁ Valw_ 0) rmw):\n      exists w_next,\n        (is_w ∩₁ Loc_ (nth thread nexts 0) \\₁ Valw_ 0) w_next /\\\n        sb G rmw w_next.\n    Proof.\n      forward eapply (@lock_writes rmw) as RMW_; [by_destruct rmw| ].\n      destruct RMW_ as [RMW_ VAL]. des; [| by_subst]. \n      \n      forward eapply (@HMCS_CLIENT (tid rmw)).\n      { red. intros. eapply wf_tid_init in H; eauto; by_destruct rmw. }\n      { apply BOUNDED_THREADS. by_subst. }\n      ins. desc. red in H. destruct (restrict G (tid rmw)) as [Gt' [TRE']]. desc.\n      \n      red in HMCS. unfold_acquire. desc.\n      rewrite <- VAL in *.\n      remember (ThreadEvent (tid rmw) index0 (Armw lock pred (tid rmw))) as rmw'.\n      \n      assert ((E G ∩₁ Tid_ (tid rmw)) rmw') as ETrmw'.\n      { rewrite <- VAL. apply TRE', TR_E0. subst.\n        rewrite VAL. trace_elems_solver. }\n      assert (rmw' = rmw); [| subst rmw'].\n      { eapply unique_eq.\n        { apply (@lock_write_unique (valw rmw)); [by_subst| ].\n          apply rmw_valw_bounded. by_subst. }\n        1, 2:  by_subst. }\n      rewrite VAL, H in *.\n      assert (pred = thread); [| subst pred]. \n      { replace thread with (valr rmw) by by_subst. by rewrite <- H. }\n\n      destruct (NPeano.Nat.eq_dec thread 0); [lia| ]. desc.\n      remember (ThreadEvent (tid rmw) index1 (Astore (nth thread nexts 0) (tid rmw))) as w_next.\n      exists w_next. split.\n      { split; [by_subst| ]. replace (valw w_next) with (tid rmw); by_subst. }\n      apply seq_eqv_lr. splits; [by_subst| ..].\n      2: { eapply hahn_subset_exp with (s := trace_elems tr0). \n           { rewrite TR_E0, TRE'. basic_solver. }\n           subst. trace_elems_solver. }\n      subst. do 2 apply trace_wf_app in TR_WF0. \n      apply trace_wf_app_both in TR_WF0 as [_ TR_WF0]; [| fin_trace_solver].\n      eapply trace_wf_app_sb; eauto;\n        [fin_trace_solver| by_subst| trace_elems_solver].\n    Qed. \n\n    Lemma lock_not_status i:\n      lock <> nth i statuses 0.\n    Proof.\n      red. intros EQ. \n      destruct (PeanoNat.Nat.lt_ge_cases i n_threads).\n      { rewrite app_comm_cons in DISJ_LOC. apply nodup_app in DISJ_LOC.\n        cdes DISJ_LOC.\n        cut (0 = S i); [lia| ].\n        eapply NoDup_nth with (d := 0); [apply DISJ_LOC0| ..]; auto; simpl;\n          [lia | ].\n        apply Lt.lt_n_S. rewrite <- STATUSES_LEN in H. auto. }\n      { rewrite nth_overflow in EQ; [| by rewrite STATUSES_LEN].\n        by_subst. }\n    Qed. \n\n    Lemma lock_not_next i:\n      lock <> nth i nexts 0.\n    Proof.\n      red. intros EQ. \n      destruct (PeanoNat.Nat.lt_ge_cases i n_threads).\n      { cdes DISJ_LOC.\n        cut (0 = n_threads + S i); [lia| ].\n        eapply NoDup_nth with (d := 0); [apply DISJ_LOC| ..]; auto;\n          [simpl; lia | .. ].\n        { cdes NEXTS_LEN. cdes STATUSES_LEN. simpl. rewrite app_length. lia. }\n        replace (n_threads + S i) with (S (length statuses + i)).\n        2: { rewrite STATUSES_LEN. lia. }\n        simpl. by rewrite app_nth2_plus. } \n      { rewrite nth_overflow in EQ; [| by rewrite NEXTS_LEN].\n        by_subst. }\n    Qed.       \n\n    Lemma release_no_wait rmw\n          (RMW: (trace_elems tr ∩₁ is_w ∩₁ Loc_ lock ∩₁ Valw_ 0 \\₁ is_init) rmw):\n      trace_finite tr.\n    Proof.      \n      eapply set_equiv_exp in RMW.\n      2: { rewrite <- set_inter_minus_r. repeat rewrite set_interA. apply set_equiv_refl. }\n      destruct RMW as [TRw RMW]. unfold tr.\n      apply trace_app_finite. split.\n      { apply trace_app_finite. split; [apply acquire_real_fin| fin_trace_solver]. }\n      apply trace_app_finite. split; [fin_trace_solver| ].\n      subst tr. \n      unfold_acquire. cdes ACQ0. move TRw at bottom. subst.\n      trace_app_elems_exh; try by_subst.\n      { destruct (lock_not_next thread). by_subst. }\n      { edestruct (@release_fence_no_write tr_relf0); by_subst. }\n      destruct (NPeano.Nat.eq_dec pred 0); desc; subst.\n      { trace_app_elems_exh. destruct (lock_not_status thread). by_subst. }\n      { trace_app_elems_exh.\n        { destruct (lock_not_next thread). by_subst. }\n        eapply wait_trace_reads in TRw2; eauto. by_subst. }\n      { edestruct (@acquire_fence_no_write tr_acqf); by_subst. }\n      { edestruct (@release_fence_no_write tr_relf); by_subst. }\n\n      unfold_release. cdes REL1. move TRw1 at bottom. subst.\n      apply trace_app_finite. split; [fin_trace_solver| ]. \n      trace_app_elems_exh.      \n      { destruct (lock_not_next thread). by_subst. }\n      { edestruct (@acquire_fence_no_write tr_acqf0); by_subst. }\n      { destruct (NPeano.Nat.eq_dec succ 0); des; desc; subst.\n        { fin_trace_solver. }\n        { trace_app_elems_exh; [by_subst| | ].\n          { eapply wait_trace_reads in TRw3; by_subst. }\n          destruct (lock_not_status ((valr\n                    (trace_last\n                       match tr_succ_wait with\n                       | trace_fin l' =>\n                           trace_fin\n                             (ThreadEvent thread index3 (Aload lock other)\n                              :: l')\n                       | trace_inf f =>\n                           trace_inf\n                             (trace_prepend\n                                [ThreadEvent thread index3 (Aload lock other)]\n                                f)\n                       end d_)))). by_subst. }\n        { fin_trace_solver. }\n      }\n    Qed. \n\n    Lemma next_write0_thread:\n      (E G ∩₁ is_w ∩₁ Loc_ (nth thread nexts 0) ∩₁ Valw_ 0 \\₁ is_init) ⊆₁ Tid_ thread.\n    Proof.\n      red. intros w W.\n      assert (0 < tid w < n_threads) as TID.\n      { split.\n        { cut (tid w <> 0); [lia| ].\n          red. intros EQ0. eapply wf_tid_init in EQ0; by_subst. }\n        { apply BOUNDED_THREADS. by_subst. }\n      }\n      forward eapply (@HMCS_CLIENT (tid w)); try lia. ins. desc. red in H.\n      destruct (restrict G (tid w)) as [Gt' [TRE']]. desc.\n      assert (trace_elems tr0 w) as TRw.\n      { apply TR_E0, TRE'. by_subst. }\n      red in HMCS. desc. red in ACQ, REL. desc.\n      subst tr0 tr_acq tr_rel. trace_app_elems_exh.\n      2: { edestruct (@acquire_fence_no_write tr_acqf0); by_subst. }\n      2: { edestruct (@release_fence_no_write tr_relf0); by_subst. }\n      2: { unfold_release. cdes REL1. subst.\n           move TRw1 at bottom. trace_app_elems_exh.\n           { forward eapply (@disj_statuses_nexts (tid w) (tid w)); [by_destruct w| ].\n             lia. }\n           { edestruct (@acquire_fence_no_write tr_acqf2); by_subst. }\n           destruct (NPeano.Nat.eq_dec succ0 0); desc; des; subst.\n           { trace_app_elems_exh.\n             forward eapply (@disj_locs thread); [lia| ].\n             ins. desc. destruct H0. by_destruct w. }\n           { trace_app_elems_exh; try by_destruct w.\n             { eapply wait_trace_reads in TRw3; eauto. by_subst. }\n             forward eapply (@disj_statuses_nexts (valr\n                    (trace_last\n                       match tr_succ_wait with\n                       | trace_fin l' =>\n                           trace_fin\n                             (ThreadEvent (tid w) index2 (Aload lock other)\n                              :: l')\n                       | trace_inf f =>\n                           trace_inf\n                             (trace_prepend\n                                [ThreadEvent (tid w) index2 (Aload lock other)]\n                                f)\n                       end d_)) thread); by_destruct w. }\n           { trace_app_elems_exh.\n             forward eapply (@disj_statuses_nexts succ0 thread); by_subst. }\n      }\n      unfold_acquire. desc. subst.\n      move TRw at bottom. trace_app_elems_exh.\n      { forward eapply (@unique_statuses (tid w) thread); [by_destruct w| ].\n        ins. des; by_subst. }\n      { forward eapply (unique_nexts (tid w) thread); by_destruct w. }\n      { edestruct (@release_fence_no_write tr_relf1); by_subst. }\n      { forward eapply (@disj_locs thread); [lia| ].\n        ins. desc. destruct H0. by_destruct w. }\n      { destruct (NPeano.Nat.eq_dec pred 0); desc; subst.\n        { trace_app_elems_exh.\n          forward eapply (@disj_statuses_nexts (tid w) thread); by_destruct w. }\n        { trace_app_elems_exh.\n          { enough (tid w = 0); by_destruct w. }\n          { eapply wait_trace_reads in TRw2; by_subst. }\n        }\n      }\n    Qed.\n\n    Lemma next_writes0:\n      exists! w, (E G ∩₁ is_w ∩₁ Loc_ (nth thread nexts 0) ∩₁ Valw_ 0 \\₁ is_init) w.\n    Proof.\n      cdes ACQ0.\n      remember (ThreadEvent thread (index + 1) (Astore (nth thread nexts 0) 0)) as w.\n      exists w. split.\n      { unfolder. splits; try by_subst. apply tr_acqr_elemsET.\n        subst. trace_elems_solver. }\n      intros w' W'.\n      assert (tid w' = thread) as TID.\n      { rewrite (@next_write0_thread w'); by_subst. }\n      assert (trace_elems tr w') as TRw'.\n      { apply TR_E. by_subst. }\n      subst tr. trace_app_elems_exh.\n      2: { edestruct (@acquire_fence_no_write tr_acqf); by_subst. }\n      2: { edestruct (@release_fence_no_write tr_relf); by_subst. }\n      2: { unfold_release. cdes REL1. subst.\n           move TRw'1 at bottom. trace_app_elems_exh.\n           { forward eapply (@disj_statuses_nexts (tid w') (tid w')); [by_destruct w'| ].\n             lia. }\n           { edestruct (@acquire_fence_no_write tr_acqf0); by_subst. }\n           destruct (NPeano.Nat.eq_dec succ 0); desc; des; subst.\n           { trace_app_elems_exh.\n             forward eapply (@disj_locs (tid w')); [by_subst| ].\n             ins. desc. destruct H0. by_destruct w'. }\n           { trace_app_elems_exh; try by_destruct w'.\n             { eapply wait_trace_reads in TRw'3; eauto. by_subst. }\n             forward eapply (@disj_statuses_nexts (valr\n                     (trace_last\n                        match tr_succ_wait with\n                        | trace_fin l' =>\n                            trace_fin\n                              (ThreadEvent (tid w') index2 (Aload lock other)\n                               :: l')\n                        | trace_inf f =>\n                            trace_inf\n                              (trace_prepend\n                                 [ThreadEvent (tid w') index2\n                                    (Aload lock other)] f)\n                        end d_)) (tid w')); by_destruct w'. }\n           { trace_app_elems_exh.\n             forward eapply (@disj_statuses_nexts succ (tid w')); by_destruct w'. }\n      }\n      unfold_acquire. desc. subst.\n      move TRw' at bottom. trace_app_elems_exh.\n      { forward eapply (@disj_statuses_nexts (tid w') (tid w')); [by_destruct w'| ].\n        lia. }\n      { edestruct (@release_fence_no_write tr_relf0); by_subst. }\n      { forward eapply (@disj_locs (tid w')); [lia| ].\n        ins. desc. destruct H0. by_destruct w'. }\n      { destruct (NPeano.Nat.eq_dec pred 0); desc; subst.\n        { trace_app_elems_exh. forward eapply (@disj_locs (tid w')); [by_destruct w'| ].\n          ins. desc. destruct H1. by_destruct w'. }\n        { trace_app_elems_exh.\n          { forward eapply (@unique_nexts (tid w') pred); [by_destruct w'| ].\n            ins. des; by_destruct w'. }\n          { eapply wait_trace_reads in TRw'2; by_subst. }\n        }\n      }\n    Qed. \n\n    Lemma release_real_fin:\n      trace_finite tr_relr.\n    Proof.\n      cdes REL1. rewrite REL2. apply trace_app_finite. split.\n      { fin_trace_solver. }\n      destruct (NPeano.Nat.eq_dec succ 0); [| red in REL4; by_subst].\n      des; [red in REL4; by_subst| ].\n      rewrite REL4. apply trace_app_finite. split; [| red in REL6; by_subst].\n      red in REL5. desc. rewrite REL5. apply trace_app_finite. split; [by_subst|].\n\n      destruct acquire_real_events as [w_next0 [rmw [Wnext RMW]]].\n      assert ((E G ∩₁ Tid_ thread) rmw) as Ermw.\n      { apply TR_E. subst tr. trace_elems_solver. }\n      remember (ThreadEvent thread index0 (Aload lock other)) as r_lock.\n      forward eapply (@tr_relr_elemsET r_lock) as ETr_lock.\n      { subst. trace_elems_solver. }\n      assert (exists rmw', rf G rmw rmw' /\\ co G rmw rmw') as [rmw' [RFlock COlock]].\n      { apply next_rmw_exists with (r_lock := r_lock); eauto. \n        { by_subst. }\n        eapply set_equiv_exp.\n        { rewrite <- set_inter_minus_r, !set_interA; apply set_equiv_refl. }\n        split; [| by_subst]. subst. trace_elems_solver. }\n\n      assert ((E G ∩₁ Loc_ lock \\₁ is_init) rmw') as ENIrmw'.\n      { apply exploit_rf in RFlock; auto.\n        apply exploit_co in COlock; by_destruct rmw'. }\n      destruct (classic (Valw_ 0 rmw')) as [VAL0 | VAL'].\n      { forward eapply (@lock_writes rmw') as LW'.\n        { apply exploit_rf in RFlock; auto. apply exploit_co in COlock; auto.\n          by_destruct rmw'. }\n        forward eapply (@release_no_wait rmw') as TR_FIN. \n        { apply set_inter_minus_r. do 4 apply set_interA. split; [| by_destruct rmw'].\n          red in LW'. desc. des.\n          { rewrite VAL0 in LW'0. symmetry in LW'0.\n            eapply wf_tid_init in LW'0; by_subst. }\n          apply TR_E. split; [by_subst| ].\n          rewrite <- LW'1. erewrite <- wf_rfv; eauto. by_subst. }\n        (* TODO: here we already have the finiteness of the whole trace *)\n        subst tr. subst.\n        repeat (exploit_trace_app_finite; auto). }\n      \n      assert (exists w_next', (is_w ∩₁ Loc_ (nth thread nexts 0) \\₁ Valw_ 0) w_next' /\\\n                         sb G rmw' w_next') as [w_next' [Wnext' SB]].\n      { apply next_write_of_rmw.\n        unfolder. splits; try by_destruct rmw'.\n        erewrite <- wf_rfv; eauto. by_subst. }\n      \n      assert (mo_max G w_next' \\/ mo_max G w_next0) as MAX.\n      { forward eapply (@fin_w_max G (nth thread nexts 0)) as [wmax [MAX LOC]]; auto.\n        { apply fin_l_writes. }\n        assert ((E G \\₁ is_init) w_next0) as ENIw_next0.\n        { split. \n          2: { unfolder in Wnext. desc. apply tr_acqr_elemsET in Wnext. \n               red. intros. eapply wf_tid_init in H; by_subst. }\n          unfolder in Wnext. desc. apply tr_acqr_elemsET in Wnext. by_subst. }\n        assert ((E G ∩₁ is_w ∩₁ Loc_ (nth thread nexts 0) \\₁ is_init) wmax) as WMAX_.\n        { enough (~ is_init wmax).\n          { red in MAX. by_subst. }\n          red. intros. red in MAX. desc. red in MAX0.\n          apply (MAX0 w_next0). red. splits; try by_subst.\n          apply co_init_l; eauto; by_subst. }\n        \n        destruct (classic (Valw_ 0 wmax)).\n        { right. replace w_next0 with wmax; auto.\n          eapply unique_eq; [apply next_writes0| ..].\n          { by_subst. }\n          { desc.\n            pose proof RMW0 as RMW0_. apply seq_eqv_lr in RMW0_. \n            assert (~ is_init w_next0) as NINITw_next0.\n            { unfolder in Wnext. desc. apply tr_acqr_elemsET in Wnext. \n              red. intros. eapply wf_tid_init in H0; eauto; by_subst. }\n            by_subst. }\n        }\n        { left. replace w_next' with wmax; auto.\n          eapply (@next_write_unique thread); auto. \n          { red in MAX. by_subst. }\n          { apply seq_eqv_lr in SB. by_subst. }        \n        }\n      }\n      des.\n      { contra INF.\n        assert (trace_elems tr_succ_wait ⊆₁ E G) as WAIT_E.\n        { transitivity (trace_elems tr_relr).\n          2: { rewrite tr_relr_elemsET. basic_solver. } \n          subst. do 2 (rewrite trace_elems_app, emiT; [| fin_trace_solver]).\n          rewrite <- trace_app_assoc, trace_elems_app, emiT; [| fin_trace_solver].\n          rewrite trace_elems_app. basic_solver. }\n        forward eapply (wait_latest_read_helper REL8) as [i LATEST]; try by_subst.\n        { unfold tr in TR_WF. apply trace_wf_app_both in TR_WF.\n          2: { apply trace_app_finite. split; [apply acquire_real_fin | fin_trace_solver]. }\n          subst. cdes TR_WF. repeat exploit_trace_app_finite.\n          rewrite <- !trace_app_assoc in TR_WF1. \n          repeat (match goal with\n                  | H: trace_wf (trace_app ?t1 ?t2) |- _ =>\n                    apply trace_wf_app_both in H; [| fin_trace_solver]; desc; try by auto\n                  end).\n          by apply trace_wf_app in TR_WF5. }\n        \n        apply INF. eapply wait_fin_iff_cond; eauto.\n        assert (NOmega.lt_nat_l i (trace_length tr_succ_wait)) as DOMi.\n        { destruct tr_succ_wait; [edestruct INF; vauto | by_subst]. }\n        remember (trace_nth i tr_succ_wait d_) as r. exists r.\n        assert (trace_elems tr_succ_wait r) as WAIT_R. \n        { subst r. by apply trace_nth_in. }\n        split; auto. \n        forward eapply (@RFC r) as [w RF]. \n        { split; [basic_solver| ]. \n          eapply wait_trace_reads in WAIT_R; eauto. by_subst. }\n        specialize (LATEST i w). specialize_full LATEST; [lia| ..].\n        { erewrite trace_nth_indep; by_subst. }\n        replace (valr r) with (valw w) by (apply exploit_rf in RF; by_subst).\n        rewrite (@mo_max_unique_helper w w_next'); try by_subst.\n        apply wait_trace_reads in REL8. specialize (REL8 r). specialize_full REL8.\n        { subst r. by apply trace_nth_in. }\n        apply exploit_rf in RF; by_subst. }\n      \n      forward eapply (@mo_max_co w_next0 w_next') as CO; try by_subst.\n      { apply seq_eqv_lr in SB. unfolder. splits; by_subst. }\n      red in CO. des; [by_subst| ].\n      destruct no_cycle. exists rmw'. do 3 (eexists; split; eauto).\n      exists rmw. split; [apply rt_refl| auto]. \n    Qed.\n    \n    Lemma thread_trace_finite:\n      trace_finite tr. \n    Proof.\n      destruct acquire_real_fin, release_real_fin.\n      subst tr. fin_trace_solver. \n    Qed.\n      \n  End InsideThread. \n\n  \n\n  Lemma hmcs_acqiure_release_terminates_induction thread\n        (IND: forall thread' (ORD: lock_order thread' thread),\n            set_finite (E G ∩₁ Tid_ thread' \\₁ is_init)):\n    set_finite (E G ∩₁ Tid_ thread \\₁ is_init).\n  Proof.\n    destruct (PeanoNat.Nat.eq_0_gt_0_cases thread) as [| NINIT].\n    { subst. rewrite tid0_init. exists []. basic_solver. }\n    destruct (PeanoNat.Nat.le_gt_cases n_threads thread) as [| LT].\n    { rewrite no_excessive_events; auto. exists []. basic_solver. }\n    cdes HMCS_CLIENT. specialize (HMCS_CLIENT0 thread). \n    specialize_full HMCS_CLIENT0; eauto; [lia| ]. desc.\n    \n    red in HMCS_CLIENT0. destruct (restrict G thread) as [Gt [TRE]]. desc.\n    unfold hmcs_acqiure_release, hmcs_acquire, hmcs_release in HMCS. desc. \n    arewrite (E G ∩₁ Tid_ thread \\₁ is_init ⊆₁ E G ∩₁ Tid_ thread) by basic_solver.\n    rewrite <- TRE, <- TR_E.\n\n    apply nodup_trace_elems; [by apply trace_wf_nodup| ].\n    subst. eapply thread_trace_finite; eauto.\n    { etransitivity; eauto. }\n    \n    ins. specialize (IND _ ORD).\n    rewrite set_union_minus_alt with (s' := is_init).\n    rewrite set_interA. arewrite (Tid_ thread' ∩₁ is_init ⊆₁ ∅).\n    2: { by rewrite set_inter_empty_r, set_union_empty_l. }\n    red. ins.\n    apply lock_order_dom, seq_eqv_lr in ORD. desc. red in ORD. desc. \n    apply ORD2. replace thread' with (tid x) by by_subst.\n    symmetry. eapply wf_tid_init; eauto; [| by_subst].\n    apply wf_initE; by_subst.\n  Qed.\n  \n  Lemma hmcs_acqiure_release_terminates thread:\n    set_finite (E G ∩₁ Tid_ thread \\₁ is_init). \n  Proof.    \n    pattern thread.\n    eapply well_founded_ind;\n      [apply lock_order_wf | apply hmcs_acqiure_release_terminates_induction].\n  Qed.\n    \n  Theorem hmcs_client_terminates_impl:\n    set_finite (E G \\₁ is_init).\n  Proof.\n    rewrite set_minusE. apply events_separation_inter.\n    ins. rewrite <- set_minusE. apply hmcs_acqiure_release_terminates. \n  Qed.\n  \nEnd HMCSClientTermination.\n\n\nTheorem hmcs_client_terminates\n        (n_threads : nat)\n        (lock : Loc)\n        (statuses nexts : list Loc)\n        (DISJ_LOC : NoDup (lock :: statuses ++ nexts))\n        (STATUSES_LEN : length statuses = n_threads)\n        (NEXTS_LEN : length nexts = n_threads)\n        (LOCS_NO0 : ~ In 0 (lock :: statuses ++ nexts))\n        (G : execution)\n        (HMCS_CLIENT : hmcs_client n_threads lock statuses nexts G)\n        (FAIR : mem_fair G)\n        (SCpL : Execution.SCpL G)\n        (WF : Wf G)\n        (RFC : rf_complete G)\n        (BOUNDED_THREADS : (fun thread : nat =>\n                     exists e : Event, (E G ∩₁ Tid_ thread) e)\n                    ≡₁ (fun thread : nat => thread < n_threads))\n        (MODEL : sc_consistent G \\/ TSO_consistent G \\/ ra_consistent G)\n  :\n  set_finite (E G \\₁ is_init). \nProof. eapply hmcs_client_terminates_impl; eauto. Qed.\n\nRedirect \"axioms_hmcs\" Print Assumptions hmcs_client_terminates.\n", "meta": {"author": "weakmemory", "repo": "fairness", "sha": "537609d3c23490a82f11f13125d1f0ce4ce3fef8", "save_path": "github-repos/coq/weakmemory-fairness", "path": "github-repos/coq/weakmemory-fairness/fairness-537609d3c23490a82f11f13125d1f0ce4ce3fef8/src/termination/HMCSTermination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.2173351794053017}}
{"text": "\nRequire Import List.\nFrom mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq tuple ssrfun.\nFrom mathcomp Require Import choice path bigop fintype.\nRequire Import Lib.Base Ipdl.Exp Ipdl.Core String Ipdl.Lems Lib.TupleLems Ipdl.Tacs Lib.Dist Pars Big Lib.Set Lib.OrdLems.\nRequire Import CFold CoinFlip.\n\nDefinition widen_ordS {n} (i : 'I_n) : 'I_(n.+1) := widen_ord (leqnSn n) i.\n\n(* The simulator should work as follows:\n   \n   0. get leak from ideal world\n\n   1. sends \"committed\" from everyone to Adv \n   2. once Adv commits message, generate random bits for all honest PIDs, except first honest which is equal to all commits xor leak\n   3. Open all to adv\n   4. Waits for open from adv, then sends ok to environment\n*)\n\nLemma pars_inline_from_big_shift_index {chan : Type -> Type} {t t'} {n1 n2} (b : chan t') (f : 'I_n1 -> 'I_n2)  (c : n2.-tuple (chan t)) (p : pred 'I_n1) (k : t -> rxn t') (r : 'I_n1 -> rxn t) (i : 'I_n1) rs :\n  isDet _ (r i) ->\n  p i ->\n  pars [::\n          Out b (x <-- Read (tnth c (f i)) ;; k x),\n          \\||_(j < n1 | p j) Out (tnth c (f j)) (r j) & rs] =p\n  pars [::\n          Out b (x <-- r i ;; k x),\n          \\||_(j < n1 | p j) Out (tnth c (f j)) (r j) & rs]. \n  intros.\n  focus_tac 1.\n  rewrite (bigpar_D1_ord i).\n  done.\n  done.\n  rewrite SeqOps.insert_0.\n  swap_tac 0 1.\n  rewrite SeqOps.insert_0.\n  rewrite par_in_pars; simpl.\n  swap_tac 0 2; rewrite SeqOps.insert_0.\n  swap_tac 1 2; rewrite SeqOps.insert_0.\n  rewrite pars_inline.\n  symmetry.\n  focus_tac 1.\n  rewrite (bigpar_D1_ord i).\n  done.\n  done.\n  rewrite SeqOps.insert_0.\n  swap_tac 0 1.\n  rewrite SeqOps.insert_0.\n  rewrite par_in_pars; simpl.\n  swap_tac 0 2; rewrite SeqOps.insert_0.\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 1; rewrite SeqOps.insert_0.\n  apply pars_cons_cong; rewrite //=.\n  done.\nQed.\n\n\n   Lemma SimComp_simpl5E_subproof {chan : Type -> Type} (k : nat) {n}\n         (commit : (n.+1).-tuple (chan k.-bv))\n         (sum_commits : (n.+1).-tuple (chan k.-bv))\n         (committed : (n.+2).-tuple (chan unit))\n         (sum_committed : (n.+2).-tuple (chan unit))\n         (r : rxn k.-bv)\n         (c : chan k.-bv) i :\n     pars [::\n             \\||_(i < n.+1) Out (tnth committed (widen_ordS i)) (_ <-- Read (tnth commit i) ;; Ret tt);\n             Out (tnth committed ord_max) (Ret tt);\n          @cfold chan _ k.-bv k.-bv commit xort id sum_commits;\n          read_all committed sum_committed;\n          Out c (_ <-- Read (tnth sum_committed ord_max) ;;\n                 _ <-- Read (tnth sum_commits i) ;; r)]\n     =p     \n     pars [::\n             \\||_(i < n.+1) Out (tnth committed (widen_ordS i)) (_ <-- Read (tnth commit i) ;; Ret tt);\n             Out (tnth committed ord_max) (Ret tt);\n          @cfold chan _ k.-bv k.-bv commit xort id sum_commits;\n          read_all committed sum_committed;\n          Out c (_ <-- Read (tnth sum_committed ord_max) ;;\n                 r)].\n     swap_tac 0 4.\n     swap_at 0 0 1.\n     symmetry; swap_tac 0 4; symmetry.\n\n\n     move: r.\n     induction i using ord_indP; intros.\n     swap_tac 1 2.\n     rewrite pars_inline_from_big.\n     rewrite {1}/cfold_body //=.\n     simp_all.\n     symmetry.\n     swap_tac 1 3.\n     rewrite -pars_undep_cfold_input.\n     instantiate (1 := ord0).\n     swap_tac 1 4.\n     have -> : tnth committed ord0 = tnth committed (widen_ordS ord0).\n        congr (_ _ _).\n        apply/eqP; rewrite eqE //=.\n     rewrite pars_inline_from_big_shift_index //=.\n     simp_all.\n     apply pars_cons_cong; rewrite //=.\n     swap_tac 0 1.\n     apply pars_cons_cong; rewrite //=.\n     swap_tac 0 1.\n     apply pars_cons_cong; rewrite //=.\n     swap_tac 0 1.\n     apply pars_cons_cong; rewrite //=.\n     done.\n     done.\n\n     intros.\n     swap_tac 1 2.\n     rewrite pars_inline_from_big.\n     rewrite {1}/cfold_body //=.\n     simp_at 0.\n     swap_at 0 0 1.\n     have -> : \n        (widen_ord (m:=n.+1) (leqnSn n)\n                            (Ordinal (n:=n) (m:=i)\n                                     (OrdLems.ltSS (lift_subproof (n:=n.+1) 0 i)))) =\n        (widen_ord (leqnSn n) i).\n        apply/eqP; rewrite eqE //=.\n     swap_at 0 1 2.\n     swap_tac 1 2.\n     rewrite IHi; clear IHi.\n\n     symmetry.\n\n     swap_tac 1 3.\n     rewrite -pars_undep_cfold_input.\n     instantiate (1 := (widen_ord (leqnSn n.+1) (lift ord0 i))).\n     swap_tac 1 4.\n     rewrite pars_inline_from_big_shift_index //=.\n     simp_all.\n     apply pars_cons_cong.\n     apply EqCongReact.\n     r_swap 0 1.\n     done.\n     swap_tac 0 2.\n     apply pars_cons_cong; rewrite //=.\n     apply pars_cons_cong; rewrite //=.\n     swap_tac 0 1.\n     apply pars_cons_cong; rewrite //=.\n     done.\n     done.\nQed.\n\n\nLtac print_lhs_size :=\n  match goal with\n  | [ |- EqProt (pars ?rs) _ ] =>\n    let j := eval simpl in (size rs) in idtac j end.\n\nLtac print_rhs_size :=\n  match goal with\n  | [ |- EqProt _ (pars ?rs) ] =>\n    let j := eval simpl in (size rs) in idtac j end.\n\nLemma pars_replace {chan} (r2 : @ipdl chan) r1 rs :\n  pars [:: r1 & rs] =p pars [:: r2 & rs] ->\n  pars [:: r1 & rs] =p pars [:: r2 & rs].\n  done.\nQed.\n\nLemma big_ord_not_maxE {chan : Type -> Type} {n} (f : 'I_(n.+1) -> @ipdl chan) :\n  \\||_(i < n.+1 | i != ord_max) (f i) =p \\||_(i < n) (f (widen_ordS i)).\n  rewrite bigpar_mkcond.\n  rewrite bigpar_ord_recr.\n  rewrite eq_refl //= -eq_0par.\n  apply EqProt_big_r; intros.\n  rewrite eqE //=.\n  have: x < n by destruct x.\n  intro h.\n  rewrite ltn_neqAle in h.\n  move/andP: h; elim; intros.\n  rewrite H1.\n  done.\nQed.\n\n\nSection SimDef.\n  Context {chan : Type -> Type}.\n  Open Scope bool_scope.\n  Context (k : nat) {n_ : nat}.\n  Let n := nosimpl n_.+2. (* we assume at least 2 players *)\n  Context (honest : pred 'I_n).\n  Context (H : honest ord_max).\n  Context (H0 : ~~ honest ord0).\n\n  Context (leak : (chan k.-bv)).\n  Context (ok : chan unit).\n\n  Context (advCommit : n.-tuple (chan k.-bv)).\n  Context (advOpen : n.-tuple (chan unit)).\n\n  Context (advCommitted : n.-tuple (n.-tuple (chan unit))).\n  Context (advOpened : n.-tuple (n.-tuple (chan k.-bv))).\n\n  \n  Definition Sim_CFRealParty_honest \n             (committed : n.-tuple (chan unit)) (opened : n.-tuple (chan k.-bv))\n             (commit : chan k.-bv) (open : chan unit) \n    :=\n      committed_sum <- newvec n @ unit ;; \n      opened_sum <- newvec n @ k.-bv ;; \n      pars [::\n            Out commit (Samp (Unif ));\n            read_all committed committed_sum;\n            Out open (copy (tnth committed_sum ord_max));\n\n            @cfold chan _ k.-bv k.-bv opened xort id opened_sum\n      ].\n\n  Definition Sim_CFRealParty_corr (i : 'I_n)\n             (committed : n.-tuple (chan unit))\n             (opened : n.-tuple (chan k.-bv))\n             (commit : chan k.-bv) (open : chan unit) :=\n    pars [::\n            Out commit (copy (tnth advCommit i));\n            Out open (copy (tnth advOpen i));\n            Outvec (tnth advCommitted i) (fun j => copy (tnth committed j));\n            Outvec (tnth advOpened i) (fun j => copy (tnth opened j))\n    ].\n\n  Definition Sim_CFParty (i : 'I_n)\n             (committed : n.-tuple (chan unit)) (opened : n.-tuple (chan k.-bv))\n             (commit : chan k.-bv) (open : chan unit) :=\n    if honest i then Sim_CFRealParty_honest committed opened commit open \n                else Sim_CFRealParty_corr i committed opened commit open.                        \n\n  Definition Sim_CFParty_last\n             (sum_commits : n.-tuple (chan k.-bv))\n             (committed_sum : n.-tuple (chan unit))\n             (commit : chan k.-bv) (open : chan unit) :=\n    pars [::\n            Out commit (\n                  x <-- Read (tnth sum_commits (inord n_)) ;; \n                  y <-- Read leak ;;\n                  Ret ((x +t y) : k.-bv));\n            Out open (copy (tnth committed_sum ord_max))\n                ].\n\n  Definition Sim :=\n    commit <- newvec n @ k.-bv ;;\n    open <- newvec n @ unit ;;\n    committed <- newvec n @ unit ;;\n    opened <- newvec n @ k.-bv ;;\n    sum_commits <- newvec n @ k.-bv ;;\n    sum_committed <- newvec n @ unit ;;\n    sum_open <- newvec n @ unit ;;\n    sum_opened <- newvec n @ k.-bv ;;\n\n    pars [::\n            \\||_(i < n | i != ord_max) Sim_CFParty i committed opened (tnth commit i) (tnth open i);\n         Sim_CFParty_last\n           sum_commits\n           sum_committed\n           (tnth commit ord_max)\n           (tnth open ord_max);\n\n         @cfold chan _ k.-bv k.-bv commit xort id sum_commits;\n         read_all committed sum_committed;\n         read_all open sum_open;\n         @cfold chan _ k.-bv k.-bv opened xort id sum_opened;\n\n         Out (tnth committed ord_max) (Ret tt);\n         Out (tnth opened ord_max) (x <-- Read (tnth commit ord_max) ;; _ <-- Read (tnth open ord_max) ;; Ret x);\n         \\||_(i < n | i != ord_max) FComm k (tnth commit i) (tnth committed i) (tnth open i) (tnth opened i);\n\n         Out ok (_ <-- Read (tnth sum_commits ord_max) ;;\n                 _ <-- Read (tnth sum_open ord_max) ;;\n                 Ret tt)\n         ].\nEnd SimDef.  \n\nSection SimComp.\n  Context {chan : Type -> Type}.\n  Open Scope bool_scope.\n  Context (k : nat) {n_ : nat}.\n  Let n := nosimpl n_.+2. (* we assume at least 2 players *)\n  Context (honest : pred 'I_n).\n  Context (H : honest ord_max).\n  Context (H0 : ~~ honest ord0).\n\n  Context (advCommit : n.-tuple (chan k.-bv)).\n  Context (advOpen : n.-tuple (chan unit)).\n\n  Context (advCommitted : n.-tuple (n.-tuple (chan unit))).\n  Context (advOpened : n.-tuple (n.-tuple (chan k.-bv))).\n\n  \n  Definition SimComp (out : n.-tuple (chan k.-bv)) :=\n    leakB <- new k.-bv ;;\n    ok <- new unit ;; \n    pars [::\n            Sim k honest leakB ok advCommit advOpen advCommitted advOpened;\n            CFIdeal k _ honest leakB ok out\n                 ].\n \n\n  (* out ->\n         Out ok (_ <-- Read (tnth sum_commits ord_max) ;;\n                 _ <-- Read (tnth sum_open ord_max) ;;\n                 x <- Read send ;;\n                 Ret x)\n  *)\n\n  Definition SimComp_simpl1 (out : n.-tuple (chan k.-bv)) :=\n    leak <- new k.-bv ;;\n    ok <- new unit ;; \n    commit <- newvec n @ k.-bv ;;\n    open <- newvec n @ unit ;;\n    committed <- newvec n @ unit ;;\n    opened <- newvec n @ k.-bv ;;\n    sum_commits <- newvec n @ k.-bv ;;\n    sum_committed <- newvec n @ unit ;;\n    sum_open <- newvec n @ unit ;;\n    sum_opened <- newvec n @ k.-bv ;;\n    r <- new k.-bv ;;\n    send <- new k.-bv ;;\n    \n (pars [:: \\||_(i<n | honest i)\n             Out (tnth out i)\n               (_ <-- Read (tnth sum_commits ord_max);;\n                _ <-- Read (tnth sum_open ord_max);;\n                copy r);\n            Out ok\n              (_ <-- Read (tnth sum_commits ord_max);;\n               _ <-- Read (tnth sum_open ord_max);;\n               Ret tt);\n            Sim_CFParty_last\n              k\n              leak\n              sum_commits\n              sum_committed\n              (tnth commit ord_max)\n              (tnth open ord_max);\n\n         @cfold chan _ k.-bv k.-bv commit xort id sum_commits;\n         read_all committed sum_committed;\n         read_all open sum_open;\n         @cfold chan _ k.-bv k.-bv opened xort id sum_opened;\n\n\n\n         Out (tnth committed ord_max) (Ret tt);\n         Out (tnth opened ord_max) (x <-- Read (tnth commit ord_max) ;; _ <-- Read (tnth open ord_max) ;; Ret x);\n         \\||_(i < n | i != ord_max) FComm k (tnth commit i) (tnth committed i) (tnth open i) (tnth opened i);\n           Out r (Samp (Unif ));\n           Out leak (copy r);\n           Out send (_ <-- Read ok ;; copy r);\n\n            \\||_(i < n | i != ord_max) Sim_CFParty k honest advCommit advOpen advCommitted advOpened i committed opened (tnth commit i) (tnth open i) ] ).\n             \n\n  Lemma SimComp_E1 out : SimComp out =p SimComp_simpl1 out.\n    rewrite /SimComp /SimComp_simpl1.\n    apply EqCongNew => leak.\n    apply EqCongNew => ok.\n    rewrite /SimComp.\n    rewrite /Sim.\n    repeat setoid_rewrite newPars.\n    apply EqCongNew_vec => commit .\n    apply EqCongNew_vec => open .\n    apply EqCongNew_vec => committed .\n    apply EqCongNew_vec => opened .\n    apply EqCongNew_vec => sum_commits .\n    apply EqCongNew_vec => sum_committed .\n    apply EqCongNew_vec => sum_open .\n    apply EqCongNew_vec => sum_opened .\n    rewrite pars_pars.\n    swap_tac 0 (@CFIdeal chan).\n    \n    rewrite newPars.\n    setoid_rewrite pars_pars; simpl. \n    etransitivity.\n    apply EqCongNew => b .\n    rewrite newPars.\n    setoid_rewrite pars_pars at 1; simpl.\n    apply EqRefl.\n    rewrite EqNewExch.\n    \n    apply EqCongNew => r .\n    apply EqCongNew => send .\n    rewrite /CFIdealParty.\n    rewrite -bigpar_mkcond.\n    swap_tac 0 3.\n    swap_tac 1 2.\n    etransitivity.\n    apply pars_big_replace.\n    intros.\n    rewrite pars_inline.\n    simp_all.\n    swap_tac 1 12.\n    rewrite pars_inline.\n    swap_tac 1 12.\n    apply EqRefl.\n    done.\n    done.\n    apply pars_cons_cong.\n    apply EqProt_big_r; intros; apply EqCongReact.\n    simp_rxn.\n    rewrite /copy //=.\n    swap_tac 0 (Out ok).\n    apply pars_cons_cong; rewrite //=.\n    swap_tac 0 2.\n    apply pars_cons_cong; rewrite //=.\n    swap_tac 0 (@cfold chan _ k.-bv k.-bv commit xort).\n    apply pars_cons_cong; rewrite //=.\n    swap_tac 0 2.\n    apply pars_cons_cong; rewrite //=.\n    swap_tac 0 2.\n    apply pars_cons_cong; rewrite //=.\n    swap_tac 0 2.\n    apply pars_cons_cong; rewrite //=.\n    swap_tac 0 2.\n    apply pars_cons_cong; rewrite //=.\n    swap_tac 0 2.\n    apply pars_cons_cong; rewrite //=.\n    swap_tac 0 2.\n    apply pars_cons_cong; rewrite //=.\n    swap_tac 0 1.\n    apply pars_cons_cong; rewrite //=.\n    apply _.\n    apply _.\n    apply _.\n    apply _.\n    apply _.\n    apply _.\n    apply _.\n    apply _.\n Qed.\n\n  Definition SimComp_simpl2 (out : n.-tuple (chan k.-bv)) :=\n    leak <- new k.-bv ;;\n    ok <- new unit ;; \n    commit <- newvec n @ k.-bv ;;\n    open <- newvec n @ unit ;;\n    committed <- newvec n @ unit ;;\n    opened <- newvec n @ k.-bv ;;\n    sum_commits <- newvec n @ k.-bv ;;\n    sum_committed <- newvec n @ unit ;;\n    sum_open <- newvec n @ unit ;;\n    sum_opened <- newvec n @ k.-bv ;;\n    r <- new k.-bv ;;\n    send <- new k.-bv ;;\n    \n (pars [:: \\||_(i<n | honest i)\n             Out (tnth out i)\n               (x <-- Read (tnth sum_commits ord_max);;\n                _ <-- Read (tnth sum_open ord_max);;\n                Ret x);\n            Out ok\n              (_ <-- Read (tnth sum_commits ord_max);;\n               _ <-- Read (tnth sum_open ord_max);;\n               Ret tt);\n            \n            Sim_CFParty_last\n              k\n              leak\n              sum_commits\n              sum_committed\n              (tnth commit ord_max)\n              (tnth open ord_max);\n\n         @cfold chan _ k.-bv k.-bv commit xort id sum_commits;\n         read_all committed sum_committed;\n         read_all open sum_open;\n         @cfold chan _ k.-bv k.-bv opened xort id sum_opened;\n\n         Out (tnth committed ord_max) (Ret tt);\n         Out (tnth opened ord_max) (x <-- Read (tnth commit ord_max) ;; _ <-- Read (tnth open ord_max) ;; Ret x);\n         \\||_(i < n | i != ord_max) FComm k (tnth commit i) (tnth committed i) (tnth open i) (tnth opened i);\n\n           Out r (Samp (Unif ));\n           Out leak (copy r);\n           Out send (_ <-- Read ok ;; copy r);\n\n      \\||_(i < n | i != ord_max) Sim_CFParty k honest advCommit advOpen advCommitted advOpened i committed opened (tnth commit i) (tnth open i) ] ).\n             \n\n  Lemma SimComp_simpl2E out :\n    SimComp_simpl1 out =p SimComp_simpl2 out.\n\n    apply EqCongNew => leak .\n    apply EqCongNew => ok .\n    rewrite /SimComp_simpl1.\n    etransitivity.\n    apply EqCongNew_vec => commit .\n    apply EqCongNew_vec => open .\n    apply EqCongNew_vec => committed .\n    apply EqCongNew_vec => opened .\n    apply EqCongNew_vec => sum_commits .\n    apply EqCongNew_vec => sum_committed .\n    apply EqCongNew_vec => sum_open .\n    apply EqCongNew_vec => sum_opened .\n    apply EqCongNew => r .\n    apply EqCongNew => send .\n    swap_tac 1 (@cfold chan _ k.-bv k.-bv commit).\n    etransitivity.\n    apply pars_big_replace; intros.\n    rewrite pars_inline_from_big //=; last first.\n    rewrite /cfold_body //=.\n    focus_tac 0.\n      apply EqCongReact.\n      simp_rxn.\n      apply EqRxnRefl.\n    swap_tac 0 (@Sim_CFParty_last).\n    rewrite pars_pars //=.\n    swap_tac 0 3.\n    swap_tac 1 3.\n\n    etransitivity.\n    apply pars_big_replace; intros.\n    rewrite pars_inline //=.\n    apply EqRefl.\n\n    simpl.\n    swap_tac 1 (Out leak).\n    etransitivity.\n    apply pars_big_replace; intros.\n    simp_at 0.\n    swap_at 0 0 1.\n    rewrite pars_inline.\n    edit_tac 0.\n    rewrite /copy; simp_rxn.\n    r_swap 1 4.\n    rewrite EqReadSame.\n    apply EqRxnRefl.\n    apply EqRefl.\n    done.\n    simpl.\n    apply EqRefl.\n    symmetry.\n\n    apply EqCongNew_vec => commit .\n    apply EqCongNew_vec => open .\n    apply EqCongNew_vec => committed .\n    apply EqCongNew_vec => opened .\n    apply EqCongNew_vec => sum_commits .\n    apply EqCongNew_vec => sum_committed .\n    apply EqCongNew_vec => sum_open .\n    apply EqCongNew_vec => sum_opened .\n    apply EqCongNew => r .\n    apply EqCongNew => send .\n\n    swap_tac 1 3.\n    etransitivity.\n    apply pars_big_replace; intros.\n    rewrite pars_inline_from_big.\n    rewrite {1}/cfold_body //=.\n    apply EqRefl.\n    done.\n    done.\n    swap_tac 0 2.\n    rewrite pars_pars //=.\n    swap_tac 1 (Out leak).\n    swap_at 0 0 1.\n    rewrite pars_inline //=.\n    swap_tac 0 3.\n    swap_tac 1 3.\n    etransitivity.\n    apply pars_big_replace; intros.\n    simp_at 0.\n    rewrite pars_inline //=.\n    simp_at 0.\n    edit_tac 0.\n    rewrite /copy; simp_rxn.\n    have -> :\n      (tnth sum_commits (inord n_)) =\n      (tnth sum_commits\n        (widen_ord (m:=n_.+2) (leqnSn n_.+1)\n           (Ordinal (n:=n_.+1) (m:=n_) (OrdLems.ltSS (ltnSn n_.+1))))).\n    congr (_ _ _).\n    apply/eqP; rewrite eqE //=.\n    rewrite inordK //=.\n    apply EqBind_r; intro.\n    rewrite !EqReadSame.\n    apply EqBind_r; intro.\n    apply EqBind_r; intro.\n    destruct x1; rewrite //= ?negbK //=.\n    instantiate (1 := fun _ => Ret x).\n    rewrite -xortA xortK xortC xort0 //=.\n\n    simp_at 0.\n    apply EqRefl.\n\n    apply pars_cons_cong; rewrite //=.\n    apply EqProt_big_r; intros; apply EqCongReact.\n    apply EqBind_r; intros.\n\n    have -> :\n      (tnth sum_commits (inord n_)) =\n      (tnth sum_commits\n        (widen_ord (m:=n_.+2) (leqnSn n_.+1)\n           (Ordinal (n:=n_.+1) (m:=n_) (OrdLems.ltSS (ltnSn n_.+1))))).\n    congr (_ _ _).\n    apply/eqP; rewrite eqE //=.\n    rewrite inordK //=.\n    rewrite EqReadSame.\n    apply EqBind_r; intro.\n    done.\n\n    symmetry.\n    swap_tac 0 (Out (tnth commit ord_max)).\n    swap_at 0 0 1.\n    swap_tac 1 (Out leak).\n    rewrite pars_inline.\n    align.\n    done.\n Qed.\n\n\n  (* Eliminate send, leakB and ok channels *)\n\n  Definition SimComp_simpl3 (out : n.-tuple (chan k.-bv)) :=\n    commit <- newvec n @ k.-bv ;;\n    open <- newvec n @ unit ;;\n    committed <- newvec n @ unit ;;\n    opened <- newvec n @ k.-bv ;;\n    sum_commits <- newvec n @ k.-bv ;;\n    sum_committed <- newvec n @ unit ;;\n    sum_open <- newvec n @ unit ;;\n    sum_opened <- newvec n @ k.-bv ;;\n    r <- new k.-bv ;;\n    \n[pars [:: \\||_(i<n | honest i)\n             Out (tnth out i)\n               (x <-- Read (tnth sum_commits ord_max);;\n                _ <-- Read (tnth sum_open ord_max);;\n                Ret x);\n      Out (tnth commit ord_max) (x <-- Read (tnth sum_commits (inord n_)) ;;\n                                 y <-- Read r ;; Ret ((x +t y)));\n      Out (tnth open ord_max) (copy (tnth sum_committed ord_max));\n\n         @cfold chan _ k.-bv k.-bv commit xort id sum_commits;\n         read_all committed sum_committed;\n         read_all open sum_open;\n         @cfold chan _ k.-bv k.-bv opened xort id sum_opened;\n\n         Out (tnth committed ord_max) (Ret tt);\n         Out (tnth opened ord_max) (x <-- Read (tnth commit ord_max) ;; _ <-- Read (tnth open ord_max) ;; Ret x);\n         \\||_(i < n | i != ord_max) FComm k (tnth commit i) (tnth committed i) (tnth open i) (tnth opened i);\n         Out r (Samp (Unif));\n\n      \\||_(i < n | i != ord_max) Sim_CFParty k honest advCommit advOpen advCommitted advOpened i committed opened (tnth commit i) (tnth open i) ] ].\n\n  Lemma SimComp_simpl3E out :\n    SimComp_simpl2 out =p SimComp_simpl3 out.\n    rewrite /SimComp_simpl2.\n\n    etransitivity.\n    rotate_news.\n    rotate_news.\n    apply EqRefl.\n\n    rewrite /SimComp_simpl3.\n\n    apply EqCongNew_vec => commit .\n    apply EqCongNew_vec => open .\n    apply EqCongNew_vec => committed .\n    apply EqCongNew_vec => opened .\n    apply EqCongNew_vec => sum_commits .\n    apply EqCongNew_vec => sum_committed .\n    apply EqCongNew_vec => sum_open .\n    apply EqCongNew_vec => sum_opened .\n    apply EqCongNew => r .\n\n    (* elim c0 *)\n    etransitivity.\n    rewrite EqNewExch.\n    setoid_rewrite EqNewExch at 2.\n    apply EqCongNew; intro.\n    apply EqCongNew; intro.\n    swap_tac 0 12. \n    rewrite new_pars_remove; last first.\n      intros; repeat set_tac.\n    apply EqRefl.\n\n    (* elim c0 *)\n    etransitivity.\n    apply EqCongNew => c.\n    rewrite new_pars_remove //=.\n    apply EqRefl.\n   (* now elim last *)\n   swap_tac 0 9. \n   rewrite /Sim_CFParty_last.\n   swap_tac 0 9.\n   setoid_rewrite pars_pars; simpl.\n   etransitivity.\n   apply EqCongNew => c.\n   swap_at 0 0 1.\n   swap_tac 1 (Out c).\n   apply EqRefl.\n   rewrite pars_fold.\n   align.\n   apply EqCongReact.\n   rewrite /copy; simp_rxn.\n   r_swap 0 1.\n   done.\n Qed.\n\n  (* Rerandomize r *)\n\n  Definition SimComp_simpl4 (out : n.-tuple (chan k.-bv)) :=\n    commit <- newvec n @ k.-bv ;;\n    open <- newvec n @ unit ;;\n    committed <- newvec n @ unit ;;\n    opened <- newvec n @ k.-bv ;;\n    sum_commits <- newvec n @ k.-bv ;;\n    sum_committed <- newvec n @ unit ;;\n    sum_open <- newvec n @ unit ;;\n    sum_opened <- newvec n @ k.-bv ;;\n    r <- new k.-bv ;;\n    \n[pars [:: \\||_(i<n | honest i)\n             Out (tnth out i)\n               (x <-- Read (tnth sum_commits ord_max);;\n                _ <-- Read (tnth sum_open ord_max);;\n                Ret x);\n      Out (tnth commit ord_max) (_ <-- Read (tnth sum_commits (inord n_)) ;;\n                                 x <-- Read r ;; Ret x);\n      Out (tnth open ord_max) (copy (tnth sum_committed ord_max));\n\n         @cfold chan _ k.-bv k.-bv commit xort id sum_commits;\n         read_all committed sum_committed;\n         read_all open sum_open;\n         @cfold chan _ k.-bv k.-bv opened xort id sum_opened;\n\n         Out (tnth committed ord_max) (Ret tt);\n         Out (tnth opened ord_max) (x <-- Read (tnth commit ord_max) ;; _ <-- Read (tnth open ord_max) ;; Ret x);\n         \\||_(i < n | i != ord_max) FComm k (tnth commit i) (tnth committed i) (tnth open i) (tnth opened i);\n        Out r (Samp (Unif));\n\n      \\||_(i < n | i != ord_max) Sim_CFParty k honest advCommit advOpen advCommitted advOpened i committed opened (tnth commit i) (tnth open i) ] ].\n\n  Lemma SimComp_simpl4E out :\n    SimComp_simpl3 out =p SimComp_simpl4 out.\n    apply EqCongNew_vec => commit .\n    apply EqCongNew_vec => open .\n    apply EqCongNew_vec => committed .\n    apply EqCongNew_vec => opened .\n    apply EqCongNew_vec => sum_commits .\n    apply EqCongNew_vec => sum_committed .\n    apply EqCongNew_vec => sum_open .\n    apply EqCongNew_vec => sum_opened .\n    etransitivity.\n    swap_tac 0 10.\n    etransitivity.\n    apply EqCongNew => r .\n    swap_at 1 0 1.\n    apply EqRefl.\n    swap_tac 0 1.\n    rewrite pars_fold.\n    edit_tac 0.\n    r_swap 0 1.\n    apply EqBind_r; intro.\n    instantiate (1 := fun _ => (y <-- Samp (Unif) ;; Ret y)).\n    simpl.\n    rewrite EqBindRet.\n    symmetry.\n    apply EqSampBijection.\n    apply xort_inj_l.\n    apply uniform_Unif.\n    swap_at 0 0 1.\n    rewrite -pars_fold.\n    apply EqRefl.\n    apply EqCongNew => r.\n    swap_at 0 0 1.\n    align.\nQed.\n\n  (* Eliminate last commit *)\n\n  Definition SimComp_simpl5 (out : n.-tuple (chan k.-bv)) :=\n    open <- newvec n @ unit ;;\n    committed <- newvec n @ unit ;;\n    opened <- newvec n @ k.-bv ;;\n    sum_commits_ <- newvec (n_.+1) @ k.-bv ;;\n    sum_commits_last <- new k.-bv;;\n    sum_committed <- newvec n @ unit ;;\n    sum_open <- newvec n @ unit ;;\n    sum_opened <- newvec n @ k.-bv ;;\n    r <- new k.-bv ;;\n    commit <- newvec (n_.+1) @ k.-bv ;;\n    \n[pars [:: \\||_(i<n | honest i)\n             Out (tnth out i)\n               (x <-- Read (tnth [tuple of rcons sum_commits_ sum_commits_last] ord_max);;\n                _ <-- Read (tnth sum_open ord_max);;\n                Ret x);\n      Out r (Samp (Unif ));\n      Out (tnth open ord_max) (copy (tnth sum_committed ord_max));\n\n      @cfold chan _ k.-bv k.-bv commit xort id sum_commits_;\n      Out sum_commits_last (x <-- Read r ;; y <-- Read (tnth sum_commits_ ord_max) ;; Ret ((x +t y)));\n         read_all committed sum_committed;\n         read_all open sum_open;\n         @cfold chan _ k.-bv k.-bv opened xort id sum_opened;\n\n         Out (tnth committed ord_max) (Ret tt);\n         Out (tnth opened ord_max) (x <-- Read r ;; _ <-- Read (tnth open ord_max) ;; Ret x);\n         \\||_(i < (n_.+1)) FComm k (tnth commit i) (tnth committed (widen_ordS i)) (tnth open (widen_ordS  i)) (tnth opened (widen_ordS i));\n\n      \\||_(i < n_.+1) Sim_CFParty k honest advCommit advOpen advCommitted advOpened (widen_ordS i) committed opened (tnth commit i) (tnth open (widen_ordS i)) ] ].\n\n  Lemma SimComp_simpl5E out :\n    SimComp_simpl4 out =p SimComp_simpl5 out.\n    rewrite /SimComp_simpl4.\n    rewrite /SimComp_simpl5.\n    etransitivity.\n    rotate_news.\n    apply EqRefl.\n\n    apply EqCongNew_vec => open .\n    apply EqCongNew_vec => committed .\n    apply EqCongNew_vec => opened .\n    etransitivity.\n    rewrite newvecS_r.\n    apply EqRefl.\n    rewrite -New_newvec.\n    apply EqCongNew_vec => sum_commits.\n    apply EqCongNew => sum_commits_last .\n    apply EqCongNew_vec => sum_committed .\n    apply EqCongNew_vec => sum_open .\n    apply EqCongNew_vec => sum_opened .\n    apply EqCongNew => r .\n    etransitivity.\n    rewrite newvecS_r.\n    done.\n    rewrite -New_newvec.\n    apply EqCongNew_vec => commit .\n\n    etransitivity.\n    (* Now elim y *)\n    etransitivity.\n    apply EqCongNew => commit_last.\n    have -> : tnth [tuple of rcons commit commit_last] ord_max = commit_last.\n        rewrite /tnth nth_rcons size_tuple //= ltnn eq_refl //=.\n    rewrite cfoldS_r.\n    swap_tac 0 3.\n    rewrite pars_pars //=.\n    inline_tac (Out sum_commits_last) (Out commit_last).\n    simp_at 0.\n        edit_tac 0.\n        r_swap 1 2.\n        have -> : (tnth [tuple of rcons sum_commits sum_commits_last] (inord n_))\n                  =\n                  (tnth sum_commits ord_max).\n            rewrite /tnth nth_rcons.\n            rewrite size_tuple inordK ltnS.\n            rewrite leqnn.\n            simpl.\n            apply set_nth_default.\n            rewrite size_tuple.\n            rewrite ltnS leqnn //=.\n            rewrite leqnSn //=.\n        \n        rewrite EqReadSame.\n        r_swap 0 1.\n        done.\n\n   inline_tac (Out (tnth opened ord_max)) (Out commit_last).\n   simp_at 0.\n   apply EqRefl.\n   \n   (* remove commit_last from FComm and Sim_CFParty *)\n   etransitivity.\n   apply EqCongNew => commit_last.\n   focus_tac 10.\n   rewrite big_ord_not_maxE.\n   apply EqProt_big_r; intros.\n   have -> : tnth [tuple of rcons commit commit_last] (widen_ordS x) =\n             tnth commit x.\n       rewrite /tnth nth_rcons //= size_tuple.\n       have -> : x < n_.+1 by destruct x.\n       apply set_nth_default.\n       rewrite size_tuple; destruct x; done.\n   apply EqRefl.\n   focus_tac 12.\n   rewrite big_ord_not_maxE.\n   apply EqProt_big_r; intros.\n   have -> : tnth [tuple of rcons commit commit_last] (widen_ordS x) =\n             tnth commit x.\n       rewrite /tnth nth_rcons //= size_tuple.\n       have -> : x < n_.+1 by destruct x.\n       apply set_nth_default.\n       rewrite size_tuple; by destruct x.\n   apply EqRefl.\n\n   apply EqRefl.\n   swap_tac 0 1.\n   rewrite new_pars_remove.\n   apply EqRefl.\n\n   (* now the LHS and RHS are the same, except that opened ord_max has a dependency on this sum_commits stuff -- so now we remove it *)\n   etransitivity.\n   apply (pars_replace\n            (Out (tnth opened ord_max) (\n                   x <-- Read r ;; _ <-- Read (tnth open ord_max) ;; Ret x))).\n   have -> : tnth [tuple of rcons sum_commits sum_commits_last] (inord n_) =\n             tnth sum_commits ord_max.\n      rewrite /tnth nth_rcons //=.\n      rewrite size_tuple inordK //=.\n      rewrite ltnSn.\n      apply set_nth_default.\n      rewrite size_tuple ltnSn //=.\n\n    etransitivity.\n    edit_tac 0.\n    r_swap 0 2.\n    done.\n   inline_tac (Out (tnth opened ord_max)) (Out (tnth open ord_max)).\n   rewrite /copy.\n   simp_at 0.\n\n   symmetry.\n    etransitivity.\n    edit_tac 0.\n    r_swap 0 1.\n    done.\n\n   inline_tac (Out (tnth opened ord_max)) (Out (tnth open ord_max)).\n   rewrite /copy.\n   etransitivity.\n   edit_tac 0.\n     simp_rxn.\n     apply EqRxnRefl.\n   apply EqRefl.\n   symmetry.\n   swap_tac 1 2.\n   swap_tac 2 4.\n   swap_tac 3 9.\n   swap_tac 4 7.\n   rewrite (pars_split 5); simpl.\n\n   symmetry.\n   swap_tac 1 2.\n   swap_tac 2 4.\n   swap_tac 3 9.\n   swap_tac 4 7.\n   rewrite (pars_split 5); simpl.\n   symmetry.\n\n   apply EqCong.\n   rewrite big_pars2.\n   swap_tac 0 3; rewrite pars_pars //=; swap_tac 0 1.\n   symmetry; swap_tac 0 3; rewrite pars_pars //=; swap_tac 0 1; symmetry.\n   apply pars_cons_cong; rewrite //=.\n   swap_tac 1 4.\n   swap_tac 2 4.\n   swap_tac 3 4.\n   rewrite SimComp_simpl5E_subproof.\n   align.\n\n   align.\n\n   swap_tac 0 3.\n   apply pars_cons_cong; rewrite //=.\n   swap_tac 0 (Out r).\n   apply pars_cons_cong; rewrite //=.\n   align.\n   apply EqCongReact.\n   apply EqBind_r; intro.\n   apply EqBind_r; intro.\n   rewrite xortC //=.\nQed.\n\n\n(* 1. Collapse r into commit\n   2. re-fold sum_commits and sum_commits_last, given 1.\n   3. depend last committed on last commit, fold last committed, opened into FComm\n *)\n\n\n  Definition SimComp_simpl6 (out : n.-tuple (chan k.-bv)) :=\n    open <- newvec n @ unit ;;\n    committed <- newvec n @ unit ;;\n    opened <- newvec n @ k.-bv ;;\n    sum_commits <- newvec n @ k.-bv ;;\n    sum_committed <- newvec n @ unit ;;\n    sum_open <- newvec n @ unit ;;\n    sum_opened <- newvec n @ k.-bv ;;\n    commit <- newvec n @ k.-bv ;;\n    \n[pars [:: \\||_(i<n | honest i)\n             Out (tnth out i)\n               (x <-- Read (tnth sum_commits ord_max);;\n                _ <-- Read (tnth sum_open ord_max);;\n                Ret x);\n      Out (tnth commit ord_max) (Samp (Unif ));\n      Out (tnth open ord_max) (copy (tnth sum_committed ord_max));\n\n      @cfold chan _ k.-bv k.-bv commit xort id sum_commits;\n         read_all committed sum_committed;\n         read_all open sum_open;\n         @cfold chan _ k.-bv k.-bv opened xort id sum_opened;\n\n         \\||_(i < n) FComm k (tnth commit i) (tnth committed i) (tnth open i) (tnth opened i);\n\n      \\||_(i < n | i != ord_max) Sim_CFParty k honest advCommit advOpen advCommitted advOpened i committed opened (tnth commit i) (tnth open i) ] ].\n\nLemma SimComp_simpl6E out :\n    SimComp_simpl5 out =p SimComp_simpl6 out.\n  rewrite /SimComp_simpl5.\n  rewrite /SimComp_simpl6.\n  symmetry.\n\n  apply EqCongNew_vec => open .\n  apply EqCongNew_vec => committed .\n  apply EqCongNew_vec => opened .\n\n  etransitivity.\n  rewrite newvecS_r.\n  apply EqRefl.\n  rewrite New_newvec.\n  apply EqCongNew => sum_commits_last .\n  apply EqCongNew_vec => sum_commits .\n  apply EqCongNew_vec => sum_committed .\n  apply EqCongNew_vec => sum_open .\n  apply EqCongNew_vec => sum_opened .\n  etransitivity.\n    rewrite newvecS_r.\n  apply EqRefl.\n  apply EqCongNew => last_commit .\n  apply EqCongNew_vec => commit .\n  symmetry.\n\n  swap_tac 0 (Out (tnth committed ord_max)).\n  rewrite pars_mkdep //=.\n  symmetry.\n  swap_tac 0 7.\n  rewrite bigpar_ord_recr par_in_pars.\n  rewrite pars_pars //=.\n\n  (* just matching things up now *)\n  apply pars_cons_cong.\n    rewrite tnth_rcons_ord_max; done.\n  swap_tac 0 2.\n  apply pars_cons_cong.\n    rewrite tnth_rcons_ord_max; done.\n  swap_tac 0 (Out (tnth open ord_max)).\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 2.\n  rewrite cfoldS_r pars_pars //=.\n  apply pars_cons_cong; rewrite //=.\n  apply pars_cons_cong; rewrite //=.\n  apply EqCongReact; apply EqBind_r; intro; apply EqBind_r; intro; rewrite xortC //=.\n  swap_tac 0 2.\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 2.\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 2.\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 2.\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 1.\n  apply pars_cons_cong; rewrite //=.\n  rewrite /copy.\n  apply EqCongReact.\n  rewrite tnth_rcons_ord_max.\n  r_swap 0 1.\n  done.\n  apply pars_cons_cong; rewrite //=.\n  apply EqProt_big_r; intros.\n  rewrite tnth_rcons_widen_ord //=.\n  apply pars_cons_cong; rewrite //=.\n  rewrite big_ord_not_maxE.\n  apply EqProt_big_r; intros.\n  rewrite tnth_rcons_widen_ord //.\nQed.\n\n(* Restore last party to be like others *)\n\n  Definition SimComp_simpl7 (out : n.-tuple (chan k.-bv)) :=\n    open <- newvec n @ unit ;;\n    committed <- newvec n @ unit ;;\n    opened <- newvec n @ k.-bv ;;\n    sum_commits <- newvec n @ k.-bv ;;\n    sum_open <- newvec n @ unit ;;\n    commit <- newvec n @ k.-bv ;;\n    \n[pars [:: \\||_(i<n | honest i)\n             Out (tnth out i)\n               (x <-- Read (tnth sum_commits ord_max);;\n                _ <-- Read (tnth sum_open ord_max);;\n                Ret x);\n\n      @cfold chan _ k.-bv k.-bv commit xort id sum_commits;\n         read_all open sum_open;\n\n         \\||_(i < n) FComm k (tnth commit i) (tnth committed i) (tnth open i) (tnth opened i);\n\n      \\||_(i < n) Sim_CFParty k honest advCommit advOpen advCommitted advOpened i committed opened (tnth commit i) (tnth open i) ] ].\n\n  Lemma SimComp_simpl7E out :\n    SimComp_simpl6 out =p SimComp_simpl7 out.\n    rewrite /SimComp_simpl6.\n    rewrite /SimComp_simpl7.\n    apply EqCongNew_vec => open .\n    apply EqCongNew_vec => committed .\n    apply EqCongNew_vec => opened .\n    apply EqCongNew_vec => sum_commits .\n    rotate_news.\n    apply EqCongNew_vec => sum_open .\n    rotate_news.\n    apply EqCongNew_vec => commit .\n    symmetry.\n    etransitivity.\n    swap_tac 0 4.\n    rewrite (bigpar_D1_ord ord_max).\n    rewrite par_in_pars.\n    rewrite /Sim_CFParty H.\n    rewrite newPars.\n    setoid_rewrite newPars.\n    setoid_rewrite pars_pars.\n    apply EqRefl.\n    apply _.\n    done.\n    apply EqCongNew_vec => sum_committed .\n    apply EqCongNew_vec => sum_opened .\n    simpl.\n    align.\n Qed.\nEnd SimComp.\n", "meta": {"author": "ipdl", "repo": "ipdl", "sha": "d41b022c9a216acfefaefcbd0ede9e52e350ab8a", "save_path": "github-repos/coq/ipdl-ipdl", "path": "github-repos/coq/ipdl-ipdl/ipdl-d41b022c9a216acfefaefcbd0ede9e52e350ab8a/theories/protocols/CoinFlip/Proof/CFSimComp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.21733517671825026}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\nRequire Import Crypto.AbstractInterpretation.AbstractInterpretation.\nRequire Import Crypto.Bedrock.Field.Common.Types.\nRequire Import Crypto.Language.API.\nRequire Import Crypto.Util.Option.\n\nImport Language.API.Compilers AbstractInterpretation.Compilers.\nImport Types.Notations.\nExisting Instances rep.Z rep.listZ_mem.\n\nSection with_parameters.\n  Context \n    {width BW word mem locals env ext_spec varname_gen error}\n   `{parameters_sentinel : @parameters width BW word mem locals env ext_spec varname_gen error}.\n\n  Fixpoint list_lengths_repeat_base (n : nat) t : base_listonly nat t :=\n    match t as t0 return base_listonly nat t0 with\n    | base.type.prod a b =>\n      (list_lengths_repeat_base n a, list_lengths_repeat_base n b)\n    | base_listZ => n\n    | _ => tt\n    end.\n  Fixpoint list_lengths_repeat_args (n : nat) t\n    : type.for_each_lhs_of_arrow list_lengths t :=\n    match t as t0 return type.for_each_lhs_of_arrow list_lengths t0 with\n    | type.base b => tt\n    | type.arrow (type.base s) d =>\n      (list_lengths_repeat_base n s, list_lengths_repeat_args n d)\n    | type.arrow s d => (tt, list_lengths_repeat_args n d)\n    end.\n\n  (* mostly a duplicate of list_lengths_from_value, just with ZRange interp *)\n  Fixpoint list_lengths_from_bounds {t}\n    : ZRange.type.base.option.interp t -> option (base_listonly nat t) :=\n    match t as t0 return\n          ZRange.type.base.option.interp t0 -> option (base_listonly nat t0) with\n    | base.type.prod a b =>\n      fun x =>\n        (x1 <- list_lengths_from_bounds (fst x);\n           x2 <- list_lengths_from_bounds (snd x);\n           Some (x1, x2))%option\n    | base_listZ =>\n      fun x : option (list _) => option_map (@List.length _) x\n    | _ => fun _ => Some tt\n    end.\n  Fixpoint list_lengths_from_argbounds {t}\n    : type.for_each_lhs_of_arrow ZRange.type.option.interp t ->\n      option (type.for_each_lhs_of_arrow list_lengths t) :=\n    match t as t0 return\n          type.for_each_lhs_of_arrow _ t0 ->\n          option (type.for_each_lhs_of_arrow _ t0) with\n    | type.base b => fun _ => Some tt\n    | type.arrow (type.base a) b =>\n      fun x =>\n        (x1 <- list_lengths_from_bounds (fst x);\n           x2 <- list_lengths_from_argbounds (snd x);\n           Some (x1, x2))%option\n    | type.arrow a b => fun _ => None\n    end.\nEnd with_parameters.\n", "meta": {"author": "Veridise", "repo": "Coda", "sha": "d22d56c09ac541f012adae34820850ce6cd10270", "save_path": "github-repos/coq/Veridise-Coda", "path": "github-repos/coq/Veridise-Coda/Coda-d22d56c09ac541f012adae34820850ce6cd10270/BigInt/fiat-crypto/src/Bedrock/Field/Common/Arrays/MakeListLengths.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.21733516318344398}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import Init_ext ssrZ ZArith_ext seq_ext uniq_tac.\nRequire Import machine_int multi_int encode_decode integral_type.\nImport MachineInt.\nRequire Import mips_bipl mips_tactics mips_syntax.\nImport mips_bipl.expr_m.\nRequire Import simu.\nImport simu.simu_m.\nRequire Import multi_is_even_u_prg multi_is_even_u_triple.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope assoc_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope asm_cmd_scope.\nLocal Open Scope asm_expr_scope.\nLocal Open Scope zarith_ext_scope.\n\nLemma var_mint_multi_is_even u rk ru s st h a0 :\n  uniq(rk, ru, a0, r0) ->\n  var_mint u (unsign rk ru) s st (heap_mint (unsign rk ru) st h) ->\n  forall st' h',\n    Some (st, h) -- multi_is_even_u rk ru a0 ---> Some (st', h')->\n  (([var_e u \\% nat_e 2 \\= nat_e 1 ]b_ s)%pseudo_expr <-> [ beq a0 r0 ]b_ st').\nProof.\nmove=> Hset u_ru st' h' exec_asm.\ncase: u_ru => u_ru u_ru' u_ru''.\n  move: (multi_is_even_u_triple _ _ _ Hset '|u2Z ([rk ]_ st)| (Z2ints 32 '|u2Z ([rk ]_ st)| ([u ]_ s)%pseudo_expr) ([ru]_st)).\n  rewrite size_Z2ints.\n  move/(_ refl_equal) => hoare_triple.\n  move/mips_seplog.hoare_prop_m.soundness : (hoare_triple).\n  rewrite /while.hoare_semantics.\n  move/(_ st (heap_mint (unsign rk ru) st h)).\n  rewrite Z_of_nat_Zabs_nat; last exact: min_u2Z.\n  move/( _ (conj (refl_equal _) (conj (refl_equal _) u_ru''))).\n  case=> _.\n  have exec_asm':\n    ((Some (st, heap_mint (unsign rk ru) st h)) -- multi_is_even_u rk ru a0 ---> Some (st', heap_mint (unsign rk ru) st h')).\n    rewrite /heap_mint /heap_cut.\n    eapply mips_syntax.triple_exec_proj; last exact: exec_asm.\n    apply hoare_triple.\n    rewrite /= Z_of_nat_Zabs_nat //; exact: min_u2Z.\n  case/(_ _ _ exec_asm') => Hrk [Hru [Hmem [Heven Hodd]]].\nsplit.\n- rewrite /= /ZIT.eqb /ZIT.rem => /eqP X.\n  rewrite store.get_r0 Z2uK //.\n  apply/eqP.\n  rewrite Hodd //; last first.\n    rewrite lSum_Z2ints_pos //.\n    apply not_Zmod_2_Zodd; by rewrite X.\n  by rewrite Z2uK.\n- rewrite /= /ZIT.eqb /ZIT.rem => /eqP X.\n  rewrite store.get_r0 Z2uK // in X.\n  apply/eqP.\n  rewrite lSum_Z2ints_pos // in Heven.\n  rewrite lSum_Z2ints_pos // in Hodd.\n  case: (Zeven_odd_dec ([u]_s)%pseudo_expr).\n    move/Heven => abs.\n    by rewrite abs Z2uK in X.\n  by apply Zodd_Zmod_2.\nQed.\n\nLemma fwd_sim_b_multi_is_even_u u rk ru d a0 : uniq(rk, ru, a0, r0) ->\n  disj (mints_regs (assoc.cdom d)) (a0 :: nil) ->\n  u \\notin assoc.dom d ->\n  unsign rk ru \\notin assoc.cdom d ->\n  fwd_sim_b (state_mint (u |=> unsign rk ru \\U+ d ))\n  (var_e u \\% nat_e 2 \\= nat_e 1)%pseudo_expr\n  (multi_is_even_u rk ru a0)\n  (beq a0 r0).\nProof.\nmove=> Hregs d_a0 u_d rk_ru_d.\nrewrite /fwd_sim_b => s st h s_st_h.\nset nk := '|u2Z [rk]_st|.\nset U := Z2ints 32 nk ([ u ]_ s)%pseudo_expr.\nhave Hpre : (var_e ru |--> U)%asm_assert st (heap_mint (unsign rk ru) st h).\n  move: (proj1 s_st_h u (unsign rk ru)).\n  rewrite assoc.get_union_sing_eq. case/(_ refl_equal) => _ [_]; exact.\nmove: (multi_is_even_u_triple _ _ _ Hregs nk U [ru]_st).\nrewrite /U size_Z2ints.\nmove/(_ (refl_equal _)) => Htriple.\nset code := multi_is_even_u _ _ _.\nhave [st' Hst'] : exists st', Some (st, h) -- code ---> Some (st', h).\n  have [[st' he'] Hst'] : exists st', Some (st, h) -- code ---> Some st'.\n    apply constructive_indefinite_description'.\n    eapply mips_seplog.hoare_prop_m.termi.\n    - apply mips_frame.frame_rule_R with (R := assert_m.TT).\n      + exact: Htriple.\n      + by Inde.\n      + move=> ?; by Inde_mult.\n    - move=> s0 h0 /= H.\n      apply Epsilon.constructive_indefinite_description.\n      by apply mips_syntax.no_while_terminate.\n    - exists (heap_mint (unsign rk ru) st h).\n      exists (h \\D\\ iota '|u2Z ([ru ]_ st) / 4| nk).\n      split.\n        rewrite /= /heap_cut.\n        by apply heap.proj_difs_disj, inc_refl.\n      split.\n        rewrite /= /heap_cut; by apply heap.proj_difs.\n      split; last by [].\n      split; first by rewrite /nk Z_of_nat_Zabs_nat //; apply min_u2Z.\n      split; first by reflexivity.\n      exact Hpre.\n  exists st'.\n  suff : h = he' by move=> X; rewrite -X in Hst'.\n  by apply (mips_syntax.no_sw_heap_invariant _ _ _ Hst' refl_equal _ _ _ _ refl_equal refl_equal).\nexists st'; split; first by exact Hst'.\nmove/mips_seplog.soundness : (Htriple).\nrewrite /while.hoare_semantics.\nmove/(_ st (heap_mint (unsign rk ru) st h)).\nrewrite {1}/nk Z_of_nat_Zabs_nat; last by apply min_u2Z.\ncase/(_ (conj (refl_equal _) (conj (refl_equal _) Hpre))) => _ Hpost.\nmove: {Htriple}(triple_exec_proj _ _ _ Htriple) => Hexec_proj.\nrewrite {1}/nk Z_of_nat_Zabs_nat in Hexec_proj; last by apply min_u2Z.\nrewrite /heap_mint /heap_cut in Hpre.\nmove: {Hexec_proj Hpre}(Hexec_proj _ _ _ _ _ (conj refl_equal (conj refl_equal Hpre)) Hst').\nmove/Hpost => {}Hpost.\ncase: Hpost => Hrk' [Hru' [Hmem Hret]].\nrewrite lSum_Z2ints_pos in Hret; last first.\n  move: (proj1 s_st_h u (unsign rk ru)).\n  rewrite assoc.get_union_sing_eq.\n  move/(_ refl_equal).\n  rewrite /var_mint.\n  by case=> ? [].\nsplit=> [u_mod_2|].\n+ apply/eqP.\n  congr (Z<=u _).\n  rewrite store.get_r0.\n  apply (proj2 Hret).\n  rewrite /= in u_mod_2.\n  apply not_Zmod_2_Zodd.\n  move/eqP : u_mod_2; by rewrite /ZIT.rem => ->.\n+ move => u_mod_2.\n  apply/eqP => /=.\n  move/eqP : u_mod_2.\n  rewrite store.get_r0 Z2uK // => Ha0.\n  case: (Zeven_odd_dec ([u ]_ s)%pseudo_expr) => Hu.\n  by rewrite (proj1 Hret Hu) Z2uK in Ha0.\n  by apply Zodd_Zmod_2.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/begcd/multi_is_even_u_simu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.21726549670545522}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\nRequire Import omega.Omega.\nRequire Import Setoid.\nRequire Import ZArith.\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith. \nLocal Open Scope struct_scope.\nRequire Import FinProof.CommonProofs.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolClass.\nRequire Import depoolContract.SolidityNotations.\nRequire Import depoolContract.DePoolFunc.\nRequire Import depoolContract.DePoolConsts.\n\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\nImport DePoolSpec.LedgerClass.SolidityNotations. \nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope solidity_scope.\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\nSet Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100.\n\nModule ScenarioCommon  (dc : DePoolConstsTypesSig XTypesSig StateMonadSig).\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig dc.\nImport dc.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\n\n\n\nRecord NetParams := NetParamsC {\n    NetParams_ι_validatorsElectedFor : Z ;\n    NetParams_ι_electionsStartBefore : Z ;\n    NetParams_ι_electionsEndBefore : Z ;\n    NetParams_ι_stakeHeldFor : Z ;\n\nNetParams_ι_curValidatorData :  TvmCell;\n    NetParams_ι_unknown34 : Z ; \n    NetParams_ι_utime_since : Z ;\n    NetParams_ι_utime_until : Z ;\n    NetParams_ι_prevValidatorData : TvmCell ;\n\nNetParams_ι_rawConfigParam_17 : TvmCell ;\n    NetParams_ι_unknown17_1 : Z ; \n    NetParams_ι_unknown17_2 : Z ; \n    NetParams_ι_unknown17_3 : Z ; \n    NetParams_ι_maxStakeFactor : Z;\n\nNetParams_ι_rawConfigParam_1 : TvmCell ;\n    NetParams_ι_electorRawAddress: Z ;\n\n}.\n\nDefinition withNetParams (l : Ledger) (p : NetParams):= \n    {$ l With     (VMState_ι_validatorsElectedFor , NetParams_ι_validatorsElectedFor  p) ;\n                  (VMState_ι_electionsStartBefore, NetParams_ι_electionsStartBefore p) ;\n                  (VMState_ι_electionsEndBefore, NetParams_ι_electionsEndBefore p) ;\n                  (VMState_ι_stakeHeldFor, NetParams_ι_stakeHeldFor p) ;\n\n                  (VMState_ι_curValidatorData, NetParams_ι_curValidatorData p);\n                  (VMState_ι_unknown34, NetParams_ι_unknown34 p) ; \n                  (VMState_ι_utime_since, NetParams_ι_utime_since p) ;\n                  (VMState_ι_utime_until, NetParams_ι_utime_until p) ;\n\n(* NetParams_ι_rawConfigParam_32 : C ; *)\n                  (VMState_ι_prevValidatorData, NetParams_ι_prevValidatorData p) ;\n\n                  (VMState_ι_rawConfigParam_17, NetParams_ι_rawConfigParam_17 p) ;\n                  (VMState_ι_unknown17_1, NetParams_ι_unknown17_1 p) ; (*check the type*)\n                  (VMState_ι_unknown17_2, NetParams_ι_unknown17_2 p) ; \n                  (VMState_ι_unknown17_3, NetParams_ι_unknown17_3 p) ; \n                  (VMState_ι_maxStakeFactor, NetParams_ι_maxStakeFactor p);\n\n                  (VMState_ι_rawConfigParam_1, NetParams_ι_rawConfigParam_1 p) ;\n                  (VMState_ι_electorRawAddress, NetParams_ι_electorRawAddress p) $} .\n\n \nDefinition DePoolContract_Ф_addOrdinaryStake'' ( Л_stake : XInteger64 ) : LedgerT ( XErrorValue True XInteger ) := \n           do r ← DePoolContract_Ф_addOrdinaryStake' Л_stake ; \n           return! (xErrorMapDefaultF (fun vv => xErrorMapDefaultF xValue vv (fun _ => xError xInt0)) r xError). \n                   \nDefinition DePoolContract_Ф_participateInElections'' ( Л_queryId : XInteger64 ) \n           ( Л_validatorKey : XInteger256 ) \n           ( Л_stakeAt : XInteger32 ) \n           ( Л_maxFactor : XInteger32 ) \n           ( Л_adnlAddr : XInteger256 ) \n           ( Л_signature : XList XInteger8 ) \n            : LedgerT ( XErrorValue True XInteger ) := \ndo r ← DePoolContract_Ф_participateInElections' Л_queryId Л_validatorKey Л_stakeAt Л_maxFactor Л_adnlAddr Л_signature; \nreturn! (xErrorMapDefaultF (fun vv => xErrorMapDefaultF xValue vv (fun _ => xError xInt0)) r xError).       \n\nDefinition DePoolContract_Ф_addVestingOrLock'' ( Л_stake : XInteger64 ) \n           ( Л_beneficiary : XAddress ) \n                                 ( Л_withdrawalPeriod : XInteger32 ) \n                                 ( Л_totalPeriod : XInteger32 ) \n                                 ( Л_isVesting : XBool ) : LedgerT (XErrorValue True XInteger) := \ndo r ← DePoolContract_Ф_addVestingOrLock' Л_stake Л_beneficiary Л_withdrawalPeriod Л_totalPeriod Л_isVesting ; \nreturn! (xErrorMapDefaultF (fun v => xValue v)  r (fun _ => xError xInt0)). \n\nEnd ScenarioCommon.", "meta": {"author": "Pruvendo", "repo": "depool_contract", "sha": "6afe23011d62f65921ac2493df691ab888ffeb95", "save_path": "github-repos/coq/Pruvendo-depool_contract", "path": "github-repos/coq/Pruvendo-depool_contract/depool_contract-6afe23011d62f65921ac2493df691ab888ffeb95/src/Scenarios/ScenarioCommon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.36658972940200996, "lm_q1q2_score": 0.21726548850277172}}
{"text": "(** ** Normalization of types\n    This file contains a lot of stuff related to the historical normalization of types performed as a pre-processing phase.\n    The current version uses a notion of dynamic types instead and a conversion function [TypToDtyp.typ_to_dtyp].\n    The content of this file is however likely to be useful for static analyses in the future.\n*)\n\nFrom Coq Require Import\n     List\n     String\n     Logic.FunctionalExtensionality.\n\nFrom Vellvm Require Import \n     Utils.Util\n     Syntax.LLVMAst\n     Syntax.AstLib\n     Syntax.DynamicTypes.\n\nRequire Import Coqlib.\n\nImport ListNotations.\nOpen Scope list_scope.\n\n\nLtac contra :=\n  try match goal with\n  | [Heq : ?x = ?y, Hneq : ?y <> ?x |- _] => symmetry in Heq\n  end; contradiction.\n\n\n(* Inductive predicate for types in LLVM with a size *)\nInductive sized_typ : list (ident * typ) -> typ -> Prop :=\n| sized_typ_I :\n    forall (defs : list (ident * typ)) (sz : N),\n      sized_typ defs (TYPE_I sz)\n\n| sized_typ_Pointer :\n    forall (defs : list (ident * typ)) (t : typ),\n      sized_typ defs (TYPE_Pointer t)\n\n| sized_typ_Half :\n    forall (defs : list (ident * typ)),\n      sized_typ defs TYPE_Half\n\n| sized_typ_Float :\n    forall (defs : list (ident * typ)),\n      sized_typ defs TYPE_Float\n\n| sized_typ_Double :\n    forall (defs : list (ident * typ)),\n      sized_typ defs TYPE_Double\n\n| sized_typ_X86_fp80 :\n    forall (defs : list (ident * typ)),\n      sized_typ defs TYPE_X86_fp80\n\n| sized_typ_Fp128 :\n    forall (defs : list (ident * typ)),\n      sized_typ defs TYPE_Fp128\n\n| sized_typ_Ppc_fp128 :\n    forall (defs : list (ident * typ)),\n      sized_typ defs TYPE_Ppc_fp128\n\n| sized_typ_Metadata :\n    forall (defs : list (ident * typ)),\n      sized_typ defs TYPE_Metadata\n\n| sized_typ_X86_mmx :\n    forall (defs : list (ident * typ)),\n      sized_typ defs TYPE_X86_mmx\n\n| sized_typ_Array :\n    forall (defs : list (ident * typ)) (sz : N) (t : typ),\n      sized_typ defs t -> sized_typ defs (TYPE_Array sz t)\n\n| sized_typ_Struct :\n    forall (defs : list (ident * typ)) (fields : list typ),\n      (forall (f : typ), In f fields -> sized_typ defs f) -> sized_typ defs (TYPE_Struct fields)\n\n| sized_typ_Packed_struct :\n    forall (defs : list (ident * typ)) (fields : list typ),\n      (forall (f : typ), In f fields -> sized_typ defs f) -> sized_typ defs (TYPE_Packed_struct fields)\n\n| sized_typ_Vector :\n    forall (defs : list (ident * typ)) (sz : N) (t : typ),\n      sized_typ defs t -> sized_typ defs (TYPE_Vector sz t)\n\n| sized_typ_Identified :\n    forall (defs : list (ident * typ)) (id : ident),\n      (exists (t : typ), In (id, t) defs -> sized_typ defs t) -> sized_typ defs (TYPE_Identified id)\n.\n\n\n(* Inductive predicate for types in LLVM that can be elements of vectors.\n\n   \"elementtype\" may be any integer, floating-point or pointer type.\n\n   https://llvm.org/docs/LangRef.html#vector-type *)\nInductive element_typ : typ -> Prop :=\n| element_typ_Pointer : forall (t : typ), element_typ (TYPE_Pointer t)\n| element_typ_I : forall (sz : N), element_typ (TYPE_I sz)\n| element_typ_Half : element_typ TYPE_Half\n| element_typ_Float : element_typ TYPE_Float\n| element_typ_Double : element_typ TYPE_Double\n| element_typ_X86_fp80 : element_typ TYPE_X86_fp80\n| element_typ_Fp128 : element_typ TYPE_Fp128\n| element_typ_Ppc_fp128 : element_typ TYPE_Ppc_fp128\n.\n  \n\n(* Predicate to ensure that an ident is guarded by a pointer everywhere in a type in an environment *)\nInductive guarded_typ : ident -> list (ident * typ) -> typ -> Prop :=\n| guarded_typ_I :\n    forall (id : ident) (env : list (ident * typ)) (sz : N),\n      guarded_typ id env (TYPE_I sz)\n\n| guarded_typ_Pointer :\n    forall (id : ident) (env : list (ident * typ)) (t : typ),\n      guarded_typ id env (TYPE_Pointer t)\n\n| guarded_typ_Void :\n    forall (id : ident) (env : list (ident * typ)),\n      guarded_typ id env TYPE_Void\n\n| guarded_typ_Half :\n    forall (id : ident) (env : list (ident * typ)),\n      guarded_typ id env TYPE_Half\n\n| guarded_typ_Float :\n    forall (id : ident) (env : list (ident * typ)),\n      guarded_typ id env TYPE_Float\n\n| guarded_typ_Double :\n    forall (id : ident) (env : list (ident * typ)),\n      guarded_typ id env TYPE_Double\n\n| guarded_typ_X86_fp80 :\n    forall (id : ident) (env : list (ident * typ)),\n      guarded_typ id env TYPE_X86_fp80\n\n| guarded_typ_Fp128 :\n    forall (id : ident) (env : list (ident * typ)),\n      guarded_typ id env TYPE_Fp128\n\n| guarded_typ_Ppc_fp128 :\n    forall (id : ident) (env : list (ident * typ)),\n      guarded_typ id env TYPE_Ppc_fp128\n\n| guarded_typ_Metadata :\n    forall (id : ident) (env : list (ident * typ)),\n      guarded_typ id env TYPE_Metadata\n\n| guarded_typ_X86_mmx :\n    forall (id : ident) (env : list (ident * typ)),\n      guarded_typ id env TYPE_X86_mmx\n\n| guarded_typ_Function :\n    forall (id : ident) (env : list (ident * typ)) (ret : typ) (args : list typ),\n      guarded_typ id env ret ->\n      (forall a, In a args -> guarded_typ id env a) ->\n      guarded_typ id env (TYPE_Function ret args)\n\n| guarded_typ_Array :\n    forall (id : ident) (env : list (ident * typ)) (sz : N) (t : typ),\n      guarded_typ id env t -> guarded_typ id env (TYPE_Array sz t)\n\n| guarded_typ_Struct :\n    forall (id : ident) (env : list (ident * typ)) (t : typ) (fields : list typ),\n      (forall f, In f fields -> guarded_typ id env f) ->\n      guarded_typ id env (TYPE_Struct fields)\n\n| guarded_typ_Packed_struct :\n    forall (id : ident) (env : list (ident * typ)) (t : typ) (fields : list typ),\n      (forall f, In f fields -> guarded_typ id env f) ->\n      guarded_typ id env (TYPE_Packed_struct fields)\n\n| guarded_typ_Opaque :\n    forall (id : ident) (env : list (ident * typ)),\n      guarded_typ id env TYPE_Opaque\n\n| guarded_typ_Vector :\n    forall (id : ident) (env : list (ident * typ)) (sz : N) (t : typ),\n      guarded_typ id env (TYPE_Vector sz t)\n\n| guarded_typ_Identified_Some :\n    forall (id : ident) (env : list (ident * typ)) (id' : ident) (t : typ),\n      id <> id' ->\n      Some (id', t) = find (fun a => Ident.eq_dec id' (fst a)) env ->\n      guarded_typ id env t ->\n      guarded_typ id' env t ->\n      guarded_typ id env (TYPE_Identified id')\n\n| guarded_typ_Identified_None :\n    forall (id : ident) (env : list (ident * typ)) (id' : ident),\n      id <> id' ->\n      None = find (fun a => Ident.eq_dec id' (fst a)) env ->\n      guarded_typ id env (TYPE_Identified id')\n.\n\n\nInductive first_class_typ : typ -> Prop :=\n| first_class_I : forall sz, first_class_typ (TYPE_I sz)\n| first_class_Pointer : forall t, first_class_typ (TYPE_Pointer t)\n| first_class_Void : first_class_typ TYPE_Void\n| first_class_Half : first_class_typ TYPE_Half\n| first_class_Float : first_class_typ TYPE_Float\n| first_class_Double : first_class_typ TYPE_Double\n| first_class_X86_fp80 : first_class_typ TYPE_X86_fp80\n| first_class_Fp128 : first_class_typ TYPE_Fp128\n| first_class_Ppc_fp128 : first_class_typ TYPE_Ppc_fp128\n| first_class_Metadata : first_class_typ TYPE_Metadata\n| first_class_X86_mmx : first_class_typ TYPE_X86_mmx\n| first_class_Array : forall sz t, first_class_typ (TYPE_Array sz t)\n| first_class_Struct : forall fields, first_class_typ (TYPE_Struct fields)\n| first_class_Packed_struct : forall fields, first_class_typ (TYPE_Packed_struct fields)\n| first_class_Opaque : first_class_typ TYPE_Opaque\n| first_class_Vector : forall sz t, first_class_typ (TYPE_Vector sz t)\n| first_class_Identified : forall id, first_class_typ (TYPE_Identified id)\n.\n\n\nDefinition function_ret_typ (t : typ) : Prop :=\n  first_class_typ t /\\ t <> TYPE_Metadata.\n\n\n(* Inductive predicate for well-formed LLVM types.\n\n   wf_typ env t\n\n   means that 't' is a well-formed type in the environment 'env'. The\n   environment just associates identifiers to types, so this contains\n   things like user-defined structure types.\n\n   well-formed LLVM types should cover every valid type in LLVM.\n\n   Examples of invalid types:\n\n   - Vectors of size 0\n   - Arrays with unsized elements\n   - Recursive structures (must be guarded by a pointer) *)\n\nInductive wf_typ : list (ident * typ) -> typ -> Prop :=\n| wf_typ_Pointer:\n    forall (defs : list (ident * typ)) (t : typ),\n      wf_typ defs t -> wf_typ defs (TYPE_Pointer t)\n\n| wf_typ_I :\n    forall (defs : list (ident * typ)) (sz : N),\n      (sz > 0)%N -> wf_typ defs (TYPE_I sz)\n\n| wf_typ_Void :\n    forall (defs : list (ident * typ)),\n      wf_typ defs TYPE_Void\n\n| wf_typ_Half :\n    forall (defs : list (ident * typ)),\n      wf_typ defs TYPE_Half\n\n| wf_typ_Float :\n    forall (defs : list (ident * typ)),\n      wf_typ defs TYPE_Float\n\n| wf_typ_Double :\n    forall (defs : list (ident * typ)),\n      wf_typ defs TYPE_Double\n\n| wf_typ_X86_fp80 :\n    forall (defs : list (ident * typ)),\n      wf_typ defs TYPE_X86_fp80\n\n| wf_typ_Fp128 :\n    forall (defs : list (ident * typ)),\n      wf_typ defs TYPE_Fp128\n\n| wf_typ_Ppc_fp128 :\n    forall (defs : list (ident * typ)),\n      wf_typ defs TYPE_Ppc_fp128\n\n| wf_typ_Metadata :\n    forall (defs : list (ident * typ)),\n      wf_typ defs TYPE_Metadata\n\n| wf_typ_X86_mmx :\n    forall (defs : list (ident * typ)),\n      wf_typ defs TYPE_X86_mmx\n\n| wf_typ_Function :\n    forall (defs : list (ident * typ)) (ret : typ) (args : list typ),\n      function_ret_typ ret ->\n      wf_typ defs ret ->\n      (forall (a : typ), In a args -> sized_typ defs a) ->\n      (forall (a : typ), In a args -> wf_typ defs a) ->\n      wf_typ defs (TYPE_Function ret args)\n\n(* Arrays are only well formed if the size is >= 0, and the element type is sized. *)\n| wf_typ_Array :\n    forall (defs : list (ident * typ)) (sz : N) (t : typ),\n      (sz >= 0)%N -> sized_typ defs t -> wf_typ defs t -> wf_typ defs (TYPE_Array sz t)\n\n(* Vectors of size 0 are not allowed, and elements must be of element_typ. *)\n| wf_typ_Vector :\n    forall (defs : list (ident * typ)) (sz : N) (t : typ),\n      (sz > 0)%N -> element_typ t -> wf_typ defs t -> wf_typ defs (TYPE_Vector sz t)\n\n(* Any type identifier must exist in the environment.\n\n   Additionally the identifier must not occur anywhere in the type\n   that it refers to *unless* it is guarded by a pointer. *)\n| wf_typ_Identified :\n    forall (defs : list (ident * typ)) (id : ident),\n      (exists t, In (id, t) defs) ->\n      (forall (t : typ), In (id, t) defs -> guarded_typ id defs t) ->\n      (forall (t : typ), In (id, t) defs -> wf_typ defs t) ->\n      wf_typ defs (TYPE_Identified id)\n\n(* Fields of structure must be sized types *)\n| wf_typ_Struct :\n    forall (defs : list (ident * typ)) (fields : list typ),\n      (forall (f : typ), In f fields -> sized_typ defs f) ->\n      (forall (f : typ), In f fields -> wf_typ defs f) ->\n      wf_typ defs (TYPE_Struct fields)\n\n| wf_typ_Packed_struct :\n    forall (defs : list (ident * typ)) (fields : list typ),\n      (forall (f : typ), In f fields -> sized_typ defs f) ->\n      (forall (f : typ), In f fields -> wf_typ defs f) ->\n      wf_typ defs (TYPE_Packed_struct fields)\n\n| wf_typ_Opaque :\n    forall (defs : list (ident * typ)),\n      wf_typ defs TYPE_Opaque\n.\n\n\nHint Constructors wf_typ.\n\n\nDefinition wf_env (env : list (ident * typ)) : Prop :=\n  NoDup (map fst env) /\\ Forall (wf_typ env) (map snd env).\n\n\nInductive guarded_wf_typ : list (ident * typ) -> typ -> Prop :=\n| guarded_wf_typ_Pointer:\n    forall (defs : list (ident * typ)) (t : typ),\n      guarded_wf_typ defs (TYPE_Pointer t)\n\n| guarded_wf_typ_I :\n    forall (defs : list (ident * typ)) (sz : N),\n      (sz > 0)%N -> guarded_wf_typ defs (TYPE_I sz)\n\n| guarded_wf_typ_Void :\n    forall (defs : list (ident * typ)),\n      guarded_wf_typ defs TYPE_Void\n\n| guarded_wf_typ_Half :\n    forall (defs : list (ident * typ)),\n      guarded_wf_typ defs TYPE_Half\n\n| guarded_wf_typ_Float :\n    forall (defs : list (ident * typ)),\n      guarded_wf_typ defs TYPE_Float\n\n| guarded_wf_typ_Double :\n    forall (defs : list (ident * typ)),\n      guarded_wf_typ defs TYPE_Double\n\n| guarded_wf_typ_X86_fp80 :\n    forall (defs : list (ident * typ)),\n      guarded_wf_typ defs TYPE_X86_fp80\n\n| guarded_wf_typ_Fp128 :\n    forall (defs : list (ident * typ)),\n      guarded_wf_typ defs TYPE_Fp128\n\n| guarded_wf_typ_Ppc_fp128 :\n    forall (defs : list (ident * typ)),\n      guarded_wf_typ defs TYPE_Ppc_fp128\n\n| guarded_wf_typ_Metadata :\n    forall (defs : list (ident * typ)),\n      guarded_wf_typ defs TYPE_Metadata\n\n| guarded_wf_typ_X86_mmx :\n    forall (defs : list (ident * typ)),\n      guarded_wf_typ defs TYPE_X86_mmx\n\n| guarded_wf_typ_Function :\n    forall (defs : list (ident * typ)) (ret : typ) (args : list typ),\n      function_ret_typ ret ->\n      guarded_wf_typ defs ret ->\n      (forall (a : typ), In a args -> sized_typ defs a) ->\n      (forall (a : typ), In a args -> guarded_wf_typ defs a) ->\n      guarded_wf_typ defs (TYPE_Function ret args)\n\n(* Arrays are only well formed if the size is >= 0, and the element type is sized. *)\n| guarded_wf_typ_Array :\n    forall (defs : list (ident * typ)) (sz : N) (t : typ),\n      (sz >= 0)%N -> sized_typ defs t -> guarded_wf_typ defs t -> guarded_wf_typ defs (TYPE_Array sz t)\n\n(* Vectors of size 0 are not allowed, and elemnts must be of element_typ. *)\n| guarded_wf_typ_Vector :\n    forall (defs : list (ident * typ)) (sz : N) (t : typ),\n      (sz > 0)%N -> element_typ t -> guarded_wf_typ defs t -> guarded_wf_typ defs (TYPE_Vector sz t)\n\n(* Identifier must be in the typing environment.\n\n   Additionally the identifier must not occur anywhere in the type\n   that it refers to *unless* it is guarded by a pointer. *)\n| guarded_wf_typ_Identified :\n    forall (defs : list (ident * typ)) (id : ident),\n      (exists t, In (id, t) defs) ->\n      (forall (t : typ), In (id, t) defs -> guarded_typ id defs t) ->\n      (forall (t : typ), In (id, t) defs -> guarded_wf_typ defs t) ->\n      guarded_wf_typ defs (TYPE_Identified id)\n\n(* Fields of structure must be sized types *)\n| guarded_wf_typ_Struct :\n    forall (defs : list (ident * typ)) (fields : list typ),\n      (forall (f : typ), In f fields -> sized_typ defs f) ->\n      (forall (f : typ), In f fields -> guarded_wf_typ defs f) ->\n      guarded_wf_typ defs (TYPE_Struct fields)\n\n| guarded_wf_typ_Packed_struct :\n    forall (defs : list (ident * typ)) (fields : list typ),\n      (forall (f : typ), In f fields -> sized_typ defs f) ->\n      (forall (f : typ), In f fields -> guarded_wf_typ defs f) ->\n      guarded_wf_typ defs (TYPE_Packed_struct fields)\n\n| guarded_wf_typ_Opaque :\n    forall (defs : list (ident * typ)),\n      guarded_wf_typ defs TYPE_Opaque\n.\n\nHint Constructors guarded_wf_typ.\n\n\nTheorem wf_typ_is_guarded_wf_typ :\n  forall env t,\n    wf_typ env t ->\n    guarded_wf_typ env t.\nProof.\n  induction 1; auto.\nQed.\n\n\n(* An unrolled type is an LLVM type that contains no identifiers,\n   unless the identifier is behind a pointer.\n\n *)\n\n\nInductive unrolled_typ : typ -> Prop :=\n| unrolled_typ_I :\n    forall (sz : N),\n      unrolled_typ (TYPE_I sz)\n\n| unrolled_typ_Pointer :\n    forall (t : typ),\n      unrolled_typ (TYPE_Pointer t)\n\n| unrolled_typ_Void :\n    unrolled_typ TYPE_Void\n\n| unrolled_typ_Half :\n    unrolled_typ TYPE_Half\n\n| unrolled_typ_Float :\n    unrolled_typ TYPE_Float\n\n| unrolled_typ_Double :\n    unrolled_typ TYPE_Double\n\n| unrolled_typ_X86_fp80 :\n    unrolled_typ TYPE_X86_fp80\n\n| unrolled_typ_Fp128 :\n    unrolled_typ TYPE_Fp128\n\n| unrolled_typ_Ppc_fp128 :\n    unrolled_typ TYPE_Ppc_fp128\n\n| unrolled_typ_Metadata :\n    unrolled_typ TYPE_Metadata\n\n| unrolled_typ_X86_mmx :\n    unrolled_typ TYPE_X86_mmx\n\n| unrolled_typ_Array :\n    forall (sz : N) (t : typ),\n      unrolled_typ t ->\n      unrolled_typ (TYPE_Array sz t)\n\n| unrolled_typ_Function :\n    forall (ret : typ) (args : list typ),\n      unrolled_typ ret ->\n      Forall unrolled_typ args ->\n      unrolled_typ (TYPE_Function ret args)\n\n| unrolled_typ_Struct :\n    forall (fields : list typ),\n      Forall (unrolled_typ) fields ->\n      unrolled_typ (TYPE_Struct fields)\n\n| unrolled_typ_Packed_struct :\n    forall (fields : list typ),\n      Forall (unrolled_typ) fields ->\n      unrolled_typ (TYPE_Packed_struct fields)\n\n| unrolled_typ_Opaque :\n    unrolled_typ TYPE_Opaque\n\n| unrolled_typ_Vector :\n    forall (sz : N) (t : typ), unrolled_typ (TYPE_Vector sz t)\n.\n\n\nInductive typ_order : typ -> typ -> Prop :=\n| typ_order_Pointer : forall (t : typ), typ_order t (TYPE_Pointer t)\n| typ_order_Array : forall (sz : N) (t : typ), typ_order t (TYPE_Array sz t)\n| typ_order_Vector : forall (sz : N) (t : typ), typ_order t (TYPE_Vector sz t)\n| typ_order_Struct : forall (fields : list typ),\n    forall f, In f fields -> typ_order f (TYPE_Struct fields)\n| typ_order_Packed_struct : forall (fields : list typ),\n    forall f, In f fields -> typ_order f (TYPE_Packed_struct fields)\n| typ_order_Function_args : forall (ret : typ) (args : list typ),\n    forall a, In a args -> typ_order a (TYPE_Function ret args)\n| typ_order_Function_ret : forall (ret : typ) (args : list typ),\n    typ_order ret (TYPE_Function ret args)\n.\n\n\nHint Constructors typ_order.\n\n\nTheorem wf_typ_order :\n    well_founded typ_order.\nProof.\n  unfold well_founded.\n  induction a; constructor; intros y H'; inversion H'; subst; auto.\nQed.\n\n\nTheorem wf_lt_typ_order :\n  well_founded (lex_ord lt typ_order).\nProof.\n  apply wf_lex_ord.\n  apply lt_wf. apply wf_typ_order.\nQed.\n\nHint Resolve wf_lt_typ_order.\nHint Constructors lex_ord.\n\n\nDefinition length_order {A : Type} (l1 l2 : list A) :=\n  (List.length l1 < List.length l2)%nat.\n\n\n(* Lemma lengthOrder_wf' : forall A len, forall ls, (List.length ls <= len)%nat -> Acc (@length_order A) ls. *)\n(*   unfold length_order; induction len; *)\n(*     intros ls H; inversion H; subst; constructor; firstorder. *)\n(* Defined. *)\n\n\n(* Theorem lengthOrder_wf : forall A, well_founded (@length_order A). *)\n(*   red; intros A a; eapply lengthOrder_wf'; eauto. *)\n(* Defined. *)\n\n\n(* Theorem wf_length_typ_order : *)\n(*   forall A, *)\n(*     well_founded (lex_ord (@length_order A) typ_order). *)\n(* Proof. *)\n(*   intros. *)\n(*   apply wf_lex_ord. apply lengthOrder_wf. apply wf_typ_order. *)\n(* Defined. *)\n\nLemma map_In {A B : Type} (l : list A) (f : forall (x : A), In x l -> B) : list B.\nProof.\n  induction l.\n  - exact [].\n  - refine (f a _ :: IHl _).\n    + simpl. auto.\n    + intros x H. apply (f x). simpl. auto.\nDefined.\n\n\nFixpoint remove_key {A B : Type} (eq_dec : (forall (x y : A), {x = y} + {x <> y})) (a : A) (l : list (A * B)) : list (A * B) :=\n  match l with\n  | nil => nil\n  | cons (h, b) t =>\n    match eq_dec a h with\n    | left _ => t\n    | right _ => (h, b) :: remove_key eq_dec a t\n    end\n  end.\n\n\nFixpoint remove_keys {A B : Type} (eq_dec : (forall (x y : A), {x = y} + {x <> y})) (keys : list A) (l : list (A * B)) : list (A * B) :=\n  match keys with\n  | nil => l\n  | key :: rest_of_keys => remove_keys eq_dec rest_of_keys (remove_key eq_dec key l)\n  end.\n\n\nLtac destruct_prod :=\n  match goal with\n  | [ |- context[let (_, _) := ?p in _]] => destruct p\n  | [ p: ?A * ?B |- _ ] => destruct p\n  end.\n\n\nLtac destruct_eq_dec :=\n  match goal with\n  | [ eq: forall x y : ?A , {x = y} + {x <> y} |- context[eq ?a ?b] ] => destruct (eq a b) eqn:?; simpl\n  | [ |- context[Ident.eq_dec ?a ?b] ] => destruct (Ident.eq_dec a b) eqn:?; simpl\n  end.\n\n\nLemma remove_key_in :\n  forall (A B : Type) (a : A)  (b : B) eq_dec l,\n    In (a, b) l ->\n    (List.length (remove_key eq_dec a l) < List.length l)%nat.\nProof.\n  induction l.\n  - intros H. inversion H.\n  - intros H.\n    destruct_prod.\n    simpl. destruct_eq_dec.\n    + apply Nat.lt_succ_diag_r.\n    + simpl. apply lt_n_S. apply IHl.\n      destruct H.\n      * inversion H. subst. contradiction.\n      * assumption.\nQed.\n\n\nLemma remove_key_not_in :\n  forall (A B : Type) (a : A) eq_dec (l : list (A * B)),\n    ~ In a (map fst l) ->\n    remove_key eq_dec a l = l.\nProof.\n  induction l; intros H.\n  - reflexivity.\n  - simpl in *. destruct_prod; destruct_eq_dec.\n    + intuition.\n    + rewrite IHl; intuition.\nQed.\n\n\nLtac solve_eq_dec_if :=\n  match goal with\n  | [ eq: forall x y : ?A , {x = y} + {x <> y},\n        Heq : ?eq ?a ?b = ?c |- context[if ?eq ?a ?b then _ else _] ] => rewrite Heq\n  | [ Heq : Ident.eq_dec ?a ?b = ?c |- context[if Ident.eq_dec ?a ?b then _ else _] ] => rewrite Heq\n  | [ eq: forall x y : ?A , {x = y} + {x <> y},\n        Heq : ?eq ?a ?b = ?c |- context[if proj_sumbool (?eq ?a ?b) then _ else _] ] => rewrite Heq\n  | [ Heq : Ident.eq_dec ?a ?b = ?c |- context[if proj_sumbool (Ident.eq_dec ?a ?b) then _ else _] ] => rewrite Heq\n\n  end.\n\n\nLtac subst_eq :=\n  match goal with\n  | [ eq: forall x y : ?A , {x = y} + {x <> y}, Heq: eq ?a ?b = ?c |- _ ] => rewrite Heq\n  | [ Heq : Ident.eq_dec ?a ?b = ?c |- _ ] => rewrite Heq\n  end.\n\n\nLtac solve_eq_dec :=\n  repeat destruct_prod; simpl in *;\n  repeat (destruct_eq_dec; simpl in *; subst; simpl; try contra; auto; repeat (solve_eq_dec_if; simpl); auto);\n  intuition; try congruence.\n\n\nLemma remove_key_commutes :\n  forall (A B : Type) (k1 k2 : A) eq_dec (l : list (A * B)),\n    remove_key eq_dec k1 (remove_key eq_dec k2 l) = remove_key eq_dec k2 (remove_key eq_dec k1 l).\nProof.\n  induction l; solve_eq_dec.\nQed.  \n\n\nLemma remove_key_keys :\n  forall (A B : Type) (keys : list A) eq_dec (key : A) (l : list (A * B)),\n    remove_key eq_dec key (remove_keys eq_dec keys l) = remove_keys eq_dec (key :: keys) l.\nProof.\n  intros A B keys.\n  induction keys as [| k keys' IHkeys]; intros eq_dec key l; auto.\n  simpl in *.\n  rewrite IHkeys.\n  apply f_equal; apply remove_key_commutes.\nQed.\n\n\nLemma remove_keys_key :\n  forall (A B : Type) (keys : list A) eq_dec (key : A) (l : list (A * B)),\n    remove_keys eq_dec keys (remove_key eq_dec key l) = remove_keys eq_dec (key :: keys) l.\nProof.\n  intros A B keys.\n  induction keys; intros eq_dec key l; auto.\nQed.\n\n\nProgram Fixpoint normalize_type (env : list (ident * typ)) (t : typ) {measure (List.length env, t) (lex_ord lt typ_order)} : typ :=\n  match t with\n  | TYPE_Array sz t =>\n    let nt := normalize_type env t in\n    TYPE_Array sz nt\n\n  | TYPE_Function ret args =>\n    let nret := (normalize_type env ret) in\n    let nargs := map_In args (fun t _ => normalize_type env t) in\n    TYPE_Function nret nargs\n\n  | TYPE_Struct fields =>\n    let nfields := map_In fields (fun t _ => normalize_type env t) in\n    TYPE_Struct nfields\n\n  | TYPE_Packed_struct fields =>\n    let nfields := map_In fields (fun t _ => normalize_type env t) in\n    TYPE_Packed_struct nfields\n\n  | TYPE_Vector sz t =>\n    let nt := normalize_type env t in\n    TYPE_Vector sz nt\n\n  | TYPE_Identified id =>\n    match find (fun a => Ident.eq_dec id (fst a)) env with\n    | None => TYPE_Identified id\n    | Some (_, t) => normalize_type (remove_key Ident.eq_dec id env) t\n    end\n\n  | TYPE_I sz => t\n  | TYPE_Pointer t' => t\n  | TYPE_Void => t\n  | TYPE_Half => t\n  | TYPE_Float => t\n  | TYPE_Double => t\n  | TYPE_X86_fp80 => t\n  | TYPE_Fp128 => t\n  | TYPE_Ppc_fp128 => t\n  | TYPE_Metadata => t\n  | TYPE_X86_mmx => t\n  | TYPE_Opaque => t\n  end.\nNext Obligation.\n  left.\n  symmetry in Heq_anonymous. apply find_some in Heq_anonymous. destruct Heq_anonymous as [Hin Heqb_ident].\n  simpl in Heqb_ident.\n  destruct (Ident.eq_dec id wildcard'). subst. eapply remove_key_in. apply Hin.\n  inversion Heqb_ident.\nDefined.\n\n\nLemma normalize_type_equation : forall env t,\n    normalize_type env t =\n    match t with\n  | TYPE_Array sz t =>\n    let nt := normalize_type env t in\n    TYPE_Array sz nt\n\n  | TYPE_Function ret args =>\n    let nret := (normalize_type env ret) in\n    let nargs := map_In args (fun t _ => normalize_type env t) in\n    TYPE_Function nret nargs\n\n  | TYPE_Struct fields =>\n    let nfields := map_In fields (fun t _ => normalize_type env t) in\n    TYPE_Struct nfields\n\n  | TYPE_Packed_struct fields =>\n    let nfields := map_In fields (fun t _ => normalize_type env t) in\n    TYPE_Packed_struct nfields\n\n  | TYPE_Vector sz t =>\n    let nt := normalize_type env t in\n    TYPE_Vector sz nt\n\n  | TYPE_Identified id =>\n    let opt := find (fun a => Ident.eq_dec id (fst a)) env in\n    match opt with\n    | None => TYPE_Identified id   (* TODO: should this be None? *)\n    | Some (_, t) => normalize_type (remove_key Ident.eq_dec id env) t\n    end\n\n  | TYPE_I sz => TYPE_I sz\n  | TYPE_Pointer t' => TYPE_Pointer t'\n  | TYPE_Void => TYPE_Void\n  | TYPE_Half => TYPE_Half\n  | TYPE_Float => TYPE_Float\n  | TYPE_Double => TYPE_Double\n  | TYPE_X86_fp80 => TYPE_X86_fp80\n  | TYPE_Fp128 => TYPE_Fp128\n  | TYPE_Ppc_fp128 => TYPE_Ppc_fp128\n  | TYPE_Metadata => TYPE_Metadata\n  | TYPE_X86_mmx => TYPE_X86_mmx\n  | TYPE_Opaque => TYPE_Opaque\n  end.\nProof.\n  intros env t.\n  unfold normalize_type. \n  unfold normalize_type_func at 1.\n  rewrite Wf.WfExtensionality.fix_sub_eq_ext.\n  destruct t; try reflexivity. simpl.\n  destruct (find (fun a : ident * typ => Ident.eq_dec id (fst a)) env).\n  destruct p; simpl; eauto.\n  reflexivity.\nDefined.    \n\n\nHint Constructors unrolled_typ.\n\n\nLemma find_in_wf_env :\n  forall env id t,\n    NoDup (map fst env) ->\n    In (id, t) env ->\n    find (fun a : ident * typ => Ident.eq_dec id (fst a)) env = Some (id, t).\nProof.\n  intros env id t Hdup Hin.\n  induction env as [| [id' t'] env IHenv].\n  - contradiction.\n  - destruct Hin as [Hin | Hin]; try inversion Hin; subst.\n    + simpl. destruct_eq_dec; intuition.\n    + simpl. destruct_eq_dec.\n      * inversion Hdup. subst. apply in_map with (f:=fst) in Hin. simpl in *.\n        contradiction.\n      * simpl. inversion Hdup. auto.\nQed.\n\n\nLemma guarded_typ_id_same :\n  forall env id,\n    guarded_typ id env (TYPE_Identified id) -> False.\nProof.\n  intros env id H.\n  inversion H; contradiction.\nQed.\n\n\n\nLemma find_different_key_from_removed :\n  forall env id id',\n    id <> id' ->\n    find (fun a : ident * typ => Ident.eq_dec id' (fst a)) env = find (fun a : ident * typ => Ident.eq_dec id' (fst a)) (remove_key Ident.eq_dec id env).\nProof.\n  intros env id id' H.\n  induction env; solve_eq_dec.\nQed.\n\n\nLemma remove_keys_find :\n  forall env id ids,\n    ~ In id ids ->\n    find (fun a : ident * typ => Ident.eq_dec id (fst a)) env = find (fun a : ident * typ => Ident.eq_dec id (fst a)) (remove_keys Ident.eq_dec ids env).\nProof.\n  intros env id ids H.\n  induction ids.\n  - reflexivity.\n  - rewrite <- remove_key_keys.\n    rewrite <- find_different_key_from_removed with (id:=a); intuition; subst; intuition.\nQed.\n\n\nLtac solve_some :=\n  match goal with\n  | [ H: (?i1, ?t1) = (?i2, ?t2) |- ?F (?i1, ?t1) = ?F (?i2, ?t2) ] => inversion H; reflexivity\n  | [ Hdup : NoDup (?i :: map fst ?env),\n      Hin : In (?i, ?t) ?env |- ?F (?i, ?t1) = ?F (?i, ?t2) ] =>\n    let Hnin := fresh in\n    let Hdup' := fresh in\n    inversion Hdup as [| ? ? Hnin Hdup']; subst;\n    exfalso; apply Hnin;\n    replace i with (fst (i, t)) by reflexivity;\n    apply in_map; auto\n  | [ Hin : In (?i, ?t1) ((?i, ?t2) :: ?env) |- ?F (?i, ?t1) = ?F (?i, ?t2) ] => symmetry; solve_some\n  | [ Hin : In (?i, ?t2) ((?i, ?t1) :: ?env) |- ?F (?i, ?t1) = ?F (?i, ?t2) ] => inversion Hin; solve_some\n  end.\n\n\nLtac solve_in :=\n  match goal with\n  | [ Hin: In (?id, ?t) ((?i, ?t0) :: ?env),\n      Hneq: ?id <> ?i |- In (?id, ?t) ?env ] =>\n    let Htup := fresh in\n    inversion Hin as [Htup | ?]; [> inversion Htup; contra | auto]\n\n  | [ H: find (fun a => (proj_sumbool (?eq ?id (fst a)))) ?env = Some (?i, ?t)\n      |- In (?id, ?t) ?env ] =>\n    let Hfind := fresh in\n    apply find_some in H as [? Hfind];\n    simpl in Hfind;\n    destruct (Ident.eq_dec id i) eqn:?; subst; intuition\n  end.\n\n\nLemma find_some_id :\n  forall env id p t,\n    NoDup (map fst env) ->\n    In (id, t) env ->\n    find (fun a : ident * typ => Ident.eq_dec id (fst a)) env = Some p ->\n    find (fun a : ident * typ => Ident.eq_dec id (fst a)) env = Some (id, t).\nProof.\n  intros env id p t Hdup Hin H.\n  induction env.\n  - inversion H.\n  - destruct a. simpl.\n    destruct_eq_dec.\n    + subst. simpl in Hdup. solve_some.\n    + simpl. apply IHenv.\n      * inversion Hdup; auto.\n      * solve_in.\n      * simpl in *. rewrite Heqs in H. simpl in *.\n        assumption.\nQed.\n\nHint Constructors sized_typ.\nHint Constructors guarded_typ.\n\n\n(* Types with no identifiers *)\nInductive simple_typ : typ -> Prop :=\n| simple_typ_I : forall sz, simple_typ (TYPE_I sz)\n| simple_typ_Pointer : forall t, simple_typ t -> simple_typ (TYPE_Pointer t)\n| simple_typ_Void : simple_typ (TYPE_Void)\n| simple_typ_Half : simple_typ (TYPE_Half)\n| simple_typ_Float : simple_typ (TYPE_Float)\n| simple_typ_Double : simple_typ (TYPE_Double)\n| simple_typ_X86_fp80 : simple_typ (TYPE_X86_fp80)\n| simple_typ_Fp128 : simple_typ (TYPE_Fp128)\n| simple_typ_Ppc_fp128 : simple_typ (TYPE_Ppc_fp128)\n| simple_typ_Metadata : simple_typ (TYPE_Metadata)\n| simple_typ_X86_mmx : simple_typ (TYPE_X86_mmx)\n| simple_typ_Array : forall sz t, simple_typ t -> simple_typ (TYPE_Array sz t)\n| simple_typ_Function :\n    forall ret args,\n      simple_typ ret ->\n      (forall a, In a args -> simple_typ a) ->\n      simple_typ (TYPE_Function ret args)\n| simple_typ_Struct :\n    forall fields,\n      (forall f, In f fields -> simple_typ f) ->\n      simple_typ (TYPE_Struct fields)\n| simple_typ_Packed_struct :\n    forall fields,\n      (forall f, In f fields -> simple_typ f) ->\n      simple_typ (TYPE_Packed_struct fields)\n| simple_typ_Opaque : simple_typ (TYPE_Opaque)\n| simple_typ_Vector : forall sz t, simple_typ t -> simple_typ (TYPE_Vector sz t)\n.\n\n\nHint Constructors simple_typ.\n\n\nTheorem map_in_id :\n  forall {A : Type} (l : list A) (f : forall x : A, In x l -> A),\n    (forall a (Hin : In a l), f a Hin = a) ->\n    map_In l f = l.\nProof.\n  intros A l f H.\n  induction l; auto.\n  simpl. rewrite H. rewrite IHl; auto.\nQed.\n\n\nTheorem simple_normalizes_to_self :\n  forall env t,\n    simple_typ t ->\n    normalize_type env t = t.\nProof.\n  intros env t H.\n  induction H; rewrite normalize_type_equation; simpl;\n    repeat\n      match goal with\n      | [H : normalize_type env _ = _ |- context[normalize_type _ _]] => rewrite H\n      | [|- context[(map_In _ (fun (t : typ) (_ : In t _) => normalize_type env t))]] => rewrite map_in_id; auto\n      end; auto.\nQed.\n\n\nTheorem simple_unrolled :\n  forall t,\n    simple_typ t -> unrolled_typ t.\nProof.\n  intros t H.\n  induction H; constructor;\n    try match goal with\n        | [|- Forall _ _] => apply Forall_forall\n        end; auto.\nQed.\n\n\nTheorem in_map_in :\n  forall {A : Type} (x : A) (l : list A) f,\n    In x (map_In l (fun t (_ : In t l) => f t)) ->\n    exists t, In t l /\\ f t = x.\nProof.\n  intros A x l f H.\n  induction l.\n  - inversion H.\n  - simpl in *. destruct H.\n    + exists a. split; auto.\n    + apply IHl in H as [t [Hin Hftx]].\n      exists t. intuition.      \nQed.\n\n\nTheorem map_rewrite :\n  forall {A B : Type} (x : A) (l : list A) (f g : A -> B),\n    (forall x, In x l -> f x = g x) ->\n    map_In l (fun t (_ : In t l) => f t) = map_In l (fun t (_ : In t l) => g t).\nProof.\n  intros A B x l f g H.\n  induction l as [| a l IHl]; simpl; auto.\n  pose proof (H a) as Ha.\n  rewrite Ha; intuition.\n  rewrite IHl; intuition.\nQed.\n\n\nLtac simpl_remove_keys :=\n  match goal with\n  | [ |- context[remove_key ?eq ?id (remove_keys ?eq ?ids ?assoc_list)] ] =>\n    replace (remove_key eq id (remove_keys eq ids assoc_list)) with\n        (remove_keys eq (id :: ids) assoc_list) by auto using remove_key_keys\n\n  | [ |- context[remove_keys ?eq ?ids (remove_key ?eq ?id ?assoc_list)] ] =>\n    replace (remove_keys eq ids (remove_key eq id assoc_list)) with\n        (remove_keys eq (id :: ids) assoc_list) by auto using remove_keys_key\n\n  | [ |- context[remove_key ?eq ?id ?assoc_list] ] =>\n    replace (remove_key eq id assoc_list) with\n        (remove_keys eq [id] assoc_list) by auto\n  end.\n\n\nLtac subst_find_some :=\n  match goal with\n  | [ H1: ?F ?filter ?defs = ?G (?i1, ?t1),\n      H2: ?X = ?F ?filter ?defs |- _ ] => rewrite H1 in H2; inversion H2\n  end.\n\n\nLtac solve_guard :=\n  match goal with\n  | [ H: element_typ ?x |- guarded_typ ?id ?defs ?x ] =>\n        match goal with\n        | [H : element_typ _ |- _] => inversion H\n        end; auto\n\n  | [ Hguard: forall i, In i ?ids -> guarded_typ i ?env ?t |- ~(In ?id ?ids) ] =>\n    let Hguard' := fresh in\n    let Hin := fresh in\n    unfold not; intros Hin;\n    pose proof Hguard id Hin as Hguard';\n    inversion Hguard'; auto\n\n  | [ Hguard: forall t, In (?i, t) ?defs -> guarded_typ ?i ?defs t,\n        Hin: In ?id [?i] |- _ ] =>\n    intros; inversion Hin; subst; try contradiction; auto\n\n  | [ Hguard: forall i, In ?id [i] -> guarded_typ ?i ?env ?t |- ~(In ?id ?ids) ] =>\n    let Hguard' := fresh in\n    let Hin := fresh in\n    unfold not; intros Hin;\n    pose proof Hguard id Hin as Hguard';\n    inversion Hguard'; subst; try contra; auto\n\n  | [ Hguard: forall i, In i ?ids -> guarded_typ i ?env ?t,\n        Hin: In ?id [?one] |- guarded_typ ?id ?defs ?x ] =>\n    inversion Hin; subst; auto; contra\n\n  | [ Hguard: forall i, In i ?ids -> guarded_typ i ?env ?t,\n      Hin: In ?id ?ids |- guarded_typ ?id ?defs ?x ] =>\n    let Hguard' := fresh in\n    pose proof Hguard _ Hin as Hguard'; inversion Hguard'; auto; subst; subst_find_some; subst; auto\n\n  | [ |- forall id, In id ?ids -> guarded_typ id ?defs ?x ] =>\n    intros; solve_guard\n  end.\n\nTheorem guarded_id_normalize_same :\n  forall t env,\n    NoDup (map fst env) ->\n    guarded_wf_typ env t ->\n    (forall ids,\n        (forall id, In id ids -> guarded_typ id env t) ->\n        normalize_type (remove_keys Ident.eq_dec ids env) t = normalize_type env t).\nProof.\n  intros t env Hdup Hwf.\n  induction Hwf; intros ids Hguard;\n    rewrite normalize_type_equation; symmetry; rewrite normalize_type_equation; simpl; auto;\n      try rewrite IHHwf; auto;\n        try match goal with\n            | [H : element_typ _ |- _] => inversion H\n            end;\n        try (rewrite map_rewrite with (f:=normalize_type (remove_keys _ _ _)) (g:=normalize_type defs);\n             try exact (TYPE_Void);\n             auto; intros;\n             match goal with\n             | [ H: _ |- _ ] => apply H\n             end;\n             auto);\n        try (intros id Hidin; solve_guard).\n\n  (* Identifiers *)\n  repeat simpl_remove_keys.\n\n  (* If id is in ids, this means that guarded_typ id defs\n     (TYPE_Identified id), which is a contradiction. *)\n  assert (~ In id ids) as Hnotin by solve_guard.\n\n  replace (find (fun a : ident * typ => Ident.eq_dec id (fst a)) (remove_keys Ident.eq_dec ids defs)) with\n      (find (fun a : ident * typ => Ident.eq_dec id (fst a)) defs) by (auto using remove_keys_find).\n\n  destruct (find (fun a : ident * typ => Ident.eq_dec id (fst a)) defs) eqn:Hfind; auto.\n  destruct_prod. simpl.\n\n  assert (In (id, t) defs).\n  apply find_some in Hfind as [Hin Hfind].\n  simpl in Hfind.\n\n  destruct (Ident.eq_dec id i) eqn:Hidi; subst; intuition.\n\n  repeat (simpl_remove_keys;\n          repeat match goal with\n                 | [ H: _ |- _ ] => rewrite H\n                 end; auto); intros id0 [Hidid0 | Hin']; subst; auto.\n\n  - inversion Hin'.\n  - pose proof (Hguard id0 Hin') as Hguard'. inversion Hguard'; subst_find_some; subst; auto.\nQed.\n\n\nTheorem double_map_In :\n  forall A B C (l : list A) (f : A -> B) (g : B -> C),\n    (map_In (map_In l (fun x (_ : In x l) => f x)) (fun x (_ : In x (map_In l (fun x (_ : In x l) => f x))) => g x)) = map_In l (fun x (_ : In x l) => g (f x)).\nProof.\n  intros A B C l f g.\n  induction l; simpl; auto using f_equal.\nQed.\n\n\nLtac solve_map_in :=\n  repeat\n    match goal with\n    | [  |- context[map_In (map_In _ _)] ] => rewrite double_map_In\n    | [ defs : list (ident * typ) |- _ ] =>\n      try (rewrite map_rewrite with (f:=fun x => normalize_type defs (normalize_type defs x)) (g:=normalize_type defs); [> eauto | exact TYPE_Void | eauto]);\n      try solve [intros;\n                 match goal with\n                 | [ H: _ |- _ ] => apply H\n                 end; auto; solve_guard]\n\n  end.\n\n\nLtac solve_match_find :=\n  match goal with\n  | [ |- context[match ?Find with _ => _ end = _] ] =>\n    let i := fresh in\n    let t := fresh in\n    let Hfind := fresh in\n    destruct Find as [[i t] |] eqn:Hfind;\n    match goal with\n    | [ Hf: context[find (fun a => proj_sumbool (?eq ?id (fst a))) ?defs],\n            defs : list (ident * typ) |- _ ] =>\n      try (assert (In (id, t) defs) by solve_in;\n           symmetry; simpl_remove_keys;\n           rewrite guarded_id_normalize_same; auto using wf_typ_is_guarded_wf_typ; try solve_guard;\n\n           try (match goal with\n                | [ H: _ |- _ ] => apply H\n                end; auto; solve_guard));\n      try (rewrite normalize_type_equation; simpl; rewrite Hfind; reflexivity)\n    end\n  end.\n\n\nTheorem guarded_normalize_same :\n  forall t env,\n    NoDup (map fst env) ->\n    guarded_wf_typ env t ->\n    (forall ids,\n        (forall id, In id ids -> guarded_typ id env t) ->\n        normalize_type env (normalize_type env t) = normalize_type env t).\nProof.\n  intros t env Hdup Hwf ids Hguard_all.\n  induction Hwf;\n    try solve [rewrite normalize_type_equation; symmetry; rewrite normalize_type_equation;\n               simpl; auto;\n               try rewrite IHHwf; auto; try solve_guard; solve_map_in].\n\n  symmetry; rewrite normalize_type_equation; simpl.\n  solve_match_find.\nQed.\n\n\nLemma wf_typ_guarded_normalize_twice :\n  forall env t,\n    NoDup (map fst env) ->\n    wf_typ env t ->\n    (forall ids,\n        (forall id, In id ids -> guarded_typ id env t) ->\n        normalize_type env (normalize_type env t) = normalize_type env t).\nProof.\n  eauto using wf_typ_is_guarded_wf_typ, guarded_normalize_same.\nQed.\n\n  \nTheorem double_normalize_type :\n  forall env t,\n    wf_env env ->\n    wf_typ env t ->\n    normalize_type env (normalize_type env t) = normalize_type env t.\nProof.\n  intros env t [Hdup Henv] Hwf.\n  induction Hwf;\n    try solve [rewrite normalize_type_equation; symmetry; rewrite normalize_type_equation;\n               simpl; auto;\n               try rewrite IHHwf; auto; try solve_guard; solve_map_in].\n\n  symmetry; rewrite normalize_type_equation; simpl.\n  solve_match_find.\nQed.\n\n\nTheorem guarded_normalize_type_unrolls:\n  forall env t,\n    NoDup (map fst env) ->\n    guarded_wf_typ env t ->\n    (forall ids,\n        (forall id, In id ids -> guarded_typ id env t) ->\n        unrolled_typ (normalize_type env t)).\nProof.\n  intros env t Hdup Hwf ids Hguard_all.\n  induction Hwf; rewrite normalize_type_equation; simpl; auto;\n    try constructor;\n    try (apply IHHwf; auto; solve_guard);\n    try (rewrite Forall_forall; intros;\n         match goal with\n         | [ H: In ?x (map_In _ _) |- _ ] =>  apply in_map_in in H as [t [Hin Hnorm]]\n         end;\n\n         rewrite <- Hnorm;\n\n         match goal with\n         | [ H: _ |- _ ] => apply H\n         end; auto; solve_guard).\n  - destruct (find (fun a : ident * typ => Ident.eq_dec id (fst a)) defs) as [[i t] |] eqn:Hfind.\n    + pose proof Hfind as Hfind'.\n      apply find_some in Hfind' as [Hin Heq].\n      simpl in *. destruct (Ident.eq_dec id i) as [He | He]; inversion Heq.\n\n      rewrite He.\n      simpl_remove_keys.\n      rewrite guarded_id_normalize_same; auto;\n        try match goal with\n            | [ H: _ |- _ ] => apply H\n            end;\n        subst; auto; solve_guard.\n    + destruct H as [t Hin].\n      eapply find_none in Hfind; eauto.\n      simpl in Hfind. destruct (Ident.eq_dec id id).\n      inversion Hfind. contradiction.\nQed.\n\n\nTheorem normalize_type_unrolls:\n  forall env t,\n    wf_env env ->\n    wf_typ env t ->\n    unrolled_typ (normalize_type env t).\nProof.\n  intros env t [Hdup Henv] Hwf.\n  induction Hwf; rewrite normalize_type_equation; simpl; auto;\n    try constructor;\n    try (apply IHHwf; auto);\n    try (rewrite Forall_forall; intros;\n         match goal with\n         | [ H: In ?x (map_In _ _) |- _ ] =>  apply in_map_in in H as [t [Hin Hnorm]]\n         end;\n\n         rewrite <- Hnorm;\n\n         match goal with\n         | [ H: _ |- _ ] => apply H\n         end; auto; solve_guard).\n  - destruct (find (fun a : ident * typ => Ident.eq_dec id (fst a)) defs) as [[i t] |] eqn:Hfind.\n    +\n      apply find_some in Hfind as [Hin Heq].\n      simpl in *. destruct (Ident.eq_dec id i); inversion Heq; subst.\n\n      simpl_remove_keys.\n\n      rewrite guarded_id_normalize_same; auto using wf_typ_is_guarded_wf_typ; solve_guard.\n    + destruct H as [t Hin].\n      eapply find_none in Hfind; eauto.\n      simpl in Hfind. destruct (Ident.eq_dec id id).\n      inversion Hfind. contradiction.\nQed.\n", "meta": {"author": "vellvm", "repo": "vellvm", "sha": "c9b7d6a283c4954b25bf7bcb1b1e54b92b62d699", "save_path": "github-repos/coq/vellvm-vellvm", "path": "github-repos/coq/vellvm-vellvm/vellvm-c9b7d6a283c4954b25bf7bcb1b1e54b92b62d699/src/coq/Syntax/TypeUtil.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.21726548440142998}}
{"text": "(****************************************************************************)\n(* Copyright 2020 The Project Oak Authors                                   *)\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\nRequire Import Coq.Arith.Arith Coq.Vectors.Vector.\nRequire Import Cava.Arrow.ArrowExport.\n\nRequire Import Aes.Pkg Aes.MixSingleColumn.\n\nImport VectorNotations.\nImport KappaNotation.\nOpen Scope kind_scope.\n\n(* module aes_mix_columns (\n  input  aes_pkg::ciph_op_e    op_i,\n  input  logic [3:0][3:0][7:0] data_i,\n  output logic [3:0][3:0][7:0] data_o\n); *)\nDefinition aes_mix_columns\n  :\n    <<Bit, Vector (Vector (Vector Bit 8) 4) 4, Unit>> ~>\n      Vector (Vector (Vector Bit 8) 4) 4 :=\n      (* // Transpose to operate on columns\n      logic [3:0][3:0][7:0] data_i_transposed;\n      logic [3:0][3:0][7:0] data_o_transposed;\n\n      assign data_i_transposed = aes_transpose(data_i);\n\n      // Individually mix columns\n      for (genvar i = 0; i < 4; i++) begin : gen_mix_column\n        aes_mix_single_column aes_mix_column_i (\n          .op_i   ( op_i                 ),\n          .data_i ( data_i_transposed[i] ),\n          .data_o ( data_o_transposed[i] )\n        );\n      end\n\n      assign data_o = aes_transpose(data_o_transposed); *)\n  <[\\op_i data_i =>\n    let transposed = !aes_transpose data_i in\n    let ouput_transposed = !(map2 aes_mix_single_column) (!replicate op_i) transposed in\n    !aes_transpose ouput_transposed\n  ]>.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/investigations/Arrow/aes/MixColumns.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.21723898060202199}}
{"text": "Require Import Bool String List.\nRequire Import Lib.CommonTactics Lib.ilist Lib.Word.\nRequire Import Lib.Struct Lib.FMap Lib.StringEq Lib.Indexer.\nRequire Import Kami.Syntax Kami.Semantics Kami.RefinementFacts Kami.Renaming Kami.Wf.\nRequire Import Kami.Renaming Kami.Inline Kami.InlineFacts.\nRequire Import Kami.Decomposition Kami.Notations Kami.Tactics.\nRequire Import Ex.MemTypes Ex.NativeFifo Ex.MemAsync.\nRequire Import Ex.SC Ex.ProcDec Ex.ProcThreeStage Ex.ProcThreeStInl Ex.ProcThreeStInv.\nRequire Import Eqdep.\n\nSet Implicit Arguments.\n\nSection ProcThreeStDec.\n  Variables addrSize iaddrSize instBytes dataBytes rfIdx: nat.\n\n  Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes)\n            (dec: AbsDec addrSize instBytes dataBytes rfIdx)\n            (exec: AbsExec addrSize instBytes dataBytes rfIdx).\n\n  Variable (d2eElt: Kind).\n  Variable (d2ePack:\n              forall ty,\n                Expr ty (SyntaxKind (Bit 2)) -> (* opTy *)\n                Expr ty (SyntaxKind (Bit rfIdx)) -> (* dst *)\n                Expr ty (SyntaxKind (Bit addrSize)) -> (* addr *)\n                Expr ty (SyntaxKind (Array Bool dataBytes)) -> (* byteEn *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val1 *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* val2 *)\n                Expr ty (SyntaxKind (Data instBytes)) -> (* rawInst *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* curPc *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* nextPc *)\n                Expr ty (SyntaxKind Bool) -> (* epoch *)\n                Expr ty (SyntaxKind d2eElt)).\n  Variables\n    (d2eOpType: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Bit 2)))\n    (d2eDst: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                        Expr ty (SyntaxKind (Bit rfIdx)))\n    (d2eAddr: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                         Expr ty (SyntaxKind (Bit addrSize)))\n    (d2eByteEn: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Array Bool dataBytes)))\n    (d2eVal1 d2eVal2: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                                 Expr ty (SyntaxKind (Data dataBytes)))\n    (d2eRawInst: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                            Expr ty (SyntaxKind (Data instBytes)))\n    (d2eCurPc: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                          Expr ty (SyntaxKind (Pc addrSize)))\n    (d2eNextPc: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                           Expr ty (SyntaxKind (Pc addrSize)))\n    (d2eEpoch: forall ty, fullType ty (SyntaxKind d2eElt) ->\n                          Expr ty (SyntaxKind Bool)).\n\n  Hypotheses\n    (Hd2eOpType: forall opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch,\n        evalExpr (d2eOpType _ (evalExpr (d2ePack opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch))) = evalExpr opType)\n    (Hd2eDst: forall opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch,\n        evalExpr (d2eDst _ (evalExpr (d2ePack opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch))) = evalExpr dst)\n    (Hd2eAddr: forall opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch,\n        evalExpr (d2eAddr _ (evalExpr (d2ePack opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch))) = evalExpr addr)\n    (Hd2eByteEn: forall opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch,\n        evalExpr (d2eByteEn _ (evalExpr (d2ePack opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch))) = evalExpr byteEn)\n    (Hd2eVal1: forall opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch,\n        evalExpr (d2eVal1 _ (evalExpr (d2ePack opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch))) = evalExpr val1)\n    (Hd2eVal2: forall opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch,\n        evalExpr (d2eVal2 _ (evalExpr (d2ePack opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch))) = evalExpr val2)\n    (Hd2eRawInst: forall opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch,\n        evalExpr (d2eRawInst _ (evalExpr (d2ePack opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch))) = evalExpr rawInst)\n    (Hd2eCurPc: forall opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch,\n        evalExpr (d2eCurPc _ (evalExpr (d2ePack opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch))) = evalExpr curPc)\n    (Hd2eNextPc: forall opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch,\n        evalExpr (d2eNextPc _ (evalExpr (d2ePack opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch))) = evalExpr nextPc)\n    (Hd2eEpoch: forall opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch,\n        evalExpr (d2eEpoch _ (evalExpr (d2ePack opType dst addr byteEn val1 val2 rawInst curPc nextPc epoch))) = evalExpr epoch).\n\n  Variable (e2wElt: Kind).\n  Variable (e2wPack:\n              forall ty,\n                Expr ty (SyntaxKind d2eElt) -> (* decInst *)\n                Expr ty (SyntaxKind (Data dataBytes)) -> (* execVal *)\n                Expr ty (SyntaxKind e2wElt)).\n  Variables\n    (e2wDecInst: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                            Expr ty (SyntaxKind d2eElt))\n    (e2wVal: forall ty, fullType ty (SyntaxKind e2wElt) ->\n                        Expr ty (SyntaxKind (Data dataBytes))).\n\n  Hypotheses\n    (He2wDecInst: forall decInst val,\n        evalExpr (e2wDecInst _ (evalExpr (e2wPack decInst val))) = evalExpr decInst)\n    (He2wVal: forall decInst val,\n        evalExpr (e2wVal _ (evalExpr (e2wPack decInst val))) = evalExpr val).\n\n  Variable (init: ProcInit addrSize dataBytes rfIdx).\n\n  Definition p3st := ProcThreeStage.p3st\n                       fetch dec exec\n                       d2ePack d2eOpType d2eDst d2eAddr d2eByteEn d2eVal1 d2eVal2\n                       d2eRawInst d2eCurPc d2eNextPc d2eEpoch\n                       e2wPack e2wDecInst e2wVal init.\n  Definition pdec := ProcDec.pdec fetch dec exec init.\n  \n  #[local] Hint Unfold p3st: ModuleDefs. (* for kinline_compute *)\n  #[local] Hint Extern 1 (ModEquiv type typeUT p3st) => unfold p3st. (* for kequiv *)\n  #[local] Hint Extern 1 (ModEquiv type typeUT pdec) => unfold pdec. (* for kequiv *)\n\n  Definition p3st_pdec_ruleMap (o: RegsT): string -> option string :=\n    \"pgmInitRq\" |-> \"pgmInitRq\";\n      \"pgmInitRqEnd\" |-> \"pgmInitRqEnd\";\n      \"pgmInitRs\" |-> \"pgmInitRs\";\n      \"pgmInitRsEnd\" |-> \"pgmInitRsEnd\";\n      \"reqLd\" |-> \"reqLd\";\n      \"reqSt\" |-> \"reqSt\";\n      \"repLd\" |-> \"repLd\";\n      \"repLdZ\" |-> \"repLdZ\";\n      \"repSt\" |-> \"repSt\";\n      \"wbNm\" |-> \"execNm\";\n      \"wbNmZ\" |-> \"execNmZ\"; ||.\n  #[local] Hint Unfold p3st_pdec_ruleMap: MethDefs.\n\n  Definition p3st_pdec_regMap (r: RegsT): RegsT :=\n    (mlet pcv : (Pc addrSize) <- r |> \"pc\";\n       mlet pinitv : Bool <- r |> \"pinit\";\n       mlet pinitRqv : Bool <- r |> \"pinitRq\";\n       mlet pinitRqOfsv : (Bit iaddrSize) <- r |> \"pinitRqOfs\";\n       mlet pinitRsOfsv : (Bit iaddrSize) <- r |> \"pinitRsOfs\";\n       mlet pgmv : (Vector (Data instBytes) iaddrSize) <- r |> \"pgm\";\n       mlet rfv : (Vector (Data dataBytes) rfIdx) <- r |> \"rf\";\n       mlet d2eeltv : d2eElt <- r |> \"d2e\"--\"elt\";\n       mlet d2efv : Bool <- r |> \"d2e\"--\"full\";\n       mlet e2weltv : e2wElt <- r |> \"e2w\"--\"elt\";\n       mlet e2wfv : Bool <- r |> \"e2w\"--\"full\";\n       mlet w2deltv : w2dElt addrSize <- r |> \"w2d\"--\"elt\";\n       mlet w2dfv : Bool <- r |> \"w2d\"--\"full\";\n       mlet eev : Bool <- r |> \"eEpoch\";\n       mlet stallv : Bool <- r |> \"stall\";\n       mlet stalledv : d2eElt <- r |> \"stalled\";\n\n       ([\"stall\" <- existT _ _ stallv]\n        +[\"pgm\" <- existT _ _ pgmv]\n        +[\"pinitRsOfs\" <- existT _ _ pinitRsOfsv]\n        +[\"pinitRqOfs\" <- existT _ _ pinitRqOfsv]\n        +[\"pinitRq\" <- existT _ _ pinitRqv]\n        +[\"pinit\" <- existT _ _ pinitv]\n        +[\"rf\" <- existT _ _ rfv]\n        +[\"pc\" <- existT _ (SyntaxKind (Pc addrSize))\n               (if w2dfv then w2deltv (Fin.FS Fin.F1)\n                else if stallv then evalExpr (d2eCurPc _ stalledv)\n                     else if e2wfv then\n                            (if Bool.eqb eev (evalExpr\n                                                (d2eEpoch _ (evalExpr (e2wDecInst _ e2weltv))))\n                             then evalExpr (d2eCurPc _ (evalExpr (e2wDecInst _ e2weltv)))\n                             else\n                               (if d2efv then\n                                  (if Bool.eqb eev (evalExpr (d2eEpoch _ d2eeltv))\n                                   then evalExpr (d2eCurPc _ d2eeltv)\n                                   else pcv)\n                                else pcv))\n                          else if d2efv then\n                                 (if Bool.eqb eev (evalExpr (d2eEpoch _ d2eeltv))\n                                  then evalExpr (d2eCurPc _ d2eeltv)\n                                  else pcv)\n                               else pcv)])%fmap)%mapping.\n  #[local] Hint Unfold p3st_pdec_regMap: MapDefs.\n\n  Ltac is_not_ife t :=\n    match t with\n    | context [if _ then _ else _] => fail 1\n    | _ => idtac\n    end.\n  \n  Ltac dest_if :=\n    match goal with\n    | [ |- context[if ?x then _ else _] ] =>\n      let c := fresh \"c\" in is_not_ife x; remember x as c; destruct c\n    | [H: context[if ?x then _ else _] |- _] =>\n      let c := fresh \"c\" in is_not_ife x; remember x as c; destruct c\n    end.\n\n  Ltac d2e_abs_tac :=\n    try rewrite Hd2eOpType in *;\n    try rewrite Hd2eDst in *;\n    try rewrite Hd2eAddr in *;\n    try rewrite Hd2eVal1 in *;\n    try rewrite Hd2eVal2 in *;\n    try rewrite Hd2eRawInst in *;\n    try rewrite Hd2eCurPc in *;\n    try rewrite Hd2eNextPc in *;\n    try rewrite Hd2eEpoch in *;\n    try rewrite He2wDecInst in *;\n    try rewrite He2wVal in *.\n\n  Ltac kinv_bool :=\n    repeat\n      (try match goal with\n           | [H: ?t = true |- _] => rewrite H in *\n           | [H: ?t = false |- _] => rewrite H in *\n           | [H: true = ?t |- _] => rewrite <-H in *\n           | [H: false = ?t |- _] => rewrite <-H in *\n           end; dest_if; kinv_simpl; intuition idtac).\n\n  Ltac p3st_inv_tac := d2e_abs_tac; kinv_bool.\n\n  Ltac p3st_dest_tac :=\n    repeat match goal with\n           | [H: context[p3st_pinit_inv] |- _] => destruct H\n           | [H: context[p3st_epochs_inv] |- _] => destruct H\n           | [H: context[p3st_pc_inv] |- _] => destruct H\n           | [H: context[p3st_decode_inv] |- _] => destruct H\n           | [H: context[p3st_stalled_inv] |- _] => destruct H\n           | [H: context[p3st_raw_inv] |- _] => destruct H\n           | [H: context[p3st_scoreboard_waw_inv] |- _] => destruct H\n           | [H: context[p3st_exec_inv] |- _] => destruct H\n           end;\n    kinv_red.\n\n  Definition p3stInl := ProcThreeStInl.p3stInl\n                          fetch dec exec\n                          d2ePack d2eOpType d2eDst d2eAddr d2eByteEn d2eVal1 d2eVal2\n                          d2eRawInst d2eCurPc d2eNextPc d2eEpoch\n                          e2wPack e2wDecInst e2wVal init.\n\n  Definition p3stConfig :=\n    {| inlining := ITProvided p3stInl;\n       decomposition := DTFunctional p3st_pdec_regMap p3st_pdec_ruleMap;\n       invariants := IVCons p3st_inv_ok IVNil\n    |}.\n\n  Theorem p3st_refines_pdec:\n    p3st <<== pdec.\n  Proof. (* SKIP_PROOF_ON\n\n    (** inlining *)\n    ketrans; [exact (projT2 p3stInl)|].\n\n    (** decomposition *)\n    kdecompose_nodefs p3st_pdec_regMap p3st_pdec_ruleMap.\n    kinv_add p3st_inv_ok.\n    kinv_add_end.\n    kinvert.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    - kinv_magic_with p3st_dest_tac p3st_inv_tac.\n    \n      (* kami_ok p3stConfig p3st_dest_tac p3st_inv_tac. *)\n      END_SKIP_PROOF_ON *) apply cheat.\n  Qed.\n\nEnd ProcThreeStDec.\n\n", "meta": {"author": "mit-plv", "repo": "kami", "sha": "cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0", "save_path": "github-repos/coq/mit-plv-kami", "path": "github-repos/coq/mit-plv-kami/kami-cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0/Kami/Ex/ProcThreeStDec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.21723898060202199}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness proof for RTL generation. *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Smallstep.\nRequire Import Globalenvs.\nRequire Import Switch.\nRequire Import Registers.\nRequire Import Cminor.\nRequire Import Op.\nRequire Import CminorSel.\nRequire Import RTL.\nRequire Import RTLgen.\nRequire Import RTLgenspec.\n\nRequire Import mem_lemmas.\nRequire Import semantics.\nRequire Import semantics_lemmas.\nRequire Import effect_semantics.\nRequire Import structured_injections.\nRequire Import reach.\nRequire Import simulations.\nRequire Import effect_properties.\nRequire Import simulations_lemmas.\n\nRequire Export Axioms.\nRequire Import CminorSel_coop.\nRequire Import CminorSel_eff.\nRequire Import RTL_coop.\nRequire Import BuiltinEffects.\nRequire Import RTL_eff.\n\nLemma FreeEffect_PropagateLeft':\n  forall (m : mem) (sp : block) (lo hi : Z) (m' : mem),\n  Mem.free m sp lo hi = Some m' ->\n  forall (mu : SM_Injection) (m2 : mem),\n  sm_valid mu m m2 ->\n  SM_wd mu ->\n  forall spb' : block,\n  local_of mu sp = Some (spb', 0%Z) ->\n  forall (b2 : block) (ofs : Z),\n  FreeEffect m2 lo hi spb' b2 ofs = true ->\n  locBlocksTgt mu b2 = false ->\n  exists (b1 : block) (delta : Z),\n    foreign_of mu b1 = Some (b2, delta) /\\\n    FreeEffect m lo hi sp b1 (ofs - delta) = true /\\\n    Mem.perm m b1 (ofs - delta) Max Nonempty.\nProof. intros.\n  eapply FreeEffect_PropagateLeft; try eassumption.\n  eapply local_in_all; eassumption.\n  unfold vis. destruct (local_DomRng _ H1 _ _ _ H2); intuition.\nQed.\n\n(** * Correspondence between Cminor environments and RTL register sets *)\n\n(** A compilation environment (mapping) is well-formed if\n  the following properties hold:\n- Two distinct Cminor local variables are mapped to distinct pseudo-registers.\n- A Cminor local variable and a let-bound variable are mapped to\n  distinct pseudo-registers.\n*)\n\nRecord map_wf (m: mapping) : Prop :=\n  mk_map_wf {\n    map_wf_inj:\n      (forall id1 id2 r,\n         m.(map_vars)!id1 = Some r -> m.(map_vars)!id2 = Some r -> id1 = id2);\n     map_wf_disj:\n      (forall id r,\n         m.(map_vars)!id = Some r -> In r m.(map_letvars) -> False)\n  }.\n\nLemma init_mapping_wf:\n  map_wf init_mapping.\nProof.\n  unfold init_mapping; split; simpl.\n  intros until r. rewrite PTree.gempty. congruence.\n  tauto.\nQed.\n\nLemma add_var_wf:\n  forall s1 s2 map name r map' i,\n  add_var map name s1 = OK (r,map') s2 i -> \n  map_wf map -> map_valid map s1 -> map_wf map'.\nProof.\n  intros. monadInv H. \n  apply mk_map_wf; simpl.\n  intros until r0. repeat rewrite PTree.gsspec.\n  destruct (peq id1 name); destruct (peq id2 name).\n  congruence.\n  intros. inv H. elimtype False. \n  apply valid_fresh_absurd with r0 s1. \n  apply H1. left; exists id2; auto.\n  eauto with rtlg.\n  intros. inv H2. elimtype False. \n  apply valid_fresh_absurd with r0 s1. \n  apply H1. left; exists id1; auto.\n  eauto with rtlg.\n  inv H0. eauto.\n  intros until r0. rewrite PTree.gsspec.\n  destruct (peq id name). \n  intros. inv H.\n  apply valid_fresh_absurd with r0 s1.\n  apply H1. right; auto.\n  eauto with rtlg.\n  inv H0; eauto.\nQed.\n\nLemma add_vars_wf:\n  forall names s1 s2 map map' rl i,\n  add_vars map names s1 = OK (rl,map') s2 i ->\n  map_wf map -> map_valid map s1 -> map_wf map'.\nProof.\n  induction names; simpl; intros; monadInv H. \n  auto.\n  exploit add_vars_valid; eauto. intros [A B].\n  eapply add_var_wf; eauto.\nQed.\n\nLemma add_letvar_wf:\n  forall map r,\n  map_wf map -> ~reg_in_map map r -> map_wf (add_letvar map r).\nProof.\n  intros. inv H. unfold add_letvar; constructor; simpl.\n  auto.\n  intros. elim H1; intro. subst r0. elim H0. left; exists id; auto.\n  eauto.\nQed.\n\n(** An RTL register environment matches a CminorSel local environment and\n  let-environment if the value of every local or let-bound variable in\n  the CminorSel environments is identical to the value of the\n  corresponding pseudo-register in the RTL register environment. *)\n\n(*LENB: replaced extension by injection. In particular, added paranmeter j:meminj\n  and replaced lessdefs by val_injects*)\n\nRecord match_env (j:meminj)\n      (map: mapping) (e: env) (le: letenv) (rs: regset) : Prop :=\n  mk_match_env {\n    me_vars:\n      (forall id v,\n         e!id = Some v -> exists r, map.(map_vars)!id = Some r\n          /\\ val_inject j v rs#r);\n    me_letvars:\n      val_list_inject j le rs##(map.(map_letvars))\n  }.\n\nLemma match_env_find_var:\n  forall j map e le rs id v r,\n  match_env j map e le rs ->\n  e!id = Some v ->\n  map.(map_vars)!id = Some r ->\n  val_inject j v rs#r.\nProof.\n  intros. exploit me_vars; eauto. intros [r' [EQ' RS]].\n  replace r with r'. auto. congruence.\nQed.\n\nLemma match_env_inject_incr: forall j map e le rs\n        (MENV: match_env j map e le rs) j'\n        (INC: inject_incr j j'),\n      match_env j' map e le rs.\nProof.\n  intros.\n  destruct MENV as [MENVa MENVb].\n  constructor; intros.\n    destruct (MENVa _ _ H) as [r [MAP INJ]].\n    apply (val_inject_incr _ _ _ _ INC) in INJ.\n    exists r; split; trivial.\n  apply (val_list_inject_incr _ _ _ _ INC) in MENVb; trivial.\nQed.\n\nLemma match_env_restrictD: forall j X map e le rs\n        (MENV: match_env (restrict j X) map e le rs),\n      match_env j map e le rs.\nProof. intros.\n  eapply match_env_inject_incr; try eassumption.\n  eapply restrict_incr.\nQed.\n\nLemma match_env_find_letvar:\n  forall j map e le rs idx v r,\n  match_env j map e le rs ->\n  List.nth_error le idx = Some v ->\n  List.nth_error map.(map_letvars) idx = Some r ->\n  val_inject j v rs#r.\nProof.\n  intros. exploit me_letvars; eauto.\n  clear H. revert le H0 H1. generalize (map_letvars map). clear map.\n  induction idx; simpl; intros.\n  inversion H; subst le; inversion H0. subst v0.\n  destruct l; inversion H1. subst r0.\n  inversion H2. subst v'. auto.\n  destruct l; destruct le; try discriminate.\n  eapply IHidx; eauto.\n  inversion H. auto.\nQed.\n\nLemma match_env_invariant:\n  forall j map e le rs rs',\n  match_env j map e le rs ->\n  (forall r, (reg_in_map map r) -> rs'#r = rs#r) ->\n  match_env j map e le rs'.\nProof.\n  intros. inversion H. apply mk_match_env.\n  intros. exploit me_vars0; eauto. intros [r [A B]].\n  exists r; split. auto. rewrite H0; auto. left; exists id; auto.\n  replace (rs'##(map_letvars map)) with (rs ## (map_letvars map)). auto.\n  apply list_map_exten. intros. apply H0. right; auto.\nQed.\n\n(** Matching between environments is preserved when an unmapped register\n  (not corresponding to any Cminor variable) is assigned in the RTL\n  execution. *)\n\nLemma match_env_update_temp:\n  forall j map e le rs r v,\n  match_env j map e le rs ->\n  ~(reg_in_map map r) ->\n  match_env j map e le (rs#r <- v).\nProof.\n  intros. apply match_env_invariant with rs; auto.\n  intros. case (Reg.eq r r0); intro. \n  subst r0; contradiction.\n  apply Regmap.gso; auto.\nQed.\nHint Resolve match_env_update_temp: rtlg.\n\n(** Matching between environments is preserved by simultaneous\n  assignment to a Cminor local variable (in the Cminor environments)\n  and to the corresponding RTL pseudo-register (in the RTL register\n  environment). *)\n\nLemma match_env_update_var:\n  forall j map e le rs id r v tv,\n  val_inject j v tv ->\n  map_wf map ->\n  map.(map_vars)!id = Some r ->\n  match_env j map e le rs ->\n  match_env j map (PTree.set id v e) le (rs#r <- tv).\nProof.\n  intros. inversion H0. inversion H2. apply mk_match_env.\n  intros id' v'. rewrite PTree.gsspec. destruct (peq id' id); intros.\n  subst id'. inv H3. exists r; split. auto. rewrite PMap.gss. auto.\n  exploit me_vars0; eauto. intros [r' [A B]].\n  exists r'; split. auto. rewrite PMap.gso; auto.\n  red; intros. subst r'. elim n. eauto.\n  erewrite list_map_exten. eauto.\n  intros. symmetry. apply PMap.gso. red; intros. subst x. eauto. \nQed.\n\n(** A variant of [match_env_update_var] where a variable is optionally\n  assigned to, depending on the [dst] parameter. *)\n\nLemma match_env_update_dest:\n  forall j map e le rs dst r v tv,\n  val_inject j v tv ->\n  map_wf map ->\n  reg_map_ok map r dst ->\n  match_env j map e le rs ->\n  match_env j map (set_optvar dst v e) le (rs#r <- tv).\nProof.\n  intros. inv H1; simpl. \n  eapply match_env_update_temp; eauto. \n  eapply match_env_update_var; eauto.\nQed.\nHint Resolve match_env_update_dest: rtlg.\n\n(** Matching and [let]-bound variables. *)\n\nLemma match_env_bind_letvar:\n  forall j map e le rs r v,\n  match_env j map e le rs ->\n  val_inject j v rs#r ->\n  match_env j (add_letvar map r) e (v :: le) rs.\nProof.\n  intros. inv H. unfold add_letvar. apply mk_match_env; simpl; auto.\nQed.\n\nLemma match_env_unbind_letvar:\n  forall j map e le rs r v,\n  match_env j (add_letvar map r) e (v :: le) rs ->\n  match_env j map e le rs.\nProof.\n  unfold add_letvar; intros. inv H. simpl in *. \n  constructor. auto. inversion me_letvars0. auto.\nQed.\n\n(** Matching between initial environments. *)\n\nLemma match_env_empty:\n  forall j map,\n  map.(map_letvars) = nil ->\n  match_env j map (PTree.empty val) nil (Regmap.init Vundef).\nProof.\n  intros. apply mk_match_env.\n  intros. rewrite PTree.gempty in H0. discriminate.\n  rewrite H. constructor.\nQed.\n\n(** The assignment of function arguments to local variables (on the Cminor\n  side) and pseudo-registers (on the RTL side) preserves matching\n  between environments. *)\n\nLemma match_set_params_init_regs:\n  forall j il rl s1 map2 s2 vl tvl i,\n  add_vars init_mapping il s1 = OK (rl, map2) s2 i ->\n  val_list_inject j vl tvl ->\n  match_env j map2 (set_params vl il) nil (init_regs tvl rl)\n  /\\ (forall r, reg_fresh r s2 -> (init_regs tvl rl)#r = Vundef).\nProof.\n  induction il; intros.\n\n  inv H. split. apply match_env_empty. auto. intros. \n  simpl. apply Regmap.gi.\n\n  monadInv H. simpl.\n  exploit add_vars_valid; eauto. apply init_mapping_valid. intros [A B].\n  exploit add_var_valid; eauto. intros [A' B']. clear B'.\n  monadInv EQ1. \n  destruct H0 as [ | v1 tv1 vs tvs].\n  (* vl = nil *)\n  destruct (IHil _ _ _ _ nil nil _ EQ) as [ME UNDEF]. constructor. inv ME. split.\n  replace (init_regs nil x) with (Regmap.init Vundef) in me_vars0, me_letvars0.\n  constructor; simpl.\n  intros id v. repeat rewrite PTree.gsspec. destruct (peq id a); intros.\n  subst a. inv H. exists x1; split. auto. constructor.\n  eauto.\n  eauto.\n  destruct x; reflexivity.\n  intros. apply Regmap.gi.\n  (* vl = v1 :: vs *)\n  destruct (IHil _ _ _ _ _ _ _ EQ H0) as [ME UNDEF]. inv ME. split.\n  constructor; simpl.\n  intros id v. repeat rewrite PTree.gsspec. destruct (peq id a); intros.\n  subst a. (*inv H.*) inv H1. exists x1; split. auto. rewrite Regmap.gss. assumption.   \n  exploit me_vars0; eauto. intros [r' [C D]]. \n  exists r'; split. auto. rewrite Regmap.gso. auto.\n  apply valid_fresh_different with s.\n  apply B. left; exists id; auto.\n  eauto with rtlg. \n  destruct (map_letvars x0). auto. simpl in me_letvars0. inversion me_letvars0.\n  intros. rewrite Regmap.gso. apply UNDEF. \n  apply reg_fresh_decr with s2; eauto with rtlg.\n  apply sym_not_equal. apply valid_fresh_different with s2; auto.\nQed.\n\nLemma match_set_locals:\n  forall j map1 s1,\n  map_wf map1 ->\n  forall il rl map2 s2 e le rs i,\n  match_env j map1 e le rs ->\n  (forall r, reg_fresh r s1 -> rs#r = Vundef) ->\n  add_vars map1 il s1 = OK (rl, map2) s2 i ->\n  match_env j map2 (set_locals il e) le rs.\nProof.\n  induction il; simpl in *; intros.\n\n  inv H2. auto.\n\n  monadInv H2. \n  exploit IHil; eauto. intro. \n  monadInv EQ1.\n  constructor.\n  intros id v. simpl. repeat rewrite PTree.gsspec. \n  destruct (peq id a). subst a. intro. \n  exists x1. split. auto. inv H3. constructor.\n  eauto with rtlg.\n  intros. eapply me_vars; eauto. \n  simpl. eapply me_letvars; eauto.\nQed.\n\nLemma match_init_env_init_reg:\n  forall j params s0 rparams map1 s1 i1 vars rvars map2 s2 i2 vparams tvparams,\n  add_vars init_mapping params s0 = OK (rparams, map1) s1 i1 ->\n  add_vars map1 vars s1 = OK (rvars, map2) s2 i2 ->\n  val_list_inject j vparams tvparams ->\n  match_env j map2 (set_locals vars (set_params vparams params))\n            nil (init_regs tvparams rparams).\nProof.\n  intros.\n  exploit match_set_params_init_regs; eauto. intros [A B].\n  eapply match_set_locals; eauto.\n  eapply add_vars_wf; eauto. apply init_mapping_wf.\n  apply init_mapping_valid.\nQed.\n\n(** * The simulation argument *)\n\nRequire Import Errors.\n\nSection CORRECTNESS.\n\nVariable prog: CminorSel.program.\nVariable tprog: RTL.program.\nHypothesis TRANSL: transl_program prog = OK tprog.\n\nLet ge : CminorSel.genv := Genv.globalenv prog.\nLet tge : RTL.genv := Genv.globalenv tprog.\n\n(*NEW*) Variable hf : I64Helpers.helper_functions.\n\n(** Relationship between the global environments for the original\n  CminorSel program and the generated RTL program. *)\n\nLemma symbols_preserved:\n  forall (s: ident), Genv.find_symbol tge s = Genv.find_symbol ge s.\nProof\n  (Genv.find_symbol_transf_partial transl_fundef _ TRANSL).\n\nLemma function_ptr_translated:\n  forall (b: block) (f: CminorSel.fundef),\n  Genv.find_funct_ptr ge b = Some f ->\n  exists tf,\n  Genv.find_funct_ptr tge b = Some tf /\\ transl_fundef f = OK tf.\nProof\n  (Genv.find_funct_ptr_transf_partial transl_fundef _ TRANSL).\n\nLemma functions_translated:\n  forall (v: val) (f: CminorSel.fundef),\n  Genv.find_funct ge v = Some f ->\n  exists tf,\n  Genv.find_funct tge v = Some tf /\\ transl_fundef f = OK tf.\nProof\n  (Genv.find_funct_transf_partial transl_fundef _ TRANSL).\n\nLemma sig_transl_function:\n  forall (f: CminorSel.fundef) (tf: RTL.fundef),\n  transl_fundef f = OK tf ->\n  RTL.funsig tf = CminorSel.funsig f.\nProof.\n  intros until tf. unfold transl_fundef, transf_partial_fundef.\n  case f; intro.\n  unfold transl_function. \n  destruct (reserve_labels (fn_body f0) (PTree.empty node, init_state)) as [ngoto s0].\n  case (transl_fun f0 ngoto s0); simpl; intros.\n  discriminate.\n  destruct p. simpl in H. inversion H. reflexivity.\n  intro. inversion H. reflexivity.\nQed.\n\nLemma varinfo_preserved:\n  forall b, Genv.find_var_info tge b = Genv.find_var_info ge b.\nProof.\n  apply (Genv.find_var_info_transf_partial transl_fundef _ TRANSL).\nQed.\n\nLemma GDE_lemma: genvs_domain_eq ge tge.\nProof.\n    unfold genvs_domain_eq, genv2blocks.\n    simpl; split; intros. \n     split; intros; destruct H as [id Hid].\n       rewrite <- symbols_preserved in Hid.\n       exists id; trivial.\n     rewrite symbols_preserved in Hid.\n       exists id; trivial.\n    split. intros. rewrite varinfo_preserved. intuition.\n    intros. split.\n      intros [f H].\n        apply function_ptr_translated in H. \n        destruct H as [? [? _]]. \n        eexists; eassumption.\n     intros [f H]. \n         apply (@Genv.find_funct_ptr_rev_transf_partial\n           _ _ _ transl_fundef prog _ TRANSL) in H.\n         destruct H as [? [? _]]. eexists; eassumption.\nQed.\n\n(** Correctness of the code generated by [add_move]. *)\n\nLemma tr_move_correct:\n  forall r1 ns r2 nd cs f sp rs m,\n  tr_move f.(fn_code) ns r1 nd r2 ->\n  exists rs',\n  corestep_star (rtl_eff_sem hf) tge\n     (RTL_State cs f sp ns rs) m \n     (RTL_State cs f sp nd rs') m /\\\n  rs'#r2 = rs#r1 /\\\n  (forall r, r <> r2 -> rs'#r = rs#r).\nProof.\n  intros. inv H. \n  exists rs; split. eapply corestep_star_zero. auto.\n  exists (rs#r2 <- (rs#r1)); split. \n  apply corestep_star_one. eapply rtl_corestep_exec_Iop. eauto. auto. \n  split. apply Regmap.gss. intros; apply Regmap.gso; auto.\nQed.\n\n(** Correctness of the translation of [switch] statements *)\n\nLemma transl_switch_correct:\n  forall j cs sp e m f map r nexits t ns,\n  tr_switch f.(fn_code) map r nexits t ns ->\n  forall rs i act,\n  rs#r = Vint i ->\n  map_wf map ->\n  match_env j map e nil rs ->\n  comptree_match i t = Some act ->\n  exists nd, exists rs',\n  corestep_star (rtl_eff_sem hf) tge (RTL_State cs f sp ns rs) m (RTL_State cs f sp nd rs') m /\\\n  nth_error nexits act = Some nd /\\\n  match_env j map e nil rs'.\nProof.\n  Opaque Int.sub.\n  induction 1; simpl; intros.\n(* action *)\n  inv H3. exists n; exists rs; intuition.\n  apply corestep_star_zero.\n(* ifeq *)\n  caseEq (Int.eq i key); intro EQ; rewrite EQ in H5.\n  inv H5. exists nfound; exists rs; intuition.\n  apply corestep_star_one. eapply rtl_corestep_exec_Icond with (b := true); eauto. \n  simpl. rewrite H2. simpl. congruence.\n  exploit IHtr_switch; eauto. intros [nd1 [rs1 [EX [NTH ME]]]].\n  exists nd1; exists rs1; intuition.\n  eapply corestep_star_trans. \n    eapply corestep_star_one. eapply rtl_corestep_exec_Icond with (b := false); eauto.  \n      simpl. rewrite H2. simpl. congruence. eexact EX.\n(* iflt *)\n  caseEq (Int.ltu i key); intro EQ; rewrite EQ in H5.\n  exploit IHtr_switch1; eauto. intros [nd1 [rs1 [EX [NTH ME]]]].\n  exists nd1; exists rs1; intuition.\n  eapply corestep_star_trans. \n    eapply corestep_star_one. eapply rtl_corestep_exec_Icond with (b := true); eauto.  \n    simpl. rewrite H2. simpl. congruence. eexact EX.\n  exploit IHtr_switch2; eauto. intros [nd1 [rs1 [EX [NTH ME]]]].\n  exists nd1; exists rs1; intuition.\n  eapply corestep_star_trans. \n    eapply corestep_star_one. eapply rtl_corestep_exec_Icond with (b := false); eauto. \n    simpl. rewrite H2. simpl. congruence. eexact EX.\n(* jumptable *)\n  set (rs1 := rs#rt <- (Vint(Int.sub i ofs))).\n  assert (ME1: match_env j map e nil rs1).\n    unfold rs1. eauto with rtlg.\n  assert (EX1: RTL_corestep hf tge (RTL_State cs f sp n rs) m (RTL_State cs f sp n1 rs1) m).\n    eapply rtl_corestep_exec_Iop; eauto. \n    predSpec Int.eq Int.eq_spec ofs Int.zero; simpl.\n    rewrite H10. rewrite Int.sub_zero_l. congruence.\n    rewrite H6. simpl. rewrite <- Int.sub_add_opp. auto. \n  caseEq (Int.ltu (Int.sub i ofs) sz); intro EQ; rewrite EQ in H9.\n  exploit H5; eauto. intros [nd [A B]].\n  exists nd; exists rs1; intuition.\n  eapply corestep_star_trans. \n    eapply corestep_star_one. eexact EX1.\n  eapply corestep_star_trans. \n    eapply corestep_star_one. eapply rtl_corestep_exec_Icond with (b := true); eauto.  \n    simpl. unfold rs1. rewrite Regmap.gss. simpl. congruence. \n  apply corestep_star_one. eapply rtl_corestep_exec_Ijumptable; eauto. unfold rs1. apply Regmap.gss.\n  exploit (IHtr_switch rs1); eauto. unfold rs1. rewrite Regmap.gso; auto.\n  intros [nd [rs' [EX [NTH ME]]]].\n  exists nd; exists rs'; intuition.\n  eapply corestep_star_trans. \n    eapply corestep_star_one. eexact EX1.\n  eapply corestep_star_trans. \n    eapply corestep_star_one. eapply rtl_corestep_exec_Icond with (b := false); eauto. \n    simpl. unfold rs1. rewrite Regmap.gss. simpl. congruence.\n  eexact EX. \nQed.\n\n(** ** Semantic preservation for the translation of expressions *)\n\n(*LENB: translation of sp. Contrary to selection phase,\n  the use of eval_operation (and the existing lemmas about\n  eval_operation_inject) here suggests that we\n  require sp=Vptr b Int.zero and sp' = Vptr b' Int.zero instead\n  of sp=Vptr b i and sp' = Vptr b' i for some arbitrary i.*)\nDefinition sp_preserved (j:meminj) (sp sp':val) := \n    exists b b', sp = Vptr b Int.zero /\\ sp' = Vptr b' Int.zero /\\ \n                j b = Some(b',0).\n\nLemma sp_incr j j' sp sp': sp_preserved j sp sp' -> inject_incr j j' ->\n     sp_preserved j' sp sp'.\nProof. intros.  \n  destruct H as [b [b' [? [? ?]]]].\n  exists b, b'; repeat split; eauto.\nQed.\n\nLemma sp_preserved_intern_incr mu mu' sp sp': forall\n      (SP : sp_preserved (local_of mu) sp sp')\n      (INC : intern_incr mu mu'),\n   sp_preserved (local_of mu') sp sp'.\nProof. intros.\n  destruct SP as [spb [tspb [SP [TSP LocSP]]]]. \n  exists spb, tspb. intuition. eapply INC; assumption. \nQed.\n\nLemma shift_stack_addressing_zero: forall addr,\n shift_stack_addressing (Int.repr 0) addr = addr.\nProof. intros.\n  destruct addr; try reflexivity. \n  simpl. rewrite Int.add_zero_l. trivial.\nQed.\n\nSection CORRECTNESS_EXPR.\n\nVariable sp: val.\nVariable e: env.\nVariable m: mem.\n\n(** The proof of semantic preservation for the translation of expressions\n  is a simulation argument based on diagrams of the following form:\n<<\n                    I /\\ P\n    e, le, m, a ------------- State cs code sp ns rs tm\n         ||                      |\n         ||                      |*\n         ||                      |\n         \\/                      v\n    e, le, m, v ------------ State cs code sp nd rs' tm'\n                    I /\\ Q\n>>\n  where [tr_expr code map pr a ns nd rd] is assumed to hold.\n  The left vertical arrow represents an evaluation of the expression [a].\n  The right vertical arrow represents the execution of zero, one or\n  several instructions in the generated RTL flow graph [code].\n\n  The invariant [I] is the agreement between Cminor environments and\n  RTL register environment, as captured by [match_envs].\n\n  The precondition [P] includes the well-formedness of the compilation\n  environment [mut].\n\n  The postconditions [Q] state that in the final register environment\n  [rs'], register [rd] contains value [v], and the registers in\n  the set of preserved registers [pr] are unchanged, as are the registers\n  in the codomain of [map].\n\n  We formalize this simulation property by the following predicate\n  parameterized by the CminorSel evaluation (left arrow).  *)\n\nDefinition transl_expr_prop \n     (le: letenv) (a: expr) (v: val) : Prop :=\n  forall mu tm cs f map pr ns nd rd rs dst\n (*NEW:*)(PG: meminj_preserves_globals ge (as_inj mu))\n         sp' (SP: sp_preserved (local_of mu) sp sp')\n         (WD: SM_wd mu) (SMV: sm_valid mu m tm) \n         (RC: REACH_closed m (vis mu))\n         (Glob: forall b, isGlobalBlock ge b = true -> \n                  frgnBlocksSrc mu b = true)\n         (OBS: silent hf ge a)\n\n    (MWF: map_wf map)\n    (TE: tr_expr f.(fn_code) map pr a ns nd rd dst)\n    (ME: match_env (restrict (as_inj mu) (vis mu)) map e le rs)\n    (EXT: Mem.inject (as_inj mu) m tm),\n  exists rs', exists tm', exists mu',\n  (intern_incr mu mu'\n  /\\ sm_inject_separated mu mu' m tm\n  /\\ globals_separate ge mu mu'             \n  /\\ sm_locally_allocated mu mu' m tm m tm'\n  /\\ SM_wd mu'\n  /\\ sm_valid mu' m tm'\n  /\\ REACH_closed m (vis mu'))\n  /\\ corestep_star (rtl_eff_sem hf) tge\n        (RTL_State cs f sp' ns rs) tm (RTL_State cs f sp' nd rs') tm' \n  /\\ match_env (restrict (as_inj mu') (vis mu')) map (set_optvar dst v e) le rs'\n  /\\ val_inject (restrict (as_inj mu') (vis mu')) v rs'#rd\n  /\\ (forall r, In r pr -> rs'#r = rs#r)\n  /\\ Mem.inject (as_inj mu') m tm'.\n\nDefinition transl_exprlist_prop \n     (le: letenv) (al: exprlist) (vl: list val) : Prop :=\n  forall mu tm cs f map pr ns nd rl rs\n (*NEW:*)(PG: meminj_preserves_globals ge (as_inj mu))\n         sp' (SP: sp_preserved (local_of mu) sp sp')\n         (WD: SM_wd mu) (SMV: sm_valid mu m tm)\n         (RC: REACH_closed m (vis mu))\n         (Glob: forall b, isGlobalBlock ge b = true -> \n                  frgnBlocksSrc mu b = true)\n         (OBS: silentExprList hf ge al)\n\n    (MWF: map_wf map)\n    (TE: tr_exprlist f.(fn_code) map pr al ns nd rl)\n    (ME: match_env (restrict (as_inj mu) (vis mu)) map e le rs)\n    (EXT: Mem.inject (as_inj mu) m tm),\n  exists rs', exists tm', exists mu',\n  (intern_incr mu mu'\n   /\\ sm_inject_separated mu mu' m tm\n  /\\ globals_separate ge mu mu'\n  /\\ sm_locally_allocated mu mu' m tm m tm'\n  /\\ SM_wd mu'\n  /\\ sm_valid mu' m tm'\n  /\\ REACH_closed m (vis mu'))\n  /\\ corestep_star (rtl_eff_sem hf) tge\n       (RTL_State cs f sp' ns rs) tm (RTL_State cs f sp' nd rs') tm'\n  /\\ match_env (restrict (as_inj mu') (vis mu')) map e le rs'\n  /\\ val_list_inject (restrict (as_inj mu') (vis mu')) vl rs'##rl\n  /\\ (forall r, In r pr -> rs'#r = rs#r)\n  /\\ Mem.inject (as_inj mu') m tm'.\n\nDefinition transl_condexpr_prop \n     (le: letenv) (a: condexpr) (v: bool) : Prop :=\n  forall mu tm cs f map pr ns ntrue nfalse rs\n (*NEW:*)(PG: meminj_preserves_globals ge (as_inj mu))\n         sp' (SP: sp_preserved (local_of mu) sp sp')\n         (WD: SM_wd mu) (SMV: sm_valid mu m tm)\n         (RC: REACH_closed m (vis mu))\n         (Glob: forall b, isGlobalBlock ge b = true -> \n                  frgnBlocksSrc mu b = true)\n         (OBS: silentCondExpr hf ge a)\n\n    (MWF: map_wf map)\n    (TE: tr_condition f.(fn_code) map pr a ns ntrue nfalse)\n    (ME: match_env (restrict (as_inj mu) (vis mu)) map e le rs)\n    (EXT: Mem.inject (as_inj mu) m tm),\n  exists rs', exists tm', exists mu',\n   (intern_incr mu mu'\n   /\\ sm_inject_separated mu mu' m tm\n  /\\ globals_separate ge mu mu'\n  /\\ sm_locally_allocated mu mu' m tm m tm'\n  /\\ SM_wd mu'\n  /\\ sm_valid mu' m tm'\n  /\\ REACH_closed m (vis mu'))\n  /\\ corestep_plus (rtl_eff_sem hf) tge\n       (RTL_State cs f sp' ns rs) tm (RTL_State cs f sp' (if v then ntrue else nfalse) rs') tm'\n  /\\ match_env (restrict (as_inj mu') (vis mu')) map e le rs'\n  /\\ (forall r, In r pr -> rs'#r = rs#r)\n  /\\ Mem.inject (as_inj mu') m tm'.\n\n(** The correctness of the translation is a huge induction over\n  the Cminor evaluation derivation for the source program.  To keep\n  the proof manageable, we put each case of the proof in a separate\n  lemma.  There is one lemma for each Cminor evaluation rule.\n  It takes as hypotheses the premises of the Cminor evaluation rule,\n  plus the induction hypotheses, that is, the [transl_expr_prop], etc,\n  corresponding to the evaluations of sub-expressions or sub-statements. *)\n\nLemma transl_expr_Evar_correct:\n  forall (le : letenv) (id : positive) (v: val),\n  e ! id = Some v ->\n  transl_expr_prop le (Evar id) v.\nProof.\n  intros; red; intros. inv TE.\n  exploit match_env_find_var; eauto. intro EQ.\n  exploit tr_move_correct; eauto. intros [rs' [A [B C]]]. \n  exists rs'; exists tm; exists mu. \n    split. simpl. trivial.\n    split. apply intern_incr_refl.\n    split. apply sm_inject_separated_same_sminj.\n    split. apply gsep_refl. \n    split. apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.\n      eauto.\n  split. eauto.\n  destruct H2 as [[D E] | [D E]].\n  (* optimized case *)\n  subst r dst. simpl.\n  assert (forall r, rs'#r = rs#r).\n    intros. destruct (Reg.eq r rd). subst r. auto. auto. \n  split. eapply match_env_invariant; eauto.\n  split. congruence.\n  split; auto.\n  (* general case *)\n  split.\n  apply match_env_invariant with (rs#rd <- (rs#r)).\n  apply match_env_update_dest; auto. \n  intros. rewrite Regmap.gsspec. destruct (peq r0 rd). congruence. auto. \n  split. congruence. \n  split. intros. apply C. intuition congruence.\n  auto.\nQed.\n\nLemma transl_expr_Eop_correct:\n  forall (le : letenv) (op : operation) (args : exprlist)\n         (vargs : list val) (v : val),\n  eval_exprlist ge sp e m le args vargs ->\n  transl_exprlist_prop le args vargs ->\n  eval_operation ge sp op vargs m = Some v ->\n  transl_expr_prop le (Eop op args) v.\nProof.\n  intros; red; intros. \n(*  assert (PGR: meminj_preserves_globals ge (restrict (as_inj mu) (vis mu))).     \n     rewrite <- restrict_sm_all. \n     eapply restrict_sm_preserves_globals; try eassumption.\n     unfold vis. intuition. *)\n  inv TE.\n(* normal case *) \n  exploit H0; eauto. \n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RR1 [RO1 EXT1]]]]]]]].\n  (*Was: edestruct eval_operation_lessdef...*)\n\n  assert (PGR': meminj_preserves_globals ge (restrict (as_inj mu') (vis mu'))).     \n     rewrite <- restrict_sm_all. \n     eapply restrict_sm_preserves_globals. \n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n      apply MU'. apply MU'. \n      intros b Gb. eapply intern_incr_vis. eapply MU'.\n         unfold vis. rewrite (Glob _ Gb). intuition. \n\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  edestruct eval_operation_inject as [v' []]; try eapply H1. \n    eapply PGR'. \n    eapply restrictI_Some. \n      apply local_in_all; try eapply MU'. eassumption.       \n      destruct (local_DomRng _ WD _ _ _ Jsp) as [lS lT].\n        eapply intern_incr_vis; try eapply MU'. \n        unfold vis; rewrite lS. trivial.\n    eapply RR1.\n    eapply inject_restrict; try eassumption. eapply MU'.\n  rewrite eval_shift_stack_operation in H2. simpl in H2. rewrite Int.add_zero in H2.\n\n  exists (rs1#rd <- v'); exists tm1.\n  exists mu'. split. assumption. \n(* Exec *)\n  split. eapply corestep_star_trans. eexact EX1.\n  eapply corestep_star_one. eapply rtl_corestep_exec_Iop; eauto.\n  rewrite (@eval_operation_preserved CminorSel.fundef _ _ _ ge tge). eauto.\n  exact symbols_preserved. \n(* Match-env *)\n  split. eauto with rtlg.\n(* Result reg *)\n  split. rewrite Regmap.gss. auto.\n(* Other regs *)\n  split. intros. rewrite Regmap.gso. auto. intuition congruence.\n(* Mem *)\n  auto.\nQed.\n\nLemma transl_expr_Eload_correct:\n  forall (le : letenv) (chunk : memory_chunk) (addr : Op.addressing)\n         (args : exprlist) (vargs : list val) (vaddr v : val),\n  eval_exprlist ge sp e m le args vargs ->\n  transl_exprlist_prop le args vargs ->\n  Op.eval_addressing ge sp addr vargs = Some vaddr ->\n  Mem.loadv chunk m vaddr = Some v ->\n  transl_expr_prop le (Eload chunk addr args) v.\nProof.\n  intros; red; intros.\n  inv TE.\n  exploit H0; eauto. \n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RES1 [OTHER1 EXT1]]]]]]]].\n  (*Was: edestruct eval_addressing_lessdef as [vaddr' []]; eauto.*)\n\n  assert (PGR': meminj_preserves_globals ge (restrict (as_inj mu') (vis mu'))).     \n     rewrite <- restrict_sm_all. \n     eapply restrict_sm_preserves_globals. \n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n      apply MU'. apply MU'. \n      intros b Gb. eapply intern_incr_vis. eapply MU'.\n         unfold vis. rewrite (Glob _ Gb). intuition. \n\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  edestruct eval_addressing_inject as [vaddr' [? ?]]; try eapply RES1. \n    eapply PGR'.\n    eapply restrictI_Some. \n      apply local_in_all; try eapply MU'. eassumption.       \n      destruct (local_DomRng _ WD _ _ _ Jsp) as [lS lT].\n        eapply intern_incr_vis; try eapply MU'. \n        unfold vis; rewrite lS. trivial.\n    eapply H1.\n    \n  rewrite shift_stack_addressing_zero in H3; simpl in H3.\n  edestruct Mem.loadv_inject as [v' []].\n    eapply inject_restrict. eapply EXT1. eapply MU'.\n    eassumption.\n    eassumption. \n  exists (rs1#rd <- v'); exists tm1; exists mu'.\n  split. assumption. \n(* Exec *)\n  split. eapply corestep_star_trans. eexact EX1.\n    eapply corestep_star_one.\n      eapply rtl_corestep_exec_Iload; try eassumption. \n    rewrite (eval_addressing_preserved ge). assumption.\n       exact symbols_preserved.\n(* Match-env *)\n  split. eauto with rtlg. \n(* Result *)\n  split. rewrite Regmap.gss. auto.\n(* Other regs *)\n  split. intros. rewrite Regmap.gso. auto. intuition congruence.\n(* Mem *)\n  auto. \nQed.\n\nLemma transl_expr_Econdition_correct:\n  forall (le : letenv) (a: condexpr) (ifso ifnot : expr)\n         (va : bool) (v : val),\n  eval_condexpr ge sp e m le a va ->\n  transl_condexpr_prop le a va ->\n  eval_expr ge sp e m le (if va then ifso else ifnot) v ->\n  transl_expr_prop le (if va then ifso else ifnot) v ->\n  transl_expr_prop le (Econdition a ifso ifnot) v.\nProof.\n  intros; red; intros; inv TE.\n  exploit H0; eauto. \n     simpl in OBS. apply OBS.\n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [OTHER1 EXT1]]]]]]].\n  assert (tr_expr f.(fn_code) map pr (if va then ifso else ifnot) (if va then ntrue else nfalse) nd rd dst).\n    destruct va; auto.\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  exploit H2; try eapply EXT1. \n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n       eapply MU'. eapply MU'.\n       { red. exists spb, spb'. split. eassumption. \n           split. reflexivity. \n           eapply MU'. eassumption. }\n       eapply MU'. eapply MU'. eapply MU'. \n       intros b Gb. \n         assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply MU'.  \n         rewrite <- FRG. apply (Glob _ Gb). \n         destruct va; eapply OBS.\n     eauto. \n     eauto.\n     eassumption. \n  intros [rs2 [tm2 [mu'' [MU'' [EX2 [ME2 [RES2 [OTHER2 EXT2]]]]]]]].\n  exists rs2; exists tm2, mu''.\n  split. \n    intuition.\n    eapply intern_incr_trans; eassumption.\n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply corestep_plus_fwd. eassumption.\n    eapply gsep_trans'; eassumption.\n    eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply corestep_plus_fwd. eassumption.\n             eapply corestep_star_fwd. eassumption.  \n (* Exec *)\n  split. eapply corestep_star_trans.\n           apply corestep_plus_star. eexact EX1. eexact EX2.\n(* Match-env *)\n  split. assumption.\n(* Result value *)\n  split. assumption.\n(* Other regs *)\n  split. intros. transitivity (rs1#r); auto.\n(* Mem *)\n  auto.\nQed.\n\nLemma transl_expr_Elet_correct:\n  forall (le : letenv) (a1 a2 : expr) (v1 v2 : val),\n  eval_expr ge sp e m le a1 v1 ->\n  transl_expr_prop le a1 v1 ->\n  eval_expr ge sp e m (v1 :: le) a2 v2 ->\n  transl_expr_prop (v1 :: le) a2 v2 ->\n  transl_expr_prop le (Elet a1 a2) v2.\nProof.\n  intros; red; intros; inv TE. \n  exploit H0; eauto. eapply OBS.\n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RES1 [OTHER1 EXT1]]]]]]]].\n  assert (map_wf (add_letvar map r)).\n    eapply add_letvar_wf; eauto.\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  exploit H2; try eapply EXT1. \n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n       eapply MU'. eapply MU'.\n       { red. exists spb, spb'. split. eassumption. \n           split. reflexivity. \n           eapply MU'. eassumption. }\n       eapply MU'. eapply MU'. eapply MU'. \n       intros b Gb. \n         assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply MU'.  \n         rewrite <- FRG. apply (Glob _ Gb). \n       eapply OBS.\n     eauto. \n     eauto.\n     eapply match_env_bind_letvar; eauto.\n  intros [rs2 [tm2 [mu'' [MU'' [EX2 [ME3 [RES2 [OTHER2 EXT2]]]]]]]].\n  exists rs2; exists tm2, mu''.\n  split. \n  intuition.\n  eapply intern_incr_trans; eassumption. \n  eapply inject_separated_intern_incr_fwd; try eassumption.\n         eapply corestep_star_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n  eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply corestep_star_fwd. eassumption.\n             eapply corestep_star_fwd. eassumption.\n(* Exec *)\n  split. eapply corestep_star_trans. eexact EX1. eexact EX2. (* auto.*)\n(* Match-env *)\n  split. eapply match_env_unbind_letvar; eauto.\n(* Result *)\n  split. assumption.\n(* Other regs *)\n  split. intros. transitivity (rs1#r0); auto.\n(* Mem *)\n  auto.\nQed.\n\nLemma transl_expr_Eletvar_correct:\n  forall (le : list val) (n : nat) (v : val),\n  nth_error le n = Some v ->\n  transl_expr_prop le (Eletvar n) v.\nProof.\n  intros; red; intros; inv TE.\n  exploit tr_move_correct; eauto. intros [rs1 [EX1 [RES1 OTHER1]]].\n  exists rs1; exists tm, mu.\n  split. clear H2. intuition. \n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply gsep_refl.\n\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.      \n(* Exec *)\n  split. eexact EX1.\n(* Match-env *)\n  split. \n  destruct H2 as [[A B] | [A B]].\n  subst r dst; simpl. \n  apply match_env_invariant with rs. auto.\n  intros. destruct (Reg.eq r rd). subst r. auto. auto.\n  apply match_env_invariant with (rs#rd <- (rs#r)).\n  apply match_env_update_dest; auto.\n  eapply match_env_find_letvar; eauto.\n  intros. rewrite Regmap.gsspec. destruct (peq r0 rd); auto.\n  congruence.\n(* Result *)\n  split. rewrite RES1. eapply match_env_find_letvar; eauto. \n(* Other regs *)\n  split. intros. \n  destruct H2 as [[A B] | [A B]].\n  destruct (Reg.eq r0 rd); subst; auto.\n  apply OTHER1. intuition congruence.\n(* Mem *)\n  auto.\nQed.\n\nLemma transl_expr_Ebuiltin_correct:\n  forall le ef al vl v,\n  eval_exprlist ge sp e m le al vl ->\n  transl_exprlist_prop le al vl ->\n  external_call ef ge vl m E0 v m ->\n  transl_expr_prop le (Ebuiltin ef al) v.\nProof.\n  intros; red; intros. \n  assert (PGR: meminj_preserves_globals ge (restrict (as_inj mu) (vis mu))).     \n     rewrite <- restrict_sm_all. \n     eapply restrict_sm_preserves_globals; try eassumption.\n     unfold vis. intuition. \n  inv TE.\n  simpl in OBS.\n  exploit H0; eauto. eapply OBS.\n  destruct OBS as [isHLP SEL]. \n  assert (OBS :~ observableEF hf ef) by solve [eapply EFhelpers; trivial]. \n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RR1 [RO1 EXT1]]]]]]]].\n  (*WAS: exploit external_call_mem_extends; eauto. \n        intros [v' [tm2 [A [B [C [D E]]]]]].*)\n  destruct MU' as [INC [SEP [GSEP [LOCALLOC' [WD' [SMV' RC']]]]]].\n  exploit (inlineable_extern_inject _ _ GDE_lemma);\n       try eapply RR1; try eapply H1; try eassumption.\n     apply symbols_preserved.\n     assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC. \n        rewrite <- FF; apply Glob.\n     eapply intern_incr_meminj_preserves_globals_as_inj.\n         apply WD. split; assumption. \n     assumption. assumption. \n (* exploit external_call_mem_inject; eauto. \n        intros [j' [v' [tm2 [A [B [C [D [E [F G]]]]]]]]].*)\n     intros [mu'' [vres' [tm' [EC [VINJ [MINJ' [UNMAPPED [OUTOFREACH \n           [INCR [SEPARATED [LOCALLOC [WD'' [SMV'' RC'']]]]]]]]]]]]].\n  exists (rs1#rd <- vres'); exists tm', mu''.\n  split. intuition.\n    eapply intern_incr_trans. eassumption. eassumption.\n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply corestep_star_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n    eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply corestep_star_fwd. eassumption.\n             eapply external_call_mem_forward; eassumption.\n(* Exec *)\n  split. eapply corestep_star_trans. eexact EX1.\n         apply corestep_star_one. eapply rtl_corestep_exec_Ibuiltin; try eassumption. \n(*  eapply external_call_symbols_preserved; eauto. exact symbols_preserved. exact varinfo_preserved.*)\n(* Match-env *)\n         split. eapply match_env_update_dest; try eassumption.\n         \n     eapply match_env_inject_incr; try eassumption.\n     apply intern_incr_restrict; eassumption. \n(* Result reg *)\n  split. intros. rewrite Regmap.gss. auto.\n(* Other regs *)\n  split. intros. rewrite Regmap.gso. auto. intuition congruence.\n(* Mem *)\n  assumption. \nQed.\n\nLemma silentD_Eexternal name ef al b:  forall\n  (SIL: silent hf ge (Eexternal name (ef_sig ef) al))\n  (FS: Genv.find_symbol ge name = Some b)\n  (FFP: Genv.find_funct_ptr ge b = Some (External ef)),\n  silentExprList hf ge al /\\ EFisHelper hf ef.\nProof. intros.  \nunfold silent in SIL.\nrewrite FS, FFP in SIL.\nintuition.\nQed.\n(*\nLemma silentD_Eexternal name ef al b:  forall\n  (SIL: silent hf ge (Eexternal name (ef_sig ef) al))\n  (FS: Genv.find_symbol ge name = Some b)\n  (FFP: Genv.find_funct_ptr ge b = Some (External ef)),\n  silentExprList hf ge al /\\ observableEF hf ef = false\n   /\\ forall (args : list val) (m : mem),\n             BuiltinEffect ge ef args m = EmptyEffect.\nProof. intros.  \nunfold silent in SIL.\nrewrite FS, FFP in SIL.\nintuition.\nQed.\n*)\nLemma transl_expr_Eexternal_correct:\n  forall le id sg al b ef vl v,\n  Genv.find_symbol ge id = Some b ->\n  Genv.find_funct_ptr ge b = Some (External ef) ->\n  ef_sig ef = sg ->\n  eval_exprlist ge sp e m le al vl ->\n  transl_exprlist_prop le al vl ->\n  external_call ef ge vl m E0 v m ->\n  transl_expr_prop le (Eexternal id sg al) v.\nProof.\n  intros; red; intros. inv TE.\n  destruct (silentD_Eexternal _ _ _ _ OBS H H0)\n    as [SilentArgs isHLP]; clear OBS.\n  assert (OBS := EFhelpers _ _ isHLP). \n  exploit H3; eauto. \n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RR1 [RO1 EXT1]]]]]]]].\n  assert (PG': meminj_preserves_globals ge (as_inj mu')).     \n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n      apply MU'. apply MU'.\n  destruct MU' as [INC [SEP [GSEP [LOCALLOC' [WD' [SMV' RC']]]]]].\n  exploit (inlineable_extern_inject _ _ GDE_lemma);\n       try eapply RR1; try eapply H1; try eassumption.\n     apply symbols_preserved.\n     assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC. \n        rewrite <- FF; apply Glob.\n  intros [mu'' [vres' [tm' [EC [VINJ [MINJ' [UNMAPPED [OUTOFREACH \n           [INCR [SEPARATED [LOCALLOC [WD'' [SMV'' RC'']]]]]]]]]]]]].\n  eexists; exists tm', mu''. \n  split. intuition.\n     eapply intern_incr_trans; eassumption.\n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply corestep_star_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n     eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply corestep_star_fwd. eassumption.\n             eapply external_call_mem_forward; eassumption.\n  exploit function_ptr_translated; eauto. simpl. intros [tf [P Q]]. inv Q. \n(*  exists (rs1#rd <- vres'); exists tm2.*)\n(* Exec *)\n  split. eapply corestep_star_trans. eexact EX1.\n    eapply corestep_star_trans. \n     apply corestep_star_one. eapply rtl_corestep_exec_Icall; eauto.\n        simpl. rewrite symbols_preserved. rewrite H. eauto. auto.\n    eapply corestep_star_trans. \n     apply corestep_star_one. eapply rtl_corestep_exec_function_external.\n       assumption. eassumption.\n     (*  eapply external_call_symbols_preserved; eauto. exact symbols_preserved. exact varinfo_preserved.*)\n     apply corestep_star_one. apply rtl_corestep_exec_return. \n(* Match-env *)\n  split. eapply match_env_update_dest; try eassumption.\n     eapply match_env_inject_incr; try eassumption.\n     apply intern_incr_restrict; eassumption. \n(* Result reg *)\n   split. rewrite Regmap.gss. auto.\n(* Other regs *)\n  split. intros. rewrite Regmap.gso. auto. intuition congruence.\n(* Mem *)\n  auto.\nQed.\n\nLemma transl_exprlist_Enil_correct:\n  forall (le : letenv),\n  transl_exprlist_prop le Enil nil.\nProof.\n  intros; red; intros; inv TE.\n  exists rs; exists tm, mu.\n  split. intuition. \n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply gsep_refl.\n\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.     \n  split. apply corestep_star_zero.\n  split. assumption.\n  split. constructor.\n  auto.\nQed.\n\nLemma transl_exprlist_Econs_correct:\n  forall (le : letenv) (a1 : expr) (al : exprlist) (v1 : val)\n         (vl : list val),\n  eval_expr ge sp e m le a1 v1 ->\n  transl_expr_prop le a1 v1 ->\n  eval_exprlist ge sp e m le al vl ->\n  transl_exprlist_prop le al vl ->\n  transl_exprlist_prop le (Econs a1 al) (v1 :: vl).\nProof.\n  intros; red; intros; inv TE.\n  exploit H0; eauto. eapply OBS.\n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RES1 [OTHER1 EXT1]]]]]]]].\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  exploit H2; try eapply EXT1.\n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n       eapply MU'. eapply MU'.\n       { red. exists spb, spb'. split. eassumption. \n           split. reflexivity. \n           eapply MU'. eassumption. }\n       eapply MU'. eapply MU'. eapply MU'. \n       intros b Gb. \n         assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply MU'.  \n         rewrite <- FRG. apply (Glob _ Gb). \n     eapply OBS.\n     eauto. \n     eauto.\n     eassumption. \n  intros [rs2 [tm2 [mu'' [MU'' [EX2 [ME2 [RES2 [OTHER2 EXT2]]]]]]]].\n  exists rs2; exists tm2, mu''.\n  split. intuition.\n    eapply intern_incr_trans; eassumption. \n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply corestep_star_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n    eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply corestep_star_fwd. eassumption.\n             eapply corestep_star_fwd. eassumption.\n(* Exec *)\n  split. eapply corestep_star_trans. eexact EX1. eexact EX2. \n(* Match-env *)\n  split. assumption.\n(* Results *)\n  split. simpl. constructor. rewrite OTHER2. \n     eapply val_inject_incr; try eassumption. \n     eapply intern_incr_restrict. eapply MU''. eapply MU''.\n    simpl; tauto.\n  auto.\n(* Other regs *)\n  split. intros. transitivity (rs1#r).\n  apply OTHER2; auto. simpl; tauto. \n  apply OTHER1; auto.\n(* Mem *)\n  auto.\nQed.\n\nLemma transl_condexpr_CEcond_correct:\n  forall le cond al vl vb,\n  eval_exprlist ge sp e m le al vl ->\n  transl_exprlist_prop le al vl ->\n  eval_condition cond vl m = Some vb ->\n  transl_condexpr_prop le (CEcond cond al) vb.\nProof.\n  intros; red; intros. inv TE. \n  exploit H0; eauto. \n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RES1 [OTHER1 EXT1]]]]]]]].\n  exists rs1; exists tm1, mu'.\n  split. assumption.\n(* Exec *)\n  split. eapply corestep_star_plus_trans. eexact EX1.\n      eapply corestep_plus_one. eapply rtl_corestep_exec_Icond. eauto. \n      (*eapply eval_condition_lessdef; eauto.*)\n    eapply eval_condition_inject; eauto. \n    eapply inject_restrict; eauto.\n     eapply MU'.\n    auto.\n(* Match-env *)\n  split. assumption.\n(* Other regs *)\n  split. assumption. \n(* Mem *)\n  auto.\nQed.\n\nLemma transl_condexpr_CEcondition_correct:\n  forall le a b c va v,\n  eval_condexpr ge sp e m le a va ->\n  transl_condexpr_prop le a va ->\n  eval_condexpr ge sp e m le (if va then b else c) v ->\n  transl_condexpr_prop le (if va then b else c) v ->\n  transl_condexpr_prop le (CEcondition a b c) v.\nProof.\n  intros; red; intros. inv TE. \n  exploit H0; eauto. eapply OBS.\n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [OTHER1 EXT1]]]]]]].\n  assert (tr_condition (fn_code f) map pr (if va then b else c) (if va then n2 else n3) ntrue nfalse).\n    destruct va; auto.\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  exploit H2; try eapply EXT1.\n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n       eapply MU'. eapply MU'.\n       { red. exists spb, spb'. split. eassumption. \n           split. reflexivity. \n           eapply MU'. eassumption. }\n       eapply MU'. eapply MU'. eapply MU'. \n       intros bb Gb. \n         assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply MU'.  \n         rewrite <- FRG. apply (Glob _ Gb). \n       destruct va; eapply OBS.\n     eauto. \n     eauto.\n     eassumption. \n  intros [rs2 [tm2 [mu'' [MU'' [EX2 [ME2 [OTHER2 EXT2]]]]]]].\n  exists rs2; exists tm2, mu''.\n  split. intuition.\n    eapply intern_incr_trans; eassumption. \n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply corestep_plus_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n    eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply corestep_plus_fwd. eassumption.\n             eapply corestep_plus_fwd. eassumption.\n(* Exec *)\n  split. eapply corestep_plus_trans. eexact EX1. eexact EX2.\n(* Match-env *)\n  split. assumption.\n(* Other regs *)\n  split. intros. rewrite OTHER2; auto. \n(* Mem *)\n  auto.\nQed.\n\nLemma transl_condexpr_CElet_correct:\n  forall le a b v1 v2,\n  eval_expr ge sp e m le a v1 ->\n  transl_expr_prop le a v1 ->\n  eval_condexpr ge sp e m (v1 :: le) b v2 ->\n  transl_condexpr_prop (v1 :: le) b v2 ->\n  transl_condexpr_prop le (CElet a b) v2.\nProof.\n  intros; red; intros. inv TE. \n  exploit H0; eauto. eapply OBS.\n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RES1 [OTHER1 EXT1]]]]]]]].\n  assert (map_wf (add_letvar map r)).\n    eapply add_letvar_wf; eauto. \n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  exploit H2; try eapply EXT1.\n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n       eapply MU'. eapply MU'.\n       { red. exists spb, spb'. split. eassumption. \n           split. reflexivity. \n           eapply MU'. eassumption. }\n       eapply MU'. eapply MU'. eapply MU'. \n       intros bb Gb. \n         assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply MU'.  \n         rewrite <- FRG. apply (Glob _ Gb).\n       eapply OBS. \n     eauto. \n     eauto.\n     eapply match_env_bind_letvar; eauto. \n  intros [rs2 [tm2 [mu'' [MU'' [EX2 [ME3 [OTHER2 EXT2]]]]]]].\n  exists rs2; exists tm2, mu''.\n  split. intuition.\n    eapply intern_incr_trans; eassumption. \n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply corestep_star_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n    eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply corestep_star_fwd. eassumption.\n             eapply corestep_plus_fwd. eassumption.\n(* Exec *)\n  split. eapply corestep_star_plus_trans. eexact EX1. eexact EX2.\n(* Match-env *)\n  split. eapply match_env_unbind_letvar; eauto.\n(* Other regs *)\n  split. intros. rewrite OTHER2; auto. \n(* Mem *)\n  auto.\nQed.\n\nTheorem transl_expr_correct:\n  forall le a v,\n  eval_expr ge sp e m le a v ->\n  transl_expr_prop le a v.\nProof\n  (eval_expr_ind3 ge sp e m\n     transl_expr_prop\n     transl_exprlist_prop\n     transl_condexpr_prop\n     transl_expr_Evar_correct\n     transl_expr_Eop_correct\n     transl_expr_Eload_correct\n     transl_expr_Econdition_correct\n     transl_expr_Elet_correct\n     transl_expr_Eletvar_correct\n     transl_expr_Ebuiltin_correct\n     transl_expr_Eexternal_correct\n     transl_exprlist_Enil_correct\n     transl_exprlist_Econs_correct\n     transl_condexpr_CEcond_correct\n     transl_condexpr_CEcondition_correct\n     transl_condexpr_CElet_correct).\n\nTheorem transl_exprlist_correct:\n  forall le a v,\n  eval_exprlist ge sp e m le a v ->\n  transl_exprlist_prop le a v.\nProof\n  (eval_exprlist_ind3 ge sp e m\n     transl_expr_prop\n     transl_exprlist_prop\n     transl_condexpr_prop\n     transl_expr_Evar_correct\n     transl_expr_Eop_correct\n     transl_expr_Eload_correct\n     transl_expr_Econdition_correct\n     transl_expr_Elet_correct\n     transl_expr_Eletvar_correct\n     transl_expr_Ebuiltin_correct\n     transl_expr_Eexternal_correct\n     transl_exprlist_Enil_correct\n     transl_exprlist_Econs_correct\n     transl_condexpr_CEcond_correct\n     transl_condexpr_CEcondition_correct\n     transl_condexpr_CElet_correct).\n\nTheorem transl_condexpr_correct:\n  forall le a v,\n  eval_condexpr ge sp e m le a v ->\n  transl_condexpr_prop le a v.\nProof\n  (eval_condexpr_ind3 ge sp e m\n     transl_expr_prop\n     transl_exprlist_prop\n     transl_condexpr_prop\n     transl_expr_Evar_correct\n     transl_expr_Eop_correct\n     transl_expr_Eload_correct\n     transl_expr_Econdition_correct\n     transl_expr_Elet_correct\n     transl_expr_Eletvar_correct\n     transl_expr_Ebuiltin_correct\n     transl_expr_Eexternal_correct\n     transl_exprlist_Enil_correct\n     transl_exprlist_Econs_correct\n     transl_condexpr_CEcond_correct\n     transl_condexpr_CEcondition_correct\n     transl_condexpr_CElet_correct).\n\nEnd CORRECTNESS_EXPR.\n\n(*LENB: The same for effect-steps*)\nSection CORRECTNESS_EXPR_EFF.\n\nLemma Efftr_move_correct:\n  forall r1 ns r2 nd cs f sp rs m,\n  tr_move f.(fn_code) ns r1 nd r2 ->\n  exists rs',\n  effstep_star (rtl_eff_sem hf) tge EmptyEffect\n     (RTL_State cs f sp ns rs) m \n     (RTL_State cs f sp nd rs') m /\\\n  rs'#r2 = rs#r1 /\\\n  (forall r, r <> r2 -> rs'#r = rs#r).\nProof.\n  intros. inv H. \n  exists rs; split. eapply effstep_star_zero. auto.\n  exists (rs#r2 <- (rs#r1)); split. \n  apply effstep_star_one. eapply rtl_effstep_exec_Iop. eauto. auto. \n  split. apply Regmap.gss. intros; apply Regmap.gso; auto.\nQed.\n\nLemma Efftransl_switch_correct:\n  forall j cs sp e m f map r nexits t ns,\n  tr_switch f.(fn_code) map r nexits t ns ->\n  forall rs i act,\n  rs#r = Vint i ->\n  map_wf map ->\n  match_env j map e nil rs ->\n  comptree_match i t = Some act ->\n  exists nd, exists rs',\n  effstep_star (rtl_eff_sem hf) tge EmptyEffect\n        (RTL_State cs f sp ns rs) m (RTL_State cs f sp nd rs') m /\\\n  nth_error nexits act = Some nd /\\\n  match_env j map e nil rs'.\nProof.\n  Opaque Int.sub.\n  induction 1; simpl; intros.\n(* action *)\n  inv H3. exists n; exists rs; intuition.\n  apply effstep_star_zero.\n(* ifeq *)\n  caseEq (Int.eq i key); intro EQ; rewrite EQ in H5.\n  inv H5. exists nfound; exists rs; intuition.\n  apply effstep_star_one. eapply rtl_effstep_exec_Icond with (b := true); eauto. \n  simpl. rewrite H2. simpl. congruence.\n  exploit IHtr_switch; eauto. intros [nd1 [rs1 [EX [NTH ME]]]].\n  exists nd1; exists rs1; intuition.\n  eapply effstep_star_trans'. \n    eapply effstep_star_one. eapply rtl_effstep_exec_Icond with (b := false); eauto.  \n      simpl. rewrite H2. simpl. congruence. eexact EX.\n   extensionality b; extensionality z. rewrite absoption_orb; trivial.\n(* iflt *)\n  caseEq (Int.ltu i key); intro EQ; rewrite EQ in H5.\n  exploit IHtr_switch1; eauto. intros [nd1 [rs1 [EX [NTH ME]]]].\n  exists nd1; exists rs1; intuition.\n  eapply effstep_star_trans'. \n    eapply effstep_star_one. eapply rtl_effstep_exec_Icond with (b := true); eauto.  \n    simpl. rewrite H2. simpl. congruence. eexact EX.\n    extensionality b; extensionality z. rewrite absoption_orb; trivial.\n  exploit IHtr_switch2; eauto. intros [nd1 [rs1 [EX [NTH ME]]]].\n  exists nd1; exists rs1; intuition.\n  eapply effstep_star_trans'. \n    eapply effstep_star_one. eapply rtl_effstep_exec_Icond with (b := false); eauto. \n    simpl. rewrite H2. simpl. congruence. eexact EX.\n    extensionality b; extensionality z. rewrite absoption_orb; trivial.\n(* jumptable *)\n  set (rs1 := rs#rt <- (Vint(Int.sub i ofs))).\n  assert (ME1: match_env j map e nil rs1).\n    unfold rs1. eauto with rtlg.\n  assert (EX1: RTL_effstep hf tge EmptyEffect (RTL_State cs f sp n rs) m (RTL_State cs f sp n1 rs1) m).\n    eapply rtl_effstep_exec_Iop; eauto. \n    predSpec Int.eq Int.eq_spec ofs Int.zero; simpl.\n    rewrite H10. rewrite Int.sub_zero_l. congruence.\n    rewrite H6. simpl. rewrite <- Int.sub_add_opp. auto. \n  caseEq (Int.ltu (Int.sub i ofs) sz); intro EQ; rewrite EQ in H9.\n  exploit H5; eauto. intros [nd [A B]].\n  exists nd; exists rs1; intuition.\n  eapply effstep_star_trans'. \n    eapply effstep_star_one. eexact EX1.\n    eapply effstep_star_trans. \n      eapply effstep_star_one. eapply rtl_effstep_exec_Icond with (b := true); eauto.  \n      simpl. unfold rs1. rewrite Regmap.gss. simpl. congruence.  \n    apply effstep_star_one. eapply rtl_effstep_exec_Ijumptable; eauto. unfold rs1. apply Regmap.gss.    \n    extensionality b; extensionality z. rewrite absoption_orb; trivial.\n  exploit (IHtr_switch rs1); eauto. unfold rs1. rewrite Regmap.gso; auto.\n  intros [nd [rs' [EX [NTH ME]]]].\n  exists nd; exists rs'; intuition.\n  eapply effstep_star_trans'. \n    eapply effstep_star_one. eexact EX1.\n    eapply effstep_star_trans. \n      eapply effstep_star_one. eapply rtl_effstep_exec_Icond with (b := false); eauto. \n      simpl. unfold rs1. rewrite Regmap.gss. simpl. congruence.\n    eexact EX.\n  extensionality b; extensionality z. rewrite absoption_orb; trivial. \nQed.\n\nVariable sp: val.\nVariable e: env.\nVariable m: mem.\n\nDefinition Efftransl_expr_prop \n     (le: letenv) (a: expr) (v: val) : Prop :=\n  forall mu tm cs f map pr ns nd rd rs dst\n (*NEW:*)(PG: meminj_preserves_globals ge (as_inj mu))\n         sp' (SP: sp_preserved (local_of mu) sp sp')\n         (WD: SM_wd mu) (SMV: sm_valid mu m tm) \n         (RC: REACH_closed m (vis mu))\n         (Glob: forall b, isGlobalBlock ge b = true -> \n                  frgnBlocksSrc mu b = true)\n         (OBS: silent hf ge a)\n\n    (MWF: map_wf map)\n    (TE: tr_expr f.(fn_code) map pr a ns nd rd dst)\n    (ME: match_env (restrict (as_inj mu) (vis mu)) map e le rs)\n    (EXT: Mem.inject (as_inj mu) m tm),\n  exists rs', exists tm', exists mu',\n  (intern_incr mu mu'\n  /\\ sm_inject_separated mu mu' m tm\n  /\\ globals_separate ge mu mu'\n  /\\ sm_locally_allocated mu mu' m tm m tm'\n  /\\ SM_wd mu'\n  /\\ sm_valid mu' m tm'\n  /\\ REACH_closed m (vis mu'))\n  /\\ effstep_star (rtl_eff_sem hf) tge EmptyEffect\n        (RTL_State cs f sp' ns rs) tm (RTL_State cs f sp' nd rs') tm'\n  /\\ match_env (restrict (as_inj mu') (vis mu')) map (set_optvar dst v e) le rs'\n  /\\ val_inject (restrict (as_inj mu') (vis mu')) v rs'#rd\n  /\\ (forall r, In r pr -> rs'#r = rs#r)\n  /\\ Mem.inject (as_inj mu') m tm'.\n\nDefinition Efftransl_exprlist_prop \n     (le: letenv) (al: exprlist) (vl: list val) : Prop :=\n  forall mu tm cs f map pr ns nd rl rs\n (*NEW:*)(PG: meminj_preserves_globals ge (as_inj mu))\n         sp' (SP: sp_preserved  (local_of mu) sp sp')\n         (WD: SM_wd mu) (SMV: sm_valid mu m tm)\n         (RC: REACH_closed m (vis mu))\n         (Glob: forall b, isGlobalBlock ge b = true -> \n                  frgnBlocksSrc mu b = true)\n         (OBS: silentExprList hf ge al)\n\n    (MWF: map_wf map)\n    (TE: tr_exprlist f.(fn_code) map pr al ns nd rl)\n    (ME: match_env (restrict (as_inj mu) (vis mu)) map e le rs)\n    (EXT: Mem.inject (as_inj mu) m tm),\n  exists rs', exists tm', exists mu',\n  (intern_incr mu mu'\n   /\\ sm_inject_separated mu mu' m tm\n  /\\ globals_separate ge mu mu'\n  /\\ sm_locally_allocated mu mu' m tm m tm'\n  /\\ SM_wd mu'\n  /\\ sm_valid mu' m tm'\n  /\\ REACH_closed m (vis mu'))\n  /\\ effstep_star (rtl_eff_sem hf) tge EmptyEffect\n       (RTL_State cs f sp' ns rs) tm (RTL_State cs f sp' nd rs') tm'\n  /\\ match_env (restrict (as_inj mu') (vis mu')) map e le rs'\n  /\\ val_list_inject (restrict (as_inj mu') (vis mu')) vl rs'##rl\n  /\\ (forall r, In r pr -> rs'#r = rs#r)\n  /\\ Mem.inject (as_inj mu') m tm'.\n\nDefinition Efftransl_condexpr_prop \n     (le: letenv) (a: condexpr) (v: bool) : Prop :=\n  forall mu tm cs f map pr ns ntrue nfalse rs\n (*NEW:*)(PG: meminj_preserves_globals ge (as_inj mu))\n         sp' (SP: sp_preserved (local_of mu) sp sp')\n         (WD: SM_wd mu) (SMV: sm_valid mu m tm)\n         (RC: REACH_closed m (vis mu))\n         (Glob: forall b, isGlobalBlock ge b = true -> \n                  frgnBlocksSrc mu b = true)\n         (OBS: silentCondExpr hf ge a)\n\n    (MWF: map_wf map)\n    (TE: tr_condition f.(fn_code) map pr a ns ntrue nfalse)\n    (ME: match_env (restrict (as_inj mu) (vis mu)) map e le rs)\n    (EXT: Mem.inject (as_inj mu) m tm),\n  exists rs', exists tm', exists mu',\n   (intern_incr mu mu'\n  /\\ sm_inject_separated mu mu' m tm\n  /\\ globals_separate ge mu mu'\n  /\\ sm_locally_allocated mu mu' m tm m tm'\n  /\\ SM_wd mu'\n  /\\ sm_valid mu' m tm'\n  /\\ REACH_closed m (vis mu'))\n  /\\ effstep_plus (rtl_eff_sem hf) tge EmptyEffect\n       (RTL_State cs f sp' ns rs) tm (RTL_State cs f sp' (if v then ntrue else nfalse) rs') tm'\n  /\\ match_env (restrict (as_inj mu') (vis mu')) map e le rs'\n  /\\ (forall r, In r pr -> rs'#r = rs#r)\n  /\\ Mem.inject (as_inj mu') m tm'.\n\n(** The correctness of the translation is a huge induction over\n  the Cminor evaluation derivation for the source program.  To keep\n  the proof manageable, we put each case of the proof in a separate\n  lemma.  There is one lemma for each Cminor evaluation rule.\n  It takes as hypotheses the premises of the Cminor evaluation rule,\n  plus the induction hypotheses, that is, the [transl_expr_prop], etc,\n  corresponding to the evaluations of sub-expressions or sub-statements. *)\n\nLemma Efftransl_expr_Evar_correct:\n  forall (le : letenv) (id : positive) (v: val),\n  e ! id = Some v ->\n  Efftransl_expr_prop le (Evar id) v.\nProof.\n  intros; red; intros. inv TE.\n  exploit match_env_find_var; eauto. intro EQ.\n  exploit Efftr_move_correct; eauto. intros [rs' [A [B C]]]. \n  exists rs'; exists tm;  exists mu. \n    split. simpl. trivial.\n    split. apply intern_incr_refl.\n    split. apply sm_inject_separated_same_sminj.\n    split. apply gsep_refl.\n    split. apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.\n      eauto.\n  split. eauto. \n  destruct H2 as [[D E] | [D E]].\n  (* optimized case *)\n  subst r dst. simpl.\n  assert (forall r, rs'#r = rs#r).\n    intros. destruct (Reg.eq r rd). subst r. auto. auto. \n  split. eapply match_env_invariant; eauto.\n  split. congruence.\n  split; auto.\n  (* general case *)\n  split.\n  apply match_env_invariant with (rs#rd <- (rs#r)).\n  apply match_env_update_dest; auto. \n  intros. rewrite Regmap.gsspec. destruct (peq r0 rd). congruence. auto. \n  split. congruence. \n  split. intros. apply C. intuition congruence.\n  auto.\nQed.\n\nLemma Efftransl_expr_Eop_correct:\n  forall (le : letenv) (op : operation) (args : exprlist)\n         (vargs : list val) (v : val),\n  eval_exprlist ge sp e m le args vargs ->\n  Efftransl_exprlist_prop le args vargs ->\n  eval_operation ge sp op vargs m = Some v ->\n  Efftransl_expr_prop le (Eop op args) v.\nProof.\n  intros; red; intros. inv TE.\n(* normal case *) \n  exploit H0; eauto.\n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RR1 [RO1 EXT1]]]]]]]].\n  (*Was: edestruct eval_operation_lessdef...*)\n\n  assert (PGR': meminj_preserves_globals ge (restrict (as_inj mu') (vis mu'))).     \n     rewrite <- restrict_sm_all. \n     eapply restrict_sm_preserves_globals. \n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n      apply MU'. apply MU'. \n      intros b Gb. eapply intern_incr_vis. eapply MU'.\n         unfold vis. rewrite (Glob _ Gb). intuition. \n\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  edestruct eval_operation_inject as [v' []]; try eapply H1. \n    eapply PGR'. \n    eapply restrictI_Some. \n      apply local_in_all; try eapply MU'. eassumption.       \n      destruct (local_DomRng _ WD _ _ _ Jsp) as [lS lT].\n        eapply intern_incr_vis; try eapply MU'. \n        unfold vis; rewrite lS. trivial.\n    eapply RR1.\n    eapply inject_restrict; try eassumption. eapply MU'.\n  rewrite eval_shift_stack_operation in H2. simpl in H2. rewrite Int.add_zero in H2.\n\n  exists (rs1#rd <- v'); exists tm1.\n  exists mu'. split. assumption. \n(* Exec *)\n  split. eapply effstep_star_trans'. eexact EX1.\n    eapply effstep_star_one. eapply rtl_effstep_exec_Iop; eauto.\n      rewrite (@eval_operation_preserved CminorSel.fundef _ _ _ ge tge). eauto.\n      exact symbols_preserved.\n    extensionality b; extensionality z. rewrite absoption_orb; trivial. \n(* Match-env *)\n  split. eauto with rtlg.\n(* Result reg *)\n  split. rewrite Regmap.gss. auto.\n(* Other regs *)\n  split. intros. rewrite Regmap.gso. auto. intuition congruence.\n(* Mem *)\n  auto.\nQed.\n\nLemma Efftransl_expr_Eload_correct:\n  forall (le : letenv) (chunk : memory_chunk) (addr : Op.addressing)\n         (args : exprlist) (vargs : list val) (vaddr v : val),\n  eval_exprlist ge sp e m le args vargs ->\n  Efftransl_exprlist_prop le args vargs ->\n  Op.eval_addressing ge sp addr vargs = Some vaddr ->\n  Mem.loadv chunk m vaddr = Some v ->\n  Efftransl_expr_prop le (Eload chunk addr args) v.\nProof.\n  intros; red; intros. inv TE.\n  exploit H0; eauto. \n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RES1 [OTHER1 EXT1]]]]]]]].\n  (*Was: edestruct eval_addressing_lessdef as [vaddr' []]; eauto.*)\n\n  assert (PGR': meminj_preserves_globals ge (restrict (as_inj mu') (vis mu'))).     \n     rewrite <- restrict_sm_all. \n     eapply restrict_sm_preserves_globals. \n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n      apply MU'. apply MU'. \n      intros b Gb. eapply intern_incr_vis. eapply MU'.\n         unfold vis. rewrite (Glob _ Gb). intuition. \n\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  edestruct eval_addressing_inject as [vaddr' [? ?]]; try eapply RES1. \n    eapply PGR'.\n    eapply restrictI_Some. \n      apply local_in_all; try eapply MU'. eassumption.       \n      destruct (local_DomRng _ WD _ _ _ Jsp) as [lS lT].\n        eapply intern_incr_vis; try eapply MU'. \n        unfold vis; rewrite lS. trivial.\n    eapply H1.\n    \n  rewrite shift_stack_addressing_zero in H3; simpl in H3.\n  edestruct Mem.loadv_inject as [v' []].\n    eapply inject_restrict. eapply EXT1. eapply MU'.\n    eassumption.\n    eassumption. \n  exists (rs1#rd <- v'); exists tm1; exists mu'.\n  split. assumption. \n(* Exec *)\n  split. eapply effstep_star_trans'. eexact EX1.\n    eapply effstep_star_one.\n      eapply rtl_effstep_exec_Iload; try eassumption. \n    rewrite (eval_addressing_preserved ge). assumption.\n       exact symbols_preserved.\n    extensionality b; extensionality z. rewrite absoption_orb; trivial.\n(* Match-env *)\n  split. eauto with rtlg. \n(* Result *)\n  split. rewrite Regmap.gss. auto.\n(* Other regs *)\n  split. intros. rewrite Regmap.gso. auto. intuition congruence.\n(* Mem *)\n  auto. \nQed.\n\nLemma Efftransl_expr_Econdition_correct:\n  forall (le : letenv) (a: condexpr) (ifso ifnot : expr)\n         (va : bool) (v : val),\n  eval_condexpr ge sp e m le a va ->\n  Efftransl_condexpr_prop le a va ->\n  eval_expr ge sp e m le (if va then ifso else ifnot) v ->\n  Efftransl_expr_prop le (if va then ifso else ifnot) v ->\n  Efftransl_expr_prop le (Econdition a ifso ifnot) v.\nProof.\n  intros; red; intros; inv TE.\n  exploit H0; eauto. \n     simpl in OBS. apply OBS.\n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [OTHER1 EXT1]]]]]]].\n  assert (tr_expr f.(fn_code) map pr (if va then ifso else ifnot) (if va then ntrue else nfalse) nd rd dst).\n    destruct va; auto.\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  exploit H2; try eapply EXT1. \n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n       eapply MU'. eapply MU'.\n       { red. exists spb, spb'. split. eassumption. \n           split. reflexivity. \n           eapply MU'. eassumption. }\n       eapply MU'. eapply MU'. eapply MU'. \n       intros b Gb. \n         assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply MU'.  \n         rewrite <- FRG. apply (Glob _ Gb). \n         destruct va; eapply OBS.\n     eauto. \n     eauto.\n     eassumption. \n  intros [rs2 [tm2 [mu'' [MU'' [EX2 [ME2 [RES2 [OTHER2 EXT2]]]]]]]].\n  exists rs2; exists tm2, mu''.\n  split. \n    intuition.\n    eapply intern_incr_trans; eassumption.\n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply effstep_plus_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n    eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply effstep_plus_fwd. eassumption.\n             eapply effstep_star_fwd. eassumption.  \n (* Exec *)\n  split. eapply effstep_star_trans'.\n           apply effstep_plus_star. eexact EX1. eexact EX2.\n    extensionality b; extensionality z. rewrite absoption_orb; trivial.\n(* Match-env *)\n  split. assumption.\n(* Result value *)\n  split. assumption.\n(* Other regs *)\n  split. intros. transitivity (rs1#r); auto.\n(* Mem *)\n  auto.\nQed.\n\nLemma Efftransl_expr_Elet_correct:\n  forall (le : letenv) (a1 a2 : expr) (v1 v2 : val),\n  eval_expr ge sp e m le a1 v1 ->\n  Efftransl_expr_prop le a1 v1 ->\n  eval_expr ge sp e m (v1 :: le) a2 v2 ->\n  Efftransl_expr_prop (v1 :: le) a2 v2 ->\n  Efftransl_expr_prop le (Elet a1 a2) v2.\nProof.\n  intros; red; intros; inv TE. \n  exploit H0; eauto. eapply OBS.\n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RES1 [OTHER1 EXT1]]]]]]]].\n  assert (map_wf (add_letvar map r)).\n    eapply add_letvar_wf; eauto.\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  exploit H2; try eapply EXT1. \n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n       eapply MU'. eapply MU'.\n       { red. exists spb, spb'. split. eassumption. \n           split. reflexivity. \n           eapply MU'. eassumption. }\n       eapply MU'. eapply MU'. eapply MU'. \n       intros b Gb. \n         assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply MU'.  \n         rewrite <- FRG. apply (Glob _ Gb). \n       eapply OBS.\n     eauto. \n     eauto.\n     eapply match_env_bind_letvar; eauto.\n  intros [rs2 [tm2 [mu'' [MU'' [EX2 [ME3 [RES2 [OTHER2 EXT2]]]]]]]].\n  exists rs2; exists tm2, mu''.\n  split. intuition.\n    eapply intern_incr_trans; eassumption.\n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply effstep_star_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n    eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply effstep_star_fwd. eassumption.\n             eapply effstep_star_fwd. eassumption.\n(* Exec *)\n  split. eapply effstep_star_trans'. eexact EX1. eexact EX2. auto.\n(* Match-env *)\n  split. eapply match_env_unbind_letvar; eauto.\n(* Result *)\n  split. assumption.\n(* Other regs *)\n  split. intros. transitivity (rs1#r0); auto.\n(* Mem *)\n  auto.\nQed.\n\nLemma Efftransl_expr_Eletvar_correct:\n  forall (le : list val) (n : nat) (v : val),\n  nth_error le n = Some v ->\n  Efftransl_expr_prop le (Eletvar n) v.\nProof.\n  intros; red; intros; inv TE.\n  exploit Efftr_move_correct; eauto. intros [rs1 [EX1 [RES1 OTHER1]]].\n  exists rs1; exists tm, mu.\n  split. clear H2. intuition. \n      apply intern_incr_refl.\n      apply sm_inject_separated_same_sminj.\n      apply gsep_refl.\n\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.      \n(* Exec *)\n  split. eexact EX1.\n(* Match-env *)\n  split. \n  destruct H2 as [[A B] | [A B]].\n  subst r dst; simpl. \n  apply match_env_invariant with rs. auto.\n  intros. destruct (Reg.eq r rd). subst r. auto. auto.\n  apply match_env_invariant with (rs#rd <- (rs#r)).\n  apply match_env_update_dest; auto.\n  eapply match_env_find_letvar; eauto.\n  intros. rewrite Regmap.gsspec. destruct (peq r0 rd); auto.\n  congruence.\n(* Result *)\n  split. rewrite RES1. eapply match_env_find_letvar; eauto. \n(* Other regs *)\n  split. intros. \n  destruct H2 as [[A B] | [A B]].\n  destruct (Reg.eq r0 rd); subst; auto.\n  apply OTHER1. intuition congruence.\n(* Mem *)\n  auto.\nQed.\n\nLemma Efftransl_expr_Ebuiltin_correct:\n  forall le ef al vl v,\n  eval_exprlist ge sp e m le al vl ->\n  Efftransl_exprlist_prop le al vl ->\n  external_call ef ge vl m E0 v m ->\n  Efftransl_expr_prop le (Ebuiltin ef al) v.\nProof.\n  intros; red; intros. \n  assert (PGR: meminj_preserves_globals ge (restrict (as_inj mu) (vis mu))).     \n     rewrite <- restrict_sm_all. \n     eapply restrict_sm_preserves_globals; try eassumption.\n     unfold vis. intuition. \n  inv TE.\n  destruct OBS as [isHLP silExpr].\n  exploit H0; eauto. \n  assert (OBS' := EFhelpers _ _ isHLP). \n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RR1 [RO1 EXT1]]]]]]]].\n  (*WAS: exploit external_call_mem_extends; eauto. \n        intros [v' [tm2 [A [B [C [D E]]]]]].*)\n  destruct MU' as [INC [SEP [GSEP [LOCALLOC' [WD' [SMV' RC']]]]]].\n  exploit (inlineable_extern_inject _ _ GDE_lemma);\n       try eapply RR1; try eapply H1; try eassumption.\n     apply symbols_preserved.\n     assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC. \n        rewrite <- FF; apply Glob.\n     eapply intern_incr_meminj_preserves_globals_as_inj.\n         apply WD. split; assumption. \n     assumption. assumption. \n (* exploit external_call_mem_inject; eauto. \n        intros [j' [v' [tm2 [A [B [C [D [E [F G]]]]]]]]].*)\n   intros [mu'' [vres' [tm' [EC [VINJ [MINJ' [UNMAPPED [OUTOFREACH \n           [INCR [SEPARATED [LOCALLOC [WD'' [SMV'' RC'']]]]]]]]]]]]].\n  exists (rs1#rd <- vres'); exists tm', mu''.\n  split. intuition.\n    eapply intern_incr_trans. eassumption. eassumption.\n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply effstep_star_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n    eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply effstep_star_fwd. eassumption.\n             eapply external_call_mem_forward; eassumption.\n(* Exec *)\n  split. eapply effstep_star_trans'. eexact EX1.\n         apply effstep_star_one. eapply rtl_effstep_exec_Ibuiltin; try eassumption. \n         rewrite (helpers_EmptyEffect _ _ _ _ _ isHLP). intuition. \n    (*  eapply external_call_symbols_preserved; eauto. \n        exact symbols_preserved. exact varinfo_preserved.*)\n(* Match-env *)\n  split. eapply match_env_update_dest; try eassumption.\n     eapply match_env_inject_incr; try eassumption.\n     apply intern_incr_restrict; eassumption. \n(* Result reg *)\n  split. intros. rewrite Regmap.gss. auto.\n(* Other regs *)\n  split. intros. rewrite Regmap.gso. auto. intuition congruence.\n(* Mem *)\n  assumption. \nQed.\n\nLemma Efftransl_expr_Eexternal_correct:\n  forall le id sg al b ef vl v,\n  Genv.find_symbol ge id = Some b ->\n  Genv.find_funct_ptr ge b = Some (External ef) ->\n  ef_sig ef = sg ->\n  eval_exprlist ge sp e m le al vl ->\n  Efftransl_exprlist_prop le al vl ->\n  external_call ef ge vl m E0 v m ->\n  Efftransl_expr_prop le (Eexternal id sg al) v.\nProof.\n  intros; red; intros. inv TE.\n  destruct (silentD_Eexternal _ _ _ _ OBS H H0)\n    as [SilentArgs isHLP]; clear OBS.\n  exploit H3; eauto.  \n  assert (OBS' := EFhelpers _ _ isHLP). \n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RR1 [RO1 EXT1]]]]]]]].\n  assert (PG': meminj_preserves_globals ge (as_inj mu')).     \n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n      apply MU'. apply MU'. \n  destruct MU' as [INC [SEP [GSEP [LOCALLOC' [WD' [SMV' RC']]]]]].\n  exploit (inlineable_extern_inject _ _ GDE_lemma);\n       try eapply RR1; try eapply H1; try eassumption.\n     apply symbols_preserved.\n     assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC. \n        rewrite <- FF; apply Glob.\n  intros [mu'' [vres' [tm' [EC [VINJ [MINJ' [UNMAPPED [OUTOFREACH \n           [INCR [SEPARATED [GSEP' [LOCALLOC [WD'' [SMV'' RC'']]]]]]]]]]]]]].\n  eexists; exists tm', mu''. \n  split. intuition.\n     eapply intern_incr_trans; eassumption.\n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply effstep_star_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n     eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply effstep_star_fwd. eassumption.\n             eapply external_call_mem_forward; eassumption.\n  exploit function_ptr_translated; eauto. simpl. intros [tf [P Q]]. inv Q. \n(*  exists (rs1#rd <- vres'); exists tm2.*)\n(* Exec *)\n  split. eapply effstep_star_trans'. eexact EX1.\n    eapply effstep_star_trans'. \n     apply effstep_star_one. eapply rtl_effstep_exec_Icall; eauto.\n        simpl. rewrite symbols_preserved. rewrite H. eauto. auto.\n    eapply effstep_star_trans'. \n     apply effstep_star_one. eapply rtl_effstep_exec_function_external.\n       assumption. eassumption.\n     (*  eapply external_call_symbols_preserved; eauto. exact symbols_preserved. exact varinfo_preserved.*)\n     apply effstep_star_one. apply rtl_effstep_exec_return. \n     reflexivity. reflexivity.\n     simpl in *. rewrite (helpers_EmptyEffect _ _ _ _ _ isHLP). intuition. \n(* Match-env *)\n  split. eapply match_env_update_dest; try eassumption.\n     eapply match_env_inject_incr; try eassumption.\n     apply intern_incr_restrict; eassumption. \n(* Result reg *)\n   split. rewrite Regmap.gss. auto.\n(* Other regs *)\n  split. intros. rewrite Regmap.gso. auto. intuition congruence.\n(* Mem *)\n  auto.\nQed.\n\nLemma Efftransl_exprlist_Enil_correct:\n  forall (le : letenv),\n  Efftransl_exprlist_prop le Enil nil.\nProof.\n  intros; red; intros; inv TE.\n  exists rs; exists tm, mu.\n  split. intuition. \n  apply intern_incr_refl.\n  apply sm_inject_separated_same_sminj.\n  apply gsep_refl. \n\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition. \n  split. apply effstep_star_zero.\n  split. assumption.\n  split. constructor.\n  auto.\nQed.\n\nLemma Efftransl_exprlist_Econs_correct:\n  forall (le : letenv) (a1 : expr) (al : exprlist) (v1 : val)\n         (vl : list val),\n  eval_expr ge sp e m le a1 v1 ->\n  Efftransl_expr_prop le a1 v1 ->\n  eval_exprlist ge sp e m le al vl ->\n  Efftransl_exprlist_prop le al vl ->\n  Efftransl_exprlist_prop le (Econs a1 al) (v1 :: vl).\nProof.\n  intros; red; intros; inv TE.\n  simpl in OBS. destruct OBS as [silentA silentAL].\n  exploit H0; eauto. \n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RES1 [OTHER1 EXT1]]]]]]]].\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  exploit H2; try eapply EXT1.\n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n       eapply MU'. eapply MU'.\n       { red. exists spb, spb'. split. eassumption. \n           split. reflexivity. \n           eapply MU'. eassumption. }\n       eapply MU'. eapply MU'. eapply MU'. \n       intros b Gb. \n         assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply MU'.  \n         rewrite <- FRG. apply (Glob _ Gb). \n     eapply silentAL.\n     eauto. \n     eauto.\n     eassumption. \n  intros [rs2 [tm2 [mu'' [MU'' [EX2 [ME2 [RES2 [OTHER2 EXT2]]]]]]]].\n  exists rs2; exists tm2, mu''.\n  split. intuition.\n    eapply intern_incr_trans; eassumption. \n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply effstep_star_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n    eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply effstep_star_fwd. eassumption.\n             eapply effstep_star_fwd. eassumption.\n(* Exec *)\n  split. eapply effstep_star_trans'. eexact EX1. eexact EX2. auto. \n(* Match-env *)\n  split. assumption.\n(* Results *)\n  split. simpl. constructor. rewrite OTHER2. \n     eapply val_inject_incr; try eassumption. \n     eapply intern_incr_restrict. eapply MU''. eapply MU''.\n    simpl; tauto.\n  auto.\n(* Other regs *)\n  split. intros. transitivity (rs1#r).\n  apply OTHER2; auto. simpl; tauto. \n  apply OTHER1; auto.\n(* Mem *)\n  auto.\nQed.\n\nLemma Efftransl_condexpr_CEcond_correct:\n  forall le cond al vl vb,\n  eval_exprlist ge sp e m le al vl ->\n  Efftransl_exprlist_prop le al vl ->\n  eval_condition cond vl m = Some vb ->\n  Efftransl_condexpr_prop le (CEcond cond al) vb.\nProof.\n  intros; red; intros. inv TE. \n  exploit H0; eauto. \n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RES1 [OTHER1 EXT1]]]]]]]].\n  exists rs1; exists tm1, mu'.\n  split. assumption.\n(* Exec *)\n  split. eapply effstep_star_plus_trans'. eexact EX1.\n      eapply effstep_plus_one.\n        eapply rtl_effstep_exec_Icond. eauto. \n      (*eapply eval_condition_lessdef; eauto.*)\n    eapply eval_condition_inject; eauto. \n    eapply inject_restrict; eauto.\n     eapply MU'.\n    auto.\n    eauto.\n(* Match-env *)\n  split. assumption.\n(* Other regs *)\n  split. assumption. \n(* Mem *)\n  auto.\nQed.\n\nLemma Efftransl_condexpr_CEcondition_correct:\n  forall le a b c va v,\n  eval_condexpr ge sp e m le a va ->\n  Efftransl_condexpr_prop le a va ->\n  eval_condexpr ge sp e m le (if va then b else c) v ->\n  Efftransl_condexpr_prop le (if va then b else c) v ->\n  Efftransl_condexpr_prop le (CEcondition a b c) v.\nProof.\n  intros; red; intros. inv TE. \n  exploit H0; eauto. eapply OBS.\n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [OTHER1 EXT1]]]]]]].\n  assert (tr_condition (fn_code f) map pr (if va then b else c) (if va then n2 else n3) ntrue nfalse).\n    destruct va; auto.\n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  exploit H2; try eapply EXT1.\n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n       eapply MU'. eapply MU'.\n       { red. exists spb, spb'. split. eassumption. \n           split. reflexivity. \n           eapply MU'. eassumption. }\n       eapply MU'. eapply MU'. eapply MU'. \n       intros bb Gb. \n         assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply MU'.  \n         rewrite <- FRG. apply (Glob _ Gb). \n       destruct va; eapply OBS.\n     eauto. \n     eauto.\n     eassumption. \n  intros [rs2 [tm2 [mu'' [MU'' [EX2 [ME2 [OTHER2 EXT2]]]]]]].\n  exists rs2; exists tm2, mu''.\n  split. intuition.\n    eapply intern_incr_trans; eassumption. \n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply effstep_plus_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n    eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply effstep_plus_fwd. eassumption.\n             eapply effstep_plus_fwd. eassumption.\n(* Exec *)\n  split. eapply effstep_plus_trans'. eexact EX1. eexact EX2. eauto.\n(* Match-env *)\n  split. assumption.\n(* Other regs *)\n  split. intros. rewrite OTHER2; auto. \n(* Mem *)\n  auto.\nQed.\n\nLemma Efftransl_condexpr_CElet_correct:\n  forall le a b v1 v2,\n  eval_expr ge sp e m le a v1 ->\n  Efftransl_expr_prop le a v1 ->\n  eval_condexpr ge sp e m (v1 :: le) b v2 ->\n  Efftransl_condexpr_prop (v1 :: le) b v2 ->\n  Efftransl_condexpr_prop le (CElet a b) v2.\nProof.\n  intros; red; intros. inv TE. \n  exploit H0; eauto. eapply OBS.\n  intros [rs1 [tm1 [mu' [MU' [EX1 [ME1 [RES1 [OTHER1 EXT1]]]]]]]].\n  assert (map_wf (add_letvar map r)).\n    eapply add_letvar_wf; eauto. \n  destruct SP as [spb [spb' [SP [SP' Jsp]]]]. subst sp sp'.\n  exploit H2; try eapply EXT1.\n       eapply intern_incr_meminj_preserves_globals_as_inj.\n         eassumption. split; assumption. \n       eapply MU'. eapply MU'.\n       { red. exists spb, spb'. split. eassumption. \n           split. reflexivity. \n           eapply MU'. eassumption. }\n       eapply MU'. eapply MU'. eapply MU'. \n       intros bb Gb. \n         assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply MU'.  \n         rewrite <- FRG. apply (Glob _ Gb).\n       eapply OBS. \n     eauto. \n     eauto.\n     eapply match_env_bind_letvar; eauto. \n  intros [rs2 [tm2 [mu'' [MU'' [EX2 [ME3 [OTHER2 EXT2]]]]]]].\n  exists rs2; exists tm2, mu''.\n  split. intuition.\n    eapply intern_incr_trans; eassumption. \n    eapply inject_separated_intern_incr_fwd; try eassumption. \n           eapply effstep_star_fwd. eassumption.\n  eapply gsep_trans'; eassumption.\n    eapply sm_locally_allocated_trans; try eassumption. \n             apply mem_forward_refl. \n             apply mem_forward_refl.\n             eapply effstep_star_fwd. eassumption.\n             eapply effstep_plus_fwd. eassumption.\n(* Exec *)\n  split. eapply effstep_star_plus_trans'. \n    eexact EX1. eexact EX2. eauto.\n(* Match-env *)\n  split. eapply match_env_unbind_letvar; eauto.\n(* Other regs *)\n  split. intros. rewrite OTHER2; auto. \n(* Mem *)\n  auto.\nQed.\n\nTheorem Efftransl_expr_correct:\n  forall le a v,\n  eval_expr ge sp e m le a v ->\n  Efftransl_expr_prop le a v.\nProof\n  (eval_expr_ind3 ge sp e m\n     Efftransl_expr_prop\n     Efftransl_exprlist_prop\n     Efftransl_condexpr_prop\n     Efftransl_expr_Evar_correct\n     Efftransl_expr_Eop_correct\n     Efftransl_expr_Eload_correct\n     Efftransl_expr_Econdition_correct\n     Efftransl_expr_Elet_correct\n     Efftransl_expr_Eletvar_correct\n     Efftransl_expr_Ebuiltin_correct\n     Efftransl_expr_Eexternal_correct\n     Efftransl_exprlist_Enil_correct\n     Efftransl_exprlist_Econs_correct\n     Efftransl_condexpr_CEcond_correct\n     Efftransl_condexpr_CEcondition_correct\n     Efftransl_condexpr_CElet_correct).\n\nTheorem Efftransl_exprlist_correct:\n  forall le a v,\n  eval_exprlist ge sp e m le a v ->\n  Efftransl_exprlist_prop le a v.\nProof\n  (eval_exprlist_ind3 ge sp e m\n     Efftransl_expr_prop\n     Efftransl_exprlist_prop\n     Efftransl_condexpr_prop\n     Efftransl_expr_Evar_correct\n     Efftransl_expr_Eop_correct\n     Efftransl_expr_Eload_correct\n     Efftransl_expr_Econdition_correct\n     Efftransl_expr_Elet_correct\n     Efftransl_expr_Eletvar_correct\n     Efftransl_expr_Ebuiltin_correct \n     Efftransl_expr_Eexternal_correct\n     Efftransl_exprlist_Enil_correct\n     Efftransl_exprlist_Econs_correct\n     Efftransl_condexpr_CEcond_correct\n     Efftransl_condexpr_CEcondition_correct\n     Efftransl_condexpr_CElet_correct).\n\nTheorem Efftransl_condexpr_correct:\n  forall le a v,\n  eval_condexpr ge sp e m le a v ->\n  Efftransl_condexpr_prop le a v.\nProof\n  (eval_condexpr_ind3 ge sp e m\n     Efftransl_expr_prop\n     Efftransl_exprlist_prop\n     Efftransl_condexpr_prop\n     Efftransl_expr_Evar_correct\n     Efftransl_expr_Eop_correct\n     Efftransl_expr_Eload_correct\n     Efftransl_expr_Econdition_correct\n     Efftransl_expr_Elet_correct\n     Efftransl_expr_Eletvar_correct\n     Efftransl_expr_Ebuiltin_correct\n     Efftransl_expr_Eexternal_correct\n     Efftransl_exprlist_Enil_correct\n     Efftransl_exprlist_Econs_correct\n     Efftransl_condexpr_CEcond_correct\n     Efftransl_condexpr_CEcondition_correct\n     Efftransl_condexpr_CElet_correct).\n\nEnd CORRECTNESS_EXPR_EFF.\n\n(** ** Measure over CminorSel states *)\n\nOpen Local Scope nat_scope.\n\nFixpoint size_stmt (s: stmt) : nat :=\n  match s with\n  | Sskip => 0\n  | Sseq s1 s2 => (size_stmt s1 + size_stmt s2 + 1)\n  | Sifthenelse c s1 s2 => (size_stmt s1 + size_stmt s2 + 1)\n  | Sloop s1 => (size_stmt s1 + 1)\n  | Sblock s1 => (size_stmt s1 + 1)\n  | Sexit n => 0\n  | Slabel lbl s1 => (size_stmt s1 + 1)\n  | _ => 1\n  end.\n\nFixpoint size_cont (k: cont) : nat :=\n  match k with\n  | Kseq s k1 => (size_stmt s + size_cont k1 + 1)\n  | Kblock k1 => (size_cont k1 + 1)\n  | _ => 0%nat\n  end.\n\nDefinition measure_state (S: CMinSel_core) :=\n  match S with\n  | CMinSel_State _ s k _ _ => (size_stmt s + size_cont k, size_stmt s)\n  | _                           => (0, 0)\n  end.\n\nDefinition lt_state (S1 S2: CMinSel_core) :=\n  lex_ord lt lt (measure_state S1) (measure_state S2).\n\nLemma lt_state_intro:\n  forall f1 s1 k1 sp1 e1 f2 s2 k2 sp2 e2,\n  size_stmt s1 + size_cont k1 < size_stmt s2 + size_cont k2\n  \\/ (size_stmt s1 + size_cont k1 = size_stmt s2 + size_cont k2\n      /\\ size_stmt s1 < size_stmt s2) ->\n  lt_state (CMinSel_State f1 s1 k1 sp1 e1)\n           (CMinSel_State f2 s2 k2 sp2 e2).\nProof.\n  intros. unfold lt_state. simpl. destruct H as [A | [A B]].\n  left. auto.\n  rewrite A. right. auto.\nQed.\n\nLtac Lt_state :=\n  apply lt_state_intro; simpl; try omega.\n\nRequire Import Wellfounded.\n\nLemma lt_state_wf:\n  well_founded lt_state.\nProof.\n  unfold lt_state. apply wf_inverse_image with (f := measure_state).\n  apply wf_lex_ord. apply lt_wf. apply lt_wf. \nQed.\n\n(** ** Semantic preservation for the translation of statements *)   \n\n(** The simulation diagram for the translation of statements\n  and functions is a \"star\" diagram of the form:\n<<\n           I                         I\n     S1 ------- R1             S1 ------- R1\n     |          |              |          |\n   t |        + | t      or  t |        * | t    and |S2| < |S1|\n     v          v              v          |\n     S2 ------- R2             S2 ------- R2\n           I                         I\n>>\n  where [I] is the [match_states] predicate defined below.  It includes:\n- Agreement between the Cminor statement under consideration and\n  the current program point in the RTL control-flow graph,\n  as captured by the [tr_stmt] predicate.\n- Agreement between the Cminor continuation and the RTL control-flow\n  graph and call stack, as captured by the [tr_cont] predicate below.\n- Agreement between Cminor environments and RTL register environments,\n  as captured by [match_envs].\n\n*)\n\nInductive tr_fun (tf: function) (map: mapping) (f: CminorSel.function)\n                     (ngoto: labelmap) (nret: node) (rret: option reg) : Prop :=\n  | tr_fun_intro: forall nentry r,\n      rret = ret_reg f.(CminorSel.fn_sig) r ->\n      tr_stmt tf.(fn_code) map f.(fn_body) nentry nret nil ngoto nret rret ->\n      tf.(fn_stacksize) = f.(fn_stackspace) ->\n      tr_fun tf map f ngoto nret rret.\n\n(*LENB: new: meminj parameter mu*)\nInductive tr_cont mu: RTL.code -> mapping -> \n                   CminorSel.cont -> node -> list node -> labelmap -> node -> option reg ->\n                   list RTL.stackframe -> Prop :=\n  | tr_Kseq: forall c map s k nd nexits ngoto nret rret cs n,\n      tr_stmt c map s nd n nexits ngoto nret rret ->\n      tr_cont mu c map k n nexits ngoto nret rret cs ->\n      tr_cont mu c map (Kseq s k) nd nexits ngoto nret rret cs\n  | tr_Kblock: forall c map k nd nexits ngoto nret rret cs,\n      tr_cont mu c map k nd nexits ngoto nret rret cs ->\n      tr_cont mu c map (Kblock k) nd (nd :: nexits) ngoto nret rret cs\n  | tr_Kstop: forall c map ngoto nret rret cs,\n      c!nret = Some(Ireturn rret) ->\n      match_stacks mu Kstop cs ->\n      tr_cont mu c map Kstop nret nil ngoto nret rret cs\n  | tr_Kcall: forall c map optid f sp e k ngoto nret rret cs,\n      c!nret = Some(Ireturn rret) ->\n      match_stacks mu (Kcall optid f sp e k) cs ->\n      tr_cont mu c map (Kcall optid f sp e k) nret nil ngoto nret rret cs\n\nwith match_stacks mu : CminorSel.cont -> list RTL.stackframe -> Prop :=\n  | match_stacks_stop:\n      match_stacks mu Kstop nil\n  | match_stacks_call: forall optid f sp e k r tf n rs cs map nexits ngoto nret rret sp',\n      map_wf map ->\n      tr_fun tf map f ngoto nret rret ->\n      match_env (as_inj mu) map e nil rs ->\n      reg_map_ok map r optid ->\n      tr_cont mu tf.(fn_code) map k n nexits ngoto nret rret cs ->\n      (*NEW:*) sp_preserved (local_of mu) sp sp' ->\n      match_stacks mu (Kcall optid f sp e k) (Stackframe r tf sp' n rs :: cs).\n\n(*Derivation of induction scheme as explained her:\nhttp://coq.inria.fr/cocorico/Mutual%20Induction*)\nScheme tr_cont_ind_2 := Induction for tr_cont Sort Prop\n  with match_stacks_ind_2 := Induction for match_stacks Sort Prop.\nCombined Scheme tr_cont_match_stacks_mutual_ind\n  from tr_cont_ind_2, match_stacks_ind_2.\n\nLemma tr_cont_match_stacks_intern_incr: \n      forall mu mu' (WD': SM_wd mu') (INC: intern_incr mu mu'),\n      (forall c map k ncont nexits ngoto nret rret cs,\n         tr_cont mu c map k ncont nexits ngoto nret rret cs -> \n         tr_cont mu' c map k ncont nexits ngoto nret rret cs) /\\\n       (forall k cs, match_stacks mu k cs -> match_stacks mu' k cs).\nProof. intros. apply tr_cont_match_stacks_mutual_ind; intros.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; try eassumption. \n     eapply match_env_inject_incr; try eassumption.\n       apply intern_incr_as_inj; trivial. \n     eapply sp_incr; eauto. eapply INC.\nQed.\n\nLemma tr_cont_intern_incr: \n      forall mu c map k ncont nexits ngoto nret rret cs\n        (TR: tr_cont mu c map k ncont nexits ngoto nret rret cs)\n        mu' (WD': SM_wd mu') (INC: intern_incr mu mu'),\n      tr_cont mu' c map k ncont nexits ngoto nret rret cs.\nProof. intros. \n       eapply tr_cont_match_stacks_intern_incr; try eassumption.\nQed.\nLemma match_stacks_intern_incr: \n      forall mu k cs (MS:match_stacks mu k cs) \n             mu' (WD': SM_wd mu') (INC: intern_incr mu mu'), \n      match_stacks mu' k cs.\nProof. intros. \n       eapply tr_cont_match_stacks_intern_incr; try eassumption. \nQed. \n\nLemma tr_cont_match_stacks_replace_locals: \n      forall mu pubSrc' pubTgt' (WD: SM_wd mu)\n      (WD': SM_wd (replace_locals mu pubSrc' pubTgt')), \n      (forall c map k ncont nexits ngoto nret rret cs,\n         tr_cont (restrict_sm mu (vis mu)) \n                 c map k ncont nexits ngoto nret rret cs -> \n         tr_cont (restrict_sm (replace_locals mu pubSrc' pubTgt') (vis mu))\n                 c map k ncont nexits ngoto nret rret cs) /\\\n       (forall k cs, match_stacks (restrict_sm mu (vis mu)) k cs ->\n                     match_stacks (restrict_sm (replace_locals mu pubSrc' pubTgt') (vis mu)) k cs).\nProof. intros. apply tr_cont_match_stacks_mutual_ind; intros.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; try eassumption.\n     rewrite restrict_sm_all in *. \n     rewrite replace_locals_as_inj. assumption.\n     rewrite restrict_sm_local' in *; trivial.\n      rewrite replace_locals_local; trivial.\n     rewrite replace_locals_vis. trivial.\nQed.\n\nLemma tr_cont_replace_locals: \n      forall mu c map k ncont nexits ngoto nret rret cs\n        (TR: tr_cont (restrict_sm mu (vis mu)) c map k ncont nexits ngoto nret rret cs)\n        pubSrc' pubTgt' (WD: SM_wd mu)\n        (WD': SM_wd (replace_locals mu pubSrc' pubTgt')),\n      tr_cont (restrict_sm (replace_locals mu pubSrc' pubTgt') (vis mu)) c map k ncont nexits ngoto nret rret cs.\nProof. intros. \n       eapply tr_cont_match_stacks_replace_locals; try eassumption.\nQed.\nLemma match_stacks_replace_locals: \n      forall mu k cs (MS:match_stacks (restrict_sm mu (vis mu)) k cs) \n        pubSrc' pubTgt' (WD: SM_wd mu)\n        (WD': SM_wd (replace_locals mu  pubSrc' pubTgt')),\n      match_stacks (restrict_sm (replace_locals mu pubSrc' pubTgt') (vis mu)) k cs.\nProof. intros. \n       eapply tr_cont_match_stacks_replace_locals; try eassumption. \nQed. \n\nLemma tr_cont_match_stacks_extern_incr: \n      forall mu mu' (WD': SM_wd mu') (INC: extern_incr mu mu'),\n      (forall c map k ncont nexits ngoto nret rret cs,\n         tr_cont mu c map k ncont nexits ngoto nret rret cs -> \n         tr_cont mu' c map k ncont nexits ngoto nret rret cs) /\\\n       (forall k cs, match_stacks mu k cs -> match_stacks mu' k cs).\nProof. intros. apply tr_cont_match_stacks_mutual_ind; intros.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; try eassumption. \n     eapply match_env_inject_incr; try eassumption.\n       apply extern_incr_as_inj; trivial. \n     assert (local_of mu = local_of mu') by eapply INC.\n     rewrite <- H0; trivial.\nQed.\n\nLemma tr_cont_extern_incr: \n      forall mu c map k ncont nexits ngoto nret rret cs\n        (TR: tr_cont mu c map k ncont nexits ngoto nret rret cs)\n        mu' (WD': SM_wd mu') (INC: extern_incr mu mu'),\n      tr_cont mu' c map k ncont nexits ngoto nret rret cs.\nProof. intros. \n       eapply tr_cont_match_stacks_extern_incr; try eassumption.\nQed.\nLemma match_stacks_extern_incr: \n      forall mu k cs (MS:match_stacks mu k cs) \n             mu' (WD': SM_wd mu') (INC: extern_incr mu mu'), \n      match_stacks mu' k cs.\nProof. intros. \n       eapply tr_cont_match_stacks_extern_incr; try eassumption. \nQed. \n\n(*Lemma tr_cont_match_stacks_replace_externs: \n      forall mu FS FT \n      (HFS: forall b, vis mu b = true -> \n          locBlocksSrc mu b || FS b = true),\n      (forall c map k ncont nexits ngoto nret rret cs,\n         tr_cont (restrict_sm mu (vis mu)) \n                 c map k ncont nexits ngoto nret rret cs -> \n         tr_cont (restrict_sm (replace_externs mu FS FT) FS)\n                 c map k ncont nexits ngoto nret rret cs) /\\\n       (forall k cs, match_stacks (restrict_sm mu (vis mu)) k cs ->\n                     match_stacks (restrict_sm (replace_externs mu FS FT) FS) k cs).\nProof. intros. apply tr_cont_match_stacks_mutual_ind; intros.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; try eassumption.\n    rewrite restrict_sm_all in *.\n    rewrite replace_externs_as_inj; trivial.\n      eapply match_env_inject_incr; try eassumption.\n      red; intros. destruct (restrictD_Some _ _ _ _ _ H0).\n      apply restrictI_Some; trivial.\n      apply \n    rewrite restrict_sm_local in *; trivial.\n    rewrite replace_externs_local; trivial.\n    eapply sp_incr. eassumption.\n      red; intros. destruct (restrictD_Some _ _ _ _ _ H0).\n      apply restrictI_Some; eauto.\nQed.\n\nLemma tr_cont_replace_externs mu FS FT:\n      forall c map k ncont nexits ngoto nret rret cs\n         (TR: tr_cont (restrict_sm mu (vis mu)) \n                 c map k ncont nexits ngoto nret rret cs)\n         (HFS: forall b, vis mu b = true -> FS b = true),\n         tr_cont (restrict_sm (replace_externs mu FS FT) FS)\n                 c map k ncont nexits ngoto nret rret cs.\nProof. intros. \n       eapply tr_cont_match_stacks_replace_externs; try eassumption.\nQed.\nLemma match_stacks_replace_externs mu FS FT k cs: forall\n       (MS: match_stacks (restrict_sm mu (vis mu)) k cs)\n       (HFS: forall b, vis mu b = true -> FS b = true),\n       match_stacks (restrict_sm (replace_externs mu FS FT) FS) \n                     k cs.\nProof. intros. \n       eapply tr_cont_match_stacks_replace_externs; try eassumption. \nQed. \n*)\n\nLemma tr_cont_match_stacks_replace_externs: \n      forall mu FS FT \n      (HFS: forall b, vis mu b = true -> \n          locBlocksSrc mu b || FS b = true),\n      (forall c map k ncont nexits ngoto nret rret cs,\n         tr_cont  mu c map k ncont nexits ngoto nret rret cs -> \n         tr_cont (replace_externs mu FS FT)\n                 c map k ncont nexits ngoto nret rret cs) /\\\n       (forall k cs, match_stacks mu k cs ->\n                     match_stacks (replace_externs mu FS FT) k cs).\nProof. intros. apply tr_cont_match_stacks_mutual_ind; intros.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; eassumption.\n  econstructor; try eassumption.\n    rewrite replace_externs_as_inj; trivial.\n    rewrite replace_externs_local; trivial.\nQed.\n\nLemma tr_cont_replace_externs mu FS FT:\n      forall c map k ncont nexits ngoto nret rret cs\n         (TR: tr_cont mu c map k ncont nexits ngoto nret rret cs)\n         (HFS: forall b, vis mu b = true -> \n               locBlocksSrc mu b || FS b = true),\n         tr_cont (replace_externs mu FS FT)\n                 c map k ncont nexits ngoto nret rret cs.\nProof. intros. \n       eapply tr_cont_match_stacks_replace_externs; try eassumption.\nQed.\nLemma match_stacks_replace_externs mu FS FT k cs: forall\n       (MS: match_stacks mu k cs)\n         (HFS: forall b, vis mu b = true -> \n               locBlocksSrc mu b || FS b = true),\n       match_stacks (replace_externs mu FS FT) k cs.\nProof. intros. \n       eapply tr_cont_match_stacks_replace_externs; try eassumption. \nQed. \n\nInductive match_states mu: CMinSel_core -> mem -> RTL_core -> mem -> Prop :=\n  | match_state:\n      forall f s k sp e m tm cs tf ns rs map ncont nexits ngoto nret rret sp'\n        (MWF: map_wf map)\n        (TS: tr_stmt tf.(fn_code) map s ns ncont nexits ngoto nret rret)\n        (TF: tr_fun tf map f ngoto nret rret)\n        (TK: tr_cont mu tf.(fn_code) map k ncont nexits ngoto nret rret cs)\n        (ME: match_env (as_inj mu) map e nil rs)\n        (*(MEXT: Mem.extends m tm)*)\n        (MINJ: Mem.inject (as_inj mu) m tm)\n        (*NEW:*) (SP: sp_preserved (local_of mu) sp sp'),\n      match_states mu (CMinSel_State f s k sp e) m\n                     (RTL_State cs tf sp' ns rs) tm\n  | match_callstate:\n      forall f args targs k m tm cs tf\n        (TF: transl_fundef f = OK tf)\n        (MS: match_stacks (restrict_sm mu (vis mu)) k cs)\n        (*(LD: Val.lessdef_list args targs)*)\n        (AINJ: val_list_inject (restrict (as_inj mu) (vis mu)) args targs)\n        (*(MEXT: Mem.extends m tm)*)\n        (MINJ: Mem.inject (as_inj mu) m tm),\n      match_states mu (CMinSel_Callstate f args k) m\n                     (RTL_Callstate cs tf targs) tm\n  | match_returnstate:\n      forall v tv k m tm cs\n        (MS: match_stacks (restrict_sm mu (vis mu)) k cs)\n        (*(LD: Val.lessdef v tv)*)\n         (VINJ: val_inject (restrict (as_inj mu) (vis mu)) v tv)\n        (*(MEXT: Mem.extends m tm)*)\n        (MINJ: Mem.inject (as_inj mu) m tm),\n      match_states mu (CMinSel_Returnstate v k) m\n                     (RTL_Returnstate cs tv) tm.\n\n\nLemma match_stacks_call_cont:\n  forall mu c map k ncont nexits ngoto nret rret cs,\n  tr_cont mu c map k ncont nexits ngoto nret rret cs ->\n  match_stacks mu (call_cont k) cs /\\ c!nret = Some(Ireturn rret).\nProof.\n  induction 1; simpl; auto.\nQed.\n\nLemma tr_cont_call_cont:\n  forall mu c map k ncont nexits ngoto nret rret cs,\n  tr_cont mu c map k ncont nexits ngoto nret rret cs ->\n  tr_cont mu c map (call_cont k) nret nil ngoto nret rret cs.\nProof.\n  induction 1; simpl; auto; econstructor; eauto.\nQed.\n\nLemma tr_find_label:\n  forall mu c map lbl n (ngoto: labelmap) nret rret s' k' cs,\n  ngoto!lbl = Some n ->\n  forall s k ns1 nd1 nexits1,\n  find_label lbl s k = Some (s', k') ->\n  tr_stmt c map s ns1 nd1 nexits1 ngoto nret rret ->\n  tr_cont mu c map k nd1 nexits1 ngoto nret rret cs ->\n  exists ns2, exists nd2, exists nexits2,\n     c!n = Some(Inop ns2)\n  /\\ tr_stmt c map s' ns2 nd2 nexits2 ngoto nret rret\n  /\\ tr_cont mu c map k' nd2 nexits2 ngoto nret rret cs.\nProof.\n  induction s; intros until nexits1; simpl; try congruence.\n  (* seq *)\n  caseEq (find_label lbl s1 (Kseq s2 k)); intros.\n  inv H1. inv H2. eapply IHs1; eauto. econstructor; eauto.\n  inv H2. eapply IHs2; eauto. \n  (* ifthenelse *)\n  caseEq (find_label lbl s1 k); intros.\n  inv H1. inv H2. eapply IHs1; eauto.\n  inv H2. eapply IHs2; eauto.\n  (* loop *)\n  intros. inversion H1; subst.\n  eapply IHs; eauto. econstructor; eauto. econstructor; eauto.\n  (* block *)\n  intros. inv H1.\n  eapply IHs; eauto. econstructor; eauto.\n  (* label *)\n  destruct (ident_eq lbl l); intros.\n  inv H0. inv H1.\n  assert (n0 = n). change positive with node in H4. congruence. subst n0.\n  exists ns1; exists nd1; exists nexits1; auto.\n  inv H1. eapply IHs; eauto.\nQed.\n\nDefinition MATCH (d:CMinSel_core) mu c1 m1 c2 m2:Prop :=\n  match_states (restrict_sm mu (vis mu)) c1 m1 c2 m2 /\\\n  REACH_closed m1 (vis mu) /\\\n  meminj_preserves_globals ge (as_inj mu) /\\\n  globalfunction_ptr_inject ge (as_inj mu) /\\\n  (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true) /\\\n  sm_valid mu m1 m2 /\\ SM_wd mu /\\ Mem.inject (as_inj mu) m1 m2.\n\nLemma MATCH_wd: forall d mu c1 m1 c2 m2 \n  (MC: MATCH d mu c1 m1 c2 m2), SM_wd mu.\nProof. intros. eapply MC. Qed.\n\nLemma MATCH_RC: forall d mu c1 m1 c2 m2 \n  (MC: MATCH d mu c1 m1 c2 m2), REACH_closed m1 (vis mu).\nProof. intros. eapply MC. Qed.\n\nLemma MATCH_restrict: forall d mu c1 m1 c2 m2 X\n  (MC: MATCH d mu c1 m1 c2 m2)\n  (HX: forall b : block, vis mu b = true -> X b = true) \n  (RX: REACH_closed m1 X), \n  MATCH d (restrict_sm mu X) c1 m1 c2 m2.\nProof. intros.\n  destruct MC as [MS [RC [PG [GFP [Glob [SMV [WD INJ]]]]]]].\nassert (WDR: SM_wd (restrict_sm mu X)).\n   apply restrict_sm_WD; assumption.\nsplit.\n  rewrite vis_restrict_sm.\n(*  rewrite restrict_sm_all.*)\n  rewrite restrict_sm_nest; intuition.\nsplit. unfold vis.\n  rewrite restrict_sm_locBlocksSrc, restrict_sm_frgnBlocksSrc.\n  apply RC.\nsplit. clear -PG Glob HX.\n  eapply restrict_sm_preserves_globals; try eassumption.\n  unfold vis in HX. intuition.\nsplit. rewrite restrict_sm_all.\n  eapply restrict_preserves_globalfun_ptr; try eassumption.\n  unfold vis in HX. intuition.\nsplit. \n  rewrite restrict_sm_frgnBlocksSrc. apply Glob.\nsplit. \n  destruct SMV.\n  split; intros.\n    rewrite restrict_sm_DOM in H1.\n    apply (H _ H1).\n  rewrite restrict_sm_RNG in H1.\n    apply (H0 _ H1).\nsplit. assumption.\n(*split. *) rewrite restrict_sm_all.\n  eapply inject_restrict; try eassumption.\n(*rewrite restrict_sm_DomTgt. trivial.*)\nQed.\n\nLemma MATCH_valid: forall d mu c1 m1 c2 m2 \n  (MC: MATCH d mu c1 m1 c2 m2), sm_valid mu m1 m2.\nProof. intros. eapply MC. Qed.\n\nLemma MATCH_PG: forall d mu c1 m1 c2 m2 \n  (MC: MATCH d mu c1 m1 c2 m2),\n  meminj_preserves_globals ge (extern_of mu) /\\\n  (forall b : block, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true).\nProof.\n  intros.\n  assert (GF: forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true).\n    apply MC.\n  split; trivial.\n  rewrite <- match_genv_meminj_preserves_extern_iff_all; trivial.\n    apply MC. apply MC.\nQed.\n\nLemma MATCH_initial: forall v\n      vals1 c1 m1 j vals2 m2 (DomS DomT : block -> bool)\n      (Ini: initial_core (cminsel_eff_sem hf) ge v vals1 = Some c1)\n      (Inj: Mem.inject j m1 m2)\n      (VInj: Forall2 (val_inject j) vals1 vals2)\n      (PG:meminj_preserves_globals ge j)\n      (J: forall b1 b2 delta, j b1 = Some (b2, delta) -> \n            (DomS b1 = true /\\ DomT b2 = true))\n      (RCH: forall b, REACH m2 \n          (fun b' : block => isGlobalBlock tge b' || getBlocks vals2 b') b = true ->\n          DomT b = true)\n      (GFI: globalfunction_ptr_inject ge j)\n      (GDE: genvs_domain_eq ge tge)\n      (HDomS: forall b : block, DomS b = true -> Mem.valid_block m1 b)\n      (HDomT: forall b : block, DomT b = true -> Mem.valid_block m2 b),\nexists c2,\n  initial_core (rtl_eff_sem hf) tge v vals2 = Some c2 /\\\n  MATCH c1\n    (initial_SM DomS DomT\n       (REACH m1 (fun b : block => isGlobalBlock ge b || getBlocks vals1 b))\n       (REACH m2 (fun b : block => isGlobalBlock tge b || getBlocks vals2 b))\n       j) c1 m1 c2 m2.\nProof. intros.\n  inversion Ini.\n  unfold CMinSel_initial_core in H0. unfold ge in *. unfold tge in *.\n  destruct v; inv H0.\n  remember (Int.eq_dec i Int.zero) as z; destruct z; inv H1. clear Heqz.\n  remember (Genv.find_funct_ptr (Genv.globalenv prog) b) as zz; destruct zz; inv H0. \n    apply eq_sym in Heqzz.\n  destruct f; try discriminate.\n  simpl; revert H1; case_eq \n    (zlt (match match Zlength vals1 with 0%Z => 0%Z\n                      | Z.pos y' => Z.pos y'~0 | Z.neg y' => Z.neg y'~0\n                     end\n               with 0%Z => 0%Z\n                 | Z.pos y' => Z.pos y'~0~0 | Z.neg y' => Z.neg y'~0~0\n               end) Int.max_unsigned).\n  intros l _.\n  2: solve[simpl; rewrite andb_comm; inversion 2].\n\n  exploit function_ptr_translated; eauto. intros [tf [FP TF]].\n  exists (RTL_Callstate nil tf vals2).\n  split.\n    subst. inv Heqzz. unfold tge in FP. inv FP. rewrite H2.\n    unfold cminsel_eff_sem, cminsel_coop_sem. simpl.\n    case_eq (Int.eq_dec Int.zero Int.zero). intros ? e.\n\n  assert (Zlength vals2 = Zlength vals1) as ->. \n  { apply forall_inject_val_list_inject in VInj. clear - VInj. \n    induction VInj; auto. rewrite !Zlength_cons, IHVInj; auto. }\n\n  assert (val_casted.val_has_type_list_func vals2\n           (sig_args (funsig tf))=true) as ->.\n  { eapply val_casted.val_list_inject_hastype; eauto.\n    eapply forall_inject_val_list_inject; eauto.\n    destruct (val_casted.vals_defined vals1); auto.\n    rewrite andb_comm in H1; simpl in H1. \n    solve[rewrite andb_comm in H1; inv H1].\n    assert (sig_args (funsig tf)\n          = sig_args (CminorSel.funsig (Internal f))) as ->.\n    { erewrite sig_transl_function; eauto. }\n    destruct (val_casted.val_has_type_list_func vals1\n      (sig_args (CminorSel.funsig (Internal f)))); auto. inv H1. }\n  assert (val_casted.vals_defined vals2=true) as ->.\n  { eapply val_casted.val_list_inject_defined.\n    eapply forall_inject_val_list_inject; eauto.\n    destruct (val_casted.vals_defined vals1); auto.\n    rewrite <-andb_assoc, andb_comm in H1; inv H1. }\n  monadInv TF. rename x into tf.\n  simpl; revert H1; case_eq \n    (zlt (match match Zlength vals1 with 0%Z => 0%Z\n                      | Z.pos y' => Z.pos y'~0 | Z.neg y' => Z.neg y'~0\n                     end\n               with 0%Z => 0%Z\n                 | Z.pos y' => Z.pos y'~0~0 | Z.neg y' => Z.neg y'~0~0\n               end) Int.max_unsigned).\n  solve[simpl; auto].\n  intros CONTRA. solve[elimtype False; auto].\n  intros CONTRA. solve[elimtype False; auto].\n\n  destruct (core_initial_wd ge tge _ _ _ _ _ _ _  Inj\n     VInj J RCH PG GDE HDomS HDomT _ (eq_refl _))\n    as [AA [BB [CC [DD [EE [FF GG]]]]]].\n  split.\n    revert H1.\n    destruct (val_casted.val_has_type_list_func vals1\n             (sig_args (CminorSel.funsig (Internal f))) && val_casted.vals_defined vals1); \n      try solve[inversion 1]. \n    inversion 1; subst. clear H1.\n    eapply match_callstate; try eassumption.\n      constructor.\n      rewrite restrict_sm_all, restrict_nest.\n      rewrite initial_SM_as_inj.\n        unfold vis, initial_SM; simpl.\n        apply forall_inject_val_list_inject.\n        eapply restrict_forall_vals_inject; try eassumption.\n          intros. apply REACH_nil. rewrite H; intuition.\n    rewrite vis_restrict_sm. \n      unfold vis, initial_SM; simpl. trivial.\n    rewrite restrict_sm_all, initial_SM_as_inj.\n      unfold vis, initial_SM; simpl. \n      eapply inject_restrict; try eassumption.\n  intuition.\n    rewrite match_genv_meminj_preserves_extern_iff_all.\n      assumption.\n      apply BB.\n      apply EE.\n    (*as in selectionproofEFF*)\n    rewrite initial_SM_as_inj; auto.\n    rewrite initial_SM_as_inj; assumption.\nQed.\n\nLemma MATCH_atExternal: forall mu c1 m1 c2 m2 e vals1 ef_sig\n       (MTCH: MATCH c1 mu c1 m1 c2 m2)\n       (AtExtSrc: at_external (cminsel_eff_sem hf) c1 = Some (e, ef_sig, vals1)),\n     Mem.inject (as_inj mu) m1 m2 /\\\n     exists vals2,\n       Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2 /\\\n       at_external (rtl_eff_sem hf) c2 = Some (e, ef_sig, vals2) /\\\n      (forall pubSrc' pubTgt',\n       pubSrc' = (fun b => locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b) ->\n       pubTgt' = (fun b => locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b) ->\n       forall nu : SM_Injection, nu = replace_locals mu pubSrc' pubTgt' ->\n       MATCH c1 nu c1 m1 c2 m2 /\\ Mem.inject (shared_of nu) m1 m2).\nProof. intros.\ndestruct MTCH as [MC [RC [PG [GFP [Glob [SMV [WD INJ]]]]]]].\ninv MC; simpl in AtExtSrc; inv AtExtSrc.\ndestruct f; simpl in *; inv H0.\ninv TF.\ndestruct (observableEF_dec hf e0); inv H1.\nsplit; trivial.\nrewrite vis_restrict_sm, restrict_sm_all, restrict_nest in AINJ; trivial.\nexploit val_list_inject_forall_inject; try eassumption. intros ARGS'.\nexists targs.\nsplit; trivial.\nsplit; trivial.\nspecialize (forall_vals_inject_restrictD _ _ _ _ ARGS'); intros.\nexploit replace_locals_wd_AtExternal; try eassumption. \nintuition. \n(*MATCH*)\n    split; subst; rewrite replace_locals_vis. \n      econstructor; eauto. \n       rewrite restrict_sm_nest, vis_restrict_sm in *. \n         rewrite replace_locals_vis. \n         eapply match_stacks_replace_locals; eassumption.\n         rewrite vis_restrict_sm; trivial.\n       rewrite vis_restrict_sm, replace_locals_vis; trivial.\n       rewrite vis_restrict_sm; trivial. \n       rewrite vis_restrict_sm, restrict_sm_all,\n         restrict_nest; trivial. \n         rewrite replace_locals_as_inj, replace_locals_vis; trivial.\n       rewrite replace_locals_vis; trivial.\n       rewrite restrict_sm_all in *.\n         rewrite replace_locals_as_inj. trivial.\n    subst. rewrite replace_locals_frgnBlocksSrc, replace_locals_as_inj in *.\n           intuition.\n   (*sm_valid*)\n     red. rewrite replace_locals_DOM, replace_locals_RNG. apply SMV.\n(*Shared*)\n  eapply inject_shared_replace_locals; try eassumption.\n  subst; trivial.\nQed.\n\nLemma MATCH_afterExternal: forall\n      (GDE : genvs_domain_eq ge tge)\n      mu st1 st2 m1 e vals1 m2 ef_sig vals2 e' ef_sig'\n      (MemInjMu : Mem.inject (as_inj mu) m1 m2)\n      (MatchMu: MATCH st1 mu st1 m1 st2 m2)\n      (AtExtSrc : at_external (cminsel_eff_sem hf) st1 = Some (e, ef_sig, vals1))\n      (AtExtTgt : at_external (rtl_eff_sem hf) st2 = Some (e', ef_sig', vals2))\n      (ValInjMu : Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n      (pubSrc' : block -> bool)\n      (pubSrcHyp : pubSrc' =\n                 (fun b : block => \n                 locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b))\n      (pubTgt' : block -> bool)\n      (pubTgtHyp: pubTgt' =\n                 (fun b : block => \n                 locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b))\n       nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt')\n       nu' ret1 m1' ret2 m2' \n       (INC: extern_incr nu nu')\n       (SEP : globals_separate tge nu nu')\n       (*SEP: sm_inject_separated nu nu' m1 m2*)\n       (WDnu': SM_wd nu')\n       (SMvalNu': sm_valid nu' m1' m2')\n       (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n       (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n       (FwdSrc: mem_forward m1 m1')\n       (FwdTgt: mem_forward m2 m2')\n       (frgnSrc' : block -> bool)\n       (frgnSrcHyp: frgnSrc' =\n             (fun b : block => DomSrc nu' b &&\n            (negb (locBlocksSrc nu' b) && REACH m1' (exportedSrc nu' (ret1 :: nil)) b)))\n       (frgnTgt' : block -> bool)\n       (frgnTgtHyp: frgnTgt' =\n            (fun b : block => DomTgt nu' b &&\n             (negb (locBlocksTgt nu' b) && REACH m2' (exportedTgt nu' (ret2 :: nil)) b)))\n       mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n       (UnchPrivSrc: Mem.unchanged_on\n               (fun b z => locBlocksSrc nu b = true /\\ pubBlocksSrc nu b = false) m1 m1')\n       (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n  exists st1' st2',\n  after_external (cminsel_eff_sem hf) (Some ret1) st1 =Some st1' /\\\n  after_external (rtl_eff_sem hf) (Some ret2) st2 = Some st2' /\\\n  MATCH st1' mu' st1' m1' st2' m2'.\nProof. intros.\nsimpl.\n destruct MatchMu as [MC [RC [PG [GFP [Glob [VAL [WDmu INJ]]]]]]].\n simpl in *. inv MC; simpl in *; inv AtExtSrc.\n destruct f; inv H0. \n destruct tf; inv AtExtTgt.\n inv TF.\n destruct (observableEF_dec hf e1); inv H0; inv H1.\n eexists. eexists.\n    split. reflexivity.\n    split. reflexivity.\n simpl in *.\n assert (INCvisNu': inject_incr\n  (restrict (as_inj nu')\n     (vis\n        (replace_externs nu'\n           (fun b : Values.block =>\n            DomSrc nu' b &&\n            (negb (locBlocksSrc nu' b) &&\n             REACH m1' (exportedSrc nu' (ret1 :: nil)) b))\n           (fun b : Values.block =>\n            DomTgt nu' b &&\n            (negb (locBlocksTgt nu' b) &&\n             REACH m2' (exportedTgt nu' (ret2 :: nil)) b))))) (as_inj nu')).\n      unfold vis. rewrite replace_externs_frgnBlocksSrc, replace_externs_locBlocksSrc.\n      apply restrict_incr. \nassert (RC': REACH_closed m1' (mapped (as_inj nu'))).\n        eapply inject_REACH_closed; eassumption.\n       assert (PGnu': meminj_preserves_globals (Genv.globalenv prog) (as_inj nu')).\n       eapply meminj_preserves_globals_extern_incr_separate. eassumption.\n       rewrite replace_locals_as_inj. assumption.\n       assumption. \n       specialize (genvs_domain_eq_isGlobal _ _ GDE_lemma). intros GL.\n       red. unfold ge in GL. rewrite GL. apply SEP.\n\nassert (RR1: REACH_closed m1'\n  (fun b : Values.block =>\n   locBlocksSrc nu' b\n   || DomSrc nu' b &&\n      (negb (locBlocksSrc nu' b) &&\n       REACH m1' (exportedSrc nu' (ret1 :: nil)) b))).\n  intros b Hb. rewrite REACHAX in Hb. destruct Hb as [L HL].\n  generalize dependent b.\n  induction L; simpl; intros; inv HL.\n     assumption.\n  specialize (IHL _ H1); clear H1.\n  apply orb_true_iff in IHL.\n  remember (locBlocksSrc nu' b') as l.\n  destruct l; apply eq_sym in Heql.\n  (*case locBlocksSrc nu' b' = true*)\n    clear IHL.\n    remember (pubBlocksSrc nu' b') as p.\n    destruct p; apply eq_sym in Heqp.\n      assert (Rb': REACH m1' (mapped (as_inj nu')) b' = true).\n        apply REACH_nil. \n        destruct (pubSrc _ WDnu' _ Heqp) as [bb2 [dd1 [PUB PT]]].\n        eapply mappedI_true.\n         apply (pub_in_all _ WDnu' _ _ _ PUB).\n      assert (Rb:  REACH m1' (mapped (as_inj nu')) b = true).\n        eapply REACH_cons; try eassumption.\n      specialize (RC' _ Rb).\n      destruct (mappedD_true _ _ RC') as [[b2 d1] AI'].\n      remember (locBlocksSrc nu' b) as d.\n      destruct d; simpl; trivial.\n      apply andb_true_iff. \n      split. eapply as_inj_DomRng; try eassumption.\n      eapply REACH_cons; try eassumption.\n        apply REACH_nil. unfold exportedSrc.\n        rewrite (pubSrc_shared _ WDnu' _ Heqp). intuition.\n      destruct (UnchPrivSrc) as [UP UV]; clear UnchLOOR.\n        specialize (UP b' z Cur Readable). \n        specialize (UV b' z). \n        destruct INC as [_ [_ [_ [_ [LCnu' [_ [PBnu' [_ [FRGnu' _]]]]]]]]].\n        rewrite <- LCnu'. rewrite replace_locals_locBlocksSrc.  \n        rewrite <- LCnu' in Heql. rewrite replace_locals_locBlocksSrc in *.\n        rewrite <- PBnu' in Heqp. rewrite replace_locals_pubBlocksSrc in *.\n        clear INCvisNu'. \n        rewrite Heql in *. simpl in *. intuition.\n        assert (VB: Mem.valid_block m1 b').\n          eapply VAL. unfold DOM, DomSrc. rewrite Heql. intuition.\n        apply (H VB) in H2.\n        rewrite (H0 H2) in H4. clear H H0.\n        remember (locBlocksSrc mu b) as q.\n        destruct q; simpl; trivial; apply eq_sym in Heqq.\n        assert (Rb : REACH m1 (vis mu) b = true).\n           eapply REACH_cons; try eassumption.\n           apply REACH_nil. unfold vis. rewrite Heql; trivial.\n        specialize (RC _ Rb). unfold vis in RC.\n           rewrite Heqq in RC; simpl in *.\n        rewrite replace_locals_frgnBlocksSrc in FRGnu'.\n        rewrite FRGnu' in RC.\n        apply andb_true_iff.  \n        split. unfold DomSrc. rewrite (frgnBlocksSrc_extBlocksSrc _ WDnu' _ RC). intuition.\n        apply REACH_nil. unfold exportedSrc.\n          rewrite (frgnSrc_shared _ WDnu' _ RC). intuition.\n  (*case DomSrc nu' b' &&\n    (negb (locBlocksSrc nu' b') &&\n     REACH m1' (exportedSrc nu' (ret1 :: nil)) b') = true*)\n    destruct IHL. congruence.\n    apply andb_true_iff in H. simpl in H. \n    destruct H as [DomNu' Rb']. \n    clear INC SEP INCvisNu' UnchLOOR UnchPrivSrc.\n    remember (locBlocksSrc nu' b) as d.\n    destruct d; simpl; trivial. apply eq_sym in Heqd.\n    apply andb_true_iff.\n    split. assert (RET: Forall2 (val_inject (as_inj nu')) (ret1::nil) (ret2::nil)).\n              constructor. assumption. constructor.\n           destruct (REACH_as_inj _ WDnu' _ _ _ _ MemInjNu' RET\n               _ Rb' (fun b => true)) as [b2 [d1 [AI' _]]]; trivial.\n           assert (REACH m1' (mapped (as_inj nu')) b = true).\n             eapply REACH_cons; try eassumption.\n             apply REACH_nil. eapply mappedI_true; eassumption.\n           specialize (RC' _ H). \n           destruct (mappedD_true _ _ RC') as [[? ?] ?].\n           eapply as_inj_DomRng; eassumption.\n    eapply REACH_cons; try eassumption.\n    \nassert (RRC: REACH_closed m1' (fun b : Values.block =>\n                         mapped (as_inj nu') b &&\n                           (locBlocksSrc nu' b\n                            || DomSrc nu' b &&\n                               (negb (locBlocksSrc nu' b) &&\n                           REACH m1' (exportedSrc nu' (ret1 :: nil)) b)))).\n  eapply REACH_closed_intersection; eassumption.\nassert (GFnu': forall b, isGlobalBlock (Genv.globalenv prog) b = true ->\n               DomSrc nu' b &&\n               (negb (locBlocksSrc nu' b) && REACH m1' (exportedSrc nu' (ret1 :: nil)) b) = true).\n     intros. specialize (Glob _ H).\n       assert (FSRC:= extern_incr_frgnBlocksSrc _ _ INC).\n          rewrite replace_locals_frgnBlocksSrc in FSRC.\n       rewrite FSRC in Glob.\n       rewrite (frgnBlocksSrc_locBlocksSrc _ WDnu' _ Glob). \n       apply andb_true_iff; simpl.\n        split.\n          unfold DomSrc. rewrite (frgnBlocksSrc_extBlocksSrc _ WDnu' _ Glob). intuition.\n          apply REACH_nil. unfold exportedSrc.\n          rewrite (frgnSrc_shared _ WDnu' _ Glob). intuition.\nrewrite restrict_sm_nest, vis_restrict_sm in *; trivial. \n2: rewrite vis_restrict_sm; trivial.\nsplit. rewrite replace_externs_vis.\n{ (* MATCH*)\n  rewrite restrict_sm_all in *.\n  econstructor. \n  Focus 2. rewrite vis_restrict_sm, restrict_sm_all,\n            replace_externs_vis, replace_externs_as_inj,\n            restrict_nest; trivial.\n          clear - RValInjNu' WDnu'.\n          inv RValInjNu'; econstructor; eauto.\n          apply restrictI_Some; trivial.\n          destruct (locBlocksSrc nu' b1); simpl; trivial.\n          destruct (as_inj_DomRng _ _ _ _ H WDnu') as [dS dT].\n          rewrite dS; simpl.\n          apply REACH_nil. unfold exportedSrc.\n          apply orb_true_iff; left.\n          apply getBlocks_char. exists ofs1; left; eauto.\n  Focus 2. rewrite restrict_sm_all, replace_externs_as_inj.\n    eapply inject_restrict; try eassumption.\n  rewrite vis_restrict_sm, replace_externs_vis.\n  rewrite restrict_sm_nest; trivial. \n  rewrite <- restrict_sm_replace_externs in *.\n   eapply match_stacks_replace_externs.\n    eapply match_stacks_extern_incr.\n      eapply match_stacks_replace_locals; try eassumption. \n       instantiate (2:=fun b => locBlocksSrc mu b &&\n                         REACH m1 (exportedSrc mu vals1) b).\n       instantiate (1:=fun b => locBlocksTgt mu b && \n                         REACH m2 (exportedTgt mu vals2) b).\n       apply replace_locals_wd; try eassumption.\n       intros. rewrite andb_true_iff in H. destruct H as [HH1 HH2]. \n       exploit REACH_local_REACH; try apply HH2. \n          eassumption. eassumption. \n          rewrite restrict_nest in AINJ; trivial. \n          eapply val_list_inject_forall_inject. \n          eapply val_list_inject_incr; try eassumption.\n          apply restrict_incr.\n          assumption.\n      intros [b2 [d [LOC RCH2]]]. exists b2, d; rewrite LOC, RCH2.\n        destruct (local_DomRng _ WDmu _ _ _ LOC) as [_ lT]; intuition.\n      intros. rewrite andb_true_iff in H. destruct H; trivial.\n      eapply restrict_sm_WD; try eassumption. \n      intros. unfold vis in H.\n        destruct (locBlocksSrc nu' b); simpl in *; trivial. \n        apply andb_true_iff; split. \n         unfold DomSrc.\n           rewrite (frgnBlocksSrc_extBlocksSrc _ WDnu' _ H).\n           intuition.\n         apply REACH_nil. unfold exportedSrc.\n           rewrite sharedSrc_iff_frgnpub, H. intuition. trivial.\n      clear - INC WDmu WDnu'.  \n      red in INC; red.    \n          repeat rewrite restrict_sm_extern, restrict_sm_local, \n                  restrict_sm_extBlocksSrc, restrict_sm_extBlocksTgt,\n                  restrict_sm_locBlocksSrc, restrict_sm_locBlocksTgt,\n                  restrict_sm_pubBlocksSrc, restrict_sm_pubBlocksTgt,\n                  restrict_sm_frgnBlocksSrc, restrict_sm_frgnBlocksTgt.\n          rewrite replace_locals_extern, replace_locals_local,\n                  replace_locals_extBlocksSrc, replace_locals_extBlocksTgt,\n                  replace_locals_locBlocksSrc, replace_locals_locBlocksTgt,\n                  replace_locals_pubBlocksSrc, replace_locals_pubBlocksTgt,\n                  replace_locals_frgnBlocksSrc, replace_locals_frgnBlocksTgt in INC. \n          rewrite replace_locals_extern, replace_locals_local,\n                  replace_locals_extBlocksSrc, replace_locals_extBlocksTgt,\n                  replace_locals_locBlocksSrc, replace_locals_locBlocksTgt,\n                  replace_locals_pubBlocksSrc, replace_locals_pubBlocksTgt,\n                  replace_locals_frgnBlocksSrc, replace_locals_frgnBlocksTgt. \n          intuition.\n          red; intros. destruct (restrictD_Some _ _ _ _ _ H8).\n            apply restrictI_Some. apply H; trivial.\n            unfold vis in H11; unfold DomSrc.\n              rewrite H7, H3 in *.\n              destruct (locBlocksSrc nu' b); simpl in *; trivial. \n            apply andb_true_iff; split. \n               apply (frgnBlocksSrc_extBlocksSrc _ WDnu' _ H11).\n               apply REACH_nil. unfold exportedSrc.\n                 rewrite sharedSrc_iff_frgnpub, H11. intuition. trivial.\n          unfold vis. rewrite H1, H3, H7.\n            unfold restrict. extensionality bb. unfold DomSrc. \n            remember (local_of nu' bb) as loc.\n            destruct loc. \n            apply eq_sym in Heqloc. destruct p.\n              destruct (local_DomRng _ WDnu' _ _ _ Heqloc) as [lS _].\n              rewrite lS; simpl; trivial.\n            destruct (locBlocksSrc nu' bb); simpl; trivial.\n            destruct (frgnBlocksSrc nu' bb); simpl; trivial.\n              destruct (extBlocksSrc nu' bb); simpl; trivial.\n              destruct (REACH m1' (exportedSrc nu' (ret1 :: nil)) bb); \n                 simpl; trivial. \n              destruct (extBlocksSrc nu' bb); simpl; trivial.\n              destruct (REACH m1' (exportedSrc nu' (ret1 :: nil)) bb);\n                 simpl; trivial. \n       rewrite vis_restrict_sm, restrict_sm_locBlocksSrc. \n         clear - WDnu'.\n         intros. unfold vis in H.\n         destruct (locBlocksSrc nu' b); simpl in *; trivial. \n         apply andb_true_iff; split. \n          unfold DomSrc.\n            rewrite (frgnBlocksSrc_extBlocksSrc _ WDnu' _ H).\n            intuition.\n          apply REACH_nil. unfold exportedSrc.\n            rewrite sharedSrc_iff_frgnpub, H. intuition. trivial. }\n\nunfold vis in *.\nrewrite replace_externs_locBlocksSrc, replace_externs_frgnBlocksSrc,\n        replace_externs_as_inj in *.\n  \ndestruct (eff_after_check2 _ _ _ _ _ MemInjNu' RValInjNu' \n      _ (eq_refl _) _ (eq_refl _) _ (eq_refl _) WDnu' SMvalNu').\nunfold vis in *.\nintuition.\n(*as in selectionproofEFF*)\n  red; intros. destruct (GFP _ _ H1). split; trivial.\n  eapply extern_incr_as_inj; try eassumption.\n  rewrite replace_locals_as_inj. assumption.\nQed.\n\nLemma MATCH_effcore_diagram: forall \n         st1 m1 st1' m1' (U1 : block -> Z -> bool)\n         (CS: effstep (cminsel_eff_sem hf) ge U1 st1 m1 st1' m1')\n         st2 mu m2 \n         (MTCH: MATCH st1 mu st1 m1 st2 m2),\nexists st2' m2' mu', exists U2 : block -> Z -> bool,\n  (effstep_plus (rtl_eff_sem hf) tge U2 st2 m2 st2' m2' \\/\n      effstep_star (rtl_eff_sem hf) tge U2 st2 m2 st2' m2' /\\ lt_state st1' st1) /\\\n  intern_incr mu mu' /\\ \n  globals_separate ge mu mu' /\\\n  sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n  MATCH st1' mu' st1' m1' st2' m2' /\\\n     (forall \n       (UHyp: forall b z, U1 b z = true -> vis mu b = true)\n        b ofs, U2 b ofs = true ->\n      visTgt mu b = true /\\\n      (locBlocksTgt mu b = false ->\n       exists (b1 : block) (delta1 : Z),\n         foreign_of mu b1 = Some (b, delta1) /\\\n         U1 b1 (ofs - delta1)%Z = true /\\\n         Mem.perm m1 b1 (ofs - delta1) Max Nonempty)).\nProof. intros st1 m1 st1' m1' U1 CS.\n  assert (SymbPres:= symbols_preserved).\n  induction CS; intros; destruct MTCH as [MSTATE PRE]; inv MSTATE. \n{ (* skip seq *)\n  inv TS. inv TK.\n  eexists; exists m2, mu; eexists; split.\n     right; split. apply effstep_star_zero. Lt_state.\n  intuition. \n  apply intern_incr_refl.\n  apply gsep_refl.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto.\n      intuition.  }\n\n{ (* skip block *)\n  inv TS. inv TK. \n  eexists; exists m2, mu; eexists; split. \n    right; split. apply effstep_star_zero. Lt_state.\n  intuition. \n      apply intern_incr_refl. \n      apply gsep_refl.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto. constructor.\n      intuition. }\n\n{ (* skip return *)\n  inv TS. \n  assert ((fn_code tf)!ncont = Some(Ireturn rret)\n          /\\ match_stacks (restrict_sm mu (vis mu)) k cs).\n    inv TK; simpl in H; (*try rewrite restrict_sm_all in *;*)\n         try contradiction; auto. \n  destruct H1.\n  rewrite restrict_sm_all in *.\n  assert (fn_stacksize tf = fn_stackspace f).\n    inv TF. auto.\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  destruct SP as [spb [spb' [X [Y Rsp]]]]; subst sp'; inv X.\n  rewrite restrict_sm_local' in *; trivial. \n  edestruct free_parallel_inject as [tm' []]; eauto.\n    eapply incr_local_restrictvis; eassumption.  \n  eexists; exists tm', mu, (FreeEffect m2 0 (fn_stacksize tf) spb'); split.\n    simpl in *; rewrite Zplus_0_r in H4. rewrite <- H3 in H4.\n    left; apply effstep_plus_one. \n      eapply rtl_effstep_exec_Ireturn; try eassumption.\n  assert (SMV': sm_valid mu m' tm').\n    split; intros;  \n      eapply free_forward; try eassumption.\n      eapply SMV; assumption.\n      eapply SMV; assumption.\n  intuition. \n      apply intern_incr_refl. \n      apply gsep_refl.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_free _ _ _ _ _ H4);\n          try rewrite (freshloc_free _ _ _ _ _ H0); intuition.\n  split. \n    econstructor; eauto.\n      rewrite restrict_sm_nest, vis_restrict_sm; trivial.\n        rewrite vis_restrict_sm; trivial.\n      rewrite restrict_sm_all; trivial.      \n    intuition.\n    eapply REACH_closed_free; try eassumption.\n      eapply (free_free_inject _ m m' m2); try eassumption.\n    eapply local_in_all; eassumption.\n  apply FreeEffectD in H6. destruct H6 as [? [VB Arith2]]; subst.\n        eapply local_visTgt; eassumption.\n  rewrite H3 in H6. eapply FreeEffect_PropagateLeft'; eassumption. }\n\n{ (* assign *)\n  inv TS.\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  rewrite restrict_sm_all, restrict_sm_local' in *; trivial.\n  exploit Efftransl_expr_correct; eauto. \n  intros [rs' [tm' [mu' [MU' [A [B [C [D E]]]]]]]]; subst.\n  destruct MU' as [INC' [SEP' [GSEP' [LOCALLOC' [WD' [SMV' RC']]]]]].\n  assert (PG':  meminj_preserves_globals ge (as_inj mu')).\n  eapply meminj_preserves_globals_intern_incr_separate; eassumption.\n   (*eapply meminj_preserves_incr_sep_vb \n        with (j:=as_inj mu)(m0:=m)(tm:=m2); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.*)\n  clear PG.\n  eexists; eexists; exists mu', EmptyEffect; split.\n    right; split. eauto. Lt_state.\n  assert (WDR: SM_wd (restrict_sm mu' (vis mu'))).\n     apply restrict_sm_WD; trivial. \n  specialize (restrict_sm_intern_incr _ _ WD' INC'); intros INCR.\n  intuition. \n  split.\n      econstructor; try rewrite restrict_sm_nest; \n            try rewrite restrict_sm_all; eauto.\n        econstructor; eauto. \n        eapply tr_cont_intern_incr; try eassumption.\n        eapply inject_restrict; eassumption.\n        eapply sp_incr; try eassumption.\n          rewrite restrict_sm_local'; trivial. eapply INC'.\n    intuition.\n\n    red; intros ? ? Hb. destruct (GFP _ _ Hb). split; trivial.\n         eapply intern_incr_as_inj; eassumption.\n    assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n      rewrite <-FF; auto. }\n\n{ (* store *)\n  inv TS.\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  rewrite restrict_sm_all, restrict_sm_local' in *; trivial.\n  exploit Efftransl_exprlist_correct; eauto.\n  intros [rs' [tm' [mu' [MU' [A [B [C [D E]]]]]]]]; subst.\n  destruct MU' as [INC' [SEP' [GSEP' [LOCALLOC' [WD' [SMV' RC']]]]]].\n  assert (PG':  meminj_preserves_globals ge (as_inj mu')).\n  eapply meminj_preserves_globals_intern_incr_separate; eassumption.\n   (*eapply meminj_preserves_incr_sep_vb \n        with (j:=as_inj mu)(m0:=m)(tm:=m2); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.*)\n  assert (PGR' : meminj_preserves_globals ge\n                (restrict (as_inj mu') (vis mu'))).\n     rewrite <- restrict_sm_all. \n     eapply restrict_sm_preserves_globals; try eassumption.\n     intros. eapply intern_incr_vis; try eassumption.\n      unfold vis. intuition.\n  clear PG.\n  exploit sp_preserved_intern_incr; try eassumption.\n  intros SP'; clear SP.\n  exploit Efftransl_expr_correct; eauto.\n    assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n    rewrite <- FF; intuition.\n  intros [rs'' [tm'' [mu'' [MU'' [F [G [J [K L]]]]]]]]; subst.\n  destruct MU'' as [INC'' [SEP'' [GSEP'' [LOCALLOC'' [WD'' [SMV'' RC'']]]]]].\n  assert (val_list_inject (restrict (as_inj mu') (vis mu')) vl rs''##rl).\n    replace (rs'' ## rl) with (rs' ## rl). auto.\n    apply list_map_exten. intros. apply K. auto.\n  destruct SP' as [spb [spb' [X [Y Rsp]]]]; subst sp'; inv X. \n  edestruct eval_addressing_inject as [vaddr' []]; try eapply H1.\n    apply PGR'.\n    eapply incr_local_restrictvis; eassumption.\n    eassumption.\n  edestruct Mem.storev_mapped_inject as [tm''' []].\n    eapply (inject_restrict _ _ _ _ L RC''). \n    eassumption.\n    eapply val_inject_incr; try eassumption.\n       eapply intern_incr_restrict; try eassumption.\n    eassumption.\n  assert (SMV''': sm_valid mu'' m' tm''').\n    split; intros. \n      eapply storev_valid_block_1; try eassumption.\n        eapply SMV''; assumption.\n      eapply storev_valid_block_1; try eassumption.\n        eapply SMV''; assumption.\n  assert (ADDRINJ: val_inject (restrict (as_inj mu) (vis mu)) vaddr vaddr').\n           clear - INC' SEP' WD WD' H5 H2 Glob. inv H5; inv H2.\n           destruct (restrictD_Some _ _ _ _ _ H) as [AI' VS']. \n           destruct SEP' as [SEPa [SEPb SEPc]].\n           econstructor; try reflexivity.\n           remember (as_inj mu b1) as d. \n           destruct d; apply eq_sym in Heqd.\n             destruct p.\n             rewrite (intern_incr_as_inj _ _ INC' WD' _ _ _ Heqd) in AI'. \n             inv AI'.\n             apply restrictI_Some; try eassumption. \n             eapply intern_incr_vis_inv with (nu:=mu'); eassumption. \n             destruct (SEPa _ _ _ Heqd AI') as [DS _]. \n             destruct (as_inj_DomRng _ _ _ _ AI' WD') as [DS' _]. \n             elim (SEPb _ DS DS'). \n             exploit Mem.store_valid_access_3. eapply H1. intros. \n              eapply Mem.valid_access_valid_block; try eassumption.\n              eapply Mem.valid_access_implies; try eassumption. \n                 constructor. \n  eexists; exists tm''', mu''.\n    exists (StoreEffect vaddr' (encode_val chunk (rs'' # rd))).\n  split.\n    left; eapply effstep_star_plus_trans'.\n      eapply effstep_star_trans'. eexact A. eexact F. reflexivity.\n      eapply effstep_plus_one. \n        eapply rtl_effstep_exec_Istore with (a := vaddr'). eauto.\n        rewrite <- H4. rewrite shift_stack_addressing_zero.\n        eapply eval_addressing_preserved. exact symbols_preserved.\n      eassumption.\n      simpl. extensionality bb; extensionality z. \n       remember (StoreEffect vaddr' (encode_val chunk rs'' # rd) bb z) as d.\n       destruct d; simpl; apply eq_sym in Heqd; trivial.\n         destruct (valid_block_dec m2 bb); trivial.\n         elim n; clear n.\n         destruct vaddr; inv H2. inv H5. \n         apply StoreEffectD in Heqd. destruct Heqd as [ii [VV Arith]].\n         inv VV. clear -  ADDRINJ MINJ. inv ADDRINJ.\n             eapply Mem.valid_block_inject_2; eassumption.\n  split. \n    eapply intern_incr_trans; eassumption. \n  split. \n  eapply gsep_trans'; eassumption.\n  split. eapply sm_locally_allocated_trans. eapply LOCALLOC'. \n      apply sm_locally_allocatedChar.\n      apply sm_locally_allocatedChar in LOCALLOC''.\n      destruct LOCALLOC'' as [DS [DT [LBS [LBT [EBS EBT]]]]].\n      rewrite DS, DT, LBS, LBT, EBS, EBT.\n      repeat split; extensionality bb;\n        try rewrite (freshloc_irrefl);\n        try rewrite (storev_freshloc _ _ _ _ _ H2);\n        try rewrite (storev_freshloc _ _ _ _ _ H6); intuition.\n      rewrite <- (freshloc_trans tm' tm'' tm''' ), \n                 (storev_freshloc _ _ _ _ _ H6).\n          rewrite orb_false_r. trivial. \n             eapply effstep_star_fwd. eassumption.\n             destruct vaddr'; inv H6. eapply store_forward; eassumption.\n      rewrite <- (freshloc_trans tm' tm'' tm''' ), \n                 (storev_freshloc _ _ _ _ _ H6).\n          rewrite orb_false_r. trivial. \n             eapply effstep_star_fwd. eassumption.\n             destruct vaddr'; inv H6. eapply store_forward; eassumption.\n        apply mem_forward_refl.\n        destruct vaddr; inv H2. eapply store_forward; eassumption.\n        eapply effstep_star_fwd. eassumption.\n        eapply mem_forward_trans.\n           eapply effstep_star_fwd; eassumption.\n           destruct vaddr'; inv H6. eapply store_forward; eassumption.\n    assert (WDR': SM_wd (restrict_sm mu' (vis mu'))).\n      apply restrict_sm_WD; trivial. \n    assert (WDR'': SM_wd (restrict_sm mu'' (vis mu''))).\n      apply restrict_sm_WD; trivial. \n    specialize (restrict_sm_intern_incr _ _ WD' INC'); intros INCR'.\n    specialize (restrict_sm_intern_incr _ _ WD'' INC''); intros INCR''.\n  split.\n    split.\n      econstructor; try rewrite restrict_sm_all; eauto. \n        constructor.\n        eapply tr_cont_intern_incr; try eassumption.\n          eapply intern_incr_trans; eassumption.\n        rewrite restrict_sm_local'; trivial.\n        eapply sp_preserved_intern_incr; try eassumption. \n          exists spb, spb'. split; trivial. split; trivial.\n      intuition.\n\n      destruct vaddr; inv H2.\n        eapply REACH_Store; try eassumption. \n          inv H5. destruct (restrictD_Some _ _ _ _ _ H10); trivial.\n           eapply intern_incr_vis; eassumption.\n          intros b' Hb'. rewrite getBlocks_char in Hb'. destruct Hb' as [off Hoff].\n             destruct Hoff; try contradiction. subst.   \n             inv J. destruct (restrictD_Some _ _ _ _ _ H11); trivial.\n      eapply meminj_preserves_globals_intern_incr_separate; eassumption.\n   (*eapply meminj_preserves_incr_sep_vb \n        with (j:=as_inj mu)(m0:=m)(tm:=m2); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.*)\n\n      red; intros ? ? Hb. destruct (GFP _ _ Hb). split; trivial.\n         eapply intern_incr_as_inj; try eapply H8. \n         eapply intern_incr_trans; eassumption.\n         assumption.\n      assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n        assert (FF': frgnBlocksSrc mu' = frgnBlocksSrc mu'') by eapply INC''.\n        rewrite <-FF', <-FF; auto. \n      assert (VaddrMu: val_inject (as_inj mu'') vaddr vaddr').\n        eapply val_inject_incr; try eapply H5.\n        eapply inject_incr_trans. apply restrict_incr. \n          apply intern_incr_as_inj; eassumption.\n      assert (VMu: val_inject (as_inj mu'') v (rs'' # rd)).\n        eapply val_inject_incr; try eassumption.\n        apply restrict_incr. \n      destruct (Mem.storev_mapped_inject _ _ _ _ _ _ _ _ _ \n          L H2 VaddrMu VMu) as [mm [Hmm1 Hmm2]].\n      rewrite Hmm1 in H6. inv H6. assumption. \n (*effect propagation*)\n  intros.\n  destruct (StoreEffectD _ _ _ _ H8) as [i [HI OFF]]. subst.\n  simpl in H6. (*inv ADDRINJ; inv H2. *)\n  assert (VIST: visTgt mu b0 = true). \n     inv ADDRINJ; inv H2.\n     eapply visPropagateR; try eassumption.\n  intuition. \n    unfold visTgt in VIST; rewrite H11 in VIST; simpl in VIST. \n    exploit StoreEffect_PropagateLeft.\n         eapply H2. 2: eapply L. eassumption.\n         eapply val_inject_incr; try eapply H5.\n            apply intern_incr_restrict; eassumption.\n         simpl. eassumption. \n         eassumption. \n         eapply frgnBlocksTgt_locBlocksTgt; try eassumption.\n          assert (FF: frgnBlocksTgt mu = frgnBlocksTgt mu') by eapply INC'.\n          assert (FF': frgnBlocksTgt mu' = frgnBlocksTgt mu'') by eapply INC''.\n          rewrite <- FF', <- FF; trivial.\n   intros [b1 [delta [FRG' [STEFF PERM]]]].\n     exists b1, delta. repeat split; trivial.\n     rewrite (intern_incr_foreign _ _ INC').\n     rewrite (intern_incr_foreign _ _ INC''). trivial. }\n\n{ (* call *)\n  inv TS; inv H.\n  (* indirect *)\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  rewrite restrict_sm_all in *.\n  rewrite restrict_sm_local' in SP; trivial.\n  exploit Efftransl_expr_correct; eauto.\n  intros [rs' [tm' [mu' [MU' [A [B [C [D E]]]]]]]]. \n  destruct MU' as [INC' [SEP' [GSEP' [LOCALLOC' [WD' [SMV' RC']]]]]].\n  assert (PG':  meminj_preserves_globals ge (as_inj mu')).\n   eapply meminj_preserves_incr_sep_vb \n        with (j:=as_inj mu)(m0:=m)(tm:=m2); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.\n  assert (PGR' : meminj_preserves_globals ge\n                (restrict (as_inj mu') (vis mu'))).\n     rewrite <- restrict_sm_all. \n     eapply restrict_sm_preserves_globals; try eassumption.\n     intros. eapply intern_incr_vis; try eassumption.\n      unfold vis. intuition.\n  clear PG.\n  exploit sp_preserved_intern_incr; try eassumption.\n  intros SP'; clear SP.\n  exploit Efftransl_exprlist_correct; eauto.\n    assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n    rewrite <- FF; intuition.\n  intros [rs'' [tm'' [mu'' [MU'' [F [G [J [K L]]]]]]]]. \n  destruct MU'' as [INC'' [SEP'' [GSEP'' [LOCALLOC'' [WD'' [SMV'' RC'']]]]]].\n  exploit functions_translated; eauto. intros [tf' [P Q]].\n  destruct (Genv.find_funct_inv _ _ H1) as [bb XX]; subst vf.\n  rewrite Genv.find_funct_find_funct_ptr in H1.\n  destruct (GFP _ _ H1) as [muBB isGlobalBB].\n  inv C. destruct (restrictD_Some _ _ _ _ _ H5). \n  exploit (intern_incr_as_inj _ _ INC'). \n     apply WD'. apply muBB. \n  rewrite H; intros XX; inv XX. \n  rewrite Int.add_zero in H3.\n  eexists; eexists; exists mu'', EmptyEffect; split.\n    left; eapply effstep_star_plus_trans'.\n            eapply effstep_star_trans. eexact A. eexact F.\n          eapply effstep_plus_one. \n            eapply rtl_effstep_exec_Icall; eauto.\n               simpl. rewrite K. rewrite <- H3. eassumption. simpl; eauto.\n               apply sig_transl_function; auto.\n          reflexivity.\n  intuition.\n  eapply intern_incr_trans; eassumption.\n  eapply gsep_trans'; eassumption.\n      eapply sm_locally_allocated_trans; try eassumption.      \n         apply mem_forward_refl.   \n         apply mem_forward_refl.\n         eapply effstep_star_fwd; eassumption.\n         eapply effstep_star_fwd; eassumption.\n  assert (WDR': SM_wd (restrict_sm mu' (vis mu'))).\n      apply restrict_sm_WD; trivial. \n  assert (WDR'': SM_wd (restrict_sm mu'' (vis mu''))).\n      apply restrict_sm_WD; trivial. \n  specialize (restrict_sm_intern_incr _ _ WD' INC'); intros INCR'.\n  specialize (restrict_sm_intern_incr _ _ WD'' INC''); intros INCR''.\n  split. \n    econstructor; try rewrite restrict_sm_nest, vis_restrict_sm; eauto. \n      econstructor; try rewrite restrict_sm_all; try eassumption.\n      \n      eapply tr_cont_intern_incr; try eassumption.\n          eapply intern_incr_trans; eassumption.\n      exploit sp_preserved_intern_incr; try eassumption. \n        rewrite restrict_sm_local'; trivial.\n      rewrite vis_restrict_sm; trivial.\n      rewrite restrict_sm_all, restrict_nest, vis_restrict_sm; try eassumption. \n      rewrite vis_restrict_sm; trivial.\n      rewrite restrict_sm_all. eapply inject_restrict; eassumption.\n      intuition.\n   eapply meminj_preserves_incr_sep_vb\n        with (j:=as_inj mu')(m0:=m)(tm:=tm'); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV'; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.\n    red; intros ? ? Hb. destruct (GFP _ _ Hb). split; trivial.\n         eapply intern_incr_as_inj; try eapply H8. \n         eapply intern_incr_trans. eapply INC'. eassumption. assumption.\n         assumption.\n    assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n      assert (FF': frgnBlocksSrc mu' = frgnBlocksSrc mu'') by eapply INC''.\n      rewrite <-FF', <-FF; auto. \n  (* direct *)\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  rewrite restrict_sm_all in *.\n  rewrite restrict_sm_local' in SP; trivial.\n  exploit Efftransl_exprlist_correct; eauto.\n  intros [rs' [tm' [mu' [MU' [A [B [C [D E]]]]]]]]. \n  destruct MU' as [INC' [SEP' [GSEP' [LOCALLOC' [WD' [SMV' RC']]]]]].\n  assert (PG':  meminj_preserves_globals ge (as_inj mu')).\n   eapply meminj_preserves_incr_sep_vb \n        with (j:=as_inj mu)(m0:=m)(tm:=m2); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.\n  assert (PGR' : meminj_preserves_globals ge\n                (restrict (as_inj mu') (vis mu'))).\n     rewrite <- restrict_sm_all. \n     eapply restrict_sm_preserves_globals; try eassumption.\n     intros. eapply intern_incr_vis; try eassumption.\n      unfold vis. intuition.\n  clear PG.\n  exploit sp_preserved_intern_incr; try eassumption.\n  intros SP'; clear SP.\n  exploit functions_translated; eauto. intros [tf' [P Q]].\n  rewrite Genv.find_funct_find_funct_ptr in H1.\n  destruct (GFP _ _ H1) as [muBB isGlobalBB].\n  eexists; eexists; exists mu', EmptyEffect; split.\n    left. eapply effstep_star_plus_trans'. eexact A.\n          eapply effstep_plus_one. \n            eapply rtl_effstep_exec_Icall; eauto. \n             simpl. rewrite symbols_preserved. rewrite H4. \n             rewrite Genv.find_funct_find_funct_ptr in P. eauto. \n             apply sig_transl_function; auto.\n          reflexivity.\n  intuition. \n  assert (WDR': SM_wd (restrict_sm mu' (vis mu'))).\n      apply restrict_sm_WD; trivial. \n  specialize (restrict_sm_intern_incr _ _ WD' INC'); intros INCR'.\n  split. \n    econstructor; try rewrite restrict_sm_nest, restrict_sm_all, \n             vis_restrict_sm; eauto.\n      rewrite restrict_sm_nest.\n      econstructor; try rewrite vis_restrict_sm; try eassumption. \n        rewrite restrict_sm_all; try eassumption.\n      eapply tr_cont_intern_incr; try eassumption.\n      rewrite restrict_sm_local'; trivial.\n      rewrite vis_restrict_sm; trivial.\n      rewrite restrict_sm_all, vis_restrict_sm, restrict_nest; trivial.\n      rewrite restrict_sm_all. eapply inject_restrict; eassumption.\n      intuition.\n    red; intros ? ? Hb. destruct (GFP _ _ Hb). split; trivial.\n         eapply intern_incr_as_inj; try eapply H8. \n         eassumption. assumption.\n         assumption.\n    assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n      rewrite <-FF; auto. }\n\n{ (* tailcall *)\n  inv TS; inv H.\n  (* indirect *)\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  rewrite restrict_sm_all in *.\n  rewrite restrict_sm_local' in SP; trivial.\n  exploit Efftransl_expr_correct; eauto.\n  intros [rs' [tm' [mu' [MU' [A [B [C [D E]]]]]]]]. \n  destruct MU' as [INC' [SEP'[GSEP'  [LOCALLOC' [WD' [SMV' RC']]]]]].\n  assert (PG':  meminj_preserves_globals ge (as_inj mu')).\n   eapply meminj_preserves_incr_sep_vb \n        with (j:=as_inj mu)(m0:=m)(tm:=m2); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.\n  clear PG.\n  exploit sp_preserved_intern_incr; try eassumption.\n  intros SP'.\n  exploit Efftransl_exprlist_correct; try eapply PG'.\n     eassumption.  eassumption.  eassumption.  eassumption. \n     eassumption.  \n     assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n      rewrite <- FF; intuition.\n     eassumption.  eassumption.  eassumption.\n     eassumption.  eassumption. \n  intros [rs'' [tm'' [mu'' [MU'' [EX [F [G [J K]]]]]]]].\n  destruct MU'' as [INC'' [SEP''[GSEP''  [LOCALLOC'' [WD'' [SMV'' RC'']]]]]].\n  exploit functions_translated; eauto. intros [tf' [P Q]].\n  exploit match_stacks_call_cont; eauto. intros [U V].\n  assert (FSS: fn_stacksize tf = fn_stackspace f). inv TF; auto.\n  exploit sp_preserved_intern_incr; try eassumption.\n  intros SP''; clear SP'.\n  destruct SP'' as [spb [spb' [SPB [SPB' Rsp]]]]; subst sp'; inv SPB. \n  edestruct free_parallel_inject as [tm''' []]; eauto.\n    eapply local_in_all; eassumption.\n  destruct (Genv.find_funct_inv _ _ H1) as [bb XX]; subst vf.\n  rewrite Genv.find_funct_find_funct_ptr in H1.\n  destruct (GFP _ _ H1) as [muBB isGlobalBB].\n  inv C. destruct (restrictD_Some _ _ _ _ _ H9). \n     specialize (intern_incr_as_inj _ _ INC' WD' _ _ _ muBB). \n     intros XX; rewrite H4 in XX; inv XX. \n  rewrite Int.add_zero in H8.\n  simpl in H. rewrite Zplus_0_r in H.\n  assert (LOC: local_of mu spb = Some (spb', 0%Z)). \n     destruct SP as [xb [xtb [XX [YY LOC]]]]; inv XX; inv YY.\n     trivial.    \n  eexists; exists tm'''; exists mu''. \n  exists (FreeEffect tm'' 0 (fn_stacksize tf) spb').\n  split. left; eapply effstep_star_plus_trans'.\n           eapply effstep_star_trans. eexact A. eexact EX.\n           eapply effstep_plus_one.\n             eapply rtl_effstep_exec_Itailcall; eauto.\n             simpl. rewrite J. rewrite <- H8. eassumption.\n             simpl; eauto.\n             apply sig_transl_function; auto.\n           rewrite FSS. eassumption.\n         simpl. apply extensionality; intros b'. \n                apply extensionality; intros z.\n             remember (FreeEffect tm'' 0 (fn_stacksize tf) spb' b' z) as d. \n             destruct d; simpl; trivial. \n             apply eq_sym in Heqd. \n             apply FreeEffectD in Heqd. \n             destruct Heqd as [? [? ?]]; subst.\n             clear - LOC WD SMV MInj. \n             apply local_in_all in LOC; trivial.\n             destruct (as_inj_DomRng _ _ _ _ LOC WD) as [_ DT].\n             destruct (valid_block_dec m2 spb'); simpl; trivial. \n             elim n. eapply SMV; trivial. \n  assert (SMV''': sm_valid mu'' m' tm''').\n    split; intros;\n      eapply Mem.valid_block_free_1; try eassumption;\n      eapply SMV''; assumption.\n  assert (WDR': SM_wd (restrict_sm mu' (vis mu'))).\n      apply restrict_sm_WD; trivial. \n  assert (WDR'': SM_wd (restrict_sm mu'' (vis mu''))).\n      apply restrict_sm_WD; trivial. \n  specialize (restrict_sm_intern_incr _ _ WD' INC'); intros INCR'.\n  specialize (restrict_sm_intern_incr _ _ WD'' INC''); intros INCR''.\n  intuition.\n  eapply intern_incr_trans; eassumption.\n  eapply gsep_trans'; eassumption.\n    eapply sm_locally_allocated_trans. eapply LOCALLOC'. \n      apply sm_locally_allocatedChar.\n      apply sm_locally_allocatedChar in LOCALLOC''.\n      destruct LOCALLOC'' as [DS [DT [LBS [LBT [EBS EBT]]]]].\n      rewrite DS, DT, LBS, LBT, EBS, EBT.\n      repeat split; extensionality bbb;\n        try rewrite (freshloc_irrefl);\n        try rewrite (freshloc_free _ _ _ _ _ H);\n        try rewrite (freshloc_free _ _ _ _ _ H3); intuition.\n      rewrite <- (freshloc_trans tm' tm'' tm''' ), \n                 (freshloc_free _ _ _ _ _ H).\n          rewrite orb_false_r. trivial. \n             eapply effstep_star_fwd. eassumption.\n             eapply free_forward; eassumption.\n      rewrite <- (freshloc_trans tm' tm'' tm''' ), \n                 (freshloc_free _ _ _ _ _ H).\n          rewrite orb_false_r. trivial. \n             eapply effstep_star_fwd. eassumption.\n             eapply free_forward; eassumption.\n        apply mem_forward_refl.\n        eapply free_forward; eassumption.\n        eapply effstep_star_fwd; eassumption.\n        eapply mem_forward_trans.\n          eapply effstep_star_fwd; eassumption.\n          eapply free_forward; eassumption.\n    assert (RC''': REACH_closed m' (vis mu'')).\n        eapply REACH_closed_free; eassumption.\n    split. \n      econstructor; try rewrite restrict_sm_all, vis_restrict_sm, \n           restrict_nest; eauto. \n        rewrite restrict_sm_nest, vis_restrict_sm; trivial.\n        eapply match_stacks_intern_incr; try eassumption.\n            eapply intern_incr_trans; eassumption.\n        rewrite vis_restrict_sm; trivial.\n        rewrite restrict_sm_all. \n          eapply inject_restrict; try eassumption.\n      intuition.\n   eapply meminj_preserves_incr_sep_vb\n        with (j:=as_inj mu')(m0:=m)(tm:=tm'); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV'; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.\n    red; intros ? ? Hb. destruct (GFP _ _ Hb). split; trivial.\n         eapply intern_incr_as_inj; try eapply H8. \n         eapply intern_incr_trans. eapply INC'. eassumption. assumption.\n         assumption.\n    assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n      assert (FF': frgnBlocksSrc mu' = frgnBlocksSrc mu'') by eapply INC''.\n      rewrite <-FF', <-FF; auto. \n  apply FreeEffectD in H10. destruct H10 as [? [VB Arith2]]; subst.\n    eapply local_visTgt; eassumption.      \n  rewrite FSS in H10. \n    exploit FreeEffect_PropagateLeft'; try eapply H10.\n      eapply H3. eassumption. eassumption.  eassumption. \n       apply FreeEffectD in H10. destruct H10 as [? [VB Arith2]]; subst.\n       destruct (local_DomRng _ WD _ _ _ LOC) as [_ lT].\n       rewrite lT in H11; discriminate.\n    intros [b1 [delta [FRG' [STEFF PERM]]]].\n      exists b1, delta. repeat split; trivial.\n      rewrite (intern_incr_foreign _ _ INC').\n      rewrite (intern_incr_foreign _ _ INC''). trivial. \n\n  (* direct *)\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  rewrite restrict_sm_all in *.\n  rewrite restrict_sm_local' in SP; trivial.\n  exploit Efftransl_exprlist_correct; eauto.\n  intros [rs' [tm' [mu' [MU' [A [B [C [D E]]]]]]]]. \n  destruct MU' as [INC' [SEP' [GSEP'  [LOCALLOC' [WD' [SMV' RC']]]]]].\n  assert (PG':  meminj_preserves_globals ge (as_inj mu')).\n   eapply meminj_preserves_incr_sep_vb \n        with (j:=as_inj mu)(m0:=m)(tm:=m2); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.\n  clear PG.\n  exploit sp_preserved_intern_incr; try eassumption.\n  intros SP'.\n  exploit functions_translated; eauto. intros [tf' [P Q]].\n  exploit match_stacks_call_cont; eauto. intros [U V].\n  assert (FSS: fn_stacksize tf = fn_stackspace f). inv TF; auto.\n  destruct SP' as [spb [spb' [SPB [SPB' Rsp]]]]; subst sp'; inv SPB.\n  edestruct free_parallel_inject as [tm''' []]; eauto.\n    apply local_in_all; eassumption.\n  simpl in H. rewrite Zplus_0_r in H.\n  assert (LOC: local_of mu spb = Some (spb', 0%Z)). \n     destruct SP as [xb [xtb [XX [YY LOC]]]]; inv XX; inv YY.\n     assumption. \n  eexists; exists tm''', mu';\n    exists (FreeEffect tm' 0 (fn_stacksize tf) spb'). \n  split. left; eapply effstep_star_plus_trans'. eexact A.\n          eapply effstep_plus_one.\n            eapply rtl_effstep_exec_Itailcall; eauto.\n             simpl. rewrite symbols_preserved. rewrite H5. \n             rewrite Genv.find_funct_find_funct_ptr in P. eauto. \n             apply sig_transl_function; auto.\n           rewrite FSS. assumption.\n         simpl. apply extensionality; intros b'. \n                apply extensionality; intros z.\n             remember (FreeEffect tm' 0 (fn_stacksize tf) spb' b' z) as d. \n             destruct d; simpl; trivial. \n             apply eq_sym in Heqd. \n             apply FreeEffectD in Heqd. \n             destruct Heqd as [? [? ?]]; subst.\n             clear - LOC WD SMV MInj. \n             apply local_in_all in LOC; trivial.\n             destruct (as_inj_DomRng _ _ _ _ LOC WD) as [_ DT].\n             destruct (valid_block_dec m2 spb'); simpl; trivial. \n             elim n. eapply SMV; trivial. \n  assert (SMV'': sm_valid mu' m' tm''').\n    split; intros;\n      eapply Mem.valid_block_free_1; try eassumption;\n      eapply SMV'; assumption.\n  assert (WDR': SM_wd (restrict_sm mu' (vis mu'))).\n      apply restrict_sm_WD; trivial. \n  specialize (restrict_sm_intern_incr _ _ WD' INC'); intros INCR'.\n  split. trivial.\n  split. trivial.\n  split.\n    eapply sm_locally_allocated_trans. eapply LOCALLOC'. \n      apply sm_locally_allocatedChar.\n      repeat split; extensionality bbb;\n        try rewrite (freshloc_free _ _ _ _ _ H);\n        try rewrite (freshloc_free _ _ _ _ _ H3); intuition.\n        apply mem_forward_refl.\n        eapply free_forward; eassumption.\n        eapply effstep_star_fwd; eassumption.\n        eapply free_forward; eassumption.\n  assert (RC'': REACH_closed m' (vis mu')).\n        eapply REACH_closed_free; eassumption.\n  split. \n    split.\n      econstructor; try rewrite restrict_sm_all, vis_restrict_sm, \n           restrict_nest; eauto. \n        rewrite restrict_sm_nest, vis_restrict_sm; trivial.\n          eapply match_stacks_intern_incr; try eassumption.\n        rewrite vis_restrict_sm; trivial.\n        rewrite restrict_sm_all. \n          eapply inject_restrict; try eassumption.\n    intuition. \n    red; intros ? ? Hb. destruct (GFP _ _ Hb). split; trivial.\n         eapply intern_incr_as_inj; eassumption.\n    assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n      rewrite <-FF; auto.\n  (*effect propagation*)\n  intros UVis ? z FREFF.\n  split. apply FreeEffectD in FREFF. \n         destruct FREFF as [? [VB Arith2]]; subst.\n         eapply local_visTgt; eassumption.  \n  rewrite FSS in FREFF; intros lTF.\n  exploit FreeEffect_PropagateLeft'; try eapply FREFF.\n      eapply H3. eassumption. eassumption.  eassumption. \n       apply FreeEffectD in FREFF. destruct FREFF as [? [VB Arith2]]; subst.\n       destruct (local_DomRng _ WD _ _ _ LOC) as [_ lT].\n       rewrite lT in lTF; discriminate.\n    intros [b1 [delta [FRG' [STEFF PERM]]]].\n      exists b1, delta. repeat split; trivial.\n      rewrite (intern_incr_foreign _ _ INC'). trivial.  }\n\n{  (* builtin*)\n  inv TS. \n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD INJ]]]]]].\n  rewrite restrict_sm_all in *.\n  rewrite restrict_sm_local' in SP; trivial.\n  exploit Efftransl_exprlist_correct; try eapply MINJ; try eassumption.\n  intros [rs' [tm' [mu' [MU' [A [B [C [D E]]]]]]]]. \n  destruct MU' as [INC' [SEP' [GSEP'  [LOCALLOC' [WD' [SMV' RC']]]]]].\n  assert (PG':  meminj_preserves_globals ge (as_inj mu')).\n   eapply meminj_preserves_incr_sep_vb \n        with (j:=as_inj mu)(m0:=m)(tm:=m2); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.\n  clear PG.\n  exploit sp_preserved_intern_incr; try eassumption.\n  intros SP'; clear SP.\n  exploit (inlineable_extern_inject _ _ GDE_lemma);\n     try eapply C; try eassumption.   \n     assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'. \n       rewrite <- FF; eapply Glob; eassumption. \n  intros [mu'' [vres' [tm'' [EC [VINJ [MINJ' [UNMAPPED [OUTOFREACH \n           [INC'' [SEP'' [GSEP'' [LOCALLOC'' [WD'' [SMV'' RC'']]]]]]]]]]]]]].\n  eexists; eexists; eexists mu''. eexists.\n  split. left.\n    eapply effstep_star_plus_trans'. eapply A.\n      eapply effstep_plus_one.\n      eapply rtl_effstep_exec_Ibuiltin. eauto. eassumption.\n      assumption. reflexivity.\n  exploit sp_preserved_intern_incr; try eassumption.\n  intros SP''; clear SP'.\n  assert (WDR': SM_wd (restrict_sm mu' (vis mu'))).\n      apply restrict_sm_WD; trivial. \n  assert (WDR'': SM_wd (restrict_sm mu'' (vis mu''))).\n      apply restrict_sm_WD; trivial. \n  specialize (restrict_sm_intern_incr _ _ WD' INC'); intros INCR'.\n  specialize (restrict_sm_intern_incr _ _ WD'' INC''); intros INCR''.\n  split.\n    eapply intern_incr_trans; eassumption.\n  split. \n  eapply gsep_trans'; eassumption.\n  split.    eapply sm_locally_allocated_trans; try eassumption. \n      apply mem_forward_refl.\n      eapply external_call_mem_forward; eassumption.\n      eapply effstep_star_fwd; eassumption.\n      eapply external_call_mem_forward; eassumption.\n  split. \n    split.\n      econstructor; try rewrite restrict_sm_all, vis_restrict_sm, \n           restrict_nest; eauto. \n      constructor.\n      eapply tr_cont_intern_incr; try eassumption.\n        eapply intern_incr_trans; eassumption.\n      rewrite restrict_sm_all.\n        eapply match_env_update_dest; eauto.\n          eapply match_env_inject_incr; try eassumption.\n          eapply intern_incr_restrict; try eassumption.\n      rewrite restrict_sm_all.\n       eapply inject_restrict; try eassumption. auto.\n      destruct SP'' as [spb [tspb [? [? BSP]]]].\n        exists spb, tspb. split; trivial. split; trivial.\n          rewrite restrict_sm_local'; trivial.\n    intuition.\n    eapply meminj_preserves_incr_sep. eapply PG'. eassumption. \n             apply intern_incr_as_inj; trivial.\n             apply sm_inject_separated_mem; eassumption.\n    red; intros ? ? Hb. destruct (GFP _ _ Hb).\n          split; trivial.\n          eapply intern_incr_as_inj; try eapply H2. \n          eapply intern_incr_trans; eassumption.\n          assumption.\n    assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n     assert (FRG': frgnBlocksSrc mu' = frgnBlocksSrc mu'') by eapply INC''.\n          rewrite <- FRG', <- FRG. eapply Glob; eassumption. \n  (*effect propagation*)\n  simpl. intros UVis b z EFF. \n    apply andb_true_iff in EFF; destruct EFF as [EFF VB].\n    exploit @BuiltinEffect_Propagate; try eapply EFF. \n     4: eassumption. eassumption. eassumption. eassumption.\n      rewrite (intern_incr_foreign _ _ INC'). \n  intros [visT EffProp].\n  assert (FF: frgnBlocksTgt mu = frgnBlocksTgt mu') by eapply INC'.\n  assert (VIST: visTgt mu b = true). \n    clear EffProp.\n    unfold visTgt; unfold visTgt in visT. rewrite <- FF in visT.\n    clear FF. destruct (frgnBlocksTgt mu b). apply orb_true_r.\n    rewrite orb_false_r in visT.\n    apply sm_locally_allocatedChar in LOCALLOC'.\n      destruct LOCALLOC' as [_ [_ [_ [lT _]]]]. rewrite lT in visT.\n      destruct (locBlocksTgt mu b); simpl in *. trivial.\n      apply freshloc_charT in visT.\n      destruct (valid_block_dec m2 b). intuition. discriminate.\n  split. trivial.\n  intros; eapply EffProp; clear EffProp.\n    unfold visTgt in VIST. rewrite H2 in VIST; simpl in *. \n    rewrite FF in VIST. eapply frgnBlocksTgt_locBlocksTgt; trivial. } \n\n{ (* seq *)\n  inv TS.\n  eexists; exists m2, mu, EmptyEffect; split.\n    right; split. apply effstep_star_zero. Lt_state.\n  intuition. \n      apply intern_incr_refl.\n  apply gsep_refl.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto. econstructor; eauto.\n      intuition. }\n\n{ (* ifthenelse *)\n  inv TS.\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  rewrite restrict_sm_all in *.\n  rewrite restrict_sm_local' in SP; trivial.\n  exploit Efftransl_condexpr_correct; try eassumption.\n  intros [rs' [tm' [mu' [MU' [A [B [C D]]]]]]]. \n  destruct MU' as [INC' [SEP'[GSEP'  [LOCALLOC' [WD' [SMV' RC']]]]]].\n  assert (PG':  meminj_preserves_globals ge (as_inj mu')).\n   eapply meminj_preserves_incr_sep_vb \n        with (j:=as_inj mu)(m0:=m)(tm:=m2); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.\n  clear PG.\n  exploit sp_preserved_intern_incr; try eassumption.\n  intros SP'; clear SP.\n  eexists; exists tm', mu', EmptyEffect.\n  split.\n    left. eexact A.\n  assert (WDR': SM_wd (restrict_sm mu' (vis mu'))).\n      apply restrict_sm_WD; trivial. \n  specialize (restrict_sm_intern_incr _ _ WD' INC'); intros INCR'.\n  intuition. \n  split.  \n    econstructor; eauto.\n      destruct b; eassumption. \n      eapply tr_cont_intern_incr; try eassumption.\n      rewrite restrict_sm_all. assumption.\n      rewrite restrict_sm_all. \n        apply inject_restrict; eassumption. \n      rewrite restrict_sm_local'; trivial. \n      intuition.\n      red; intros ? ? Hb. destruct (GFP _ _ Hb).\n          split; trivial.\n          eapply intern_incr_as_inj; eassumption.\n      assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n          rewrite <- FRG. eapply (Glob _ H0).  }\n\n{ (* loop *)\n  inversion TS; subst.\n  eexists; exists m2, mu, EmptyEffect; split.\n    left. apply effstep_plus_one. eapply rtl_effstep_exec_Inop; eauto. \n  intuition. \n      apply intern_incr_refl.\n  apply gsep_refl. \n      apply sm_locally_allocatedChar.\n      repeat split; extensionality bb; \n          try rewrite (freshloc_irrefl); intuition.\n      econstructor.\n       econstructor; eauto.  \n       econstructor; eauto.\n       econstructor; eauto.\n      intuition. }\n\n{ (* block *)\n  inv TS.\n  eexists; exists m2, mu, EmptyEffect; split.\n    right; split. apply effstep_star_zero. Lt_state.\n  intuition. \n      apply intern_incr_refl.\n  apply gsep_refl. \n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto.\n        econstructor; eauto.\n      intuition. }\n\n{ (* exit seq *)\n  inv TS. inv TK. \n  eexists; exists m2, mu, EmptyEffect; split.\n    right; split. apply effstep_star_zero. Lt_state. \n  intuition. \n      apply intern_incr_refl. \n  apply gsep_refl.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto.\n        econstructor; eauto.\n      intuition. }\n\n{ (* exit block 0 *)\n  inv TS. inv TK. simpl in H0. inv H0.\n  eexists; exists m2, mu, EmptyEffect; split.\n    right; split. apply effstep_star_zero. Lt_state. \n  intuition. \n      apply intern_incr_refl. \n  apply gsep_refl.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto.\n        econstructor; eauto.\n      intuition. }\n\n{ (* exit block n+1 *)\n  inv TS. inv TK. simpl in H0.\n  eexists; exists m2, mu, EmptyEffect; split.\n    right; split. apply effstep_star_zero. Lt_state. \n  intuition. \n      apply intern_incr_refl. \n  apply gsep_refl.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto.\n        econstructor; eauto.\n      intuition. }\n\n{ (* switch *)\n  inv TS.\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  rewrite restrict_sm_all in *.\n  rewrite restrict_sm_local' in SP; trivial.\n  exploit validate_switch_correct; eauto. intro CTM.\n  exploit Efftransl_expr_correct; eauto. \n  intros [rs' [tm' [mu' [MU' [A [B [C [D E]]]]]]]]. \n  destruct MU' as [INC' [SEP' [GSEP'  [LOCALLOC' [WD' [SMV' RC']]]]]].\n  assert (PG':  meminj_preserves_globals ge (as_inj mu')).\n   eapply meminj_preserves_incr_sep_vb \n        with (j:=as_inj mu)(m0:=m)(tm:=m2); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.\n  clear PG.\n  exploit sp_preserved_intern_incr; try eassumption.\n  exploit Efftransl_switch_correct; eauto. inv C. auto.\n  intros [nd [rs'' [F [G K]]]].\n  eexists; eexists; exists mu', EmptyEffect; split.\n    right; split. eapply effstep_star_trans'. \n          eexact A. eexact F. reflexivity. Lt_state. \n  assert (WDR': SM_wd (restrict_sm mu' (vis mu'))).\n      apply restrict_sm_WD; trivial. \n  specialize (restrict_sm_intern_incr _ _ WD' INC'); intros INCR'.\n  intuition. \n  split.\n    econstructor; eauto. constructor; eassumption.\n      eapply tr_cont_intern_incr; try eassumption.\n      rewrite restrict_sm_all. assumption.\n      rewrite restrict_sm_all. \n        apply inject_restrict; eassumption. \n      rewrite restrict_sm_local'; trivial. \n      intuition.\n      red; intros ? ? Hb. destruct (GFP _ _ Hb).\n          split; trivial.\n          eapply intern_incr_as_inj; eassumption.\n      assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n          rewrite <- FRG. eapply (Glob _ H1).  }\n\n{ (* return none *)\n  inv TS.\n  exploit match_stacks_call_cont; eauto. intros [U V].\n  inversion TF.\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  rewrite restrict_sm_all in *.\n  rewrite restrict_sm_local' in SP; trivial.\n  destruct SP as [spb [spb' [SPB [SPB' Rsp]]]]; subst sp'; inv SPB.\n  edestruct free_parallel_inject as [tm''' []]; eauto.\n    eapply incr_local_restrictvis; eassumption.\n  eexists; exists tm''', mu.\n  exists (FreeEffect m2 0 (fn_stacksize tf) spb'). \n  split. \n    simpl in H0; rewrite Zplus_0_r in H0. rewrite <- H2 in H0. \n    left; eapply effstep_plus_one. \n            eapply rtl_effstep_exec_Ireturn; eauto.\n  assert (SMV': sm_valid mu m' tm''').\n    split; intros;\n      eapply Mem.valid_block_free_1; try eassumption;\n      eapply SMV; assumption.\n  intuition. \n      apply intern_incr_refl. \n  apply gsep_refl.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b'; \n          try rewrite (freshloc_free _ _ _ _ _ H0);\n          try rewrite (freshloc_free _ _ _ _ _ H); intuition.\n  split. econstructor; try rewrite restrict_sm_all; eauto.\n        rewrite vis_restrict_sm, restrict_sm_nest; trivial.\n      intuition.\n        eapply REACH_closed_free; eassumption.\n           eapply free_free_inject; try eassumption.\n           apply local_in_all; eassumption.\n  apply FreeEffectD in H4. destruct H4 as [? [VB Arith2]]; subst.\n    eapply local_visTgt; eassumption.\n  rewrite H2 in H4. \n   eapply FreeEffect_PropagateLeft'; try eassumption. }\n\n{ (* return some *)\n  inv TS.\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  rewrite restrict_sm_all in *.\n  rewrite restrict_sm_local' in SP; trivial.\n  exploit Efftransl_expr_correct; eauto.\n  intros [rs' [tm' [mu' [MU' [A [B [C [D E]]]]]]]]. \n  destruct MU' as [INC' [SEP'[GSEP'  [LOCALLOC' [WD' [SMV' RC']]]]]].\n  assert (PG':  meminj_preserves_globals ge (as_inj mu')).\n   eapply meminj_preserves_incr_sep_vb \n        with (j:=as_inj mu)(m0:=m)(tm:=m2); try eassumption. \n      intros ? ? ? AI. apply as_inj_DomRng in AI.\n              split; eapply SMV; eapply AI.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.\n  clear PG.\n  exploit sp_preserved_intern_incr; try eassumption.\n  exploit match_stacks_call_cont; eauto. intros [U V].\n  inversion TF.\n  destruct SP as [spb [spb' [SPB [SPB' Rsp]]]]; subst sp'; inv SPB.\n  edestruct free_parallel_inject as [tm'' []]; eauto.\n    eapply intern_incr_as_inj; try eassumption.\n     apply local_in_all; eassumption.\n  intros.\n  eexists; exists tm'', mu'.\n  exists (FreeEffect tm' 0 (fn_stacksize tf) spb'). \n  split. \n    simpl in H5; rewrite Zplus_0_r in H5. rewrite <- H4 in H5. \n    left; eapply effstep_star_plus_trans'. eexact A.\n          eapply effstep_plus_one.\n            eapply rtl_effstep_exec_Ireturn; eauto.\n         simpl. apply extensionality; intros b'. \n                apply extensionality; intros z.\n             remember (FreeEffect tm' 0 (fn_stacksize tf) spb' b' z) as d. \n             destruct d; simpl; trivial. \n             apply eq_sym in Heqd. \n             apply FreeEffectD in Heqd. \n             destruct Heqd as [? [? ?]]; subst.\n             clear - Rsp WD SMV MInj. \n             apply local_in_all in Rsp; trivial.\n             destruct (as_inj_DomRng _ _ _ _ Rsp WD) as [_ DT].\n             destruct (valid_block_dec m2 spb'); simpl; trivial. \n             elim n. eapply SMV; trivial. \n  assert (SMV'': sm_valid mu' m' tm'').\n    split; intros;\n      eapply Mem.valid_block_free_1; try eassumption;\n      eapply SMV'; assumption.\n  assert (WDR': SM_wd (restrict_sm mu' (vis mu'))).\n      apply restrict_sm_WD; trivial. \n  specialize (restrict_sm_intern_incr _ _ WD' INC'); intros INCR'.\n  intuition. \n      apply sm_locally_allocatedChar.\n      apply sm_locally_allocatedChar in LOCALLOC'.\n      destruct LOCALLOC' as [DS [DT [LBS [LBT [EBS EBT]]]]].\n      rewrite DS, DT, LBS, LBT, EBS, EBT.\n      repeat split; extensionality b'; \n          try rewrite (freshloc_irrefl);\n          try rewrite (freshloc_free _ _ _ _ _ H0);\n          try rewrite (freshloc_free _ _ _ _ _ H5); intuition.\n      rewrite <- (freshloc_trans m2 tm' tm''),\n                 (freshloc_free _ _ _ _ _ H5).\n          rewrite orb_false_r. trivial. \n             eapply effstep_star_fwd; eassumption.\n             eapply free_forward; eassumption.\n      rewrite <- (freshloc_trans m2 tm' tm''),\n                 (freshloc_free _ _ _ _ _ H5).\n          rewrite orb_false_r. trivial. \n             eapply effstep_star_fwd; eassumption.\n             eapply free_forward; eassumption.\n   assert (RC'': REACH_closed m' (vis mu')).\n        eapply REACH_closed_free; eassumption.\n   split. \n     econstructor; try rewrite restrict_sm_all; eauto.\n      rewrite vis_restrict_sm, restrict_sm_nest; trivial.\n      eapply match_stacks_intern_incr; try eassumption.\n      rewrite vis_restrict_sm, restrict_nest; trivial.\n      eapply inject_restrict; try eassumption.\n     intuition.\n      red; intros ? ? Hb. destruct (GFP _ _ Hb).\n          split; trivial.\n          eapply intern_incr_as_inj; eassumption.\n      assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n          rewrite <- FRG. eapply (Glob _ H8).  \n  apply FreeEffectD in H8. destruct H8 as [? [VB Arith2]]; subst.\n    eapply local_visTgt; eassumption.      \n  rewrite H4 in H8. \n    exploit FreeEffect_PropagateLeft'; try eapply H8.\n      eapply H0. eassumption. eassumption. eapply INC'; eassumption. \n       apply FreeEffectD in H8. destruct H8 as [? [VB Arith2]]; subst.\n       destruct (local_DomRng _ WD _ _ _ Rsp) as [_ lT].\n       rewrite lT in H9; discriminate.\n    rewrite (intern_incr_foreign _ _ INC'); trivial. }\n\n{ (* label *)\n  inv TS.\n  eexists; exists m2, mu, EmptyEffect; split.\n    right; split. apply effstep_star_zero. Lt_state.\n  intuition. \n      apply intern_incr_refl. \n  apply gsep_refl.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto.\n      intuition. }\n\n{ (* goto *)\n  inv TS. inversion TF; subst.\n  exploit tr_find_label; eauto. eapply tr_cont_call_cont; eauto. \n  intros [ns2 [nd2 [nexits2 [A [B C]]]]].\n  eexists; exists m2, mu, EmptyEffect; split.\n    left; apply effstep_plus_one. eapply rtl_effstep_exec_Inop; eauto.\n  intuition. \n      apply intern_incr_refl. \n  apply gsep_refl.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.\n      econstructor. econstructor; eauto.\n      intuition. }\n\n{ (* internal call *)\n  monadInv TF. exploit transl_function_charact; eauto. intro TRF.\n  inversion TRF. subst f0.\n  pose (e := set_locals (fn_vars f) (set_params vargs (CminorSel.fn_params f))).\n  pose (rs := init_regs targs rparams).\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  rewrite restrict_sm_all in *.\n  rewrite vis_restrict_sm in *.\n  rewrite restrict_nest in *; trivial.\n  assert (ME: match_env (restrict (as_inj mu) (vis mu)) map2 e nil rs).\n    unfold rs, e. eapply match_init_env_init_reg; eauto.\n  assert (MWF: map_wf map2).\n    assert (map_valid init_mapping s0) by apply init_mapping_valid.\n    exploit (add_vars_valid (CminorSel.fn_params f)); eauto.\n    intros [A B].\n    eapply add_vars_wf; eauto. eapply add_vars_wf; eauto. \n      apply init_mapping_wf.\n      edestruct alloc_parallel_intern as [mu' [tm' [b' [Alloc' [MInj' [INC' [mu'SP mu'MuR]]]]]]]; eauto; try apply Zle_refl.\n      \n  destruct mu'MuR as [A [B [C [WD' [E F]]]]].\n  eexists. exists tm', mu', EmptyEffect; split.\n    left; apply effstep_plus_one.\n       eapply rtl_effstep_exec_function_internal; simpl; eauto.\n  assert (DomSP:= alloc_DomSrc _ _ _ SMV _ _ _ _ H).\n      assert (TgtB2: DomTgt mu b' = false).\n        remember (DomTgt mu b') as d.\n        destruct d; trivial; apply eq_sym in Heqd.\n        elim (Mem.fresh_block_alloc _ _ _ _ _ Alloc').\n          apply SMV. assumption.\n  assert (WDR': SM_wd (restrict_sm mu' (vis mu'))).\n      apply restrict_sm_WD; trivial. \n  specialize (restrict_sm_intern_incr _ _ WD' INC'); intros INCR'.\n  assert (IncVis: inject_incr (restrict (as_inj mu) (vis mu)) (restrict (as_inj mu') (vis mu'))). \n    red; intros. destruct (restrictD_Some _ _ _ _ _ H5).\n         eapply restrictI_Some.\n           eapply intern_incr_as_inj; try eassumption.\n         eapply intern_incr_vis; eassumption.\n  intuition.\n          eapply intern_incr_globals_separate; eassumption.\n  split. econstructor; try rewrite restrict_sm_all, restrict_sm_nest,\n                 vis_restrict_sm; try eassumption.\n           econstructor; eauto.\n           simpl. inversion MS; subst; econstructor; eauto.\n           econstructor.\n           inv MS. econstructor; try rewrite restrict_sm_nest;\n                    try eassumption.\n                   eapply match_env_inject_incr; try eassumption.\n                      rewrite restrict_sm_nest, restrict_sm_all; trivial.\n                      rewrite restrict_sm_all; trivial.\n                   rewrite restrict_sm_nest in H26; trivial.\n                     eapply tr_cont_intern_incr; try eassumption.\n                   rewrite restrict_sm_local'; trivial.\n                     rewrite restrict_sm_nest, restrict_sm_local' in H27; trivial.\n                     eapply sp_incr; try eassumption. apply INC'.\n                  \n                     eapply match_env_inject_incr; try eassumption.\n                       rewrite restrict_sm_all; trivial.\n           rewrite restrict_sm_all; trivial.\n             eapply inject_restrict; eassumption.\n           exists sp, b'. split; trivial. split; trivial.\n             rewrite restrict_sm_local'; trivial.  \n             destruct (joinD_Some _ _ _ _ _ mu'SP) as [EXT | [_ LOC]];\n               trivial.\n             destruct (extern_DomRng _ WD' _ _ _ EXT) as [eS eT].\n              assert (extBlocksSrc mu = extBlocksSrc mu') by eapply INC'. \n              rewrite <- H7 in eS.\n              unfold DomSrc in DomSP; rewrite eS, orb_true_r in DomSP;\n                 discriminate. \n  intuition.\n    apply meminj_preserves_incr_sep_vb with (j:=as_inj mu)(m0:=m)(tm:=m2); try eassumption. \n      intros. apply as_inj_DomRng in H7.\n              split; eapply SMV; eapply H7.\n      assumption.\n      apply intern_incr_as_inj; eassumption.\n      apply sm_inject_separated_mem. assumption.\n      assumption.\n    red; intros. destruct (GFP _ _ H7). split; trivial.\n         eapply intern_incr_as_inj; eassumption.\n    assert (FF: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC'.\n      apply Glob in H7. rewrite <-FF; trivial. }\n\n  (* no external call *)\n\n{ (* return *)\n  inv MS.\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n  rewrite restrict_sm_all in *.\n  rewrite vis_restrict_sm in *.\n  rewrite restrict_nest in *; trivial.\n  eexists; exists m2, mu, EmptyEffect; split. \n    left; apply effstep_plus_one; constructor. \n  intuition. \n      apply intern_incr_refl. \n  apply gsep_refl.\n      apply sm_locally_allocatedChar.\n      repeat split; extensionality b; \n          try rewrite (freshloc_irrefl); intuition.\n      split. econstructor; try rewrite restrict_sm_all; eauto. \n              constructor. \n             rewrite restrict_sm_nest in *; trivial. eassumption.\n             rewrite restrict_sm_all, restrict_nest in H7; trivial.\n               eapply match_env_update_dest; eauto.\n             rewrite restrict_sm_nest in H10; trivial.\n      intuition. }\nQed.  \n\nLemma MATCH_halted cd mu c1 m1 c2 m2 v1: forall\n        (MTCH: MATCH cd mu c1 m1 c2 m2)\n        (HALT: halted (cminsel_eff_sem hf) c1 = Some v1),\nexists v2 : val,\n  Mem.inject (as_inj mu) m1 m2 /\\\n  val_inject (restrict (as_inj mu) (vis mu)) v1 v2 /\\\n  halted (rtl_eff_sem hf) c2 = Some v2 \n  /\\ forall (pubSrc' pubTgt' : block -> bool)\n        (pubSrcHyp : pubSrc' =\n                 (fun b : block => \n                 locBlocksSrc mu b && REACH m1 (exportedSrc mu (v1::nil)) b))\n        (pubTgtHyp: pubTgt' =\n                 (fun b : block => \n                 locBlocksTgt mu b && REACH m2 (exportedTgt mu (v2::nil)) b))\n        nu (Hnu: nu = (replace_locals mu pubSrc' pubTgt')),\n      MATCH cd nu c1 m1 c2 m2 /\\ Mem.inject (shared_of nu) m1 m2 /\\\n      Forall2 (val_inject (restrict (as_inj nu) (sharedSrc nu))) (v1::nil) (v2::nil) /\\\n      exportedSrc nu (v1::nil) = mapped (shared_of nu) /\\\n      REACH_closed m1 (exportedSrc nu (v1::nil)) .\nProof. intros.\n  destruct MTCH as [MC [RC [PG [GFP [Glob [SMV [WDmu INJ]]]]]]]. \n    destruct c1; inv HALT. destruct k; inv H0.\n    inv MC. exists tv.\n    rewrite restrict_sm_nest, vis_restrict_sm,\n            restrict_sm_all, restrict_nest in *; trivial.\n    split. assumption.\n    split. eassumption.\n    split. simpl. inv MS. trivial.\nintros.\nassert (WDnu: SM_wd nu).\n  subst.\n  eapply replace_locals_wd; eauto.\n    intros.\n    apply andb_true_iff in H. destruct H.\n    exploit (REACH_local_REACH _ WDmu); try eassumption.\n      eapply val_list_inject_forall_inject.\n      econstructor.   \n        eapply val_inject_incr; try eassumption.\n        apply restrict_incr.\n      constructor.\n    intros [b2 [d [loc R2]]].\n      exists b2, d.\n      rewrite loc, R2. destruct (local_DomRng _ WDmu _ _ _ loc). intuition.\n   intros. apply andb_true_iff in H. eapply H.\nsplit. subst.\n  split. rewrite replace_locals_vis.\n    econstructor; eauto.\n    rewrite vis_restrict_sm, restrict_sm_nest, replace_locals_vis.\n      eapply match_stacks_replace_locals; assumption.\n      rewrite replace_locals_vis; trivial.\n    rewrite vis_restrict_sm, restrict_sm_all, restrict_nest; trivial.\n      rewrite replace_locals_as_inj, replace_locals_vis; trivial.\n      rewrite replace_locals_vis; trivial.\n    rewrite restrict_sm_all, replace_locals_as_inj; trivial.\n  rewrite replace_locals_as_inj, replace_locals_vis,\n         replace_locals_frgnBlocksSrc.\n  intuition.\n  split; intros.\n    rewrite replace_locals_DOM in H. eapply SMV; trivial.\n    rewrite replace_locals_RNG in H. eapply SMV; trivial.\n   (*rewrite replace_locals_DomTgt. assumption.*)\nassert (RCnu: REACH_closed m1 (mapped (shared_of nu))).\n  subst. rewrite replace_locals_shared.\n  red; intros. apply REACHAX in H. destruct H as [L HL].\n    generalize dependent b.\n    induction L; simpl; intros; inv HL. trivial.\n    specialize (IHL _ H1); clear H1.\n    destruct (mappedD_true _ _ IHL) as [[bb ofs] Hbb]. clear IHL.\n    apply mapped_charT.\n    assert (MV:= Mem.mi_memval _ _ _ (Mem.mi_inj _ _ _ MINJ)).\n    destruct (joinD_Some _ _ _ _ _ Hbb); clear Hbb.\n      exploit (MV b' z bb ofs).\n        eapply restrictI_Some. apply foreign_in_all; eassumption.\n          unfold vis. unfold foreign_of in H. destruct mu. simpl in *. destruct (frgnBlocksSrc b'); inv H. intuition.\n        assumption.\n      clear MV; intros. rewrite H4 in H0. inv H0.\n      exists (b2, delta). apply joinI.\n      remember (locBlocksSrc mu b) as d.\n      destruct d; apply eq_sym in Heqd. \n        right; simpl. destruct (restrictD_Some _ _ _ _ _ H5); clear H5.\n        split. eapply locBlocksSrc_foreignNone; eassumption.\n        destruct (joinD_Some _ _ _ _ _ H0).\n          destruct (extern_DomRng _ WDmu _ _ _ H3).\n          apply extBlocksSrc_locBlocksSrc in H5. rewrite H5 in Heqd; inv Heqd.\n           trivial.\n        destruct H3. rewrite H5.\n        assert (REACH m1 (exportedSrc mu (v1::nil)) b = true).\n          eapply REACH_cons; try eassumption.\n          eapply REACH_nil. unfold exportedSrc, sharedSrc. apply foreign_in_shared in H. rewrite H. intuition.\n        rewrite H6. trivial.\n      left. eapply restrict_vis_foreign; try eassumption.\n               destruct (restrictD_Some _ _ _ _ _ H5).\n               rewrite (as_inj_locBlocks _ _ _ _ WDmu H0) in Heqd. trivial.\n    destruct H. remember (locBlocksSrc mu b' && REACH m1 (exportedSrc mu (v1::nil)) b') as d. \n       destruct d; apply eq_sym in Heqd; inv H0.\n       apply andb_true_iff in Heqd; destruct Heqd.\n      exploit (MV b' z bb ofs).\n        eapply restrictI_Some. apply local_in_all; eassumption.\n          unfold vis. rewrite H0; trivial.\n        assumption.\n      clear MV; intros. rewrite H4 in H5. inv H5.\n      exists (b2, delta). apply joinI.\n      remember (locBlocksSrc mu b) as d.\n      destruct d; apply eq_sym in Heqd. \n        right; simpl. destruct (restrictD_Some _ _ _ _ _ H8); clear H8.\n        split. eapply locBlocksSrc_foreignNone; eassumption.\n        destruct (joinD_Some _ _ _ _ _ H5).\n          destruct (extern_DomRng _ WDmu _ _ _ H7).\n          apply extBlocksSrc_locBlocksSrc in H8. rewrite H8 in Heqd; inv Heqd.\n           trivial.\n        destruct H7. rewrite H8.\n        assert (REACH m1 (exportedSrc mu (v1::nil)) b = true).\n          eapply REACH_cons; try eassumption.\n        rewrite H9. trivial.\n      simpl. left. eapply restrict_vis_foreign; try eassumption.\n               destruct (restrictD_Some _ _ _ _ _ H8).\n               rewrite (as_inj_locBlocks _ _ _ _ WDmu H5) in Heqd. trivial.\nassert (MINJNU: Mem.inject (shared_of nu) m1 m2).\n  eapply inject_mapped. eapply INJ. eassumption.\n  subst. rewrite replace_locals_shared.\n    red; intros. destruct (joinD_Some _ _ _ _ _ H); clear H.\n    eapply foreign_in_all; eassumption.\n    destruct H0.\n      destruct (locBlocksSrc mu b && REACH m1 (exportedSrc mu (v1::nil)) b); inv H0.\n      rewrite H2; eapply local_in_all; eassumption.\nsplit; trivial.\nrewrite restrict_SharedSrc; trivial.\nsplit. \n  eapply val_list_inject_forall_inject.\n  econstructor; eauto.\n  eapply val_inject_sub_on'; try eassumption.\n  intros. rewrite restrict_vis_foreign_local in H0; trivial.\n    unfold shared_of. subst. clear MINJNU.\n    rewrite replace_locals_foreign, replace_locals_pub.\n    apply joinI.\n    destruct (joinD_Some _ _ _ _ _ H0); clear H0.\n      left; trivial.\n    destruct H1. right; split; trivial.\n      destruct (local_DomRng _ WDmu _ _ _ H1).\n      rewrite H2, H1, (getBlocks_REACH_exportedSrc _ _ _ _ H); trivial.\nassert (exportedSrc nu (v1::nil) = mapped (shared_of nu)).\n  clear MINJNU RCnu.\n  unfold exportedSrc, mapped.\n  extensionality b. unfold sharedSrc.\n  remember (shared_of nu b) as d.\n  destruct d; simpl. apply orb_true_r.\n  rewrite orb_false_r.\n  subst. rewrite replace_locals_shared in Heqd.\n    apply eq_sym in Heqd.\n    apply joinD_None in Heqd. destruct Heqd.\n    remember (getBlocks (v1::nil) b) as d.\n    destruct d; simpl; trivial. apply eq_sym in Heqd.\n    rewrite (getBlocks_REACH_exportedSrc _ _ _ _ Heqd) in H0.\n    rewrite andb_true_r in H0.\n(*    rewrite getBlocks_char in Heqd. destruct Heqd. destruct H1.\n      subst. inv VINJ.*)\n    exploit getBlocks_inject. \n      eapply val_list_inject_forall_inject.\n        eapply val_cons_inject; try eapply val_nil_inject.\n         eapply VINJ.\n      eassumption.\n    intros [b2 [delta [Rb GB2]]].\n    destruct (restrictD_Some _ _ _ _ _ Rb); clear Rb.\n    unfold vis in H2.\n    destruct (foreign_None_frgnBlocksSrc_false _ _ WDmu H).\n      rewrite H3 in H1; discriminate.\n      rewrite H3, orb_false_r in H2.\n      rewrite H2 in H0. \n      rewrite (locBlocksSrc_as_inj_local _ _ WDmu H2) in H1.\n      rewrite H1 in H0; discriminate.\nrewrite H; split; trivial.\ntrivial.\nrewrite vis_restrict_sm; trivial. \nQed.\n\n(** The simulation proof *)\nTheorem transl_program_correct:\n  SM_simulation.SM_simulation_inject (cminsel_eff_sem hf)\n   (rtl_eff_sem hf) ge tge.\nProof.\nintros.\nassert (GDE:=GDE_lemma).\napply simulations_lemmas.inj_simulation_star_wf with\n  (match_states:=MATCH) (order :=lt_state).\n(*genvs_dom_eq*)\n  assumption.\n(*MATCH_wd*)\n  apply MATCH_wd. \n(*MATCH_reachclosed*)\n  apply MATCH_RC.\n(*MATCH_restrict*)\n  (*apply MATCH_restrict.*)\n(*MATCH_valid*)\n  apply MATCH_valid.\n(*MATCH_preserves_globals*)\n  apply MATCH_PG.\n(*MATCHinitial*)\n  { intros.\n    eapply (MATCH_initial _ _ _); eauto. }\n(*halted*) \n  { intros. destruct H as [MC [RC [PG [GFP [Glob [SMV [WD INJ]]]]]]]. \n    destruct c1; inv H0. destruct k; inv H1.\n    inv MC. exists tv.\n    rewrite vis_restrict_sm, restrict_sm_all, \n            restrict_sm_nest, restrict_nest in *; trivial.\n    split. assumption.\n    split. eassumption.\n    simpl. inv MS. trivial. }\n(* at_external*)\n  { apply MATCH_atExternal. }\n(* order_wf *)\n  { apply lt_state_wf. }\n(* after_external*)\n  { intros.\n    specialize (MATCH_afterExternal GDE _ _ _ _ _ _ _ _ _ _ _ \n       MemInjMu MatchMu AtExtSrc AtExtTgt ValInjMu\n       _ pubSrcHyp _ pubTgtHyp _ NuHyp _ _ _ _ _ INC GSep WDnu' SMvalNu'\n       MemInjNu' RValInjNu' FwdSrc FwdTgt _ frgnSrcHyp _ frgnTgtHyp\n       _ Mu'Hyp UnchPrivSrc UnchLOOR).\n    intros. eapply H. }\n(*effcore_diagram*)\n { intros. exploit MATCH_effcore_diagram; try eassumption.\n    intros [st2' [m2' [mu' [U2 [CS2 [? [? [? [? ?]]]]]]]]].\n    exists st2', m2', mu'.\n    repeat (split; trivial).\n    exists U2. split; assumption. }\nQed.\n\nEnd CORRECTNESS.\n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/backend/RTLgenproof_comp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.21704305994259127}}
{"text": "From iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Export weakestpre.\nFrom iris.base_logic Require Export big_op invariants.\nFrom iris_logrel.F_mu_ref_conc Require Export rules_binary typing.\nFrom iris.algebra Require Import list.\nFrom iris.prelude Require Import tactics.\nImport uPred.\n\n(* HACK: move somewhere else *)\nLtac auto_equiv ::=\n  (* Deal with \"pointwise_relation\" *)\n  repeat lazymatch goal with\n  | |- pointwise_relation _ _ _ _ => intros ?\n  end;\n  (* Normalize away equalities. *)\n  repeat match goal with\n  | H : _ ≡{_}≡ _ |-  _ => apply (timeless_iff _ _) in H\n  | _ => progress simplify_eq\n  end;\n  (* repeatedly apply congruence lemmas and use the equalities in the hypotheses. *)\n  try (f_equiv; fast_done || auto_equiv).\n\nDefinition logN : namespace := nroot .@ \"logN\".\n\n(** interp : is a unary logical relation. *)\nSection logrel.\n  Context `{heapIG Σ, cfgSG Σ}.\n  Notation D := (prodC valC valC -n> iProp Σ).\n  Implicit Types τi : D.\n  Implicit Types Δ : listC D.\n  Implicit Types interp : listC D → D.\n\n  Definition interp_expr (τi : listC D -n> D) (Δ : listC D)\n      (ee : expr * expr) : iProp Σ := (∀ j K,\n    j ⤇ fill K (ee.2) →\n    WP ee.1 {{ v, ∃ v', j ⤇ fill K (of_val v') ∗ τi Δ (v, v') }})%I.\n  Global Instance interp_expr_ne n :\n    Proper (dist n ==> dist n ==> (=) ==> dist n) interp_expr.\n  Proof. solve_proper. Qed.\n\n  Program Definition ctx_lookup (x : var) : listC D -n> D := λne Δ,\n    from_option id (cconst True)%I (Δ !! x).\n  Solve Obligations with solve_proper_alt.\n\n  Program Definition interp_unit : listC D -n> D := λne Δ ww,\n    (ww.1 = UnitV ∧ ww.2 = UnitV)%I.\n  Solve Obligations with solve_proper_alt.\n  Program Definition interp_nat : listC D -n> D := λne Δ ww,\n    (∃ n : nat, ww.1 = #nv n ∧ ww.2 = #nv n)%I.\n  Solve Obligations with solve_proper.\n  Program Definition interp_bool : listC D -n> D := λne Δ ww,\n    (∃ b : bool, ww.1 = #♭v b ∧ ww.2 = #♭v b)%I.\n  Solve Obligations with solve_proper.\n\n  Program Definition interp_prod\n      (interp1 interp2 : listC D -n> D) : listC D -n> D := λne Δ ww,\n    (∃ vv1 vv2, ww = (PairV (vv1.1) (vv2.1), PairV (vv1.2) (vv2.2)) ∧\n                interp1 Δ vv1 ∧ interp2 Δ vv2)%I.\n  Solve Obligations with solve_proper.\n\n  Program Definition interp_sum\n      (interp1 interp2 : listC D -n> D) : listC D -n> D := λne Δ ww,\n    ((∃ vv, ww = (InjLV (vv.1), InjLV (vv.2)) ∧ interp1 Δ vv) ∨\n     (∃ vv, ww = (InjRV (vv.1), InjRV (vv.2)) ∧ interp2 Δ vv))%I.\n  Solve Obligations with solve_proper.\n\n  Program Definition interp_arrow\n          (interp1 interp2 : listC D -n> D) : listC D -n> D :=\n    λne Δ ww,\n    (□ ∀ vv, interp1 Δ vv →\n             interp_expr\n               interp2 Δ (App (of_val (ww.1)) (of_val (vv.1)),\n                          App (of_val (ww.2)) (of_val (vv.2))))%I.\n  Solve Obligations with solve_proper.\n\n  Program Definition interp_forall\n      (interp : listC D -n> D) : listC D -n> D := λne Δ ww,\n    (□ ∀ τi,\n          (■ ∀ ww, PersistentP (τi ww)) →\n          interp_expr\n            interp (τi :: Δ) (TApp (of_val (ww.1)), TApp (of_val (ww.2))))%I.\n  Solve Obligations with solve_proper.\n\n  Program Definition interp_rec1\n      (interp : listC D -n> D) (Δ : listC D) (τi : D) : D := λne ww,\n    (□ ∃ vv, ww = (FoldV (vv.1), FoldV (vv.2)) ∧ ▷ interp (τi :: Δ) vv)%I.\n  Solve Obligations with solve_proper.\n\n  Global Instance interp_rec1_contractive\n    (interp : listC D -n> D) (Δ : listC D) : Contractive (interp_rec1 interp Δ).\n  Proof.\n    intros n τi1 τi2 Hτi ww; cbn.\n    apply always_ne, exist_ne; intros vv; apply and_ne; trivial.\n    apply later_contractive =>i Hi. by rewrite Hτi.\n  Qed.\n\n  Program Definition interp_rec (interp : listC D -n> D) : listC D -n> D := λne Δ,\n    fixpoint (interp_rec1 interp Δ).\n  Next Obligation.\n    intros interp n Δ1 Δ2 HΔ; apply fixpoint_ne => τi ww. solve_proper.\n  Qed.\n\n  Program Definition interp_ref_inv (ll : loc * loc) : D -n> iProp Σ := λne τi,\n    (∃ vv, ll.1 ↦ᵢ vv.1 ∗ ll.2 ↦ₛ vv.2 ∗ τi vv)%I.\n  Solve Obligations with solve_proper.\n\n  Program Definition interp_ref\n      (interp : listC D -n> D) : listC D -n> D := λne Δ ww,\n    (∃ ll, ww = (LocV (ll.1), LocV (ll.2)) ∧\n           inv (logN .@ ll) (interp_ref_inv ll (interp Δ)))%I.\n  Solve Obligations with solve_proper.\n\n  Fixpoint interp (τ : type) : listC D -n> D :=\n    match τ return _ with\n    | TUnit => interp_unit\n    | TNat => interp_nat\n    | TBool => interp_bool\n    | TProd τ1 τ2 => interp_prod (interp τ1) (interp τ2)\n    | TSum τ1 τ2 => interp_sum (interp τ1) (interp τ2)\n    | TArrow τ1 τ2 => interp_arrow (interp τ1) (interp τ2)\n    | TVar x => ctx_lookup x\n    | TForall τ' => interp_forall (interp τ')\n    | TRec τ' => interp_rec (interp τ')\n    | Tref τ' => interp_ref (interp τ')\n    end.\n  Notation \"⟦ τ ⟧\" := (interp τ).\n\n  Definition interp_env (Γ : list type)\n      (Δ : listC D) (vvs : list (val * val)) : iProp Σ :=\n    (length Γ = length vvs ∗ [∗] zip_with (λ τ, ⟦ τ ⟧ Δ) Γ vvs)%I.\n  Notation \"⟦ Γ ⟧*\" := (interp_env Γ).\n\n  Class env_PersistentP Δ :=\n    ctx_persistentP : Forall (λ τi, ∀ vv, PersistentP (τi vv)) Δ.\n  Global Instance ctx_persistent_nil : env_PersistentP [].\n  Proof. by constructor. Qed.\n  Global Instance ctx_persistent_cons τi Δ :\n    (∀ vv, PersistentP (τi vv)) → env_PersistentP Δ → env_PersistentP (τi :: Δ).\n  Proof. by constructor. Qed.\n  Global Instance ctx_persistent_lookup Δ x vv :\n    env_PersistentP Δ → PersistentP (ctx_lookup x Δ vv).\n  Proof. intros HΔ; revert x; induction HΔ=>-[|?] /=; apply _. Qed.\n  Global Instance interp_persistent τ Δ vv :\n    env_PersistentP Δ → PersistentP (⟦ τ ⟧ Δ vv).\n  Proof.\n    revert vv Δ; induction τ=> vv Δ HΔ; simpl; try apply _.\n    rewrite /PersistentP /interp_rec fixpoint_unfold /interp_rec1 /=.\n    by apply always_intro'.\n  Qed.\n  Global Instance interp_env_persistent Γ Δ vvs :\n    env_PersistentP Δ → PersistentP (⟦ Γ ⟧* Δ vvs) := _.\n\n  Lemma interp_weaken Δ1 Π Δ2 τ :\n    ⟦ τ.[upn (length Δ1) (ren (+ length Π))] ⟧ (Δ1 ++ Π ++ Δ2)\n    ≡ ⟦ τ ⟧ (Δ1 ++ Δ2).\n  Proof.\n    revert Δ1 Π Δ2. induction τ=> Δ1 Π Δ2; simpl; auto.\n    - intros ww; simpl; properness; auto.\n    - intros ww; simpl; properness; auto.\n    - intros ww; simpl; properness; auto.\n    - intros ww; simpl; properness; auto. by apply IHτ1. by apply IHτ2.\n    - intros ww; simpl; properness; auto. by apply IHτ1. by apply IHτ2.\n    - unfold interp_expr.\n      intros ww; simpl; properness; auto. by apply IHτ1. by apply IHτ2.\n    - apply fixpoint_proper=> τi ww /=.\n      properness; auto. apply (IHτ (_ :: _)).\n    - rewrite iter_up; destruct lt_dec as [Hl | Hl]; simpl.\n      { by rewrite !lookup_app_l. }\n      rewrite !lookup_app_r; [|lia ..]. do 2 f_equiv. lia. done.\n    - unfold interp_expr.\n      intros ww; simpl; properness; auto. by apply (IHτ (_ :: _)).\n    - intros ww; simpl; properness; auto. by apply IHτ.\n  Qed.\n\n  Lemma interp_subst_up Δ1 Δ2 τ τ' :\n    ⟦ τ ⟧ (Δ1 ++ interp τ' Δ2 :: Δ2)\n    ≡ ⟦ τ.[upn (length Δ1) (τ' .: ids)] ⟧ (Δ1 ++ Δ2).\n  Proof.\n    revert Δ1 Δ2; induction τ=> Δ1 Δ2; simpl; auto.\n    - intros ww; simpl; properness; auto.\n    - intros ww; simpl; properness; auto.\n    - intros ww; simpl; properness; auto.\n    - intros ww; simpl; properness; auto. by apply IHτ1. by apply IHτ2.\n    - intros ww; simpl; properness; auto. by apply IHτ1. by apply IHτ2.\n    - unfold interp_expr.\n      intros ww; simpl; properness; auto. by apply IHτ1. by apply IHτ2.\n    - apply fixpoint_proper=> τi ww /=.\n      properness; auto. apply (IHτ (_ :: _)).\n    - rewrite iter_up; destruct lt_dec as [Hl | Hl]; simpl.\n      { by rewrite !lookup_app_l. }\n      rewrite !lookup_app_r; [|lia ..].\n      destruct (x - length Δ1) as [|n] eqn:?; simpl.\n      { symmetry. asimpl. apply (interp_weaken [] Δ1 Δ2 τ'). }\n      rewrite !lookup_app_r; [|lia ..]. do 2 f_equiv. lia. done.\n    - unfold interp_expr.\n      intros ww; simpl; properness; auto. apply (IHτ (_ :: _)).\n    - intros ww; simpl; properness; auto. by apply IHτ.\n  Qed.\n\n  Lemma interp_subst Δ2 τ τ' : ⟦ τ ⟧ (⟦ τ' ⟧ Δ2 :: Δ2) ≡ ⟦ τ.[τ'/] ⟧ Δ2.\n  Proof. apply (interp_subst_up []). Qed.\n\n  Lemma interp_env_length Δ Γ vvs : ⟦ Γ ⟧* Δ vvs ⊢ length Γ = length vvs.\n  Proof. by iIntros \"[% ?]\". Qed.\n\n  Lemma interp_env_Some_l Δ Γ vvs x τ :\n    Γ !! x = Some τ → ⟦ Γ ⟧* Δ vvs ⊢ ∃ vv, vvs !! x = Some vv ∧ ⟦ τ ⟧ Δ vv.\n  Proof.\n    iIntros (?) \"[Hlen HΓ]\"; iDestruct \"Hlen\" as %Hlen.\n    destruct (lookup_lt_is_Some_2 vvs x) as [v Hv].\n    { by rewrite -Hlen; apply lookup_lt_Some with τ. }\n    iExists v; iSplit. done. iApply (big_sep_elem_of with \"HΓ\").\n    apply elem_of_list_lookup_2 with x.\n    rewrite lookup_zip_with; by simplify_option_eq.\n  Qed.\n\n  Lemma interp_env_nil Δ : True ⊢ ⟦ [] ⟧* Δ [].\n  Proof. iIntros \"\"; iSplit; auto. Qed.\n  Lemma interp_env_cons Δ Γ vvs τ vv :\n    ⟦ τ :: Γ ⟧* Δ (vv :: vvs) ⊣⊢ ⟦ τ ⟧ Δ vv ∗ ⟦ Γ ⟧* Δ vvs.\n  Proof.\n    rewrite /interp_env /= (assoc _ (⟦ _ ⟧ _ _)) -(comm _ (_ = _)%I) -assoc.\n    by apply sep_proper; [apply pure_proper; omega|].\n  Qed.\n\n  Lemma interp_env_ren Δ (Γ : list type) vvs τi :\n    ⟦ subst (ren (+1)) <$> Γ ⟧* (τi :: Δ) vvs ⊣⊢ ⟦ Γ ⟧* Δ vvs.\n  Proof.\n    apply sep_proper; [apply pure_proper; by rewrite fmap_length|].\n    revert Δ vvs τi; induction Γ=> Δ [|v vs] τi; csimpl; auto.\n    apply sep_proper; auto. apply (interp_weaken [] [τi] Δ).\n  Qed.\n\n  Lemma interp_EqType_agree τ v v' Δ :\n    env_PersistentP Δ → EqType τ → interp τ Δ (v, v') ⊢ ■ (v = v').\n  Proof.\n    intros ? Hτ; revert v v'; induction Hτ; iIntros (v v') \"#H1 /=\".\n    - by iDestruct \"H1\" as \"[% %]\"; subst.\n    - by iDestruct \"H1\" as (n) \"[% %]\"; subst.\n    - by iDestruct \"H1\" as (b) \"[% %]\"; subst.\n    - iDestruct \"H1\" as ([??] [??]) \"[% [H1 H2]]\"; simplify_eq/=.\n      rewrite IHHτ1 IHHτ2.\n      by iDestruct \"H1\" as \"%\"; iDestruct \"H2\" as \"%\"; subst.\n    - iDestruct \"H1\" as \"[H1|H1]\".\n      + iDestruct \"H1\" as ([??]) \"[% H1]\"; simplify_eq/=.\n        rewrite IHHτ1. by iDestruct \"H1\" as \"%\"; subst.\n      + iDestruct \"H1\" as ([??]) \"[% H1]\"; simplify_eq/=.\n        rewrite IHHτ2. by iDestruct \"H1\" as \"%\"; subst.\n  Qed.\nEnd logrel.\n\nTypeclasses Opaque interp_env.\nNotation \"⟦ τ ⟧\" := (interp τ).\nNotation \"⟦ τ ⟧ₑ\" := (interp_expr (interp τ)).\nNotation \"⟦ Γ ⟧*\" := (interp_env Γ).\n", "meta": {"author": "amintimany", "repo": "iris-logrel", "sha": "dad6c7edd1e6ef2d443a2da1ce55b8439b0bc261", "save_path": "github-repos/coq/amintimany-iris-logrel", "path": "github-repos/coq/amintimany-iris-logrel/iris-logrel-dad6c7edd1e6ef2d443a2da1ce55b8439b0bc261/F_mu_ref_conc/logrel_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.21704305994259127}}
{"text": "(** * SHL and SHR instructions *)\nRequire Import x86proved.x86.instrrules.core.\nImport x86.instrrules.core.instrruleconfig.\n\nRequire Import x86proved.bitsopsprops (* for [dropmsb_iter_shlB] *).\n\n(** Lazy man's proof *)\nLemma SmallCount : forall count, count < 32 -> toNat (n:=8) (andB #x\"1f\" (fromNat count)) = count.\nProof. do 32 case => //.\nQed.\n\nLemma SHL_RI_rule s (r:VReg s) (v:VWORD s) (count:nat):\n  count < n32 ->\n  |-- basic (r~=v ** OSZCP?) (SHL r, count) \n            (r~=iter count shlB v ** OSZCP?).\nProof.\n  move => BOUND.\n  (** We don't want to spin forever if something goes wrong, so we\n      only allow [count] to be destructed 5 times.  We do it in the\n      middle of the proof to reduce proof term size. *)\n  destruct s;\n  do 5?[do ![ progress instrrule_triple_bazooka using sbazooka\n            | progress rewrite (SmallCount BOUND)\n            | progress rewrite /stateIsAny ]\n       | destruct count as [|count]; rewrite /(iter 0) ?dropmsb_iter_shlB ].\nQed.\n\nLemma SHR_RI_rule s (r:VReg s) (v:VWORD s) (count:nat):\n  count < n32 ->\n  |-- basic (r~=v ** OSZCP?) (SHR r, count) \n            (r~=iter count shrB v ** OSZCP?).\nProof.\n  move => BOUND.\n  (** We don't want to spin forever if something goes wrong, so we\n      only allow [count] to be destructed 5 times.  We do it in the\n      middle of the proof to reduce proof term size. *)\n  destruct s;\n  do 5?[do ![ progress instrrule_triple_bazooka using sbazooka\n            | progress rewrite (SmallCount BOUND)\n            | progress rewrite /stateIsAny ]\n       | destruct count as [|count]; rewrite /(iter 0) ?droplsb_iter_shrB ].\nQed.\n\n(** We make this rule an instance of the typeclass, and leave\n    unfolding things like [specAtDstSrc] to the getter tactic\n    [get_instrrule_of]. *)\nGlobal Instance: forall s (r : VReg s) (count : nat), instrrule (SHL r, count) := fun s r count v => @SHL_RI_rule s r v count.\nGlobal Instance: forall s (r : VReg s) (count : nat), instrrule (SHR r, count) := fun s r count v => @SHR_RI_rule s r v count.\n", "meta": {"author": "nbenton", "repo": "x86proved", "sha": "7a58960f6456ee09dd46c990204a30c2fdd7fa1a", "save_path": "github-repos/coq/nbenton-x86proved", "path": "github-repos/coq/nbenton-x86proved/x86proved-7a58960f6456ee09dd46c990204a30c2fdd7fa1a/src/x86/instrrules/shift.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.21701741776674796}}
{"text": "Require Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import Global.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import SimLocal.\nRequire Import SimMemory.\nRequire Import SimGlobal.\n\nSet Implicit Arguments.\n\n\nSection SimulationThread.\n  Definition SIM_TERMINAL (lang_src lang_tgt:language) :=\n    forall (st_src:(Language.state lang_src)) (st_tgt:(Language.state lang_tgt)), Prop.\n\n  Definition SIM_THREAD :=\n    forall (lang_src lang_tgt:language) (sim_terminal: SIM_TERMINAL lang_src lang_tgt)\n      (st1_src:(Language.state lang_src)) (lc1_src:Local.t) (gl0_src:Global.t)\n      (st1_tgt:(Language.state lang_tgt)) (lc1_tgt:Local.t) (gl0_tgt:Global.t), Prop.\n\n  Definition _sim_thread_step\n             (lang_src lang_tgt:language)\n             (sim_thread:\n               forall (st1_src:(Language.state lang_src)) (lc1_src:Local.t) (gl0_src:Global.t)\n                 (st1_tgt:(Language.state lang_tgt)) (lc1_tgt:Local.t) (gl0_tgt:Global.t), Prop)\n             st1_src lc1_src gl1_src\n             st1_tgt lc1_tgt gl1_tgt\n    :=\n    forall e_tgt st3_tgt lc3_tgt gl3_tgt\n      (STEP_TGT: Thread.step e_tgt\n                             (Thread.mk _ st1_tgt lc1_tgt gl1_tgt)\n                             (Thread.mk _ st3_tgt lc3_tgt gl3_tgt)),\n      (<<FAILURE: Thread.steps_failure (Thread.mk _ st1_src lc1_src gl1_src)>>) \\/\n      exists e_src st2_src lc2_src gl2_src st3_src lc3_src gl3_src,\n        (<<FAILURE: ThreadEvent.get_machine_event e_tgt <> MachineEvent.failure>>) /\\\n        (<<STEPS: rtc (@Thread.tau_step _)\n                      (Thread.mk _ st1_src lc1_src gl1_src)\n                      (Thread.mk _ st2_src lc2_src gl2_src)>>) /\\\n        (<<STEP_SRC: Thread.opt_step e_src\n                                     (Thread.mk _ st2_src lc2_src gl2_src)\n                                     (Thread.mk _ st3_src lc3_src gl3_src)>>) /\\\n        (<<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>>) /\\\n        (<<GLOBAL3: sim_global gl3_src gl3_tgt>>) /\\\n        (<<SIM: sim_thread st3_src lc3_src gl3_src st3_tgt lc3_tgt gl3_tgt>>).\n\n  Definition _sim_thread\n             (sim_thread: SIM_THREAD)\n             (lang_src lang_tgt:language)\n             (sim_terminal: SIM_TERMINAL lang_src lang_tgt)\n             (st1_src:(Language.state lang_src)) (lc1_src:Local.t) (gl0_src:Global.t)\n             (st1_tgt:(Language.state lang_tgt)) (lc1_tgt:Local.t) (gl0_tgt:Global.t): Prop :=\n    forall\n      gl1_src gl1_tgt\n      (GLOBAL: sim_global gl1_src gl1_tgt)\n      (GL_FUTURE_SRC: Global.strong_le gl0_src gl1_src)\n      (GL_FUTURE_TGT: Global.le gl0_tgt gl1_tgt)\n      (LC_WF_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF_SRC: Global.wf gl1_src)\n      (GL_WF_TGT: Global.wf gl1_tgt),\n      (<<TERMINAL:\n        forall (TERMINAL_TGT: (Language.is_terminal lang_tgt) st1_tgt),\n          (<<FAILURE: Thread.steps_failure (Thread.mk _ st1_src lc1_src gl1_src)>>) \\/\n          exists st2_src lc2_src gl2_src,\n            (<<STEPS: rtc (@Thread.tau_step _)\n                          (Thread.mk _ st1_src lc1_src gl1_src)\n                          (Thread.mk _ st2_src lc2_src gl2_src)>>) /\\\n            (<<GLOBAL: sim_global gl2_src gl1_tgt>>) /\\\n            (<<TERMINAL_SRC: (Language.is_terminal lang_src) st2_src>>) /\\\n            (<<LOCAL: sim_local lc2_src lc1_tgt>>) /\\\n            (<<TERMINAL: sim_terminal st2_src st1_tgt>>)>>) /\\\n      (<<PROMISES:\n        forall (PROMISES_TGT: Local.promises lc1_tgt = BoolMap.bot),\n          (<<FAILURE: Thread.steps_failure (Thread.mk _ st1_src lc1_src gl1_src)>>) \\/\n          exists st2_src lc2_src gl2_src,\n            (<<STEPS: rtc (@Thread.tau_step _)\n                          (Thread.mk _ st1_src lc1_src gl1_src)\n                          (Thread.mk _ st2_src lc2_src gl2_src)>>) /\\\n            (<<PROMISES_SRC: Local.promises lc2_src = BoolMap.bot>>)>>) /\\\n      (<<STEP: _sim_thread_step _ _ (@sim_thread lang_src lang_tgt sim_terminal)\n                                st1_src lc1_src gl1_src\n                                st1_tgt lc1_tgt gl1_tgt>>).\n\n  Lemma _sim_thread_mon: monotone9 _sim_thread.\n  Proof.\n    ii. exploit IN; eauto. i. des.\n    splits; eauto. ii.\n    exploit STEP; eauto. i. des; eauto.\n    right. esplits; eauto.\n  Qed.\n  #[local] Hint Resolve _sim_thread_mon: paco.\n\n  Definition sim_thread: SIM_THREAD := paco9 _sim_thread bot9.\n\n  Lemma sim_thread_mon\n        (lang_src lang_tgt:language)\n        (sim_terminal1 sim_terminal2: SIM_TERMINAL lang_src lang_tgt)\n        (SIM: sim_terminal1 <2= sim_terminal2):\n    sim_thread sim_terminal1 <6= sim_thread sim_terminal2.\n  Proof.\n    pcofix CIH. i. punfold PR. pfold. ii.\n    exploit PR; eauto. i. des.\n    splits; auto.\n    - i. exploit TERMINAL; eauto. i. des; eauto.\n      right. esplits; eauto.\n    - ii. exploit STEP; eauto. i. des; eauto.\n      inv SIM0; [|done].\n      right. esplits; eauto.\n  Qed.\nEnd SimulationThread.\n#[export] Hint Resolve _sim_thread_mon: paco.\n\n\nLemma sim_thread_step\n      lang_src lang_tgt\n      sim_terminal\n      e_tgt\n      st1_src lc1_src gl1_src\n      st1_tgt lc1_tgt gl1_tgt\n      st3_tgt lc3_tgt gl3_tgt\n      (STEP: @Thread.step lang_tgt e_tgt\n                          (Thread.mk _ st1_tgt lc1_tgt gl1_tgt)\n                          (Thread.mk _ st3_tgt lc3_tgt gl3_tgt))\n      (GLOBAL: sim_global gl1_src gl1_tgt)\n      (LC_WF_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF_SRC: Global.wf gl1_src)\n      (GL_WF_TGT: Global.wf gl1_tgt)\n      (SIM: sim_thread sim_terminal st1_src lc1_src gl1_src st1_tgt lc1_tgt gl1_tgt):\n  (<<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src gl1_src)>>) \\/\n  exists e_src st2_src lc2_src gl2_src st3_src lc3_src gl3_src,\n    (<<FAILURE: ThreadEvent.get_machine_event e_tgt <> MachineEvent.failure>>) /\\\n    (<<STEPS: rtc (@Thread.tau_step lang_src)\n                  (Thread.mk _ st1_src lc1_src gl1_src)\n                  (Thread.mk _ st2_src lc2_src gl2_src)>>) /\\\n    (<<STEP: Thread.opt_step e_src\n                             (Thread.mk _ st2_src lc2_src gl2_src)\n                             (Thread.mk _ st3_src lc3_src gl3_src)>>) /\\\n    (<<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>>) /\\\n    (<<GLOBAL: sim_global gl3_src gl3_tgt>>) /\\\n    (<<LC_WF_SRC: Local.wf lc3_src gl3_src>>) /\\\n    (<<LC_WF_TGT: Local.wf lc3_tgt gl3_tgt>>) /\\\n    (<<GL_WF_SRC: Global.wf gl3_src>>) /\\\n    (<<GL_WF_TGT: Global.wf gl3_tgt>>) /\\\n    (<<SIM: sim_thread sim_terminal st3_src lc3_src gl3_src st3_tgt lc3_tgt gl3_tgt>>).\nProof.\n  punfold SIM. exploit SIM; eauto; try refl. i. des.\n  exploit STEP0; eauto. i. des; eauto.\n  inv SIM0; [|done]. right.\n  exploit Thread.step_future; eauto. s. i. des.\n  exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n  exploit Thread.opt_step_future; eauto. s. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_thread_opt_step\n      lang_src lang_tgt\n      sim_terminal\n      e_tgt\n      st1_src lc1_src gl1_src\n      st1_tgt lc1_tgt gl1_tgt\n      st3_tgt lc3_tgt gl3_tgt\n      (STEP: @Thread.opt_step lang_tgt e_tgt\n                              (Thread.mk _ st1_tgt lc1_tgt gl1_tgt)\n                              (Thread.mk _ st3_tgt lc3_tgt gl3_tgt))\n      (GLOBAL: sim_global gl1_src gl1_tgt)\n      (LC_WF_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF_TGT: Local.wf lc1_tgt gl1_tgt)\n      (GL_WF_SRC: Global.wf gl1_src)\n      (GL_WF_TGT: Global.wf gl1_tgt)\n      (SIM: sim_thread sim_terminal st1_src lc1_src gl1_src st1_tgt lc1_tgt gl1_tgt):\n  (<<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src gl1_src)>>) \\/\n  exists e_src st2_src lc2_src gl2_src st3_src lc3_src gl3_src,\n    (<<FAILURE: ThreadEvent.get_machine_event e_tgt <> MachineEvent.failure>>) /\\\n    (<<STEPS: rtc (@Thread.tau_step lang_src)\n                  (Thread.mk _ st1_src lc1_src gl1_src)\n                  (Thread.mk _ st2_src lc2_src gl2_src)>>) /\\\n    (<<STEP: Thread.opt_step e_src\n                             (Thread.mk _ st2_src lc2_src gl2_src)\n                             (Thread.mk _ st3_src lc3_src gl3_src)>>) /\\\n    (<<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>>) /\\\n    (<<GLOBAL: sim_global gl3_src gl3_tgt>>) /\\\n    (<<LC_WF_SRC: Local.wf lc3_src gl3_src>>) /\\\n    (<<LC_WF_TGT: Local.wf lc3_tgt gl3_tgt>>) /\\\n    (<<GL_WF_SRC: Global.wf gl3_src>>) /\\\n    (<<GL_WF_TGT: Global.wf gl3_tgt>>) /\\\n    (<<SIM: sim_thread sim_terminal st3_src lc3_src gl3_src st3_tgt lc3_tgt gl3_tgt>>).\nProof.\n  inv STEP.\n  - right. esplits; eauto; ss.\n  - eapply sim_thread_step; eauto.\nQed.\n\nLemma sim_thread_rtc_step\n      lang_src lang_tgt\n      sim_terminal\n      st1_src lc1_src gl1_src\n      th1_tgt th2_tgt\n      (STEPS: rtc (@Thread.tau_step lang_tgt) th1_tgt th2_tgt)\n      (GLOBAL: sim_global gl1_src (Thread.global th1_tgt))\n      (LC_WF_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF_TGT: Local.wf (Thread.local th1_tgt) (Thread.global th1_tgt))\n      (GL_WF_SRC: Global.wf gl1_src)\n      (GL_WF_TGT: Global.wf (Thread.global th1_tgt))\n      (SIM: sim_thread sim_terminal\n                       st1_src lc1_src gl1_src\n                       (Thread.state th1_tgt) (Thread.local th1_tgt) (Thread.global th1_tgt)):\n  (<<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src gl1_src)>>) \\/\n  exists st2_src lc2_src gl2_src,\n    (<<STEPS: rtc (@Thread.tau_step lang_src)\n                  (Thread.mk _ st1_src lc1_src gl1_src)\n                  (Thread.mk _ st2_src lc2_src gl2_src)>>) /\\\n    (<<GLOBAL: sim_global gl2_src (Thread.global th2_tgt)>>) /\\\n    (<<LC_WF_SRC: Local.wf lc2_src gl2_src>>) /\\\n    (<<LC_WF_TGT: Local.wf (Thread.local th2_tgt) (Thread.global th2_tgt)>>) /\\\n    (<<GL_WF_SRC: Global.wf gl2_src>>) /\\\n    (<<GL_WF_TGT: Global.wf (Thread.global th2_tgt)>>) /\\\n    (<<SIM: sim_thread sim_terminal\n                       st2_src lc2_src gl2_src\n                       (Thread.state th2_tgt) (Thread.local th2_tgt) (Thread.global th2_tgt)>>).\nProof.\n  revert GLOBAL LC_WF_SRC LC_WF_TGT GL_WF_SRC GL_WF_TGT SIM.\n  revert st1_src lc1_src gl1_src.\n  induction STEPS; i.\n  { right. esplits; eauto. }\n  inv H. destruct x, y. ss.\n  exploit Thread.step_future; eauto. s. i. des.\n  exploit sim_thread_step; eauto. i. des; eauto.\n  exploit IHSTEPS; eauto. i. des.\n  - left. inv FAILURE0. des.\n    econs; [|eauto|eauto].\n    etrans; eauto. inv STEP; eauto.\n    econs 2; eauto. econs.\n    + eauto.\n    + destruct e, e_src; ss.\n  - right. destruct z. ss.\n    esplits; try apply GLOBAL1; eauto.\n    etrans; [eauto|]. etrans; [|eauto]. inv STEP; eauto.\n    econs 2; eauto. econs.\n    + eauto.\n    + destruct e, e_src; ss.\nQed.\n\nLemma sim_thread_plus_step\n      lang_src lang_tgt\n      sim_terminal\n      e_tgt\n      st1_src lc1_src gl1_src\n      th1_tgt th2_tgt th3_tgt\n      (STEPS: rtc (@Thread.tau_step lang_tgt) th1_tgt th2_tgt)\n      (STEP: @Thread.step lang_tgt e_tgt th2_tgt th3_tgt)\n      (GLOBAL: sim_global gl1_src (Thread.global th1_tgt))\n      (LC_WF_SRC: Local.wf lc1_src gl1_src)\n      (LC_WF_TGT: Local.wf (Thread.local th1_tgt) (Thread.global th1_tgt))\n      (GL_WF_SRC: Global.wf gl1_src)\n      (GL_WF_TGT: Global.wf (Thread.global th1_tgt))\n      (SIM: sim_thread sim_terminal\n                       st1_src lc1_src gl1_src\n                       (Thread.state th1_tgt) (Thread.local th1_tgt) (Thread.global th1_tgt)):\n  (<<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src gl1_src)>>) \\/\n  exists e_src st2_src lc2_src gl2_src st3_src lc3_src gl3_src,\n    (<<STEPS: rtc (@Thread.tau_step lang_src)\n                  (Thread.mk _ st1_src lc1_src gl1_src)\n                  (Thread.mk _ st2_src lc2_src gl2_src)>>) /\\\n    (<<STEP: Thread.opt_step e_src\n                             (Thread.mk _ st2_src lc2_src gl2_src)\n                             (Thread.mk _ st3_src lc3_src gl3_src)>>) /\\\n    (<<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>>) /\\\n    (<<GLOBAL: sim_global gl3_src (Thread.global th3_tgt)>>) /\\\n    (<<LC_WF_SRC: Local.wf lc3_src gl3_src>>) /\\\n    (<<LC_WF_TGT: Local.wf (Thread.local th3_tgt) (Thread.global th3_tgt)>>) /\\\n    (<<GL_WF_SRC: Global.wf gl3_src>>) /\\\n    (<<GL_WF_TGT: Global.wf (Thread.global th3_tgt)>>) /\\\n    (<<SIM: sim_thread sim_terminal\n                       st3_src lc3_src gl3_src\n                       (Thread.state th3_tgt) (Thread.local th3_tgt) (Thread.global th3_tgt)>>).\nProof.\n  destruct th1_tgt, th2_tgt, th3_tgt. ss.\n  exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n  exploit sim_thread_rtc_step; eauto. s. i. des; eauto.\n  exploit Thread.rtc_tau_step_future; try exact STEPS0; eauto. s. i. des.\n  exploit sim_thread_step; try exact STEP; try exact SIM0; eauto. s. i. des.\n  - left. inv FAILURE. des.\n    econs; [|eauto|eauto].\n    etrans; eauto.\n  - right. rewrite STEPS1 in STEPS0.\n    esplits; try exact STEPS0; try exact STEP0; eauto.\nQed.\n\nLemma sim_thread_steps_failure\n      lang_src lang_tgt\n      sim_terminal\n      e_src e_tgt\n      (FAILURE: Thread.steps_failure e_tgt)\n      (GLOBAL: sim_global (Thread.global e_src) (Thread.global e_tgt))\n      (LC_WF_SRC: Local.wf (Thread.local e_src) (Thread.global e_src))\n      (LC_WF_TGT: Local.wf (Thread.local e_tgt) (Thread.global e_tgt))\n      (GL_WF_SRC: Global.wf (Thread.global e_src))\n      (GL_WF_TGT: Global.wf (Thread.global e_tgt))\n      (SIM: @sim_thread lang_src lang_tgt sim_terminal\n                        (Thread.state e_src) (Thread.local e_src) (Thread.global e_src)\n                        (Thread.state e_tgt) (Thread.local e_tgt) (Thread.global e_tgt)):\n  (<<FAILURE: Thread.steps_failure e_src>>).\nProof.\n  destruct e_src, e_tgt. ss. inv FAILURE.\n  exploit sim_thread_plus_step; eauto. i. des; eauto.\n  rewrite EVENT_FAILURE in *. inv STEP; ss.\n  esplits; eauto.\nQed.\n\nLemma sim_thread_future\n      lang_src lang_tgt\n      sim_terminal\n      st_src lc_src gl1_src gl2_src\n      st_tgt lc_tgt gl1_tgt gl2_tgt\n      (SIM: @sim_thread lang_src lang_tgt sim_terminal st_src lc_src gl1_src st_tgt lc_tgt gl1_tgt)\n      (GL_FUTURE_SRC: Global.strong_le gl1_src gl2_src)\n      (GL_FUTURE_TGT: Global.le gl1_tgt gl2_tgt):\n  sim_thread sim_terminal st_src lc_src gl2_src st_tgt lc_tgt gl2_tgt.\nProof.\n  pfold. ii.\n  punfold SIM. exploit SIM; (try by etrans; eauto); eauto.\nQed.\n\nLemma sim_thread_cap\n      lang_src lang_tgt\n      sim_terminal\n      st_src lc_src gl_src\n      st_tgt lc_tgt gl_tgt\n      (SIM: @sim_thread lang_src lang_tgt sim_terminal st_src lc_src gl_src st_tgt lc_tgt gl_tgt):\n  sim_thread sim_terminal\n             st_src lc_src (Global.cap_of gl_src)\n             st_tgt lc_tgt (Global.cap_of gl_tgt).\nProof.\n  eapply sim_thread_future; eauto.\n  { eapply Global.cap_strong_le; eauto. }\n  { eapply Global.cap_le; eauto. }\nQed.\n\nLemma sim_thread_consistent\n      lang_src lang_tgt\n      sim_terminal\n      st_src lc_src gl_src\n      st_tgt lc_tgt gl_tgt\n      (SIM: sim_thread sim_terminal st_src lc_src gl_src st_tgt lc_tgt gl_tgt)\n      (GLOBAL: sim_global gl_src gl_tgt)\n      (LC_WF_SRC: Local.wf lc_src gl_src)\n      (LC_WF_TGT: Local.wf lc_tgt gl_tgt)\n      (GL_WF_SRC: Global.wf gl_src)\n      (GL_WF_TGT: Global.wf gl_tgt)\n      (CONSISTENT: Thread.consistent (Thread.mk lang_tgt st_tgt lc_tgt gl_tgt)):\n  Thread.consistent (Thread.mk lang_src st_src lc_src gl_src).\nProof.\n  generalize SIM. intro X.\n  exploit sim_memory_max_timemap; try eapply GLOBAL; try apply GL_WF_SRC; try apply GL_WF_TGT. i.\n  exploit Local.cap_wf; try exact LC_WF_SRC. i.\n  exploit Local.cap_wf; try exact LC_WF_TGT. i.\n  exploit Global.cap_wf; try exact GL_WF_SRC. i.\n  exploit Global.cap_wf; try exact GL_WF_TGT. i.\n  hexploit sim_thread_cap; eauto. intros CAP.\n  hexploit sim_global_cap; eauto. intros GL.\n  inv CONSISTENT.\n  - exploit sim_thread_steps_failure; try exact x2; eauto; s; eauto.\n  - exploit sim_thread_rtc_step; eauto.\n    i. des; eauto. destruct th2. ss.\n    punfold SIM0. exploit SIM0; try exact x0; eauto; try refl. i. des.\n    exploit PROMISES0; eauto. i. des.\n    + econs 1. inv FAILURE.\n      econs; [|eauto|eauto]. etrans; eauto.\n    + econs 2; [etrans; eauto|]. ss.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/trans/SimThread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228891883799, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.21689114402883625}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Typing rules and a type inference algorithm for RTL. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Op.\nRequire Import Registers.\nRequire Import Globalenvs.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Integers.\nRequire Import Events.\nRequire Import Smallstep.\nRequire Import RTL.\nRequire Import Conventions.\n\n(** * The type system *)\n\n(** Like Cminor and all intermediate languages, RTL can be equipped with\n  a simple type system that statically guarantees that operations\n  and addressing modes are applied to the right number of arguments\n  and that the arguments are of the correct types.  The type algebra\n  is trivial, consisting of the two types [Tint] (for integers and pointers)\n  and [Tfloat] (for floats).  \n\n  Additionally, we impose that each pseudo-register has the same type\n  throughout the function.  This requirement helps with register allocation,\n  enabling each pseudo-register to be mapped to a single hardware register\n  or stack location of the correct type.\n\n  Finally, we also check that the successors of instructions\n  are valid, i.e. refer to non-empty nodes in the CFG.\n\n  The typing judgement for instructions is of the form [wt_instr f env\n  instr], where [f] is the current function (used to type-check\n  [Ireturn] instructions) and [env] is a typing environment\n  associating types to pseudo-registers.  Since pseudo-registers have\n  unique types throughout the function, the typing environment does\n  not change during type-checking of individual instructions.  One\n  point to note is that we have one polymorphic operator, [Omove],\n  which can work over both integers and floats.\n*)\n\nDefinition regenv := reg -> typ.\n\nSection WT_INSTR.\n\nVariable env: regenv.\nVariable funct: function.\n\nDefinition valid_successor (s: node) : Prop :=\n  exists i, funct.(fn_code)!s = Some i.\n\nInductive wt_instr : instruction -> Prop :=\n  | wt_Inop:\n      forall s,\n      valid_successor s ->\n      wt_instr (Inop s)\n  | wt_Iopmove:\n      forall r1 r s,\n      env r1 = env r ->\n      valid_successor s ->\n      wt_instr (Iop Omove (r1 :: nil) r s)\n  | wt_Iop:\n      forall op args res s,\n      op <> Omove ->\n      (List.map env args, env res) = type_of_operation op ->\n      valid_successor s ->\n      wt_instr (Iop op args res s)\n  | wt_Iload:\n      forall chunk addr args dst s,\n      List.map env args = type_of_addressing addr ->\n      env dst = type_of_chunk chunk ->\n      valid_successor s ->\n      wt_instr (Iload chunk addr args dst s)\n  | wt_Istore:\n      forall chunk addr args src s,\n      List.map env args = type_of_addressing addr ->\n      env src = type_of_chunk chunk ->\n      valid_successor s ->\n      wt_instr (Istore chunk addr args src s)\n  | wt_Icall:\n      forall sig ros args res s,\n      match ros with inl r => env r = Tint | inr s => True end ->\n      List.map env args = sig.(sig_args) ->\n      env res = proj_sig_res sig ->\n      valid_successor s ->\n      wt_instr (Icall sig ros args res s)\n  | wt_Itailcall:\n      forall sig ros args,\n      match ros with inl r => env r = Tint | inr s => True end ->\n      sig.(sig_res) = funct.(fn_sig).(sig_res) ->\n      List.map env args = sig.(sig_args) ->\n      tailcall_possible sig ->\n      wt_instr (Itailcall sig ros args)\n  | wt_Ibuiltin:\n      forall ef args res s,\n      List.map env args = (ef_sig ef).(sig_args) ->\n      env res = proj_sig_res (ef_sig ef) ->\n      arity_ok (ef_sig ef).(sig_args) = true \\/ ef_reloads ef = false ->\n      valid_successor s ->\n      wt_instr (Ibuiltin ef args res s)\n  | wt_Icond:\n      forall cond args s1 s2,\n      List.map env args = type_of_condition cond ->\n      valid_successor s1 ->\n      valid_successor s2 ->\n      wt_instr (Icond cond args s1 s2)\n  | wt_Ijumptable:\n      forall arg tbl,\n      env arg = Tint ->\n      (forall s, In s tbl -> valid_successor s) ->\n      list_length_z tbl * 4 <= Int.max_unsigned ->\n      wt_instr (Ijumptable arg tbl)\n  | wt_Ireturn: \n      forall optres,\n      option_map env optres = funct.(fn_sig).(sig_res) ->\n      wt_instr (Ireturn optres).\n\nEnd WT_INSTR.\n\n(** A function [f] is well-typed w.r.t. a typing environment [env],\n   written [wt_function env f], if all instructions are well-typed,\n   parameters agree in types with the function signature, and\n   parameters are pairwise distinct. *)\n\nRecord wt_function (f: function) (env: regenv): Prop :=\n  mk_wt_function {\n    wt_params:\n      List.map env f.(fn_params) = f.(fn_sig).(sig_args);\n    wt_norepet:\n      list_norepet f.(fn_params);\n    wt_instrs:\n      forall pc instr, \n      f.(fn_code)!pc = Some instr -> wt_instr env f instr;\n    wt_entrypoint:\n      valid_successor f f.(fn_entrypoint)\n}.\n\nInductive wt_fundef: fundef -> Prop :=\n  | wt_fundef_external: forall ef,\n      wt_fundef (External ef)\n  | wt_function_internal: forall f env,\n      wt_function f env ->\n      wt_fundef (Internal f).\n\nDefinition wt_program (p: program): Prop :=\n  forall i f, In (i, f) (prog_funct p) -> wt_fundef f.\n\n(** * Type inference *)\n\n(** There are several ways to ensure that RTL code is well-typed and\n  to obtain the typing environment (type assignment for pseudo-registers)\n  needed for register allocation.  One is to start with well-typed Cminor\n  code and show type preservation for RTL generation and RTL optimizations.\n  Another is to start with untyped RTL and run a type inference algorithm\n  that reconstructs the typing environment, determining the type of\n  each pseudo-register from its uses in the code.  We follow the second\n  approach.\n\n  We delegate the task of determining the type of each pseudo-register\n  to an external ``oracle'': a function written in Caml and not\n  proved correct.  We verify the returned type environment using\n  the following Coq code, which we will prove correct. *)\n\nParameter infer_type_environment:\n  function -> list (node * instruction) -> option regenv.\n\n(** ** Algorithm to check the correctness of a type environment *)\n\nSection TYPECHECKING.\n\nVariable funct: function.\nVariable env: regenv.\n\nDefinition check_reg (r: reg) (ty: typ): bool :=\n  if typ_eq (env r) ty then true else false.\n\nFixpoint check_regs (rl: list reg) (tyl: list typ) {struct rl}: bool :=\n  match rl, tyl with\n  | nil, nil => true\n  | r1::rs, ty::tys => check_reg r1 ty && check_regs rs tys\n  | _, _ => false\n  end.\n\nDefinition check_op (op: operation) (args: list reg) (res: reg): bool :=\n  let (targs, tres) := type_of_operation op in\n  check_regs args targs && check_reg res tres.\n\nDefinition check_successor (s: node) : bool :=\n  match funct.(fn_code)!s with None => false | Some i => true end.\n\nDefinition check_instr (i: instruction) : bool :=\n  match i with\n  | Inop s =>\n      check_successor s\n  | Iop Omove (arg::nil) res s =>\n      if typ_eq (env arg) (env res) \n      then check_successor s\n      else false\n  | Iop Omove args res s =>\n      false\n  | Iop op args res s =>\n      check_op op args res && check_successor s\n  | Iload chunk addr args dst s =>\n      check_regs args (type_of_addressing addr)\n      && check_reg dst (type_of_chunk chunk)\n      && check_successor s\n  | Istore chunk addr args src s =>\n      check_regs args (type_of_addressing addr)\n      && check_reg src (type_of_chunk chunk)\n      && check_successor s\n  | Icall sig ros args res s =>\n      match ros with inl r => check_reg r Tint | inr s => true end\n      && check_regs args sig.(sig_args)\n      && check_reg res (proj_sig_res sig)\n      && check_successor s\n  | Itailcall sig ros args =>\n      match ros with inl r => check_reg r Tint | inr s => true end\n      && check_regs args sig.(sig_args)\n      && opt_typ_eq sig.(sig_res) funct.(fn_sig).(sig_res)\n      && tailcall_is_possible sig\n  | Ibuiltin ef args res s =>\n      check_regs args (ef_sig ef).(sig_args)\n      && check_reg res (proj_sig_res (ef_sig ef))\n      && (if ef_reloads ef then arity_ok (ef_sig ef).(sig_args) else true)\n      && check_successor s\n  | Icond cond args s1 s2 =>\n      check_regs args (type_of_condition cond)\n      && check_successor s1\n      && check_successor s2\n  | Ijumptable arg tbl =>\n      check_reg arg Tint\n      && List.forallb check_successor tbl\n      && zle (list_length_z tbl * 4) Int.max_unsigned\n  | Ireturn optres =>\n      match optres, funct.(fn_sig).(sig_res) with\n      | None, None => true\n      | Some r, Some t => check_reg r t\n      | _, _ => false\n      end\n  end.\n\nDefinition check_params_norepet (params: list reg): bool :=\n  if list_norepet_dec Reg.eq params then true else false.\n\nFixpoint check_instrs (instrs: list (node * instruction)) : bool :=\n  match instrs with\n  | nil => true\n  | (pc, i) :: rem => check_instr i && check_instrs rem\n  end.\n\n(** ** Correctness of the type-checking algorithm *)\n\nLtac elimAndb :=\n  match goal with\n  | [ H: _ && _ = true |- _ ] =>\n      elim (andb_prop _ _ H); clear H; intros; elimAndb\n  | _ =>\n      idtac\n  end.\n\nLemma check_reg_correct:\n  forall r ty, check_reg r ty = true -> env r = ty.\nProof.\n  unfold check_reg; intros.\n  destruct (typ_eq (env r) ty). auto. discriminate.\nQed.\n\nLemma check_regs_correct:\n  forall rl tyl, check_regs rl tyl = true -> List.map env rl = tyl.\nProof.\n  induction rl; destruct tyl; simpl; intros.\n  auto. discriminate. discriminate.\n  elimAndb.\n  rewrite (check_reg_correct _ _ H). rewrite (IHrl tyl H0). auto.\nQed.\n\nLemma check_op_correct:\n  forall op args res,\n  check_op op args res = true ->\n  (List.map env args, env res) = type_of_operation op.\nProof.\n  unfold check_op; intros.\n  destruct (type_of_operation op) as [targs tres].\n  elimAndb. \n  rewrite (check_regs_correct _ _ H).\n  rewrite (check_reg_correct _ _ H0).\n  auto.\nQed.\n\nLemma check_successor_correct:\n  forall s,\n  check_successor s = true -> valid_successor funct s.\nProof.\n  intro; unfold check_successor, valid_successor.\n  destruct (fn_code funct)!s; intro.\n  exists i; auto.\n  discriminate.\nQed.\n\nLemma check_instr_correct:\n  forall i, check_instr i = true -> wt_instr env funct i.\nProof.\n  unfold check_instr; intros; destruct i; elimAndb.\n  (* nop *)\n  constructor. apply check_successor_correct; auto.\n  (* op *)\n  destruct o; elimAndb;\n  try (apply wt_Iop; [ congruence\n                     | apply check_op_correct; auto\n                     | apply check_successor_correct; auto ]).\n  destruct l; try discriminate. destruct l; try discriminate.\n  destruct (typ_eq (env r0) (env r)); try discriminate.\n  apply wt_Iopmove; auto. apply check_successor_correct; auto.\n  (* load *)\n  constructor. apply check_regs_correct; auto. apply check_reg_correct; auto.\n  apply check_successor_correct; auto.\n  (* store *)\n  constructor. apply check_regs_correct; auto. apply check_reg_correct; auto.\n  apply check_successor_correct; auto.\n  (* call *)\n  constructor.\n  destruct s0; auto. apply check_reg_correct; auto.\n  apply check_regs_correct; auto.\n  apply check_reg_correct; auto.\n  apply check_successor_correct; auto.\n  (* tailcall *)\n  constructor.\n  destruct s0; auto. apply check_reg_correct; auto.\n  eapply proj_sumbool_true; eauto.\n  apply check_regs_correct; auto.\n  apply tailcall_is_possible_correct; auto.\n  (* builtin *)\n  constructor.\n  apply check_regs_correct; auto.\n  apply check_reg_correct; auto.\n  auto.\n  destruct (ef_reloads e); auto. \n  apply check_successor_correct; auto.\n  (* cond *)\n  constructor. apply check_regs_correct; auto.\n  apply check_successor_correct; auto.\n  apply check_successor_correct; auto.\n  (* jumptable *)\n  constructor. apply check_reg_correct; auto.\n  rewrite List.forallb_forall in H1. intros. apply check_successor_correct; auto.\n  eapply proj_sumbool_true. eauto.  \n  (* return *)\n  constructor. \n  destruct o; simpl; destruct funct.(fn_sig).(sig_res); try discriminate.\n  rewrite (check_reg_correct _ _ H); auto.\n  auto.\nQed.\n\nLemma check_instrs_correct:\n  forall instrs,\n  check_instrs instrs = true ->\n  forall pc i, In (pc, i) instrs -> wt_instr env funct i.\nProof.\n  induction instrs; simpl; intros.\n  elim H0.\n  destruct a as [pc' i']. elimAndb. \n  elim H0; intro.\n  inversion H2; subst pc' i'. apply check_instr_correct; auto.\n  eauto.\nQed.\n\nEnd TYPECHECKING.\n\n(** ** The type inference function **)\n\nOpen Scope string_scope.\n\nDefinition type_function (f: function): res regenv :=\n  let instrs := PTree.elements f.(fn_code) in\n  match infer_type_environment f instrs with\n  | None => Error (msg \"RTL type inference error\")\n  | Some env =>\n      if check_regs env f.(fn_params) f.(fn_sig).(sig_args)\n      && check_params_norepet f.(fn_params)\n      && check_instrs f env instrs\n      && check_successor f f.(fn_entrypoint)\n      then OK env\n      else Error (msg \"RTL type checking error\")\n  end.\n\nLemma type_function_correct:\n  forall f env,\n  type_function f = OK env ->\n  wt_function f env.\nProof.\n  unfold type_function; intros until env.\n  set (instrs := PTree.elements f.(fn_code)).\n  case (infer_type_environment f instrs).\n  intro env'. \n  caseEq (check_regs env' f.(fn_params) f.(fn_sig).(sig_args)); intro; simpl; try congruence.\n  caseEq (check_params_norepet f.(fn_params)); intro; simpl; try congruence.\n  caseEq (check_instrs f env' instrs); intro; simpl; try congruence.\n  caseEq (check_successor f (fn_entrypoint f)); intro; simpl; try congruence.\n  intro EQ; inversion EQ; subst env'.\n  constructor. \n  apply check_regs_correct; auto.\n  unfold check_params_norepet in H0. \n  destruct (list_norepet_dec Reg.eq (fn_params f)). auto. discriminate.\n  intros. eapply check_instrs_correct. eauto. \n  unfold instrs. apply PTree.elements_correct. eauto.\n  apply check_successor_correct. auto.\n  congruence.\nQed.\n\n(** * Type preservation during evaluation *)\n\n(** The type system for RTL is not sound in that it does not guarantee\n  progress: well-typed instructions such as [Icall] can fail because\n  of run-time type tests (such as the equality between callee and caller's\n  signatures).  However, the type system guarantees a type preservation\n  property: if the execution does not fail because of a failed run-time\n  test, the result values and register states match the static\n  typing assumptions.  This preservation property will be useful\n  later for the proof of semantic equivalence between [Linear] and [Mach].\n  Even though we do not need it for [RTL], we show preservation for [RTL]\n  here, as a warm-up exercise and because some of the lemmas will be\n  useful later. *)\n\nDefinition wt_regset (env: regenv) (rs: regset) : Prop :=\n  forall r, Val.has_type (rs#r) (env r).\n\nLemma wt_regset_assign:\n  forall env rs v r,\n  wt_regset env rs ->\n  Val.has_type v (env r) ->\n  wt_regset env (rs#r <- v).\nProof.\n  intros; red; intros. \n  rewrite Regmap.gsspec.\n  case (peq r0 r); intro.\n  subst r0. assumption.\n  apply H.\nQed.\n\nLemma wt_regset_list:\n  forall env rs,\n  wt_regset env rs ->\n  forall rl, Val.has_type_list (rs##rl) (List.map env rl).\nProof.\n  induction rl; simpl.\n  auto.\n  split. apply H. apply IHrl.\nQed.  \n\nLemma wt_init_regs:\n  forall env rl args,\n  Val.has_type_list args (List.map env rl) ->\n  wt_regset env (init_regs args rl).\nProof.\n  induction rl; destruct args; simpl; intuition.\n  red; intros. rewrite Regmap.gi. simpl; auto. \n  apply wt_regset_assign; auto.\nQed.\n\nInductive wt_stackframes: list stackframe -> option typ -> Prop :=\n  | wt_stackframes_nil:\n      wt_stackframes nil (Some Tint)\n  | wt_stackframes_cons:\n      forall s res f sp pc rs env tyres,\n      wt_function f env ->\n      wt_regset env rs ->\n      env res = match tyres with None => Tint | Some t => t end ->\n      wt_stackframes s (sig_res (fn_sig f)) ->\n      wt_stackframes (Stackframe res f sp pc rs :: s) tyres.\n\nInductive wt_state: state -> Prop :=\n  | wt_state_intro:\n      forall s f sp pc rs m env\n        (WT_STK: wt_stackframes s (sig_res (fn_sig f)))\n        (WT_FN: wt_function f env)\n        (WT_RS: wt_regset env rs),\n      wt_state (State s f sp pc rs m)\n  | wt_state_call:\n      forall s f args m,\n      wt_stackframes s (sig_res (funsig f)) ->\n      wt_fundef f ->\n      Val.has_type_list args (sig_args (funsig f)) ->\n      wt_state (Callstate s f args m)\n  | wt_state_return:\n      forall s v m tyres,\n      wt_stackframes s tyres ->\n      Val.has_type v (match tyres with None => Tint | Some t => t end) ->\n      wt_state (Returnstate s v m).\n\nSection SUBJECT_REDUCTION.\n\nVariable p: program.\n\nHypothesis wt_p: wt_program p.\n\nLet ge := Genv.globalenv p.\n\nLemma subject_reduction:\n  forall st1 t st2, step ge st1 t st2 ->\n  forall (WT: wt_state st1), wt_state st2.\nProof.\n  induction 1; intros; inv WT;\n  try (generalize (wt_instrs _ _ WT_FN pc _ H);\n       intro WT_INSTR;\n       inv WT_INSTR).\n  (* Inop *)\n  econstructor; eauto.\n  (* Iop *)\n  econstructor; eauto.\n  apply wt_regset_assign. auto. \n  simpl in H0. inv H0. rewrite <- H3. apply WT_RS.\n  econstructor; eauto.\n  apply wt_regset_assign. auto.\n  replace (env res) with (snd (type_of_operation op)).\n  eapply type_of_operation_sound; eauto.\n  rewrite <- H6. reflexivity.\n  (* Iload *)\n  econstructor; eauto.\n  apply wt_regset_assign. auto. rewrite H8. \n  eapply type_of_chunk_correct; eauto.\n  (* Istore *)\n  econstructor; eauto.\n  (* Icall *)\n  assert (wt_fundef fd).\n    destruct ros; simpl in H0.\n    pattern fd. apply Genv.find_funct_prop with fundef unit p (rs#r).\n    exact wt_p. exact H0. \n    caseEq (Genv.find_symbol ge i); intros; rewrite H1 in H0.\n    pattern fd. apply Genv.find_funct_ptr_prop with fundef unit p b.\n    exact wt_p. exact H0.\n    discriminate.\n  econstructor; eauto.\n  econstructor; eauto.\n  rewrite <- H7. apply wt_regset_list. auto.\n  (* Itailcall *)\n  assert (wt_fundef fd).\n    destruct ros; simpl in H0.\n    pattern fd. apply Genv.find_funct_prop with fundef unit p (rs#r).\n    exact wt_p. exact H0. \n    caseEq (Genv.find_symbol ge i); intros; rewrite H1 in H0.\n    pattern fd. apply Genv.find_funct_ptr_prop with fundef unit p b.\n    exact wt_p. exact H0.\n    discriminate.\n  econstructor; eauto.\n  rewrite H6; auto.\n  rewrite <- H7. apply wt_regset_list. auto.\n  (* Ibuiltin *)\n  econstructor; eauto.\n  apply wt_regset_assign. auto. \n  rewrite H6. eapply external_call_well_typed; eauto. \n  (* Icond *)\n  econstructor; eauto.\n  (* Ijumptable *)\n  econstructor; eauto.\n  (* Ireturn *)\n  econstructor; eauto. \n  destruct or; simpl in *.\n  rewrite <- H2. apply WT_RS. exact I.\n  (* internal function *)\n  simpl in *. inv H5. inversion H1; subst.  \n  econstructor; eauto.\n  apply wt_init_regs; auto. rewrite wt_params0; auto.\n  (* external function *)\n  simpl in *. inv H5. \n  econstructor; eauto. \n  change (Val.has_type res (proj_sig_res (ef_sig ef))).\n  eapply external_call_well_typed; eauto.\n  (* return *)\n  inv H1. econstructor; eauto. \n  apply wt_regset_assign; auto. congruence. \nQed.\n\nEnd SUBJECT_REDUCTION.\n", "meta": {"author": "Ptival", "repo": "compcert-alias", "sha": "c839efb9cd2a4c27add46a1868fe0444d1dfdd9e", "save_path": "github-repos/coq/Ptival-compcert-alias", "path": "github-repos/coq/Ptival-compcert-alias/compcert-alias-c839efb9cd2a4c27add46a1868fe0444d1dfdd9e/backend/RTLtyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21678555428705873}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Recognition of combined operations, addressing modes and conditions\n  during the [CSE] phase. *)\n\nRequire Import FunInd.\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Op.\nRequire Import Registers.\nRequire Import RTL.\nRequire Import CSEdomain.\nRequire Import CombineOp.\n\nSection COMBINE.\n\nVariable ge: genv.\nVariable sp: val.\nVariable m: mem.\nVariable get: valnum -> option rhs.\nVariable valu: valnum -> val.\nHypothesis get_sound: forall v rhs, get v = Some rhs -> rhs_eval_to valu ge sp m rhs (valu v).\n\nLemma get_op_sound:\n  forall v op vl, get v = Some (Op op vl) -> eval_operation ge sp op (map valu vl) m = Some (valu v).\nProof.\n  intros. exploit get_sound; eauto. intros REV; inv REV; auto.\nQed.\n\nLtac UseGetSound :=\n  match goal with\n  | [ H: get _ = Some _ |- _ ] =>\n      let x := fresh \"EQ\" in (generalize (get_op_sound _ _ _ H); intros x; simpl in x; FuncInv)\n  end.\n\nLemma combine_compimm_ne_0_sound:\n  forall x cond args,\n  combine_compimm_ne_0 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Cne (valu x) (Vint Int.zero) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Cne (valu x) (Vint Int.zero).\nProof.\n  intros until args. functional induction (combine_compimm_ne_0 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  destruct (eval_condition cond (map valu args) m); simpl; auto. destruct b; auto.\nQed.\n\nLemma combine_compimm_eq_0_sound:\n  forall x cond args,\n  combine_compimm_eq_0 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Ceq (valu x) (Vint Int.zero) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Ceq (valu x) (Vint Int.zero).\nProof.\n  intros until args. functional induction (combine_compimm_eq_0 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  rewrite eval_negate_condition.\n  destruct (eval_condition c (map valu args) m); simpl; auto. destruct b; auto.\nQed.\n\nLemma combine_compimm_eq_1_sound:\n  forall x cond args,\n  combine_compimm_eq_1 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Ceq (valu x) (Vint Int.one) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Ceq (valu x) (Vint Int.one).\nProof.\n  intros until args. functional induction (combine_compimm_eq_1 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  destruct (eval_condition cond (map valu args) m); simpl; auto. destruct b; auto.\nQed.\n\nLemma combine_compimm_ne_1_sound:\n  forall x cond args,\n  combine_compimm_ne_1 get x = Some(cond, args) ->\n  eval_condition cond (map valu args) m = Val.cmp_bool Cne (valu x) (Vint Int.one) /\\\n  eval_condition cond (map valu args) m = Val.cmpu_bool (Mem.valid_pointer m) Cne (valu x) (Vint Int.one).\nProof.\n  intros until args. functional induction (combine_compimm_ne_1 get x); intros EQ; inv EQ.\n  (* of cmp *)\n  UseGetSound. rewrite <- H.\n  rewrite eval_negate_condition.\n  destruct (eval_condition c (map valu args) m); simpl; auto. destruct b; auto.\nQed.\n\nTheorem combine_cond_sound:\n  forall cond args cond' args',\n  combine_cond get cond args = Some(cond', args') ->\n  eval_condition cond' (map valu args') m = eval_condition cond (map valu args) m.\nProof.\n  intros. functional inversion H; subst.\n  (* compimm ne zero *)\n  - simpl; eapply combine_compimm_ne_0_sound; eauto.\n  (* compimm ne one *)\n  - simpl; eapply combine_compimm_ne_1_sound; eauto.\n  (* compimm eq zero *)\n  - simpl; eapply combine_compimm_eq_0_sound; eauto.\n  (* compimm eq one *)\n  - simpl; eapply combine_compimm_eq_1_sound; eauto.\n  (* compuimm ne zero *)\n  - simpl; eapply combine_compimm_ne_0_sound; eauto.\n  (* compuimm ne one *)\n  - simpl; eapply combine_compimm_ne_1_sound; eauto.\n  (* compuimm eq zero *)\n  - simpl; eapply combine_compimm_eq_0_sound; eauto.\n  (* compuimm eq one *)\n  - simpl; eapply combine_compimm_eq_1_sound; eauto.\nQed.\n\nTheorem combine_addr_sound:\n  forall addr args addr' args',\n  combine_addr get addr args = Some(addr', args') ->\n  eval_addressing ge sp addr' (map valu args') = eval_addressing ge sp addr (map valu args).\nProof.\n  intros. functional inversion H; subst.\n- (* indexed - addimm *)\n  UseGetSound. simpl. rewrite <- H0. destruct v; auto. simpl; rewrite H7; simpl.\n  rewrite Ptrofs.add_assoc. auto.\n- (* indexed - addimml *)\n  UseGetSound. simpl. rewrite <- H0. destruct v; auto. simpl; rewrite H7; simpl.\n  rewrite Ptrofs.add_assoc. auto.\nQed.\n\nTheorem combine_op_sound:\n  forall op args op' args',\n  combine_op get op args = Some(op', args') ->\n  eval_operation ge sp op' (map valu args') m = eval_operation ge sp op (map valu args) m.\nProof.\n  intros. functional inversion H; subst.\n  (* addimm - addimm *)\n  - UseGetSound. FuncInv. simpl.\n    rewrite <- H0. rewrite Val.add_assoc. auto.\n  (* andimm - andimm *)\n  - UseGetSound; simpl.\n    generalize (Int.eq_spec p m0); rewrite H7; intros.\n    rewrite <- H0. rewrite Val.and_assoc. simpl. fold p. rewrite H1. auto.\n  - UseGetSound; simpl.\n    rewrite <- H0. rewrite Val.and_assoc. auto.\n  (* orimm - orimm *)\n  - UseGetSound. simpl. rewrite <- H0. rewrite Val.or_assoc. auto.\n  (* xorimm - xorimm *)\n  - UseGetSound. simpl. rewrite <- H0. rewrite Val.xor_assoc. auto.\n  (* addlimm - addlimm *)\n  - UseGetSound. FuncInv. simpl.\n    rewrite <- H0. rewrite Val.addl_assoc. auto.\n  (* andlimm - andlimm *)\n  - UseGetSound; simpl.\n    generalize (Int64.eq_spec p m0); rewrite H7; intros.\n    rewrite <- H0. rewrite Val.andl_assoc. simpl. fold p. rewrite H1. auto.\n  - UseGetSound; simpl.\n    rewrite <- H0. rewrite Val.andl_assoc. auto.\n  (* orlimm - orlimm *)\n  - UseGetSound. simpl. rewrite <- H0. rewrite Val.orl_assoc. auto.\n  (* xorlimm - xorlimm *)\n  - UseGetSound. simpl. rewrite <- H0. rewrite Val.xorl_assoc. auto.\n  (* cmp *)\n  - simpl. decEq; decEq. eapply combine_cond_sound; eauto.\nQed.\n\nEnd COMBINE.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/riscV/CombineOpproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2167539031891296}}
{"text": "From iris.base_logic.lib Require Import invariants gen_heap wsat ghost_map.\nFrom iris.program_logic Require Import weakestpre adequacy.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic.lib Require Import invariants gen_heap.\nFrom st.STLCmuVS Require Import lang.\nFrom st.STLCmuST Require Import wkpre lang types.\nFrom st.backtranslations.st_sem.correctness.st_le_sem.logrel Require Import definition lift.\nFrom st Require Import resources.\n\nDefinition Σ : gFunctors :=\n  #[invΣ;\n    gen_heapΣ loc val;\n    ghost_mapΣ nat STLCmuVS.lang.val;\n    ghost_mapΣ nat loc\n    ].\n\nInstance st_le_semΣ_inst (H : invGS Σ) (H' : gen_heapGS loc lang.val Σ) : st_le_semΣ Σ :=\n  { invGS_inst := _ ;\n    genHeapG_inst' := _;\n    val_ghost_mapG_inst' := _;\n    loc_ghost_mapG_inst' := _;\n  }.\n\n(* st_le_ *)\nLemma exprel_adequate (e : expr) (e' : STLCmuVS.lang.expr)\n      (Hee' : ∀ {Σ : gFunctors}\n                {st_le_semΣ_inst : st_le_semΣ Σ},\n          ⊢ exprel_typed [] TUnit e e') :\n  STLCmuST_halts e → STLCmuVS_halts e'.\nProof.\n  intros He. destruct He as (v & σ & He).\n  cut (adequate MaybeStuck e ∅ (fun _ _ => STLCmuVS_halts e')).\n  { intro Ha. apply (adequate_result _ _ _ _ Ha [] σ v).\n    change ([?e], ?σ) with ((fun p => ([p.2], p.1)) (σ, e)).\n    eapply (rtc_congruence (fun p => ([p.2], p.1))); eauto.\n    intros [σ1 e1] [σ2 e2] Hstep. rewrite /STLCmuST_step in Hstep.\n    rewrite /erased_step /=. exists []. apply (step_atomic e1 σ1 e2 σ2 [] [] []); by simpl. }\n  apply (wp_adequacy Σ STLCmuST_lang MaybeStuck e (∅ : gmap loc val) (fun _ => STLCmuVS_halts e')).\n  { intros invGS_inst' κs.\n    iMod (gen_heap_init (∅ : gmap loc val)) as (gen_heapGS_inst') \"(H∅ & _ & _)\". iModIntro.\n    iExists (fun σ _ => gen_heap_interp σ).\n    iExists (fun _ => True%I).\n    iFrame \"H∅\".\n    specialize (Hee' Σ _).\n    iDestruct Hee' as \"Hee'\". rewrite /exprel_typed /lift /=.\n    iApply (wp_wand with \"Hee'\").\n    iIntros (w) \"Hdes\". iDestruct \"Hdes\" as (w') \"[%He' _]\".\n    iPureIntro. by eexists.\n  }\nQed.\n\n", "meta": {"author": "scaup", "repo": "sem_backs_st", "sha": "e14aa7f421de94df5c1369d2b4b44d8644243cec", "save_path": "github-repos/coq/scaup-sem_backs_st", "path": "github-repos/coq/scaup-sem_backs_st/sem_backs_st-e14aa7f421de94df5c1369d2b4b44d8644243cec/theories/backtranslations/st_sem/correctness/st_le_sem/logrel/adequacy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160666, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.21663503464644104}}
{"text": "Require Import RamifyCoq.sample_mark.env_unionfind_iter.\nRequire Import RamifyCoq.graph.graph_model.\nRequire Import RamifyCoq.graph.path_lemmas.\nRequire Import RamifyCoq.graph.subgraph2.\nRequire Import RamifyCoq.graph.graph_relation.\nRequire Import RamifyCoq.graph.reachable_computable.\nRequire Import RamifyCoq.msl_application.Graph.\nRequire Import RamifyCoq.msl_application.UnionFindGraph.\nRequire Import RamifyCoq.msl_application.GList.\nRequire Import RamifyCoq.msl_application.GList_UnionFind.\nRequire Import RamifyCoq.floyd_ext.share.\nRequire Import RamifyCoq.sample_mark.spatial_graph_uf_iter.\n\nLocal Coercion UGraph_LGraph: Graph >-> LGraph.\nLocal Coercion LGraph_SGraph: LGraph >-> SGraph.\nLocal Identity Coercion ULGraph_LGraph: LGraph >-> UnionFindGraph.LGraph.\nLocal Identity Coercion LGraph_LabeledGraph: UnionFindGraph.LGraph >-> LabeledGraph.\nLocal Identity Coercion SGraph_PointwiseGraph: SGraph >-> PointwiseGraph.\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nNotation vertices_at sh P g:= (@vertices_at _ _ _ _ _ _ (@SGP pSGG_VST nat unit (sSGG_VST sh)) _ P g).\nNotation whole_graph sh g := (vertices_at sh (vvalid g) g).\nNotation graph sh x g := (@reachable_vertices_at _ _ _ _ _ _ _ _ _ _ (@SGP pSGG_VST nat unit (sSGG_VST sh)) _ x g).\nNotation Graph := (@Graph pSGG_VST).\nExisting Instances maGraph finGraph liGraph RGF.\n\nDefinition find_spec :=\n DECLARE _find\n  WITH sh: wshare, g: Graph, x: pointer_val\n  PRE [ _x OF (tptr (Tstruct _Node noattr))]\n          PROP  (vvalid g x)\n          LOCAL (temp _x (pointer_val_val x))\n          SEP   (whole_graph sh g)\n  POST [ tptr (Tstruct _Node noattr) ]\n        EX g': Graph, EX rt : pointer_val,\n        PROP (uf_equiv g g' /\\ uf_root g' x rt)\n        LOCAL (temp ret_temp (pointer_val_val rt))\n        SEP (whole_graph sh g').\n\nDefinition Gprog : funspecs := ltac:(with_library prog [find_spec]).\n\nLemma false_Cne_eq: forall x y, typed_false tint (force_val (sem_cmp_pp Cne (pointer_val_val x) (pointer_val_val y))) -> x = y.\nProof.\n  intros. hnf in H. destruct x, y; inversion H; auto. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n  - destruct (Ptrofs.eq i i0) eqn:? .    \n    + pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. subst; auto.\n    + simpl in H. inversion H.\n  - simpl in H. inversion H.\nQed.\n\nLemma true_Cne_neq: forall x y, typed_true tint (force_val (sem_cmp_pp Cne (pointer_val_val x) (pointer_val_val y))) -> x <> y.\nProof.\n  intros. hnf in H. destruct x, y; inversion H; [|intro; inversion H0..]. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n  - destruct (Ptrofs.eq i i0) eqn:? .    \n    + simpl in H. inversion H.\n    + subst b0. pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. intro; apply H0. inversion H1. reflexivity.\n  - intro. inversion H0. auto.\nQed.\n\nLemma graph_local_facts: forall sh x (g: Graph), vvalid g x -> whole_graph sh g |-- valid_pointer (pointer_val_val x).\nProof.\n  intros. eapply derives_trans; [apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g (vvalid g) x (vgamma g x)); auto |].\n  simpl vertex_at at 1. unfold binode. entailer!.\nQed.\n\nLemma body_find: semax_body Vprog Gprog f_find find_spec.\nProof.\n  start_function.\n  remember (vgamma g x) as rpa eqn:?H. destruct rpa as [r pa]. symmetry in H0.\n  (* tmp = x *)\n  Opaque pointer_val_val. forward. Transparent pointer_val_val.\n  (* p = x -> parent; *)\n  localize [data_at sh node_type (vgamma2cdata (vgamma g x)) (pointer_val_val x)].\n  rewrite H0. simpl vgamma2cdata. forward. 1: entailer!; destruct pa; simpl; auto.\n  unlocalize [whole_graph sh g].\n  1: rewrite H0; simpl; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g (vvalid g) x (r, pa)); auto.\n  forward_while (EX p: pointer_val, EX ppa: pointer_val,\n                 PROP (reachable g x p /\\ vgamma g p = (vlabel g p, ppa))\n                 LOCAL (temp _p (pointer_val_val ppa); temp _tmp (pointer_val_val p); temp _x (pointer_val_val x))\n                 SEP (vertices_at sh (vvalid g) g)).\n  - Exists x pa. entailer!. split; [apply reachable_refl | f_equal; simpl in H0; inversion H0]; auto.\n  - entailer!. destruct H1. apply reachable_foot_valid in H1. pose proof (valid_parent _ _ _ _ H1 H5). apply denote_tc_test_eq_split; apply graph_local_facts; auto.\n  - destruct H1. apply true_Cne_neq in HRE.\n    Opaque pointer_val_val. forward. Transparent pointer_val_val. remember (vgamma g ppa) as rpa eqn:?H. destruct rpa as [mr mgpa]. symmetry in H3.\n    assert (H_VALID_PPA: vvalid g ppa) by (apply (valid_parent _ p (vlabel g p)); [apply reachable_foot_valid in H1 |]; auto).\n    localize [data_at sh node_type (vgamma2cdata (vgamma g ppa)) (pointer_val_val ppa)].\n    rewrite H3. simpl vgamma2cdata. forward. 1: entailer!; destruct mgpa; simpl; auto.\n    unlocalize [whole_graph sh g].\n    1: rewrite H3; simpl; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g (vvalid g) ppa (mr, mgpa)); auto.\n    Exists (ppa, mgpa). simpl fst. simpl snd. assert (mr = vlabel g ppa) by (simpl in H3; inversion H3; auto). rewrite <- H4. entailer !.\n    apply reachable_edge with p; auto. apply (vgamma_not_edge g p (vlabel g p)); auto. apply reachable_foot_valid in H1; auto.\n  - destruct H1. apply false_Cne_eq in HRE. subst ppa. assert (uf_root g x p) by (split; intros; auto; apply (parent_loop g p (vlabel g p) y); auto).\n    forward_while (EX g': Graph, EX tmp: pointer_val, EX xv: pointer_val,\n                   PROP (uf_equiv g g' /\\ uf_root g' xv p)\n                   LOCAL (temp _p (pointer_val_val p); temp _tmp (pointer_val_val tmp); temp _x (pointer_val_val xv))\n                   SEP (whole_graph sh g')).\n    + Exists g p x. entailer!. apply (uf_equiv_refl _  (liGraph g)).\n    + entailer!. apply denote_tc_test_eq_split; apply graph_local_facts.\n      * destruct H4 as [_ [? _]]. apply reachable_head_valid in H4; assumption.\n      * destruct H4 as [[? _] _]. rewrite <- H4. apply reachable_foot_valid in H1; assumption.\n    + destruct H4 as [? ?]. apply true_Cne_neq in HRE. remember (vgamma g' xv) as rpa eqn:?H. destruct rpa as [xr xpa]. symmetry in H6.\n      assert (H_VALID_XV: vvalid g' xv) by (destruct H5 as [? _]; apply reachable_head_valid in H5; auto).\n      localize [data_at sh node_type (vgamma2cdata (vgamma g' xv)) (pointer_val_val xv)].\n      rewrite H6. simpl vgamma2cdata. forward. 1: entailer!; destruct xpa; simpl; auto.\n      unlocalize [whole_graph sh g'].\n      1: rewrite H6; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g' (vvalid g') xv (xr, xpa)); auto.\n      assert (weak_valid g' p) by (right; destruct H4; rewrite <- H4; apply reachable_foot_valid in H1; auto).\n      assert (vvalid g' xv) by (destruct H5; apply reachable_head_valid in H5; auto).\n      assert (~ reachable g' p xv) by (intro; destruct H5 as [_ ?]; specialize (H5 _ H9); auto). \n      assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g' xv p H7 H8 H9)) (Graph_gen_redirect_parent g' xv p H7 H8 H9) =\n              vertices_at sh (vvalid g') (Graph_gen_redirect_parent g' xv p H7 H8 H9)). {\n        apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition. }\n      assert (H_P_NOT_NULL: p <> null) by (apply reachable_foot_valid in H1; intro; subst p; apply (valid_not_null g null H1); simpl; auto).\n      localize [data_at sh node_type (Vint (Int.repr (Z.of_nat xr)), pointer_val_val xpa) (pointer_val_val xv)].\n      forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g' xv p H7 H8 H9)].\n      1: rewrite H10; apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto.\n      Opaque pointer_val_val. forward. Transparent pointer_val_val.\n      Exists (((Graph_gen_redirect_parent g' xv p H7 H8 H9), xpa), xpa). simpl fst. simpl snd. rewrite H10. entailer !. split.\n      * apply (graph_gen_redirect_parent_equiv' g g' xv p); auto.\n      * apply (uf_root_gen_dst_preserve g' (liGraph g')); auto.\n        -- apply (vgamma_not_reachable _ _ xr); auto. pose proof (uf_root_not_eq_root_vgamma g' _ _ _ _ H6 H5 HRE). auto.\n        -- apply (vgamma_uf_root g' xv xr xpa p); auto.\n    + destruct H4. forward. Exists g' p. entailer!. rewrite <- (uf_equiv_root_the_same g g' x p); auto.\nQed.\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/sample_mark/verif_unionfind_iter.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.21661930045734948}}
{"text": "Require Import UpperBound_A UpperBound_B LowerBound.\nRequire Import CompilerC.\nRequire Import CoqlibC.\nRequire Import BehaviorsC LinkingC EventsC MapsC ASTC CtypesC.\n\n\nTheorem separate_compilation_correct\n        (srcs: list Csyntax.program) (tgts: list Asm.program) builtins src_link\n        (TYPECHECKS: Forall (fun src => CsemC.typechecked builtins src) srcs)\n        (TYPECHECKLINK: CsemC.typechecked builtins src_link)\n        (LINK: link_list srcs = Some src_link)\n        (MAIN: exists main_f,\n            (<<INTERNAL: (prog_defmap src_link) ! (src_link.(prog_main)) = Some (Gfun (Ctypes.Internal main_f))>>) /\\\n            (<<SIG: type_of_function main_f = Tfunction Ctypes.Tnil type_int32s cc_default>>))\n        (TR: Errors.mmap transf_c_program srcs = Errors.OK tgts):\n    (<<INITUB: program_behaves (Csem.semantics src_link) (Goes_wrong E0)>>) \\/\n    exists tgt_link, <<LINK: link_list tgts = Some tgt_link>> /\\\n                     <<IMPROVES: improves (Csem.semantics src_link) (Asm.semantics tgt_link)>>.\nProof.\n  hexploit upperbound_b_correct; eauto. { des. esplits; et. } intro A.\n  hexploit upperbound_a_correct; eauto. instantiate (1:= []). ss. intro B; des.\n  hexploit compiler_correct_full; eauto.\n  { do 2 instantiate (1:= []). ss. }\n  instantiate (1:= []). ss. rewrite ! app_nil_r. intro C; des.\n  hexploit (lower_bound_correct tgts); eauto. intro D. des.\n  { left.\n    hexploit back_propagate_ub_program; try apply C; et. intro CUB.\n    hexploit back_propagate_ub_program; try apply CUB; et. intro BUB.\n    hexploit back_propagate_ub_program; try apply BUB; et.\n  }\n  right. esplits; et. etrans; et. etrans; et. etrans; et.\nQed.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/driver/SepComp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.37022538564692037, "lm_q1q2_score": 0.21661930045734948}}
{"text": "(******************************************************************************)\n(** Generic Syntax                                                            *)\n(******************************************************************************)\n\nFrom Bits Require Import bits.\n\nFrom Coq Require Import ssreflect.\nFrom Coq Require Import List.\nImport ListNotations.\n\nFrom mathcomp Require Import eqtype tuple.\n\nFrom BIRD Require Import Bits Util.\n\nDeclare Scope bird_scope.\nDelimit Scope bird_scope with bird.\n\n(******************************************************************************)\n(*** Memory                                                                   *)\n(******************************************************************************)\n\nSection ADDRESS.\n\n  Local Open Scope bird.\n\n  Let _0 : qword := (#0, #0, #0, #0, #0, #0, #0, #0).\n  Let _1 : qword := (#0, #0, #0, #0, #0, #0, #0, #1).\n  Let _2 : qword := (#0, #0, #0, #0, #0, #0, #0, #2).\n  Let _4 : qword := (#0, #0, #0, #0, #0, #0, #0, #4).\n  Let _8 : qword := (#0, #0, #0, #0, #0, #0, #0, #8).\n\n  Variable (Cell : Type).\n\n  Variant scale := scale1 | scale2 | scale4 | scale8.\n\n  Definition qword_scale (v : qword) (s : scale) : qword :=\n    match s with\n    | scale1 => v\n    | scale2 => v + v\n    | scale4 => v + v + v + v\n    | scale8 => v + v + v + v + v + v + v\n    end.\n\n  Definition abs_addr := qword.\n\n  Record addr_expr := mk_addr_expr\n    { expr_base   : option Cell\n    ; expr_index  : option Cell\n    ; expr_scale  : scale\n    ; expr_offset : abs_addr\n    }.\n\n  Definition addr := (word_size * addr_expr)%type.\n\n  Definition addr_expr_eval (e : addr_expr) (f : Cell -> qword) : abs_addr :=\n    let b_val := if expr_base e is Some b_cell then f b_cell else _0 in\n    let i_val := if expr_index e is Some i_cell then f i_cell else _0 in\n    let d_val := expr_offset e in\n    b_val + (qword_scale i_val (expr_scale e)) + d_val.\n\n  Definition addr_word_type (a : addr) : Type :=\n    match fst a with\n    | BYTE  => byte\n    | WORD  => word\n    | DWORD => dword\n    | QWORD => qword\n    end.\n\nEnd ADDRESS.\n\nArguments addr_word_type {Cell}.\nArguments addr_expr_eval {Cell}.\n\n(******************************************************************************)\n(*** FLAGS                                                                    *)\n(******************************************************************************)\n\nSection FLAGS.\n\n  Variant flag := zero_flag | adjust_flag | carry_flag | parity_flag.\n\n  Definition flag_eq_dec (a b : flag) : {a = b} + {a <> b}. decide equality. Defined.\n  Definition flag_eqb (a b : flag) := if flag_eq_dec a b is left _ then true else false.\n\nEnd FLAGS.\n\n(******************************************************************************)\n(*** STATE PART                                                               *)\n(******************************************************************************)\n\nSection STATEPART.\n\n  Variable (Cell : Type).\n  Variable (Annot : Type).\n\n  Variant source :=\n    | src_imm  of qword\n    | src_addr of addr Cell\n    | src_expr of addr_expr Cell\n    | src_cell of Cell & Annot\n    | src_rip.\n\n  Variant destination :=\n    | dst_addr of addr Cell\n    | dst_cell of Cell & Annot.\n\nEnd STATEPART.\n\n(******************************************************************************)\n(*** PROGRAM GRAPH                                                            *)\n(******************************************************************************)\n\nSection GRAPH.\n\n  Variables (Cell Annot Label : Type).\n\n  Variant opcode_1_1  := op_mov  | op_inc | op_dec | op_neg | op_not.\n  Variant opcode_2_0  := op_cmp  | op_test.\n  Variant opcode_2_1  := op_add  | op_sub | op_xor | op_or  | op_and.\n  Variant opcode_2_2  := op_imul | op_xchg.\n  Variant opcode_cond := op_jz   | op_jnz | op_js  | op_jns | op_jg | op_jge | op_jl | op_jle.\n\n  Local Notation the_src  := (source Cell Annot).\n  Local Notation the_dst  := (destination Cell Annot).\n\n  Variant instruction (labels : list Label) :=\n    | instr_nop  of                                                            { l | In l labels }\n    | instr_hlt\n    | instr_1_1  of opcode_1_1  & the_dst           & the_src           &      { l | In l labels }\n    | instr_2_0  of opcode_2_0                      & the_src & the_src &      { l | In l labels }\n    | instr_2_1  of opcode_2_1  & the_dst           & the_src & the_src &      { l | In l labels }\n    | instr_2_2  of opcode_2_2  & the_dst & the_dst & the_src & the_src &      { l | In l labels }\n    | instr_push of                         Cell    & Cell    & the_src &      { l | In l labels }\n    | instr_pop  of               the_dst & Cell    & Cell              &      { l | In l labels }\n    | instr_jmp  of                                   the_src           & list { l | In l labels }\n    | instr_cjmp of opcode_cond                     & the_src           & list { l | In l labels } & { l | In l labels }\n    | instr_call of                         Cell    & Cell    & the_src & list { l | In l labels } & { l | In l labels }\n    | instr_ret  of                         Cell    & Cell    &           list { l | In l labels }\n  .\n\n  Definition instr_next {labels} (i : instruction labels) : list { l | In l labels } :=\n    match i with\n    | instr_nop            next        => [next]\n    | instr_hlt                        => []\n    | instr_1_1  _ _   _   next        => [next]\n    | instr_2_0  _ _ _     next        => [next]\n    | instr_2_1  _ _ _ _   next        => [next]\n    | instr_2_2  _ _ _ _ _ next        => [next]\n    | instr_push     _ _ _ next        => [next]\n    | instr_pop    _ _ _   next        => [next]\n    | instr_jmp        _   next        =>  next\n    | instr_cjmp _     _   target next =>  next::target\n    | instr_call   _ _ _   next ret    =>  ret::next\n    | instr_ret      _ _   next        =>  next\n    end.\n\n  Record phi_instruction :=\n    { phi_srcs : list Cell\n    ; phi_dst  : Cell\n    }.\n\n  Definition phi_block := list phi_instruction.\n\n  Definition code    (labels : list Label) := forall l, In l labels -> instruction labels.\n  Definition phicode (labels : list Label) := forall l, In l labels -> phi_block.\n\n  Record program :=\n    { prog_nodes   : list Label\n    ; prog_entry   : Label\n    ; prog_code    : code prog_nodes\n    ; prog_phicode : phicode prog_nodes\n    }.\n\n  Definition prog_nodes_instrs {p} (ns : list Label) (H : forall n, In n ns -> In n (prog_nodes p)) : list (instruction (prog_nodes p)).\n    destruct p as [nodes entry code phicode] ; simpl in *.\n    induction ns as [|hd tl rec].\n    - exact nil.\n    - apply cons.\n      + apply (code hd). apply H. now left.\n      + apply rec ; intros n Hn. apply H. now right.\n  Defined.\n\n  Definition prog_instrs p : list (instruction (prog_nodes p)) :=\n    prog_nodes_instrs (prog_nodes p) (fun _ H => H).\n\n  Record wf_phi (p : phi_block) : Prop :=\n    { wf_phi_n : exists n, forall i, In i p -> length (phi_srcs i) = n\n    }.\n\n  Record wf_prog (p : program) : Prop :=\n    { wf_prog_entry : In (prog_entry p) (prog_nodes p)\n    }.\n\n  Definition node (p : program) := { n | In n (prog_nodes p) }.\n\n  Definition prog_nodes_nodes {p} (ns : list Label) (H : forall n, In n ns -> In  n (prog_nodes p)) : list (node p).\n    unfold node.\n    destruct p as [nodes entry code phicode] ; simpl in *.\n    induction ns as [|hd tl rec].\n    - exact nil.\n    - apply cons.\n      + exists hd. apply H. now left.\n      + apply rec ; intros n Hn. apply H. now right.\n  Defined.\n\n  Definition prog_nodes' p : list (node p) :=\n    prog_nodes_nodes (prog_nodes p) (fun _ H => H).\n\n  Definition instr {p} (n : node p) : instruction (prog_nodes p) :=\n    prog_code p (proj1_sig n) (proj2_sig n).\n\n  Definition phi {p} (n : node p) : phi_block :=\n    prog_phicode p (proj1_sig n) (proj2_sig n).\n\n  Definition succs {p} (n : node p) : list (node p) :=\n    instr_next (prog_code p (proj1_sig n) (proj2_sig n)).\n\n  Definition is_pred {_ : EqDec Label} {p} (pred succ : node p) : bool :=\n    List.existsb (fun s => eqb (proj1_sig succ) (proj1_sig s)) (instr_next (instr pred)).\n\n  Definition preds {_ : EqDec Label} {p} (succ : node p) : list (node p) :=\n    List.filter (fun pred => is_pred pred succ) (prog_nodes' p).\n\n  Definition is_nth_predb {_ : EqDec Label} {p} (pred succ : node p) (n : nat) : bool :=\n    if List.nth_error (preds succ) n is Some pred' then eqb (proj1_sig pred) (proj1_sig pred') else false.\n\n  Definition is_nth_pred {_ : EqDec Label} {p} (pred succ : node p) (n : nat) : Prop :=\n    if is_nth_predb pred succ n then True else False.\n\nEnd GRAPH.\n", "meta": {"author": "proof-by-sledgehammer", "repo": "BIRD", "sha": "50ba5eee27301cee326f6c57bbd511cada2c80a8", "save_path": "github-repos/coq/proof-by-sledgehammer-BIRD", "path": "github-repos/coq/proof-by-sledgehammer-BIRD/BIRD-50ba5eee27301cee326f6c57bbd511cada2c80a8/GenericSyntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.2166192910347036}}
{"text": "(* \n This is the definition of formal syntax for Dan Grossman's Thesis, \n  \"SAFE PROGRAMMING AT THE C LEVEL OF ABSTRACTION\". \n  \n Term Preservation Proof\n\n*)\n\nSet Implicit Arguments.\nRequire Export Cyclone_Formal_Syntax Cyclone_Static_Semantics_Kinding_And_Context_Well_Formedness.\nRequire Export Cyclone_Dynamic_Semantics.\nRequire Export Cyclone_Classes Cyclone_Inductions Cyclone_LN_Tactics Cyclone_LN_Extra_Lemmas_And_Automation.\nRequire Export Cyclone_WFC_Lemmas.\nRequire Export Cyclone_WFU_Lemmas.\nRequire Export Cyclone_Context_Weakening_Proof.\nRequire Export Cyclone_Substitutions_Proof.\nRequire Export Cyclone_LN_Types_Lemmas.\nRequire Export Cyclone_Get_Lemmas.\nRequire Export Cyclone_Admit_Environment.\nClose Scope list_scope.\nImport LibEnvNotations.\nImport LVPE.LibVarPathEnvNotations.\n\n(* This has serious problems because dynamic semantics, D', is always in\nterms of statements but typing relations are in terms of St, E, ... *)\nFunction A_13_Term_Preservation_prop (In : Type) (H : TypJudgement In) \n         (u : Upsilon) (g : Gamma) (s : In) (t : Tau)\n         (st : typ' empty u g s t) := \n  forall u g h,\n    htyp u g h g ->\n    refp h u ->\n      forall h', (* s',\n         D' h s h' s' -> *)\n        exists g' u',\n          extends g g' ->\n          LVPE.extends u u' ->\n          htyp u' g' h' g' /\\\n          refp h' u' /\\\n          typ' empty u' g' s(*'*) t.\nHint Unfold A_13_Term_Preservation_prop.\nCheck A_13_Term_Preservation_prop.\n\nFunction PL (h : Heap) (s : St) (h' : Heap) (s' : St) (_ : L h s h' s') := \n  forall u g h,\n    htyp u g h g ->\n    refp h u ->\n    forall t, \n      ltyp empty u g s t ->\n    exists g' u',\n      extends g g' ->\n      LVPE.extends u u' ->\n      htyp u' g' h' g' /\\\n      refp h' u' /\\\n      ltyp empty u' g' s' t.\nHint Unfold PL.\n\nFunction PR (d : Delta) (u: Upsilon) (g : Gamma) (e: E) (t : Tau) (_ : rtyp d u g e t) := \n  forall u g h,\n    htyp u g h g ->\n    refp h u ->\n      forall h' e', \n        R h (e_s e) h' e' ->\n        exists g' u',\n          extends g g' ->\n          LVPE.extends u u' ->\n          htyp u' g' h' g' /\\\n          refp h' u' /\\\n          rtyp empty u' g' e t.\nHint Unfold PR.\n\nFunction PS (d : Delta) (u: Upsilon) (g : Gamma) (s: St) (t : Tau) (_ : styp d u g s t) := \n  forall u g h,\n    htyp u g h g ->\n    refp h u ->\n      forall h' s', \n        S h s h' s' ->\n        exists g' u',\n          extends g g' ->\n          LVPE.extends u u' ->\n          htyp u' g' h' g' /\\\n          refp h' u' /\\\n          styp empty u' g' s t.\nHint Unfold PS.\n\nLemma A_13_Term_Preservation_1:\n  forall (d : Delta) (u: Upsilon) (g : Gamma) (e: E) (t : Tau),\n    d = empty ->\n    forall (typ : ltyp d u g e t),\n      PL typ.\nProof.\n  introv DE.\n  unfold PL.\n  (* wrong! on S not ltyp! *)\n  apply (ltyp_ind_mutual PS PL PR); autounfold in *; intros; subst.\n  apply(SRL_ind_mutual\n          (fun (h : Heap) (s : St) (h' : Heap) (s' : St) (_ : S h s h' s') =>\n             f h s h' s')\n          (fun (h : Heap) (s : St) (h' : Heap) (s' : St) (_ : R h s h' s') =>\n             f h s h' s')\n          (fun (h : Heap) (s : St) (h' : Heap) (s' : St) (_ : L h s h' s') =>\n             f h s h' s')); intros.\n\n\n\nLemma A_13_Term_Preservation_2:\n  forall u g h,\n    htyp u g h g ->\n    refp h u ->\n    forall e t,\n      rtyp empty u g e t ->\n      forall h' e', \n        R h (e_s e) h' e' ->\n        exists g' u',\n          extends g g' ->\n          LVPE.extends u u' ->\n          htyp u' g' h' g' /\\\n          refp h' u' /\\\n          rtyp empty u' g' e t.\nAdmitted.\n\nLemma A_13_Term_Preservation_3:\n  forall u g h,\n    htyp u g h g ->\n    refp h u ->\n    forall e t,\n      styp empty u g e t ->\n      forall h' e', \n        S h e h' e' ->\n        exists g' u',\n          extends g g' ->\n          LVPE.extends u u' ->\n          htyp u' g' h' g' /\\\n          refp h' u' /\\\n          styp empty u' g' e t.\nAdmitted.              \n    ", "meta": {"author": "briangmilnes", "repo": "CycloneCoqSemantics", "sha": "190c0fc57d5aebfde244efb06a119f108de7a150", "save_path": "github-repos/coq/briangmilnes-CycloneCoqSemantics", "path": "github-repos/coq/briangmilnes-CycloneCoqSemantics/CycloneCoqSemantics-190c0fc57d5aebfde244efb06a119f108de7a150/4.5/Cyclone_Term_Preservation_Proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.21658693512831115}}
{"text": "Require Import DataTypes Useful Channel Cache Compatible L1 Coq.Logic.Classical\nCoq.Relations.Operators_Properties Coq.Relations.Relation_Operators List MsiState L1.\n(*Require List.*)\n\nModule Type LatestValueAxioms (dt: DataTypes) (ch: ChannelPerAddr dt).\n  Import dt ch.\n\n  Axiom toChild: forall {n a t p m}, defined n -> defined p ->\n                   parent n p -> \n                   mark mch p n a t m -> from m = MsiState.In -> dataM m = data p a t.\n  Axiom fromParent: forall {n a t p m}, defined n -> defined p ->\n                      parent n p -> \n                      recv mch p n a t m -> from m = MsiState.In -> data n a (S t) = dataM m.\n  Axiom toParent: forall {n a t c m}, defined n -> defined c ->\n                     parent c n ->\n                     mark mch c n a t m -> slt Sh (from m) -> dataM m = data c a t.\n  Axiom fromChild: forall {n a t c m}, defined n -> defined c ->\n                     parent c n ->\n                     recv mch c n a t m -> slt Sh (from m) -> data n a (S t) = dataM m.\n\n  Axiom initLatest: forall a, data hier a 0 = initData a /\\ state hier a 0 = Mo.\n\n  Axiom deqImpData: forall {a n t i}, defined n -> deqR a n i t ->\n                                    desc (reqFn a n i) = St ->\n                                    data n a (S t) = dataQ (reqFn a n i).\n\n  Axiom changeData:\n    forall {n a t}, defined n ->\n      data n a (S t) <> data n a t ->\n      (exists m, (exists p, defined p /\\ parent n p /\\ recv mch p n a t m /\\ from m = MsiState.In) \\/\n                 (exists c, defined c /\\ parent c n /\\ recv mch c n a t m /\\\n                            slt Sh (from m))) \\/\n      exists i, deqR a n i t /\\ desc (reqFn a n i) = St.\n\n\n  Axiom deqImpNoSend: forall {c a i t}, defined c -> deqR a c i t -> \n                                      forall {m p}, defined p ->\n                                                    ~ mark mch c p a t m.\nEnd LatestValueAxioms.\n\nModule LatestValueTheorems (dt: DataTypes) (ch: ChannelPerAddr dt) (c: BehaviorAxioms dt ch)\n       (l1: L1Axioms dt) (comp: CompatBehavior dt ch) (lv: LatestValueAxioms dt ch): L1Theorems dt l1.\n  Module mbt := mkBehaviorTheorems dt ch c.\n  Module cbt := mkCompat dt ch comp c.\n  Import dt ch c l1 comp lv mbt cbt.\n\n\n  Theorem uniqM:\n    forall {c a t}, defined c ->\n      leaf c ->\n      state c a t = Mo -> forall {co}, defined co -> leaf co -> c <> co -> state co a t = MsiState.In.\n  Proof.\n    intros c a t defC leaf_c cM co defCo leaf_co c_ne_co.\n    pose proof (noLeafsDesc leaf_c leaf_co c_ne_co) as desc1.\n    assert (co_ne_c: co <> c) by auto.\n    pose proof (noLeafsDesc leaf_co leaf_c co_ne_c) as desc2.\n    pose proof (@nonDescCompat c co defC defCo desc1 desc2 a t) as st.\n    rewrite cM in st.\n    unfold sle in *; destruct (state co a t); firstorder.\n  Qed.\n\n  Theorem parentLeafFalse: forall {c p}, leaf c -> parent p c -> False.\n  Proof.\n    intros c p leafC p_c.\n    unfold leaf in *; unfold parent in *.\n    destruct c.\n    destruct l0.\n    unfold List.In in *.\n    assumption.\n    assumption.\n  Qed.\n\n  Theorem leafGood: forall {p n a t}, defined p -> defined n -> parent n p ->\n                                      slt MsiState.In (dir p n a t) -> slt (state n a t) Mo ->\n                                      forall {c i}, \n                                        defined c ->\n                                        deqR a c i t -> desc (reqFn a c i) = St ->\n                                        False.\n  Proof.\n    unfold not; intros p n a t defP defN n_p pGtI nLtM c i defC deqSt isSt.\n    pose proof (deqLeaf deqSt) as leafC.\n    pose proof (processDeq deqSt) as st; simpl in st.\n    destruct (classic (descendent c p)) as [c_p | c_ne_p].\n    destruct (classic (descendent c n)) as [c_n | c_ne_n].\n    pose proof (@descSle c n defC defN c_n a t) as low.\n    rewrite isSt in st.\n    rewrite st in low.\n    apply (slt_slei_false nLtM low).\n    pose proof (clos_rt_rtn1 Tree parent c p c_p) as trans.\n    destruct trans.\n    apply (parentLeafFalse leafC n_p).\n    pose proof (clos_rtn1_rt Tree parent c y trans) as c_y.\n    pose proof (rt_step Tree parent y z H) as y_z.\n    pose proof (rt_trans Tree parent y z hier y_z defP) as defY.\n    clear trans y_z; fold descendent in *.\n    assert (y_ne_n: n = y -> False).\n    intros y_eq_n.\n    rewrite y_eq_n in *.\n    firstorder.\n    pose proof (compatible defP a t defY H) as [_ good].\n    specialize (good n defN y_ne_n n_p).\n    pose proof (@descSle c y defC defY c_y a t) as low.\n    rewrite isSt in st.\n    rewrite st in low.\n    pose proof (conservative defP defY H a t) as stuff.\n    unfold sle in *; destruct (dir z y a t); destruct (dir z n a t); \n    destruct (state y a t); auto.\n    assert (sec: ~ descendent p c).\n    unfold not; intros p_c.\n    pose proof (clos_rt_rtn1 Tree parent p c p_c) as trans.\n    destruct trans.\n    firstorder.\n    apply (parentLeafFalse leafC H).\n    pose proof (@nonDescCompat c p defC defP c_ne_p sec a t) as contra.\n    rewrite isSt in st.\n    rewrite st in contra.\n    pose proof (compatible defP a t defN n_p) as [good _].\n    destruct (dir p n a t); destruct (state p a t); unfold slt in *; unfold sle in *;\n    auto.\n  Qed.\n\n  Theorem leafGood2: forall {p n a t}, defined p -> defined n -> parent n p ->\n                                       forall {m}, mark mch p n a t m ->\n                                                   forall {c i}, \n                                                     defined c ->\n                                                     deqR a c i t -> desc (reqFn a c i) = St ->\n                                                     False.\n  Proof.\n    unfold not; intros p n a t defP defN n_p m markm c i defC deqSt isSt.\n    pose proof (pSendUpgrade defP defN n_p markm) as dir_n_lt_M.\n    pose proof (sendCCond defP defN n_p markm) as [st_hg othersCompat].\n    pose proof (sendmChange (dt defP defN n_p) markm) as rew.\n    rewrite <- rew in *; clear rew.\n    pose proof (deqLeaf deqSt) as leafC.\n    pose proof (processDeq deqSt) as st; simpl in st.\n    destruct (classic (descendent c p)) as [c_p | c_ne_p].\n    destruct (classic (descendent c n)) as [c_n | c_ne_n].\n    pose proof (@descSle c n defC defN c_n a t) as low.\n    pose proof (conservative defP defN n_p a t) as sth.\n    rewrite isSt in st.\n    rewrite st in *.\n    destruct (state n a t); destruct (dir p n a t); destruct (dir p n a (S t));\n    unfold sle in *; unfold slt in *; auto.\n    pose proof (clos_rt_rtn1 Tree parent c p c_p) as trans.\n    destruct trans.\n    apply (parentLeafFalse leafC n_p).\n    pose proof (clos_rtn1_rt Tree parent c y trans) as c_y.\n    pose proof (rt_step Tree parent y z H) as y_z.\n    pose proof (rt_trans Tree parent y z hier y_z defP) as defY.\n    clear trans y_z; fold descendent in *.\n    assert (y_ne_n: y = n -> False).\n    intros y_eq_n.\n    rewrite y_eq_n in *.\n    firstorder.\n    specialize (othersCompat y defY y_ne_n H).\n    pose proof (@descSle c y defC defY c_y a t) as low.\n    pose proof (conservative defP defY H a t) as stuff.\n    rewrite isSt in st.\n    rewrite st in *.\n    unfold sle in *; unfold slt in *; destruct (dir z n a (S t)); destruct (dir z n a t);\n    destruct (dir z y a t); destruct (state y a t); auto.\n    assert (sec: ~ descendent p c).\n    unfold not; intros p_c.\n    pose proof (clos_rt_rtn1 Tree parent p c p_c) as trans.\n    destruct trans.\n    firstorder.\n    apply (parentLeafFalse leafC H).\n    pose proof (@nonDescCompat c p defC defP c_ne_p sec a t) as contra.\n    rewrite isSt in st.\n    rewrite st in contra.\n    unfold sle in *; unfold slt in *; destruct (dir p n a t); destruct (dir p n a (S t));\n    destruct (state p a t); auto.\n  Qed.\n\n  Theorem leafGood3: forall {p n a t}, defined p -> defined n -> parent n p ->\n                                       forall {m}, mark mch n p a t m ->\n                                                   forall {c i}, \n                                                     defined c ->\n                                                     deqR a c i t -> desc (reqFn a c i) = St ->\n                                                     False.\n  Proof.\n    unfold not; intros p n a t defP defN n_p m markm c i defC deqSt isSt.\n    destruct (classic (c = n)) as [eq|notEq].\n    rewrite eq in *.\n    apply (deqImpNoSend defN deqSt defP markm).\n    destruct (classic (descendent c n)) as [c_n | c_no_n].\n    pose proof (@sendPCond n a t p defN defP n_p m markm) as dirLower.\n    pose proof (allDirLower defN dirLower notEq c_n) as condToM.\n    pose proof (cSendDowngrade defP defN n_p markm) as dgd.\n    pose proof (sendmChange (st defP defN n_p) markm) as stEq.\n    rewrite stEq in dgd.\n    pose proof (processDeq deqSt) as eqSth; simpl in *.\n    rewrite isSt in eqSth.\n    rewrite eqSth in *.\n    destruct (state n a t); destruct (to m); unfold slt in *; unfold sle in *; auto.\n    assert (n_no_c: ~ descendent n c).\n    unfold not; intros n_c.\n    pose proof (clos_rt_rtn1 Tree parent n c n_c) as trans.\n    destruct trans.\n    assert (n = n) by reflexivity; firstorder.\n    pose proof (deqLeaf deqSt) as leaf_z.\n    unfold parent in *; unfold leaf in *. destruct z. destruct l0.\n    unfold List.In in H. assumption.\n    assumption.\n    pose proof (@nonDescCompat n c defN defC n_no_c c_no_n a t) as stNow.\n    pose proof (cSendDowngrade defP defN n_p markm) as dgd.\n    pose proof (processDeq deqSt) as eqSth; simpl in *;\n    rewrite isSt in eqSth.\n    rewrite eqSth in *.\n    unfold sle in *; unfold slt in *; destruct (state n a t); destruct (state n a (S t));\n    auto.\n  Qed.\n\n  Theorem allLatestValue:\n    forall {a t n}, defined n ->\n                    sle Sh (state n a t) ->\n                    (forall {c}, defined c -> parent c n -> sle (dir n c a t) Sh) ->\n                    (data n a t = initData a /\\\n                     forall {ti}, 0 <= ti < t ->\n                                  forall {ci ii}, defined ci ->\n                                                  ~ (deqR a ci ii ti /\\\n                                                     desc (reqFn a ci ii) = St)) \\/\n    (exists cb ib tb, defined cb /\\ tb < t /\\ deqR a cb ib tb /\\ desc (reqFn a cb ib) = St /\\\n                      data n a t = dataQ (reqFn a cb ib) /\\\n                      forall {ti}, tb < ti < t ->\n                                   forall {ci ii},\n                                     defined ci ->\n                                     ~ (deqR a ci ii ti /\\\n                                        desc (reqFn a ci ii) = St)\n    ).\n    Proof.\n      intros a.\n      pose (fun t => forall n,\n              defined n ->\n                    sle Sh (state n a t) ->\n                    (forall {c}, defined c -> parent c n -> sle (dir n c a t) Sh) ->\n                    (data n a t = initData a /\\\n                     forall {ti}, 0 <= ti < t ->\n                                  forall {ci ii}, defined ci ->\n                                                  ~ (deqR a ci ii ti /\\\n                                                     desc (reqFn a ci ii) = St)) \\/\n    (exists cb ib tb, defined cb /\\ tb < t /\\ deqR a cb ib tb /\\ desc (reqFn a cb ib) = St /\\\n                      data n a t = dataQ (reqFn a cb ib) /\\\n                      forall {ti}, tb < ti < t ->\n                                   forall {ci ii},\n                                     defined ci ->\n                                     ~ (deqR a ci ii ti /\\\n                                        desc (reqFn a ci ii) = St)\n           )) as P.\n      pose proof (initLatest a) as [hierInit hierM].\n      apply (@ind P).\n      unfold P in *; clear P.\n      intros n defN stCond dirCond.\n      destruct (classic (n = hier)) as [eq|notEq].\n      rewrite eq.\n      rewrite hierInit.\n      constructor. constructor. reflexivity.\n      intros ti [_ bad].\n      assert (f: False) by omega.\n      firstorder.\n      pose proof (rt_refl Tree parent hier) as defHier.\n      pose proof (@initCompat hier) as dir0.\n      pose proof (clos_rt_rtn1 Tree parent n hier defN) as trans.\n      pose proof @conservative as cons.\n      pose proof @descSle as descSle.\n      unfold defined in *.\n      destruct trans.\n      firstorder.\n      pose proof (clos_rtn1_rt Tree parent n y trans) as n_y.\n      pose proof (rt_step Tree parent y z H) as defY.\n      clear dirCond trans; fold descendent in *.\n      specialize (dir0 y defHier defY H a).\n      pose proof (cons z y defHier defY H a 0) as sleUse.\n      pose proof @descSle n y defN defY n_y a 0 as contra.\n      rewrite dir0 in sleUse.\n      unfold sle in *; destruct (state n a 0); destruct (state y a 0); firstorder.\n\n      unfold P in *; clear P.\n      intros t SIHt n defN condSt condDir.\n\n      destruct (classic (sle Sh (state n a t) /\\\n                         forall c, defined c -> parent c n -> sle (dir n c a t) Sh))\n               as [[condSt' condDir']|prevNotLatest].\n\n      assert (triv: t <= t) by omega.\n      specialize (SIHt t triv n defN condSt' condDir'); clear triv.\n\n\n      assert (noneElse: forall co, defined co -> leaf co -> co <> n -> sle (state co a t) Sh).\n      intros co defCo leafco co_ne_n.\n      destruct (classic (descendent co n)) as [desc|noDesc].\n      apply (allDirLower defN condDir' co_ne_n desc).\n\n\n      assert (not_n_co: ~ descendent n co).\n      unfold not; intros n_co.\n      assert (no_co_parent: forall p, ~ parent p co) by\n          (unfold not; intros p p_co; unfold leaf in *; unfold parent in *;\n                                      unfold List.In in *; destruct co; destruct l0; auto).\n      pose proof (clos_rt_rtn1 Tree parent n co n_co) as trans.\n      destruct trans.\n      assert (n = n) by reflexivity; firstorder.\n      firstorder.\n\n      pose proof (@nonDescCompat n co defN defCo not_n_co noDesc a t) as condState.\n      destruct (state n a t); unfold sle in *; destruct (state co a t); auto.\n\n\n\n      assert (noStore: forall co, defined co ->\n                                  co <> n -> forall i,\n                                               ~ (deqR a co i t /\\\n                                                  desc (reqFn a co i) = St\n             )).\n      unfold not; intros co defCo co_ne_n i [deqSt isSt].\n      pose proof (deqLeaf deqSt) as leafCo.\n      specialize (noneElse co defCo leafCo co_ne_n).\n      pose proof (processDeq deqSt) as use; simpl in use.\n      rewrite isSt in use.\n      rewrite use in noneElse; unfold sle in *; auto.\n\n\n      destruct (classic (exists i, deqR a n i t /\\ \n               desc (reqFn a n i) = St)) as [[i [deqSt isSt]] | noNStore].\n\n      pose proof (deqImpData defN deqSt) as st.\n      rewrite isSt in st.\n      rewrite st.\n      assert (triv: t < S t) by omega.\n      assert (triv2: forall ti, t < ti < S t -> False) by (intros ti cond; omega).\n      right.\n      exists n; exists i; exists t.\n      generalize defN triv deqSt isSt st triv2; clear; firstorder.\n      reflexivity.\n\n\n      assert (good: forall c i, defined c ->\n                                ~ (deqR a c i t /\\ \n                                   desc (reqFn a c i) = St)).\n      unfold not. intros c i defC [deqc isSt].\n      destruct (classic (c = n)) as [eq|notEq].\n      rewrite eq in *; generalize noNStore deqc isSt; clear; firstorder.\n      generalize noStore defC notEq deqc isSt; clear; firstorder.\n\n\n      destruct (classic (data n a (S t) = data n a t)) as [dataEq| dataNeq].\n      rewrite dataEq.\n\n      destruct SIHt as [[initi condInit]|[resti condResti]].\n      left.\n      constructor. assumption.\n      intros ti cond.\n      assert (cases: 0 <= ti < t \\/ ti = t) by omega.\n      destruct cases as [ind|rew].\n      specialize (condInit ti ind).\n      assumption.\n      rewrite rew.\n      assumption.\n\n      destruct condResti as [ib [tb [defCb [tb_lt_t [deqSt [isSt [dEq rest]]]]]]].\n      right.\n      exists resti; exists ib; exists tb.\n      constructor. assumption.\n      constructor.\n      omega.\n      constructor.\n      assumption.\n      constructor.\n      assumption.\n      constructor.\n      assumption.\n      intros ti cond.\n      assert (cases: tb < ti < t \\/ ti = t) by omega.\n      destruct cases as [ind|rew].\n      \n      apply (rest ti ind).\n      rewrite rew.\n      assumption.\n\n\n      pose proof (changeData defN dataNeq) as someChange.\n      destruct someChange as [[m [[p [defP [n_p [recvm mIn]]]] |\n                                  [c [defC [c_n [recvm mNotIn]]]]]] | bad].\n\n\n      pose proof (cRecvmCond defP defN n_p recvm) as currSt.\n      rewrite <- currSt in condSt'; rewrite mIn in condSt'.\n      unfold sle in condSt'; firstorder.\n\n      pose proof (recvmCond defN defC c_n recvm) as currSt.\n      specialize (condDir' c defC c_n).\n      rewrite currSt in mNotIn.\n      pose proof (slt_slei_false mNotIn condDir') as f.\n      firstorder.\n\n      generalize noNStore bad; clear; firstorder.\n\n      destruct (classic (state n a t = MsiState.In \\/ exists c, defined c /\\ parent c n /\\\n                                                       slt Sh (dir n c a t)))\n               as [hard | easy].\n      clear prevNotLatest.\n\n      destruct hard as [stIn | [c [defC [c_n dirM]]]].\n\n      assert (lt: slt (state n a t) (state n a (S t))) by\n          (rewrite stIn; unfold sle in *; unfold slt in *; destruct (state n a (S t));\n           auto).\n      assert (chnge: state n a (S t) <> state n a t) by\n          (destruct (state n a (S t)); destruct (state n a t); unfold slt in *;\n                                                               unfold sle in *;\n                                                               auto; discriminate).\n      destruct (classic (exists p, defined p /\\ parent n p)) as [[p [defP n_p]] | noP].\n      pose proof (change (st defP defN n_p) chnge) as [[m markm] | [m recvm]].\n      pose proof (cSendDowngrade defP defN n_p markm) as contra.\n      pose proof (slt_slti_false lt contra) as f.\n      firstorder.\n\n\n\n\n\n\n\n\n\n\n      pose proof (recvImpMark recvm) as [ts [ts_le_t markm]].\n      pose proof (@pSendNonI p n defP defN n_p m ts t a markm recvm) as pHigh.\n      pose proof (@cRecvNonM p n defP defN n_p m ts t a markm recvm) as cLow.\n      assert (cLow1: forall t0, ts < t0 <= t -> slt (state n a t0) Mo) by\n          ( intros t0 cond; assert (H: ts <= t0 <= t) by omega; apply (cLow t0 H)).\n      assert (cLow2: slt (state n a ts) Mo) by (assert (H: ts <= ts <= t) by omega;\n                                                apply (cLow ts H)).\n\n      assert (noDeq1: forall t0, ts < t0 <= t ->\n                                 forall c i, defined c -> ~ (deqR a c i t0\n                                                            /\\ \n                                                            desc (reqFn a c i) = St)).\n      intros t0 cond.\n      specialize (pHigh t0 cond).\n      specialize (cLow1 t0 cond).\n      pose proof (@leafGood p n a t0 defP defN n_p pHigh cLow1) as H.\n      generalize H; clear; firstorder.\n\n      pose proof (@leafGood2 p n a ts defP defN n_p m markm) as noDeq2.\n\n      assert (goodT: forall t0, ts <= t0 <= t ->\n                                forall c i, defined c -> ~ (deqR a c i t0 /\\\n                                                            desc (reqFn a c i) = St)).\n      intros t0 cond.\n      assert (H: ts < t0 <= t \\/ t0 = ts) by omega.\n      destruct H as [c1|c2].\n      apply (noDeq1 t0 c1).\n      rewrite c2 in *.\n      generalize noDeq2; clear; firstorder.\n\n\n      pose proof (cRecvmCond defP defN n_p recvm) as stEq.\n      rewrite <- stEq in stIn.\n      pose proof (fromParent defN defP n_p recvm stIn) as dataEq.\n      pose proof (toChild defN defP n_p markm stIn) as dataEq2.\n      rewrite <- dataEq in dataEq2.\n      rewrite dataEq2.\n\n      pose proof (sendCCond defP defN n_p markm) as [one two].\n      pose proof (pSendUpgrade defP defN n_p markm) as upg.\n      pose proof (sendmChange (dt defP defN n_p) markm) as ch.\n      rewrite ch in upg.\n      assert (p1: sle Sh (state p a ts)) by\n          ( unfold sle in *; unfold slt in *; destruct (to m); destruct (state p a ts);\n            destruct (dir p n a ts); auto).\n      assert (p2: forall c', defined c' -> parent c' p ->\n                         sle (dir p c' a ts) Sh).\n      intros c' defC' c'_p.\n\n\n      destruct (classic (c' = n)) as [eq|not].\n      pose proof (cRecvRespPrevState defP defN n_p recvm markm) as stDir.\n      rewrite <- stEq in stDir.\n      rewrite stIn in stDir.\n      rewrite eq.\n      rewrite <- stDir.\n      unfold sle; auto.\n\n      specialize (two c' defC' not c'_p).\n      unfold sle in *; unfold slt in *; destruct (to m); destruct (dir p n a ts);\n      destruct (dir p c' a ts); auto.\n\n      specialize (SIHt ts ts_le_t p defP p1 p2).\n      destruct (SIHt) as [[initi condInit] | [resti condRest]].\n      left.\n      constructor. assumption. \n\n      intros ti cond; assert (H: 0 <= ti < ts \\/ ts <= ti <= t ) by omega; \n      destruct H as [ind|tough].\n\n      apply (condInit ti ind).\n      apply (goodT ti tough).\n\n\n      right.\n      destruct condRest as [ib [tb [defCb [tb_lt_ts [deqSt [isSt [dtEq rest]]]]]]].\n      exists resti; exists ib; exists tb.\n      constructor. assumption. constructor.\n      assert (tb < S t) by omega. assumption.\n      constructor. assumption.\n      constructor. assumption.\n      constructor. assumption.\n      intros ti cond; assert (H: tb < ti < ts \\/ ts <= ti <= t) by omega;\n      destruct H as [ind|tough].\n      apply (rest ti ind).\n      apply (goodT ti tough).\n\n\n\n\n\n\n\n\n\n      assert (contra: forall p, defined p -> ~ parent n p) by firstorder.\n      specialize (@noParentSame n a t defN contra).\n      firstorder.\n\n\n      specialize (condDir c defC c_n).\n\n      assert (gt: slt (dir n c a (S t)) (dir n c a t)) by\n          (unfold slt in *; unfold sle in *; destruct (dir n c a (S t));\n           destruct (dir n c a t); auto; discriminate).\n      assert (chnge: dir n c a (S t) <> dir n c a t) by\n          (destruct (dir n c a (S t)); destruct (dir n c a t); unfold slt in *;\n                                                               unfold sle in *;\n                                                               auto; discriminate).\n\n      pose proof (change (dt defN defC c_n) chnge) as [[m markm] | [m recvm]].\n      pose proof (pSendUpgrade defN defC c_n markm) as contra.\n      pose proof (slt_slti_false gt contra) as f.\n      firstorder.\n\n\n      pose proof (recvImpMark recvm) as [ts [ts_le_t markm]].\n      pose proof (@pRecvNonI n c defN defC c_n m ts t a markm recvm) as pHigh.\n      pose proof (@cSendNonM n c defN defC c_n m ts t a markm recvm) as cLow.\n      assert (pHigh1: forall t0, ts < t0 <= t -> slt MsiState.In (dir n c a t0)) by\n          ( intros t0 cond; assert (H: ts <= t0 <= t) by omega; apply (pHigh t0 H)).\n      assert (pHigh2: slt MsiState.In (dir n c a ts)) by (assert (H: ts <= ts <= t) by omega;\n                                                apply (pHigh ts H)).\n\n      assert (noDeq1: forall t0, ts < t0 <= t ->\n                                 forall c i, defined c -> ~ (deqR a c i t0 /\\\n                                                             desc (reqFn a c i) = St)).\n      intros t0 cond.\n      specialize (cLow t0 cond).\n      specialize (pHigh1 t0 cond).\n      pose proof (@leafGood n c a t0 defN defC c_n pHigh1 cLow) as H.\n      generalize H; clear; firstorder.\n\n\n      pose proof (@leafGood3 n c a ts defN defC c_n m markm) as noDeq2.\n\n      assert (goodT: forall t0, ts <= t0 <= t ->\n                                forall c i, defined c -> ~ (deqR a c i t0 /\\\n                                                            desc (reqFn a c i) = St)).\n      intros t0 cond.\n      assert (H: ts < t0 <= t \\/ t0 = ts) by omega.\n      destruct H as [c1|c2].\n      apply (noDeq1 t0 c1).\n      rewrite c2 in *.\n      generalize noDeq2; clear; firstorder.\n\n\n\n\n      pose proof (recvmCond defN defC c_n recvm) as stEq.\n      rewrite <- stEq in dirM.\n      pose proof (fromChild defN defC c_n recvm dirM) as dataEq.\n      pose proof (toParent defN defC c_n markm dirM) as dataEq2.\n      rewrite <- dataEq in dataEq2.\n      rewrite dataEq2.\n\n      pose proof (@sendPCond c a ts n defC defN c_n m markm) as sth.\n      pose proof (recvmChange (dt defN defC c_n) recvm) as ch.\n      rewrite ch in condDir.\n      pose proof (cSendDowngrade defN defC c_n markm) as dwn.\n\n\n      assert (p2: forall c0, defined c0 -> parent c0 c -> sle (dir c c0 a ts) Sh).\n      intros c0 defC0 c0_c; specialize (sth c0 defC0 c0_c);\n      destruct (to m); destruct (dir c c0 a ts); unfold sle in *; unfold slt in *;\n      auto.\n\n      assert (p1: sle Sh (state c a ts)) by\n          ( unfold sle in *; unfold slt in *; destruct (state c a (S ts));\n            destruct (state c a ts); auto).\n\n      specialize (SIHt ts ts_le_t c defC p1 p2).\n\n\n      destruct SIHt as [[initi condInit] | [resti condRest]].\n      left.\n      constructor. assumption.\n      intros ti cond; assert (H: 0 <= ti < ts \\/ ts <= ti <= t ) by omega; \n      destruct H as [ind|tough].\n\n      apply (condInit ti ind).\n      apply (goodT ti tough).\n\n      right.\n      destruct condRest as [ib [tb [defCb [tb_lt_ts [deqSt [isSt [dtEq rest]]]]]]].\n      exists resti; exists ib; exists tb.\n      constructor. assumption. constructor.\n      assert (tb < S t) by omega. assumption.\n      constructor. assumption.\n      constructor. assumption.\n      constructor. assumption.\n      intros ti cond; assert (H: tb < ti < ts \\/ ts <= ti <= t) by omega;\n     destruct H as [ind|tough].\n      apply (rest ti ind).\n      apply (goodT ti tough).\n\n\n\n\n\n      assert (ex: forall c, defined c -> parent c n -> ~ slt Sh (dir n c a t)) by\n          firstorder.\n      assert (ex': forall c, defined c -> parent c n -> sle (dir n c a t) Sh) by\n          ( intros c defC c_n; unfold sle in *; specialize (ex c defC c_n);\n            unfold slt in *; destruct (dir n c a t); auto).\n      assert (ex2: state n a t <> MsiState.In) by firstorder.\n      assert (ex2': sle Sh (state n a t)) by (destruct (state n a t); unfold sle in *;\n                                                                      auto).\n      firstorder.\n\n    Qed.\n\n  Theorem latestValue:\n  forall {c a t},\n    defined c ->\n    leaf c ->\n    sle Sh (state c a t) ->\n    (data c a t = initData a /\\\n     forall {ti}, 0 <= ti < t -> forall {ci ii},\n                                   defined ci ->\n                                   ~ (deqR a ci ii ti /\\\n                                      desc (reqFn a ci ii) = St)) \\/\n    (exists cb ib tb, defined cb /\\ tb < t /\\ deqR a cb ib tb /\\ desc (reqFn a cb ib) = St /\\\n                      data c a t = dataQ (reqFn a cb ib) /\\\n                      forall {ti}, tb < ti < t ->\n                                   forall {ci ii},\n                                     defined ci ->\n                                     ~ (deqR a ci ii ti /\\\n                                        desc (reqFn a ci ii) = St)\n    ).\n  Proof.\n    intros c a t cDef leafC more.\n    assert (cond: forall {c'}, defined c' -> parent c' c -> sle (dir c c' a t) Sh).\n    intros c' defC' c'_c; unfold leaf in *; unfold parent in *.\n    destruct c.\n    destruct l0.\n    unfold List.In in *.\n    firstorder.\n    firstorder.\n    pose proof (allLatestValue cDef more cond) as useful.\n    assumption.\n  Qed.\n\n  Definition deqOrNot := l1.deqOrNot.\nEnd LatestValueTheorems.\n", "meta": {"author": "vmurali", "repo": "CacheProofBetter", "sha": "e00bb4a4f1677c69969797c25ab9ef4bb8a213a0", "save_path": "github-repos/coq/vmurali-CacheProofBetter", "path": "github-repos/coq/vmurali-CacheProofBetter/CacheProofBetter-e00bb4a4f1677c69969797c25ab9ef4bb8a213a0/LatestValue.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.21658692962467552}}
{"text": "Require Import Relations.\nRequire Import NArith.\nRequire Import PArith.\nRequire Import ZArith.\nRequire Import Lia.\nRequire Import FMapPositive.\nRequire Import FSetPositive.\nRequire Import EquivDec.\nRequire Import sflib.\nRequire Import PacoNotation.\nRequire Import HahnRelationsBasic.\nRequire Import HahnSets.\n\nRequire Import PromisingArch.lib.Basic.\nRequire Import PromisingArch.lib.HahnRelationsMore.\nRequire Import PromisingArch.lib.Order.\nRequire Import PromisingArch.lib.Time.\nRequire Import PromisingArch.lib.Lang.\n\nSet Implicit Arguments.\n\nCreate HintDb tso discriminated.\n\nModule Label.\n  Inductive t :=\n  | read (loc:Loc.t) (val:Val.t)\n  | write (loc:Loc.t) (val:Val.t)\n  | update (loc:Loc.t) (vold vnew:Val.t)\n  | barrier (b:Barrier.t)\n  | flush (loc:Loc.t)\n  | flushopt (loc:Loc.t)\n  .\n  Hint Constructors t : tso.\n\n  Definition is_read (label:t): bool :=\n    match label with\n    | read _ _ => true\n    | _ => false\n    end.\n\n  Definition is_reading (loc:Loc.t) (label:t): bool :=\n    match label with\n    | read loc' _ => loc' == loc\n    | _ => false\n    end.\n\n  Definition is_reading_val (loc:Loc.t) (val:Val.t) (label:t): bool :=\n    match label with\n    | read loc' val' => (loc' == loc) && (val' == val)\n    | _ => false\n    end.\n\n  Definition is_write (label:t): bool :=\n    match label with\n    | write _ _ => true\n    | _ => false\n    end.\n\n  Definition is_writing_cl (loc:Loc.t) (label:t): bool :=\n    match label with\n    | write loc' _ => Loc.cl loc loc'\n    | _ => false\n    end.\n\n  Definition is_update (label:t): bool :=\n    match label with\n    | update _ _ _ => true\n    | _ => false\n    end.\n\n  Definition is_flush (label:t): bool :=\n    match label with\n    | flush _ => true\n    | _ => false\n    end.\n\n  Definition is_flushing (loc:Loc.t) (label:t): bool :=\n    match label with\n    | flush loc' => loc' == loc\n    | _ => false\n    end.\n\n  Definition is_flushing_cl (loc:Loc.t) (label:t): bool :=\n    match label with\n    | flush loc' => Loc.cl loc loc'\n    | _ => false\n    end.\n\n  Definition is_flushopt (label:t): bool :=\n    match label with\n    | flushopt _ => true\n    | _ => false\n    end.\n\n  Definition is_flushopting (loc:Loc.t) (label:t): bool :=\n    match label with\n    | flushopt loc' => loc' == loc\n    | _ => false\n    end.\n\n  Definition is_flushopting_cl (loc:Loc.t) (label:t): bool :=\n    match label with\n    | flushopt loc' => Loc.cl loc loc'\n    | _ => false\n    end.\n\n  Definition is_kinda_read (label:t): bool :=\n    match label with\n    | read _ _ => true\n    | update _ _ _ => true\n    | _ => false\n    end.\n\n  Definition is_kinda_reading (loc:Loc.t) (label:t): bool :=\n    match label with\n    | read loc' _ => loc' == loc\n    | update loc' _ _ => loc' == loc\n    | _ => false\n    end.\n\n  Definition is_kinda_reading_val (loc:Loc.t) (val:Val.t) (label:t): bool :=\n    match label with\n    | read loc' val' => (loc' == loc) && (val' == val)\n    | update loc' val' _ => (loc' == loc) && (val' == val)\n    | _ => false\n    end.\n\n  Definition is_kinda_write (label:t): bool :=\n    match label with\n    | write _ _ => true\n    | update _ _ _ => true\n    | _ => false\n    end.\n\n  Definition is_kinda_writing (loc:Loc.t) (label:t): bool :=\n    match label with\n    | write loc' _ => loc' == loc\n    | update loc' _ _ => loc' == loc\n    | _ => false\n    end.\n\n  Definition is_kinda_writing_val (loc:Loc.t) (val:Val.t) (label:t): bool :=\n    match label with\n    | write loc' val' => (loc' == loc) && (val' == val)\n    | update loc' _ val' => (loc' == loc) && (val' == val)\n    | _ => false\n    end.\n\n  Definition is_kinda_writing_cl (loc:Loc.t) (label:t): bool :=\n    match label with\n    | write loc' _ => Loc.cl loc loc'\n    | update loc' _ _ => Loc.cl loc loc'\n    | _ => false\n    end.\n\n  Definition is_access (label:t): bool :=\n    match label with\n    | read _ _ => true\n    | write _ _ => true\n    | update _ _ _ => true\n    | _ => false\n    end.\n\n  Definition is_accessing (loc:Loc.t) (label:t): bool :=\n    match label with\n    | read loc' _ => loc' == loc\n    | write loc' _ => loc' == loc\n    | update loc' _ _ => loc' == loc\n    | _ => false\n    end.\n\n  Definition is_accessing_cl (loc:Loc.t) (label:t): bool :=\n    match label with\n    | read loc' _ => Loc.cl loc loc'\n    | write loc' _ => Loc.cl loc loc'\n    | update loc' _ _ => Loc.cl loc loc'\n    | _ => false\n    end.\n\n  Definition is_barrier (label:t): bool :=\n    match label with\n    | barrier b => true\n    | _ => false\n    end.\n\n  Definition is_barrier_c (c:Barrier.t -> bool) (label:t): bool :=\n    match label with\n    | barrier b => c b\n    | _ => false\n    end.\n\n  Definition is_kinda_write_flush (label:t): bool :=\n    match label with\n    | write _ _ => true\n    | update _ _ _ => true\n    | flush _ => true\n    | _ => false\n    end.\n\n  Definition is_persist (label:t): bool :=\n    match label with\n    | flush _ => true\n    | flushopt _ => true\n    | _ => false\n    end.\n\n  Definition is_persisting (loc:Loc.t) (label:t): bool :=\n    match label with\n    | flush loc' => loc' == loc\n    | flushopt loc' => loc' == loc\n    | _ => false\n    end.\n\n  Definition is_persisting_cl (loc:Loc.t) (label:t): bool :=\n    match label with\n    | flush loc' => Loc.cl loc loc'\n    | flushopt loc' => Loc.cl loc loc'\n    | _ => false\n    end.\n\n  Definition is_access_persist (label:t): bool :=\n    match label with\n    | read _ _ => true\n    | write _ _ => true\n    | update _ _ _ => true\n    | flush _ => true\n    | flushopt _ => true\n    | _ => false\n    end.\n\n  Definition is_access_persisting (loc:Loc.t) (label:t): bool :=\n    match label with\n    | read loc' _ => loc' == loc\n    | write loc' _ => loc' == loc\n    | update loc' _ _ => loc' == loc\n    | flush loc' => loc' == loc\n    | flushopt loc' => loc' == loc\n    | _ => false\n    end.\n\n  Definition is_kinda_write_persist (label:t): bool :=\n    match label with\n    | write _ _ => true\n    | update _ _ _ => true\n    | flush _ => true\n    | flushopt _ => true\n    | _ => false\n    end.\n\n  Definition is_persist_barrier (label:t): bool :=\n    match label with\n    | update _ _ _ => true\n    | barrier b => orb (Barrier.is_mfence b) (Barrier.is_sfence b)\n    | _ => false\n    end.\n\n  Lemma kinda_reading_is_kinda_read\n        loc l\n        (RD: is_kinda_reading loc l):\n    is_kinda_read l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma kinda_reading_is_accessing\n        loc l\n        (RD: is_kinda_reading loc l):\n    is_accessing loc l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma read_is_kinda_reading loc val:\n    is_kinda_reading loc (read loc val).\n  Proof.\n    s. destruct (equiv_dec loc loc); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma read_is_reading_val loc val:\n    is_reading_val loc val (read loc val).\n  Proof.\n    s. destruct (equiv_dec loc loc); destruct (equiv_dec val val); ss; exfalso.\n    all: apply c; ss.\n  Qed.\n\n  Lemma read_is_kinda_reading_val loc val:\n    is_kinda_reading_val loc val (read loc val).\n  Proof.\n    s. destruct (equiv_dec loc loc); destruct (equiv_dec val val); ss; exfalso.\n    all: apply c; ss.\n  Qed.\n\n  Lemma kinda_read_exists_loc_val\n        l\n        (RD: is_kinda_read l):\n    exists loc val,\n      is_kinda_reading_val loc val l.\n  Proof.\n    destruct l; ss.\n    - exists loc. exists val.\n      destruct (equiv_dec loc loc); destruct (equiv_dec val val); ss; try by exfalso; apply c; ss.\n    - exists loc. exists vold.\n      destruct (equiv_dec loc loc); destruct (equiv_dec vold vold); ss; try by exfalso; apply c; ss.\n  Qed.\n\n  Lemma kinda_reading_exists_val\n        loc l\n        (RDING: is_kinda_reading loc l):\n    exists val,\n      is_kinda_reading_val loc val l.\n  Proof.\n    destruct l; ss; destruct (equiv_dec loc0 loc); ss.\n    - eexists val. destruct (equiv_dec val val); ss. exfalso. apply c. ss.\n    - eexists vold. destruct (equiv_dec vold vold); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma reading_val_is_reading\n        loc val l\n        (RDING: is_reading_val loc val l):\n    is_reading loc l.\n  Proof.\n    destruct l; ss; destruct (equiv_dec loc0 loc); ss.\n  Qed.\n\n  Lemma reading_is_read\n        loc l\n        (RDING: is_reading loc l):\n    is_read l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma kinda_reading_val_is_kinda_reading\n        loc val l\n        (RDING: is_kinda_reading_val loc val l):\n    is_kinda_reading loc l.\n  Proof.\n    destruct l; ss; destruct (equiv_dec loc0 loc); ss.\n  Qed.\n\n  Lemma kinda_writing_is_kinda_write\n        loc l\n        (WR: is_kinda_writing loc l):\n    is_kinda_write l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma read_is_kinda_read\n        l\n        (RD: is_read l):\n    is_kinda_read l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma kinda_read_is_access\n        l\n        (WR: is_kinda_read l):\n    is_access l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma write_is_kinda_write\n        l\n        (WR: is_write l):\n    is_kinda_write l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma writing_cl_is_write\n        loc l\n        (LABEL: is_writing_cl loc l):\n    is_write l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma kinda_write_is_access\n        l\n        (WR: is_kinda_write l):\n    is_access l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma kinda_writing_is_accessing\n        loc l\n        (WR: is_kinda_writing loc l):\n    is_accessing loc l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma write_is_kinda_writing loc val:\n    is_kinda_writing loc (write loc val).\n  Proof.\n    s. destruct (equiv_dec loc loc); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma write_is_kinda_writing_val loc val:\n    is_kinda_writing_val loc val (write loc val).\n  Proof.\n    s. destruct (equiv_dec loc loc); destruct (equiv_dec val val); ss; exfalso.\n    all: apply c; ss.\n  Qed.\n\n  Lemma kinda_write_exists_loc_val\n        l\n        (WR: is_kinda_write l):\n    exists loc val,\n      is_kinda_writing_val loc val l.\n  Proof.\n    destruct l; ss.\n    - exists loc. exists val.\n      destruct (equiv_dec loc loc); destruct (equiv_dec val val); ss; try by exfalso; apply c; ss.\n    - exists loc. exists vnew.\n      destruct (equiv_dec loc loc); destruct (equiv_dec vnew vnew); ss; try by exfalso; apply c; ss.\n  Qed.\n\n  Lemma kinda_writing_exists_val\n        loc l\n        (WRING: is_kinda_writing loc l):\n    exists val,\n      is_kinda_writing_val loc val l.\n  Proof.\n    destruct l; ss; destruct (equiv_dec loc0 loc); ss.\n    - eexists val. destruct (equiv_dec val val); ss. exfalso. apply c. ss.\n    - eexists vnew. destruct (equiv_dec vnew vnew); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma kinda_writing_val_is_kinda_writing\n        loc val l\n        (RDING: is_kinda_writing_val loc val l):\n    is_kinda_writing loc l.\n  Proof.\n    destruct l; ss; destruct (equiv_dec loc0 loc); ss.\n  Qed.\n\n  Lemma update_is_kinda_reading loc vold vnew:\n    is_kinda_reading loc (update loc vold vnew).\n  Proof.\n    s. destruct (equiv_dec loc loc); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma update_is_kinda_writing loc vold vnew:\n    is_kinda_writing loc (update loc vold vnew).\n  Proof.\n    s. destruct (equiv_dec loc loc); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma update_is_kinda_writing_val loc vold vnew:\n    is_kinda_writing_val loc vnew (update loc vold vnew).\n  Proof.\n    s. destruct (equiv_dec loc loc); destruct (equiv_dec vnew vnew); ss; exfalso.\n    all: apply c; ss.\n  Qed.\n\n  Lemma accessing_is_access\n        loc l\n        (RD: is_accessing loc l):\n    is_access l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma read_is_accessing loc val:\n    is_accessing loc (read loc val).\n  Proof.\n    s. destruct (equiv_dec loc loc); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma write_is_accessing loc val:\n    is_accessing loc (write loc val).\n  Proof.\n    s. destruct (equiv_dec loc loc); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma update_is_accessing loc vold vnew:\n    is_accessing loc (update loc vold vnew).\n  Proof.\n    s. destruct (equiv_dec loc loc); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma kinda_writing_same_loc loc1 loc2 l\n    (W1: is_kinda_writing loc1 l)\n    (W2: is_kinda_writing loc2 l):\n    loc1 = loc2.\n  Proof.\n    destruct l; ss.\n    - destruct (equiv_dec loc loc1); ss. inv e. destruct (equiv_dec loc1 loc2); ss.\n    - destruct (equiv_dec loc loc1); ss. inv e. destruct (equiv_dec loc1 loc2); ss.\n  Qed.\n\n  Lemma flushopting_is_flushopt\n        loc l\n        (RD: is_flushopting loc l):\n    is_flushopt l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma flushing_is_flush\n        loc l\n        (RD: is_flushing loc l):\n    is_flush l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma flushopt_is_flushopting loc:\n    is_flushopting loc (flushopt loc).\n  Proof.\n    s. destruct (equiv_dec loc loc); ss. exfalso. apply c. ss.\n  Qed.\n\n  Lemma persisting_is_persist\n        loc l\n        (RD: is_persisting loc l):\n    is_persist l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma flush_is_persist\n        l\n        (LABEL: is_flush l):\n    is_persist l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma flushopt_is_persist\n        l\n        (LABEL: is_flushopt l):\n    is_persist l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma access_is_access_persist\n        l\n        (LABEL: is_access l):\n    is_access_persist l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma persist_is_kinda_write_persist\n        l\n        (LABEL: is_persist l):\n    is_kinda_write_persist l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma kinda_write_flush_is_kinda_write_persist\n        l\n        (LABEL: is_kinda_write_flush l):\n    is_kinda_write_persist l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma kinda_write_persist_is_access_persist\n        l\n        (LABEL: is_kinda_write_persist l):\n    is_access_persist l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma flushing_is_persisting\n        loc l\n        (LABEL: is_flushing loc l):\n    is_persisting loc l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma flushopting_is_persisting\n        loc l\n        (LABEL: is_flushopting loc l):\n    is_persisting loc l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma persisting_is_access_persisting\n        loc l\n        (LABEL: is_persisting loc l):\n    is_access_persisting loc l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma accessing_is_access_persisting\n        loc l\n        (LABEL: is_accessing loc l):\n    is_access_persisting loc l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma mfence_is_persist_barrier\n        l\n        (LABEL: Label.is_barrier_c Barrier.is_mfence l):\n    is_persist_barrier l.\n  Proof.\n    destruct l; ss. unfold orb. condtac; ss.\n  Qed.\n\n  Lemma sfence_is_persist_barrier\n        l\n        (LABEL: Label.is_barrier_c Barrier.is_sfence l):\n    is_persist_barrier l.\n  Proof.\n    destruct l; ss. unfold orb. condtac; ss.\n  Qed.\n\n  Lemma accessing_cl_is_access\n        loc l\n        (LABEL: is_accessing_cl loc l):\n    is_access l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma flushing_cl_is_flush\n        loc l\n        (LABEL: is_flushing_cl loc l):\n    is_flush l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma flushopting_cl_is_flushopt\n        loc l\n        (LABEL: is_flushopting_cl loc l):\n    is_flushopt l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma flushing_cl_is_persisting_cl\n        loc l\n        (LABEL: is_flushing_cl loc l):\n    is_persisting_cl loc l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma flushopting_cl_is_persisting_cl\n        loc l\n        (LABEL: is_flushopting_cl loc l):\n    is_persisting_cl loc l.\n  Proof.\n    destruct l; ss.\n  Qed.\n\n  Lemma persisting_cl_inv\n        loc l\n        (LABEL: Label.is_persisting_cl loc l):\n    exists loc0,\n      <<PERSISTING: Label.is_persisting loc0 l>> /\\\n      <<CL: Loc.cl loc loc0>>.\n  Proof.\n    destruct l; ss; esplits; eauto; destruct (equiv_dec loc0 loc0); ss; exfalso; apply c; ss.\n  Qed.\n\n  Hint Resolve\n       read_is_reading_val reading_val_is_reading reading_is_read\n       kinda_reading_is_kinda_read read_is_kinda_read kinda_read_is_access kinda_reading_is_accessing read_is_kinda_reading read_is_kinda_reading_val kinda_read_exists_loc_val kinda_reading_exists_val kinda_reading_val_is_kinda_reading\n       kinda_writing_is_kinda_write write_is_kinda_write kinda_write_is_access kinda_writing_is_accessing write_is_kinda_writing write_is_kinda_writing_val kinda_write_exists_loc_val kinda_writing_exists_val kinda_writing_val_is_kinda_writing\n       update_is_kinda_reading update_is_kinda_writing update_is_kinda_writing_val\n       accessing_is_access read_is_accessing write_is_accessing update_is_accessing\n       kinda_writing_same_loc\n       access_is_access_persist\n       flushopting_is_flushopt flushing_is_flush flushopt_is_flushopting\n       persisting_is_persist flush_is_persist flushopt_is_persist persist_is_kinda_write_persist\n       kinda_write_flush_is_kinda_write_persist kinda_write_persist_is_access_persist\n       flushing_is_persisting flushopting_is_persisting persisting_is_access_persisting accessing_is_access_persisting\n       mfence_is_persist_barrier sfence_is_persist_barrier\n       writing_cl_is_write accessing_cl_is_access\n       flushing_cl_is_flush flushing_cl_is_persisting_cl\n       flushopting_cl_is_flushopt flushopting_cl_is_persisting_cl\n    : tso.\nEnd Label.\n\nModule ALocal.\n  Inductive t := mk {\n    labels: list Label.t;\n  }.\n  Hint Constructors t : tso.\n\n  Definition init: t := mk [].\n\n  Definition next_eid (eu:t): nat :=\n    List.length eu.(labels).\n\n  Inductive step (event:Event.t (A:=unit)) (alocal1:t) (alocal2:t): Prop :=\n  | step_internal\n      (EVENT: event = Event.internal)\n      (ALOCAL: alocal2 =\n               mk\n                 alocal1.(labels))\n  | step_read\n      rmw_fail vloc res ord\n      (EVENT: event = Event.read false rmw_fail ord vloc (ValA.mk _ res tt))\n      (ALOCAL: alocal2 =\n               mk\n                 (alocal1.(labels) ++ [Label.read vloc.(ValA.val) res]))\n  | step_write\n      vloc vval ord\n      (EVENT: event = Event.write false ord vloc vval (ValA.mk _ 0 tt))\n      (ALOCAL: alocal2 =\n               mk\n                 (alocal1.(labels) ++ [Label.write vloc.(ValA.val) vval.(ValA.val)]))\n  | step_update\n      vloc voldv vnewv ordr ordw\n      (EVENT: event = Event.rmw ordr ordw vloc voldv vnewv)\n      (ALOCAL: alocal2 =\n               mk\n                 (alocal1.(labels) ++ [Label.update vloc.(ValA.val) voldv.(ValA.val) vnewv.(ValA.val)]))\n  | step_mfence\n      b\n      (EVENT: event = Event.barrier b)\n      (BARRIER: Barrier.is_mfence b)\n      (ALOCAL: alocal2 =\n               mk\n                 (alocal1.(labels) ++ [Label.barrier b]))\n  | step_sfence\n      b\n      (EVENT: event = Event.barrier b)\n      (BARRIER: Barrier.is_sfence b)\n      (ALOCAL: alocal2 =\n               mk\n                 (alocal1.(labels) ++ [Label.barrier b]))\n  | step_flush\n      vloc\n      (EVENT: event = Event.flush vloc)\n      (ALOCAL: alocal2 =\n               mk\n                 (alocal1.(labels) ++ [Label.flush vloc.(ValA.val)]))\n  | step_flushopt\n      vloc\n      (EVENT: event = Event.flushopt vloc)\n      (ALOCAL: alocal2 =\n               mk\n                 (alocal1.(labels) ++ [Label.flushopt vloc.(ValA.val)]))\n  .\n  Hint Constructors step : tso.\n\n  Inductive le (alocal1 alocal2:t): Prop :=\n  | le_intro\n      (LABELS: exists l, alocal2.(labels) = alocal1.(labels) ++ l)\n  .\n  Hint Constructors le : tso.\n\n  Global Program Instance le_preorder: PreOrder le.\n  Next Obligation.\n    ii. econs.\n    all: try by exists []; rewrite List.app_nil_r.\n    all: try by apply inclusion_refl.\n  Qed.\n  Next Obligation.\n    ii. inv H; inv H0. econs.\n    all: try by eapply inclusion_trans; eauto.\n    des. rewrite LABELS0, LABELS. rewrite <- List.app_assoc. eexists; eauto.\n  Qed.\nEnd ALocal.\n\nModule AExecUnit.\n  Inductive t := mk {\n    state: State.t (A:=unit);\n    local: ALocal.t;\n  }.\n  Hint Constructors t : tso.\n\n  Inductive step (eu1 eu2:t): Prop :=\n  | step_intro\n      e\n      (STATE: State.step e eu1.(state) eu2.(state))\n      (LOCAL: ALocal.step e eu1.(local) eu2.(local))\n  .\n  Hint Constructors step : tso.\n\n  Inductive label_is (labels:list Label.t) (pred:Label.t -> Prop) (iid:nat): Prop :=\n  | label_is_intro\n      l\n      (EID: List.nth_error labels iid = Some l)\n      (LABEL: pred l)\n  .\n  Hint Constructors label_is : tso.\n\n  Definition wf_rmap (rmap: RMap.t (A:=unit)) (labels:list Label.t): Prop := True.\n  Hint Unfold wf_rmap : tso.\n\n  Inductive wf (aeu:t): Prop :=\n  | wf_intro\n      (REG: wf_rmap aeu.(state).(State.rmap) aeu.(local).(ALocal.labels))\n  .\n  Hint Constructors wf : tso.\n\n  Lemma label_is_lt\n        labels pred iid\n        (LABEL: label_is labels pred iid):\n    iid < length labels.\n  Proof.\n    inv LABEL. apply List.nth_error_Some. congr.\n  Qed.\n\n  Lemma label_is_mon\n        labels1 labels2 pred:\n    label_is labels1 pred <1= label_is (labels1 ++ labels2) pred.\n  Proof.\n    ii. inv PR. econs; eauto.\n    rewrite List.nth_error_app1; ss.\n    apply List.nth_error_Some. congr.\n  Qed.\n\n  Lemma union_mon\n        A\n        (p1 p2 q1 q2: A -> Prop)\n        (P: p1 <1= p2)\n        (Q: q1 <1= q2):\n    (p1 ∪₁ q1) <1= (p2 ∪₁ q2).\n  Proof.\n    ii. inv PR.\n    - left. eauto.\n    - right. eauto.\n  Qed.\n\n  Lemma times_mon\n        A\n        (p1 p2 q1 q2: A -> Prop)\n        (P: p1 <1= p2)\n        (Q: q1 <1= q2):\n    p1 × q1 <2= p2 × q2.\n  Proof.\n    ii. inv PR. econs; eauto.\n  Qed.\n\n  Lemma wf_init stmts: wf (mk (State.init stmts) ALocal.init).\n  Proof.\n    econs; ss.\n  Qed.\n\n  Lemma step_future\n        eu1 eu2\n        (WF: wf eu1)\n        (STEP: step eu1 eu2):\n    <<WF: wf eu2>> /\\\n    <<LE: ALocal.le eu1.(local) eu2.(local)>>.\n  Proof.\n    destruct eu1 as [state1 local1].\n    destruct eu2 as [state2 local2].\n    inv STEP. ss.\n    inv STATE; inv LOCAL; inv EVENT; ss;\n      repeat match goal with\n             | [|- context[bot × _]] => rewrite cross_bot_l\n             | [|- context[_ ∪ bot]] => rewrite union_bot_r\n             end.\n    - splits.\n      + inv WF. econs; ss.\n      + destruct local1. refl.\n    - splits.\n      + inv WF. econs; ss.\n      + destruct local1. refl.\n    - splits.\n      + inv WF. econs; ss.\n      + econs; ss. eauto.\n    - splits.\n      + inv WF. econs; ss.\n      + econs; ss. eauto.\n    - splits.\n      + inv WF. econs; ss.\n      + econs; ss. eauto.\n    - splits.\n      + inv WF. econs; ss.\n      + econs; ss. eauto.\n    - splits.\n      + inv WF. econs; ss.\n      + econs; ss. eauto.\n    - splits.\n      + inv WF. econs; ss.\n      + econs; ss. eauto.\n    - splits.\n      + inv WF. econs; ss.\n      + destruct local1. refl.\n    - splits.\n      + inv WF. econs; ss.\n      + econs; ss. eauto.\n    - splits.\n      + inv WF. econs; ss.\n      + econs; ss. eauto.\n  Qed.\n\n  Lemma rtc_step_future\n        eu1 eu2\n        (WF: wf eu1)\n        (STEP: rtc step eu1 eu2):\n    <<WF: wf eu2>> /\\\n    <<LE: ALocal.le eu1.(local) eu2.(local)>>.\n  Proof.\n    revert WF. induction STEP; eauto.\n    - esplits; eauto. refl.\n    - i. exploit step_future; eauto. i. des.\n      exploit IHSTEP; eauto. i. des.\n      esplits; ss. etrans; eauto.\n  Qed.\nEnd AExecUnit.\n\nDefinition eidT := (Id.t * nat)%type.\n\nModule Execution.\n  Inductive t := mk {\n    labels: IdMap.t (list Label.t);\n    co: relation eidT;\n    rf: relation eidT;\n    pf: relation eidT;\n  }.\n  Hint Constructors t : tso.\n\n  Definition label (eid:eidT) (ex:t): option Label.t :=\n    match IdMap.find (fst eid) ex.(labels) with\n    | None => None\n    | Some labels => List.nth_error labels (snd eid)\n    end.\n\n  Definition eids (ex:t): list eidT :=\n    IdMap.fold\n      (fun tid local eids => (List.map (fun i => (tid, i)) (List.seq 0 (List.length local))) ++ eids)\n      ex.(labels)\n      [].\n\n  Lemma eids_spec ex:\n    <<LABEL: forall eid, label eid ex <> None <-> List.In eid (eids ex)>> /\\\n    <<NODUP: List.NoDup (eids ex)>>.\n  Proof.\n    generalize (PositiveMap.elements_3w (labels ex)). intro NODUP.\n    hexploit SetoidList.NoDupA_rev; eauto.\n    { apply IdMap.eqk_equiv. }\n    intro NODUP_REV. splits.\n    - (* LABEL *)\n      i. destruct eid. unfold label, eids. s.\n      rewrite IdMap.fold_1, <- List.fold_left_rev_right, IdMap.elements_spec.\n      rewrite SetoidList_findA_rev; eauto; cycle 1.\n      { apply eq_equivalence. }\n      { apply []. }\n      revert NODUP_REV. induction (List.rev (IdMap.elements (labels ex))); ss.\n      destruct a. i. inv NODUP_REV. s. rewrite List.in_app_iff, <- IHl; ss.\n      match goal with\n      | [|- context[if ?c then true else false]] => destruct c\n      end; ss; i; cycle 1.\n      { econs; eauto. i. des; ss.\n        apply List.in_map_iff in H. des. inv H. congr.\n      }\n      inv e. rewrite List.nth_error_Some, List.in_map_iff.\n      econs; i; des.\n      + left. esplits; eauto. apply HahnList.in_seq0_iff. ss.\n      + inv H. apply HahnList.in_seq0_iff. ss.\n      + revert H.\n        match goal with\n        | [|- context[match ?f with Some _ => _ | None => _ end]] => destruct f eqn:FIND\n        end; ss.\n        apply SetoidList.findA_NoDupA in FIND; ss; cycle 1.\n        { apply eq_equivalence. }\n        exfalso. apply H1. revert FIND. clear. induction l; i; inv FIND.\n        * destruct a. ss. des. inv H0. left. ss.\n        * right. apply IHl. ss.\n    - (* NODUP *)\n      unfold eids. rewrite IdMap.fold_1, <- List.fold_left_rev_right.\n      revert NODUP_REV. induction (List.rev (IdMap.elements (labels ex))); ss. i.\n      inv NODUP_REV. destruct a. s.\n      apply HahnList.nodup_app. splits; eauto.\n      + apply FinFun.Injective_map_NoDup.\n        * ii. inv H. ss.\n        * apply List.seq_NoDup.\n      + ii. apply List.in_map_iff in IN1. des. subst.\n        apply H1. revert IN2. clear. induction l; ss.\n        i. apply List.in_app_iff in IN2. des.\n        * apply List.in_map_iff in IN2. des. inv IN2. left. ss.\n        * right. eauto.\n  Qed.\n\n  Inductive label_is (ex:t) (pred:Label.t -> Prop) (eid:eidT): Prop :=\n  | label_is_intro\n      l\n      (EID: label eid ex = Some l)\n      (LABEL: pred l)\n  .\n  Hint Constructors label_is : tso.\n\n  Inductive label_rel (ex:t) (rel:relation Label.t) (eid1 eid2:eidT): Prop :=\n  | label_rel_intro\n      l1 l2\n      (EID1: label eid1 ex = Some l1)\n      (EID2: label eid2 ex = Some l2)\n      (LABEL: rel l1 l2)\n  .\n  Hint Constructors label_rel : tso.\n\n  Inductive label_is_rel (ex: t) (pred: Label.t -> Prop) (eid1 eid2: eidT): Prop :=\n  | label_is_rel_intro\n      l1 l2\n      (EID1: label eid1 ex = Some l1)\n      (EID2: label eid2 ex = Some l2)\n      (LABEL1: pred l1)\n      (LABEL2: pred l2)\n  .\n  Hint Constructors label_is_rel : tso.\n\n  Inductive label_loc (x y:Label.t): Prop :=\n  | label_loc_intro\n      loc\n      (X: Label.is_accessing loc x)\n      (Y: Label.is_accessing loc y)\n  .\n  Hint Constructors label_loc : tso.\n\n  Inductive label_cl (x y:Label.t): Prop :=\n  | label_cl_intro\n      loc loc'\n      (X: Label.is_access_persisting loc x)\n      (Y: Label.is_access_persisting loc' y)\n      (CL: Loc.cl loc loc')\n  .\n  Hint Constructors label_cl : tso.\n\n  Lemma label_is_mon\n        exec p1 p2 eid\n        (PREL: p1 <1= p2)\n        (P1: label_is exec p1 eid):\n    label_is exec p2 eid.\n  Proof.\n    destruct P1; eauto with tso.\n  Qed.\n\n  (* let obs = rfe | fre | co *)\n  (* let dob = ((W U U U R); po; (W U U U R)) \\ (W × R) ~~~> ([R]; po; [W U U U R]) U ([W U U U R]; po; [W]) *)\n  (* let bob = [W U U U R]; po; [MF]; po; [W U U U R] *)\n  (* let fob =\n      | [W U U U R]; po; [FL]\n      | ([U U R] U ([W]; po; [MF U SF])); po; [FO]\n      | [W]; (po; [FL])?; po_cl; [FO]\n  *)\n  (* let ob = obs | dob | bob | fob | pf | fp *)\n\n  (* irrefl po?; rf as corw *)\n  (* irrefl po; fr as cowr *)\n  (* acyclic ob as external *)\n\n  (* let per = pf; ([FL] U ([FO]; po; [MF U SF U U])) *)\n\n  (* P = dom(per) *)\n  (* forall l, exists w, M(l)=Val(w) /\\ (P x {w})&Loc <= co? *)\n\n  Inductive po (eid1 eid2:eidT): Prop :=\n  | po_intro\n      (TID: fst eid1 = fst eid2)\n      (N: snd eid1 < snd eid2)\n  .\n  Hint Constructors po : tso.\n\n  Global Program Instance po_trans: Transitive po.\n  Next Obligation.\n    ii. destruct x, y, z. inv H. inv H0. ss. subst. econs; ss. lia.\n  Qed.\n\n  Inductive po_adj (eid1 eid2:eidT): Prop :=\n  | po_adj_intro\n      (TID: fst eid1 = fst eid2)\n      (N: snd eid2 = S (snd eid1))\n  .\n  Hint Constructors po_adj : tso.\n\n  Lemma po_adj_po:\n    po_adj ⊆ po.\n  Proof.\n    ii. destruct x, y. inv H. ss. subst. econs; ss.\n  Qed.\n\n  Lemma po_po_adj:\n    po = po^? ⨾ po_adj.\n  Proof.\n    funext. i. funext. i. propext. econs; i.\n    - inv H. destruct x, x0. ss. subst.\n      destruct n0; [lia|].\n      exists (t1, n0). splits; ss. inv N; [left|right]; eauto with tso.\n    - inv H. des. inv H0.\n      + apply po_adj_po. ss.\n      + etrans; eauto. apply po_adj_po. ss.\n  Qed.\n\n  Lemma po_po_adj_weak:\n    (Execution.po ⨾ Execution.po_adj) ⊆ Execution.po.\n  Proof.\n    rewrite po_po_adj at 2. apply inclusion_seq_mon; ss.\n    econs 2. ss.\n  Qed.\n\n  Inductive i (eid1 eid2:eidT): Prop :=\n  | i_intro\n      (TID: fst eid1 = fst eid2)\n  .\n  Hint Constructors i : tso.\n\n  Inductive e (eid1 eid2:eidT): Prop :=\n  | e_intro\n      (TID: fst eid1 <> fst eid2)\n  .\n  Hint Constructors e : tso.\n\n  Definition po_loc (ex:t): relation eidT := po ∩ ex.(label_rel) label_loc.\n\n  Definition fr (ex:t): relation eidT :=\n    (ex.(rf)⁻¹ ⨾ ex.(co)) ∪\n    ((ex.(label_rel) label_loc) ∩\n     ((ex.(label_is) Label.is_kinda_read) \\₁ codom_rel ex.(rf)) × (ex.(label_is) Label.is_kinda_write)).\n  Definition fre (ex:t): relation eidT := (fr ex) ∩ e.\n\n  Definition rfi (ex:t): relation eidT := ex.(rf) ∩ i.\n  Definition rfe (ex:t): relation eidT := ex.(rf) ∩ e.\n\n  Definition cowr (ex:t): relation eidT := po ⨾ (fr ex).\n  Definition corw (ex:t): relation eidT := po^? ⨾ ex.(rf).\n\n  Definition obs (ex:t): relation eidT := (rfe ex) ∪ (fre ex) ∪ ex.(co).\n\n  Definition dob (ex:t): relation eidT :=\n    (⦗ex.(label_is) Label.is_kinda_read⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) Label.is_access⦘) ∪\n    (⦗ex.(label_is) Label.is_access⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) Label.is_kinda_write⦘).\n\n  Definition bob (ex:t): relation eidT :=\n    ⦗ex.(label_is) Label.is_access⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) (Label.is_barrier_c Barrier.is_mfence)⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) Label.is_access⦘.\n\n  Definition po_cl (ex:t): relation eidT := po ∩ ex.(label_rel) label_cl.\n\n  Definition no_pf (ex:t) (loc:Loc.t) (eid:eidT): Prop :=\n    forall eid2\n           (LABEL: ex.(Execution.label_is) (Label.is_kinda_writing loc) eid2)\n           (PF: ex.(Execution.pf) eid2 eid),\n      False.\n\n  Inductive fp_uninit (ex:t) (eid1 eid2:eidT): Prop :=\n  | fp_uninit_intro\n      loc\n      (PERSIST: ex.(Execution.label_is) (Label.is_persisting_cl loc) eid1)\n      (WRITE: ex.(Execution.label_is) (Label.is_kinda_writing loc) eid2)\n      (NOPF: no_pf ex loc eid1)\n  .\n  Hint Constructors fp_uninit.\n\n  Definition fp (ex:t): relation eidT :=\n    (ex.(pf)⁻¹ ⨾ ex.(co)) ∪ (fp_uninit ex).\n\n  Definition fob (ex:t): relation eidT :=\n    (⦗ex.(label_is) Label.is_access⦘ ⨾\n     po ⨾\n     ⦗ex.(label_is) Label.is_flush⦘) ∪\n    ((⦗ex.(label_is) Label.is_kinda_read⦘ ∪\n      (⦗ex.(label_is) Label.is_write⦘ ⨾\n       po ⨾\n       (⦗ex.(label_is) (Label.is_barrier_c Barrier.is_mfence)⦘ ∪\n        ⦗ex.(label_is) (Label.is_barrier_c Barrier.is_sfence)⦘)))⨾\n     po ⨾\n     ⦗ex.(label_is) Label.is_flushopt⦘) ∪\n    (⦗ex.(label_is) Label.is_write⦘ ⨾\n     (po ⨾\n      ⦗ex.(label_is) Label.is_flush⦘)^? ⨾\n     (po_cl ex) ⨾\n     ⦗ex.(label_is) Label.is_flushopt⦘).\n\n  Definition ob (ex:t): relation eidT :=\n    (obs ex) ∪ (dob ex) ∪ (bob ex) ∪ (fob ex) ∪ (pf ex) ∪ (fp ex).\n\n  Definition per (ex:t): relation eidT :=\n    ex.(pf) ⨾\n    (⦗ex.(label_is) Label.is_flush⦘ ∪\n     (⦗ex.(label_is) Label.is_flushopt⦘ ⨾\n      po ⨾\n      ⦗ex.(label_is) Label.is_persist_barrier⦘)).\n\n  Ltac obtac :=\n    repeat\n      (try match goal with\n           | [H: Execution.ob _ _ _ |- _] => inv H\n           | [H: Execution.obs _ _ _ |- _] => inv H\n           | [H: Execution.dob _ _ _ |- _] => inv H\n           | [H: Execution.bob _ _ _ |- _] => inv H\n           | [H: Execution.fob _ _ _ |- _] => inv H\n           | [H: Execution.fr _ _ _ |- _] => inv H\n           | [H: Execution.fre _ _ _ |- _] => inv H\n           | [H: Execution.rfe _ _ _ |- _] => inv H\n           | [H: Execution.fp _ _ _ |- _] => inv H\n           | [H: Execution.fp_uninit _ _ _ |- _] => inv H\n           | [H: Execution.per _ _ _ |- _] => inv H\n           | [H: (_⨾ _) _ _ |- _] => inv H\n           | [H: ⦗_⦘ _ _ |- _] => inv H\n           | [H: (_ ∪ _) _ _ |- _] => inv H\n           | [H: (_ ∩ _) _ _ |- _] => inv H\n           | [H: (_ × _) _ _ |- _] => inv H\n           | [H: (minus_rel _ _) _ |- _] => inv H\n           | [H: Execution.label_is _ _ _ |- _] => inv H\n           | [H: Execution.label_rel _ _ _ _ |- _] => inv H\n           | [H: Execution.label_loc _ _ |- _] => inv H\n           | [H: Execution.label_cl _ _ |- _] => inv H\n           end;\n       des).\n\n  Ltac simtac :=\n  repeat match goal with\n           | [H: _ |- (_⨾ _) _ _] => econs\n           | [H: _ |- ⦗Execution.label_is _ _⦘ _ _] => econs; eauto with tso\n           | [H: _ |- Execution.label_is _ _ _] => eauto with tso\n           | [H: _ |- Execution.label_rel _ _ _ _] => econs; eauto with tso\n           | [H: _ |- rc _ _ /\\ _] => econs; eauto\n           | [H: _ |- Execution.po _ _ /\\ _] => econs; eauto\n           | [H: _ |- _ /\\ Execution.po _ _] => econs; eauto\n           | [H: _ |- Execution.po_cl _ _ _ /\\ _] => econs; eauto\n           | [H: _ |- Execution.pf _ _ _ /\\ _] => econs; eauto\n           | [H: _ |- ⦗Execution.label_is _ _⦘ _ _ /\\ _] => econs; econs; eauto with tso\n           | [H: _ |- Execution.fp_uninit _ _ _] => econs; eauto with tso\n          end.\n\n  Ltac labtac :=\n    repeat match goal with\n            | [H1: Execution.label ?eid ?ex = Some (_ _ _),\n              H2: Execution.label ?eid ?ex = Some (_ _ _) |- _] =>\n              rewrite H1 in H2; inv H2\n            | [H1: Execution.label ?eid ?ex = Some (_ _ _ _),\n              H2: Execution.label ?eid ?ex = Some (_ _ _) |- _] =>\n              rewrite H1 in H2; inv H2\n            | [H1: Execution.label ?eid ?ex = Some (_ _ _),\n              H2: Execution.label ?eid ?ex = Some ?l2 |- _] =>\n              rewrite H1 in H2; inv H2\n            | [H1: Execution.label ?eid ?ex = Some (_ _ _ _),\n              H2: Execution.label ?eid ?ex = Some ?l2 |- _] =>\n              rewrite H1 in H2; inv H2\n            | [H1: Execution.label ?eid ?ex = Some ?l1,\n              H2: Execution.label ?eid ?ex = Some ?l2 |- _] =>\n              rewrite H1 in H2; inv H2\n            end; ss.\n\n  Lemma fob_persist\n        ex\n        eid1 eid2\n        (FOB: (fob ex) eid1 eid2):\n    ex.(label_is) Label.is_persist eid2.\n  Proof.\n    obtac; simtac.\n  Qed.\n\nEnd Execution.\n\nLtac obtac := Execution.obtac.\nLtac simtac := Execution.simtac.\nLtac labtac := Execution.labtac.\n\nInductive tid_lift (tid:Id.t) (rel:relation nat) (eid1 eid2:eidT): Prop :=\n| tid_lift_intro\n    (TID1: fst eid1 = tid)\n    (TID1: fst eid2 = tid)\n    (REL: rel (snd eid1) (snd eid2))\n.\nHint Constructors tid_lift : tso.\n\nLemma tid_lift_incl\n      tid rel1 rel2\n      (REL: rel1 ⊆ rel2):\n  tid_lift tid rel1 ⊆ tid_lift tid rel2.\nProof.\n  ii. inv H. econs; eauto.\nQed.\n\nInductive tid_join (rels: IdMap.t (relation nat)) (eid1 eid2:eidT): Prop :=\n| tid_join_intro\n    tid rel\n    (RELS: IdMap.find tid rels = Some rel)\n    (REL: tid_lift tid rel eid1 eid2)\n.\nHint Constructors tid_join : tso.\n\n\nModule Valid.\n  Inductive pre_ex (p:program) (ex:Execution.t) := mk_pre_ex {\n    aeus: IdMap.t AExecUnit.t;\n\n    AEUS: IdMap.Forall2\n            (fun tid stmts aeu =>\n               rtc AExecUnit.step\n                   (AExecUnit.mk (State.init stmts) ALocal.init)\n                   aeu)\n            p aeus;\n    LABELS: ex.(Execution.labels) = IdMap.map (fun aeu => aeu.(AExecUnit.local).(ALocal.labels)) aeus;\n  }.\n  Hint Constructors pre_ex : tso.\n\n  Definition co1 (ex: Execution.t) :=\n    forall eid1 eid2,\n      (exists loc,\n          <<LABEL: ex.(Execution.label_is) (Label.is_kinda_writing loc) eid1>> /\\\n          <<LABEL: ex.(Execution.label_is) (Label.is_kinda_writing loc) eid2>>) ->\n      (eid1 = eid2 \\/ ex.(Execution.co) eid1 eid2 \\/ ex.(Execution.co) eid2 eid1).\n\n  Definition co2 (ex: Execution.t) :=\n    forall eid1 eid2,\n      ex.(Execution.co) eid1 eid2 ->\n      exists loc,\n        <<LABEL: ex.(Execution.label_is) (Label.is_kinda_writing loc) eid1>> /\\\n        <<LABEL: ex.(Execution.label_is) (Label.is_kinda_writing loc) eid2>>.\n\n  Definition rf1 (ex: Execution.t) :=\n    forall eid1 loc val\n       (LABEL: ex.(Execution.label_is) (Label.is_kinda_reading_val loc val) eid1),\n      (<<NORF: ~ codom_rel ex.(Execution.rf) eid1>> /\\ <<VAL: val = Val.default>>) \\/\n      (exists eid2,\n          <<LABEL: ex.(Execution.label_is) (Label.is_kinda_writing_val loc val) eid2>> /\\\n          <<RF: ex.(Execution.rf) eid2 eid1>>).\n\n  Definition rf2 (ex: Execution.t) :=\n    forall eid1 eid2 (RF: ex.(Execution.rf) eid2 eid1),\n    exists loc val,\n      <<READ: ex.(Execution.label_is) (Label.is_kinda_reading_val loc val) eid1>> /\\\n      <<WRITE: ex.(Execution.label_is) (Label.is_kinda_writing_val loc val) eid2>>.\n\n  Definition rf_wf (ex: Execution.t) := functional (ex.(Execution.rf))⁻¹.\n\n  Definition pf1 (ex: Execution.t):=\n    forall eid1 loc\n           (LABEL: ex.(Execution.label_is) (Label.is_persisting_cl loc) eid1),\n      <<NOPF: Execution.no_pf ex loc eid1>> \\/\n      (exists eid2,\n          <<LABEL: ex.(Execution.label_is) (Label.is_kinda_writing loc) eid2>> /\\\n          <<PF: ex.(Execution.pf) eid2 eid1>>).\n\n  Definition pf2 (ex: Execution.t) :=\n    forall eid1 eid2 (PF: ex.(Execution.pf) eid2 eid1),\n      exists loc,\n      <<PERSIST: ex.(Execution.label_is) (Label.is_persisting_cl loc) eid1>> /\\\n      <<WRITE: ex.(Execution.label_is) (Label.is_kinda_writing loc) eid2>>.\n\n  Inductive persisted_event (ex:Execution.t) (loc:Loc.t) (eid:eidT) :=\n  | persisted_event_intro\n    (EID: ex.(Execution.label_is) (Label.is_kinda_writing loc) eid)\n    (DOM: dom_rel (Execution.per ex) eid)\n  .\n  Hint Constructors persisted_event : tso.\n\n  Inductive persisted_loc (ex:Execution.t) (loc:Loc.t) (val:Val.t): Prop :=\n  | persisted_loc_uninit\n      (UNINIT: val = Val.default)\n      (NPER: forall eid (PEID: persisted_event ex loc eid), False)\n  | persisted_loc_init\n      eid\n      (EID: ex.(Execution.label_is) (Label.is_kinda_writing_val loc val) eid)\n      (PER: forall eid0 (PEID: persisted_event ex loc eid0), ex.(Execution.co)^? eid0 eid)\n  .\n  Hint Constructors persisted_loc : tso.\n\n  Definition persisted ex smem :=\n    forall loc, persisted_loc ex loc (smem loc).\n\n  Inductive ex (p:program) (ex:Execution.t) := mk_ex {\n    PRE: pre_ex p ex;\n    CO1: co1 ex;\n    CO2: co2 ex;\n    RF1: rf1 ex;\n    RF2: rf2 ex;\n    RF_WF: rf_wf ex;\n    PF1: pf1 ex;\n    PF2: pf2 ex;\n    COWR: irreflexive (Execution.cowr ex);\n    CORW: irreflexive (Execution.corw ex);\n    EXTERNAL: acyclic (Execution.ob ex);\n  }.\n  Hint Constructors ex : tso.\n  Coercion PRE: ex >-> pre_ex.\n\n  Definition is_terminal\n             p ex (EX: pre_ex p ex): Prop :=\n    forall tid aeu (FIND: IdMap.find tid EX.(aeus) = Some aeu),\n      State.is_terminal aeu.(AExecUnit.state).\n\n  Lemma po_label_pre\n        p exec\n        eid1 eid2 label2\n        (PRE: pre_ex p exec)\n        (PO: Execution.po eid1 eid2)\n        (LABEL: Execution.label eid2 exec = Some label2):\n    exists label1, <<LABEL: Execution.label eid1 exec = Some label1>>.\n  Proof.\n    destruct eid1, eid2. inv PO. ss. subst.\n    revert LABEL. unfold Execution.label.\n    rewrite PRE.(LABELS), ? IdMap.map_spec. s.\n    destruct (IdMap.find t0 PRE.(aeus)) eqn:LOCAL; ss.\n    generalize (PRE.(AEUS) t0). rewrite LOCAL. intro X. inv X. des.\n    i. exploit List.nth_error_Some. rewrite LABEL. intros [X _]. exploit X; [congr|]. clear X. i.\n    generalize (List.nth_error_Some t.(AExecUnit.local).(ALocal.labels) n). intros [_ X]. hexploit X; [lia|]. i.\n    destruct (List.nth_error t.(AExecUnit.local).(ALocal.labels) n); ss. eauto.\n  Qed.\n\n  Lemma po_label\n        p exec\n        eid1 eid2 label2\n        (EX: ex p exec)\n        (PO: Execution.po eid1 eid2)\n        (LABEL: Execution.label eid2 exec = Some label2):\n    exists label1, <<LABEL: Execution.label eid1 exec = Some label1>>.\n  Proof.\n    inv EX. eapply po_label_pre; eauto.\n  Qed.\n\n  Lemma po_irrefl:\n    forall eid (PO: Execution.po eid eid), False.\n  Proof.\n    ii. inv PO. lia.\n  Qed.\n\n  Lemma coi_is_po\n        p exec\n        eid1 eid2\n        (EX: ex p exec)\n        (RF: exec.(Execution.co) eid1 eid2)\n        (I: Execution.i eid1 eid2):\n    Execution.po eid1 eid2.\n  Proof.\n    destruct eid1 as [tid1 iid1].\n    destruct eid2 as [tid2 iid2].\n    inv I. ss. subst.\n    destruct (lt_eq_lt_dec iid2 iid1); ss.\n    exfalso. eapply EX.(EXTERNAL). apply t_step_rt. esplits.\n    { left. left. left. left. left. right. eauto. }\n    exploit EX.(CO2); eauto. i. des. inv LABEL. inv LABEL0.\n    destruct s.\n    + econs 1.  left. left. left. left. right. right. econs. esplits.\n      * econs; eauto with tso.\n      * econs. esplits; cycle 1.\n        { econs; eauto with tso. }\n        eauto with tso.\n    + subst. econs 2.\n  Qed.\n\n  Lemma rfi_is_po\n        p exec\n        eid1 eid2\n        (EX: ex p exec)\n        (RF: exec.(Execution.rf) eid1 eid2)\n        (I: Execution.i eid1 eid2):\n    Execution.po eid1 eid2.\n  Proof.\n    destruct eid1 as [tid1 iid1].\n    destruct eid2 as [tid2 iid2].\n    inv I. ss. subst. econs; ss.\n    destruct (le_lt_dec iid2 iid1); ss.\n    exfalso. eapply EX.(CORW). econs. econs; [|by eauto].\n    apply Nat.le_lteq in l. des.\n    - econs 2. ss.\n    - econs 1. eauto.\n  Qed.\n\n  Lemma coherence_ww\n        p exec\n        eid1 eid2 loc\n        (EX: ex p exec)\n        (EID1: exec.(Execution.label_is) (Label.is_kinda_writing loc) eid1)\n        (EID2: exec.(Execution.label_is) (Label.is_kinda_writing loc) eid2)\n        (PO: Execution.po eid1 eid2):\n    exec.(Execution.co) eid1 eid2.\n  Proof.\n    inv EID1. inv EID2. exploit EX.(CO1).\n    { obtac. esplits; econs; [exact EID| |exact EID0|]; eauto. }\n    i. des; ss.\n    { subst. apply po_irrefl in PO. inv PO. }\n    exfalso. eapply EX.(EXTERNAL). apply t_step_rt. esplits.\n    - left. left. left. left. left. right. eauto.\n    - econs. left. left. left. left. right. right. econs. esplits.\n      + econs; eauto with tso.\n      + econs. esplits; eauto. econs; eauto with tso.\n  Qed.\n\n  Lemma coherence_wr\n        p exec\n        eid1 eid2 loc\n        (EX: ex p exec)\n        (EID1: exec.(Execution.label_is) (Label.is_kinda_writing loc) eid1)\n        (EID2: exec.(Execution.label_is) (Label.is_kinda_reading loc) eid2)\n        (PO: Execution.po eid1 eid2):\n    exists eid3,\n      <<RF: exec.(Execution.rf) eid3 eid2>> /\\\n      <<CO: exec.(Execution.co)^? eid1 eid3>>.\n  Proof.\n    inv EID1. inv EID2.\n    inversion LABEL0. apply Label.kinda_reading_exists_val in H0. des.\n    exploit EX.(RF1).\n    { instantiate (1 := eid2). econs; eauto. }\n    i. des.\n    { exfalso. eapply EX.(COWR). econs; econs; [by eauto|].\n      right. econs.\n      - econs; eauto with tso.\n      - econs; econs; eauto with tso.\n    }\n    esplits; eauto.\n    exploit EX.(CO1).\n    { obtac. esplits; econs; [exact EID| |exact EID1|]; eauto with tso. }\n    i. des; subst; ss.\n    { refl. }\n    { econs 2. ss. }\n    exfalso. eapply EX.(COWR). econs; econs; [by eauto|].\n    econs; eauto. econs; eauto.\n  Qed.\n\n  Lemma coherence_rr\n        p exec\n        eid1 eid2 eid3 loc\n        (EX: ex p exec)\n        (EID1: exec.(Execution.label_is) (Label.is_kinda_reading loc) eid1)\n        (EID2: exec.(Execution.label_is) (Label.is_kinda_reading loc) eid2)\n        (EID3: exec.(Execution.label_is) (Label.is_kinda_writing loc) eid3)\n        (RF: exec.(Execution.rf) eid3 eid1)\n        (PO: Execution.po eid1 eid2):\n    exists eid4,\n      <<RF: exec.(Execution.rf) eid4 eid2>> /\\\n      <<CO: exec.(Execution.co)^? eid3 eid4>>.\n  Proof.\n    inv EID1. inv EID2. inv EID3.\n    destruct eid1 as [tid1 iid1].\n    destruct eid2 as [tid2 iid2].\n    destruct eid3 as [tid3 iid3].\n    inversion PO. ss. subst.\n    inv LABEL0. apply Label.kinda_reading_exists_val in H0. des.\n    destruct (tid2 == tid3).\n    - inv e. exploit rfi_is_po; eauto with tso. intro X. inv X. ss. subst.\n      (* po-wr -> co?; rf *)\n      exploit EX.(RF1); eauto with tso. i. des.\n      + exfalso. exploit EX.(COWR); eauto. instantiate (1 := (tid3, iid3)). econs; esplits.\n        * etrans; eauto. econs; ss.\n        * right. econs.\n          -- econs; eauto with tso.\n          -- econs; eauto with tso. econs; eauto with tso.\n      + inv LABEL0. rename eid2 into eid4. exploit EX.(CO1).\n        { obtac. esplits; econs; [exact EID1| |exact EID2|]; eauto with tso. }\n        intro X. rewrite <- or_assoc in X. destruct X; [by esplits; eauto|].\n        exfalso. exploit EX.(COWR); eauto. instantiate (1 := (tid3, iid3)). econs; esplits.\n        { etrans; eauto. econs; ss. }\n        left. econs; eauto.\n    - (* ob-wr -> co?; rf *)\n      exploit EX.(RF1); eauto with tso. i. des.\n      + exfalso. exploit EX.(EXTERNAL); eauto. instantiate (1 := (tid3, iid3)).\n        apply t_step_rt. econs; eauto. esplits; [|etrans; [econs|econs]].\n        * repeat left. econs; eauto with tso.\n        * left. left. left. left. right. left. econs. esplits.\n          -- econs; eauto with tso.\n          -- econs. esplits; eauto. econs; eauto with tso.\n        * left. left. left. left. left. left. right. split; ss. right. econs.\n          -- econs; eauto with tso.\n          -- econs; eauto with tso. econs; eauto with tso.\n      + inv LABEL0. rename eid2 into eid4. exploit EX.(CO1).\n        { obtac. esplits; econs; [exact EID1| |exact EID2|]; eauto with tso. }\n        intro X. rewrite <- or_assoc in X. destruct X; [by esplits; eauto|].\n        exfalso. exploit EX.(EXTERNAL); eauto. instantiate (1 := (tid3, iid3)).\n        apply t_step_rt. econs; eauto. esplits; [|etrans; [econs|econs]].\n        * repeat left. econs; eauto with tso.\n        * left. left. left. left. right. left. econs. esplits.\n          -- econs; eauto with tso.\n          -- econs. esplits; eauto. econs; eauto with tso.\n        * left. left. left. left. left. left. right. split; ss. econs. econs. econs; eauto.\n  Qed.\n\n  Lemma coherence_rw\n        p exec\n        eid1 eid2 eid3 loc\n        (EX: ex p exec)\n        (EID1: exec.(Execution.label_is) (Label.is_kinda_reading loc) eid1)\n        (EID2: exec.(Execution.label_is) (Label.is_kinda_writing loc) eid2)\n        (EID3: exec.(Execution.label_is) (Label.is_kinda_writing loc) eid3)\n        (RF1: exec.(Execution.rf) eid3 eid1)\n        (PO: Execution.po eid1 eid2):\n    exec.(Execution.co) eid3 eid2.\n  Proof.\n    inv EID1. inv EID2. inv EID3.\n    exploit EX.(CO1).\n    { obtac. esplits; econs; [exact EID0| |exact EID1|]; eauto. }\n    i. rewrite <- or_assoc in x0. destruct x0; [|done]. inv H.\n    { exfalso. eapply EX.(CORW). econs; eauto. }\n    destruct (fst eid1 == fst eid3).\n    - (* rfi *)\n      exfalso. eapply EX.(CORW). econs. instantiate (1 := eid1). esplits; [|by eauto].\n      right. rewrite PO.\n      inv PO. inv e. rewrite TID in H1. eapply coi_is_po in H0; eauto with tso.\n    - (* rfe *)\n      exfalso. eapply EX.(EXTERNAL). apply t_step_rt. esplits.\n      { repeat left. econs; eauto with tso. }\n      etrans.\n      + instantiate (1 := eid2). econs. left. left. left. left. right. left. econs. econs.\n        * econs; eauto with tso.\n        * econs; eauto. econs; eauto. econs; eauto with tso.\n      + econs. left. left. left. left. left. right. eauto.\n  Qed.\n\n  Lemma rf_inv_write\n        p exec\n        eid1 eid2 loc val\n        (EX: ex p exec)\n        (EID2: exec.(Execution.label_is) (Label.is_kinda_reading_val loc val) eid2)\n        (RF3: exec.(Execution.rf) eid1 eid2):\n    <<LABEL: exec.(Execution.label_is) (Label.is_kinda_writing_val loc val) eid1>>.\n  Proof.\n    exploit EX.(RF1); eauto. i. des.\n    - contradict NORF. econs. eauto.\n    - exploit EX.(RF_WF); [exact RF3|exact RF|]. i. subst. eauto.\n  Qed.\n\n  Lemma barrier_ob\n        p exec\n        eid1 eid2\n        (EX: pre_ex p exec)\n        (CO2: co2 exec)\n        (RF2: rf2 exec)\n        (PF2: pf2 exec)\n        (EID1: Execution.label_is exec Label.is_barrier eid1)\n        (OB: Execution.ob exec eid1 eid2):\n    False.\n  Proof.\n    inv EID1. destruct l; ss. unfold co2, rf2 in *.\n    obtac; labtac; ss.\n    - exploit RF2; eauto. i. des. obtac. labtac.\n    - exploit RF2; eauto. i. des. obtac. labtac.\n    - exploit CO2; eauto. i. des. obtac. labtac.\n    - exploit PF2; eauto. i. des. obtac. labtac.\n    - exploit PF2; eauto. i. des. obtac. labtac.\n  Qed.\n\n  Lemma ob_label\n        p exec\n        eid1 eid2\n        (PRE: pre_ex p exec)\n        (CO2: co2 exec)\n        (RF2: rf2 exec)\n        (PF2: pf2 exec)\n        (OB: Execution.ob exec eid1 eid2)\n        (EID1: Execution.label eid1 exec = None):\n    False.\n  Proof.\n    unfold co2, rf2 in *.\n    obtac.\n    all: try congr.\n    - exploit RF2. eauto. i. des. inv WRITE. inv READ.\n      destruct l; ss. destruct l0; ss. congr. congr.\n      destruct l0; ss. congr. congr.\n    - exploit RF2. eauto. i. des. inv WRITE. inv READ.\n      destruct l; ss. destruct l0; ss. congr. congr.\n      destruct l0; ss. congr. congr.\n    - exploit CO2; eauto. i. des. obtac. congr.\n    - exploit PF2; eauto. i. des. obtac. congr.\n    - exploit PF2; eauto. i. des. obtac. congr.\n  Qed.\n\n  Lemma ob_cycle\n        p exec eid\n        (PRE: pre_ex p exec)\n        (CO2: co2 exec)\n        (RF2: rf2 exec)\n        (PF2: pf2 exec)\n        (CYCLE: (Execution.ob exec)⁺ eid eid):\n    exists eid_nb,\n      (Execution.ob exec ∩ (Execution.label_is_rel exec Label.is_access_persist))⁺ eid_nb eid_nb.\n  Proof.\n    exploit minimalize_cycle; eauto.\n    { instantiate (1 := Execution.label_is exec Label.is_access_persist).\n      i. destruct (Execution.label b exec) eqn:LABEL.\n      - destruct t; try by contradict H1; econs; eauto.\n        exfalso. eapply barrier_ob; eauto with tso.\n      - exfalso. eapply ob_label; eauto.\n    }\n    i. des.\n    - esplits. eapply clos_trans_mon; eauto. s. i. des.\n      econs; ss. inv H0. inv H1. econs; eauto.\n    - destruct (Execution.label a exec) eqn:LABEL.\n      + destruct t; try by contradict x0; econs; eauto.\n        exfalso. eapply barrier_ob; eauto with tso.\n      + exfalso. eapply ob_label; eauto.\n  Qed.\n\n  Lemma ob_read_read_po\n        p ex\n        eid1 eid2\n        (PRE: pre_ex p ex)\n        (CO2: co2 ex)\n        (RF2: rf2 ex)\n        (PF2: pf2 ex)\n        (OB: Execution.ob ex eid1 eid2)\n        (EID1: ex.(Execution.label_is) Label.is_read eid1)\n        (EID2: ex.(Execution.label_is) Label.is_read eid2):\n    Execution.po eid1 eid2.\n  Proof.\n    inv EID1. inv EID2.\n    destruct l; ss. destruct l0; ss.\n    obtac; labtac.\n    - exploit RF2; eauto. i. des.\n      inv WRITE. labtac.\n    - exploit CO2; eauto. i. des.\n      obtac. labtac.\n    - exploit CO2; eauto. i. des.\n      obtac. labtac.\n    - etrans; eauto.\n    - exploit PF2; eauto. i. des.\n      obtac. labtac.\n    - exploit PF2; eauto. i. des.\n      obtac. labtac.\n  Qed.\n\n  Lemma persist_ob_write\n        ex\n        eid1 eid2\n        (CO2: co2 ex)\n        (RF2: rf2 ex)\n        (PF2: pf2 ex)\n        (OB: Execution.ob ex eid1 eid2)\n        (EID1: ex.(Execution.label_is) Label.is_persist eid1):\n    ex.(Execution.label_is) Label.is_kinda_write eid2.\n  Proof.\n    obtac; labtac.\n    all: try by destruct l1; ss.\n    all: try by destruct l2; ss.\n    - exploit RF2; eauto. i. des.\n      obtac. labtac. destruct l0; ss.\n    - exploit RF2; eauto. i. des.\n      obtac. labtac. destruct l1; ss.\n    - exploit CO2; eauto. i. des.\n      obtac. labtac. destruct l1; ss.\n    - exploit PF2; eauto. i. des.\n      obtac. labtac. destruct l0; ss.\n    - exploit CO2; eauto. i. des.\n      obtac. simtac.\n    - simtac.\n  Qed.\n\n  Lemma ob_persist_spec\n        ex\n        eid1 eid2\n        (CO2: co2 ex)\n        (RF2: rf2 ex)\n        (PF2: pf2 ex)\n        (OB: Execution.ob ex eid1 eid2)\n        (EID1: ex.(Execution.label_is) Label.is_persist eid2):\n    <<ACCESS: ex.(Execution.label_is) Label.is_access eid1>>.\n  Proof.\n    inv OB; cycle 1.\n    { obtac.\n      - exploit CO2; eauto. i. des.\n        obtac. labtac. destruct l0; ss; congr.\n      - destruct l; destruct l1; ss; congr.\n    }\n    inv H; cycle 1.\n    { exploit PF2; eauto. i. des.\n      obtac. econs; eauto with tso.\n    }\n    inv H0; cycle 1.\n    { obtac; econs; eauto with tso. }\n    obtac; labtac.\n    all: try by destruct l1; ss.\n    all: try by destruct l2; ss.\n    - exploit RF2; eauto. i. des.\n      obtac. labtac. destruct l1; ss.\n    - exploit CO2; eauto. i. des.\n      obtac. labtac. destruct l0; ss.\n    - exploit CO2; eauto. i. des.\n      obtac. labtac. destruct l0; ss.\n  Qed.\nEnd Valid.\n\nCoercion Valid.PRE: Valid.ex >-> Valid.pre_ex.\n", "meta": {"author": "kaist-cp", "repo": "view-hw", "sha": "e41c8ab30119acd73b6b47cf95584f966ccb8e62", "save_path": "github-repos/coq/kaist-cp-view-hw", "path": "github-repos/coq/kaist-cp-view-hw/view-hw-e41c8ab30119acd73b6b47cf95584f966ccb8e62/src/axiomatic/TsoAxiomatic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.33807713081919877, "lm_q1q2_score": 0.21658433170417743}}
{"text": "Require Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Import Bool.\nRequire Import Zbool.\nRequire Import BinPos. \nRequire Import eq_dec.\n\nRequire Import Globalenvs.\nRequire Import Memory.\nRequire Import Values.\nRequire Import Maps.\n\nRequire Import Axioms.\n\nRequire Import sepcomp. Import SepComp.\n\nRequire Import pred_lemmas.\nRequire Import seq_lemmas.\nRequire Import inj_lemmas.\nRequire Import join_sm.\n\n(* nwp = no wild pointers *)\n\nDefinition nwp_aux m (IN OUT : block -> bool) :=\n  forall b ofs, \n  IN b -> \n  Mem.perm m b ofs Cur Readable -> \n  forall b' ofs' n, \n    ZMap.get ofs (Mem.mem_contents m) !! b = Pointer b' ofs' n -> \n    OUT b'.\n\nDefinition nwp m := [fun bs => nwp_aux m bs bs].\n\nLemma nwp_REACH_closed1 bs m : \n  nwp m bs -> \n  REACH_closed m bs.\nProof.\nmove=> A; rewrite/REACH_closed=> b; rewrite REACHAX=> [][]L B.\nelim: L b B=> //; first by move=> b; rewrite reach_reach'.\nmove=> [b' ofs'] L' IH b; rewrite reach_reach'=> /=.\nmove: {A}(A b' ofs').\ncase: (ZMap.get _ _ !! _)=> // b'' n n' A []B []C.\nrewrite -reach_reach'; move/(IH _)=> D.\nby move: (A D C b'' n n' erefl); rewrite -B.\nQed.\n\nLemma nwp_REACH_closed2 bs m : \n  REACH_closed m bs -> \n  nwp m bs.\nProof.\nrewrite/REACH_closed=> A b ofs B C b' ofs' n D; apply: A.\nby rewrite REACHAX; exists [:: (b,ofs)]; rewrite reach_reach' /= D.\nQed.\n\nLemma REACH_closedP bs m : REACH_closed m bs <-> nwp m bs.\nProof.\nsplit; first by apply: nwp_REACH_closed2.\nby apply: nwp_REACH_closed1.\nQed.\n\n(* nwp_aux is invariant over disjoint memory updates -- phi2 is the frame *)\n\nLemma nwp_aux_pre phi1 phi1' phi2 m :\n  nwp_aux m phi1 phi2 -> \n  {subset phi1' <= phi1} -> \n  nwp_aux m phi1' phi2.\nProof.\nmove=> A sub b ofs B C b' ofs' n D.\nby move: (sub _ B); move/(A b ofs); move/(_ C b' ofs' n D).\nQed.\n\nLemma nwp_aux_post phi1 phi2 phi2' m :\n  nwp_aux m phi1 phi2 -> \n  {subset phi2 <= phi2'} -> \n  nwp_aux m phi1 phi2'.\nProof.\nmove=> A sub b ofs B C b' ofs' n D.\nby apply: sub; apply: (A _ _ B C b' ofs' n D).\nQed.\n\nLemma nwp_aux_update phi1 phi2 m m' : \n  (forall b, phi2 b=true -> Mem.valid_block m b) -> \n  nwp_aux m phi2 (fun b => phi1 b || phi2 b) -> \n  Mem.unchanged_on (fun b ofs => phi2 b) m m' -> \n  nwp_aux m' phi1 (fun b => phi1 b || phi2 b) -> \n  nwp_aux m' phi2 (fun b => phi1 b || phi2 b).\nProof.\nmove=> val A unch C b ofs D E b' ofs' n F.\nhave G: Mem.perm m b ofs Cur Readable.\n  by case: unch; move/(_ b ofs Cur Readable D (val _ D))=> ->.\napply: (A b ofs D G b' ofs' n).\nby case: unch=> _; move/(_ _ _ D G)=> <-.\nQed.\n\nLemma nwp_unchanged_on m m' bs : \n  nwp m bs -> \n  mem_forward m m' -> \n  Mem.unchanged_on (fun b ofs => bs b) m m' -> \n  (forall b, bs b -> Mem.valid_block m b) ->\n  nwp m' bs.\nProof.\nby move=> A B C D; apply nwp_aux_update \n  with (phi1 := fun b => false) (phi2 := bs) (m := m).\nQed.\n\nLemma nwp_union phi1 phi2 m : \n  nwp_aux m phi1 (fun b => phi1 b || phi2 b) -> \n  nwp_aux m phi2 (fun b => phi1 b || phi2 b) -> \n  nwp m (fun b => phi1 b || phi2 b).\nProof.\nmove=> A B b ofs; move/orP; case=> C D b' ofs' n E.\nby apply: (A b ofs C D b' ofs' n E).\nby apply: (B b ofs C D b' ofs' n E).\nQed.\n\nLemma nwp_aux_update_spec1 priv1 pub1 priv2 pub2 m m' : \n  let phi1 := fun b => priv1 b || pub1 b || pub2 b in\n  let phi2 := fun b => priv2 b in\n  (forall b, phi2 b=true -> Mem.valid_block m b) -> \n  nwp m (fun b => phi1 b || phi2 b) -> \n  Mem.unchanged_on (fun b ofs => phi2 b) m m' -> \n  nwp m' phi1 -> \n  nwp m' (fun b => phi1 b || phi2 b).\nProof.\nmove=> phi1 phi2 A B C D.\nhave X: nwp_aux m phi2 (fun b : block => phi1 b || phi2 b).\n  apply nwp_aux_pre with (phi1 := (fun b => phi1 b || phi2 b))=> //.\n  by move=> b; rewrite/in_mem/= => ->; apply/orP; right.\nhave Y: nwp_aux m' phi1 (fun b : block => phi1 b || phi2 b).\n  apply nwp_aux_post with (phi2 := phi1)=> //.\n  by move=> b; rewrite/in_mem/= => ->; apply/orP; left.\nmove: (@nwp_aux_update phi1 phi2 m m' A X C Y)=> E.\nby apply: (nwp_union Y E).\nQed.\n\nLemma nwp_aux_update_spec2 loc1 frgn1 loc2 frgn2 m m' : \n  let phi1 := fun b => loc1 b || frgn1 b || frgn2 b in\n  let phi2 := fun b => loc2 b && ~~frgn1 b in\n  (forall b, phi2 b=true -> Mem.valid_block m b) -> \n  nwp m (fun b => phi1 b || phi2 b) -> \n  Mem.unchanged_on (fun b ofs => phi2 b) m m' -> \n  nwp m' phi1 -> \n  nwp m' (fun b => phi1 b || phi2 b).\nProof.\nmove=> phi1 phi2 A B C D.\nhave X: nwp_aux m phi2 (fun b : block => phi1 b || phi2 b).\n  apply nwp_aux_pre with (phi1 := (fun b => phi1 b || phi2 b))=> //.\n  by move=> b; rewrite/in_mem/= => ->; apply/orP; right.\nhave Y: nwp_aux m' phi1 (fun b : block => phi1 b || phi2 b).\n  apply nwp_aux_post with (phi2 := phi1)=> //.\n  by move=> b; rewrite/in_mem/= => ->; apply/orP; left.\nmove: (@nwp_aux_update phi1 phi2 m m' A X C Y)=> E.\nby apply: (nwp_union Y E).\nQed.\n\nLemma nwp_aux_update_spec3 phi1 phi1' phi2 m m' : \n  (forall b, phi2 b=true -> Mem.valid_block m b) -> \n  nwp_aux m phi2 (fun b => phi1 b || phi2 b) -> \n  Mem.unchanged_on (fun b ofs => phi2 b) m m' -> \n  (forall b, phi1 b=true -> phi1' b=true) -> \n  nwp_aux m' phi1' (fun b => phi1' b || phi2 b) -> \n  nwp_aux m' phi2 (fun b => phi1' b || phi2 b).\nProof.\nmove=> A B C D E.\napply: (nwp_aux_update (m:=m))=> //.\napply: (nwp_aux_post (phi2:=(fun b => phi1 b || phi2 b)))=> //.\nmove=> b; rewrite/in_mem/=; case F: (phi1 b)=> //= X.\nby apply/orP; left; apply: (D _ F).\nby apply/orP; right.\nQed.\n\nLemma nwp_aux_update_spec4 loc1 loc1' frgn1 loc2 frgn2 m m' : \n  let phi1 := fun b => loc1 b || frgn1 b || frgn2 b in\n  let phi1' := fun b => loc1' b || frgn1 b || frgn2 b in\n  let phi2 := fun b => loc2 b && ~~frgn1 b in\n  (forall b, phi1 b -> phi1' b) -> \n  (forall b, phi2 b=true -> Mem.valid_block m b) -> \n  nwp m (fun b => phi1 b || phi2 b) -> \n  Mem.unchanged_on (fun b ofs => phi2 b) m m' -> \n  nwp m' phi1' -> \n  nwp m' (fun b => phi1' b || phi2 b).\nProof.\nmove=> phi1 phi1' phi2 A B C D E.\nhave X: nwp_aux m phi2 (fun b : block => phi1 b || phi2 b).\n  apply nwp_aux_pre with (phi1 := (fun b => phi1 b || phi2 b))=> //.\n  by move=> b; rewrite/in_mem/= => ->; apply/orP; right.\nhave Y: nwp_aux m' phi1' (fun b : block => phi1' b || phi2 b).\n  apply nwp_aux_post with (phi2 := phi1')=> //.\n  by move=> b; rewrite/in_mem/= => ->; apply/orP; left.\nmove: (@nwp_aux_update_spec3 phi1 phi1' phi2 m m' B X D A Y)=> F.\nby apply: (nwp_union Y F).\nQed.\n\nLemma nwp_aux_update_spec5 loc1 loc1' frgn1 loc2 frgn2 m m' : \n  let phi1 := fun b => loc1 b || (frgn1 b && frgn2 b) in\n  let phi1' := fun b => loc1' b || (frgn1 b && frgn2 b) in\n  let phi2 := fun b => loc2 b && ~~frgn1 b in\n  (forall b, phi1 b -> phi1' b) -> \n  (forall b, phi2 b=true -> Mem.valid_block m b) -> \n  nwp m (fun b => phi1 b || phi2 b) -> \n  Mem.unchanged_on (fun b ofs => phi2 b) m m' -> \n  nwp m' phi1' -> \n  nwp m' (fun b => phi1' b || phi2 b).\nProof.\nmove=> phi1 phi1' phi2 A B C D E.\nhave X: nwp_aux m phi2 (fun b : block => phi1 b || phi2 b).\n  apply nwp_aux_pre with (phi1 := (fun b => phi1 b || phi2 b))=> //.\n  by move=> b; rewrite/in_mem/= => ->; apply/orP; right.\nhave Y: nwp_aux m' phi1' (fun b : block => phi1' b || phi2 b).\n  apply nwp_aux_post with (phi2 := phi1')=> //.\n  by move=> b; rewrite/in_mem/= => ->; apply/orP; left.\nmove: (@nwp_aux_update_spec3 phi1 phi1' phi2 m m' B X D A Y)=> F.\nby apply: (nwp_union Y F).\nQed.\n\nLemma join_sm_REACH_closed mu1 mu1' mu2 m1 m1' : \n  Mem.unchanged_on (fun b ofs => \n    locBlocksSrc mu2 b && ~~frgnBlocksSrc mu1 b) m1 m1' -> \n  (forall b, \n     frgnBlocksSrc mu1 b -> \n     locBlocksSrc mu2 b || frgnBlocksSrc mu2 b) -> \n  intern_incr mu1 mu1' -> \n  smvalid_src mu2 m1 -> \n  REACH_closed m1 (vis (join_sm mu1 mu2)) ->\n  REACH_closed m1' (vis mu1') ->\n  REACH_closed m1' (vis (join_sm mu1' mu2)).\nProof.\nrewrite !REACH_closedP.\nmove=> A contain B valid.\nrewrite/vis/join_sm/=/in_mem/= => C D.\nset phi1 := (fun b => \n  locBlocksSrc mu1 b || frgnBlocksSrc mu1 b).\nset phi1' := (fun b => \n  locBlocksSrc mu1' b || frgnBlocksSrc mu1 b).\nset phi2 := (fun b => locBlocksSrc mu2 b && ~~frgnBlocksSrc mu1 b).\nhave val: forall b, phi2 b = true -> Mem.valid_block m1 b. \n  rewrite/phi2=> b; move/andP=> []X Y.  \n  by move: (valid b); rewrite/DOM/DomSrc X; apply.\nset phi0 := fun b => locBlocksSrc mu1 b || locBlocksSrc mu2 b\n               || frgnBlocksSrc mu1 b && frgnBlocksSrc mu2 b.\nhave sub: forall b, phi1 b = true -> phi1' b = true.\n  rewrite/phi1/phi1'=> b; case/orP=> X.\n  by case: B=> _ []_ []; move/(_ b); rewrite X=> Y _; rewrite Y.\n  by rewrite X; apply/orP; right.\nhave sub':\n  forall b,\n    locBlocksSrc mu1 b || locBlocksSrc mu2 b\n      || frgnBlocksSrc mu1 b && frgnBlocksSrc mu2 b ->\n    locBlocksSrc mu1 b || frgnBlocksSrc mu1 b\n      || locBlocksSrc mu2 b && ~~ frgnBlocksSrc mu1 b.\n  move=> b.\n  case: (locBlocksSrc mu1 b)=> //=.\n  case: (locBlocksSrc mu2 b)=> //=.\n  case: (frgnBlocksSrc mu1 b)=> //.\n  by move/andP=> []->.\nhave X: nwp_aux m1 phi2 (fun b : block => phi1 b || phi2 b). \n  apply: (nwp_aux_pre (phi1 := phi0)).\n  apply: (nwp_aux_post (phi2 := phi0))=> //.\n  move=> b; rewrite/phi2/phi0/in_mem/=.\n  by move/andP=> []-> _; apply/orP; left; apply/orP; right.\nhave eq: (frgnBlocksSrc mu1=frgnBlocksSrc mu1'). \n  by case: B=> _ []_ []_ []_ []_ []_ []->.\nhave Y: nwp_aux m1' phi1' (fun b : block => phi1' b || phi2 b).\n  apply: (nwp_aux_pre \n    (phi1 := (fun b => locBlocksSrc mu1' b || frgnBlocksSrc mu1' b))).\n  apply: (nwp_aux_post \n    (phi2 := (fun b => locBlocksSrc mu1' b || frgnBlocksSrc mu1' b)))=> //.\n  by move=> b; rewrite/phi1'/phi2/in_mem/= eq=> ->.\n  by move=> b; rewrite/phi1'/in_mem/= eq.\nmove: (@nwp_aux_update_spec3 phi1 phi1' phi2 m1 m1' val X A sub Y)=> E.\napply: (nwp_aux_pre (phi1 := fun b => phi1' b || phi2 b)).\napply: (nwp_aux_post (phi2 := fun b => phi1' b || phi2 b))=> //.\nby apply: nwp_union.\nmove=> b; rewrite/in_mem/=/phi1'/phi2.\ncase U: (locBlocksSrc mu1' b)=> //=.\nrewrite eq; case V: (frgnBlocksSrc mu1' b)=> //=.\nby move=> _; apply: contain; rewrite eq.\nmove=> b; rewrite/in_mem/=/phi1'/phi2.\ncase: (locBlocksSrc mu1' b)=> //=.\ncase: (locBlocksSrc mu2)=> //=.\nmove=> _.\nby case: (frgnBlocksSrc mu1 b).\nrewrite eq.\nby move/andP=> [] -> _.\nQed.\n\nLemma join_sm_REACH_closed' mu1 mu1' mu2 m1 m1' : \n  DisjointLS mu1 mu2 -> \n  Mem.unchanged_on (fun b ofs => vis mu1 b = false) m1 m1' -> \n  (forall b, \n     frgnBlocksSrc mu1 b -> \n     locBlocksSrc mu2 b || frgnBlocksSrc mu2 b) -> \n  intern_incr mu1 mu1' -> \n  smvalid_src mu2 m1 -> \n  REACH_closed m1 (vis (join_sm mu1 mu2)) ->\n  REACH_closed m1' (vis mu1') ->\n  REACH_closed m1' (vis (join_sm mu1' mu2)).\nProof.\nmove=> A B C D E F G.\nhave unch: \n  Mem.unchanged_on (fun b ofs => \n    locBlocksSrc mu2 b && ~~frgnBlocksSrc mu1 b) m1 m1'.\n  apply mem_unchanged_on_sub with (Q:=(fun b ofs => vis mu1 b=false))=> //.\n  move=> b _; rewrite/vis.\n  case H: (locBlocksSrc mu2 b)=> //=.\n  case I: (frgnBlocksSrc mu1 b)=> //=.                                   \n  move: A; move/(DisjointP _); move/(_ b); rewrite H.\n  by case=> //; case: (locBlocksSrc mu1 b).\nby apply: (join_sm_REACH_closed unch C D E F G).\nQed.\n\nLemma join_all_REACH_closed \n      (mu_trash mu mu' : Inj.t) (mus : seq Inj.t) m1 m1' : \n  DisjointLS mu mu_trash -> \n  All (DisjointLS mu) [seq Inj.mu x | x <- mus] -> \n  Mem.unchanged_on (fun b ofs => vis mu b = false) m1 m1' -> \n  (forall b, \n     frgnBlocksSrc mu b -> \n     let mu_rest := join_all mu_trash mus \n     in locBlocksSrc mu_rest b || frgnBlocksSrc mu_rest b) -> \n  intern_incr mu mu' -> \n  smvalid_src mu_trash m1 -> \n  All (fun mu0 => smvalid_src mu0 m1) [seq Inj.mu x | x <- mus] -> \n  REACH_closed m1 (vis (join_all mu_trash (mu :: mus))) -> \n  REACH_closed m1' (vis mu') ->\n  REACH_closed m1' (vis (join_all mu_trash (mu' :: mus))).\nProof.\nmove=> /= A B C D E F G H I.\nhave disj: DisjointLS mu (join_all mu_trash mus). \n  by apply: join_all_disjoint_src; split.\nhave val: smvalid_src (join_all mu_trash mus) m1. \n  apply: join_all_valid_src=> //.\n  by move: G; rewrite -All_comp3.\nby apply: (join_sm_REACH_closed' disj C D E val H I).\nQed.\n\nLemma reach_trans m B L0 L1 b0 ofs0 b1 :\n  reach m B (L0 ++ [::(b0,ofs0)]) b1 -> \n  reach m B L1 b0 -> \n  reach m B (L0 ++ [::(b0,ofs0) & L1]) b1.\nProof.\nelim: L0 b0 ofs0 b1 L1.\nmove=> b0 ofs0 b1 L1 /=; inversion 1; subst=> A.\nby eapply reach_cons; eauto.\ncase=> bb ofss L IH b0 ofs0 b1; inversion 1; subst=> /= A.\nby eapply reach_cons; eauto.\nQed.\n\nLemma notin_REACHP m B b : \n  b \\notin REACH m B ->\n  forall l, ~reach m B l b.\nProof.\nmove/negP=> H l H2; apply: H.\nby rewrite /is_true /in_mem; rewrite /= REACHAX; exists l.\nQed.\n\nLemma valid_dec m b : Mem.valid_block m b -> valid_block_dec m b.\nProof. by rewrite /is_left; case l: (valid_block_dec m b). Qed.\n\nLemma valid_dec' m b : valid_block_dec m b -> Mem.valid_block m b.\nProof. by rewrite /is_left; case l: (valid_block_dec m b). Qed.\n\nSection reach_upd.\n\nVariable B : block -> bool.\n\nVariable E : block -> Z -> bool.\n\nVariable m1 m1' : mem.\n\nVariable VIS' : block -> bool.\n\nVariable E_sub : forall b ofs, E b ofs -> VIS' b.    \n\nVariable localloc_sub : {subset freshloc m1 m1' <= VIS'}.\n\nLemma reach_upd_inE b : \n  b \\notin REACH m1 B -> \n  b \\in REACH m1' B -> \n  Mem.unchanged_on (fun b ofs => E b ofs=false) m1 m1' -> \n  exists b0 ofs L, [/\\ reach m1' B L b, List.In (b0,ofs) L & VIS' b0].\nProof.\nrewrite /is_true /in_mem /= => H; rewrite REACHAX=> [][]L rch unch. \nelim: L b H rch.\nmove=> b H; inversion 1; subst; move: {H}(negP H)=> H.\nhave H3: forall l, ~ reach m1 B l b.\n{ by apply: notin_REACHP; apply/negP; apply: H. }\nby elimtype False; apply: (H3 [::]); apply: reach_nil.\ncase=> b0 ofs0 L IH b H; inversion 1; subst.\nhave H7: forall l, ~ reach m1 B l b by apply: notin_REACHP.\ncase get: (ZMap.get ofs0 (Mem.mem_contents m1) !! b0)=> [||b' off' n'].\nexists b0,ofs0,[::(b0,ofs0) & L]; split=> //; first by left.\ncase e: (E b0 ofs0); first by apply: (E_sub e).\ncase f: (valid_block_dec m1 b0)=> [valid|nvalid].\nhave H5': Mem.perm m1 b0 ofs0 Cur Readable.\n{ case: unch; move/(_ _ _ _ _ e valid); case/(_ Cur Readable)=> E1 E2.\n  by move=> _; apply: E2. }\nby case: unch=> _; move/(_ _ _ e H5'); rewrite H6 get.\napply: localloc_sub; apply/andP; split=> //.\nhave X: Mem.valid_block m1' b0.\n{ by move: H5; apply: Mem.perm_valid_block. }\nby move: X; move/valid_dec.\nby apply/negP; move/valid_dec'=> X; clear f; apply: nvalid.\nexists b0,ofs0,[::(b0,ofs0) & L]; split=> //; first by left.\ncase e: (E b0 ofs0); first by apply: (E_sub e).\ncase f: (valid_block_dec m1 b0)=> [valid|nvalid].\nhave H5': Mem.perm m1 b0 ofs0 Cur Readable.\n{ case: unch; move/(_ _ _ _ _ e valid); case/(_ Cur Readable)=> E1 E2.\n  by move=> _; apply: E2. }\nby case: unch=> _; move/(_ _ _ e H5'); rewrite H6 get.\napply: localloc_sub; apply/andP; split=> //.\nhave X: Mem.valid_block m1' b0.\n{ by move: H5; apply: Mem.perm_valid_block. }\nby move: X; move/valid_dec.\nby apply/negP; move/valid_dec'=> X; clear f; apply: nvalid.\ncase p: (Mem.perm_dec m1 b0 ofs0 Cur Readable)=> [prm|nprm].\n \n{ case e: (eq_dec (b,off) (b',off'))=> [pf|pf].\n  inversion pf; subst; clear e pf.\n  case f: (REACH m1 B b0).\n  move: f; rewrite REACHAX; case=> L0 rch0.\n  elimtype False; apply: (H7 [::(b0,ofs0) & L0]).\n  by apply: (reach_cons _ _ _ _ _ _ _ _ rch0 prm get).\n  have H8: ~~ REACH m1 B b0=true by apply/negP; rewrite f. \n  case: (IH _ H8 H3)=> bM []offM []L0 []rch' inL0 inE.\n  exists bM,offM,[::(b0,ofs0) & L0]; split=> //.\n  by eapply reach_cons; eauto.\n  by right. \n\n  exists b0,ofs0,[::(b0,ofs0) & L]; split=> //; first by left.\n  case f: (E b0 ofs0); first by apply: (E_sub f).\n  case g: (valid_block_dec m1 b0)=> [valid|nvalid].\n  have H5': Mem.perm m1 b0 ofs0 Cur Readable.\n  { case: unch; move/(_ _ _ _ _ f valid); case/(_ Cur Readable)=> E1 E2.\n    by move=> _; apply: E2. }\n  case: unch=> _; move/(_ _ _ f H5'); rewrite H6 get=> H8.\n  by move: pf e; case: H8=> -> -> _ pf; elimtype False; apply: pf.\n  apply: localloc_sub; apply/andP; split=> //.\n  have X: Mem.valid_block m1' b0.\n  { by move: H5; apply: Mem.perm_valid_block. }\n  by move: X; move/valid_dec.\n  by apply/negP; move/valid_dec'=> X; clear g; apply: nvalid. }\n\n{ exists b0,ofs0,[::(b0,ofs0) & L]; split=> //; first by left.\n  case f: (E b0 ofs0); first by apply: (E_sub f).\n  case g: (valid_block_dec m1 b0)=> [valid|nvalid].\n  have H5': Mem.perm m1 b0 ofs0 Cur Readable.\n  { case: unch; move/(_ _ _ _ _ f valid); case/(_ Cur Readable)=> E1 E2.\n    by move=> _; apply: E2. }\n  by clear p; elimtype False; apply: nprm.\n  apply: localloc_sub; apply/andP; split=> //.\n  have X: Mem.valid_block m1' b0.\n  { by move: H5; apply: Mem.perm_valid_block. }\n  by move: X; move/valid_dec.\n  by apply/negP; move/valid_dec'=> X; clear g; apply: nvalid. }\nQed.  \n\nLemma reach_split m X (Y : block -> bool) l1 l2 b0 ofs b : \n  Y b0 ->\n  reach m X ((l1 ++ [::(b0,ofs)]) ++ l2) b -> \n  reach m Y (l1 ++ [::(b0,ofs)]) b.\nProof.\nelim: l1 b=> //=.\nmove=> b H; inversion 1; subst; apply: reach_cons; eauto.\nby apply: reach_nil.\ncase=> b1 ofs1 L IH b H; inversion 1; subst.\nby apply: reach_cons; eauto.\nQed.\n\nLemma reach_upd b : \n  b \\notin REACH m1 B -> \n  b \\in REACH m1' B -> \n  Mem.unchanged_on (fun b ofs => E b ofs=false) m1 m1' -> \n  b \\in REACH m1' VIS'.\nProof.\nmove=> H H2 H3; case: (reach_upd_inE H H2 H3). \nmove=> b0 []ofs []L []rch inL inE.\nrewrite /in_mem /= /is_true REACHAX.\nhave [L0 [L1 L_eq]]: exists l0 l1, L = (l0 ++ [::(b0,ofs)]) ++ l1.\n{ clear - inL; elim: L inL=> // a L IH /=; case.\n  by move=> ->; exists [::],L.\n  by case/IH=> l0 []l1 ->; exists [::a & l0],l1. }\nexists (L0++[::(b0,ofs)]); move: rch; rewrite L_eq.\nby apply: reach_split. \nQed.\n\nEnd reach_upd.\n  \n  ", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/linking/reach_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21654557728860435}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.client_lemmas.\nRequire Import VST.floyd.type_induction.\n(*Require Import VST.floyd.fieldlist.*)\nRequire Import VST.floyd.compact_prod_sum.\n(*Require Import VST.floyd.aggregate_type.*)\nRequire Import VST.floyd.mapsto_memory_block.\nRequire Import VST.floyd.nested_pred_lemmas.\nRequire Import VST.floyd.jmeq_lemmas.\nRequire Import VST.floyd.sublist.\n\nRequire Export VST.floyd.fieldlist.\nRequire Export VST.floyd.aggregate_type.\n\nOpen Scope Z.\nOpen Scope logic.\n\n(******************************************\n\nDefinition and lemmas about rangespec\n\n******************************************)\n\nFixpoint rangespec (lo: Z) (n: nat) (P: Z -> val -> mpred): val -> mpred :=\n  match n with\n  | O => fun _ => emp\n  | S n' => P lo * rangespec (Zsucc lo) n' P\n end.\n\nFixpoint fold_range' {A: Type} (f: Z -> A -> A) (zero: A) (lo: Z) (n: nat) : A :=\n match n with\n  | O => zero\n  | S n' => f lo (fold_range' f  zero (Zsucc lo) n')\n end.\n\nDefinition fold_range {A: Type} (f: Z -> A -> A) (zero: A) (lo hi: Z) : A :=\n  fold_range' f zero lo (Z.to_nat (hi-lo)).\n\nLemma rangespec_shift_derives: forall lo lo' len P P' p p',\n  (forall i i', lo <= i < lo + Z_of_nat len -> i - lo = i' - lo' -> P i p |-- P' i' p') ->\n  rangespec lo len P p |-- rangespec lo' len P' p'.\nProof.\n  intros.\n  revert lo lo' H;\n  induction len; intros.\n  + simpl. auto.\n  + simpl.\n    apply sepcon_derives.\n    - apply H; [| omega].\n      rewrite Nat2Z.inj_succ.\n      rewrite <- Z.add_1_r.\n      omega.\n    - apply IHlen. intros.\n      apply H; [| omega].\n      rewrite Nat2Z.inj_succ.\n      rewrite <- Z.add_1_r.\n      pose proof Zle_0_nat (S len).\n      omega.\nQed.\n\nLemma rangespec_ext_derives: forall lo len P P' p,\n  (forall i, lo <= i < lo + Z_of_nat len -> P i p |-- P' i p) ->\n  rangespec lo len P p |-- rangespec lo len P' p.\nProof.\n  intros.\n  apply rangespec_shift_derives.\n  intros.\n  assert (i = i') by omega.\n  subst.\n  apply H.\n  auto.\nQed.\n\nLemma rangespec_shift: forall lo lo' len P P' p p',\n  (forall i i', lo <= i < lo + Z_of_nat len -> i - lo = i' - lo' -> P i p = P' i' p') ->\n  rangespec lo len P p = rangespec lo' len P' p'.\nProof.\n  intros; apply pred_ext; apply rangespec_shift_derives;\n  intros.\n  + erewrite H; eauto.\n  + erewrite H; eauto.\n    omega.\nQed.\n\nLemma rangespec_ext: forall lo len P P' p,\n  (forall i, lo <= i < lo + Z_of_nat len -> P i p = P' i p) ->\n  rangespec lo len P p = rangespec lo len P' p.\nProof.\n  intros; apply pred_ext; apply rangespec_ext_derives;\n  intros; rewrite H; auto.\nQed.\n\nLemma rangespec_sepcon: forall lo len P Q p,\n  rangespec lo len P p * rangespec lo len Q p = rangespec lo len (P * Q) p.\nProof.\n  intros.\n  revert lo; induction len; intros.\n  + simpl.\n    rewrite sepcon_emp; auto.\n  + simpl.\n    rewrite !sepcon_assoc.\n    f_equal.\n    rewrite <- sepcon_assoc, (sepcon_comm _ (Q lo p)), sepcon_assoc.\n    f_equal.\n    rewrite IHlen.\n    reflexivity.\nQed.\n\nLemma rangespec_elim: forall lo len P i,\n  lo <= i < lo + Z_of_nat len -> rangespec lo len P |-- P i * TT.\nProof.\n  intros. revert lo i H; induction len; intros.\n  + simpl in H. omega.\n  + simpl. intros; destruct (Z.eq_dec i lo).\n    - subst. cancel.\n    - replace (P i x * !!True) with (TT * (P i x * TT)) by (apply pred_ext; cancel).\n      apply sepcon_derives; [cancel |].\n      apply IHlen.\n      rewrite Nat2Z.inj_succ in H.\n      rewrite <- Z.add_1_l in *.\n      omega.\nQed.\n\nInductive Forallz {A} (P: Z -> A->Prop) : Z -> list A -> Prop :=\n | Forallz_nil : forall i, Forallz P i nil\n | Forallz_cons : forall i x l, P i x -> Forallz P (Z.succ i) l -> Forallz P i (x::l).\n\n(******************************************\n\nDefinition of aggregate predicates.\n\n******************************************)\n\nDefinition array_pred {A: Type} (default: A) (lo hi: Z) (P: Z -> A -> val -> mpred) (v: list A) (p: val) : mpred :=\n  !! (Zlength v = hi - lo) &&\n  rangespec lo (Z.to_nat (hi-lo)) (fun i => P i (Znth (i-lo) v default)) p.\n\nDefinition struct_pred (m: members) {A: ident * type -> Type} (P: forall it, A it -> val -> mpred) (v: compact_prod (map A m)) (p: val): mpred.\nProof.\n  destruct m as [| (i0, t0) m]; [exact emp |].\n  revert i0 t0 v; induction m as [| (i0, t0) m]; intros ? ? v.\n  + simpl in v.\n    exact (P _ v p).\n  + simpl in v.\n    exact ((P _ (fst v) p) * IHm i0 t0 (snd v)).\nDefined.\n\n(* when unfold, do cbv [struct_pred list_rect]. *)\n\nDefinition union_pred (m: members) {A: ident * type -> Type} (P: forall it, A it -> val -> mpred) (v: compact_sum (map A m)) (p: val): mpred.\nProof.\n  destruct m as [| (i0, t0) m]; [exact emp |].\n  revert i0 t0 v; induction m as [| (i0, t0) m]; intros ? ? v.\n  + simpl in v.\n    exact (P _ v p).\n  + simpl in v.\n    destruct v as [v | v].\n    - exact (P _ v p).\n    - exact (IHm i0 t0 v).\nDefined.\n\nDefinition array_Prop {A: Type} (d:A) (lo hi: Z) (P: Z -> A -> Prop) (v: list A) : Prop :=\n   Zlength v = hi-lo /\\ Forallz P 0 v.\n\nDefinition struct_Prop (m: members) {A: ident * type -> Type}\n                             (P: forall it, A it -> Prop) (v: compact_prod (map A m)) : Prop.\nProof.\n  destruct m as [| (i0, t0) m]; [exact True |].\n  revert i0 t0 v; induction m as [| (i0, t0) m]; intros ? ? v.\n  + simpl in v.\n    exact (P _ v).\n  + simpl in v.\n    exact ((P _ (fst v)) /\\ IHm i0 t0 (snd v)).\nDefined.\n\nDefinition union_Prop (m: members) {A: ident * type -> Type}\n               (P: forall it, A it -> Prop) (v: compact_sum (map A m)): Prop.\nProof.\n  destruct m as [| (i0, t0) m]; [exact True |].\n  revert i0 t0 v; induction m as [| (i0, t0) m]; intros ? ? v.\n  + simpl in v.\n    exact (P _ v).\n  + simpl in v.\n    destruct v as [v | v].\n    - exact (P _ v).\n    - exact (IHm i0 t0 v).\nDefined.\n\n(******************************************\n\nProperties\n\n******************************************)\n\nLemma array_pred_len_0: forall {A} (d: A) lo hi P p,\n  hi = lo ->\n  array_pred d lo hi P nil p = emp.\nProof.\n  intros.\n  unfold array_pred.\n  replace (Z.to_nat (hi - lo)) with 0%nat by (symmetry; apply nat_of_Z_neg; omega).\n  simpl.\n  rewrite prop_true_andp by (unfold Zlength; simpl; omega).\n  reflexivity.\nQed.\n\nLemma array_pred_len_1: forall {A} (d: A) i P v p,\n  array_pred d i (i + 1) P (v :: nil) p = P i v p.\nProof.\n  intros.\n  unfold array_pred.\n  replace (i + 1 - i) with 1 by omega.\n  simpl. rewrite sepcon_emp.\n  rewrite prop_true_andp by (unfold Zlength; simpl; omega).\n  unfold Znth. rewrite Z.sub_diag. rewrite if_false by omega. change (Z.to_nat 0) with 0%nat. auto.\nQed.\n\nLemma split_array_pred: forall {A}  (d: A) lo mid hi P v p,\n  lo <= mid <= hi ->\n  Zlength v = hi - lo ->\n  array_pred d lo hi P v p =\n  array_pred d lo mid P (sublist 0 (mid-lo) v) p *\n  array_pred d mid hi P (sublist (mid-lo) (hi-lo) v) p.\nProof.\n  intros.\n  unfold array_pred.\n  normalize.\n  rewrite prop_true_andp by (rewrite !Zlength_sublist by omega; omega).\n  clear H0.\n  remember (Z.to_nat (mid-lo)) as n.\n  replace (Z.to_nat (hi-lo)) with (n + Z.to_nat (hi-mid))%nat in *\n    by (subst n; rewrite <- Z2Nat.inj_add by omega; f_equal; omega).\n  assert (lo = mid - Z.of_nat n)\n    by (rewrite Heqn; rewrite Z2Nat.id by omega; omega).\n  clear Heqn.\n  revert lo v H H0; induction n; intros.\n  + subst lo.\n    change (Z.of_nat 0) with 0 in *.\n    simpl rangespec at 2. rewrite emp_sepcon.\n    rewrite Z.sub_0_r, Z.sub_diag, plus_0_l.\n    apply rangespec_ext; intros.\n    rewrite Z2Nat.id in H0 by omega.\n    f_equal.\n    rewrite Znth_sublist, Z.add_0_r by omega.\n    reflexivity.\n  + simpl plus at 1.\n    unfold rangespec; fold rangespec.\n    repeat match goal with |- context [(?A * ?B) p] => change ((A*B)p) with (A p * B p) end.\n    rewrite !sepcon_assoc.\n    f_equal.\n    - f_equal.\n      rewrite Z.sub_diag.\n      subst lo.\n      rewrite Znth_sublist by (try rewrite Nat2Z.inj_succ; omega).\n      reflexivity.\n    - replace (rangespec (Z.succ lo) (n + Z.to_nat (hi - mid))\n              (fun i : Z => P i (Znth (i - lo) v d)) p)\n      with (rangespec (Z.succ lo) (n + Z.to_nat (hi - mid))\n              (fun i : Z => P i (Znth (i - Z.succ lo) (skipn 1 v) d)) p).\n      Focus 2. {\n        apply rangespec_ext; intros.\n        f_equal.\n        rewrite <- Znth_succ by omega; auto.\n      } Unfocus.\n      rewrite Nat2Z.inj_succ in H0.\n      rewrite IHn by omega.\n      f_equal.\n      * apply rangespec_ext; intros.\n        f_equal.\n        rewrite Znth_sublist, Z.add_0_r by omega.\n        rewrite <- Znth_succ by omega; auto.\n        rewrite Znth_sublist, Z.add_0_r by omega.\n        reflexivity.\n      * apply rangespec_ext; intros.\n        f_equal.\n        rewrite Z2Nat.id in H1 by omega.\n        rewrite Znth_sublist by omega.\n        rewrite Znth_sublist by omega.\n        replace (i - mid + (mid - Z.succ lo)) with (i - Z.succ lo) by omega.\n        rewrite <- Znth_succ by omega; auto.\n         f_equal; omega.\nQed.\n\nLemma array_pred_shift: forall {A} (d: A) (lo hi lo' hi' mv : Z) P' P v p,\n  lo - lo' = mv ->\n  hi - hi' = mv ->\n (forall i i', lo <= i < hi -> i - i' = mv -> P' i' (Znth (i-lo) v d) p = P i (Znth (i-lo) v d) p) ->\n  array_pred d lo' hi' P' v p = array_pred d lo hi P v p.\nProof.\n  intros.\n  unfold array_pred.\n  apply andp_prop_ext; [omega | intros].\n  replace (hi' - lo') with (hi - lo) by omega.\n  destruct (zlt hi lo). rewrite Z2Nat_neg by omega. reflexivity.\n  apply pred_ext; apply rangespec_shift_derives; intros.\n  rewrite H4; rewrite Z2Nat.id in H3 by omega.\n  rewrite H1; auto; omega.\n  rewrite <- H4; rewrite Z2Nat.id in H3 by omega.\n  rewrite H1; auto; omega.\nQed.\n\nLemma array_pred_ext_derives: forall {A B} (dA: A) (dB: B) lo hi P0 P1 v0 v1 p,\n  (Zlength v0 = hi - lo -> Zlength v1 = hi - lo) ->\n  (forall i, lo <= i < hi ->\n    P0 i (Znth (i-lo) v0 dA) p |-- P1 i (Znth (i-lo) v1 dB) p) ->\n  array_pred dA lo hi P0 v0 p |-- array_pred dB lo hi P1 v1 p.\nProof.\n  intros.\n  unfold array_pred.\n  normalize.\n  rewrite prop_true_andp by omega.\n  apply rangespec_ext_derives.\n  intros.\n  destruct (zlt hi lo).\n  + rewrite Z2Nat_neg  in H2 by omega.\n    change (Z.of_nat 0) with 0 in H2. omega.\n  + rewrite Z2Nat.id in H2 by omega.\n    apply H0. omega.\nQed.\n\nLemma array_pred_ext: forall {A B} (dA: A) (dB: B) lo hi P0 P1 v0 v1 p,\n  Zlength v0 = Zlength v1 ->\n  (forall i, lo <= i < hi ->\n    P0 i (Znth (i-lo) v0 dA) p = P1 i (Znth (i-lo) v1 dB) p) ->\n  array_pred dA lo hi P0 v0 p = array_pred dB lo hi P1 v1 p.\nProof.\n  intros; apply pred_ext; apply array_pred_ext_derives; intros; try omega;\n  rewrite H0; auto.\nQed.\n\nLemma at_offset_array_pred: forall  {A} (d:A) lo hi P v ofs p,\n  at_offset (array_pred d lo hi P v) ofs p = array_pred d lo hi (fun i v => at_offset (P i v) ofs) v p.\nProof.\n  intros.\n  rewrite at_offset_eq.\n  unfold array_pred.\n  f_equal.\n  apply rangespec_shift.\n  intros.\n  assert (i = i') by omega; subst i'; clear H0.\n  rewrite at_offset_eq.\n  auto.\nQed.\n\nLemma array_pred_sepcon: forall  {A} (d:A) lo hi P Q v p,\n  array_pred d lo hi P v p * array_pred d lo hi Q v p = array_pred d lo hi (P * Q) v p.\nProof.\n  intros.\n  unfold array_pred.\n  normalize.\n  apply andp_prop_ext; [omega | intros].\n  rewrite rangespec_sepcon.\n  auto.\nQed.\n\nOpaque member_dec.\n\nLemma struct_pred_ext_derives: forall m {A0 A1} (P0: forall it, A0 it -> val -> mpred) (P1: forall it, A1 it -> val -> mpred) v0 v1 p,\n  members_no_replicate m = true ->\n  (forall i d0 d1, in_members i m ->\n     P0 _ (proj_struct i m v0 d0) p |-- P1 _ (proj_struct i m v1 d1) p) ->\n  struct_pred m P0 v0 p |-- struct_pred m P1 v1 p.\nProof.\n  unfold proj_struct, field_type.\n  intros.\n  destruct m as [| (i0, t0) m]; [simpl; auto |].\n  revert i0 t0 v0 v1 H H0; induction m as [| (i1, t1) m]; intros.\n  + specialize (H0 i0).\n    simpl in H0.\n    if_tac in H0; [| congruence].\n    specialize (H0 v0 v1).\n    spec H0; [left; reflexivity |].\n    destruct (member_dec (i0, t0) (i0, t0)); [| congruence].\n    unfold eq_rect_r in H0; rewrite <- !eq_rect_eq in H0.\n    simpl.\n    exact H0.\n  + change (struct_pred ((i0, t0) :: (i1, t1) :: m) P0 v0 p) with\n      (P0 (i0, t0) (fst v0) p * struct_pred ((i1, t1) :: m) P0 (snd v0) p).\n    change (struct_pred ((i0, t0) :: (i1, t1) :: m) P1 v1 p) with\n      (P1 (i0, t0) (fst v1) p * struct_pred ((i1, t1) :: m) P1 (snd v1) p).\n    apply sepcon_derives.\n    - specialize (H0 i0).\n      simpl in H0.\n      if_tac in H0; [| congruence].\n      specialize (H0 (fst v0) (fst v1)).\n      spec H0; [left; reflexivity |].\n      destruct (member_dec (i0, t0) (i0, t0)); [| congruence].\n      unfold eq_rect_r in H0; rewrite <- !eq_rect_eq in H0.\n      simpl.\n      exact H0.\n    - rewrite members_no_replicate_ind in H.\n      apply IHm; [tauto |].\n      intros.\n      specialize (H0 i).\n      simpl in H0.\n      if_tac in H0.\n      * clear - H H1 H2.\n        subst.\n        tauto.\n      * specialize (H0 d0 d1).\n        spec H0; [right; auto |].\n        change (if ident_eq i i1\n                then Errors.OK t1\n                else Ctypes.field_type i m) with (Ctypes.field_type i ((i1, t1) :: m)) in H0.\n        destruct (member_dec\n             (i,\n             match Ctypes.field_type i ((i1, t1) :: m) with\n             | Errors.OK t => t\n             | Errors.Error _ => Tvoid\n             end) (i0, t0)); [congruence |].\n        exact H0.\nQed.\n\nLemma struct_pred_ext: forall m {A0 A1} (P0: forall it, A0 it -> val -> mpred) (P1: forall it, A1 it -> val -> mpred) v0 v1 p,\n  members_no_replicate m = true ->\n  (forall i d0 d1, in_members i m ->\n     P0 _ (proj_struct i m v0 d0) p = P1 _ (proj_struct i m v1 d1) p) ->\n  struct_pred m P0 v0 p = struct_pred m P1 v1 p.\nProof.\n  intros.\n  apply pred_ext; eapply struct_pred_ext_derives; eauto;\n  intros; erewrite H0 by eauto; auto.\nQed.\n\nLemma struct_pred_not_member: forall m {A} (P: forall it, A it -> val -> mpred) (i: ident) v p,\n  let P' it := if ident_eq i (fst it) then fun _ _ => emp else P it in\n  ~ in_members i m ->\n  struct_pred m P v p = struct_pred m P' v p.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [auto |].\n  unfold proj_struct, field_type in *.\n  revert i0 t0 H v; induction m as [| (i1, t1) m]; intros i0 t0 H.\n  + intros; subst P'; simpl.\n    rewrite if_false; auto.\n    intro; apply H; subst; left; auto.\n  + set (M := (i1, t1) :: m).\n    simpl compact_prod; simpl Ctypes.field_type.\n    intros v.\n    subst M.\n    change (struct_pred ((i0, t0) :: (i1, t1) :: m) P v p)\n      with (P _ (fst v) p * struct_pred ((i1, t1) :: m) P (snd v) p).\n    change (struct_pred ((i0, t0) :: (i1, t1) :: m) P' v p)\n      with (P' _ (fst v) p * struct_pred ((i1, t1) :: m) P' (snd v) p).\n    destruct (ident_eq i i0).\n    - subst P'; intros; subst.\n      exfalso; apply H.\n      left; auto.\n    - intros.\n      f_equal.\n      * unfold P'.\n        rewrite if_false by auto.\n        auto.\n      * apply IHm.\n        intro; apply H; right; auto.\nQed.\n\nLemma struct_pred_proj: forall m {A} (P: forall it, A it -> val -> mpred) (i: ident) v p d,\n  let P' it := if ident_eq i (fst it) then fun _ _ => emp else P it in\n  members_no_replicate m = true ->\n  in_members i m ->\n  struct_pred m P v p = P _ (proj_struct i m v d) p * struct_pred m P' v p.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [inv H0 |].\n  unfold proj_struct, field_type in *.\n  revert i0 t0 H v d H0; induction m as [| (i1, t1) m]; intros.\n  + subst P'; simpl in *.\n    destruct H0; [simpl in H0; subst i | tauto].\n    destruct (ident_eq i0 i0); [| congruence].\n    destruct (member_dec (i0, t0) (i0, t0)); [| congruence].\n    unfold eq_rect_r; rewrite <- eq_rect_eq.\n    rewrite sepcon_emp; auto.\n  + pose proof H.\n    apply members_no_replicate_ind in H1; destruct H1.\n    set (M := (i1, t1) :: m).\n    simpl compact_prod in v |- *; simpl Ctypes.field_type in d |- *.\n    subst M.\n    change (struct_pred ((i0, t0) :: (i1, t1) :: m) P v p)\n      with (P _ (fst v) p * struct_pred ((i1, t1) :: m) P (snd v) p).\n    change (struct_pred ((i0, t0) :: (i1, t1) :: m) P' v p)\n      with (P' _ (fst v) p * struct_pred ((i1, t1) :: m) P' (snd v) p).\n    destruct (ident_eq i i0).\n    - subst i0.\n      f_equal.\n      * simpl.\n        destruct (member_dec (i, t0) (i, t0)); [| congruence].\n        unfold eq_rect_r; rewrite <- eq_rect_eq.\n        auto.\n      * erewrite struct_pred_not_member by eauto.\n        unfold P' at 1.\n        rewrite if_true by auto.\n        rewrite emp_sepcon; auto.\n    - intros.\n      destruct H0; [simpl in H0; congruence |].\n      rewrite <- sepcon_assoc, (sepcon_comm _ (P' _ _ _)), sepcon_assoc.\n      f_equal.\n      * unfold P'.\n        rewrite if_false by (simpl; congruence).\n        auto.\n      * erewrite IHm by eauto.\n        f_equal.\n        simpl.\n        match goal with\n        | |- context [member_dec (i, ?t') (i0, t0)] =>\n                destruct (member_dec (i, t') (i0, t0));\n                  [inversion e; congruence |]\n        end.\n        auto.\nQed.\n\nLemma struct_pred_upd: forall m {A} (P: forall it, A it -> val -> mpred) (i: ident) v p v0,\n  let P' it := if ident_eq i (fst it) then fun _ _ => emp else P it in\n  members_no_replicate m = true ->\n  in_members i m ->\n  struct_pred m P (upd_struct i m v v0) p = P _ v0 p * struct_pred m P' v p.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [inv H0 |].\n  unfold proj_struct, field_type in *.\n  revert i0 t0 H v v0 H0; induction m as [| (i1, t1) m]; intros.\n  + subst P'; simpl in *.\n    destruct H0; [simpl in H0; subst i | tauto].\n    destruct (ident_eq i0 i0); [| congruence].\n    destruct (member_dec (i0, t0) (i0, t0)); [| congruence].\n    unfold eq_rect_r; rewrite <- eq_rect_eq.\n    rewrite sepcon_emp; auto.\n  + pose proof H.\n    apply members_no_replicate_ind in H1; destruct H1.\n    simpl compact_prod in v |- *; simpl Ctypes.field_type in v0 |- *.\n    set (v' := (upd_struct i ((i0, t0) :: (i1, t1) :: m) v v0)).\n    change (struct_pred ((i0, t0) :: (i1, t1) :: m) P v' p)\n      with (P _ (fst v') p * struct_pred ((i1, t1) :: m) P (snd v') p).\n    change (struct_pred ((i0, t0) :: (i1, t1) :: m) P' v p)\n      with (P' _ (fst v) p * struct_pred ((i1, t1) :: m) P' (snd v) p).\n    subst v'.\n    simpl upd_struct.\n    destruct (ident_eq i i0).\n    - subst i0.\n      destruct (member_dec (i, t0) (i, t0)); [| congruence].\n      f_equal.\n      * simpl.\n        unfold eq_rect_r; rewrite <- eq_rect_eq.\n        auto.\n      * unfold eq_rect_r; rewrite <- eq_rect_eq.\n        change (snd (v0, snd v)) with (snd v).\n        erewrite struct_pred_not_member by eauto.\n        unfold P' at 1.\n        rewrite if_true by auto.\n        rewrite emp_sepcon; auto.\n    - destruct H0; [simpl in H0; congruence |].\n      rewrite <- sepcon_assoc, (sepcon_comm _ (P' _ _ _)), sepcon_assoc.\n      match goal with\n      | |- context [member_dec (i, ?t') (i0, t0)] =>\n              destruct (member_dec (i, t') (i0, t0));\n                [inversion e; congruence |]\n      end.\n      f_equal.\n      * unfold P'; simpl.\n        rewrite if_false by (simpl; congruence).\n        auto.\n      * simpl snd.\n        simpl in IHm |- *; erewrite IHm by auto.\n        reflexivity.\nQed.\n\nLemma struct_pred_ramif: forall m {A} (P: forall it, A it -> val -> mpred) (i: ident) v p d,\n  in_members i m ->\n  members_no_replicate m = true ->\n  struct_pred m P v p |--\n    P _ (proj_struct i m v d) p *\n     (ALL v0: _, P _ v0 p -* struct_pred m P (upd_struct i m v v0) p).\nProof.\n  intros.\n  set (P' it := if ident_eq i (fst it) then fun _ _ => emp else P it).\n  apply RAMIF_Q.solve with (struct_pred m P' v p).\n  + apply derives_refl'.\n    apply struct_pred_proj; auto.\n  + intro v0.\n    apply derives_refl'.\n    symmetry; rewrite sepcon_comm.\n    apply struct_pred_upd; auto.\nQed.\n\nLemma at_offset_struct_pred: forall m {A} (P: forall it, A it -> val -> mpred) v p ofs,\n  at_offset (struct_pred m P v) ofs p = struct_pred m (fun it v => at_offset (P it v) ofs) v p.\nProof.\n  intros.\n  rewrite at_offset_eq.\n  destruct m as [| (i0, t0) m]; [auto |].\n  revert i0 t0 v; induction m as [| (i1, t1) m]; intros.\n  + simpl.\n    rewrite at_offset_eq.\n    auto.\n  + simpl.\n    rewrite at_offset_eq.\n    f_equal.\nQed.\n\nLemma corable_andp_struct_pred: forall m {A} (P: forall it, A it -> val -> mpred) v p Q,\n  corable Q ->\n  Q && struct_pred m P v p =\n  match m with\n  | nil => Q && emp\n  | _ => struct_pred m (fun it v p => Q && P it v p) v p\n  end.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [auto |].\n  revert i0 t0 v; induction m as [| (i1, t1) m]; intros.\n  + simpl.\n    auto.\n  + change (struct_pred ((i0, t0) :: (i1, t1) :: m) P v p)\n      with (P (i0, t0) (fst v) p * struct_pred ((i1, t1) :: m) P (snd v) p).\n    pattern Q at 1; rewrite <- (andp_dup Q).\n    rewrite andp_assoc.\n    rewrite <- corable_sepcon_andp1 by auto.\n    rewrite IHm.\n    rewrite <- corable_andp_sepcon1 by auto.\n    reflexivity.\nQed.\n\nLemma struct_pred_sepcon: forall m {A} (P Q: forall it, A it -> val -> mpred) v p,\n  struct_pred m P v p * struct_pred m Q v p = struct_pred m (fun it => P it * Q it) v p.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [| revert i0 t0 v; induction m as [| (i1, t1) m]; intros].\n  + simpl.\n    rewrite emp_sepcon; auto.\n  + simpl.\n    auto.\n  + change (struct_pred ((i0, t0) :: (i1, t1) :: m) P v p)\n      with (P (i0, t0) (fst v) p * struct_pred ((i1, t1) :: m) P (snd v) p).\n    change (struct_pred ((i0, t0) :: (i1, t1) :: m) Q v p)\n      with (Q (i0, t0) (fst v) p * struct_pred ((i1, t1) :: m) Q (snd v) p).\n    change (struct_pred ((i0, t0) :: (i1, t1) :: m) (fun it => P it * Q it) v p)\n      with (P (i0, t0) (fst v) p * Q (i0, t0) (fst v) p * struct_pred ((i1, t1) :: m) (fun it => P it * Q it) (snd v) p).\n    rewrite !sepcon_assoc; f_equal.\n    rewrite <- sepcon_assoc, (sepcon_comm _ (Q _ _ _)), sepcon_assoc; f_equal.\n    apply IHm.\nQed.\n\nLemma compact_sum_inj_eq_spec: forall {A} a0 a1 (l: list A) F0 F1 (v0: compact_sum (map F0 (a0 :: a1 :: l))) (v1: compact_sum (map F1 (a0 :: a1 :: l))) H,\n  ~ In a0 (a1 :: l) ->\n ((forall a, compact_sum_inj v0 a H <-> compact_sum_inj v1 a H) <->\n  match v0, v1 with\n  | inl _, inl _ => True\n  | inr v0, inr v1 => forall a, compact_sum_inj (v0: compact_sum (map F0 (a1 :: l))) a H <-> compact_sum_inj (v1: compact_sum (map F1 (a1 :: l))) a H\n  | _, _ => False\n  end).\nProof.\n  intros.\n  rename H0 into H_not_in.\n  destruct v0, v1.\n  + simpl.\n    firstorder.\n  + assert (~ (forall a : A,\n      iff\n        (@compact_sum_inj A F0 (@cons A a0 (@cons A a1 l))\n           (@inl (F0 a0) (compact_sum (@map A Type F0 (@cons A a1 l))) f) a H)\n        (@compact_sum_inj A F1 (@cons A a0 (@cons A a1 l))\n           (@inr (F1 a0) (compact_sum (@map A Type F1 (@cons A a1 l))) c) a H))); [| tauto].\n    intro.\n    specialize (H0 a0).\n    simpl in H0.\n    destruct (H a0 a0); [| congruence].\n    tauto.\n  + assert (~ (forall a : A,\n      iff\n        (@compact_sum_inj A F0 (@cons A a0 (@cons A a1 l))\n           (@inr (F0 a0) (compact_sum (@map A Type F0 (@cons A a1 l))) c) a H)\n        (@compact_sum_inj A F1 (@cons A a0 (@cons A a1 l))\n           (@inl (F1 a0) (compact_sum (@map A Type F1 (@cons A a1 l))) f) a H))); [| tauto].\n    intro.\n    specialize (H0 a0).\n    simpl in H0.\n    destruct (H a0 a0); [| congruence].\n    tauto.\n  + split; intros HH a; specialize (HH a).\n    - pose proof compact_sum_inj_in c a H.\n      pose proof compact_sum_inj_in c0 a H.\nOpaque In.\n      simpl in HH, H0, H1 |- *.\nTransparent In.\n      destruct (H a a0).\n      * subst.\n        tauto.\n      * tauto.\n    - simpl in HH |- *.\n      destruct (H a a0).\n      * tauto.\n      * tauto.\nQed.\n\nLemma union_pred_ext_derives: forall m {A0 A1} (P0: forall it, A0 it -> val -> mpred) (P1: forall it, A1 it -> val -> mpred) v0 v1 p,\n  members_no_replicate m = true ->\n  (forall it, members_union_inj v0 it <-> members_union_inj v1 it) ->\n  (forall i d0 d1, members_union_inj v0 (i, field_type i m) -> members_union_inj v1 (i, field_type i m) ->\n     P0 _ (proj_union i m v0 d0) p |-- P1 _ (proj_union i m v1 d1) p) ->\n  union_pred m P0 v0 p |-- union_pred m P1 v1 p.\nProof.\n  unfold members_union_inj, proj_union, field_type.\n  intros.\n  destruct m as [| (i0, t0) m]; [simpl; auto |].\n  revert i0 t0 v0 v1 H H0 H1; induction m as [| (i1, t1) m]; intros.\n  + specialize (H1 i0).\n    simpl in H1.\n    if_tac in H1; [| congruence].\n    specialize (H1 v0 v1).\n    spec H1; [if_tac; [auto | congruence] |].\n    spec H1; [if_tac; [auto | congruence] |].\n    destruct (member_dec (i0, t0) (i0, t0)); [| congruence].\n    unfold eq_rect_r in H1; rewrite <- !eq_rect_eq in H1.\n    simpl.\n    exact H1.\n  + rewrite compact_sum_inj_eq_spec in H0.\n    Focus 2. {\n      clear - H.\n      pose proof in_members_tail_no_replicate i0 _ _ _ H.\n      intro HH; apply in_map with (f := fst) in HH.\n      apply H0 in HH.\n      tauto.\n    } Unfocus.\n    destruct v0 as [v0 | v0], v1 as [v1 | v1]; try solve [inversion H0].\n    - specialize (H1 i0).\n      simpl in H1.\n      if_tac in H1; [| congruence].\n      specialize (H1 v0 v1).\n      spec H1; [if_tac; [auto | congruence] |].\n      spec H1; [if_tac; [auto | congruence] |].\n      destruct (member_dec (i0, t0) (i0, t0)); [| congruence].\n      unfold eq_rect_r in H1; rewrite <- !eq_rect_eq in H1.\n      simpl.\n      exact H1.\n    - rewrite members_no_replicate_ind in H.\n      apply IHm; [tauto | tauto |].\n      intros.\n      specialize (H1 i).\n      simpl in H1.\n      if_tac in H1. (* i = i0 vs i <> i0 *)\n      * clear - H H2 H4 t0.\n        pose proof compact_sum_inj_in v0 (i, field_type i ((i1, t1) :: m)) member_dec.\n        spec H0; [exact H2 |].\n        subst.\n        apply in_map with (f := fst) in H0.\n        unfold fst at 1 in H0.\n        tauto.\n      * specialize (H1 d0 d1).\n        change (if ident_eq i i1\n                then Errors.OK t1\n                else Ctypes.field_type i m) with (Ctypes.field_type i ((i1, t1) :: m)) in H1.\n        destruct (member_dec\n             (i,\n             match Ctypes.field_type i ((i1, t1) :: m) with\n             | Errors.OK t => t\n             | Errors.Error _ => Tvoid\n             end) (i0, t0)); [congruence |].\n        spec H1; [auto |].\n        spec H1; [auto |].\n        exact H1.\nQed.\n\nLemma union_pred_ext: forall m {A0 A1} (P0: forall it, A0 it -> val -> mpred) (P1: forall it, A1 it -> val -> mpred) v0 v1 p,\n  members_no_replicate m = true ->\n  (forall it, members_union_inj v0 it <-> members_union_inj v1 it) ->\n  (forall i d0 d1, members_union_inj v0 (i, field_type i m) -> members_union_inj v1 (i, field_type i m) ->\n     P0 _ (proj_union i m v0 d0) p = P1 _ (proj_union i m v1 d1) p) ->\n  union_pred m P0 v0 p = union_pred m P1 v1 p.\nProof.\n  intros.\n  assert (forall it, members_union_inj v1 it <-> members_union_inj v0 it)\n    by (intro it; specialize (H0 it); tauto).\n  apply pred_ext; eapply union_pred_ext_derives; auto;\n  intros; erewrite H1 by eauto; auto.\nQed.\n\nLemma union_pred_derives_const: forall m {A} (P: forall it, A it -> val -> mpred) p v R,\n  members_no_replicate m = true ->\n  m <> nil ->\n  (forall i (v: A (i, field_type i m)), in_members i m -> P _ v p |-- R) ->\n  union_pred m P v p |-- R.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [congruence |].\n  clear H0.\n  revert i0 t0 v H H1; induction m as [| (i1, t1) m]; intros.\n  + simpl.\n    specialize (H1 i0); simpl in H1.\n    destruct (ident_eq i0 i0); [| congruence].\n    apply H1; left; auto.\n  + destruct v; simpl.\n    - specialize (H1 i0); simpl in H1.\n      destruct (ident_eq i0 i0); [| congruence].\n      apply H1; left; auto.\n    - pose proof H.\n      rewrite members_no_replicate_ind in H; destruct H.\n      apply (IHm i1 t1); auto.\n      intros.\n      specialize (H1 i).\n      pose proof in_members_tail_no_replicate _ _ _ _ H0 H3.\n      simpl in H1; destruct (ident_eq i i0); [congruence |].\n      apply H1.\n      right; auto.\nQed.\n\nLemma union_pred_proj: forall m {A} (P: forall it, A it -> val -> mpred) (i: ident) v p d,\n  members_no_replicate m = true ->\n  in_members i m ->\n  (forall i' (v': A (i', field_type i' m)), in_members i' m -> P _ v' p |-- P _ d p) ->\n  union_pred m P v p |-- P _ (proj_union i m v d) p.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [inv H0 |].\n  revert i0 t0 v d H H0 H1; induction m as [| (i1, t1) m]; intros.\n  + destruct H0; [simpl in H0; subst i | tauto].\n    simpl in *.\n    destruct (ident_eq i0 i0); [| congruence].\n    destruct (member_dec (i0, t0) (i0, t0)); [| congruence].\n    unfold eq_rect_r; rewrite <- eq_rect_eq.\n    auto.\n  + pose proof H.\n    rewrite members_no_replicate_ind in H; destruct H.\n    simpl in *; destruct (ident_eq i i0), v.\n    - subst i.\n      destruct (member_dec (i0, t0) (i0, t0)); [| congruence].\n      unfold eq_rect_r; rewrite <- eq_rect_eq.\n      auto.\n    - subst i.\n      destruct (member_dec (i0, t0) (i0, t0)); [| congruence].\n      unfold eq_rect_r; rewrite <- eq_rect_eq.\n      apply (union_pred_derives_const ((i1, t1) :: m) P p y); [auto | congruence |].\n      intros.\n      specialize (H1 i).\n      pose proof in_members_tail_no_replicate _ _ _ _ H2 H4.\n      simpl in H1; destruct (ident_eq i i0); [congruence |].\n      apply H1.\n      right; auto.\n    - match goal with\n      | |- context [member_dec (i, ?t') (i0, t0)] =>\n              destruct (member_dec (i, t') (i0, t0));\n                [inversion e; congruence |]\n      end.\n      specialize (H1 i0).\n      destruct (ident_eq i0 i0); [| congruence].\n      apply H1.\n      left; auto.\n    - match goal with\n      | |- context [member_dec (i, ?t') (i0, t0)] =>\n              destruct (member_dec (i, t') (i0, t0));\n                [inversion e; congruence |]\n      end.\n      apply (IHm i1 t1); auto.\n      * destruct H0; [| auto].\n        simpl in H0; congruence.\n      * intros.\n        specialize (H1 i').\n        pose proof in_members_tail_no_replicate _ _ _ _ H2 H4.\n        simpl in H1; destruct (ident_eq i' i0); [congruence |].\n        apply H1.\n        right; auto.\nQed.\n\nLemma union_pred_upd: forall m {A} (P: forall it, A it -> val -> mpred) (i: ident) v p v0,\n  members_no_replicate m = true ->\n  in_members i m ->\n  union_pred m P (upd_union i m v v0) p = P _ v0 p.\nProof.\n  intros.\n  intros.\n  unfold upd_union, upd_compact_sum.\n  destruct (in_dec member_dec (i, field_type i m) m) as [?H | ?H];\n    [| apply in_members_field_type in H0; tauto].\n  clear v.\n  destruct m as [| (i0, t0) m]; [inv H0 |].\n  revert i0 t0 v0 H H0 H1; induction m as [| (i1, t1) m]; intros.\n  + simpl in *.\n    destruct H0; [simpl in H0; subst i | tauto].\n    destruct (ident_eq i0 i0); [| congruence].\n    destruct (member_dec (i0, t0) (i0, t0)); [| congruence].\n    unfold eq_rect_r; rewrite <- eq_rect_eq.\n    auto.\n  + destruct H0; [simpl in H0; subst i |].\n    - simpl in *.\n      destruct (ident_eq i0 i0); [| congruence].\n      destruct (member_dec (i0, t0) (i0, t0)); [| congruence].\n      unfold eq_rect_r; rewrite <- eq_rect_eq.\n      auto.\n    - simpl in *.\n      pose proof in_members_tail_no_replicate _ _ _ _ H H0.\n      destruct (ident_eq i i0); [congruence |].\n      match goal with\n      | |- context [member_dec (i, ?t') (i0, t0)] =>\n              destruct (member_dec (i, t') (i0, t0));\n                [inversion e; congruence |]\n      end.\n      rewrite members_no_replicate_ind in H; destruct H.\n      apply (IHm i1 t1); auto.\nQed.\n\nLemma union_pred_ramif: forall m {A} (P: forall it, A it -> val -> mpred) (i: ident) v p d,\n  (forall i' (v': A (i', field_type i' m)), in_members i' m -> P _ v' p |-- P _ d p) ->\n  in_members i m ->\n  members_no_replicate m = true ->\n  union_pred m P v p |--\n    P _ (proj_union i m v d) p *\n     (ALL v0: _, P _ v0 p -* union_pred m P (upd_union i m v v0) p).\nProof.\n  intros.\n  apply RAMIF_Q.solve with emp.\n  + rewrite sepcon_emp.\n    apply union_pred_proj; auto.\n  + intro v0.\n    rewrite emp_sepcon.\n    apply derives_refl'.\n    symmetry.\n    apply union_pred_upd; auto.\nQed.\n\nLemma at_offset_union_pred: forall m {A} (P: forall it, A it -> val -> mpred) v p ofs,\n  at_offset (union_pred m P v) ofs p = union_pred m (fun it v => at_offset (P it v) ofs) v p.\nProof.\n  intros.\n  rewrite at_offset_eq.\n  destruct m as [| (i0, t0) m]; [simpl; auto |].\n  revert i0 t0 v; induction m as [| (i1, t1) m]; intros.\n  + simpl.\n    rewrite at_offset_eq.\n    auto.\n  + simpl.\n    destruct v.\n    - rewrite at_offset_eq.\n      auto.\n    - apply IHm.\nQed.\n\nLemma andp_union_pred: forall m {A} (P: forall it, A it -> val -> mpred) v p Q,\n  Q && union_pred m P v p =\n  match m with\n  | nil => Q && emp\n  | _ => union_pred m (fun it v p => Q && P it v p) v p\n  end.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [auto |].\n  revert i0 t0 v; induction m as [| (i1, t1) m]; intros.\n  + simpl.\n    auto.\n  + destruct v.\n    - simpl.\n      auto.\n    - simpl.\n      apply IHm.\nQed.\n\nLemma union_pred_sepcon: forall m {A} (P Q: forall it, A it -> val -> mpred) v p,\n  union_pred m P v p * union_pred m Q v p = union_pred m (fun it => P it * Q it) v p.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [| revert i0 t0 v; induction m as [| (i1, t1) m]; intros].\n  + simpl.\n    rewrite sepcon_emp; auto.\n  + simpl.\n    auto.\n  + destruct v.\n    - simpl; auto.\n    - apply IHm.\nQed.\n\nLemma struct_Prop_compact_prod_gen: forall m (F: ident * type -> Type) (P: forall it, F it -> Prop) (f: forall it, F it),\n  members_no_replicate m = true ->\n  (forall i, in_members i m -> P (i, field_type i m) (f (i, field_type i m))) ->\n  struct_Prop m P (compact_prod_gen f m).\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [simpl; auto |].\n  revert i0 t0 H H0; induction m as [| (i1, t1) m]; intros.\n  + simpl.\n    specialize (H0 i0).\n    simpl in H0.\n    rewrite if_true in H0 by auto.\n    apply H0; left; auto.\n  + change (struct_Prop ((i0, t0) :: (i1, t1) :: m) P\n             (compact_prod_gen f ((i0, t0) :: (i1, t1) :: m)))\n    with (P (i0, t0) (f (i0, t0)) /\\\n            struct_Prop ((i1, t1) :: m) P (compact_prod_gen f ((i1, t1) :: m))).\n    split.\n    - specialize (H0 i0).\n      simpl in H0.\n      rewrite if_true in H0 by auto.\n      apply H0; left; auto.\n    - rewrite members_no_replicate_ind in H; destruct H.\n      apply (IHm i1 t1); auto.\n      intros.\n      specialize (H0 i).\n      simpl in H0.\n      destruct (ident_eq i i0); [subst; tauto |].\n      apply H0; right; auto.\nQed.\n\nLemma struct_Prop_proj: forall m (F: ident * type -> Type) (P: forall it, F it -> Prop) v i d,\n  in_members i m ->\n  struct_Prop m P v ->\n  P (i, field_type i m) (proj_struct i m v d).\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [inversion H |].\n  revert i0 t0 v d H H0; induction m as [| (i1, t1) m]; intros.\n  + inversion H; [simpl in H0; subst| tauto].\n    simpl in *.\n    destruct (ident_eq i0 i0); [| tauto].\n    destruct (member_dec (i0, t0) (i0, t0)); [| tauto].\n    unfold eq_rect_r; rewrite <- eq_rect_eq.\n    auto.\n  + destruct (ident_eq i i0).\n    - subst.\n      simpl in *.\n      destruct (ident_eq i0 i0); [| tauto].\n      destruct (member_dec (i0, t0) (i0, t0)); [| tauto].\n      unfold eq_rect_r; rewrite <- eq_rect_eq.\n      exact (proj1 H0).\n    - assert (in_members i ((i1, t1) :: m)) by (inversion H; [subst; tauto | auto]).\n      simpl in *.\n      destruct (ident_eq i i0); [tauto |].\n      destruct (member_dec\n         (i,\n         match\n           (if ident_eq i i1 then Errors.OK t1 else Ctypes.field_type i m)\n         with\n         | Errors.OK t => t\n         | Errors.Error _ => Tvoid\n         end) (i0, t0)); [inversion e; subst; tauto |].\n      apply IHm; auto.\n      exact (proj2 H0).\nQed.\n\nLemma union_Prop_compact_sum_gen: forall m (F: ident * type -> Type) (P: forall it, F it -> Prop) (f: forall it, F it),\n  members_no_replicate m = true ->\n  (forall i, in_members i m -> P (i, field_type i m) (f (i, field_type i m))) ->\n  union_Prop m P (compact_sum_gen (fun _ => true) f m).\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [simpl; auto |].\n  destruct m as [| (i1, t1) m].\n  + simpl.\n    specialize (H0 i0).\n    simpl in H0.\n    rewrite if_true in H0 by auto.\n    apply H0; left; auto.\n  + simpl.\n    specialize (H0 i0).\n    simpl in H0.\n    rewrite if_true in H0 by auto.\n    apply H0; left; auto.\nQed.\n\nLemma union_Prop_proj: forall m (F: ident * type -> Type) (P: forall it, F it -> Prop) v i d,\n  members_union_inj v (i, field_type i m) ->\n  union_Prop m P v ->\n  P (i, field_type i m) (proj_union i m v d).\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [inversion H |].\n  revert i0 t0 v d H H0; induction m as [| (i1, t1) m]; intros.\n  + simpl in H. if_tac in H; [| tauto].\n    inversion H1; subst i.\n    clear H1 H4.\n    simpl in *.\n    destruct (ident_eq i0 i0); [| tauto].\n    destruct (member_dec (i0, t0) (i0, t0)); [| tauto].\n    unfold eq_rect_r; rewrite <- eq_rect_eq.\n    auto.\n  + destruct (ident_eq i i0).\n    - subst.\n      simpl in *.\n      destruct (ident_eq i0 i0); [| tauto].\n      destruct (member_dec (i0, t0) (i0, t0)); [| tauto].\n      unfold eq_rect_r; rewrite <- eq_rect_eq.\n      destruct v; [| inversion H].\n      auto.\n    - assert (members_union_inj v (i, field_type i ((i1, t1) :: m))) by (simpl in H; destruct (ident_eq i i0); [tauto | auto]).\n      simpl in *.\n      destruct (ident_eq i i0); [tauto |].\n      destruct (member_dec\n         (i,\n         match\n           (if ident_eq i i1 then Errors.OK t1 else Ctypes.field_type i m)\n         with\n         | Errors.OK t => t\n         | Errors.Error _ => Tvoid\n         end) (i0, t0)); [inversion e; subst; tauto |].\n      destruct v; [tauto |].\n      apply IHm; auto.\nQed.\n\nLemma array_pred_local_facts: forall {A} (d: A) lo hi P v p Q,\n  (forall i x, lo <= i < hi -> P i x p |-- !! Q x) ->\n  array_pred d lo hi P v p |-- !! (Zlength v = hi - lo /\\ Forall Q v).\nProof.\n  intros.\n  unfold array_pred.\n  normalize.\n  rewrite prop_and; apply andp_right; [normalize |].\n  pose proof ZtoNat_Zlength v.\n  rewrite H0 in H1; symmetry in H1; clear H0.\n  revert hi lo H H1; induction v; intros.\n  + apply prop_right; constructor.\n  + replace (hi - lo) with (Z.succ (hi - Z.succ lo)) in * by omega.\n    assert (hi - Z.succ lo >= 0).\n    Focus 1. {\n      destruct (zlt (hi - Z.succ lo) 0); auto.\n      assert (Z.succ (hi - Z.succ lo) <= 0) by omega.\n      simpl length in H1.\n      destruct (zeq (Z.succ (hi - Z.succ lo)) 0);\n       [rewrite e in H1 | rewrite Z2Nat_neg in H1 by omega]; inv H1.\n    } Unfocus.\n    rewrite Z2Nat.inj_succ in H1 |- * by omega.\n    inv H1.\n    simpl rangespec.\n    replace (rangespec (Z.succ lo) (length v)\n              (fun i : Z => P i (Znth (i - lo) (a :: v) d)) p)\n    with (rangespec (Z.succ lo) (length v)\n            (fun i : Z => P i (Znth (i - Z.succ lo) v d)) p).\n    Focus 2. {\n      apply rangespec_ext; intros.\n      change v with (skipn 1 (a :: v)) at 1.\n      rewrite <- Znth_succ by omega.\n      auto.\n    } Unfocus.\n    rewrite H3.\n    eapply derives_trans; [apply sepcon_derives; [apply H | apply IHv; auto] |].\n    - omega.\n    - intros; apply H; omega.\n    - rewrite sepcon_prop_prop.\n      apply prop_derives; intros.\n      rewrite Z.sub_diag in H1; cbv in H1.\n      constructor; tauto.\nQed.\n\nLemma struct_pred_local_facts: forall m {A} (P: forall it, A it -> val -> mpred)v p (R: forall it, A it -> Prop),\n  members_no_replicate m = true ->\n  (forall i v0, in_members i m -> P (i, field_type i m) v0 p |-- !! R _ v0) ->\n  struct_pred m P v p |-- !! struct_Prop m R v.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [simpl; apply prop_right; auto |].\n  revert i0 t0 v H H0; induction m as [| (i1, t1) m]; intros.\n  + simpl.\n    specialize (H0 i0).\n    simpl in H0.\n    rewrite if_true in H0 by auto.\n    apply H0; left; auto.\n  + change (struct_Prop ((i0, t0) :: (i1, t1) :: m) R v)\n      with (R (i0, t0) (fst v) /\\ struct_Prop ((i1, t1) :: m) R (snd v)).\n    change (struct_pred ((i0, t0) :: (i1, t1) :: m) P v p)\n      with (P (i0, t0) (fst v) p * struct_pred ((i1, t1) :: m) P (snd v) p).\n    rewrite members_no_replicate_ind in H.\n\n    pose proof H0 i0.\n    simpl in H1.\n    if_tac in H1; [| congruence].\n    specialize (H1 (fst v)).\n    spec H1; [left; auto |].\n\n    specialize (IHm i1 t1 (snd v)).\n    spec IHm; [tauto |].\n    eapply derives_trans; [apply sepcon_derives; [apply H1 | apply IHm] |].\n    - intros.\n      specialize (H0 i).\n      simpl in H0.\n      destruct (ident_eq i i0); [subst; tauto |].\n      apply H0; right; auto.\n    - rewrite sepcon_prop_prop; normalize.\nQed.\n\nLemma union_pred_local_facts: forall m {A} (P: forall it, A it -> val -> mpred)v p (R: forall it, A it -> Prop),\n  members_no_replicate m = true ->\n  (forall i v0, in_members i m -> P (i, field_type i m) v0 p |-- !! R _ v0) ->\n  union_pred m P v p |-- !! union_Prop m R v.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [simpl; apply prop_right; auto |].\n  revert i0 t0 v H H0; induction m as [| (i1, t1) m]; intros.\n  + simpl.\n    specialize (H0 i0).\n    simpl in H0.\n    rewrite if_true in H0 by auto.\n    apply H0; left; auto.\n  + rewrite members_no_replicate_ind in H.\n    destruct v.\n    - simpl.\n      pose proof H0 i0.\n      simpl in H1.\n      if_tac in H1; [| congruence].\n      specialize (H1 a).\n      apply H1; left; auto.\n    - specialize (IHm i1 t1 c).\n      spec IHm; [tauto |].\n      apply IHm.\n      intros.\n      specialize (H0 i).\n      simpl in H0.\n      destruct (ident_eq i i0); [subst; tauto |].\n      apply H0; right; auto.\nQed.\n\nSection MEMORY_BLOCK_AGGREGATE.\n\nContext {cs: compspecs}.\n\nLemma memory_block_array_pred: forall  {A} (d:A) sh t lo hi v b ofs,\n  0 <= ofs + sizeof t * lo /\\ ofs + sizeof t * hi < Ptrofs.modulus ->\n  0 <= lo <= hi ->\n  Zlength v = hi - lo ->\n  array_pred d lo hi\n    (fun i _ p => memory_block sh (sizeof t) (offset_val (sizeof t * i) p)) v\n    (Vptr b (Ptrofs.repr ofs)) =\n   memory_block sh (sizeof t * (hi - lo)) (Vptr b (Ptrofs.repr (ofs + sizeof t * lo))).\nProof.\n  intros.\n  unfold array_pred.\n  rewrite prop_true_andp by auto; clear H1.\n  f_equal.\n  remember (Z.to_nat (hi - lo)) as n eqn:HH.\n  revert lo HH H H0 v; induction n; intros.\n  + simpl.\n    pose proof arith_aux00 _ _ (proj2 H0) HH.\n    rewrite H1, Z.mul_0_r, memory_block_zero_Vptr.\n    reflexivity.\n  + simpl.\n    pose proof arith_aux01 _ _ _ HH.\n    solve_mod_modulus.\n    pose_size_mult cenv_cs t (0 :: hi - Z.succ lo :: hi - lo :: nil).\n    rewrite IHn; [| apply arith_aux02; auto | omega | omega | exact v].\n    replace (ofs + sizeof  t * Z.succ lo) with (ofs + sizeof t * lo + sizeof t) by omega.\n    rewrite <- memory_block_split by (auto; omega).\n    f_equal.\n    omega.\nQed.\n\nLemma memory_block_array_pred': forall {A} (d:A)  sh t z b ofs,\n  0 <= z ->\n  0 <= ofs /\\ ofs + sizeof t * z < Ptrofs.modulus ->\n  array_pred d 0 z\n     (fun i _ p =>\n      memory_block sh (sizeof t) (offset_val (sizeof t * i) p))\n             (list_repeat (Z.to_nat z) d)\n     (Vptr b (Ptrofs.repr ofs))  =\n  memory_block sh (sizeof t * z) (Vptr b (Ptrofs.repr ofs)).\nProof.\n  intros.\n  rewrite memory_block_array_pred.\n  f_equal. f_equal. omega. f_equal. f_equal. rewrite Z.mul_0_r. omega.\n  rewrite Z.mul_0_r. split; omega. omega.\n  rewrite Z.sub_0_r. auto. rewrite Zlength_list_repeat', Z2Nat.id by omega.\n  omega.\nQed.\n\nLemma memory_block_struct_pred: forall sh m sz {A} (v: compact_prod (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  members_no_replicate m = true ->\n  sizeof_struct cenv_cs 0 m <= sz < Ptrofs.modulus ->\n  0 <= ofs /\\ ofs + sz < Ptrofs.modulus ->\n  struct_pred m\n   (fun it _ p =>\n     (memory_block sh (field_offset_next cenv_cs (fst it) m sz - field_offset cenv_cs (fst it) m))\n     (offset_val (field_offset cenv_cs (fst it) m) p)) v (Vptr b (Ptrofs.repr ofs)) =\n  memory_block sh sz (Vptr b (Ptrofs.repr ofs)).\nProof.\n  unfold field_offset, Ctypes.field_offset, field_offset_next.\n  intros sh m sz A v b ofs NIL_CASE NO_REPLI; intros.\n  destruct m as [| (i0, t0) m].\n  1: rewrite (NIL_CASE eq_refl), memory_block_zero; simpl; normalize.\n  assert (align 0 (alignof t0) = 0) by apply align_0, alignof_pos.\n  revert H0; pattern ofs at 1 4; replace ofs with (ofs + align 0 (alignof t0)) by omega; intros.\n  revert H; pattern sz at 2 4; replace sz with (sz - align 0 (alignof t0)) by omega; intros.\n  pattern 0 at 1; rewrite <- H1.\n  clear NIL_CASE H1.\n  revert H H0; generalize 0 at 1 2 4 5 6 8 10 11; revert i0 t0 v NO_REPLI;\n  induction m as [| (i1, t1) m]; intros.\n  + simpl.\n    if_tac; [| congruence].\n    solve_mod_modulus.\n    reflexivity.\n  + match goal with\n    | |- struct_pred ((i0, t0) :: (i1, t1) :: m) ?P v ?p = _ =>\n           change (struct_pred ((i0, t0) :: (i1, t1) :: m) P v p) with\n             (P (i0, t0) (fst v) p * struct_pred ((i1, t1) :: m) P (snd v) p);\n           simpl (P (i0, t0) (fst v) p)\n    end.\n    if_tac; [| congruence].\n    solve_mod_modulus.\n    erewrite struct_pred_ext.\n    - rewrite members_no_replicate_ind in NO_REPLI; destruct NO_REPLI as [NOT_IN NO_REPLI].\n      rewrite IHm with (z := align z (alignof t0) + sizeof t0);\n        [| now auto\n         | simpl in H |- *; pose_align_le; pose_sizeof_pos; omega\n         | pose_align_le; pose_sizeof_pos; omega].\n      replace (ofs + align (align z (alignof t0) + sizeof t0) (alignof t1)) with\n        (ofs + align z (alignof t0) +\n         (align (align z (alignof t0) + sizeof t0) (alignof t1) -\n          align z (alignof t0))) by omega.\n      rewrite <- memory_block_split by\n        (simpl in H; revert H; pose_align_le; pose_sizeof_pos; intros; omega).\n      f_equal; omega.\n    - rewrite members_no_replicate_ind in NO_REPLI; destruct NO_REPLI as [NOT_IN NO_REPLI].\n      auto.\n    - intros. instantiate (1 := (snd v)).\n      solve_mod_modulus.\n      unfold fst.\n      pose proof in_members_tail_no_replicate _ _ _ _ NO_REPLI H2.\n      rewrite (neq_field_offset_rec_cons cenv_cs i i0 t0) by auto.\n      rewrite (neq_field_offset_next_rec_cons cenv_cs i i0 t0) by auto.\n      reflexivity.\nQed.\n\nLemma memory_block_union_pred: forall sh m sz {A} (v: compact_sum (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  union_pred m (fun it _ => memory_block sh sz) v (Vptr b (Ptrofs.repr ofs)) =\n  memory_block sh sz (Vptr b (Ptrofs.repr ofs)).\nProof.\n  intros sh m sz A v b ofs NIL_CASE; intros.\n  destruct m as [| (i0, t0) m].\n  1: rewrite (NIL_CASE eq_refl), memory_block_zero; simpl; normalize.\n  clear NIL_CASE.\n  revert i0 t0 v; induction m as [| (i1, t1) m]; intros.\n  + simpl; auto.\n  + destruct v.\n    - simpl; auto.\n    - apply IHm.\nQed.\n\nEnd MEMORY_BLOCK_AGGREGATE.\n\nModule aggregate_pred.\n\nOpen Scope Z.\nOpen Scope logic.\n\n\nDefinition array_pred: forall {A: Type} (d:A) (lo hi: Z) (P: Z -> A -> val -> mpred) (v: list A),\n    val -> mpred := @array_pred.\n\nDefinition struct_pred: forall (m: members) {A: ident * type -> Type} (P: forall it, A it -> val -> mpred) (v: compact_prod (map A m)) (p: val), mpred := @struct_pred.\n\nDefinition union_pred: forall (m: members) {A: ident * type -> Type} (P: forall it, A it -> val -> mpred) (v: compact_sum (map A m)) (p: val), mpred := @union_pred.\n\nDefinition array_Prop: forall {A: Type} (d:A) (lo hi: Z) (P: Z -> A -> Prop) (v: list A), Prop := @array_Prop.\n\nDefinition struct_Prop: forall (m: members) {A: ident * type -> Type} (P: forall it, A it -> Prop) (v: compact_prod (map A m)), Prop := @struct_Prop.\n\nDefinition union_Prop: forall (m: members) {A: ident * type -> Type} (P: forall it, A it -> Prop) (v: compact_sum (map A m)), Prop := union_Prop.\n\nDefinition array_pred_len_0: forall {A} (d:A) lo hi P p,\n  hi = lo ->\n  array_pred d lo hi P nil p = emp\n:= @array_pred_len_0.\n\nDefinition array_pred_len_1: forall {A} (d:A) i P v p,\n  array_pred d i (i + 1) P (v :: nil) p =  P i v p\n:= @array_pred_len_1.\n\nDefinition split_array_pred: forall  {A} (d:A) lo mid hi P v p,\n  lo <= mid <= hi ->\n  Zlength v = (hi-lo) ->\n  array_pred d lo hi P v p =\n  array_pred d lo mid P (sublist 0 (mid-lo) v) p *\n  array_pred d mid hi P (sublist (mid-lo) (hi-lo) v) p\n:= @split_array_pred.\n\nDefinition array_pred_shift: forall {A} (d:A) lo hi lo' hi' mv P' P v p,\n  lo - lo' = mv ->\n  hi - hi' = mv ->\n  (forall i i', lo <= i < hi -> i - i' = mv -> P' i' (Znth (i - lo) v d) p = P i (Znth (i - lo) v d) p) ->\n  array_pred d lo' hi' P' v p = array_pred d lo hi P v p\n:= @array_pred_shift.\n\nDefinition array_pred_ext_derives:\n  forall {A B} (dA:A) (dB:B) lo hi P0 P1 v0 v1 p,\n  (Zlength v0 = hi - lo -> Zlength v1 = hi - lo) ->\n  (forall i, lo <= i < hi ->\n      P0 i (Znth (i-lo) v0 dA) p |-- P1 i (Znth (i-lo) v1 dB) p) ->\n  array_pred dA lo hi P0 v0 p |-- array_pred dB lo hi P1 v1 p\n:= @array_pred_ext_derives.\n\nDefinition array_pred_ext:\n  forall {A B} (dA:A) (dB:B) lo hi P0 P1 v0 v1 p,\n  Zlength v0 = Zlength v1 ->\n  (forall i, lo <= i < hi ->\n     P0 i (Znth (i - lo) v0 dA) p = P1 i (Znth (i - lo) v1 dB) p) ->\n  array_pred dA lo hi P0 v0 p = array_pred dB lo hi P1 v1 p\n:= @array_pred_ext.\n\nDefinition at_offset_array_pred: forall {A} (d:A) lo hi P v ofs p,\n  at_offset (array_pred d lo hi P v) ofs p = array_pred d lo hi (fun i v => at_offset (P i v) ofs) v p\n:= @at_offset_array_pred.\n\nDefinition array_pred_sepcon: forall  {A} (d:A) lo hi P Q v p,\n  array_pred d lo hi P v p * array_pred d lo hi Q v p = array_pred d lo hi (P * Q) v p\n:= @array_pred_sepcon.\n\nDefinition struct_pred_ramif: forall m {A} (P: forall it, A it -> val -> mpred) (i: ident) v p d,\n  in_members i m ->\n  members_no_replicate m = true ->\n  struct_pred m P v p |--\n    P _ (proj_struct i m v d) p *\n     allp ((fun v0: _ => P _ v0 p) -* (fun v0: _ => struct_pred m P (upd_struct i m v v0) p))\n:= @struct_pred_ramif.\n\nDefinition struct_pred_ext_derives:\n  forall m {A0 A1} (P0: forall it, A0 it -> val -> mpred) (P1: forall it, A1 it -> val -> mpred) v0 v1 p,\n  members_no_replicate m = true ->\n  (forall i d0 d1, in_members i m ->\n     P0 _ (proj_struct i m v0 d0) p |-- P1 _ (proj_struct i m v1 d1) p) ->\n  struct_pred m P0 v0 p |-- struct_pred m P1 v1 p\n:= @struct_pred_ext_derives.\n\nDefinition struct_pred_ext:\n  forall m {A0 A1} (P0: forall it, A0 it -> val -> mpred) (P1: forall it, A1 it -> val -> mpred) v0 v1 p,\n  members_no_replicate m = true ->\n  (forall i d0 d1, in_members i m ->\n     P0 _ (proj_struct i m v0 d0) p = P1 _ (proj_struct i m v1 d1) p) ->\n  struct_pred m P0 v0 p = struct_pred m P1 v1 p\n:= @struct_pred_ext.\n\nDefinition at_offset_struct_pred: forall m {A} (P: forall it, A it -> val -> mpred) v p ofs,\n  at_offset (struct_pred m P v) ofs p = struct_pred m (fun it v => at_offset (P it v) ofs) v p\n:= @at_offset_struct_pred.\n\nDefinition andp_struct_pred: forall m {A} (P: forall it, A it -> val -> mpred) v p Q,\n  corable Q ->\n  Q && struct_pred m P v p =\n  match m with\n  | nil => Q && emp\n  | _ => struct_pred m (fun it v p => Q && P it v p) v p\n  end\n:= @corable_andp_struct_pred.\n\nDefinition struct_pred_sepcon: forall m {A} (P Q: forall it, A it -> val -> mpred) v p,\n  struct_pred m P v p * struct_pred m Q v p = struct_pred m (fun it => P it * Q it) v p\n:= @struct_pred_sepcon.\n\nDefinition union_pred_ramif: forall m {A} (P: forall it, A it -> val -> mpred) (i: ident) v p d,\n  (forall i' (v': A (i', field_type i' m)), in_members i' m -> P _ v' p |-- P _ d p) ->\n  in_members i m ->\n  members_no_replicate m = true ->\n  union_pred m P v p |--\n    P _ (proj_union i m v d) p *\n     allp ((fun v0: _ => P _ v0 p) -* (fun v0 =>union_pred m P (upd_union i m v v0) p))\n:= @union_pred_ramif.\n\nDefinition union_pred_ext_derives:\n  forall m {A0 A1} (P0: forall it, A0 it -> val -> mpred) (P1: forall it, A1 it -> val -> mpred) v0 v1 p,\n  members_no_replicate m = true ->\n  (forall it, members_union_inj v0 it <-> members_union_inj v1 it) ->\n  (forall i d0 d1, members_union_inj v0 (i, field_type i m) -> members_union_inj v1 (i, field_type i m) ->\n     P0 _ (proj_union i m v0 d0) p |-- P1 _ (proj_union i m v1 d1) p) ->\n  union_pred m P0 v0 p |-- union_pred m P1 v1 p\n:= @union_pred_ext_derives.\n\nDefinition union_pred_ext:\n  forall m {A0 A1} (P0: forall it, A0 it -> val -> mpred) (P1: forall it, A1 it -> val -> mpred) v0 v1 p,\n  members_no_replicate m = true ->\n  (forall it, members_union_inj v0 it <-> members_union_inj v1 it) ->\n  (forall i d0 d1, members_union_inj v0 (i, field_type i m) -> members_union_inj v1 (i, field_type i m) ->\n     P0 _ (proj_union i m v0 d0) p = P1 _ (proj_union i m v1 d1) p) ->\n  union_pred m P0 v0 p = union_pred m P1 v1 p\n:= @union_pred_ext.\n\nDefinition at_offset_union_pred: forall m {A} (P: forall it, A it -> val -> mpred) v p ofs,\n  at_offset (union_pred m P v) ofs p = union_pred m (fun it v => at_offset (P it v) ofs) v p\n:= at_offset_union_pred.\n\nDefinition andp_union_pred: forall m {A} (P: forall it, A it -> val -> mpred) v p Q,\n  Q && union_pred m P v p =\n  match m with\n  | nil => Q && emp\n  | _ => union_pred m (fun it v p => Q && P it v p) v p\n  end\n:= @andp_union_pred.\n\nDefinition union_pred_sepcon: forall m {A} (P Q: forall it, A it -> val -> mpred) v p,\n  union_pred m P v p * union_pred m Q v p = union_pred m (fun it => P it * Q it) v p\n:= @union_pred_sepcon.\n\nDefinition struct_Prop_compact_prod_gen: forall m (F: ident * type -> Type) (P: forall it, F it -> Prop) (f: forall it, F it),\n  members_no_replicate m = true ->\n  (forall i, in_members i m -> P (i, field_type i m) (f (i, field_type i m))) ->\n  struct_Prop m P (compact_prod_gen f m)\n:= @struct_Prop_compact_prod_gen.\n\nDefinition struct_Prop_proj: forall m (F: ident * type -> Type) (P: forall it, F it -> Prop) v i d,\n  in_members i m ->\n  struct_Prop m P v ->\n  P (i, field_type i m) (proj_struct i m v d)\n:= @struct_Prop_proj.\n\nDefinition union_Prop_compact_sum_gen: forall m (F: ident * type -> Type) (P: forall it, F it -> Prop) (f: forall it, F it),\n  members_no_replicate m = true ->\n  (forall i, in_members i m -> P (i, field_type i m) (f (i, field_type i m))) ->\n  union_Prop m P (compact_sum_gen (fun _ => true) f m)\n:= @union_Prop_compact_sum_gen.\n\nDefinition union_Prop_proj: forall m (F: ident * type -> Type) (P: forall it, F it -> Prop) v i d,\n  members_union_inj v (i, field_type i m) ->\n  union_Prop m P v ->\n  P (i, field_type i m) (proj_union i m v d)\n:= @union_Prop_proj.\n\nDefinition array_pred_local_facts: forall {A} (d: A) lo hi P v p Q,\n  (forall i x, lo <= i < hi -> P i x p |-- !! Q x) ->\n  array_pred d lo hi P v p |-- !! (Zlength v = hi - lo /\\ Forall Q v)\n:= @array_pred_local_facts.\n\nDefinition struct_pred_local_facts: forall m {A} (P: forall it, A it -> val -> mpred)v p (R: forall it, A it -> Prop),\n  members_no_replicate m = true ->\n  (forall i v0, in_members i m -> P (i, field_type i m) v0 p |-- !! R _ v0) ->\n  struct_pred m P v p |-- !! struct_Prop m R v\n:= @struct_pred_local_facts.\n\nDefinition union_pred_local_facts: forall m {A} (P: forall it, A it -> val -> mpred)v p (R: forall it, A it -> Prop),\n  members_no_replicate m = true ->\n  (forall i v0, in_members i m -> P (i, field_type i m) v0 p |-- !! R _ v0) ->\n  union_pred m P v p |-- !! union_Prop m R v\n:= @union_pred_local_facts.\n\nEnd aggregate_pred.\n\nRequire Import VST.floyd.reptype_lemmas.\n\n(******************************************\n\nAuxiliary predicates\n\n******************************************)\n\nSection AUXILIARY_PRED.\n\nContext {cs: compspecs}.\n\nVariable sh: share.\n\nDefinition struct_data_at_rec_aux (m m0: members) (sz: Z) (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> (val -> mpred)) m)) (v: compact_prod (map (fun it => reptype (field_type (fst it) m0)) m)) : (val -> mpred).\nProof.\n  destruct m as [| (i0, t0) m]; [exact (fun _ => emp) |].\n  revert i0 t0 v P; induction m as [| (i0, t0) m]; intros ? ? v P.\n  + simpl in v, P.\n    inversion P; subst.\n    exact (withspacer sh\n            (field_offset cenv_cs i0 m0 + sizeof (field_type i0 m0))\n            (field_offset_next cenv_cs i0 m0 sz)\n            (at_offset (a v) (field_offset cenv_cs i0 m0))).\n  + simpl in v, P.\n    destruct (ident_eq i1 i1); [| congruence].\n    inversion P; subst.\n    exact (withspacer sh\n            (field_offset cenv_cs i1 m0 + sizeof (field_type i1 m0))\n            (field_offset_next cenv_cs i1 m0 sz)\n            (at_offset (a (fst v)) (field_offset cenv_cs i1 m0)) * IHm i0 t0 (snd v) b)%logic.\nDefined.\n\nDefinition union_data_at_rec_aux (m m0: members) (sz: Z) (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> (val -> mpred)) m)) (v: compact_sum (map (fun it => reptype (field_type (fst it) m0)) m)) : (val -> mpred).\nProof.\n  destruct m as [| (i0, t0) m]; [exact (fun _ => emp) |].\n  revert i0 t0 v P; induction m as [| (i0, t0) m]; intros ? ? v P.\n  + simpl in v, P.\n    inversion P; subst.\n    exact (withspacer sh (sizeof (field_type i0 m0)) sz (a v)).\n  + simpl in v, P.\n    inversion P; subst.\n    destruct v as [v | v].\n    - exact (withspacer sh (sizeof (field_type i1 m0)) sz (a v)).\n    - exact (IHm i0 t0 v b).\nDefined.\n\nLemma struct_data_at_rec_aux_spec: forall m m0 sz v P,\n  struct_data_at_rec_aux m m0 sz\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> val -> mpred)\n     P m) v =\n  struct_pred m\n   (fun it v =>\n      withspacer sh\n       (field_offset cenv_cs (fst it) m0 + sizeof (field_type (fst it) m0))\n       (field_offset_next cenv_cs (fst it) m0 sz)\n       (at_offset (P it v) (field_offset cenv_cs (fst it) m0))) v.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [reflexivity |].\n  revert i0 t0 v; induction m as [| (i0, t0) m]; intros.\n  + simpl; reflexivity.\n  + replace\n     (struct_data_at_rec_aux ((i1, t1) :: (i0, t0) :: m) m0 sz\n     (ListTypeGen (fun it : ident * type => reptype (field_type (fst it) m0) -> val -> mpred)\n        P ((i1, t1) :: (i0, t0) :: m)) v) with\n     (withspacer sh\n       (field_offset cenv_cs i1 m0 + sizeof (field_type i1 m0))\n         (field_offset_next cenv_cs i1 m0 sz)\n           (at_offset (P (i1, t1) (fst v)) (field_offset cenv_cs i1 m0)) *\n      struct_data_at_rec_aux ((i0, t0) :: m) m0 sz\n     (ListTypeGen (fun it : ident * type => reptype (field_type (fst it) m0) -> val -> mpred)\n        P ((i0, t0) :: m)) (snd v))%logic.\n    - rewrite IHm.\n      reflexivity.\n    - simpl.\n      destruct (ident_eq i1 i1); [| congruence].\n      reflexivity.\nQed.\n\nLemma union_data_at_rec_aux_spec: forall m m0 sz v P,\n  union_data_at_rec_aux m m0 sz\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> val -> mpred)\n     P m) v =\n  union_pred m\n   (fun it v =>\n      withspacer sh\n       (sizeof (field_type (fst it) m0))\n       sz\n       (P it v)) v.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [reflexivity |].\n  revert i0 t0 v; induction m as [| (i0, t0) m]; intros.\n  + simpl. unfold union_pred. simpl. reflexivity.\n  + destruct v as [v | v].\n    - reflexivity.\n    - match goal with\n      | _ => apply IHm\n      | _ => simpl ; f_equal ; apply IHm\n      end.\nQed.\n\nDefinition struct_value_fits_aux (m m0: members)\n      (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> Prop) m))\n      (v: compact_prod (map (fun it => reptype (field_type (fst it) m0)) m)) : Prop.\nProof.\n  destruct m as [| (i0, t0) m]; [exact True |].\n  revert i0 t0 v P; induction m as [| (i0, t0) m]; intros ? ? v P.\n  + simpl in v, P.\n    inversion P; subst.\n    apply (a v).\n  + simpl in v, P.\n    destruct (ident_eq i1 i1); [| congruence].\n    inversion P; subst.\n    apply (a (fst v) /\\ IHm i0 t0 (snd v) b).\nDefined.\n\nDefinition union_value_fits_aux (m m0: members)\n      (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> Prop) m))\n      (v: compact_sum (map (fun it => reptype (field_type (fst it) m0)) m)) : Prop.\nProof.\n  destruct m as [| (i0, t0) m]; [exact True |].\n  revert i0 t0 v P; induction m as [| (i0, t0) m]; intros ? ? v P.\n  + simpl in v, P.\n    inversion P; subst.\n    exact (a v).\n  + simpl in v, P.\n    inversion P; subst.\n    destruct v as [v | v].\n    - exact (a v).\n    - exact (IHm i0 t0 v b).\nDefined.\n\nLemma struct_value_fits_aux_spec: forall m m0 v P,\n  struct_value_fits_aux m m0\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> Prop)\n     P m) v =\n  struct_Prop m P v.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [reflexivity |].\n  revert i0 t0 v; induction m as [| (i0, t0) m]; intros.\n  + simpl; reflexivity.\n  + replace\n     (struct_value_fits_aux ((i1, t1) :: (i0, t0) :: m) m0\n     (ListTypeGen (fun it : ident * type => reptype (field_type (fst it) m0) -> Prop)\n        P ((i1, t1) :: (i0, t0) :: m)) v) with\n     (P (i1, t1) (fst v) /\\  struct_value_fits_aux ((i0, t0) :: m) m0\n     (ListTypeGen (fun it : ident * type => reptype (field_type (fst it) m0) -> Prop)\n        P ((i0, t0) :: m)) (snd v)).\n    - rewrite IHm.\n      reflexivity.\n    - simpl.\n      destruct (ident_eq i1 i1); [| congruence].\n      reflexivity.\nQed.\n\nLemma union_value_fits_aux_spec: forall m m0 v P,\n  union_value_fits_aux m m0\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> Prop)\n     P m) v =\n  union_Prop m P v.\nProof.\n  intros.\n  destruct m as [| (i0, t0) m]; [reflexivity |].\n  revert i0 t0 v; induction m as [| (i0, t0) m]; intros.\n  + simpl. unfold union_Prop. simpl. reflexivity.\n  + destruct v as [v | v].\n    - reflexivity.\n    - match goal with\n      | _ => apply IHm\n      | _ => simpl ; f_equal ; apply IHm\n      end.\nQed.\n\nEnd AUXILIARY_PRED.\n\nModule auxiliary_pred.\n\nImport aggregate_pred.\n\nDefinition struct_data_at_rec_aux:\n   forall {cs: compspecs} (sh: share) (m m0: members) (sz: Z) (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> (val -> mpred)) m)) (v: compact_prod (map (fun it => reptype (field_type (fst it) m0)) m)), (val -> mpred)\n:= @struct_data_at_rec_aux.\n\nDefinition union_data_at_rec_aux:\n  forall {cs: compspecs} (sh: share) (m m0: members) (sz: Z) (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> (val -> mpred)) m)) (v: compact_sum (map (fun it => reptype (field_type (fst it) m0)) m)), (val -> mpred)\n:= @union_data_at_rec_aux.\n\nDefinition struct_data_at_rec_aux_spec: forall {cs: compspecs} (sh: share) m m0 sz v P,\n  struct_data_at_rec_aux sh m m0 sz\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> val -> mpred)\n     P m) v =\n  struct_pred m\n   (fun it v =>\n      withspacer sh\n       (field_offset cenv_cs (fst it) m0 + sizeof (field_type (fst it) m0))\n       (field_offset_next cenv_cs (fst it) m0 sz)\n       (at_offset (P it v) (field_offset cenv_cs (fst it) m0))) v\n:= @struct_data_at_rec_aux_spec.\n\nDefinition union_data_at_rec_aux_spec: forall {cs: compspecs} sh m m0 sz v P,\n  union_data_at_rec_aux sh m m0 sz\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> val -> mpred)\n     P m) v =\n  union_pred m\n   (fun it v =>\n      withspacer sh\n       (sizeof (field_type (fst it) m0))\n       sz\n       (P it v)) v\n:= @union_data_at_rec_aux_spec.\n\nDefinition struct_value_fits_aux:\n  forall {cs: compspecs} (m m0: members)\n      (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> Prop) m))\n      (v: compact_prod (map (fun it => reptype (field_type (fst it) m0)) m)), Prop\n:= @struct_value_fits_aux.\n\nDefinition union_value_fits_aux:\n  forall {cs: compspecs} (m m0: members)\n      (P: ListType (map (fun it => reptype (field_type (fst it) m0) -> Prop) m))\n      (v: compact_sum (map (fun it => reptype (field_type (fst it) m0)) m)), Prop\n:= @union_value_fits_aux.\n\nDefinition struct_value_fits_aux_spec: forall {cs: compspecs} m m0 v P,\n  struct_value_fits_aux m m0\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> Prop)\n     P m) v =\n  struct_Prop m P v\n:= @struct_value_fits_aux_spec.\n\nDefinition union_value_fits_aux_spec: forall {cs: compspecs} m m0 v P,\n  union_value_fits_aux m m0\n   (ListTypeGen\n     (fun it => reptype (field_type (fst it) m0) -> Prop)\n     P m) v =\n  union_Prop m P v\n:= @union_value_fits_aux_spec.\n\nDefinition memory_block_array_pred:\n  forall {cs: compspecs} (A : Type) (d : A) sh t z b ofs,\n  0 <= z ->\n  0 <= ofs /\\ ofs + sizeof t * z < Ptrofs.modulus ->\n  array_pred d 0 z\n     (fun i _ p =>\n      memory_block sh (sizeof t)\n        (offset_val (sizeof t * i) p)) (list_repeat (Z.to_nat z) d)\n     (Vptr b (Ptrofs.repr ofs))  =\n  memory_block sh (sizeof t * z) (Vptr b (Ptrofs.repr ofs))\n:= @memory_block_array_pred'.\n\nDefinition memory_block_struct_pred:\n  forall {cs: compspecs} sh m sz {A} (v: compact_prod (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  members_no_replicate m = true ->\n  sizeof_struct cenv_cs 0 m <= sz < Ptrofs.modulus ->\n  0 <= ofs /\\ ofs + sz < Ptrofs.modulus ->\n  struct_pred m\n   (fun it _ p =>\n     (memory_block sh (field_offset_next cenv_cs (fst it) m sz - field_offset cenv_cs (fst it) m))\n     (offset_val (field_offset cenv_cs (fst it) m) p)) v (Vptr b (Ptrofs.repr ofs)) =\n  memory_block sh sz (Vptr b (Ptrofs.repr ofs))\n:= @memory_block_struct_pred.\n\nDefinition memory_block_union_pred:\n  forall sh m sz {A} (v: compact_sum (map A m)) b ofs,\n  (m = nil -> sz = 0) ->\n  union_pred m (fun it _ => memory_block sh sz) v (Vptr b (Ptrofs.repr ofs)) =\n  memory_block sh sz (Vptr b (Ptrofs.repr ofs))\n:= @memory_block_union_pred.\n\nEnd auxiliary_pred.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/floyd/aggregate_pred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.21654557728860432}}
{"text": "Require Import CSet Le Var.\n\nRequire Import Plus Util AllInRel Map CSet OptionR MoreList.\nRequire Import Val Var Envs IL Annotation Infra.Lattice RenamedApart.\nRequire Import DecSolve Analysis Filter Terminating.\nRequire Import Analysis AnalysisForwardSSA FiniteFixpointIteration.\nRequire Import Reachability Subterm AnnotationLattice DomainSSA.\n\nSet Implicit Arguments.\n\nLocal Arguments proj1_sig {A} {P} e.\nLocal Arguments length {A} e.\nLocal Arguments forward {sT} {D} {H} {H0} exp_transf reach_transf ZL ZLIncl st ST d anr.\n\nOpaque poLe.\n\nLtac simpl_forward_setTopAnn :=\n  match goal with\n  | [H : ann_R _ (snd (fst (@forward ?sT ?D ?PO ?JSL ?f ?fr ?ZL ?ZLIncl\n                                     ?s ?ST ?d ?r))) ?r' |- _ ] =>\n    let X := fresh \"HEQ\" in\n    match goal with\n    | [ H' : getAnn r = getAnn r' |- _ ] => fail 1\n    | _ => first\n            [ unify r r'; fail 1\n            | exploit (@forward_getAnn sT D PO JSL f fr ZL ZLIncl s ST d r r' H) as X;\n              subst]\n    end\n  end; subst; try eassumption;\n  try rewrite getAnn_setTopAnn in *;\n  repeat rewrite setTopAnn_eta' in *.\n\nSmpl Add 130 simpl_forward_setTopAnn : inv_trivial.\n\n\n\nLemma domupdd_eq (D : Type) `{PartialOrder D} (U : ⦃var⦄) (d:VDom U D) x v pf\n  : domenv (proj1_sig d) x === v\n    -> d ≣ @domupdd _ _ d x v pf.\nProof.\n  eapply poEq_domupd; eauto.\nQed.\n\nOpaque poEq.\nOpaque poLe.\n\n\nLtac PIR2_eq_simpl :=\n  match goal with\n  | [ H : PIR2 (ann_R eq) _ _ |- _ ] =>\n    eapply PIR2_R_impl with (R':=eq) in H;\n    [|intros ? ?; rewrite <- ann_R_eq; let A := fresh \"A\" in intros A; apply A]\n  | [ H : (@poEq (list (ann bool)) _) _ _ |- _ ] =>\n    eapply PIR2_R_impl with (R':=eq) in H;\n    [|intros ? ?; rewrite <- ann_R_eq; let A := fresh \"A\" in intros A; apply A]\n  | [ H : PIR2 eq _ _ |- _ ] =>\n    eapply PIR2_eq in H\n  | [ H : PIR2 (@poEq bool _) _ _ |- _ ] =>\n    eapply PIR2_eq in H\n  | [ H : ann_R eq _ _ |- _ ] => rewrite ann_R_eq in H\n  | [ H : _ = ?x |- _ ] => is_var x; rewrite H in *\n  end.\n\n\nTransparent poEq.\n\nLemma agree_comp_inv A `{OrderedType A} B (R:B->B->Prop) `{Transitive _ R} (f g : (A -> B) -> (A -> B)) Gf Gg\n      (AGRf: forall d, agree_on R Gf d (f d))\n      (AGRg: forall d, agree_on R Gg d (g d))\n  : forall d, agree_on R (Gf ∩ Gg) d (f (g d)).\nProof.\n  intros d. hnf; intros x IN.\n  cset_tac'.\n  rewrite <- (AGRf (g d) x); eauto.\n  eapply AGRg; eauto.\nQed.\n\nLemma agree_comp_inv' A `{OrderedType A} B (R:B->B->Prop) `{Transitive _ R} (f g : (A -> B) -> (A -> B)) d D Gf Gg (disj: disj Gf Gg)\n      (AGR:forall x, R (f (g d) x) (d x))\n      (AGRf: forall d, agree_on R (D \\ Gf) d (f d))\n      (AGRg: forall d, agree_on R (D \\ Gg) (g d) d)\n  : agree_on R D (g d) d.\nProof.\n  intros x IN.\n  decide (x ∈ Gg).\n  - assert (x ∉ Gf). cset_tac.\n    specialize (AGRf (g d) x ).\n    etransitivity. eapply AGRf. cset_tac.\n    eapply AGR.\n  - eapply AGRg. cset_tac.\nQed.\n\nLemma agree_comp_inv'' A `{OrderedType A} B (R:B->B->Prop) `{Transitive _ R}\n      X (r : X -> (A -> B))\n      (f g : X -> X) (d:X) D Gf Gg (disj: disj Gf Gg)\n      (AGR:forall x, R (r (f (g d)) x) (r d x))\n      (AGRf: forall d, agree_on R (D \\ Gf) (r d) (r (f d)))\n      (AGRg: forall d, agree_on R (D \\ Gg) (r (g d)) (r d))\n  : agree_on R D (r (g d)) (r d).\nProof.\n  intros x IN.\n  decide (x ∈ Gg).\n  - assert (x ∉ Gf). cset_tac.\n    specialize (AGRf (g d) x ).\n    etransitivity. eapply AGRf. cset_tac.\n    eapply AGR.\n  - eapply AGRg. cset_tac.\nQed.\n\nLemma poEq_VDom D `{PartialOrder D} U (d d':VDom U D)\n  : (forall G, agree_on poEq G (domenv (proj1_sig d)) (domenv (proj1_sig d')))\n         <-> d ≣ d'.\nProof.\n  intros. split; intros.\n  - hnf; intros.\n    eapply (H0 (singleton x)). cset_tac.\n  - hnf; intros. eapply H0.\nQed.\n\n(*\n  eapply poEq_VDom; intros.\n  decide (disj G (list_union (of_list ⊝ ZL))).\n  - symmetry in disj1.\n    eapply agree_comp_inv'' with\n    (r:=fun d => domenv (proj1_sig d))\n      (f:=fun d => fst (fst (forward f fr ZL ZLIncl t STt d ta)))\n      (g:=fun d => fst (fst (forward f fr ZL ZLIncl s STs d sa))); try eapply disj1; eauto.\n    hnf; intros. rewrite H1. eauto.\n    + intros.\n      eapply agree_on_incl.\n      eapply forward_agree; eauto.\n      instantiate (1:=G). revert d0. clear; cset_tac.\n    + intros. symmetry.\n      intros.\n      eapply agree_on_incl.\n      eapply forward_agree; eauto.\n      instantiate (1:=G). revert d0. clear; cset_tac.\n  -\n *)\n\nLemma forward_if_inv (sT:stmt) D `{JoinSemiLattice D}\n      f fr ZL s t (d:VDom (occurVars sT) D) STt STs ZLIncl sa ta\n      (EQ: fst (fst (forward f fr ZL ZLIncl t STt (fst (fst (forward f fr ZL ZLIncl s STs d sa))) ta)) ≣ d)\n      (ANs:annotation s sa) (ANt:annotation t ta)\n      (disj1:disj (definedVars s) (definedVars t))\n      (disj2:disj (definedVars s ∪ definedVars t) (list_union (of_list ⊝ ZL)))\n  : (fst (fst (forward f fr ZL ZLIncl s STs d sa))) ≣ d.\nProof.\n  hnf; intros x.\n  exploit (@forward_agree sT _ _ _ f fr ZL d (singleton x) s STs ZLIncl); eauto; dcr.\n  decide (x ∈ (definedVars s ∪ list_union (of_list ⊝ ZL))).\n  - specialize (EQ x).\n    rewrite <- EQ.\n    exploit (@forward_agree sT _ _ _ f fr ZL (fst (fst (forward f fr ZL ZLIncl s STs d sa))) (singleton x) t STt ZLIncl); eauto; dcr.\n    decide (x ∈ list_union (of_list ⊝ ZL)).\n    + assert (x ∉ definedVars t) by cset_tac.\n      eapply poLe_antisymmetric.\n      * specialize (H5 x). rewrite H5. reflexivity.\n        cset_tac.\n      * rewrite EQ. eapply H3. cset_tac.\n    + specialize (H4 x).\n      rewrite H4. reflexivity. cset_tac.\n  - symmetry.\n    eapply H2. cset_tac.\nQed.\n\nLemma forward_agree_ren sT D `{JoinSemiLattice D} f fr\n      ZL AE G s (ST:subTerm s sT) ra ZLIncl anr\n      (RA:renamedApart s ra) (AN:annotation s anr)\n  : agree_on poEq (G \\ (snd (getAnn ra) ∪ list_union (of_list ⊝ ZL)))\n             (domenv (proj1_sig AE))\n             (domenv (proj1_sig\n                        (fst (fst (forward f fr ZL ZLIncl\n                                            s ST AE anr))))) /\\\n    agree_on poLe (G \\ (snd (getAnn ra)))\n             (domenv (proj1_sig AE))\n             (domenv (proj1_sig\n                        (fst (fst (forward f fr ZL ZLIncl\n                                            s ST AE anr))))).\nProof.\n  rewrite <- renamedApart_occurVars; eauto.\n  eapply forward_agree; eauto.\nQed.\n\n\nLemma forward_agree_def_ren sT D `{JoinSemiLattice D} ZL AE G s f fr\n      (ST:subTerm s sT) ra ZLIncl anr pf\n  (RA:renamedApart s ra) (AN:annotation s anr)\n  : agree_on poEq (G \\ (snd (getAnn ra) ∪ list_union (of_list ⊝ ZL)))\n             (domenv AE)\n             (domenv (proj1_sig\n                        (fst (fst (forward f fr\n                                            ZL ZLIncl\n                                            s ST (exist _ AE pf) anr))))).\nProof.\n  edestruct forward_agree_ren with (AE:=exist _ AE pf); dcr; eauto.\nQed.\n\n\nLemma forward_agree_def sT D `{JoinSemiLattice D} ZL AE G s f fr\n      (ST:subTerm s sT) ra ZLIncl anr pf\n  (RA:renamedApart s ra) (AN:annotation s anr)\n  : agree_on poEq (G \\ (definedVars s ∪ list_union (of_list ⊝ ZL)))\n             (domenv AE)\n             (domenv (proj1_sig\n                        (fst (fst (forward f fr\n                                            ZL ZLIncl\n                                            s ST (exist _ AE pf) anr))))).\nProof.\n  edestruct forward_agree with (AE:=exist _ AE pf); dcr; eauto.\nQed.\n\nLemma list_union_definedVars_renamedApart (F:list (params * stmt)) ra\n      (RA:forall n Zs a,\n          get F n Zs -> get ra n a -> renamedApart (snd Zs) a)\n      (Len:❬F❭ = ❬ra❭)\n  : list_union (snd ⊝ getAnn ⊝ ra) [=] list_union (definedVars ⊝ snd ⊝ F).\nProof.\n  general induction Len; simpl; eauto.\n  norm_lunion. rewrite IHLen; eauto using get.\n  rewrite renamedApart_occurVars; eauto using get.\n  reflexivity.\nQed.\n\nLemma forwardF_agree_get (sT:stmt) D `{JoinSemiLattice D} f fr\n      (F : 〔params * stmt〕)\n      (t : stmt)\n      (ZL : 〔params〕)\n      (ra : 〔ann (⦃var⦄ * ⦃var⦄)〕)\n      (AE AE': VDom (occurVars sT) D) BL\n      STF\n      (ZLIncl : list_union (of_list ⊝ ZL) [<=] occurVars sT)\n      (LenZL:❬ZL❭ >= ❬F❭)\n      (sa : 〔ann bool〕)\n      (ta : ann bool)  tra\n      (RAt:renamedApart t tra) (AN:annotation t ta)\n      (EQM :   (fst (fst (@forwardF sT (sTDom D) BL\n                                (forward f fr ZL ZLIncl) F\n                                sa\n                                AE'\n                                STF))) ≣ AE)\n      (STt:subTerm t sT)\n      (EQ: (fst (fst (forward f fr ZL ZLIncl t STt AE ta))) ≣ AE')\n      (Disj1:disj (snd (getAnn tra)) (list_union (of_list ⊝ ZL)))\n      (Disj2:disj (snd (getAnn tra)) (list_union (snd ⊝ getAnn ⊝ ra)))\n      (Disj3:disj (list_union (of_list ⊝ ZL)) (list_union (snd ⊝ getAnn ⊝ ra)))\n      (Disj5:disj (list_union (of_list ⊝ fst ⊝ F)) (list_union (snd ⊝ getAnn ⊝ ra)))\n      (Disj6:PairwiseDisjoint.pairwise_ne disj (defVars ⊜ F ra))\n      (Len2 : ❬F❭ = ❬ra❭)\n      (Len1 : ❬F❭ = ❬sa❭)\n      (AnnF : forall (n : nat) (s' : params * stmt) (sa' : ann bool),\n         get sa n sa' -> get F n s' -> annotation (snd s') sa')\n      (RA : forall (n : nat) (Zs : params * stmt) (a : ann (⦃var⦄ * ⦃var⦄)),\n          get F n Zs -> get ra n a -> renamedApart (snd Zs) a)\n      (fExt:forall (U : ⦃var⦄) (e : exp) (a0 a' : VDom U D),\n          a0 ≣ a' -> forall b b' : bool, b ≣ b' -> f U b a0 e ≣ f U b' a' e)\n      (frExt:forall (U : ⦃var⦄) (e : op) (a0 a' : VDom U D),\n          a0 ≣ a' -> forall b b' : bool, b ≣ b' -> fr U b a0 e ≣ fr U b' a' e)\n  : (fst (fst (forward f fr ZL ZLIncl t STt AE ta)) ≣ AE)\n    /\\  forall n Zs r (ST : subTerm (snd Zs) sT),\n      get F n Zs ->\n      get sa n r ->\n      fst (fst (forward f fr ZL ZLIncl (snd Zs) ST AE r)) ≣ AE.\nProof.\n  Opaque poEq.\n  general induction Len1; simpl in *; eauto.\n  - split; isabsurd. etransitivity; eauto.\n  - destruct ra; simpl in *; isabsurd.\n    revert Disj2 Disj3 Disj5. norm_lunion. intros Disj2 Disj3 Disj5.\n    edestruct (IHLen1 sT _ _ _ f fr t ZL); eauto using get.\n    + Transparent poEq.\n      hnf; intros z.\n      exploit (@forward_agree_ren sT _ _ _ f fr ZL AE (singleton z) t STt tra ZLIncl); eauto; dcr.\n      exploit (@forward_agree_ren sT _ _ _ f fr ZL AE' (singleton z) (snd x) (STF 0 x (getLB XL x)) a ZLIncl); eauto using get; dcr.\n      exploit (@forwardF_agree sT _ _ _ BL (singleton z) XL f fr YL ZL ZLIncl);\n      eauto using get; dcr.\n      * eauto with len.\n      * intros. inv_get. inv_get. exploit (RA (S n)); eauto using get.\n        eapply renamedApart_occurVars in H9; eauto.\n        rewrite H9.\n        eapply forward_agree_ren; eauto using get.\n      * specialize (EQ z). specialize (EQM z).\n    instantiate (3:=(fst (fst (forward f fr ZL ZLIncl (snd x) (STF 0 x (getLB _ _)) AE' y)))) in H6.\n    instantiate (1:=(fun (n : nat) (s : params * stmt) (H : get XL n s) =>\n                       STF (S n) s (getLS x H))) in H6.\n        {\n          decide (z ∈ snd (getAnn tra) ∪ list_union (of_list ⊝ ZL)).\n          + eapply disj_union_inv in i. destruct i; dcr.\n            * rewrite EQ.\n              eapply H4.\n              revert H8 H9 Disj2. clear.\n              intros. cset_tac.\n            * eapply poLe_antisymmetric.\n              -- rewrite EQ.\n                 eapply H5.\n                 revert H8 Disj3; clear_all. intros. cset_tac.\n              -- etransitivity; [| eapply H3].\n                 rewrite <- EQM. specialize (H7 z).\n                 eapply H7.\n                 revert H8 Disj3.\n                 rewrite list_union_definedVars_renamedApart; eauto using get.\n                 clear_all; intros. cset_tac.\n                 intros.\n                 revert H9; clear_all; cset_tac.\n            * eapply disj_2_incl; try eapply Disj1; eauto.\n          + decide (z ∈ (list_union (defVars ⊜ XL ra))).\n            * clear H7 H6.\n              rewrite EQ. eapply H4.\n              eapply (@defVars_drop_disj (x::XL) (a::ra) 0) in Disj6;\n                eauto using get. simpl in *.\n              unfold defVars in Disj6 at 1.\n              rewrite list_union_defVars_decomp in *; eauto.\n              revert n i Disj5 Disj6. clear_all.\n              intros. cset_tac.\n            * exploit (H2 z). revert n; clear_all; cset_tac.\n              rewrite <- H1.\n              rewrite <- EQM. symmetry. eapply H6.\n              revert n n0.\n              rewrite list_union_definedVars'; eauto.\n              rewrite list_union_defVars_decomp; eauto.\n              rewrite list_union_definedVars_renamedApart; eauto using get.\n              clear_all; cset_tac.\n        }\n    + eapply disj_2_incl; eauto.\n    + eapply disj_2_incl. eapply Disj3. clear_all; cset_tac.\n    + eapply disj_incl. eapply Disj5.\n      clear_all; cset_tac.\n      clear_all; cset_tac.\n    + hnf; intros. eapply Disj6; [|eauto using get|eauto using get]. omega.\n    + intros; split; eauto.\n      intros. inv H3; inv H4; eauto using get.\n      assert (AEQ:AE === AE').\n      { hnf; intros.\n        specialize (EQ x). specialize (H1 x).\n        rewrite <- EQ. rewrite H1. reflexivity.\n      }\n      assert (EQF:@forwardF sT (sTDom D) BL (forward f fr ZL ZLIncl) XL YL\n                            (fst (fst (forward f fr ZL ZLIncl _ (STF 0 Zs (@getLB (params * stmt) XL Zs)) AE' r)))\n                            (fun (n : nat) (s : params * stmt) (H : get XL n s) =>\n                               STF (S n) s (getLS Zs H)) ===\n                            forwardF BL (forward f fr ZL ZLIncl) XL YL\n                            (fst (fst (forward f fr ZL ZLIncl _ ST AE r)))\n                            (fun (n : nat) (s : params * stmt) (H : get XL n s) =>\n                               STF (S n) s (getLS Zs H))\n             ). {\n        eapply forwardF_ext'; eauto.\n        assert ((STF 0 Zs (@getLB (params * stmt) XL Zs)) = ST) by eapply subTerm_PI.\n        subst.\n        eapply forward_ext; eauto.\n      }\n      hnf; intros z.\n      exploit (@forward_agree sT _ _ _ f fr ZL AE (singleton z) (snd Zs) ST ZLIncl); eauto using get; dcr.\n      exploit (@forwardF_agree sT _ _ _  BL (singleton z) XL f fr YL ZL ZLIncl);\n        eauto using get; dcr.\n      eauto with len.\n      intros. inv_get.\n      eapply forward_agree; eauto using get.\n      unfold domenv in *.\n      instantiate (2:=(fst (fst (forward f fr ZL ZLIncl (snd Zs) ST AE r)))) in H9.\n      decide (z ∈ snd (getAnn tra) ∪ list_union (of_list ⊝ ZL)).\n      * eapply disj_union_inv in i. destruct i; dcr.\n        -- symmetry.\n           eapply (H6 z).\n           revert H10 H11 Disj2.\n           rewrite list_union_definedVars_renamedApart; eauto using get.\n           rewrite renamedApart_occurVars; eauto using get.\n           clear. intros. cset_tac.\n        -- eapply poLe_antisymmetric.\n           ++ etransitivity. Transparent poLe.\n             eapply (H9 z).\n             revert H10 Disj3.\n             rewrite list_union_definedVars_renamedApart; eauto using get.\n             clear_all. intros; cset_tac.\n             rewrite <- (EQM z).\n             hnf in EQF. dcr.\n             hnf in H5. dcr.\n             specialize (H13 z).\n             rewrite H13. reflexivity.\n           ++ eapply H7.\n             rewrite renamedApart_occurVars; eauto using get.\n             revert H10 H11 Disj3; clear_all. intros. cset_tac.\n        -- eauto.\n      * decide (z ∈ (list_union (defVars ⊜ XL ra))).\n        -- symmetry.\n           eapply H6.\n           eapply (@defVars_drop_disj (Zs::XL) (a::ra) 0) in Disj6;\n             eauto using get. simpl in *.\n           unfold defVars in Disj6 at 1.\n           rewrite list_union_defVars_decomp in Disj6; eauto.\n           rewrite list_union_defVars_decomp in i; eauto.\n           revert n i Disj5 Disj6.\n           rewrite renamedApart_occurVars; eauto using get.\n           clear_all. intros. cset_tac.\n        -- rewrite (H8 z).\n           rewrite <- (EQM z).\n           hnf in EQF. dcr.\n           hnf in H5. dcr.\n           specialize (H11 z).\n           rewrite H11. reflexivity.\n           revert n n0.\n           rewrite list_union_defVars_decomp; eauto.\n           rewrite list_union_definedVars_renamedApart; eauto using get.\n           rewrite list_union_definedVars'; eauto.\n           clear_all; cset_tac.\nQed.\n\n\n\nOpaque poEq.\n\n\n\nLemma forward_domupdd_eq (sT:stmt) D `{JoinSemiLattice D} ZL ZLIncl s f fr sa v x IN\n      (d:VDom (occurVars sT) D) STs (AN:annotation s sa)\n      (NOTIN:x ∉ definedVars s ∪ list_union (of_list ⊝ ZL))\n      (EQ : fst (fst (forward f fr ZL ZLIncl s STs (@domupdd _ _ d x v IN) sa)) ≣ d)\n\n  : fst (fst (forward f fr ZL ZLIncl s STs (@domupdd _ _ d x v IN) sa))\n        ≣ domupdd d v IN.\nProof.\n  exploit (@forward_agree sT _ _ _ f fr ZL (domupdd d v IN) (singleton x) s STs ZLIncl); eauto; dcr.\n  exploit (H2 x).\n  - cset_tac.\n  - rewrite EQ.\n    eapply domupdd_eq.\n    exploit (EQ x).\n    rewrite H4 in H1.\n    rewrite <- H1. symmetry.\n    unfold domenv, domupdd; simpl.\n    rewrite domupd_var_eq. reflexivity. reflexivity.\nQed.\n\nLtac ST_pat :=\n  match goal with\n  | [ H : context [ forward _ _ _ ?ZLIncl _ ?ST _ _ ] |- _  ] =>\n    try (first [ is_var ZLIncl; fail 1\n               | let X := fresh \"ZLIncl\" in set (X:=ZLIncl) in * ]);\n    first [ is_var ST; fail 1\n          | let X := fresh \"ST\" in set (X:=ST) in * ]\n  | [ H : context [ forwardF _ _ _ _ _ ?STF ] |- _  ] =>\n    first [ is_var STF; fail 1\n          | let X := fresh \"STF\" in set (X:=STF) in * ]\n  end.\n\nHint Resolve funConstr_disj_Dt' funConstr_disj_ZL_getAnn disj_Dt_getAnn : ren.\n\nLemma poEq_refl D `{PartialOrder D} x\n  : poEq x x.\nProof.\n  reflexivity.\nQed.\n\nLemma poEq_sym D `{PartialOrder D} x y\n  : poEq x y -> poEq y x.\nProof.\n  intros. symmetry. eauto.\nQed.\n\nHint Immediate poEq_refl poEq_sym : po.\n\nInstance join_respects_le A  `{JoinSemiLattice A}\n  : Proper (poEq ==> poEq ==> poLe) join.\nProof.\n  unfold Proper, respectful; intros.\n  rewrite H1, H2. reflexivity.\nQed.\n\nDefinition reachability_sound (sT:stmt) D `{JoinSemiLattice D}\n           f fr pr ZL BL s (d:VDom (occurVars sT) D) r (ST:subTerm s sT) ZLIncl\n           (EQ:(fst (forward f fr ZL ZLIncl s ST d r)) ≣ (d,r)) ra\n    (Ann: annotation s r) (RA:renamedApart s ra)\n    (DefZL: labelsDefined s (length ZL))\n    (DefBL: labelsDefined s (length BL))\n    (BL_le: poLe (snd (forward f fr ZL ZLIncl s ST d r)) BL)\n    (Disj:disj (list_union (of_list ⊝ ZL)) (snd (getAnn ra)))\n    (frExt:forall U e (a a':VDom U D), a ≣ a' ->\n        forall b b', b ≣ b' -> fr _ b a e ≣ fr _ b' a' e)\n    (fExt:forall (U : ⦃var⦄) (e : exp) (a a' : VDom U D),\n        a ≣ a' -> forall b b' : bool, b ≣ b' -> f U b a e ≣ f U b' a' e)\n    (frSound1: forall e d r,\n        ~ pr d e ⊑ ⎣ wTA false ⎦ -> uceq Sound r (fst (fr (occurVars sT) r d e)))\n    (frSound2: forall e d r,\n        ~ pr d e ⊑ ⎣ wTA true ⎦ -> uceq Sound r (snd (fr (occurVars sT) r d e)))\n  : reachability (pr d) Sound BL s r.\nProof.\n  general induction Ann; invt renamedApart; simpl in *; inv DefZL; inv DefBL;\n    repeat let_case_eq; repeat simpl_pair_eqs; subst; simpl in *;\n      simpl in *; inv_cleanup.\n  - clear_trivial_eqs.\n    econstructor; eauto.\n    exploit forward_domupdd_eq; eauto.\n    rewrite renamedApart_occurVars; eauto. pe_rewrite.\n    set_simpl. eapply renamedApart_disj in H6; eauto.\n    pe_rewrite. revert Disj H6; clear_all; cset_tac.\n    rewrite EQ in H1. symmetry in H1.\n    eapply forward_ext in H1; try reflexivity; eauto.\n    rewrite H1 in *.\n    eapply IHAnn; eauto.\n    + split; simpl; eauto.\n    + pe_rewrite. eapply disj_2_incl; eauto. cset_tac.\n  - clear_trivial_eqs.\n    set_simpl.\n    exploit (forward_if_inv _ _ _ _ _ _ EQ); eauto.\n    repeat rewrite renamedApart_occurVars; eauto;\n      pe_rewrite; eauto with cset.\n    repeat rewrite renamedApart_occurVars; eauto;\n      pe_rewrite; eauto with cset.\n    rewrite forward_ext in EQ; try eapply H1; try reflexivity; eauto.\n    econstructor; eauto.\n    + rewrite <- HEQ0. eapply frSound1.\n    + rewrite <- HEQ. eapply frSound2.\n    + eapply IHAnn1;\n        eauto using @PIR2_zip_join_inv_left with len.\n      * split; simpl; eauto.\n      * pe_rewrite. eapply disj_2_incl; eauto.\n    + eapply IHAnn2;\n        eauto using @PIR2_zip_join_inv_left, @PIR2_zip_join_inv_right with len.\n      * split; simpl; eauto.\n        rewrite forward_ext; eauto.\n      * eapply PIR2_zip_join_inv_right.\n        rewrite <- BL_le. eapply PIR2_ojoin_zip. reflexivity.\n        eapply poLe_refl. eapply forward_ext; eauto.\n        symmetry; eauto with len.\n      * pe_rewrite. eapply disj_2_incl; eauto.\n  - edestruct get_in_range; eauto.\n    edestruct get_in_range; try eapply H7; eauto.\n    Transparent poLe. hnf in BL_le.\n    edestruct PIR2_nth; eauto using ListUpdateAt.list_update_at_get_3; dcr.\n    econstructor; simpl; eauto.\n  - econstructor.\n  - clear_trivial_eqs.\n    eapply PIR2_get in H23; try eassumption. clear H22.\n    exploit (snd_forwardF_inv _ _ _ _ _ _ _ H23); eauto with len.\n    exploit (snd_forwardF_inv' _ _ _ _ _ _ _ H23); eauto with len.\n    Transparent poEq. simpl poEq in H23.\n    repeat PIR2_eq_simpl. repeat ST_pat.\n    Opaque poEq.\n    set (FWt:=(forward f fr (fst ⊝ s ++ ZL) ZLIncl0 t ST0 d ta)) in *.\n    set (FWF:=forwardF (snd FWt) (forward f fr (fst ⊝ s ++ ZL) ZLIncl0)\n                       s sa (fst (fst FWt)) STF) in *.\n\n    assert (fst (fst (FWt)) ≣ d /\\\n            forall (n : nat) (Zs : params * stmt) (r : ann bool) (ST0 : subTerm (snd Zs) sT),\n              get s n Zs ->\n              get sa n r ->\n              fst\n                (fst\n                   (forward f fr (fst ⊝ s ++ ZL) (ZLIncl_ext ZL eq_refl ST ZLIncl) (snd Zs) ST0 d r))\n                ≣ d). {\n      pe_rewrite. set_simpl.\n      eapply forwardF_agree_get; eauto. eauto with len.\n      rewrite <- EQ. unfold FWF. reflexivity.\n      unfold FWt. reflexivity.\n      pe_rewrite. eauto with ren.\n      pe_rewrite.\n      eapply disj_Dt_getAnn; eauto.\n      eapply funConstr_disj_ZL_getAnn; eauto.\n      eapply disj_1_incl.\n      eapply funConstr_disj_ZL_getAnn; eauto.\n      rewrite List.map_app. rewrite list_union_app.\n      clear_all. cset_tac.\n    } dcr.\n\n    assert (forall (n : nat) (r : ann bool) (Zs : params * stmt),\n       get sa n r ->\n       get s n Zs ->\n       forall STZs : subTerm (snd Zs) sT,\n         (snd\n            (fst\n               (forward f fr (fst ⊝ s ++ ZL) ZLIncl0 (snd Zs) STZs d r))) ≣ r). {\n      eapply (@snd_forwardF_inv_get) with (BL:=(snd FWt)); eauto.\n      subst FWt; eauto with len.\n      subst FWt; eauto with len.\n      rewrite <- H5 at 2. unfold FWF.\n      rewrite forwardF_ext'; try reflexivity; eauto.\n    }\n    econstructor; eauto.\n    + eapply IHAnn; eauto.\n      * split; eauto.\n      * erewrite (take_eta ❬s❭) at 1. eapply PIR2_app; eauto.\n        --change (PIR2 poLe) with (@poLe (list bool) _).\n          assert (poLe (Take.take ❬s❭ (snd FWt)) (getAnn ⊝ sa)). {\n            rewrite H.\n            eapply (@joinTopAnn_map_inv).\n            rewrite <- H4 at 2. reflexivity.\n          }\n          rewrite <- H4. subst FWF.\n          subst FWt.\n          rewrite H4.\n          rewrite <- H5.\n          rewrite <- (@forwardF_mon' sT D _ _ f fr); eauto.\n        -- rewrite <- BL_le.\n           eapply PIR2_drop.\n           etransitivity;[|\n                          eapply forwardF_mon; eauto].\n           reflexivity.\n           subst FWt. eauto with len.\n      * pe_rewrite.\n        set_simpl.\n        rewrite List.map_app. rewrite list_union_app.\n        eapply disj_union_left.\n        -- symmetry.\n           eapply funConstr_disj_Dt; eauto.\n        -- symmetry. eapply disj_incl; eauto.\n    + intros. inv_get. exploit H7; eauto.\n      eapply H1; eauto.\n      -- split; simpl; eauto.\n      -- rewrite (take_eta ❬sa❭) at 1.\n         eapply PIR2_app; eauto.\n         ++ Transparent poEq.\n           unfold poEq in H23. simpl in H23.\n           unfold poEq in H23. simpl in H23.\n           repeat PIR2_eq_simpl.\n           eapply setTopAnn_map_inv in H23.\n           rewrite <- H23. eapply PIR2_take.\n           change (PIR2 poLe) with (@poLe (list bool) _).\n           unfold FWF.\n           rewrite forwardF_ext'; eauto; try reflexivity.\n           eapply forwardF_PIR2; eauto.\n           subst FWt. clear_all. eauto with len.\n         ++ etransitivity; eauto.\n           rewrite H. eapply PIR2_drop.\n           change (PIR2 poLe) with (@poLe (list bool) _).\n           unfold FWF.\n           rewrite forwardF_ext'; eauto; try reflexivity.\n           unfold poEq in H23. simpl in H23.\n           unfold poEq in H23. simpl in H23.\n           repeat PIR2_eq_simpl.\n           eapply forwardF_PIR2; eauto.\n           subst FWt. clear_all. eauto with len.\n      -- set_simpl.\n         eapply disj_2_incl.\n         eapply funConstr_disj_ZL_getAnn; eauto with ren.\n         eapply incl_list_union; eauto using zip_get.\n         Grab Existential Variables.\n         eauto.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Reachability/ReachabilityAnalysisCorrectSSA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21654557143829822}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Vincent Rahli\n\n *)\n\n\nRequire Export terms.\n\n\nLemma canonical_dec_op {o} :\n  forall (x y : @CanonicalOp o), option (x = y).\nProof.\n  introv.\n  destruct x; destruct y; try (complete (left; reflexivity));\n    match goal with\n    | [ |- option (?x _ = ?x _) ] => idtac\n    | _ => exact None\n    end.\n\n  - destruct (can_inj_deq c c0) as [d|d]; subst;[left|right];auto.\n\n  - destruct (Z.eq_dec z z0) as [d|d]; subst;[left|right];auto.\n\n  - right; auto.\n\n  - destruct (String.string_dec s s0) as [d|d]; subst;[left|right]; auto.\n\n  - assert (Deq (get_patom_set o)) as d by (destruct o; destruct patom; auto).\n    pose proof (d g g0) as h; dorn h;subst;[left|right]; auto.\n\n  - destruct (deq_nat n n0) as [d|d]; subst; [left|right]; auto.\n\n  - right; auto.\n\n  - right; auto.\nDefined.\n\nLemma opid_dec_op {o} :\n  forall (x y : @Opid o), option (x = y).\nProof.\n  introv.\n  dopid x as [can1|ncan1|exc1|abs1] Case;\n    dopid y as [can2|ncan2|exc2|abs2] SCase.\n\n  - Case \"Can\"; SCase \"Can\".\n    pose proof (canonical_dec_op can1 can2) as h; destruct h as [h|h]; subst;\n      try (complete (left; auto)).\n    right; auto.\n\n  - Case \"Can\"; SCase \"NCan\".\n    right; auto.\n\n  - Case \"Can\"; SCase \"Exc\".\n    right; auto.\n\n  - Case \"Can\"; SCase \"Abs\".\n    right; auto.\n\n  - Case \"NCan\"; SCase \"Can\".\n    right; auto.\n\n  - destruct ncan1; destruct ncan2; try (complete (left; auto));\n      match goal with\n      | [ |- option (NCan (?x _) = NCan (?x _)) ] => idtac\n      | _ => exact None\n      end.\n\n    + try destruct c; try destruct c0; try (complete (left; auto)); right; auto.\n    + try destruct a; try destruct a0; try (complete (left; auto)); right; auto.\n    + try destruct c; try destruct c0; try (complete (left; auto)); right; auto.\n\n  - Case \"NCan\"; SCase \"Exc\".\n    right; auto.\n\n  - Case \"NCan\"; SCase \"Abs\".\n    right; auto.\n\n  - Case \"Exc\"; SCase \"Can\".\n    right; auto.\n\n  - Case \"Exc\"; SCase \"NCan\".\n    right; auto.\n\n  - Case \"Exc\"; SCase \"Exc\".\n    left; auto.\n\n  - Case \"Exc\"; SCase \"Abs\".\n    right; auto.\n\n  - Case \"Abs\"; SCase \"Can\".\n    right; auto.\n\n  - Case \"Abs\"; SCase \"NCan\".\n    right; auto.\n\n  - Case \"Abs\"; SCase \"Exc\".\n    right; auto.\n\n  - destruct abs1, abs2.\n    pose proof (String.string_dec opabs_name opabs_name0) as h.\n    dorn h; subst;[|right].\n    pose proof (parameters_dec opabs_params opabs_params0) as h.\n    dorn h; subst;[|right].\n    pose proof (opsign_dec opabs_sign opabs_sign0) as h.\n    dorn h; subst;[|right].\n    left; auto.\nDefined.\n\nLemma term_dec_op {o} :\n  forall (x y : @NTerm o), option (x = y).\nProof.\n  sp_nterm_ind1 x as [v1|f1|op1 bs1 ind] Case; introv.\n\n  - Case \"vterm\".\n    destruct y as [v2|f1|op bs2];[|exact None|exact None].\n    destruct (deq_nvar v1 v2); subst;[|exact None].\n    left; reflexivity.\n\n  - Case \"sterm\".\n    right.\n\n  - Case \"oterm\".\n    destruct y as [v2|f2|op2 bs2];[right|right|].\n    destruct (opid_dec_op op1 op2); subst;[|right].\n\n    assert (option (bs1 = bs2)) as opbs.\n    {\n      revert bs2.\n      induction bs1; introv.\n      - destruct bs2;[left|right]; auto.\n      - destruct bs2;[right|].\n        destruct a as [l1 t1], b as [l2 t2].\n        simpl in *.\n        autodimp IHbs1 hyp.\n        { introv i; introv; eapply ind; eauto. }\n        pose proof (ind t1 l1) as q; autodimp q hyp; clear ind.\n        pose proof (q t2) as h; clear q.\n        destruct (list_eq_dec deq_nvar l1 l2) as [d|d]; subst;[|right].\n        destruct h as [d|d]; subst;[|right].\n        destruct (IHbs1 bs2) as [d|d]; subst;[|right].\n        left; auto.\n    }\n\n    destruct opbs as [d|d]; subst;[left|right];auto.\nDefined.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/terms/terms_deq_op.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.21649116269402047}}
{"text": "Require Import Unicode.Utf8 ssreflect.\nRequire Import GuardedLF.\nRequire Import Logic.FunctionalExtensionality.\n\n(* This is a relatively simple theory of typed CBPV λ-calculus with\nrecursive types; every type is made to be an algebra for the later\nmodality. *)\n\nAxiom mode : ◻.\nAxiom pos : mode.\nAxiom neg : mode.\n\nAxiom tp : mode → ◻.\nAxiom tm : tp pos → Type.\n\nAxiom bool : tp pos.\nAxiom one : tp pos.\nAxiom arr : tp pos → tp neg → tp neg.\nAxiom prod : ∀ {μ}, tp μ → tp μ → tp μ.\nAxiom coprod : tp pos → tp pos → tp pos.\nAxiom rec : (tp neg → tp neg) → tp neg.\nAxiom F : tp pos → tp neg.\nAxiom U : tp neg → tp pos.\n\nNotation \"[ A ]\" := (tm A).\nNotation \"⟪ A ⟫\" := [ U A ].\n\nAxiom bind : ∀ {A B}, [U (F A)] → ([A] → [U B]) → [U B].\nAxiom ret : ∀ {A}, [A] → [U (F A)].\nNotation \"ret: e\" := (ret e) (at level 100).\n\nInfix \"⇒\" := arr (right associativity, at level 60).\nInfix \"&\" := (@prod neg) (right associativity, at level 60).\nInfix \"⊗\" := (@prod pos) (right associativity, at level 60).\nInfix \"⊕\" := coprod (right associativity, at level 60).\nNotation \"rec: X ; B\" := (rec (λ X, B)) (at level 100).\n\nAxiom θ : ∀ {A}, ▶ [U A] → [U A].\nDefinition δ {A} (e : [U A]) : [U A] := θ (next e).\n\nNotation \"θ: e\" := (θ e) (at level 100).\nNotation \"δ: e\" := (δ e) (at level 100).\nNotation \"θ[ A ]\" := (@θ A).\nNotation \"δ[ A ]\" := (@δ A).\n\nAxiom def_arr : ∀ {A B}, ([A] → [U B]) ≅ [U (A ⇒ B)].\nAxiom def_prod_neg : ∀ {A B}, (product ⟪A⟫ ⟪B⟫) ≅ ⟪ A & B ⟫.\nAxiom def_prod_pos : ∀ {A B}, (product [A] [B]) ≅ [A ⊗ B].\nAxiom def_coprod : ∀ {A B}, (sum [A] [B]) ≅ [A ⊕ B].\nAxiom def_rec : ∀ {H}, ▶ [U (H (rec H))] ≅ [U (rec H)].\nAxiom def_one : True ≅ [one].\n\nNotation lam := (intro def_arr).\nNotation app := (elim def_arr).\nNotation \"lam: x ; e\" := (lam (λ x, e)) (at level 100).\nInfix \"@\" := app (left associativity, at level 50).\n\nNotation fold := (intro def_rec).\nNotation unfold := (elim def_rec).\nNotation \"fold: e\" := (fold e) (at level 100).\nNotation \"unfold: e\" := (unfold e) (at level 100).\n\nNotation \"pair-\" := (intro def_prod_neg).\nNotation \"split-\" := (elim def_prod_neg).\nNotation \"⟨ e , e' ⟩-\" := (pair- (Build_product e  e')).\nNotation \"fst-: e\" := (π1 (split- e)) (at level 100).\nNotation \"snd-: e\" := (π2 (split- e)) (at level 100).\n\nNotation \"pair+\" := (intro def_prod_pos).\nNotation \"split+\" := (elim def_prod_pos).\nNotation \"⟨ e , e' ⟩+\" := (pair+ (Build_product e  e')).\nNotation \"fst+: e\" := (π1 (split+ e)) (at level 100).\nNotation \"snd+: e\" := (π2 (split+ e)) (at level 100).\n\n\nNotation \"bind: x ← e ; k\" := (bind e (λ x, k)) (at level 100).\n\nDefinition θ_arr_rhs {A B} (e : ▶ [U (A ⇒ B)]) : [U (A ⇒ B)] :=\n  lam: x;\n  θ: (λ f, f @ x) <$> e.\n\nDefinition θ_prod_rhs {A B} (e : ▶ [U (A & B)]) : [U (A & B)] :=\n  ⟨ θ: (λ x, fst-: x) <$> e, θ: (λ x, snd-: x) <$> e ⟩-.\n\nDefinition θ_rec_rhs {H} (e : ▶ [U (rec H)]) : [U (rec H)] :=\n  fold: (θ ∘ unfold) <$> e.\n\nAxiom bind_ret : ∀ {A B} {x : [A]} {k : [A] → [U B]}, bind (ret x) k = k x.\nAxiom θ_bind : ∀ {A B x k}, bind (θ[F A] x) k = θ[B] ((λ z, bind z k) <$> x).\nAxiom θ_arr : ∀ {A B}, θ[A ⇒ B] = θ_arr_rhs.\nAxiom θ_prod : ∀ {A B}, θ[A & B] = θ_prod_rhs.\nAxiom θ_rec : ∀ {F}, θ[rec F] = θ_rec_rhs.\n\nAxiom tt : [bool].\nAxiom ff : [bool].\nAxiom case : ∀ {A}, [bool] → [U A] → [U A] → [U A].\n\nNotation \"case: b 'with' 'tt' ⇒ t | 'ff' ⇒ f 'end'\" := (case b t f) (at level 100).\nNotation \"case[ A ]: b 'with' 'tt' ⇒ t | 'ff' ⇒ f 'end'\" := (@case A b t f) (at level 100).\n\nAxiom case_tt : ∀ {A} t f, case[A]: tt with tt ⇒ t | ff ⇒ f end = t.\nAxiom case_ff : ∀ {A} t f, case[A]: tt with tt ⇒ t | ff ⇒ f end = f.\n\nDefinition bits := rec: X; F (bool ⊗ U X).\nDefinition cons : ⟪ bool ⇒ U bits ⇒ bits ⟫ :=\n  lam: x; lam: xs;\n  fold: next: ret: ⟨x,xs⟩+.\n\nDefinition head : ⟪ U bits ⇒ F bool ⟫ :=\n  lam: xs;\n  bind: u ← θ: unfold: xs;\n  ret: fst+: u.\n\nDefinition tail : ⟪ U bits ⇒ bits ⟫ :=\n  lam: xs;\n  bind: u ← θ: unfold: xs;\n  snd+: u.\n\nLtac crush :=\n  repeat\n    (autorewrite with crush;\n     autounfold with crush;\n     simpl).\n\nHint Unfold θ_prod_rhs θ_rec_rhs θ_arr_rhs Later.map δ : crush.\nHint Rewrite @beta @θ_prod @θ_arr @θ_rec @Later.ap_compute @bind_ret @θ_bind : crush.\n\nGoal ∀ x xs, head @ (cons @ x @ xs) = δ: ret x.\n  move=> x xs.\n  rewrite /head /cons.\n  by crush.\nQed.\n\n\nGoal ∀ x xs, tail @ (tail @ (cons @ x @ (cons @ x @ xs))) = δ: δ: xs.\n  move=> x xs.\n  rewrite /bits /tail /cons.\n  by crush.\nQed.\n\n\nDefinition zeroes : ⟪ bits ⟫ :=\n  fix: xs; cons @ ff @ θ: xs.\n\nLemma head_zeroes : head @ zeroes = δ: ret: ff.\n  rewrite /head /zeroes /cons loeb_unfold.\n  by crush.\nQed.\n\nLemma tail_cons : ∀ x xs, tail @ (cons @ x @ xs) = δ: xs.\n  move=> x xs.\n  rewrite /tail /cons /bits.\n  by crush.\nQed.\n\nLemma tail_zeroes : tail @ zeroes = δ: δ: zeroes.\n  rewrite /zeroes.\n  rewrite {1} loeb_unfold.\n  by rewrite tail_cons.\nQed.\n\nLemma tail_strict : ∀ xs, (tail @ δ: xs) = δ: tail @ xs.\n  move=> xs.\n  rewrite /tail /bits.\n  by crush.\nQed.\n\nLemma head_strict : ∀ xs, (head @ δ: xs) = δ: head @ xs.\n  move=> xs.\n  rewrite /head /bits.\n  by crush.\nQed.\n\nGoal head @ (tail @ (tail @ zeroes)) = δ: δ: δ: δ: δ: ret ff.\n  do 2 rewrite tail_zeroes ? tail_strict.\n  rewrite ? head_strict.\n  by rewrite head_zeroes.\nQed.\n\n\nDefinition bot {A} : ⟪ A ⟫ := fix: x; θ: x.\n\nGoal 1 ⊩ (δ: δ: ret: tt) = bot.\n  move=> z.\n  rewrite /bot loeb_unfold -/bot /δ.\n  f_equal.\n  apply: Later.from_eq; move: z.\n  apply: Later.pmap => z.\n  rewrite /bot loeb_unfold -/bot /δ.\n  f_equal.\n  apply: Later.from_eq; move: z.\n  by apply: Later.pmap.\nQed.\n\nFixpoint rep {A} (n : nat) (f : A → A) (x : A) : A :=\n  match n with\n  | 0 => x\n  | S n => f (rep n f x)\n  end.\n\nDefinition conat : tp neg := rec: X; F (one ⊕ U X).\n\nNotation ax := (intro def_one I).\n\nDefinition ze : ⟪conat⟫ :=\n  fold: next: ret: intro def_coprod (inl ax).\n\nDefinition su (n : ⟪conat⟫) : ⟪conat⟫ :=\n  fold: next: ret: intro def_coprod (inr n).\n\n\n\nInductive wp_F {A : tp pos} (Φ : [A] → Prop) (H : ⟪F A⟫ → Prop) : ⟪F A⟫ → Prop :=\n| wp_ret : ∀ e v, e = ret v → Φ v → wp_F Φ H e\n| wp_step : ∀ e e', (e = δ: e') → H e' → wp_F Φ H e.\n\n\n(* Weakest precondition *)\nDefinition wp {A : tp pos} (Φ : [A] → Prop) : ⟪F A⟫ → Prop :=\n  fix: wp'; wp_F Φ (λ e, ⟨▷⟩ (wp' ⊛ next: e)).\n\n\nLemma wp_unfold {A : tp pos} {Φ : [A] → Prop} {e : ⟪F A⟫} : wp Φ e = wp_F Φ (fun e => ▷ (wp Φ e)) e.\nProof.\n  rewrite /wp {1} loeb_unfold /Later.map.\n  do ? f_equal; extensionality e'; f_equal.\n  by rewrite Later.ap_compute Later.dlater_compute.\nQed.\n\nGoal wp (λ v, v = tt) (head @ (cons @ tt @ zeroes)).\n  rewrite wp_unfold; apply: wp_step.\n  - by rewrite /head /cons; crush.\n  - apply: pnext.\n    rewrite wp_unfold.\n    by apply: wp_ret.\nQed.\n\n(* Only partial correctness ;-) *)\nGoal wp (λ v, v = tt) bot.\n  apply: ploeb => L.\n  rewrite wp_unfold; apply: wp_step; eauto.\n  by rewrite /bot {1} loeb_unfold.\nQed.\n", "meta": {"author": "jonsterling", "repo": "guarded-theories", "sha": "8cd3a5a669a9e0788277a7b288ff88fe0f42be40", "save_path": "github-repos/coq/jonsterling-guarded-theories", "path": "github-repos/coq/jonsterling-guarded-theories/guarded-theories-8cd3a5a669a9e0788277a7b288ff88fe0f42be40/Lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.21649116269402044}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire bedrock2.Syntax.\nRequire bedrock2.Semantics.\nRequire bedrock2.WeakestPrecondition.\nRequire Import bedrock2.Map.Separation.\nRequire Import bedrock2.Array bedrock2.Scalars.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Word.Interface.\nRequire Import Crypto.Language.API.\nImport ListNotations. Local Open Scope Z_scope.\nImport API.Compilers.\n\n(*** This file contains the setup for the bedrock2 backend; the type\n  system, the parameter class, and some shorthand notations. ***)\n\n(* Notations for commonly-used types in the fiat-crypto language *)\nModule Import Notations.\n  Notation base_range := (base.type.type_base base.type.zrange).\n  Notation base_nat := (base.type.type_base base.type.nat).\n  Notation base_Z := (base.type.type_base base.type.Z).\n  Notation base_listZ := (base.type.list base_Z).\n  Notation base_range2 := (base.type.prod base_range base_range).\n  Notation base_ZZ := (base.type.prod base_Z base_Z).\n\n  Notation type_range := (type.base base_range).\n  Notation type_nat := (type.base base_nat).\n  Notation type_Z := (type.base base_Z).\n  Notation type_listZ := (type.base base_listZ).\n  Notation type_range2 := (type.base base_range2).\n  Notation type_ZZ := (type.base base_ZZ).\nEnd Notations.\n\nClass parameters\n  {width: Z} {BW: Bitwidth.Bitwidth width} {word: word.word width} {mem: map.map word Byte.byte}\n  {locals: map.map String.string word}\n  {env: map.map String.string (list String.string * list String.string * Syntax.cmd)}\n  {ext_spec: bedrock2.Semantics.ExtSpec}\n  {varname_gen : nat -> String.string}\n  {error : Syntax.expr.expr} := parameters_sentinel : unit.\n\nSection WithParameters.\n  Context \n    {width BW word mem locals env ext_spec varname_gen error}\n   `{parameters_sentinel : @parameters\n     width BW word mem locals env ext_spec varname_gen error}.\n  Local Notation parameters := (ltac:(let t := type of parameters_sentinel in exact t)) (only parsing).\n  Class ok {parameters_sentinel : parameters} :=\n    {\n      (* semantics_ok : Semantics.parameters_ok semantics *)\n      word_ok :> word.ok word;\n      mem_ok :> map.ok mem;\n      locals_ok :> map.ok locals;\n      env_ok :> map.ok env;\n      ext_spec_ok :> Semantics.ext_spec.ok ext_spec;\n\n      varname_gen_unique :\n        forall i j : nat, varname_gen i = varname_gen j <-> i = j;\n    }.\n\n  Context {ok : ok}.\n  Lemma word_size_in_bytes_pos : 0 < Memory.bytes_per_word width.\n  Proof. destruct Bitwidth.width_cases as [H|H]; rewrite H; cbv; trivial. Qed.\n  Lemma width_0mod_8 : width mod 8 = 0.\n  Proof. destruct Bitwidth.width_cases as [H|H]; rewrite H; cbv; trivial. Qed.\nEnd WithParameters.\n\nModule rep.\n  Section rep.\n    Context \n      {width BW word mem locals env ext_spec varname_gen error}\n     `{parameters_sentinel : @parameters\n       width BW word mem locals env ext_spec varname_gen error}.\n    Local Notation parameters := (ltac:(let t := type of parameters_sentinel in exact t)) (only parsing).\n\n    Class rep {parameters_sentinel : parameters} (t : base.type) :=\n      { ltype : Type; (* type for LHS of assignment *)\n        rtype : Type; (* type for RHS of assignment *)\n        size : Type; (* amount of space taken in memory, if applicable *)\n        rtype_of_ltype : ltype -> rtype;\n        dummy_ltype : ltype;\n        make_error : rtype;\n        dummy_size : size;\n        varname_set : ltype -> PropSet.set string;\n        equiv : base.interp t -> rtype -> size -> locals -> mem -> Prop }.\n\n    (* store a list in local variables; each element of the list is\n       represented as a separate variable *)\n    Instance listZ_local {zrep : rep base_Z} : rep base_listZ :=\n      { ltype := list ltype;\n        rtype := list rtype;\n        size := size;\n        rtype_of_ltype := map rtype_of_ltype;\n        dummy_ltype := nil;\n        make_error := [make_error];\n        dummy_size := dummy_size;\n        varname_set :=\n          fold_right\n            (fun x s =>\n               PropSet.union (varname_set x) s) PropSet.empty_set;\n        equiv :=\n          fun (x : list Z) (y : list rtype) sz locals _ =>\n            Forall2 (fun a b => equiv a b sz locals map.empty) x y\n      }.\n\n    (* store a list in memory; the list is represented by one Z, which\n         is the location of the head of the list *)\n    Instance listZ_mem {zrep : rep base_Z} : rep base_listZ :=\n      { ltype := ltype;\n        rtype := rtype;\n        size := Syntax.access_size;\n        rtype_of_ltype := rtype_of_ltype;\n        dummy_ltype := dummy_ltype;\n        make_error := make_error;\n        dummy_size := Syntax.access_size.one;\n        varname_set := varname_set;\n        equiv :=\n          fun (x : list Z) (y : rtype) sz locals =>\n            Lift1Prop.ex1\n              (fun start : word =>\n                 Lift1Prop.ex1\n                   (fun ws : list word =>\n                      let bytes :=\n                          Z.of_nat (Memory.bytes_per (width:=width) sz) in\n                      sep (map:=mem)\n                          (sep\n                             (emp (map word.unsigned ws = x /\\\n                                   Forall\n                                     (fun z =>\n                                        (0 <= z < 2 ^ (bytes * 8))%Z)\n                                     x))\n                             (fun mem : mem =>\n                                equiv (word.unsigned start) y\n                                      (dummy_size (rep:=zrep))\n                                      locals mem))\n                          (array (truncated_scalar sz)\n                                 (word.of_Z bytes) start\n                                 (map word.unsigned ws))))\n      }.\n\n    Instance Z : rep base_Z :=\n      { ltype := String.string;\n        rtype := Syntax.expr.expr;\n        size := unit;\n        rtype_of_ltype := Syntax.expr.var;\n        dummy_ltype := varname_gen 0%nat;\n        make_error := error;\n        dummy_size := tt;\n        varname_set := PropSet.singleton_set;\n        equiv :=\n          fun (x : Z) (y : Syntax.expr.expr) _ locals =>\n            Lift1Prop.ex1\n              (fun w : word =>\n                 emp (word.unsigned w = x /\\\n                      WeakestPrecondition.dexpr\n                        map.empty locals y w))\n      }.\n  End rep.\nEnd rep.\n\nSection defs.\n  Context\n    {width BW word mem locals env ext_spec varname_gen error}\n   `{parameters_sentinel : @parameters\n     width BW word mem locals env ext_spec varname_gen error}.\n  Local Notation parameters := (ltac:(let t := type of parameters_sentinel in exact t)) (only parsing).\n  Context\n          (* list representation -- could be local or in-memory *)\n          {listZ : rep.rep base_listZ}.\n  Existing Instance rep.Z.\n\n  (* Types that appear in the bedrock2 expressions on the left-hand-side of\n     assignments (or in return values). For example, if we want to assign three\n     integers, we need three strings.\n\n     Functions can't appear on the left-hand-side, so we return garbage output\n     (the unit type). *)\n  Fixpoint base_ltype (t : base.type) : Type :=\n    match t with\n    | base.type.prod a b => base_ltype a * base_ltype b\n    | base_listZ => rep.ltype (rep:=listZ)\n    | _ => rep.ltype (rep:=rep.Z)\n    end.\n  Definition ltype (t : type.type base.type) : Type :=\n    match t with\n    | type.base t => base_ltype t\n    | type.arrow s d => unit (* garbage *)\n    end.\n\n  (* Types that appear in the bedrock2 expressions on the right-hand-side of\n       assignments. For example, if we want to assign three integers, we need\n       three [Syntax.expr.expr]s. *)\n  Fixpoint base_rtype (t : base.type) : Type :=\n    match t with\n    | base.type.prod a b => base_rtype a * base_rtype b\n    | base_listZ => rep.rtype (rep:=listZ)\n    | _ => rep.rtype (rep:=rep.Z)\n    end.\n  Fixpoint rtype (t : type.type base.type) : Type :=\n    match t with\n    | type.base a => base_rtype a\n    | type.arrow a b => rtype a -> rtype b\n    end.\n\n  (* error creation *)\n  Fixpoint base_make_error t : base_rtype t :=\n    match t with\n    | base.type.prod a b => (base_make_error a, base_make_error b)\n    | base_listZ => rep.make_error\n    |  _ => rep.make_error\n    end.\n  Fixpoint make_error t : rtype t :=\n    match t with\n    | type.base a => base_make_error a\n    | type.arrow a b => fun _ => make_error b\n    end.\n\n  (* These should only be used to fill holes in unreachable cases;\n     nothing about them should need to be proven *)\n  Fixpoint dummy_base_ltype (t : base.type) : base_ltype t :=\n    match t with\n    | base.type.prod a b => (dummy_base_ltype a, dummy_base_ltype b)\n    | base_listZ => rep.dummy_ltype\n    | _ => rep.dummy_ltype\n    end.\n  Definition dummy_ltype (t : API.type) : ltype t :=\n    match t with\n    | type.base a => dummy_base_ltype a\n    | type.arrow a b => tt\n    end.\n\n  (* convert ltypes to rtypes (used for renaming variables) - the opposite\n     direction is not permitted *)\n  Fixpoint base_rtype_of_ltype {t} : base_ltype t -> base_rtype t :=\n    match t with\n    | base.type.prod a b =>\n      fun x => (base_rtype_of_ltype (fst x),\n                base_rtype_of_ltype (snd x))\n    | base_listZ => rep.rtype_of_ltype\n    | _ => Syntax.expr.var\n    end.\n  Fixpoint rtype_of_ltype t\n    : ltype t -> rtype t :=\n    match t as t0 return ltype t0 -> rtype t0 with\n    | type.base b => base_rtype_of_ltype\n    | type.arrow a b =>\n      (* garbage; not a valid ltype *)\n      fun (_:unit) =>\n        fun (x : rtype a) =>\n          rtype_of_ltype b (dummy_ltype b)\n    end.\n\n  Fixpoint base_access_sizes t :=\n    match t with\n    | base.type.prod a b =>\n      (base_access_sizes a * base_access_sizes b)%type\n    | base_listZ => rep.size (rep:=listZ)\n    | _ => rep.size (rep:=rep.Z)\n    end.\n  Definition access_sizes t :=\n    match t with\n    | type.base b => base_access_sizes b\n    | _ => unit\n    end.\n\n  Fixpoint base_dummy_access_sizes t : base_access_sizes t :=\n    match t with\n    | base.type.prod a b =>\n      (base_dummy_access_sizes a, base_dummy_access_sizes b)\n    | base_listZ => rep.dummy_size\n    | _ => rep.dummy_size\n    end.\n  Definition dummy_access_sizes t : access_sizes t :=\n    match t with\n    | type.base b => base_dummy_access_sizes b\n    | _ => tt\n    end.\n  Fixpoint dummy_access_sizes_args t :\n    type.for_each_lhs_of_arrow access_sizes t :=\n    match t with\n    | type.base _ => tt\n    | type.arrow s d =>\n      (dummy_access_sizes s, dummy_access_sizes_args d)\n    end.\n\n  Definition baseonly (f : base.type -> Type) t : Type :=\n    match t with\n    | type.base b => f b\n    | type.arrow _ _ => unit\n    end.\n\n  (* Types for partitioning return values into list and non-list *)\n  Section ListOnlyListExcl.\n    Fixpoint base_listonly (T : Type) t : Type :=\n      match t with\n      | base.type.prod a b =>\n        (base_listonly T a * base_listonly T b)\n      | base_listZ => T\n      | _ => unit\n      end.\n    Fixpoint base_listexcl (f : base.type -> Type) t : Type :=\n      match t with\n      | base.type.prod a b =>\n        base_listexcl f a * base_listexcl f b\n      | base_listZ => unit\n      | _ => f t\n      end.\n    Definition listonly T := baseonly (base_listonly T).\n    Definition listexcl f := baseonly (base_listexcl f).\n\n    Definition list_lengths (t : API.type) :=\n      listonly nat t.\n    Definition listonly_base_ltype t :=\n      base_listonly (base_ltype base_listZ) t.\n    Definition listexcl_base_ltype t :=\n      base_listexcl base_ltype t.\n    Definition listonly_base_rtype t :=\n      base_listonly (base_rtype base_listZ) t.\n    Definition listexcl_base_rtype t :=\n      base_listexcl base_rtype t.\n\n    Fixpoint map_listonly {A B t} (f : A -> B)\n      : base_listonly A t -> base_listonly B t :=\n      match t as t0 return\n            base_listonly A t0 -> base_listonly B t0 with\n      | base.type.prod a b =>\n        fun x =>\n          (map_listonly f (fst x), map_listonly f (snd x))\n      | base_listZ => f\n      | _ => fun _ => tt\n      end.\n    Fixpoint map_listexcl {t}\n             {f g : base.type -> Type}\n             (F : forall t, f t -> g t)\n      : base_listexcl f t -> base_listexcl g t :=\n      match t as t0 return\n            base_listexcl f t0 -> base_listexcl g t0 with\n      | base.type.prod a b =>\n        fun x =>\n          (map_listexcl F (fst x), map_listexcl F (snd x))\n      | base_listZ => fun _ => tt\n      | _ => F _\n      end.\n  End ListOnlyListExcl.\nEnd defs.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Bedrock/Field/Common/Types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.2163885625344265}}
{"text": "(* Assume insertion: inserting Assume instructions *)\n(* A pass of the dynamic optimizer *)\n(* To insert an assume, you need a guard (what to speculate on) *)\n(* And you need a label where there is a framestate, that you want to copy the metadata of *)\n(* And the Assume is inserted next to that Framestate instruction *)\n\nRequire Export List.\nRequire Export Coqlib.\nRequire Export Maps.\nRequire Export specIR.\nRequire Import Coq.MSets.MSetPositive.\nRequire Export def_regs.\n\n(** * Guard checking  *)\n(* To ensure that the Assume does not intriduce bugs, *)\n(* We check that the guard can evaluate without errors *)\nDefinition check_reg (r:reg) (def:regset) : bool :=\n  PositiveSet.mem r def.\n\nDefinition check_op (o:op) (def:regset) : bool :=\n  match o with\n  | Reg r => check_reg r def\n  | Cst _ => true\n  end.\n\nDefinition check_expr (e:expr) (def:regset): bool :=\n  match e with\n  | Binexpr _ o1 o2 => andb (check_op o1 def) (check_op o2 def)\n  | Unexpr _ o => check_op o def\n  end.\n\n(* making sure that the guard can evaluate, given a set of defined registers *)\nFixpoint check_guard (guard:list expr) (def:regset): bool :=\n  match guard with\n  | nil => true\n  | e::guard' =>\n    andb (check_expr e def) (check_guard guard' def)\n  end.   \n\n\n(** * The optimization that inserts Assume directly after the Framestate *)\n\n(* Verify that the assume can be inserted: no code between assume and Framestate *)\nDefinition validator (v:version) (fs_lbl: label) (guard:list expr) (params: list reg): res unit :=\n  match ((ver_code v)#fs_lbl) with\n  | Some (Framestate _ _ _ next) =>\n    do abs <- try_op (defined_regs_analysis (ver_code v) params (ver_entry v)) \"Def_regs analysis failed\";\n      do def_regs <- OK(def_absstate_get fs_lbl abs);\n      match def_regs with\n      | DefFlatRegset.Inj def =>\n        match (check_guard guard def) with\n        | true => OK tt\n        | false => Error \"The guard might evaluate to an error\"\n        end\n      | DefFlatRegset.Top => Error \"The analysis couldn't get the exact set of defined registers: TOP\"\n      | DefFlatRegset.Bot => Error \"The analysis couldn't get the exact set of defined registers: BOT\"\n      end\n  | _ => Error \"Not pointing to a valid Framestate\"\n  end.\n\n(* Returns the version where the Assume has been inserted *)\nDefinition insert_assume_version (v:version) (fid:fun_id) (guard:list expr) (fsl:label) (params:list reg): res version :=\n  do code <- OK(ver_code v);\n    do freshlbl <- OK (fresh_label (Pos.succ fsl) code);\n    do _ <- validator v fsl guard params; (* validating that the assume can be inserted *)\n    match code # fsl with\n    | Some (Framestate tgt vm sl next) =>\n      do instr <- try_op (code # next) \"Next Label is not used in the function\";\n        do update_fs <- OK (code # fsl <- (Framestate tgt vm sl freshlbl));\n        do new_code <- OK (update_fs # freshlbl <- (Assume guard tgt vm sl next));\n        (* in the new assume, the deopt target, the varmap and the synth list are copied from the framestate *)\n        OK (mk_version new_code (ver_entry v))\n    | _ => Error \"Not pointing to a valid Framestate\"\n    end.\n\n(* The optimization pass *)\nDefinition insert_assume (fid: fun_id) (guard:list expr) (fs_lbl: label) (p:program): res program :=\n  do f <- try_op (find_function fid p) \"Function to optimize not found\";\n    do v <- OK(current_version f); (* the optimized code if it exists, the base version otherwise *)\n    do newv <- insert_assume_version v fid guard fs_lbl (fn_params f);\n    do new_program <- OK (set_version p fid newv);\n    OK (new_program).\n    \n\nDefinition safe_insert_assume (p:program) (fid:fun_id) (guard:list expr) (fs_lbl: label): program :=\n  safe_res (insert_assume fid guard fs_lbl) p.\n", "meta": {"author": "Aurele-Barriere", "repo": "CoreJIT", "sha": "8740d4149be649d0746d9f0d2d759b387a8f3246", "save_path": "github-repos/coq/Aurele-Barriere-CoreJIT", "path": "github-repos/coq/Aurele-Barriere-CoreJIT/CoreJIT-8740d4149be649d0746d9f0d2d759b387a8f3246/src/coqjit/assume_insertion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21638856253442648}}
{"text": "Require Export Fiat.QueryStructure.Specification.Representation.QueryStructureNotations\n        Fiat.QueryStructure.Specification.Operations.Query.\nRequire Import Coq.Lists.List\n        Coq.Arith.Compare_dec\n        Coq.Bool.Bool\n        Coq.Strings.String\n        Coq.Strings.Ascii\n        Fiat.Common.BoolFacts\n        Fiat.Common.List.PermutationFacts\n        Fiat.Common.List.ListMorphisms\n        Fiat.Common.Tactics.CacheStringConstant\n        Fiat.QueryStructure.Specification.Operations.FlattenCompList\n        Fiat.Common.Ensembles.EnsembleListEquivalence\n        Fiat.QueryStructure.Implementation.Operations.General.QueryRefinements\n        Fiat.Common.IterateBoundedIndex\n        Fiat.Common.List.ListFacts\n        Fiat.Common.LogicFacts\n        Fiat.Common.DecideableEnsembles\n        Fiat.QueryStructure.Specification.Constraints.tupleAgree\n        Fiat.QueryStructure.Specification.Operations.Mutate\n        Fiat.QueryStructure.Implementation.Constraints.ConstraintChecksRefinements\n        Fiat.QueryStructure.Automation.Common.\n\nLtac dec_tauto :=\n  clear; intuition eauto;\n  eapply Tuple_Agree_eq_dec;\n  match goal with\n  | [ |- ?E = true ] => case_eq E; intuition idtac; [ exfalso ]\n  end;\n  match goal with\n  | [ H : _ |- _ ] => apply Tuple_Agree_eq_dec' in H; solve [ eauto ]\n  end.\n\nLemma query_eq_true_iff {A}\n      (q_eq : Query_eq A)\n  : forall (a a' : A), ?[ A_eq_dec a a'] = true <-> a = a'.\nProof.\n  intros; destruct (A_eq_dec a a'); split; intros; try congruence.\nQed.\n\nLtac prove_decidability_for_functional_dependencies :=\n  simpl; econstructor; intros;\n  (*repeat setoid_rewrite <- (@query_eq_true_iff _ _); *)\n  try setoid_rewrite <- eq_nat_dec_bool_true_iff;\n  try setoid_rewrite <- eq_N_dec_bool_true_iff;\n  try setoid_rewrite <- eq_Z_dec_bool_true_iff;\n  try setoid_rewrite <- string_dec_bool_true_iff;\n  try setoid_rewrite <- ascii_dec_bool_true_iff;\n  setoid_rewrite and_True;\n  repeat progress (\n           try setoid_rewrite <- andb_true_iff;\n           try setoid_rewrite not_true_iff_false;\n           try setoid_rewrite <- negb_true_iff);\n  rewrite bool_equiv_true;\n  reflexivity.\n\nHint Extern 100 (DecideableEnsemble _) => prove_decidability_for_functional_dependencies : typeclass_instances.\n\nTactic Notation \"refine\" \"existence\" \"check\" \"into\" \"query\" :=\n  match goal with\n    |- context[{b | decides b\n                            (exists tup : @IndexedTuple ?heading,\n                                (@GetUnConstrRelation ?qs_schema ?qs ?tbl tup /\\ @?P tup))}]\n    =>\n    let H1 := fresh in\n    let H2 := fresh in\n    makeEvar (Ensemble (@Tuple heading))\n             ltac:(fun P' => assert (Same_set (@IndexedTuple heading) (fun t => P' (indexedElement t)) P) as H1;\n                   [unfold Same_set, Included, Ensembles.In;\n                     split; [intros x H; pattern (indexedElement x);\n                             match goal with\n                               |- ?P'' (indexedElement x) => unify P' P'';\n                                 simpl; eauto\n                             end\n                            | eauto]\n                   |\n                   assert (DecideableEnsemble P') as H2;\n                     [ simpl; eauto with typeclass_instances (* Discharge DecideableEnsemble w/ intances. *)\n                     | setoid_rewrite (@refine_constraint_check_into_query' qs_schema tbl qs P P' H2 H1); clear H1 H2 ] ]) end.\n\nLtac funDepToQuery :=\n  match goal with\n  | |-\n    context [{b : _ |\n              decides b\n                      (forall tup' : @IndexedElement ?T,\n                          GetUnConstrRelation (QSSchema := ?qsSchema) ?or ?Ridx _ ->\n                          @FunctionalDependency_P ?heading ?attrlist1 ?attrlist2 ?n _)}] =>\n    let H' := fresh in\n    let H'' := fresh in\n    let refine_fundep := fresh in\n    assert\n      ((forall (tup' : @IndexedElement T),\n           GetUnConstrRelation or Ridx tup' ->\n           @FunctionalDependency_P heading attrlist1 attrlist2 n (indexedElement tup')) <->\n       (forall tup' : @IndexedElement T,\n           ~\n             (GetUnConstrRelation or Ridx tup' /\\\n              @tupleAgree heading n (indexedElement tup') attrlist2 /\\\n              ~ @tupleAgree heading n (indexedElement tup') attrlist1)))\n      as H' by (unfold FunctionalDependency_P; dec_tauto);\n      assert\n        (DecideableEnsemble\n           (fun x : T =>\n              @tupleAgree_computational heading n x attrlist2 /\\\n              ~ @tupleAgree_computational heading n x attrlist1))\n      as H''\n        by (subst_all;\n            FunctionalDependencyAutomation.prove_decidability_for_functional_dependencies);\n      (let refine_fundep :=\n           eval simpl in\n       ( (@refine_functional_dependency_check_into_query qsSchema Ridx n attrlist2\n                                                         attrlist1 or H'' H')) in\n           setoid_rewrite refine_fundep; clear H'' H')\n  end.\n\nLtac fundepToQuery :=\n  match goal with\n  | [ |- context[Pick\n                   (fun b => decides\n                               b\n                               (forall tup' : @IndexedRawTuple ?sch,\n                                   GetUnConstrRelation (QSSchema := ?qs_schema) ?or ?Ridx _\n                                   -> @FunctionalDependency_P ?heading ?attrlist1 ?attrlist2 ?n _))] ] =>\n    let H' := fresh in\n    let H'' := fresh in\n    let refine_fundep := fresh in\n    assert ((forall tup' : IndexedRawTuple,\n                GetUnConstrRelation or Ridx tup'\n                -> @FunctionalDependency_P heading attrlist1 attrlist2 n (indexedElement tup'))\n            <-> (forall tup' : IndexedRawTuple,\n                    ~ (GetUnConstrRelation or Ridx tup'\n                       /\\ @tupleAgree sch n (indexedElement tup') attrlist2\n                       /\\ ~ @tupleAgree sch n (indexedElement tup') attrlist1))) as H'\n        by (unfold FunctionalDependency_P; dec_tauto);\n      assert (DecideableEnsemble (fun x : RawTuple =>\n                                    @tupleAgree_computational sch n x attrlist2 /\\\n                                    ~ @tupleAgree_computational sch n x attrlist1)) as H''\n        by (subst_all;\n            prove_decidability_for_functional_dependencies);\n      let refine_fundep := eval simpl in (@refine_functional_dependency_check_into_query qs_schema Ridx n attrlist2 attrlist1 or H'' H') in\n          (* as refine_fundep; simpl in refine_fundep;\n        fold_heading_hyps_in refine_fundep; fold_string_hyps_in refine_fundep; *)\n          setoid_rewrite refine_fundep; clear H'' H'\n  | [ |- context[Pick\n                   (fun b => decides\n                               b\n                               (forall tup' : @IndexedRawTuple ?sch,\n                                   GetUnConstrRelation ?or ?Ridx _\n                                   -> @FunctionalDependency_P ?heading ?attrlist1 ?attrlist2 _ ?n ))] ] =>\n    let H' := fresh in\n    let H'' := fresh in\n    let refine_fundep := fresh in\n    assert ((forall tup' : IndexedTuple,\n                GetUnConstrRelation or Ridx tup'\n                -> @FunctionalDependency_P heading attrlist1 attrlist2 (indexedElement tup') n)\n            <-> (forall tup' : IndexedTuple,\n                    ~ (GetUnConstrRelation or Ridx tup'\n                       /\\ @tupleAgree sch (indexedElement tup') n attrlist2\n                       /\\ ~ @tupleAgree sch (indexedElement tup') n attrlist1))) as H'\n        by (unfold FunctionalDependency_P; dec_tauto);\n      assert (DecideableEnsemble (fun x : Tuple =>\n                                    @tupleAgree_computational sch x n attrlist2 /\\\n                                    ~ @tupleAgree_computational sch x n attrlist1)) as H''\n        by prove_decidability_for_functional_dependencies;\n      let refine_fundep := eval simpl in\n      (@refine_functional_dependency_check_into_query' _ _ n attrlist2 attrlist1 or H'' H') in\n          (*simpl in refine_fundep; setoid_rewrite refine_fundep; *) clear H'' H'\n  end; try simplify with monad laws; pose_string_hyps; pose_heading_hyps.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/QueryStructure/Automation/Constraints/FunctionalDependencyAutomation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21638856253442648}}
{"text": "(*\n * Copyright (c) 2009-2010, Andrew Appel, Robert Dockins and Aquinas Hobor.\n *\n *)\n\nRequire Import VST.msl.base.\nRequire Import VST.msl.ageable.\nRequire Import VST.msl.sepalg.\nRequire Import VST.msl.sepalg_generators.\nRequire Import VST.msl.age_sepalg.\nRequire Import VST.msl.predicates_hered.\nRequire Import VST.msl.cross_split.\n\nDefinition compareR {A} {JA: Join A}{SA: Sep_alg A}{AG: ageable A} : relation A\n   := comparable.\nDefinition extendR  {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A} : relation A := join_sub.\n\nLemma valid_rel_compare {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : valid_rel compareR.\nProof.\n  split; hnf; intros.\n\n  apply comparable_common_unit in H0.\n  destruct H0 as [w [? ?]].\n  destruct (age1_join2  _ H1 H)\n    as [u [v [? [? ?]]]].\n  destruct (age1_join _ H0 H3)\n    as [u' [v' [? [? ?]]]].\n  assert (u' = v').\n  unfold age in *; congruence.\n  subst v'.\n  exists u'; auto.\n  assert (x = v).\n  unfold age in *; congruence.\n  subst v.\n  apply common_unit_comparable.\n  exists u; auto.\n\n  apply comparable_common_unit in H.\n  destruct H as [w [? ?]].\n  destruct (unage_join2 _ H H0)\n    as [u [v [? [? ?]]]].\n  destruct (unage_join _ H1 H3)\n    as [u' [v' [? [? ?]]]].\n  exists v'; auto.\n  apply common_unit_comparable.\n  destruct (join_ex_units u) as [uu Huu].\n  red in Huu.\n  exists uu; split.\n  destruct (join_assoc Huu H2) as [q [? ?]].\n  assert (q = z).\n  eapply join_eq; eauto.\n  subst q; auto.\n  destruct (join_assoc Huu H5) as [q [? ?]].\n  assert (q = v').\n  eapply join_eq; eauto.\n  subst q.\n  auto.\nQed.\n\nLemma valid_rel_extend {A}  {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A} : valid_rel extendR.\nProof.\n  intros; split; hnf; intros.\n  destruct H0 as [w ?].\n  destruct (age1_join2 _ H0 H)\n    as [u [v [? [? ?]]]].\n  exists u; auto.\n  exists v; auto.\n\n  destruct H.\n  destruct (unage_join _ H H0)\n    as [u [v [? [? ?]]]].\n  exists v; auto.\n  exists u; auto.\nQed.\n\nDefinition compareM {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : modality\n  := exist _ compareR valid_rel_compare.\nDefinition extendM {A}{JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A} : modality\n  := exist _ extendR valid_rel_extend.\n\n(* Definitions of the BI connectives. *)\nObligation Tactic := unfold hereditary; intros; try solve [intuition].\n\nProgram Definition emp {A}  {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : pred A := identity.\nNext Obligation.\n  repeat intro.\n  destruct (unage_join _ H1 H) as [a0' [b' [? [? ?]]]].\n  apply H0 in H2. subst b'. unfold age in H3, H4. congruence.\nQed.\n\nProgram Definition sepcon {A}  {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A} (p q:pred A) : pred A := fun x:A =>\n  exists y:A, exists z:A, join y z x /\\ p y /\\ q z.\nNext Obligation.\n  destruct H0 as [y [z [? [? ?]]]].\n  destruct (age1_join2 _ H0 H) as [w [v [? [? ?]]]].\n  exists w; exists v; split; auto.\n  split.\n  apply pred_hereditary with y; auto.\n  apply pred_hereditary with z; auto.\nQed.\n\nProgram Definition wand {A}  {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A} (p q:pred A) : pred A := fun x =>\n  forall x' y z, necR x x' -> join x' y z -> p y -> q z.\nNext Obligation.\n  apply H0 with x' y; auto.\n  apply rt_trans with a'; auto.\n  apply rt_step; auto.\nQed.\n\nNotation \"P '*' Q\" := (sepcon P Q) : pred.\nNotation \"P '-*' Q\" := (wand P Q) (at level 60, right associativity) : pred.\nNotation \"'%' e\"  := (box extendM e)(at level 30, right associativity): pred.\n\nLemma extendM_refl {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}: reflexive _ extendM.\nProof.\nintros; intro; simpl; apply join_sub_refl.\nQed.\n\nLemma compareM_refl {A}{JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : reflexive _ compareM.\nProof.\nintros; intro; simpl.\napply comparable_refl.\nQed.\n\nHint Resolve @extendM_refl.\nHint Resolve @compareM_refl.\n\n\n(* Rules for the BI connectives *)\n\nLemma wand_sepcon_adjoint {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A} : forall (P Q R:pred A),\n  ((P * Q) |-- R) = (P |-- (Q -* R)).\nProof.\n  intros. apply prop_ext.\n  split; intros.\n  hnf; intros; simpl; intros.\n  apply H.\n  exists x'; exists y.\n  intuition.\n  apply pred_nec_hereditary with a; auto.\n  hnf; intros.\n  hnf in H.\n  unfold wand in H; simpl in H.\n  destruct H0 as [w [v [? [? ?]]]].\n  eapply H; eauto.\nQed.\n\nLemma sepcon_assoc {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A} : forall (P Q R:pred A),\n  ((P * Q) * R = P * (Q * R))%pred.\nProof.\n  pose proof I.\n  intros; apply pred_ext; hnf; intros.\n  destruct H0 as [x [y [? [? ?]]]].\n  destruct H1 as [z [w [? [? ?]]]].\n  destruct (join_assoc H1 H0) as [q [? ?]].\n  exists z; exists q; intuition.\n  exists w; exists y; intuition.\n  destruct H0 as [x [y [? [? ?]]]].\n  destruct H2 as [z [w [? [? ?]]]].\n  apply join_comm in H0.\n  apply join_comm in H2.\n  destruct (join_assoc H2 H0) as [q [? ?]].\n  exists q; exists w; intuition.\n  exists x; exists z; intuition.\nQed.\n\nLemma sepcon_comm {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A} : forall (P Q:pred A),\n  (P * Q = Q * P)%pred.\nProof.\n  pose proof I.\n  intros; apply pred_ext; hnf; intros.\n  destruct H0 as [x [y [? [? ?]]]].\n  exists y; exists x; intuition; apply join_comm; auto.\n  destruct H0 as [x [y [? [? ?]]]].\n  exists y; exists x; intuition; apply join_comm; auto.\nQed.\n\nLemma split_sepcon {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A} : forall (P Q R S:pred A),\n  P |-- Q ->\n  R |-- S ->\n  (P * R) |-- (Q * S).\nProof.\n  intros; hnf; intros.\n  destruct H1 as [x [y [? [? ?]]]].\n  exists x; exists y; intuition.\nQed.\n\nLemma sepcon_cut {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A} : forall (P Q R S:pred A),\n  P |-- (Q -* R) ->\n  S |-- Q ->\n  (P * S) |-- R.\nProof.\n  intros.\n  rewrite wand_sepcon_adjoint.\n  hnf; intros.\n  simpl; intros.\n  eapply H; eauto.\nQed.\n\nLemma emp_sepcon {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : forall (P:pred A),\n  (emp * P = P)%pred.\nProof.\n  intros; apply pred_ext; hnf; intros.\n  destruct H as [x [y [? [? ?]]]].\n  simpl in H0.\n  replace a with y; auto.\n  destruct (join_ex_identities a) as [u [Hu [? Hj]]].\n  exists u; exists a. split; auto.\n  specialize (Hu _ _ Hj); subst; auto.\nQed.\n\nLemma sepcon_emp {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}  : forall (P:pred A),\n  (P * emp = P)%pred.\nProof.\n  intros.\n  rewrite sepcon_comm.\n  apply emp_sepcon.\nQed.\n\n(*Lemma emp_sepcon : forall {A} `{Age_alg A} (P:pred A), emp * P = P.\nProof. exact @emp_sepcon. Qed.\nLemma sepcon_emp : forall {A} `{Age_alg A} (P:pred A), P * emp = P.\nProof. exact @sepcon_emp. Qed.\n*)\n\t\nLemma later_wand {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A} : forall P Q,\n  (|>(P -* Q) = |>P -* |>Q)%pred.\nProof.\n  pose proof I.\n  intros.\n  repeat rewrite later_age.\n  apply pred_ext; hnf; intros.\n  simpl; intros.\n  simpl in H0.\n  case_eq (age1 a); intros.\n  specialize ( H0 a0 H5).\n  apply nec_refl_or_later in H1.\n  destruct H1; subst.\n  destruct (age1_join2 _ H2 H4) as [w [v [? [? ?]]]].\n  eapply H0; eauto.\n  replace a0 with w; auto.\n  congruence.\n  assert (necR a0 x').\n  eapply age_later_nec; eauto.\n  destruct (age1_join2 _ H2 H4) as [w [v [? [? ?]]]].\n  apply H0 with w v; auto.\n  apply rt_trans with x'; auto.\n  apply rt_step; auto.\n  apply nec_refl_or_later in H1; destruct H1; subst.\n  destruct (age1_join2 _  H2 H4) as [w [v [? [? ?]]]].\n  hnf in H6.\n  rewrite H5 in H6; discriminate.\n  clear -H1 H5.\n  elimtype False.\n  revert H5; induction H1; auto.\n  intros.\n  unfold age in H.\n  rewrite H in H5; discriminate.\n\n  simpl; intros.\n  simpl in H0.\n  destruct (valid_rel_nec).\n  destruct (H6 _ _ H2 _ H1).\n  destruct (unage_join _ H3 H7) as [w [v [? [? ?]]]].\n  apply H0 with x w v; auto.\n  intros.\n  replace a'0 with y; auto.\n  congruence.\nQed.\n\nLemma later_sepcon {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : forall P Q,\n  (|>(P * Q) = |>P * |>Q)%pred.\nProof.\n  pose (H:=True).\n  intros.\n  repeat rewrite later_age.\n  apply pred_ext; hnf; intros.\n  simpl in H0.\n  case_eq (age1 a); intros.\n  destruct (H0 a0) as [w [v [? [? ?]]]]; auto.\n  destruct (unage_join2 _ H2 H1) as [w' [v' [? [? ?]]]].\n  exists w'; exists v'; intuition.\n  simpl; intros.\n  replace a' with w; auto.\n  unfold age in *; congruence.\n  simpl; intros.\n  replace a' with v; auto.\n  unfold age in *; congruence.\n  destruct (join_ex_units a).\n  exists x; exists a.\n  intuition.\n  hnf; intros.\n  red in u.\n  simpl in H2.\n  destruct (age1_join _ u H2) as [s [t [? [? ?]]]].\n  unfold age in H5.\n  rewrite H1 in H5; discriminate.\n  hnf; intros.\n  simpl in H2.\n  unfold age in H2.\n  rewrite H1 in H2; discriminate.\n\n  destruct H0 as [w [v [? [? ?]]]].\n  hnf; intros.\n  simpl in H3.\n  destruct (age1_join2 _ H0 H3) as [w' [v' [? [? ?]]]].\n  exists w'; exists v'; intuition.\nQed.\n\nLemma FF_sepcon : forall {A}{JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A} (P:pred A),\n  (FF * P = FF)%pred.\nProof.\n  intros. apply pred_ext; repeat intro.\n  destruct H as [? [? [? [? ?]]]].  elim H0.\n  elim H.\nQed.\n\nLemma sepcon_derives {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall p q p' q', (p |-- p') -> (q |-- q') -> (p * q |-- p' * q').\nProof.\nintros.\ndo 2 intro.\ndestruct H1 as [w1 [w2 [? [? ?]]]].\nexists w1; exists w2; repeat split ;auto.\nQed.\n\nLemma exp_sepcon1 {A}  {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall T (P: T ->  pred A) Q,  (exp P * Q = exp (fun x => P x * Q))%pred.\nProof.\nintros.\napply pred_ext; intros ? ?.\ndestruct H as [w1 [w2 [? [[x ?] ?]]]].\nexists x; exists w1; exists w2; split; auto.\ndestruct H as [x [w1 [w2 [? [? ?]]]]].\nexists w1; exists w2; split; auto.\nsplit; auto.\nexists x; auto.\nQed.\n\nLemma exp_sepcon2 {A}  {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall T (P: pred A) (Q: T -> pred A),  (P * exp Q = exp (fun x => P * Q x))%pred.\nProof.\nintros.\napply pred_ext; intros ? ?.\ndestruct H as [w1 [w2 [? [? [x ?]]]]].\nexists x; exists w1; exists w2; split; auto.\ndestruct H as [x [w1 [w2 [? [? ?]]]]].\nexists w1; exists w2; split; auto.\nsplit; auto.\nexists x; auto.\nQed.\n\nLemma extend_later {A}  {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}: forall P, (%|>P = |>%P)%pred.\nProof.\n  intros; rewrite later_commute; auto.\nQed.\n\nLemma extend_later' {A}{JA: Join A}{PA: Perm_alg A}{agA: ageable A}{AgeA: Age_alg A}: forall P, boxy extendM P -> boxy extendM (|> P).\nProof.\nintros. unfold boxy in *. rewrite later_commute. rewrite H. auto.\nQed.\nHint Resolve @extend_later'.\n\nLemma age_sepcon {A}  {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} :\n      forall P Q, (box ageM (P * Q) = box ageM P * box ageM Q)%pred.\nProof.\n  pose proof I.\n  intros.\n  apply pred_ext; hnf; intros.\n  hnf in H0.\n  case_eq (age1 a); intros.\n  destruct (H0 a0) as [u [v [? [? ?]]]]; auto.\n  red.\n  destruct (unage_join2 _ H2 H1) as [x [y [? [? ?]]]].\n  exists x; exists y.\n  intuition.\n  hnf; intros.\n  replace a' with u; auto.\n  unfold age in *; congruence.\n  hnf; intros.\n  replace a' with v; auto.\n  unfold age in *; congruence.\n  destruct (join_ex_units a).\n  exists x; exists a.\n  intuition.\n  hnf; intros.\n  red in u.\n  destruct (age1_join _ u H2)\n    as [p [q [? [? ?]]]]; auto.\n  unfold age in *.\n  rewrite H1 in H4; discriminate.\n  hnf; intros.\n  simpl in *.\n  unfold age in *.\n  rewrite H1 in H2; discriminate.\n\n  destruct H0 as [u [v [? [? ?]]]].\n  hnf; intros.\n  destruct (age1_join2 _ H0 H3)\n    as [p [q [? [? ?]]]]; auto.\n  exists p; exists q; intuition.\nQed.\n\n\nLemma age_twin {A}  {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall phi1 phi2 n phi1',\n  comparable phi1 phi2 ->\n  ageN n phi1 = Some phi1' ->\n  exists phi2', ageN n phi2 = Some phi2' /\\ comparable phi1' phi2'.\nProof.\nintros until n; revert n phi1 phi2.\ninduction n; intros.\nexists phi2.\nsplit; trivial.\ninversion H0.\nsubst phi1'.\ntrivial.\nunfold ageN in H0.\nsimpl in H0.\nrevert H0; case_eq (age1 phi1); intros; try discriminate.\nrename a into phi.\nassert (exists ophi2, age phi2 ophi2 /\\ comparable phi ophi2).\ndestruct (comparable_common_unit H) as [e [? ?]].\ndestruct (age1_join _ (join_comm H2) H0) as [eo [phi1'a [eof [? ?]]]].\ndestruct (age1_join _ H3 H4) as [phi2' [phi2'a [eof' [? ?]]]].\nunfold age in H7. rewrite H6 in H7. symmetry in H7; inv H7.\nrewrite H5 in H0. inv H0.\nexists phi2'. split; auto.\napply common_unit_comparable; exists eo; split; auto.\ndestruct H2 as [ophi2 [? ?]].\nspecialize (IHn _ _ _ H3 H1).\ndestruct IHn as [phi2' [? ?]].\nexists phi2'.\nsplit; trivial.\nunfold ageN.\nsimpl.\nrewrite H2.\ntrivial.\nQed.\n\nLemma ageN_different {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}: forall n phi phi', ageN (S n) phi = Some phi' ->\n    ~ comparable phi phi'.\nProof.\n   intros.\n   intro.\n   generalize (age_noetherian' phi); intros [k [[? [? ?]] H4]].\n   assert (k <= n \\/ k > n)%nat by omega.\n   destruct H3.\n   replace (S n) with (k + (S n - k))%nat in H by omega.\n   destruct (ageN_compose' _ _ _ _ H) as [b [? ?]].\n   rewrite H1 in H5; inv H5.\n   replace (S n - k)%nat with (S (n-k))%nat in H6 by omega.\n   unfold ageN in H6; simpl in H6. rewrite H2 in H6; inv H6.\n   replace k with (S n + (k - S n))%nat in H1 by omega.\n   destruct (ageN_compose' _ _ _ _ H1) as [c [? ?]].\n   rewrite H in H5; inv H5.\n   destruct (age_twin phi c _ _ H0 H1) as [b [? ?]].\n   replace (S n + (k - S n))%nat with ((k - S n) + S n)%nat in H5 by omega.\n   destruct (ageN_compose' _ _ _ _ H5) as [d [? ?]].\n   rewrite H6 in H8; inv H8.\n   clear - H9 H2.\n   unfold ageN in H9; simpl  in H9; rewrite H2 in H9; inv H9.\nQed.\n\nLemma necR_comparable{A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall w w', necR w w' -> comparable w w' -> w=w'.\nProof.\nintros.\nrewrite necR_evolve in H.\ndestruct H as [n H].\ndestruct n.\ninv H; auto.\ncontradiction (ageN_different _ _ _ H); auto.\nQed.\n\n\nLemma sepcon_andp_prop {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall P Q R, (P * (!!Q && R) = !!Q && (P * R))%pred.\nProof.\nintros.\napply pred_ext; intros w ?.\ndestruct H as [w1 [w2 [? [? [? ?]]]]].\nsplit. apply H1.\nexists w1; exists w2; split; [|split]; auto.\ndestruct H.\ndestruct H0 as [w1 [w2 [? [? ?]]]].\nexists w1; exists w2; repeat split; auto.\nQed.\n\nLemma TT_sepcon_TT {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}: (TT * TT = TT)%pred.\nProof.\nintros.\napply pred_ext; intros w ?; auto.\ndestruct (join_ex_units w).\nexists x; exists w; split; auto.\nQed.\n\n\nLemma join_exactly {A}  {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall w1 w2 w3, join w1 w2 w3 ->  (exactly w1 * exactly w2 = exactly w3)%pred.\nProof.\npose proof I.\nintros.\nunfold exactly.\napply pred_ext; intros w ?; simpl in *.\ndestruct H1 as [? [? [? [? ?]]]].\ndestruct (nec_join H0 H2) as [a [b [? [? ?]]]].\nassert (x0=a).\n eapply necR_linear'; eauto.\n  transitivity (level x).\n  symmetry; apply comparable_fashionR. eapply join_comparable2; eauto.\n  apply comparable_fashionR. eapply join_comparable2; eauto.\nsubst x0.\ngeneralize (join_eq H4 H1); clear H4; intro; subst.\nauto.\neapply nec_join2; eauto.\nQed.\n\nLemma extend_sepcon_andp {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall P Q R, boxy extendM Q -> P * (Q && R) |-- Q && (P * R).\nProof.\nintros.\nintros ?w [?w [?w [? [? [? ?]]]]].\nsplit.\nrewrite <- H in H2.\neapply H2.\nexists w0.\napply join_comm; auto.\nexists w0; exists w1; auto.\nQed.\nArguments extend_sepcon_andp : clear implicits.\n\nLemma distrib_sepcon_andp {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall P Q R, P * (Q && R) |-- (P * Q) && (P * R).\nProof.\nintros. intros w [w1 [w2 [? [? ?]]]].\ndestruct H1.\nsplit; exists w1; exists w2; split; auto.\nQed.\n\nLemma modus_wand {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall P Q,  P * (P -* Q) |-- Q.\nProof.\nintros.\nintros w  [?w [?w [? [? ?]]]].\neapply H1; eauto.\nQed.\n\nLemma extend_sepcon {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall {Q R: pred A}, boxy extendM Q ->  Q * R |-- Q.\nProof.\nintros.\nintros w [w1 [w2 [? [? _]]]].\nrewrite <- H in H1. eapply H1; eauto.\nsimpl; eauto.\nexists w2; auto.\nQed.\n\nDefinition precise {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} (P: pred A) : Prop :=\n     forall w w1 w2, P w1 -> P w2 -> join_sub w1 w -> join_sub w2 w -> w1=w2.\n\nDefinition precise2  {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} (P: pred A) : Prop :=\n     forall Q R, (P * (Q && R) = (P * Q) && (P * R))%pred.\n\nLemma precise_eq {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}{AG: ageable A}{XA: Age_alg A}: precise =\n                 fun P : pred A => forall Q R, (P * (Q && R) = (P * Q) && (P * R))%pred.\nProof.\nextensionality P.\nunfold precise.\napply prop_ext; split; intros.\napply pred_ext; unfold derives; intros; rename a into w.\ndestruct H0 as [phi1 [phi2 [? [? [? ?]]]]].\nsplit; exists phi1; exists phi2; auto.\ndestruct H0 as [[phi1a [phi2a [? [? ?]]]] [phi1b [phi2b [? [? ?]]]]].\nspecialize (H w _ _ H1 H4).\nspec H.\neconstructor; eauto.\nspec H.\neconstructor; eauto.\nsubst phi1b.\ngeneralize (join_canc (join_comm H0) (join_comm H3)).\nintro; subst phi2b.\nexists phi1a; exists phi2a; split; auto.\nsplit; auto.\nsplit; auto.\nrename w1 into w1a.\nrename w2 into w1b.\ndestruct H2 as [w2a ?].\ndestruct H3 as [w2b ?].\nassert (((P * exactly w2a) && (P * exactly w2b)) w)%pred.\nsplit; do 2 econstructor; repeat split;\ntry solve [simpl; apply necR_refl].\neassumption. auto. eassumption. auto.\nrewrite <- H in H4.\ndestruct H4 as [w1 [w2 [? [? [? ?]]]]].\nsimpl in H6,H7.\nrewrite (necR_comparable _ _ H6) in H2.\nrewrite (necR_comparable _ _ H7) in H3.\neapply join_canc; eauto.\napply comparable_trans with w.\napply join_comparable with w1b; auto.\napply comparable_sym; apply join_comparable with w1; auto.\napply comparable_trans with w.\napply join_comparable with w1a; auto.\napply comparable_sym; apply join_comparable with w1; auto.\nQed.\n\nLemma derives_precise {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall P Q, (P |-- Q) -> precise Q -> precise P.\nProof.\nintros; intro; intros; eauto.\nQed.\n\nLemma precise_emp {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}: precise emp.\nProof.\nrepeat intro.\neapply join_sub_same_identity with (a := w1)(c := w); auto.\napply identity_unit'; auto.\neapply join_sub_unit_for; eauto.\napply identity_unit'; auto.\nQed.\n\nDefinition superprecise {A}  {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} (P: pred A) :=\n   forall w1 w2, P w1 -> P w2 -> comparable w1 w2 -> w1=w2.\n\nLemma superprecise_exactly {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}: forall w, superprecise (exactly w).\nProof.\nunfold superprecise; intros.\nhnf in H,H0.\neapply necR_linear'; eauto.\napply comparable_fashionR; auto.\nQed.\nHint Resolve @superprecise_exactly.\n\nLemma superprecise_precise {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}: forall (P: pred A) , superprecise P -> precise P.\nProof.\n  pose proof I.\n  unfold precise. unfold superprecise.\n  intros.\n  assert (comparable w1 w2). assert (comparable w1 w) by apply (join_sub_comparable H3).\n  assert (comparable w w2).\n    apply comparable_sym; destruct H4; eapply join_comparable; eauto.\n    apply (comparable_trans H5 H6).\n  apply (H0 _ _ H1 H2 H5).\nQed.\n\n(* EXistential Magic Wand *)\n\nProgram Definition ewand {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A} (P Q: pred A) : pred A :=\n  fun w => exists w1, exists w2, join w1 w w2 /\\ P w1 /\\ Q w2.\nNext Obligation.\ndestruct H0 as [w1 [w2 [? [? ?]]]].\napply join_comm in H0; eapply age1_join in H0; eauto.\ndestruct H0 as [w1' [w3' [? [? ?]]]].\nexists w1'; exists w3'; split; auto.\nsplit;   eapply pred_nec_hereditary; try eassumption.\nconstructor 1; auto.\nconstructor 1; auto.\nQed.\n\nLemma later_ewand {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A} : forall P Q,\n  (|>(ewand P Q) = ewand (|>P) (|>Q))%pred.\nProof.\nintros.\napply pred_ext.\nintros w ?.\ncase_eq (age1 w); intros.\ndestruct (H a (t_step _ _ _ _ H0)) as [a1 [a2 [? [? ?]]]].\ndestruct (unage_join _ (join_comm H1) H0) as [w1 [w2 [? [? ?]]]].\nexists w1; exists w2; split; [|split]; auto.\nhnf; intros.\napply pred_nec_hereditary with a1; auto.\neapply age_later_nec; eauto.\nhnf; intros.\napply pred_nec_hereditary with a2; auto.\neapply age_later_nec; eauto.\nexists (core w), w.\nsplit; [|split].\napply core_unit.\nhnf; intros.\nassert (age1 (core w) = None).\napply age1_None_joins with w; auto.\nexists w; apply join_comm; apply core_unit.\nunfold laterM in H1. simpl in H1.\nunfold laterR in H1.\napply clos_trans_t1n in H1. inv H1; rewrite H3 in H2; inv H2.\nintros w' ?.\nhnf in H1. apply clos_trans_t1n in H1.\ninv H1; rewrite H2 in H0; inv H0.\n\nintros w [w1 [w2 [? [? ?]]]].\nintros w' ?.\nhnf in H2. apply clos_trans_t1n in H2.\nrevert w1 w2 H H0 H1; induction H2; intros.\ndestruct (age1_join _ (join_comm H0) H) as [w1' [w2' [? [? ?]]]].\nexists w1'; exists w2'; split; auto.\nsplit.\neapply H1. hnf; apply clos_t1n_trans. constructor 1; auto.\neapply H2. hnf; apply clos_t1n_trans. constructor 1; auto.\ndestruct (age1_join _ (join_comm H0) H) as [w1' [w2' [? [? ?]]]].\napply (IHclos_trans_1n _ _ (join_comm H4)); auto; eapply pred_hereditary; eauto.\nQed.\n\n(* Notation \"P '-o' Q\" := (ewand P Q) (at level 60, right associativity). *)\n\nLemma emp_ewand {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{AG: ageable A}{XA: Age_alg A}:\n      forall P, ewand emp P = P.\nProof.\nintros.\napply pred_ext; intros w ?.\ndestruct H as [w1 [w2 [? [? ?]]]].\nreplace w with w2; auto.\neapply join_eq; eauto.\neapply identity_unit; eauto.\ndestruct (join_ex_identities w) as [e [He [? Hj]]].\nexists e; exists w.\nsplit; auto.\nspecialize (He _ _ Hj); subst; auto.\nQed.\n\n\nLemma pry_apart {A}  {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}{DA: Disj_alg A}{CrA: Cross_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall G P Q, superprecise G -> P = ewand G (G * P) ->\n                       (P * Q) && (G * TT) |-- (P * G * (ewand G Q)).\nProof.\n pose proof I. intros.\nintros w [? ?].\ndestruct H2 as [w2 [w3 [? [? Hq]]]].\ndestruct H3 as [w4 [w5 [? [? _]]]].\nrewrite H1 in H4.\ndestruct H4 as [wa [wb [? [? ?]]]].\nassert (wa = w4). apply H0; auto.\napply comparable_trans with w2. apply join_comparable2 with wb; auto.\napply comparable_trans with w. apply join_comparable with w3; auto.\napply comparable_sym. apply join_comparable with w5; auto.\nsubst wa; clear H6.\ndestruct H7 as [w4' [w2' [? [? ?]]]].\nassert (w4' = w4). apply H0; auto.\napply comparable_trans with wb. eapply join_comparable; eauto.\napply comparable_sym.  eapply join_comparable; eauto.\nsubst w4'; clear H7.\nassert (w2' = w2). eapply join_canc; try apply join_comm; eauto.\nsubst w2'; clear H6.\ndestruct (CrA _ _ _ _ _ H2 H3) as [[[[w24 w25] w34] w35] [? [? [? ?]]]].\nassert (identity w24).\n  destruct (join_assoc (join_comm H9) H4) as [f [? ?]].\n  destruct (join_assoc (join_comm H6) (join_comm H11)) as [g [? ?]].\n  eapply join_self; eauto.\nassert (w34=w4). eapply join_eq; [eapply identity_unit; eauto | auto ].\nsubst w34.\nassert (w25 = w2). eapply join_eq; [eapply identity_unit; eauto | auto ].\nsubst w25.\nclear H11 H9 H6 w24.\ndestruct (join_assoc (join_comm H10) (join_comm H3)) as [h [? ?]].\ngeneralize (join_eq H6 (join_comm H4)); clear H6; intro; subst h.\ndestruct (join_assoc (join_comm H4) (join_comm H9)) as [h [? ?]].\ngeneralize (join_eq H6 H7); clear H6; intro; subst h.\nclear H11.\nexists wb; exists w35.\nsplit. apply join_comm; auto.\nsplit; auto.\nexists w2; exists w4; split; auto.\nunfold ewand.\nexists w4; exists w3; split; auto.\nQed.\n\nDefinition wk_split {A} {JA: Join A} :=\n      forall a b c d e : A, join a b c -> join d e c -> joins a d -> join_sub d b.\n\nLemma crosssplit_wkSplit {A}  {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{DA: Disj_alg A}{CrA: Cross_alg A}{AG: ageable A}{XA: Age_alg A}:\n    wk_split.\nProof.\nunfold wk_split; intros.\ndestruct (CrA _ _ _ _ _ H H0) as [[[[ad ae] bd] be] [myH1 [myH2 [myH3 myH4]]]].\ndestruct H1 as [x H_x].\nassert (exists X, join ad X be) as [X HX].\n2:{   exists X.\n               destruct (join_assoc (join_comm HX) (join_comm myH2)) as [y [myH5 myH6]].\n               assert (y=d) by apply (join_eq myH5 myH3).  subst y.\n               apply (join_comm myH6).\n}\ndestruct (join_assoc (join_comm myH1) H_x) as [y [myH5 myH6]].\ndestruct (join_assoc (join_comm myH3) (join_comm myH5)) as [? [Had ?]].\napply join_self in Had.\npose proof (Had _ _ myH1); subst.\ndestruct (join_assoc (join_comm myH1) myH4) as [? [Hbe ?]].\nspecialize (Had _ _ Hbe); subst; eauto.\nQed.\n\nLemma wk_pry_apart {A}  {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}{DA: Disj_alg A}{CrA: Cross_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall G P Q, wk_split -> superprecise G -> P = ewand G (G * P) ->\n                       (P * Q) && (G * TT) |-- (P * G * (ewand G Q)).\nProof.\nintros.\nintros w [? ?]. unfold ewand.\ndestruct H2 as [w2 [w3 [? [? Hq]]]].\ndestruct H3 as [w4 [w5 [? [? _]]]].\nrewrite H1 in H4.\ndestruct H4 as [wa [wb [? [? ?]]]].\nassert (wa = w4). apply H0; auto.\napply comparable_trans with w2. eapply join_comparable2; eauto.\napply comparable_trans with w. eapply join_comparable; eauto.\napply comparable_sym.  eapply join_comparable; eauto.\nsubst wa; clear H6.\ndestruct H7 as [w4' [w2' [? [? ?]]]].\nassert (w4' = w4). apply H0; auto.\napply comparable_trans with wb. eapply join_comparable; eauto.\napply comparable_sym.  eapply join_comparable; eauto.\nsubst w4'; clear H7.\nassert (w2' = w2). eapply join_canc; try apply join_comm; eauto.\nsubst w2'; clear H6.\nassert (exists y, join w2 y w5).\n    destruct (H _ _ _ _ _ H2 H3 (join_joins (join_comm H4))).\n    destruct (join_assoc H6 (join_comm H2)) as [y [myH1 myH2]].\n    assert (y=w5) by apply (join_canc  (join_comm myH2) (join_comm H3)). subst y.\n    exists x. apply (join_comm myH1).\nexists wb.\ndestruct H6 as [y w2_y_w5].\n               destruct (join_assoc w2_y_w5 (join_comm H3)) as [x [myH1 myH2]].\n               destruct (join_assoc  (join_comm myH1) (join_comm myH2)) as [z [myH3 myH4]].\n                                        assert (w5=z) by apply  (join_canc (join_comm H3) (join_comm myH4)). subst w5.\n                                        assert (w3=x) by apply (join_canc (join_comm H2) (join_comm myH2)).  subst w3.\n                                        destruct (join_assoc myH3 (join_comm myH4)) as [u [myH5 myH6]].\n                                        assert (wb=u) by apply (join_eq H4 (join_comm myH5)). subst wb.\n               exists y. split. apply (join_comm myH6).\n               split. exists w2. exists w4. split. apply (join_comm H4). split; assumption.\n               exists w4. exists x; split. apply (join_comm myH1). split; assumption.\nQed.\n\nLemma ewand_overlap {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}{DA: Disj_alg A}{CrA: Cross_alg A}{AG: ageable A}{XA: Age_alg A}:\n    forall (P Q: pred A),\n       superprecise Q ->\n       ewand TT (P * Q) * Q |-- ewand TT (P * Q).\nProof.\nintros P Q PrecQ.\nintros w [w1 [w2 [? [? ?]]]].\ndestruct H0 as [w5 [w6 [? [_ ?]]]].\ndestruct H2 as [w3 [w4 [? [? ?]]]].\ngeneralize (PrecQ  _ _ H4 H1); clear H4; intro.\nspec H4.\napply comparable_trans with w6.\napply join_comparable with w3; apply join_comm; auto.\napply comparable_trans with w1.\napply comparable_sym; apply join_comparable with w5; apply join_comm; auto.\neapply join_comparable2; eauto.\nsubst w4.\ndestruct (CrA _ _ _ _ _ H0 H2) as [[[[a b] c] d] [? [? [? ?]]]].\ndestruct (join_assoc H5 H) as [f [? ?]].\ndestruct (join_assoc H7 (join_comm H8)) as [g [? ?]].\ngeneralize (join_self' H10); intro.\nsubst g.\nassert (identity d).\neapply unit_identity; eauto.\nassert (b=w2).\neapply join_canc; eauto.\nsubst b.\nassert (f=w2).\neapply join_eq; eauto.\nsubst f.\nclear H11 H10 H7.\nassert (c=w1).\n specialize ( H12 c w1). apply H12. auto.\nsubst c.\nclear H9 H5.\ndestruct (join_assoc H6 H2) as [h [? ?]].\ngeneralize (join_eq H5 H); clear H5; intro; subst h.\nexists a; exists w6; split; auto.\nsplit; auto.\nexists w3; exists w2; split; auto.\nQed.\n\nLemma ewand_derives {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall P P' Q Q',  P |-- P' -> Q |-- Q' -> ewand P Q |-- ewand P' Q'.\nProof.\nintros.\nintros w ?.\ndestruct H1 as [?w [?w [? [? ?]]]].\nexists w0; exists w1; split; auto.\nQed.\n\nLemma ewand_sepcon {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}: forall P Q R,\n      (ewand (P * Q) R = ewand P (ewand Q R))%pred.\nProof.\nintros; apply pred_ext; intros w ?.\ndestruct H as [w1 [w2 [? [? ?]]]].\ndestruct H0 as [w3 [w4 [? [? ?]]]].\nexists w3.\ndestruct (join_assoc (join_comm H0) H) as [wf [? ?]].\nexists wf.\nsplit; [|split]; auto.\nexists w4. exists w2. split; auto.\ndestruct H as [w1 [w2 [? [? ?]]]].\ndestruct H1 as [w3 [w4 [? [? ?]]]].\ndestruct (join_assoc (join_comm H) (join_comm H1)) as [wf [? ?]].\nexists wf. exists w4. split; [|split]; auto.\nexists w1; exists w3; split; auto.\nQed.\n\nLemma ewand_sepcon_assoc {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CrA: Cross_alg A}{AG: ageable A}{XA: Age_alg A}:\n  Trip_alg A ->\n  forall P Q R: pred A,\n      (forall w1 w2 w3, join w1 w2 w3 -> P w3 -> P w1) ->\n      (forall w w', comparable w w' -> P w -> R w' -> joins w w') ->\n      (ewand TT P) && (ewand TT R) |-- emp ->\n     (ewand P (Q * R) = (ewand P Q * R))%pred.\nProof.\nintros TRIPLE P Q R ?H Hjoins ?H.\napply pred_ext; intros w ?.\ndestruct H1 as [w1 [w2 [? [? ?]]]].\ndestruct H3 as [w3 [w4 [? [? ?]]]].\ndestruct (CrA _ _ _ _ _ H1 H3) as [[[[? ?] ?] ?] [? [? [? ?]]]].\ngeneralize (H _ _ _ (join_comm H6) H2); intro.\nassert (emp a0).\napply H0.\nsplit.\n2:{ do 2 econstructor; (split; [|split]). 3: eauto. eauto. auto. }\nexists a; exists w1; split; [|split]; eauto.\napply join_unit2_e in H6; auto.\nsubst a.\napply join_unit1_e in H9; auto.\nsubst a2.\nexists a1; exists w4; split; [|split]; auto.\ndo 2 econstructor; eauto.\n(*****)\ndestruct H1 as [w1 [wR [? [? ?]]]].\ndestruct H2 as [wP [wQ [? [? ?]]]].\napply join_comm in H2.\nspecialize (Hjoins wP wR).\nspec Hjoins.\napply comparable_trans with w1; eapply join_comparable2; eauto.\ndestruct Hjoins as [w6 ?]; auto.\ndestruct (TRIPLE _ _ _ _ _ _ H1 (join_comm H6) H2) as [wQR ?].\nexists wP. exists wQR.\nsplit; [|split]; auto.\ndestruct (join_assoc H1 j) as [wf [? ?]].\ngeneralize (join_eq H6 (join_comm H7)); clear H6; intros; subst w6.\ndestruct (join_assoc H7 (join_comm H8)) as [wg [? ?]].\ngeneralize (join_eq H2 (join_comm H6)); clear H6; intros; subst wg.\ndo 2 econstructor; eauto.\nQed.\n\n\nLemma ewand_sepcon2 {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}{DA: Disj_alg A}{CrA: Cross_alg A}{AG: ageable A}{XA: Age_alg A}:\n      forall\n          R (SP: superprecise R)\n          P (H: P = ewand R (R * P))\n          Q,\n          ewand P (Q * R) |-- ewand P Q * R.\nProof.\nintros.\nintros w ?.\ndestruct H0 as [w1 [w34 [? [? [w3 [w4 [? [? ?]]]]]]]].\ngeneralize (crosssplit_wkSplit  _ _ _ _ _ H0 (join_comm H2)); unfold wk_split; intro.\nspec H5.\nrewrite H in H1.\ndestruct H1 as [wa [wb [? [? ?]]]].\ngeneralize (SP _ _ H6 H4); clear H4; intro.\nspec H4.\napply comparable_trans with w34. apply comparable_trans with w1.\neapply join_comparable2; eauto. eapply join_comparable; eauto.\napply comparable_sym; eapply join_comparable; eauto.\nsubst wa.\ndestruct H7 as [wx [wy [? [? ?]]]].\ngeneralize (SP _ _ H7 H6); clear H7; intro.\nspec H7.\napply comparable_trans with wb.  eapply join_comparable; eauto.\napply comparable_sym; eapply join_comparable; eauto.\nsubst wx.\ngeneralize (join_canc (join_comm H1) (join_comm H4)); clear H4; intro.\nsubst wy.\neconstructor; eauto.\ndestruct H5 as [w5 ?].\nexists w5; exists w4; split; [|split]; auto.\nexists w1; exists w3; split; [|split]; auto.\ndestruct (join_assoc H5 (join_comm H0)) as [wf [? ?]].\ngeneralize (join_canc (join_comm H7) H2); clear H7; intro.\nsubst wf.\nauto.\nQed.\n\nLemma sepcon_andp_prop2 {A} {JA: Join A}{PA: Perm_alg A}{AG: ageable A}{XA: Age_alg A}:\n  forall P Q R,  (P * (!!Q && R) = !!Q && (P * R))%pred.\nProof.\nintros.\napply pred_ext; intros w ?.\ndestruct H as [w1 [w2 [? [? [? ?]]]]].\nsplit. apply H1.\nexists w1; exists w2; split; [|split]; auto.\ndestruct H.\ndestruct H0 as [w1 [w2 [? [? ?]]]].\nexists w1; exists w2; repeat split; auto.\nQed.\n\nLemma sepcon_andp_prop1 {A}{JA: Join A}{PA: Perm_alg A}{agA: ageable A}{AgeA: Age_alg A}:\n   forall (P: Prop) (Q R: pred A) , ((!! P && Q) * R = !! P && (Q * R))%pred.\nProof.\n intros. rewrite (sepcon_comm). rewrite sepcon_andp_prop2. rewrite sepcon_comm; auto.\nQed.\n\nLemma distrib_orp_sepcon {A : Type}{JA : Join A}{PA : Perm_alg A}{agA : ageable A}\n    {AgeA : Age_alg A}:\n  forall (P Q R : pred A), ((P || Q) * R = P * R || Q * R)%pred.\nProof.\n intros. apply pred_ext.\n  intros w [w1 [w2 [? [[?|?] ?]]]]; [left|right]; exists w1; exists w2; repeat split; auto.\n intros ? [?|?];  destruct H as [w1 [w2 [? [? ?]]]]; exists w1; exists w2; repeat split; auto.\n  left; auto. right; auto.\nQed.\n\nLemma distrib_orp_sepcon2{A : Type}{JA : Join A}{PA : Perm_alg A}{agA : ageable A}\n    {AgeA : Age_alg A}:\n  forall (P Q R : pred A),\n     (R * (P || Q) = R * P || R * Q)%pred.\nProof.\nintros. rewrite !(sepcon_comm R). apply distrib_orp_sepcon.\nQed.\n\nLemma ewand_conflict {T}{agT:ageable T}{JT: Join T}{PT: Perm_alg T}{ST: Sep_alg T}{AT: Age_alg T}:\n       forall P Q R, sepcon P Q |-- FF -> andp P (ewand Q R) |-- FF.\nProof.\n intros. intros w [? [w1 [w2 [? [? ?]]]]].\n specialize (H w2). apply H. exists w; exists w1; repeat split; auto.\nQed.\n\nLemma ewand_TT_sepcon {T}{agT:ageable T}{JT: Join T}{PT: Perm_alg T}{ST: Sep_alg T}{AT: Age_alg T}:\n      forall P Q R,\n(P * Q && ewand R (!!True))%pred |-- (P && ewand R (!!True) * (Q && ewand R (!!True)))%pred.\nProof.\nintros.\nintros w [[w1 [w2 [? [? ?]]]] [w3 [w4 [? [? ?]]]]].\nexists w1; exists w2; repeat split; auto.\ndestruct (join_assoc (join_comm H) (join_comm H2)) as [f [? ?]].\nexists w3; exists f; repeat split; auto.\ndestruct (join_assoc H (join_comm H2)) as [g [? ?]].\nexists w3; exists g; repeat split; auto.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/msl/predicates_sl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21637931414650782}}
{"text": "Require Import Bool.\nRequire Import List.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import Compatibility.\nRequire Import SimThread.\n\nRequire Import ReorderStep.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\n\nInductive reorder_fence (or1 ow1:Ordering.t): forall (i2:Instr.t), Prop :=\n| reorder_fence_load\n    r2 l2 o2\n    (ORDR1: Ordering.le or1 Ordering.acqrel)\n    (ORDW1: Ordering.le ow1 Ordering.relaxed)\n    (ORD2: Ordering.le o2 Ordering.plain \\/ Ordering.le Ordering.acqrel o2):\n    reorder_fence or1 ow1 (Instr.load r2 l2 o2)\n| reorder_fence_store\n    l2 v2 o2\n    (ORDR1: Ordering.le or1 Ordering.acqrel)\n    (ORDW1: Ordering.le ow1 Ordering.relaxed):\n    reorder_fence or1 ow1 (Instr.store l2 v2 o2)\n| reorder_fence_update\n    r2 l2 rmw2 or2 ow2\n    (ORDR1: Ordering.le or1 Ordering.acqrel)\n    (ORDW1: Ordering.le ow1 Ordering.relaxed)\n    (ORDR2: Ordering.le or2 Ordering.plain \\/ Ordering.le Ordering.acqrel or2):\n    reorder_fence or1 ow1 (Instr.update r2 l2 rmw2 or2 ow2)\n.\n\nInductive sim_fence: forall (st_src:(Language.state lang)) (lc_src:Local.t) (sc1_src:TimeMap.t) (mem1_src:Memory.t)\n                       (st_tgt:(Language.state lang)) (lc_tgt:Local.t) (sc1_tgt:TimeMap.t) (mem1_tgt:Memory.t), Prop :=\n| sim_fence_intro\n    or1 ow1 i2 rs\n    lc1_src sc1_src mem1_src\n    lc1_tgt sc1_tgt mem1_tgt\n    lc2_src sc2_src\n    (REORDER: reorder_fence or1 ow1 i2)\n    (FENCE: Local.fence_step lc1_src sc1_src or1 ow1 lc2_src sc2_src)\n    (LOCAL: sim_local SimPromises.bot lc2_src lc1_tgt):\n    sim_fence\n      (State.mk rs [Stmt.instr i2; Stmt.instr (Instr.fence or1 ow1)]) lc1_src sc1_src mem1_src\n      (State.mk rs [Stmt.instr i2]) lc1_tgt sc1_tgt mem1_tgt\n.\n\nLemma sim_fence_step\n      st1_src lc1_src sc0_src mem0_src\n      st1_tgt lc1_tgt sc0_tgt mem0_tgt\n      (SIM: sim_fence st1_src lc1_src sc0_src mem0_src\n                      st1_tgt lc1_tgt sc0_tgt mem0_tgt):\n  forall sc1_src sc1_tgt\n    mem1_src mem1_tgt\n    (SC: TimeMap.le sc1_src sc1_tgt)\n    (MEMORY: sim_memory mem1_src mem1_tgt)\n    (SC_FUTURE_SRC: TimeMap.le sc0_src sc1_src)\n    (SC_FUTURE_TGT: TimeMap.le sc0_tgt sc1_tgt)\n    (MEM_FUTURE_SRC: Memory.future_weak mem0_src mem1_src)\n    (MEM_FUTURE_TGT: Memory.future_weak mem0_tgt mem1_tgt)\n    (WF_SRC: Local.wf lc1_src mem1_src)\n    (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n    (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n    (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n    (MEM_SRC: Memory.closed mem1_src)\n    (MEM_TGT: Memory.closed mem1_tgt),\n    _sim_thread_step lang lang ((sim_thread (sim_terminal eq)) \\8/ sim_fence)\n                     st1_src lc1_src sc1_src mem1_src\n                     st1_tgt lc1_tgt sc1_tgt mem1_tgt.\nProof.\n  inv SIM. ii. right.\n  exploit future_fence_step; try apply FENCE; eauto; i.\n  { inv REORDER; etrans; eauto. }\n  inv STEP_TGT; [inv STEP|inv STEP; inv LOCAL0];\n    try (inv STATE; inv INSTR; inv REORDER); ss.\n  - (* promise *)\n    exploit sim_local_promise; eauto.\n    { eapply Local.fence_step_future; eauto. }\n    i. des.\n    exploit reorder_fence_promise; try apply x0; try apply STEP_SRC; eauto.\n    { inv REORDER; ss. }\n    i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs 1. econs; eauto.\n    + eauto.\n    + right. econs; eauto.\n  - (* load *)\n    guardH ORD2.\n    exploit sim_local_read; try exact LOCAL0; try apply SC; eauto; try refl; viewtac.\n    { eapply Local.fence_step_future; eauto. }\n    i. des.\n    exploit reorder_fence_read; try apply x0; try apply STEP_SRC; eauto; try by viewtac. i. des.\n    esplits.\n    + ss.\n    + econs 2; [|econs 1]. econs.\n      * econs. econs 2. econs; [|econs 2]; eauto. econs. econs.\n      * eauto.\n    + econs 2. econs 2. econs; [|econs 5]; eauto. econs. econs.\n    + auto.\n    + etrans; eauto.\n    + auto.\n    + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n      etrans; eauto.\n  - (* update-load *)\n    guardH ORDR2.\n    exploit sim_local_read; try exact LOCAL0; try apply SC; eauto; try refl; viewtac.\n    { eapply Local.fence_step_future; eauto. }\n    i. des.\n    exploit reorder_fence_read; try apply x0; try apply STEP_SRC; eauto; try by viewtac. i. des.\n    esplits.\n    + ss.\n    + econs 2; [|econs 1]. econs.\n      * econs. econs 2. econs; [|econs 2]; eauto. econs. econs. eauto.\n      * eauto.\n    + econs 2. econs 2. econs; [|econs 5]; eauto. econs. econs.\n    + auto.\n    + etrans; eauto.\n    + auto.\n    + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n      etrans; eauto.\n  - (* store *)\n    hexploit sim_local_write_bot; try exact LOCAL1; try apply SC; eauto; try refl; viewtac.\n    { eapply Local.fence_step_future; eauto. }\n    i. des.\n    exploit reorder_fence_write; try apply x0; try apply STEP_SRC; eauto; try by viewtac. i. des.\n    esplits.\n    + ss.\n    + econs 2; [|econs 1]. econs.\n      * econs. econs 2. econs; [|econs 3]; eauto. econs. econs.\n      * eauto.\n    + econs 2. econs 2. econs; [|econs 5]; eauto. econs. econs.\n    + auto.\n    + etrans; eauto.\n    + etrans; eauto.\n    + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n      etrans; eauto.\n  - (* update *)\n    guardH ORDR2.\n    exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read; try exact LOCAL1; try apply SC; eauto; try refl; viewtac.\n    { eapply Local.fence_step_future; eauto. }\n    i. des.\n    exploit reorder_fence_read; try apply x0; try apply STEP_SRC; eauto; try by viewtac. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    exploit Local.fence_step_future; eauto. i. des.\n    generalize LOCAL3. i. rewrite LOCAL0 in LOCAL3.\n    generalize SC0. i. rewrite SC in SC1.\n    hexploit sim_local_write_bot; try exact LOCAL2; try apply SC1; eauto; try refl; viewtac. i. des.\n    exploit reorder_fence_write; try apply STEP2; try apply STEP_SRC0; eauto; try by viewtac. i. des.\n    esplits.\n    + ss.\n    + econs 2; [|econs 1]. econs.\n      * econs. econs 2. econs; [|econs 4]; eauto. econs. econs. eauto.\n      * eauto.\n    + econs 2. econs 2. econs; [|econs 5]; eauto. econs. econs.\n    + auto.\n    + etrans; eauto.\n    + etrans; eauto.\n    + left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\n      etrans; eauto.\nQed.\n\nLemma sim_fence_sim_thread:\n  sim_fence <8= (sim_thread (sim_terminal eq)).\nProof.\n  pcofix CIH. i. pfold. ii. ss. splits; ss; ii.\n  - right. inv TERMINAL_TGT. inv PR; ss.\n  - eapply SimPromises.cap; eauto.\n    inv PR. inv FENCE. apply LOCAL.\n  - right. esplits; eauto.\n    inv PR. inversion FENCE. subst lc2_src. inversion LOCAL. ss.\n    apply SimPromises.sem_bot_inv in PROMISES; auto. rewrite PROMISES. auto.\n  - exploit sim_fence_step; try apply PR; try apply SC; eauto. i. des; eauto.\n    + right. esplits; eauto.\n      left. eapply paco9_mon; eauto. ss.\n    + right. esplits; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising2-coq", "sha": "52dd46538036a7a69c132e89dd3e7698b5e2f830", "save_path": "github-repos/coq/snu-sf-promising2-coq", "path": "github-repos/coq/snu-sf-promising2-coq/promising2-coq-52dd46538036a7a69c132e89dd3e7698b5e2f830/src/opt/ReorderFence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.21636186528249268}}
{"text": "Require Import Ascii FunctionApp List Program.Basics String.\nImport ListNotations.\n\nSection ui.\n\n  Inductive uiInput :=\n  | uiConsoleIn : string -> uiInput\n  | uiDecrypted : string -> uiInput.\n\n  Inductive uiOutput :=\n  | uiConsoleOut : string -> uiOutput\n  | uiEncrypt : string -> uiOutput\n  | uiNoop : uiOutput.\n\n  Fixpoint split (sep : ascii) (s : string) : list string :=\n    match s with\n      | EmptyString => nil\n      | String c s' =>\n        if ascii_dec c sep then EmptyString :: split sep s'\n        else match split sep s' with\n               | nil => [String c EmptyString]\n               | w :: ws => String c w :: ws\n             end\n    end.\n\n  Definition newline := \"010\"%char.\n\n  Definition dump (pws : list (string * string)) : string :=\n    fold_right append \"\"%string\n               (map (fun p => (fst p ++ \" \" ++ snd p ++ String newline \"\")%string) pws).\n\n  Fixpoint load (s : string) : list (string * string) :=\n    flat_map (fun l => match split \" \" l with\n                         | account :: password :: nil => [(account, password)]\n                         | _ => nil\n                       end)\n             (split newline s).\n\n  Definition uiState := list (string * string).\n\n  Open Scope string_scope.\n\n  Definition ui (pws : uiState) (i : uiInput) : (uiOutput * uiState) :=\n    match i with\n      | uiConsoleIn s =>\n        match split \" \" s with\n          | comm :: ls =>\n            match string_dec comm \"get\", ls with\n              | left _, account :: nil =>\n                match\n                  find (fun p => if string_dec account (fst p)\n                                 then true else false) pws\n                with\n                  | None =>\n                    (uiConsoleOut \"account not found\", pws)\n                  | Some (_, password) =>\n                    (uiConsoleOut password, pws)\n                end\n              | _, _ =>\n                match string_dec comm \"set\", ls with\n                  | left _,  account :: password :: nil =>\n                    let pws' :=\n                        (account, password)\n                          :: filter (fun p => if string_dec account (fst p)\n                                              then false else true) pws\n                    in (uiEncrypt (dump pws'), pws')\n\n                  | _, _ =>\n                    (uiConsoleOut \"unrecognized command\", pws)\n                end\n            end\n          | _ => (uiConsoleOut \"unrecognized command\", pws)\n        end\n      | uiDecrypted s =>\n        (uiNoop, load s)\n    end.\n\n  Definition uiStateInit : uiState := nil.\n\nEnd ui.\n\n\nSection net.\n\n  Inductive netInput :=\n  | netReceived : string -> netInput\n  | netEncrypted : string -> netInput.\n\n  Inductive netOutput :=\n  | netDecrypt : string -> netOutput\n  | netSend : string -> netOutput.\n\n  Definition net (i : netInput) :=\n    match i with\n      | netReceived s => netDecrypt s\n      | netEncrypted s => netSend s\n    end.\n\nEnd net.\n\n\nSection pwMgr.\n\n  Context (world : Type).\n  Context (consoleOut : string -> action world).\n  Context (send : string -> action world).\n\n  Inductive pwMgrInput :=\n  | pwMgrConsoleIn : string -> pwMgrInput\n  | pwMgrReceived : string -> pwMgrInput.\n\n  Definition uiOutputDec (out : uiOutput) : {s | out = uiConsoleOut s} + {s | out = uiEncrypt s} + {out = uiNoop}.\n    destruct out.\n    - left; left; eexists; eauto.\n    - left; right; eexists; eauto.\n    - right; eauto.\n  Defined.\n\n  Definition netOutputDec (out : netOutput) : {s | out = netDecrypt s} + {s | out = netSend s}.\n    destruct out.\n    - left; eexists; eauto.\n    - right; eexists; eauto.\n  Defined.\n\n  Ltac unfold_all :=\n    repeat match goal with\n             | H := _ |- _ => unfold H in *; clear H\n           end.\n\n  Lemma ui_ConsoleIn_not_Noop st s : fst (ui st (uiConsoleIn s)) <> uiNoop.\n  Proof.\n    intros H.\n    unfold ui in *.\n    destruct (split \" \") as [ | comm ls].\n    { simpl in *; discriminate. }\n    { \n      destruct (string_dec comm \"get\").\n      {\n        destruct ls.\n        { destruct (string_dec comm \"set\"); simpl in *; discriminate. }\n        destruct ls.\n        { destruct (find (fun p => if string_dec s0 (fst p) then true else false) st); try destruct p; simpl in *; discriminate. }\n        destruct (string_dec comm \"set\").\n        { destruct ls; simpl in *; discriminate. }\n        simpl; discriminate.\n      }\n      {\n        destruct (string_dec comm \"set\").\n        {\n          destruct ls.\n          { simpl in *; discriminate. }\n          destruct ls.\n          { simpl in *; discriminate. }\n          { destruct ls; simpl in *; discriminate. }\n        }\n        { simpl in *; discriminate. }\n      }          \n    }\n  Qed.\n\n  CoFixpoint pwMgrLoop (ui_st : uiState) : process pwMgrInput world.\n  refine\n    (Step (fun i =>\n             match i with\n               | pwMgrConsoleIn s =>\n                 let r := ui ui_st (uiConsoleIn s) in \n                 let a := fst r in\n                 let ui_st' := snd r in\n                 match uiOutputDec a with\n                   | inleft (inl (exist s _)) => (consoleOut s, pwMgrLoop ui_st')\n                   | inleft (inr (exist s _)) =>\n                     (* TODO: crypto *)\n                     let a := net (netEncrypted s) in\n                     match netOutputDec a with\n                       | inr (exist s _) => (send s, pwMgrLoop ui_st')\n                       | _ => _\n                     end\n                   | _ => _\n                 end\n               | pwMgrReceived s =>\n                 let a := net (netReceived s) in\n                 match netOutputDec a with \n                   | inl (exist s _) =>\n                     (* TODO: crypto *)\n                     let (_, ui_st') := ui ui_st (uiDecrypted s) in (id, pwMgrLoop ui_st') \n                   | _ => _\n                 end\n             end)).\n  - unfold_all.\n    simpl in s3.\n    destruct s3; discriminate.\n  - unfold_all.\n    simpl.\n    contradict e; eapply ui_ConsoleIn_not_Noop.\n  - unfold_all.\n    simpl in s0.\n    destruct s0; discriminate.\n  Defined.\n\n  Definition pwMgr := pwMgrLoop uiStateInit.\n\nEnd pwMgr.\n\n\nRequire Import ExtrOcamlBasic ExtrOcamlString.\nExtraction \"ExamplePwMgr2\" pwMgr.\n", "meta": {"author": "JasonGross", "repo": "apps", "sha": "906b9ca6f3f53e3a37a9a487a9289959f5167ba2", "save_path": "github-repos/coq/JasonGross-apps", "path": "github-repos/coq/JasonGross-apps/apps-906b9ca6f3f53e3a37a9a487a9289959f5167ba2/ExamplePwMgr2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.21636186103696003}}
{"text": "Require Import ZArith String List Bool.\nRequire Import ExtLib.Structures.Monads.\nRequire Import ExtLib.Structures.Maps.\nRequire Import ExtLib.Data.Map.FMapAList.\nRequire Import ExtLib.Data.Strings.\nRequire Import ExtLib.ExtLib.\nRequire Import ExtLib.Programming.Show.\nRequire Import CoqCompile.Lambda.\nRequire Import CoqCompile.CpsK CoqCompile.CpsKExamples.\nRequire Import CoqCompile.LLVM.\nRequire Import CoqCompile.Parse.\nRequire Import CoqCompile.TraceMonad.\nRequire Import CoqCompile.Compile.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nModule CompileTest.\n  Definition identity : string := \"(define ident (lambda (x) ident))\"%string.\n\n  Definition e_ident : Lambda.exp :=\n    Eval compute in \n      match Parse.parse_topdecls identity with\n        | inl _ => Lambda.Var_e (Env.wrapVar \"\"%string)\n        | inr o => o\n      end.\n\n  Definition hello_world := \"\n(define __ (lambda (_) __))\n\n(define ret (lambdas (monad x)\n  (match monad\n     ((Build_Monad ret0 bind0) (@ ret0 __ x)))))\n\n(define bind (lambdas (monad x x0)\n  (match monad\n     ((Build_Monad ret0 bind0) (@ bind0 __ x __ x0)))))\n\n(define monoid_plus (lambda (m)\n  (match m\n     ((Build_Monoid monoid_plus0 monoid_unit0) monoid_plus0))))\n\n(define monoid_unit (lambda (m)\n  (match m\n     ((Build_Monoid monoid_plus0 monoid_unit0) monoid_unit0))))\n\n(define inject (lambda (injection) injection))\n\n(define chr_newline `(Ascii ,`(False) ,`(True) ,`(False) ,`(True) ,`(False)\n  ,`(False) ,`(False) ,`(False)))\n\n(define show_mon (lambda (showScheme)\n  (match showScheme\n     ((Build_ShowScheme show_mon0 show_inj0) show_mon0))))\n\n(define show_inj (lambda (showScheme)\n  (match showScheme\n     ((Build_ShowScheme show_mon0 show_inj0) show_inj0))))\n\n(define runShow (lambdas (m m0) (@ m0 __ (show_inj m) (show_mon m))))\n\n(define show (lambdas (show0 x x0 x1) (@ show0 x __ x0 x1)))\n\n(define empty (lambdas (x m) (monoid_unit m)))\n\n(define cat (lambdas (a b i m) (@ monoid_plus m (@ a __ i m) (@ b __ i m))))\n\n(define injection_ascii_showM (lambdas (v i x) (i v)))\n\n(define show_exact (lambdas (s x x0)\n  (match s\n     ((EmptyString) (@ empty x x0))\n     ((String a s~)\n       (@ cat (@ inject (lambdas (x1 _) (injection_ascii_showM x1)) a)\n         (lambda (_) (show_exact s~)) x x0)))))\n  \n(define _inject_char (lambdas (x x0 x1)\n  (@ inject (lambdas (x2 _) (injection_ascii_showM x2)) x __ x0 x1)))\n\n(define ascii_Show (lambdas (a x x0)\n  (@ cat (lambda (_)\n    (@ cat (lambda (_)\n      (_inject_char `(Ascii ,`(True) ,`(True) ,`(True) ,`(False) ,`(False)\n        ,`(True) ,`(False) ,`(False)))) (lambda (_) (_inject_char a))))\n    (lambda (_)\n    (_inject_char `(Ascii ,`(True) ,`(True) ,`(True) ,`(False) ,`(False)\n      ,`(True) ,`(False) ,`(False)))) x x0)))\n\n(define iO_bind io_bind)\n\n(define iO_ret io_ret)\n\n(define iO_printChar io_printChar)\n\n(define monad_IO `(Build_Monad ,(lambda (_) iO_ret) ,(lambdas (_ x _)\n  (iO_bind x))))\n\n(define showScheme_IO `(Build_ShowScheme ,`(Build_Monoid ,(lambdas (x y)\n  (@ bind monad_IO x (lambda (x0) y))) ,(@ ret monad_IO `(Tt)))\n  ,iO_printChar))\n\n(define main\n  (@ runShow showScheme_IO (lambda (_)\n    (@ cat (lambda (_)\n      (show_exact `(String ,`(Ascii ,`(False) ,`(False) ,`(False) ,`(True)\n        ,`(False) ,`(False) ,`(True) ,`(False)) ,`(String ,`(Ascii ,`(True)\n        ,`(False) ,`(False) ,`(False) ,`(False) ,`(True) ,`(False) ,`(False))\n        ,`(EmptyString))))) (lambda (_)\n      (@ show (lambdas (x _) (ascii_Show x)) chr_newline))))))\"%string.\n\n  Definition e_hello : Lambda.exp :=\n    Eval vm_compute in \n      match Parse.parse_topdecls hello_world with\n        | inl _ => Lambda.Var_e (Env.wrapVar \"\"%string)\n        | inr o => o\n      end.\n\n(*\n  Definition fact :=\n  \"(define plus (lambdas (n m)\n     (match n\n       ((O) m)\n       ((S p) `(S ,(@ plus p m))))))\n  \n   (define mult (lambdas (n m)\n     (match n\n       ((O) `(O))\n       ((S p) (@ plus m (@ mult p m))))))\n  \n   (define fact (lambda (n)\n     (match n\n       ((O) `(S ,`(O)))\n       ((S n~) (@ mult n (fact n~))))))\"%string.\n\n  Definition e_fact : Lambda.exp :=\n    Eval vm_compute in \n      match Parse.parse_topdecls fact with\n        | inl _ => Lambda.Var_e (Env.wrapVar \"\"%string)\n        | inr o => o\n      end.\n\n  Definition broke :=\n   \"(define __ (lambda (_) __))\n\n(define ret (lambdas (monad x)\n  (match monad\n     ((Build_Monad ret0 bind0) (@ ret0 __ x)))))\n\n(define bind (lambdas (monad x x0)\n  (match monad\n     ((Build_Monad ret0 bind0) (@ bind0 __ x __ x0)))))\n\n(define monoid_plus (lambda (m)\n  (match m\n     ((Build_Monoid monoid_plus0 monoid_unit0) monoid_plus0))))\n\n(define monoid_unit (lambda (m)\n  (match m\n     ((Build_Monoid monoid_plus0 monoid_unit0) monoid_unit0))))\n\n(define inject (lambda (injection) injection))\n\n(define chr_newline `(Ascii ,`(False) ,`(True) ,`(False) ,`(True) ,`(False)\n  ,`(False) ,`(False) ,`(False)))\n\n(define show_mon (lambda (showScheme)\n  (match showScheme\n     ((Build_ShowScheme show_mon0 show_inj0) show_mon0))))\n\n(define show_inj (lambda (showScheme)\n  (match showScheme\n     ((Build_ShowScheme show_mon0 show_inj0) show_inj0))))\n\n(define runShow (lambdas (m m0) (@ m0 __ (show_inj m) (show_mon m))))\n\n(define show (lambdas (show0 x x0 x1) (@ show0 x __ x0 x1)))\n\n(define empty (lambdas (x m) (monoid_unit m)))\n\n(define cat (lambdas (a b i m) (@ monoid_plus m (@ a __ i m) (@ b __ i m))))\n\n(define injection_ascii_showM (lambdas (v i x) (i v)))\n\n(define show_exact (lambdas (s x x0)\n  (match s\n     ((EmptyString) (@ empty x x0))\n     ((String a s~)\n       (@ cat (@ inject (lambdas (x1 _) (injection_ascii_showM x1)) a)\n         (lambda (_) (show_exact s~)) x x0)))))\n  \n(define _inject_char (lambdas (x x0 x1)\n  (@ inject (lambdas (x2 _) (injection_ascii_showM x2)) x __ x0 x1)))\n\n(define ascii_Show (lambdas (a x x0)\n  (@ cat (lambda (_)\n    (@ cat (lambda (_)\n      (_inject_char `(Ascii ,`(True) ,`(True) ,`(True) ,`(False) ,`(False)\n        ,`(True) ,`(False) ,`(False)))) (lambda (_) (_inject_char a))))\n    (lambda (_)\n    (_inject_char `(Ascii ,`(True) ,`(True) ,`(True) ,`(False) ,`(False)\n      ,`(True) ,`(False) ,`(False)))) x x0)))\n\n(define iO_bind io_bind)\n\n(define iO_ret io_ret)\n\n(define iO_printChar io_printChar)\n\n(define monad_IO `(Build_Monad ,(lambda (_) iO_ret) ,(lambdas (_ x _)\n  (iO_bind x))))\n\n(define showScheme_IO `(Build_ShowScheme ,`(Build_Monoid ,(lambdas (x y)\n  (@ bind monad_IO x (lambda (x0) y))) ,(@ ret monad_IO `(Tt)))\n  ,iO_printChar))\n\n(define main\n  (@ runShow showScheme_IO (lambda (_)\n    (@ cat (lambda (_)\n      (show_exact `(String ,`(Ascii ,`(False) ,`(False) ,`(False) ,`(True)\n        ,`(False) ,`(False) ,`(True) ,`(False)) ,`(String ,`(Ascii ,`(True)\n        ,`(False) ,`(True) ,`(False) ,`(False) ,`(True) ,`(True) ,`(False))\n        ,`(String ,`(Ascii ,`(False) ,`(False) ,`(True) ,`(True) ,`(False)\n        ,`(True) ,`(True) ,`(False)) ,`(String ,`(Ascii ,`(False) ,`(False)\n        ,`(True) ,`(True) ,`(False) ,`(True) ,`(True) ,`(False)) ,`(String\n        ,`(Ascii ,`(True) ,`(True) ,`(True) ,`(True) ,`(False) ,`(True)\n        ,`(True) ,`(False)) ,`(String ,`(Ascii ,`(False) ,`(False) ,`(False)\n        ,`(False) ,`(False) ,`(True) ,`(False) ,`(False)) ,`(String ,`(Ascii\n        ,`(True) ,`(True) ,`(True) ,`(False) ,`(True) ,`(True) ,`(True)\n        ,`(False)) ,`(String ,`(Ascii ,`(True) ,`(True) ,`(True) ,`(True)\n        ,`(False) ,`(True) ,`(True) ,`(False)) ,`(String ,`(Ascii ,`(False)\n        ,`(True) ,`(False) ,`(False) ,`(True) ,`(True) ,`(True) ,`(False))\n        ,`(String ,`(Ascii ,`(False) ,`(False) ,`(True) ,`(True) ,`(False)\n        ,`(True) ,`(True) ,`(False)) ,`(String ,`(Ascii ,`(False) ,`(False)\n        ,`(True) ,`(False) ,`(False) ,`(True) ,`(True) ,`(False)) ,`(String\n        ,`(Ascii ,`(True) ,`(False) ,`(False) ,`(False) ,`(False) ,`(True)\n        ,`(False) ,`(False)) ,`(EmptyString))))))))))))))) (lambda (_)\n      (@ show (lambdas (x _) (ascii_Show x)) chr_newline))))))\"%string.\n\n  Definition e_broke : Lambda.exp :=\n    Eval vm_compute in \n      match Parse.parse_topdecls broke with\n        | inl _ => Lambda.Var_e (Env.wrapVar \"\"%string)\n        | inr o => o\n      end.\n*)\n\n  Definition c_hello : CPSK.exp :=\n    Eval vm_compute in \n      CpsKConvert.CPS_io e_hello.\n\n  Require Import ExtLib.Data.Monads.EitherMonad.\n\n  Definition cc_hello : string + (list CPSK.decl * CPSK.exp) :=\n    Eval vm_compute in\n      CloConvK.ClosureConvert.cloconv_exp c_hello.\n\n  Definition low_hello : string + Low.program :=\n    Eval vm_compute in\n      match cc_hello as cc_hello return match cc_hello with\n                                          | inl _ => unit\n                                          | inr _ => string + Low.program\n                                        end\n        with\n        | inl _ => tt\n        | inr (ds, main) =>\n          CpsK2Low.cpsk2low (sum string) ds main\n      end.\n(* Stack overflow\n  Eval vm_compute in to_string low_hello.\n*)\n\n(*\n  Eval vm_compute in\n    Compile.lamToCPSIO e_hello.\n\n  Eval vm_compute in\n    Compile.lamToClosIO e_hello.\n\n  Eval compute in\n    Compile.lamToLowIO e_hello.\n*)\n(*\n  (** TODO: This is stack overflowing **)\n  Eval vm_compute in\n    match Compile.runM (Compile.topCompile 8 Compile.Opt.O0 false e_fact) with\n      | (inl err, t) => (err, t)\n      | (inr mod', t) => (to_string mod', t)\n    end.\n*)\nEnd CompileTest.\n", "meta": {"author": "coq-ext-lib", "repo": "coq-compile", "sha": "8edfe71f4f91d5abf479bee50a3f1529b99acd4f", "save_path": "github-repos/coq/coq-ext-lib-coq-compile", "path": "github-repos/coq/coq-ext-lib-coq-compile/coq-compile-8edfe71f4f91d5abf479bee50a3f1529b99acd4f/src/coq/CompileTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2162026371988897}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n  Copyright 2018 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Export PBFTprops2.\nRequire Export PBFTwell_formed_log.\n\n\nSection PBFTcommit_in_log_preserves.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { pbft_context : PBFTcontext      }.\n  Context { pbft_auth    : PBFTauth         }.\n  Context { pbft_keys    : PBFTinitial_keys }.\n  Context { pbft_hash    : PBFThash         }.\n\n  Lemma check_send_replies_preserves_commit_in_log :\n    forall com slf view keys entryop state sn msgs state',\n      check_send_replies slf view keys entryop state sn = (msgs, state')\n      -> commit_in_log com (log state') = true\n      -> commit_in_log com (log state) = true.\n  Proof.\n    pbft_brute_force.\n  Qed.\n  Hint Resolve check_send_replies_preserves_commit_in_log: pbft.\n\n  Lemma commit_in_log_add_new_pre_prepare2log_log_entry_commits :\n    forall com pp d entry L,\n      commit_in_log com (add_new_pre_prepare2log pp d L) = commit_in_log com L\n      -> similar_entry_and_pre_prepare entry pp d = true\n      -> log_entry_commits (change_pre_prepare_info_of_entry pp entry)\n         = log_entry_commits entry.\n  Proof.\n    pbft_brute_force.\n  Qed.\n  (*Hint Rewrite commit_in_log_add_new_pre_prepare2log_log_entry_commits : pbft.*)\n\n  (* MOVE *)\n(*  DO WE NEED THESE??? We have stronger ones below.\n  Lemma is_commit_for_entry_true_implies :\n    forall entry c,\n      is_commit_for_entry entry c = true\n      -> log_entry_request_data entry = commit2request_data c.\n  Proof.\n    introv h.\n    unfold is_commit_for_entry, eq_request_data in h.\n    dest_cases w.\n  Qed.\n\n  Lemma is_commit_for_entry_false_implies :\n    forall entry c,\n      is_commit_for_entry entry c = false\n      -> log_entry_request_data entry <> commit2request_data c.\n  Proof.\n    introv h.\n    unfold is_commit_for_entry, eq_request_data in h.\n    dest_cases w.\n  Qed.\n*)\n\n  Lemma is_commit_for_entry_true_iff :\n    forall entry c,\n      is_commit_for_entry entry c = true\n      <-> log_entry_request_data entry = commit2request_data c.\n  Proof.\n    introv.\n    unfold is_commit_for_entry, eq_request_data;\n      destruct entry; simpl in *; pbft_dest_all x; split; tcsp.\n  Qed.\n  Hint Rewrite is_commit_for_entry_true_iff : pbft.\n\n  Lemma is_commit_for_entry_false_iff :\n    forall entry c,\n      is_commit_for_entry entry c = false\n      <-> log_entry_request_data entry <> commit2request_data c.\n  Proof.\n    introv.\n    unfold is_commit_for_entry, eq_request_data;\n      destruct entry; simpl in *; pbft_dest_all x; split; tcsp.\n  Qed.\n  Hint Rewrite is_commit_for_entry_false_iff : pbft.\n\n  Lemma add_new_pre_prepare2log_preserves_commit_in_log :\n    forall com pp s L,\n      commit_in_log com (add_new_pre_prepare2log pp s L) =\n      commit_in_log com L.\n  Proof.\n    induction L; simpl in *; smash_pbft.\n\n    {\n      pose proof (commit_in_log_add_new_pre_prepare2log_log_entry_commits com pp s a L) as xx.\n      apply xx in IHL; [| auto]. clear xx.\n      rewrite IHL in *. auto.\n    }\n\n(*    {\n      allrw is_commit_for_entry_true_iff.\n      allrw is_commit_for_entry_false_iff.\n\n      allrw similar_entry_and_pre_prepare_true_iff.\n\n      unfold change_pre_prepare_info_of_entry in *.\n      destruct a; simpl in *.\n      tcsp.\n    }\n\n    {\n      allrw is_commit_for_entry_true_iff.\n      allrw is_commit_for_entry_false_iff.\n\n      allrw similar_entry_and_pre_prepare_true_iff.\n\n      unfold change_pre_prepare_info_of_entry in *.\n      destruct a; simpl in *.\n      tcsp.\n    }*)\n  Qed.\n  Hint Rewrite  add_new_pre_prepare2log_preserves_commit_in_log : pbft.\n\n  Lemma decomp_commit :\n    forall com,\n      request_data_and_rep_toks2commit\n        (commit2request_data com)\n        (commit2rep_toks com)\n      = com.\n  Proof.\n    destruct com; simpl.\n    destruct b; simpl; auto.\n  Qed.\n  Hint Rewrite decomp_commit : pbft.\n\n  (* MOVE *)\n  Lemma rt_rep_commit2rep_toks_as_commit2sender :\n    forall com,\n      rt_rep (commit2rep_toks com)\n      = commit2sender com.\n  Proof.\n    introv; destruct com, b; simpl; auto.\n  Qed.\n  Hint Rewrite rt_rep_commit2rep_toks_as_commit2sender: pbft.\n\n  Lemma split_commit :\n    forall com,\n      com = request_data_and_rep_toks2commit (commit2request_data com) (commit2rep_toks com).\n  Proof.\n    introv; destruct com, b; simpl; tcsp.\n  Qed.\n\n  Lemma add_new_pre_prepare_and_prepare2log_preserves_commit_in_log :\n    forall L K pp d Fp Fc giop slf com,\n      slf = rt_rep (Fc tt)\n      -> add_new_pre_prepare_and_prepare2log slf L pp d Fp Fc = (giop, K)\n      -> commit_in_log com K = true\n      -> commit_in_log com L = true\n         \\/\n         (\n           com = request_data_and_rep_toks2commit (pre_prepare2request_data pp d) (Fc tt)\n           /\\\n           commit_in_log com L = false\n           /\\\n           prepared_log (pre_prepare2request_data pp d) K = true\n         ).\n  Proof.\n    induction L; introv irt h q; repeat (progress (simpl in *; smash_pbft));\n      try (complete (unfold is_request_data_for_entry, eq_request_data in *; smash_pbft;\n                     allrw similar_entry_and_pre_prepare_true_iff;\n                     allrw similar_entry_and_pre_prepare_false_iff;\n                     try (rename_hyp_with fill_out_pp_info_with_prepare fill);\n                     try (apply fill_out_pp_info_with_prepare_preserves_request_data in fill);\n                     congruence)).\n\n    allrw similar_entry_and_pre_prepare_true_iff.\n    unfold fill_out_pp_info_with_prepare in *.\n    destruct a; simpl in *;[].\n    destruct log_entry_pre_prepare_info; ginv; smash_pbft.\n    unfold add_commit_if_prepared in *; smash_pbft.\n\n    repndors; tcsp;[].\n\n    match goal with\n    | [ |- context[?x = true] ] => remember x as b; destruct b; tcsp; clear Heqb\n    end.\n    right.\n\n    unfold is_request_data_for_entry in *; simpl in *.\n    unfold same_rep_tok in *; smash_pbft.\n\n    rewrite (split_commit com).\n    allrw.\n    dands; tcsp.\n  Qed.\n  (*Hint Rewrite add_new_pre_prepare_and_prepare2log_preserves_commit_in_log : pbft.*)\n\n  Lemma add_new_prepare2log_preserves_commit_in_log :\n    forall i com new_prep L K gi Fc,\n      add_new_prepare2log i L new_prep Fc = (gi, K)\n      -> commit_in_log com K = true\n      -> commit_in_log com L = true\n         \\/\n         (\n           com = request_data_and_rep_toks2commit (prepare2request_data new_prep) (Fc tt)\n           /\\\n           commit_in_log com L = false\n           /\\\n           prepared_log (prepare2request_data new_prep) K = true\n         ).\n  Proof.\n    induction L; introv h q; simpl in *; smash_pbft; tcsp;\n      try (simpl in *; smash_pbft);\n      try (allrw is_commit_for_entry_false_iff; allrw is_commit_for_entry_true_iff;\n           match goal with\n           | [ H : add_prepare2entry _ _ _ _ = _, H' : _ <> _ |- _ ] =>\n             apply add_prepare2entry_some_implies_log_entry_request_data in H;\n             destruct H'; allrw <-; auto\n           end).\n\n   {\n     hide_hyp IHL.\n\n     allrw is_prepare_for_entry_true_iff.\n     unfold is_request_data_for_entry in *.\n     unfold eq_request_data in *. smash_pbft.\n\n     unfold add_prepare2entry in *.\n     destruct a;[]; simpl in *; ginv; simpl in *; smash_pbft; tcsp.\n     unfold add_commit_if_prepared in *.\n     smash_pbft.\n\n     allrw same_rep_tok_true_iff.\n\n     repndors; tcsp;[].\n\n     remember (existsb (same_rep_tok (commit2rep_toks com)) log_entry_commits) as b.\n     symmetry in Heqb; destruct b; tcsp.\n     pose proof (decomp_commit com) as q1. rewrite <- q1. clear q1.\n     allrw; dands; auto.\n   }\n\n   {\n     unfold is_request_data_for_entry in *.\n     unfold eq_request_data in *. smash_pbft.\n     allrw is_prepare_for_entry_true_iff.\n\n     match goal with\n       [H1 :  _ = commit2request_data com , H2 : _ = commit2request_data com |-_ ] =>\n       rewrite <- H2 in H1\n     end.\n     match goal with\n       [H1 : log_entry_request_data a = prepare2request_data new_prep , H2 : log_entry_request_data (gi_entry x) = _ |-_ ] =>\n       rewrite H1 in H2\n     end.\n    tcsp.\n\n   }\n\n   {\n     allrw is_prepare_for_entry_false_iff.\n     unfold is_request_data_for_entry in *.\n     unfold eq_request_data in *; smash_pbft.\n   }\n  Qed.\n  (*Hint Rewrite add_new_prepare2log_preserves_commit_in_log : pbft.*)\n\n\n  Lemma add_commit2entry_some_implies_log_entry_commits_gi_entry_or :\n    forall  entry com entry' ,\n      add_commit2entry entry com = Some entry'\n      -> if in_list_rep_toks (commit2sender com) (log_entry_commits entry)\n         then log_entry_commits entry' = log_entry_commits entry\n         else log_entry_commits entry' = commit2rep_toks com :: log_entry_commits entry.\n  Proof.\n    introv h.\n    unfold add_commit2entry in h.\n    destruct entry; simpl in *.\n    smash_pbft.\n  Qed.\n  Hint Resolve add_commit2entry_some_implies_log_entry_commits_gi_entry_or: pbft.\n\n  Lemma commit2sender_eq_if_request_data_and_rep_toks_equal :\n    forall com new_com,\n      commit2request_data new_com = commit2request_data com\n      -> commit2rep_toks com = commit2rep_toks new_com\n      -> commit2sender new_com = commit2sender com.\n  Proof.\n    introv H1 H2.\n    pose proof (decomp_commit com) as q1; rewrite <- q1; clear q1.\n    pose proof (decomp_commit new_com) as q2; rewrite <- q2; clear q2.\n    allrw. auto.\n  Qed.\n  Hint Resolve commit2sender_eq_if_request_data_and_rep_toks_equal : pbft.\n\n  Lemma add_new_commit2log_preserves_commit_in_log :\n    forall com new_com L gi K,\n      add_new_commit2log L new_com = (gi, K)\n      -> commit_in_log com K = true\n      -> commit_in_log com L = true\n         \\/\n         (\n           new_com = com\n           /\\\n           commit_in_log com L = false\n(*           /\\\n           prepared_log (commit2request_data new_com) K = true*)\n         ).\n  Proof.\n    induction L; introv IH1 IH2; repeat (simpl in *; ginv; smash_pbft; tcsp).\n\n    {\n      repndors;[|ginv].\n      pose proof (decomp_commit com) as q1; rewrite <- q1; clear q1.\n      pose proof (decomp_commit new_com) as q2; rewrite <- q2; clear q2.\n      allrw same_rep_tok_true_iff.\n      allrw; simpl; tcsp.\n    }\n\n    {\n      match goal with\n      | [ H : add_commit2entry _ _ = _ |- _ ] =>\n        apply add_commit2entry_some_implies_log_entry_commits_gi_entry_or in H\n      end.\n      smash_pbft; GC; ginv;[].\n\n      match goal with\n      | [ H1 : ?x = _, H2 : existsb _ ?x = _ |- _ ] =>\n        rewrite H1 in H2; simpl in H2; pbft_simplifier; repndors; auto;[]\n      end.\n\n      match goal with\n      | [ H1 : log_entry_request_data ?x = _, H2 : log_entry_request_data _ = _ |- _ ] =>\n        rewrite H1 in H2\n      end.\n\n      allrw same_rep_tok_true_iff.\n\n      right; dands; tcsp;[|].\n\n      {\n        pose proof (decomp_commit com) as q1; rewrite <- q1; clear q1.\n        pose proof (decomp_commit new_com) as q2; rewrite <- q2; clear q2.\n        allrw; simpl; autorewrite with pbft; tcsp.\n      }\n\n      {\n        apply in_list_rep_toks_false_implies_existsb_same_rep_toks_false.\n        autorewrite with pbft.\n        pose proof (commit2sender_eq_if_request_data_and_rep_toks_equal com new_com) as xx.\n        autodimp xx hyp.\n        autodimp xx hyp.\n        rewrite <- xx. auto.\n      }\n    }\n\n    {\n      apply gi_entry_of_add_commit2entry_some in Heqx1.\n      allrw is_commit_for_entry_true_iff.\n      allrw is_commit_for_entry_false_iff.\n      rewrite Heqx1 in Heqx2. tcsp.\n    }\n\n    {\n      allrw is_commit_for_entry_true_iff.\n      allrw is_commit_for_entry_false_iff.\n\n      destruct x;[]; simpl in *.\n      unfold add_commit2entry in *.\n      destruct a;[]; simpl in *.\n      smash_pbft.\n    }\n  Qed.\n  (*Hint Rewrite add_new_commit2log_preserves_commit_in_log : pbft.*)\n\n  Lemma entry_of_commit_in_log :\n    forall com L,\n      commit_in_log com L = true\n      -> exists entry,\n        In entry L\n        /\\ log_entry_request_data entry = commit2request_data com.\n  Proof.\n    induction L; introv h; simpl in *; tcsp.\n    pbft_dest_all x.\n\n    - exists a; dands; tcsp.\n      allrw is_commit_for_entry_true_iff; auto.\n\n    - apply IHL in h; exrepnd; exists entry; auto.\n  Qed.\n  (*Hint Rewrite entry_of_commit_in_log : pbft.*)\n\n  Lemma clear_log_checkpoint_preserves_commit_in_log2 :\n    forall com L sn,\n      well_formed_log L\n      -> commit_in_log com (clear_log_checkpoint L sn) = true\n      -> commit_in_log com L = true /\\ sn < commit2seq com.\n  Proof.\n    induction L; simpl in *; introv wf h; tcsp; smash_pbft.\n\n    - inversion wf as [|? ? imp wf1 wf2]; subst; clear wf.\n      apply IHL in h; repnd; dands; auto.\n\n      match goal with\n      | [ H : commit_in_log _ _ = _ |- _ ] => apply entry_of_commit_in_log in H\n      end.\n      exrepnd.\n      discover.\n      unfold entries_have_different_request_data in *; congruence.\n\n    - inversion wf as [|? ? imp wf1 wf2]; subst; clear wf.\n      apply IHL in h; auto.\n\n    - inversion wf as [|? ? imp wf1 wf2]; subst; clear wf.\n      dands; auto.\n      destruct com, b, a; simpl in *; subst; simpl in *; auto.\n\n    - inversion wf as [|? ? imp wf1 wf2]; subst; clear wf.\n      apply IHL in h; auto.\n  Qed.\n\n  Lemma clear_log_checkpoint_preserves_commit_in_log :\n    forall com L sn,\n      well_formed_log L\n      -> commit_in_log com (clear_log_checkpoint L sn) = true\n      -> commit_in_log com L = true.\n  Proof.\n    introv wf c.\n    apply clear_log_checkpoint_preserves_commit_in_log2 in c; tcsp.\n  Qed.\n  Hint Resolve clear_log_checkpoint_preserves_commit_in_log : pbft.\n\n  Lemma check_stable_preserves_commit_in_log :\n    forall slf state entryop state' com,\n      well_formed_log (log state)\n      -> check_stable slf state entryop = Some state'\n      -> commit_in_log com (log state') = true\n      -> commit_in_log com (log state) = true.\n  Proof.\n    introv wf h q.\n    unfold check_stable in h.\n    pbft_dest_all x;[].\n    apply clear_log_checkpoint_preserves_commit_in_log in q; auto.\n  Qed.\n  Hint Resolve check_stable_preserves_commit_in_log : pbft.\n\n  Lemma add_replies2entry_preserves_log_entry_commits :\n    forall entry reps,\n      log_entry_commits (add_replies2entry entry reps) = (log_entry_commits entry).\n  Proof.\n    induction entry; simpl in *; ginv; simpl in *; tcsp.\n  Qed.\n  Hint Rewrite add_replies2entry_preserves_log_entry_commits : pbft.\n\n  Lemma add_replies2entry_preserves_log_entry_request_data :\n    forall entry reps,\n      log_entry_request_data (add_replies2entry entry reps) = (log_entry_request_data entry).\n  Proof.\n    induction entry; simpl in *; ginv; simpl in *; tcsp.\n  Qed.\n  Hint Rewrite add_replies2entry_preserves_log_entry_request_data : pbft.\n\n  Lemma change_entry_add_replies2entry_preserves_commit_in_log :\n    forall com sn entry reps L,\n      commit_in_log\n        com\n        (change_entry L (add_replies2entry entry reps)) = true\n      -> find_entry L sn = Some entry\n      -> commit_in_log com L = true.\n  Proof.\n    induction L; introv h fe; simpl in *; tcsp.\n    smash_pbft;\n      try (complete (applydup entry2seq_if_find_entry in fe as eqsn;\n                     match goal with\n                     | [ H : similar_entry _ _ = _ |- _ ] =>\n                       apply entry2seq_if_similar_entry in H\n                     end;\n                     match goal with\n                     | [ H : _ <> _ |- _ ] => destruct H; allrw; auto\n                     end)).\n\n    {\n      match goal with\n      | [ H : similar_entry _ _ = _ |- _ ] =>\n        apply entry2seq_if_similar_entry in H\n      end.\n      match goal with\n      | [ H : find_entry _ _ = _ |- _ ] =>\n        apply entry2seq_if_find_entry in H; rewrite H in *; clear H\n      end.\n      smash_pbft.\n    }\n  Qed.\n  Hint Resolve change_entry_add_replies2entry_preserves_commit_in_log : pbft.\n\n  Lemma change_log_entry_add_replies2entry_preserves_commit_in_log :\n    forall com sn entry state reps,\n      commit_in_log\n        com\n        (log\n           (change_log_entry\n              state\n              (add_replies2entry entry reps))) = true\n      -> find_entry (log state) sn = Some entry\n      -> commit_in_log com (log state) = true.\n  Proof.\n    introv h fe.\n    destruct state; simpl in *.\n    eapply change_entry_add_replies2entry_preserves_commit_in_log in h;[|eauto].\n    auto.\n  Qed.\n  Hint Resolve change_log_entry_add_replies2entry_preserves_commit_in_log : pbft.\n\n  Lemma find_and_execute_requests_preserves_commit_in_log :\n    forall msg i com st p,\n      find_and_execute_requests i (current_view p) (local_keys p) p = (msg, st)\n      -> commit_in_log com (log st) = true\n      -> commit_in_log com (log p) = true.\n  Proof.\n    introv H1 H2.\n\n    unfold find_and_execute_requests in *.\n    pbft_dest_all x;[].\n    rename x1 into st.\n    unfold execute_requests in *.\n    destruct (ready p); simpl in *;[ inversion Heqx; allrw; tcsp |].\n\n    pbft_dest_all y.\n\n    match goal with\n    | [ H : context[reply2requests] |- _ ] => hide_hyp H\n    end.\n\n    match goal with\n    | [ H : check_broadcast_checkpoint _ _ _ _ _ = _ |- _ ] =>\n      apply check_broadcast_checkpoint_preserves_log in H\n    end.\n\n    match goal with\n    | [ H1 : commit_in_log _ (log ?s) = _, H2 : _ = log ?s |- _ ] =>\n      rewrite <- H2 in H1; clear H2\n    end.\n\n    pose proof (change_log_entry_add_replies2entry_preserves_commit_in_log\n                  com (next_to_execute p) y p y3) as xx.\n    apply xx in H2; auto.\n  Qed.\n  Hint Resolve find_and_execute_requests_preserves_commit_in_log : pbft.\n\n  Lemma add_prepare_to_log_from_new_view_pre_prepare_preserves_commit_in_log :\n    forall slf com pp d state state' msgs,\n      add_prepare_to_log_from_new_view_pre_prepare slf state (pp,d) = (state', msgs)\n      -> commit_in_log com (log state') = true\n      -> commit_in_log com (log state) = true\n         \\/\n         (\n           com\n           = request_data_and_rep_toks2commit\n               (pre_prepare2request_data pp d)\n               (pre_prepare2rep_toks_of_commit slf (local_keys state) pp d)\n           /\\ low_water_mark state < pre_prepare2seq pp\n           /\\ prepared_log (pre_prepare2request_data pp d) (log state') = true\n           /\\ commit_in_log com (log state) = false).\n  Proof.\n    introv h q.\n    unfold add_prepare_to_log_from_new_view_pre_prepare in h; smash_pbft.\n\n    match goal with\n    | [ H : check_send_replies _ _ _ _ _ _ = _ |- _ ] =>\n      apply check_send_replies_preserves_log in H; simpl in *; subst\n    end.\n\n    match goal with\n    | [ H : add_new_pre_prepare_and_prepare2log _ _ _ _ _ _ = _ |- _ ] =>\n      eapply add_new_pre_prepare_and_prepare2log_preserves_commit_in_log in H;[ | | eauto]\n    end.\n\n    - repndors; auto.\n      exrepnd; tcsp.\n\n    - unfold pre_prepare2rep_toks_of_commit.\n      autorewrite with pbft.\n      destruct pp, b. simpl in *. auto.\n  Qed.\n\n\n  Lemma fill_out_pp_info_with_prepare_preserves_existsb_rep_tok_commit :\n    forall i entry pp Fp Fc gi rt,\n      fill_out_pp_info_with_prepare i entry pp Fp Fc = Some gi\n      -> existsb (same_rep_tok rt) (log_entry_commits entry) = true\n      -> existsb (same_rep_tok rt) (log_entry_commits (gi_entry gi)) = true.\n  Proof.\n    introv h q; unfold fill_out_pp_info_with_prepare in h.\n    destruct entry; simpl in *.\n    destruct log_entry_pre_prepare_info; ginv.\n    smash_pbft.\n    unfold add_commit_if_prepared in *. smash_pbft.\n  Qed.\n  Hint Resolve fill_out_pp_info_with_prepare_preserves_existsb_rep_tok_commit : pbft.\n\n\n  Lemma add_new_pre_prepare_and_prepare2log_preserves_commit_in_log_forward :\n    forall i L pp d Fp Fc giop K com,\n      add_new_pre_prepare_and_prepare2log i L pp d Fp Fc = (giop, K)\n      -> commit_in_log com L = true\n      -> commit_in_log com K = true.\n  Proof.\n    induction L; introv h q; simpl in *; smash_pbft.\n\n    - allrw is_commit_for_entry_true_iff.\n      allrw is_commit_for_entry_false_iff.\n\n      match goal with\n      | [ H : fill_out_pp_info_with_prepare _ _ _ _ _ = _ |- _ ] =>\n        eapply fill_out_pp_info_with_prepare_preserves_request_data in H\n      end.\n\n      rewrite Heqx in Heqx1. tcsp.\n\n    - allrw is_commit_for_entry_true_iff.\n      allrw is_commit_for_entry_false_iff.\n\n      match goal with\n      | [ H : fill_out_pp_info_with_prepare _ _ _ _ _ = _ |- _ ] =>\n        apply fill_out_pp_info_with_prepare_preserves_request_data in H\n      end.\n\n      match goal with\n      | [ H1 : ?x = ?y, H2 : ?x = ?z |- _ ] => rewrite H2 in H1; tcsp\n      end.\n  Qed.\n  Hint Resolve add_new_pre_prepare_and_prepare2log_preserves_commit_in_log_forward : pbft.\n\n  Lemma check_send_replies_preserves_commit_in_log_forward :\n    forall i v keys giop state n msgs state' com,\n      check_send_replies i v keys giop state n = (msgs, state')\n      -> commit_in_log com (log state) = true\n      -> commit_in_log com (log state') = true.\n  Proof.\n    pbft_brute_force.\n  Qed.\n  Hint Resolve check_send_replies_preserves_commit_in_log_forward : pbft.\n\n  Lemma add_prepare_to_log_from_new_view_pre_prepare_preserves_commit_in_log_forward :\n    forall slf com state pp d state' msgs,\n      add_prepare_to_log_from_new_view_pre_prepare slf state (pp, d) = (state', msgs)\n      -> commit_in_log com (log state) = true\n      -> commit_in_log com (log state') = true.\n  Proof.\n    introv h q.\n    unfold add_prepare_to_log_from_new_view_pre_prepare in h.\n    smash_pbft.\n  Qed.\n  Hint Resolve add_prepare_to_log_from_new_view_pre_prepare_preserves_commit_in_log_forward : pbft.\n\n\n  Lemma add_prepares_to_log_from_new_view_pre_prepares_preserves_commit_in_log_forward :\n    forall slf com pps state state' msgs,\n      add_prepares_to_log_from_new_view_pre_prepares slf state pps = (state', msgs)\n      -> commit_in_log com (log state) = true\n      -> commit_in_log com (log state') = true.\n  Proof.\n    induction pps; introv h q; simpl in *; smash_pbft; repnd.\n    eapply IHpps; eauto with pbft.\n  Qed.\n  Hint Resolve add_prepares_to_log_from_new_view_pre_prepares_preserves_commit_in_log_forward : pbft.\n\n\n  Lemma add_prepare_to_log_from_new_view_pre_prepare_preserves_commit_in_log_backward :\n    forall slf com state pp d state' msgs,\n      add_prepare_to_log_from_new_view_pre_prepare slf state (pp, d) = (state', msgs)\n      -> commit_in_log com (log state') = false\n      -> commit_in_log com (log state) = false.\n  Proof.\n    introv h q.\n    match goal with\n    | [ |- ?a = ?b ] => remember a as pb; symmetry in Heqpb; destruct pb; auto\n    end.\n    eapply add_prepare_to_log_from_new_view_pre_prepare_preserves_commit_in_log_forward in h;[|eauto].\n    rewrite h in q; ginv.\n  Qed.\n  Hint Resolve add_prepare_to_log_from_new_view_pre_prepare_preserves_commit_in_log_backward : pbft.\n\n\n  Lemma add_prepares_to_log_from_new_view_pre_prepares_preserves_commit_in_log_backward :\n    forall slf com pps state state' msgs,\n      add_prepares_to_log_from_new_view_pre_prepares slf state pps = (state', msgs)\n      -> commit_in_log com (log state') = false\n      -> commit_in_log com (log state) = false.\n  Proof.\n    introv h q.\n    match goal with\n    | [ |- ?a = ?b ] => remember a as pb; symmetry in Heqpb; destruct pb; auto\n    end.\n    eapply add_prepares_to_log_from_new_view_pre_prepares_preserves_commit_in_log_forward in h;[|eauto].\n    rewrite h in q; ginv.\n  Qed.\n  Hint Resolve add_prepares_to_log_from_new_view_pre_prepares_preserves_commit_in_log_backward : pbft.\n\n  Lemma add_prepares_to_log_from_new_view_pre_prepares_preserves_commit_in_log :\n    forall slf com pps state state' msgs,\n      add_prepares_to_log_from_new_view_pre_prepares slf state pps = (state', msgs)\n      -> commit_in_log com (log state') = true\n      -> commit_in_log com (log state) = true\n         \\/\n         (\n           exists pp d,\n             In (pp,d) pps\n             /\\ com\n                = request_data_and_rep_toks2commit\n                    (pre_prepare2request_data pp d)\n                    (pre_prepare2rep_toks_of_commit slf (local_keys state) pp d)\n             /\\ low_water_mark state < pre_prepare2seq pp\n             /\\ commit_in_log com (log state) = false).\n  Proof.\n    induction pps; introv h q; simpl in *; smash_pbft; repnd;\n      match goal with\n      | [ H : add_prepares_to_log_from_new_view_pre_prepares _ _ _ = _ |- _ ] =>\n        apply IHpps in H;auto;[]\n      end;\n      repndors; tcsp.\n\n    {\n      rename_hyp_with check_send_replies check.\n      rename_hyp_with add_new_pre_prepare_and_prepare2log add.\n      eapply check_send_replies_preserves_commit_in_log in check;[|eauto]; simpl in *.\n      eapply add_new_pre_prepare_and_prepare2log_preserves_commit_in_log in add; eauto; autorewrite with pbft; auto.\n      repndors; tcsp.\n      repnd; subst; simpl in *.\n      right; eexists; eexists; dands; try reflexivity; tcsp.\n    }\n\n    {\n      exrepnd; subst.\n      rename_hyp_with check_send_replies check.\n      rename_hyp_with add_new_pre_prepare_and_prepare2log add.\n      right.\n      applydup check_send_replies_preserves_keys in check; simpl in *.\n      applydup check_send_replies_preserves_low_water_mark in check; simpl in *; autorewrite with pbft in *.\n\n      eexists; eexists; dands; try reflexivity; try rewrite check0;\n        try rewrite <- check1; try reflexivity; simpl; try omega;\n          tcsp; try rewrite <- check0.\n      match goal with\n      | [ |- ?x = _ ] => remember x as b; symmetry in Heqb; destruct b; auto\n      end.\n      eapply add_new_pre_prepare_and_prepare2log_preserves_commit_in_log_forward in add;[|eauto].\n      eapply check_send_replies_preserves_commit_in_log_forward in check;[|simpl;eauto]; ginv.\n    }\n\n    {\n      exrepnd; subst.\n      right.\n      eexists; eexists; dands; try reflexivity; tcsp.\n    }\n  Qed.\n  (*Hint Rewrite add_prepares_to_log_from_new_view_pre_prepares_preserves_commit_in_log : pbft.*)\n\n  Lemma log_pre_prepares_preserves_commit_in_log :\n    forall com P L lwm,\n      commit_in_log com (log_pre_prepares L lwm P)\n      = commit_in_log com L.\n  Proof.\n    induction P; introv; simpl in *; tcsp; repnd; smash_pbft.\n    rewrite IHP.\n    apply add_new_pre_prepare2log_preserves_commit_in_log.\n  Qed.\n  Hint Rewrite log_pre_prepares_preserves_commit_in_log : pbft.\n\n  Lemma update_state_new_view_preserves_commit_in_log2 :\n    forall i st nv st' msgs com,\n      well_formed_log (log st)\n      -> correct_new_view nv = true\n      -> update_state_new_view i st nv = (st', msgs)\n      -> commit_in_log com (log st') = true\n      -> commit_in_log com (log st) = true\n         /\\ (low_water_mark st < low_water_mark st' -> low_water_mark st' < commit2seq com).\n  Proof.\n    introv wf cor upd h.\n    unfold update_state_new_view in *; smash_pbft;\n      try (complete (dands; auto; introv q; try omega));[].\n\n    apply clear_log_checkpoint_preserves_commit_in_log2 in h; eauto 3 with pbft;[].\n    repnd.\n    unfold log_checkpoint_cert_from_new_view in *; smash_pbft.\n\n    + unfold low_water_mark; simpl; dands; auto.\n\n      rename_hyp_with view_change_cert2max_seq_vc maxs.\n      applydup view_change_cert2_max_seq_vc_some_in in maxs.\n      applydup sn_of_view_change_cert2max_seq_vc in maxs.\n      subst.\n\n      rename_hyp_with extract_seq_and_digest_from_checkpoint_certificate ext.\n      eapply extract_seq_and_digest_from_checkpoint_certificate_implies_eq_view_change2seq in ext; eauto 3 with pbft; [].\n      subst; auto.\n\n    + rename_hyp_with extract_seq_and_digest_from_checkpoint_certificate ext.\n      eapply extract_seq_and_digest_from_checkpoint_certificate_none_implies in ext.\n      rewrite ext in *.\n      simpl in *; ginv.\n\n    + rename_hyp_with extract_seq_and_digest_from_checkpoint_certificate ext.\n      eapply extract_seq_and_digest_from_checkpoint_certificate_implies_eq_view_change2seq in ext; eauto 3 with pbft;[].\n      subst.\n      unfold low_water_mark; simpl in *.\n      dands; auto.\n\n      rename_hyp_with view_change_cert2max_seq_vc maxs.\n      applydup view_change_cert2_max_seq_vc_some_in in maxs.\n      applydup sn_of_view_change_cert2max_seq_vc in maxs.\n      subst; auto.\n\n    + rename_hyp_with extract_seq_and_digest_from_checkpoint_certificate ext.\n      apply extract_seq_and_digest_from_checkpoint_certificate_none_implies in ext.\n      dands; auto.\n\n      rename_hyp_with view_change_cert2max_seq_vc maxs.\n      applydup view_change_cert2_max_seq_vc_some_in in maxs.\n      applydup sn_of_view_change_cert2max_seq_vc in maxs.\n      subst; auto.\n\n      assert (correct_view_change (new_view2view nv) x2 = true) as cvc by eauto 3 with pbft;[].\n      unfold correct_view_change in cvc; smash_pbft.\n      rewrite ext in *.\n      simpl in *; ginv; try omega.\n  Qed.\n\n  Lemma update_state_new_view_preserves_commit_in_log :\n    forall i st nv st' msgs com,\n      well_formed_log (log st)\n      -> update_state_new_view i st nv = (st', msgs)\n      -> commit_in_log com (log st') = true\n      -> commit_in_log com (log st) = true.\n  Proof.\n    introv wf upd h.\n    unfold update_state_new_view in *; smash_pbft.\n    apply clear_log_checkpoint_preserves_commit_in_log in h; eauto 3 with pbft;[].\n    unfold log_checkpoint_cert_from_new_view in *; smash_pbft.\n  Qed.\n  Hint Resolve update_state_new_view_preserves_commit_in_log : pbft.\n\n  Lemma commit_in_log_clear_log_checkpoint_false_implies :\n    forall (n : SeqNum) c L,\n      n < commit2seq c\n      -> commit_in_log c (clear_log_checkpoint L n) = false\n      -> commit_in_log c L = false.\n  Proof.\n    induction L; introv h prep; simpl in *; smash_pbft.\n    repeat (autodimp IHL hyp).\n    allrw SeqNumLe_true.\n    destruct a, c, b, log_entry_request_data; simpl in *; ginv; omega.\n  Qed.\n  Hint Resolve commit_in_log_clear_log_checkpoint_false_implies : pbft.\n\n  Lemma update_state_new_view_preserves_commit_in_log_false_forward :\n    forall c i s1 v s2 msgs,\n      correct_new_view v = true\n      -> update_state_new_view i s1 v = (s2, msgs)\n      -> low_water_mark s2 < commit2seq c\n      -> commit_in_log c (log s2) = false\n      -> commit_in_log c (log s1) = false.\n  Proof.\n    introv cor upd h com.\n\n    unfold update_state_new_view in upd; smash_pbft.\n    unfold log_checkpoint_cert_from_new_view in *; smash_pbft.\n\n    - unfold update_log_checkpoint_stable, low_water_mark in *; simpl in *.\n      apply commit_in_log_clear_log_checkpoint_false_implies in com; eauto 3 with pbft.\n\n      rename_hyp_with view_change_cert2max_seq_vc mseq.\n      applydup view_change_cert2_max_seq_vc_some_in in mseq.\n      apply sn_of_view_change_cert2max_seq_vc in mseq; subst.\n\n      rename_hyp_with extract_seq_and_digest_from_checkpoint_certificate ext.\n      eapply extract_seq_and_digest_from_checkpoint_certificate_implies_eq_view_change2seq in ext; eauto 3 with pbft;[].\n      subst; auto.\n\n    - rename_hyp_with view_change_cert2max_seq_vc mseq.\n      applydup view_change_cert2_max_seq_vc_some_in in mseq.\n      apply sn_of_view_change_cert2max_seq_vc in mseq; subst.\n\n      rename_hyp_with extract_seq_and_digest_from_checkpoint_certificate ext.\n      apply extract_seq_and_digest_from_checkpoint_certificate_none_implies in ext.\n      rewrite ext in *.\n      simpl in *; ginv.\n\n    - unfold update_log_checkpoint_stable, low_water_mark in *; simpl in *.\n      apply commit_in_log_clear_log_checkpoint_false_implies in com; eauto 3 with pbft.\n\n      rename_hyp_with view_change_cert2max_seq_vc mseq.\n      applydup view_change_cert2_max_seq_vc_some_in in mseq.\n      apply sn_of_view_change_cert2max_seq_vc in mseq; subst.\n\n      rename_hyp_with extract_seq_and_digest_from_checkpoint_certificate ext.\n      eapply extract_seq_and_digest_from_checkpoint_certificate_implies_eq_view_change2seq in ext; eauto 3 with pbft;[].\n      subst; auto.\n\n    - rename_hyp_with view_change_cert2max_seq_vc mseq.\n      applydup view_change_cert2_max_seq_vc_some_in in mseq.\n      apply sn_of_view_change_cert2max_seq_vc in mseq; subst.\n\n      rename_hyp_with extract_seq_and_digest_from_checkpoint_certificate ext.\n      apply extract_seq_and_digest_from_checkpoint_certificate_none_implies in ext.\n      rewrite ext in *.\n      simpl in *; ginv.\n\n      apply correct_new_view_implies_correct_view_change in mseq0; auto.\n      unfold correct_view_change, correct_view_change_cert in *; smash_pbft.\n      rewrite ext in *; simpl in *; omega.\n  Qed.\n  Hint Resolve update_state_new_view_preserves_commit_in_log_false_forward : pbft.\n\nEnd PBFTcommit_in_log_preserves.\n\n\nHint Resolve check_send_replies_preserves_commit_in_log: pbft.\nHint Resolve commit2sender_eq_if_request_data_and_rep_toks_equal : pbft.\nHint Resolve fill_out_pp_info_with_prepare_preserves_existsb_rep_tok_commit : pbft.\nHint Resolve add_new_pre_prepare_and_prepare2log_preserves_commit_in_log_forward : pbft.\nHint Resolve check_send_replies_preserves_commit_in_log_forward : pbft.\nHint Resolve add_prepare_to_log_from_new_view_pre_prepare_preserves_commit_in_log_forward : pbft.\nHint Resolve add_prepares_to_log_from_new_view_pre_prepares_preserves_commit_in_log_forward : pbft.\nHint Resolve add_prepare_to_log_from_new_view_pre_prepare_preserves_commit_in_log_backward : pbft.\nHint Resolve add_prepares_to_log_from_new_view_pre_prepares_preserves_commit_in_log_backward : pbft.\nHint Resolve commit_in_log_clear_log_checkpoint_false_implies : pbft.\nHint Resolve update_state_new_view_preserves_commit_in_log_false_forward : pbft.\nHint Resolve clear_log_checkpoint_preserves_commit_in_log : pbft.\nHint Resolve update_state_new_view_preserves_commit_in_log : pbft.\nHint Resolve check_stable_preserves_commit_in_log : pbft.\nHint Resolve change_entry_add_replies2entry_preserves_commit_in_log : pbft.\nHint Resolve change_log_entry_add_replies2entry_preserves_commit_in_log : pbft.\nHint Resolve find_and_execute_requests_preserves_commit_in_log : pbft.\n\n\nHint Rewrite @is_commit_for_entry_true_iff : pbft.\nHint Rewrite @is_commit_for_entry_false_iff : pbft.\nHint Rewrite @add_new_pre_prepare2log_preserves_commit_in_log : pbft.\nHint Rewrite @decomp_commit : pbft.\nHint Rewrite @rt_rep_commit2rep_toks_as_commit2sender: pbft.\nHint Rewrite @add_replies2entry_preserves_log_entry_request_data : pbft.\nHint Rewrite @log_pre_prepares_preserves_commit_in_log : pbft.\nHint Rewrite @add_replies2entry_preserves_log_entry_commits : pbft.\n(*Hint Rewrite @commit_in_log_add_new_pre_prepare2log_log_entry_commits : pbft.*)\n(*Hint Rewrite @add_new_pre_prepare_and_prepare2log_preserves_commit_in_log : pbft.*)\n(*Hint Rewrite @add_new_prepare2log_preserves_commit_in_log : pbft.*)\n(*Hint Resolve @add_commit2entry_some_implies_log_entry_commits_gi_entry_or: pbft.*)\n(*Hint Rewrite @add_new_commit2log_preserves_commit_in_log : pbft.*)\n(*Hint Rewrite @entry_of_commit_in_log : pbft.*)\n(*Hint Rewrite @add_prepares_to_log_from_new_view_pre_prepares_preserves_commit_in_log : pbft.*)\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/PBFT/PBFTcommit_in_log_preserves.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21620263719888966}}
{"text": "Load coql.\n\n(**\n    We represent the internal state as a stack.\n\n    Perhaps a stack is not the best data structure \n    since at every step of the evaluation of a query we need at most the top element of the stack.\n\n    However, this is an example to show how the underlying state can be represented in arbitrary ways.\n\n    For example, it could be an SQL table or a JSON object.\n*)\n\nRecord UserRecord := {\n  _id: nat;\n  name: string;\n  surname: string;\n  age: nat;\n}.\n\nInductive data: Type :=\n  | mkUser: UserRecord -> data\n  | mkString: string -> data\n  | mkNat: nat -> data.\n\nDefinition Stack := list data.\n\n(**\n    This function represents a simple database query\n*)\n\nDefinition findUserById := fun(id: nat) =>\n  match id with\n    | 1 => Some {| _id := 1; name := \"Johnny\"; surname := \"Hendrix\"; age := 27 |}\n    | _ => None\n  end.\n\nDefinition User: ty := \n    TPar\n      (TField \"name\" TBot TString)\n      (TPar\n        (TField \"surname\" TBot TString)\n        (TField \"age\" TBot TNat)).\n\nDefinition update: UserRecord -> (state Stack unit) := fun(user: UserRecord)(st: Stack) => (tt, mkUser(user)::st).\n\nDefinition findUserByIdResolver: resolver(Stack) := fun(t: tm)(st: Stack) => \n  match t with \n    | tnat userId => \n      match findUserById(userId) with \n        | Some user => \n          let (_, st') := update user st in\n            (inl (Some User), st')\n        | None => (inl None, st)\n      end\n    | _ => (inr err, st)\n  end.\n\nDefinition findUserNameResolver: resolver(Stack) := fun(t: tm)(st: Stack) =>\n  match st with \n    | x::st' => \n      match x with \n        | mkUser(x) => ( inl (Some TString),  mkString(name x)::st)\n        | _ => (inr err, st)\n      end\n    | nil => (inr err, st)\n  end.\n\nDefinition findUserAgeResolver: resolver(Stack) := fun(t: tm)(st: Stack) =>\n  match st with \n    | x::st' => \n      match x with \n        | mkUser(x) => ( inl (Some TNat),  mkNat(age x)::st)\n        | _ => (inr err, st)\n      end\n    | nil => (inr err, st)\n  end.\n\nDefinition Schema: schema(Stack) := fun( p: list string ) =>\n  match p with\n    | \"findUserById\" :: nil => Some(findUserByIdResolver)\n    | \"name\" :: \"findUserById\" :: nil => Some( findUserNameResolver )\n    | \"age\" :: \"findUserById\" :: nil => Some( findUserAgeResolver )\n    | _ => None\n  end.\n\n\nDefinition Root: ty := TField \"findUserById\" TNat User.\n\nDefinition get: getter(Stack) := fun(st: Stack) =>\n  match st with \n    | x::st' => \n      match x with\n        | mkString(s) => (Some (tstring s), st)\n        | mkNat(n) => (Some (tnat n), st)\n        | _ => (None, st)\n      end\n    | nil => (None, st)\n  end.\n\nExample res1: \n  < Stack ; Schema ; get ; [] ; Root > |= \n    tfield \"findUserById\" (tnat 1) \n      (tpar\n        (tfield \"name\" tempty thole)\n        (tfield \"age\" tempty thole) ) / []\n      \\\\ tfieldr \"findUserById\" (tnat 1)\n          (tpar\n            (tfieldr \"name\" tempty (tstring \"Johnny\"))\n            (tfieldr \"age\" tempty (tnat 27))\n          ).\nProof. \n  apply E_Field with User findUserByIdResolver [ mkUser {| _id := 1; name := \"Johnny\"; surname := \"Hendrix\"; age := 27 |}].\n  - trivial.\n  - simpl. reflexivity.\n  - simpl. reflexivity.\n  - apply E_Par.\n      apply E_Field with TString findUserNameResolver [ mkString \"Johnny\" ; mkUser {| _id := 1; name := \"Johnny\"; surname := \"Hendrix\"; age := 27 |}].\n      trivial.\n      simpl. reflexivity.\n      trivial.\n      apply E_Hole. simpl. reflexivity.\n      trivial.\n      apply E_Field with TNat findUserAgeResolver [ mkNat 27 ; mkUser {| _id := 1; name := \"Johnny\"; surname := \"Hendrix\"; age := 27 |}].\n      trivial.\n      simpl. reflexivity.\n      simpl. reflexivity.\n      apply E_Hole. simpl. reflexivity. trivial.\nQed. ", "meta": {"author": "mstn", "repo": "coql", "sha": "ba9e6b24fb772334e735eac94646b0920a6f75b8", "save_path": "github-repos/coq/mstn-coql", "path": "github-repos/coq/mstn-coql/coql-ba9e6b24fb772334e735eac94646b0920a6f75b8/example_eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117165898111865, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21620263090653713}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Website: http://nuprl.org/html/verification/\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Import type_sys_useful.\nRequire Import dest_close.\n\n\n\nLemma close_type_system_pertype {p} :\n  forall lib (ts : cts(p))\n         T T'\n         (eq : per)\n         R1 R2 eq1 eq2,\n    type_system lib ts\n    -> defines_only_universes lib ts\n    -> computes_to_valc lib T (mkc_pertype R1)\n    -> computes_to_valc lib T' (mkc_pertype R2)\n    -> (forall x y : CTerm,\n          close lib ts (mkc_apply2 R1 x y) (mkc_apply2 R1 x y) (eq1 x y))\n    -> (forall x y : CTerm,\n          type_system lib ts\n          -> defines_only_universes lib ts\n          -> type_sys_props lib (close lib ts)\n                            (mkc_apply2 R1 x y)\n                            (mkc_apply2 R1 x y)\n                            (eq1 x y))\n    -> (forall x y : CTerm,\n          close lib ts (mkc_apply2 R2 x y) (mkc_apply2 R2 x y) (eq2 x y))\n    -> (forall x y : CTerm,\n          type_system lib ts\n          -> defines_only_universes lib ts\n          -> type_sys_props lib (close lib ts)\n                            (mkc_apply2 R2 x y)\n                            (mkc_apply2 R2 x y)\n                            (eq2 x y))\n    -> (forall x y : CTerm, inhabited (eq1 x y) <=> inhabited (eq2 x y))\n    -> is_per eq1\n    -> (forall t t' : CTerm, eq t t' <=> inhabited (eq1 t t'))\n    -> per_pertype lib (close lib ts) T T' eq\n    -> type_sys_props lib (close lib ts) T T' eq.\nProof.\n  introv X X0 c1 c2 cl1 rec1 cl2 rec2 inh isper.\n  intros eqiff per.\n\n  rw @type_sys_props_iff_type_sys_props3.\n  prove_type_sys_props3 SCase; intros.\n\n  - SCase \"uniquely_valued\".\n    dclose_lr.\n\n    SSCase \"CL_pertype\".\n    clear per.\n    allunfold @per_pertype; exrepd.\n    unfold eq_term_equals; intros.\n    allrw.\n    ccomputes_to_eqval.\n    rw <- t; rw <- inh.\n    generalize (c3 t1 t2); intro clt1.\n    generalize (rec1 t1 t2); sp.\n    onedtsp uv tys tyt tyst tyvr tes tet tevr tygs tygt dum.\n    implies_ts_or (mkc_apply2 R1 t1 t2) clt1.\n    apply uv in clt1.\n    unfold eq_term_equals in clt1.\n    unfold inhabited; split; sp.\n    exists t3; rw <- clt1; sp.\n    exists t3; rw clt1; sp.\n\n  - SCase \"type_symmetric\"; repdors; subst; dclose_lr;\n    apply CL_pertype;\n    clear per;\n    allunfold @per_pertype; exrepd;\n    unfold per_pertype;\n    ccomputes_to_eqval.\n\n    + exists R1 R3 eq1 eq3; sp; spcast; sp.\n      rw <- t; rw <- eqiff; rw <- t0; sp.\n      allrw <-; sp.\n\n  - SCase \"type_value_respecting\"; repdors; subst;\n    apply CL_pertype; unfold per_pertype.\n\n    (* 1 *)\n    apply cequivc_mkc_pertype with (a := R1) in X1; sp.\n    exists R1 b eq1 eq1; sp; spcast; sp.\n    generalize (cl1 x y); intro clt1.\n    generalize (rec1 x y); sp.\n    onedtsp uv tys tyt tyst tyvr tes tet tevr tygs tygt tymt.\n    generalize (tyvr (mkc_apply2 R1 x y) (mkc_apply2 b x y)); intro imp1.\n    repeat (autodimp imp1 hyp).\n    repeat (rw @mkc_apply2_eq).\n    repeat (apply sp_implies_cequivc_apply); auto.\n\n    generalize (tyt (mkc_apply2 b x y) (eq1 x y)); sp.\n\n    (* 2 *)\n    apply @cequivc_mkc_pertype with (a := R2) in X1; sp.\n    exists R2 b eq2 eq2; sp; spcast; sp.\n    generalize (cl2 x y); intro clt1.\n    generalize (rec2 x y); sp.\n    onedtsp uv tys tyt tyst tyvr tes tet tevr tygs tygt tymt.\n    generalize (tyvr (mkc_apply2 R2 x y) (mkc_apply2 b x y)); intro imp1.\n    repeat (autodimp imp1 hyp).\n    repeat (rw @mkc_apply2_eq).\n    repeat (apply sp_implies_cequivc_apply); auto.\n\n    generalize (tyt (mkc_apply2 b x y) (eq2 x y)); sp.\n\n    apply @is_per_iff with (eq1 := eq1); auto.\n\n    rw eqiff; sp.\n\n  - SCase \"term_symmetric\".\n    unfold term_equality_symmetric; introv eqt.\n    rw eqiff in eqt; rw eqiff.\n    apply is_per_sym; sp.\n\n  - SCase \"term_transitive\".\n    unfold term_equality_transitive; introv eqt1 eqt2.\n    rw eqiff in eqt1; rw eqiff in eqt2; rw eqiff.\n    apply is_per_trans with (b := t2); sp.\n\n  - SCase \"term_value_respecting\".\n    unfold term_equality_respecting; introv eqt ceq.\n    rw eqiff in eqt; rw eqiff.\n\n    spcast.\n    assert (eq_term_equals (eq1 t t') (eq1 t t)) as eqteq.\n    generalize (rec1 t t); sp.\n    onedtsp uv tys tyt tyst tyvr tes tet tevr tygs tygt tymt.\n    generalize (tyvr (mkc_apply2 R1 t t) (mkc_apply2 R1 t t')); intro i; repeat (autodimp i h).\n    repeat (rw @mkc_apply2_eq).\n    apply implies_cequivc_apply; sp.\n    generalize (rec1 t t'); sp.\n    onedtsp uv2 tys2 tyt2 tyst2 tyvr2 tes2 tet2 tevr2 tygs2 tygt2 tymt2.\n    generalize (tygs (mkc_apply2 R1 t t) (mkc_apply2 R1 t t') (eq1 t t)); intro k; repeat (autodimp k h).\n    rw k in i.\n    generalize (uv2 (mkc_apply2 R1 t t) (eq1 t t)); intro j; repeat (autodimp j h).\n\n    apply eq_term_equals_implies_inhabited in eqteq.\n    rw eqteq; sp.\n\n  - SCase \"type_gsymmetric\".\n    repdors; subst; split; sp; dclose_lr;\n    apply CL_pertype;\n    clear per;\n    allunfold @per_pertype; exrepd;\n    ccomputes_to_eqval;\n    unfold per_pertype.\n\n    (* 1 *)\n    assert (forall x y, eq_term_equals (eq1 x y) (eq0 x y))\n           as eqteq1\n           by (apply (type_sys_props_pertype_eq_term_equals lib) with (ts := close lib ts) (R := R1); sp).\n\n    exists R3 R1 eq3 eq1; sp; spcast; sp.\n    rw <- t.\n    apply eq_term_equals_implies_inhabited; sp.\n    apply eq_term_equals_sym; sp.\n\n    apply @is_per_iff with (eq1 := eq0); auto.\n\n    rw t0; auto.\n\n    (* 2 *)\n    assert (forall x y, eq_term_equals (eq1 x y) (eq3 x y))\n           as eqteq1\n           by (apply (type_sys_props_pertype_eq_term_equals lib) with (ts := close lib ts) (R := R1); sp).\n\n    exists R1 R0 eq1 eq0; sp; spcast; sp.\n    rw t.\n    apply eq_term_equals_implies_inhabited; sp.\n\n    rw t0.\n    rw t.\n    apply eq_term_equals_implies_inhabited; sp.\n    apply eq_term_equals_sym; sp.\n\n  - SCase \"type_gtransitive\"; sp.\n\n  - SCase \"type_mtransitive\".\n    repdors; subst; dclose_lr;\n    try (move_term_to_top (per_pertype lib (close lib ts) T T4 eq3));\n    try (move_term_to_top (per_pertype lib (close lib ts) T' T4 eq3));\n    allunfold @per_pertype; exrepd;\n    ccomputes_to_eqval;\n    try (assert (forall x y, eq_term_equals (eq1 x y) (eq8 x y))\n                as eqteq1\n                by (apply (type_sys_props_pertype_eq_term_equals lib) with (ts := close lib ts) (R := R1); sp));\n    try (assert (forall x y, eq_term_equals (eq1 x y) (eq7 x y))\n                as eqteq2\n                by (apply (type_sys_props_pertype_eq_term_equals lib) with (ts := close lib ts) (R := R1); sp));\n    try (assert (forall x y, eq_term_equals (eq1 x y) (eq4 x y))\n                as eqteq3\n                by (apply (type_sys_props_pertype_eq_term_equals lib) with (ts := close lib ts) (R := R1); sp));\n    try (assert (forall x y, eq_term_equals (eq2 x y) (eq9 x y))\n                as eqteq4\n                by (apply (type_sys_props_pertype_eq_term_equals lib) with (ts := close lib ts) (R := R2); sp));\n    try (assert (forall x y, eq_term_equals (eq2 x y) (eq7 x y))\n                as eqteq5\n                by (apply (type_sys_props_pertype_eq_term_equals lib) with (ts := close lib ts) (R := R2); sp));\n    try (assert (forall x y, eq_term_equals (eq2 x y) (eq4 x y))\n                as eqteq6\n                by (apply (type_sys_props_pertype_eq_term_equals lib) with (ts := close lib ts) (R := R2); sp)).\n\n    + dands; apply CL_pertype; unfold per_pertype.\n\n      * exists R4 R3 eq6 eq5; sp; spcast; sp.\n        rw <- t; rw t1.\n        apply eq_term_equals_implies_inhabited; sp.\n        apply @eq_term_equals_trans with (eq2 := eq1 x y); sp.\n        apply eq_term_equals_sym; sp.\n\n      * exists R4 R3 eq6 eq5; sp; spcast; sp.\n        rw <- t; rw t1.\n        apply eq_term_equals_implies_inhabited; sp.\n        apply @eq_term_equals_trans with (eq2 := eq1 x y); sp.\n        apply eq_term_equals_sym; sp.\n\n        rw t0; rw t1.\n        apply eq_term_equals_implies_inhabited; sp.\n        apply @eq_term_equals_trans with (eq2 := eq1 t5 t'); sp.\n        apply eq_term_equals_sym; sp.\n\n    + dands; apply CL_pertype; unfold per_pertype.\n\n      * exists R4 R3 eq6 eq5; sp; spcast; sp.\n        rw <- t; rw t1.\n        apply eq_term_equals_implies_inhabited; sp.\n        apply @eq_term_equals_trans with (eq2 := eq2 x y); sp.\n        apply eq_term_equals_sym; sp.\n\n      * exists R4 R3 eq6 eq5; sp; spcast; sp.\n        rw <- t; rw t1.\n        apply eq_term_equals_implies_inhabited; sp.\n        apply @eq_term_equals_trans with (eq2 := eq2 x y); sp.\n        apply eq_term_equals_sym; sp.\n\n        rw t0; rw t1.\n        apply eq_term_equals_implies_inhabited; sp.\n        apply @eq_term_equals_trans with (eq2 := eq2 t5 t'); sp.\n        apply eq_term_equals_sym; sp.\nQed.\n\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/close/close_type_sys_per_pertype.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241632752914, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.21607874058580692}}
{"text": "(* Skeleton by Edgser for Crowdfunding_Based_On_Scilla.ds *)\nRequire Import BinPos.\nRequire Import DeepSpec.Runtime.\nRequire Import Crowdfunding_Based_On_Scilla.EdsgerIdents.\nRequire Import Crowdfunding_Based_On_Scilla.DataTypes.\nRequire Import Crowdfunding_Based_On_Scilla.DataTypeOps.\nRequire Import Crowdfunding_Based_On_Scilla.DataTypeProofs.\nRequire Import Crowdfunding_Based_On_Scilla.LayerCROWDFUNDING.\n\nRequire Import Additions.Tactics.\n\nSection EdsgerGen.\n\nExisting Instance GlobalLayerSpec.\nExisting Instances CROWDFUNDING_overlay_spec.\n\nContext {memModelOps : MemoryModelOps mem}.\n\nLemma Crowdfunding_constructor_vc me d :\n    high_level_invariant d ->\n    synth_func_cond Crowdfunding_constructor Crowdfunding_constructor_wf\n                    me d.\nProof.\n    code_proofs_auto.\nQed.\n\nLemma Crowdfunding_constructor_oblg me d :\n    high_level_invariant d ->\n    synth_func_obligation Crowdfunding_constructor Crowdfunding_constructor_wf\n                          me d.\nProof.\n    code_proofs_auto.\nQed.\n\nLemma Crowdfunding_donate_vc me d :\n    high_level_invariant d ->\n    synth_func_cond Crowdfunding_donate Crowdfunding_donate_wf\n                    me d.\nProof.\n    code_proofs_auto.\nQed.\n\nLemma Crowdfunding_donate_oblg me d :\n    high_level_invariant d ->\n    synth_func_obligation Crowdfunding_donate Crowdfunding_donate_wf\n                          me d.\nProof.\n    code_proofs_auto.\nQed.\n\nLemma Crowdfunding_getFunds_vc me d :\n    high_level_invariant d ->\n    synth_func_cond Crowdfunding_getFunds Crowdfunding_getFunds_wf\n                    me d.\nProof.\n    code_proofs_auto.\nQed.\n\nLemma Crowdfunding_getFunds_oblg me d :\n    high_level_invariant d ->\n    synth_func_obligation Crowdfunding_getFunds Crowdfunding_getFunds_wf\n                          me d.\nProof.\n    code_proofs_auto.\nQed.\n\nLemma Crowdfunding_claim_vc me d :\n    high_level_invariant d ->\n    synth_func_cond Crowdfunding_claim Crowdfunding_claim_wf\n                    me d.\nProof.\n    code_proofs_auto.\nQed.\n\nLemma Crowdfunding_claim_oblg me d :\n    high_level_invariant d ->\n    synth_func_obligation Crowdfunding_claim Crowdfunding_claim_wf\n                          me d.\nProof.\n    code_proofs_auto.\nQed.\n\nEnd EdsgerGen.\n", "meta": {"author": "Coda-Coda", "repo": "popl-2022-example", "sha": "f1a87da27957ccf3756fb14846e5a8189fda4939", "save_path": "github-repos/coq/Coda-Coda-popl-2022-example", "path": "github-repos/coq/Coda-Coda-popl-2022-example/popl-2022-example-f1a87da27957ccf3756fb14846e5a8189fda4939/ObjCrowdfundingCodeProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21602354846075858}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Function calling conventions and other conventions regarding the use of\n    machine registers and stack slots. *)\n\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Events.\nRequire Import Locations.\nRequire Archi.\n\n(** * Classification of machine registers *)\n\n(** Machine registers (type [mreg] in module [Locations]) are divided in\n  the following groups:\n- Temporaries used for spilling, reloading, and parallel move operations.\n- Allocatable registers, that can be assigned to RTL pseudo-registers.\n  These are further divided into:\n-- Callee-save registers, whose value is preserved across a function call.\n-- Caller-save registers that can be modified during a function call.\n\n  We follow the ARM application binary interface (EABI) in our choice\n  of callee- and caller-save registers.\n*)\n\nDefinition int_caller_save_regs :=\n  R0 :: R1 :: R2 :: R3 :: R12 :: nil.\n\nDefinition float_caller_save_regs :=\n  F0 :: F1 :: F2 :: F3 :: F4 :: F5 :: F6 :: F7 :: nil.\n\nDefinition int_callee_save_regs :=\n  R4 :: R5 :: R6 :: R7 :: R8 :: R9 :: R10 :: R11 :: nil.\n\nDefinition float_callee_save_regs :=\n  F8 :: F9 :: F10 :: F11 :: F12 :: F13 :: F14 :: F15 :: nil.\n\nDefinition destroyed_at_call :=\n  int_caller_save_regs ++ float_caller_save_regs.\n\nDefinition dummy_int_reg := R0.     (**r Used in [Coloring]. *)\nDefinition dummy_float_reg := F0.   (**r Used in [Coloring]. *)\n\n(** The [index_int_callee_save] and [index_float_callee_save] associate\n  a unique positive integer to callee-save registers.  This integer is\n  used in [Stacking] to determine where to save these registers in\n  the activation record if they are used by the current function. *)\n\nDefinition index_int_callee_save (r: mreg) :=\n  match r with\n  | R4 => 0  | R5 => 1  | R6 => 2  | R7 => 3\n  | R8 => 4  | R9 => 5  | R10 => 6 | R11 => 7\n  | _ => -1\n  end.\n\nDefinition index_float_callee_save (r: mreg) :=\n  match r with\n  | F8 => 0  | F9 => 1  | F10 => 2  | F11 => 3\n  | F12 => 4  | F13 => 5  | F14 => 6  | F15 => 7\n  | _ => -1\n  end.\n\nLtac ElimOrEq :=\n  match goal with\n  |  |- (?x = ?y) \\/ _ -> _ =>\n       let H := fresh in\n       (intro H; elim H; clear H;\n        [intro H; rewrite <- H; clear H | ElimOrEq])\n  |  |- False -> _ =>\n       let H := fresh in (intro H; contradiction)\n  end.\n\nLtac OrEq :=\n  match goal with\n  | |- (?x = ?x) \\/ _ => left; reflexivity\n  | |- (?x = ?y) \\/ _ => right; OrEq\n  | |- False => fail\n  end.\n\nLtac NotOrEq :=\n  match goal with\n  | |- (?x = ?y) \\/ _ -> False =>\n       let H := fresh in (\n       intro H; elim H; clear H; [intro; discriminate | NotOrEq])\n  | |- False -> False =>\n       contradiction\n  end.\n\nLemma index_int_callee_save_pos:\n  forall r, In r int_callee_save_regs -> index_int_callee_save r >= 0.\nProof.\n  intro r. simpl; ElimOrEq; unfold index_int_callee_save; omega.\nQed.\n\nLemma index_float_callee_save_pos:\n  forall r, In r float_callee_save_regs -> index_float_callee_save r >= 0.\nProof.\n  intro r. simpl; ElimOrEq; unfold index_float_callee_save; omega.\nQed.\n\nLemma index_int_callee_save_pos2:\n  forall r, index_int_callee_save r >= 0 -> In r int_callee_save_regs.\nProof.\n  destruct r; simpl; intro; omegaContradiction || OrEq.\nQed.\n\nLemma index_float_callee_save_pos2:\n  forall r, index_float_callee_save r >= 0 -> In r float_callee_save_regs.\nProof.\n  destruct r; simpl; intro; omegaContradiction || OrEq.\nQed.\n\nLemma index_int_callee_save_inj:\n  forall r1 r2,\n  In r1 int_callee_save_regs ->\n  In r2 int_callee_save_regs ->\n  r1 <> r2 ->\n  index_int_callee_save r1 <> index_int_callee_save r2.\nProof.\n  intros r1 r2.\n  simpl; ElimOrEq; ElimOrEq; unfold index_int_callee_save;\n  intros; congruence.\nQed.\n\nLemma index_float_callee_save_inj:\n  forall r1 r2,\n  In r1 float_callee_save_regs ->\n  In r2 float_callee_save_regs ->\n  r1 <> r2 ->\n  index_float_callee_save r1 <> index_float_callee_save r2.\nProof.\n  intros r1 r2.\n  simpl; ElimOrEq; ElimOrEq; unfold index_float_callee_save;\n  intros; congruence.\nQed.\n\n(** The following lemmas show that\n    (temporaries, destroyed at call, integer callee-save, float callee-save)\n    is a partition of the set of machine registers. *)\n\nLemma int_float_callee_save_disjoint:\n  list_disjoint int_callee_save_regs float_callee_save_regs.\nProof.\n  red; intros r1 r2. simpl; ElimOrEq; ElimOrEq; discriminate.\nQed.\n\nLemma register_classification:\n  forall r,\n  In r destroyed_at_call \\/ In r int_callee_save_regs \\/ In r float_callee_save_regs.\nProof.\n  destruct r;\n  try (left; simpl; OrEq);\n  try (right; left; simpl; OrEq);\n  try (right; right; simpl; OrEq).\nQed.\n\n\nLemma int_callee_save_not_destroyed:\n  forall r,\n    In r destroyed_at_call -> In r int_callee_save_regs -> False.\nProof.\n  intros. revert H0 H. simpl. ElimOrEq; NotOrEq.\nQed.\n\nLemma float_callee_save_not_destroyed:\n  forall r,\n    In r destroyed_at_call -> In r float_callee_save_regs -> False.\nProof.\n  intros. revert H0 H. simpl. ElimOrEq; NotOrEq.\nQed.\n\nLemma int_callee_save_type:\n  forall r, In r int_callee_save_regs -> mreg_type r = Tany32.\nProof.\n  intro. simpl; ElimOrEq; reflexivity.\nQed.\n\nLemma float_callee_save_type:\n  forall r, In r float_callee_save_regs -> mreg_type r = Tany64.\nProof.\n  intro. simpl; ElimOrEq; reflexivity.\nQed.\n\nLtac NoRepet :=\n  match goal with\n  | |- list_norepet nil =>\n      apply list_norepet_nil\n  | |- list_norepet (?a :: ?b) =>\n      apply list_norepet_cons; [simpl; intuition discriminate | NoRepet]\n  end.\n\nLemma int_callee_save_norepet:\n  list_norepet int_callee_save_regs.\nProof.\n  unfold int_callee_save_regs; NoRepet.\nQed.\n\nLemma float_callee_save_norepet:\n  list_norepet float_callee_save_regs.\nProof.\n  unfold float_callee_save_regs; NoRepet.\nQed.\n\n(** * Function calling conventions *)\n\n(** The functions in this section determine the locations (machine registers\n  and stack slots) used to communicate arguments and results between the\n  caller and the callee during function calls.  These locations are functions\n  of the signature of the function and of the call instruction.\n  Agreement between the caller and the callee on the locations to use\n  is guaranteed by our dynamic semantics for Cminor and RTL, which demand\n  that the signature of the call instruction is identical to that of the\n  called function.\n\n  Calling conventions are largely arbitrary: they must respect the properties\n  proved in this section (such as no overlapping between the locations\n  of function arguments), but this leaves much liberty in choosing actual\n  locations.  *)\n\n(** ** Location of function result *)\n\n(** The result value of a function is passed back to the caller in\n  registers [R0] or [F0] or [R0,R1], depending on the type of the\n  returned value.  We treat a function without result as a function\n  with one integer result.\n\n  For the \"softfloat\" convention, results of FP types should be passed\n  in [R0] or [R0,R1].  This doesn't fit the CompCert register model,\n  so we have code in [arm/PrintAsm.ml] that inserts additional moves\n  to/from [F0]. *)\n\nDefinition loc_result (s: signature) : list mreg :=\n  match s.(sig_res) with\n  | None => R0 :: nil\n  | Some (Tint | Tany32) => R0 :: nil\n  | Some (Tfloat | Tsingle | Tany64) => F0 :: nil\n  | Some Tlong => R1 :: R0 :: nil\n  end.\n\n(** The result registers have types compatible with that given in the signature. *)\n\nLemma loc_result_type:\n  forall sig,\n  subtype_list (proj_sig_res' sig) (map mreg_type (loc_result sig)) = true.\nProof.\n  intros. unfold proj_sig_res', loc_result. destruct (sig_res sig) as [[]|]; auto.\nQed.\n\n(** The result locations are caller-save registers *)\n\nLemma loc_result_caller_save:\n  forall (s: signature) (r: mreg),\n  In r (loc_result s) -> In r destroyed_at_call.\nProof.\n  intros.\n  assert (r = R0 \\/ r = R1 \\/ r = F0).\n    unfold loc_result in H. destruct (sig_res s); [destruct t|idtac]; simpl in H; intuition.\n  destruct H0 as [A | [A | A]]; subst r; simpl; OrEq.\nQed.\n\n(** ** Location of function arguments *)\n\n(** For the \"hardfloat\" configuration, we use the following calling conventions,\n    adapted from the ARM EABI-HF:\n- The first 4 integer arguments are passed in registers [R0] to [R3].\n- The first 2 long integer arguments are passed in an aligned pair of\n  two integer registers.\n- The first 8 single- and double-precision float arguments are passed\n  in registers [F0...F7]\n- Extra arguments are passed on the stack, in [Outgoing] slots, consecutively\n  assigned (1 word for an integer or single argument, 2 words for a float\n  or a long), starting at word offset 0.\n\nThis convention is not quite that of the ARM EABI-HF, whereas single float\narguments are passed in 32-bit float registers.  Unfortunately,\nthis does not fit the data model of CompCert.  In [PrintAsm.ml]\nwe insert additional code around function calls that moves\ndata appropriately. *)\n\nDefinition int_param_regs :=\n  R0 :: R1 :: R2 :: R3 :: nil.\n\nDefinition float_param_regs :=\n  F0 :: F1 :: F2 :: F3 :: F4 :: F5 :: F6 :: F7 :: nil.\n\nDefinition ireg_param (n: Z) : mreg :=\n  match list_nth_z int_param_regs n with Some r => r | None => R0 end.\n\nDefinition freg_param (n: Z) : mreg :=\n  match list_nth_z float_param_regs n with Some r => r | None => F0 end.\n\nFixpoint loc_arguments_hf\n     (tyl: list typ) (ir fr ofs: Z) {struct tyl} : list loc :=\n  match tyl with\n  | nil => nil\n  | (Tint | Tany32) as ty :: tys =>\n      if zlt ir 4\n      then R (ireg_param ir) :: loc_arguments_hf tys (ir + 1) fr ofs\n      else S Outgoing ofs ty :: loc_arguments_hf tys ir fr (ofs + 1)\n  | (Tfloat | Tany64) as ty :: tys =>\n      if zlt fr 8\n      then R (freg_param fr) :: loc_arguments_hf tys ir (fr + 1) ofs\n      else let ofs := align ofs 2 in\n           S Outgoing ofs ty :: loc_arguments_hf tys ir fr (ofs + 2)\n  | Tsingle :: tys =>\n      if zlt fr 8\n      then R (freg_param fr) :: loc_arguments_hf tys ir (fr + 1) ofs\n      else S Outgoing ofs Tsingle :: loc_arguments_hf tys ir fr (ofs + 1)\n  | Tlong :: tys =>\n      let ir := align ir 2 in\n      if zlt ir 4\n      then R (ireg_param (ir + 1)) :: R (ireg_param ir) :: loc_arguments_hf tys (ir + 2) fr ofs\n      else let ofs := align ofs 2 in\n          S Outgoing (ofs + 1) Tint :: S Outgoing ofs Tint :: loc_arguments_hf tys ir fr (ofs + 2)\n  end.\n\n(** For the \"softfloat\" configuration, as well as for variable-argument functions\n  in the \"hardfloat\" configuration, we use the default ARM EABI (not HF)\n  calling conventions:\n- The first 4 integer arguments are passed in registers [R0] to [R3].\n- The first 2 long integer arguments are passed in an aligned pair of\n  two integer registers.\n- The first 2 double-precision float arguments are passed in [F0] or [F2]\n- The first 4 single-precision float arguments are passed in [F0...F3]\n- Integer arguments and float arguments are kept in sync so that\n  they can all be mapped back to [R0...R3] in [PrintAsm.ml].\n- Extra arguments are passed on the stack, in [Outgoing] slots, consecutively\n  assigned (1 word for an integer or single argument, 2 words for a float\n  or a long), starting at word offset 0.\n\nThis convention is not quite that of the ARM EABI, whereas every float\nargument are passed in one or two integer registers.  Unfortunately,\nthis does not fit the data model of CompCert.  In [PrintAsm.ml]\nwe insert additional code around function calls and returns that moves\ndata appropriately. *)\n\nFixpoint loc_arguments_sf\n     (tyl: list typ) (ofs: Z) {struct tyl} : list loc :=\n  match tyl with\n  | nil => nil\n  | (Tint|Tany32) as ty :: tys =>\n      (if zlt ofs 0 then R (ireg_param (ofs + 4)) else S Outgoing ofs ty)\n      :: loc_arguments_sf tys (ofs + 1)\n  | (Tfloat|Tany64) as ty :: tys =>\n      let ofs := align ofs 2 in\n      (if zlt ofs 0 then R (freg_param (ofs + 4)) else S Outgoing ofs ty)\n      :: loc_arguments_sf tys (ofs + 2)\n  | Tsingle :: tys =>\n      (if zlt ofs 0 then R (freg_param (ofs + 4)) else S Outgoing ofs Tsingle)\n      :: loc_arguments_sf tys (ofs + 1)\n  | Tlong :: tys =>\n      let ofs := align ofs 2 in\n      (if zlt ofs 0 then R (ireg_param (ofs+1+4)) else S Outgoing (ofs+1) Tint)\n      :: (if zlt ofs 0 then R (ireg_param (ofs+4)) else S Outgoing ofs Tint)\n      :: loc_arguments_sf tys (ofs + 2)\n  end.\n\n(** [loc_arguments s] returns the list of locations where to store arguments\n  when calling a function with signature [s].  *)\n\nDefinition loc_arguments (s: signature) : list loc :=\n  match Archi.abi with\n  | Archi.Softfloat =>\n      loc_arguments_sf s.(sig_args) (-4)\n  | Archi.Hardfloat =>\n      if s.(sig_cc).(cc_vararg)\n      then loc_arguments_sf s.(sig_args) (-4)\n      else loc_arguments_hf s.(sig_args) 0 0 0\n  end.\n\n(** [size_arguments s] returns the number of [Outgoing] slots used\n  to call a function with signature [s]. *)\n\nFixpoint size_arguments_hf (tyl: list typ) (ir fr ofs: Z) {struct tyl} : Z :=\n  match tyl with\n  | nil => ofs\n  | (Tint|Tany32) :: tys =>\n      if zlt ir 4\n      then size_arguments_hf tys (ir + 1) fr ofs\n      else size_arguments_hf tys ir fr (ofs + 1)\n  | (Tfloat|Tany64) :: tys =>\n      if zlt fr 8\n      then size_arguments_hf tys ir (fr + 1) ofs\n      else size_arguments_hf tys ir fr (align ofs 2 + 2)\n  | Tsingle :: tys =>\n      if zlt fr 8\n      then size_arguments_hf tys ir (fr + 1) ofs\n      else size_arguments_hf tys ir fr (ofs + 1)\n  | Tlong :: tys =>\n      let ir := align ir 2 in\n      if zlt ir 4\n      then size_arguments_hf tys (ir + 2) fr ofs\n      else size_arguments_hf tys ir fr (align ofs 2 + 2)\n  end.\n\nFixpoint size_arguments_sf (tyl: list typ) (ofs: Z) {struct tyl} : Z :=\n  match tyl with\n  | nil => Zmax 0 ofs\n  | (Tint | Tsingle | Tany32) :: tys => size_arguments_sf tys (ofs + 1)\n  | (Tfloat | Tlong | Tany64) :: tys => size_arguments_sf tys (align ofs 2 + 2)\n  end.\n\nDefinition size_arguments (s: signature) : Z :=\n  match Archi.abi with\n  | Archi.Softfloat =>\n      size_arguments_sf s.(sig_args) (-4)\n  | Archi.Hardfloat =>\n      if s.(sig_cc).(cc_vararg)\n      then size_arguments_sf s.(sig_args) (-4)\n      else size_arguments_hf s.(sig_args) 0 0 0\n  end.\n\n(** Argument locations are either non-temporary registers or [Outgoing]\n  stack slots at nonnegative offsets. *)\n\nDefinition loc_argument_acceptable (l: loc) : Prop :=\n  match l with\n  | R r => In r destroyed_at_call\n  | S Outgoing ofs ty => ofs >= 0 /\\ ty <> Tlong\n  | _ => False\n  end.\n\nRemark ireg_param_in_params: forall n, In (ireg_param n) int_param_regs.\nProof.\n  unfold ireg_param; intros.\n  destruct (list_nth_z int_param_regs n) as [r|] eqn:NTH.\n  eapply list_nth_z_in; eauto.\n  simpl; auto.\nQed.\n\nRemark freg_param_in_params: forall n, In (freg_param n) float_param_regs.\nProof.\n  unfold freg_param; intros.\n  destruct (list_nth_z float_param_regs n) as [r|] eqn:NTH.\n  eapply list_nth_z_in; eauto.\n  simpl; auto.\nQed.\n\nRemark loc_arguments_hf_charact:\n  forall tyl ir fr ofs l,\n  In l (loc_arguments_hf tyl ir fr ofs) ->\n  match l with\n  | R r => In r int_param_regs \\/ In r float_param_regs\n  | S Outgoing ofs' ty => ofs' >= ofs /\\ ty <> Tlong\n  | S _ _ _ => False\n  end.\nProof.\n  assert (INCR: forall l ofs1 ofs2,\n            match l with\n            | R r => In r int_param_regs \\/ In r float_param_regs\n            | S Outgoing ofs' ty => ofs' >= ofs2 /\\ ty <> Tlong\n            | S _ _ _ => False\n            end ->\n            ofs1 <= ofs2 ->\n            match l with\n            | R r => In r int_param_regs \\/ In r float_param_regs\n            | S Outgoing ofs' ty => ofs' >= ofs1 /\\ ty <> Tlong\n            | S _ _ _ => False\n            end).\n  {\n    intros. destruct l; auto. destruct sl; auto. intuition omega.\n  }\n  induction tyl; simpl loc_arguments_hf; intros.\n  elim H.\n  destruct a.\n- (* int *)\n  destruct (zlt ir 4); destruct H.\n  subst. left; apply ireg_param_in_params.\n  eapply IHtyl; eauto.\n  subst. split; [omega | congruence].\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* float *)\n  destruct (zlt fr 8); destruct H.\n  subst. right; apply freg_param_in_params.\n  eapply IHtyl; eauto.\n  subst. split. apply Zle_ge. apply align_le. omega. congruence.\n  eapply INCR. eapply IHtyl; eauto.\n  apply Zle_trans with (align ofs 2). apply align_le; omega. omega.\n- (* long *)\n  set (ir' := align ir 2) in *.\n  assert (ofs <= align ofs 2) by (apply align_le; omega).\n  destruct (zlt ir' 4).\n  destruct H. subst l; left; apply ireg_param_in_params.\n  destruct H. subst l; left; apply ireg_param_in_params.\n  eapply IHtyl; eauto.\n  destruct H. subst l; split; [ omega | congruence ].\n  destruct H. subst l; split; [ omega | congruence ].\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* single *)\n  destruct (zlt fr 8); destruct H.\n  subst. right; apply freg_param_in_params.\n  eapply IHtyl; eauto.\n  subst. split; [omega | congruence].\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* any32 *)\n  destruct (zlt ir 4); destruct H.\n  subst. left; apply ireg_param_in_params.\n  eapply IHtyl; eauto.\n  subst. split; [omega | congruence].\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* any64 *)\n  destruct (zlt fr 8); destruct H.\n  subst. right; apply freg_param_in_params.\n  eapply IHtyl; eauto.\n  subst. split. apply Zle_ge. apply align_le. omega. congruence.\n  eapply INCR. eapply IHtyl; eauto.\n  apply Zle_trans with (align ofs 2). apply align_le; omega. omega.\nQed.\n\nRemark loc_arguments_sf_charact:\n  forall tyl ofs l,\n  In l (loc_arguments_sf tyl ofs) ->\n  match l with\n  | R r => In r int_param_regs \\/ In r float_param_regs\n  | S Outgoing ofs' ty => ofs' >= Zmax 0 ofs /\\ ty <> Tlong\n  | S _ _ _ => False\n  end.\nProof.\n  assert (INCR: forall l ofs1 ofs2,\n            match l with\n            | R r => In r int_param_regs \\/ In r float_param_regs\n            | S Outgoing ofs' ty => ofs' >= Zmax 0 ofs2 /\\ ty <> Tlong\n            | S _ _ _ => False\n            end ->\n            ofs1 <= ofs2 ->\n            match l with\n            | R r => In r int_param_regs \\/ In r float_param_regs\n            | S Outgoing ofs' ty => ofs' >= Zmax 0 ofs1 /\\ ty <> Tlong\n            | S _ _ _ => False\n            end).\n  {\n    intros. destruct l; auto. destruct sl; auto. intuition xomega.\n  }\n  induction tyl; simpl loc_arguments_sf; intros.\n  elim H.\n  destruct a.\n- (* int *)\n  destruct H.\n  destruct (zlt ofs 0); subst l.\n  left; apply ireg_param_in_params.\n  split. xomega. congruence.\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* float *)\n  set (ofs' := align ofs 2) in *.\n  assert (ofs <= ofs') by (apply align_le; omega).\n  destruct H.\n  destruct (zlt ofs' 0); subst l.\n  right; apply freg_param_in_params.\n  split. xomega. congruence.\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* long *)\n  set (ofs' := align ofs 2) in *.\n  assert (ofs <= ofs') by (apply align_le; omega).\n  destruct H.\n  destruct (zlt ofs' 0); subst l.\n  left; apply ireg_param_in_params.\n  split. xomega. congruence.\n  destruct H.\n  destruct (zlt ofs' 0); subst l.\n  left; apply ireg_param_in_params.\n  split. xomega. congruence.\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* single *)\n  destruct H.\n  destruct (zlt ofs 0); subst l.\n  right; apply freg_param_in_params.\n  split. xomega. congruence.\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* any32 *)\n  destruct H.\n  destruct (zlt ofs 0); subst l.\n  left; apply ireg_param_in_params.\n  split. xomega. congruence.\n  eapply INCR. eapply IHtyl; eauto. omega.\n- (* any64 *)\n  set (ofs' := align ofs 2) in *.\n  assert (ofs <= ofs') by (apply align_le; omega).\n  destruct H.\n  destruct (zlt ofs' 0); subst l.\n  right; apply freg_param_in_params.\n  split. xomega. congruence.\n  eapply INCR. eapply IHtyl; eauto. omega.\nQed.\n\nLemma loc_arguments_acceptable:\n  forall (s: signature) (l: loc),\n  In l (loc_arguments s) -> loc_argument_acceptable l.\nProof.\n  unfold loc_arguments; intros.\n  assert (forall r, In r int_param_regs \\/ In r float_param_regs -> In r destroyed_at_call).\n  {\n    intros. elim H0; simpl; ElimOrEq; OrEq.\n  }\n  assert (In l (loc_arguments_sf (sig_args s) (-4)) -> loc_argument_acceptable l).\n  { intros. red. exploit loc_arguments_sf_charact; eauto. destruct l; auto. }\n  assert (In l (loc_arguments_hf (sig_args s) 0 0 0) -> loc_argument_acceptable l).\n  { intros. red. exploit loc_arguments_hf_charact; eauto. destruct l; auto. }\n  destruct Archi.abi; [ | destruct (cc_vararg (sig_cc s)) ]; auto.\nQed.\n\nHint Resolve loc_arguments_acceptable: locs.\n\n(** The offsets of [Outgoing] arguments are below [size_arguments s]. *)\n\nRemark size_arguments_hf_above:\n  forall tyl ir fr ofs0,\n  ofs0 <= size_arguments_hf tyl ir fr ofs0.\nProof.\n  induction tyl; simpl; intros.\n  omega.\n  destruct a.\n  destruct (zlt ir 4); eauto. apply Zle_trans with (ofs0 + 1); auto; omega.\n  destruct (zlt fr 8); eauto.\n  apply Zle_trans with (align ofs0 2). apply align_le; omega.\n  apply Zle_trans with (align ofs0 2 + 2); auto; omega.\n  set (ir' := align ir 2).\n  destruct (zlt ir' 4); eauto.\n  apply Zle_trans with (align ofs0 2). apply align_le; omega.\n  apply Zle_trans with (align ofs0 2 + 2); auto; omega.\n  destruct (zlt fr 8); eauto.\n  apply Zle_trans with (ofs0 + 1); eauto. omega.\n  destruct (zlt ir 4); eauto. apply Zle_trans with (ofs0 + 1); auto; omega.\n  destruct (zlt fr 8); eauto.\n  apply Zle_trans with (align ofs0 2). apply align_le; omega.\n  apply Zle_trans with (align ofs0 2 + 2); auto; omega.\nQed.\n\nRemark size_arguments_sf_above:\n  forall tyl ofs0,\n  Zmax 0 ofs0 <= size_arguments_sf tyl ofs0.\nProof.\n  induction tyl; simpl; intros.\n  omega.\n  destruct a; (eapply Zle_trans; [idtac|eauto]).\n  xomega.\n  assert (ofs0 <= align ofs0 2) by (apply align_le; omega). xomega.\n  assert (ofs0 <= align ofs0 2) by (apply align_le; omega). xomega.\n  xomega.\n  xomega.\n  assert (ofs0 <= align ofs0 2) by (apply align_le; omega). xomega.\nQed.\n\nLemma size_arguments_above:\n  forall s, size_arguments s >= 0.\nProof.\n  intros; unfold size_arguments. apply Zle_ge.\n  assert (0 <= size_arguments_sf (sig_args s) (-4)).\n  { change 0 with (Zmax 0 (-4)). apply size_arguments_sf_above. }\n  assert (0 <= size_arguments_hf (sig_args s) 0 0 0).\n  { apply size_arguments_hf_above. }\n  destruct Archi.abi; [ | destruct (cc_vararg (sig_cc s)) ]; auto.\nQed.\n\nLemma loc_arguments_hf_bounded:\n  forall ofs ty tyl ir fr ofs0,\n  In (S Outgoing ofs ty) (loc_arguments_hf tyl ir fr ofs0) ->\n  ofs + typesize ty <= size_arguments_hf tyl ir fr ofs0.\nProof.\n  induction tyl; simpl; intros.\n  elim H.\n  destruct a.\n- (* int *)\n  destruct (zlt ir 4); destruct H.\n  discriminate.\n  eauto.\n  inv H. apply size_arguments_hf_above.\n  eauto.\n- (* float *)\n  destruct (zlt fr 8); destruct H.\n  discriminate.\n  eauto.\n  inv H. apply size_arguments_hf_above.\n  eauto.\n- (* long *)\n  destruct (zlt (align ir 2) 4).\n  destruct H. discriminate. destruct H. discriminate. eauto.\n  destruct H. inv H.\n  rewrite <- Zplus_assoc. simpl. apply size_arguments_hf_above.\n  destruct H. inv H.\n  eapply Zle_trans. 2: apply size_arguments_hf_above. simpl; omega.\n  eauto.\n- (* float *)\n  destruct (zlt fr 8); destruct H.\n  discriminate.\n  eauto.\n  inv H. apply size_arguments_hf_above.\n  eauto.\n- (* any32 *)\n  destruct (zlt ir 4); destruct H.\n  discriminate.\n  eauto.\n  inv H. apply size_arguments_hf_above.\n  eauto.\n- (* any64 *)\n  destruct (zlt fr 8); destruct H.\n  discriminate.\n  eauto.\n  inv H. apply size_arguments_hf_above.\n  eauto.\nQed.\n\nLemma loc_arguments_sf_bounded:\n  forall ofs ty tyl ofs0,\n  In (S Outgoing ofs ty) (loc_arguments_sf tyl ofs0) ->\n  Zmax 0 (ofs + typesize ty) <= size_arguments_sf tyl ofs0.\nProof.\n  induction tyl; simpl; intros.\n  elim H.\n  destruct a.\n- (* int *)\n  destruct H.\n  destruct (zlt ofs0 0); inv H. apply size_arguments_sf_above.\n  eauto.\n- (* float *)\n  destruct H.\n  destruct (zlt (align ofs0 2) 0); inv H. apply size_arguments_sf_above.\n  eauto.\n- (* long *)\n  destruct H.\n  destruct (zlt (align ofs0 2) 0); inv H.\n  rewrite <- Zplus_assoc. simpl. apply size_arguments_sf_above.\n  destruct H.\n  destruct (zlt (align ofs0 2) 0); inv H.\n  eapply Zle_trans. 2: apply size_arguments_sf_above. simpl; xomega.\n  eauto.\n- (* float *)\n  destruct H.\n  destruct (zlt ofs0 0); inv H. apply size_arguments_sf_above.\n  eauto.\n- (* any32 *)\n  destruct H.\n  destruct (zlt ofs0 0); inv H. apply size_arguments_sf_above.\n  eauto.\n- (* any64 *)\n  destruct H.\n  destruct (zlt (align ofs0 2) 0); inv H. apply size_arguments_sf_above.\n  eauto.\nQed.\n\nLemma loc_arguments_bounded:\n  forall (s: signature) (ofs: Z) (ty: typ),\n  In (S Outgoing ofs ty) (loc_arguments s) ->\n  ofs + typesize ty <= size_arguments s.\nProof.\n  unfold loc_arguments, size_arguments; intros.\n  assert (In (S Outgoing ofs ty) (loc_arguments_sf (sig_args s) (-4)) ->\n          ofs + typesize ty <= size_arguments_sf (sig_args s) (-4)).\n  { intros. eapply Zle_trans. 2: eapply loc_arguments_sf_bounded; eauto. xomega. }\n  assert (In (S Outgoing ofs ty) (loc_arguments_hf (sig_args s) 0 0 0) ->\n          ofs + typesize ty <= size_arguments_hf (sig_args s) 0 0 0).\n  { intros. eapply loc_arguments_hf_bounded; eauto. }\n  destruct Archi.abi; [ | destruct (cc_vararg (sig_cc s)) ]; eauto.\nQed.\n\nLemma loc_arguments_main:\n  loc_arguments signature_main = nil.\nProof.\n  unfold loc_arguments.\n  destruct Archi.abi; reflexivity.\nQed.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/compcert/arm/Conventions1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21602354846075858}}
{"text": "From Coq Require Import ZArith.\nFrom stdpp Require Import base gmap list.\nFrom iris.heap_lang Require Export locations.\nFrom melocoton Require Import stdpp_extra language_commons.\nFrom melocoton.c_interface Require Import defs.\nFrom melocoton.ml_lang Require Import lang.\n\n(* the type of memory addresses used by the C semantics *)\nNotation addr := iris.heap_lang.locations.loc (only parsing).\n(* We call \"mem\" a C memory and \"word\" a C value. *)\nNotation memory := (gmap loc heap_cell).\nNotation word := C_intf.val.\n(* We call \"store\" an ML memory and \"val\" an ML value. *)\nNotation store := (gmap loc (option (list val))).\nNotation val := ML_lang.val.\n\n(************\n   Block-level \"logival\" values and store.\n\n   Block-level values and store exist as an intermediate abstraction that helps\n   bridging the gap between ML memory/values and C memory/values.\n\n   These block-level values and store are part of the wrapper private state, and\n   help specify many of the \"runtime invariants\" modeled by the wrapper.\n\n   Indeed, most runtime/GC invariants make the most sense when expressed at the\n   level of this abstract block layer.\n*)\n\n(* The idea is that a block-level value is either an immediate integer, or a\n   reference to a block in the block-level store. A block then stores an array\n   of block-level values.\n\n   The block-level store contains blocks that can be either mutable or\n   immutable, and always stay at the same location. In fact, the block-level\n   store monotonically grows: blocks are never deallocated at that level.\n\n   NB: this means that blocks in the block-level store represent both mutable ML\n   values (e.g. references, arrays) that are already \"heap-allocated\" in the ML\n   semantics, but also *immutable values* (e.g. pairs) that are not\n   heap-allocated in ML semantics, but are given an identity (a location) in the\n   block-level layer.\n*)\n\n(* locations in the block-level store *)\nNotation lloc := nat (only parsing).\nImplicit Type γ : lloc.\n\n(* block-level values *)\nInductive lval :=\n  | Lint : Z → lval\n  | Lloc : lloc → lval.\n\n(* Currently the mutability tag applies to a whole block; but ultimately we want\n   each field of the block to have its [ismut] tag (to handle record types of\n   the form { foo : int; mutable bar : int }) *)\nInductive ismut := Mut | Immut.\n\n(* Possible tags for \"value blocks\", i.e. blocks that contain ML values. *)\n(* Right now the tag is only used to distinguish between InjLV and InjRV (the\n   constructors of the basic sum-type). In the future we might want to expand\n   this to handle richer kinds of values (e.g. richer sum types). *)\nInductive vblock_tag :=\n  | TagDefault (* the default tag, used for InjLV and other blocks (pairs, refs, arrays) *)\n  | TagInjRV. (* the tag for InjRV *)\n\n(* Possible tags for blocks in the general case. *)\nInductive tag : Type :=\n  | TagVblock (vtg : vblock_tag)\n  | TagClosure\n  | TagForeign.\n\nDefinition vblock_tag_as_int (vtg : vblock_tag) : Z :=\n  match vtg with\n  | TagDefault => 0\n  | TagInjRV => 1\n  end.\n\nDefinition tag_as_int (tg : tag) : Z :=\n  match tg with\n  | TagVblock vtg => vblock_tag_as_int vtg\n  | TagClosure => 247\n  | TagForeign => 255\n  end.\n\nGlobal Instance vblock_tag_as_int_inj : Inj (=) (=) vblock_tag_as_int.\nProof using.\n  intros t t'. destruct t; destruct t'; by inversion 1.\nQed.\n\nGlobal Instance tag_as_int_inj : Inj (=) (=) tag_as_int.\nProof using.\n  intros t t'.\n  destruct t as [vt| |]; destruct t' as [vt'| |];\n    try destruct vt; try destruct vt';\n    by inversion 1.\nQed.\n\n(* a \"value block\" (the most common type of block) *)\nNotation vblock :=\n  (ismut * (vblock_tag * list lval))%type.\n\n(* a block in the block-level store *)\nInductive block :=\n  | Bvblock (vblk : vblock)\n  | Bclosure (clos_f clos_x : binder) (clos_body : ML_lang.expr)\n  (* A limited form of OCaml's \"custom blocks\", storing a C value *)\n  | Bforeign (ptr : option C_intf.val).\n\nDefinition vblock_mutability (vb: vblock) : ismut :=\n  let '(i,_) := vb in i.\n\nDefinition mutability (b: block) : ismut :=\n  match b with\n  | Bvblock vblk => vblock_mutability vblk\n  | Bclosure _ _ _ => Immut\n  | Bforeign _ => Mut\n  end.\n\nInductive lval_in_block : block → lval → Prop :=\n  | ValInVblock v m tg vs :\n    v ∈ vs → lval_in_block (Bvblock (m, (tg, vs))) v.\n\n(* a block-level store *)\nNotation lstore := (gmap lloc block).\nImplicit Type ζ : lstore.\n\n\n(************\n   In order to tie the logical block-level store to the ML and C stores, the\n   wrapper maintains a map that relates block-level locations to ML locations,\n   and a map that relates block-level locations with C values. *)\n\n(* For each block-level location, we track whether it correspond to a ML-level\n   location ℓ (case [LlocPublic ℓ]), or whether it only exists in the\n   block-level heap (case [LlocPrivate]). *)\nInductive lloc_visibility :=\n  | LlocPublic (ℓ : loc)\n  | LlocForeign (id : nat)\n  | LlocPrivate.\n\n(* An [lloc_map] maps a block location to its visibility status *)\nNotation lloc_map := (gmap lloc lloc_visibility).\nImplicit Type χ : lloc_map.\n\n(* An [addr_map] maps a block location to its \"current\" C address.\n   Note: since blocks do not move around in the logical store, even though they\n   *are* moved around by the GC in the actual memory, this means that \"the\n   current θ\" will often arbitrarily change during the execution, each time a GC\n   might occur. *)\nNotation addr_map := (gmap lloc addr).\nImplicit Type θ : addr_map.\n\n(* maps each root (a heap cell in C memory) to the logical value it is tracking\n   and keeping alive *)\nNotation roots_map := (gmap addr lval).\n\n\n(*************\n   lloc_map injectivity: lloc_maps are always injective wrt public locs and\n   foreign ids\n*)\n\nDefinition lloc_map_inj χ :=\n  ∀ γ1 γ2 vis,\n    χ !! γ1 = Some vis →\n    χ !! γ2 = Some vis →\n    vis ≠ LlocPrivate →\n    γ1 = γ2.\n\n(************\n   Block-level state changes.\n\n   These relations define various transitions that might need to happen on the\n   logical store; these are used to define the wrapper semantics.\n*)\n\n(* freezing: turning a mutable block into an immutable block. (This is typically\n   only legal as long as the mutable block has not been \"observable\" by other\n   code than the wrapper..) *)\nInductive freeze_block : block → block → Prop :=\n  | freeze_block_mut tgvs m' :\n    freeze_block (Bvblock (Mut, tgvs)) (Bvblock (m', tgvs))\n  | freeze_block_refl b :\n    freeze_block b b.\n\nDefinition freeze_lstore (ζ1 ζ2 : lstore) : Prop :=\n  dom ζ1 = dom ζ2 ∧\n  (∀ γ b1 b2, ζ1 !! γ = Some b1 → ζ2 !! γ = Some b2 → freeze_block b1 b2).\n\nInductive expose_lloc : lloc_visibility → lloc_visibility → Prop :=\n  | expose_lloc_private ℓ : expose_lloc LlocPrivate (LlocPublic ℓ)\n  | expose_lloc_refl vis : expose_lloc vis vis.\n\nDefinition expose_llocs (χ1 χ2 : lloc_map) : Prop :=\n  dom χ1 = dom χ2 ∧\n  lloc_map_inj χ2 ∧\n  (∀ γ vis1 vis2, χ1 !! γ = Some vis1 → χ2 !! γ = Some vis2 → expose_lloc vis1 vis2).\n\nDefinition is_store_blocks (χ : lloc_map) (σ : store) (ζ : lstore) : Prop :=\n  (∀ ℓ, ℓ ∈ dom σ → ∃ γ, χ !! γ = Some (LlocPublic ℓ)) ∧\n  (∀ γ, γ ∈ dom ζ ↔ ∃ ℓ Vs, χ !! γ = Some (LlocPublic ℓ) ∧ σ !! ℓ = Some (Some Vs)).\n\nDefinition is_private_blocks (χ : lloc_map) (ζ : lstore) : Prop :=\n  ∀ γ, γ ∈ dom ζ → χ !! γ = Some LlocPrivate.\n\n(* An lloc_map χ maintains a monotonically growing correspondance between ML\n   locations and block-level locations. When crossing a wrapper boundary, χ\n   typically needs to be extended to account for allocation of new blocks on\n   either side.\n\n   Additionally, we enforce here that the new χ2 must be injective. (Typically,\n   we already know that χ1 is injective, and we are trying to impose constraints\n   on χ2.) *)\nDefinition lloc_map_mono (χ1 χ2 : lloc_map) : Prop :=\n  χ1 ⊆ χ2 ∧ lloc_map_inj χ2.\n\n(* Helper relation to modify the contents of a block at a given index (which has\n   to be in the bounds). Used to define the semantics of the \"modify\" primitive.\n*)\nInductive modify_block : block → nat → lval → block → Prop :=\n  | mk_modify_block tg vs i v :\n    i < length vs →\n    modify_block (Bvblock (Mut, (tg, vs))) i v (Bvblock (Mut, (tg, (<[ i := v ]> vs)))).\n\n(* \"GC correctness\": a sanity condition when picking a fresh addr_map that\n   assigns C-level identifiers to the subset of \"currently live\" block-level\n   locations.\n\n   If a block is live in memory (its block-level location γ is in θ), then all\n   the locations it points to are also live. By transitivity, all blocks\n   reachable from live blocks are also live.\n\n   (+ administrative side-conditions: θ must be injective and map locations that\n   exist in ζ) *)\nDefinition GC_correct (ζ : lstore) (θ : addr_map) : Prop :=\n  gmap_inj θ ∧\n  ∀ γ blk γ',\n    γ ∈ dom θ →\n    ζ !! γ = Some blk →\n    lval_in_block blk (Lloc γ') →\n    γ' ∈ dom θ.\n\nDefinition roots_are_live (θ : addr_map) (roots : roots_map) : Prop :=\n  ∀ a γ, roots !! a = Some (Lloc γ) → γ ∈ dom θ.\n\n(* C representation of block-level values, roots and memory *)\n\nDefinition code_int (z:Z) : word := (C_intf.LitV (C_intf.LitInt (2*z + 1))).\n\nInductive repr_lval : addr_map → lval → C_intf.val → Prop :=\n  | repr_lint θ x :\n    repr_lval θ (Lint x) (code_int x)\n  | repr_lloc θ γ a :\n    θ !! γ = Some a →\n    repr_lval θ (Lloc γ) (C_intf.LitV (C_intf.LitLoc a)).\n\nInductive repr_roots : addr_map → roots_map → memory → Prop :=\n  | repr_roots_emp θ :\n    repr_roots θ ∅ ∅\n  | repr_roots_elem θ a v w roots mem :\n    repr_roots θ roots mem →\n    repr_lval θ v w →\n    a ∉ dom roots →\n    a ∉ dom (mem) →\n    repr_roots θ (<[ a := v ]> roots)\n                 (<[ a := Storing w ]> mem).\n\n\nDefinition repr_raw (θ : addr_map) (roots : roots_map) (privmem mem memr : memory) : Prop :=\n  repr_roots θ roots memr ∧\n  privmem ##ₘ memr ∧\n  mem = memr ∪ privmem.\n\nDefinition repr (θ : addr_map) (roots : roots_map) (privmem mem : memory) : Prop :=\n  ∃ memr, repr_raw θ roots privmem mem memr.\n\n\n(* Block-level representation of ML values and store *)\nInductive is_val : lloc_map → lstore → val → lval → Prop :=\n  (* non-loc base literals *)\n  | is_val_int χ ζ x :\n    is_val χ ζ (ML_lang.LitV (ML_lang.LitInt x)) (Lint x)\n  | is_val_bool χ ζ b :\n    is_val χ ζ (ML_lang.LitV (ML_lang.LitBool b)) (Lint (if b then 1 else 0))\n  | is_val_unit χ ζ :\n    is_val χ ζ (ML_lang.LitV ML_lang.LitUnit) (Lint 0)\n  (* locations *)\n  | is_val_loc χ ζ ℓ γ :\n    χ !! γ = Some (LlocPublic ℓ) →\n    is_val χ ζ (ML_lang.LitV (ML_lang.LitLoc ℓ)) (Lloc γ)\n  (* pairs *)\n  | is_val_pair χ ζ v1 v2 γ lv1 lv2 :\n    ζ !! γ = Some (Bvblock (Immut, (TagDefault, [lv1; lv2]))) →\n    is_val χ ζ v1 lv1 →\n    is_val χ ζ v2 lv2 →\n    is_val χ ζ (ML_lang.PairV v1 v2) (Lloc γ)\n  (* sum-type constructors *)\n  | is_val_injl χ ζ v lv γ :\n    ζ !! γ = Some (Bvblock (Immut, (TagDefault, [lv]))) →\n    is_val χ ζ v lv →\n    is_val χ ζ (ML_lang.InjLV v) (Lloc γ)\n  | is_val_injr χ ζ v lv γ :\n    ζ !! γ = Some (Bvblock (Immut, (TagInjRV, [lv]))) →\n    is_val χ ζ v lv →\n    is_val χ ζ (ML_lang.InjRV v) (Lloc γ)\n  (* closures *)\n  | is_val_closure χ ζ γ f x e :\n    ζ !! γ = Some (Bclosure f x e) →\n    is_val χ ζ (ML_lang.RecV f x e) (Lloc γ)\n  (* foreign blocks *)\n  | is_val_foreign χ ζ γ id :\n    χ !! γ = Some (LlocForeign id) →\n    is_val χ ζ (ML_lang.LitV (ML_lang.LitForeign id)) (Lloc γ).\n\n(* Elements of the ML store are lists of values representing refs and arrays;\n   they correspond to a mutable block with the default tag. *)\nInductive is_heap_elt (χ : lloc_map) (ζ : lstore) : list val → block → Prop :=\n| is_heap_elt_block vs lvs :\n  Forall2 (is_val χ ζ) vs lvs →\n  is_heap_elt χ ζ vs (Bvblock (Mut, (TagDefault, lvs))).\n\nDefinition is_store (χ : lloc_map) (ζ : lstore) (σ : store) : Prop :=\n  ∀ ℓ vs γ blk,\n    σ !! ℓ = Some (Some vs) → χ !! γ = Some (LlocPublic ℓ) → ζ !! γ = Some blk →\n    is_heap_elt χ ζ vs blk.\n\n\n(******************************************************************************)\n(* auxiliary definitions and lemmas *)\n\n(******************************************************************************)\n(* auxiliary definitions and lemmas *)\n\nGlobal Hint Resolve freeze_block_refl : core.\nGlobal Hint Resolve expose_lloc_refl : core.\n\nGlobal Instance ismut_eqdecision : EqDecision ismut.\nProof. intros [] []; solve_decision. Qed.\n\nGlobal Instance lloc_visibility_eqdecision : EqDecision lloc_visibility.\nProof. intros [] []; solve_decision. Qed.\n\nDefinition lloc_map_pubs (χ : lloc_map) : gmap lloc loc :=\n  omap (λ vis, match vis with LlocPublic ℓ => Some ℓ | _ => None end) χ.\n\nDefinition lloc_map_foreign (χ : lloc_map) : gmap lloc nat :=\n  omap (λ vis, match vis with LlocForeign id => Some id | _ => None end) χ.\n\nDefinition lloc_map_pub_locs (χ : lloc_map) : gset loc :=\n  list_to_set ((map_to_list (lloc_map_pubs χ)).*2).\n\nDefinition pub_locs_in_lstore (χ : lloc_map) (ζ : lstore) : gmap lloc loc :=\n  filter (λ '(γ, _), γ ∈ dom ζ) (lloc_map_pubs χ).\n\nDefinition lstore_immut_blocks (ζ : lstore) : lstore :=\n  filter (λ '(_, bb), mutability bb = Immut) ζ.\n\nLemma lloc_map_pubs_empty : lloc_map_pubs ∅ = ∅.\nProof. rewrite /lloc_map_pubs omap_empty //. Qed.\n\nLemma lloc_map_pubs_lookup_Some χ γ ℓ :\n  lloc_map_pubs χ !! γ = Some ℓ ↔ χ !! γ = Some (LlocPublic ℓ).\nProof.\n  rewrite /lloc_map_pubs lookup_omap.\n  destruct (χ !! γ) as [[]|]; naive_solver.\nQed.\n\nLemma lloc_map_pubs_lookup_Some_1 χ γ ℓ :\n  lloc_map_pubs χ !! γ = Some ℓ → χ !! γ = Some (LlocPublic ℓ).\nProof. apply lloc_map_pubs_lookup_Some. Qed.\nGlobal Hint Resolve lloc_map_pubs_lookup_Some_1 : core.\n\nLemma lloc_map_pubs_lookup_Some_2 χ γ ℓ :\n  χ !! γ = Some (LlocPublic ℓ) → lloc_map_pubs χ !! γ = Some ℓ.\nProof. apply lloc_map_pubs_lookup_Some. Qed.\nGlobal Hint Resolve lloc_map_pubs_lookup_Some_2 : core.\n\nLemma lloc_map_pubs_lookup_None χ γ :\n  lloc_map_pubs χ !! γ = None ↔\n  χ !! γ = None ∨\n  χ !! γ = Some LlocPrivate ∨\n  ∃ id, χ !! γ = Some (LlocForeign id).\nProof.\n  rewrite /lloc_map_pubs lookup_omap.\n  destruct (χ !! γ) as [[]|]; naive_solver.\nQed.\n\nLemma lloc_map_pubs_insert_pub χ γ ℓ :\n  lloc_map_pubs (<[γ:=LlocPublic ℓ]> χ) = <[γ:=ℓ]> (lloc_map_pubs χ).\nProof. rewrite /lloc_map_pubs omap_insert //. Qed.\n\nLemma lloc_map_pubs_insert_priv χ γ :\n  lloc_map_pubs (<[γ:=LlocPrivate]> χ) = delete γ (lloc_map_pubs χ).\nProof. rewrite /lloc_map_pubs omap_insert //. Qed.\n\nLemma lloc_map_pubs_insert_foreign χ γ id :\n  lloc_map_pubs (<[γ:=LlocForeign id]> χ) = delete γ (lloc_map_pubs χ).\nProof. rewrite /lloc_map_pubs omap_insert //. Qed.\n\nLemma elem_of_lloc_map_pub_locs ℓ χ :\n  ℓ ∈ lloc_map_pub_locs χ ↔ ∃ γ, χ !! γ = Some (LlocPublic ℓ).\nProof.\n  rewrite elem_of_list_to_set elem_of_list_fmap.\n  split; [intros ([? ?] & -> & HH) | intros (? & ?)].\n  { rewrite elem_of_map_to_list in HH. eauto. }\n  { eexists (_, _). cbn. split; eauto. rewrite elem_of_map_to_list. eauto. }\nQed.\n\nLemma elem_of_lloc_map_pub_locs_1 ℓ γ χ :\n  χ !! γ = Some (LlocPublic ℓ) → ℓ ∈ lloc_map_pub_locs χ.\nProof. intros HH. apply elem_of_lloc_map_pub_locs. eauto. Qed.\nGlobal Hint Resolve elem_of_lloc_map_pub_locs_1 : core.\n\nLemma lloc_map_foreign_lookup_Some χ γ id :\n  lloc_map_foreign χ !! γ = Some id ↔ χ !! γ = Some (LlocForeign id).\nProof.\n  rewrite /lloc_map_foreign lookup_omap.\n  destruct (χ !! γ) as [[]|]; naive_solver.\nQed.\n\nLemma lloc_map_foreign_lookup_Some_1 χ γ id :\n  lloc_map_foreign χ !! γ = Some id → χ !! γ = Some (LlocForeign id).\nProof. apply lloc_map_foreign_lookup_Some. Qed.\nGlobal Hint Resolve lloc_map_foreign_lookup_Some_1 : core.\n\nLemma lloc_map_foreign_lookup_Some_2 χ γ ℓ :\n  χ !! γ = Some (LlocForeign ℓ) → lloc_map_foreign χ !! γ = Some ℓ.\nProof. apply lloc_map_foreign_lookup_Some. Qed.\nGlobal Hint Resolve lloc_map_foreign_lookup_Some_2 : core.\n\nLemma lloc_map_foreign_insert_pub χ γ ℓ :\n  lloc_map_foreign (<[γ:=LlocPublic ℓ]> χ) = delete γ (lloc_map_foreign χ).\nProof. rewrite /lloc_map_foreign omap_insert //. Qed.\n\nLemma lloc_map_foreign_insert_priv χ γ :\n  lloc_map_foreign (<[γ:=LlocPrivate]> χ) = delete γ (lloc_map_foreign χ).\nProof. rewrite /lloc_map_foreign omap_insert //. Qed.\n\nLemma lloc_map_foreign_insert_foreign χ γ id :\n  lloc_map_foreign (<[γ:=LlocForeign id]> χ) = <[γ := id]> (lloc_map_foreign χ).\nProof. rewrite /lloc_map_foreign omap_insert //. Qed.\n\nLemma pub_locs_in_lstore_empty :\n  pub_locs_in_lstore ∅ ∅ = ∅.\nProof. rewrite /pub_locs_in_lstore lloc_map_pubs_empty //. Qed.\n\nLemma pub_locs_in_lstore_lookup χ ζ γ ℓ :\n  γ ∈ dom ζ\n→ χ !! γ = Some (LlocPublic ℓ)\n→ pub_locs_in_lstore χ ζ !! γ = Some ℓ.\nProof.\n  intros H1 H2. unfold pub_locs_in_lstore.\n  erewrite map_filter_lookup_Some_2. 3: done. 1: done.\n  erewrite lloc_map_pubs_lookup_Some_2; done.\nQed.\n\nLemma pub_locs_in_lstore_lookup_notin χ ζ γ :\n  ζ !! γ = None →\n  pub_locs_in_lstore χ ζ !! γ = None.\nProof.\n  intros Hnotin. apply map_filter_lookup_None. right.\n  intros ? ?%lloc_map_pubs_lookup_Some ?.\n  by apply not_elem_of_dom_2 in Hnotin.\nQed.\nGlobal Hint Resolve pub_locs_in_lstore_lookup_notin : core.\n\nLemma pub_locs_in_lstore_insert_lstore_pub χ ζ γ ℓ blk :\n  χ !! γ = Some (LlocPublic ℓ) →\n  pub_locs_in_lstore χ (<[γ:=blk]> ζ) = <[γ:=ℓ]> (pub_locs_in_lstore χ ζ).\nProof.\n  intros Hγ. rewrite /pub_locs_in_lstore dom_insert_L. eapply map_eq.\n  intros γ'. destruct (decide (γ = γ')) as [<-|].\n  { rewrite lookup_insert. apply map_filter_lookup_Some.\n    rewrite lloc_map_pubs_lookup_Some. set_solver. }\n  rewrite lookup_insert_ne//. rewrite !map_filter_lookup.\n  destruct (lloc_map_pubs χ !! γ'); eauto; cbn.\n  apply option_guard_iff. set_solver.\nQed.\n\nLemma pub_locs_in_lstore_insert_existing χ ζ γ blk :\n  γ ∈ dom ζ →\n  pub_locs_in_lstore χ (<[γ:=blk]> ζ) = pub_locs_in_lstore χ ζ.\nProof.\n  intros Hγζ. rewrite /pub_locs_in_lstore dom_insert_L. eapply map_eq.\n  intros γ'. rewrite !map_filter_lookup.\n  destruct (lloc_map_pubs χ !! γ'); eauto; cbn.\n  destruct (decide (γ = γ')) as [<-|].\n  { rewrite !option_guard_True; set_solver. }\n  apply option_guard_iff. set_solver.\nQed.\n\nLemma pub_locs_in_lstore_insert_pub χ ζ γ ℓ :\n  γ ∈ dom ζ →\n  pub_locs_in_lstore (<[γ:=LlocPublic ℓ]> χ) ζ = <[γ:=ℓ]> (pub_locs_in_lstore χ ζ).\nProof.\n  intros Hγ. rewrite /pub_locs_in_lstore lloc_map_pubs_insert_pub. eapply map_eq.\n  intros γ'. rewrite map_filter_lookup.\n  destruct (decide (γ = γ')) as [<-|]; simplify_map_eq.\n  { destruct (decide (γ ∈ dom ζ)); by simplify_map_eq. }\n  rewrite map_filter_lookup //.\nQed.\n\nLemma pub_locs_in_lstore_insert_priv χ ζ γ b :\n  χ !! γ = Some LlocPrivate →\n  pub_locs_in_lstore χ (<[γ:=b]> ζ) = pub_locs_in_lstore χ ζ.\nProof.\n  intros Hγ. rewrite /pub_locs_in_lstore.\n  apply map_filter_strong_ext_1.\n  intros γ' ℓ; split; intros [H1 H2]; split; try done.\n  2: erewrite dom_insert_L; eapply elem_of_union; by right.\n  erewrite dom_insert_L in H1; eapply elem_of_union in H1; destruct H1 as [H1%elem_of_singleton|H1].\n  2: done.\n  apply lloc_map_pubs_lookup_Some_1 in H2. congruence.\nQed.\n\nLemma pub_locs_in_lstore_alloc_priv χ ζ γ b:\n  χ !! γ = None →\n  pub_locs_in_lstore (<[γ:=LlocPrivate]> χ) (<[γ:=b]>ζ) = pub_locs_in_lstore χ ζ.\nProof.\n  intros Hγ. rewrite pub_locs_in_lstore_insert_priv.\n  2: apply lookup_insert.\n  rewrite /pub_locs_in_lstore lloc_map_pubs_insert_priv delete_notin.\n  2: apply lloc_map_pubs_lookup_None; by left.\n  done.\nQed.\n\nLemma pub_locs_in_lstore_alloc_foreign χ ζ γ id a:\n  χ !! γ = None →\n  pub_locs_in_lstore (<[γ:=LlocForeign id]> χ) (<[γ:=Bforeign a]>ζ) = pub_locs_in_lstore χ ζ.\nProof.\n  intros Hγ. rewrite /pub_locs_in_lstore lloc_map_pubs_insert_foreign delete_notin.\n  2: { apply lloc_map_pubs_lookup_None. eauto. }\n  apply map_filter_strong_ext_1.\n  intros γ' ℓ. rewrite dom_insert_L lloc_map_pubs_lookup_Some.\n  rewrite elem_of_union elem_of_singleton. naive_solver.\nQed.\n\nLemma pub_locs_in_lstore_insert_priv_store χ ζ ζ2 :\n  is_private_blocks χ ζ2 →\n  pub_locs_in_lstore χ (ζ ∪ ζ2) = pub_locs_in_lstore χ ζ.\nProof.\n  intros Hγ. rewrite /pub_locs_in_lstore.\n  apply map_filter_strong_ext_1.\n  intros γ' ℓ; split; intros [H1 H2]; split; try done.\n  2: erewrite dom_union_L; eapply elem_of_union; by left.\n  erewrite dom_union_L in H1; eapply elem_of_union in H1; destruct H1 as [H1|H1].\n  1: done.\n  specialize (Hγ γ' H1).\n  apply lloc_map_pubs_lookup_Some_1 in H2.\n  congruence.\nQed.\n\nLemma pub_locs_in_lstore_mono χ1 χ2 ζ :\n  dom ζ ⊆ dom χ1 →\n  lloc_map_mono χ1 χ2 →\n  pub_locs_in_lstore χ1 ζ = pub_locs_in_lstore χ2 ζ.\nProof.\n  intros Hsub (Hsub2&Hinj).\n  unfold pub_locs_in_lstore.\n  apply map_filter_strong_ext_1.\n  intros γ' ℓ; split; intros [H1 H2]; split; try done.\n  - apply lloc_map_pubs_lookup_Some. apply lloc_map_pubs_lookup_Some in H2.\n    eapply lookup_weaken; done.\n  - apply lloc_map_pubs_lookup_Some. apply lloc_map_pubs_lookup_Some in H2.\n    eapply elem_of_weaken in H1; last apply Hsub.\n    eapply elem_of_dom in H1; destruct H1 as [v Hv].\n    eapply lookup_weaken_inv in H2; last apply Hsub2; last done. congruence.\nQed.\n\nLemma pub_locs_in_lstore_delete_lstore χ ζ γ :\n  pub_locs_in_lstore χ (delete γ ζ) = delete γ (pub_locs_in_lstore χ ζ).\nProof.\n  rewrite /pub_locs_in_lstore dom_delete_L. eapply map_eq.\n  intros γ'. destruct (decide (γ = γ')) as [<-|].\n  { rewrite lookup_delete. apply map_filter_lookup_None. set_solver. }\n  rewrite lookup_delete_ne//. rewrite !map_filter_lookup.\n  destruct (lloc_map_pubs χ !! γ'); eauto; cbn.\n  apply option_guard_iff. set_solver.\nQed.\n\nLemma lstore_immut_blocks_lookup_Some ζ γ b :\n  lstore_immut_blocks ζ !! γ = Some b ↔ ζ !! γ = Some b ∧ mutability b = Immut.\nProof.\n  rewrite /lstore_immut_blocks map_filter_lookup /=.\n  set X := (ζ !! γ). destruct (ζ !! γ) as [[[i' ?]| |]|] eqn:HH; subst X; cbn;\n      try naive_solver.\n  { destruct (decide (i' = Immut)); subst.\n    { rewrite option_guard_True //. naive_solver. }\n    { rewrite option_guard_False //. naive_solver. } }\n  { rewrite option_guard_True //. naive_solver. }\n  { rewrite option_guard_False //. naive_solver. }\nQed.\n\nLemma lstore_immut_blocks_lookup_notin ζ γ :\n  ζ !! γ = None →\n  lstore_immut_blocks ζ !! γ = None.\nProof.\n  intros Hnotin. rewrite /lstore_immut_blocks map_filter_lookup Hnotin //.\nQed.\nGlobal Hint Resolve lstore_immut_blocks_lookup_notin : core.\n\nLemma lstore_immut_blocks_lookup_mut ζ γ b :\n  ζ !! γ = Some b →\n  mutability b = Mut →\n  lstore_immut_blocks ζ !! γ = None.\nProof.\n  intros Hb Hmut. rewrite /lstore_immut_blocks map_filter_lookup Hb /=.\n  rewrite option_guard_False//. congruence.\nQed.\nGlobal Hint Resolve lstore_immut_blocks_lookup_mut : core.\n\nLemma lstore_immut_blocks_lookup_immut ζ γ b :\n  ζ !! γ = Some b →\n  mutability b = Immut →\n  lstore_immut_blocks ζ !! γ = Some b.\nProof.\n  intros ? ?. rewrite lstore_immut_blocks_lookup_Some. naive_solver.\nQed.\n\nLemma lstore_immut_blocks_insert_mut ζ γ bb :\n  mutability bb = Mut →\n  lstore_immut_blocks (<[γ:=bb]> ζ) = delete γ (lstore_immut_blocks ζ).\nProof.\n  intros Hmut. rewrite /lstore_immut_blocks map_filter_insert_False; [|congruence].\n  apply map_filter_delete.\nQed.\n\nLemma lstore_immut_blocks_insert_immut ζ γ bb :\n  mutability bb = Immut →\n  lstore_immut_blocks (<[γ:=bb]> ζ) = <[γ:=bb]> (lstore_immut_blocks ζ).\nProof.\n  intros HH. rewrite /lstore_immut_blocks map_filter_insert_True; done.\nQed.\n\nLemma lstore_immut_blocks_delete ζ γ :\n  lstore_immut_blocks (delete γ ζ) = delete γ (lstore_immut_blocks ζ).\nProof. rewrite /lstore_immut_blocks. apply map_filter_delete. Qed.\n\nLemma lloc_map_mono_inj χ1 χ2 :\n  lloc_map_mono χ1 χ2 →\n  lloc_map_inj χ2.\nProof. intro H. apply H. Qed.\nGlobal Hint Resolve lloc_map_mono_inj : core.\n\n\nLemma lloc_map_mono_trans χ1 χ2 χ3 : lloc_map_mono χ1 χ2 → lloc_map_mono χ2 χ3 → lloc_map_mono χ1 χ3.\nProof.\n  intros [H1 _] [H2 H3]. split.\n  1: by etransitivity. done.\nQed.\n\nLemma lloc_map_inj_insert χ vis γ :\n  lloc_map_inj χ →\n  (∀ γ' vis', vis ≠ LlocPrivate → χ !! γ' = Some vis' → vis' ≠ vis) →\n  lloc_map_inj (<[γ := vis]> χ).\nProof.\n  intros Hinj Hid γ1 γ2 vis' H1 H2 Hvis'.\n  destruct (decide (γ1 = γ2)); auto. exfalso.\n  destruct (decide (γ = γ1)) as [<-|]; simplify_map_eq; first naive_solver.\n  destruct (decide (γ = γ2)) as [<-|]; simplify_map_eq; naive_solver.\nQed.\n\nLemma lloc_map_inj_insert_pub χ ℓ γ :\n  lloc_map_inj χ →\n  ℓ ∉ lloc_map_pub_locs χ →\n  lloc_map_inj (<[γ := LlocPublic ℓ]> χ).\nProof.\n  intros ? Hℓ. apply lloc_map_inj_insert; eauto.\n  intros ? ? _ ? ->. apply Hℓ. apply elem_of_lloc_map_pub_locs; eauto.\nQed.\n\nLemma lloc_map_inj_insert_priv χ γ :\n  lloc_map_inj χ →\n  lloc_map_inj (<[γ := LlocPrivate]> χ).\nProof. intros. apply lloc_map_inj_insert; eauto. Qed.\n\nLemma lloc_map_inj_insert_foreign χ id γ :\n  lloc_map_inj χ →\n  (∀ γ' id', χ !! γ' = Some (LlocForeign id') → id' ≠ id) →\n  lloc_map_inj (<[γ := LlocForeign id]> χ).\nProof. intros. apply lloc_map_inj_insert; naive_solver. Qed.\n\nLemma expose_llocs_inj χ1 χ2 :\n  expose_llocs χ1 χ2 →\n  lloc_map_inj χ2.\nProof. intro H. apply H. Qed.\nGlobal Hint Resolve expose_llocs_inj : core.\n\nLemma expose_llocs_trans χ1 χ2 χ3 :\n  expose_llocs χ1 χ2 →\n  expose_llocs χ2 χ3 →\n  expose_llocs χ1 χ3.\nProof.\n  intros (Hdom1 & Hinj1 & He1) (Hdom2 & Hinj2 & He2).\n  repeat split.\n  - by rewrite Hdom1.\n  - done.\n  - intros γ vis1 vis2 H1 H3. destruct (χ2 !! γ) eqn:H2.\n    2: { apply not_elem_of_dom in H2. apply elem_of_dom_2 in H1. set_solver. }\n    specialize (He1 _ _ _ H1 H2). specialize (He2 _ _ _ H2 H3).\n    inversion He1; inversion He2; simplify_eq; econstructor; eauto.\nQed.\n\nLemma expose_llocs_insert χ γ ℓ :\n  χ !! γ = Some LlocPrivate →\n  ℓ ∉ lloc_map_pub_locs χ →\n  lloc_map_inj χ →\n  expose_llocs χ (<[γ := LlocPublic ℓ]> χ).\nProof.\n  intros Hγ Hℓ Hinj. repeat split.\n  - rewrite dom_insert_L. apply elem_of_dom_2 in Hγ. set_solver.\n  - eapply lloc_map_inj_insert_pub; eauto.\n  - intros γ' vis1 vis2 H1 H2.\n    destruct (decide (γ = γ')) as [<-|]; simplify_map_eq; econstructor; eauto.\nQed.\n\nLemma expose_llocs_insert_both χ χ' γ vis vis' :\n  expose_llocs χ χ' →\n  χ !! γ = None →\n  (∀ γ' vis'', vis' ≠ LlocPrivate → χ' !! γ' = Some vis'' → vis'' ≠ vis') →\n  expose_lloc vis vis' →\n  expose_llocs (<[γ:=vis]> χ) (<[γ:=vis']> χ').\nProof.\n  intros (Hdom & Hinj & Hexp) Hγ Hvis. repeat split.\n  { rewrite !dom_insert_L Hdom //. }\n  { by apply lloc_map_inj_insert. }\n  { intros γ0 vis1 vis2 ?%lookup_insert_Some ?%lookup_insert_Some.\n    destruct_or!; destruct_and!; simplify_eq; eauto. }\nQed.\n\nLemma is_val_mono χ χL ζ ζL x y :\n  χ ⊆ χL → ζ ⊆ ζL →\n  is_val χ ζ x y →\n  is_val χL ζL x y.\nProof.\n  intros H1 H2; induction 1 in χL,ζL,H1,H2|-*; econstructor; eauto.\n  all: eapply lookup_weaken; done.\nQed.\n\nLemma is_val_expose_llocs χ χ' ζ v lv :\n  expose_llocs χ χ' →\n  is_val χ ζ v lv →\n  is_val χ' ζ v lv.\nProof.\n  intros He. induction 1 in χ',He; econstructor; eauto.\n  { destruct He as (Hdom & Hinj & He).\n    destruct (χ' !! γ) eqn:HH.\n    2: { exfalso. apply not_elem_of_dom_2 in HH. rewrite -Hdom in HH.\n         apply not_elem_of_dom_1 in HH. naive_solver. }\n    specialize (He _ _ _ ltac:(eassumption) HH). inversion He; auto. }\n  { destruct He as (Hdom & Hinj & He).\n    destruct (χ' !! γ) eqn:HH.\n    2: { exfalso. apply not_elem_of_dom_2 in HH. rewrite -Hdom in HH.\n         apply not_elem_of_dom_1 in HH. naive_solver. }\n    specialize (He _ _ _ ltac:(eassumption) HH). inversion He; auto. }\nQed.\n\nLemma is_val_insert_immut χ ζ γ bb bb2 x y :\n  ζ !! γ = Some bb2 →\n  mutability bb2 = Mut →\n  is_val χ ζ x y →\n  is_val χ (<[γ := bb]> ζ) x y.\nProof.\n  intros H1 H2; induction 1; econstructor; eauto.\n  all: rewrite lookup_insert_ne; first done.\n  all: intros ->; destruct bb2 as [[mut [? ?]]| |]; cbn in *.\n  all: congruence.\nQed.\n\nLemma is_store_blocks_is_private_blocks_disjoint χ σ ζs ζp :\n  is_store_blocks χ σ ζs →\n  is_private_blocks χ ζp →\n  ζs ##ₘ ζp.\nProof.\n  intros [Hs1 Hs2] Hp. apply map_disjoint_spec. intros ℓ b1 b2 Hsℓ Hpℓ.\n  apply elem_of_dom_2, Hs2 in Hsℓ as (?&?&?&?).\n  apply elem_of_dom_2, Hp in Hpℓ. congruence.\nQed.\n\nLemma is_store_blocks_has_loc χ σ ζ ℓ Vs :\n  is_store_blocks χ σ ζ →\n  σ !! ℓ = Some (Some Vs) →\n  ∃ γ, χ !! γ = Some (LlocPublic ℓ) ∧ γ ∈ dom ζ.\nProof.\n  intros [H1 H2] Hℓ.\n  destruct (H1 ℓ) as (γ & Hγ); [by eapply elem_of_dom_2|].\n  eexists; split; eauto. apply H2. eauto.\nQed.\n\nLemma is_store_blocks_discarded_loc χ σ ζ ℓ γ :\n  is_store_blocks χ σ ζ →\n  σ !! ℓ = Some None →\n  χ !! γ = Some (LlocPublic ℓ) →\n  γ ∉ dom ζ.\nProof.\n  intros [Hdom Hstore] Hσ Hχ [ℓ' (Hℓ' & Hχ' & ?)]%Hstore.\n  simplify_map_eq.\nQed.\n\nLemma is_store_blocks_discard_loc χ σ ζ ℓ γ Vs :\n  is_store_blocks χ σ ζ →\n  lloc_map_inj χ →\n  χ !! γ = Some (LlocPublic ℓ) →\n  σ !! ℓ = Some (Some Vs) →\n  is_store_blocks χ (<[ℓ:=None]> σ) (delete γ ζ).\nProof.\n  intros [Hs1 Hs2] χinj Hχℓ Hσℓ. split.\n  { intros ℓ'. rewrite dom_insert_lookup_L//. eauto. }\n  intros γ'. destruct (decide (γ = γ')) as [<-|].\n  { split. { rewrite dom_delete_L. set_solver. }\n    intros (ℓ' & Vs' & Hχℓ' & Hσℓ'). simplify_map_eq. }\n  { rewrite dom_delete_L elem_of_difference. split.\n    { intros [Hγ' _]. apply Hs2 in Hγ' as (ℓ'' & ? & Hχℓ'' & ?).\n      do 2 eexists. split; eauto. rewrite lookup_insert_ne //.\n      intros ->. by specialize (χinj _ _ _ Hχℓ Hχℓ'' ltac:(done)). }\n    { intros (ℓ' & Vs' & Hχℓ' & Hσℓ').\n      rewrite lookup_insert_ne in Hσℓ'.\n      2: { intros ->. by specialize (χinj _ _ _ Hχℓ Hχℓ' ltac:(done)). }\n      split; [| set_solver]. apply Hs2. do 2 eexists. split; eauto. } }\nQed.\n\nLemma is_store_discard_loc χ ζ σ ℓ :\n  is_store χ ζ σ →\n  is_store χ ζ (<[ℓ:=None]> σ).\nProof.\n  intros Hstore ℓ' Vs γ blk HH1 HH2 HH3.\n  eapply Hstore; try done. destruct (decide (ℓ = ℓ')) as [<-|].\n  { rewrite lookup_insert in HH1; done. }\n  rewrite lookup_insert_ne in HH1; try done.\nQed.\n\nLemma is_store_blocks_restore_loc χ σ ζ ℓ γ Vs blk:\n  is_store_blocks χ σ ζ →\n  lloc_map_inj χ →\n  χ !! γ = Some (LlocPublic ℓ) →\n  (σ !! ℓ = Some None ∨ σ !! ℓ = None) →\n  is_store_blocks χ (<[ℓ:=Some Vs]> σ) (<[γ:=blk]> ζ).\nProof.\n  intros [Hsl Hsr] Hχinj Hχℓ Hσℓ. split.\n  { intros ℓ'. rewrite dom_insert_L //. intros [->%elem_of_singleton|H]%elem_of_union.\n    1: by eexists. eauto. }\n  intros γ'. destruct (Hsr γ') as [Hsrl Hsrr]; split.\n  * intros Hin. rewrite dom_insert_L in Hin. apply elem_of_union in Hin.\n    destruct Hin as [->%elem_of_singleton|Hin2].\n    - exists ℓ, Vs. split; try done. by rewrite lookup_insert.\n    - destruct (Hsrl Hin2) as (ℓ2 & Vs2 & H1 & H2); exists ℓ2, Vs2; split; try done.\n      rewrite lookup_insert_ne; first done; destruct Hσℓ; congruence.\n  * intros (ℓ2 & Vs2 & H1 & H2). destruct (decide (ℓ2 = ℓ)) as [->|Hne].\n    - specialize (Hχinj _ _ _ Hχℓ H1). simplify_map_eq. set_solver.\n    - rewrite dom_insert_L. apply elem_of_union; right. apply Hsrr.\n      eexists _, _; split; try done. rewrite lookup_insert_ne in H2; done.\nQed.\n\nLemma is_store_restore_loc χ ζ σ ℓ γ Vs blk :\n  is_store χ ζ σ →\n  lloc_map_inj χ →\n  χ !! γ = Some (LlocPublic ℓ) →\n  ζ !! γ = Some blk →\n  is_heap_elt χ ζ Vs blk →\n  is_store χ ζ (<[ℓ:=Some Vs]> σ).\nProof.\n  intros Hstore Hχinj Hχℓ Hζγ Hblk ℓ1 vs1 γ1 bl1 Hs1 Hs2 Hs3.\n  destruct (decide (ℓ = ℓ1)) as [<- | Hne].\n  * specialize (Hχinj _ _ _ Hχℓ Hs2 ltac:(done)). by simplify_map_eq.\n  * rewrite lookup_insert_ne in Hs1; last done. eapply Hstore; done.\nQed.\n\nLemma is_store_blocks_expose_lloc χ ζ σ ℓ γ :\n  is_store_blocks χ σ ζ →\n  χ !! γ = Some LlocPrivate →\n  ℓ ∉ dom σ →\n  is_store_blocks (<[γ:=LlocPublic ℓ]> χ) (<[ℓ:=None]> σ) ζ.\nProof.\n  intros [Hsl Hsr] Hγ Hℓdom. split.\n  - intros ℓ'. rewrite !dom_insert_L elem_of_union elem_of_singleton.\n    intros [<-|Hℓ']. by exists γ; simplify_map_eq.\n    specialize (Hsl _ Hℓ') as (γ'&?). exists γ'.\n    rewrite lookup_insert_ne //. set_solver.\n  - intros γ'; destruct (Hsr γ') as [Hsrl Hsrr]. split.\n    * intros Hin. specialize (Hsrl Hin) as (ℓ' & Vs' & H1 & H2).\n      eexists ℓ', Vs'. rewrite lookup_insert_ne. 2: congruence.\n      split; eauto. rewrite lookup_insert_ne//.\n      eapply not_elem_of_dom in Hℓdom. naive_solver.\n    * intros (ℓ2 & Vs & H1 & H2). destruct (decide (ℓ = ℓ2)) as [<- | Hn].\n      1: rewrite lookup_insert in H2; congruence.\n      apply Hsrr. destruct (decide (γ = γ')) as [<-|]; [by simplify_map_eq|].\n      rewrite !lookup_insert_ne // in H1, H2. exists ℓ2, Vs. eauto.\nQed.\n\nLemma is_store_expose_lloc χ ζ σ ℓ γ :\n  is_store χ ζ σ →\n  χ !! γ = Some LlocPrivate →\n  ℓ ∉ dom σ →\n  ℓ ∉ lloc_map_pub_locs χ →\n  lloc_map_inj χ →\n  is_store (<[γ:=LlocPublic ℓ]> χ) ζ (<[ℓ:=None]> σ).\nProof.\n  intros Hstore Hγ Hℓdom Hℓpubs Hinj ℓ1 vs γ1 blk H1 H2 H3.\n  destruct (decide (ℓ = ℓ1)) as [<- | Hn]; [by simplify_map_eq|].\n  destruct (decide (γ = γ1)) as [<- |]; [by simplify_map_eq|].\n  rewrite !lookup_insert_ne // in H1, H2.\n  specialize (Hstore _ _ _ _ H1 H2 H3).\n  inversion Hstore; subst.\n  econstructor. eapply Forall2_impl; first eauto.\n  intros x y Hval. eapply is_val_expose_llocs; last done; eauto.\n  eapply expose_llocs_insert; eauto.\nQed.\n\nLemma is_store_freeze_lloc χ ζ σ γ b:\n  is_store χ ζ σ →\n  χ !! γ = Some LlocPrivate →\n  ζ !! γ = Some (Bvblock (Mut, b)) →\n  is_store χ (<[γ:=Bvblock (Immut, b)]> ζ) σ.\nProof.\n  intros Hstore Hpriv Hζγ l vs' γ1 bb H1 H2 H3.\n  destruct (decide (γ = γ1)) as [<- | H4].\n  * simplify_map_eq.\n  * rewrite lookup_insert_ne in H3; last done.\n    specialize (Hstore _ _ _ _ H1 H2 H3).\n    inversion Hstore. subst vs bb.\n    econstructor. eapply Forall2_impl; first done.\n    intros x y H5. eapply is_val_insert_immut; eauto.\nQed.\n\nLemma GC_correct_freeze_lloc ζ θ γ b :\n  GC_correct ζ θ →\n  ζ !! γ = Some (Bvblock (Mut, b)) →\n  GC_correct (<[γ := Bvblock (Immut, b)]> ζ) θ.\nProof.\n  intros [H1 H2] Hζγ; split; first done. intros γ1 * ? ?.\n  inversion 1; subst.\n  destruct (decide (γ1 = γ)) as [-> |];\n    simplify_map_eq; eauto.\n  eapply H2; eauto. by constructor.\nQed.\n\nGlobal Instance freeze_lstore_refl : Reflexive (freeze_lstore).\nProof.\n  intros ζ; split; first done.\n  intros γ b1 b2 H1 H2. rewrite H1 in H2; injection H2; intros ->.\n  apply freeze_block_refl.\nQed.\n\nLemma freeze_lstore_freeze_lloc ζ ζ' γ b :\n  freeze_lstore ζ ζ' →\n  ζ' !! γ = Some (Bvblock (Mut, b)) →\n  freeze_lstore ζ (<[γ:=Bvblock (Immut, b)]> ζ').\nProof.\n  intros [HL HR] Hζ'γ. split.\n  - rewrite HL. rewrite dom_insert_L. rewrite subseteq_union_1_L. 1:done.\n    intros ? ->%elem_of_singleton. by eapply elem_of_dom.\n  - intros γ1 b1 b2 H1 H2. destruct (decide (γ = γ1)) as [<- |H3].\n    * rewrite lookup_insert in H2. injection H2; intros <-.\n      specialize (HR γ b1 (Bvblock (Mut, b)) H1 Hζ'γ).\n      inversion HR; subst; econstructor.\n    * rewrite lookup_insert_ne in H2; last done. by eapply HR.\nQed.\n\nLemma freeze_lstore_lookup_backwards ζ ζ' γ blk' :\n  freeze_lstore ζ ζ' →\n  ζ' !! γ = Some blk' →\n  ∃ blk, freeze_block blk blk' ∧ ζ !! γ = Some blk.\nProof.\n  intros [HL HR] Hγ.\n  destruct (ζ !! γ) eqn:Hγ'; eauto.\n  apply elem_of_dom_2 in Hγ. apply not_elem_of_dom in Hγ'. congruence.\nQed.\n\nLemma freeze_lstore_lookup_bclosure ζ ζ' γ f x e :\n  freeze_lstore ζ ζ' →\n  ζ' !! γ = Some (Bclosure f x e) →\n  ζ !! γ = Some (Bclosure f x e).\nProof.\n  intros Hfreeze Hζ'.\n  eapply freeze_lstore_lookup_backwards in Hfreeze as (? & Hfrz & ?);\n    eauto.\n  by inversion Hfrz; simplify_eq.\nQed.\n\nLemma repr_roots_dom θ a b : repr_roots θ a b -> dom a = dom b.\nProof.\n  induction 1.\n  + by do 2 rewrite dom_empty_L.\n  + by do 2 rewrite dom_insert_L; rewrite IHrepr_roots.\nQed.\n\nLemma code_int_inj z1 z2 : code_int z1 = code_int z2 → z1 = z2.\nProof.\n  intros H; simplify_eq; lia.\nQed.\n\nLemma repr_lval_inj θ v w w' : repr_lval θ v w -> repr_lval θ v w' -> w = w'.\nProof.\n  induction 1; inversion 1.\n  + done.\n  + rewrite H in H3. injection H3; intros ->; done.\nQed.\n\nLemma repr_lval_inj_1 θ v v' w : gmap_inj θ → repr_lval θ v w -> repr_lval θ v' w -> v = v'.\nProof.\n  unfold code_int.\n  intros H; induction 1; inversion 1.\n  + f_equal; lia.\n  + subst. f_equal. by eapply H.\nQed.\n\nLemma repr_lval_lint θ1 θ2 z w : repr_lval θ1 (Lint z) w → repr_lval θ2 (Lint z) w.\nProof.\n  inversion 1; simplify_eq; by econstructor.\nQed.\n\nLemma repr_lval_mono θ θ' v w: θ ⊆ θ' -> repr_lval θ v w -> repr_lval θ' v w.\nProof.\n  intros H; induction 1; econstructor.\n  eapply lookup_weaken; done.\nQed.\n\n(* The development is generic over the precise encoding of ints *)\nOpaque code_int.\n\nLemma repr_mono θ θ' roots_m privmem mem : θ ⊆ θ' -> repr θ roots_m privmem mem -> repr θ' roots_m privmem mem.\nProof.\n  intros Helem (memr&(H1&H2)). exists memr. split; last done.\n  clear H2.\n  induction H1.\n  - econstructor.\n  - econstructor. 1: by eapply IHrepr_roots. 2-3: done.\n    by eapply repr_lval_mono.\nQed.\n\nLemma lval_in_vblock v m tg vs :\n  lval_in_block (Bvblock (m, (tg, vs))) v ↔ v ∈ vs.\nProof. split. by inversion 1. intros; by constructor. Qed.\n\n\nLemma GC_correct_transport ζ1 ζ2 θ : freeze_lstore ζ1 ζ2 → GC_correct ζ1 θ → GC_correct ζ2 θ.\nProof.\n  intros (H1L&H1R) (H2&H3). split; first done.\n  intros γ blk γ' HH1 HH2 HH3.\n  destruct (ζ1 !! γ) as [b|] eqn:Heq.\n  2: { eapply elem_of_dom_2 in HH2. eapply not_elem_of_dom in Heq. rewrite H1L in Heq; tauto. }\n  specialize (H1R _ _ _ Heq HH2). inversion H1R; subst.\n  2: { eapply H3; done. }\n  destruct tgvs. eapply lval_in_vblock in HH3.\n  eapply H3. 1: exact HH1. 1: done. eapply lval_in_vblock. done.\nQed.\n\n\nLemma GC_correct_transport_rev ζ1 ζ2 θ : freeze_lstore ζ2 ζ1 → GC_correct ζ1 θ → GC_correct ζ2 θ.\nProof.\n  intros (H1L&H1R) (H2&H3). split; first done.\n  intros γ blk γ' HH1 HH2 HH3.\n  destruct (ζ1 !! γ) as [b|] eqn:Heq.\n  2: { eapply elem_of_dom_2 in HH2. eapply not_elem_of_dom in Heq. rewrite -H1L in Heq; tauto. }\n  specialize (H1R _ _ _ HH2 Heq). inversion H1R; subst.\n  2: { eapply H3; done. }\n  destruct tgvs. eapply lval_in_vblock in HH3.\n  eapply H3. 1: exact HH1. 1: done. eapply lval_in_vblock. done.\nQed.\n\nLemma GC_correct_gmap_inj ζ θ :\n  GC_correct ζ θ →\n  gmap_inj θ.\nProof. intros H; apply H. Qed.\nGlobal Hint Resolve GC_correct_gmap_inj : core.\n\n(******************************************************************************)\n(* auxiliary hints & tactics *)\n\nGlobal Hint Constructors repr_lval : core.\n\nLtac inv_repr_lval :=\n  progress repeat match goal with\n  | H : repr_lval _ (Lloc _) _ |- _ =>\n      inversion H; subst; clear H\n  | H : repr_lval _ (Lint _) _ |- _ =>\n      inversion H; subst; clear H\n  end.\n\nLtac inv_modify_block :=\n  match goal with\n  | H : modify_block _ _ _ _ |- _ =>\n      inversion H; simplify_eq; clear H\n  end.\n\nLtac repr_lval_inj :=\n  progress repeat match goal with\n  | Hinj : gmap_inj ?θ,\n    Hr1 : repr_lval ?θ ?v ?w,\n    Hr2 : repr_lval ?θ ?v' ?w |- _ =>\n      pose proof (repr_lval_inj_1 _ _ _ _ Hinj Hr1 Hr2); subst v'; clear Hr2\n  | Hr1 : repr_lval _ ?v ?w,\n    Hr2 : repr_lval _ ?v ?w' |- _ =>\n      pose proof (repr_lval_inj _ _ _ _ Hr1 Hr2); subst w'; clear Hr2\n  end.\n", "meta": {"author": "logsem", "repo": "melocoton", "sha": "b77eecc3381f53db0eb3c4cf1314e881a8dc41b3", "save_path": "github-repos/coq/logsem-melocoton", "path": "github-repos/coq/logsem-melocoton/melocoton-b77eecc3381f53db0eb3c4cf1314e881a8dc41b3/theories/interop/basics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21602354846075858}}
{"text": "From mathcomp Require Import ssreflect ssrfun ssrbool eqtype seq.\nFrom extructures Require Import ord fmap.\nFrom CoqUtils Require Import word.\nRequire Import lib.utils common.types cfi.property.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* CFI preserved by refinement for two generic (cfi) machines *)\n\nSection Preservation.\n\nContext {mt : machine_types}\n        {ops : machine_ops mt}\n        {opss : machine_ops_spec ops}.\n\nVariable amachine : cfi_machine.\nVariable cmachine : cfi_machine.\n\n(* General notion of refinement between two machines*)\nClass machine_refinement (amachine : cfi_machine) (cmachine : cfi_machine) := {\n  refine_state : (@state amachine) -> (@state cmachine) -> Prop;\n\n  check : (@state cmachine) -> (@state cmachine) -> bool;\n\n  backwards_refinement_normal :\n    forall ast cst cst'\n      (REF: refine_state ast cst)\n      (STEP: step cst cst'),\n      (check cst cst' ->\n       exists ast', step ast ast' /\\ refine_state ast' cst')\n      /\\ (~~ check cst cst' ->\n          refine_state ast cst' \\/\n          exists ast', step ast ast' /\\ refine_state ast' cst');\n\n  backwards_refinement_attacker :\n    forall ast cst cst'\n      (REF: refine_state ast cst)\n      (STEPA: step_a cst cst'),\n    exists ast', step_a ast ast' /\\ refine_state ast' cst'\n\n}.\n\nContext (rf : machine_refinement amachine cmachine).\n\nInductive refine_traces :\n  seq (@state amachine) -> seq (@state cmachine) -> Prop :=\n| TRNil : forall ast cst,\n            refine_state ast cst ->\n            refine_traces [:: ast] [:: cst]\n| TRNormal0 : forall ast cst cst' axs cxs,\n    step cst cst' ->\n    ~~ check cst cst' ->\n    refine_state ast cst ->\n    refine_state ast cst' ->\n    refine_traces (ast :: axs) (cst' :: cxs) ->\n    refine_traces (ast :: axs) (cst :: cst' :: cxs)\n| TRNormal1 : forall ast ast' cst cst' axs cxs,\n    step cst cst' ->\n    step ast ast' ->\n    refine_state ast cst ->\n    refine_state ast' cst' ->\n    refine_traces (ast' :: axs) (cst' :: cxs) ->\n    refine_traces (ast :: ast' :: axs) (cst :: cst' :: cxs)\n| TRAttacker : forall ast ast' cst cst' axs cxs,\n    ~step cst cst' ->\n    step_a cst cst' ->\n    step_a ast ast' ->\n    refine_state ast cst ->\n    refine_state ast' cst' ->\n    refine_traces (ast' :: axs) (cst' :: cxs) ->\n    refine_traces (ast :: ast' :: axs) (cst :: cst' :: cxs).\n\nLemma refine_traces_single ast cst cst' cxs :\n  refine_traces [:: ast] (cst :: cst' :: cxs) ->\n  forall csi csj,\n    In2 csi csj (cst :: cst' :: cxs) ->\n    ~~ check csi csj.\nProof.\n  intros REF csi csj IN2.\n  inv REF.\n  destruct IN2 as [[E1 E2] | IN2]; subst.\n  - assumption.\n  - induction (cst' :: cxs).\n    + destruct IN2.\n    + inv H8.\n      * destruct IN2.\n      * destruct IN2 as [[E1 E2] | IN2]; subst;\n        by auto.\nQed.\n\nLemma refine_traces_execution ast cst cst' cxs :\n  refine_traces [:: ast] (cst :: cxs) ->\n  cst' \\in cst :: cxs ->\n  exec step cst cst'.\nProof.\nelim: cxs cst => /= [|cst'' cxs IH] cst; rewrite inE.\n  by move=> ? /eqP -> {cst'}; constructor.\nmove=> Href /orP [/eqP ->|Hin]; first by constructor.\ninv Href.\nby eapply re_step; eauto; apply: IH.\nQed.\n\nLemma refine_traces_astep ast ast' cst axs cxs :\n  refine_traces (ast :: ast' :: axs) (cst :: cxs) ->\n  exists cst' cst'', In2 cst' cst'' (cst :: cxs) /\\\n                     (step ast ast' \\/ step_a ast ast' /\\ step_a cst' cst'').\nProof.\n  intros RTRACE.\n  move: cst RTRACE.\n  induction cxs; intros.\n  - inv RTRACE.\n  - inversion RTRACE\n    as [| ? ? ? ? ? STEP CHECK REF REF' RTRACE'\n        | ? ? ? ? ? ? STEP ASTEP REF REF' RTRACE'\n        | ? ? ? ? ? ? NSTEP STEPA SSTEPA REF REF' RTRACE'];\n    subst.\n    +  destruct (IHcxs _ RTRACE') as [cst' [cst'' IH]].\n       destruct IH as [IN2 [SSTEP | [STEPA CSTEPA]]].\n       * exists cst'; exists cst''.\n         split. simpl; by auto.\n         left. by assumption.\n       * exists cst'; exists cst''.\n         split. simpl; by auto.\n         right; by auto.\n    + exists cst; exists a. split; [simpl; by auto | left; by assumption].\n    + exists cst; exists a.\n      split; [simpl; by auto | right; auto].\nQed.\n\nClass machine_refinement_specs := {\n\n  step_classic : forall (cst cst': @state cmachine),\n    (step cst cst') \\/ (~step cst cst');\n\n  initial_refine : forall (cst : @state cmachine),\n    initial cst ->\n    exists (ast : @state amachine), initial ast /\\ refine_state ast cst;\n\n  cfg_nocheck : forall asi csi csj,\n    refine_state asi csi ->\n    step csi csj ->\n    ~~ check csi csj ->\n    succ csi csj;\n\n  (* We should merge this with av_implies_cv, as we did in the paper *)\n  cfg_equiv : forall (asi asj : @state amachine) csi csj,\n    refine_state asi csi ->\n    refine_state asj csj ->\n    step asi asj ->\n    check csi csj ->\n    step csi csj ->\n    succ csi csj = succ asi asj;\n\n  (* We discharge this for abstract and symbolic machine without\n     making any assumptions on the shape of the CFG *)\n  av_no_attacker : forall (asi asj : @state amachine) csi,\n    refine_state asi csi ->\n    ~~ succ asi asj ->\n    step asi asj ->\n    ~ step_a asi asj;\n\n  as_implies_cs : forall axs cxs asi asj csi csj,\n    check csi csj ->\n    ~~ succ asi asj ->\n    step asi asj ->\n    refine_state asi csi ->\n    refine_traces (asj :: axs) (csj :: cxs) ->\n    stopping (asj :: axs) ->\n    stopping (csj :: cxs)\n\n}.\n\nContext (rfs : machine_refinement_specs).\n\n(* nit: the final state is irrelevant for both intermstep and\n        intermrstep, can we remove it and get of useless existentials? no :P *)\nLemma backwards_refinement_traces_stronger\n    (ast : @state amachine) cst cst' cxs :\n  refine_state ast cst ->\n  intermstep cxs cst cst' ->\n  exists axs,\n    (exists ast', intermrstep axs ast ast') /\\\n    refine_traces axs cxs.\nProof.\n  intros INITREF INTERM2.\n  generalize dependent ast.\n  induction INTERM2 as [cst cst' STEP2 | cst cst'' cst' cxs' STEP2 INTERM2']; intros.\n  {\n    destruct (step_classic cst cst') as [STEPN | NST].\n  - destruct (backwards_refinement_normal INITREF STEPN) as [VIS INVIS].\n    have [CHECK|CHECK] := boolP (check cst cst').\n    + destruct (VIS CHECK) as [ast' [ASTEP AREF]]. clear INVIS VIS.\n      exists [:: ast;ast']. split.\n      * exists ast'. eapply intermr_multi. right. eassumption. now constructor.\n      * apply TRNormal1; auto.\n        constructor; assumption.\n    + specialize (INVIS CHECK); clear VIS.\n      destruct INVIS as [ZERO | [ast' [STEP REF]]].\n      * exists [:: ast]; split; [exists ast; constructor | apply TRNormal0; auto].\n        constructor; assumption.\n      * exists [:: ast; ast'].\n        { split.\n          - exists ast'.\n            econstructor; first by (right; eauto).\n            constructor.\n          - apply TRNormal1; eauto.\n            by constructor. }\n  - destruct STEP2 as [STEP2A | STEP2N]; [idtac | tauto].\n    destruct (backwards_refinement_attacker INITREF STEP2A) as [ast' [STEPA REF]].\n    exists [:: ast;ast']; split;\n    [exists ast' | apply TRAttacker; auto; constructor; assumption].\n    eapply intermr_multi; eauto. left; eassumption. now constructor.\n  }\n  { destruct (step_classic cst cst'') as [STEPN | NST].\n    - destruct (backwards_refinement_normal INITREF STEPN) as [VIS INVIS].\n      have [CHECK|CHECK] := boolP (check cst cst'').\n      + destruct (VIS CHECK) as [ast'' [ASTEP AREF]]. clear INVIS VIS.\n        destruct (IHINTERM2' ast'' AREF) as [axs [[ast' INTERMR1] IH]].\n        exists (ast :: axs); split.\n        assert (INTERMR1' : intermrstep (ast :: axs) ast ast').\n        { eapply intermr_multi. right; eauto. assumption. }\n        eexists; now eassumption.\n        destruct axs; [inversion IH | destruct cxs'].\n        * inversion IH.\n        * apply intermr_first_step in INTERMR1; apply interm_first_step in INTERM2';\n          subst.\n          apply TRNormal1; auto.\n      + (*nocheck step case*)\n        specialize (INVIS CHECK); clear VIS.\n        destruct INVIS as [ZERO | [ast' [STEP REF]]].\n        * destruct (IHINTERM2' ast ZERO) as [axs [[ast' INTERMR1] IH]].\n          exists axs. split.\n          exists ast'; now assumption.\n          destruct axs;\n            [inversion INTERMR1 | apply intermr_first_step in INTERMR1; subst].\n          destruct cxs';\n            [inversion INTERM2' | apply interm_first_step in INTERM2'; subst].\n          apply TRNormal0; auto.\n        * destruct (IHINTERM2' _ REF) as [axs [[ast'' INTERMR1] IH]].\n          exists (ast :: axs).\n          { split.\n            - exists ast''. econstructor; eauto. by right.\n            - destruct axs; first by inversion IH.\n              destruct cxs'; first by inversion IH.\n              apply interm_first_step in INTERM2'. subst.\n              apply intermr_first_step in INTERMR1. subst.\n              by eapply TRNormal1; eauto. }\n      + destruct STEP2 as [STEP2A | STEP2N]; subst.\n        { (*case it's an attacker step*)\n          destruct (backwards_refinement_attacker INITREF STEP2A)\n          as [ast'' [ASTEP REF]].\n        destruct (IHINTERM2' _ REF) as [axs [[ast' INTERMR1] IH]].\n        exists (ast::axs).\n        split. exists ast'. eapply intermr_multi; eauto.\n        left; now assumption.\n        destruct axs;\n          [inversion INTERMR1 | apply intermr_first_step in INTERMR1; subst].\n        destruct cxs';\n          [inversion INTERM2' | apply interm_first_step in INTERM2'; subst].\n        apply TRAttacker; auto.\n        }\n        { (*case it's a normal step*)\n          tauto.\n        }\n  }\nQed.\n\nLemma refine_traces_preserves_cfi_trace : forall axs cxs,\n  refine_traces axs cxs ->\n  trace_has_cfi axs ->\n  trace_has_cfi cxs.\nProof.\n  intros axs cxs RTRACE TSAFE csi csj IN2 CSTEP.\n  induction RTRACE\n    as [ast cst REF | ast cst cst' axs' cxs' STEP VIS REF REF' RTRACE' |\n        ast ast' cst cst' axs cxs STEP ASTEP' REF REF' RTRACE'|\n        ast ast' cst cst' axs cxs NSTEP STEP ASTEP' REF REF' RTRACE']; subst.\n  - destruct IN2.\n  - destruct IN2 as [[? ?] | IN2]; subst.\n    * apply (cfg_nocheck REF CSTEP VIS).\n    * apply IHRTRACE'; assumption.\n  - destruct IN2 as [[? ?] | IN2]; subst.\n    * assert (SUCC: succ ast ast').\n      { apply TSAFE; simpl; auto. }\n      have [CHECK|CHECK] := boolP (check csi csj).\n        by rewrite (cfg_equiv REF REF' ASTEP' CHECK STEP).\n      by apply (cfg_nocheck REF STEP CHECK).\n    * apply IHRTRACE'.\n      destruct axs.\n      + intros ? ? CONTRA; destruct CONTRA.\n      + intros asi asj IN2'. unfold trace_has_cfi in TSAFE.\n        apply in2_strengthen with (ys := [:: ast]) in IN2'.\n        change ([:: ast] ++ ast' :: s :: axs )\n        with (ast :: ast' :: s :: axs) in IN2'.\n        apply TSAFE. now assumption.\n        now assumption.\n  - destruct IN2 as [[? ?] | IN2]; subst.\n    * tauto.\n    * apply IHRTRACE'.\n      destruct axs.\n      + intros ? ? CONTRA; destruct CONTRA.\n      + intros asi asj IN2'. unfold trace_has_cfi in TSAFE.\n        apply in2_strengthen with (ys := [:: ast]) in IN2'.\n        change ([:: ast] ++ ast' :: s :: axs )\n        with (ast :: ast' :: s :: axs) in IN2'.\n        apply TSAFE. now assumption.\n        now assumption.\nQed.\n\nLemma refine_traces_split axs ahd atl asi asj cxs :\n  axs = ahd ++ asi :: asj :: atl ->\n  refine_traces axs cxs ->\n  step asi asj ->\n  ~~ succ asi asj ->\n  exists chd csi csj ctl,\n    step csi csj /\\\n    refine_state asi csi /\\\n    refine_state asj csj /\\\n    refine_traces (rcons ahd asi) (rcons chd csi) /\\\n    refine_traces (asj :: atl) (csj :: ctl) /\\\n    cxs = chd ++ csi :: csj :: ctl.\nProof.\n  intros eqaxs ref astep viol.\n  move: atl asj asi ahd eqaxs astep viol.\n  induction ref; intros.\n  - by repeat (destruct ahd; inversion eqaxs).\n  - edestruct IHref as [chd [csi [csj [ctl [CSTEP [REFI [REFJ [RTHD [RTT CLST]]]]]]]]]; eauto.\n    exists (cst :: chd); repeat eexists; eauto. simpl.\n    destruct chd; destruct ahd; simpl in *; inv CLST; inv eqaxs; apply TRNormal0; eauto.\n    rewrite CLST. reflexivity.\n  - destruct ahd; simpl in *.\n    + inv eqaxs. clear IHref.\n      exists [::]. exists cst. exists cst'. exists cxs.\n      repeat split; eauto. by constructor; assumption.\n    + inv eqaxs.\n      edestruct IHref as [chd [csi [csj [ctl [CSTEP [REFI [REFJ [RTHD [RTT CLST]]]]]]]]]; eauto.\n      clear IHref.\n      exists (cst :: chd). exists csi. exists csj. exists ctl.\n      repeat split; eauto.\n      * destruct chd; destruct ahd; simpl in *; inv CLST; inv H5;\n         apply TRNormal1; eauto.\n        rewrite CLST. reflexivity.\n  - destruct ahd; simpl in *; inv eqaxs.\n    { exfalso. clear H3. by eapply av_no_attacker; eauto. }\n    edestruct IHref as [chd [csi [csj [ctl [CSTEP [REFI [REFJ [RTHD [RTT CLST]]]]]]]]]; eauto.\n    exists (cst :: chd); repeat eexists; eauto. simpl.\n    destruct chd; destruct ahd; simpl in *; inv CLST; inv H6;\n    apply TRAttacker; eauto.\n    rewrite CLST. reflexivity.\nQed.\n\n(*Preservation Theorem*)\n\nTheorem backwards_refinement_preserves_cfi :\n  cfi amachine ->\n  cfi cmachine.\nProof.\n  intros CFI1 cst cst' cxs INIT2 INTERM2.\n  destruct (initial_refine INIT2) as [ast [INIT1 INITREF]].\n  destruct (backwards_refinement_traces_stronger INITREF INTERM2)\n    as [axs [[ast' INTERMR1] RTRACE]].\n  destruct (intermr_implies_interm INTERMR1) as [INTERM1 | [EQ LST]].\n  { (*machine1  steps*)\n    clear INTERMR1.\n    destruct (CFI1 ast ast' axs INIT1 INTERM1) as [TSAFE1 | VIOLATED].\n    - (*machine1 has CFI at all steps*)\n      left. by apply (refine_traces_preserves_cfi_trace RTRACE TSAFE1).\n    - (*machine1 has a violation*)\n      destruct VIOLATED\n         as [asi [asj [ahs [atl [ALST [[ASTEP AV] [TSAFE1 [TSAFE2 STOP1]]]]]]]].\n      assert (IN2: In2 asi asj axs) by (rewrite ALST; apply in2_trivial).\n      destruct (refine_traces_split ALST RTRACE ASTEP AV)\n        as [chs [csi [csj [ctl [CSTEP [REFI [REFJ [RHT [RTT CLST]]]]]]]]].\n      have [VIS|VIS] := boolP (check csi csj).\n      + right.\n        exists csi; exists csj; exists chs; exists ctl.\n        split; first by [].\n        split.\n          split; first by [].\n          by rewrite (cfg_equiv REFI REFJ ASTEP VIS CSTEP).\n        split; first by apply (refine_traces_preserves_cfi_trace RHT TSAFE1).\n        split; first by apply (refine_traces_preserves_cfi_trace  RTT TSAFE2).\n        by apply (as_implies_cs VIS AV ASTEP REFI RTT STOP1).\n      + left.\n        intros csi' csj' IN2' STEP'.\n        subst cxs.\n        apply In2_inv in IN2'.\n        destruct IN2' as [IN2' | [[E1 E2] | IN2']].\n        * by rewrite cats1 in IN2'; apply (refine_traces_preserves_cfi_trace RHT TSAFE1).\n        * subst. by eauto using cfg_nocheck.\n        * by apply (refine_traces_preserves_cfi_trace  RTT TSAFE2).\n  }\n  { (*machine1 no step*)\n    subst. left.\n    intros csi csj IN2 CSTEP.\n    simpl in INTERMR1; apply intermr_first_step in INTERMR1; subst.\n    destruct cxs. inversion INTERM2.\n    apply interm_first_step in INTERM2; subst.\n    clear INIT1. clear INIT2. clear INITREF.\n    generalize dependent cst.\n    induction cxs; intros.\n    - destruct IN2.\n    - destruct IN2 as [[? ?] | IN2]; subst.\n      * inversion RTRACE as [|? ? ? ? ? STEP CHECK REF REF' RTRACE'| |]; subst.\n        apply (cfg_nocheck REF STEP CHECK).\n      * inversion RTRACE as [|? ? ? ? ? STEP CHECK REF REF' RTRACE'| |]; subst.\n        now apply (IHcxs _ RTRACE' IN2).\n  }\nQed.\n\nEnd Preservation.\n", "meta": {"author": "micro-policies", "repo": "micro-policies-coq", "sha": "28163163c88387fc24475ed219f5705f9e0d4fc6", "save_path": "github-repos/coq/micro-policies-micro-policies-coq", "path": "github-repos/coq/micro-policies-micro-policies-coq/micro-policies-coq-28163163c88387fc24475ed219f5705f9e0d4fc6/cfi/preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2160235484607585}}
{"text": "(****************************************************************************)\n(* Copyright 2020 The Project Oak Authors                                   *)\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\nRequire Import Coq.Lists.List Coq.Numbers.NaryFunctions Coq.Arith.Arith\n     Coq.Vectors.Vector Coq.Logic.Eqdep_dec.\nRequire Import Cava.Arrow.Classes.Category Cava.Arrow.Classes.Arrow.\n\nImport ListNotations.\nImport VectorNotations.\nImport CategoryNotations.\n\nRequire Import Cava.Types.\nRequire Import Cava.VectorUtils.\n\nInductive Kind : Set :=\n| Tuple: Kind -> Kind -> Kind\n| Unit: Kind\n| Bit: Kind\n| Vector: Kind -> nat -> Kind\n.\n\nFixpoint eq_kind_dec (k1 k2: Kind) {struct k1} : {k1=k2} + {k1<>k2}.\nProof.\n  decide equality.\n  exact (PeanoNat.Nat.eq_dec n n0).\nDefined.\n\nInstance kind_decidable_equality_inst : DecidableEquality Kind := {\n  eq_dec := eq_kind_dec\n}.\n\n(* TODO: Coq.Init.Logic f_equal2 is opaque, f_equal is not, should transparency here be upstreamed? *)\nLemma f_equal2 {A B C} {x y:A}  {a b: B} (f: A -> B -> C) : x = y -> a = b -> f x a = f y b.\nProof.\n  destruct 1.\n  destruct 1.\n  trivial.\nDefined.\n\nDefinition kind_proj_tup_left (ty: Kind):=\n  match ty with\n  | Tuple t1 t2 => t1\n  | _ => ty\n  end.\n\nDefinition kind_proj_tup_right (ty: Kind):=\n  match ty with\n  | Tuple t1 t2 => t2\n  | _ => ty\n  end.\nDefinition kind_proj_vec_t (ty: Kind):=\n  match ty with\n  | Vector t _ => t\n  | _ => ty\n  end.\nDefinition kind_proj_vec_n (ty: Kind) :=\n  match ty with\n  | Vector _ n => n\n  | _ => 0\n  end.\n\nLemma UIP_refl_kind (ty:Kind) (x : ty = ty) : x = eq_refl.\nProof.\n  induction ty.\n\n  - specialize IHty1 with (f_equal kind_proj_tup_left x).\n    specialize IHty2 with (f_equal kind_proj_tup_right x).\n    change eq_refl with (f_equal2 Tuple (@eq_refl _ ty1) (@eq_refl _ ty2)).\n    rewrite <- IHty1.\n    rewrite <- IHty2.\n    clear IHty1.\n    clear IHty2.\n\n    change (match Tuple ty1 ty2 as x return Tuple ty1 ty2 = x -> Prop with\n            | Tuple _ _ =>\n              fun H => H = f_equal2 Tuple (f_equal kind_proj_tup_left H) (f_equal kind_proj_tup_right H)\n            | _ => fun _ => True\n            end x).\n    pattern (Tuple ty1 ty2) at 2 3, x.\n    destruct x.\n    reflexivity.\n\n  - change (match Unit as n return Unit=n -> Prop with\n            | Unit => fun x => x = eq_refl\n            | _ => fun _ => True\n            end x); destruct x; reflexivity.\n\n  - change (match Bit as n return Bit=n -> Prop with\n            | Bit => fun x => x = eq_refl\n            | _ => fun _ => True\n            end x); destruct x; reflexivity.\n\n  - specialize IHty with (f_equal kind_proj_vec_t x).\n    pose proof (UIP_refl_nat n (f_equal kind_proj_vec_n x)).\n    change eq_refl with (f_equal2 Vector (@eq_refl _ ty) (@eq_refl _ n)).\n    rewrite <- IHty.\n    rewrite <- H.\n    clear IHty.\n    clear H.\n    change (match Vector ty n as a return Vector ty n = a -> Prop with\n            | Vector _ _ => fun x => x = f_equal2 Vector (f_equal kind_proj_vec_t x) (f_equal kind_proj_vec_n x)\n            | _ => fun _ => True\n            end x).\n\n    pattern (Vector ty n) at 2 3, x.\n    destruct x.\n    reflexivity.\nDefined.\n\nLemma kind_eq: forall ty, eq_kind_dec ty ty = left eq_refl.\nProof.\n  intros.\n  destruct (eq_kind_dec ty ty); try rewrite (UIP_refl_kind _ _); auto.\n  destruct n.\n  reflexivity.\nQed.\n\nLtac reduce_kind_eq :=\n  match goal with\n  | [ |- context[eq_kind_dec _ _] ] =>\n    rewrite kind_eq; unfold eq_rect_r, eq_rect, eq_sym\n  | [H: context[eq_kind_dec _ _] |- _] =>\n    rewrite kind_eq in H; unfold eq_rect_r, eq_rect, eq_sym in H\n  end; try subst.\n\nDeclare Scope kind_scope.\nBind Scope kind_scope with Kind.\n\nNotation \"<< x >>\" := (x) (only parsing) : kind_scope.\nNotation \"<< x , .. , y , z >>\" := (Tuple x .. (Tuple y z )  .. ) : kind_scope.\n\nFixpoint arg_length (ty: Kind) :=\nmatch ty with\n| Tuple _ r => S (arg_length r)\n| _ => O\nend.\n\nDefinition arg_length_order (ty1 ty2: Kind) :=\n  arg_length ty1 < arg_length ty2.\n\nLemma arg_length_order_wf': forall len ty, arg_length ty < len -> Acc arg_length_order ty.\nProof.\n  unfold arg_length_order; induction len; intros.\n  - inversion H.\n  - refine (Acc_intro _ _); intros.\n    eapply (IHlen y).\n\n    apply lt_n_Sm_le in H.\n    apply (lt_le_trans _ _ _ H0 H).\nDefined.\n\nLemma arg_length_order_wf: well_founded arg_length_order.\nProof.\n  cbv [well_founded]; intros.\n  eapply arg_length_order_wf'.\n  eauto.\nDefined.\n\nFixpoint vec_to_nprod (A: Type) n (v: Vector.t A n): A^n :=\n  match v with\n  | [] => tt\n  | x::xs => (x, vec_to_nprod A _ xs)\n  end%vector.\n\nFixpoint insert_rightmost_unit (ty: Kind): Kind :=\nmatch ty with\n| Tuple l r => Tuple l (insert_rightmost_unit r)\n| Unit => Unit\n| x => Tuple x Unit\nend.\n\nFixpoint remove_rightmost_unit (ty: Kind): Kind :=\nmatch ty with\n| Tuple l Unit => l\n| Tuple l r => Tuple l (remove_rightmost_unit r)\n| x => x\nend.\n\nFixpoint denote_kind (ty: Kind): Type :=\n  match ty with\n  | Tuple l r => denote_kind l * denote_kind r\n  | Bit => bool\n  | Vector ty n => Vector.t (denote_kind ty) n\n  | Unit => unit\n  end.\n\nFixpoint kind_default (ty: Kind): denote_kind ty :=\n  match ty return denote_kind ty with\n  | Tuple l r => (kind_default l, kind_default r)\n  | Bit => false\n  | Vector ty n => const (kind_default ty) n\n  | Unit => tt\n  end.\n\nLemma blank_rew: forall ty ty' H x, eq_rect ty (fun (_ : Kind) => Kind) x ty' H = x.\nProof.\n  intros.\n  destruct H.\n  simpl.\n  reflexivity.\nQed.\n\nLocal Open Scope category_scope.\n\nFixpoint insert_rightmost_tt `{A: Arrow Kind Unit Tuple} (ty: Kind): ty ~> (insert_rightmost_unit ty) :=\n  match ty as ty' return ty' ~> (insert_rightmost_unit ty') with\n  | Tuple l r => second (insert_rightmost_tt r)\n  | Unit => id\n  | Bit => uncancelr\n  | Vector t n => uncancelr\n  end.\n\nFixpoint denote_apply_rightmost_tt (x: Kind)\n  : denote_kind (remove_rightmost_unit x) -> denote_kind x\n  :=\n  match x as x' return denote_kind (remove_rightmost_unit x') -> denote_kind x' with\n  | Tuple l r =>\n    let rec := denote_apply_rightmost_tt r in\n    match r as r' return\n      (denote_kind (remove_rightmost_unit r') -> denote_kind r') ->\n        denote_kind (remove_rightmost_unit (Tuple l r')) -> denote_kind (Tuple l r')\n      with\n    | Unit => fun f x => (x, tt)\n    | _ => fun f p => (fst p, f (snd p))\n    end rec\n  | _ => fun x => x\n  end.\n\nFixpoint apply_rightmost_tt `{A: Arrow Kind Unit Tuple} (x: Kind)\n  : remove_rightmost_unit x ~> x\n  :=\n  match x as x' return remove_rightmost_unit x' ~> x' with\n  | Tuple l r =>\n    let rec := apply_rightmost_tt r in\n    match r as r' return\n      (remove_rightmost_unit r' ~> r') -> remove_rightmost_unit (Tuple l r') ~> Tuple l r'\n      with\n    | Unit => fun f => uncancelr\n    | _ => fun f => second f\n    end rec\n  | _ => id\n  end.\n\n(* Avoid eq_rect type equality rewriting by inductively matching the Kind\n* structure. *)\nFixpoint rewrite_or_default (x y: Kind): denote_kind x -> denote_kind y :=\n  match x as x' return denote_kind x' -> denote_kind y with\n  | Unit =>\n      match y with\n      | Unit => fun a => a\n      | _ => fun _ => kind_default _\n      end\n  | Tuple l r =>\n      match y with\n      | Tuple ll rr => fun '(a,b) => (rewrite_or_default l ll a, rewrite_or_default r rr b)\n      | _ => fun _ => kind_default _\n      end\n  | Vector t n =>\n      match y with\n      | Vector t2 n2 => fun a => resize_default (kind_default _) _ (Vector.map (rewrite_or_default t t2) a)\n      | _ => fun _ => kind_default _\n      end\n  | Bit =>\n      match y with\n      | Bit => fun a => a\n      | _ => fun _ => kind_default _\n      end\n  end.\n\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/investigations/Arrow/ArrowKind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21602354267437587}}
{"text": "(* (c) Copyright 2006-2018 Microsoft Corporation and Inria.                  *)\n(* Distributed under the terms of CeCILL-B.                                  *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nFrom fourcolor Require Import color ctree chromogram gtree.\n\n(******************************************************************************)\n(* This is the first phase of a D-reducibility step: removing from the set of *)\n(* (partial) chromograms set those that match a set of admissible colorings.  *)\n(* The result of this step is a partition of the set into deleted and         *)\n(* remaining chromograms, represented by a gtree_pair. To save overhead we    *)\n(* do a single pass over the gtree, passing down a list of matching ctree's   *)\n(* to delete. In the proof this list has size at most 32, and usually size at *)\n(* most 8.                                                                    *)\n(* Main definitions:                                                          *)\n(*  gtree_restriction == a monomorphic type representing a set of trace       *)\n(*                    matches to be removed from a gtree. It is equivalent to *)\n(*                    seq (bit_stack * ctree), with each pair (bs, ct) in the *)\n(*                    sequence standing for the 'matches' (bs, et, w) such    *)\n(*                    matchpg bs et w, and ctree_mem ct et.                   *)\n(*  gtr_cons bs ct gtr == adds the pair (bs, ct) to gtr : gtree_restriction.  *)\n(*  gtr_mem gtr w <=> the gtree_restriction gtr contains a match (bs, et, w)  *)\n(*                    with the partial chromogram w.                          *)\n(*                    the set repesented by ctr : ctree_restriction.          *)\n(* gtr_split k r0 r1 r2 r3 gtr == continuation-passing style split of gtr;    *)\n(*                    adds to each gtree_restriction r_i the (bs, ct) pairs   *)\n(*                    repesenting matches (bs, et, w) that correspond 1-to-1  *)\n(*                    to matches (bs', e :: et, s_i :: w) in gtr, where s_i   *)\n(*                    is the ith gram_symbol in [Gskip, Gpush, Gpop0, Gpop1], *)\n(*                    then calls k on the resulting 4-tuple. With gtr_split   *)\n(*                    we can view and eliminate a gtree_restriction as a      *)\n(*                    gtree - both denote sets of chromogram.                 *)\n(* gtree_restrict gt gtr == a gtree_pair partition pt of gt : gtree, whose    *)\n(*                    first component is obtained by removing all matches in  *)\n(*                    gtr : ctree_restriction from those in gt.               *)\n(* gtr_match[0123] gtr <=> the matches represented by gtr contain the size 1  *)\n(*                    chromogram [s_i], where s_i is the ith gram_symbol, and *)\n(*                    i is [0123], respectively.                              *)\n(*  gtp_e_01, etc. == a statically defined gtree_pair of GtreeEmpty and       *)\n(*                    GtreeLeaf01 (there 24 variation in all, e.g., gtp_0_e). *)\n(******************************************************************************)\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection GtreeRestrict.\n\nInductive gtree_restriction :=\n  GtrNil | GtrCons of bit_stack & ctree & gtree_restriction.\n\n(* A restriction set represents a set of matching chromograms *)\n\nFixpoint gtr_mem r w :=\n  if r isn't GtrCons bs t r' then false else\n  has_match bs (ctree_mem t) w || gtr_mem r' w.\n\nDefinition gtr_cons bs t r := if ctree_empty t then r else GtrCons bs t r.\n\nLemma gtr_mem_cons bs t r w :\n gtr_mem (gtr_cons bs t r) w = has_match bs (ctree_mem t) w || gtr_mem r w.\nProof.\nrewrite /gtr_cons; case: ifP => // /ctree_empty_eq-> /=; rewrite orb_idl //.\nby case/has_matchP; case.\nQed.\n\nSection GtrSplit.\n\nVariables (A : Set) (continue : forall r0 r1 r2 r3 : gtree_restriction, A).\n\nFixpoint gtr_split r0 r1 r2 r3 r :=\n  match r with\n  | GtrNil => continue r0 r1 r2 r3\n  | GtrCons bs (CtreeNode t1 t2 t3) r' =>\n      let r02 := GtrCons (Bpush0 bs) t2 r0 in\n      let r03 := GtrCons (Bpush1 bs) t3 r0 in\n      let r023 := GtrCons (Bpush0 bs) t2 r03 in\n      let r1' := if t1 is CtreeEmpty then r1 else GtrCons bs t1 r1 in\n      let r2' bs' t':= GtrCons bs' t' r2 in\n      let r3' bs' t' := GtrCons bs' t' r3 in\n      match t2, t3, bs with\n      | CtreeEmpty, CtreeEmpty, _ => gtr_split r0 r1' r2 r3 r'\n      | CtreeEmpty, _, Bstack0 => gtr_split r03 r1' r2 r3 r'\n      | CtreeEmpty, _, Bpush0 bs' => gtr_split r03 r1' r2 (r3' bs' t3) r'\n      | CtreeEmpty, _, Bpush1 bs' => gtr_split r03 r1' (r2' bs' t3) r3 r'\n      | _, CtreeEmpty, Bstack0 => gtr_split r02 r1' r2 r3 r'\n      | _, CtreeEmpty, Bpush0 bs' => gtr_split r02 r1' (r2' bs' t2) r3 r'\n      | _, CtreeEmpty, Bpush1 bs' => gtr_split r02 r1' r2 (r3' bs' t2) r'\n      | _, _, Bstack0 => gtr_split r023 r1' r2 r3 r'\n      | _, _, Bpush0 bs' => gtr_split r023 r1' (r2' bs' t2) (r3' bs' t3) r'\n      | _, _, Bpush1 bs' => gtr_split r023 r1' (r2' bs' t3) (r3' bs' t2) r'\n      end\n  | GtrCons _ _ r' => gtr_split r0 r1 r2 r3 r'\n  end.\n\nLemma gtr_split_some bs t1 t2 t3 r0 r1 r2 r3 r :\n let cons_pop t t' r' := match bs with\n   | Bstack0 => r'\n   | Bpush0 bs' => gtr_cons bs' t r'\n   | Bpush1 bs' => gtr_cons bs' t' r'\n   end in\n gtr_split r0 r1 r2 r3 (GtrCons bs (CtreeNode t1 t2 t3) r) =\n gtr_split (gtr_cons (Bpush0 bs) t2 (gtr_cons (Bpush1 bs) t3 r0))\n           (gtr_cons bs t1 r1) (cons_pop t2 t3 r2) (cons_pop t3 t2 r3) r.\nProof.\nby case: bs => [|bs|bs] /=; rewrite !fold_ctree_empty /gtr_cons; do 2!case: ifP.\nQed.\n\nEnd GtrSplit.\n\nLet gsplit r s :=\n  let gtk gt0 gt1 gt2 gt3 := @gram_symbol_rec (fun _ => _) gt0 gt1 gt2 gt3 s in\n  gtr_split gtk GtrNil GtrNil GtrNil GtrNil r.\n\nLemma gtr_split_eq A rk r :\n @gtr_split A rk GtrNil GtrNil GtrNil GtrNil r =\n   rk (gsplit r Gpush) (gsplit r Gskip) (gsplit r Gpop0) (gsplit r Gpop1).\nProof.\nrewrite /gsplit; move: GtrNil => rn.\nmove: rn {2 4 6 8 10}rn {3 6 9 12 15}rn {4 8 12 16 20}rn.\nby elim: r => // bs [t1 t2 t3|lf|] r IHr *; rewrite ?gtr_split_some -IHr.\nQed.\n\nLemma gtr_mem_gsplit r s w : gtr_mem r (s :: w) = gtr_mem (gsplit r s) w.\nProof.\nrewrite /gsplit; move Drn: GtrNil => rn; rewrite -[lhs in lhs = _]orFb.\nhave <-: gtr_mem (@gram_symbol_rec (fun _ => _) rn rn rn rn s) w = false.\n  by rewrite -Drn; case: s.\nelim: r rn {2 4}rn {3 6}rn {4 8}rn {Drn}; first by move=> *; rewrite /= orbF.\nmove=> bs [t1 t2 t3|lf|] r IHr r0 r1 r2 r3; rewrite ?gtr_split_some -?{}IHr;\n  try by rewrite [s :: w]lock /= -lock; case: has_matchP => [[[]] | ].\ncase: s; rewrite /= ?gtr_mem_cons orbA {-2 3}[orb]lock orbC -?orbA -!lock //;\n  by case: bs => *; rewrite ?gtr_mem_cons.\nQed.\n\nFixpoint gtr_match0 r :=\n  match r with\n  | GtrNil => false\n  | GtrCons _ (CtreeNode _ (CtreeLeaf _) _) _ => true\n  | GtrCons _ (CtreeNode _ _ (CtreeLeaf _)) _ => true\n  | GtrCons _ _ r' => gtr_match0 r'\n  end.\n\nLemma gtr_match0E r : gtr_match0 r = gtr_mem r [:: Gpush].\nProof.\nby elim: r => //= bs [] //= t1 t2 t3 r <-; case: t2 => //; case: t3.\nQed.\n\nFixpoint gtr_match1 r :=\n  match r with\n  | GtrNil => false\n  | GtrCons _ (CtreeNode (CtreeLeaf _) _ _) _ => true\n  | GtrCons _ _ r' => gtr_match1 r'\n  end.\n\nLemma gtr_match1E r : gtr_match1 r = gtr_mem r [:: Gskip].\nProof. by elim: r => //= bs [] //= t1 t2 t3 r <-; case: t1. Qed.\n\nFixpoint gtr_match2 r :=\n  match r with\n  | GtrNil => false\n  | GtrCons (Bpush0 _) (CtreeNode _ (CtreeLeaf _) _) _ => true\n  | GtrCons (Bpush1 _) (CtreeNode _ _ (CtreeLeaf _)) _ => true\n  | GtrCons _ _ r' => gtr_match2 r'\n  end.\n\nLemma gtr_match2E r : gtr_match2 r = gtr_mem r [:: Gpop0].\nProof.\nby elim: r => //= [] [|bs|bs] [] //= t1 t2 t3 r <-; [case: t2 | case: t3].\nQed.\n\nFixpoint gtr_match3 r :=\n  match r with\n  | GtrNil => false\n  | GtrCons (Bpush0 _) (CtreeNode _ _ (CtreeLeaf _)) _ => true\n  | GtrCons (Bpush1 _) (CtreeNode _ (CtreeLeaf _) _) _ => true\n  | GtrCons _ _ r' => gtr_match3 r'\n  end.\n\nLemma gtr_match3E r : gtr_match3 r = gtr_mem r [:: Gpop1].\nProof.\nby elim: r => //= [] [|bs|bs] [] //= t1 t2 t3 r <-; [case: t3 | case: t2].\nQed.\n\nDefinition gtp_0_e := GtreePair GtreeLeaf0 GtreeEmpty.\nDefinition gtp_1_e := GtreePair GtreeLeaf1 GtreeEmpty.\nDefinition gtp_2_e := GtreePair GtreeLeaf2 GtreeEmpty.\nDefinition gtp_3_e := GtreePair GtreeLeaf3 GtreeEmpty.\nDefinition gtp_01_e := GtreePair GtreeLeaf01 GtreeEmpty.\nDefinition gtp_12_e := GtreePair GtreeLeaf12 GtreeEmpty.\nDefinition gtp_13_e := GtreePair GtreeLeaf13 GtreeEmpty.\nDefinition gtp_23_e := GtreePair GtreeLeaf23 GtreeEmpty.\n\nDefinition gtp_e_0 := GtreePair GtreeEmpty GtreeLeaf0.\nDefinition gtp_e_1 := GtreePair GtreeEmpty GtreeLeaf1.\nDefinition gtp_e_2 := GtreePair GtreeEmpty GtreeLeaf2.\nDefinition gtp_e_3 := GtreePair GtreeEmpty GtreeLeaf3.\nDefinition gtp_e_01 := GtreePair GtreeEmpty GtreeLeaf01.\nDefinition gtp_e_12 := GtreePair GtreeEmpty GtreeLeaf12.\nDefinition gtp_e_13 := GtreePair GtreeEmpty GtreeLeaf13.\nDefinition gtp_e_23 := GtreePair GtreeEmpty GtreeLeaf23.\n\nDefinition gtp_0_1 := GtreePair GtreeLeaf0 GtreeLeaf1.\nDefinition gtp_1_0 := GtreePair GtreeLeaf1 GtreeLeaf0.\nDefinition gtp_1_2 := GtreePair GtreeLeaf1 GtreeLeaf2.\nDefinition gtp_2_1 := GtreePair GtreeLeaf2 GtreeLeaf1.\nDefinition gtp_1_3 := GtreePair GtreeLeaf1 GtreeLeaf3.\nDefinition gtp_3_1 := GtreePair GtreeLeaf3 GtreeLeaf1.\nDefinition gtp_2_3 := GtreePair GtreeLeaf2 GtreeLeaf3.\nDefinition gtp_3_2 := GtreePair GtreeLeaf3 GtreeLeaf2.\n\nLemma gtree_partition_left t :\n  gtree_pair_partition t (GtreePair t GtreeEmpty).\nProof. by move=> w; rewrite gtree_mem_empty; case: ifP. Qed.\n\nLemma gtree_partition_right t :\n  gtree_pair_partition t (GtreePair GtreeEmpty t).\nProof. by move=> w; rewrite gtree_mem_empty; case: ifP. Qed.\n\nFixpoint gtree_restrict t r {struct t} :=\n  match r, t with\n  | GtrNil, _ => GtreePair GtreeEmpty t\n  | _, GtreeNode t0 t1 t2 t3 =>\n    let cont r0 r1 r2 r3 :=\n      gtree_cons_pairs t (gtree_restrict t0 r0) (gtree_restrict t1 r1)\n                         (gtree_restrict t2 r2) (gtree_restrict t3 r3) in\n    gtr_split cont GtrNil GtrNil GtrNil GtrNil r\n  | _, GtreeLeaf0 => if gtr_match0 r then gtp_0_e else gtp_e_0\n  | _, GtreeLeaf1 => if gtr_match1 r then gtp_1_e else gtp_e_1\n  | _, GtreeLeaf2 => if gtr_match2 r then gtp_2_e else gtp_e_2\n  | _, GtreeLeaf3 => if gtr_match3 r then gtp_3_e else gtp_e_3\n  | _, GtreeLeaf01 =>\n    if gtr_match0 r\n    then if gtr_match1 r then gtp_01_e else gtp_0_1\n    else if gtr_match1 r then gtp_1_0 else gtp_e_01\n  | _, GtreeLeaf12 =>\n    if gtr_match1 r\n    then if gtr_match2 r then gtp_12_e else gtp_1_2\n    else if gtr_match2 r then gtp_2_1 else gtp_e_12\n  | _, GtreeLeaf13 =>\n    if gtr_match1 r\n    then if gtr_match3 r then gtp_13_e else gtp_1_3\n    else if gtr_match3 r then gtp_3_1 else gtp_e_13\n  | _, GtreeLeaf23 =>\n    if gtr_match2 r\n    then if gtr_match3 r then gtp_23_e else gtp_2_3\n    else if gtr_match3 r then gtp_3_2 else gtp_e_23\n  | _, GtreeEmpty => empty_gtree_pair\n  end.\n\nLet gtpl := gtree_partition_left.\nLet gtpr := gtree_partition_right.\n\nTheorem gtree_restrict_partition t r :\n  gtree_pair_partition t (gtree_restrict t r).\nProof.\nelim: t r => [t0 IHt0 t1 IHt1 t2 IHt2 t3 IHt3|||||||||] r /=;\n  case Dr: r => [|bs ct r']; do [exact: gtpr | rewrite -{r' ct bs}Dr];\n  by [ case: ifP => _; [apply: gtpl | apply: gtpr]\n     | do 2![case: ifP] => _ _ [|[] []]\n     | rewrite gtr_split_eq; apply: gtree_cons_pairs_partition].\nQed.\n\nTheorem gtree_mem0_restrict t r w :\n  let t' := gtree_pair_sub (gtree_restrict t r) false in\n  gtree_mem t' w = gtree_mem t w && gtr_mem r w.\nProof.\npose gm := =^~ (gtr_match0E, gtr_match1E, gtr_match2E, gtr_match3E).\nelim: t => /= [t0 IHt0 t1 IHt1 t2 IHt2 t3 IHt3|||||||||] in r w *;\n  case Dr: r => [|bs ct r'];\n  do [ by rewrite /= gtree_mem_empty ?andbF | rewrite -{bs ct r'}Dr];\n  try by do 2?case: ifP => /(pair gm){}gm; case: w => [|[][]] //; rewrite !gm.\nrewrite gtr_split_eq gtree_mem0_cons_pairs; try exact: gtree_restrict_partition.\nby case: w => [|s w]; rewrite // (gtr_mem_gsplit r); case: s => /=.\nQed.\n\nEnd GtreeRestrict.\n", "meta": {"author": "coq-community", "repo": "fourcolor", "sha": "e831b0b00e264285f91938917a0a5ef64ec1a829", "save_path": "github-repos/coq/coq-community-fourcolor", "path": "github-repos/coq/coq-community-fourcolor/fourcolor-e831b0b00e264285f91938917a0a5ef64ec1a829/theories/gtreerestrict.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21594799526356653}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export subst_tacs2.\nRequire Export computation_preserve1.\n(*Require Export list. (* WTF!! *)*)\n(** printing #  $\\times$ #×# *)\n(** printing <=>  $\\Leftrightarrow$ #&hArr;# *)\n(** printing $  $\\times$ #×# *)\n(** printing &  $\\times$ #×# *)\n\n\n(* begin hide *)\n\n(* Definition simulation_relation_step (n:nat )(P: (list NTerm )-> (list NTerm ) -> Type):=\n  forall (l1 l2: list NTerm),\n    length l1 = n\n    -> length l2 = n\n    -> (forall m, m<n -> compute_step (selectnt m l1) = csuccess (selectnt m l2))\n    -> P l1 l2.\n\nDefinition simulation_relation (n:nat )(P: (list NTerm )-> (list NTerm ) -> Type):=\n  forall (l1 l2: list NTerm),\n    length l1 = n\n    -> length l2 = n\n    -> (forall m, m<n -> computes_to_value (selectnt m l1) (selectnt m l2))\n    -> P l1 l2.\n*)\n\n(*\nLemma computek_preserves_nt_wf :\n  forall k t1 t2,\n    compute_at_most_k_steps k t1 = csuccess t2\n    -> nt_wf t1\n    -> nt_wf t2.\nProof.\n  induction k; intros ? ?  Hck Hpt1; inverts Hck as Hck; auto.\n  remember (compute_at_most_k_steps k t1) as rec. destruct rec; inverts Hck as Hck.\n  symmetry in Heqrec. inverts Hck as Hck. apply IHk in Heqrec; auto.\n  apply preserve_nt_wf_compute_step in Hck; auto.\nQed.\n\nTheorem computes_to_ovalue_preserves_nt_wf :\n  forall t1 t2,\n    computes_to_ovalue t1 t2\n    -> nt_wf t1\n    -> nt_wf t2.\nProof.\n  intros ? ? Hcv Hpt1. inverts Hcv as Hcv. inverts Hcv as Hcv.\n  apply computek_preserves_nt_wf in Hcv; auto.\nQed.\n*)\n\n(*\nTheorem preserve_program : forall (t1 t2 :NTerm),\n  (computes_to_value t1 t2) -> (isprogram t1) ->(isprogram t2).\nProof.\n intros ? ? Hcv Hpt1. inverts Hcv as Hcv. inverts Hcv as Hcv.\n  apply computek_preserves_program in Hcv; auto.\nQed.\n*)\n\n\n(*\nLemma lsubst_subst :\n  forall t v arg sub,\n    subst (lsubst t (sub_filter sub [v])) v (lsubst arg sub)\n    = lsubst (subst t v arg) sub.\nProof.\n  intro. nterm_ind t Case.\n\n  - Case \"vterm\"; sp; allsimpl.\n    unfold subst; simpl.\n    remember (beq_var v n); destruct b.\n    apply beq_var_eq in Heqb; subst.\n    rewrite sub_find_sub_filter; simpl.\n    rewrite <- beq_var_refl; auto.\n    left; auto.\n    symmetry in Heqb.\n    apply beq_var_false_not_eq in Heqb.\nQed.\n*)\n\n(*\nLemma compute_step_preserves_lsubst :\n  forall t1 t2 sub,\n    (forall v u, LIn (v, u) sub -> isprogram u)\n    -> compute_step t1 = csuccess t2\n    -> compute_step (lsubst t1 sub) = csuccess (lsubst t2 sub).\nProof.\n  intro. nterm_ind t1 Case.\n\n  - Case \"vterm\"; sp; allsimpl.\n    inversion H0.\n\n  - Case \"oterm\".\n    rename H into IHind.\n    intros t2 sub Hsub Hcomp.\n    dopid o as [c| nc] SCase.\n\n    + SCase \"Can\".\n      allsimpl; inverts Hcomp; auto.\n\n    + SCase \"NCan\".\n      (*simpl in Hcomp.*)\n      dlist lbt SSCase as [| arg1].\n      try (inverts Hcomp; fail).\n      SSCase \"conscase\".\n      simpl in Hcomp;\n        destruct arg1 as [arg1vs arg1nt];\n        dlist arg1vs SSSCase as [|arg1v1];\n        destruct arg1nt as [v89| arg1o arg1bts];\n        inversion Hcomp;\n        thin_trivials.\n      dopid arg1o as [arg1c | arg1nc ] SSSSCase.\n\n      * SSSSCase \"Can\". (* arg1 (principle in all cases) is canonical. *)\n        dopid_noncan nc SSSSSCase.\n\n        SSSSSCase \"NApply\".\n        applydup compute_step_apply_success in Hcomp; sp; subst.\n        unfold compute_step_apply in Hcomp.\n        (* XXXXXXXXXXXXXXXX *)\n        inversion Hcomp; subst.\n        simpl.\n        rewrite sub_filter_nil_r.\n        rewrite bvar_renamings_subst_isprogram; simpl; auto.\n\n        apply subst_preserves_wf; auto.\n        generalize (Hbf (bterm [] (oterm (Can NLambda) [bterm [v] b]))); simpl; sp.\n        dimp H.\n        inversion hyp; subst.\n        inversion H1; subst.\n        generalize (H3 (bterm [v] b)); simpl; sp.\n        dimp H0.\n        inversion hyp0; subst; auto.\n        generalize (Hbf (bterm [] arg)); simpl; sp.\n        dimp H.\n        inversion hyp; subst; auto.\n\n        SSSSSCase \"NFix\".\n        simpl in Hcomp.\n        applydup compute_step_fix_success in Hcomp; sp; subst.\n        unfold compute_step_fix in Hcomp.\n        inversion Hcomp; subst.\n        constructor; sp.\n        allsimpl; sp; subst.\n        constructor.\n        generalize (Hbf (bterm [] (oterm (Can arg1c) arg1bts))); sp.\n        dimp H.\n        inversion hyp; subst; auto.\n        constructor.\n        constructor; sp.\n\n        SSSSSCase \"NSpread\".\n        simpl in Hcomp.\n        applydup compute_step_spread_success in Hcomp; sp; subst.\n        inversion Hcomp; subst; allsimpl.\n        apply lsubst_preserves_wf; allsimpl; sp.\n        generalize (Hbf (bterm [va, vb] arg)); simpl; sp.\n        dimp H.\n        inversion hyp; subst; auto.\n        inversion H; subst.\n        generalize (Hbf (bterm [] ((|u, b|)))); sp.\n        dimp H0.\n        inversion hyp; subst.\n        inversion H2; subst.\n        generalize (H4 (bterm [] u)); simpl; sp.\n        dimp H1.\n        inversion hyp0; subst; auto.\n        inversion H; subst.\n        generalize (Hbf (bterm [] ((|a, u|)))); sp.\n        dimp H0.\n        inversion hyp; subst.\n        inversion H2; subst.\n        generalize (H4 (bterm [] u)); simpl; sp.\n        dimp H1.\n        inversion hyp0; subst; auto.\n\n        SSSSSCase \"NDecide\".\n        simpl in Hcomp.\n        applydup compute_step_decide_success in Hcomp; sp; subst.\n        inversion Hcomp; subst; allsimpl.\n        apply lsubst_preserves_wf; allsimpl; sp.\n        generalize (Hbf (bterm [v1] t1)); simpl; sp.\n        dimp H.\n        inversion hyp; subst; auto.\n        inversion H; subst.\n        generalize (Hbf (bterm [] (oterm (Can NInl) [bterm [] u0]))); sp.\n        dimp H0.\n        inversion hyp; subst.\n        inversion H2; subst.\n        generalize (H4 (bterm [] u0)); simpl; sp.\n        dimp H1.\n        inversion hyp0; subst; auto.\n        inversion Hcomp; subst; allsimpl.\n        apply lsubst_preserves_wf; allsimpl; sp.\n        generalize (Hbf (bterm [v2] t0)); simpl; sp.\n        dimp H.\n        inversion hyp; subst; auto.\n        inversion H; subst.\n        generalize (Hbf (bterm [] (oterm (Can NInr) [bterm [] u0]))); sp.\n        dimp H0.\n        inversion hyp; subst.\n        inversion H2; subst.\n        generalize (H4 (bterm [] u0)); simpl; sp.\n        dimp H1.\n        inversion hyp0; subst; auto.\n\n        SSSSSCase \"NCbv\".\n        simpl in Hcomp.\n        applydup compute_step_cbv_success in Hcomp; sp; subst.\n        inversion Hcomp; subst; allsimpl.\n        apply lsubst_preserves_wf; allsimpl; sp.\n        generalize (Hbf (bterm [v] x)); simpl; sp.\n        dimp H.\n        inversion hyp; subst; auto.\n        inversion H; subst.\n        generalize (Hbf (bterm [] (oterm (Can arg1c) arg1bts))); sp.\n        dimp H0.\n        inversion hyp; subst; auto.\n\n        SSSSSCase \"NCompOp\".\n        acdmit.\n\n        SSSSSCase \"NArithOp\".\n        acdmit.\n\n        SSSSSCase \"NCanTest\".\n        simpl in Hcomp.\n        applydup compute_step_can_test_success in Hcomp; sp; subst.\n        destruct (canonical_form_test_for c arg1c).\n        generalize (Hbf (bterm [] arg2nt)); simpl; sp.\n        dimp H.\n        inversion hyp; subst; auto.\n        generalize (Hbf (bterm [] arg3nt)); simpl; sp.\n        dimp H.\n        inversion hyp; subst; auto.\n\n      * SSSSCase \"NCan\".\n        unfold compute_step in Hcomp; fold (compute_step (oterm (NCan arg1nc) arg1bts)) in Hcomp.\n        remember (compute_step (oterm (NCan arg1nc) arg1bts)) as crt2s.\n        destruct crt2s; inversion Hcomp; subst.\n        symmetry in Heqcrt2s.\n        apply IHind with (lv := []) in Heqcrt2s; auto; simpl.\n        constructor; simpl; sp; subst.\n        constructor; auto.\n        apply Hbf; simpl; right; auto.\n        left; auto.\n        inversion Hiswf; subst.\n        generalize (H1 (bterm [] (oterm (NCan arg1nc) arg1bts))); simpl; sp.\n        dimp H.\n        inversion hyp; subst; sp.\nQed.\n\nTheorem computes_to_value_lsubst :\n  forall t1 t2 sub,\n    (forall v u, LIn (v, u) sub -> isprogram u)\n    -> computes_to_value t1 t2\n    -> computes_to_value (lsubst t1 sub) t2.\nProof.\n  intros.\n  allunfold computes_to_value; allunfold reduces_to; sp.\n  rewrite compute_at_most_k_steps_eq_f in H0.\n  revert t1 t2 H1 H0.\n  induction k; allsimpl; sp.\n  inversion H0; subst.\n  exists 0; simpl.\n  rewrite lsubst_trivial; sp.\n  apply H with (v := v); sp.\n  apply isvalue_closed in H1.\n  unfold closed in H1.\n  rewrite H1 in H3; allsimpl; sp.\n\n  remember (compute_step t1); destruct c.\n  applydup IHk in H0; sp.\nQed.*)\n\nLemma compute_step_mk_cbv_ncan {p} :\n  forall lib c l v u,\n    compute_step lib (mk_cbv (oterm (@NCan p c) l) v u)\n    = match compute_step lib (oterm (NCan c) l) with\n        | csuccess f => csuccess (mk_cbv f v u)\n        | cfailure str ts => cfailure str ts\n      end.\nProof.\n  introv; rw @compute_step_eq_unfold; sp.\nQed.\n\nLemma compute_step_mk_cbv_abs {o} :\n  forall (lib : @library o) x l v u,\n    compute_step lib (mk_cbv (oterm (Abs x) l) v u)\n    = match compute_step_lib lib x l with\n        | csuccess f => csuccess (mk_cbv f v u)\n        | cfailure str ts => cfailure str ts\n      end.\nProof.\n  introv; rw @compute_step_eq_unfold; sp.\nQed.\n\nLemma reduces_to_apply_id {p} :\n  forall lib (t : @NTerm p), reduces_to lib (mk_apply mk_id t) t.\nProof.\n  unfold reduces_to; sp.\n  exists 1.\n  simpl.\n  unfold subst; simpl; sp.\nQed.\n\nHint Immediate reduces_to_apply_id.\n\nLemma reduces_toc_apply_id {p} :\n  forall lib (t : @CTerm p), reduces_toc lib (mkc_apply mkc_id t) t.\nProof.\n  destruct t; unfold reduces_toc; simpl.\n  fold (@mk_id p); sp.\nQed.\n\nHint Immediate reduces_toc_apply_id.\n\nLemma is_compute_step_apply {p} :\n  forall lib c l a,\n    @compute_step p lib (mk_apply (oterm (Can c) l) a)\n    = compute_step_apply c (mk_apply (oterm (Can c) l) a) l [nobnd a].\nProof.\n  sp.\nQed.\n\nLemma is_compute_step_decide {p} :\n  forall lib c l x f y g,\n    compute_step lib (mk_decide (oterm (@Can p c) l) x f y g)\n    = compute_step_decide c (mk_decide (oterm (Can c) l) x f y g) l [bterm [x] f, bterm [y] g].\nProof.\n  sp.\nQed.\n\n\n\n(*\nLemma compute_at_most_k_steps_marker {o} :\n  forall (lib : @library o) k t,\n    ismrk lib t\n    -> compute_at_most_k_steps lib k t\n       = csuccess t.\nProof.\n  induction k; introv ism; simpl; tcsp.\n  rw IHk; auto.\nQed.\n*)\n\n(*\nLemma reduces_in_atmost_k_steps_marker {o} :\n  forall (lib : @library o) k mrk l v,\n    reduces_in_atmost_k_steps lib (oterm (Mrk mrk) l) v k\n    -> v = oterm (Mrk mrk) l.\nProof.\n  introv h.\n  unfold reduces_in_atmost_k_steps in h.\n  rw @compute_at_most_k_steps_marker in h; ginv; auto.\nQed.\n*)\n\n(*\nLemma ismrk_implies {o} :\n  forall lib (t : @NTerm o),\n    ismrk lib t ->\n    {opabs : opabs\n     & {bs : list BTerm\n     & t = oterm (Abs opabs) bs\n     # find_entry lib opabs bs = None}}.\nProof.\n  introv ism.\n  destruct t as [v|f|op bs]; allsimpl; tcsp.\n  dopid op as [can|ncan|exc|abs] Case; allsimpl; tcsp.\n  eexists; eexists; dands; eauto.\nQed.\n *)\n\n(*\nLemma reduces_to_marker {p} :\n  forall lib e (t : @NTerm p), ismrk lib e -> reduces_to lib e t -> t = e.\nProof.\n  introv ism r.\n  unfold reduces_to in r; exrepnd.\n  revert e t ism r0.\n  induction k; introv ism comp.\n  - allrw @reduces_in_atmost_k_steps_0; auto.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    apply ismrk_implies in ism; exrepnd; subst.\n    csunf comp1; allsimpl.\n    apply compute_step_lib_success in comp1; exrepnd; subst.\n    unfold found_entry in comp2.\n    rw ism1 in comp2; ginv.\nQed.\n *)\n\n(*\nLemma compute_at_most_k_stepsf_marker {o} :\n  forall lib k (t u : @NTerm o),\n    ismrk lib t\n    -> compute_at_most_k_stepsf lib k t = csuccess u\n    -> u = t.\nProof.\n  introv i c.\n  apply (reduces_to_marker lib t u); auto.\n  exists k.\n  unfold reduces_in_atmost_k_steps.\n  rw @compute_at_most_k_steps_eq_f; auto.\nQed.\n *)\n\nLemma iscan_mk_exception {o} :\n  forall n e : @NTerm o, iscan (mk_exception n e) -> False.\nProof.\n  introv isc.\n  apply iscan_implies in isc; repndors; exrepnd; ginv.\nQed.\n\nLemma isvalue_mk_exception {o} :\n  forall n e : @NTerm o, isvalue (mk_exception n e) -> False.\nProof.\n  introv isv.\n  inversion isv as [? isp isc]; subst.\n  apply iscan_mk_exception in isc; sp.\nQed.\n\nLemma cbv_reduce0 {pp} :\n  forall lib t v u,\n    isprog t\n    -> @isprog pp u\n    -> hasvalue lib t\n    -> reduces_to lib (mk_cbv t v u) u.\nProof.\n  unfold hasvalue, computes_to_value, reduces_to.\n  introv ispt ispu comp; exrepnd.\n  revert t comp2 ispt.\n  induction k; simpl; sp.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    exists 1; rw @reduces_in_atmost_k_steps_S.\n    inversion comp0 as [? isp isc]; subst.\n    rw @compute_step_eq_unfold; simpl.\n\n    apply iscan_implies in isc; repndors; exrepnd; subst;\n    eexists; dands; eauto;\n    rw @reduces_in_atmost_k_steps_0; unfold apply_bterm; simpl;\n    rewrite lsubst_trivial2; simpl; sp; inj;\n    rw @isprogram_eq; sp.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    applydup @preserve_compute_step in comp2;\n      try (complete (allrw @isprogram_eq; sp)).\n    allrw @isprogram_eq.\n    applydup IHk in comp1; tcsp; exrepnd.\n    destruct t as [x|f|op bs].\n    { csunf comp2; ginv. }\n    { csunf comp2; ginv; GC.\n      eexists; eauto. }\n    dopid op as [c|nc|exc|abs] Case.\n\n    + Case \"Can\".\n      rw @compute_step_eq_unfold in comp2; allsimpl; ginv.\n      exists k0; auto.\n\n    + Case \"NCan\".\n      exists (S k0); allrw @reduces_in_atmost_k_steps_S.\n      rw @compute_step_eq_unfold; simpl.\n      rw comp2; simpl.\n      eexists; dands; eauto.\n\n    + Case \"Exc\".\n      provefalse.\n      rw @compute_step_eq_unfold in comp2; allsimpl; ginv.\n      allrw @isprog_eq; allapply @isprogram_exception_implies; exrepnd; subst; ginv.\n      fold_terms.\n      allrw (@fold_exception).\n      pose proof (reduces_to_exception lib (mk_exception a t) t') as ee;\n        repeat (autodimp ee hyp); sp; try (exists k; auto).\n      subst.\n      allapply @isvalue_mk_exception; sp.\n\n    + Case \"Abs\".\n      exists (S k0); allrw @reduces_in_atmost_k_steps_S.\n      rw @compute_step_eq_unfold; simpl.\n      rw comp2; simpl.\n      eexists; dands; eauto.\nQed.\n\nLemma isvalue_ncan {o} :\n  forall nc (bs : list (@BTerm o)),\n    isvalue (oterm (NCan nc) bs) -> False.\nProof.\n  introv isv.\n  inversion isv as [? isp isc]; subst.\n  apply iscan_implies in isc; repndors; exrepnd; ginv.\nQed.\n\nLemma isvalue_exc {o} :\n  forall (bs : list (@BTerm o)),\n    isvalue (oterm Exc bs) -> False.\nProof.\n  introv isv.\n  inversion isv as [? isp isc]; subst.\n  apply iscan_implies in isc; repndors; exrepnd; ginv.\nQed.\n\nLemma isvalue_abs {o} :\n  forall a (bs : list (@BTerm o)),\n    isvalue (oterm (Abs a) bs) -> False.\nProof.\n  introv isv.\n  inversion isv as [? isp isc]; subst.\n  apply iscan_implies in isc; repndors; exrepnd; ginv.\nQed.\n\nLemma isprog_vterm {o} :\n  forall v, @isprog o (vterm v) -> False.\nProof.\n  introv isp.\n  inversion isp; allsimpl; allapply not_assert_false; sp.\nQed.\n\nLemma cbv_reduce {p} :\n  forall lib t v u x,\n    @isprog p t\n    -> computes_to_value lib t x\n    -> reduces_to lib (mk_cbv t v u) (subst u v x).\nProof.\n  unfold hasvalue, computes_to_value, reduces_to.\n  introv isp comp; exrepnd.\n  revert dependent t.\n  induction k; simpl; introv isp e.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    exists 1; rw @reduces_in_atmost_k_steps_S.\n    rw @compute_step_eq_unfold; simpl.\n    destruct x as [x|f|op bs].\n    { allapply @isprog_vterm; sp. }\n    { eexists; dands; eauto.\n      unfold apply_bterm; simpl; allrw @fold_subst.\n      apply reduces_in_atmost_k_steps_0; auto. }\n\n    dopid op as [c|nc|exc|abs] Case; tcsp;\n    try (apply isvalue_ncan in comp; sp);\n    try (apply isvalue_exc in comp; sp);\n    try (apply isvalue_abs in comp; sp).\n\n    unfold apply_bterm; simpl.\n    eexists; dands; eauto.\n    rw @reduces_in_atmost_k_steps_0; auto.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n\n    applydup @preserve_compute_step in e1;\n      try (complete (allrw @isprogram_eq; sp)).\n    allrw @isprogram_eq.\n    applydup IHk in e0; sp.\n    destruct t as [z|f|op bs].\n    { allapply @isprog_vterm; sp. }\n    { csunf e1; allsimpl; ginv.\n      eexists; dands; eauto. }\n\n    dopid op as [c|nc|exc|abs] Case.\n\n    + Case \"Can\".\n      rw @compute_step_eq_unfold in e1; allsimpl; ginv.\n      exists k0; sp.\n\n    + Case \"NCan\".\n      exists (S k0); allrw @reduces_in_atmost_k_steps_S.\n      rw @compute_step_eq_unfold; simpl; rw e1; simpl.\n      eexists; dands; eauto.\n\n    + Case \"Exc\".\n      provefalse.\n      allrw @isprog_eq; allapply @isprogram_exception_implies; exrepnd; subst.\n      fold_terms.\n      allrw @fold_exception.\n      rw @compute_step_exception in e1; sp; ginv.\n      pose proof (reduces_to_exception lib (mk_exception a t) x) as ee;\n        repeat (autodimp ee hyp); sp; try (exists k; auto).\n      subst.\n      allapply @isvalue_mk_exception; sp.\n\n    + Case \"Abs\".\n      exists (S k0); allrw @reduces_in_atmost_k_steps_S.\n      rw @compute_step_eq_unfold; simpl; rw e1; simpl.\n      eexists; dands; eauto.\nQed.\n\nLemma isprog_sterm_implies_isvalue {o} :\n  forall (f : @ntseq o), isprog (sterm f) -> isvalue (sterm f).\nProof.\n  introv isp.\n  constructor; simpl; eauto 3 with slow.\nQed.\nHint Resolve isprog_sterm_implies_isvalue : slow.\n\nLemma if_hasvalue_cbv0 {p} :\n  forall lib t v u,\n    @isprog p t\n    -> hasvalue lib (mk_cbv t v u)\n    -> hasvalue lib t.\nProof.\n  unfold hasvalue, computes_to_value, reduces_to, reduces_in_atmost_k_steps.\n  intros lib t v u pt hv; exrepd.\n  allrewrite @compute_at_most_k_steps_eq_f.\n  revert t pt e.\n  induction k; simpl; introv isp comp; ginv; tcsp.\n\n  - allapply @isvalue_ncan; sp.\n\n  - destruct t as [x|f|op bs].\n    { allapply @isprog_vterm; sp. }\n    { exists (sterm f); dands; eauto 3 with slow.\n      exists 1; simpl; csunf; simpl; auto. }\n\n    dopid op as [c|nc|exc|abs] Case.\n\n    + Case \"Can\".\n      exists (oterm (Can c) bs); sp.\n      exists 0; simpl; sp.\n      constructor; simpl; auto.\n      rw @isprogram_eq; sp.\n\n    + Case \"NCan\".\n      unfold mk_cbv, nobnd in comp.\n      rw @compute_step_ncan_ncan in comp.\n      remember (compute_step lib (oterm (NCan nc) bs)); symmetry in Heqc; destruct c;\n      try (complete (inversion comp)).\n\n      allrw @fold_nobnd; allrw @fold_cbv.\n      assert (isprog n) as in0 by (apply preserve_compute_step in Heqc; sp; allrw @isprogram_eq; sp).\n      applydup IHk in in0; sp.\n      exists t'0; sp.\n      exists (S k0).\n      allrewrite @compute_at_most_k_steps_eq_f.\n      rewrite compute_at_most_k_stepsf_S.\n      rewrite Heqc; sp.\n\n   + Case \"Exc\".\n     simpl in comp.\n     provefalse.\n     allrw @isprog_eq; allapply @isprogram_exception_implies; exrepnd; subst.\n     fold_terms.\n     allrw @fold_exception.\n     rw <- @compute_at_most_k_steps_eq_f in comp.\n     generalize (reduces_to_exception lib (mk_exception a t) t');\n       intro ee; repeat (autodimp ee hyp); sp; try (exists k; auto).\n     subst.\n     apply isvalue_exc in i; sp.\n\n   + Case \"Abs\".\n     unfold mk_cbv, nobnd in comp.\n     rw @compute_step_ncan_abs in comp.\n     remember (compute_step_lib lib abs bs) as c; destruct c; try (complete (inversion comp)).\n     pose proof (compute_step_lib_success lib abs bs n) as h.\n     autodimp h hyp; exrepnd; subst.\n     allrw @fold_nobnd; allrw @fold_cbv.\n\n     assert (isprog (mk_instance vars bs rhs)) as ispi.\n     { apply @isprogram_eq.\n       apply (isprogram_subst_lib abs oa2 vars rhs lib bs correct); auto.\n       apply @isprogram_eq in isp.\n       apply isprogram_ot_iff in isp; repnd; auto. }\n\n     apply IHk in comp; auto; exrepnd.\n\n     exists t'0; dands; auto.\n     exists (S k0).\n     allrw @compute_at_most_k_steps_eq_f.\n     rw @compute_at_most_k_stepsf_S.\n     rw @compute_step_eq_unfold; simpl; rw <- Heqc; auto.\nQed.\n\nLemma isprog_can_implies_isvalue {o} :\n  forall c (bs : list (@BTerm o)),\n    isprog (oterm (Can c) bs) -> isvalue (oterm (Can c) bs).\nProof.\n  introv isp; constructor; simpl; auto.\n  apply isprogram_eq; auto.\nQed.\nHint Resolve isprog_can_implies_isvalue : slow.\n\nLemma if_hasvalue_cbv {p} :\n  forall lib t v u,\n    isprog t\n    -> isprog_vars [v] u\n    -> hasvalue lib (mk_cbv t v u)\n    -> {x : @NTerm p & computes_to_value lib t x # hasvalue lib (subst u v x)}.\nProof.\n  unfold hasvalue, computes_to_value, reduces_to, reduces_in_atmost_k_steps.\n  introv pt pu hv; exrepd.\n  allrewrite @compute_at_most_k_steps_eq_f.\n  revert t pt e.\n  induction k; simpl; introv pt e; ginv; tcsp.\n\n  - allapply @isvalue_ncan; sp.\n\n  - destruct t as [x|f|op bs].\n\n    { allapply @isprog_vterm; sp. }\n    { exists (sterm f); dands; eauto 3 with slow.\n      - exists 1; simpl; csunf; simpl; auto.\n      - csunf e; allsimpl.\n        allunfold @apply_bterm; allsimpl; allrw @fold_subst.\n        exists t'; dands; auto.\n        exists k.\n        rw @compute_at_most_k_steps_eq_f; auto. }\n\n    dopid op as [c|nc|exc|abs] Case.\n\n    + Case \"Can\".\n      exists (oterm (Can c) bs); dands; eauto 3 with slow.\n\n      * exists 0; simpl; eauto 3 with slow.\n\n      * exists t'; sp.\n        exists k; unfold subst; allrewrite @compute_at_most_k_steps_eq_f; sp.\n\n    + Case \"NCan\".\n      unfold mk_cbv, nobnd in e.\n      rw @compute_step_ncan_ncan in e.\n      remember (compute_step lib (oterm (NCan nc) bs)); symmetry in Heqc; destruct c;\n      try (complete (inversion e)).\n\n      allrewrite @fold_cbv.\n      assert (isprog n) as in0 by (apply preserve_compute_step in Heqc; sp; allrw @isprogram_eq; sp).\n      applydup IHk in in0; exrepd; auto.\n\n      exists x; sp.\n\n      exists (S k1).\n      allrewrite @compute_at_most_k_steps_eq_f.\n      rewrite compute_at_most_k_stepsf_S.\n      rewrite Heqc; sp.\n\n      exists t'0; sp.\n      exists k0; sp.\n\n    + Case \"Exc\".\n      simpl in e.\n      provefalse.\n      allrw @isprog_eq; allapply @isprogram_exception_implies; exrepnd; subst.\n      fold_terms.\n      allrw @fold_exception.\n      rw <- @compute_at_most_k_steps_eq_f in e.\n      generalize (reduces_to_exception lib (mk_exception a t) t');\n        intro ee; repeat (autodimp ee hyp); sp; try (exists k; auto).\n      subst.\n      allapply @isvalue_exc; sp.\n\n    + Case \"Abs\".\n      unfold mk_cbv, nobnd in e.\n      rw @compute_step_ncan_abs in e.\n      unfold on_success in e; simpl in e.\n      remember (compute_step_lib lib abs bs) as c; destruct c; try (complete (inversion e)).\n      pose proof (compute_step_lib_success lib abs bs n) as h.\n      autodimp h hyp; exrepnd; subst.\n      allrw @fold_nobnd; allrw @fold_cbv.\n\n      assert (isprog (mk_instance vars bs rhs)) as isp.\n      { apply @isprogram_eq.\n        apply (isprogram_subst_lib abs oa2 vars rhs lib bs correct); auto.\n        apply @isprogram_eq in pt.\n        apply isprogram_ot_iff in pt; repnd; auto. }\n\n      apply IHk in e; auto; exrepnd.\n\n      exists x; dands; auto.\n      exists (S k1).\n      allrw @compute_at_most_k_steps_eq_f.\n      rw @compute_at_most_k_stepsf_S.\n      rw @compute_step_eq_unfold; simpl; rw <- Heqc; auto.\n      exists t'0; dands; auto.\n      exists k0; auto.\nQed.\n\n(* !! MOVE *)\nHint Resolve isvalue_mk_nseq : slow.\n\nLemma if_hasvalue_apply {pp} :\n  forall lib f a,\n    isprog f\n    -> isprog a\n    -> hasvalue lib (mk_apply f a)\n    -> {v : NVar\n        & {b : @NTerm pp\n        & computes_to_value lib f (mk_lam v b)\n        # hasvalue lib (subst b v a)}}\n       [+] {s : nseq\n            & computes_to_value lib f (mk_nseq s)\n            # hasvalue lib (mk_eapply (mk_nseq s) a)}\n       [+] {s : ntseq\n            & computes_to_value lib f (mk_ntseq s)\n            # hasvalue lib (mk_eapply (mk_ntseq s) a)}.\nProof.\n  unfold hasvalue, computes_to_value, reduces_to.\n  introv pf pa hv; exrepd.\n  revert dependent f.\n  induction k; simpl; introv isp comp.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    allapply @isvalue_ncan; sp.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    rw @compute_step_eq_unfold in comp1; allsimpl.\n    destruct f as [v|f|op bs]; ginv.\n\n    { right; right.\n      exists f; dands; eauto 3 with slow.\n      - exists 0.\n        apply reduces_in_atmost_k_steps_0; auto.\n      - exists t'; dands; auto.\n        eexists; eauto. }\n\n    dopid op as [c|nc|exc|abs] Case.\n\n    + Case \"Can\".\n      apply compute_step_apply_success in comp1.\n      repndors; [left|right]; exrepnd; subst; fold_terms; ginv.\n\n      * exists v b; dands; try (complete (constructor; sp; allrw @fold_lam; sp; rw @isprogram_eq; sp)); eauto with slow.\n        exists 0; sp; try (complete (constructor; sp; allrw @fold_lam; sp; rw @isprogram_eq; sp)).\n\n      * left; exists f; dands; eauto 3 with slow.\n        { exists 0; allrw @reduces_in_atmost_k_steps_0; auto. }\n        { eexists; dands;[eexists;exact comp0|]; auto. }\n\n    + Case \"NCan\".\n      remember (compute_step lib (oterm (NCan nc) bs)); symmetry in Heqc; destruct c; allsimpl; ginv.\n      fold_terms.\n      assert (isprog n) as in0 by (apply preserve_compute_step in Heqc; sp; allrw @isprogram_eq; sp).\n      applydup IHk in comp0; auto; repndors; [left|right;left|right;right]; exrepd; auto.\n\n      * exists v b; sp.\n\n        exists (S k1).\n\n        { rw @reduces_in_atmost_k_steps_S; exists n; dands; auto. }\n\n        { exists t'0; sp.\n          exists k0; sp. }\n\n      * exists s; dands; eauto 3 with slow.\n        { exists (S k1).\n          allrw @reduces_in_atmost_k_steps_S.\n          eexists; dands; eauto. }\n        { eexists; dands;[eexists;exact r|]; auto. }\n\n      * exists s; dands; eauto 3 with slow.\n        { exists (S k1).\n          allrw @reduces_in_atmost_k_steps_S.\n          eexists; dands; eauto. }\n        { eexists; dands;[eexists;exact r|]; auto. }\n\n    + Case \"Exc\".\n      ginv.\n      provefalse.\n      allrw @isprog_eq; allapply @isprogram_exception_implies; exrepnd; subst.\n      fold_terms.\n      allrw @fold_exception.\n      generalize (reduces_to_exception lib (mk_exception a0 t) t');\n        intro ee; repeat (autodimp ee hyp); sp; try (exists k; auto).\n      subst.\n      allapply @isvalue_exc; sp.\n\n    + Case \"Abs\".\n      rw @compute_step_eq_unfold in comp1; allsimpl.\n      remember (compute_step_lib lib abs bs) as c; destruct c; allsimpl; ginv.\n      pose proof (compute_step_lib_success lib abs bs n) as h.\n      autodimp h hyp; exrepnd; subst.\n      allrw @fold_nobnd; allrw @fold_cbv.\n\n      assert (isprog (mk_instance vars bs rhs)) as isp'.\n      { apply @isprogram_eq.\n        apply (isprogram_subst_lib abs oa2 vars rhs lib bs correct); auto.\n        apply @isprogram_eq in isp.\n        apply isprogram_ot_iff in isp; repnd; auto. }\n\n      apply IHk in comp0; auto; repndors; [left|right;left|right;right]; exrepnd.\n\n      * exists v b; dands; auto.\n        { exists (S k1).\n          rw @reduces_in_atmost_k_steps_S.\n          rw @compute_step_eq_unfold; simpl.\n          simpl; rw <- Heqc; auto.\n          eexists; dands; eauto. }\n        { exists t'0; dands; auto.\n          exists k0; auto. }\n\n      * exists s; dands; eauto 3 with slow.\n        { exists (S k1).\n          allrw @reduces_in_atmost_k_steps_S.\n          eexists; dands; eauto. }\n        { eexists; dands;[eexists;exact comp4|]; auto. }\n\n      * exists s; dands; eauto 3 with slow.\n        { exists (S k1).\n          allrw @reduces_in_atmost_k_steps_S.\n          eexists; dands; eauto. }\n        { eexists; dands;[eexists;exact comp4|]; auto. }\nQed.\n\nLemma if_computes_to_value_apply {o} :\n  forall lib (f a x : @NTerm o),\n    isprog f\n    -> isprog a\n    -> computes_to_value lib (mk_apply f a) x\n    -> {v : NVar\n        & {b : NTerm\n        & computes_to_value lib f (mk_lam v b)\n        # computes_to_value lib (subst b v a) x}}\n       [+] {s : nseq\n            & computes_to_value lib f (mk_nseq s)\n            # computes_to_value lib (mk_eapply (mk_nseq s) a) x}\n       [+] {s : ntseq\n            & computes_to_value lib f (mk_ntseq s)\n            # computes_to_value lib (mk_eapply (mk_ntseq s) a) x}.\nProof.\n  unfold computes_to_value, reduces_to.\n  introv pf pa hv; exrepd.\n  revert dependent f.\n  induction k; simpl; introv isp comp.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    allapply @isvalue_ncan; sp.\n\n  - destruct f as [|f|op bs].\n\n    { allapply @isprog_vterm; sp. }\n\n    { right; right.\n      exists f; dands; eauto 3 with slow.\n      - exists 0; apply reduces_in_atmost_k_steps_0; auto.\n      - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n        csunf comp1; allsimpl; ginv.\n        eexists; eauto. }\n\n    allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    dopid op as [c|nc|exc|abs] Case.\n\n    + Case \"Can\".\n      csunf comp1; allsimpl.\n      apply compute_step_apply_success in comp1;\n        repndors; [left|right]; exrepnd; subst; fold_terms; ginv.\n\n      * exists v b; sp; try (complete (constructor; sp; allrw @fold_lam; sp; rw @isprogram_eq; sp)).\n        { exists 0; sp; try (complete (constructor; sp; allrw @fold_lam; sp; rw @isprogram_eq; sp)). }\n        { exists k; allrewrite @compute_at_most_k_steps_eq_f; sp. }\n\n      * left; exists f; dands; eauto 3 with slow.\n        { exists 0; allrw @reduces_in_atmost_k_steps_0; auto. }\n\n    + Case \"NCan\".\n      unfold mk_apply, nobnd in comp1.\n      rw @compute_step_ncan_ncan in comp1.\n      remember (compute_step lib (oterm (NCan nc) bs)); symmetry in Heqc; destruct c; allsimpl; ginv.\n      fold_terms.\n      assert (isprog n) as in0 by (apply preserve_compute_step in Heqc; sp; allrw @isprogram_eq; sp).\n      applydup IHk in in0; auto; repndors; [left|right;left|right;right]; exrepd; auto.\n\n      * exists v b; sp.\n\n        { exists (S k1).\n          rw @reduces_in_atmost_k_steps_S.\n          exists n; dands; auto. }\n\n        exists k0; sp.\n\n      * exists s; dands; eauto 3 with slow.\n        { exists (S k1).\n          allrw @reduces_in_atmost_k_steps_S.\n          eexists; dands; eauto. }\n\n      * exists s; dands; eauto 3 with slow.\n        { exists (S k1).\n          allrw @reduces_in_atmost_k_steps_S.\n          eexists; dands; eauto. }\n\n    + Case \"Exc\".\n      csunf comp1; allsimpl; ginv.\n      provefalse.\n      allrw @isprog_eq; allapply @isprogram_exception_implies; exrepnd; subst.\n      fold_terms.\n      allrw @fold_exception.\n      generalize (reduces_to_exception lib (mk_exception a0 t) x);\n        intro ee; repeat (autodimp ee hyp); sp; try (exists k; auto).\n      subst.\n      allapply @isvalue_exc; sp.\n\n    + Case \"Abs\".\n      unfold mk_apply, nobnd in comp1.\n      rw @compute_step_ncan_abs in comp1.\n      remember (compute_step_lib lib abs bs) as c; destruct c; allsimpl; ginv.\n      pose proof (compute_step_lib_success lib abs bs n) as h.\n      autodimp h hyp; exrepnd; subst.\n      allrw @fold_nobnd; allrw @fold_cbv.\n\n      assert (isprog (mk_instance vars bs rhs)) as isp'.\n      { apply @isprogram_eq.\n        apply (isprogram_subst_lib abs oa2 vars rhs lib bs correct); auto.\n        apply @isprogram_eq in isp.\n        apply isprogram_ot_iff in isp; repnd; auto. }\n\n      apply IHk in comp0; auto; repndors; [left|right;left|right;right]; exrepnd.\n\n      * exists v b; dands; auto.\n        { exists (S k1).\n          rw @reduces_in_atmost_k_steps_S.\n          exists (mk_instance vars bs rhs); dands; auto. }\n        exists k0; auto.\n\n      * exists s; dands; eauto 3 with slow.\n        { exists (S k1).\n          allrw @reduces_in_atmost_k_steps_S.\n          eexists; dands; eauto. }\n\n      * exists s; dands; eauto 3 with slow.\n        { exists (S k1).\n          allrw @reduces_in_atmost_k_steps_S.\n          eexists; dands; eauto. }\nQed.\n\nLemma compute_step_value_like {p} :\n  forall lib (t : @NTerm p), isvalue_like t -> compute_step lib t = csuccess t.\nProof.\n  introv h.\n  dorn h.\n  - apply iscan_implies in h; repndors; exrepnd; subst; reflexivity.\n  - destruct t as [|f|op]; allsimpl; tcsp;\n    try (complete (dorn h; allsimpl; sp)).\n    destruct op; allsimpl; sp;\n    try (complete (dorn h; allsimpl; sp)).\nQed.\n\nLemma reduces_in_atmost_k_steps_if_isvalue_like {o} :\n  forall lib k (t1 t2 : @NTerm o),\n    reduces_in_atmost_k_steps lib t1 t2 k\n    -> isvalue_like t1\n    -> t2 = t1.\nProof.\n  induction k; introv r iv.\n  - rw @reduces_in_atmost_k_steps_0 in r; auto.\n  - rw @reduces_in_atmost_k_steps_S in r; exrepnd.\n    rw @compute_step_value_like in r1; auto; ginv.\n    apply IHk in r0; auto; subst; auto.\nQed.\n\nLemma isvalue_like_integer {o} :\n  forall z, @isvalue_like o (mk_integer z).\nProof.\n  introv; unfold isvalue_like; simpl; sp.\nQed.\nHint Resolve isvalue_like_integer : slow.\n\nLemma isvalue_like_uni {o} :\n  forall n, @isvalue_like o (mk_uni n).\nProof.\n  introv; unfold isvalue_like; simpl; sp.\nQed.\nHint Resolve isvalue_like_uni : slow.\n\nLemma isvalue_like_utoken {o} :\n  forall a, @isvalue_like o (mk_utoken a).\nProof.\n  introv; unfold isvalue_like; simpl; sp.\nQed.\nHint Resolve isvalue_like_utoken : slow.\n\nLemma implies_computes_to_value_apply {p} :\n  forall lib f a v b x,\n    computes_to_value lib f (@mk_lam p v b)\n    -> computes_to_value lib (subst b v a) x\n    -> computes_to_value lib (mk_apply f a) x.\nProof.\n  unfold computes_to_value, reduces_to.\n  introv cf cs; exrepnd; dands; auto.\n  exists (S (k0 + k)).\n  rw @reduces_in_atmost_k_steps_S.\n  revert dependent f.\n  revert dependent k0.\n\n  induction k0; introv r1.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    exists (subst b v a); simpl; dands; tcsp.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    destruct f as [|f|op bs].\n\n    + csunf r1; simpl in r1; ginv.\n\n    + csunf r1; allsimpl; ginv.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto 3 with slow; ginv.\n\n    + dopid op as [c|nc|exc|abs] Case.\n\n      * Case \"Can\".\n        csunf r1; simpl in r1; ginv.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto with slow; ginv.\n        inversion r0; subst; fold_terms; GC.\n        exists (subst b v a); simpl; dands; auto.\n        eapply no_change_after_value2; eauto; try omega.\n\n      * Case \"NCan\".\n        pose proof (IHk0 u) as h; repeat (autodimp h hyp); exrepnd.\n        exists (mk_apply u a); dands; tcsp.\n\n        { unfold mk_apply, nobnd.\n          rw @compute_step_ncan_ncan.\n          rw r1; auto. }\n\n        simpl; rw @reduces_in_atmost_k_steps_S.\n        exists u0; sp.\n\n      * Case \"Exc\".\n        csunf r1; simpl in r1; ginv.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto with slow; ginv.\n\n      * Case \"Abs\".\n        csunf r1; simpl in r1.\n        pose proof (IHk0 u) as h; repeat (autodimp h hyp); exrepnd.\n        exists (mk_apply u a); dands; tcsp.\n\n        { unfold mk_apply, nobnd; csunf; simpl; csunf; simpl.\n          unfold on_success.\n          rw r1; auto. }\n\n        simpl; rw @reduces_in_atmost_k_steps_S.\n        exists u0; sp.\nQed.\n\nLemma implies_computes_to_value_inl_decide {pp} :\n  forall lib d x f y g a v,\n    computes_to_value lib d (@mk_inl pp a)\n    -> computes_to_value lib (subst f x a) v\n    -> computes_to_value lib (mk_decide d x f y g) v.\nProof.\n  unfold computes_to_value, reduces_to.\n  introv cd cf; exrepnd; dands; auto.\n  exists (S (k0 + k)).\n  rw @reduces_in_atmost_k_steps_S.\n  clear cd.\n  revert dependent d.\n  revert dependent k0.\n  induction k0; introv r.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst; simpl.\n    exists (subst f x a); sp.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    destruct d as [|s|op bs].\n\n    + csunf r1; simpl in r1; ginv.\n\n    + csunf r1; allsimpl; ginv.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto 3 with slow; ginv.\n\n    + dopid op as [c|nc|exc|abs] Case.\n\n      * Case \"Can\".\n        csunf r1; simpl in r1; ginv.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto with slow; ginv.\n        inversion r0; subst; fold_terms; GC.\n        exists (subst f x a); simpl; dands; auto.\n        eapply no_change_after_value2; eauto; try omega.\n\n      * Case \"NCan\".\n        pose proof (IHk0 u) as h; repeat (autodimp h hyp); exrepnd.\n        exists (mk_decide u x f y g); dands; tcsp.\n\n        { unfold mk_decide, nobnd.\n          rw @compute_step_ncan_ncan.\n          rw r1; auto. }\n\n        simpl; rw @reduces_in_atmost_k_steps_S.\n        exists u0; sp.\n\n      * Case \"Exc\".\n        csunf r1; simpl in r1; ginv.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto with slow; ginv.\n\n      * Case \"Abs\".\n        pose proof (IHk0 u) as h; repeat (autodimp h hyp); exrepnd.\n        exists (mk_decide u x f y g); dands; tcsp.\n\n        { unfold mk_decide, nobnd.\n          rw @compute_step_ncan_abs.\n          csunf r1; simpl in r1; rw r1; auto. }\n\n        simpl; rw @reduces_in_atmost_k_steps_S.\n        exists u0; sp.\nQed.\n\nLemma implies_computes_to_value_inr_decide {pp} :\n  forall lib d x f y g a v,\n    computes_to_value lib d (@mk_inr pp a)\n    -> computes_to_value lib (subst g y a) v\n    -> computes_to_value lib (mk_decide d x f y g) v.\nProof.\n  unfold computes_to_value, reduces_to.\n  introv cd cf; exrepnd; dands; auto.\n  exists (S (k0 + k)).\n  rw @reduces_in_atmost_k_steps_S.\n  clear cd.\n  revert dependent d.\n  revert dependent k0.\n  induction k0; introv r1.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst; simpl.\n    exists (subst g y a); sp.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    destruct d as [|s|op bs].\n\n    + csunf r1; simpl in r1; ginv.\n\n    + csunf r1; allsimpl; ginv.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto 3 with slow; ginv.\n\n    + dopid op as [c|nc|exc|abs] Case.\n\n      * Case \"Can\".\n        csunf r1; simpl in r1; ginv.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto with slow; ginv.\n        inversion r0; subst; fold_terms; GC.\n        exists (subst g y a); simpl; dands; auto.\n        eapply no_change_after_value2; eauto; try omega.\n\n      * Case \"NCan\".\n        pose proof (IHk0 u) as h; repeat (autodimp h hyp); exrepnd.\n        exists (mk_decide u x f y g); dands; tcsp.\n\n        { unfold mk_decide, nobnd.\n          rw @compute_step_ncan_ncan.\n          rw r1; auto. }\n\n        simpl; rw @reduces_in_atmost_k_steps_S.\n        exists u0; sp.\n\n      * Case \"Exc\".\n        csunf r1; simpl in r1; ginv.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in r0; eauto with slow; ginv.\n\n      * Case \"Abs\".\n        pose proof (IHk0 u) as h; repeat (autodimp h hyp); exrepnd.\n        exists (mk_decide u x f y g); dands; tcsp.\n\n        { unfold mk_decide, nobnd.\n          rw @compute_step_ncan_abs.\n          csunf r1; simpl in r1; rw r1; auto. }\n\n        simpl; rw @reduces_in_atmost_k_steps_S.\n        exists u0; sp.\nQed.\n\nDefinition computes_to_pk {o} lib (t : @NTerm o) (pk : param_kind) :=\n  computes_to_value lib t (pk2term pk).\n\nDefinition mk_compop_eq {p} (a b c d : @NTerm p) :=\n  oterm (NCan (NCompOp CompOpEq)) [nobnd a, nobnd b, nobnd c, nobnd d].\n\nLemma reduces_in_atmost_k_steps_exception {o} :\n  forall lib bs (t : @NTerm o) k,\n    reduces_in_atmost_k_steps lib (oterm Exc bs) t k\n    -> t = oterm Exc bs.\nProof.\n  introv comp.\n  unfold reduces_in_atmost_k_steps in comp.\n  rw @compute_at_most_k_steps_exception in comp.\n  ginv; auto.\nQed.\n\nLemma implies_computes_to_value_comp {p} :\n  forall lib (a b c d : @NTerm p) pk1 pk2 v,\n    computes_to_pk lib a pk1\n    -> computes_to_pk lib b pk2\n    -> computes_to_value lib (if param_kind_deq pk1 pk2 then c else d) v\n    -> computes_to_value lib (mk_compop_eq a b c d) v.\nProof.\n  unfold computes_to_pk, computes_to_value, reduces_to.\n  introv comppk1 comppk2 comp; exrepnd; dands; auto.\n  exists (S (k1 + k0 + k)).\n  revert dependent a.\n  induction k1; introv compk1.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst; allsimpl.\n    revert dependent b.\n    induction k0; introv compk2.\n\n    + allrw @reduces_in_atmost_k_steps_0; subst; allsimpl.\n      rw @reduces_in_atmost_k_steps_S.\n      csunf; simpl.\n      allrw @pk2term_eq.\n      dcwf h; allsimpl;\n      [|unfold co_wf in Heqh; allsimpl;allrw @get_param_from_cop_pk2can; complete ginv].\n      unfold compute_step_comp; simpl.\n      allrw @get_param_from_cop_pk2can.\n      eexists; dands; eauto.\n\n    + allrw @reduces_in_atmost_k_steps_S; exrepnd.\n      applydup IHk0 in compk0; clear IHk0; allsimpl.\n      csunf; simpl.\n      allrw @pk2term_eq.\n      destruct b as [x|f|op bs];[csunf compk1;allsimpl;ginv|idtac|].\n\n      { csunf compk1; allsimpl; ginv.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in compk0;\n          eauto 3 with slow; ginv. }\n\n      dopid op as [can|ncan|exc|abs] Case.\n\n      * Case \"Can\".\n        csunf compk1; allsimpl; ginv.\n        apply reduces_in_atmost_k_steps_if_isvalue_like in compk0; tcsp; ginv.\n        dcwf h; allsimpl;\n        [|unfold co_wf in Heqh; allsimpl;allrw @get_param_from_cop_pk2can; complete ginv].\n        unfold compute_step_comp; simpl.\n        allrw @get_param_from_cop_pk2can.\n        eexists; dands; eauto.\n        eapply no_change_after_value2; eauto; try omega.\n\n      * Case \"NCan\".\n        rw compk1; simpl.\n        dcwf h; allsimpl;\n        [|unfold co_wf in Heqh; allsimpl;allrw @get_param_from_cop_pk2can; complete ginv].\n        eexists; dands; eauto.\n\n      * Case \"Exc\".\n        eexists; dands; eauto.\n        csunf compk1; allsimpl; ginv.\n        apply reduces_in_atmost_k_steps_exception in compk0; ginv.\n\n      * Case \"Abs\".\n        rw compk1; simpl.\n        dcwf h; allsimpl;\n        [|unfold co_wf in Heqh; allsimpl;allrw @get_param_from_cop_pk2can; complete ginv].\n        eexists; dands; eauto.\n\n  - rw @reduces_in_atmost_k_steps_S in compk1; exrepnd.\n    applydup IHk1 in compk0; clear IHk1; allsimpl.\n    destruct a as [x|f|op bs];[csunf compk1;allsimpl;ginv|idtac|].\n\n    { csunf compk1; allsimpl; ginv.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in compk0;\n        eauto 3 with slow; ginv.\n      allrw @pk2term_eq; ginv. }\n\n    dopid op as [can|ncan|exc|abs] Case.\n\n    + Case \"Can\".\n      csunf compk1; allsimpl; ginv.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in compk0; tcsp; ginv.\n      rw @pk2term_eq in compk0; ginv.\n      eapply no_change_after_value2; eauto; try omega.\n\n    + Case \"NCan\".\n      rw @reduces_in_atmost_k_steps_S.\n      csunf; simpl.\n      rw compk1; simpl.\n      eexists; dands; eauto.\n\n    + Case \"Exc\".\n      csunf compk1; allsimpl; ginv.\n      apply reduces_in_atmost_k_steps_exception in compk0; ginv.\n      rw @pk2term_eq in compk0; ginv.\n\n    + Case \"Abs\".\n      rw @reduces_in_atmost_k_steps_S.\n      csunf; simpl.\n      rw compk1; simpl.\n      eexists; dands; eauto.\nQed.\n\nLemma computes_to_value_implies_computes_to_pk {o} :\n  forall lib (t : @NTerm o) pk,\n    computes_to_value lib t (pk2term pk)\n    -> computes_to_pk lib t pk.\nProof. sp. Qed.\nHint Resolve computes_to_value_implies_computes_to_pk : slow.\n\nLemma reduces_in_atmost_k_steps_implies_computes_to_value {o} :\n  forall lib (t : @NTerm o) u k,\n    reduces_in_atmost_k_steps lib t u k\n    -> isvalue u\n    -> computes_to_value lib t u.\nProof.\n  introv r isv.\n  unfold computes_to_value; dands; auto.\n  exists k; auto.\nQed.\nHint Resolve reduces_in_atmost_k_steps_implies_computes_to_value : slow.\n\nLemma implies_computes_to_value_trycatch {p} :\n  forall lib a (t : @NTerm p) v pk x b,\n    computes_to_value lib t v\n    -> computes_to_pk lib a pk\n    -> computes_to_value lib (mk_try t a x b) v.\nProof.\n  unfold computes_to_pk, computes_to_value, reduces_to.\n  introv compt compa; exrepnd; dands; auto.\n  revert dependent t.\n  induction k0; introv comp.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    dup compt as isv.\n    apply isvalue_implies_iscan in isv.\n    apply iscan_implies in isv; repndors; exrepnd; subst.\n\n    + pose proof (implies_computes_to_value_comp\n                    lib a a (oterm (Can c) bterms) mk_bot\n                    pk pk (oterm (Can c) bterms)) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      { boolvar; tcsp; apply computes_to_value_isvalue_refl; tcsp. }\n      unfold computes_to_value, reduces_to in h; exrepnd.\n\n      exists (S k0).\n      rw @reduces_in_atmost_k_steps_S.\n      csunf; simpl; eexists; dands; eauto.\n\n    + pose proof (implies_computes_to_value_comp\n                    lib a a (sterm f) mk_bot\n                    pk pk (sterm f)) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      { boolvar; tcsp; apply computes_to_value_isvalue_refl; tcsp. }\n      unfold computes_to_value, reduces_to in h; exrepnd.\n\n      exists (S k0).\n      rw @reduces_in_atmost_k_steps_S.\n      csunf; simpl; eexists; dands; eauto.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    destruct t as [|f|op bs];[csunf comp1; allsimpl; complete ginv|idtac|].\n\n    { csunf comp1; allsimpl; ginv.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in comp0; subst; eauto 3 with slow.\n\n      pose proof (implies_computes_to_value_comp\n                    lib a a (sterm f) mk_bot\n                    pk pk (sterm f)) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      { boolvar; tcsp; apply computes_to_value_isvalue_refl; tcsp. }\n      unfold computes_to_value, reduces_to in h; exrepnd.\n\n      exists (S k1).\n      rw @reduces_in_atmost_k_steps_S.\n      csunf; simpl; eexists; dands; eauto. }\n\n    dopid op as [c|nc|exc|abs] Case; try (complete (allsimpl; auto)).\n\n    + Case \"Can\".\n      csunf comp1; simpl in comp1; ginv.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in comp0; eauto with slow; ginv; subst.\n\n      pose proof (implies_computes_to_value_comp\n                    lib a a (oterm (Can c) bs) mk_bot\n                    pk pk (oterm (Can c) bs)) as h.\n      repeat (autodimp h hyp); eauto 3 with slow.\n      { boolvar; tcsp; apply computes_to_value_isvalue_refl; tcsp. }\n      unfold computes_to_value, reduces_to in h; exrepnd.\n\n      exists (S k1).\n      rw @reduces_in_atmost_k_steps_S.\n      csunf; simpl; eexists; dands; eauto.\n\n    + Case \"NCan\".\n      apply IHk0 in comp0; clear IHk0; exrepnd.\n      exists (S k1).\n      rw @reduces_in_atmost_k_steps_S.\n      rw @compute_step_try_ncan.\n      rw comp1.\n      eexists; dands; eauto.\n\n    + Case \"Exc\".\n      csunf comp1; simpl in comp1; ginv.\n      apply reduces_in_atmost_k_steps_if_isvalue_like in comp0; eauto with slow; ginv; subst.\n      allapply @isvalue_exc; sp.\n\n    + Case \"Abs\".\n      apply IHk0 in comp0; clear IHk0; exrepnd.\n      exists (S k1).\n      rw @reduces_in_atmost_k_steps_S.\n      rw @compute_step_try_abs.\n      csunf comp1; allsimpl; rw comp1.\n      eexists; dands; eauto.\nQed.\n\nLemma can_doesnt_raise_an_exception {p} :\n  forall lib a c bterms (e : @NTerm p),\n    computes_to_exception lib a (oterm (Can c) bterms) e -> False.\nProof.\n  introv ce.\n  destruct ce as [k r].\n  unfold reduces_to, reduces_in_atmost_k_steps in r; exrepnd.\n  rw @compute_at_most_k_steps_eq_f in r.\n  induction k; simpl in r; sp.\n  inversion r; subst.\nQed.\n\nLemma not_bot_reduces_to_value {p} :\n  forall lib t, @isvalue p t -> !reduces_to lib mk_bot t.\nProof.\n  introv isv red.\n  unfold reduces_to, reduces_in_atmost_k_steps in red; sp.\n  rw @compute_at_most_k_steps_eq_f in e.\n  revert t isv e.\n  induction k as [? ind] using comp_ind_type; sp; allsimpl.\n  destruct (zerop k); subst; ginv; allsimpl.\n\n  - allapply @isvalue_ncan; sp.\n\n  - destruct k; try (complete (inversion l)).\n    simpl in e.\n    destruct k; simpl in e; ginv;[allapply @isvalue_ncan; sp|].\n    destruct k; simpl in e; ginv.\n\n    + allunfold @apply_bterm; allsimpl.\n      allunfold @lsubst; allsimpl.\n      allapply @isvalue_ncan; sp.\n\n    + destruct k; ginv; allsimpl;[allapply @isvalue_ncan; sp|].\n      allunfold @apply_bterm; allsimpl.\n      allunfold @lsubst; allsimpl.\n      apply ind in e; sp.\nQed.\n\nLemma bottom_diverges {p} :\n  forall lib t, !@computes_to_value p lib mk_bot t.\nProof.\n  introv comp.\n  unfold computes_to_value in comp; repnd.\n  apply not_bot_reduces_to_value in comp0; auto.\nQed.\n\nLemma not_hasvalue_bot {p} : forall lib, @hasvalue p lib mk_bot -> False.\nProof.\n  introv Hsc; repnud Hsc; exrepnd.\n  apply bottom_diverges in Hsc0; cpx.\nQed.\n\nLemma bottom_doesnt_converge {p} :\n  forall lib a,\n    @computes_to_value p lib mk_bottom a\n    -> False.\nProof.\n  introv comp.\n  apply bottom_diverges in comp; sp.\nQed.\n\nLemma bottom_doesnt_raise_an_exception {p} :\n  forall lib a (e : @NTerm p),\n    computes_to_exception lib a mk_bottom e\n    -> False.\nProof.\n  introv Hcv.\n  repnud Hcv.\n  repnud Hcv.\n  exrepnd.\n  unfold reduces_in_atmost_k_steps in Hcv0.\n  generalize dependent a.\n  generalize dependent k.\n  unfold_all_mk.\n  induction k as [k  Hind] using comp_ind.\n  introv Hc.\n  destruct k.\n\n  - inverts Hc.\n\n  - rw @compute_at_most_k_steps_eq_f in Hc.\n    rw @compute_at_most_k_stepsf_S in Hc.\n    simpl in Hc.\n    destruct k.\n\n    + inversion Hc.\n\n    + rw @compute_at_most_k_stepsf_S in Hc.\n      simpl in Hc.\n      unfold apply_bterm in Hc.\n      simpl in Hc.\n      revert Hc.\n      change_to_lsubst_aux4; simpl; try (complete sp).\n      intro Hc.\n      rw <- @compute_at_most_k_steps_eq_f in Hc.\n      apply Hind in Hc; sp.\nQed.\n\nLemma not_vbot_reduces_to_value {p} :\n  forall lib v t, @isvalue p t -> !reduces_to lib (mk_vbot v) t.\nProof.\n  introv isv red.\n  unfold reduces_to, reduces_in_atmost_k_steps in red; sp.\n  rw @compute_at_most_k_steps_eq_f in e.\n  revert t isv e.\n  induction k as [? ind] using comp_ind_type; sp; allsimpl.\n  destruct (zerop k); subst; ginv; allsimpl.\n\n  - allapply @isvalue_ncan; sp.\n\n  - destruct k; try (complete (inversion l)).\n    simpl in e.\n    destruct k; allsimpl; ginv; allapply @isvalue_ncan; tcsp.\n    destruct k; allsimpl; ginv.\n\n    + allunfold @apply_bterm; allsimpl.\n      allunfold @lsubst; allsimpl.\n      boolvar; tcsp.\n      allapply @isvalue_ncan; tcsp.\n\n    + destruct k; allsimpl.\n\n      * allunfold @apply_bterm; allsimpl.\n        revert e; change_to_lsubst_aux4; simpl; auto; boolvar; simpl; intro e.\n        ginv; allapply @isvalue_ncan; tcsp.\n\n      * allunfold @apply_bterm; allsimpl.\n        revert e; change_to_lsubst_aux4; simpl; auto; boolvar; simpl.\n        unfold apply_bterm; simpl; change_to_lsubst_aux4; simpl; boolvar; intro e.\n        apply ind in e; sp.\nQed.\n\nLemma vbot_diverges {p} :\n  forall lib v t, !@computes_to_value p lib (mk_vbot v) t.\nProof.\n  introv comp.\n  unfold computes_to_value in comp; repnd.\n  apply not_vbot_reduces_to_value in comp0; auto.\nQed.\n\nLemma vbot_doesnt_raise_an_exception {p} :\n  forall lib a v (e : @NTerm p),\n    !computes_to_exception lib a (mk_vbot v) e.\nProof.\n  introv Hcv.\n  unfold computes_to_exception, reduces_to, reduces_in_atmost_k_steps in Hcv.\n  exrepnd.\n  generalize dependent e.\n  induction k as [k Hind] using comp_ind.\n  introv Hc.\n  destruct k.\n\n  - inverts Hc.\n\n  - rw @compute_at_most_k_steps_eq_f in Hc.\n    rw @compute_at_most_k_stepsf_S in Hc.\n    simpl in Hc.\n    destruct k.\n\n    + inversion Hc.\n\n    + rw @compute_at_most_k_stepsf_S in Hc.\n      simpl in Hc.\n      unfold apply_bterm in Hc.\n      simpl in Hc.\n      revert Hc.\n      change_to_lsubst_aux4; simpl; try (complete sp); boolvar.\n      intro Hc.\n      rw <- @compute_at_most_k_steps_eq_f in Hc.\n      apply Hind in Hc; sp.\nQed.\n\nLemma axiom_doesnt_raise_an_exception {p} :\n  forall lib a (e : @NTerm p),\n    computes_to_exception lib a mk_axiom e -> False.\nProof.\n  introv c.\n  apply can_doesnt_raise_an_exception in c; sp.\nQed.\n\nLemma apply_compute_step_prinargcan {p} :\n  forall lib arg1c arg1lbt lbt tc,\n    compute_step lib\n        (oterm (NCan NApply)\n        (bterm [] (oterm (Can arg1c) arg1lbt) :: lbt))\n      = csuccess tc\n      -> (arg1c = NLambda\n          # {lamv : NVar\n             & {lamb,applicand : @NTerm p\n             $ arg1lbt = [bterm [lamv] lamb]\n             # lbt = [bterm [] applicand]\n             # tc = subst lamb lamv applicand }})\n         [+] {s : nseq\n              & {arg : NTerm\n              & arg1c = Nseq s\n              # arg1lbt = []\n              # lbt = [bterm [] arg]\n              # tc = mk_eapply (mk_nseq s) arg }}.\nProof.\n  introv Hcomp.\n  simpl in Hcomp.\n  csunf Hcomp; allsimpl.\n  apply compute_step_apply_success in Hcomp.\n  repndors; auto.\n  exrepnd; subst.\n  left; dands; auto.\n  eexists; eexists; eexists; eauto.\nQed.\n\n\nLtac destructbt bt:=\n  let btlv := fresh bt \"lv\" in\n  let btnt := fresh bt \"nt\" in\n  destruct bt as [btlv btnt].\n\nLtac destructbtdeep bt Hcomp :=\n  let btlv := fresh bt \"lv\" in\n  let btnt := fresh bt \"nt\" in\n  let btlv1 := fresh btlv \"1\" in\n  let btlv2 := fresh btlv \"2\" in\n  let btlv3 := fresh btlv \"3\" in\n  destruct bt as [btlv btnt];\n  destruct btlv as [| btlv1]; inverts Hcomp as Hcomp;\n  try(destruct btlv as [| btlv2]; inverts Hcomp as Hcomp);\n  try(destruct btlv as [| btlv3]; inverts Hcomp as Hcomp).\n\n\nLemma compute_step_lib_success_change_bs {o} :\n  forall (lib : @library o) oa1 oa2 bs1 bs2 vars rhs correct,\n    map num_bvars bs1 = map num_bvars bs2\n    -> found_entry lib oa1 bs1 oa2 vars rhs correct\n    -> compute_step_lib lib oa1 bs2 = csuccess (mk_instance vars bs2 rhs).\nProof.\n  introv e f.\n  unfold compute_step_lib.\n  rw (unfold_abs_success_change_bs lib oa1 oa2 bs1 bs2 vars rhs correct e f); auto.\nQed.\n\nLemma eq_num_bvars_if_alpha {o} :\n  forall bs1 bs2 : list (@BTerm o),\n    length bs1 = length bs2\n    -> (forall n : nat, n < length bs1 -> alpha_eq_bterm (bs1 {[n]}) (bs2 {[n]}))\n    -> map num_bvars bs1 = map num_bvars bs2.\nProof.\n  induction bs1; destruct bs2; introv l h; allsimpl; auto; cpx.\n  apply eq_cons.\n  - pose proof (h 0) as k; autodimp k hyp; try omega.\n    unfold selectbt in k; simpl in k.\n    inversion k; allsimpl.\n    unfold num_bvars; simpl; auto.\n  - apply IHbs1; auto.\n    introv k.\n    pose proof (h (S n)) as x.\n    autodimp x hyp; omega.\nQed.\n\nLemma alpha_eq_lsubst_mk_abs_subst {o} :\n  forall lib oa1 oa2 rhs vars correct (bs1 bs2 : list (@BTerm o)),\n    found_entry lib oa1 bs1 oa2 vars rhs correct\n    -> found_entry lib oa1 bs2 oa2 vars rhs correct\n    -> map num_bvars bs1 = map num_bvars bs2\n    -> (forall n : nat,\n            n < length bs1\n            -> alpha_eq_bterm (bs1 {[n]}) (bs2 {[n]}))\n    -> alpha_eq (mk_instance vars bs1 rhs)\n                (mk_instance vars bs2 rhs).\nProof.\n  introv fe1 fe2 e hal.\n  apply alphaeq_eq.\n  apply mk_instance_alpha_congr; auto.\n\n  - apply found_entry_implies_matching_entry in fe1.\n    unfold matching_entry in fe1; repnd.\n    apply map_eq_length_eq in fe1; auto.\n\n  - apply found_entry_implies_matching_entry in fe2.\n    unfold matching_entry in fe2; repnd.\n    apply map_eq_length_eq in fe2; auto.\n\n  - inversion correct; sp.\n\n  - inversion correct; sp.\n\n  - apply found_entry_implies_matching_entry in fe1.\n    unfold matching_entry in fe1; repnd; auto.\n\n  - apply found_entry_implies_matching_entry in fe2.\n    unfold matching_entry in fe2; repnd; auto.\n\n  - unfold bin_rel_bterm, binrel_list.\n    applydup map_eq_length_eq in e; auto.\n    introv.\n    dands; auto.\n    introv i; applydup hal in i.\n    apply alphaeqbt_eq; auto.\nQed.\n\nLemma alpha_eq_mk_cbv {o} :\n  forall (t : @NTerm o) v a u,\n    alpha_eq (mk_cbv t v a) u\n    -> {t' : NTerm\n        & {v' : NVar\n        & {a' : NTerm\n        & u = mk_cbv t' v' a'\n        # alpha_eq t t'\n        # alpha_eq_bterm (bterm [v] a) (bterm [v'] a')}}}.\nProof.\n  introv aeq.\n  inversion aeq as [|?|? ? ? len i]; subst; allsimpl.\n  destruct lbt2; allsimpl; repeat cpx.\n  pose proof (i 0) as h1; autodimp h1 hyp; allsimpl.\n  pose proof (i 1) as h2; autodimp h2 hyp; allsimpl.\n  clear i.\n  unfold selectbt in h1, h2; allsimpl.\n  inversion h1 as [? ? ? ? ? disj1 ? ? norep1 aeq1]; subst; allsimpl; cpx; clear h1.\n  allrw @var_ren_nil_l; allrw @lsubst_nil.\n  inversion h2 as [? ? ? ? ? disj2 ? ? norep2 aeq2]; subst; allsimpl; cpx; clear h2.\n  fold_terms.\n  exists nt2 x0 nt0; sp.\n  apply (al_bterm _ _ [x]); simpl; tcsp.\nQed.\n\nLemma alpha_eq_mk_fresh {o} :\n  forall v (a : @NTerm o) u,\n    alpha_eq (mk_fresh v a) u\n    -> {v' : NVar\n        & {a' : NTerm\n        & u = mk_fresh v' a'\n        # alpha_eq_bterm (bterm [v] a) (bterm [v'] a')}}.\nProof.\n  introv aeq.\n  inversion aeq as [|?|? ? ? len i]; subst; allsimpl.\n  destruct lbt2; allsimpl; repeat cpx.\n  pose proof (i 0) as h1; autodimp h1 hyp; allsimpl.\n  clear i.\n  unfold selectbt in h1; allsimpl.\n  inversion h1 as [? ? ? ? ? disj1 ? ? norep1 aeq1]; subst; allsimpl; cpx; clear h1.\n  allrw @var_ren_nil_l; allrw @lsubst_nil.\n  fold_terms.\n  exists x0 nt2; sp.\n  apply (al_bterm _ _ [x]); simpl; tcsp.\nQed.\n\nLemma alpha_eq_mk_ntry {o} :\n  forall en (t : @NTerm o) v a u,\n    alpha_eq (mk_try t en v a) u\n    -> {en' : NTerm\n        & {t' : NTerm\n        & {v' : NVar\n        & {a' : NTerm\n        & u = mk_try t' en' v' a'\n        # alpha_eq en en'\n        # alpha_eq t t'\n        # alpha_eq_bterm (bterm [v] a) (bterm [v'] a')}}}}.\nProof.\n  introv aeq.\n  inversion aeq as [|?|? ? ? len i]; subst; allsimpl.\n  repeat (destruct lbt2; allsimpl; repeat cpx).\n  pose proof (i 0) as h1; autodimp h1 hyp; allsimpl.\n  pose proof (i 1) as h2; autodimp h2 hyp; allsimpl.\n  pose proof (i 2) as h3; autodimp h3 hyp; allsimpl.\n  clear i.\n  unfold selectbt in h1, h2, h3; allsimpl.\n  inversion h1 as [? ? ? ? ? disj1 ? ? norep1 aeq1]; subst; allsimpl; cpx; clear h1.\n  allrw @var_ren_nil_l; allrw @lsubst_nil.\n  inversion h2 as [? ? ? ? ? disj2 ? ? norep2 aeq2]; subst; allsimpl; cpx; clear h2.\n  allrw @var_ren_nil_l; allrw @lsubst_nil.\n  inversion h3 as [? ? ? ? ? disj3 ? ? norep3 aeq3]; subst; allsimpl; cpx; clear h3.\n  fold_terms.\n  exists nt0 nt2 x0 nt3; sp.\n  apply (al_bterm _ _ [x]); simpl; tcsp.\nQed.\n\nLemma alpha_eq_mk_var {o} :\n  forall v (u : @NTerm o),\n    alpha_eq (mk_var v) u\n    -> u = mk_var v.\nProof.\n  introv aeq.\n  inversion aeq; subst; allsimpl; cpx.\nQed.\n\nLemma alpha_eq_mk_utoken {o} :\n  forall a (u : @NTerm o),\n    alpha_eq (mk_utoken a) u\n    -> u = mk_utoken a.\nProof.\n  introv aeq.\n  inversion aeq; subst; allsimpl; cpx.\nQed.\n\nLemma alpha_eq_bterm_nobnd {o} :\n  forall (t : @NTerm o) b,\n    alpha_eq_bterm (nobnd t) b\n    -> {u : NTerm & b = nobnd u # alpha_eq t u}.\nProof.\n  introv aeq.\n  inversion aeq; subst; allsimpl; cpx.\n  allrw @var_ren_nil_l; allrw @lsubst_nil.\n  eexists; dands; eauto; reflexivity.\nQed.\n\nLemma alpha_eq_mk_compop {o} :\n  forall c (t1 t2 t3 t4 u : @NTerm o),\n    alpha_eq (mk_compop c t1 t2 t3 t4) u\n    -> {t1' : NTerm\n        & {t2' : NTerm\n        & {t3' : NTerm\n        & {t4' : NTerm\n        & u = mk_compop c t1' t2' t3' t4'\n        # alpha_eq t1 t1'\n        # alpha_eq t2 t2'\n        # alpha_eq t3 t3'\n        # alpha_eq t4 t4'}}}}.\nProof.\n  introv aeq.\n  inversion aeq as [|?|? ? ? len i]; subst; allsimpl; cpx.\n  pose proof (i 0) as h1; autodimp h1 hyp; allsimpl.\n  pose proof (i 1) as h2; autodimp h2 hyp; allsimpl.\n  pose proof (i 2) as h3; autodimp h3 hyp; allsimpl.\n  pose proof (i 3) as h4; autodimp h4 hyp; allsimpl.\n  clear i.\n  allunfold @selectbt; allsimpl.\n  inversion h1; subst; allsimpl; cpx.\n  inversion h2; subst; allsimpl; cpx.\n  inversion h3; subst; allsimpl; cpx.\n  inversion h4; subst; allsimpl; cpx.\n  allrw @var_ren_nil_l.\n  allrw @lsubst_nil.\n  eexists; eexists; eexists; eexists; sp.\nQed.\n\nLemma alpha_eq_mk_arithop {o} :\n  forall c (t1 t2 u : @NTerm o),\n    alpha_eq (mk_arithop c t1 t2) u\n    -> {t1' : NTerm\n        & {t2' : NTerm\n        & u = mk_arithop c t1' t2'\n        # alpha_eq t1 t1'\n        # alpha_eq t2 t2'}}.\nProof.\n  introv aeq.\n  inversion aeq as [|?|? ? ? len i]; subst; allsimpl; cpx.\n  pose proof (i 0) as h1; autodimp h1 hyp; allsimpl.\n  pose proof (i 1) as h2; autodimp h2 hyp; allsimpl.\n  clear i.\n  allunfold @selectbt; allsimpl.\n  inversion h1; subst; allsimpl; cpx.\n  inversion h2; subst; allsimpl; cpx.\n  allrw @var_ren_nil_l.\n  allrw @lsubst_nil.\n  eexists; eexists; sp.\nQed.\n\nLemma alpha_eq_mk_cantest {o} :\n  forall c (t1 t2 t3 u : @NTerm o),\n    alpha_eq (mk_can_test c t1 t2 t3) u\n    -> {t1' : NTerm\n        & {t2' : NTerm\n        & {t3' : NTerm\n        & u = mk_can_test c t1' t2' t3'\n        # alpha_eq t1 t1'\n        # alpha_eq t2 t2'\n        # alpha_eq t3 t3'}}}.\nProof.\n  introv aeq.\n  inversion aeq as [|?|? ? ? len i]; subst; allsimpl; cpx.\n  pose proof (i 0) as h1; autodimp h1 hyp; allsimpl.\n  pose proof (i 1) as h2; autodimp h2 hyp; allsimpl.\n  pose proof (i 2) as h3; autodimp h3 hyp; allsimpl.\n  clear i.\n  allunfold @selectbt; allsimpl.\n  inversion h1; subst; allsimpl; cpx.\n  inversion h2; subst; allsimpl; cpx.\n  inversion h3; subst; allsimpl; cpx.\n  allrw @var_ren_nil_l.\n  allrw @lsubst_nil.\n  eexists; eexists; eexists; sp.\nQed.\n\nLemma alpha_eq_bterm_vterm {o} :\n  forall vs1 vs2 v (t : @NTerm o),\n    alpha_eq_bterm (bterm vs1 (vterm v)) (bterm vs2 t)\n    -> {v' : NVar & t = vterm v'}.\nProof.\n  introv aeq.\n  inversion aeq as [? ? ? ? ? disj len1 len2 norep a]; allsimpl; subst; clear aeq.\n  rw @lsubst_vterm in a.\n  remember (sub_find (var_ren vs1 lv) v) as op.\n  destruct op; allsimpl; symmetry in Heqop.\n  - apply sub_find_varsub in Heqop; exrepnd; repnd; subst.\n    inversion a as [x|?|]; subst.\n    allapply @lsubst_is_vterm; auto.\n  - inversion a as [x|?|]; subst.\n    allapply @lsubst_is_vterm; auto.\nQed.\n\nLemma fold_subst_aux {o} :\n  forall (t : @NTerm o) v u,\n    lsubst_aux t [(v,u)] = subst_aux t v u.\nProof. sp. Qed.\n\nLemma alphaeq_preserves_isnoncan_like {o} :\n  forall (t1 t2 : @NTerm o),\n    alpha_eq t1 t2\n    -> isnoncan_like t1\n    -> isnoncan_like t2.\nProof.\n  introv aeq isn.\n  allunfold @isnoncan_like; repndors.\n  - apply isnoncan_implies in isn; exrepnd; subst.\n    inversion aeq; subst; tcsp.\n  - apply isabs_implies in isn; exrepnd; subst.\n    inversion aeq; subst; tcsp.\nQed.\n\nLemma isnoncan_like_subst_aux_axiom_implies {o} :\n  forall (t : @NTerm o) v,\n    isnoncan_like (subst_aux t v mk_axiom)\n    -> isnoncan_like t.\nProof.\n  introv isn.\n  destruct t; allsimpl; tcsp.\n  unfold subst_aux in isn; allsimpl; boolvar; tcsp.\nQed.\n\nLemma isnoncan_like_subst_aux_utoken_implies {o} :\n  forall (t : @NTerm o) v a,\n    isnoncan_like (subst_aux t v (mk_utoken a))\n    -> isnoncan_like t.\nProof.\n  introv isn.\n  destruct t; allsimpl; tcsp.\n  unfold subst_aux in isn; allsimpl; boolvar; tcsp.\nQed.\n\nLemma null_flat_map :\n  forall (A B : tuniv) (f : A -> list B) (l : list A),\n    null (flat_map f l)\n    <=> (forall a : A, LIn a l -> null (f a)).\nProof.\n  induction l; allsimpl; split; introv k; tcsp.\n  - rw null_app in k; repnd.\n    introv i; repndors; subst; tcsp.\n    rw IHl in k; apply k; auto.\n  - rw null_app; dands; tcsp.\n    apply IHl; introv i.\n    apply k; tcsp.\nQed.\n\nLemma get_utokens_lsubst_aux_trivial1 {o} :\n  forall (t : @NTerm o) sub,\n    null (get_utokens_sub sub)\n    -> get_utokens (lsubst_aux t sub) = get_utokens t.\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv e; allsimpl; auto.\n\n  - Case \"vterm\".\n    remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; allsimpl; auto.\n    apply sub_find_some in Heqsf.\n    rw null_flat_map in e.\n    apply in_sub_eta in Heqsf; repnd.\n    apply e in Heqsf; auto.\n    rw null_iff_nil in Heqsf; auto.\n\n  - Case \"oterm\".\n    f_equal.\n    rw flat_map_map; unfold compose.\n    apply eq_flat_maps; introv i; destruct x as [l t]; allsimpl.\n    apply (ind t l); auto.\n    eapply null_subset;[|exact e].\n    apply get_utokens_sub_filter_subset.\nQed.\n\nLemma get_utokens_subst_aux_trivial1 {o} :\n  forall (t : @NTerm o) v u,\n    null (get_utokens u)\n    -> get_utokens (subst_aux t v u) = get_utokens t.\nProof.\n  introv n.\n  unfold subst_aux; apply get_utokens_lsubst_aux_trivial1; simpl.\n  unfold get_utokens_sub; simpl; rw app_nil_r; auto.\nQed.\n\nFixpoint size_sub {o} (sub : @Sub o) :=\n  match sub with\n    | [] => 0\n    | (v,t) :: s => (size t - 1) + size_sub s\n  end.\n\nLemma not_in_bound_vars_if_alpha_eq_bterm {o} :\n  forall (t1 t2 : @NTerm o) v1 v2,\n    alpha_eq_bterm (bterm [v1] t1) (bterm [v2] t2)\n    -> (!LIn v1 (free_vars t2) [+] v1 = v2).\nProof.\n  introv a.\n  destruct (deq_nvar v1 v2); subst; tcsp.\n  left; intro k.\n  apply alpha_eq_bterm_preserves_free_vars in a; allsimpl.\n  assert (LIn v1 (remove_nvars [v2] (free_vars t2))) as i.\n  { rw in_remove_nvars; simpl; tcsp. }\n  rw <- a in i.\n  rw in_remove_nvars in i; allsimpl; tcsp.\nQed.\n\nLemma atom_sub_compat_refl {o} :\n  forall (t : @NTerm o) s vs1 vs2,\n    atom_sub_compat t vs1 vs2 s s.\nProof.\n  induction s; introv; tcsp.\nQed.\nHint Resolve atom_sub_compat_refl : slow.\n\nLemma ce_change_atom_sub_trivial {o} :\n  forall lib : @compenv o,\n    ce_change_atom_sub lib (ce_atom_sub lib) = lib.\nProof.\n  introv.\n  unfold ce_change_atom_sub, mk_ce; simpl.\n  destruct lib; auto.\nQed.\n\n(*\nLemma compute_step_ncan_utoken_success {o} :\n  forall lib ncan a (bs : list (@BTerm o)) u,\n    compute_step lib (oterm (NCan ncan) (nobnd (mk_utoken a) :: bs))\n    = csuccess u\n    -> (ncan = NFix\n        # bs = []\n        # u = mk_apply (mk_utoken a) (mk_fix (mk_utoken a)))\n       [+]\n       {x : NVar\n        & {b : NTerm\n        & ncan = NCbv\n        # bs = [bterm [x] b]\n        # u = subst b x (mk_utoken a)}}\n       [+]\n       {x : NVar\n        & {b : NTerm\n        & {en : exc_name\n        & ncan = NTryCatch en\n        # bs = [bterm [x] b]\n        # u = mk_utoken a}}}\n        [+]\n        {t1 : NTerm\n         & {bs1 : list BTerm\n         & bs = nobnd t1 :: bs1\n         # ncan = NCompOp CompOpAtomeq\n        # (\n            {t2 : NTerm\n             & {t3 : NTerm\n             & {a' : get_patom_set o\n             & bs1 = [nobnd t2, nobnd t3]\n             # (t1 = mk_utoken a'\n                [+] {v : NVar\n                     & t1 = vterm v\n                     # find_atom (ce_atom_sub lib) v = Some a'})\n             # ((a = a' # u = t2) [+] (a <> a' # u = t3))}}}\n            [+]\n            {x : NTerm\n             & compute_step lib t1 = csuccess x\n             # isnoncan_like t1\n             # u = oterm (NCan ncan) (nobnd (mk_utoken a) :: nobnd x :: bs1) }\n            [+]\n            (isexc t1 # u = t1)\n          )}}\n       [+]\n       {t1 : NTerm\n        & {t2 : NTerm\n        & {x : CanonicalTest\n        & ncan = NCanTest x\n        # bs = [nobnd t1, nobnd t2]\n        # ((x = CanIsuatom # u = t1) [+] (x <> CanIsuatom # u = t2))}}}.\nProof.\n  introv comp.\n  allsimpl.\n  dopid_noncan ncan Case;\n    try (complete (allsimpl; ginv));\n    try (complete (destruct bs; ginv)).\n\n  - Case \"NFix\".\n    allsimpl.\n    apply compute_step_fix_success in comp; repnd; subst.\n    left; auto.\n\n  - Case \"NCbv\".\n    allsimpl.\n    apply compute_step_cbv_success in comp; exrepnd; subst.\n    right; left.\n    eexists; eexists; dands; eauto.\n\n  - Case \"NTryCatch\".\n    allsimpl.\n    apply compute_step_try_success in comp; exrepnd; subst.\n    right; right; left.\n    eexists; eexists; eexists; auto.\n\n  - Case \"NCompOp\".\n    right; right; right; left.\n    destruct bs; ginv; try (complete (allsimpl; boolvar; ginv)).\n    destruct b as [l t].\n    destruct l; ginv; try (complete (allsimpl; boolvar; ginv)).\n    destruct t as [v1|op1 bs1]; try (complete (allsimpl; boolvar; ginv)).\n\n    + allsimpl; boolvar; allsimpl; tcsp; GC; ginv.\n      unfold compute_var in comp.\n      dest_find_atom a' e'; allsimpl.\n      unfold compute_step_comp in comp; allsimpl.\n      destruct bs; ginv.\n      destruct b as [l t].\n      destruct l; ginv.\n      destruct bs; ginv.\n      destruct b as [l t2].\n      destruct l; ginv.\n      destruct bs; ginv.\n      destruct c; ginv.\n      exists (@vterm o v1) [nobnd t, nobnd t2]; dands; auto.\n      left.\n      exists t t2  a'; dands; boolvar; tcsp.\n      right.\n      exists v1; sp.\n\n    + dopid op1 as [can1|ncan1|exc1|mrk1|abs1] SCase.\n\n      * SCase \"Can\".\n        allsimpl; boolvar; allsimpl; tcsp; GC; ginv.\n        unfold compute_step_comp in comp.\n        destruct bs1; allsimpl; ginv.\n        destruct bs; allsimpl; ginv.\n        destruct b as [l t1].\n        destruct l; ginv.\n        destruct bs; allsimpl; ginv.\n        destruct b as [l t2].\n        destruct l; ginv.\n        destruct bs; allsimpl; ginv.\n        destruct c; ginv.\n\n        remember (get_str_from_cop can1) as g.\n        symmetry in Heqg; destruct g; ginv.\n        allapply @get_param_from_cop_pka; subst.\n\n        exists (mk_utoken g) [nobnd t1, nobnd t2]; dands; auto.\n        left.\n        exists t1 t2 g; dands; boolvar; auto.\n\n      * SCase \"NCan\".\n        remember (compute_step lib (oterm (NCan ncan1) bs1)) as c1; ginv.\n        destruct c1;\n          try (complete (allsimpl; boolvar; allsimpl; tcsp; ginv;\n                         rw <- Heqc1 in comp; allsimpl; ginv)).\n        exists (oterm (NCan ncan1) bs1) bs; dands; auto.\n        { simpl in comp; boolvar; ginv; destruct c; allsimpl; allsimpl; tcsp. }\n        right; left.\n        exists n; dands; auto.\n        allsimpl; boolvar; allsimpl; tcsp; ginv; rw <- Heqc1 in comp; allsimpl; ginv; auto.\n\n      * SCase \"Exc\".\n        allsimpl; ginv; boolvar; allsimpl; tcsp; ginv.\n        exists (oterm (Exc exc1) bs1) bs; dands; auto.\n        { destruct c; allsimpl; allsimpl; tcsp. }\n\n      * SCase \"Mrk\".\n        allsimpl; ginv; boolvar; allsimpl; tcsp; ginv.\n\n      * SCase \"Abs\".\n        remember (compute_step lib (oterm (Abs abs1) bs1)) as c1; ginv.\n        destruct c1; try (complete (allsimpl; boolvar; allsimpl; tcsp; ginv; rw <- Heqc1 in comp; allsimpl; ginv)).\n        exists (oterm (Abs abs1) bs1) bs; dands; auto.\n        { simpl in comp; boolvar; ginv; destruct c; allsimpl; allsimpl; tcsp. }\n        right; left.\n        exists n; dands; auto.\n        allsimpl; boolvar; allsimpl; tcsp; ginv; rw <- Heqc1 in comp; allsimpl; ginv; auto.\n\n  - Case \"NArithOp\".\n    allsimpl; boolvar; allsimpl; tcsp; ginv.\n\n  - Case \"NCanTest\".\n    right; right; right; right.\n    allsimpl.\n    apply compute_step_can_test_success in comp; exrepnd; subst.\n    exists arg2nt arg3nt c; dands; auto.\n    destruct c; allsimpl; tcsp;\n    try (complete (right; dands; auto; intro k; inversion k)).\nQed.\n*)\n\nLemma free_vars_utok_sub_swap_utok_sub {o} :\n  forall (vs1 vs2 : list NVar) (sub : @utok_sub o),\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> free_vars_utok_sub (swap_utok_sub (mk_swapping vs1 vs2) sub)\n       = swapbvars (mk_swapping vs1 vs2) (free_vars_utok_sub sub).\nProof.\n  induction sub; introv norep disj; allsimpl; tcsp.\n  destruct a; allsimpl.\n  rw swapbvars_app; f_equal; tcsp.\n  apply free_vars_swap; auto.\nQed.\n\nLemma free_vars_utok_sub_cswap_utok_sub {o} :\n  forall (vs1 vs2 : list NVar) (sub : @utok_sub o),\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> free_vars_utok_sub (cswap_utok_sub (mk_swapping vs1 vs2) sub)\n       = swapbvars (mk_swapping vs1 vs2) (free_vars_utok_sub sub).\nProof.\n  induction sub; introv norep disj; allsimpl; tcsp.\n  destruct a; allsimpl.\n  rw swapbvars_app; f_equal; tcsp.\n  apply free_vars_cswap; auto.\nQed.\n\nLemma alpha_eq_same_cswap {o} :\n  forall (t1 t2 : @NTerm o) vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> length vs1 = length vs2\n    -> alpha_eq t1 t2\n    -> alpha_eq (cswap (mk_swapping vs1 vs2) t1) (cswap (mk_swapping vs1 vs2) t2).\nProof.\n  introv norep disj len aeq.\n  allrw <- @alphaeq_eq.\n  pose proof (alphaeq_add_cswap [] vs1 vs2 t1 t2) as h; allrw app_nil_r.\n  repeat (autodimp h hyp); eauto with slow.\n  - apply alphaeq_implies_alphaeq_vs; auto.\n  - rw @alphaeq_exists; eexists; eauto.\nQed.\n\nLemma subst_utokens_swap_swap {o} :\n  forall (t : @NTerm o) vs1 vs2 sub,\n    no_repeats vs2\n    -> disjoint vs1 vs2\n    -> length vs1 = length vs2\n    -> alpha_eq\n         (cswap (mk_swapping vs1 vs2) (subst_utokens t sub))\n         (subst_utokens (cswap (mk_swapping vs1 vs2) t)\n                        (cswap_utok_sub (mk_swapping vs1 vs2) sub)).\nProof.\n  introv norep disj len.\n  pose proof (unfold_subst_utokens sub t) as h; exrepnd.\n  rw h0.\n  rw @cswap_subst_utokens_aux.\n  pose proof (unfold_subst_utokens\n                (cswap_utok_sub (mk_swapping vs1 vs2) sub)\n                (cswap (mk_swapping vs1 vs2) t)) as k; exrepnd.\n  rw k0.\n\n  apply alpha_eq_subst_utokens_aux; eauto with slow.\n  - rw @bound_vars_cswap.\n    rw @free_vars_utok_sub_cswap_utok_sub; auto.\n    apply disjoint_swap; eauto with slow.\n  - eapply alpha_eq_trans;[|exact k1].\n    apply alpha_eq_same_cswap; eauto with slow.\nQed.\n\nLemma implies_alpha_eq_mk_atom_eq {o} :\n  forall (a1 a2 b1 b2 c1 c2 d1 d2 : @NTerm o),\n    alpha_eq a1 a2\n    -> alpha_eq b1 b2\n    -> alpha_eq c1 c2\n    -> alpha_eq d1 d2\n    -> alpha_eq (mk_atom_eq a1 b1 c1 d1) (mk_atom_eq a2 b2 c2 d2).\nProof.\n  introv aeq1 aeq2 aeq3 aeq4.\n  unfold mk_atom_eq, nobnd.\n  prove_alpha_eq4.\n  introv i.\n  repeat (destruct n; cpx); apply alphaeqbt_nilv2; auto.\nQed.\n\nLemma cswap_alpha_congr {o} :\n  forall l1 l2 vs (t1 t2 : @NTerm o),\n    length vs = length l1\n    -> no_repeats vs\n    -> disjoint vs l1\n    -> disjoint vs (allvars t1)\n    -> disjoint vs l2\n    -> disjoint vs (allvars t2)\n    -> alpha_eq_bterm (bterm l1 t1) (bterm l2 t2)\n    -> alpha_eq (cswap (mk_swapping l1 vs) t1) (cswap (mk_swapping l2 vs) t2).\nProof.\n  introv len norep d1 d2 d3 d4 aeq.\n  apply alphaeqbt_eq in aeq.\n  rw @alphaeqbt_all in aeq.\n  pose proof (aeq vs) as h; clear aeq.\n  inversion h as [? ? ? ? ? len1 len2 disj1 norep1 a]; subst; clear h.\n  allrw disjoint_app_r; repnd.\n  apply (alphaeq_vs_implies_less _ _ _ []) in a; auto.\n  apply alphaeq_eq in a.\n  apply (alpha_eq_same_cswap _ _ vs0 vs) in a; auto; try omega.\n  allrw @cswap_cswap.\n  repeat (rw mk_swapping_app in a; auto).\n  repeat (rw @cswap_disj_chain in a; auto; try omega;\n          allrw disjoint_app_r; dands; eauto 3 with slow).\nQed.\n\nLemma alpha_eq_mk_apply {o} :\n  forall (a b : @NTerm o) t,\n    alpha_eq (mk_apply a b) t\n    -> {a' : NTerm\n        & {b' : NTerm\n        & t = mk_apply a' b'\n        # alpha_eq a a'\n        # alpha_eq b b' }}.\nProof.\n  introv aeq.\n  apply alpha_eq_oterm_implies_combine in aeq.\n  exrepnd; subst; allsimpl; cpx; allsimpl.\n  pose proof (aeq0 (nobnd a) x) as h1; autodimp h1 hyp.\n  pose proof (aeq0 (nobnd b) y) as h2; autodimp h2 hyp.\n  clear aeq0.\n  allapply @alpha_eq_bterm_nobnd; exrepnd; subst.\n  exists u0 u; dands; auto.\nQed.\n\nLemma alpha_eq_mk_eapply {o} :\n  forall (a b : @NTerm o) t,\n    alpha_eq (mk_eapply a b) t\n    -> {a' : NTerm\n        & {b' : NTerm\n        & t = mk_eapply a' b'\n        # alpha_eq a a'\n        # alpha_eq b b' }}.\nProof.\n  introv aeq.\n  apply alpha_eq_oterm_implies_combine in aeq.\n  exrepnd; subst; allsimpl; cpx; allsimpl.\n  pose proof (aeq0 (nobnd a) x) as h1; autodimp h1 hyp.\n  pose proof (aeq0 (nobnd b) y) as h2; autodimp h2 hyp.\n  clear aeq0.\n  allapply @alpha_eq_bterm_nobnd; exrepnd; subst.\n  exists u0 u; dands; auto.\nQed.\n\nLemma alpha_eq_sterm {o} :\n  forall (f : @ntseq o) t,\n    alpha_eq (sterm f) t\n    -> {g : ntseq\n        & t = sterm g\n        # forall n, alpha_eq (f n) (g n) }.\nProof.\n  introv aeq.\n  inversion aeq as [|? ? imp|]; subst.\n  eexists; dands; eauto.\nQed.\n\nLemma implies_alpha_eq_mk_apply {o} :\n  forall f1 f2 a1 a2 : @NTerm o,\n    alpha_eq f1 f2\n    -> alpha_eq a1 a2\n    -> alpha_eq (mk_apply f1 a1) (mk_apply f2 a2).\nProof.\n  introv aeq1 aeq2.\n  apply alpha_eq_oterm_combine; simpl; dands; auto.\n  introv i; repndors; tcsp; ginv; apply alphaeqbt_nilv2; auto.\nQed.\n\nLemma implies_alpha_eq_mk_eapply {o} :\n  forall f1 f2 a1 a2 : @NTerm o,\n    alpha_eq f1 f2\n    -> alpha_eq a1 a2\n    -> alpha_eq (mk_eapply f1 a1) (mk_eapply f2 a2).\nProof.\n  introv aeq1 aeq2.\n  apply alpha_eq_oterm_combine; simpl; dands; auto.\n  introv i; repndors; tcsp; ginv; apply alphaeqbt_nilv2; auto.\nQed.\n\nLemma implies_alpha_eq_mk_fix {o} :\n  forall a1 a2 : @NTerm o,\n    alpha_eq a1 a2\n    -> alpha_eq (mk_fix a1) (mk_fix a2).\nProof.\n  introv aeq.\n  apply alpha_eq_oterm_combine; simpl; dands; auto.\n  introv i; repndors; tcsp; ginv; apply alphaeqbt_nilv2; auto.\nQed.\n\nLemma implies_alpha_eq_sterm {o} :\n  forall (f g : @ntseq o),\n    (forall n, alpha_eq (f n) (g n))\n    -> alpha_eq (sterm f) (sterm g).\nProof.\n  introv imp.\n  constructor; auto.\nQed.\n\nLemma alpha_eq_mk_nat {o} :\n  forall i (u : @NTerm o),\n    alpha_eq (mk_nat i) u\n    -> u = mk_nat i.\nProof.\n  introv aeq.\n  inversion aeq; subst; allsimpl; cpx.\nQed.\n\nLemma compute_step_eapply_iscan_isnoncan_like {o} :\n  forall lib (x t : @NTerm o) bs,\n    eapply_wf_def x\n    -> isnoncan_like t\n    -> compute_step lib (oterm (NCan NEApply) (nobnd x :: nobnd t :: bs))\n       = match compute_step lib t with\n           | csuccess u => csuccess (oterm (NCan NEApply) (nobnd x :: nobnd u :: bs))\n           | cfailure m u => cfailure m u\n         end.\nProof.\n  introv ew isn.\n  unfold isnoncan_like in isn.\n  unfold eapply_wf_def in ew; repndors; exrepnd; subst.\n  - apply isnoncan_implies in isn; exrepnd; subst.\n    csunf; simpl.\n    remember (compute_step lib (oterm (NCan c) bterms)) as comp;\n      destruct comp; simpl; auto;\n      try (complete (unfold compute_step_eapply; dcwf h)).\n  - apply isnoncan_implies in isn; exrepnd; subst.\n    csunf; simpl.\n    remember (compute_step lib (oterm (NCan c) bterms)) as comp;\n      destruct comp; simpl; auto.\n  - apply isnoncan_implies in isn; exrepnd; subst.\n    csunf; simpl.\n    remember (compute_step lib (oterm (NCan c) bterms)) as comp;\n      destruct comp; simpl; auto.\n  - apply isabs_implies in isn; exrepnd; subst.\n    csunf; simpl.\n    remember (compute_step lib (oterm (Abs abs) bterms)) as comp;\n      destruct comp; simpl; auto;\n      try (complete (unfold compute_step_eapply; dcwf h)).\n  - apply isabs_implies in isn; exrepnd; subst.\n    csunf; simpl.\n    remember (compute_step lib (oterm (Abs abs) bterms)) as comp; destruct comp; simpl; auto.\n  - apply isabs_implies in isn; exrepnd; subst.\n    csunf; simpl.\n    remember (compute_step lib (oterm (Abs abs) bterms)) as comp; destruct comp; simpl; auto.\nQed.\n\nLemma compute_step_eapply_lam_iscan {o} :\n  forall lib v (b t : @NTerm o) bs,\n    iscan t\n    -> compute_step lib (oterm (NCan NEApply) (nobnd (mk_lam v b) :: nobnd t :: bs))\n       = match bs with\n           | [] => csuccess (subst b v t)\n           | _ => cfailure\n                    bad_args\n                    (oterm (NCan NEApply) (nobnd (mk_lam v b) :: nobnd t :: bs))\n         end.\nProof.\n  introv isc.\n  apply iscan_implies in isc; repndors; exrepnd; subst.\n  - csunf; simpl.\n    unfold compute_step_eapply2; simpl.\n    unfold apply_bterm; simpl; allrw @fold_subst; auto.\n  - csunf; simpl.\n    unfold compute_step_eapply2; simpl.\n    unfold apply_bterm; simpl; allrw @fold_subst; auto.\nQed.\n\nLemma alpha_eq_mk_fix {o} :\n  forall (t u : @NTerm o),\n    alpha_eq (mk_fix t) u\n    -> {x : NTerm & u = mk_fix x # alpha_eq t x}.\nProof.\n  introv aeq.\n  inversion aeq as [|?|? ? ? len i]; subst; allsimpl; cpx.\n  pose proof (i 0) as h; autodimp h hyp; allsimpl.\n  unfold selectbt in h; allsimpl.\n  inversion h; subst; allsimpl; cpx.\n  allrw @var_ren_nil_l.\n  allrw @lsubst_nil.\n  exists nt2; sp.\nQed.\n\nLemma alpha_eq_bterm_sterm {o} :\n  forall vs1 vs2 f (t : @NTerm o),\n    alpha_eq_bterm (bterm vs1 (sterm f)) (bterm vs2 t)\n    -> {g : ntseq & t = sterm g}.\nProof.\n  introv aeq.\n  inversion aeq as [? ? ? ? ? disj len1 len2 norep a]; allsimpl; subst; clear aeq.\n  allrw disjoint_app_r; repnd.\n  repeat (rw @lsubst_lsubst_aux2 in a; simpl; tcsp; eauto 3 with slow).\n  simpl in a.\n  inversion a as [|? g imp|]; subst; clear a.\n  destruct t; allsimpl; ginv.\n  - remember (sub_find (var_ren vs2 lv) n) as sf.\n    destruct sf; allsimpl; symmetry in Heqsf; subst; ginv.\n    apply sub_find_varsub in Heqsf; exrepnd; ginv.\n  - eexists; eauto.\nQed.\n\nLemma get_utokens_step_seq_cswap {o} :\n  forall s (t : @NTerm o),\n    get_utokens_step_seq (cswap s t) = get_utokens_step_seq t.\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; simpl; auto.\n  apply app_if; auto;[].\n  apply app_if; auto;[|].\n  - rw flat_map_map; unfold compose.\n    apply eq_flat_maps; introv i.\n    destruct x; simpl.\n    eapply ind; eauto.\n  - dopid op as [can|ncan|exc|abs] SCase; auto.\n    + SCase \"NCan\".\n      dopid_noncan ncan SSCase; simpl; auto.\n      * SSCase \"NApply\".\n        destruct bs; simpl; auto;[].\n        destruct b as [l t]; simpl.\n        destruct l; simpl; auto;[].\n        destruct t as [v|f|op bs']; simpl; auto;[].\n        destruct bs; simpl; auto;[].\n        destruct b as [l t]; simpl.\n        destruct l; simpl; auto;[].\n        destruct t as [v|g|op bs']; simpl; auto.\n      * SSCase \"NEApply\".\n        destruct bs; simpl; auto;[].\n        destruct b as [l t]; simpl.\n        destruct l; simpl; auto;[].\n        destruct t as [v|f|op bs']; simpl; auto;[].\n        destruct bs; simpl; auto;[].\n        destruct b as [l t]; simpl.\n        destruct l; simpl; auto;[].\n        destruct t as [v|g|op bs']; simpl; auto.\nQed.\n\nLemma alphaeq_preserves_get_utokens_step_seq {o} :\n  forall (t1 t2 : @NTerm o),\n    alpha_eq t1 t2\n    -> get_utokens_step_seq t1 = get_utokens_step_seq t2.\nProof.\n  nterm_ind1s t1 as [v1|f1 ind1|op1 bs1 ind1] Case; introv aeq; allsimpl.\n\n  - Case \"vterm\".\n    inversion aeq; subst; clear aeq; allsimpl; auto.\n\n  - Case \"sterm\".\n    apply alpha_eq_sterm in aeq; exrepnd; subst.\n    simpl; auto.\n\n  - Case \"oterm\".\n    apply alpha_eq_oterm_implies_combine in aeq; exrepnd; subst; allsimpl.\n    apply f_equal;[].\n    apply app_if.\n\n    { apply eq_flat_maps_diff; auto.\n      introv i; applydup aeq0 in i.\n      destruct t1 as [l1 t1].\n      destruct t2 as [l2 t2].\n      allsimpl.\n      apply alphaeqbt_eq in i0.\n      inversion i0 as [? ? ? ? ? len1 len2 disj norep a]; subst; allsimpl; clear i0.\n      applydup in_combine in i; repnd.\n      pose proof (ind1 t1\n                       (cswap (mk_swapping l1 vs) t1)\n                       l1) as h;\n        repeat (autodimp h hyp); allrw @osize_cswap; eauto 3 with slow.\n      pose proof (h (cswap (mk_swapping l2 vs) t2)) as x; clear h.\n      apply alphaeq_eq in a.\n      autodimp x hyp.\n      allrw @get_utokens_step_seq_cswap; auto. }\n\n    dopid op1 as [can|ncan|exc|abs] SCase; simpl; auto.\n\n    + SCase \"NCan\".\n      dopid_noncan ncan SSCase; simpl; auto.\n\n      * SSCase \"NApply\".\n        destruct bs1; allsimpl; cpx; auto;[].\n        destruct bs'; allsimpl; cpx;[].\n        destruct b as [l1 t1]; simpl.\n        destruct b0 as [l2 t2]; simpl.\n        pose proof (aeq0 (bterm l1 t1) (bterm l2 t2)) as aeq; autodimp aeq hyp.\n        applydup @alphaeqbt_numbvars in aeq.\n        unfold num_bvars in aeq1; allsimpl.\n        destruct l1; allsimpl; cpx;[|destruct l2; allsimpl; cpx];[].\n        allrw @alphaeqbt_nilv2.\n\n        destruct t1 as [v|f|op bs1'];allsimpl;auto;[| |].\n\n        { inversion aeq; auto. }\n\n        { inversion aeq; allsimpl; subst.\n          destruct bs1; allsimpl; cpx.\n          destruct bs'; allsimpl; cpx.\n          pose proof (aeq0 b b0) as aeq1; autodimp aeq1 hyp.\n          destruct b as [l1 t1]; simpl.\n          destruct b0 as [l2 t2]; simpl.\n          applydup @alphaeqbt_numbvars in aeq1.\n          allunfold @num_bvars; allsimpl.\n          destruct l1; allsimpl; cpx;[|destruct l2; allsimpl; cpx];[].\n          allrw @alphaeqbt_nilv2.\n\n          destruct t1 as [v|f1|op bs1'];allsimpl;auto;[| |].\n\n          { inversion aeq1; auto. }\n\n          { inversion aeq1; allsimpl; subst; auto. }\n\n          { apply alpha_eq_oterm_implies_combine in aeq1; exrepnd; subst; auto.\n            dopid op as [can|ncan|exc|abs] SSSCase; simpl; auto;[].\n            destruct can; simpl; auto.\n            boolvar; auto.\n            pose proof (ind1 (sterm f) (f (Z.to_nat z)) []) as h;\n              allsimpl; repeat (autodimp h hyp).\n            eapply ord_le_trans;[|apply ord_le_OS].\n            eapply implies_ord_le_limit_right; apply ord_le_refl. }\n        }\n\n        apply alpha_eq_oterm_implies_combine in aeq; exrepnd; subst; auto.\n\n      * SSCase \"NEApply\".\n        destruct bs1; allsimpl; cpx; auto;[].\n        destruct bs'; allsimpl; cpx;[].\n        destruct b as [l1 t1]; simpl.\n        destruct b0 as [l2 t2]; simpl.\n        pose proof (aeq0 (bterm l1 t1) (bterm l2 t2)) as aeq; autodimp aeq hyp.\n        applydup @alphaeqbt_numbvars in aeq.\n        unfold num_bvars in aeq1; allsimpl.\n        destruct l1; allsimpl; cpx;[|destruct l2; allsimpl; cpx];[].\n        allrw @alphaeqbt_nilv2.\n\n        destruct t1 as [v|f|op bs1'];allsimpl;auto;[| |].\n\n        { inversion aeq; auto. }\n\n        { inversion aeq; allsimpl; subst.\n          destruct bs1; allsimpl; cpx.\n          destruct bs'; allsimpl; cpx.\n          pose proof (aeq0 b b0) as aeq1; autodimp aeq1 hyp.\n          destruct b as [l1 t1]; simpl.\n          destruct b0 as [l2 t2]; simpl.\n          applydup @alphaeqbt_numbvars in aeq1.\n          allunfold @num_bvars; allsimpl.\n          destruct l1; allsimpl; cpx;[|destruct l2; allsimpl; cpx];[].\n          allrw @alphaeqbt_nilv2.\n\n          destruct t1 as [v|f1|op bs1'];allsimpl;auto;[| |].\n\n          { inversion aeq1; auto. }\n\n          { inversion aeq1; allsimpl; subst; auto. }\n\n          { apply alpha_eq_oterm_implies_combine in aeq1; exrepnd; subst; auto.\n            dopid op as [can|ncan|exc|abs] SSSCase; simpl; auto;[].\n            destruct can; simpl; auto.\n            boolvar; auto.\n            pose proof (ind1 (sterm f) (f (Z.to_nat z)) []) as h;\n              allsimpl; repeat (autodimp h hyp).\n            eapply ord_le_trans;[|apply ord_le_OS].\n            eapply implies_ord_le_limit_right; apply ord_le_refl. }\n        }\n\n        apply alpha_eq_oterm_implies_combine in aeq; exrepnd; subst; auto.\nQed.\n\nLemma compute_step_eapply_iscan_isexc {o} :\n  forall lib (x t : @NTerm o) bs,\n    eapply_wf_def x\n    -> iscan x\n    -> isexc t\n    -> compute_step lib (oterm (NCan NEApply) (nobnd x :: nobnd t :: bs))\n       = csuccess t.\nProof.\n  introv ew isc ise.\n  apply isexc_implies2 in ise.\n  apply iscan_implies in isc; repndors; exrepnd; subst;\n  csunf; simpl; auto.\n  unfold compute_step_eapply; dcwf h; auto.\nQed.\n\nDefinition get_utokens_step_seq_sub {o} (sub : @Sub o) :=\n  flat_map get_utokens_step_seq (range sub).\n\nLemma get_utokens_step_seq_sub_filter_subset {o} :\n  forall (sub : @Sub o) l,\n    subset (get_utokens_step_seq_sub (sub_filter sub l)) (get_utokens_step_seq_sub sub).\nProof.\n  unfold get_utokens_step_seq_sub; introv i.\n  allrw lin_flat_map; exrepnd.\n  exists x0; dands; auto.\n  apply range_sub_filter_subset in i1; auto.\nQed.\n\nDefinition onull {T} (o : OList T) := forall x, !in_olist x o.\n\nLemma get_cutokens_sub_cons {o} :\n  forall v (t : @NTerm o) sub,\n    get_cutokens_sub ((v,t) :: sub)\n    = oapp (get_cutokens t) (get_cutokens_sub sub).\nProof.\n  introv.\n  unfold get_cutokens_sub; allsimpl.\n  rw @oeqset_oappl_cons; auto.\nQed.\n\nLemma onull_oapp {T} :\n  forall (o1 o2 : OList T),\n    onull (oapp o1 o2) <=> (onull o1 # onull o2).\nProof.\n  introv.\n  unfold onull; split; introv h; repnd; dands; introv i.\n  - pose proof (h x) as q.\n    allrw @in_olist_oapp; destruct q; sp.\n  - pose proof (h x) as q.\n    allrw @in_olist_oapp; destruct q; sp.\n  - allrw @in_olist_oapp; repndors.\n    + apply h0 in i; sp.\n    + apply h in i; sp.\nQed.\n\nLemma onull_get_cutokens_sub_in {o} :\n  forall (sub : @Sub o) v t,\n    onull (get_cutokens_sub sub)\n    -> LIn (v,t) sub\n    -> onull (get_cutokens t).\nProof.\n  induction sub; introv h1 h2; allsimpl; ginv; tcsp.\n  destruct a; allsimpl.\n  rw @get_cutokens_sub_cons in h1.\n  apply onull_oapp in h1; repnd.\n  repndors; tcsp; ginv; auto.\n  eapply IHsub; eauto.\nQed.\n\nLemma subseto_get_utokens_step_seq_get_cutokens {o} :\n  forall (t : @NTerm o),\n    subseto (get_utokens_step_seq t) (get_cutokens t).\nProof.\n  nterm_ind1s t as [v|f ind|op bs ind] Case; simpl; eauto 3 with slow;[].\n  Case \"oterm\".\n  introv i.\n  allrw in_app_iff; repndors.\n  - apply in_olist_oappl_app; left.\n    unfold oatomvs.\n    apply in_olist_oappl.\n    apply in_olist_OLL_map.\n    eexists; dands; eauto.\n    unfold oatomv; constructor.\n  - allrw lin_flat_map; exrepnd.\n    destruct x0 as [l t]; allsimpl.\n    eapply ind in i0; eauto 3 with slow.\n    apply in_olist_oappl_app; right.\n    apply in_olist_oappl.\n    apply in_olist_OLL_map.\n    eexists; dands; eauto.\n  - dopid op as [can|ncan|exc|abs] SCase; allsimpl; tcsp;[].\n    dopid_noncan ncan SSCase; allsimpl; tcsp.\n    + destruct bs; allsimpl; tcsp.\n      destruct b as [l t]; allsimpl.\n      destruct l; allsimpl; tcsp.\n      destruct t as [v|f|op bs1]; allsimpl; tcsp;[].\n      destruct bs; allsimpl; tcsp.\n      destruct b as [l t]; allsimpl.\n      destruct l; allsimpl; tcsp.\n      destruct t as [v|g|op bs1]; allsimpl; tcsp;[].\n      dopid op as [can|ncan|exc|abs] SSSCase; allsimpl; tcsp.\n      destruct can; allsimpl; tcsp.\n      boolvar; allsimpl; tcsp.\n      pose proof (ind (sterm f) (f (Z.to_nat z)) []) as h;\n        repeat (autodimp h hyp); simpl.\n      { eapply ord_le_trans;[|apply ord_le_OS].\n        eapply implies_ord_le_limit_right; apply ord_le_refl. }\n      apply h in i.\n      unfold oatoms.\n      apply in_olist_oappl.\n      apply in_olist_OLL_cons; left.\n      apply in_olist_s; eexists; eauto.\n    + destruct bs; allsimpl; tcsp.\n      destruct b as [l t]; allsimpl.\n      destruct l; allsimpl; tcsp.\n      destruct t as [v|f|op bs1]; allsimpl; tcsp;[].\n      destruct bs; allsimpl; tcsp.\n      destruct b as [l t]; allsimpl.\n      destruct l; allsimpl; tcsp.\n      destruct t as [v|g|op bs1]; allsimpl; tcsp;[].\n      dopid op as [can|ncan|exc|abs] SSSCase; allsimpl; tcsp.\n      destruct can; allsimpl; tcsp.\n      boolvar; allsimpl; tcsp.\n      pose proof (ind (sterm f) (f (Z.to_nat z)) []) as h;\n        repeat (autodimp h hyp); simpl.\n      { eapply ord_le_trans;[|apply ord_le_OS].\n        eapply implies_ord_le_limit_right; apply ord_le_refl. }\n      apply h in i.\n      unfold oatoms.\n      apply in_olist_oappl.\n      apply in_olist_OLL_cons; left.\n      apply in_olist_s; eexists; eauto.\nQed.\n\nLemma onull_get_cutokens_implies_null_get_utokens_step_seq {o} :\n  forall (t : @NTerm o),\n    onull (get_cutokens t)\n    -> null (get_utokens_step_seq t).\nProof.\n  introv h i.\n  apply subseto_get_utokens_step_seq_get_cutokens in i.\n  apply h in i; sp.\nQed.\n\nLemma onull_OLS {T} :\n  forall (f : nat -> OList T),\n    onull (OLS f) <=> (forall n, onull (f n)).\nProof.\n  introv.\n  split; intro h; introv.\n  - introv i.\n    destruct (h x).\n    constructor; eexists; eauto.\n  - introv i.\n    inversion i as [|?|? q]; exrepnd; subst.\n    apply h in q0; sp.\nQed.\n\nDefinition is_ax_sub {o} (sub : @Sub o) :=\n  forall v t, LIn (v,t) sub -> t = mk_axiom.\n\nLemma get_utokens_step_seq_lsubst_aux_trivial1 {o} :\n  forall (t : @NTerm o) sub,\n    is_ax_sub sub\n    -> get_utokens_step_seq (lsubst_aux t sub) = get_utokens_step_seq t.\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv e; allsimpl; auto.\n\n  - Case \"vterm\".\n    remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; allsimpl; auto.\n    apply sub_find_some in Heqsf.\n    apply e in Heqsf; subst; simpl; auto.\n\n  - Case \"oterm\".\n    f_equal.\n    rw flat_map_map; unfold compose.\n    apply app_if.\n\n    + apply eq_flat_maps; introv i; destruct x as [l t]; allsimpl.\n      apply (ind t l); auto.\n      introv j; allrw @in_sub_filter; repnd; apply e in j0; auto.\n\n    + dopid op as [can|ncan|exc|abs] SCase; auto.\n\n      * SCase \"NCan\".\n        dopid_noncan ncan SSCase; simpl; auto.\n\n        { SSCase \"NApply\".\n          destruct bs; simpl; auto;[].\n          destruct b as [l t]; simpl.\n          destruct l; simpl; auto;[].\n          allrw @sub_filter_nil_r.\n          destruct t as [v|f|op bs']; simpl; auto;[|].\n\n          { remember (sub_find sub v) as sf; destruct sf; allsimpl; auto;[].\n            destruct n; allsimpl; auto;[].\n            destruct bs; allsimpl; auto;[].\n            destruct b as [l t]; simpl.\n            destruct l; allsimpl; auto;[].\n            allrw @sub_filter_nil_r.\n            destruct t as [x|f|op bs1]; allsimpl; auto;[|].\n\n            { remember (sub_find sub x) as sf1; destruct sf1; allsimpl; auto;[].\n              destruct n0 as [|?|op bs1]; auto;[].\n              dopid op as [can|ncan|exc|abs] SSSCase; auto;[].\n              destruct can; simpl; auto.\n              boolvar; simpl; auto.\n              symmetry in Heqsf.\n              apply sub_find_some in Heqsf.\n              apply e in Heqsf; ginv. }\n\n            { dopid op as [can|ncan|exc|abs] SSSCase; allsimpl; tcsp;[].\n              destruct can; allsimpl; tcsp.\n              boolvar; auto.\n              symmetry in Heqsf.\n              apply sub_find_some in Heqsf.\n              apply e in Heqsf; ginv. }\n          }\n\n          destruct bs; simpl; auto;[].\n          destruct b as [l t]; simpl.\n          destruct l; simpl; auto;[].\n          allrw @sub_filter_nil_r.\n          destruct t as [v|g|op bs']; simpl; auto;[].\n\n          remember (sub_find sub v) as sf; destruct sf; allsimpl; auto;[].\n          destruct n as [|?|op bs1]; allsimpl; auto;[].\n          dopid op as [can|ncan|exc|abs] SSSCase; auto;[].\n          destruct can; simpl; auto.\n          boolvar; simpl; auto.\n          symmetry in Heqsf.\n          apply sub_find_some in Heqsf.\n          apply e in Heqsf; ginv.\n        }\n\n        { SSCase \"NEApply\".\n          destruct bs; simpl; auto;[].\n          destruct b as [l t]; simpl.\n          destruct l; simpl; auto;[].\n          allrw @sub_filter_nil_r.\n          destruct t as [v|f|op bs']; simpl; auto;[|].\n\n          { remember (sub_find sub v) as sf; destruct sf; allsimpl; auto;[].\n            destruct n; allsimpl; auto;[].\n            destruct bs; allsimpl; auto;[].\n            destruct b as [l t]; simpl.\n            destruct l; allsimpl; auto;[].\n            allrw @sub_filter_nil_r.\n            destruct t as [x|f|op bs1]; allsimpl; auto;[|].\n\n            { remember (sub_find sub x) as sf1; destruct sf1; allsimpl; auto;[].\n              destruct n0 as [|?|op bs1]; auto;[].\n              dopid op as [can|ncan|exc|abs] SSSCase; auto;[].\n              destruct can; simpl; auto.\n              boolvar; simpl; auto.\n              symmetry in Heqsf.\n              apply sub_find_some in Heqsf.\n              apply e in Heqsf; ginv. }\n\n            { dopid op as [can|ncan|exc|abs] SSSCase; allsimpl; tcsp;[].\n              destruct can; allsimpl; tcsp.\n              boolvar; auto.\n              symmetry in Heqsf.\n              apply sub_find_some in Heqsf.\n              apply e in Heqsf; ginv. }\n          }\n\n          destruct bs; simpl; auto;[].\n          destruct b as [l t]; simpl.\n          destruct l; simpl; auto;[].\n          allrw @sub_filter_nil_r.\n          destruct t as [v|g|op bs']; simpl; auto;[].\n\n          remember (sub_find sub v) as sf; destruct sf; allsimpl; auto;[].\n          destruct n as [|?|op bs1]; allsimpl; auto;[].\n          dopid op as [can|ncan|exc|abs] SSSCase; auto;[].\n          destruct can; simpl; auto.\n          boolvar; simpl; auto.\n          symmetry in Heqsf.\n          apply sub_find_some in Heqsf.\n          apply e in Heqsf; ginv.\n        }\nQed.\n\nLemma get_utokens_step_seq_subst_aux_trivial1 {o} :\n  forall (t : @NTerm o) v,\n    get_utokens_step_seq (subst_aux t v mk_axiom) = get_utokens_step_seq t.\nProof.\n  introv.\n  unfold subst_aux.\n  apply get_utokens_step_seq_lsubst_aux_trivial1; simpl.\n  introv i; allsimpl; repndors; ginv; tcsp.\nQed.\n\nLemma eapply_wf_def_sterm {o} :\n  forall (f : @ntseq o), eapply_wf_def (sterm f).\nProof.\n  introv.\n  unfold eapply_wf_def; simpl; left; eexists; eauto.\nQed.\nHint Resolve eapply_wf_def_sterm : slow.\n\n\n(* end hide *)\n\n\nTheorem compute_step_alpha {p} :\n  forall lib t1 t2 t1',\n    nt_wf t1\n    -> alpha_eq t1 t2\n    -> compute_step lib t1 = csuccess t1'\n    -> { t2' : @NTerm p\n        & compute_step lib t2 = csuccess t2'\n        # alpha_eq t1' t2'}.\nProof.\n  nterm_ind1s t1 as [v1|f1 ind1|o1 lbt1 IHind] Case; introv wf Hal Hcomp;\n  duplicate Hal as backup;\n  [ subst;\n    invertsn Hal;\n    invertsn Hcomp\n  |\n  | ].\n\n  { csunf Hcomp; allsimpl; ginv.\n    inversion Hal as [|? ? imp|]; subst; clear Hal.\n    csunf; simpl.\n    eexists; dands; eauto. }\n\n  - Case \"oterm\".\n    dopid o1 as [c1 | nc1 | exc1 | abs1] SCase.\n\n    + SCase \"Can\".\n      inverts Hcomp; auto; exists t2; split; auto;[]; inverts Hal; refl.\n\n    + SCase \"NCan\".  (* destruct lbt and the bts inside enough\n    times so that the structure re4quired\n     for computation rules is visible. need to split\n      on whether the opid of arg1(prin_arg) is canonical *)\n\n      dlist lbt1 SSCase as [| arg1];\n        [ dopid_noncan nc1 SSSCase;\n          inverts Hcomp\n        |\n        ]; [].\n      (*takes care of nilcase as no ncop takes 0 bterms*)\n\n      * SSCase \"conscase\".\n        destruct arg1 as [arg1vs arg1nt];\n          dlist arg1vs SSSCase as [|arg1v1].\n\n        { SSSCase \"nilcase\".\n          destruct arg1nt as [v|f|arg1o arg1bts].\n\n          { csunf Hcomp; allsimpl; ginv. }\n\n          { csunf Hcomp; allsimpl.\n            dopid_noncan nc1 SSSSCase; allsimpl; ginv.\n\n            - SSSSCase \"NApply\".\n              apply compute_step_seq_apply_success in Hcomp; exrepnd; subst; fold_terms; GC.\n              apply alpha_eq_mk_apply in Hal; exrepnd; subst.\n              apply alpha_eq_sterm in Hal2; exrepnd; subst.\n              csunf; simpl; eexists; dands; eauto.\n              apply implies_alpha_eq_mk_eapply; auto.\n\n            - SSSSCase \"NEApply\".\n              apply compute_step_eapply_success in Hcomp; exrepnd; subst; fold_terms; GC.\n              repndors; exrepnd; subst; allsimpl; fold_terms.\n\n              + apply compute_step_eapply2_success in Hcomp1; exrepnd; subst; fold_terms.\n                apply alpha_eq_mk_eapply in Hal; exrepnd; subst.\n                apply alpha_eq_sterm in Hal2; exrepnd; subst.\n                repndors; exrepnd; subst; ginv.\n                apply alpha_eq_mk_nat in Hal1; subst.\n                csunf; simpl; dcwf h; allsimpl; boolvar; try omega.\n                allrw Znat.Nat2Z.id.\n                eexists; dands; eauto.\n\n              + apply alpha_eq_oterm_implies_combine in Hal; exrepnd; subst.\n                allsimpl.\n                destruct bs'; allsimpl; cpx.\n                destruct bs'; allsimpl; cpx.\n                pose proof (Hal0 (nobnd (sterm f)) b) as h; autodimp h hyp.\n                pose proof (Hal0 (nobnd arg2) b0) as q; autodimp q hyp.\n                allapply @alpha_eq_bterm_nobnd; exrepnd; subst.\n                apply alpha_eq_sterm in h0; exrepnd; subst.\n                apply isexc_implies2 in Hcomp0; exrepnd; subst.\n                apply alpha_eq_oterm_implies_combine in q0; exrepnd; subst.\n                csunf; simpl; dcwf h; allsimpl.\n                eexists; dands; eauto.\n                apply alpha_eq_oterm_combine; dands; auto.\n\n              + pose proof (IHind arg2 arg2 []) as h; clear IHind.\n                repeat (autodimp h hyp); eauto 3 with slow.\n\n                apply alpha_eq_oterm_implies_combine in Hal; exrepnd; subst; allsimpl.\n                destruct bs'; allsimpl; cpx.\n                destruct bs'; allsimpl; cpx.\n                pose proof (Hal0 (nobnd (sterm f)) b) as z; autodimp z hyp.\n                pose proof (Hal0 (nobnd arg2) b0) as q; autodimp q hyp.\n                allapply @alpha_eq_bterm_nobnd; exrepnd; subst.\n                apply alpha_eq_sterm in z0; exrepnd; subst.\n\n                allrw @nt_wf_eapply_iff; exrepnd; allunfold @nobnd; ginv; fold_terms.\n                allsimpl; cpx.\n\n                pose proof (h u x) as ih; clear h.\n                repeat (autodimp ih hyp); exrepnd.\n                applydup @alphaeq_preserves_isnoncan_like in q0; auto.\n                rw @compute_step_eapply_iscan_isnoncan_like; simpl; eauto 3 with slow.\n                rw ih1.\n                eexists; dands; eauto.\n                apply alpha_eq_oterm_combine; simpl; dands; auto.\n                introv i; repndors; subst; ginv; auto.\n                apply alphaeqbt_nilv2; auto.\n\n            - SSSSCase \"NFix\".\n              apply compute_step_fix_success in Hcomp; repnd; subst; fold_terms; GC.\n              apply alpha_eq_mk_fix in Hal; exrepnd; subst.\n              apply alpha_eq_sterm in Hal0; exrepnd; subst.\n              csunf; simpl; eexists; dands; eauto.\n              apply implies_alpha_eq_mk_apply; auto.\n              apply implies_alpha_eq_mk_fix; auto.\n\n            - SSSSCase \"NCbv\".\n              apply compute_step_cbv_success in Hcomp; exrepnd; subst; GC; fold_terms.\n              apply alpha_eq_mk_cbv in Hal; exrepnd; subst.\n              apply alpha_eq_sterm in Hal2; exrepnd; subst.\n              csunf; simpl; eexists; dands; eauto.\n              unfold apply_bterm; simpl; allrw @fold_subst.\n\n              eapply lsubst_alpha_congr4; eauto.\n              constructor; auto.\n              apply alphaeq_eq.\n              constructor; auto.\n\n            - SSSSCase \"NTryCatch\".\n              apply compute_step_try_success in Hcomp; exrepnd; subst; fold_terms; GC.\n              apply alpha_eq_mk_ntry in Hal; exrepnd; subst.\n              apply alpha_eq_sterm in Hal3; exrepnd; subst.\n              csunf; simpl; eexists; dands; eauto.\n              apply implies_alpha_eq_mk_atom_eq; auto.\n\n            - SSSSCase \"NCanTest\".\n              apply compute_step_seq_can_test_success in Hcomp; exrepnd; subst; allsimpl; fold_terms; GC.\n              apply alpha_eq_mk_cantest in Hal; exrepnd; subst.\n              apply alpha_eq_sterm in Hal2; exrepnd; subst.\n              csunf; simpl.\n              eexists; dands; eauto.\n          }\n\n          inverts Hal as Hlen Hal. simpl in Hal. lapply (Hal 0); [introv H1al| omega].\n          destruct lbt2 as [| bt2 lbt2]; [inverts Hlen|]; [].\n          unfold selectbt in H1al. simpl in H1al. apply alphaeqbt_nilv in H1al. exrepnd.\n          simpl in H1al1. symmetry in H1al1.\n          destruct H1al1.\n          duplicate H1al0 as Halarg1.\n          invertsna Halarg1 H1alarg. rename lbt3 into t2arg1bts.\n          dopid arg1o as [arg1c | arg1nc | arg1exc | arg1abs] SSSSCase.\n\n          { SSSSCase \"Can\". GC.\n            dopid_noncan nc1 SSSSSCase.\n\n            (* arg1 (principle in all cases) is canonical. *)\n            - SSSSSCase \"NApply\".\n\n              allsimpl; cpx.\n              apply @apply_compute_step_prinargcan in Hcomp.\n              repndors; exrepnd; subst; allsimpl; cpx; allsimpl.\n\n              + (* some work required to get lbt2 to be of the right shape*)\n                allunfold @selectbt. repeat(alphahypsd).\n                csunf; simpl. eexists; split; eauto.\n                GC. clear backup H1al0 IHind. unfold subst.\n                apply al_bterm in H1alarg00bt0;sp.\n                eapply lsubst_alpha_congr4; simpl; eauto.\n                constructor; auto; apply alphaeq_eq; auto.\n\n              + allunfold @selectbt.\n                repeat alphahypsd.\n                csunf; simpl.\n                eexists; dands; eauto.\n                repeat prove_alpha_eq4.\n\n            - SSSSSCase \"NEApply\".\n\n              allsimpl; cpx; GC.\n              csunf Hcomp; allsimpl.\n              apply compute_step_eapply_success in Hcomp; exrepnd; subst; fold_terms; GC.\n              allsimpl.\n              destruct lbt2; allsimpl; cpx;[].\n              repndors; exrepnd; subst; allsimpl; fold_terms.\n\n              + apply compute_step_eapply2_success in Hcomp1; exrepnd; subst; allsimpl; cpx.\n                repndors; exrepnd; subst; allsimpl; ginv;\n                [|allunfold @mk_nseq; ginv; allsimpl; cpx; GC; fold_terms;\n                  pose proof (Hal 1) as q; autodimp q hyp;\n                  unfold selectbt in q; allsimpl;\n                  allapply @alpha_eq_bterm_nobnd; exrepnd; subst;\n                  allapply @alpha_eq_mk_nat; subst;\n                  csunf; allsimpl; dcwf h; allsimpl; boolvar; try omega;\n                  allrw Znat.Nat2Z.id;\n                  eexists; dands; eauto].\n\n                allunfold @mk_lam; ginv; allsimpl; cpx; fold_terms.\n                pose proof (H1alarg0 0) as aeq; autodimp aeq hyp.\n                unfold selectbt in aeq; allsimpl.\n\n                destruct x as [l t].\n                applydup @alphaeqbt1v2 in aeq; exrepnd; subst; fold_terms.\n\n                allrw disjoint_singleton_l.\n                pose proof (Hal 1) as q; autodimp q hyp.\n                unfold selectbt in q; allsimpl.\n                allapply @alpha_eq_bterm_nobnd; exrepnd; subst.\n                applydup @alphaeq_preserves_iscan in q0; auto.\n                rw @compute_step_eapply_lam_iscan; auto.\n                eexists; dands; eauto.\n                unfold apply_bterm; simpl; allrw @fold_subst.\n                eapply lsubst_alpha_congr4; simpl; eauto.\n                constructor; auto; apply alphaeq_eq; auto.\n\n              + pose proof (Hal 1) as q; autodimp q hyp; try omega.\n                unfold selectbt in q; allsimpl.\n                allapply @alpha_eq_bterm_nobnd; exrepnd; subst.\n                applydup @alphaeq_preserves_isexc in q0; auto.\n                applydup @alpha_eq_ot_numvars in H1al0; auto.\n                rw @compute_step_eapply_iscan_isexc; eauto 3 with slow.\n\n              + pose proof (Hal 1) as q; autodimp q hyp; try omega.\n                unfold selectbt in q; allsimpl.\n                allapply @alpha_eq_bterm_nobnd; exrepnd; subst.\n                applydup @alphaeq_preserves_isnoncan_like in q0; auto.\n                applydup @alpha_eq_ot_numvars in H1al0; auto.\n                rw @compute_step_eapply_iscan_isnoncan_like; eauto 3 with slow.\n\n                allrw @nt_wf_eapply_iff; exrepnd; allunfold @nobnd; ginv; fold_terms.\n                allsimpl; cpx.\n\n                pose proof (IHind b b []) as h;\n                  repeat (autodimp h hyp); clear IHind; eauto 3 with slow.\n                pose proof (h u x) as ih; clear h; repeat (autodimp ih hyp); exrepnd.\n                rw ih1.\n                eexists; dands; eauto.\n                apply alpha_eq_oterm_combine; simpl; dands; auto.\n                introv i; repndors; subst; ginv; auto; try (apply alphaeqbt_nilv2; auto); tcsp.\n\n                (*\n            - SSSSSCase \"NApseq\".\n\n              clear IHind.\n              allsimpl; cpx.\n              csunf Hcomp; allsimpl.\n              apply compute_step_apseq_success in Hcomp; exrepnd; subst; allsimpl; cpx.\n              allunfold @selectbt; allsimpl; fold_terms.\n              csunf; simpl; boolvar; try omega.\n              rw @Znat.Nat2Z.id.\n              eexists; dands; eauto.*)\n\n            - SSSSSCase \"NFix\".\n\n              csunf Hcomp; csunf; allsimpl.\n              invertsn Hcomp. simpl. allunfold @compute_step_fix.\n              destruct lbt1; inverts Hcomp. allsimpl. destruct lbt2; inverts Hlen.\n              eexists; split; eauto. simpl. unfold mk_apply, nobnd.\n              prove_alpha_eq3.\n\n            - SSSSSCase \"NSpread\".\n\n              csunf Hcomp; csunf; allsimpl.\n              try(\n                  ( (destruct arg1c;inverts Hcomp as Hcomp;[])\n                      ||\n                      (destruct arg1c;inverts Hcomp as Hcomp;[|]));\n                  destruct arg1bts as [|arg1b1t ?]; invertsn Hcomp;\n                  try(destructbtdeep arg1b1t Hcomp);\n                  try(destruct arg1bts as [|arg1b2t ?]; invertsn Hcomp);\n                  try(destructbtdeep arg1b2t Hcomp);\n                  try(destruct arg1bts; invertsn Hcomp);\n                  destruct lbt1 as [| arg2]; invertsn Hcomp;\n                  try(destructbtdeep arg2 Hcomp);\n                  try(destruct lbt1 as [| arg3]; invertsn Hcomp);\n                  try(destructbtdeep arg3 Hcomp);\n                  try(destruct lbt1 as [| arg4]; invertsn Hcomp)).\n              simphyps. repeat(alphahypsd). clear backup.\n              simpl. eexists; split; eauto. GC.\n              clear IHind H1al0 .\n              apply al_bterm in Hal1bt0 ;sp;[].\n              apply apply_bterm_alpha_congr;sp.\n              split;[sp|simpl];[].\n              introv Hlt. repeat (destruct n; try(omega));sp.\n\n            - SSSSSCase \"NDsup\".\n\n              csunf Hcomp; csunf; allsimpl.\n              try(\n                  ( (destruct arg1c;inverts Hcomp as Hcomp;[])\n                      ||\n                      (destruct arg1c;inverts Hcomp as Hcomp;[|]));\n                  destruct arg1bts as [|arg1b1t ?]; invertsn Hcomp;\n                  try(destructbtdeep arg1b1t Hcomp);\n                  try(destruct arg1bts as [|arg1b2t ?]; invertsn Hcomp);\n                  try(destructbtdeep arg1b2t Hcomp);\n                  try(destruct arg1bts; invertsn Hcomp);\n                  destruct lbt1 as [| arg2]; invertsn Hcomp;\n                  try(destructbtdeep arg2 Hcomp);\n                  try(destruct lbt1 as [| arg3]; invertsn Hcomp);\n                  try(destructbtdeep arg3 Hcomp);\n                  try(destruct lbt1 as [| arg4]; invertsn Hcomp)).\n              simphyps. repeat(alphahypsd). clear backup.\n              simpl. eexists; split; eauto. GC.\n              clear IHind H1al0 .\n              apply al_bterm in Hal1bt0 ;sp;[].\n              apply apply_bterm_alpha_congr;sp.\n              split;[sp|simpl];[].\n              introv Hlt. repeat (destruct n; try(omega));sp.\n\n            - SSSSSCase \"NDecide\".\n\n              csunf Hcomp; csunf; allsimpl.\n              apply compute_step_decide_success in Hcomp; exrepnd; subst; allsimpl; cpx.\n              allsimpl; cpx; allsimpl.\n              repeat(alphahypsd); GC; clear backup IHind H1al0.\n              apply al_bterm in Hal1bt0; auto.\n              apply al_bterm in Hal2bt0; auto.\n              repndors; repnd; subst; allsimpl; eexists; dands; eauto.\n\n              + apply (apply_bterm_alpha_congr _ _ [d] [nt2]) in Hal1bt0; allsimpl; tcsp.\n                split;[sp|simpl];[].\n                introv Hlt.\n                repeat (destruct n; try(omega));sp.\n\n              + apply (apply_bterm_alpha_congr _ _ [d] [nt2]) in Hal2bt0; allsimpl; tcsp.\n                split;[sp|simpl];[].\n                introv Hlt.\n                repeat (destruct n; try(omega));sp.\n\n            - SSSSSCase \"NCbv\".\n\n              csunf Hcomp; csunf; allsimpl.\n              destruct lbt1 as [| arg2]; invertsn Hcomp;\n              try(destructbtdeep arg2 Hcomp);\n              try(destruct lbt1 as [| arg3]; invertsn Hcomp);\n              try(destructbtdeep arg3 Hcomp);\n              try(destruct lbt1 as [| arg4]; invertsn Hcomp).\n              allsimpl. repeat(alphahypsd).\n              allsimpl. eexists; split; eauto.\n              clear IHind backup.\n              apply al_bterm in Hal1bt0;sp.\n              apply apply_bterm_alpha_congr;sp.\n              split;[sp|simpl];[].\n              introv Hlt. repeat (destruct n; try(omega));sp.\n\n            - SSSSSCase \"NSleep\".\n\n              csunf Hcomp; csunf; allsimpl.\n              allsimpl.\n              apply compute_step_sleep_success in Hcomp; exrepnd; subst; allsimpl; cpx.\n              destruct lbt2; allsimpl; cpx; GC.\n              exists (@mk_axiom p); dands; auto.\n\n            - SSSSSCase \"NTUni\".\n\n              csunf Hcomp; csunf; allsimpl.\n              allsimpl.\n              apply compute_step_tuni_success in Hcomp; exrepnd; subst; allsimpl; cpx.\n              destruct lbt2; allsimpl; cpx; GC.\n              exists (@mk_uni p n); dands; auto.\n              unfold compute_step_tuni; simpl.\n              destruct (Z_le_gt_dec 0 (Z.of_nat n)); sp; try omega.\n              rw Znat.Nat2Z.id; sp.\n\n            - SSSSSCase \"NMinus\".\n\n              csunf Hcomp; csunf; allsimpl.\n              allsimpl.\n              apply compute_step_minus_success in Hcomp; exrepnd; subst; allsimpl; cpx.\n              destruct lbt2; allsimpl; cpx; GC.\n              exists (@mk_integer p (- z)); dands; auto.\n\n            - SSSSSCase \"NFresh\".\n              csunf Hcomp; csunf; allsimpl.\n              allsimpl; cpx; ginv.\n\n            - SSSSSCase \"NTryCatch\".\n\n              csunf Hcomp; csunf; allsimpl.\n              apply compute_step_try_success in Hcomp; exrepnd; subst.\n              allsimpl; repeat cpx.\n              generalize (Hal 1); intro k1; autodimp k1 hyp.\n              unfold selectbt in k1; simpl in k1.\n              generalize (Hal 2); intro k2; autodimp k2 hyp.\n              unfold selectbt in k2; simpl in k2.\n              apply alphaeqbt_nilv in k1; exrepnd; subst.\n              dup k2 as aeqbt.\n              apply alphaeqbt_1v in k2; exrepnd; subst.\n              exists (mk_atom_eq nt2 nt2 (oterm (Can arg1c) t2arg1bts) mk_bot); dands; auto.\n              apply implies_alpha_eq_mk_atom_eq; eauto 2 with slow.\n\n            - SSSSSCase \"NParallel\".\n\n              csunf Hcomp; allsimpl.\n              apply compute_step_parallel_success in Hcomp; subst; allsimpl.\n              exists (@mk_axiom p); dands; auto.\n\n            - SSSSSCase \"NCompOp\".\n\n              (* the next 2 cases are different because they have 2 prinargs\n      i.e. they make recursive calls if the second arg is non-can *)\n              destruct lbt1 as [| arg2]; try (complete (csunf Hcomp; allsimpl; dcwf h));[].\n              destruct arg2 as [lv2 nt2].\n              destruct lv2; try (complete (csunf Hcomp; allsimpl; boolvar; dcwf h));[].\n              destruct nt2 as [?|?| arg2o arg2bts]; try (complete (csunf Hcomp; allsimpl; dcwf h));[].\n\n              allsimpl;[].\n              destruct lbt2 as [| t2arg2]; invertsn Hlen;[].\n              csunf Hcomp.\n              simphyps. alphahypdfv Hal. repeat( alphahypsd).\n              simphyps. subst. GC.\n\n              duplicate Hal1bt0 as XXXX.\n              invertsna Hal1bt0 Halarg2. rename lbt3 into t2arg2bts.\n              boolvar; ginv.\n\n              dopid arg2o as [arg2c| arg2nc | arg2exc | arg2abs] SSSSSSCase.\n\n              + SSSSSSCase \"Can\".\n                dcwf h.\n                apply compute_step_compop_success_can_can in Hcomp; exrepnd; subst.\n                csunf; allsimpl; tcsp.\n                destruct lbt2; allsimpl; repeat cpx.\n                boolvar; tcsp.\n\n                repeat(alphahypsd).\n                allapply @alpha_eq_bterm_nobnd; exrepnd; subst.\n                dcwf h; try (complete (apply co_wf_false_implies_not in Heqh0; tcsp)).\n\n                repndors; exrepnd; subst;\n                allrw @get_param_from_cop_some; subst; allsimpl;\n                unfold compute_step_comp; simpl;\n                allrw @get_param_from_cop_pk2can;\n                boolvar; subst; eexists; eauto.\n\n              + SSSSSSCase \"NCan\".\n                dcwf h; allsimpl.\n                remember (compute_step lib ((oterm (NCan arg2nc) arg2bts))) as rec.\n                destruct rec as [csuccrec | cfail]; inverts Hcomp as Hcomp.\n                symmetry in Heqrec.\n\n                allrw @nt_wf_NCompOp; exrepnd; allunfold @nobnd; allsimpl; ginv.\n                allsimpl; cpx.\n\n                eapply IHind with (lv:=[]) in Heqrec; eauto 3 with slow; tcsp;[].\n                exrepnd. subst.\n                exists (oterm (NCan (NCompOp c))\n                              (bterm [] (oterm (Can arg1c) t2arg1bts) :: bterm [] t2' :: x :: y ::[])).\n                rw @compute_step_ncompop_ncan2.\n                dcwf h.\n                rewrite Heqrec1.\n                split; [refl|].\n                prove_alpha_eq2.\n\n              + SSSSSSCase \"Exc\".\n                dcwf h; ginv; subst; GC; allsimpl.\n                csunf; simpl.\n                dcwf h.\n                boolvar; tcsp.\n                exists (oterm Exc t2arg2bts); sp.\n\n              + SSSSSSCase \"Abs\".\n                csunf Hcomp; allsimpl.\n                dcwf h.\n                remember (compute_step_lib lib arg2abs arg2bts) as csl.\n                destruct csl; allsimpl; ginv; subst; GC.\n\n                pose proof (compute_step_lib_success lib arg2abs arg2bts n) as h.\n                autodimp h hyp; exrepnd; subst.\n                pose proof (eq_num_bvars_if_alpha arg2bts t2arg2bts) as e; repeat (autodimp e hyp).\n                pose proof (found_entry_change_bs\n                              arg2abs oa2 vars rhs\n                              lib\n                              arg2bts correct t2arg2bts h0 e) as fe.\n                pose proof (compute_step_lib_success_change_bs\n                              lib arg2abs oa2 arg2bts t2arg2bts\n                              vars rhs correct e h0) as k.\n                rw @compute_step_ncompop_abs2; boolvar; tcsp.\n                dcwf h;[].\n                exists (oterm (NCan (NCompOp c))\n                              (bterm [] (oterm (Can arg1c) t2arg1bts)\n                                     :: bterm [] (mk_instance vars t2arg2bts rhs)\n                                     :: lbt2));\n                  dands; [complete (simpl; boolvar; tcsp; unfold on_success; rw k; auto)|].\n                apply al_oterm; simpl; auto.\n                introv h.\n                destruct n; unfold selectbt; simpl; cpx;[|destruct n].\n                * apply alpha_eq_bterm_congr; auto.\n                * apply alpha_eq_bterm_congr.\n                  eapply alpha_eq_lsubst_mk_abs_subst; eauto.\n                * pose proof (Hal (S (S n))) as x.\n                  autodimp x hyp; omega.\n\n\n            - SSSSSCase \"NArithOp\".\n\n              destruct lbt1 as [| arg2]; try (complete (csunf Hcomp; allsimpl; dcwf h));[].\n              destruct arg2 as [lv2 nt2].\n              destruct lv2; destruct nt2 as [?|?|arg2o arg2bts];\n              try (complete (csunf Hcomp; allsimpl; dcwf h));[].\n\n              destruct lbt2 as [| t2arg2]; invertsn Hlen.\n              csunf Hcomp.\n              simphyps. alphahypdfv Hal. repeat( alphahypsd).\n              dcwf h;[].\n              simphyps. subst.  GC.\n\n              duplicate Hal1bt0 as XXXX.\n              invertsna Hal1bt0 Halarg2. rename lbt3 into t2arg2bts.\n              boolvar; ginv.\n\n              dopid arg2o as [arg2c | arg2nc | arg2exc | arg2abs] SSSSSSCase.\n\n              + SSSSSSCase \"Can\".\n                apply compute_step_arithop_success_can_can in Hcomp; exrepnd; subst.\n                csunf; allsimpl; tcsp; cpx.\n                dcwf h;[].\n                boolvar; tcsp.\n\n                repeat(alphahypsd).\n\n                repndors; exrepnd; subst;\n                allapply @get_param_from_cop_pki;\n                subst; ginv; GC;\n                unfold compute_step_arith; simpl; boolvar; eexists; eauto.\n\n              + SSSSSSCase \"NCan\".\n                remember (compute_step lib ((oterm (NCan arg2nc) arg2bts))) as rec.\n                destruct rec as [csuccrec | cfail]; allsimpl; ginv.\n                symmetry in Heqrec.\n\n                allrw @nt_wf_NArithOp; exrepnd; allunfold @nobnd; ginv; allsimpl; cpx.\n\n                eapply IHind with (lv:=[])  in Heqrec; eauto 3 with slow;[].\n                exrepnd. subst.\n                exists (oterm (NCan (NArithOp a))\n                              (bterm [] (oterm (Can arg1c) t2arg1bts) :: bterm [] t2' :: [])).\n                rw @compute_step_narithop_ncan2.\n                dcwf h;[].\n                rw Heqrec1; dands; auto.\n                prove_alpha_eq3.\n\n              + SSSSSSCase \"Exc\".\n                ginv.\n                csunf; simpl.\n                dcwf h;[].\n                boolvar; tcsp.\n                exists (oterm Exc t2arg2bts); sp.\n\n              + SSSSSSCase \"Abs\".\n                csunf Hcomp; allsimpl.\n                remember (compute_step_lib lib arg2abs arg2bts) as csl.\n                destruct csl; allsimpl; ginv; subst; GC.\n\n                pose proof (compute_step_lib_success lib arg2abs arg2bts n) as h.\n                autodimp h hyp; exrepnd; subst.\n                pose proof (eq_num_bvars_if_alpha arg2bts t2arg2bts) as e; repeat (autodimp e hyp).\n                pose proof (found_entry_change_bs\n                              arg2abs oa2 vars rhs lib\n                              arg2bts correct t2arg2bts h0 e) as fe.\n                pose proof (compute_step_lib_success_change_bs\n                              lib arg2abs oa2 arg2bts t2arg2bts\n                              vars rhs correct e h0) as k.\n                rw @compute_step_narithop_abs2.\n                dcwf h;[].\n                exists (oterm (NCan (NArithOp a))\n                              (bterm [] (oterm (Can arg1c) t2arg1bts)\n                                     :: bterm [] (mk_instance vars t2arg2bts rhs)\n                                     :: lbt2));\n                  dands; [complete (simpl; boolvar; tcsp; unfold on_success; rw k; auto)|].\n                apply al_oterm; simpl; auto.\n                introv h.\n                destruct n; unfold selectbt; simpl; cpx;[|destruct n].\n                * apply alpha_eq_bterm_congr; auto.\n                * apply alpha_eq_bterm_congr.\n                  eapply alpha_eq_lsubst_mk_abs_subst; eauto.\n                * pose proof (Hal (S (S n))) as x.\n                  autodimp x hyp; omega.\n\n            - SSSSSCase \"NCanTest\".\n\n              csunf Hcomp; csunf; allsimpl.\n              simpl in Hcomp. unfold compute_step_can_test in Hcomp.\n              destruct lbt1 as [| arg2]; invertsn Hcomp;\n              (destructbtdeep arg2 Hcomp);\n              (destruct lbt1 as [| arg3]; invertsn Hcomp);\n              (destructbtdeep arg3 Hcomp);\n              (destruct lbt1 as [| arg4]; invertsn Hcomp).\n              simphyps; repeat(alphahypsd).\n              simpl. eexists; split; eauto.\n              cases_if; auto.\n          }\n\n          { SSSSCase \"NCan\".\n\n            (* computation now occurs in one of the subterms\n (principle arg); hence use the induction hyp*)\n\n            rw @compute_step_ncan_ncan in Hcomp.\n            remember (compute_step lib (oterm (NCan arg1nc) arg1bts)) as crt2s.\n            symmetry in Heqcrt2s.\n            destruct crt2s as [csucct2s | cfail]; ginv.\n\n            rw @compute_step_ncan_ncan.\n            apply nt_wf_oterm_iff in wf; repnd; allsimpl.\n            pose proof (wf (bterm [] (oterm (NCan arg1nc) arg1bts))) as w1; autodimp w1 hyp.\n            allrw @bt_wf_iff.\n            eapply IHind with (lv:=[]) in Heqcrt2s; eauto 3 with slow; try(simpl; left; auto); exrepnd.\n            exists ((oterm (NCan nc1) (bterm [] t2' :: lbt2))). rename Heqcrt2s1 into Hcomp.\n            rename Heqcrt2s0 into H1alcarg.\n            rw Hcomp. split; [refl|].\n            constructor; auto.\n            simpl. introv Hlt.\n            apply_clear Hal in Hlt.\n            clear Hcomp.\n            allunfold @selectbt; allsimpl.\n            destruct n; auto;[].\n            apply alphaeqbt_nilv2; trivial.\n          }\n\n          { SSSSCase \"Exc\".\n\n            csunf Hcomp; csunf; allsimpl; cpx.\n            apply compute_step_catch_success in Hcomp;\n              repdors; exrepnd; subst; cpx; allsimpl; auto;\n              fold_terms; allrw @fold_exception; cpx.\n\n            + destruct x.\n              applydup @alpha_eq_ot_numvars in H1al0.\n              simpl in H1al1; cpx; allunfold @num_bvars; allsimpl.\n              fold_terms.\n              allrw @fold_exception.\n              applydup @alpha_eq_ot_numvars in backup.\n              simpl in backup0; cpx.\n              allunfold @num_bvars; allsimpl; cpx.\n              destruct l; allsimpl; cpx.\n              destruct x0; allsimpl; cpx.\n              destruct l; allsimpl; cpx.\n              destruct y; allsimpl; cpx.\n              repeat (destruct l; allsimpl; cpx).\n              destruct y0; allsimpl; cpx.\n              repeat (destruct l; allsimpl; cpx).\n              generalize (H1alarg0 0); intro k0; autodimp k0 hyp.\n              unfold selectbt in k0; simpl in k0.\n              generalize (H1alarg0 1); intro k1; autodimp k1 hyp.\n              unfold selectbt in k1; simpl in k1.\n              generalize (Hal 1); intro k2; autodimp k2 hyp.\n              unfold selectbt in k2; simpl in k2.\n              generalize (Hal 2); intro k3; autodimp k3 hyp.\n              unfold selectbt in k3; simpl in k3.\n              apply alphaeqbt_nilv2 in k0.\n              apply alphaeqbt_nilv2 in k1.\n              apply alphaeqbt_nilv2 in k2.\n              exists (mk_atom_eq n0 n (subst n2 n3 n1) (mk_exception n n1)); dands; auto.\n              apply implies_alpha_eq_mk_atom_eq; auto.\n              generalize (apply_bterm_alpha_congr\n                            (bterm [v] b) (bterm [n3] n2) [e] [n1]);\n                intro k; repeat (autodimp k hyp).\n              unfold bin_rel_nterm; apply binrel_list_cons; dands; auto.\n              apply binrel_list_nil.\n\n            + exists (oterm Exc t2arg1bts); dands; auto.\n              unfold compute_step_catch; destruct nc1; sp; boolvar; subst; tcsp.\n          }\n\n          { SSSSCase \"Abs\".\n\n            rw @compute_step_ncan_abs in Hcomp.\n            rw @compute_step_ncan_abs; allsimpl.\n            remember (compute_step_lib lib arg1abs arg1bts) as c; destruct c; allsimpl; ginv.\n\n            pose proof (compute_step_lib_success lib arg1abs arg1bts n) as h.\n            autodimp h hyp; exrepnd; subst.\n            pose proof (eq_num_bvars_if_alpha arg1bts t2arg1bts) as e; repeat (autodimp e hyp).\n            pose proof (found_entry_change_bs\n                          arg1abs oa2 vars rhs lib\n                          arg1bts correct t2arg1bts h0 e) as fe.\n            pose proof (compute_step_lib_success_change_bs\n                          lib arg1abs oa2 arg1bts t2arg1bts\n                          vars rhs correct e h0) as k.\n            rw k.\n            exists (oterm (NCan nc1)\n                          (bterm [] (mk_instance vars t2arg1bts rhs) :: lbt2));\n              dands; auto.\n            apply al_oterm; simpl; auto.\n            introv h.\n            destruct n; unfold selectbt; simpl; cpx.\n            + apply alpha_eq_bterm_congr.\n              eapply alpha_eq_lsubst_mk_abs_subst; eauto.\n            + pose proof (Hal (S n)) as x.\n              autodimp x hyp; omega.\n          }\n        }\n\n        { (* fresh case *)\n          csunf Hcomp; allsimpl.\n          apply @compute_step_fresh_success in Hcomp; repnd; subst.\n          repndors; exrepnd; subst; allsimpl;\n          clear backup; apply alpha_eq_mk_fresh in Hal; exrepnd; subst.\n\n          - exists (@mk_fresh p v' (mk_var v')).\n            apply alphaeqbt_1v in Hal1; exrepnd; ginv.\n            allrw disjoint_singleton_l; simphyps; allrw not_over_or; repnd.\n\n            allrw @lsubst_vterm; simphyps; boolvar; simphyps;\n            apply alpha_eq_mk_var in Hal0; symmetry in Hal0;\n            applydup @lsubst_is_vterm in Hal0; exrepnd; subst;\n            allrw @lsubst_vterm; simphyps; boolvar; simphyps; ginv; GC;\n            allrw not_over_or; repnd; tcsp; GC; ginv;\n            inversion Hal0; subst; tcsp.\n\n            dands; auto.\n            + csunf; simpl; boolvar; auto.\n            + apply (implies_alpha_eq_mk_fresh_sub vn); simpl; tcsp.\n              unfold lsubst; simpl; boolvar; auto.\n\n          - exists (pushdown_fresh v' a').\n            dands.\n            + unfold isvalue_like in Hcomp0; repndors.\n              * apply iscan_implies in Hcomp0; repndors; exrepnd; subst.\n                { applydup @alpha_eq_bterm_oterm in Hal1; exrepnd; subst.\n                  csunf; simpl; auto. }\n                { applydup @alpha_eq_bterm_sterm in Hal1; exrepnd; subst; simpl.\n                  csunf; simpl; auto. }\n              * apply isexc_implies2 in Hcomp0; exrepnd; subst.\n                applydup @alpha_eq_bterm_oterm in Hal1; exrepnd; subst.\n                csunf; simpl; auto.\n            + apply implies_alpha_eq_pushdown_fresh; auto.\n\n          - remember (get_fresh_atom arg1nt) as a.\n            pose proof (IHind arg1nt (subst arg1nt arg1v1 (mk_utoken a)) [arg1v1]) as h.\n            repeat (autodimp h hyp).\n            { rw @simple_osize_subst; eauto 3 with slow. }\n\n            pose proof (lsubst_alpha_congr4 [arg1v1] [v'] arg1nt a' [(arg1v1,mk_utoken a)] [(v',mk_utoken a)]) as aeq.\n            repeat (autodimp aeq hyp); eauto with slow.\n            pose proof (lsubst_alpha_congr4 [arg1v1] [v'] arg1nt a' [(arg1v1,mk_axiom)] [(v',mk_axiom)]) as aeq'.\n            repeat (autodimp aeq' hyp); eauto with slow.\n\n            apply nt_wf_oterm_iff in wf; repnd; allsimpl.\n            pose proof (wf (bterm [arg1v1] arg1nt)) as w1; autodimp w1 hyp.\n            allrw @bt_wf_iff.\n\n            pose proof (h (subst a' v' (mk_utoken a)) x) as k; clear h.\n            repeat (autodimp k hyp).\n            { apply nt_wf_subst; eauto 3 with slow. }\n            exrepnd.\n\n            repeat (rw @cl_lsubst_lsubst_aux in aeq; eauto with slow).\n            repeat (rw @cl_lsubst_lsubst_aux in aeq'; eauto with slow).\n            simpl in aeq; allrw @fold_subst_aux.\n            simpl in aeq'; allrw @fold_subst_aux.\n            pose proof (implies_isnoncan_like_subst_aux arg1nt arg1v1 (mk_utoken a) Hcomp1) as k.\n            pose proof (alphaeq_preserves_isnoncan_like (subst_aux arg1nt arg1v1 (mk_utoken a)) (subst_aux a' v' (mk_utoken a)) aeq k) as q.\n            apply isnoncan_like_subst_aux_utoken_implies in q.\n            rw @compute_step_fresh_if_isnoncan_like; auto.\n            simpl; unfold on_success.\n\n            applydup @alphaeq_preserves_utokens in aeq'.\n            repeat (rw @get_utokens_subst_aux_trivial1 in aeq'0; simpl; auto).\n            pose proof (eq_fresh_atom arg1nt a' aeq'0) as e; rw <- e; rw <- Heqa.\n\n            rw k1; eexists; dands; eauto.\n            unfold mk_fresh.\n            prove_alpha_eq4; introv z; destruct n; tcsp.\n            pose proof (ex_fresh_var (arg1v1\n                                        :: v'\n                                        :: allvars (subst_utokens x [(a, vterm arg1v1)])\n                                        ++ allvars (subst_utokens t2' [(a, vterm v')])\n                                        ++ allvars x\n                                        ++ allvars t2'\n                       ))\n              as fv; exrepnd; allsimpl.\n            allrw in_app_iff; allrw not_over_or; repnd.\n            apply alphaeqbt_eq.\n            apply (aeqbt _ [v]); allsimpl; auto.\n            { rw disjoint_singleton_l; simpl; allrw in_app_iff; sp. }\n\n            pose proof (subst_utokens_swap_swap x [arg1v1] [v] [(a,vterm arg1v1)]) as hh; allsimpl.\n            repeat (autodimp hh hyp).\n            { apply disjoint_singleton_l; simpl; sp. }\n            pose proof (subst_utokens_swap_swap t2' [v'] [v] [(a,vterm v')]) as kk; allsimpl.\n            repeat (autodimp kk hyp).\n            { apply disjoint_singleton_l; simpl; sp. }\n\n            apply alphaeq_eq.\n            unfold oneswapvar in hh; unfold oneswapvar in kk.\n            boolvar.\n            eapply alpha_eq_trans;[exact hh|].\n            eapply alpha_eq_trans ;[|apply alpha_eq_sym; apply kk].\n            apply alpha_eq_subst_utokens; eauto with slow.\n\n            assert (!LIn arg1v1 (free_vars x)) as ni1.\n            { introv i.\n              pose proof (compute_step_preserves\n                            lib (subst arg1nt arg1v1 (mk_utoken a))\n                            x) as hhh; repnd.\n              repeat (autodimp hhh hyp); repnd.\n              { apply nt_wf_subst; eauto 3 with slow. }\n              rw subvars_prop in hhh0.\n              apply hhh0 in i.\n              rw @cl_subst_subst_aux in i; eauto with slow; unfold subst_aux in i.\n              rw @free_vars_lsubst_aux_cl in i; eauto with slow.\n              rw in_remove_nvars in i; simpl in i; sp. }\n\n            applydup @alphaeqbt_preserves_wf in Hal1 as wa'.\n            allrw @bt_wf_iff.\n            applydup wa' in w1.\n\n            assert (!LIn v' (free_vars t2')) as ni2.\n            { introv i.\n              pose proof (compute_step_preserves\n                            lib (subst a' v' (mk_utoken a))\n                            t2') as hhh; repnd.\n              repeat (autodimp hhh hyp); repnd.\n              { apply nt_wf_subst; eauto 3 with slow. }\n              rw subvars_prop in hhh0.\n              apply hhh0 in i.\n              rw @cl_subst_subst_aux in i; eauto with slow; unfold subst_aux in i.\n              rw @free_vars_lsubst_aux_cl in i; eauto with slow.\n              rw in_remove_nvars in i; simpl in i; sp. }\n\n            pose proof (alphaeq_cswap_disj_free_vars x [arg1v1] [v]) as hhh;\n              allsimpl; repeat (autodimp hhh hyp);\n              try (apply disjoint_singleton_r; simpl; tcsp).\n\n            pose proof (alphaeq_cswap_disj_free_vars t2' [v'] [v]) as kkk;\n              allsimpl; repeat (autodimp kkk hyp);\n              try (apply disjoint_singleton_r; simpl; tcsp).\n\n            allrw @alphaeq_eq.\n            eapply alpha_eq_trans;[exact hhh|].\n            eapply alpha_eq_trans;[exact k0|]; eauto with slow.\n        }\n\n    + SCase \"Exc\".\n      csunf Hcomp; allsimpl; ginv.\n      apply alpha_eq_oterm_implies_combine in Hal; exrepnd; subst.\n      csunf; simpl.\n      eexists; dands; eauto.\n\n    + SCase \"Abs\".\n      csunf Hcomp; allsimpl.\n      pose proof (compute_step_lib_success lib abs1 lbt1 t1' Hcomp) as h; exrepnd; subst.\n      clear IHind backup Hcomp.\n\n      inversion Hal as [|?|? ? ? len aeq]; subst.\n\n      pose proof (eq_num_bvars_if_alpha lbt1 lbt2) as e; repeat (autodimp e hyp).\n      pose proof (found_entry_change_bs abs1 oa2 vars rhs lib lbt1 correct lbt2 h0 e) as fe.\n      pose proof (compute_step_lib_success_change_bs\n                    lib abs1 oa2 lbt1 lbt2 vars rhs correct e h0) as k.\n\n      exists (mk_instance vars lbt2 rhs); dands; auto.\n      eapply alpha_eq_lsubst_mk_abs_subst; eauto.\nQed.\n\n(*\nTheorem compute_step_alpha_exception :\n  forall t1 t2 t1' : NTerm,\n    alpha_eq t1 t2\n    -> compute_step t1 = cexception t1'\n   -> { t2':NTerm & compute_step t2 = cexception t2'\n        # alpha_eq t1' t2'}.\nProof.\n  introv aeq e.\n  apply compute_step_alpha_aux with (t1 := t1); auto.\nQed.\n*)\n\n(* begin hide *)\n\n\nLemma compute_at_most_steps_var {p} :\n  forall lib n v,\n    compute_at_most_k_steps lib (S n) (vterm v)\n    = cfailure compute_step_error_not_closed (@vterm p v) .\nProof.\n  induction n; allsimpl; cpx.\n  intro. rewrite IHn. refl.\nQed.\n\nLemma compute_in_k_steps_var {p} :\n  forall lib n v,\n    computes_k_steps lib (S n) (vterm v)\n    = cfailure compute_step_error_not_closed (@vterm p v) .\nProof.\n  introv.\n  rw @computes_k_steps_eq_f; simpl; sp.\nQed.\n\nLemma compute_1_step_success_implies_compute_step {p} :\n forall lib (t1 t2 : @NTerm p),\n  compute_1_step lib t1 = csuccess t2\n  -> compute_step lib t1 = csuccess t2.\nProof.\n  introv k.\n  unfold compute_1_step in k.\n  destruct t1; ginv.\n  destruct o; auto; inversion k.\nQed.\n\nLemma compute_step_ncan_implies_compute_1_step {p} :\n forall lib nc bts res,\n  compute_step lib (oterm (@NCan p nc) bts) = res\n  -> compute_1_step lib (oterm (NCan nc) bts) = res.\nProof. sp. Qed.\n\n(*\nLemma compute_step_exception_implies_compute_1_step :\n forall t e,\n  compute_step t = csuccess (mk_exception e)\n  -> compute_1_step t = csuccess (mk_exception e).\nProof.\n  introv c.\n  unfold compute_1_step.\n  destruct t; auto.\n  destruct o; auto.\n  unfold compute_step in c; inversion c.\nQed.\n*)\n\nLemma compute_step_exact_implies_atmost {p} :\n forall lib n (t1 t2 : @NTerm p),\n  computes_k_steps lib n t1 = csuccess t2\n  -> compute_at_most_k_steps lib n t1 = csuccess t2.\nProof.\n  induction n; introv c; allsimpl; auto.\n  remember (computes_k_steps lib n t1) as ck.\n  symmetry in Heqck; destruct ck; try (complete (inversion c)).\n\n  apply IHn in Heqck.\n  rw Heqck.\n  apply compute_1_step_success_implies_compute_step in c; auto.\nQed.\n\nLemma compute_step_atmost_exact {p} :\n forall lib n (t1 t2 : @NTerm p),\n  compute_at_most_k_steps lib n t1 = csuccess t2\n  -> { m : nat & m <=n # computes_k_steps lib m t1 = csuccess t2  }.\nProof.\n  induction n; introns Hc; sp;\n  allsimpl;[ exists 0; cpx|];[].\n  destructr (compute_at_most_k_steps lib n t1) as [ss|nn];\n    [| inverts Hc]; [].\n  symmetry in HeqHdeq. applydup IHn in HeqHdeq.\n  exrepnd.\n  destruct ss;[inverts Hc|idtac|];[|].\n  { csunf Hc; allsimpl; ginv.\n    exists m; allsimpl; split; tcsp. }\n  dopid o as [c|nc|exc|abs] Case.\n  - Case \"Can\".\n    csunf Hc; allsimpl; ginv.\n    exists m. allsimpl. split; spc.\n  - Case \"NCan\".\n    exists (S m).\n    split; spc; [omega|]. simpl.\n    rw HeqHdeq1.\n    apply compute_step_exact_implies_atmost in HeqHdeq1; auto.\n  - Case \"Exc\".\n    rw @compute_step_exception in Hc; sp; ginv.\n    exists m; sp.\n  - Case \"Abs\".\n    simpl in Hc.\n    exists (S m); dands; [omega|]; simpl.\n    rw HeqHdeq1; simpl; auto.\nQed.\n\n(*\nLemma compute_step_atmost_exception_exact :\n forall n t1 t2,\n  computes_to_exception_in_max_k_steps t1 t2 n\n  -> { m : nat & m <=n # computes_k_steps m t1 = cexception t2  }.\nProof.\n  induction n; introns Hc; sp;\n  allsimpl;[ exists 0; cpx|];[].\n  destructr (compute_at_most_k_steps n t1) as [ss|nn|ee];\n    [| inverts Hc | inverts Hc].\n\n  - symmetry in HeqHdeq.\n    apply compute_step_atmost_exact in HeqHdeq; exrepnd.\n    exists (S m); dands; try omega.\n    rw computes_k_steps_S.\n    rw HeqHdeq0; auto.\n    apply compute_step_exception_implies_compute_1_step in Hc; auto.\n\n  - symmetry in HeqHdeq.\n    apply IHn in HeqHdeq; exrepnd.\n    exists m; auto.\nQed.\n*)\n\nLemma compute_1_step_mk_try {p} :\n  forall lib a (t : @NTerm p) x b,\n    compute_1_step lib (mk_try t a x b)\n    = compute_step lib (mk_try t a x b).\nProof. sp. Qed.\n\nLemma implies_reduces_to_trycatch {p} :\n  forall lib a a' (t : @NTerm p) e x b,\n    computes_to_exception lib a t e\n    -> reduces_to lib (mk_try t a' x b) (mk_atom_eq a' a (subst b x e) (mk_exception a e)).\nProof.\n  unfold computes_to_exception, reduces_to.\n  introv comp; exrepnd.\n  revert dependent t; induction k; introv comp.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    exists 1.\n    rw @reduces_in_atmost_k_steps_S.\n    csunf; simpl; boolvar; tcsp; GC.\n    eexists; dands; eauto.\n    rw @reduces_in_atmost_k_steps_0; auto.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    apply IHk in comp0; exrepnd.\n\n    destruct t as [v|f|op bs].\n\n    { csunf comp1; allsimpl; ginv. }\n\n    { csunf comp1; allsimpl; ginv.\n      eexists; eauto. }\n\n    dopid op as [can|ncan|exc|abs] Case.\n\n    + Case \"Can\".\n      csunf comp1; allsimpl; ginv.\n      eexists; eauto.\n\n    + Case \"NCan\".\n      exists (S k0).\n      rw @reduces_in_atmost_k_steps_S.\n      unfold mk_try, nobnd.\n      rw @compute_step_ncan_ncan; rw comp1.\n      eexists; dands; eauto.\n\n    + Case \"Exc\".\n      csunf comp1; allsimpl; ginv.\n      eexists; eauto.\n\n    + Case \"Abs\".\n      exists (S k0).\n      rw @reduces_in_atmost_k_steps_S.\n      unfold mk_try, nobnd.\n      csunf comp1; allsimpl.\n      rw @compute_step_ncan_abs; rw comp1.\n      eexists; dands; eauto.\nQed.\n\nLemma compute_at_most_k_steps_preserves_wf {o} :\n  forall lib k (t1 t2 : @NTerm o),\n    compute_at_most_k_steps lib k t1 = csuccess t2\n    -> nt_wf t1\n    -> nt_wf t2.\nProof.\n  induction k; introv comp wf.\n  - allsimpl; ginv; auto.\n  - allsimpl.\n    remember (compute_at_most_k_steps lib k t1) as c;\n      destruct c; allsimpl; ginv; symmetry in Heqc.\n    apply IHk in Heqc; auto.\n    apply preserve_nt_wf_compute_step in comp; auto.\nQed.\n\nTheorem reduces_in_atmost_k_steps_alpha {p} :\n  forall lib (t1 t2 : NTerm),\n    nt_wf t1\n    -> alpha_eq t1 t2\n    -> forall k t1',\n        reduces_in_atmost_k_steps lib t1 t1' k\n        -> { t2':@NTerm p & reduces_in_atmost_k_steps lib t2 t2' k\n              # alpha_eq t1' t2'}.\nProof.\n  introv wf Hal.\n  induction k as [| k Hind]; introv Hc0;\n  allunfold @reduces_in_atmost_k_steps;\n  [allsimpl; invertsn Hc0; eexists; eauto; fail |].\n  allsimpl.\n  remember (compute_at_most_k_steps lib k t1) as ck.\n  destruct ck as [csk|?]; invertsn Hc0.\n  dimp (Hind csk);exrepnd; sp;[].\n  clear Hind.\n  rw hyp1.\n  eapply compute_step_alpha in Hc0; eauto.\n  eapply compute_at_most_k_steps_preserves_wf; eauto.\nQed.\n\nLemma alpha_eq_exception {p} :\n  forall a (e t : @NTerm p),\n    alpha_eq (mk_exception a e) t\n    -> {a' : NTerm\n        & {e' : NTerm\n        & t = mk_exception a' e'\n        # alpha_eq a a'\n        # alpha_eq e e'}}.\nProof.\n  introv Hal.\n  inversion Hal as [|?|? ? ? len bts]; subst; allsimpl; cpx.\n  generalize (bts 0); intro al1; autodimp al1 hyp.\n  generalize (bts 1); intro al2; autodimp al2 hyp.\n  clear bts.\n  allunfold @selectbt; allsimpl.\n  allapply @alphaeqbt_nilv; exrepnd; subst.\n  allrw @fold_exception.\n  exists nt0 nt2; sp.\nQed.\n\nLemma reduces_in_atmost_k_Steps_preserves_wf {o} :\n  forall lib k (t1 t2 : @NTerm o),\n    reduces_in_atmost_k_steps lib t1 t2 k\n    -> nt_wf t1\n    -> nt_wf t2.\nProof.\n  introv r w.\n  apply compute_at_most_k_steps_preserves_wf in r; auto.\nQed.\n\nTheorem exception_in_atmost_k_steps_alpha {p} :\n  forall lib a (t1 t2 : @NTerm p),\n    nt_wf t1\n    -> alpha_eq t1 t2\n    -> forall k t1',\n        computes_to_exception_in_max_k_steps lib a t1 t1' k\n        -> {a' : NTerm\n            & {t2' : NTerm\n            & computes_to_exception_in_max_k_steps lib a' t2 t2' k\n            # alpha_eq a a'\n            # alpha_eq t1' t2'}}.\nProof.\n  introv wf Hal.\n  induction k as [| k Hind]; introv Hc0;\n  allunfold @computes_to_exception_in_max_k_steps;\n  allunfold @reduces_in_atmost_k_steps; allsimpl.\n\n  - ginv.\n    apply alpha_eq_exception in Hal; exrepnd; subst.\n    exists a' e'; sp.\n\n  - remember (compute_at_most_k_steps lib k t1) as ck.\n    destruct ck; ginv.\n\n    clear Hind.\n    symmetry in Heqck.\n    applydup @reduces_in_atmost_k_Steps_preserves_wf in Heqck; auto.\n    apply @reduces_in_atmost_k_steps_alpha with (t2 := t2) in Heqck; auto.\n    exrepnd.\n    rw Heqck2.\n    eapply compute_step_alpha in Hc0; eauto; exrepnd.\n    apply alpha_eq_exception in Hc1; exrepnd; subst.\n    exists a' e'; sp.\nQed.\n\n\n(*\n(* every step is alpha equal*)\nTheorem reduces_in_k_steps_alpha :\n  forall (t1 t2 :NTerm),\n    alpha_eq t1 t2\n    -> forall k t1',\n        reduces_in_k_steps t1 t1' k\n        -> { t2':NTerm & reduces_in_k_steps t2 t2' k\n              # alpha_eq t1' t2'}.\ndestruct t1 as [v1 | o1 lbt1] ; invertsna Hc0 Hcc; sp.\n  - exists t1'. split; auto.\n  - remember (compute_at_most_k_steps k (oterm o1 lbt1)) as ck;\n      destruct ck  as [oc1 |?]; [| inverts Hc0];[].\n    symmetry in Heqck.\n    pose proof (Hind oc1 Heqck) as XXX.\n    exrepnd. rewrite XXX1.\n    eapply compute_step_alpha in Hc0; eauto.\nQed. *)\n\n\n\n\n\n\n\n\nLemma reduces_to_alpha {o} :\n  forall lib (t1 t2 t1' : @NTerm o),\n    nt_wf t1\n    -> alpha_eq t1 t2\n    -> reduces_to lib t1 t1'\n    -> {t2' : NTerm\n        & reduces_to lib t2 t2'\n        # alpha_eq t1' t2'}.\nProof.\n  introv wf aeq r.\n  allunfold @reduces_to; exrepnd.\n  eapply reduces_in_atmost_k_steps_alpha in r0; eauto; exrepnd.\n  exists t2'; dands; auto.\n  exists k; auto.\nQed.\n\nTheorem compute_to_value_alpha {p} :\n  forall lib (t1 t2 t1' : NTerm),\n    nt_wf t1\n    -> alpha_eq t1 t2\n    -> computes_to_value lib t1 t1'\n    -> {t2':@NTerm p\n        & computes_to_value lib t2 t2'\n        # alpha_eq t1' t2'}.\nProof.\n  introns Xc.\n  unfold computes_to_value in Xc1; repnd.\n  eapply reduces_to_alpha in Xc2; eauto.\n  exrepnd.\n  exists t2'; dands; auto.\n  unfold computes_to_value; dands; auto.\n  apply alpha_preserves_value in Xc3; auto.\nQed.\n\nTheorem compute_to_exception_alpha {p} :\n  forall lib a (t1 t2 t1' : @NTerm p),\n    nt_wf t1\n    -> alpha_eq t1 t2\n    -> computes_to_exception lib a t1 t1'\n    -> {a' : NTerm\n        & {t2': NTerm\n        & computes_to_exception lib a' t2 t2'\n        # alpha_eq a a'\n        # alpha_eq t1' t2'}}.\nProof.\n  introv wf; introns Xc.\n  unfold computes_to_exception in Xc0.\n  eapply reduces_to_alpha in Xc; eauto.\n  exrepnd.\n  apply alpha_eq_exception in Xc1; exrepnd; subst.\n  exists a' e'; dands; auto.\nQed.\n\nLemma compute_split {p} :\n  forall lib n m (t1 t2 t3 : @NTerm p),\n    compute_at_most_k_steps lib n t1 = csuccess t2\n    -> compute_at_most_k_steps lib m t1 = csuccess t3\n    -> n<=m\n    -> compute_at_most_k_steps lib (m-n) t2 = csuccess t3.\nProof.\n  induction n as [| n Hind]; introv H1c H2c Hlt.\n  - allsimpl. inverts H1c. assert (m-0=m) as Heq by omega. rw Heq;sp.\n  - simpl in H1c. remember (compute_at_most_k_steps lib n t1) as cn.\n    destruct cn; invertsn H1c. symmetry in Heqcn.\n    eapply Hind in H2c; eauto;sp;[| omega].\n    assert (S (m - S n) = (m-n)) as XX by omega.\n    rw <- XX in H2c. rw  @compute_at_most_k_steps_eq_f in H2c.\n    simpl in H2c. rw H1c in H2c. rw  <- @compute_at_most_k_steps_eq_f in H2c.\n    sp.\nQed.\n\n\nHint Resolve preserve_compute_step is_program_ot_subst1: slow.\n\n\n\nLemma computes_to_val_like_in_max_k_steps_can {p} :\n  forall lib c bterms a k,\n    @computes_to_val_like_in_max_k_steps p lib (oterm (Can c) bterms) a k\n    -> a = oterm (Can c) bterms.\nProof.\n  introv comp.\n  unfold computes_to_val_like_in_max_k_steps, reduces_in_atmost_k_steps in comp; repnd.\n  rw @compute_at_most_k_steps_can in comp0.\n  inversion comp0; subst; sp.\nQed.\n\nLemma computes_to_val_like_in_max_k_steps_exc {p} :\n  forall lib bterms (t : @NTerm p) k,\n    computes_to_val_like_in_max_k_steps lib (oterm Exc bterms) t k\n    -> t = oterm Exc bterms.\nProof.\n  introv comp.\n  unfold computes_to_val_like_in_max_k_steps, reduces_in_atmost_k_steps in comp; repnd.\n  rw @compute_at_most_k_steps_exception in comp0.\n  inversion comp0; subst; sp.\nQed.\n\n(*\nLemma compute_at_most_k_stepsf_primarg_marker {o} :\n  forall (lib : @library o) k nc mrk l bs,\n    compute_at_most_k_stepsf\n      lib\n      k\n      (oterm (NCan nc) (nobnd (oterm (Mrk mrk) l) :: bs))\n    = csuccess (oterm (NCan nc) (nobnd (oterm (Mrk mrk) l) :: bs)).\nProof.\n  induction k; introv; simpl; sp.\n  csunf; simpl.\n  apply IHk.\nQed.\n\nLemma compute_at_most_k_steps_primarg_marker {o} :\n  forall (lib : @library o) k nc mrk l bs,\n    compute_at_most_k_steps\n      lib\n      k\n      (oterm (NCan nc) (nobnd (oterm (Mrk mrk) l) :: bs))\n    = csuccess (oterm (NCan nc) (nobnd (oterm (Mrk mrk) l) :: bs)).\nProof.\n  induction k; introv; simpl; sp.\n  rw IHk.\n  csunf; simpl; auto.\nQed.\n\nLemma reduces_in_atmost_k_steps_primarg_marker {o} :\n  forall (lib : @library o) k nc mrk l bs a,\n    reduces_in_atmost_k_steps\n      lib\n      (oterm (NCan nc) (nobnd (oterm (Mrk mrk) l) :: bs))\n      a\n      k\n    -> a = oterm (NCan nc) (nobnd (oterm (Mrk mrk) l) :: bs).\nProof.\n  induction k; introv comp.\n  - allrw @reduces_in_atmost_k_steps_0; auto.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    csunf comp1; allsimpl; ginv; tcsp.\nQed.\n*)\n\nLemma compute_step_fresh_if_isvalue_like2 {o} :\n  forall lib v vs (t : @NTerm o) bs,\n    isvalue_like t\n    -> compute_step lib (oterm (NCan NFresh) (bterm (v :: vs) t :: bs))\n       = match vs, bs with\n           | [],[] => csuccess (pushdown_fresh v t)\n           | _,_ => cfailure \"check 1st arg\" (oterm (NCan NFresh) (bterm (v :: vs) t :: bs))\n         end.\nProof.\n  introv isv.\n  unfold isvalue_like in isv; repndors.\n  - apply iscan_implies in isv; repndors; exrepnd; subst;\n    csunf; simpl; auto.\n  - apply isexc_implies2 in isv; exrepnd; subst.\n    csunf; simpl; auto.\nQed.\n\nLemma isvalue_like_lsubst_aux {o} :\n  forall (t : @NTerm o) sub,\n    isvalue_like t\n    -> isvalue_like (lsubst_aux t sub).\nProof.\n  introv isv.\n  unfold isvalue_like in isv; repndors.\n  - apply iscan_implies in isv; repndors; exrepnd; subst;\n    simpl; eauto with slow.\n  - apply isexc_implies2 in isv; exrepnd; subst.\n    simpl; eauto with slow.\nQed.\nHint Resolve isvalue_like_lsubst_aux : slow.\n\nLemma isvalue_like_lsubst {o} :\n  forall (t : @NTerm o) sub,\n    isvalue_like t\n    -> isvalue_like (lsubst t sub).\nProof.\n  introv isv.\n  pose proof (unfold_lsubst sub t) as h; exrepnd.\n  rw h0.\n  apply isvalue_like_lsubst_aux.\n  apply alpha_eq_preserves_isvalue_like in h1; auto.\nQed.\nHint Resolve isvalue_like_lsubst : slow.\n\nLemma isvalue_like_subst {o} :\n  forall (t : @NTerm o) v u,\n    isvalue_like t\n    -> isvalue_like (subst t v u).\nProof.\n  introv isv.\n  unfold subst; eauto with slow.\nQed.\nHint Resolve isvalue_like_subst : slow.\n\nFixpoint subst_utoken_aux_lsubst_aux {o} (usub : @utok_sub o) (sub : @Sub o) : Sub :=\n  match sub with\n    | nil => nil\n    | (v,t) :: s => (v, subst_utokens_aux t usub) :: subst_utoken_aux_lsubst_aux usub s\n  end.\n\nDefinition cl_utok_sub {p} (sub : @utok_sub p) :=\n  forall a t, LIn (a,t) sub -> closed t.\n\nLemma sub_find_utok_sub_lsubst_aux {o} :\n  forall (usub : @utok_sub o) sub v,\n    sub_find (subst_utoken_aux_lsubst_aux usub sub) v\n    = match sub_find sub v with\n        | Some t => Some (subst_utokens_aux t usub)\n        | None => None\n      end.\nProof.\n  induction sub; introv; simpl; auto.\n  destruct a; simpl; boolvar; auto.\nQed.\n\nLemma cl_utok_sub_cons {o} :\n  forall a t (sub : @utok_sub o),\n    cl_utok_sub ((a,t) :: sub) <=> (closed t # cl_utok_sub sub).\nProof.\n  introv; unfold cl_utok_sub; simpl; split; introv k; repnd; dands; tcsp.\n  - eapply k; eauto.\n  - introv i.\n    eapply k; eauto.\n  - introv i; repndors; cpx.\n    eapply k; eauto.\nQed.\n\nLemma implies_cl_utok_sub_cons {o} :\n  forall a t (sub : @utok_sub o),\n    closed t\n    -> cl_utok_sub sub\n    -> cl_utok_sub ((a,t) :: sub).\nProof.\n  introv c1 c2.\n  apply cl_utok_sub_cons; auto.\nQed.\nHint Resolve implies_cl_utok_sub_cons : slow.\n\nLemma cl_utok_sub_nil {o} :\n  @cl_utok_sub o [].\nProof.\n  unfold cl_utok_sub; simpl; sp.\nQed.\nHint Resolve cl_utok_sub_nil : slow.\n\nLemma cl_utok_sub_implies_free_vars_utok_sub_nil {o} :\n  forall (sub : @utok_sub o),\n    cl_utok_sub sub\n    -> free_vars_utok_sub sub = [].\nProof.\n  induction sub; introv cl; allsimpl; auto.\n  destruct a.\n  rw @cl_utok_sub_cons in cl; repnd.\n  rw cl0; sp.\nQed.\n\nLemma cl_subst_utokens_aux {o} :\n  forall (t : @NTerm o) sub,\n    cl_utok_sub sub\n    -> subst_utokens t sub = subst_utokens_aux t sub.\nProof.\n  introv cl.\n  unfold subst_utokens.\n  rw @cl_utok_sub_implies_free_vars_utok_sub_nil; auto.\n  boolvar; tcsp.\n  provefalse; sp.\nQed.\n\nLemma sub_filter_subst_utoken_aux_lsubst_aux {o} :\n  forall (usub : @utok_sub o) (sub : @Sub o) l,\n    sub_filter (subst_utoken_aux_lsubst_aux usub sub) l\n    = subst_utoken_aux_lsubst_aux usub (sub_filter sub l).\nProof.\n  induction sub; introv; allsimpl; auto.\n  destruct a; allsimpl; boolvar; allsimpl; tcsp.\n  f_equal; sp.\nQed.\n\nLemma cl_subst_utokens_lsubst_aux {o} :\n  forall (t : @NTerm o) sub usub,\n    cl_utok_sub usub\n    -> cl_sub sub\n    -> subst_utokens_aux (lsubst_aux t sub) usub\n       = lsubst_aux (subst_utokens_aux t usub) (subst_utoken_aux_lsubst_aux usub sub).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv cl1 cl2; auto.\n\n  - Case \"vterm\".\n    simpl.\n    rw @sub_find_utok_sub_lsubst_aux.\n    remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; auto.\n\n  - Case \"oterm\".\n    rw @lsubst_aux_oterm.\n    repeat (rw @subst_utokens_aux_oterm).\n    remember (get_utok op) as guo; symmetry in Heqguo; destruct guo.\n\n    + allapply @get_utok_some; subst.\n      unfold subst_utok.\n      remember (utok_sub_find usub g) as usf; symmetry in Hequsf; destruct usf.\n\n      * apply utok_sub_find_some in Hequsf.\n        apply cl1 in Hequsf.\n        rw @lsubst_aux_trivial_cl_term2; auto.\n\n      * simpl; f_equal.\n        unfold lsubst_bterms_aux.\n        allrw map_map; allunfold @compose.\n        apply eq_maps; introv i.\n        destruct x as [l t]; simpl.\n        f_equal.\n        rw @sub_filter_subst_utoken_aux_lsubst_aux.\n        eapply ind; eauto with slow.\n\n    + simpl.\n      f_equal.\n      unfold lsubst_bterms_aux.\n      allrw map_map; allunfold @compose.\n      apply eq_maps; introv i.\n      destruct x as [l t]; simpl.\n      f_equal.\n      rw @sub_filter_subst_utoken_aux_lsubst_aux.\n      eapply ind; eauto with slow.\nQed.\n\nLemma isvalue_like_bot {o} :\n  @isvalue_like o mk_bot -> False.\nProof.\n  introv isv.\n  unfold isvalue_like in isv; sp.\nQed.\n\nLemma isvalue_like_apply {o} :\n  forall (a b : @NTerm o), isvalue_like (mk_apply a b) -> False.\nProof.\n  introv isv.\n  unfold isvalue_like in isv; tcsp.\nQed.\n\nLemma not_bot_reduces_to_value_like {p} :\n  forall lib (t : @NTerm p), isvalue_like t -> !reduces_to lib mk_bot t.\nProof.\n  introv isv r.\n  unfold reduces_to in r; sp.\n  revert t isv r.\n  induction k as [? ind] using comp_ind_type; sp; allsimpl.\n  destruct k.\n\n  - allrw @reduces_in_atmost_k_steps_0; subst.\n    apply isvalue_like_bot in isv; sp.\n\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    csunf r1; simpl in r1; ginv.\n    destruct k.\n\n    + allrw @reduces_in_atmost_k_steps_0; subst.\n      apply isvalue_like_apply in isv; sp.\n\n    + allrw @reduces_in_atmost_k_steps_S; exrepnd.\n      csunf r0; simpl in r0; ginv.\n      unfold apply_bterm, lsubst in r1; allsimpl.\n      apply ind in r1; tcsp.\nQed.\n\nLemma isprogram_fresh {p} :\n  forall v (b : @NTerm p),\n    isprogram (mk_fresh v b) <=> isprog_vars [v] b.\nProof.\n  introv; split; introv k; allrw @isprog_vars_eq; repnd; dands.\n  - inversion k as [c w].\n    rw subvars_prop; introv i; simpl; left.\n    unfold closed in c; allsimpl; allrw app_nil_r.\n    destruct (deq_nvar v x); auto.\n    assert (LIn x (remove_nvars [v] (free_vars b))) as h.\n    { rw in_remove_nvars; simpl; sp. }\n    rw c in h; allsimpl; sp.\n  - inversion k as [c w].\n    allrw @nt_wf_eq.\n    apply wf_fresh_iff in w; auto.\n  - split.\n    + unfold closed.\n      rw <- null_iff_nil.\n      introv i; allsimpl; allrw app_nil_r.\n      allrw in_remove_nvars; repnd; allsimpl; allrw not_over_or; repnd; GC.\n      rw subvars_prop in k0; apply k0 in i0; allsimpl; sp.\n    + allrw @nt_wf_eq.\n      apply wf_fresh_iff; auto.\nQed.\n\nDefinition isprog_vars_utok_sub {o} (vs : list NVar) (sub : @utok_sub o) :=\n  forall a t, LIn (a,t) sub -> isprog_vars vs t.\n\nLemma isprog_vars_utok_sub_nil {o} :\n  forall vs, @isprog_vars_utok_sub o vs [].\nProof.\n  introv i; allsimpl; sp.\nQed.\nHint Resolve isprog_vars_utok_sub_nil : slow.\n\nLemma isprog_vars_utok_sub_cons {o} :\n  forall a (t : @NTerm o) sub vs,\n    isprog_vars_utok_sub vs ((a,t) :: sub)\n    <=> (isprog_vars vs t # isprog_vars_utok_sub vs sub).\nProof.\n  introv; unfold isprog_vars_utok_sub; split; introv k; allsimpl; repnd; dands.\n  - eapply k; eauto.\n  - introv i; eapply k; eauto.\n  - introv i; repndors; cpx.\n    eapply k; eauto.\nQed.\n\nLemma implies_isprog_vars_utok_sub_cons {o} :\n  forall a (t : @NTerm o) sub vs,\n    isprog_vars vs t\n    -> isprog_vars_utok_sub vs sub\n    -> isprog_vars_utok_sub vs ((a,t) :: sub).\nProof.\n  introv ispt isps.\n  apply isprog_vars_utok_sub_cons; sp.\nQed.\nHint Resolve implies_isprog_vars_utok_sub_cons : slow.\n\nLemma isprog_vars_utok_sub_subvars {o} :\n  forall (sub : @utok_sub o) vs1 vs2,\n    subvars vs1 vs2\n    -> isprog_vars_utok_sub vs1 sub\n    -> isprog_vars_utok_sub vs2 sub.\nProof.\n  induction sub; introv sv isp; allsimpl; eauto with slow.\n  destruct a.\n  allrw @isprog_vars_utok_sub_cons; repnd; dands; eauto with slow.\nQed.\nHint Resolve isprog_vars_utok_sub_subvars : slow.\n\nLemma implies_isprog_vars_subst_utokens_aux {o} :\n  forall (t : @NTerm o) sub vs,\n    isprog_vars_utok_sub vs sub\n    -> isprog_vars vs t\n    -> isprog_vars vs (subst_utokens_aux t sub).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv isps ipst; auto.\n  Case \"oterm\".\n  rw @subst_utokens_aux_oterm.\n  remember (get_utok op) as guo; symmetry in Heqguo; destruct guo.\n\n  - apply get_utok_some in Heqguo; subst.\n    unfold subst_utok.\n    remember (utok_sub_find sub g) as usf; symmetry in Hequsf; destruct usf; auto.\n\n    + apply utok_sub_find_some in Hequsf.\n      apply isps in Hequsf; auto.\n\n    + allrw @isprog_vars_ot_iff; allrw map_map; unfold compose; repnd; dands.\n\n      * rw <- ipst0.\n        apply eq_maps; introv i; destruct x as [l t]; unfold num_bvars; simpl; auto.\n\n      * introv i.\n        rw in_map_iff in i; exrepnd.\n        destruct a as [l1 t1]; allsimpl; ginv.\n        eapply ind; eauto with slow.\n\n  - allrw @isprog_vars_ot_iff; allrw map_map; unfold compose; repnd.\n    rw <- ipst0; dands.\n\n    + apply eq_maps; introv i; destruct x as [l t]; unfold num_bvars; simpl; auto.\n\n    + introv i.\n      rw in_map_iff in i; exrepnd.\n      destruct a as [l1 t1]; allsimpl; ginv.\n      eapply ind; eauto with slow.\nQed.\n\nLemma implies_isprog_vars_subst_utokens {o} :\n  forall (t : @NTerm o) sub vs,\n    isprog_vars_utok_sub vs sub\n    -> isprog_vars vs t\n    -> isprog_vars vs (subst_utokens t sub).\nProof.\n  introv isps ispt.\n  pose proof (unfold_subst_utokens sub t) as h; exrepnd; rw h0.\n  apply implies_isprog_vars_subst_utokens_aux; auto.\n  eapply alphaeq_preserves_isprog_vars in h1; eauto.\nQed.\n\n(* !!MOVE *)\nHint Resolve isprog_vars_mk_var : slow.\nHint Resolve nt_wf_utoken : slow.\n\nDefinition covered_sub {p} (sub1 sub2 : @Sub p) :=\n  sub_range_sat sub1 (fun t => covered t (dom_sub sub2)).\n\nLemma covered_sub_nil {o} :\n  forall (sub : @Sub o),\n    covered_sub [] sub.\nProof.\n  introv; unfold covered_sub, sub_range_sat; allsimpl; sp.\nQed.\n\nLemma covered_sub_cons {o} :\n  forall v t (sub1 sub2 : @Sub o),\n    covered_sub ((v,t) :: sub1) sub2\n    <=> (covered t (dom_sub sub2) # covered_sub sub1 sub2).\nProof.\n  unfold covered_sub, sub_range_sat; introv; split; intro k; repnd; dands; introv.\n  - apply (k v t); simpl; sp.\n  - intro i; apply (k v0 t0); simpl; sp.\n  - intro i; simpl in i; dorn i; cpx.\n    apply (k v0 t0); auto.\nQed.\n\nLemma implies_cl_sub_lsubst_aux_sub {o} :\n  forall (sub1 sub2 : @Sub o),\n    cl_sub sub2\n    -> covered_sub sub1 sub2\n    -> cl_sub (lsubst_aux_sub sub1 sub2).\nProof.\n  induction sub1; introv cl cov; allsimpl; auto.\n  - apply cl_sub_nil.\n  - destruct a.\n    rw @covered_sub_cons in cov; repnd.\n    apply cl_sub_cons; dands; auto.\n    apply closed_lsubst_aux; auto.\nQed.\n\nLemma simple_lsubst_aux_lsubst_aux_sub_aeq {o} :\n  forall (t t' : @NTerm o) sub1 sub2,\n    cl_sub sub2\n    -> covered_sub sub1 sub2\n    -> disjoint (bound_vars t') (sub_free_vars sub1)\n    -> alpha_eq t t'\n    -> alpha_eq\n         (lsubst_aux (lsubst_aux t (sub_filter sub2 (dom_sub sub1)))\n                     (lsubst_aux_sub sub1 sub2))\n         (lsubst_aux (lsubst_aux t' sub1) sub2).\nProof.\n  introv cl cov disj aeq.\n  pose proof (simple_lsubst_aux_lsubst_aux_sub t' sub1 sub2 cl disj) as h.\n  rw <- h; clear h.\n  repeat (apply lsubst_aux_alpha_congr_same_cl_sub); auto.\n  - apply implies_cl_sub_filter; auto.\n  - apply implies_cl_sub_lsubst_aux_sub; auto.\nQed.\n\nLemma simple_lsubst_lsubst_aux_sub_aeq {o} :\n  forall (t : @NTerm o) sub1 sub2,\n    cl_sub sub2\n    -> covered_sub sub1 sub2\n    -> alpha_eq\n         (lsubst (lsubst_aux t (sub_filter sub2 (dom_sub sub1)))\n                 (lsubst_aux_sub sub1 sub2))\n         (lsubst_aux (lsubst t sub1) sub2).\nProof.\n  introv cl cov.\n  unfold lsubst; allsimpl; boolvar; allsimpl;\n  try (complete (destruct n;\n                 pose proof (implies_cl_sub_lsubst_aux_sub sub1 sub2 cl cov) as h;\n                 apply flat_map_free_vars_range_cl_sub in h; rw h; auto)).\n\n  - rw @simple_lsubst_aux_lsubst_aux_sub; auto.\n    rw @sub_free_vars_is_flat_map_free_vars_range; auto.\n\n  - pose proof (change_bvars_alpha_spec t (flat_map free_vars (range sub1))) as h;\n    simpl in h; repnd.\n    remember (change_bvars_alpha (flat_map free_vars (range sub1)) t) as t';\n      clear Heqt'.\n\n    apply simple_lsubst_aux_lsubst_aux_sub_aeq; eauto with slow.\n    rw @sub_free_vars_is_flat_map_free_vars_range; eauto with slow.\nQed.\n\nLemma alpha_eq_oterm_snd_subterm {o} :\n  forall op b b1 b2 (bs : list (@BTerm o)),\n    alpha_eq_bterm b1 b2\n    -> alpha_eq (oterm op (b :: b1 :: bs)) (oterm op (b :: b2 :: bs)).\nProof.\n  introv aeq.\n  constructor; simpl; auto.\n  introv k.\n  destruct n; cpx.\n  destruct n; cpx.\nQed.\n\nLemma alpha_eq_oterm_fst_subterm {o} :\n  forall op b1 b2 (bs : list (@BTerm o)),\n    alpha_eq_bterm b1 b2\n    -> alpha_eq (oterm op (b1 :: bs)) (oterm op (b2 :: bs)).\nProof.\n  introv aeq.\n  constructor; simpl; auto.\n  introv k.\n  destruct n; cpx.\nQed.\n\nLemma compute_step_catch_non_trycatch {o} :\n  forall ncan (bts bs : list (@BTerm o)),\n    ncan <> NTryCatch\n    -> compute_step_catch\n         ncan\n         (oterm (NCan ncan) (bterm [] (oterm Exc bts) :: bs))\n         bts\n         bs\n       = csuccess (oterm Exc bts).\nProof.\n  introv d.\n  unfold compute_step_catch; destruct ncan; auto; cpx.\nQed.\n\nLemma implies_prog_sub_cons {o} :\n  forall (sub : @Sub o) (v : NVar) (t : NTerm),\n    isprogram t\n    -> prog_sub sub\n    -> prog_sub ((v, t) :: sub).\nProof.\n  introv a b.\n  rw @prog_sub_cons; auto.\nQed.\nHint Resolve implies_prog_sub_cons : slow.\n\n(* !! MOVE *)\nHint Resolve prog_sub_sub_filter : slow.\n\nLemma cl_lsubst_aux_swap_cons_snoc {o} :\n  forall (t : @NTerm o) sub v u,\n    cl_sub sub\n    -> closed u\n    -> !LIn v (dom_sub sub)\n    -> lsubst_aux t ((v, u) :: sub) = lsubst_aux t (snoc sub (v, u)).\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv cls clu ni; allsimpl; auto.\n\n  - Case \"vterm\".\n    rw @sub_find_snoc; boolvar; auto.\n\n    + remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; auto.\n      apply sub_find_some in Heqsf.\n      apply in_sub_eta in Heqsf; sp.\n\n    + remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; auto.\n\n  - Case \"oterm\".\n    f_equal.\n    apply eq_maps; introv i.\n    destruct x as [l t]; simpl.\n    f_equal; simpl.\n    boolvar; tcsp.\n\n    + rw @sub_filter_snoc; boolvar; tcsp.\n\n    + rw @sub_filter_snoc; boolvar; tcsp.\n      eapply ind; eauto with slow.\n      rw <- @dom_sub_sub_filter.\n      rw in_remove_nvars; sp.\nQed.\n\nLemma cl_sub_snoc {o} :\n  forall (sub : @Sub o) v t,\n    cl_sub (snoc sub (v,t))\n    <=> (cl_sub sub # closed t).\nProof.\n  induction sub; introv; allsimpl; split; intro k; repnd; dands; eauto with slow;\n  allrw @cl_sub_cons; repnd; dands; eauto with slow.\n  - apply IHsub in k; sp.\n  - apply IHsub in k; sp.\n  - apply IHsub; sp.\nQed.\n\nLemma implies_cl_sub_snoc {o} :\n  forall (sub : @Sub o) v t,\n    cl_sub sub\n    -> closed t\n    -> cl_sub (snoc sub (v,t)).\nProof.\n  introv cls clt.\n  apply cl_sub_snoc; sp.\nQed.\nHint Resolve implies_cl_sub_snoc : slow.\n\nLemma cl_lsubst_swap {o} :\n  forall (t : @NTerm o) sub v u,\n    cl_sub sub\n    -> closed u\n    -> !LIn v (dom_sub sub)\n    -> lsubst t ((v, u) :: sub) = lsubst t (snoc sub (v, u)).\nProof.\n  introv cls clu ni.\n  unfold lsubst; simpl.\n  rw clu; allsimpl.\n  allrw <- @sub_free_vars_is_flat_map_free_vars_range.\n  allrw @sub_free_vars_if_cl_sub; eauto with slow.\n  boolvar; tcsp; try (complete (provefalse; tcsp)).\n  apply cl_lsubst_aux_swap_cons_snoc; auto.\nQed.\n\nLemma cl_simple_lsubst_cons3 {o} :\n  forall (t : @NTerm o) v u sub,\n    cl_sub ((v, u) :: sub)\n    -> !LIn v (dom_sub sub)\n    -> subst (lsubst t sub) v u = lsubst t ((v, u) :: sub).\nProof.\n  introv Hps Hd.\n  allrw @cl_sub_cons; repnd.\n  rw @cl_lsubst_swap; auto.\n  rw snoc_as_append.\n  rw @cl_lsubst_app; eauto with slow.\nQed.\n\nLemma cl_simple_lsubst_cons2 {o} :\n  forall (t : @NTerm o) v u sub,\n    cl_sub ((v, u) :: sub)\n    -> lsubst (subst t v u) sub = lsubst t ((v, u) :: sub).\nProof.\n  introv cl.\n  allrw @cl_sub_cons; repnd.\n  unfold subst.\n  rw <- @cl_lsubst_app; eauto with slow.\nQed.\n\nLemma isnoncan_like_lsubst_aux {o} :\n  forall (t : @NTerm o) sub,\n    isnoncan_like t\n    -> isnoncan_like (lsubst_aux t sub).\nProof.\n  introv isv.\n  unfold isnoncan_like in isv; repndors.\n  - apply isnoncan_implies in isv; exrepnd; subst.\n    simpl; eauto with slow.\n  - apply isabs_implies in isv; exrepnd; subst.\n    simpl; eauto with slow.\nQed.\nHint Resolve isnoncan_like_lsubst_aux : slow.\n\nLemma iscan_lsubst_aux {o} :\n  forall (t : @NTerm o) sub,\n    iscan t\n    -> iscan (lsubst_aux t sub).\nProof.\n  introv isc.\n  apply iscan_implies in isc; repndors; exrepnd; subst; allsimpl; auto.\nQed.\nHint Resolve iscan_lsubst_aux : slow.\n\nLemma isexc_lsubst_aux {o} :\n  forall (t : @NTerm o) sub,\n    isexc t\n    -> isexc (lsubst_aux t sub).\nProof.\n  introv ise.\n  apply isexc_implies2 in ise; exrepnd; subst; allsimpl; auto.\nQed.\nHint Resolve isexc_lsubst_aux : slow.\n\nLemma alpha_eq_preserves_isnoncan_like {o} :\n  forall (a b : @NTerm o),\n    alpha_eq a b\n    -> isnoncan_like a\n    -> isnoncan_like b.\nProof.\n  introv aeq iv.\n  unfold isnoncan_like in iv.\n  repndors.\n  - apply isnoncan_implies in iv; exrepnd; subst.\n    inversion aeq; subst; left; sp.\n  - apply isabs_implies in iv; exrepnd; subst.\n    inversion aeq; subst; right; sp.\nQed.\n\nLemma isnoncan_like_lsubst {o} :\n  forall (t : @NTerm o) sub,\n    isnoncan_like t\n    -> isnoncan_like (lsubst t sub).\nProof.\n  introv isv.\n  pose proof (unfold_lsubst sub t) as h; exrepnd.\n  rw h0.\n  apply isnoncan_like_lsubst_aux.\n  apply alpha_eq_preserves_isnoncan_like in h1; auto.\nQed.\nHint Resolve isnoncan_like_lsubst : slow.\n\nLemma compute_step_ncan_vterm_success {o} :\n  forall lib ncan (bs : list (@BTerm o)) u a,\n    compute_step lib (oterm (NCan ncan) (bterm [] (mk_utoken a) :: bs))\n    = csuccess u\n    -> (\n         (ncan = NParallel # u = mk_axiom)\n         [+]\n         (ncan = NFix\n          # bs = []\n          # u = mk_apply (mk_utoken a) (mk_fix (mk_utoken a)))\n         [+]\n         {x : NVar\n          & {b : NTerm\n          & ncan = NCbv\n          # bs = [bterm [x] b]\n          # u = subst b x (mk_utoken a)}}\n         [+]\n         {a' : NTerm\n          & {x : NVar\n          & {b : NTerm\n          & ncan = NTryCatch\n          # bs = [nobnd a', bterm [x] b]\n          # u = mk_atom_eq a' a' (mk_utoken a) mk_bot}}}\n         [+]\n         {t1 : NTerm\n          & {bs1 : list BTerm\n          & bs = nobnd t1 :: bs1\n          # ncan = NCompOp CompOpEq\n          # (\n              {t2 : NTerm\n               & {t3 : NTerm\n\n                       & {pk : param_kind\n               & bs1 = [nobnd t2, nobnd t3]\n               # t1 = pk2term pk\n               # ((pk = PKa a # u = t2) [+] (pk <> PKa a # u = t3))}}}\n              [+]\n              {x : NTerm\n               & compute_step lib t1 = csuccess x\n               # isnoncan_like t1\n               # u = oterm (NCan ncan) (nobnd (mk_utoken a) :: nobnd x :: bs1) }\n              [+]\n              (isexc t1 # u = t1)\n            )}}\n         [+]\n         {t1 : NTerm\n          & {t2 : NTerm\n          & {x : CanonicalTest\n          & ncan = NCanTest x\n          # bs = [nobnd t1, nobnd t2]\n          # ((x = CanIsuatom # u = t1) [+] (x <> CanIsuatom # u = t2))}}}\n       ).\nProof.\n  introv comp.\n  csunf comp.\n  allsimpl.\n  unfold compute_step_can in comp.\n  dopid_noncan ncan Case;\n    try (complete (allsimpl; ginv));\n    try (complete (destruct bs; ginv)).\n\n  - Case \"NFix\".\n    apply compute_step_fix_success in comp; repnd; subst.\n    right; left; auto.\n\n  - Case \"NCbv\".\n    apply compute_step_cbv_success in comp; exrepnd; subst.\n    right; right; left.\n    exists v x; auto.\n\n  - Case \"NTryCatch\".\n    apply compute_step_try_success in comp; exrepnd; subst.\n    right; right; right; left.\n    exists a0 v x; auto.\n\n  - Case \"NParallel\".\n    apply compute_step_parallel_success in comp; subst; tcsp.\n\n  - Case \"NCompOp\".\n    right; right; right; right; left.\n    boolvar; tcsp; ginv.\n    destruct bs; ginv; try (complete (allsimpl; dcwf h));[].\n    destruct b as [l t].\n    destruct l; ginv; try (complete (allsimpl; dcwf h));[].\n    destruct t as [v1|f1|op1 bs1]; try (complete (allsimpl; dcwf h));[].\n\n    dcwf h.\n    allunfold @co_wf_def; exrepnd; allsimpl; ginv; GC.\n    repndors; exrepnd; subst; ginv;[].\n    dopid op1 as [can1|ncan1|exc1|abs1] SCase.\n\n    + SCase \"Can\".\n      apply compute_step_compop_success_can_can in comp; exrepnd; subst; GC.\n      repndors; exrepnd; subst; allsimpl; ginv.\n      allrw @get_param_from_cop_some; subst.\n      exists (oterm (Can (pk2can pk2)) []) [nobnd t1, nobnd t2]; dands; auto.\n      left.\n      exists t1 t2 pk2.\n      allrw @pk2term_eq; dands; auto.\n      boolvar; tcsp.\n\n    + SCase \"NCan\".\n      remember (compute_step lib (oterm (NCan ncan1) bs1)) as c1; ginv.\n      destruct c1; allsimpl; ginv.\n      exists (oterm (NCan ncan1) bs1) bs; dands; auto.\n      right; left.\n      exists n; dands; auto.\n\n    + SCase \"Exc\".\n      ginv.\n      exists (oterm Exc bs1) bs; dands; auto.\n\n    + SCase \"Abs\".\n      remember (compute_step lib (oterm (Abs abs1) bs1)) as c1; ginv.\n      destruct c1; allsimpl; ginv.\n      exists (oterm (Abs abs1) bs1) bs; dands; auto.\n      right; left.\n      exists n; dands; auto.\n\n  - Case \"NCanTest\".\n    right; right; right; right; right.\n    apply compute_step_can_test_success in comp; exrepnd; subst.\n    exists arg2nt arg3nt c; dands; auto.\n    destruct c; allsimpl; tcsp;\n    try (complete (right; dands; auto; intro k; inversion k)).\nQed.\n\nLemma singleton_disjoint :\n  forall T (x y : T),\n    x <> y -> disjoint [x] [y].\nProof.\n  introv ni.\n  apply disjoint_singleton_l; simpl; sp.\nQed.\nHint Resolve singleton_disjoint : slow.\n\nLemma allvars_sub_nil {o} :\n  @allvars_sub o [].\nProof.\n  unfold allvars_sub, sub_range_sat; simpl; sp.\nQed.\nHint Resolve allvars_sub_nil : slow.\n\nLemma isvariable_implies {o} :\n  forall (t : @NTerm o), isvariable t -> {v : NVar & t = vterm v}.\nProof.\n  introv isv.\n  destruct t; allsimpl; tcsp.\n  eexists; eauto.\nQed.\n\nLemma allvars_sub_cons {o} :\n  forall v t (s : @Sub o),\n    allvars_sub ((v,t) :: s) <=> (isvariable t # allvars_sub s).\nProof.\n  introv; unfold allvars_sub, sub_range_sat; simpl; split; intro k; repnd; dands.\n  - pose proof (k v t) as h; autodimp h hyp.\n    unfold isvarc in h; exrepnd; subst; simpl; auto.\n  - introv h; eapply k; eauto.\n  - introv h; repndors; cpx; repdors.\n    + apply isvariable_implies in k0; auto.\n    + eapply k; eauto.\nQed.\n\nLemma implies_allvars_sub_cons {o} :\n  forall v t (s : @Sub o),\n    isvariable t\n    -> allvars_sub s\n    -> allvars_sub ((v,t) :: s).\nProof.\n  introv a b; apply allvars_sub_cons; sp.\nQed.\nHint Resolve implies_allvars_sub_cons : slow.\n\nLemma isvariable_var {o} :\n  forall v, @isvariable o (mk_var v).\nProof. sp. Qed.\nHint Resolve isvariable_var : slow.\n\nLemma lsubst_aux_utoken_eq_utoken_implies {o} :\n  forall (t : @NTerm o) a sub,\n    lsubst_aux t sub = mk_utoken a\n    -> !LIn a (get_utokens t)\n    -> {v : NVar & sub_find sub v = Some (mk_utoken a) # t = mk_var v}.\nProof.\n  destruct t as [v|f ind|op bs ind]; introv e ni; allsimpl; GC; ginv.\n\n  - remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; subst; ginv.\n    eexists; dands; eauto.\n\n  - inversion e; subst.\n    destruct bs; allsimpl; cpx; GC; fold_terms.\n    allrw not_over_or; sp.\nQed.\n\nLemma lsubst_aux_utoken_eq_utoken_implies2 {o} :\n  forall (t : @NTerm o) a sub,\n    lsubst_aux t sub = mk_utoken a\n    -> !LIn a (get_utokens_sub sub)\n    -> t = mk_utoken a.\nProof.\n  destruct t as [v|f|op bs ind]; introv e ni; allsimpl; GC; ginv.\n\n  - remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; subst; ginv.\n    apply sub_find_some in Heqsf.\n    destruct ni; unfold get_utokens_sub.\n    rw lin_flat_map.\n    exists (mk_utoken a); simpl; dands; tcsp.\n    apply in_sub_eta in Heqsf; sp.\n\n  - inversion e; subst.\n    destruct bs; allsimpl; cpx; GC; fold_terms.\nQed.\n\nLemma memvar_cons :\n  forall x v vs,\n    memvar x (v :: vs) =\n    if deq_nvar x v then true else memvar x vs.\nProof.\n  introv.\n  unfold memvar; simpl.\n  boolvar; tcsp.\nQed.\n\nLemma remove_nvars_swapbvars_nil :\n  forall vs vs1 vs2,\n    length vs1 = length vs2\n    -> subvars vs vs1\n    -> no_repeats vs2\n    -> disjoint vs1 vs2\n    -> remove_nvars vs2 (swapbvars (mk_swapping vs1 vs2) vs) = [].\nProof.\n  induction vs; introv len sv norep disj; allsimpl.\n  - rw remove_nvars_nil_r; auto.\n  - allrw subvars_cons_l; repnd.\n    rw remove_nvars_cons_r; boolvar; tcsp.\n    rw IHvs; auto.\n    destruct Heqb.\n    apply swapvar_implies3; auto.\nQed.\n\nLemma compute_step_ncompop_can1_success {o} :\n  forall lib c can (bts bs : list (@BTerm o)) u,\n    compute_step lib (oterm (NCan (NCompOp c)) (bterm [] (oterm (Can can) bts) :: bs))\n    = csuccess u\n    -> co_wf_def c can bts\n       #\n       (\n          {can' : CanonicalOp\n           & {t1 : NTerm\n           & {t2 : NTerm\n           & bs = [nobnd (oterm (Can can') []),nobnd t1,nobnd t2]\n           # compute_step_comp\n               c can can' bts [] [nobnd t1, nobnd t2]\n               (oterm (NCan (NCompOp c)) (bterm [] (oterm (Can can) bts) :: bs))\n             = csuccess u}}}\n          [+]\n          {t : NTerm\n           & {t' : NTerm\n           & {bs' : list BTerm\n           & bs = bterm [] t :: bs'\n           # isnoncan_like t\n           # compute_step lib t = csuccess t'\n           # u = oterm (NCan (NCompOp c)) (bterm [] (oterm (Can can) bts) :: bterm [] t' :: bs')}}}\n          [+]\n           {t : NTerm\n           & {bs' : list BTerm\n           & isexc t\n           # bs = nobnd t :: bs'\n           # u = t}}\n         ).\nProof.\n  introv comp.\n  csunf comp; allsimpl.\n  dcwf h; dands; auto;[].\n  destruct bs as [|b bs]; ginv;[].\n  destruct b as [l t].\n  destruct l as [|v vs]; ginv;[].\n  destruct t as [v|f|op bs1]; ginv;[].\n  dopid op as [can1|ncan1|exc1|abs1] Case; ginv.\n  - Case \"Can\".\n    dup comp as comp'.\n    apply compute_step_compop_success_can_can in comp; exrepnd; subst.\n    left; exists can1 t1 t2; dands; auto.\n  - Case \"NCan\".\n    remember (compute_step lib (oterm (NCan ncan1) bs1)) as nc.\n    symmetry in Heqnc; destruct nc; allsimpl; ginv.\n    right; left.\n    exists (oterm (NCan ncan1) bs1) n bs; dands; auto.\n  - Case \"Exc\".\n    right; right.\n    exists (oterm Exc bs1) bs; simpl; sp.\n  - Case \"Abs\".\n    remember (compute_step lib (oterm (Abs abs1) bs1)) as nc.\n    symmetry in Heqnc; destruct nc; allsimpl; ginv.\n    right; left.\n    exists (oterm (Abs abs1) bs1) n bs; dands; auto.\nQed.\n\nLemma compute_step_narithop_can1_success {o} :\n  forall lib c can (bts bs : list (@BTerm o)) u,\n    compute_step lib (oterm (NCan (NArithOp c)) (bterm [] (oterm (Can can) bts) :: bs))\n    = csuccess u\n    -> ca_wf_def can bts\n       # (\n          {can' : CanonicalOp\n           & bs = [nobnd (oterm (Can can') [])]\n           # compute_step_arith\n               c can can' bts [] []\n               (oterm (NCan (NArithOp c)) (bterm [] (oterm (Can can) bts) :: bs))\n             = csuccess u}\n          [+]\n          {t : NTerm\n           & {t' : NTerm\n           & {bs' : list BTerm\n           & bs = bterm [] t :: bs'\n           # isnoncan_like t\n           # compute_step lib t = csuccess t'\n           # u = oterm (NCan (NArithOp c)) (bterm [] (oterm (Can can) bts) :: bterm [] t' :: bs')}}}\n          [+]\n           {t : NTerm\n           & {bs' : list BTerm\n           & isexc t\n           # bs = nobnd t :: bs'\n           # u = t}}\n         ).\nProof.\n  introv comp.\n  csunf comp; allsimpl.\n  dcwf h; dands; auto;[].\n  destruct bs as [|b bs]; ginv;[].\n  destruct b as [l t];[].\n  destruct l as [|v vs]; ginv;[].\n  destruct t as [v|f|op bs1]; ginv;[].\n  dopid op as [can1|ncan1|exc1|abs1] Case; ginv.\n  - Case \"Can\".\n    apply compute_step_arithop_success_can_can in comp; exrepnd; subst.\n    allapply @get_param_from_cop_pki; subst; allsimpl.\n    left; exists (@Nint o n2); dands; auto.\n  - Case \"NCan\".\n    remember (compute_step lib (oterm (NCan ncan1) bs1)) as nc.\n    symmetry in Heqnc; destruct nc; allsimpl; ginv.\n    right; left.\n    exists (oterm (NCan ncan1) bs1) n bs; dands; auto.\n  - Case \"Exc\".\n    right; right.\n    exists (oterm Exc bs1) bs; simpl; sp.\n  - Case \"Abs\".\n    remember (compute_step lib (oterm (Abs abs1) bs1)) as nc.\n    symmetry in Heqnc; destruct nc; allsimpl; ginv.\n    right; left.\n    exists (oterm (Abs abs1) bs1) n bs; dands; auto.\nQed.\n\nLemma lsubst_aux_eq_spcan_implies {o} :\n  forall (t : @NTerm o) sub can,\n    lsubst_aux t sub = oterm (Can can) []\n    -> ({v : NVar & sub_find sub v = Some (oterm (Can can) []) # t = mk_var v}\n        [+] t = oterm (Can can) []).\nProof.\n  introv e.\n  destruct t as [v|f|op bs]; allsimpl; auto.\n  - remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; subst; ginv.\n    left; exists v; dands; auto.\n  - destruct bs; allsimpl; ginv; sp.\nQed.\n\nLemma lsubst_aux_eq_vterm_implies {o} :\n  forall (t : @NTerm o) sub v,\n    lsubst_aux t sub = vterm v\n    -> ({x : NVar & sub_find sub x = Some (vterm v) # t = mk_var x}\n        [+] t = vterm v).\nProof.\n  introv e.\n  destruct t as [z|f|op bs]; allsimpl; auto.\n  - remember (sub_find sub z) as sf; symmetry in Heqsf; destruct sf; subst; ginv; tcsp.\n    left; exists z; dands; auto.\n  - destruct bs; allsimpl; ginv; sp.\nQed.\n\nLemma compute_step_narithop_ncanlike2 {p} :\n  forall lib ar c cbts (t : @NTerm p) rest,\n    isnoncan_like t\n    -> compute_step\n         lib\n         (oterm (NCan (NArithOp ar))\n                (bterm [] (oterm (Can c) cbts)\n                       :: bterm [] t\n                       :: rest))\n       = if ca_wf c cbts\n         then match compute_step lib t with\n                | csuccess f => csuccess (oterm (NCan (NArithOp ar))\n                                                (bterm [] (oterm (Can c) cbts)\n                                                       :: bterm [] f\n                                                       :: rest))\n                | cfailure str ts => cfailure str ts\n              end\n         else cfailure bad_args (oterm (NCan (NArithOp ar))\n                                       (bterm [] (oterm (Can c) cbts)\n                                              :: bterm [] t\n                                              :: rest)).\nProof.\n  introv isn.\n  unfold isnoncan_like in isn; repndors.\n  - apply isnoncan_implies in isn; exrepnd; subst.\n    rw @compute_step_eq_unfold; sp.\n  - apply isabs_implies in isn; exrepnd; subst.\n    rw @compute_step_eq_unfold; sp.\nQed.\n\nLemma alpha_eq_mk_vbot_lsubst_aux {o} :\n  forall v1 v2 (sub : @Sub o),\n    alpha_eq (mk_vbot v1) (lsubst_aux (mk_vbot v2) sub).\nProof.\n  introv; simpl.\n  allrw @sub_filter_nil_r.\n  rw @sub_find_sub_filter_eq; rw memvar_singleton; boolvar; tcsp.\n  unfold mk_vbot.\n  prove_alpha_eq4; introv h; destruct n; cpx.\n  apply alphaeqbt_nilv2.\n  prove_alpha_eq4; introv k; destruct n; cpx.\n  pose proof (ex_fresh_var [v1,v2]) as fv; exrepnd.\n  apply (al_bterm _ _ [v]); allsimpl; auto;\n  allrw disjoint_singleton_l; allsimpl; tcsp.\n  unfold lsubst; simpl; boolvar; auto.\nQed.\nHint Resolve alpha_eq_mk_vbot_lsubst_aux : slow.\n\nLemma alpha_eq_mk_bot_implies {o} :\n  forall (t : @NTerm o),\n    alpha_eq mk_bot t\n    -> {v : NVar & t = mk_vbot v}.\nProof.\n  introv aeq.\n  inversion aeq as [|?|? ? ? len imp]; subst; allsimpl; cpx; clear aeq.\n  pose proof (imp 0) as h; clear imp; autodimp h hyp.\n  unfold selectbt in h; allsimpl.\n  apply alphaeqbt_nilv in h; exrepnd; subst.\n  inversion h0 as [|?|? ? ? len imp]; subst; allsimpl; cpx; clear h0.\n  pose proof (imp 0) as h; clear imp; autodimp h hyp.\n  unfold selectbt in h; allsimpl.\n  apply alphaeqbt_1v in h; exrepnd; subst; allrw disjoint_singleton_l.\n  allunfold @lsubst; allsimpl.\n  allrw not_over_or; repnd; boolvar; allrw disjoint_singleton_r.\n  - destruct nt2 as [v|f|op bs]; allsimpl; allrw not_over_or; repnd; boolvar; tcsp;\n    inversion h0; subst; tcsp.\n    exists v; auto.\n  - destruct n; allunfold @all_vars; allrw in_app_iff; sp.\nQed.\n\nLemma alpha_eq_mk_bot_lsubst {o} :\n  forall (sub : @Sub o),\n    alpha_eq mk_bot (lsubst mk_bot sub).\nProof.\n  introv.\n  pose proof (unfold_lsubst sub mk_bot) as h; exrepnd; rw h0.\n  apply alpha_eq_mk_bot_implies in h1; exrepnd; subst.\n  apply alpha_eq_mk_vbot_lsubst_aux.\nQed.\nHint Resolve alpha_eq_mk_bot_lsubst : slow.\n\nLemma compute_step_fresh_if_isnoncan_like {o} :\n  forall lib v vs (t : @NTerm o) bs,\n    isnoncan_like t\n    -> compute_step lib (oterm (NCan NFresh) (bterm (v :: vs) t :: bs))\n       = match vs with\n           | [] =>\n             match bs with\n               | [] =>\n                 on_success\n                   (compute_step lib (subst t v (mk_utoken (get_fresh_atom t))))\n                   (fun r : NTerm => mk_fresh v (subst_utokens r [(get_fresh_atom t, mk_var v)]))\n               | _ :: _ =>\n                 cfailure \"check 1st arg\"\n                          (oterm (NCan NFresh) (bterm (v :: vs) t :: bs))\n             end\n           | _ :: _ =>\n             cfailure \"check 1st arg\"\n                      (oterm (NCan NFresh) (bterm (v :: vs) t :: bs))\n         end.\nProof.\n  introv isn.\n  csunf; simpl.\n  destruct vs; auto.\n  destruct bs; auto.\n  unfold isnoncan_like in isn; repndors.\n  - apply isnoncan_implies in isn; exrepnd; subst; auto.\n  - apply isabs_implies in isn; exrepnd; subst; auto.\nQed.\n\nLemma implies_alpha_eq_mk_fresh_subst_utokens {o} :\n  forall n a (t1 t2 : @NTerm o),\n    alpha_eq t1 t2\n    -> alpha_eq (mk_fresh n (subst_utokens t1 [(a, mk_var n)]))\n                (mk_fresh n (subst_utokens t2 [(a, mk_var n)])).\nProof.\n  introv aeq.\n  unfold mk_fresh.\n  apply alpha_eq_oterm_combine; simpl; dands; auto.\n  introv i; repndors; cpx.\n  apply alpha_eq_bterm_congr; auto.\n  apply alpha_eq_subst_utokens; eauto with slow.\nQed.\n\nLemma alpha_eq_oterm_combine2 {o} :\n  forall op1 op2 (bs1 bs2 : list (@BTerm o)),\n    alpha_eq (oterm op1 bs1) (oterm op2 bs2)\n    <=> (op1 = op2\n         # length bs1 = length bs2\n         # (forall b1 b2, LIn (b1,b2) (combine bs1 bs2) -> alpha_eq_bterm b1 b2)).\nProof.\n  introv; split; intro k.\n  - inversion k; subst; dands; auto.\n    introv i.\n    allunfold @selectbt.\n    allrw in_combine_sel_iff; exrepnd.\n    discover.\n    rw (nth_select1 n bs1 (@default_bt o)) in i3; auto.\n    rw (nth_select1 n bs2 (@default_bt o)) in i0; auto.\n    ginv; auto.\n  - repnd; subst; constructor; auto.\n    introv i.\n    unfold selectbt.\n    apply k.\n    apply in_combine_sel_iff.\n    exists n; dands; auto; try omega.\n    + rw (nth_select1 n bs1 (@default_bt o)); auto.\n    + rw (nth_select1 n bs2 (@default_bt o)); auto; try omega.\nQed.\n\nLemma lsubst_subst_utokens_aux_disj {o} :\n  forall (t : @NTerm o) (sub : Sub) (usub : utok_sub),\n    disjoint (get_utokens_sub sub) (utok_sub_dom usub)\n    -> disjoint (free_vars_utok_sub usub) (dom_sub sub)\n    -> disjoint (sub_free_vars sub) (bound_vars (subst_utokens_aux t usub))\n    -> disjoint (sub_free_vars sub) (bound_vars t)\n    -> lsubst (subst_utokens_aux t usub) sub\n       = subst_utokens_aux (lsubst t sub) usub.\nProof.\n  introv d1 d2 d3 d4.\n  unfold lsubst; boolvar; tcsp;\n  allrw <- @sub_free_vars_is_flat_map_free_vars_range.\n  - apply lsubst_aux_subst_utokens_aux_disj; auto.\n  - provefalse; destruct n; eauto with slow.\n  - provefalse; destruct n; eauto with slow.\n  - provefalse; destruct n; eauto with slow.\nQed.\n\nLemma sub_free_vars_var_ren {o} :\n  forall vs1 vs2,\n    length vs1 = length vs2\n    -> @sub_free_vars o (var_ren vs1 vs2) = vs2.\nProof.\n  induction vs1; introv len; allsimpl; cpx.\n  destruct vs2; allsimpl; cpx.\n  f_equal; tcsp.\n  fold (@var_ren o vs1 vs2); sp.\nQed.\n\nLemma get_utokens_sub_allvars_sub {o} :\n  forall (sub : @Sub o),\n    allvars_sub sub\n    -> get_utokens_sub sub = [].\nProof.\n  induction sub; introv av; allsimpl; tcsp.\n  destruct a.\n  allrw @allvars_sub_cons; repnd.\n  apply isvariable_implies in av0; exrepnd; subst.\n  unfold get_utokens_sub; simpl; sp.\nQed.\n\nLemma get_utokens_sub_var_ren {o} :\n  forall vs1 vs2,\n    @get_utokens_sub o (var_ren vs1 vs2) = [].\nProof.\n  introv; apply get_utokens_sub_allvars_sub; eauto with slow.\nQed.\n\nLemma allvars_sub_sub_keep_first {o} :\n  forall (sub : @Sub o) vs,\n    allvars_sub sub\n    -> allvars_sub (sub_keep_first sub vs).\nProof.\n  induction sub; introv av; allsimpl; tcsp.\n  destruct a; allrw @allvars_sub_cons; repnd.\n  boolvar; tcsp.\n  rw @allvars_sub_cons; dands; auto.\nQed.\nHint Resolve allvars_sub_sub_keep_first : slow.\n\nLemma lsubst_sub_trivial {o} :\n  forall (sub1 sub2 : @Sub o),\n    cl_sub sub2\n    -> disjoint (sub_free_vars sub1) (dom_sub sub2)\n    -> lsubst_sub sub1 sub2 = sub1.\nProof.\n  induction sub1; introv cl d; allsimpl; auto.\n  destruct a.\n  allrw disjoint_app_l; repnd.\n  f_equal; tcsp.\n  rw @cl_lsubst_trivial; eauto with slow.\nQed.\n\nLemma simple_alphaeq_subst_utokens_aux_lsubst_aux {o} :\n  forall (t' t : @NTerm o) v a,\n    !LIn a (get_utokens t)\n    -> !LIn v (bound_vars t')\n    -> alpha_eq (lsubst_aux t [(v, mk_utoken a)]) t'\n    -> alpha_eq (subst_utokens_aux t' [(a, mk_var v)]) t.\nProof.\n  nterm_ind1s t' as [v|f ind|op bs ind] Case; introv ni1 ni2 aeq; auto.\n\n  - Case \"vterm\".\n    allsimpl; GC.\n    destruct t as [v1|f1 ind|op1 bs1]; allsimpl; boolvar; allsimpl; GC;\n    inversion aeq; subst; auto.\n\n  - Case \"sterm\".\n    allsimpl; GC.\n    destruct t as [v1|f1|op1 bs1]; allsimpl; boolvar; allsimpl; GC;\n    try (complete (inversion aeq; subst; auto)).\n    apply alpha_eq_sym; auto.\n\n  - Case \"oterm\".\n    rw @subst_utokens_aux_oterm.\n    destruct t as [v1|f1|op1 bs1]; allsimpl; boolvar; GC;\n    try (complete (inversion aeq)).\n\n    + inversion aeq; subst; allsimpl; cpx; allsimpl; fold_terms; GC.\n      unfold subst_utok; simpl; boolvar; tcsp.\n\n    + allrw in_app_iff; allrw not_over_or; repnd.\n      rw @alpha_eq_oterm_combine2 in aeq; repnd; subst.\n      allrw map_length.\n      remember (get_utok op) as guo; symmetry in Heqguo; destruct guo.\n\n      * apply get_utok_some in Heqguo; subst; allsimpl; allrw not_over_or; repnd; GC.\n        unfold subst_utok; simpl; boolvar; subst; tcsp.\n        apply alpha_eq_oterm_combine; allrw map_length; dands; auto.\n        introv i.\n        rw <- map_combine_left in i.\n        rw in_map_iff in i; exrepnd; cpx; allsimpl.\n        destruct a1 as [l1 t1].\n        destruct a0 as [l2 t2]; allsimpl.\n\n        pose proof (aeq (lsubst_bterm_aux (bterm l2 t2) [(v,mk_utoken a)]) (bterm l1 t1)) as h.\n        autodimp h hyp.\n        { rw <- map_combine_left.\n          rw in_map_iff.\n          apply in_combine_swap in i1; auto.\n          eexists; dands; eauto. }\n\n        allsimpl.\n        applydup in_combine in i1; repnd.\n        apply alphaeq_bterm3_if\n        with (lva := v\n                       :: all_vars (subst_utokens_aux t1 [(a, mk_var v)])\n                       ++ all_vars t2\n                       ++ bound_vars (lsubst t2 [(v, mk_utoken a)])\n             )\n          in h.\n\n        inversion h as [? ? ? ? ? disj len1 len2 norep al]; subst; clear h.\n        allrw disjoint_app_r; allrw disjoint_cons_r; allrw disjoint_app_r; repnd.\n\n        apply (al_bterm _ _ lv); allrw disjoint_app_r; dands; try omega; eauto with slow.\n\n        assert (!LIn v l1) as ni.\n        { intro k; destruct ni2.\n          rw lin_flat_map; eexists; dands; eauto.\n          simpl; rw in_app_iff; sp. }\n\n        rw @lsubst_subst_utokens_aux_disj; simpl;\n        allrw @dom_sub_var_ren;\n        allrw @sub_free_vars_var_ren;\n        allrw @get_utokens_sub_var_ren;\n        allrw disjoint_singleton_l;\n        try omega; eauto with slow.\n\n        pose proof (ind t1 (lsubst t1 (var_ren l1 lv)) l1) as h; clear ind.\n        repeat (autodimp h hyp).\n        { rw @lsubst_allvars_preserves_osize2; eauto 3 with slow. }\n        pose proof (h (lsubst t2 (var_ren l2 lv)) v a) as k; clear h.\n        repeat (autodimp k hyp).\n\n        { intro k.\n          apply get_utokens_lsubst in k.\n          rw @get_utokens_sub_allvars_sub in k; eauto with slow.\n          allrw in_app_iff; allsimpl; repndors; tcsp.\n          destruct ni1; rw lin_flat_map; eexists; dands; eauto. }\n\n        { rw @boundvars_lsubst_vars; auto; try omega.\n          intro k; destruct ni2; rw lin_flat_map; eexists; dands; eauto; simpl.\n          rw in_app_iff; sp. }\n\n        { apply alpha_eq_if3 in al.\n          boolvar.\n\n          - allrw @lsubst_aux_nil.\n            pose proof (simple_lsubst_lsubst_sub_aeq3\n                          t2 (var_ren l2 lv) [(v, mk_utoken a)]) as h.\n            repeat (autodimp h hyp); simpl; eauto 2 with slow.\n            allsimpl; rw @dom_sub_var_ren in h; auto; boolvar; tcsp.\n            allrw @lsubst_nil.\n            repeat (rw <- @lsubst_lsubst_aux2 in al; try omega; eauto 2 with slow).\n            rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow.\n            rw @lsubst_sub_trivial in h; simpl;\n            try (rw @sub_free_vars_var_ren); try (rw disjoint_singleton_r);\n            eauto with slow.\n\n          - rw <- (lsubst_lsubst_aux2 t1) in al; try omega; eauto 2 with slow.\n            eapply alpha_eq_trans;[|exact al].\n            rw <- (cl_lsubst_lsubst_aux t2); eauto 2 with slow.\n            rw <- (cl_lsubst_lsubst_aux (lsubst t2 (var_ren l2 lv))); eauto 2 with slow.\n            pose proof (simple_lsubst_lsubst_sub_aeq3\n                          t2 (var_ren l2 lv) [(v, mk_utoken a)]) as h.\n            repeat (autodimp h hyp); simpl; eauto 2 with slow.\n            allsimpl; rw @dom_sub_var_ren in h; auto; boolvar; tcsp.\n            eapply alpha_eq_trans;[apply alpha_eq_sym; apply h|].\n            rw @lsubst_sub_trivial; simpl;\n            try (rw @sub_free_vars_var_ren); try (rw disjoint_singleton_r);\n            eauto 2 with slow.\n            rw <- @lsubst_lsubst_aux2; try omega; eauto 2 with slow.\n        }\n\n      * apply alpha_eq_oterm_combine; allrw map_length; dands; auto.\n        introv i.\n        rw <- map_combine_left in i.\n        rw in_map_iff in i; exrepnd; cpx; allsimpl.\n        destruct a1 as [l1 t1].\n        destruct a0 as [l2 t2]; allsimpl.\n\n        pose proof (aeq (lsubst_bterm_aux (bterm l2 t2) [(v,mk_utoken a)]) (bterm l1 t1)) as h.\n        autodimp h hyp.\n        { rw <- map_combine_left.\n          rw in_map_iff.\n          apply in_combine_swap in i1; auto.\n          eexists; dands; eauto. }\n\n        allsimpl.\n        applydup in_combine in i1; repnd.\n        apply alphaeq_bterm3_if\n        with (lva := v\n                       :: all_vars (subst_utokens_aux t1 [(a, mk_var v)])\n                       ++ all_vars t2\n                       ++ bound_vars (lsubst t2 [(v, mk_utoken a)])\n             )\n          in h.\n\n        inversion h as [? ? ? ? ? disj len1 len2 norep al]; subst; clear h.\n        allrw disjoint_app_r; allrw disjoint_cons_r; allrw disjoint_app_r; repnd.\n\n        apply (al_bterm _ _ lv); allrw disjoint_app_r; dands; try omega; eauto with slow.\n\n        assert (!LIn v l1) as ni.\n        { intro k; destruct ni2.\n          rw lin_flat_map; eexists; dands; eauto.\n          simpl; rw in_app_iff; sp. }\n\n        rw @lsubst_subst_utokens_aux_disj; simpl;\n        allrw @dom_sub_var_ren;\n        allrw @sub_free_vars_var_ren;\n        allrw @get_utokens_sub_var_ren;\n        allrw disjoint_singleton_l;\n        try omega; eauto with slow.\n\n        pose proof (ind t1 (lsubst t1 (var_ren l1 lv)) l1) as h; clear ind.\n        repeat (autodimp h hyp).\n        { rw @lsubst_allvars_preserves_osize2; eauto 3 with slow. }\n        pose proof (h (lsubst t2 (var_ren l2 lv)) v a) as k; clear h.\n        repeat (autodimp k hyp).\n\n        { intro k.\n          apply get_utokens_lsubst in k.\n          rw @get_utokens_sub_allvars_sub in k; eauto with slow.\n          allrw in_app_iff; allsimpl; repndors; tcsp.\n          destruct ni1; rw lin_flat_map; eexists; dands; eauto. }\n\n        { rw @boundvars_lsubst_vars; auto; try omega.\n          intro k; destruct ni2; rw lin_flat_map; eexists; dands; eauto; simpl.\n          rw in_app_iff; sp. }\n\n        { apply alpha_eq_if3 in al.\n          boolvar.\n\n          - allrw @lsubst_aux_nil.\n            pose proof (simple_lsubst_lsubst_sub_aeq3\n                          t2 (var_ren l2 lv) [(v, mk_utoken a)]) as h.\n            repeat (autodimp h hyp); simpl; eauto 2 with slow.\n            allsimpl; rw @dom_sub_var_ren in h; auto; boolvar; tcsp.\n            allrw @lsubst_nil.\n            repeat (rw <- @lsubst_lsubst_aux2 in al; try omega; eauto 2 with slow).\n            rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow.\n            rw @lsubst_sub_trivial in h; simpl;\n            try (rw @sub_free_vars_var_ren); try (rw disjoint_singleton_r);\n            eauto with slow.\n\n          - rw <- (lsubst_lsubst_aux2 t1) in al; try omega; eauto 2 with slow.\n            eapply alpha_eq_trans;[|exact al].\n            rw <- (cl_lsubst_lsubst_aux t2); eauto 2 with slow.\n            rw <- (cl_lsubst_lsubst_aux (lsubst t2 (var_ren l2 lv))); eauto 2 with slow.\n            pose proof (simple_lsubst_lsubst_sub_aeq3\n                          t2 (var_ren l2 lv) [(v, mk_utoken a)]) as h.\n            repeat (autodimp h hyp); simpl; eauto 2 with slow.\n            allsimpl; rw @dom_sub_var_ren in h; auto; boolvar; tcsp.\n            eapply alpha_eq_trans;[apply alpha_eq_sym; apply h|].\n            rw @lsubst_sub_trivial; simpl;\n            try (rw @sub_free_vars_var_ren); try (rw disjoint_singleton_r);\n            eauto 2 with slow.\n            rw <- @lsubst_lsubst_aux2; try omega; eauto 2 with slow.\n        }\nQed.\n\nLemma simple_alphaeq_subst_utokens_subst {o} :\n  forall (t : @NTerm o) v a,\n    !LIn a (get_utokens t)\n    -> alpha_eq (subst_utokens (subst t v (mk_utoken a)) [(a, mk_var v)]) t.\nProof.\n  introv ni.\n  unfsubst.\n  pose proof (unfold_subst_utokens [(a,mk_var v)] (lsubst_aux t [(v,mk_utoken a)])) as h.\n  exrepnd; rw h0; allsimpl; allrw disjoint_singleton_r.\n  apply simple_alphaeq_subst_utokens_aux_lsubst_aux; auto.\nQed.\n\nLemma cl_subst_swap {o} :\n  forall (t : @NTerm o) v1 v2 u1 u2,\n    closed u1\n    -> closed u2\n    -> v1 <> v2\n    -> subst (subst t v1 u1) v2 u2 = subst (subst t v2 u2) v1 u1.\nProof.\n  introv cl1 cl2 d.\n  unfold subst.\n  apply substitution3.cl_lsubst_swap; simpl; eauto with slow.\nQed.\n\nDefinition is_utok {o} (t : @NTerm o) :=\n  match t with\n    | oterm (Can (NUTok _)) [] => True\n    | _ => False\n  end.\n\nLemma is_utok_implies {o} :\n  forall t : @NTerm o,\n    is_utok t -> {a : get_patom_set o & t = mk_utoken a}.\nProof.\n  introv i.\n  destruct t as [v|f|op bs]; allsimpl; tcsp.\n  destruct op as [c|nc|e|a]; allsimpl; tcsp.\n  destruct c; allsimpl; tcsp.\n  destruct bs; allsimpl; tcsp.\n  exists g; sp.\nQed.\n\n(*\nInductive nr_ut_sub {o} : @Sub o -> Type :=\n| nr_ut_sub_nil : nr_ut_sub []\n| nr_ut_sub_cons :\n    forall v a s,\n      !LIn a (get_utokens_sub s)\n      -> nr_ut_sub s\n      -> nr_ut_sub ((v,mk_utoken a) :: s).\n*)\n\nInductive nr_ut_sub {o} : @NTerm o -> @Sub o -> Type :=\n| nr_ut_sub_nil : forall t, nr_ut_sub t []\n| nr_ut_sub_cons :\n    forall v a s t,\n      (LIn v (free_vars t) -> !LIn a (get_utokens t))\n      -> nr_ut_sub (subst t v (mk_utoken a)) s\n      -> nr_ut_sub t ((v,mk_utoken a) :: s).\nHint Constructors nr_ut_sub.\n\nLemma nr_ut_sub_cons_iff {o} :\n  forall v t (s : @Sub o) u,\n    nr_ut_sub u ((v,t) :: s)\n    <=> {a : get_patom_set o\n         & t = mk_utoken a\n         # (LIn v (free_vars u) -> !LIn a (get_utokens u))\n         # nr_ut_sub (subst u v (mk_utoken a)) s}.\nProof.\n  introv; split; intro k; exrepnd; subst; auto.\n  inversion k; subst; eexists; dands; eauto.\nQed.\n\nLemma cl_nr_ut_sub {o} :\n  forall (sub : @Sub o) u,\n    nr_ut_sub u sub\n    -> cl_sub sub.\nProof.\n  induction sub; introv nrut; eauto with slow.\n  destruct a; allrw @cl_sub_cons.\n  apply nr_ut_sub_cons_iff in nrut; exrepnd; subst.\n  dands; eauto with slow.\nQed.\nHint Resolve cl_nr_ut_sub : slow.\n\nLemma in_nr_ut_sub {o} :\n  forall (s : @Sub o) v t u,\n    LIn (v,t) s\n    -> nr_ut_sub u s\n    -> {a : get_patom_set o & t = mk_utoken a}.\nProof.\n  induction s; introv i nr; allsimpl; tcsp.\n  destruct a; allrw @nr_ut_sub_cons_iff; exrepnd.\n  repndors; cpx; subst; tcsp.\n  - eexists; dands; eauto.\n  - eapply IHs; eauto.\nQed.\n\nLemma sub_find_some_eq_doms_nr_ut_sub {o} :\n  forall (sub1 sub2 : @Sub o) v u,\n    nr_ut_sub u sub2\n    -> dom_sub sub1 = dom_sub sub2\n    -> match sub_find sub1 v with\n         | Some _ => {a : get_patom_set o & sub_find sub2 v = Some (mk_utoken a)}\n         | None => sub_find sub2 v = None\n       end.\nProof.\n  induction sub1; destruct sub2; introv nr eqdoms; allsimpl; tcsp.\n  destruct a, p; allsimpl; cpx.\n  allrw @nr_ut_sub_cons_iff; exrepnd; subst.\n  boolvar; allsimpl; tcsp.\n  - eexists; dands; eauto.\n  - pose proof (IHsub1 sub2 v (subst u n1 (mk_utoken a))) as h; sp.\nQed.\n\nLemma lsubst_aux_utoken_eq_utoken_implies_or {o} :\n  forall (t : @NTerm o) a sub,\n    lsubst_aux t sub = mk_utoken a\n    -> ({v : NVar & sub_find sub v = Some (mk_utoken a) # t = mk_var v}\n        [+] t = mk_utoken a).\nProof.\n  destruct t as [v|f|op bs ind]; introv e; allsimpl; GC; ginv.\n  - remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; subst; ginv.\n    left; exists v; auto.\n  - inversion e; subst.\n    destruct bs; allsimpl; cpx.\nQed.\n\nLemma lsubst_aux_pk2term_eq_utoken_implies_or {o} :\n  forall (t : @NTerm o) pk sub,\n    lsubst_aux t sub = pk2term pk\n    -> ({v : NVar & sub_find sub v = Some (pk2term pk) # t = mk_var v}\n        [+] t = pk2term pk).\nProof.\n  destruct t as [v|f|op bs ind]; introv e; allsimpl; GC; ginv.\n  - remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; subst; ginv.\n    left; exists v; auto.\n  - allrw @pk2term_eq; inversion e; subst.\n    destruct bs; allsimpl; cpx; GC.\nQed.\n\nLemma nr_ut_sub_in_false {o} :\n  forall (sub : @Sub o) v a u,\n    nr_ut_sub u sub\n    -> sub_find sub v = Some (mk_utoken a)\n    -> LIn a (get_utokens u)\n    -> LIn v (free_vars u)\n    -> False.\nProof.\n  induction sub; introv nr sf ia iv; allsimpl; ginv.\n  destruct a; allsimpl.\n  allrw @nr_ut_sub_cons_iff; exrepnd; subst.\n  boolvar; tcsp.\n  - autodimp nr2 hyp; ginv; tcsp.\n  - pose proof (IHsub v a0 (subst u n (mk_utoken a))) as h.\n    repeat (autodimp h hyp).\n    + apply get_utokens_subst; rw in_app_iff; sp.\n    + pose proof (eqvars_free_vars_disjoint u [(n,mk_utoken a)]) as h.\n      rw eqvars_prop in h; apply h; clear h; simpl.\n      rw in_app_iff; left.\n      rw in_remove_nvars; simpl; sp.\nQed.\n\nLemma nr_ut_sub_some_eq {o} :\n  forall (sub : @Sub o) v1 v2 a u,\n    nr_ut_sub u sub\n    -> sub_find sub v1 = Some (mk_utoken a)\n    -> sub_find sub v2 = Some (mk_utoken a)\n    -> LIn v1 (free_vars u)\n    -> LIn v2 (free_vars u)\n    -> v1 = v2.\nProof.\n  induction sub; introv nrut sf1 sf2 i1 i2; allsimpl; tcsp.\n  destruct a.\n  allrw @nr_ut_sub_cons_iff; exrepnd; subst; allsimpl.\n  boolvar; ginv; tcsp; GC.\n\n  - provefalse.\n    autodimp nrut2 hyp.\n    eapply nr_ut_sub_in_false in nrut0; eauto.\n    + apply get_utokens_subst; rw in_app_iff; boolvar; tcsp.\n    + pose proof (eqvars_free_vars_disjoint u [(v1,mk_utoken a0)]) as h.\n      rw eqvars_prop in h; apply h; clear h; simpl.\n      rw in_app_iff; left.\n      rw in_remove_nvars; simpl; sp.\n\n  - provefalse.\n    autodimp nrut2 hyp.\n    eapply nr_ut_sub_in_false in nrut0; eauto.\n    + apply get_utokens_subst; rw in_app_iff; boolvar; tcsp.\n    + pose proof (eqvars_free_vars_disjoint u [(v2,mk_utoken a0)]) as h.\n      rw eqvars_prop in h; apply h; clear h; simpl.\n      rw in_app_iff; left.\n      rw in_remove_nvars; simpl; sp.\n\n  - eapply IHsub; eauto.\n    + pose proof (eqvars_free_vars_disjoint u [(n,mk_utoken a)]) as h.\n      rw eqvars_prop in h; apply h; clear h; simpl.\n      rw in_app_iff; left.\n      rw in_remove_nvars; simpl; sp.\n    + pose proof (eqvars_free_vars_disjoint u [(n,mk_utoken a)]) as h.\n      rw eqvars_prop in h; apply h; clear h; simpl.\n      rw in_app_iff; left.\n      rw in_remove_nvars; simpl; sp.\nQed.\n\n\nLemma nr_ut_sub_some_diff2 {o} :\n  forall (sub : @Sub o) v1 v2 a1 a2 u,\n    nr_ut_sub u sub\n    -> sub_find sub v1 = Some (mk_utoken a1)\n    -> sub_find sub v2 = Some (mk_utoken a2)\n    -> LIn v1 (free_vars u)\n    -> LIn v2 (free_vars u)\n    -> v1 <> v2\n    -> a1 <> a2.\nProof.\n  introv nrut e1 e2 i1 i2 d e; subst.\n  pose proof (nr_ut_sub_some_eq sub v1 v2 a2 u); sp.\nQed.\n\nLemma nr_ut_sub_some_diff {o} :\n  forall (sub : @Sub o) v1 v2 a1 a2 u,\n    nr_ut_sub u sub\n    -> sub_find sub v1 = Some (mk_utoken a1)\n    -> sub_find sub v2 = Some (mk_utoken a2)\n    -> a1 <> a2\n    -> v1 <> v2.\nProof.\n  induction sub; introv nrut e1 e2 d; allsimpl; tcsp.\n  destruct a; allsimpl.\n  allrw @nr_ut_sub_cons_iff; exrepnd; subst.\n  boolvar; tcsp; ginv; tcsp.\n  eapply IHsub; eauto.\nQed.\n\nLemma isnoncan_like_lsubst_aux_nr_ut_implies {o} :\n  forall (t : @NTerm o) sub u,\n    nr_ut_sub u sub\n    -> isnoncan_like (lsubst_aux t sub)\n    -> isnoncan_like t.\nProof.\n  introv nrut isn.\n  destruct t as [v|f|op bs]; allsimpl; tcsp.\n  remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; tcsp.\n  apply sub_find_some in Heqsf.\n  eapply in_nr_ut_sub in Heqsf; eauto.\n  exrepnd; subst; inversion isn; sp.\nQed.\n\nLemma lsubst_sub_nr_ut_sub {o} :\n  forall (sub1 sub2 : @Sub o) u,\n    nr_ut_sub u sub1\n    -> lsubst_sub sub1 sub2 = sub1.\nProof.\n  induction sub1; introv nrut; allsimpl; auto.\n  destruct a.\n  allrw @nr_ut_sub_cons_iff; exrepnd; subst.\n  erewrite IHsub1; eauto.\nQed.\n\n(*\nLemma nr_ut_sub_sub_filter {o} :\n  forall (sub : @Sub o) vs u,\n    nr_ut_sub u sub\n    -> nr_ut_sub u (sub_filter sub vs).\nProof.\n  induction sub; introv nrut; allsimpl; auto.\n  destruct a.\n  allrw @nr_ut_sub_cons_iff; exrepnd; subst.\n  boolvar; tcsp.\n  apply IHsub.\n  apply nr_ut_sub_cons_iff; eexists; dands; eauto.\n  intro k; apply get_utokens_sub_filter_subset in k; sp.\nQed.\nHint Resolve nr_ut_sub_sub_filter : slow.\n*)\n\nLemma isexc_lsubst_aux_nr_ut_sub {o} :\n  forall (t : @NTerm o) sub u,\n    nr_ut_sub u sub\n    -> isexc (lsubst_aux t sub)\n    -> isexc t.\nProof.\n  destruct t as [v|f|op bs]; introv nrut ise; allsimpl; tcsp.\n  remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; allsimpl; tcsp.\n  apply sub_find_some in Heqsf.\n  eapply in_nr_ut_sub in Heqsf; eauto; exrepnd; subst; allsimpl; tcsp.\nQed.\n\nLemma isvalue_like_lsubst_aux_implies {o} :\n  forall (t : @NTerm o) sub,\n    isvalue_like (lsubst_aux t sub)\n    -> (isvalue_like t\n        [+] {u : NTerm\n             & {v : NVar\n             & sub_find sub v = Some u\n             # t = mk_var v\n             # isvalue_like u}}).\nProof.\n  introv isv.\n  destruct t as [v|f|op bs]; allsimpl; tcsp.\n  remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf.\n  + right.\n    exists n v; sp.\n  + unfold isvalue_like in isv; allsimpl; sp.\nQed.\n\nLemma simple_size_lsubst {o} :\n  forall (t : @NTerm o) sub,\n    shallow_sub sub\n    -> size (lsubst t sub) = size t.\nProof.\n  introv sh.\n  pose proof (unfold_lsubst sub t) as h; exrepnd; rw h0.\n  rw @simple_size_lsubst_aux; auto.\n  apply alpha_eq_preserves_size; eauto with slow.\nQed.\n\nLemma shallow_sub_app {o} :\n  forall (sub1 sub2 : @Sub o),\n    shallow_sub sub1\n    -> shallow_sub sub2\n    -> shallow_sub (sub1 ++ sub2).\nProof.\n  introv.\n  unfold shallow_sub.\n  introv h1 h2 i.\n  allrw @range_app; allrw in_app_iff; repndors; tcsp.\nQed.\nHint Resolve shallow_sub_app : slow.\n\nLemma shallow_sub_nil {o} :\n  @shallow_sub o [].\nProof.\n  unfold shallow_sub; simpl; sp.\nQed.\nHint Resolve shallow_sub_nil : slow.\n\nLemma shallow_sub_cons {o} :\n  forall v t (sub : @Sub o),\n    shallow_sub ((v,t) :: sub)\n    <=> (size t = 1 # shallow_sub sub).\nProof.\n  introv; split; introv k; repnd.\n  - unfold shallow_sub in k; allsimpl.\n    pose proof (k t) as h; autodimp h hyp; dands; auto.\n    introv j; eapply k; eauto.\n  - introv i; allsimpl; repndors; subst; tcsp.\nQed.\n\nLemma implies_shallow_sub_cons {o} :\n  forall v t (sub : @Sub o),\n    size t = 1\n    -> shallow_sub sub\n    -> shallow_sub ((v,t) :: sub).\nProof.\n  introv e s.\n  rw @shallow_sub_cons; sp.\nQed.\nHint Resolve implies_shallow_sub_cons : slow.\n\nLemma nr_ut_sub_is_shallow {o} :\n  forall (sub : @Sub o) u,\n    nr_ut_sub u sub\n    -> shallow_sub sub.\nProof.\n  induction sub; introv nrut; eauto with slow.\n  destruct a.\n  rw @nr_ut_sub_cons_iff in nrut; exrepnd; subst.\n  eauto with slow.\nQed.\nHint Resolve nr_ut_sub_is_shallow : slow.\n\nLemma lsubst_sub_shallow_cl_sub {o} :\n  forall (sub1 sub2 : @Sub o),\n    cl_sub sub1\n    -> shallow_sub sub1\n    -> lsubst_sub sub1 sub2 = sub1.\nProof.\n  induction sub1; introv cl sh; allsimpl; auto.\n  destruct a.\n  allrw @cl_sub_cons; exrepnd; subst.\n  allrw @shallow_sub_cons; repnd.\n  erewrite IHsub1; eauto; f_equal; f_equal.\n  destruct n0 as [v|f|op bs]; tcsp; allsimpl; cpx.\n  - unfold closed in cl0; allsimpl; ginv.\n  - assert (bs = []); subst.\n    { destruct bs; allsimpl; cpx.\n      destruct b as [l t]; allsimpl.\n      destruct t; allsimpl; cpx. }\n    unfold lsubst; simpl; auto.\nQed.\n\nLemma get_utokens_sub_nil {o} :\n  @get_utokens_sub o [] = [].\nProof. sp. Qed.\nHint Rewrite @get_utokens_sub_nil : slow.\n\nLemma get_utokens_sub_cons {o} :\n  forall v t (sub : @Sub o),\n    get_utokens_sub ((v,t) :: sub)\n    = get_utokens t ++ get_utokens_sub sub.\nProof. sp. Qed.\n\nLemma get_utokens_sub_app {o} :\n  forall (sub1 sub2 : @Sub o),\n    get_utokens_sub (sub1 ++ sub2)\n    = get_utokens_sub sub1 ++ get_utokens_sub sub2.\nProof.\n  induction sub1; introv; allsimpl; auto.\n  destruct a; allsimpl.\n  allrw @get_utokens_sub_cons; rw IHsub1.\n  rw app_assoc; auto.\nQed.\n\n(*\nLemma implies_nr_ut_sub_app {o} :\n  forall (sub1 sub2 : @Sub o),\n    disjoint (get_utokens_sub sub1) (get_utokens_sub sub2)\n    -> nr_ut_sub sub1\n    -> nr_ut_sub sub2\n    -> nr_ut_sub (sub1 ++ sub2).\nProof.\n  induction sub1; introv d n1 n2; allsimpl; eauto with slow.\n  destruct a; allsimpl.\n  allrw @nr_ut_sub_cons_iff; exrepnd; subst; allsimpl.\n  exists a; dands; tcsp.\n  - intro i.\n    rw @get_utokens_sub_app in i; allrw in_app_iff.\n    allrw @get_utokens_sub_cons; allsimpl; allrw disjoint_cons_l; repnd.\n    repndors; tcsp.\n  - allrw @get_utokens_sub_cons; allsimpl; allrw disjoint_cons_l; repnd.\n    apply IHsub1; auto.\nQed.\nHint Resolve implies_nr_ut_sub_app : slow.\n*)\n\nLemma subset_eqset_l :\n  forall (T : tuniv) (s1 s2 s3 : list T),\n    eqset s1 s2 -> subset s1 s3 -> subset s2 s3.\nProof.\n  introv eqs ss i; apply eqset_sym in eqs; apply eqs in i; apply ss in i; auto.\nQed.\n\nLemma nr_ut_sub_change_term {o} :\n  forall sub (t u : @NTerm o),\n    subvars (free_vars t) (free_vars u)\n    -> subset (get_utokens t) (get_utokens u)\n    -> nr_ut_sub u sub\n    -> nr_ut_sub t sub.\nProof.\n  induction sub; introv sv ss nrut; tcsp.\n  destruct a; allrw @nr_ut_sub_cons_iff; exrepnd; subst.\n  exists a; dands; auto.\n  - intro i.\n    rw subvars_prop in sv; apply sv in i; apply nrut2 in i.\n    intro k; apply ss in k; sp.\n  - apply (IHsub _ (subst u n (mk_utoken a))); auto.\n    + repeat unfsubst; repeat (rw @free_vars_lsubst_aux_cl; eauto with slow); simpl.\n      apply subars_remove_nvars_lr; auto.\n    + eapply subset_eqset_r;[apply eqset_sym; apply get_utokens_subst|].\n      eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_subst|].\n      boolvar; allsimpl; allrw app_nil_r; tcsp; eauto with slow.\n      rw subvars_prop in sv; apply sv in Heqb; sp.\nQed.\nHint Resolve nr_ut_sub_change_term : slow.\n\nLemma shallow_sub_sub_filter {o} :\n  forall (sub : @Sub o) vs,\n    shallow_sub sub\n    -> shallow_sub (sub_filter sub vs).\nProof.\n  induction sub; introv sh; allsimpl; tcsp.\n  destruct a; allrw @shallow_sub_cons; repnd.\n  boolvar; tcsp.\n  apply shallow_sub_cons; sp.\nQed.\nHint Resolve shallow_sub_sub_filter : slow.\n\nLemma in_cl_sub {o} :\n  forall (sub : @Sub o) v t,\n  cl_sub sub\n  -> LIn (v, t) sub\n  -> closed t.\nProof.\n  introv cl i.\n  rw @cl_sub_eq2 in cl; eapply cl; eauto.\nQed.\n\nLemma nr_ut_sub_sub_filter_disj {o} :\n  forall (sub : @Sub o) vs u,\n    disjoint vs (free_vars u)\n    -> nr_ut_sub u sub\n    -> nr_ut_sub u (sub_filter sub vs).\nProof.\n  induction sub; introv d nrut; allsimpl; auto.\n  destruct a.\n  allrw @nr_ut_sub_cons_iff; exrepnd; subst.\n  boolvar; tcsp.\n  - apply IHsub; auto.\n    rw @cl_subst_trivial in nrut0; eauto with slow.\n  - apply nr_ut_sub_cons_iff; eexists; dands; eauto.\n    apply IHsub; auto.\n    unfsubst.\n    rw @free_vars_lsubst_aux_cl; eauto with slow.\nQed.\nHint Resolve nr_ut_sub_sub_filter_disj : slow.\n\nLemma implies_nr_ut_sub_app {o} :\n  forall (sub1 sub2 : @Sub o) t,\n    nr_ut_sub t sub1\n    -> nr_ut_sub (lsubst t sub1) sub2\n    -> nr_ut_sub t (sub1 ++ sub2).\nProof.\n  induction sub1; introv n1 n2; allsimpl; eauto with slow.\n  - allrw @lsubst_nil; auto.\n  - destruct a; allsimpl.\n    allrw @nr_ut_sub_cons_iff; exrepnd; subst; allsimpl.\n    exists a; dands; tcsp.\n    apply IHsub1; auto.\n    unfold subst.\n    rw <- @cl_lsubst_app; eauto with slow.\nQed.\nHint Resolve implies_nr_ut_sub_app : slow.\n\nLemma nr_ut_sub_sub_filter_change_term_disj {o} :\n  forall sub (t u : @NTerm o) vs,\n    disjoint vs (free_vars u)\n    -> subvars (free_vars t) (free_vars u ++ vs)\n    -> subset (get_utokens t) (get_utokens u)\n    -> nr_ut_sub u sub\n    -> nr_ut_sub t (sub_filter sub vs).\nProof.\n  induction sub; introv d sv ss nrut; tcsp.\n  destruct a; allsimpl.\n  allrw @nr_ut_sub_cons_iff; exrepnd; subst.\n  boolvar.\n  - eapply IHsub; eauto.\n    apply d in Heqb.\n    unfsubst in nrut0.\n    rw @lsubst_aux_trivial_cl_term in nrut0; simpl; eauto with slow.\n    apply disjoint_singleton_r; auto.\n  - rw @nr_ut_sub_cons_iff; exists a; dands; eauto with slow.\n    + intro i.\n      rw subvars_prop in sv; apply sv in i; tcsp.\n      allrw in_app_iff; repndors; tcsp.\n    + apply (IHsub _ (subst u n (mk_utoken a))); auto.\n      * repeat unfsubst; repeat (rw @free_vars_lsubst_aux_cl; eauto with slow); simpl.\n      * repeat unfsubst; repeat (rw @free_vars_lsubst_aux_cl; eauto with slow); simpl.\n        allrw subvars_prop; introv i; allrw in_remove_nvars; allsimpl; allrw not_over_or; repnd.\n        apply sv in i0; allrw in_app_iff; allrw in_remove_nvars; allsimpl; repndors; tcsp.\n        left; sp.\n      * eapply subset_eqset_r;[apply eqset_sym; apply get_utokens_subst|].\n        eapply subset_eqset_l;[apply eqset_sym; apply get_utokens_subst|].\n        boolvar; allsimpl; allrw app_nil_r; tcsp; eauto with slow.\n        provefalse.\n        rw subvars_prop in sv; apply sv in Heqb0; sp.\n        allrw in_app_iff; sp.\nQed.\n\nLemma get_utokens_sub_sub_keep_first {o} :\n  forall (sub : @Sub o) l,\n    subset (get_utokens_sub (sub_keep_first sub l)) (get_utokens_sub sub).\nProof.\n  unfold get_utokens_sub; introv i.\n  allrw lin_flat_map; exrepnd.\n  exists x0; dands; auto.\n  allrw @in_range_iff; exrepnd.\n  allrw @in_sub_keep_first; repnd.\n  apply sub_find_some in i1; eexists; eauto.\nQed.\n\nLemma implies_subvars_cons_l :\n  forall (v : NVar) (vs1 vs2 : list NVar),\n    LIn v vs2\n    -> subvars vs1 vs2\n    -> subvars (v :: vs1) vs2.\nProof.\n  introv i sv.\n  rw subvars_cons_l; dands; auto.\nQed.\nHint Resolve implies_subvars_cons_l : slow.\n\nLemma in_get_utokens_sub {o} :\n  forall (sub : @Sub o) a,\n    LIn a (get_utokens_sub sub)\n    <=> {v : NVar & {t : NTerm & LIn (v,t) sub # LIn a (get_utokens t)}}.\nProof.\n  induction sub; introv.\n  - rw @get_utokens_sub_nil; simpl; split; introv k; tcsp.\n  - destruct a; rw @get_utokens_sub_cons; rw in_app_iff; simpl.\n    rw IHsub; clear IHsub; split; intro k; repndors; exrepnd; subst.\n    + exists n n0; tcsp.\n    + exists v t; tcsp.\n    + repndors; cpx; tcsp.\n      right; exists v t; tcsp.\nQed.\n\nLemma alpha_eq_option_refl {o} :\n  forall (op : option (@NTerm o)),\n    alpha_eq_option op op.\nProof.\n  introv.\n  destruct op; simpl; auto.\nQed.\nHint Resolve alpha_eq_option_refl : slow.\n\nLemma cl_lsubst_pushdown_fresh {o} :\n  forall (t : @NTerm o) v sub,\n    cl_sub sub\n    -> isvalue_like t\n    -> alpha_eq\n         (lsubst (pushdown_fresh v t) sub)\n         (pushdown_fresh v (lsubst t (sub_filter sub [v]))).\nProof.\n  introv cl isv.\n  repeat unflsubst.\n  destruct t as [x|f|op bs]; simpl; tcsp.\n\n  - unfold isvalue_like in isv; allsimpl; sp.\n\n  - f_equal.\n    unfold mk_fresh_bterms.\n    allrw map_map; unfold compose.\n    apply alpha_eq_oterm_combine; allrw map_length; dands; auto.\n    introv i.\n    rw <- @map_combine in i.\n    rw in_map_iff in i; exrepnd; cpx.\n    apply in_combine_same in i1; repnd; subst.\n    destruct a as [l t]; simpl; fold_terms.\n    unfold maybe_new_var; boolvar.\n\n    + apply alpha_eq_bterm_congr.\n\n      pose proof (ex_fresh_var\n                    (all_vars (lsubst_aux t (sub_filter (sub_filter sub l) [newvar t]))\n                              ++ all_vars (lsubst_aux t (sub_filter (sub_filter sub [v]) l)))\n                 ) as h; exrepnd.\n      apply (implies_alpha_eq_mk_fresh_sub v0); auto.\n      allrw in_app_iff; allrw not_over_or; repnd.\n\n      pose proof (lsubst_trivial4\n                    (lsubst_aux t (sub_filter (sub_filter sub l) [newvar t]))\n                    (var_ren [newvar t] [v0])) as k1.\n      repeat (autodimp k1 hyp).\n      { rw @dom_sub_var_ren; simpl; auto.\n        apply disjoint_singleton_l; auto.\n        rw @free_vars_lsubst_aux_cl; eauto with slow.\n        allrw <- @dom_sub_sub_filter.\n        allrw in_remove_nvars.\n        intro k; repnd.\n        apply newvar_prop in k0; sp. }\n      { simpl; introv i; repndors; cpx.\n        simpl.\n        apply disjoint_singleton_l; auto. }\n\n      pose proof (lsubst_trivial4\n                    (lsubst_aux t (sub_filter (sub_filter sub [v]) l))\n                    (var_ren [newvar (lsubst_aux t (sub_filter (sub_filter sub [v]) l))] [v0])) as k2.\n      repeat (autodimp k2 hyp).\n      { rw @dom_sub_var_ren; simpl; auto.\n        apply disjoint_singleton_l; auto.\n        apply newvar_prop. }\n      { simpl; introv i; repndors; cpx.\n        simpl.\n        apply disjoint_singleton_l; auto. }\n\n      rw k1; rw k2; clear k1 k2.\n\n      apply alpha_eq_lsubst_aux_if_ext_eq; auto;\n      try (rw @sub_free_vars_if_cl_sub; eauto with slow).\n\n      allrw <- @sub_filter_app_r.\n      unfold ext_alpha_eq_subs; introv i.\n      allrw @sub_find_sub_filter_eq.\n      allrw memvar_app; allrw memvar_singleton.\n      boolvar; simpl; tcsp; eauto with slow.\n      apply newvar_prop in i; sp.\n\n    + rw @sub_filter_swap; auto.\nQed.\n\nLemma alpha_eq_mk_atom_eq_lsubst {o} :\n  forall (a b c d : @NTerm o) sub,\n    alpha_eq (lsubst (mk_atom_eq a b c d) sub)\n             (mk_atom_eq (lsubst a sub) (lsubst b sub) (lsubst c sub) (lsubst d sub)).\nProof.\n  introv.\n  pose proof (unfold_lsubst sub a) as ha; exrepnd; rw ha0.\n  pose proof (unfold_lsubst sub b) as hb; exrepnd; rw hb0.\n  pose proof (unfold_lsubst sub c) as hc; exrepnd; rw hc0.\n  pose proof (unfold_lsubst sub d) as hd; exrepnd; rw hd0.\n  unfold lsubst; simpl.\n  allrw @var_ren_nil_l.\n  allrw @sub_filter_nil_r.\n  allrw app_nil_r.\n  rw <- @sub_free_vars_is_flat_map_free_vars_range.\n  allrw @lsubst_aux_nil.\n  boolvar; unfold mk_atom_eq, nobnd.\n  - allrw disjoint_app_l; repnd.\n    apply implies_alpha_eq_mk_atom_eq;\n      apply lsubst_aux_alpha_congr_same_disj;\n      auto.\n  - apply implies_alpha_eq_mk_atom_eq; auto;\n    t_change u;\n    apply lsubst_aux_alpha_congr_same_disj;\n    eauto with slow.\nQed.\n\nLemma alpha_eq_mk_exception_lsubst {o} :\n  forall (a b : @NTerm o) sub,\n    alpha_eq (lsubst (mk_exception a b) sub)\n             (mk_exception (lsubst a sub) (lsubst b sub)).\nProof.\n  introv.\n  pose proof (unfold_lsubst sub a) as ha; exrepnd; rw ha0.\n  pose proof (unfold_lsubst sub b) as hb; exrepnd; rw hb0.\n  unfold lsubst; simpl.\n  allrw @var_ren_nil_l.\n  allrw @sub_filter_nil_r.\n  allrw app_nil_r.\n  rw <- @sub_free_vars_is_flat_map_free_vars_range.\n  allrw @lsubst_aux_nil.\n  boolvar; unfold mk_atom_eq, nobnd.\n  - allrw disjoint_app_l; repnd.\n    apply implies_alphaeq_exception;\n      apply lsubst_aux_alpha_congr_same_disj;\n      auto.\n  - apply implies_alphaeq_exception; auto;\n    t_change u;\n    apply lsubst_aux_alpha_congr_same_disj;\n    eauto with slow.\nQed.\n\nLemma nr_ut_some_implies {o} :\n  forall (sub : @Sub o) v t u,\n    nr_ut_sub u sub\n    -> sub_find sub v = Some t\n    -> {a : get_patom_set o & t = mk_utoken a}.\nProof.\n  induction sub; introv nrut sf; allsimpl; ginv.\n  destruct a as [x z].\n  inversion nrut as [|? ? ? ? imp nrut1]; subst; clear nrut.\n  boolvar; ginv.\n  - eexists; dands; eauto.\n  - eapply IHsub in sf; eauto.\nQed.\n\nLemma lsubst_aux_pk2term {o} :\n  forall (pk : @param_kind o) sub,\n    lsubst_aux (pk2term pk) sub = pk2term pk.\nProof.\n  introv; destruct pk; simpl; auto.\nQed.\n\nHint Resolve covered_sub_nil : slow.\n\nLemma nt_wf_oterm_fst {o} :\n  forall op (t : @NTerm o) vs bs,\n    nt_wf (oterm op (bterm vs t :: bs)) -> nt_wf t.\nProof.\n  introv w.\n  allrw @nt_wf_oterm_iff; repnd; allsimpl.\n  pose proof (w (bterm vs t)) as w1; autodimp w1 hyp.\n  allrw @bt_wf_iff; auto.\nQed.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/computation/computation3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21594798927958447}}
{"text": "Require Import CoqlibC.\nRequire Import Memory.\nRequire Import Values.\nRequire Import Maps.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import sflib.\nRequire Import RelationClasses.\nRequire Import FSets.\nRequire Import Ordered.\nRequire Import AST.\nRequire Import Integers.\n\nRequire Import IntegersC LinkingC.\nRequire Import SimSymb Skeleton Mod ModSem.\nRequire SimSymbId.\nRequire Import SimMemLift.\n\nSet Implicit Arguments.\n\n\n\n\nRecord t' := mk {\n  src: mem;\n  tgt: mem;\n}.\n\nProgram Instance SimMemId : SimMem.class :=\n{ t := t';\n  src := src;\n  tgt := tgt;\n  wf := fun (rel: t') => rel.(src) = rel.(tgt);\n  le := fun (mrel0 mrel1: t') => True;\n  lepriv := top2;\n  sim_val := fun (_: t') => eq;\n  sim_val_list := fun (_: t') => eq;\n}.\nNext Obligation.\n  do 2 (apply Axioms.functional_extensionality; i). apply prop_ext1. split; i; ss; clarify.\n  - ginduction x; ii; inv H; ss. erewrite IHx; eauto.\n  - ginduction x1; ii; ss. econs; eauto.\nQed.\n\n\n\n\n\nProgram Instance SimMemIdLift: SimMemLift.class SimMemId :=\n{ lift := id;\n  unlift := fun _ => id;\n}.\n\n\n\n\n\n\n\n\n\n\n\nGlobal Program Instance SimSymbId: SimSymb.class SimMemId := {\n  t := SimSymbId.t';\n  src := SimSymbId.src;\n  tgt := SimSymbId.tgt;\n  le := SimSymbId.le;\n  wf := SimSymbId.wf;\n  sim_skenv (_: SimMem.t) (_: SimSymbId.t') := SimSymbId.sim_skenv;\n}.\nNext Obligation. rr in SIMSK. r. congruence. Qed.\nNext Obligation. eapply SimSymbId.wf_link; eauto. Qed.\nNext Obligation. rr in SIMSKE. clarify. Qed.\nNext Obligation.\n  exploit SimSymbId.wf_load_sim_skenv; eauto. i; des.\n  eexists. eexists (mk _ _). esplits; ss; eauto.\nQed.\nNext Obligation. eapply SimSymbId.sim_skenv_monotone; try apply SIMSKENV; eauto. Qed.\nNext Obligation. eapply SimSymbId.sim_skenv_func_bisim; eauto. Qed.\nNext Obligation. esplits; eauto. eapply SimSymbId.system_sim_skenv; eauto. Qed.\nNext Obligation.\n  inv ARGS; ss. clarify. destruct sm0; ss. clarify.\n  destruct retv_src; ss.\n  esplits; eauto.\n  - eapply external_call_symbols_preserved; eauto.\n    { eapply SimSymbId.sim_skenv_equiv; eauto. }\n    instantiate (1:= Retv.mk _ _). ss. eauto.\n  - instantiate (1:= mk _ _). econs; ss; eauto.\n  - ss.\nQed.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/proof/SimMemId.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21594798927958447}}
{"text": "Require Import AutoSep Wrap StringOps SinglyLinkedList Malloc ArrayOps Bags.\nRequire Import RelDb RelDbCondition RelDbSelect.\n\n\nSet Implicit Arguments.\n\n\n(** * A language for generating XML code *)\n\nInductive xml :=\n| Cdata (const : string)\n| Var (start len : string)\n| Tag (tag : string) (inner : list xml)\n| Column (tab : string) (col : string)\n| Select (tab rw data : string) (cond : condition) (inner : xml)\n| IfEqual (tab1 col1 tab2 col2 : string) (inner : xml).\n\nSection ForallR.\n  Variable A : Type.\n  Variable P : A -> Prop.\n\n  Fixpoint ForallR (ls : list A) : Prop :=\n    match ls with\n      | nil => True\n      | x :: ls' => P x /\\ ForallR ls'\n    end.\n\n  Theorem Forall_ForallR : forall ls, List.Forall P ls -> ForallR ls.\n    induction 1; simpl; intuition.\n  Qed.\n\n  Theorem ForallR_Forall : forall ls, ForallR ls -> List.Forall P ls.\n    induction ls; simpl; intuition.\n  Qed.\n\n  Fixpoint ExistsR (ls : list A) : Prop :=\n    match ls with\n      | nil => False\n      | x :: ls' => P x \\/ ExistsR ls'\n    end.\n\n  Theorem Exists_ExistsR : forall ls, List.Exists P ls -> ExistsR ls.\n    induction 1; simpl; intuition.\n  Qed.\n\n  Theorem ExistsR_Exists : forall ls, ExistsR ls -> List.Exists P ls.\n    induction ls; simpl; intuition.\n  Qed.\nEnd ForallR.\n\nRecord table := {\n  Name : string;\n  Address : W;\n  Schema : schema\n}.\n\nRecord avail := {\n  Table : table;\n  Row : string;\n  Data : string\n}.\n\nDefinition twf (t : table) := goodSize (2 + length (Schema t) + length (Schema t)).\n\nDefinition tables := list table.\nDefinition twfs : tables -> Prop := List.Forall twf.\n\nDefinition ewf (ns : list string) (cdatas : list (string * string)) (e : exp) : Prop :=\n  match e with\n    | Const s => goodSize (String.length s)\n    | Input pos len => In pos ns /\\ In len ns /\\ ~ In pos baseVars /\\ ~ In len baseVars\n      /\\ In (pos, len) cdatas\n  end.\n\nDefinition eqwf ns (sch : schema) cdatas (e : equality) : Prop :=\n  In (fst e) sch /\\ ewf ns cdatas (snd e).\n\nDefinition cwf ns sch cdatas : condition -> Prop := List.Forall (eqwf ns sch cdatas).\n\nFixpoint removeTable (tab : string) (ts : tables) : tables :=\n  match ts with\n    | nil => nil\n    | t :: ts => if string_dec tab (Name t) then removeTable tab ts else t :: removeTable tab ts\n  end.\n\nDefinition cvars := \"rp\" :: \"ibuf\" :: \"overflowed\" :: \"ipos\" :: \"ilen\"\n  :: \"opos\" :: \"tmp\" :: \"len\" :: \"buf\" :: \"matched\" :: \"res\" :: \"obuf\"\n  :: \"olen\" :: nil.\n\nDefinition dontTouch rw data :=\n  ForallR (fun p : string * string => fst p <> rw /\\ snd p <> rw /\\ fst p <> data /\\ snd p <> data).\n\nDefinition dontReuse rw data :=\n  ForallR (fun av => Row av <> rw /\\ Row av <> data /\\ Data av <> rw /\\ Data av <> data).\n\nFixpoint wf ns (cdatas : list (string * string)) (avs : list avail) (ts : list table) (xm : xml) : Prop :=\n  match xm with\n    | Cdata const => goodSize (String.length const)\n    | Var _ _ => True\n    | Tag tag inner => goodSize (String.length tag + 3) /\\ ForallR (wf ns cdatas avs ts) inner\n    | Column tab col => exists av, In av avs /\\ Name (Table av) = tab /\\ In col (Schema (Table av))\n      /\\ In (Data av) ns\n    | Select tab rw data cond inner =>\n      rw <> data /\\ ~In rw cvars /\\ ~In data cvars\n      /\\ dontTouch rw data cdatas /\\ dontReuse rw data avs\n      /\\ exists t, In t ts /\\ Name t = tab /\\ cwf ns (Schema t) cdatas cond\n        /\\ wf ns cdatas ({| Table := t; Row := rw; Data := data |} :: avs)\n        (removeTable tab ts) inner\n    | IfEqual tab1 col1 tab2 col2 inner => tab1 <> tab2\n      /\\ (exists av, In av avs /\\ Name (Table av) = tab1\n        /\\ In col1 (Schema (Table av))\n        /\\ In (Data av) ns)\n      /\\ (exists av, In av avs /\\ Name (Table av) = tab2\n        /\\ In col2 (Schema (Table av))\n        /\\ In (Data av) ns)\n      /\\ wf ns cdatas avs ts inner\n  end.\n\n\nDefinition efreeVar (e : exp) (xs : string * string) : Prop :=\n  match e with\n    | Const _ => False\n    | Input pos len => xs = (pos, len)\n  end.\n\nFixpoint freeVar (xm : xml) (xs : string * string) : Prop :=\n  match xm with\n    | Cdata _ => False\n    | Var start len => xs = (start, len)\n    | Tag _ inner => ExistsR (fun xm' => freeVar xm' xs) inner\n    | Column _ _ => False\n    | Select _ _ _ cond inner => List.Exists (fun e => efreeVar (snd e) xs) cond\n      \\/ freeVar inner xs\n    | IfEqual _ _ _ _ inner => freeVar inner xs\n  end.\n\nFixpoint bindsRowVar (xm : xml) (xs : string * string) : Prop :=\n  match xm with\n    | Cdata _ => False\n    | Var _ _ => False\n    | Tag _ inner => ExistsR (fun xm' => bindsRowVar xm' xs) inner\n    | Column _ _ => False\n    | Select _ rw data _ inner => xs = (rw, data) \\/ bindsRowVar inner xs\n    | IfEqual _ _ _ _ inner => bindsRowVar inner xs\n  end.\n\nSection xml_ind'.\n  Variable P : xml -> Prop.\n\n  Hypothesis H_Cdata : forall const, P (Cdata const).\n\n  Hypothesis H_Var : forall start len, P (Var start len).\n\n  Hypothesis H_Tag : forall tag inner, List.Forall P inner -> P (Tag tag inner).\n\n  Hypothesis H_Column : forall tab col, P (Column tab col).\n\n  Hypothesis H_Select : forall tab rw data cond inner, P inner\n    -> P (Select tab rw data cond inner).\n\n  Hypothesis H_IfEqual : forall tab1 col1 tab2 col2 inner, P inner\n    -> P (IfEqual tab1 col1 tab2 col2 inner).\n\n  Fixpoint xml_ind' (xm : xml) : P xm :=\n    match xm with\n      | Cdata const => H_Cdata const\n      | Var start len => H_Var start len\n      | Tag tag inner => H_Tag tag ((fix xmls_ind (xms : list xml) : List.Forall P xms :=\n        match xms with\n          | nil => Forall_nil _\n          | xm :: xms' => Forall_cons _ (xml_ind' xm) (xmls_ind xms')\n        end) inner)\n      | Column tab col => H_Column tab col\n      | Select tab rw data cond inner =>\n        H_Select tab rw data cond (xml_ind' inner)\n      | IfEqual tab1 col1 tab2 col2 inner =>\n        H_IfEqual tab1 col1 tab2 col2 (xml_ind' inner)\n    end.\nEnd xml_ind'.\n\nOpaque xml_ind'.\n\nDefinition inBounds (cdatas : list (string * string)) (V : vals) :=\n  List.Forall (fun p => wordToNat (V (fst p)) + wordToNat (V (snd p)) <= wordToNat (V \"len\"))%nat\n  cdatas.\n\nDefinition db := starL (fun t => RelDb.table (Schema t) (Address t)).\nDefinition cursor (V : vals) (av : avail) := (\n  row (Schema (Table av)) (V (Data av))\n  * RelDbSelect.inv (Address (Table av)) (Schema (Table av)) (V (Row av)) (V (Data av))\n)%Sep.\nDefinition cursors (V : vals) := starL (cursor V).\n\nFixpoint findTable (tab : string) (ts : tables) : option table :=\n  match ts with\n    | nil => None\n    | t :: ts => if string_dec tab (Name t) then Some t else findTable tab ts\n  end.\n\nFixpoint findCursor (tab : string) (avs : list avail) : option avail :=\n  match avs with\n    | nil => None\n    | av :: avs => if string_dec tab (Name (Table av)) then Some av else findCursor tab avs\n  end.\n\nFixpoint findCol (sch : schema) (s : string) : nat :=\n  match sch with\n    | nil => O\n    | s' :: sch' => if string_dec s s' then O else S (findCol sch' s)\n  end.\n\nFixpoint removeCursor (tab : string) (avs : list avail) : list avail :=\n  match avs with\n    | nil => nil\n    | av :: avs => if string_dec tab (Name (Table av)) then removeCursor tab avs\n      else av :: removeCursor tab avs\n  end.\n\nLtac ift := match goal with\n              | [ |- context[if ?E then _ else _] ] => destruct E; intuition\n            end.\n\nDefinition Names := map Name.\n\nLemma findTable_good : forall tab t ts0,\n  NoDup (Names ts0)\n  -> In t ts0\n  -> Name t = tab\n  -> findTable tab ts0 = Some t.\n  induction ts0; simpl; inversion 1; intuition subst; ift.\n  exfalso; eapply H2.\n  rewrite <- e.\n  apply in_map; auto.\nQed.\n\nLemma removeTable_irrel_fwd : forall x ts,\n  ~In x (Names ts)\n  -> db ts ===> db (removeTable x ts).\n  induction ts; simpl; intuition subst; try ift; sepLemma.\nQed.\n\nLemma removeTable_irrel_bwd : forall x ts,\n  ~In x (Names ts)\n  -> db (removeTable x ts) ===> db ts.\n  induction ts; simpl; intuition subst; try ift; sepLemma.\nQed.\n\nHint Immediate removeTable_irrel_fwd removeTable_irrel_bwd.\n\nLemma removeTable_bwd : forall x ts,\n  NoDup (Names ts)\n  -> In x ts\n  -> RelDb.table (Schema x) (Address x) * db (removeTable (Name x) ts)\n  ===> db ts.\n  induction ts; inversion 1; simpl; intuition subst;\n    match goal with\n      | [ |- context[if ?E then _ else _] ] => destruct E; intuition\n    end.\n  apply Himp_star_frame; try apply Himp_refl; auto.\n  exfalso; apply H2; rewrite <- e; eapply in_map; auto.\n  simpl.\n\n  sepLemma.\n  etransitivity; [ | apply H6 ]; sepLemma.\nQed.\n\nLemma removeTable_fwd : forall x ts,\n  NoDup (Names ts)\n  -> In x ts\n  -> db ts ===> RelDb.table (Schema x) (Address x) * db (removeTable (Name x) ts).\n  induction ts; inversion 1; simpl; intuition subst;\n    match goal with\n      | [ |- context[if ?E then _ else _] ] => destruct E; intuition\n    end.\n  apply Himp_star_frame; try apply Himp_refl; auto.\n  exfalso; apply H2; rewrite <- e; eapply in_map; auto.\n  simpl.\n\n  sepLemma.\n  etransitivity; [ apply H6 | ]; sepLemma.\nQed.\n\nLemma mult4_S : forall n, 4 * S n = S (S (S (S (4 * n)))).\n  simpl; intros; omega.\nQed.\n\nDefinition cdatasGood (cdatas : list (string * string)) :=\n  List.Forall (fun p => fst p <> \"opos\" /\\ fst p <> \"overflowed\" /\\ fst p <> \"tmp\" /\\ fst p <> \"matched\"\n    /\\ fst p <> \"res\" /\\ fst p <> \"ibuf\" /\\ fst p <> \"ilen\" /\\ fst p <> \"ipos\"\n    /\\ snd p <> \"opos\" /\\ snd p <> \"overflowed\" /\\ snd p <> \"tmp\" /\\ snd p <> \"matched\"\n    /\\ snd p <> \"res\" /\\ snd p <> \"ibuf\" /\\ snd p <> \"ilen\" /\\ snd p <> \"ipos\")\n  cdatas.\n\nLemma removeTable_bwd' : forall x ts P,\n  NoDup (Names ts)\n  -> In x ts\n  -> RelDb.table (Schema x) (Address x) * (db (removeTable (Name x) ts) * P)\n  ===> P * db ts.\n  intros; eapply Himp_trans; [ apply Himp_star_assoc' | ].\n  eapply Himp_trans; [ | apply Himp_star_comm ].\n  apply Himp_star_frame; try apply Himp_refl.\n  apply removeTable_bwd; auto.\nQed.\n\nLemma removeTable_fwd' : forall x ts P,\n  NoDup (Names ts)\n  -> In x ts\n  -> P * db ts\n  ===> RelDb.table (Schema x) (Address x) * (P * db (removeTable (Name x) ts)).\n  intros; eapply Himp_trans; [ | apply Himp_star_frame; [ | apply Himp_star_comm ] ].\n  intros; eapply Himp_trans; [ | apply Himp_star_assoc ].\n  eapply Himp_trans; [ apply Himp_star_comm | ].\n  apply Himp_star_frame; try apply Himp_refl.\n  apply removeTable_fwd; auto.\n  apply Himp_refl.\nQed.\n\nLemma make_cursor : forall specs t V rw data P,\n  himp specs (row (Schema t) (sel V data)\n    * (inv (Address t) (Schema t) (sel V rw) (sel V data) * P))%Sep\n  (P * cursor V {| Table := t; Row := rw; Data := data |})%Sep.\nsepLemma; apply himp_star_comm.\nQed.\n\nLemma unmake_cursor : forall specs t V rw data P,\n  himp specs (P * cursor V {| Table := t; Row := rw; Data := data |})%Sep\n  (row (Schema t) (sel V data)\n    * (inv (Address t) (Schema t) (sel V rw) (sel V data) * P))%Sep.\nsepLemma; apply himp_star_comm.\nQed.\n\nTheorem matchup : forall P Q R P' Q',\n  P ===> P'\n  -> Q ===> Q'\n  -> P * (Q * R) ===> R * (P' * Q').\n  sepLemma; eapply Himp_star_frame; eauto.\nQed.\n\nTheorem matchup2 : forall P Q R Q' R',\n  Q ===> Q'\n  -> R ===> R'\n  -> P * (Q * R) ===> P * (Q' * R').\n  sepLemma; eapply Himp_star_frame; eauto.\nQed.\n\nDefinition ANames := map (fun av => Name (Table av)).\n\nLemma cursors_irrel : forall V av avs,\n  ~In (Name (Table av)) (ANames avs)\n  -> cursors V (removeCursor (Name (Table av)) avs) ===> cursors V avs.\n  induction avs; simpl; intuition; try ift; sepLemma.\nQed.\n\nTheorem grab_cursor : forall V av avs,\n  In av avs\n  -> NoDup (ANames avs)\n  -> (cursors V (removeCursor (Name (Table av)) avs)\n    * inv (Address (Table av)) (Schema (Table av))\n    (sel V (Row av)) (sel V (Data av))\n    * row (Schema (Table av)) (sel V (Data av)))\n  ===> cursors V avs.\n  clear; induction avs; inversion_clear 2; simpl in *; intuition subst.\n  ift.\n  unfold cursor.\n  repeat match goal with\n           | [ |- context[V ?x] ] => change (V x) with (sel V x)\n         end.\n  sepLemma.\n  apply cursors_irrel; auto.\n  ift.\n  exfalso; apply H1.\n  rewrite <- e.\n  apply (in_map (fun av => Name (Table av))); auto.\n  simpl.\n  sepLemma.\n  etransitivity; [ | apply H3 ].\n  sepLemma.\nQed.\n\nLemma cursors_irrel' : forall V av avs,\n  ~In (Name (Table av)) (ANames avs)\n  -> cursors V avs ===> cursors V (removeCursor (Name (Table av)) avs).\n  induction avs; simpl; intuition; try ift; sepLemma.\nQed.\n\nTheorem release_cursor : forall V av avs,\n  In av avs\n  -> NoDup (ANames avs)\n  -> cursors V avs\n  ===> cursor V av * cursors V (removeCursor (Name (Table av)) avs).\n  clear; induction avs; inversion_clear 2; simpl in *; intuition subst; ift.\n  sepLemma.\n  apply cursors_irrel'; auto.\n  exfalso; apply H1.\n  rewrite <- e.\n  apply (in_map (fun av => Name (Table av))); auto.\n  sepLemma.\n  etransitivity; [ | apply himp_star_comm ]; auto.\nQed.\n\nDefinition goodCursors avs := List.Forall (fun av => ~In (Row av) cvars /\\ ~In (Data av) cvars\n  /\\ goodSize (length (Schema (Table av)))) avs.\n\nLemma weaken_cursors : forall specs V V',\n  (forall x, x <> \"overflowed\" -> x <> \"opos\"\n    -> x <> \"tmp\" -> x <> \"matched\" -> x <> \"res\"\n    -> sel V x = sel V' x)\n  -> forall avs,\n    goodCursors avs\n    -> himp specs (cursors V avs) (cursors V' avs).\n  induction avs; inversion_clear 1; simpl; intuition.\n  apply himp_star_frame; auto.\n  unfold cvars in *; simpl in *; intuition idtac;\n    unfold cursor; apply himp_star_frame;\n      repeat match goal with\n               | [ V : vals |- _ ] =>\n                 progress repeat match goal with\n                                   | [ |- context[V ?x] ] => change (V x) with (sel V x)\n                                 end\n             end;\n      try match goal with\n            | [ H : forall x : string, _ |- _ ] => repeat rewrite H by congruence\n          end; reflexivity.\nQed.\n\nHint Resolve weaken_cursors.\n\nLemma Weaken_cursors : forall V V',\n  (forall x, x <> \"overflowed\" -> x <> \"opos\"\n    -> x <> \"tmp\" -> x <> \"matched\" -> x <> \"res\" -> sel V x = sel V' x)\n  -> forall avs,\n    goodCursors avs\n    -> cursors V avs ===> cursors V' avs.\n  intros; hnf; intros; apply weaken_cursors; auto.\nQed.\n\nHint Extern 1 (cursors _ _ ===> cursors _ _) =>\n  apply Weaken_cursors; eauto 1; [ descend ].\n\nLemma cursor_expand : forall V' V P Q avs av,\n  In av avs\n  -> NoDup (ANames avs)\n  -> goodCursors avs\n  -> (forall x, x <> \"overflowed\" -> x <> \"opos\" ->\n    x <> \"tmp\" -> x <> \"matched\" -> x <> \"res\" -> sel V' x = sel V x)\n  -> P * Q * cursors V' (removeCursor (Name (Table av)) avs)\n  * inv (Address (Table av)) (Schema (Table av))\n  (sel V' (Row av)) (sel V' (Data av))\n  * row (Schema (Table av)) (sel V' (Data av)) ===> P * (Q * cursors V avs).\n  sepLemma.\n  etransitivity; [ | eapply weaken_cursors ]; try eassumption.\n  etransitivity; [ | apply grab_cursor ]; eauto.\n  sepLemma.\nQed.\n\nLemma cursor_expand' : forall V' V P Q avs av,\n  In av avs\n  -> NoDup (ANames avs)\n  -> goodCursors avs\n  -> (forall x, x <> \"overflowed\" -> x <> \"opos\" ->\n    x <> \"tmp\" -> x <> \"matched\" -> x <> \"res\" -> sel V' x = sel V x)\n  -> P * Q * cursors V' (removeCursor (Name (Table av)) avs)\n  * inv (Address (Table av)) (Schema (Table av))\n  (sel V' (Row av)) (sel V' (Data av))\n  * row (Schema (Table av)) (sel V' (Data av)) ===> P * (cursors V avs * Q).\n  sepLemma.\n  etransitivity; [ | eapply weaken_cursors ]; try eassumption.\n  etransitivity; [ | apply grab_cursor ]; eauto.\n  sepLemma.\nQed.\n\nHint Constructors unit.\n\nLemma length_append : forall s1 s2, String.length (s1 ++ s2) = String.length s1 + String.length s2.\n  induction s1; simpl; intuition.\nQed.\n\nHint Rewrite length_append : sepFormula.\n\nLemma Forall_impl2 : forall A (P Q R : A -> Prop) ls,\n  List.Forall P ls\n  -> List.Forall Q ls\n  -> (forall x, P x -> Q x -> R x)\n  -> List.Forall R ls.\n  induction 1; inversion 1; eauto.\nQed.\n\nLemma wplus_wminus : forall u v : W, u ^+ v ^- v = u.\n  intros; words.\nQed.\n\nHint Rewrite wplus_wminus mult4_S : sepFormula.\n\nLemma findCol_bound : forall s col,\n  In col s\n  -> (findCol s col < length s)%nat.\n  clear; induction s; simpl; intuition subst;\n    match goal with\n      | [ |- context[if ?E then _ else _] ] => destruct E\n    end; intuition.\nQed.\n\nLemma findCol_bound_natToW : forall sch col n,\n  In col sch\n  -> goodSize (Datatypes.length sch)\n  -> n = length sch\n  -> natToW (findCol sch col) < natToW n.\n  clear; intros; subst.\n  pre_nomega.\n  rewrite wordToNat_natToWord_idempotent.\n  rewrite wordToNat_natToWord_idempotent.\n  eauto using findCol_bound.\n  apply findCol_bound in H; congruence.\n  change (goodSize (findCol sch col)); eapply goodSize_weaken; eauto.\n  apply findCol_bound in H; auto.\nQed.\n\nLemma findCol_posl : forall sch col cols,\n  In col sch\n  -> goodSize (Datatypes.length sch)\n  -> length cols = length sch\n  -> natToW (findCol sch col) < natToW (length (posl cols)).\n  intros; rewrite length_posl; eauto using findCol_bound_natToW.\nQed.\n\nLemma findCol_lenl : forall sch col cols,\n  In col sch\n  -> goodSize (Datatypes.length sch)\n  -> length cols = length sch\n  -> natToW (findCol sch col) < natToW (length (lenl cols)).\n  intros; rewrite length_lenl; eauto using findCol_bound_natToW.\nQed.\n\nHint Resolve findCol_posl findCol_lenl.\n\nLemma selN_col : forall sch col cols,\n  In col sch\n  -> goodSize (length sch)\n  -> length cols = length sch\n  -> Array.sel cols (natToW (findCol sch col)) = selN cols (findCol sch col).\n  clear; unfold Array.sel; intros; f_equal.\n  apply wordToNat_natToWord_idempotent.\n  change (goodSize (findCol sch col)).\n  eapply goodSize_weaken; eauto.\n  apply findCol_bound in H; auto.\nQed.\n\nLemma selN_posl : forall sch col cols,\n  In col sch\n  -> goodSize (length sch)\n  -> length cols = length sch\n  -> Array.sel (posl cols) (natToW (findCol sch col)) = selN (posl cols) (findCol sch col).\n  intros; apply selN_col; auto; rewrite length_posl; auto.\nQed.\n\nLemma selN_lenl : forall sch col cols,\n  In col sch\n  -> goodSize (length sch)\n  -> length cols = length sch\n  -> Array.sel (lenl cols) (natToW (findCol sch col)) = selN (lenl cols) (findCol sch col).\n  intros; apply selN_col; auto; rewrite length_lenl; auto.\nQed.\n\nHint Resolve selN_posl selN_lenl.\n\nLemma inBounds_selN : forall sch len cols,\n  RelDb.inBounds len cols\n  -> forall col a b c, a = selN (posl cols) (findCol sch col)\n    -> b = selN (lenl cols) (findCol sch col)\n    -> c = wordToNat len\n    -> In col sch\n    -> length cols = length sch\n    -> (wordToNat a + wordToNat b <= c)%nat.\n  intros; eapply inBounds_selN; try eassumption.\n  rewrite H4; eapply findCol_bound; auto.\nQed.\n\nHint Resolve inBounds_selN.\n\nHint Extern 1 (_ + _ <= _)%nat =>\n  eapply inBounds_selN; try eassumption; (cbv beta; congruence).\n\nLemma findCursor_good : forall tab av avs,\n  NoDup (map (fun av => Name (Table av)) avs)\n  -> Name (Table av) = tab\n  -> In av avs\n  -> findCursor tab avs = Some av.\n  induction avs; simpl; inversion 1; intuition subst; ift.\n  exfalso; eapply H2.\n  rewrite <- e.\n  eapply (in_map (fun av => Name (Table av)) _ _ H6).\nQed.\n\nLemma inBounds_inputOk : forall ns sch V cdatas,\n  inBounds cdatas V\n  -> forall cond, cwf ns sch cdatas cond\n    -> inputOk V (exps cond).\n  clear; induction 2; simpl; constructor; auto.\n  unfold eqwf in *; destruct x; simpl in *; intuition.\n  destruct e; simpl in *; intuition idtac.\n  eapply Forall_forall in H; [ | eauto ]; eauto.\nQed.\n\nHint Immediate inBounds_inputOk.\n\nLemma inBounds_weaken_dontTouch : forall cdatas V rw data V',\n  inBounds cdatas V\n  -> dontTouch rw data cdatas\n  -> cdatasGood cdatas\n  -> ~In rw cvars\n  -> ~In data cvars\n  -> (forall x, x <> rw -> x <> data\n    -> x <> \"ibuf\" -> x <> \"ilen\" -> x <> \"tmp\" -> x <> \"ipos\"\n    -> x <> \"overflowed\" -> x <> \"matched\" -> sel V x = sel V' x)\n  -> inBounds cdatas V'.\n  clear; intros; eapply Forall_impl3; [ apply H | apply ForallR_Forall; apply H0 | apply H1 | ].\n  simpl in *; intuition idtac.\n  match goal with\n    | [ H : (_ <= _)%nat |- _ ] => generalize dependent H;\n      repeat match goal with\n               | [ V : vals |- _ ] =>\n                 progress repeat match goal with\n                                   | [ |- context[V ?x] ] => change (V x) with (sel V x)\n                                 end\n             end; intros\n  end.\n  repeat rewrite <- H4 by congruence.\n  assumption.\nQed.\n\nHint Extern 1 (inBounds _ _) => eapply inBounds_weaken_dontTouch; try eassumption;\n  [ | ]; (simpl; tauto).\n\nHint Extern 1 False =>\n  match goal with\n    | [ H : forall rw data : string, _ \\/ _ -> _ |- _ ] =>\n      specialize (H _ _ (or_introl _ eq_refl)); tauto\n  end.\n\nLemma weaken_cursors' : forall rw data specs V V',\n  (forall x, x <> rw -> x <> data\n    -> x <> \"ibuf\" -> x <> \"ilen\" -> x <> \"tmp\" -> x <> \"ipos\"\n    -> x <> \"overflowed\" -> x <> \"matched\" -> sel V x = sel V' x)\n  -> forall avs,\n    goodCursors avs\n    -> dontReuse rw data avs\n    -> himp specs (cursors V avs) (cursors V' avs).\n  unfold dontReuse; induction avs; inversion_clear 1; simpl; intuition.\n  apply himp_star_frame; auto.\n  unfold cvars in *; simpl in *; intuition idtac;\n    unfold cursor; apply himp_star_frame;\n      repeat match goal with\n               | [ V : vals |- _ ] =>\n                 progress repeat match goal with\n                                   | [ |- context[V ?x] ] => change (V x) with (sel V x)\n                                 end\n             end;\n      try match goal with\n            | [ H : forall x : string, _ |- _ ] => repeat rewrite H by congruence\n          end; reflexivity.\nQed.\n\nHint Resolve weaken_cursors'.\n\nLemma twfs_removeTable : forall x ts,\n  twfs ts\n  -> twfs (removeTable x ts).\n  unfold twfs; induction 1; simpl; intuition; ift.\nQed.\n\nHint Constructors NoDup.\n\nLemma In_removeTable : forall x y ts,\n  In x (Names (removeTable y ts))\n  -> In x (Names ts).\n  induction ts; simpl; intuition idtac;\n    match goal with\n      | [ _ : context[if ?E then _ else _] |- _ ] => destruct E; simpl in *; tauto\n    end.\nQed.\n\nHint Immediate In_removeTable.\n\nLemma NoDup_removeTable : forall x ts,\n  NoDup (Names ts)\n  -> NoDup (Names (removeTable x ts)).\n  induction ts; inversion_clear 1; simpl; intuition;\n    match goal with\n      | [ |- context[if ?E then _ else _] ] => destruct E; simpl; eauto\n    end.\nQed.\n\nHint Immediate twfs_removeTable NoDup_removeTable.\n\nHint Extern 1 (goodCursors _) =>\n  apply Forall_cons; try assumption; simpl; tauto.\n\nHint Extern 1 (incl _ _) => hnf; simpl; intuition congruence.\n\nLemma cwf_wfEqualities : forall sch cdatas ns cond,\n  cwf ns sch cdatas cond\n  -> wfEqualities ns sch cond.\n  clear; unfold wfEqualities; induction 1; simpl; intuition.\n  constructor; auto.\n  unfold wfEquality, eqwf in *; destruct x as [ ? [ ] ]; simpl in *; tauto.\nQed.\n\nHint Immediate cwf_wfEqualities.\n\nLemma goodSize_base : forall t ts,\n  twfs ts\n  -> In t ts\n  -> goodSize (length (Schema t)).\n  intros ? ? H H0; eapply Forall_forall in H; [ | eassumption ]; unfold twf in *; intuition idtac.\n  eapply goodSize_weaken; eauto.\nQed.\n\nHint Immediate goodSize_base.\n\nLemma cwf_noOverlapExps : forall ns rw data cdatas sch cond,\n  cwf ns sch cdatas cond\n  -> dontTouch rw data cdatas\n  -> noOverlapExps rw data (exps cond).\n  unfold dontTouch, noOverlapExps, noOverlapExp, eqwf; induction 1; simpl; intuition.\n  constructor; auto.\n  unfold eqwf in *; intuition.\n  destruct (snd x); unfold ewf in *; intuition subst;\n    (eapply ForallR_Forall in H1; eapply Forall_forall in H1; [ | eassumption ];\n      simpl in *; tauto).\nQed.\n\nHint Immediate cwf_noOverlapExps.\n\nDefinition NoDups (avs : list avail) (ts : tables) :=\n  NoDup (map (fun av => Name (Table av)) avs ++ Names ts).\n\nLemma NoDups_ts : forall avs ts,\n  NoDups avs ts\n  -> NoDup (Names ts).\n  intros; eapply NoDup_unapp2; eauto.\nQed.\n\nLemma NoDups_avs : forall avs ts,\n  NoDups avs ts\n  -> NoDup (map (fun av => Name (Table av)) avs).\n  intros; eapply NoDup_unapp1; eauto.\nQed.\n\nHint Immediate NoDups_ts NoDups_avs.\n\nLemma goodCursors_removeCursor : forall tab avs,\n  goodCursors avs\n  -> goodCursors (removeCursor tab avs).\n  unfold goodCursors; induction 1; simpl; intuition; ift.\nQed.\n\nHint Immediate goodCursors_removeCursor.\n\nLemma goodCursors_cons : forall t rw data avs,\n  goodCursors avs\n  -> ~In rw cvars\n  -> ~In data cvars\n  -> goodSize (length (Schema t))\n  -> goodCursors ({| Table := t; Row := rw; Data := data |} :: avs).\n  clear; intros; constructor; intuition.\nQed.\n\nHint Extern 1 (goodCursors (_ :: _)) => eapply goodCursors_cons; eauto 2; (simpl; tauto).\n\nLemma NoDups_app : forall A (ls1 ls2 : list A),\n  NoDup ls1\n  -> NoDup ls2\n  -> (forall x, In x ls1 -> ~In x ls2)\n  -> NoDup (ls1 ++ ls2).\n  clear; induction 1; simpl; intuition.\n  constructor; eauto.\n  intro.\n  apply in_app_or in H4; intuition eauto.\nQed.\n\nLemma NoDups_unapp_cross : forall A (ls1 ls2 : list A),\n  NoDup (ls1 ++ ls2)\n  -> (forall x, In x ls1 -> ~In x ls2).\n  clear; induction ls1; inversion_clear 1; simpl; intuition eauto.\n  subst.\n  apply H0.\n  apply in_or_app; tauto.\nQed.\n\nLemma removeTable_contra : forall tab ts,\n  NoDup (Names ts)\n  -> In tab (Names (removeTable tab ts))\n  -> False.\n  clear; induction ts; inversion_clear 1; simpl; intuition.\n  destruct (string_dec tab (Name a)); subst; simpl in *; intuition.\nQed.\n\nLemma NoDups_move : forall avs ts t rw data,\n  In t ts\n  -> NoDups avs ts\n  -> NoDups ({| Table := t; Row := rw; Data := data |} :: avs) (removeTable (Name t) ts).\n  clear; unfold NoDups; intros; simpl.\n  constructor.\n  intro.\n  apply in_app_or in H1; intuition eauto using removeTable_contra.\n  specialize (NoDups_unapp_cross _ _ H0 _ H2); intro.\n  apply H1.\n  apply in_map; auto.\n  apply NoDups_app; eauto using NoDup_removeTable.\n  intros.\n  intro.\n  eapply NoDups_unapp_cross in H0; eauto.\nQed.\n\nHint Immediate NoDups_move.\n\nModule Type TO_CMD.\n  Parameter toCmd' : chunk ->\n    forall (im : LabelMap.t assert) (mn : string),\n      importsGlobal im -> list string -> nat -> cmd im mn.\n\n  Axiom toCmd'_eq : toCmd' = toCmd.\nEnd TO_CMD.\n\nModule ToCmd : TO_CMD.\n  Definition toCmd' := toCmd.\n\n  Theorem toCmd'_eq : toCmd' = toCmd.\n    auto.\n  Qed.\nEnd ToCmd.\n\nImport ToCmd.\n\nDefinition clarify (ch : chunk) : chunk := fun ns n =>\n  Structured nil (fun im mn H => toCmd' ch mn H ns n).\n\n\n(** * Compiling XML snippets into Bedrock chunks *)\n\nSection Out.\n  Variable A : Type.\n  Variable invPre : A -> vals -> HProp.\n  Variable invPost : A -> vals -> W -> HProp.\n\n  (* Precondition and postcondition of generation *)\n  Definition invar cdatas avs ts :=\n    Al a : A, Al bsI, Al bsO,\n    PRE[V] array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n      * [| length bsI = wordToNat (V \"len\") |] * [| length bsO = wordToNat (V \"olen\") |]\n      * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]\n      * cursors V avs * db ts * invPre a V\n    POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\")\n      * [| length bsO' = length bsO |] * invPost a V R.\n\n  Infix \";;\" := SimpleSeq : SP_scope.\n\n  Section OutList.\n    Variable Out' : xml -> chunk.\n\n    Fixpoint OutList (xms : list xml) : chunk :=\n      match xms with\n        | nil => Skip\n        | xm :: xms' => (Out' xm;; OutList xms')\n      end%SP.\n  End OutList.\n\n  Inductive reveal_row : Prop := RevealRow.\n  Hint Constructors reveal_row.\n\n  Fixpoint Out' (cdatas : list (string * string)) (avs : list avail) (ts : list table) (xm : xml) : chunk :=\n    match xm with\n      | Cdata const => StringWrite \"obuf\" \"olen\" \"opos\" \"overflowed\" const\n        (fun (p : list B * A) V => array8 (fst p) (V \"buf\") * [| length (fst p) = wordToNat (V \"len\") |]\n          * [| inBounds cdatas V |] * invPre (snd p) V * cursors V avs * db ts)%Sep\n        (fun _ (p : list B * A) V R => Ex bs', array8 bs' (V \"obuf\") * [| length bs' = wordToNat (V \"olen\") |]\n          * array8 (fst p) (V \"buf\") * invPost (snd p) V R)%Sep\n\n      | Var start len =>\n        \"tmp\" <- \"olen\" - \"opos\";;\n        If (len < \"tmp\") {\n          Call \"array8\"!\"copy\"(\"obuf\", \"opos\", \"buf\", start, len)\n          [Al a : A, Al bsI, Al bsO,\n            PRE[V] [| V len < V \"olen\" ^- V \"opos\" |]%word * array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n              * [| length bsI = wordToNat (V \"len\") |] * [| length bsO = wordToNat (V \"olen\") |]\n              * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word\n              * invPre a V * cursors V avs * db ts\n            POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\") * [| length bsO' = length bsO |]\n              * invPost a V R];;\n          \"opos\" <- \"opos\" + len\n        } else {\n          \"overflowed\" <- 1\n        }\n\n      | Tag tag inner =>\n        StringWrite \"obuf\" \"olen\" \"opos\" \"overflowed\" (\"<\" ++ tag ++ \">\")\n        (fun (p : list B * A) V => array8 (fst p) (V \"buf\") * [| length (fst p) = wordToNat (V \"len\") |]\n          * invPre (snd p) V * [| inBounds cdatas V |] * cursors V avs * db ts)%Sep\n        (fun _ (p : list B * A) V R => Ex bs', array8 bs' (V \"obuf\") * [| length bs' = wordToNat (V \"olen\") |]\n          * array8 (fst p) (V \"buf\") * invPost (snd p) V R)%Sep;;\n        OutList (Out' cdatas avs ts) inner;;\n        StringWrite \"obuf\" \"olen\" \"opos\" \"overflowed\" (\"</\" ++ tag ++ \">\")\n        (fun (p : list B * A) V => array8 (fst p) (V \"buf\") * [| length (fst p) = wordToNat (V \"len\") |]\n          * invPre (snd p) V * [| inBounds cdatas V |] * cursors V avs * db ts)%Sep\n        (fun _ (p : list B * A) V R => Ex bs', array8 bs' (V \"obuf\") * [| length bs' = wordToNat (V \"olen\") |]\n          * array8 (fst p) (V \"buf\") * invPost (snd p) V R)%Sep\n\n      | Column tab col =>\n        match findCursor tab avs with\n          | None => Fail\n          | Some av =>\n            Assert [Al a : A, Al bsI, Al bsO,\n              PRE[V] array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n                * [| length bsI = wordToNat (V \"len\") |] * [| length bsO = wordToNat (V \"olen\") |]\n                * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word\n                * cursor V av * cursors V (removeCursor tab avs) * db ts * invPre a V\n              POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\")\n                * [| length bsO' = length bsO |] * invPost a V R];;\n\n            Note [reveal_row];;\n\n            Assert [Al a : A, Al bsI, Al bsO,\n              PRE[V] array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n                * [| length bsI = wordToNat (V \"len\") |] * [| length bsO = wordToNat (V \"olen\") |]\n                * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word * invPre a V\n                * cursors V (removeCursor tab avs) * db ts\n                * RelDbSelect.inv (Address (Table av)) (Schema (Table av)) (V (Row av)) (V (Data av))\n                * Ex buf, Ex len, Ex cols, Ex bs,\n                  (V (Data av) ==*> buf, len) * array (posl cols) (V (Data av) ^+ $8)\n                  * array (lenl cols) (V (Data av) ^+ $8 ^+ $(length (Schema (Table av)) * 4)) * array8 bs buf\n                  * [| length bs = wordToNat len |] * [| length cols = length (Schema (Table av)) |]\n                  * [| RelDb.inBounds len cols |]\n                  * [| V (Data av) <> 0 |]\n                  * [| freeable (V (Data av)) (2 + length (Schema (Table av)) + length (Schema (Table av))) |]\n                  * [| buf <> 0 |] * [| freeable8 buf (length bs) |]\n                  * [| natToW (findCol (Schema (Table av)) col) < natToW (length (lenl cols)) |]%word\n              POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\")\n                * [| length bsO' = length bsO |] * invPost a V R];;\n\n            \"matched\" <- Data av + 8;;\n            \"matched\" <- \"matched\" + (length (Schema (Table av)) * 4)%nat;;\n            \"matched\" <-* \"matched\" + (4 * findCol (Schema (Table av)) col)%nat;;\n\n            \"tmp\" <- \"olen\" - \"opos\";;\n            Note [reveal_row];;\n            If (\"matched\" < \"tmp\") {\n              Assert [Al a : A, Al bsI, Al bsO,\n                PRE[V] array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n                  * [| length bsI = wordToNat (V \"len\") |] * [| length bsO = wordToNat (V \"olen\") |]\n                  * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word * invPre a V\n                  * cursors V (removeCursor tab avs) * db ts\n                  * RelDbSelect.inv (Address (Table av)) (Schema (Table av)) (V (Row av)) (V (Data av))\n                  * Ex buf, Ex len, Ex cols, Ex bs,\n                    (V (Data av) ==*> buf, len) * array (posl cols) (V (Data av) ^+ $8)\n                    * array (lenl cols) (V (Data av) ^+ $8 ^+ $(length (Schema (Table av)) * 4)) * array8 bs buf\n                    * [| length bs = wordToNat len |] * [| length cols = length (Schema (Table av)) |]\n                    * [| RelDb.inBounds len cols |]\n                    * [| V (Data av) <> 0 |]\n                    * [| freeable (V (Data av)) (2 + length (Schema (Table av)) + length (Schema (Table av))) |]\n                    * [| buf <> 0 |] * [| freeable8 buf (length bs) |]\n                    * [| V \"matched\" = Array.selN (lenl cols) (findCol (Schema (Table av)) col) |]\n                    * [| natToW (findCol (Schema (Table av)) col) < natToW (length (posl cols)) |]%word\n                    * [| V \"matched\" < V \"olen\" ^- V \"opos\" |]%word\n                POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\")\n                  * [| length bsO' = length bsO |] * invPost a V R];;\n\n              \"tmp\" <- Data av + 8;;\n              \"tmp\" <-* \"tmp\" + (4 * findCol (Schema (Table av)) col)%nat;;\n              Note [reveal_row];;\n\n              Assert [Al a : A, Al bsI, Al bsO,\n                PRE[V] array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n                  * [| length bsI = wordToNat (V \"len\") |] * [| length bsO = wordToNat (V \"olen\") |]\n                  * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word * invPre a V\n                  * cursors V (removeCursor tab avs) * db ts\n                  * RelDbSelect.inv (Address (Table av)) (Schema (Table av)) (V (Row av)) (V (Data av))\n                  * Ex buf, Ex len, Ex cols, Ex bs,\n                    (V (Data av) ==*> buf, len) * array (posl cols) (V (Data av) ^+ $8)\n                    * array (lenl cols) (V (Data av) ^+ $8 ^+ $(length (Schema (Table av)) * 4)) * array8 bs buf\n                    * [| length bs = wordToNat len |] * [| length cols = length (Schema (Table av)) |]\n                    * [| RelDb.inBounds len cols |]\n                    * [| V (Data av) <> 0 |]\n                    * [| freeable (V (Data av)) (2 + length (Schema (Table av)) + length (Schema (Table av))) |]\n                    * [| buf <> 0 |] * [| freeable8 buf (length bs) |]\n                    * [| V \"matched\" = Array.selN (lenl cols) (findCol (Schema (Table av)) col) |]\n                    * [| V \"tmp\" = Array.selN (posl cols) (findCol (Schema (Table av)) col) |]\n                    * [| V \"matched\" < V \"olen\" ^- V \"opos\" |]%word\n                POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\")\n                  * [| length bsO' = length bsO |] * invPost a V R];;\n\n              Note [reveal_row];;\n              \"res\" <-* Data av;;\n\n              Call \"array8\"!\"copy\"(\"obuf\", \"opos\", \"res\", \"tmp\", \"matched\")\n              [Al a : A, Al bsI, Al bsO,\n                PRE[V] [| V \"matched\" < V \"olen\" ^- V \"opos\" |]%word\n                  * array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n                  * [| length bsI = wordToNat (V \"len\") |] * [| length bsO = wordToNat (V \"olen\") |]\n                  * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word\n                  * invPre a V * cursors V avs * db ts\n                POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\") * [| length bsO' = length bsO |]\n                  * invPost a V R];;\n              \"opos\" <- \"opos\" + \"matched\"\n            } else {\n              Note [reveal_row];;\n\n              \"overflowed\" <- 1\n            }\n        end\n\n      | Select tab rw data cond inner =>\n        match findTable tab ts with\n          | None => Fail\n          | Some t => RelDbSelect.Select\n            (fun (p : list B * A) V => cursors V avs\n              * db (removeTable tab ts)\n              * array8 (fst p) (V \"obuf\")\n              * [| length (fst p) = wordToNat (V \"olen\") |]\n              * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word\n              * invPre (snd p) V)%Sep\n            (fun p V R => Ex bsO', array8 bsO' (V \"obuf\") * [| length bsO' = length (fst p) |]\n              * invPost (snd p) V R)%Sep\n            (Address t) (Schema t) rw data cond\n            (Out' cdatas\n              ({| Table := t; Row := rw; Data := data |} :: avs)\n              (removeTable tab ts)\n              inner)\n        end\n\n      | IfEqual tab1 col1 tab2 col2 inner =>\n        match findCursor tab1 avs, findCursor tab2 avs with\n          | Some av1, Some av2 =>\n            If (\"overflowed\" = 0) {\n              Assert [Al a : A, Al bsI, Al bsO,\n                PRE[V] array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n                  * [| length bsI = wordToNat (V \"len\") |]\n                  * [| length bsO = wordToNat (V \"olen\") |]\n                  * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word\n                  * cursor V av1 * cursor V av2\n                  * cursors V (removeCursor tab2 (removeCursor tab1 avs))\n                  * db ts * invPre a V\n                POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\")\n                  * [| length bsO' = length bsO |] * invPost a V R];;\n\n              Note [reveal_row];;\n\n              Assert [Al a : A, Al bsI, Al bsO,\n                PRE[V] array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n                  * [| length bsI = wordToNat (V \"len\") |]\n                  * [| length bsO = wordToNat (V \"olen\") |]\n                  * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word\n                  * invPre a V\n                  * cursors V (removeCursor tab2 (removeCursor tab1 avs)) * db ts\n                  * RelDbSelect.inv (Address (Table av1)) (Schema (Table av1))\n                  (V (Row av1)) (V (Data av1))\n                  * RelDbSelect.inv (Address (Table av2)) (Schema (Table av2))\n                  (V (Row av2)) (V (Data av2))\n                  * (Ex buf1, Ex len1, Ex cols1, Ex bs1,\n                    (V (Data av1) ==*> buf1, len1)\n                    * array (posl cols1) (V (Data av1) ^+ $8)\n                    * array (lenl cols1) (V (Data av1) ^+ $8\n                      ^+ $(length (Schema (Table av1)) * 4)) * array8 bs1 buf1\n                    * [| length bs1 = wordToNat len1 |]\n                    * [| length cols1 = length (Schema (Table av1)) |]\n                    * [| RelDb.inBounds len1 cols1 |]\n                    * [| V (Data av1) <> 0 |]\n                    * [| freeable (V (Data av1))\n                      (2 + length (Schema (Table av1))\n                        + length (Schema (Table av1))) |]\n                    * [| buf1 <> 0 |] * [| freeable8 buf1 (length bs1) |]\n                    * [| natToW (findCol (Schema (Table av1)) col1)\n                      < natToW (length (lenl cols1)) |]%word)\n                  * (Ex buf2, Ex len2, Ex cols2, Ex bs2,\n                    (V (Data av2) ==*> buf2, len2)\n                    * array (posl cols2) (V (Data av2) ^+ $8)\n                    * array (lenl cols2) (V (Data av2) ^+ $8\n                      ^+ $(length (Schema (Table av2)) * 4)) * array8 bs2 buf2\n                    * [| length bs2 = wordToNat len2 |]\n                    * [| length cols2 = length (Schema (Table av2)) |]\n                    * [| RelDb.inBounds len2 cols2 |]\n                    * [| V (Data av2) <> 0 |]\n                    * [| freeable (V (Data av2))\n                      (2 + length (Schema (Table av2))\n                        + length (Schema (Table av2))) |]\n                    * [| buf2 <> 0 |] * [| freeable8 buf2 (length bs2) |]\n                    * [| natToW (findCol (Schema (Table av2)) col2)\n                      < natToW (length (lenl cols2)) |]%word)\n                POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\")\n                  * [| length bsO' = length bsO |] * invPost a V R];;\n\n              \"matched\" <- Data av1 + 8;;\n              \"matched\" <- \"matched\" + (length (Schema (Table av1)) * 4)%nat;;\n              \"matched\" <-* \"matched\" + (4 * findCol (Schema (Table av1)) col1)%nat;;\n\n              Assert [Al a : A, Al bsI, Al bsO,\n                PRE[V] array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n                  * [| length bsI = wordToNat (V \"len\") |]\n                  * [| length bsO = wordToNat (V \"olen\") |]\n                  * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word\n                  * invPre a V\n                  * cursors V (removeCursor tab2 (removeCursor tab1 avs)) * db ts\n                  * RelDbSelect.inv (Address (Table av1)) (Schema (Table av1))\n                  (V (Row av1)) (V (Data av1))\n                  * RelDbSelect.inv (Address (Table av2)) (Schema (Table av2))\n                  (V (Row av2)) (V (Data av2))\n                  * (Ex buf1, Ex len1, Ex cols1, Ex bs1,\n                    (V (Data av1) ==*> buf1, len1)\n                    * array (posl cols1) (V (Data av1) ^+ $8)\n                    * array (lenl cols1) (V (Data av1) ^+ $8\n                      ^+ $(length (Schema (Table av1)) * 4)) * array8 bs1 buf1\n                    * [| length bs1 = wordToNat len1 |]\n                    * [| length cols1 = length (Schema (Table av1)) |]\n                    * [| RelDb.inBounds len1 cols1 |]\n                    * [| V (Data av1) <> 0 |]\n                    * [| freeable (V (Data av1))\n                      (2 + length (Schema (Table av1))\n                        + length (Schema (Table av1))) |]\n                    * [| buf1 <> 0 |] * [| freeable8 buf1 (length bs1) |]\n                    * [| V \"matched\" = Array.selN (lenl cols1)\n                        (findCol (Schema (Table av1)) col1) |])\n                  * (Ex buf2, Ex len2, Ex cols2, Ex bs2,\n                    (V (Data av2) ==*> buf2, len2)\n                    * array (posl cols2) (V (Data av2) ^+ $8)\n                    * array (lenl cols2) (V (Data av2) ^+ $8\n                      ^+ $(length (Schema (Table av2)) * 4)) * array8 bs2 buf2\n                    * [| length bs2 = wordToNat len2 |]\n                    * [| length cols2 = length (Schema (Table av2)) |]\n                    * [| RelDb.inBounds len2 cols2 |]\n                    * [| V (Data av2) <> 0 |]\n                    * [| freeable (V (Data av2))\n                      (2 + length (Schema (Table av2))\n                        + length (Schema (Table av2))) |]\n                    * [| buf2 <> 0 |] * [| freeable8 buf2 (length bs2) |]\n                    * [| natToW (findCol (Schema (Table av2)) col2)\n                      < natToW (length (lenl cols2)) |]%word)\n                POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\")\n                  * [| length bsO' = length bsO |] * invPost a V R];;\n\n              \"tmp\" <- Data av2 + 8;;\n              \"tmp\" <- \"tmp\" + (length (Schema (Table av2)) * 4)%nat;;\n              \"tmp\" <-* \"tmp\" + (4 * findCol (Schema (Table av2)) col2)%nat;;\n\n              Note [reveal_row];;\n              If (\"matched\" = \"tmp\") {\n                Assert [Al a : A, Al bsI, Al bsO,\n                  PRE[V] array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n                    * [| length bsI = wordToNat (V \"len\") |]\n                    * [| length bsO = wordToNat (V \"olen\") |]\n                    * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word\n                    * invPre a V\n                    * cursors V (removeCursor tab2 (removeCursor tab1 avs))\n                    * db ts\n                    * RelDbSelect.inv (Address (Table av1)) (Schema (Table av1))\n                    (V (Row av1)) (V (Data av1))\n                    * RelDbSelect.inv (Address (Table av2)) (Schema (Table av2))\n                    (V (Row av2)) (V (Data av2))\n                    * (Ex buf1, Ex len1, Ex cols1, Ex bs1,\n                      (V (Data av1) ==*> buf1, len1)\n                      * array (posl cols1) (V (Data av1) ^+ $8)\n                      * array (lenl cols1) (V (Data av1) ^+ $8\n                        ^+ $(length (Schema (Table av1)) * 4)) * array8 bs1 buf1\n                      * [| length bs1 = wordToNat len1 |]\n                      * [| length cols1 = length (Schema (Table av1)) |]\n                      * [| RelDb.inBounds len1 cols1 |]\n                      * [| V (Data av1) <> 0 |]\n                      * [| freeable (V (Data av1)) (2\n                        + length (Schema (Table av1))\n                        + length (Schema (Table av1))) |]\n                      * [| buf1 <> 0 |] * [| freeable8 buf1 (length bs1) |]\n                      * [| V \"matched\" = Array.selN (lenl cols1)\n                        (findCol (Schema (Table av1)) col1) |]\n                      * [| natToW (findCol (Schema (Table av1)) col1)\n                        < natToW (length (posl cols1)) |]%word)\n                    * (Ex buf2, Ex len2, Ex cols2, Ex bs2,\n                      (V (Data av2) ==*> buf2, len2)\n                      * array (posl cols2) (V (Data av2) ^+ $8)\n                      * array (lenl cols2) (V (Data av2) ^+ $8\n                        ^+ $(length (Schema (Table av2)) * 4)) * array8 bs2 buf2\n                      * [| length bs2 = wordToNat len2 |]\n                      * [| length cols2 = length (Schema (Table av2)) |]\n                      * [| RelDb.inBounds len2 cols2 |]\n                      * [| V (Data av2) <> 0 |]\n                      * [| freeable (V (Data av2)) (2\n                        + length (Schema (Table av2))\n                        + length (Schema (Table av2))) |]\n                      * [| buf2 <> 0 |] * [| freeable8 buf2 (length bs2) |]\n                      * [| V \"tmp\" = Array.selN (lenl cols2)\n                        (findCol (Schema (Table av2)) col2) |]\n                      * [| natToW (findCol (Schema (Table av2)) col2)\n                        < natToW (length (posl cols2)) |]%word)\n                    * [| V \"matched\" = V \"tmp\"|]%word\n                  POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\")\n                    * [| length bsO' = length bsO |] * invPost a V R];;\n\n                \"tmp\" <- Data av1 + 8;;\n                \"tmp\" <-* \"tmp\" + (4 * findCol (Schema (Table av1)) col1)%nat;;\n\n                Assert [Al a : A, Al bsI, Al bsO,\n                  PRE[V] array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n                    * [| length bsI = wordToNat (V \"len\") |]\n                    * [| length bsO = wordToNat (V \"olen\") |]\n                    * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word\n                    * invPre a V\n                    * cursors V (removeCursor tab2 (removeCursor tab1 avs))\n                    * db ts\n                    * RelDbSelect.inv (Address (Table av1)) (Schema (Table av1))\n                    (V (Row av1)) (V (Data av1))\n                    * RelDbSelect.inv (Address (Table av2)) (Schema (Table av2))\n                    (V (Row av2)) (V (Data av2))\n                    * (Ex buf1, Ex len1, Ex cols1, Ex bs1,\n                      (V (Data av1) ==*> buf1, len1)\n                      * array (posl cols1) (V (Data av1) ^+ $8)\n                      * array (lenl cols1) (V (Data av1) ^+ $8\n                        ^+ $(length (Schema (Table av1)) * 4)) * array8 bs1 buf1\n                      * [| length bs1 = wordToNat len1 |]\n                      * [| length cols1 = length (Schema (Table av1)) |]\n                      * [| RelDb.inBounds len1 cols1 |]\n                      * [| V (Data av1) <> 0 |]\n                      * [| freeable (V (Data av1)) (2\n                        + length (Schema (Table av1))\n                        + length (Schema (Table av1))) |]\n                      * [| buf1 <> 0 |] * [| freeable8 buf1 (length bs1) |]\n                      * [| V \"matched\" = Array.selN (lenl cols1)\n                        (findCol (Schema (Table av1)) col1) |]\n                      * [| V \"tmp\" = Array.selN (posl cols1)\n                        (findCol (Schema (Table av1)) col1) |])\n                    * (Ex buf2, Ex len2, Ex cols2, Ex bs2,\n                      (V (Data av2) ==*> buf2, len2)\n                      * array (posl cols2) (V (Data av2) ^+ $8)\n                      * array (lenl cols2) (V (Data av2) ^+ $8\n                        ^+ $(length (Schema (Table av2)) * 4)) * array8 bs2 buf2\n                      * [| length bs2 = wordToNat len2 |]\n                      * [| length cols2 = length (Schema (Table av2)) |]\n                      * [| RelDb.inBounds len2 cols2 |]\n                      * [| V (Data av2) <> 0 |]\n                      * [| freeable (V (Data av2)) (2\n                        + length (Schema (Table av2))\n                        + length (Schema (Table av2))) |]\n                      * [| buf2 <> 0 |] * [| freeable8 buf2 (length bs2) |]\n                      * [| V \"matched\" = Array.selN (lenl cols2)\n                        (findCol (Schema (Table av2)) col2) |]\n                      * [| natToW (findCol (Schema (Table av2)) col2)\n                        < natToW (length (posl cols2)) |]%word)\n                  POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\")\n                    * [| length bsO' = length bsO |] * invPost a V R];;\n\n                \"res\" <- Data av2 + 8;;\n                \"res\" <-* \"res\" + (4 * findCol (Schema (Table av2)) col2)%nat;;\n\n                Note [reveal_row];;\n\n                Assert [Al a : A, Al bsI, Al bsO,\n                  PRE[V] array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n                    * [| length bsI = wordToNat (V \"len\") |]\n                    * [| length bsO = wordToNat (V \"olen\") |]\n                    * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word\n                    * invPre a V\n                    * cursors V (removeCursor tab2 (removeCursor tab1 avs)) * db ts\n                    * RelDbSelect.inv (Address (Table av1)) (Schema (Table av1))\n                    (V (Row av1)) (V (Data av1))\n                    * RelDbSelect.inv (Address (Table av2)) (Schema (Table av2))\n                    (V (Row av2)) (V (Data av2))\n                    * (Ex buf1, Ex len1, Ex cols1, Ex bs1,\n                      (V (Data av1) ==*> buf1, len1)\n                      * array (posl cols1) (V (Data av1) ^+ $8)\n                      * array (lenl cols1) (V (Data av1) ^+ $8\n                        ^+ $(length (Schema (Table av1)) * 4)) * array8 bs1 buf1\n                      * [| length bs1 = wordToNat len1 |]\n                      * [| length cols1 = length (Schema (Table av1)) |]\n                      * [| RelDb.inBounds len1 cols1 |]\n                      * [| V (Data av1) <> 0 |]\n                      * [| freeable (V (Data av1)) (2\n                        + length (Schema (Table av1))\n                        + length (Schema (Table av1))) |]\n                      * [| buf1 <> 0 |] * [| freeable8 buf1 (length bs1) |]\n                      * [| V \"matched\" = Array.selN (lenl cols1)\n                        (findCol (Schema (Table av1)) col1) |]\n                      * [| V \"tmp\" = Array.selN (posl cols1)\n                        (findCol (Schema (Table av1)) col1) |])\n                    * (Ex buf2, Ex len2, Ex cols2, Ex bs2,\n                      (V (Data av2) ==*> buf2, len2)\n                      * array (posl cols2) (V (Data av2) ^+ $8)\n                      * array (lenl cols2) (V (Data av2) ^+ $8\n                        ^+ $(length (Schema (Table av2)) * 4)) * array8 bs2 buf2\n                      * [| length bs2 = wordToNat len2 |]\n                      * [| length cols2 = length (Schema (Table av2)) |]\n                      * [| RelDb.inBounds len2 cols2 |]\n                      * [| V (Data av2) <> 0 |]\n                      * [| freeable (V (Data av2)) (2\n                        + length (Schema (Table av2))\n                        + length (Schema (Table av2))) |]\n                      * [| buf2 <> 0 |] * [| freeable8 buf2 (length bs2) |]\n                      * [| V \"matched\" = Array.selN (lenl cols2)\n                        (findCol (Schema (Table av2)) col2) |]\n                      * [| V \"res\" = Array.selN (posl cols2)\n                        (findCol (Schema (Table av2)) col2) |])\n                  POST[R] Ex bsO', array8 bsI (V \"buf\") * array8 bsO' (V \"obuf\")\n                    * [| length bsO' = length bsO |] * invPost a V R];;\n\n                Note [reveal_row];;\n                Rp <-* Data av2;;\n                \"overflowed\" <-* Data av1;;\n\n                \"res\" <-- Call \"array8\"!\"equal\"(\"overflowed\", \"tmp\", Rp, \"res\", \"matched\")\n                [Al a : A, Al bsI, Al bsO,\n                  PRE[V] array8 bsI (V \"buf\") * array8 bsO (V \"obuf\")\n                    * [| length bsI = wordToNat (V \"len\") |]\n                    * [| length bsO = wordToNat (V \"olen\") |]\n                    * [| inBounds cdatas V |] * [| V \"opos\" <= V \"olen\" |]%word\n                    * invPre a V * cursors V avs * db ts\n                  POST[R] Ex bsO', array8 bsI (V \"buf\")\n                    * array8 bsO' (V \"obuf\") * [| length bsO' = length bsO |]\n                    * invPost a V R];;\n\n                \"overflowed\" <- 0;;\n\n                If (\"res\" = 1) {\n                  clarify (Out' cdatas avs ts inner)\n                } else {\n                  Skip\n                }\n              } else {\n                Note [reveal_row]\n              }\n            } else {\n              Skip\n            }\n          | _, _ => Fail\n        end\n    end%SP.\n\n  Opaque mult.\n\n  Lemma invPre_sel : forall a V, invPre a (sel V) = invPre a V.\n    auto.\n  Qed.\n\n  Lemma invPost_sel : forall a V R, invPost a (sel V) R = invPost a V R.\n    auto.\n  Qed.\n\n  Lemma inBounds_sel : forall cdatas V, inBounds cdatas (sel V) = inBounds cdatas V.\n    auto.\n  Qed.\n\n  Lemma cursors_sel : forall V av, cursors (sel V) av = cursors V av.\n    auto.\n  Qed.\n\n  Lemma cursor_sel : forall V av, cursor (sel V) av = cursor V av.\n    auto.\n  Qed.\n\n  Ltac prep :=\n    clear_fancy; repeat match goal with\n                          | [ H : LabelMap.find _ _ = _ |- _ ] => try rewrite H; clear H\n                          | [ st : (settings * state)%type |- _ ] => destruct st; simpl in *\n                        end;\n    try match goal with\n          | [ _ : context[reveal_row] |- _ ] => unfold cursor, row in *\n        end.\n\n  Ltac reger := repeat match goal with\n                         | [ H : Regs _ _ = _ |- _ ] => rewrite H\n                       end.\n\n  Ltac my_refold :=\n    refold;\n    fold (@length B) in *; fold (@length string) in *;\n      fold (@length (W * W)) in *; fold (@length W) in *.\n\n  Ltac simp :=\n    repeat match goal with\n             | [ H : context[invPre ?a (sel ?V)] |- _ ] => rewrite (invPre_sel a V) in H\n             | [ |- context[invPre ?a (sel ?V)] ] => rewrite (invPre_sel a V)\n             | [ H : context[invPost ?a (sel ?V) ?R] |- _ ] => rewrite (invPost_sel a V R) in H\n             | [ |- context[invPost ?a (sel ?V) ?R] ] => rewrite (invPost_sel a V R)\n             | [ H : context[inBounds ?x (sel ?V)] |- _ ] => rewrite (inBounds_sel x V) in H\n             | [ |- context[inBounds ?x (sel ?V)] ] => rewrite (inBounds_sel x V)\n             | [ H : context[cursors (sel ?V) ?x] |- _ ] => rewrite (cursors_sel V x) in H\n             | [ |- context[cursors (sel ?V) ?x] ] => rewrite (cursors_sel V x)\n             | [ H : context[cursor (sel ?V) ?x] |- _ ] => rewrite (cursor_sel V x) in H\n             | [ |- context[cursor (sel ?V) ?x] ] => rewrite (cursor_sel V x)\n             | [ H : context[inputOk (sel ?V) ?x] |- _ ] => rewrite (inputOk_sel V x) in H\n             | [ |- context[inputOk (sel ?V) ?x] ] => rewrite (inputOk_sel V x)\n           end; reger.\n\n  Ltac prepl := post; unfold lvalIn, regInL, immInR in *;\n    repeat match goal with\n             | [ H : ForallR _ _ |- _ ] => clear H\n             | [ H : List.Forall _ _ |- _ ] => clear H\n             | [ H : importsGlobal _ |- _ ] =>\n               repeat match goal with\n                        | [ H' : context[H] |- _ ] => clear H'\n                      end; clear H\n           end; prep_locals; simp; try rewrite mult4_S in *;\n    try match goal with\n          | [ H : cdatasGood _, H' : In _ _ |- _ ] =>\n            specialize (proj1 (Forall_forall _ _) H _ H'); simpl; intuition idtac\n        end;\n    try rewrite natToW_4times in *.\n\n  Ltac my_descend :=\n    try match goal with\n          | [ H : inBounds _ _, H' : In _ _ |- _ ] =>\n            rewrite <- inBounds_sel in H;\n              specialize (proj1 (Forall_forall _ _) H _ H'); simpl; intuition idtac;\n                rewrite inBounds_sel in H\n        end;\n    repeat match goal with\n             | [ H : evalInstrs _ _ _ = _ |- _ ] => clear H\n             | [ H : evalCond _ _ _ _ _ = _ |- _ ] => clear H\n             | [ H : In _ ?ls |- _ ] =>\n               match type of ls with\n                 | schema => fail 1\n                 | list table => fail 1\n                 | list avail => fail 1\n                 | _ => clear H\n               end\n             | [ x : (_ * _)%type |- _ ] => destruct x; simpl in *\n           end;\n    unfold invar, localsInvariant; descend;\n      simp; reger;\n      try match goal with\n            | [ |- context[match ?U with pair _ _ => _ end] ] =>\n              match type of U with\n                | prod ?A ?B =>\n                  let x := fresh in let y := fresh in\n                    evar (x : A); evar (y : B); let x' := eval unfold x in x in\n                      let y' := eval unfold y in y in equate U (x', y'); clear x y; simpl\n              end\n          end; autorewrite with sepFormula in *; my_refold.\n  \n  Ltac deSpec :=\n    repeat match goal with\n             | [ H : LabelMap.find _ _ = _ |- _ ] => try rewrite H; clear H\n           end.\n\n  Ltac invoke1 :=\n    match goal with\n      | [ H : interp _ _, H' : _ |- _ ] => apply H' in H; clear H'\n      | [ |- vcs (_ :: _) ] => wrap0; try discriminate\n      | [ H : _ |- vcs _ ] => apply vcs_app_fwd || apply H\n    end; post.\n\n  Lemma cursor_wiggle : forall V' V P avs a,\n    goodCursors avs\n    -> (forall x, x <> \"overflowed\" -> x <> \"opos\" ->\n      x <> \"tmp\" -> x <> \"matched\" -> x <> \"res\" -> sel V x = sel V' x)\n    -> invPre a V ===> invPre a V'\n    -> invPre a V * (cursors V avs * P)\n    ===> P * (invPre a V' * cursors V' avs).\n    clear; sepLemma; apply himp_star_frame.\n    apply weaken_cursors; auto.\n    auto.\n  Qed.\n\n  Ltac bash :=\n    try match goal with\n          | [ H : context[invPost] |- ?P = ?Q ] =>\n            match P with\n              | context[invPost ?a ?V _] =>\n                match Q with\n                  | context[invPost a ?V' _] =>\n                    rewrite (H a V V') by intuition; reflexivity\n                end\n            end\n        end;\n\n    match goal with\n      | [ |- interp _ (![?pre] _ ---> ![?post] _)%PropX ] =>\n        match post with\n          | context[locals ?ns ?vs ?avail _] =>\n            match pre with\n              | context[excessStack _ ns avail ?ns' ?avail'] =>\n                match avail' with\n                  | avail => fail 1\n                  | _ =>\n                    match pre with\n                      | context[locals ns ?vs' 0 ?sp] =>\n                        match goal with\n                          | [ _ : _ = sp |- _ ] => fail 1\n                          | _ => equate vs vs';\n                            let offset := eval simpl in (4 * List.length ns) in\n                              rewrite (create_locals_return ns' avail' ns avail offset);\n                                assert (ok_return ns ns' avail avail' offset)%nat by (split; [\n                                  simpl; omega\n                                  | reflexivity ] ); autorewrite with sepFormula in *;\n                                cancel auto_ext\n                        end\n                    end\n                end\n            end\n        end\n      | _ => weaken_invPre\n      | [ _ : context[reveal_row] |- _ ] => try match_locals; step RelDb.hints\n      | _ => try match_locals; step auto_ext\n    end;\n    try (apply removeTable_bwd'; solve [ eauto ]);\n    try (apply removeTable_fwd'; solve [ eauto ]);\n    try apply make_cursor; try apply unmake_cursor;\n    try (apply matchup; solve [ auto ]);\n    try (apply matchup2; solve [ auto ]);\n    try (apply cursor_wiggle; solve [ descend; try apply goodCursors_removeCursor; auto ]);\n    try (etransitivity; [ apply himp_star_comm | ]; apply himp_star_frame; try reflexivity;\n      apply release_cursor; eauto);\n    try (etransitivity; [ | (apply cursor_expand || apply cursor_expand'); try eassumption ];\n      match goal with\n        | [ |- himp _ _ _ ] => unfold row; simpl; bash\n        | _ => descend; eauto\n      end).\n\n  Ltac desc := my_descend;\n    [ try match goal with\n            | [ _ : context[reveal_row], H : goodCursors _, H' : In _ _ |- _ ] =>\n              destruct (proj1 (Forall_forall _ _) H _ H');\n                simpl in *; intuition idtac\n          end | .. ].\n\n  Ltac t := post; repeat invoke1; prep; propxFo;\n    repeat invoke1; prepl; evaluate auto_ext;\n      desc; (repeat (bash; my_descend); eauto).\n\n  Notation \"l ~~ im ~~> s\" := (LabelMap.find l%SP im = Some (Precondition s None)) (at level 0).\n\n  Section Out_correct.\n    Variables (ns : list string) (res : nat).\n\n    Hypothesis Hrp : ~In \"rp\" ns.\n    Hypothesis Hobuf : In \"obuf\" ns.\n    Hypothesis Holen : In \"olen\" ns.\n    Hypothesis Hopos : In \"opos\" ns.\n    Hypothesis Hoverflowed : In \"overflowed\" ns.\n    Hypothesis Htmp : In \"tmp\" ns.\n    Hypothesis Hbuf : In \"buf\" ns.\n    Hypothesis Hmatched : In \"matched\" ns.\n    Hypothesis HresV : In \"res\" ns.\n\n    Hypothesis Hres : (res >= 11)%nat.\n\n    Ltac split_IH :=\n      match goal with\n        | [ IH : forall pre : settings * state -> _, _ |- _ ] =>\n          (generalize (fun a b => proj1 (IH a b));\n            generalize (fun a b => proj2 (IH a b)))\n          || (generalize (fun a b c => proj1 (IH a b c));\n            generalize (fun a b c => proj2 (IH a b c))); clear IH; intros\n        | [ H : forall start len : string, _ |- _ ] =>\n          generalize (fun start len H' => H start len (or_introl _ H'));\n            specialize (fun start len H' => H start len (or_intror _ H')); intro\n        | [ H : forall (data : string) (sch : schema), _ |- _ ] =>\n          generalize (fun start len H' => H start len (or_introl _ H'));\n            specialize (fun start len H' => H start len (or_intror _ H')); intro\n      end.\n\n    Lemma OutList_correct : forall cdatas, cdatasGood cdatas\n      -> forall xms,\n        List.Forall\n        (fun xm => forall avs ts pre im mn (H : importsGlobal im),\n          \"array8\"!\"copy\" ~~ im ~~> copyS\n          -> \"array8\"!\"equal\" ~~ im ~~> equalS\n          -> wf ns cdatas avs ts xm\n          -> (forall start len, freeVar xm (start, len) -> In (start, len) cdatas)\n          -> (forall start len, freeVar xm (start, len) -> In start ns /\\ In len ns)\n          -> (forall specs st, interp specs (pre st)\n            -> interp specs (invar cdatas avs ts true (fun x => x) ns res st))\n          -> (forall rw data, bindsRowVar xm (rw, data) -> In rw ns /\\ In data ns)\n          -> goodCursors avs\n          -> twfs ts\n          -> NoDups avs ts\n          -> (forall a V V',\n            (forall x, x <> \"overflowed\" -> x <> \"opos\" -> x <> \"tmp\" -> x <> \"matched\" ->\n              x <> \"res\" -> x <> \"ipos\" -> x <> \"ilen\" -> x <> \"ibuf\" ->\n              (forall rw data, bindsRowVar xm (rw, data) -> x <> rw /\\ x <> data)\n              -> sel V x = sel V' x) -> invPre a V ===> invPre a V')\n          -> (forall a V V' R,\n            (forall x, x <> \"overflowed\" -> x <> \"opos\" -> x <> \"tmp\" -> x <> \"matched\" ->\n              x <> \"res\" -> x <> \"ipos\" -> x <> \"ilen\" -> x <> \"ibuf\" ->\n              (forall rw data, bindsRowVar xm (rw, data) -> x <> rw /\\ x <> data)\n              -> sel V x = sel V' x) -> invPost a V R = invPost a V' R)\n          -> (forall specs st,\n            interp specs (Postcondition (toCmd (Out' cdatas avs ts xm) mn H ns res pre) st)\n            -> interp specs (invar cdatas avs ts true (fun x => x) ns res st))\n          /\\ vcs (VerifCond (toCmd (Out' cdatas avs ts xm) mn H ns res pre))) xms\n        -> forall avs ts, ForallR (wf ns cdatas avs ts) xms\n        -> forall pre im mn (H : importsGlobal im),\n          \"array8\"!\"copy\" ~~ im ~~> copyS\n          -> \"array8\"!\"equal\" ~~ im ~~> equalS\n          -> (forall start len, ExistsR (fun xm => freeVar xm (start, len)) xms -> In (start, len) cdatas)\n          -> (forall start len, ExistsR (fun xm => freeVar xm (start, len)) xms -> In start ns /\\ In len ns)\n          -> (forall specs st, interp specs (pre st)\n            -> interp specs (invar cdatas avs ts true (fun x => x) ns res st))\n          -> (forall rw data, ExistsR (fun xm => bindsRowVar xm (rw, data)) xms -> In rw ns /\\ In data ns)\n          -> goodCursors avs\n          -> twfs ts\n          -> NoDups avs ts\n          -> (forall a V V',\n            (forall x, x <> \"overflowed\" -> x <> \"opos\" -> x <> \"tmp\" -> x <> \"matched\" ->\n              x <> \"res\" -> x <> \"ipos\" -> x <> \"ilen\" -> x <> \"ibuf\" ->\n              (forall rw data, ExistsR (fun xm => bindsRowVar xm (rw, data)) xms -> x <> rw /\\ x <> data)\n              -> sel V x = sel V' x) -> invPre a V ===> invPre a V')\n          -> (forall a V V' R,\n            (forall x, x <> \"overflowed\" -> x <> \"opos\" -> x <> \"tmp\" -> x <> \"matched\" ->\n              x <> \"res\" -> x <> \"ipos\" -> x <> \"ilen\" -> x <> \"ibuf\" ->\n              (forall rw data, ExistsR (fun xm => bindsRowVar xm (rw, data)) xms -> x <> rw /\\ x <> data)\n              -> sel V x = sel V' x) -> invPost a V R = invPost a V' R)\n          -> (forall specs st, interp specs (Postcondition (toCmd (OutList (Out' cdatas avs ts ) xms) mn H ns res pre) st)\n            -> interp specs (invar cdatas avs ts true (fun x => x) ns res st))\n          /\\ vcs (VerifCond (toCmd (OutList (Out' cdatas avs ts) xms) mn H ns res pre)).\n      induction 2; simpl; intuition auto 1; split; intros; try apply vcs_app_fwd;\n        repeat match goal with\n                 | [ H : _ |- vcs _ ] => eapply H; eauto; intros\n                 | [ H : _ |- _ ] => eapply H; [ .. | eassumption ]; eauto; intros\n               end.\n    Qed.\n\n    Hint Extern 1 (goodSize _) => eapply goodSize_weaken; [ eassumption | omega ].\n\n    Lemma inBounds_weaken : forall cdatas V V',\n      cdatasGood cdatas\n      -> inBounds cdatas V\n      -> (forall x, x <> \"overflowed\" -> x <> \"opos\" -> x <> \"tmp\" -> x <> \"matched\"\n        -> x <> \"res\" -> sel V x = sel V' x)\n      -> inBounds cdatas V'.\n      intros; rewrite <- inBounds_sel in *;\n        eapply Forall_impl2; [ match goal with\n                                 | [ H : cdatasGood _ |- _ ] => apply H\n                               end\n          | match goal with\n              | [ H : inBounds _ _ |- _ ] => apply H\n            end\n          | ]; cbv beta; intuition idtac;\n        match goal with\n          | [ H : forall x : string, _ |- _ ] => repeat rewrite <- H by congruence; assumption\n        end.\n    Qed.\n\n    Hint Extern 1 (inBounds _ _) => eapply inBounds_weaken; [ eassumption | eassumption\n      | descend ].\n\n    Ltac deDouble :=\n      repeat match goal with\n               | [ H : forall start len : string, _ |- _ ] =>\n                   specialize (H _ _ eq_refl)\n               | [ H : forall (data' : string) (sch' : schema), _ |- _ ] =>\n                   specialize (H _ _ eq_refl)\n               | [ H : forall rw data : string, _ \\/ _ -> _ |- _ ] =>\n                 generalize (H _ _ (or_introl _ eq_refl));\n                   specialize (fun x y H' => H x y (or_intror _ H')); intuition idtac\n             end.\n\n    Ltac clear_fancier :=\n      repeat match goal with\n               | [ H : importsGlobal _ |- _ ] => clear dependent H\n               | [ H : wf _ _ _ _ _ |- _ ] => clear H\n               | [ H : ForallR _ _ |- _ ] => clear H\n               | [ H : List.Forall _ _ |- _ ] => clear H\n             end; clear_fancy.\n\n    Ltac proveHimp :=\n      simpl; repeat match goal with\n                      | [ V : vals |- _ ] =>\n                        progress repeat match goal with\n                                          | [ |- context[V ?x] ] => change (V x) with (sel V x)\n                                        end\n                    end;\n      try match goal with\n            | [ H : forall x : string, _ |- _ ] => repeat rewrite H by congruence\n          end;\n      try match goal with\n            | [ H : context[invPost] |- context[?P = ?Q] ] =>\n              match P with\n                | context[invPost ?a ?V ?r] =>\n                  match Q with\n                    | context[invPost a ?V' r] =>\n                      rewrite (H a V V') by intuition\n                  end\n              end\n          end; reflexivity || clear_fancier; sepLemma; eauto; apply himp_star_frame; eauto.\n\n    Lemma convert : forall a b c : W,\n      a < b ^- c\n      -> c <= b\n      -> c ^+ a <= b.\n      clear; intros.\n      pre_nomega.\n      rewrite wordToNat_wplus in *.\n      omega.\n      apply goodSize_weaken with (wordToNat b); eauto.\n    Qed.\n\n    Hint Immediate convert.\n\n    Hint Extern 1 (himp _ _ _) =>\n      apply himp_star_frame; try reflexivity; [].\n\n    Hint Extern 1 (himp _ (invPre _ _) (invPre _ _)) =>\n      match goal with\n        | [ H : _ |- _ ] => apply H; solve [ descend; auto 1 ]\n      end.\n\n    Hint Extern 1 (invPre _ _ ===> invPre _ _) =>\n      match goal with\n        | [ H : _ |- _ ] => apply H; solve [ descend; auto 1 ]\n      end.\n\n    Hint Extern 1 (himp _ (invPost ?a ?b ?c) (invPost ?a ?b' ?c)) =>\n      match goal with\n        | [ HinvPost : context[invPost] |- _ ] =>\n          rewrite (HinvPost a b b' c) by descend; reflexivity\n      end.\n\n    Lemma convert' : forall (a b c : W) n,\n      a < b ^- c\n      -> c <= b\n      -> n = wordToNat b\n      -> (wordToNat c + wordToNat a <= n)%nat.\n      clear; intros; subst.\n      pre_nomega.\n      omega.\n    Qed.\n\n    Hint Immediate convert'.\n\n    Ltac vcgen_simp :=\n      cbv beta iota zeta\n        delta [map app imps Entry Blocks Postcondition VerifCond\n          Straightline_ Seq_ Diverge_ Fail_ Skip_ Assert_ Structured.If_\n          Structured.While_ Goto_ Structured.Call_ IGoto setArgs Reserved\n          Formals Precondition importsMap fullImports buildLocals blocks union\n          N.add N.succ Datatypes.length N.of_nat fold_left ascii_lt string_lt\n          label'_lt LabelKey.compare' LabelKey.compare LabelKey.eq_dec\n          toCmd Seq Instr Diverge Fail Skip Assert_ If_ While_\n          Goto Call_ RvImm' Assign' localsInvariant localsInvariantCont regInL\n          lvalIn immInR labelIn string_eq ascii_eq andb Bool.eqb\n          qspecOut ICall_ Structured.ICall_ Assert_ Structured.Assert_\n          string_dec Ascii.ascii_dec string_rec string_rect\n          sumbool_rec sumbool_rect Ascii.ascii_rec Ascii.ascii_rect\n          Bool.bool_dec bool_rec bool_rect eq_rec_r eq_rec eq_rect eq_sym fst\n          snd Ascii.N_of_ascii Ascii.N_of_digits N.compare N.mul\n          Pos.compare Pos.compare_cont Pos.mul Pos.add\n          Int.Z_as_Int.gt_le_dec Int.Z_as_Int.ge_lt_dec\n          ZArith_dec.Z_gt_le_dec Int.Z_as_Int.plus Int.Z_as_Int.max\n          ZArith_dec.Z_gt_dec Int.Z_as_Int._1 BinInt.Z.add\n          Int.Z_as_Int._0 Int.Z_as_Int._2 BinInt.Z.max ZArith_dec.Zcompare_rec\n          ZArith_dec.Z_ge_lt_dec BinInt.Z.compare ZArith_dec.Zcompare_rect\n          ZArith_dec.Z_ge_dec label'_eq label'_rec label'_rect COperand1 CTest\n          COperand2 Pos.succ makeVcs Note_ Note__ IGotoStar_ IGotoStar\n          AssertStar_ AssertStar Cond_ Cond\n          Wrap WrapC SimpleSeq StringWrite clarify];\n        my_refold.\n\n    Ltac step1 :=\n      match goal with\n        | [ |- context[Select] ] =>\n          simpl; propxFo; erewrite findTable_good in * by eauto;\n            deDouble; intuition subst;\n              try match goal with\n                    | [ |- vcs _ ] => wrap0\n                  end; eauto;\n              try match goal with\n                    | [ IH : _ |- vcs _ ] =>\n                      eapply IH; clear IH; eauto\n                    | [ IH : _, H : interp _ (Postcondition _ _) |- _ ] =>\n                      apply IH in H; clear IH; eauto\n                  end\n        | [ |- context[Column] ] =>\n          simpl; intros;\n            match goal with\n              | [ H : Logic.ex _ |- _ ] => destruct H as [ ? [ ? [ ] ] ]\n            end; erewrite findCursor_good by eauto; vcgen_simp;\n            post; try match goal with\n                        | [ |- vcs (_ :: _) ] => wrap0; try discriminate\n                      end\n        | [ |- context[IfEqual] ] =>\n          simpl; propxFo;\n            do 2 erewrite findCursor_good in * by eauto;\n              try match goal with\n                    | [ H : interp _ _ |- _ ] =>\n                      generalize dependent H; vcgen_simp; propxFo\n                  end;\n              match goal with\n                | [ |- vcs _ ] =>\n                  vcgen_simp; wrap0;\n                  try match goal with\n                        | [ |- vcs _] => fold (@app Prop); wrap0;\n                          rewrite toCmd'_eq; match goal with\n                                               | [ IH : _ |- _ ] => apply IH; eauto\n                                             end\n                      end\n                | _ => deDouble; intuition subst;\n                  match goal with\n                    | [ H : interp _ _, IH : _ |- _ ] =>\n                      rewrite toCmd'_eq in H;\n                        apply IH in H; eauto; [ | clear H ]; (deSpec; t)\n                  end\n                | _ => idtac\n              end\n        | _ =>\n          intros; split; unfold Out'; match goal with\n                                        | [ |- context[OutList] ] => simpl\n                                        | _ => vcgen_simp\n                                      end;\n            post; try match goal with\n                        | [ |- vcs (_ :: _) ] => wrap0; try discriminate\n                      end;\n            try match goal with\n                  | _ => apply OutList_correct; auto\n                  | [ H : _ |- _ ] => apply OutList_correct in H; auto\n                end\n      end.\n\n    Ltac step2 := abstract (deDouble; deSpec; intuition subst;\n      solve [ t | proveHimp ]).\n\n    Lemma cursor_survived : forall tab t avs,\n      In t avs\n      -> tab <> Name (Table t)\n      -> In t (removeCursor tab avs).\n      clear; induction avs; simpl; intuition;\n        ift; simpl; intuition.\n    Qed.\n\n    Hint Immediate cursor_survived.\n\n    Lemma NoDup_survived' : forall tab' tab avs,\n      In tab' (ANames (removeCursor tab avs))\n      -> In tab' (ANames avs).\n      clear; induction avs; simpl; intuition;\n        generalize dependent H; ift; simpl in *; intuition.\n    Qed.\n\n    Lemma NoDup_survived : forall tab avs,\n      NoDup (ANames avs)\n      -> NoDup (ANames (removeCursor tab avs)).\n      clear; induction avs; inversion_clear 1; simpl; intuition.\n      ift; simpl; intuition eauto using NoDup_survived'.\n    Qed.\n\n    Hint Resolve NoDup_survived.\n\n    Lemma double_cursor_appear : forall V avs av1 av2 P,\n      In av1 avs\n      -> In av2 avs\n      -> Name (Table av1) <> Name (Table av2)\n      -> NoDup (ANames avs)\n      -> cursors V avs * P\n      ===> P * (cursor V av1 * (cursor V av2\n        * cursors V (removeCursor (Name (Table av2))\n          (removeCursor (Name (Table av1)) avs)))).\n      clear; sepLemma.\n      etransitivity; [ apply release_cursor; try apply H; eauto | ]; sepLemma.\n      etransitivity; [ apply release_cursor; eauto | ]; sepLemma.\n    Qed.\n\n    Hint Extern 1 (himp _ _ _) => apply double_cursor_appear.\n\n    Lemma goodSize_goodCursors : forall t avs,\n      In t avs\n      -> goodCursors avs\n      -> goodSize (length (Schema (Table t))).\n      clear; intros.\n      eapply Forall_forall in H0; [ | eassumption ].\n      tauto.\n    Qed.\n\n    Hint Immediate goodSize_goodCursors.\n\n    Lemma sel_upd_Data : forall av x vs v,\n      (exists avs, goodCursors avs /\\ In av avs)\n      -> In x cvars\n      -> sel (upd vs x v) (Data av) = sel vs (Data av).\n      clear; destruct 1; intros; apply sel_upd_ne; intuition.\n      eapply Forall_forall in H2; eauto; intuition.\n    Qed.\n\n    Lemma sel_upd_Row : forall av x vs v,\n      (exists avs, goodCursors avs /\\ In av avs)\n      -> In x cvars\n      -> sel (upd vs x v) (Row av) = sel vs (Row av).\n      clear; destruct 1; intros; apply sel_upd_ne; intuition.\n      eapply Forall_forall in H2; eauto; intuition.\n    Qed.\n\n    Hint Rewrite sel_upd_Data sel_upd_Row\n      using ((simpl; tauto) || (do 2 esplit; eassumption)) : sepFormula.\n\n    Lemma Out_correct : forall cdatas, cdatasGood cdatas\n      -> incl baseVars ns\n      -> forall xm avs ts pre im mn (H : importsGlobal im),\n        \"array8\"!\"copy\" ~~ im ~~> copyS\n        -> \"array8\"!\"equal\" ~~ im ~~> equalS\n        -> wf ns cdatas avs ts xm\n        -> (forall start len, freeVar xm (start, len) -> In (start, len) cdatas)\n        -> (forall start len, freeVar xm (start, len) -> In start ns /\\ In len ns)\n        -> (forall specs st, interp specs (pre st)\n          -> interp specs (invar cdatas avs ts true (fun x => x) ns res st))\n        -> (forall rw data, bindsRowVar xm (rw, data) -> In rw ns /\\ In data ns)\n        -> goodCursors avs\n        -> twfs ts\n        -> NoDups avs ts\n        -> (forall a V V', (forall x, x <> \"overflowed\" -> x <> \"opos\" -> x <> \"tmp\"\n            -> x <> \"matched\" -> x <> \"res\"\n            -> x <> \"ipos\" -> x <> \"ilen\" -> x <> \"ibuf\"\n            -> (forall rw data, bindsRowVar xm (rw, data) -> x <> rw /\\ x <> data)\n            -> sel V x = sel V' x)\n          -> invPre a V ===> invPre a V')\n        -> (forall a V V' R, (forall x, x <> \"overflowed\" -> x <> \"opos\" -> x <> \"tmp\"\n            -> x <> \"matched\" -> x <> \"res\"\n            -> x <> \"ipos\" -> x <> \"ilen\" -> x <> \"ibuf\"\n            -> (forall rw data, bindsRowVar xm (rw, data) -> x <> rw /\\ x <> data)\n            -> sel V x = sel V' x)\n          -> invPost a V R = invPost a V' R)\n        -> (forall specs st, interp specs (Postcondition (toCmd (Out' cdatas avs ts xm) mn H ns res pre) st)\n          -> interp specs (invar cdatas avs ts true (fun x => x) ns res st))\n        /\\ vcs (VerifCond (toCmd (Out' cdatas avs ts xm) mn H ns res pre)).\n      induction xm using xml_ind'.\n\n      step1.\n\n      step2.\n      step2.\n      step2.\n      step2.\n\n      step1.\n\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n\n      step1.\n\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n\n      step1.\n\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n\n      step1.\n\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n\n      step1.\n\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n      step2.\n    Qed.\n  End Out_correct.\n\n  Notation OutVcs cdatas avs ts xm := (fun im ns res =>\n    (~In \"rp\" ns) :: In \"obuf\" ns :: In \"olen\" ns :: In \"opos\" ns :: In \"overflowed\" ns\n    :: In \"tmp\" ns :: In \"buf\" ns :: In \"matched\" ns :: In \"res\" ns\n    :: (forall a V V', (forall x, x <> \"overflowed\" -> x <> \"opos\" -> x <> \"tmp\"\n      -> x <> \"matched\" -> x <> \"res\"\n      -> x <> \"ipos\" -> x <> \"ilen\" -> x <> \"ibuf\"\n      -> (forall rw data, bindsRowVar xm (rw, data) -> x <> rw /\\ x <> data)\n      -> sel V x = sel V' x)\n    -> invPre a V ===> invPre a V')\n    :: (forall a V V' R, (forall x, x <> \"overflowed\" -> x <> \"opos\" -> x <> \"tmp\"\n      -> x <> \"matched\" -> x <> \"res\"\n      -> x <> \"ipos\" -> x <> \"ilen\" -> x <> \"ibuf\"\n      -> (forall rw data, bindsRowVar xm (rw, data) -> x <> rw /\\ x <> data)\n      -> sel V x = sel V' x)\n    -> invPost a V R = invPost a V' R)\n    :: (res >= 11)%nat\n    :: wf ns cdatas avs ts xm\n    :: (forall start len, freeVar xm (start, len) -> In (start, len) cdatas)\n    :: (forall start len, freeVar xm (start, len) -> In start ns /\\ In len ns)\n    :: cdatasGood cdatas\n    :: \"array8\"!\"copy\" ~~ im ~~> copyS\n    :: \"array8\"!\"equal\" ~~ im ~~> equalS\n    :: incl baseVars ns\n    :: (forall rw data, bindsRowVar xm (rw, data) -> In rw ns /\\ In data ns)\n    :: goodCursors avs\n    :: twfs ts%list\n    :: NoDups avs ts%list\n    :: nil).\n\n  Definition Out (cdatas : list (string * string)) (avs : list avail) (ts : tables) (xm : xml) : chunk.\n    refine (WrapC (Out' cdatas avs ts xm)\n      (invar cdatas avs ts)\n      (invar cdatas avs ts)\n      (OutVcs cdatas avs ts xm)\n      _ _); abstract (intros; repeat match goal with\n                                       | [ H : vcs (_ :: _) |- _ ] => inversion_clear H; subst\n                                     end; eapply Out_correct; eauto).\n  Defined.\nEnd Out.\n", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/XmlOutput.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.21591155218523922}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom compcert Require Import Ctypes AST Integers.\nFrom Coq Require Import ZArith.\n\nFrom bpf.comm Require Import Regs rBPFAST.\n\n(** For use to distinguish ALU32 and ALU64 *)\nInductive arch := A32 | A64.\n\nLemma arch_eq: forall (x y: arch), {x=y} + {x<>y}.\nProof.\n  decide equality.\nDefined.\n\nDefinition arch_eqb (a0 a1: arch) : bool :=\n  match a0, a1 with\n  | A32, A32\n  | A64, A64 => true\n  | _, _ => false\n  end.\n\nLemma arch_eqb_true:\n  forall x y, x = y <-> arch_eqb x y = true.\nProof.\n  destruct x, y; simpl; intuition congruence.\nQed.\n\nLemma arch_eqb_false:\n  forall x y, x <> y <-> arch_eqb x y = false.\nProof.\n  destruct x, y; simpl; intuition congruence.\nQed.\n\nDefinition arch2Z (a: arch) : Z :=\n  match a with\n  | A32 => 32%Z\n  | A64 => 64%Z\n  end.\n\n(** For condition flags *)\n(*Inductive signedness := Signed | Unsigned.*)\n\nInductive cond := \n  Eq \n| Gt: signedness -> cond \n| Ge: signedness -> cond\n| Lt: signedness -> cond\n| Le: signedness -> cond\n| SEt \n| Ne\n.\n\nLemma signedness_eq32: forall (s1 s2: signedness), {s1=s2} + {s1<>s2}.\nProof.\n  decide equality.\nDefined.\n\nDefinition signedness_eqb (s1 s2: signedness) :=\n  match s1, s2 with\n  | Signed, Signed\n  | Unsigned, Unsigned => true\n  | _, _ => false\n  end.\n\nLemma signedness_eqb_true:\n  forall x y, x = y <-> signedness_eqb x y = true.\nProof.\n  destruct x, y; simpl; intuition congruence.\nQed.\n\nLemma signedness_eqb_false:\n  forall x y, x <> y <-> signedness_eqb x y = false.\nProof.\n  destruct x, y; simpl; intuition congruence.\nQed.\n\nLemma cond_eq: forall (x y: cond), {x=y} + {x<>y}.\nProof.\n  decide equality. all: apply signedness_eq32.\nDefined.\n\nDefinition cond_eqb (c0 c1: cond): bool :=\n  match c0, c1 with\n  | Eq, Eq\n  | SEt, SEt\n  | Ne, Ne => true\n  | Gt s0, Gt s1\n  | Ge s0, Ge s1\n  | Lt s0, Lt s1\n  | Le s0, Le s1 => signedness_eqb s0 s1\n  | _, _ => false\n  end.\n\nLemma cond_eqb_true:\n  forall x y, x = y <-> cond_eqb x y = true.\nProof.\n  unfold cond_eqb.\n  destruct x, y; simpl; try (rewrite <- signedness_eqb_true); intuition congruence.\nQed.\n\nLemma cond_eqb_false:\n  forall x y, x <> y <-> cond_eqb x y = false.\nProof.\n  unfold cond_eqb.\n  destruct x, y; simpl; try (rewrite <- signedness_eqb_false); intuition congruence.\nQed.\n\nDefinition off := int.\nDefinition imm := int.\n\nInductive binOp: Type :=\n  BPF_ADD | BPF_SUB | BPF_MUL | BPF_DIV | BPF_OR | BPF_AND\n| BPF_LSH | BPF_RSH | BPF_MOD | BPF_XOR | BPF_MOV| BPF_ARSH.\n\nLemma binOp_eq: forall (b1 b2: binOp), {b1=b2} + {b1<>b2}.\nProof.\n  decide equality.\nDefined.\n\nDefinition binOp_eqb (b0 b1: binOp): bool :=\n  match b0, b1 with\n  | BPF_ADD, BPF_ADD\n  | BPF_SUB, BPF_SUB\n  | BPF_MUL, BPF_MUL\n  | BPF_DIV, BPF_DIV\n  | BPF_OR,  BPF_OR\n  | BPF_AND, BPF_AND\n  | BPF_LSH, BPF_LSH\n  | BPF_RSH, BPF_RSH\n  | BPF_MOD, BPF_MOD\n  | BPF_XOR, BPF_XOR\n  | BPF_MOV, BPF_MOV\n  | BPF_ARSH, BPF_ARSH => true\n  | _, _ => false\n  end.\n\nLemma binOp_eqb_true:\n  forall x y, x = y <-> binOp_eqb x y = true.\nProof.\n  destruct x, y; simpl; intuition congruence.\nQed.\n\nLemma binOp_eqb_false:\n  forall x y, x <> y <-> binOp_eqb x y = false.\nProof.\n  destruct x, y; simpl; intuition congruence.\nQed.\n\n(**r BPD_LDDW are splitted into BPD_LDDW_low and BPD_LDDW_high *)\n\nInductive instruction: Type :=\n  (**r ALU64/32*)\n  | BPF_NEG    : arch -> reg -> instruction\n  | BPF_BINARY : arch -> binOp -> reg -> reg+imm -> instruction\n  (**r Branch *)\n  | BPF_JA   : off -> instruction\n  | BPF_JUMP : cond -> reg -> reg+imm -> off -> instruction\n\n  (**r Load *)\n  | BPF_LDDW_low : reg -> imm -> instruction\n  | BPF_LDDW_high : reg -> imm -> instruction\n  (**r Load_x *)\n  | BPF_LDX  : memory_chunk -> reg -> reg -> off -> instruction\n  (**r Store/ Store_x *)\n  | BPF_ST   : memory_chunk -> reg -> reg+imm -> off -> instruction\n  (**r exit *)\n  | BPF_CALL : imm -> instruction\n  | BPF_RET  : instruction\n  | BPF_ERR  : instruction\n.\n\n(*\nDefinition sum_eqb {A B: Type} (eq1 : A -> A -> bool) (eq2 : B -> B -> bool) (x y : sum A B) : bool :=\n  match x, y with\n  | inl r0', inl r1' => eq1  r0' r1'\n  | inr i0', inr i1' => eq2  i0' i1'\n  | _, _ => false\n  end.\n\n\nDefinition bpf_instruction_eqb (a b: instruction) : bool :=\n  match a, b with\n  | BPF_NEG a0 r0, BPF_NEG a1 r1 => arch_eqb a0 a1 && reg_eqb r0 r1\n  | BPF_BINARY a0 b0 r0 ri0, BPF_BINARY a1 b1 r1 ri1 => arch_eqb a0 a1 && binOp_eqb b0 b1 && reg_eqb r0 r1 && sum_eqb reg_eqb Int.eq ri0 ri1\n  | BPF_JA ofs0, BPF_JA ofs1 => Int.eq ofs0 ofs1\n  | BPF_JUMP c0 r0 ri0 ofs0, BPF_JUMP c1 r1 ri1 ofs1 => cond_eqb c0 c1 && reg_eqb r0 r1 && sum_eqb reg_eqb Int.eq ri0 ri1  && Int.eq ofs0 ofs1\n  | BPF_LDDW_low r0 i0, BPF_LDDW_low r1 i1 => reg_eqb r0 r1 && Int.eq i0 i1\n  | BPF_LDDW_high r0 i0, BPF_LDDW_high r1 i1 => reg_eqb r0 r1 && Int.eq i0 i1\n  | BPF_LDX mc0 d0 s0 ofs0, BPF_LDX mc1 d1 s1 ofs1 => chunk_eqb mc0 mc1 && reg_eqb d0 d1 && reg_eqb s0 s1 && Int.eq ofs0 ofs1\n  | BPF_ST mc0 r0 ri0 ofs0, BPF_ST mc1 r1 ri1 ofs1 => chunk_eqb mc0 mc1 && reg_eqb r0 r1 && sum_eqb reg_eqb Int.eq ri0 ri1 && Int.eq ofs0 ofs1\n  | BPF_CALL i0 , BPF_CALL i1 => Int.eq i0 i1\n  | BPF_RET, BPF_RET\n  | BPF_ERR, BPF_ERR => true\n  | _, _ => false\n  end.\n*)\n\nLemma Int_eq_true:\n  forall x y : int, Int.eq x y = true <-> x = y.\nProof.\n  split.\n  apply Int.same_if_eq.\n  intro H; rewrite H; apply Int.eq_true.\nQed.\n\nLemma Int_eq_false:\n  forall x y : int, Int.eq x y = false <-> x <> y.\nProof.\n  split.\n  intro H.\n  assert (Hspec: if Int.eq x y then x = y else x <> y) by apply Int.eq_spec.\n  rewrite H in Hspec.\n  assumption.\n  apply Int.eq_false.\nQed.\n(*\nLemma sum_eqb_true :\n  forall {A B: Type} eq1 eq2\n         (eq1_ok : forall x y, x = y <-> eq1 x y  = true)\n         (eq2_ok : forall x y, x = y <-> eq2 x y  = true)\n    (x y: sum A B),\n  x = y <-> sum_eqb eq1 eq2 x y = true.\nProof.\n  destruct x,y; simpl.\n  - rewrite <- eq1_ok.\n    intuition congruence.\n  - intuition congruence.\n  - intuition congruence.\n  - rewrite <- eq2_ok.\n    intuition congruence.\nQed.\n\nLemma bpf_instruction_eqb_true:\n  forall x y, x = y <-> bpf_instruction_eqb x y = true.\nProof.\n  unfold bpf_instruction_eqb.\n  destruct x, y; try intuition congruence.\n  - rewrite Bool.andb_true_iff.\n    rewrite <- arch_eqb_true.\n    rewrite <- reg_eqb_true.\n    intuition congruence.\n  - rewrite ! Bool.andb_true_iff.\n    rewrite <- arch_eqb_true.\n    rewrite <- reg_eqb_true.\n    rewrite <- sum_eqb_true.\n    rewrite <- binOp_eqb_true.\n    intuition congruence.\n    apply reg_eqb_true.\n    intros. rewrite Int_eq_true.\n    tauto.\n  - rewrite Int_eq_true. intuition congruence.\n  - rewrite! Bool.andb_true_iff.\n    rewrite <- cond_eqb_true.\n    rewrite <- sum_eqb_true.\n    rewrite Int_eq_true.\n    rewrite <- reg_eqb_true.\n    intuition congruence.\n    apply reg_eqb_true.\n    intros. rewrite Int_eq_true.\n    tauto.\n  - rewrite! Bool.andb_true_iff.\n    rewrite <- reg_eqb_true.\n    rewrite Int_eq_true.\n    intuition congruence.\n  - rewrite! Bool.andb_true_iff.\n    rewrite <- reg_eqb_true.\n    rewrite Int_eq_true.\n    intuition congruence.\n  - rewrite! Bool.andb_true_iff.\n    rewrite <- !reg_eqb_true.\n    rewrite Int_eq_true.\n    rewrite <- chunk_eqb_true.\n    intuition congruence.\n  - rewrite! Bool.andb_true_iff.\n    rewrite <- chunk_eqb_true.\n    rewrite <- reg_eqb_true.\n    rewrite <- sum_eqb_true.\n    rewrite Int_eq_true.\n    intuition congruence.\n    apply reg_eqb_true.\n    intros. rewrite Int_eq_true.\n    tauto.\n  -     intros. rewrite Int_eq_true.\n        intuition congruence.\nQed.\n\nLemma bpf_instruction_eqb_false:\n  forall x y, x <> y <-> bpf_instruction_eqb x y = false.\nProof.\n  intros.\n  generalize (bpf_instruction_eqb_true x y).\n  destruct (bpf_instruction_eqb x y); intuition congruence.\nQed.\n*)", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/model/Syntax.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.21588846511546628}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Relational specification of expression simplification. *)\n\nRequire Import Coqlib (* Maps  *)Errors Integers Floats.\nRequire Import AST Linking Memory.\nRequire Import Ctypes Cop Csyntax Clight SimplExpr.\nRequire Import SepBasicCore SepSet SimplMonad Locally.\nImport Maps.PTree.\n\nSection SPEC.\n\nVariable ce: composite_env.\n\nLocal Open Scope free_monad_scope.\n\n(** * Relational specification of the translation. *)\n\n  (** ** Translation of expressions *)\n\n  (** This specification covers:\n- all cases of [transl_lvalue] and [transl_rvalue];\n- two additional cases for [Csyntax.Eparen], so that reductions of [Csyntax.Econdition]\n  expressions are properly tracked;\n- three additional cases allowing [Csyntax.Eval v] C expressions to match\n  any Clight expression [a] that evaluates to [v] in any environment\n  matching the given temporary environment [le].\n   *)\n\n  Definition dest_below (dst: destination) : iProp :=\n    match dst with\n    | For_set sd => & (sd_temp sd)\n    | _ => emp\n    end.\n\n  Definition final (dst: destination) (a: expr) : list statement :=\n    match dst with\n    | For_val => nil\n    | For_effects => nil\n    | For_set sd => do_set sd a\n    end.\n\n  (** Iris version *)\n\n  Definition tr_is_bitfield_access (l: expr) (bf: bitfield) : Prop :=\n  match l with\n  | Efield r f _ =>\n      exists co ofs,\n      match typeof r with\n      | Tstruct id _ =>\n          ce!id = Some co /\\ field_offset ce f (co_members co) = OK (ofs, bf)\n      | Tunion id _ =>\n          ce!id = Some co /\\ union_field_offset ce f (co_members co) = OK (ofs, bf)\n      | _ => False%type\n      end\n  | _ => bf = Full\n  end.\n\n  Definition tr_rvalof (ty : type) (e1 : expr) (ls : list statement) (e : expr) : iProp :=\n    if type_is_volatile ty\n    then\n      (∃ t bf, ⌜ ls = make_set bf t e1 :: nil /\\ tr_is_bitfield_access e1 bf /\\ e = Etempvar t ty⌝ ∗ & t)%I\n    else\n      ⌜ls =nil /\\ e = e1⌝%I.\n\n  Fixpoint tr_expr (le : temp_env) (dst : destination) (e : Csyntax.expr)\n           (sl : list statement ) (a : expr) : iProp :=\n    (<absorb>\n       match e with\n       | Csyntax.Evar id ty =>\n           dest_below dst ∗ ⌜ sl = final dst (Evar id ty) /\\  a = Evar id ty ⌝\n       | Csyntax.Ederef e1 ty =>\n           dest_below dst ∗\n             ∃ sl2 a2, tr_expr le For_val e1 sl2 a2 ∗\n                         ⌜sl = sl2 ++ final dst (Ederef' a2 ty) /\\ a = Ederef' a2 ty⌝\n       | Csyntax.Efield e1 f ty =>\n           dest_below dst ∗\n             ∃ sl2 a2, tr_expr le For_val e1 sl2 a2 ∗\n                         ⌜ sl = sl2 ++ final dst (Efield a2 f ty) /\\ a = Efield a2 f ty ⌝\n       | Csyntax.Eval v ty =>\n           match dst with\n           | For_effects => ⌜sl = nil⌝\n           | For_val =>\n               (∀ tge e m, locally le (fun le' => ⌜eval_expr tge e le' m a v⌝))\n                 ∗ ⌜ typeof a = ty /\\ sl = nil ⌝\n           | For_set sd =>\n               (<absorb> dest_below dst) ∧\n                 ∃ a,\n                   (∀ tge e m, locally le (fun le' => ⌜eval_expr tge e le' m a v⌝))\n                     ∗ ⌜ typeof a = ty /\\ sl = do_set sd a ⌝\n\n           end\n       | Csyntax.Esizeof ty' ty =>\n           dest_below dst ∗ ⌜ sl = final dst (Esizeof ty' ty) /\\ a = Esizeof ty' ty⌝\n       | Csyntax.Ealignof ty' ty =>\n           dest_below dst ∗ ⌜ sl = final dst (Ealignof ty' ty) /\\ a = Ealignof ty' ty ⌝\n       | Csyntax.Evalof e1 ty =>\n           dest_below dst ∗\n             ∃ sl2 a2 sl3,\n               tr_expr le For_val e1 sl2 a2  ∗\n                 tr_rvalof (Csyntax.typeof e1) a2 sl3 a  ∗\n                 ⌜ sl = (sl2 ++ sl3 ++ final dst a) ⌝\n       | Csyntax.Eaddrof e1 ty =>\n           dest_below dst ∗\n             ∃ sl2 a2, tr_expr le For_val e1 sl2 a2  ∗\n                         ⌜ sl = sl2 ++ final dst (Eaddrof' a2 ty) /\\ a = Eaddrof' a2 ty ⌝\n       | Csyntax.Eunop ope e1 ty =>\n           dest_below dst ∗\n             ∃ sl2 a2, tr_expr le For_val e1 sl2 a2  ∗\n                         ⌜ sl = sl2 ++ final dst (Eunop ope a2 ty) /\\ a = Eunop ope a2 ty ⌝\n       | Csyntax.Ebinop ope e1 e2 ty =>\n           dest_below dst ∗\n             ∃ sl2 a2 sl3 a3, tr_expr le For_val e1 sl2 a2  ∗\n                                tr_expr le For_val e2 sl3 a3  ∗\n                                ⌜ sl = sl2 ++ sl3 ++ final dst (Ebinop ope a2 a3 ty) /\\ a = Ebinop ope a2 a3 ty ⌝\n       | Csyntax.Ecast e1 ty =>\n           match dst with\n           | For_val | For_set _ =>\n                         dest_below dst ∗\n                           ∃ sl2 a2, tr_expr le For_val e1 sl2 a2  ∗\n                                       ⌜ sl = sl2 ++ final dst (Ecast a2 ty) /\\ a = Ecast a2 ty ⌝\n           | For_effects =>\n               tr_expr le For_effects e1 sl a\n           end\n       | Csyntax.Eseqand e1 e2 ty =>\n           match dst with\n           | For_val =>\n               ∃ sl2 a2 sl3 a3 t,\n       tr_expr le For_val e1 sl2 a2 ∗\n         tr_expr le (For_set (sd_seqbool_val t ty)) e2 sl3 a3 ∗\n         ⌜ sl = sl2 ++ makeif a2 (makeseq sl3) (Sset t (Econst_int Int.zero ty)) :: nil /\\\n         a = Etempvar t ty ⌝\n    | For_effects =>\n        ∃ sl2 a2 sl3 a3,\n       tr_expr le For_val e1 sl2 a2 ∗\n         tr_expr le For_effects e2 sl3 a3  ∗\n         ⌜  sl = sl2 ++ makeif a2 (makeseq sl3) Sskip :: nil ⌝\n    | For_set sd =>\n        ∃ sl2 a2 sl3 a3,\n       tr_expr le For_val e1 sl2 a2 ∗\n         tr_expr le (For_set (sd_seqbool_set ty sd)) e2 sl3 a3 ∗\n         ⌜ sl = sl2 ++ makeif a2 (makeseq sl3) (makeseq (do_set sd (Econst_int Int.zero ty))) :: nil ⌝\n     end\n    | Csyntax.Eseqor e1 e2 ty =>\n        match dst with\n        | For_val =>\n            ∃ sl2 a2 sl3 a3 t,\n       tr_expr le For_val e1 sl2 a2  ∗\n         tr_expr le (For_set (sd_seqbool_val t ty)) e2 sl3 a3 ∗\n         ⌜ sl = sl2 ++ makeif a2 (Sset t (Econst_int Int.one ty)) (makeseq sl3) :: nil /\\\n         a = Etempvar t ty ⌝\n    | For_effects =>\n        ∃ sl2 a2 sl3 a3,\n       tr_expr le For_val e1 sl2 a2  ∗\n         tr_expr le For_effects e2 sl3 a3  ∗\n         ⌜ sl = sl2 ++ makeif a2 Sskip (makeseq sl3) :: nil ⌝\n    | For_set sd =>\n        ∃ sl2 a2 sl3 a3,\n       tr_expr le For_val e1 sl2 a2 ∗\n       tr_expr le (For_set (sd_seqbool_set ty sd)) e2 sl3 a3 ∗\n       ⌜ sl = sl2 ++ makeif a2 (makeseq (do_set sd (Econst_int Int.one ty))) (makeseq sl3) :: nil ⌝\n     end\n\n    | Csyntax.Econdition e1 e2 e3 ty =>\n      match dst with\n      | For_val =>\n        ∃ sl2 a2 sl3 a3 sl4 a4 t,\n       tr_expr le For_val e1 sl2 a2 ∗\n       (tr_expr le (For_set (SDbase ty ty t)) e2 sl3 a3 ∧\n       tr_expr le (For_set (SDbase ty ty t)) e3 sl4 a4) ∗\n       ⌜ sl = sl2 ++ makeif a2 (makeseq sl3) (makeseq sl4) :: nil /\\ a = Etempvar t ty⌝\n    | For_effects =>\n      ∃ sl2 a2 sl3 a3 sl4 a4,\n       tr_expr le For_val e1 sl2 a2  ∗\n       tr_expr le For_effects e2 sl3 a3 ∗\n       tr_expr le For_effects e3 sl4 a4 ∗\n       ⌜ sl = sl2 ++ makeif a2 (makeseq sl3) (makeseq sl4) :: nil ⌝\n    | For_set sd =>\n      dest_below dst ∗\n      ∃ sl2 a2 sl3 a3 sl4 a4 t,\n      tr_expr le For_val e1 sl2 a2  ∗\n      (tr_expr le (For_set (SDcons ty ty t sd)) e2 sl3 a3 ∧\n      tr_expr le (For_set (SDcons ty ty t sd)) e3 sl4 a4) ∗\n      ⌜ sl = sl2 ++ makeif a2 (makeseq sl3) (makeseq sl4) :: nil ⌝\n     end\n    | Csyntax.Eassign e1 e2 ty =>\n      match dst with\n      | For_val | For_set _ =>\n          ∃ sl2 a2 sl3 a3 t bf,\n       tr_expr le For_val e1 sl2 a2  ∗\n       tr_expr le For_val e2 sl3 a3  ∗\n       & t ∗\n       dest_below dst ∗\n       ⌜ tr_is_bitfield_access a2 bf /\\\n         sl = sl2 ++ sl3 ++ Sset t (Ecast a3 (Csyntax.typeof e1)) ::\n                make_assign bf a2 (Etempvar t (Csyntax.typeof e1)) ::\n                final dst (make_assign_value bf (Etempvar t (Csyntax.typeof e1))) /\\\n         a = make_assign_value bf (Etempvar t (Csyntax.typeof e1))⌝\n       | For_effects =>\n       ∃ sl2 a2 sl3 a3 bf,\n       tr_expr le For_val e1 sl2 a2  ∗\n       tr_expr le For_val e2 sl3 a3  ∗\n       ⌜ tr_is_bitfield_access a2 bf /\\ sl = sl2 ++ sl3 ++ make_assign bf a2 a3 :: nil ⌝\n     end\n\n    | Csyntax.Eassignop ope e1 e2 tyres ty =>\n      match dst with\n      | For_effects =>\n        ∃ sl2 a2 sl3 a3 sl4 a4 bf,\n       tr_expr le For_val e1 sl2 a2  ∗\n       tr_expr le For_val e2 sl3 a3  ∗\n       tr_rvalof (Csyntax.typeof e1) a2 sl4 a4  ∗\n       ⌜tr_is_bitfield_access a2 bf /\\ sl = sl2 ++ sl3 ++ sl4 ++ make_assign bf a2 (Ebinop ope a4 a3 tyres) :: nil ⌝\n    | _ =>\n      dest_below dst ∗ ∃ sl2 a2 sl3 a3 sl4 a4 bf t,\n       tr_expr le For_val e1 sl2 a2  ∗\n       tr_expr le For_val e2 sl3 a3  ∗\n       tr_rvalof (Csyntax.typeof e1) a2 sl4 a4  ∗\n       & t ∗\n       ⌜ tr_is_bitfield_access a2 bf /\\\n         sl = sl2 ++ sl3 ++ sl4 ++ Sset t (Ecast (Ebinop ope a4 a3 tyres) (Csyntax.typeof e1)) ::\n                make_assign bf a2 (Etempvar t (Csyntax.typeof e1)) ::\n                final dst (make_assign_value bf (Etempvar t (Csyntax.typeof e1)))\n       /\\ a = make_assign_value bf (Etempvar t (Csyntax.typeof e1)) ⌝\n     end\n    | Csyntax.Epostincr id e1 ty =>\n      ∃ sl2 a2 bf,\n       tr_expr le For_val e1 sl2 a2  ∗\n       match dst with\n       | For_effects =>\n         ∃ sl3 a3,\n       tr_rvalof (Csyntax.typeof e1) a2 sl3 a3  ∗\n       ⌜ tr_is_bitfield_access a2 bf /\\\n        sl = sl2 ++ sl3 ++ make_assign bf a2 (transl_incrdecr id a3 (Csyntax.typeof e1)) :: nil ⌝\n    | _ =>\n      dest_below dst ∗\n      ∃ t, & t  ∗\n      ⌜ tr_is_bitfield_access a2 bf /\\\n        sl = sl2 ++ make_set bf t a2 :: make_assign bf a2 (transl_incrdecr id (Etempvar t (Csyntax.typeof e1)) (Csyntax.typeof e1)) :: final dst (Etempvar t (Csyntax.typeof e1))\n           /\\ a = Etempvar t (Csyntax.typeof e1)⌝\n     end\n\n    | Csyntax.Ecomma e1 e2 ty =>\n      ∃ sl2 a2 sl3,\n       tr_expr le For_effects e1 sl2 a2  ∗\n       tr_expr le dst e2 sl3 a ∗\n       ⌜ sl = sl2 ++ sl3 ⌝\n\n    | Csyntax.Ecall e1 el2 ty =>\n      match dst with\n      | For_effects =>\n        ∃ sl2 a2 sl3 al3,\n       tr_expr le For_val e1 sl2 a2  ∗\n       tr_exprlist le el2 sl3 al3  ∗\n       ⌜  sl = sl2 ++ sl3 ++ Scall None a2 al3 :: nil ⌝\n    | _ =>\n      dest_below dst ∗ ∃ sl2 a2 sl3 al3 t,\n       & t ∗\n        tr_expr le For_val e1 sl2 a2  ∗\n        tr_exprlist le el2 sl3 al3  ∗\n        ⌜ sl = sl2 ++ sl3 ++ Scall (Some t) a2 al3 :: final dst (Etempvar t ty) /\\\n       a = Etempvar t ty⌝\n     end\n\n    | Csyntax.Ebuiltin ef tyargs el ty =>\n      match dst with\n      | For_effects =>\n        ∃ sl2 al2,\n       tr_exprlist le el sl2 al2 ∗\n       ⌜ sl = sl2 ++ Sbuiltin None ef tyargs al2 :: nil ⌝\n    | _ =>\n      dest_below dst ∗ ∃ sl2 al2 t,\n       tr_exprlist le el sl2 al2  ∗\n       & t  ∗\n       ⌜ sl = sl2 ++ Sbuiltin (Some t) ef tyargs al2 :: final dst (Etempvar t ty) /\\\n       a = Etempvar t ty⌝\n     end\n    | Csyntax.Eparen e1 tycast ty =>\n      match dst with\n      | For_val =>\n        ∃ a2 t, tr_expr le (For_set (SDbase tycast ty t)) e1 sl a2 ∗ ⌜ a = Etempvar t ty ⌝\n    | For_effects =>\n      ∃ a2, tr_expr le For_effects e1 sl a2\n    | For_set sd =>\n      ∃ a2 t0, if Pos.eq_dec t0 (sd_temp sd)\n               then\n                 tr_expr le (For_set (SDcons tycast ty t0 sd)) e1 sl a2\n               else\n                 tr_expr le (For_set (SDcons tycast ty t0 sd)) e1 sl a2 ∗ dest_below dst\n     end\n\n| _ => False\n  end)\n  with tr_exprlist (le : temp_env) (e : Csyntax.exprlist) (sl : list statement) (a : list expr) : iProp :=\n         match e with\n         | Csyntax.Enil => ⌜ sl = nil /\\ a = nil⌝\n         | Csyntax.Econs e1 el2 =>\n           ∃ sl2 a2 sl3 al3,\n    tr_expr le For_val e1 sl2 a2  ∗\n    tr_exprlist le el2 sl3 al3  ∗\n    ⌜ sl = sl2 ++ sl3 /\\ a = a2 :: al3⌝\n  end.\n\n(** Useful invariance properties. *)\n\n  Ltac tac :=\n    match goal with\n    | |- {{ _ }} bind2 _ (fun _ _ => _) {{ _; _ }} =>\n      eapply bind_spec; intros; tac\n    | |- {{ _ }} bind _ (fun _ => _) {{ _; _ }} =>\n      eapply bind_spec; [> tac | intro; tac]\n    | |- {{ _ }} ret _ {{ _; ∃ _, _ }} => eapply exists_spec; tac\n    | |- {{ _ }} error _ {{ _; _ }} => apply rule_error\n    | |- {{ _ }} gensym _ {{ _; _ }} => Frame; apply rule_gensym\n    | H : (forall _ _, {{ emp }} transl_valof _ _ _ {{ _; _}})\n      |- {{ _ }} transl_valof _ _ _ {{ _; _ }} =>\n        Frame; apply H; tac\n    | H : (forall _, {{ emp }} is_bitfield_access _ _ {{ _; _}})\n      |- {{ _ }} is_bitfield_access _ _ {{ _; _ }} =>\n        Frame; apply H; tac\n    | H : (forall _, {{ emp }} transl_expr _ _ ?l {{ __; _}})\n      |- {{ _ }} transl_expr _ _ ?l {{ _; _ }} =>\n        Frame; apply H; tac\n    | H : (forall _ _, {{ emp }} transl_expr _ _ _ {{ _; _}})\n      |- {{ _ }} transl_expr _ _ _ {{ _; _ }} =>\n      Frame; apply H; tac\n    | H :(forall _, {{ emp }} transl_exprlist _ _ {{ _; _}})\n      |- {{ _ }} transl_exprlist _ _ {{ _; _ }} =>\n      Frame; apply H; tac\n    | H : {{ emp }} transl_exprlist _ ?l {{ _; _}}\n      |- {{ _ }} transl_exprlist _ ?l {{ _; _ }} =>\n      Frame; apply H; tac\n    | |- {{ _ }} match ?a with\n          | _ => _\n          end  {{ _; _ }} =>\n      destruct a eqn:?; tac\n    | _ => idtac\n    end.\n\n  Ltac tac2 :=\n    match goal with\n    | |- {{ _ }} ret _  {{ _; _ }} => iApply ret_spec\n    | _ => (progress tac); tac2\n    | _ => idtac\n    end.\n\n  Lemma is_bitfield_access_meets_spec: forall l,\n      {{ emp }} is_bitfield_access ce l {{ bf ; ⌜ tr_is_bitfield_access l bf ⌝ }}.\n  Proof.\n    intro l. unfold is_bitfield_access. tac; simpl; auto.\n    all : unfold is_bitfield_access_aux; destruct (ce!i0) as [co|] eqn:P; auto.\n    all : tac2; iIntros; iPureIntro; destruct (typeof e); try discriminate;\n      injection Heqt1; intros; subst; do 2 eexists; split; eauto.\n  Qed.\n\n  Lemma transl_valof_meets_spec ty a :\n    {{ emp }} transl_valof ce ty a {{ r; tr_rvalof ty a r.1 r.2 }}.\n  Proof.\n    unfold transl_valof. unfold tr_rvalof.\n    destruct (type_is_volatile ty).\n    - tac2. Frame. eapply is_bitfield_access_meets_spec.\n      iIntros \"[HA [$ _]]\". norm_all.\n    - auto.\n  Qed.\n\n  Lemma tr_expr_abs : forall r le dst sl a, <absorb> tr_expr le dst r sl a ⊢ tr_expr le dst r sl a.\n  Proof. induction r; iIntros \"* >$\". Qed.\n\n  (** ** Top-level translation *)\n\n  (** The \"top-level\" translation is equivalent to [tr_expr] above\n  for source terms.  It brings additional flexibility in the matching\n  between Csyntax values and Cminor expressions: in the case of\n  [tr_expr], the Cminor expression must not depend on memory,\n  while in the case of [tr_top] it can depend on the current memory\n  state. *)\n\n\n  Scheme expr_ind2 := Induction for Csyntax.expr Sort Prop\n    with exprlist_ind2 := Induction for Csyntax.exprlist Sort Prop.\n  Combined Scheme tr_expr_exprlist from expr_ind2, exprlist_ind2.\n\n  Lemma transl_meets_spec :\n    (forall r dst,\n        {{ emp }}\n          transl_expr ce dst r {{ res; dest_below dst -∗ ∀ le, tr_expr le dst r res.1 res.2 }})\n    /\\\n    (forall rl,\n        {{ emp }} transl_exprlist ce rl {{ res; ∀ le, tr_exprlist le rl res.1 res.2 }}).\n  Proof.\n\n    pose transl_valof_meets_spec.\n    pose is_bitfield_access_meets_spec.\n    apply tr_expr_exprlist; unfold transl_exprlist; unfold transl_expr;\n      fold (transl_expr ce); fold (transl_exprlist ce); intros; tac; iApply ret_spec;\n      simpl; iIntros; iNorm; try iModIntro.\n\n\n    Ltac EvalTac dst :=\n        destruct dst; auto; iSplitL; auto; try iExists _;\n        try iSplitL; iIntros; [ iApply locally_simpl | iApply locally_simpl | idtac ];\n        intros; iPureIntro; [econstructor | econstructor | simpl; eauto].\n    1-4 : EvalTac dst.\n\n    - iFrame. repeat iExists _; destruct dst; simpl; simpl_list; eauto.\n    - iFrame. repeat iExists _. destruct dst; simpl; iFrame; simpl_list; eauto.\n    - iFrame; repeat iExists _; destruct dst; simpl; iFrame;\n        iSplitL \"HE\"; auto; simpl_list; eauto.\n      rewrite <- app_assoc. eauto.\n    - iFrame; repeat iExists _; destruct dst; simpl; simpl_list; eauto.\n    - iFrame; repeat iExists _; destruct dst; simpl; simpl_list; eauto.\n    - iFrame. repeat iExists _. iSplitL \"HC\"; eauto.\n      destruct dst; simpl; simpl_list; auto.\n    - iFrame. repeat iExists _. iSplitL \"HF\"; eauto. iSplitL \"HC\"; eauto.\n      destruct dst; simpl; simpl_list; auto. rewrite <- app_assoc. eauto.\n    - iFrame; repeat iExists _; destruct dst; simpl; simpl_list; eauto.\n    - iApply wp_consequence. iApply H; auto. iIntros; norm_all.\n    - iFrame. repeat iExists _. iSplitL \"HC\"; eauto.\n    -repeat iExists _. iSplitL \"HG\"; auto. iDestruct (\"HC\" with \"[HE]\") as \"HA\"; auto.\n    - repeat iExists _. iSplitL \"HF\"; eauto.\n    - repeat iExists _. iSplitL \"HE\"; eauto. iSplitL; eauto. iApply (\"HC\" with \"[HH]\"); auto.\n    - repeat iExists _. iSplitL \"HG\"; auto. iSplitL; eauto. iApply (\"HC\" with \"[HE]\"); auto.\n    - repeat iExists _. iSplitL \"HF\"; eauto.\n    - repeat iExists _. iSplitL \"HE\"; eauto. iSplitL; eauto. iApply (\"HC\" with \"[HH]\"); auto.\n    - repeat iExists _. iSplitL \"HI\"; auto. iSplitL; eauto. iSplit; iApply tr_expr_abs.\n      iApply (\"HE\" with \"[HG]\"); auto. iApply (\"HC\" with \"[HG]\"); auto.\n    - repeat iExists _. iSplitL \"HI\"; eauto. iSplitL \"HF\"; auto.\n    - iSplitL \"HL\"; auto. repeat iExists _. iSplitL \"HI\"; auto. iSplitL; eauto.\n      iSplit; iApply tr_expr_abs. iApply (\"HE\" with \"[HG]\"); auto. iApply (\"HC\" with \"[HG]\"); auto.\n    - iFrame; repeat iExists _; destruct dst; simpl; simpl_list; eauto.\n    - iFrame; repeat iExists _; destruct dst; simpl; simpl_list; eauto.\n    - repeat iExists _. iSplitL \"HJ\"; eauto. iSplitL \"HG\"; auto.\n    - repeat iExists _. iSplitL \"HH\"; eauto.\n    - repeat iExists _. iSplitL \"HJ\"; eauto. iSplitL \"HG\"; auto. iSplitL \"HC\"; eauto.\n      iSplitL; eauto. iPureIntro. repeat split; eauto. do 2 (rewrite <- app_assoc; f_equal).\n    - iSplitR; auto. repeat iExists _. iFrame. iSplitL \"HL\"; eauto.\n    - repeat iExists _. iFrame. iSplitL \"HJ\"; eauto.\n    - iSplitL \"HO\"; auto. repeat iExists _. iSplitL \"HL\"; auto. iSplitL \"HI\"; eauto.\n      iSplitL \"HG\"; auto. iSplitL \"HC\"; eauto. iPureIntro. repeat split; eauto.\n      do 3 (rewrite <- app_assoc; f_equal).\n    - repeat iExists _. iSplitL \"HG\"; eauto.\n    - repeat iExists _. iSplitL \"HG\"; eauto.\n    - repeat iExists _. iSplitL \"HG\"; eauto. iSplitL \"HJ\"; auto. iExists v1.\n      iSplitL \"HC\"; auto. iPureIntro. repeat split; eauto. rewrite <- app_assoc; f_equal.\n    - repeat iExists _. iSplitL \"HE\"; eauto. iSplitL; auto. iApply (\"HC\" with \"HH\").\n    - iSplitR; auto. repeat iExists _. iSplitL \"HC\"; auto. iSplitL \"HG\"; auto.\n    - repeat iExists _. iSplitL \"HE\"; eauto.\n    - iSplitL \"HJ\"; auto. repeat iExists _. iSplitL \"HC\"; auto. iSplitL \"HG\"; auto.\n      iSplitL \"HE\"; eauto. iPureIntro. repeat split; eauto.\n      do 2 (rewrite <- app_assoc; f_equal).\n    - iSplitR; auto. repeat iExists _. iSplitL \"HE\"; auto.\n    - iSplitL \"HG\"; auto. repeat iExists _. iSplitL \"HE\"; auto. iSplitL \"HC\"; auto.\n      iPureIntro. repeat split; eauto. rewrite <- app_assoc; f_equal.\n    - repeat iExists _. iSplitL \"HD\"; auto.\n  Qed.\n\n\n  Section TR_TOP.\n\n    Variable ge: genv.\n    Variable e: Clight.env.\n    Variable le: temp_env.\n    Variable m: mem.\n\n    Inductive tr_top: destination -> Csyntax.expr -> list statement -> expr ->  Prop :=\n  | tr_top_val_val: forall v ty a,\n      typeof a = ty -> eval_expr ge e le m a v ->\n      tr_top For_val (Csyntax.Eval v ty) nil a\n  | tr_top_base: forall dst r sl a tmp,\n      tr_expr le dst r sl a () tmp ->\n      tr_top dst r sl a.\n\n  End TR_TOP.\n\n\n(** Translation of statements *)\n\n  Lemma tr_top_spec : forall r dst sl a,\n      ⊢(∀ le, tr_expr le dst r sl a)\n        -∗ ⌜∀ ge e le m, tr_top ge e le m dst r sl a⌝.\n  Proof.\n    iIntros \"* HA\". iStopProof. apply instance_heap. intros. econstructor.\n    apply soundness. apply completeness in H. iIntros \"HA\". iApply (H with \"HA\").\n  Qed.\n\n  Lemma transl_expr_meets_spec:\n    forall r dst,\n      {{ emp }} transl_expr ce dst r\n      {{ res;  dest_below dst -∗ ⌜ ∀ ge e le m, tr_top ge e le m dst r res.1 res.2 ⌝ }}.\n  Proof.\n    intros. iApply (consequence _ _ _ _ _ (proj1 transl_meets_spec _ _)); eauto.\n    iIntros \"* HA HB\". iDestruct (\"HA\" with \"HB\") as \"HA\". iApply (tr_top_spec with \"HA\").\n  Qed.\n\n  Inductive tr_expression: Csyntax.expr -> statement -> expr -> Prop :=\n  | tr_expression_intro: forall r sl a,\n      (forall ge e le m, tr_top ge e le m For_val r sl a) ->\n      tr_expression r (makeseq sl) a.\n\n\n  Lemma transl_expression_meets_spec: forall r,\n      {{ emp }} transl_expression ce r {{ res; ⌜ tr_expression r res.1 res.2 ⌝ }}.\n  Proof.\n    intro. unfold transl_expression. epose transl_expr_meets_spec. tac2.\n    iIntros; norm_all.\n  Qed.\n\n  Inductive tr_expr_stmt: Csyntax.expr -> statement -> Prop :=\n  | tr_expr_stmt_intro: forall r sl a,\n      (forall ge e le m, tr_top ge e le m For_effects r sl a) ->\n      tr_expr_stmt r (makeseq sl).\n\n  Lemma transl_expr_stmt_meets_spec: forall r,\n      {{ emp }} transl_expr_stmt ce r {{ res; ⌜ tr_expr_stmt r res ⌝}}.\n  Proof.\n    intro. unfold transl_expr_stmt. epose transl_expr_meets_spec. tac2.\n    iIntros; norm_all. iPureIntro. econstructor. auto.\n  Qed.\n\n  Inductive tr_if: Csyntax.expr -> statement -> statement -> statement -> Prop :=\n  | tr_if_intro: forall r s1 s2 sl a,\n      (forall ge e le m, tr_top ge e le m For_val r sl a) ->\n      tr_if r s1 s2 (makeseq (sl ++ makeif a s1 s2 :: nil)).\n\n  Lemma transl_if_meets_spec: forall r s1 s2,\n      {{ emp }} transl_if ce r s1 s2 {{ res; ⌜ tr_if r s1 s2 res ⌝ }}.\n  Proof.\n    intros. unfold transl_if. epose transl_expr_meets_spec. tac2.\n    iIntros; norm_all.\n  Qed.\n\n  Inductive tr_stmt: Csyntax.statement -> statement -> Prop :=\n  | tr_skip:\n      tr_stmt Csyntax.Sskip Sskip\n  | tr_do: forall r s,\n      tr_expr_stmt r s ->\n      tr_stmt (Csyntax.Sdo r) s\n  | tr_seq: forall s1 s2 ts1 ts2,\n      tr_stmt s1 ts1 -> tr_stmt s2 ts2 ->\n      tr_stmt (Csyntax.Ssequence s1 s2) (Ssequence ts1 ts2)\n  | tr_ifthenelse_empty: forall r s' a,\n      tr_expression r s' a ->\n      tr_stmt (Csyntax.Sifthenelse r Csyntax.Sskip Csyntax.Sskip) (Ssequence s' Sskip)\n  | tr_ifthenelse: forall r s1 s2 s' a ts1 ts2,\n      tr_expression r s' a ->\n      tr_stmt s1 ts1 -> tr_stmt s2 ts2 ->\n      tr_stmt (Csyntax.Sifthenelse r s1 s2) (Ssequence s' (Sifthenelse a ts1 ts2))\n  | tr_while: forall r s1 s' ts1,\n      tr_if r Sskip Sbreak s' ->\n      tr_stmt s1 ts1 ->\n      tr_stmt (Csyntax.Swhile r s1)\n              (Sloop (Ssequence s' ts1) Sskip)\n  | tr_dowhile: forall r s1 s' ts1,\n      tr_if r Sskip Sbreak s' ->\n      tr_stmt s1 ts1 ->\n      tr_stmt (Csyntax.Sdowhile r s1)\n              (Sloop ts1 s')\n  | tr_for_1: forall r s3 s4 s' ts3 ts4,\n      tr_if r Sskip Sbreak s' ->\n      tr_stmt s3 ts3 ->\n      tr_stmt s4 ts4 ->\n      tr_stmt (Csyntax.Sfor Csyntax.Sskip r s3 s4)\n              (Sloop (Ssequence s' ts4) ts3)\n  | tr_for_2: forall s1 r s3 s4 s' ts1 ts3 ts4,\n      tr_if r Sskip Sbreak s' ->\n      s1 <> Csyntax.Sskip ->\n      tr_stmt s1 ts1 ->\n      tr_stmt s3 ts3 ->\n      tr_stmt s4 ts4 ->\n      tr_stmt (Csyntax.Sfor s1 r s3 s4)\n              (Ssequence ts1 (Sloop (Ssequence s' ts4) ts3))\n  | tr_break:\n      tr_stmt Csyntax.Sbreak Sbreak\n  | tr_continue:\n      tr_stmt Csyntax.Scontinue Scontinue\n  | tr_return_none:\n      tr_stmt (Csyntax.Sreturn None) (Sreturn None)\n  | tr_return_some: forall r s' a,\n      tr_expression r s' a ->\n      tr_stmt (Csyntax.Sreturn (Some r)) (Ssequence s' (Sreturn (Some a)))\n  | tr_switch: forall r ls s' a tls,\n      tr_expression r s' a ->\n      tr_lblstmts ls tls ->\n      tr_stmt (Csyntax.Sswitch r ls) (Ssequence s' (Sswitch a tls))\n  | tr_label: forall lbl s ts,\n      tr_stmt s ts ->\n      tr_stmt (Csyntax.Slabel lbl s) (Slabel lbl ts)\n  | tr_goto: forall lbl,\n      tr_stmt (Csyntax.Sgoto lbl) (Sgoto lbl)\n\nwith tr_lblstmts: Csyntax.labeled_statements -> labeled_statements -> Prop :=\n  | tr_ls_nil:\n      tr_lblstmts Csyntax.LSnil LSnil\n  | tr_ls_cons: forall c s ls ts tls,\n      tr_stmt s ts ->\n      tr_lblstmts ls tls ->\n      tr_lblstmts (Csyntax.LScons c s ls) (LScons c ts tls).\n\n  Ltac tac3 :=\n    match goal with\n    | H : forall _, {{ emp }} transl_expression _ _ {{ _; _ }}\n      |- {{ _ }} transl_expression _ _ {{ _; _ }} =>\n      Frame; apply H; tac3\n    | H : forall _, {{ emp }} transl_expr_stmt _ _ {{ _; _}}\n      |- {{ _ }} transl_expr_stmt _ _ {{ _; _}} =>\n      Frame; apply H; tac3\n    | H: forall _ _ _, {{ emp }} transl_if _ _ _ _ {{ _; _ }}\n      |- {{ _ }} transl_if _ _ _ _ {{ _; _ }} =>\n      Frame; apply H; tac3\n    | H: {{ emp }} transl_stmt _ ?s {{ _; _ }}\n      |- {{ _ }} transl_stmt _ ?s {{ _; _ }} =>\n      Frame; apply H; tac3\n    | H:(forall _, {{ emp }} transl_stmt _ _ {{ _; _ }})\n      |- {{ _ }} transl_stmt _ ?s {{ _; _ }} =>\n      Frame; apply H; tac3\n    | H: {{ emp }} transl_lblstmt _ ?l {{ _; _ }}\n      |- {{ _ }} transl_lblstmt _ ?l {{ _; _ }} =>\n      Frame; apply H; tac3\n    | H: (forall _, {{ emp }} transl_lblstmt _  _ {{ _; _ }})\n      |- {{ _ }} transl_lblstmt _  _ {{ _; _ }} =>\n      Frame; apply H; tac3\n    | _ => (progress tac); tac3\n    | _ => (progress tac2); tac3\n    | _ => idtac\n    end.\n\n\n  Lemma transl_stmt_meets_spec : forall s,\n      {{ emp }} transl_stmt ce s {{ res; ⌜ tr_stmt s res ⌝}}\n  with transl_lblstmt_meets_spec:\n         forall s,\n           {{ emp }} transl_lblstmt ce s {{ res; ⌜ tr_lblstmts s res ⌝ }}.\n  Proof.\n    pose transl_expression_meets_spec.\n    pose transl_if_meets_spec.\n    pose transl_expr_stmt_meets_spec.\n    clear transl_stmt_meets_spec. intro.\n    induction s; rewrite /transl_stmt; fold (transl_stmt ce); fold (transl_lblstmt ce); tac3.\n    - iIntros. iPureIntro. constructor.\n    - apply (consequence _ _ _ _ _ (b1 e)); eauto. iIntros (v tr). iPureIntro. apply (tr_do _ _ tr).\n    - iIntros \"[% [% _]]\". iPureIntro. constructor; auto.\n    - iIntros \"[% [% [% _]]]\". iPureIntro. pose Heqb2. apply Is_true_eq_left in e0.\n      apply andb_prop_elim in e0 as (P0&P1).\n      destruct (is_Sskip s1); destruct (is_Sskip s2) eqn:?; try contradiction. subst.\n      eapply tr_ifthenelse_empty; eauto.\n    - iIntros\"[% [% [% _]]]\". iPureIntro. apply (tr_ifthenelse _ _ _ _ _ _ _ H H1 H0).\n    - iIntros \"[% [% _]]\". iPureIntro. apply (tr_while _ _ _ _ H0 H).\n    - iIntros \"[% [% _]]\". iPureIntro. apply (tr_dowhile _ _ _ _ H0 H).\n    - iIntros \"[% [% [% [% _]]]]\"; iPureIntro; subst. apply (tr_for_1 _ _ _ _ _ _ H1 H0 H).\n    - iIntros \"[% [% [% [% _]]]]\"; iPureIntro; subst. apply (tr_for_2 _ _ _ _ _ _ _ _ H1 n H2 H0 H).\n    - iIntros \"_\". iPureIntro. constructor.\n    - iIntros \"_\". iPureIntro. constructor.\n    - iIntros \"[% _]\". iPureIntro. apply (tr_return_some _ _ _ H).\n    - iIntros \"_\". iPureIntro. constructor.\n    - iIntros \"[% [% _]]\". iPureIntro. constructor; auto.\n    - iIntros \"[% _]\". iPureIntro. constructor; auto.\n    - iIntros \"_\". iPureIntro. constructor.\n    - induction s; rewrite /transl_lblstmt; fold (transl_lblstmt ce); fold (transl_stmt ce); tac3.\n      + iIntros \"_\". iPureIntro. constructor.\n      + iIntros \"[% [% _]]\". iPureIntro. constructor; auto.\n  Qed.\n\n  Inductive tr_fun : Csyntax.statement -> (statement * list (ident * type)) -> Prop :=\n  | tr_fun_intro : forall s ts l,\n      tr_stmt s ts ->\n      tr_fun s (ts, l).\n\n  Lemma transl_fun_meets_spec : forall s,\n      {{ emp }} transl_fun ce s {{ res; ⌜ tr_fun s res ⌝}}.\n  Proof.\n    intro. unfold transl_fun. tac3. apply transl_stmt_meets_spec. Frame. eapply rule_trail.\n    iIntros \"[_ %]\". eauto.\n    Qed.\n\n  (** Relational presentation for the transformation of functions, fundefs, and variables. *)\n\n  Inductive tr_function: Csyntax.function -> Clight.function -> Prop :=\n  | tr_function_intro: forall f tf l,\n      tr_fun f.(Csyntax.fn_body) (tf.(fn_body),l) ->\n      fn_return tf = Csyntax.fn_return f ->\n      fn_callconv tf = Csyntax.fn_callconv f ->\n      fn_params tf = Csyntax.fn_params f ->\n      fn_vars tf = Csyntax.fn_vars f ->\n      tr_function f tf.\n\n  Lemma transl_function_spec:\n    forall f tf,\n      transl_function ce f = OK tf ->\n      tr_function f tf.\n  Proof.\n    unfold transl_function; intros.\n    destruct (run (transl_fun ce (Csyntax.fn_body f))) eqn:?; inversion H.\n    destruct p. simpl in *.\n    eapply tr_function_intro; auto; simpl.\n    eapply adequacy.\n    2 : apply Heqr. apply transl_fun_meets_spec.\n  Qed.\n\nEnd SPEC.\n\n\n  Inductive tr_fundef (p: Csyntax.program): Csyntax.fundef -> Clight.fundef -> Prop :=\n  | tr_internal: forall f tf,\n      tr_function p.(prog_comp_env) f tf ->\n      tr_fundef p (Internal f) (Internal tf)\n  | tr_external: forall ef targs tres cconv,\n      tr_fundef p (External ef targs tres cconv) (External ef targs tres cconv).\n\n  Lemma transl_fundef_spec:\n    forall p fd tfd,\n      transl_fundef p.(prog_comp_env) fd = OK tfd ->\n      tr_fundef p fd tfd.\n  Proof.\n    unfold transl_fundef; intros.\n    destruct fd; Errors.monadInv H.\n    + constructor. eapply transl_function_spec; eauto.\n    + constructor.\n  Qed.\n", "meta": {"author": "Artalik", "repo": "NigronThesis", "sha": "370358a919f3d83c327b3bb7b455d9c8763fe543", "save_path": "github-repos/coq/Artalik-NigronThesis", "path": "github-repos/coq/Artalik-NigronThesis/NigronThesis-370358a919f3d83c327b3bb7b455d9c8763fe543/src/fresh/CompCert/cfrontend/SimplExprspec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.3812195732862559, "lm_q1q2_score": 0.21577735004114906}}
{"text": "From Coq Require Import String NArith ZArith DecimalString HexString.\n\nFrom Vyper Require Import Config FSet.\nFrom Vyper.L10 Require AST Base ToString.\n\nSection AST.\n\nContext {C: VyperConfig}.\n\nInductive small_stmt\n:= Pass\n | Const (dst: N) (val: uint256)\n | Copy (dst src: N)\n | StorageGet (dst: N) (name: string)\n | StoragePut (name: string) (src: N)\n | UnOp (op: L10.AST.unop) (dst src: N)\n | PowConstBase (dst: N) (base: uint256) (exp: N)\n | PowConstExp (dst base: N) (exp: uint256)\n | BinOp (op: L10.AST.binop) (dst src1 src2: N) (Ok: op <> L10.AST.Pow)\n | PrivateCall (dst: N) (name: string) (args_offset args_count: N)\n | BuiltinCall (dst: N) (name: string) (args_offset args_count: N)\n | Abort (ab: L10.Base.abort)\n | Return (src: N)\n | Raise (src: N).\n\nInductive stmt\n:= SmallStmt (s: small_stmt)\n | IfElseStmt (cond_src: N) (yes: stmt) (no: stmt)\n | Loop (var: N) (count: uint256) (body: stmt)\n | Semicolon (a b: stmt).\n\nInductive decl\n:= StorageVarDecl (name: string)\n | FunDecl (name: string) (args_count: N) (body: stmt).\n\n(****************************   format   ******************************)\n\nLocal Open Scope string_scope.\n\nDefinition string_of_small_stmt (ss: small_stmt)\n:= match ss with\n   | Pass => \"pass\"\n   | Const dst val => \"var\" ++ NilZero.string_of_uint (N.to_uint dst)\n                      ++ \" = \"\n                      ++ HexString.of_Z (Z_of_uint256 val)\n   | Copy dst src => \"var\" ++ NilZero.string_of_uint (N.to_uint dst)\n                     ++ \" = var\"\n                     ++ NilZero.string_of_uint (N.to_uint src)\n   | StorageGet dst name => \"var\" ++ NilZero.string_of_uint (N.to_uint dst)\n                            ++ \" = storage_get(\" ++ name ++ \")\"\n   | StoragePut name src => \"storage_put(\" ++ name\n                            ++ \", var\" ++ NilZero.string_of_uint (N.to_uint src) ++ \")\"\n   | UnOp op dst src => \"var\" ++ NilZero.string_of_uint (N.to_uint dst)\n                        ++ \" = \"\n                        ++ L10.ToString.string_of_unop op\n                        ++ \" var\" ++ NilZero.string_of_uint (N.to_uint src)\n   | PowConstBase dst base exp => \n      \"var\" ++ NilZero.string_of_uint (N.to_uint dst) ++ \" = \"\n       ++ NilZero.string_of_int (Z.to_int (Z_of_uint256 base))\n       ++ \" ** var\" ++ NilZero.string_of_uint (N.to_uint exp)\n   | PowConstExp dst base exp => \n      \"var\" ++ NilZero.string_of_uint (N.to_uint dst)\n       ++ \" = var\" ++ NilZero.string_of_uint (N.to_uint base)\n       ++ \" ** \" ++ NilZero.string_of_int (Z.to_int (Z_of_uint256 exp))\n   | BinOp op dst src1 src2 _ => \"var\" ++ NilZero.string_of_uint (N.to_uint dst)\n                                 ++ \" = var\" ++ NilZero.string_of_uint (N.to_uint src1) ++ \" \"\n                                 ++ L10.ToString.string_of_binop op\n                                 ++ \" var\" ++ NilZero.string_of_uint (N.to_uint src2)\n   | PrivateCall dst name args_offset args_count =>\n       \"var\" ++ NilZero.string_of_uint (N.to_uint dst)\n        ++ \" = \" ++ name ++ \"/\"\n        ++ NilZero.string_of_uint (N.to_uint args_count)\n        ++ \"(var\" ++ NilZero.string_of_uint (N.to_uint args_offset) ++ \", ...)\"\n   | BuiltinCall dst name args_offset args_count =>\n       \"var\" ++ NilZero.string_of_uint (N.to_uint dst)\n        ++ \" = $\" ++ name ++ \"/\"\n        ++ NilZero.string_of_uint (N.to_uint args_count)\n        ++ \"(var\" ++ NilZero.string_of_uint (N.to_uint args_offset) ++ \", ...)\"\n   | Abort a => \"abort \" ++ L10.Base.string_of_abort a\n   | Return n => \"return var\" ++ NilZero.string_of_uint (N.to_uint n)\n   | Raise n => \"raise var\" ++ NilZero.string_of_uint (N.to_uint n)\n   end.\n\n\nFixpoint lines_of_stmt (s: stmt)\n: list string\n:=  match s with\n    | SmallStmt ss => string_of_small_stmt ss :: nil\n    | IfElseStmt cond yes no => (\"if var\" ++ NilZero.string_of_uint (N.to_uint cond) ++ \":\")\n                                :: L10.ToString.add_indent (lines_of_stmt yes)\n                                ++ \"else:\" :: L10.ToString.add_indent (lines_of_stmt no)\n    | Loop var count body =>  (\"for var\" ++ NilZero.string_of_uint (N.to_uint var) ++ \" in count(\"\n                                       ++ HexString.of_Z (Z_of_uint256 count) ++ \"):\")\n                                       :: L10.ToString.add_indent (lines_of_stmt body)\n    | Semicolon a b => lines_of_stmt a ++ lines_of_stmt b\n    end.\n\nDefinition lines_of_decl (d: decl)\n: list string\n:= (match d with\n    | StorageVarDecl name => (\"var \" ++ name)%string :: nil\n    | FunDecl name args body =>\n        (\"def \" ++ name ++ \"/\" ++ NilZero.string_of_uint (N.to_uint args) ++ \":\")%string\n        :: L10.ToString.add_indent (lines_of_stmt body)\n    end)%list.\n\nDefinition string_of_decl (d: decl)\n:= let newline := \"\n\" in newline ++ List.fold_right (fun x tail => x ++ newline ++ tail) \"\" (lines_of_decl d).\n\nDefinition string_of_decls {C: VyperConfig} (l: list decl)\n:= List.fold_right append \"\" (List.map string_of_decl l).\n\nEnd AST.", "meta": {"author": "formalize", "repo": "coq-vyper", "sha": "8996c1534b9d56696f92b60031ff1523b3593690", "save_path": "github-repos/coq/formalize-coq-vyper", "path": "github-repos/coq/formalize-coq-vyper/coq-vyper-8996c1534b9d56696f92b60031ff1523b3593690/L30/AST.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.21577734048039915}}
{"text": "Require Import Raft.\nRequire Import RaftRefinementInterface.\n\nSection AppendEntriesLeader.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Definition appendEntries_leader net :=\n    forall p t leaderId prevLogIndex prevLogTerm entries leaderCommit h e,\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm\n                              entries leaderCommit ->\n      In e entries ->\n      currentTerm (snd (nwState net h)) = t ->\n      type (snd (nwState net h)) = Leader ->\n      In e (log (snd (nwState net h))).\n\n\n  Class append_entries_leader_interface : Prop :=\n    {\n      append_entries_leader_invariant :\n        forall net,\n          refined_raft_intermediate_reachable net ->\n          appendEntries_leader net\n    }.\nEnd AppendEntriesLeader.", "meta": {"author": "ahmet-celik", "repo": "pverdi", "sha": "dc88c4a5fd7d90b5bb48e583bd8286097f983f81", "save_path": "github-repos/coq/ahmet-celik-pverdi", "path": "github-repos/coq/ahmet-celik-pverdi/pverdi-dc88c4a5fd7d90b5bb48e583bd8286097f983f81/raft/AppendEntriesLeaderInterface.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3486451353339458, "lm_q1q2_score": 0.2157347880646223}}
{"text": "(*********************************************************************************************************************************)\n(* HaskWeakToStrong: convert HaskWeak to HaskStrong                                                                              *)\n(*********************************************************************************************************************************)\n\nGeneralizable All Variables.\nRequire Import Preamble.\nRequire Import General.\nRequire Import NaturalDeduction.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Init.Specif.\nRequire Import HaskKinds.\nRequire Import HaskLiterals.\nRequire Import HaskTyCons.\nRequire Import HaskWeakTypes.\nRequire Import HaskWeakVars.\nRequire Import HaskWeak.\nRequire Import HaskWeakToCore.\nRequire Import HaskStrongTypes.\nRequire Import HaskStrong.\nRequire Import HaskCoreVars.\nRequire Import HaskCoreToWeak.\nRequire Import HaskCoreTypes.\n\nOpen Scope string_scope.\nDefinition TyVarResolver Γ   := forall wt:WeakTypeVar, ???(HaskTyVar Γ wt).\nDefinition CoVarResolver Γ Δ := forall wt:WeakCoerVar, ???(HaskCoVar Γ Δ).\n\nDefinition lamer {a}{b}{c}{κ}(lt:HaskType (app (app a  b) c) κ) : HaskType (app a (app b c)) κ.\n  rewrite <- ass_app in lt.\n  exact lt.\n  Defined.\n\nDefinition upPhi {Γ}(tv:WeakTypeVar)(φ:TyVarResolver Γ) : TyVarResolver ((tv:Kind)::Γ).\n  unfold TyVarResolver.\n  refine (fun tv' =>\n    if eqd_dec tv tv' \n    then let fresh := @FreshHaskTyVar Γ tv in OK _\n    else φ tv' >>= fun tv'' => OK (fun TV ite => tv'' TV (weakITE ite))).\n  rewrite <- _H; apply fresh.\n  Defined.\n\nDefinition upPhi2 {Γ}(tvs:list WeakTypeVar)(φ:TyVarResolver Γ)\n  : (TyVarResolver (app (map (fun tv:WeakTypeVar => tv:Kind) tvs) Γ)).\n  induction tvs.\n  apply φ.    \n  simpl.\n  apply upPhi.\n  apply IHtvs.\n  Defined.\n\nDefinition substPhi {Γ:TypeEnv}(κ κ':Kind)(θ:HaskType Γ κ) : HaskType (κ::Γ) κ' -> HaskType Γ κ'.\n  intro ht.\n  refine (substT _ θ).\n  clear θ.\n  unfold HaskType in ht.\n  intros.\n  apply ht.\n  apply ICons; [ idtac | apply env ].\n  apply X.\n  Defined.\n\nDefinition substphi {Γ:TypeEnv}(lk:list Kind)(θ:IList _ (fun κ => HaskType Γ κ) lk){κ} : HaskType (app lk Γ) κ -> HaskType Γ κ.\n  induction lk.\n  intro q; apply q.\n  simpl.\n  intro q.\n  apply IHlk.\n  inversion θ; subst; auto.\n  inversion θ; subst.\n  eapply substPhi.\n  eapply weakT'.\n  apply X.\n  apply q.\n  Defined.\n\n(* this is a StrongAltCon plus some stuff we know about StrongAltCons which we've built ourselves *)\nRecord StrongAltConPlusJunk {tc:TyCon} :=\n{ sacpj_sac : @StrongAltCon tc\n; sacpj_phi   : forall Γ          (φ:TyVarResolver Γ  ),  (TyVarResolver (sac_gamma sacpj_sac Γ))\n; sacpj_psi   : forall Γ Δ atypes (ψ:CoVarResolver Γ Δ), CoVarResolver _ (sac_delta sacpj_sac Γ atypes (weakCK'' Δ))\n}.\nImplicit Arguments StrongAltConPlusJunk [ ].\nCoercion sacpj_sac : StrongAltConPlusJunk >-> StrongAltCon. \n\n(* yes, I know, this is really clumsy *)\nVariable emptyφ : TyVarResolver nil.\n  Extract Inlined Constant emptyφ => \"(\\x -> Prelude.error \"\"encountered unbound tyvar!\"\")\".\n\nDefinition mkPhi (lv:list WeakTypeVar)\n  : (TyVarResolver (map (fun x:WeakTypeVar => x:Kind) lv)).\n  set (upPhi2(Γ:=nil) lv emptyφ) as φ2.\n  rewrite <- app_nil_end in φ2.\n  apply φ2.\n  Defined.\n\nDefinition dataConExKinds dc := vec_map (fun x:WeakTypeVar => (x:Kind)) (list2vec (dataConExTyVars dc)).\nDefinition tyConKinds     tc := vec_map (fun x:WeakTypeVar => (x:Kind)) (list2vec (tyConTyVars tc)).\n\nDefinition fixkind {κ}(tv:WeakTypeVar) := weakTypeVar tv κ.\nNotation \" ` x \" := (@fixkind _ x) (at level 100).\n\nLtac matchThings T1 T2 S :=\n  destruct (eqd_dec T1 T2) as [matchTypeVars_pf|];\n   [ idtac | apply (Error (S +++ toString T1 +++ \" \" +++ toString T2)) ].\n\nDefinition mkTAll' {κ}{Γ} : HaskType (κ :: Γ) ★ -> (forall TV (ite:InstantiatedTypeEnv TV Γ), TV κ -> RawHaskType TV ★).\n  intros.\n  unfold InstantiatedTypeEnv in ite.\n  apply X.\n  apply (X0::::ite).\n  Defined.\n\nDefinition mkTAll {κ}{Γ} : HaskType (κ :: Γ) ★ -> HaskType Γ ★.\n  intro.\n  unfold HaskType.\n  intros.\n  apply (TAll κ).\n  eapply mkTAll'.\n  apply X.\n  apply X0.\n  Defined.\n\nDefinition weakTypeToType : forall {Γ:TypeEnv}(φ:TyVarResolver Γ)(t:WeakType), ???(HaskTypeOfSomeKind Γ).\n  refine (fix weakTypeToType {Γ:TypeEnv}(φ:TyVarResolver Γ)(t:WeakType) {struct t} : ???(HaskTypeOfSomeKind Γ) :=\n  addErrorMessage (\"weakTypeToType \" +++ toString t)\n  match t with\n    | WFunTyCon         => let case_WFunTyCon := tt in OK (haskTypeOfSomeKind (fun TV ite => TArrow))\n    | WTyCon      tc    => let case_WTyCon := tt    in _\n    | WClassP   c lt    => let case_WClassP := tt   in Error \"weakTypeToType: WClassP not implemented\"\n    | WIParam _ ty      => let case_WIParam := tt   in Error \"weakTypeToType: WIParam not implemented\"\n    | WAppTy  t1 t2     => let case_WAppTy := tt    in weakTypeToType _ φ t1 >>= fun t1' => weakTypeToType _ φ t2 >>= fun t2' => _\n    | WTyVarTy  v       => let case_WTyVarTy := tt  in φ v >>= fun v' => _\n    | WForAllTy wtv t   => let case_WForAllTy := tt in weakTypeToType _ (upPhi wtv φ) t >>= fun t => _\n    | WCodeTy ec tbody  => let case_WCodeTy := tt   in weakTypeToType _ φ tbody\n                                 >>= fun tbody' => φ (@fixkind ECKind ec) >>= fun ec' => _\n    | WCoFunTy t1 t2 t3 => let case_WCoFunTy := tt  in\n      weakTypeToType _ φ t1 >>= fun t1' =>\n      weakTypeToType _ φ t2 >>= fun t2' =>\n      weakTypeToType _ φ t3 >>= fun t3' => _\n    | WTyFunApp   tc lt =>\n      ((fix weakTypeListToTypeList (lk:list Kind) (lt:list WeakType)\n        { struct lt } : ???(forall TV (ite:InstantiatedTypeEnv TV Γ), @RawHaskTypeList TV lk) :=\n        match lt with\n          | nil    => match lk as LK return ???(forall TV (ite:InstantiatedTypeEnv TV Γ), @RawHaskTypeList TV LK) with\n                        | nil => OK (fun TV _ => TyFunApp_nil)\n                        | _   => Error \"WTyFunApp not applied to enough types\"\n                      end\n          | tx::lt' => weakTypeToType Γ φ tx >>= fun t' =>\n                        match lk as LK return ???(forall TV (ite:InstantiatedTypeEnv TV Γ), @RawHaskTypeList TV LK) with\n                          | nil    => Error (\"WTyFunApp applied to too many types\"(* +++ eol +++\n                                             \"  tyCon= \"           +++ toString tc +++ eol +++\n                                             \"  tyConKindArgs= \"   +++ toString (fst (tyFunKind tc)) +++ eol +++\n                                             \"  tyConKindResult= \" +++ toString (snd (tyFunKind tc)) +++ eol +++\n                                             \"  types= \"           +++ toString lt +++ eol*))\n                          | k::lk' => weakTypeListToTypeList lk' lt' >>= fun rhtl' =>\n                                        let case_weakTypeListToTypeList := tt in _\n                        end\n        end\n      ) (fst (tyFunKind tc)) lt) >>= fun lt' => let case_WTyFunApp := tt in  _\n  end ); clear weakTypeToType.\n  apply ConcatenableString.\n\n  destruct case_WTyVarTy.\n    apply (addErrorMessage \"case_WTyVarTy\").\n    apply OK.\n    exact (haskTypeOfSomeKind (fun TV env => TVar (v' TV env))).\n\n  destruct case_WAppTy.\n    apply (addErrorMessage \"case_WAppTy\").\n    destruct t1' as  [k1' t1'].\n    destruct t2' as [k2' t2'].\n    set (\"tried to apply type \"+++toString t1'+++\" of kind \"+++toString k1'+++\" to type \"+++\n      toString t2'+++\" of kind \"+++toString k2') as err.\n    destruct k1';\n      try (matchThings k1'1 k2' \"Kind mismatch in WAppTy: \";\n        subst; apply OK; apply (haskTypeOfSomeKind (fun TV env => TApp (t1' TV env) (t2' TV env))));\n      apply (Error (\"Kind mismatch in WAppTy: \"+++err)).\n\n  destruct case_weakTypeListToTypeList.\n    apply (addErrorMessage \"case_weakTypeListToTypeList\").\n    destruct t' as [ k' t' ].\n    matchThings k k' \"Kind mismatch in weakTypeListToTypeList\".\n    subst.\n    apply (OK (fun TV ite => TyFunApp_cons _ _ (t' TV ite) (rhtl' TV ite))).\n\n  destruct case_WTyFunApp.\n    apply (addErrorMessage \"case_WTyFunApp\").\n    apply OK.\n    eapply haskTypeOfSomeKind.\n    unfold HaskType; intros.\n    apply (TyFunApp tc (fst (tyFunKind tc)) (snd (tyFunKind tc))).\n    apply lt'.\n    apply X.\n\n  destruct case_WTyCon.\n    apply (addErrorMessage \"case_WTyCon\").\n    apply OK.\n    eapply haskTypeOfSomeKind.\n    unfold HaskType; intros.\n    apply (TCon tc).\n\n  destruct case_WCodeTy.    \n    apply (addErrorMessage \"case_WCodeTy\").\n    destruct tbody'.\n    matchThings κ ★ \"Kind mismatch in WCodeTy: \".\n    apply OK.\n    eapply haskTypeOfSomeKind.\n    unfold HaskType; intros.\n    apply TCode.\n    apply (TVar (ec' TV X)).\n    subst.\n    apply h.\n    apply X.\n\n  destruct case_WCoFunTy.\n    apply (addErrorMessage \"case_WCoFunTy\").\n    destruct t1' as [ k1' t1' ].\n    destruct t2' as [ k2' t2' ].\n    destruct t3' as [ k3' t3' ].\n    matchThings k1' k2' \"Kind mismatch in arguments of WCoFunTy\".\n    subst.\n    matchThings k3' ★ \"Kind mismatch in result of WCoFunTy\".\n    subst.\n    apply OK.\n    apply (haskTypeOfSomeKind (t1' ∼∼ t2' ⇒ t3')).\n\n  destruct case_WForAllTy.\n    apply (addErrorMessage \"case_WForAllTy\").\n    destruct t1.\n    matchThings ★  κ \"Kind mismatch in WForAllTy: \".\n    subst.\n    apply OK.\n    apply (@haskTypeOfSomeKind _ ★).\n    apply (@mkTAll wtv).\n    apply h.\n    Defined.\n    \n(* information about a datacon/literal/default which is common to all instances of a branch with that tag *)\nSection StrongAltCon.\n  Context (tc : TyCon)(dc:DataCon tc).\n\nDefinition weakTypeToType' {Γ} : IList Kind (HaskType Γ) (vec2list (tyConKinds tc))\n -> WeakType → ???(HaskType (app (vec2list (dataConExKinds dc)) Γ) ★).\n  intro avars.\n  intro ct.\n  apply (addErrorMessage \"weakTypeToType'\").\n  set (ilmap (@weakT' _ (vec2list (dataConExKinds dc))) avars) as avars'.\n  set (@substphi _ _ avars') as q.\n  set (upPhi2 (tyConTyVars tc)  (mkPhi (dataConExTyVars dc))) as φ2.\n  set (@weakTypeToType _ φ2 ct) as t.\n  destruct t as [|t]; try apply (Error error_message).\n  destruct t as [tk t].\n  matchThings tk ★ \"weakTypeToType'\".\n  subst.\n  apply OK.\n  set (@weakT'' _ Γ _ t) as t'.\n  set (@lamer _ _ _ _ t') as t''.\n  fold (tyConKinds tc) in t''.\n  fold (dataConExKinds dc) in t''.\n  apply q.\n  clear q.\n  unfold tyConKinds.\n  unfold dataConExKinds.\n  rewrite <- vec2list_map_list2vec.\n  rewrite <- vec2list_map_list2vec.\n  rewrite vec2list_list2vec.\n  rewrite vec2list_list2vec.\n  apply t''.\n  Defined.\n\nDefinition mkStrongAltCon : @StrongAltCon tc.\n  refine\n   {| sac_altcon      := WeakDataAlt dc\n    ; sac_numCoerVars := length (dataConCoerKinds dc)\n    ; sac_numExprVars := length (dataConFieldTypes dc)\n    ; sac_ekinds      := dataConExKinds dc\n    ; sac_coercions   := fun Γ avars => let case_sac_coercions := tt in _\n    ; sac_types       := fun Γ avars => let case_sac_types := tt in _\n    |}.\n  \n  destruct case_sac_coercions.\n    refine (vec_map _ (list2vec (dataConCoerKinds dc))).\n    intro.\n    destruct X.\n    unfold tyConKind in avars.\n    set (@weakTypeToType' Γ) as q.\n    unfold tyConKinds in q.\n    rewrite <- vec2list_map_list2vec in q.\n    rewrite vec2list_list2vec in q.\n    apply (\n      match\n        q avars w >>= fun t1 =>\n        q avars w0 >>= fun t2 =>\n          OK (mkHaskCoercionKind t1 t2)\n      with\n        | Error s => Prelude_error s\n        | OK y => y\n      end).\n\n  destruct case_sac_types.\n    refine (vec_map _ (list2vec (dataConFieldTypes dc))).\n    intro X.\n    unfold tyConKind in avars.\n    set (@weakTypeToType' Γ) as q.\n    unfold tyConKinds in q.\n    rewrite <- vec2list_map_list2vec in q.\n    rewrite vec2list_list2vec in q.\n    set (q avars X) as y.\n    apply (match y with \n             | Error s =>Prelude_error s\n             | OK y' => y'\n           end).\n    Defined.\n\n\nLemma weakCV' : forall {Γ}{Δ} Γ',\n   HaskCoVar Γ Δ\n   -> HaskCoVar (app Γ' Γ) (weakCK'' Δ).\n  intros.\n  unfold HaskCoVar in *.\n  intros; apply (X TV CV).\n  apply ilist_chop' in env; auto.\n  unfold InstantiatedCoercionEnv in *.\n  unfold weakCK'' in cenv.\n  destruct Γ'.\n  rewrite <- map_preserves_length in cenv.\n  apply cenv.\n  rewrite <- map_preserves_length in cenv.\n  apply cenv.\n  Defined.\n\nDefinition mkStrongAltConPlusJunk : StrongAltConPlusJunk tc.\n    refine \n     {| sacpj_sac     := mkStrongAltCon\n      ; sacpj_phi       := fun Γ φ => (fun htv => φ htv >>= fun htv' => OK (weakV' htv'))\n      ; sacpj_psi       :=\n      fun Γ Δ avars ψ => (fun htv => ψ htv >>= fun htv' => OK (_ (weakCV' (vec2list (sac_ekinds mkStrongAltCon)) htv')))\n      |}.\n    intro.\n    unfold sac_gamma.\n    unfold HaskCoVar in *.\n    intros.\n    apply (x TV CV env).\n    simpl in cenv.\n    unfold sac_delta in *.\n    unfold InstantiatedCoercionEnv in *.\n    apply vec_chop' in cenv.\n    apply cenv.\n    Defined.\n\n  Lemma weakCK'_nil_inert : forall Γ Δ, (@weakCK'' Γ (@nil Kind)) Δ = Δ.\n    intros.\n    induction Δ.\n    reflexivity.\n    simpl.\n    rewrite IHΔ.\n    reflexivity.\n    Qed.\n  \nEnd StrongAltCon.\n\nDefinition mkStrongAltConPlusJunk' (tc : TyCon)(alt:WeakAltCon) : ???(@StrongAltConPlusJunk tc).\n  destruct alt.\n  set (c:DataCon _) as dc.\n  set ((dataConTyCon c):TyCon) as tc' in *.\n  set (eqd_dec tc tc') as eqpf; destruct eqpf;\n    [ idtac\n      | apply (Error (\"in a case of tycon \"+++toString tc+++\", found a branch with datacon \"+++toString (dc:CoreDataCon))) ]; subst.\n  apply OK.\n  eapply mkStrongAltConPlusJunk.\n  simpl in *.\n  apply dc.\n\n  apply OK; refine {| sacpj_sac := {| \n                     sac_ekinds  := vec_nil ; sac_coercions := fun _ _ => vec_nil ; sac_types := fun _ _ => vec_nil\n                    ; sac_altcon := WeakLitAlt h\n                    |} |}.\n            intro; intro φ; apply φ.\n            intro; intro; intro; intro ψ. simpl. unfold sac_gamma; simpl. unfold sac_delta; simpl.\n            rewrite weakCK'_nil_inert. apply ψ.\n  apply OK; refine {| sacpj_sac := {| \n                     sac_ekinds := vec_nil ; sac_coercions := fun _ _ => vec_nil ; sac_types := fun _ _ => vec_nil\n                      ; sac_altcon := WeakDEFAULT |} |}.\n            intro; intro φ; apply φ.\n            intro; intro; intro; intro ψ. simpl. unfold sac_gamma; simpl. unfold sac_delta; simpl.\n            rewrite weakCK'_nil_inert. apply ψ.\nDefined.\n\nDefinition weakExprVarToWeakType : WeakExprVar -> WeakType :=\n  fun wev => match wev with weakExprVar _ t => t end.\n  Coercion weakExprVarToWeakType : WeakExprVar >-> WeakType.\n\nVariable weakCoercionToHaskCoercion : forall Γ Δ κ, WeakCoercion -> HaskCoercion Γ Δ κ.\n\nDefinition weakPsi {Γ}{Δ:CoercionEnv Γ} {κ}(ψ:WeakCoerVar -> ???(HaskCoVar Γ Δ)) :\n  WeakCoerVar -> ???(HaskCoVar Γ (κ::Δ)).\n  intros.\n  refine (ψ X >>= _).\n  unfold HaskCoVar.\n  intros.\n  apply OK.\n  intros.\n  inversion cenv; auto.\n  Defined.\n\n(* attempt to \"cast\" an expression by simply checking if it already had the desired type, and failing otherwise *)\nDefinition castExpr (we:WeakExpr)(err_msg:string) {Γ} {Δ} {ξ} {τ} {l} τ' l' (e:@Expr _ CoreVarEqDecidable Γ Δ ξ τ l)\n  : ???(@Expr _ CoreVarEqDecidable Γ Δ ξ τ' l').\n  apply (addErrorMessage (\"castExpr \" +++ err_msg)).\n  intros.\n  destruct (eqd_dec l l'); [ idtac\n    | apply (Error (\"level mismatch in castExpr, invoked by \"+++err_msg+++eol+++\n                    \"  got: \" +++(fold_left (fun x y => y+++\",\"+++y) (map (toString ○ haskTyVarToType) l) \"\")+++eol+++\n                    \"  wanted: \"+++(fold_left (fun x y => x+++\",\"+++y) (map (toString ○ haskTyVarToType) l') \"\")\n    )) ].\n  destruct (eqd_dec τ τ'); [ idtac\n    | apply (Error (\"type mismatch in castExpr, invoked by \"+++err_msg+++eol+++\n                    \"  got: \" +++toString τ+++eol+++\n                    \"  wanted: \"+++toString τ'\n    )) ].\n  subst.\n  apply OK.\n  apply e.\n  Defined.\n\nDefinition coVarKind (wcv:WeakCoerVar) : Kind :=\n  match wcv with weakCoerVar _ t _ => (kindOfCoreType (weakTypeToCoreType t)) end.\n  Coercion coVarKind : WeakCoerVar >-> Kind.\n\nDefinition weakTypeToTypeOfKind : forall {Γ:TypeEnv}(φ:TyVarResolver Γ)(t:WeakType)(κ:Kind), ???(HaskType Γ κ).\n  intros.\n  set (weakTypeToType φ t) as wt.\n  destruct wt; try apply (Error error_message).\n  destruct h.\n  matchThings κ κ0 (\"Kind mismatch in weakTypeToTypeOfKind in \").\n  subst.\n  apply OK.\n  apply h.\n  Defined.\n\nFixpoint varsTypes {Γ}(t:Tree ??(WeakExprVar * WeakExpr))(φ:TyVarResolver Γ) : Tree ??(CoreVar * HaskType Γ ★) := \n  match t with\n    | T_Leaf None            => []\n    | T_Leaf (Some (wev,e))  => match weakTypeToTypeOfKind φ wev ★ with\n                                  | OK    t' => [((wev:CoreVar),t')]\n                                  | _        => []\n                                end\n    | T_Branch b1 b2         => (varsTypes b1 φ),,(varsTypes b2 φ)\n  end.\n\nFixpoint mkAvars {Γ}(wtl:list WeakType)(lk:list Kind)(φ:TyVarResolver Γ) : ???(IList Kind (HaskType Γ) lk) :=\nmatch lk as LK return ???(IList Kind (HaskType Γ) LK) with\n  | nil => match wtl with\n             | nil => OK INil\n             | _   => Error \"length mismatch in mkAvars\"\n           end\n  | k::lk' => match wtl with\n                | nil => Error \"length mismatch in mkAvars\"\n                | wt::wtl' =>\n                  weakTypeToTypeOfKind φ wt k >>= fun t =>\n                    mkAvars wtl' lk' φ >>= fun rest =>\n                    OK (ICons _ _ t rest)\n              end\nend.\n\nFixpoint update_ig (ig:CoreVar -> bool) (vars:list CoreVar) : CoreVar -> bool :=\n  match vars with\n    | nil => ig\n    | v::vars' =>\n      fun v' =>\n        if eqd_dec v v'\n          then false\n            else update_ig ig vars' v'\n  end.\n\n(* does the specified variable occur free in the expression? *)\nFixpoint doesWeakVarOccur (wev:WeakExprVar)(me:WeakExpr) : bool :=\n  match me with\n    | WELit    _        => false\n    | WEVar    cv       => if eqd_dec (wev:CoreVar) (cv:CoreVar) then true else false\n    | WECast   e co     =>                            doesWeakVarOccur wev e\n    | WENote   n e      =>                            doesWeakVarOccur wev e\n    | WETyApp  e t      =>                            doesWeakVarOccur wev e\n    | WECoApp  e co     =>                            doesWeakVarOccur wev e\n    | WEBrak _ ec e _   =>                            doesWeakVarOccur wev e\n    | WEEsc  _ ec e _   =>                            doesWeakVarOccur wev e\n    | WECSP  _ ec e _   =>                            doesWeakVarOccur wev e\n    | WELet    cv e1 e2 => doesWeakVarOccur wev e1 || (if eqd_dec (wev:CoreVar) (cv:CoreVar)then false else doesWeakVarOccur wev e2)\n    | WEApp    e1 e2    => doesWeakVarOccur wev e1 || doesWeakVarOccur wev e2\n    | WELam    cv e     => if eqd_dec (wev:CoreVar) (cv:CoreVar) then false else doesWeakVarOccur wev e\n(*\n    | WEKappaApp  e1 e2 => doesWeakVarOccur wev e1 || doesWeakVarOccur wev e2\n    | WEKappa  cv e     => if eqd_dec (wev:CoreVar) (cv:CoreVar) then false else doesWeakVarOccur wev e\n*)\n    | WETyLam  cv e     => doesWeakVarOccur wev e\n    | WECoLam  cv e     => doesWeakVarOccur wev e\n    | WECase vscrut escrut tbranches tc avars alts =>\n      doesWeakVarOccur wev escrut ||\n      if eqd_dec (wev:CoreVar) (vscrut:CoreVar) then false else\n        ((fix doesWeakVarOccurAlts alts {struct alts} : bool :=\n          match alts with\n            | T_Leaf  None                                         => false\n            | T_Leaf (Some (WeakDEFAULT,_,_,_,e))                      => doesWeakVarOccur wev e\n            | T_Leaf (Some (WeakLitAlt lit,_,_,_,e))                   => doesWeakVarOccur wev e\n            | T_Leaf (Some ((WeakDataAlt dc), tvars, cvars, evars,e))  => doesWeakVarOccur wev e  (* FIXME!!! *)\n            | T_Branch b1 b2                                       => doesWeakVarOccurAlts b1 || doesWeakVarOccurAlts b2\n          end) alts)\n    | WELetRec mlr e =>\n      doesWeakVarOccur wev e ||\n      (fix doesWeakVarOccurLetRec (mlr:Tree ??(WeakExprVar * WeakExpr)) : bool :=\n      match mlr with\n        | T_Leaf None          => false\n        | T_Leaf (Some (cv,e)) => if eqd_dec (wev:CoreVar) (cv:CoreVar) then false else doesWeakVarOccur wev e\n        | T_Branch b1 b2       => doesWeakVarOccurLetRec b1 || doesWeakVarOccurLetRec b2\n      end) mlr\n  end.\nFixpoint doesWeakVarOccurAlts (wev:WeakExprVar)\n  (alts:Tree ??(WeakAltCon * list WeakTypeVar * list WeakCoerVar * list WeakExprVar * WeakExpr)) : bool := \n  match alts with\n    | T_Leaf  None                                             => false\n    | T_Leaf (Some (WeakDEFAULT,_,_,_,e))                      => doesWeakVarOccur wev e\n    | T_Leaf (Some (WeakLitAlt lit,_,_,_,e))                   => doesWeakVarOccur wev e\n    | T_Leaf (Some ((WeakDataAlt dc), tvars, cvars, evars,e))  => doesWeakVarOccur wev e  (* FIXME!!! *)\n    | T_Branch b1 b2                                           => doesWeakVarOccurAlts wev b1 || doesWeakVarOccurAlts wev b2\n  end.\n\nDefinition checkDistinct :\n  forall {V}(EQ:EqDecidable V)(lv:list V), ???(distinct lv).\n  intros.\n  set (distinct_decidable lv) as q.\n  destruct q.\n  exact (OK d).\n  exact (Error \"checkDistinct failed\").\n  Defined.\n\n(* FIXME: check the kind of the type of the weakexprvar to support >0 *)\nDefinition mkGlobal Γ (τ:HaskType Γ ★) (wev:WeakExprVar) : Global Γ.\n  refine {| glob_kinds := nil |}.\n  apply wev.\n  intros.\n  apply τ.\n  Defined.\n\nDefinition weakExprToStrongExpr : forall\n    (Γ:TypeEnv)\n    (Δ:CoercionEnv Γ)\n    (φ:TyVarResolver Γ)\n    (ψ:CoVarResolver Γ Δ)\n    (ξ:CoreVar -> LeveledHaskType Γ ★)\n    (ig:CoreVar -> bool)\n    (τ:HaskType Γ ★)\n    (lev:HaskLevel Γ),\n    WeakExpr -> ???(@Expr _ CoreVarEqDecidable Γ Δ ξ τ lev ).\n  refine ((\n    fix weakExprToStrongExpr \n    (Γ:TypeEnv)\n    (Δ:CoercionEnv Γ)\n    (φ:TyVarResolver Γ)\n    (ψ:CoVarResolver Γ Δ)\n    (ξ:CoreVar -> LeveledHaskType Γ ★)\n    (ig:CoreVar -> bool)\n    (τ:HaskType Γ ★)\n    (lev:HaskLevel Γ)\n    (we:WeakExpr) : ???(@Expr _ CoreVarEqDecidable Γ Δ ξ τ lev )  :=\n    addErrorMessage (\"in weakExprToStrongExpr \" +++ toString we)\n    match we with\n\n    | WEVar   v                         => if ig v\n                                              then OK ((EGlobal Γ Δ ξ (mkGlobal Γ τ v) INil lev) : Expr Γ Δ ξ τ lev)\n                                              else castExpr we (\"WEVar \"+++toString (v:CoreVar)) τ lev (EVar Γ Δ ξ v)\n\n    | WELit   lit                       => castExpr we (\"WELit \"+++toString lit) τ lev (ELit Γ Δ ξ lit lev)\n\n    | WELam   ev ebody                  => weakTypeToTypeOfKind φ ev ★ >>= fun tv =>\n                                             weakTypeOfWeakExpr ebody >>= fun tbody =>\n                                               weakTypeToTypeOfKind φ tbody ★ >>= fun tbody' =>\n                                                 let ξ' := update_xi ξ lev (((ev:CoreVar),tv)::nil) in\n                                                 let ig' := update_ig ig ((ev:CoreVar)::nil) in\n                                                   weakExprToStrongExpr Γ Δ φ ψ ξ' ig' tbody' lev ebody >>= fun ebody' =>\n                                                     castExpr we \"WELam\" τ lev (ELam Γ Δ ξ tv tbody' lev ev ebody')\n\n    | WEBrak  _ ec e tbody              => φ (`ec) >>= fun ec' =>\n                                             weakTypeToTypeOfKind φ tbody ★ >>= fun tbody' =>\n                                               weakExprToStrongExpr Γ Δ φ ψ ξ ig tbody' ((ec')::lev) e >>= fun e' =>\n                                                 castExpr we \"WEBrak\" τ lev (EBrak Γ Δ ξ ec' tbody' lev e')\n\n    | WEEsc   _ ec e tbody              => φ ec >>= fun ec'' =>\n                                           weakTypeToTypeOfKind φ tbody ★ >>= fun tbody' =>\n                                           match lev with\n                                             | nil       => Error \"ill-leveled escapification\"\n                                             | ec'::lev' => weakExprToStrongExpr Γ Δ φ ψ ξ ig (<[ ec' |- tbody' ]>) lev' e\n                                               >>= fun e' => castExpr we \"WEEsc\" τ lev (EEsc Γ Δ ξ ec' tbody' lev' e')\n                                           end\n\n    | WECSP   _ ec e tbody              => Error \"FIXME: CSP not supported beyond HaskWeak stage\"\n\n    | WENote  n e                       => weakExprToStrongExpr Γ Δ φ ψ ξ ig τ lev e >>= fun e' => OK (ENote _ _ _ _ _ n e')\n\n    | WELet   v ve  ebody               => weakTypeToTypeOfKind φ v ★  >>= fun tv =>\n                                             weakExprToStrongExpr Γ Δ φ ψ ξ ig tv lev ve >>= fun ve' =>\n                                               weakExprToStrongExpr Γ Δ φ ψ (update_xi ξ lev (((v:CoreVar),tv)::nil))\n                                                    (update_ig ig ((v:CoreVar)::nil)) τ lev ebody\n                                               >>= fun ebody' =>\n                                                 OK (ELet _ _ _ tv _ lev (v:CoreVar) ve' ebody')\n\n    | WEApp   e1 e2                     => weakTypeOfWeakExpr e2 >>= fun t2 =>\n                                             weakTypeToTypeOfKind φ t2 ★ >>= fun t2' =>\n                                               weakExprToStrongExpr Γ Δ φ ψ ξ ig t2' lev e2 >>= fun e2' =>\n                                                 weakExprToStrongExpr Γ Δ φ ψ ξ ig (t2'--->τ) lev e1 >>= fun e1' =>\n                                                   OK (EApp _ _ _ _ _ _ e1' e2')\n\n    | WETyLam tv e                      => let φ2 := upPhi tv φ in\n                                             weakTypeOfWeakExpr e >>= fun te =>\n                                               weakTypeToTypeOfKind φ2 te ★ >>= fun τ' =>\n                                                 weakExprToStrongExpr _ (weakCE_(n:=O) Δ) φ2\n                                                   (fun x => (ψ x) >>= fun y =>\n                                                     OK (weakCV_ y)) (weakLT_○ξ) ig _ (weakL_ lev) e\n                                                   >>= fun e' => castExpr we \"WETyLam2\" _ _\n                                                     (ETyLam Γ Δ ξ tv (mkTAll' τ') lev 0 e')\n\n    | WETyApp e t                       => weakTypeOfWeakExpr e >>= fun te =>\n                                           match te with\n                                             | WForAllTy wtv te' =>\n                                               let φ2 := upPhi wtv φ in\n                                                 weakTypeToTypeOfKind φ2 te' ★ >>= fun te'' =>\n                                                   weakExprToStrongExpr Γ Δ φ ψ ξ ig (mkTAll te'') lev e >>= fun e' =>\n                                                     weakTypeToTypeOfKind φ t (wtv:Kind) >>= fun t' =>\n                                                       castExpr we \"WETyApp\" _ _ (ETyApp Γ Δ wtv (mkTAll' te'') t' ξ lev e')\n                                             | _                 => Error (\"weakTypeToType: WETyApp body with type \"+++toString te)\n                                           end\n\n    | WECoApp e co                     => weakTypeOfWeakExpr e >>= fun te =>\n                                           match te with\n                                             | WCoFunTy t1 t2 t3 =>\n                                               weakTypeToType φ t1 >>= fun t1' =>\n                                                 match t1' with\n                                                   haskTypeOfSomeKind κ t1'' =>\n                                                   weakTypeToTypeOfKind φ t2 κ >>= fun t2'' =>\n                                                     weakTypeToTypeOfKind φ t3 ★ >>= fun t3'' =>\n                                                       weakExprToStrongExpr Γ Δ φ ψ ξ ig (t1'' ∼∼ t2'' ⇒ τ) lev e >>= fun e' =>\n                                                         castExpr we \"WECoApp\" _ _ e' >>= fun e'' =>\n                                                           OK (ECoApp Γ Δ κ t1'' t2''\n                                                             (weakCoercionToHaskCoercion _ _ _ co) τ ξ lev e'')\n                                                 end\n                                             | _                 => Error (\"weakTypeToType: WECoApp body with type \"+++toString te)\n                                           end\n\n    | WECoLam cv e                      => let (_,t1,t2) := cv in\n                                           weakTypeOfWeakExpr e >>= fun te =>\n                                             weakTypeToTypeOfKind φ te ★ >>= fun te' =>\n                                               weakTypeToTypeOfKind φ t1 cv >>= fun t1' =>\n                                                 weakTypeToTypeOfKind φ t2 cv >>= fun t2' =>\n                                                   weakExprToStrongExpr Γ (_ :: Δ) φ (weakPsi ψ) ξ ig te' lev e >>= fun e' =>\n                                                     castExpr we \"WECoLam\" _ _ (ECoLam Γ Δ cv te' t1' t2' ξ lev e')\n\n    | WECast  e co                      => let (t1,t2) := weakCoercionTypes co in\n                                             weakTypeToTypeOfKind φ t1 ★ >>= fun t1' =>\n                                               weakTypeToTypeOfKind φ t2 ★ >>= fun t2' =>\n                                                   weakExprToStrongExpr Γ Δ φ ψ ξ ig t1' lev e >>= fun e' =>\n                                                     castExpr we \"WECast\" _ _\n                                                       (ECast Γ Δ ξ t1' t2' (weakCoercionToHaskCoercion _ _ _ co) lev e')\n\n    | WELetRec rb   e                   =>\n      let ξ' := update_xi ξ lev _ in\n      let ig' := update_ig ig (map (fun x:(WeakExprVar*_) => (fst x):CoreVar) (leaves rb)) in\n      let binds := \n        (fix binds (t:Tree ??(WeakExprVar * WeakExpr))\n          : ???(ELetRecBindings Γ Δ ξ' lev (varsTypes t φ)) :=\n        match t with\n          | T_Leaf None           => let case_nil := tt in OK (ELR_nil _ _ _ _)\n          | T_Leaf (Some (wev,e)) => let case_some := tt in (fun e' => _) (fun τ => weakExprToStrongExpr Γ Δ φ ψ ξ' ig' τ lev e)\n          | T_Branch b1 b2        =>\n            binds b1 >>= fun b1' =>\n              binds b2 >>= fun b2' =>\n                OK (ELR_branch Γ Δ ξ' lev _ _ b1' b2')\n        end) rb\n      in binds >>= fun binds' =>\n         checkDistinct CoreVarEqDecidable (map (@fst _ _) (leaves (varsTypes rb φ))) >>= fun rb_distinct =>\n           weakExprToStrongExpr Γ Δ φ ψ ξ' ig' τ lev e >>= fun e' =>       \n             OK (ELetRec Γ Δ ξ lev τ _ _ binds' e')\n\n    | WECase vscrut escrut tbranches tc avars alts =>\n        weakTypeOfWeakExpr escrut >>= fun tscrut =>\n          weakTypeToTypeOfKind φ tscrut ★ >>= fun tscrut' =>\n            if doesWeakVarOccurAlts vscrut alts\n            then Error \"encountered a Case which actually used its binder - these should have been desugared away!!\"\n            else mkAvars avars (tyConKind tc) φ >>= fun avars' =>\n                weakTypeToTypeOfKind φ tbranches ★  >>= fun tbranches' =>\n                  (fix mkTree (t:Tree ??(WeakAltCon*list WeakTypeVar*list WeakCoerVar*list WeakExprVar*WeakExpr)) : ???(Tree\n                      ??{ sac : _ & {scb : StrongCaseBranchWithVVs CoreVar CoreVarEqDecidable tc avars' sac &\n                        Expr (sac_gamma sac Γ) (sac_delta sac Γ avars' (weakCK'' Δ))(scbwv_xi scb ξ lev)(weakT' tbranches')(weakL' lev)}}) := \n                    match t with\n                      | T_Leaf None           => OK []\n                      | T_Leaf (Some (ac,extyvars,coervars,exprvars,ebranch)) => \n                        mkStrongAltConPlusJunk' tc ac >>= fun sac =>\n                          list2vecOrFail (map (fun ev:WeakExprVar => ev:CoreVar) exprvars) _ (fun _ _ => \"WECase\")\n                          >>= fun exprvars' =>\n                            (let case_pf := tt in _) >>= fun pf =>\n                            let scb := @Build_StrongCaseBranchWithVVs CoreVar CoreVarEqDecidable tc Γ avars' sac exprvars' pf in\n                              weakExprToStrongExpr (sac_gamma sac Γ) (sac_delta sac Γ avars' (weakCK'' Δ)) (sacpj_phi sac _ φ)\n                              (sacpj_psi sac _ _ avars' ψ)\n                              (scbwv_xi scb ξ lev)\n                              (update_ig ig (map (@fst _ _) (vec2list (scbwv_varstypes scb))))\n                              (weakT' tbranches') (weakL' lev) ebranch >>= fun ebranch' =>\n                                let case_case := tt in OK [ _ ]\n                      | T_Branch b1 b2        =>\n                        mkTree b1 >>= fun b1' =>\n                          mkTree b2 >>= fun b2' =>\n                            OK (b1',,b2')\n                    end) alts >>= fun tree =>\n\n                    weakExprToStrongExpr Γ Δ φ ψ ξ ig (caseType tc avars') lev escrut >>= fun escrut' =>\n                      castExpr we \"ECase\" τ lev (ECase Γ Δ ξ lev tc tbranches' avars' escrut' tree)\n    end)); try clear binds; try apply ConcatenableString.\n  \n    destruct case_some.\n    apply (addErrorMessage \"case_some\").\n      simpl.\n      destruct (weakTypeToTypeOfKind φ wev ★); try apply (Error error_message).\n      matchThings h (unlev (ξ' wev)) \"LetRec\".\n      destruct wev.\n      rewrite matchTypeVars_pf.\n      clear matchTypeVars_pf.\n      set (e' (unlev (ξ' (weakExprVar c w)))) as e''.\n      destruct e''; try apply (Error error_message).\n      apply OK.\n      apply ELR_leaf.\n      unfold ξ'.\n      simpl.\n      induction (leaves (varsTypes rb φ)).\n        simpl; auto.\n        destruct (ξ c).\n        simpl.\n      apply e1.\n      rewrite mapleaves.\n      apply rb_distinct.\n\n    destruct case_pf.\n      set (distinct_decidable (vec2list exprvars')) as dec.\n      destruct dec; [ idtac | apply (Error \"malformed HaskWeak: case branch with variables repeated\") ].\n      apply OK; auto.\n\n    destruct case_case.\n      exists sac.\n      exists scb.\n      apply ebranch'.\n\n    Defined.\n\n", "meta": {"author": "cartazio", "repo": "coq-hetmet", "sha": "0a6fb1705e459370d0afab10fed55e4165bf0fa8", "save_path": "github-repos/coq/cartazio-coq-hetmet", "path": "github-repos/coq/cartazio-coq-hetmet/coq-hetmet-0a6fb1705e459370d0afab10fed55e4165bf0fa8/src/HaskWeakToStrong.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.21573477478695915}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import ASI_mmap0.\nRequire Import malloc.\nRequire Import ASI_malloc.\nRequire Import malloc_lemmas.\nRequire Import malloc_sep.\n\nDefinition Tok_APD := Build_MallocTokenAPD malloc_token' malloc_token'_valid_pointer\n                    malloc_token'_local_facts.\n\nDefinition R_APD := Build_MallocFree_R_APD Tok_APD mem_mgr_R.\n\n(*+ specs of private functions *)\n\nDefinition bin2size_spec :=\n DECLARE _bin2size\n  WITH b: Z\n  PRE [ tint ] \n     PROP( 0 <= b < BINS ) \n     PARAMS ((Vint (Int.repr b))) GLOBALS () SEP ()\n  POST [ tuint ] \n     PROP() LOCAL(temp ret_temp (Vptrofs (Ptrofs.repr (bin2sizeZ b)))) SEP ().\n\nDefinition size2bin_spec :=\n DECLARE _size2bin\n  WITH s: Z\n  PRE [ tuint ]    \n     PROP( 0 <= s <= Ptrofs.max_unsigned ) \n     PARAMS ((Vptrofs (Ptrofs.repr s))) GLOBALS () SEP ()\n  POST [ tint ]\n     PROP() LOCAL(temp ret_temp (Vint (Int.repr (size2binZ s)))) SEP ().\n\n\nDefinition list_from_block_spec :=\n DECLARE _list_from_block\n  WITH s: Z, p: val, tl: val, tlen: nat, b: Z\n  PRE [ tuint, tptr tschar, tptr tvoid ]    \n     PROP( 0 <= b < BINS /\\ s = bin2sizeZ b /\\ malloc_compatible BIGBLOCK p ) \n     PARAMS ((Vptrofs (Ptrofs.repr s)); p; tl) GLOBALS ()\n     SEP ( memory_block Tsh BIGBLOCK p; mmlist s tlen tl nullval )\n  POST [ tptr tvoid ] EX res:_,\n     PROP() \n     LOCAL(temp ret_temp res)\n     SEP ( mmlist s (Z.to_nat(chunks_from_block (size2binZ s)) + tlen) res nullval * TT ).\n\n\n(* The postcondition describes the list returned, together with\n   TT for the wasted space at the beginning and end of the big block from mmap. *)\n\nDefinition fill_bin_spec :=\n DECLARE _fill_bin\n  WITH b: _\n  PRE [ tint ]\n     PROP(0 <= b < BINS) PARAMS ((Vint (Int.repr b))) GLOBALS () SEP ()\n  POST [ (tptr tvoid) ] EX p:_, EX len:Z,\n     PROP( if eq_dec p nullval then True else len > 0 ) \n     LOCAL(temp ret_temp p)\n     SEP ( if eq_dec p nullval then emp\n           else mmlist (bin2sizeZ b) (Z.to_nat len) p nullval * TT).\n\nDefinition malloc_small_spec :=\n   DECLARE _malloc_small\n   WITH n:Z, gv:globals, rvec:resvec\n   PRE [ size_t ] \n       PROP (0 <= n <= bin2sizeZ(BINS-1))\n       PARAMS ((Vptrofs (Ptrofs.repr n))) GLOBALS (gv)\n       SEP ( mem_mgr_R rvec gv)\n   POST [ tptr tvoid ] EX p:_, \n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP ( if guaranteed rvec n\n             then mem_mgr_R (add_resvec rvec (size2binZ n) (-1)) gv *\n                  malloc_token' Ews n p * memory_block Ews n p\n             else if eq_dec p nullval \n                  then mem_mgr_R rvec gv\n                  else (EX rvec':_, !!(eq_except rvec' rvec (size2binZ n))\n                                 && mem_mgr_R rvec' gv *\n                                    malloc_token' Ews n p * memory_block Ews n p) ).\n\nDefinition malloc_large_spec :=\n   DECLARE _malloc_large\n   WITH n:Z, gv:globals, rvec:resvec\n   PRE [ size_t ]\n       PROP (bin2sizeZ(BINS-1) < n <= Ptrofs.max_unsigned - (WA+WORD))\n       PARAMS ((Vptrofs (Ptrofs.repr n))) GLOBALS (gv)\n       SEP ( mem_mgr_R rvec gv)\n   POST [ tptr tvoid ] EX p:_, \n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (mem_mgr_R rvec gv;\n            if eq_dec p nullval then emp \n            else malloc_token' Ews n p * memory_block Ews n p).\n\n(* s is the stored chunk size and n is the original request amount. *)\n(* Note: the role of n in free_small_spec is merely to facilitate proof for free itself *)\nDefinition free_small_spec :=\n   DECLARE _free_small\n   WITH p:_, s:_, n:_, gv:globals, rvec:resvec\n   PRE [ tptr tvoid, tuint ]\n       PROP (0 <= n <= bin2sizeZ(BINS-1) /\\ s = bin2sizeZ(size2binZ n) /\\ \n             malloc_compatible s p)\n       PARAMS (p; (Vptrofs (Ptrofs.repr s))) GLOBALS (gv)\n       SEP ( data_at Tsh tuint (Vptrofs (Ptrofs.repr s)) (offset_val (- WORD) p); \n            data_at_ Tsh (tptr tvoid) p;\n            memory_block Tsh (s - WORD) (offset_val WORD p);\n            mem_mgr_R rvec gv)\n   POST [ tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (mem_mgr_R (add_resvec rvec (size2binZ n) 1) gv).\n\nDefinition free_large_spec :=\n   DECLARE _free_large\n   WITH p:_, s:_, gv:globals, rvec:resvec\n   PRE [ tptr tvoid, tuint ]\n       PROP (malloc_compatible s p /\\ maxSmallChunk < s <= Ptrofs.max_unsigned - (WA+WORD))\n       PARAMS (p; (Vptrofs (Ptrofs.repr s))) GLOBALS (gv)\n       SEP ( data_at Tsh tuint (Vptrofs (Ptrofs.repr s)) (offset_val (- WORD) p); \n            data_at_ Tsh (tptr tvoid) p;\n            memory_block Tsh (s - WORD) (offset_val WORD p);\n            memory_block Tsh WA (offset_val (- (WA+WORD)) p);\n            mem_mgr_R rvec gv)\n   POST [ tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (mem_mgr_R rvec gv).\n\nDefinition MF_Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition MF_internal_specs: funspecs :=\n    [malloc_large_spec; malloc_small_spec; free_large_spec; free_small_spec;\n     bin2size_spec; size2bin_spec; list_from_block_spec; fill_bin_spec]\n   ++ Malloc_R_ASI R_APD _pre_fill _try_pre_fill _malloc _free.\n\nDefinition MF_Imports:funspecs := Mmap0_ASI _mmap0 _munmap.\n\nDefinition MF_Gprog:funspecs := MF_Imports ++ MF_internal_specs.\n\nLtac start_function_hint ::= idtac. (* no hint reminder *)\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/memmgr/VSU_malloc_definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.21568617975659904}}
{"text": "From Coq Require Import Lists.List.\nFrom Coq Require Import micromega.Lia.\nFrom Coq Require Import ZArith.ZArith.\n\nFrom VST Require Import floyd.proofauto.\nFrom VST Require Import floyd.functional_base.\n\nFrom CertiGraph Require Import graph.graph_gen.\nFrom CertiGraph Require Import graph.graph_model.\nFrom CertiGraph Require Import lib.EquivDec_ext.\nFrom CertiGraph Require Import lib.List_ext.\n\nFrom CertiGC Require Import model.compatible.compatible.\nFrom CertiGC Require Import model.constants.\nFrom CertiGC Require Import model.heap.heap.\nFrom CertiGC Require Import model.heapgraph.block.block.\nFrom CertiGC Require Import model.heapgraph.block.ptr.\nFrom CertiGC Require Import model.heapgraph.block.cell.\nFrom CertiGC Require Import model.heapgraph.block.field.\nFrom CertiGC Require Import model.heapgraph.field_pairs.\nFrom CertiGC Require Import model.heapgraph.generation.generation.\nFrom CertiGC Require Import model.heapgraph.graph.\nFrom CertiGC Require Import model.heapgraph.has_block.\nFrom CertiGC Require Import model.heapgraph.has_field.\nFrom CertiGC Require Import model.heapgraph.mark.\nFrom CertiGC Require Import model.heapgraph.predicates.\nFrom CertiGC Require Import model.heapgraph.remset.remset.\nFrom CertiGC Require Import model.heapgraph.roots.\nFrom CertiGC Require Import model.op.copy.\nFrom CertiGC Require Import model.op.cut.\nFrom CertiGC Require Import model.op.update.\nFrom CertiGC Require Import model.thread_info.thread_info.\nFrom CertiGC Require Import model.util.\n\nDefinition forward_t: Type := Z + GC_Pointer + Addr + Field.\n\nDefinition root2forward (r: root_t): forward_t :=\n  match r with\n  | inl (inl z) => inl (inl (inl z))\n  | inl (inr p) => inl (inl (inr p))\n  | inr v => inl (inr v)\n  end.\n\nDefinition field2forward (f: Cell): forward_t :=\n  match f with\n  | inl (inl z) => inl (inl (inl z))\n  | inl (inr p) => inl (inl (inr p))\n  | inr e => inr e\n  end.\n\nDefinition forward_p_type: Type := Z + (Addr * Z).\n\n#[global]Instance forward_p_type_Inhabitant: Inhabitant forward_p_type := inl 0.\n\nDefinition forward_p2forward_t\n           (p: forward_p_type) (roots: roots_t) (g: HeapGraph): forward_t :=\n  match p with\n  | inl root_index => root2forward (Znth root_index roots)\n  | inr (v, n) => if (heapgraph_block g v).(block_mark) && (n =? 0)\n                  then (inl (inr (heapgraph_block g v).(block_copied_vertex)))\n                  else field2forward (Znth n (heapgraph_block_cells g v))\n  end.\n\nInductive forward_relation (from to: nat):\n  nat -> forward_t -> HeapGraph -> HeapGraph -> Prop :=\n| fr_z: forall depth z g, forward_relation from to depth (inl (inl (inl z))) g g\n| fr_p: forall depth p g, forward_relation from to depth (inl (inl (inr p))) g g\n| fr_v_not_in: forall depth v g,\n    addr_gen v <> from -> forward_relation from to depth (inl (inr v)) g g\n| fr_v_in_forwarded: forall depth v g,\n    addr_gen v = from -> (heapgraph_block g v).(block_mark) = true ->\n    forward_relation from to depth (inl (inr v)) g g\n| fr_v_in_not_forwarded_O: forall v g,\n    addr_gen v = from -> (heapgraph_block g v).(block_mark) = false ->\n    forward_relation from to O (inl (inr v)) g (lgraph_copy_v g v to)\n| fr_v_in_not_forwarded_Sn: forall depth v g g',\n    addr_gen v = from -> (heapgraph_block g v).(block_mark) = false ->\n    let new_g := lgraph_copy_v g v to in\n    forward_loop from to depth (heapgraph_field_pairs new_g (new_copied_v g to)) new_g g' ->\n    forward_relation from to (S depth) (inl (inr v)) g g'\n| fr_e_not_to: forall depth e (g: HeapGraph),\n    addr_gen (dst g e) <> from -> forward_relation from to depth (inr e) g g\n| fr_e_to_forwarded: forall depth e (g: HeapGraph),\n    addr_gen (dst g e) = from -> (heapgraph_block g (dst g e)).(block_mark) = true ->\n    let new_g := labeledgraph_gen_dst g e (heapgraph_block g (dst g e)).(block_copied_vertex) in\n    forward_relation from to depth (inr e) g new_g\n| fr_e_to_not_forwarded_O: forall e (g: HeapGraph),\n    addr_gen (dst g e) = from -> (heapgraph_block g (dst g e)).(block_mark) = false ->\n    let new_g := labeledgraph_gen_dst (lgraph_copy_v g (dst g e) to) e\n                                      (new_copied_v g to) in\n    forward_relation from to O (inr e) g new_g\n| fr_e_to_not_forwarded_Sn: forall depth e (g g': HeapGraph),\n    addr_gen (dst g e) = from -> (heapgraph_block g (dst g e)).(block_mark) = false ->\n    let new_g := labeledgraph_gen_dst (lgraph_copy_v g (dst g e) to) e\n                                      (new_copied_v g to) in\n    forward_loop from to depth (heapgraph_field_pairs new_g (new_copied_v g to)) new_g g' ->\n    forward_relation from to (S depth) (inr e) g g'\nwith\nforward_loop (from to: nat): nat -> list forward_p_type -> HeapGraph -> HeapGraph -> Prop :=\n| fl_nil: forall depth g, forward_loop from to depth nil g g\n| fl_cons: forall depth g1 g2 g3 f fl,\n    forward_relation from to depth (forward_p2forward_t f nil g1) g1 g2 ->\n    forward_loop from to depth fl g2 g3 -> forward_loop from to depth (f :: fl) g1 g3.\n\nLemma fr_general_prop_bootstrap: forall depth from to p g g'\n                                        (P: nat -> HeapGraph -> HeapGraph -> Prop),\n    (forall to g, P to g g) ->\n    (forall to g1 g2 g3, P to g1 g2 -> P to g2 g3 -> P to g1 g3) ->\n    (forall to g e v, P to g (labeledgraph_gen_dst g e v)) ->\n    (forall to g v, P to g (lgraph_copy_v g v to)) ->\n    forward_relation from to depth p g g' -> P to g g'.\nProof.\n  induction depth; intros.\n  - inversion H3; subst; try (specialize (H to g'); assumption).\n    + apply H2.\n    + subst new_g. apply H1.\n    + subst new_g. remember (lgraph_copy_v g (dst g e) to) as g1.\n      remember (labeledgraph_gen_dst g1 e (new_copied_v g to)) as g2.\n      cut (P to g1 g2). 2: subst; apply H1. intros. apply (H0 to g g1 g2).\n      2: assumption. subst g1. apply H2.\n  - assert (forall l from to g1 g2,\n                 forward_loop from to depth l g1 g2 -> P to g1 g2). {\n    induction l; intros; inversion H4. 1: apply H. subst.\n    specialize (IHl _ _ _ _ H11). specialize (IHdepth _ _ _ _ _ _ H H0 H1 H2 H8).\n    apply (H0 _ _ _ _ IHdepth IHl). }\n    clear IHdepth. inversion H3; subst; try (specialize (H to g'); assumption).\n    + cut (P to g new_g).\n      * intros. apply (H0 to g new_g g'). 1: assumption. apply (H4 _ _ _ _ _ H8).\n      * subst new_g. apply H2.\n    + subst new_g. apply H1.\n    + cut (P to g new_g).\n      * intros. apply (H0 to g new_g g'). 1: assumption. apply (H4 _ _ _ _ _ H8).\n      * subst new_g. remember (lgraph_copy_v g (dst g e) to) as g1.\n        remember (labeledgraph_gen_dst g1 e (new_copied_v g to)) as g2.\n        cut (P to g1 g2). 2: subst; apply H1. intros. apply (H0 to g g1 g2).\n        2: assumption. subst g1. apply H2.\nQed.\n\nLemma fr_graph_has_gen: forall depth from to p g g',\n    heapgraph_has_gen g to -> forward_relation from to depth p g g' ->\n    forall x, heapgraph_has_gen g x <-> heapgraph_has_gen g' x.\nProof.\n  intros. remember (fun to g1 g2 =>\n                      heapgraph_has_gen g1 to ->\n                      forall x, heapgraph_has_gen g1 x <-> heapgraph_has_gen g2 x) as P.\n  pose proof (fr_general_prop_bootstrap depth from to p g g' P). subst P.\n  apply H1; clear H1; intros; try assumption; try reflexivity.\n  - rewrite H1 by assumption. apply H2. rewrite <- H1; assumption.\n  - apply lcv_graph_has_gen. assumption.\nQed.\n\nLemma fr__heapgraph_block_is_no_scan from to depth x g1 g2\n  (H: forward_relation from to depth x g1 g2):\n  forall v, heapgraph_block_is_no_scan g1 v <-> heapgraph_block_is_no_scan g2 v.\nProof.\n  admit.\nAdmitted.\n\nLemma fl_graph_has_gen: forall from to depth l g g',\n    heapgraph_has_gen g to -> forward_loop from to depth l g g' ->\n    forall x, heapgraph_has_gen g x <-> heapgraph_has_gen g' x.\nProof.\n  intros. revert g g' H H0 x. induction l; intros; inversion H0. 1: reflexivity.\n  subst. assert (forall y, heapgraph_has_gen g y <-> heapgraph_has_gen g2 y) by\n      (intros; apply (fr_graph_has_gen _ _ _ _ _ _ H H4)).\n  transitivity (heapgraph_has_gen g2 x). 1: apply H1. rewrite H1 in H.\n  apply IHl; assumption.\nQed.\n\nLemma fr_general_prop:\n  forall depth from to p g g' A (Q: HeapGraph -> A -> nat -> Prop)\n         (P: HeapGraph -> HeapGraph -> A -> Prop) (R: nat -> nat -> Prop),\n    R from to -> heapgraph_has_gen g to -> (forall g v, P g g v) ->\n    (forall g1 g2 g3 v, P g1 g2 v -> P g2 g3 v -> P g1 g3 v) ->\n    (forall g e v x, P g (labeledgraph_gen_dst g e v) x) ->\n    (forall from g v to x,\n        heapgraph_has_gen g to -> Q g x from -> (heapgraph_block g v).(block_mark) = false ->\n        R from to -> addr_gen v = from -> P g (lgraph_copy_v g v to) x) ->\n    (forall depth from to p g g',\n        heapgraph_has_gen g to -> forward_relation from to depth p g g' ->\n        forall v, Q g v from -> Q g' v from) ->\n    (forall g v to x from, heapgraph_has_gen g to -> Q g x from ->\n                           Q (lgraph_copy_v g v to) x from) ->\n    (forall g e v x from, Q g x from -> Q (labeledgraph_gen_dst g e v) x from) ->\n    forward_relation from to depth p g g' ->\n    forall v, Q g v from -> P g g' v.\nProof.\n  induction depth; intros.\n  - inversion H8; subst; try (specialize (H1 g' v); assumption).\n    + apply (H4 (addr_gen v0)); [assumption.. | reflexivity].\n    + subst new_g. apply H3.\n    + subst new_g. remember (lgraph_copy_v g (dst g e) to) as g1.\n      remember (labeledgraph_gen_dst g1 e (new_copied_v g to)) as g2.\n      cut (P g1 g2 v). 2: subst; apply H3. intros. apply (H2 g g1 g2).\n      2: assumption. subst g1.\n      apply (H4 (addr_gen (dst g e))); [assumption.. | reflexivity].\n  - assert (forall l from to g1 g2,\n               heapgraph_has_gen g1 to -> forward_loop from to depth l g1 g2 ->\n               R from to -> forall v, Q g1 v from -> P g1 g2 v). {\n      induction l; intros; inversion H11. 1: apply H1. subst.\n      specialize (IHdepth _ _ _ _ _ _ _ _ _ H12 H10 H1 H2 H3 H4 H5 H6 H7 H17 _ H13).\n      apply (H5 _ _ _ _ _ _ H10 H17) in H13.\n      rewrite (fr_graph_has_gen _ _ _ _ _ _ H10 H17) in H10.\n      specialize (IHl _ _ _ _ H10 H20 H12 _ H13). apply (H2 _ _ _ _ IHdepth IHl). }\n    clear IHdepth. inversion H8; subst; try (specialize (H1 g' v); assumption).\n    + cut (P g new_g v).\n      * intros. apply (H2 g new_g g'). 1: assumption.\n        assert (heapgraph_has_gen new_g to) by\n            (subst new_g; rewrite <- lcv_graph_has_gen; assumption).\n        apply (H10 _ _ _ _ _ H12 H14 H). subst new_g. apply H6; assumption.\n      * subst new_g. apply (H4 (addr_gen v0)); [assumption.. | reflexivity].\n    + subst new_g. apply H3.\n    + cut (P g new_g v).\n      * intros. apply (H2 g new_g g'). 1: assumption.\n        assert (heapgraph_has_gen new_g to) by\n            (subst new_g; rewrite lgd_graph_has_gen, <- lcv_graph_has_gen; assumption).\n        apply (H10 _ _ _ _ _ H12 H14 H). subst new_g. apply H7, H6; assumption.\n      * subst new_g. remember (lgraph_copy_v g (dst g e) to) as g1.\n        remember (labeledgraph_gen_dst g1 e (new_copied_v g to)) as g2.\n        cut (P g1 g2 v). 2: subst; apply H3. intros. apply (H2 g g1 g2).\n        2: assumption. subst g1.\n        apply (H4 (addr_gen (dst g e))); [assumption.. | reflexivity].\nQed.\n\nLemma fr_heapgraph_has_block (depth from to: nat) (p: forward_t) (g g': HeapGraph)\n    (Hto: heapgraph_has_gen g to)\n    (Hg__g': forward_relation from to depth p g g')\n    (v: Addr)\n    (Hv: heapgraph_has_block g v):\n    heapgraph_has_block g' v.\nProof.\n    remember (fun (g: HeapGraph) (v: Addr) (x: nat) => True) as Q.\n    remember (fun g1 g2 v => heapgraph_has_block g1 v -> heapgraph_has_block g2 v) as P.\n    remember (fun (x1 x2: nat) => True) as R.\n    pose proof (fr_general_prop depth from to p g g' _ Q P R) as HP.\n    subst Q P R.\n    apply HP; clear HP ; try easy.\n    + intros g1 g2 g3 w Hg1g2 Hg2g3 Hg1.\n      now apply Hg2g3, Hg1g2.\n    + intros g'' f w u Hu.\n      destruct Hu ; now constructor.\n    + intros from' g'' w to' u Hg'' _ Hw _ Efrom' Hu.\n      unfold lgraph_copy_v ; rewrite <- lmc_heapgraph_has_block.\n      now apply lgraph_add_copied_v__heapgraph_has_block.\nQed.\n\n\nLemma fr_gen_start: forall depth from to p g g',\n    heapgraph_has_gen g to -> forward_relation from to depth p g g' ->\n    forall x, heapgraph_generation_base g x = heapgraph_generation_base g' x.\nProof.\n  intros. remember (fun (g: HeapGraph) (v: nat) (x: nat) => True) as Q.\n  remember (fun g1 g2 x => heapgraph_generation_base g1 x = heapgraph_generation_base g2 x) as P.\n  remember (fun (x1 x2: nat) => True) as R.\n  pose proof (fr_general_prop depth from to p g g' _ Q P R). subst Q P R.\n  apply H1; clear H1; intros; try assumption; try reflexivity.\n  - rewrite H1. assumption.\n  - rewrite lcv_gen_start; [reflexivity | assumption].\nQed.\n\nLemma fl_gen_start: forall from to depth l g g',\n    heapgraph_has_gen g to -> forward_loop from to depth l g g' ->\n    forall x, heapgraph_generation_base g x = heapgraph_generation_base g' x.\nProof.\n  intros. revert g g' H H0 x. induction l; intros; inversion H0. 1: reflexivity.\n  subst. transitivity (heapgraph_generation_base g2 x).\n  - apply (fr_gen_start _ _ _ _ _ _ H H4).\n  - assert (heapgraph_has_gen g2 to) by\n        (rewrite <- (fr_graph_has_gen _ _ _ _ _ _ H H4); assumption).\n    apply IHl; assumption.\nQed.\n\nLemma fr_heapgraph_block_size (depth from to: nat) (p: forward_t) (g1 g2: HeapGraph)\n    (Hg1: heapgraph_has_gen g1 to)\n    (Hg1g2: forward_relation from to depth p g1 g2)\n    (v: Addr)\n    (Hv: heapgraph_has_block g1 v):\n    heapgraph_block_size g1 v = heapgraph_block_size g2 v.\nProof.\n    remember (fun g v (x: nat) => heapgraph_has_block g v) as Q.\n    remember (fun g1 g2 v => heapgraph_block_size g1 v = heapgraph_block_size g2 v) as P.\n    remember (fun (x1 x2: nat) => True) as R.\n    pose proof (fr_general_prop depth from to p g1 g2 _ Q P R)as E. subst Q P R.\n    apply E ; clear E ; try easy.\n    + intros g3 g4 g5 w Hg3g4 Hg4g5.\n      congruence.\n    + intros from' g w to' u Hto' Hu Hw _ Efrom'.\n      now rewrite lcv_heapgraph_block_size_old.\n    + intros depth' from' to' p' g g' Hto' Hgg' w Hw.\n      apply (fr_heapgraph_has_block _ _ _ _ _ _ Hto' Hgg' _ Hw).\n    + intros g w to' u _ Hto' Hu.\n      now apply lcv_heapgraph_has_block_old.\n    + intros g f w u _ Hu.\n      destruct Hu ; now constructor.\nQed.\n\nLemma fr_O_heapgraph_generation_unchanged: forall from to p g1 g2,\n    heapgraph_has_gen g1 to -> forward_relation from to O p g1 g2 ->\n    forall gen, gen <> to -> heapgraph_generation g1 gen = heapgraph_generation g2 gen.\nProof.\n  intros. inversion H0; subst; try reflexivity.\n  - rewrite lcv_heapgraph_generation; auto.\n  - subst new_g. transitivity (heapgraph_generation (lgraph_copy_v g1 (dst g1 e) to) gen).\n    2: reflexivity. rewrite lcv_heapgraph_generation; [reflexivity | assumption..].\nQed.\n\nLemma fr_O_graph_gen_size_unchanged: forall from to p g1 g2,\n    heapgraph_has_gen g1 to -> forward_relation from to O p g1 g2 ->\n    forall gen, heapgraph_has_gen g1 gen -> gen <> to ->\n                heapgraph_generation_size g1 gen = heapgraph_generation_size g2 gen.\nProof.\n  intros. unfold heapgraph_generation_size.\n  erewrite <- (fr_O_heapgraph_generation_unchanged from to _ g1 g2); eauto.\n  replace\n    (heapgraph_block_size_prev g2 gen (generation_block_count (heapgraph_generation g1 gen)))\n    with (heapgraph_block_size_prev g1 gen (generation_block_count (heapgraph_generation g1 gen))).\n  {\n    easy.\n  }\n  apply fold_left_ext.\n  intros.\n  unfold heapgraph_block_size_accum.\n  f_equal.\n  rewrite nat_inc_list_In_iff in H3.\n  now apply (fr_heapgraph_block_size O from to p g1 g2).\nQed.\n\nLemma fr_O_graph_remember_size_unchanged: forall from to p g1 g2,\n    heapgraph_has_gen g1 to -> forward_relation from to O p g1 g2 ->\n    forall gen, heapgraph_has_gen g1 gen -> gen <> to ->\n                heapgraph_remember_size g1 gen = heapgraph_remember_size g2 gen.\nProof.\n  intros.\n  unfold heapgraph_remember_size.\n  erewrite <- (fr_O_heapgraph_generation_unchanged from to _ g1 g2); eauto.\nQed.\n\n\nDefinition forward_p_compatible\n           (p: forward_p_type) (roots: roots_t) (g: HeapGraph) (from: nat): Prop :=\n  match p with\n  | inl root_index => 0 <= root_index < Zlength roots\n  | inr (v, n) => heapgraph_has_block g v /\\ 0 <= n < Zlength (heapgraph_block g v).(block_fields) /\\\n                  (heapgraph_block g v).(block_mark) = false /\\ addr_gen v <> from\n  end.\n\n\nDefinition upd_roots (from to: nat) (forward_p: forward_p_type)\n           (g: HeapGraph) (roots: roots_t) (f_info: fun_info): roots_t :=\n  match forward_p with\n  | inr _ => roots\n  | inl index => match Znth index roots with\n                 | inl (inl z) => roots\n                 | inl (inr p) => roots\n                 | inr v => if Nat.eq_dec (addr_gen v) from\n                            then if (heapgraph_block g v).(block_mark)\n                                 then upd_bunch index f_info roots\n                                                (inr (heapgraph_block g v).(block_copied_vertex))\n                                 else upd_bunch index f_info roots\n                                                (inr (new_copied_v g to))\n                            else roots\n                 end\n  end.\n\nLemma upd_roots_Zlength: forall from to p g roots f_info,\n    Zlength roots = Zlength (live_roots_indices f_info) ->\n    Zlength (upd_roots from to p g roots f_info) = Zlength roots.\nProof.\n  intros. unfold upd_roots. destruct p. 2: reflexivity.\n  destruct (Znth z roots). 1: destruct s; reflexivity. if_tac. 2: reflexivity.\n  destruct (block_mark (heapgraph_block g a)); rewrite upd_bunch_Zlength; auto.\nQed.\n\n\nInductive forward_roots_loop (from to: nat) (f_info: fun_info):\n  list nat -> roots_t -> HeapGraph -> roots_t -> HeapGraph -> Prop :=\n| frl_nil: forall g roots, forward_roots_loop from to f_info nil roots g roots g\n| frl_cons: forall g1 g2 g3 i il roots1 roots3,\n    forward_relation from to O (root2forward (Znth (Z.of_nat i) roots1)) g1 g2 ->\n    forward_roots_loop from to f_info il\n                       (upd_roots from to (inl (Z.of_nat i)) g1 roots1 f_info)\n                       g2 roots3 g3 ->\n    forward_roots_loop from to f_info (i :: il) roots1 g1 roots3 g3.\n\nDefinition forward_roots_relation from to f_info roots1 g1 roots2 g2 :=\n  forward_roots_loop from to f_info (nat_inc_list (length roots1)) roots1 g1 roots2 g2.\n\nLemma fl__heapgraph_remember_upto from to depth l g1 g2 gen\n  (H: forward_loop from to depth l g1 g2)\n  (Hto: heapgraph_has_gen g1 to)\n  (Edepth: depth = O):\n  heapgraph_remember_upto g2 gen = heapgraph_remember_upto g1 gen.\nProof.\n  induction H ; try easy.\n  assert\n    (heapgraph_has_gen g2 to)\n    as Hto_g2\n    by now rewrite <- (fr_graph_has_gen _ _ _ _ _ _ Hto H to).\n  rewrite IHforward_loop by easy.\n  inversion H ; subst ; try easy.\n  - now apply lcv__heapgraph_remember_upto.\n  - rewrite <- (lcv__heapgraph_remember_upto _ (dst g1 e) to gen Hto).\n    subst new_g.\n    apply heapgraph_remember_upto__labeledgraph_gen_dst.\nQed.\n\nLemma frr__heapgraph_remember_upto from to f_info roots1 g1 roots2 g2 gen\n  (H: forward_roots_relation from to f_info roots1 g1 roots2 g2)\n  (Hto: heapgraph_has_gen g1 to):\n  heapgraph_remember_upto g2 gen = heapgraph_remember_upto g1 gen.\nProof.\n  red in H.\n  induction H ; try easy.\n  rewrite\n    IHforward_roots_loop\n    by now rewrite <- (fr_graph_has_gen _ _ _ _ _ _ Hto H to).\n  clear IHforward_roots_loop H0.\n  remember O as depth eqn:Edepth.\n  inversion H ; subst ; try easy.\n  - now apply lcv__heapgraph_remember_upto.\n  - subst new_g.\n    rewrite heapgraph_remember_upto__labeledgraph_gen_dst.\n    now apply lcv__heapgraph_remember_upto.\nQed.\n\nDefinition forward_condition g t_info from to: Prop :=\n  enough_space_to_copy g t_info from to /\\\n  heapgraph_has_gen g from /\\ heapgraph_has_gen g to /\\\n  copy_compatible g /\\ no_dangling_dst g.\n\nLemma lgd_forward_condition: forall g t_info v to v' e,\n    addr_gen v <> to ->\n    heapgraph_has_block g v ->\n    heapgraph_has_block g v' ->\n    forward_condition g t_info (addr_gen v) to ->\n    forward_condition (labeledgraph_gen_dst g e v') t_info (addr_gen v) to.\nProof.\n  intros. destruct H2 as [? [? [? [? ?]]]]. split; [|split; [|split; [|split]]].\n  - apply lgd_enough_space_to_copy; assumption.\n  - apply lgd_graph_has_gen; assumption.\n  - apply lgd_graph_has_gen; assumption.\n  - apply lgd_copy_compatible; assumption.\n  - apply lgd_no_dangling_dst; assumption.\nQed.\n\n\nLemma lcv_forward_condition: forall\n    g t_info v to index uv\n    (Hi : 0 <= Z.of_nat to < Zlength (heap_spaces (ti_heap t_info)))\n    (Hh : has_space (Znth (Z.of_nat to) (heap_spaces (ti_heap t_info))) (heapgraph_block_size g v))\n    (Hm : 0 <= index < MAX_ARGS),\n    addr_gen v <> to -> heapgraph_has_block g v -> block_mark (heapgraph_block g v) = false ->\n    forward_condition g t_info (addr_gen v) to ->\n    forward_condition\n      (lgraph_copy_v g v to)\n      (update_thread_info_arg\n         (cut_thread_info t_info (Z.of_nat to) (heapgraph_block_size g v) Hi Hh) index uv Hm)\n      (addr_gen v) to.\nProof.\n  intros. destruct H2 as [? [? [? [? ?]]]]. split; [|split; [|split; [|split]]].\n  - apply forward_estc; assumption.\n  - apply lcv_graph_has_gen; assumption.\n  - apply lcv_graph_has_gen; assumption.\n  - apply lcv_copy_compatible; assumption.\n  - apply lcv_no_dangling_dst; assumption.\nQed.\n\nLemma lcv_forward_condition_unchanged: forall\n    g t_info v to\n    (Hi : 0 <= Z.of_nat to < Zlength (heap_spaces (ti_heap t_info)))\n    (Hh : has_space (Znth (Z.of_nat to) (heap_spaces (ti_heap t_info))) (heapgraph_block_size g v)),\n    addr_gen v <> to -> heapgraph_has_block g v -> block_mark (heapgraph_block g v) = false ->\n    forward_condition g t_info (addr_gen v) to ->\n    forward_condition (lgraph_copy_v g v to)\n         (cut_thread_info t_info (Z.of_nat to) (heapgraph_block_size g v) Hi Hh)\n      (addr_gen v) to.\nProof.\n  intros. destruct H2 as [? [? [? [? ?]]]]. split; [|split; [|split; [|split]]].\n  - apply forward_estc_unchanged; assumption.\n  - apply lcv_graph_has_gen; assumption.\n  - apply lcv_graph_has_gen; assumption.\n  - apply lcv_copy_compatible; assumption.\n  - apply lcv_no_dangling_dst; assumption.\nQed.\n\n\nLemma fr_closure_has_v: forall depth from to p g g',\n    heapgraph_has_gen g to -> forward_relation from to depth p g g' ->\n    forall v, closure_has_v g v -> closure_has_v g' v.\nProof.\n  intros. remember (fun (g: HeapGraph) (v: Addr) (x: nat) => True) as Q.\n  remember (fun g1 g2 v => closure_has_v g1 v -> closure_has_v g2 v) as P.\n  remember (fun (x1 x2: nat) => True) as R.\n  pose proof (fr_general_prop depth from to p g g' _ Q P R). subst Q P R.\n  apply H2; clear H2; intros; try assumption; try reflexivity.\n  - apply H3, H2. assumption.\n  - apply lcv_closure_has_v; assumption.\nQed.\n\n\nLemma fl_heapgraph_has_block: forall from to depth l g g',\n    heapgraph_has_gen g to -> forward_loop from to depth l g g' ->\n    forall v, heapgraph_has_block g v -> heapgraph_has_block g' v.\nProof.\n  intros. revert g g' H H0 v H1. induction l; intros; inversion H0; subst.\n  1: assumption. cut (heapgraph_has_block g2 v).\n  - intros. assert (heapgraph_has_gen g2 to) by\n        (apply (fr_graph_has_gen _ _ _ _ _ _ H H5); assumption).\n    apply (IHl _ _ H3 H8 _ H2).\n  - apply (fr_heapgraph_has_block _ _ _ _ _ _ H H5 _ H1).\nQed.\n\nLemma fr_heapgraph_block_ptr: forall depth from to p g g',\n    heapgraph_has_gen g to -> forward_relation from to depth p g g' ->\n    forall v, closure_has_v g v -> heapgraph_block_ptr g v = heapgraph_block_ptr g' v.\nProof.\n  intros. remember (fun g v (x: nat) => closure_has_v g v) as Q.\n  remember (fun g1 g2 v => heapgraph_block_ptr g1 v = heapgraph_block_ptr g2 v) as P.\n  remember (fun (x1 x2: nat) => True) as R.\n  pose proof (fr_general_prop depth from to p g g' _ Q P R). subst Q P R.\n  apply H2; clear H2; intros; try assumption; try reflexivity.\n  - rewrite H2. assumption.\n  - rewrite lcv_heapgraph_block_ptr; [reflexivity | assumption..].\n  - apply (fr_closure_has_v _ _ _ _ _ _ H2 H3 _ H4).\n  - apply lcv_closure_has_v; assumption.\nQed.\n\nLemma fl_heapgraph_block_ptr: forall from to depth l g g',\n    heapgraph_has_gen g to -> forward_loop from to depth l g g' ->\n    forall v, closure_has_v g v -> heapgraph_block_ptr g v = heapgraph_block_ptr g' v.\nProof.\n  intros. revert g g' H H0 v H1. induction l; intros; inversion H0; subst.\n  1: reflexivity. transitivity (heapgraph_block_ptr g2 v).\n  - apply (fr_heapgraph_block_ptr _ _ _ _ _ _ H H5 _ H1).\n  - apply IHl; [|assumption|].\n    + erewrite <- fr_graph_has_gen; eauto.\n    + eapply fr_closure_has_v; eauto.\nQed.\n\nLemma fr_block_fields (depth from to: nat) (p: forward_t) (g g': HeapGraph)\n    (Hto: heapgraph_has_gen g to)\n    (Hgg': forward_relation from to depth p g g')\n    (v: Addr)\n    (Hv: heapgraph_has_block g v):\n    block_fields (heapgraph_block g v) = block_fields (heapgraph_block g' v).\nProof.\n    remember (fun (g: HeapGraph) (v: Addr) (x: nat) => heapgraph_has_block g v) as Q.\n    remember (fun g1 g2 v => block_fields (heapgraph_block g1 v) = block_fields (heapgraph_block g2 v)) as P.\n    remember (fun (x1 x2: nat) => True) as R.\n    pose proof (fr_general_prop depth from to p g g' _ Q P R) as HP.\n    subst Q P R.\n    apply HP ; clear HP ; try easy.\n    + intros g1 g2 g3 w H12 H23.\n      congruence.\n    + intros from' g'' w to' u Hto' Hu Hw _ Efrom'.\n      now rewrite <- lcv_block_fields.\n    + intros depth' from' to' p' g1 g2 Hto' Hg1g2 w Hw.\n      apply (fr_heapgraph_has_block _ _ _ _ _ _ Hto' Hg1g2 _ Hw).\n    + intros g'' w to' u _ Hto' Hu.\n      now apply lcv_heapgraph_has_block_old.\n    + intros g'' f w u _ Hu.\n      destruct Hu ; now constructor.\nQed.\n\nLemma fl_block_fields: forall from to depth l g g',\n    heapgraph_has_gen g to -> forward_loop from to depth l g g' ->\n    forall v, heapgraph_has_block g v -> block_fields (heapgraph_block g v) = block_fields (heapgraph_block g' v).\nProof.\n  intros. revert g g' H H0 v H1. induction l; intros; inversion H0; subst.\n  1: reflexivity. transitivity (block_fields (heapgraph_block g2 v)).\n  - apply (fr_block_fields _ _ _ _ _ _ H H5 _ H1).\n  - apply IHl; [|assumption|].\n    + erewrite <- fr_graph_has_gen; eauto.\n    + eapply fr_heapgraph_has_block; eauto.\nQed.\n\n\nLemma fr_block_mark (depth from to: nat) (p: forward_t) (g g': HeapGraph)\n    (Hto: heapgraph_has_gen g to)\n    (Hgg': forward_relation from to depth p g g')\n    (v: Addr)\n    (Hv: heapgraph_has_block g v)\n    (Hv__from: addr_gen v <> from):\n    block_mark (heapgraph_block g v) = block_mark (heapgraph_block g' v).\nProof.\n    remember (fun g v x => heapgraph_has_block g v /\\ addr_gen v <> x) as Q.\n    remember (fun g1 g2 v => block_mark (heapgraph_block g1 v) = block_mark (heapgraph_block g2 v)) as P.\n    remember (fun (x1 x2: nat) => True) as R.\n    pose proof (fr_general_prop depth from to p g g' _ Q P R) as HP. subst Q P R.\n    apply HP ; clear HP ; try easy.\n    + intros g1 g2 g3 w Hg1g2 Hg2g3.\n      congruence.\n    + intros from' g'' w to' u Hto' [Hu Hx__from'] Hw _ Efrom'.\n      rewrite <- lcv_block_mark ; try easy.\n      congruence.\n    + intros depth' from' to' p' g1 g2 Hto' Hg1g2 w [Hw Hw__from'].\n      split ; try easy.\n      apply (fr_heapgraph_has_block _ _ _ _ _ _ Hto' Hg1g2 _ Hw).\n    + intros g'' w to' u from' Hto' [Hu Hu__from'].\n      split ; try easy.\n      now apply lcv_heapgraph_has_block_old.\n    + intros g'' f w u from' [Hu Hu__from'].\n      split ; try easy.\n      destruct Hu ; now constructor.\nQed.\n\nLemma fl_block_mark: forall depth from to l g g',\n    heapgraph_has_gen g to -> forward_loop from to depth l g g' ->\n    forall v, heapgraph_has_block g v -> addr_gen v <> from ->\n              block_mark (heapgraph_block g v) = block_mark (heapgraph_block g' v).\nProof.\n  intros. revert g g' H H0 v H1 H2. induction l; intros; inversion H0; subst.\n  1: reflexivity. transitivity (block_mark (heapgraph_block g2 v)).\n  - apply (fr_block_mark _ _ _ _ _ _ H H6 _ H1 H2).\n  - apply IHl; [|assumption| |assumption].\n    + erewrite <- fr_graph_has_gen; eauto.\n    + eapply fr_heapgraph_has_block; eauto.\nQed.\n\n\nLemma forward_loop_add_tail: forall from to depth l x g1 g2 g3 roots,\n    forward_loop from to depth l g1 g2 ->\n    forward_relation from to depth (forward_p2forward_t (inr x) roots g2) g2 g3 ->\n    forward_loop from to depth (l +:: (inr x)) g1 g3.\nProof.\n  intros. revert x g1 g2 g3 H H0. induction l; intros.\n  - simpl. inversion H. subst. apply fl_cons with g3. 2: constructor. apply H0.\n  - inversion H. subst. clear H. simpl app. apply fl_cons with g4. 1: assumption.\n    apply IHl with g2; assumption.\nQed.\n\nLemma forward_p2t_inr_roots: forall v n roots g,\n    forward_p2forward_t (inr (v, n)) roots g = forward_p2forward_t (inr (v, n)) nil g.\nProof. intros. simpl. reflexivity. Qed.\n\nLemma forward_loop_add_tail_vpp: forall from to depth x g g1 g2 g3 roots i,\n    (0 <= i < Zlength (block_fields (heapgraph_block g x)))%Z ->\n    forward_loop from to depth (VST.floyd.sublist.sublist 0 i (heapgraph_field_pairs g x))%Z g1 g2 ->\n    forward_relation from to depth (forward_p2forward_t (inr (x, i)) roots g2) g2 g3 ->\n    forward_loop from to depth (VST.floyd.sublist.sublist 0 (i + 1) (heapgraph_field_pairs g x))%Z g1 g3.\nProof.\n  intros. rewrite <- heapgraph_field_pairs__Zlength in H. rewrite sublist_last_1; [|lia..].\n  rewrite heapgraph_field_pairs__Zlength in H. rewrite heapgraph_field_pairs__Znth by assumption.\n  apply forward_loop_add_tail with (g2 := g2) (roots := roots); assumption.\nQed.\n\n\nLemma fr_heapgraph_generation_is_unmarked: forall from to depth p g g',\n    heapgraph_has_gen g to -> forward_relation from to depth p g g' ->\n    forall gen, from  <> gen -> heapgraph_generation_is_unmarked g gen -> heapgraph_generation_is_unmarked g' gen.\nProof.\n  intros. remember (fun (g: HeapGraph) (gen: nat) (x: nat) => x <> gen) as Q.\n  remember (fun (g1 g2: HeapGraph) gen =>\n              heapgraph_generation_is_unmarked g1 gen -> heapgraph_generation_is_unmarked g2 gen) as P.\n  remember (fun (x1 x2: nat) => True) as R.\n  pose proof (fr_general_prop depth from to p g g' _ Q P R). subst Q P R.\n  apply H3; clear H3; intros; try assumption; try reflexivity.\n  - apply H4, H3. assumption.\n  - rewrite <- H7 in H4. apply lcv_heapgraph_generation_is_unmarked; assumption.\nQed.\n\n\nLemma frl_roots_Zlength: forall from to f_info l roots g roots' g',\n    Zlength roots = Zlength (live_roots_indices f_info) ->\n    forward_roots_loop from to f_info l roots g roots' g' ->\n    Zlength roots' = Zlength roots.\nProof.\n  intros. induction H0. 1: reflexivity. rewrite IHforward_roots_loop.\n  - apply upd_roots_Zlength; assumption.\n  - rewrite upd_roots_Zlength; assumption.\nQed.\n\n\nOpaque upd_roots.\n\nLemma frl_add_tail: forall from to f_info l i g1 g2 g3 roots1 roots2,\n    forward_roots_loop from to f_info l roots1 g1 roots2 g2 ->\n    forward_relation from to O (root2forward (Znth (Z.of_nat i) roots2)) g2 g3 ->\n    forward_roots_loop\n      from to f_info (l +:: i) roots1 g1\n      (upd_roots from to (inl (Z.of_nat i)) g2 roots2 f_info) g3.\nProof.\n  intros ? ? ? ?. induction l; intros.\n  - simpl. inversion H. subst. apply frl_cons with g3. 2: constructor. apply H0.\n  - inversion H. subst. clear H. simpl app. apply frl_cons with g4. 1: assumption.\n    apply IHl; assumption.\nQed.\n\nTransparent upd_roots.\n\nLemma frr_heapgraph_block_ptr: forall from to f_info roots1 g1 roots2 g2,\n    heapgraph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall v, closure_has_v g1 v -> heapgraph_block_ptr g1 v = heapgraph_block_ptr g2 v.\nProof.\n  intros. induction H0. 1: reflexivity. rewrite <- IHforward_roots_loop.\n  - eapply fr_heapgraph_block_ptr; eauto.\n  - rewrite <- fr_graph_has_gen; eauto.\n  - eapply fr_closure_has_v; eauto.\nQed.\n\nLemma frr_closure_has_v: forall from to f_info roots1 g1 roots2 g2,\n    heapgraph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall v, closure_has_v g1 v -> closure_has_v g2 v.\nProof.\n  intros. induction H0. 1: assumption. apply IHforward_roots_loop.\n  - rewrite <- fr_graph_has_gen; eauto.\n  - eapply fr_closure_has_v; eauto.\nQed.\n\nLemma frr_heapgraph_generation_is_unmarked: forall from to f_info roots1 g1 roots2 g2,\n    heapgraph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall gen, gen <> from -> heapgraph_generation_is_unmarked g1 gen -> heapgraph_generation_is_unmarked g2 gen.\nProof.\n  intros. induction H0. 1: assumption. apply IHforward_roots_loop.\n  - rewrite <- fr_graph_has_gen; eauto.\n  - eapply fr_heapgraph_generation_is_unmarked; eauto.\nQed.\n\nLemma upd_roots_rf_compatible: forall from to f_info roots p g,\n    roots_fi_compatible roots f_info ->\n    roots_fi_compatible (upd_roots from to p g roots f_info) f_info.\nProof.\n  intros. unfold upd_roots. destruct p; [|assumption]. destruct (Znth z roots).\n  1: destruct s; assumption. if_tac. 2: assumption.\n  destruct (block_mark (heapgraph_block g a)); apply upd_bunch_rf_compatible; assumption.\nQed.\n\n\nLemma upd_roots_not_pointing: forall from to i g roots f_info roots',\n    copy_compatible g -> roots_graph_compatible roots g -> from <> to ->\n    0 <= i < Zlength roots -> roots_fi_compatible roots f_info ->\n    roots' = upd_roots from to (inl i) g roots f_info ->\n    np_roots_rel from f_info roots roots' [i].\nProof.\n  intros. unfold np_roots_rel. intros. simpl.\n  assert (Zlength roots' = Zlength roots) by\n      (rewrite H4; apply upd_roots_Zlength, (proj1 H3)).\n  assert (0 <= j < Zlength roots). {\n    rewrite <- H6. destruct (Z_lt_le_dec j (Zlength roots')).\n    2: rewrite Znth_outofbounds in H5 by lia; inversion H5. split; auto.\n    destruct (Z_lt_le_dec j 0); auto. rewrite Znth_outofbounds in H5 by lia.\n    inversion H5. } simpl in H4. destruct H3. destruct (Znth i roots) eqn:? .\n  - assert (roots' = roots) by (destruct s; assumption). clear H4. subst roots'.\n    split; intros; auto. destruct H4; auto.\n    destruct H3. apply H8 in H4; try assumption. rewrite Heqr, H5 in H4. inversion H4.\n  - if_tac in H4.\n    + destruct (block_mark (heapgraph_block g a)) eqn: ?; subst; split; intros.\n      * destruct H4; auto. symmetry in H4. rewrite upd_bunch_same in H5 by assumption.\n        inversion H5. red in H0. rewrite Forall_forall in H0.\n        assert (heapgraph_has_block g a). {\n          apply H0. rewrite <- filter_sum_right_In_iff, <- Heqr.\n          apply Znth_In; assumption. } destruct (H _ H9 Heqb) as [_ ?]. auto.\n      * assert (Znth j (live_roots_indices f_info) <>\n                Znth i (live_roots_indices f_info)) by intuition. clear H4.\n        rewrite upd_bunch_diff in H5; assumption.\n      * destruct H4; auto. symmetry in H4. rewrite upd_bunch_same in H5 by assumption.\n        inversion H5. unfold new_copied_v. simpl. auto.\n      * assert (Znth j (live_roots_indices f_info) <>\n                Znth i (live_roots_indices f_info)) by intuition. clear H4.\n        rewrite upd_bunch_diff in H5; assumption.\n    + split; intros; subst roots'; auto. destruct H10; auto.\n      apply H8 in H4; try assumption. rewrite Heqr, H5 in H4. inversion H4.\n      subst a. assumption.\nQed.\n\n\nLemma fr_copy_compatible (depth from to: nat) (p: forward_t) (g g': HeapGraph)\n    (Hfrom__to: from <> to)\n    (Hto: heapgraph_has_gen g to)\n    (Hgg': forward_relation from to depth p g g')\n    (Hg: copy_compatible g):\n    copy_compatible g'.\nProof.\n    remember (fun (g: HeapGraph) (v: Addr) (x: nat) => True) as Q.\n    remember (fun g1 g2 (v: Addr) => copy_compatible g1 -> copy_compatible g2) as P.\n    remember (fun (x y: nat) => x <> y) as R.\n    pose proof (fr_general_prop depth from to p g g' _ Q P R) as HP. subst Q P R.\n    apply HP ; clear HP ; try easy.\n    + intros g1 g2 g3 _ Hg1g2 Hg2g3 Hg1.\n      now apply Hg2g3, Hg1g2.\n    + intros g'' f w _ Hg'' u Hu Eu.\n      apply lgd_heapgraph_has_block in Hu.\n      destruct (Hg'' u Hu Eu) as [H1u H2u].\n      split ; try easy.\n      destruct H1u ; now constructor.\n    + intros from' g'' w to' _ Hto' _ Hw Hto'__from' Efrom' Hg''.\n      subst from'.\n      now apply lcv_copy_compatible.\nQed.\n\nLemma fr_right_roots_graph_compatible (depth from to: nat) (e: Addr * Z) (g g': HeapGraph) (roots: roots_t)\n    (Hto: heapgraph_has_gen g to)\n    (Hfrom: forward_p_compatible (inr e) roots g from)\n    (Hgg': forward_relation from to depth (forward_p2forward_t (inr e) [] g) g g')\n    (Hroots: roots_graph_compatible roots g):\n    roots_graph_compatible roots g'.\nProof.\n    simpl in Hfrom, Hgg'.\n    destruct e as [e_addr e_z].\n    destruct Hfrom as [_ [_ [Hfrom _]]].\n    rewrite Hfrom in Hgg'. simpl in Hgg'.\n    remember (fun (g: HeapGraph) (v: nat) (x: nat) => True) as Q.\n    remember (fun g1 g2 (x: nat) => roots_graph_compatible roots g1->\n                                    roots_graph_compatible roots g2) as P.\n    remember (fun (x1 x2: nat) => True) as R.\n    pose proof (fr_general_prop depth from to (field2forward (Znth e_z (heapgraph_block_cells g e_addr))) g g' _ Q P R) as HP.\n    subst Q P R.\n    apply HP ; clear HP ; try easy.\n    - intros g1 g2 g3 _ Hg1g2 Hg2g3 Hg1.\n      now apply Hg2g3, Hg1g2.\n    - intros g'' e v _ Hg''.\n      unfold roots_graph_compatible in *.\n      now apply lgd_forall_heapgraph_has_block.\n    - intros from' g'' u to' _ Hto' _ Hu _ Efrom' Hg''.\n      now apply lcv_rgc_unchanged.\nQed.\n\nLemma fl_edge_roots_graph_compatible: forall depth from to l g g' v roots,\n    addr_gen v <> from ->\n    heapgraph_has_gen g to -> heapgraph_has_block g v -> block_mark (heapgraph_block g v) = false ->\n    forward_loop from to depth (map (fun x : nat => inr (v, Z.of_nat x)) l) g g' ->\n    (forall i, In i l -> i < length (block_fields (heapgraph_block g v)))%nat ->\n    roots_graph_compatible roots g -> roots_graph_compatible roots g'.\nProof.\n  do 4 intro. induction l; intros; simpl in H3; inversion H3; subst. 1: assumption.\n  cut (roots_graph_compatible roots g2).\n  - intros. apply (IHl g2 _ v); try assumption.\n    + rewrite <- fr_graph_has_gen; eauto.\n    + eapply fr_heapgraph_has_block; eauto.\n    + rewrite <- H2. symmetry. eapply fr_block_mark; eauto.\n    + assert (block_fields (heapgraph_block g v) = block_fields (heapgraph_block g2 v)) by\n          (eapply fr_block_fields; eauto). rewrite <- H7.\n      intros; apply H4; right; assumption.\n  - specialize (H4 _ (in_eq a l)). eapply fr_right_roots_graph_compatible; eauto.\n    simpl. intuition. rewrite Zlength_correct. apply inj_lt; assumption.\nQed.\n\nLemma fr_roots_outlier_compatible: forall from to p g roots f_info outlier,\n    roots_outlier_compatible roots outlier ->\n    roots_outlier_compatible (upd_roots from to p g roots f_info) outlier.\nProof.\n  intros. destruct p; simpl in *. 2: assumption. destruct (Znth z roots) eqn: ?.\n  + destruct s; assumption.\n  + if_tac. 2: assumption.\n    destruct (block_mark (heapgraph_block g a)); apply upd_roots_outlier_compatible; assumption.\nQed.\n\nLemma fr_roots_graph_compatible (depth from to: nat) (p : forward_p_type) (g g' : HeapGraph) (roots : roots_t) (f_info : fun_info)\n    (Hto: heapgraph_has_gen g to)\n    (Hp: forward_p_compatible p roots g from)\n    (Hg: copy_compatible g)\n    (Hfwd: forward_relation from to depth (forward_p2forward_t p roots g) g g')\n    (Hfrom_to: from <> to)\n    (Hroots: roots_graph_compatible roots g):\n    roots_graph_compatible (upd_roots from to p g roots f_info) g'.\nProof.\n  destruct p.\n  - simpl in *. destruct (Znth z roots) eqn: ?; simpl in *.\n    + destruct s; inversion Hfwd; subst; assumption.\n    + assert (heapgraph_has_block g a). {\n        red in Hroots. rewrite Forall_forall in Hroots. apply Hroots.\n        rewrite <- filter_sum_right_In_iff. rewrite <- Heqr. apply Znth_In.\n        assumption. }\n      inversion Hfwd ; destruct (Nat.eq_dec (addr_gen v) from) eqn:HE_v_from ; subst ; rewrite HE_v_from ; try easy.\n      * rename H3 into Eblock_mark ; rewrite Eblock_mark.\n        apply upd_bunch_graph_compatible ; try assumption.\n        now apply Hg.\n      * rename H3 into Eblock_mark ; rewrite Eblock_mark.\n        now apply lcv_roots_graph_compatible.\n      * rename H2 into Eblock_mark ; rewrite Eblock_mark.\n        assert (heapgraph_has_block new_g (new_copied_v g to)) by\n          (subst new_g; apply lcv_heapgraph_has_block_new; assumption).\n        remember (nat_inc_list (length (block_fields (heapgraph_block new_g (new_copied_v g to))))) as new_fields.\n        assert (heapgraph_has_block new_g (new_copied_v g to)) by (subst new_g; apply lcv_heapgraph_has_block_new; assumption).\n        remember (upd_bunch z f_info roots (inr (new_copied_v g to))) as roots'.\n        assert (roots_graph_compatible roots' new_g) by (subst; subst new_g; apply lcv_roots_graph_compatible; assumption).\n        assert (block_mark (heapgraph_block new_g (new_copied_v g to)) = false). {\n          subst new_g. unfold lgraph_copy_v. rewrite <- lmc_block_mark.\n          - now rewrite lacv_vlabel_new.\n          - unfold new_copied_v. destruct a. destruct Heqroots'. simpl in *.\n            destruct H1. intro HS. inversion HS. lia. }\n        eapply (fl_edge_roots_graph_compatible depth0 (addr_gen a) to new_fields new_g _ (new_copied_v g to)) ; eauto.\n        -- subst new_g. now rewrite <- lcv_graph_has_gen.\n        -- now subst new_fields.\n        -- intros idx Hidx. subst new_fields. now rewrite nat_inc_list_In_iff in Hidx.\n  - simpl. eapply fr_right_roots_graph_compatible; eauto.\nQed.\n\nLemma fr_roots_compatible: forall depth from to p g g' roots f_info outlier,\n    heapgraph_has_gen g to -> forward_p_compatible p roots g from -> copy_compatible g ->\n    forward_relation from to depth (forward_p2forward_t p roots g) g g' ->\n    roots_compatible g outlier roots -> from <> to ->\n    roots_compatible g' outlier (upd_roots from to p g roots f_info).\nProof.\n  intros. destruct H3. split.\n  - apply fr_roots_outlier_compatible; assumption.\n  - eapply fr_roots_graph_compatible; eauto.\nQed.\n\nLemma frl_not_pointing: forall from to f_info l roots1 g1 roots2 g2,\n    copy_compatible g1 -> roots_graph_compatible roots1 g1 -> from <> to ->\n    (forall i, In i l -> i < length roots1)%nat -> roots_fi_compatible roots1 f_info ->\n    forward_roots_loop from to f_info l roots1 g1 roots2 g2 -> heapgraph_has_gen g1 to ->\n    np_roots_rel from f_info roots1 roots2 (map Z.of_nat l).\nProof.\n  do 4 intro. induction l; intros; inversion H4; subst.\n  1: red; simpl; intros; intuition.\n  remember (upd_roots from to (inl (Z.of_nat a)) g1 roots1 f_info) as roots3.\n  simpl. apply np_roots_rel_cons with roots3.\n  - apply (upd_roots_not_pointing from to _ g1); try assumption.\n    split. 1: lia. rewrite Zlength_correct. apply inj_lt. apply H2. left; auto.\n  - assert (Zlength roots3 = Zlength roots1) by\n        (subst roots3; apply upd_roots_Zlength; apply (proj1 H3)).\n    apply (IHl _ g3 _ g2); auto.\n    + apply fr_copy_compatible in H8; assumption.\n    + subst roots3. eapply fr_roots_graph_compatible; eauto. simpl. split. 1: lia.\n      specialize (H2 _ (in_eq a l)). rewrite Zlength_correct. apply inj_lt; assumption.\n    + intros. subst roots3. rewrite <- ZtoNat_Zlength, H6, ZtoNat_Zlength.\n      apply H2; right; assumption.\n    + subst roots3; apply upd_roots_rf_compatible; assumption.\n    + rewrite <- (fr_graph_has_gen _ _ _ _ _ _ H5 H8); assumption.\nQed.\n\n\nLemma frr_not_pointing: forall from to f_info roots1 g1 roots2 g2,\n    copy_compatible g1 -> roots_graph_compatible roots1 g1 -> from <> to ->\n    heapgraph_has_gen g1 to -> roots_fi_compatible roots1 f_info ->\n    forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    roots_have_no_gen roots2 from.\nProof.\n  intros. unfold forward_roots_relation in H0. eapply frl_not_pointing in H0; eauto.\n  red; intros. 2: intros; rewrite nat_inc_list_In_iff in H5; assumption. red in H0.\n  apply In_Znth in H5. destruct H5 as [i [? ?]]. specialize (H0 _ _ H6). destruct H0.\n  apply H0. destruct H3 as [? _].\n  replace (length roots1) with (length (live_roots_indices f_info)) by\n      (rewrite <- !ZtoNat_Zlength, H3; reflexivity).\n  remember (live_roots_indices f_info). rewrite map_map.\n  assert (map (fun x : nat => Znth (Z.of_nat x) l) (nat_inc_list (length l)) = l). {\n    clear. rewrite Znth_list_eq. split.\n    - rewrite Zlength_map, !Zlength_correct, nat_inc_list_length. reflexivity.\n    - intros. rewrite Zlength_map in H. rewrite Znth_map by assumption. f_equal.\n      rewrite <- nth_Znth by assumption. rewrite nat_inc_list_nth.\n      1: apply Z2Nat.id; lia. rewrite Zlength_correct, nat_inc_list_length in H.\n      rep_lia. } rewrite H8. clear H8. apply Znth_In. apply frl_roots_Zlength in H4.\n  2: subst; assumption. rewrite <- H3, <- H4. assumption.\nQed.\n\n\nLemma frr_graph_has_gen: forall from to f_info roots1 g1 roots2 g2,\n    heapgraph_has_gen g1 to ->\n    forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall gen, heapgraph_has_gen g1 gen <-> heapgraph_has_gen g2 gen.\nProof.\n  intros. induction H0. 1: reflexivity. rewrite <- IHforward_roots_loop.\n  - eapply fr_graph_has_gen; eauto.\n  - rewrite <- fr_graph_has_gen; eauto.\nQed.\n\n\nLemma fr_O_dst_unchanged_root (from to: nat) (r: root_t) (g g': HeapGraph)\n    (Hgg': forward_relation from to O (root2forward r) g g')\n    (e: Field)\n    (He: heapgraph_has_block g (field_addr e)):\n    dst g e = dst g' e.\nProof.\n    destruct r; [destruct s|]; simpl in Hgg'; inversion Hgg'; subst; try reflexivity.\n    simpl. rewrite pcv_dst_old. 1: reflexivity. destruct e as [[gen vidx] eidx].\n    unfold new_copied_v. simpl in *. intro.\n    inversion H. subst.\n    pose proof (heapgraph_has_block__has_index He) as F.\n    red in F. simpl in F.\n    lia.\nQed.\n\nLemma frr_dst_unchanged: forall from to f_info roots1 g1 roots2 g2,\n    heapgraph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall e, heapgraph_has_block g1 (field_addr e) -> dst g1 e = dst g2 e.\nProof.\n  intros. induction H0. 1: reflexivity. rewrite <- IHforward_roots_loop.\n  - eapply fr_O_dst_unchanged_root; eauto.\n  - rewrite <- fr_graph_has_gen; eauto.\n  - eapply fr_heapgraph_has_block; eauto.\nQed.\n\nLemma fr_O_heapgraph_has_block_inv (from to: nat) (p: forward_t) (g g': HeapGraph)\n    (Hto: heapgraph_has_gen g to)\n    (Hgg': forward_relation from to O p g g')\n    (v: Addr)\n    (Hv: heapgraph_has_block g' v):\n    heapgraph_has_block g v \\/ v = new_copied_v g to.\nProof.\n    inversion Hgg' ; subst ; try (now left).\n    + now apply lcv_heapgraph_has_block_inv in Hv.\n    + left.\n      subst new_g.\n      now rewrite <- lgd_heapgraph_has_block in Hv.\n    + subst new_g.\n      rewrite <- lgd_heapgraph_has_block in Hv.\n      now apply lcv_heapgraph_has_block_inv in Hv.\nQed.\n\n\nLemma fr_O_gen_v_num_to: forall from to p g g',\n    heapgraph_has_gen g to -> forward_relation from to O p g g' ->\n    (heapgraph_generation_block_count g to <= heapgraph_generation_block_count g' to)%nat.\nProof.\n  intros. inversion H0; subst; try lia; [|subst new_g..].\n  - apply lcv_gen_v_num_to; auto.\n  - rewrite heapgraph_generation_block_count__labeledgraph_gen_dst. lia.\n  - rewrite heapgraph_generation_block_count__labeledgraph_gen_dst. apply lcv_gen_v_num_to. assumption.\nQed.\n\nLemma frr_gen_v_num_to: forall from to f_info roots1 g1 roots2 g2,\n    heapgraph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    (heapgraph_generation_block_count g1 to <= heapgraph_generation_block_count g2 to)%nat.\nProof.\n  intros. induction H0. 1: lia. transitivity (heapgraph_generation_block_count g2 to).\n  - eapply fr_O_gen_v_num_to; eauto.\n  - apply IHforward_roots_loop; rewrite <- fr_graph_has_gen; eauto.\nQed.\n\nLemma frr_heapgraph_has_block_inv (from to: nat) (f_info: fun_info) (roots1: list root_t) (g1: HeapGraph) (roots2: roots_t) (g2: HeapGraph)\n    (Hto: heapgraph_has_gen g1 to)\n    (Hg1g2: forward_roots_relation from to f_info roots1 g1 roots2 g2)\n    (v: Addr)\n    (Hv: heapgraph_has_block g2 v):\n    heapgraph_has_block g1 v \\/ (\n      addr_gen v = to /\\\n      heapgraph_generation_block_count g1 to <= addr_block v < heapgraph_generation_block_count g2 to\n    )%nat.\nProof.\n    induction Hg1g2 ; try (now left).\n    assert (heapgraph_has_gen g2 to) by (rewrite <- fr_graph_has_gen; eauto).\n    specialize (IHHg1g2 H0 Hv).\n    destruct IHHg1g2.\n    - eapply (fr_O_heapgraph_has_block_inv from to _ g1 g2) in H1; eauto. destruct H1.\n      1: left; assumption. right. unfold new_copied_v in H1. subst v.\n      pose proof (heapgraph_has_block__has_index Hv) as Hindex.\n      unfold heapgraph_generation_block_count.\n      red in Hindex ; simpl in Hindex ; simpl.\n      lia.\n    - right.\n      apply fr_O_gen_v_num_to in H ; try easy.\n      lia.\nQed.\n\nLemma frr_block_fields: forall from to f_info roots1 g1 roots2 g2,\n    heapgraph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall v, heapgraph_has_block g1 v -> block_fields (heapgraph_block g1 v) = block_fields (heapgraph_block g2 v).\nProof.\n  intros. induction H0. 1: reflexivity. rewrite <- IHforward_roots_loop.\n  - eapply fr_block_fields; eauto.\n  - rewrite <- fr_graph_has_gen; eauto.\n  - eapply fr_heapgraph_has_block; eauto.\nQed.\n\n\nLemma frr_heapgraph_generation_unchanged: forall from to f_info roots1 g1 roots2 g2,\n    heapgraph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall gen, gen <> to -> heapgraph_generation g1 gen = heapgraph_generation g2 gen.\nProof.\n  intros. induction H0. 1: reflexivity. rewrite <- IHforward_roots_loop.\n  - eapply fr_O_heapgraph_generation_unchanged; eauto.\n  - rewrite <- fr_graph_has_gen; eauto.\nQed.\n\n\nLemma frr_gen2gen_no_edge (from to: nat) (f_info: fun_info) (roots1: list root_t) (g1: HeapGraph) (roots2: roots_t) (g2: HeapGraph)\n    (Hto: heapgraph_has_gen g1 to)\n    (Hg1g2: forward_roots_relation from to f_info roots1 g1 roots2 g2)\n    (gen1 gen2: nat)\n    (Hgen1: gen1 <> to)\n    (Hgen1gen2: gen2gen_no_edge g1 gen1 gen2):\n    gen2gen_no_edge g2 gen1 gen2.\nProof.\n    unfold gen2gen_no_edge in *.\n    intros vidx eidx Hg2.\n    cut (heapgraph_has_field g1 {| field_addr := {| addr_gen := gen1; addr_block := vidx |} ; field_index := eidx |}).\n    + intros.\n      specialize (Hgen1gen2 vidx eidx H).\n      apply heapgraph_has_field__has_block in H.\n      erewrite (frr_dst_unchanged from to _ _ g1 _ g2) in Hgen1gen2; eauto.\n      apply Hgen1gen2.\n      intro F.\n      apply H0.\n      pose proof (fun gk => frr__heapgraph_remember_upto _ _ _ _ _ _ _ gk Hg1g2 Hto) as H1.\n      rewrite H1.\n      assert\n        (closure_has_v g1 {| addr_gen := gen1; addr_block := vidx |})\n        as Hg1_closure\n        by now apply heapgraph_has_block_in_closure.\n      simpl in F |-*.\n      now rewrite <- (frr_heapgraph_block_ptr _ _ _ _ _ _ _ Hto Hg1g2 _ Hg1_closure).\n    + pose proof (heapgraph_has_field__has_block Hg2) as Hblock.\n      eapply frr_heapgraph_has_block_inv in Hblock ; eauto.\n      destruct Hblock as [Hblock | [Eto Hblock]] ; try easy.\n      refine {|\n        heapgraph_has_field__has_block := _;\n        heapgraph_has_field__in := _;\n      |} ; try easy.\n      simpl in *.\n      cut (heapgraph_block_fields g1 {| addr_gen := gen1 ; addr_block := vidx |} = heapgraph_block_fields g2 {| addr_gen := gen1 ; addr_block := vidx |}).\n      - pose proof (heapgraph_has_field__in Hg2) as Hfield.\n        intro Eg1g2.\n        now rewrite Eg1g2.\n      - unfold heapgraph_block_fields, heapgraph_block_cells.\n        erewrite frr_block_fields; eauto.\nQed.\n\nLemma fr_O_dst_unchanged_field (from to: nat) (v: Addr) (n: nat) (g g': HeapGraph)\n    (Hfrom: forward_p_compatible (inr (v, Z.of_nat n)) [] g from)\n    (Hgg': forward_relation from to O (forward_p2forward_t (inr (v, Z.of_nat n)) [] g) g g')\n    (e: Field)\n    (He: heapgraph_has_block g (field_addr e))\n    (H'e: e <> {| field_addr := v; field_index := n |}):\n    dst g e = dst g' e.\nProof.\n    simpl in *. destruct Hfrom as [Hv [Hn [Hmark_v Hv__from]]].\n    rewrite Hmark_v in Hgg' ; simpl in Hgg'.\n    remember (Znth (Z.of_nat n) (heapgraph_block_cells g v)) as c eqn:Ec.\n    assert (forall e0, inr e0 = Znth (Z.of_nat n) (heapgraph_block_cells g v) -> e0 <> e) as Hnth.\n    {\n      intros.\n      symmetry in H.\n      apply heapgraph_block_cells_Znth_edge in H ; try easy.\n      rewrite Nat2Z.id in H.\n      congruence.\n    }\n    destruct c; [destruct s |]; simpl in Hgg'; inversion Hgg'; subst; try easy.\n    + subst new_g.\n      rewrite lgd_dst_old ; try easy.\n      now apply Hnth.\n    + subst new_g.\n      rewrite lgd_dst_old ; try now apply Hnth.\n      simpl.\n      rewrite pcv_dst_old ; try easy.\n      intro F. rewrite F in He.\n      pose proof (heapgraph_has_block__has_index He) as F'.\n      simpl in F'. red in F'.\n      lia.\nQed.\n\n\nLemma frr_heapgraph_has_block: forall from to f_info roots1 g1 roots2 g2,\n    heapgraph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall v, heapgraph_has_block g1 v -> heapgraph_has_block g2 v.\nProof.\n  intros. induction H0; subst. 1: assumption. cut (heapgraph_has_block g2 v).\n  - intros. apply IHforward_roots_loop; auto. erewrite <- fr_graph_has_gen; eauto.\n  - eapply fr_heapgraph_has_block; eauto.\nQed.\n\nLemma fr_O_dst_changed_field: forall from to v n g g',\n    copy_compatible g -> no_dangling_dst g -> from <> to -> heapgraph_has_gen g to ->\n    forward_p_compatible (inr (v, Z.of_nat n)) [] g from ->\n    forward_relation from to O (forward_p2forward_t (inr (v, Z.of_nat n)) [] g) g g' ->\n    forall e, Znth (Z.of_nat n) (heapgraph_block_cells g' v) = inr e ->\n              addr_gen (dst g' e) <> from.\nProof.\n  intros. simpl in *. destruct H3 as [? [? [? ?]]]. rewrite H7 in H4. simpl in H4.\n  assert (heapgraph_block_cells g v = heapgraph_block_cells g' v) by\n      (unfold heapgraph_block_cells; erewrite fr_block_fields; eauto). rewrite <- H9 in *.\n  clear H9. remember (Znth (Z.of_nat n) (heapgraph_block_cells g v)). destruct c; inversion H5.\n  subst. clear H5. symmetry in Heqc. pose proof Heqc.\n  apply heapgraph_block_cells_Znth_edge in Heqc. 2: assumption. simpl in H4. subst.\n  rewrite Nat2Z.id in *.\n  inversion H4; subst; try assumption; subst new_g; rewrite lgd_dst_new.\n  - apply H in H12. 1: destruct H12; auto. specialize (H0 _ H3). apply H0.\n    unfold heapgraph_block_fields. rewrite <- filter_sum_right_In_iff, <- H5. apply Znth_In.\n    rewrite heapgraph_block_cells_eq_length. assumption.\n  - unfold new_copied_v. simpl. auto.\nQed.\n\nLemma fr_O_no_dangling_dst: forall from to p g g' roots,\n    forward_p_compatible p roots g from -> heapgraph_has_gen g to ->\n    roots_graph_compatible roots g -> copy_compatible g ->\n    forward_relation from to O (forward_p2forward_t p roots g) g g' ->\n    no_dangling_dst g -> no_dangling_dst g'.\nProof.\n  intros. inversion H3; subst; try assumption.\n  - destruct p; simpl in H5.\n    + destruct (Znth z roots) eqn:? ; [destruct s|]; simpl in H5; inversion H5.\n      subst. clear H5. apply lcv_no_dangling_dst; auto. red in H1.\n      rewrite Forall_forall in H1. apply H1. rewrite <- filter_sum_right_In_iff.\n      rewrite <- Heqr. apply Znth_In. assumption.\n    + destruct p. simpl in H. destruct H as [? [? [? ?]]]. rewrite H8 in H5.\n      simpl in H5. destruct (Znth z (heapgraph_block_cells g a)); [destruct s|];\n                     simpl in H5; inversion H5.\n  - subst new_g. apply lgd_no_dangling_dst_copied_vert; auto.\n    destruct p; simpl in H5.\n    + destruct (Znth z roots); [destruct s|]; simpl in H5; inversion H5.\n    + destruct p. simpl in H. destruct H as [? [? [? ?]]]. rewrite H7 in H5.\n      simpl in H5. destruct (Znth z (heapgraph_block_cells g a)) eqn:? ; [destruct s|];\n                     simpl in H5; inversion H5. subst. clear H5.\n      specialize (H4 _ H). apply H4. unfold heapgraph_block_fields.\n      rewrite <- filter_sum_right_In_iff, <- Heqc. apply Znth_In.\n      rewrite heapgraph_block_cells_eq_length. assumption.\n  - subst new_g. apply lgd_no_dangling_dst. 1: apply lcv_heapgraph_has_block_new; auto.\n    apply lcv_no_dangling_dst; auto. destruct p; simpl in H5.\n    + destruct (Znth z roots); [destruct s|]; simpl in H5; inversion H5.\n    + destruct p. simpl in H. destruct H as [? [? [? ?]]]. rewrite H8 in H5.\n      simpl in H5. destruct (Znth z (heapgraph_block_cells g a)) eqn:? ; [destruct s|];\n                     simpl in H5; inversion H5. subst. clear H5.\n      specialize (H4 _ H). apply H4. unfold heapgraph_block_fields.\n      rewrite <- filter_sum_right_In_iff, <- Heqc. apply Znth_In.\n      rewrite heapgraph_block_cells_eq_length. assumption.\nQed.\n\n\nLemma frr_firstn_gen_clear: forall from to f_info roots1 g1 roots2 g2,\n    heapgraph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall gen, (gen <= to)%nat ->\n                firstn_gen_clear g1 gen -> firstn_gen_clear g2 gen.\nProof.\n  intros. unfold firstn_gen_clear, graph_gen_clear in *. intros.\n  erewrite <- frr_heapgraph_generation_unchanged; eauto. lia.\nQed.\n\nLemma fr_O_stcg: forall from to p g1 g2,\n    heapgraph_has_gen g1 to -> forward_relation from to O p g1 g2 ->\n    forall gen1 gen2, heapgraph_has_gen g1 gen2 -> gen2 <> to ->\n                      heapgraph_generation_can_copy g1 gen1 gen2 -> heapgraph_generation_can_copy g2 gen1 gen2.\nProof.\n  intros. unfold heapgraph_generation_can_copy in *.\n  erewrite <- (fr_O_graph_gen_size_unchanged from to); eauto.\n  erewrite <- (fr_O_graph_remember_size_unchanged from to); eauto.\nQed.\n\nLemma frr_stcg: forall from to f_info roots1 g1 roots2 g2,\n    heapgraph_has_gen g1 to -> forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    forall gen1 gen2, heapgraph_has_gen g1 gen2 -> gen2 <> to ->\n                      heapgraph_generation_can_copy g1 gen1 gen2 -> heapgraph_generation_can_copy g2 gen1 gen2.\nProof.\n  intros. induction H0. 1: assumption. apply IHforward_roots_loop.\n  - erewrite <- (fr_graph_has_gen O from to); eauto.\n  - erewrite <- (fr_graph_has_gen O from to); eauto.\n  - eapply (fr_O_stcg from to); eauto.\nQed.\n\nLemma frr_copy_compatible: forall from to f_info roots g roots' g',\n    from <> to -> heapgraph_has_gen g to ->\n    forward_roots_relation from to f_info roots g roots' g' ->\n    copy_compatible g -> copy_compatible g'.\nProof.\n  intros. induction H1. 1: assumption. apply IHforward_roots_loop.\n  - rewrite <- fr_graph_has_gen; eauto.\n  - eapply fr_copy_compatible; eauto.\nQed.\n\nLemma frl_no_dangling_dst: forall from to f_info l roots g roots' g',\n    heapgraph_has_gen g to -> copy_compatible g -> from <> to ->\n    (forall i, In i l -> i < length roots)%nat ->\n    Zlength roots = Zlength (live_roots_indices f_info) ->\n    roots_graph_compatible roots g ->\n    forward_roots_loop from to f_info l roots g roots' g' ->\n    no_dangling_dst g -> no_dangling_dst g'.\nProof.\n  do 4 intro. induction l; intros; inversion H5; subst. 1: assumption.\n  assert (forward_p_compatible (inl (Z.of_nat a)) roots g from). {\n    simpl. split. 1: lia. rewrite Zlength_correct. apply inj_lt.\n    apply H2; left; reflexivity. } cut (no_dangling_dst g2).\n  - intros. eapply (IHl (upd_roots from to (inl (Z.of_nat a)) g roots f_info)\n                        g2 roots'); eauto.\n    + erewrite <- fr_graph_has_gen; eauto.\n    + eapply (fr_copy_compatible O from to _ g); eauto.\n    + intros. rewrite <- ZtoNat_Zlength, upd_roots_Zlength, ZtoNat_Zlength; auto.\n      apply H2. right; assumption.\n    + rewrite upd_roots_Zlength; assumption.\n    + eapply fr_roots_graph_compatible; eauto.\n  - fold (forward_p2forward_t (inl (Z.of_nat a)) roots g) in H9.\n    eapply fr_O_no_dangling_dst; eauto.\nQed.\n\nLemma frr_no_dangling_dst: forall from to f_info roots g roots' g',\n    heapgraph_has_gen g to -> copy_compatible g -> from <> to ->\n    Zlength roots = Zlength (live_roots_indices f_info) ->\n    roots_graph_compatible roots g ->\n    forward_roots_relation from to f_info roots g roots' g' ->\n    no_dangling_dst g -> no_dangling_dst g'.\nProof.\n  intros. eapply frl_no_dangling_dst; eauto. intros.\n  rewrite nat_inc_list_In_iff in H6. assumption.\nQed.\n\nLemma frr_roots_fi_compatible: forall from to f_info roots1 g1 roots2 g2,\n    forward_roots_relation from to f_info roots1 g1 roots2 g2 ->\n    roots_fi_compatible roots1 f_info -> roots_fi_compatible roots2 f_info.\nProof.\n  intros. induction H; subst. 1: assumption. apply IHforward_roots_loop.\n  apply upd_roots_rf_compatible; assumption.\nQed.\n", "meta": {"author": "CertiGraph", "repo": "CertiGC", "sha": "ec0183449d5e7dc66d33c9bc2dd5759de0ebd877", "save_path": "github-repos/coq/CertiGraph-CertiGC", "path": "github-repos/coq/CertiGraph-CertiGC/CertiGC-ec0183449d5e7dc66d33c9bc2dd5759de0ebd877/theories/CertiGC/model/op/forward.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.21568617666058773}}
{"text": "Require Import UFO.Rel.Definitions.\nRequire Import UFO.Rel.BasicFacts.\nRequire Import UFO.Rel.Monotone.\nRequire Import UFO.Rel.Compat_sub.\nRequire Import UFO.Util.Subset.\nRequire Import UFO.Util.Postfix.\nRequire Import UFO.Lang.BindingsFacts.\nRequire Import UFO.Lang.Static.\nRequire Import UFO.Lang.StaticFacts.\nSet Implicit Arguments.\n\nSection section_ccompat_tm_up.\n\nContext (EV LV : Set).\nContext (Ξ : XEnv EV LV).\nContext (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig).\nContext (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig).\nContext (T : ty ∅ EV LV ∅) (E₁ E₂ : eff ∅ EV LV ∅) (ℓ : lbl LV ∅).\n\nLemma ccompat_tm_up n ξ₁ ξ₂ t₁ t₂ :\nn ⊨ 𝓣⟦ Ξ ⊢ (ty_ms (ms_res T E₁) ℓ) # E₂ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ t₁ t₂ →\nn ⊨ 𝓣⟦ Ξ ⊢ T # ((ef_lbl ℓ) :: (E₁ ++ E₂)) ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ (⇧ t₁) (⇧ t₂).\nProof.\nintro Ht.\nchange (⇧ t₁) with (ktx_plug (ktx_up ktx_hole) t₁).\nchange (⇧ t₂) with (ktx_plug (ktx_up ktx_hole) t₂).\neapply plug0 with (Ta := ty_ms (ms_res T E₁) ℓ).\n+ intro ; simpl ; auto.\n+ intro ; simpl ; auto.\n+ iintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂' ;\n  iintro v₁ ; iintro v₂ ; iintro Hv.\n  bind_hole ; apply 𝓦_in_𝓣.\n  destruct v₁ as [ | | | m₁ [ | X₁] | m₁ [ | X₁] ], v₂ as [ | | | m₂ [ | X₂] | m₂ [ | X₂] ] ; simpl in Hv ;\n  idestruct Hv as m₁' Hv ; idestruct Hv as m₂' Hv ;\n  idestruct Hv as X₁' Hv ; idestruct Hv as X₂' Hv ;\n  idestruct Hv as Hv Hr ; ielim_prop Hv ; destruct Hv as [Hv₁ Hv₂] ;\n  inversion Hv₁ ; inversion Hv₂ ; clear Hv₁ Hv₂ ; subst m₁' m₂' X₁' X₂'.\n\n  idestruct Hr as HX₁X₂ Hr ; idestruct Hr as r₁ Hr ; idestruct Hr as r₂ Hr ;\n  idestruct Hr as Hr₁r₂ Hr ; idestruct Hr as HX Hr.\n  ielim_prop Hr₁r₂ ; destruct Hr₁r₂; subst m₁ m₂.\n  ielim_prop HX₁X₂ ; destruct HX₁X₂ as [HX₁ HX₂].\n\n  simpl ktx_plug.\n  destruct ℓ as [ α | [ α | X ] ] ; simpl in Hr ; [ | destruct α | ].\n  { eapply fold_𝓦\n    with (ψ := 𝓣⟦ Ξ ⊢ T # (ef_lbl (lbl_var α) :: E₁) ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ).\n    + apply ccompat_eff_In with (ε := ef_lbl (lbl_var α)).\n      { left ; trivial. }\n      repeat ieexists ; repeat isplit ; try iintro_prop ; crush.\n    + crush.\n    + clear.\n      do 7 iintro.\n      later_shift.\n      eapply ccompat_sub ; try eassumption.\n      { apply st_reflexive. }\n      { rewrite app_comm_cons ; apply se_app_l. }\n  }\n  { eapply fold_𝓦\n    with (ψ := 𝓣⟦ Ξ ⊢ T # (ef_lbl (lbl_id (lid_f X)) :: E₁) ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ).\n    + apply ccompat_eff_In with (ε := ef_lbl (lbl_id (lid_f X))).\n      { left ; trivial. }\n      simpl in HX₁, HX₂.\n      inversion HX₁ ; inversion HX₂ ; clear HX₁ HX₂ ; subst X₁ X₂.\n      simpl 𝓾_Fun.\n      repeat ieexists ; repeat isplit ; try iintro_prop ; crush.\n    + crush.\n    + clear.\n      do 7 iintro ; later_shift.\n      eapply ccompat_sub ; try eassumption.\n      { apply st_reflexive. }\n      { rewrite app_comm_cons ; apply se_app_l. }\n  }\n+ apply postfix_refl.\n+ apply postfix_refl.\n+ eapply ccompat_sub ; try eassumption.\n  { apply st_reflexive. }\n  { apply se_cons_r ; apply se_app_r. }\nQed.\n\nEnd section_ccompat_tm_up.\n\n\nSection section_compat_tm_up.\nContext (n : nat).\nContext (EV LV V : Set).\nContext (Ξ : XEnv EV LV).\nContext (Γ : V → ty ∅ EV LV ∅).\nContext (T : ty ∅ EV LV ∅) (E₁ E₂ : eff ∅ EV LV ∅) (ℓ : lbl LV ∅).\n\nLemma compat_tm_up t₁ t₂ :\nn ⊨ ⟦ Ξ Γ ⊢ t₁ ≼ˡᵒᵍ t₂ : (ty_ms (ms_res T E₁) ℓ) # E₂ ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ (⇧ t₁) ≼ˡᵒᵍ (⇧ t₂) : T # ((ef_lbl ℓ) :: (E₁ ++ E₂)) ⟧.\nProof.\nintro Ht.\niintro ξ₁ ; iintro ξ₂ ;\niintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ;\niintro γ₁ ; iintro γ₂.\niintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.\nsimpl subst_tm.\napply ccompat_tm_up.\niespecialize Ht.\nispecialize Ht ; [ eassumption | ].\nispecialize Ht ; [ eassumption | ].\nispecialize Ht ; [ eassumption | ].\nispecialize Ht ; [ eassumption | ].\napply Ht.\nQed.\n\nLemma compat_ktx_up T' E' K₁ K₂ :\nn ⊨ ⟦ Ξ Γ ⊢ K₁ ≼ˡᵒᵍ K₂ :\n      T' # E' ⇢ (ty_ms (ms_res T E₁) ℓ) # E₂ ⟧ →\nn ⊨ ⟦ Ξ Γ ⊢ (ktx_up K₁) ≼ˡᵒᵍ (ktx_up K₂) :\n      T' # E' ⇢ T # ((ef_lbl ℓ) :: (E₁ ++ E₂)) ⟧.\nProof.\nintro HK.\niintro ξ₁ ; iintro ξ₂ ;\niintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ;\niintro γ₁ ; iintro γ₂.\niintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.\niintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂' ;\niintro t₁ ; iintro t₂ ; iintro Ht.\niespecialize HK.\nispecialize HK ; [ eassumption | ].\nispecialize HK ; [ eassumption | ].\nispecialize HK ; [ eassumption | ].\nispecialize HK ; [ eassumption | ].\nielim_vars HK ; [ | eassumption | eassumption ].\niespecialize HK.\nispecialize HK ; [ eassumption | ].\nsimpl ktx_plug.\napply ccompat_tm_up.\napply HK.\nQed.\n\nEnd section_compat_tm_up.\n", "meta": {"author": "yizhouzhang", "repo": "olaf-coq", "sha": "03090a5e60e739dfa45ad60322d848c18faad48d", "save_path": "github-repos/coq/yizhouzhang-olaf-coq", "path": "github-repos/coq/yizhouzhang-olaf-coq/olaf-coq-03090a5e60e739dfa45ad60322d848c18faad48d/coq-src/UFO/Rel/Compat_tm_up.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.2156861684246386}}
{"text": "(*============================================================================\n EVM Instructions.\n \n ============================================================================*)\n\n\nRequire Import mathcomp.ssreflect.ssreflect.\nFrom mathcomp Require Import ssrfun ssrbool eqtype ssrnat seq fintype tuple zmodp.\n\nRequire Import bitsrep bitsops.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n(*= Instr *)\nInductive Instr :=\n    (* Stop and arithmetic operations *)\n| STOP\n| ADD\n| MUL\n| SUB\n| DIV\n| SDIV\n| MOD\n| SMOD\n| ADDMOD\n| MULMOD\n| EXP\n| SIGNEXTEND\n    (* Comparison and bitwise logic operations *)\n| LT\n| GT\n| SLT\n| SGT\n| EQ\n| ISZERO\n| AND\n| OR\n| XOR\n| NOT\n| GETBYTE\n    (* SHA3 *)\n| SHA3\n    (* Environmental Information *)\n| GETADDRESS\n| BALANCE\n| ORIGIN\n| CALLER\n| CALLVALUE\n| CALLDATALOAD\n| CALLDATASIZE\n| CALLDATACOPY\n| CODESIZE\n| CODECOPY\n| GASPRICE\n| EXTCODESIZE\n| EXTCODECOPY\n    (* Block Information *)\n| BLOCKHASH\n| COINBASE\n| TIMESTAMP\n| NUMBER\n| DIFFICULTY\n| GASLIMIT\n    (* Stack, memory, storage and flow controls *)\n| POP\n| MLOAD\n| MSTORE\n| MSTORE8\n| SLOAD\n| SSTORE\n| JUMP\n| JUMPI\n| PC\n| MSIZE\n| GAS\n| JUMPDEST\n    (* Push operations *)\n| PUSH1\n| PUSH2\n| PUSH3\n| PUSH4\n| PUSH5\n| PUSH6\n| PUSH7\n| PUSH8\n| PUSH9\n| PUSH10\n| PUSH11\n| PUSH12\n| PUSH13\n| PUSH14\n| PUSH15\n| PUSH16\n| PUSH17\n| PUSH18\n| PUSH19\n| PUSH20\n| PUSH21\n| PUSH22\n| PUSH23\n| PUSH24\n| PUSH25\n| PUSH26\n| PUSH27\n| PUSH28\n| PUSH29\n| PUSH30\n| PUSH31\n| PUSH32\n    (* Duplication operations *)\n| DUP1\n| DUP2\n| DUP3\n| DUP4\n| DUP5\n| DUP6\n| DUP7\n| DUP8\n| DUP9\n| DUP10\n| DUP11\n| DUP12\n| DUP13\n| DUP14\n| DUP15\n| DUP16\n    (* Exchange Operations *)\n| SWAP1\n| SWAP2\n| SWAP3\n| SWAP4\n| SWAP5\n| SWAP6\n| SWAP7\n| SWAP8\n| SWAP9\n| SWAP10\n| SWAP11\n| SWAP12\n| SWAP13\n| SWAP14\n| SWAP15\n| SWAP16\n    (* Logging Operations *)\n| LOG0\n| LOG1\n| LOG2\n| LOG3\n| LOG4\n    (* System Operations *)\n| CREATE\n| CALL\n| CALLCODE\n| RETURN\n| DELEGATECALL\n| SUCIDE\n| BADINSTR.\n\n    \n(*-------------------------------------------------------------------\n From nat to Instr\n -------------------------------------------------------------------*)\nDefinition fromNatToInstr (n : nat) : Instr :=\n  match n with\n    | 0 => STOP\n    | 1 => ADD\n    | 2 => MUL\n    | 3 => SUB\n    | 4 => DIV\n    | 5 => SDIV\n    | 6 => MOD\n    | 7 => SMOD\n    | 8 => ADDMOD\n    | 9 => MULMOD\n    | 10 => EXP\n    | 11 => SIGNEXTEND\n    (* Comparison and bitwise logic operations *)\n    | 16 => LT\n    | 17 => GT\n    | 18 => SLT\n    | 19 => SGT\n    | 20 => EQ\n    | 21 => ISZERO\n    | 22 => AND\n    | 23 => OR\n    | 24 => XOR\n    | 25 => NOT\n    | 26 => GETBYTE\n    (* SHA3 *)\n    | 32 => SHA3\n    (* Environmental Information *)\n    | 48 => GETADDRESS\n    | 49 => BALANCE\n    | 50 => ORIGIN\n    | 51 => CALLER\n    | 52 => CALLVALUE\n    | 53 => CALLDATALOAD\n    | 54 => CALLDATASIZE\n    | 55 => CALLDATACOPY\n    | 56 => CODESIZE\n    | 57 => CODECOPY\n    | 58 => GASPRICE\n    | 59 => EXTCODESIZE\n    | 60 => EXTCODECOPY\n    (* Block Information *)\n    | 64 => BLOCKHASH\n    | 65 => COINBASE\n    | 66 => TIMESTAMP\n    | 67 => NUMBER\n    | 68 => DIFFICULTY\n    | 69 => GASLIMIT\n    (* Stack, memory, storage and flow controls *)\n    | 80 => POP\n    | 81 => MLOAD\n    | 82 => MSTORE\n    | 83 => MSTORE8\n    | 84 => SLOAD\n    | 85 => SSTORE\n    | 86 => JUMP\n    | 87 => JUMPI\n    | 88 => PC\n    | 89 => MSIZE\n    | 90 => GAS\n    | 91 =>JUMPDEST\n    (* Push operations *)\n    | 96 => PUSH1\n    | 97 => PUSH2\n    | 98 => PUSH3\n    | 99 => PUSH4\n    | 100 => PUSH5\n    | 101 => PUSH6\n    | 102 => PUSH7\n    | 103 => PUSH8\n    | 104 => PUSH9\n    | 105 => PUSH10\n    | 106 => PUSH11\n    | 107 => PUSH12\n    | 108 => PUSH13\n    | 109 => PUSH14\n    | 110 => PUSH15\n    | 111 => PUSH16\n    | 112 => PUSH17\n    | 113 => PUSH18\n    | 114 => PUSH19\n    | 115 => PUSH20\n    | 116 => PUSH21\n    | 117 => PUSH22\n    | 118 => PUSH23\n    | 119 => PUSH24\n    | 120 => PUSH25\n    | 121 => PUSH26\n    | 122 => PUSH27\n    | 123 => PUSH28\n    | 124 => PUSH29\n    | 125 => PUSH30\n    | 126 => PUSH31\n    | 127 => PUSH32\n    (* Duplication operations *)\n    | 128 => DUP1\n    | 129 => DUP2\n    | 130 => DUP3\n    | 131 => DUP4\n    | 132 => DUP5\n    | 133 => DUP6\n    | 134 => DUP7\n    | 135 => DUP8\n    | 136 => DUP9\n    | 137 => DUP10\n    | 138 => DUP11\n    | 139 => DUP12\n    | 140 => DUP13\n    | 141 => DUP14\n    | 142 => DUP15\n    | 143 => DUP16\n    (* Exchange Operations *)\n    | 144 => SWAP1\n    | 145 => SWAP2\n    | 146 => SWAP3\n    | 147 => SWAP4\n    | 148 => SWAP5\n    | 149 => SWAP6\n    | 150 => SWAP7\n    | 151 => SWAP8\n    | 152 => SWAP9\n    | 153 => SWAP10\n    | 154 => SWAP11\n    | 155 => SWAP12\n    | 156 => SWAP13\n    | 157 => SWAP14\n    | 158 => SWAP15\n    | 159 => SWAP16\n    (* Logging Operations *)\n    | 160 => LOG0\n    | 161 => LOG1\n    | 162 => LOG2\n    | 163 => LOG3\n    | 164 => LOG4\n    (* System Operations *)\n    | 240 => CREATE\n    | 241 => CALL\n    | 242 => CALLCODE\n    | 243 => RETURN\n    | 244 => DELEGATECALL\n    | 255 => SUCIDE            \n    | _ => BADINSTR\n  end.\n\n(*--------------------------------------------------------------------\n Instr to string for assembly decoder.\n --------------------------------------------------------------------*)\nFrom Coq Require Import ZArith.ZArith Strings.String.\nImport Ascii.\n\nDefinition instrToString (i : Instr) :=\n  (match i with\n          (* Stop and arithmetic operations *)\n| STOP => \"STOP\"\n| ADD => \"ADD\"\n| MUL => \"MUL\"\n| SUB => \"SUB\"\n| DIV => \"DIV\"\n| SDIV => \"SDIV\"\n| MOD => \"MOD\"\n| SMOD => \"SMOD\"\n| ADDMOD => \"ADDMOD\"\n| MULMOD => \"MULMOD\"\n| EXP => \"EXP\"\n| SIGNEXTEND => \"SIGNEXTEND\"\n    (* Comparison and bitwise logic operations *)\n| LT => \"LT\"\n| GT => \"GT\"\n| SLT => \"SLT\"\n| SGT => \"SGT\"\n| EQ => \"EQ\"\n| ISZERO => \"ISZERO\"\n| AND => \"AND\"\n| OR => \"OR\"\n| XOR => \"XOR\"\n| NOT => \"NOT\"\n| GETBYTE => \"BYTE\"\n    (* SHA3 *)\n| SHA3 => \"SHA3\"\n    (* Environmental Information *)\n| GETADDRESS => \"ADDRESS\"\n| BALANCE => \"BALANCE\"\n| ORIGIN => \"ORIGIN\"\n| CALLER => \"CALLER\"\n| CALLVALUE => \"CALLVALUE\"\n| CALLDATALOAD => \"CALLDATALOAD\"\n| CALLDATASIZE => \"CALLDATASIZE\"\n| CALLDATACOPY => \"CALLDATACOPY\"\n| CODESIZE => \"CODESIZE\"\n| CODECOPY => \"CODECOPY\"\n| GASPRICE => \"GASPRICE\"\n| EXTCODESIZE => \"EXTCODESIZE\"\n| EXTCODECOPY => \"EXTCODECOPY\"\n    (* Block Information *)\n| BLOCKHASH => \"BLOCKHASH\"\n| COINBASE => \"COINBASE\"\n| TIMESTAMP => \"TIMESTAMP\"\n| NUMBER => \"NUMBER\"\n| DIFFICULTY => \"DIFFICULTY\"\n| GASLIMIT => \"GASLIMIT\"\n    (* Stack, memory, storage and flow controls *)\n| POP => \"POP\"\n| MLOAD => \"MLOAD\"\n| MSTORE => \"MSTORE\"\n| MSTORE8 => \"MSTORE8\"\n| SLOAD => \"SLOAD\"\n| SSTORE => \"SSTORE\"\n| JUMP => \"JUMP\"\n| JUMPI => \"JUMPI\"\n| PC => \"PC\"\n| MSIZE => \"MSIZE\"\n| GAS => \"GAS\"\n| JUMPDEST => \"JUMPDEST\"\n    (* Push operations *)\n| PUSH1 => \"PUSH1\"\n| PUSH2 => \"PUSH2\"\n| PUSH3 => \"PUSH3\"\n| PUSH4 => \"PUSH4\"\n| PUSH5 => \"PUSH5\"\n| PUSH6 => \"PUSH6\"\n| PUSH7 => \"PUSH7\"\n| PUSH8 => \"PUSH8\"\n| PUSH9 => \"PUSH9\"\n| PUSH10 => \"PUSH10\"\n| PUSH11 => \"PUSH11\"\n| PUSH12 => \"PUSH12\"\n| PUSH13 => \"PUSH13\"\n| PUSH14 => \"PUSH14\"\n| PUSH15 => \"PUSH15\"\n| PUSH16 => \"PUSH16\"\n| PUSH17 => \"PUSH17\"\n| PUSH18 => \"PUSH18\"\n| PUSH19 => \"PUSH19\"\n| PUSH20 => \"PUSH20\"\n| PUSH21 => \"PUSH21\"\n| PUSH22 => \"PUSH22\"\n| PUSH23 => \"PUSH23\"\n| PUSH24 => \"PUSH24\"\n| PUSH25 => \"PUSH25\"\n| PUSH26 => \"PUSH26\"\n| PUSH27 => \"PUSH27\"\n| PUSH28 => \"PUSH28\"\n| PUSH29 => \"PUSH29\"\n| PUSH30 => \"PUSH30\"\n| PUSH31 => \"PUSH31\"\n| PUSH32 => \"PUSH32\"\n    (* Duplication operations *)\n| DUP1 => \"DUP1\"\n| DUP2 => \"DUP2\"\n| DUP3 => \"DUP3\"\n| DUP4 => \"DUP4\"\n| DUP5 => \"DUP5\"\n| DUP6 => \"DUP6\"\n| DUP7 => \"DUP7\" \n| DUP8 => \"DUP8\"\n| DUP9 => \"DUP9\"\n| DUP10 => \"DUP10\"\n| DUP11 => \"DUP11\"\n| DUP12 => \"DUP12\"\n| DUP13 => \"DUP13\"\n| DUP14 => \"DUP14\"\n| DUP15 => \"DUP15\"\n| DUP16 => \"DUP16\"\n    (* Exchange Operations *)\n| SWAP1 => \"SWAP1\"\n| SWAP2 => \"SWAP2\"\n| SWAP3 => \"SWAP3\"\n| SWAP4 => \"SWAP4\"\n| SWAP5 => \"SWAP5\"\n| SWAP6 => \"SWAP6\"\n| SWAP7 => \"SWAP7\"\n| SWAP8 => \"SWAP8\"\n| SWAP9 => \"SWAP9\"\n| SWAP10 => \"SWAP10\"\n| SWAP11 => \"SWAP11\"\n| SWAP12 => \"SWAP12\"\n| SWAP13 => \"SWAP13\"\n| SWAP14 => \"SWAP14\"\n| SWAP15 => \"SWAP15\"\n| SWAP16 => \"SWAP16\"\n    (* Logging Operations *)\n| LOG0 => \"LOG0\"\n| LOG1 => \"LOG1\"\n| LOG2 => \"LOG2\"\n| LOG3 => \"LOG3\"\n| LOG4 => \"LOG4\"\n    (* System Operations *)\n| CREATE => \"CREATE\"\n| CALL => \"CALL\"\n| CALLCODE => \"CALLCODE\"\n| RETURN => \"RETURN\"\n| DELEGATECALL => \"DELEGATECALL\"\n| SUCIDE => \"SUCIDE\"\n| _ => \"BADINSTR\"\n   end)%string.\n\n\n(*--------------------------------------------------------------------\n Unit test.\n --------------------------------------------------------------------*)\nCompute (fromNatToInstr 243).", "meta": {"author": "channgo2203", "repo": "fevm", "sha": "5ecf7e136ef7c5bc89d0ac24df04ff461122a850", "save_path": "github-repos/coq/channgo2203-fevm", "path": "github-repos/coq/channgo2203-fevm/fevm-5ecf7e136ef7c5bc89d0ac24df04ff461122a850/src/instr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.21549176579436202}}
{"text": "Require Import veric.rmaps.\nRequire Import progs.conclib.\nRequire Import progs.ghost.\nRequire Import floyd.library.\nRequire Import floyd.sublist.\nRequire Import mailbox.sim_atomics.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition acquire_spec := DECLARE _acquire acquire_spec.\nDefinition release_spec := DECLARE _release release_spec.\nDefinition makelock_spec := DECLARE _makelock (makelock_spec _).\nDefinition freelock_spec := DECLARE _freelock (freelock_spec _).\n\nDefinition surely_malloc_spec :=\n DECLARE _surely_malloc\n   WITH n:Z\n   PRE [ _n OF tuint ]\n       PROP (0 <= n <= Int.max_unsigned)\n       LOCAL (temp _n (Vint (Int.repr n)))\n       SEP ()\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (malloc_token Tsh n p * memory_block Tsh n p).\n\n\n(* lock invariant for atomic locations *)\nDefinition tatomic := Tstruct _atomic_loc noattr.\n\nDefinition A_inv p l R := EX v : Z, !!(repable_signed v) &&\n  (field_at Tsh tatomic [StructField _val] (vint v) p * R v *\n   (weak_precise_mpred (R v) && emp) * malloc_token Tsh (sizeof tatomic) p * malloc_token Tsh (sizeof tlock) l).\n\nDefinition atomic_loc sh p R := !!(field_compatible tatomic [] p) &&\n  (EX lock : val, field_at sh tatomic [StructField _lock] lock p * lock_inv sh lock (A_inv p lock R)).\n\nLemma A_inv_super_non_expansive : forall n p l R,\n  compcert_rmaps.RML.R.approx n (A_inv p l R) =\n  compcert_rmaps.RML.R.approx n (A_inv p l (fun v => compcert_rmaps.RML.R.approx n (R v))).\nProof.\n  intros; unfold A_inv.\n  rewrite !approx_exp; apply f_equal; extensionality v.\n  rewrite !approx_andp, !approx_sepcon, !approx_andp.\n  rewrite approx_idem.\n  rewrite (nonexpansive_super_non_expansive (fun R => weak_precise_mpred R))\n    by (apply precise_mpred_nonexpansive); auto.\nQed.\n\nLemma atomic_loc_super_non_expansive : forall n sh p R,\n  compcert_rmaps.RML.R.approx n (atomic_loc sh p R) =\n  compcert_rmaps.RML.R.approx n (atomic_loc sh p (fun v => compcert_rmaps.RML.R.approx n (R v))).\nProof.\n  intros; unfold atomic_loc.\n  rewrite !approx_andp; apply f_equal.\n  rewrite !approx_exp; apply f_equal; extensionality l.\n  rewrite !approx_sepcon.\n  rewrite (nonexpansive_super_non_expansive (fun R => lock_inv sh l R)) by (apply nonexpansive_lock_inv).\n  setoid_rewrite (nonexpansive_super_non_expansive (fun R => lock_inv sh l R)) at 2;\n    [|apply nonexpansive_lock_inv].\n  rewrite A_inv_super_non_expansive; auto.\nQed.\n\nNotation \"'TYPE' A 'WITH'  x1 : t1 , x2 : t2 , x3 : t3 , x4 : t4 'PRE'  [ u , .. , v ] P 'POST' [ tz ] Q\" :=\n     (mk_funspec ((cons u%formals .. (cons v%formals nil) ..), tz) cc_default A\n  (fun (ts: list Type) (x: t1*t2*t3*t4) =>\n     match x with (x1,x2,x3,x4) => P%assert end)\n  (fun (ts: list Type) (x: t1*t2*t3*t4) =>\n     match x with (x1,x2,x3,x4) => Q%assert end) _ _)\n            (at level 200, x1 at level 0, x2 at level 0, x3 at level 0, x4 at level 0,\n             P at level 100, Q at level 100).\n\nDefinition MA_spec i P (R : Z -> mpred) Q := view_shift P (R i * (weak_precise_mpred (R i) && emp) * Q).\n\nDefinition MA_type := ProdType (ProdType (ProdType (ConstType Z) Mpred) (ArrowType (ConstType Z) Mpred)) Mpred.\n\nProgram Definition make_atomic_spec := DECLARE _make_atomic TYPE MA_type\n  WITH i : Z, P : mpred, R : Z -> mpred, Q : mpred\n  PRE [ _i OF tint ]\n   PROP (MA_spec i P R Q; repable_signed i)\n   LOCAL (temp _i (vint i))\n   SEP (P)\n  POST [ tptr tatomic ]\n   EX p : val,\n   PROP ()\n   LOCAL (temp ret_temp p)\n   SEP (atomic_loc Tsh p R; Q).\nNext Obligation.\nProof.\n  replace _ with (fun (_ : list Type) (x : Z * mpred * (Z -> mpred) * mpred) rho =>\n    PROP (let '(i, P, R, Q) := x in MA_spec i P R Q /\\ repable_signed i)\n    LOCAL (let '(i, P, R, Q) := x in temp _i (vint i))\n    SEP (let '(i, P, R, Q) := x in P) rho).\n  apply (PROP_LOCAL_SEP_super_non_expansive MA_type [fun _ => _] [fun _ => _] [fun _ => _]);\n    repeat constructor; hnf; intros; destruct x as (((i, P), R), Q); auto; simpl.\n  - rewrite !prop_and, !approx_andp; f_equal.\n    unfold MA_spec.\n    rewrite view_shift_super_non_expansive.\n    setoid_rewrite view_shift_super_non_expansive at 2.\n    rewrite !approx_sepcon, !approx_idem, !approx_andp.\n    rewrite (nonexpansive_super_non_expansive weak_precise_mpred) by (apply precise_mpred_nonexpansive); auto.\n  - rewrite approx_idem; auto.\n  - extensionality ts x rho.\n    destruct x as (((?, ?), ?), ?); unfold PROPx, SEPx; simpl.\n    rewrite !sepcon_emp; f_equal; f_equal.\n    apply prop_ext; tauto.\nQed.\nNext Obligation.\nProof.\n  replace _ with (fun (_ : list Type) (x : Z * mpred * (Z -> mpred) * mpred) rho =>\n    EX p : val, PROP () LOCAL (let '(i, P, R, Q) := x in temp ret_temp p)\n                SEP (let '(i, P, R, Q) := x in atomic_loc Tsh p R * Q) rho).\n  - repeat intro.\n    rewrite !approx_exp; apply f_equal; extensionality p.\n    apply (PROP_LOCAL_SEP_super_non_expansive MA_type []\n      [fun ts x => let '(i, P, R, Q) := x in temp ret_temp p]\n      [fun ts x => let '(i, P, R, Q) := x in atomic_loc Tsh p R * Q]); repeat constructor; hnf; intros;\n      destruct x0 as (((i, P), R), Q); [auto | simpl].\n    rewrite !approx_sepcon, approx_idem, atomic_loc_super_non_expansive; auto.\n  - extensionality ts x rho.\n    destruct x as (((?, ?), ?), ?); unfold SEPx; simpl.\n    apply f_equal; extensionality p.\n    rewrite sepcon_assoc; auto.\nQed.\n\nNotation \"'TYPE' A 'WITH'  x1 : t1 , x2 : t2 'PRE'  [ u , .. , v ] P 'POST' [ tz ] Q\" :=\n     (mk_funspec ((cons u%formals .. (cons v%formals nil) ..), tz) cc_default A\n  (fun (ts: list Type) (x: t1*t2) =>\n     match x with (x1,x2) => P%assert end)\n  (fun (ts: list Type) (x: t1*t2) =>\n     match x with (x1,x2) => Q%assert end) _ _)\n            (at level 200, x1 at level 0, x2 at level 0,\n             P at level 100, Q at level 100).\n\nProgram Definition free_atomic_spec := DECLARE _free_atomic\n  TYPE ProdType (ConstType val) (ArrowType (ConstType Z) Mpred)\n  WITH p : val, R : Z -> mpred\n  PRE [ _tgt OF tptr tatomic ]\n   PROP ()\n   LOCAL (temp _tgt p)\n   SEP (atomic_loc Tsh p R)\n  POST [ tint ]\n   EX v : Z,\n   PROP (repable_signed v)\n   LOCAL (temp ret_temp (vint v))\n   SEP (R v).\nNext Obligation.\nProof.\n  replace _ with (fun (_ : list Type) (x : val * (Z -> mpred)) rho =>\n    PROP () LOCAL (let '(p, R) := x in temp _tgt p)\n    SEP (let '(p, R) := x in atomic_loc Tsh p R) rho).\n  apply (PROP_LOCAL_SEP_super_non_expansive (ProdType (ConstType val) (ArrowType (ConstType Z) Mpred)) []\n    [fun _ x => let '(p, R) := x in _] [fun _ x => let '(p, R) := x in _]);\n    repeat constructor; hnf; intros; destruct x as (p, R); [auto|].\n  - apply atomic_loc_super_non_expansive.\n  - extensionality ts x rho.\n    destruct x; auto.\nQed.\nNext Obligation.\nProof.\n  replace _ with (fun (_ : list Type) (x : val * (Z -> mpred)) rho =>\n    EX v : Z, PROP (let '(p, R) := x in repable_signed v)\n      LOCAL (let '(p, R) := x in temp ret_temp (vint v)) SEP (let '(p, R) := x in R v) rho).\n  - repeat intro.\n    rewrite !approx_exp; apply f_equal; extensionality v.\n    apply (PROP_LOCAL_SEP_super_non_expansive (ProdType (ConstType val) (ArrowType (ConstType Z) Mpred))\n      [fun ts x => let '(p, R) := x in _] [fun ts x => let '(p, R) := x in _]\n      [fun ts x => let '(p, R) := x in _]); repeat constructor; hnf; intros;\n      destruct x0 as (p, R); auto; simpl.\n    rewrite approx_idem; auto.\n  - extensionality ts x rho.\n    destruct x; auto.\nQed.\n\nDefinition AL_spec P (R : Z -> mpred) Q := forall vx, repable_signed vx -> view_shift (R vx * P) (R vx * Q vx).\n\nDefinition AL_type := ProdType (ProdType (ProdType (ConstType (share * val))\n  Mpred) (ArrowType (ConstType Z) Mpred)) (ArrowType (ConstType Z) Mpred).\n\nNotation \"'TYPE' A 'WITH'  x1 : t1 , x2 : t2 , x3 : t3 , x4 : t4 , x5 : t5 'PRE'  [ u , .. , v ] P 'POST' [ tz ] Q\" :=\n     (mk_funspec ((cons u%formals .. (cons v%formals nil) ..), tz) cc_default A\n  (fun (ts: list Type) (x: t1*t2*t3*t4*t5) =>\n     match x with (x1,x2,x3,x4,x5) => P%assert end)\n  (fun (ts: list Type) (x: t1*t2*t3*t4*t5) =>\n     match x with (x1,x2,x3,x4,x5) => Q%assert end) _ _)\n            (at level 200, x1 at level 0, x2 at level 0, x3 at level 0, x4 at level 0,\n             x5 at level 0,\n             P at level 100, Q at level 100).\n\n(* One obvious restriction on this rule that might be needed for soundness (but maybe not for SC?) is that\n   the footprint of P be empty, and vice versa for store. *)\n(* For this to work with load_acquire, Q needs to be somehow future-proof: it should be okay even if v wasn't\n   actually the latest value of tgt. For instance, Q might only get a history that's some prefix of the\n   latest state. *)\nProgram Definition load_SC_spec := DECLARE _load_SC TYPE AL_type\n  WITH sh : share, tgt : val, P : mpred, R : Z -> mpred, Q : Z -> mpred\n  PRE [ _tgt OF tptr tatomic ]\n   PROP (AL_spec P R Q; readable_share sh)\n   LOCAL (temp _tgt tgt)\n   SEP (atomic_loc sh tgt R; P)\n  POST [ tint ]\n   EX v : Z,\n   PROP (repable_signed v)\n   LOCAL (temp ret_temp (vint v))\n   SEP (atomic_loc sh tgt R; Q v).\nNext Obligation.\nProof.\n  replace _ with (fun (_ : list Type) (x : share * val * mpred * (Z -> mpred) * (Z -> mpred)) rho =>\n    PROP (let '(sh, tgt, P, R, Q) := x in AL_spec P R Q /\\ readable_share sh)\n    LOCAL (let '(sh, tgt, P, R, Q) := x in temp _tgt tgt)\n    SEP (let '(sh, tgt, P, R, Q) := x in atomic_loc sh tgt R * P) rho).\n  apply (PROP_LOCAL_SEP_super_non_expansive AL_type [fun _ => _] [fun _ => _] [fun _ => _]);\n    repeat constructor; hnf; intros; destruct x as ((((?, ?), P), R), Q); auto; simpl.\n  - rewrite !prop_and, !approx_andp; f_equal.\n    unfold AL_spec.\n    rewrite !prop_forall, !(approx_allp _ _ _ 0); apply f_equal; extensionality vx.\n    rewrite !prop_impl.\n    setoid_rewrite approx_imp at 1.\n    setoid_rewrite approx_imp at 2.\n    rewrite view_shift_super_non_expansive.\n    rewrite !approx_sepcon; auto.\n  - rewrite !approx_sepcon, approx_idem, atomic_loc_super_non_expansive; auto.\n  - extensionality ts x rho.\n    destruct x as ((((?, ?), P), R), Q).\n    unfold PROPx, SEPx; simpl; rewrite !sepcon_assoc; f_equal.\n    apply f_equal; apply prop_ext; tauto.\nQed.\nNext Obligation.\nProof.\n  replace _ with (fun (_ : list Type) (x : share * val * mpred * (Z -> mpred) * (Z -> mpred)) rho =>\n    EX v : Z,\n      PROP (let '(sh, tgt, P, R, Q) := x in repable_signed v)\n      LOCAL (let '(sh, tgt, P, R, Q) := x in temp ret_temp (vint v))\n      SEP (let '(sh, tgt, P, R, Q) := x in atomic_loc sh tgt R * Q v) rho).\n  - repeat intro.\n    rewrite !approx_exp; apply f_equal; extensionality v.\n    apply (PROP_LOCAL_SEP_super_non_expansive AL_type [fun ts x => let '(sh, tgt, P, R, Q) := x in _]\n      [fun ts x => let '(sh, tgt, P, R, Q) := x in _] [fun ts x => let '(sh, tgt, P, R, Q) := x in _]);\n      repeat constructor; hnf; intros; destruct x0 as ((((?, ?), P), R), Q); auto; simpl.\n    rewrite !approx_sepcon, approx_idem, atomic_loc_super_non_expansive; auto.\n  - extensionality ts x rho.\n    destruct x as ((((?, ?), P), R), Q); auto.\n    apply f_equal; extensionality.\n    unfold SEPx; simpl; rewrite !sepcon_assoc; auto.\nQed.\n\nNotation \"'TYPE' A 'WITH'  x1 : t1 , x2 : t2 , x3 : t3 , x4 : t4 , x5 : t5 , x6 : t6 'PRE'  [ u , .. , v ] P 'POST' [ tz ] Q\" :=\n     (mk_funspec ((cons u%formals .. (cons v%formals nil) ..), tz) cc_default A\n  (fun (ts: list Type) (x: t1*t2*t3*t4*t5*t6) =>\n     match x with (x1,x2,x3,x4,x5,x6) => P%assert end)\n  (fun (ts: list Type) (x: t1*t2*t3*t4*t5*t6) =>\n     match x with (x1,x2,x3,x4,x5,x6) => Q%assert end) _ _)\n            (at level 200, x1 at level 0, x2 at level 0, x3 at level 0, x4 at level 0, \n             x5 at level 0, x6 at level 0,\n             P at level 100, Q at level 100).\n\nDefinition AS_spec v P (R : Z -> mpred) Q := forall vx, repable_signed vx ->\n  view_shift (R vx * P)\n  (R v * (weak_precise_mpred (R v) && emp) * Q).\n\nDefinition AS_type := ProdType (ProdType (ProdType\n  (ConstType (share * val * Z)) Mpred) (ArrowType (ConstType Z) Mpred)) Mpred.\n\nProgram Definition store_SC_spec := DECLARE _store_SC\n  TYPE AS_type WITH sh : share, tgt : val, v : Z, P : mpred, R : Z -> mpred, Q : mpred\n  PRE [ _tgt OF tptr tatomic, _v OF tint ]\n   PROP (AS_spec v P R Q; readable_share sh; repable_signed v)\n   LOCAL (temp _tgt tgt; temp _v (vint v))\n   SEP (atomic_loc sh tgt R; P)\n  POST [ tvoid ]\n   PROP ()\n   LOCAL ()\n   SEP (atomic_loc sh tgt R; Q).\nNext Obligation.\nProof.\n  replace _ with (fun (_ : list Type) (x : share * val * Z * mpred * (Z -> mpred) * mpred) rho =>\n    PROP (let '(sh, tgt, v, P, R, Q) := x in AS_spec v P R Q /\\ readable_share sh /\\ repable_signed v)\n    LOCAL (let '(sh, tgt, v, P, R, Q) := x in temp _tgt tgt; let '(sh, tgt, v, P, R, Q) := x in temp _v (vint v))\n    SEP (let '(sh, tgt, v, P, R, Q) := x in atomic_loc sh tgt R * P) rho).\n  apply (PROP_LOCAL_SEP_super_non_expansive AS_type [fun _ => _] [fun _ => _; fun _ => _] [fun _ => _]);\n    repeat constructor; hnf; intros; destruct x as (((((?, ?), ?), P), R), Q); auto; simpl.\n  - rewrite !prop_and, !approx_andp; f_equal.\n    unfold AS_spec.\n    rewrite !prop_forall, !(approx_allp _ _ _ 0); apply f_equal; extensionality vx.\n    rewrite !prop_impl.\n    setoid_rewrite approx_imp at 1.\n    setoid_rewrite approx_imp at 2.\n    rewrite view_shift_super_non_expansive.\n    setoid_rewrite view_shift_super_non_expansive at 2.\n    rewrite !approx_sepcon, !approx_andp, !approx_idem.\n    rewrite (nonexpansive_super_non_expansive weak_precise_mpred) by (apply precise_mpred_nonexpansive); auto.\n  - rewrite !approx_sepcon, approx_idem, atomic_loc_super_non_expansive; auto.\n  - extensionality ts x rho.\n    destruct x as (((((?, ?), ?), P), R), Q).\n    unfold PROPx, SEPx; simpl; rewrite !sepcon_assoc; f_equal.\n    apply f_equal; apply prop_ext; tauto.\nQed.\nNext Obligation.\nProof.\n  replace _ with (fun (_ : list Type) (x : share * val * Z * mpred * (Z -> mpred) * mpred) rho =>\n    PROP () LOCAL () SEP (let '(sh, tgt, v, P, R, Q) := x in atomic_loc sh tgt R * Q) rho).\n  - repeat intro.\n    apply (PROP_LOCAL_SEP_super_non_expansive AS_type [] [] [fun ts x => let '(sh, tgt, v, P, R, Q) := x in _]);\n      repeat constructor; hnf; intros; destruct x0 as (((((?, ?), ?), P), R), Q); auto; simpl.\n    rewrite !approx_sepcon, approx_idem, atomic_loc_super_non_expansive; auto.\n  - extensionality ts x rho.\n    destruct x as (((((?, ?), ?), P), R), Q); auto.\n    unfold SEPx; simpl; rewrite !sepcon_assoc; auto.\nQed.\n\nNotation \"'TYPE' A 'WITH'  x1 : t1 , x2 : t2 , x3 : t3 , x4 : t4 , x5 : t5 , x6 : t6 , x7 : t7 'PRE'  [ u , .. , v ] P 'POST' [ tz ] Q\" :=\n     (mk_funspec ((cons u%formals .. (cons v%formals nil) ..), tz) cc_default A\n  (fun (ts: list Type) (x: t1*t2*t3*t4*t5*t6*t7) =>\n     match x with (x1,x2,x3,x4,x5,x6,x7) => P%assert end)\n  (fun (ts: list Type) (x: t1*t2*t3*t4*t5*t6*t7) =>\n     match x with (x1,x2,x3,x4,x5,x6,x7) => Q%assert end) _ _)\n            (at level 200, x1 at level 0, x2 at level 0, x3 at level 0, x4 at level 0,\n             x5 at level 0, x6 at level 0, x7 at level 0,\n             P at level 100, Q at level 100).\n\nDefinition ACAS_spec c v P (R Q : Z -> mpred) := forall vx, repable_signed vx ->\n  view_shift (R vx * P)\n  (R (if eq_dec c vx then v else vx) * (weak_precise_mpred (R (if eq_dec c vx then v else vx)) && emp) * Q vx).\n\nDefinition ACAS_type := ProdType (ProdType (ProdType\n  (ConstType (share * val * Z * Z)) Mpred)\n  (ArrowType (ConstType Z) Mpred))\n  (ArrowType (ConstType Z) Mpred).\n\nProgram Definition CAS_SC_spec := DECLARE _CAS_SC\n  TYPE ACAS_type WITH sh : share, tgt : val, c : Z, v : Z, P : mpred, R : Z -> mpred, Q : Z -> mpred\n  PRE [ _tgt OF tptr tatomic, _c OF tint, _v OF tint ]\n   PROP (ACAS_spec c v P R Q; readable_share sh; repable_signed c; repable_signed v)\n   LOCAL (temp _tgt tgt; temp _c (vint c); temp _v (vint v))\n   SEP (atomic_loc sh tgt R; P)\n  POST [ tint ]\n   EX v' : Z,\n   PROP (repable_signed v')\n   LOCAL (temp ret_temp (if eq_dec c v' then vint 1 else vint 0))\n   SEP (atomic_loc sh tgt R; Q v').\nNext Obligation.\nProof.\n  replace _ with (fun (_ : list Type) (x : share * val * Z * Z * mpred * (Z -> mpred) * (Z -> mpred)) rho =>\n    PROP (let '(sh, tgt, c, v, P, R, Q) := x in ACAS_spec c v P R Q /\\ readable_share sh /\\ repable_signed c /\\\n      repable_signed v)\n    LOCAL (let '(sh, tgt, c, v, P, R, Q) := x in temp _tgt tgt;\n           let '(sh, tgt, c, v, P, R, Q) := x in temp _c (vint c);\n           let '(sh, tgt, c, v, P, R, Q) := x in temp _v (vint v))\n    SEP (let '(sh, tgt, c, v, P, R, Q) := x in atomic_loc sh tgt R * P) rho).\n  apply (PROP_LOCAL_SEP_super_non_expansive ACAS_type [fun _ => _] [fun _ => _; fun _ => _; fun _ => _]\n    [fun _ => _]); repeat constructor; hnf; intros; destruct x as ((((((?, ?), ?), ?), P), R), Q); auto; simpl.\n  - rewrite !prop_and, !approx_andp; f_equal.\n    unfold ACAS_spec.\n    rewrite !prop_forall, !(approx_allp _ _ _ 0); apply f_equal; extensionality vx.\n    rewrite !prop_impl.\n    setoid_rewrite approx_imp at 1.\n    setoid_rewrite approx_imp at 2.\n    rewrite view_shift_super_non_expansive.\n    setoid_rewrite view_shift_super_non_expansive at 2.\n    rewrite !approx_sepcon, !approx_andp, !approx_idem.\n    rewrite (nonexpansive_super_non_expansive weak_precise_mpred) by (apply precise_mpred_nonexpansive); auto.\n  - rewrite !approx_sepcon, approx_idem, atomic_loc_super_non_expansive; auto.\n  - extensionality ts x rho.\n    destruct x as ((((((?, ?), ?), ?), P), R), Q).\n    unfold PROPx, SEPx; simpl; rewrite !sepcon_assoc; f_equal.\n    apply f_equal; apply prop_ext; tauto.\nQed.\nNext Obligation.\nProof.\n  replace _ with (fun (_ : list Type) (x : share * val * Z * Z * mpred * (Z -> mpred) * (Z -> mpred)) rho =>\n    EX v' : Z,\n      PROP (let '(sh, tgt, c, v, P, R, Q) := x in repable_signed v')\n      LOCAL (let '(sh, tgt, c, v, P, R, Q) := x in temp ret_temp (if eq_dec c v' then vint 1 else vint 0))\n      SEP (let '(sh, tgt, c, v, P, R, Q) := x in atomic_loc sh tgt R * Q v') rho).\n  - repeat intro.\n    rewrite !approx_exp; apply f_equal; extensionality v'.\n    apply (PROP_LOCAL_SEP_super_non_expansive ACAS_type [fun ts x => let '(sh, tgt, c, v, P, R, Q) := x in _]\n      [fun ts x => let '(sh, tgt, c, v, P, R, Q) := x in _] [fun ts x => let '(sh, tgt, c, v, P, R, Q) := x in _]);\n    repeat constructor; hnf; intros; destruct x0 as ((((((?, ?), ?), ?), P), R), Q); auto; simpl.\n    rewrite !approx_sepcon, approx_idem, atomic_loc_super_non_expansive; auto.\n  - extensionality ts x rho.\n    destruct x as ((((((?, ?), ?), ?), P), R), Q); auto.\n    apply f_equal; extensionality.\n    unfold SEPx; simpl; rewrite !sepcon_assoc; auto.\nQed.\n\nDefinition Gprog : funspecs := ltac:(with_library prog [acquire_spec; release_spec; makelock_spec; freelock_spec;\n  surely_malloc_spec; make_atomic_spec; free_atomic_spec; load_SC_spec; store_SC_spec; CAS_SC_spec]).\n\nLemma body_surely_malloc: semax_body Vprog Gprog f_surely_malloc surely_malloc_spec.\nProof.\n  start_function.\n  forward_call n.\n  Intros p.\n  forward_if\n  (PROP ( )\n   LOCAL (temp _p p)\n   SEP (malloc_token Tsh n p * memory_block Tsh n p)).\n  - if_tac; entailer!.\n  - forward_call tt.\n    contradiction.\n  - if_tac.\n    + forward. subst p. discriminate.\n    + Intros. forward. entailer!.\n  - forward. Exists p; entailer!.\nQed.\n\nLemma A_inv_positive : forall x l R, positive_mpred (A_inv x l R).\nProof.\n  unfold A_inv; intros.\n  apply ex_positive; intro.\n  apply positive_andp2; repeat apply positive_sepcon1.\n  apply positive_andp2; unfold at_offset; rewrite data_at_rec_eq; simpl; auto.\nQed.\nHint Resolve A_inv_positive.\n\nLemma A_inv_precise : forall x l R,\n  predicates_hered.derives TT (weak_precise_mpred (A_inv x l R)).\nProof.\n  intros ??? rho _ ???\n    (? & v1 & ? & ? & ? & Hj1 & (? & ? & Hj'1 & (? & ? & Hj''1 & (? & r1 & Hj'''1 &\n      (? & Hv1) & Hr1) & HR & Hemp1) & Hma1) & Hml1)\n    (? & v2 & ? & ? & ? & Hj2 & (? & ? & Hj'2 & (? & ? & Hj''2 & (? & r2 & Hj'''2 &\n      (? & Hv2) & Hr2) & _ & Hemp2) & Hma2) & Hml2)\n    Hw1 Hw2.\n  unfold at_offset in *; simpl in *; rewrite data_at_rec_eq in Hv1, Hv2; simpl in *.\n  exploit (malloc_token_precise _ _ _ w _ _ Hma1 Hma2); try join_sub; intro; subst.\n  exploit (malloc_token_precise _ _ _ w _ _ Hml1 Hml2); try join_sub; intro; subst.\n  assert (readable_share Tsh) as Hsh by auto.\n  exploit (mapsto_inj _ _ _ _ _ _ _ w Hsh Hv1 Hv2); auto; try join_sub; unfold unfold_reptype; simpl; try discriminate.\n  intros (? & ?); subst.\n  assert (v1 = v2) by (apply repr_inj_signed; auto; congruence); subst.\n  pose proof (juicy_mem.rmap_join_sub_eq_level _ _ Hw1);\n    pose proof (juicy_mem.rmap_join_sub_eq_level _ _ Hw2).\n  destruct (age_sepalg.join_level _ _ _ Hj1), (age_sepalg.join_level _ _ _ Hj2),\n    (age_sepalg.join_level _ _ _ Hj'1), (age_sepalg.join_level _ _ _ Hj'2),\n    (age_sepalg.join_level _ _ _ Hj''1), (age_sepalg.join_level _ _ _ Hj''2),\n    (age_sepalg.join_level _ _ _ Hj'''1), (age_sepalg.join_level _ _ _ Hj'''2).\n  exploit (HR w r1 r2); try (split; auto; omega); try join_sub.\n  intro; subst; join_inj.\n  apply sepalg.join_comm in Hj''1; apply sepalg.join_comm in Hj''2.\n  match goal with H1 : predicates_hered.app_pred emp ?a,\n    H2 : predicates_hered.app_pred emp ?b |- _ => assert (a = b);\n      [eapply sepalg.same_identity; auto;\n        [match goal with H : sepalg.join a ?x ?y |- _ =>\n           specialize (Hemp1 _ _ H); instantiate (1 := x); subst; auto end |\n         match goal with H : sepalg.join b ?x ?y |- _ =>\n           specialize (Hemp2 _ _ H); subst; auto end] | subst] end.\n  join_inj.\nQed.\n\nLemma body_make_atomic : semax_body Vprog Gprog f_make_atomic make_atomic_spec.\nProof.\n  start_dep_function.\n  simpl; destruct ts as (((i, P), R), Q).\n  forward_call (sizeof tatomic).\n  { simpl; computable. }\n  Intros p.\n  rewrite malloc_compat; auto; Intros.\n  rewrite memory_block_data_at_; auto.\n  forward_call (sizeof tlock).\n  { simpl; computable. }\n  Intros l.\n  rewrite malloc_compat; auto; Intros.\n  rewrite memory_block_data_at_; auto.\n  forward.\n  forward.\n  forward_call (l, Tsh, A_inv p l R).\n  focus_SEP 4; apply H.\n  forward_call (l, Tsh, A_inv p l R).\n  { rewrite ?sepcon_assoc; rewrite <- sepcon_emp at 1; rewrite sepcon_comm; apply sepcon_derives;\n      [repeat apply andp_right; auto; eapply derives_trans; try apply positive_weak_positive; auto|].\n    { apply A_inv_precise; auto. }\n    unfold A_inv.\n    unfold_field_at 1%nat.\n    Exists i; simpl; entailer!. }\n  forward.\n  unfold atomic_loc.\n  Exists p l; entailer!.\n  { exists 2; auto. }\n  { exists 2; auto. }\nQed.\n\nLemma body_free_atomic : semax_body Vprog Gprog f_free_atomic free_atomic_spec.\nProof.\n  start_dep_function.\n  simpl; destruct ts as (p, R).\n  unfold atomic_loc; Intros l.\n  rewrite lock_inv_isptr; Intros.\n  forward.\n  forward_call (l, Tsh, A_inv p l R).\n  forward_call (l, Tsh, A_inv p l R).\n  { rewrite <- emp_sepcon at 1; apply sepcon_derives; [|cancel].\n    apply andp_right; auto; apply andp_right.\n    - eapply derives_trans, A_inv_precise; auto.\n    - eapply derives_trans, positive_weak_positive, A_inv_positive; auto. }\n  unfold A_inv; Intros v.\n  forward_call (l, sizeof tlock).\n  { rewrite data_at__memory_block; entailer!. }\n  forward.\n  gather_SEP 0 4.\n  forward_call (p, sizeof tatomic).\n  { rewrite sepcon_assoc.\n    apply sepcon_derives; [|cancel].\n    eapply derives_trans; [apply sepcon_derives; apply field_at_field_at_|].\n    rewrite !field_at__memory_block; simpl.\n    rewrite !field_compatible_field_address by (rewrite field_compatible_cons; unfold in_members; simpl; auto); simpl.\n    replace 8 with (4 + 4) by omega.\n    exploit field_compatible_isptr; eauto; intro.\n    destruct p; try contradiction.\n    rewrite <- (Int.repr_unsigned i), memory_block_split; try computable.\n    simpl; entailer!.\n    { match goal with H : field_compatible _ _ _ |- _ => destruct H as (? & ? & ? & ? & ? & Hsize & ?) end.\n      pose proof (Int.unsigned_range i).\n      simpl in Hsize; omega. } }\n  forward.\n  Exists v; entailer!.\n  apply andp_left2; auto.\nQed.\n\nLemma body_load_SC : semax_body Vprog Gprog f_load_SC load_SC_spec.\nProof.\n  start_dep_function.\n  simpl; destruct ts as ((((sh, tgt), P), R), Q).\n  unfold atomic_loc.\n  Intros l.\n  rewrite lock_inv_isptr; Intros.\n  forward.\n  forward_call (l, sh, A_inv tgt l R).\n  unfold A_inv at 2; Intros v.\n  forward.\n  gather_SEP 2 7; apply H; auto.\n  forward_call (l, sh, A_inv tgt l R).\n  { rewrite ?sepcon_assoc; rewrite <- sepcon_emp at 1; rewrite sepcon_comm; apply sepcon_derives;\n      [repeat apply andp_right; auto; eapply derives_trans; try apply positive_weak_positive; auto|].\n    { apply A_inv_precise; auto. }\n    unfold A_inv.\n    Exists v; simpl; entailer!. }\n  forward.\n  Exists v; unfold atomic_loc; Exists l; entailer!.\nQed.\n\nLemma body_store_SC : semax_body Vprog Gprog f_store_SC store_SC_spec.\nProof.\n  start_dep_function.\n  simpl; destruct ts as (((((sh, tgt), v), P), R), Q).\n  unfold atomic_loc.\n  Intros l.\n  rewrite lock_inv_isptr; Intros.\n  forward.\n  forward_call (l, sh, A_inv tgt l R).\n  unfold A_inv at 2; Intros v'.\n  forward.\n  gather_SEP 2 7; apply H; auto.\n  forward_call (l, sh, A_inv tgt l R).\n  { rewrite ?sepcon_assoc; rewrite <- sepcon_emp at 1; rewrite sepcon_comm; apply sepcon_derives;\n      [repeat apply andp_right; auto; eapply derives_trans; try apply positive_weak_positive; auto|].\n    { apply A_inv_precise; auto. }\n    unfold A_inv.\n    Exists v; simpl; entailer!. }\n  forward.\n  unfold atomic_loc; Exists l; entailer!.\n  apply andp_left2; auto.\nQed.\n\nLemma body_CAS_SC : semax_body Vprog Gprog f_CAS_SC CAS_SC_spec.\nProof.\n  start_dep_function.\n  simpl; destruct ts as ((((((sh, tgt), c), v), P), R), Q).\n  unfold atomic_loc.\n  Intros l.\n  rewrite lock_inv_isptr; Intros.\n  forward.\n  forward_call (l, sh, A_inv tgt l R).\n  unfold A_inv at 2; Intros v'.\n  forward.\n  focus_SEP 1.\n  match goal with |- semax _ (PROP () (LOCALx (temp _x (vint v') :: ?Q)\n    (SEPx (field_at Tsh tatomic ?f (vint v') tgt :: ?R)))) _ _ =>\n    forward_if (PROP ( ) (LOCALx (temp _x (if eq_dec c v' then vint 1 else vint 0) :: Q)\n               (SEPx (field_at Tsh tatomic f (vint (if eq_dec c v' then v else v')) tgt :: R)))) end.\n  { forward.\n    forward.\n    subst; rewrite !eq_dec_refl; entailer!. }\n  { forward.\n    if_tac; [absurd (c = v'); auto|].\n    entailer!. }\n  gather_SEP 2 7; apply H; auto.\n  forward_call (l, sh, A_inv tgt l R).\n  { rewrite ?sepcon_assoc; rewrite <- sepcon_emp at 1; rewrite sepcon_comm; apply sepcon_derives;\n      [repeat apply andp_right; auto; eapply derives_trans; try apply positive_weak_positive; auto|].\n    { apply A_inv_precise; auto. }\n    unfold A_inv.\n    Exists (if eq_dec c v' then v else v'); entailer!.\n    if_tac; auto. }\n  forward.\n  Exists v'; unfold atomic_loc; Exists l; entailer!.\n  apply andp_left2; auto.\nQed.\n\nLemma atomic_loc_isptr : forall sh p R, atomic_loc sh p R = !!isptr p && atomic_loc sh p R.\nProof.\n  intros; eapply local_facts_isptr with (P := fun p => atomic_loc sh p R); eauto.\n  unfold atomic_loc; entailer!.\nQed.\nHint Resolve atomic_loc_isptr : saturate_local.\n\nLemma atomic_loc_precise : forall sh p R, readable_share sh -> precise (atomic_loc sh p R).\nProof.\n  intros; unfold atomic_loc.\n  intros ??? (? & l1 & r1 & r1' & ? & (? & Hl1) & ?) (? & l2 & r2 & r2' & ? & (? & Hl2) & ?) ??.\n  unfold at_offset in *.\n  rewrite data_at_rec_eq in Hl1, Hl2; simpl in *.\n  unfold unfold_reptype in *; simpl in *.\n  rewrite lock_inv_isptr in *; repeat match goal with H : predicates_hered.app_pred (!!_ && _) _ |- _ =>\n    destruct H end.\n  exploit (mapsto_inj sh (tptr (Tstruct sim_atomics._lock_t noattr)) l1 l2 (offset_val 4 p) r1 r2 w);\n    auto; try join_sub.\n  { intro; subst; contradiction. }\n  { intro; subst; contradiction. }\n  intros (? & ?); subst.\n  assert (r1' = r2').\n  { eapply lock_inv_precise; eauto; join_sub. }\n  subst; join_inj.\nQed.\n\nLemma atomic_loc_join : forall sh1 sh2 sh p R (Hjoin : sepalg.join sh1 sh2 sh)\n  (Hsh1 : readable_share sh1) (Hsh2 : readable_share sh2),\n  atomic_loc sh1 p R * atomic_loc sh2 p R = atomic_loc sh p R.\nProof.\n  intros; unfold atomic_loc.\n  rewrite sepcon_andp_prop', sepcon_andp_prop.\n  rewrite <- andp_assoc, andp_dup.\n  apply f_equal.\n  apply mpred_ext.\n  - Intros l1 l2.\n    match goal with |- (?P1 * ?Q1) * (?P2 * ?Q2) |-- _ =>\n      apply derives_trans with (Q := (Q1 * Q2) * (P1 * P2)); [cancel|] end.\n    rewrite (lock_inv_isptr sh1), (lock_inv_isptr sh2); Intros.\n    unfold field_at, at_offset; Intros.\n    rewrite !data_at_rec_eq; unfold unfold_reptype; simpl.\n    rewrite sepcon_comm.\n    assert_PROP (l1 = l2) by (apply sepcon_derives_prop, mapsto_value_eq; auto; intro; subst; contradiction).\n    Exists l1; subst.\n    erewrite mapsto_share_join, lock_inv_share_join; eauto; entailer!.\n  - Intros l; Exists l l.\n    erewrite <- field_at_share_join, <- (lock_inv_share_join sh1 sh2); eauto; cancel.\nQed.\n\n(* Now, we can specialize these to the history PCM. *)\nInductive hist_el := Load (v : val) | Store (v : val) | CAS (r : val) (c : val) (w : val).\n\nInstance EqDec_hist_el : EqDec hist_el.\nProof.\n  unfold EqDec; decide equality; apply EqDec_val.\nQed.\n\nFixpoint apply_hist a h :=\n  match h with\n  | [] => Some a\n  | Load v :: h' => if eq_dec v a then apply_hist a h' else None\n  | Store v :: h' => apply_hist v h'\n  | CAS r c w :: h' => if eq_dec r a then if eq_dec c a then apply_hist w h' else apply_hist a h' else None\n  end.\n\nNotation hist := (list (nat * hist_el)).\n\nLemma apply_hist_app : forall h1 i h2, apply_hist i (h1 ++ h2) =\n  match apply_hist i h1 with Some v => apply_hist v h2 | None => None end.\nProof.\n  induction h1; auto; simpl; intros.\n  destruct a; auto.\n  - destruct (eq_dec v i); auto.\n  - destruct (eq_dec r i); auto.\n    destruct (eq_dec c i); auto.\nQed.\n\nDefinition writes e v :=\n  match e with\n  | Load _ => False\n  | Store v' => v' = v\n  | CAS r c v' => r = c /\\ v' = v\n  end.\n\nLemma change_implies_write : forall v h i, apply_hist i h = Some v -> v <> i ->\n  exists e, In e h /\\ writes e v.\nProof.\n  induction h; simpl; intros.\n  - inv H; contradiction.\n  - destruct a.\n    + destruct (eq_dec v0 i); [|discriminate].\n      exploit IHh; eauto; intros (? & ? & ?); eauto.\n    + destruct (eq_dec v v0).\n      * subst; do 2 eexists; eauto; simpl; auto.\n      * exploit IHh; eauto; intros (? & ? & ?); eauto.\n    + destruct (eq_dec r i); [|discriminate].\n      destruct (eq_dec c i).\n      * destruct (eq_dec v w); [subst; do 2 eexists; eauto; simpl; auto|].\n        exploit IHh; eauto; intros (? & ? & ?); eauto.\n      * exploit IHh; eauto; intros (? & ? & ?); eauto.\nQed.\n\nDefinition value_of e :=\n  match e with\n  | Load v => v\n  | Store v => v\n  | CAS r c w => if eq_dec r c then w else r\n  end.\n\nLemma apply_one_value : forall i a v, apply_hist i [a] = Some v -> value_of a = v.\nProof.\n  destruct a; simpl; intros.\n  - destruct (eq_dec v i); inv H; auto.\n  - inv H; auto.\n  - destruct (eq_dec r i); [|discriminate].\n    destruct (eq_dec c i); inv H.\n    + rewrite eq_dec_refl; auto.\n    + destruct (eq_dec v c); auto; contradiction n; auto.\nQed.\n\nDefinition last_value (h : hist) v :=\n  (* initial condition *)\n  (h = [] /\\ v = vint 0) \\/\n  exists n e, In (n, e) h /\\ value_of e = v /\\ Forall (fun x => let '(m, _) := x in m <= n)%nat h.\n\nLemma last_value_new : forall h n e, newer h n ->\n  last_value (h ++ [(n, e)]) (value_of e).\nProof.\n  right.\n  do 3 eexists; [rewrite in_app; simpl; eauto|].\n  rewrite Forall_app; repeat constructor.\n  eapply Forall_impl; [|eauto]; intros.\n  destruct a; simpl in *; omega.\nQed.\n\nDefinition value_of_hist (h : hist) := value_of (snd (last h (O, Store (vint 0)))).\n\nLemma value_of_hist_snoc : forall h t e, value_of_hist (h ++ [(t, e)]) = value_of e.\nProof.\n  intros; unfold value_of_hist; rewrite last_snoc; auto.\nQed.\n\nNotation ordered_hist := (ordered_hist (Store (vint 0))).\n\nLemma ordered_last_value : forall h v (Hordered : ordered_hist h), last_value h v <-> value_of_hist h = v.\nProof.\n  unfold last_value, value_of_hist; split; intro.\n  - destruct H as [(? & ?) | (? & ? & ? & ? & ?)]; subst; auto.\n    erewrite ordered_last; eauto; auto.\n  - destruct h; [auto | right].\n    destruct (last (p :: h) (O, Store (vint 0))) as (t, e) eqn: Hlast.\n    exploit (@app_removelast_last _ (p :: h)); [discriminate | intro Heq].\n    rewrite Hlast in Heq.\n    exists t; exists e; repeat split; auto.\n    + rewrite Heq, in_app; simpl; auto.\n    + unfold ordered_hist in Hordered.\n      rewrite Forall_forall; intros (?, ?) Hin.\n      apply In_Znth with (d := (O, Store (vint 0))) in Hin.\n      destruct Hin as (i & ? & Hi).\n      rewrite <- Znth_last in Hlast.\n      destruct (eq_dec i (Zlength (p :: h) - 1)).\n      * subst; rewrite Hlast in Hi; inv Hi; auto.\n      * exploit (Hordered i (Zlength (p :: h) - 1)); try omega.\n        rewrite Hlast, Hi; simpl; omega.\nQed.\n\nLemma hist_list_value : forall h l v (Horder : ordered_hist h) (Hl : hist_list h l)\n  (Hv : apply_hist (vint 0) l = Some v), value_of_hist h = v.\nProof.\n  intros.\n  destruct Hl as (Hd & Hl).\n  destruct (eq_dec (Zlength l) 0).\n  { apply Zlength_nil_inv in e; subst; inv Hv.\n    destruct h as [|(t, e)]; auto.\n    specialize (Hl t e); rewrite nth_error_nil in Hl; simpl in Hl.\n    destruct Hl as (Hl & _); exploit Hl; [auto | discriminate]. }\n  assert (l <> []) by (intro; subst; contradiction).\n  pose proof (Hl (length l - 1)%nat (last l (Store (vint 0)))) as Hlast.\n  assert (length l > 0)%nat by (destruct l; [contradiction | simpl; omega]).\n  erewrite nth_error_nth, nth_last in Hlast by omega.\n  destruct Hlast as (_ & Hlast); exploit Hlast; eauto.\n  intro Hin; unfold value_of_hist.\n  rewrite app_removelast_last with (l := l)(d := Store (vint 0)), apply_hist_app in Hv by auto.\n  destruct (apply_hist (vint 0) (removelast l)) eqn: Hh; [|discriminate].\n  apply apply_one_value in Hv.\n  assert (hist_list h l) as Hlist by (split; auto).\n  pose proof (hist_list_length _ _ Hlist) as Hlen.\n  erewrite <- Znth_last, ordered_hist_list; eauto; simpl; rewrite Hlen.\n  rewrite Znth_last; eauto.\n  { pose proof (Zlength_nonneg h); omega. }\nQed.\n\nDefinition full_hist h v := exists l, hist_list h l /\\ apply_hist (vint 0) l = Some (vint v).\n\nDefinition full_hist' h v := exists l, hist_list' h l /\\ apply_hist (vint 0) l = Some v.\n\nLemma full_hist_weak : forall h v (Hl : full_hist h v), full_hist' h (vint v).\nProof.\n  intros ?? (l & ? & ?); exists l; split; auto.\n  apply hist_list_weak; auto.\nQed.\n\nLemma full_hist'_drop : forall h h' v (Hh : full_hist' h v)\n  (Hh' : incl h' h) (HNoDup : NoDup (map fst h'))\n  (Hdiff : forall t e, In (t, e) h -> ~In (t, e) h' -> forall v, ~writes e v),\n  full_hist' h' v.\nProof.\n  intros ??? (l & Hl & Hv) ?.\n  revert dependent h'; revert dependent v; revert dependent h; induction l using rev_ind; intros.\n  - inv Hl; simpl in *.\n    destruct h'.\n    exists []; auto.\n    { specialize (Hh' p); simpl in Hh'; contradiction Hh'; auto. }\n    { exploit app_cons_not_nil; [symmetry; eauto | contradiction]. }\n  - pose proof (hist_list'_NoDup _ _ Hl) as Hh.\n    inv Hl.\n    { exploit app_cons_not_nil; [symmetry; eauto | contradiction]. }\n    apply app_inj_tail in H1; destruct H1; subst.\n    rewrite map_app in Hh; simpl in Hh; apply NoDup_remove in Hh; rewrite <- map_app in Hh.\n    rewrite apply_hist_app in Hv.\n    destruct (apply_hist (vint 0) l) eqn: Hl; [|discriminate].\n    destruct (in_dec (EqDec_prod _ _ _ _) (t, x) h').\n    + exploit in_split; eauto; intros (h1' & h2' & ?); subst.\n      rewrite map_app in HNoDup; simpl in HNoDup; apply NoDup_remove in HNoDup; rewrite <- map_app in HNoDup.\n      assert (incl (h1' ++ h2') (h1 ++ h2)).\n      { intros (t', e') Hin.\n        specialize (Hh' (t', e')); exploit Hh'.\n        { rewrite in_app in *; simpl; tauto. }\n        rewrite !in_app; intros [? | [Heq | ?]]; auto; inv Heq.\n        destruct HNoDup as (? & HNoDup); contradiction HNoDup.\n        rewrite in_map_iff; do 2 eexists; eauto; auto. }\n      exploit IHl; eauto.\n      { tauto. }\n      { intros t' e' ? Hin2 ??.\n        eapply (Hdiff t' e'); eauto.\n        { rewrite in_app in *; simpl; tauto. }\n        { intro Hin; contradiction Hin2.\n          rewrite in_app in *; destruct Hin as [? | [Heq | ?]]; auto; inv Heq.\n          destruct Hh as (_ & Hh); contradiction Hh.\n          rewrite in_map_iff; do 2 eexists; [|rewrite in_app; eauto]; auto. } }\n      intros (l' & ? & Hl').\n      exists (l' ++ [x]); split; [|rewrite apply_hist_app, Hl'; auto].\n      econstructor; eauto.\n      eapply Forall_incl; eauto.\n    + eapply IHl; eauto.\n      * specialize (Hdiff t x).\n        rewrite in_app in Hdiff; simpl in Hdiff.\n        specialize (Hdiff (or_intror (or_introl eq_refl)) n).\n        destruct x; simpl in *.\n        { destruct (eq_dec v1 v0); inv Hv; auto. }\n        { specialize (Hdiff _ eq_refl); contradiction. }\n        { destruct (eq_dec r v0); [|discriminate].\n          destruct (eq_dec c v0); inv Hv; auto.\n          exploit Hdiff; eauto; contradiction. }\n      * intros ? Hin; specialize (Hh' _ Hin).\n        rewrite in_app in *; destruct Hh' as [? | [? | ?]]; auto; subst; contradiction.\n      * intros t' e' ????; eapply (Hdiff t' e'); eauto.\n        rewrite in_app in *; simpl; tauto.\nQed.\n\nLemma full_hist'_nil : forall n l, Forall2 full_hist' (repeat [] n) l -> l = repeat (vint 0) n.\nProof.\n  intros.\n  assert (Zlength l = Z.of_nat n).\n  { rewrite <- (mem_lemmas.Forall2_Zlength H), Zlength_repeat; auto. }\n  intros; eapply list_Znth_eq'.\n  { rewrite Zlength_repeat; auto. }\n  intros; rewrite Znth_repeat.\n  eapply Forall2_Znth with (i := j)(d2 := vint 0) in H; [|rewrite Zlength_repeat; omega].\n  destruct H as (? & Hl & Hv).\n  rewrite Znth_repeat in Hl; inv Hl; inv Hv; auto.\n  apply app_cons_not_nil in He; contradiction.\nQed.\n\nCorollary full_hist_nil' : forall n l (Hfull : Forall2 full_hist' (repeat [] n) (map (fun x => vint x) l))\n  (Hrep : Forall repable_signed l), l = repeat 0 n.\nProof.\n  intros; apply full_hist'_nil in Hfull.\n  revert dependent l; induction n; destruct l; auto; try discriminate; simpl; intros.\n  inv Hrep; f_equal; [|apply IHn; inv Hfull; auto].\n  apply repr_inj_signed; auto; congruence.\nQed.\n\nCorollary full_hist_nil : forall n l (Hfull : Forall2 full_hist (repeat [] n) l)\n  (Hrep : Forall repable_signed l), l = repeat 0 n.\nProof.\n  intros; apply full_hist_nil'; auto.\n  eapply Forall2_map2, Forall2_impl', Hfull.\n  intros ?? Hin ??; apply full_hist_weak; auto.\nQed.\n\nDefinition int_op e :=\n  match e with\n  | Load v | Store v => tc_val tint v\n  | CAS r c w => tc_val tint r /\\ tc_val tint c /\\ tc_val tint w\n  end.\n\nDefinition make_int v := match v with Vint i => Int.signed i | _ => 0 end.\n\nLemma make_int_spec : forall v, tc_val tint v -> vint (make_int v) = v.\nProof.\n  destruct v; try contradiction; simpl.\n  rewrite Int.repr_signed; auto.\nQed.\n\nLemma make_int_repable : forall v, repable_signed (make_int v).\nProof.\n  destruct v; simpl; try (split; computable).\n  apply Int.signed_range.\nQed.\n\nLemma int_op_value : forall e, int_op e -> tc_val tint (value_of e).\nProof.\n  destruct e; auto; simpl.\n  intros (? & ? & ?); destruct (eq_dec r c); auto.\nQed.\n\nCorollary int_op_value_of_hist : forall h, Forall int_op (map snd h) -> tc_val tint (value_of_hist h).\nProof.\n  intros; unfold value_of_hist.\n  apply Forall_last; simpl; auto.\n  rewrite Forall_map in H; eapply Forall_impl; [|eauto].\n  simpl; intros; apply int_op_value; auto.\nQed.\n\nLemma apply_int_ops : forall v h i (Hv : apply_hist (Vint i) h = Some v)\n  (Hints : Forall int_op h), tc_val tint v.\nProof.\n  induction h; simpl; intros.\n  - inv Hv; eauto.\n  - inversion Hints as [|?? Ha]; subst.\n    destruct a.\n    + destruct (eq_dec v0 (Vint i)); [eapply IHh; eauto | discriminate].\n    + destruct v0; try contradiction; eapply IHh; eauto.\n    + destruct (eq_dec r (Vint i)); [|discriminate].\n      destruct Ha as (? & ? & ?).\n      destruct w; try contradiction.\n      destruct (eq_dec c (Vint i)); eapply IHh; eauto.\nQed.\n\nDefinition hist_R g i R v := EX h : _, !!(apply_hist (vint i) h = Some (vint v)) && ghost_ref h g * R h v.\n\nDefinition atomic_loc_hist sh p g i R (h : hist) := atomic_loc sh p (hist_R g i R) * ghost_hist sh h g.\n\nLemma atomic_loc_hist_isptr : forall sh p g i R h,\n  atomic_loc_hist sh p g i R h = !!(isptr p) && atomic_loc_hist sh p g i R h.\nProof.\n  intros; eapply local_facts_isptr with (P := fun p => atomic_loc_hist sh p g i R h); eauto.\n  unfold atomic_loc_hist; rewrite atomic_loc_isptr; entailer!.\nQed.\nHint Resolve atomic_loc_hist_isptr : saturate_local.\n\nLemma hist_R_precise : forall p i R v, precise (EX h : _, R h v) -> precise (hist_R p i R v).\nProof.\n  intros; unfold hist_R; apply derives_precise' with\n    (Q := (EX g : option (share * hist) * option hist, ghost g p) * EX h : _, R h v).\n  - unfold ghost_ref; Intros h hr; Exists (@None (share * hist), Some hr) h; auto.\n  - apply precise_sepcon; auto; apply ex_ghost_precise.\nQed.\nHint Resolve hist_R_precise.\n\nLemma atomic_loc_hist_precise : forall sh p g i R, readable_share sh ->\n  precise (EX h : _, atomic_loc_hist sh p g i R h).\nProof.\n  intros; unfold atomic_loc_hist.\n  eapply derives_precise' with\n    (Q := atomic_loc _ _ _ * EX g' : option (share * hist) * option hist, ghost g' g).\n  - Intro h; Exists (Some (sh, h), @None hist); entailer!.\n  - apply precise_sepcon; [apply atomic_loc_precise | apply ex_ghost_precise]; auto.\nQed.\n\nNotation init_hist := (Some (Tsh, [] : hist), Some ([] : hist)).\n\n(* The user must make the init_hist before calling make_atomic, so that the ghost location is known. *)\nNotation MA_witness g i R :=\n  (i%Z, ghost init_hist g * R%function [] i%Z, hist_R g i R, ghost_hist Tsh ([] : hist) g).\nLemma MA_hist_spec : forall g i R, precise (EX h : _, R h i) ->\n  MA_spec i (ghost init_hist g * R [] i) (hist_R g i R) (ghost_hist Tsh ([] : hist) g).\nProof.\n  repeat intro.\n  eapply semax_pre; [|eauto].\n  unfold hist_R; go_lowerx.\n  Exists (@nil hist_el); entailer!.\n  rewrite sepcon_comm, <- !sepcon_assoc, hist_ref_join_nil by (apply Share.nontrivial).\n  unfold share; cancel.\n  apply andp_right; auto.\n  eapply derives_trans, precise_weak_precise, hist_R_precise; auto.\nQed.\n\nInductive add_events h : list hist_el -> hist -> Prop :=\n| add_events_nil : add_events h [] h\n| add_events_snoc : forall le h' t e (Hh' : add_events h le h') (Ht : newer h' t),\n    add_events h (le ++ [e]) (h' ++ [(t, e)]).\nHint Resolve add_events_nil.\n\nLemma add_events_1 : forall h t e (Ht : newer h t), add_events h [e] (h ++ [(t, e)]).\nProof.\n  intros; apply (add_events_snoc _ []); auto.\nQed.\n\nLemma add_events_trans : forall h le h' le' h'' (H1 : add_events h le h') (H2 : add_events h' le' h''),\n  add_events h (le ++ le') h''.\nProof.\n  induction 2.\n  - rewrite app_nil_r; auto.\n  - rewrite app_assoc; constructor; auto.\nQed.\n\nLemma add_events_add : forall h le h', add_events h le h' -> exists h2, h' = h ++ h2 /\\ map snd h2 = le.\nProof.\n  induction 1.\n  - eexists; rewrite app_nil_r; auto.\n  - destruct IHadd_events as (? & -> & ?).\n    rewrite <- app_assoc; do 2 eexists; eauto.\n    subst; rewrite map_app; auto.\nQed.\n\nCorollary add_events_snd : forall h le h', add_events h le h' -> map snd h' = map snd h ++ le.\nProof.\n  intros; apply add_events_add in H.\n  destruct H as (? & ? & ?); subst.\n  rewrite map_app; auto.\nQed.\n\nCorollary add_events_incl : forall h le h', add_events h le h' -> incl h h'.\nProof.\n  intros; apply add_events_add in H.\n  destruct H as (? & ? & ?); subst.\n  apply incl_appl, incl_refl.\nQed.\n\nCorollary add_events_newer : forall h le h' t, add_events h le h' -> newer h' t -> newer h t.\nProof.\n  intros; eapply Forall_incl, add_events_incl; eauto.\nQed.\n\nLemma add_events_in : forall h le h' e, add_events h le h' -> In e le -> exists t, newer h t /\\ In (t, e) h'.\nProof.\n  induction 1; [contradiction|].\n  rewrite in_app; intros [? | [? | ?]]; try contradiction.\n  - destruct IHadd_events as (? & ? & ?); auto.\n    do 2 eexists; [|rewrite in_app]; eauto.\n  - subst; do 2 eexists; [|rewrite in_app; simpl; eauto].\n    eapply add_events_newer; eauto.\nQed.\n\nLemma add_events_ordered : forall h le h', add_events h le h' -> ordered_hist h -> ordered_hist h'.\nProof.\n  induction 1; auto; intros.\n  apply ordered_snoc; auto.\nQed.\n\nLemma add_events_last : forall h le h', add_events h le h' -> le <> [] ->\n  value_of_hist h' = value_of (last le (Store (vint 0))).\nProof.\n  intros; apply add_events_add in H.\n  destruct H as (? & ? & ?); subst.\n  unfold value_of_hist.\n  rewrite last_app, last_map; auto.\n  intro; subst; contradiction.\nQed.\n\nLemma add_events_NoDup : forall h le h', add_events h le h' -> NoDup (map fst h) -> NoDup (map fst h').\nProof.\n  induction 1; auto; intros.\n  rewrite map_app, NoDup_app_iff.\n  split; auto.\n  split; [repeat constructor; simpl; auto|].\n  simpl; intros ? Hin [? | ?]; [subst | contradiction].\n  unfold newer in Ht.\n  rewrite in_map_iff in Hin; destruct Hin as (? & ? & Hin); subst.\n  rewrite Forall_forall in Ht; specialize (Ht _ Hin); omega.\nQed.\n\n(* FCSL takes the approach that h is always empty, and the previous history is framed out and then combined\n   with the new event by hist join. We can do that, but whether it's preferable might be a matter of taste. *)\nNotation AL_witness sh p g i R h P Q :=\n  (sh%logic, p%logic, (ghost_hist sh h g * P)%logic, hist_R g%logic i R,\n   EX h' : hist, fun v => !!(add_events h [Load (vint v)] h') && ghost_hist sh h' g * Q v).\nLemma AL_hist_spec : forall sh g i R h P Q\n  (HPQR : forall h' v (Hhist : hist_incl h h'), apply_hist (vint i) h' = Some (vint v) -> repable_signed v ->\n    view_shift (R h' v * P) (R (h' ++ [Load (vint v)]) v * Q v)) (Hsh : sh <> Share.bot),\n  AL_spec (ghost_hist sh h g * P) (hist_R g i R)\n    (EX h' : hist, fun v => !!(add_events h [Load (vint v)] h') && ghost_hist sh h' g * Q v).\nProof.\n  repeat intro.\n  unfold hist_R.\n  rewrite exp_sepcon1, extract_exists_in_SEP; Intro h'.\n  erewrite !sepcon_andp_prop', extract_prop_in_SEP with (n := O); simpl; eauto; Intros.\n  rewrite <- sepcon_assoc, (sepcon_comm _ (ghost_hist _ _ _)), <- sepcon_assoc.\n  rewrite sepcon_assoc, flatten_sepcon_in_SEP.\n  assert_PROP (hist_incl h h').\n  { go_lowerx; apply sepcon_derives_prop.\n    rewrite hist_ref_join by auto; Intros l.\n    eapply prop_right, hist_sub_list_incl; eauto. }\n  apply hist_add' with (e := Load (vint vx)); auto.\n  focus_SEP 1; apply HPQR; auto.\n  eapply semax_pre; [|eauto].\n  unfold hist_R; go_lowerx.\n  Exists (h' ++ [Load (vint vx)]) (h ++ [(length h', Load (vint vx))]); entailer!.\n  split; [|apply add_events_1, hist_incl_lt; auto].\n  rewrite apply_hist_app; simpl.\n  replace (apply_hist (vint i) h') with (Some (vint vx)); rewrite eq_dec_refl; auto.\nQed.\n\nNotation AS_witness sh p g i R h v P Q :=\n  (sh%logic, p%logic, v%Z%logic, (ghost_hist sh h g * P)%logic, hist_R g%logic i R,\n   EX h' : hist, !!(add_events h [Store (vint v)] h') && ghost_hist sh h' g * Q).\nLemma AS_hist_spec : forall sh g i R h v P Q\n  (HPQR : forall h' v' (Hhist : hist_incl h h'), apply_hist (vint i) h' = Some (vint v') -> repable_signed v' ->\n     view_shift (R h' v' * P) (R (h' ++ [Store (vint v)]) v * Q)) (Hsh : sh <> Share.bot)\n  (Hprecise : precise (EX h : _, R h v)),\n  AS_spec v (ghost_hist sh h g * P) (hist_R g i R)\n    (EX h' : hist, !!(add_events h [Store (vint v)] h') && ghost_hist sh h' g * Q).\nProof.\n  repeat intro.\n  unfold hist_R.\n  rewrite exp_sepcon1, extract_exists_in_SEP; Intro h'.\n  erewrite !sepcon_andp_prop', extract_prop_in_SEP with (n := O); simpl; eauto; Intros.\n  rewrite <- sepcon_assoc, (sepcon_comm _ (ghost_hist _ _ _)), <- sepcon_assoc.\n  rewrite sepcon_assoc, flatten_sepcon_in_SEP.\n  assert_PROP (hist_incl h h').\n  { go_lowerx; apply sepcon_derives_prop.\n    rewrite hist_ref_join by auto; Intros l.\n    eapply prop_right, hist_sub_list_incl; eauto. }\n  apply hist_add' with (e := Store (vint v)); auto.\n  focus_SEP 1; apply HPQR; auto.\n  eapply semax_pre; [|eauto].\n  unfold hist_R; go_lowerx.\n  Exists (h' ++ [Store (vint v)]) (h ++ [(length h', Store (vint v))]); entailer!.\n  split; [|apply add_events_1, hist_incl_lt; auto].\n  rewrite apply_hist_app; simpl.\n  replace (apply_hist (vint i) h') with (Some (vint vx)); auto.\n  { apply andp_right; auto.\n    eapply derives_trans, precise_weak_precise, hist_R_precise; auto. }\nQed.\n\nNotation ACAS_witness sh p g i R h c v P Q :=\n  (sh%logic, p%logic, c%Z%logic, v%Z%logic, (ghost_hist sh h g * P)%logic, hist_R g%logic i R,\n   fun v' => EX h' : hist, !!(add_events h [CAS (vint v') (vint c) (vint v)] h') &&\n     ghost_hist sh h' g * Q v').\nLemma ACAS_hist_spec : forall sh g i R h v c P Q\n  (HPQR : forall h' v' (Hhist : hist_incl h h'), apply_hist (vint i) h' = Some (vint v') -> repable_signed v' ->\n    view_shift (R h' v' * P) (R (h' ++ [CAS (vint v') (vint c) (vint v)]) (if eq_dec c v' then v else v') * Q v'))\n  (Hsh : sh <> Share.bot) (Hc : repable_signed c) (Hprecise : forall v, precise (EX h : _, R h v)),\n  ACAS_spec c v (ghost_hist sh h g * P) (hist_R g i R)\n    (fun v' => EX h' : hist, !!(add_events h [CAS (vint v') (vint c) (vint v)] h') && ghost_hist sh h' g * Q v').\nProof.\n  repeat intro.\n  unfold hist_R.\n  rewrite exp_sepcon1, extract_exists_in_SEP; Intro h'.\n  erewrite !sepcon_andp_prop', extract_prop_in_SEP with (n := O); simpl; eauto; Intros.\n  rewrite <- sepcon_assoc, (sepcon_comm _ (ghost_hist _ _ _)), <- sepcon_assoc.\n  rewrite sepcon_assoc, flatten_sepcon_in_SEP.\n  assert_PROP (hist_incl h h').\n  { go_lowerx; apply sepcon_derives_prop.\n    rewrite hist_ref_join by auto; Intros l.\n    eapply prop_right, hist_sub_list_incl; eauto. }\n  apply hist_add' with (e := CAS (vint vx) (vint c) (vint v)); auto.\n  focus_SEP 1; apply HPQR; auto.\n  eapply semax_pre; [|eauto].\n  unfold hist_R; go_lowerx.\n  Exists (h' ++ [CAS (vint vx) (vint c) (vint v)]) (h ++ [(length h', CAS (vint vx) (vint c) (vint v))]);\n    entailer!.\n  split; [|apply add_events_1, hist_incl_lt; auto].\n  rewrite apply_hist_app; simpl.\n  replace (apply_hist (vint i) h') with (Some (vint vx)); rewrite eq_dec_refl.\n  if_tac.\n  - assert (c = vx) by (apply repr_inj_signed; auto; congruence).\n    subst; rewrite eq_dec_refl; auto.\n  - if_tac; [absurd (vint c = vint vx); subst; auto | auto].\n  - apply andp_right; auto.\n    eapply derives_trans, precise_weak_precise, hist_R_precise; auto.\nQed.\n\nLemma atomic_loc_hist_join : forall sh1 sh2 sh p g i R h1 h2 h (Hjoin : sepalg.join sh1 sh2 sh)\n  (Hh : Permutation.Permutation (h1 ++ h2) h) (Hsh1 : readable_share sh1) (Hsh2 : readable_share sh2),\n  atomic_loc_hist sh1 p g i R h1 * atomic_loc_hist sh2 p g i R h2 =\n  !!(disjoint h1 h2) && atomic_loc_hist sh p g i R h.\nProof.\n  intros; unfold atomic_loc_hist.\n  assert (sh1 <> Share.bot) by (intro; subst; contradiction unreadable_bot).\n  assert (sh2 <> Share.bot) by (intro; subst; contradiction unreadable_bot).\n  match goal with |- (?P1 * ?Q1) * (?P2 * ?Q2) = _ =>\n    transitivity ((P1 * P2) * (Q1 * Q2)); [apply mpred_ext; cancel|] end.\n  erewrite ghost_hist_join, atomic_loc_join; eauto.\n  rewrite sepcon_andp_prop; auto.\nQed.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/mailbox/verif_atomics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.21549176579436202}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nRequire Import Coq.Classes.RelationClasses Lia Program.\nFrom Fairness Require Export ITreeLib WFLibLarge FairBeh NatStructsLarge Mod pind.\n\nSet Implicit Arguments.\n\n\nModule WMod.\n  Variant output (state: Type) (ident: ID) (mident: ID) (R: Type) :=\n    | normal (st: state) (r: R) (fm: fmap (id_sum ident mident))\n    | stuck\n    | disabled\n  .\n\n  Record function (state: Type) (ident: ID) (mident: ID): Type :=\n    mk_fun {\n        type: ident;\n        A: Type;\n        R: Type;\n        body: A -> state -> output state ident mident R -> Prop;\n      }.\n\n  Record t: Type :=\n    mk {\n        state: Type;\n        ident: ID;\n        mident: ID;\n        st_init: state;\n        funs: list (fname * function state ident mident);\n      }.\n\n  Section INTERP.\n    Variable m: t.\n\n    Definition interp_state := (m.(state) * NatMap.t m.(ident))%type.\n\n    Definition interp_ident := id_sum thread_id m.(mident).\n\n    Definition interp_fmap\n               (fm: fmap (id_sum m.(ident) m.(mident))) (ts: NatMap.t m.(ident)) : fmap interp_ident :=\n      fun i =>\n        match i with\n        | inl i =>\n            match NatMap.find i ts with\n            | Some i => fm (inl i)\n            | None => Flag.emp\n            end\n        | inr i => fm (inr i)\n        end.\n\n    Definition interp_fun (f: function m.(state) m.(ident) m.(mident))\n      : ktree (programE interp_ident interp_state) f.(A) f.(R) :=\n      fun (arg: f.(A)) =>\n        _ <- trigger Yield;;\n\n        tid <- trigger (GetTid);;\n        '(st, ts) <- trigger (Get id);;\n        let ts := NatMap.add tid f.(type) ts in\n        _ <- trigger (Put (st, ts));;\n        _ <- trigger (Fair (prism_fmap inlp (fun i => if tid_dec i tid then Flag.success else Flag.emp)));;\n\n        ITree.iter\n          (fun (_: unit) =>\n             b <- trigger (Choose bool);;\n             if (b: bool)\n             then\n               _ <- trigger (Fair (prism_fmap inlp (fun i => if tid_dec i tid then Flag.fail else Flag.emp)));;\n               _ <- trigger Yield;; Ret (inl tt)\n             else\n               '(st, ts) <- trigger (Get id);;\n               next <- trigger (Choose (sig (f.(body) arg st)));;\n               match proj1_sig next with\n               | normal st r fm =>\n                   let ts := NatMap.remove tid ts in\n                   _ <- trigger (Fair (interp_fmap fm ts));;\n                   _ <- trigger (Put (st, ts));;\n                   _ <- trigger Yield;;\n                   Ret (inr r)\n               | stuck _ _ _ _ => UB\n               | disabled _ _ _ _ => _ <- trigger Yield;; Ret (inl tt)\n               end) tt\n    .\n\n    Definition interp_fun_register (tid: thread_id) (i: m.(ident)): itree (programE interp_ident interp_state) unit :=\n      '(st, ts) <- trigger (Get id);;\n      let ts := NatMap.add tid i ts in\n      _ <- trigger (Put (st, ts));;\n      _ <- trigger (Fair (prism_fmap inlp (fun i => if tid_dec i tid then Flag.success else Flag.emp)));;\n      Ret tt\n    .\n\n    Definition interp_fun_body R (tid: thread_id)\n               (step: m.(state) -> output m.(state) m.(ident) m.(mident) R -> Prop)\n      : itree (programE interp_ident interp_state) R :=\n      ITree.iter\n        (fun (_: unit) =>\n           b <- trigger (Choose bool);;\n           if (b: bool) then\n             _ <- trigger (Fair (prism_fmap inlp (fun i => if tid_dec i tid then Flag.fail else Flag.emp)));;\n             _ <- trigger Yield;; Ret (inl tt)\n           else\n             '(st, ts) <- trigger (Get id);;\n             next <- trigger (Choose (sig (step st)));;\n             match proj1_sig next with\n             | normal st r fm =>\n                 let ts := NatMap.remove tid ts in\n                 _ <- trigger (Fair (interp_fmap fm ts));;\n                 _ <- trigger (Put (st, ts));;\n                 _ <- trigger Yield;;\n                 Ret (inr r)\n             | stuck _ _ _ _ => UB\n             | disabled _ _ _ _ => _ <- trigger Yield;; Ret (inl tt)\n             end) tt.\n\n    Lemma interp_fun_unfold f arg\n      :\n      interp_fun f arg\n      =\n        _ <- trigger Yield;;\n        tid <- trigger (GetTid);;\n        _ <- (interp_fun_register tid f.(type));;\n        interp_fun_body tid (f.(body) arg)\n    .\n    Proof.\n      unfold interp_fun, interp_fun_register, interp_fun_body. grind.\n    Qed.\n\n    Lemma interp_loop_unfold\n          R (tid: thread_id)\n          (step: m.(state) -> output m.(state) m.(ident) m.(mident) R -> Prop)\n      :\n      interp_fun_body tid step\n      =\n        b <- trigger (Choose bool);;\n        if (b: bool) then\n          _ <- trigger (Fair (prism_fmap inlp (fun i => if tid_dec i tid then Flag.fail else Flag.emp)));;\n          _ <- trigger Yield;;\n          tau;; interp_fun_body tid step\n        else\n          '(st, ts) <- trigger (Get id);;\n          next <- trigger (Choose (sig (step st)));;\n          match proj1_sig next with\n          | normal st r fm =>\n              let ts := NatMap.remove tid ts in\n              _ <- trigger (Fair (interp_fmap fm ts));;\n              _ <- trigger (Put (st, ts));;\n              _ <- trigger Yield;;\n              Ret r\n          | stuck _ _ _ _ => UB\n          | disabled _ _ _ _ => _ <- trigger Yield;; tau;; interp_fun_body tid step\n          end.\n    Proof.\n      unfold interp_fun_body at 1. rewrite unfold_iter_eq.\n      unfold interp_fun_body, UB. grind.\n    Qed.\n\n    Definition interp_mod: Mod.t :=\n      Mod.mk\n        (m.(st_init), NatMap.empty m.(ident))\n        (Mod.get_funs (List.map (fun '(fn, f) => (fn, Mod.wrap_fun (interp_fun f))) m.(funs)))\n    .\n  End INTERP.\nEnd WMod.\nArguments WMod.disabled {_ _ _ _}.\nArguments WMod.stuck {_ _ _ _}.\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/src/semantics/Wrapper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2154772122374626}}
{"text": "From iris.algebra Require Import excl auth list.\nFrom iris.bi.lib Require Import fractional.\nFrom iris.base_logic.lib Require Import invariants.\nFrom iris.program_logic Require Import atomic.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.heap_lang Require Import proofmode notation atomic_heap.\nFrom iris_examples.logatom.elimination_stack Require Import spec.\nFrom iris.prelude Require Import options.\n\n(** * Implement a concurrent stack with helping on top of an arbitrary atomic\nheap. *)\n\n(** The CMRA & functor we need. *)\n(* Not bundling heapGS, as it may be shared with other users. *)\nClass stackG Σ := StackG {\n  stack_tokG :> inG Σ (exclR unitO);\n  stack_stateG :> inG Σ (authR (optionUR $ exclR (listO valO)));\n }.\nDefinition stackΣ : gFunctors :=\n  #[GFunctor (exclR unitO); GFunctor (authR (optionUR $ exclR (listO valO)))].\n\nGlobal Instance subG_stackΣ {Σ} : subG stackΣ Σ → stackG Σ.\nProof. solve_inG. Qed.\n\nSection stack.\n  Context `{!heapGS Σ, stackG Σ} {aheap: atomic_heap Σ} (N : namespace).\n  Notation iProp := (iProp Σ).\n\n  Let offerN := N .@ \"offer\".\n  Let stackN := N .@ \"stack\".\n\n  Import atomic_heap.notation.\n\n  (** Code. A stack is a pair of two pointers-to-option-pointers, one for the\n  head element (if the stack is non-empty) and for the current offer (if it\n  exists).  A stack element is a pair of a value an an optional pointer to the\n  next element. *)\n  Definition new_stack : val :=\n    λ: <>,\n      let: \"head\" := ref NONE in\n      let: \"offer\" := ref NONE in\n      (\"head\", \"offer\").\n\n  Definition push : val :=\n    rec: \"push\" \"stack\" \"val\" :=\n      let: \"head_old\" := !(Fst \"stack\") in\n      let: \"head_new\" := ref (\"val\", \"head_old\") in\n      if: CAS (Fst \"stack\") \"head_old\" (SOME \"head_new\") then #() else\n      (* the CAS failed due to a race, let's try an offer on the side-channel *)\n      let: \"state\" := ref #0 in\n      let: \"offer\" := (\"val\", \"state\") in\n      (Snd \"stack\") <- SOME \"offer\" ;;\n      (* wait to see if anyone takes it *)\n      (* okay, enough waiting *)\n      (Snd \"stack\") <- NONE ;;\n      if: CAS \"state\" #0 #2 then\n        (* We retracted the offer. Just try the entire thing again. *)\n        \"push\" \"stack\" \"val\"\n      else\n        (* Someone took the offer. We are done. *)\n        #().\n\n  Definition pop : val :=\n    rec: \"pop\" \"stack\" :=\n      match: !(Fst \"stack\") with\n        NONE => NONE (* stack empty *)\n      | SOME \"head_old\" =>\n        let: \"head_old_data\" := !\"head_old\" in\n        (* See if we can change the master head pointer *)\n        if: CAS (Fst \"stack\") (SOME \"head_old\") (Snd \"head_old_data\") then\n          (* That worked! We are done. Return the value. *)\n          SOME (Fst \"head_old_data\")\n        else\n          (* See if there is an offer on the side-channel *)\n          match: !(Snd \"stack\") with\n            NONE =>\n            (* Nope, no offer. Just try again. *)\n            \"pop\" \"stack\"\n          | SOME \"offer\" =>\n            (* Try to accept the offer. *)\n            if: CAS (Snd \"offer\") #0 #1 then\n              (* Success! We are done. Return the offered value. *)\n              SOME (Fst \"offer\")\n            else\n              (* Someone else was faster. Just try again. *)\n              \"pop\" \"stack\"\n          end\n      end.\n\n  (** Invariant and protocol. *)\n  Definition stack_content (γs : gname) (l : list val) : iProp :=\n    (own γs (◯ Excl' l))%I.\n  Global Instance stack_content_timeless γs l : Timeless (stack_content γs l) := _.\n\n  Lemma stack_content_exclusive γs l1 l2 :\n    stack_content γs l1 -∗ stack_content γs l2 -∗ False.\n  Proof.\n    iIntros \"Hl1 Hl2\".\n    iDestruct (own_valid_2 with \"Hl1 Hl2\") as %[]%auth_frag_op_valid_1.\n  Qed.\n\n  Definition stack_elem_to_val (stack_rep : option loc) : val :=\n    match stack_rep with\n    | None => NONEV\n    | Some l => SOMEV #l\n    end.\n  Local Instance stack_elem_to_val_inj : Inj (=) (=) stack_elem_to_val.\n  Proof. rewrite /Inj /stack_elem_to_val=>??. repeat case_match; congruence. Qed.\n\n  Fixpoint list_inv (l : list val) (rep : option loc) : iProp :=\n    match l with\n    | nil => ⌜rep = None⌝\n    | v::l => ∃ (ℓ : loc) (rep' : option loc), ⌜rep = Some ℓ⌝ ∗\n                              ℓ ↦□ (v, stack_elem_to_val rep') ∗ list_inv l rep'\n    end%I.\n\n  Local Hint Extern 0 (environments.envs_entails _ (list_inv (_::_) _)) => simpl : core.\n\n  Inductive offer_state := OfferPending | OfferRevoked | OfferAccepted | OfferAcked.\n\n  Local Instance: Inhabited offer_state := populate OfferPending.\n\n  Definition offer_state_rep (st : offer_state) : Z :=\n    match st with\n    | OfferPending => 0\n    | OfferRevoked => 2\n    | OfferAccepted => 1\n    | OfferAcked => 1\n    end.\n\n  Definition offer_inv (st_loc : loc) (γo : gname) (P Q : iProp) : iProp :=\n    (∃ st : offer_state, st_loc ↦ #(offer_state_rep st) ∗\n      match st with\n      | OfferPending => P\n      | OfferAccepted => Q\n      | _ => own γo (Excl ())\n      end)%I.\n\n  Local Hint Extern 0 (environments.envs_entails _ (offer_inv _ _ _ _)) => unfold offer_inv : core.\n\n  Definition is_offer (γs : gname) (offer_rep : option (val * loc)) :=\n    match offer_rep with\n    | None => True\n    | Some (v, st_loc) =>\n      ∃ P Q γo, inv offerN (offer_inv st_loc γo P Q) ∗\n                (* The persistent part of the Laterable AU *)\n                □ (▷ P -∗ ◇ AU << ∀ l, stack_content γs l >> @ ⊤∖↑N, ∅\n                               << stack_content γs (v::l), COMM Q >>)\n    end%I.\n\n  Local Instance is_offer_persistent γs offer_rep : Persistent (is_offer γs offer_rep).\n  Proof. destruct offer_rep as [[??]|]; apply _. Qed.\n\n  Definition offer_to_val (offer_rep : option (val * loc)) : val :=\n    match offer_rep with\n    | None => NONEV\n    | Some (v, l) => SOMEV (v, #l)\n    end.\n\n  Definition stack_inv (γs : gname) (head : loc) (offer : loc) : iProp :=\n    (∃ stack_rep offer_rep l, own γs (● Excl' l) ∗\n       head ↦ stack_elem_to_val stack_rep ∗ list_inv l stack_rep ∗\n       offer ↦ offer_to_val offer_rep ∗ is_offer γs offer_rep)%I.\n\n  Local Hint Extern 0 (environments.envs_entails _ (stack_inv _ _ _)) => unfold stack_inv : core.\n\n  Definition is_stack (γs : gname) (s : val) : iProp :=\n    (∃ head offer : loc, ⌜s = (#head, #offer)%V⌝ ∗ inv stackN (stack_inv γs head offer))%I.\n  Global Instance is_stack_persistent γs s : Persistent (is_stack γs s) := _.\n\n  (** Proofs. *)\n  Lemma new_stack_spec :\n    {{{ True }}} new_stack #() {{{ γs s, RET s; is_stack γs s ∗ stack_content γs [] }}}.\n  Proof.\n    iIntros (Φ) \"_ HΦ\". wp_lam. wp_pures.\n    wp_apply alloc_spec; first done. iIntros (head) \"Hhead\". wp_pures.\n    wp_apply alloc_spec; first done. iIntros (offer) \"Hoffer\". wp_pures.\n    iMod (own_alloc (● Excl' [] ⋅ ◯ Excl' [])) as (γs) \"[Hs● Hs◯]\".\n    { apply auth_both_valid_discrete. split; done. }\n    iMod (inv_alloc stackN _ (stack_inv γs head offer) with \"[-HΦ Hs◯]\").\n    { iNext. iExists None, None, _. iFrame. done. }\n    iApply \"HΦ\". iFrame \"Hs◯\". iModIntro. iExists _, _. auto.\n  Qed.\n\n  Lemma push_spec γs s (v : val) :\n    is_stack γs s -∗\n    <<< ∀ l : list val, stack_content γs l >>>\n      push s v @ ↑N\n    <<< stack_content γs (v::l), RET #() >>>.\n  Proof.\n    iIntros \"#Hinv\". iIntros (Φ) \"AU\".\n    iDestruct \"Hinv\" as (head offer) \"[% #Hinv]\". subst s.\n    iLöb as \"IH\".\n    wp_lam. wp_pures.\n    (* Load the old head. *)\n    awp_apply load_spec without \"AU\".\n    iInv stackN as (stack_rep offer_rep l) \"(Hs● & >H↦ & Hrem)\".\n    iAaccIntro with \"H↦\"; first by eauto 10 with iFrame.\n    iIntros \"?\". iSplitL; first by eauto 10 with iFrame.\n    iIntros \"!> AU\". clear offer_rep l.\n    (* Go on. *)\n    wp_pures. wp_apply alloc_spec; first done. iIntros (head_new) \"Hhead_new\".\n    (* CAS to change the head. *)\n    wp_pures. awp_apply cas_spec; [by destruct stack_rep|].\n    iInv stackN as (stack_rep' offer_rep l) \"(>Hs● & >H↦ & Hlist & Hoffer)\".\n    iAaccIntro with \"H↦\"; first by eauto 10 with iFrame.\n    iIntros \"H↦\".\n    destruct (decide (stack_elem_to_val stack_rep' = stack_elem_to_val stack_rep)) as\n      [->%stack_elem_to_val_inj|_].\n    - (* The CAS succeeded. Update everything accordingly. *)\n      iMod \"AU\" as (l') \"[Hl' [_ Hclose]]\".\n      iMod (mapsto_persist with \"Hhead_new\") as \"#Hhead_new\".\n      iDestruct (own_valid_2 with \"Hs● Hl'\") as\n        %[->%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n      iMod (own_update_2 with \"Hs● Hl'\") as \"[Hs● Hl']\".\n      { eapply auth_update, option_local_update, (exclusive_local_update _ (Excl _)). done. }\n      iMod (\"Hclose\" with \"Hl'\") as \"HΦ\". iModIntro.\n      change (InjRV #head_new) with (stack_elem_to_val (Some head_new)).\n      iSplitR \"HΦ\"; first by eauto 12 with iFrame.\n      wp_if. by iApply \"HΦ\".\n    - (* The CAS failed, go on making an offer. *)\n      iModIntro. iSplitR \"AU\"; first by eauto 8 with iFrame.\n      clear stack_rep stack_rep' offer_rep l head_new.\n      wp_if.\n      wp_apply alloc_spec; first done. iIntros (st_loc) \"Hoffer_st\".\n      (* Make the offer *)\n      wp_pures. awp_apply store_spec.\n      iInv stackN as (stack_rep offer_rep l) \"(Hs● & >H↦ & Hlist & >Hoffer↦ & Hoffer)\".\n      iAaccIntro with \"Hoffer↦\"; first by eauto 10 with iFrame.\n      iMod (own_alloc (Excl ())) as (γo) \"Htok\"; first done.\n      iDestruct (laterable with \"AU\") as (AU_later) \"[AU #AU_back]\".\n      iMod (inv_alloc offerN _ (offer_inv st_loc γo AU_later _)  with \"[AU Hoffer_st]\") as \"#Hoinv\".\n      { iNext. iExists OfferPending. iFrame. }\n      iIntros \"?\". iSplitR \"Htok\".\n      { iClear \"Hoffer\". iExists _, (Some (v, st_loc)), _. iFrame.\n        rewrite /is_offer /=. iExists _, _, _. iFrame \"AU_back Hoinv\". done. }\n      clear stack_rep offer_rep l. iIntros \"!>\".\n      (* Retract the offer. *)\n      wp_pures. awp_apply store_spec.\n      iInv stackN as (stack_rep offer_rep l) \"(Hs● & >H↦ & Hlist & >Hoffer↦ & Hoffer)\".\n      iAaccIntro with \"Hoffer↦\"; first by eauto 10 with iFrame.\n      iIntros \"?\". iSplitR \"Htok\".\n      { iClear \"Hoffer\". iExists _, None, _. iFrame. done. }\n      iIntros \"!>\". wp_seq.\n      clear stack_rep offer_rep l.\n      (* See if someone took it. *)\n      awp_apply cas_spec; [done|].\n      iInv offerN as (offer_st) \"[>Hst↦ Hst]\".\n      iAaccIntro with \"Hst↦\"; first by eauto 10 with iFrame.\n      iIntros \"Hst↦\". destruct offer_st; simpl.\n      + (* Offer was still pending, and we revoked it. Loop around and try again. *)\n        iModIntro. iSplitR \"Hst\".\n        { iNext. iExists OfferRevoked. iFrame. }\n        iDestruct (\"AU_back\" with \"Hst\") as \">AU {AU_back Hoinv}\". clear AU_later.\n        wp_if. iApply (\"IH\" with \"AU\").\n      + (* Offer revoked by someone else? Impossible! *)\n        iDestruct \"Hst\" as \">Hst\".\n        iDestruct (own_valid_2 with \"Htok Hst\") as %[].\n      + (* Offer got accepted by someone, awesome! We are done. *)\n        iModIntro. iSplitR \"Hst\".\n        { iNext. iExists OfferAcked. iFrame. }\n        wp_if. by iApply \"Hst\".\n      + (* Offer got acked by someone else? Impossible! *)\n        iDestruct \"Hst\" as \">Hst\".\n        iDestruct (own_valid_2 with \"Htok Hst\") as %[].\n  Qed.\n\n  Lemma pop_spec γs (s : val) :\n    is_stack γs s -∗\n    <<< ∀ l, stack_content γs l >>>\n      pop s @ ↑N\n    <<< stack_content γs (tail l),\n        RET match l with [] => NONEV | v :: _ => SOMEV v end >>>.\n  Proof.\n    iIntros \"#Hinv\". iIntros (Φ) \"AU\".\n    iDestruct \"Hinv\" as (head offer) \"[% #Hinv]\". subst s.\n    iLöb as \"IH\". wp_lam. wp_pures.\n    (* Load the old head *)\n    awp_apply load_spec.\n    iInv stackN as (stack_rep offer_rep l) \"(>Hs● & >H↦ & Hlist & Hrem)\".\n    iAaccIntro with \"H↦\"; first by eauto 10 with iFrame.\n    iIntros \"?\". destruct l as [|v l]; simpl.\n    - (* The list is empty! We are already done, but it's quite some work to\n      prove that. *)\n      iDestruct \"Hlist\" as \">%\". subst stack_rep.\n      iMod \"AU\" as (l') \"[Hl' [_ Hclose]]\".\n      iDestruct (own_valid_2 with \"Hs● Hl'\") as\n        %[->%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n      iMod (\"Hclose\" with \"Hl'\") as \"HΦ\".\n      iSplitR \"HΦ\"; first by eauto 10 with iFrame.\n      iIntros \"!>\". wp_pures. by iApply \"HΦ\".\n    - (* Non-empty list, let's try to pop. *)\n      iDestruct \"Hlist\" as (tail rep) \"[>% [#Htail Hlist]]\". subst stack_rep.\n      iSplitR \"AU Htail\"; first by eauto 15 with iFrame.\n      clear offer_rep l.\n      iIntros \"!>\". wp_match.\n      wp_apply (atomic_wp_seq $! (load_spec _) with \"Htail\").\n      iIntros \"_\". wp_pures.\n      (* CAS to change the head *)\n      awp_apply cas_spec; [done|].\n      iInv stackN as (stack_rep offer_rep l) \"(>Hs● & >H↦ & Hlist & Hrem)\".\n      iAaccIntro with \"H↦\"; first by eauto 10 with iFrame.\n      iIntros \"H↦\". change (InjRV #tail) with (stack_elem_to_val (Some tail)).\n      destruct (decide (stack_elem_to_val stack_rep = stack_elem_to_val (Some tail))) as\n        [->%stack_elem_to_val_inj|_].\n      + (* CAS succeeded! It must still be the same head element in the list,\n        and we are done. *)\n        iMod \"AU\" as (l') \"[Hl' [_ Hclose]]\".\n        iDestruct (own_valid_2 with \"Hs● Hl'\") as\n          %[->%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n        destruct l as [|v' l]; simpl.\n        { (* Contradiction. *) iDestruct \"Hlist\" as \">%\". done. }\n        iDestruct \"Hlist\" as (tail' rep') \"[>% [>Htail' Hlist]]\". simplify_eq.\n        iDestruct (mapsto_agree with \"Htail Htail'\") as %[= <- <-%stack_elem_to_val_inj].\n        iMod (own_update_2 with \"Hs● Hl'\") as \"[Hs● Hl']\".\n        { eapply auth_update, option_local_update, (exclusive_local_update _ (Excl _)). done. }\n        iMod (\"Hclose\" with \"Hl'\") as \"HΦ {Htail Htail'}\".\n        iSplitR \"HΦ\"; first by eauto 10 with iFrame.\n        iIntros \"!>\". clear offer_rep l.\n        wp_pures. by iApply \"HΦ\".\n      + (* CAS failed.  Go on looking for an offer. *)\n        iSplitR \"AU\"; first by eauto 10 with iFrame.\n        iIntros \"!>\". wp_if. iClear (rep stack_rep offer_rep l tail v) \"Htail\".\n        wp_proj.\n        (* Load the offer pointer. *)\n        awp_apply load_spec.\n        iInv stackN as (stack_rep offer_rep l) \"(>Hs● & >H↦ & Hlist & >Hoff↦ & #Hoff)\".\n        iAaccIntro with \"Hoff↦\"; first by eauto 10 with iFrame.\n        iIntros \"Hoff↦\". iSplitR \"AU\"; first by eauto 10 with iFrame.\n        iIntros \"!>\". destruct offer_rep as [[v offer_st_loc]|]; last first.\n        { (* No offer, just loop. *) wp_match. iApply (\"IH\" with \"AU\"). }\n        clear l stack_rep. wp_match. wp_proj.\n        (* CAS to accept the offer. *)\n        awp_apply cas_spec; [done|]. simpl.\n        iDestruct \"Hoff\" as (Poff Qoff γo) \"[#Hoinv #AUoff]\".\n        iInv offerN as (offer_st) \"[>Hoff↦ Hoff]\".\n        iAaccIntro with \"Hoff↦\"; first by eauto 10 with iFrame.\n        iIntros \"Hoff↦\".\n        destruct (decide (#(offer_state_rep offer_st) = #0)) as [Heq|_]; last first.\n        { (* CAS failed, we don't do a thing. *)\n          iSplitR \"AU\"; first by eauto 10 with iFrame.\n          iIntros \"!>\". wp_if. iApply (\"IH\" with \"AU\"). }\n        (* CAS succeeded! We accept and complete the offer. *)\n        destruct offer_st; try done; []. clear Heq.\n        iMod (\"AUoff\" with \"Hoff\") as \"{AUoff IH} AUoff\".\n        iInv stackN as (stack_rep offer_rep l) \"(>Hs● & >H↦ & Hlist & Hoff)\".\n        iMod \"AUoff\" as (l') \"[Hl' [_ Hclose]]\".\n        iDestruct (own_valid_2 with \"Hs● Hl'\") as\n          %[->%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n        iMod (own_update_2 with \"Hs● Hl'\") as \"[Hs● Hl']\".\n        { eapply auth_update, option_local_update, (exclusive_local_update _ (Excl _)). done. }\n        iMod (\"Hclose\" with \"Hl'\") as \"HQoff\".\n        iMod \"AU\" as (l') \"[Hl' [_ Hclose]]\".\n        iDestruct (own_valid_2 with \"Hs● Hl'\") as\n          %[->%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n        iMod (own_update_2 with \"Hs● Hl'\") as \"[Hs● Hl']\".\n        { eapply auth_update, option_local_update, (exclusive_local_update _ (Excl _)). done. }\n        iMod (\"Hclose\" with \"Hl'\") as \"HΦ\".\n        iSplitR \"Hoff↦ HQoff HΦ\"; first by eauto 10 with iFrame. iSplitR \"HΦ\".\n        { iIntros \"!> !> !>\". iExists OfferAccepted. iFrame. }\n        iIntros \"!> !>\". wp_pures. by iApply \"HΦ\".\n  Qed.\n\nEnd stack.\n\nDefinition elimination_stack `{!heapGS Σ, stackG Σ} {aheap: atomic_heap Σ} :\n  atomic_stack Σ :=\n  {| spec.new_stack_spec := new_stack_spec;\n     spec.push_spec := push_spec;\n     spec.pop_spec := pop_spec;\n     spec.stack_content_exclusive := stack_content_exclusive |}.\n\nTypeclasses Opaque stack_content is_stack.\n", "meta": {"author": "pavel-ivanov-rnd", "repo": "iris-heaplang-experiments", "sha": "a283a53fe994672f7a6dbdaefa0d4eedd044b733", "save_path": "github-repos/coq/pavel-ivanov-rnd-iris-heaplang-experiments", "path": "github-repos/coq/pavel-ivanov-rnd-iris-heaplang-experiments/iris-heaplang-experiments-a283a53fe994672f7a6dbdaefa0d4eedd044b733/theories/logatom/elimination_stack/stack.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21547721223746258}}
{"text": "(** * Block labels and freshness frames\n\n    Specialization of [VariableBinding] to block labels.\n *)\nRequire Import Helix.LLVMGen.Correctness_Prelude.\nRequire Import Helix.LLVMGen.VariableBinding.\nRequire Import Helix.LLVMGen.IdLemmas.\nRequire Import Helix.LLVMGen.StateCounters.\n\nFrom Coq Require Import ZArith.\n\nImport ListNotations.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nOpaque incBlockNamed.\nOpaque incVoid.\nOpaque incLocal.\n\nSection BidBound.\n  (* Block id has been generated by an earlier IRState *)\n  Definition bid_bound (s : IRState) (bid: block_id) : Prop\n    := state_bound block_count incBlockNamed s bid.\n\n  (* If an id has been bound between two states.\n\n     The primary use for this is in lemmas like, bid_bound_fresh,\n     which let us know that since a id was bound between two states,\n     it can not possibly collide with an id from an earlier state.\n   *)\n  Definition bid_bound_between (s1 s2 : IRState) (bid : block_id) : Prop\n    := state_bound_between block_count incBlockNamed s1 s2 bid.\n\n  Lemma incBlockNamed_count_gen_injective :\n    count_gen_injective block_count incBlockNamed.\n  Proof.\n    unfold count_gen_injective.\n    intros s1 s1' s2 s2' name1 name2 id1 id2 GEN1 GEN2 H1 H2 H3.\n\n    Transparent incBlockNamed.    \n    inv GEN1.\n    inv GEN2.\n    Opaque incBlockNamed.\n    cbn in *.\n\n    intros CONTRA.\n    apply Name_inj in CONTRA.\n    apply valid_prefix_neq_differ in CONTRA; eauto.\n  Qed.\n\n  Lemma bid_bound_only_block_count :\n    forall s lc vc γ bid,\n      bid_bound s bid ->\n      bid_bound {| block_count := block_count s; local_count := lc; void_count := vc; Γ := γ |} bid.\n  Proof.\n    intros s lc vc γ bid BOUND.\n    destruct BOUND as (n1 & s1' & s1'' & N_S1 & COUNT_S1 & GEN_bid).\n    unfold bid_bound.\n    exists n1. exists s1'. exists s1''.\n    repeat (split; auto).\n  Qed.\n\n  Lemma bid_bound_between_only_block_count_r :\n    forall s1 s2 lc vc γ bid,\n      bid_bound_between s1 s2 bid ->\n      bid_bound_between s1 {| block_count := block_count s2; local_count := lc; void_count := vc; Γ := γ |} bid.\n  Proof.\n    intros s1 s2 lc vc γ bid BOUND.\n    destruct BOUND as (n1 & s1' & s1'' & N_S1 & COUNT_S1 & GEN_bid).\n    unfold bid_bound.\n    exists n1. exists s1'. exists s1''.\n    repeat (split; auto).\n  Qed.\n\n  Lemma bid_bound_mono : forall s1 s2 b,\n      bid_bound s1 b ->\n      (block_count s1 <= block_count s2)%nat ->\n      bid_bound s2 b.\n  Proof.\n    intros; eapply state_bound_mono; eauto.\n  Qed.\n\n  Lemma bid_bound_fresh :\n    forall (s1 s2 : IRState) (bid bid' : block_id),\n      bid_bound s1 bid ->\n      bid_bound_between s1 s2 bid' ->\n      bid ≢ bid'.\n  Proof.\n    intros s1 s2 bid bid' BOUND BETWEEN.\n    eapply state_bound_fresh; eauto.\n    apply incBlockNamed_count_gen_injective.\n  Qed.\n\n  Lemma bid_bound_fresh' :\n    forall (s1 s2 s3 : IRState) (bid bid' : block_id),\n      bid_bound s1 bid ->\n      (block_count s1 <= block_count s2)%nat ->\n      bid_bound_between s2 s3 bid' ->\n      bid ≢ bid'.\n  Proof.\n    intros s1 s2 s3 bid bid' BOUND COUNT BETWEEN.\n    destruct BOUND as (n1 & s1' & s1'' & N_S1 & COUNT_S1 & GEN_bid).\n    destruct BETWEEN as (n2 & sm' & sm'' & N_S2 & COUNT_Sm_ge & COUNT_Sm_lt & GEN_bid').\n\n    inversion GEN_bid.\n    destruct s1'. cbn in *.\n\n    inversion GEN_bid'.\n    intros CONTRA.\n    apply Name_inj in CONTRA.\n    apply valid_prefix_neq_differ in CONTRA; eauto.\n    cbn.\n    lia.\n  Qed.\n\n  Lemma bid_bound_bound_between :\n    forall (s1 s2 : IRState) (bid : block_id),\n      bid_bound s2 bid ->\n      ~(bid_bound s1 bid) ->\n      bid_bound_between s1 s2 bid.\n  Proof.\n    intros s1 s2 bid BOUND NOTBOUND.\n    destruct BOUND as (n1 & s1' & s1'' & N_S1 & COUNT_S1 & GEN_bid).\n    unfold bid_bound_between.\n    exists n1. exists s1'. exists s1''.\n    repeat (split; auto).\n    pose proof (NatUtil.lt_ge_dec (block_count s1') (block_count s1)) as [LT | GE].\n    - (* If this is the case, I must have a contradiction, which would mean that\n         bid_bound s1 bid... *)\n      assert (bid_bound s1 bid).\n      unfold bid_bound.\n      exists n1. exists s1'. exists s1''.\n      auto.\n      contradiction.\n    - auto.\n  Qed.\n\n  Lemma bid_bound_between_bound_earlier :\n    forall s1 s2 bid,\n      bid_bound_between s1 s2 bid ->\n      bid_bound s2 bid.\n  Proof.\n    intros s1 s2 bid BOUND.\n    unfold bid_bound_between, state_bound_between in BOUND.\n    destruct BOUND as (name & s1' & s2' & PREF' & COUNT1 & COUNT2 & GEN).\n    exists name. exists s1'. exists s2'.\n    repeat (split; auto).\n  Qed.\n\n  Lemma not_bid_bound_incBlockNamed :\n    forall s1 s2 n bid,\n      is_correct_prefix n ->\n      incBlockNamed n s1 ≡ inr (s2, bid) ->\n      ~ (bid_bound s1 bid).\n  Proof.\n    intros s1 s2 n bid NEND GEN BOUND.\n    unfold bid_bound, state_bound in BOUND.\n    destruct BOUND as (n' & s' & s'' & NEND' & COUNT & GEN').\n    Transparent incBlockNamed.\n    unfold incBlockNamed in *.\n    Opaque incBlockNamed.\n    cbn in *.\n    simp.\n    apply valid_prefix_string_of_nat_forward in H1; auto.\n    lia.\n  Qed.\n\n  Lemma bid_bound_name :\n    forall s1 n x,\n      is_correct_prefix n ->\n      bid_bound s1 (Name (n @@ string_of_nat x)) ->\n      (x < block_count s1)%nat.\n  Proof.\n    intros s1 s2 n PREF BOUND.\n    unfold bid_bound, state_bound in BOUND.\n    destruct BOUND as (name & s' & s'' & PREF' & COUNT & GEN).\n    cbn in GEN.\n    inv GEN.\n    eapply valid_prefix_string_of_nat_forward in H1; eauto; lia.\n  Qed.\n\n  Lemma bid_bound_incBlockNamed :\n    forall name s1 s2 bid,\n      is_correct_prefix name ->\n      incBlockNamed name s1 ≡ inr (s2, bid) ->\n      bid_bound s2 bid.\n  Proof.\n    intros name s1 s2 bid ENDS INC.\n    exists name. exists s1. exists s2.\n    repeat (split; auto).\n    erewrite incBlockNamed_block_count with (s':=s2); eauto.\n  Qed.\n\n  Lemma incBlockNamed_bound_between :\n    forall s1 s2 n bid,\n      is_correct_prefix n ->\n      incBlockNamed n s1 ≡ inr (s2, bid) ->\n      bid_bound_between s1 s2 bid.\n  Proof.\n    intros s1 s2 n bid NEND GEN.\n    apply bid_bound_bound_between.\n    - eapply bid_bound_incBlockNamed; eauto.\n    - eapply not_bid_bound_incBlockNamed; eauto.\n  Qed.\n\n  (* TODO: typeclasses for these mono lemmas to make automation easier? *)\n  Lemma bid_bound_incVoid_mono :\n    forall s1 s2 bid bid',\n      bid_bound s1 bid ->\n      incVoid s1 ≡ inr (s2, bid') ->\n      bid_bound s2 bid.\n  Proof.\n    intros s1 s2 bid bid' BOUND INC.\n    destruct BOUND as (n1 & s1' & s1'' & N_S1 & COUNT_S1 & GEN_bid).\n    unfold bid_bound.\n    exists n1. exists s1'. exists s1''.\n    intuition.\n    apply incVoid_block_count in INC.\n    lia.\n  Qed.\n\n  Lemma bid_bound_incLocal_mono :\n    forall s1 s2 bid bid',\n      bid_bound s1 bid ->\n      incLocal s1 ≡ inr (s2, bid') ->\n      bid_bound s2 bid.\n  Proof.\n    intros s1 s2 bid bid' BOUND INC.\n    destruct BOUND as (n1 & s1' & s1'' & N_S1 & COUNT_S1 & GEN_bid).\n    unfold bid_bound.\n    exists n1. exists s1'. exists s1''.\n    intuition.\n    apply incLocal_block_count in INC.\n    lia.\n  Qed.\n\n  Lemma bid_bound_between_sep :\n    ∀ (bid : block_id) s1 s2 s3,\n      bid_bound_between s1 s2 bid → ¬ (bid_bound_between s2 s3 bid).\n  Proof.\n    intros. cbn in H. red in H.\n    intro.\n    assert (((bid ≡ bid) -> False) -> False). auto. apply H1. clear H1.\n    eapply bid_bound_fresh; eauto.\n    destruct H as (? & ? & ? & ? & ? & ? & ?).\n    red. red. exists x. exists x0, x1. split; eauto.\n  Qed.\n\n  Lemma not_bid_bound_between :\n    forall bid s1 s2, bid_bound s1 bid -> not (bid_bound_between s1 s2 bid).\n  Proof.\n    repeat intro.\n    assert (((bid ≡ bid) -> False) -> False). auto. apply H1. clear H1.\n    eapply bid_bound_fresh; eauto.\n  Qed.\n\n  Lemma bid_bound_newLocalVar_mono :\n    forall s1 s2 bid bid' p x,\n      bid_bound s1 bid ->\n      newLocalVar p x s1 ≡ inr (s2, bid') ->\n      bid_bound s2 bid.\n  Proof.\n    intros s1 s2 bid bid' * BOUND INC.\n    destruct BOUND as (n1 & s1' & s1'' & N_S1 & COUNT_S1 & GEN_bid).\n    unfold bid_bound.\n    exists n1. exists s1'. exists s1''.\n    intuition.\n    apply newLocalVar_block_count in INC.\n    lia.\n  Qed.\n\n  Lemma bid_bound_incBlock_neq:\n    forall i i' bid bid',\n      incBlock i ≡ inr (i', bid) ->\n      bid_bound i bid' ->\n      bid ≢ bid'.\n  Proof.\n    intros.\n    destruct (rel_dec_p bid bid'); auto.\n    subst; exfalso.\n    cbn in H; inv H.\n    destruct H0 as (? & ? & ? & ? & ? & ?).\n    cbn in *.\n    inv H1.\n    apply valid_prefix_string_of_nat_forward in H4 as [? ?]; subst; cbn in *; auto.\n    lia.\n  Qed.\n\n Lemma bid_bound_incBlockNamed_mono :\n    forall name s1 s2 bid bid',\n      bid_bound s1 bid ->\n      incBlockNamed name s1 ≡ inr (s2, bid') ->\n      bid_bound s2 bid.\n  Proof.\n    intros name s1 s2 bid bid' BOUND INC.\n    destruct BOUND as (n1 & s1' & s1'' & N_S1 & COUNT_S1 & GEN_bid).\n    unfold bid_bound.\n    exists n1. exists s1'. exists s1''.\n    intuition.\n    apply incBlockNamed_block_count in INC.\n    lia.\n  Qed.\n\n  Lemma bid_bound_genNExpr_mono :\n    forall s1 s2 bid nexp e c,\n      bid_bound s1 bid ->\n      genNExpr nexp s1 ≡ inr (s2, (e, c)) ->\n      bid_bound s2 bid.\n  Proof.\n    intros s1 s2 bid nexp e c BOUND GEN.\n    apply genNExpr_block_count in GEN.\n    destruct BOUND as (n1 & s1' & s1'' & N_S1 & COUNT_S1 & GEN_bid).\n    unfold bid_bound.\n    exists n1. exists s1'. exists s1''.\n    repeat (split; auto).\n    rewrite GEN.\n    auto.\n  Qed.\n\n  Lemma bid_bound_genMExpr_mono :\n    forall s1 s2 bid mexp e c,\n      bid_bound s1 bid ->\n      genMExpr mexp s1 ≡ inr (s2, (e, c)) ->\n      bid_bound s2 bid.\n  Proof.\n    intros s1 s2 bid mexp e c BOUND GEN.\n    apply genMExpr_block_count in GEN.\n    destruct BOUND as (n1 & s1' & s1'' & N_S1 & COUNT_S1 & GEN_bid).\n    unfold bid_bound.\n    exists n1. exists s1'. exists s1''.\n    repeat (split; auto).\n    rewrite GEN.\n    auto.\n  Qed.\n\n  Lemma bid_bound_genAExpr_mono :\n    forall s1 s2 bid aexp e c,\n      bid_bound s1 bid ->\n      genAExpr aexp s1 ≡ inr (s2, (e, c)) ->\n      bid_bound s2 bid.\n  Proof.\n    intros s1 s2 bid nexp e c BOUND GEN.\n    apply genAExpr_block_count in GEN.\n    destruct BOUND as (n1 & s1' & s1'' & N_S1 & COUNT_S1 & GEN_bid).\n    unfold bid_bound.\n    exists n1. exists s1'. exists s1''.\n    repeat (split; auto).\n    rewrite GEN.\n    auto.\n  Qed.\n\n  Lemma bid_bound_genIR_mono :\n    forall s1 s2 bid op nextblock b bks,\n      bid_bound s1 bid ->\n      genIR op nextblock s1 ≡ inr (s2, (b, bks)) ->\n      bid_bound s2 bid.\n  Proof.\n    intros s1 s2 bid op nextblock b bks BOUND GEN.\n    apply genIR_block_count in GEN.\n    destruct BOUND as (n1 & s1' & s1'' & N_S1 & COUNT_S1 & GEN_bid).\n    unfold bid_bound.\n    exists n1. exists s1'. exists s1''.\n    repeat (split; auto).\n    lia.\n  Qed.\n\nEnd BidBound.\n\nHint Resolve incBlockNamed_count_gen_injective : CountGenInj.\n\nLtac solve_bid_bound :=\n  repeat\n    match goal with\n    | H: incBlockNamed ?msg ?s1 ≡ inr (?s2, ?bid) |-\n      bid_bound ?s2 ?bid =>\n      eapply bid_bound_incBlockNamed; try eapply H; solve_prefix\n    | H: incBlock ?s1 ≡ inr (?s2, ?bid) |-\n      bid_bound ?s2 ?bid =>\n      eapply bid_bound_incBlockNamed; try eapply H; solve_prefix\n\n    | H: incBlockNamed ?msg ?s1 ≡ inr (_, ?bid) |-\n      ~(bid_bound ?s1 ?bid) =>\n      eapply gen_not_state_bound; try eapply H; solve_prefix\n    | H: incBlock ?s1 ≡ inr (_, ?bid) |-\n      ~(bid_bound ?s1 ?bid) =>\n      eapply gen_not_state_bound; try eapply H; solve_prefix\n\n    (* Monotonicity *)\n    | |- bid_bound {| block_count := block_count ?s; local_count := ?lc; void_count := ?vc; Γ := ?γ |} ?bid =>\n      apply bid_bound_only_block_count\n\n    | H: incVoid ?s1 ≡ inr (?s2, _) |-\n      bid_bound ?s2 _ =>\n      eapply bid_bound_incVoid_mono; try eapply H\n    | H: incLocal ?s1 ≡ inr (?s2, _) |-\n      bid_bound ?s2 _ =>\n      eapply bid_bound_incLocal_mono; try eapply H\n    | H: incBlockNamed _ ?s1 ≡ inr (?s2, _) |-\n      bid_bound ?s2 _ =>\n      eapply bid_bound_incBlockNamed_mono; try eapply H\n    | H: incBlock ?s1 ≡ inr (?s2, _) |-\n      bid_bound ?s2 _ =>\n      eapply bid_bound_incBlockNamed_mono; try eapply H\n    | H: genNExpr ?n ?s1 ≡ inr (?s2, _) |-\n      bid_bound ?s2 _ =>\n      eapply bid_bound_genNExpr_mono; try eapply H\n    | H: genMExpr ?n ?s1 ≡ inr (?s2, _) |-\n      bid_bound ?s2 _ =>\n      eapply bid_bound_genMExpr_mono; try eapply H\n    | H: genAExpr ?n ?s1 ≡ inr (?s2, _) |-\n      bid_bound ?s2 _ =>\n      eapply bid_bound_genAExpr_mono; try eapply H\n    | H: genIR ?op ?n ?s1 ≡ inr (?s2, _) |-\n      bid_bound ?s2 _ =>\n      eapply bid_bound_genIR_mono; try eapply H\n    | H : resolve_PVar _ _ ≡ inr _ |- _ =>\n      apply resolve_PVar_state in H; subst\n    end.\n\n\nLtac invert_err2errs :=\n  match goal with\n  | H : ErrorWithState.err2errS (MInt64asNT.from_nat ?n) ?s1 ≡ inr (?s2, _) |- _ =>\n    destruct (MInt64asNT.from_nat n); inversion H; subst\n  | H : ErrorWithState.err2errS (inl _) _ ≡ inr _ |- _ =>\n    inversion H\n  | H : ErrorWithState.err2errS (inr _) _ ≡ inr _ |- _ =>\n    inversion H; subst\n  end.\n\nLtac block_count_replace :=\n  repeat match goal with\n         | H : incVoid ?s1 ≡ inr (?s2, ?bid) |- _\n           => apply incVoid_block_count in H; cbn in H\n         | H : incBlockNamed ?name ?s1 ≡ inr (?s2, ?bid) |- _\n           => apply incBlockNamed_block_count in H; cbn in H\n         | H : incBlock ?s1 ≡ inr (?s2, ?bid) |- _\n           => apply incBlockNamed_block_count in H; cbn in H\n         | H : incLocal ?s1 ≡ inr (?s2, ?bid) |- _\n           => apply incLocal_block_count in H; cbn in H\n         | H: genNExpr ?n ?s1 ≡ inr (?s2, _) |- _\n           => eapply genNExpr_block_count in H; cbn in H\n         | H: genMExpr ?n ?s1 ≡ inr (?s2, _) |- _\n           => eapply genMExpr_block_count in H; cbn in H\n         | H: genAExpr ?n ?s1 ≡ inr (?s2, _) |- _\n           => eapply genAExpr_block_count in H; cbn in H\n         | H: genIR ?op ?nextblock ?s1 ≡ inr (?s2, _) |- _\n           => eapply genIR_block_count in H; cbn in H\n         end.\n\nLtac solve_block_count :=\n  match goal with\n  | |- (block_count ?s1 <= block_count ?s2)%nat\n    => block_count_replace; cbn; lia\n  | |- (block_count ?s1 >= block_count ?s2)%nat\n    => block_count_replace; cbn; lia\n  end.\n\nLtac solve_not_bid_bound :=\n  match goal with\n  | H: incBlockNamed ?name ?s1 ≡ inr (?s2, ?bid) |-\n    ~(bid_bound ?s3 ?bid) =>\n    eapply (not_id_bound_gen_mono incBlockNamed_count_gen_injective); [eassumption |..]\n  | H: incBlock ?s1 ≡ inr (?s2, ?bid) |-\n    ~(bid_bound ?s3 ?bid) =>\n    eapply (not_id_bound_gen_mono incBlockNamed_count_gen_injective); [eassumption |..]\n  end.\n\nLtac solve_count_gen_injective :=\n  match goal with\n  | |- count_gen_injective _ _\n    => eauto with CountGenInj\n  end.\n\nLtac big_solve :=\n  repeat\n    (try invert_err2errs;\n     try solve_block_count;\n     try solve_not_bid_bound;\n     try solve_prefix;\n     try solve_count_gen_injective;\n     try match goal with\n         | |- Forall _ (?x::?xs) =>\n           apply Forall_cons; eauto\n         | |- bid_bound_between ?s1 ?s2 ?bid =>\n           eapply bid_bound_bound_between; solve_bid_bound\n         | |- bid_bound_between ?s1 ?s2 ?bid ∨ ?bid ≡ ?nextblock =>\n           try auto; try left\n         end).\n\nLemma bid_bound_genIR_entry :\n  forall op s1 s2 nextblock bid bks,\n    genIR op nextblock s1 ≡ inr (s2, (bid, bks)) ->\n    bid_bound s2 bid.\nProof.\n  induction op;\n    intros s1 s2 nextblock b bks GEN.\n  10: {\n    cbn in GEN; simp.\n    eapply IHop1; eauto.\n  }\n  all: cbn in GEN; simp; solve_bid_bound.\nQed.\n\nSection Inputs.\n\n  (* Lemmas about the inputs to blocks *)\n  Lemma inputs_bound_between :\n    forall (op : DSHOperator) (s1 s2 : IRState) (nextblock op_entry : block_id) (bk_op : list (LLVMAst.block typ)),\n      genIR op nextblock s1 ≡ inr (s2, (op_entry, bk_op)) ->\n      Forall (bid_bound_between s1 s2) (inputs (convert_typ [ ] bk_op)).\n  Proof.\n    induction op;\n      intros s1 s2 nextblock op_entry bk_op GEN;\n      pose proof GEN as BACKUP_GEN;\n      cbn in GEN; simp; cbn.\n    all: try (solve [big_solve]).\n    - big_solve; cbn in *; try solve_not_bid_bound; cbn in *; big_solve.\n\n      rewrite convert_typ_ocfg_app.\n\n      (* TODO: clean this up *)\n      unfold tfmap.\n      rewrite map_app.\n\n      apply Forall_app.\n      split.\n      + eapply all_state_bound_between_shrink.\n        eapply IHop; eauto.\n        solve_block_count.\n        solve_block_count.\n      + cbn.\n        rewrite List.Forall_cons_iff.\n        split.\n        2: { apply List.Forall_nil. }\n        big_solve.\n    - apply Forall_cons.\n      + big_solve.\n      + eapply Forall_impl.\n        apply bid_bound_between_only_block_count_r.\n        eapply all_state_bound_between_shrink.\n        eapply IHop; eapply Heqs0.\n        cbn. auto.\n        block_count_replace.\n        lia.\n    - rewrite add_comment_inputs_typ.\n      rewrite convert_typ_ocfg_app.\n\n      unfold inputs.\n      setoid_rewrite map_app.\n\n      apply Forall_app.\n      split.\n      + eapply all_state_bound_between_shrink.\n        eapply IHop1; eauto.\n        all: solve_block_count.\n      + eapply all_state_bound_between_shrink.\n        eapply IHop2; eauto.\n        all: solve_block_count.\n  Qed.\n\n  Lemma inputs_not_earlier_bound :\n    forall (op : DSHOperator) (s1 s2 s3 : IRState) (bid nextblock op_entry : block_id) (bk_op : list (LLVMAst.block typ)),\n      bid_bound s1 bid ->\n      (block_count s1 <= block_count s2)%nat ->\n      genIR op nextblock s2 ≡ inr (s3, (op_entry, bk_op)) ->\n      Forall (fun x => x ≢ bid) (inputs (convert_typ [ ] bk_op)).\n  Proof.\n    intros op s1 s2 s3 bid nextblock op_entry bk_op BOUND COUNT GEN.\n    pose proof (inputs_bound_between _ _ _ GEN) as BETWEEN.\n    apply Forall_forall.\n    intros x H.\n    assert (bid ≢ x) as BIDX; auto.\n    { eapply state_bound_fresh'.\n      - apply incBlockNamed_count_gen_injective.\n      - assert (bid_bound_between s2 s3 x).\n        eapply Forall_forall. apply BETWEEN.\n        auto.\n        apply BOUND.\n      - apply COUNT.\n      - eapply Forall_forall.\n        apply BETWEEN.\n        auto.\n    }\n  Qed.\n\n  (* TODO: may not actually needs this. *)\n  Lemma inputs_nextblock :\n    forall (op : DSHOperator) (s1 s2 s3 : IRState) (nextblock op_entry : block_id) (bk_op : list (LLVMAst.block typ)),\n      bid_bound s1 nextblock ->\n      (block_count s1 <= block_count s2)%nat ->\n      genIR op nextblock s2 ≡ inr (s3, (op_entry, bk_op)) ->\n      Forall (fun bid => bid ≢ nextblock) (inputs (convert_typ [ ] bk_op)).\n  Proof.\n    intros op s1 s2 s3 nextblock op_entry bk_op BOUND COUNT GEN.\n    eapply inputs_not_earlier_bound; eauto.\n  Qed.\nEnd Inputs.\n\nSection Outputs.\n  Lemma entry_bound_between :\n    forall (op : DSHOperator) (s1 s2 : IRState) (nextblock op_entry : block_id) (bk_op : list (LLVMAst.block typ)),\n      genIR op nextblock s1 ≡ inr (s2, (op_entry, bk_op)) ->\n      bid_bound_between s1 s2 op_entry.\n  Proof.\n    induction op;\n      intros s1 s2 nextblock op_entry bk_op GEN;\n      pose proof GEN as BACKUP_GEN;\n      cbn in GEN; simp; cbn.\n    all: try (solve [big_solve]).\n\n    apply IHop1 in Heqs2.\n    eapply state_bound_between_shrink; eauto.\n    solve_block_count.\n  Qed.\n\nOpaque incBlockNamed.\nOpaque incVoid.\nOpaque incLocal.\n\n  \n  Lemma outputs_bound_between :\n    forall (op : DSHOperator) (s1 s2 : IRState) (nextblock op_entry : block_id) (bk_op : list (LLVMAst.block typ)),\n      genIR op nextblock s1 ≡ inr (s2, (op_entry, bk_op)) ->\n      Forall (fun bid => bid_bound_between s1 s2 bid \\/ bid ≡ nextblock) (outputs (convert_typ [ ] bk_op)).\n  Proof.\n    induction op;\n      intros s1 s2 nextblock op_entry bk_op GEN;\n      pose proof GEN as BACKUP_GEN;\n      cbn in GEN; simp; cbn.\n    all: try (solve [big_solve]).\n    - cbn.\n      clear BACKUP_GEN.\n      cbn* in *; simp.\n      rename i into s1, i6 into s2.\n      rewrite convert_typ_ocfg_app.\n      rewrite fold_left_app.\n      cbn.\n      clean_goal.\n      \n      assert (bid_bound_between s1 s2 b2) as B2.\n      { eapply incBlockNamed_bound_between in Heqs3.\n        eapply state_bound_between_shrink; eauto.\n        solve_block_count.\n        solve_block_count.\n        reflexivity.\n      }\n\n      assert (bid_bound_between s1 s2 b0) as B0.\n      { eapply entry_bound_between in Heqs2.\n        eapply state_bound_between_shrink; eauto.\n        solve_block_count.\n        solve_block_count.\n      }\n      \n      rewrite outputs_acc.\n      (* Can probably prove stuff for b2 and nextblock to save space *)\n      rewrite Forall_app.\n      split.\n      rewrite Forall_app.\n      split.\n\n      + auto.\n      + epose proof (IHop _ _ _ _ _ Heqs2).\n\n        (* TODO: may want to pull this out as a lemma *)\n        eapply Forall_impl; [| eapply H].\n        intros bid BOUND.\n        destruct BOUND.\n        * left.\n          eapply state_bound_between_shrink; eauto.\n          solve_block_count.\n          solve_block_count.\n        * left; subst.\n          eapply incBlockNamed_bound_between in Heqs1.\n          eapply state_bound_between_shrink; eauto.\n          solve_block_count.\n          reflexivity.\n      + auto.\n    -\n      (* Should show me that the outputs of l (genIR op result) are all bound between s1 and i *)\n      epose proof (IHop _ _ _ _ _ Heqs0).\n      cbn in H.\n      unfold outputs in H.\n\n      cbn in Heqs; inversion Heqs; subst.\n\n      rewrite outputs_acc.\n      apply Forall_app.\n      split.\n      + apply Forall_cons; [|apply Forall_nil].\n        cbn in Heqs.\n        left.\n        eapply entry_bound_between in Heqs0.\n        eapply state_bound_between_shrink; eauto.\n        cbn. solve_block_count.\n      +\n        (* TODO: may want to pull this out as a lemma *)\n        assert (forall bid, bid_bound_between s1 i bid \\/ bid ≡ nextblock -> bid_bound_between s1 i1 bid \\/ bid ≡ nextblock) as WEAKEN.\n        { intros bid BOUND.\n          destruct BOUND.\n          - left.\n            eapply state_bound_between_shrink; eauto.\n            solve_block_count.\n          - right; auto.\n        }\n\n        eapply Forall_impl.\n        * eapply WEAKEN.\n        * eauto.\n    - rewrite add_comment_outputs_typ.\n      rewrite convert_typ_ocfg_app.\n      setoid_rewrite outputs_app.\n      apply Forall_app.\n      split.\n      +\n        (* TODO: may want to pull this out as a lemma *)\n        assert (forall bid, bid_bound_between i s2 bid \\/ bid ≡ b -> bid_bound_between s1 s2 bid \\/ bid ≡ nextblock) as WEAKEN.\n        { intros bid BOUND.\n          destruct BOUND.\n          - left.\n            eapply state_bound_between_shrink; eauto.\n            solve_block_count.\n          - left.\n            eapply entry_bound_between in Heqs0.\n            subst.\n            eapply state_bound_between_shrink; eauto.\n            solve_block_count.\n        }\n\n        eapply Forall_impl.\n        * eapply WEAKEN.\n        * eauto.\n      +\n        (* TODO: may want to pull this out as a lemma *)\n        assert (forall bid, bid_bound_between s1 i bid \\/ bid ≡ nextblock -> bid_bound_between s1 s2 bid \\/ bid ≡ nextblock) as WEAKEN.\n        { intros bid BOUND.\n          destruct BOUND.\n          - left.\n            eapply state_bound_between_shrink; eauto.\n            solve_block_count.\n          - right; auto.\n        }\n\n        eapply Forall_impl.\n        * eapply WEAKEN.\n        * eauto.\n  Qed.\nEnd Outputs.\n\nLtac get_block_count_hyps :=\n  repeat\n    match goal with\n    (* | H: incBlockNamed ?n ?s1 ≡ inr (?s2, _) |- _ => *)\n      (* apply incBlockNamed_block_count in H *)\n    (* | H: incLocalNamed ?n ?s1 ≡ inr (?s2, _) |- _ => *)\n    (* apply incLocalNamed_block_count in H *)\n    | H: resolve_PVar _ _ ≡ _ |- _ => apply resolve_PVar_state in H\n    | H: incVoid ?s1 ≡ inr (?s2, _) |- _ =>\n      apply incVoid_block_count in H\n    | H: incLocal ?s1 ≡ inr (?s2, _) |- _ =>\n      apply incLocal_block_count in H\n    | H : genNExpr _ _ ≡ inr _ |- _ =>\n      apply genNExpr_local_count in H\n    | H: genMExpr ?m ?s1 ≡ inr (?s2, _) |- _ =>\n      apply genMExpr_block_count in H\n    | H: genAExpr ?a ?s1 ≡ inr (?s2, _) |- _ =>\n      apply genAExpr_block_count in H\n    | H: genIR ?op ?id ?s1 ≡ inr (?s2, _) |- _ =>\n      apply genIR_block_count in H\n    end.\n\n(* This establishes that the generated code does not contain any two blocks with the same id. *)\nTransparent incBlockNamed.\nLemma generates_wf_ocfg_bids :\n  ∀ (op : DSHOperator) (s1 s2 : IRState) (nextblock b : block_id) (bk_op : list (LLVMAst.block typ)),\n    bid_bound s1 nextblock ->\n    genIR op nextblock s1 ≡ inr (s2, (b, bk_op)) →\n    wf_ocfg_bid bk_op.\nProof.\n  induction op; intros * NEXT GEN.\n  - cbn* in *; simp; cbn.\n    eapply wf_ocfg_bid_singleton.\n  - cbn* in *; simp; cbn in *.\n    eapply wf_ocfg_bid_singleton.\n  - destruct NEXT as (? & [?bid ? ? ?] & [?bid ? ? ?] & ? & ? & ?).\n    cbn* in *.\n    simp.\n    cbn* in *; simp; cbn in *.\n    clean_goal.\n    get_block_count_hyps; subst; cbn in *.\n    repeat match goal with\n           | h: IRState |- _ => destruct h as [?bid ? ? ?]\n           end; cbn in *.\n    subst.\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition;\n        match goal with\n        | h: Name _ ≡ Name _ |- _ => apply Name_inj in h; inv h\n        end.\n    }\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition;\n        match goal with\n        | h: Name _ ≡ Name _ |- _ => apply Name_inj in h; inv h\n        end.\n    }\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition;\n        match goal with\n        | h: Name _ ≡ Name _ |- _ => apply Name_inj in h; inv h\n        end.\n    }\n    eapply wf_ocfg_bid_singleton.\n  - destruct NEXT as (? & [?bid ? ? ?] & [?bid ? ? ?] & ? & ? & ?).\n    cbn* in *.\n    simp.\n    cbn* in *; simp; cbn in *.\n    clean_goal.\n    get_block_count_hyps; subst; cbn in *.\n    repeat match goal with\n           | h: IRState |- _ => destruct h as [?bid ? ? ?]\n           end; cbn in *.\n    subst.\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition;\n        match goal with\n        | h: Name _ ≡ Name _ |- _ => apply Name_inj in h; inv h\n        end.\n    }\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition;\n        match goal with\n        | h: Name _ ≡ Name _ |- _ => apply Name_inj in h; inv h\n        end.\n    }\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition;\n        match goal with\n        | h: Name _ ≡ Name _ |- _ => apply Name_inj in h; inv h\n        end.\n    }\n    eapply wf_ocfg_bid_singleton.\n\n  - destruct NEXT as (? & [?bid ? ? ?] & [?bid ? ? ?] & ? & ? & ?).\n    cbn* in *.\n    simp.\n    cbn* in *; simp; cbn in *.\n    clean_goal.\n    get_block_count_hyps; subst; cbn in *.\n    repeat match goal with\n           | h: IRState |- _ => destruct h as [?bid ? ? ?]\n           end; cbn in *.\n    subst.\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition;\n        match goal with\n        | h: Name _ ≡ Name _ |- _ => apply Name_inj in h; inv h\n        end.\n    }\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition;\n        match goal with\n        | h: Name _ ≡ Name _ |- _ => apply Name_inj in h; inv h\n        end.\n    }\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition;\n        match goal with\n        | h: Name _ ≡ Name _ |- _ => apply Name_inj in h; inv h\n        end.\n    }\n    eapply wf_ocfg_bid_singleton.\n\n  - destruct NEXT as (? & [?bid ? ? ?] & [?bid ? ? ?] & ? & ? & ?).\n    cbn* in *.\n    simp.\n    cbn* in *; simp; cbn in *.\n    clean_goal.\n    get_block_count_hyps; subst; cbn in *.\n    repeat match goal with\n           | h: IRState |- _ => destruct h as [?bid ? ? ?]\n           end; cbn in *.\n    subst.\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition;\n        match goal with\n        | h: Name _ ≡ Name _ |- _ => apply Name_inj in h; inv h\n        end.\n    }\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition;\n        match goal with\n        | h: Name _ ≡ Name _ |- _ => apply Name_inj in h; inv h\n        end.\n    }\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition;\n        match goal with\n        | h: Name _ ≡ Name _ |- _ => apply Name_inj in h; inv h\n        end.\n    }\n    eapply wf_ocfg_bid_singleton.\n\n  - cbn* in *.\n    simp.\n    clean_goal.\n\n    pose proof Heqs1.\n    eapply inputs_bound_between in H.\n\n    apply IHop in Heqs1.\n    2:{\n      eapply bid_bound_incBlockNamed with (name := \"Loop_lcont\")\n                                         (s1 := {|\n                                             block_count := (block_count i);\n                                             local_count := S (local_count i);\n                                             void_count := void_count i;\n                                             Γ := (ID_Local (Name (\"Loop_i\" @@ string_of_nat (local_count i))), TYPE_I 64%N) :: Γ i |}); reflexivity.\n    }\n    clear IHop; clean_goal.\n    cbn in *.\n    simp.\n    cbn in *.\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition.\n      match goal with\n      | h: Name _ ≡ Name _ |- _ =>\n        apply Name_inj in h;\n          first [now inv h | apply valid_prefix_string_of_nat_forward in h as [abs _]; intuition]\n      end.\n\n      rewrite map_app in H1.\n      eapply in_app_or in H1.\n      destruct H1.\n      - rewrite inputs_convert_typ in H.\n\n        eapply Forall_forall in H0; eauto.\n        eapply bid_bound_between_bound_earlier in H0.\n\n        eapply bid_bound_name in H0; [lia | solve_prefix].\n      - cbn in H0. destruct H0; inversion H0.\n    }\n\n    (* TODO: Automate this... *)\n    eapply wf_ocfg_bid_cons'.\n    { cbn.\n      intuition.\n\n      rewrite inputs_app in H0.\n      eapply in_app_or in H0.\n      destruct H0.\n      - rewrite inputs_convert_typ in H.\n\n        eapply Forall_forall in H0; eauto.\n        eapply bid_bound_between_bound_earlier in H0.\n\n        eapply bid_bound_name in H0; [lia | solve_prefix].\n      - cbn in H0. destruct H0; inversion H0.\n    }\n    \n    unfold wf_ocfg_bid.\n    rewrite inputs_app. cbn.\n    apply Coqlib.list_norepet_append; eauto.\n\n    { constructor.\n      intros CONTRA; inv CONTRA.\n      constructor.\n    }\n\n    unfold Coqlib.list_disjoint.\n    intros x y H0 H1.\n\n    cbn in H1. destruct H1; inv H1.\n    \n    rewrite inputs_convert_typ in H.\n\n    eapply Forall_forall in H0; eauto.\n\n    destruct H0 as (name & s' & s'' & PREF & COUNT & GEN).\n    cbn in GEN; inv GEN.\n    intros NAME. inv H1.\n    rename H4 into NAME.\n    apply Name_inj in NAME.\n    eapply valid_prefix_string_of_nat_forward in NAME; eauto.\n    destruct NAME; subst.\n    lia.\n\n  - rename nextblock into entryblock, b into nextblock.\n    simpl in GEN.\n    break_match_hyp; [simp |].\n    inv GEN.\n    break_match_hyp; [simp |].\n    destruct s1 as [bid1  lid1  void1  Γ1]; cbn in *.\n    destruct NEXT as (? & [?bid ? ? ?] & [?bid ? ? ?] & ? & ? & ?); cbn in *.\n    inv H1; cbn in *.\n    destruct p as [s' [bblock bcode]].\n    destruct s' as [bid2  lid2  void2  Γ2]; cbn in *.\n    simp.\n    cbn* in *; simp; cbn in *.\n    clean_goal.\n    cbn* in *; simp; cbn in *.\n    generalize Heqs0; intros GEN.\n    apply genIR_block_count in Heqs0.\n    cbn in *.\n    assert (BOUND:bid_bound\n                    {|\n                      block_count := bid1;\n                      local_count := S lid1;\n                      void_count := void1;\n                      Γ := (ID_Local (Name (\"a\" @@ string_of_nat lid1)),\n                            TYPE_Pointer (TYPE_Array (Z.to_N (Int64.intval size)) TYPE_Double)) :: Γ1 |}\n                    (Name (x @@ string_of_nat bid))).\n    {\n      do 2 red.\n      exists x.\n      exists {|\n          block_count := bid;\n          local_count := S lid1;\n          void_count := void1;\n          Γ := (ID_Local (Name (\"a\" @@ string_of_nat lid1)),\n                TYPE_Pointer (TYPE_Array (Z.to_N (Int64.intval size)) TYPE_Double)) :: Γ1 |}.\n      eexists; repeat split; cbn; eauto.\n    }\n    generalize GEN; intros WF;\n    apply IHop in WF; auto; clear IHop.\n    apply wf_ocfg_bid_cons'; auto; clear WF.\n    cbn.\n    cbn in *; intros abs; apply ListUtil.in_map_elim in abs as (? & ? & ?).\n    cbn in *.\n    clean_goal.\n\n    eapply inputs_bound_between in GEN.\n    rewrite inputs_convert_typ in GEN.\n\n    assert (In (blk_id x0) (map blk_id bcode)).\n    { apply in_map; eauto. }\n\n    eapply Forall_forall in GEN; eauto.\n    rewrite <- H2 in GEN.\n    destruct GEN as (n & s' & s'' & PREF & COUNT1 & COUNT2 & GEN').\n    cbn in *.\n\n    inv GEN'.\n    eapply valid_prefix_string_of_nat_forward in H6; eauto.\n    destruct H6; subst.\n    lia.\n  - rename nextblock into entryblock, b into nextblock.\n    simpl in GEN.\n    break_match_hyp; [simp |].\n    inv GEN.\n    break_match_hyp; [simp |].\n    destruct s1 as [bid1  lid1  void1  Γ1]; cbn in *.\n    destruct NEXT as (? & [?bid ? ? ?] & [?bid ? ? ?] & ? & ? & ?); cbn in *.\n    inv H1; cbn in *.\n    destruct p as [s' [bblock bcode]].\n    destruct s' as [bid2  lid2  void2  Γ2]; cbn in *.\n    simp.\n    cbn* in *; simp; cbn in *.\n    clean_goal.\n    cbn* in *; simp; cbn in *.\n    generalize Heqs0; intros GEN.\n    apply resolve_PVar_state in Heqs0.\n    inv Heqs0.\n    cbn in *.\n\n    apply wf_ocfg_bid_cons'; cbn.\n    { intros CONTRA.\n      destruct CONTRA; inv H1.\n      inv H2.\n      inv H2.\n      inv H1.\n      auto.\n    }\n\n    apply wf_ocfg_bid_cons'; cbn.\n    { intros CONTRA.\n      destruct CONTRA; inv H1.\n      inv H2.\n      inv H2.\n    }\n\n    apply wf_ocfg_bid_cons'; cbn.\n    { intros CONTRA.\n      destruct CONTRA; auto.\n\n      rename H1 into NAME.\n      eapply Name_inj in NAME.\n      eapply valid_prefix_string_of_nat_forward in NAME; eauto.\n      destruct NAME. inv H2.\n    }\n\n    unfold wf_ocfg_bid.\n    cbn.\n    constructor.\n    auto.\n    constructor.\n  - rename nextblock into entryblock, b into nextblock.\n    simpl in GEN.\n    break_match_hyp; [simp |].\n    inv GEN.\n    break_match_hyp; [simp |].\n    destruct s1 as [bid1  lid1  void1  Γ1]; cbn in *.\n    destruct NEXT as (? & s' & s'' & ? & ? & ?); cbn in *.\n    inv H1; cbn in *.\n    destruct p as [s''' [bblock bcode]].\n    simp.\n    cbn* in *; simp; cbn in *.\n    clean_goal.\n    cbn* in *; simp; cbn in *.\n    generalize Heqs0; intros GEN.\n    apply genIR_block_count in Heqs0.\n    cbn in *.\n\n    unfold wf_ocfg_bid.\n    unfold add_comment; cbn.\n    break_match_goal.\n    constructor.\n    cbn.\n\n    pose proof Heqs1 as OP1BOUND; eapply inputs_bound_between in OP1BOUND.\n    pose proof GEN as OP2BOUND; eapply inputs_bound_between in OP2BOUND.\n\n    eapply IHop1 in Heqs1.\n    eapply IHop2 in GEN.\n\n    change (blk_id b :: map blk_id l0) with (map blk_id (b :: l0)).\n    rewrite <- Heql0.\n\n    rewrite map_app.\n    rewrite inputs_convert_typ in *.\n\n    {  apply Coqlib.list_norepet_append_commut.\n       unfold wf_ocfg_bid in *.\n       eapply state_bound_between_disjoint_norepet; eauto.\n       apply incBlockNamed_count_gen_injective.\n    }\n\n    { exists x. do 2 eexists.\n      repeat split; eauto.\n    }\n\n    { eapply bid_bound_genIR_entry; eauto.\n    }\nQed.\n\nLemma genWhileLoop_entry_in_scope : forall op b s1 s2 entry_body bodyV,\n    genIR op b s1 ≡ inr (s2, (entry_body, bodyV)) ->\n    In entry_body (inputs bodyV).\nProof.\n  induction op; intros *; try (cbn; intros GEN; clear -GEN; simp; cbn; auto; fail).\n  cbn; intros GEN; simp.\n  rewrite add_comment_inputs, inputs_app.\n  apply ListUtil.in_appl; eauto.\nQed.\n\n", "meta": {"author": "vzaliva", "repo": "helix", "sha": "5d0a71df99722d2011c36156f12b04875df7e1cb", "save_path": "github-repos/coq/vzaliva-helix", "path": "github-repos/coq/vzaliva-helix/helix-5d0a71df99722d2011c36156f12b04875df7e1cb/coq/LLVMGen/BidBound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.2152131689901}}
{"text": "Require Import VST.msl.Axioms.\nRequire Import compcert.common.Memory.\nRequire Import VST.sepcomp.semantics.\n\nModule FSem.\nRecord t M TM := mk {\n    F : forall C, @CoreSemantics C M -> @CoreSemantics C TM\n  ; E : TM -> M\n  ; P : TM -> TM -> Prop\n  ; step  : forall C sem c m c' m',\n            @corestep _ _ (F C sem) c m c' m' =\n           (@corestep _ _ sem c (E m) c' (E m') /\\ P m m')\n(*  ; init : forall C sem n m m' v vl q,\n     initial_core (F C sem) n m q m' v vl <->\n     initial_core sem n (E m) q (E m') v vl*) (* Should this really be true? *)\n  ; atext  : forall C sem c m,\n      at_external (F C sem) c m = at_external sem c (E m)\n  ; aftext : forall C sem ret c m,\n      after_external (F C sem) ret c m = after_external sem ret c (E m)\n  ; halted : forall C sem, halted (F C sem) = halted sem\n  }.\nEnd FSem.\n\nModule IdFSem.\nProgram Definition t M : FSem.t M M :=\n  FSem.mk M M (fun C sem => sem) id (fun _ _ => True) _ _ _ _.\nNext Obligation.\napply prop_ext.\nsplit; intros H.\nsplit; auto.\ndestruct H; auto.\nQed.\n(*Next Obligation.\nintuition.\nQed.*)\nEnd IdFSem.\n\nRequire Import VST.veric.juicy_mem.\nRequire Import VST.veric.juicy_extspec.\nRequire Import VST.veric.compcert_rmaps.\nRequire Import VST.veric.own.\n\nModule JuicyFSem.\nProgram Definition t : FSem.t mem juicy_mem :=\n  FSem.mk mem juicy_mem (@juicy_core_sem) m_dry\n    (fun jm jm' => resource_decay (Mem.nextblock (m_dry jm)) (m_phi jm) (m_phi jm') /\\\n       ageable.level jm = S (ageable.level jm') /\\\n       ghost_of (m_phi jm') = ghost_approx jm' (ghost_of (m_phi jm)))\n    _ _ _ _.\nEnd JuicyFSem.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/veric/jstep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.21521316628245754}}
{"text": "(* Other library imports *)\nAdd LoadPath \"../libs\".\nAdd LoadPath \"../libs/CompCert-Toolkit\".\nRequire Import Tactics.\nRequire Import Bits.\nRequire Import Consider.\n\nRequire Import Flocq.Appli.Fappli_IEEE_bits.\n\nRequire Import Coqlib.\nRequire Import Axioms.\n\n\n(* Illvm imports *)\nRequire Import Utility.\nRequire Import IllvmAST.\nRequire Import TargetData.\n\n\n(* ---------------------------------------------------------------------- *)\n(* Run-time tags and values *)\n\n(* Tags that a run-time value can have *)\nInductive rt_tag :=\n| RT_int : forall sz, (sz < MAX_I_BITS)%nat -> Word.int sz -> rt_tag\n| RT_fun : lab -> rt_tag. (* We can get rid of this ... *)\n\n(* Floats, doubles and pointers are just bit-vectors. *) \nDefinition RT_float (f:float_t) := RT_int 31 lt_31_MAX_I_BITS (Word.repr (Word.unsigned f)).\nDefinition RT_double (d:double_t) := RT_int 63 lt_63_MAX_I_BITS (Word.repr (Word.unsigned d)).\nDefinition RT_ptr i := RT_int WORDSIZE_BITS lt_63_MAX_I_BITS i.\n \n(* Run-time value, note that its flat, i.e., the typ's give it structure. *)\nDefinition rt_val := list rt_tag.\n\n(* Convert a tag into a run-time value *)\nDefinition tag2rt (tag:rt_tag) := tag :: nil.\n\n(* Size of a tag in bytes *)\nDefinition size_rttag (lo:layout) (tag:rt_tag) : Z :=\n  match tag with\n    | RT_int sz pf _ => size_ftyp lo (Ftyp_int sz pf)\n    | RT_fun _ => size_ftyp lo (Ftyp_fun nil nil None)\n  end.\nDefinition size_rttag_nat (lo:layout) (tag:rt_tag) : nat :=\n  nat_of_Z (size_rttag lo tag).\n\n(* Random bit-pattern generator. *)\nParameter UNDEF_STREAM : unit -> Z.\n\nFixpoint undef_ls ts :=\n  match ts with\n    | nil => nil\n    | t::ts =>\n      match t with\n        | Ftyp_float => (RT_float (Word.repr (UNDEF_STREAM tt)) :: undef_ls ts)\n        | Ftyp_double => (RT_double (Word.repr (UNDEF_STREAM tt)) :: undef_ls ts)\n        | Ftyp_int sz pf => (RT_int sz pf (Word.repr (UNDEF_STREAM tt)) :: undef_ls ts)\n        | Ftyp_ptr _ _ => (RT_ptr (Word.repr (UNDEF_STREAM tt)) :: undef_ls ts)\n        | Ftyp_fun _ _ _ => (RT_fun (Word.repr (UNDEF_STREAM tt)) :: undef_ls ts)\n        | Ftyp_ptrU _ _ => (RT_ptr (Word.repr (UNDEF_STREAM tt)) :: undef_ls ts)\n      end\n  end.\n\n(* Convert a constant to rt_val *)\nDefinition const2rtv (c:const) : rt_val :=\n  match c with\n    | Const_null => (RT_ptr (Word.repr 0) :: nil)\n    | Const_nullU => (RT_ptr (Word.repr 0) :: nil)\n    | Const_float f => (RT_float f :: nil)\n    | Const_double d => (RT_double d :: nil)\n    | Const_int sz pf i => (RT_int sz pf i :: nil)\n    | Const_fun l => (RT_fun l :: nil)\n    | Const_undef ts => undef_ls ts\n    | Const_baddr l1 l2 => (RT_ptr l2 :: nil)\n    (* | Const_struct ls => List.fold_left (fun acc c => const2rtv c ++ acc) ls nil *)\n  end.\n\nSection OP.\n  Variable o : operand.\n  Variable env : Nenv.t rt_val.\n\n  (* Convert an operand to rt_val *)\n  Definition op2rtv : option rt_val :=\n    match o with\n      | Op_reg x => Nenv.find x env\n      | Op_const c => Some (const2rtv c)\n    end.\n\n  (* Convert an operand to a pointer *)\n  Definition op2ptr : option PTRTYP :=\n    match op2rtv with\n      | Some rt => match rt with\n                     | RT_int WORDSIZE_BITS _ addr :: nil => Some (Word.repr (Word.unsigned addr))\n                     | _ => None\n                   end\n      | None => None\n    end.\n\n  (* Convert an operand to a function pointer *)\n  Definition op2fun : option lab :=\n    match op2rtv with\n      | Some rt => match rt with\n                     | RT_fun l :: nil => Some l\n                     | _ => None\n                   end\n      | None => None\n    end.\nEnd OP.\n\n(* ---------------------------------------------------------------------- *)\n(* Value Typing *)\n\n(* ---------------------------------------------------------------------- *)\n(* Heap Typing Definitions *)\n\nDefinition heap_t := Zenv.t (ftyp * rgn).\n\nSection HT_SEC.\n \n  Variable lo : layout.\n  Variable HT : heap_t.\n\n  Fixpoint check_HT' (base:Z) (r:rgn) (t:ftyps) : bool :=\n    match t with\n      | nil => true\n      | t'::ts => \n        match Zenv.find base HT with\n          | Some (t'',r'') => \n            if rgn_dec r r'' \n              then\n                if ftyp_eq_dec t' t'' (* ftyp_sub t' t'' *)\n                  then check_HT' (base + size_ftyp lo t') r ts \n                  else false\n            else false\n          | None => false\n        end\n  end.\n                    \n  Definition check_HT (base:Z) (r:rgn) (t:ftyps) : bool :=\n    if zeq base 0 then true else check_HT' base r t.\n\n  Fixpoint construct_HT (base:Z) (r:rgn) (t:ftyps) : heap_t :=\n    match t with\n      | nil => HT\n      | t'::ts => \n        let HT' := construct_HT (base + size_ftyp lo t') r ts in\n          Zenv.add base (t',r) HT'\n    end.\n\nEnd HT_SEC.\n\nLtac t_simpl_check_HT :=\n  repeat \n    match goal with\n      | [ H: context [ match ?p with | (_, _) => _ end ] |- _ ] => destruct p\n      | [ H: context [ match ?x with | Some _ => _ | None => _ end ] |- _ ] => \n        (consider x); intros; try congruence\n      | [ H: context [ if ?x then _ else _ ] |- _ ] =>\n        (consider x); intros; try congruence\n    end; simpl in *; subst.\n\n(* Heap type extension *)\nDefinition heapt_ext (HT HT':heap_t) : Prop :=\n  forall n t r,\n    Zenv.find n HT = Some (t,r) ->\n    Zenv.find n HT' = Some (t,r).\n\n(* Another heap type extension stating all values in the new heap type that are \n   in the previous live regions also belong to the old heap type. *)\nDefinition heapt_ext2 (live:list rgn) (HT HT':heap_t) : Prop :=\n  forall n t r,\n    Zenv.find n HT' = Some (t,r) ->\n    In r live ->\n    Zenv.find n HT = Some (t,r).\n\n(* Well-formed heap-type *)\nDefinition wf_HT (lo:layout) (HT:heap_t) : Prop :=\n  forall n t r,\n    Zenv.find n HT = Some (t,r) ->\n    (forall n' t' r',\n      n <> n' ->\n      Zenv.find n' HT = Some (t',r') ->\n      n' + size_ftyp lo t' <= n \\/ \n      n + size_ftyp lo t <= n') /\\\n    0 < n /\\ \n    n + size_ftyp lo t < Word.modulus WORDSIZE_BITS.\n\n(* The regions a heap-type mentions is closed under live *)\nDefinition wf_HT_live (live:list rgn) (HT:heap_t) : Prop :=\n  forall n r t,\n    Zenv.find n HT = Some (t, r) ->\n    wf_tenv_ftyp live t.\n\n(* Get the maximum address mapped in the heap-typing *)\nFixpoint max_HT (HT:heap_t) : Z :=\n    match HT with\n      | nil => 0\n      | (x,y)::HT' => \n        let n := max_HT HT' in if zlt n x then x else n\n    end.\n\nLemma max_HT_spec : forall HT n t,\n  Zenv.find n HT = Some t ->\n  n <= max_HT HT.\nProof.\n  induction HT; simpl; intros; try congruence. destruct a.\n  destruct (OrderedTypeEx.Z_as_OT.eq_dec n z); subst.\n  destruct zlt; omega.\n  destruct zlt; crush.\nQed.\n\nDefinition wf_HT_bounds (HT:heap_t) : Prop :=\n  max_HT HT + ftyp_max < Word.max_unsigned WORDSIZE_BITS /\\\n  max_HT HT + ftyp_max > 0.\n \n(* ---------------------------------------------------------------------- *)\n(* Value Typing *)\n\nDefinition check_fun (fs:functions) (l:lab) (prgn:list rgn) (sig:list typ) (r:option typ) : bool :=\n  if lab_dec l Word.zero then true\n    else \n      match lookup_fun l fs with\n        | Some f => \n          if list_eq_dec typ_eq_dec (f_sig f) sig then\n            if list_eq_dec rgn_dec (domain (f_prgn f)) prgn then\n              match r, (f_ret f) with\n                | Some t1, Some t2 => if typ_eq_dec t1 t2 then true else false\n                | None, None => true\n                | _, _ => false\n              end\n              else false\n            else false\n        | None => false\n      end.\n\nSection VALUE_SEC.\n\n  Variable fs : functions.\n  Variable lo : layout.\n  Variable tenv : tenv_t.\n\n  Inductive wf_value' : list rgn -> heap_t -> rt_tag -> ftyp -> Prop :=\n  | wf_val_float : forall live HT f,\n    wf_value' live HT (RT_float f) Ftyp_float\n  | wf_val_double : forall live HT d,\n    wf_value' live HT (RT_double d) Ftyp_double\n  | wf_val_int : forall live HT sz pf (i:Word.int sz),\n    wf_value' live HT (RT_int sz pf i) (Ftyp_int sz pf)\n  | wf_val_ptr : forall live HT n t r t',\n    t' = flatten_typ lo tenv t ->\n    (if zeq (Word.unsigned n) 0 then True else In r live) ->\n    check_HT lo HT (Word.unsigned n) r t' = true ->\n    wf_value' live HT (RT_ptr n) (Ftyp_ptr t r)\n  | wf_val_fun : forall live HT prgn sig ret l,\n    check_fun fs l prgn sig ret = true ->\n    wf_value' live HT (RT_fun l) (Ftyp_fun prgn sig ret)\n  | wf_val_ptrU : forall live HT n sz r t',\n    t' = list_repeat sz Ftyp_int8 ->\n    (if zeq (Word.unsigned n) 0 then True else In r live) ->\n    check_HT lo HT (Word.unsigned n) r t' = true ->\n    wf_value' live HT (RT_ptr n) (Ftyp_ptrU sz r).\n  Hint Constructors wf_value'.\n  \n  Inductive wf_value : list rgn -> heap_t -> rt_val -> ftyps -> Prop :=\n  | wf_val_nil : forall live HT,\n    wf_value live HT nil nil\n  | wf_val_cons : forall live HT v t vs ts,\n    wf_value' live HT v t ->\n    wf_value live HT vs ts ->\n    wf_value live HT (v::vs) (t::ts).\n  Hint Constructors wf_value.\n  \nEnd VALUE_SEC.\n\n(* ---------------------------------------------------------------------- *)\n(* Value Typing Properties *)\n\nLemma wf_val_live_ext2 : forall fs lo tenv t v live HT r,\n  wf_value' fs lo tenv live HT v t ->\n  wf_value' fs lo tenv (r :: live) HT v t.\nProof.\n  induction 1; econstructor; eauto; destruct_c zeq; intuition.\nQed.\n\nLemma wf_val_live_ext' : forall fs lo tenv t HT live v rgns,\n  wf_value' fs lo tenv live HT v t ->\n  wf_value' fs lo tenv (rgns++live) HT v t.\nProof.\n  induction 1; econstructor; eauto; destruct_c zeq; intuition.\nQed.\n\nLemma wf_val_live_ext : forall fs lo tenv t HT live v rgns,\n  wf_value fs lo tenv live HT v t ->\n  wf_value fs lo tenv (rgns++live) HT v t.\nProof.\n  induction 1; econstructor; eauto. eapply wf_val_live_ext'; eauto.\nQed.\n\nLemma check_HT_HT_ext' : forall lo t HT HT' n r,\n  heapt_ext HT HT' ->\n  check_HT' lo HT n r t = true ->\n  check_HT' lo HT' n r t = true.\nProof.\n  induction t; simpl; intros; auto. t_simpl_check_HT.\n  unfold heapt_ext in H. apply H in H0. rewrite H0. \n  destruct_c rgn_dec. destruct_c ftyp_eq_dec. eauto.\nQed.\n\nLemma check_HT_HT_ext : forall lo t HT HT' n r,\n  heapt_ext HT HT' ->\n  check_HT lo HT n r t = true ->\n  check_HT lo HT' n r t = true.\nProof.\n  unfold check_HT; intros. destruct_c zeq. eapply check_HT_HT_ext'; eauto.\nQed.\n  \nLemma wf_val_HT_ext' : forall fs lo tenv t HT HT' live v,\n  heapt_ext HT HT' ->\n  wf_value' fs lo tenv live HT v t ->\n  wf_value' fs lo tenv live HT' v t.\nProof.\n  induction 2; econstructor; eauto; eapply check_HT_HT_ext; eauto.\nQed.\n\nLemma wf_val_HT_ext : forall fs lo tenv t HT HT' live v,\n  heapt_ext HT HT' ->\n  wf_value fs lo tenv live HT v t ->\n  wf_value fs lo tenv live HT' v t.\nProof.\n  induction 2; econstructor; eauto. eapply wf_val_HT_ext'; eauto.\nQed.\n\n(* ---------------------------------------------------------------------- *)\n(* Encoding and Decoding bytes *)\n\n(* ---------------------------------------------------------------------- *)\n(* From Compcert with minor changes *)\nFixpoint bytes_of_int (n : nat) (x : Z) {struct n} : list int8 :=\n  match n with\n  | 0%nat => nil\n  | S m => Word.repr x :: bytes_of_int m (x / 256)\n  end.\n\nFixpoint int_of_bytes (l : list int8) : Z :=\n  match l with\n  | nil => 0\n  | b :: l' => Word.unsigned b + int_of_bytes l' * 256\n  end.\n\nLemma int_of_bytes_of_int:\n  forall n x,\n  int_of_bytes (bytes_of_int n x) = x mod (two_p (Z_of_nat n * 8)).\nProof.\n  induction n; intros.\n  simpl. rewrite Zmod_1_r. auto.\n  Opaque Word.wordsize.\n  rewrite inj_S. simpl.\n  replace (Zsucc (Z_of_nat n) * 8) with (Z_of_nat n * 8 + 8) by omega.\n  rewrite two_p_is_exp; try omega. \n  rewrite Zmod_recombine. rewrite IHn. rewrite Zplus_comm. reflexivity. \n  apply two_p_gt_ZERO. omega. apply two_p_gt_ZERO. omega.\n  Transparent Word.wordsize.\nQed.\n\nLemma length_bytes_of_int:\n  forall n x, length (bytes_of_int n x) = n.\nProof.\n  induction n; simpl; intros. auto. decEq. auto.\nQed.\n\n(* ---------------------------------------------------------------------- *)\n(* Decoding and encoding runtime tags / bits *)\n\nDefinition encode_rttag (lo:layout) (tag:rt_tag) : list int8 :=\n  let bytes :=\n  match tag with\n    | RT_int n pf i => bytes_of_int (size_ftyp_nat lo (Ftyp_int n pf)) (Word.unsigned i)\n    | RT_fun l => bytes_of_int (size_ftyp_nat lo (Ftyp_ptr Typ_int32 0%nat)) (Word.unsigned l)\n  end in\n  if endian lo then rev bytes else bytes.\n\nFixpoint encode_rtval (lo:layout) (ftls:ftyps) (rt:rt_val) : list int8 :=\n  match rt with\n    | nil => nil\n    | tag :: tl' => encode_rttag lo tag ++ (encode_rtval lo ftls tl')\n  end.\n\n(* Turn a list of bytes into a run-time value as indicated by its ftyps *)\nDefinition decode_rttag (lo:layout) (ft:ftyp) (bytes:list int8) : rt_tag :=\n  let bytes := if endian lo then rev bytes else bytes in\n  match ft with\n    | Ftyp_float => RT_float (Word.repr (int_of_bytes bytes))\n    | Ftyp_double => RT_double (Word.repr (int_of_bytes bytes))\n    | Ftyp_int n pf => RT_int n pf (Word.repr (int_of_bytes bytes))\n    | Ftyp_ptr _ _ => RT_ptr (Word.repr (int_of_bytes bytes))\n    | Ftyp_fun _ _ _ => RT_fun (Word.repr (int_of_bytes bytes))\n    | Ftyp_ptrU _ _ => RT_ptr (Word.repr (int_of_bytes bytes))\n  end.\nFixpoint decode_rtval (lo:layout) (ftls:ftyps) (bytes:list int8) : rt_val :=\n  match ftls with \n    | ft' :: ftls' => \n      decode_rttag lo ft' (firstn (size_ftyp_nat lo ft') bytes) ::\n      decode_rtval lo ftls' (skipn (size_ftyp_nat lo ft') bytes)\n    | nil => nil\n  end.\n\nLemma decode_encode_int_same : forall sz pf (i:Word.int sz) lo,\n  RT_int sz pf\n  (Word.repr \n    (int_of_bytes\n      (bytes_of_int (size_ftyp_nat lo (Ftyp_int sz pf))\n        (Word.unsigned i)))) = RT_int sz pf i.\nProof.\n  intros. f_equal; auto. rewrite int_of_bytes_of_int. unfold size_ftyp_nat. unfold size_ftyp.\n  rewrite nat_of_Z_eq. rewrite Z.mul_add_distr_r. destruct i. apply Word.mkint_eq. simpl. \n  unfold Word.modulus in *. unfold Word.wordsize in *. rewrite two_power_nat_two_p in *.\n  \n  assert (8 > 0). omega.\n      \n  assert (Z.of_nat (S sz) <= Z.of_nat sz / 8 * 8 + 8).\n  specialize (Z_div_mod_eq (Z.of_nat sz) 8 H); intros.\n  assert (Z.of_nat sz - Z.of_nat sz mod 8 = 8 * (Z.of_nat sz / 8)). omega.\n  rewrite Zmult_comm. rewrite <- H1.\n  rewrite inj_S. rewrite <- Z.add_1_l.\n  specialize (Z_mod_lt (Z.of_nat sz) 8 H); intros. omega.\n  \n  assert (two_p (Z.of_nat (S sz)) > 0). apply two_p_gt_ZERO. omega.\n  specialize (Z_mod_lt intval (two_p (Z.of_nat (S sz))) H1); intros.\n  \n  assert (0 <= Z.of_nat (S sz) <= Z.of_nat sz / 8 * 8 + 8). omega.\n  apply two_p_monotone in H3.\n  assert (0 <= intval mod two_p (Z.of_nat (S sz)) < two_p (Z.of_nat sz / 8 * 8 + 8)). omega.\n  \n  assert (intval mod (two_p (Z.of_nat (S sz))) = intval).\n  rewrite Zmod_small; auto.\n  rewrite H5 in *.\n  \n  rewrite Zmod_small in *; auto. rewrite Zmod_small; auto.\n  rewrite Zmod_small; auto.\n  \n  assert (0 <= Z.of_nat sz / 8). apply Z_div_pos; omega. omega.\nQed.\n\nLemma decode_encode_fun_same : forall n lo,\n  RT_fun\n  (Word.repr\n    (int_of_bytes\n      (bytes_of_int (size_ftyp_nat lo (Ftyp_ptr Typ_int32 0%nat))\n        (Word.unsigned n)))) = RT_fun n.\nProof.\n  intros. f_equal. rewrite int_of_bytes_of_int. simpl. destruct n.\n  apply Word.mkint_eq. simpl. unfold Word.modulus in *.\n  unfold Word.wordsize in *. rewrite two_power_nat_two_p.\n  unfold two_p. simpl. rewrite Zmod_mod. rewrite Zmod_small; auto.\nQed.\n\nLemma decode_encode_same : forall t v fs lo tenv HT live,\n  wf_value' fs lo tenv HT live v t ->\n  decode_rttag lo t (encode_rttag lo v) = v.\nProof.\n  intros. inv H; unfold decode_rttag; unfold encode_rttag.\n  { unfold RT_float. destruct (endian lo). rewrite rev_involutive.\n    rewrite Word.repr_unsigned. apply decode_encode_int_same.\n    rewrite Word.repr_unsigned. apply decode_encode_int_same. }\n  { unfold RT_double. destruct (endian lo). rewrite rev_involutive. \n    rewrite Word.repr_unsigned. apply decode_encode_int_same.\n    rewrite Word.repr_unsigned. apply decode_encode_int_same. }\n  { destruct (endian lo). rewrite rev_involutive.\n    apply decode_encode_int_same. apply decode_encode_int_same. }\n  { destruct (endian lo). rewrite rev_involutive. \n    apply decode_encode_int_same. apply decode_encode_int_same. }\n  { destruct (endian lo). rewrite rev_involutive.\n    apply decode_encode_fun_same. apply decode_encode_fun_same. }\n  { destruct (endian lo). rewrite rev_involutive. \n    apply decode_encode_int_same. apply decode_encode_int_same. }\nQed.\n\n(* ---------------------------------------------------------------------- *)\n\nFixpoint bytestoint' (rt:rt_val) : list int8 :=\n  match rt with\n    | nil => nil\n    | v::rt' => match v with \n                  | RT_int 7 _ b => b :: bytestoint' rt'\n                  | _ => Word.zero :: bytestoint' rt'\n                end\n  end.\nDefinition bytestoint16 (lo:layout) (rt:rt_val) : rt_val :=\n  RT_int 15 lt_15_MAX_I_BITS (Word.repr (int_of_bytes (bytestoint' rt))) :: nil.\nDefinition bytestoint (lo:layout) (rt:rt_val) : rt_val :=\n  RT_int 31 lt_31_MAX_I_BITS (Word.repr (int_of_bytes (bytestoint' rt))) :: nil.\nDefinition bytestoint64 (lo:layout) (rt:rt_val) : rt_val :=\n  RT_int 63 lt_63_MAX_I_BITS (Word.repr (int_of_bytes (bytestoint' rt))) :: nil.\n\n(* ---------------------------------------------------------------------- *)\n\nFixpoint anytobytes' (lo:layout) (rt:rt_val) : list int8 :=\n  match rt with\n    | nil => nil\n    | v::rt' => match v with\n                  | RT_int n pf i => bytes_of_int (size_ftyp_nat lo (Ftyp_int n pf)) (Word.unsigned i) ++ anytobytes' lo rt'\n                  | RT_fun l => bytes_of_int (size_ftyp_nat lo (Ftyp_ptr Typ_int32 0%nat)) (Word.unsigned l) ++ anytobytes' lo rt'\n                end\n  end.\n\nDefinition anytobytes (lo:layout) (rt:rt_val) : rt_val :=\n  map (fun b => RT_int 7 lt_7_MAX_I_BITS b) (anytobytes' lo rt).\n\nLemma wf_val_anytobytesh : forall n bs fs lo tenv live HT,\n  n = length bs ->\n  wf_value fs lo tenv live HT (map (fun b => RT_int 7 lt_7_MAX_I_BITS b) bs) (list_repeat n Ftyp_int8).\nProof.\n  induction n; destruct bs; crush. econstructor; eauto.\n  econstructor; eauto. destruct i. \n  assert (Word.repr intval = Word.mkint _ intval intrange). \n  apply Word.mkint_eq. rewrite Zmod_small; auto. rewrite <- H.\n  econstructor; eauto.\nQed.\n\nLemma wf_val_anytobytes : forall b fs lo tenv live HT n,\n  n = length (anytobytes lo b) ->\n  wf_value fs lo tenv live HT (anytobytes lo b) (list_repeat n Ftyp_int8).\nProof.\n  intros. specialize (wf_val_anytobytesh n (anytobytes' lo b) fs lo tenv live HT); intros. \n  unfold anytobytes in *. rewrite map_length in H. crush.\nQed.\n\nLemma wf_val_any_size_nat' : forall fs lo tenv live HT t v,\n  wf_value' fs lo tenv live HT v t ->\n  (length (anytobytes lo (v::nil))) = size_ftyp_nat lo t.\nProof.\n  induction 1; unfold anytobytes; simpl; intros; auto. rewrite map_length.\n  unfold size_ftyp_nat. unfold size_ftyp. rewrite app_length.\n  rewrite length_bytes_of_int. auto.\nQed.\n\nLemma wf_val_any_size_nat : forall fs lo tenv live HT t v,\n  wf_value fs lo tenv live HT v t ->\n  (length (anytobytes lo v) = size_ftyps_nat lo t)%nat.\nProof.\n  induction t; simpl; intros.\n  { inv H. simpl. auto. }\n  { assert (forall lo t1 t2, \n    size_ftyps_nat lo (t1 :: t2) = (size_ftyp_nat lo t1 + size_ftyps_nat lo t2)%nat).\n    intros. unfold size_ftyps_nat. unfold size_ftyp_nat. simpl.\n    rewrite nat_of_Z_plus; auto. apply size_ftyp_nonneg. apply size_ftyps_nonneg.\n    rewrite H0. inv H. eapply IHt in H7.\n    unfold anytobytes in *. rewrite map_length in *. \n    inv H6; simpl; repeat f_equal; auto. \n    unfold size_ftyp_nat. unfold size_ftyp. rewrite app_length. rewrite length_bytes_of_int.\n    auto. }\nQed.\n\nLemma wf_val_any_size : forall fs lo tenv live HT t v,\n  wf_value fs lo tenv live HT v t ->\n  Z.of_nat (length (anytobytes lo v)) = size_ftyps lo t.\nProof.\n  intros. apply wf_val_any_size_nat in H. unfold size_ftyps_nat in H. \n  assert (Z.of_nat (length (anytobytes lo v)) = Z.of_nat (nat_of_Z (size_ftyps lo t))).\n  omega. rewrite H0. rewrite nat_of_Z_eq; auto. apply size_ftyps_nonneg.\nQed.\n\n(* ---------------------------------------------------------------------- *)\n\nLemma check_HT_mid' : forall t t' s addr lo HT f,\n  ftyps_subset t' t = true ->\n  check_HT' lo HT (addr + size_ftyp lo f) s t = true ->\n  check_HT' lo HT (addr + size_ftyp lo f) s t' = true.\nProof.\n  induction t; destruct t'; crush.\n  (* case_eq (ftyp_subset f a); intros. rewrite H1 in H. *)\n  destruct ftyp_eq_dec; try congruence.\n  remember (Zenv.find (addr + size_ftyp lo f0) HT) as Hd.\n  symmetry in HeqHd. destruct Hd; try congruence.\n  destruct p. destruct rgn_dec; try congruence. subst.\n  destruct_c ftyp_eq_dec; eauto.\nQed.\n\nLemma check_HT_mid : forall t n t' lo HT addr r rmap,\n  addr > 0 ->\n  (n < length t)%nat ->\n  ftyps_subset t' (skipn n t) = true ->\n  check_HT lo HT addr (alpha rmap r) (sigma rmap t) = true ->\n  check_HT lo HT (addr + walk_offset lo n t) (alpha rmap r) (sigma rmap t') = true.\nProof.\n  induction t; crush.\n  destruct n; simpl in *.\n  { unfold check_HT in *. destruct zeq; crush. destruct_c zeq.\n    remember (Zenv.find addr HT) as Hd. destruct_c Hd.\n    destruct p. destruct_c rgn_dec. subst.\n    destruct t'. \n    simpl in H1. unfold check_HT'. reflexivity.\n    simpl in H1. destruct_c ftyp_eq_dec. subst.\n    assert (addr + 0 = addr). omega. rewrite H3.\n    simpl. rewrite <- HeqHd. destruct_c rgn_dec. destruct_c ftyp_eq_dec.\n    eapply check_HT_mid'; eauto. eapply ftyps_subset_sigma; eauto. }\n  { assert (addr + (walk_offset lo n t + size_ftyp lo a) = \n    (addr + size_ftyp lo a) + (walk_offset lo n t)). omega.\n    rewrite H3. eapply IHt; eauto. size_ftyp_prop. omega. omega.\n    unfold check_HT in *. destruct zeq; crush. destruct_c zeq.\n    destruct_c (Zenv.find addr HT). destruct p. destruct_c rgn_dec.\n    destruct_c ftyp_eq_dec. erewrite <- size_ftyp_sigma_inv; eauto. }\nQed.\n\nLemma check_HT_bounds : forall t r n lo HT,\n  n > 0 ->\n  t <> nil ->\n  wf_HT_bounds HT ->\n  check_HT lo HT n r t = true ->\n  n <= Word.max_unsigned WORDSIZE_BITS.\nProof.\n  destruct t; intros. \n  { unfold check_HT in H2. destruct zeq; crush. }\n  { unfold check_HT in H2. destruct zeq; crush. \n    remember (Zenv.find n HT) as Hd. destruct_c Hd. \n    symmetry in HeqHd. unfold wf_HT_bounds in H1. destruct H1.\n    apply max_HT_spec in HeqHd. unfold ftyp_max in *. omega. }\nQed.\n\nLemma check_HT_subset' : forall t2 t1 lo HT addr r rmap,\n  ftyps_subset t2 t1 = true ->\n  check_HT' lo HT addr r (sigma rmap t1) = true ->\n  check_HT' lo HT addr r (sigma rmap t2) = true.\nProof.\n  induction t2; simpl; intros; auto.\n  destruct_c t1. destruct_c ftyp_eq_dec. subst. simpl in *.\n  destruct_c (Zenv.find addr HT). destruct p.\n  destruct_c rgn_dec. destruct_c ftyp_eq_dec.\n  eapply IHt2; eauto.\nQed.\n\nLemma check_HT_subset : forall t2 t1 lo HT addr r rmap,\n  ftyps_subset t2 t1 = true ->\n  check_HT lo HT addr r (sigma rmap t1) = true ->\n  check_HT lo HT addr r (sigma rmap t2) = true.\nProof.\n  intros. unfold check_HT in *. destruct_c zeq.\n  eapply check_HT_subset'; eauto.\nQed.\n\nLemma check_HT_subset_bytes : forall sz1 sz2 lo HT rmap addr r,\n  check_HT lo HT addr r (sigma rmap (list_repeat sz1 Ftyp_int8)) = true ->\n  Z.of_nat sz2 <= Z.of_nat sz1 ->\n  check_HT lo HT addr r (sigma rmap (list_repeat sz2 Ftyp_int8)) = true.\nProof.\n  intros. eapply check_HT_subset; eauto. eapply ftyps_subset_ls_repeat; eauto. omega.\nQed.\n\nLemma check_HT_range' : forall sz lo HT i1 i2 r,\n  i1 <= Word.modulus WORDSIZE_BITS ->\n  wf_HT lo HT ->\n  i2 < Z.of_nat sz ->\n  check_HT' lo HT i1 r (list_repeat sz Ftyp_int8) = true ->\n  i1 + i2 < Word.modulus WORDSIZE_BITS.\nProof.\n  induction sz; simpl; intros; auto.\n  crush.\n  remember (Zenv.find i1 HT) as Hd. symmetry in HeqHd.\n  destruct_c Hd. destruct p. destruct_c rgn_dec. destruct_c ftyp_eq_dec. subst.\n  eapply IHsz with (i2 := i2 - 1) in H2; eauto. omega.\n  unfold wf_HT in H0. apply H0 in HeqHd. t_simp. simpl in H5. omega.\n  rewrite Zpos_P_of_succ_nat in H1. omega.\nQed.\n\nLemma check_HT_range : forall sz lo HT i1 i2 r,\n  i1 <= Word.modulus WORDSIZE_BITS ->\n  wf_HT lo HT ->\n  i2 < Z.of_nat sz <= Word.modulus WORDSIZE_BITS ->\n  check_HT lo HT i1 r (list_repeat sz Ftyp_int8) = true ->\n  i1 + i2 < Word.modulus WORDSIZE_BITS.\nProof.\n  unfold check_HT; intros. destruct_c zeq. subst. omega.\n  eapply check_HT_range'; eauto. omega.\nQed.\n\nLemma check_HT_mid_bytes' : forall sz i1 i2 lo HT r,\n  check_HT' lo HT i1 r (list_repeat sz Ftyp_int8) = true ->\n  (i2 < sz)%nat ->\n  check_HT' lo HT (i1 + Z.of_nat i2) r (list_repeat (sz - i2) Ftyp_int8) = true.\nProof.\n  induction sz; simpl; intros; auto.\n  remember (Zenv.find i1 HT) as Hd. destruct_c Hd. symmetry in HeqHd.\n  destruct p. destruct_c rgn_dec. destruct_c ftyp_eq_dec. subst.\n  destruct i2. simpl. \n  { assert (i1 + 0 = i1) by omega. rewrite H1. rewrite HeqHd.\n    destruct_c rgn_dec. destruct_c ftyp_eq_dec. }\n  rewrite Nat2Z.inj_succ. rewrite <- Z.add_1_r. \n  { assert (i1 + (Z.of_nat i2 + 1) = i1 + 1 + Z.of_nat i2) by omega.\n    rewrite H1. eapply IHsz; eauto. omega. }\nQed.\n \nLemma check_HT_mid_bytes : forall sz i1 i2 lo HT r,\n  i1 > 0 ->\n  (i2 < sz)%nat ->\n  check_HT lo HT i1 r (list_repeat sz Ftyp_int8) = true ->\n  check_HT lo HT (i1 + Z.of_nat i2) r (list_repeat (sz - i2) Ftyp_int8) = true.\nProof.\n  intros. unfold check_HT in *. destruct_c zeq. destruct zeq; auto. subst. inv H.\n  destruct zeq; auto. eapply check_HT_mid_bytes'; eauto. \nQed.\n\n(* ---------------------------------------------------------------------- *)\n\nLemma check_HT_disj' : forall t1 t2 lo HT addr r,\n  check_HT' lo HT addr r (t1 ++ t2) = true ->\n  check_HT' lo HT addr r t1 = true /\\\n  check_HT' lo HT (addr + size_ftyps lo t1) r t2 = true.\nProof.\n  induction t1; simpl; intros; auto.\n  split; auto. cutrewrite (addr + 0 = addr); [ | omega]. auto. \n  case_eq (Zenv.find addr HT); intros. rewrite H0 in H. destruct p. destruct_c rgn_dec; subst.\n  destruct_c ftyp_eq_dec; subst.\n  apply IHt1 in H. \n  assert ((addr + (size_ftyp lo f + size_ftyps lo t1)) = (addr + size_ftyp lo f + size_ftyps lo t1)). omega. \n  rewrite H1. auto.\n  rewrite H0 in H. crush.\nQed.\n\nLemma check_HT_comb : forall t1 t2 lo HT addr r,\n  check_HT' lo HT addr r t1 = true ->\n  check_HT' lo HT (addr + size_ftyps lo t1) r t2 = true ->\n  check_HT' lo HT addr r (t1 ++ t2) = true.\nProof.\n  induction t1; simpl; intros; auto.\n  cutrewrite (addr + 0 = addr) in H0; [ | omega]. auto.\n  case_eq (Zenv.find addr HT); intros. rewrite H1 in H. destruct p. destruct_c rgn_dec; subst.\n  destruct_c ftyp_eq_dec; subst.\n  apply IHt1 with (t2 := t2) in H; auto.\n  cutrewrite (addr + (size_ftyp lo f + size_ftyps lo t1) = addr + size_ftyp lo f + size_ftyps lo t1) in H0; [ | omega].\n  auto.\n  rewrite H1 in H. crush.\nQed.\n\nLemma check_HT_array'' : forall sz,\n  (0 < sz)%nat ->\n  forall lo HT addr r rmap tenv t,\n  check_HT' lo HT addr r (sigma rmap (flatten_typ lo tenv (Typ_array t sz))) = true ->\n  check_HT' lo HT addr r (sigma rmap (flatten_typ lo tenv t)) = true.\nProof.\n  induction 1; intros. simpl in *. rewrite app_nil_r in H. auto.\n  simpl in H0. unfold sigma in H0. rewrite map_app in H0. \n  eapply check_HT_disj' in H0. destruct H0; auto.\nQed.\n\nLemma check_HT_array : forall sz,\n  (0 < sz)%nat ->\n  forall lo HT addr r rmap tenv t,\n  check_HT lo HT addr r (sigma rmap (flatten_typ lo tenv (Typ_array t sz))) = true ->\n  check_HT lo HT addr r (sigma rmap (flatten_typ lo tenv t)) = true.\nProof.\n  unfold check_HT; intros. destruct_c zeq.\n  eapply check_HT_array''; eauto.\nQed.\n\nLemma check_HT_array_subset' : forall sz lo HT addr r tenv t rmap,\n  check_HT' lo HT addr r (sigma rmap (flatten_typ lo tenv (Typ_array t sz))) = true ->\n  check_HT' lo HT (addr + size_ftyps lo (flatten_typ lo tenv t)) r (sigma rmap (flatten_typ lo tenv (Typ_array t (sz - 1)))) = true.\nProof.\n  destruct sz; simpl; intros; auto.\n  unfold sigma in H. rewrite map_app in H. apply check_HT_disj' in H. destruct H. unfold sigma.\n  replace (sz - 0)%nat with sz by omega. auto.\n  erewrite <- size_ftyps_sigma_inv; eauto.\nQed.\n\nLemma check_HT_range_general' : forall t lo HT i1 r,\n  i1 < Word.modulus WORDSIZE_BITS ->\n  wf_HT lo HT ->\n  check_HT' lo HT i1 r t = true ->\n  i1 + size_ftyps lo t < Word.modulus WORDSIZE_BITS.\nProof.\n  induction t; simpl; intros; auto. omega.\n  replace (i1 + (size_ftyp lo a + size_ftyps lo t)) with (i1 + size_ftyp lo a + size_ftyps lo t) by omega.\n  case_eq (Zenv.find i1 HT); intros.\n  rewrite H2 in H1. destruct p. destruct_c rgn_dec; subst.\n  destruct_c ftyp_eq_dec; subst.\n  eapply IHt in H1; eauto.\n  unfold wf_HT in H0. apply H0 in H2. destruct H2. intuition.\n  rewrite H2 in H1. crush.\nQed.\n\nLemma check_HT_range_general : forall t lo HT i1 r,\n  i1 > 0 ->\n  i1 < Word.modulus WORDSIZE_BITS ->\n  wf_HT lo HT ->\n  check_HT lo HT i1 r t = true ->\n  i1 + size_ftyps lo t < Word.modulus WORDSIZE_BITS.\nProof.\n  unfold check_HT; intros. destruct_c zeq. omegaContradiction. \n  eapply check_HT_range_general'; eauto.\nQed.\n\n(* ---------------------------------------------------------------------- *)\nLemma wf_val_ftyp_sub : forall t1 t2 fs lo tenv HT live v,\n  ftyp_sub t1 t2 = true ->\n  wf_value' fs lo tenv HT live v t1 ->\n  wf_value' fs lo tenv HT live v t2.\nProof.\n  induction t1; destruct t2; simpl; intros; \n    try destruct_c ftyp_eq_dec; eauto.\n  { inv H0. destruct_c eq_nat_dec; subst. \n    assert (lt_31_MAX_I_BITS = l). apply proof_irr. subst. econstructor; eauto. }\n  { inv H0. destruct_c eq_nat_dec; subst. \n    assert (lt_63_MAX_I_BITS = l). apply proof_irr. subst. econstructor; eauto. }\n  { inv H0. destruct_c eq_nat_dec; subst. \n    assert (RT_float i0 = RT_int 31 pf0 i0). unfold RT_float. f_equal.\n    apply proof_irr. rewrite Word.repr_unsigned. reflexivity. \n    rewrite <- H0. econstructor; eauto. }\n  { inv H0. destruct_c eq_nat_dec; subst. \n    assert (RT_double i0 = RT_int 63 pf0 i0). unfold RT_double. f_equal.\n    apply proof_irr. rewrite Word.repr_unsigned. reflexivity. \n    rewrite <- H0. econstructor; eauto. }\n  { inv H0. unfold RT_ptr. destruct_c eq_nat_dec; subst. \n    assert (lt_63_MAX_I_BITS = l). apply proof_irr. subst.\n    econstructor; eauto. }\n  { inv H0. unfold RT_ptr. destruct_c eq_nat_dec; subst. \n    assert (lt_63_MAX_I_BITS = l). apply proof_irr. subst.\n    econstructor; eauto. }\n  { destruct_c rgn_dec. destruct_c zle. inv H0. econstructor; eauto.\n    assert (forall n rmap, list_repeat n Ftyp_int8 = sigma rmap (list_repeat n Ftyp_int8)).\n    induction n2; crush. erewrite H0. erewrite H0 in H8.\n    eapply check_HT_subset_bytes; eauto.\n    Grab Existential Variables.\n    apply Nenv.empty.\n  }\nQed.\n\nLemma wf_val_ftyp_sub2 : forall t1 t2 fs lo tenv HT live v rmap,\n  ftyp_sub t1 t2 = true ->\n  wf_value' fs lo tenv HT live v (sigma' rmap t1) ->\n  wf_value' fs lo tenv HT live v (sigma' rmap t2).\nProof.\n  induction t1; destruct t2; simpl; intros; \n    try destruct_c ftyp_eq_dec; eauto.\n  { inv H0. destruct_c eq_nat_dec; subst. \n    assert (lt_31_MAX_I_BITS = l). apply proof_irr. subst. econstructor; eauto. }\n  { inv H0. destruct_c eq_nat_dec; subst. \n    assert (lt_63_MAX_I_BITS = l). apply proof_irr. subst. econstructor; eauto. }\n  { inv H0. destruct_c eq_nat_dec; subst. \n    assert (RT_float i0 = RT_int 31 pf0 i0). unfold RT_float. f_equal.\n    apply proof_irr. rewrite Word.repr_unsigned. reflexivity. \n    rewrite <- H0. econstructor; eauto. }\n  { inv H0. destruct_c eq_nat_dec; subst. \n    assert (RT_double i0 = RT_int 63 pf0 i0). unfold RT_double. f_equal.\n    apply proof_irr. rewrite Word.repr_unsigned. reflexivity. \n    rewrite <- H0. econstructor; eauto. }\n  { inv H0. unfold RT_ptr. destruct_c eq_nat_dec; subst. \n    assert (lt_63_MAX_I_BITS = l). apply proof_irr. subst.\n    econstructor; eauto. }\n  { inv H0. unfold RT_ptr. destruct_c eq_nat_dec; subst. \n    assert (lt_63_MAX_I_BITS = l). apply proof_irr. subst.\n    econstructor; eauto. }\n  { destruct_c rgn_dec. destruct_c zle. inv H0. econstructor; eauto.\n    assert (forall n rmap, list_repeat n Ftyp_int8 = sigma rmap (list_repeat n Ftyp_int8)).\n    induction n2; crush.\n    rewrite H0 with (rmap := rmap) in H8.\n    rewrite H0 with (rmap := rmap).\n    eapply check_HT_subset_bytes; eauto. }\nQed.\n\nFixpoint weaken_val (v:rt_val) (t:ftyps) : rt_val :=\n  match v, t with\n    | v::vs, t::ts => v :: weaken_val vs ts\n    | _, nil => nil\n    | nil, _ => nil\n  end.\n\nLemma wf_val_ftyps_weaken : forall t1 t2 fs lo tenv HT live v rmap,\n  ftyps_weaken t1 t2 = true ->\n  wf_value fs lo tenv HT live v (sigma rmap t1) ->\n  wf_value fs lo tenv HT live (weaken_val v t2) (sigma rmap t2).\nProof.\n  induction t1; simpl; intros. \n  { destruct_c t2. simpl. destruct v; simpl; auto. constructor. }\n  { destruct_c t2. simpl. destruct v; simpl; auto. \n    constructor. constructor. consider (ftyp_sub a f); intros. inv H0.\n    eapply IHt1 in H8; eauto. econstructor; eauto. eapply wf_val_ftyp_sub2; eauto. }\nQed.\n", "meta": {"author": "danehuang", "repo": "vsafecode", "sha": "71653ef1d58b87dfa3ade695f5f48f54bf18b86e", "save_path": "github-repos/coq/danehuang-vsafecode", "path": "github-repos/coq/danehuang-vsafecode/vsafecode-71653ef1d58b87dfa3ade695f5f48f54bf18b86e/formalization/src/IllvmValues.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.21521316495081877}}
{"text": "(** * Bicolano: Semantic domains *)\n\n(* <Insert License Here>\n\n    $Id: Domain.v 69 2006-03-06 20:16:11Z davidpichardie $ *)\n\n(** Formalization of Java semantic domain.\n Based on The \"Java (TM) Virtual Machine Specification, Second Edition, \n  Tim Lindholm, Frank Yellin\"\n\n @author David Pichardie, ...  *)\n(* Hendra : - Modified to suit DEX program (removed operand stack).\n            - Removed reference comparison \n            - Also trim the system to contain only Arithmetic *)\n\nRequire Export DEX_Program.\nRequire Export Numeric.\nRequire Export List.\nOpen Scope Z_scope.\n\n(** All semantic domains and basic operation are encapsulated in a module signature *)\n\nModule Type DEX_SEMANTIC_DOMAIN.\n\n (** We depend on the choices done for program data structures *)\n Declare Module DEX_Prog : DEX_PROGRAM. Import DEX_Prog.\n\n Declare Module Byte  : NUMERIC with Definition power := 7%nat.\n Declare Module Short : NUMERIC with Definition power := 15%nat.\n Declare Module Int   : NUMERIC with Definition power := 31%nat.\n\n (** conversion *)\n Parameter b2i : Byte.t -> Int.t.\n Parameter s2i : Short.t -> Int.t. \n Parameter i2b : Int.t -> Byte.t. \n Parameter i2s : Int.t -> Short.t.\n Parameter i2bool : Int.t -> Byte.t.\n\n Inductive DEX_num : Set :=\n   | I : Int.t -> DEX_num\n   | B : Byte.t -> DEX_num\n   | Sh : Short.t -> DEX_num.\n\n Inductive DEX_value : Set :=\n   | Num : DEX_num -> DEX_value.\n\n Definition init_value (t:DEX_type) : DEX_value :=\n    match t with\n     | DEX_PrimitiveType _ => Num (I (Int.const 0))\n    end.\n \n (** Domain of local variables *)\n Module Type DEX_REGISTERS.\n   Parameter t : Type.\n   Parameter get : t-> DEX_Reg -> option DEX_value.\n   Parameter update : t -> DEX_Reg -> DEX_value -> t.\n   Parameter dom : t -> list DEX_Reg.\n   Parameter get_update_new : forall l x v, get (update l x v) x = Some v.\n   Parameter get_update_old : forall l x y v,\n     x<>y -> get (update l x v) y = get l y.\n End DEX_REGISTERS.\n Declare Module DEX_Registers : DEX_REGISTERS.\n\n Parameter listreg2regs : DEX_Registers.t -> nat -> list DEX_Reg -> DEX_Registers.t.\n\n(* 290415 - Some Notes\n- According to verified DEX bytecode, every registers have\n  to have a value before used. This means we can safely assume\n  that we don't need the update to be option anymore because\n  the only possible case where it updates empty value is when\n  the source is empty, which has been taken care by the assumption\n- The special register ret and ex are assigned the number\n  65536 and 65537 respectively (in binary) because we know\n  that the maximum number of registers is 65535.\n*)\n\n  Inductive DEX_ReturnVal : Set :=\n   | Normal : option DEX_value -> DEX_ReturnVal.\n\n (** Domain of frames *)\n Module Type DEX_FRAME.\n   Inductive t : Type := \n      make : DEX_Method -> DEX_PC -> DEX_Registers.t -> t.\n End DEX_FRAME.\n Declare Module DEX_Frame : DEX_FRAME.\n\n (** Domain of call stacks *)\n Module Type DEX_CALLSTACK.\n   Definition t : Type := list DEX_Frame.t.\n End DEX_CALLSTACK.\n Declare Module DEX_CallStack : DEX_CALLSTACK.\n\n (** Domain of states *)\n Module Type DEX_STATE.\n   Inductive t : Type := \n      normal : DEX_Frame.t -> DEX_CallStack.t -> t.\n   Definition get_sf (s:t) : DEX_CallStack.t :=\n     match s with\n       normal _ sf => sf\n     end.\n   Definition get_m (s:t) : DEX_Method :=\n     match s with\n       normal (DEX_Frame.make m _ _)_ => m\n     end.\n End DEX_STATE.\n Declare Module DEX_State : DEX_STATE.\n \n (** Some notations *)\n Notation St := DEX_State.normal.\n Notation Fr := DEX_Frame.make.\n\n  (** compatibility between ValKind and value *) \n  Inductive compat_ValKind_value : DEX_ValKind -> DEX_value -> Prop :=\n    | compat_ValKind_value_int : forall n,\n        compat_ValKind_value DEX_Ival (Num (I n)).\n\n  (** [assign_compatible_num source target] holds if a numeric value [source] can be \n    assigned to a variable of type [target]. This point is not clear in the JVM spec. *)\n  Inductive assign_compatible_num : DEX_num -> DEX_primitiveType -> Prop :=\n   | assign_compatible_int_int : forall i, assign_compatible_num (I i) DEX_INT\n   | assign_compatible_short_int : forall sh, assign_compatible_num (Sh sh) DEX_INT\n   | assign_compatible_byte_int : forall b, assign_compatible_num (B b) DEX_INT\n   | assign_compatible_short_short : forall sh, assign_compatible_num (Sh sh) DEX_SHORT\n   | assign_compatible_byte_byte : forall b, assign_compatible_num (B b) DEX_BYTE\n   | assign_compatible_byte_boolean : forall b, assign_compatible_num (B b) DEX_BOOLEAN.\n\n  (** [assign_compatible h source target] holds if a value [source] can be \n    assigned to a variable of type [target] *)\n  Inductive assign_compatible (p:DEX_Program) : DEX_value -> DEX_type -> Prop :=\n   | assign_compatible_num_val : forall (n:DEX_num) (t:DEX_primitiveType),\n       assign_compatible_num n t -> assign_compatible p (Num n) (DEX_PrimitiveType t).\n\n  Definition SemCompInt (cmp:DEX_CompInt) (z1 z2: Z) : Prop :=\n    match cmp with\n      DEX_EqInt =>  z1=z2\n    | DEX_NeInt => z1<>z2\n    | DEX_LtInt => z1<z2\n    | DEX_LeInt => z1<=z2\n    | DEX_GtInt => z1>z2\n    | DEX_GeInt => z1>=z2\n    end.\n\n  Definition SemBinopInt (op:DEX_BinopInt) (i1 i2:Int.t) : Int.t :=\n    match op with \n    | DEX_AddInt => Int.add i1 i2\n    | DEX_AndInt => Int.and i1 i2\n    | DEX_DivInt => Int.div i1 i2\n    | DEX_MulInt => Int.mul i1 i2\n    | DEX_OrInt => Int.or i1 i2\n    | DEX_RemInt => Int.rem i1 i2\n    | DEX_ShlInt => Int.shl i1 i2\n    | DEX_ShrInt => Int.shr i1 i2\n    | DEX_SubInt => Int.sub i1 i2\n    | DEX_UshrInt => Int.ushr i1 i2\n    | DEX_XorInt => Int.xor i1 i2\n    end.\n\nEnd DEX_SEMANTIC_DOMAIN.", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/DEX_I/DEX_Domain.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21518379462501686}}
{"text": "Require Export MicroBFTprops2.\n\n\nSection MicroBFTass_diss_if_kn.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext          }.\n  Context { microbft_context    : MicroBFT_context      }.\n  Context { m_initial_keys      : MicroBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys     }.\n  Context { usig_hash           : USIG_hash             }.\n  Context { microbft_auth       : MicroBFT_auth         }.\n\n\n  Lemma ASSUMPTION_disseminate_if_knows_true :\n    forall (eo : EventOrdering) d, assume_eo eo (ASSUMPTION_disseminate_if_knows d).\n  Proof.\n    introv diss.\n    simpl in *.\n    exrepnd.\n\n    unfold disseminate_data in *.\n    unfold knows_after. simpl in *.\n(*    unfold MicroBFT_data_knows.\n    unfold MicroBFT_data_in_log. *)\n    unfold state_after. simpl.\n\n    (* exists c. *)\n\n\n    unfold M_byz_output_sys_on_event in *; simpl.\n    rewrite M_byz_output_ls_on_event_as_run in diss0; simpl.\n    unfold M_byz_output_ls_on_this_one_event in *.\n    allrw; simpl.\n\n    unfold MicroBFTheader.node2name in *. simpl in *; subst.\n    unfold MicroBFTsys in *. simpl in *.\n\n    SearchAbout M_byz_run_ls_before_event.\n\n    pose proof (ex_M_byz_run_ls_before_event_MicroBFTlocalSys e (loc e)) as run.\n    repndors.\n    {\n      exrepnd.\n      rewrite run0 in *. clear run0. simpl in *.\n\n      remember (trigger e) as trig. symmetry in Heqtrig.\n      destruct trig; simpl in *; ginv; tcsp;[].\n      unfold state_of_trusted in *. simpl in *.\n      unfold USIG_update in *. destruct i; simpl in *; ginv; subst; tcsp;[|].\n      {\n        destruct diss0; simpl in *; ginv; tcsp.\n\n        eexists; dands; eauto;[|].\n        {\n          eexists; dands; eauto.\n          erewrite M_state_sys_on_event_unfold.\n          erewrite map_option_Some.\n          \n\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MicroBFTass_diss_if_kn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526660244838, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.21514255664728985}}
{"text": "From Perennial.program_proof Require Import grove_prelude.\nFrom Goose.github_com.mit_pdos.gokv Require Import pb.\nFrom Perennial.program_proof.pb Require Export ghost_proof.\n\n(*\n  Ownership/repr predicates for owning a ghost replica.\n\n  The state of a replica is split into the core Replica state, the extra state\n  that a Primary has, and the extra state that a Committer has. A committer is\n  just a replica that also keeps information about what part of the log has been\n  committed.\n *)\nSection replica_ghost_defns.\n\nContext `{!heapGS Σ}.\nContext `{!urpcregG Σ}.\nContext `{!pb_ghostG Σ}.\nImplicit Type γ:pb_names.\n\nRecord Replica := mkReplica\n{\n  opLog : list u8;\n  cn : u64;\n}.\n\nDefinition own_Replica_ghost (rid:u64) γ (r:Replica) : iProp Σ :=\n  \"Haccepted\" ∷ accepted_ptsto γ r.(cn) rid r.(opLog) ∗\n  \"HacceptedUnused\" ∷ ([∗ set] cn_some ∈ (fin_to_set u64),\n                      ⌜int.Z cn_some ≤ int.Z r.(cn)⌝ ∨ accepted_ptsto γ cn_some rid []\n                      ) ∗\n  \"#Hproposal_lb\" ∷ proposal_lb_fancy γ r.(cn) r.(opLog)\n.\n\n(* A primary is a replica with some more stuff; technically, the rid from the\n   replica is not necessary to have a primary*)\nRecord PrimaryExtra := mkPrimaryExtra\n{\n  conf : list u64;\n  matchIdx : list u64;\n}.\n\nDefinition own_Primary_ghost γ (r:Replica) (p:PrimaryExtra) : iProp Σ :=\n  \"HprimaryOwnsProposal\" ∷ proposal_ptsto γ r.(cn) r.(opLog) ∗\n  \"#HconfPtsto\" ∷ config_ptsto γ r.(cn) p.(conf) ∗\n  \"#HmatchIdxAccepted\" ∷ [∗ list] _ ↦ rid;j ∈ p.(conf); p.(matchIdx), accepted_lb γ r.(cn) rid (take (int.nat j) r.(opLog))\n.\n\nRecord CommitterExtra := mkCommitterExtra\n{\n  commitIdx : u64;\n}.\n\nDefinition own_Committer_ghost γ (r:Replica) (c:CommitterExtra) : iProp Σ :=\n  \"#Hcommit_lb\" ∷ commit_lb_by γ r.(cn) (take (int.nat c.(commitIdx)) r.(opLog)) ∗\n  \"%HcommitLeLogLen\" ∷ ⌜int.Z c.(commitIdx) <= length r.(opLog)⌝\n.\n\nEnd replica_ghost_defns.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/pb/replica_ghost_defns.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.21514254561530477}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import stdlib. \nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nLocal Open Scope assert.\n\nParameter mem_mgr: globals -> mpred.\nParameter malloc_token': share -> Z -> val -> mpred.\nParameter malloc_token'_valid_pointer: forall sh sz p, malloc_token' sh sz p |-- valid_pointer p.\nAxiom make_mem_mgr: forall gv, emp |-- mem_mgr gv.\n\nDefinition malloc_token {cs: compspecs} sh t v := \n   !! field_compatible t [] v && \n   malloc_token' sh (sizeof t) v.\nLemma malloc_token_valid_pointer: forall {cs: compspecs} sh t p, malloc_token sh t p |-- valid_pointer p.\nProof. intros. unfold malloc_token.\n apply andp_left2. apply malloc_token'_valid_pointer. Qed.\n\nHint Resolve malloc_token'_valid_pointer : valid_pointer.\nHint Resolve malloc_token_valid_pointer : valid_pointer.\n\nParameter malloc_token'_local_facts:  forall sh sz p, malloc_token' sh sz p |-- !! malloc_compatible sz p.\nLemma malloc_token_local_facts:  forall {cs: compspecs} sh t p, malloc_token sh t p |-- !! (field_compatible t [] p /\\ malloc_compatible (sizeof t) p).\nProof. intros.\n unfold malloc_token.\n normalize. rewrite prop_and.\n apply andp_right. apply prop_right; auto.\n apply malloc_token'_local_facts.\nQed.\nHint Resolve malloc_token'_local_facts : saturate_local.\nHint Resolve malloc_token_local_facts : saturate_local.\n\nDefinition malloc_spec' :=\n DECLARE _malloc\n   WITH n:Z, gv: globals\n   PRE [ 1%positive OF size_t ]\n       PROP (0 <= n <= Ptrofs.max_unsigned)\n       LOCAL (temp 1%positive (Vptrofs (Ptrofs.repr n)); gvars gv)\n       SEP (mem_mgr gv)\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (mem_mgr gv;\n             if eq_dec p nullval then emp\n            else (malloc_token' Ews n p * memory_block Ews n p)).\n\nDefinition free_spec' :=\n DECLARE _free\n   WITH n:Z, p:val, gv: globals\n   PRE [ 1%positive OF tptr tvoid ]\n       PROP ()\n       LOCAL (temp 1%positive p; gvars gv)\n       SEP (mem_mgr gv;\n              if eq_dec p nullval then emp\n              else (malloc_token' Ews n p * memory_block Ews n p))\n    POST [ Tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (mem_mgr gv).\n\nDefinition exit_spec :=\n DECLARE _exit\n WITH u: unit\n PRE [1%positive OF tint]\n   PROP () LOCAL() SEP()\n POST [ tvoid ]\n   PROP(False) LOCAL() SEP().\n\nDefinition placeholder_spec :=\n DECLARE _placeholder\n WITH u: unit\n PRE [ ]\n   PROP (False) LOCAL() SEP()\n POST [ tint ]\n   PROP() LOCAL() SEP().\n\nDefinition ispecs := [placeholder_spec].\nDefinition specs := [malloc_spec'; free_spec'; exit_spec].\n\nDefinition malloc_spec  {cs: compspecs} (t: type) :=\n DECLARE _malloc\n   WITH gv: globals\n   PRE [ 1%positive OF size_t ]\n       PROP (0 <= sizeof t <= Ptrofs.max_unsigned;\n                complete_legal_cosu_type t = true;\n                natural_aligned natural_alignment t = true)\n       LOCAL (temp 1%positive (Vptrofs (Ptrofs.repr (sizeof t))); gvars gv)\n       SEP (mem_mgr gv)\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (mem_mgr gv;\n             if eq_dec p nullval then emp\n            else (malloc_token Ews t p * data_at_ Ews t p)).\n\nDefinition free_spec  {cs: compspecs} (t: type) :=\n DECLARE _free\n   WITH p: val, gv: globals\n   PRE [ 1%positive OF tptr tvoid ]\n       PROP ()\n       LOCAL (temp 1%positive p; gvars gv)\n       SEP (mem_mgr gv;\n              if eq_dec p nullval then emp\n              else (malloc_token Ews t p * data_at_ Ews t p))\n    POST [ Tvoid ]\n       PROP ()\n       LOCAL ()\n       SEP (mem_mgr gv).\n\nLemma malloc_spec_sub:\n forall {cs: compspecs} (t: type), \n   funspec_sub (snd malloc_spec') (snd (malloc_spec t)).\nProof.\nintros.\napply NDsubsume_subsume.\nsplit; extensionality x; reflexivity.\nsplit3; auto.\nintros gv.\nsimpl in gv.\nExists (sizeof t, gv) emp.\nchange (liftx emp) with (@emp (environ->mpred) _ _).\nrewrite !emp_sepcon.\napply andp_right.\nentailer!.\nmatch goal with |- _ |-- prop ?PP => set (P:=PP) end.\nentailer!.\nsubst P.\nIntros p.\nExists p.\nentailer!.\nif_tac; auto.\nunfold malloc_token.\nassert_PROP (field_compatible t [] p).\nentailer!.\napply malloc_compatible_field_compatible; auto.\nentailer!.\nrewrite memory_block_data_at_; auto.\nQed.\n\nLemma free_spec_sub:\n forall {cs: compspecs} (t: type), \n   funspec_sub (snd free_spec') (snd (free_spec t)).\nProof.\nintros.\napply NDsubsume_subsume.\nsplit; extensionality x; reflexivity.\nsplit3; auto.\nintros (p,gv).\nsimpl in gv.\nExists (sizeof t, p, gv) emp.\nchange (liftx emp) with (@emp (environ->mpred) _ _).\nrewrite !emp_sepcon.\napply andp_right.\nif_tac.\nentailer!.\nentailer!. simpl in H0.\nunfold malloc_token. entailer!.\napply data_at__memory_block_cancel.\napply prop_right.\nentailer!.\nQed.\n\n", "meta": {"author": "anshumanmohan", "repo": "RamifyCoq_VST", "sha": "0517a39b069f79f50a45321db6ca81c48397b73d", "save_path": "github-repos/coq/anshumanmohan-RamifyCoq_VST", "path": "github-repos/coq/anshumanmohan-RamifyCoq_VST/RamifyCoq_VST-0517a39b069f79f50a45321db6ca81c48397b73d/VST/progs/pile/spec_stdlib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926666143434, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.215119730146225}}
{"text": "Require Import LibTactics.\nRequire Import Metalib.Metatheory.\n\nRequire Import\n        syntax_ott\n        rules_inf\n        Infrastructure\n        KeyProperties\n        SubtypingInversion\n        Disjointness\n        Deterministic\n        Progress.\n\nRequire Import Arith Lia.\n\n\n#[export]\nHint Extern 0 => match goal with\n                   | [ H1: ~topLike ?A, H2: topLike (t_rcd _ ?A) |- _ ] => (exfalso; apply H1; inverts H2)\n                 end : falseHd.\n\n\nTheorem consistent_sound: forall v1 v2 A B,\n    value v1 -> value v2 ->\n    Typing nil v1 Inf A -> Typing nil v2 Inf B ->\n    consistent v1 v2 -> consistencySpec v1 v2.\nProof.\n  intros v1 v2 A B Val1 Val2 Typ1 Typ2 Cons.\n  unfolds. intros C v1' v2' Ord R1 R2.\n  forwards*: TypedReduce_unique Cons.\nQed.\n\n\nLemma consistent_mergel: forall v1 v2 v,\n    lc_exp v1 -> lc_exp v2 -> consistent (e_merge v1 v2) v -> consistent v1 v /\\ consistent v2 v.\nProof.\n  intros v1 v2 v Lc1 Lc2 H.\n  inductions H.\n  -\n    inverts H.\n    lets* (?&?): disjoint_splitl H1.\n  - split; eauto.\n  - forwards (?&?): IHconsistent1; try reflexivity; auto.\n    forwards (?&?): IHconsistent2; try reflexivity; auto.\nQed.\n\nLemma consistent_merger: forall v1 v2 v,\n    lc_exp v1 -> lc_exp v2 -> consistent v (e_merge v1 v2) -> consistent v v1 /\\ consistent v v2.\nProof.\n  intros v1 v2 v Lc1 Lc2 H.\n  inductions H.\n  -\n    inverts H0.\n    lets* (?&?): disjoint_splitr H1.\n  - forwards (?&?): IHconsistent1; try reflexivity; auto.\n    forwards (?&?): IHconsistent2; try reflexivity; auto.\n  - split; eauto.\nQed.\n\n\nLemma consistencySpec_mergel: forall v1 v2 v,\n    lc_exp v1 -> lc_exp v2 -> consistencySpec (e_merge v1 v2) v -> consistencySpec v1 v /\\ consistencySpec v2 v.\nProof.\n  intros v1 v2 v Lc1 Lc2 H.\n  split; unfolds; intros.\n  - forwards*: H A.\n  - forwards*: H A.\nQed.\n\nLemma consistencySpec_merger: forall v1 v2 v,\n    lc_exp v1 -> lc_exp v2 -> consistencySpec v (e_merge v1 v2) -> consistencySpec v v1 /\\ consistencySpec v v2.\nProof.\n  intros v1 v2 v Lc1 Lc2 H.\n  split; unfolds; intros.\n  - forwards*: H A.\n  - forwards*: H A.\nQed.\n\nLemma topLike_disjoint: forall A B,\n    topLike A -> disjointSpec A B.\nProof.\n  intros A B H.\n  unfolds. intros C H0 H1.\n  apply topLike_super_top in H.\n  apply topLike_super_top.\n  auto_sub.\nQed.\n\n\nLemma disjoint_or_exists: forall A B,\n    disjoint A B \\/ exists C, ord C /\\ algo_sub A C /\\ algo_sub B C /\\ ~ topLike C.\nProof with solve_false.\n  intros A B. gen B.\n  induction A; intros; auto.\n  - induction B; auto.\n    + right. exists t_int.\n      repeat split~...\n    + lets [?|(?&?&?&?&?)]: IHB1.\n      * lets [?|(?&?&?&?&?)]: IHB2.\n        ** left*.\n        ** right. exists* x.\n      * right. exists* x.\n  - clear IHA1.\n    induction B; auto.\n    + clear IHB1 IHB2.\n      lets [?|(?&?&?&?&?)]: (IHA2 B2); jauto.\n      * right. exists* (t_arrow (t_and A1 B1) x).\n    + lets [?|(?&?&?&?&?)]: IHB1.\n      * lets [?|(?&?&?&?&?)]: IHB2; auto.\n        ** right. exists* x.\n      * right. exists* x.\n  - lets [?|(?&?&?&?&?)]: IHA1.\n    lets [?|(?&?&?&?&?)]: IHA2.\n    * left*.\n    * right. exists* x.\n    * right. exists* x.\n  - (* rcd *)\n    induction~ B.\n    + lets [?|(?&?&?&?&?)]: IHB1.\n      * lets [?|(?&?&?&?&?)]: IHB2; auto.\n        ** right. exists* x.\n      * right. exists* x.\n    + destruct* (l == l0). subst.\n      lets~ [?|(?&?&?&?&?)]: (IHA B).\n      right. exists (t_rcd l0 x). splits*.\n      intros HF. apply H2. inverts~ HF.\nQed.\n\nLemma consistencySpec_lams_inv : forall T1 T2 e1 e2 A1 A2 B1 B2,\n    Typing nil (e_abs A1 e1 B1) Inf T1 -> Typing nil (e_abs A2 e2 B2) Inf T2 ->\n    consistencySpec (e_abs A1 e1 B1) (e_abs A2 e2 B2) -> disjoint B1 B2 \\/ (e1=e2) /\\ (A1=A2).\nProof.\n  introv Typ1 Typ2 Cons.\n  inverts keep Typ1. inverts keep Typ2.\n  lets~ [?|(?&?&?&?&?)]: disjoint_or_exists B1 B2.\n  right.\n  assert (S1: algo_sub (t_arrow A1 B1) (t_arrow (t_and A1 A2) x)) by auto_sub.\n  assert (S2: algo_sub (t_arrow A2 B2) (t_arrow (t_and A1 A2) x)) by auto_sub.\n  forwards~ T1: Typ_sub Typ1 S1.\n  forwards~ T2: Typ_sub Typ2 S2.\n  forwards* (?&R1) : TypedReduce_progress T1.\n  forwards* (?&R2) : TypedReduce_progress T2.\n  forwards~ : Cons R1 R2.\n  inverts keep R1; inverts keep R2; solve_false.\n  (* TEMP0 : e_abs A0 e0 x = e_abs A e x *)\n  inverts~ TEMP0.\nQed.\n\nLemma consistencySpec_rcd_inv : forall T1 T2 l v1 v2,\n    value v1 -> value v2 -> nil ⊢ v1 ⇒ T1 -> nil ⊢ v2 ⇒ T2 ->\n    consistencySpec (e_rcd l v1) (e_rcd l v2) -> consistencySpec v1 v2.\nProof.\n  intros T1 T2 l v1 v2 Val1 Val2 Typ1 Typ2 Cons.\n  unfolds. introv Ord R1 R2.\n  destruct (toplike_decidable A).\n  - forwards~: TypedReduce_toplike R1 R2.\n  - forwards*: Cons (t_rcd l A).\n    inversion~ H0.\nQed.\n\nLtac indExpSize s :=\n  assert (SizeInd: exists i, s < i) by eauto;\n  destruct SizeInd as [i SizeInd];\n  repeat match goal with | [ h : exp |- _ ] => (gen h) end;\n  induction i as [|i IH]; [\n      intros; match goal with | [ H : _ < 0 |- _ ] => inverts H end\n    | intros ].\n\nTheorem consistent_complete: forall v1 v2 A B,\n    value v1 -> value v2 ->\n    Typing nil v1 Inf A -> Typing nil v2 Inf B ->\n    consistencySpec v1 v2 -> consistent v1 v2.\nProof with (simpl; try lia; auto).\n  intros v1 v2 A B Val1 Val2 Typ1 Typ2 Cons. gen Val1 Val2 Cons A B.\n  indExpSize (size_exp v1 + size_exp v2);\n  inverts Val1 as V1_1 V1_2; inverts Val2 as V2_1 V2_2; simpl in SizeInd;\n    try solve [\n          inverts Typ1 as T1_1 T1_2; inverts Typ2 as T2_1 T2_2;\n            match goal with\n            | |- consistent (e_merge _ _) _ =>\n              ( lets~ (C1&C2): consistencySpec_mergel Cons;\n                forwards*: IH C1; simpl; try lia; auto;\n                try forwards*: IH C2; simpl; try lia; auto\n              )\n            | |- consistent _ (e_merge _ _) =>\n              ( lets~ (C1&C2): consistencySpec_merger Cons;\n                forwards*: IH C1; simpl; try lia; auto;\n                try forwards*: IH C2; simpl; try lia; auto\n              )\n            | _ =>\n              ( applys C_disjoint; constructor* )\n            end].\n  - (* lit *)\n    inverts keep Typ1; inverts keep Typ2.\n    enough (i5=i0).\n    subst~.\n    forwards* (?&R1) : TypedReduce_progress (e_lit i0).\n    forwards* (?&R2) : TypedReduce_progress (e_lit i5).\n    forwards*: Cons. subst*.\n    forwards R1': TReduce_refl i0. forwards R2': TReduce_refl i5.\n    forwards*: TypedReduce_unique R1 R1'.\n    forwards*: TypedReduce_unique R2 R2'.\n    congruence.\n  - (* abs *)\n    forwards* [?|(?&?)]: consistencySpec_lams_inv Cons.\n    + applys* C_disjoint.\n    + subst*.\n  - (* rcd *)\n    inverts keep Typ1; inverts keep Typ2.\n    destruct (l0==l1).\n    + subst*.\n      forwards~ Con': consistencySpec_rcd_inv H1 H2 Cons.\n      forwards*: IH Con'...\n    + applys C_disjoint; constructor*.\nQed.\n\n\nLemma consistent_lams_inv : forall T1 T2 e1 e2 A1 A2 B1 B2,\n    Typing nil (e_abs A1 e1 B1) Inf T1 -> Typing nil (e_abs A2 e2 B2) Inf T2 ->\n    consistent (e_abs A1 e1 B1) (e_abs A2 e2 B2) -> disjoint B1 B2 \\/ (e1=e2) /\\ (A1=A2).\nProof.\n  introv Typ1 Typ2 Cons.\n  eapply consistent_sound in Cons; eauto.\n  forwards* : consistencySpec_lams_inv Cons.\nQed.\n\nLemma consistent_rcd_inv : forall l v1 v2,\n    consistent (e_rcd l v1) (e_rcd l v2) -> consistent v1 v2.\nProof.\n  intros l v1 v2 H.\n  inverts~ H.\n  - inverts H0. inverts H1.\n    enough (Dis: disjoint A0 A).\n    applys* C_disjoint Dis. eauto.\nQed.\n\n#[export]\nHint Immediate consistent_rcd_inv : core.\n", "meta": {"author": "XSnow", "repo": "TamingMerge", "sha": "f2c55da56db597ed94a1a45a49c31e2869362d9c", "save_path": "github-repos/coq/XSnow-TamingMerge", "path": "github-repos/coq/XSnow-TamingMerge/TamingMerge-f2c55da56db597ed94a1a45a49c31e2869362d9c/plus/coq/Consistency.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21501087096214241}}
{"text": "Set Implicit Arguments.\n\nRequire Import Pattern.PatternImplDef.\nRequire Import Pattern.PatternImplTheory.\nRequire Import Pattern.PatternInterface.\nRequire Import Coq.Lists.List.\nRequire Import Wildcard.Wildcard.\nRequire Import Network.NetworkPacket.\nRequire Import Coq.Classes.Equivalence.\n\nLocal Open Scope equiv_scope.\n\nModule Pattern : PATTERN.\n\n  Record pat := Pat {\n    raw : pattern;\n    valid : ValidPattern raw\n  }.\n\n  Definition t := pat.\n\n  Definition beq (p1 p2 : t) :=\n    match eq_dec (raw p1) (raw p2) with\n      | left _ => true\n      | right _ => false\n    end.\n\n  Definition inter (p1 p2 : t) := \n    Pat (inter_preserves_valid (valid p1) (valid p2)).\n\n\n  Lemma all_is_Valid : ValidPattern all.\n  Proof.\n    apply ValidPat_any.\n  Qed.\n\n  Definition all : t := Pat all_is_Valid.\n\n  Lemma empty_is_valid : ValidPattern empty.\n  Proof.\n    apply ValidPat_None.\n    reflexivity.\n  Qed.\n\n  Definition empty : t := Pat empty_is_valid.\n\n  Definition exact_pattern pk pt : t :=\n    Pat (exact_is_valid pt pk).\n\n  Definition is_empty pat : bool := is_empty (raw pat).\n\n  Definition match_packet pt pk pat : bool :=\n    match_packet pt pk (raw pat).\n\n  Definition is_exact pat : bool := is_exact (raw pat).\n\n  Definition to_match pat (H : is_empty pat = false) :=\n    to_match (raw pat) H.\n\n  Section Constructors.\n\n    Definition inPort pt : t :=\n      @Pat\n        (Pattern \n           WildcardAll\n           WildcardAll\n           WildcardAll\n           WildcardAll\n           WildcardAll \n           WildcardAll \n           WildcardAll\n           WildcardAll \n           WildcardAll \n           WildcardAll \n           WildcardAll\n           (WildcardExact pt))\n        (ValidPat_any _ _ _ _ _ _).\n\n    Definition dlSrc dlAddr : t :=\n      @Pat\n        (Pattern \n          (WildcardExact dlAddr)\n           WildcardAll\n           WildcardAll\n           WildcardAll\n           WildcardAll \n           WildcardAll \n           WildcardAll\n           WildcardAll \n           WildcardAll \n           WildcardAll \n           WildcardAll\n           WildcardAll)\n        (ValidPat_any (WildcardExact dlAddr) _ _ _ _ _).\n\n    Definition dlDst dlAddr : t :=\n      @Pat\n        (Pattern \n           WildcardAll\n          (WildcardExact dlAddr)\n           WildcardAll\n           WildcardAll\n           WildcardAll \n           WildcardAll \n           WildcardAll\n           WildcardAll \n           WildcardAll \n           WildcardAll \n           WildcardAll\n           WildcardAll)\n        (ValidPat_any _ (WildcardExact dlAddr) _ _ _ _).\n\n    Definition dlTyp typ : t :=\n      @Pat\n        (Pattern \n           WildcardAll\n           WildcardAll\n           (WildcardExact typ)\n           WildcardAll\n           WildcardAll \n           WildcardAll \n           WildcardAll\n           WildcardAll \n           WildcardAll \n           WildcardAll \n           WildcardAll\n           WildcardAll)\n        (ValidPat_any _ _ (WildcardExact typ) _ _ _).\n\n    Definition dlVlan vlan : t :=\n      @Pat\n        (Pattern \n           WildcardAll\n           WildcardAll\n           WildcardAll\n           (WildcardExact vlan)\n           WildcardAll\n           WildcardAll \n           WildcardAll \n           WildcardAll \n           WildcardAll \n           WildcardAll \n           WildcardAll\n           WildcardAll)\n        (ValidPat_any _ _ _ (WildcardExact vlan) _ _).\n\n    Definition dlVlanPcp pcp : t :=\n      @Pat\n        (Pattern \n           WildcardAll\n           WildcardAll\n           WildcardAll\n           WildcardAll\n           (WildcardExact pcp)\n           WildcardAll \n           WildcardAll \n           WildcardAll \n           WildcardAll \n           WildcardAll \n           WildcardAll\n           WildcardAll)\n        (ValidPat_any _ _ _ _ (WildcardExact pcp) _).\n\n    Definition ipSrc addr : t :=\n      @Pat\n        (Pattern\n          WildcardAll\n          WildcardAll\n          (WildcardExact Const_0x800)\n          WildcardAll\n          WildcardAll\n          (WildcardExact addr)\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          WildcardAll)\n        (ValidPat_IP_any _ _ _ _ (WildcardExact addr) _ _ _ _).\n\n    Definition ipDst addr : t :=\n      @Pat\n        (Pattern\n          WildcardAll\n          WildcardAll\n          (WildcardExact Const_0x800)\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          (WildcardExact addr)\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          WildcardAll)\n        (ValidPat_IP_any _ _ _ _ _ (WildcardExact addr) _ _ _).\n\n    Definition ipProto proto : t :=\n      @Pat\n        (Pattern\n          WildcardAll\n          WildcardAll\n          (WildcardExact Const_0x800)\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          (WildcardExact proto)\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          WildcardAll)\n        (ValidPat_IP_any _ _ _ _ _ _ _ _ (WildcardExact proto)).\n\n    Definition tpSrcPort proto (H : In proto SupportedNwProto) tpPort : t :=\n      @Pat\n        (Pattern\n          WildcardAll\n          WildcardAll\n          (WildcardExact Const_0x800)\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          (WildcardExact proto)\n          WildcardAll\n          (WildcardExact tpPort)\n          WildcardAll\n          WildcardAll)\n        (@ValidPat_TCPUDP _ _ _ _ _ _ _ (WildcardExact tpPort) _ _ _ H).\n\n    Definition tpDstPort proto (H : In proto SupportedNwProto) tpPort : t :=\n      @Pat\n        (Pattern\n          WildcardAll\n          WildcardAll\n          (WildcardExact Const_0x800)\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          WildcardAll\n          (WildcardExact proto)\n          WildcardAll\n          WildcardAll\n          (WildcardExact tpPort)\n          WildcardAll)\n        (@ValidPat_TCPUDP _ _ _ _ _ _ _ _ (WildcardExact tpPort) _ _ H).\n\n    Lemma TCP_is_supported : In Const_0x6 SupportedNwProto.\n    Proof with auto with datatypes.\n      unfold SupportedNwProto...\n    Qed.\n\n    Lemma UDP_is_supported : In Const_0x7 SupportedNwProto.\n    Proof with auto with datatypes.\n      unfold SupportedNwProto...\n    Qed.\n\n    Definition tcpSrcPort := tpSrcPort TCP_is_supported.\n\n    Definition tcpDstPort := tpDstPort TCP_is_supported.\n\n    Definition udpSrcPort := tpSrcPort UDP_is_supported.\n\n    Definition udpDstPort := tpDstPort UDP_is_supported.\n\n  End Constructors.\n\n\n    Definition equiv (pat1 pat2 : t) : Prop :=\n      forall pt pk, \n        match_packet pt pk pat1 = match_packet pt pk pat2.\n\n    Lemma equiv_is_Equivalence : Equivalence equiv.\n    Proof with auto.\n      unfold equiv.\n      unfold match_packet.\n      split.\n      unfold Reflexive...\n      unfold Symmetric...\n      unfold Transitive...\n      intros.\n      rewrite -> H...\n    Qed.\n\n\nInstance Pattern_Equivalence : Equivalence equiv.\n  apply equiv_is_Equivalence.\nQed.\n\nSection Lemmas.\n\n  Lemma inter_comm : forall (p p0 : pat),  equiv (inter p p0) (inter p0 p).\n  Proof with auto.\n    unfold equiv.\n    unfold match_packet.\n    unfold inter.\n    intros.\n    simpl.\n    rewrite -> inter_comm...\n  Qed.\n\n  Lemma inter_assoc : forall (p p' p'' : pat),\n    equiv (inter p (inter p' p'')) (inter (inter p p') p'').\n  Proof with auto.\n    unfold equiv.\n    unfold match_packet.\n    unfold inter.\n    intros.\n    simpl.\n    rewrite -> inter_assoc...\n  Qed.\n\n  Hint Unfold inter is_empty is_exact equiv match_packet.\n\n  Lemma is_empty_false_distr_l : forall x y,\n    is_empty (inter x y) = false -> \n    is_empty x = false .\n  Proof with eauto.\n    intros.\n    autounfold in *.\n    eapply is_empty_false_distr_l...\n  Qed.\n\n  Lemma is_empty_false_distr_r : forall x y,\n    is_empty (inter x y) = false -> \n    is_empty y = false.\n  Proof with eauto.\n    intros.\n    autounfold in *.\n    eapply is_empty_false_distr_r...\n  Qed.\n\n  Lemma is_empty_true_l : forall x y,\n    is_empty x = true ->\n    is_empty (inter x y) = true.\n  Proof with eauto.\n    intros.\n    autounfold in *.\n    eapply is_empty_true_l...\n  Qed.\n\n  Lemma is_empty_true_r : forall x y,\n    is_empty y = true ->\n    is_empty (inter x y) = true.\n  Proof with eauto.\n    intros.\n    autounfold in *.\n    eapply is_empty_true_r...\n  Qed.\n\n  Lemma is_match_false_inter_l :\n    forall pt (pkt : packet) pat1 pat2,\n      match_packet pt pkt pat1 = false ->\n      match_packet pt pkt (inter pat1 pat2) = false.\n  Proof with eauto.\n    intros.\n    autounfold in *.\n    eapply is_match_false_inter_l...\n  Qed.\n\n  Lemma is_match_false_inter_r :\n    forall pt (pkt : packet) pat1 pat2,\n      match_packet pt pkt pat2 = false ->\n      match_packet pt pkt (inter pat1 pat2) = false.\n  Proof with eauto.\n    intros.\n    autounfold in *.\n    eapply is_match_false_inter_r...\n  Qed.\n\n  Lemma no_match_subset_r : forall k n t t',\n    match_packet n k t' = false -> \n    match_packet n k (inter t t') = false.\n  Proof with eauto.\n    intros.\n    autounfold in *.\n    eapply no_match_subset_r...\n  Qed.\n\n  Lemma exact_match_inter : forall x y,\n    is_exact x = true ->\n    is_empty (inter x y) = false ->\n    equiv (inter x y) x.\n  Proof with eauto.\n    intros.\n    unfold equiv.\n    unfold match_packet.\n    intros.\n    destruct x.\n    destruct y.\n    unfold is_exact in *.\n    unfold inter in *.\n    unfold is_empty in *.\n    simpl in H.\n    simpl in H0.\n    pose (J := PatternImplTheory.exact_match_inter _ _ H H0).\n    simpl.\n    rewrite -> J...\n  Qed.\n\n  Lemma all_spec : forall pt pk,\n    match_packet pt pk all = true.\n  Proof with auto.\n    unfold all.\n    unfold match_packet.\n    simpl.\n    exact all_spec.\n  Qed.\n\n  Lemma all_is_not_empty : is_empty all = false.\n  Proof.\n    reflexivity.\n  Qed.\n\n  Lemma exact_match_is_exact : forall pk pt,\n    is_exact (exact_pattern pk pt) = true.\n  Proof with auto.\n    unfold exact_pattern.\n    unfold is_exact.\n    intros.\n    apply exact_match_is_exact.\n  Qed.\n\n  Lemma exact_intersect : forall k n t,\n    match_packet k n t = true ->\n    equiv (inter (exact_pattern n k) t) (exact_pattern n k).\n  Proof with auto.\n    unfold equiv.\n    unfold exact_pattern.\n    unfold match_packet.\n    unfold inter.\n    intros.\n    simpl.\n    pose (J := exact_intersect k n (raw t0) H).\n    rewrite -> J...\n  Qed.  \n\n  Lemma is_match_true_inter : forall pat1 pat2 pt pk,\n    match_packet pt pk pat1 = true ->\n    match_packet pt pk pat2 = true ->\n    match_packet pt pk (inter pat1 pat2) = true.\n  Proof with auto.\n    intros.\n    unfold match_packet in *.\n    unfold inter.\n    simpl.\n    rewrite -> is_match_true_inter...\n  Qed.\n\n  Lemma beq_true_spec : forall p p',\n    beq p p' = true ->\n    equiv p p'.\n  Proof with auto.\n    intros.\n    unfold equiv.\n    unfold match_packet.\n    destruct p.\n    destruct p'.\n    unfold beq in H.\n    simpl in H.\n    destruct (eq_dec raw0 raw1); subst...\n    inversion H.\n  Qed.\n\n  Lemma match_packet_spec : forall pt pk pat,\n    match_packet pt pk pat = \n    negb (is_empty (inter (exact_pattern pk pt) pat)).\n  Proof.\n    intros.\n    destruct pat0.\n    unfold match_packet.\n    unfold is_empty.\n    unfold inter.\n    unfold exact_pattern.\n    unfold PatternImplDef.match_packet.\n    unfold raw.\n    reflexivity.\n  Qed.\n\nEnd Lemmas.\n\nEnd Pattern.\n\nDefinition pattern := Pattern.t.\n", "meta": {"author": "frenetic-lang", "repo": "featherweight-openflow", "sha": "4470518794e3ed867919d30500be2d0128b1de1c", "save_path": "github-repos/coq/frenetic-lang-featherweight-openflow", "path": "github-repos/coq/frenetic-lang-featherweight-openflow/featherweight-openflow-4470518794e3ed867919d30500be2d0128b1de1c/coq/Pattern/Pattern.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21490684071289798}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Elimination of unneeded computations over RTL: correctness proof. *)\n\nRequire Import Coqlib Maps Errors Integers Floats Lattice Kildall.\nRequire Import AST Linking.\nRequire Import Values Memory Globalenvs Events Smallstep.\nRequire Import Registers Op RTL.\nRequire Import ValueDomain ValueAnalysis NeedDomain NeedOp Deadcode.\n\nDefinition match_prog (prog tprog: RTL.program) :=\n  match_program (fun cu f tf => transf_fundef (romem_for cu) f = OK tf) eq prog tprog.\n\nLemma transf_program_match:\n  forall prog tprog, transf_program prog = OK tprog -> match_prog prog tprog.\nProof.\n  intros. eapply match_transform_partial_program_contextual; eauto.\nQed.\n\n(** * Relating the memory states *)\n\n(** The [magree] predicate is a variant of [Mem.extends] where we\n  allow the contents of the two memory states to differ arbitrarily\n  on some locations.  The predicate [P] is true on the locations whose\n  contents must be in the [lessdef] relation. *)\n\nDefinition locset := block -> Z -> Prop.\n\nRecord magree (m1 m2: mem) (P: locset) : Prop := mk_magree {\n  ma_perm:\n    forall b ofs k p,\n    Mem.perm m1 b ofs k p -> Mem.perm m2 b ofs k p;\n  ma_perm_inv:\n    forall b ofs k p,\n    Mem.perm m2 b ofs k p -> Mem.perm m1 b ofs k p \\/ ~Mem.perm m1 b ofs Max Nonempty;\n  ma_memval:\n    forall b ofs,\n    Mem.perm m1 b ofs Cur Readable ->\n    P b ofs ->\n    memval_lessdef (ZMap.get ofs (PMap.get b (Mem.mem_contents m1)))\n                   (ZMap.get ofs (PMap.get b (Mem.mem_contents m2)));\n  ma_nextblock:\n    Mem.nextblock m2 = Mem.nextblock m1\n}.\n\nLemma magree_monotone:\n  forall m1 m2 (P Q: locset),\n  magree m1 m2 P ->\n  (forall b ofs, Q b ofs -> P b ofs) ->\n  magree m1 m2 Q.\nProof.\n  intros. destruct H. constructor; auto.\nQed.\n\nLemma mextends_agree:\n  forall m1 m2 P, Mem.extends m1 m2 -> magree m1 m2 P.\nProof.\n  intros. destruct H. destruct mext_inj. constructor; intros.\n- replace ofs with (ofs + 0) by omega. eapply mi_perm; eauto. auto.\n- eauto.\n- exploit mi_memval; eauto. unfold inject_id; eauto.\n  rewrite Zplus_0_r. auto.\n- auto.\nQed.\n\nLemma magree_extends:\n  forall m1 m2 (P: locset),\n  (forall b ofs, P b ofs) ->\n  magree m1 m2 P -> Mem.extends m1 m2.\nProof.\n  intros. destruct H0. constructor; auto. constructor; unfold inject_id; intros.\n- inv H0. rewrite Zplus_0_r. eauto.\n- inv H0. apply Zdivide_0.\n- inv H0. rewrite Zplus_0_r. eapply ma_memval0; eauto.\nQed.\n\nLemma magree_loadbytes:\n  forall m1 m2 P b ofs n bytes,\n  magree m1 m2 P ->\n  Mem.loadbytes m1 b ofs n = Some bytes ->\n  (forall i, ofs <= i < ofs + n -> P b i) ->\n  exists bytes', Mem.loadbytes m2 b ofs n = Some bytes' /\\ list_forall2 memval_lessdef bytes bytes'.\nProof.\n  assert (GETN: forall c1 c2 n ofs,\n    (forall i, ofs <= i < ofs + Z.of_nat n -> memval_lessdef (ZMap.get i c1) (ZMap.get i c2)) ->\n    list_forall2 memval_lessdef (Mem.getN n ofs c1) (Mem.getN n ofs c2)).\n  {\n    induction n; intros; simpl.\n    constructor.\n    rewrite inj_S in H. constructor.\n    apply H. omega.\n    apply IHn. intros; apply H; omega.\n  }\nLocal Transparent Mem.loadbytes.\n  unfold Mem.loadbytes; intros. destruct H.\n  destruct (Mem.range_perm_dec m1 b ofs (ofs + n) Cur Readable); inv H0.\n  rewrite pred_dec_true. econstructor; split; eauto.\n  apply GETN. intros. rewrite nat_of_Z_max in H.\n  assert (ofs <= i < ofs + n) by xomega.\n  apply ma_memval0; auto.\n  red; intros; eauto.\nQed.\n\nLemma magree_load:\n  forall m1 m2 P chunk b ofs v,\n  magree m1 m2 P ->\n  Mem.load chunk m1 b ofs = Some v ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> P b i) ->\n  exists v', Mem.load chunk m2 b ofs = Some v' /\\ Val.lessdef v v'.\nProof.\n  intros. exploit Mem.load_valid_access; eauto. intros [A B].\n  exploit Mem.load_loadbytes; eauto. intros [bytes [C D]].\n  exploit magree_loadbytes; eauto. intros [bytes' [E F]].\n  exists (decode_val chunk bytes'); split.\n  apply Mem.loadbytes_load; auto.\n  apply val_inject_id. subst v. apply decode_val_inject; auto.\nQed.\n\nLemma magree_storebytes_parallel:\n  forall m1 m2 (P Q: locset) b ofs bytes1 m1' bytes2,\n  magree m1 m2 P ->\n  Mem.storebytes m1 b ofs bytes1 = Some m1' ->\n  (forall b' i, Q b' i ->\n                b' <> b \\/ i < ofs \\/ ofs + Z_of_nat (length bytes1) <= i ->\n                P b' i) ->\n  list_forall2 memval_lessdef bytes1 bytes2 ->\n  exists m2', Mem.storebytes m2 b ofs bytes2 = Some m2' /\\ magree m1' m2' Q.\nProof.\n  assert (SETN: forall (access: Z -> Prop) bytes1 bytes2,\n    list_forall2 memval_lessdef bytes1 bytes2 ->\n    forall p c1 c2,\n    (forall i, access i -> i < p \\/ p + Z.of_nat (length bytes1) <= i -> memval_lessdef (ZMap.get i c1) (ZMap.get i c2)) ->\n    forall q, access q ->\n    memval_lessdef (ZMap.get q (Mem.setN bytes1 p c1))\n                   (ZMap.get q (Mem.setN bytes2 p c2))).\n  {\n    induction 1; intros; simpl.\n  - apply H; auto. simpl. omega.\n  - simpl length in H1; rewrite inj_S in H1.\n    apply IHlist_forall2; auto.\n    intros. rewrite ! ZMap.gsspec. destruct (ZIndexed.eq i p). auto.\n    apply H1; auto. unfold ZIndexed.t in *; omega.\n  }\n  intros.\n  destruct (Mem.range_perm_storebytes m2 b ofs bytes2) as [m2' ST2].\n  { erewrite <- list_forall2_length by eauto. red; intros.\n    eapply ma_perm; eauto.\n    eapply Mem.storebytes_range_perm; eauto. }\n  exists m2'; split; auto.\n  constructor; intros.\n- eapply Mem.perm_storebytes_1; eauto. eapply ma_perm; eauto.\n  eapply Mem.perm_storebytes_2; eauto.\n- exploit ma_perm_inv; eauto using Mem.perm_storebytes_2.\n  intuition eauto using Mem.perm_storebytes_1, Mem.perm_storebytes_2.\n- rewrite (Mem.storebytes_mem_contents _ _ _ _ _ H0).\n  rewrite (Mem.storebytes_mem_contents _ _ _ _ _ ST2).\n  rewrite ! PMap.gsspec. destruct (peq b0 b).\n+ subst b0. apply SETN with (access := fun ofs => Mem.perm m1' b ofs Cur Readable /\\ Q b ofs); auto.\n  intros. destruct H5. eapply ma_memval; eauto.\n  eapply Mem.perm_storebytes_2; eauto.\n+ eapply ma_memval; eauto. eapply Mem.perm_storebytes_2; eauto.\n- rewrite (Mem.nextblock_storebytes _ _ _ _ _ H0).\n  rewrite (Mem.nextblock_storebytes _ _ _ _ _ ST2).\n  eapply ma_nextblock; eauto.\nQed.\n\nLemma magree_store_parallel:\n  forall m1 m2 (P Q: locset) chunk b ofs v1 m1' v2,\n  magree m1 m2 P ->\n  Mem.store chunk m1 b ofs v1 = Some m1' ->\n  vagree v1 v2 (store_argument chunk) ->\n  (forall b' i, Q b' i ->\n                b' <> b \\/ i < ofs \\/ ofs + size_chunk chunk <= i ->\n                P b' i) ->\n  exists m2', Mem.store chunk m2 b ofs v2 = Some m2' /\\ magree m1' m2' Q.\nProof.\n  intros.\n  exploit Mem.store_valid_access_3; eauto. intros [A B].\n  exploit Mem.store_storebytes; eauto. intros SB1.\n  exploit magree_storebytes_parallel. eauto. eauto.\n  instantiate (1 := Q). intros. rewrite encode_val_length in H4.\n  rewrite <- size_chunk_conv in H4. apply H2; auto.\n  eapply store_argument_sound; eauto.\n  intros [m2' [SB2 AG]].\n  exists m2'; split; auto.\n  apply Mem.storebytes_store; auto.\nQed.\n\nLemma magree_storebytes_left:\n  forall m1 m2 P b ofs bytes1 m1',\n  magree m1 m2 P ->\n  Mem.storebytes m1 b ofs bytes1 = Some m1' ->\n  (forall i, ofs <= i < ofs + Z_of_nat (length bytes1) -> ~(P b i)) ->\n  magree m1' m2 P.\nProof.\n  intros. constructor; intros.\n- eapply ma_perm; eauto. eapply Mem.perm_storebytes_2; eauto.\n- exploit ma_perm_inv; eauto.\n  intuition eauto using Mem.perm_storebytes_1, Mem.perm_storebytes_2.\n- rewrite (Mem.storebytes_mem_contents _ _ _ _ _ H0).\n  rewrite PMap.gsspec. destruct (peq b0 b).\n+ subst b0. rewrite Mem.setN_outside. eapply ma_memval; eauto. eapply Mem.perm_storebytes_2; eauto.\n  destruct (zlt ofs0 ofs); auto. destruct (zle (ofs + Z.of_nat (length bytes1)) ofs0); try omega.\n  elim (H1 ofs0). omega. auto.\n+ eapply ma_memval; eauto. eapply Mem.perm_storebytes_2; eauto.\n- rewrite (Mem.nextblock_storebytes _ _ _ _ _ H0).\n  eapply ma_nextblock; eauto.\nQed.\n\nLemma magree_store_left:\n  forall m1 m2 P chunk b ofs v1 m1',\n  magree m1 m2 P ->\n  Mem.store chunk m1 b ofs v1 = Some m1' ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> ~(P b i)) ->\n  magree m1' m2 P.\nProof.\n  intros. eapply magree_storebytes_left; eauto.\n  eapply Mem.store_storebytes; eauto.\n  intros. rewrite encode_val_length in H2.\n  rewrite <- size_chunk_conv in H2. apply H1; auto.\nQed.\n\nLemma magree_free:\n  forall m1 m2 (P Q: locset) b lo hi m1',\n  magree m1 m2 P ->\n  Mem.free m1 b lo hi = Some m1' ->\n  (forall b' i, Q b' i ->\n                b' <> b \\/ ~(lo <= i < hi) ->\n                P b' i) ->\n  exists m2', Mem.free m2 b lo hi = Some m2' /\\ magree m1' m2' Q.\nProof.\n  intros.\n  destruct (Mem.range_perm_free m2 b lo hi) as [m2' FREE].\n  red; intros. eapply ma_perm; eauto. eapply Mem.free_range_perm; eauto.\n  exists m2'; split; auto.\n  constructor; intros.\n- (* permissions *)\n  assert (Mem.perm m2 b0 ofs k p). { eapply ma_perm; eauto. eapply Mem.perm_free_3; eauto. }\n  exploit Mem.perm_free_inv; eauto. intros [[A B] | A]; auto.\n  subst b0. eelim Mem.perm_free_2. eexact H0. eauto. eauto.\n- (* inverse permissions *)\n  exploit ma_perm_inv; eauto using Mem.perm_free_3. intros [A|A].\n  eapply Mem.perm_free_inv in A; eauto. destruct A as [[A B] | A]; auto.\n  subst b0; right; eapply Mem.perm_free_2; eauto.\n  right; intuition eauto using Mem.perm_free_3.\n- (* contents *)\n  rewrite (Mem.free_result _ _ _ _ _ H0).\n  rewrite (Mem.free_result _ _ _ _ _ FREE).\n  simpl. eapply ma_memval; eauto. eapply Mem.perm_free_3; eauto.\n  apply H1; auto. destruct (eq_block b0 b); auto.\n  subst b0. right. red; intros. eelim Mem.perm_free_2. eexact H0. eauto. eauto.\n- (* nextblock *)\n  rewrite (Mem.free_result _ _ _ _ _ H0).\n  rewrite (Mem.free_result _ _ _ _ _ FREE).\n  simpl. eapply ma_nextblock; eauto.\nQed.\n\nLemma magree_valid_access:\n  forall m1 m2 (P: locset) chunk b ofs p,\n  magree m1 m2 P ->\n  Mem.valid_access m1 chunk b ofs p ->\n  Mem.valid_access m2 chunk b ofs p.\nProof.\n  intros. destruct H0; split; auto.\n  red; intros. eapply ma_perm; eauto.\nQed.\n\n(** * Properties of the need environment *)\n\nLemma add_need_all_eagree:\n  forall e e' r ne,\n  eagree e e' (add_need_all r ne) -> eagree e e' ne.\nProof.\n  intros; red; intros. generalize (H r0). unfold add_need_all.\n  rewrite NE.gsspec. destruct (peq r0 r); auto with na.\nQed.\n\nLemma add_need_all_lessdef:\n  forall e e' r ne,\n  eagree e e' (add_need_all r ne) -> Val.lessdef e#r e'#r.\nProof.\n  intros. generalize (H r); unfold add_need_all.\n  rewrite NE.gsspec, peq_true. auto with na.\nQed.\n\nLemma add_need_eagree:\n  forall e e' r nv ne,\n  eagree e e' (add_need r nv ne) -> eagree e e' ne.\nProof.\n  intros; red; intros. generalize (H r0); unfold add_need.\n  rewrite NE.gsspec. destruct (peq r0 r); auto.\n  subst r0. intros. eapply nge_agree; eauto. apply nge_lub_r.\nQed.\n\nLemma add_need_vagree:\n  forall e e' r nv ne,\n  eagree e e' (add_need r nv ne) -> vagree e#r e'#r nv.\nProof.\n  intros. generalize (H r); unfold add_need.\n  rewrite NE.gsspec, peq_true. intros. eapply nge_agree; eauto. apply nge_lub_l.\nQed.\n\nLemma add_needs_all_eagree:\n  forall rl e e' ne,\n  eagree e e' (add_needs_all rl ne) -> eagree e e' ne.\nProof.\n  induction rl; simpl; intros.\n  auto.\n  apply IHrl. eapply add_need_all_eagree; eauto.\nQed.\n\nLemma add_needs_all_lessdef:\n  forall rl e e' ne,\n  eagree e e' (add_needs_all rl ne) -> Val.lessdef_list e##rl e'##rl.\nProof.\n  induction rl; simpl; intros.\n  constructor.\n  constructor. eapply add_need_all_lessdef; eauto.\n  eapply IHrl. eapply add_need_all_eagree; eauto.\nQed.\n\nLemma add_needs_eagree:\n  forall rl nvl e e' ne,\n  eagree e e' (add_needs rl nvl ne) -> eagree e e' ne.\nProof.\n  induction rl; simpl; intros.\n  auto.\n  destruct nvl. apply add_needs_all_eagree with (a :: rl); auto.\n  eapply IHrl. eapply add_need_eagree; eauto.\nQed.\n\nLemma add_needs_vagree:\n  forall rl nvl e e' ne,\n  eagree e e' (add_needs rl nvl ne) -> vagree_list e##rl e'##rl nvl.\nProof.\n  induction rl; simpl; intros.\n  constructor.\n  destruct nvl.\n  apply vagree_lessdef_list. eapply add_needs_all_lessdef with (rl := a :: rl); eauto.\n  constructor. eapply add_need_vagree; eauto.\n  eapply IHrl. eapply add_need_eagree; eauto.\nQed.\n\nLemma add_ros_need_eagree:\n  forall e e' ros ne, eagree e e' (add_ros_need_all ros ne) -> eagree e e' ne.\nProof.\n  intros. destruct ros; simpl in *. eapply add_need_all_eagree; eauto. auto.\nQed.\n\nHint Resolve add_need_all_eagree add_need_all_lessdef\n             add_need_eagree add_need_vagree\n             add_needs_all_eagree add_needs_all_lessdef\n             add_needs_eagree add_needs_vagree\n             add_ros_need_eagree: na.\n\nLemma eagree_init_regs:\n  forall rl vl1 vl2 ne,\n  Val.lessdef_list vl1 vl2 ->\n  eagree (init_regs vl1 rl) (init_regs vl2 rl) ne.\nProof.\n  induction rl; intros until ne; intros LD; simpl.\n- red; auto with na.\n- inv LD.\n  + red; auto with na.\n  + apply eagree_update; auto with na.\nQed.\n\n(** * Basic properties of the translation *)\n\nSection PRESERVATION.\n\nVariable prog: program.\nVariable tprog: program.\nHypothesis TRANSF: match_prog prog tprog.\nLet ge := Genv.globalenv prog.\nLet tge := Genv.globalenv tprog.\n\nLemma symbols_preserved:\n  forall (s: ident), Genv.find_symbol tge s = Genv.find_symbol ge s.\nProof (Genv.find_symbol_match TRANSF).\n\nLemma senv_preserved:\n  Senv.equiv ge tge.\nProof (Genv.senv_match TRANSF).\n\nLemma functions_translated:\n  forall (v: val) (f: RTL.fundef),\n  Genv.find_funct ge v = Some f ->\n  exists cu tf,\n  Genv.find_funct tge v = Some tf /\\ transf_fundef (romem_for cu) f = OK tf /\\ linkorder cu prog.\nProof (Genv.find_funct_match TRANSF).\n\nLemma function_ptr_translated:\n  forall (b: block) (f: RTL.fundef),\n  Genv.find_funct_ptr ge b = Some f ->\n  exists cu tf,\n  Genv.find_funct_ptr tge b = Some tf /\\ transf_fundef (romem_for cu) f = OK tf /\\ linkorder cu prog.\nProof (Genv.find_funct_ptr_match TRANSF).\n\nLemma sig_function_translated:\n  forall rm f tf,\n  transf_fundef rm f = OK tf ->\n  funsig tf = funsig f.\nProof.\n  intros; destruct f; monadInv H.\n  unfold transf_function in EQ.\n  destruct (analyze (ValueAnalysis.analyze rm f) f); inv EQ; auto.\n  auto.\nQed.\n\nLemma stacksize_translated:\n  forall rm f tf,\n  transf_function rm f = OK tf -> tf.(fn_stacksize) = f.(fn_stacksize).\nProof.\n  unfold transf_function; intros. destruct (analyze (ValueAnalysis.analyze rm f) f); inv H; auto.\nQed.\n\nDefinition vanalyze (cu: program) (f: function) :=\n  ValueAnalysis.analyze (romem_for cu) f.\n\nLemma transf_function_at:\n  forall cu f tf an pc instr,\n  transf_function (romem_for cu) f = OK tf ->\n  analyze (vanalyze cu f) f = Some an ->\n  f.(fn_code)!pc = Some instr ->\n  tf.(fn_code)!pc = Some(transf_instr (vanalyze cu f) an pc instr).\nProof.\n  intros. unfold transf_function in H. unfold vanalyze in H0. rewrite H0 in H. inv H; simpl.\n  rewrite PTree.gmap. rewrite H1; auto.\nQed.\n\nLemma is_dead_sound_1:\n  forall nv, is_dead nv = true -> nv = Nothing.\nProof.\n  destruct nv; simpl; congruence.\nQed.\n\nLemma is_dead_sound_2:\n  forall nv, is_dead nv = false -> nv <> Nothing.\nProof.\n  intros; red; intros. subst nv; discriminate.\nQed.\n\nHint Resolve is_dead_sound_1 is_dead_sound_2: na.\n\nLemma is_int_zero_sound:\n  forall nv, is_int_zero nv = true -> nv = I Int.zero.\nProof.\n  unfold is_int_zero; destruct nv; try discriminate.\n  predSpec Int.eq Int.eq_spec m Int.zero; congruence.\nQed.\n\nLemma find_function_translated:\n  forall ros rs fd trs ne,\n  find_function ge ros rs = Some fd ->\n  eagree rs trs (add_ros_need_all ros ne) ->\n  exists cu tfd,\n     find_function tge ros trs = Some tfd\n  /\\ transf_fundef (romem_for cu) fd = OK tfd\n  /\\ linkorder cu prog.\nProof.\n  intros. destruct ros as [r|id]; simpl in *.\n- assert (LD: Val.lessdef rs#r trs#r) by eauto with na. inv LD.\n  apply functions_translated; auto.\n  rewrite <- H2 in H; discriminate.\n- rewrite symbols_preserved. destruct (Genv.find_symbol ge id); try discriminate.\n  apply function_ptr_translated; auto.\nQed.\n\n(** * Semantic invariant *)\n\nInductive match_stackframes: stackframe -> stackframe -> Prop :=\n  | match_stackframes_intro:\n      forall res f sp pc e tf te cu an\n        (LINK: linkorder cu prog)\n        (FUN: transf_function (romem_for cu) f = OK tf)\n        (ANL: analyze (vanalyze cu f) f = Some an)\n        (RES: forall v tv,\n              Val.lessdef v tv ->\n              eagree (e#res <- v) (te#res<- tv)\n                     (fst (transfer f (vanalyze cu f) pc an!!pc))),\n      match_stackframes (Stackframe res f (Vptr sp Ptrofs.zero) pc e)\n                        (Stackframe res tf (Vptr sp Ptrofs.zero) pc te).\n\nInductive match_states: state -> state -> Prop :=\n  | match_regular_states:\n      forall s f sp pc e m ts tf te tm cu an\n        (STACKS: list_forall2 match_stackframes s ts)\n        (LINK: linkorder cu prog)\n        (FUN: transf_function (romem_for cu) f = OK tf)\n        (ANL: analyze (vanalyze cu f) f = Some an)\n        (ENV: eagree e te (fst (transfer f (vanalyze cu f) pc an!!pc)))\n        (MEM: magree m tm (nlive ge sp (snd (transfer f (vanalyze cu f) pc an!!pc)))),\n      match_states (State s f (Vptr sp Ptrofs.zero) pc e m)\n                   (State ts tf (Vptr sp Ptrofs.zero) pc te tm)\n  | match_call_states:\n      forall s f args m ts tf targs tm cu\n        (STACKS: list_forall2 match_stackframes s ts)\n        (LINK: linkorder cu prog)\n        (FUN: transf_fundef (romem_for cu) f = OK tf)\n        (ARGS: Val.lessdef_list args targs)\n        (MEM: Mem.extends m tm),\n      match_states (Callstate s f args m)\n                   (Callstate ts tf targs tm)\n  | match_return_states:\n      forall s v m ts tv tm\n        (STACKS: list_forall2 match_stackframes s ts)\n        (RES: Val.lessdef v tv)\n        (MEM: Mem.extends m tm),\n      match_states (Returnstate s v m)\n                   (Returnstate ts tv tm).\n\n(** [match_states] and CFG successors *)\n\nLemma analyze_successors:\n  forall cu f an pc instr pc',\n  analyze (vanalyze cu f) f = Some an ->\n  f.(fn_code)!pc = Some instr ->\n  In pc' (successors_instr instr) ->\n  NA.ge an!!pc (transfer f (vanalyze cu f) pc' an!!pc').\nProof.\n  intros. eapply DS.fixpoint_solution; eauto.\n  intros. unfold transfer; rewrite H2. destruct a. apply DS.L.eq_refl.\nQed.\n\nLemma match_succ_states:\n  forall s f sp pc e m ts tf te tm an pc' cu instr ne nm\n    (LINK: linkorder cu prog)\n    (STACKS: list_forall2 match_stackframes s ts)\n    (FUN: transf_function (romem_for cu) f = OK tf)\n    (ANL: analyze (vanalyze cu f) f = Some an)\n    (INSTR: f.(fn_code)!pc = Some instr)\n    (SUCC: In pc' (successors_instr instr))\n    (ANPC: an!!pc = (ne, nm))\n    (ENV: eagree e te ne)\n    (MEM: magree m tm (nlive ge sp nm)),\n  match_states (State s f (Vptr sp Ptrofs.zero) pc' e m)\n               (State ts tf (Vptr sp Ptrofs.zero) pc' te tm).\nProof.\n  intros. exploit analyze_successors; eauto. rewrite ANPC; simpl. intros [A B].\n  econstructor; eauto.\n  eapply eagree_ge; eauto.\n  eapply magree_monotone; eauto.\nQed.\n\n(** Builtin arguments and results *)\n\nLemma eagree_set_res:\n  forall e1 e2 v1 v2 res ne,\n  Val.lessdef v1 v2 ->\n  eagree e1 e2 (kill_builtin_res res ne) ->\n  eagree (regmap_setres res v1 e1) (regmap_setres res v2 e2) ne.\nProof.\n  intros. destruct res; simpl in *; auto.\n  apply eagree_update; eauto. apply vagree_lessdef; auto.\nQed.\n\nLemma transfer_builtin_arg_sound:\n  forall bc e e' sp m m' a v,\n  eval_builtin_arg ge (fun r => e#r) (Vptr sp Ptrofs.zero) m a v ->\n  forall nv ne1 nm1 ne2 nm2,\n  transfer_builtin_arg nv (ne1, nm1) a = (ne2, nm2) ->\n  eagree e e' ne2 ->\n  magree m m' (nlive ge sp nm2) ->\n  genv_match bc ge ->\n  bc sp = BCstack ->\n  exists v',\n     eval_builtin_arg ge (fun r => e'#r) (Vptr sp Ptrofs.zero) m' a  v'\n  /\\ vagree v v' nv\n  /\\ eagree e e' ne1\n  /\\ magree m m' (nlive ge sp nm1).\nProof.\n  induction 1; simpl; intros until nm2; intros TR EA MA GM SPM; inv TR.\n- exists e'#x; intuition auto. constructor. eauto 2 with na. eauto 2 with na.\n- exists (Vint n); intuition auto. constructor. apply vagree_same.\n- exists (Vlong n); intuition auto. constructor. apply vagree_same.\n- exists (Vfloat n); intuition auto. constructor. apply vagree_same.\n- exists (Vsingle n); intuition auto. constructor. apply vagree_same.\n- simpl in H. exploit magree_load; eauto.\n  intros. eapply nlive_add; eauto with va. rewrite Ptrofs.add_zero_l in H0; auto.\n  intros (v' & A & B).\n  exists v'; intuition auto. constructor; auto. apply vagree_lessdef; auto.\n  eapply magree_monotone; eauto. intros; eapply incl_nmem_add; eauto.\n- exists (Vptr sp (Ptrofs.add Ptrofs.zero ofs)); intuition auto with na. constructor.\n- unfold Senv.symbol_address in H; simpl in H.\n  destruct (Genv.find_symbol ge id) as [b|] eqn:FS; simpl in H; try discriminate.\n  exploit magree_load; eauto.\n  intros. eapply nlive_add; eauto. constructor. apply GM; auto.\n  intros (v' & A & B).\n  exists v'; intuition auto.\n  constructor. simpl. unfold Senv.symbol_address; simpl; rewrite FS; auto.\n  apply vagree_lessdef; auto.\n  eapply magree_monotone; eauto. intros; eapply incl_nmem_add; eauto.\n- exists (Senv.symbol_address ge id ofs); intuition auto with na. constructor.\n- destruct (transfer_builtin_arg All (ne1, nm1) hi) as [ne' nm'] eqn:TR.\n  exploit IHeval_builtin_arg2; eauto. intros (vlo' & A & B & C & D).\n  exploit IHeval_builtin_arg1; eauto. intros (vhi' & P & Q & R & S).\n  exists (Val.longofwords vhi' vlo'); intuition auto.\n  constructor; auto.\n  apply vagree_lessdef.\n  apply Val.longofwords_lessdef; apply lessdef_vagree; auto.\nQed.\n\nLemma transfer_builtin_args_sound:\n  forall e sp m e' m' bc al vl,\n  eval_builtin_args ge (fun r => e#r) (Vptr sp Ptrofs.zero) m al vl ->\n  forall ne1 nm1 ne2 nm2,\n  transfer_builtin_args (ne1, nm1) al = (ne2, nm2) ->\n  eagree e e' ne2 ->\n  magree m m' (nlive ge sp nm2) ->\n  genv_match bc ge ->\n  bc sp = BCstack ->\n  exists vl',\n     eval_builtin_args ge (fun r => e'#r) (Vptr sp Ptrofs.zero) m' al vl'\n  /\\ Val.lessdef_list vl vl'\n  /\\ eagree e e' ne1\n  /\\ magree m m' (nlive ge sp nm1).\nProof.\nLocal Opaque transfer_builtin_arg.\n  induction 1; simpl; intros.\n- inv H. exists (@nil val); intuition auto. constructor.\n- destruct (transfer_builtin_arg All (ne1, nm1) a1) as [ne' nm'] eqn:TR.\n  exploit IHlist_forall2; eauto. intros (vs' & A1 & B1 & C1 & D1).\n  exploit transfer_builtin_arg_sound; eauto. intros (v1' & A2 & B2 & C2 & D2).\n  exists (v1' :: vs'); intuition auto. constructor; auto.\nQed.\n\nLemma can_eval_builtin_arg:\n  forall sp e m e' m' P,\n  magree m m' P ->\n  forall a v,\n  eval_builtin_arg ge (fun r => e#r) (Vptr sp Ptrofs.zero) m a v ->\n  exists v', eval_builtin_arg tge (fun r => e'#r) (Vptr sp Ptrofs.zero) m' a v'.\nProof.\n  intros until P; intros MA.\n  assert (LD: forall chunk addr v,\n              Mem.loadv chunk m addr = Some v ->\n              exists v', Mem.loadv chunk m' addr = Some v').\n  {\n    intros. destruct addr; simpl in H; try discriminate.\n    eapply Mem.valid_access_load. eapply magree_valid_access; eauto.\n    eapply Mem.load_valid_access; eauto. }\n  induction 1; try (econstructor; now constructor).\n- exploit LD; eauto. intros (v' & A). exists v'; constructor; auto.\n- exploit LD; eauto. intros (v' & A). exists v'; constructor.\n  unfold Senv.symbol_address, Senv.find_symbol. rewrite symbols_preserved. assumption.\n- destruct IHeval_builtin_arg1 as (v1' & A1).\n  destruct IHeval_builtin_arg2 as (v2' & A2).\n  exists (Val.longofwords v1' v2'); constructor; auto.\nQed.\n\nLemma can_eval_builtin_args:\n  forall sp e m e' m' P,\n  magree m m' P ->\n  forall al vl,\n  eval_builtin_args ge (fun r => e#r) (Vptr sp Ptrofs.zero) m al vl ->\n  exists vl', eval_builtin_args tge (fun r => e'#r) (Vptr sp Ptrofs.zero) m' al vl'.\nProof.\n  induction 2.\n- exists (@nil val); constructor.\n- exploit can_eval_builtin_arg; eauto. intros (v' & A).\n  destruct IHlist_forall2 as (vl' & B).\n  exists (v' :: vl'); constructor; eauto.\nQed.\n\n(** Properties of volatile memory accesses *)\n\nLemma transf_volatile_store:\n  forall v1 v2 v1' v2' m tm chunk sp nm t v m',\n  volatile_store_sem chunk ge (v1::v2::nil) m t v m' ->\n  Val.lessdef v1 v1' ->\n  vagree v2 v2' (store_argument chunk) ->\n  magree m tm (nlive ge sp nm) ->\n  v = Vundef /\\\n  exists tm', volatile_store_sem chunk ge (v1'::v2'::nil) tm t Vundef tm'\n           /\\ magree m' tm' (nlive ge sp nm).\nProof.\n  intros. inv H. split; auto.\n  inv H0. inv H9.\n- (* volatile *)\n  exists tm; split; auto. econstructor. econstructor; eauto.\n  eapply eventval_match_lessdef; eauto. apply store_argument_load_result; auto.\n- (* not volatile *)\n  exploit magree_store_parallel. eauto. eauto. eauto.\n  instantiate (1 := nlive ge sp nm). auto.\n  intros (tm' & P & Q).\n  exists tm'; split. econstructor. econstructor; eauto. auto.\nQed.\n\nLemma eagree_set_undef:\n  forall e1 e2 ne r, eagree e1 e2 ne -> eagree (e1#r <- Vundef) e2 ne.\nProof.\n  intros; red; intros. rewrite PMap.gsspec. destruct (peq r0 r); auto with na.\nQed.\n\n(** * The simulation diagram *)\n\nTheorem step_simulation:\n  forall S1 t S2, step ge S1 t S2 ->\n  forall S1', match_states S1 S1' -> sound_state prog S1 ->\n  exists S2', step tge S1' t S2' /\\ match_states S2 S2'.\nProof.\n\nLtac TransfInstr :=\n  match goal with\n  | [INSTR: (fn_code _)!_ = Some _,\n     FUN: transf_function _ _ = OK _,\n     ANL: analyze _ _ = Some _ |- _ ] =>\n       generalize (transf_function_at _ _ _ _ _ _ FUN ANL INSTR);\n       let TI := fresh \"TI\" in\n       intro TI; unfold transf_instr in TI\n  end.\n\nLtac UseTransfer :=\n  match goal with\n  | [INSTR: (fn_code _)!?pc = Some _,\n     ANL: analyze _ _ = Some ?an |- _ ] =>\n       destruct (an!!pc) as [ne nm] eqn:ANPC;\n       unfold transfer in *;\n       rewrite INSTR in *;\n       simpl in *\n  end.\n\n  induction 1; intros S1' MS SS; inv MS.\n\n- (* nop *)\n  TransfInstr; UseTransfer.\n  econstructor; split.\n  eapply exec_Inop; eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n\n- (* op *)\n  TransfInstr; UseTransfer.\n  destruct (is_dead (nreg ne res)) eqn:DEAD;\n  [idtac|destruct (is_int_zero (nreg ne res)) eqn:INTZERO;\n  [idtac|destruct (operation_is_redundant op (nreg ne res)) eqn:REDUNDANT]].\n+ (* dead instruction, turned into a nop *)\n  econstructor; split.\n  eapply exec_Inop; eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_update_dead; auto with na.\n+ (* instruction with needs = [I Int.zero], turned into a load immediate of zero. *)\n  econstructor; split.\n  eapply exec_Iop with (v := Vint Int.zero); eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_update; auto.\n  rewrite is_int_zero_sound by auto.\n  destruct v; simpl; auto. apply iagree_zero.\n+ (* redundant operation *)\n  destruct args.\n  * (* kept as is because no arguments -- should never happen *)\n  simpl in *.\n  exploit needs_of_operation_sound. eapply ma_perm; eauto.\n  eauto. instantiate (1 := nreg ne res). eauto with na. eauto with na. intros [tv [A B]].\n  econstructor; split.\n  eapply exec_Iop with (v := tv); eauto.\n  rewrite <- A. apply eval_operation_preserved. exact symbols_preserved.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_update; auto.\n  * (* turned into a move *)\n  unfold fst in ENV. unfold snd in MEM. simpl in H0.\n  assert (VA: vagree v te#r (nreg ne res)).\n  { eapply operation_is_redundant_sound with (arg1' := te#r) (args' := te##args).\n    eauto. eauto. exploit add_needs_vagree; eauto. }\n  econstructor; split.\n  eapply exec_Iop; eauto. simpl; reflexivity.\n  eapply match_succ_states; eauto. simpl; auto.\n  eapply eagree_update; eauto 2 with na.\n+ (* preserved operation *)\n  simpl in *.\n  exploit needs_of_operation_sound. eapply ma_perm; eauto. eauto. eauto 2 with na. eauto with na.\n  intros [tv [A B]].\n  econstructor; split.\n  eapply exec_Iop with (v := tv); eauto.\n  rewrite <- A. apply eval_operation_preserved. exact symbols_preserved.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_update; eauto 2 with na.\n\n- (* load *)\n  TransfInstr; UseTransfer.\n  destruct (is_dead (nreg ne dst)) eqn:DEAD;\n  [idtac|destruct (is_int_zero (nreg ne dst)) eqn:INTZERO];\n  simpl in *.\n+ (* dead instruction, turned into a nop *)\n  econstructor; split.\n  eapply exec_Inop; eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_update_dead; auto with na.\n+ (* instruction with needs = [I Int.zero], turned into a load immediate of zero. *)\n  econstructor; split.\n  eapply exec_Iop with (v := Vint Int.zero); eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_update; auto.\n  rewrite is_int_zero_sound by auto.\n  destruct v; simpl; auto. apply iagree_zero.\n+ (* preserved *)\n  exploit eval_addressing_lessdef. eapply add_needs_all_lessdef; eauto. eauto.\n  intros (ta & U & V). inv V; try discriminate.\n  destruct ta; simpl in H1; try discriminate.\n  exploit magree_load; eauto.\n  exploit aaddressing_sound; eauto. intros (bc & A & B & C).\n  intros. apply nlive_add with bc i; assumption.\n  intros (tv & P & Q).\n  econstructor; split.\n  eapply exec_Iload with (a := Vptr b i). eauto.\n  rewrite <- U. apply eval_addressing_preserved. exact symbols_preserved.\n  eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_update; eauto 2 with na.\n  eapply magree_monotone; eauto. intros. apply incl_nmem_add; auto.\n\n- (* store *)\n  TransfInstr; UseTransfer.\n  destruct (nmem_contains nm (aaddressing (vanalyze cu f) # pc addr args)\n             (size_chunk chunk)) eqn:CONTAINS.\n+ (* preserved *)\n  simpl in *.\n  exploit eval_addressing_lessdef. eapply add_needs_all_lessdef; eauto. eauto.\n  intros (ta & U & V). inv V; try discriminate.\n  destruct ta; simpl in H1; try discriminate.\n  exploit magree_store_parallel. eauto. eauto. instantiate (1 := te#src). eauto with na.\n  instantiate (1 := nlive ge sp0 nm).\n  exploit aaddressing_sound; eauto. intros (bc & A & B & C).\n  intros. apply nlive_remove with bc b i; assumption.\n  intros (tm' & P & Q).\n  econstructor; split.\n  eapply exec_Istore with (a := Vptr b i). eauto.\n  rewrite <- U. apply eval_addressing_preserved. exact symbols_preserved.\n  eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n  eauto 3 with na.\n+ (* dead instruction, turned into a nop *)\n  destruct a; simpl in H1; try discriminate.\n  econstructor; split.\n  eapply exec_Inop; eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n  eapply magree_store_left; eauto.\n  exploit aaddressing_sound; eauto. intros (bc & A & B & C).\n  intros. eapply nlive_contains; eauto.\n\n- (* call *)\n  TransfInstr; UseTransfer.\n  exploit find_function_translated; eauto 2 with na. intros (cu' & tfd & A & B & C).\n  econstructor; split.\n  eapply exec_Icall; eauto. eapply sig_function_translated; eauto.\n  eapply match_call_states with (cu := cu'); eauto.\n  constructor; auto. eapply match_stackframes_intro with (cu := cu); eauto.\n  intros.\n  edestruct analyze_successors; eauto. simpl; eauto.\n  eapply eagree_ge; eauto. rewrite ANPC. simpl.\n  apply eagree_update; eauto with na.\n  eauto 2 with na.\n  eapply magree_extends; eauto. apply nlive_all.\n\n- (* tailcall *)\n  TransfInstr; UseTransfer.\n  exploit find_function_translated; eauto 2 with na. intros (cu' & tfd & A & B & L).\n  exploit magree_free. eauto. eauto. instantiate (1 := nlive ge stk nmem_all).\n  intros; eapply nlive_dead_stack; eauto.\n  intros (tm' & C & D).\n  econstructor; split.\n  eapply exec_Itailcall; eauto. eapply sig_function_translated; eauto.\n  erewrite stacksize_translated by eauto. eexact C.\n  eapply match_call_states with (cu := cu'); eauto 2 with na.\n  eapply magree_extends; eauto. apply nlive_all.\n\n- (* builtin *)\n  TransfInstr; UseTransfer. revert ENV MEM TI.\n  functional induction (transfer_builtin (vanalyze cu f)#pc ef args res ne nm);\n  simpl in *; intros.\n+ (* volatile load *)\n  inv H0. inv H6. rename b1 into v1.\n  destruct (transfer_builtin_arg All\n              (kill_builtin_res res ne,\n              nmem_add nm (aaddr_arg (vanalyze cu f) # pc a1)\n                (size_chunk chunk)) a1) as (ne1, nm1) eqn: TR.\n  InvSoundState. exploit transfer_builtin_arg_sound; eauto.\n  intros (tv1 & A & B & C & D).\n  inv H1. simpl in B. inv B.\n  assert (X: exists tvres, volatile_load ge chunk tm b ofs t tvres /\\ Val.lessdef vres tvres).\n  {\n    inv H2.\n  * exists (Val.load_result chunk v); split; auto. constructor; auto.\n  * exploit magree_load; eauto.\n    exploit aaddr_arg_sound_1; eauto. rewrite <- AN. intros.\n    intros. eapply nlive_add; eassumption.\n    intros (tv & P & Q).\n    exists tv; split; auto. constructor; auto.\n  }\n  destruct X as (tvres & P & Q).\n  econstructor; split.\n  eapply exec_Ibuiltin; eauto.\n  apply eval_builtin_args_preserved with (ge1 := ge). exact symbols_preserved.\n  constructor. eauto. constructor.\n  eapply external_call_symbols_preserved. apply senv_preserved.\n  constructor. simpl. eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_set_res; auto.\n  eapply magree_monotone; eauto. intros. apply incl_nmem_add; auto.\n+ (* volatile store *)\n  inv H0. inv H6. inv H7. rename b1 into v1. rename b0 into v2.\n  destruct (transfer_builtin_arg (store_argument chunk)\n              (kill_builtin_res res ne, nm) a2) as (ne2, nm2) eqn: TR2.\n  destruct (transfer_builtin_arg All (ne2, nm2) a1) as (ne1, nm1) eqn: TR1.\n  InvSoundState.\n  exploit transfer_builtin_arg_sound. eexact H4. eauto. eauto. eauto. eauto. eauto.\n  intros (tv1 & A1 & B1 & C1 & D1).\n  exploit transfer_builtin_arg_sound. eexact H3. eauto. eauto. eauto. eauto. eauto.\n  intros (tv2 & A2 & B2 & C2 & D2).\n  exploit transf_volatile_store; eauto.\n  intros (EQ & tm' & P & Q). subst vres.\n  econstructor; split.\n  eapply exec_Ibuiltin; eauto.\n  apply eval_builtin_args_preserved with (ge1 := ge). exact symbols_preserved.\n  constructor. eauto. constructor. eauto. constructor.\n  eapply external_call_symbols_preserved. apply senv_preserved.\n  simpl; eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_set_res; auto.\n+ (* memcpy *)\n  rewrite e1 in TI.\n  inv H0. inv H6. inv H7. rename b1 into v1. rename b0 into v2.\n  set (adst := aaddr_arg (vanalyze cu f) # pc dst) in *.\n  set (asrc := aaddr_arg (vanalyze cu f) # pc src) in *.\n  destruct (transfer_builtin_arg All\n              (kill_builtin_res res ne,\n               nmem_add (nmem_remove nm adst sz) asrc sz) dst)\n           as (ne2, nm2) eqn: TR2.\n  destruct (transfer_builtin_arg All (ne2, nm2) src) as (ne1, nm1) eqn: TR1.\n  InvSoundState.\n  exploit transfer_builtin_arg_sound. eexact H3. eauto. eauto. eauto. eauto. eauto.\n  intros (tv1 & A1 & B1 & C1 & D1).\n  exploit transfer_builtin_arg_sound. eexact H4. eauto. eauto. eauto. eauto. eauto.\n  intros (tv2 & A2 & B2 & C2 & D2).\n  inv H1.\n  exploit magree_loadbytes. eauto. eauto.\n  intros. eapply nlive_add; eauto.\n  unfold asrc, vanalyze; rewrite AN; eapply aaddr_arg_sound_1; eauto.\n  intros (tbytes & P & Q).\n  exploit magree_storebytes_parallel.\n  eapply magree_monotone. eexact D2.\n  instantiate (1 := nlive ge sp0 (nmem_remove nm adst sz)).\n  intros. apply incl_nmem_add; auto.\n  eauto.\n  instantiate (1 := nlive ge sp0 nm).\n  intros. eapply nlive_remove; eauto.\n  unfold adst, vanalyze; rewrite AN; eapply aaddr_arg_sound_1; eauto.\n  erewrite Mem.loadbytes_length in H1 by eauto.\n  rewrite nat_of_Z_eq in H1 by omega. auto.\n  eauto.\n  intros (tm' & A & B).\n  econstructor; split.\n  eapply exec_Ibuiltin; eauto.\n  apply eval_builtin_args_preserved with (ge1 := ge). exact symbols_preserved.\n  constructor. eauto. constructor. eauto. constructor.\n  eapply external_call_symbols_preserved. apply senv_preserved.\n  simpl in B1; inv B1. simpl in B2; inv B2. econstructor; eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_set_res; auto.\n+ (* memcpy eliminated *)\n  rewrite e1 in TI.\n  inv H0. inv H6. inv H7. rename b1 into v1. rename b0 into v2.\n  set (adst := aaddr_arg (vanalyze cu f) # pc dst) in *.\n  set (asrc := aaddr_arg (vanalyze cu f) # pc src) in *.\n  inv H1.\n  econstructor; split.\n  eapply exec_Inop; eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n  destruct res; auto. apply eagree_set_undef; auto.\n  eapply magree_storebytes_left; eauto.\n  clear H3.\n  exploit aaddr_arg_sound; eauto.\n  intros (bc & A & B & C).\n  intros. eapply nlive_contains; eauto.\n  erewrite Mem.loadbytes_length in H0 by eauto.\n  rewrite nat_of_Z_eq in H0 by omega. auto.\n+ (* annot *)\n  destruct (transfer_builtin_args (kill_builtin_res res ne, nm) _x1) as (ne1, nm1) eqn:TR.\n  InvSoundState.\n  exploit transfer_builtin_args_sound; eauto. intros (tvl & A & B & C & D).\n  inv H1.\n  econstructor; split.\n  eapply exec_Ibuiltin; eauto.\n  apply eval_builtin_args_preserved with (ge1 := ge); eauto. exact symbols_preserved.\n  eapply external_call_symbols_preserved. apply senv_preserved.\n  constructor. eapply eventval_list_match_lessdef; eauto 2 with na.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_set_res; auto.\n+ (* annot val *)\n  destruct (transfer_builtin_args (kill_builtin_res res ne, nm) _x1) as (ne1, nm1) eqn:TR.\n  InvSoundState.\n  exploit transfer_builtin_args_sound; eauto. intros (tvl & A & B & C & D).\n  inv H1. inv B. inv H6.\n  econstructor; split.\n  eapply exec_Ibuiltin; eauto.\n  apply eval_builtin_args_preserved with (ge1 := ge); eauto. exact symbols_preserved.\n  eapply external_call_symbols_preserved. apply senv_preserved.\n  constructor.\n  eapply eventval_match_lessdef; eauto 2 with na.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_set_res; auto.\n+ (* debug *)\n  inv H1.\n  exploit can_eval_builtin_args; eauto. intros (vargs' & A).\n  econstructor; split.\n  eapply exec_Ibuiltin; eauto. constructor.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_set_res; auto.\n+ (* all other builtins *)\n  assert ((fn_code tf)!pc = Some(Ibuiltin _x _x0 res pc')).\n  {\n    destruct _x; auto. destruct _x0; auto. destruct _x0; auto. destruct _x0; auto. contradiction.\n  }\n  clear y TI.\n  destruct (transfer_builtin_args (kill_builtin_res res ne, nmem_all) _x0) as (ne1, nm1) eqn:TR.\n  InvSoundState.\n  exploit transfer_builtin_args_sound; eauto. intros (tvl & A & B & C & D).\n  exploit external_call_mem_extends; eauto 2 with na.\n  eapply magree_extends; eauto. intros. apply nlive_all.\n  intros (v' & tm' & P & Q & R & S).\n  econstructor; split.\n  eapply exec_Ibuiltin; eauto.\n  apply eval_builtin_args_preserved with (ge1 := ge); eauto. exact symbols_preserved.\n  eapply external_call_symbols_preserved. apply senv_preserved. eauto.\n  eapply match_succ_states; eauto. simpl; auto.\n  apply eagree_set_res; auto.\n  eapply mextends_agree; eauto.\n\n- (* conditional *)\n  TransfInstr; UseTransfer.\n  econstructor; split.\n  eapply exec_Icond; eauto.\n  eapply needs_of_condition_sound. eapply ma_perm; eauto. eauto. eauto with na.\n  eapply match_succ_states; eauto 2 with na.\n  simpl; destruct b; auto.\n\n- (* jumptable *)\n  TransfInstr; UseTransfer.\n  assert (LD: Val.lessdef rs#arg te#arg) by eauto 2 with na.\n  rewrite H0 in LD. inv LD.\n  econstructor; split.\n  eapply exec_Ijumptable; eauto.\n  eapply match_succ_states; eauto 2 with na.\n  simpl. eapply list_nth_z_in; eauto.\n\n- (* return *)\n  TransfInstr; UseTransfer.\n  exploit magree_free. eauto. eauto. instantiate (1 := nlive ge stk nmem_all).\n  intros; eapply nlive_dead_stack; eauto.\n  intros (tm' & A & B).\n  econstructor; split.\n  eapply exec_Ireturn; eauto.\n  erewrite stacksize_translated by eauto. eexact A.\n  constructor; auto.\n  destruct or; simpl; eauto 2 with na.\n  eapply magree_extends; eauto. apply nlive_all.\n\n- (* internal function *)\n  monadInv FUN. generalize EQ. unfold transf_function. fold (vanalyze cu f). intros EQ'.\n  destruct (analyze (vanalyze cu f) f) as [an|] eqn:AN; inv EQ'.\n  exploit Mem.alloc_extends; eauto. apply Zle_refl. apply Zle_refl.\n  intros (tm' & A & B).\n  econstructor; split.\n  econstructor; simpl; eauto.\n  simpl. econstructor; eauto.\n  apply eagree_init_regs; auto.\n  apply mextends_agree; auto.\n\n- (* external function *)\n  exploit external_call_mem_extends; eauto.\n  intros (res' & tm' & A & B & C & D).\n  simpl in FUN. inv FUN.\n  econstructor; split.\n  econstructor; eauto.\n  eapply external_call_symbols_preserved; eauto. apply senv_preserved.\n  econstructor; eauto.\n\n- (* return *)\n  inv STACKS. inv H1.\n  econstructor; split.\n  constructor.\n  econstructor; eauto. apply mextends_agree; auto.\nQed.\n\nLemma transf_initial_states:\n  forall st1, initial_state prog st1 ->\n  exists st2, initial_state tprog st2 /\\ match_states st1 st2.\nProof.\n  intros. inversion H.\n  exploit function_ptr_translated; eauto. intros (cu & tf & A & B & C).\n  exists (Callstate nil tf nil m0); split.\n  econstructor; eauto.\n  eapply (Genv.init_mem_match TRANSF); eauto.\n  replace (prog_main tprog) with (prog_main prog). \n  rewrite symbols_preserved. eauto.\n  symmetry; eapply match_program_main; eauto.\n  rewrite <- H3. eapply sig_function_translated; eauto.\n  econstructor; eauto. constructor. apply Mem.extends_refl.\nQed.\n\nLemma transf_final_states:\n  forall st1 st2 r,\n  match_states st1 st2 -> final_state st1 r -> final_state st2 r.\nProof.\n  intros. inv H0. inv H. inv STACKS. inv RES. constructor.\nQed.\n\n(** * Semantic preservation *)\n\nTheorem transf_program_correct:\n  forward_simulation (RTL.semantics prog) (RTL.semantics tprog).\nProof.\n  intros.\n  apply forward_simulation_step with\n     (match_states := fun s1 s2 => sound_state prog s1 /\\ match_states s1 s2).\n- apply senv_preserved.\n- simpl; intros. exploit transf_initial_states; eauto. intros [st2 [A B]].\n  exists st2; intuition. eapply sound_initial; eauto.\n- simpl; intros. destruct H. eapply transf_final_states; eauto.\n- simpl; intros. destruct H0.\n  assert (sound_state prog s1') by (eapply sound_step; eauto).\n  fold ge; fold tge. exploit step_simulation; eauto. intros [st2' [A B]].\n  exists st2'; auto.\nQed.\n\nEnd PRESERVATION.\n", "meta": {"author": "CertiKOS", "repo": "SingleStackCompCert", "sha": "04eb987a8cc0f428365edaa4dffb2237d02d9500", "save_path": "github-repos/coq/CertiKOS-SingleStackCompCert", "path": "github-repos/coq/CertiKOS-SingleStackCompCert/SingleStackCompCert-04eb987a8cc0f428365edaa4dffb2237d02d9500/backend/Deadcodeproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21490684071289798}}
{"text": "Require Import compcert.common.Errors.\nRequire Import compcert.driver.Compiler.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Smallstep.\nRequire Import compcert.lib.Integers.\n(* Here we show that we can turn steps in Cminor into steps in Asm *)\n\nSection sim.\n\n  Variable prog : Cminor.program.\n  \n  Variable st : Cminor.state.\n\n  Hypothesis init_state : Cminor.initial_state prog st.\n\n  Variable st' : Cminor.state.\n\n  Variable res : Int.int.\n  \n  Hypothesis final_state : Cminor.final_state st' res.\n\n  Variable t : trace.\n\n  Definition ge := Genv.globalenv prog.\n\n  Hypothesis steps : Smallstep.star Cminor.step ge st t st'.\n\n  Variable tprog : Asm.program.\n\n  Hypothesis TRANSF : transf_cminor_program prog = OK tprog.\n\n  Definition compcert_forward_simulation := fst (transf_cminor_program_correct prog tprog TRANSF).\n\n  Definition match_states := fsim_match_states compcert_forward_simulation.\n\n  Definition tge := Genv.globalenv tprog.\n  \n  Lemma asm_steps :\n    exists ast i,\n      match_states i st ast /\\\n      exists ast' i',\n        match_states i' st' ast' /\\\n        Smallstep.star Asm.step tge ast t ast'.\n  Proof.\n    eapply (fsim_match_initial_states compcert_forward_simulation) in init_state.\n    destruct init_state.\n    destruct H.\n    destruct H.\n    clear init_state.\n\n    assert (HStar : Star (Cminor.semantics prog) st t st').\n    {\n      apply steps.\n    }\n    eapply simulation_star in HStar; eauto.\n    destruct HStar.\n    destruct H1.\n    destruct H1.\n    unfold match_states.\n    remember H2 as H3. clear HeqH3.\n    eapply fsim_match_final_states in H2; eauto.\n    repeat eexists; eauto.\n  Qed.    \n\n\nEnd sim.\n    ", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/demos/word_freq/src/CminorToAsm.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.384912151539776, "lm_q1q2_score": 0.21490683899477867}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.ZArith.BinInt.\n\nOpen Scope list_scope.\nOpen Scope Z_scope.\n\nImport ListNotations.\n\nInductive Direction :=\n    | forward (n : Z)\n    | down (n : Z)\n    | up (n : Z)\n    .\n\nDefinition example_data := [ forward 5 ; down 5 ; forward 8 ; up 3 ; down 8 ; forward 2 ].\nDefinition data := [ forward 4 ; forward 6 ; down 8 ; forward 3 ; forward 9 ; down 7 ; down 7 ; down 1 ; forward 1 ; forward 5 ; up 4 ; forward 3 ; forward 9 ; forward 5 ; down 8 ; forward 6 ; forward 8 ; up 4 ; forward 1 ; forward 4 ; up 3 ; down 2 ; down 2 ; up 8 ; forward 9 ; down 5 ; down 6 ; down 4 ; forward 1 ; forward 7 ; down 1 ; forward 2 ; down 7 ; down 6 ; forward 3 ; forward 1 ; down 7 ; forward 3 ; up 7 ; up 1 ; forward 6 ; down 8 ; down 4 ; down 1 ; down 7 ; forward 9 ; down 2 ; forward 9 ; up 4 ; down 7 ; forward 9 ; forward 9 ; up 4 ; up 7 ; up 2 ; forward 1 ; down 9 ; forward 2 ; forward 8 ; forward 5 ; down 9 ; forward 5 ; up 1 ; forward 8 ; down 6 ; down 1 ; down 1 ; down 8 ; down 6 ; down 4 ; down 6 ; forward 7 ; forward 5 ; forward 4 ; up 8 ; up 4 ; forward 6 ; forward 9 ; forward 6 ; down 2 ; up 8 ; forward 3 ; forward 8 ; down 5 ; forward 1 ; down 6 ; down 7 ; up 4 ; down 8 ; forward 6 ; up 4 ; forward 7 ; down 8 ; down 8 ; down 2 ; down 8 ; up 7 ; forward 7 ; forward 6 ; down 2 ; forward 9 ; down 7 ; down 4 ; forward 1 ; up 9 ; down 6 ; up 7 ; down 6 ; down 2 ; down 2 ; forward 3 ; down 8 ; forward 4 ; down 7 ; down 2 ; up 8 ; down 6 ; forward 2 ; forward 2 ; down 6 ; up 6 ; down 7 ; up 5 ; up 4 ; up 9 ; forward 9 ; forward 7 ; down 4 ; down 4 ; up 5 ; down 2 ; forward 3 ; down 9 ; down 5 ; forward 8 ; up 3 ; forward 7 ; forward 9 ; down 3 ; forward 1 ; up 1 ; forward 5 ; down 8 ; down 2 ; forward 3 ; down 6 ; down 8 ; up 9 ; down 9 ; forward 4 ; up 5 ; forward 8 ; forward 7 ; forward 7 ; down 3 ; down 5 ; forward 8 ; down 1 ; down 2 ; forward 2 ; up 9 ; down 3 ; down 9 ; forward 2 ; down 4 ; up 9 ; up 3 ; down 1 ; down 1 ; forward 6 ; down 5 ; down 9 ; forward 2 ; up 5 ; forward 3 ; down 1 ; down 7 ; forward 1 ; forward 1 ; down 7 ; up 3 ; up 1 ; up 6 ; forward 9 ; up 1 ; down 8 ; down 5 ; up 6 ; up 2 ; down 8 ; forward 3 ; forward 1 ; down 7 ; up 1 ; down 9 ; down 9 ; up 8 ; forward 4 ; up 8 ; forward 8 ; down 5 ; forward 5 ; forward 2 ; forward 1 ; forward 5 ; down 8 ; forward 6 ; forward 8 ; down 5 ; forward 8 ; up 1 ; up 9 ; up 7 ; down 5 ; down 9 ; up 4 ; down 7 ; up 8 ; up 3 ; forward 6 ; down 9 ; forward 4 ; down 4 ; forward 2 ; forward 3 ; down 4 ; down 5 ; down 3 ; forward 9 ; forward 5 ; forward 9 ; forward 4 ; down 5 ; down 7 ; down 5 ; forward 8 ; up 5 ; down 2 ; forward 3 ; forward 4 ; down 5 ; up 8 ; forward 5 ; down 2 ; up 4 ; down 5 ; down 2 ; forward 1 ; up 3 ; down 6 ; down 8 ; down 3 ; forward 1 ; up 5 ; forward 1 ; down 3 ; forward 4 ; down 6 ; forward 8 ; forward 4 ; forward 1 ; down 8 ; down 2 ; forward 8 ; down 5 ; forward 2 ; forward 2 ; down 9 ; forward 1 ; forward 8 ; up 1 ; forward 1 ; down 1 ; down 7 ; down 4 ; up 4 ; down 3 ; forward 1 ; forward 9 ; down 9 ; up 6 ; up 8 ; down 2 ; down 2 ; down 3 ; forward 2 ; forward 9 ; down 1 ; up 9 ; down 3 ; down 9 ; down 1 ; down 7 ; forward 9 ; forward 7 ; down 5 ; down 2 ; down 9 ; down 2 ; down 7 ; up 7 ; down 2 ; up 3 ; up 5 ; forward 8 ; up 7 ; forward 1 ; down 9 ; down 9 ; down 1 ; forward 6 ; down 7 ; up 4 ; up 4 ; down 9 ; up 5 ; up 8 ; down 3 ; down 5 ; forward 6 ; up 3 ; down 8 ; down 5 ; forward 9 ; up 6 ; forward 9 ; forward 5 ; up 6 ; up 9 ; down 2 ; up 5 ; forward 9 ; down 1 ; up 1 ; down 9 ; forward 4 ; forward 4 ; forward 8 ; down 5 ; down 3 ; down 7 ; forward 5 ; down 6 ; forward 3 ; down 5 ; down 5 ; up 5 ; forward 8 ; forward 1 ; forward 2 ; forward 6 ; up 1 ; down 5 ; down 4 ; up 5 ; forward 3 ; forward 2 ; forward 2 ; forward 2 ; forward 7 ; forward 8 ; down 2 ; up 8 ; forward 4 ; down 4 ; forward 7 ; down 6 ; down 7 ; forward 5 ; down 5 ; forward 1 ; down 8 ; forward 6 ; down 1 ; forward 3 ; up 3 ; down 7 ; down 2 ; up 4 ; down 3 ; up 2 ; up 8 ; down 2 ; forward 5 ; forward 3 ; down 9 ; down 9 ; up 2 ; forward 6 ; forward 9 ; down 1 ; forward 6 ; down 4 ; up 2 ; down 7 ; down 3 ; down 3 ; forward 2 ; down 5 ; down 9 ; down 7 ; forward 7 ; forward 9 ; up 8 ; down 8 ; down 3 ; up 5 ; down 9 ; forward 8 ; forward 8 ; down 1 ; forward 5 ; forward 2 ; forward 7 ; down 9 ; down 7 ; forward 6 ; up 9 ; forward 3 ; forward 5 ; up 7 ; down 9 ; forward 9 ; forward 4 ; forward 5 ; forward 9 ; forward 8 ; forward 1 ; forward 2 ; forward 8 ; down 7 ; forward 3 ; up 2 ; up 7 ; forward 1 ; forward 3 ; forward 9 ; up 3 ; down 2 ; forward 3 ; forward 6 ; forward 3 ; forward 3 ; forward 3 ; forward 1 ; forward 1 ; up 5 ; down 5 ; up 5 ; down 5 ; down 5 ; forward 8 ; forward 1 ; down 4 ; forward 7 ; down 6 ; down 1 ; down 2 ; down 2 ; down 6 ; up 8 ; forward 3 ; forward 2 ; up 8 ; up 2 ; forward 1 ; forward 6 ; forward 5 ; forward 6 ; forward 7 ; down 8 ; forward 1 ; down 4 ; forward 2 ; up 4 ; forward 4 ; down 1 ; forward 5 ; down 7 ; forward 7 ; up 7 ; forward 1 ; down 2 ; forward 8 ; forward 5 ; up 8 ; up 8 ; up 2 ; down 9 ; forward 2 ; down 4 ; down 3 ; down 5 ; down 5 ; down 2 ; up 5 ; forward 6 ; up 7 ; forward 8 ; up 7 ; down 4 ; forward 1 ; down 3 ; forward 2 ; forward 1 ; down 2 ; up 7 ; forward 5 ; up 8 ; up 1 ; down 4 ; forward 6 ; down 4 ; up 9 ; forward 5 ; down 2 ; down 7 ; down 7 ; forward 4 ; forward 4 ; forward 9 ; down 1 ; forward 6 ; forward 1 ; up 9 ; forward 4 ; forward 4 ; forward 8 ; forward 3 ; forward 4 ; down 3 ; up 5 ; up 1 ; forward 3 ; down 6 ; down 4 ; down 2 ; forward 3 ; forward 8 ; up 6 ; up 3 ; forward 8 ; down 3 ; down 6 ; forward 1 ; up 7 ; down 4 ; down 5 ; up 7 ; forward 3 ; up 4 ; forward 9 ; forward 6 ; down 3 ; forward 4 ; down 6 ; forward 1 ; forward 6 ; forward 4 ; forward 2 ; forward 1 ; forward 3 ; forward 1 ; down 1 ; down 9 ; down 5 ; down 7 ; down 4 ; down 8 ; up 1 ; down 6 ; down 1 ; forward 4 ; down 9 ; up 9 ; down 6 ; forward 6 ; forward 8 ; up 7 ; forward 4 ; down 3 ; forward 9 ; forward 6 ; forward 8 ; down 1 ; up 2 ; down 2 ; down 8 ; forward 4 ; down 9 ; down 3 ; forward 5 ; down 9 ; down 4 ; up 5 ; down 8 ; down 4 ; down 9 ; up 4 ; down 5 ; down 7 ; down 3 ; up 1 ; up 1 ; down 4 ; down 6 ; forward 8 ; down 8 ; down 6 ; forward 6 ; forward 9 ; forward 3 ; forward 3 ; down 2 ; down 4 ; forward 3 ; up 5 ; up 3 ; down 5 ; down 1 ; forward 5 ; forward 7 ; forward 1 ; forward 4 ; forward 5 ; forward 1 ; down 7 ; down 8 ; up 9 ; down 8 ; down 5 ; up 3 ; down 5 ; down 5 ; forward 8 ; down 2 ; forward 7 ; forward 7 ; down 1 ; forward 2 ; forward 7 ; forward 5 ; down 6 ; forward 5 ; down 5 ; forward 4 ; down 8 ; forward 7 ; up 5 ; forward 5 ; down 7 ; down 7 ; up 4 ; forward 8 ; up 1 ; forward 3 ; forward 7 ; down 2 ; forward 1 ; down 4 ; up 8 ; forward 3 ; forward 1 ; forward 6 ; forward 3 ; up 4 ; forward 3 ; down 3 ; forward 7 ; forward 9 ; forward 8 ; down 6 ; down 8 ; up 6 ; down 9 ; forward 7 ; forward 1 ; up 4 ; forward 5 ; forward 8 ; down 7 ; down 9 ; up 6 ; up 6 ; forward 9 ; down 1 ; forward 8 ; down 9 ; down 5 ; forward 6 ; forward 1 ; down 4 ; forward 8 ; down 9 ; down 4 ; forward 5 ; forward 7 ; forward 3 ; down 2 ; forward 6 ; forward 3 ; forward 8 ; down 1 ; down 5 ; up 6 ; down 2 ; down 1 ; up 3 ; down 7 ; up 1 ; forward 8 ; down 6 ; down 6 ; forward 8 ; up 3 ; forward 8 ; up 3 ; forward 3 ; forward 7 ; forward 1 ; down 1 ; up 5 ; forward 5 ; forward 9 ; forward 5 ; forward 1 ; forward 4 ; down 8 ; forward 2 ; up 3 ; forward 3 ; down 9 ; forward 2 ; forward 6 ; forward 3 ; up 8 ; up 1 ; down 6 ; forward 3 ; down 4 ; down 5 ; forward 6 ; forward 9 ; down 4 ; down 9 ; down 7 ; down 1 ; up 3 ; up 6 ; forward 4 ; forward 5 ; down 1 ; forward 3 ; up 5 ; forward 7 ; down 9 ; forward 5 ; down 5 ; down 1 ; down 1 ; down 1 ; up 8 ; down 4 ; down 9 ; forward 5 ; down 5 ; up 5 ; up 3 ; forward 1 ; forward 7 ; down 2 ; forward 6 ; forward 5 ; up 4 ; up 4 ; forward 1 ; down 7 ; down 8 ; up 3 ; down 3 ; up 4 ; forward 2 ; up 4 ; up 4 ; forward 8 ; forward 1 ; forward 2 ; forward 7 ; down 6 ; forward 8 ; forward 9 ; forward 6 ; forward 9 ; down 3 ; up 3 ; forward 5 ; down 1 ; forward 1 ; forward 4 ; forward 2 ; down 6 ; up 7 ; forward 9 ; down 2 ; up 5 ; forward 6 ; down 9 ; down 6 ; down 8 ; forward 2 ; down 7 ; forward 6 ; down 8 ; forward 3 ; forward 7 ; forward 6 ; down 7 ; down 6 ; forward 5 ; up 8 ; forward 6 ; down 1 ; up 9 ; forward 6 ; down 6 ; down 5 ; down 6 ; up 2 ; down 3 ; down 7 ; down 3 ; forward 4 ; up 9 ; up 2 ; forward 1 ; forward 7 ; forward 7 ; forward 9 ; forward 8 ; forward 7 ; down 3 ; forward 4 ; forward 8 ; down 9 ; forward 2 ; forward 2 ; up 9 ; up 7 ; forward 2 ; down 8 ; down 3 ; down 1 ; forward 1 ; forward 3 ; down 2 ; forward 7 ; up 4 ; down 7 ; down 1 ; forward 8 ; forward 2 ; up 1 ; down 5 ; forward 8 ; up 5 ; up 7 ; forward 4 ; forward 7 ; up 4 ; up 3 ; forward 5 ; forward 9 ; forward 1 ; forward 3 ; down 9 ; up 2 ; forward 8 ; down 3 ; forward 3 ; forward 2 ; down 8 ; down 2 ; down 3 ; forward 1 ; up 7 ; down 1 ; forward 3 ; forward 8 ; down 3 ; down 9 ; up 1 ; down 9 ; up 7 ; up 7 ; forward 7 ; forward 7 ; up 8 ; down 2 ; down 7 ; down 1 ; forward 5 ; forward 5 ; forward 7 ; down 8 ; forward 5 ; down 9 ; down 8 ; forward 3 ; up 9 ; forward 3 ; up 6 ; forward 7 ; up 7 ; forward 3 ; forward 2 ; down 1 ; down 4 ; forward 1 ; forward 8 ; up 5 ; down 5 ; up 1 ; down 5 ; up 1 ; up 6 ; forward 5 ; forward 5 ; down 3 ; down 3 ; forward 2 ; up 3 ; up 2 ; down 6 ; down 5 ; down 1 ; down 1 ; up 6 ; forward 2 ; forward 2 ; up 4 ; up 6 ; up 6 ; down 8 ; up 2 ; forward 4 ; down 3 ; forward 3 ; up 4 ; down 5 ; forward 6 ; forward 7 ; up 6 ; down 3 ; down 7 ; up 4 ; down 2 ; up 2 ; forward 1 ; down 8 ; down 1 ; down 1 ; up 9 ; down 1 ; down 1 ; up 1 ; forward 8 ; forward 4 ; down 4 ; forward 1 ; down 4 ; up 7 ; forward 7 ; forward 3 ; down 4 ; forward 9 ; forward 1 ; down 3 ; down 2 ; forward 7 ; up 1 ; forward 3 ; up 3 ; down 3 ; down 7 ; up 3 ; up 4 ; forward 7 ; down 2 ; up 2 ; down 9 ; up 1 ; forward 3 ; up 8 ; up 8 ; down 8 ; down 1 ; up 8 ; up 4 ; down 6 ; forward 8 ].\n\nFixpoint position (x y : Z) (data : list Direction) :=\n    match data with\n    | [] => x * y\n    | (forward n) :: l => position (x + n) y l\n    | (down n) :: l => position x (y + n) l\n    | (up n) :: l => position x (y - n) l\n    end.\n\nDefinition part1 := position 0 0 data.\n\nFixpoint position_aim (x y aim : Z) (data : list Direction) :=\n    match data with\n    | [] => x * y\n    | (forward n) :: l => position_aim (x + n) (y + n*aim) aim l\n    | (down n) :: l => position_aim x y (aim + n) l\n    | (up n) :: l => position_aim x y (aim - n) l\n    end.\n\nDefinition part2 := position_aim 0 0 0 data.\n\nCompute part1.\nCompute part2.", "meta": {"author": "ThomasJSains", "repo": "advent-of-code-21", "sha": "b3b6ddd221e5ea10b8dea048e483d3ab83652f9a", "save_path": "github-repos/coq/ThomasJSains-advent-of-code-21", "path": "github-repos/coq/ThomasJSains-advent-of-code-21/advent-of-code-21-b3b6ddd221e5ea10b8dea048e483d3ab83652f9a/day2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.21486378383334437}}
{"text": "From iris.proofmode Require Import tactics.\nFrom machine_program_logic.program_logic Require Import weakestpre.\nFrom HypVeri.lang Require Import lang.\nFrom HypVeri Require Import big_sepFM machine_extra.\nFrom HypVeri.algebra Require Import base base_extra mem mailbox trans.\nFrom HypVeri.logrel Require Import big_sepSS.\nImport uPred.\n\n\nSection slice_trans.\n  Context `{hypconst:HypervisorConstants}.\n  Context `{vmG: !gen_VMG Σ}.\n  Context (Φ : (gmap Addr transaction) -> VMID -> VMID -> iProp Σ).\n\n  Definition trans_preserve_slice i j (trans trans': (gmap Addr transaction)):=\n    filter (λ kv, kv.2.1.1.1.1 = i ∧ kv.2.1.1.1.2 = j) trans\n                        = filter (λ kv, kv.2.1.1.1.1 = i ∧ kv.2.1.1.1.2 = j) trans'.\n\n  Class SliceTransWf :=\n    {\n      slice_trans_valid : ∀ i j trans trans',\n        trans_preserve_slice i j trans trans'-> (Φ trans i j ⊣⊢ Φ trans' i j)\n    }.\n\n\nEnd slice_trans.\n\nGlobal Arguments SliceTransWf {_} {_} _.\nGlobal Arguments slice_trans_valid {_} {_} _ {_} {_} {_} {_} {_} _.\nGlobal Hint Mode SliceTransWf + + ! : typeclass_instances.\n\nSection slice_rxs.\n  Context `{hypconst:HypervisorConstants}.\n  Context `{vmG: !gen_VMG Σ}.\n  Context (Φ :VMID -> option (Word * VMID)-> VMID -> iProp Σ).\n\n  Class SliceRxsWf :=\n    {\n      slice_rxs_empty : ∀ i j, Φ i None j ⊣⊢ True;\n      slice_rxs_sym : ∀ i os k k',\n        (match os with\n         | None => True\n         | Some (_,j) => j ≠ V0 ->  Φ i os k ⊣⊢ Φ i os k'\n         end);\n    }.\n\nEnd slice_rxs.\n\nGlobal Arguments SliceRxsWf {_} {_} _.\nGlobal Arguments slice_rxs_empty {_} {_} _ {_} _ _.\nGlobal Arguments slice_rxs_sym {_} {_} _ {_} {_} {_} _ _.\nGlobal Hint Mode SliceRxsWf + + ! : typeclass_instances.\n\n(**  unary logical relation **)\nSection logrel.\n  Context `{hypconst:HypervisorConstants}.\n  Context `{hypparams:!HypervisorParameters}.\n  Context `{vmG: !gen_VMG Σ}.\n\n  Definition set_of_vmids : gset VMID := (list_to_set list_of_vmids).\n  Definition lift_option_gmap`{Countable K} {V: Type} (m: gmap K V) := (λ v, Some v) <$> m.\n  Definition pages_in_trans (trans: gmap Word transaction) : gset PID :=\n    pages_in_trans' (lift_option_gmap trans).\n\n  Definition trans_ps_disj trans := inv_trans_ps_disj' (lift_option_gmap trans).\n\n  Definition pgt (ps: gset PID) q (vo: VMID) (be: bool) : iProp Σ :=\n    [∗ set] p ∈ ps, p -@{q}O> vo ∗ p -@{q}E> be.\n\n  Definition pgt_full ps vo be := pgt ps 1 vo be.\n  Definition pgt_3_4 ps vo be : iProp Σ := pgt ps (1/4) vo be ∗ pgt ps (1/2) vo be.\n  Definition pgt_1_4 ps vo be : iProp Σ := pgt ps (1/4) vo be.\n\n  (** definitions **)\n\n   (* [transaction_pagetable_entries_transferred] : For donation, the half of transaction entries that are kept by sender in case\n      of sharing and lending are also be passed around between the sender and the receiver, as retrieval in this case also requires\n      full entries.\n      Pagetable entries are transferred along as both sender and receiver could be the exclusive owner of those pages. *)\n  Definition transaction_pagetable_entries_transferred i (trans: gmap Addr transaction) : iProp Σ:=\n    big_sepFM trans (λ kv, (kv.2.1.1.1.1 = i ∨ kv.2.1.1.1.2 = i) ∧ kv.2.1.2 = Donation) (λ k v, k -{1/4}>t v.1 ∗ pgt_1_4 v.1.1.2 v.1.1.1.1 true)%I.\n\n  (* [retrieval entries]: half of all retrieval entries of i-related transactions are required.\n     For transactions where i is the sender, we need the corresponding retrieval entries to check if it is allowed for i to reclaim,\n     for the cases when i is the receiver, they are required so that i can retrieve or relinquish *)\n  (* There are also some cases when we need the second half, as in those cases we may update/remove the retrival state *)\n  (* XXX: How to relate retrieval and transaction entries? Using option(frac_agree transaction,option bool)? or is it unnecessary? *)\n  Definition retrievable_transaction_transferred i (trans: gmap Addr transaction) : iProp Σ:=\n    (big_sepFM trans (λ kv, kv.2.1.1.1.1 = i ∨ kv.2.1.1.1.2 = i) (λ k v, k -{1/2}>re v.2 )%I) ∗\n    (big_sepFM trans (λ kv, (kv.2.1.1.1.1 = i ∨ kv.2.1.1.1.2 = i) ∧ kv.2.2 = false) (λ k v, k -{1/4}>t v.1 ∗ k -{1/2}>re v.2)%I).\n\n  (* [transaction_pagetable_entries_owned]: transaction and page table entries that are owned initially by i,\n     i.e. they are not transferred by VMProp, so we doesn't need to take care of them when reasoning the primary VM.\n     As the invoker of sharing and lending transactions, i always has the ownership of involved pages.\n     Therefore, i ownes these pagetable entries even if they are in some transactions.\n     Furthermore, since it is suffice for the receiver to retrieve or relinquish with half of transacitons entries,\n     while the sender needs full to reclaim, we let i always own half and only pass the otner half around with VMProp*)\n  (* [TODO] relation to [pagetable_entries_excl_owned] *)\n  Definition transaction_pagetable_entries_owned i (trans: gmap Addr transaction) : iProp Σ:=\n    big_sepFM trans (λ kv, kv.2.1.1.1.1 = i ∧ kv.2.1.2 ≠ Donation) (λ k v, k -{1/4}>t v.1 ∗ pgt_1_4 v.1.1.2 v.1.1.1.1 (bool_decide (v.1.2 ≠ Sharing)))%I.\n\n  Context (i : (leibnizO VMID)).\n\n  (* [TODO] *)\n  Definition retrieved_transaction_owned i (trans: gmap Addr transaction) : iProp Σ:=\n    (big_sepFM trans (λ kv, kv.2.1.1.1.2 = i ∧ kv.2.2 = true) (λ k v, k -{1/4}>t v.1 ∗ k -{1/2}>re v.2)%I).\n\n  Program Definition interp_execute: iPropO Σ :=\n   (⌜i ≠ V0⌝ -∗\n        (VMProp_holds i (1/2)%Qp -∗ WP ExecI @ i {{(λ _, True )}}))%I.\n\n  (* [pagetable_entries_excl_owned]: For pages that are exclusively accessible and owned by i, i keeps the entries. *)\n  Definition pagetable_entries_excl_owned (i:VMID) (ps: gset PID) := pgt ps 1 i true.\n\n  (* [transaction_hpool_global_transferred]: All of half of transactions, as we don't know which one would be used by i. *)\n  (* We need the pure proposition to ensure all transaction entries are transferred.\n     Only half is needed so that the invokers can remember transactions by keeping the other half.*)\n  Definition transaction_hpool_global_transferred (trans: gmap Addr transaction) : iProp Σ:=\n    ∃ hpool,  ⌜hpool ∪ dom trans = valid_handles⌝ ∗ fresh_handles 1 hpool\n       ∗ ([∗ map] h ↦ tran ∈ trans, h -{1/2}>t tran.1 ∗ pgt_3_4 tran.1.1.2 tran.1.1.1.1 (bool_decide (tran.1.2 ≠ Sharing))).\n\n  (* [transferred_memory_pages]: some memory points-to predicates are transferred by VMProp.\n      NOTE: we exclude the case when the type of transaction is lending and has been retrieved,\n      as the associated memory pages in this case is exclusively owned by the receiver*)\n  Definition transferred_memory_pages (trans : gmap Word transaction) :=\n    pages_in_trans (filter (λ kv, (kv.2.1.1.1.1 = i ∨ kv.2.1.1.1.2 = i) ∧ ¬(kv.2.2 = true ∧ kv.2.1.2 = Lending)) trans).\n\n  (* [retrieved_lending_memory_pages]: the memory of these pages are owned by the receiver *)\n  Definition retrieved_lending_memory_pages (trans : gmap Word transaction) :=\n    pages_in_trans (filter (λ kv, kv.2.1.1.1.2 = i ∧ (kv.2.2 = true ∧ kv.2.1.2 = Lending)) trans).\n\n  (* [accessible_in_trans_memory_pages] (maybe) accessible memory pages associated with transactions *)\n  Definition accessible_in_trans_memory_pages (trans : gmap Word transaction) :=\n    pages_in_trans (filter (λ kv, (kv.2.1.1.1.1 = i ∧ ¬(kv.2.2 = true ∧ kv.2.1.2 = Lending)) ∨ kv.2.1.1.1.2 = i) trans).\n\n  (* [currently_accessible_in_trans_memory_pages] currently accessible memory pages associated with transactions *)\n  Definition currently_accessible_in_trans_memory_pages (trans : gmap Word transaction) :=\n    pages_in_trans (filter (λ kv, (kv.2.1.1.1.1 = i ∧ kv.2.1.2 = Sharing) ∨ (kv.2.1.1.1.2 = i ∧ kv.2.2 = true)) trans).\n\n  Definition trans_rel_wand (P : gmap Word transaction -d> iPropO Σ) (trans trans': gmap Word transaction ): iProp Σ:=\n    □(P trans -∗ P trans').\n\n  Definition trans_rel_eq (P : gmap Word transaction -> gset PID) (trans trans': gmap Word transaction ): Prop:=\n    P trans = P trans'.\n\n  Definition rx_state_match i os : iProp Σ :=\n    match os with\n    | None => RX_state@i := None ∗ ∃p_rx, RX@ i := p_rx ∗ (∃ mem_rx, memory_page p_rx mem_rx)\n    | Some s => RX_state{1/2}@i := Some(s)\n    end.\n\n  Definition rx_states_global (rxs: gmap VMID (option (Word*VMID))) : iProp Σ :=\n    [∗ map]i ↦ os ∈ rxs, rx_state_match i os.\n\n  Definition rx_state_get (i:VMID) (rxs: gmap VMID (option (Word*VMID))) :iProp Σ:=\n    ∀ rs, ⌜rxs !! i = Some rs⌝ -∗ RX_state@i := rs.\n\n  (* (* [TODO] *) *)\n  (* Definition return_reg_rx i (rs : option (Word * VMID)) (rxs :gmap VMID (option(Word*VMID))): iProp Σ:= *)\n  (*   ((R0 @@ V0 ->r encode_hvc_func(Yield) ∨ *)\n  (*     R0 @@ V0 ->r encode_hvc_func(Wait) ∗ ⌜rs = None⌝) *)\n  (*    ∗ rx_states_global (delete i rxs) *)\n  (*    ∗ R1 @@ V0 ->r encode_vmid(i) ∗ ∃ r2, R2 @@ V0 ->r r2) ∨ *)\n  (*   (R0 @@ V0 ->r encode_hvc_func(Send) *)\n  (*     ∗ ∃ l j, RX_state{1/2}@j := Some(l,i) ∗ (∃ p_rx, RX@ j := p_rx ∗ ∃ mem_rx, memory_page p_rx mem_rx) *)\n  (*     ∗ rx_states_global (<[j:=Some(l,i)]>(delete i rxs)) ∗ ⌜rxs !! j = Some None⌝ *)\n  (*     ∗ (∃r1, R1 @@ V0 ->r r1 ∗ ⌜decode_vmid r1 = Some j⌝) ∗  R2 @@ V0 ->r l). *)\n\n  Definition only (trans: gmap Word transaction) := (filter (λ (kv :Word*transaction), (kv.2.1.1.1.1 = i ∨ kv.2.1.1.1.2 = i)) trans).\n\n  Definition except (trans: gmap Word transaction) := (filter (λ (kv :Word*transaction), ¬(kv.2.1.1.1.1 = i ∨ kv.2.1.1.1.2 = i)) trans).\n\n  (* [trans_rel_secondary] relates [trans], the transactions at the beginning of the proof, and\n                [trans'], those at the point of switching to i. These assumptions are (I believe) necessary to prove FTLR.\n                Moreover, they are provable because of that fact that i as the invoker is the only vm can manipulate\n                the state of some transactions, and since, i is not scheduled during the time between starting pvm\n                and switching to i, states of those transactions are immutable. *)\n  Definition trans_rel_secondary (i:VMID) (trans trans': gmap Word transaction): Prop :=\n    (λ tran, tran.1) <$> filter (λ kv, (kv.2.1.1.1.1 = i ∧ kv.2.1.2 ≠ Donation)) trans' =\n    (λ tran, tran.1) <$> filter (λ kv, (kv.2.1.1.1.1 = i ∧ kv.2.1.2 ≠ Donation)) trans\n    ∧\n    (filter (λ kv, (kv.2.1.1.1.2 = i ∧ kv.2.2 = true)) trans') =\n    (filter (λ kv, (kv.2.1.1.1.2 = i ∧ kv.2.2 = true)) trans).\n  (* Definition trans_rel_pre (i:VMID) (trans trans': gmap Word transaction): Prop := *)\n  (*   dom (filter (λ kv, (kv.2.1.1.1.1 = i ∧ kv.2.1.2 ≠ Donation)) trans') *)\n  (*     ⊆ dom (filter (λ kv, (kv.2.1.1.1.1 = i ∧ kv.2.1.2 ≠ Donation)) trans) *)\n  (*   ∧ *)\n  (*   dom (filter (λ kv, (kv.2.1.1.1.2 = i ∧ kv.2.2 = true)) trans') *)\n  (*   ⊆ dom (filter (λ kv, (kv.2.1.1.1.2 = i ∧ kv.2.2 = true)) trans). *)\n\n(* Section vmprop. *)\n(*   Context `{HypervisorConstants}. *)\n(*   Context `{!HypervisorParameters}. *)\n(*   Context `{vmG: !gen_VMG Σ}. *)\n  (* Context (i : VMID). *)\n  Context (Φ_t : (gmap Addr transaction) -> VMID -> VMID -> iProp Σ).\n  Context (Φ_r : VMID -> option (Word * VMID)-> VMID -> iProp Σ).\n\n  Definition rx_states_transferred (rxs: gmap VMID (option (Word*VMID))) : iProp Σ :=\n    [∗ map]i ↦ os ∈ rxs, match os with\n                           | None => True\n                           | Some s => Φ_r i os V0\n                          end.\n\n  Definition rx_states_owned (rxs: gmap VMID (option (Word*VMID))) : iProp Σ :=\n    [∗ map]i ↦ os ∈ rxs, match os with\n                           | None => True\n                           | Some s => if bool_decide (s.2 = V0) then Φ_r i os i else True\n                          end.\n\n  Definition return_reg_rx i (rs : option (Word * VMID)) (rxs :gmap VMID (option(Word*VMID))): iProp Σ:=\n    ((R0 @@ V0 ->r encode_hvc_func(Yield) ∨\n      R0 @@ V0 ->r encode_hvc_func(Wait) ∗ ⌜rs = None⌝)\n     ∗ rx_states_global (delete i rxs)\n     ∗ R1 @@ V0 ->r encode_vmid(i) ∗ ∃ r2, R2 @@ V0 ->r r2) ∨\n    (R0 @@ V0 ->r encode_hvc_func(Send)\n      ∗ ∃ l j, Φ_r j (Some (l,i)) V0\n      ∗ rx_states_global (<[j:=Some(l,i)]>(delete i rxs)) ∗ ⌜rxs !! j = Some None⌝\n      ∗ (∃r1, R1 @@ V0 ->r r1 ∗ ⌜decode_vmid r1 = Some j⌝) ∗  R2 @@ V0 ->r l).\n\n  Definition vmprop_zero_pre (Ψ: (gmap Word transaction) -d> iPropO Σ) : (gmap Word transaction) -d> (gmap VMID (option(Word * VMID))) -d> iPropO Σ :=\n    λ trans rxs, (∃ (trans' :gmap Word transaction) rs',\n                     let trans_ret := (only trans') ∪ (except trans) in\n                           ⌜dom (only trans') ## dom (except trans)⌝ ∗\n                           ⌜∀ x, x ≠ i -> trans_rel_secondary x trans trans_ret⌝ ∗\n                           transaction_hpool_global_transferred (trans_ret) ∗\n                           big_sepSS_singleton set_of_vmids i (Φ_t trans_ret) ∗\n                           rx_state_match i rs' ∗ Φ_r i rs' V0 ∗\n                           return_reg_rx i rs' rxs ∗\n                           VMProp i (Ψ trans_ret) (1/2)%Qp)%I.\n\n  Definition vmprop_unknown_pre\n    (Ψ :(gmap Word transaction) -d> iPropO Σ) : (gmap Word transaction) -d> iPropO Σ :=\n   λ trans, (∃ (trans' : gmap Word transaction) (rxs : gmap VMID (option(Word * VMID))),\n               ⌜trans_rel_secondary i trans trans'⌝ ∗\n               (* transaction and pagetable entries *)\n               transaction_hpool_global_transferred trans' ∗\n               big_sepSS_singleton set_of_vmids i (Φ_t trans') ∗\n               (∃ r0, R0 @@ V0 ->r r0 ∗ ⌜decode_hvc_func r0 = Some Run⌝) ∗ (∃ r1, R1 @@ V0 ->r r1 ∗ ⌜decode_vmid r1 = Some i⌝)∗ (∃ r2, R2 @@ V0 ->r r2) ∗\n               (∀ rs : option (Addr * VMID), ⌜rxs !! i = Some rs⌝ -∗ rx_state_match i rs ∗ Φ_r i rs i) ∗\n               (* rx pages for all other VMs *)\n               (rx_states_global (delete i rxs)) ∗ ⌜is_total_gmap rxs⌝ ∗\n               (* if i yielding, we give following resources back to pvm *)\n               VMProp V0 (vmprop_zero_pre Ψ trans' rxs) (1/2)%Qp)%I.\n\n  Local Instance vmprop_unknown_pre_contractive : Contractive (vmprop_unknown_pre).\n  Proof.\n    rewrite /vmprop_unknown_pre => n vmprop_unknown vmprop_unknown' Hvmprop_unknown trans /=.\n    do 13 f_equiv.\n    rewrite /VMProp /=.\n    do 6 f_equiv.\n    f_contractive.\n    rewrite /vmprop_zero_pre.\n    do 10 f_equiv.\n    rewrite /VMProp.\n    repeat f_equiv.\n  Qed.\n\n  Definition vmprop_unknown:= fixpoint (vmprop_unknown_pre).\n\n  Definition vmprop_zero := vmprop_zero_pre vmprop_unknown.\n\n  Lemma vmprop_unknown_eq trans: vmprop_unknown trans ⊣⊢\n    (∃ (trans' : gmap Word transaction) (rxs : gmap VMID (option(Word * VMID))),\n               ⌜trans_rel_secondary i trans trans'⌝ ∗\n               (* transaction and pagetable entries *)\n               transaction_hpool_global_transferred trans' ∗\n               big_sepSS_singleton set_of_vmids i (Φ_t trans') ∗\n               (∃ r0, R0 @@ V0 ->r r0 ∗ ⌜decode_hvc_func r0 = Some Run⌝) ∗ (∃ r1, R1 @@ V0 ->r r1 ∗ ⌜decode_vmid r1 = Some i⌝)∗ (∃ r2, R2 @@ V0 ->r r2) ∗\n               (∀ rs : option (Addr * VMID), ⌜rxs !! i = Some rs⌝ -∗ rx_state_match i rs ∗ Φ_r i rs i) ∗\n               (* rx pages for all other VMs *)\n               (rx_states_global (delete i rxs)) ∗ ⌜is_total_gmap rxs⌝ ∗\n               (* if i yielding, we give following resources back to pvm *)\n          VMProp V0 (vmprop_zero trans' rxs) (1/2)%Qp)%I.\n  Proof.\n    rewrite /vmprop_unknown.\n    apply (fixpoint_unfold vmprop_unknown_pre).\n  Qed.\n\n  (* Definition vmprop_zero_pre (Ψ: (gmap Word transaction) -d> iPropO Σ) : (gmap Word transaction) -d> (gmap VMID (option(Word*VMID))) -d> iPropO Σ := *)\n  (*   λ trans rxs, (∃ trans' rs', *)\n  (*                    let trans_ret := (only trans') ∪ (except trans) in *)\n  (*                          ⌜dom (only trans') ## dom (except trans)⌝ ∗ *)\n  (*                          ⌜∀ x, x ≠ i -> trans_rel_secondary x trans trans_ret⌝ ∗ *)\n  (*                          (* transaction and pagetable entries *) *)\n  (*                          transaction_hpool_global_transferred trans_ret ∗ *)\n  (*                          transaction_pagetable_entries_transferred i trans_ret ∗ *)\n  (*                          retrievable_transaction_transferred i trans_ret ∗ *)\n  (*                          (* memory *) *)\n  (*                          (∃ mem_trans, memory_pages (transferred_memory_pages trans_ret) mem_trans) ∗ *)\n  (*                          (RX_state@i:= rs') ∗ (∃p_rx, RX@i := p_rx ∗ (∃ mem_rx, memory_page p_rx mem_rx)) ∗ *)\n  (*                          return_reg_rx i rs' rxs ∗ *)\n  (*                          VMProp i (Ψ trans_ret) (1/2)%Qp)%I. *)\n\n  (* Definition vmprop_unknown_pre (Φ: (gmap Word transaction) -d> iPropO Σ) : (gmap Word transaction) -d> iPropO Σ := *)\n  (*  λ trans, (∃ (trans' : gmap Word transaction) (rxs : gmap VMID (option(Word * VMID))), *)\n  (*              ⌜trans_rel_secondary i trans trans'⌝ ∗ *)\n  (*              (* transaction and pagetable entries *) *)\n  (*              transaction_hpool_global_transferred trans' ∗ *)\n  (*              transaction_pagetable_entries_transferred i trans' ∗ *)\n  (*              retrievable_transaction_transferred i trans' ∗ *)\n  (*              (* memory *) *)\n  (*              (∃ mem_trans, memory_pages (transferred_memory_pages trans') mem_trans) ∗ *)\n  (*              (∃ r0, R0 @@ V0 ->r r0 ∗ ⌜decode_hvc_func r0 = Some Run⌝) ∗ (∃ r1, R1 @@ V0 ->r r1 ∗ ⌜decode_vmid r1 = Some i⌝)∗ (∃ r2, R2 @@ V0 ->r r2) ∗ *)\n  (*              (rx_state_get i rxs ∗ (∃p_rx, RX@i := p_rx ∗ (∃ mem_rx, memory_page p_rx mem_rx))) ∗ *)\n  (*              (* rx pages for all other VMs *) *)\n  (*              rx_states_global (delete i rxs) ∗ ⌜is_total_gmap rxs⌝ ∗ *)\n  (*              (* if i yielding, we give following resources back to pvm *) *)\n  (*              VMProp V0 (vmprop_zero_pre Φ trans' rxs) (1/2)%Qp)%I. *)\n\n  (* Local Instance vmprop_unknown_pre_contractive : Contractive (vmprop_unknown_pre). *)\n  (* Proof. *)\n  (*   rewrite /vmprop_unknown_pre => n vmprop_unknown vmprop_unknown' Hvmprop_unknown trans /=. *)\n  (*   do 15 f_equiv. *)\n  (*   rewrite /VMProp /=. *)\n  (*   do 6 f_equiv. *)\n  (*   f_contractive. *)\n  (*   rewrite /vmprop_zero_pre. *)\n  (*   do 12 f_equiv. *)\n  (*   rewrite /VMProp. *)\n  (*   repeat f_equiv. *)\n  (*   (* apply Hvmprop_unknown. *) *)\n  (* Qed. *)\n\n  (* Definition vmprop_unknown := fixpoint (vmprop_unknown_pre). *)\n\n  (* Definition vmprop_zero := vmprop_zero_pre vmprop_unknown. *)\n\n  (* Lemma vmprop_unknown_eq trans : vmprop_unknown trans ⊣⊢ *)\n  (*   (∃ (trans' : gmap Word transaction) (rxs : gmap VMID (option(Word * VMID))), *)\n  (*              ⌜trans_rel_secondary i trans trans'⌝ ∗ *)\n  (*              (* transaction and pagetable entries *) *)\n  (*              transaction_hpool_global_transferred trans' ∗ *)\n  (*              transaction_pagetable_entries_transferred i trans' ∗ *)\n  (*              retrievable_transaction_transferred i trans' ∗ *)\n  (*              (* memory *) *)\n  (*              (∃ mem_trans, memory_pages (transferred_memory_pages trans') mem_trans) ∗ *)\n  (*              (∃ r0, R0 @@ V0 ->r r0 ∗ ⌜decode_hvc_func r0 = Some Run⌝) ∗ (∃ r1, R1 @@ V0 ->r r1 ∗ ⌜decode_vmid r1 = Some i⌝)∗ (∃ r2, R2 @@ V0 ->r r2) ∗ *)\n  (*              (rx_state_get i rxs ∗ (∃p_rx, RX@i := p_rx ∗ (∃ mem_rx, memory_page p_rx mem_rx))) ∗ *)\n  (*              (* rx pages for all other VMs *) *)\n  (*              rx_states_global (delete i rxs) ∗ ⌜is_total_gmap rxs⌝ ∗ *)\n  (*              (* if i yielding, we give following resources back to pvm *) *)\n  (*              VMProp V0 (vmprop_zero trans' rxs) (1/2)%Qp)%I. *)\n  (*   Proof. *)\n  (*     rewrite /vmprop_unknown. *)\n  (*     apply (fixpoint_unfold vmprop_unknown_pre). *)\n  (*   Qed. *)\n\n  Definition transferred_memory_slice (trans : gmap Addr transaction) (i: VMID) (j:VMID): iProp Σ:=\n    big_sepFM trans (λ kv, (kv.2.1.1.1.1 = i ∧ kv.2.1.1.1.2 = j) ∧ ¬(kv.2.2 = true ∧ kv.2.1.2 = Lending)) (λ _ tran, (∃ mem , memory_pages tran.1.1.2 mem)%I).\n\n  Definition retrievable_transaction_transferred_slice (trans : gmap Addr transaction) (i:VMID) (j: VMID) : iProp Σ :=\n    (big_sepFM trans (λ kv, kv.2.1.1.1.1 = i ∧ kv.2.1.1.1.2 = j) (λ k v, k -{1/2}>re v.2 )%I) ∗\n    (big_sepFM trans (λ kv, (kv.2.1.1.1.1 = i ∧ kv.2.1.1.1.2 = j) ∧ kv.2.2 = false) (λ k v, k -{1/4}>t v.1 ∗ k -{1/2}>re v.2)%I).\n\n  Definition transaction_pagetable_entries_transferred_slice (trans: gmap Addr transaction) (i: VMID) (j: VMID) : iProp Σ :=\n    big_sepFM trans (λ kv, (kv.2.1.1.1.1 = i ∧ kv.2.1.1.1.2 = j) ∧ kv.2.1.2 = Donation) (λ k v, k -{1/4}>t v.1 ∗ pgt_1_4 v.1.1.2 v.1.1.1.1 true)%I.\n\n  Definition slice_transfer_all :=\n    (λ trans i j, transaction_pagetable_entries_transferred_slice trans i j\n                ∗ retrievable_transaction_transferred_slice trans i j\n                ∗ transferred_memory_slice trans i j)%I.\n\n  Definition slice_rx_state (j : VMID) (os : option (Word * VMID)) : iProp Σ :=\n    (RX_state{1/2}@j := os) ∗ ∃ p_rx, RX@ j := p_rx ∗ (∃ mem_rx, memory_page p_rx mem_rx).\n\n  Definition interp_access p_tx p_rx ps_acc trans: iPropO Σ:=\n    (\n      (* exclusively owned pages are pages i has access to, but ain't in any transactions related to i. *)\n      (* [ps_oea], we exclude all pages involved in in-flight transactions,\n       NOTE: it has to be (currently_accessible_in_trans_memory_pages)*)\n      let ps_oea := ps_acc ∖ {[p_rx;p_tx]} ∖ (currently_accessible_in_trans_memory_pages trans) in\n      ⌜∀ k j trans, (k = i ∨ j = i) -> Φ_t trans k j ⊣⊢ slice_transfer_all trans k j⌝ ∗\n      ⌜∀ os, (match os with\n                 | None => True\n                 | _ => Φ_r i os i ⊣⊢ slice_rx_state i os\n                end)⌝ ∗\n      ⌜∀ os, (match os with\n                 | None => True\n                 | _ => Φ_r i os V0 ⊣⊢ slice_rx_state i os\n                end)⌝ ∗\n      ⌜∀ k os, (match os with\n          | None => True\n          | Some (_, j) => j = i -> Φ_r k os V0 ⊣⊢ slice_rx_state k os\n          end)⌝ ∗\n      ⌜∀ i j, Φ_r i None j ⊣⊢ True⌝ ∗\n      (* registers *)\n      (∃ regs, ⌜is_total_gmap regs⌝ ∗ [∗ map] r ↦ w ∈ regs, r @@ i ->r w) ∗\n      (* TX page and its memory *)\n      (tx_page i p_tx ∗ ∃ mem_tx, memory_page p_tx mem_tx) ∗\n      rx_page i p_rx ∗\n      (* access *)\n      i -@A> ps_acc ∗\n      ⌜{[p_tx;p_rx]} ⊆ ps_acc⌝ ∗ ⌜currently_accessible_in_trans_memory_pages trans ⊆ ps_acc ∖ {[p_tx;p_rx]}⌝ ∗\n      pagetable_entries_excl_owned i ps_oea ∗\n      transaction_pagetable_entries_owned i trans ∗\n      retrieved_transaction_owned i trans ∗\n      (∃ mem_oea, memory_pages (ps_oea ∪ (retrieved_lending_memory_pages trans)) mem_oea) ∗\n      VMProp i (vmprop_unknown trans) (1/2)%Qp\n    )%I.\n\nEnd logrel.\n", "meta": {"author": "logsem", "repo": "VMSL", "sha": "0a9b005b599a770e40c07abc9aa10a4ee9759315", "save_path": "github-repos/coq/logsem-VMSL", "path": "github-repos/coq/logsem-VMSL/VMSL-0a9b005b599a770e40c07abc9aa10a4ee9759315/theories/logrel/logrel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.2148637755828311}}
{"text": "Set Warnings \"-notation-overridden\".\n\nFrom Equations Require Import Equations.\nUnset Equations With Funext.\n\nRequire Import Category.Lib.\nRequire Import Category.Theory.\nRequire Import Category.Instance.Coq.\n\nRequire Import Embed.Theory.Functor.Void.\nRequire Import Embed.Theory.Functor.Refined.Def.\nRequire Import Embed.Theory.Functor.Refined.Iso.\n\nRequire Import Embed.Theory.Btree.\nRequire Import Embed.Theory.Btree.Functor.\nRequire Import Embed.Theory.Btree.Monad.\n\nRequire Import Embed.Theory.Btree.Refined.Iso.\nRequire Import Embed.Theory.Btree.Refined.Leaves.\nRequire Import Embed.Theory.Btree.Refined.Join.\n\nGeneralizable All Variables.\nSet Universe Polymorphism.\nSet Nested Proofs Allowed.\n\nLemma iso_refined_btree_void_ret {A} (x : @btree A)\n  (pf : iso_refined (void[btree_Functor] x) (bnil ())) :\n    { y | ret y = x}.\ndestruct x.\nexact (exist _ a eq_refl).\nunfold void in pf.\nsimpl in pf.\nunfold ret_btree in pf.\nrewrite fmap_btree_equation_2 in pf.\npose (not_iso_refined_bcons_bnil (fmap_btree (λ _ : A, ()) x1) (fmap_btree (λ _ : A, ()) x2)).\ndestruct (f pf).\nQed.\n\nLemma iso_refined_btree_void_ret_join {A} (x : @btree (@btree A))\n  (pf : iso_refined (void x) (ret tt)) :\n  ret (join x) = x.\ndestruct x.\n\nreflexivity.\n\nrewrite join_btree_equation_2.\ndestruct (iso_refined_btree_void_ret (bcons x1 x2) pf).\nsimpl in e.\nunfold ret_btree in e.\ndiscriminate.\nQed.\n\nLemma iso_refined_btree_void_join (x : @btree (@btree 1)) (y : @btree 1)\n  (pf : iso_refined (join[btree_Functor] x) y) (A : Type) :\n    @refined (Compose btree_Functor btree_Functor) x A ≅ refined y A.\npose (pf A).\nexact (iso_compose _ (piso_refined_btree x)).\nDefined.\n\n", "meta": {"author": "michaeljklein", "repo": "btree-lattice-experiments", "sha": "769670d3c98591a4ddb3854feea22eae554323f5", "save_path": "github-repos/coq/michaeljklein-btree-lattice-experiments", "path": "github-repos/coq/michaeljklein-btree-lattice-experiments/btree-lattice-experiments-769670d3c98591a4ddb3854feea22eae554323f5/Theory/Btree/Refined.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.21482608111446486}}
{"text": "Set Implicit Arguments.\n\nRequire Import AutoSep.\n\nDefinition NameNotInImports name imports := \n  fold_left\n    (fun (b : bool) (p : string * string * assert) =>\n       let '(m, _, _) := p in\n       (b || (if string_dec m name then true else false))%bool)\n    imports false = false.\n\nDefinition fst_2 A B C (x : A * B * C) := fst (fst x).\nNotation fst2 := (@fst_2 _ _ _).\n\nLemma NotIn_NameNotInImports : forall imps mn, ~ In mn (map fst2 imps) -> NameNotInImports mn imps.\n  clear.\n  unfold NameNotInImports.\n  induction imps; simpl; intros.\n  eauto.\n  destruct a; destruct p; simpl in *.\n  destruct (string_dec s mn).\n  contradict H.\n  eauto.\n  eapply IHimps.\n  intuition.\nQed.\n\nDefinition f mod_name (mOpt : option (LabelMap.t unit))\n           (p : string * assert *\n                (forall imports : LabelMap.t assert,\n                   importsGlobal imports -> cmd imports mod_name)) :=\n  let '(modl, _, _) := p in\n  match mOpt with\n    | Some m =>\n      let k := (modl, Local 0) in\n      if LabelMap.mem (elt:=unit) k m\n      then None\n      else Some (LabelMap.add k tt m)\n    | None => None\n  end.\n\nDefinition NoDupFuncNames' init mod_name funcs :=\n  match fold_left (@f mod_name) funcs (Some init)\n  with\n    | Some _ => True\n    | None => False\n  end.\n\nDefinition NoDupFuncNames := NoDupFuncNames' (LabelMap.empty unit).\n\nLemma NoDup_NoDupFuncNames' : \n  forall mod_name funcs init, \n    let names := map (fun f => fst (fst f)) funcs in \n    NoDup names -> \n    (forall x, List.In x names -> LabelMap.mem (elt := unit) (x, Local 0) init = false) ->\n    @NoDupFuncNames' init mod_name funcs.\nProof.\n  induction funcs; simpl; intuition.\n  compute; eauto.\n  unfold NoDupFuncNames' in *; simpl in *.\n  erewrite H0 by eauto.\n  eapply IHfuncs.\n  inversion H; subst; eauto.\n  intros.\n  erewrite LabelFacts.add_neq_b.\n  eapply H0.\n  eauto.\n  intuition.\n  injection H2; intros.\n  subst.\n  inversion H; subst.\n  contradiction.\nQed.\n\nLemma NoDup_NoDupFuncNames : forall mod_name funcs, NoDup (map (fun f => fst (fst f)) funcs) -> @NoDupFuncNames mod_name funcs.\n  intros.\n  eapply NoDup_NoDupFuncNames'.\n  eauto.\n  intros.\n  eauto.\nQed.\n\n", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/cito/NameVC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.21482608111446486}}
{"text": "\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\n\nRequire Import MirrorSolve.FirstOrder.\n\nRequire Import MetaCoq.Template.All.\nRequire Import MirrorSolve.Reflection.Core.\nSet Universe Polymorphism.\n\nRequire Import MirrorSolve.HLists.\n\nMetaCoq Quote Definition c_True := True.\nMetaCoq Quote Definition c_False := False.\nMetaCoq Quote Definition c_eq := @eq.\nMetaCoq Quote Definition c_not := @not.\nMetaCoq Quote Definition c_or := @or.\nMetaCoq Quote Definition c_and := @and.\n\nDefinition app_ty_info (f: term -> term) (x: predicate term) : predicate term := \n  {| puinst := x.(puinst); pparams := map f x.(pparams); pcontext := x.(pcontext); preturn := f x.(preturn) |}.\n\nDefinition app_branch (f: term -> term) (x: branch term) : branch term := \n  {| bcontext := x.(bcontext); bbody := f x.(bbody) |}.\n\nFixpoint dec_vars (d: nat) (t: term) : term :=\n  match t with\n  | tRel n => if (Nat.leb d n) then tRel (n - 1) else tRel n\n  | tCast from kind to => \n    tCast (dec_vars d from) kind (dec_vars d to)\n  | tProd na ty body => \n    let d' := \n      match na.(binder_name) with \n      | nAnon => d\n      | _ => S d\n      end in\n    tProd na (dec_vars d ty) (dec_vars d' body)\n  | tLambda na ty body => \n    tLambda na (dec_vars d ty) (dec_vars (S d) body)\n  | tLetIn na def def_ty body =>\n    tLetIn na (dec_vars d def) (dec_vars d def_ty) (dec_vars (S d) body)\n  | tApp f args => \n    tApp (dec_vars d f) (map (dec_vars d) args)\n  | tCase c_info type_info discr branches =>\n    tCase c_info (app_ty_info (dec_vars d) type_info) (dec_vars d discr) (List.map (app_branch (dec_vars d)) branches)\n  | tProj proj t0 => tProj proj (dec_vars d t0)\n  | _ => t\n  end. \n\nFixpoint reindex_vars (t: term) : term :=\n  match t with\n  | tCast from kind to => \n    tCast (reindex_vars from) kind (reindex_vars to)\n  | tProd na ty body => \n    let bod' := reindex_vars body in \n    let bod'' := \n      match na.(binder_name) with \n      | nAnon => dec_vars 0 bod'\n      | _ => bod'\n      end in\n    tProd na (reindex_vars ty) bod''\n  | tLambda na ty body => \n    tLambda na (reindex_vars ty) (reindex_vars body)\n  | tLetIn na def def_ty body =>\n    tLetIn na (reindex_vars def) (reindex_vars def_ty) (reindex_vars body)\n  | tApp f args => \n    tApp (reindex_vars f) (map reindex_vars args)\n  | tCase c_info type_info discr branches =>\n    tCase c_info (app_ty_info reindex_vars type_info) (reindex_vars discr) (List.map (app_branch reindex_vars) branches)\n  | tProj proj t0 => tProj proj (reindex_vars t0)\n  | _ => t\n  end.\n\nSection ExtractFM.\n  Variable (s: signature).\n  Variable (m: model s).\n\n  Variable (extract_t2tm : forall c, term -> list (option ({srt & (tm s c srt)})) -> option ({srt & (tm s c srt)})).\n  Variable (extract_t2rel : forall c, term -> list (option ({srt & (tm s c srt)})) -> option (fm s c)).\n  Variable (extract_t2srt : term -> option (sig_sorts s)).\n  \n  Variable (sort_eq_dec: EquivDec.EqDec (sig_sorts s) eq).\n\n  Equations extract_var (c: ctx s) (n: nat) : option ({srt & var s c srt}) by struct c :=\n    extract_var (Snoc _ _ ty) 0 := Some (ty; VHere _ _ ty);\n    extract_var (Snoc _ c _) (S n) :=\n      match extract_var c n with\n      | Some (ty; v') => Some (ty; VThere _ _ _ _ v')\n      | None => None\n      end;\n    extract_var SLNil _ := None.\n\n  Fixpoint extract_t2tm' (c: ctx s) (t: term) : option ({srt & tm s c srt}) :=  \n    match t with \n    | tRel n => \n      match extract_var c n with \n      | Some (ty; v) => Some (ty; TVar v)\n      | None => None\n      end\n    | tApp f es => extract_t2tm c t (map (extract_t2tm' c) es)\n    | _ => extract_t2tm c t []\n    end.\n\n  Obligation Tactic := intros.\n  Equations extract_t2fm (c: ctx s) (t: term) : option (fm _ c) by struct t := \n    extract_t2fm c t := \n      if eq_term t c_True then Some FTrue else \n      if eq_term t c_False then Some FFalse else\n      match t with\n      | tApp f es => \n        if eq_term f c_eq then \n          match es with \n          | _ :: tl :: tr :: _ => \n            match extract_t2tm' c tl, extract_t2tm' c tr with \n            | Some l, Some r => \n              let (sl, el) := l in \n              let (sr, er) := r in \n                match sort_eq_dec sl sr with \n                | left HEq => \n                  Some (FEq el (eq_rect_r _ er HEq))\n                | _ => None\n                end\n            | _, _ => None\n            end\n          | _ => None\n          end\n        else if eq_term f c_or then \n          match es with \n          | tl :: tr :: _ => \n            match extract_t2fm c tl, extract_t2fm c tr with \n            | Some l, Some r => Some (@FOr _ c l r)\n            | _, _ => None\n            end\n          | _ => None\n          end\n        else if eq_term f c_and then \n          match es with \n          | tl :: tr :: _ => \n            match extract_t2fm c tl, extract_t2fm c tr with \n            | Some l, Some r => Some (@FAnd _ c l r)\n            | _, _ => None\n            end\n          | _ => None\n          end\n        else if eq_term f c_not then \n          match es with \n          | x :: _ => \n            match extract_t2fm c x with \n            | Some x' => Some (FNeg _ x')\n            | None => None\n            end\n          | _ => None\n          end\n        else\n          extract_t2rel c t (map (extract_t2tm' c) es)\n      | tProd ba_name pre pst => \n        match ba_name.(binder_name) with \n        | nAnon => \n          match extract_t2fm c pre, extract_t2fm c pst with \n          | Some el, Some er => Some (FImpl el er)\n          | _, _ => None\n          end\n        | nNamed _ => \n          let srt := extract_t2srt pre in \n          match srt with \n          | Some srt => \n            let c' := Snoc _ c srt in\n            let inner := extract_t2fm c' pst in \n            match inner with \n            | Some fm => Some (FForall _ fm)\n            | None => None\n            end\n              \n          | None => None\n          end\n        end\n      | _ => \n        extract_t2rel c t []\n      end.\n\n  Definition extract_fm t := extract_t2fm (SLNil _) (reindex_vars t).\n\n  (* Some light tests *)\n  Variable (c: ctx s).\n\n  MetaCoq Quote Definition test_1 := (False -> True).\n  MetaCoq Quote Definition test_2 := (True = False -> False).\n  MetaCoq Quote Definition test_3 := (~ ~ False).\n  MetaCoq Quote Definition test_4 := (False /\\ True).\n  MetaCoq Quote Definition test_5 := (forall (x y: unit), x = y -> y = x).\n  MetaCoq Quote Definition test_6 := (forall (x: unit), True \\/ False \\/ ~ True).\n\n  (*\n  Eval vm_compute in extract_fm test_1.\n  Eval vm_compute in extract_fm test_2.\n  Eval vm_compute in extract_fm test_3.\n  Eval vm_compute in extract_fm test_4.\n  Eval vm_compute in extract_fm test_5.\n  Eval vm_compute in extract_fm test_6. *)\n  \nEnd ExtractFM.\n    \n\nSection DenoteFM.\n\n  Variable (s: signature).\n  Variable (m: model s).\n\n  Variable (sorts_eq_dec: EquivDec.EqDec (s.(sig_sorts)) eq).\n\n  Notation res_ty := (option ({ty & mod_sorts s m ty})).\n  Notation env_ty c := (valu s m c).\n\n  Variable (denote_tm : term -> list res_ty -> res_ty).\n  Variable (denote_rel: term -> list res_ty -> Prop).\n  Variable (reify_srt : term -> option (s.(sig_sorts))).\n\n  Fixpoint denote_var {c} (env: env_ty c) (n: nat) : res_ty :=\n    match env, n with\n    | VSnoc _ _ _ x, 0 => Some (_; x)\n    | VSnoc _ _ env' _, S n' => denote_var env' n'\n    | VEmp, _ => None\n    end.\n\n  Fixpoint denote_tm' {c} (env: env_ty c) (t: term) : res_ty :=  \n    match t with \n    | tRel n => \n      match denote_var env n with \n      | Some (ty; r) => Some (ty; r)\n      | None => None\n      end\n    | tApp f es => denote_tm t (map (denote_tm' env) es)\n    | _ => denote_tm t []\n    end.\n\n  Obligation Tactic := intros.\n  Equations denote_t2fm {c} (env: env_ty c) (t: term) : Prop by struct t := \n    denote_t2fm env t := \n      if eq_term t c_True then True else \n      if eq_term t c_False then False else\n      match t with\n      | tApp f es => \n        if eq_term f c_eq then \n          match es with \n          | _ :: tl :: tr :: _ => \n            match denote_tm' env tl, denote_tm' env tr with \n            | Some l, Some r => \n              let (tl, el) := l in \n              let (tr, er) := r in \n                match sorts_eq_dec tl tr with \n                | left HEq => \n                  (el = (eq_rect_r _ er HEq))\n                | _ => False\n                end\n            | _, _ => False\n            end\n          | _ => False\n          end\n        else if eq_term f c_or then \n          match es with \n          | tl :: tr :: _ => denote_t2fm env tl \\/ denote_t2fm env tr\n          | _ => False\n          end\n        else if eq_term f c_and then \n          match es with \n          | tl :: tr :: _ => denote_t2fm env tl /\\ denote_t2fm env tr\n          | _ => False\n          end\n        else if eq_term f c_not then \n          match es with \n          | x :: _ => ~ denote_t2fm env x\n          | _ => False\n          end\n        else \n          denote_rel t (map (denote_tm' env) es)\n      | tProd ba_name pre pst => \n        match ba_name.(binder_name) with \n        | nAnon => denote_t2fm env pre -> denote_t2fm env pst\n        | nNamed _ =>\n          match reify_srt pre with\n          | Some ty' => \n            forall x: (mod_sorts s m ty'), \n              denote_t2fm (VSnoc _ _ ty' c env x) pst \n          | None => False\n          end\n        end\n      | _ => denote_rel t []\n      end.\n\n  Definition denote_fm t := denote_t2fm (VEmp _ _) (reindex_vars t).\n\n  (* Eval vm_compute in denote_fm test_1.\n  Eval vm_compute in denote_fm test_2.\n  Eval vm_compute in denote_fm test_3.\n  Eval vm_compute in denote_fm test_4.\n  Eval vm_compute in denote_fm test_5.\n  Eval vm_compute in denote_fm test_6. *)\nEnd DenoteFM.\n", "meta": {"author": "jsarracino", "repo": "mirrorsolve", "sha": "74fc7790b21952d4f27ea70545b0038f298915b0", "save_path": "github-repos/coq/jsarracino-mirrorsolve", "path": "github-repos/coq/jsarracino-mirrorsolve/mirrorsolve-74fc7790b21952d4f27ea70545b0038f298915b0/src/theories/Reflection/FM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.21482608111446486}}
{"text": "Require Import AutoSep.\n\nSet Implicit Arguments. \n\nSection TopLevel.\n\n  Variable vars : list string.\n\n  Variable var : option string.\n\n  Definition is_state sp vs : HProp :=\n    locals vars vs 0 (sp ^+ $8).\n\n  Definition new_pre : assert := \n    x ~> ExX, Ex vs,\n    ![^[is_state x#Sp vs] * #0]x.\n\n  Require Import Semantics.\n\n  Definition runs_to x_pre x := \n    forall specs other vs,\n      interp specs (![is_state x_pre#Sp vs * other ] x_pre) ->\n      Regs x Sp = x_pre#Sp /\\\n      interp specs (![is_state (Regs x Sp) (upd_option vs var x_pre#Rv) * other ] (fst x_pre, x)).\n\n  Definition post (pre : assert) := \n    st ~> Ex st_pre, \n    pre (fst st, st_pre) /\\\n    [| runs_to (fst st, st_pre) (snd st) |].\n\n  Definition imply (pre new_pre: assert) := forall specs x, interp specs (pre x) -> interp specs (new_pre x).\n\n  Definition syn_req := \n    match var with\n      | Some x => List.In x vars\n      | None => True\n    end.\n\n  Definition verifCond pre := imply pre new_pre :: syn_req :: nil.\n\n  Variable imports : LabelMap.t assert.\n\n  Variable imports_global : importsGlobal imports.\n\n  Variable modName : string.\n\n  Definition Strline := Straightline_ imports modName.\n\n  Definition SaveRv lv := Strline (IL.Assign lv (RvLval (LvReg Rv)) :: nil).\n\n  Definition vars_start := 4 * 2.\n  Definition var_slot x := LvMem (Sp + (vars_start + variablePosition vars x)%nat)%loc.\n\n  Definition Skip := Straightline_ imports modName nil.\n\n  Definition body :=\n    match var with\n      | None => Skip\n      | Some x => SaveRv (var_slot x)\n    end.\n\n  Require Import Wrap.\n\n  Definition compile : cmd imports modName.\n    refine (Wrap imports imports_global modName body post verifCond _ _).\n\n    Lemma postOk : forall specs pre x,\n      interp specs (Postcondition (body pre) x)\n      -> imply pre new_pre\n      -> syn_req\n      -> exists x0, interp specs (pre (fst x, x0))\n        /\\ runs_to (fst x, x0) (snd x).\n      intros.\n      unfold syn_req, body, runs_to in *.\n      destruct var; simpl in *; post.\n\n      Focus 2.\n      Transparent evalInstrs.\n      simpl in H2.\n      Opaque evalInstrs.\n      injection H2; clear H2; intros; subst.\n      descend; eauto.\n\n      Opaque mult.\n\n      Lemma evalInstrs_write_var : forall sm x s,\n        evalInstrs sm x (Assign (var_slot s) Rv :: nil)\n        = evalInstrs sm x (Assign (LvMem (Imm ((Regs x Sp ^+ natToW vars_start) ^+ natToW (variablePosition vars s)))) Rv :: nil).\n        Transparent evalInstrs.\n        simpl.\n        intros.\n        replace (Regs x Sp ^+ natToW (vars_start + variablePosition vars s))\n          with (Regs x Sp ^+ natToW vars_start ^+ natToW (variablePosition vars s)); auto.\n        rewrite natToW_plus.\n        words.\n        Opaque evalInstrs.\n      Qed.\n\n      rewrite evalInstrs_write_var in *.\n      generalize H2; intro Hs.\n      apply H0 in Hs; clear H0; post.\n      clear_fancy.\n      unfold vars_start in H3.\n      change (4 * 2) with 8 in *.\n      descend.\n      eauto.\n      clear H.\n      unfold is_state in H0.\n      evaluate auto_ext.\n      destruct x; simpl in *.\n      intuition.\n      unfold is_state.\n      step auto_ext.\n    Qed.\n\n    abstract (unfold verifCond; wrap0;\n      match goal with\n        | [ H : interp _ _ |- _ ] =>\n          apply postOk in H; post; descend; eauto\n      end).\n\n    Lemma verifCondOk : forall pre,\n      imply pre new_pre\n      -> syn_req\n      -> vcs (VerifCond (body pre)).\n      unfold syn_req, body; intros.\n      destruct var; wrap0.\n      rewrite evalInstrs_write_var in *.\n      apply H in H1; clear H; post.\n      unfold is_state in H.\n      unfold vars_start in *.\n      change (4 * 2) with 8 in *.\n      clear_fancy.\n      evaluate auto_ext.\n      Transparent evalInstrs.\n      discriminate.\n      Opaque evalInstrs.\n    Qed.\n\n    abstract (unfold verifCond; wrap0; eauto using verifCondOk).\n Defined.\n\nEnd TopLevel.  \n", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/cito/SaveRet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21479363236859833}}
{"text": "Require Import Recdef.\nRequire Import VST.floyd.proofauto.\nLocal Open Scope logic.\nRequire Import List. Import ListNotations.\n\nRequire Import tweetnacl20140427.split_array_lemmas.\nRequire Import ZArith.\nLocal Open Scope Z.\nRequire Import tweetnacl20140427.tweetNaclBase.\nRequire Import tweetnacl20140427.Salsa20.\nRequire Import tweetnacl20140427.tweetnaclVerifiableC.\nRequire Import tweetnacl20140427.verif_salsa_base.\n\nRequire Import tweetnacl20140427.spec_salsa. Opaque Snuffle.Snuffle. Opaque fcore_result.\n\nDefinition X_content (x: SixteenByte * SixteenByte * (SixteenByte * SixteenByte))\n                     (i:Z) (l:list val) : Prop :=\n    l = upd_upto x (Z.to_nat i) (repeat Vundef 16).\n\nLemma XcontUpdate Nonce C Key1 Key2 i l\n      (I: 0 <= i < 4)\n      (L: X_content (Nonce, C, (Key1, Key2)) i l):\nX_content (Nonce, C, (Key1, Key2)) (i + 1)\n  (upd_Znth (11 + i)\n     (upd_Znth (6 + i)\n        (upd_Znth (1 + i)\n           (upd_Znth (5 * i) l\n              (Vint (littleendian (Select16Q C i))))\n           (Vint (littleendian (Select16Q Key1 i))))\n        (Vint (littleendian (Select16Q Nonce i))))\n     (Vint (littleendian (Select16Q Key2 i)))).\nProof. unfold X_content in *.\n  rewrite (Z.add_comm _ 1), Z2Nat.inj_add; try lia. simpl.\n  rewrite Z2Nat.id; try lia. subst l; reflexivity.\nQed.\n\n(*Issue : writing the lemma using the Delta := func_typcontext ...\n  @semax CompSepcs Espec Delta ...\n  leads to failure - but only 40 lines down, in the call to forward_call,\n  where check_Delta now fails since it introduces a Delta0.\n  I think we need to complement the line (\n    Delta := @abbreviate tycontext (mk_tycontext _ _ _ _ _) |- _ => ...\n  in checkDelta (checkDeltaOLD) with a second option,\n  Delta := func_tycontext ... =>.\n  Note that\n  1. rerunning abbreviate_semax at that place (before calling forward_call)\n     does not resolve the situation\n  2. In the master-branch, we actually could write the lemma using Delta :=,\n     so this is really an issue ith the new_compcert branch*)\n\nLemma f_core_loop1 (Espec : OracleKind) FR c k h nonce out w x y t\n(data : SixteenByte * SixteenByte * (SixteenByte * SixteenByte))\n(*(Delta := func_tycontext f_core SalsaVarSpecs SalsaFunSpecs) *):\n@semax CompSpecs Espec\n  (func_tycontext f_core SalsaVarSpecs SalsaFunSpecs nil) (*Delta*)\n  (PROP  ()\n   LOCAL  (lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n           lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; \n           temp _out out; temp _in nonce; temp _k k; \n           temp _c c; temp _h (Vint (Int.repr h)))\n   SEP  (FR; data_at_ Tsh (tarray tuint 16) x;\n         CoreInSEP data (nonce, c, k)))\n\n  (Sfor (Sset _i (Econst_int (Int.repr 0) tint))\n     (Ebinop Olt (Etempvar _i tint) (Econst_int (Int.repr 4) tint) tint)\n     (Ssequence\n        (Ssequence\n           (Scall (Some _t'1)\n              (Evar _ld32\n                 (Tfunction (Tcons (tptr tuchar) Tnil) tuint cc_default))\n              [Ebinop Oadd (Etempvar _c (tptr tuchar))\n                 (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                    (Etempvar _i tint) tint) (tptr tuchar)])\n           (Sassign\n              (Ederef\n                 (Ebinop Oadd (Evar _x (tarray tuint 16))\n                    (Ebinop Omul (Econst_int (Int.repr 5) tint)\n                       (Etempvar _i tint) tint) (tptr tuint)) tuint)\n              (Etempvar _t'1 tuint)))\n        (Ssequence\n           (Ssequence\n              (Scall (Some _t'2)\n                 (Evar _ld32\n                    (Tfunction (Tcons (tptr tuchar) Tnil) tuint cc_default))\n                 [Ebinop Oadd (Etempvar _k (tptr tuchar))\n                    (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                       (Etempvar _i tint) tint) (tptr tuchar)])\n              (Sassign\n                 (Ederef\n                    (Ebinop Oadd (Evar _x (tarray tuint 16))\n                       (Ebinop Oadd (Econst_int (Int.repr 1) tint)\n                          (Etempvar _i tint) tint) (tptr tuint)) tuint)\n                 (Etempvar _t'2 tuint)))\n           (Ssequence\n              (Ssequence\n                 (Scall (Some _t'3)\n                    (Evar _ld32\n                       (Tfunction (Tcons (tptr tuchar) Tnil) tuint cc_default))\n                    [Ebinop Oadd (Etempvar _in (tptr tuchar))\n                       (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                          (Etempvar _i tint) tint) (tptr tuchar)])\n                 (Sassign\n                    (Ederef\n                       (Ebinop Oadd (Evar _x (tarray tuint 16))\n                          (Ebinop Oadd (Econst_int (Int.repr 6) tint)\n                             (Etempvar _i tint) tint) (tptr tuint)) tuint)\n                    (Etempvar _t'3 tuint)))\n              (Ssequence\n                 (Scall (Some _t'4)\n                    (Evar _ld32\n                       (Tfunction (Tcons (tptr tuchar) Tnil) tuint cc_default))\n                    [Ebinop Oadd\n                       (Ebinop Oadd (Etempvar _k (tptr tuchar))\n                          (Econst_int (Int.repr 16) tint) (tptr tuchar))\n                       (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                          (Etempvar _i tint) tint) (tptr tuchar)])\n                 (Sassign\n                    (Ederef\n                       (Ebinop Oadd (Evar _x (tarray tuint 16))\n                          (Ebinop Oadd (Econst_int (Int.repr 11) tint)\n                             (Etempvar _i tint) tint) (tptr tuint)) tuint)\n                    (Etempvar _t'4 tuint))))))\n     (Sset _i\n        (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint) tint)))\n  (normal_ret_assert (\nPROP  ()\n   LOCAL  (temp _i (Vint (Int.repr 4)); lvar _t (tarray tuint 4) t;\n   lvar _y (tarray tuint 16) y; lvar _x (tarray tuint 16) x;\n   lvar _w (tarray tuint 16) w; temp _out out; temp _in nonce; temp _k k; temp _c c;\n   temp _h (Vint (Int.repr h)))\n   SEP  (FR;\n         EX  l : list val, !!X_content data 4 l &&\n                 data_at Tsh (tarray tuint 16) l x;\n         CoreInSEP data (nonce, c, k)))).\nProof. intros. abbreviate_semax.\nTime forward_for_simple_bound 4 (EX i:Z,\n   PROP  ()\n   LOCAL  (\n   lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n   lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; \n   temp _out out; temp _in nonce; temp _k k; temp _c c; temp _h (Vint (Int.repr h)))\n   SEP  (FR;\n         EX l:_, !!(X_content data i l) && data_at Tsh (tarray tuint 16) l x;\n         CoreInSEP data (nonce, c, k))). (*0.8 versus 2.1*)\n{ Exists (repeat Vundef 16). Time entailer!. (*1.3 versus 4.2*) }\n{ rename H into I.\n\n  destruct data as ((Nonce, C), Key). unfold CoreInSEP.\n  unfold SByte at 2. Intros X0; rename H into X0cont.\n\n  freeze [0;2;4] FR1.\n  freeze [0;1] FR2.\n\n  assert (C16:= SixteenByte2ValList_Zlength C).\n  remember (SplitSelect16Q C i) as FB; destruct FB as (Front, Back).\n  Time assert_PROP (isptr c /\\ field_compatible (Tarray tuchar 16 noattr) [] c) as FCc by entailer!. (*2.1 versus 3.7*)\n  destruct FCc as [Pc FC]; apply isptrD in Pc; destruct Pc as [cb [coff CP]]; rewrite CP in *.\n  destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB I) as [FL _].\n\n  rewrite (split3_data_at_Tarray_tuchar Tsh 16 (Zlength (QuadChunks2ValList Front))\n        (Zlength (QuadChunks2ValList Front) + Zlength (QuadChunks2ValList [Select16Q C i])));\n    repeat rewrite QuadChunk2ValList_ZLength;\n    try rewrite FL; try rewrite <- C1; try rewrite Zlength_cons, Zlength_nil; try solve[simpl; lia].\n  rewrite Zminus_plus. change (Z.succ 0) with 1. repeat rewrite Z.mul_1_r.\n  rewrite (Select_SplitSelect16Q C i _ _ HeqFB) at 2.\n  rewrite field_address0_offset by auto with field_compatible.\n  rewrite field_address0_offset by auto with field_compatible. simpl.\n  autorewrite with sublist.\n  rewrite sublist_app2; (*. (4 * Zlength Front) (4 + 4 * Zlength Front)); *)\n    repeat rewrite QuadChunk2ValList_ZLength; repeat rewrite FL.\n    2: lia.\n  rewrite Zminus_diag. rewrite Z.add_simpl_l. repeat rewrite Z.mul_1_l.\n  Intros.\n  freeze [1;3;0] FR3.\n  rewrite (sublist0_app1 4), (sublist_same 0 4); try rewrite <- QuadByteValList_ZLength; try lia.\n\n  (*Issue this is where the call fails if we use abbreviation Delta := ... in the statement of the lemma*)\n\n\n  Time forward_call (offset_val (4 * i) (Vptr cb coff), Select16Q C i). (*3.4 versus 15.4*)\n  (*{ goal automatically discharged versus 4.2 }*)\n\n  thaw FR3. \n  apply semax_pre with (P':=\n  (PROP  ()\n   LOCAL  ( temp _t'1 (Vint (littleendian (Select16Q C i)));\n   temp _i (Vint (Int.repr i));\n   lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n   lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; \n   temp _out out; temp _in nonce;temp _k k; \n   temp _c c; temp _h (Vint (Int.repr h)))\n   SEP\n   (FRZL FR2; data_at Tsh (Tarray tuchar 16 noattr) (SixteenByte2ValList C) c))).\n  { rewrite (Select_SplitSelect16Q C i _ _ HeqFB). unfold QByte.\n    rewrite (split3_data_at_Tarray_tuchar Tsh 16 (Zlength (QuadChunks2ValList Front)) (Zlength (QuadChunks2ValList Front)+4)); trivial;\n    repeat rewrite Zlength_app;\n    repeat rewrite QuadChunk2ValList_ZLength;\n(*    repeat rewrite FL; try rewrite BL; *)\n    try rewrite <- QuadByteValList_ZLength; try rewrite Z.mul_1_r; try lia.\n     2: destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB I) as [_ BL]; rewrite FL, BL; lia.\n    autorewrite with sublist.\n    rewrite CP in *.\n    rewrite field_address0_offset by auto with field_compatible.\n    rewrite field_address0_offset by auto with field_compatible.\n    Time entailer!. (*7.8*)\n    simpl.\n    rewrite app_nil_r.\n    apply sepcon_derives. autorewrite with sublist.\n      rewrite sublist_app2; repeat rewrite QuadChunk2ValList_ZLength; repeat rewrite FL; try lia.\n      repeat rewrite Zminus_diag. rewrite Z.add_simpl_l.\n      rewrite sublist_app1; try rewrite <- QuadByteValList_ZLength; try lia.\n      rewrite sublist_same; try rewrite <- QuadByteValList_ZLength; try lia.\n    rewrite Z.mul_1_l. apply derives_refl.\n    rewrite sublist_app2; repeat rewrite QuadChunk2ValList_ZLength; repeat rewrite FL; try lia.\n    repeat rewrite Z.add_simpl_l, app_nil_r in *.\n    autorewrite with norm. apply derives_refl.\n }\n\n  (*Store into x[...]*)\n  thaw FR2.\n  freeze [0;2] FR4.\n  Time forward. (*2.5 versus 5.8*)\n\n  destruct Key as [Key1 Key2].\n  thaw FR4.\n  Opaque ThirtyTwoByte.\n  thaw FR1.\n  freeze [0;1;3;4] FR5. Transparent ThirtyTwoByte.\n  Time assert_PROP (field_compatible (Tarray tuchar 32 noattr) [] k) as FCK32\n    by (unfold ThirtyTwoByte; entailer!). (*1.1 versus 5.1*)\n  erewrite ThirtyTwoByte_split16; trivial. unfold SByte at 1. Opaque ThirtyTwoByte.\n  simpl.\n(*  Time normalize. (*2.2 versus 3.8*) *)\n  Time assert_PROP (field_compatible (Tarray tuchar 16 noattr) [] k) as FCK16 by entailer!. (*1 versus 4.7*)\n  assert (K1_16:= SixteenByte2ValList_Zlength Key1).\n  remember (SplitSelect16Q Key1 i) as FB_K1. destruct FB_K1 as (Front_K1, Back_K1).\n(*  rewrite (Select_SplitSelect16Q Key1 i _ _ HeqFB_K1).*)\n  erewrite Select_Unselect_Tarray_at. (*; repeat rewrite <- K1_16; trivial.*)\n    2: symmetry; apply (Select_SplitSelect16Q Key1 i _ _ HeqFB_K1).\n    2: assumption.\n    2: rewrite <- (Select_SplitSelect16Q Key1 i _ _ HeqFB_K1), <- K1_16; trivial.\n    2: rewrite <- (Select_SplitSelect16Q Key1 i _ _ HeqFB_K1), <- K1_16; cbv; trivial.\n  unfold Select_at. simpl. rewrite app_nil_r. flatten_sepcon_in_SEP.\n  Intros.\n  freeze FR6 := (Unselect_at _ _ _ _ _) (SByte _ _) (FRZL FR5).\n  (*assert (FrontBackK1:= (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB_K1 I)) as [FLK BLK].*)\n  rewrite <- QuadByteValList_ZLength. (*rewrite Z.mul_1_l. *)\n  rewrite  QuadChunk2ValList_ZLength.\n  destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB_K1 I) as [FLK _]; rewrite FLK.\n\n  Time forward_call (offset_val (4 * i) k,\n                 Select16Q Key1 i). (*8.9 versus 19.5; both were 3-4 secs faster befor tick elimination etc*)\n\n  thaw  FR6.\n  apply semax_pre with (P':=\n  (PROP  ()\n   LOCAL  (temp _t'2 (Vint (littleendian (Select16Q Key1 i)));\n   temp _i (Vint (Int.repr i));\n   lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n   lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; temp _in nonce;\n   temp _out out; temp _c c; temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FRZL FR5; ThirtyTwoByte (Key1,Key2) k))).\n  { erewrite ThirtyTwoByte_split16; trivial.\n    repeat rewrite  <- QuadByteValList_ZLength; repeat rewrite QuadChunk2ValList_ZLength.\n    Time entailer!. (*4.4 versus 6.6*)\n    unfold SByte. rewrite (Select_SplitSelect16Q _ _ _ _ HeqFB_K1) in *.\n    erewrite Select_Unselect_Tarray_at with (data:= QuadChunks2ValList Front_K1 ++\n       QuadChunks2ValList [Select16Q Key1 (Zlength Front)(*i*)] ++ QuadChunks2ValList Back_K1); try reflexivity.\n    + unfold QByte, Select_at. simpl. repeat rewrite app_nil_r.\n      unfold Unselect_at.\n      rewrite  QuadChunk2ValList_ZLength.\n      rewrite <- QuadByteValList_ZLength, FLK. cancel.\n    + assumption.\n    + rewrite <- K1_16; assumption.\n    + rewrite <- K1_16. cbv; trivial.\n  }\n\n  (*Store into x[...]*)\n  thaw FR5.\n  freeze [0;1;2;4] FR6.\n  Time forward. (*2.8 versus 7.8*)\n\n  (*Load nonce*)\n  thaw FR6. freeze [0;2;3;4] FR7.\n  unfold SByte at 1; simpl.\n  assert (N16:= SixteenByte2ValList_Zlength Nonce).\n  remember (SplitSelect16Q Nonce i) as FB_N; destruct FB_N as (Front_N, BACK_N).\n    rewrite (Select_SplitSelect16Q _ i _ _ HeqFB_N) in *.\n  Time assert_PROP (field_compatible (Tarray tuchar 16 noattr) [] nonce) as FCN by entailer!. (*1.2 versus 6.8*)\n  erewrite Select_Unselect_Tarray_at with (d:=nonce); try reflexivity; try assumption.\n  2: solve [rewrite <- N16; trivial].\n  2: solve [rewrite <- N16; cbv; trivial].\n  Intros.\n  freeze FR8 := (Unselect_at _ _ _ _ _) (FRZL _).\n  unfold Select_at. simpl. rewrite app_nil_r.\n  rewrite <- QuadByteValList_ZLength. (*rewrite Z.mul_1_l.  simpl.*)\n  rewrite  QuadChunk2ValList_ZLength.\n  destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB_N I) as [FrontN _]; rewrite FrontN.\n  (*destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB_N I) as [FrontN BackN].*)\n\n  Time forward_call (offset_val (4 * i) nonce,\n                 Select16Q Nonce i). (*11.7 versus 21*)\n\n  thaw FR8.\n  apply semax_pre with (P':=\n  (PROP  ()\n   LOCAL  (\n   temp _t'3 (Vint (littleendian (Select16Q Nonce i)));\n   temp _i (Vint (Int.repr i));\n   lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n   lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; temp _out out; temp _in nonce;\n   temp _k k; temp _c c; temp _h (Vint (Int.repr h)))\n   SEP (FRZL FR7; SByte Nonce nonce))).\n  { Time entailer!. (*1.8 versus 9.5*)\n\n    (*Apart from the unfold QByte, the next 9 lines are exactly as above, inside the function call*)\n    unfold SByte. rewrite (Select_SplitSelect16Q _ _ _ _ HeqFB_N) in *.\n    erewrite Select_Unselect_Tarray_at; try reflexivity; try assumption.\n    + unfold QByte, Select_at. simpl. rewrite app_nil_r. cancel.\n      rewrite <- QuadByteValList_ZLength. (*rewrite Z.mul_1_l. simpl.*)\n      rewrite  QuadChunk2ValList_ZLength.\n      (*destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB_N I) as [FrontN _]; rewrite FrontN; cancel.*)\n      rewrite FrontN; cancel.\n    + rewrite <- N16; trivial.\n    + rewrite <- N16; cbv; trivial. }\n\n  (*Store into x[...]*)\n  thaw FR7. freeze [0;1;2;4] FR9.\n  Time forward. (*3.2 versus 15*)\n\n  (*Load Key2*)\n  thaw FR9. freeze [0;1;3;4] FR10.\n  rewrite ThirtyTwoByte_split16; trivial. simpl. Intros.\n  unfold SByte at 2.\n  assert (K2_16:= SixteenByte2ValList_Zlength Key2).\n  Time assert_PROP (isptr k/\\ field_compatible (Tarray tuchar 16 noattr) [] (offset_val 16 k))\n     as Pk_FCK2 by entailer!. (*1.4 versus 6.6*)\n  destruct Pk_FCK2 as [Pk FCK2]; apply isptrD in Pk; destruct Pk as [kb [koff Pk]]; rewrite Pk in *.\n  remember (SplitSelect16Q Key2 i) as FB_K2; destruct FB_K2 as (Front_K2, Back_K2).\n  rewrite (Select_SplitSelect16Q _ i _ _ HeqFB_K2) in *.\n  erewrite Select_Unselect_Tarray_at with (d:=offset_val 16 (Vptr kb koff)); try reflexivity; try assumption.\n  2: solve [rewrite <- K2_16; trivial]. 2: solve [rewrite <- K2_16; cbv; trivial].\n  Intros.\n  Time normalize. (*1.4 versus 6.6*)\n  unfold Select_at. simpl. rewrite app_nil_r.\n  repeat rewrite <- QuadByteValList_ZLength.\n  rewrite QuadChunk2ValList_ZLength.\n  freeze FR11 := (Unselect_at _ _ _ _ _) (SByte _ _) (FRZL FR10).\n  Time forward_call (Vptr kb\n           (Ptrofs.add (Ptrofs.add koff (Ptrofs.repr 16)) (Ptrofs.repr (4 * Zlength Front_K2))),\n                 Select16Q Key2 i). (*8.9 versus 20.5 SLOW*)\n  { destruct (Select_SplitSelect16Q_Zlength _ _ _ _ HeqFB_K2 I) as [FK2 _]; rewrite FK2.\n     apply prop_right; simpl. unfold Ptrofs.of_ints; simpl. autorewrite with norm. auto. }\n\n  thaw FR11.\n  apply semax_pre with (P':=\n  (PROP  ()\n   LOCAL  ( \n   temp _t'4 (Vint (littleendian (Select16Q Key2 i)));\n   temp _i (Vint (Int.repr i));\n   lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n   lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; temp _in nonce;\n   temp _out out; temp _c c; temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FRZL FR10; ThirtyTwoByte (Key1,Key2) k))).\n  { rewrite Pk in *. erewrite ThirtyTwoByte_split16 by assumption.\n    Time entailer!. (*4.6 versus 7.4*) \n    simpl. cancel.\n\n    (*Apart from the unfold QByte, the next 9 lines are exactly as above, inside the function call*)\n    unfold SByte. rewrite (Select_SplitSelect16Q _ _ _ _ HeqFB_K2) in *.\n    erewrite Select_Unselect_Tarray_at; try reflexivity; try assumption.\n    + unfold QByte, Select_at. simpl. repeat rewrite app_nil_r. cancel.\n      rewrite <- QuadByteValList_ZLength. (*rewrite Z.mul_1_l. simpl.*)\n      rewrite  QuadChunk2ValList_ZLength. rewrite Ptrofs.add_assoc. rewrite ptrofs_add_repr. cancel.\n    + rewrite <- K2_16; assumption.\n    + rewrite <- K2_16; cbv; trivial. }\n\n  (*Store into x[...]*)\n  thaw FR10. freeze [0;1;2;4] FR11.\n  Time forward. (*4.3 versus 14.7*) clear FL.\n\n  Time entailer!. (*4.9 versus 16.1*)  remember (Zlength Front_K1) as i.\n  Exists (upd_Znth (11 + i)\n     (upd_Znth (6 + i)\n        (upd_Znth (1 + i)\n           (upd_Znth (5 * i) X0\n              (Vint (littleendian (Select16Q C i))))\n           (Vint (littleendian (Select16Q Key1 i))))\n        (Vint (littleendian (Select16Q Nonce i))))\n     (Vint (littleendian (Select16Q Key2 i)))).\n  Time entailer!. (*2 versus 2.8  - penalty*)\n    clear - X0cont I. apply XcontUpdate; trivial.\n\n  thaw FR11. simpl. Time cancel. (*0.3*)\n }\napply andp_left2; apply derives_refl.\nTime Qed. (*VST 20.: 5.5s*) (* 19.046 secs (17.109u,0.015s) (successful)*)\n\nLemma XX data l: X_content data 4 l ->\n  l = match data with ((Nonce, C), (Key1, Key2)) =>\n          match Nonce with (N1, N2, N3, N4) =>\n          match C with (C1, C2, C3, C4) =>\n          match Key1 with (K1, K2, K3, K4) =>\n          match Key2 with (L1, L2, L3, L4) =>\n      map Vint (map littleendian [C1; K1; K2; K3;\n                                  K4; C2; N1; N2;\n                                  N3; N4; C3; L1;\n                                  L2; L3; L4; C4])\n      end end end end end.\nProof.\nintros. red in H. subst l.\napply upd_upto_char. reflexivity.\nQed.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/tweetnacl20140427/verif_fcore_loop1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.3242354055108441, "lm_q1q2_score": 0.21461882774334998}}
{"text": "Require Import Setoid PArith.\nFrom hahn Require Import Hahn.\nRequire Import PromisingLib.\nFrom Promising2 Require Import TView View Time Event Cell Thread Memory Configuration Local.\n\nFrom imm Require Import Events.\nFrom imm Require Import Execution.\nFrom imm Require Import Execution_eco.\nFrom imm Require Import imm_s_hb.\nFrom imm Require Import imm_s.\nFrom imm Require Import imm_bob imm_s_ppo.\nFrom imm Require Import CombRelations.\nFrom imm Require Import CombRelationsMore.\nFrom imm Require Import AuxDef.\n\nFrom imm Require Import TraversalConfig.\nFrom imm Require Import ViewRelHelpers.\nRequire Import SimulationRel.\nRequire Import SimState.\nRequire Import MemoryAux.\nRequire Import MaxValue.\nRequire Import ViewRel.\nRequire Import Event_imm_promise.\nRequire Import ExtTraversalConfig.\nRequire Import ExtTraversal.\nRequire Import ExtTraversalProperties.\nRequire Import FtoCoherent.\nRequire Import SimulationRelProperties.\nRequire Import IntervalHelper.\nRequire Import ExistsIssueNextInterval.\n\nSet Implicit Arguments.\n\nSection IssueStepHelper.\n\nVariable G : execution.\nVariable WF : Wf G.\nVariable sc : relation actid.\n\nNotation \"'acts'\" := G.(acts).\nNotation \"'co'\" := G.(co).\nNotation \"'sw'\" := G.(sw).\nNotation \"'hb'\" := G.(hb).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rf'\" := G.(rf).\nNotation \"'rfi'\" := G.(rfi).\nNotation \"'rfe'\" := G.(rfe).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'lab'\" := G.(lab).\nNotation \"'msg_rel'\" := (msg_rel G sc).\nNotation \"'urr'\" := (urr G sc).\nNotation \"'release'\" := G.(release).\n\nNotation \"'E'\" := G.(acts_set).\nNotation \"'R'\" := (fun a => is_true (is_r lab a)).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\nNotation \"'Loc_' l\" := (fun x => loc lab x = Some l) (at level 1).\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'W_'\" := (fun l => W ∩₁ Loc_ l).\n(* Notation \"'RW'\" := (fun x => R x \\/ W x). *)\nNotation \"'FR'\" := (fun x => F x \\/ R x).\nNotation \"'FW'\" := (fun x => F x \\/ W x).\n\nNotation \"'W_ex'\" := (W_ex G).\nNotation \"'W_ex_acq'\" := (W_ex ∩₁ (fun a => is_true (is_xacq lab a))).\n\nNotation \"'Pln'\" := (fun a => is_true (is_only_pln lab a)).\nNotation \"'Rlx'\" := (is_rlx lab).\nNotation \"'Rel'\" := (is_rel lab).\nNotation \"'Acq'\" := (is_acq lab).\nNotation \"'Acqrel'\" := (is_acqrel lab).\nNotation \"'Sc'\" := (fun a => is_true (is_sc lab a)).\n\nVariable IMMCON : imm_consistent G sc.\n\nVariable T : trav_config.\nVariable S : actid -> Prop.\nVariable ETCCOH : etc_coherent G sc (mkETC T S).\n\nVariable RELCOV : W ∩₁ Rel ∩₁ issued T ⊆₁ covered T.\n\nVariable f_to f_from : actid -> Time.t.\nVariable FCOH : f_to_coherent G S f_to f_from.\n\nVariable PC : Configuration.t.\nHypothesis THREAD : forall e (ACT : E e) (NINIT : ~ is_init e),\n    exists langst, IdentMap.find (tid e) PC.(Configuration.threads) = Some langst.\n\nVariable smode : sim_mode.\nHypothesis SC_REQ :\n  smode = sim_normal -> \n  forall (l : Loc.t),\n    max_value f_to (S_tm G l (covered T)) (LocFun.find l PC.(Configuration.sc)).\n\nVariable thread : thread_id.\nVariable local : Local.t.\nHypothesis SIM_PROM     : sim_prom     G sc T   f_to f_from thread local.(Local.promises).\nHypothesis SIM_RES_PROM : sim_res_prom G    T S f_to f_from thread local.(Local.promises).\n\nHypothesis CLOSED_SC : Memory.closed_timemap PC.(Configuration.sc) PC.(Configuration.memory).\n\nHypothesis PROM_DISJOINT :\n  forall thread' langst' local'\n         (TNEQ : thread <> thread')\n         (TID' : IdentMap.find thread' PC.(Configuration.threads) =\n                 Some (langst', local')),\n  forall loc to,\n    Memory.get loc to local .(Local.promises) = None \\/\n    Memory.get loc to local'.(Local.promises) = None.\n\nHypothesis PROM_IN_MEM :\n  forall thread' langst local\n         (TID : IdentMap.find thread' PC.(Configuration.threads) =\n                Some (langst, local)),\n    Memory.le local.(Local.promises) PC.(Configuration.memory).\n\nHypothesis INHAB      : Memory.inhabited (Configuration.memory PC).\nHypothesis CLOSED_MEM : Memory.closed (Configuration.memory PC).\nHypothesis PLN_RLX_EQ : pln_rlx_eq local.(Local.tview).\nHypothesis MEM_CLOSE : memory_close local.(Local.tview) PC.(Configuration.memory).\n\nHypothesis RESERVED_TIME:\n  reserved_time G T S f_to f_from smode PC.(Configuration.memory).\n\nHypothesis SIM_RES_MEM :\n  sim_res_mem G T S f_to f_from thread local (Configuration.memory PC).\n\nHypothesis SIM_MEM : sim_mem G sc T f_to f_from thread local PC.(Configuration.memory).\nHypothesis SIM_TVIEW : sim_tview G sc (covered T) f_to local.(Local.tview) thread.\nHypothesis RMWREX : dom_rel rmw ⊆₁ R_ex lab.\n\nLemma issue_step_helper_next w wnext valw locw ordw langst\n      (TID : IdentMap.find (tid w) PC.(Configuration.threads) = Some (langst, local))\n      (NWEX : ~ W_ex w)\n      (NISSB : ~ issued T w)\n      (ISSUABLE : issuable G sc T w)\n      (NEXT : dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) wnext)\n      (LOC : loc lab w = Some locw)\n      (VAL : val lab w = Some valw)\n      (ORD : mod lab w = ordw)\n      (WTID : thread = tid w) :\n  let promises := local.(Local.promises) in\n  let memory   := PC.(Configuration.memory) in\n  let sc_view  := PC.(Configuration.sc) in\n  let covered' := if Rel w then covered T ∪₁ eq w else covered T in\n  let T'       := mkTC covered' (issued T ∪₁ eq w) in\n  let S'       := S ∪₁ eq w ∪₁ dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) in\n  exists p_rel,\n    rfrmw_prev_rel G sc T f_to f_from PC.(Configuration.memory) w locw p_rel /\\\n    (⟪ FOR_ISSUE :\n         exists f_to' f_from',\n           let rel'' :=\n               if is_rel lab w\n               then (TView.cur (Local.tview local))\n               else (TView.rel (Local.tview local) locw)\n           in\n           let rel' := (View.join (View.join rel'' p_rel.(View.unwrap))\n                                  (View.singleton_ur locw (f_to' w))) in\n           ⟪ RELWFEQ : View.pln rel' = View.rlx rel' ⟫ /\\\n           ⟪ REL_VIEW_LT : Time.lt (View.rlx rel'' locw) (f_to' w) ⟫ /\\\n           ⟪ REL_VIEW_LE : Time.le (View.rlx rel'  locw) (f_to' w) ⟫ /\\\n\n           ⟪ REQ_TO : forall e (SE : S e), f_to' e = f_to e ⟫ /\\\n           ⟪ REQ_FROM : forall e (SE : S e), f_from' e = f_from e ⟫ /\\\n           ⟪ ISSEQ_TO   : forall e (ISS: issued T e), f_to' e = f_to e ⟫ /\\\n           ⟪ ISSEQ_FROM : forall e (ISS: issued T e), f_from' e = f_from e ⟫ /\\\n           ⟪ FTOWNBOT     : f_to' w <> Time.bot ⟫ /\\\n           ⟪ FTOWNEXTNBOT : f_to' wnext <> Time.bot ⟫ /\\\n           << FTONEXTNEQ  : f_to' w <> f_to' wnext >> /\\\n\n           exists promises_add memory_add promises_rel promises_add2 memory',\n             ⟪ PADD :\n                 Memory.add local.(Local.promises) locw (f_from' w) (f_to' w)\n                            (Message.full valw (Some rel')) promises_add ⟫ /\\\n             ⟪ MADD :\n                 Memory.add memory locw (f_from' w) (f_to' w)\n                            (Message.full valw (Some rel')) memory_add ⟫ /\\\n\n             ⟪ PEQ :\n                 if Rel w\n                 then Memory.remove promises_add locw (f_from' w) (f_to' w)\n                                    (Message.full valw (Some rel')) promises_rel\n                 else promises_rel = promises_add ⟫ /\\\n\n             ⟪ PADD2 :\n                 Memory.add promises_rel locw (f_from' wnext) (f_to' wnext)\n                            Message.reserve promises_add2 ⟫ /\\\n             ⟪ MADD2 :\n                 Memory.add memory_add locw (f_from' wnext) (f_to' wnext)\n                            Message.reserve memory' ⟫ /\\\n\n\n             ⟪ INHAB : Memory.inhabited memory' ⟫ /\\\n             ⟪ RELMCLOS : Memory.closed_timemap (View.rlx rel') memory_add ⟫ /\\\n             ⟪ RELVCLOS : Memory.closed_view rel' memory_add ⟫ /\\\n\n             ⟪ FCOH : f_to_coherent G S' f_to' f_from' ⟫ /\\\n\n             ⟪ HELPER :\n                 sim_mem_helper\n                   G sc f_to' w (f_from' w) valw\n                   (View.join (View.join (if is_rel lab w\n                                          then (TView.cur (Local.tview local))\n                                          else (TView.rel (Local.tview local) locw))\n                                         p_rel.(View.unwrap))\n                              (View.singleton_ur locw (f_to' w))) ⟫ /\\\n\n             ⟪ RESERVED_TIME :\n                 reserved_time G T' S' f_to' f_from' smode memory' ⟫ /\\\n\n             ⟪ MEM_PROMISE :\n                 Memory.promise (Local.promises local) memory locw (f_from' w) (f_to' w)\n                                (Message.full valw (Some rel'))\n                                promises_add memory_add Memory.op_kind_add ⟫ /\\\n\n             ⟪ MEM_PROMISE2 :\n                 Memory.promise promises_rel memory_add locw (f_from' wnext) (f_to' wnext)\n                                Message.reserve\n                                promises_add2 memory' Memory.op_kind_add ⟫ /\\\n\n             ⟪ OLD_PROM_IN_NEW_PROM : Memory.le (Local.promises local) promises_add2 ⟫ /\\\n             ⟪ NEW_PROM_IN_MEM      : Memory.le promises_add2 memory' ⟫ /\\\n\n             let tview' := if is_rel lab w\n                           then TView.write_tview\n                                  (Local.tview local) sc_view locw\n                                  (f_to' w) (Event_imm_promise.wmod ordw)\n                           else (Local.tview local) in\n             let local' := Local.mk tview' promises_add2 in\n             let threads' :=\n                 IdentMap.add (tid w)\n                              (langst, local')\n                              (Configuration.threads PC) in\n\n             ⟪ THREAD : forall e (ACT : E e) (NINIT : ~ is_init e),\n                 exists langst, IdentMap.find (tid e) threads' = Some langst ⟫ /\\\n\n             ⟪ SC_REQ : smode = sim_normal -> \n                        forall (l : Loc.t),\n                          max_value\n                            f_to' (S_tm G l covered') (LocFun.find l sc_view) ⟫ /\\\n             ⟪ CLOSED_SC : Memory.closed_timemap sc_view memory' ⟫ /\\\n\n             ⟪ PROM_IN_MEM :\n                 forall thread' langst local\n                        (TID : IdentMap.find thread' threads' = Some (langst, local)),\n                   Memory.le (Local.promises local) memory' ⟫ /\\\n\n             ⟪ SIM_PROM     : sim_prom G sc T' f_to' f_from' (tid w) promises_add2  ⟫ /\\\n             ⟪ SIM_RES_PROM : sim_res_prom G T' S' f_to' f_from' (tid w) promises_add2  ⟫ /\\\n\n             ⟪ PROM_DISJOINT :\n                 forall thread' langst' local'\n                        (TNEQ : tid w <> thread')\n                        (TID' : IdentMap.find thread' threads' =\n                                Some (langst', local')),\n                 forall loc to,\n                   Memory.get loc to promises_add2 = None \\/\n                   Memory.get loc to (Local.promises local') = None ⟫ /\\\n\n             ⟪ SIM_MEM     : sim_mem G sc T' f_to' f_from' (tid w) local' memory' ⟫ /\\\n             ⟪ SIM_RES_MEM : sim_res_mem G T' S' f_to' f_from' (tid w) local' memory' ⟫ /\\\n             ⟪ NOWLOC : Rel w -> Memory.nonsynch_loc locw (Local.promises local') ⟫\n     ⟫).\nProof using All.\n  assert (tc_coherent G sc T) as TCCOH by apply ETCCOH.\n  assert (complete G) as COMPL by apply IMMCON.\n  assert (sc_per_loc G) as SPL by (apply coherence_sc_per_loc; apply IMMCON).\n \n  assert (NSW : ~ S w).\n  { intros HH. apply NWEX. apply ETCCOH. by split. }\n\n  assert (S ⊆₁ E ∩₁ W) as SEW.\n  { apply set_subset_inter_r. split; [by apply ETCCOH|].\n    apply (reservedW WF ETCCOH). }\n  assert (E w /\\ W w) as [EW WW] by (by apply ISSUABLE).\n  assert (~ covered T w) as NCOVB.\n  { intros AA. apply NISSB. eapply w_covered_issued; eauto. by split. }\n  assert (~ is_init w) as WNINIT.\n  { intros HH. apply NCOVB. eapply init_covered; eauto. by split. }\n\n  forward (eapply dom_sb_S_rfrmw_single_props with (w:=w) (wnext:=wnext)); eauto.\n  intros HH. desc.\n  assert (w <> wnext) as WNEXTNEQ.\n  { intros HH. subst. eapply WF.(co_irr); eauto. }\n\n  subst.\n  edestruct exists_time_interval_for_issue_next as [p_rel [PREL HH]]; eauto.\n  red in HH. desc. exists p_rel. splits; eauto.\n  exists f_to', f_from'. splits; eauto.\n  exists promises_add, memory_add, promises_rel.\n  exists promises', memory'.\n\n  assert (Time.lt (f_to' w) (f_to' wnext)) as FLT.\n  { eapply f_to_co_mon; eauto; basic_solver. }\n\n  set (rel'' :=\n        if is_rel lab w\n        then (TView.cur (Local.tview local))\n        else (TView.rel (Local.tview local) locw)).\n  set (rel' := (View.join (View.join rel'' p_rel.(View.unwrap))\n                          (View.singleton_ur locw (f_to' w)))).\n\n  set (S':=S ∪₁ eq w ∪₁ dom_sb_S_rfrmw G (mkETC T S) rfi (eq w)).\n  assert (S ⊆₁ S') as SINS by (unfold S'; eauto with hahn).\n  assert (S' ⊆₁ E ∩₁ W) as SEW'.\n  { subst S'. rewrite SEW at 1. unionL; eauto with hahn.\n    { unfolder. ins. desf. }\n    intros x HH.\n    assert (x = wnext); subst.\n    2: by split.\n    eapply dom_sb_S_rfrmwf; eauto. }\n  assert (S' w) as SW'.\n  { red. basic_solver. }\n  assert (S' wnext) as SWNEXT'.\n  { red. basic_solver. }\n\n  assert (Memory.le promises_add memory_add) as PP'.\n  { eapply memory_le_add2; eauto. }\n  assert (Memory.le promises' memory') as PP.\n  { eapply memory_le_add2. 2,3: by eauto.\n    destruct (Rel w); subst; auto.\n    etransitivity; [|by apply PP'].\n    eapply memory_remove_le; eauto. }\n\n  assert (forall thread' langst' local' (TNEQ : tid w <> thread')\n                 (TID' : IdentMap.find thread' (Configuration.threads PC) =\n                         Some (langst', local')),\n             Memory.get locw (f_to' w) (Local.promises local') = None) as NINTER.\n  (* TODO: Move to IssueInterval.v? *)\n  { ins.\n    destruct (Memory.get locw (f_to' w) (Local.promises local')) eqn:HH; auto.\n    exfalso. destruct p as [from].\n    eapply PROM_IN_MEM in HH; eauto.\n    set (AA := HH). apply Memory.get_ts in AA.\n    destruct AA as [|AA]; desc; eauto.\n    apply DISJOINT in HH.\n    apply HH with (x:=f_to' w); constructor; simpls; try reflexivity.\n    apply FCOH0; auto. }\n\n  assert (forall thread' langst' local' (TNEQ : tid w <> thread')\n                 (TID' : IdentMap.find thread' (Configuration.threads PC) =\n                         Some (langst', local')),\n             Memory.get locw (f_to' wnext) (Local.promises local') = None) as NINTER'.\n  (* TODO: Move to IssueInterval.v? *)\n  { ins.\n    destruct (Memory.get locw (f_to' wnext) (Local.promises local')) eqn:HH; auto.\n    exfalso. destruct p as [from].\n    eapply PROM_IN_MEM in HH; eauto.\n    set (AA := HH). apply Memory.get_ts in AA.\n    destruct AA as [|AA]; desc; eauto.\n    apply DISJOINT' in HH.\n    apply HH with (x:=f_to' wnext); constructor; simpls; try reflexivity.\n    apply FCOH0; auto. }\n\n  assert (forall tmap (MCLOS : Memory.closed_timemap tmap PC.(Configuration.memory)),\n             Memory.closed_timemap tmap memory') as MADDCLOS.\n  { ins. repeat (eapply Memory.add_closed_timemap; eauto). }\n  \n  (* assert (Memory.le promises'' promises') as LEPADD. *)\n  (* { destruct (Rel w) eqn:RELB; subst; [|reflexivity]. *)\n  (*   eapply memory_remove_le; eauto. } *)\n\n  (* assert (Memory.le promises'' memory') as NEW_PROM_IN_MEM. *)\n  (* { etransitivity; eauto. } *)\n\n  (* assert (forall l to from msg  *)\n  (*                (NEQ : l <> locw \\/ to <> f_to w), *)\n  (*            Memory.get l to promises_cancel = Some (from, msg) <-> *)\n  (*            Memory.get l to local.(Local.promises) = Some (from, msg)) *)\n  (*   as NOTNEWC. *)\n  (* { ins. erewrite Memory.remove_o; eauto. *)\n  (*   rewrite loc_ts_eq_dec_neq; auto. } *)\n\n  assert (forall l to from msg\n                 (NEQ  : l <> locw \\/ to <> f_to' w)\n                 (NEQ' : l <> locw \\/ to <> f_to' wnext),\n             Memory.get l to memory' = Some (from, msg) <->\n             Memory.get l to PC.(Configuration.memory) = Some (from, msg))\n    as NOTNEWM.\n  { ins. repeat (erewrite Memory.add_o; eauto; rewrite loc_ts_eq_dec_neq; auto). }\n\n  assert (forall l to from msg\n                 (NEQ  : l <> locw \\/ to <> f_to' w)\n                 (NEQ' : l <> locw \\/ to <> f_to' wnext),\n             Memory.get l to promises_rel = Some (from, msg) <->\n             Memory.get l to local.(Local.promises) = Some (from, msg))\n    as NOTNEWR.\n  { ins.\n    destruct (Rel w); subst.\n    erewrite Memory.remove_o; eauto; rewrite loc_ts_eq_dec_neq; auto.\n    all: erewrite Memory.add_o; eauto; rewrite loc_ts_eq_dec_neq; auto. }\n\n  assert (forall l to from msg\n                 (NEQ  : l <> locw \\/ to <> f_to' w)\n                 (NEQ' : l <> locw \\/ to <> f_to' wnext),\n             Memory.get l to promises' = Some (from, msg) <->\n             Memory.get l to local.(Local.promises) = Some (from, msg))\n    as NOTNEWA.\n  { ins.\n    erewrite Memory.add_o; eauto; rewrite loc_ts_eq_dec_neq; auto. }\n\n  assert (~ Rel w ->\n          Memory.get locw (f_to' w) promises' =\n          Some (f_from' w, Message.full valw (Some rel')))\n    as INP''.\n  { ins. destruct (Rel w); subst; [by desf|].\n    erewrite Memory.add_o; eauto. rewrite loc_ts_eq_dec_neq; eauto.\n    erewrite Memory.add_o; eauto. by rewrite loc_ts_eq_dec_eq. }\n\n  assert (RESGET' :\n            Memory.get locw (f_to' wnext) promises' =\n            Some (f_from' wnext, Message.reserve)).\n  { by erewrite Memory.add_o; eauto; rewrite loc_ts_eq_dec_eq. }\n\n  (* assert (RESGET : *)\n  (*           Memory.get locw (f_to' wnext) promises'' = *)\n  (*           Some (f_from' wnext, Message.reserve)). *)\n  (* { destruct (Rel w) eqn:RELB; subst. *)\n  (*   erewrite Memory.remove_o; eauto. rewrite loc_ts_eq_dec_neq; eauto. *)\n  (*   all: by erewrite Memory.add_o; eauto; rewrite loc_ts_eq_dec_eq. } *)\n\n  assert (PROMGET :\n            Memory.get locw (f_to' w) promises' = None \\/\n            exists rel,\n              Memory.get locw (f_to' w) promises' =\n              Some (f_from' w, Message.full valw rel)).\n  { erewrite Memory.add_o; eauto. rewrite loc_ts_eq_dec_neq; eauto.\n    destruct (Rel w) eqn:RELB; subst.\n    { erewrite Memory.remove_o; eauto. rewrite loc_ts_eq_dec_eq; eauto. }\n    erewrite Memory.add_o; eauto. rewrite loc_ts_eq_dec_eq; eauto. }\n\n  assert (Memory.le (Local.promises local) promises_add) as OLD_PROM_IN_PROM_ADD.\n  { eapply memory_add_le; eauto. }\n\n  assert (Memory.le (Local.promises local) promises') as OLD_PROM_IN_PROM_REL.\n  { etransitivity; [|by eapply memory_add_le; eauto].\n    destruct (Rel w); subst; auto.\n    red. ins. erewrite Memory.remove_o; eauto.\n    destruct (loc_ts_eq_dec (loc, to) (locw, f_to' w)) as [|NN].\n    2: { rewrite loc_ts_eq_dec_neq; auto. }\n    desc. simpls. subst. exfalso.\n    apply Memory.add_get0 in PADD.\n    clear -PADD LHS. desc. rewrite PADD in LHS. inv LHS. }\n\n  splits; eauto.\n  1,2: econstructor; eauto; ins.\n  { inv MSG. clear MSG.\n    set (AA:=GET). apply DISJOINT' in AA.\n    rewrite FWWNEXTEQ in AA.\n    set (BB:=GET). apply Memory.get_ts in BB.\n    destruct BB as [|BB]; desc; eauto.\n    destruct (TimeFacts.le_lt_dec (f_to' wnext) to').\n    { eapply AA with (x:=f_to' wnext); constructor; simpls; auto. reflexivity. }\n    eapply AA with (x:=to'); constructor; simpls; auto; try reflexivity.\n    apply Time.le_lteq. eauto. }\n  { rewrite FWWNEXTEQ.\n    erewrite Memory.add_o; eauto. rewrite loc_ts_eq_dec_eq. eauto. }\n  { ins.\n    destruct (Ident.eq_dec (tid e) (tid w)) as [EQ|NEQ].\n    { rewrite EQ. rewrite IdentMap.gss.\n      eexists. eauto. }\n    rewrite IdentMap.gso; auto. }\n  { intros QQ l.\n    assert (max_value f_to' (S_tm G l (covered T)) (LocFun.find l (Configuration.sc PC))) as BB.\n    { eapply sc_view_f_issued; eauto. }\n    destruct (Rel w); auto.\n    eapply max_value_same_set.\n    { apply BB. }\n    eapply s_tm_n_f_steps.\n    { apply TCCOH. }\n    { clear. basic_solver. }\n    intros a [HB|HB] HH AA.\n    { eauto. }\n    subst. clear -WW AA. type_solver. }\n  { ins.\n    destruct (Ident.eq_dec thread' (tid w)) as [EQ|NEQ].\n    { subst. rewrite IdentMap.gss in TID0.\n      inv TID0; simpls; clear TID0. }\n    red; ins; rewrite IdentMap.gso in TID0; auto.\n    erewrite Memory.add_o; eauto.\n    destruct (loc_ts_eq_dec (loc, to) (locw, f_to' wnext)) as [[A B]|LL'].\n    { simpls; rewrite A in *; rewrite B in *; subst.\n      exfalso. erewrite NINTER' in LHS; eauto. inv LHS. }\n    rewrite (loc_ts_eq_dec_neq LL').\n    erewrite Memory.add_o; eauto.\n    destruct (loc_ts_eq_dec (loc, to) (locw, f_to' w)) as [[A B]|LL].\n    { simpls; rewrite A in *; rewrite B in *; subst.\n      exfalso. erewrite NINTER in LHS; eauto. inv LHS. }\n    rewrite (loc_ts_eq_dec_neq LL).\n    eapply PROM_IN_MEM in LHS; eauto. }\n  { simpls. red. ins.\n    destruct (loc_ts_eq_dec (l, to) (locw, f_to' wnext)) as [[A' B']|LL'].\n    { simpls; rewrite A' in *; rewrite B' in *.\n      exfalso. rewrite RESGET' in PROM. inv PROM. }\n    erewrite Memory.add_o in PROM; eauto. rewrite (loc_ts_eq_dec_neq LL') in PROM.\n    destruct (loc_ts_eq_dec (l, to) (locw, f_to' w)) as [[A' B']|LL].\n    { simpls; rewrite A' in *; rewrite B' in *.\n      destruct (Rel w) eqn:RELB; subst.\n      { erewrite Memory.remove_o in PROM; eauto.\n        rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in PROM. inv PROM. }\n      erewrite Memory.add_o in PROM; eauto.\n      rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in PROM.\n      inv PROM. exists w. splits; eauto. by right. }\n    eapply NOTNEWR in PROM; eauto.\n    edestruct SIM_PROM as [b H]; eauto; desc.\n    exists b; splits; auto.\n    { by left. }\n    { assert (W b) as WB by (eapply issuedW; eauto).\n      destruct (Rel w) eqn:RELB; auto.\n      intros [HH|HH]; desf. }\n    { by rewrite ISSEQ_FROM. }\n    { by rewrite ISSEQ_TO. }\n    eapply sim_mem_helper_f_issued with (f_to:=f_to); eauto. }\n  { simpls. red. ins.\n    destruct (loc_ts_eq_dec (l, to) (locw, f_to' wnext)) as [[A' B']|LL'].\n    { simpls; rewrite A' in *; rewrite B' in *.\n      rewrite RESGET' in RES. inv RES.\n      exists wnext. splits; eauto.\n      intros [HH|HH]; subst; eauto. }\n    erewrite Memory.add_o in RES; eauto. rewrite (loc_ts_eq_dec_neq LL') in RES.\n    destruct (loc_ts_eq_dec (l, to) (locw, f_to' w)) as [[A' B']|LL].\n    { simpls; rewrite A' in *; rewrite B' in *.\n      destruct (Rel w) eqn:RELB; subst.\n      erewrite Memory.remove_o in RES; eauto.\n      2: erewrite Memory.add_o in RES; eauto.\n      all: rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in RES; inv RES. }\n    apply NOTNEWR in RES; auto.\n    edestruct SIM_RES_PROM as [b H]; eauto; desc.\n    exists b. splits; auto.\n    { intros [A|A]; desf. }\n    { rewrite REQ_FROM; auto. }\n    rewrite REQ_TO; auto. }\n  { ins.\n    rewrite IdentMap.gso in TID'; auto.\n    destruct (loc_ts_eq_dec (loc, to) (locw, (f_to' w))) as [EQ|NEQ]; simpls.\n    { desc. subst. right.\n      destruct (Memory.get locw (f_to' w) (Local.promises local')) eqn: HH; auto.\n      exfalso.\n      erewrite NINTER in HH; eauto. inv HH. }\n    destruct (loc_ts_eq_dec (loc, to) (locw, (f_to' wnext))) as [EQ|NEQ']; simpls.\n    { desc. subst. right.\n      destruct (Memory.get locw (f_to' wnext) (Local.promises local')) eqn: HH; auto.\n      exfalso.\n      erewrite NINTER' in HH; eauto. inv HH. }\n    edestruct (PROM_DISJOINT TNEQ TID') as [HH|HH]; eauto.\n    left.\n    destruct (Memory.get loc to promises') eqn:BB; auto.\n    destruct p. eapply NOTNEWA in BB; eauto. desf. }\n  { red. ins.\n    destruct ISSB as [ISSB|]; subst.\n    { edestruct SIM_MEM as [rel_opt HH]; eauto. simpls. desc.\n      exists rel_opt. unnw.\n      destruct (loc_ts_eq_dec (l, f_to' b) (locw, (f_to' w))) as [EQ|NEQ]; simpls; desc; subst.\n      { exfalso.\n        assert (b = w); [|by desf].\n        eapply f_to_eq; try apply FCOH0; eauto.\n        { red. by rewrite LOC. }\n        do 2 left. by apply ETCCOH.(etc_I_in_S). }\n      destruct (loc_ts_eq_dec (l, f_to' b) (locw, (f_to' wnext))) as [EQ|NEQ'];\n        simpls; desc; subst.\n      { exfalso.\n        assert (b = wnext); [|by desf].\n        eapply f_to_eq; try apply FCOH0; eauto.\n        { red. by rewrite WNEXTLOC. }\n        do 2 left. by apply ETCCOH.(etc_I_in_S). }\n      erewrite Memory.add_o with (mem2:=memory'); eauto.\n      erewrite Memory.add_o with (mem2:=memory_add); eauto.\n      rewrite !loc_ts_eq_dec_neq; auto.\n      splits; eauto.\n      { rewrite ISSEQ_TO; auto. rewrite ISSEQ_FROM; auto. }\n      { rewrite ISSEQ_FROM; auto. eapply sim_mem_helper_f_issued; eauto. }\n      intros AA BB.\n      assert (~ covered T b) as NCOVBB.\n      { intros HH. apply BB. generalize HH. clear. basic_solver. }\n      specialize (HH1 AA NCOVBB).\n      desc. splits; auto.\n      { apply NOTNEWA; auto.\n        rewrite ISSEQ_TO; auto. rewrite ISSEQ_FROM; auto. }\n      eexists. splits; eauto.\n      2: { destruct HH2 as [[CC DD]|CC]; [left|right].\n           { split; eauto. intros [y HH]. destruct_seq_l HH as OO.\n             destruct OO as [OO|]; subst.\n             { apply CC. exists y. apply seq_eqv_l. by split. }\n             apply NISSB. eapply rfrmw_I_in_I; eauto. exists b.\n             apply seqA. apply seq_eqv_r. by split. }\n           desc. exists p. splits; auto.\n           { by left. }\n           eexists. splits; eauto.\n           destruct (classic (l = locw)) as [|LNEQ]; subst; auto.\n           2: { apply NOTNEWM.\n                1,2: by left.\n                rewrite ISSEQ_TO; auto. rewrite ISSEQ_FROM; auto. }\n           assert (S' p) as SPP.\n           { do 2 left. by apply ETCCOH.(etc_I_in_S). }\n           assert (loc lab p = Some locw) as PLOC.\n           { rewrite <- LOC0. by apply WF.(wf_rfrmwl). }\n           apply NOTNEWM.\n           3: { rewrite ISSEQ_TO; auto. rewrite ISSEQ_FROM; auto. }\n           all: right; intros HH.\n           all: eapply f_to_eq in HH; eauto; subst; auto.\n           { red. by rewrite LOC. }\n           red. by rewrite WNEXTLOC. }\n      destruct (Rel w) eqn:RELW; auto.\n      2: by rewrite ISSEQ_TO.\n      assert (wmod (mod lab w) = Ordering.acqrel) as MM.\n      { clear -RELW. mode_solver. }\n      rewrite MM.\n      unfold TView.rel, TView.write_tview. \n      arewrite (Ordering.le Ordering.acqrel Ordering.acqrel = true) by reflexivity.\n      destruct (classic (l = locw)) as [|LNEQ]; subst.\n      2: { unfold LocFun.add. rewrite Loc.eq_dec_neq; auto. by rewrite ISSEQ_TO. }\n      exfalso.\n      assert (E b) as EB by (eapply issuedE; eauto).\n      assert (W b) as WB by (eapply issuedW; eauto).\n      assert ((⦗E⦘ ⨾ same_tid ⨾ ⦗E⦘) w b) as ST.\n      { apply seq_eqv_lr. by splits. }\n      apply tid_sb in ST. destruct ST as [[[|ST]|ST]|[AI BI]]; subst; auto.\n      2: { apply NCOVBB. apply ISSUABLE. exists w. apply seq_eqv_r. split; auto.\n           apply sb_to_w_rel_in_fwbob. apply seq_eqv_r. split; auto. by split. }\n      assert (issuable G sc T b) as IB by (eapply issued_in_issuable; eauto).\n      apply NCOVB. apply IB. exists b. apply seq_eqv_r. split; auto.\n      apply sb_from_w_rel_in_fwbob; auto. apply seq_eqv_lr. splits; auto.\n      all: split; auto. red. by rewrite LOC. }\n    assert (Some l = Some locw) as QQ.\n    { by rewrite <- LOC0. }\n    inv QQ.\n    eexists. splits; eauto.\n    { erewrite Memory.add_o; eauto; rewrite loc_ts_eq_dec_neq; eauto.\n      erewrite Memory.add_o; eauto. rewrite loc_ts_eq_dec_eq; eauto. }\n    { apply HELPER. }\n    { apply RELWFEQ. }\n    { eapply Memory.add_closed_timemap; eauto. }\n    intros _ NT.\n    clear PROMGET.\n    destruct (Rel b); desf.\n    { exfalso. apply NT. by right. }\n    splits.\n    { erewrite Memory.add_o; eauto; rewrite loc_ts_eq_dec_neq; eauto.\n      erewrite Memory.add_o; eauto. rewrite loc_ts_eq_dec_eq; eauto. }\n    exists p_rel. splits; eauto. left.\n    cdes PREL. destruct PREL1; desc.\n    2: { exfalso. apply NWEX. red. generalize INRMW. clear. basic_solver. }\n    split; auto.\n    intros [a HH].\n    apply seq_eqv_l in HH. destruct HH as [[HH|] RFRMW]; subst; eauto.\n    { apply NINRMW. generalize HH RFRMW. clear. basic_solver 10. }\n    eapply wf_rfrmw_irr; eauto. }\n  { red. ins.\n    assert (b <> w /\\ ~ issued T b) as [BNEQ NISSBB].\n    { generalize NISSB0. clear. basic_solver. }\n    destruct RESB as [[SB|]|HH]; subst.\n    2: by desf.\n    { unnw.\n      erewrite Memory.add_o with (mem2:=memory'); eauto.\n      destruct (loc_ts_eq_dec (l, f_to' b) (locw, (f_to' w))) as [PEQ'|PNEQ];\n        simpls; desc; subst.\n      { exfalso. apply BNEQ.\n        eapply f_to_eq with (f_to:=f_to'); eauto. red.\n          by rewrite LOC. }\n      destruct (loc_ts_eq_dec (l, f_to' b) (locw, (f_to' wnext))) as [PEQ'|PNEQ'];\n        simpls; desc; subst.\n      { exfalso. eapply f_to_eq with (I:=S') in PEQ'0; subst; eauto.\n          by red; rewrite WNEXTLOC. }\n      edestruct SIM_RES_MEM with (b:=b); eauto; unnw.\n      rewrite (loc_ts_eq_dec_neq PNEQ').\n      erewrite Memory.add_o with (mem2:=memory_add); eauto.\n      rewrite (loc_ts_eq_dec_neq PNEQ).\n      rewrite REQ_TO; auto. rewrite REQ_FROM; auto. }\n    assert (b = wnext); subst.\n    { eapply dom_sb_S_rfrmw_single; eauto. }\n    assert (Some l = Some locw) as LL.\n    { by rewrite <- LOC0. }\n    inv LL.\n    splits; ins.\n    erewrite Memory.add_o; eauto. by rewrite loc_ts_eq_dec_eq. }\n  intros WREL. red. ins. destruct msg; auto.\n  rewrite WREL in PEQ.\n  exfalso.\n  erewrite Memory.add_o in GET; eauto.\n  destruct (loc_ts_eq_dec (locw, t) (locw, f_to' wnext)) as [AA|NEQ']; simpls.\n  { desc; subst.\n    rewrite (loc_ts_eq_dec_eq locw (f_to' wnext)) in GET. inv GET. }\n  rewrite (loc_ts_eq_dec_neq NEQ') in GET.\n  destruct (loc_ts_eq_dec (locw, t) (locw, f_to' w)) as [AA|NEQ]; simpls.\n  { desc; subst.\n    erewrite Memory.remove_o in GET; eauto.\n    rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in GET. inv GET. }\n  apply NOTNEWR in GET; auto.\n  eapply SIM_PROM in GET. desc; subst.\n  assert (E b) as EB.\n  { eapply issuedE; eauto. }\n  assert (W b) as WB.\n  { eapply issuedW; eauto. }\n  assert ((⦗E⦘ ⨾ same_tid ⨾ ⦗E⦘) b w) as HH.\n  { apply seq_eqv_lr. splits; auto. }\n  apply tid_sb in HH. destruct HH as [[[HH|HH]|HH]|[AA BB]]; subst; auto.\n  2: { apply NCOVB. eapply dom_W_Rel_sb_loc_I_in_C; eauto.\n       exists b. apply seq_eqv_l. split; [by split|].\n       apply seqA.\n       do 2 (apply seq_eqv_r; split; auto).\n       split; auto. red. rewrite LOC. auto. }\n  apply NCOV. apply ISSUABLE. exists w. apply seq_eqv_r. split; auto.\n  apply sb_to_w_rel_in_fwbob. apply seq_eqv_r. \n  do 2 (split; auto).\nQed.\n\nEnd IssueStepHelper.\n", "meta": {"author": "weakmemory", "repo": "promising2ToImm", "sha": "8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c", "save_path": "github-repos/coq/weakmemory-promising2ToImm", "path": "github-repos/coq/weakmemory-promising2ToImm/promising2ToImm-8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c/src/reserve_steps/IssueNextStepHelper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.32423539898095244, "lm_q1q2_score": 0.2146188234210654}}
{"text": "Require Import Coqlib.\nRequire Import Maps.\n\nRequire Import Integers.\nOpen Scope Z_scope.\nImport ListNotations. \n\nRequire Import state.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n(*+ Syntax of SPARC Code +*)\n(* Instructions will not cause control transfermation *)\nInductive ins: Type :=\n| ld : AddrExp -> GenReg -> ins\n| st : GenReg -> AddrExp -> ins\n| nop : ins\n| add : GenReg -> OpExp -> GenReg -> ins\n| sub : GenReg -> OpExp -> GenReg -> ins\n| subcc : GenReg -> OpExp -> GenReg -> ins\n| and : GenReg -> OpExp -> GenReg -> ins\n| andcc : GenReg -> OpExp -> GenReg -> ins\n| or : GenReg -> OpExp -> GenReg -> ins\n| sll : GenReg -> OpExp -> GenReg -> ins\n| srl : GenReg -> OpExp -> GenReg -> ins\n| sett : Val -> GenReg -> ins\n| save : GenReg -> OpExp -> GenReg -> ins\n| restore : GenReg -> OpExp -> GenReg -> ins\n| rd : SpReg -> GenReg -> ins\n| wr : GenReg -> OpExp -> SpReg -> ins\n| getcwp : GenReg -> ins.\n\n(* Command *)\nInductive command: Type :=\n| cntrans : ins -> command\n| ccall : Label -> command\n| cjumpl : AddrExp -> GenReg -> command\n| cretl : command\n| cret : command\n| cbe : Label -> command\n| cbne : Label -> command.\n\n(* Instruction Sequence *)\nInductive InsSeq : Type :=\n| consSeq : ins -> InsSeq -> InsSeq\n| consJ : AddrExp -> GenReg -> ins -> InsSeq\n| consCall : Label -> ins -> InsSeq -> InsSeq\n| consRetl : ins -> InsSeq\n| consRet : ins -> InsSeq\n| consBe : Label -> ins -> InsSeq -> InsSeq\n| consBne : Label -> ins -> InsSeq -> InsSeq.\n\n(* Verified Instruction Sequence *)\nInductive vInsSeq : Type :=\n| vSeq : Label -> InsSeq -> vInsSeq.\n\nNotation \"i ;; I\" := (consSeq i I) (at level 90, right associativity,\n                                              format\n                                                \"i ;; '//' I\"\n                                             ): code_scope.\nNotation \"'jmpl' addr rr ;; i\" := (consJ addr rr i)\n                                    (at level 78, right associativity): code_scope.\n\nNotation \" 'call' f # i # I\" :=\n  (consCall f i I) (at level 90, right associativity,\n                    format\n                      \"'call' '/' f # i # '//' I\"\n                   ): code_scope.\n\nNotation \"'retl' ;; i\" :=\n  (consRetl i) (at level 80, right associativity): code_scope.\n\nNotation \"'ret' ;; i\" :=\n  (consRet i) (at level 80, right associativity): code_scope.\n\nNotation \"'be' f # i # I\" :=\n  (consBe f i I) (at level 90, right associativity,\n                     format\n                       \"'be' '/' f # i # '//' I\"\n                 ): code_scope.\n\nNotation \"'bne' f # i # I\" :=\n  (consBne f i I) (at level 90, right associativity,\n                   format\n                     \"'bne' '/' f # i # '//' I\"\n                  ): code_scope.\n\n(* Test code *)\n(* Definition f1 := ($ 1).\nDefinition f2 := ($ 2).\nDefinition f3 := ($ 3).\nDefinition f4 := ($ 4).\n\nDefinition code : InsSeq := \n  consJ (Ao (Or r1)) r3 nop. \n\nDefinition code1 : InsSeq :=\n  consSeq (add r1 (Or r2) r3) (consJ (Ao (Or r1)) r3 nop).\nPrint code1.\n\nDefinition code2 : InsSeq :=\n  retl ;; nop.\n\nDefinition code3 : InsSeq :=\n  nop ;; (add r1 (Or r1) r2) ;;\n      retl ;; nop.\n\nDefinition code4 : InsSeq :=\n  call f3 # nop # code3.\n\nDefinition code5 : InsSeq :=\n  be f3 # nop # code3.*)\n\nOpen Scope code_scope.\n\n(*+ Code Heap +*)\nModule LabEq.\n  Definition t := Word.\n  Definition eq := Int.eq_dec.\nEnd LabEq.\nModule CodeMap := EMap(LabEq).\n\n(* The definition of code heap *)\nDefinition CodeHeap := CodeMap.t (option command). \n\n(* basic code block constructor *)\nInductive LookupC : CodeHeap -> Label -> InsSeq -> Prop :=\n| lookupNoTransIns :\n    forall C f I i,\n      C f = Some (cntrans i) -> LookupC C (f +ᵢ ($ 4)) I ->\n      LookupC C f (i ;; I)\n| LookupJmp :\n    forall C f i aexp rr,\n      C f = Some (cjumpl aexp rr) ->\n      C (f +ᵢ ($ 4)) = Some (cntrans i) ->\n      LookupC C f (consJ aexp rr i)\n| lookupRetl :\n    forall C f i,\n      C f = Some (cretl) -> C (f +ᵢ ($ 4)) = Some (cntrans i) ->\n      LookupC C f (retl ;; i)\n| lookupRet :\n    forall C f i,\n      C f = Some (cret) -> C (f +ᵢ ($ 4)) = Some (cntrans i) ->\n      LookupC C f (ret ;; i)\n| lookupCall :\n    forall C f f' i I,\n      C f = Some (ccall f') -> C (f +ᵢ ($ 4)) = Some (cntrans i) ->\n      LookupC C (f +ᵢ ($ 8)) I ->\n      LookupC C f (call f' # i # I)\n| lookupBe :\n    forall C f f' i I,\n      C f = Some (cbe f') -> C (f +ᵢ ($ 4)) = Some (cntrans i) ->\n      LookupC C (f +ᵢ ($ 8)) I ->\n      LookupC C f (be f' # i # I)\n| lookupBne :\n    forall C f f' i I,\n      C f = Some (cbne f') -> C (f +ᵢ ($ 4)) = Some (cntrans i) ->\n      LookupC C (f +ᵢ ($ 8)) I ->\n      LookupC C f (bne f' # i # I).\n\n(*+ Operational Semantics +*)\n\nDefinition get_range: Z -> Z -> Word -> Word :=\n  fun i j N =>\n    N &ᵢ (((($1)<<ᵢ($(j-i+1))) -ᵢ($1)) <<ᵢ($i)).\nDefinition word_aligned: Val -> bool :=\n  fun v => match v with\n         | Ptr (b, ofs) => if (get_range 0 1 ofs) =ᵢ ($0) then true else false\n         | W w => if (get_range 0 1 w) =ᵢ ($0) then true else false\n         end.\n\nDefinition iszero v :=\n  if Int.eq_dec v ($ 0) then $ 1 else $ 0.\n\nFixpoint set_Rs R (vl : list (RegName * Val)) :=\n  match vl with\n  | (rr, v) :: vl =>\n    set_Rs (set_R R rr v) vl\n  | nil => R\n  end.\n\n(* operational Semantics for normal instruction *)\nInductive R__ : Memory * RegFile -> ins -> Memory * RegFile -> Prop :=\n| Ld_step : forall aexp (ri : GenReg) M R R' addr v,\n    eval_addrexp R aexp = Some (Ptr addr) -> word_aligned (Ptr addr) = true ->\n    M addr = Some v -> indom ri R -> set_R R ri v = R' ->\n    R__ (M, R) (ld aexp ri) (M, R')\n\n| ST_step : forall (ri : GenReg) aexp M M' R addr v,\n    eval_addrexp R aexp = Some (Ptr addr) -> word_aligned (Ptr addr) = true ->\n    get_R R ri = Some v -> indom addr M -> MemMap.set addr (Some v) M = M' ->\n    R__ (M, R) (st ri aexp) (M', R)\n\n| Nop_step : forall M R,\n    R__ (M, R) nop (M, R)\n\n| Add_step : forall M (R R' : RegFile) oexp (rs rd : GenReg) v1 v2 v,\n    get_R R rs = Some v1 -> eval_opexp R oexp = Some v2 ->\n    indom rd R -> set_R R rd v = R' -> val_add v1 v2 = Some v ->\n    R__ (M, R) (add rs oexp rd) (M, R')\n        \n| Sub_step : forall M (R R' : RegFile) oexp (rs rd : GenReg) v1 v2 v,\n    get_R R rs = Some v1 -> eval_opexp R oexp = Some v2 ->\n    indom rd R -> set_R R rd v = R' -> val_sub v1 v2 = Some v ->\n    R__ (M, R) (sub rs oexp rd) (M, R')\n\n| Subcc_step : forall M (R R' : RegFile) oexp (rs rd : GenReg) v1 v2 v,\n    get_R R rs = Some (W v1) -> eval_opexp R oexp = Some (W v2) ->\n    indom rd R -> indom n R -> indom z R -> v = v1 -ᵢ v2 ->\n    set_Rs R ((Rr rd, W v) :: (Rpsr n, W (get_range 31 31 v)) :: (Rpsr z, W (iszero v)) :: nil) = R' ->\n    R__ (M, R) (subcc rs oexp rd) (M, R')\n\n| And_step : forall M (R R' : RegFile) oexp (rs rd : GenReg) v1 v2,\n    get_R R rs = Some (W v1) -> eval_opexp R oexp = Some (W v2) ->\n    indom rd R -> set_R R rd (W (v1 &ᵢ v2)) = R' ->\n    R__ (M, R) (and rs oexp rd) (M, R')\n\n| Andcc_step : forall M (R R' : RegFile) oexp (rs rd : GenReg) v1 v2 v,\n    get_R R rs = Some (W v1) -> eval_opexp R oexp = Some (W v2) ->\n    indom rd R -> indom n R -> indom z R -> v = v1 &ᵢ v2 ->\n    set_Rs R ((Rr rd, W v) :: (Rpsr n, W (get_range 31 31 v)) :: (Rpsr z, W (iszero v)) :: nil) = R' ->\n    R__ (M, R) (andcc rs oexp rd) (M, R')\n\n| Or_step : forall M (R R' : RegFile) oexp (rs rd : GenReg) v1 v2,\n    get_R R rs = Some (W v1) -> eval_opexp R oexp = Some (W v2) ->\n    indom rd R -> set_R R rd (W (v1 |ᵢ v2)) = R' ->\n    R__ (M, R) (or rs oexp rd) (M, R')\n\n| Sll_step : forall M (R R' : RegFile) oexp (rs rd : GenReg) v1 v2,\n    get_R R rs = Some (W v1) -> eval_opexp R oexp = Some (W v2) ->\n    indom rd R -> set_R R rd (W (v1 <<ᵢ (get_range 0 4 v2))) = R' ->\n    R__ (M, R) (sll rs oexp rd) (M, R')\n\n| Srl_step : forall M (R R' : RegFile) oexp (rs rd : GenReg) v1 v2,\n    get_R R rs = Some (W v1) -> eval_opexp R oexp = Some (W v2) ->\n    indom rd R -> set_R R rd (W (v1 >>ᵢ (get_range 0 4 v2))) = R' ->\n    R__ (M, R) (srl rs oexp rd) (M, R')\n\n| Set_step : forall M (R R' : RegFile) (rd : GenReg) v,\n    indom rd R -> set_R R rd v = R' ->\n    R__ (M, R) (sett v rd) (M, R')\n\n| Rd_step : forall M (R R' : RegFile) (rsp : SpReg) (ri : GenReg) v,\n    get_R R rsp = Some (W v) -> indom ri R -> set_R R ri (W v) = R' ->\n    R__ (M, R) (rd rsp ri) (M, R')\n\n| GetCwp_step : forall M (R R' : RegFile) (ri : GenReg) v,\n    get_R R cwp = Some (W v) -> indom ri R -> set_R R ri (W v) = R' ->\n    R__ (M, R) (getcwp ri) (M, R').\n\n(* Operation to write a frame *)\nDefinition set_frame R (rr0 rr1 rr2 rr3 rr4 rr5 rr6 rr7 : GenReg) (fm : Frame) :=\n  match fm with\n  | consfm v0 v1 v2 v3 v4 v5 v6 v7 =>\n    set_Rs R\n           ((Rr rr0, v0) :: (Rr rr1, v1) :: (Rr rr2, v2) :: (Rr rr3, v3) :: (Rr rr4, v4) ::\n                         (Rr rr5, v5) :: (Rr rr6, v6) :: (Rr rr7, v7) :: nil)\n  end.\n\n(* Operation to write a window *)\nDefinition set_window R (fm1 fm2 fm3 : Frame) :=\n  let R1 := set_frame R r8 r9 r10 r11 r12 r13 r14 r15 fm1 in\n  let R2 := set_frame R1 r16 r17 r18 r19 r20 r21 r22 r23 fm2 in\n  set_frame R2 r24 r25 r26 r27 r28 r29 r30 r31 fm3.\n\nDefinition N := $ 8.\n\nDefinition post_cwp: Word -> Word :=\n   fun k => (k +ᵢ ($ 1)) modu N.\n\nDefinition pre_cwp: Word -> Word :=\n  fun k => (k +ᵢ N -ᵢ ($ 1)) modu N.\n\nDefinition win_masked: Word -> Word -> bool :=\n  fun w v => if ((($1) <<ᵢ w) &ᵢ v) !=ᵢ ($0) then true else false.\n\nDefinition set_spec_reg (rsp : SpReg) (v : Word) :=\n  match rsp with\n  | Rwim => get_range 0 7 v\n  | _ => v\n  end.\n\n(* Operations that may touch DelayList and FrameList *)\nInductive Q__: State -> command -> State -> Prop :=\n| NormalIns :\n    forall i M M' R R' F D,\n      R__ (M, R) i (M', R') ->\n      Q__ (M, (R, F), D) (cntrans i) (M', (R', F), D)\n\n| SSave :\n    forall (M : Memory) (R R' R'': RegFile) D F F' k k' oexp\n           fmo fml fmi fm1 fm2 v1 v2 v res (rs rd : GenReg),\n      Some res = val_add v1 v2 ->\n      get_R R cwp = Some (W k) -> get_R R Rwim = Some (W v) ->\n      fetch R = Some [fmo; fml; fmi] -> indom rd R -> \n      get_R R rs = Some v1 -> eval_opexp R oexp = Some v2 -> F = F' ++ (fm1 :: fm2 :: nil) ->\n      R' = set_window R fm1 fm2 fmo -> k' = pre_cwp k -> win_masked k' v = false -> \n      R'' = set_Rs R' ((Rpsr cwp, W k') :: (Rr rd, res) :: nil) ->\n      Q__ (M, (R, F), D) (cntrans (save rs oexp rd)) (M, (R'', fml :: fmi :: F'), D)\n\n| RRestore :\n    forall (M : Memory) (R R' R'': RegFile) D F F' k k' oexp\n           fmo fml fmi fm1 fm2 v1 v2 v (rs rd : GenReg) res,\n      Some res = val_add v1 v2 ->\n      get_R R cwp = Some (W k) -> get_R R Rwim = Some (W v) ->\n      fetch R = Some [fmo; fml; fmi] -> indom rd R ->\n      get_R R rs = Some v1 -> eval_opexp R oexp = Some v2 -> F = fm1 :: fm2 :: F' ->\n      R' = set_window R fmi fm1 fm2 -> k' = post_cwp k -> win_masked k' v = false ->\n      R'' = set_Rs R' ((Rpsr cwp, W (post_cwp k)) :: (Rr rd, res) :: nil) ->\n      Q__ (M, (R, F), D) (cntrans (restore rs oexp rd)) (M, (R'', F' ++ (fmo :: fml :: nil)), D)\n\n| Wr :\n    forall M (R : RegFile) F D D' (rs : GenReg) (rsp : SpReg) oexp v1 v2 v,\n      get_R R rs = Some (W v1) -> eval_opexp R oexp = Some (W v2) ->\n      v = set_spec_reg rsp (v1 xor v2) -> indom rsp R -> D' = set_delay rsp v D ->\n      Q__ (M, (R, F), D) (cntrans (wr rs oexp rsp)) (M, (R, F), D').\n\n(* Operation Semantics for Control Transfer *)\nInductive H__ : CodeHeap -> State * Label * Label -> State * Label * Label -> Prop :=\n| NTrans :\n    forall C i S S' pc npc,\n      C pc = Some (cntrans i) -> Q__ S (cntrans i) S' ->\n      H__ C (S, pc, npc) (S', npc, (npc +ᵢ ($ 4)))\n\n| Jumpl :\n    forall C M aexp rd (R R' : RegFile) F D (pc npc f : Label),\n      C pc = Some (cjumpl aexp rd) -> eval_addrexp R aexp = Some (W f) ->\n      word_aligned (W f) = true -> indom rd R -> set_R R rd (W pc) = R' ->\n      H__ C ((M, (R, F), D), pc, npc) ((M, (R', F), D), npc, f)\n\n| Call :\n    forall C M (R R' : RegFile) F D pc npc f,\n      C pc = Some (ccall f) -> indom r15 R -> set_R R r15 (W pc) = R' ->\n      H__ C ((M, (R, F), D), pc, npc) ((M, (R', F), D), npc, f)\n\n| Retl :\n    forall C M (R : RegFile) F D pc npc f,\n      C pc = Some (cretl) -> get_R R r15 = Some (W f) ->\n      H__ C ((M, (R, F), D), pc, npc) ((M, (R, F), D), npc, f +ᵢ ($ 8))\n\n| Ret :\n    forall C M (R : RegFile) F D pc npc f,\n      C pc = Some (cret) -> get_R R r31 = Some (W f) ->\n      H__ C ((M, (R, F), D), pc, npc) ((M, (R, F), D), npc, f +ᵢ ($ 8))\n\n| Be_true :\n    forall C M (R : RegFile) F D pc npc f v,\n      C pc = Some (cbe f) -> get_R R z = Some (W v) -> v <> ($ 0) ->\n      H__ C ((M, (R, F), D), pc, npc) ((M, (R, F), D), npc, f)\n\n| Be_false :\n    forall C M (R : RegFile) F D pc npc f,\n      C pc = Some (cbe f) -> get_R R z = Some (W ($ 0)) ->\n      H__ C ((M, (R, F), D), pc, npc) ((M, (R, F), D), npc, npc +ᵢ ($ 4))\n\n| Bne_true :\n    forall C M (R : RegFile) F D pc npc f,\n      C pc = Some (cbne f) -> get_R R z = Some (W ($ 0)) ->\n      H__ C ((M, (R, F), D), pc, npc) ((M, (R, F), D), npc, f)\n\n| Bne_false :\n    forall C M (R : RegFile) F D pc npc f v,\n      C pc = Some (cbne f) -> get_R R z = Some (W v) -> v <> ($ 0) ->\n      H__ C ((M, (R, F), D), pc, npc) ((M, (R, F), D), npc, npc +ᵢ ($ 4)).\n\nInductive P__ : CodeHeap -> State * Label * Label -> State * Label * Label -> Prop :=\n  CStep :\n    forall C M M' R R' R'' D D' D'' F F' pc pc' npc npc',\n      (R', D') = exe_delay R D ->\n      H__ C ((M, (R', F), D'), pc, npc) ((M', (R'', F'), D''), pc', npc') ->\n      P__ C ((M, (R, F), D), pc, npc) ((M', (R'', F'), D''), pc', npc').\n", "meta": {"author": "jpzha", "repo": "VeriSparc", "sha": "7fc60fbc4b4357b93836d1b461d7d27c669e9f58", "save_path": "github-repos/coq/jpzha-VeriSparc", "path": "github-repos/coq/jpzha-VeriSparc/VeriSparc-7fc60fbc4b4357b93836d1b461d7d27c669e9f58/coqimp/framework/models/language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2145528662715974}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool eqtype seq.\nRequire Import Init_ext ZArith_ext uniq_tac.\nRequire Import machine_int multi_int encode_decode integral_type.\nImport MachineInt.\nRequire Import mips_bipl mips_tactics mips_syntax mips_mint.\nImport mips_bipl.expr_m.\nRequire Import simu.\nImport simu.simu_m.\nRequire Import multi_negate_prg multi_negate_termination multi_negate_triple.\n\nLocal Open Scope heap_scope.\nLocal Open Scope assoc_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope machine_int_scope.\n\nLemma multi_negate_safe_termination a0 rx x nk d : uniq(rx, a0, r0) ->\n  safe_termination (state_mint (x |=> signed nk rx \\U+ d)) (multi_negate rx a0).\nProof.\nmove=> Hregs.\nrewrite /safe_termination.\nmove=> s st h s_st_h.\ncase/(multi_negate_termination st h) : (Hregs) => sf Hsf.\nmove: (proj1 s_st_h x (signed nk rx)).\nrewrite assoc.get_union_sing_eq.\nmove/(_ (refl_equal _)).\ncase=> len ptr X rx_fit encX ptr_fit HX.\nmove/(multi_negate_triple) : (Hregs).\nmove/(_ len ptr X) => hoare_triple.\napply constructive_indefinite_description'.\nmove: (triple_exec_precond _ _ _ hoare_triple _ _ _ Hsf (heap.dom (heap_mint (signed nk rx) st h))).\napply.\nsuff : h |P| heap.dom (heap_mint (signed nk rx) st h) = heap_mint (signed nk rx) st h by move=> ->.\nrewrite -heap.incluE; by apply heap_inclu_heap_mint_signed.\nQed.\n\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/begcd/multi_negate_safe_termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2145528662715974}}
{"text": "From stdpp Require Import coPset namespaces.\nFrom iris.bi Require Export bi updates.\nFrom iris.bi.lib Require Import fixpoint.\nFrom iris.proofmode Require Import coq_tactics proofmode reduction.\nFrom iris.prelude Require Import options.\nFrom iris.base_logic Require Import invariants.\nFrom iris.program_logic Require Import weakestpre.\n\n(** Conveniently split a conjunction on both assumption and conclusion. *)\nLocal Tactic Notation \"iSplitWith\" constr(H) :=\n  iApply (bi.and_parallel with H); iSplit; iIntros H.\n\nSection post_definition.\n  Context `{BiFUpd PROP} {TC : tele}.\n  Implicit Types\n    (Eo Ei : coPset) (* outer/inner masks *)\n    (Ψ : TC → PROP) (* atomic post-condition *)\n    (Q : PROP) (* keep Ψ condition *)\n    (Φ : PROP) (* post-condition *)\n  .\n\n  (** atomic_post_acc as the \"introduction form\" of atomic post-conditions: An \n      accessor that can return to [Q]. *)\n  Definition atomic_post_acc Eo Ei Ψ Q Φ : PROP :=\n    |={Eo, Ei}=> ∃.. z, Ψ z ∗ ((Ψ z ={Ei, Eo}=∗ Q) ∧ (Ψ z ={Ei, Eo}=∗ Φ)).\n\n  Lemma atomic_post_acc_wand Eo Ei Ψ Q1 Q2 Φ1 Φ2 :\n    ((Q1 -∗ Q2) ∧ (Φ1 -∗ Φ2)) -∗\n    (atomic_post_acc Eo Ei Ψ Q1 Φ1 -∗ atomic_post_acc Eo Ei Ψ Q2 Φ2).\n  Proof.\n    iIntros \"HQΦ Hpost\". \n    iMod \"Hpost\" as (z) \"[HΨ Hclose]\". iModIntro. \n    iExists z. iFrame \"HΨ\". iSplitWith \"Hclose\".\n    + iIntros \"HΨ\". iMod (\"Hclose\" with \"HΨ\") as \"HQ\".\n      iModIntro. iApply \"HQΦ\". done.\n    + iIntros \"HΨ\". iMod (\"Hclose\" with \"HΨ\") as \"HΦ\".\n      iModIntro. iApply \"HQΦ\". done.\n  Qed.\n\n  Lemma atomic_post_acc_mask_weaken Eo1 Eo2 Ei Ψ Q Φ :\n    Eo1 ⊆ Eo2 →\n    atomic_post_acc Eo1 Ei Ψ Q Φ -∗ atomic_post_acc Eo2 Ei Ψ Q Φ.\n  Proof.\n    iIntros (HE) \"Hpost\".\n    iMod (fupd_mask_subseteq Eo1) as \"Hclose'\"; first done.\n    iMod \"Hpost\" as (z) \"[HΨ Hclose]\". iModIntro. \n    iExists z. iFrame \"HΨ\". iSplitWith \"Hclose\".\n    + iIntros \"HΨ\". iMod (\"Hclose\" with \"HΨ\") as \"HQ\".\n      iMod \"Hclose'\" as \"_\". iModIntro. done.\n    + iIntros \"HΨ\". iMod (\"Hclose\" with \"HΨ\") as \"HΦ\".\n      iMod \"Hclose'\" as \"_\". iModIntro. done.\n  Qed.\n\n  (** atomic_post as a fixed-point of the equation\n   AP = atomic_post_acc Ψ AP Φ\n  *)\n  Context Eo Ei Ψ Φ.\n\n  Definition atomic_post_pre (Θ : () → PROP) (_ : ()) : PROP :=\n    atomic_post_acc Eo Ei Ψ (Θ ()) Φ.\n\n  Local Instance atomic_post_pre_mono : BiMonoPred atomic_post_pre.\n  Proof.\n    constructor.\n    - iIntros (Q1 Q2 ??) \"#HQ12\". iIntros ([]) \"AP\".\n      iApply (atomic_post_acc_wand with \"[HQ12] AP\").\n      iSplit; last auto. iApply \"HQ12\".\n    - intros ??. solve_proper.\n  Qed.\n\n  Local Definition atomic_post_def :=\n    bi_greatest_fixpoint atomic_post_pre ().\n\nEnd post_definition.\n\n(** Seal it *)\nLocal Definition atomic_post_aux : seal (@atomic_post_def).\nProof. by eexists. Qed.\nDefinition atomic_post := atomic_post_aux.(unseal).\nGlobal Arguments atomic_post {PROP _ TC}.\nLocal Definition atomic_post_unseal :\n  @atomic_post = _ := atomic_post_aux.(seal_eq).\n\nGlobal Arguments atomic_post_acc {PROP _ TC} Eo Ei _ _ _ : simpl never.\nGlobal Arguments atomic_post {PROP _ TC} Eo Ei _ _ : simpl never.\n\n(** Notation: Atomic post-conditions *)\nNotation \"'AP' '<<' ∃∃ z1 .. zn , Ψ '>>' @ Eo , Ei '<<' 'COMM' Φ '>>'\" :=\n  (atomic_post (TC:=TeleS (λ z1, .. (TeleS (λ zn, TeleO)) .. ))\n               Eo Ei\n               (tele_app $ λ z1, .. (λ zn, Ψ%I) ..)\n               Φ%I\n  )\n  (at level 20, Eo, Ei, Ψ, Φ at level 200, z1 binder, zn binder,\n   format \"'[hv   ' 'AP'  '<<'  '[' ∃∃  x1  ..  xn ,  '/' Ψ  ']' '>>'  '/' @  '[' Eo ,  '/' Ei ']'  '/' '<<'  '[' COMM  Φ  ']' '>>' ']'\") : bi_scope.\n\nNotation \"'AP' '<<' Ψ '>>' @ Eo , Ei '<<' 'COMM' Φ '>>'\" :=\n  (atomic_post (TC:=TeleO) Eo Ei (tele_app Ψ%I) Φ%I\n  )\n  (at level 20, Eo, Ei, Ψ, Φ at level 200,\n   format \"'[hv   ' 'AP'  '<<'  '[' Ψ  ']' '>>'  '/' @  '[' Eo ,  '/' Ei ']'  '/' '<<'  '[' COMM  Φ  ']' '>>' ']'\") : bi_scope.\n\n(** Lemmas about AP *)\nSection post_lemmas.\n  Context `{BiFUpd PROP}.\n\n  Local Existing Instance atomic_post_pre_mono.\n\n  (* Can't be in the section above as that fixes the parameters *)\n  Global Instance atomic_post_acc_ne {TC : tele} Eo Ei n :\n    Proper (\n        pointwise_relation TC (dist n) ==>\n        dist n ==>\n        dist n ==>\n        dist n\n    ) (atomic_post_acc (PROP:=PROP) Eo Ei).\n  Proof. solve_proper. Qed.\n\n  Global Instance atomic_post_ne {TC : tele} Eo Ei n :\n    Proper (\n        pointwise_relation TC (dist n) ==>\n        dist n ==>\n        dist n\n    ) (atomic_post (PROP:=PROP) Eo Ei).\n  Proof.\n    rewrite atomic_post_unseal /atomic_post_def /atomic_post_pre. solve_proper.\n  Qed.\n\n  Lemma atomic_post_mask_weaken {TC : tele} Eo1 Eo2 Ei (Ψ : TC → PROP) Φ :\n    Eo1 ⊆ Eo2 →\n    atomic_post Eo1 Ei Ψ Φ -∗ atomic_post Eo2 Ei Ψ Φ.\n  Proof.\n    rewrite atomic_post_unseal {2}/atomic_post_def /=.\n    iIntros (Heo) \"HAP\".\n    iApply (greatest_fixpoint_coiter _ (λ _, atomic_post_def Eo1 Ei Ψ Φ)); last done.\n    iIntros \"!> *\". rewrite {1}/atomic_post_def /= greatest_fixpoint_unfold.\n    iApply atomic_post_acc_mask_weaken. done.\n  Qed.\n\n  Lemma atomic_post_wand {TC : tele} Eo Ei (Ψ : TC → PROP) Φ1 Φ2 :\n    (Φ1 -∗ Φ2) -∗\n    (atomic_post Eo Ei Ψ Φ1 -∗ atomic_post Eo Ei Ψ Φ2).\n  Proof.\n    rewrite atomic_post_unseal {2}/atomic_post_def /=.\n    iIntros \"HΦ Hpost\".\n    iApply (greatest_fixpoint_coiter _ (λ _, (Φ1 -∗ Φ2) ∗ atomic_post_def Eo Ei Ψ Φ1)%I); last iFrame.\n    iIntros \"!> * [HΦ Hpost]\". rewrite {1}/atomic_post_def /= greatest_fixpoint_unfold.\n    iApply (atomic_post_acc_wand with \"[HΦ]\"); last iFrame.\n    iSplit; last done. iIntros; by iFrame.\n  Qed.\n\n  Lemma apst_unfold {TC : tele} Eo Ei (Ψ : TC → PROP) Φ :\n    atomic_post Eo Ei Ψ Φ ⊣⊢\n    atomic_post_acc Eo Ei Ψ (atomic_post Eo Ei Ψ Φ) Φ.\n  Proof.\n    rewrite atomic_post_unseal /atomic_post_def /=. apply: greatest_fixpoint_unfold.\n  Qed.\n\n  (* This lets you eliminate atomic updates with iMod. *)\n  Global Instance elim_mod_apost {TC : tele} φ Eo Ei E (Ψ : TC → PROP) Φ Q Q' :\n    (∀ R, ElimModal φ false false (|={E,Ei}=> R) R Q Q') →\n    ElimModal (φ ∧ Eo ⊆ E) false false\n              (atomic_post Eo Ei Ψ Φ)\n              (∃.. z, Ψ z ∗ ((Ψ z ={Ei,E}=∗ atomic_post Eo Ei Ψ Φ) ∧ (Ψ z ={Ei,E}=∗ Φ)))\n              Q Q'.\n  Proof.\n    intros ?. rewrite /ElimModal /= =>-[??]. iIntros \"[AP Hcont]\".\n    iDestruct (apst_unfold with \"AP\") as \"AC\".\n    iMod (atomic_post_acc_mask_weaken with \"AC\"); first done.\n    iApply \"Hcont\". done.\n  Qed.\n\n  Local Lemma apst_intro {TC : tele} Eo Ei (Ψ : TC → PROP) Φ :\n    Ei ⊆ Eo →\n    (∃.. z, Ψ z ∗ (Ψ z -∗ Φ)) -∗\n    atomic_post Eo Ei Ψ Φ.\n  Proof.\n    iIntros (HE) \"(%z & HΨ & HΦ)\".\n    rewrite atomic_post_unseal /atomic_post_def /=.\n    iApply (greatest_fixpoint_coiter _ (λ _, (Ψ z ∗ (Ψ z -∗ Φ))%I)); last iFrame.\n    iIntros \"!> * [HΨ HΦ]\". iApply (atomic_post_acc_wand with \"[HΦ]\").\n    + iSplit; first iIntros \"?\"; by iFrame.\n    + iApply fupd_mask_intro; first done.\n      iIntros \"Hclose\". iExists z. iFrame \"HΨ\". \n      iSplit; iIntros \"HΨ\"; iMod \"Hclose\" as \"_\"; iModIntro; iFrame.\n  Qed.\n\n  Lemma apst_apst_sup {TC TC' : tele} E1 E1' E2 E3\n        (Ψ : TC → PROP) (Φ : PROP)\n        (Ψ' : TC' → PROP) (Φ' : PROP) \n        (R : PROP):\n    E1' ⊆ E1 → E3 ⊆ E2 →\n    R -∗\n    □ (∀.. z, R ∗ Ψ z -∗ ∃.. z', (Ψ' z' ∗ (Ψ' z' -∗ R ∗ Ψ z))) -∗\n    atomic_post E1' E2 Ψ Φ -∗\n    (R ∗ atomic_post E1' E2 Ψ Φ ={E1}=∗ Φ') -∗\n    atomic_post E1 E3 Ψ' Φ'.\n  Proof.\n    iIntros (??) \"HR #HRΨΨ' AP Hstep\".\n    rewrite {3} atomic_post_unseal /atomic_post_def /=.\n    iApply (greatest_fixpoint_coiter _ (λ _, (R ∗ atomic_post E1' E2 Ψ Φ ∗\n      (R ∗ atomic_post E1' E2 Ψ Φ ={E1}=∗ Φ')\n    )%I)); last iFrame.\n    iIntros \"!> * [HR [AP Hstep]]\".\n    iMod (atomic_post_mask_weaken with \"AP\") as (z) \"[HΨ [Hclose _]]\"; first done.\n    iApply fupd_mask_intro; first done. iIntros \"Hclose'\".\n    iDestruct (\"HRΨΨ'\" with \"[$]\") as (z') \"[HΨ' HRΨ]\".\n    iExists z'. iFrame \"HΨ'\".\n    iSplit; iIntros \"HΨ'\"; iMod \"Hclose'\" as \"_\";\n      iDestruct (\"HRΨ\" with \"HΨ'\") as \"[HR HΨ]\";\n      iMod (\"Hclose\" with \"HΨ\") as \"HΦ\".\n    + iModIntro. iFrame.\n    + iApply \"Hstep\". iFrame. \n  Qed.\n\n  Lemma apst_apst_sub {TC TC' : tele} E1 E1' E2 E3\n        (Ψ : TC → PROP) (Φ : PROP)\n        (Ψ' : TC' → PROP) (Φ' : PROP) :\n    E1' ⊆ E1 → E3 ⊆ E2 →\n    □ (∀.. z, Ψ z -∗ ∃.. z', (Ψ' z' ∗ (Ψ' z' -∗ Ψ z))) -∗\n    atomic_post E1' E2 Ψ Φ -∗\n    (atomic_post E1' E2 Ψ Φ ={E1}=∗ Φ') -∗\n    atomic_post E1 E3 Ψ' Φ'.\n  Proof.\n    iIntros (??) \"#HΨΨ' AP Hstep\".\n    rewrite {3} atomic_post_unseal /atomic_post_def /=.\n    iApply (greatest_fixpoint_coiter _ (λ _, (atomic_post E1' E2 Ψ Φ ∗\n      (atomic_post E1' E2 Ψ Φ ={E1}=∗ Φ')\n    )%I)); last iFrame.\n    iIntros \"!> * [AP Hstep]\".\n    iMod (atomic_post_mask_weaken with \"AP\") as (z) \"[HΨ [Hclose _]]\"; first done.\n    iApply fupd_mask_intro; first done. iIntros \"Hclose'\".\n    iDestruct (\"HΨΨ'\" with \"HΨ\") as (z') \"[HΨ' HΨ]\".\n    iExists z'. iFrame \"HΨ'\".\n    iSplit; iIntros \"HΨ'\"; iMod \"Hclose'\" as \"_\";\n      iDestruct (\"HΨ\" with \"HΨ'\") as \"HΨ\"; \n      iMod (\"Hclose\" with \"HΨ\") as \"HΦ\".\n    + iModIntro. iFrame.\n    + by iApply \"Hstep\". \n  Qed.\n\n  Lemma apst_apst_eq {TC : tele} E1 E1' E2 E3\n        (Ψ : TC → PROP) Φ\n        (Φ' : PROP) :\n    E1' ⊆ E1 → E3 ⊆ E2 →\n    atomic_post E1' E2 Ψ Φ -∗\n    (atomic_post E1' E2 Ψ Φ ={E1}=∗ Φ') -∗\n    atomic_post E1 E3 Ψ Φ'.\n  Proof.\n    iIntros (??) \"AP Hstep\".\n    iApply (apst_apst_sub with \"[] AP\"); try done.\n    iIntros \"!> * %z HΨ\". iExists z. iFrame; iIntros; iFrame.\n  Qed.\n\n  Lemma atomic_post_commit {TC : tele} Eo Ei (Ψ : TC → PROP) Φ :\n    atomic_post Eo Ei Ψ Φ ={Eo}=∗ Φ.\n  Proof.\n    iIntros \"AP\". iMod \"AP\" as (z) \"[HΨ [_ HΦ]]\".\n    iMod (\"HΦ\" with \"HΨ\"). by iModIntro.\n  Qed.\n\nEnd post_lemmas.\n\n\n\nSection definition.\n  Context `{BiFUpd PROP} {TA TB TC : tele}.\n  Implicit Types\n    (Eo Ei : coPset) (* outer/inner masks *)\n    (α : TA → PROP) (* atomic pre-condition *)\n    (P : PROP) (* abortion condition *)\n    (Ψ : TC → PROP) (* atomic post-condition *)\n    (β : TA → TB → PROP)\n    (Φ : TA → TB → PROP) (* post-condition *)\n  .\n\n  (** atomic_acc as the \"introduction form\" of atomic updates: An accessor\n      that can be aborted back to [P]. *)\n  Definition atomic_acc Eo Ei α P Ψ β Φ : PROP :=\n    |={Eo, Ei}=> ∃.. x, α x ∗ (\n          (α x ={Ei, Eo}=∗ P) ∧ (* abort *)\n          (∀.. y, β x y ={Ei, Eo}=∗ atomic_post Eo Ei Ψ (Φ x y)) (* commit *)\n    ).\n\n  Lemma atomic_acc_wand Eo Ei α P1 P2 Ψ β Φ1 Φ2 :\n    ((P1 -∗ P2) ∧ (∀.. x y, Φ1 x y -∗ Φ2 x y)) -∗\n    (atomic_acc Eo Ei α P1 Ψ β Φ1 -∗ atomic_acc Eo Ei α P2 Ψ β Φ2).\n  Proof.\n    iIntros \"HPΦ AS\". iMod \"AS\" as (x) \"[Hα Hclose]\".\n    iModIntro. iExists x. iFrame \"Hα\". iSplit.\n    - iIntros \"Hα\". iDestruct \"Hclose\" as \"[Hclose _]\".\n      iApply \"HPΦ\". iApply \"Hclose\". done.\n    - iIntros (y) \"Hβ\". iDestruct \"Hclose\" as \"[_ Hclose]\".\n      iMod (\"Hclose\" with \"Hβ\") as \"HΦ1\".\n      iModIntro. iDestruct \"HPΦ\" as \"[_ HΦ]\".\n      iApply (atomic_post_wand with \"HΦ\"). done.\n  Qed.\n\n  Lemma atomic_acc_mask_weaken Eo1 Eo2 Ei α P Ψ β Φ :\n    Eo1 ⊆ Eo2 →\n    atomic_acc Eo1 Ei α P Ψ β Φ -∗ atomic_acc Eo2 Ei α P Ψ β Φ.\n  Proof.\n    iIntros (HE) \"Hstep\".\n    iMod (fupd_mask_subseteq Eo1) as \"Hclose'\"; first done.\n    iMod \"Hstep\" as (x) \"[Hα Hclose]\". iModIntro. iExists x.\n    iFrame. iSplitWith \"Hclose\".\n    - iIntros \"Hα\". iMod (\"Hclose\" with \"Hα\") as \"$\". done.\n    - iIntros (y) \"Hβ\". iMod (\"Hclose\" with \"Hβ\") as \"HΦ\".\n      iMod \"Hclose'\" as \"_\". iModIntro.\n      iApply atomic_post_mask_weaken; done.\n  Qed.\n\n  (** atomic_update as a fixed-point of the equation\n   AU = atomic_acc α AU Ψ β Φ\n  *)\n  Context Eo Ei α Ψ β Φ.\n\n  Definition atomic_update_pre (Θ : () → PROP) (_ : ()) : PROP :=\n    atomic_acc Eo Ei α (Θ ()) Ψ β Φ.\n\n  Local Instance atomic_update_pre_mono : BiMonoPred atomic_update_pre.\n  Proof.\n    constructor.\n    - iIntros (P1 P2 ??) \"#HP12\". iIntros ([]) \"AU\".\n      iApply (atomic_acc_wand with \"[HP12] AU\").\n      iSplit; last by eauto. iApply \"HP12\".\n    - intros ??. solve_proper.\n  Qed.\n\n  Local Definition atomic_update_def :=\n    bi_greatest_fixpoint atomic_update_pre ().\n\nEnd definition.\n\n(** Seal it *)\nLocal Definition atomic_update_aux : seal (@atomic_update_def).\nProof. by eexists. Qed.\nDefinition atomic_update := atomic_update_aux.(unseal).\nGlobal Arguments atomic_update {PROP _ TA TB TC}.\nLocal Definition atomic_update_unseal :\n  @atomic_update = _ := atomic_update_aux.(seal_eq).\n\nGlobal Arguments atomic_acc {PROP _ TA TB TC} Eo Ei _ _ _ _ _ : simpl never.\nGlobal Arguments atomic_update {PROP _ TA TB TC} Eo Ei _ _ _ _ : simpl never.\n\n(** Notation: Atomic updates *)\n(* The way to read the [tele_app foo] here is that they convert the n-ary\nfunction [foo] into a unary function taking a telescope as the argument. *)\nNotation \"'AU' '<<' ∃∃ x1 .. xn , α '>>' @ Eo , Ei '<<' ∀∀ y1 .. yn , β , 'POST' ∃∃ z1 .. zn , Ψ , 'COMM' Φ '>>'\" :=\n  (atomic_update (TA:=TeleS (λ x1, .. (TeleS (λ xn, TeleO)) .. ))\n                 (TB:=TeleS (λ y1, .. (TeleS (λ yn, TeleO)) .. ))\n                 (TC:=TeleS (λ z1, .. (TeleS (λ zn, TeleO)) .. ))\n                 Eo Ei\n                 (tele_app $ λ x1, .. (λ xn, α%I) ..)\n                 (tele_app $ λ z1, .. (λ zn, Ψ%I) ..)\n                 (tele_app $ λ x1, .. (λ xn,\n                         tele_app (λ y1, .. (λ yn, β%I) .. )\n                        ) .. )\n                 (tele_app $ λ x1, .. (λ xn,\n                         tele_app (λ y1, .. (λ yn, Φ%I) .. )\n                        ) .. )\n  )\n  (at level 20, Eo, Ei, α, Ψ, β, Φ at level 200, x1 binder, xn binder, y1 binder, yn binder, z1 binder, zn binder,\n   format \"'[hv   ' 'AU'  '<<'  '[' ∃∃  x1  ..  xn ,  '/' α  ']' '>>'  '/' @  '[' Eo ,  '/' Ei ']'  '/' '<<'  '[' ∀∀  y1  ..  yn ,  '/' β ,  '/' POST  '[' ∃∃  z1  ..  zn ,  '/' Ψ  ']' ,  '/' COMM  Φ  ']' '>>' ']'\") : bi_scope.\n\nNotation \"'AU' '<<' ∃∃ x1 .. xn , α '>>' @ Eo , Ei '<<' β , 'POST' ∃∃ z1 .. zn , Ψ , 'COMM' Φ '>>'\" :=\n  (atomic_update (TA:=TeleS (λ x1, .. (TeleS (λ xn, TeleO)) .. ))\n                 (TB:=TeleO)\n                 (TC:=TeleS (λ z1, .. (TeleS (λ zn, TeleO)) .. ))\n                 Eo Ei\n                 (tele_app $ λ x1, .. (λ xn, α%I) ..)\n                 (tele_app $ λ z1, .. (λ zn, Ψ%I) ..)\n                 (tele_app $ λ x1, .. (λ xn, tele_app β%I) .. )\n                 (tele_app $ λ x1, .. (λ xn, tele_app Φ%I) .. )\n  )\n  (at level 20, Eo, Ei, α, Ψ, β, Φ at level 200, x1 binder, xn binder, z1 binder, zn binder,\n   format \"'[hv   ' 'AU'  '<<'  '[' ∃∃  x1  ..  xn ,  '/' α  ']' '>>'  '/' @  '[' Eo ,  '/' Ei ']'  '/' '<<'  '[' β ,  '/' POST  '[' ∃∃  z1  ..  zn ,  '/' Ψ  ']' ,  '/' COMM  Φ  ']' '>>' ']'\") : bi_scope.\n\nNotation \"'AU' '<<' α '>>' @ Eo , Ei '<<' ∀∀ y1 .. yn , β , 'POST' Ψ , 'COMM' Φ '>>'\" :=\n  (atomic_update (TA:=TeleO)\n                 (TB:=TeleS (λ y1, .. (TeleS (λ yn, TeleO)) .. ))\n                 (TC:=TeleO)\n                 Eo Ei\n                 (tele_app α%I)\n                 (tele_app Ψ%I)\n                 (tele_app $ tele_app (λ y1, .. (λ yn, β%I) ..))\n                 (tele_app $ tele_app (λ y1, .. (λ yn, Φ%I) ..))\n  )\n  (at level 20, Eo, Ei, α, Ψ, β, Φ at level 200, y1 binder, yn binder,\n   format \"'[hv   ' 'AU'  '<<'  '[' α  ']' '>>'  '/' @  '[' Eo ,  '/' Ei ']'  '/' '<<'  '[' ∀∀  y1  ..  yn ,  '/' β ,  '/' POST  Ψ ,  '/' COMM  Φ  ']' '>>' ']'\") : bi_scope.\n\nNotation \"'AU' '<<' α '>>' @ Eo , Ei '<<' β , 'POST' Ψ , 'COMM' Φ '>>'\" :=\n  (atomic_update (TA:=TeleO) (TB:=TeleO) (TC:=TeleO)\n                 Eo Ei\n                 (tele_app α%I)\n                 (tele_app Ψ%I)\n                 (tele_app $ tele_app β%I)\n                 (tele_app $ tele_app Φ%I)\n  )\n  (at level 20, Eo, Ei, α, Ψ, β, Φ at level 200,\n   format \"'[hv   ' 'AU'  '<<'  '[' α  ']' '>>'  '/' @  '[' Eo ,  '/' Ei ']'  '/' '<<'  '[' β ,  '/' POST  Ψ ,  '/' COMM  Φ  ']' '>>' ']'\") : bi_scope.\n\n(** Notation: Atomic accessors *)\nNotation \"'AACC' '<<' ∃∃ x1 .. xn , α , 'ABORT' P '>>' @ Eo , Ei '<<' ∀∀ y1 .. yn , β , 'POST' ∃∃ z1 .. zn , Ψ , 'COMM' Φ '>>'\" :=\n  (atomic_acc (TA:=TeleS (λ x1, .. (TeleS (λ xn, TeleO)) .. ))\n              (TB:=TeleS (λ y1, .. (TeleS (λ yn, TeleO)) .. ))\n              (TC:=TeleS (λ z1, .. (TeleS (λ zn, TeleO)) .. ))\n              Eo Ei\n              (tele_app $ λ x1, .. (λ xn, α%I) ..)\n              P%I\n              (tele_app $ λ z1, .. (λ zn, Ψ%I) ..)\n              (tele_app $ λ x1, .. (λ xn,\n                      tele_app (λ y1, .. (λ yn, β%I) .. )\n                     ) .. )\n              (tele_app $ λ x1, .. (λ xn,\n                      tele_app (λ y1, .. (λ yn, Φ%I) .. )\n                     ) .. )\n  )\n  (at level 20, Eo, Ei, α, P, Ψ, β, Φ at level 200, x1 binder, xn binder, y1 binder, yn binder, z1 binder, zn binder,\n   format \"'[hv     ' 'AACC'  '<<'  '[' ∃∃  x1  ..  xn ,  '/' α ,  '/' ABORT  P  ']' '>>'  '/' @  '[' Eo ,  '/' Ei ']'  '/' '<<'  '[' ∀∀  y1  ..  yn ,  '/' β ,  '/' POST  '[' ∃∃  z1  ..  zn ,  '/' Ψ  ']' ,  '/' COMM  Φ  ']' '>>' ']'\") : bi_scope.\n\nNotation \"'AACC' '<<' ∃∃ x1 .. xn , α , 'ABORT' P '>>' @ Eo , Ei '<<' β , 'POST' ∃∃ z1 .. zn , Ψ , 'COMM' Φ '>>'\" :=\n  (atomic_acc (TA:=TeleS (λ x1, .. (TeleS (λ xn, TeleO)) .. ))\n              (TB:=TeleO)\n              (TC:=TeleS (λ z1, .. (TeleS (λ zn, TeleO)) .. ))\n              Eo Ei\n              (tele_app $ λ x1, .. (λ xn, α%I) ..)\n              P%I\n              (tele_app $ λ z1, .. (λ zn, Ψ%I) ..)\n              (tele_app $ λ x1, .. (λ xn, tele_app β%I) .. )\n              (tele_app $ λ x1, .. (λ xn, tele_app Φ%I) .. )\n  )\n  (at level 20, Eo, Ei, α, P, Ψ, β, Φ at level 200, x1 binder, xn binder, z1 binder, zn binder,\n   format \"'[hv     ' 'AACC'  '<<'  '[' ∃∃  x1  ..  xn ,  '/' α ,  '/' ABORT  P  ']' '>>'  '/' @  '[' Eo ,  '/' Ei ']'  '/' '<<'  '[' β ,  '/' POST  '[' ∃∃  z1  ..  zn ,  '/' Ψ  ']' ,  '/' COMM  Φ  ']' '>>' ']'\") : bi_scope.\n\nNotation \"'AACC' '<<' α , 'ABORT' P '>>' @ Eo , Ei '<<' ∀∀ y1 .. yn , β , 'POST' Ψ , 'COMM' Φ '>>'\" :=\n  (atomic_acc (TA:=TeleO)\n              (TB:=TeleS (λ y1, .. (TeleS (λ yn, TeleO)) .. ))\n              (TC:=TeleO)\n              Eo Ei\n              (tele_app α%I)\n              P%I\n              (tele_app Ψ%I)\n              (tele_app $ tele_app (λ y1, .. (λ yn, β%I) ..))\n              (tele_app $ tele_app (λ y1, .. (λ yn, Φ%I) ..))\n  )\n  (at level 20, Eo, Ei, α, P, Ψ, β, Φ at level 200, y1 binder, yn binder,\n   format \"'[hv     ' 'AACC'  '<<'  '[' α ,  '/' ABORT  P  ']' '>>'  '/' @  '[' Eo ,  '/' Ei ']'  '/' '<<'  '[' ∀∀  y1  ..  yn ,  '/' β ,  '/' POST  Ψ ,  '/' COMM  Φ  ']' '>>' ']'\") : bi_scope.\n\nNotation \"'AACC' '<<' α , 'ABORT' P '>>' @ Eo , Ei '<<' β , 'POST' Ψ , 'COMM' Φ '>>'\" :=\n  (atomic_acc (TA:=TeleO)\n              (TB:=TeleO)\n              (TC:=TeleO)\n              Eo Ei\n              (tele_app α%I)\n              P%I\n              (tele_app Ψ%I)\n              (tele_app $ tele_app β%I)\n              (tele_app $ tele_app Φ%I)\n  )\n  (at level 20, Eo, Ei, α, P, Ψ, β, Φ at level 200,\n   format \"'[hv     ' 'AACC'  '<<'  '[' α ,  '/' ABORT  P  ']' '>>'  '/' @  '[' Eo ,  '/' Ei ']'  '/' '<<'  '[' β ,  '/' POST  Ψ ,  '/' COMM  Φ  ']' '>>' ']'\") : bi_scope.\n\n(** Lemmas about AU *)\nSection lemmas.\n  Context `{BiFUpd PROP}.\n\n  Local Existing Instance atomic_update_pre_mono.\n\n  (* Can't be in the section above as that fixes the parameters *)\n  Global Instance atomic_acc_ne {TA TB TC : tele} Eo Ei n :\n    Proper (\n        pointwise_relation TA (dist n) ==>\n        dist n ==>\n        pointwise_relation TC (dist n) ==>\n        pointwise_relation TA (pointwise_relation TB (dist n)) ==>\n        pointwise_relation TA (pointwise_relation TB (dist n)) ==>\n        dist n\n    ) (atomic_acc (PROP:=PROP) Eo Ei).\n  Proof. solve_proper. Qed.\n\n  Global Instance atomic_update_ne {TA TB TC : tele} Eo Ei n :\n    Proper (\n        pointwise_relation TA (dist n) ==>\n        pointwise_relation TC (dist n) ==>\n        pointwise_relation TA (pointwise_relation TB (dist n)) ==>\n        pointwise_relation TA (pointwise_relation TB (dist n)) ==>\n        dist n\n    ) (atomic_update (PROP:=PROP) Eo Ei).\n  Proof.\n    rewrite atomic_update_unseal /atomic_update_def /atomic_update_pre. solve_proper.\n  Qed.\n\n  Lemma atomic_update_mask_weaken {TA TB TC : tele} Eo1 Eo2 Ei \n      (α : TA → PROP) (Ψ : TC → PROP) (β Φ : TA → TB → PROP) :\n    Eo1 ⊆ Eo2 →\n    atomic_update Eo1 Ei α Ψ β Φ -∗ atomic_update Eo2 Ei α Ψ β Φ.\n  Proof.\n    rewrite atomic_update_unseal {2}/atomic_update_def /=.\n    iIntros (Heo) \"HAU\".\n    iApply (greatest_fixpoint_coiter _ (λ _, atomic_update_def Eo1 Ei α Ψ β Φ)); last done.\n    iIntros \"!> *\". rewrite {1}/atomic_update_def /= greatest_fixpoint_unfold.\n    iApply atomic_acc_mask_weaken. done.\n  Qed.\n\n  Lemma atomic_update_wand {TA TB TC : tele} Eo Ei \n    (α : TA → PROP) (Ψ : TC → PROP) (β Φ1 Φ2 : TA → TB → PROP) :\n    (∀.. x y, Φ1 x y -∗ Φ2 x y) -∗\n    (atomic_update Eo Ei α Ψ β Φ1 -∗ atomic_update Eo Ei α Ψ β Φ2).\n  Proof.\n    rewrite atomic_update_unseal {2}/atomic_update_def /=.\n    iIntros \"HΦ Hupd\".\n    iApply (greatest_fixpoint_coiter _ (λ _, (∀.. x y, Φ1 x y -∗ Φ2 x y) ∗ \n      atomic_update_def Eo Ei α Ψ β Φ1\n    )%I); last iFrame.\n    iIntros \"!> * [HΦ Hupd]\". rewrite {1}/atomic_update_def /= greatest_fixpoint_unfold.\n    iApply (atomic_acc_wand with \"[HΦ]\"); last iFrame.\n    iSplit; last done. iIntros; by iFrame.\n  Qed.\n\n  Local Lemma aupd_unfold {TA TB TC : tele} Eo Ei \n      (α : TA → PROP) (Ψ : TC → PROP) (β Φ : TA → TB → PROP) :\n    atomic_update Eo Ei α Ψ β Φ ⊣⊢\n    atomic_acc Eo Ei α (atomic_update Eo Ei α Ψ β Φ) Ψ β Φ.\n  Proof.\n    rewrite atomic_update_unseal /atomic_update_def /=. apply: greatest_fixpoint_unfold.\n  Qed.\n\n  (** The elimination form: an atomic accessor *)\n  Lemma aupd_aacc {TA TB TC : tele} Eo Ei\n      (α : TA → PROP) (Ψ : TC → PROP) (β Φ : TA → TB → PROP) :\n    atomic_update Eo Ei α Ψ β Φ -∗\n    atomic_acc Eo Ei α (atomic_update Eo Ei α Ψ β Φ) Ψ β Φ.\n  Proof using Type*. by rewrite {1}aupd_unfold. Qed.\n\n  (* This lets you eliminate atomic updates with iMod. *)\n  Global Instance elim_mod_aupd {TA TB TC : tele} φ Eo Ei E \n      (α : TA → PROP) (Ψ : TC → PROP) (β Φ : TA → TB → PROP) Q Q' :\n    (∀ R, ElimModal φ false false (|={E,Ei}=> R) R Q Q') →\n    ElimModal (φ ∧ Eo ⊆ E) false false\n              (atomic_update Eo Ei α Ψ β Φ)\n              (∃.. x, α x ∗\n                       (α x ={Ei,E}=∗ atomic_update Eo Ei α Ψ β Φ) ∧\n                       (∀.. y, β x y ={Ei,E}=∗ atomic_post E Ei Ψ (Φ x y)))\n              Q Q'.\n  Proof.\n    intros ?. rewrite /ElimModal /= =>-[??]. iIntros \"[AU Hcont]\".\n    iPoseProof (aupd_aacc with \"AU\") as \"AC\".\n    iMod (atomic_acc_mask_weaken with \"AC\"); first done.\n    iApply \"Hcont\". done.\n  Qed.\n\n  (** The introduction lemma for atomic_update. This should usually not be used\n  directly; use the [iAuIntro] tactic instead. *)\n  Local Lemma aupd_intro {TA TB TC : tele} Eo Ei\n      (α : TA → PROP) P Q (Ψ : TC → PROP) (β Φ : TA → TB → PROP) :\n    Absorbing P → Persistent P →\n    (P ∧ Q -∗ atomic_acc Eo Ei α Q Ψ β Φ) →\n    P ∧ Q -∗ atomic_update Eo Ei α Ψ β Φ.\n  Proof.\n    rewrite atomic_update_unseal {1}/atomic_update_def /=.\n    iIntros (?? HAU) \"[#HP HQ]\".\n    iApply (greatest_fixpoint_coiter _ (λ _, Q)); last done. iIntros \"!>\" ([]) \"HQ\".\n    iApply HAU. iSplit; by iFrame.\n  Qed.\n\n  Lemma aacc_intro {TA TB TC : tele} Eo Ei\n      (α : TA → PROP) P (Ψ : TC → PROP) (β Φ : TA → TB → PROP) :\n    Ei ⊆ Eo → ⊢ (∀.. x, α x -∗ (\n      (α x ={Eo}=∗ P) ∧ \n      (∀.. y, β x y ={Eo}=∗ ∃.. z, Ψ z ∗ (Ψ z -∗ Φ x y))\n    ) -∗\n    atomic_acc Eo Ei α P Ψ β Φ).\n  Proof.\n    iIntros (? x) \"Hα Hclose\".\n    iApply fupd_mask_intro; first set_solver. iIntros \"Hclose'\".\n    iExists x. iFrame. iSplitWith \"Hclose\".\n    - iIntros \"Hα\". iMod \"Hclose'\" as \"_\". iApply \"Hclose\". done.\n    - iIntros (y) \"Hβ\". iMod \"Hclose'\" as \"_\". iMod (\"Hclose\" with \"Hβ\"). \n      iModIntro. by iApply apst_intro.\n  Qed.\n\n  (* This lets you open invariants etc. when the goal is an atomic accessor. *)\n  Global Instance elim_acc_aacc {TA TB TC : tele} {X} E1 E2 Ei\n      (α' β' : X → PROP) γ' \n      (α : TA → PROP) Pas (Ψ : TC → PROP) (β Φ : TA → TB → PROP) :\n    ElimAcc (X:=X) True (fupd E1 E2) (fupd E2 E1) α' β' γ'\n            (atomic_acc E1 Ei α Pas Ψ β Φ)\n            (λ x', \n              atomic_acc E2 Ei α (β' x' ∗ (γ' x' -∗? Pas))%I Ψ β\n              (λ.. x y, β' x' ∗ (γ' x' -∗? atomic_post E1 Ei Ψ (Φ x y)))\n            )%I.\n  Proof.\n    (* FIXME: Is there any way to prevent maybe_wand from unfolding?\n       It gets unfolded by env_cbv in the proofmode, ideally we'd like that\n       to happen only if one argument is a constructor. *)\n    iIntros (_) \"Hinner Hacc\".\n    iMod \"Hacc\" as (x') \"[Hα' Hclose]\".\n    iMod (\"Hinner\" with \"Hα'\") as (x) \"[Hα Hclose']\".\n    iModIntro. iExists x. iFrame \"Hα\". iSplitWith \"Hclose'\".\n    - iIntros \"Hα\".\n      iMod (\"Hclose'\" with \"Hα\") as \"[Hβ' HPas]\".\n      iMod (\"Hclose\" with \"Hβ'\"). iModIntro.\n      by iApply \"HPas\".\n    - iIntros (y) \"Hβ\". \n      iMod (\"Hclose'\" with \"Hβ\") as \"AP\"; rewrite ->!tele_app_bind.\n      iMod (atomic_post_commit with \"AP\") as \"[Hβ' HAP]\".\n      iMod (\"Hclose\" with \"Hβ'\"). iModIntro.\n      by iApply \"HAP\".\n  Qed.\n\n  (* Everything that fancy updates can eliminate without changing, atomic\n  accessors can eliminate as well.  This is a forwarding instance needed because\n  atomic_acc is becoming opaque. *)\n  Global Instance elim_modal_acc {TA TB TC : tele} p q φ P P' Eo Ei \n      (α : TA → PROP) Pas (Ψ : TC → PROP) (β Φ : TA → TB → PROP) :\n    (∀ Q, ElimModal φ p q P P' (|={Eo,Ei}=> Q) (|={Eo,Ei}=> Q)) →\n    ElimModal φ p q P P'\n              (atomic_acc Eo Ei α Pas Ψ β Φ)\n              (atomic_acc Eo Ei α Pas Ψ β Φ).\n  Proof. intros Helim. apply Helim. Qed.\n\n  (** Lemmas for directly proving one atomic accessor in terms of another (or an\n      atomic update).  These are only really useful when the atomic accessor you\n      are trying to prove exactly corresponds to an atomic update/accessor you\n      have as an assumption -- which is not very common. *)\n  Lemma aacc_aacc {TA TB TC TA' TB' TC' : tele} E1 E1' E2 E3\n      (α : TA → PROP) P (Ψ : TC → PROP) (β Φ : TA → TB → PROP)\n      (α' : TA' → PROP) P' (Ψ' : TC' → PROP) (β' Φ' : TA' → TB' → PROP) :\n    E1' ⊆ E1 →\n    atomic_acc E1' E2 α P Ψ β Φ -∗\n    (∀.. x, α x -∗ atomic_acc E2 E3 α' (α x ∗ (P ={E1}=∗ P')) Ψ' β'\n      (λ.. x' y', \n        (α x ∗ (P ={E1}=∗ atomic_post E1 E3 Ψ' (Φ' x' y')))\n        ∨ \n        (∃.. y, β x y ∗ (atomic_post E1 E2 Ψ (Φ x y) ={E1}=∗ atomic_post E1 E3 Ψ' (Φ' x' y')))\n      )) -∗\n    atomic_acc E1 E3 α' P' Ψ' β' Φ'.\n  Proof.\n    iIntros (?) \"Hupd Hstep\".\n    iMod (atomic_acc_mask_weaken with \"Hupd\") as (x) \"[Hα Hclose]\"; first done.\n    iMod (\"Hstep\" with \"Hα\") as (x') \"[Hα' Hclose']\".\n    iModIntro. iExists x'. iFrame \"Hα'\". iSplitWith \"Hclose'\".\n    - iIntros \"Hα'\". \n      iMod (\"Hclose'\" with \"Hα'\") as \"[Hα Hupd]\".\n      iDestruct \"Hclose\" as \"[Hclose _]\".\n      iMod (\"Hclose\" with \"Hα\"). iApply \"Hupd\". done.\n    - iIntros (y') \"Hβ'\".\n      iMod (\"Hclose'\" with \"Hβ'\") as \"HAP\". rewrite ->!tele_app_bind. \n      iMod \"HAP\" as (x'') \"[HΨ' [_ HAP]]\".\n      iMod (\"HAP\" with \"HΨ'\") as \"[[Hα HAP']|Hcont]\".\n      + (* Abort the step we are eliminating *)\n        iDestruct \"Hclose\" as \"[Hclose _]\".\n        iMod (\"Hclose\" with \"Hα\") as \"HP\". by iApply \"HAP'\".\n      + (* Complete the step we are eliminating *)\n        iDestruct \"Hclose\" as \"[_ Hclose]\". iDestruct \"Hcont\" as (y) \"[Hβ HAP']\".\n        iMod (\"Hclose\" with \"Hβ\") as \"HAP\". by iApply \"HAP'\".\n  Qed.\n\n  Lemma aacc_aupd {TA TB TC TA' TB' TC' : tele} E1 E1' E2 E3\n      (α : TA → PROP) (Ψ : TC → PROP) (β Φ : TA → TB → PROP)\n      (α' : TA' → PROP) P' (Ψ' : TC' → PROP) (β' Φ' : TA' → TB' → PROP) :\n    E1' ⊆ E1 →\n    atomic_update E1' E2 α Ψ β Φ -∗\n    (∀.. x, α x -∗ atomic_acc E2 E3 α' (α x ∗ (atomic_update E1' E2 α Ψ β Φ ={E1}=∗ P')) Ψ' β'\n      (λ.. x' y', \n        (α x ∗ (atomic_update E1' E2 α Ψ β Φ ={E1}=∗ atomic_post E1 E3 Ψ' (Φ' x' y')))\n        ∨ \n        ∃.. y, β x y ∗ (atomic_post E1 E2 Ψ (Φ x y) ={E1}=∗ atomic_post E1 E3 Ψ' (Φ' x' y'))\n      )) -∗\n    atomic_acc E1 E3 α' P' Ψ' β' Φ'.\n  Proof.\n    iIntros (?) \"Hupd Hstep\". iApply (aacc_aacc _ E1' with \"[Hupd] Hstep\"); try done.\n    iApply aupd_aacc; done.\n  Qed.\n\n  Lemma aacc_aupd_commit {TA TB TC TA' TB' TC' : tele} E1 E1' E2 E3\n      (α : TA → PROP) (Ψ : TC → PROP) (β Φ : TA → TB → PROP)\n      (α' : TA' → PROP) P' (Ψ' : TC' → PROP) (β' Φ' : TA' → TB' → PROP) :\n    E1' ⊆ E1 →\n    atomic_update E1' E2 α Ψ β Φ -∗\n    (∀.. x, α x -∗ atomic_acc E2 E3 α' (α x ∗ (atomic_update E1' E2 α Ψ β Φ ={E1}=∗ P')) Ψ' β'\n      (λ.. x' y', \n        ∃.. y, β x y ∗ (atomic_post E1 E2 Ψ (Φ x y) ={E1}=∗ atomic_post E1 E3 Ψ' (Φ' x' y'))\n      )) -∗\n    atomic_acc E1 E3 α' P' Ψ' β' Φ'.\n  Proof.\n    iIntros (?) \"Hupd Hstep\". iApply (aacc_aupd with \"Hupd\"); try done.\n    iIntros (x) \"Hα\". iApply atomic_acc_wand; last first.\n    { iApply \"Hstep\". done. }\n    (* FIXME: Using ssreflect rewrite does not work, see Coq bug #7773. *)\n    iSplit; first by eauto. iIntros (??) \"?\". rewrite ->!tele_app_bind. by iRight.\n  Qed.\n\n  Lemma aacc_aupd_abort {TA TB TC TA' TB' TC' : tele} E1 E1' E2 E3\n      (α : TA → PROP) (Ψ : TC → PROP) (β Φ : TA → TB → PROP)\n      (α' : TA' → PROP) P' (Ψ' : TC' → PROP) (β' Φ' : TA' → TB' → PROP) :\n    E1' ⊆ E1 →\n    atomic_update E1' E2 α Ψ β Φ -∗\n    (∀.. x, α x -∗ atomic_acc E2 E3 α' (α x ∗ (atomic_update E1' E2 α Ψ β Φ ={E1}=∗ P')) Ψ' β'\n      (λ.. x' y', \n        (α x ∗ (atomic_update E1' E2 α Ψ β Φ ={E1}=∗ atomic_post E1 E3 Ψ' (Φ' x' y')))\n      )) -∗\n    atomic_acc E1 E3 α' P' Ψ' β' Φ'.\n  Proof.\n    iIntros (?) \"Hupd Hstep\". iApply (aacc_aupd with \"Hupd\"); try done.\n    iIntros (x) \"Hα\". iApply atomic_acc_wand; last first.\n    { iApply \"Hstep\". done. }\n    (* FIXME: Using ssreflect rewrite does not work, see Coq bug #7773. *)\n    iSplit; first by eauto. iIntros (??) \"?\". rewrite ->!tele_app_bind. by iLeft.\n  Qed.\n\n  Lemma apst_aupd_sup {TA TB TC TC' : tele} E1 E1' E2 E3\n      (α : TA → PROP) (Ψ : TC → PROP) (β Φ : TA → TB → PROP)\n      (Ψ' : TC' → PROP) (Φ' : PROP)\n      (R : PROP) :\n    E1' ⊆ E1 → E3 ⊆ E2 →\n    R -∗\n    □ (∀.. x, R ∗ α x -∗ ∃.. z', (Ψ' z' ∗ (Ψ' z' -∗ R ∗ α x))) -∗\n    atomic_update E1' E2 α Ψ β Φ -∗\n    (R ∗ atomic_update E1' E2 α Ψ β Φ ={E1}=∗ Φ') -∗\n    atomic_post E1 E3 Ψ' Φ'.\n  Proof.\n    iIntros (??) \"HR #HRαΨ' AU Hstep\".\n    rewrite atomic_post_unseal /atomic_post_def /=.\n    iApply (greatest_fixpoint_coiter _ (λ _, (R ∗ atomic_update E1' E2 α Ψ β Φ ∗\n      (R ∗ atomic_update E1' E2 α Ψ β Φ ={E1}=∗ Φ')\n    )%I)); last iFrame.\n    iIntros \"!> * [HR [AU Hstep]]\".\n    iMod (atomic_update_mask_weaken with \"AU\") as (x) \"[Hα [Hclose _]]\"; first done.\n    iApply fupd_mask_intro; first done. iIntros \"Hclose'\".\n    iDestruct (\"HRαΨ'\" with \"[$]\") as (z') \"[HΨ' HRα]\".\n    iExists z'. iFrame \"HΨ'\". \n    iSplit; iIntros \"HΨ'\"; iMod \"Hclose'\" as \"_\";\n      iDestruct (\"HRα\" with \"HΨ'\") as \"[HR Hα]\"; iMod (\"Hclose\" with \"Hα\");\n      last iApply \"Hstep\"; by iFrame.\n  Qed.\n\n  Lemma apst_aupd_sub {TA TB TC TC' : tele} E1 E1' E2 E3\n      (α : TA → PROP) (Ψ : TC → PROP) (β Φ : TA → TB → PROP)\n      (Ψ' : TC' → PROP) (Φ' : PROP) :\n    E1' ⊆ E1 → E3 ⊆ E2 →\n    □ (∀.. x, α x -∗ ∃.. z', (Ψ' z' ∗ (Ψ' z' -∗ α x))) -∗\n    atomic_update E1' E2 α Ψ β Φ -∗\n    (atomic_update E1' E2 α Ψ β Φ ={E1}=∗ Φ') -∗\n    atomic_post E1 E3 Ψ' Φ'.\n  Proof.\n    iIntros (??) \"#HαΨ' AU Hstep\".\n    rewrite atomic_post_unseal /atomic_post_def /=.\n    iApply (greatest_fixpoint_coiter _ (λ _, (atomic_update E1' E2 α Ψ β Φ ∗\n      (atomic_update E1' E2 α Ψ β Φ ={E1}=∗ Φ')\n    )%I)); last iFrame.\n    iIntros \"!> * [AU Hstep]\".\n    iMod (atomic_update_mask_weaken with \"AU\") as (x) \"[Hα [Hclose _]]\"; first done.\n    iApply fupd_mask_intro; first done. iIntros \"Hclose'\".\n    iDestruct (\"HαΨ'\" with \"Hα\") as (z') \"[HΨ' Hα]\".\n    iExists z'. iFrame \"HΨ'\". \n    iSplit; iIntros \"HΨ'\"; iMod \"Hclose'\" as \"_\";\n      iDestruct (\"Hα\" with \"HΨ'\") as \"Hα\"; iMod (\"Hclose\" with \"Hα\");\n      last iApply \"Hstep\"; by iFrame.\n  Qed.\n\n  Lemma aacc_aupd_sup {TA TB TA' TB' TC' : tele} E1 E1' E2 E3\n      (α : TA → PROP) (β Φ : TA → TB → PROP)\n      (α' : TA' → PROP) P' (Ψ' : TC' → PROP) (β' Φ' : TA' → TB' → PROP)\n      (R : PROP) :\n    E1' ⊆ E1 → E3 ⊆ E2 →\n    R -∗\n    □ (∀.. x, R ∗ α x -∗ ∃.. z', (Ψ' z' ∗ (Ψ' z' -∗ R ∗ α x))) -∗\n    atomic_update E1' E2 α α β Φ -∗\n    (∀.. x, R ∗ α x -∗ atomic_acc E2 E3 α' (α x ∗ (atomic_update E1' E2 α α β Φ ={E1}=∗ P')) Ψ' β'\n      (λ.. x' y', \n        (R ∗ α x ∗ (R ∗ atomic_update E1' E2 α α β Φ ={E1}=∗ Φ' x' y'))\n        ∨ \n        ∃.. y, R ∗ β x y ∗ (R ∗ atomic_post E1 E2 α (Φ x y) ={E1}=∗ Φ' x' y')\n      )) -∗\n    atomic_acc E1 E3 α' P' Ψ' β' Φ'.\n  Proof.\n    iIntros (??) \"HR #HRαΨ' Hupd Hstep\".\n    iMod (atomic_update_mask_weaken with \"Hupd\") as (x) \"[Hα Hclose]\"; first done.\n    iMod (\"Hstep\" with \"[$]\") as (x') \"[Hα' Hclose']\".\n    iModIntro. iExists x'. iFrame \"Hα'\". iSplitWith \"Hclose'\".\n    - iIntros \"Hα'\". \n      iMod (\"Hclose'\" with \"Hα'\") as \"[Hα Hupd]\".\n      iDestruct \"Hclose\" as \"[Hclose _]\".\n      iMod (\"Hclose\" with \"Hα\"). iApply \"Hupd\". iFrame.\n    - iIntros (y') \"Hβ'\".\n      iMod (\"Hclose'\" with \"Hβ'\") as \"HAP\". rewrite ->!tele_app_bind. \n      iMod \"HAP\" as (z') \"[HΨ' [_ HAP]]\".\n      iMod (\"HAP\" with \"HΨ'\") as \"[[HR [Hα HAP']]|Hcont]\".\n      + (* Abort the step we are eliminating *)\n        iDestruct \"Hclose\" as \"[Hclose _]\".\n        iMod (\"Hclose\" with \"Hα\") as \"HAP\". iModIntro.\n        iApply (apst_aupd_sup with \"HR [] HAP\"); try done.\n      + (* Complete the step we are eliminating *)\n        iDestruct \"Hclose\" as \"[_ Hclose]\". iDestruct \"Hcont\" as (y) \"[HR [Hβ HAP']]\".\n        iMod (\"Hclose\" with \"Hβ\") as \"HAP\". iModIntro.\n        iApply (apst_apst_sup with \"HR [] HAP\"); try done.\n  Qed.\n\n  Lemma aacc_aupd_sub {TA TB TA' TB' TC' : tele} E1 E1' E2 E3\n      (α : TA → PROP) (β Φ : TA → TB → PROP)\n      (α' : TA' → PROP) P' (Ψ' : TC' → PROP) (β' Φ' : TA' → TB' → PROP) :\n    E1' ⊆ E1 → E3 ⊆ E2 →\n    □ (∀.. x, α x -∗ ∃.. z', (Ψ' z' ∗ (Ψ' z' -∗ α x))) -∗\n    atomic_update E1' E2 α α β Φ -∗\n    (∀.. x, α x -∗ atomic_acc E2 E3 α' (α x ∗ (atomic_update E1' E2 α α β Φ ={E1}=∗ P')) Ψ' β'\n      (λ.. x' y', \n        (α x ∗ (atomic_update E1' E2 α α β Φ ={E1}=∗ Φ' x' y'))\n        ∨ \n        ∃.. y, β x y ∗ (atomic_post E1 E2 α (Φ x y) ={E1}=∗ Φ' x' y')\n      )) -∗\n    atomic_acc E1 E3 α' P' Ψ' β' Φ'.\n  Proof.\n    iIntros (??) \"#HαΨ' Hupd Hstep\".\n    iMod (atomic_update_mask_weaken with \"Hupd\") as (x) \"[Hα Hclose]\"; first done.\n    iMod (\"Hstep\" with \"Hα\") as (x') \"[Hα' Hclose']\".\n    iModIntro. iExists x'. iFrame \"Hα'\". iSplitWith \"Hclose'\".\n    - iIntros \"Hα'\". \n      iMod (\"Hclose'\" with \"Hα'\") as \"[Hα Hupd]\".\n      iDestruct \"Hclose\" as \"[Hclose _]\".\n      iMod (\"Hclose\" with \"Hα\"). iApply \"Hupd\". iFrame.\n    - iIntros (y') \"Hβ'\".\n      iMod (\"Hclose'\" with \"Hβ'\") as \"HAP\". rewrite ->!tele_app_bind. \n      iMod \"HAP\" as (z') \"[HΨ' [_ HAP]]\".\n      iMod (\"HAP\" with \"HΨ'\") as \"[[Hα HAP']|Hcont]\".\n      + (* Abort the step we are eliminating *)\n        iDestruct \"Hclose\" as \"[Hclose _]\".\n        iMod (\"Hclose\" with \"Hα\") as \"HAP\". iModIntro.\n        iApply (apst_aupd_sub with \"[] HAP\"); try done.\n      + (* Complete the step we are eliminating *)\n        iDestruct \"Hclose\" as \"[_ Hclose]\". iDestruct \"Hcont\" as (y) \"[Hβ HAP']\".\n        iMod (\"Hclose\" with \"Hβ\") as \"HAP\". iModIntro.\n        iApply (apst_apst_sub with \"[] HAP\"); try done.\n  Qed.\n\n  Lemma aacc_aupd_eq {TA TB TB' : tele} E1 E1' E2 E3\n      (α : TA → PROP) (β Φ : TA → TB → PROP)\n      P' (β' Φ' : TA → TB' → PROP) :\n    E1' ⊆ E1 → E3 ⊆ E2 →\n    atomic_update E1' E2 α α β Φ -∗\n    (∀.. x, α x -∗ atomic_acc E2 E3 α (α x ∗ (atomic_update E1' E2 α α β Φ ={E1}=∗ P')) α β'\n      (λ.. x' y', \n        (α x ∗ (atomic_update E1' E2 α α β Φ ={E1}=∗ Φ' x' y'))\n        ∨ \n        ∃.. y, β x y ∗ (atomic_post E1 E2 α (Φ x y) ={E1}=∗ Φ' x' y')\n      )) -∗\n    atomic_acc E1 E3 α P' α β' Φ'.\n  Proof.\n    iIntros (??) \"AU Hstep\".\n    iApply (aacc_aupd_sub with \"[] AU Hstep\"); try done.\n    iIntros \"!> %x Hα\". iExists x. iFrame; by iIntros.\n  Qed.\n\n  Lemma aacc_apst_sub {TC TA' TB' TC' : tele} E1 E1' E2 E3\n      (Ψ : TC → PROP) Φ\n      (α' : TA' → PROP) P (Ψ' : TC' → PROP) (β' Φ' : TA' → TB' → PROP) :\n    E1' ⊆ E1 → E3 ⊆ E2 →\n    □ (∀.. z, Ψ z -∗ ∃.. z', (Ψ' z' ∗ (Ψ' z' -∗ Ψ z))) -∗\n    atomic_post E1' E2 Ψ Φ -∗\n    (∀.. z, Ψ z -∗ atomic_acc E2 E3 α' (Ψ z ∗ (atomic_post E1' E2 Ψ Φ ={E1}=∗ P)) Ψ' β'\n      (λ.. x' y', \n        (Ψ z ∗ (atomic_post E1' E2 Ψ Φ ={E1}=∗ Φ' x' y'))\n      )) -∗\n    atomic_acc E1 E3 α' P Ψ' β' Φ'.\n  Proof.\n    iIntros (??) \"#HαΨ' Hpst Hstep\".\n    iMod (atomic_post_mask_weaken with \"Hpst\") as (x) \"[HΨ Hclose]\"; first done.\n    iMod (\"Hstep\" with \"HΨ\") as (x') \"[Hα' Hclose']\".\n    iModIntro. iExists x'. iFrame \"Hα'\". iSplitWith \"Hclose'\".\n    - iIntros \"Hα'\". \n      iMod (\"Hclose'\" with \"Hα'\") as \"[Hα Hupd]\".\n      iDestruct \"Hclose\" as \"[Hclose _]\".\n      iMod (\"Hclose\" with \"Hα\"). iApply \"Hupd\". iFrame.\n    - iIntros (y') \"Hβ'\".\n      iMod (\"Hclose'\" with \"Hβ'\") as \"HAP\". rewrite ->!tele_app_bind. \n      iMod \"HAP\" as (z') \"[HΨ' [_ HAP]]\".\n      iMod (\"HAP\" with \"HΨ'\") as \"[HΨ HAP']\".\n      iDestruct \"Hclose\" as \"[Hclose _]\".\n      iMod (\"Hclose\" with \"HΨ\") as \"HAP\". iModIntro.\n      iApply (apst_apst_sub with \"[] HAP\"); try done.\n  Qed.\n\n  Lemma aacc_apst_eq {TC TA' TB' TC' : tele} E1 E1' E2 E3\n      (Ψ : TC → PROP) Φ\n      (α' : TA' → PROP) P (β' Φ' : TA' → TB' → PROP) :\n    E1' ⊆ E1 → E3 ⊆ E2 →\n    atomic_post E1' E2 Ψ Φ -∗\n    (∀.. z, Ψ z -∗ atomic_acc E2 E3 α' (Ψ z ∗ (atomic_post E1' E2 Ψ Φ ={E1}=∗ P)) Ψ β'\n      (λ.. x' y', \n        (Ψ z ∗ (atomic_post E1' E2 Ψ Φ ={E1}=∗ Φ' x' y'))\n      )) -∗\n    atomic_acc E1 E3 α' P Ψ β' Φ'.\n  Proof.\n    iIntros (??) \"Hpst Hstep\".\n    iApply (aacc_apst_sub with \"[] Hpst Hstep\"); try done.\n    iIntros \"!> %z HΨ\". iExists z. iFrame; by iIntros.\n  Qed.\n\nEnd lemmas.\n\n(** ProofMode support for atomic updates. *)\nSection proof_mode.\n  Context `{BiFUpd PROP} {TA TB TC : tele}.\n  Implicit Types (α : TA → PROP) (β Φ : TA → TB → PROP) (Ψ : TC → PROP) (P : PROP).\n\n  Lemma tac_aupd_intro Γp Γs n α β Ψ Eo Ei Φ P :\n    P = env_to_prop Γs →\n    envs_entails (Envs Γp Γs n) (atomic_acc Eo Ei α P Ψ β Φ) →\n    envs_entails (Envs Γp Γs n) (atomic_update Eo Ei α Ψ β Φ).\n  Proof.\n    intros ->. rewrite envs_entails_unseal of_envs_eq /atomic_acc /=.\n    setoid_rewrite env_to_prop_sound =>HAU.\n    rewrite assoc. apply: aupd_intro. by rewrite -assoc.\n  Qed.\nEnd proof_mode.\n\n(** * Now the coq-level tactics *)\n\nTactic Notation \"iAuIntro\" :=\n  match goal with\n  | |- envs_entails (Envs ?Γp ?Γs _) (atomic_update _ _ _ _ _ ?Φ) =>\n      notypeclasses refine (tac_aupd_intro Γp Γs _ _ _ _ _ _ Φ _ _ _); [\n        (* P = ...: make the P pretty *) pm_reflexivity\n      | (* the new proof mode goal *) ]\n  end.\n\n(** Tactic to apply [aacc_intro]. This only really works well when you have\n[α ?] already and pass it as [iAaccIntro with \"Hα\"]. Doing\n[rewrite /atomic_acc /=] is an entirely legitimate alternative. *)\nTactic Notation \"iAaccIntro\" \"with\" constr(sel) :=\n  iStartProof; lazymatch goal with\n  | |- envs_entails _ (@atomic_acc ?PROP ?H ?TA ?TB ?TC ?Eo ?Ei ?α ?P ?Ψ ?β ?Φ) =>\n    iApply (@aacc_intro PROP H TA TB TC Eo Ei α P Ψ β Φ with sel);\n    first try solve_ndisj; last iSplit\n  | _ => fail \"iAaccIntro: Goal is not an atomic accessor\"\n  end.\n\nLemma aupd_inv `{!irisGS_gen hlc Λ Σ} {TA TB : tele} E\n  (α : TA → iProp Σ) (β Q Φ : TA → TB → iProp Σ) \n  I N :\n  ↑N ⊆ E →\n  inv N I -∗\n  atomic_update (E ∖ ↑N) ∅ \n    α \n    α \n    β \n    (λ.. x y, Q x y ={E ∖ ↑N}=∗ Φ x y) -∗\n  atomic_update E ∅ \n    (λ.. x, ▷I ∗ α x)\n    (λ.. x, ▷I ∗ α x)\n    (λ.. x y, ▷I ∗ β x y) \n    (λ.. x y, Q x y ={E}=∗ Φ x y).\nProof.\n  iIntros (HN) \"#Hinv AU\".\n  rewrite {2}atomic_update_unseal /atomic_update_def /=.\n  iApply (greatest_fixpoint_coiter _ (\n    λ _, (atomic_update (E ∖ ↑N) ∅ α α β (λ.. x y, Q x y ={E ∖ ↑N}=∗ Φ x y))%I\n  )); last iFrame.\n  iIntros \"!> * AU\". iInv N as \"HI\" \"Hclose'\".\n  iMod \"AU\" as (x) \"[Hα Hclose]\".\n  iModIntro. iExists x. rewrite ->!tele_app_bind.\n  iFrame. iSplitWith \"Hclose\".\n  + iIntros \"[HI Hα]\". iMod (\"Hclose\" with \"Hα\") as \"AU\".\n    by iMod (\"Hclose'\" with \"HI\") as \"_\".\n  + clear y; iIntros (y). rewrite ->!tele_app_bind.\n    iIntros \"[HI Hβ]\". iMod (\"Hclose\" with \"Hβ\") as \"AP\".\n    rewrite ->!tele_app_bind.\n    iMod (\"Hclose'\" with \"HI\") as \"_\". iModIntro.\n\n    rewrite {2}atomic_post_unseal /atomic_post_def /=.\n    iApply (greatest_fixpoint_coiter _ (\n      λ _, (atomic_post (E ∖ ↑N) ∅ α (Q x y ={E ∖ ↑N}=∗ Φ x y))%I\n    )); last iFrame.\n    iIntros \"!> * AP\". iInv N as \"HI\" \"Hclose'\".\n    iMod \"AP\" as (z) \"[Hα Hclose]\".\n    iModIntro. iExists z. rewrite ->!tele_app_bind.\n    iFrame. iSplitWith \"Hclose\"; iIntros \"[HI Hα]\";\n      iMod (\"Hclose\" with \"Hα\") as \"HΦ\";\n      iMod (\"Hclose'\" with \"HI\") as \"_\"; first done.\n    iModIntro. iIntros \"HQ\".\n    iApply fupd_mask_mono; last by iApply \"HΦ\". solve_ndisj.\nQed.\n\nLemma aupd_inv_timeless `{!irisGS_gen hlc Λ Σ} {TA TB : tele} E\n  (α : TA → iProp Σ) (β Q Φ : TA → TB → iProp Σ) \n  I N `{!Timeless I} :\n  ↑N ⊆ E →\n  inv N I -∗\n  atomic_update (E ∖ ↑N) ∅ \n    α \n    α \n    β \n    (λ.. x y, Q x y ={E ∖ ↑N}=∗ Φ x y) -∗\n  atomic_update E ∅ \n    (λ.. x, I ∗ α x)\n    (λ.. x, I ∗ α x)\n    (λ.. x y, I ∗ β x y) \n    (λ.. x y, Q x y ={E}=∗ Φ x y).\nProof.\n  iIntros (HN) \"#Hinv AU\".\n  rewrite {2}atomic_update_unseal /atomic_update_def /=.\n  iApply (greatest_fixpoint_coiter _ (\n    λ _, (atomic_update (E ∖ ↑N) ∅ α α β (λ.. x y, Q x y ={E ∖ ↑N}=∗ Φ x y))%I\n  )); last iFrame.\n  iIntros \"!> * AU\". iInv N as \">HI\" \"Hclose'\".\n  iMod \"AU\" as (x) \"[Hα Hclose]\".\n  iModIntro. iExists x. rewrite ->!tele_app_bind.\n  iFrame. iSplitWith \"Hclose\".\n  + iIntros \"[HI Hα]\". iMod (\"Hclose\" with \"Hα\") as \"AU\".\n    by iMod (\"Hclose'\" with \"HI\") as \"_\".\n  + clear y; iIntros (y). rewrite ->!tele_app_bind.\n    iIntros \"[HI Hβ]\". iMod (\"Hclose\" with \"Hβ\") as \"AP\".\n    rewrite ->!tele_app_bind.\n    iMod (\"Hclose'\" with \"HI\") as \"_\". iModIntro.\n\n    rewrite {2}atomic_post_unseal /atomic_post_def /=.\n    iApply (greatest_fixpoint_coiter _ (\n      λ _, (atomic_post (E ∖ ↑N) ∅ α (Q x y ={E ∖ ↑N}=∗ Φ x y))%I\n    )); last iFrame.\n    iIntros \"!> * AP\". iInv N as \">HI\" \"Hclose'\".\n    iMod \"AP\" as (z) \"[Hα Hclose]\".\n    iModIntro. iExists z. rewrite ->!tele_app_bind.\n    iFrame. iSplitWith \"Hclose\"; iIntros \"[HI Hα]\";\n      iMod (\"Hclose\" with \"Hα\") as \"HΦ\";\n      iMod (\"Hclose'\" with \"HI\") as \"_\"; first done.\n    iModIntro. iIntros \"HQ\".\n    iApply fupd_mask_mono; last by iApply \"HΦ\". solve_ndisj.\nQed.", "meta": {"author": "sr-lab", "repo": "iris-jellyfish", "sha": "51ef73143ae06731ec48740c481961cf41c595fb", "save_path": "github-repos/coq/sr-lab-iris-jellyfish", "path": "github-repos/coq/sr-lab-iris-jellyfish/iris-jellyfish-51ef73143ae06731ec48740c481961cf41c595fb/atomic/update.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2145528662715974}}
{"text": "\nRequire Import VST.floyd.proofauto.\nRequire Import listfree.\nFrom SSL_VST Require Import core.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition free_spec :=\n  DECLARE _free\n          WITH ty: type, x: val\n                              PRE  [ (tptr tvoid) ]\n                              PROP()\n                              PARAMS(x)\n                              SEP (data_at_ Tsh ty x)\n                              POST [ Tvoid ]\n                              PROP()\n                              LOCAL()\n                              SEP (emp).\n\nInductive lseg_card : Set :=\n    | lseg_card_0 : lseg_card\n    | lseg_card_1 : lseg_card -> lseg_card.\n\nFixpoint lseg (x: val) (s: (list Z)) (self_card: lseg_card) {struct self_card} : mpred := match self_card with\n    | lseg_card_0  =>  !!((x : val) = nullval) && !!((s : list Z) = ([] : list Z)) && emp\n    | lseg_card_1 _alpha_513 => \n      EX v : Z,\n      EX s1 : (list Z),\n      EX nxt : val,\n !!(Int.min_signed <= v <= Int.max_signed) && !!(is_pointer_or_null nxt) && !!(~ ((x : val) = nullval)) && !!((s : list Z) = (([(v : Z)] : list Z) ++ (s1 : list Z))) && (data_at Tsh (tarray (Tunion _sslval noattr) 2) [(inl ((Vint (Int.repr v)) : val)); (inr (nxt : val))] (x : val)) * (lseg (nxt : val) (s1 : list Z) (_alpha_513 : lseg_card))\nend.\n\nInductive lseg2_card : Set :=\n    | lseg2_card_0 : lseg2_card\n    | lseg2_card_1 : lseg2_card -> lseg2_card.\n\nFixpoint lseg2 (x: val) (y: val) (s: (list Z)) (self_card: lseg2_card) {struct self_card} : mpred := match self_card with\n    | lseg2_card_0  =>  !!((x : val) = (y : val)) && !!((s : list Z) = ([] : list Z)) && emp\n    | lseg2_card_1 _alpha_514 => \n      EX v : Z,\n      EX s1 : (list Z),\n      EX nxt : val,\n !!(Int.min_signed <= v <= Int.max_signed) && !!(is_pointer_or_null nxt) && !!(~ ((x : val) = (y : val))) && !!((s : list Z) = (([(v : Z)] : list Z) ++ (s1 : list Z))) && (data_at Tsh (tarray (Tunion _sslval noattr) 2) [(inl ((Vint (Int.repr v)) : val)); (inr (nxt : val))] (x : val)) * (lseg2 (nxt : val) (y : val) (s1 : list Z) (_alpha_514 : lseg2_card))\nend.\n\n\nDefinition listfree_spec :=\n  DECLARE _listfree\n   WITH x: val, s: (list Z), _alpha_515: lseg_card\n   PRE [ (tptr (Tunion _sslval noattr)) ]\n   PROP( is_pointer_or_null((x : val)) )\n   PARAMS(x)\n   SEP ((lseg (x : val) (s : list Z) (_alpha_515 : lseg_card)))\n   POST[ tvoid ]\n   PROP(  )\n   LOCAL()\n   SEP ().\n\nLemma lseg_x_valid_pointerP x s self_card: lseg x s self_card |-- valid_pointer x. Proof. destruct self_card; simpl; entailer;  entailer!; eauto. Qed.\nHint Resolve lseg_x_valid_pointerP : valid_pointer.\nLemma lseg_local_factsP x s self_card :\n  lseg x s self_card|-- !!(((((x : val) = nullval)) -> (self_card = lseg_card_0))/\\(((~ ((x : val) = nullval))) -> (exists _alpha_513, self_card = lseg_card_1 _alpha_513))/\\is_pointer_or_null((x : val))).\n Proof.  destruct self_card;  simpl; entailer; saturate_local; apply prop_right; eauto. Qed.\nHint Resolve lseg_local_factsP : saturate_local.\nLemma unfold_lseg_card_0  (x: val) (s: (list Z)) : lseg x s (lseg_card_0 ) =  !!((x : val) = nullval) && !!((s : list Z) = ([] : list Z)) && emp. Proof. auto. Qed.\nLemma unfold_lseg_card_1 (_alpha_513 : lseg_card) (x: val) (s: (list Z)) : lseg x s (lseg_card_1 _alpha_513) = \n      EX v : Z,\n      EX s1 : (list Z),\n      EX nxt : val,\n !!(Int.min_signed <= v <= Int.max_signed) && !!(is_pointer_or_null nxt) && !!(~ ((x : val) = nullval)) && !!((s : list Z) = (([(v : Z)] : list Z) ++ (s1 : list Z))) && (data_at Tsh (tarray (Tunion _sslval noattr) 2) [(inl ((Vint (Int.repr v)) : val)); (inr (nxt : val))] (x : val)) * (lseg (nxt : val) (s1 : list Z) (_alpha_513 : lseg_card)). Proof. auto. Qed.\nLemma lseg2_local_factsP x y s self_card :\n  lseg2 x y s self_card|-- !!(((((x : val) = (y : val))) -> (self_card = lseg2_card_0))/\\(((~ ((x : val) = (y : val)))) -> (exists _alpha_514, self_card = lseg2_card_1 _alpha_514))).\n Proof.  destruct self_card;  simpl; entailer; saturate_local; apply prop_right; eauto. Qed.\nHint Resolve lseg2_local_factsP : saturate_local.\nLemma unfold_lseg2_card_0  (x: val) (y: val) (s: (list Z)) : lseg2 x y s (lseg2_card_0 ) =  !!((x : val) = (y : val)) && !!((s : list Z) = ([] : list Z)) && emp. Proof. auto. Qed.\nLemma unfold_lseg2_card_1 (_alpha_514 : lseg2_card) (x: val) (y: val) (s: (list Z)) : lseg2 x y s (lseg2_card_1 _alpha_514) = \n      EX v : Z,\n      EX s1 : (list Z),\n      EX nxt : val,\n !!(Int.min_signed <= v <= Int.max_signed) && !!(is_pointer_or_null nxt) && !!(~ ((x : val) = (y : val))) && !!((s : list Z) = (([(v : Z)] : list Z) ++ (s1 : list Z))) && (data_at Tsh (tarray (Tunion _sslval noattr) 2) [(inl ((Vint (Int.repr v)) : val)); (inr (nxt : val))] (x : val)) * (lseg2 (nxt : val) (y : val) (s1 : list Z) (_alpha_514 : lseg2_card)). Proof. auto. Qed.\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [listfree_spec; free_spec]).\n\nLemma body_listfree : semax_body Vprog Gprog f_listfree listfree_spec.\nProof.\nstart_function.\nssl_open_context.\nforward_if.\n\n - {\nassert_PROP (_alpha_515 = lseg_card_0) as ssl_card_assert. { entailer!; ssl_dispatch_card. }\nssl_card lseg ssl_card_assert .\nassert_PROP (((x : val) = nullval)). { entailer!. }\nlet ssl_var := fresh in assert_PROP(s = ([] : list Z)) as ssl_var; try rewrite ssl_var in *. { entailer!. }\nforward; entailer!.\n\n}\n - {\nassert_PROP (exists _alpha_513, _alpha_515 = lseg_card_1 _alpha_513) as ssl_card_assert. { entailer!; ssl_dispatch_card. }\nssl_card lseg ssl_card_assert _alpha_513x.\nassert_PROP ((~ ((x : val) = nullval))). { entailer!. }\nIntros vx s1x nxtx.\nlet ssl_var := fresh in assert_PROP(s = (([(vx : Z)] : list Z) ++ (s1x : list Z))) as ssl_var; try rewrite ssl_var in *. { entailer!. }\ntry rename vx into vx2.\nforward.\ntry rename nxtx into nxtx2.\nforward.\nassert_PROP(is_pointer_or_null((nxtx2 : val))). { entailer!. }\nforward_call ((nxtx2 : val), (s1x : list Z), (_alpha_513x : lseg_card)).\nforward_call (tarray (Tunion _sslval noattr) 2, x).\nforward; entailer!.\n\n}\nQed.", "meta": {"author": "TyGuS", "repo": "ssl-vst", "sha": "638107b15e18608ef364ae1d900eb2d2aaf8a475", "save_path": "github-repos/coq/TyGuS-ssl-vst", "path": "github-repos/coq/TyGuS-ssl-vst/ssl-vst-638107b15e18608ef364ae1d900eb2d2aaf8a475/examples/verif_listfree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21455286627159736}}
{"text": "(* Do not edit this file, it was generated automatically *)\nRequire Import VST.floyd.proofauto.\nRequire Import VST.progs64.append.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\nDefinition t_struct_list := Tstruct _list noattr.\n\n\nFixpoint listrep (sh: share)\n            (contents: list val) (x: val) : mpred :=\n match contents with\n | h::hs =>\n              EX y:val,\n                data_at sh t_struct_list (h,y) x * listrep sh hs y\n | nil => !! (x = nullval) && emp\n end.\n\nArguments listrep sh contents x : simpl never.\n\nLemma listrep_local_facts:\n  forall sh contents p,\n     listrep sh contents p |--\n     !! (is_pointer_or_null p /\\ (p=nullval <-> contents=nil)).\nProof.\nintros.\nrevert p; induction contents; \n  unfold listrep; fold listrep; intros. entailer!. intuition.\nIntros y. entailer!.\nsplit; intro. subst p. destruct H; contradiction. inv H2.\nQed.\n\n#[export] Hint Resolve listrep_local_facts : saturate_local.\n\nLemma listrep_valid_pointer:\n  forall sh contents p,\n   sepalg.nonidentity sh ->\n   listrep sh contents p |-- valid_pointer p.\nProof.\n destruct contents; unfold listrep; fold listrep; intros; Intros; subst.\n auto with valid_pointer.\n Intros y.\n apply sepcon_valid_pointer1.\n apply data_at_valid_ptr; auto.\n simpl;  computable.\nQed.\n\n#[export] Hint Resolve listrep_valid_pointer : valid_pointer.\n\nLemma listrep_null: forall sh contents,\n    listrep sh contents nullval = !! (contents=nil) && emp.\nProof.\ndestruct contents; unfold listrep; fold listrep.\nautorewrite with norm. auto.\napply pred_ext.\nIntros y. entailer. destruct H; contradiction.\nIntros. discriminate.\nQed.\n\nLemma is_pointer_or_null_not_null:\n forall x, is_pointer_or_null x -> x <> nullval -> isptr x.\nProof.\nintros.\n destruct x; try contradiction. hnf in H; subst i. contradiction H0; reflexivity.\n apply I.\nQed.\n\nDefinition append_spec :=\n DECLARE _append\n  WITH sh : share, x: val, y: val, s1: list val, s2: list val\n  PRE [ tptr t_struct_list , tptr t_struct_list]\n     PROP(writable_share sh)\n     PARAMS (x; y) GLOBALS()\n     SEP (listrep sh s1 x; listrep sh s2 y)\n  POST [ tptr t_struct_list ]\n    EX r: val,\n     PROP()\n     RETURN (r)\n     SEP (listrep sh (s1++s2) r).\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [ append_spec ]).\n\nModule Proof1.\n\nDefinition lseg (sh: share) (contents: list val) (x z: val) : mpred :=\n  ALL cts2:list val, listrep sh cts2 z -* listrep sh (contents++cts2) x.\n\nLemma body_append: semax_body Vprog Gprog f_append append_spec.\nProof.\nstart_function.\nforward_if.\n*\n subst x. rewrite listrep_null.  Intros.  subst.\n forward.\n Exists y.\n entailer!.\n simpl; auto.\n*\n forward.\n destruct s1 as [ | v s1']; unfold listrep at 1; fold listrep.\n Intros.  contradiction.\n Intros u.\n remember (v::s1') as s1.\n forward.\n forward_while\n      ( EX a: val, EX s1b: list val, EX t: val, EX u: val,\n            PROP ()\n            LOCAL (temp _x x; temp _t t; temp _u u; temp _y y)\n            SEP (listrep sh (a::s1b++s2) t -* listrep sh (s1++s2) x;\n                   data_at sh t_struct_list (a,u) t;\n                   listrep sh s1b u;\n                   listrep sh s2 y))%assert.\n+ (* current assertion implies loop invariant *)\n   Exists v s1' x u.\n   subst s1. entailer!. simpl. cancel_wand.\n+ (* loop test is safe to execute *)\n   entailer!.\n+ (* loop body preserves invariant *)\n   clear v Heqs1.\n   destruct s1b; unfold listrep at 3; fold listrep. Intros. contradiction.\n   Intros z.\n   forward.\n   forward.\n   Exists (v,s1b,u0,z). unfold fst, snd.\n   simpl app.\n   entailer!.\n   rewrite sepcon_comm.\n   apply RAMIF_PLAIN.trans''.\n   apply wand_sepcon_adjoint.\n   forget (v::s1b++s2) as s3.\n   unfold listrep; fold listrep; Exists u0; auto.\n+ (* after the loop *)\n   clear v s1' Heqs1.\n   forward.\n   forward.\n   rewrite (proj1 H2 (eq_refl _)).\n   Exists x.\n   simpl app.\n   clear.\n   entailer!.\n   unfold listrep at 3; fold listrep. Intros.\n   pull_right (listrep sh (a :: s2) t -* listrep sh (s1 ++ s2) x).\n   apply modus_ponens_wand'.\n   unfold listrep at 2; fold listrep. Exists y; cancel.\nQed.\n\nEnd Proof1.\n\nModule Proof2.\n\nDefinition lseg (sh: share) (contents: list val) (x z: val) : mpred :=\n  ALL cts2:list val, listrep sh cts2 z -* listrep sh (contents++cts2) x.\n\nLemma body_append: semax_body Vprog Gprog f_append append_spec.\nProof.\nstart_function.\nforward_if.\n*\n subst x. rewrite listrep_null. Intros; subst. \n forward.\n Exists y.\n entailer!.\n simpl; auto.\n*\n forward.\n destruct s1 as [ | v s1']; unfold listrep; fold listrep. Intros; contradiction.\n Intros u.\n remember (v::s1') as s1.\n forward.\n forward_while\n      (EX s1a: list val,  EX a: val, EX s1b: list val, EX t: val, EX u: val,\n            PROP (s1 = s1a ++ a :: s1b)\n            LOCAL (temp _x x; temp _t t; temp _u u; temp _y y)\n            SEP (lseg sh s1a x t;\n                   data_at sh t_struct_list (a,u) t;\n                   listrep sh s1b u;\n                   listrep sh s2 y))%assert.\n+ (* current assertion implies loop invariant *)\n   Exists (@nil val) v s1' x u.  entailer!.\n   unfold lseg. apply allp_right; intro. simpl. cancel_wand.\n+ (* loop test is safe to execute *)\n   entailer!.\n+ (* loop body preserves invariant *)\n   clear v Heqs1. subst s1.\n   destruct s1b; unfold listrep; fold listrep. Intros; contradiction.\n   Intros z.\n   forward.\n   forward.\n   Exists (s1a++[a],v,s1b,u0,z). unfold fst, snd.\n   rewrite !app_ass. simpl app.\n   entailer!.\n   unfold lseg.\n   rewrite sepcon_comm.\n   clear.\n   apply RAMIF_Q.trans'' with (cons a).\n   extensionality cts; simpl; rewrite app_ass; reflexivity.\n   apply allp_right; intro. apply wand_sepcon_adjoint.\n   unfold listrep at 2; fold listrep; Exists u0.  apply derives_refl.\n + (* after the loop *)\n   forward. forward.\n   Exists x. entailer!.\n   destruct H3 as [? _]. specialize (H3 (eq_refl _)). subst s1b.\n   unfold listrep at 1.  Intros. autorewrite with norm.  rewrite H0. rewrite app_ass. simpl app.\n   unfold lseg.\n   rewrite sepcon_assoc.\n   eapply derives_trans; [apply allp_sepcon1 | ]. apply allp_left with (a::s2).\n   rewrite sepcon_comm.\n   eapply derives_trans; [ | apply modus_ponens_wand].\n   apply sepcon_derives; [ | apply derives_refl].\n   unfold listrep at 2; fold listrep. Exists y; auto.\nQed.\n\nEnd Proof2.\n\nModule Proof3.  (*************** inductive lseg *******************)\n\nFixpoint lseg (sh: share)\n            (contents: list val) (x z: val) : mpred :=\n match contents with\n | h::hs => !! (x<>z) && \n              EX y:val,\n                data_at sh t_struct_list (h,y) x * lseg sh hs y z\n | nil => !! (x = z /\\ is_pointer_or_null x) && emp\n end.\n\nArguments lseg sh contents x z : simpl never.\n\nLemma lseg_local_facts:\n  forall sh contents p q,\n     lseg sh contents p q |--\n     !! (is_pointer_or_null p /\\ is_pointer_or_null q /\\ (p=q <-> contents=nil)).\nProof.\nintros.\napply derives_trans with (lseg sh contents p q && !! (is_pointer_or_null p /\\\n        is_pointer_or_null q /\\ (p = q <-> contents = []))).\n2: entailer!.\nrevert p; induction contents; intros; simpl; unfold lseg; fold lseg.\nentailer!.\nintuition.\nIntros y. Exists y.\neapply derives_trans.\napply sepcon_derives.\napply derives_refl.\napply IHcontents.\nentailer!.\nintuition congruence.\nQed.\n\n#[export] Hint Resolve lseg_local_facts : saturate_local.\n\nLemma lseg_valid_pointer:\n  forall sh contents p ,\n   sepalg.nonidentity sh ->\n   lseg sh contents p nullval |-- valid_pointer p.\nProof.\n destruct contents; unfold lseg; fold lseg; intros. entailer!.\n Intros. Intros y.\n auto with valid_pointer.\nQed.\n\n#[export] Hint Resolve lseg_valid_pointer : valid_pointer.\n\nLemma lseg_eq: forall sh contents x,\n    lseg sh contents x x = !! (contents=nil /\\ is_pointer_or_null x) && emp.\nProof.\nintros.\ndestruct contents; unfold lseg; fold lseg.\nf_equal. f_equal. f_equal. apply prop_ext; intuition.\napply pred_ext.\nIntros y. contradiction.\nIntros. discriminate.\nQed.\n\nLemma lseg_null: forall sh contents,\n    lseg sh contents nullval nullval = !! (contents=nil) && emp.\nProof.\nintros.\n rewrite lseg_eq.\n apply pred_ext.\n entailer!.\n entailer!.\nQed.\n\nLemma lseg_cons: forall sh (v u x: val) s,\n   readable_share sh ->\n data_at sh t_struct_list (v, u) x * lseg sh s u nullval\n |-- lseg sh [v] x u * lseg sh s u nullval.\nProof.\nintros.\n     unfold lseg at 2. Exists u. \n     entailer.\n     destruct s; unfold lseg at 1; fold lseg; entailer.\nQed.\n\nLemma lseg_cons': forall sh (v u x a b: val) ,\n   readable_share sh ->\n data_at sh t_struct_list (v, u) x * data_at sh t_struct_list (a,b) u\n |-- lseg sh [v] x u * data_at sh t_struct_list (a,b) u.\nProof.\nintros.\n     unfold lseg. Exists u. \n     entailer.\nQed.\n\nLemma lseg_app': forall sh s1 s2 (a w x y z: val),\n   readable_share sh ->\n   lseg sh s1 w x * lseg sh s2 x y * data_at sh t_struct_list (a,z) y |--\n   lseg sh (s1++s2) w y * data_at sh t_struct_list (a,z) y.\nProof.\n intros.\n revert w; induction s1; intro; simpl.\n unfold lseg at 1. entailer!.\n unfold lseg at 1 3; fold lseg. Intros j; Exists j.\n entailer.\n sep_apply (IHs1 j).\n cancel. \nQed.\n\nLemma lseg_app_null: forall sh s1 s2 (w x: val),\n   readable_share sh ->\n   lseg sh s1 w x * lseg sh s2 x nullval |--\n   lseg sh (s1++s2) w nullval.\nProof.\n intros.\n revert w; induction s1; intro; simpl.\n unfold lseg at 1. entailer!.\n unfold lseg at 1 3; fold lseg. Intros j; Exists j.\n entailer.\n sep_apply (IHs1 j).\n cancel.\nQed.\n\nLemma lseg_app: forall sh s1 s2 a s3 (w x y z: val),\n   readable_share sh ->\n   lseg sh s1 w x * lseg sh s2 x y * lseg sh (a::s3) y z |--\n   lseg sh (s1++s2) w y * lseg sh (a::s3) y z.\nProof.\n intros.\n unfold lseg at 3 5; fold lseg.\n Intros u; Exists u. rewrite prop_true_andp by auto.\n sep_apply (lseg_app' sh s1 s2 a w x y u); auto.\n cancel.\nQed.\n\nLemma listrep_lseg_null :\n listrep = fun sh s p => lseg sh s p nullval.\nProof.\nextensionality sh s p.\nrevert p.\ninduction s; intros.\nunfold lseg, listrep; apply pred_ext; entailer!.\nunfold lseg, listrep; fold lseg; fold listrep.\napply pred_ext; Intros y; Exists y; rewrite IHs; entailer!.\nQed.\n\nLemma body_append: semax_body Vprog Gprog f_append append_spec.\nProof.\nstart_function.\nrevert POSTCONDITION; rewrite listrep_lseg_null; intro.\nforward_if.\n*\n subst x. rewrite lseg_null. Intros. subst.\n forward.\n Exists y.\n entailer!.\n simpl; auto.\n*\n forward.\n destruct s1 as [ | v s1']; unfold lseg at 1; fold lseg.\n Intros. contradiction H.\n Intros u.\n clear - SH.\n remember (v::s1') as s1.\n forward.\n forward_while\n      (EX s1a: list val, EX a: val, EX s1b: list val, EX t: val, EX u: val,\n            PROP (s1 = s1a ++ a :: s1b)\n            LOCAL (temp _x x; temp _t t; temp _u u; temp _y y)\n            SEP (lseg sh s1a x t; \n                   data_at sh t_struct_list (a,u) t;\n                   lseg sh s1b u nullval; \n                   lseg sh s2 y nullval))%assert.\n + (* current assertion implies loop invariant *)\n     Exists (@nil val) v s1' x u.\n     subst s1. rewrite lseg_eq.\n     entailer.\n(*     sep_apply (lseg_cons sh v u x s1'); auto. *)\n + (* loop test is safe to execute *)\n     entailer!.\n + (* loop body preserves invariant *)\n    destruct s1b; unfold lseg at 2; fold lseg.\n    Intros. contradiction.\n    Intros z.\n    forward.\n    forward.\n    Exists (s1a++a::nil, v0, s1b,u0,z). unfold fst, snd.\n    simpl app; rewrite app_ass.\n    entailer.\n    sep_apply (lseg_cons' sh a u0 t v0 z); auto.\n    sep_apply (lseg_app' sh s1a [a] v0 x t u0 z); auto.\n    cancel.\n + (* after the loop *)\n    clear v s1' Heqs1.\n    subst. rewrite lseg_eq. Intros. subst. \n    forward.\n    forward.\n    Exists x. \n    entailer!.\n    sep_apply (lseg_cons sh a y t s2); auto.\n    sep_apply (lseg_app_null sh [a] s2 t y); auto.\n    rewrite app_ass.\n    sep_apply (lseg_app_null sh s1a ([a]++s2) x t); auto.\nQed.\n\nEnd Proof3.\n\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/progs64/verif_append2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.21455286627159736}}
{"text": "Require Import RelationClasses. \nRequire Import List.\nRequire Import Omega.\nRequire Import sflib.\nFrom Paco Require Import paco.\nRequire Import Basics.\n\nRequire Import Basic.\nRequire Import Axioms.\nRequire Import Loc.\nRequire Import Language.\nRequire Import ZArith.\nRequire Import Maps.\n\nRequire Import FSets.\nRequire Import FSetInterface.\nRequire Import Lattice.\nRequire Import Event.\nRequire Import Syntax.\nRequire Import Semantics.\nRequire Import Kildall.\nRequire Import Coqlib.\n\nRequire Import Integers.\nRequire Import LibTactics.\nRequire Import ValAnalysis.\nRequire Import CorrectOpt.\nSet Implicit Arguments.\n\n(** * Constant Propagation *)\n\n(** Constant propagation first uses value analysis to analyze program and\n    then translates program according to the result of analysis. *)\n\n(** ** Transformation for the Single Instruction *)\nDefinition transform_inst (inst: Inst.t) (ae: ValLat.t) : Inst.t :=\n  match inst with\n  | Inst.assign r e =>\n    match (eval_expr_ae e (fst ae)) with\n    | LVal.VAL v => Inst.assign r (Inst.expr_val v)\n    | _ => Inst.assign r e\n    end\n  | Inst.load r loc or =>\n    match or with\n    | Ordering.plain =>\n      match (VALSET.get loc (snd ae)) with\n      | LVal.VAL v => Inst.assign r (Inst.expr_val v)\n      | _ => Inst.load r loc or\n      end\n    | _ => Inst.load r loc or\n    end\n  | _ => inst\n  end.\n\nLemma eval_expr_ae_bot_to_val_false:\n  forall expr n,\n    eval_expr_ae expr VALSET.bot = LVal.VAL n -> False.\nProof.\n  induction expr; ss; eauto.\nQed.\n\nLemma transform_inst_bot\n      inst:\n  transform_inst inst ValDS.AI.bot = inst.\nProof.\n  destruct inst; eauto.\n  ss. destruct (eval_expr_ae rhs VALSET.bot) eqn:Heqe; ss; eauto.\n  eapply eval_expr_ae_bot_to_val_false in Heqe; eauto. ss.\n  ss. destruct or; ss; eauto.\nQed.\n\n(** ** Transformation for the basic block *)\nFixpoint transform_blk (ae_blk: ValDS.AI.b) (b_s: BBlock.t) {struct b_s}: BBlock.t :=\n  match b_s, ae_blk with\n  | i##b_s', ValDS.AI.Cons ae ae_blk' =>\n    (transform_inst i ae)##(transform_blk ae_blk' b_s')\n  | _, _ => b_s\n  end.\n\nLemma transform_blk_bot':\n  forall BB,\n    transform_blk ValDS.AI.bots BB = BB.\nProof.\n  destruct BB; ss; eauto.\nQed.\n\nLemma transform_blk_bot:\n  forall BB,\n    transform_blk (transf_blk ValDS.AI.bot BB) BB = transform_blk ValDS.AI.bots BB.\nProof.\n  induction BB; try solve [ss; eauto].\n  assert (transf_blk ValDS.AI.bot (c ## BB) =\n          ValDS.AI.Cons ValDS.AI.bot (transf_blk (transf_instr c ValDS.AI.bot) BB)). eauto.\n  assert (transf_instr c ValDS.AI.bot = ValDS.AI.bot).\n  eapply transf_instr_bot; eauto.\n  rewrite H0 in H; clear H0.\n  rewrite H. clear H.\n  simpl. rewrite IHBB.\n  rewrite transform_inst_bot.\n  rewrite transform_blk_bot'. eauto.\nQed.\n\n(** ** Transformation for the code heap *)\nDefinition transform_cdhp (cdhp: CodeHeap) (analysis: ValDS.AI.ACdhp): CodeHeap := \n  PTree.map (fun (i: positive) (b: BBlock.t) => transform_blk (analysis!!i) b) cdhp.\n\nLemma transform_cdhp_prop\n      C_src BB_src f afunc\n      (GET: C_src ! f = Some BB_src):\n  exists BB_tgt, (transform_cdhp C_src afunc) ! f = Some BB_tgt.\nProof.\n  unfold transform_cdhp.\n  rewrite PTree.gmap. unfold option_map.\n  rewrite GET. eauto.\nQed.\n\n(** ** Code transformation for a function *)\nDefinition transform_func (func: Func): option Func :=\n  match ValDS.analyze_func func succ ValLat.top transf_blk with\n  | Some analysis =>\n    let (cdhp, fid) := func in Some (transform_cdhp cdhp analysis, fid)\n  (* transformation error, since there is no analysis result *)\n  | None => None\n  end.\n\n(** ** Code transformation for a program *)\n(** [transform_prog] translates each function in the program according to [transform_func]. *)\nFixpoint transform_prog (prog: Code): option Code :=\n  match prog with\n  | PTree.Leaf => Some PTree.Leaf\n  | PTree.Node prog1 None prog2 =>\n    match (transform_prog prog1), (transform_prog prog2) with\n    | Some progt1, Some progt2 => Some (PTree.Node progt1 None progt2)\n    | _, _ => None\n    end\n  | PTree.Node prog1 (Some func) prog2 =>\n    match transform_func func with\n    | Some func_t =>\n      match (transform_prog prog1), (transform_prog prog2) with\n      | Some progt1, Some progt2 => Some (PTree.Node progt1 (Some func_t) progt2)\n      | _, _ => None\n      end\n    | None => None\n    end\n  end.\n\nLemma transform_prog_proper:\n  forall prog_s prog_t fid func_s\n    (TRANS_FORM: transform_prog prog_s = Some prog_t)\n    (FUNC: prog_s ! fid = Some func_s),\n  exists func_t, prog_t ! fid = Some func_t /\\ transform_func func_s = Some func_t.\nProof.\n  induction prog_s; ss; ii.\n  - rewrite PTree.gleaf in FUNC. tryfalse.\n  - destruct fid; ss.\n    + destruct o; ss.\n      destruct (transform_func f) eqn:TRANS_FUNC; ss.\n      destruct (transform_prog prog_s1) eqn:TRANS_PROG1; ss.\n      destruct (transform_prog prog_s2) eqn:TRANS_PROG2; ss.\n      inv TRANS_FORM.\n      eapply IHprog_s2 in FUNC; eauto.\n      destruct (transform_prog prog_s1) eqn:TRANS_PROG1; ss.\n      destruct (transform_prog prog_s2) eqn:TRANS_PROG2; ss.\n      inv TRANS_FORM.\n      eapply IHprog_s2 in FUNC; eauto.\n    + destruct o; ss.\n      destruct (transform_func f) eqn:TRANS_FUNC; ss.\n      destruct (transform_prog prog_s1) eqn:TRANS_PROG1; ss.\n      destruct (transform_prog prog_s2) eqn:TRANS_PROG2; ss.\n      inv TRANS_FORM.\n      eapply IHprog_s1 in FUNC; eauto.\n      destruct (transform_prog prog_s1) eqn:TRANS_PROG1; ss.\n      destruct (transform_prog prog_s2) eqn:TRANS_PROG2; ss.\n      inv TRANS_FORM.\n      eapply IHprog_s1 in FUNC; eauto.\n    + subst; ss.\n      destruct (transform_func func_s) eqn:TRANS_FUNC; ss.\n      destruct (transform_prog prog_s1) eqn:TRANS_PROG1; ss.\n      destruct (transform_prog prog_s2) eqn:TRANS_PROG2; ss.\n      inv TRANS_FORM.\n      exists f. split; eauto.\nQed.\n\nLemma transform_prog_proper_none:\n  forall prog_s prog_t fid\n    (TRANS_FORM: transform_prog prog_s = Some prog_t)\n    (FUNC: prog_s ! fid = None),\n    prog_t ! fid = None.\nProof.\n  induction prog_s; ss; ii.\n  - inv TRANS_FORM. rewrite PTree.gleaf; eauto.\n  - destruct fid; ss.\n    + destruct o; ss.\n      destruct (transform_func f) eqn:TRANS_FUNC; ss.\n      destruct (transform_prog prog_s1) eqn:TRANS_PROG1; ss.\n      destruct (transform_prog prog_s2) eqn:TRANS_PROG2; ss.\n      inv TRANS_FORM; eauto.\n      destruct (transform_prog prog_s1) eqn:TRANS_PROG1; ss.\n      destruct (transform_prog prog_s2) eqn:TRANS_PROG2; ss.\n      inv TRANS_FORM; eauto.\n    + destruct o; ss.\n      destruct (transform_func f) eqn:TRANS_FUNC; ss.\n      destruct (transform_prog prog_s1) eqn:TRANS_PROG1; ss.\n      destruct (transform_prog prog_s2) eqn:TRANS_PROG2; ss.\n      inv TRANS_FORM; eauto.\n      destruct (transform_prog prog_s1) eqn:TRANS_PROG1; ss.\n      destruct (transform_prog prog_s2) eqn:TRANS_PROG2; ss.\n      inv TRANS_FORM; eauto.\n    + destruct o; ss.\n      destruct (transform_prog prog_s1) eqn:TRANS_PROG1; ss.\n      destruct (transform_prog prog_s2) eqn:TRANS_PROG2; ss.\n      inv TRANS_FORM; eauto.\nQed.\n\nLemma transform_func_init\n      c_s f_s c_t f_t B_t\n      (TRANS_FUNC: transform_func (c_s, f_s) = Some (c_t, f_t))\n      (ENTRY_BB_T: c_t ! f_t = Some B_t):\n  exists B_s ab, c_s ! f_s = Some B_s /\\\n            ValDS.analyze_func (c_s, f_s) succ ValLat.top transf_blk = Some ab /\\\n            transform_cdhp c_s ab = c_t /\\ f_s = f_t.\nProof.\n  unfold transform_func in *.\n  destruct (ValDS.analyze_func (c_s, f_s) succ ValLat.top transf_blk) eqn:ANALYSIS; tryfalse.\n  inv TRANS_FUNC. unfold transform_cdhp in ENTRY_BB_T.\n  rewrite PTree.gmap in ENTRY_BB_T.\n  unfold option_map in ENTRY_BB_T.\n  destruct (c_s ! f_t) eqn:Heqe; tryfalse.\n  exists t a. split; eauto.\nQed.\n\nLemma transf_cdhp_prop\n      C_src C_tgt afunc BB_tgt f f_s ep\n      (ANALYSIS_FUNC: ValDS.analyze_func (C_src, f_s) succ ep transf_blk = Some afunc)\n      (TRANS_CDHP: transform_cdhp C_src afunc = C_tgt)\n      (BB: C_tgt ! f = Some BB_tgt):\n  exists BB_src ae_pblk,\n    C_src ! f = Some BB_src /\\\n    transf_blk (ValDS.AI.getFirst (afunc !! f)) BB_src = ae_pblk /\\\n    transform_blk ae_pblk BB_src = BB_tgt /\\\n    (forall s BB_src',\n        In s (succ BB_src) -> C_src ! s = Some BB_src' ->  \n        ValDS.L.ge (ValDS.AI.getFirst (afunc !! s)) (ValDS.AI.getLast ae_pblk)).\nProof.\n  unfold transform_cdhp in TRANS_CDHP.\n  subst. rewrite PTree.gmap in BB.\n  unfold option_map in BB. destruct (C_src ! f) eqn:BB_SRC; ss.\n  inv BB. renames t to BB_src.\n  do 2 eexists. splits; eauto.\n  - exploit ValDS.analyze_func_solution_get; [ | | eapply ANALYSIS_FUNC | eauto..].\n    eapply transf_blk_first; eauto.\n    eapply transf_blk_bot; eauto.\n    i. des1. rewrite H. eauto.\n    rewrite H; ss.\n    rewrite transform_blk_bot. eauto.\n  - ii.\n    eapply ValDS.analyze_func_solution1 in ANALYSIS_FUNC; eauto.\n    ii. eapply transf_blk_first; eauto.\n    ii. eapply transf_blk_bot; eauto.\nQed.\n\n(** ** The Implementation of Constant propagation *)\nDefinition constprop_optimizer: Optimizer rtl_lang :=\n  fun (lo: Ordering.LocOrdMap) (prog_s: Code) => transform_prog prog_s.\n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/rtl/optimizer/ConstProp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2145055134810661}}
{"text": "Require Import Events. (*is needed for some definitions (loc_unmapped etc*)\nRequire Import Memory.\nRequire Import Coqlib.\nRequire Import Integers.\nRequire Import compcert.common.Values.\nRequire Import Maps.\nRequire Import Axioms.\n\nRequire Import FiniteMaps.\nRequire Import sepcomp.mem_lemmas.\nRequire Import sepcomp.mem_interpolation_defs.\n\nDefinition AccessMap_EI_Property (j:meminj) (m1 m1' m2 : mem)\n           (AM:ZMap.t (Z -> perm_kind -> option permission)):Prop :=\n  forall b2,\n    (Mem.valid_block m2 b2 -> forall k ofs2,\n       match j b2 with\n         None => PMap.get b2 AM ofs2 k  =\n                        PMap.get b2 m2.(Mem.mem_access) ofs2 k\n       | Some (b3,d3) =>\n          (Mem.perm m1 b2 ofs2 Max Nonempty ->\n           PMap.get b2 AM ofs2 k = PMap.get b2 m1'.(Mem.mem_access) ofs2 k)\n       /\\ (~Mem.perm m1 b2 ofs2 Max Nonempty ->\n           PMap.get b2 AM ofs2 k  = PMap.get b2 m2.(Mem.mem_access) ofs2 k)\n     end)\n  /\\ (~ Mem.valid_block m2 b2 -> forall k ofs2,\n         (Mem.perm m1' b2 ofs2 Max Nonempty ->\n           PMap.get b2 AM ofs2 k = PMap.get b2 m1'.(Mem.mem_access) ofs2 k)\n       /\\ (~Mem.perm m1' b2 ofs2 Max Nonempty -> PMap.get b2 AM ofs2 k = None)).\n\nDefinition Content_EI_Property (j:meminj) (m1 m1' m2:Mem.mem)\n                               (CM:ZMap.t (ZMap.t memval)):=\n  forall b2,\n      (Mem.valid_block m2 b2 -> forall ofs2,\n             match j b2 with\n               None =>  ZMap.get ofs2 (PMap.get b2 CM) =\n                           ZMap.get ofs2 (PMap.get b2 m2.(Mem.mem_contents))\n             | Some (b3,delta3) =>\n                     (Mem.perm m1 b2 ofs2 Max Nonempty ->\n                            ZMap.get ofs2 (PMap.get b2 CM) =\n                           ZMap.get ofs2 (PMap.get b2 m1'.(Mem.mem_contents)))\n                 /\\ (~Mem.perm m1 b2 ofs2 Max Nonempty ->\n                          ZMap.get ofs2 (PMap.get b2 CM) =\n                         ZMap.get ofs2 (PMap.get b2 m2.(Mem.mem_contents)))\n            end)\n    /\\ (~ Mem.valid_block m2 b2 -> forall (HM1': Mem.valid_block m1' b2) ofs2,\n           (Mem.perm m1' b2 ofs2 Cur Readable ->\n                ZMap.get ofs2 (PMap.get b2 CM) =\n                ZMap.get ofs2 (PMap.get b2 m1'.(Mem.mem_contents)))\n        /\\ (~Mem.perm m1' b2 ofs2 Cur Readable ->\n                ZMap.get ofs2 (PMap.get b2 CM) =Undef))\n    /\\ fst CM !! b2 = Undef.\n\nLemma EI_ok: forall (m1 m2 m1':mem)\n               (Ext12: Mem.extends m1 m2)\n               (Fwd1: mem_forward m1 m1') m3 j\n               (Inj23: Mem.inject j m2 m3)\n               m3' (Fwd3: mem_forward m3 m3') j'\n               (Inj13': Mem.inject j' m1' m3')\n               (UnchOn3: Mem.unchanged_on (loc_out_of_reach j m1) m3 m3')\n               (InjInc: inject_incr j j') (injSep: inject_separated j j' m1 m3)\n               (UnchOn1: Mem.unchanged_on (loc_unmapped j) m1 m1') m2'\n               (NB: m2'.(Mem.nextblock)=m1'.(Mem.nextblock))\n               (CONT: Content_EI_Property j m1 m1' m2 (m2'.(Mem.mem_contents)))\n               (ACCESS: AccessMap_EI_Property j m1 m1' m2 (m2'.(Mem.mem_access))),\n        mem_forward m2 m2' /\\\n               Mem.extends m1' m2' /\\\n               Mem.inject j' m2' m3' /\\\n               Mem.unchanged_on (loc_out_of_bounds m1) m2 m2' /\\\n               Mem.unchanged_on (loc_unmapped j) m2 m2'.\nProof. intros.\nassert (VB' : forall b : block, Mem.valid_block m1' b = Mem.valid_block m2' b).\n  intros; unfold Mem.valid_block. rewrite NB. trivial.\nassert (Inj13:= Mem.extends_inject_compose _ _ _ _ Ext12 Inj23).\nassert (MMU_LU: Mem.unchanged_on (loc_unmapped j) m2 m2' ).\n   split. intros.\n       destruct (ACCESS b) as [Val _].\n        specialize (Val H0 k ofs). rewrite H in Val.\n        rewrite (perm_subst _ _ _ _ _ _ _ Val). split; auto.\n    intros. assert (Val2:= Mem.perm_valid_block _ _ _ _ _ H0).\n        destruct (CONT b) as [ContVal _]. rewrite H in ContVal.\n        apply (ContVal Val2 ofs).\nassert (Fwd2: mem_forward m2 m2').\n    split; intros.\n     (*valid_block*) apply (Mem.valid_block_extends _ _ b Ext12) in H.\n        apply Fwd1 in H. destruct H as[H _]. rewrite <- VB'. apply H.\n      (*max*)\n      apply (valid_split _ _ _ _  (ACCESS b)); clear ACCESS; intros.\n           specialize (H2 Max ofs).\n           remember (j b) as jb.\n           destruct jb; apply eq_sym in Heqjb.\n                destruct p0.\n                apply (perm_split _ _ _ _ _ _ _ H2); clear H2; intros.\n                    rewrite (perm_subst _ _ _ _ _ _ _ H3) in *. clear H3.\n                    unfold Mem.perm. rewrite po_oo in *.\n                       eapply po_trans. apply (extends_permorder _ _ Ext12).\n                       destruct (Fwd1 b). apply (Mem.perm_valid_block _ _ _ _ _ H2).\n                       apply (H4 ofs _ H0).\n                   rewrite (perm_subst _ _ _ _ _ _ _ H3) in *. apply H0.\n            rewrite (perm_subst _ _ _ _ _ _ _ H2) in *. apply H0.\n      exfalso. apply (H1 H).\nassert (MMU_LOOB: Mem.unchanged_on (loc_out_of_bounds m1) m2 m2').\n   split; intros.\n      apply (valid_split _ _ _ _  (ACCESS b)); clear ACCESS; intros.\n         specialize (H2 k ofs).\n         remember (j b) as jb.\n         destruct jb; apply eq_sym in Heqjb.\n              destruct p0.\n              destruct H2 as [_ NoMax].\n              rewrite (perm_subst _ _ _ _ _ _ _ (NoMax H)).\n              split; auto.\n         rewrite (perm_subst _ _ _ _ _ _ _ H2) in *.\n           split; auto.\n      contradiction.\n  destruct (CONT b) as [ValC _].\n       destruct (ACCESS b) as [ValA _].\n       specialize (ValC (Mem.perm_valid_block _ _ _ _ _ H0) ofs).\n       specialize (ValA (Mem.perm_valid_block _ _ _ _ _ H0) Cur ofs).\n       unfold loc_out_of_bounds in H.\n       remember (j b) as jb.\n       destruct jb; apply eq_sym in Heqjb.\n          destruct p.\n          eapply (perm_split _ _ _ _ _ _ _ ValC); clear ValC; intros.\n             exfalso. apply H. apply H1.\n         apply H2.\n      apply ValC.\nsplit; trivial.\nassert (Ext12':  Mem.extends m1' m2').\n    split.\n    (*nextblock*)\n        rewrite NB. trivial.\n    (*mem_inj*)\n         assert (Perm12': forall b ofs k p, Mem.perm m1' b ofs k p ->\n                                            Mem.perm m2' b ofs k p).\n              intros.\n              apply (valid_split _ _ _ _  (ACCESS b)); clear ACCESS; intros.\n                  assert (Val1: Mem.valid_block m1 b).\n                     apply (Mem.valid_block_extends _ _ _ Ext12). apply H0.\n                  assert (Perm1: Mem.perm m1 b ofs Max Nonempty).\n                        apply Fwd1. apply Val1.\n                        eapply Mem.perm_max. eapply Mem.perm_implies.\n                        apply H. constructor.\n                  specialize (H1 k ofs).\n                  remember (j b) as jb.\n                  destruct jb; apply eq_sym in Heqjb.\n                     destruct p0.\n                     apply (perm_split _ _ _ _ _ _ _ H1); clear H1; intros.\n                        rewrite (perm_subst _ _ _ _ _ _ _ H2). assumption.\n                      exfalso. apply (H1 Perm1). (*rewrite (perm_subst _ _ _ _ _ _ _ H2). assumption.*)\n            rewrite (perm_subst _ _ _ _ _ _ _ H1) in *. clear H1.\n                 destruct UnchOn1 as [UP _].\n                 eapply (extends_perm _ _ Ext12).\n                 rewrite (UP _ _ _ p Heqjb Val1). apply H.\n             destruct (H1 k ofs) as [Val _]; clear H1.\n                  assert (Perm1: Mem.perm m1' b ofs Max Nonempty).\n                          eapply Mem.perm_max. eapply Mem.perm_implies.\n                          apply H. constructor.\n                  rewrite (perm_subst _ _ _ _ _ _ _ (Val Perm1)). assumption.\n         split.\n         (*mi_perm*) intros. inv H. rewrite Zplus_0_r.\n                     apply (Perm12' _ _ _ _ H0).\n         (*mi_align*) intros. inv H. apply Z.divide_0_r.\n         (*mi_memval *) intros. inv H. rewrite Zplus_0_r.\n            destruct (CONT b2) as [ContVal [ContInval Default]]; clear CONT.\n            apply (valid_split _ _ _ _  (ACCESS b2)); clear ACCESS; intros.\n                clear ContInval.\n                assert (Perm: Mem.perm m1 b2 ofs Max Nonempty).\n                    clear H1 ContVal. apply Fwd1.\n                     apply (Mem.valid_block_extends _ _ _ Ext12). apply H.\n                    eapply Mem.perm_max. eapply Mem.perm_implies.\n                       apply H0. constructor.\n               specialize (ContVal H ofs). specialize (H1 Cur ofs).\n                  remember (j b2) as jb2.\n                  destruct jb2; apply eq_sym in Heqjb2.\n                          destruct p.\n                          destruct ContVal as [Cont _]. rewrite (Cont Perm). clear Cont.\n                          apply memval_inject_id_refl.\n                  rewrite ContVal. clear ContVal.\n                         destruct UnchOn1 as [UP UV].\n                         apply (Mem.valid_block_extends _ _ _ Ext12) in H.\n                         rewrite <- (UP _ _ _ _ Heqjb2 H) in H0.\n                         rewrite (UV _ _ Heqjb2 H0).\n                         specialize (Mem.mi_memval _ _ _ (Mem.mext_inj _ _\n                                      Ext12) b2 ofs _ _ (eq_refl _) H0).\n                         rewrite Zplus_0_r; trivial.\n                assert (VB1':= Mem.perm_valid_block _ _ _ _ _ H0).\n                destruct (ContInval H VB1' ofs) as [Cont _].\n                  clear ContVal ContInval.\n                  rewrite (Cont H0); clear Cont.\n                  apply memval_inject_id_refl.\nsplit; trivial.\nassert (Inj23': Mem.inject j' m2' m3').\n    assert (MI: Mem.mem_inj j' m2' m3').\n        assert (MiPerm: forall b1 b2 delta ofs k p,  j' b1 = Some (b2, delta) ->\n                       Mem.perm m2' b1 ofs k p ->\n                       Mem.perm m3' b2 (ofs + delta) k p).\n          intros.\n          assert (NP: Mem.perm m2' b1 ofs Max Nonempty).\n            eapply Mem.perm_max. eapply Mem.perm_implies. apply H0. constructor.\n          apply (valid_split _ _ _ _  (ACCESS b1)); clear ACCESS; intros.\n              assert (Val1: Mem.valid_block m1 b1).\n                 apply (Mem.valid_block_extends _ _ _ Ext12). apply H1.\n              assert (J: j b1 = Some (b2, delta)).\n                  remember (j b1) as d. destruct d; apply eq_sym in Heqd.\n                    destruct p0. rewrite (InjInc _ _ _ Heqd) in H.  apply H.\n                  destruct (injSep _ _ _ Heqd H). exfalso. apply (H3 Val1).\n              rewrite J in H2.\n              destruct (H2 Max ofs) as [Perm2'MaxP Perm2'MaxNop].\n              specialize (H2 k ofs).\n              apply (perm_split _ _ _ _ _ _ _ H2); clear H2; intros.\n                  clear Perm2'MaxNop.\n                  rewrite (perm_subst _ _ _ _ _ _ _ H3) in *; clear H3.\n                  eapply Inj13'. apply H. apply H0.\n              clear Perm2'MaxP.\n                  rewrite (perm_subst _ _ _ _ _ _ _ H3) in *; clear H3.\n                  rewrite (perm_subst _ _ _ _ _ _ _ (Perm2'MaxNop H2)) in *;\n                          clear Perm2'MaxNop.\n                  destruct UnchOn3 as [U3Perm _].\n                  assert (loc_out_of_reach j m1 b2 (ofs + delta)).\n                        unfold loc_out_of_reach; intros. intros N.\n                           destruct (eq_block b0 b1); subst.\n                               rewrite H3 in J; inv J.\n                               assert (ofs + delta - delta = ofs). omega.\n                               rewrite H4 in N. apply (H2 N).\n                           assert (N2: Mem.perm m2 b0 (ofs + delta - delta0)\n                                       Max Nonempty).\n                               specialize (Mem.mi_perm _ _ _ (Mem.mext_inj _ _  Ext12) b0 b0 Z0\n                                                      (ofs + delta - delta0)). rewrite Zplus_0_r. intros.\n                               apply (H4 _ _ (eq_refl _) N).\n                           destruct (Mem.mi_no_overlap _ _ _ Inj23 _ _\n                                                 _ _ _ _ _ _ n H3 J N2 NP).\n                              apply H4; trivial.\n                              apply H4. omega.\n                  assert (Val3:=Mem.valid_block_inject_2 _ _ _ _ _ _ J Inj23).\n              rewrite <- (U3Perm _ _ _ p H3 Val3).\n                eapply Inj23. apply J. apply H0.\n          assert (NVal1: ~Mem.valid_block m1 b1). intros N. apply H1.\n                 apply (Mem.valid_block_extends _ _ _ Ext12). apply N.\n          assert (J: j b1 = None).\n              remember (j b1) as d. destruct d; apply eq_sym in Heqd; trivial.\n                  destruct p0. exfalso. apply H1.\n                     apply (Mem.valid_block_inject_1 _ _ _ _ _ _ Heqd Inj23).\n          destruct (H2 Max ofs) as [Perm2'MaxP Perm2'MaxNop].\n          specialize (H2 k ofs).\n          apply (perm_split _ _ _ _ _ _ _ H2); clear H2; intros.\n              clear Perm2'MaxNop.\n              rewrite (perm_subst _ _ _ _ _ _ _ H3) in *; clear H3.\n              rewrite (perm_subst _ _ _ _ _ _ _ (Perm2'MaxP H2)) in NP;\n                      clear Perm2'MaxP.\n              eapply Inj13'. apply H. apply H0.\n          clear Perm2'MaxP.\n              unfold Mem.perm in NP.\n              rewrite (Perm2'MaxNop H2) in NP. inv NP.\n         (*end of proof of MiPerm*)\n    split.\n    (*mi_perm*) apply MiPerm.\n    (*mi_align*)\n       intros.\n       apply (valid_split _ _ _ _  (ACCESS b1)); clear ACCESS; intros.\n         specialize (H2 Max).\n         remember (j b1) as q.\n         destruct q; apply eq_sym in Heqq.\n           destruct p0.\n           assert (J':= InjInc _ _ _ Heqq). rewrite J' in H. inv H.\n           assert (RNG: Mem.range_perm m2 b1 ofs (ofs + size_chunk chunk) Max p).\n             intros z; intros.\n             destruct (H2 z) as [Perm NoPerm].\n             specialize (H0 _ H). clear H2.\n             destruct (Mem.perm_dec m1 b1 z Max Nonempty).\n               rewrite (perm_subst _ _ _ _ _ _ _ (Perm p0)) in *; clear Perm NoPerm.\n                 eapply (extends_perm _ _ Ext12).\n                 eapply Fwd1. eapply Mem.valid_block_inject_1. apply Heqq. eassumption.\n                      assumption.\n             rewrite (perm_subst _ _ _ _ _ _ _ (NoPerm n)) in *; clear Perm NoPerm.\n               assumption.\n           eapply Inj23. apply Heqq. eassumption.\n         destruct (injSep _ _ _ Heqq H).\n            exfalso. apply H3.\n            eapply (Mem.valid_block_extends _ _ b1 Ext12). assumption.\n       assert (RNG: Mem.range_perm m1' b1 ofs (ofs + size_chunk chunk) Max p).\n             intros z; intros.\n             destruct (H2 Max z) as [Perm NoPerm]. clear H2.\n             specialize (H0 _ H3).\n             destruct (Mem.perm_dec m1' b1 z Max Nonempty).\n               rewrite (perm_subst _ _ _ _ _ _ _ (Perm p0)) in *; clear Perm NoPerm. assumption.\n             unfold Mem.perm in H0. rewrite (NoPerm n) in H0. simpl in H0. intuition.\n        eapply Inj13'. apply H. apply RNG.\n       (*mi_memval *) intros.\n           destruct (CONT b1) as [ContVal [ContInval Default]]; clear CONT.\n           assert (NP: Mem.perm m2' b1 ofs Max Nonempty).\n                   eapply Mem.perm_max. eapply Mem.perm_implies.\n                   apply H0. constructor.\n           apply (valid_split _ _ _ _  (ACCESS b1)); clear ACCESS; intros.\n              clear ContInval.\n              specialize (ContVal H1 ofs).\n              apply (Mem.valid_block_extends _ _ _ Ext12) in H1.\n              assert (J: j b1 = Some (b2, delta)).\n                  remember (j b1) as d. destruct d; apply eq_sym in Heqd.\n                    destruct p. rewrite (InjInc _ _ _ Heqd) in H.  apply H.\n                  destruct (injSep _ _ _ Heqd H). exfalso. apply (H3 H1).\n              rewrite J in ContVal. destruct ContVal as [ContPerm ContNoperm].\n              rewrite J in H2.\n              destruct (H2 Max ofs) as [Perm2'MaxP Perm2'MaxNop].\n              specialize (H2 Cur ofs).\n              apply (perm_split _ _ _ _ _ _ _ H2); clear H2; intros.\n                  clear Perm2'MaxNop ContNoperm.\n                  rewrite (perm_subst _ _ _ _ _ _ _ H3) in *; clear H3.\n                  rewrite (ContPerm H2). clear ContPerm.\n                  rewrite (perm_subst _ _ _ _ _ _ _ (Perm2'MaxP H2)) in *;\n                          clear Perm2'MaxP.\n                  eapply Inj13'. apply H. apply H0.\n              clear Perm2'MaxP ContPerm.\n                  rewrite (perm_subst _ _ _ _ _ _ _ H3) in *; clear H3.\n                  rewrite (perm_subst _ _ _ _ _ _ _ (Perm2'MaxNop H2)) in *;\n                          clear Perm2'MaxNop.\n                  rewrite (ContNoperm H2). clear ContNoperm.\n                  destruct UnchOn3 as [U3Perm U3Val].\n                  assert (loc_out_of_reach j m1 b2 (ofs + delta)).\n                    unfold loc_out_of_reach; intros. intros N.\n                       destruct (eq_block b0 b1); subst.\n                           rewrite H3 in J; inv J.\n                           assert (ofs + delta - delta = ofs). omega.\n                           rewrite H4 in N. apply (H2 N).\n                       assert (N2: Mem.perm m2 b0 (ofs + delta - delta0)\n                                   Max Nonempty).\n                          (*rewrite EP12. apply N. apply N.*)\n                               specialize (Mem.mi_perm _ _ _ (Mem.mext_inj _ _  Ext12) b0 b0 Z0\n                                                      (ofs + delta - delta0)). rewrite Zplus_0_r. intros.\n                               apply (H4 _ _ (eq_refl _) N).\n                       destruct (Mem.mi_no_overlap _ _ _ Inj23 _ _ _\n                                                   _ _ _ _ _ n H3 J N2 NP).\n                              apply H4; trivial.\n                              apply H4. omega.\n              assert (Val3:=Mem.valid_block_inject_2 _ _ _ _ _ _ J Inj23).\n              assert (Perm3:  Mem.perm m3 b2 (ofs+delta) Cur Readable).\n                  eapply Inj23. apply J. apply H0.\n            rewrite (U3Val _ _ H3 Perm3).\n              eapply memval_inject_incr.\n                 apply (Mem.mi_memval _ _ _ (Mem.mi_inj _ _ _ Inj23)\n                                      _ _ _ _ J H0).\n                   assumption.\n           clear ContVal.\n              assert (NVal1: ~Mem.valid_block m1 b1). intros N. apply H1.\n                   apply (Mem.valid_block_extends _ _ _ Ext12). apply N.\n              assert (J: j b1 = None).\n                remember (j b1) as d.\n                destruct d; apply eq_sym in Heqd; trivial.\n                    destruct p. exfalso. apply H1.\n                    apply (Mem.valid_block_inject_1 _ _ _ _ _ _ Heqd Inj23).\n              destruct (H2 Max ofs) as [Perm2'MaxP Perm2'MaxNop].\n              assert (VB1': Mem.valid_block m1' b1).\n                 rewrite VB'. apply (Mem.perm_valid_block _ _ _ _ _ H0).\n              destruct (ContInval H1 VB1' ofs) as [ContPerm ContNoPerm];\n                       clear ContInval.\n              specialize (H2 Cur ofs).\n              apply (perm_split _ _ _ _ _ _ _ H2); clear H2; intros.\n                  clear Perm2'MaxNop ContNoPerm.\n                  rewrite (perm_subst _ _ _ _ _ _ _ H3) in *; clear H3.\n                  rewrite (perm_subst _ _ _ _ _ _ _ (Perm2'MaxP H2)) in NP;\n                          clear Perm2'MaxP.\n                  rewrite (ContPerm H0); clear ContPerm.\n                  eapply Inj13'. apply H. apply H0.\n              clear Perm2'MaxP ContPerm.\n                  unfold Mem.perm in NP.\n                  rewrite (Perm2'MaxNop H2) in NP. inv NP.\n    (*end of proof of MI: Mem.mem_inj j' m2' m3'*)\n    split; intros.\n        (*mi_inj*)\n           apply MI.\n        (*mi_freeblocks*)\n           eapply Inj13'. rewrite VB'. apply H.\n        (* mi_mappedblocks*)\n           eapply Inj13'. apply H.\n        (* mi_no_overlap*)\n           intros b1 b1' delta1 b2 b2'; intros.\n           remember (j b1) as jb1.\n           destruct jb1; apply eq_sym in Heqjb1.\n           (*j b = Some p*)\n              destruct p. rewrite (InjInc _ _ _ Heqjb1) in H0. inv H0.\n              assert (ValB1:=Mem.valid_block_inject_1 _ _ _ _ _ _ Heqjb1 Inj23).\n              assert (Perm1: Mem.perm m2 b1 ofs1 Max Nonempty).\n                     eapply Fwd2. apply ValB1. apply H2.\n              remember (j b2) as jb2.\n              destruct jb2; apply eq_sym in Heqjb2.\n              (*j b2 = Some p*)\n                 destruct p. rewrite (InjInc _ _ _ Heqjb2) in H1. inv H1.\n                 assert (ValB2:= Mem.valid_block_inject_1 _ _ _ _ _ _\n                                 Heqjb2 Inj23).\n                 assert (Perm2: Mem.perm m2 b2 ofs2 Max Nonempty).\n                    eapply Fwd2. apply ValB2. apply H3.\n                 eapply (Mem.mi_no_overlap _ _ _ Inj23 _ _ _ _ _ _\n                                    _ _ H Heqjb1 Heqjb2 Perm1 Perm2).\n              (*j b2 = None*)\n                 destruct (injSep _ _ _ Heqjb2 H1).\n                 left. intros N; subst.\n                 apply H4.\n                 apply (Mem.valid_block_inject_2 _ _ _ _ _ _ Heqjb1 Inj13).\n           (*j b = None*)\n              destruct (injSep _ _ _ Heqjb1 H0).\n              remember (j b2) as jb2.\n              destruct jb2; apply eq_sym in Heqjb2.\n              (*j b2 = Some p*)\n                 destruct p. rewrite (InjInc _ _ _ Heqjb2) in H1. inv H1.\n                 left. intros N; subst.\n                 apply H5.\n                 apply (Mem.valid_block_inject_2 _ _ _ _ _ _ Heqjb2 Inj13).\n              (*j b2 = None*)\n                 destruct (injSep _ _ _ Heqjb2 H1).\n                 apply (valid_split _ _ _ _  (ACCESS b1)); intros.\n                     exfalso. apply H4.\n                        apply (Mem.valid_block_extends _ _ _ Ext12). apply H8.\n                 specialize (H9 Max ofs1).\n                 apply (valid_split _ _ _ _  (ACCESS b2)); intros.\n                     exfalso. apply H6.\n                        apply (Mem.valid_block_extends _ _ _ Ext12). apply H10.\n                 specialize (H11 Max ofs2).\n                 apply (perm_split _ _ _ _ _ _ _ H9); clear H9; intros.\n                    rewrite (perm_subst _ _ _ _ _ _ _ H12) in *; clear H12.\n                    apply (perm_split _ _ _ _ _ _ _ H11); clear H11; intros.\n                       rewrite (perm_subst _ _ _ _ _ _ _ H12) in *; clear H12.\n                       eapply (Mem.mi_no_overlap _ _ _ Inj13' _ _ _\n                                 _ _ _  _ _ H H0 H1 H2 H3).\n                    unfold Mem.perm in H3. rewrite H12 in H3. inv H3.\n                 unfold Mem.perm in H2. rewrite H12 in H2. inv H2.\n        (*mi_representable*)\n           apply (valid_split _ _ _ _  (ACCESS b)); intros.\n           (*case valid*)\n             assert (J: j b = Some (b', delta)).\n               remember (j b) as d. destruct d; apply eq_sym in Heqd.\n                 destruct p. rewrite (InjInc _ _ _ Heqd) in H.  apply H.\n                 destruct (injSep _ _ _ Heqd H). exfalso.\n                 apply (Mem.valid_block_extends _ _ _ Ext12) in H1. apply (H3 H1).\n             (* weak_valid_pointer*)\n             rewrite J in H2.\n             destruct H0.\n             (*location ofs*)\n               specialize (H2 Max (Int.unsigned ofs)).\n               apply (perm_split _ _ _ _ _ _ _ H2); clear H2; intros.\n                 rewrite (perm_subst _ _ _ _ _ _ _ H3) in *. clear H3.\n                 eapply Inj13'. apply H. left. apply H0.\n               rewrite (perm_subst _ _ _ _ _ _ _ H3) in *. clear H3.\n                 eapply Inj23. apply J. left. apply H0.\n             (*location ofs -1*)\n               specialize (H2 Max (Int.unsigned ofs -1)).\n               apply (perm_split _ _ _ _ _ _ _ H2); clear H2; intros.\n                 rewrite (perm_subst _ _ _ _ _ _ _ H3) in *. clear H3.\n                 eapply Inj13'. apply H. right. apply H0.\n               rewrite (perm_subst _ _ _ _ _ _ _ H3) in *. clear H3.\n                 eapply Inj23. apply J. right. apply H0.\n           (*case invalid*)\n             assert (J: j b = None).\n               remember (j b) as d. destruct d; apply eq_sym in Heqd; trivial.\n                  destruct p. exfalso. apply H1.\n                  apply (Mem.valid_block_inject_1 _ _ _ _ _ _ Heqd Inj23).\n             (* weak_valid_pointer*)\n             destruct H0.\n             (*location ofs*)\n               specialize (H2 Max (Int.unsigned ofs)).\n               apply (perm_split _ _ _ _ _ _ _ H2); clear H2; intros.\n                 rewrite (perm_subst _ _ _ _ _ _ _ H3) in *. clear H3.\n                 eapply Inj13'. apply H. left. apply H0.\n               unfold Mem.perm in H0. rewrite H3 in H0. contradiction.\n             (*location ofs -1*)\n               specialize (H2 Max (Int.unsigned ofs -1)).\n               apply (perm_split _ _ _ _ _ _ _ H2); clear H2; intros.\n                 rewrite (perm_subst _ _ _ _ _ _ _ H3) in *. clear H3.\n                 eapply Inj13'. apply H. right. apply H0.\n               unfold Mem.perm in H0. rewrite H3 in H0. contradiction.\nsplit; trivial.\nsplit; trivial.\nQed.\n\nDefinition AccessMap_EI_FUN (j:meminj) (m1 m1' m2 : mem) (b2:block):\n           Z -> perm_kind -> option permission :=\n  if plt b2 (Mem.nextblock m2)\n  then (fun ofs2 k =>\n       match j b2 with\n         None => PMap.get b2 m2.(Mem.mem_access) ofs2 k\n       | Some (b3,d3) =>\n          if Mem.perm_dec m1 b2 ofs2 Max Nonempty\n          then PMap.get b2 m1'.(Mem.mem_access) ofs2 k\n          else PMap.get b2 m2.(Mem.mem_access) ofs2 k\n        end)\n  else (fun ofs2 k =>\n         if Mem.perm_dec m1' b2 ofs2 Max Nonempty\n         then PMap.get b2 m1'.(Mem.mem_access) ofs2 k\n         else None).\n\nLemma mkAccessMap_EI_existsT: forall j (m1 m1' m2:Mem.mem)\n       (VB : (Mem.nextblock m2 <= Mem.nextblock m1')%positive),\n      { M : PMap.t (Z -> perm_kind -> option permission) |\n          fst M = (fun k ofs => None) /\\\n          forall b, PMap.get b M = AccessMap_EI_FUN j m1 m1' m2 b}.\nProof. intros.\n  apply (pmap_construct_c _ (AccessMap_EI_FUN j m1 m1' m2)\n              (Mem.nextblock m1') (fun ofs k => None)).\n    intros. unfold AccessMap_EI_FUN.\n    remember (plt n (Mem.nextblock m2)) as d.\n    destruct d; clear Heqd; trivial.\n       exfalso. xomega.\n    extensionality ofs. extensionality k.\n      destruct (Mem.perm_dec m1' n ofs Max Nonempty); trivial.\n      apply Mem.perm_valid_block in p.\n      exfalso. unfold Mem.valid_block in p. xomega.\nQed.\n\nDefinition ContentMap_EI_ValidBlock_FUN (j:meminj) m1 m1' m2 b2 ofs2: memval :=\n             match j b2 with\n               None => ZMap.get ofs2 (PMap.get b2 m2.(Mem.mem_contents))\n             | Some (b3,delta3) =>\n                  if Mem.perm_dec m1 b2 ofs2 Max Nonempty\n                  then ZMap.get ofs2 (PMap.get b2 m1'.(Mem.mem_contents))\n                  else ZMap.get ofs2 (PMap.get b2 m2.(Mem.mem_contents))\n             end.\n\nDefinition ContentMap_EI_InvalidBlock_FUN m1' b2 ofs2: memval :=\n    if Mem.perm_dec m1' b2 ofs2 Cur Readable\n    then ZMap.get ofs2 (PMap.get b2 m1'.(Mem.mem_contents))\n    else Undef.\n\nDefinition ContentMap_EI_Block_FUN j m1 m1' m2 b ofs : memval:=\n  if plt b (Mem.nextblock m2)\n  then ContentMap_EI_ValidBlock_FUN j m1 m1' m2 b ofs\n  else ContentMap_EI_InvalidBlock_FUN m1' b ofs.\n\nLemma CM_block_EI_existsT: forall j (m1 m1' m2:Mem.mem) b,\n      { M : ZMap.t memval |\n          fst M = Undef /\\\n          forall ofs, ZMap.get ofs M =\n                      ContentMap_EI_Block_FUN j m1 m1' m2 b ofs}.\nProof. intros.\n  remember (zmap_finite_c _ (PMap.get b m1'.(Mem.mem_contents))) as LH1.\n  apply eq_sym in HeqLH1. destruct LH1 as [lo1 hi1].\n  specialize (zmap_finite_sound_c _ _ _ _ HeqLH1).\n  intros Bounds1; clear HeqLH1.\n  remember (zmap_finite_c _ (PMap.get b m2.(Mem.mem_contents))) as LH2.\n  apply eq_sym in HeqLH2. destruct LH2 as [lo2 hi2].\n  specialize (zmap_finite_sound_c _ _ _ _ HeqLH2).\n  intros Bounds2; clear HeqLH2.\n   assert (Undef2: fst (Mem.mem_contents m2) !! b = Undef). apply m2.\n   assert (Undef1: fst (Mem.mem_contents m1') !! b = Undef). apply m1'.\n   rewrite Undef2 in *. rewrite Undef1 in *. clear Undef1 Undef2.\n\n  destruct (zmap_construct_c _ (ContentMap_EI_Block_FUN j m1 m1' m2 b)\n             (Z.min lo1 lo2) (Z.max hi1 hi2) Undef) as [M PM].\n    intros. unfold ContentMap_EI_Block_FUN; simpl.\n        unfold ContentMap_EI_ValidBlock_FUN.\n        unfold ContentMap_EI_InvalidBlock_FUN.\n   rewrite Bounds1.\n   rewrite Bounds2.\n     destruct (plt b (Mem.nextblock m2)); trivial.\n       destruct (j b); trivial.\n         destruct p0.\n         destruct (Mem.perm_dec m1 b n Max Nonempty); trivial.\n     destruct (Mem.perm_dec m1' b n Cur Readable); trivial.\n\n     destruct H.  apply Z.min_glb_lt_iff in H. left. apply H.\n     assert (Z.max hi1 hi2 < n) by omega.\n     apply Z.max_lub_lt_iff in H0. right; omega.\n     destruct H.  apply Z.min_glb_lt_iff in H. left. apply H.\n     assert (Z.max hi1 hi2 < n) by omega.\n     apply Z.max_lub_lt_iff in H0. right; omega.\n  exists M. apply PM.\nQed.\n\nDefinition ContentsMap_EI_FUN (j:meminj) (m1 m1' m2:Mem.mem) (b:block):\n            ZMap.t memval.\ndestruct (plt b (Mem.nextblock m1')).\n  apply(CM_block_EI_existsT j m1 m1' m2 b).\n  apply (ZMap.init Undef).\nDefined.\n\n\nLemma ContentsMap_EI_existsT: forall (j:meminj) (m1 m1' m2:Mem.mem),\n      { M : PMap.t (ZMap.t memval) |\n        fst M = ZMap.init Undef /\\\n        forall b, PMap.get b M = ContentsMap_EI_FUN j m1 m1' m2 b}.\nProof. intros.\n  apply (pmap_construct_c _ (ContentsMap_EI_FUN j m1 m1' m2)\n              (Mem.nextblock m1') (ZMap.init Undef)).\n    intros. unfold ContentsMap_EI_FUN. simpl.\n    remember (plt n (Mem.nextblock m1')) as d.\n    destruct d; clear Heqd; trivial.\n      exfalso. xomega.\nQed.\n\nDefinition mkEI (j j': meminj) (m1 m2 m1':mem)\n                (Ext12: Mem.extends m1 m2)\n                (Fwd1: mem_forward m1 m1') m3\n                (Inj23: Mem.inject j m2 m3)\n                m3' (Fwd3: mem_forward m3 m3')\n                (Inj13': Mem.inject j' m1' m3')\n                (UnchOn3: Mem.unchanged_on (loc_out_of_reach j m1) m3 m3')\n                (InjInc: inject_incr j j') (injSep: inject_separated j j' m1 m3)\n                (UnchOn1: Mem.unchanged_on (loc_unmapped j) m1 m1')\n             : Mem.mem'.\nassert (VB: (Mem.nextblock m2 <= Mem.nextblock m1')%positive).\n   destruct Ext12. rewrite <- mext_next.\n   apply (forward_nextblock _ _ Fwd1).\ndestruct (mkAccessMap_EI_existsT j m1 m1' m2) as [AM [ADefault PAM]].\n   assumption.\ndestruct (ContentsMap_EI_existsT j m1 m1' m2) as [CM [CDefault PCM]].\neapply Mem.mkmem with (nextblock:=m1'.(Mem.nextblock))\n                      (mem_access:=AM)\n                      (mem_contents:=CM).\n  (*apply (mkContentsMap_EI_exists j m1 m1' m2).*)\n(*  apply m1'.*)\n  (*access_max*)\n     intros. rewrite PAM. unfold AccessMap_EI_FUN.\n     destruct (plt b (Mem.nextblock m2)).\n     (*valid_block m2 b*)\n        destruct (j b).\n          destruct p0.\n          destruct (Mem.perm_dec m1 b ofs Max Nonempty).\n             apply m1'.\n             apply m2.\n        apply m2.\n     (*~ valid_block m2 b*)\n        destruct (Mem.perm_dec m1' b ofs Max Nonempty).\n           apply m1'.\n           reflexivity.\n  (*nextblock_noaccess*)\n    intros. rewrite PAM.\n    unfold AccessMap_EI_FUN.\n    destruct (plt b (Mem.nextblock m2)).\n      exfalso. apply H; clear - VB p. xomega.\n    destruct (Mem.perm_dec m1' b ofs Max Nonempty); trivial.\n      exfalso. apply H. apply (Mem.perm_valid_block _ _ _ _ _ p).\n  (*contents_default*)\n    intros. rewrite PCM.\n    unfold ContentsMap_EI_FUN.\n    destruct (plt b (Mem.nextblock m1')).\n     remember (CM_block_EI_existsT j m1 m1' m2 b).\n     destruct s. apply a.\n    reflexivity.\nDefined.\n\nLemma interpolate_EI: forall (m1 m2 m1':mem)\n                   (Ext12: Mem.extends m1 m2) (Fwd1: mem_forward m1 m1')\n                   m3 j (Inj23: Mem.inject j m2 m3) m3'\n                   (Fwd3: mem_forward m3 m3') j'\n                   (Inj13': Mem.inject j' m1' m3')\n                   (UnchOn3: Mem.unchanged_on (loc_out_of_reach j m1) m3 m3')\n                   (InjInc: inject_incr j j')\n                   (injSep: inject_separated j j' m1 m3)\n                   (UnchOn1:  Mem.unchanged_on (loc_unmapped j) m1 m1'),\n       exists m2', mem_forward m2 m2' /\\ Mem.extends m1' m2' /\\\n                   Mem.inject j' m2' m3' /\\\n                   Mem.unchanged_on (loc_out_of_bounds m1) m2 m2' /\\\n                   Mem.unchanged_on (loc_unmapped j) m2 m2'.\nProof. intros.\n  assert (VB: Mem.nextblock\n    (mkEI j j' m1 m2 m1' Ext12 Fwd1 m3 Inj23 m3' Fwd3 Inj13' UnchOn3 InjInc\n       injSep UnchOn1) = Mem.nextblock m1').\n    unfold mkEI.\n   destruct (mkAccessMap_EI_existsT j m1 m1' m2) as [AM [ADefault PAM]].\n   simpl.\n   destruct (ContentsMap_EI_existsT j m1 m1' m2) as [CM [CDefault PCM]].\n   simpl. reflexivity.\n  exists (mkEI j j' m1 m2 m1' Ext12 Fwd1 _ Inj23 _ Fwd3 Inj13'\n              UnchOn3 InjInc injSep UnchOn1).\n  apply (EI_ok m1 m2 m1' Ext12 Fwd1 _ _ Inj23 _ Fwd3 _ Inj13'\n            UnchOn3 InjInc injSep UnchOn1\n            (mkEI j j' m1 m2 m1' Ext12 Fwd1 m3 Inj23 m3' Fwd3\n                  Inj13' UnchOn3 InjInc injSep UnchOn1)\n            VB).\n(*ContentMapOK*)\n   unfold Content_EI_Property, mkEI.\n   destruct (mkAccessMap_EI_existsT j m1 m1' m2) as [AM [ADef AP]]; simpl.\n        destruct (ContentsMap_EI_existsT j m1 m1' m2) as [CM [CDef CP]]. simpl.\n   intros.\n   split; intros.\n   (*valid_block m2 b*)\n     rewrite CP. unfold ContentsMap_EI_FUN.\n     destruct (CM_block_EI_existsT j m1 m1' m2 b2) as [CMb [CMbDef CMbP]]; simpl.\n     destruct (plt b2 (Mem.nextblock m1')).\n       remember (j b2).\n       destruct o.\n         destruct p0.\n         rewrite CMbP.\n         unfold ContentMap_EI_Block_FUN.\n         destruct (plt b2 (Mem.nextblock m2)).\n           unfold ContentMap_EI_ValidBlock_FUN.\n           rewrite <- Heqo.\n           destruct (Mem.perm_dec m1 b2 ofs2 Max Nonempty).\n           split; intros; trivial. contradiction.\n           split; intros; trivial. contradiction.\n         contradiction.\n       rewrite CMbP.\n         unfold ContentMap_EI_Block_FUN.\n         destruct (plt b2 (Mem.nextblock m2)); try contradiction.\n         unfold ContentMap_EI_ValidBlock_FUN.\n         rewrite <- Heqo. trivial.\n    exfalso. apply n. apply Fwd1.\n      rewrite Mem.valid_block_extends. apply H. assumption.\n  split; intros.\n     rewrite CP. unfold ContentsMap_EI_FUN.\n     destruct (CM_block_EI_existsT j m1 m1' m2 b2) as [CMb [CMbDef CMbP]]; simpl.\n     destruct (plt b2 (Mem.nextblock m1')); try contradiction.\n     split; intros.\n       rewrite CMbP. unfold ContentMap_EI_Block_FUN.\n         destruct (plt b2 (Mem.nextblock m2)); try contradiction.\n         unfold ContentMap_EI_InvalidBlock_FUN.\n         destruct (Mem.perm_dec m1' b2 ofs2 Cur Readable); try contradiction.\n         trivial.\n       rewrite CMbP. unfold ContentMap_EI_Block_FUN.\n         destruct (plt b2 (Mem.nextblock m2)); try contradiction.\n         unfold ContentMap_EI_InvalidBlock_FUN.\n         destruct (Mem.perm_dec m1' b2 ofs2 Cur Readable); try contradiction.\n         trivial.\n  (*default*)\n     rewrite CP.\n     unfold ContentsMap_EI_FUN.\n     destruct ( plt b2 (Mem.nextblock m1')).\n       destruct (CM_block_EI_existsT j m1 m1' m2 b2) as [CMb [CMbDef CMbP]]; simpl.\n       assumption.\n       reflexivity.\n(*AccessMapOK*)\n   unfold AccessMap_EI_Property, mkEI.\n   destruct (mkAccessMap_EI_existsT j m1 m1' m2) as [AM [ADef AP]]; simpl.\n        destruct (ContentsMap_EI_existsT j m1 m1' m2) as [CM [CDef CP]]. simpl.\n   intros.\n   split; intros.\n   (*valid_block m2 b*)\n     rewrite AP. unfold AccessMap_EI_FUN.\n     destruct (plt b2 (Mem.nextblock m2)); try contradiction.\n     destruct (Mem.perm_dec m1 b2 ofs2 Max Nonempty).\n       remember (j b2).\n       destruct o; trivial.\n       destruct p1.\n          split; intros; try contradiction. trivial.\n     remember (j b2).\n       destruct o; trivial.\n       destruct p0.\n          split; intros; try contradiction. trivial.\n\n  (*invalid_block m2 b*)\n   rewrite AP. unfold AccessMap_EI_FUN.\n   destruct (plt b2 (Mem.nextblock m2)); try contradiction.\n   destruct (Mem.perm_dec m1' b2 ofs2 Max Nonempty).\n     split; intros; try contradiction. trivial.\n     split; intros; try contradiction. trivial.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/sepcomp/submit/mem_interpolation_EI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.3311197330283893, "lm_q1q2_score": 0.2144987684816259}}
{"text": "(* PREAMBLE *)\n\nFrom compcert.common    Require AST.\nFrom compcert.cfrontend Require Csyntax Csem.\nFrom compcert.lib       Require Coqlib.\nFrom trancert.lib       Require Tac Decidability Option.\nFrom trancert.analysis  Require StatementQuant ExprQuant.\n\nImport Coqlib BinNums common.AST Algebraic Csyntax Csem Decidability Option Tac ExprQuant StatementQuant.\n\nSection Appears.\n\n  Variable v: ident.\n\n  Definition appears_expr e : Prop := exists_var_in_expr (Logic.eq v) e.\n  Definition appears_exprlist e : Prop := exists_var_in_exprlist (Logic.eq v) e.\n\n  Definition appears_ctx (C: expr->expr): Prop := forall k1 k2 e, context k1 k2 C -> appears_expr (C e).\n  Definition appears_ctxlist (C: expr->exprlist): Prop := forall k e, contextlist k C -> appears_exprlist (C e).\n\n  Definition appears_stmt : statement -> Prop := exists_var_in_stmt (Logic.eq v).\n\n  Definition appears_expr_dec : forall e, dec (appears_expr e) :=\n    exists_var_in_expr_dec (eq v) (peq v).\n\n  Definition appears_stmt_dec : forall s, dec (appears_stmt s).\n    apply exists_var_in_stmt_dec.\n    apply Coqlib.peq.\n  Defined.\n\nEnd Appears.\n", "meta": {"author": "sayon", "repo": "trancert", "sha": "eb5c94c75067782158522f61bdd7cc902bf74185", "save_path": "github-repos/coq/sayon-trancert", "path": "github-repos/coq/sayon-trancert/trancert-eb5c94c75067782158522f61bdd7cc902bf74185/analysis/Appears.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.21449207504754553}}
{"text": "Require Import Ssreflect.ssreflect Ssreflect.ssrfun Ssreflect.ssrbool Ssreflect.finfun Ssreflect.fintype Ssreflect.ssrnat Ssreflect.eqtype Ssreflect.seq Ssreflect.tuple.\nRequire Import x86proved.bitsrep x86proved.bitsops x86proved.bitsprops x86proved.bitsopsprops.\nRequire Import x86proved.spred x86proved.septac x86proved.spec x86proved.safe x86proved.x86.basic x86proved.x86.program x86proved.x86.macros x86proved.x86.call.\nRequire Import x86proved.x86.instr x86proved.monad x86proved.reader x86proved.writer x86proved.x86.procstate x86proved.x86.procstatemonad x86proved.x86.mem x86proved.x86.exn x86proved.x86.eval\n               x86proved.monadinst x86proved.x86.ioaction x86proved.bitsrep x86proved.bitsops x86proved.x86.eval x86proved.x86.step x86proved.x86.instrcodec x86proved.pointsto x86proved.cursor.\nRequire Import x86proved.x86.program x86proved.x86.programassem x86proved.x86.reg x86proved.x86.instrsyntax x86proved.x86.instrrules.\nRequire Import x86proved.spectac x86proved.charge.iltac x86proved.triple.\n\n\n(* ATBR *)\nRequire Import ATBR.DecideKleeneAlgebra.\nRequire Import ATBR.DKA_Definitions.\n\nRequire Import interfaceATBR.\nRequire Import regexpsyntax.\n\nLocal Open Scope regex_scope.\nOpen Scope char_scope.\n\n(**********************************)\n(* Floating point regexp          *)\n(**********************************)\n\nDefinition alphabet: seq DWORD :=\ncat [seq (# c) | c <- iota (Ascii.nat_of_ascii \"0\") 10 ]\n    [:: #(Ascii.nat_of_ascii \"-\")\n      ; #(Ascii.nat_of_ascii \"+\")\n      ; #(Ascii.nat_of_ascii \"e\")\n      ; #(Ascii.nat_of_ascii \".\")].\n\n\n(* ^[-+]?[0-9]*\\.?[0-9]+([e][-+]?[0-9]+)?$ *)\n(*=FP *)\nDefinition FP: regex :=\n  [[ \"-\" , \"+\"]]? '\n  [{ \"0\" , \"9\" }]* ' $\".\" ? '\n  [{ \"0\" , \"9\" }]+ '\n  ($\"e\" ' [[ \"-\" , \"+\"]]? ' [{ \"0\" , \"9\" }]+)?.\n(*=End *)\n\n(**********************************)\n(* Examples:                      *)\n(**********************************)\n\n(*=FP_code*)\nDefinition FP_x86 (acc rej: DWORD): program :=\n    X_to_x86 FP alphabet acc rej.\n(*=End*)\n\n(*\nDefinition code_zero: program := code rO [:: #1 ; #2 ; #3 ] #42 #24.\nDefinition bytes_zero := assemble #x\"C0000000\" code_zero.\n(* Compute (bytesToHex bytes_zero). *)\n\nDefinition code_var1: program := code $\"1\" [:: #1 ; #2 ; #3 ] #42 #24.\nDefinition bytes_var1 := assemble #x\"C0000000\" code_var1.\n(* Compute (bytesToHex bytes_var1). *)\n*)\n\nLocal Close Scope regex_scope.\n", "meta": {"author": "nbenton", "repo": "x86proved", "sha": "7a58960f6456ee09dd46c990204a30c2fdd7fa1a", "save_path": "github-repos/coq/nbenton-x86proved", "path": "github-repos/coq/nbenton-x86proved/x86proved-7a58960f6456ee09dd46c990204a30c2fdd7fa1a/src/x86/lib/regexp/exampleregexp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2144844920428747}}
{"text": "Require Import Platform.AutoSep Platform.Malloc Platform.tests.Abort Platform.Bootstrap.\n\n\nModule Type S.\n  Variable heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"test\"!\"main\" @ [Abort.mainS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Goto \"test\"!\"main\"\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Definition m0 := link Malloc.m boot.\n  Definition m1 := link Abort.m m0.\n\n  Lemma ok0 : moduleOk m0.\n    link Malloc.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link Abort.ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n\n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, $ (size * 4) <= w -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/tests/AbortDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3738758157951908, "lm_q1q2_score": 0.21448448804060385}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import coqutil.Z.Lia.\nRequire Import coqutil.Macros.unique.\nRequire Import compiler.util.Common.\nRequire Import bedrock2.Semantics.\nRequire Import riscv.Utility.Monads.\nRequire Import compiler.FlatImp.\nRequire Import riscv.Spec.Decode.\nRequire Import coqutil.sanity.\nRequire Import riscv.Utility.MkMachineWidth.\nRequire Import riscv.Spec.PseudoInstructions.\nRequire Import riscv.Utility.InstructionCoercions.\nRequire Import riscv.Spec.Machine.\nRequire Import compiler.FlatToRiscvDef.\nRequire Import compiler.FlatToRiscvFunctions.\nRequire Import riscv.Platform.RiscvMachine.\nRequire Import riscv.Platform.MinimalMMIO.\nRequire Import riscv.Platform.MetricMinimalMMIO.\nRequire Import riscv.Spec.Primitives.\nRequire Import riscv.Spec.MetricPrimitives.\nRequire Import compiler.MetricsToRiscv.\nRequire Import compiler.FlatToRiscvDef.\nRequire Import riscv.Utility.runsToNonDet.\nRequire Import compiler.GoFlatToRiscv.\nRequire Import compiler.SeparationLogic.\nRequire Import coqutil.Datatypes.Option.\nRequire Import coqutil.Tactics.Simp.\nRequire Import compiler.util.Learning.\nRequire Export coqutil.Word.SimplWordExpr.\nRequire Import compiler.RiscvWordProperties.\nRequire Import riscv.Platform.FE310ExtSpec.\nRequire Import coqutil.Z.div_mod_to_equations.\nRequire Import coqutil.Datatypes.ListSet.\nRequire bedrock2.FE310CSemantics.\nImport ListNotations.\n\nOpen Scope ilist_scope.\n\nDefinition compile_interact(results: list Z) a (args: list Z):\n  list Instruction :=\n  if String.eqb \"MMIOWRITE\" a then\n    match results, args with\n    | [], [addr; val] => [[ Sw addr val 0 ]]\n    | _, _ => [[]] (* invalid, excluded by ext_spec *)\n    end\n  else\n    match results, args with\n    | [res], [addr] => [[ Lw res addr 0 ]]\n    | _, _ => [[]] (* invalid, excluded by ext_spec *)\n    end.\n\nLemma compile_interact_length: forall binds f args,\n    Z.of_nat (List.length (compile_interact binds f args)) <= 1.\nProof.\n  intros. unfold compile_interact.\n  destruct (String.eqb _ _); destruct binds; try destruct binds;\n  try destruct args; try destruct args; try destruct args;\n  cbv; intros; discriminate.\nQed.\n\nLemma compile_interact_length': forall binds f args,\n    Z.of_nat (List.length (compile_interact binds f args)) <= 7.\nProof. intros. rewrite compile_interact_length. blia. Qed.\n\nLemma compile_interact_emits_valid: forall iset binds a args,\n    Forall valid_FlatImp_var binds ->\n    Forall valid_FlatImp_var args ->\n    valid_instructions iset (compile_interact binds a args).\nProof.\n  intros.\n  unfold compile_interact.\n  destruct (String.eqb _ _); destruct args; try destruct args; try destruct args;\n    destruct binds; try destruct binds;\n    intros instr HIn; cbn -[String.eqb] in *; intuition idtac; try contradiction.\n  - rewrite <- H1.\n    simp_step.\n    simp_step.\n    (* try simp_step. (* TODO this should not fail fatally *) *)\n    split; [|cbv;auto].\n    unfold Encode.respects_bounds. simpl.\n    unfold Encode.verify_S, valid_FlatImp_var, opcode_STORE, funct3_SW in *.\n    repeat split; (blia || assumption).\n  - rewrite <- H1.\n    simp_step.\n    simp_step.\n    simp_step.\n    simp_step.\n    (* try simp_step. (* TODO this should not fail fatally *) *)\n    split; [|cbv;auto].\n    unfold Encode.respects_bounds. simpl.\n    unfold Encode.verify_I, valid_FlatImp_var, opcode_LOAD, funct3_LW in *.\n    repeat split; (blia || assumption).\nQed.\n\nLocal Arguments Z.mul: simpl never.\nLocal Arguments Z.add: simpl never.\nLocal Arguments Z.of_nat: simpl never.\nLocal Arguments Z.modulo : simpl never.\nLocal Arguments Z.pow: simpl never.\nLocal Arguments Z.sub: simpl never.\nLocal Arguments Registers.reg_class.all: simpl never.\n\nSection MMIO1.\n  Context {iset : InstructionSet} {bitwidth_iset : FlatToRiscvCommon.bitwidth_iset 32 iset}.\n  Context {word: Word.Interface.word 32}.\n  Context {word_ok: word.ok word}.\n  Context {word_riscv_ok: word.riscv_ok word}.\n  Context {mem: map.map word byte}.\n  Context {mem_ok: map.ok mem}.\n  Context {locals: map.map Z word}.\n  Context {locals_ok: map.ok locals}.\n  Context {funname_env: forall T, map.map String.string T}.\n  Context {funname_env_ok: forall T, map.ok (funname_env T)}.\n\n  Add Ring wring : (word.ring_theory (word := word))\n      (preprocess [autorewrite with rew_word_morphism],\n       morphism (word.ring_morph (word := word)),\n       constants [word_cst]).\n\n  Definition compile_ext_call(_: funname_env Z)(_ _: Z)(s: stmt Z) :=\n      match s with\n      | SInteract resvars action argvars => compile_interact resvars action argvars\n      | _ => []\n      end.\n\n  Section CompilationTest.\n    Definition magicMMIOAddrLit: Z := 0x10024000.\n    Variable addr: Z.\n    Variable i: Z.\n    Variable s: Z.\n\n    (*\n    addr = magicMMIOAddr;\n    loop {\n      i = input addr;\n      stay in loop only if i is non-zero;\n      s = i _ i;\n      output addr s;\n    }\n    *)\n    Definition doubler: stmt Z :=\n      (SSeq (SLit addr magicMMIOAddrLit)\n            (SLoop (SLoad Syntax.access_size.four i addr 0)\n                   (CondNez i)\n                   (SSeq (SOp s Syntax.bopname.add i (Var i))\n                         (SStore Syntax.access_size.four addr s 0)))).\n\n    Definition compiled: list Instruction :=\n      Eval cbv in compile_stmt RV32I compile_ext_call map.empty 0 0 doubler.\n    Goal True.\n      let c := eval cbv in compiled in pose c.\n    Abort.\n  End CompilationTest.\n\n  Lemma load4bytes_in_MMIO_is_None: forall (m: mem) (addr: word),\n      map.undef_on m isMMIOAddr ->\n      isMMIOAddr addr ->\n      Memory.load_bytes 4 m addr = None.\n  Proof.\n    intros. unfold Memory.load_bytes, map.undef_on, map.agree_on, map.getmany_of_tuple in *.\n    simpl.\n    rewrite H by assumption.\n    rewrite map.get_empty.\n    reflexivity.\n  Qed.\n\n  Lemma loadWord_in_MMIO_is_None: forall (m: mem) (addr: word),\n      map.undef_on m isMMIOAddr ->\n      isMMIOAddr addr ->\n      Memory.loadWord m addr = None.\n  Proof.\n    intros. unfold Memory.loadWord.\n    apply load4bytes_in_MMIO_is_None; assumption.\n  Qed.\n\n  Lemma storeWord_in_MMIO_is_None: forall (m: mem) (addr: word) v,\n      map.undef_on m isMMIOAddr ->\n      isMMIOAddr addr ->\n      Memory.storeWord m addr v = None.\n  Proof.\n    unfold Memory.storeWord. intros. unfold Memory.store_bytes.\n    rewrite load4bytes_in_MMIO_is_None; auto.\n  Qed.\n\n  Ltac contrad := contradiction || discriminate || congruence.\n\n  (* TODO: why are these here? *)\n  Arguments LittleEndian.combine: simpl never. (* TODO can we put this next to its definition? *)\n  Arguments mcomp_sat: simpl never.\n  Arguments LittleEndian.split: simpl never.\n  Local Arguments String.eqb: simpl never.\n\n  Ltac fwd :=\n    match goal with\n    |- free.interp interp_action ?p ?s ?post =>\n      let p' := eval hnf in p in\n      change (free.interp interp_action p' s post);\n      rewrite free.interp_act;\n      cbn [interp_action MinimalMMIO.interpret_action snd fst];\n        simpl_MetricRiscvMachine_get_set\n    | |- load ?n ?ctx ?a ?s ?k =>\n        let g' := eval cbv beta delta [load] in (load n ctx a s k) in\n        change g';\n        simpl_MetricRiscvMachine_get_set\n    | _ => progress cbn [free.bind]\n    | |- store ?n ?ctx ?a ?v ?s ?k =>\n        let g' := eval cbv beta delta [store] in (store n ctx a v s k) in\n        change g';\n        simpl_MetricRiscvMachine_get_set\n    | _ => progress cbn [free.bind]\n    | _ => rewrite free.interp_ret\n    end.\n\n  Lemma disjoint_MMIO_goal: forall (x y: word),\n      isMMIOAddr x ->\n      ~ isMMIOAddr y ->\n      word.unsigned x mod 4 = 0 ->\n      word.add (word.add (word.add x (word.of_Z 1)) (word.of_Z 1)) (word.of_Z 1) <> y /\\\n      word.add (word.add x (word.of_Z 1)) (word.of_Z 1) <> y /\\\n      word.add x (word.of_Z 1) <> y /\\\n      x <> y.\n  Proof.\n    intros.\n    unfold isMMIOAddr, FE310_mmio, isOTP,isPRCI, isGPIO0, isUART0, isSPI1 in *.\n    simpl in *.\n    ssplit.\n    all: intro C.\n    1: replace x with (word.sub y (word.of_Z 3)) in * by (subst y; solve_word_eq word_ok).\n    2: replace x with (word.sub y (word.of_Z 2)) in * by (subst y; solve_word_eq word_ok).\n    3: replace x with (word.sub y (word.of_Z 1)) in * by (subst y; solve_word_eq word_ok).\n    4: replace x with y in * by assumption.\n    all: clear C;\n      rewrite ?word.unsigned_sub, ?word.unsigned_of_Z in H, H1;\n      unfold word.wrap in *;\n      pose proof (word.unsigned_range y);\n      forget (word.unsigned y) as Y; clear x y;\n      let r := eval cbv in (2 ^ 32) in change (2 ^ 32) with r in *;\n      Z.div_mod_to_equations;\n      (* COQBUG (performance) https://github.com/coq/coq/issues/10743,\n         workaround by @thery *)\n      repeat match goal with\n             | [ H : ?x -> _, H' : ?x -> _ |- _ ] =>\n               pose proof (fun u : x => conj (H u) (H' u)); clear H H'\n             end.\n    all: time blia.\n  Time Qed.\n\n  Lemma compile_ext_call_correct: forall resvars extcall argvars,\n      FlatToRiscvCommon.compiles_FlatToRiscv_correctly compile_ext_call compile_ext_call\n        (FlatImp.SInteract resvars extcall argvars).\n  Proof.\n    unfold FlatToRiscvCommon.compiles_FlatToRiscv_correctly. simpl. intros.\n    destruct H5 as (? & ? & V_resvars & V_argvars).\n    rename extcall into action.\n    pose proof (compile_interact_emits_valid RV32I _ action _ V_resvars V_argvars).\n    simp.\n    destruct_RiscvMachine initialL.\n    unfold FlatToRiscvCommon.goodMachine in *.\n    match goal with\n    | H: forall _ _, outcome _ _ -> _ |- _ => specialize H with (mReceive := map.empty)\n    end.\n    destruct (String.eqb \"MMIOWRITE\" action) eqn: E;\n      cbn [getRegs getPc getNextPc getMem getLog getMachine getMetrics getXAddrs] in *.\n    + (* MMOutput *)\n      progress simpl in *|-.\n      match goal with\n      | H: FE310CSemantics.ext_spec _ _ _ _ _ |- _ => rename H into Ex\n      end.\n      unfold compile_interact in *.\n      cbv [FE310CSemantics.ext_spec] in Ex.\n      rewrite E in *.\n      destruct Ex as (?&?&?&(?&?&?)&?). subst mGive argvals.\n      repeat match goal with\n             | H: _ /\\ _ |- _ => destruct H\n             | H: exists x, _ |- _ => let x' := fresh x in destruct H as [x' H]\n             end.\n      destruct argvars. {\n        exfalso.\n        match goal with\n        | A: map.getmany_of_list _ ?L1 = Some ?L2 |- _ =>\n          clear -A; cbn in *; congruence\n        end.\n      }\n      destruct argvars. {\n        exfalso.\n        match goal with\n        | A: map.getmany_of_list _ ?L1 = Some ?L2 |- _ =>\n          clear -A; cbn in *; destruct_one_match_hyp; congruence\n        end.\n      }\n      destruct argvars; cycle 1. {\n        exfalso.\n        match goal with\n        | A: map.getmany_of_list _ ?L1 = Some ?L2 |- _ =>\n          clear -A; cbn in *; simp; destruct_one_match_hyp; congruence\n        end.\n      }\n      cbn in *|-.\n      match goal with\n      | H: map.split _ _ map.empty |- _ => rewrite map.split_empty_r in H; subst\n      end.\n      match goal with\n      | HO: outcome _ _, H: _ |- _ => specialize (H _ HO); rename H into HP\n      end.\n      destruct g. FlatToRiscvCommon.simpl_g_get.\n      simp.\n      subst.\n      cbn in *.\n      simp.\n      eapply runsToNonDet.runsToStep_cps.\n      match goal with\n      | H: iff1 allx _ |- _ => apply iff1ToEq in H; subst allx\n      end.\n\n      split; simpl_MetricRiscvMachine_get_set. {\n        intros _.\n        eapply ptsto_instr_subset_to_isXAddr4.\n        eapply shrink_footpr_subset. 1: eassumption.\n        cbn in *. wwcancel.\n      }\n\n      erewrite ptsto_bytes.load_bytes_of_sep; cycle 1.\n      { cbv [program ptsto_instr Scalars.truncated_scalar Scalars.littleendian] in *.\n        cbn [array bytes_per] in *.\n        simpl_MetricRiscvMachine_get_set.\n        wcancel_assumption. }\n      change (@Bind _ _) with (@free.bind MetricMinimalMMIO.action result) in *.\n      unfold free.bind at 1.\n\n      rewrite <-LittleEndian.split_eq, LittleEndian.combine_split.\n      rewrite Z.mod_small by eapply EncodeBound.encode_range.\n      rewrite DecodeEncode.decode_encode; cycle 1. {\n        epose proof Registers.arg_range_Forall as HH.\n        rewrite E3 in HH.\n        repeat match goal with HH : Forall _ (_::_)|-_ => inversion HH; subst; clear HH end.\n        split; cbn; unfold Encode.verify_S, funct3_SW, opcode_STORE; ssplit; try Lia.lia.\n      }\n      repeat fwd.\n\n      unfold getReg.\n      destr ((0 <? z1) && (z1 <? 32))%bool; cbv [valid_FlatImp_var] in *; [|exfalso; blia].\n      destr ((0 <? z2) && (z2 <? 32))%bool; cbv [valid_FlatImp_var] in *; [|exfalso; blia].\n      replace (map.get initialL_regs z1) with (Some x) by (symmetry; unfold map.extends in *; eauto).\n      replace (map.get initialL_regs z2) with (Some x0) by (symmetry; unfold map.extends in *; eauto).\n\n      cbv [Utility.add Utility.ZToReg MachineWidth_XLEN]; rewrite word.add_0_r.\n      unshelve erewrite (_ : _ = None); [eapply storeWord_in_MMIO_is_None; eauto|].\n\n      cbv [MinimalMMIO.nonmem_store FE310_mmio].\n      split; [trivial|].\n      split; [red; auto|].\n\n      repeat fwd.\n\n      eapply runsToNonDet.runsToDone.\n      simpl_MetricRiscvMachine_get_set.\n      simpl_word_exprs word_ok.\n      unfold mmioStoreEvent, signedByteTupleToReg in *.\n      unfold regToInt32.\n      rewrite LittleEndian.combine_split.\n      rewrite sextend_width_nop by reflexivity.\n      rewrite Z.mod_small by apply word.unsigned_range.\n      rewrite word.of_Z_unsigned.\n      apply eqb_eq in E. subst action.\n      cbn -[invalidateWrittenXAddrs] in *.\n      specialize (HPp1 mKeep). rewrite map.split_empty_r in HPp1. specialize (HPp1 eq_refl).\n      do 4 eexists.\n      split; eauto.\n      split; eauto.\n      split; [unfold map.only_differ; eauto|].\n      split. {\n        unfold id. MetricsToRiscv.solve_MetricLog.\n      }\n      split; eauto.\n      split; eauto.\n      split; eauto.\n      split; eauto.\n      split; eauto.\n      split. {\n        lazymatch goal with\n        | H: map.undef_on initialL_mem ?A |- _ =>\n          rename H into U; change (map.undef_on initialL_mem isMMIOAddr) in U; move U at bottom\n        end.\n        lazymatch goal with\n        | H: disjoint (of_list initialL_xaddrs) ?A |- _ =>\n          rename H into D; change (disjoint (of_list initialL_xaddrs) isMMIOAddr) in D;\n            move D at bottom\n        end.\n        lazymatch goal with\n        | H: FE310CSemantics.isMMIOAddr x |- _ =>\n          rename H into M0; change (isMMIOAddr x) in M0; move M0 at bottom\n        end.\n        lazymatch goal with\n        | H: word.unsigned x mod 4 = 0 |- _ => rename H into D4; move D4 at bottom\n        end.\n        assert (forall {T: Type} (a b c: set T), subset a b -> subset b c -> subset a c)\n          as subset_trans. {\n          clear. unfold subset, PropSet.elem_of. intros. firstorder idtac.\n        }\n        eapply subset_trans. 1: eassumption.\n        clear -D4 M0 D word_ok.\n        unfold invalidateWrittenXAddrs.\n        change removeXAddr with (@List.removeb word word.eqb).\n        rewrite ?ListSet.of_list_removeb.\n        unfold map.undef_on, map.agree_on, disjoint in *.\n        unfold subset, diff, singleton_set, of_list, PropSet.elem_of in *.\n        intros y HIn.\n        specialize (D y). destruct D; [contradiction|].\n        rewrite ?and_assoc.\n        split; [exact HIn|clear HIn].\n        eapply disjoint_MMIO_goal; assumption.\n      }\n      ssplit; eauto.\n      unfold invalidateWrittenXAddrs.\n      change removeXAddr with (@List.removeb word word.eqb).\n      rewrite ?ListSet.of_list_removeb.\n      repeat apply disjoint_diff_l.\n      assumption.\n\n    + (* MMInput *)\n      simpl in *|-.\n      match goal with\n      | H: FE310CSemantics.ext_spec _ _ _ _ _ |- _ => rename H into Ex\n      end.\n      unfold compile_interact in *.\n      cbv [FE310CSemantics.ext_spec] in Ex.\n      simpl in *|-.\n\n      rewrite E in *.\n      destruct (\"MMIOREAD\" =? action)%string eqn:EE in Ex; try contradiction.\n      destruct Ex as (?&?&(?&?&?)&?). subst mGive argvals.\n      repeat match goal with\n             | l: list _ |- _ => destruct l;\n                                   try (exfalso; (contrad || (cheap_saturate; contrad))); []\n             end.\n      destruct argvars; cycle 1. {\n        exfalso.\n        match goal with\n        | A: map.getmany_of_list _ ?L1 = Some ?L2 |- _ =>\n          clear -A; cbn in *; simp; destruct_one_match_hyp; congruence\n        end.\n      }\n      cbn in *|-.\n      match goal with\n      | H: map.split _ _ map.empty |- _ => rewrite map.split_empty_r in H; subst\n      end.\n      destruct g. FlatToRiscvCommon.simpl_g_get.\n      simp.\n      subst.\n      cbn in *.\n      eapply runsToNonDet.runsToStep_cps.\n      match goal with\n      | H: iff1 allx _ |- _ => apply iff1ToEq in H; subst allx\n      end.\n\n      split; simpl_MetricRiscvMachine_get_set. {\n        intros _.\n        eapply ptsto_instr_subset_to_isXAddr4.\n        eapply shrink_footpr_subset. 1: eassumption.\n        unfold program.\n        cbn in *. wwcancel.\n      }\n      erewrite ptsto_bytes.load_bytes_of_sep; cycle 1.\n      { cbv [program ptsto_instr Scalars.truncated_scalar Scalars.littleendian] in *.\n        cbn [array bytes_per] in *.\n        simpl_MetricRiscvMachine_get_set.\n        wcancel_assumption. }\n\n      change (@Bind _ _) with (@free.bind MetricMinimalMMIO.action result) in *.\n      unfold free.bind at 1.\n\n      rewrite <-LittleEndian.split_eq, LittleEndian.combine_split.\n      rewrite Z.mod_small by (eapply EncodeBound.encode_range).\n      rewrite DecodeEncode.decode_encode; cycle 1. {\n        epose proof Registers.arg_range_Forall as HH.\n        rewrite E1 in HH.\n        repeat match goal with HH : Forall _ (_::_)|-_ => inversion HH; subst; clear HH end.\n        split; cbn; unfold Encode.verify_I, opcode_LOAD, funct3_LW; ssplit; try Lia.lia.\n      }\n\n      repeat fwd.\n\n      unfold getReg.\n      destr ((0 <? z1) && (z1 <? 32))%bool; cbv [valid_FlatImp_var] in *; [|exfalso; blia].\n      replace (map.get initialL_regs z1) with (Some x) by (symmetry; unfold map.extends in *; eauto).\n\n      split; try discriminate.\n      cbv [Utility.add Utility.ZToReg MachineWidth_XLEN]; rewrite word.add_0_r.\n      unshelve erewrite (_ : _ = None); [eapply loadWord_in_MMIO_is_None|]; eauto.\n\n      cbv [MinimalMMIO.nonmem_load FE310_mmio].\n      split; [trivial|].\n      split; [red; auto|].\n      split; [ cbv [MMIOReadOK];\n               exists (LittleEndian.split 4 0); trivial |].\n      intros.\n\n      repeat fwd.\n\n      eapply runsToNonDet.runsToDone.\n      simpl_MetricRiscvMachine_get_set.\n      simpl_word_exprs word_ok.\n\n      unfold mmioLoadEvent, signedByteTupleToReg.\n      match goal with\n      | A: forall _, outcome _ _ -> _, OC: forall _, outcome _ _ |- _ =>\n         epose proof (A (cons _ nil) (OC _)) as P; clear A\n      end.\n      cbn in P.\n      simp.\n      apply eqb_eq in EE. subst action.\n      cbn in *.\n      specialize (Pp1 mKeep). rewrite map.split_empty_r in Pp1. specialize (Pp1 eq_refl).\n      unfold setReg.\n      destr ((0 <? z1) && (z1 <? 32))%bool; [|exfalso;blia].\n      do 4 eexists.\n      split; eauto.\n      split; eauto.\n      split. {\n        unfold map.only_differ. intros. unfold union, of_list, elem_of, singleton_set. simpl.\n        rewrite map.get_put_dec.\n        destruct_one_match; auto.\n      }\n      split. {\n        unfold id. MetricsToRiscv.solve_MetricLog.\n      }\n      split. {\n        eapply map.put_extends. eassumption.\n      }\n      split. {\n        unfold map.forall_keys in *.\n        intros.\n        lazymatch goal with\n        | H : context [map.get _ ?x] |- _ <= ?x < _ =>\n          rewrite map.get_put_dec in H\n        end.\n        destruct_one_match_hyp. 1: blia. eauto.\n      }\n      split. {\n        rewrite map.get_put_diff; eauto. unfold RegisterNames.sp. blia.\n      }\n      split. {\n        eapply @regs_initialized.preserve_regs_initialized_after_put.\n        2: eassumption.\n        typeclasses eauto.\n      }\n      eauto 10.\n  Time Qed. (* takes ~70s *)\n\nEnd MMIO1.\n", "meta": {"author": "mit-plv", "repo": "bedrock2", "sha": "7f2d764ed79f394fe715505a04301d0fb502407f", "save_path": "github-repos/coq/mit-plv-bedrock2", "path": "github-repos/coq/mit-plv-bedrock2/bedrock2-7f2d764ed79f394fe715505a04301d0fb502407f/compiler/src/compiler/MMIO.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.21448447858812217}}
{"text": "Require Import Util LengthEq IL RenamedApart LabelsDefined OptionR.\nRequire Import Keep Drop Take Restrict SetOperations OUnion.\nRequire Import Annotation Liveness.Liveness Coherence Delocation.\nRequire Import AddParam AddAdd MoreListSet DelocationAlgo DelocationAlgoIsCalled.\nRequire Import PartialOrder.\n\nSet Implicit Arguments.\n\nOpaque to_list.\n\nLemma additionalParameters_live_monotone ZL Lv LV' s an' LV lv\n: live_sound Imperative ZL Lv s lv\n  -> additionalParameters_live LV s lv an'\n  -> PIR2 Subset LV' (Lv \\\\ ZL)\n  -> additionalParameters_live LV' s lv an'.\nProof.\n  intros LS APLS LE.\n  general induction APLS; invt live_sound;\n    eauto using additionalParameters_live.\n  - inv_get. simpl in *.\n    edestruct PIR2_nth_2 as [? [A B]]; eauto using zip_get.\n    econstructor; eauto using map_get_1; simpl; eauto with cset.\n  - lnorm.\n    econstructor; eauto.\n    + intros. exploit H1; eauto.\n      rewrite zip_app; eauto with len. eapply PIR2_app; eauto.\n      eapply PIR2_get. intros. inv_get.\n      exploit H; eauto using @ifFstR.\n      eauto 30 with len.\n    + exploit IHAPLS; eauto.\n      rewrite zip_app; eauto with len. eapply PIR2_app; eauto.\n      eapply PIR2_get. intros. inv_get.\n      exploit H; eauto using @ifFstR.\n      eauto 30 with len.\nQed.\n\nLemma computeParameters_live b ZL Lv AP s lv\n: live_sound Imperative ZL Lv s lv\n  -> poLe AP (Lv \\\\ ZL)\n  -> length Lv = length ZL\n  -> length ZL = length AP\n  -> noUnreachableCode (isCalled b) s\n  -> additionalParameters_live (oget ⊝ (snd (computeParameters (Lv \\\\ ZL) AP s lv)))\n                              s lv (fst (computeParameters (Lv \\\\ ZL) AP s lv)).\nProof.\n  intros LS SUB LEN1 LEN2 REACH.\n  general induction LS; inv REACH; simpl in *; repeat let_pair_case_eq; repeat let_case_eq;\n    subst; simpl in *.\n  - econstructor; eauto 20 using addParam_Subset with len.\n  - econstructor; eauto with len.\n    + eapply additionalParameters_live_monotone; eauto.\n      * eapply PIR2_ifFstR_Subset_oget, ifFstR_zip_ounion;\n          eauto using computeParameters_LV_DL with len.\n    + eapply additionalParameters_live_monotone; eauto.\n      * eapply PIR2_ifFstR_Subset_oget, ifFstR_zip_ounion;\n          eauto using computeParameters_LV_DL with len.\n  - inv_get. hnf in SUB. PIR2_inv. inv_get.\n    econstructor; eauto using map_get_eq, keep_Some; simpl; eauto with cset.\n    etransitivity; eauto. eapply SUB0.\n  - econstructor.\n  - exploit computeParameters_length as Len1; eauto with len.\n    lnorm.\n    econstructor.\n    + eauto with len.\n    + intros. inv_get.\n      pose proof (H8 _ H10).\n      edestruct computeParameters_isCalledFrom_get_Some; try eapply H9;\n        eauto using map_get_1, get_app with len; dcr; subst.\n      intros; edestruct H2; eauto.\n      simpl. rewrite of_list_3.\n      exploit (@computeParameters_LV_DL (fst ⊝ F ++ ZL) (getAnn ⊝ als ++ Lv) (tab {}  ‖F‖ ++ AP));\n        eauto using PIR2_Subset_tab_extend with len.\n      len_simpl.\n      exploit computeParametersF_LV_DL; eauto; eauto with len.\n      eapply PIR2_nth in H13; eauto. dcr; inv_get.\n      split.\n      rewrite H15. clear_all; cset_tac.\n      edestruct H2; eauto.\n      eapply NoDupA_app; eauto.\n      eapply nodup_to_list_eq.\n      intros.\n      rewrite InA_In_eq in H18. rewrite InA_in in H18.\n      rewrite InA_In_eq in H17. rewrite InA_in in H17.\n      rewrite of_list_3 in H18.\n      revert H15 H17 H18. clear_all. cset_tac.\n    + intros. inv_get. len_simpl.\n      exploit H1; eauto using pair_eta, PIR2_Subset_tab_extend with len.\n      eapply additionalParameters_live_monotone; try eapply H9; eauto.\n      rewrite map_map.\n      rewrite of_list_oto_list_oget.\n      rewrite <- List.map_app. rewrite <- take_eta.\n      eapply PIR2_ifFstR_Subset_oget.\n      eapply ifFstR_addAdds2. rewrite zip_app; eauto with len.\n      eapply computeParametersF_LV_DL; eauto with len.\n      eapply computeParameters_LV_DL; eauto using PIR2_Subset_tab_extend with len.\n    + eapply additionalParameters_live_monotone; try eapply IHLS;\n        eauto using PIR2_Subset_tab_extend with len.\n      rewrite map_map.\n      rewrite of_list_oto_list_oget.\n      rewrite <- List.map_app. rewrite <- take_eta.\n      eapply PIR2_ifFstR_Subset_oget.\n      eapply ifFstR_addAdds2. rewrite zip_app; eauto with len.\n      eapply computeParametersF_LV_DL; eauto with len.\n      eapply computeParameters_LV_DL; eauto using PIR2_Subset_tab_extend with len.\n    + rewrite map_length. rewrite take_length_le; eauto.\n      rewrite zip_length2.\n      * eauto 20 with len.\n      * rewrite fold_zip_ounion_length; eauto.\n        -- eauto 20 with len.\n        -- eapply computeParametersF_length; eauto.\n           rewrite computeParameters_length; eauto with len.\n           eauto with len.\nQed.\n\nLemma is_live b s lv\n: live_sound Imperative nil nil s lv\n  -> noUnreachableCode (isCalled b) s\n  -> additionalParameters_live nil s lv (fst (computeParameters nil nil s lv)).\nProof.\n  intros.\n  assert (snd (computeParameters nil nil s lv) = nil). {\n    exploit computeParameters_AP_LV; eauto.\n    inv H1; eauto.\n  }\n  exploit computeParameters_live; eauto; try reflexivity.\n  simpl in *. rewrite H1 in H2. eauto.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Coherence/DelocationAlgoLive.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.21444739695432277}}
{"text": "(* Copyright (c) 2011. Greg Morrisett, Gang Tan, Joseph Tassarotti, \n   Jean-Baptiste Tristan, and Edward Gan.\n\n   This file is part of RockSalt.\n\n   This file is free software; you can redistribute it and/or\n   modify it under the terms of the GNU General Public License as\n   published by the Free Software Foundation; either version 2 of\n   the License, or (at your option) any later version.\n*)\n\n\n(** Broke out the reasoning for the \"masked jumps\" used in the NaCL verifier\n    so I don't have to wait for long compile times on DFACorrectness.v\n*)\nRequire Import Coqlib.\nRequire Import Parser.\nRequire Import Ascii.\nRequire Import String.\nRequire Import List.\nRequire Import Bits.\nRequire Import Decode.\nRequire Import VerifierDFA.\nRequire Import Eqdep.\nUnset Automatic Introduction.\nSet Implicit Arguments.\nRequire ExtrOcamlString.\nRequire ExtrOcamlNatBigInt.\nRequire ExtrOcamlNatInt.\nImport X86_PARSER_ARG.\nImport X86_PARSER.\nImport X86_BASE_PARSER.\nImport X86Syntax.\nRequire Import DFACorrectness.\nHint Constructors in_parser.\n\nImport ABSTRACT_MAKE_DFA.\n\nLemma nacl_jmp_parser_splits' : \n  forall s v, \n    in_parser (alts nacljmp_mask) (flat_map byte_explode s) v -> \n    exists s1, exists s2, exists r,\n      r <> ESP /\\ \n      flat_map byte_explode s = s1 ++ s2 /\\\n      in_parser (nacl_MASK_p r) s1 (fst v) /\\ \n      in_parser (nacl_JMP_p r |+| nacl_CALL_p r) s2 (snd v).\nProof.\n  unfold nacljmp_mask. unfold nacljmp_p. simpl ; unfold never. intros. \n  repeat pinv ; simpl ; \n  econstructor ; econstructor ; econstructor ; repeat split ; eauto ; try congruence ;\n  match goal with \n    | [ H : in_parser (nacl_JMP_p _) _ _ |- _ ] => eapply Alt_left_pi\n    | [ H : in_parser (nacl_CALL_p _) _ _ |- _ ] => eapply Alt_right_pi\n  end ; auto.\nQed.\n\nLemma byte_explode_bits b : \n  exists b1,exists b2,exists b3,exists b4,exists b5,exists b6,exists b7,exists b8,\n    byte_explode b = b1::b2::b3::b4::b5::b6::b7::b8::nil.\nProof.\n  unfold byte_explode. repeat econstructor.\nQed.\n\nLocal Open Scope nat_scope.\nLemma split_bytes_n : \n  forall n bs x1 x2,\n    flat_map byte_explode bs = x1 ++ x2 ->\n    length x1 = n * 8 -> \n    exists b1, exists b2, \n      bs = b1 ++ b2 /\\ flat_map byte_explode b1 = x1 /\\ flat_map byte_explode b2 = x2.\nProof.\n  induction n ; simpl ; intros. destruct x1. simpl in *. exists nil. exists bs.\n  simpl. auto. simpl in H0. congruence.\n\n  destruct x1. simpl in H0 ; assert False ; [omega | contradiction].\n  destruct x1. simpl in H0 ; assert False ; [omega | contradiction].\n  destruct x1. simpl in H0 ; assert False ; [omega | contradiction].\n  destruct x1. simpl in H0 ; assert False ; [omega | contradiction].\n  destruct x1. simpl in H0 ; assert False ; [omega | contradiction].\n  destruct x1. simpl in H0 ; assert False ; [omega | contradiction].\n  destruct x1. simpl in H0 ; assert False ; [omega | contradiction].\n  destruct x1. simpl in H0 ; assert False ; [omega | contradiction].\n  simpl in H0. assert (length x1 = n*8). omega. destruct bs. simpl in H. congruence.\n  replace (flat_map byte_explode (i :: bs)) with \n    (byte_explode i ++ flat_map byte_explode bs) in H; auto.\n  generalize (byte_explode_bits i). t. rewrite H2 in *.\n  injection H ; clear H ; intros ; subst.\n  specialize (IHn bs x1 x2 H H1). t. \n  exists (i::x). exists x0. replace (flat_map byte_explode (i :: x)) with\n  (byte_explode i ++ (flat_map byte_explode x)) ; auto. rewrite H2.\n  split. simpl. rewrite H3. auto. split. rewrite H4. auto. auto.\nQed.\n\nLemma nacl_jmp_parser_splits : \n  forall bs v,\n    in_parser (alts nacljmp_mask) (flat_map byte_explode bs) v -> \n    exists b1, exists b2, exists r,\n      r <> ESP /\\ \n      bs = b1 ++ b2 /\\ \n      in_parser (nacl_MASK_p r) (flat_map byte_explode b1) (fst v) /\\ \n      in_parser (nacl_JMP_p r |+| nacl_CALL_p r) (flat_map byte_explode b2) (snd v).\nProof.\n  intros. generalize (nacl_jmp_parser_splits' _ H). t.\n  assert (length x = 24). unfold nacl_MASK_p in H2. unfold bitsleft in H2.\n  simpl in H2. repeat pinv ; simpl ; auto.\n  generalize (split_bytes_n 3 _ _ _ H1 H4). t. exists x2. exists x3. exists x1.\n  repeat split ; auto. rewrite H6. auto. rewrite H7. auto.\nQed.\n\nImport CheckDeterministic.\n\nLemma byte2token_app xs n1 n2 :\n  List.map byte2token xs = n1 ++ n2 -> \n  exists b1, exists b2, \n    xs = b1 ++ b2 /\\ List.map byte2token b1 = n1 /\\ List.map byte2token b2 = n2.\nProof.\n  induction xs. simpl. intros. generalize (nil_is_nil_app_nil _ _ H). t. subst.\n  exists nil ; exists nil ; auto.\n  simpl ; intros ; destruct n1. simpl in *. destruct n2 ; try congruence.\n  injection H ; clear H ; intros. specialize (IHxs nil n2 H). t. subst.\n  exists x. exists (a::x0). assert (x = nil). destruct x ; auto. simpl in H2 ; \n  congruence. subst. simpl. auto. simpl in *. injection H ; clear H ; intros.\n  specialize (IHxs n1 n2 H). t. exists (a::x). exists x0. rewrite H1.\n  split ; auto. simpl. split. rewrite H0. rewrite H2. auto. auto.\nQed.\n\nLemma nat2bools_byte2token_is_byte_explode xs : \n  flat_map nat2bools (List.map byte2token xs) = flat_map byte_explode xs.\nProof.\n  induction xs. auto. replace (flat_map byte_explode (a::xs)) with \n  (byte_explode a ++ (flat_map byte_explode xs)) ; auto.\n  replace (flat_map nat2bools (List.map byte2token (a::xs))) with\n    (nat2bools (byte2token a) ++ (flat_map nat2bools (List.map byte2token xs))) ; auto.\n  rewrite IHxs. replace (nat2bools (byte2token a)) with (byte_explode a) ; auto.\n  clear IHxs. unfold byte_explode. unfold nat2bools. replace (Z_of_nat (byte2token a))\n  with (Word.unsigned a) ; auto. unfold byte2token.\n  rewrite inj_Zabs_nat. unfold Word.unsigned. generalize (Word.intrange _ a).\n  intros. rewrite (Zabs_eq _).  auto. omega.\nQed.\n\nLemma reg_parser r s : \n  in_parser (bitslist (register_to_bools r)) s tt -> \n  in_parser reg s r.\nProof.\n  unfold reg, field ; destruct r ; simpl ; intros ; repeat pinv ; \n  repeat econstructor ; eauto.\nQed.\n\nLemma mask_parser s : \n  in_parser (bitslist (int_to_bools safeMask)) s tt -> \n  in_parser byte s safeMask.\nProof.\n  simpl. unfold byte. unfold field. simpl. intros.\n  repeat pinv. repeat econstructor.\nQed.\n\nLemma nacl_mask_subset r s i : \n  in_parser (nacl_MASK_p r) s i -> \n  in_parser instruction_parser s (mkPrefix None None false false, i).\nProof.\n  unfold nacl_MASK_p. intros.\n  unfold instruction_parser. unfold instruction_parser_list. eapply in_alts_app.\n  left. eapply in_map_alts. replace s with (nil ++ s) ; auto. econstructor ; eauto.\n  unfold prefix_parser_nooverride. unfold option_perm2. econstructor ; eauto.\n  eapply Alt_left_pi. econstructor ; eauto. auto. unfold instr_parsers_nosize_pre.\n  simpl. repeat  match goal with \n      | [ |- in_parser ((AND_p _) |+| _) _ _ ] => eapply Alt_left_pi \n      | [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi\n    end.\n  unfold AND_p. unfold logic_or_arith_p. eapply Alt_right_pi. eapply Alt_left_pi.\n  unfold bitsleft in H. repeat \n  match goal with \n    | [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t\n    | [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t\n  end ; subst.\n  econstructor. econstructor. econstructor. eauto. econstructor. econstructor.\n  eauto. econstructor. econstructor. eauto. econstructor. econstructor. eauto.\n  econstructor. eapply reg_parser. destruct x21. eauto. eapply mask_parser.\n  destruct x22. eauto. eauto. eauto. eauto. eauto. eauto. eauto. eauto.\n  eauto. eauto. eauto. eauto. eauto. eauto. eauto. simpl. auto.\nQed.\n\nLemma nacl_jump_subset r s i : \n  in_parser (nacl_JMP_p r |+| nacl_CALL_p r) s i -> \n  in_parser instruction_parser s (mkPrefix None None false false, i).\nProof.\n  intros. unfold instruction_parser. unfold instruction_parser_list. eapply in_alts_app.\n  left. eapply in_map_alts. replace s with (nil ++ s) ; auto. econstructor ; eauto.\n  unfold prefix_parser_nooverride, option_perm2. econstructor ; eauto.\n  eapply Alt_left_pi ; eauto. econstructor ; eauto. auto.\n  unfold instr_parsers_nosize_pre. simpl. repeat pinv.\n  repeat match goal with \n           | [ |- in_parser (JMP_p |+| _) _ _ ] => eapply Alt_left_pi\n           | [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi\n         end. \n  unfold nacl_JMP_p, JMP_p in *. eapply Alt_right_pi. eapply Alt_right_pi.\n  eapply Alt_left_pi. unfold bitsleft in H. repeat\n  match goal with \n    | [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t\n    | [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t\n  end ; subst.\n  econstructor. econstructor. econstructor. eapply H3. econstructor. econstructor.\n  eauto. unfold ext_op_modrm2. econstructor. repeat eapply Alt_right_pi.\n  econstructor. eauto. econstructor. eauto. unfold rm11. econstructor.\n  eapply reg_parser. destruct x18. eauto. eauto. eauto. eauto. eauto. eauto.\n  eauto. eauto. eauto. eauto. auto. eauto. eauto. simpl. auto.\n  repeat match goal with \n           | [ |- in_parser (CALL_p |+| _) _ _ ] => eapply Alt_left_pi\n           | [ |- in_parser (_ |+| _) _ _ ] => eapply Alt_right_pi\n         end. \n  unfold nacl_CALL_p, CALL_p in *. eapply Alt_right_pi. \n  eapply Alt_left_pi. unfold bitsleft in H. repeat\n  match goal with \n    | [ H : in_parser (_ @ _) _ _ |- _ ] => generalize (inv_map_pi H) ; clear H ; t\n    | [ H : in_parser (_ $ _) _ _ |- _ ] => generalize (inv_cat_pi H) ; clear H ; t\n  end ; subst.\n  econstructor. econstructor. econstructor. eapply H3. econstructor. econstructor.\n  eauto. unfold ext_op_modrm2. econstructor. repeat eapply Alt_right_pi.\n  econstructor. eauto. econstructor. eauto. unfold rm11. econstructor.\n  eapply reg_parser. destruct x18. eauto. eauto. eauto. eauto. eauto. eauto.\n  eauto. eauto. eauto. eauto. auto. eauto. eauto. simpl. auto.\nQed.\n\nLemma nacl_jmp_parser_inv r s1 s2 i1 i2: \n  r <> ESP -> \n  in_parser (nacl_MASK_p r) s1 i1 -> \n  in_parser (nacl_JMP_p r |+| nacl_CALL_p r) s2 i2 -> \n  nacljmp_mask_instr (mkPrefix None None false false) i1 \n                     (mkPrefix None None false false) i2 = true.\nProof.\n  unfold nacl_MASK_p, nacl_JMP_p, nacl_CALL_p ; intros. \n  repeat pinv ; unfold nacljmp_mask_instr ; simpl ; destruct (register_eq_dec r ESP) ; \n  try congruence ; destruct (register_eq_dec r r) ; try congruence ; auto.\nQed.\n\nLemma nacljmp_dfa_corr1 : \n  forall (d:DFA),\n    abstract_build_dfa 256 nat2bools 400 (par2rec (alts nacljmp_mask)) = Some d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize 256 d (List.map byte2token bytes) = Some (n,nats2) -> \n      exists bytes1, exists pfx1:prefix, exists ins1:instr, exists bytes2,\n        exists pfx2:prefix, exists ins2:instr,\n        in_parser (alts nacljmp_mask) (flat_map byte_explode (bytes1 ++ bytes2))\n        (ins1,ins2) /\\\n        in_parser instruction_parser (flat_map byte_explode bytes1) (pfx1,ins1) /\\ \n        in_parser instruction_parser (flat_map byte_explode bytes2) (pfx2,ins2) /\\ \n        n = length (bytes1 ++ bytes2) /\\ \n        bytes = bytes1 ++ bytes2 ++ (List.map nat_to_byte nats2) /\\ \n        nacljmp_mask_instr pfx1 ins1 pfx2 ins2 = true /\\\n        (forall ts3 ts4,\n          (length ts3 < length (bytes1 ++ bytes2))%nat -> \n          bytes = ts3 ++ ts4 ->\n          forall v0, ~ in_parser (alts nacljmp_mask) (flat_map byte_explode ts3) v0).\nProof.\n  intros. subst. rewrite build_dfa_eq in H.\n  generalize (dfa_recognize_corr _ _ _ _ H (List.map byte2token bytes)\n    (bytesLt256 _)). clear H. rewrite H0. clear H0. mysimp.\n  generalize (byte2token_app _ _ _ H). t. subst.\n  rewrite (nat2bools_byte2token_is_byte_explode _) in H1.\n  generalize (nacl_jmp_parser_splits _ H1). clear H1. t. destruct x0. simpl in *.\n  exists x. exists (mkPrefix None None false false). exists i.\n  exists x3. exists (mkPrefix None None false false). exists i0. split.\n  rewrite flat_map_app. unfold nacljmp_p. destruct x4 ; try congruence ;\n  repeat (try (eapply Alt_left_pi ; econstructor ; eauto ; fail) ; eapply Alt_right_pi).\n  split. apply (nacl_mask_subset H3). split. eapply (nacl_jump_subset H4). \n  split. rewrite H1. rewrite map_length. auto. split. subst. rewrite app_assoc.\n  assert (x2 = List.map nat_to_byte (List.map byte2token x2)) ; [ idtac | congruence].\n  rewrite n2bs. auto. split. eapply nacl_jmp_parser_inv ; eauto.\n  intros. rewrite H1 in H2. specialize (H2 (List.map byte2token ts3)\n  (List.map byte2token ts4)). repeat rewrite map_length in H2.\n  specialize (H2 H5). subst. rewrite H6 in H2. rewrite map_app in H2.\n  specialize (H2 (eq_refl _)). rewrite nat2bools_byte2token_is_byte_explode in H2.\n  intro. apply (H2 v0 H1).\nQed.\n\nLemma flat_map_nil_is_nil x : \n  flat_map byte_explode x = nil -> x = nil.\nProof.\n  induction x ; intros. auto. replace (flat_map byte_explode (a :: x))\n  with (byte_explode a ++ (flat_map byte_explode x)) in H ; auto.\n  generalize (nil_is_nil_app_nil _ _ (eq_sym H)). t.\n  clear IHx H H1. assert False ; try contradiction. \n  unfold byte_explode in H0. congruence.\nQed.\n\n(** This should get placed in DFACorrectness and used for the other 2 DFAs. *)\nLemma in_parser_implies_simple_parse\n  bytes1 pfx ins bytes2 :\n  in_parser instruction_parser (flat_map byte_explode bytes1) (pfx,ins) ->\n  simple_parse (bytes1 ++ bytes2) = Some (pfx, ins, bytes2).\nProof.\n  unfold simple_parse ; intros.\n  Opaque instruction_parser. \n  generalize (@simple_parse'_corr2 \n    instruction_parser (bytes1 ++ bytes2) initial_parser_state nil \n    (eq_refl _) (eq_refl _)).\n  simpl ; intros. \n  assert (forall s1 s2, nil = s1 ++ s2 -> \n    apply_null (snd (parser2regexp instruction_parser))\n          (deriv_parse' (fst (parser2regexp instruction_parser))\n             (flat_map byte_explode s1))\n          (wf_derivs (snd (parser2regexp instruction_parser))\n             (flat_map byte_explode s1)\n             (fst (parser2regexp instruction_parser))\n             (p2r_wf instruction_parser initial_ctxt)) = nil). intros. clear H0.\n  generalize (nil_is_nil_app_nil _ _ H1) ; t ; subst.\n  generalize (min_count_not_null _ min_instruction_bits).\n  generalize instruction_parser. clear H H1. simpl. intro.\n  generalize (apply_null (snd(parser2regexp p)) (fst (parser2regexp p))).\n  assert (wf_derivs (snd (parser2regexp p)) nil (fst (parser2regexp p))\n    (p2r_wf p initial_ctxt) = p2r_wf p initial_ctxt). \n  apply Coqlib.proof_irrelevance. \n  generalize H. clear H. unfold parser2regexp.\n  generalize (p2r_wf p initial_ctxt). intros. rewrite <- H in H0. auto.\n  specialize (H0 H1). clear H1.\n  destruct (simple_parse' initial_parser_state (bytes1 ++ bytes2)).\n  destruct p. t. destruct p. assert (length bytes1 >= length x).\n  assert (length bytes1 < length x -> False). intros.\n  eapply (H2 bytes1 bytes2 (eq_refl _) H3 _ H). omega.\n  assert (exists s2, bytes1 = x ++ s2). generalize bytes1 x H3 H0.\n  induction bytes0 ; destruct x0 ; simpl ; intros. exists nil. auto.\n  assert False. omega. contradiction. subst. eauto. injection H5 ; clear H5 ; t ; subst.\n  assert (length bytes0 >= length x0). omega. specialize (IHbytes0 _ H6 H5). t.\n  subst. eauto. t. subst. rewrite app_ass in H0. generalize (app_inv_head _ _ _ H0).\n  intros. subst. rewrite flat_map_app in H. generalize (parser_determ H). intros.\n  specialize (H4 _ _ (p,i) (eq_refl _) H1). t. injection H5 ; intros.\n  rewrite (flat_map_nil_is_nil _ H4). subst.  auto.\n  specialize (H0 bytes1 bytes2 (pfx,ins) (eq_refl _)). contradiction.\nQed.\n\nLemma nacljmp_dfa_corr : \n  forall (d:DFA),\n    abstract_build_dfa 256 nat2bools 400 (par2rec (alts nacljmp_mask)) = Some d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize 256 d (List.map byte2token bytes) = Some (n, nats2) -> \n      exists bytes1, exists pfx1:prefix, exists ins1:instr, exists bytes2,\n        exists pfx2:prefix, exists ins2:instr,\n        simple_parse bytes = Some ((pfx1,ins1), bytes2 ++ List.map nat_to_byte nats2) /\\\n        simple_parse (bytes2 ++ List.map nat_to_byte nats2) = \n            Some ((pfx2,ins2), List.map nat_to_byte nats2) /\\\n        nacljmp_mask_instr pfx1 ins1 pfx2 ins2 = true /\\\n        n = length (bytes1 ++ bytes2) /\\ \n        bytes = bytes1 ++ bytes2 ++ (List.map nat_to_byte nats2).\nProof.\n  intros d H bytes n nats2 H1.\n  generalize (@nacljmp_dfa_corr1 d H bytes n nats2 H1). t.\n  exists x. exists x0. exists x1. exists x2. exists x3. exists x4. repeat split ; auto.\n  rewrite H5. eapply in_parser_implies_simple_parse ; auto.\n  eapply in_parser_implies_simple_parse ; auto.\nQed.\n\nLemma nacljmp_mask_dfa_length : \n  forall (d:DFA), \n    (* Need to use abstract_build_dfa for the same reason as above I believe *)\n    abstract_build_dfa 256 nat2bools 400 (par2rec (alts nacljmp_mask)) = Some d -> \n    forall (bytes:list int8) (n:nat) (nats2:list nat),\n      dfa_recognize 256 d (List.map byte2token bytes) = Some (n, nats2) -> \n        (n <= 15). \nProof.\n  intros. apply nacljmp_dfa_corr1 in H0.\n   destruct H0. destruct H0.\n   destruct H0. destruct H0. \n   destruct H0. destruct H0. \n   destruct H0.\n   destruct H1. destruct H2.\n   destruct H3.\n   assert (max_bit_count (alts nacljmp_mask) = Some 40).\n     vm_compute; trivial.\n   eapply max_count_corr in H0.\n   rewrite H5 in H0.\n   rewrite byte_explode_mult_len in H0.\n   rewrite H3. omega.\n   auto.\nQed.\n", "meta": {"author": "gangtan", "repo": "CPUmodels", "sha": "a6decc3085e1f8d8d4875e67f9ad9c7663910f8a", "save_path": "github-repos/coq/gangtan-CPUmodels", "path": "github-repos/coq/gangtan-CPUmodels/CPUmodels-a6decc3085e1f8d8d4875e67f9ad9c7663910f8a/x86model/RockSalt/NACLjmp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21437850147737175}}
{"text": "Require Import CompCert.Events.\nRequire Import CompCert.Smallstep.\nRequire Import Common.Definitions.\nRequire Import Common.Util.\nRequire Import Common.Values.\nRequire Import Common.Memory.\nRequire Import Common.CompCertExtensions.\nRequire Import Common.Traces.\nRequire Import Common.RenamingOption.\nRequire Import Source.Language.\nRequire Import Source.GlobalEnv.\nRequire Import Lib.Tactics.\nRequire Import Lib.Monads.\nRequire Import Lib.Extra.\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype seq.\nFrom mathcomp Require ssrnat.\n\nRequire Import Lia.\n\nCanonical ssrnat.nat_eqType.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\nImport Source.\n\nInductive cont : Type :=\n| Kstop\n| Kbinop1 (op: binop) (re: expr) (k: cont)\n| Kbinop2 (op: binop) (lv: value) (k: cont)\n| Kseq (e: expr) (k: cont)\n| Kif (e1: expr) (e2: expr) (k: cont)\n| Kalloc (k: cont)\n| Kderef (k: cont)\n| Kassign1 (e: expr) (k: cont)\n| Kassign2 (v: value) (k: cont)\n| Kcall (C: Component.id) (P: Procedure.id) (k: cont)\n| Kcallptr1 (funptr: expr) (k: cont)\n| Kcallptr2 (arg: value) (k: cont)  \n.\n\nModule CS.\n\nRecord frame : Type := Frame {\n  f_component : Component.id;\n  f_arg       : value;\n  f_cont      : cont\n}.\n\nDefinition stack : Type := list frame.\n\nRecord state : Type := State {\n  s_component : Component.id;\n  s_stack     : stack;\n  s_memory    : Memory.t;\n  s_cont      : cont;\n  s_expr      : expr;\n  s_arg       : value\n}.\n\nNotation \"[ 'State' C , stk , mem , k , e , arg ]\" :=\n  (State C stk mem k e arg)\n  (at level 0, format \"[ 'State'  C ,  stk ,  mem ,  k ,  e ,  arg ]\").\n\nLtac unfold_state st :=\n  let C := fresh \"C\" in\n  let s := fresh \"s\" in\n  let mem := fresh \"mem\" in\n  let k := fresh \"k\" in\n  let e := fresh \"e\" in\n  let arg := fresh \"arg\" in\n  destruct st as [C s mem k e arg].\n\nLtac unfold_states :=\n  repeat (match goal with\n          | st: state |- _ => unfold_state st\n          end).\n\nImport MonadNotations.\nOpen Scope monad_scope.\n\nDefinition initial_machine_state (p: program) : state :=\n  match prog_main p with\n  | Some main_expr => State Component.main [::] (prepare_buffers p) Kstop main_expr (Int 0)\n  | None =>\n    (* this case shouldn't happen for a well formed p *)\n    State Component.main [::] emptym Kstop E_exit (Int 0)\n  end.\n\n(* transition system *)\n\nDefinition initial_state (p: program) (st: state) : Prop :=\n  st = initial_machine_state p.\n\nDefinition final_state (st: state) : Prop :=\n  let: State C s mem k e arg := st in\n  e = E_exit \\/ (exists v, e = E_val v /\\ k = Kstop /\\ s = []).\n\nInductive kstep (G: global_env) : state -> trace event -> state -> Prop :=\n| KS_Binop1 : forall C s mem k op e1 e2 arg,\n    kstep G [State C, s, mem, k, E_binop op e1 e2, arg] E0\n            [State C, s, mem, Kbinop1 op e2 k, e1, arg]\n| KS_Binop2 : forall C s mem k op v1 e2 arg,\n    kstep G [State C, s, mem, Kbinop1 op e2 k, E_val v1, arg] E0\n            [State C, s, mem, Kbinop2 op v1 k, e2, arg]\n| KS_BinopEval : forall C s mem k op v1 v2 arg,\n    kstep G [State C, s, mem, Kbinop2 op v1 k, E_val v2, arg] E0\n            [State C, s, mem, k, E_val (eval_binop op v1 v2), arg]\n| KS_Seq1 :  forall C s mem k e1 e2 arg,\n    kstep G [State C, s, mem, k, E_seq e1 e2, arg] E0\n            [State C, s, mem, Kseq e2 k, e1, arg]\n| KS_Seq2 : forall C s mem k v e2 arg,\n    kstep G [State C, s, mem, Kseq e2 k, E_val v, arg] E0\n            [State C, s, mem, k, e2, arg]\n| KS_If1 : forall C s mem k e1 e2 e3 arg,\n    kstep G [State C, s, mem, k, E_if e1 e2 e3, arg] E0\n            [State C, s, mem, Kif e2 e3 k, e1, arg]\n| KS_If2 : forall C s mem k e2 e3 i arg,\n    kstep G [State C, s, mem, Kif e2 e3 k, E_val (Int i), arg] E0\n            [State C, s, mem, k, if i != 0%Z then e2 else e3, arg]\n| KS_Arg : forall C s mem k v,\n    kstep G [State C, s, mem, k, E_arg, v] E0\n            [State C, s, mem, k, E_val v, v]\n| KS_LocalBuffer : forall C s mem k arg,\n    kstep G [State C, s, mem, k, E_local, arg] E0\n            [State C, s, mem, k, E_val (Ptr (Permission.data,C,Block.local,0%Z)), arg]\n| KS_Alloc1 : forall C s mem k e arg,\n    kstep G [State C, s, mem, k, E_alloc e, arg] E0\n            [State C, s, mem, Kalloc k, e, arg]\n| KS_AllocEval : forall C s mem mem' k size ptr arg,\n    (size > 0) % Z ->\n    Memory.alloc mem C (Z.to_nat size) = Some (mem', ptr) ->\n    kstep G [State C, s, mem, Kalloc k, E_val (Int size), arg] E0\n            [State C, s, mem', k, E_val (Ptr ptr), arg]\n| KS_Deref1 : forall C s mem k e arg,\n    kstep G [State C, s, mem, k, E_deref e, arg] E0\n          [State C, s, mem, Kderef k, e, arg]\n| KS_DerefEval : forall C s mem k P' C' b' o' v arg,\n    (* C = C' -> *)\n    Memory.load mem (P',C',b',o') = Some v ->\n    kstep G [State C, s, mem, Kderef k, E_val (Ptr (P',C',b',o')), arg] E0\n          [State C, s, mem, k, E_val v, arg]\n| KS_FunPtr : forall C s mem k P Pexpr arg,\n    find_procedure (genv_procedures G) C P = Some Pexpr ->\n    kstep G [State C, s, mem, k, E_funptr P, arg] E0\n          [State C, s, mem, k, E_val (Ptr (Permission.code, C, P, 0%Z)), arg]\n| KS_Assign1 : forall C s mem k e1 e2 arg,\n    kstep G [State C, s, mem, k, E_assign e1 e2, arg] E0\n            [State C, s, mem, Kassign1 e1 k, e2, arg]\n| KS_Assign2 : forall C s mem k v e1 arg,\n    kstep G [State C, s, mem, Kassign1 e1 k, E_val v, arg] E0\n            [State C, s, mem, Kassign2 v k, e1, arg]\n| KS_AssignEval : forall C s mem mem' k v P' C' b' o' arg,\n    (* C = C' -> *)\n    Memory.store mem (P', C', b', o') v = Some mem' ->\n    kstep G [State C, s, mem, Kassign2 v k, E_val (Ptr (P', C', b', o')), arg] E0\n          [State C, s, mem', k, E_val v, arg]\n| KS_InitCall : forall C s mem k C' P e arg,\n    kstep G [State C, s, mem, k, E_call C' P e, arg] E0\n          [State C, s, mem, Kcall C' P k, e, arg]\n| KS_InitCallPtr1 : forall C s mem k e1 e2 arg,\n    kstep G [State C, s, mem, k, E_callptr e1 e2, arg] E0\n          [State C, s, mem, Kcallptr1 e1 k, e2, arg]\n| KS_InitCallPtr2 : forall C s mem k e1 v arg,\n    kstep G [State C, s, mem, Kcallptr1 e1 k, E_val v, arg] E0\n          [State C, s, mem, Kcallptr2 v k, e1, arg]\n| KS_InitCallPtr3 : forall C s mem k v C' P arg,\n    C = C' ->\n    kstep G [State C, s, mem, Kcallptr2 v k, E_val (Ptr (Permission.code, C', P, 0%Z)),\n             arg] E0\n          [State C, s, mem, Kcall C' P k, E_val v, arg]\n| KS_InternalCall : forall C s mem k C' P v P_expr old_call_arg,\n    C = C' ->\n    (* retrieve the procedure code *)\n    find_procedure (genv_procedures G) C' P = Some P_expr ->\n    kstep G [State C, s, mem, Kcall C' P k, E_val v, old_call_arg] E0\n            [State C', Frame C old_call_arg k :: s, mem, Kstop, P_expr, v]\n| KS_ExternalCall : forall C s mem k C' P v P_expr old_call_arg,\n    C <> C' ->\n    (* check permission *)\n    imported_procedure (genv_interface G) C C' P  ->\n    (* retrieve the procedure code *)\n    find_procedure (genv_procedures G) C' P = Some P_expr ->\n    kstep G [State C, s, mem, Kcall C' P k, E_val v, old_call_arg]\n            [:: ECall C P v mem C']\n            [State C', Frame C old_call_arg k :: s, mem, Kstop, P_expr, v]\n| KS_InternalReturn: forall C s mem k v arg C' old_call_arg,\n    C = C' ->\n    kstep G [State C, Frame C' old_call_arg k :: s, mem, Kstop, E_val v, arg] E0\n            [State C', s, mem, k, E_val v, old_call_arg]\n| KS_ExternalReturn: forall C s mem k v arg C' old_call_arg,\n    C <> C' ->\n    kstep G [State C, Frame C' old_call_arg k :: s, mem, Kstop, E_val v, arg]\n            [:: ERet C v mem C']\n            [State C', s, mem, k, E_val v, old_call_arg].\n\nLemma kstep_component G s t s' :\n  kstep G s t s' ->\n  s_component s' =\n  if t is e :: _ then next_comp_of_event e\n  else s_component s.\nProof. by case: s t s' /. Qed.\n\nLemma final_state_stuck G (st: state) :\n  final_state st ->\n  forall t st', ~ kstep G st t st'.\nProof.\nmove=> Hfinal t st' Hstep.\ncase: st t st' / Hstep Hfinal => //= *;\nby repeat match goal with\n| H : _ \\/ _ |- _ => case: H=> ?\n| H : exists _, _ |- _ => case: H => ??\n| H : _ /\\ _ |- _ => case: H => ??\nend.\nQed.\n\n(* functional kstep *)\n\nDefinition eval_kstep (G : global_env) (st : state) : option (trace event * state) :=\n  let: State C s mem k e arg := st in\n  match e with\n  (* pushing a new continuation *)\n  | E_binop b_op e1 e2 =>\n    ret (E0, [State C, s, mem, Kbinop1 b_op e2 k, e1, arg])\n  | E_seq e1 e2 =>\n    ret (E0, [State C, s, mem, Kseq e2 k, e1, arg])\n  | E_if e1 e2 e3 =>\n    ret (E0, [State C, s, mem, Kif e2 e3 k, e1, arg])\n  | E_arg =>\n    (* if arg is Int v then *)\n      ret (E0, [State C, s, mem, k, E_val arg(* (Int v) *), arg])\n    (* else None *)\n  | E_local =>\n    ret (E0, [State C, s, mem, k, E_val (Ptr (Permission.data, C, Block.local, 0%Z)), arg])\n  | E_alloc e =>\n    ret (E0, [State C, s, mem, Kalloc k, e, arg])\n  | E_deref e =>\n    ret (E0, [State C, s, mem, Kderef k, e, arg])\n  | E_funptr P =>\n    match find_procedure (genv_procedures G) C P with\n    | Some Pexpr => ret (E0, [State C, s, mem, k,\n                              E_val (Ptr (Permission.code, C, P, 0%Z)), arg])\n    | None => None\n    end\n  | E_assign e1 e2 =>\n    ret (E0, [State C, s, mem, Kassign1 e1 k, e2, arg])\n  | E_callptr e1 e2 =>\n    ret (E0, [State C, s, mem, Kcallptr1 e1 k, e2, arg])\n  | E_call C' P e =>\n    ret (E0, [State C, s, mem, Kcall C' P k, e, arg])\n  (* evaluating current continuation *)\n  | E_val v =>\n    match k with\n    | Kbinop1 b_op e2 k' =>\n      ret (E0, [State C, s, mem, Kbinop2 b_op v k', e2, arg])\n    | Kbinop2 b_op v1 k' =>\n      ret (E0, [State C, s, mem, k', E_val (eval_binop b_op v1 v), arg])\n    | Kseq e2 k' =>\n      ret (E0, [State C, s, mem, k', e2, arg])\n    | Kif e2 e3 k' =>\n      match v with\n      | Int z => ret (E0, [State C, s, mem, k', if z != 0%Z then e2 else e3, arg])\n      | _ => None\n      end\n    | Kalloc k' =>\n      match v with\n      | Int size =>\n        if (size >? 0) % Z then\n          do (mem',ptr) <- Memory.alloc mem C (Z.to_nat size);\n          ret (E0, [State C, s, mem', k', E_val (Ptr ptr), arg])\n        else\n          None\n      | _ => None\n      end\n    | Kderef k' =>\n      match v with\n      | Ptr (P',C',b',o') =>\n        (* if C == C' then *)\n          do v <- Memory.load mem (P',C',b',o');\n          ret (E0, [State C, s, mem, k', E_val v, arg])\n        (* else *)\n        (*   None *)\n      | _ => None\n      end\n    | Kassign1 e1 k' =>\n      ret (E0, [State C, s, mem, Kassign2 v k', e1, arg])\n    | Kassign2 v' k' =>\n      match v with\n      | Ptr (P',C',b',o') =>\n        (* if C == C' then *)\n          do mem' <- Memory.store mem (P',C',b',o') v';\n          ret (E0, [State C, s, mem', k', E_val v', arg])\n        (* else *)\n        (*   None *)\n      | _ => None\n      end\n    | Kcallptr1 efunptr k' =>\n      ret (E0, [State C, s, mem, Kcallptr2 v k', efunptr, arg])\n    | Kcallptr2 varg k' =>\n      match v with\n      | Ptr (perm, C', P', 0%Z) =>\n        if (Permission.eqb perm Permission.code) && (C' =? C) then\n            ret (E0, [State C, s, mem, Kcall C' P' k', E_val varg, arg])\n        else None\n      | _ => None\n      end\n    | Kcall C' P k' =>\n      (*match v with\n      | Int i =>*)\n        if C == C' then\n          (* retrieve the procedure code *)\n          do P_expr <- find_procedure (genv_procedures G) C' P;\n          ret (E0, [State C', Frame C arg k' :: s, mem, Kstop, P_expr, v])\n        else if imported_procedure_b (genv_interface G) C C' P then\n          (* retrieve the procedure code *)\n          do P_expr <- find_procedure (genv_procedures G) C' P;\n          ret ([ECall C P v mem C'], [State C', Frame C arg k' :: s, mem, Kstop, P_expr, v])\n        else\n          None\n      (*| _ => None\n      end*)\n    | Kstop =>\n      match (*v,*) s with\n      | (*Int i,*) Frame C' old_call_arg k' :: s' =>\n        let t := if C == C' then E0 else [:: ERet C v mem C'] in\n        ret (t, [State C', s', mem, k', E_val v, old_call_arg])\n      | (*_,*) _ => None\n      end\n    end\n  | E_exit => None\n  end.\n\nHint Unfold eval_kstep.\n\nFixpoint execN (n: nat) (G: global_env) (st: state) : option state :=\n  match n with\n  | O => None\n  | S n' =>\n    match eval_kstep G st with\n    | None => Some st\n    | Some (_, st') => execN n' G st'\n    end\n  end.\n\nClose Scope monad_scope.\n\n(* Semantics Properties *)\n\nTheorem eval_kstep_complete:\n  forall G st t st',\n    kstep G st t st' -> eval_kstep G st = Some (t, st').\nProof.\n  intros G st t st' Hkstep.\n  inversion Hkstep; subst; simpl; auto;\n    try (unfold Memory.store, Memory.load, Memory.alloc in *;\n         repeat simplify_nat_equalities;\n         repeat simplify_option;\n         reflexivity).\n  (* if expressions *)\n  - assert (Hsize: (size >? 0) % Z = true). {\n      destruct size; try inversion H; auto.\n    }\n    rewrite Hsize.\n    rewrite H0. reflexivity.\n  (* external calls *)\n  - move/eqP/negbTE: H => ->.\n    apply imported_procedure_iff in H0.\n    rewrite H0 H1.\n    reflexivity.\n  (* external return *)\n  - move/eqP/negbTE: H => ->.\n    reflexivity.\nQed.\n\nTheorem eval_kstep_sound:\n  forall G st t st',\n    eval_kstep G st = Some (t, st') -> kstep G st t st'.\nProof.\n  intros.\n  unfold_states.\n  match goal with\n  | H: eval_kstep _ _ = Some _ |- kstep _ [State _, _, _, _, ?E, _] _ [State _, _, _, _, _, _] =>\n    destruct E; simpl in H;\n      try discriminate;\n      try (repeat simplify_option;\n           econstructor; eauto;\n           repeat simplify_nat_equalities;\n           reflexivity)\n  end.\n  - repeat simplify_option.\n    + destruct (C0 == C) eqn:eC0.\n      * assert (C0 = C). by apply/eqP. subst.\n        eapply KS_InternalReturn; by auto.\n      * econstructor. intros ?. subst. by rewrite eq_refl in eC0.\n    + econstructor; eauto.\n    + econstructor; eauto.\n    + econstructor; eauto.\n    + destruct z; econstructor; eauto; discriminate.\n    + econstructor; eauto.\n      * apply Zgt_is_gt_bool. assumption.\n    + by econstructor; eauto; apply/eqP.\n    + econstructor; eauto.\n    + by econstructor; eauto; apply/eqP.\n    + econstructor; eauto. by apply/eqP.\n    + econstructor; eauto; first exact/eqP/negbT.\n      apply imported_procedure_iff. assumption.\n    + econstructor; eauto.\n    + move: Heqb => /andP.\n      intros [Hperm HC].\n      assert (i0 = Permission.code). by apply /Permission.eqP. subst.\n      assert (i1 = C). by apply beq_nat_true. subst.\n      by econstructor.\nQed.\n\nTheorem eval_kstep_correct:\n  forall G st t st',\n    eval_kstep G st = Some (t, st') <-> kstep G st t st'.\nProof.\n  split.\n  apply eval_kstep_sound.\n  apply eval_kstep_complete.\nQed.\n\nSection Semantics.\n  Variable p: program.\n\n  Hypothesis valid_program:\n    well_formed_program p.\n\n  Hypothesis complete_program:\n    closed_program p.\n\n  Let G := prepare_global_env p.\n\n  Definition sem :=\n    @Semantics_gen event state global_env kstep (initial_state p) final_state G.\n\n  Lemma receptiveness_step:\n    forall s t1 s1 t2,\n      kstep G s t1 s1 -> equal_and_nil_or_singleton t1 t2 ->\n      exists s2, kstep G s t2 s2.\n  Proof.\n    intros s t1 s1 t2.\n    intros Hkstep Hmatch_traces.\n    inversion Hkstep; subst;\n    inversion Hmatch_traces; subst;\n      try (eexists; apply Hkstep);\n      match goal with H: event_equal _ _ |- _ => apply event_equal_equal in H end;\n      subst; eexists; exact Hkstep.\n  Qed.\n\n  Lemma singleton_traces:\n    single_events sem.\n  Proof.\n    unfold single_events.\n    intros s t s' Hstep.\n    inversion Hstep; subst; simpl; auto.\n  Qed.\n\n  Theorem receptiveness:\n    receptive sem.\n  Proof.\n    constructor.\n    - apply receptiveness_step.\n    - apply singleton_traces.\n  Qed.\n\n  Local Open Scope fset_scope.\n\n  Definition stack_components (cs: state) : {fset Component.id} :=\n    s_component cs |: fset [seq f_component f | f <- s_stack cs].\n\n  Lemma stack_components_step cs t cs' :\n    Step sem cs t cs' ->\n    fsubset (stack_components cs) (domm (prog_interface p)) ->\n    fsubset (stack_components cs') (domm (prog_interface p)).\n  Proof.\n  case: cs t cs' / => //=.\n  - (* Internal Call *)\n    move=> C stk mem k _ P v P_expr arg <-; rewrite /stack_components /=.\n    by rewrite fset_cons fsetUA fsetUid.\n  - (* External Call *)\n    move=> C stk mem k C' P v P_expr arg _; rewrite /stack_components /=.\n    rewrite (fsubU1set C') mem_domm fset_cons.\n    by case/(cprog_closed_interface complete_program)=> CI [->].\n  - (* Internal Return *)\n    move=> C stk mem k v arg _ old <-; rewrite /stack_components /=.\n    by rewrite fset_cons fsetUA fsetUid.\n  - (* External Return *)\n    move=> C stk mem k v arg C' old _; rewrite /stack_components /=.\n    by rewrite (fsubU1set C) fset_cons; case/andP.\n  Qed.\n\n  Lemma stack_components_star cs t cs' :\n    initial_state p cs ->\n    Star sem cs t cs' ->\n    fsubset (stack_components cs') (domm (prog_interface p)).\n  Proof.\n  move=> init star.\n  have main_ok : Component.main \\in domm (prog_interface p).\n    have := cprog_main_existence complete_program.\n    rewrite wfprog_defined_procedures // mem_domm /prog_main /find_procedure.\n    by case: getm.\n  have {init main_ok} cs_ok : fsubset (stack_components cs) (domm (prog_interface p)).\n    rewrite init /initial_machine_state /stack_components.\n    by case e_main: (prog_main p)=> [mainP|] /=; rewrite -fset0E fsetU0 fsub1set.\n  elim: cs t cs' / star cs_ok=> // cs1 t1 cs2 t2 cs3 t step _ IH _ cs1_ok.\n  by apply: IH; apply: stack_components_step cs1_ok; eauto.\n  Qed.\n\n  Fixpoint unstutter (T : eqType) (x : T) (s : seq T) :=\n    if s is x' :: s' then\n      if x == x' then unstutter x s'\n      else x' :: unstutter x' s'\n    else [::].\n\n  Definition stack_state_of (cs: state) : stack_state :=\n    let: State curr stk _ _ _ _ := cs in\n    StackState curr (unstutter curr (map f_component stk)).\n\n  Lemma star_component s1 t s2 :\n    Star sem s1 t s2 ->\n    s_component s2 =\n    last (s_component s1) [seq next_comp_of_event e | e <- t].\n  Proof.\n  elim: s1 t s2 / => //= s1 t1 s2 t2 s3 _ Hstep _ -> ->.\n  rewrite map_cat last_cat (kstep_component Hstep).\n  move/singleton_traces: Hstep.\n  by case: t1=> [|e [|e' t1]] //= *; lia.\n  Qed.\n\n  Lemma initial_state_exists:\n    exists s, initial_state p s.\n  Proof.\n    unfold initial_state, initial_machine_state;\n      by eauto.\n  Qed.\n\n  Lemma load_component_prog_interface_intitial_state s ptr ptr':\n    initial_state p s ->\n    Memory.load (s_memory s) ptr = Some (Ptr ptr') ->\n    Pointer.component ptr' \\in domm (prog_interface p).\n  Proof.\n    intros Hini Hload.\n    unfold initial_state, initial_machine_state in Hini.\n    apply cprog_main_existence in complete_program as HisSome.\n    destruct (prog_main p) eqn:emain; last discriminate. subst. simpl in *.\n    unfold prepare_buffers, Memory.load in *. rewrite mapmE in Hload.\n    find_if_inside_hyp Hload; last discriminate.\n    destruct ((prog_buffers p (Pointer.component ptr))) as [buf|] eqn:ebuf;\n      last discriminate.\n    simpl in *. rewrite ComponentMemory.load_prealloc in Hload.\n    find_if_inside_hyp Hload; last discriminate.\n    destruct (setm emptym 0 buf (Pointer.block ptr)) as [buf'|] eqn:esetm;\n      last discriminate.\n    destruct buf'; first (find_if_inside_hyp Hload; discriminate).\n    apply nth_error_In in Hload.\n    rewrite setmE in esetm.\n    find_if_inside_hyp esetm; last discriminate. inversion esetm; subst; clear esetm.\n    assert (exists x, prog_interface p (Pointer.component ptr) = Some x) as [? H_].\n    {\n      apply/dommP. rewrite wfprog_defined_buffers; auto. apply/dommP; by eauto.\n    }\n    assert (H__: prog_interface p (Pointer.component ptr)). by rewrite H_.\n    specialize (wfprog_well_formed_buffers valid_program H__) as [? Bwf].\n    clear H_ H__. unfold Buffer.well_formed_buffer_opt in *.\n    rewrite ebuf in Bwf. simpl in *. move : Bwf => /andP => [[_ Bwf]].\n    apply In_in in Hload.\n    assert (contra: exists2 x, x \\in l & ~~ (fun v : value => ~~ is_ptr v) x).\n    { by eauto. }\n    move : contra => /allPn => contra. by rewrite Bwf in contra.\n  Qed.\n\n  Definition runtime_val_wf_wrt_prog_interface_ (v: value) : bool :=\n    match v with\n      | Ptr ptr => Pointer.component ptr \\in domm (prog_interface p)\n      | _ => true\n    end.\n  \n  Fixpoint runtime_expr_struct_invariant\n           (e: expr) (val_test: value -> bool) : bool :=\n    match e with\n    | E_val v => val_test v      \n    | E_binop _ e1 e2 =>\n      runtime_expr_struct_invariant e1 val_test &&\n      runtime_expr_struct_invariant e2 val_test\n    | E_seq e1 e2 =>\n      runtime_expr_struct_invariant e1 val_test &&\n      runtime_expr_struct_invariant e2 val_test\n    | E_if e1 e2 e3 =>\n      runtime_expr_struct_invariant e1 val_test &&\n      runtime_expr_struct_invariant e2 val_test &&\n      runtime_expr_struct_invariant e3 val_test\n    | E_alloc e =>\n      runtime_expr_struct_invariant e val_test\n    | E_deref e =>\n      runtime_expr_struct_invariant e val_test\n    | E_assign e1 e2 =>\n      runtime_expr_struct_invariant e1 val_test &&\n      runtime_expr_struct_invariant e2 val_test\n    | E_call _ _ e =>\n      runtime_expr_struct_invariant e val_test\n    | E_callptr e1 e2 =>\n      runtime_expr_struct_invariant e1 val_test &&\n      runtime_expr_struct_invariant e2 val_test\n    | E_funptr _\n    | E_arg\n    | E_local\n    | E_exit => true\n    end.\n\n  Fixpoint cont_struct_invariant (k: cont) (val_test: value -> bool) : bool :=\n    match k with\n    | Kbinop1 _ e k2 =>\n      runtime_expr_struct_invariant e val_test &&\n      cont_struct_invariant k2 val_test\n    | Kbinop2 _ v k2 =>\n      val_test v &&\n      cont_struct_invariant k2 val_test\n    | Kseq e k2 =>\n      runtime_expr_struct_invariant e val_test &&\n      cont_struct_invariant k2 val_test\n    | Kif e1 e2 k3 =>\n      runtime_expr_struct_invariant e1 val_test &&\n      runtime_expr_struct_invariant e2 val_test &&\n      cont_struct_invariant k3 val_test\n    | Kalloc k2 =>\n      cont_struct_invariant k2 val_test\n    | Kderef k2 =>\n      cont_struct_invariant k2 val_test\n    | Kassign1 e k2 =>\n      runtime_expr_struct_invariant e val_test &&\n      cont_struct_invariant k2 val_test\n    | Kassign2 v k2 =>\n      val_test v &&\n      cont_struct_invariant k2 val_test\n    | Kcall _ _ k2 =>\n      cont_struct_invariant k2 val_test\n    | Kcallptr1 e k2 =>\n      runtime_expr_struct_invariant e val_test &&\n      cont_struct_invariant k2 val_test\n    | Kcallptr2 v k2 =>\n      val_test v &&\n      cont_struct_invariant k2 val_test\n    | Kstop => true\n    end.\n\n  Definition stack_wf_wrt_prog_interface (s: stack) (val_test: value -> bool) : bool :=\n    all (fun frm =>\n           (f_component frm \\in domm (prog_interface p))\n           &&\n           val_test (f_arg frm) \n           &&\n           cont_struct_invariant (f_cont frm) val_test \n        )\n        s.\n  \n  Lemma values_are_integers_runtime_expr_wf_wrt_prog_interface e:\n    values_are_integers e ->\n    runtime_expr_struct_invariant e (runtime_val_wf_wrt_prog_interface_).\n  Proof.\n    induction e; auto; intros Hval; inversion Hval as [Hval'];\n      try (\n          move : Hval' => /andP => [[Hval1 Hval2]];\n                                   specialize (IHe1 Hval1);\n                                   specialize (IHe2 Hval2);\n                                   simpl; by rewrite IHe1 IHe2\n        ).\n    - destruct v; by auto.\n    - move : Hval' => /andP => [[Hval1 Hval_]].\n      move : Hval_ => /andP => [[Hval2 Hval3]].\n      specialize (IHe1 Hval1).\n      specialize (IHe2 Hval2).\n      specialize (IHe3 Hval3).\n      simpl. by rewrite IHe1 IHe2 IHe3.\n  Qed.\n\n  Lemma well_formed_expr_runtime_expr_wf_wrt_prog_interface C e:\n    well_formed_expr p C e ->\n    runtime_expr_struct_invariant e runtime_val_wf_wrt_prog_interface_.\n  Proof.\n    unfold well_formed_expr. intros [_ [? _]].\n    by apply values_are_integers_runtime_expr_wf_wrt_prog_interface.\n  Qed.\n\n  Lemma runtime_val_wf_wrt_prog_interface_eval_binop v1 v2 op:\n    runtime_val_wf_wrt_prog_interface_ v1 ->\n    runtime_val_wf_wrt_prog_interface_ v2 ->\n    runtime_val_wf_wrt_prog_interface_ (eval_binop op v1 v2).\n  Proof.\n    intros Hv1 Hv2.\n    destruct op; destruct v1 as [| [[[perm1 c1] b1] o1] |];\n      destruct v2 as [| [[[perm2 c2] b2] o2] |]; simpl in *; auto.\n    - find_if_inside_goal; by auto.\n    - find_if_inside_goal; by auto.\n  Qed.\n  \n  Lemma load_component_prog_interface_inductively_provable s t s':\n    initial_state p s ->\n    Star sem s t s' ->\n    (\n      (\n        forall ptr ptr',\n          Memory.load (s_memory s') ptr = Some (Ptr ptr') ->\n          Pointer.component ptr' \\in domm (prog_interface p)\n      )\n      /\\\n      runtime_expr_struct_invariant (s_expr s') runtime_val_wf_wrt_prog_interface_\n      /\\\n      cont_struct_invariant (s_cont s') runtime_val_wf_wrt_prog_interface_\n      /\\\n      runtime_val_wf_wrt_prog_interface_ (s_arg s')\n      /\\\n      s_component s' \\in domm (prog_interface p)\n      /\\\n      stack_wf_wrt_prog_interface (s_stack s') runtime_val_wf_wrt_prog_interface_                   \n    ).\n  Proof.\n    intros Hini Hstar.\n    apply star_iff_starR in Hstar.\n    revert Hini.\n    induction Hstar as [| s1 t1 s2 t2 s3 ? Hstar12 IHHstar Hstep23];\n      subst;\n      intros Hini.\n    - split; [intros ? ? Hload | split; [| ]].\n      + by eapply load_component_prog_interface_intitial_state; eauto.\n      + unfold initial_state, initial_machine_state in Hini.\n        destruct (prog_main p) eqn:emain; subst; simpl; auto.\n        unfold prog_main in emain.\n        apply wfprog_well_formed_procedures in emain; auto.\n        unfold well_formed_expr in *. destruct emain as [_ [G_ _]].\n        by apply values_are_integers_runtime_expr_wf_wrt_prog_interface in G_.\n      + unfold initial_state, initial_machine_state in Hini.\n        destruct (prog_main p) eqn:emain; subst; simpl; auto.\n        * rewrite wfprog_main_existence; auto; by rewrite emain.\n        * specialize (cprog_main_existence complete_program) as contra.\n          by rewrite emain in contra.\n    - specialize (IHHstar Hini)\n        as [IHload [IHexpr [IHcont [IHarg [IHcomp IHstack]]]]];\n            simpl in *.\n      split;\n        [\n          intros ? ? Hload; inversion Hstep23; subst;\n          try (simpl in Hload; eapply IHload; by eauto)\n        |].\n      + (* Hload in context; case alloc *)\n        simpl in *. \n        destruct ((Pointer.component ptr, Pointer.block ptr) ==\n                  (Pointer.component ptr0, Pointer.block ptr0)) eqn:eqalloc.\n        * move : eqalloc => /eqP => eqalloc.\n          specialize (Memory.load_after_alloc_eq _ _ _ _ _ _ H0 eqalloc) as Hload'.\n          rewrite Hload' in Hload. repeat (find_if_inside_hyp Hload; last discriminate).\n          discriminate.\n        * assert (Hneq: (Pointer.component ptr, Pointer.block ptr) <>\n                        (Pointer.component ptr0, Pointer.block ptr0)).\n          { unfold not. move => /eqP => contra. by rewrite contra in eqalloc. } \n          specialize (Memory.load_after_alloc _ _ _ _ _ _ H0 Hneq) as Hrewr.\n          rewrite Hrewr in Hload. by eapply IHload; eauto.\n      + (* Hload in context; case store *)\n        simpl in *.\n        specialize (Memory.load_after_store _ _ _ _ ptr H) as Hload'.\n        rewrite Hload' in Hload.\n        find_if_inside_hyp Hload.\n        * inversion Hload; subst; clear Hload.\n          simpl in IHcont. by move : IHcont => /andP => [[G_ _]].\n        * eapply IHload; by eauto.\n      + split; [inversion Hstep23; subst; simpl in *; auto;\n                try (by move : IHexpr => /andP => [[? ?]]);\n                try (by move : IHcont => /andP => [[? ?]])\n               |].\n        * apply runtime_val_wf_wrt_prog_interface_eval_binop; auto.\n          by move : IHcont => /andP => [[? ?]].\n        * move : IHexpr => /andP => [[G_ ?]].\n          by move : G_ => /andP => [[? ?]].\n        * move : IHcont => /andP => [[G_ ?]].\n          move : G_ => /andP => [[? ?]].\n          by find_if_inside_goal.\n        * by apply Memory.component_of_alloc_ptr in H0; subst.\n        * destruct v; auto. by eapply IHload; eauto.\n        * apply wfprog_well_formed_procedures in H0; auto.\n          by eapply well_formed_expr_runtime_expr_wf_wrt_prog_interface; eauto.\n        * apply wfprog_well_formed_procedures in H1; auto.\n          by eapply well_formed_expr_runtime_expr_wf_wrt_prog_interface; eauto.\n        * split; [inversion Hstep23; subst; simpl in *; auto;\n                try (move : IHexpr => /andP => [[IHe1 IHe2]]);\n                try (move : IHcont => /andP => [[IHk1 IHk2]]);\n                auto;\n                try (\n                    match goal with\n                    | H1 : is_true (?X), H2: is_true (?Y) |-\n                      is_true (andb ?X ?Y) => by rewrite H1 H2\n                    end\n                  )\n               |].\n          -- move : IHe1 => /andP => [[IHe1 IHe2_]].\n             by rewrite IHe2_ IHe2 IHcont.\n          -- move : IHstack => /andP => [[IHstack _]].\n             by move : IHstack => /andP => [[_ ?]].\n          -- move : IHstack => /andP => [[IHstack _]].\n             by move : IHstack => /andP => [[_ ?]].\n          -- split; [inversion Hstep23; subst; simpl in *; auto;\n                     try (move : IHexpr => /andP => [[IHe1 IHe2]]);\n                     try (move : IHcont => /andP => [[IHk1 IHk2]]);\n                     auto;\n                     try (\n                         match goal with\n                         | H1 : is_true (?X), H2: is_true (?Y) |-\n                           is_true (andb ?X ?Y) => by rewrite H1 H2\n                         end\n                       )\n                    |].\n             ++ do 2 (move : IHstack => /andP => [[IHstack _]]).\n                by move : IHstack => /andP => [[_ ?]].\n             ++ do 2 (move : IHstack => /andP => [[IHstack _]]).\n                by move : IHstack => /andP => [[_ ?]].\n             ++ split; [inversion Hstep23; subst; simpl in *; auto |].\n                ** by eapply find_procedure_prog_interface; eauto.\n                ** by repeat (move : IHstack => /andP => [[IHstack _]]).\n                ** inversion Hstep23; subst; simpl in *; auto.\n                   --- by rewrite IHarg IHcont IHstack IHcomp.\n                   --- by rewrite IHarg IHcont IHstack IHcomp.\n                   --- by (move : IHstack => /andP => [[_ ?]]).\n                   --- by (move : IHstack => /andP => [[_ ?]]).\n  Qed.\n  \n  Lemma load_component_prog_interface s t s' ptr ptr' :\n    initial_state p s ->\n    Star sem s t s' ->\n    Memory.load (s_memory s') ptr = Some (Ptr ptr') ->\n    Pointer.component ptr' \\in domm (prog_interface p).\n  Proof.\n    intros Hini Hstar.\n    specialize (load_component_prog_interface_inductively_provable Hini Hstar);\n      intuition.\n    (* by eapply H1; eauto. *)\n  Qed.\n\n  (* TODO: Move to Common/Memory.v *)\n  Lemma load_some_in_domm mem ptr v:\n    Memory.load mem ptr = Some v ->\n    Pointer.component ptr \\in domm mem.\n  Proof.\n    unfold Memory.load. find_if_inside_goal; last discriminate.\n    destruct (mem (Pointer.component ptr)) eqn:emem; last discriminate. intros _.\n    apply/dommP. by eauto.\n  Qed.\n\n  Lemma initial_state_domm_s_memory s:\n    initial_state p s ->\n    domm (s_memory s) = domm (prog_interface p).\n  Proof.\n    unfold initial_state. intros. subst. unfold initial_machine_state.\n    apply cprog_main_existence in complete_program as HisSome.\n    destruct (prog_main p) eqn:emain; last discriminate. simpl.\n    by apply domm_prepare_buffers.\n  Qed.\n  \n  Lemma step_preserves_mem_domm s t s' :\n    Step sem s t s' ->\n    domm (s_memory s) = domm (s_memory s').\n  Proof.\n    intros Hstep.\n    inversion Hstep; subst;\n      try reflexivity. (* Most operations do not modify the memory. *)\n    - (* Preservation by Memory.alloc. *)\n      match goal with\n      | Halloc : Memory.alloc _ _ _ = _ |- _ =>\n        unfold Memory.alloc in Halloc;\n          destruct (mem C) as [memC |] eqn:Hcase;\n            [| discriminate];\n          destruct (ComponentMemory.alloc memC (Z.to_nat size)) as [memC' b];\n          inversion Halloc; subst; simpl;\n          rewrite domm_set fsetU1in; [reflexivity |];\n          apply /dommP; now eauto\n      end.\n    - (* Preservation by Memory.store. *)\n      rename H into Hstore.\n    match goal with\n    | Hstore : Memory.store _ ?PTR ?V = _ |- _ =>\n      unfold Memory.store in Hstore;\n        destruct (Permission.eqb (Pointer.permission PTR) Permission.data) eqn:Hperm;\n        [| discriminate];\n        destruct (mem (Pointer.component PTR)) as [memC |] eqn:Hcase1;\n        [| discriminate];\n        destruct (ComponentMemory.store\n                    memC (Pointer.block PTR) (Pointer.offset PTR) V)\n          as [memC' |] eqn:Hcase2;\n        [| discriminate];\n        inversion Hstore as [Hsetm];\n        simpl; rewrite domm_set fsetU1in;\n          [reflexivity |];\n          apply /dommP; now eauto\n    end.\n  Qed.\n\n  Lemma comes_from_initial_state_mem_domm s t s' :\n    initial_state p s ->\n    Star sem s t s' ->\n    domm (s_memory s') = domm (prog_interface p).\n  Proof.\n    intros Hini Hstar.\n    apply star_iff_starR in Hstar.\n    revert Hini.\n    induction Hstar as [| s1 t1 s2 t2 s3 ? Hstar12 IHHstar Hstep23];\n      subst;\n      intros Hini.\n    - by apply initial_state_domm_s_memory.\n    - specialize (IHHstar Hini).\n      apply step_preserves_mem_domm in Hstep23. congruence.\n  Qed.\n  \n  Lemma load_component_prog_interface_addr s t s' ptr v :\n    initial_state p s ->\n    Star sem s t s' ->\n    Memory.load (s_memory s') ptr = Some v ->\n    Pointer.component ptr \\in domm (prog_interface p).\n  Proof.\n    intros Hini Hstar.\n    apply star_iff_starR in Hstar.\n    revert Hini.\n    induction Hstar as [| s1 t1 s2 t2 s3 ? Hstar12 IHHstar Hstep23];\n      subst;\n      intros Hini Hload.\n    - apply load_some_in_domm in Hload.\n      by erewrite <- initial_state_domm_s_memory; eauto.\n    - specialize (IHHstar Hini).\n      inversion Hstep23; subst;\n        try (simpl in Hload; apply IHHstar; by auto);\n        (\n          apply load_some_in_domm in Hload; simpl in Hload;\n          apply star_iff_starR in Hstar12;\n          specialize (comes_from_initial_state_mem_domm Hini Hstar12) as G_; simpl in G_\n        ).\n      + apply Memory.domm_alloc in H0. by rewrite -G_ H0. \n      + apply Memory.domm_store in H. by rewrite -G_ H.\n  Qed.\n\n  Definition b_nextblock mem (v: value) : bool :=\n    match v with\n    | Ptr (Permission.data, C, b, o) =>\n      match mem C with\n      | Some Cmem => b <? ComponentMemory.next_block Cmem\n      | None => false\n      end\n    | _ => true\n    end.\n\n  Lemma values_are_integers_b_nextblock e mem:\n    values_are_integers e ->\n    runtime_expr_struct_invariant e (b_nextblock mem).\n  Proof.\n    induction e; simpl; auto.\n    - by destruct v; auto.\n    - move => /andP [? ?]. rewrite IHe1; by auto.\n    - move => /andP [? ?]. rewrite IHe1; by auto.\n    - move => /andP [? H]. move : H => /andP => [[? ?]].\n      rewrite IHe1; auto. rewrite IHe2; by auto.\n    - move => /andP [? ?]. rewrite IHe1; by auto.\n    - move => /andP [? ?]. rewrite IHe1; by auto.\n  Qed.\n\n(* Print Assumptions comes_from_initial_state_mem_domm. *)\n\n  Lemma b_next_block_eval_binop mem v1 v2 op:\n    b_nextblock mem v1 ->\n    b_nextblock mem v2 ->\n    b_nextblock mem (eval_binop op v1 v2).\n  Proof.\n    intros Hv1 Hv2.\n    destruct op; destruct v1 as [| [[[perm1 c1] b1] o1] |];\n      destruct v2 as [| [[[perm2 c2] b2] o2] |]; simpl in *; auto.\n    - find_if_inside_goal; by auto.\n    - find_if_inside_goal; by auto.\n  Qed.\n  \n  Lemma load_data_next_block_initial_state s:\n    initial_state p s ->\n    forall ptr C b o,\n      Memory.load (s_memory s) ptr = Some (Ptr (Permission.data, C, b, o)) ->\n      exists Cmem,\n        (s_memory s) C = Some Cmem /\\\n        b < ComponentMemory.next_block Cmem.\n  Proof.\n    intros Hinit ? ? ? ? Hload.\n    unfold initial_state in Hinit. subst.\n    unfold initial_machine_state in *.\n    destruct (prog_main p) eqn:e; simpl in *.\n    - unfold prepare_buffers, Memory.load in *.\n      find_if_inside_hyp Hload; [|discriminate].\n      rewrite mapmE in Hload.\n      unfold omap, obind, oapp in *.\n      destruct (prog_buffers p (Pointer.component ptr)) as [buf|] eqn:ebuf;\n        [|discriminate].\n      simpl in *. rewrite ComponentMemory.load_prealloc in Hload.\n      find_if_inside_hyp Hload; [|discriminate].\n      rewrite setmE in Hload.\n      find_if_inside_hyp Hload; [|discriminate].\n      destruct buf as [sz|chnk].\n      + find_if_inside_hyp Hload; discriminate.\n      + assert (exists x, prog_interface p (Pointer.component ptr) = Some x)\n          as [? Hifc].\n        {\n          apply/dommP. specialize (wfprog_defined_buffers valid_program) as Hrewr.\n          rewrite Hrewr. apply/dommP. by eauto.   \n        }\n        assert (Hifc_: prog_interface p (Pointer.component ptr)).\n        { by rewrite Hifc. }\n        specialize (wfprog_well_formed_buffers valid_program Hifc_) as Hwfbuf.\n        rewrite ebuf in Hwfbuf.\n        simpl in *. destruct Hwfbuf as [_ G_]. move : G_ => /andP => [[_ G_]].\n        move : G_ => /allP => G_. apply nth_error_In, In_in, G_ in Hload.\n        by simpl in *.\n    - unfold Memory.load in *. find_if_inside_hyp Hload; [|discriminate].\n      by rewrite emptymE in Hload.\n  Qed.\n\n  Lemma b_nextblock_alloc v (mem: Memory.t) C sz ptr mem':\n    b_nextblock mem v ->\n    Memory.alloc mem C (Z.to_nat sz) = Some (mem', ptr) ->\n    b_nextblock mem' v.\n  Proof.\n    intros Hb Halloc. \n    destruct v as [ | [[[[] c] b] o] | ]; auto. simpl in *.\n    unfold Memory.alloc in *.\n    destruct (mem c) as [memc|] eqn:ememc; [|discriminate].\n    destruct (mem C) as [memC|] eqn:ememC; [|discriminate].\n    destruct (ComponentMemory.alloc memC (Z.to_nat sz))\n      as [memC' b'] eqn:ememC'.\n    inversion Halloc; subst. rewrite setmE.\n    find_if_inside_goal.\n    + move : e => /eqP => ?; subst.\n      apply ComponentMemory.next_block_alloc in ememC' as [G1 G2]; subst; rewrite G2.\n      apply Nat.ltb_lt. apply/ssrnat.leP. apply ssrnat.ltn_addr.\n      apply/ssrnat.leP. apply Nat.ltb_lt.\n      rewrite ememc in ememC. inversion ememC; subst. by rewrite Hb.\n    + by rewrite ememc.\n  Qed.\n    \n  Lemma b_nextblock_store (mem: Memory.t) v P C b o v' mem':\n    b_nextblock mem v ->\n    Memory.store mem (P, C, b, o) v' = Some mem' ->\n    b_nextblock mem' v.\n  Proof.\n    intros Hb Hstore. \n    destruct v as [ | [[[[] c] bv] ov] | ]; auto. simpl in *.\n    unfold Memory.store in *.\n    destruct (mem c) as [memc|] eqn:ememc; [|discriminate].\n    find_if_inside_hyp Hstore; [|discriminate]; simpl in *.\n    destruct (mem C) as [memC|] eqn:ememC; [|discriminate].\n    destruct (ComponentMemory.store memC b o v')\n      as [memC'|] eqn:ememC'; [|discriminate].\n    inversion Hstore; subst. rewrite setmE.\n    find_if_inside_goal.\n    + apply ComponentMemory.next_block_store_stable in ememC'. rewrite -ememC'.\n      move : e0 => /eqP => ?; subst. rewrite ememc in ememC. inversion ememC. by subst.\n    + by rewrite ememc.\n  Qed.\n  \n  Lemma runtime_expr_struct_invariant_b_nextblock_alloc\n        re (mem: Memory.t) C sz ptr mem':\n    runtime_expr_struct_invariant re (b_nextblock mem) ->\n    Memory.alloc mem C (Z.to_nat sz) = Some (mem', ptr) ->\n    runtime_expr_struct_invariant re (b_nextblock mem').\n  Proof.\n    induction re; auto; intros Hre Halloc; simpl in *;\n      try (move : Hre => /andP => [[H1 H2]]; apply/andP; by intuition).\n    - by eapply b_nextblock_alloc; eauto.\n    - move : Hre => /andP => [[H1 H2]]. apply/andP. intuition.\n      move : H1 => /andP => [[? ?]]. apply/andP. by intuition.\n  Qed. \n      \n  Lemma runtime_expr_struct_invariant_b_nextblock_store\n        re (mem: Memory.t) P C b o v' mem':\n    runtime_expr_struct_invariant re (b_nextblock mem) ->\n    Memory.store mem (P, C, b, o) v' = Some mem' ->\n    runtime_expr_struct_invariant re (b_nextblock mem').\n  Proof.\n    induction re; auto; intros Hre Hstore; simpl in *;\n      try (move : Hre => /andP => [[H1 H2]]; apply/andP; by intuition).\n    - by eapply b_nextblock_store; eauto.\n    - move : Hre => /andP => [[H1 H2]]. apply/andP. intuition.\n      move : H1 => /andP => [[? ?]]. apply/andP. by intuition.\n  Qed. \n  \n  Lemma cont_struct_invariant_b_nextblock_alloc k (mem: Memory.t) C sz ptr mem' :\n    cont_struct_invariant k (b_nextblock mem) ->\n    Memory.alloc mem C (Z.to_nat sz) = Some (mem', ptr) ->\n    cont_struct_invariant k (b_nextblock mem').\n  Proof.\n    induction k; auto; intros Hmem Halloc; simpl in *;\n      move : Hmem => /andP => [[H1 H2]]; apply/andP; intuition;\n                                try (by eapply b_nextblock_alloc; eauto);\n                                try (by eapply runtime_expr_struct_invariant_b_nextblock_alloc; eauto).\n    - apply/andP. move : H1 => /andP => [[? ?]].\n      split; by eapply runtime_expr_struct_invariant_b_nextblock_alloc; eauto.\n  Qed.\n\n  Lemma cont_struct_invariant_b_nextblock_store k (mem: Memory.t) P C b o v mem':\n    cont_struct_invariant k (b_nextblock mem) ->\n    Memory.store mem (P, C, b, o) v = Some mem' ->\n    cont_struct_invariant k (b_nextblock mem').\n  Proof.\n    induction k; auto; intros Hmem Hstore; simpl in *;\n      move : Hmem => /andP => [[H1 H2]]; apply/andP; intuition;\n                                try (by eapply b_nextblock_store; eauto);\n                                try (by eapply runtime_expr_struct_invariant_b_nextblock_store; eauto).\n    - apply/andP. move : H1 => /andP => [[? ?]].\n      split; by eapply runtime_expr_struct_invariant_b_nextblock_store; eauto.\n  Qed.\n\n  Lemma stack_wf_wrt_prog_interface_b_nextblock_alloc\n        s (mem: Memory.t) C size mem' ptr:\n    stack_wf_wrt_prog_interface s (b_nextblock mem) ->\n    Memory.alloc mem C (Z.to_nat size) = Some (mem', ptr) ->\n    stack_wf_wrt_prog_interface s (b_nextblock mem').\n  Proof.\n    induction s using last_ind; auto. unfold stack_wf_wrt_prog_interface.\n    rewrite !all_rcons. intros Hwf Halloc.\n    repeat (let H := fresh \"H\" in move : Hwf => /andP => [[Hwf H]]).\n    specialize (IHs H Halloc).\n    apply/andP; split; [|assumption].\n    apply/andP; split; [|by eapply cont_struct_invariant_b_nextblock_alloc; eauto].\n    apply/andP; split; [assumption|by eapply b_nextblock_alloc; eauto].\n  Qed.\n    \n  Lemma stack_wf_wrt_prog_interface_b_nextblock_store\n        s (mem: Memory.t) P C b o v mem':\n    stack_wf_wrt_prog_interface s (b_nextblock mem) ->\n    Memory.store mem (P, C, b, o) v = Some mem' ->\n    stack_wf_wrt_prog_interface s (b_nextblock mem').\n  Proof.\n    induction s using last_ind; auto. unfold stack_wf_wrt_prog_interface.\n    rewrite !all_rcons. intros Hwf Hstore.\n    repeat (let H := fresh \"H\" in move : Hwf => /andP => [[Hwf H]]).\n    specialize (IHs H Hstore).\n    apply/andP; split; [|assumption].\n    apply/andP; split; [|by eapply cont_struct_invariant_b_nextblock_store; eauto].\n    apply/andP; split; [assumption|by eapply b_nextblock_store; eauto].\n  Qed.\n\n\n  Lemma load_data_next_block_inductively_provable s t s' :\n    initial_state p s ->\n    Star sem s t s' ->\n    (\n      (\n        forall ptr C b o,\n          Memory.load (s_memory s') ptr = Some (Ptr (Permission.data, C, b, o)) ->\n          exists Cmem,\n            (* Memory.next_block (s_memory s') c = some b' /\\ *)\n            (s_memory s') C = Some Cmem /\\\n            b < ComponentMemory.next_block Cmem\n      )\n      /\\\n      runtime_expr_struct_invariant (s_expr s') (b_nextblock (s_memory s'))\n      /\\\n      cont_struct_invariant (s_cont s') (b_nextblock (s_memory s'))\n      /\\\n      b_nextblock (s_memory s') (s_arg s')\n      /\\\n      (exists cmem,\n          (s_memory s') (s_component s') = Some cmem\n          /\\\n          Block.local <? ComponentMemory.next_block cmem\n      )\n      /\\\n      stack_wf_wrt_prog_interface (s_stack s') (b_nextblock (s_memory s'))\n      /\\\n      (\n        forall C',\n          C' \\in domm (prog_interface p) ->\n          exists cmem : ComponentMemory.t,\n            (s_memory s') C' = Some cmem /\\\n            Block.local <? ComponentMemory.next_block cmem\n      )\n    ).\n  Proof.\n    intros Hini Hstar.\n    apply star_iff_starR in Hstar.\n    revert Hini.\n    induction Hstar as [| s1 t1 s2 t2 s3 ? Hstar12 IHHstar Hstep23];\n      subst;\n      intros Hini.\n    - split; [intros ? ? ? ? Hload | split; [| ]].\n      + by eapply load_data_next_block_initial_state; eauto.\n      + unfold initial_state, initial_machine_state in Hini.\n        destruct (prog_main p) eqn:emain; subst; simpl; auto.\n        unfold prog_main in emain.\n        apply wfprog_well_formed_procedures in emain; auto.\n        unfold well_formed_expr in *. destruct emain as [_ [G_ _]].\n          by eapply values_are_integers_b_nextblock in G_; eauto.\n      + unfold initial_state, initial_machine_state in Hini.\n        destruct (prog_main p) eqn:emain; subst; simpl; try by eauto; intuition.\n        -- assert (exists cmem, prepare_buffers p Component.main = Some cmem) as [? ?].\n           {\n             apply/dommP. rewrite domm_prepare_buffers; auto.\n             rewrite wfprog_main_existence; auto.\n             by rewrite emain.\n           }\n           assert (G1: Block.local <? ComponentMemory.next_block x).\n           {\n             unfold prepare_buffers in H. rewrite mapmE in H.\n             unfold omap, obind, oapp in *.\n             destruct (prog_buffers p Component.main)\n               as [buf|] eqn:ebuf; [|discriminate].\n             inversion H; subst. by rewrite ComponentMemory.nextblock_prealloc.\n           }\n           intuition.\n           ++ exists x; by intuition.\n           ++ assert (exists cmem, prepare_buffers p C' = Some cmem) as [? ?].\n              {\n                apply/dommP. rewrite domm_prepare_buffers; auto.\n              }\n              eexists; intuition; eauto.\n              unfold prepare_buffers in H1. rewrite mapmE in H1.\n              unfold omap, obind, oapp in *.\n              destruct (prog_buffers p C')\n                as [buf|] eqn:ebuf; [|discriminate].\n              inversion H1; subst. by rewrite ComponentMemory.nextblock_prealloc.\n        -- intuition; destruct complete_program;\n             by rewrite emain in cprog_main_existence0. \n    - specialize (IHHstar Hini)\n        as [IHload [IHexpr [IHcont [IHarg [[compMem [HcompMem HcompMem2]] [IHstack IHfind]]]]]];\n            simpl in *.\n      split;\n        [\n          intros ? ? ? ? Hload; inversion Hstep23; subst;\n          try (simpl in Hload; eapply IHload; by eauto)\n         |]; simpl in *.\n      + destruct ((Pointer.component ptr, Pointer.block ptr) ==\n                  (Pointer.component ptr0, Pointer.block ptr0)) eqn:eptr.\n        * move : eptr => /eqP => eptr.\n          erewrite Memory.load_after_alloc_eq in Hload; eauto.\n          repeat (find_if_inside_hyp Hload; [|discriminate]).\n          by inversion Hload.\n        * erewrite Memory.load_after_alloc in Hload; eauto.\n          -- specialize (IHload _ _ _ _ Hload) as [? [? ?]].\n             unfold Memory.alloc in *.\n             destruct (mem C0) as [memC0|] eqn:eC0; [|discriminate].\n             destruct (ComponentMemory.alloc memC0 (Z.to_nat size))\n               as [memC' b'] eqn:ememC'.\n             inversion H0; subst. rewrite setmE.\n             find_if_inside_goal.\n             ++ move : e => /eqP => ?; subst. rewrite eC0 in H1. inversion H1; subst.\n                simpl in *. apply ComponentMemory.next_block_alloc in ememC' as [G1 G2].\n                subst. exists memC'. intuition. \n                rewrite G2. apply/ssrnat.ltP. \n                apply ssrnat.ltn_addr. by apply/ssrnat.ltP.\n             ++ rewrite H1. by eauto.\n          -- apply/eqP. by rewrite eptr.\n      + destruct (Pointer.eq (P', C', b', o') ptr) eqn:eptr.\n        * move : eptr => /Pointer.eqP => eptr; subst.\n          specialize (Memory.load_after_store_eq _ _ _ _ H) as H_.\n          rewrite Hload in H_. inversion H_; subst. clear H_.\n          simpl in *. move : IHcont => /andP => [[G1 G2]].\n          unfold Memory.store in H. find_if_inside_hyp H; [simpl in *|discriminate].\n          destruct (mem C') as [memC'|] eqn:ememC'; [|discriminate].\n          destruct (ComponentMemory.store memC' b' o' (Ptr (Permission.data, C, b, o)))\n            as [memC'_after|] eqn:ememC'_after; [|discriminate].\n          inversion H; subst. clear H. move : e => /Permission.eqP => e. subst.\n          rewrite setmE. find_if_inside_goal.\n          -- move : e => /eqP => ?; subst. exists memC'_after; intuition.\n             rewrite ememC' in G1.\n             apply ComponentMemory.next_block_store_stable in ememC'_after.\n             by rewrite -ememC'_after -Nat.ltb_lt. \n          -- destruct (mem C) as [memC|] eqn:ememC; [|discriminate].\n             exists memC; intuition. by rewrite -Nat.ltb_lt.\n        * move : eptr => /Pointer.eqP => eptr.\n          erewrite (Memory.load_after_store_neq _ _ _ _ _ eptr) in Hload; eauto.\n          specialize (IHload _ _ _ _ Hload) as [memC [ememC G1]].\n          unfold Memory.store in H. find_if_inside_hyp H; [simpl in *|discriminate].\n          destruct (mem C') as [memC'|] eqn:ememC'; [|discriminate].\n          destruct (ComponentMemory.store memC' b' o' v)\n            as [memC'_after|] eqn:ememC'_after; [|discriminate].\n          inversion H; subst. clear H. move : e => /Permission.eqP => e. subst.\n          rewrite setmE. find_if_inside_goal.\n          -- move : e => /eqP => ?; subst. exists memC'_after; intuition.\n             rewrite ememC' in ememC; inversion ememC; subst.\n             apply ComponentMemory.next_block_store_stable in ememC'_after.\n             by rewrite -ememC'_after. \n          -- by eexists; eauto.\n      + split; [inversion Hstep23; subst; simpl in *; auto;\n                try (by move : IHexpr => /andP => [[? ?]]);\n                try (by move : IHcont => /andP => [[? ?]])\n               |].\n        * apply b_next_block_eval_binop; auto.\n          by move : IHcont => /andP => [[? ?]].\n        * move : IHexpr => /andP => [[G_ ?]].\n          by move : G_ => /andP => [[? ?]].\n        * move : IHcont => /andP => [[G_ ?]].\n          move : G_ => /andP => [[? ?]].\n          by find_if_inside_goal.\n        * by rewrite HcompMem.\n        * destruct ptr as [[[[] c] b] o]; auto.\n          specialize (Memory.next_block_alloc _ _ _ _ _ H0) as [G1 G2].\n          specialize (Memory.component_of_alloc_ptr _ _ _ _ _ H0). simpl; intros; subst.\n          simpl in *. unfold Memory.next_block in *.\n          rewrite HcompMem in G1.\n          destruct (mem' C) as [mem'C|] eqn:emem'C; [|discriminate].\n          inversion G1. subst. inversion G2 as [G3]. rewrite G3 ssrnat.addn1.\n          by apply Nat.ltb_lt.\n        * destruct v as [| [[[[] c] b] o] |]; auto.\n          specialize (IHload _ _ _ _ H) as [? [G1 G2]]. simpl. rewrite G1. \n          by apply Nat.ltb_lt.\n        * destruct v as [| [[[[] c] b] o] |]; auto.\n          move : IHcont => /andP => [[G1 _]].\n          simpl in *.\n          assert (exists Cmem, mem' c = Some Cmem) as [memc ememc].\n          { apply/ dommP. erewrite <- Memory.domm_store; eauto. apply/dommP.\n            by destruct (mem c) as [memc|] eqn:ememc; [|discriminate]; eauto.\n          }\n          rewrite ememc. \n          specialize (Memory.next_block_store_stable _ _ _ _ c H) as Heq.\n          destruct (mem c) as [memc_|] eqn:ememc_; [|discriminate].\n          unfold Memory.next_block in *. rewrite ememc ememc_ in Heq.\n          inversion Heq as [Hrewr]. by rewrite Hrewr.\n        * apply values_are_integers_b_nextblock.\n          eapply wfprog_well_formed_procedures in H0; auto.\n          unfold well_formed_expr in *. by intuition.\n        * apply values_are_integers_b_nextblock.\n          eapply wfprog_well_formed_procedures in H1; auto.\n          unfold well_formed_expr in *. by intuition.\n        * split; [inversion Hstep23; subst; simpl in *; auto;\n                try (move : IHexpr => /andP => [[IHe1 IHe2]]);\n                try (move : IHcont => /andP => [[IHk1 IHk2]]);\n                auto;\n                try (\n                    match goal with\n                    | H1 : is_true (?X), H2: is_true (?Y) |-\n                      is_true (andb ?X ?Y) => by rewrite H1 H2\n                    end\n                  )\n               |].\n          -- move : IHe1 => /andP => [[IHe1 IHe2_]].\n             by rewrite IHe2_ IHe2 IHcont.\n          -- by eapply cont_struct_invariant_b_nextblock_alloc; eauto.\n          -- by eapply cont_struct_invariant_b_nextblock_store; eauto.\n          -- move : IHstack => /andP => [[IHstack _]].\n             by move : IHstack => /andP => [[_ ?]].\n          -- move : IHstack => /andP => [[IHstack _]].\n             by move : IHstack => /andP => [[_ ?]].\n          -- split; [inversion Hstep23; subst; simpl in *; auto;\n                     try (move : IHexpr => /andP => [[IHe1 IHe2]]);\n                     try (move : IHcont => /andP => [[IHk1 IHk2]]);\n                     auto;\n                     try (\n                         match goal with\n                         | H1 : is_true (?X), H2: is_true (?Y) |-\n                           is_true (andb ?X ?Y) => by rewrite H1 H2\n                         end\n                       )\n                    |].\n             ++ by eapply b_nextblock_alloc; eauto.\n             ++ by eapply b_nextblock_store; eauto.\n             ++ do 2 (move : IHstack => /andP => [[IHstack _]]).\n                by move : IHstack => /andP => [[_ ?]].\n             ++ do 2 (move : IHstack => /andP => [[IHstack _]]).\n                by move : IHstack => /andP => [[_ ?]].\n             ++ split; [inversion Hstep23; subst; simpl in *; auto;\n                        try (by rewrite HcompMem; eauto)\n                       |].\n                ** specialize (@b_nextblock_alloc\n                                 (Ptr (Permission.data, C, Block.local, 0%Z))\n                                 mem C size ptr mem')\n                    as G1.\n                   assert (b_nextblock\n                             mem (Ptr (Permission.data, C, Block.local, 0%Z))) as G2.\n                   {\n                     simpl. by rewrite HcompMem.\n                   }\n                   specialize (G1 G2 H0). simpl in G1.\n                   destruct (mem' C); [|discriminate].\n                   by eauto.\n                ** specialize (@b_nextblock_store\n                                 \n                                 mem\n                                 (Ptr (Permission.data, C, Block.local, 0%Z))\n                                 P' C' b' o' v mem') as G1.\n                   assert (b_nextblock\n                             mem (Ptr (Permission.data, C, Block.local, 0%Z))) as G2.\n                   {\n                     simpl. by rewrite HcompMem.\n                   }\n                   specialize (G1 G2 H). simpl in G1.\n                   destruct (mem' C); [|discriminate].\n                   by eauto.\n                ** eapply IHfind; eauto. by eapply find_procedure_prog_interface; eauto.\n                ** repeat (move : IHstack => /andP => [[IHstack _]]).\n                   by eapply IHfind; eauto.\n                ** split; [inversion Hstep23; subst; simpl in *; auto |].\n                   --- by eapply stack_wf_wrt_prog_interface_b_nextblock_alloc; eauto.\n                   --- by eapply stack_wf_wrt_prog_interface_b_nextblock_store; eauto.\n                   --- repeat (apply/andP; split; [|assumption]).\n                       by eapply find_procedure_prog_interface; eauto.\n                   --- repeat (apply/andP; split; [|assumption]).\n                       assert (Hrewr: mem =\n                                      s_memory [State C, s, mem,\n                                                Kcall C' P k,\n                                                E_val v, old_call_arg]) by auto.\n                       erewrite <- comes_from_initial_state_mem_domm.\n                       +++ apply/dommP. exists compMem. by erewrite <- Hrewr.\n                       +++ eassumption.\n                       +++ apply star_iff_starR. eassumption.\n                   --- by (move : IHstack => /andP => [[_ ?]]).\n                   --- by (move : IHstack => /andP => [[_ ?]]).\n                   --- inversion Hstep23; subst; simpl in *; auto.\n                       +++ intros ? Hdomm.\n                           specialize (IHfind _ Hdomm) as [? [Ga Gb]].\n                           specialize (@b_nextblock_alloc\n                                         (Ptr (Permission.data, C', Block.local, 0%Z))\n                                         mem C size ptr mem')\n                             as G1.\n                           assert (b_nextblock\n                                     mem\n                                     (Ptr (Permission.data, C', Block.local, 0%Z)))\n                             as G2.\n                           {\n                             simpl. by rewrite Ga.\n                           }\n                           specialize (G1 G2 H0). simpl in G1.\n                           destruct (mem' C'); [|discriminate].\n                           by eauto.\n                       +++ intros C'0 Hdomm.\n                           specialize (IHfind _ Hdomm) as [? [Ga Gb]].\n                           specialize (@b_nextblock_store\n                                         mem\n                                         (Ptr (Permission.data, C'0, Block.local, 0%Z))\n                                         P' C' b' o' v mem') as G1.\n                           assert (b_nextblock\n                                     mem (Ptr (Permission.data, C'0, Block.local, 0%Z)))\n                             as G2.\n                           {\n                             simpl. by rewrite Ga.\n                           }\n                           specialize (G1 G2 H). simpl in G1.\n                           destruct (mem' C'0); [|discriminate].\n                           by eauto.\n  Qed.\n\n  Lemma load_data_next_block:\n      forall s t s' ptr C b o,\n        initial_state p s ->\n        Star sem s t s' ->\n        Memory.load (CS.s_memory s') ptr = Some (Ptr (Permission.data, C, b, o)) ->\n        exists Cmem : ComponentMemory.t,\n          CS.s_memory s' C = Some Cmem /\\ b < ComponentMemory.next_block Cmem.\n  Proof.\n    intros.\n    specialize (load_data_next_block_inductively_provable H H0) as [G1 _].\n    eapply G1; eauto.\n  Qed.\n  \n  (* NOTE: Consider a CSInvariants for the Source *)\n  Definition private_pointers_never_leak_S metadata_size :=\n    forall (s : state) (t : Events.trace Events.event),\n      Star sem (initial_machine_state p) t s ->\n      good_trace_extensional (left_addr_good_for_shifting metadata_size) t /\\\n      (forall (mem : eqtype.Equality.sort Memory.Memory.t),\n          s_memory s = mem ->\n          shared_locations_have_only_shared_values mem metadata_size\n      ).\nEnd Semantics.\n\nEnd CS.\n\nNotation \"[ 'CState' C , stk , mem , k , e , arg ]\" :=\n  (CS.State C stk mem k e arg)\n  (at level 0, format \"[ 'CState'  C ,  stk ,  mem ,  k ,  e ,  arg ]\").\n", "meta": {"author": "secure-compilation", "repo": "SecurePtrs", "sha": "5b4c34eda0b827469a5c73e434a12c6c87773e04", "save_path": "github-repos/coq/secure-compilation-SecurePtrs", "path": "github-repos/coq/secure-compilation-SecurePtrs/SecurePtrs-5b4c34eda0b827469a5c73e434a12c6c87773e04/Source/CS.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.2143784954871867}}
{"text": "Add Rec LoadPath \".\" as DEP_AI.\n\nRequire Import language.\nRequire Import values.\nRequire Import operational_semantics.\n\nRequire Import over_instrumented_values.\nRequire Import oitval_instantiation.\nRequire Import oitval_val_conversion.\nRequire Import oitval_val_conversion_facts.\nRequire Import is_instantiable_oitval.\nRequire Import over_instrumented_semantics.\n\nRequire Import injection_operational_semantics.\nRequire Import ldna_in.\nRequire Import ldna_in_facts.\nRequire Import proof_injection_op_sem.\n\nRequire Import instrumented_values.\nRequire Import instrumented_semantics.\nRequire Import itval_val_conversion.\nRequire Import oival_ival_conversion.\nRequire Import oival_ival_conversion_facts.\n\n\n\n\nDefinition dummy_val := V_Num 0.\nDefinition dummy_oival := OIV_Num 0.\n\n(* SIMPLE VALUES *)\n\nInductive partially_approximated_val : val -> val -> Prop :=\n| PApprox_val_approx :\n    forall (v:val),\n      partially_approximated_val v dummy_val\n| PApprox_val_Num :\n    forall (n:Z),\n      partially_approximated_val (V_Num n) (V_Num n)\n| PApprox_val_Bool :\n    forall (b:bool),\n      partially_approximated_val (V_Bool b) (V_Bool b)\n| PApprox_val_Constr0 :\n    forall (n:constr),\n      partially_approximated_val (V_Constr0 n) (V_Constr0 n)\n| PApprox_val_Constr1 :\n    forall (n:constr) (v v':val),\n      partially_approximated_val v v'\n      -> partially_approximated_val (V_Constr1 n v) (V_Constr1 n v')\n| PApprox_val_Couple :\n    forall (v1 v1' v2 v2':val),\n    partially_approximated_val v1 v1'\n    -> partially_approximated_val v2 v2'\n    -> partially_approximated_val (V_Couple v1 v2) (V_Couple v1' v2')\n| PApprox_val_Closure :\n    forall (x:identifier) (e:expr) (c c':env),\n      partially_approximated_env c c'\n      -> partially_approximated_val (V_Closure x e c) (V_Closure x e c')\n| PApprox_val_Rec_Closure :\n    forall (f x:identifier) (e:expr) (c c':env),\n      partially_approximated_env c c'\n      -> partially_approximated_val (V_Rec_Closure f x e c) (V_Rec_Closure f x e c')\n\nwith partially_approximated_env : env -> env -> Prop :=\n| PApprox_env_empty :\n    partially_approximated_env Env_empty Env_empty\n| PApprox_env_cons :\n    forall (x:identifier) (v v':val) (c c':env),\n    partially_approximated_val v v'\n    -> partially_approximated_env c c'\n    -> partially_approximated_env (Env_cons x v c) (Env_cons x v' c').\n\n(* OVER-INSTRUMENTED VALUES *)\n\nInductive partially_approximated_oitdeps_fun : (val->bool) -> (val->bool) -> Prop :=\n| PApprox_oitdeps_fun :\n    forall (tf tf':val->bool),\n      (forall (vl:val), tf' vl = true \\/ tf' vl = tf vl)\n      -> partially_approximated_oitdeps_fun tf tf'.\n\nInductive partially_approximated_oitdeps : oitdeps -> oitdeps -> Prop :=\n| PApprox_oitdeps_empty :\n    partially_approximated_oitdeps nil nil\n| PApprox_oitdeps_cons :\n    forall (oitd oitd':oitdeps) (l:label) (tf tf':val->bool),\n      partially_approximated_oitdeps oitd oitd'\n      -> partially_approximated_oitdeps_fun tf tf'\n      -> partially_approximated_oitdeps (cons (l,tf) oitd) (cons (l,tf') oitd').\n\nInductive partially_approximated_oideps_fun : (val->val) -> (val->val) -> Prop :=\n| PApprox_oideps_fun :\n    forall (f f':val->val),\n      (forall (vl:val), partially_approximated_val (f vl) (f' vl))\n      -> partially_approximated_oideps_fun f f'.\n\nInductive partially_approximated_oideps : oideps -> oideps -> Prop :=\n| PApprox_oideps_empty :\n    partially_approximated_oideps nil nil\n| PApprox_oideps_cons :\n    forall (oid oid':oideps) (l:label) (f f':val->val),\n      partially_approximated_oideps oid oid'\n      -> partially_approximated_oideps_fun f f'\n      -> partially_approximated_oideps (cons (l,f) oid) (cons (l,f') oid').\n\n\n(* express that oiu2 is a partial approximation of oiu1 *)\nInductive partially_approximated_oival0 : oival0 -> oival0 -> Prop :=\n| PApprox_oival0_approx :\n    forall (v:oival0),\n      partially_approximated_oival0 v (OIV_Num 0)\n| PApprox_oival0_Num :\n    forall (n:Z),\n    partially_approximated_oival0 (OIV_Num n) (OIV_Num n)\n| PApprox_oival0_Bool :\n    forall (b:bool),\n    partially_approximated_oival0 (OIV_Bool b) (OIV_Bool b)\n| PApprox_oival0_Constr0 :\n    forall (n:constr),\n    partially_approximated_oival0 (OIV_Constr0 n) (OIV_Constr0 n)\n| PApprox_oival0_Constr1 :\n    forall (oiu oiu':oival) (n:constr),\n    partially_approximated_oival oiu oiu'\n    -> partially_approximated_oival0 (OIV_Constr1 n oiu) (OIV_Constr1 n oiu')\n| PApprox_oival0_Couple :\n    forall (oiu1 oiu2 oiu1' oiu2':oival),\n    partially_approximated_oival oiu1 oiu1'\n    -> partially_approximated_oival oiu2 oiu2'\n    -> partially_approximated_oival0 (OIV_Couple oiu1 oiu2) (OIV_Couple oiu1' oiu2')\n| PApprox_oival0_Closure :\n    forall (oic oic':oienv) (x:identifier) (e:expr),\n    partially_approximated_oienv oic oic'\n    -> partially_approximated_oival0 (OIV_Closure x e oic) (OIV_Closure x e oic')\n| PApprox_oival0_Rec_Closure :\n    forall (oic oic':oienv) (f x:identifier) (e:expr),\n    partially_approximated_oienv oic oic'\n    -> partially_approximated_oival0 (OIV_Rec_Closure f x e oic) (OIV_Rec_Closure f x e oic')\n\n\nwith partially_approximated_oival : oival -> oival -> Prop :=\n| PApprox_oival :\n    forall (oid oid':oideps) (oiv oiv':oival0),\n    partially_approximated_oideps oid oid'\n    -> partially_approximated_oival0 oiv oiv'\n    -> partially_approximated_oival (OIV_ oid oiv) (OIV_ oid' oiv')\n\nwith partially_approximated_oienv : oienv -> oienv -> Prop :=\n| PApprox_oienv_empty :\n    partially_approximated_oienv OIEnv_empty OIEnv_empty\n| PApprox_oienv_cons :\n    forall (x:identifier) (oiu oiu':oival) (oic oic':oienv),\n    partially_approximated_oival oiu oiu'\n    -> partially_approximated_oienv oic oic'\n    -> partially_approximated_oienv (OIEnv_cons x oiu oic) (OIEnv_cons x oiu' oic').\n\n\nInductive partially_approximated_oitval : oitval -> oitval -> Prop :=\n| PApprox_oitval :\n    forall (oitd oitd':oitdeps) (oiu oiu':oival),\n    partially_approximated_oitdeps oitd oitd'\n    -> partially_approximated_oival oiu oiu'\n    -> partially_approximated_oitval (OIV oitd oiu) (OIV oitd' oiu').\n\nInductive partially_approximated_oitenv : oitenv -> oitenv -> Prop :=\n| PApprox_oitenv_empty :\n    partially_approximated_oitenv OITEnv_empty OITEnv_empty\n| PApprox_oitenv_cons :\n    forall (x:identifier) (oitu oitu':oitval) (oitc oitc':oitenv),\n    partially_approximated_oitval oitu oitu'\n    -> partially_approximated_oitenv oitc oitc'\n    -> partially_approximated_oitenv (OITEnv_cons x oitu oitc) (OITEnv_cons x oitu' oitc').\n\n(*\nTODO: déplacer l'explication hors du code source Coq\n\nexplications:\n- pa_oid possède 2 cas à cause de la règle Annot (qui ajoute un f non approximé dans d)\n- pa_oitd possède 2 cas à cause des 3 deps_spec_... qui propagent l'approx\n- \nà part ça, le reste est équivalent à oitval_to_itval_to_oitval\n\npa_oitd_fun =\n| forall vl, tf' vl = true OR tf' vl = tf vl\npa_oitd =\n| nil\n| cons: tf = pa_oitd_fun, oitd = pa_oitd\n\npa_oid_fun =\n| forall vl, f' vl = dummy_val OR f' vl = f vl\npa_oid =\n| nil\n| cons: f = pa_oid_fun, oid = pa_oid\n\npa_oienv =\n| empty\n| cons: oiu = pa_oival, oic = pa_oienv\n\npa_oival0 =\n| same (num, bool, constr0)\n| constr1: u = pa_oival\n| closure: c = pa_oienv\n| rec: c = pa_oienv\n| couple: u1 = pa_oival, u2 = pa_oival\n\npa_oival =\n|d' = pa_oid, v = pa_oival0\n\npa_oitval =\n|td' = pa_oitd, u = pa_oival\n\n\nà l'endroit où on utilisait le lemme oival_of_in_approximated_oitenv_via_itenv, on avait une évaluation dans un environnement complètement approximé (oitenv_to_itenv_to_oitenv, donc le lemme suivant nous suffirait:\nsi éval dans env approx donne oitu\nalors on a éval dans env qui donne oitu'\n      et oitu = partial_approx oitu'\nmais la preuve par induction nécessite une hypothèse moins forte:\nsi éval dans env partial_approx donne oitu\nalors on a éval dans env qui donne oitu'\n      et oitu = partial_approx oitu'\n\n *)\n\n\n(* STRICT FOR OVER-INSTRUMENTED VALUES *)\n\n(* express that oiu2 is a partial approximation of oiu1 *)\nInductive strictly_partially_approximated_oival0 : oival0 -> oival0 -> Prop :=\n| SPApprox_oival0_Num :\n    forall (n:Z),\n    strictly_partially_approximated_oival0 (OIV_Num n) (OIV_Num n)\n| SPApprox_oival0_Bool :\n    forall (b:bool),\n    strictly_partially_approximated_oival0 (OIV_Bool b) (OIV_Bool b)\n| SPApprox_oival0_Constr0 :\n    forall (n:constr),\n    strictly_partially_approximated_oival0 (OIV_Constr0 n) (OIV_Constr0 n)\n| SPApprox_oival0_Constr1 :\n    forall (oiu oiu':oival) (n:constr),\n    strictly_partially_approximated_oival oiu oiu'\n    -> strictly_partially_approximated_oival0 (OIV_Constr1 n oiu) (OIV_Constr1 n oiu')\n| SPApprox_oival0_Couple :\n    forall (oiu1 oiu2 oiu1' oiu2':oival),\n    strictly_partially_approximated_oival oiu1 oiu1'\n    -> strictly_partially_approximated_oival oiu2 oiu2'\n    -> strictly_partially_approximated_oival0 (OIV_Couple oiu1 oiu2) (OIV_Couple oiu1' oiu2')\n| SPApprox_oival0_Closure :\n    forall (oic oic':oienv) (x:identifier) (e:expr),\n    strictly_partially_approximated_oienv oic oic'\n    -> strictly_partially_approximated_oival0 (OIV_Closure x e oic) (OIV_Closure x e oic')\n| SPApprox_oival0_Rec_Closure :\n    forall (oic oic':oienv) (f x:identifier) (e:expr),\n    strictly_partially_approximated_oienv oic oic'\n    -> strictly_partially_approximated_oival0 (OIV_Rec_Closure f x e oic) (OIV_Rec_Closure f x e oic')\n\n\nwith strictly_partially_approximated_oival : oival -> oival -> Prop :=\n| SPApprox_oival :\n    forall (oid oid':oideps) (oiv oiv':oival0),\n    partially_approximated_oideps oid oid'\n    -> strictly_partially_approximated_oival0 oiv oiv'\n    -> strictly_partially_approximated_oival (OIV_ oid oiv) (OIV_ oid' oiv')\n\nwith strictly_partially_approximated_oienv : oienv -> oienv -> Prop :=\n| SPApprox_oienv_empty :\n    strictly_partially_approximated_oienv OIEnv_empty OIEnv_empty\n| SPApprox_oienv_cons :\n    forall (x:identifier) (oiu oiu':oival) (oic oic':oienv),\n    strictly_partially_approximated_oival oiu oiu'\n    -> strictly_partially_approximated_oienv oic oic'\n    -> strictly_partially_approximated_oienv (OIEnv_cons x oiu oic) (OIEnv_cons x oiu' oic').\n\n\nInductive strictly_partially_approximated_oitval : oitval -> oitval -> Prop :=\n| SPApprox_oitval :\n    forall (oitd oitd':oitdeps) (oiu oiu':oival),\n    partially_approximated_oitdeps oitd oitd'\n    -> strictly_partially_approximated_oival oiu oiu'\n    -> strictly_partially_approximated_oitval (OIV oitd oiu) (OIV oitd' oiu').\n\nInductive strictly_partially_approximated_oitenv : oitenv -> oitenv -> Prop :=\n| SPApprox_oitenv_empty :\n    strictly_partially_approximated_oitenv OITEnv_empty OITEnv_empty\n| SPApprox_oitenv_cons :\n    forall (x:identifier) (oitu oitu':oitval) (oitc oitc':oitenv),\n    strictly_partially_approximated_oitval oitu oitu'\n    -> strictly_partially_approximated_oitenv oitc oitc'\n    -> strictly_partially_approximated_oitenv (OITEnv_cons x oitu oitc) (OITEnv_cons x oitu' oitc').\n\n\n(*** TACTIC ***)\n\nLtac auto_papprox :=\n  match goal with\n    | |- partially_approximated_val _ dummy_val => apply PApprox_val_approx; auto_papprox\n    | |- partially_approximated_val _ (V_Num 0) => apply PApprox_val_approx; auto_papprox\n    | |- partially_approximated_val (V_Num _) _ => apply PApprox_val_Num; auto_papprox\n    | |- partially_approximated_val (V_Bool _) _ => apply PApprox_val_Bool; auto_papprox\n    | |- partially_approximated_val (V_Constr0 _) _ => apply PApprox_val_Constr0; auto_papprox\n    | |- partially_approximated_val (V_Constr1 _ _) _ => apply PApprox_val_Constr1; auto_papprox\n    | |- partially_approximated_val (V_Couple _ _) _ => apply PApprox_val_Couple; auto_papprox\n    | |- partially_approximated_val (V_Closure _ _ _) _ => apply PApprox_val_Closure; auto_papprox\n    | |- partially_approximated_val (V_Rec_Closure _ _ _ _) _ => apply PApprox_val_Rec_Closure; auto_papprox\n    | |- partially_approximated_env (Env_empty) _ => apply PApprox_env_empty; auto_papprox\n    | |- partially_approximated_env (Env_cons _ _ _) _ => apply PApprox_env_cons; auto_papprox\n    | |- partially_approximated_oitdeps nil nil => apply PApprox_oitdeps_empty; auto_papprox\n    | |- partially_approximated_oitdeps (cons _ _) _ => apply PApprox_oitdeps_cons; auto_papprox\n    | |- partially_approximated_oideps nil nil => apply PApprox_oideps_empty; auto_papprox\n    | |- partially_approximated_oideps (cons _ _) _ => apply PApprox_oideps_cons; auto_papprox\n    | |- partially_approximated_oitval _ _ => apply PApprox_oitval; auto_papprox\n    | |- partially_approximated_oival _ _ => apply PApprox_oival; auto_papprox\n    | |- partially_approximated_oival0 _ (OIV_Num 0) => apply PApprox_oival0_approx; auto_papprox\n    | |- partially_approximated_oival0 (OIV_Num _) _ => apply PApprox_oival0_Num; auto_papprox\n    | |- partially_approximated_oival0 (OIV_Bool _) _ => apply PApprox_oival0_Bool; auto_papprox\n    | |- partially_approximated_oival0 (OIV_Constr0 _) _ => apply PApprox_oival0_Constr0; auto_papprox\n    | |- partially_approximated_oival0 (OIV_Constr1 _ _) _ => apply PApprox_oival0_Constr1; auto_papprox\n    | |- partially_approximated_oival0 (OIV_Couple _ _) _ => apply PApprox_oival0_Couple; auto_papprox\n    | |- partially_approximated_oival0 (OIV_Closure _ _ _) _ => apply PApprox_oival0_Closure; auto_papprox\n    | |- partially_approximated_oival0 (OIV_Rec_Closure _ _ _ _) _ => apply PApprox_oival0_Rec_Closure; auto_papprox\n    | |- partially_approximated_oienv OIEnv_empty OIEnv_empty => apply PApprox_oienv_empty; auto_papprox\n    | |- partially_approximated_oienv (OIEnv_cons _ _ _) (OIEnv_cons _ _ _) =>\n      apply PApprox_oienv_cons; auto_papprox\n    | |- partially_approximated_oitenv OITEnv_empty OITEnv_empty => apply PApprox_oitenv_empty; auto_papprox\n    | |- partially_approximated_oitenv (OITEnv_cons _ _ _) (OITEnv_cons _ _ _) =>\n      apply PApprox_oitenv_cons; auto_papprox\n\n    | |- strictly_partially_approximated_oitval _ _ => apply SPApprox_oitval; auto_papprox\n    | |- strictly_partially_approximated_oival _ _ => apply SPApprox_oival; auto_papprox\n    | |- strictly_partially_approximated_oival0 (OIV_Num _) _ => apply SPApprox_oival0_Num; auto_papprox\n    | |- strictly_partially_approximated_oival0 (OIV_Bool _) _ => apply SPApprox_oival0_Bool; auto_papprox\n    | |- strictly_partially_approximated_oival0 (OIV_Constr0 _) _ => apply SPApprox_oival0_Constr0; auto_papprox\n    | |- strictly_partially_approximated_oival0 (OIV_Constr1 _ _) _ => apply SPApprox_oival0_Constr1; auto_papprox\n    | |- strictly_partially_approximated_oival0 (OIV_Couple _ _) _ => apply SPApprox_oival0_Couple; auto_papprox\n    | |- strictly_partially_approximated_oival0 (OIV_Closure _ _ _) _ => apply SPApprox_oival0_Closure; auto_papprox\n    | |- strictly_partially_approximated_oival0 (OIV_Rec_Closure _ _ _ _) _ => apply SPApprox_oival0_Rec_Closure; auto_papprox\n    | |- strictly_partially_approximated_oienv OIEnv_empty OIEnv_empty => apply SPApprox_oienv_empty; auto_papprox\n    | |- strictly_partially_approximated_oienv (OIEnv_cons _ _ _) (OIEnv_cons _ _ _) =>\n      apply SPApprox_oienv_cons; auto_papprox\n    | |- strictly_partially_approximated_oitenv OITEnv_empty OITEnv_empty => apply SPApprox_oitenv_empty; auto_papprox\n    | |- strictly_partially_approximated_oitenv (OITEnv_cons _ _ _) (OITEnv_cons _ _ _) =>\n      apply SPApprox_oitenv_cons; auto_papprox\n    | |- _ => auto\n  end.\n\n\n\n\n\n\n(*** FACTS  ***)\n\nLemma partially_approximated_val_refl :\n  forall v : val, partially_approximated_val v v.\nProof.\n  apply (val_ind2\n           (fun v => partially_approximated_val v v)\n           (fun c => partially_approximated_env c c));\n  intros; auto_papprox.\nQed.\n\nLemma partially_approximated_env_refl :\n  forall c : env, partially_approximated_env c c.\nProof.\n  apply (env_ind2\n           (fun v => partially_approximated_val v v)\n           (fun c => partially_approximated_env c c));\n  intros; auto_papprox.\nQed.\n\n\n\nLemma partially_approximated_oitdeps_fun_refl :\n  forall tf : val->bool, partially_approximated_oitdeps_fun tf tf.\nProof.\n  intros tf.\n  apply PApprox_oitdeps_fun.\n  intros vl.\n  right; auto.\nQed.\n\nLemma partially_approximated_oitdeps_refl :\n  forall oitd : oitdeps, partially_approximated_oitdeps oitd oitd.\nProof.\n  induction oitd; auto_papprox.\n  destruct a as [l f].\n  auto_papprox.\n  apply partially_approximated_oitdeps_fun_refl.\nQed.\n\nLemma partially_approximated_oideps_fun_refl :\n  forall f : val->val, partially_approximated_oideps_fun f f.\nProof.\n  intros f.\n  apply PApprox_oideps_fun.\n  intros vl.\n  apply partially_approximated_val_refl.\nQed.\n\nLemma partially_approximated_oideps_refl :\n  forall oid : oideps, partially_approximated_oideps oid oid.\nProof.\n  induction oid; auto_papprox.\n  destruct a as [l f].\n  auto_papprox.\n  apply partially_approximated_oideps_fun_refl.\nQed.\n\nLemma strictly_partially_approximated_oival_refl :\n  forall oiu : oival, strictly_partially_approximated_oival oiu oiu.\nProof.\n  apply (oival_ind2\n           (fun oiu => strictly_partially_approximated_oival oiu oiu)\n           (fun oiv => strictly_partially_approximated_oival0 oiv oiv)\n           (fun oic => strictly_partially_approximated_oienv oic oic));\n  intros;  auto_papprox.\n  apply partially_approximated_oideps_refl.\nQed.\n\nLemma strictly_partially_approximated_oitenv_refl :\n  forall oitc : oitenv, strictly_partially_approximated_oitenv oitc oitc.\nProof.\n  apply (oitenv_ind2\n           (fun oitu => strictly_partially_approximated_oitval oitu oitu)\n           (fun oitc => strictly_partially_approximated_oitenv oitc oitc));\n  intros;  auto_papprox.\n  apply partially_approximated_oitdeps_refl.\n  apply strictly_partially_approximated_oival_refl.\nQed.\n\n(*** FACTS ABOUT INSTANTIATION ***)\n\nLemma aif_in_partially_approximated_oideps_some :\n  forall (oid oid':oideps) (l:label) (vl v':val),\n  partially_approximated_oideps oid oid'\n  -> apply_impact_fun l vl oid' = Some v'\n  -> exists (v:val), apply_impact_fun l vl oid = Some v\n    /\\ partially_approximated_val v v'.\nProof.\n  intros oid oid' l vl v' H H0.\n  induction H.\n\n  inversion H0.\n\n  simpl in H0.\n  destruct (eq_label_dec l l0) eqn:H_l_l0.\n\n  (* l = l0 *)\n  induction H1.\n  specialize (H1 vl).\n  inversion H1; inversion H0.\n\n  exists (f vl); simpl; rewrite H_l_l0; split; auto_papprox.\n\n  exists (V_Num n); simpl; rewrite H_l_l0, <-H3, <-H4; split; auto_papprox.\n  exists (V_Bool b); simpl; rewrite H_l_l0, <-H3, <-H4; split; auto_papprox.\n  exists (V_Constr0 n); simpl; rewrite H_l_l0, <-H3, <-H4; split; auto_papprox.\n  exists (V_Constr1 n v); simpl; rewrite H_l_l0, <-H2, <-H3; split; auto_papprox.\n  exists (V_Couple v1 v2); simpl; rewrite H_l_l0, <-H2, <-H3; split; auto_papprox.\n  exists (V_Closure x e0 c); simpl; rewrite H_l_l0, <-H2, <-H3; split; auto_papprox.\n  exists (V_Rec_Closure f0 x e0 c); simpl; rewrite H_l_l0, <-H2, <-H3; split; auto_papprox.\n\n  (* l <> l0 *)\n  specialize (IHpartially_approximated_oideps H0).\n  inversion IHpartially_approximated_oideps as [v HH].\n  inversion HH as [H_aif_oid H_papprox_v].\n  exists v.\n  simpl.\n  rewrite H_l_l0.\n  split; auto.\nQed.\n\nLemma aif_in_partially_approximated_oideps_none :\n  forall (oid oid':oideps) (l:label) (vl:val),\n  partially_approximated_oideps oid oid'\n  -> apply_impact_fun l vl oid' = None\n  -> apply_impact_fun l vl oid = None.\nProof.\n  intros oid oid' l vl H H0.\n  induction H; auto.\n\n  simpl; simpl in H0.\n  destruct (eq_label_dec l l0).\n  inversion H0.\n  auto.\nQed.\n\nLemma atif_in_partially_approximated_oitdeps_some_true :\n  forall (oitd oitd':oitdeps) (l:label) (vl:val),\n  partially_approximated_oitdeps oitd oitd'\n  -> apply_timpact_fun l vl oitd' <> Some true\n  -> apply_timpact_fun l vl oitd <> Some true.\nProof.\n  intros oitd oitd' l vl H H0.\n  induction H; auto.\n\n  simpl; simpl in H0.\n  destruct (eq_label_dec l l0).\n\n  inversion H1.\n  specialize (H2 vl).\n  inversion_clear H2.\n  rewrite H5 in H0.\n  simpl in H0.\n  destruct (apply_timpact_fun l vl oitd'); elim (H0 eq_refl).\n  rewrite <-H5.\n\n  assert(HH: apply_timpact_fun l vl oitd' <> Some true).\n  intro HH; rewrite HH in H0; simpl in H0; rewrite Bool.orb_true_intro in H0; auto.\n  rewrite utils.match_option_bool_not_true2 in H0; auto.\n  apply IHpartially_approximated_oitdeps in HH.\n  rewrite utils.match_option_bool_not_true2; auto.\n  auto.\nQed.\n\nLemma instantiate_partially_approximated_oival :\n  forall (oiu oiu':oival) (l:label) (vl v':val),\n  partially_approximated_oival oiu oiu'\n  -> instantiate_oival l vl oiu' = Some v'\n  -> exists (v:val), instantiate_oival l vl oiu = Some v\n                     /\\ partially_approximated_val v v'.\nProof.\n  apply (oival_ind2\n    (fun oiu => forall (oiu':oival) (l:label) (vl v':val),\n      partially_approximated_oival oiu oiu'\n      -> instantiate_oival l vl oiu' = Some v'\n      -> exists (v:val), instantiate_oival l vl oiu = Some v\n        /\\ partially_approximated_val v v')\n    (fun oiv => forall (oiv':oival0) (l:label) (vl v':val),\n      partially_approximated_oival0 oiv oiv'\n      -> instantiate_oival0 l vl oiv' = Some v'\n      -> exists (v:val), instantiate_oival0 l vl oiv = Some v\n        /\\ partially_approximated_val v v')\n    (fun oic => forall (oic':oienv) (l:label) (vl:val) (c':env),\n      partially_approximated_oienv oic oic'\n      -> instantiate_oienv l vl oic' = Some c'\n      -> exists (c:env), instantiate_oienv l vl oic = Some c\n        /\\ partially_approximated_env c c')).\n\n  (* case oival *)\n  intros d vv H oiu' l vl v' H0 H1.\n  inversion H0.\n  rewrite <-H5 in H1.\n  simpl in H1.\n\n  destruct (apply_impact_fun l vl oid') eqn:H_aif_oid'.\n  \n  (** l is in oid *)\n  rewrite H1 in H_aif_oid'; clear H1 v.\n  apply aif_in_partially_approximated_oideps_some with (oid:=d) in H_aif_oid'; auto.\n  inversion_clear H_aif_oid' as [v HH].\n  inversion_clear HH as [H_aif_oid H_papprox_v].\n  exists v.\n  simpl.\n  rewrite H_aif_oid.\n  auto.\n\n  (** l is not in oid *)\n  apply aif_in_partially_approximated_oideps_none with (oid:=d) in H_aif_oid'; auto.\n  rename H_aif_oid' into H_aif_oid.\n  specialize(H oiv' l vl v' H6 H1).\n  inversion_clear H as [v HH].\n  inversion_clear HH as [H_inst_vv H_papprox_v].\n  exists v.\n  simpl.\n  rewrite H_aif_oid.\n  auto.\n\n  (* case oival0 Num *)\n  intros n oiv' l vl v' H H0.\n  inversion H;\n    [rewrite <-H2 in H0|rewrite <-H1 in H0];\n    inversion H0;\n    exists (V_Num n);\n    split; auto_papprox.\n\n  (* case oival0 Bool *)\n  intros b oiv' l vl v' H H0.\n  inversion H;\n  [rewrite <-H2 in H0|rewrite <-H1 in H0];\n    inversion H0;\n    exists (V_Bool b);\n    split; auto_papprox.\n\n  (* case oival0 Constr0 *)\n  intros n oiv' l vl v' H H0.\n  inversion H;\n  [rewrite <-H2 in H0|rewrite <-H1 in H0];\n    inversion H0;\n    exists (V_Constr0 n);\n    split; auto_papprox.\n\n  (* case oival0 Constr1 *)\n  intros n u H oiv' l vl v' H0 H1.\n  inversion H0;\n  rewrite <-H3 in H1; simpl in H1.\n\n  destruct (is_instantiable_oival u l vl) as [v0 H_inst_u];\n  exists(V_Constr1 n v0);\n  simpl; rewrite H_inst_u.\n  inversion H1.\n  split; simpl; auto_papprox.\n\n  destruct(instantiate_oival l vl oiu') as [v'0|] eqn:H_inst_oiu'; try solve [inversion H1].\n  simpl in H1.\n  inversion H1.\n  specialize(H oiu' l vl v'0 H5 H_inst_oiu').\n  inversion_clear H as [v HH].\n  inversion_clear HH as [H_inst_u H_papprox_v].\n  exists (V_Constr1 n v).\n  split; auto_papprox.\n  simpl.\n  rewrite H_inst_u; auto.\n\n  (* case oival0 Closure *)\n  intros x e oic H oiv' l vl v' H0 H1.\n  inversion H0;\n    rewrite <-H3 in H1; inversion H1.\n\n  destruct (is_instantiable_oienv oic l vl) as [c H_inst_oic];\n  exists(V_Closure x e c);\n  simpl; rewrite H_inst_oic.\n  inversion H1.\n  split; simpl; auto_papprox.\n\n  destruct(instantiate_oienv l vl oic') as [c'|] eqn:H_inst_oic'; try solve [inversion H8]; inversion H8.\n  specialize(H oic' l vl c' H6 H_inst_oic').\n  inversion_clear H as [c HH].\n  inversion_clear HH as [H_inst_oic H_papprox_c].\n  exists (V_Closure x e c).\n  split; auto_papprox.\n  simpl.\n  rewrite H_inst_oic; auto.\n\n  (* case oival0 Couple *)\n  intros u1 H u2 H0 oiv' l vl v' H1 H2.\n  inversion H1.\n\n  rewrite <-H4 in H2; simpl in H2.\n  destruct (is_instantiable_oival u1 l vl) as [v1 H_inst_u1];\n  destruct (is_instantiable_oival u2 l vl) as [v2 H_inst_u2];\n  exists(V_Couple v1 v2);\n  simpl; rewrite H_inst_u1; rewrite H_inst_u2.\n  inversion H2.\n  split; simpl; auto_papprox.\n\n  rewrite <-H6 in H2; simpl in H2.\n  destruct(instantiate_oival l vl oiu1') as [v'1|] eqn:H_inst_oiu1'; try solve [inversion H2].\n  destruct(instantiate_oival l vl oiu2') as [v'2|] eqn:H_inst_oiu2'; try solve [inversion H2].\n  inversion_clear H2.\n  specialize(H oiu1' l vl v'1 H5 H_inst_oiu1').\n  inversion_clear H as [v1 HH].\n  inversion_clear HH as [H_inst_u1 H_papprox_v1].\n  specialize(H0 oiu2' l vl v'2 H7 H_inst_oiu2').\n  inversion_clear H0 as [v2 HH].\n  inversion_clear HH as [H_inst_u2 H_papprox_v2].\n  exists(V_Couple v1 v2).\n  split; auto_papprox.\n  simpl; rewrite H_inst_u1, H_inst_u2; auto.\n\n  (* case oival0 Rec_Closure *)\n  intros f x e oic H oiv' l vl v' H0 H1.\n  inversion H0;\n    rewrite <-H3 in H1; inversion H1.\n\n  destruct (is_instantiable_oienv oic l vl) as [c H_inst_oic];\n  exists(V_Rec_Closure f x e c);\n  simpl; rewrite H_inst_oic.\n  inversion H1.\n  split; simpl; auto_papprox.\n\n  destruct(instantiate_oienv l vl oic') as [c'|] eqn:H_inst_oic'; try solve [inversion H9]; inversion H9.\n  specialize(H oic' l vl c' H7 H_inst_oic').\n  inversion_clear H as [c HH].\n  inversion_clear HH as [H_inst_oic H_papprox_c].\n  exists (V_Rec_Closure f x e c).\n  split; auto_papprox.\n  simpl.\n  rewrite H_inst_oic; auto.\n\n  (* case env empty *)\n  intros oic' l vl c' H H0.\n  inversion H.\n  rewrite <-H2 in H0; inversion H0.\n  exists Env_empty; split; auto_papprox.\n\n  (* case env cons *)\n  intros x u H oic'0 H0 oic' l vl c'0 H1 H2.\n  inversion H1.\n  rewrite <-H5 in H2; simpl in H2.\n  destruct(instantiate_oival l vl oiu') as [v'|] eqn:H_inst_oiu'; try solve [inversion H2].\n  destruct(instantiate_oienv l vl oic'1) as [c'1|] eqn:H_inst_oic'1; try solve [inversion H2]; inversion H2.\n  inversion_clear H2.\n  specialize(H oiu' l vl v' H7 H_inst_oiu').\n  inversion_clear H as [v HH].\n  inversion_clear HH as [H_inst_u H_papprox_v].\n  specialize(H0 oic'1 l vl c'1 H8 H_inst_oic'1).\n  inversion_clear H0 as [c HH].\n  inversion_clear HH as [H_inst_oic' H_papprox_c].\n  exists (Env_cons x v c).\n  split; auto_papprox.\n  simpl.\n  rewrite H_inst_u, H_inst_oic'; auto.\nQed.\n\n\nLemma instantiate_partially_approximated_oitval :\n  forall (oitu oitu':oitval) (l:label) (vl v':val),\n  partially_approximated_oitval oitu oitu'\n  -> instantiate_oitval l vl oitu' = Some v'\n  -> exists (v:val), instantiate_oitval l vl oitu = Some v\n                     /\\ partially_approximated_val v v'.\nProof.\n  intros oitu oitu' l vl v' H H0.\n  inversion H.\n  rewrite <-H4 in H0; simpl in H0.\n  assert(HH: apply_timpact_fun l vl oitd' <> Some true); try solve [intro HH; rewrite HH in H0; inversion H0].\n  rewrite utils.match_option_bool_not_true in H0; auto.\n  destruct(instantiate_partially_approximated_oival oiu oiu' l vl v' H2 H0) as [v].\n  inversion H5 as [H_inst_oiu H_papprox_v].\n  exists (v).\n  split; auto.\n  simpl.\n  rewrite utils.match_option_bool_not_true; auto.\n  apply atif_in_partially_approximated_oitdeps_some_true with (oitd':=oitd'); auto.\nQed.\n\nLemma instantiate_partially_approximated_oitenv :\n  forall (oitc oitc_:oitenv) (l:label) (vl:val) (c_:env),\n  partially_approximated_oitenv oitc oitc_\n  -> instantiate_oitenv l vl oitc_ = Some c_\n  -> exists (c:env), instantiate_oitenv l vl oitc = Some c\n                     /\\ partially_approximated_env c c_.\nProof.\n  intros oitc oitc_ l vl c_ H.\n  revert c_.\n  induction H; intros c_ H_inst_oitc_.\n  exists c_; split; auto.\n  apply partially_approximated_env_refl.\n\n  simpl in H_inst_oitc_.\n  destruct(instantiate_oitval l vl oitu') as [v'|] eqn:H_inst_oitu'; try solve [inversion H_inst_oitc_].\n  destruct(instantiate_oitenv l vl oitc') as [c'|] eqn:H_inst_oitc'; try solve [inversion H_inst_oitc_].\n  inversion_clear H_inst_oitc_.\n  specialize (IHpartially_approximated_oitenv c' eq_refl).\n  inversion_clear IHpartially_approximated_oitenv as [c HH].\n  inversion_clear HH as [H_inst_oitc H_papprox_c].\n  destruct(instantiate_partially_approximated_oitval _ _ _ _ _ H H_inst_oitu') as [v HH].\n  inversion_clear HH as [H_inst_oitu H_papprox_v].  \n  exists (Env_cons x v c).\n  simpl.\n  rewrite H_inst_oitu, H_inst_oitc; simpl.\n  split; auto_papprox.\nQed.\n\n\n(*** FACTS ABOUT CONVERSION ***)\n\nLemma partially_approximated_val_to_oival :\n  forall (v v_:val),\n    partially_approximated_val v v_\n    -> partially_approximated_oival (val_to_oival v) (val_to_oival v_).\nProof.\n  intros v v_ H.\n\n  apply (val_ind2\n           (fun v => forall (v_:val), partially_approximated_val v v_\n                     -> partially_approximated_oival (val_to_oival v) (val_to_oival v_))\n           (fun c => forall (c_:env), partially_approximated_env c c_\n                     -> partially_approximated_oienv (env_to_oienv c) (env_to_oienv c_)));\n    intros; try inversion H2; try inversion H1; try inversion H0; simpl; auto_papprox.\nQed.\n\nLemma partially_approximated_val_to_oitval :\n  forall (v v_:val),\n    partially_approximated_val v v_\n    -> partially_approximated_oitval (val_to_oitval v) (val_to_oitval v_).\nProof.\n  intros v v_ H.\n\n  unfold val_to_oitval; simpl; auto_papprox.\n  apply partially_approximated_val_to_oival; auto.\nQed.\n\nLemma partially_approximated_env_to_oitenv :\n  forall (c c_:env),\n    partially_approximated_env c c_\n    -> partially_approximated_oitenv (env_to_oitenv c) (env_to_oitenv c_).\nProof.\n  intros c c_ H.\n\n  induction H; simpl; auto_papprox.\n\n  apply partially_approximated_val_to_oival; auto.\nQed.\n\n(*** FACTS ABOUT TOTALLY-APPROXIMATED ***)\n\nLemma approximated_oitval_implies_strictly_partially_approximated :\n  forall (oitu oitu':oitval),\n    oitu' = itval_to_oitval (oitval_to_itval oitu)\n    -> strictly_partially_approximated_oitval oitu oitu'.\nProof.\n  intros oitu oitu' H.\n  destruct oitu as [oitd oiu].\n  destruct oitu' as [oitd' oiu'].\n  inversion H.\n  apply SPApprox_oitval with (oitd:=oitd) (oitd':=itdeps_to_oitdeps (oitdeps_to_itdeps oitd)) (oiu:=oiu) (oiu':=ival_to_oival (oival_to_ival oiu)); auto.\n  \n  (* oitdeps *)\n  clear dependent oiu'.\n  clear dependent oitd'.\n  induction oitd.\n  apply PApprox_oitdeps_empty.\n  destruct a as [l f].\n  simpl.\n  apply PApprox_oitdeps_cons; auto.\n  apply PApprox_oitdeps_fun; auto.\n\n  (* oival *)\n  clear dependent oiu'.\n  clear dependent oitd'.\n  apply (oival_ind2\n           (fun oiu => strictly_partially_approximated_oival oiu (ival_to_oival (oival_to_ival oiu)))\n           (fun oiv => strictly_partially_approximated_oival0 oiv (ival0_to_oival0 (oival0_to_ival0 oiv)))\n           (fun oic => strictly_partially_approximated_oienv oic (ienv_to_oienv (oienv_to_ienv oic))));\n    intros; simpl; auto_papprox.\n\n  (* oideps *)\n  induction d.\n  apply PApprox_oideps_empty.\n  destruct a as [l f].\n  simpl.\n  apply PApprox_oideps_cons; auto.\n  apply PApprox_oideps_fun; auto.\n  intros vl.\n  auto_papprox.\nQed.\n\nLemma approximated_oitenv_implies_strictly_partially_approximated :\n  forall (oitc oitc_:oitenv),\n    oitc_ = itenv_to_oitenv (oitenv_to_itenv oitc)\n    -> strictly_partially_approximated_oitenv oitc oitc_.\nProof.\n  induction oitc; intros oitc_ H.\n\n  inversion H; simpl; auto_papprox.\n\n  simpl in H.\n  rewrite H; auto_papprox.\n  apply approximated_oitval_implies_strictly_partially_approximated; auto.\nQed.\n\n\n(*** FACTS ABOUT TOTALLY-APPROXIMATED ***)\n\nLemma strictly_partially_approximated_oitval_implies_partially_approximated :\n  forall (oitu oitu':oitval),\n    strictly_partially_approximated_oitval oitu oitu'\n    -> partially_approximated_oitval oitu oitu'.\nProof.\n  intros oitu oitu' H.\n\n  inversion H; simpl; auto_papprox.\n\n  (* oitval *)\n  clear H H0 H2 H3 oitd oitd' oitu oitu'.\n  revert oiu' H1.\n  apply (oival_ind2\n           (fun oiu => forall oiu' : oival, strictly_partially_approximated_oival oiu oiu' ->\n                                            partially_approximated_oival oiu oiu')\n           (fun oiv => forall oiv' : oival0, strictly_partially_approximated_oival0 oiv oiv' ->\n                                            partially_approximated_oival0 oiv oiv')\n           (fun oic => forall oic' : oienv, strictly_partially_approximated_oienv oic oic' ->\n                                            partially_approximated_oienv oic oic')\n        );\n    intros;\n    try solve [inversion H; auto_papprox];\n    try solve [inversion H0; auto_papprox];\n    try solve [inversion H1; auto_papprox].\nQed.\n\nLemma strictly_partially_approximated_oitenv_implies_partially_approximated :\n  forall (oitc oitc':oitenv),\n    strictly_partially_approximated_oitenv oitc oitc'\n    -> partially_approximated_oitenv oitc oitc'.\nProof.\n  intros oitc oitc' H.\n  induction H; auto_papprox.\n\n  apply strictly_partially_approximated_oitval_implies_partially_approximated; auto.\nQed.\n\n(*** FACTS ABOUT CONCATENATION ***)\n\nLemma partially_approximated_conc_oitenv :\n  forall (oitc1 oitc1_ oitc2 oitc2_:oitenv),\n    partially_approximated_oitenv oitc1 oitc1_\n    -> partially_approximated_oitenv oitc2 oitc2_\n    -> partially_approximated_oitenv (conc_oitenv oitc1 oitc2) (conc_oitenv oitc1_ oitc2_).\nProof.\n  induction oitc1; intros oitc1_ oitc2 oitc2_ H H0; simpl.\n\n  inversion H; simpl; auto.\n\n  inversion H; simpl.\n  auto_papprox.\nQed.\n\nLemma strictly_partially_approximated_conc_oitenv :\n  forall (oitc1 oitc1_ oitc2 oitc2_:oitenv),\n    strictly_partially_approximated_oitenv oitc1 oitc1_\n    -> strictly_partially_approximated_oitenv oitc2 oitc2_\n    -> strictly_partially_approximated_oitenv (conc_oitenv oitc1 oitc2) (conc_oitenv oitc1_ oitc2_).\nProof.\n  induction oitc1; intros oitc1_ oitc2 oitc2_ H H0; simpl.\n\n  inversion H; simpl; auto.\n\n  inversion H; simpl.\n  auto_papprox.\nQed.\n\n(*** FACTS ABOUT IS_FILTERED_VAL ***)\n\nLemma is_filtered_partially_approximated_val :\n  forall (c_p_:env) (v v_:val) (p:pattern),\n    partially_approximated_val v v_\n    -> is_filtered v_ p = Filtered_result_Match c_p_\n    -> exists (c_p:env), is_filtered v p = Filtered_result_Match c_p\n                              /\\ partially_approximated_env c_p c_p_.\nProof.\n  intros c_p_ v v_ p H H0.\n  destruct v_; destruct p; inversion H0.\n\n  (* case Constr0 *)\n  destruct (eq_nat_dec n c) eqn:H_n_c; inversion H2.\n  inversion H.\n  exists Env_empty.\n  simpl; rewrite H_n_c.\n  split; auto_papprox.\n\n  (* case Constr1 *)\n  destruct (eq_nat_dec n c) eqn:H_n_c; inversion H2.\n  inversion H.\n  exists (Env_cons i v0 Env_empty).\n  simpl; rewrite H_n_c.\n  split; auto_papprox.\n\n  (* case Couple *)\n  inversion H.\n  exists (Env_cons i v1 (Env_cons i0 v2 Env_empty)); simpl; split; auto_papprox.\nQed.\n\nLemma is_not_filtered_partially_approximated_val :\n  forall (v v_:val) (p:pattern),\n    partially_approximated_val v v_\n    -> is_filtered v_ p = Filtered_result_Match_var\n    -> is_filtered v p = Filtered_result_Match_var.\nProof.\n  intros v v_ p H H0.\n  destruct v_; destruct p; inversion H0; inversion H; auto.\n\n  (* case Constr0 *)\n  destruct (eq_nat_dec n c) eqn:H_n_c; inversion H2.\n  simpl; rewrite H_n_c; auto.\nQed.\n\n(*** FACTS ABOUT IS_FILTERED_OITVAL ***)\n\nLemma is_filtered_strictly_partially_approximated_oitval :\n  forall (c_p_:oitenv) (oitu oitu_:oitval) (p:pattern),\n    strictly_partially_approximated_oitval oitu oitu_\n    -> is_filtered_oitval oitu_ p = Filtered_oitval_result_Match c_p_\n    -> exists (c_p:oitenv), is_filtered_oitval oitu p = Filtered_oitval_result_Match c_p\n                              /\\ strictly_partially_approximated_oitenv c_p c_p_.\nProof.\n  intros c_p_ oitu oitu_ p H H0.\n  inversion H.\n  inversion H2.\n  destruct oiv'; destruct p;\n  rewrite <-H4, <-H8 in H0; inversion H0.\n\n  (* case Constr0 *)\n  destruct (eq_nat_dec n c) eqn:H_n_c; inversion H10.\n  inversion H6.\n  exists OITEnv_empty.\n  simpl; rewrite H_n_c.\n  split; auto_papprox.\n\n  (* case Constr1 *)\n  destruct (eq_nat_dec n c) eqn:H_n_c; inversion H10.\n  inversion H6.\n  exists (OITEnv_cons i (OIV nil oiu0) OITEnv_empty).\n  simpl; rewrite H_n_c.\n  split; auto_papprox.\n\n  (* case Couple *)\n  inversion H6.\n  exists (OITEnv_cons i (OIV nil oiu1) (OITEnv_cons i0 (OIV nil oiu2) OITEnv_empty)); simpl; split; auto_papprox.\nQed.\n\nLemma is_not_filtered_strictly_partially_approximated_oitval :\n  forall (oitu oitu_:oitval) (p:pattern),\n    strictly_partially_approximated_oitval oitu oitu_\n    -> is_filtered_oitval oitu_ p = Filtered_oitval_result_Match_var\n    -> is_filtered_oitval oitu p = Filtered_oitval_result_Match_var.\nProof.\n  intros oitu oitu_ p H H0.\n  inversion H.\n  inversion H2.\n  destruct oiv'; destruct p;\n  rewrite <-H4, <-H8 in H0; inversion H0;\n  inversion H6; auto.\n\n  (* case Constr0 *)\n  destruct (eq_nat_dec n c) eqn:H_n_c; inversion H10.\n  simpl; rewrite H_n_c; auto.\nQed.\n\n(*** FACTS ABOUT ASSOC_IN_OITENV ***)\n\nLemma assoc_in_partially_approximated_oitenv :\n  forall (oitc oitc_:oitenv) (oitu_:oitval) (x:identifier),\n    partially_approximated_oitenv oitc oitc_\n    -> assoc_ident_in_oitenv x oitc_ = Ident_in_oitenv oitu_\n    -> exists (oitu:oitval), assoc_ident_in_oitenv x oitc = Ident_in_oitenv oitu\n                             /\\ partially_approximated_oitval oitu oitu_.\nProof.\n  intros oitc oitc_ oitu_ x H.\n  induction H; intros H_assoc_in_oitc_; inversion H_assoc_in_oitc_.\n\n  destruct (beq_identifier x x0) eqn:H_x_x0; inversion H2.\n\n  exists oitu.\n  simpl.\n  rewrite H_x_x0, <-H3; auto.\n\n  specialize (IHpartially_approximated_oitenv H2).\n  inversion_clear IHpartially_approximated_oitenv as [oitu0 HH].\n  inversion_clear HH.\n  exists oitu0.\n  simpl.\n  rewrite H_x_x0; auto.\nQed.\n", "meta": {"author": "vincent-benayoun", "repo": "PhD-thesis", "sha": "4ee793739177b56c923196765c90ef36b82a9d9f", "save_path": "github-repos/coq/vincent-benayoun-PhD-thesis", "path": "github-repos/coq/vincent-benayoun-PhD-thesis/PhD-thesis-4ee793739177b56c923196765c90ef36b82a9d9f/Coq-proof/partially_approximated.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21437849548718665}}
{"text": "(* Do not edit this file, it was generated automatically *)\nRequire Import VST.floyd.proofauto.\nRequire Import VST.floyd.library.\nRequire Import VST.progs64.object.\n\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nLocal Open Scope Z.\nLocal Open Scope logic.\n\nDefinition object_invariant := list Z -> val -> mpred.\n\nDefinition tobject := tptr (Tstruct _object noattr).\n\nDefinition reset_spec (instance: object_invariant) :=\n  WITH self: val, history: list Z\n  PRE [ tobject]\n          PROP ()\n          PARAMS (self)\n          SEP (instance history self)\n  POST [ tvoid ]\n          PROP() RETURN () SEP(instance nil self).\n\nDefinition twiddle_spec (instance: object_invariant) :=\n  WITH self: val, i: Z, history: list Z\n  PRE [ tobject, tint]\n          PROP (0 < i <= Int.max_signed / 4;\n                0 <= fold_right Z.add 0 history <= Int.max_signed / 4)\n          PARAMS (self; Vint (Int.repr i))\n          SEP (instance history self)\n  POST [ tint ]\n      EX v: Z, \n          PROP(2* fold_right Z.add 0 history < v <= 2* fold_right Z.add 0 (i::history))\n          RETURN (Vint (Int.repr v))\n          SEP(instance (i::history) self).\n\nDefinition object_methods (instance: object_invariant) (mtable: val) : mpred :=\n  EX sh: share, EX reset: val, EX twiddle: val,\n  !! readable_share sh && \n  func_ptr' (reset_spec instance) reset *\n  func_ptr' (twiddle_spec instance) twiddle *\n  data_at sh (Tstruct _methods noattr) (reset,twiddle) mtable.\n\nLemma object_methods_local_facts: forall instance p,\n  object_methods instance p |-- !! isptr p.\nProof.\nintros.\nunfold object_methods.\nIntros sh reset twiddle.\nentailer!.\nQed.\n#[export] Hint Resolve object_methods_local_facts : saturate_local.\n\nDefinition object_mpred (history: list Z) (self: val) : mpred :=\n  EX instance: object_invariant, EX mtable: val, \n       (object_methods instance mtable *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable self*\n     instance history self).\n\nDefinition foo_invariant : object_invariant :=\n  (fun (history: list Z) p =>\n    withspacer Ews (sizeof size_t + sizeof tint) (2 * sizeof size_t) (field_at Ews (Tstruct _foo_object noattr) \n            [StructField _data] (Vint (Int.repr (2*fold_right Z.add 0 history)))) p\n      *  malloc_token Ews (Tstruct _foo_object noattr) p).\n\nDefinition foo_reset_spec :=\n DECLARE _foo_reset (reset_spec foo_invariant).\n\nDefinition foo_twiddle_spec :=\n DECLARE _foo_twiddle  (twiddle_spec foo_invariant).\n\nDefinition make_foo_spec :=\n DECLARE _make_foo\n WITH gv: globals\n PRE [ ]\n    PROP () PARAMS() GLOBALS (gv) \n    SEP (mem_mgr gv; object_methods foo_invariant (gv _foo_methods))\n POST [ tobject ]\n    EX p: val, PROP () RETURN (p)\n     SEP (mem_mgr gv; object_mpred nil p; object_methods foo_invariant (gv _foo_methods)).\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv: globals\n  PRE  [] main_pre prog tt gv\n  POST [ tint ]\n     EX i:Z, PROP(0<=i<=6) RETURN (Vint (Int.repr i)) SEP(TT).\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [\n    foo_reset_spec; foo_twiddle_spec; make_foo_spec; main_spec]).\n\nLemma object_mpred_i:\n  forall (history: list Z) (self: val) (instance: object_invariant) (mtable: val),\n    object_methods instance mtable *\n     field_at Ews (Tstruct _object noattr) [StructField _mtable] mtable self *\n     instance history self \n    |-- object_mpred history self.\nProof.\nintros. unfold object_mpred. Exists instance mtable; auto.\nQed.\n\nLemma body_foo_reset: semax_body Vprog Gprog f_foo_reset foo_reset_spec.\nProof.\nunfold foo_reset_spec, foo_invariant, reset_spec.\nstart_function.\nunfold withspacer; simpl; Intros.\nforward.  (* self->data=0; *)\nentailer!!.\nall: unfold withspacer; simpl; entailer!!.  (* needed if Archi.ptr64=true *)\nQed.\n\nLemma body_foo_twiddle: semax_body Vprog Gprog f_foo_twiddle foo_twiddle_spec.\nProof.\nunfold foo_twiddle_spec, foo_invariant, twiddle_spec.\nstart_function.\nunfold withspacer; simpl.\nIntros.\nforward.  (* d = self->data; *)\nforward.  (* self -> data = d+2*i; *) \n set (j:= Int.max_signed / 4) in *; compute in j; subst j.\n forget (fold_right Z.add 0 history) as h.\n entailer!!.\nforward.  (* return d+i; *)\nsimpl.\n set (j:= Int.max_signed / 4) in *; compute in j; subst j.\n forget (fold_right Z.add 0 history) as h.\n entailer!!.\nExists (2 * fold_right Z.add 0 history + i).\nsimpl;\nentailer!!.\nrewrite Z.mul_add_distr_l, Z.add_comm.\nunfold withspacer; simpl.\nentailer!!.\nQed.\n\nLemma split_object_methods:\n  forall instance m, \n    object_methods instance m |-- object_methods instance m * object_methods instance m.\nProof.\nintros.\nunfold object_methods.\nIntros sh reset twiddle.\n\nExists (fst (slice.cleave sh)) reset twiddle.\nExists (snd (slice.cleave sh)) reset twiddle.\nrewrite (split_func_ptr' (reset_spec instance) reset) at 1.\nrewrite (split_func_ptr' (twiddle_spec instance) twiddle) at 1.\nentailer!!.\nsplit.\napply slice.cleave_readable1; auto.\napply slice.cleave_readable2; auto.\nrewrite (data_at_share_join (fst (slice.cleave sh)) (snd (slice.cleave sh)) sh).\nauto.\napply slice.cleave_join.\nQed.\n\nLemma body_make_foo: semax_body Vprog Gprog f_make_foo make_foo_spec.\nProof.\nunfold make_foo_spec.\nstart_function.\nforward_call (Tstruct _foo_object noattr, gv).\nIntros p.\nforward_if\n  (PROP ( )\n   LOCAL (temp _p p; gvars gv)\n   SEP (mem_mgr gv;\n          malloc_token Ews (Tstruct _foo_object noattr) p;\n          data_at_ Ews (Tstruct _foo_object noattr) p;\n          object_methods foo_invariant (gv _foo_methods))).\n*\nchange (EqDec_val p nullval) with (eq_dec p nullval).\nif_tac; entailer!!.\n*\nforward_call 1.\ncontradiction.\n*\nrewrite if_false by auto.\nIntros.\nforward.  (*  /*skip*/;  *)\nentailer!!.\n*\nunfold data_at_, field_at_, default_val; simpl.\nforward. (* p->mtable = &foo_methods; *)\nforward. (* p->data = 0; *)\nforward. (* return (struct object * ) p; *)\nExists p.\nunfold object_mpred.\nExists foo_invariant (gv _foo_methods).\nsep_apply (split_object_methods foo_invariant (gv _foo_methods)).\nunfold foo_invariant at 4.\nentailer!!.\nsimpl.\nunfold_data_at (field_at _ _ nil _ p).\ncancel.\nunfold withspacer; simpl.\nrewrite !field_at_data_at.\nsimpl.\napply derives_refl'.\nrewrite <- ?sepcon_assoc. (* needed if Archi.ptr64=true *)\nrewrite !field_compatible_field_address; auto with field_compatible.\nclear - H.\n(* TODO: simplify the following proof. *)\ndestruct p; try contradiction.\ndestruct H as [AL SZ].\nrepeat split; auto.\nsimpl in *.  unfold sizeof in *; simpl in *; lia.\neapply align_compatible_rec_Tstruct; [reflexivity.. |].\nsimpl co_members; intros.\nsimpl in H.\nif_tac in H; [| inv H].\ninv H. inv H0.\neapply align_compatible_rec_by_value.\nreflexivity.\nrewrite Z.add_0_r.\nsimpl.\nunfold natural_alignment in AL.\neapply Z.divide_trans; [ | apply AL].\napply prove_Zdivide.\nreflexivity.\nleft; auto.\nQed.\n\n\nLemma make_object_methods:\n  forall sh instance reset twiddle mtable,\n  readable_share sh ->\n  func_ptr' (reset_spec instance) reset *\n  func_ptr' (twiddle_spec instance) twiddle *\n  data_at sh (Tstruct _methods noattr) (reset, twiddle) mtable\n  |-- object_methods instance mtable.\nProof.\n  intros.\n  unfold object_methods.\n  Exists sh reset twiddle.\n  entailer!!.\nQed.\n\nLtac method_call witness hist' result :=\nrepeat apply seq_assoc1;\nmatch goal with \n   |- semax _ (PROPx _ (LOCALx ?Q (SEPx ?R))) \n            (Ssequence (Sset ?mt (Efield (Ederef (Etempvar ?x _)  _) _ _))\n                 _) _  =>\n    match Q with context [temp ?x ?x'] =>\n     match R with context [object_mpred _ x'] =>\n          let instance := fresh \"instance\" in let mtable := fresh \"mtable\" in\n          unfold object_mpred; Intros instance mtable;\n          forward;\n          unfold object_methods at 1; \n          let sh := fresh \"sh\" in let r := fresh \"r\" in let t := fresh \"t\" in\n          Intros sh r t;\n          forward;\n          forward_call witness;\n          [ .. | try Intros result;\n                  sep_apply (make_object_methods sh instance r t mtable); [ auto .. | ];\n                  sep_apply (object_mpred_i hist' x' instance mtable);\n                  deadvars; try clear dependent sh; try clear r; try clear t\n           ]\n    end end\nend.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nsep_apply (create_mem_mgr gv).\n(* assert_gvar _foo_methods. (* TODO: this is needed for a field_compatible later on *) *)\nfold noattr cc_default.\n(* 0. This part should be handled automatically by start_function *)\ngather_SEP (mapsto _ _ _ _) (data_at _ _ _ _);\nreplace_SEP 0 (data_at Ews (Tstruct _methods noattr) \n   (gv _foo_reset, gv _foo_twiddle) (gv _foo_methods)). {\n  entailer!.\n  unfold_data_at (data_at _ (Tstruct _methods _) _ (gv _foo_methods)).\n  rewrite <- mapsto_field_at with (gfs := [StructField _twiddle]) (v:= (gv _foo_twiddle))\n  by  auto with field_compatible.\n  rewrite field_at_data_at.  rewrite !field_compatible_field_address by auto with field_compatible.\n  rewrite !isptr_offset_val_zero by auto.\n  cancel.\n}\n\n(* 1. Prove that [mtable] is a proper method-table for foo-objects *)\n\nmake_func_ptr _foo_twiddle.\nmake_func_ptr _foo_reset.\nsep_apply (make_object_methods Ews foo_invariant(gv _foo_reset) (gv _foo_twiddle) (gv _foo_methods)); auto.\n\n(* 2. Build an instance of class [foo], called [p] *)\nforward_call (* p = make_foo(); *)\n        gv.\nIntros p.\nassert_PROP (p<>Vundef) by entailer!.\n(* Illustration of an alternate method to prove the method calls.\n   Method 1:  comment out lines AA and BB and the entire range CC-DD.\n   Method 2:  comment out lines AA-BB, inclusive.\n*)\n\n(* AA *) try (tryif \n  (method_call (p, @nil Z) (@nil Z) whatever;\n   method_call (p, 3, @nil Z) [3%Z] i;\n     [simpl; computable | ])\n(* BB *)  then fail else fail 99)\n  .\n\n(* CC *)\n(* 4. first method-call *)\nunfold object_mpred.\nIntros instance mtable0.\nforward. (*  mtable = p->mtable; *)\nunfold object_methods at 1.\nIntros sh r0 t0.\nforward. (* p_reset = mtable->reset; *)\nforward_call (* p_reset(p); *)\n      (p, @nil Z).\n(* Finish the method-call by regathering the object p back together *)\nsep_apply (make_object_methods sh instance r0 t0 mtable0); auto.\nsep_apply (object_mpred_i [] p instance mtable0).\ndeadvars!. clear.\n\n(* 5. second method-call *)\nunfold object_mpred.\nIntros instance mtable0.\nforward.  (* mtable = p->mtable; *)\nunfold object_methods at 1.\nIntros sh r0 t0.\nforward.   (* p_twiddle = mtable->twiddle; *)\nassert_PROP (p<>Vundef) by entailer!.\nforward_call (* i = p_twiddle(p,3); *)\n      (p, 3, @nil Z).\n  simpl. computable.\nIntros i.\nsimpl in H0.\nsep_apply (make_object_methods sh instance r0 t0 mtable0); auto.\nsep_apply (object_mpred_i [3] p instance mtable0).\ndeadvars!.\nsimpl in H1.\n\n(* DD *)\n\n(* 6. return *)\nforward.  (* return i; *)\nExists i; entailer!!.\nQed.\n\n\n\n\n\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs64/verif_object.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21437849548718665}}
{"text": "Require Import Axioms.\n\nRequire Import effect_semantics.\n\nRequire Import pos.\nRequire Import compcert_linking.\n\nRequire Import ssreflect ssrbool ssrnat ssrfun seq fintype.\nSet Implicit Arguments.\n\nRequire Import AST. (*for ident*)\nRequire Import Values. \nRequire Import Globalenvs. \n\nSection linkingLemmas.\n\nImport Linker.\nImport Modsem.\n\nVariable N : pos.\nVariable cores : 'I_N -> Modsem.t. \nVariable fun_tbl : ident -> option 'I_N.\nVariable my_ge : ge_ty.\n\nLet linker := effsem N cores fun_tbl.\n\nLemma upd_upd (st : Linker.t N cores) c c' :\n  updCore (updCore st c) c' = updCore st c'.\nProof. \nrewrite /updCore /updStack /=; f_equal.\nmove: (updCore_obligation_1 _ _); simpl.\nrewrite collection.COL.theory.unbumpbump=> w2.\nby have ->: w2 = updCore_obligation_1 _ _ by apply: proof_irr.\nQed.\n\nLemma step_STEP {U st1 m1 c1' m1'} : \n  let: c1 := peekCore st1 in\n  effect_semantics.effstep \n    (sem (cores (Core.i c1))) \n    (ge (cores (Core.i c1))) U (Core.c c1) m1 c1' m1' -> \n  effect_semantics.effstep linker my_ge \n  U st1 m1 (updCore st1 (Core.upd c1 c1')) m1'.\nProof.\nmove=> STEP; move: (@effstep_corestep _ _ _ _ _ _ _ _ _ STEP)=> STEP'; split.\nby left; exists c1'; split.\nby move=> ?; exists c1'; split.\nby move=> H b ofs; case: H; rewrite/LinkerSem.corestep0; exists c1'; split.\nQed.\n\nLemma stepN_STEPN {U st1 m1 c1' m1' n} :\n  let: c1 := peekCore st1 in\n  effect_semantics.effstepN \n    (sem (cores (Core.i c1))) \n    (ge (cores (Core.i c1))) n U (Core.c c1) m1 c1' m1' -> \n  effect_semantics.effstepN linker my_ge \n    n U st1 m1 (updCore st1 (Core.upd c1 c1')) m1'.\nProof.\nmove: st1 c1' m1 U; elim: n.\nmove=> st1 c1' m1 U /= [][] <- <- <-; split=> //; f_equal. \n{ have H: Core.upd (peekCore st1) (Core.c (peekCore st1))\n        = peekCore st1.\n  { by clear; rewrite /Core.upd; case: (peekCore st1). }\n  by rewrite H LinkerSem.updPeekCore.\n}\nmove=> n IH st1 c1' m1 U /= => [][]c1'' []m1'' []U1 []U2 []B []C D.\nexists (updCore st1 (Core.upd (peekCore st1) c1'')), m1'',U1,U2; split.\nby apply: (step_STEP B).\nhave H: Core.i (peekCore st1)\n      = Core.i (peekCore (updCore st1 (Core.upd (peekCore st1) c1''))).\n{ admit. }\nadmit.\n(*move: (IH (updCore st1 (Core.upd (peekCore st1) c1'')) c1' m1'' U2).\nby rewrite upd_upd=> H; split=> //; move: H; apply; apply: C.*)\nQed.\n\nLemma stepPLUS_STEPPLUS {U st1 m1 c1' m1'} :\n  let: c1 := peekCore st1 in\n  effect_semantics.effstep_plus \n    (sem (cores (Core.i c1))) \n    (ge (cores (Core.i c1))) U (Core.c c1) m1 c1' m1' -> \n  effect_semantics.effstep_plus linker my_ge \n  U st1 m1 (updCore st1 (Core.upd c1 c1')) m1'.\nProof. by rewrite/effstep_plus=> [][]n; move/stepN_STEPN=> B; exists n. Qed.\n\nLemma stepSTAR_STEPSTAR {U st1 m1 c1' m1'} :\n  let: c1 := peekCore st1 in\n  effect_semantics.effstep_star\n    (sem (cores (Core.i c1))) \n    (ge (cores (Core.i c1))) U (Core.c c1) m1 c1' m1' -> \n  effect_semantics.effstep_star linker my_ge \n  U st1 m1 (updCore st1 (Core.upd c1 c1')) m1'.\nProof. by rewrite/effstep_star=> [][]n; move/stepN_STEPN=> B; exists n. Qed.\n\nEnd linkingLemmas.\n", "meta": {"author": "nickgian", "repo": "compcomp1", "sha": "eced26b32afb09e81467ed7b51f548d3b642f8f2", "save_path": "github-repos/coq/nickgian-compcomp1", "path": "github-repos/coq/nickgian-compcomp1/compcomp1-eced26b32afb09e81467ed7b51f548d3b642f8f2/linking/compcert_linking_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306515, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21437848949700158}}
{"text": "From aneris.examples.consensus Require Import paxos_prelude.\nImport RecordSetNotations.\n\nSection paxos_proposer.\n  Context `{!anerisG (Paxos_model params) Σ}.\n  Context `{!paxosG Σ params}.\n\n  Lemma recv_promises_spec p h (n : nat) (b : Ballot) :\n    p ∈ Proposers →\n    {{{ inv paxosN paxos_inv ∗ p ⤇ proposer_si ∗\n        h ↪[ip_of_address p] (mkSocket (Some p) true) }}}\n      recv_promises int_serializer #(LitSocket h) #n #b\n      @[ip_of_address p]\n    {{{ vp (promises : gset (option (Ballot * Value))) (senders : gset Acceptor),\n        RET vp;\n        h ↪[ip_of_address p] (mkSocket (Some p) true) ∗\n        ⌜is_set promises vp⌝ ∗\n        ⌜size senders = n⌝ ∗\n        (∀ a, ⌜a ∈ senders⌝ -∗\n               ∃ mv, ⌜mv ∈ promises⌝ ∗ msgs_elem_of (msg1b a b mv)) ∗\n        (* TODO: better spec/implementation? - this is a bit silly *)\n        (∀ mv, ⌜mv ∈ promises⌝ →\n               ∃ a, ⌜a ∈ senders⌝ ∗ msgs_elem_of (msg1b a b mv)) }}}.\n  Proof.\n    iIntros (? Φ) \"(#Hinv & #Hp_si & Hh) HΦ\". rewrite /recv_promises.\n    wp_pures.\n    wp_apply (wp_set_empty (option (Ballot * Value))); [done|].\n    iIntros (vp Hvp). wp_alloc lp as \"Hlp\".\n    wp_pures.\n    wp_apply (wp_set_empty Acceptor); [done|].\n    iIntros (vs Hvs). wp_alloc ls as \"Hls\".\n    do 4 wp_pure _.\n    (* loop invariant *)\n    iAssert (\n        ∃ (promises : gset (option (Ballot * Value))) (senders : gset Acceptor) vp vs,\n          lp ↦[ip_of_address p] vp ∗ ls ↦[ip_of_address p] vs ∗\n             ⌜is_set promises vp⌝ ∗ ⌜is_set senders vs⌝ ∗\n             (∀ a, ⌜a ∈ senders⌝ -∗\n                    ∃ mv, ⌜mv ∈ promises⌝ ∗ msgs_elem_of (msg1b a b mv)) ∗\n             (∀ mv, ⌜mv ∈ promises⌝ →\n               ∃ a, ⌜a ∈ senders⌝ ∗ msgs_elem_of (msg1b a b mv)))%I\n      with \"[Hlp Hls]\" as \"Hloop\".\n    { iExists ∅, ∅, _, _. iFrame \"∗%\". iSplit; iIntros (? []%elem_of_empty). }\n    clear Hvp Hvs vs vp. wp_pure _.\n    iLöb as \"IH\".\n    iDestruct \"Hloop\" as (promises senders vp vs) \"(Hlp & Hls & %Hvp & %Hvs & Hincl & Hacc)\".\n    wp_pures.\n    wp_load.\n    wp_apply wp_set_cardinal; [done|]; iIntros \"_\".\n    wp_op. case_bool_decide as Heq; wp_pures.\n    { wp_load. iApply \"HΦ\". iFrame. apply Nat2Z.inj in Heq. by iFrame \"%\". }\n    wp_bind (ReceiveFrom _).\n    iInv (paxosN) as (δ) \"(>Hfrag & >Hmauth & >Hbal & >Hval & Hmcoh & >HbI)\"\n                         \"Hclose\".\n    iDestruct \"Hmcoh\" as \">Hmcoh\".\n    iDestruct \"Hmcoh\" as (F Ts) \"(Has & Hps & -> & %HM)\".\n    iDestruct (big_sepS_delete _ _ p with \"Hps\") as \"[[% Hp] Hps]\"; [done|].\n    wp_apply (aneris_wp_pers_receivefrom with \"[$Hh $Hp $Hp_si]\"); [done..|].\n    iIntros (m) \"(Hh & Hp & Hm)\".\n    iMod (\"Hclose\" with \"[-Hh Hm Hlp Hls Hincl Hacc HΦ]\") as \"_\".\n    { iModIntro. iExists _. iFrame.\n      iExists _, _. iFrame (HM) \"Has\".\n      iSplit; [|done].\n      iDestruct (big_sepS_insert _ _ p with \"[Hp $Hps]\")\n        as \"Hps\"; [set_solver|eauto|].\n      rewrite -union_difference_singleton_L //. }\n    rewrite /proposer_si.\n    iDestruct \"Hm\" as (?? mval Hser) \"(-> & Hm)\".\n    iModIntro. wp_apply wp_unSOME; [done|]; iIntros \"_\".\n    wp_pures.\n    wp_apply (s_deser_spec proposer_serialization); [done|]; iIntros \"_\".\n    wp_pures.\n    case_bool_decide; wp_if; last first.\n    { wp_seq. wp_apply (\"IH\" with \"Hh HΦ [Hlp Hls Hincl Hacc]\").\n      iExists _, _, _, _. auto with iFrame. }\n    simplify_eq.\n    wp_load.\n    wp_apply (wp_set_add $! Hvs). iIntros (vs' ?).\n    wp_store. wp_load.\n    wp_apply (wp_set_add $! Hvp).\n    iIntros (vp' Hvp'). wp_store.\n    wp_apply (\"IH\" with \"Hh HΦ\").\n    iExists (_ ∪ _), (_ ∪ _), _, _. iFrame \"Hlp Hls\".\n    do 2 (iSplit; [done|]).\n    iSplit; last first.\n    { iIntros (mv). rewrite elem_of_union elem_of_singleton. iIntros ([-> | Hin]).\n      - iExists _. iFrame. iPureIntro; set_solver.\n      - iDestruct (\"Hacc\" $! mv Hin) as (a') \"[% ?]\".\n        iExists a'. iFrame. iPureIntro; set_solver. }\n    iIntros (a').\n    rewrite elem_of_union elem_of_singleton.\n    iIntros ([-> | ?]); last first.\n    { iDestruct (\"Hincl\" $! a' with \"[//]\") as (mv') \"[% H]\".\n      iExists mv'. iFrame. iPureIntro; set_solver. }\n    iExists _. iFrame. iPureIntro; set_solver.\n  Qed.\n\n  Lemma find_max_promise_spec (lp : val)\n        (promises : gset (option (Ballot * Value))) ip :\n    is_set promises lp →\n    {{{ True }}}\n      find_max_promise lp @[ip]\n    {{{ v, RET v;\n        (⌜v = NONEV⌝ ∗ ⌜set_Forall (λ p, p = None) promises⌝) ∨\n        (∃ (b : Ballot) (val : Value),\n            ⌜Some (b, val) ∈ promises⌝ ∗\n            ⌜v = SOMEV ($b, $val)⌝ ∗\n            ⌜set_Forall (λ p, if p is Some (b', v')\n                              then b ≥ b' else True) promises⌝) }}}.\n  Proof.\n    iIntros (? Φ) \"_ HΦ\". rewrite /find_max_promise.\n    wp_pures.\n    wp_apply (wp_set_foldl (A := option (Ballot * Value))\n                (λ X v, (⌜v = NONEV⌝ ∗ ⌜set_Forall (λ p, p = None) X⌝) ∨\n                        (∃ (b : Ballot) (val : Value),\n                            ⌜Some (b, val) ∈ X⌝ ∗\n                            ⌜v = SOMEV ($b, $val)⌝ ∗\n                            ⌜set_Forall (λ p, if p is Some (b', v')\n                                              then b ≥ b' else True) X⌝))%I\n                (λ _, True%I) (λ _, True%I)).\n    { iIntros ([[b v]|] acc X) \"!#\";\n        iIntros (Ψ) \"[[[-> %Hall] | (% & % & %Hin & -> & %Hall)] _] HΨ\".\n      - wp_pures. iApply \"HΨ\". iSplit; [|done]. iRight.\n        iExists b, v. iPureIntro.\n        split; [by apply elem_of_union_r, elem_of_singleton|].\n        split; [done|].\n        apply set_Forall_union.\n        { apply (set_Forall_impl _ _ _ Hall). by intros ? ->. }\n        apply set_Forall_singleton. lia.\n      - wp_pures. case_bool_decide; wp_if.\n        + iApply \"HΨ\". iPureIntro.\n          split; [|done]. right.\n          do 2 eexists.\n          split; [apply elem_of_union_l, Hin|].\n          split; [done|].\n          apply set_Forall_union; [done|].\n          apply set_Forall_singleton. lia.\n        + iApply \"HΨ\". iPureIntro.\n          split; [|done]. right.\n          do 2 eexists.\n          split; [by apply elem_of_union_r, elem_of_singleton|].\n          split; [done|].\n          apply set_Forall_union; [|apply set_Forall_singleton; lia].\n          apply (set_Forall_impl _ _ _ Hall).\n          intros [[]|]; [|done]. lia.\n      - wp_pures. iApply \"HΨ\". iPureIntro.\n        split; [|done]. left.\n        split; [done|].\n        apply set_Forall_union; [done|].\n        by apply set_Forall_singleton.\n      - wp_pures. iApply \"HΨ\". iPureIntro.\n        split; [|done]. right.\n        do 2 eexists.\n        split; [by apply elem_of_union_l, Hin|].\n        split; [done|].\n        apply set_Forall_union; [done|].\n        by apply set_Forall_singleton. }\n    { iFrame \"%\". rewrite big_opS_unit; eauto. }\n    iIntros (?) \"[H _]\". by iApply \"HΦ\".\n  Qed.\n\n  (* Definition bal (n : nat) (p : nat) := n * ProposersN + p. *)\n\n  Lemma proposer_spec av h b (p : Proposer) (z : Value) :\n    is_set Acceptors av →\n    inv paxosN paxos_inv -∗\n    ([∗ set] a ∈ Acceptors, a ⤇ acceptor_si) -∗\n    (`p) ⤇ proposer_si -∗\n    h ↪[ip_of_address (`p)] (mkSocket (Some (`p)) true) -∗\n    pending b -∗\n    WP proposer int_serializer av #(LitSocket h) #b #`z @[ip_of_address (`p)]\n    {{ _, ∃ v, msgs_elem_of (msg2a b v) ∗\n               h ↪[ip_of_address (`p)] (mkSocket (Some (`p)) true) }}.\n  Proof.\n    iIntros (?) \"#Hinv #HA_sis #Hp_si Hh Hb\".\n    rewrite /proposer.\n    wp_pures.\n    wp_apply (s_ser_spec (acceptor_serialization)).\n    { iPureIntro. apply serializable. }\n    iIntros (s) \"%Hser\".\n    (* send a phase 1a message to all acceptors, taking a step in the model for\n       each message. *)\n    wp_apply (wp_pers_sendto_all_take_step\n                True%I\n                (λ _, msgs_elem_of (msg1a _))\n                (λ _, True)%I\n                with \"[] [$Hh //]\"); [done|done|eassumption| |].\n    { iIntros \"!#\" (a ?) \"(_ & _ & %Ha)\".\n      set (m := {| m_sender := `p; m_destination := a; m_body := s |}).\n      iInv (paxosN) as (δ) \">(Hfrag & Hmauth & Hbal & Hval & Hmcoh & HbI)\" \"Hclose\".\n      iMod (msgs_update (msg1a b) with \"Hmauth\") as \"[Hmauth #Hm]\".\n      iModIntro.\n      iDestruct \"Hmcoh\" as (F Ts) \"(Has & Hps & -> & %HM)\".\n      iDestruct (big_sepS_delete _ _ (`p) with \"Hps\") as \"[[% Hp] Hps]\"; [auto|].\n      iDestruct (big_sepS_elem_of _ _ a with \"HA_sis\") as \"#Ha_si\"; [done|].\n      iExists _, _, _, _, δ, (δ <| msgs ::= λ ms, ms ∪ {[msg1a _]} |>).\n      iFrame \"#∗\".\n      iSplit.\n      { iPureIntro. right. constructor. }\n      iSplitR.\n      { iExists p. iSplit; [done|]. iLeft. iExists _. iFrame \"% #\". }\n      iIntros \"(Hp & Hfrag)\".\n      iMod (\"Hclose\" with \"[-]\"); [|done].\n      iModIntro. iExists _. iFrame.\n      iSplitR \"HbI\"; last first.\n      { iApply (ballot_inv_send_not2a with \"HbI\"). naive_solver. }\n      iExists (<[(`p) := {[m]} ∪ F (`p)]>F), _; simpl.\n      rewrite send_msg_notin; [|auto].\n      iFrame.\n      iDestruct (send_msg_combine with \"Hp Hps\") as \"$\"; [auto|].\n      iSplit; [done|].\n      iPureIntro.\n      apply messages_agree_add; [| |done].\n      { apply elem_of_union; auto. }\n      simpl. destruct_is_ser Hser.\n      by exists p, (a ↾ Ha). }\n    iIntros \"(_ & Hh & _ & Helem)\". wp_pures.\n    wp_apply (wp_set_cardinal with \"[//]\"); iIntros \"_\".\n    wp_pures.\n    replace #(_ + 1) with #(size Acceptors / 2 + 1)%nat; last first.\n    { do 2 f_equal. lia. }\n    wp_apply (recv_promises_spec with \"[$Hinv $Hp_si $Hh]\"); [auto|].\n    iIntros (vp promises senders) \"(Hh & %Hvp & %Hsize & #Hmsgs & #Hacc)\".\n    wp_pures.\n    (* find the maximum phase 1b message from the majority, if any *)\n    wp_apply (find_max_promise_spec _ promises with \"[//]\"); [done|].\n    iIntros (?) \"[(-> & %Hpromises) | (%b0 & %z' & %Hin &-> & %Hall)]\".\n    - (* no value was proposed by the majority *)\n      wp_pures.\n      iMod (pend_update_shot b z with \"Hb\") as \"#Hshot\".\n      wp_apply (s_ser_spec (acceptor_serialization)).\n      { iPureIntro. apply serializable. }\n      iIntros (s' Hser').\n      (* send phase 2a decision to all acceptors *)\n      wp_apply (wp_pers_sendto_all_take_step\n                  True%I (λ _, msgs_elem_of (msg2a b z)) (λ _, True)%I\n                  with \"[Hmsgs] [$Hh]\"); [done|done|eassumption| |].\n      { iIntros \"!#\" (a _) \"(_ & _ & %Ha)\".\n        iInv (paxosN) as (δ) \">(Hfrag & Hmauth & Hbal & Hval & Hmcoh & HbI)\" \"Hclose\".\n        iAssert (⌜∀ a, a ∈ senders →\n                       ∃ mv, mv ∈ promises ∧ msg1b a b mv ∈ δ.(msgs)⌝)%I\n          as \"%Hsenders\".\n        { iIntros (a' Ha').\n          iDestruct (\"Hmsgs\" $! a' Ha') as (mv) \"[% Hm]\".\n          iDestruct (msgs_elem_of_in with \"Hmauth Hm\") as %?. eauto. }\n        iMod (msgs_update (msg2a b z) with \"Hmauth\") as \"[Hmauth #Hm]\".\n        iModIntro.\n        iDestruct \"Hmcoh\" as (F Ts) \"(Has & Hps & -> & %HM)\".\n        iDestruct (big_sepS_delete _ _ (`p) with \"Hps\") as \"[[% Hp] Hps]\"; [auto|].\n        iDestruct (big_sepS_elem_of _ _ a with \"HA_sis\") as \"#Ha_si\"; [done|].\n        set (m := {| m_sender := `p; m_destination := a; m_body := s' |}).\n        (* this viewshift is used for all acceptors; here we destruct on whether\n           we're considering the first (the 2a message has not been recorded in\n           the model) or not. *)\n        destruct (decide (msg2a b z ∈ δ.(msgs))).\n        + iExists _, _, _, _, δ, δ.\n          iFrame \"Hfrag Hp Ha_si\".\n          iSplit; [auto|].\n          iSplitR.\n          { iExists p. iSplit; [done|]. iRight. iExists _, z. by iFrame \"Hm\". }\n          iIntros \"(Hp & Hfrag)\".\n          iMod (\"Hclose\" with \"[-]\") as \"_\"; [|auto].\n          iModIntro. iExists _. simpl.\n          assert ((msgs δ ∪ {[msg2a b z]}) = msgs δ) as -> by set_solver.\n          iFrame.\n          iExists (<[(`p) := {[m]} ∪ F (`p)]>F), _; iFrame.\n          rewrite send_msg_notin; [|auto]. iFrame.\n          iDestruct (send_msg_combine with \"Hp Hps\") as \"$\"; [auto|].\n          iSplit; [done|]. iPureIntro.\n          eapply messages_agree_duplicate; [done| |done].\n          destruct_is_ser Hser'. by exists p, (a ↾ Ha).\n        + iExists _, _, _, _, δ, (δ <| msgs ::= λ ms, ms ∪ {[msg2a _ z]} |>).\n          iAssert (⌜¬ (∃ z', msg2a b z' ∈ msgs δ)⌝)%I as \"%\".\n          { iIntros ([? Hz']).\n            iSpecialize (\"HbI\" $! _ _ Hz').\n            by iDestruct (shot_agree with \"Hshot HbI\") as %->. }\n          iDestruct (frag_st_rtc with \"Hfrag\") as %Hrtc.\n          iFrame \"Hfrag Hp Ha_si\".\n          iSplit.\n          { iPureIntro. right.\n            eapply (phase2a _ _ _ senders).\n            * done.\n            * apply majority_show_quorum. rewrite Hsize. lia.\n            * split.\n              - intros a' Ha'.\n                destruct (Hsenders a' Ha') as (mv &?&?).\n                exists (msg1b a' b mv).\n                rewrite !elem_of_PropSet. split; eauto.\n              - left.\n                rewrite set_equiv=> m'.\n                rewrite !elem_of_PropSet.\n                split; [|done].\n                intros ([Hin1 (? &?&?& Ha')] & a' & [? ?]); simplify_eq.\n                destruct (Hsenders a' Ha') as (? & Hprom & Hin2).\n                (* N.B.: here we are explicitlty using a pure property of the\n                   model to obtain the contradiction! *)\n                specialize (msg1b_agree _ _ _ _ _ Hrtc Hin1 Hin2).\n                rewrite (Hpromises _ Hprom).\n                done. }\n          iSplit.\n          { iExists p. iSplit; [done|]. iRight. iExists _, z. by iFrame \"Hm\". }\n          iIntros \"[Hp Hfrag]\".\n          iMod (\"Hclose\" with \"[-]\") as \"_\"; [|auto].\n          iModIntro. iExists _. iFrame \"Hfrag Hmauth Hbal Hval\".\n          iSplitR \"HbI\"; last first.\n          { iIntros (??).\n            rewrite elem_of_union elem_of_singleton.\n            iIntros ([?|?]); by [iApply \"HbI\"|simplify_eq]. }\n          iExists (<[(`p) := {[m]} ∪ F (`p)]>F), _. simpl.\n          rewrite send_msg_notin; [|auto]. iFrame.\n          iDestruct (send_msg_combine with \"Hp Hps\") as \"$\"; [auto|].\n          iSplit; [done|].\n          iPureIntro.\n          apply messages_agree_add; [| |done].\n          { apply elem_of_union; auto. }\n          destruct_is_ser Hser'. by exists p, (a ↾ Ha). }\n      iIntros \"(_ & Hh & _ & H2a)\".\n      iExists _. iFrame.\n      destruct Acceptors_choose as [a ?].\n      by iApply (big_sepS_elem_of _ _ a with \"H2a\").\n    - (* a value has already been proposed *)\n      wp_pures.\n      wp_apply (s_ser_spec (acceptor_serialization)).\n      { iPureIntro. apply serializable. }\n      iIntros (s' Hser').\n      iMod (pend_update_shot b z' with \"Hb\") as \"#Hshot\".\n      wp_apply (wp_pers_sendto_all_take_step\n                  True%I (λ _, msgs_elem_of (msg2a b z')) (λ _, True)%I\n                  with \"[Hmsgs] [$Hh]\"); [done|done|eassumption| |].\n      { iIntros \"!#\" (a _) \"(_ & _ & %Ha)\".\n        iInv (paxosN) as (δ) \">(Hfrag & Hmauth & Hbal & Hval & Hmcoh & HbI)\"\n                                 \"Hclose\".\n        iAssert (⌜∀ a, a ∈ senders →\n                       ∃ mv, mv ∈ promises ∧ msg1b a b mv ∈ δ.(msgs)⌝)%I as \"%Hsenders\".\n        { iIntros (a' Ha').\n          iDestruct (\"Hmsgs\" $! a' Ha') as (mv) \"[% Hm']\".\n          iDestruct (msgs_elem_of_in with \"Hmauth Hm'\") as %?. eauto. }\n        iAssert (⌜∀ mv, mv ∈ promises →\n                        ∃ a, a ∈ senders ∧ msg1b a b mv ∈ δ.(msgs)⌝)%I as \"%Hpromises\".\n        { iIntros (mv Hmv).\n          iDestruct (\"Hacc\" $! mv Hmv) as (a') \"[% Hm']\".\n          iDestruct (msgs_elem_of_in with \"Hmauth Hm'\") as %?. eauto. }\n        iMod (msgs_update (msg2a b z') with \"Hmauth\") as \"[Hmauth #Hm]\".\n        iModIntro.\n        iDestruct \"Hmcoh\" as (F Ts) \"(Has & Hps & -> & %HM)\".\n        iDestruct (big_sepS_delete _ _ (`p) with \"Hps\") as \"[[% Hp] Hps]\"; [auto|].\n        iDestruct (big_sepS_elem_of _ _ a with \"HA_sis\") as \"#Ha_si\"; [done|].\n        set (m := {| m_sender := `p; m_destination := a; m_body := s' |}).\n        destruct (decide ((msg2a b z') ∈ δ.(msgs))).\n        + iExists _, _, _, _, δ, δ.\n          iFrame \"Hfrag Hp Ha_si\".\n          iSplit; [auto|].\n          iSplit.\n          { iExists p. iSplit; [done|]. iRight. iExists _, _. by iFrame \"Hm\". }\n          iIntros \"[Hp Hfrag]\".\n          iMod (\"Hclose\" with \"[-]\") as \"_\"; [|auto].\n          iModIntro. iExists _. simpl.\n          assert ((msgs δ ∪ {[msg2a b z']}) = msgs δ) as -> by set_solver.\n          iFrame. iExists (<[(`p) := {[m]} ∪ F (`p)]>F), _.\n          rewrite send_msg_notin; [|auto]. iFrame.\n          iDestruct (send_msg_combine with \"Hp Hps\") as \"$\"; [auto|].\n          iSplit; [done|]. iPureIntro.\n          eapply messages_agree_duplicate; [done| |done].\n          destruct_is_ser Hser'. by exists p, (a ↾ Ha).\n        + iExists _, _, _, _, δ, (δ <| msgs ::= λ ms, ms ∪ {[msg2a b z']} |>).\n          iAssert (⌜¬ (∃ z', msg2a b z' ∈ msgs δ)⌝)%I as \"%\".\n          { iIntros ([? Hz']).\n            iSpecialize (\"HbI\" $! _ _ Hz').\n            by iDestruct (shot_agree with \"Hshot HbI\") as %->. }\n          iDestruct (frag_st_rtc with \"Hfrag\") as %Hrtc.\n          iFrame \"Hfrag Hp Ha_si\".\n          iSplit.\n          { iPureIntro. right.\n            eapply (phase2a _ z' _ senders).\n            * done.\n            * apply majority_show_quorum. rewrite Hsize. lia.\n            * split.\n              - intros a' Ha'.\n                destruct (Hsenders a' Ha') as (mv &?&?).\n                exists (msg1b a' b mv).\n                rewrite !elem_of_PropSet. split; eauto.\n              - right.\n                destruct (Hpromises _ Hin) as (a' & Ha' & Hm).\n                eexists _; exists a', b0.\n                repeat split; eauto.\n                intros m' ((Hin1 &?&?&?& Hin') & ? & ([]&?)); simplify_eq.\n                do 3 eexists. split; [done|].\n                destruct (Hsenders _ Hin') as (mv & Hmv & Hin2).\n                specialize (Hall _ Hmv).\n                (* N.B.: here we are explicitlty using a pure property of the\n                   model to finish the proof!  *)\n                specialize (msg1b_agree _ _ _ _ _ Hrtc Hin1 Hin2) as ?.\n                simplify_eq. done. }\n          iSplitR.\n          { iExists p. iSplit; [done|]. iRight. iExists _, z'. by iFrame \"Hm\". }\n          iIntros \"[Hp Hfrag]\".\n          iMod (\"Hclose\" with \"[-]\") as \"_\"; [|auto].\n          iModIntro. iExists _. iFrame.\n          iSplitR \"HbI\"; last first.\n          { iIntros (??).\n            rewrite elem_of_union elem_of_singleton.\n            iIntros ([?|?]); by [iApply \"HbI\"|simplify_eq]. }\n          iExists (<[(`p) := {[m]} ∪ F (`p)]>F), _; simpl.\n          rewrite send_msg_notin; [|auto]. iFrame.\n          iDestruct (send_msg_combine with \"Hp Hps\") as \"$\"; [auto|].\n          iSplit; [done|].\n          iPureIntro.\n          apply messages_agree_add; [| |done].\n          { apply elem_of_union; auto. }\n          destruct_is_ser Hser'. by exists p, (a ↾ Ha). }\n      iIntros \"(_ & Hh & _ & H2a)\".\n      iExists _. iFrame.\n      destruct Acceptors_choose as [a ?].\n      by iApply (big_sepS_elem_of _ _ a with \"H2a\").\n  Qed.\n\n  Lemma proposer'_spec av i (p : Proposer) (z : Value) :\n    i < size Proposers →             \n    is_set Acceptors av →\n    inv paxosN paxos_inv -∗\n    ([∗ set] a ∈ Acceptors, a ⤇ acceptor_si) -∗\n    free_ports (ip_of_address (`p)) {[port_of_address (`p)]} -∗\n    (`p) ⤇ proposer_si -∗\n    pending_class i 0 -∗\n    WP proposer' int_serializer av #(`p) #i #(size Proposers) #`z\n       @[ip_of_address (`p)] {{ _, True }}.\n  Proof.\n    iIntros (??) \"#Hinv #Has Hport #Hp Hi\". rewrite /proposer'.\n    wp_pures.\n    wp_socket sh as \"Hskt\".\n    wp_pures.\n    wp_socketbind.\n    wp_alloc l as \"Hl\".\n    do 4 wp_pure _.\n    (* loop invariant *)\n    iAssert (∃ c, pending_class i c ∗ l ↦[ip_of_address (`p)] #c)%I\n      with \"[Hi Hl]\" as \"Hloop\".\n    { iExists 0. replace (#0%nat) with (#0) by f_equal. iFrame. }\n    wp_pure _.\n    iLöb as \"IH\".\n    iDestruct \"Hloop\" as (b) \"(Hi & Hl)\".\n    wp_pures.\n    wp_load.\n    wp_pures.\n    iDestruct (pending_pend_split with \"Hi\") as \"[Hi Hpend]\"; [done|].                             \n    replace (#(b * size Proposers + i)) with (#(b * size Proposers + i)%nat)\n      by (do 2 f_equal; lia).\n    wp_bind (proposer _ _ _ _ _)%E.\n    wp_apply aneris_wp_wand_r. iSplitL \"Hpend Hskt\".\n    { by wp_apply (proposer_spec with \"Hinv Has Hp Hskt Hpend\"). }\n    iIntros (?) \"(% & #? & Hskt)\".\n    wp_seq. wp_load. wp_op.\n    wp_store.\n    iApply (\"IH\" with \"Hskt [-]\").\n    iExists _. iFrame.\n    replace (#(b + 1)%nat) with (#(b + 1)) by (do 2 f_equal; lia).\n    done.\n  Qed.\n\nEnd paxos_proposer.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/consensus/paxos_proposer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21437848949700153}}
{"text": "Require Import List.\nRequire Import ZArith.\n\nRequire Import Utils.\nRequire Import Lattices.\nRequire Import CLattices.\nRequire Import Instr.\nRequire Import Memory.\nRequire Import AbstractCommon.\nRequire Import AbstractMachine.\nRequire Import NIAbstractMachine.\nRequire Import Concrete.\nRequire Import ConcreteMachine.\nRequire Import ConcreteExecutions.\nRequire Import Semantics.\nRequire Import Refinement.\nRequire Import RefinementAQA.\nRequire Import RefinementQAC.\nRequire Import RefinementAC.\nRequire TINI.\n\nOpen Scope Z_scope.\n\nSet Implicit Arguments.\n\n\nSection NI.\n\nContext {T: Type}\n        {Latt: JoinSemiLattice T}\n        {CLatt: ConcreteLattice T}.\n\nVariable cblock : FaultRoutine.block.\nHypothesis stamp_cblock : Mem.stamp cblock = Kernel.\n\nVariable ctable_impl : list CSysCallImpl.\n\nLet faultHandler := FaultRoutine.faultHandler _ QuasiAbstractMachine.fetch_rule.\nLet ctable := build_syscall_table (Z.of_nat (length faultHandler)) ctable_impl.\n\nContext {WFCLatt: WfConcreteLattice cblock ctable T Latt CLatt}.\n\nVariable atable : ASysTable T.\nHypothesis Hatable : parametric_asystable atable.\nHypothesis Hctable_impl_correct : ctable_impl_correct cblock atable ctable_impl faultHandler.\nHypothesis table_syscall_lowstep : forall o, syscall_lowstep o atable.\nHypothesis table_systable_inv : systable_inv atable.\n\nInductive concrete_i_equiv (o : T) :\n  concrete_init_data -> concrete_init_data -> Prop :=\n  | ci_equiv : forall ai1 ai2 ci1 ci2\n                      (EQ : abstract_i_equiv o ai1 ai2)\n                      (MATCH1 : ac_match_initial_data cblock QuasiAbstractMachine.fetch_rule ai1 ci1)\n                      (MATCH2 : ac_match_initial_data cblock QuasiAbstractMachine.fetch_rule ai2 ci2),\n                 concrete_i_equiv o ci1 ci2.\n\nInstance CMObservation : TINI.Observation (tini_concrete_machine cblock ctable_impl) (Event T) := {\n  out e := match e with\n             | CEInt (z, t) m => EInt (z, valToLab t m)\n           end;\n  e_low := fun o e => @TINI.e_low _ _ (AMObservation atable) o e;\n  e_low_dec := fun o e => TINI.e_low_dec o e;\n  i_equiv := concrete_i_equiv\n}.\n\nLemma ac_low_compatible :\n  forall (o : T)\n         (e1 : event (abstract_machine atable))\n         (e2 : CEvent),\n    ref_match_events (@abstract_concrete_ref _ _ _ cblock stamp_cblock\n                                             ctable_impl\n                                             WFCLatt\n                                             atable Hatable Hctable_impl_correct) e1 e2 ->\n    (TINI.e_low o (TINI.out e1)\n       <-> TINI.e_low o (@TINI.out _ _ CMObservation e2)).\nProof.\n  simpl.\n  intros o [[x xl]] [[x' xt] m] H; simpl.\n  inv H. unfold pcatom_labToVal in ATOMS. simpl in ATOMS.\n  destruct ATOMS as [? TAG]. subst x'.\n  assert (valToLab xt m = xl) by (eapply labToVal_valToLab_id; eauto).\n  subst. reflexivity.\nQed.\n\nLemma concrete_equiv_abstract_equiv :\n  forall o ci1 ci2,\n    concrete_i_equiv o ci1 ci2 ->\n    exists ai1 ai2,\n      abstract_i_equiv o ai1 ai2 /\\\n      ac_match_initial_data cblock QuasiAbstractMachine.fetch_rule ai1 ci1 /\\\n      ac_match_initial_data cblock QuasiAbstractMachine.fetch_rule ai2 ci2.\nProof.\n  intros o ci1 ci2 EQ.\n  inv EQ. eauto.\nQed.\n\nLemma ac_match_events_equiv :\n  forall o e11 e12 e21 e22\n         (EQ : @TINI.a_equiv (abstract_machine atable) _ _ o (E e11) (E e12))\n         (MATCH1 : ref_match_events (abstract_concrete_ref stamp_cblock Hatable Hctable_impl_correct) e11 e21)\n         (MATCH2 : ref_match_events (abstract_concrete_ref stamp_cblock Hatable Hctable_impl_correct) e12 e22),\n    @TINI.a_equiv (tini_concrete_machine cblock ctable_impl) _ _ o (E e21) (E e22).\nProof.\n  simpl.\n  intros o [[x1 xl1]] [[x2 xl2]] [[x1' xt1] m1] [[x2' xt2] m2].\n  intros.\n  inv EQ; inv MATCH1; inv MATCH2;\n  repeat match goal with\n           | ATOMS : pcatom_labToVal _ _ _ |- _ =>\n             unfold pcatom_labToVal in ATOMS;\n             simpl in ATOMS; destruct ATOMS; subst\n           | H : TINI.out _ = TINI.out _ |- _ =>\n             simpl in H; inv H\n           | H : TINI.e_low _ _ |- _ =>\n             simpl in H\n         end;\n  intuition; repeat subst;\n  [> once (constructor; solve [simpl; eauto;\n                        repeat match goal with\n                               | H : labToVal _ _ _ |- _ =>\n                                 eapply labToVal_valToLab_id in H; eauto; rewrite H\n                             end;\n                      eauto]) ..].\nQed.\n\nLemma ac_tini_preservation_premises :\n  tini_preservation_hypothesis\n    (abstract_concrete_ref stamp_cblock Hatable Hctable_impl_correct).\nProof.\n  intros o. exists o.\n  split. { apply ac_low_compatible. }\n  split. { apply concrete_equiv_abstract_equiv. }\n  apply ac_match_events_equiv.\nQed.\n\nLemma concrete_noninterference :\n  TINI.tini CMObservation.\nProof.\n   exact (@refinement_preserves_noninterference\n          (abstract_machine atable) (tini_concrete_machine cblock ctable_impl)\n          _ _ _\n          (abstract_concrete_ref stamp_cblock Hatable Hctable_impl_correct)\n          (abstract_noninterference_short table_syscall_lowstep table_systable_inv)\n          ac_tini_preservation_premises).\nQed.\n\nEnd NI.\n", "meta": {"author": "micro-policies", "repo": "verified-ifc", "sha": "1ce5075b3a5580679feddb718d274d89fc7dd77f", "save_path": "github-repos/coq/micro-policies-verified-ifc", "path": "github-repos/coq/micro-policies-verified-ifc/verified-ifc-1ce5075b3a5580679feddb718d274d89fc7dd77f/extended_machines/NIConcreteMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.21434999696836624}}
{"text": "Require Import Coq.Strings.String.\nFrom Equations Require Import Equations.\nRequire Import PeanoNat.\n\nRequire Export SystemFR.EquivalentContext.\nRequire Export SystemFR.ErasedList.\nRequire Export SystemFR.EquivalenceLemmas3.\nRequire Export SystemFR.EvalListMatch.\nRequire Export SystemFR.EvalFixDefault.\n\nOpaque reducible_values.\n\nReserved Notation \"'[' Γ ⊨ t1 '⤳*' t2 ']'\" (at level 60, Γ at level 60, t1 at level 60).\n\nInductive delta_beta_reduction: context -> tree -> tree -> Prop :=\n| DBVar:\n    forall Γ x ty t v,\n      wf t 0 ->\n      lookup Nat.eq_dec Γ x = Some (T_singleton ty t) ->\n      [ Γ ⊨ t ⤳* v ] ->\n      [ Γ ⊨ fvar x term_var ⤳* v ]\n\n| DBPair:\n    forall Γ t1 t2 v1 v2,\n      [ Γ ⊨ t1 ⤳* v1 ] ->\n      [ Γ ⊨ t2 ⤳* v2 ] ->\n      [ Γ ⊨ pp t1 t2 ⤳* pp v1 v2 ]\n\n| DBFirst:\n    forall Γ t v1 v2,\n      is_erased_term v1 ->\n      is_erased_term v2 ->\n      wf v1 0 ->\n      wf v2 0 ->\n      subset (fv v1) (support Γ) ->\n      subset (fv v2) (support Γ) ->\n      [ Γ ⊫ v1 : T_top ] ->\n      [ Γ ⊫ v2 : T_top ] ->\n      [ Γ ⊨ t ⤳* pp v1 v2 ] ->\n      [ Γ ⊨ pi1 t ⤳* v1 ]\n\n| DBSecond:\n    forall Γ t v1 v2,\n      is_erased_term v1 ->\n      is_erased_term v2 ->\n      wf v1 0 ->\n      wf v2 0 ->\n      subset (fv v1) (support Γ) ->\n      subset (fv v2) (support Γ) ->\n      [ Γ ⊫ v1 : T_top ] ->\n      [ Γ ⊫ v2 : T_top ] ->\n      [ Γ ⊨ t ⤳* pp v1 v2 ] ->\n      [ Γ ⊨ pi2 t ⤳* v2 ]\n\n| DBApp1:\n    forall Γ f t t' body v,\n      is_erased_term t' ->\n      is_erased_term body ->\n      pfv t' term_var = nil ->\n      pfv body term_var = nil ->\n      wf t' 0 ->\n      wf body 0 ->\n      [ Γ ⊫ t' : T_top ] ->\n      [ Γ ⊨ t ⤳* t' ] ->\n      [ Γ ⊨ f ⤳* notype_lambda body ] ->\n      [ Γ ⊨ open 0 body t' ⤳* v ] ->\n      [ Γ ⊨ app f t ⤳* v ]\n\n| DBApp2:\n    forall Γ f f' t t',\n      [ Γ ⊨ t ⤳* t' ] ->\n      [ Γ ⊨ f ⤳* f' ] ->\n      [ Γ ⊨ app f t ⤳* app f' t' ]\n\n\n| DBNatMatch1:\n    forall Γ t t0 ts v,\n      is_erased_term ts ->\n      wf ts 1 ->\n      subset (fv ts) (support Γ) ->\n      [ Γ ⊨ t ⤳* zero ] ->\n      [ Γ ⊨ t0 ⤳* v ] ->\n      [ Γ ⊨ tmatch t t0 ts ⤳* v ]\n\n| DBNatMatch2:\n    forall Γ t t0 ts t' v,\n      is_erased_term t0 ->\n      is_erased_term ts ->\n      wf t0 0 ->\n      wf ts 1 ->\n      subset (fv t0) (support Γ) ->\n      subset (fv ts) (support Γ) ->\n      subset (fv v) (support Γ) ->\n      [ Γ ⊫ t' : T_top ] ->\n      [ Γ ⊨ t ⤳* succ t' ] ->\n      [ Γ ⊨ open 0 ts t' ⤳* v ] ->\n      [ Γ ⊨ tmatch t t0 ts ⤳* v ]\n\n| DBNatMatch3:\n    forall Γ t t' t0 ts,\n      is_erased_term t0 ->\n      is_erased_term ts ->\n      wf t0 0 ->\n      wf ts 1 ->\n      subset (fv t0) (support Γ) ->\n      subset (fv ts) (support Γ) ->\n      [ Γ ⊨ t ⤳* t' ] ->\n      [ Γ ⊨ tmatch t t0 ts ⤳* tmatch t' t0 ts ]\n\n| DBListMatch1:\n    forall Γ t t1 t2 v,\n      is_erased_term t2 ->\n      wf t2 2 ->\n      subset (fv t2) (support Γ) ->\n      [ Γ ⊨ t ⤳* tnil ] ->\n      [ Γ ⊨ t1 ⤳* v ] ->\n      [ Γ ⊨ list_match t t1 t2 ⤳* v ]\n\n| DBListMatch2:\n    forall Γ t1 t2 h t v,\n      wf t1 0 ->\n      wf t2 2 ->\n      is_erased_term t1 ->\n      is_erased_term t2 ->\n      subset (fv t1) (support Γ) ->\n      subset (fv t2) (support Γ) ->\n      [ Γ ⊫ t : List ] ->\n      [ Γ ⊨ t ⤳* tcons h t ] ->\n      [ Γ ⊨ open 0 (open 1 t2 h) t ⤳* v ] ->\n      [ Γ ⊨ list_match t t1 t2 ⤳* v ]\n\n| DBListMatch3:\n    forall Γ t t' t1 t2,\n      is_erased_term t1 ->\n      is_erased_term t2 ->\n      wf t1 0 ->\n      wf t2 2 ->\n      subset (fv t1) (support Γ) ->\n      subset (fv t2) (support Γ) ->\n      [ Γ ⊨ t ⤳* t' ] ->\n      [ Γ ⊨ list_match t t1 t2 ⤳* list_match t' t1 t2 ]\n\n| DBLeft:\n    forall Γ t v,\n      [ Γ ⊨ t ⤳* v ] ->\n      [ Γ ⊨ tleft t ⤳* tleft v ]\n\n| DBRight:\n    forall Γ t v,\n      [ Γ ⊨ t ⤳* v ] ->\n      [ Γ ⊨ tright t ⤳* tright v ]\n\n| DBFix0:\n    forall Γ t default v,\n      wf default 0 ->\n      wf t 1 ->\n      is_erased_term default ->\n      is_erased_term t ->\n      subset (fv default) (support Γ) ->\n      subset (fv t) (support Γ) ->\n      [ Γ ⊨ default ⤳* v ] ->\n      [ Γ ⊨ fix_default' t default zero  ⤳* v ]\n\n| DBFix:\n    forall Γ t default fuel v,\n      is_nat_value fuel ->\n      wf default 0 ->\n      wf t 1 ->\n      is_erased_term default ->\n      is_erased_term t ->\n      subset (fv default) (support Γ) ->\n      subset (fv t) (support Γ) ->\n      [ Γ ⊨ open 0 t (fix_default' t default fuel) ⤳* v ] ->\n      [ Γ ⊨ fix_default' t default (succ fuel) ⤳* v ]\n\n| DBRefl:\n    forall Γ v,\n      is_erased_term v ->\n      wf v 0 ->\n      subset (fv v) (support Γ) ->\n      [ Γ ⊨ v ⤳* v ] (* when evaluation is finished *)\n\nwhere \"'[' Γ ⊨ t1 '⤳*' t2 ']'\" := (delta_beta_reduction Γ t1 t2).\n\nLemma delta_beta_var:\n  forall Θ Γ x ty t v,\n    wf t 0 ->\n    lookup Nat.eq_dec Γ x = Some (T_singleton ty t) ->\n    [ Θ; Γ ⊨ t ≡ v ] ->\n    [ Θ; Γ ⊨ fvar x term_var ≡ v ].\nProof.\n  unfold open_equivalent, T_singleton;\n    repeat step || t_lookup || erewrite satisfies_same_support in * by eauto.\n  unshelve epose proof (satisfies_lookup2 _ _ _ _ _ _ H3 H0 matched);\n    repeat step || simp_red || open_none || rewrite shift_nothing2 in * by eauto with wf;\n    eauto using equivalent_trans.\nQed.\n\nLemma delta_beta_pair:\n  forall Θ Γ t1 t2 t1' t2',\n    [ Θ; Γ ⊨ t1 ≡ t1' ] ->\n    [ Θ; Γ ⊨ t2 ≡ t2' ] ->\n    [ Θ; Γ ⊨ pp t1 t2 ≡ pp t1' t2' ].\nProof.\n  unfold open_equivalent; repeat step || apply equivalent_pp; eauto.\nQed.\n\nLemma open_equivalent_refl:\n  forall Θ Γ t,\n    is_erased_term t ->\n    wf t 0 ->\n    subset (fv t) (support Γ) ->\n    [ Θ; Γ ⊨ t ≡ t ].\nProof.\n  unfold open_equivalent; intros; apply equivalent_refl; steps;\n    eauto with erased fv wf.\nQed.\n\nLemma equivalent_pi1_pp:\n  forall t1 t2,\n    is_erased_term t1 ->\n    is_erased_term t2 ->\n    wf t1 0 ->\n    wf t2 0 ->\n    pfv t1 term_var = nil ->\n    pfv t2 term_var = nil ->\n    scbv_normalizing t1 ->\n    scbv_normalizing t2 ->\n    [ pi1 (pp t1 t2) ≡ t1 ].\nProof.\n  unfold scbv_normalizing; steps.\n  apply equivalent_trans with v0.\n  - equivalent_star.\n    eapply star_trans; eauto with cbvlemmas.\n    eapply star_trans; eauto with cbvlemmas.\n    eauto using star_one with smallstep.\n  - apply equivalent_sym; equivalent_star.\nQed.\n\nLemma equivalent_pi2_pp:\n  forall t1 t2,\n    is_erased_term t1 ->\n    is_erased_term t2 ->\n    wf t1 0 ->\n    wf t2 0 ->\n    pfv t1 term_var = nil ->\n    pfv t2 term_var = nil ->\n    scbv_normalizing t1 ->\n    scbv_normalizing t2 ->\n    [ pi2 (pp t1 t2) ≡ t2 ].\nProof.\n  unfold scbv_normalizing; steps.\n  apply equivalent_trans with v.\n  - equivalent_star.\n    eapply star_trans; eauto with cbvlemmas.\n    eapply star_trans; eauto with cbvlemmas.\n    eauto using star_one with smallstep.\n  - apply equivalent_sym; equivalent_star.\nQed.\n\nLemma lookup_value:\n  forall l x v,\n    are_values l ->\n    lookup Nat.eq_dec l x = Some v ->\n    cbv_value v.\nProof.\n  induction l; steps; eauto.\nQed.\n\nLemma satisfies_are_values:\n  forall l ρ Γ,\n    valid_interpretation ρ ->\n    satisfies (reducible_values ρ) Γ l ->\n    are_values l.\nProof.\n  induction l; repeat step || step_inversion satisfies; eauto with values.\nQed.\n\nLemma typable_normalizing:\n  forall Θ Γ t T ρ l,\n    [ Θ; Γ ⊨ t : T ] ->\n    satisfies (reducible_values ρ) Γ l ->\n    valid_interpretation ρ ->\n    Θ = support ρ ->\n    scbv_normalizing (psubstitute t l term_var).\nProof.\n  unfold scbv_normalizing, open_reducible, reduces_to;\n    repeat step || t_instantiate_sat3; eauto with values.\nQed.\n\nLemma delta_beta_first:\n  forall Γ t t1 t2,\n    is_erased_term t1 ->\n    is_erased_term t2 ->\n    wf t1 0 ->\n    wf t2 0 ->\n    subset (fv t1) (support Γ) ->\n    subset (fv t2) (support Γ) ->\n    [ Γ ⊫ t1 : T_top ] ->\n    [ Γ ⊫ t2 : T_top ] ->\n    [ Γ ⊫ t ≡ pp t1 t2 ] ->\n    [ Γ ⊫ pi1 t ≡ t1 ].\nProof.\n  unfold open_equivalent; repeat step; eauto.\n  eapply equivalent_trans; eauto using equivalent_pi1.\n  apply equivalent_pi1_pp; steps; eauto with erased wf fv;\n    eauto using typable_normalizing.\nQed.\n\nLemma delta_beta_second:\n  forall Γ t t1 t2,\n    is_erased_term t1 ->\n    is_erased_term t2 ->\n    wf t1 0 ->\n    wf t2 0 ->\n    subset (fv t1) (support Γ) ->\n    subset (fv t2) (support Γ) ->\n    [ Γ ⊫ t1 : T_top ] ->\n    [ Γ ⊫ t2 : T_top ] ->\n    [ Γ ⊫ t ≡ pp t1 t2 ] ->\n    [ Γ ⊫ pi2 t ≡ t2 ].\nProof.\n  unfold open_equivalent; repeat step; eauto.\n  eapply equivalent_trans; eauto using equivalent_pi2.\n  apply equivalent_pi2_pp; steps; eauto with erased wf fv;\n    eauto using typable_normalizing.\nQed.\n\nLemma equivalent_beta2:\n  forall f t,\n    is_erased_term t ->\n    is_erased_term f ->\n    pfv t term_var = nil ->\n    pfv f term_var = nil ->\n    wf t 0 ->\n    wf f 1 ->\n    scbv_normalizing t ->\n    equivalent_terms (app (notype_lambda f) t) (open 0 f t).\nProof.\n  unfold scbv_normalizing; repeat step; eauto using equivalent_beta.\nQed.\n\nLemma delta_beta_app1:\n  forall Γ f t t' v body,\n    is_erased_term t' ->\n    is_erased_term body ->\n    pfv t' term_var = nil ->\n    pfv body term_var = nil ->\n    wf t' 0 ->\n    wf body 0 ->\n    [ Γ ⊫ t' : T_top ] ->\n    [ Γ ⊫ t ≡ t' ] ->\n    [ Γ ⊫ f ≡ notype_lambda body ] ->\n    [ Γ ⊫ open 0 body t' ≡ v ] ->\n    [ Γ ⊫ app f t ≡ v ].\nProof.\n  unfold open_equivalent; repeat step || t_instantiate_sat3 || t_substitutions.\n  eapply equivalent_trans; eauto using equivalent_app.\n  eapply equivalent_trans; eauto; repeat step || t_substitutions.\n  eapply equivalent_beta2; steps; eauto using typable_normalizing;\n    eauto with erased fv wf.\nQed.\n\nLemma delta_beta_app2:\n  forall Θ Γ f f' t t',\n    [ Θ; Γ ⊨ t ≡ t' ] ->\n    [ Θ; Γ ⊨ f ≡ f' ] ->\n    [ Θ; Γ ⊨ app f t ≡ app f' t' ].\nProof.\n  unfold open_equivalent; repeat step || t_instantiate_sat3 || t_substitutions;\n    eauto using equivalent_app.\nQed.\n\nLemma equivalent_match_scrut:\n  forall t t' t0 ts,\n    is_erased_term t0 ->\n    is_erased_term ts ->\n    wf t0 0 ->\n    wf ts 1 ->\n    pfv t0 term_var = nil ->\n    pfv ts term_var = nil ->\n    [ t ≡ t' ] ->\n    [ tmatch t t0 ts ≡ tmatch t' t0 ts ].\nProof.\n  intros.\n  unshelve epose proof (equivalent_context (tmatch (lvar 0 term_var) t0 ts) _ _ _ _ _ H5);\n    repeat step || list_utils || open_none;\n    eauto with wf.\nQed.\n\nLemma equivalent_list_match_scrut:\n  forall t t' t1 t2,\n    is_erased_term t1 ->\n    is_erased_term t2 ->\n    wf t1 0 ->\n    wf t2 2 ->\n    pfv t1 term_var = nil ->\n    pfv t2 term_var = nil ->\n    [ t ≡ t' ] ->\n    [ list_match t t1 t2 ≡ list_match t' t1 t2 ].\nProof.\n  intros.\n  unshelve epose proof (equivalent_context (list_match (lvar 0 term_var) t1 t2) _ _ _ _ _ H5);\n    repeat step || list_utils || open_none ||\n           (rewrite (open_none t1) in * by eauto with wf) ||\n           (rewrite open_none in H6 by (steps; eauto with wf step_tactic));\n    eauto 3 with wf erased fv step_tactic.\nQed.\n\nLemma delta_beta_match_zero:\n  forall Θ Γ t t0 ts v,\n    is_erased_term ts ->\n    wf ts 1 ->\n    subset (fv ts) (support Γ) ->\n    [ Θ; Γ ⊨ t ≡ zero ] ->\n    [ Θ; Γ ⊨ t0 ≡ v ] ->\n    [ Θ; Γ ⊨ tmatch t t0 ts ≡ v ].\nProof.\n  unfold open_equivalent; repeat step || t_instantiate_sat3.\n  eapply equivalent_trans; eauto.\n  eapply equivalent_trans; try apply equivalent_match_scrut; eauto;\n    eauto with erased wf fv;\n    equivalent_star.\nQed.\n\nLemma delta_beta_match_succ:\n  forall Γ t t0 ts t' v,\n    is_erased_term t0 ->\n    is_erased_term ts ->\n    wf t0 0 ->\n    wf ts 1 ->\n    subset (fv t0) (support Γ) ->\n    subset (fv ts) (support Γ) ->\n    subset (fv v) (support Γ) ->\n    [ Γ ⊫ t' : T_top ] ->\n    [ Γ ⊫ t ≡ succ t' ] ->\n    [ Γ ⊫ open 0 ts t' ≡ v ] ->\n    [ Γ ⊫ tmatch t t0 ts ≡ v ].\nProof.\n  unfold open_equivalent, open_reducible;\n    repeat step || t_instantiate_sat3_nil || t_substitutions.\n  eapply equivalent_trans; eauto; repeat step || t_substitutions.\n  eapply equivalent_trans; try apply equivalent_match_scrut;\n    eauto with erased fv wf.\n  top_level_unfold reduces_to; steps.\n  eapply equivalent_trans; try apply equivalent_match_scrut;\n    eauto with erased fv wf;\n    try solve [ apply equivalent_succ; equivalent_star ].\n\n  eapply equivalent_trans; try solve [ equivalent_star ].\n  apply equivalent_context; eauto with erased wf fv.\n  apply equivalent_sym; equivalent_star.\nQed.\n\nLemma delta_beta_match_scrut:\n  forall Θ Γ t t' t0 ts,\n    is_erased_term t0 ->\n    is_erased_term ts ->\n    wf t0 0 ->\n    wf ts 1 ->\n    subset (fv t0) (support Γ) ->\n    subset (fv ts) (support Γ) ->\n    [ Θ; Γ ⊨ t ≡ t' ] ->\n    [ Θ; Γ ⊨ tmatch t t0 ts ≡ tmatch t' t0 ts ].\nProof.\n  unfold open_equivalent; steps; apply equivalent_match_scrut;\n    eauto with erased wf fv.\nQed.\n\nOpaque list_match.\n\nLemma delta_beta_list_match_nil:\n  forall Θ Γ t t1 t2 v,\n    is_erased_term t2 ->\n    wf t2 2 ->\n    subset (fv t2) (support Γ) ->\n    [ Θ; Γ ⊨ t ≡ tnil ] ->\n    [ Θ; Γ ⊨ t1 ≡ v ] ->\n    [ Θ; Γ ⊨ list_match t t1 t2 ≡ v ].\nProof.\n  unfold open_equivalent; repeat step || t_instantiate_sat3 || rewrite substitute_list_match;\n    eauto with wf.\n  eapply equivalent_trans; eauto.\n  eapply equivalent_trans; try apply equivalent_list_match_scrut; eauto;\n    eauto with erased wf fv;\n    try solve [ equivalent_star ].\n\n  evaluate_list_match; repeat step; eauto with wf fv erased.\n  - apply reducible_nil; auto.\n  - equivalent_star; eauto 3 with wf erased fv step_tactic.\n  - unfold tcons in *; steps.\nQed.\n\nOpaque List.\n\nLemma equivalent_right_eval_left:\n  forall t t' v,\n    cbv_value v  ->\n    [ t ≡ tright t' ] ->\n    t ~>* tleft v ->\n    False.\nProof.\n  intros.\n  apply right_left_equivalence with t' v; auto.\n  eapply equivalent_trans; eauto using equivalent_sym; equivalent_star.\nQed.\n\nLemma equivalent_right_eval_nil:\n  forall t t',\n    [ t ≡ tright t' ] ->\n    t ~>* tnil ->\n    False.\nProof.\n  intros.\n  apply equivalent_right_eval_left with t t' uu; steps.\nQed.\n\nLemma equivalent_context2:\n  forall C t1 t1' t2 t2',\n    is_erased_term C ->\n    wf C 2 ->\n    pfv C term_var = nil ->\n    [ t1 ≡ t1' ] ->\n    [ t2 ≡ t2' ] ->\n    [ open 0 (open 1 C t1) t2 ≡ open 0 (open 1 C t1') t2' ].\nProof.\n  intros.\n  eapply equivalent_trans; try solve [ apply equivalent_context; steps; eauto with erased wf fv ].\n  repeat rewrite (swap_term_holes_open C); steps; eauto with wf.\n  apply equivalent_context; steps; eauto with erased wf fv.\nQed.\n\nLemma delta_beta_list_match_cons:\n  forall Γ h t t1 t2 v,\n    wf t1 0 ->\n    wf t2 2 ->\n    is_erased_term t1 ->\n    is_erased_term t2 ->\n    subset (fv t1) (support Γ) ->\n    subset (fv t2) (support Γ) ->\n    [ Γ ⊫ t : List ] ->\n    [ Γ ⊫ t ≡ tcons h t ] ->\n    [ Γ ⊫ open 0 (open 1 t2 h) t ≡ v ] ->\n    [ Γ ⊫ list_match t t1 t2 ≡ v ].\nProof.\n  unfold open_equivalent, open_reducible;\n    repeat step || t_instantiate_sat3_nil || t_substitutions || rewrite substitute_list_match;\n    eauto with wf.\n\n  eapply equivalent_trans; eauto.\n\n  eapply equivalent_trans; try apply equivalent_list_match_scrut; eauto;\n    eauto with erased wf fv;\n    try solve [ equivalent_star ].\n\n  evaluate_list_match2; repeat step || t_invert_star || unfold tcons in *; eauto with wf fv erased;\n    eauto using reducibility_equivalent2, is_erased_list, wf_list;\n    try solve [ unfold tnil in *; repeat step || t_invert_star ].\n\n  eapply equivalent_trans; eauto.\n  apply_anywhere right_right_star.\n  apply equivalent_context2; steps; eauto with fv wf erased.\n  - apply equivalent_sym; equivalent_star; eauto using pp_pp_star_1.\n  - apply equivalent_sym; equivalent_star; eauto using pp_pp_star_2.\nQed.\n\nLemma delta_beta_list_match_scrut:\n  forall Θ Γ t t' t1 t2,\n    is_erased_term t1 ->\n    is_erased_term t2 ->\n    wf t1 0 ->\n    wf t2 2 ->\n    subset (fv t1) (support Γ) ->\n    subset (fv t2) (support Γ) ->\n    [ Θ; Γ ⊨ t ≡ t' ] ->\n    [ Θ; Γ ⊨ list_match t t1 t2 ≡ list_match t' t1 t2 ].\nProof.\n  unfold open_equivalent; repeat step || rewrite substitute_list_match;\n    try apply equivalent_list_match_scrut;\n    eauto with erased wf fv.\nQed.\n\nLemma open_equivalent_context:\n  forall Θ Γ t1 t2 C,\n    is_erased_term C ->\n    wf C 1 ->\n    subset (fv C) (support Γ) ->\n    [ Θ; Γ ⊨ t1 ≡ t2 ] ->\n    [ Θ; Γ ⊨ open 0 C t1 ≡ open 0 C t2 ].\nProof.\n  unfold open_equivalent;\n    repeat step || t_instantiate_sat3 || t_substitutions || apply equivalent_context;\n    eauto with fv wf erased.\nQed.\n\nLemma delta_beta_left:\n  forall Θ Γ t t',\n    [ Θ; Γ ⊨ t ≡ t' ] ->\n    [ Θ; Γ ⊨ tleft t ≡ tleft t' ].\nProof.\n  intros.\n  unshelve epose proof (open_equivalent_context _ _ _ _ (tleft (lvar 0 term_var)) _ _ _ H);\n    steps; eauto with sets.\nQed.\n\nLemma delta_beta_right:\n  forall Θ Γ t t',\n    [ Θ; Γ ⊨ t ≡ t' ] ->\n    [ Θ; Γ ⊨ tright t ≡ tright t' ].\nProof.\n  intros.\n  unshelve epose proof (open_equivalent_context _ _ _ _ (tright (lvar 0 term_var)) _ _ _ H);\n    steps; eauto with sets.\nQed.\n\nOpaque fix_default'.\n\nLemma delta_beta_fix_zero:\n  forall Γ t default v,\n    wf default 0 ->\n    wf t 1 ->\n    is_erased_term default ->\n    is_erased_term t ->\n    subset (fv default) (support Γ) ->\n    subset (fv t) (support Γ) ->\n    [ Γ ⊫ default ≡ v ] ->\n    [ Γ ⊫ fix_default' t default zero ≡ v ].\nProof.\n  unfold open_equivalent; repeat step || rewrite subst_fix_default; eauto with wf.\n\n  evaluate_fix_default; steps; eauto with wf.\n  eapply equivalent_trans; eauto.\n\n  equivalent_star; eauto 4 with fv erased wf step_tactic.\nQed.\n\nLemma delta_beta_fix_succ:\n  forall Γ t default fuel v,\n    is_nat_value fuel ->\n    wf default 0 ->\n    wf t 1 ->\n    is_erased_term default ->\n    is_erased_term t ->\n    subset (fv default) (support Γ) ->\n    subset (fv t) (support Γ) ->\n    [ Γ ⊫ open 0 t (fix_default' t default fuel) ≡ v ] ->\n    [ Γ ⊫ fix_default' t default (succ fuel) ≡ v ].\nProof.\n  unfold open_equivalent; repeat step || t_instantiate_sat3_nil || t_substitutions ||\n                                 rewrite subst_fix_default in * by eauto with wf.\n  evaluate_fix_default; repeat step || rewrite (substitute_nothing5 fuel) in * by eauto with fv;\n    eauto with wf; eauto with is_nat_value.\n  eapply equivalent_trans; eauto.\n  equivalent_star; eauto with erased wf fv step_tactic.\nQed.\n\nLemma delta_beta_obs_equiv:\n  forall Γ t1 t2,\n    [ Γ ⊨ t1 ⤳* t2 ] ->\n    [ Γ ⊫ t1 ≡ t2 ].\nProof.\n  induction 1; repeat step;\n    eauto using delta_beta_var;\n    eauto using delta_beta_pair;\n    eauto using delta_beta_first;\n    eauto using delta_beta_second;\n    eauto using delta_beta_app1;\n    eauto using delta_beta_app2;\n    eauto using delta_beta_match_zero;\n    eauto using delta_beta_match_succ;\n    eauto using delta_beta_match_scrut;\n    eauto using delta_beta_list_match_nil;\n    eauto using delta_beta_list_match_cons;\n    eauto using delta_beta_list_match_scrut;\n    eauto using delta_beta_left;\n    eauto using delta_beta_right;\n    eauto using delta_beta_fix_zero;\n    eauto using delta_beta_fix_succ;\n    eauto using open_equivalent_refl.\nQed.\n", "meta": {"author": "epfl-lara", "repo": "SystemFR", "sha": "a68d12d6360f395958506deea66112c46be492a0", "save_path": "github-repos/coq/epfl-lara-SystemFR", "path": "github-repos/coq/epfl-lara-SystemFR/SystemFR-a68d12d6360f395958506deea66112c46be492a0/DeltaBetaReduction.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.21433668472387096}}
{"text": "Require Import Bedrock.Bedrock Bedrock.Platform.PreAutoSep.\n\n\n(** * Separation logic specifications for system calls *)\n\nDefinition abortS := SPEC reserving 0\n  PREonly[_] Emp.\n\nDefinition printIntS := SPEC(\"n\") reserving 0\n  PRE[_] Emp\n  POST[_] Emp.\n\nDefinition listenS := SPEC(\"port\") reserving 0\n  PRE[_] Emp\n  POST[stream] Emp.\n\nDefinition acceptS := SPEC(\"stream\") reserving 0\n  PRE[_] Emp\n  POST[stream'] Emp.\n\nDefinition buffer (p : W) (size : nat) : HProp :=\n  (Ex bs, array8 bs p * [| length bs = size |])%Sep.\n\nInfix \"=?>8\" := buffer (at level 39) : Sep_scope.\nNotation \"buf =?>8 size\" := (Body (buf =?>8 size)%Sep) : qspec_scope.\n\nDefinition connectS := SPEC(\"address\", \"size\") reserving 0\n  PRE[V] V \"address\" =?>8 wordToNat (V \"size\")\n  POST[bytesRead] V \"address\" =?>8 wordToNat (V \"size\").\n\nDefinition readS := SPEC(\"stream\", \"buffer\", \"size\") reserving 0\n  PRE[V] V \"buffer\" =?>8 wordToNat (V \"size\")\n  POST[bytesRead] V \"buffer\" =?>8 wordToNat (V \"size\").\n\nDefinition writeS := SPEC(\"stream\", \"buffer\", \"size\") reserving 0\n  PRE[V] V \"buffer\" =?>8 wordToNat (V \"size\")\n  POST[bytesWritten] V \"buffer\" =?>8 wordToNat (V \"size\").\n\n(* Limited version of epoll_ctl *)\nDefinition declareS := SPEC(\"stream\", \"mode\") reserving 0\n  PRE[_] Emp\n  POST[index] Emp.\n(* Mode is either 0 for read or 1 for write. *)\n\n(* Limited version of epoll_wait *)\nDefinition waitS := SPEC(\"blocking\") reserving 0\n  PRE[_] Emp\n  POST[index] Emp.\n\nDefinition closeS := SPEC(\"stream\") reserving 0\n  PRE[_] Emp\n  POST[_] Emp.\n\n\n(** * More primitive operational semantics *)\n\nDefinition mapped (base : W) (len : nat) (m : mem) :=\n  forall n, (n < len)%nat -> m (base ^+ $ (n)) <> None.\n\nRecord onlyChange (base : W) (len : nat) (m m' : mem) : Prop :=\n  { Elsewhere : forall p, (forall n, (n < len)%nat -> p <> base ^+ $ (n))\n    -> m' p = m p;\n    SameMapped : forall p, m p = None <-> m' p = None }.\n\nHint Constructors onlyChange.\n\nSection OpSem.\n  Variable stn : settings.\n  Variable prog : program.\n\n  Inductive sys_step : state' -> state' -> Prop :=\n  | Normal : forall st st', step stn prog st = Some st'\n    -> sys_step st st'\n  | Abort : forall st, Labels stn (\"sys\", Global \"abort\") = Some (fst st)\n    -> sys_step st st\n  | PrintInt : forall st st',\n    Labels stn (\"sys\", Global \"printInt\") = Some (fst st)\n    -> mapped (Regs (snd st) Sp) 8 (Mem (snd st))\n    -> Regs st' Sp = Regs (snd st) Sp\n    -> Mem st' = Mem (snd st)\n    -> sys_step st (Regs (snd st) Rp, st')\n  | Listen : forall st st', Labels stn (\"sys\", Global \"listen\") = Some (fst st)\n    -> mapped (Regs (snd st) Sp) 8 (Mem (snd st))\n    -> Regs st' Sp = Regs (snd st) Sp\n    -> Mem st' = Mem (snd st)\n    -> sys_step st (Regs (snd st) Rp, st')\n  | Accept : forall st st',\n    Labels stn (\"sys\", Global \"accept\") = Some (fst st)\n    -> mapped (Regs (snd st) Sp) 8 (Mem (snd st))\n    -> Regs st' Sp = Regs (snd st) Sp\n    -> Mem st' = Mem (snd st)\n    -> sys_step st (Regs (snd st) Rp, st')\n  | Connect : forall st address size st',\n    Labels stn (\"sys\", Global \"connect\") = Some (fst st)\n    -> mapped (Regs (snd st) Sp) 12 (Mem (snd st))\n    -> ReadWord stn (Mem (snd st)) (Regs (snd st) Sp ^+ $4) = Some address\n    -> ReadWord stn (Mem (snd st)) (Regs (snd st) Sp ^+ $8) = Some size\n    -> mapped address (wordToNat size) (Mem (snd st))\n    -> Regs st' Sp = Regs (snd st) Sp\n    -> onlyChange address (wordToNat size) (Mem (snd st)) (Mem st')\n    -> sys_step st (Regs (snd st) Rp, st')\n  | Read : forall st buffer size st',\n    Labels stn (\"sys\", Global \"read\") = Some (fst st)\n    -> mapped (Regs (snd st) Sp) 16 (Mem (snd st))\n    -> ReadWord stn (Mem (snd st)) (Regs (snd st) Sp ^+ $8) = Some buffer\n    -> ReadWord stn (Mem (snd st)) (Regs (snd st) Sp ^+ $12) = Some size\n    -> mapped buffer (wordToNat size) (Mem (snd st))\n    -> Regs st' Sp = Regs (snd st) Sp\n    -> onlyChange buffer (wordToNat size) (Mem (snd st)) (Mem st')\n    -> sys_step st (Regs (snd st) Rp, st')\n  | Write : forall st buffer size st',\n    Labels stn (\"sys\", Global \"write\") = Some (fst st)\n    -> mapped (Regs (snd st) Sp) 16 (Mem (snd st))\n    -> ReadWord stn (Mem (snd st)) (Regs (snd st) Sp ^+ $8) = Some buffer\n    -> ReadWord stn (Mem (snd st)) (Regs (snd st) Sp ^+ $12) = Some size\n    -> mapped buffer (wordToNat size) (Mem (snd st))\n    -> Regs st' Sp = Regs (snd st) Sp\n    -> Mem st' = Mem (snd st)\n    -> sys_step st (Regs (snd st) Rp, st')\n  | Declare : forall st st',\n    Labels stn (\"sys\", Global \"declare\") = Some (fst st)\n    -> mapped (Regs (snd st) Sp) 12 (Mem (snd st))\n    -> Regs st' Sp = Regs (snd st) Sp\n    -> Mem st' = Mem (snd st)\n    -> sys_step st (Regs (snd st) Rp, st')\n  | Wait : forall st st',\n    Labels stn (\"sys\", Global \"wait\") = Some (fst st)\n    -> mapped (Regs (snd st) Sp) 8 (Mem (snd st))\n    -> Regs st' Sp = Regs (snd st) Sp\n    -> Mem st' = Mem (snd st)\n    -> sys_step st (Regs (snd st) Rp, st')\n  | Close : forall st st',\n    Labels stn (\"sys\", Global \"close\") = Some (fst st)\n    -> mapped (Regs (snd st) Sp) 8 (Mem (snd st))\n    -> Regs st' Sp = Regs (snd st) Sp\n    -> Mem st' = Mem (snd st)\n    -> sys_step st (Regs (snd st) Rp, st').\n\n  Inductive sys_reachable : state' -> state' -> Prop :=\n  | SR0 : forall st, sys_reachable st st\n  | SR1 : forall st st' st'', sys_step st st'\n    -> sys_reachable st' st''\n    -> sys_reachable st st''.\n\n  Definition sys_safe (st : state') :=\n    forall st', sys_reachable st st' -> exists st'', sys_step st' st''.\nEnd OpSem.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Platform/Sys.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.21433667441236523}}
{"text": "From iris.base_logic Require Export invariants gen_heap.\nFrom iris.program_logic Require Export weakestpre ectx_lifting.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import frac.\nFrom cap_machine Require Import machine_base rules_base.\n\nSection cap_lang_rules.\n  Context `{memG Σ, regG Σ}.\n  Context `{MachineParameters}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types σ : ExecConf.\n  Implicit Types c : cap_lang.expr. \n  Implicit Types a b : Addr.\n  Implicit Types r : RegName.\n  Implicit Types v : cap_lang.val. \n  Implicit Types w : Word.\n  Implicit Types reg : gmap RegName Word.\n  Implicit Types ms : gmap Addr Word.\n\n  (* TODO: move to stdpp *)\n  Tactic Notation \"destruct_or\" ident(H) :=\n  match type of H with\n  | _ ∨ _ => destruct H as [H|H]\n  | Is_true (_ || _) => apply orb_True in H; destruct H as [H|H]\n  end.\n  Tactic Notation \"destruct_or\" \"?\" ident(H) := repeat (destruct_or H).\n  Tactic Notation \"destruct_or\" \"!\" ident(H) := hnf in H; destruct_or H; destruct_or? H.\n\n  Definition denote (i: instr) (n1 n2: Z): Z :=\n    match i with\n    | machine_base.Add _ _ _ => (n1 + n2)%Z\n    | Sub _ _ _ => (n1 - n2)%Z\n    | Lt _ _ _ => (Z.b2z (n1 <? n2)%Z)\n    | _ => 0%Z\n    end.\n\n  Definition is_AddSubLt (i: instr) (r: RegName) (arg1 arg2: Z + RegName) :=\n    i = machine_base.Add r arg1 arg2 ∨\n    i = Sub r arg1 arg2 ∨\n    i = Lt r arg1 arg2.\n\n  Lemma regs_of_is_AddSubLt i r arg1 arg2 :\n    is_AddSubLt i r arg1 arg2 →\n    regs_of i = {[ r ]} ∪ regs_of_argument arg1 ∪ regs_of_argument arg2.\n  Proof.\n    intros HH. destruct_or! HH; subst i; reflexivity.\n  Qed.\n\n  Inductive AddSubLt_failure (i: instr) (regs: Reg) (dst: RegName) (rv1 rv2: Z + RegName) (regs': Reg) :=\n  | AddSubLt_fail_nonconst1:\n      z_of_argument regs rv1 = None ->\n      AddSubLt_failure i regs dst rv1 rv2 regs'\n  | AddSubLt_fail_nonconst2:\n      z_of_argument regs rv2 = None ->\n      AddSubLt_failure i regs dst rv1 rv2 regs'\n  | AddSubLt_fail_incrPC n1 n2:\n      z_of_argument regs rv1 = Some n1 ->\n      z_of_argument regs rv2 = Some n2 ->\n      incrementPC (<[ dst := inl (denote i n1 n2) ]> regs) = None ->\n      regs' = (<[ dst := inl (denote i n1 n2) ]> regs) ->\n      AddSubLt_failure i regs dst rv1 rv2 regs'.\n\n  Inductive AddSubLt_spec (i: instr) (regs: Reg) (dst: RegName) (rv1 rv2: Z + RegName) (regs': Reg): cap_lang.val -> Prop :=\n  | AddSubLt_spec_success n1 n2:\n      z_of_argument regs rv1 = Some n1 ->\n      z_of_argument regs rv2 = Some n2 ->\n      incrementPC (<[ dst := inl (denote i n1 n2) ]> regs) = Some regs' ->\n      AddSubLt_spec i regs dst rv1 rv2 regs' NextIV\n  | AddSubLt_spec_failure:\n      AddSubLt_failure i regs dst rv1 rv2 regs' ->\n      AddSubLt_spec i regs dst rv1 rv2 regs' FailedV.\n\n  Local Ltac iFail Hcont get_fail_case :=\n    cbn; iFrame; iApply Hcont; iFrame; iPureIntro;\n    econstructor; eapply get_fail_case; eauto.\n\n  Lemma wp_AddSubLt Ep i pc_p pc_g pc_b pc_e pc_a w dst arg1 arg2 regs :\n    decodeInstrW w = i →\n    is_AddSubLt i dst arg1 arg2 →\n    isCorrectPC (inr ((pc_p, pc_g), pc_b, pc_e, pc_a)) →\n    regs !! PC = Some (inr ((pc_p, pc_g), pc_b, pc_e, pc_a)) →\n    regs_of i ⊆ dom _ regs →\n    {{{ ▷ pc_a ↦ₐ w ∗\n        ▷ [∗ map] k↦y ∈ regs, k ↦ᵣ y }}}\n      Instr Executable @ Ep\n    {{{ regs' retv, RET retv;\n        ⌜ AddSubLt_spec (decodeInstrW w) regs dst arg1 arg2 regs' retv ⌝ ∗\n          pc_a ↦ₐ w ∗\n          [∗ map] k↦y ∈ regs', k ↦ᵣ y }}}.\n  Proof.\n    iIntros (Hdecode Hinstr Hvpc HPC Dregs φ) \"(>Hpc_a & >Hmap) Hφ\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 l1 l2 n) \"Hσ1 /=\". destruct σ1 as [r m]; simpl.\n    iDestruct \"Hσ1\" as \"[Hr Hm]\".\n    iDestruct (gen_heap_valid_inclSepM with \"Hr Hmap\") as %Hregs.\n    have HPC' := regs_lookup_eq _ _ _ HPC.\n    have ? := lookup_weaken _ _ _ _ HPC Hregs.\n    iDestruct (@gen_heap_valid with \"Hm Hpc_a\") as %Hpc_a; auto.\n    iModIntro. iSplitR. by iPureIntro; apply normal_always_head_reducible.\n    iNext. iIntros (e2 σ2 efs Hpstep).\n    apply prim_step_exec_inv in Hpstep as (-> & -> & (c & -> & Hstep)).\n    iSplitR; auto. eapply step_exec_inv in Hstep; eauto.\n\n    specialize (indom_regs_incl _ _ _ Dregs Hregs) as Hri.\n    erewrite regs_of_is_AddSubLt in Hri, Dregs; eauto.\n    destruct (Hri dst) as [wdst [H'dst Hdst]]. by set_solver+.\n\n    destruct (z_of_argument regs arg1) as [n1|] eqn:Hn1;\n      pose proof Hn1 as Hn1'; cycle 1.\n    (* Failure: arg1 is not an integer *)\n    { unfold z_of_argument in Hn1. destruct arg1 as [| r0]; [ congruence |].\n      destruct (Hri r0) as [r0v [Hr'0 Hr0]]. by unfold regs_of_argument; set_solver+.\n      rewrite Hr'0 in Hn1. destruct r0v as [| (([[? ?] ?] & ?) & ?) ]; [ congruence |].\n      assert (c = Failed ∧ σ2 = (r, m)) as (-> & ->).\n      { destruct_or! Hinstr; rewrite Hinstr /= in Hstep.\n        all: rewrite /RegLocate Hr0 in Hstep. all: repeat case_match; simplify_eq; eauto. }\n      iFail \"Hφ\" AddSubLt_fail_nonconst1. }\n\n    destruct (z_of_argument regs arg2) as [n2|] eqn:Hn2;\n      pose proof Hn2 as Hn2'; cycle 1.\n    (* Failure: arg2 is not an integer *)\n    { unfold z_of_argument in Hn2. destruct arg2 as [| r0]; [ congruence |].\n      destruct (Hri r0) as [r0v [Hr'0 Hr0]]. by unfold regs_of_argument; set_solver+.\n      rewrite Hr'0 in Hn2. destruct r0v as [| (([[? ?] ?] & ?) & ?) ]; [ congruence |].\n      assert (c = Failed ∧ σ2 = (r, m)) as (-> & ->).\n      { destruct_or! Hinstr; rewrite Hinstr /= in Hstep.\n        all: rewrite /RegLocate Hr0 in Hstep. all: repeat case_match; simplify_eq; eauto. }\n      iFail \"Hφ\" AddSubLt_fail_nonconst2. }\n\n    eapply z_of_argument_Some_inv' in Hn1; eapply z_of_argument_Some_inv' in Hn2; eauto.\n\n    assert ((c, σ2) = updatePC (update_reg (r, m) dst (inl (denote i n1 n2)))) as HH.\n    { destruct Hn1 as [ -> | (r1 & -> & _ & Hr1) ]; destruct Hn2 as [ -> | (r2 & -> & _ & Hr2) ].\n      all: destruct_or! Hinstr; rewrite Hinstr /= /RegLocate /update_reg /= in Hstep |- *; auto.\n      all: rewrite ?Hr1 ?Hr2 /= in Hstep; auto. }\n    rewrite /update_reg /= in HH.\n\n    destruct (incrementPC (<[ dst := inl (denote i n1 n2) ]> regs))\n      as [regs'|] eqn:Hregs'; pose proof Hregs' as H'regs'; cycle 1.\n    (* Failure: Cannot increment PC *)\n    { apply incrementPC_fail_updatePC with (m:=m) in Hregs'.\n      eapply updatePC_fail_incl with (m':=m) in Hregs'.\n      2: by apply lookup_insert_is_Some'; eauto.\n      2: by apply insert_mono; eauto.\n      simplify_pair_eq.\n      iMod ((gen_heap_update_inSepM _ _ dst) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n      iFail \"Hφ\" AddSubLt_fail_incrPC. }\n\n    (* Success *)\n\n    eapply (incrementPC_success_updatePC _ m) in Hregs'\n      as (p' & g' & b' & e' & a'' & a_pc' & HPC'' & Ha_pc' & HuPC & -> & X).\n    eapply updatePC_success_incl with (m':=m) in HuPC. 2: by eapply insert_mono; eauto.\n    simplify_pair_eq. iFrame.\n    iMod ((gen_heap_update_inSepM _ _ dst) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n    iMod ((gen_heap_update_inSepM _ _ PC) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n    iFrame. iModIntro. iApply \"Hφ\". iFrame. iPureIntro. econstructor; eauto.\n  Qed.\n\n  (* Derived specifications *)\n\n  Lemma wp_add_sub_lt_success_z_z E dst pc_p pc_g pc_b pc_e pc_a w wdst ins n1 n2 pc_a' :\n    decodeInstrW w = ins →\n    is_AddSubLt ins dst (inl n1) (inl n2) →\n    (pc_a + 1)%a = Some pc_a' →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) ->\n\n    {{{ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ pc_a ↦ₐ w\n        ∗ dst ↦ᵣ wdst\n    }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ dst ↦ᵣ inl (denote ins n1 n2)\n      }}}.\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc ϕ) \"(HPC & Hpc_a & Hdst) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hdst\") as \"[Hmap %]\".\n    iApply (wp_AddSubLt with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite insert_commute // insert_insert insert_commute // insert_insert.\n      iDestruct (regs_of_map_2 with \"Hmap\") as \"[? ?]\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n      destruct e1; try congruence.\n      inv Hvpc. destruct H3 as [? | [? | [? | [? | ?]]]]; destruct H10 as [? | [? | ?]]; congruence. }\n  Qed.\n\n  Lemma wp_add_sub_lt_success_r_z E dst pc_p pc_g pc_b pc_e pc_a w wdst ins r1 n1 n2 pc_a' :\n    decodeInstrW w = ins →\n    is_AddSubLt ins dst (inr r1) (inl n2) →\n    (pc_a + 1)%a = Some pc_a' →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) ->\n\n    {{{ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ pc_a ↦ₐ w\n        ∗ r1 ↦ᵣ inl n1\n        ∗ dst ↦ᵣ wdst\n    }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ r1 ↦ᵣ inl n1\n          ∗ dst ↦ᵣ inl (denote ins n1 n2)\n      }}}.\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc ϕ) \"(HPC & Hpc_a & Hr1 & Hdst) Hφ\".\n    iDestruct (map_of_regs_3 with \"HPC Hr1 Hdst\") as \"[Hmap (%&%&%)]\".\n    iApply (wp_AddSubLt with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC dst) // insert_insert (insert_commute _ r1 dst) //\n              (insert_commute _ dst PC) // insert_insert.\n      iDestruct (regs_of_map_3 with \"Hmap\") as \"(?&?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n      destruct e1; try congruence.\n      inv Hvpc. destruct H5 as [? | [? | [? | [? | ?]]]]; destruct H12 as [? | [? | ?]]; congruence. }\n  Qed.\n\n  Lemma wp_add_sub_lt_success_z_r E dst pc_p pc_g pc_b pc_e pc_a w wdst ins n1 r2 n2 pc_a' :\n    decodeInstrW w = ins →\n    is_AddSubLt ins dst (inl n1) (inr r2) →\n    (pc_a + 1)%a = Some pc_a' →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) ->\n\n    {{{ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ pc_a ↦ₐ w\n        ∗ r2 ↦ᵣ inl n2\n        ∗ dst ↦ᵣ wdst\n    }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ r2 ↦ᵣ inl n2\n          ∗ dst ↦ᵣ inl (denote ins n1 n2)\n      }}}.\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc ϕ) \"(HPC & Hpc_a & Hr2 & Hdst) Hφ\".\n    iDestruct (map_of_regs_3 with \"HPC Hr2 Hdst\") as \"[Hmap (%&%&%)]\".\n    iApply (wp_AddSubLt with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC dst) // insert_insert (insert_commute _ r2 dst) //\n              (insert_commute _ dst PC) // insert_insert.\n      iDestruct (regs_of_map_3 with \"Hmap\") as \"(?&?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n      destruct e1; try congruence. \n      inv Hvpc. destruct H5 as [? | [? | [? | [? | ?]]]]; destruct H12 as [? | [? | ?]]; congruence. }\n  Qed.\n\n  Lemma wp_add_sub_lt_success_r_r E dst pc_p pc_g pc_b pc_e pc_a w wdst ins r1 n1 r2 n2 pc_a' :\n    decodeInstrW w = ins →\n    is_AddSubLt ins dst (inr r1) (inr r2) →\n    (pc_a + 1)%a = Some pc_a' →\n    isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) ->\n\n    {{{ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ pc_a ↦ₐ w\n        ∗ r1 ↦ᵣ inl n1\n        ∗ r2 ↦ᵣ inl n2\n        ∗ dst ↦ᵣ wdst\n    }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ r1 ↦ᵣ inl n1\n          ∗ r2 ↦ᵣ inl n2\n          ∗ dst ↦ᵣ inl (denote ins n1 n2)\n      }}}.\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc ϕ) \"(HPC & Hpc_a & Hr1 & Hr2 & Hdst) Hφ\".\n    iDestruct (map_of_regs_4 with \"HPC Hr1 Hr2 Hdst\") as \"[Hmap (%&%&%&%&%&%)]\".\n    iApply (wp_AddSubLt with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC dst) // insert_insert (insert_commute _ r2 dst) //\n              (insert_commute _ r1 dst) // (insert_commute _ PC dst) // insert_insert.\n      iDestruct (regs_of_map_4 with \"Hmap\") as \"(?&?&?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n      destruct e1; try congruence. \n      inv Hvpc. destruct H8 as [? | [? | [? | [? | ?]]]]; destruct H15 as [? | [? | ?]]; congruence. }\n  Qed.\n\n  Lemma wp_add_sub_lt_success_r_r_same E dst pc_p pc_g pc_b pc_e pc_a w wdst ins r n pc_a' :\n    decodeInstrW w = ins →\n    is_AddSubLt ins dst (inr r) (inr r) →\n    (pc_a + 1)%a = Some pc_a' →\n    isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) ->\n\n    {{{ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ pc_a ↦ₐ w\n        ∗ r ↦ᵣ inl n\n        ∗ dst ↦ᵣ wdst\n    }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ r ↦ᵣ inl n\n          ∗ dst ↦ᵣ inl (denote ins n n)\n      }}}.\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc ϕ) \"(HPC & Hpc_a & Hr & Hdst) Hφ\".\n    iDestruct (map_of_regs_3 with \"HPC Hr Hdst\") as \"[Hmap (%&%&%)]\".\n    iApply (wp_AddSubLt with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC dst) // insert_insert (insert_commute _ r dst) //\n              (insert_commute _ PC dst) // insert_insert.\n      iDestruct (regs_of_map_3 with \"Hmap\") as \"(?&?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n      destruct e1; try congruence. \n      inv Hvpc. destruct H5 as [? | [? | [? | [? | ?]]]]; destruct H12 as [? | [? | ?]]; congruence. }\n  Qed.\n\n  Lemma wp_add_sub_lt_success_dst_z E dst pc_p pc_g pc_b pc_e pc_a w ins n1 n2 pc_a' :\n    decodeInstrW w = ins →\n    is_AddSubLt ins dst (inr dst) (inl n2) →\n    (pc_a + 1)%a = Some pc_a' →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) ->\n\n    {{{ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ pc_a ↦ₐ w\n        ∗ dst ↦ᵣ inl n1\n    }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ dst ↦ᵣ inl (denote ins n1 n2)\n      }}}.\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc ϕ) \"(HPC & Hpc_a & Hdst) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hdst\") as \"[Hmap %]\".\n    iApply (wp_AddSubLt with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC dst) // insert_insert insert_commute // insert_insert.\n      iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n      destruct e1; try congruence. \n      inv Hvpc. destruct H3 as [? | [? | [? | [? | ?]]]]; destruct H10 as [? | [? | ?]]; congruence. }\n  Qed.\n\n  Lemma wp_add_sub_lt_success_z_dst E dst pc_p pc_g pc_b pc_e pc_a w ins n1 n2 pc_a' :\n    decodeInstrW w = ins →\n    is_AddSubLt ins dst (inl n1) (inr dst) →\n    (pc_a + 1)%a = Some pc_a' →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) ->\n\n    {{{ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ pc_a ↦ₐ w\n        ∗ dst ↦ᵣ inl n2\n    }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ dst ↦ᵣ inl (denote ins n1 n2)\n      }}}.\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc ϕ) \"(HPC & Hpc_a & Hdst) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hdst\") as \"[Hmap %]\".\n    iApply (wp_AddSubLt with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC dst) // insert_insert insert_commute // insert_insert.\n      iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n      destruct e1; try congruence.\n      inv Hvpc. destruct H3 as [? | [? | [? | [? | ?]]]]; destruct H10 as [? | [? | ?]]; congruence. }\n  Qed.\n\n  Lemma wp_add_sub_lt_success_dst_r E dst pc_p pc_g pc_b pc_e pc_a w ins n1 r2 n2 pc_a' :\n    decodeInstrW w = ins →\n    is_AddSubLt ins dst (inr dst) (inr r2) →\n    (pc_a + 1)%a = Some pc_a' →\n    isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) ->\n\n    {{{ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ pc_a ↦ₐ w\n        ∗ r2 ↦ᵣ inl n2\n        ∗ dst ↦ᵣ inl n1\n    }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ r2 ↦ᵣ inl n2\n          ∗ dst ↦ᵣ inl (denote ins n1 n2)\n      }}}.\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc ϕ) \"(HPC & Hpc_a & Hr2 & Hdst) Hφ\".\n    iDestruct (map_of_regs_3 with \"HPC Hr2 Hdst\") as \"[Hmap (%&%&%)]\".\n    iApply (wp_AddSubLt with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC dst) // insert_insert (insert_commute _ r2 dst) //\n              (insert_commute _ PC dst) // insert_insert. \n      iDestruct (regs_of_map_3 with \"Hmap\") as \"(?&?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n      destruct e1; try congruence. \n      inv Hvpc. destruct H5 as [? | [? | [? | [? | ?]]]]; destruct H12 as [? | [? | ?]]; congruence. }\n  Qed.\n\n  Lemma wp_add_sub_lt_success_r_dst E dst pc_p pc_g pc_b pc_e pc_a w ins r1 n1 n2 pc_a' :\n    decodeInstrW w = ins →\n    is_AddSubLt ins dst (inr r1) (inr dst) →\n    (pc_a + 1)%a = Some pc_a' →\n    isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) ->\n\n    {{{ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ pc_a ↦ₐ w\n        ∗ r1 ↦ᵣ inl n1\n        ∗ dst ↦ᵣ inl n2\n    }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ r1 ↦ᵣ inl n1\n          ∗ dst ↦ᵣ inl (denote ins n1 n2)\n      }}}.\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc ϕ) \"(HPC & Hpc_a & Hr2 & Hdst) Hφ\".\n    iDestruct (map_of_regs_3 with \"HPC Hr2 Hdst\") as \"[Hmap (%&%&%)]\".\n    iApply (wp_AddSubLt with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC dst) // insert_insert (insert_commute _ r1 dst) //\n              (insert_commute _ PC dst) // insert_insert.\n      iDestruct (regs_of_map_3 with \"Hmap\") as \"(?&?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n      destruct e1; try congruence. \n      inv Hvpc. destruct H5 as [? | [? | [? | [? | ?]]]]; destruct H12 as [? | [? | ?]]; congruence. }\n  Qed.\n\n  Lemma wp_add_sub_lt_success_dst_dst E dst pc_p pc_g pc_b pc_e pc_a w ins n pc_a' :\n    decodeInstrW w = ins →\n    is_AddSubLt ins dst (inr dst) (inr dst) →\n    (pc_a + 1)%a = Some pc_a' →\n    isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) ->\n\n    {{{ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n        ∗ pc_a ↦ₐ w\n        ∗ dst ↦ᵣ inl n\n    }}}\n      Instr Executable @ E\n      {{{ RET NextIV;\n          PC ↦ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n          ∗ pc_a ↦ₐ w\n          ∗ dst ↦ᵣ inl (denote ins n n)\n      }}}.\n  Proof.\n    iIntros (Hdecode Hinstr Hpc_a Hvpc ϕ) \"(HPC & Hpc_a & Hdst) Hφ\".\n    iDestruct (map_of_regs_2 with \"HPC Hdst\") as \"[Hmap %]\".\n    iApply (wp_AddSubLt with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n    by erewrite regs_of_is_AddSubLt; eauto; rewrite !dom_insert; set_solver+.\n    iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC dst) // insert_insert insert_commute // insert_insert.\n      iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; try incrementPC_inv; simplify_map_eq; eauto.\n      destruct e1; try congruence.\n      inv Hvpc. destruct H3 as [? | [? | [? | [? | ?]]]]; destruct H10 as [? | [? | ?]]; congruence. }\n  Qed.\n\nEnd cap_lang_rules.\n\n(* Hints to automate proofs of is_AddSubLt *)\nLemma is_AddSubLt_Add dst arg1 arg2 :\n  is_AddSubLt (machine_base.Add dst arg1 arg2) dst arg1 arg2.\nProof. intros; unfold is_AddSubLt; eauto. Qed.\nLemma is_AddSubLt_Sub dst arg1 arg2 :\n  is_AddSubLt (Sub dst arg1 arg2) dst arg1 arg2.\nProof. intros; unfold is_AddSubLt; eauto. Qed.\nLemma is_AddSubLt_Lt dst arg1 arg2 :\n  is_AddSubLt (Lt dst arg1 arg2) dst arg1 arg2.\nProof. intros; unfold is_AddSubLt; eauto. Qed.\n\nGlobal Hint Resolve is_AddSubLt_Add : core.\nGlobal Hint Resolve is_AddSubLt_Sub : core.\nGlobal Hint Resolve is_AddSubLt_Lt : core.\n", "meta": {"author": "logsem", "repo": "cerise-stack-monotone", "sha": "dff1909f6abc6de99c28d8f12e903b98dd76fb41", "save_path": "github-repos/coq/logsem-cerise-stack-monotone", "path": "github-repos/coq/logsem-cerise-stack-monotone/cerise-stack-monotone-dff1909f6abc6de99c28d8f12e903b98dd76fb41/theories/rules/rules_AddSubLt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.21431268741985512}}
{"text": "From mtl.Classes Require Import Monad.\n\nRecord Identity (a : Type) : Type :=\n  MkIdentity { runIdentity : a }.\n\nArguments MkIdentity {a} _.\nArguments runIdentity {a} _.\n\nLemma injective_runIdentity {a} (u v : Identity a)\n  : runIdentity u = runIdentity v -> u = v.\nProof.\n  destruct u, v; intros; f_equal; auto.\nQed.\n\nInstance Monad_Identity : Monad Identity :=\n  { pure _ := MkIdentity\n  ; bind _ _ u k := k (runIdentity u)\n  }.\n\nInstance LawfulMonad_Identity : LawfulMonad Identity.\nProof.\n  split; intros; apply injective_runIdentity; reflexivity.\nQed.\n", "meta": {"author": "Lysxia", "repo": "coq-mtl", "sha": "fd36ee27fd9e6191a506b08dc72dd598dd9f1c74", "save_path": "github-repos/coq/Lysxia-coq-mtl", "path": "github-repos/coq/Lysxia-coq-mtl/coq-mtl-fd36ee27fd9e6191a506b08dc72dd598dd9f1c74/theories/Monads/Identity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.21425416085561969}}
{"text": "(* PREAMBLE *)\n\nFrom compcert.common     Require Memory.\nFrom compcert.cfrontend  Require Csem.\nFrom compcert.lib        Require Coqlib.\n\nFrom trancert.lib        Require All.\nFrom trancert.properties Require memory.Assign Env.\n\nImport Csem Memory Mem Coqlib Tac lib.All Assign properties.Env.\n\n(** [bind_parameters] does not change memory size ([nextblock]). *)\n\nTheorem bind_parameters_nextblock:\n  forall ge e1 m1 ps vs m2,\n    bind_parameters ge e1 m1 ps vs m2 ->\n    nextblock m1 = nextblock m2.\nProof.\n  intros ge e1 m1 ps vs m2 H.\n  induction H;auto.\n  eapply assign_loc_nextblock in H0; eauto.\n  rewrite <-IHbind_parameters, H0. reflexivity.\nQed.\n\n\nTheorem bind_parameters_env_freeable_any:\n  forall (ge:genv) e m1 e' params vargs m2,\n    env_freeable ge m1 e  ->\n    bind_parameters ge e' m1 params vargs m2 ->\n    env_freeable ge m2 e.\nProof.\n  intros ge e m1 e' params vargs m2 H H0.\n  unfold env_freeable in *.\n  induction H0; eauto.\n  apply IHbind_parameters.\n  intros i b0 t0 H3 delta Hdelta.\n  eapply assign_loc_perm; eauto.\n  eapply H; eauto.\nQed.\n", "meta": {"author": "sayon", "repo": "trancert", "sha": "eb5c94c75067782158522f61bdd7cc902bf74185", "save_path": "github-repos/coq/sayon-trancert", "path": "github-repos/coq/sayon-trancert/trancert-eb5c94c75067782158522f61bdd7cc902bf74185/properties/memory/BindParameters.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.21425416085561969}}
{"text": "From Coq Require Import String HexString ZArith.\nFrom Vyper Require Import Config.\nFrom Vyper.L50 Require Import Types.\n\nInductive expr {C: VyperConfig}\n:= FunCall (name: string) (args: list expr) \n | LocVar (name: string)\n | Const (t: yul_type) (val: yul_value t).\n\nDefinition typename: Type := yul_type * string.\n\nInductive stmt {C: VyperConfig}\n:= BlockStmt (s: block)\n | VarDecl (vars: list typename) (init: option expr)\n | Assign (lhs: list string) (rhs: expr)\n | If (cond: expr) (body: block)\n | Expr (e: expr)\n | Switch (e: expr) (cases: list case) (default: option block)\n | For (init: block) (cond: expr) (after body: block)\n | Break\n | Continue\n | Leave\nwith case  {C: VyperConfig} := Case (t: yul_type) (val: yul_value t) (body: block)\nwith block {C: VyperConfig} := Block (body: list stmt).\n\nRecord fun_decl {C: VyperConfig} := {\n  fd_name: string;\n  fd_inputs: list typename;\n  fd_outputs: list typename;\n  fd_body: block;\n}.\n\nDefinition program {C: VyperConfig}: Type := string_map fun_decl * block.\n\n\nDefinition is_var_decl {C: VyperConfig} (s: stmt)\n:= match s with\n   | VarDecl _ _ => true\n   | _ => false\n   end.\n\nProgram Definition var_decl_unpack {C: VyperConfig} (s: stmt) (IsVarDecl: is_var_decl s = true)\n: list typename * option expr\n:= match s with\n   | VarDecl vars init => (vars, init)\n   | _ => False_rect _ _\n   end.\nNext Obligation.\ndestruct s; cbn in IsVarDecl; try discriminate.\nexact (H vars init eq_refl).\nQed.\n\n(****************************   print   ******************************)\n\nLocal Open Scope list_scope.\nLocal Open Scope string_scope.\n\nFixpoint to_comma_list {A} (s: A -> string) (l: list A)\n: string\n:= match l with\n   | nil => \"\"\n   | x :: nil => s x\n   | h :: t => s h ++ \", \" ++ to_comma_list s t\n   end.\n\nDefinition string_of_typename (tn: typename)\n:= let '(t, n) := tn in\n   n ++ \":\" ++ string_of_type t.\n\nDefinition string_of_yul_value {C: VyperConfig} {t: yul_type} (v: yul_value t)\n:= match v with\n   | NumberValue _ value _ => HexString.of_Z (Z_of_uint256 value)\n   | BoolValue _ true _ => \"true\"\n   | BoolValue _ false _ => \"false\"\n   end.\n\nFixpoint string_of_expr {C: VyperConfig} (e: expr)\n:= match e with\n   | FunCall name args => (name ++ \"(\" ++\n                          (* Coq won't allow to_comma_list here *)\n                          (fix string_of_exprs (l: list expr) :=\n                             match l with\n                             | nil => \"\"\n                             | x :: nil => string_of_expr x\n                             | h :: t => string_of_expr h ++ \", \" ++ string_of_exprs t\n                             end) args\n                            ++ \")\")%string\n   | LocVar name => name\n   | Const t v => string_of_yul_value v ++ \":\" ++ string_of_type t\n   end.\n\nDefinition attach (a b: list string)\n: list string\n:= match b with\n   | nil => a\n   | hb :: tb =>\n     let a' := List.rev a in\n       match a' with\n       | nil => b\n       | ha :: ta => List.rev ta ++ (ha ++ \" \" ++ hb) :: tb\n       end\n   end.\n\nFixpoint lines_of_stmt {C: VyperConfig} (s: stmt)\n: list string\n:= match s with\n   | BlockStmt b => lines_of_block b\n   | VarDecl vars init => (\"let \" ++ to_comma_list string_of_typename vars\n                             ++ match init with\n                                | Some e => \" := \" ++ string_of_expr e\n                                | None => \"\"\n                                end) :: nil\n   | Assign lhs rhs => (to_comma_list id lhs ++ \" := \" ++ string_of_expr rhs) :: nil\n   | If cond body => (\"if \" ++ string_of_expr cond) :: lines_of_block body\n   | Expr e => string_of_expr e :: nil\n   | Switch e cases default =>\n      (\"switch \" ++ string_of_expr e) ::\n      (fix lines_of_cases (l: list case): list string :=\n        match l with\n        | nil => nil\n        | h :: t => (lines_of_case h ++ lines_of_cases t)%list\n        end) cases ++\n       match default with\n       | None => nil\n       | Some def => \"default\" :: lines_of_block def\n       end\n   | For init cond inc body => attach (\"for\" :: nil)\n                                      (attach (lines_of_block init)\n                                              (attach (string_of_expr cond :: nil)\n                                                      (lines_of_block inc)))\n                                ++ lines_of_block body\n   | Break => \"break\" :: nil\n   | Continue => \"continue\" :: nil\n   | Leave => \"leave\" :: nil\n   end\nwith lines_of_case {C: VyperConfig} (c: case)\n: list string\n:= let '(Case t v body) := c in\n   (\"case \" ++ string_of_yul_value v ++ \":\" ++ string_of_type t) :: lines_of_block body\nwith lines_of_block {C: VyperConfig} (b: block)\n: list string\n:= let fix lines_of_stmts (l: list stmt) :=\n          match l with\n          | nil => nil\n          | h :: t => (lines_of_stmt h ++ lines_of_stmts t)%list\n          end in\n   let '(Block stmts) := b in\n   let lines := lines_of_stmts stmts in\n   match lines with\n   | nil => \"{}\" :: nil\n   | line :: nil => (\"{ \" ++ line ++ \" }\") :: nil\n   | _ => \"{\" :: List.map (fun x => \"    \" ++ x) lines ++ \"}\" :: nil\n   end.\n\n(** Name override is needed because fd_name not properly mangled.\n    (Actually fun_decl has no reason to store its name at all.)\n *)\nDefinition lines_of_fun_decl {C: VyperConfig} (fd: fun_decl) (override_name: string)\n:= (\"function \" ++ override_name ++ \n      \"(\" ++ to_comma_list string_of_typename (fd_inputs fd) ++ \")\" ++\n      match fd_outputs fd with\n      | nil => \"\"\n      | _ => \" -> \" ++ to_comma_list string_of_typename (fd_outputs fd)\n      end)\n   :: lines_of_block (fd_body fd).\n\nDefinition lines_of_fun_decls {C: VyperConfig} (decls: string_map fun_decl)\n:= let _ := string_map_impl in\n   (fix lines_of_alist (l: list (string * fun_decl))\n    := match l with\n       | nil => nil\n       | h :: t => let '(k, v) := h in (lines_of_fun_decl v k ++ lines_of_alist t)%list\n       end) (Map.items decls).\n", "meta": {"author": "formalize", "repo": "coq-vyper", "sha": "8996c1534b9d56696f92b60031ff1523b3593690", "save_path": "github-repos/coq/formalize-coq-vyper", "path": "github-repos/coq/formalize-coq-vyper/coq-vyper-8996c1534b9d56696f92b60031ff1523b3593690/L50/AST.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.21425416085561969}}
{"text": "From Undecidability Require Import L.Util.L_facts.\n\nFrom Undecidability.Shared.Libs.PSL Require Import FinTypes Vectors.\nRequire Import List.\n\nRequire Import Undecidability.TM.Util.TM_facts.\n\nFrom Undecidability Require Import ProgrammingTools LM_heap_def WriteValue CaseList Copy ListTM Hoare.\nFrom Undecidability.TM.L Require Import JumpTargetTM Alphabets M_LHeapInterpreter.\nFrom Undecidability Require Import L.AbstractMachines.FlatPro.LM_heap_correct.\n\nRequire Import List.\n\nImport Vector.VectorNotations.\nImport ListNotations ResourceMeasures.\n\n\nFrom Undecidability.TM.L Require Import UnfoldClos.\n\nImport CasePair Code.CaseList.\n\nSet Default Proof Using \"Type\".\n\n\nModule EvalL.\nSection Fix.\n\n  Variable Σ : finType.\n\n  Definition Σintern :Type := sigStep + sigList (sigPair sigHClos sigNat).\n\n\n  Context (retr_eval : Retract Σintern Σ) (retr_pro : Retract sigPro Σ).\n\n\n  Definition retr_unfolder : Retract (sigList (sigPair sigHClos sigNat)) Σ := ComposeRetract retr_eval _.\n  Definition retr_interpreter : Retract sigStep Σ := ComposeRetract retr_eval _.\n\n  Local Instance retr_closs_intrp : Retract (sigList (sigHClos)) Σ := ComposeRetract retr_interpreter _.\n  Local Instance retr_clos_intrp : Retract sigHClos Σ := ComposeRetract retr_closs_intrp _.\n  Local Instance retr_pro_intrp : Retract sigPro Σ := ComposeRetract retr_clos_intrp _.\n  \n  Local Instance retr_nat_clos_ad' : Retract sigNat sigHClos := Retract_sigPair_X _ (Retract_id _).\n  Local Instance retr_nat_clos_ad : Retract sigNat Σ := ComposeRetract _ retr_nat_clos_ad'.\n  Local Instance retr_heap : Retract sigHeap Σ := ComposeRetract retr_interpreter _.\n\n\n  (*\n    auxiliary tapes:\n\n    0    : T\n    1    : V\n    2    : H\n    3-4  : aux for init\n    5-12 : aux for loop\n    13   : t\n   *)\n   \n  Definition M : pTM (Σ^+) unit 11 :=\n    Translate retr_pro retr_pro_intrp @ [|Fin0|];;\n    CopyValue _ @ [|Fin0;Fin1|];;\n    Reset _ @[|Fin0|];;\n    WriteValue 0 ⇑ retr_nat_clos_ad @ [| Fin0|];;\n    Constr_pair _ _ ⇑ retr_clos_intrp @ [|Fin0;Fin1|];;\n    Reset _ @ [|Fin0|];;\n    WriteValue ( []%list) ⇑ retr_closs_intrp @ [| Fin0|];;\n    Constr_cons _ ⇑ retr_closs_intrp @ [|Fin0;Fin1|];;\n    Reset _ @ [|Fin1|];;\n    WriteValue ( []%list) ⇑ retr_closs_intrp @ [| Fin1|];;\n    WriteValue ( []%list ) ⇑ retr_heap @ [| Fin2|];;\n    M_LHeapInterpreter.Loop ⇑ retr_interpreter;;\n    Reset _ @ [|Fin0|];;\n    CaseList _ ⇑ retr_closs_intrp @ [| Fin1;Fin0 |];;\n    Reset _ @ [|Fin1|];;\n    UnfoldClos.M retr_unfolder retr_heap retr_clos_intrp @ [| Fin0;Fin2;Fin1;Fin3;Fin4;Fin5;Fin6;Fin7;Fin8;Fin9|];;\n    Reset _ @ [|Fin2|];;\n    Translate (UnfoldClos.retr_pro _) retr_pro @ [|Fin0|].\n\n  \n  Arguments \"+\" : simpl never.\n  Arguments \"*\" : simpl never.\n\n  Definition steps (s : term) (k:nat) (t:term) Hcl (HR:evalIn k s t):=\n    1 + Translate_steps (compile s) +\n    (1 + CopyValue_steps (compile s) +\n    (1 + Reset_steps (compile s) +\n      (1 + WriteValue_steps (size 0) +\n      (1 + Constr_pair_steps 0 +\n        (1 + Reset_steps 0 +\n        (1 + WriteValue_steps (size []%list) +\n          (1 + Constr_cons_steps (0, compile s) +\n          (1 + Reset_steps (0, compile s) +\n            (1 + WriteValue_steps (size []%list) +\n            (1 + WriteValue_steps (size []%list) +\n              (1 + Loop_steps [(0, compile s)] [] []%list (3 * k + 1) +\n              (1 + Reset_steps []%list +\n                let (g,tmp) := completenessTimeInformative (proj2 (timeBS_evalIn _ _ _) HR) Hcl in\n                let (H,_):= tmp in\n                (1 + CaseList_steps [g] +\n                (1 + Reset_steps []%list +\n                  (1 + UnfoldClos.steps H g t +\n                  (1 + Reset_steps H + Translate_steps (compile t))))))))))))))))).\n  Arguments steps : clear implicits.\n\n  Lemma SpecT s k t (Hcl: closed s) (HR:evalIn k s t):\n    TripleT ≃≃([],[|Contains retr_pro (compile s)|] ++ Vector.const Void _)\n      (steps s k t Hcl HR) M\n      (fun _ => ≃≃([],[|Contains retr_pro (compile t)|] ++ Vector.const Void _)).\n  Proof.\n    unfold steps. destruct completenessTimeInformative as (g&H&?&?). clear HR.\n    eapply ConsequenceT_pre. 2:reflexivity.\n    unfold M.\n    do 11 (hstep_seq;[]). cbn.\n    hstep_seq;[| | ] .\n    { refine (TripleT_RemoveSpace _). intros. eapply Interpreter_SpecT. eassumption. inversion 1. }\n    now cbn; tspec_ext.\n    do 2 (hstep_seq;[]).\n    hintros _ _.\n    hstep_seq;[].\n    hstep_seq;[|].\n    { eapply UnfoldClos.SpecT. eassumption. }\n    cbn.\n    do 2 (hstep_seq;[]). reflexivity.\n    unfold steps. reflexivity.\n  Qed.\n\n  \n  Lemma Spec s :\n   closed s -> \n    Triple ≃≃([],[|Contains retr_pro (compile s)|] ++ Vector.const Void _)\n      M\n      (fun _ t => exists s', t ≃≃ ([s ⇓ s']%list,[|Contains retr_pro (compile s')|] ++ Vector.const Void _)).\n  Proof.\n    intros cls.\n    unfold M.\n    do 11 (hstep_seq;[]). cbn.\n    hstep.\n    {\n      eapply Consequence with (Q1:= fun y => _) (Q2:= fun y => _).\n      eapply ChangeAlphabet_Spec_ex with (Q:= fun y x => _) (Q':= fun y x => _) (Ctx:= fun x (H:Prop) => (steps_k (snd x) _ (fst x) /\\ halt_state (fst x)) /\\\n        (fst (fst (fst x)) = []%list ->\n        H)).\n      now refine (Interpreter_Spec [(0,compile s)] [] [])%list. now unfold \"==>\",Proper,Basics.impl. now cbn; tspec_ext. cbn;intros _. apply reflexivity.\n    }\n    cbn. intros _.\n    eapply Triple_exists_pre. intros [[[T' V'] H'] k'];cbn.\n    eapply Triple_and_pre. intros [HR Hhalt].\n    unfold steps_k in*.\n    edestruct soundness with (1:=cls) as (?&?&?&Heq&?&?). {split. now eapply pow_star. eassumption. }\n    injection Heq as [= -> -> ->].\n    eapply Triple_forall_pre. exists eq_refl.\n    do 2 (hstep_seq;[]).\n    hintros ? _.\n    do 2 hstep_seq;[|].\n    { refine (TripleT_Triple _). refine (UnfoldClos.SpecT _ _ _ _). eassumption. }\n    cbn.\n    hstep_seq.\n    eapply Triple_exists_con. eexists _.\n    change (fun x => ?h x) with h.\n    eapply Consequence_post.\n    now hsteps_cbn.\n    cbn. intros _. tspec_ext. easy.\n  Qed.\n\nEnd Fix.\nEnd EvalL.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/TM/L/Eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.213975953615547}}
{"text": "Require Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Globalenvs.\nRequire Import Events.\nRequire Import Smallstep.\nRequire Import Axioms.\nRequire Import Floats.\nRequire Import Asm.\nRequire Import Values.\nRequire Import Memory.\n\nRequire Import PeekTactics.\nRequire Import PregTactics.\nRequire Import PeekLib.\nRequire Import AsmCallingConv.\nRequire Import AsmBits.\nRequire Import MemoryAxioms.\nRequire Import ValEq.\nRequire Import MemEq.\nRequire Import UseBasic.\n\nRequire Import NoPtr.\n\nRequire Import MemBits.\nRequire Import Maps.\n\nLemma val_eq_longofwords :\n  forall v1 v2 v1' v2',\n    val_eq v1 v2 ->\n    val_eq v1' v2' ->\n    val_eq (Val.longofwords v1 v1') (Val.longofwords v2 v2').\nProof.\n  intros. unfold val_eq in *.\n  repeat break_match_hyp; try inv_false; subst; simpl;\n  intros; try congruence;\n  unfold Val.longofwords;\n  repeat break_match; try congruence.\nQed.\n\n\nLemma eval_annot_arg_rs :\n  forall (prog : AST.program fundef unit) a (s1 s2 : preg -> Values.val) m b md,\n    eval_annot_arg_bits md (Genv.globalenv prog) s1 (s1 (IR ESP)) m a b ->\n    forall m',\n    mem_eq md m m' ->\n    (val_eq (s1 ESP) (s2 ESP)) ->\n    (forall r, In r (get_annot_preg a) -> val_eq (s1 r) (s2 r)) ->\n    exists b',\n      eval_annot_arg_bits md (Genv.globalenv prog) s2 (s2 (IR ESP)) m' a b' /\\ val_eq b b'.\nProof.\n  \n  induction 1; intros;\n  try solve [  \n        eexists; split; try econstructor; eauto;\n        eapply H1; simpl; intuition idtac].\n\n  \n  * rewrite H in H3. simpl in H3. rewrite <- H3 in *.\n    unfold Mem.loadv in *.\n    simpl in *.\n    app eq_mem_load H1. break_and.\n    exists x.\n    split; auto. econstructor; eauto.\n  * app val_eq_or H0.\n    break_or. \n    destruct (Val.add (s2 ESP) (Vint ofs)) eqn:?;\n    exists (Val.add (s2 ESP) (Vint ofs));\n    split; try econstructor; eauto;\n    rewrite H3; simpl; eauto;\n    try solve [intros; congruence].\n           unfold Val.add in Heqv.\n           break_match_hyp; try congruence.\n           rewrite H3 in H2. simpl in H2.\n           congruence.\n    exists (Val.add (s2 ESP) (Vint ofs)).\n    split. econstructor; eauto. \n    unfold Val.add.\n    break_match; simpl; try rewrite <- H3; eauto;\n    intros; congruence.\n  * unfold Mem.loadv in *. simpl in *.\n    break_match_hyp; try congruence.\n    app eq_mem_load H. break_and.\n    exists x.\n    split; eauto.\n    econstructor; eauto.\n    unfold Mem.loadv.\n    find_rewrite. eauto.\n  * exists Vundef.\n           split; simpl; eauto.\n           econstructor; eauto.\n           intros. congruence.\n  * \n  edestruct IHeval_annot_arg_bits1; eauto.\n  intros. eapply H3. simpl.\n  rewrite in_app. left. eauto.\n  break_and.\n  edestruct IHeval_annot_arg_bits2; eauto.\n  intros. eapply H3. simpl.\n  rewrite in_app. right. eauto.\n  break_and.\n  eexists. split. econstructor; eauto.\n  eapply val_eq_longofwords; eauto.\n\nQed.\n\nLemma list_forall2_annot:\n  forall (prog : AST.program fundef unit) s1 s2 args vargs ef m m' md,\n    list_forall2 (eval_annot_arg_bits md (Genv.globalenv prog) s1 (s1 (IR ESP)) m) args vargs ->\n    (forall p, In p (use (Pannot ef args)) -> val_eq (s1 p) (s2 p)) ->\n    mem_eq md m m' ->\n    exists vargs',\n      list_forall2 (eval_annot_arg_bits md (Genv.globalenv prog) s2 (s2 (IR ESP)) m') args vargs' /\\ list_forall2 val_eq vargs vargs'.\nProof.\n  intros. induction H;\n    try solve [eexists; split; econstructor; eauto].\n  app eval_annot_arg_rs H;\n    try eapply H0;\n    repeat break_and.\n\n  Focus 2. simpl. right. left. eauto.\n  Focus 2. intros. apply H0. simpl.\n  right. right. rewrite in_app. left. auto.\n  destruct (IHlist_forall2).\n  intros. apply H0. simpl. \n  rewrite in_app. simpl in H5.\n  intuition idtac.\n  break_and. exists (x :: x0).\n  split; econstructor; eauto.\nQed.\n\nLtac unify_all :=\n  try unify_psur;\n  simpl in *;\n  try unify_find_funct_ptr;\n  simpl in *;\n  try unify_find_instr;\n  simpl in *.\n\nFixpoint getres (res : list preg) (vl : list Values.val) : list preg :=\n  match res with\n    | nil => nil\n    | f :: r =>\n      match vl with\n        | nil => nil\n        | x :: y => f :: getres r y\n      end\n  end.\n\nLemma set_regs_gnot_in :\n  forall res vl x,\n    ~ (In x (getres res vl)) ->\n    forall rs,\n      (set_regs res vl rs) x = rs x.\nProof.\n  induction res; intros.\n  simpl. reflexivity.\n  simpl in H. break_match_hyp; simpl in H.\n  subst vl. simpl. reflexivity.\n  eapply Decidable.not_or in H.\n  break_and. simpl.\n  rewrite IHres by eauto.\n  preg_simpl. reflexivity.\nQed.\n  \nLemma set_regs_gin :\n  forall res vl x,\n    In x (getres res vl) ->\n    forall rs rs',\n      (set_regs res vl rs) x = (set_regs res vl rs') x.\nProof.\n  induction res; intros.\n  simpl in H. inv H.\n  simpl in H. break_match_hyp; simpl in H; try solve [inv H].\n  destruct (in_dec preg_eq x (getres res l)).\n  simpl. apply IHres. eauto.\n  simpl. repeat rewrite set_regs_gnot_in by eauto.\n  break_or; try congruence.\n  preg_simpl. reflexivity.\nQed.\n\nLemma undef_regs_undef :\n  forall l x rs,\n    In x l ->\n    undef_regs l rs x = Values.Vundef.\nProof.\n  induction l; intros.\n  simpl in H. inv_false.\n  simpl in H.\n  destruct (in_dec preg_eq x l).\n  simpl. rewrite IHl; eauto.\n  break_or; try congruence.\n  simpl. rewrite undef_regs_not_in; eauto.\n  preg_simpl. reflexivity.\nQed.\n\nLemma val_eq_list_lessdef :\n  forall a a',\n    list_forall2 val_eq a a' ->\n    Val.lessdef_list a a'.\nProof.\n  induction 1; intros;\n  econstructor; eauto.\n  eapply val_eq_lessdef; eauto.\nQed.\n\nLemma no_ptr_nextinstr_nf :\n  forall rs,\n    (forall x, ~ In x flags -> forall b i, rs x <> Vptr b i) ->\n    no_ptr_regs (nextinstr_nf rs).\nProof.\n  intros. unfold no_ptr_regs.\n  intros. unfold nextinstr_nf.\n  unfold nextinstr. simpl.\n  repeat preg_case; try congruence.\n  name (H PC) HPC.\n  unfold Val.add. repeat break_match; try congruence.\n  unfold Vone in *. congruence.\n  unfold Vone in *. inv Heqv0.\n  exfalso. eapply HPC. simpl. intuition idtac; try congruence.\n  reflexivity. eapply H. simpl. intuition idtac.\nQed.\n\nLemma set_regs_either :\n  forall res rs l reg,\n    set_regs res l rs reg = rs reg \\/\n    exists v, set_regs res l rs reg = v /\\ In v l.\nProof.\n  induction res; intros.\n  left. simpl. reflexivity.\n  simpl. break_match. left. reflexivity.\n  subst l. simpl.\n  destruct (in_dec preg_eq reg (getres res l0)).\n  erewrite set_regs_gin; eauto.\n  instantiate (1 := rs).\n  specialize (IHres rs l0 reg).\n  destruct IHres. left. auto.\n  right. break_exists. exists x. break_and. split; auto.\n  rewrite set_regs_gnot_in; eauto.\n  clear IHres. clear n.\n  preg_case. right. eauto.\n  left. eauto.\nQed.\n\nLemma encode_long_no_ptr :\n  forall v v' x t,\n    val_eq v v' ->\n    In x (encode_long t v') ->\n    forall b i,\n      x <> Vptr b i.\nProof.\n  intros. unfold encode_long in *.\n  unfold val_eq in *.\n  destruct v; simpl in H; try inv_false; try subst v';\n  repeat break_match_hyp; simpl in *; repeat break_or; try inv_false;\n  eauto; try congruence. unfold Val.hiword. break_match; try congruence.\n  unfold Val.loword. break_match; try congruence.  \nQed.\n\nLemma global_perms_mem_eq :\n  forall md m m',\n    mem_eq md m m' ->\n    forall ge,\n      global_perms ge m ->\n      global_perms ge m'.\nProof.\n  intros.\n  unfold global_perms in *.\n  intros. app H0 H1.\n  break_and.\n  unfold mem_eq in *.\n  repeat break_and.\n  app H6 H1.\nQed.\n\nLemma list_forall2_inv_right :\n  forall {A : Type} (P : A -> A -> Prop) (l l' : list A),\n    list_forall2 P l l' ->\n    forall x,\n      In x l' ->\n      exists y,\n        In y l /\\ P y x.\nProof.\n  induction 1; intros.\n  simpl in H. inv_false.\n  simpl in H1.\n  break_or. simpl. exists a1.\n  split; auto.\n  app IHlist_forall2 H2.\n  exists x0. simpl.\n  split. right. break_and. auto.\n  break_and. auto.\nQed.\n\nLemma list_forall2_map :\n  forall l (rs rs' : regset),\n    (forall r, In r l -> val_eq (rs r) (rs' r)) ->\n      list_forall2 val_eq (map rs l) (map rs' l).\nProof.\n  induction l; intros.\n  simpl. econstructor.\n  simpl. econstructor. eapply H. simpl. left. auto.\n  eapply IHl. intros. eapply H. simpl. right. auto.\nQed.\n\nLemma val_eq_hiword :\n  forall v v',\n    val_eq v v' ->\n    val_eq (Val.hiword v) (Val.hiword v').\nProof.\n  intros.\n  unfold val_eq in H.\n  break_match_hyp; subst; simpl; eauto;\n  try congruence.\n  intros. unfold Val.hiword.\n  break_match; congruence.\nQed.\n\nLemma val_eq_loword :\n  forall v v',\n    val_eq v v' ->\n    val_eq (Val.loword v) (Val.loword v').\nProof.\n  intros.\n  unfold val_eq in H.\n  break_match_hyp; subst; simpl; eauto;\n  try congruence.\n  unfold Val.loword; break_match; congruence.\nQed.\n\nLemma set_regs_efres:\n  forall ef p r v v' rs rs',\n    In p r ->\n    (forall p0, In p0 (efres ef r) -> val_eq (rs p0) (rs' p0)) ->\n    val_eq v v' ->\n    val_eq ((set_regs r (encode_long (sig_res (ef_sig ef)) v) rs) p) ((set_regs r (encode_long (sig_res (ef_sig ef)) v') rs') p).\nProof.\n  induction r; intros.\n  * simpl in H. inv H.\n  * unfold efres in *; simpl in H0; repeat break_match_hyp.\n    \n    simpl. repeat rewrite set_regs_nil. \n    \n    destruct (preg_eq p a). subst. simpl. \n    repeat rewrite set_regs_nil. repeat rewrite Pregmap.gss.\n    assumption.\n\n    simpl. repeat rewrite set_regs_nil. repeat rewrite Pregmap.gso by auto.\n    apply H0. simpl in H. destruct H. congruence. assumption.\n\n    destruct (preg_eq p a). subst. simpl. \n    repeat rewrite set_regs_nil. repeat rewrite Pregmap.gss.\n    assumption.\n\n    simpl. repeat rewrite set_regs_nil. repeat rewrite Pregmap.gso by auto.\n    apply H0. simpl in H. destruct H. congruence. assumption.\n\n    destruct (preg_eq p a). subst. simpl.\n    destruct r. simpl. repeat rewrite Pregmap.gss.\n    eapply val_eq_hiword; assumption.\n    \n    simpl. repeat rewrite set_regs_nil.\n    destruct (preg_eq p a). subst. repeat rewrite Pregmap.gss.\n    eapply val_eq_loword; assumption.\n    rewrite Pregmap.gso by auto.\n    rewrite Pregmap.gss.\n    rewrite Pregmap.gso by auto.\n    rewrite Pregmap.gss.\n\n    eapply val_eq_hiword; assumption.\n    \n    destruct r. simpl.\n    repeat rewrite Pregmap.gso by auto.\n    simpl in H. destruct H. congruence. inv H.\n    destruct (preg_eq p p0).\n    simpl. repeat rewrite set_regs_nil.\n    subst. rewrite Pregmap.gss. rewrite Pregmap.gss.\n\n    eapply val_eq_loword; assumption.\n    simpl. repeat rewrite set_regs_nil.\n    repeat rewrite Pregmap.gso by auto.\n    apply H0. simpl. simpl in H.\n    destruct H. congruence. destruct H. congruence.\n    assumption.\n\n    destruct (preg_eq p a). subst. simpl.\n    repeat rewrite set_regs_nil. repeat rewrite Pregmap.gss.\n    assumption.\n\n    simpl. repeat rewrite set_regs_nil. repeat rewrite Pregmap.gso by auto.\n    apply H0. simpl in H. destruct H. congruence. assumption.\n\n    destruct (preg_eq p a). subst. simpl.\n    repeat rewrite set_regs_nil. repeat rewrite Pregmap.gss.\n    assumption.\n    \n    simpl. repeat rewrite set_regs_nil. repeat rewrite Pregmap.gso by auto.\n    apply H0. simpl in H. destruct H. congruence. assumption.\n\n    destruct (preg_eq p a). subst. simpl.\n    repeat rewrite set_regs_nil. repeat rewrite Pregmap.gss.\n    assumption.\n    \n    simpl. repeat rewrite set_regs_nil. repeat rewrite Pregmap.gso by auto.\n    apply H0. simpl in H. destruct H. congruence. assumption.\n\n    destruct (preg_eq p a). subst. simpl.\n    repeat rewrite set_regs_nil. repeat rewrite Pregmap.gss.\n    assumption.\n\n    simpl. repeat rewrite set_regs_nil. repeat rewrite Pregmap.gso by auto.\n    apply H0. simpl in H. destruct H. congruence. assumption.\nQed.\n\nLtac invs2 :=\n  match goal with\n    | [ H : step_bits _ _ _ _, H2 : step_bits _ _ _ _ |- _ ] => inv_step H; inv_step H2\n  end.\n\nLemma val_eq_set_regs :\n  forall v v',\n    list_forall2 val_eq v v' ->\n    forall r rs rs' p,\n      val_eq (rs p) (rs' p) ->\n      val_eq (set_regs r v rs p)\n             (set_regs r v' rs' p).\nProof.\n  intros v v' H.\n  induction H; intros.\n  repeat rewrite set_regs_nil. eauto.\n  destruct r; simpl. eauto.\n  eapply IHlist_forall2; eauto.\n  preg_case; try subst; eauto.\nQed.\n\nLemma val_eq_undef_regs :\n  forall rs rs' p,\n    val_eq (rs p) (rs' p) ->\n    forall l,\n      val_eq (undef_regs l rs p) (undef_regs l rs' p).\nProof.\n  induction l; intros. simpl. eauto.\n  simpl.\n  destruct (in_dec preg_eq p l).\n  erewrite undef_regs_in with (rs' := rs); eauto.\n  erewrite undef_regs_in with (rs := rs' # a <- Values.Vundef)(rs' := rs'); eauto.\n  repeat rewrite undef_regs_not_in; eauto.\n  preg_case; simpl; eauto.\n  congruence.\nQed.\n\n\n\nLemma val_eq_decode_longs :\n  forall sg l l',\n    list_forall2 val_eq l l' ->\n    list_forall2 val_eq (decode_longs sg l)\n                   (decode_longs sg l').\nProof.\n  induction sg; intros; simpl; repeat break_match; subst; try solve [econstructor];\n  inv H;\n  try solve [\n        econstructor; eauto;\n        eapply IHsg; eauto].\n  inv H5. inv H5.\n  inv H5. econstructor.\n  eapply val_eq_longofwords; eauto.\n  eapply IHsg; eauto.\nQed.\n\nLemma use_def_spec :\n  forall p s1 s1' s2 b z s c i m m0 m' t bits md md',\n    s1 PC = Values.Vint bits ->\n    s2 PC = Values.Vint bits ->\n    no_ptr_regs s2 ->\n    psur md bits = Some (b,z) ->\n    @Genv.find_funct_ptr fundef unit (Genv.globalenv p) b = Some (Internal (mkfunction s c)) ->\n    find_instr (Int.unsigned z) c = Some i -> \n    (forall p,\n       In p (use i) -> val_eq (s1 p) (s2 p)) ->\n    step_bits (Genv.globalenv p) (State_bits s1 m md) t (State_bits s1' m' md') ->\n    mem_eq md m m0 ->\n    no_ptr_mem m0 ->\n    ~ is_call_return i ->\n    (exists s2' m0',\n       step_bits (Genv.globalenv p) (State_bits s2 m0 md) t (State_bits s2' m0' md') /\\ (forall p, In p (def i) -> val_eq (s1' p) (s2' p)) /\\ mem_eq md' m' m0'\n    ).\nProof.\n  intros.\n  invs.\n  *\n    unify_all.\n    \n    match goal with\n      | [ H : Genv.find_funct_ptr _ _ = _ |- _ ] =>\n        name H Hge;\n          eapply use_spec with (s1 := s1) (s2 := s2) in H; eauto\n    end.\n\n    repeat break_exists. do 2 eexists.\n    split.\n    eapply exec_step_internal_bits; eauto.\n    unfold mem_eq in *.\n    repeat break_and. assumption.\n    eapply global_perms_mem_eq; eauto.\n    intros. eapply use_def_exec; eauto.\n      \n  * app mem_eq_extcall' H20.\n    repeat break_and.\n    eexists. eexists.\n    repeat unify_psur.\n    split.\n    rewrite H14. econstructor; eauto.\n    eapply no_ptr_nextinstr_nf.\n    intros.\n    edestruct (set_regs_either res).\n    rewrite H15.\n    destruct (in_dec preg_eq x1 (map preg_of (Machregs.destroyed_by_builtin ef))).\n    rewrite undef_regs_undef by assumption. congruence.\n    rewrite undef_regs_not_in by assumption. apply H1.\n    break_exists. break_and. rewrite H15.\n    app (@list_forall2_inv_right val) H12.\n    break_and. unfold val_eq in H21.\n    break_match_hyp; try congruence.\n    eapply no_ptr_mem_eq; eauto.\n    unfold mem_eq in *.\n    repeat break_and. assumption.\n    eapply global_perms_mem_eq; eauto.\n\n    split.\n    intros.\n    repeat unify_psur. repeat unify_find_funct_ptr.\n    simpl in *. unify_find_instr.\n    simpl in *. \n    eapply val_eq_nextinstr_nf. intros.\n    rewrite in_app in H2.\n    simpl in H15.\n    apply Decidable.not_or in H15; break_and.\n    apply Decidable.not_or in H16; break_and.\n    apply Decidable.not_or in H18; break_and.\n    apply Decidable.not_or in H19; break_and.\n    apply Decidable.not_or in H20; break_and.\n\n    assert (p0 = PC \\/ In p0 res \\/ In p0 (map preg_of (Machregs.destroyed_by_builtin ef))) by (\n      repeat break_or; try congruence; try (left; reflexivity); prove_or_eq assumption; assumption). \n\n    clear H2.\n\n    inv H11. inv H10.\n    destruct (in_dec preg_eq p0 res).\n    eapply set_regs_efres; eauto.\n    intros.\n    \n    destruct (in_dec preg_eq p1 (map preg_of (Machregs.destroyed_by_builtin ef))).\n    repeat rewrite undef_regs_undef by assumption.\n    simpl. congruence.\n    repeat rewrite undef_regs_not_in; eauto.\n    eapply H5. right. rewrite in_app. right. eauto.\n\n    app mem_eq_extcall H11. repeat break_and.\n    eapply external_call_determ in H11; try eapply H2.\n    break_and.\n    specialize (H30 eq_refl). break_and.\n    subst. assumption.\n\n    eapply val_eq_decode_longs.\n    eapply list_forall2_map. intros.\n    eapply H5. right. rewrite in_app. left. auto.\n\n    repeat rewrite set_regs_not_in by assumption.\n    \n    repeat break_or; try congruence.\n    destruct (in_dec preg_eq PC (map preg_of (Machregs.destroyed_by_builtin ef))).\n    repeat rewrite undef_regs_undef by assumption.\n    simpl. congruence.\n    repeat rewrite undef_regs_not_in; eauto.\n    repeat rewrite undef_regs_undef by assumption. simpl. congruence.\n    \n    congruence.\n    \n    eapply list_forall2_map.\n    intros. apply H5. repeat unify_psur.\n    unify_find_funct_ptr.\n    simpl in *. rewrite H4 in H19. inv H19.\n    simpl. right. rewrite in_app. left. assumption.\n    \n  *\n    unify_psur. unfold fundef in *.\n    unify_find_funct_ptr. simpl in *.\n    rewrite H4 in *. opt_inv. subst.\n\n    eapply (list_forall2_annot p s1 s2) in H23;\n    intros;\n    try eapply H5;\n    eauto.\n    repeat break_exists. break_and.\n    app mem_eq_extcall H24.\n    \n    repeat break_and. rewrite H15.\n\n    eexists. eexists. split.\n    eapply exec_step_annot_bits; eauto.\n    eapply no_ptr_mem_eq; eauto.\n    unfold mem_eq in *. tauto.\n    eapply global_perms_mem_eq; eauto.\n\n    split.\n    intros. simpl in H16. break_or; try inv_false.\n    preg_simpl. eapply val_eq_add.\n    eapply H5. simpl. left. reflexivity.\n    simpl. reflexivity.\n\n    congruence.\n    \n  * unify_psur. unify_find_funct_ptr.\n\nQed.\n\nLemma def_spec' :\n  forall prog s c z b i s1 m s1' m' t bits md md',\n    s1 PC = Values.Vint bits ->\n    psur md bits = Some (b,z) ->\n    @Genv.find_funct_ptr fundef unit (Genv.globalenv prog) b = Some (Internal (mkfunction s c)) ->\n    find_instr (Int.unsigned z) c = Some i ->\n    step_bits (Genv.globalenv prog) (State_bits s1 m md) t (State_bits s1' m' md') ->\n    ~ is_call_return i ->\n    (forall p, (In p (def i) \\/ s1 p = s1' p)).\nProof.\n  intros. invs; unify_all.\n\n  *\n    eapply def_spec; eauto.\n\n\n  * destruct (preg_eq PC p).\n      left. left. assumption.\n    destruct (in_dec preg_eq p flags).\n      left. simpl. simpl in i. tauto.\n    destruct (in_dec preg_eq p res).\n      left. simpl. repeat right. rewrite in_app. left. assumption.\n    destruct (in_dec preg_eq p (map preg_of (Machregs.destroyed_by_builtin ef))).\n      left. simpl. repeat right. rewrite in_app. right. assumption.\n    right. unfold nextinstr_nf. fold flags.\n    unfold nextinstr. rewrite Pregmap.gso by auto.\n    rewrite undef_regs_not_in by auto.\n    rewrite set_regs_not_in by auto.\n    rewrite undef_regs_not_in by auto.\n    reflexivity.\n\n  * destruct (preg_eq PC p).\n      left. simpl. left. assumption.\n    right. unfold nextinstr.\n    rewrite Pregmap.gso by auto.\n    reflexivity.\nQed.\n\nLemma val_eq_refl :\n  forall v,\n    (forall b ofs, v <> Vptr b ofs) ->\n    val_eq v v.\nProof.\n  intros. unfold val_eq.\n  break_match; auto.\n  congruence.\nQed.\n\n\n\n(* Lemma use_def_exec' : *)\n(*   forall prog s c i b z s1 s2 m m' s1' s2' m0 m0' t bits md md', *)\n(*     s1 PC = Values.Vint bits -> *)\n(*     s2 PC = Values.Vint bits -> *)\n(*     psur md bits = Some (b,z) -> *)\n(*     @Genv.find_funct_ptr fundef unit (Genv.globalenv prog) b = Some (Internal (mkfunction s c)) -> *)\n(*     find_instr (Int.unsigned z) c = Some i -> *)\n(*     step_bits (Genv.globalenv prog) (State_bits s1 m md) t (State_bits s1' m' md') -> *)\n(*     step_bits (Genv.globalenv prog) (State_bits s2 m0 md) t (State_bits s2' m0' md') -> *)\n(*     mem_eq md m m0 -> *)\n(*     (forall p, In p (use i) -> val_eq (s1 p) (s2 p)) -> *)\n(*     ~ is_call_return i -> *)\n(*     (forall p, In p (def i) -> val_eq (s1' p) (s2' p)) /\\ mem_eq md' m' m0'. *)\n(* Proof. *)\n(*   intros. invs2; repeat unify_all; try state_inv. *)\n\n(*   * eapply use_def_exec; eauto. *)\n(*   * split; intros. *)\n(*     eapply val_eq_nextinstr_nf. *)\n(*     intros. *)\n(*     repeat break_or; try subst p; *)\n(*     try solve [exfalso; apply H9; simpl; prove_or_eq reflexivity]. *)\n(*     eapply val_eq_set_regs. *)\n    \n(*     eapply val_eq_undef_regs. *)\n    \n(*     eapply H7. left. eauto. *)\n\n(*     inv H19. inv H27. *)\n\n(*     rewrite in_app in H1. break_or. *)\n(*     eapply set_regs_efres. eauto. *)\n(*     intros. *)\n(*     eapply val_eq_undef_regs. apply H7. *)\n(*     right. rewrite in_app. right. eauto. *)\n\n    \n\n(*     eapply val_eq_set_regs. *)\n\n(*     repeat rewrite undef_regs_undef by assumption. *)\n(*     simpl. auto. *)\n(*     congruence. *)\n    \n(*   * split; intros. *)\n(*     break_or; try inv_false. *)\n(*     eapply val_eq_nextinstr. *)\n(*     eapply H7; eauto. *)\n(* Qed. *)\n    \n", "meta": {"author": "uwplse", "repo": "peek", "sha": "4943735ed39fd5ddadf2c28fc2ada31504228561", "save_path": "github-repos/coq/uwplse-peek", "path": "github-repos/coq/uwplse-peek/peek-4943735ed39fd5ddadf2c28fc2ada31504228561/compcert/peek/Use.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.21397595361554694}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import sha.sha.\nRequire Import sha.SHA256.\nRequire Import sha.sha_lemmas.\nRequire Import sha.spec_sha.\nLocal Open Scope nat.\nLocal Open Scope logic.\n\nLemma body_SHA256_Init: semax_body Vprog Gtot f_SHA256_Init SHA256_Init_spec.\nProof.\nstart_function.\nname c_ _c.\nunfold data_at_.\n(* BEGIN: without these lines, the \"do 8 forward\" takes 40 times as long. *)\nunfold field_at_.\nunfold_data_at (field_at _ _ _ _ _).\nsimpl fst; simpl snd.\n(* END: without these lines *)\nTime do 8 (forward; unfold upd_Znth; if_tac;\n  unfold Zlength in *; simpl Zlength_aux in *; try lia;\n  unfold sublist; simpl app).\nTime repeat forward. (* 14 sec *)\nunfold sha256state_.\nExists (map Vint init_registers,\n      (Vint Int.zero, (Vint Int.zero, (repeat Vundef (Z.to_nat 64), Vint Int.zero)))).\nunfold_data_at (data_at _ _ _ _).\nTime entailer!. (* 5.2 sec *)\nrepeat split; auto.\nunfold s256_h, fst, s256a_regs.\nrewrite hash_blocks_equation. reflexivity.\nunfold data_at. apply derives_refl'; f_equal.\nf_equal.\nsimpl.\nrepeat (apply f_equal2; [f_equal; apply int_eq_e; compute; reflexivity | ]); auto.\nTime Qed. (* 33.6 sec *)\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/sha/verif_sha_init.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21397594788401117}}
{"text": "From fae_gtlc_mu.refinements.static_gradual Require Export compat_cast.defs.\nFrom fae_gtlc_mu.backtranslation Require Export general_def_lemmas.\nFrom fae_gtlc_mu.cast_calculus Require Export lang.\n\nSection compat_cast_arrow_arrow.\n  Context `{!implG Σ,!specG Σ}.\n\n  (** The case `throughArrow` in our proof by induction on the alternative consistency relation. *)\n  Lemma back_cast_ar_arrow_arrow:\n    ∀ (A : list (type * type)) (τ1 τ1' τ2 τ2' : type) (pC1 : alternative_consistency A τ1' τ1) (pC2 : alternative_consistency A τ2 τ2')\n      (IHpC1 : back_cast_ar pC1) (IHpC2 : back_cast_ar pC2),\n      back_cast_ar (throughArrow A τ1 τ1' τ2 τ2' pC1 pC2).\n  Proof.\n    intros A τ1 τ1' τ2 τ2' pC1 pC2 IHpC1 IHpC2.\n    rewrite /back_cast_ar. iIntros (ei' K' v v' fs) \"(#Hfs & #Hvv' & #Hei' & Hv')\".\n    (* extract small lemma about length fs *)\n    iDestruct \"Hfs\" as \"[% Hfs']\"; iAssert (rel_cast_functions A fs) with \"[Hfs']\" as \"Hfs\". iSplit; done. iClear \"Hfs'\".\n    (* rewriting stuff *)\n    rewrite /𝓕c /𝓕. fold (𝓕 pC1) (𝓕 pC2). rewrite between_TArrow_subst_rewrite.\n    rename v into f. rename v' into f'. iDestruct \"Hv'\" as \"Hf'\". iDestruct \"Hvv'\" as \"Hff'\".\n    fold (𝓕c pC1 fs) (𝓕c pC2 fs).\n    do 2 rewrite 𝓕c_rewrite.\n    (* 1 step in WP *)\n    unfold between_TArrow.\n    wp_head.\n    asimpl.\n    (* prove postcondition because value *)\n    iApply wp_value.\n    iExists (CastV f' (TArrow τ1 τ2) (TArrow τ1' τ2') (TArrow_TArrow_icp τ1 τ2 τ1' τ2')).\n    rewrite interp_rw_TArrow.\n    iSplitL \"Hf'\"; auto.\n    rewrite interp_rw_TArrow.\n    iModIntro.\n    (** actual thing to prove *)\n    (** ===================== *)\n    iIntros ((a , a')) \"#Haa'\".\n    simpl. clear K'.\n    iIntros (K') \"Hf'\".\n    simpl in *.\n    (* step in wp *)\n    wp_head. asimpl.\n    (* step in gradual side *)\n    iMod (step_pure _ ei' K'\n                    (App (Cast f' (TArrow τ1 τ2) (TArrow τ1' τ2')) a')\n                    (Cast (App f' (Cast a' τ1' τ1)) τ2 τ2') with \"[Hf']\") as \"Hf'\".\n    intros. eapply AppCast; try by rewrite -to_of_val. auto. by iFrame.\n    (* first IH for the arguments *)\n    iApply (wp_bind (ectx_language.fill $ [stlc_mu.lang.AppRCtx _ ; stlc_mu.lang.AppRCtx _])).\n    iApply (wp_wand with \"[-]\").\n    rewrite -𝓕c_rewrite.\n    iApply (IHpC1 ei' (AppRCtx f' :: CastCtx τ2 τ2' :: K') with \"[Hf']\"). auto.\n    iIntros (b) \"HHH\".\n    iDestruct \"HHH\" as (b') \"[Hb' #Hbb']\".\n    simpl.\n    iClear \"Haa'\". clear a a'.\n    (* using the relatedness of functions *)\n    iApply (wp_bind (ectx_language.fill $ [stlc_mu.lang.AppRCtx _ ])).\n    iApply (wp_wand with \"[-]\").\n    iDestruct (\"Hff'\" with \"Hbb'\") as \"Hfbf'b' /=\".\n    iApply (\"Hfbf'b'\" $! (CastCtx τ2 τ2' :: K')).\n    simpl.\n    iExact \"Hb'\".\n    iIntros (r) \"HHH\". iDestruct \"HHH\" as (r') \"[Hr' Hrr']\".\n    simpl.\n    iClear \"Hbb'\". clear b b'.\n    (** second IH for the results *)\n    iApply (wp_wand with \"[-]\").\n    rewrite -𝓕c_rewrite.\n    iApply (IHpC2 ei' K' r r' with \"[-]\").\n    iSplitR. done.\n    iSplitL \"Hrr'\"; try done.\n    iSplitR. done.\n    done.\n    iIntros (s) \"HHH\". done.\n  Qed.\n\nEnd compat_cast_arrow_arrow.\n", "meta": {"author": "scaup", "repo": "fae-gtlc-mu", "sha": "6c6e64f0844327d55059b97c7aefab023385973e", "save_path": "github-repos/coq/scaup-fae-gtlc-mu", "path": "github-repos/coq/scaup-fae-gtlc-mu/fae-gtlc-mu-6c6e64f0844327d55059b97c7aefab023385973e/theories/refinements/static_gradual/compat_cast/arrow_arrow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.21393857477819092}}
{"text": "Require Import AutoSep Malloc Abort Bootstrap.\n\n\nModule Type S.\n  Variable heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"test\"!\"main\" @ [Abort.mainS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Goto \"test\"!\"main\"\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Definition m0 := link Malloc.m boot.\n  Definition m1 := link Abort.m m0.\n\n  Lemma ok0 : moduleOk m0.\n    link Malloc.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link Abort.ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n  \n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, $(size * 4) <= w -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "gmalecha", "repo": "bedrock-mirror-shard", "sha": "ea7e5ad56a1d6392468b6823e0457dd44524bca7", "save_path": "github-repos/coq/gmalecha-bedrock-mirror-shard", "path": "github-repos/coq/gmalecha-bedrock-mirror-shard/bedrock-mirror-shard-ea7e5ad56a1d6392468b6823e0457dd44524bca7/platform/tests/AbortDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.21380344291378553}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import RealmExitHandlerAux.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition handle_realm_exit_spec0 (rec: Pointer) (exception: Z) (adt: RData) : option (RData * Z) :=\n    match rec, exception with\n    | (_rec_base, _rec_ofst), _exception =>\n      if (_exception =? 0) then\n        when adt == set_rec_run_exit_reason_spec (VZ64 0) adt;\n        when _t'1, adt == handle_exception_sync_spec (_rec_base, _rec_ofst) adt;\n        rely is_int _t'1;\n        Some (adt, _t'1)\n      else\n        if (_exception =? 1) then\n          when _t'2, adt == handle_excpetion_irq_lel_spec (_rec_base, _rec_ofst) adt;\n          rely is_int _t'2;\n          Some (adt, _t'2)\n        else\n          if (_exception =? 2) then\n            when adt == set_rec_run_exit_reason_spec (VZ64 2) adt;\n            Some (adt, 0)\n          else\n            Some (adt, 0)\n     end\n    .\n\nEnd SpecLow.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RealmExitHandler/LowSpecs/handle_realm_exit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953506426082, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.21380343488814063}}
{"text": "\nRequire Import List.\nFrom mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq tuple ssrfun fintype.\nFrom mathcomp Require Import choice path bigop.\nRequire Import Lib.Base Ipdl.Exp Ipdl.Core String Ipdl.Lems Lib.TupleLems Lib.Dist Ipdl.Tacs Pars Lib.Set.\nRequire Import OTIdeal.\n\nRequire Import Setoid Relation_Definitions Morphisms.\nRequire Import Permutation Typ Lib.SeqOps.\nClose Scope bool_scope.\n\n  Lemma samp_pair {chan} {t'} {t : finType} `{unif t} `{Inhabited t'} `{Inhabited t} (x : chan t') (c d : chan t) :\n    pars [::\n            Out c (_ <-- Read x ;; Samp (Unif));\n         Out d (_ <-- Read x ;; Samp Unif)] =p\n    e <- new (t * t) ;;\n    pars [::\n            Out e (_ <-- Read x ;; Samp Unif) ;\n            Out c (_ <-- Read x ;; x <-- Read e ;; Ret (x.1));\n            Out d (_ <-- Read x ;; x <-- Read e ;; Ret (x.2))].\n    symmetry.\n    simpl.\n    etransitivity.\n    Intro => e.\n    edit_tac 0.\n    rewrite /Unif_pair.\n    setoid_rewrite EqSampBind.\n    setoid_rewrite EqSampBind.\n    instantiate (1 :=\n                   x0 <-- (_ <-- Read x ;; Samp Unif) ;;\n                   y <-- (_ <-- Read x ;; Samp Unif) ;;\n                   Ret (x0, y)).\n         symmetry; simp_rxn.\n         r_swap 1 2.\n         rewrite EqReadSame.\n         setoid_rewrite EqSampRet.\n         done.\n    rewrite -pars_fold.\n    Intro => c'.\n    swap_at 0 0 1.\n    rewrite -pars_fold.\n    Intro => d'.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    \n    simpl.\n    swap_tac 0 3.\n    rewrite -pars_mkdep //=; last by firstorder.\n    swap_tac 0 4.\n    swap_at 0 0 1.\n    swap_tac 1 2.\n    rewrite -pars_mkdep //=; last by firstorder.\n    apply EqRefl.\n    rewrite EqNewExch.\n    setoid_rewrite EqNewExch at 2.\n    swap_tac 0 3.\n    setoid_rewrite new_pars_remove.\n    swap_tac 0 2.\n    setoid_rewrite pars_fold.\n    swap_tac 0 2.\n    rewrite pars_fold.\n    align.\n    apply EqCongReact; simp_rxn; r_swap 1 2; rewrite EqReadSame; setoid_rewrite EqBindRet; done.\n    apply EqCongReact; simp_rxn; r_swap 1 2; rewrite EqReadSame; setoid_rewrite EqBindRet; done.\nQed.\n\n  Lemma rerandomP {chan : Type -> Type} {L : nat} b (i : chan (bool * bool)%type) (c1 c2 : chan L.-bv) :\n    pars [::\n            Out c1 (_ <-- Read i ;; Samp Unif);\n            Out c2 (_ <-- Read i ;; Samp Unif)\n         ]\n    =p\n       c1' <- new L.-bv ;;\n       c2' <- new L.-bv ;;\n       pars [::\n               Out c1' (Samp Unif);\n               Out c2' (Samp Unif);\n               Out c1 (i <-- Read i ;; x <-- Read c1' ;; y <-- Read c2' ;; Ret (if  (if b then i.1 else i.2) then x else y));\n               Out c2 (i <-- Read i ;; x <-- Read c1' ;; y <-- Read c2' ;; Ret (if (if b then i.1 else i.2) then y else x))\n                   ].\n    rewrite samp_pair.\n    etransitivity.\n    Intro => e.\n    edit_tac 0.\n    instantiate (1 := \n                   (i <-- Read i ;; x <-- Samp Unif ;; y <-- Samp Unif ;;\n                    Ret (if (if b then i.1 else i.2) then (x, y) else (y, x )))).\n         apply EqBind_r => x.\n         destruct x as [x0 x1]; simpl.\n         destruct b.\n         destruct x0.\n         rewrite /Unif_pair EqSampBind; setoid_rewrite EqSampBind; setoid_rewrite EqSampRet; done.\n         rewrite /Unif_pair EqSampBind; setoid_rewrite EqSampBind; setoid_rewrite EqSampRet.\n         r_swap 0 1.\n         done.\n         destruct x1.\n         rewrite /Unif_pair EqSampBind; setoid_rewrite EqSampBind; setoid_rewrite EqSampRet; done.\n         rewrite /Unif_pair EqSampBind; setoid_rewrite EqSampBind; setoid_rewrite EqSampRet.\n         r_swap 0 1.\n         done.\n    swap_at 0 0 1.\n    rewrite -pars_fold.\n    Intro => c1'.\n    swap_at 0 0 2.\n    rewrite -pars_fold.\n    Intro => c2'.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    apply EqRefl.\n    setoid_rewrite EqNewExch at 1.\n    setoid_rewrite EqNewExch at 2.\n    setoid_rewrite new_pars_remove.\n    Intro => c1'.\n    Intro => c2'.\n    align.\n        apply EqCongReact.\n        r_swap 0 2.\n        r_swap 1 3.\n        rewrite EqReadSame.\n        r_swap 1 2.\n        apply EqBind_r => x.\n        apply EqBind_r => y.\n        apply EqBind_r => z.\n        destruct x as [x0 x1]; destruct b; [ destruct x0 | destruct x1]; rewrite //=.\n\n        apply EqCongReact.\n        r_swap 0 2.\n        r_swap 1 3.\n        rewrite EqReadSame.\n        r_swap 1 2.\n        apply EqBind_r => x.\n        apply EqBind_r => y.\n        apply EqBind_r => z.\n        destruct x as [x0 x1]; destruct b; [ destruct x0 | destruct x1]; rewrite //=.\nQed.\n\n  Lemma rerandomP_rs {chan : Type -> Type} {L : nat} b (i : chan (bool * bool)%type) (c1 c2 : chan L.-bv) rs :\n    pars [::\n            Out c1 (_ <-- Read i ;; Samp Unif),\n            Out c2 (_ <-- Read i ;; Samp Unif) & rs\n         ]\n    =p\n       c1' <- new L.-bv ;;\n       c2' <- new L.-bv ;;\n       pars [::\n               Out c1' (Samp Unif), \n               Out c2' (Samp Unif), \n               Out c1 (i <-- Read i ;; x <-- Read c1' ;; y <-- Read c2' ;; Ret (if  (if b then i.1 else i.2) then x else y)),\n               Out c2 (i <-- Read i ;; x <-- Read c1' ;; y <-- Read c2' ;; Ret (if (if b then i.1 else i.2) then y else x)) & rs\n                   ].\n    rewrite (pars_split 2); simpl; rewrite take0 drop0.\n    rewrite rerandomP.\n    rewrite newComp.\n    Intro => c.\n    rewrite newComp.\n    Intro => c'.\n    rewrite -pars_cat //=.\nQed.\n\nLemma ot14_xort_subproof {t} (a b c : t.-tuple bool) :\n    ((((a +t b) +t c) +t a) +t b)\n              =\n              (c +t (a +t a) +t (b +t b)).\n  rewrite (xortC _ c).\n  rewrite !xortA.\n  congr (_ _).\n  congr (_ _).\n  rewrite (xortC b).\n  rewrite xortA //=.\nQed.\n\nLtac rxn_intros_combine_reads :=\n  lazymatch goal with\n  | [ |- @EqRxn _ _ ?r1 _ ] =>\n    lazymatch r1 with\n    | @Bind _ _ _ ?c ?k =>\n      lazymatch c with\n      | Read ?ch =>\n        find_read_in_rxn (k witness) ch\n                         ltac:(fun p =>\n                            lazymatch p with\n                            | Some ?j => r_swap 1 (j.+1); rewrite EqReadSame; apply EqBind_r; intro; rxn_intros_combine_reads\n                            | None => apply EqBind_r; intro; rxn_intros_combine_reads\n                                                               end\n                         )\n      | _ => apply EqBind_r; intro; rxn_intros_combine_reads\n      end                                      \n    | _ => idtac\n end end.\n\n      \nSection OneOutOf4.\n  Context (L : nat).\n  Context {chan : Type -> Type}.\n  Context (ot_i1 ot_i2 ot_i3 : chan bool).\n  Context (ot_o1 ot_o2 ot_o3 : chan L.-bv).\n\n  Context (ot14_m : chan ((L.-bv * L.-bv) * (L.-bv * L.-bv))).\n  Context (ot14_i : chan (bool * bool)).\n  Context (ot14_o : chan L.-bv).\n\n  (* Leakage channels for bob *)\n  Context (leak_ot_o1 leak_ot_o2 leak_ot_o3 : chan L.-bv).\n  Context (leak_send : chan ((L.-bv * L.-bv) * (L.-bv * L.-bv))).\n\n  Definition One4_sender (ot_m1 ot_m2 ot_m3 : chan (L.-bv * L.-bv)) (ready : chan unit) (send : chan ((L.-bv * L.-bv) * (L.-bv * L.-bv)))  :=\n    s0 <- new L.-bv ;;\n    s1 <- new L.-bv;;\n    s2 <- new L.-bv;;\n    s3 <- new L.-bv;;\n    s4 <- new L.-bv;;\n    s5 <- new L.-bv;;\n    pars [::\n            Out s0 (_ <-- Read ready;; Samp Unif);\n            Out s1 (_ <-- Read ready;; Samp Unif);\n            Out s2 (_ <-- Read ready;; Samp Unif);\n            Out s3 (_ <-- Read ready;; Samp Unif);\n            Out s4 (_ <-- Read ready;; Samp Unif);\n            Out s5 (_ <-- Read ready;; Samp Unif);\n\n            Out send (\n                  m <-- Read ot14_m ;;\n                  s0 <-- Read s0 ;; \n                  s1 <-- Read s1 ;; \n                  s2 <-- Read s2 ;; \n                  s3 <-- Read s3 ;; \n                  s4 <-- Read s4 ;; \n                  s5 <-- Read s5 ;; \n                  Ret (\n                  let '((m0, m1), (m2, m3)) := m in\n                  ( (s0 +t s2 +t m0,\n                     s0 +t s3 +t m1),\n                    (s1 +t s4 +t m2, s1 +t s5 +t m3))));\n         Out ot_m1 (\n               a <-- Read s0 ;;\n               b <-- Read s1 ;;\n               Ret (a, b) );\n         Out ot_m2 (\n               a <-- Read s2 ;;\n               b <-- Read s3 ;;\n               Ret (a, b) );\n         Out ot_m3 (\n               a <-- Read s4 ;;\n               b <-- Read s5 ;;\n               Ret (a, b) ) ].\n               \n  Definition One4_recv (ready : chan unit) (ot_i1 ot_i2 ot_i3 : chan bool) (ot_o1 ot_o2 ot_o3 : chan L.-bv) (send : chan ((L.-bv * L.-bv) * (L.-bv * L.-bv))) :=\n    pars [::\n            Out ready (_ <-- Read ot14_i ;; Ret tt);\n            Out ot_i1 (\n                  i <-- Read ot14_i ;; Ret (i.1));\n            Out ot_i2 (\n                  i <-- Read ot14_i ;; Ret (i.2));\n            Out ot_i3 (\n                  i <-- Read ot14_i ;; Ret (i.2));\n            Out leak_send (copy send);\n            Out leak_ot_o1 (copy ot_o1);\n            Out leak_ot_o2 (copy ot_o2);\n            Out leak_ot_o3 (copy ot_o3);\n            Out ot14_o (\n                  t <-- Read ot14_i ;;\n                  a <-- Read send ;;\n                  T0 <-- Read ot_o1 ;;\n                  T1 <-- Read ot_o2 ;;\n                  T2 <-- Read ot_o3 ;;\n                  Ret (\n                      let '((a0, a1), (a2, a3)) := a in\n                      match t.1, t.2 with\n                        | false, false => a0 +t T0 +t T1\n                        | false, true => a1 +t T0 +t T1\n                        | true, false => a2 +t T0 +t T2\n                        | true, true => a3 +t T0 +t T2 \n                                                    end))].\n\n  Definition OT14_real_simpl :=\n    c <- new L.-bv ;;\n    c0 <- new L.-bv ;;\n    c1 <- new L.-bv ;;\n    c2 <- new L.-bv ;;\n    c3 <- new L.-bv ;;\n    c4 <- new L.-bv ;;\n    [pars [:: Out ot14_o\n              (x <-- Read ot14_i;; x_m <-- Read ot14_m;; Ret ((x_m # x.1) # x.2 : L.-bv));\n            Out c2 (_ <-- Read ot14_i;; Samp Unif);\n            Out c3 (_ <-- Read ot14_i;; Samp Unif);\n            Out leak_send\n              (x <-- Read ot14_m;;\n               x0 <-- Read c;;\n               x1 <-- Read c0;;\n               x2 <-- Read c1;;\n               x3 <-- Read c2;;\n               x4 <-- Read c3;;\n               x5 <-- Read c4;;\n               Ret\n                 (let\n                  '(m0, m1, (m2, m3)) := x in\n                   ( ( (x0 +t x2) +t m0, (x0 +t x3) +t m1),\n                     ( (x1 +t x4) +t m2, (x1 +t x5) +t m3))));\n            Out leak_ot_o3\n              (x <-- Read c3;;\n               x0 <-- Read c4;;\n               x1 <-- Read ot14_i;; Ret (if x1 .2 then x0 else x));\n            Out leak_ot_o2\n              (x <-- Read c1;;\n               x0 <-- Read c2;;\n               x1 <-- Read ot14_i;; Ret (if x1 .2 then x0 else x));\n            Out leak_ot_o1\n              (x <-- Read c;;\n               x0 <-- Read c0;;\n               x1 <-- Read ot14_i;; Ret (if x1 .1 then x0 else x));\n            Out c1 (_ <-- Read ot14_i;; Samp Unif);\n            Out c4 (_ <-- Read ot14_i;; Samp Unif);\n            Out c (_ <-- Read ot14_i;; Samp Unif);\n            Out c0 (_ <-- Read ot14_i;; Samp Unif) ]].\n\n  Definition OT14_real :=\n    ot_i1 <- new bool ;;\n    ot_i2 <- new bool ;;\n    ot_i3 <- new bool ;;\n    ot_m1 <- new (L.-bv * L.-bv) ;;\n    ot_m2 <- new (L.-bv * L.-bv) ;;\n    ot_m3 <- new (L.-bv * L.-bv) ;;\n    ot_o1 <- new L.-bv ;;\n    ot_o2 <- new L.-bv ;;\n    ot_o3 <- new L.-bv ;;\n    send <- new ((L.-bv * L.-bv) * (L.-bv * L.-bv)) ;;\n    ready <- new unit ;;\n    pars [::\n            OTIdeal _ ot_i1 ot_m1 ot_o1;\n            OTIdeal _ ot_i2 ot_m2 ot_o2;\n            OTIdeal _ ot_i3 ot_m3 ot_o3;\n            One4_sender ot_m1 ot_m2 ot_m3 ready send;\n            One4_recv ready ot_i1 ot_i2 ot_i3 ot_o1 ot_o2 ot_o3 send ].\n            \n  Lemma ot14_simp : OT14_real =p OT14_real_simpl.\n    etransitivity.\n    repeat ltac:(apply EqCongNew; intro).\n    rewrite /OTIdeal.\n    rewrite /One4_sender.\n    swap_tac 0 3.\n    setoid_rewrite New_in_pars at 1.\n    setoid_rewrite New_in_pars at 1.\n    setoid_rewrite New_in_pars at 1.\n    setoid_rewrite New_in_pars at 1.\n    setoid_rewrite New_in_pars at 1.\n    setoid_rewrite New_in_pars at 1.\n    apply EqCongNew => s0.\n    apply EqCongNew => s1.\n    apply EqCongNew => s2.\n    apply EqCongNew => s3.\n    apply EqCongNew => s4.\n    apply EqCongNew => s5.\n    rewrite pars_pars; simpl.\n    swap_tac 0 13.\n    rewrite pars_pars; simpl.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    do_inline; simp_all.\n    progress ltac:(do_inline; simp_all).\n    progress ltac:(do_inline; simp_all).\n    progress ltac:(do_inline; simp_all).\n    progress ltac:(do_inline; simp_all).\n    progress ltac:(do_inline; simp_all).\n    progress ltac:(do_inline; simp_all).\n    apply EqRefl.\n    (* now we elim all the useless channels *)\n    simpl.\n    repeat setoid_rewrite (EqNewExch unit).\n    under_new rewrite new_pars_remove; last first; apply EqRefl.\n    simpl.\n    repeat setoid_rewrite (EqNewExch ((L.-bv * L.-bv) * (L.-bv * L.-bv))).\n    swap_tac 0 13.\n    under_new rewrite new_pars_remove; last first; apply EqRefl.\n    simpl.\n    repeat setoid_rewrite (EqNewExch bool) at 3.\n    swap_tac 0 1.\n    under_new rewrite new_pars_remove; last first; apply EqRefl.\n    repeat setoid_rewrite (EqNewExch bool) at 2.\n    under_new rewrite new_pars_remove; last first; apply EqRefl.\n    simpl.\n    repeat setoid_rewrite (EqNewExch bool) at 1.\n    swap_tac 0 10.\n    under_new rewrite new_pars_remove; last first; apply EqRefl.\n    simpl.\n    repeat setoid_rewrite (EqNewExch (L.-bv * L.-bv)) at 3.\n    swap_tac 0 12.\n    under_new rewrite new_pars_remove; last first; apply EqRefl.\n    simpl.\n    repeat setoid_rewrite (EqNewExch (L.-bv * L.-bv)) at 2.\n    swap_tac 0 10.\n    under_new rewrite new_pars_remove; last first; apply EqRefl.\n    simpl.\n    repeat setoid_rewrite (EqNewExch (L.-bv * L.-bv)).\n    swap_tac 0 8.\n    under_new rewrite new_pars_remove; last first; apply EqRefl.\n\n    simpl.\n    swap_tac 0 10.\n    setoid_rewrite (EqNewExch L.-bv) at 2.\n    setoid_rewrite (EqNewExch L.-bv) at 3.\n    setoid_rewrite (EqNewExch L.-bv) at 4.\n    setoid_rewrite (EqNewExch L.-bv) at 5.\n    setoid_rewrite (EqNewExch L.-bv) at 6.\n    setoid_rewrite (EqNewExch L.-bv) at 7.\n    setoid_rewrite (EqNewExch L.-bv) at 8.\n    under_new rewrite new_pars_remove; last first; apply EqRefl.\n\n    simpl.\n    swap_tac 0 11.\n    setoid_rewrite (EqNewExch L.-bv) at 1.\n    setoid_rewrite (EqNewExch L.-bv) at 2.\n    setoid_rewrite (EqNewExch L.-bv) at 3.\n    setoid_rewrite (EqNewExch L.-bv) at 4.\n    setoid_rewrite (EqNewExch L.-bv) at 5.\n    setoid_rewrite (EqNewExch L.-bv) at 6.\n    setoid_rewrite (EqNewExch L.-bv) at 7.\n    under_new rewrite new_pars_remove; last first; apply EqRefl.\n\n    simpl.\n    swap_tac 0 9.\n    setoid_rewrite (EqNewExch L.-bv) at 1.\n    setoid_rewrite (EqNewExch L.-bv) at 2.\n    setoid_rewrite (EqNewExch L.-bv) at 3.\n    setoid_rewrite (EqNewExch L.-bv) at 4.\n    setoid_rewrite (EqNewExch L.-bv) at 5.\n    setoid_rewrite (EqNewExch L.-bv) at 6.\n    under_new rewrite new_pars_remove; last first; apply EqRefl.\n\n    (* Now do some final simpl *)\n    etransitivity.\n    repeat ltac:(apply EqCongNew; intro).\n    edit_tac 7.\n    etransitivity.\n    rxn_intros_combine_reads.\n    apply EqRxnRefl.\n    etransitivity.\n    rxn_intros_combine_reads.\n    apply EqRxnRefl.\n    apply EqBind_r; intro.\n    apply EqBind_r; intro.\n    apply EqBind_r; intros x_i.\n    apply EqBind_r; intro.\n    apply EqBind_r; intro.\n    apply EqBind_r; intro.\n    apply EqBind_r; intro.\n    apply EqBind_r; intros x_m.\n    instantiate (1 :=\n                   fun x_m => _).\n    simpl.\n    instantiate (1 := Ret ((x_m # x_i.1) # x_i.2)).\n    destruct x_m as [[m0 m1] [m2 m3]].\n    simpl.\n    destruct x_i as [i1 i2]; simpl.\n    destruct i1, i2; simpl.\n\n    rewrite ot14_xort_subproof !xortK !xort0 //=.\n    rewrite ot14_xort_subproof !xortK !xort0 //=.\n    rewrite ot14_xort_subproof !xortK !xort0 //=.\n    rewrite ot14_xort_subproof !xortK !xort0 //=.\n\n    swap_tac 0 7.\n    swap_tac 1 10.\n    rewrite -pars_mkdep //=; last by firstorder.\n    swap_tac 1 9.\n    rewrite -pars_mkdep //=; last by firstorder.\n    swap_at 0 0 1.\n    swap_tac 1 10.\n    rewrite -pars_mkdep //=; last by firstorder.\n    swap_at 0 0 1.\n    swap_tac 1 2.\n    rewrite -pars_mkdep //=; last by firstorder.\n    swap_at 0 0 1.\n    swap_tac 1 8.\n    rewrite -pars_mkdep //=; last by firstorder.\n    swap_at 0 0 1.\n    swap_tac 1 7.\n    rewrite -pars_mkdep //=; last by firstorder.\n    apply EqRefl.\n    apply EqRefl.\nQed.\n\n  Definition mkpair4 {t} (f : bool -> bool -> t) : (t * t) * (t * t) :=\n    ((f false false, f false true), (f true false, f true true)).\n\n  Definition cflip {t} (p : t * t) (b : bool) : t * t :=\n    if b then p else (p.2, p.1).\n\n  Lemma bind_samp_xor {n : nat} {t} (a : n.-tuple bool) (k : n.-bv -> @rxn chan t) :\n    EqRxn _ (x <-- Samp (Unif) ;; k x) (x <-- Samp Unif ;; k (x +t a)).\n    apply EqBind_r_samp_bijection.\n    apply is_unif.\n    apply xort_inj_r.\n  Qed.\n\n  Definition OT14_real_rerandomize :=\n    c <- new L.-bv;;\n  c0 <- new L.-bv;;\n  c1 <- new L.-bv;;\n  [pars [:: Out leak_send\n              (x <-- Read ot14_i;;\n               x0 <-- Read c1;;\n               x1 <-- Read c0;;\n               x2 <-- Read c;;\n               x3 <-- Read ot14_m;;\n               x4 <-- Samp Unif;;\n               x5 <-- Samp Unif;;\n               x6 <-- Samp Unif;; \n               Ret\n                 (let o := (x3 # x .1) # x .2 in\n                  let o0 := if x .2 && x .1 then o else tzero _ in\n                  let o1 := if ~~ x .2 && x .1 then o else tzero _ in\n                  let o2 := if x .2 && ~~ x .1 then o else tzero _ in\n                  let o3 := if ~~ x .2 && ~~ x .1 then o else tzero _ in\n                  ( ( ((x2, x4) # x .1 +t (x0, x6) # x .2) +t o3 : L.-bv,\n                    ((x2, x4) # x .1 +t (x6, x0) # x .2) +t o2 : L.-bv),\n                  (((x4, x2) # x .1 +t (x1, x5) # x .2) +t o1 : L.-bv,\n                  ((x4, x2) # x .1 +t (x5, x1) # x .2) +t o0 : L.-bv))));\n            Out leak_ot_o1 (_ <-- Read ot14_i;; Read c);\n            Out leak_ot_o3 (_ <-- Read ot14_i;; Read c0);\n            Out leak_ot_o2 (_ <-- Read ot14_i;; y <-- Read c1;; Ret y);\n            Out c1 (Samp Unif); Out c (Samp Unif);             Out ot14_o\n              (x <-- Read ot14_i;; x0 <-- Read ot14_m;; Ret ((x0 # x.1) # x.2 : L.-bv));\n            Out c0 (Samp Unif) ] ]. \n\n\nLemma ot_simpl_rerandomize : OT14_real_simpl =p OT14_real_rerandomize.\n    etransitivity.\n    repeat ltac:(apply EqCongNew; intro).\n    swap_tac 0 9.\n    swap_tac 1 10.\n    etransitivity.\n    rewrite (rerandomP_rs true).\n    repeat ltac:(apply EqCongNew; intro).\n    repeat ltac:(do_inline; simp_all).\n    edit_tac 8.\n        r_swap 1 3.\n        rewrite EqReadSame.\n        r_swap 1 5.\n        rewrite EqReadSame.\n        apply EqBind_r => i.\n        r_swap 1 2.\n        rewrite !EqReadSame.\n        apply EqBind_r => x.\n        rewrite !EqReadSame.\n        apply EqBind_r => y.\n        instantiate (1 := fun y => Ret y).\n        destruct i; simpl.\n        destruct b; done.\n   swap_tac 0 4.\n   swap_tac 1 10.\n    rewrite (rerandomP_rs false).\n    repeat ltac:(apply EqCongNew; intro).\n    repeat ltac:(do_inline; simp_all).\n    edit_tac 8.\n        r_swap 1 3.\n        rewrite EqReadSame.\n        r_swap 1 5.\n        rewrite EqReadSame.\n        apply EqBind_r => i.\n        r_swap 1 2.\n        rewrite !EqReadSame.\n        apply EqBind_r => x.\n        rewrite !EqReadSame.\n        apply EqBind_r => y.\n        instantiate (1 := fun y => Ret y).\n        destruct i; simpl.\n        destruct b0; done.\n  swap_tac 0 11.\n  swap_tac 1 14.\n    rewrite (rerandomP_rs false).\n    repeat ltac:(apply EqCongNew; intro).\n    repeat ltac:(do_inline; simp_all).\n    edit_tac 11.\n        r_swap 1 3.\n        rewrite EqReadSame.\n        r_swap 1 5.\n        rewrite EqReadSame.\n        apply EqBind_r => i.\n        r_swap 1 2.\n        rewrite !EqReadSame.\n        apply EqBind_r => x.\n        rewrite !EqReadSame.\n        apply EqBind_r => y.\n        instantiate (1 := fun y => Ret y).\n        destruct i; simpl.\n        destruct b0; done.\n  apply EqRefl.\n  apply EqRefl.\n  (* Now elim useless channels *)\n  setoid_rewrite (EqNewExch L.-bv) at 1.\n  setoid_rewrite (EqNewExch L.-bv) at 2.\n  setoid_rewrite (EqNewExch L.-bv) at 3.\n  setoid_rewrite (EqNewExch L.-bv) at 4.\n  setoid_rewrite (EqNewExch L.-bv) at 5.\n  setoid_rewrite (EqNewExch L.-bv) at 6.\n  setoid_rewrite (EqNewExch L.-bv) at 7.\n  setoid_rewrite (EqNewExch L.-bv) at 8.\n  setoid_rewrite (EqNewExch L.-bv) at 9.\n  setoid_rewrite (EqNewExch L.-bv) at 10.\n  setoid_rewrite (EqNewExch L.-bv) at 11.\n  swap_tac 0 6.\n  under_new rewrite new_pars_remove; last first.\n  apply EqRefl.\n\n  \n  setoid_rewrite (EqNewExch L.-bv) at 1.\n  setoid_rewrite (EqNewExch L.-bv) at 2.\n  setoid_rewrite (EqNewExch L.-bv) at 3.\n  setoid_rewrite (EqNewExch L.-bv) at 4.\n  setoid_rewrite (EqNewExch L.-bv) at 5.\n  setoid_rewrite (EqNewExch L.-bv) at 6.\n  setoid_rewrite (EqNewExch L.-bv) at 7.\n  setoid_rewrite (EqNewExch L.-bv) at 8.\n  setoid_rewrite (EqNewExch L.-bv) at 9.\n  setoid_rewrite (EqNewExch L.-bv) at 10.\n  swap_tac 0 6.\n  under_new rewrite new_pars_remove; last first.\n  apply EqRefl.\n  \n\n  setoid_rewrite (EqNewExch L.-bv) at 1.\n  setoid_rewrite (EqNewExch L.-bv) at 2.\n  setoid_rewrite (EqNewExch L.-bv) at 3.\n  setoid_rewrite (EqNewExch L.-bv) at 4.\n  setoid_rewrite (EqNewExch L.-bv) at 5.\n  setoid_rewrite (EqNewExch L.-bv) at 6.\n  setoid_rewrite (EqNewExch L.-bv) at 7.\n  setoid_rewrite (EqNewExch L.-bv) at 8.\n  setoid_rewrite (EqNewExch L.-bv) at 9.\n  under_new rewrite new_pars_remove; last first.\n  apply EqRefl.\n\n  setoid_rewrite (EqNewExch L.-bv) at 1.\n  setoid_rewrite (EqNewExch L.-bv) at 2.\n  setoid_rewrite (EqNewExch L.-bv) at 3.\n  setoid_rewrite (EqNewExch L.-bv) at 4.\n  setoid_rewrite (EqNewExch L.-bv) at 5.\n  setoid_rewrite (EqNewExch L.-bv) at 6.\n  setoid_rewrite (EqNewExch L.-bv) at 7.\n  setoid_rewrite (EqNewExch L.-bv) at 8.\n  under_new rewrite new_pars_remove; last first.\n  apply EqRefl.\n\n  setoid_rewrite (EqNewExch L.-bv) at 1.\n  setoid_rewrite (EqNewExch L.-bv) at 2.\n  setoid_rewrite (EqNewExch L.-bv) at 3.\n  setoid_rewrite (EqNewExch L.-bv) at 4.\n  setoid_rewrite (EqNewExch L.-bv) at 5.\n  setoid_rewrite (EqNewExch L.-bv) at 6.\n  setoid_rewrite (EqNewExch L.-bv) at 7.\n  under_new rewrite new_pars_remove; last first.\n  apply EqRefl.\n  \n  setoid_rewrite (EqNewExch L.-bv) at 1.\n  setoid_rewrite (EqNewExch L.-bv) at 2.\n  setoid_rewrite (EqNewExch L.-bv) at 3.\n  setoid_rewrite (EqNewExch L.-bv) at 4.\n  setoid_rewrite (EqNewExch L.-bv) at 5.\n  setoid_rewrite (EqNewExch L.-bv) at 6.\n  under_new rewrite new_pars_remove; last first.\n  apply EqRefl.\n\n\n  (* Now undep the leaks *)\n  etransitivity.\n  repeat ltac:(apply EqCongNew; intro).\n  swap_at 4 0 1.\n  (* leak_ok_o3 *)\n  swap_tac 0 4.\n  swap_tac 1 7.\n  rewrite -pars_mkdep //=.\n\n  (* leak_ok_o2 *)\n  swap_tac 0 5.\n  swap_at 0 0 1.\n  swap_tac 1 4.\n  rewrite -pars_mkdep //=.\n\n  (* leak_ot_o1 *)\n  swap_tac 0 6.\n  swap_at 0 0 1.\n  swap_tac 1 2.\n  rewrite -pars_mkdep //=.\n  edit_tac 3.\n\n    r_swap 1 3.\n    r_swap 2 6.\n    r_swap 3 9.\n    r_swap 4 12.\n    r_swap 5 15.\n    rewrite !EqReadSame.\n    apply EqBind_r => i.\n    r_swap 1 2.\n    rewrite !EqReadSame.\n    apply EqBind_r => x.\n    rewrite !EqReadSame.\n    apply EqBind_r => y.\n    r_swap 1 2.\n    rewrite !EqReadSame.\n    apply EqBind_r => z.\n    rewrite !EqReadSame.\n    apply EqBind_r => w.\n    r_swap 1 2.\n    rewrite !EqReadSame.\n    apply EqBind_r => a.\n    rewrite !EqReadSame.\n    apply EqRxnRefl.\n  apply EqRefl.\n\n  (* Now fold in the samps *)\n  simpl.\n  setoid_rewrite (EqNewExch L.-bv) at 5.\n  swap_tac 0 3.\n  under_new swap_at 0 0 1.\n  simpl.\n  swap_tac 1 2.\n  under_new rewrite pars_fold; [ apply EqRefl ].\n\n  simpl.\n  under_new swap_at 0 0 3.\n  simpl.\n  swap_tac 1 3.\n  setoid_rewrite (EqNewExch L.-bv) at 3.\n  setoid_rewrite (EqNewExch L.-bv) at 4.\n  under_new rewrite pars_fold; [ apply EqRefl ].\n\n  simpl.\n  under_new swap_at 0 0 5.\n  simpl.\n  setoid_rewrite (EqNewExch L.-bv) at 1.\n  setoid_rewrite (EqNewExch L.-bv) at 2.\n  setoid_rewrite (EqNewExch L.-bv) at 3.\n  swap_tac 1 2.\n  under_new rewrite pars_fold; [ apply EqRefl ].\n\n  (* Now simplify leak_send *)\n  simpl.\n  etransitivity.\n  apply EqCongNew; intro.\n  apply EqCongNew; intro.\n  apply EqCongNew; intro.\n  edit_tac 0.\n    r_swap 0 3.\n    r_swap 1 4.\n    r_swap 2 5.\n    r_swap 3 6.\n    r_swap 4 7.\n    apply EqBind_r; intro.\n    apply EqBind_r; intro.\n    apply EqBind_r; intro.\n    apply EqBind_r; intro.\n    apply EqBind_r; intro.\n    instantiate (1 := fun x3 =>\n                   x4 <-- Samp Unif ;;\n                   x5 <-- Samp Unif ;;\n                   x6 <-- Samp Unif ;;\n                   Ret (\n                       let o := (x3 # x.1) # x.2 in\n                       let o0 := if x.2 && x.1 then o else tzero _ in\n                       let o1 := if (~~ x.2) && x.1 then o else tzero _ in\n                       let o2 := if (x.2) && (~~ x.1) then o else tzero _ in\n                       let o3 := if (~~ x.2) && (~~ x.1) then o else tzero _ in\n                       ( (\n                              (x2, x4) # x.1 +t (x0, x6) # x.2 +t o3,\n                              (x2, x4) # x.1 +t (x6, x0) # x.2 +t o2 ),\n                         ( \n                              (x4, x2) # x.1 +t (x1, x5) # x.2 +t o1,\n                              (x4, x2) # x.1 +t (x5, x1) # x.2 +t o0 )\n                            ))).\n    simpl.\n    destruct x3 as [[m0 m1] [m2 m3]]; simpl.\n    destruct x as [ [ | ] [ | ]]; simpl.\n\n    rewrite (bind_samp_xor m1).\n    apply EqBind_r => x.\n    rewrite (bind_samp_xor m2).\n    apply EqBind_r => y.\n    rewrite (bind_samp_xor (m1 +t m0)).\n    apply EqBind_r => z.\n    rewrite (xortC _ x0).\n    rewrite !xortA !xortK !xort0.\n    rewrite (xortC m1) xortA xortK xort0.\n    rewrite (xortC x0) //=.\n\n    rewrite (bind_samp_xor m0).\n    apply EqBind_r => x.\n    rewrite (bind_samp_xor m3).\n    apply EqBind_r => y.\n    rewrite (bind_samp_xor (m0 +t m1)).\n    apply EqBind_r => z.\n    rewrite (xortC _ x0).\n    rewrite !xortA !xortK !xort0.\n    rewrite (xortC m0) xortA xortK xort0.\n    rewrite (xortC x0) //=.\n\n    rewrite (bind_samp_xor m3).\n    apply EqBind_r => x.\n    rewrite (bind_samp_xor (m3 +t m2)).\n    apply EqBind_r => y.\n    rewrite (bind_samp_xor m0).\n    apply EqBind_r => z.\n    rewrite !xortA !xortK !xort0.\n    rewrite (xortC m3) xortA xortK xort0.\n    rewrite (xortC m3) xortA xortK xort0 //=.\n\n    rewrite (bind_samp_xor m2).\n    apply EqBind_r => x.\n    rewrite (bind_samp_xor (m3 +t m2)).\n    apply EqBind_r => y.\n    rewrite (bind_samp_xor m1).\n    apply EqBind_r => z.\n    rewrite !xortA !xortK !xort0.\n    rewrite (xortC m3) xortA xortK xort0.\n    rewrite (xortC m2) xortA xortK xort0 //=.\n    rewrite (xortC m2) xortA xortK xort0 //=.\n    apply EqRefl.\n\n    rewrite /OT14_real_rerandomize.\n    apply EqCongNew => c.\n    apply EqCongNew => c1.\n    apply EqCongNew => c2.\n    align.\n    apply EqCongReact; apply EqBind_r; intro; rewrite EqBindRet //=.\n    apply EqCongReact; apply EqBind_r; intro; rewrite EqBindRet //=.\n Qed.\n\nDefinition OT14_sim (out : chan L.-bv) :=\nc <- new L.-bv;;\nc0 <- new L.-bv;;\nc1 <- new L.-bv;;\n[pars [:: Out leak_send\n          (\n            o <-- Read out ;;\n            x <-- Read ot14_i;;\n             x0 <-- Read c1;;\n             x1 <-- Read c0;;\n             x2 <-- Read c;;\n             x4 <-- Samp Unif;;\n             x5 <-- Samp Unif;;\n             x6 <-- Samp Unif;;\n             Ret\n               (\n                let o0 := if x .2 && x .1 then o else tzero L in\n                let o1 := if ~~ x .2 && x .1 then o else tzero L in\n                let o2 := if x .2 && ~~ x .1 then o else tzero L in\n                let o3 := if ~~ x .2 && ~~ x .1 then o else tzero L in\n                ((((x2, x4) # x .1 +t (x0, x6) # x .2) +t o3,\n                  ((x2, x4) # x .1 +t (x6, x0) # x .2) +t o2),\n                (((x4, x2) # x .1 +t (x1, x5) # x .2) +t o1,\n                ((x4, x2) # x .1 +t (x5, x1) # x .2) +t o0))));\n          Out leak_ot_o1 (_ <-- Read ot14_i;; Read c);\n          Out leak_ot_o3 (_ <-- Read ot14_i;; Read c0);\n          Out leak_ot_o2 (_ <-- Read ot14_i;; y <-- Read c1;; Ret y);\n          Out c1 (Samp Unif); Out c (Samp Unif); \n          Out c0 (Samp Unif) ] ].\n\nLemma OT14_real_simE :\n  OT14_real_rerandomize =p\n                           o <- new L.-bv ;;\n                           pars [::\n                                   OT14Ideal _ ot14_i ot14_m ot14_o;\n                                   OT14Ideal _ ot14_i ot14_m o;\n                                   OT14_sim o ].\n  symmetry.\n  rewrite /OT14Ideal.\n  rewrite /OT14_sim.\n  swap_tac 0 2.\n  repeat setoid_rewrite newPars.\n  repeat setoid_rewrite pars_pars; simpl.\n  etransitivity.\n  repeat ltac:(apply EqCongNew; intro).\n  do_inline; simp_all.\n  apply EqRefl.\n  setoid_rewrite (EqNewExch L.-bv) at 1.\n  setoid_rewrite (EqNewExch L.-bv) at 2.\n  setoid_rewrite (EqNewExch L.-bv) at 3.\n  swap_tac 0 7.\n  under_new rewrite new_pars_remove. apply EqRefl.\n  rewrite /OT14_real_rerandomize.\n  apply EqCongNew => c.\n  apply EqCongNew => c0.\n  apply EqCongNew => c1.\n  swap_tac 0 6.\n  apply pars_cons_cong.\n  apply EqCongReact.\n  r_swap 1 2.\n  rewrite EqReadSame.\n  apply EqBind_r; intro.\n  r_swap 0 1.\n  apply EqBind_r; intro.\n  r_swap 0 1.\n  apply EqBind_r; intro.\n  r_swap 0 1.\n  apply EqBind_r; intro.\n  apply EqBind_r; intro.\n  apply EqBind_r; intro.\n  apply EqBind_r; intro.\n  apply EqBind_r; intro.\n  destruct x as [ [|] [|] ]; done.\n  align.\n  apply _.\n  apply _.\n  apply _.\nQed.\n\nDefinition OT14_sim_ideal :=\n                           o <- new L.-bv ;;\n                           pars [::\n                                   OT14Ideal _ ot14_i ot14_m ot14_o;\n                                   OT14Ideal _ ot14_i ot14_m o;\n                                   OT14_sim o ].\n  \n\nTheorem OT14_security :\n  OT14_real =p OT14_sim_ideal.\n  rewrite ot14_simp.\n  rewrite ot_simpl_rerandomize.\n  rewrite OT14_real_simE.\n  done.\nQed.\n\n\nDefinition ot14_chans := \n[:: tag ot14_o; tag leak_ot_o1; tag leak_ot_o2; tag leak_ot_o3; tag leak_send].\n\nLemma OT14_t : ipdl_t ot14_chans OT14_real. \n  rewrite /OT14_real /OTIdeal.\n  rewrite /One4_sender /One4_recv.\n  repeat type_tac.\n  perm_match_step; rewrite insert_0.\n  perm_match_step.\n  perm_match_step.\n  simpl in *.\n  perm_match.\nQed.\n\nLemma OT14_sim_t o : ipdl_t [:: tag leak_send; tag leak_ot_o1; tag leak_ot_o3; tag leak_ot_o2] (OT14_sim o).\n  rewrite /OT14_sim.\n  repeat type_tac.\n  perm_match.\nQed.\n\nLemma OT14_sim_ideal_t : ipdl_t ot14_chans OT14_sim_ideal.\n  rewrite /OT14_sim_ideal.\n  rewrite /OT14Ideal.\n  repeat type_tac.\n  apply OT14_sim_t.\n  rewrite /ot14_chans.\n  perm_match.\nQed.\n\nEnd OneOutOf4.\n", "meta": {"author": "ipdl", "repo": "ipdl", "sha": "d41b022c9a216acfefaefcbd0ede9e52e350ab8a", "save_path": "github-repos/coq/ipdl-ipdl", "path": "github-repos/coq/ipdl-ipdl/ipdl-d41b022c9a216acfefaefcbd0ede9e52e350ab8a/theories/protocols/OT/OutOf4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.2137486199339377}}
{"text": "\nRequire Import GraphBasics.Graphs.\nRequire Import Coq.Logic.Classical_Prop.\nRequire Import Verdi.Verdi.\n\nRequire Export StructTact.Fin.\n\nRequire Import ExtrOcamlBasic.\nRequire Import ExtrOcamlNatInt.\n\nRequire Import Verdi.ExtrOcamlBasicExt.\nRequire Import Verdi.ExtrOcamlList.\n\nLoad PO_III. \n\n(* helping functions*)\n\nFixpoint remove (x : Component) (l : list Component) : list Component :=\n    match l with\n      | [] => []\n      | y::tl => if ((Component_index x) == (Component_index y)) then tl else y::(remove x tl)\n    end.\n\nDefinition empty (l : list Component) : bool :=\n  match l with\n  | nil => true\n  | a :: m => false\n  end.\n\n(***)\n\n\nInductive Name := Checker : Component  -> Name.\n\n(* get component from name*)\nDefinition name_component (n: Name): Component :=\nmatch n with \n  | Checker x => x\nend.\n\nDefinition Nodes : list Name := (map Checker (CV_list v a g)) . \n\nAxiom all_Names_Nodes : forall n, In n Nodes.\n\nAxiom NoDup_Nodes : NoDup Nodes.\n\n\nDefinition Name_eq_dec : forall x y : Name, {x = y} + {x <> y}.\n  decide equality.\n  destruct c. destruct c0. \n  case (eq_nat_dec n n0); intros H.\n  left; rewrite H; trivial.\n  right; injection; trivial.\nQed.\n\nInductive Msg := Checkermessage : list Fact -> Msg.\n\nDefinition Msg_eq_dec : forall x y : Msg, {x = y} + {x <> y}.\ndecide equality.\napply list_eq_dec.\napply fact_eq_dec. \nQed.\n\n\nRecord Checkerknowledge: Set := mk_Checkerknowledge {\n  Inp : list inp;\n  Sub_predicates: list Predicate;\n  facts: list Key\n}.\n\nRecord Checkerinput  := mk_Checkerinput {\noutput : list outp;\ncertificate : list Fact\n}.\n\n\nInductive Input : Type := \n  | ci : Checkerinput -> Input\n  | li : Checkerknowledge -> Input.\n\nDefinition Output := Msg.\n\n\n\nRecord Data := mkData{\n queue : list Component ;\n messages_received : list Component; \n consistent : bool ; \n checkerresult: bool; \n checkerinput : Checkerinput ; \n localinput : Checkerknowledge; \n initialized_localinput: bool;\n initialized_checkerinput: bool;\n control_neighbourlist: list Component\n }.\n\n\nDefinition init_Data (n: Name) := mkData\n(neighbors g (name_component n)) [] true false (mk_Checkerinput [] [(fact_cons keynull valuenull)] ) (mk_Checkerknowledge []  []  []) false false (neighbors g (name_component n)).\n\nDefinition set_queue a v := mkData v  (messages_received a) (consistent a) (checkerresult a) (checkerinput a) (localinput a) (initialized_localinput a) (initialized_checkerinput a)(control_neighbourlist a) .\nDefinition set_consistent a v:= mkData (queue a) (messages_received a)  v (checkerresult a) (checkerinput a) (localinput a)(initialized_localinput a)(initialized_checkerinput a)(control_neighbourlist a).\nDefinition set_queue_consistent a q r c:= mkData q r  c (checkerresult a)(checkerinput a) (localinput a)(initialized_localinput a)(initialized_checkerinput a)(control_neighbourlist a).\nDefinition set_checkeroutput_queue a q r v:= mkData q r (consistent a)  v (checkerinput a) (localinput a)(initialized_localinput a)(initialized_checkerinput a)(control_neighbourlist a).\n\n\n\n(* Send messages to all entries of a list (neighbours)*)\nFixpoint sendlist (neighbours: list Component) (me : Component)(cert: list Fact): list (Name * Msg)  :=\n         match neighbours with \n              | nil => [(Checker me, Checkermessage cert)]\n              | n::m => (Checker n, Checkermessage cert) :: (sendlist m me cert)\n         end.\n\n\n\n(**** 2 Inputs -> 1. Input Checkerknowledge  2. Input Checkerinput (from component) **)\nDefinition InputHandler (me : Name) (c : Input) (state: Data) :\n            (list Output) * Data * list (Name * Msg) := \n\tmatch me,c  with\n    (**** Initialize with Checkerknowledge  **)\n    | Checker x, li locali => if  (eqb state.(initialized_localinput)  false) then \n                             (* let myneighbors := (neighbors g x) in*)\n                             ( [] , (mkData (queue state) [] true (checkerresult state) (checkerinput state) locali true (initialized_checkerinput state) (control_neighbourlist state)) , [])\n      \n                              else ([], state, [])\n    (**** Initialize with Checkerinput, send message to all neighbours **)             \n\t\t| Checker x, ci checkeri => if  (eqb state.(initialized_checkerinput) false)   then \n                                let cert := checkeri.(certificate) in\n                                ( [] , (mkData (queue state) [] (consistent state) (checkerresult state) checkeri (localinput state)(initialized_localinput state) true (control_neighbourlist state) ), (sendlist state.(queue) x cert)) \n                                \n\n                                else ([], state, [])\n                  \n\tend.\n\n\n(** Check Consistency for a single fact *)\nDefinition One_Fact_Consistency_Check (c1 c2 : list Fact)  (key : Key) : bool := \nmatch (overlap c1 c2 key) with \n          | (Some x, Some y) => if (beqValue  (findValue  c1 (Some x)) (findValue  c2 (Some y))) then true else false \n          | (None, None) => false\n          | (None, Some _ ) => false\n          | (Some _, None ) => false\nend.\n\n\n(** Check Consistency for all facts in a fact list; return true if consistency is given for two certificate lists *)\nFixpoint All_Fact_Consistency_Check_ (init: bool) (c1 c2 : list Fact)  (keys : list Key) : bool := \nmatch keys with \n          | nil  => init \n          | a :: b => ( One_Fact_Consistency_Check c1 c2 a ) && All_Fact_Consistency_Check_ init c1 c2 b\nend.\n\nFunctional Scheme all_fact_ind := Induction for All_Fact_Consistency_Check_  Sort Prop.\n\n(** Initialize Consistency Check with true - Consistency Check for an empty list of facts returns true as well *)\nDefinition All_Fact_Consistency_Check := All_Fact_Consistency_Check_ true.\n\n(*stub-function for next phase of checker, e.g. decide sub-predicates*)\nVariable Check : Checkerknowledge -> Checkerinput -> bool.\n\nDefinition NetHandler (me : Name) (src: Name) (m : Msg) (state: Data) : \n    (list Output) * Data * list (Name * Msg) :=\n    \n  \n   (****  Consistency Check **)\n    match m with\n      | Checkermessage certif => if  (state.(initialized_localinput) && state.(initialized_checkerinput)) then\n\n                                     let c := state.(checkerinput) in \n                                     let l := state.(localinput) in\n                                     let mycertif := c.(certificate) in\n                                     let consistent := state.(consistent) && All_Fact_Consistency_Check mycertif certif l.(facts) in\n                                      \n                                       if (empty (remove (name_component src) state.(queue)) && (eqb consistent true)) then\n                                            let result := Check state.(localinput) state.(checkerinput) in (** check () **) \n     \t                                      ([], (set_checkeroutput_queue state (remove  (name_component src) state.(queue)) ([(name_component src)] ++ state.(messages_received)) result) , []) (** finales Resultat **)\n                                       else ([], (set_queue_consistent state  (remove  (name_component src) state.(queue)) ([(name_component src)] ++ state.(messages_received))  consistent), [])       \n                                 else ([], state,[])\n   end.\n\n\n\n(* verdi stuff*)\n\nInstance Checker_BaseParams : BaseParams :=\n  {\n    data := Data;\n    input := Input;\n    output := Output\n  }.\n\nInstance Checker_MultiParams : MultiParams Checker_BaseParams :=\n  {\n    name := Name;\n    name_eq_dec := Name_eq_dec;\n    msg := Msg;\n    msg_eq_dec := Msg_eq_dec;\n    nodes := Nodes;\n    all_names_nodes := all_Names_Nodes;\n    no_dup_nodes := NoDup_Nodes;\n    init_handlers := init_Data; \n    input_handlers := InputHandler ;\n    net_handlers := NetHandler\n    \n    }.\n\n(** helping functions for verification **)\n\n(* get certificate in message *)\nDefinition certificate_from_message ( msg: Msg) :  list Fact :=\nmatch msg with \n  | Checkermessage certif => certif\nend. \n\nDefinition initialized (state: Data) :=\n(state.(initialized_localinput) && state.(initialized_checkerinput)).\n\n(* If one fact consistency check returns true for x y na, then we have fact consistency for x y na *)\nLemma One_Fact_Consistency_Check_true:\nforall cert1 cert2 key, One_Fact_Consistency_Check cert1 cert2 key = true -> consistent_in_var cert1 cert2 key.\nProof.\nintros.\nunfold One_Fact_Consistency_Check in *.\nunfold consistent_in_var.\nrepeat break_match.\nintros.\ninversion H0.\napply beqValue_eq in Heqb.\ntrivial.\ndiscriminate.\ndiscriminate.\ndiscriminate.\ndiscriminate.\nQed.\n\n(* helping lemma *)\nLemma Consistency_Check_List:\nforall a c1 c2 keys, (forall k, In k (a :: keys) -> One_Fact_Consistency_Check c1 c2 k = true) -> (forall m : Key, In m keys -> One_Fact_Consistency_Check c1 c2 m = true ).\nProof.\nintros.\napply in_cons with (a:=a0) in H0.\napply H in H0.\ntrivial.\nQed.\n\n(* If one fact consistency check returns true for x y and all facts in fact list, then All_Fact_Consistency Check returns true for x y and fact list*)\nLemma one_fact_all_fact :\nforall c1 c2 keys, (forall k,  In k keys ->  One_Fact_Consistency_Check c1 c2 k = true) -> All_Fact_Consistency_Check c1 c2 keys = true.\nProof.\nintros.\nunfold All_Fact_Consistency_Check.\ninduction keys.\nunfold All_Fact_Consistency_Check_.\ntrivial.\nunfold All_Fact_Consistency_Check_.\napply andb_true_iff.\nsplit.\napply H with (k:=a0).\napply in_eq.\nfold All_Fact_Consistency_Check_.\napply IHkeys.\nintros.\napply Consistency_Check_List with (a:=a0) (keys :=keys).\napply H .\ntrivial.\nQed.\n\nLemma both_one_fact_all_fact :\nforall c1 c2 keys, All_Fact_Consistency_Check c1 c2 keys = true -> (forall k,  In k keys ->  One_Fact_Consistency_Check c1 c2 k = true)  .\nProof.\nintros.\nunfold All_Fact_Consistency_Check in *.\nunfold All_Fact_Consistency_Check_ in *.\ninduction keys.\nunfold One_Fact_Consistency_Check.\n  repeat break_match; repeat tuple_inversion;\n      subst; simpl in *; subst; simpl in *.\ntrivial.\nexfalso.\ntrivial.\nexfalso.\ntrivial.\nexfalso.\ntrivial.\nexfalso.\ntrivial.\n\nfold All_Fact_Consistency_Check_ in *.\napply andb_true_iff in H.\ndestruct H.\ndestruct H0.\nrewrite H0 in H.\ntrivial.\napply IHkeys.\nauto.\nauto.\nQed.\n\nVariable localin : Checkerknowledge.\n\n\nLemma both_one_fact_all_fact_allna :\nforall c1 c2, All_Fact_Consistency_Check c1 c2 localin.(facts) = true -> \n(forall k,  In k localin.(facts) ->  One_Fact_Consistency_Check c1 c2 k = true)  .\nProof.\nintros.\napply both_one_fact_all_fact with (keys:=localin.(facts)).\ntrivial.\ntrivial.\nQed.\n\nDefinition keylist (a : list Fact) : list Key :=   map fact_key a.\n\nVariable all_Keys: list Key.\nAxiom all_in_all_Keys:\nforall key: Key , In key all_Keys.\n\n\nAxiom keylistprop: forall k cert1 n,  get_pos cert1 k = Some n -> In k (keylist cert1).\n\nAxiom allkeylist: forall k cert1 , In k (facts localin) <-> In k (keylist cert1).\n\nLemma inkeylist:\nforall cert1 cert2 k, overlapping_in_var cert1 cert2 k -> In k (keylist cert1).\nProof.\nintros.\nunfold overlapping_in_var in *.\nunfold overlap in *.\nrepeat break_match. \napply keylistprop in Heqo; trivial.\ndestruct H. destruct H. discriminate.\ndestruct H. destruct H.  discriminate.\ndestruct H. destruct H.  discriminate.\nQed.\n\nLemma All_Fact_Consistency_Check_for_true:\nforall cert1 cert2 , All_Fact_Consistency_Check cert1 cert2 localin.(facts) = true -> consistent_in_all_var cert1 cert2.\nProof.\nintros.\napply consistency_defs.\nunfold consistent_alt.\nintros.\napply both_one_fact_all_fact_allna with (k:=k) in H.\nunfold overlapping_in_var in H0.\napply One_Fact_Consistency_Check_true in H.\nunfold consistent_in_var in H.\nunfold overlap in *.\nrepeat break_match.\ndestruct H0. destruct H0.\nassert (G:=H0). apply H in H0. inversion G. rewrite <- H2. rewrite <-  H3. trivial.\ndestruct H0. destruct H0. discriminate. \ndestruct H0. destruct H0. discriminate. \ndestruct H0. destruct H0. discriminate. \ntrivial.\napply inkeylist in H0.\napply allkeylist in H0.\ntrivial.\nQed.\n\n\n\n\n(************************ FOR ALL IN MESSAGES RECEIVED -> ALL FACT CONSISTENCY ********************)\n\n\n\nLemma inititialized_nethandler_b:\nforall me src msg data u dataout st', \nNetHandler me src msg data = (u, dataout, st') ->\ninitialized dataout = true -> initialized data = true.\nProof.\nintros.\nunfold NetHandler in *.\nrepeat break_match.\ninversion H.\nunfold initialized.\ntrivial.\ntrivial.\ninversion H.\ntrivial.\nQed.\n\nLemma inititialized_nethandler_:\nforall me src msg data u dataout st', \nNetHandler me src msg data = (u, dataout, st') ->\ninitialized_localinput data &&\ninitialized_checkerinput data  = true ->\ninitialized_checkerinput dataout = true.\nProof.\nintros.\nunfold NetHandler in *.\nrepeat break_match.\nunfold set_checkeroutput_queue in H.\nfind_inversion. simpl in *. \napply andb_true_iff in Heqb.\ndestruct Heqb.\ntrivial.\nfind_inversion. simpl in *. \napply andb_true_iff in Heqb.\ndestruct Heqb.\ntrivial.\ndiscriminate.\nQed.\n\nLemma inititialized_nethandler_2:\nforall me src msg data u dataout st', \nNetHandler me src msg data = (u, dataout, st') ->\ninitialized_localinput data &&\ninitialized_checkerinput data  = true ->\ninitialized_localinput dataout = true.\nProof.\nintros.\nunfold NetHandler in *.\nrepeat break_match.\nunfold set_checkeroutput_queue in H.\nfind_inversion. simpl in *. \napply andb_true_iff in Heqb.\ndestruct Heqb.\ntrivial.\nfind_inversion. simpl in *. \napply andb_true_iff in Heqb.\ndestruct Heqb.\ntrivial.\ndiscriminate.\nQed.\n\nLemma consistent_nethandler_b:\nforall me src msg data u dataout st', \nNetHandler me src msg data = (u, dataout, st') ->\nconsistent dataout = true -> consistent data = true.\nProof.\nintros.\nunfold NetHandler in *.\nrepeat break_match.\nunfold set_checkeroutput_queue in H.\nfind_inversion. simpl in *. trivial.\nfind_inversion. simpl in *. apply andb_true_iff in H0.\ndestruct H0. trivial.\ninversion H.\ntrivial.\nQed.\n\nLemma consistent_inputhandler_b:\nforall me input data u dataout l , \nInputHandler me input data = (u, dataout, l) ->\ninitialized data = true -> \nconsistent dataout = true -> consistent data = true.\nProof.\nintros.\nunfold InputHandler in *.\nrepeat break_match.\nfind_inversion. simpl in *. trivial.\nfind_inversion. trivial.\nfind_inversion. simpl in *. unfold initialized in H0.\napply andb_true_iff in H0. destruct H0.\napply eqb_prop in Heqb. rewrite H in Heqb. discriminate.\nfind_inversion. trivial.\nQed.\n\n\nLemma initialized_inputhandler_b:\nforall me input data u dataout l , \nInputHandler me input data = (u, dataout, l) ->\nmessages_received dataout <> [] -> \ninitialized dataout = true -> initialized data = true.\nProof.\nintros.\nunfold InputHandler in *.\nrepeat break_match.\nfind_inversion. simpl in *. contradiction.\n\nfind_inversion. trivial.\nfind_inversion. simpl in *. contradiction.\nfind_inversion. trivial.\nQed.\n\n\nAxiom certificate_from_src :\nforall l me src msg data u dataout st', \nNetHandler me src msg data = (u, dataout, st') ->\nmsg = Checkermessage l ->\ngetCertificate (name_component src) =  l.\n\nLemma consistency_check_in_src :\nforall me src msg data u dataout st', \ninitialized data = true -> \nNetHandler me src msg data = (u, dataout, st') ->\ndataout.(consistent) = true -> \nAll_Fact_Consistency_Check data.(checkerinput).(certificate) (getCertificate (name_component src))  data.(localinput).(facts) = true.\nProof.\nintros.\nassert (G:=H0).\nunfold NetHandler in H0.\nrepeat break_match.\n- apply andb_true_iff in Heqb0.\ndestruct Heqb0.\napply eqb_prop in H3.\n\nrewrite  certificate_from_src with (data:=data)(me:=me)(src:=src)(msg:=msg)(u:=u)(dataout:=dataout)(st':=st')(l:=l).\ntrivial.\napply andb_true_iff  in H3.\ndestruct H3.\ntrivial.\ntrivial.\nrewrite Heqm.\ntrivial.\ntrivial.\n-\nrewrite  certificate_from_src with (data:=data)(me:=me)(src:=src)(msg:=msg)(u:=u)(dataout:=dataout)(st':=st')(l:=l).\nfind_inversion. simpl in *. subst. \napply andb_true_iff  in H1.\ndestruct H1.\ntrivial.\nrewrite Heqm.\ntrivial.\ntrivial.\n- unfold initialized in H.\nrewrite H in Heqb. \ndiscriminate.\nQed.\n\nLemma consistency_check_NetHandler :\nforall me src msg data u dataout st', \ninitialized dataout = true -> \ndataout.(consistent) = true ->\nNetHandler me src msg data = (u, dataout, st') ->\nforall k, \n(In k data.(messages_received)  -> \nAll_Fact_Consistency_Check data.(checkerinput).(certificate) (getCertificate  k)  data.(localinput).(facts) = true) ->\n(In k dataout.(messages_received) -> \nAll_Fact_Consistency_Check data.(checkerinput).(certificate) (getCertificate  k)  data.(localinput).(facts) = true).\nProof.\nintros.\nassert (G:=H0).\nassert (N:=H1).\nunfold NetHandler in H1.\nrepeat break_match.\n- apply andb_true_iff in Heqb0.\ndestruct Heqb0.\napply eqb_prop in H5.\napply andb_true_iff in H5.\ninversion H1. simpl in *.\nunfold set_checkeroutput_queue in H8.\nfind_inversion. simpl in *. subst.\ndestruct H3.\nrewrite <- H1.\napply consistency_check_in_src with  (me:=me)(src:=src)(msg:=Checkermessage l)(u:=[])(dataout:= {|\n    queue := remove (name_component src) (queue data);\n    messages_received := name_component src :: messages_received data;\n    consistent := consistent data;\n    checkerresult := Check (localinput data) (checkerinput data);\n    checkerinput := checkerinput data;\n    localinput := localinput data;\n    initialized_localinput := initialized_localinput data;\n    initialized_checkerinput := initialized_checkerinput data;\n    control_neighbourlist := control_neighbourlist data\n  |})(st':=[]).\n    unfold initialized.\n    trivial.\n    unfold NetHandler.  \n    apply N.\n    simpl in *.\n    destruct H5.\n    trivial.\n    apply H2.\n    trivial.\n   - apply andb_false_iff in Heqb0.\n     destruct Heqb0.\n     unfold set_queue_consistent in H1.\n     find_inversion. simpl in *. subst.\n     destruct H3.\n     rewrite <- H1.\n    apply consistency_check_in_src with  (me:=me)(src:=src)(msg:=Checkermessage l)(u:=[])(dataout:= {|\n      queue := remove (name_component src) (queue data);\n      messages_received := name_component src :: messages_received data;\n      consistent := consistent data &&\n                    All_Fact_Consistency_Check\n                      (certificate (checkerinput data)) l\n                      (facts (localinput data));\n      checkerresult := checkerresult data;\n      checkerinput := checkerinput data;\n      localinput := localinput data;\n      initialized_localinput := initialized_localinput data;\n      initialized_checkerinput := initialized_checkerinput data;\n      control_neighbourlist := control_neighbourlist data |} )(st':=[]).\n    unfold initialized.\n    trivial.\n     unfold NetHandler.  \n    apply N.\n    simpl in *.\n    apply G.\n    apply H2. \n    trivial.\n    inversion H1. simpl in *. subst.\n    unfold set_queue_consistent in G. simpl in *.\n    apply eqb_false_iff  in H4.\n    contradiction.\n   -apply inititialized_nethandler_b with (me:=me)(src:=src) (msg:=msg) (data:=data) (dataout:=dataout) (st':=st') (u:=u) in H.\n    unfold initialized in H.\n    rewrite H in Heqb.\n    discriminate.\n    rewrite Heqm.\n    trivial.\nQed.\n\nLemma facts_nethandler:\nforall me src msg data u dataout st', \nNetHandler me src msg data = (u, dataout, st') ->\ninitialized dataout = true -> \nfacts (localinput (data)) = facts (localinput (dataout)).\nProof.\nintros.\nunfold NetHandler in *.\nrepeat break_match.\nfind_inversion. simpl in *. reflexivity.\nfind_inversion. simpl in *. reflexivity.\nfind_inversion. simpl in *. reflexivity.\nQed.\n\nLemma certificate_nethandler:\nforall me src msg data u dataout st', \nNetHandler me src msg data = (u, dataout, st') ->\ninitialized dataout = true -> \n(certificate (checkerinput data )) = (certificate (checkerinput dataout)).\nProof.\nintros.\nunfold NetHandler in *.\nrepeat break_match.\nfind_inversion; simpl in *; reflexivity.\nfind_inversion; simpl in *; reflexivity.\nfind_inversion; simpl in *; reflexivity.\nQed.\n \n\nLemma certificate_inputhandler:\nforall me input data u dataout l, \nInputHandler me input data = (u, dataout, l) ->\nmessages_received dataout <> [] -> \n(certificate (checkerinput data )) = (certificate (checkerinput dataout)).\nProof.\nintros.\nunfold InputHandler in *.\nrepeat break_match.\nfind_inversion. simpl in *. contradiction.\nfind_inversion. trivial. \nfind_inversion. simpl in *. contradiction.\nfind_inversion. trivial. \nQed.\n\nLemma facts_inputhandler:\nforall me input data u dataout l, \nInputHandler me input data = (u, dataout, l) ->\nmessages_received dataout <> [] -> \nfacts (localinput (data)) = facts (localinput (dataout)).\nProof.\nintros.\nunfold InputHandler in *.\nrepeat break_match.\nfind_inversion. simpl in *. contradiction.\nfind_inversion. trivial. \nfind_inversion. simpl in *. contradiction.\nfind_inversion. trivial.\nQed. \n\nLemma consistency_check_Inputhandler :\nforall me input data u dataout l, \nInputHandler me input data = (u, dataout, l) ->\nmessages_received dataout <> []  -> \ndataout.(consistent) = true ->\nforall k, \n(In k data.(messages_received)  -> \nAll_Fact_Consistency_Check data.(checkerinput).(certificate) (getCertificate  k)  data.(localinput).(facts) = true) ->\n(In k dataout.(messages_received) -> \nAll_Fact_Consistency_Check dataout.(checkerinput).(certificate) (getCertificate  k)  dataout.(localinput).(facts) = true).\nProof.\nintros.\nassert (G:=H).\nassert (I:=H).\nunfold InputHandler in H.\nrepeat break_match.\nassert (K:=H0).\n\napply facts_inputhandler with (me:=me) (input:=input) (data:=data) (u:=u) (dataout:=dataout) (l:=l) in H0.\nrewrite <- H0.\napply certificate_inputhandler with (me:=me) (input:=input) (data:=data) (u:=u) (dataout:=dataout) (l:=l) in K.\nrewrite <- K.\napply H2.\nfind_inversion. simpl in *. subst.\ntrivial.\nexfalso. trivial.\nrewrite Heqi.\nrewrite Heqn.\ntrivial.\nrewrite Heqn.\nrewrite Heqi.\ntrivial.\n\nassert (K:=H0).\napply facts_inputhandler with (me:=me) (input:=input) (data:=data) (u:=u) (dataout:=dataout) (l:=l) in H0.\nrewrite <- H0.\napply certificate_inputhandler with (me:=me) (input:=input) (data:=data) (u:=u) (dataout:=dataout) (l:=l) in K.\nrewrite <- K.\napply H2.\nfind_inversion. simpl in *. subst.\ntrivial.\nrewrite Heqn.\nrewrite Heqi.\ntrivial.\nrewrite Heqn.\nrewrite Heqi.\ntrivial.\n\nfind_inversion. simpl in *. exfalso. trivial.\n\n\nassert (K:=H0).\napply facts_inputhandler with (me:=me) (input:=input) (data:=data) (u:=u) (dataout:=dataout) (l:=l) in H0.\nrewrite <- H0.\napply certificate_inputhandler with (me:=me) (input:=input) (data:=data) (u:=u) (dataout:=dataout) (l:=l) in K.\nrewrite <- K.\napply H2.\nfind_inversion. simpl in *. subst.\ntrivial.\nrewrite Heqn.\nrewrite Heqi.\ntrivial.\nrewrite Heqn.\nrewrite Heqi.\ntrivial.\nQed.\n\nLemma notEmptylist:\nforall (clist : list Component), clist <> [] -> exists (m:Component), In m clist.\nProof.\nintros.\ndestruct clist.\ncontradiction.\nexists c.\napply  in_eq .\nQed.\n\n\n\nLemma notEmptylist_b:\nforall (clist : list Component) m, In m clist -> clist <> [].\nProof.\nintros.\ndestruct clist.\ncontradiction.\napply not_eq_sym.\napply nil_cons.\nQed.\n\n\n\n\n\nLemma All_Fact_Consistency_Check_Network:\nforall  net tr,\nstep_async_star (params := Checker_MultiParams) step_async_init net tr ->\nforall component c,\n(nwState net (Checker c)).(initialized)  = true -> \n(nwState net (Checker c)).(consistent)  = true -> \n(In component (nwState net (Checker c)).(messages_received) ->\nAll_Fact_Consistency_Check  (nwState net (Checker c)).(checkerinput).(certificate) (getCertificate  component)  (nwState net (Checker c)).(localinput).(facts) = true).\nProof.\nintros net tr H .\nremember step_async_init as y in *.\ninduction H using refl_trans_1n_trace_n1_ind. intros. subst.\nsimpl in *.\nexfalso.\ntrivial.\nintros.\ninvc H0.\n\n- destruct p. destruct pDst. unfold nwState in *. unfold update in *. repeat break_match. \n+  unfold net_handlers in *. unfold Checker_MultiParams in *. simpl in *.\nassert (J:=H3).\n\napply consistency_check_NetHandler with (me :=(Checker c0)) (src:=pSrc)(u:=out) (st':=l) (k:=component) (data:=(nwState (Checker c0))) (msg:= pBody ) (dataout:=d)  in H3.\nrewrite <- certificate_nethandler with (me :=(Checker c0)) (src:=pSrc)(u:=out) (st':=l) (data:=(nwState (Checker c0))) (msg:= pBody ) (dataout:=d).\nrewrite <- facts_nethandler with (me :=(Checker c0)) (src:=pSrc)(u:=out) (st':=l) (data:=(nwState (Checker c0))) (msg:= pBody ) (dataout:=d).\napply H3.\ntrivial.\ntrivial.\ntrivial.\ntrivial.\ntrivial.\ntrivial.\napply IHrefl_trans_1n_trace1  with (c:=c0).\ntrivial.\napply consistent_nethandler_b  with (me :=(Checker c0)) (src:=pSrc)(u:=out) (st':=l)(data:=(nwState (Checker c0))) (msg:= pBody ) (dataout:=d)  in H3.\napply inititialized_nethandler_b  with (me :=(Checker c0)) (src:=pSrc)(u:=out) (st':=l)(data:=(nwState (Checker c0))) (msg:= pBody ) (dataout:=d)  in H2.\ntrivial.\ntrivial.\ntrivial.\napply consistent_nethandler_b  with (me :=(Checker c0)) (src:=pSrc)(u:=out) (st':=l)(data:=(nwState (Checker c0))) (msg:= pBody ) (dataout:=d)  in H3.\ntrivial.\ntrivial.\ntrivial.\n+\nconcludes. apply IHrefl_trans_1n_trace1. trivial. trivial. trivial.\n-destruct h. unfold nwState in *. unfold update in *. repeat break_match.\n+  unfold input_handlers in *. unfold Checker_MultiParams in *. concludes.\napply consistency_check_Inputhandler with (k:=component) in H5 .\ntrivial.\nassert (G:=H4).\napply notEmptylist_b in H4.\ntrivial.\ntrivial.\napply IHrefl_trans_1n_trace1 with (c:=c0).\napply initialized_inputhandler_b in H5.\ntrivial.\napply notEmptylist_b in H4.\ntrivial.\ntrivial.\napply consistent_inputhandler_b in H5.\ntrivial.\napply initialized_inputhandler_b in H5.\ntrivial.\napply notEmptylist_b in H4.\ntrivial.\ntrivial.\ntrivial.\ntrivial.\n+ concludes. apply IHrefl_trans_1n_trace1. trivial. trivial. trivial.\nQed.\n\n\nAxiom all_keys_in_nw:\nforall  net tr c,\nstep_async_star (params := Checker_MultiParams) step_async_init net tr ->\nfacts (localinput (nwState net (Checker c))) = localin.(facts).\n\nLemma All_Fact_Check_Network:\nforall  net tr,\nstep_async_star (params := Checker_MultiParams) step_async_init net tr ->\nforall component c,\n(nwState net (Checker c)).(initialized)  = true -> \n(nwState net (Checker c)).(consistent)  = true -> \n(In component (nwState net (Checker c)).(messages_received)) ->\nconsistent_in_all_var (nwState net (Checker c)).(checkerinput).(certificate) (getCertificate  component) .\nProof.\nintros.\napply All_Fact_Consistency_Check_for_true.\nrewrite <- all_keys_in_nw with (net:=net) (tr:=tr) (c:=c).\napply All_Fact_Consistency_Check_Network with (net:=net) (c:=c) (tr:=tr) (component:=component);trivial.\ntrivial.\nQed.\n\n(********************************* QUEUE EMPTY -> ALL IN MESSAGES RECEIVED ***************************************************************)\n\nLemma removeprop:\nforall name k l1 l2,\n In k (l1 ++ l2) ->\n In k   (remove (name_component name) l1 ++  name_component name :: l2).\nProof.\nintros. \napply in_app_or in H.\ndestruct H.\napply in_or_app.\n- assert ({k= name_component name} + {k <> name_component name}) .\n  destruct name.\n  destruct k.\n  destruct Checker.\n  destruct name_component.\n  destruct index.\n  apply V_eq_dec with (x:= index n1) (y:=index n0).\ndestruct H0.\nright.\nrewrite e.\napply in_eq .\nleft.\ninduction l1; auto.\ndestruct H. \nrewrite H. \nunfold remove. \nrepeat break_match.\napply beq_nat_true in Heqb.\nunfold Component_index in Heqb.\nrepeat break_match.\nrewrite Heqb in n.\ncontradiction.\nsimpl.\nleft.\nreflexivity.\nunfold remove.\nrepeat break_match. \ntrivial.\nfold remove.\nunfold In.\nright.\nunfold In in IHl1.\napply IHl1.\nunfold In in H.\ntrivial.\n- apply in_or_app.\nright.\napply in_cons with (a:=name_component name) in H.\ntrivial.\nQed.\n\n\nLemma allincontrol_queue_messagesreceived_nethandler:\nforall me src msg data u dataout st' k, \nNetHandler me src msg data = (u, dataout, st') ->\n(In k (control_neighbourlist data) -> In k ((queue data ) ++ (messages_received data))) ->\n(In k (control_neighbourlist dataout) -> In k ( ( queue dataout ) ++ (messages_received dataout))).  \nProof.\nintros.\nunfold NetHandler in *.\nrepeat break_match. inversion H.\nunfold set_checkeroutput_queue in * .\nfind_inversion. simpl in *.\napply removeprop with (l1:=queue data) (l2:=messages_received data) (k:=k) (name:=src).\n\n\napply H0.\ntrivial.\nintros.\nfind_inversion.\nunfold set_queue_consistent.\nsimpl in *.\napply removeprop with (l1:=queue data) (l2:=messages_received data) (k:=k) (name:=src).\napply H0.\ntrivial.\nintros.\n\nunfold NetHandler in *.\nrepeat break_match. inversion H.\nunfold set_checkeroutput_queue in * .\nfind_inversion. apply H0.\ntrivial.\nQed.\n\n\nLemma initialized_false__prop_nethandler_b:\nforall me src msg data u dataout st' , \nNetHandler me src msg data = (u, dataout, st') ->\ndataout.(initialized_checkerinput) = false -> \ndata.(initialized_checkerinput) = false.\nProof.\nintros.\nunfold NetHandler in *.\nrepeat break_match.\napply andb_true_iff in Heqb. destruct Heqb. unfold set_checkeroutput_queue. find_inversion. simpl in *.\nrewrite  H0 in H2. discriminate.\nunfold  set_queue_consistent . find_inversion. simpl in *.\napply andb_true_iff in Heqb. destruct Heqb. rewrite H0 in H1. discriminate.\nfind_inversion. trivial.\nQed.\n\nLemma initialized_false_network_nethandler:\nforall me src msg data u dataout st' , \nNetHandler me src msg data = (u, dataout, st') ->\ndata.(initialized_checkerinput) = false -> \ndata.(queue) = data.(control_neighbourlist) -> \ndataout.(queue) = dataout.(control_neighbourlist).\nProof.\nintros.\nassert (G:=H).\nunfold NetHandler in *.\nrepeat break_match.\napply andb_true_iff in Heqb. destruct Heqb. unfold set_checkeroutput_queue. find_inversion. simpl in *. rewrite H0 in H3. discriminate.\napply andb_true_iff in Heqb. destruct Heqb. rewrite H0 in H3. discriminate.\nfind_inversion. trivial.\nQed.\n\nLemma initialized_false_network:\nforall  net tr ,\nstep_async_star (params := Checker_MultiParams) step_async_init net tr ->\nforall c, \n(nwState net (Checker c)).(initialized_checkerinput) = false -> \n(nwState net (Checker c)).(queue) = (nwState net (Checker c)).(control_neighbourlist).\nProof.\n  intros net tr  H.\n  remember step_async_init as y in *.\n  induction H using refl_trans_1n_trace_n1_ind. intros. subst. reflexivity.\n  invc H0. \n  - intros.  destruct p. destruct pDst. unfold nwState in *. unfold update in *. repeat break_match.\n  +  unfold net_handlers in *. unfold Checker_MultiParams in *. simpl in *.\n     apply initialized_false_network_nethandler in H3. trivial. \n     apply initialized_false__prop_nethandler_b with (msg:=pBody) (src:=pSrc) (data:=(nwState (Checker c0))) (me:=(Checker c0)) (dataout:=d) (u:=out) (st':=l) in H3. trivial. trivial.\n     concludes. apply IHrefl_trans_1n_trace1  with (c:=c0). apply initialized_false__prop_nethandler_b with (msg:=pBody) (src:=pSrc) (data:=(nwState (Checker c0))) (me:=(Checker c0)) (dataout:=d) (u:=out) (st':=l) in H3. trivial. trivial.\n  +  concludes. apply IHrefl_trans_1n_trace1. trivial.\n  - intros. destruct h. unfold nwState in *. unfold update in *. repeat break_match.\n  *   unfold input_handlers in *. unfold Checker_MultiParams in *. concludes.\n  intros.\n  unfold InputHandler in *.\n  repeat break_match. \n  find_inversion. simpl in *. discriminate.\n  find_inversion. apply IHrefl_trans_1n_trace1  with (c:=c0). trivial.\n   find_inversion. simpl in *.  apply IHrefl_trans_1n_trace1  with (c:=c0). trivial. find_inversion. apply IHrefl_trans_1n_trace1  with (c:=c0). trivial.\n *  apply IHrefl_trans_1n_trace1. trivial. trivial.\nQed.\n\nLemma messages_received_not_empty_nethandler:\nforall  net tr,\nstep_async_star (params := Checker_MultiParams) step_async_init net tr ->\nforall c, \n(nwState net (Checker c)).(initialized_checkerinput) = false -> \n(nwState net (Checker c)).(queue) = (nwState net (Checker c)).(control_neighbourlist).\nProof.\n  intros net tr  H.\n  remember step_async_init as y in *.\n  induction H using refl_trans_1n_trace_n1_ind. intros. subst. reflexivity.\n  invc H0. \n\n  - intros. destruct (pDst p) eqn:?. unfold nwState in *. unfold update in *. repeat break_match.\n  + \n     unfold net_handlers in *. unfold Checker_MultiParams in *. assert (K:=H3). unfold NetHandler in H3. concludes.\n     repeat break_match.\n   apply inititialized_nethandler_ in K.  rewrite K in H0. discriminate. trivial.\n   apply inititialized_nethandler_ in K.  rewrite K in H0. discriminate. trivial.\n     find_inversion. apply IHrefl_trans_1n_trace1.  trivial.\n  + apply IHrefl_trans_1n_trace1. trivial. trivial.\n   - intros. destruct h. unfold nwState in *. unfold update in *. repeat break_match.\n\n  *   unfold input_handlers in *. unfold Checker_MultiParams in *. concludes.  unfold InputHandler in *.\n  repeat break_match. \n  find_inversion. simpl in *. discriminate.\n  find_inversion. apply IHrefl_trans_1n_trace1  with (c:=c0). trivial.\n   find_inversion. simpl in *. trivial.\n  find_inversion. apply IHrefl_trans_1n_trace1  with (c:=c0). trivial.\n  find_inversion. apply IHrefl_trans_1n_trace1  with (c:=c0). trivial.\n *  apply IHrefl_trans_1n_trace1. trivial. trivial.\nQed.\n\nLemma messages_received_not_empty_nethandler2:\nforall  net tr,\nstep_async_star (params := Checker_MultiParams) step_async_init net tr ->\nforall c, \n(nwState net (Checker c)).(initialized_localinput) = false -> \n(nwState net (Checker c)).(queue) = (nwState net (Checker c)).(control_neighbourlist).\nProof.\n  intros net tr  H.\n  remember step_async_init as y in *.\n  induction H using refl_trans_1n_trace_n1_ind. intros. subst. reflexivity.\n  invc H0. \n - intros. destruct (pDst p) eqn:?. unfold nwState in *. unfold update in *. repeat break_match.\n     unfold net_handlers in *. unfold Checker_MultiParams in *. assert (K:=H3). unfold NetHandler in H3. concludes.\n     repeat break_match.\n     apply inititialized_nethandler_2 in K. rewrite K in H0. discriminate. trivial.\n     apply inititialized_nethandler_2 in K.  rewrite K in H0. discriminate. trivial.\n         find_inversion. apply IHrefl_trans_1n_trace1.  trivial.\n      apply IHrefl_trans_1n_trace1. trivial. trivial. \n -  intros. destruct h. unfold nwState in *. unfold update in *. repeat break_match.\n * unfold input_handlers in *. unfold Checker_MultiParams in *. concludes. unfold InputHandler in *. repeat break_match. \n  find_inversion. simpl in *.  apply IHrefl_trans_1n_trace1 with (c:=c0); trivial.\n  find_inversion. apply IHrefl_trans_1n_trace1  with (c:=c0). trivial.\n  find_inversion.  simpl in *. apply IHrefl_trans_1n_trace1  with (c:=c0). apply eqb_prop in Heqb. discriminate.\n  find_inversion. apply IHrefl_trans_1n_trace1  with (c:=c0). trivial.\n *  apply IHrefl_trans_1n_trace1. trivial. trivial.\nQed.\n\n\n\nLemma queue_message_received_equals_controllist:\nforall  net tr,\nstep_async_star (params := Checker_MultiParams) step_async_init net tr ->\nforall k c,\nIn k (nwState net (Checker c)).(control_neighbourlist) -> \nIn k ( (nwState net (Checker c)).(queue) ++ (nwState net (Checker c)).(messages_received)). \nProof.\nintros net tr H.\n  remember step_async_init as y in *.\n  induction H using refl_trans_1n_trace_n1_ind. intros. subst. unfold step_async_init in *. unfold nwState in *. unfold init_handlers in *. unfold Checker_MultiParams in *. unfold init_Data in *. simpl in *. trivial. rewrite app_nil_r. trivial.\n- invc H0.\n+ destruct (pDst p) eqn:?.  unfold nwState in *. unfold update in *. intros. repeat break_match.\n  unfold net_handlers in *. unfold Checker_MultiParams in *. concludes.\n  apply allincontrol_queue_messagesreceived_nethandler with\n  (st':=l)(u:=out) (k :=k)(me:= (pDst p)) (src:=(pSrc p)) (msg:= (pBody p) )(data:= (nwState (Checker c)) ) (dataout:=d) in H3.\n  trivial.\n  apply IHrefl_trans_1n_trace1 with (k:=k) (c:=c).\n  simpl in *.\n  trivial.\n  apply IHrefl_trans_1n_trace1 with (k:=k) (c:=c0); trivial.\n+ intros. destruct h. unfold nwState in *. unfold update in *. repeat break_match.\n* \n  unfold input_handlers in *. unfold Checker_MultiParams in *. concludes.\n  intros.\n  unfold InputHandler in *.   repeat break_match.  find_inversion. intros. simpl in *. rewrite app_nil_r. \n  apply eqb_prop in Heqb.\n  apply messages_received_not_empty_nethandler with (c:=c) in H. simpl in *. \n  rewrite <- e. rewrite H. rewrite <-  e in H0. trivial. simpl in *. rewrite  e. trivial. \n  intros. find_inversion. apply IHrefl_trans_1n_trace1 with (c:=c0). trivial.\n  intros. find_inversion. simpl in *.  rewrite app_nil_r.   apply eqb_prop in Heqb. \n  apply messages_received_not_empty_nethandler2 with (c:=c0) in H. simpl in *. rewrite H. trivial. simpl in *. trivial.\n  find_inversion.  apply IHrefl_trans_1n_trace1 with (c:=c0). trivial. (*apply IHrefl_trans_1n_trace1 with (c:=c0). trivial.*)\n* intros.  apply IHrefl_trans_1n_trace1 . trivial. trivial. \nQed.\n    \n\n\n\nLemma queue_empty_message_received_equals_controllist:\nforall  net tr,\nstep_async_star (params := Checker_MultiParams) step_async_init net tr ->\nforall k c,\n(nwState net (Checker c)).(queue) = [] -> \nIn k (nwState net (Checker c)).(control_neighbourlist) ->\nIn k  (nwState net (Checker c)).(messages_received).\nProof.\nintros.\napply queue_message_received_equals_controllist with (k:=k) (c:=c) in H.\nrewrite  H0 in H.\nauto.\ntrivial.\nQed.\n\n(***************** ALL IN CONTROLL LIST ARE NEIGHBOURS *******************)\n\n\nLemma neighbours_controllist_nethandler:\nforall me src msg data u dataout st' k, \nNetHandler me src msg data = (u, dataout, st') ->\n(In k (neighbors g (name_component me) ) ->\nIn k (control_neighbourlist data))  -> \n( In k (neighbors g (name_component me)) ->\nIn k (control_neighbourlist dataout )).\nProof.\nintros.\nassert (K:=H).\nunfold NetHandler in *.\nrepeat break_match.\nunfold set_checkeroutput_queue in *.\ninversion H.\nsimpl in *.\napply  andb_true_iff in Heqb.\ndestruct Heqb.\napply H0.\ntrivial.\ninversion H.\nsimpl in *.\ntrivial.\nunfold set_queue_consistent.\ninversion H.\nsimpl in *.\napply H0.\ntrivial.\ninversion H.\nrewrite <- H4.\napply H0.\ntrivial.\nQed.\n\n\nLemma local_input_Inputhandler :\nforall me  data u input dataout l, \nInputHandler me input data = (u, dataout, l) ->\nforall k,\n( In k (neighbors g  (name_component me)) ->\nIn k data.(control_neighbourlist)) ->\n(In k (neighbors g  (name_component me)) ->\nIn k dataout.(control_neighbourlist)).\nProof.\nintros.\nunfold InputHandler in *.\nrepeat break_match.\nfind_inversion; simpl in *.\napply H0;trivial.\nfind_inversion; simpl in *.  apply H0;trivial.\nfind_inversion; simpl in *.  apply H0;trivial. \nfind_inversion; simpl in *.  apply H0;trivial. \nQed.\n\n\nLemma neighbours_in_controllist:\nforall  net tr ,\nstep_async_star (params := Checker_MultiParams) step_async_init net tr ->\nforall c k,\nIn k (neighbors g c) ->\nIn k (nwState net (Checker c)).(control_neighbourlist).\nProof. \nintros net tr H.\n  remember step_async_init as y in *.\n  induction H using refl_trans_1n_trace_n1_ind. intros. subst. unfold initialized in *. unfold step_async_init in *. unfold nwState in *. unfold init_handlers in *. unfold Checker_MultiParams in *. unfold init_Data in *. simpl in *. trivial.\n  (*step*)\n   invc H0.\n  \n  (*NetHandler*)\n  +\n  intros. destruct (pDst p) eqn:?. unfold nwState in *. unfold update in *. repeat break_match.\n -   unfold net_handlers in *. unfold Checker_MultiParams in *.\n     apply neighbours_controllist_nethandler with (k:=k) in H3. trivial. intros. apply IHrefl_trans_1n_trace1. trivial. trivial. rewrite <- e.  unfold name_component. trivial.\n  -   apply IHrefl_trans_1n_trace1; trivial. \n (*InputHandler*)\n  +   intros. destruct h. unfold nwState in *. unfold update in *. repeat break_match.\n  *   unfold input_handlers in *. unfold Checker_MultiParams in *. concludes.   assert (G:=H2). unfold InputHandler in H2.  repeat break_match.\n\n   apply local_input_Inputhandler with (k:=k) in G. trivial.  intros. apply IHrefl_trans_1n_trace1.  inversion e. rewrite <- H5. trivial. rewrite <- e.  unfold name_component. trivial.\n\n    find_inversion.  simpl in *.  apply IHrefl_trans_1n_trace1 . trivial.  inversion e. rewrite <- H3. trivial.\n       find_inversion.  simpl in *. inversion e. rewrite <- H3. apply IHrefl_trans_1n_trace1 . trivial.\n    find_inversion. simpl in *. rewrite <- e. apply IHrefl_trans_1n_trace1. trivial. \n *  concludes. apply IHrefl_trans_1n_trace1; trivial.\nQed.\n\n(*********************** FINAL THEOREM ***********************************)\n\nAxiom getCertificate_prop:\nforall  net c, \ncertificate (checkerinput (nwState net (Checker c))) =  (getCertificate (name_component (Checker c))).\n\nLemma Neighbourhood_Consistency_Ver:\nforall  net tr,\nstep_async_star (params := Checker_MultiParams) step_async_init net tr ->\nforall c,\n(nwState net (Checker c)).(consistent) = true -> \n(nwState net (Checker c)).(initialized) = true -> \n(nwState net (Checker c)).(queue) = [] -> \nneighbourhood_consistent( name_component (Checker c)).\nProof.\nintros.\nunfold neighbourhood_consistent.\nintros.\napply All_Fact_Check_Network  with (component := comp1) (c:=c) in H.\ntrivial.\nrewrite <- getCertificate_prop with (net:=net).\napply H.\napply queue_empty_message_received_equals_controllist with (k:=comp1) (c:=c) in H.\ntrivial.\ntrivial.\nunfold initialized in H1. \napply  andb_true_iff in H1.\ndestruct H1. \napply neighbours_in_controllist with (k:=comp1) (c:=c) (tr:=tr) (net:=net) in H3.\ntrivial.\ntrivial.\nunfold name_component in H3; trivial.\ntrivial.\napply queue_empty_message_received_equals_controllist with (k:=comp1) (c:=c) (tr:=tr).\ntrivial.\ntrivial.\napply neighbours_in_controllist with (k:=comp1) (tr:=tr).\ntrivial.\ntrivial.\nQed.\n\nExtraction \"Checker_Consistent.ml\"  Checker_BaseParams Checker_MultiParams.\n\n", "meta": {"author": "voellinger", "repo": "verified-certifying-distributed-algorithms", "sha": "35b2a4dc5c0aec6228ded6b10bbe4d086692dadb", "save_path": "github-repos/coq/voellinger-verified-certifying-distributed-algorithms", "path": "github-repos/coq/voellinger-verified-certifying-distributed-algorithms/verified-certifying-distributed-algorithms-35b2a4dc5c0aec6228ded6b10bbe4d086692dadb/framework/consistency/PO_IV_iii.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.21374861181790392}}
{"text": "Require Import syntax.\nRequire Import partial.\nRequire Import heap.\nRequire Import classTable.\nRequire Import sframe.\nRequire Import reductions.\nRequire Import typing.\nRequire Import namesAndTypes.\nRequire Import preservation.\n\nRequire Import wf_env.\n\nImport ConcreteEverything.\n\n\nSection Preservation_fix.\n\n  Variable P: Program.\n\n  Definition subtypeP := subtype P.\n  Definition fldP := fld P.\n  Definition ftypeP := ftype P.\n  Definition t_frame1' := t_frame1 P.\n  Definition WF_Frame' := WF_Frame P.\n\n  Definition Reduction_SF' := Reduction_SF P .\n  Definition fieldsP := fields P.\n  Definition TypeChecksP := TypeChecksTerm P.\n  Definition TypeChecksExprP := TypeChecksExpr P.\n  Definition Heap_okP := Heap_ok P.\n  Definition Heap_dom_okP := Heap_dom_ok P .\n  \n\n  Require Import Coq.Lists.List.\n\n  Notation \"( p +++ a ↦ b )\" := (p_env.updatePartFunc\n                                     p a b) (at level 0).\n\n  Notation \"( H +*+ o ↦ obj )\" := (p_heap.updatePartFunc\n                                     H o obj)\n                                    (at level 0).\n  Notation \"( Γ ⊍ x ↦ σ )\" := (p_Γ.updatePartFunc\n                                     Γ x σ)\n                                (at level 0).\n  Notation \" a ⪳ b \" := (subtype P a b) (at level 0).\n  Notation \" a ⪯ b \" := (subclass P a b) (at level 0).\n\n  Notation \"[ L , t ] ^ a\" := (ann_frame (sframe L t) a) (at level 0).\n\n  Notation \"y ∘ f ⟵ z\" := (FieldAssignment y f z) (at level 0).\n\n  Notation \"a ⟿ b\" :=  (Reduction_SF' a b) (at level 0).\n  Notation \" ⊢ H\" := (Heap_okP H) (at level 0).\n  Notation \" ⊩ H\" := (Heap_dom_okP H) (at level 0).\n  Notation \"( Γ , ef ⊩' t ▷ σ )\" := (TypeChecksTerm P Γ ef t σ) (at level 0).\n  Notation \"( Γ , ef ⊩'' e ▷ σ )\" := (TypeChecksExpr P Γ ef e σ) (at level 0).\n\n  Notation \"a ∉ lst\" := (~ (In a lst)) (at level 0).\n    \n\n  Theorem preservation_case_box :\n    forall H L σ ann t C x o flds,\n      WF_Frame' H (ann_frame (sframe L t_let x <- Box C t_in (t)) ann) σ ->\n      Heap_okP H ->\n      ~ In o (p_heap.domain H) ->\n      fieldsP C flds ->\n      WF_Frame'\n        (p_heap.updatePartFunc H o (obj C (p_FM.newPartFunc flds FM_null)))\n        (ann_frame (sframe (p_env.updatePartFunc L x (envBox o)) t) ann) σ.\n   Admitted.\n  \n    Theorem preservation_case_select :\n    forall H L σ ann x y f t C FM fmVal o,\n      WF_Frame' H (ann_frame (sframe L t_let x <- FieldSelection y f t_in (t)) ann) σ ->\n      Heap_okP H ->\n      p_env.func L y = Some (envRef o) ->\n      p_heap.func H o = Some (obj C FM) ->\n      p_FM.func FM f = Some fmVal ->\n      WF_Frame'\n        H\n        (ann_frame (sframe (p_env.updatePartFunc L x (fm2env fmVal)) t) ann) σ.\n    intros.\n\n    (* 2 *)\n    rename H1 into t_typ_σb.\n    rename H2 into _2_cd.\n    rename H3 into _2_e.\n    rename H4 into t_is_term.\n    rename H0 into _2_j.\n    rename X into _2_k.\n\n    (* 3 *)\n    inversion _2_k.\n    clear H3 sigma0 H5 ann0 H4 H1 H2.\n    rename X into ΓL_sub.\n    rename X0 into wf_vars.\n\n\n    (* 4 *)\n    inversion ΓL_sub.\n    clear tau H3 H7 t1 H5 e H4 x0 eff0 H2.\n    rewrite <- H1 in * ; clear H1 Gamma.\n    inversion X.\n    clear H5 f0 H1 x0 eff0 H3 gamma0 H2.\n    rename C0 into D.\n    rename H7 into typ_newC.\n    rename witn into typ_next_frame.\n    set (E := ftype P D f typ_next_frame).\n    rewrite <- H4 in *.\n    fold E in X, X0.\n    clear H4.\n    (* rename H4 into _4_c. *)\n    rename X0 into _4_d.\n    rename X into _4_e.\n    set (L' := p_env.updatePartFunc L x (fm2env fmVal)).\n    clear t0 L0 H0.\n\n\n    (* 5 *)\n    set (Gamma' := p_gamma.updatePartFunc gamma x (typt_class E)).\n    fold Gamma' in _4_d.\n    \n    (* 6 *)\n    inversion wf_vars.\n    rename H0 into wf_vars_i.\n    rename X into wf_vars_ii.\n    set (_6 := subset_preserved gamma L x (typt_class E) (fm2env fmVal)  wf_vars_i).\n\n\n    (* OTHER ORDER COMPARED TO paper proof*)\n    clear H6 sigma0.\n    apply (t_frame1 P _ Gamma' eff _ _ _ _ t_is_term _4_d).\n    split.\n    apply _6.\n    intros z tau.\n\n    (* END OTHER *)\n\n    case_eq (v_eq_dec x z).\n    (* 7 *)\n    (* 7 a *)\n    intros.\n    rewrite <- e in *; clear e z.\n    clear H0.\n    assert (p_env.func L' x = Some (fm2env fmVal)) as gamma_L_subset_a.\n    unfold L'.\n    rewrite  ( proj1 (p_env.updatedFuncProp L x (fm2env fmVal) x) (eq_refl x)).\n    reflexivity.\n    \n    assert (p_gamma.func Gamma' x = Some (typt_class E)) as gamma_x_E.\n    unfold Gamma'.\n    rewrite  ( proj1 (p_gamma.updatedFuncProp gamma x (typt_class E) x) (eq_refl x)).\n    reflexivity.\n    clear H1.\n\n    (* 7 b *)\n    induction fmVal; unfold fm2env in gamma_L_subset_a.\n    \n    (* 7 b i *)\n    apply inl. apply inl.\n    exact gamma_L_subset_a.\n\n    (* 7 c *)\n    rename r into o'.\n    set (test := _2_j o C FM _2_cd f o').\n    \n    apply inl.  apply inr.\n    exists (E, o').\n    unfold Gamma'.\n    assert (subclass P C D) as C_sub_D.\n    \n    induction ( wf_vars_ii y (typt_class D) typ_newC).\n    induction a.\n    rewrite  t_typ_σb in a; discriminate a.\n    destruct b.\n    destruct x0.\n    destruct y0.\n    destruct a.\n    destruct H1.\n    rewrite t_typ_σb in H0.\n    inversion H0.\n    rewrite H4 in *.\n    rewrite typ_newC in H1.\n    inversion H1.\n    rewrite <- H5 in *.\n    clear c H5.\n    assert (heap_typeof H r x0 = C).\n    unfold heap_typeof.\n    (* TODO: rewriting *)\n    admit.\n    (* rewrite <- H4. *)\n    (* rewrite _2_cd. *)\n    (* reflexivity. *)\n    rewrite H3 in H2.\n    inversion H2.\n    exact H7.\n    destruct b.   destruct x0. \n    destruct y0.\n    destruct a.\n    rewrite t_typ_σb in H0.\n    inversion H0.\n    \n    assert (fld P C f) as f_field_C.\n    apply (field_subclass P C D  _  typ_next_frame).\n    \n    exact C_sub_D.\n    destruct (test f_field_C _2_e).\n    clear test.\n    exists x0.\n    split.\n    exact gamma_L_subset_a.\n    split.\n    exact gamma_x_E.\n    \n    (*  *)\n    (*\n     * know: Gamma' x = E\n     * typeof(H, o') <: ftype(C, f)\n     * --------------\n     * ftype(C, f) = E\n     * --------------------- \n     * Goal:  heapof(H, o') <: E\n     *\n     *)\n    apply classSub.\n    assert (E = heap.ftypeP P C f f_field_C).\n    unfold E.\n    unfold heap.ftypeP.\n    rewrite (unique_ftype P C f f_field_C (field_subclass P C D f f_field_C C_sub_D)).\n    rewrite <- (ftype_subclass P C D f f_field_C C_sub_D).\n    apply (unique_ftype P D f _ _).\n    rewrite <- H0 in s.\n    exact s.\n\n    (* 8 *)\n    intros.\n    clear H0.\n\n    (* 8 a b *)\n    assert (p_gamma.func gamma z = Some tau).\n    rewrite <- H1.\n    symmetry.\n    set (lem := proj2 (p_gamma.updatedFuncProp gamma x (typt_class E) z)).\n    firstorder.\n    rename H0 into _8_b.\n    assert (In z (p_gamma.domain gamma)) as _8_a.\n    apply (p_gamma.in_part_func_domain _ z tau _8_b).\n\n    (* 8 c *)\n    assert (In z (p_env.domain L)) as _8_c.\n    apply (wf_vars_i _ _8_a).\n\n    set (_8_e_i := wf_vars_ii z tau _8_b).\n    unfold WF_Var.\n\n    assert (p_env.func L z = p_env.func L' z) as _8_d.\n    set (lem := proj2 (p_env.updatedFuncProp L x (fm2env fmVal) z)).\n    symmetry. firstorder.\n    rewrite <- _8_d.\n    rewrite <- _8_b in H1.\n    rewrite H1.\n    exact _8_e_i.\n  Admitted.\n\n\n    Theorem preservation_case_assign H L x y f z t C FM o σ envVal ann:\n    forall witn: is_not_box envVal,\n      WF_Frame' H (ann_frame (sframe L t_let x <- (FieldAssignment y f z) t_in (t)) ann) σ ->\n      Heap_okP H ->\n      p_env.func L y = Some (envRef o) ->\n      p_heap.func H o = Some (obj C FM) ->\n      p_env.func L z = Some envVal ->\n      (* isTerm t -> *)\n      (WF_Frame'\n         (p_heap.updatePartFunc H o\n                                (obj C (p_FM.updatePartFunc FM f (env2fm envVal witn))))\n         (ann_frame (sframe (p_env.updatePartFunc L x envVal ) t) ann) sigma) *\n      (Heap_okP (p_heap.updatePartFunc H o\n                                       (obj C (p_FM.updatePartFunc FM f (env2fm envVal witn))))\n      ).\n\n    (* 1 *)\n    intros.\n    rename H0 into _1_b.\n    rename X into _1_c.\n\n    (* 2 *)\n    set (L' := (p_env.updatePartFunc L x envVal)).\n    set (FM' := (p_FM.updatePartFunc FM f (env2fm envVal witn))).\n    set (H' := (p_heap.updatePartFunc H o (obj C FM'))).\n    split.\n\n    (* 2b, L z = o_z or L_z = null*)\n    assert ({o_z | envVal = envRef o_z} + (envVal = envNull)) as wf_H_Γ_L.\n    case_eq envVal.\n    intros.\n    apply inr.\n    reflexivity.\n    intros.\n    apply inl.\n    exists r.\n    reflexivity.\n    intros.\n    rewrite H0 in *.\n    inversion _1_c.\n    inversion X.\n    inversion X1.\n\n    (* L z = b(r), show Gamma z must be Box[D] *)\n\n    inversion X0.\n    set (lem := X4 z _ H23).\n    inversion lem.\n    destruct X5.\n    rewrite e0 in H3.\n    simplify_eq H3.\n    destruct s.\n    destruct x2.\n    destruct y1.\n    destruct a.\n    rewrite H26 in H3.\n    simplify_eq H3.\n\n    destruct X5.\n    destruct x2.\n    destruct y1.\n    destruct a.\n    destruct H27.\n    rewrite H23 in H27 .\n    simplify_eq H27.\n\n    rename o into o_y.\n    rename H1 into _2_c.\n    rename H2 into _2_d.\n\n    (* 2 e says that f in fields(C) by reduction rules (this is wrong!)*)\n\n    (* 3 *)\n    inversion _1_c.\n    clear H0 H2 t0 H5 ann0 H6 sigma0 H4 L0 H1.\n    rename X into ΓL_sub.\n    rename X0 into wf_vars.\n\n    (* 4 *)\n    inversion ΓL_sub.\n    inversion X.\n    clear y0 H13 f0 H9 x1 H8 eff1 H11 gamma0 H10.\n    unfold typing.subtypeP in *.\n    fold TypeChecksP in *.\n    fold subtypeP in *.\n    unfold typing.fldP in *.\n    fold fldP in *.\n    clear H2 tau.\n\n    clear x0 H4.\n    clear t0 H6.\n    clear H1 eff0.\n    clear e H5.\n    clear gamma H0.\n    rewrite <- H12 in *.\n    clear sigma0 H12.\n    inversion X1.\n    clear eff0 H2 x0 H0 H5 f0 gamma H1.\n    set (typ_newC := p_gamma.in_part_func_domain Gamma y (typt_class C1) H4).\n    set (typ_next_frame := p_gamma.in_part_func_domain Gamma z (typt_class C0) H14).\n    rename X1 into _4_c.\n\n    (* unfold subtypeP in H15. *)\n    rename H15 into _4_d.\n    set (Gamma' := p_gamma.updatePartFunc Gamma x (typt_class C0)).\n    fold Gamma' in X0.\n    rename X0 into _4_e.\n\n    clear witn2.\n    rename C0 into D''.\n    rename C into C'.\n    rename C1 into C.\n    rename H6 into _4_f.\n\n    (* 5 *)\n    inversion wf_vars.\n    rename H0 into _5_a.\n    rename X0 into _5_b.\n\n    (* 6 *)\n\n    apply (t_frame1 _ _ Gamma' eff).\n    inversion H7.\n    exact H1.\n    exact _4_e.\n    split.\n    exact (subset_preserved _ _ _ _  _  _5_a).\n\n    intros s.\n    case_eq (v_eq_dec s x).\n    intros.\n    clear H0; rewrite -> e in *; clear e s.\n    clear sigma0 H1.\n    assert (p_gamma.func Gamma' x = p_gamma.func Gamma z ) as _6_a.\n    set (lem := proj1 (p_gamma.updatedFuncProp Gamma x (typt_class D'') _) (eq_refl _)).\n    fold Gamma' in lem.\n    transitivity (Some (typt_class D'')).\n    exact lem.\n    symmetry.\n    exact H14.\n\n    assert (p_env.func L' x = p_env.func L z) as _6_b.\n    transitivity (Some envVal).\n    exact (proj1 (p_env.updatedFuncProp L x envVal _) (eq_refl _)).\n    symmetry.\n    exact H3.\n    case_eq wf_H_Γ_L.\n    intros.\n    clear H0 wf_H_Γ_L.\n    destruct s.\n    rewrite -> e in *.\n    rename x0 into o_z.\n    assert (In o_z (p_heap.domain H)).\n    destruct (_5_b z (typt_class D'') H14).\n    destruct s.\n    rewrite e0 in H3.\n    inversion H3.\n    destruct s. destruct x0.\n    destruct y0.\n    destruct a.\n    rewrite H0 in H3.\n    inversion H3.\n    rewrite <- H5 in *.\n    exact x0.\n    destruct s.\n    destruct x0.\n    destruct y0.\n    destruct a.\n    rewrite H0 in H3; inversion H3.\n    set (stays := p_heap.staysInDomain H o_y (obj C' FM') o_z H0).\n    assert (heap_typeof H' o_z stays = heap_typeof H o_z H0) as _6_iv.\n    case_eq (rn_eq_dec o_z o_y).\n    intros.\n    clear H1; rewrite e0 in *.\n    transitivity C'.\n    unfold heap_typeof.\n    assert (p_heap.func H' o_z = Some (obj C' FM')).\n    rewrite e0.\n    unfold H'.\n    exact (proj1 (p_heap.updatedFuncProp H o_y (obj C' FM') _) (eq_refl _)).\n\n    (* TODO: rewrite *)\n    admit.\n    (* rewrite H1. *)\n    (* reflexivity. *)\n    symmetry.\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit.\n    (* rewrite e0. *)\n    (* rewrite _2_d. *)\n    (* reflexivity. *)\n    intros.\n    clear H1.\n    set (lem := proj2 (p_heap.updatedFuncProp H o_y (obj C' FM') _) n).\n    fold H' in lem.\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite lem. *)\n    (* reflexivity. *)\n    unfold WF_Var.\n    apply inl.\n    apply inr.\n    rewrite _6_b.\n    rewrite _6_a.\n    exists (D'', o_z).\n    exists stays.\n    split.\n    exact H3.\n    split.\n    exact H14.\n    rewrite _6_iv.\n    unfold wf_env.subtypeP.\n    (* apply classSub. *)\n    elim (_5_b z (typt_class D'') H14).\n    intro.\n    destruct a.\n    rewrite e0 in H3; inversion H3.\n    destruct s.\n    destruct x0.\n    destruct y0.\n    destruct a.\n    rewrite H1 in H3; inversion H3.\n    rewrite H6 in *.\n    destruct H2.\n    rewrite H14 in H2; inversion H2.\n    rewrite <- H9 in *.\n    rewrite <- H6 in *.\n    (* dependent rewrite H6 in x0. *)\n    assert ((heap_typeof H r x0) = (heap_typeof H o_z H0)).\n    case_eq (p_heap.func H r).\n    intros.\n    destruct b.\n    transitivity c0.\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite H8. *)\n    (* reflexivity. *)\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite <- H6. *)\n    (* rewrite H8. *)\n    (* reflexivity. *)\n    intros.\n    elim (proj2 (p_heap.fDomainCompat H r) H8 x0).\n    rewrite <- H8.\n    exact H5.\n    rename _6_iv into _6_d_iv.\n\n    (* 6 e *)\n    intros.\n    destruct b.\n    destruct x0.\n    destruct y0.\n    destruct a.\n    destruct H2.\n    rewrite H14 in H2; discriminate H2.\n\n    (* L z = null *)\n    intros.\n    clear H0.\n    rewrite e in *.\n    apply inl.\n    apply inl.\n    rewrite _6_b.\n    assumption.\n\n\n    (* 7 a *)\n    intros gamma_L_subset dummy tau gamma_L_subset';    clear dummy.\n    assert (p_gamma.func Gamma' s = p_gamma.func Gamma s) as gamma_L_subset_a.\n    apply (proj2 (p_gamma.updatedFuncProp _ _ _ _) gamma_L_subset).\n    assert (p_env.func L' s = p_env.func L s) as gamma_L_subset_b.\n    apply (proj2 (p_env.updatedFuncProp _ _ _ _) gamma_L_subset).\n    rewrite gamma_L_subset' in gamma_L_subset_a.\n    symmetry in gamma_L_subset_a.\n    set (gamma_L_subset_c := _5_b s tau gamma_L_subset_a).\n\n    case_eq (p_env.func L s).\n    intros.\n    case_eq b.\n    intros.\n    apply inl. apply inl.\n    rewrite H1 in H0.\n    rewrite H0 in gamma_L_subset_b.\n    assumption.\n\n    (* 7 e, b = envRef o_s *)\n    clear _1_c.\n    clear ann.\n    intros.\n    rename r into o_s.\n    rewrite H1 in *.\n    destruct gamma_L_subset_c. (* case analysis on WF-var Gamma L s *)\n    destruct s0.\n    rewrite H0 in e; discriminate e.\n    destruct s0.\n    destruct x0; destruct y0; destruct a; destruct H5.\n    rewrite H2 in H0;    inversion H0.\n    rewrite <- H9 in *; clear H9.\n    clear o_s; rename r into o_s.\n    clear H0 b H1.\n    rename H5 into gamma_L_subset_e_i.\n    rename c into G.\n    rename H6 into gamma_L_subset_e_ii.\n    set (stays := p_heap.staysInDomain H o_y (obj C' FM') o_s x0).\n    fold H' in stays.\n\n    (* 7 e iii *)\n    assert (heap_typeof H o_s x0 = heap_typeof H' o_s stays) as gamma_L_subset_e_iii.\n    case_eq (rn_eq_dec o_s o_y).\n    intros.\n    clear H0. rewrite <- e in *.\n    transitivity C'.\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit.\n    (* rewrite _2_d; reflexivity. *)\n    \n    unfold heap_typeof.\n    assert (p_heap.func H' o_y = Some (obj C' FM')).\n    unfold H'.\n    exact (proj1 (p_heap.updatedFuncProp H o_y (obj C' FM') _) (eq_refl _)).\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite e. *)\n    (* rewrite H0. *)\n    (* reflexivity. *)\n    intros.\n    clear H0.\n    \n    set (lem := proj2 (p_heap.updatedFuncProp H o_y (obj C' FM') _) n).\n    fold H' in lem.\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite lem. *)\n    (* reflexivity. *)\n    (* end 7 e iii *)\n    \n    set (lem := _5_b s tau gamma_L_subset_a).\n    unfold WF_Var.\n    rewrite gamma_L_subset_b.\n    rewrite gamma_L_subset'.\n\n    (* Case analysis L s = null / o / box with H |- Gamma L s\n     * leads to Gamma s = G, typeof(H, o_s) <: G\n     *)\n    destruct lem.\n    destruct s0.\n    apply inl. apply inl. assumption.\n    apply inl.\n    apply inr.\n    destruct s0.\n    destruct x1.\n    exists (c, r).\n    destruct y0.\n    destruct a.\n    rewrite H0 in H2; inversion H2.\n    rewrite H6 in *.\n    assert (In o_s (p_heap.domain H')).\n    assumption.\n    exists H5.\n    split.\n    assumption.\n    split.\n    destruct H1.\n    rewrite H1 in gamma_L_subset_a.\n    symmetry.\n    assumption.\n    assert ((heap_typeof H r x1) = (heap_typeof H' o_s H5)).\n    transitivity (heap_typeof H o_s x0).\n    case_eq (p_heap.func H r).\n    intros.\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite H8. *)\n    (* rewrite H6 in H8. *)\n    (* rewrite H8. *)\n    (* reflexivity. *)\n    intros.\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite H8. *)\n    (* rewrite H6 in H8. *)\n    (* rewrite H8. *)\n    (* assumption. *)\n\n    case_eq (rn_eq_dec o_s o_y).\n    intros.\n    clear H8. \n    transitivity C'.\n    unfold heap_typeof.\n    rewrite e in *.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite _2_d. reflexivity. *)\n    unfold heap_typeof.\n    assert (p_heap.func H' o_y = Some (obj C' FM')).\n    unfold H'.\n    exact (proj1 (p_heap.updatedFuncProp H o_y (obj C' FM') _) (eq_refl _)).\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite e. *)\n    (* rewrite H8. *)\n    (* reflexivity. *)\n    intros.\n    clear H8.\n    \n    set (lem := proj2 (p_heap.updatedFuncProp H o_y (obj C' FM') _) n).\n    fold H' in lem.\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite lem. *)\n    (* reflexivity. *)\n    \n    rewrite <- H8.\n    destruct H1.\n    exact H9.\n    \n    destruct s0.\n    destruct x1.\n    destruct y0.\n    destruct a.\n    destruct H1.\n    rewrite H0 in H2; inversion H2.\n\n    destruct s0.\n    destruct x0; destruct y0. destruct a. destruct H5.\n    rewrite H2 in H0; discriminate H0.\n    (* END 7 e!!! *)\n\n    intros.\n    rename r into o_s.\n    rewrite H1 in *.\n\n    (* Case analysis on H |- Gamma ; L ; s to get box prop: *)\n    set (lem := _5_b s tau gamma_L_subset_a).\n    destruct lem.\n    destruct s0.\n    rewrite e in H0; discriminate H0.\n    destruct s0; destruct x0; destruct y0; destruct a.\n    rewrite H2 in H0; discriminate H0.\n    destruct s0; destruct x0; destruct y0; destruct a; destruct H5.\n    rewrite H2 in H0; simplify_eq H0.\n    intro equRef; rewrite equRef in *.\n    clear H0.\n    rewrite gamma_L_subset_a in H5; simplify_eq H5.\n    intro equTy; rewrite equTy in *.\n    rename c into F.\n    rename gamma_L_subset' into gamma_L_subset_f_i_A.\n    assert (In o_s (p_heap.domain H)).\n    rewrite <- equRef.\n    assumption.\n    assert (In o_s (p_heap.domain H')).\n    unfold H'.\n    apply (p_heap.staysInDomain H _ _ o_s).\n    assumption.\n    assert (heap_typeof H o_s H0  = heap_typeof H' o_s H8) as gamma_L_subset_f_ii.\n\n    case_eq (rn_eq_dec o_s o_y).\n    intros.\n    rewrite e in *.\n    clear H9.\n    transitivity C'.\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite e. *)\n    (* rewrite _2_d. *)\n    (* reflexivity. *)\n\n    \n    unfold heap_typeof.\n    assert (p_heap.func H' o_y = Some (obj C' FM')).\n    apply (p_heap.updatedFuncProp _ _ _ _).\n    reflexivity.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite e. *)\n    (* rewrite H9. *)\n    (* reflexivity. *)\n    \n    intros.\n    clear H9.\n    case_eq (p_heap.func H o_s).\n    intros.\n    destruct b0.\n    transitivity c.\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit.\n    (* rewrite H9. *)\n    (* reflexivity. *)\n\n    \n    assert (p_heap.func H' o_s = Some (obj c f0)).\n    unfold H'.\n    transitivity  (p_heap.func H o_s).\n    apply (proj2 (p_heap.updatedFuncProp H o_y (obj C' FM') o_s) ).\n    assumption.\n    assumption.\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite H10. *)\n    (* reflexivity. *)\n\n    intros.\n    elim (proj2 (p_heap.fDomainCompat H o_s) H9 H0).\n    unfold WF_Var.\n    rewrite gamma_L_subset_b.\n    rewrite gamma_L_subset_f_i_A.\n    rewrite H2.\n    apply inr.\n    exists (F, o_s).\n    exists H8.\n    split.\n    reflexivity.\n    split.\n    reflexivity.\n    rewrite <- gamma_L_subset_f_ii.\n    assert ((heap_typeof H o_s H0) = (heap_typeof H r x0)\n           ).\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite equRef. *)\n    (* induction (p_heap.func H o_s); *)\n    (* reflexivity. *)\n    \n    rewrite H9.\n    assumption.\n\n    intro.\n    set (s_in_gamma := p_gamma.in_part_func_domain Gamma s tau gamma_L_subset_a).\n    set (lem := _5_a _ s_in_gamma).\n    elim (proj2 (p_env.fDomainCompat _ _) H0 lem).\n\n    (* HEAP OK *)\n\n    intro.\n    rename o into o_y.\n    rename o0 into o.\n\n    case_eq (rn_eq_dec o_y o).\n    intros; clear H0.\n    rewrite <- e in *.\n    set (lem := proj1 (p_heap.updatedFuncProp H o_y (obj C FM') _) (eq_refl _)).\n    fold H' in lem.\n    rewrite lem in H4.\n    inversion H4.\n    rewrite <- H5 in *.\n    rewrite <- H6 in *.\n    clear H5 H6 C0 FM0.\n    clear lem H4 e o.\n    intro; intros.\n    \n    case_eq (fn_eq_dec f0 f).\n    intros.\n    clear H4; rewrite e in *.\n    set (lem := proj1 (p_FM.updatedFuncProp FM f (env2fm envVal witn) f) (eq_refl _ )).\n    fold FM' in lem.\n    rewrite H0 in lem.\n    inversion lem.\n    induction envVal; \n    inversion H5.\n    rewrite <- H6 in *.\n    rename o into o_z.\n    rename H3 into _9_b_ii_B.\n    rename H0 into _9_b_ii_A.\n    \n    inversion _1_c.\n    destruct X0.\n    inversion X.\n    inversion X0.\n    set (_9_b_iii_lem := w z (typt_class C0) H23).\n    unfold WF_Var in _9_b_iii_lem.\n    assert ({C_o : class * Ref_type |\n             let (C, o) := C_o in\n             {witn : In o (p_heap.domain H) |\n              p_env.func L z = Some (envRef o) /\\\n              p_gamma.func Gamma z = Some (typt_class C) /\\\n              wf_env.subtypeP P (typt_class (heap_typeof H o witn))\n                              (typt_class C)}}).\n    induction _9_b_iii_lem.\n    induction a.\n    rewrite a in _9_b_ii_B; simplify_eq _9_b_ii_B.\n    exact b.\n    destruct b; destruct x2; destruct y1; destruct a.\n    rewrite H25 in _9_b_ii_B; simplify_eq _9_b_ii_B.\n    clear _9_b_iii_lem.\n\n    destruct X3; destruct x2; destruct y1; destruct a.\n    rewrite H25 in _9_b_ii_B; simplify_eq _9_b_ii_B.\n    intro ref_eq; rewrite ref_eq in *.\n    destruct H26.\n    rename H26 into _9_b_v_C.\n    rename H27 into _9_b_v_D.\n    rename H25 into _9_b_v_A.\n    assert (In o_z (p_heap.domain H)) as _9_b_v_B.\n    rewrite <- ref_eq; assumption.\n    rewrite _9_b_v_C in H23; simplify_eq H23; intro simpl_eq; rewrite simpl_eq in *.\n    inversion X2.\n\n    set (lemlem := w y (typt_class C1) H28).\n    \n    assert ({C_o : class * Ref_type |\n           let (C, o) := C_o in\n           {witn : In o (p_heap.domain H) |\n           p_env.func L y = Some (envRef o) /\\\n           p_gamma.func Gamma y = Some (typt_class C) /\\\n           wf_env.subtypeP P (typt_class (heap_typeof H o witn))\n                           (typt_class C)}}).\n    induction lemlem.\n    induction a.\n    rewrite a in H1; simplify_eq H1.\n    assumption.\n\n    destruct b; destruct x4; destruct y1; destruct a; destruct H32.\n    rewrite H32 in H28; simplify_eq H28.\n    destruct X3.\n    destruct x4.\n    destruct y1.\n    destruct a.\n    destruct H32.\n    rewrite H31 in H1; simplify_eq H1; intro equu; rewrite equu in *.\n    rewrite H28 in H32; simplify_eq H32; intro equuu; rewrite <- equuu in *.\n    assert (heap_typeof H r1 x4 = C).\n    unfold heap_typeof.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite equu. *)\n    (* rewrite H2. *)\n    (* reflexivity. *)\n    \n    rewrite H34 in H33.\n\n    assert ((heap.ftypeP P C f f_witn) = D).\n    rewrite <- H30.\n    symmetry.\n    inversion H33.\n    apply (ftype_subclass _ _ _ _ _ H37).\n    rewrite H35.\n\n    exists (p_heap.staysInDomain H o_y (obj C FM') o_z _9_b_v_B).\n    assert ((heap_typeof H' o_z\n                         (p_heap.staysInDomain H o_y (obj C FM') o_z _9_b_v_B))\n            = (heap_typeof H o_z _9_b_v_B)\n           ).\n    unfold heap_typeof.\n    case_eq (rn_eq_dec o_z o_y).\n    intros.\n\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite e1. *)\n    (* assert (p_heap.func H' o_y = Some (obj C FM')). *)\n    (* apply (p_heap.updatedFuncProp). *)\n    (* reflexivity. *)\n    (* rewrite H37. *)\n    (* rewrite H2. *)\n    (* reflexivity. *)\n    \n    intros.\n    assert (p_heap.func H' o_z = p_heap.func H o_z).\n    apply (p_heap.updatedFuncProp).\n    assumption.\n\n    (* TODO: rewrite *)\n    admit. \n    (* rewrite H37. *)\n    (* induction (p_heap.func H o_z). *)\n    (* reflexivity. *)\n    Admitted.\n  (*   reflexivity. *)\n  (*   rewrite H36. *)\n\n  (*   assert ((heap_typeof H o_z _9_b_v_B) = (heap_typeof H r0 x2)). *)\n  (*   unfold heap_typeof. *)\n  (*   rewrite ref_eq. *)\n  (*   induction (p_heap.func H o_z). *)\n  (*   reflexivity. *)\n  (*   reflexivity. *)\n  (*   rewrite H37. *)\n  (*   inversion _9_b_v_D. *)\n  (*   apply (subclass_trans P (heap_typeof H r0 x2) C0 D). *)\n  (*   assumption. *)\n  (*   inversion H24. *)\n  (*   assumption. *)\n  (*   inversion witn. *)\n\n  (*   intros. *)\n  (*   clear H4. *)\n\n  (*   assert (p_FM.func FM' f0 = p_FM.func FM f0). *)\n  (*   apply (p_FM.updatedFuncProp). *)\n  (*   assumption. *)\n  (*   rewrite H0 in H4. symmetry in H4. *)\n  (*   set (lem := _1_b o_y C FM H2 f0 o f_witn H4). *)\n  (*   destruct lem. *)\n  (*   exists (p_heap.staysInDomain H o_y (obj C FM') o x0). *)\n\n  (*   assert ((heap_typeof H' o (p_heap.staysInDomain H o_y (obj C FM') o x0)) *)\n  (*           = (heap_typeof H o x0) *)\n  (*          ). *)\n\n  (*   case_eq (rn_eq_dec o o_y). *)\n  (*   intros. *)\n  (*   clear H5. *)\n  (*   unfold heap_typeof. *)\n  (*   rewrite e. *)\n  (*   assert (p_heap.func H' o_y = Some (obj C FM')). *)\n  (*   apply (p_heap.updatedFuncProp). *)\n  (*   reflexivity. *)\n  (*   rewrite H5. *)\n  (*   rewrite H2. *)\n  (*   reflexivity. *)\n  (*   intros . *)\n  (*   unfold heap_typeof. *)\n  (*   assert (p_heap.func H' o = p_heap.func H o). *)\n  (*   apply (p_heap.updatedFuncProp). *)\n  (*   assumption. *)\n  (*   rewrite H6. *)\n  (*   induction (p_heap.func H o); *)\n  (*     reflexivity. *)\n  (*   rewrite H5. *)\n  (*   assumption. *)\n\n  (*   intros. *)\n  (*   assert (p_heap.func H' o = p_heap.func H o). *)\n  (*   apply (p_heap.updatedFuncProp). *)\n  (*   firstorder. *)\n  (*   case_eq (p_heap.func H o). *)\n  (*   intros. *)\n  (*   destruct b. *)\n  (*   rewrite H5 in H4. *)\n  (*   rewrite H6 in H4. *)\n  (*   inversion H4. *)\n  (*   rewrite H8, H9 in *. *)\n  (*   clear H4 H8 H9 c f0. *)\n  (*   intro; intros. *)\n  (*   set (lem := _1_b o C0 FM0 H6 f0 o0 f_witn H4). *)\n  (*   destruct lem. *)\n  (*   exists (p_heap.staysInDomain H o_y (obj C FM') o0 x0). *)\n  (*   assert ((heap_typeof H o0 x0) = (heap_typeof H' o0 (p_heap.staysInDomain H o_y (obj C FM') o0 x0))). *)\n  (*   case_eq (rn_eq_dec o0 o_y). *)\n  (*   intros. *)\n  (*   unfold heap_typeof. *)\n  (*   rewrite e. *)\n  (*   rewrite H2. *)\n  (*   assert (p_heap.func H' o_y = Some (obj C FM')). *)\n  (*   apply (p_heap.updatedFuncProp). *)\n  (*   reflexivity. *)\n  (*   rewrite H8. *)\n  (*   reflexivity. *)\n  (*   intros. *)\n  (*   unfold heap_typeof. *)\n  (*   assert (p_heap.func H o0 = p_heap.func H' o0). *)\n  (*   symmetry. *)\n  (*   apply (p_heap.updatedFuncProp). *)\n  (*   assumption. *)\n  (*   rewrite H8. *)\n  (*   induction (p_heap.func H' o0); *)\n  (*     reflexivity. *)\n  (*   rewrite <- H7. *)\n  (*   assumption. *)\n  (*   intros. *)\n  (*   rewrite H6 in H5. *)\n  (*   rewrite H5 in H4. *)\n  (*   inversion H4. *)\n\n\n", "meta": {"author": "aleloi", "repo": "lacasa-mechanized", "sha": "24dfa243f6b640d17211e732121857a4c9c14771", "save_path": "github-repos/coq/aleloi-lacasa-mechanized", "path": "github-repos/coq/aleloi-lacasa-mechanized/lacasa-mechanized-24dfa243f6b640d17211e732121857a4c9c14771/preservation_unfixed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.2137486065801828}}
{"text": "Require Import RamifyCoq.lib.Coqlib.\nRequire Import RamifyCoq.sample_mark.env_mark_bi.\nRequire Import RamifyCoq.graph.graph_model.\nRequire Import RamifyCoq.graph.weak_mark_lemmas.\nRequire Import RamifyCoq.graph.path_lemmas.\nRequire Import RamifyCoq.graph.subgraph2.\nRequire Import RamifyCoq.graph.reachable_computable.\nRequire Import RamifyCoq.msl_application.Graph.\nRequire Import RamifyCoq.msl_application.Graph_Mark.\nRequire Import RamifyCoq.msl_application.GraphBi.\nRequire Import RamifyCoq.msl_application.GraphBi_Mark.\nRequire Import RamifyCoq.floyd_ext.share.\nRequire Import RamifyCoq.sample_mark.spatial_graph_bi_mark.\nRequire Import VST.msl.wand_frame.\nRequire Import VST.floyd.reassoc_seq.\nRequire Import VST.floyd.field_at_wand.\n\nLocal Coercion Graph_LGraph: Graph >-> LGraph.\nLocal Coercion LGraph_SGraph: LGraph >-> SGraph.\nLocal Identity Coercion Graph_GeneralGraph: Graph >-> GeneralGraph.\nLocal Identity Coercion LGraph_LabeledGraph: LGraph >-> LabeledGraph.\nLocal Identity Coercion SGraph_PointwiseGraph: SGraph >-> PointwiseGraph.\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nNotation graph sh x g := (@reachable_vertices_at _ _ _ _ _ _ _ _ _ _ (@SGP pSGG_VST bool unit (sSGG_VST sh)) _ x g).\nNotation Graph := (@Graph pSGG_VST bool unit unit).\nExisting Instances MGS biGraph maGraph finGraph RGF.\n\nDefinition mark_spec :=\n DECLARE _mark\n  WITH sh: wshare, g: Graph, x: pointer_val\n  PRE [ _x OF (tptr (Tstruct _Node noattr))]\n          PROP  (weak_valid g x)\n          LOCAL (temp _x (pointer_val_val x))\n          SEP   (graph sh x g)\n  POST [ Tvoid ]\n        EX g': Graph,\n        PROP (mark x g g')\n        LOCAL ()\n        SEP   (graph sh x g').\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals \n  PRE  [] main_pre prog nil gv\n  POST [ tint ] main_post prog nil gv.\n\nDefinition Gprog : funspecs := ltac:(with_library prog [mark_spec ; main_spec]).\n\nLemma graph_local_facts: forall sh x (g: Graph), weak_valid g x -> @derives mpred Nveric (graph sh x g) (valid_pointer (pointer_val_val x)).\nProof.\n  intros. destruct H.\n  - simpl in H. subst x. entailer!.\n  - eapply derives_trans; [apply (@va_reachable_root_stable_ramify pSGG_VST _ _ _ (sSGG_VST sh) g x (vgamma g x)); auto |].\n    simpl vertex_at. entailer!.\nQed.\n\nOpaque pSGG_VST sSGG_VST.\n\nLemma body_mark: semax_body Vprog Gprog f_mark mark_spec.\nProof.\n  start_function.\n  remember (vgamma g x) as dlr eqn:?H.\n  destruct dlr as [[d l] r].\n  rename H0 into H_GAMMA_g; symmetry in H_GAMMA_g.\n  rename H into H_weak_valid.\n\n  forward_if  (* if (x == 0) *)\n    (PROP  (pointer_val_val x <> nullval)\n     LOCAL (temp _x (pointer_val_val x))\n     SEP   (graph sh x g)).\n  - apply denote_tc_test_eq_split. 2: entailer!. apply graph_local_facts; auto.\n  - forward. (* return *)\n    Exists g. entailer!. destruct x. 1: simpl in H; inversion H. apply (mark_null_refl g).\n  - forward. (* skip *) entailer!.\n  - Intros. assert (vvalid g x) as gx_vvalid. {\n      destruct H_weak_valid; [| auto].\n      unfold is_null_SGBA in H0; simpl in H0; subst x.\n      exfalso. apply H. auto.\n    } assert (isptr (pointer_val_val x) /\\ exists b i, x = ValidPointer b i). {\n      destruct x. 2: exfalso; apply H; reflexivity. split; simpl; auto.\n      exists b, i. reflexivity.\n    } destruct H0 as [? [b [i ?]]]. clear H0 H_weak_valid.\n    (* root_mark = x -> m; *)\n    localize [data_at sh node_type (Vint (Int.repr (if d then 1 else 0)), (pointer_val_val l, pointer_val_val r)) (pointer_val_val x)].\n    forward.\n    unlocalize [graph sh x g].\n    1: apply (@root_stable_ramify _ (sSGG_VST sh) g x _ H_GAMMA_g); auto.\n    (* if (root_mark == 1) *)\n    forward_if\n      (PROP (d = false)\n       LOCAL (temp _x (pointer_val_val x))\n       SEP (graph sh x g)).\n    + (* return *)\n      forward. Exists g. entailer!.\n      eapply (mark_vgamma_true_refl g); eauto.\n      clear - H0; destruct d; [auto | inversion H0].\n    + (* skip *)\n      forward. entailer!. clear - H0; destruct d; congruence.\n    + Intros. subst d.\n      (* l = x -> l; *)\n      localize [data_at sh node_type (Vint (Int.repr 0), (pointer_val_val l, pointer_val_val r)) (pointer_val_val x)].\n      forward. 1: entailer!; destruct l; simpl; auto.\n      forward. 1: entailer!; destruct r; simpl; auto.\n      forward.\n      unlocalize [graph sh x (Graph_vgen g x true)].\n      1: apply (@root_update_ramify _ (sSGG_VST sh) g x _ (false, l, r) (true, l, r)); auto; eapply Graph_vgen_vgamma; eauto.\n      pose proof Graph_vgen_true_mark1 g x _ _ H_GAMMA_g gx_vvalid.\n      forget (Graph_vgen g x true) as g1.\n      assert (weak_valid g1 l) by (eapply left_weak_valid; eauto).\n      (* mark (l); *)\n      localize [graph sh l g1].\n      forward_call (sh, g1, l).\n      Intros g2.\n      unlocalize [graph sh x g2] using g2 assuming H3.\n      1: subst; eapply (@graph_ramify_left _ (sSGG_VST sh) g); eauto.\n      assert (weak_valid g2 r) by (eapply right_weak_valid; eauto).\n      (* mark (r); *)\n      localize [graph sh r g2].\n      forward_call (sh, g2, r).\n      Intros g3.\n      unlocalize [graph sh x g3] using g3 assuming H5.\n      1: subst; eapply (@graph_ramify_right _ (sSGG_VST sh) g); eauto.\n      (* return; *)\n      forward.\n      Exists g3. entailer!.\n      apply (mark1_mark_left_mark_right g g1 g2 g3 (ValidPointer b i) l r); auto.\nQed. (* original: 358 secs; VST 2.*: 4.772 secs *)\n\n(* Print Assumptions body_mark. *)\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/sample_mark/verif_mark_bi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.21369501633008278}}
{"text": "Set Implicit Arguments.\nRequire Import Prelude.\nRequire Import Infrastructure.\nRequire Import Regularity.\nRequire Import Regularity2.\nRequire Import SubstMatch.\nRequire Import Equations.\nRequire Import TLC.LibLN.\n\n#[export] Hint Resolve okt_is_ok.\n\nLemma typing_weakening_delta_eq:\n  forall (u : trm) (Σ : GADTEnv) (D1 D2 : list typctx_elem) (E : env bind) (U : typ) eq TT,\n    {Σ, D1 |,| D2, E} ⊢(TT) u ∈ U ->\n    {Σ, D1 |,| [tc_eq eq]* |,| D2, E} ⊢(TT) u ∈ U.\nProof.\n  introv Typ; gen_eq D': (D1 |,| D2); gen D2.\n  induction Typ; introv EQ; subst;\n    try solve [\n          econstructor; fresh_intros; eauto\n        | econstructor; eauto using okt_weakening_delta_eq; eauto using wft_weaken\n        ].\n  - apply_fresh typing_tabs as Y; auto.\n    lets* IH: H1 Y (D2 |,| [tc_var Y]*).\n  - econstructor; eauto.\n    introv In Alen Adist Afr xfr xAfr.\n\n    lets* IH: H4 In xAfr (D2 |,| tc_vars Alphas |,|\n                          equations_from_lists Ts (List.map (open_tt_many_var Alphas) (Crettypes def))).\n    repeat rewrite List.app_assoc in *.\n    apply~ IH.\n  - econstructor; eauto.\n    + destruct eq. apply~ equation_weaken_eq.\n    + apply~ wft_weaken.\nQed.\n\nLemma typing_weakening_delta:\n  forall (u : trm) (Σ : GADTEnv) (D1 D2 : list typctx_elem) (E : env bind) (U : typ) (Y : var) TT,\n    {Σ, D1 |,| D2, E} ⊢(TT) u ∈ U ->\n    Y # E ->\n    Y \\notin domΔ D1 ->\n    Y \\notin domΔ D2 ->\n    Y \\notin fv_delta D2 ->\n    {Σ, D1 |,| [tc_var Y]* |,| D2, E} ⊢(TT) u ∈ U.\nProof.\n  introv Typ FE FD1 FD2 FrD; gen_eq D': (D1 |,| D2); gen D2.\n  lets Typ2: Typ.\n  induction Typ; introv FD2 FrD EQ; subst;\n    try solve [\n          econstructor; fresh_intros; eauto\n        | econstructor; eauto using okt_weakening_delta; eauto using wft_weaken\n        ].\n  - econstructor; auto;\n    try let envvars := gather_vars in\n    instantiate (1:=envvars); auto.\n    intros.\n    lets* IH: H1 X (D2 |,| [tc_var X]*).\n    repeat rewrite <- List.app_assoc in *.\n    apply IH; auto.\n    rewrite notin_domΔ_eq. split; auto.\n    cbn. rewrite notin_union.\n    split; auto.\n  - econstructor; eauto.\n    introv Hin.\n    try let envvars := gather_vars in\n    introv Hlen Hdist Afresh xfreshL xfreshA;\n      instantiate (1:=envvars) in xfreshL.\n    lets IH: H4 Hin Hlen (D2 |,| tc_vars Alphas |,| equations_from_lists Ts (List.map (open_tt_many_var Alphas) (Crettypes def))); eauto.\n    + introv Ain. lets*: Afresh Ain.\n    + eauto.\n    + apply~ H3.\n      introv Ain. lets*: Afresh Ain.\n    + repeat rewrite List.app_assoc in *.\n      apply IH; auto.\n      rewrite notin_domΔ_eq; split; auto.\n      * rewrite notin_domΔ_eq; split; auto.\n        -- apply notin_dom_tc_vars.\n           intro HF.\n           lets HF2: from_list_spec HF.\n           lets HF3: LibList_mem HF2.\n           lets HF4: Afresh HF3.\n           eapply notin_same.\n           instantiate (1:=Y).\n           eauto.\n        -- rewrite equations_have_no_dom; auto.\n           apply* equations_from_lists_are_equations.\n      * repeat rewrite fv_delta_app.\n        repeat rewrite notin_union.\n        splits~.\n        -- rewrite~ fv_delta_alphas.\n        -- lets [? [? WFT]]: typing_regular Typ.\n           lets FV: wft_gives_fv WFT.\n           cbn in FV.\n           apply fv_delta_equations.\n           ++ intros T Tin.\n              intro HF.\n              lets FV2: fold_left_subset fv_typ Tin.\n              lets FV3: subset_transitive FV2 FV.\n              lets FV4: FV3 HF.\n              rewrite domDelta_app in FV4.\n              rewrite in_union in FV4.\n              destruct FV4; auto.\n           ++ intros R Rin.\n              assert (OKS: okGadt Σ).\n              ** apply~ okt_implies_okgadt.\n                 apply* typing_regular.\n              ** apply List.in_map_iff in Rin.\n                 destruct Rin as [rT [? rTin]]; subst.\n                 lets Sub: fv_smaller_many Alphas rT.\n                 intro HF.\n                 lets HF2: Sub HF.\n                 rewrite in_union in HF2.\n                 destruct HF2 as [HF2 | HF2].\n                 ---\n                   destruct OKS as [? OKS].\n                   lets [? OKD]: OKS H0.\n                   lets Din: fst_from_zip Hin.\n                   lets OKC: OKD Din.\n                   inversion OKC as [? ? ? ? ? ? ? ? ? FrR]; subst.\n                   cbn in rTin.\n                   lets FR: FrR rTin.\n                   rewrite FR in HF2.\n                   false* in_empty_inv.\n                 ---\n                   lets [A [Ain ?]]: in_from_list HF2; subst.\n                   lets: Afresh Ain.\n                   assert (A \\notin \\{ A}); auto.\n                   false* notin_same.\n  - econstructor.\n    + apply~ IHTyp.\n    + apply~ equation_weaken_var.\n    + apply wft_weaken.\n      lets~ [? [? ?]]: typing_regular Typ2.\nQed.\n\nLemma typing_weakening_delta_many_eq : forall Σ Δ E Deqs u U TT,\n    {Σ, Δ, E} ⊢(TT) u ∈ U ->\n    (forall eq, List.In eq Deqs -> exists ϵ, eq = tc_eq ϵ) ->\n    {Σ, Δ |,| Deqs, E} ⊢(TT) u ∈ U.\nProof.\n  induction Deqs; introv Typ EQs.\n  - clean_empty_Δ. auto.\n  - destruct a;\n      try solve [lets HF: EQs (tc_var A); false~ HF].\n    fold_delta.\n    rewrite <- List.app_assoc.\n    lets W: typing_weakening_delta_eq Σ (Δ |,| Deqs) emptyΔ.\n    clean_empty_Δ.\n    rewrite <- (List.app_nil_l ((Δ |,| Deqs) |,| [tc_eq eq]*)).\n    apply~ W.\n    apply~ IHDeqs.\n    intros eq1 ?. lets Hin: EQs eq1.\n    destruct Hin; eauto.\n    cbn. auto.\nQed.\n\nLemma typing_weakening_delta_many : forall Σ Δ E As u U TT,\n    (forall A, List.In A As -> A # E) ->\n    (forall A, List.In A As -> A \\notin domΔ Δ) ->\n    DistinctList As ->\n    {Σ, Δ, E} ⊢(TT) u ∈ U ->\n    {Σ, Δ |,| tc_vars As, E} ⊢(TT) u ∈ U.\n  induction As as [| Ah Ats]; introv AE AD Adist Typ.\nProof.\n  - cbn. clean_empty_Δ. auto.\n  - cbn. fold_delta.\n    inversions Adist.\n    rewrite <- (List.app_nil_l ((Δ |,| tc_vars Ats) |,| [tc_var Ah]*)).\n    apply typing_weakening_delta; cbn; auto with listin.\n    rewrite notin_domΔ_eq. split.\n    + auto with listin.\n    + apply notin_dom_tc_vars.\n      intro HF.\n      apply from_list_spec in HF.\n      apply LibList_mem in HF.\n      auto.\nQed.\n\nLemma typing_weakening : forall Σ Δ E F G e T TT,\n    {Σ, Δ, E & G} ⊢(TT) e ∈ T ->\n    okt Σ Δ (E & F & G) ->\n    {Σ, Δ, E & F & G} ⊢(TT) e ∈ T.\nProof.\n  introv HTyp. gen_eq K: (E & G). gen G F.\n  induction HTyp using typing_ind; introv EQ Ok; subst; eauto.\n  - apply* typing_var. apply* binds_weaken.\n  - econstructor; eauto.\n    let env := gather_vars in\n    instantiate (2:=env).\n    introv xfresh.\n    lets IH: H0 x (G & x ~l V) F; auto.\n    rewrite <- concat_assoc.\n    apply IH.\n    + auto using concat_assoc.\n    + rewrite concat_assoc.\n      econstructor; eauto.\n      assert (xL: x \\notin L); auto.\n      lets Typ: H xL.\n      lets [? [? ?]]: typing_regular Typ.\n      eapply okt_is_wft. eauto.\n  - apply_fresh* typing_tabs as X.\n    lets IH: H1 X G F; auto.\n    apply IH.\n    + auto using JMeq_from_eq.\n    + rewrite <- (List.app_nil_l (Δ |,| [tc_var X]*)).\n      apply okt_weakening_delta; clean_empty_Δ; cbn; auto.\n  - apply_fresh* typing_fix as x.\n    lets IH: H1 x (G & x ~f T) F; auto.\n    rewrite <- concat_assoc.\n    apply IH; repeat rewrite concat_assoc; auto.\n    constructor; auto.\n    lets [? [? ?]]: typing_regular T; eauto.\n  - apply_fresh* typing_let as x.\n    lets IH: H0 x (G & x ~l V) F; auto.\n    rewrite <- concat_assoc.\n    apply IH; repeat rewrite concat_assoc; auto.\n    constructor; auto.\n    lets [? [? ?]]: typing_regular V; eauto.\n  - eapply typing_case; eauto.\n    introv Inzip.\n    let envvars := gather_vars in\n    (introv AlphasArity ADistinct Afresh xfresh xfreshA;\n     instantiate (1:=envvars) in Afresh).\n    assert (AfreshL: forall A : var, List.In A Alphas -> A \\notin L);\n      [ introv Ain; lets*: Afresh Ain | idtac ].\n    assert (xfreshL: x \\notin L); eauto.\n    lets* IH1: H4 Inzip Alphas x AlphasArity ADistinct.\n    lets* IH2: IH1 AfreshL xfreshL xfreshA (G & x ~l open_tt_many_var Alphas (Cargtype def)) F.\n    repeat rewrite concat_assoc in IH2.\n    apply~ IH2.\n\n    constructor; auto.\n    + rewrite <- (List.app_nil_l (Δ |,| tc_vars Alphas |,| equations_from_lists Ts (List.map (open_tt_many_var Alphas) (Crettypes def)))).\n      apply okt_weakening_delta_many_eq.\n      * apply okt_weakening_delta_many; clean_empty_Δ;\n          try solve [introv Ain; cbn; lets: Afresh Ain; auto]; auto.\n      * apply* equations_from_lists_are_equations.\n    + assert (OKS: okGadt Σ).\n      * apply~ okt_implies_okgadt.\n        apply* typing_regular.\n      * destruct OKS as [? OKS].\n        lets [? OKD]: OKS H0.\n        lets Din: fst_from_zip Inzip.\n        lets OKC: OKD Din.\n        inversion OKC as [? ? ? ? ? ? Harg ? ? ?]; subst.\n        cbn.\n        apply wft_weaken_simple.\n        apply~ Harg.\n    + repeat rewrite notin_domΔ_eq.\n      split~.\n      * split~.\n        apply notin_dom_tc_vars. auto.\n      * rewrite equations_have_no_dom; eauto using equations_from_lists_are_equations.\nQed.\n\nLemma typing_through_subst_ee_lam : forall Σ Δ E F x u U e T TT1 TT2,\n    {Σ, Δ, E & (x ~l U) & F} ⊢(TT1) e ∈ T ->\n    {Σ, Δ, E} ⊢(TT2) u ∈ U ->\n    value u ->\n    {Σ, Δ, E & F} ⊢(Tgen) subst_ee x lam_var u e ∈ T.\nProof.\n  Ltac apply_ih :=\n    match goal with\n    | H: forall X, X \\notin ?L -> forall E0 F0 x0 vk0 U0, ?P1 -> ?P2 |- _ =>\n      apply_ih_bind* H end.\n  introv TypT TypU ValU.\n  inductions TypT; introv; cbn;\n    try solve [eapply Tgen_from_any; eauto using okt_strengthen];\n    lets [okU [termU wftU]]: typing_regular TypU.\n  - match goal with\n    | [ H: okt ?A ?B ?C |- _ ] =>\n      lets: okt_strengthen H\n    end.\n    case_if~.\n    + eapply Tgen_from_any.\n      inversions C.\n      binds_get H; eauto.\n      assert (E & F & empty = E & F) as HEF by apply concat_empty_r.\n      rewrite <- HEF.\n      apply typing_weakening; rewrite concat_empty_r; eauto.\n    + eapply Tgen_from_any. binds_cases H; apply* typing_var.\n      match goal with\n      | [H: bind_var ?vk ?T = bind_var ?vk2 ?U |- _] =>\n        inversion* H\n      end.\n  - eapply Tgen_from_any.\n    apply_fresh* typing_abs as y.\n    rewrite* subst_ee_open_ee_var.\n    apply_ih.\n  - eapply Tgen_from_any.\n    apply_fresh* typing_tabs as Y; rewrite* subst_ee_open_te_var.\n    match goal with\n    | [ H: forall X, X \\notin ?L -> forall E0 F0 x0 vk0 U0, ?P1 -> ?P2 |- _ ] =>\n      apply* H\n    end.\n    rewrite <- (List.app_nil_l (Δ |,| [tc_var Y]*)).\n    apply typing_weakening_delta; clean_empty_Δ; cbn; auto.\n  - eapply Tgen_from_any.\n    apply_fresh* typing_fix as y; rewrite* subst_ee_open_ee_var.\n    apply_ih.\n  - eapply Tgen_from_any.\n    apply_fresh* typing_let as y.\n    rewrite* subst_ee_open_ee_var.\n    apply_ih.\n  - eapply Tgen_from_any.\n    econstructor; eauto.\n    + unfold map_clause_trm_trm.\n      rewrite* List.map_length.\n    + introv inzip.\n      lets* [i [Hdefs Hmapped]]: Inzip_to_nth_error inzip.\n      lets* [[clA' clT'] [Hclin Hclsubst]]: nth_error_map Hmapped.\n      destruct clause as [clA clT]. cbn.\n      inversions Hclsubst.\n      lets* Hzip: Inzip_from_nth_error Hdefs Hclin.\n      lets*: H2 Hzip.\n    + introv inzip.\n      let env := gather_vars in\n      intros Alphas xClause Alen Adist Afresh xfresh xfreshA;\n        instantiate (1:=env) in xfresh.\n      lets* [i [Hdefs Hmapped]]: Inzip_to_nth_error inzip.\n      lets* [[clA' clT'] [Hclin Hclsubst]]: nth_error_map Hmapped.\n      destruct clause as [clA clT]. cbn.\n      inversions Hclsubst.\n      lets* Hzip: Inzip_from_nth_error Hdefs Hclin.\n      lets* IH: H4 Hzip.\n\n      assert (Htypfin: {Σ, Δ |,| tc_vars Alphas |,| equations_from_lists Ts (List.map (open_tt_many_var Alphas) (Crettypes def)),\n                        E & F & xClause ~l (open_tt_many_var Alphas (Cargtype def))}\n                ⊢(Tgen) subst_ee x lam_var u (open_te_many_var Alphas clT' open_ee_varlam xClause) ∈ Tc).\n      * assert (AfreshL: forall A : var, List.In A Alphas -> A \\notin L);\n          [ introv Ain; lets*: Afresh Ain | idtac ].\n        assert (xfreshL: xClause \\notin L); eauto.\n        lets Htmp: IH Alphas xClause Alen Adist AfreshL.\n        lets Htmp2: Htmp xfreshL xfreshA.\n        lets Htmp3: Htmp2 E (F & xClause ~l (open_tt_many_var Alphas (Cargtype def))) x U.\n        cbn in Htmp3.\n        rewrite <- concat_assoc.\n        apply* Htmp3.\n        apply JMeq_from_eq.\n        eauto using concat_assoc.\n        apply typing_weakening_delta_many_eq;\n          eauto using equations_from_lists_are_equations.\n        apply typing_weakening_delta_many; auto;\n          try introv Ain; lets: Afresh Ain; auto.\n      * assert (Horder:\n                  subst_ee x lam_var u (open_te_many_var Alphas clT' open_ee_varlam xClause)\n                  =\n                  open_te_many_var Alphas (subst_ee x lam_var u clT') open_ee_varlam xClause).\n        -- rewrite* <- subst_ee_open_ee_var.\n           f_equal.\n           apply* subst_commutes_with_unrelated_opens_te_ee.\n        -- rewrite* <- Horder.\n               Qed.\n\nLemma typing_through_subst_ee_fix : forall Σ Δ E F x u U e T TT1 TT2,\n    {Σ, Δ, E & (x ~f U) & F} ⊢(TT1) e ∈ T ->\n    {Σ, Δ, E} ⊢(TT2) u ∈ U ->\n    {Σ, Δ, E & F} ⊢(Tgen) subst_ee x fix_var u e ∈ T.\nProof.\n  introv TypT TypU.\n  inductions TypT; introv; cbn;\n    try solve [eapply Tgen_from_any; eauto using okt_strengthen];\n    lets [okU [termU wftU]]: typing_regular TypU.\n  - match goal with\n    | [ H: okt ?A ?B ?C |- _ ] =>\n      lets: okt_strengthen H\n    end.\n    case_if~.\n    + inversions C.\n      eapply Tgen_from_any. binds_get H; eauto.\n      assert (E & F & empty = E & F) as HEF by apply concat_empty_r.\n      rewrite <- HEF.\n      apply typing_weakening; rewrite concat_empty_r; eauto.\n    + eapply Tgen_from_any. binds_cases H; apply* typing_var.\n      match goal with\n      | [H: bind_var ?vk ?T = bind_var ?vk2 ?U |- _] =>\n        inversion* H\n      end.\n  - eapply Tgen_from_any.\n    apply_fresh* typing_abs as y.\n    rewrite* subst_ee_open_ee_var.\n    apply_ih.\n  - eapply Tgen_from_any.\n    apply_fresh* typing_tabs as Y; rewrite* subst_ee_open_te_var.\n    + apply* subst_ee_fix_value.\n    + match goal with\n      | [ H: forall X, X \\notin ?L -> forall E0 F0 x0 vk0 U0, ?P1 -> ?P2 |- _ ] =>\n        apply* H\n      end.\n      rewrite <- (List.app_nil_l (Δ |,| [tc_var Y]* )).\n      apply typing_weakening_delta; clean_empty_Δ; cbn; auto.\n  - eapply Tgen_from_any.\n    apply_fresh* typing_fix as y; rewrite* subst_ee_open_ee_var.\n    + apply* subst_ee_fix_value.\n    + apply_ih.\n  - eapply Tgen_from_any.\n    apply_fresh* typing_let as y.\n    rewrite* subst_ee_open_ee_var.\n    apply_ih.\n  - eapply Tgen_from_any.\n    econstructor; eauto.\n    + unfold map_clause_trm_trm.\n      rewrite* List.map_length.\n    + introv inzip.\n      lets* [i [Hdefs Hmapped]]: Inzip_to_nth_error inzip.\n      lets* [[clA' clT'] [Hclin Hclsubst]]: nth_error_map Hmapped.\n      destruct clause as [clA clT]. cbn.\n      inversions Hclsubst.\n      lets* Hzip: Inzip_from_nth_error Hdefs Hclin.\n      lets*: H2 Hzip.\n    + introv inzip.\n      let env := gather_vars in\n      intros Alphas xClause Alen Adist Afresh xfresh xfreshA;\n        instantiate (1:=env) in xfresh.\n      lets* [i [Hdefs Hmapped]]: Inzip_to_nth_error inzip.\n      lets* [[clA' clT'] [Hclin Hclsubst]]: nth_error_map Hmapped.\n      destruct clause as [clA clT]. cbn.\n      inversions Hclsubst.\n      lets* Hzip: Inzip_from_nth_error Hdefs Hclin.\n      lets* IH: H4 Hzip.\n\n      assert (Htypfin: {Σ, Δ |,| tc_vars Alphas |,| equations_from_lists Ts (List.map (open_tt_many_var Alphas) (Crettypes def)),\n                        E & F & xClause ~l (open_tt_many_var Alphas (Cargtype def))}\n                ⊢(Tgen) subst_ee x fix_var u (open_te_many_var Alphas clT' open_ee_varlam xClause) ∈ Tc).\n      * assert (AfreshL: forall A : var, List.In A Alphas -> A \\notin L);\n          [ introv Ain; lets*: Afresh Ain | idtac ].\n        assert (xfreshL: xClause \\notin L); eauto.\n        lets Htmp: IH Alphas xClause Alen Adist AfreshL.\n        lets Htmp2: Htmp xfreshL xfreshA.\n        lets Htmp3: Htmp2 E (F & xClause ~l (open_tt_many_var Alphas (Cargtype def))) x U.\n        cbn in Htmp3.\n        rewrite <- concat_assoc.\n        apply* Htmp3.\n        apply JMeq_from_eq.\n        eauto using concat_assoc.\n        apply typing_weakening_delta_many_eq;\n          eauto using equations_from_lists_are_equations.\n        apply typing_weakening_delta_many; auto;\n          try introv Ain; lets: Afresh Ain; auto.\n      * assert (Horder:\n                  subst_ee x fix_var u (open_te_many_var Alphas clT' open_ee_varlam xClause)\n                  =\n                  open_te_many_var Alphas (subst_ee x fix_var u clT') open_ee_varlam xClause).\n        -- rewrite* <- subst_ee_open_ee_var.\n           f_equal.\n           apply* subst_commutes_with_unrelated_opens_te_ee.\n        -- rewrite* <- Horder.\nQed.\n\nLemma typing_through_subst_te_gen : forall Σ Δ1 Δ2 E Z e P T TT,\n    {Σ, Δ1 |,| [tc_var Z]* |,| Δ2, E} ⊢(TT) e ∈ T ->\n    wft Σ Δ1 P ->\n    Z \\notin fv_typ P ->\n    Z \\notin domΔ (Δ1 |,| Δ2) ->\n    Z # E ->\n    {Σ, Δ1 |,| List.map (subst_td Z P) Δ2, map (subst_tb Z P) E} ⊢(Tgen) subst_te Z P e ∈ subst_tt Z P T.\nProof.\n  introv Typ.\n  gen_eq G: (Δ1 |,| [tc_var Z]* |,| Δ2). gen Δ2.\n  induction Typ; introv EQ WFT FVZP FVZD FVZE; subst; eapply Tgen_from_any;\n    cbn; eauto.\n  - constructor. apply~ okt_through_subst_tdtb.\n  - cbn. econstructor.\n    + fold (subst_tb Z P (bind_var vk T)).\n      apply~ binds_map.\n    + apply~ okt_through_subst_tdtb.\n  - assert (OKS: okGadt Σ).\n    1: {\n      apply~ okt_implies_okgadt.\n      apply* typing_regular.\n    }\n    destruct OKS as [? OKS].\n    lets [? OKD]: OKS H.\n    lets Din: List.nth_error_In H0.\n    lets OKC: OKD Din.\n    inversion OKC as [? ? ? ? ? ? Harg Hwft FVarg FVret]; subst.\n    econstructor; auto.\n    + apply H.\n    + rewrite~ List.map_length.\n      eauto.\n    + rewrite~ subst_commutes_open_tt_many.\n      * apply* type_from_wft.\n      * rewrite~ FVarg.\n    + intros T' Tin.\n      apply List.in_map_iff in Tin.\n      destruct Tin as [T [? Tin]]; subst.\n      apply* wft_subst_tb_3.\n    + rewrite~ subst_commutes_open_tt_many.\n      * apply* type_from_wft.\n      * cbn. fold (fv_typs CretTypes).\n        apply~ notin_fold.\n        intros TR Tin.\n        rewrite~ FVret.\n  - apply_fresh typing_abs as x.\n    fold (subst_tb Z P (bind_var lam_var V)).\n    rewrite <- map_push.\n    rewrite subst_te_open_ee_var.\n    apply~ H0.\n  - lets: type_from_wft WFT.\n    apply_fresh typing_tabs as X.\n    + forwards~ : H X.\n      rewrite~ subst_te_open_te_var.\n    + forwards * IH : H1 X (Δ2 |,| [tc_var X]*).\n      1: {\n        fold_delta.\n        repeat rewrite domDelta_app in *.\n        repeat rewrite notin_union in *.\n        destruct FVZD.\n        repeat split~.\n        cbn.\n        rewrite notin_union; split~.\n        apply* notin_inverse.\n      }\n      fold_delta.\n      repeat rewrite List.app_assoc in *.\n      rewrite~ subst_te_open_te_var.\n      rewrite~ subst_tt_open_tt_var.\n      apply* IH.\n  - econstructor; auto.\n    + apply* IHTyp.\n    + apply* wft_subst_tb_3.\n    + fold subst_tt.\n      rewrite* subst_tt_open_tt.\n  - apply_fresh typing_fix as x.\n    + forwards~ : H x.\n      rewrite subst_te_open_ee_var.\n      apply~ subst_te_value.\n      apply* type_from_wft.\n    + fold (subst_tb Z P (bind_var fix_var T)).\n      rewrite <- map_push.\n      rewrite subst_te_open_ee_var.\n      apply~ H1.\n  - apply_fresh typing_let as x.\n    + apply* IHTyp.\n    + rewrite subst_te_open_ee_var.\n      fold (subst_tb Z P (bind_var lam_var V)).\n      rewrite <- map_push.\n      apply~ H0.\n  - econstructor; eauto.\n    + cbn. eauto.\n    + unfold map_clause_trm_trm.\n      rewrite~ List.map_length.\n    + introv Inzip.\n      lets [clA [clT [In2 ?]]]: inzip_map_clause_trm Inzip; subst.\n      lets: H2 In2.\n      cbn in *. auto.\n    + let FV := gather_vars in\n      introv Inzip Len Dist FA Fx FxA;\n        instantiate (1 := FV) in FA.\n      lets [clA [clT [In2 ?]]]: inzip_map_clause_trm Inzip; subst.\n      assert (OKS: okGadt Σ).\n      1: {\n        apply~ okt_implies_okgadt.\n        apply* typing_regular.\n      }\n      destruct OKS as [? OKS].\n      lets [? OKD]: OKS H0; clear OKS.\n      lets Din: fst_from_zip In2.\n      lets OKC: OKD Din.\n      inversion OKC as [? ? ? ? ? ? Harg Hwft FVarg FVret]; subst.\n      cbn in *.\n      lets~ IH : H4 In2 x Len Dist (Δ2 |,| tc_vars Alphas\n                                |,| equations_from_lists Ts\n                                (List.map (open_tt_many_var Alphas) retTs)).\n      * introv Ain. lets*: FA Ain.\n      * cbn in *.\n        forwards~ IH2: IH; clear IH.\n        -- repeat rewrite~ List.app_assoc.\n        -- repeat rewrite domDelta_app in *.\n           repeat rewrite notin_union.\n           repeat rewrite notin_union in FVZD.\n           destruct FVZD.\n           repeat split~.\n           ++ apply notin_dom_tc_vars.\n              apply~ notin_from_list.\n              intro HF.\n              lets HF2 : FA HF.\n              repeat rewrite notin_union in HF2.\n              assert (Z \\notin \\{ Z }).\n              ** destruct~ HF2 as [? [[? ?] ?]].\n              ** apply* notin_same.\n           ++ rewrite~ equations_have_no_dom.\n              apply* equations_from_lists_are_equations.\n        -- assert (FVZA: forall X : var, List.In X Alphas -> X <> Z).\n           1: {\n             intros A Ain.\n             intro HF.\n             subst.\n             lets FA2: FA Ain.\n             repeat rewrite notin_union in FA2.\n             destruct~ FA2 as [? [[?]]].\n             apply* notin_same.\n           }\n           rewrite~ <- subst_commutes_with_unrelated_opens_te.\n           ** rewrite subst_te_open_ee_var.\n              rewrite List.map_app in IH2.\n              rewrite List.map_app in IH2.\n              rewrite subst_td_alphas in IH2.\n              rewrite subst_td_eqs in IH2.\n              --- rewrite map_concat in IH2.\n                  rewrite map_single in IH2.\n                  cbn in IH2.\n                  assert (Hrew: subst_tt Z P (open_tt_many_var Alphas argT) = open_tt_many_var Alphas argT).\n                  +++ rewrite~ subst_commutes_with_unrelated_opens.\n                      *** f_equal. rewrite~ subst_tt_fresh.\n                          rewrite~ FVarg.\n                      *** apply* type_from_wft.\n                  +++ rewrite Hrew in IH2; clear Hrew.\n                      repeat rewrite List.app_assoc in *.\n                      apply IH2.\n              --- introv Uin.\n                  apply List.in_map_iff in Uin.\n                  destruct Uin as [V [EQ Vin]]; subst.\n                  intro HF.\n                  lets Sm: fv_smaller_many Alphas V.\n                  apply Sm in HF.\n                  rewrite in_union in HF.\n                  destruct HF as [HF|HF].\n                  +++ rewrite~ FVret in HF.\n                      apply* in_empty_inv.\n                  +++ apply from_list_spec in HF.\n                      apply LibList_mem in HF.\n                      lets: FVZA HF. false.\n           ** apply* type_from_wft.\n  - econstructor; eauto.\n    + apply* entails_through_subst.\n    + apply* wft_subst_tb_3.\nQed.\n\nLemma typing_through_subst_te_3 :\n  forall Σ Δ E Z e P T TT,\n    {Σ, Δ |,| [tc_var Z]*, E} ⊢(TT) e ∈ T ->\n    wft Σ Δ P ->\n    Z \\notin fv_typ P ->\n    Z # E ->\n    Z \\notin fv_env E ->\n    Z \\notin domΔ Δ ->\n    {Σ, Δ, E} ⊢(Tgen) subst_te Z P e ∈ subst_tt Z P T.\nProof.\n  introv Typ WFT ZP ZE1 ZE2 ZD.\n  rewrite <- (List.app_nil_l (Δ |,| [tc_var Z]*)) in Typ.\n  lets HT: typing_through_subst_te_gen Typ WFT ZP ZD ZE1.\n  cbn in HT.\n  rewrite~ subst_tb_id_on_fresh in HT.\nQed.\n\nLemma typing_through_subst_te_many : forall As Σ Δ Δ2 E F e T Ps TT,\n    {Σ, (Δ |,| tc_vars As |,| Δ2), E & F} ⊢(TT) e ∈ T ->\n    length As = length Ps ->\n    (forall P, List.In P Ps -> wft Σ Δ P) ->\n    (forall A, List.In A As -> A # E) ->\n    (forall A, List.In A As -> A # F) ->\n    (forall A, List.In A As -> A \\notin domΔ Δ) ->\n    (forall A, List.In A As -> A \\notin domΔ Δ2) ->\n    (forall A P, List.In A As -> List.In P Ps -> A \\notin fv_typ P) ->\n    (forall A, List.In A As -> A \\notin fv_env E) ->\n    DistinctList As ->\n    {Σ, Δ |,| List.map (subst_td_many As Ps) Δ2, E & map (subst_tb_many As Ps) F} ⊢(Tgen) (subst_te_many As Ps e) ∈  subst_tt_many As Ps T.\nProof.\n  induction As as [| Ah Ats]; introv Htyp Hlen Pwft AE AF AD AD2 AP AEE Adist;\n    destruct Ps as [| Ph Pts]; try solve [cbn in *; congruence].\n  - cbn. cbn in Htyp.\n    rewrite List.map_id.\n    rewrite map_def.\n    rewrite <- LibList_map.\n    rewrite <- map_id; eauto using Tgen_from_any.\n    intros. destruct x as [? [?]].\n    cbv. auto.\n  - cbn.\n    inversions Adist.\n    lets IH0: IHAts Σ Δ (List.map (subst_td Ah Ph) Δ2) (map (subst_tb Ah Ph) E) (map (subst_tb Ah Ph) F).\n    lets IH: IH0 (subst_te Ah Ph e) (subst_tt Ah Ph T) Pts; clear IH0.\n    rewrite <- (@subst_tb_id_on_fresh E Ah Ph).\n    rewrite subst_tb_many_split.\n    rewrite List.map_map in IH.\n    eapply IH; auto with listin.\n    + clear IH IHAts.\n      cbn in Htyp. fold_delta.\n      lets HT: typing_through_subst_te_gen Ph Htyp.\n      rewrite <- map_concat.\n      apply HT; auto with listin.\n      * assert (WFT: wft Σ Δ Ph); auto with listin.\n        apply* wft_weaken_simple.\n      * repeat rewrite domDelta_app.\n        repeat rewrite notin_union.\n        repeat split; auto with listin.\n        apply notin_dom_tc_vars.\n        intro HF.\n        apply from_list_spec in HF.\n        apply LibList_mem in HF.\n        false~.\n    + introv Ain.\n      rewrite <- domDelta_subst_td; auto with listin.\n    + introv Ain.\n      apply~ fv_env_subst; auto with listin.\n    + auto with listin.\nQed.\n\nLtac generalize_typings :=\n  match goal with\n  | [ H: {?Σ, ?D, ?E} ⊢(?TT) ?e ∈ ?T |- _ ] =>\n    match TT with\n    | Tgen => fail 1\n    | Treg => fail 1\n    | _ => apply Tgen_from_any in H;\n           try clear TT\n    end\n  end.\n\nLemma typing_replace_typ_gen : forall Σ Δ E F x vk T1 TT e U T2,\n    {Σ, Δ, E & x ~ bind_var vk T1 & F} ⊢( TT) e ∈ U ->\n    wft Σ Δ T2 ->\n    entails_semantic Σ Δ (T1 ≡ T2) ->\n    {Σ, Δ, E & x ~ bind_var vk T2 & F} ⊢(Tgen) e ∈ U.\nProof.\n  introv Typ.\n  gen_eq K: (E & x ~ bind_var vk T1 & F). gen F x T1.\n  induction Typ using typing_ind; introv EQ WFT Sem; subst; eauto;\n    try solve [apply Tgen_from_any with Treg; eauto].\n  - apply Tgen_from_any with Treg;\n      econstructor. apply* okt_replace_typ.\n  - destruct (classicT (x = x0)); subst.\n    + lets: okt_is_ok H0.\n      apply binds_middle_eq_inv in H; auto.\n      inversions H.\n      apply typing_eq with T2 Treg.\n      * constructor.\n        -- apply binds_concat_left.\n           ++ apply binds_push_eq.\n           ++ lets* [? ?]: ok_middle_inv H1.\n        -- apply* okt_replace_typ.\n      * apply~ teq_symmetry.\n      * apply* okt_is_wft_2.\n    + apply Tgen_from_any with Treg.\n      constructor.\n      * lets [? | [[? [? ?]] | [? [? ?]]]]: binds_middle_inv H; subst.\n        -- apply~ binds_concat_right.\n        -- false.\n        -- apply~ binds_concat_left.\n      * apply* okt_replace_typ.\n  - apply Tgen_from_any with Treg.\n    econstructor.\n    introv xiL.\n    lets IH: H0 xiL (F & x0 ~l V) x T0.\n    repeat rewrite concat_assoc in IH.\n    apply* IH.\n  - apply Tgen_from_any with Treg.\n    econstructor; eauto.\n    introv xiL.\n    lets IH: H1 xiL F x T0.\n    repeat rewrite concat_assoc in IH.\n    apply* IH.\n    + apply~ wft_weaken_simple.\n    + rewrite <- (List.app_nil_l (Δ |,| [tc_var X]*)).\n      apply~ equation_weaken_var.\n      cbn. auto.\n  - apply Tgen_from_any with Treg.\n    econstructor; eauto.\n    introv xiL.\n    lets IH: H1 xiL (F & x0 ~f T) x T1.\n    repeat rewrite concat_assoc in IH.\n    apply* IH.\n  - apply Tgen_from_any with Treg.\n    econstructor; eauto.\n    introv xiL.\n    lets IH: H0 xiL (F & x0 ~l V) x T1.\n    repeat rewrite concat_assoc in IH.\n    apply* IH.\n  - apply Tgen_from_any with Treg.\n    econstructor; eauto.\n    introv In Alen Adist Afr xfr xAfr.\n    lets Htmp: H4 In Alen Adist Afr xfr.\n    lets IH: Htmp xAfr (F & x0 ~l open_tt_many_var Alphas (Cargtype def)) x T1. clear Htmp.\n    repeat rewrite concat_assoc in IH.\n    apply* IH.\n    + repeat apply* wft_weaken_simple.\n    + apply~ equations_weaken_match.\n      rewrite List.map_length.\n      lets [OKT [? WFT2]]: typing_regular Typ.\n      inversions WFT2.\n      lets OKS: okt_implies_okgadt OKT.\n      inversion OKS as [? OKC].\n      lets [? OKD]: OKC H0.\n      lets indef: fst_from_zip In.\n      lets OKE: OKD indef.\n      inversions OKE.\n      cbn.\n      match goal with\n      | [ H1: binds ?g ?A Σ, H2: binds ?g ?B Σ |- _ ] =>\n        let H := fresh \"H\" in\n        lets H: binds_ext H1 H2;\n          inversions H\n      end.\n      auto.\nQed.\n\nLemma typing_replace_typ : forall Σ Δ E x vk T1 TT e U T2,\n    {Σ, Δ, E & x ~ bind_var vk T1} ⊢( TT) e ∈ U ->\n    entails_semantic Σ Δ (T1 ≡ T2) ->\n    wft Σ Δ T2 ->\n    {Σ, Δ, E & x ~ bind_var vk T2} ⊢( Tgen) e ∈ U.\nProof.\n  intros.\n  rewrite <- (concat_empty_r (E & x ~ bind_var vk T2)).\n  apply* typing_replace_typ_gen.\n  fold_env_empty.\nQed.\n\nLemma remove_true_equation : forall Σ Δ1 Δ2 E e TT T U1 U2,\n    {Σ, Δ1 |,| [tc_eq (U1 ≡ U2)]* |,| Δ2, E} ⊢(TT) e ∈ T ->\n    entails_semantic Σ Δ1 (U1 ≡ U2) ->\n    {Σ, Δ1 |,| Δ2, E} ⊢(TT) e ∈ T.\nProof.\n  introv Typ.\n  gen_eq D3: (Δ1 |,| [tc_eq (U1 ≡ U2)]* |,| Δ2). gen Δ1 Δ2.\n  lets: okt_strengthen_delta_eq.\n  lets: wft_strengthen_equation.\n  induction Typ using typing_ind; introv EQ Sem; subst; eauto.\n  - econstructor; eauto.\n    introv XFr.\n    lets IH: H3 XFr Δ1 (Δ2 |,| [tc_var X]*).\n    apply* IH.\n  - econstructor; eauto.\n    introv clin Hlen Hdist Afresh xfresh xfreshA.\n    lets Htmp: H6 clin Hlen Hdist Afresh xfresh.\n    lets IH: Htmp xfreshA Δ1\n                  (Δ2 |,| tc_vars Alphas |,| equations_from_lists Ts (List.map (open_tt_many_var Alphas) (Crettypes def)));\n      clear Htmp.\n    repeat rewrite List.app_assoc in *.\n    apply* IH.\n  - lets: equation_strengthen H1 Sem.\n    econstructor; eauto.\nQed.\n\nLemma remove_true_equations : forall Σ Δ E e TT V Ts Us,\n    {Σ, Δ |,| equations_from_lists Ts Us, E} ⊢(TT) e ∈ V ->\n    List.Forall2 (fun T U => entails_semantic Σ Δ (T ≡ U)) Ts Us ->\n    {Σ, Δ, E} ⊢(TT) e ∈ V.\nProof.\n  induction 2 as [| T U Ts Us].\n  - cbn in *. auto.\n  - cbn in H.\n    fold (equations_from_lists Ts Us) in H.\n    apply* IHForall2.\n    rewrite <- (List.app_nil_l ((Δ |,| equations_from_lists Ts Us) |, tc_eq (T ≡ U))) in H.\n    forwards~ H2: remove_true_equation H.\n    forwards* H3: equations_weaken_match (@nil var) Ts Us.\n    apply* Forall2_eq_len.\nQed.\n\nLemma helper_equations_commute : forall Ts As Us Vs,\n    List.length As = List.length Us ->\n    List.length Ts = List.length Vs ->\n    (forall A, List.In A As -> A \\notin fv_typs Ts) ->\n    equations_from_lists\n      Ts\n      (List.map (fun T : typ => subst_tt_many As Us (open_tt_many_var As T)) Vs)\n    =\n    List.map\n      (subst_td_many As Us)\n      (equations_from_lists Ts (List.map (open_tt_many_var As) Vs)).\nProof.\n  intros.\n  rewrite (equations_from_lists_map _ (subst_tt_many As Us) (subst_tt_many As Us)).\n  - f_equal.\n    + gen Us.\n      induction As as [| A As]; introv Len.\n      * cbn. rewrite~ List.map_id.\n      * destruct Us as [| U Us]; cbn.\n        -- rewrite~ List.map_id.\n        -- rewrite <- List.map_map.\n           rewrite (List.map_ext_in (subst_tt A U) (fun x => x)).\n           ++ rewrite List.map_id.\n              apply~ IHAs; auto with listin.\n           ++ intros T Tin.\n              apply subst_tt_fresh.\n              apply fv_typs_notin with Ts; auto with listin.\n    + rewrite List.map_map. auto.\n  - rewrite~ List.map_length.\n  - introv In.\n    gen H.\n    clear.\n    rename U into T2. rename T into T1.\n    gen Us T1 T2.\n    induction As as [| A As]; introv Len; destruct Us as [| U Us]; auto.\n    cbn.\n    rewrite~ IHAs.\nQed.\n\nTheorem preservation_thm : preservation.\nProof.\n  Ltac find_hopen :=\n    let Hopen := fresh \"Hopen\" in\n    match goal with\n    | H: forall x, x \\notin ?L -> typing _ _ _ _ _ _ |- _ =>\n      rename H into Hopen\n    end.\n  unfold preservation.\n  introv Htyp.\n  assert (term e) as Hterm; eauto using typing_implies_term.\n  generalize e'.\n  clear e'.\n  induction Htyp; inversions Hterm;\n    introv Hred; inversions Hred;\n      try solve [eauto using Tgen_from_any];\n      repeat generalize_typings.\n  - (* app *)\n    lets [U [HT EQ]]: inversion_typing_eq Htyp2.\n    inversions HT.\n    pick_fresh x.\n    find_hopen. forwards~ K: (Hopen x).\n    rewrite* (@subst_ee_intro lam_var x).\n    expand_env_empty E.\n    apply* typing_through_subst_ee_lam.\n    fold_env_empty.\n    apply teq_symmetry in EQ.\n    lets [EQarg EQret]: inversion_eq_arrow EQ.\n    apply typing_eq with T0 Tgen; auto.\n    + apply* typing_replace_typ.\n      lets*: typing_regular Htyp1.\n    + lets* [? [? WFT]]: typing_regular Htyp2.\n      inversion~ WFT.\n  - (* tabs *)\n    lets [U [HT EQ]]: inversion_typing_eq Htyp.\n    inversions HT.\n    match goal with\n    | _: {?A, ?B, ?C} ⊢( ?D ) ?e ∈ typ_all ?T |- _ =>\n      rename T into Tall\n    end.\n    match goal with\n    | _: wft ?A ?B ?T |- _ =>\n      rename T into Targ\n    end.\n\n    apply teq_symmetry in EQ.\n    lets: inversion_eq_typ_all EQ; subst.\n    apply typing_eq with (open_tt T0 Targ) Tgen.\n    + pick_fresh X.\n      rewrite* (@subst_te_intro X).\n      rewrite* (@subst_tt_intro X).\n      apply~ typing_through_subst_te_3.\n    + apply~ teq_open.\n    + lets* [? [? WFT]]: typing_regular Htyp.\n      apply~ wft_open.\n  - (* fst *)\n    lets [U [HT EQ]]: inversion_typing_eq Htyp.\n    inversions HT.\n    repeat generalize_typings.\n    apply teq_symmetry in EQ.\n    lets [EQarg EQret]: inversion_eq_tuple EQ.\n    apply* typing_eq.\n    lets* [? [? WFT]]: typing_regular Htyp.\n    inversion~ WFT.\n  - (* snd *)\n    lets [U [HT EQ]]: inversion_typing_eq Htyp.\n    inversions HT.\n    repeat generalize_typings.\n    apply teq_symmetry in EQ.\n    lets [EQarg EQret]: inversion_eq_tuple EQ.\n    apply* typing_eq.\n    lets* [? [? WFT]]: typing_regular Htyp.\n    inversion~ WFT.\n  - (* fix *)\n    pick_fresh f.\n    rewrite* (@subst_ee_intro fix_var f).\n    expand_env_empty E.\n    apply* typing_through_subst_ee_fix.\n    fold_env_empty.\n  - (* let *)\n    pick_fresh x.\n    rewrite* (@subst_ee_intro lam_var x).\n    expand_env_empty E.\n    apply* typing_through_subst_ee_lam.\n    fold_env_empty.\n  - (* matchgadt *)\n    (* we reduce to one of the branches which correspond to their definitions in type *)\n    lets* [Def [nthDef Inzip]]: nth_error_implies_zip_swap Defs H10.\n    lets HclTyp: H3 Inzip.\n    remember (Cargtype Def) as argT.\n    (* prepare fresh vars *)\n    let fresh := gather_vars in\n    lets* [Alphas [Hlen [Adist Afresh]]]: exist_alphas fresh (length Ts0).\n    pick_fresh x.\n\n    match goal with\n    | [ H: term (trm_constructor ?A ?B ?C) |- _ ] =>\n      inversions H7\n    end.\n\n    (* extract info from well-formedness of GADT env Σ - our constructors are well formed *)\n    lets [Hokt ?]: typing_regular Htyp.\n    lets okgadt: okt_implies_okgadt Hokt.\n    unfold okGadt in okgadt.\n    destruct okgadt as [okΣ okCtors].\n    lets [defsNe okDefs]: okCtors H0.\n    lets indef: fst_from_zip Inzip.\n    lets okCtor: okDefs indef.\n    inversion okCtor.\n    clear H15 H16 Tarity0 Σ0.\n    rename Carity into DefArity.\n\n    (* replace open with subst+open_var *)\n    rewrite~ (@subst_ee_intro lam_var x);\n      [ idtac\n      | apply fv_open_te_many;\n        [ introv Tin;\n          apply* fv_typs_notin\n        | auto ]\n      ].\n\n    rewrite (@subst_te_intro_many Alphas _ Ts0); auto;\n      [ idtac\n      | introv Ain; subst; cbn; cbn in Afresh; lets*: Afresh Ain\n      | introv Ain Tin; lets: Afresh Ain; apply* fv_typs_notin\n      ].\n\n    (* use fact that subst preserves typing *)\n    lets [T' [Typ2 EQ]]: inversion_typing_eq Htyp.\n    inversions Typ2.\n    match goal with\n    | [ H1: binds ?g ?A Σ, H2: binds ?g ?B Σ |- _ ] =>\n      let H := fresh \"H\" in\n      lets H: binds_ext H1 H2;\n        inversions H\n    end.\n\n    rename H20 into TypCtorArg.\n    match goal with\n    | [ H1: List.nth_error Ctors cid = ?A, H2: List.nth_error Ctors cid = ?B |- _ ] =>\n      let H := fresh \"H\" in\n      assert (H: A = B); [ rewrite <- H2; auto | idtac ];\n        inversions H\n    end.\n    rewrite (@subst_tt_intro_many Alphas _ Ts0) in TypCtorArg; auto.\n    2: {\n      intros A Ain; subst; cbn; cbn in Afresh.\n      rewrite H13. auto.\n    }\n    2: {\n      intros A U Ain Uin.\n      lets WFT: H29 Uin.\n      lets: wft_gives_fv WFT.\n      intro HF.\n      assert (HA: A \\in domΔ Δ); auto.\n      lets HA2: Afresh Ain.\n      apply HA2. repeat rewrite in_union. repeat right~.\n    }\n\n    expand_env_empty E.\n    match goal with\n    | H: value (trm_constructor _ _ e1) |- _ =>\n      inversions H\n    end.\n    eapply typing_through_subst_ee_lam with (subst_tt_many Alphas Ts0 (open_tt_many_var Alphas CargType)) Tgen _; auto; [idtac | eauto].\n\n    (* instantiate the inductive hypothesis *)\n    assert (AfreshL: forall A : var, List.In A Alphas -> A \\notin L);\n      [ introv Ain; lets*: Afresh Ain | idtac].\n    assert (xfreshL: x \\notin L); auto.\n    assert (xfreshA: x \\notin from_list Alphas); auto.\n\n    lets* IH: H3 Inzip Alphas x Adist xfreshA.\n    cbn in IH.\n\n    rewrite subst_te_many_commutes_open; auto;\n      [ idtac\n      | introv Ain; lets: Afresh Ain;\n        lets: from_list_spec2 Ain;\n        intro; subst; auto\n      ].\n\n    fold (subst_tb_many Alphas Ts0 (bind_var lam_var (open_tt_many_var Alphas CargType))).\n    rewrite <- map_single.\n    fold_env_empty.\n\n    rewrite subst_tt_many_free with Alphas Ts0 Tc;\n      [ idtac | introv Ain; lets*: Afresh Ain ].\n\n    assert (length CretTypes = length Ts).\n    1: {\n      lets [OKT [? WFT2]]: typing_regular Htyp.\n      inversions WFT2.\n      lets OKS: okt_implies_okgadt OKT.\n      inversion OKS as [? OKC].\n      lets [? OKD]: OKC H0.\n      cbn in *.\n      lets OKE: OKD indef.\n      inversions OKE.\n      match goal with\n      | [ H1: binds ?g ?A Σ, H2: binds ?g ?B Σ |- _ ] =>\n        let H := fresh \"H\" in\n        lets H: binds_ext H1 H2;\n          inversions H\n      end.\n      auto.\n    }\n\n    apply remove_true_equations with Ts (List.map (fun T => subst_tt_many Alphas Ts0 (open_tt_many_var Alphas T)) CretTypes).\n    + assert (Hrew:\n          equations_from_lists Ts (List.map (fun T : typ => subst_tt_many Alphas Ts0 (open_tt_many_var Alphas T)) CretTypes)\n          =\n          List.map (subst_td_many Alphas Ts0) (equations_from_lists Ts (List.map (open_tt_many_var Alphas) CretTypes))\n        ).\n      * apply~ helper_equations_commute.\n        introv Ain. lets~ : Afresh Ain.\n      * rewrite Hrew; clear Hrew.\n        apply typing_through_subst_te_many with Tgen; trivial.\n        -- intros A Ain.\n           lets: Afresh Ain. auto.\n        -- autorewrite with rew_env_dom.\n           intros A Ain.\n           apply notin_inverse.\n           intro HF.\n           apply xfreshA.\n           rewrite in_singleton in HF. subst.\n           apply from_list_spec2. auto.\n        -- introv Ain.\n           lets~ : Afresh Ain.\n        -- introv Ain.\n           rewrite~ equations_have_no_dom.\n           apply* equations_from_lists_are_equations.\n        -- introv Ain Tin.\n           apply fv_typs_notin with Ts0; auto.\n           lets: Afresh Ain.\n           auto with listin.\n        -- introv Ain; lets*: Afresh Ain.\n    + assert (Hrew:\n                open_tt_many Ts0 (typ_gadt CretTypes Name)\n                =\n                typ_gadt (List.map (open_tt_many Ts0) CretTypes) Name).\n      * clear.\n        rename Ts0 into Ts.\n        rename CretTypes into Us.\n        gen Us.\n        induction Ts; introv.\n        -- cbn. rewrite~ List.map_id.\n        -- cbn. rewrite IHTs.\n           f_equal.\n           rewrite List.map_map.\n           apply List.map_ext.\n           intro T. auto.\n      * rewrite Hrew in EQ; clear Hrew.\n        assert (Hrew: (List.map (fun T : typ => subst_tt_many Alphas Ts0 (open_tt_many_var Alphas T)) CretTypes) = List.map (open_tt_many Ts0) CretTypes).\n        1: {\n          apply List.map_ext_in.\n          intros T Tin.\n          rewrite~ <- subst_tt_intro_many.\n          - intros A Ain.\n            rewrite~ H14.\n          - intros A U Ain Uin.\n            lets: Afresh Ain.\n            apply fv_typs_notin with Ts0; auto.\n        }\n        rewrite Hrew; clear Hrew.\n        lets EQ2: inversion_eq_typ_gadt EQ.\n        rewrite <- (List.map_ext_in (fun T : typ => open_tt_many Ts0 T)).\n        2: {\n          intros T Tin.\n          rewrite~ (@subst_tt_intro_many Alphas T Ts0).\n          -- rewrite~ H14.\n          -- introv Ain Uin. lets HF2: Afresh Ain.\n             apply* fv_typs_notin.\n        }\n        -- rewrite~ List.map_length.\n        -- apply EQ2.\nQed.\n\nCheck preservation_thm.", "meta": {"author": "radeusgd", "repo": "GADT-thesis", "sha": "18be642b1f9ef145c9fbc02f55eefb51d4bc1fdf", "save_path": "github-repos/coq/radeusgd-GADT-thesis", "path": "github-repos/coq/radeusgd-GADT-thesis/GADT-thesis-18be642b1f9ef145c9fbc02f55eefb51d4bc1fdf/lambda2Gmu/Preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.21369501633008278}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.comm Require Import Monad.\nFrom bpf.clightlogic Require Import CommonLemma CommonLib Clightlogic CorrectRel.\nFrom bpf.verifier.comm Require Import monad.\n\nFrom bpf.verifier.synthesismodel Require Import verifier_synthesis.\nFrom bpf.verifier.clightmodel Require Import verifier.\nFrom bpf.verifier.simulation Require Import VerifierSimulation VerifierRel.\n\n\n(**\nCheck is_not_div_by_zero64.\nis_not_div_by_zero64\n     : int64 -> M bool\n*)\n\nSection Is_not_div_by_zero64.\n  Context {S: special_blocks}.\n\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(int64:Type)].\n  Definition res : Type := (bool:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M state.state res) := is_not_div_by_zero64.\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_is_not_div_by_zero64.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    dcons (fun x => StateLess _ (int64_correct x))\n          (DList.DNil _).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv state.state := fun x  => StateLess _ (bool_correct x).\n\n  Instance correct_function_is_not_div_by_zero64 : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n\n    unfold f. unfold is_not_div_by_zero64.\n    correct_forward.\n\n    get_invariant _i.\n    unfold eval_inv, int64_correct in c0.\n    subst.\n\n    eexists.\n\n    split_and; auto.\n    {\n      unfold exec_expr.\n      match goal with\n      | H: ?X = _ |- context [match ?X with _ => _ end] =>\n        rewrite H\n      end. simpl.\n      unfold Cop.sem_shr, Cop.sem_shift; simpl.\n      change Int64.iwordsize with (Int64.repr 64).\n      change (Int64.ltu (Int64.repr 32) (Int64.repr 64)) with true; simpl.\n      unfold Cop.sem_cmp; simpl.\n      unfold Cop.sem_binarith; simpl.\n      unfold Val.of_bool; simpl.\n      unfold Vtrue, Vfalse.\n      reflexivity.\n    }\n\n    unfold eval_inv, match_res, state.is_not_div_by_zero64'.\n    unfold bool_correct, Val.of_bool.\n    unfold BinrBPF.get_immediate, Int64.cmp, rBPFValues.int64_to_sint32.\n    destruct negb; reflexivity.\n    unfold Cop.sem_cast; simpl.\n    destruct negb; reflexivity.\n    destruct negb; constructor; reflexivity.\n  Qed.\n\nEnd Is_not_div_by_zero64.\n\nExisting  Instance correct_function_is_not_div_by_zero64.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/verifier/simulation/correct_is_not_div_by_zero64.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3775406617944891, "lm_q1q2_score": 0.21369501236588345}}
{"text": "From Coq Require Import Program ssreflect ssrbool List.\nFrom MetaCoq.Utils Require Import utils MCRelations.\nFrom MetaCoq.Common Require Import config Kernames.\n\n\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICPrimitive\n  PCUICReduction\n  PCUICReflect PCUICWeakeningEnv PCUICWeakeningEnvConv PCUICWeakeningEnvTyp PCUICCasesContexts\n  PCUICWeakeningConv PCUICWeakeningTyp\n  PCUICContextConversionTyp\n  PCUICTyping PCUICGlobalEnv PCUICInversion PCUICGeneration\n  PCUICConfluence PCUICConversion\n  PCUICUnivSubstitutionTyp\n  PCUICCumulativity PCUICSR PCUICSafeLemmata\n  PCUICValidity PCUICPrincipality PCUICElimination\n  PCUICOnFreeVars PCUICWellScopedCumulativity PCUICSN PCUICCanonicity.\n\nFrom MetaCoq Require Import PCUICArities PCUICSpine.\nFrom MetaCoq.PCUIC Require PCUICWcbvEval.\nFrom MetaCoq.PCUIC Require Import PCUICEquality PCUICAlpha.\n\nSection firstorder.\n\n  Context {Σ : global_env_ext}.\n  Context {Σb : list (kername × bool)}.\n\n  Fixpoint plookup_env {A} (Σ : list (kername × A)) (kn : kername) {struct Σ} : option A :=\n  match Σ with\n  | [] => None\n  | d :: tl => if eq_kername kn d.1 then Some d.2 else plookup_env tl kn\n  end.\n  (*\n  Definition zo_type (t : term) :=\n    match (PCUICAstUtils.decompose_app t).1 with\n    | tProd _ _ _ => false\n    | tSort _ => false\n    | tInd (mkInd nm i) _ => match (plookup_env Σb nm) with\n                             | Some l => nth i l false | None => false\n                             end\n    | _ => true\n    end. *)\n\n  Definition firstorder_type (n k : nat) (t : term) :=\n    match (PCUICAstUtils.decompose_app t).1 with\n    | tInd (mkInd nm i) u => match (plookup_env Σb nm) with\n                             | Some b => b | None => false\n                             end\n    | tRel i => (k <=? i) && (i <? n + k)\n    | _ => false\n    end.\n  (*\n  Definition firstorder_type (t : term) :=\n    match (PCUICAstUtils.decompose_app t).1 with\n    | tInd (mkInd nm i) _ => match (plookup_env Σb nm) with\n                             | Some l => nth i l false | None => false\n                             end\n    | _ => false\n    end. *)\n\n  Definition firstorder_con mind (c : constructor_body) :=\n    let inds := #|mind.(ind_bodies)| in\n    alli (fun k '({| decl_body := b ; decl_type := t ; decl_name := n|}) =>\n      firstorder_type inds k t) 0\n      (List.rev (c.(cstr_args) ++ mind.(ind_params)))%list.\n\n  Definition firstorder_oneind mind (ind : one_inductive_body) :=\n    forallb (firstorder_con mind) ind.(ind_ctors) && negb (Universe.is_level (ind_sort ind)).\n\n  Definition firstorder_mutind (mind : mutual_inductive_body) :=\n    (* if forallb (fun decl => firstorder_type decl.(decl_type)) mind.(ind_params) then *)\n    (mind.(ind_finite) == Finite) &&\n    forallb (firstorder_oneind mind) mind.(ind_bodies)\n    (* else repeat false (length mind.(ind_bodies)). *).\n\n  Definition firstorder_ind (i : inductive) :=\n    match lookup_env Σ.1 (inductive_mind i) with\n    | Some (InductiveDecl mind) => firstorder_mutind mind\n    | _ => false\n    end.\n\nEnd firstorder.\n\nFixpoint firstorder_env' (Σ : global_declarations) :=\n  match Σ with\n  | nil => []\n  | (nm, ConstantDecl _) :: Σ' =>\n    let Σb := firstorder_env' Σ' in\n    ((nm, false) :: Σb)\n  | (nm, InductiveDecl mind) :: Σ' =>\n    let Σb := firstorder_env' Σ' in\n    ((nm, @firstorder_mutind Σb mind) :: Σb)\n  end.\n\nDefinition firstorder_env (Σ : global_env_ext) :=\n  firstorder_env' Σ.1.(declarations).\n\nSection cf.\n\nContext {cf : config.checker_flags}.\n\nDefinition isPropositional Σ ind b :=\n  match lookup_env Σ (inductive_mind ind) with\n  | Some (InductiveDecl mdecl) =>\n    match nth_error mdecl.(ind_bodies) (inductive_ind ind) with\n    | Some idecl =>\n      match destArity [] idecl.(ind_type) with\n      | Some (_, s) => is_propositional s = b\n      | None => False\n      end\n    | None => False\n    end\n  | _ => False\n  end.\n\nInductive firstorder_value Σ Γ : term -> Prop :=\n| firstorder_value_C i n ui u args pandi :\n   Σ ;;; Γ |- mkApps (tConstruct i n ui) args :\n   mkApps (tInd i u) pandi ->\n   Forall (firstorder_value Σ Γ) args ->\n   isPropositional Σ i false ->\n   firstorder_value Σ Γ (mkApps (tConstruct i n ui) args).\n\nLemma firstorder_value_inds :\n forall (Σ : global_env_ext) (Γ : context) (P : term -> Prop),\n(forall (i : inductive) (n : nat) (ui u : Instance.t)\n   (args pandi : list term),\n Σ;;; Γ |- mkApps (tConstruct i n ui) args : mkApps (tInd i u) pandi ->\n Forall (firstorder_value Σ Γ) args ->\n Forall P args ->\n isPropositional (PCUICEnvironment.fst_ctx Σ) i false ->\n P (mkApps (tConstruct i n ui) args)) ->\nforall t : term, firstorder_value Σ Γ t -> P t.\nProof using Type.\n  intros ? ? ? ?. fix rec 2. intros t [ ]. eapply H; eauto.\n  clear - H0 rec.\n  induction H0; econstructor; eauto.\nQed.\n\nLemma firstorder_ind_propositional {Σ : global_env_ext} {wfΣ:wf Σ} i mind oind :\n  declared_inductive Σ i mind oind ->\n  @firstorder_ind Σ (firstorder_env Σ) i ->\n  isPropositional Σ i false.\nProof using Type.\n  intros d. unshelve epose proof (d_ := declared_inductive_to_gen d); eauto.\n  pose proof d_ as [d1 d2]. intros H. red in d1. unfold firstorder_ind in H.\n  red. sq.\n  unfold PCUICEnvironment.fst_ctx in *. rewrite d1 in H |- *.\n  solve_all.\n  unfold firstorder_mutind in H.\n  rewrite d2. move/andP: H => [ind H0].\n  eapply forallb_nth_error in H0; tea.\n  erewrite d2 in H0. cbn in H0.\n  unfold firstorder_oneind in H0. solve_all.\n  destruct (ind_sort oind) eqn:E2; inv H0.\n  eapply PCUICInductives.declared_inductive_type in d.\n  rewrite d. rewrite E2.\n  now rewrite destArity_it_mkProd_or_LetIn.\nQed.\n\nInductive firstorder_spine Σ (Γ : context) : term -> list term -> term -> Type :=\n| firstorder_spine_nil ty ty' :\n    isType Σ Γ ty ->\n    isType Σ Γ ty' ->\n    Σ ;;; Γ ⊢ ty ≤ ty' ->\n    firstorder_spine Σ Γ ty [] ty'\n\n| firstorder_spine_cons ty hd tl na i u args B B' mind oind :\n    isType Σ Γ ty ->\n    isType Σ Γ (tProd na (mkApps (tInd i u) args) B) ->\n    Σ ;;; Γ ⊢ ty ≤ tProd na (mkApps (tInd i u) args) B ->\n    declared_inductive Σ i mind oind ->\n    Σ ;;; Γ |- hd : (mkApps (tInd i u) args) ->\n    @firstorder_ind Σ (@firstorder_env Σ) i ->\n    firstorder_spine Σ Γ (subst10 hd B) tl B' ->\n    firstorder_spine Σ Γ ty (hd :: tl) B'.\n\nInductive instantiated {Σ} (Γ : context) : term -> Type :=\n| instantiated_mkApps i u args : instantiated Γ (mkApps (tInd i u) args)\n| instantiated_LetIn na d b ty :\n  instantiated Γ (ty {0 := d}) ->\n  instantiated Γ (tLetIn na d b ty)\n| instantiated_tProd na B i u args :\n  @firstorder_ind Σ (@firstorder_env Σ) i ->\n    (forall x,\n       (* Σ ;;; Γ |- x : mkApps (tInd i u) args ->  *)\n      instantiated Γ (subst10 x B)) ->\n    instantiated Γ (tProd na (mkApps (tInd i u) args) B).\n\nImport PCUICLiftSubst.\nLemma isType_context_conversion {Σ : global_env_ext} {wfΣ : wf Σ} {Γ Δ} {T} :\n  isType Σ Γ T ->\n  Σ ⊢ Γ = Δ ->\n  wf_local Σ Δ ->\n  isType Σ Δ T.\nProof using Type.\n  intros [s Hs]. exists s. eapply context_conversion; tea. now eapply ws_cumul_ctx_pb_forget.\nQed.\n\nLemma typing_spine_arity_spine {Σ : global_env_ext} {wfΣ : wf Σ} Γ Δ args T' i u pars :\n  typing_spine Σ Γ (it_mkProd_or_LetIn Δ (mkApps (tInd i u) pars)) args T' ->\n  arity_spine Σ Γ (it_mkProd_or_LetIn Δ (mkApps (tInd i u) pars)) args T'.\nProof using Type.\n  intros H. revert args pars T' H.\n  induction Δ using PCUICInduction.ctx_length_rev_ind; intros args pars T' H.\n  - cbn. depelim H.\n    + econstructor; eauto.\n    + eapply invert_cumul_ind_prod in w. eauto.\n  - cbn. depelim H.\n    + econstructor; eauto.\n    + rewrite it_mkProd_or_LetIn_app in w, i0 |- *. cbn. destruct d as [name [body |] type]; cbn in *.\n      -- constructor. rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps. eapply X. now len.\n         econstructor; tea. eapply isType_tLetIn_red in i0.\n         rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps Nat.add_0_r in i0. now rewrite Nat.add_0_r. pcuic.\n         etransitivity; tea. eapply into_ws_cumul_pb. 2,4:fvs.\n         econstructor 3. 2:{ econstructor. }\n         rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps //. constructor 1. reflexivity.\n         eapply isType_tLetIn_red in i0. 2:pcuic.\n         rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps in i0.\n         now eapply isType_open.\n      -- eapply cumul_Prod_inv in w as []. econstructor.\n         ++ eapply type_ws_cumul_pb. 3: eapply PCUICContextConversion.ws_cumul_pb_eq_le; symmetry. all:eauto.\n            eapply isType_tProd in i0. eapply i0.\n         ++ rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn. autorewrite with subst.\n            cbn. eapply X. len.\n            eapply typing_spine_strengthen. eauto.\n            2:{ replace (it_mkProd_or_LetIn (subst_context [hd] 0 Γ0)\n            (mkApps (tInd i u) (map (subst [hd] (#|Γ0| + 0)) pars))) with ((PCUICAst.subst10 hd (it_mkProd_or_LetIn Γ0 (mkApps (tInd i u) pars)))).\n            2:{ rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn. now autorewrite with subst. }\n            eapply substitution0_ws_cumul_pb. eauto. eauto.\n            }\n            replace (it_mkProd_or_LetIn (subst_context [hd] 0 Γ0)\n            (mkApps (tInd i u) (map (subst [hd] (#|Γ0| + 0)) pars))) with ((PCUICAst.subst10 hd (it_mkProd_or_LetIn Γ0 (mkApps (tInd i u) pars)))).\n            2:{ rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn. now autorewrite with subst. }\n            eapply isType_subst. eapply PCUICSubstitution.subslet_ass_tip. eauto.\n            eapply isType_tProd in i0 as [_ tprod].\n            eapply isType_context_conversion; tea. constructor. eapply ws_cumul_ctx_pb_refl. now eapply typing_wf_local, PCUICClosedTyp.wf_local_closed_context in t.\n            constructor; tea. constructor. pcuic. eapply validity in t. now eauto.\nQed.\n\nLemma leb_spect : forall x y : nat, BoolSpecSet (x <= y) (y < x) (x <=? y).\nProof using Type.\n  intros x y. destruct (x <=? y) eqn:E;\n  econstructor; destruct (Nat.leb_spec x y); lia.\nQed.\n\nLemma nth_error_inds {ind u mind n} : n < #|ind_bodies mind| ->\n  nth_error (inds ind u mind.(ind_bodies)) n = Some (tInd (mkInd ind (#|mind.(ind_bodies)| - S n)) u).\nProof using Type.\n  unfold inds.\n  induction #|ind_bodies mind| in n |- *.\n  - intros hm. inv hm.\n  - intros hn. destruct n => /=. lia_f_equal.\n    eapply IHn0. lia.\nQed.\n\nLemma alli_subst_instance (Γ : context) u p :\n  (forall k t, p k t = p k t@[u]) ->\n  forall n,\n    alli (fun (k : nat) '{| decl_type := t |} => p k t) n Γ =\n    alli (fun (k : nat) '{| decl_type := t |} => p k t) n Γ@[u].\nProof using Type.\n  intros hp.\n  induction Γ; cbn => //.\n  move=> n. destruct a; cbn. f_equal. apply hp. apply IHΓ.\nQed.\n\nArguments firstorder_mutind : clear implicits.\n\nLemma plookup_env_lookup_env {Σ : global_env_ext} kn b :\n  plookup_env (firstorder_env Σ) kn = Some b ->\n  ∑ Σ' decl, lookup_env Σ kn = Some decl ×\n    strictly_extends_decls Σ' Σ ×\n    match decl with\n    | ConstantDecl _ => b = false\n    | InductiveDecl mind =>\n      b = firstorder_mutind (firstorder_env' (declarations Σ')) mind\n    end.\nProof using.\n  destruct Σ as [[univs Σ retro] ext].\n  induction Σ; cbn => //.\n  destruct a as [kn' d] => //. cbn.\n  case: eqb_specT.\n  * intros ->.\n    destruct d => //; cbn; rewrite eqb_refl => [=] <-;\n    exists {| universes := univs; declarations := Σ; retroknowledge := retro |}.\n    eexists; split => //. cbn. split => //.\n    red. split => //. eexists (_ :: []); cbn; trea.\n    eexists; split => //. cbn; split => //.\n    red. split => //. eexists (_ :: []); cbn; trea.\n  * intros neq h.\n    destruct d => //. cbn in h.\n    move: h. case: eqb_specT=> // _ h'.\n    unfold firstorder_env in IHΣ. cbn in IHΣ.\n    specialize (IHΣ h') as [Σ' [decl [Hdecl [ext' ?]]]].\n    exists Σ', decl; split => //. split => //.\n    destruct ext' as [equ [Σ'' eq]]. split => //.\n    eexists (_ :: Σ''). cbn in *. rewrite eq. trea.\n    move: h. cbn. apply neqb in neq. rewrite (negbTE neq).\n    intros h'; specialize (IHΣ h') as [Σ' [decl [Hdecl [ext' ?]]]].\n    exists Σ', decl; split => //. split => //.\n    destruct ext' as [equ [Σ'' eq]]. split => //.\n    eexists (_ :: Σ''). cbn in *. rewrite eq. trea.\nQed.\n\nLemma firstorder_spine_let {Σ : global_env_ext} {wfΣ : wf Σ} {Γ na a A B args T'} :\n  firstorder_spine Σ Γ (B {0 := a}) args T' ->\n  isType Σ Γ (tLetIn na a A B) ->\n  firstorder_spine Σ Γ (tLetIn na a A B) args T'.\nProof using Type.\n  intros H; depind H.\n  - constructor; auto.\n    etransitivity; tea. eapply cumulSpec_cumulAlgo_curry; tea; fvs.\n    eapply cumul_zeta.\n  - intros. econstructor. tea.\n    2:{ etransitivity; tea.\n        eapply cumulSpec_cumulAlgo_curry; tea; fvs.\n        eapply cumul_zeta. }\n    all:tea.\nQed.\n\nLemma instantiated_typing_spine_firstorder_spine {Σ : global_env_ext} {wfΣ : wf Σ} Γ T args T' :\n  instantiated (Σ := Σ) Γ T ->\n  arity_spine Σ Γ T args T' ->\n  isType Σ Γ T ->\n  firstorder_spine Σ Γ T args T'.\nProof using Type.\n  intros hi hsp.\n  revert hi; induction hsp; intros hi isty.\n  - constructor => //. now eapply isType_ws_cumul_pb_refl.\n  - econstructor; eauto.\n  - depelim hi. solve_discr. eapply firstorder_spine_let; eauto. eapply IHhsp => //.\n    now eapply isType_tLetIn_red in isty; pcuic.\n  - depelim hi. solve_discr.\n    specialize (i1 hd). specialize (IHhsp i1).\n    destruct (validity t) as [s Hs]. eapply inversion_mkApps in Hs as [? [hi _]].\n    eapply inversion_Ind in hi as [mdecl [idecl [decli [? ?]]]].\n    econstructor; tea. 2:{ eapply IHhsp. eapply isType_apply in isty; tea. }\n    now eapply isType_ws_cumul_pb_refl. eauto.\nQed.\n\nArguments firstorder_type : clear implicits.\n\n(* Lemma firstorder_env'_app x y :\n  firstorder_env' (x ++ y) = firstorder_env' x ++ firstorder_env' y.\nProof.\n  induction x in y |- *; cbn => //.\n  destruct a => //. destruct g => //. cbn. f_equal; eauto.\n  cbn; f_equal; eauto.\n  f_equal. f_equal. eauto. *)\n\nImport PCUICGlobalMaps.\n\nLemma fresh_global_app decls decls' kn :\n  fresh_global kn (decls ++ decls') ->\n  fresh_global kn decls /\\ fresh_global kn decls'.\nProof using Type.\n  induction decls => /= //.\n  - intros f; split => //.\n  - intros f; depelim f.\n    specialize (IHdecls f) as [].\n    split; eauto. constructor => //.\nQed.\n\nLemma plookup_env_Some_not_fresh g kn b :\n  plookup_env (firstorder_env' g) kn = Some b ->\n  ~ PCUICGlobalMaps.fresh_global kn g.\nProof using Type.\n  induction g; cbn => //.\n  destruct a => //. destruct g0 => //.\n  - cbn.\n    case: eqb_spec.\n    + move=> -> [=].\n      intros neq hf. depelim hf. now cbn in H.\n    + move=> neq hl hf.\n      apply IHg => //. now depelim hf.\n  - cbn.\n    case: eqb_spec.\n    + move=> -> [=].\n      intros neq hf. depelim hf. now cbn in H.\n    + move=> neq hl hf.\n      apply IHg => //. now depelim hf.\nQed.\n\nLemma plookup_env_extends {Σ Σ' : global_env} kn b :\n  strictly_extends_decls Σ' Σ ->\n  wf Σ ->\n  plookup_env (firstorder_env' (declarations Σ')) kn = Some b ->\n  plookup_env (firstorder_env' (declarations Σ)) kn = Some b.\nProof using Type.\n  intros [equ [Σ'' eq] eqr]. rewrite eq.\n  clear equ eqr. intros []. clear o.\n  rewrite eq in o0. clear eq. move: o0.\n  generalize (declarations Σ'). clear Σ'.\n  induction Σ''.\n  - cbn => //.\n  - cbn. destruct a => //. intros gs ong.\n    depelim ong. specialize (IHΣ'' _ ong).\n    destruct o as [f ? ? ?].\n    destruct g => //.\n    * intros hl. specialize (IHΣ'' hl).\n      eapply plookup_env_Some_not_fresh in hl.\n      cbn. case: eqb_spec.\n      + intros <-.  apply fresh_global_app in f as [].\n        contradiction.\n      + now intros neq.\n    * intros hl. specialize (IHΣ'' hl).\n      eapply plookup_env_Some_not_fresh in hl.\n      cbn. case: eqb_spec.\n      + intros <-. apply fresh_global_app in f as [].\n        contradiction.\n      + now intros neq.\nQed.\n\nLemma firstorder_mutind_ext {Σ Σ' : global_env_ext} m :\n  strictly_extends_decls Σ' Σ ->\n  wf Σ ->\n  firstorder_mutind (firstorder_env' (declarations Σ')) m ->\n  firstorder_mutind (firstorder_env Σ) m.\nProof using Type.\n  intros [equ [Σ'' eq]] wf.\n  unfold firstorder_env. rewrite eq.\n  unfold firstorder_mutind.\n  move/andP => [] -> /=. apply forallb_impl => x _.\n  unfold firstorder_oneind.\n  move/andP => [] h -> /=; rewrite andb_true_r.\n  eapply forallb_impl; tea => c _.\n  unfold firstorder_con.\n  eapply alli_impl => i [] _ _ ty.\n  unfold firstorder_type.\n  destruct decompose_app => // /=.\n  destruct t => //. destruct ind => //.\n  destruct plookup_env eqn:hl => //. destruct b => //.\n  eapply (plookup_env_extends (Σ:=Σ)) in hl. 2:split; eauto.\n  rewrite eq in hl. rewrite hl //. apply wf.\nQed.\n\nLemma firstorder_args {Σ : global_env_ext} {wfΣ : wf Σ} { mind cbody i n ui args u pandi oind} :\n  declared_constructor Σ (i, n) mind oind cbody ->\n  PCUICArities.typing_spine Σ [] (type_of_constructor mind cbody (i, n) ui) args (mkApps (tInd i u) pandi) ->\n  @firstorder_ind Σ (@firstorder_env Σ) i ->\n  firstorder_spine Σ [] (type_of_constructor mind cbody (i, n) ui) args (mkApps (tInd i u) pandi).\nProof using Type.\n  intros Hdecl Hspine Hind. revert Hspine.\n  unshelve edestruct @declared_constructor_inv with (Hdecl := Hdecl); eauto. exact weaken_env_prop_typing.\n\n  (* revert Hspine. *) unfold type_of_constructor.\n  erewrite cstr_eq. 2: eapply p.\n  rewrite <- it_mkProd_or_LetIn_app.\n  rewrite PCUICUnivSubst.subst_instance_it_mkProd_or_LetIn.\n  rewrite PCUICSpine.subst0_it_mkProd_or_LetIn. intros Hspine.\n\n  match goal with\n   | [ |- firstorder_spine _ _ ?T _ _ ] =>\n  assert (@instantiated Σ [] T) as Hi end.\n  { clear Hspine. destruct Hdecl as [[d1 d3] d2]. pose proof d3 as Hdecl.\n    unfold firstorder_ind in Hind.\n    unshelve epose proof (d1_ := declared_minductive_to_gen d1); eauto.\n    rewrite d1_ in Hind. solve_all. clear a.\n    move/andP: Hind => [indf H0].\n    eapply forallb_nth_error in H0 as H'.\n    erewrite d3 in H'.\n    unfold firstorder_oneind in H'. cbn in H'.\n    rtoProp.\n    eapply nth_error_forallb in H. 2: eauto.\n    unfold firstorder_con in H.\n    revert H. cbn.\n    unfold cstr_concl.\n    rewrite PCUICUnivSubst.subst_instance_mkApps subst_mkApps.\n    rewrite subst_instance_length app_length.\n    unfold cstr_concl_head. rewrite PCUICInductives.subst_inds_concl_head. now eapply nth_error_Some_length in Hdecl.\n    rewrite -app_length.\n    generalize (cstr_args cbody ++ ind_params mind)%list.\n    clear -wfΣ d1 indf H1 H0 Hdecl.\n    (* generalize conclusion to mkApps tInd args *)\n    intros c.\n    change (list context_decl) with context in c.\n    move: (map (subst (inds _ _ _) _) _).\n    intros args.\n    rewrite (alli_subst_instance _ ui (fun k t => firstorder_type _ #|ind_bodies mind| k t)).\n    { intros k t.\n      rewrite /firstorder_type.\n      rewrite -PCUICUnivSubstitutionConv.subst_instance_decompose_app /=.\n      destruct (decompose_app) => //=. destruct t0 => //. }\n    replace (List.rev c)@[ui] with (List.rev c@[ui]).\n    2:{ rewrite /subst_instance /subst_instance_context /map_context map_rev //. }\n    revert args.\n    induction (c@[ui]) using PCUICInduction.ctx_length_rev_ind => args.\n    - unfold cstr_concl, cstr_concl_head. cbn.\n      autorewrite with substu subst.\n      rewrite subst_context_nil. cbn -[subst0].\n      econstructor.\n    - rewrite rev_app_distr /=. destruct d as [na [b|] t].\n      + move=> /andP[] fot foΓ.\n        rewrite subst_context_app /=.\n        rewrite it_mkProd_or_LetIn_app /= /mkProd_or_LetIn /=.\n        constructor.\n        rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps /=. len.\n        rewrite -subst_app_context' // PCUICSigmaCalculus.subst_context_decompo.\n        cbn. len. eapply X. now len.\n        rewrite -subst_telescope_subst_context. clear -foΓ.\n        revert foΓ. move: (lift0 #|ind_bodies mind| _).\n        generalize 0.\n        induction (List.rev Γ) => //.\n        cbn -[subst_telescope]. intros n t.\n        destruct a; cbn -[subst_telescope].\n        move/andP => [] fo fol.\n        rewrite PCUICContextSubst.subst_telescope_cons /=.\n        apply/andP; split; eauto.\n        clear -fo.\n        move: fo.\n        unfold firstorder_type; cbn.\n        destruct (decompose_app decl_type) eqn:da.\n        rewrite (decompose_app_inv da) subst_mkApps /=.\n        destruct t0 => //=.\n        { move/andP => [/Nat.leb_le hn /Nat.ltb_lt hn'].\n          destruct (Nat.leb_spec n n0).\n          destruct (n0 - n) eqn:E. lia.\n          cbn. rewrite nth_error_nil /=.\n          rewrite decompose_app_mkApps //=.\n          apply/andP. split. apply Nat.leb_le. lia. apply Nat.ltb_lt. lia.\n          cbn.\n          rewrite decompose_app_mkApps //=.\n          apply/andP. split. apply Nat.leb_le. lia. apply Nat.ltb_lt. lia. }\n        { destruct ind => //. rewrite decompose_app_mkApps //. }\n      + move=> /andP[] fot foΓ.\n        rewrite subst_context_app /=.\n        rewrite it_mkProd_or_LetIn_app /= /mkProd_or_LetIn /=.\n        unfold firstorder_type in fot.\n        destruct ((PCUICAstUtils.decompose_app t)) eqn:E.\n        cbn in fot. destruct t0; try solve [inv fot].\n        * rewrite (decompose_app_inv E) /= subst_mkApps.\n          rewrite Nat.add_0_r in fot. eapply Nat.ltb_lt in fot.\n          cbn. rewrite nth_error_inds. lia. cbn.\n          econstructor.\n          unshelve epose proof (d1_ := declared_minductive_to_gen d1); eauto.\n          { rewrite /firstorder_ind d1_ /= /firstorder_mutind indf H0 //. }\n          intros x.\n          rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps /=. len.\n          rewrite -subst_app_context' // PCUICSigmaCalculus.subst_context_decompo.\n          cbn. len. eapply X. now len.\n          rewrite -subst_telescope_subst_context. clear -foΓ.\n          revert foΓ. generalize (lift0 #|ind_bodies mind| x).\n          generalize 0.\n          induction (List.rev Γ) => //.\n          cbn -[subst_telescope]. intros n t.\n          destruct a; cbn -[subst_telescope].\n          move/andP => [] fo fol.\n          rewrite PCUICContextSubst.subst_telescope_cons /=.\n          apply/andP; split; eauto.\n          clear -fo.\n          move: fo.\n          unfold firstorder_type; cbn.\n          destruct (decompose_app decl_type) eqn:da.\n          rewrite (decompose_app_inv da) subst_mkApps /=.\n          destruct t0 => //=.\n          { move/andP => [/Nat.leb_le hn /Nat.ltb_lt hn'].\n            destruct (Nat.leb_spec n n0).\n            destruct (n0 - n) eqn:E. lia.\n            cbn. rewrite nth_error_nil /=.\n            rewrite decompose_app_mkApps //=.\n            apply/andP. split. apply Nat.leb_le. lia. apply Nat.ltb_lt. lia.\n            cbn.\n            rewrite decompose_app_mkApps //=.\n            apply/andP. split. apply Nat.leb_le. lia. apply Nat.ltb_lt. lia. }\n          { destruct ind => //. rewrite decompose_app_mkApps //. }\n        * rewrite (decompose_app_inv E) subst_mkApps //=.\n          constructor. {\n             unfold firstorder_ind. destruct ind. cbn in *.\n             destruct plookup_env eqn:hp => //.\n             eapply plookup_env_lookup_env in hp as [Σ' [decl [eq [ext he]]]].\n             rewrite eq. destruct decl; subst b => //.\n             eapply (firstorder_mutind_ext (Σ' := (empty_ext Σ'))); tea. }\n          intros x. rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn subst_mkApps /=; len.\n          rewrite -subst_app_context' // PCUICSigmaCalculus.subst_context_decompo.\n          eapply X. now len. len.\n          rewrite -subst_telescope_subst_context. clear -foΓ.\n          revert foΓ. generalize (lift0 #|ind_bodies mind| x).\n          generalize 0.\n          induction (List.rev Γ) => //.\n          cbn -[subst_telescope]. intros n t.\n          destruct a; cbn -[subst_telescope].\n          move/andP => [] fo fol.\n          rewrite PCUICContextSubst.subst_telescope_cons /=.\n          apply/andP; split; eauto.\n          clear -fo.\n          move: fo.\n          unfold firstorder_type; cbn.\n          destruct (decompose_app decl_type) eqn:da.\n          rewrite (decompose_app_inv da) subst_mkApps /=.\n          destruct t0 => //=.\n          { move/andP => [/Nat.leb_le hn /Nat.ltb_lt hn'].\n            destruct (Nat.leb_spec n n0).\n            destruct (n0 - n) eqn:E. lia.\n            cbn. rewrite nth_error_nil /=.\n            rewrite decompose_app_mkApps //=.\n            apply/andP. split. apply Nat.leb_le. lia. apply Nat.ltb_lt. lia.\n            cbn.\n            rewrite decompose_app_mkApps //=.\n            apply/andP. split. apply Nat.leb_le. lia. apply Nat.ltb_lt. lia. }\n          { destruct ind => //. rewrite decompose_app_mkApps //. }\n  }\n  cbn in Hi |- *.\n  revert Hi Hspine. cbn.\n  unfold cstr_concl, cstr_concl_head.\n  autorewrite with substu subst.\n  rewrite subst_instance_length app_length.\n  rewrite PCUICInductives.subst_inds_concl_head. { cbn. destruct Hdecl as [[d1 d2] d3]. eapply nth_error_Some. rewrite d2. congruence. }\n  match goal with [ |- context[mkApps _ ?args]] => generalize args end.\n  intros args' Hi Spine.\n  eapply instantiated_typing_spine_firstorder_spine; tea.\n  now eapply typing_spine_arity_spine in Spine.\n  now eapply typing_spine_isType_dom in Spine.\nQed.\n\nLemma invert_cumul_it_mkProd_or_LetIn_Sort_Ind {Σ : global_env_ext} {wfΣ : wf Σ} {Γ Δ s i u args} :\n  Σ ;;; Γ ⊢ it_mkProd_or_LetIn Δ (tSort s) ≤ mkApps (tInd i u) args -> False.\nProof using Type.\n  induction Δ using PCUICInduction.ctx_length_rev_ind; cbn.\n  - eapply invert_cumul_sort_ind.\n  - rewrite it_mkProd_or_LetIn_app; destruct d as [na [b|] ty]; cbn.\n    * intros hl.\n      eapply ws_cumul_pb_LetIn_l_inv in hl.\n      rewrite /subst1 PCUICLiftSubst.subst_it_mkProd_or_LetIn in hl.\n      eapply H, hl. now len.\n    * intros hl. now eapply invert_cumul_prod_ind in hl.\nQed.\n\nLemma firstorder_value_spec (Σ:global_env_ext) t i u args mind :\n  wf Σ -> wf_local Σ [] ->\n   Σ ;;; [] |- t : mkApps (tInd i u) args ->\n  PCUICWcbvEval.value Σ t ->\n  lookup_env Σ (i.(inductive_mind)) = Some (InductiveDecl mind) ->\n  @firstorder_ind Σ (firstorder_env Σ) i ->\n  firstorder_value Σ [] t.\nProof using Type.\n  intros Hwf Hwfl Hty Hvalue.\n  revert mind i u args Hty.\n\n  induction Hvalue as [ t Hvalue | t args' Hhead Hargs IH ] using PCUICWcbvEval.value_values_ind;\n   intros mind i u args Hty Hlookup Hfo.\n  - destruct t; inversion_clear Hvalue.\n    + exfalso. eapply inversion_Sort in Hty as (? & ? & Hcumul); eauto.\n      now eapply invert_cumul_sort_ind in Hcumul.\n    + exfalso. eapply inversion_Prod in Hty as (? & ? & ? & ? & Hcumul); eauto.\n      now eapply invert_cumul_sort_ind in Hcumul.\n    + exfalso. eapply inversion_Lambda in Hty as (? & ? & ? & ? & Hcumul); eauto.\n      now eapply invert_cumul_prod_ind in Hcumul.\n    + exfalso. eapply inversion_Ind in Hty as (? & ? & ? & ? & ? & ?); eauto.\n      eapply PCUICInductives.declared_inductive_type in d.\n      rewrite d in w.\n      destruct (ind_params x ,,, ind_indices x0) as [ | [? [] ?] ? _] using rev_ind.\n      * cbn in w. now eapply invert_cumul_sort_ind in w.\n      * rewrite it_mkProd_or_LetIn_app in w. cbn in w.\n        eapply ws_cumul_pb_LetIn_l_inv in w.\n        rewrite /subst1 PCUICUnivSubst.subst_instance_it_mkProd_or_LetIn PCUICLiftSubst.subst_it_mkProd_or_LetIn in w.\n        now eapply invert_cumul_it_mkProd_or_LetIn_Sort_Ind in w.\n      * rewrite it_mkProd_or_LetIn_app in w. cbn in w.\n        now eapply invert_cumul_prod_ind in w.\n    + eapply inversion_Construct in Hty as Hty'; eauto.\n      destruct Hty' as (? & ? & ? & ? & ? & ? & ?).\n      assert (ind = i) as ->. {\n         eapply PCUICInductiveInversion.Construct_Ind_ind_eq with (args := []); eauto.\n      }\n      eapply firstorder_value_C with (args := []); eauto.\n      eapply firstorder_ind_propositional; eauto. sq. eauto.\n      apply declared_inductive_from_gen.\n      eapply (declared_constructor_inductive (ind := (i, _))).\n      unshelve eapply declared_constructor_to_gen; eauto.\n    + exfalso. eapply invert_fix_ind with (args := []) in Hty as [].\n      destruct unfold_fix as [ [] | ]; auto. eapply nth_error_nil.\n    + exfalso. eapply (typing_cofix_coind (args := [])) in Hty. red in Hty.\n      red in Hfo. unfold firstorder_ind in Hfo.\n      rewrite Hlookup in Hfo.\n      eapply andb_true_iff in Hfo as [Hfo _].\n      rewrite /check_recursivity_kind Hlookup in Hty.\n      apply eqb_eq in Hfo, Hty. congruence.\n    + eapply inversion_Prim in Hty as [prim_ty [cdecl [wf hp hdecl [s []] cum]]]; eauto.\n      now eapply invert_cumul_axiom_ind in cum; tea.\n  - destruct t; inv Hhead.\n    + exfalso. now eapply invert_ind_ind in Hty.\n    + apply inversion_mkApps in Hty as Hcon; auto.\n      destruct Hcon as (?&typ_ctor& spine).\n      apply inversion_Construct in typ_ctor as (?&?&?&?&?&?&?); auto.\n      pose proof d as [[d' _] _]. red in d'. cbn in *. unfold PCUICEnvironment.fst_ctx in *.\n      eapply @PCUICInductiveInversion.Construct_Ind_ind_eq with (mdecl := x0) in Hty as Hty'; eauto.\n      destruct Hty' as (([[[]]] & ?)  & ? & ? & ? & ? & _). subst.\n      econstructor; eauto.\n      2:{ eapply firstorder_ind_propositional; sq; eauto.\n          unshelve eapply declared_constructor_to_gen in d; eauto.\n          eapply declared_constructor_inductive in d.\n          apply declared_inductive_from_gen; eauto. }\n      eapply PCUICSpine.typing_spine_strengthen in spine. 3: eauto.\n      2: eapply PCUICInductiveInversion.declared_constructor_valid_ty; eauto.\n\n      eapply firstorder_args in spine; eauto.\n      clear c0 c1 e0 w Hty H0 Hargs.\n      induction spine.\n      * econstructor.\n      * destruct d as [d1 d2]. inv IH.\n        econstructor. inv X.\n        eapply H0. tea.\n        unshelve eapply declared_inductive_to_gen in d0; eauto.\n        exact i3.\n        inv X. eapply IHspine; eauto.\n     + exfalso.\n       destruct PCUICWcbvEval.cunfold_fix as [[] | ] eqn:E; inversion H.\n       eapply invert_fix_ind in Hty. auto.\n       unfold unfold_fix. unfold PCUICWcbvEval.cunfold_fix in E.\n       destruct (nth_error mfix idx); auto.\n       inversion E; subst; clear E.\n       eapply nth_error_None. lia.\n    + exfalso. eapply (typing_cofix_coind (args := args')) in Hty.\n      red in Hfo. unfold firstorder_ind in Hfo.\n      rewrite Hlookup in Hfo.\n      eapply andb_true_iff in Hfo as [Hfo _].\n      rewrite /check_recursivity_kind Hlookup in Hty.\n      apply eqb_eq in Hfo, Hty. congruence.\nQed.\n\nLemma firstorder_value_alpha Σ t t' :\n  t ≡α t' ->\n  firstorder_value Σ [] t ->\n  t = t'.\nProof.\n  intros Ha H. induction H in t', Ha |- using firstorder_value_inds.\n  eapply eq_term_upto_univ_napp_mkApps_l_inv in Ha as (? & ? & [] & ->).\n  invs e. repeat f_equal.\n  - now eapply eq_univ_make.\n  - revert x0 a. clear - H0. induction H0; intros; invs a; f_equal; eauto.\nQed.\n\nEnd cf.", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/pcuic/theories/PCUICFirstorder.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2136950108023673}}
{"text": "Require Export MinBFTprops2.\nRequire Export MinBFTinv.\nRequire Export MinBFTrun.\n\n\nSection MinBFTass_uniq.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext        }.\n  Context { minbft_context      : MinBFT_context      }.\n  Context { m_initial_keys      : MinBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys   }.\n  Context { usig_hash           : USIG_hash           }.\n  Context { minbft_auth         : MinBFT_auth         }.\n\n\n  Lemma ASSUMPTION_disseminate_unique_true :\n    forall (eo : EventOrdering), assume_eo eo ASSUMPTION_disseminate_unique.\n  Proof.\n    introv h; simpl in *; exrepnd; subst; GC; f_equal.\n    rewrite h0 in h1; ginv.\n\n    unfold disseminate_data in *; simpl in *; exrepnd.\n    rewrite h6 in *; ginv.\n    unfold M_byz_output_sys_on_event in *; simpl in *.\n\n    revert dependent o.\n    allrw; simpl.\n    introv dout1 out dout2.\n\n    unfold M_byz_output_ls_on_event in *; simpl in *.\n\n    remember (M_byz_run_ls_before_event (MinBFTlocalSys c3) e) as run; symmetry in Heqrun.\n    apply M_byz_run_ls_before_event_ls_is_minbft in Heqrun.\n    repndors; exrepnd; subst; simpl in *.\n\n    { unfold M_byz_run_ls_on_one_event in *.\n      unfold M_byz_run_ls_on_input in *.\n      unfold data_is_in_out, event2out in *.\n      remember (trigger e) as trig.\n      destruct trig; simpl in *; tcsp.\n\n      { apply in_flat_map in dout1; exrepnd.\n        apply in_flat_map in dout2; exrepnd.\n        unfold M_run_ls_on_input in *; simpl in *.\n        autorewrite with comp minbft in *; simpl in *.\n\n        Time minbft_dest_msg Case;\n          repeat (simpl in *; autorewrite with minbft in *; smash_minbft2);\n          repeat (repndors; subst; simpl in *; tcsp; ginv);\n            try (rename_hyp_with invalid_prepare invp);\n            try (rename_hyp_with invalid_commit invc);\n            try (complete (eapply data_is_owned_by_invalid_prepare_implies_false in invp; eauto; tcsp));\n            try (complete (unfold commit2ui_i in *; simpl in *;\n                           unfold ui_has_counter in *; simpl in *;\n                           unfold ui2counter in *; simpl in *; subst; simpl in *;\n                           eapply data_is_owned_by_invalid_commit_not_pil_implies_false in invc; eauto; tcsp)). }\n\n      { pose proof (snd_M_run_ls_on_trusted_incr_n_procs_eq (USIGlocalSys u) i) as z.\n        unfold LocalSystem in *; simpl in *; rewrite z in out; clear z.\n        rewrite rw_M_run_ls_on_trusted_USIGlocalSys in out.\n        destruct i as [cn i]; simpl in *; dest_cases w;[].\n        subst; simpl in *.\n        destruct i; repnd; repeat (simpl in *; repndors; ginv; tcsp). } }\n\n    { unfold M_byz_run_ls_on_one_event in *.\n      unfold M_byz_run_ls_on_input in *.\n      unfold data_is_in_out, event2out in *.\n      remember (trigger e) as trig.\n      destruct trig; simpl in *; tcsp;[].\n\n      pose proof (snd_M_run_ls_on_trusted_incr_n_procs_eq (USIGlocalSys u) i) as z.\n      unfold LocalSystem in *; simpl in *; rewrite z in out; clear z.\n      rewrite rw_M_run_ls_on_trusted_USIGlocalSys in out.\n      destruct i as [cn i]; simpl in *; dest_cases w;[].\n      subst; simpl in *.\n      destruct i; repnd; repeat (simpl in *; repndors; ginv; tcsp). }\n  Qed.\n  Hint Resolve ASSUMPTION_disseminate_unique_true : minbft.\n\nEnd MinBFTass_uniq.\n\n\nHint Resolve ASSUMPTION_disseminate_unique_true : minbft.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MinBFTass_uniq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2135808683690612}}
{"text": "\nRequire Import CpdtTactics.\nFrom Coq Require Import Arith.PeanoNat.\nFrom Coq Require Import Strings.String.\nFrom Coq Require Import Lists.List.\nImport ListNotations.\n\nRequire Import SyntaxRuntime.\n\nLocal Set Warnings \"-implicit-core-hint-db\".\n\nSet Implicit Arguments.\n\nLtac inv H := inversion H; subst; clear H.\n\nFixpoint keyset_to_keyset (t : term) :=\nmatch t with\n| t_ks_nil => []\n| t_ks_cons (t_result k) ks => k :: keyset_to_keyset ks\n| _ => []\nend.\n\nInductive frff : Type :=\n| FRf : term -> rstream -> frff.\nHint Constructors frff.\nInductive frtt : Type :=\n| FRt : term -> ostream -> frtt.\nHint Constructors frtt.\nReserved Notation \"frff '==>' frtt\" (at level 40).\n\nInductive fstep : frff -> frtt -> Prop :=\n| F_Emit_PFold : forall rs l f t ks,\n    value f ->\n    value t ->\n    value ks ->\n    FRf (t_emit_pfold l f t ks) rs ==> FRt (t_label l) [l ->> pfold f t (keyset_to_keyset ks)]\n| F_Emit_PMap : forall c b os rs l f ks,\n    c = C b os rs (t_emit_pmap l f ks) ->\n    value f ->\n    value ks ->\n    FRf (t_emit_pmap l f ks) rs ==> FRt (t_label l) [l ->> pmap f (keyset_to_keyset ks)]\n| F_Emit_Add : forall rs l k v,\n    FRf (t_emit_add l (t_result k) (t_result v)) rs ==> FRt (t_label l) [l ->> add k (t_result v)]\n| F_Claim : forall rs l v,\n    In (l ->>> v) rs ->\n    FRf (t_downarrow (t_label l)) rs ==> FRt (t_result v) []\n| F_Ctx_Downarrow : forall os rs t t',\n    FRf t rs ==> FRt t' os ->\n    FRf (t_downarrow t) rs ==> FRt (t_downarrow t') os\n| F_Ctx_Emit_PFold1 : forall os rs l t1 t2 t3 t1',\n    FRf t1 rs ==> FRt t1' os ->\n    FRf (t_emit_pfold l t1 t2 t3) rs ==> FRt (t_emit_pfold l t1' t2 t3) os\n| F_Ctx_Emit_PFold2 : forall os rs l t1 t2 t3 t2',\n    value t1 ->\n    FRf t2 rs ==> FRt t2' os ->\n    FRf (t_emit_pfold l t1 t2 t3) rs ==> FRt (t_emit_pfold l t1 t2' t3) os\n| F_Ctx_Emit_PFold3 : forall os rs l t1 t2 t3 t3',\n    value t1 ->\n    value t2 ->\n    FRf t3 rs ==> FRt t3' os ->\n    FRf (t_emit_pfold l t1 t2 t3) rs ==> FRt (t_emit_pfold l t1 t2 t3') os\n| F_Ctx_Emit_PMap1 : forall os rs l t1 t2 t1',\n    FRf t1 rs ==> FRt t1' os ->\n    FRf (t_emit_pmap l t1 t2) rs ==> FRt (t_emit_pmap l t1' t2) os\n| F_Ctx_Emit_PMap2 : forall os rs l t1 t2 t2',\n    value t1 ->\n    FRf t2 rs ==> FRt t2' os ->\n    FRf (t_emit_pmap l t1 t2) rs ==> FRt (t_emit_pmap l t1 t2') os\n| F_Ctx_Emit_Add1 : forall os rs l t1 t2 t1',\n    FRf t1 rs ==> FRt t1' os ->\n    FRf (t_emit_add l t1 t2) rs ==> FRt (t_emit_add l t1' t2) os\n| F_Ctx_Emit_Add2 : forall os rs l t1 t2 t2',\n    value t1 ->\n    FRf t2 rs ==> FRt t2' os ->\n    FRf (t_emit_add l t1 t2) rs ==> FRt (t_emit_add l t1 t2') os\n| F_App : forall rs x T t12 v2,\n    value v2 ->\n    FRf (t_app (t_abs x T t12) v2) rs ==> FRt (#[x:=v2]t12) []\n| F_App1 : forall os rs t1 t2 t1',\n    FRf t1 rs ==> FRt t1' os ->\n    FRf (t_app t1 t2) rs ==> FRt (t_app t1' t2) os\n| F_App2 : forall os rs t1 t2 t2',\n    value t1 ->\n    FRf t2 rs ==> FRt t2' os ->\n    FRf (t_app t1 t2) rs ==> FRt (t_app t1 t2') os\n| F_Ctx_KS1 : forall os rs k ks k',\n    FRf k rs ==> FRt k' os ->\n    FRf (t_ks_cons k ks) rs ==> FRt (t_ks_cons k' ks) os\n| F_Ctx_KS2 : forall os rs k ks ks',\n    value k ->\n    FRf ks rs ==> FRt ks' os ->\n    FRf (t_ks_cons k ks) rs ==> FRt (t_ks_cons k ks') os\n| F_Ctx_Node1 : forall os rs k p es k',\n    FRf k rs ==> FRt k' os ->\n    FRf (t_node k p es) rs ==> FRt (t_node k' p es) os\n| F_Ctx_Node2 : forall os rs k p es p',\n    value k ->\n    FRf p rs ==> FRt p' os ->\n    FRf (t_node k p es) rs ==> FRt (t_node k p' es) os\n| F_Ctx_Node3 : forall os rs k p es es',\n    value k ->\n    value p ->\n    FRf es rs ==> FRt es' os ->\n    FRf (t_node k p es) rs ==> FRt (t_node k p es') os\n| F_Fix : forall rs t T,\n    value t ->\n    FRf (t_fix T t) rs ==> FRt (t_abs \"x\" T (t_app (t_app t (t_fix T t)) (t_var \"x\"))) []\n| F_Ctx_Na1 : forall os rs t t',\n    FRf t rs ==> FRt t' os ->\n    FRf (t_na1 t) rs ==> FRt (t_na1 t') os\n| F_Ctx_Na2 : forall os rs t t',\n    FRf t rs ==> FRt t' os ->\n    FRf (t_na2 t) rs ==> FRt (t_na2 t') os\n| F_Ctx_Na3 : forall os rs t t',\n    FRf t rs ==> FRt t' os ->\n    FRf (t_na3 t) rs ==> FRt (t_na3 t') os\n| F_Na1 : forall rs t1 t2 t3,\n    value t1 ->\n    value t2 ->\n    value t3 ->\n    FRf (t_na1 (t_node t1 t2 t3)) rs ==> FRt t1 []\n| F_Na2 : forall rs t1 t2 t3,\n    value t1 ->\n    value t2 ->\n    value t3 ->\n    FRf (t_na2 (t_node t1 t2 t3)) rs ==> FRt t2 []\n| F_Na3 : forall rs t1 t2 t3,\n    value t1 ->\n    value t2 ->\n    value t3 ->\n    FRf (t_na3 (t_node t1 t2 t3)) rs ==> FRt t3 []\n| F_Ctx_Fix : forall os rs t t' T,\n    FRf t rs ==> FRt t' os ->\n    FRf (t_fix T t) rs ==> FRt (t_fix T t') os\nwhere \"frff ==> frtt\" := (fstep frff frtt).\nHint Constructors fstep.\n\nInductive lappears_free_in : label -> term -> Prop :=\n| lafi_label : forall l,\n    lappears_free_in l (t_label l)\n| lafi_app1 : forall x t1 t2,\n    lappears_free_in x t1 ->\n    lappears_free_in x (t_app t1 t2)\n| lafi_app2 : forall x t1 t2,\n    lappears_free_in x t2 ->\n    lappears_free_in x (t_app t1 t2)\n| lafi_abs : forall x y T11 t12,\n    lappears_free_in x t12 ->\n    lappears_free_in x (t_abs y T11 t12)\n| lafi_ks1 : forall x k ks,\n    lappears_free_in x k ->\n    lappears_free_in x (t_ks_cons k ks)\n| lafi_ks2 : forall x k ks,\n    lappears_free_in x ks ->\n    lappears_free_in x (t_ks_cons k ks)\n| lafi_node1 : forall x k p es,\n    lappears_free_in x k ->\n    lappears_free_in x (t_node k p es)\n| lafi_node2 : forall x k p es,\n    lappears_free_in x p ->\n    lappears_free_in x (t_node k p es)\n| lafi_node3 : forall x k p es,\n    lappears_free_in x es ->\n    lappears_free_in x (t_node k p es)\n| lafi_downarrow : forall x t,\n    lappears_free_in x t ->\n    lappears_free_in x (t_downarrow t)\n| lafi_emit_getpay1 : forall x l t1 t2 t3,\n    lappears_free_in x t1 ->\n    lappears_free_in x (t_emit_pfold l t1 t2 t3)\n| lafi_emit_getpay2 : forall x l t1 t2 t3,\n    lappears_free_in x t2 ->\n    lappears_free_in x (t_emit_pfold l t1 t2 t3)\n| lafi_emit_getpay3 : forall x l t1 t2 t3,\n    lappears_free_in x t3 ->\n    lappears_free_in x (t_emit_pfold l t1 t2 t3)\n| lafi_emit_pmap1 : forall x l t1 t2,\n    lappears_free_in x t1 ->\n    lappears_free_in x (t_emit_pmap l t1 t2)\n| lafi_emit_pmap2 : forall x l t1 t2,\n    lappears_free_in x t2 ->\n    lappears_free_in x (t_emit_pmap l t1 t2)\n| lafi_emit_add1 : forall x l t1 t2,\n    lappears_free_in x t1 ->\n    lappears_free_in x (t_emit_add l t1 t2)\n| lafi_emit_add2 : forall x l t1 t2,\n    lappears_free_in x t2 ->\n    lappears_free_in x (t_emit_add l t1 t2)\n| lafi_na1 : forall x t,\n    lappears_free_in x t ->\n    lappears_free_in x (t_na1 t)\n| lafi_na2 : forall x t,\n    lappears_free_in x t ->\n    lappears_free_in x (t_na2 t)\n| lafi_na3 : forall x t,\n    lappears_free_in x t ->\n    lappears_free_in x (t_na3 t)\n| lafi_fix : forall x t T,\n    lappears_free_in x t ->\n    lappears_free_in x (t_fix T t).\nHint Constructors lappears_free_in.\n\n\nDefinition pmap_compose f f' :=\nt_abs \"x\" Result (t_app f (t_app f' (t_var \"x\"))).\n\nReserved Notation \"c1 '-->' c2\" (at level 40).\n\n(* Fig 11: Operational Semantics *)\n\nInductive step : config -> config -> Prop :=\n(* frontend *)\n| S_Frontend : forall c b os rs t os' t',\n    c = C b os rs t ->\n    FRf t rs ==> FRt t' os' ->\n    c --> C b (os ++ os') rs t'\n(* to-graph *)\n| S_Empty : forall c os rs os' o l op term H,\n    c = C [] os rs term ->\n    os = o :: os' ->\n    o = l ->> op ->\n    not_add op ->\n    c --> C [] os' (l ->>> (@final op) H :: rs) term\n| S_First : forall c b os rs o os' b' n1 os1 op l term,\n    c = C b os rs term ->\n    os = o :: os' ->\n    b = (<<n1; os1>>)::b' ->\n    o = l ->> op ->\n    not_add op ->\n    c --> C (<<n1; (os1 ++ [o])>> :: b') os' rs term\n| S_Add : forall c b os rs os' l k v o term H,\n    c = C b os rs term ->\n    os = o :: os' ->\n    o = l ->> add k v ->\n    c --> C (<<(N k v t_ks_nil); []>> :: b) os' (l ->>> (@final (add k v)) H :: rs) term\n(* task *)\n| S_PMap : forall c b os rs b1 s1 s1' os1 os1' os1'' b2 k v es ks l term f,\n    c = C b os rs term ->\n    b = b1 ++ s1 :: b2 ->\n    s1 = <<N k v es; os1>> ->\n    os1 = l ->> pmap f ks :: os1'' ->\n    os1' = l ->> pmap f (remove Nat.eq_dec k ks) :: os1'' ->\n    s1' = <<N k (t_app f v) es; os1'>> ->\n    In k ks ->\n    c --> C (b1 ++ s1' :: b2) os rs term\n| S_PFold : forall c b os rs b1 s1 s1' os1 os1' os1'' b2 k t es f t' ks l term,\n    c = C b os rs term ->\n    b = b1 ++ s1 :: b2 ->\n    s1 = <<N k t es; os1>> ->\n    os1 = l ->> pfold f t' ks :: os1'' ->\n    os1' = l ->> pfold f (t_app (t_app f t) t') (remove Nat.eq_dec k ks) :: os1'' ->\n    s1' = <<N k t es; os1'>> ->\n    In k ks ->\n    c --> C (b1 ++ s1' :: b2) os rs term\n| S_Last : forall c b os rs l n1 os1 os1' op b1 k term H,\n    c = C b os rs term ->\n    b = b1 ++ [<<n1; os1>>] ->\n    os1 = l ->> op :: os1' ->\n    k = getKey n1 ->\n    not (In k (target op)) ->\n    c --> C (b1 ++ [<<n1; os1'>>]) os (l ->>> (@final op) H :: rs) term\n(* Fig 12: Temporal Locality Optimization *)\n| S_FusePMap : forall c b n b1 b2 os os1 os2 rs term f f' ks l l' H,\n    c = C b os rs term ->\n    b = b1 ++ <<n; os1 ++ l ->> pmap f ks :: l' ->> pmap f' ks :: os2>> :: b2 ->\n    c --> C (b1 ++ <<n; os1 ++ l' ->> pmap (pmap_compose f' f) ks :: os2>> :: b2) os (l ->>> (@final (pmap f ks)) H :: rs) term\n| S_SwapReads : forall c b n b1 b2 os os1 os2 rs term l l' f f' ks ks' t t',\n    c = C b os rs term ->\n    b = b1 ++ <<n; os1 ++ l ->> pfold f t ks :: l' ->> pfold f' t' ks' :: os2>> :: b2 ->\n    not (lappears_free_in l f') ->\n    not (lappears_free_in l t') ->\n    c --> (C (b1 ++ <<n; os1 ++ l' ->> pfold f' t' ks' :: l ->> pfold f t ks :: os2>> :: b2) os rs term)\n| S_Prop : forall c b os rs n1 n2 os1 os2 b1 b2 l op term,\n    c = C b os rs term ->\n    ~ (In (getKey n1) (target op)) ->\n    b = b1 ++ <<n1; l ->> op :: os1>> :: <<n2; os2>> :: b2 ->\n    c --> C (b1 ++ <<n1; os1>> :: <<n2; os2 ++ [l ->> op]>> :: b2) os rs term\n(* task *)\n| S_Load : forall c b os0 rs0 term0 b1 b2 k t es t' os,\n   c = C b os0 rs0 term0 ->\n   b = b1 ++ <<N k t es; os>> :: b2 ->\n   FRf t rs0 ==> FRt t' [] ->\n   c --> C (b1 ++ <<N k t' es; os>> :: b2) os0 rs0 term0\n| S_LoadPFold : forall c b b' os0 rs0 term0 l b1 b2 k t es f t1 t1' ks os os',\n   c = C b os0 rs0 term0 ->\n   b = b1 ++ <<N k t es; os ++ l ->> pfold f t1 ks :: os'>> :: b2 ->\n   FRf t1 rs0 ==> FRt t1' [] ->\n   b' = b1 ++ <<N k t es; os ++ l ->> pfold f t1' ks :: os'>> :: b2 ->\n   c --> C b' os0 rs0 term0\nwhere \"c1 --> c2\" := (step c1 c2).\nHint Constructors step.\n\nInductive star {A : Type} (R : A -> A -> Prop) : nat -> A -> A -> Prop :=\n| Zero : forall x, star R 0 x x\n| Step : forall x y, R x y -> forall n z, star R n y z -> star R (S n) x z.\nHint Constructors star.\n\nNotation \"c1 '-->*[' n ']' c2\" := (star step n c1 c2) (at level 40).\n\nLemma star_zero :\n  forall {A : Type} (R : A -> A -> Prop) x y,\n  star R 0 x y ->\n  x = y.\nProof using.\n  intros.\n  inversion H; subst; clear H; crush.\nQed.\nHint Immediate star_zero.\n\nLemma one_star :\n  forall {A : Type} R (x:A) y,\n  star R 1 x y <->\n  R x y.\nProof using.\n  split; intros.\n  - inv H.\n    apply star_zero in H2; subst.\n    assumption.\n  - eapply Step.\n    instantiate (1:=y).\n    assumption.\n    apply Zero.\nQed.\nHint Immediate one_star.\n\nLemma star_zero_exists :\n  forall {A : Type} (R : A -> A -> Prop) x,\n  exists m, star R m x x.\nProof using.\n  intros.\n  apply ex_intro with (0).\n  crush.\nQed.\nHint Immediate star_zero_exists.\n\nLemma star_trans :\n  forall {A : Type} (R : A -> A -> Prop) x y z m n,\n  star R m x y ->\n  star R n y z ->\n  star R (m+n) x z.\nProof using.\n  intros.\n  generalize dependent z.\n  generalize dependent x.\n  generalize dependent y.\n  generalize dependent n.\n  induction m; induction n; intros.\n  - crush.\n    apply star_zero in H; subst; crush.\n  - simpl.\n    apply star_zero in H; subst; crush.\n  - apply star_zero in H0; subst.\n    assert (S m = S m + 0) by crush.\n    rewrite H0 in H.\n    crush.\n  - simpl in *.\n    inversion H; subst; clear H.\n    inversion H0; subst; clear H0.\n    eapply Step.\n    instantiate (1:=y0).\n    assumption.\n    eapply IHm.\n    instantiate (1:=y).\n    assumption.\n    eapply Step.\n    instantiate (1:=y1).\n    assumption.\n    assumption.\nQed.\nHint Resolve star_trans.\n\nDefinition backend_keys (b : backend) :=\nmap (fun s => getKey (get_node s)) b.\nHint Unfold backend_keys.\n\nDefinition ostream_keys (os : ostream) :=\nList.concat (map (fun o => match o with\n             | l ->> add k _ => [k]\n             | _ => []\n           end) os).\nHint Unfold ostream_keys.\n\nDefinition config_keys (c : config) :=\nmatch c with\n| C b os rs term => List.concat [backend_keys b; ostream_keys os]\nend.\nHint Unfold config_keys.\n\nDefinition ostream_labels (os : ostream) :=\nmap (fun o => match o with l ->> _ => l end) os.\nHint Unfold ostream_labels.\n\nLemma ostream_labels_dist :\n  forall os1 os2,\n  ostream_labels (os1 ++ os2) = ostream_labels os1 ++ ostream_labels os2.\nProof using.\n induction os1; intros; crush.\nQed.\nHint Rewrite ostream_labels_dist.\n\nLemma cons_equal :\n  forall {A: Type} (x : A) y xs ys,\n  x = y ->\n  xs = ys ->\n  x :: xs = y :: ys.\nProof using.\n  crush.\nQed.\n\nLemma ostream_keys_dist :\n  forall os1 os2,\n  ostream_keys (os1 ++ os2) = ostream_keys os1 ++ ostream_keys os2.\nProof using.\n  induction os1; intros.\n  - crush.\n  - simpl.\n    destruct a; destruct o.\n    + unfold ostream_keys.\n      simpl.\n      apply IHos1.\n    + unfold ostream_keys.\n      simpl.\n      apply cons_equal; crush.\n      apply IHos1.\n    + unfold ostream_keys.\n      simpl.\n      eauto.\nQed.\nHint Rewrite ostream_labels_dist.\n\nLemma backend_keys_dist :\n  forall b1 b2,\n  backend_keys (b1 ++ b2) = backend_keys b1 ++ backend_keys b2.\nProof using.\n induction b1; intros; crush.\nQed.\nHint Rewrite backend_keys_dist.\n\nDefinition rstream_labels (rs : rstream) :=\nmap (fun r => match r with l ->>> _ => l end) rs.\nHint Unfold rstream_labels.\n\nLemma rstream_labels_dist :\n  forall rs1 rs2,\n  rstream_labels (rs1 ++ rs2) = rstream_labels rs1 ++ rstream_labels rs2.\nProof using.\n induction rs1; intros; crush.\nQed.\nHint Rewrite rstream_labels_dist.\n\n\nDefinition backend_labels (b : backend) :=\nList.concat (map (fun s => ostream_labels (get_ostream s)) b).\nHint Unfold backend_labels.\n\nLemma backend_labels_dist :\n  forall b1 b2,\n  backend_labels (b1 ++ b2) = backend_labels b1 ++ backend_labels b2.\nProof using.\n  induction b1; intros; intuition.\n  simpl.\n  unfold backend_labels in *.\n  simpl.\n  crush.\nQed.\nHint Rewrite backend_labels_dist.\n\nDefinition config_labels (c : config) :=\nmatch c with\n| C b os rs term => List.concat [backend_labels b; ostream_labels os; rstream_labels rs]\nend.\nHint Unfold config_labels.\n\nInductive distinct (A : Type) : list A -> Prop :=\n| distinct_empty : distinct []\n| distinct_one : forall x, distinct [x]\n| distinct_many : forall xs x xs', xs = x :: xs' -> not (In x xs') -> distinct xs' -> distinct xs.\nHint Constructors distinct.\n\nLemma distinct_remove :\n  forall A (x : A) xs,\n  distinct (x :: xs) ->\n  distinct xs /\\ not (In x xs).\nProof using.\n  intros.\n  inversion H; crush.\nQed.\nHint Resolve distinct_remove.\n\nLemma not_in_app_comm :\n  forall A (x : A) xs ys,\n  ~ In x (xs ++ ys) ->\n  ~ In x (ys ++ xs).\nProof using.\n  unfold not in *.\n  intros.\n  apply List.in_app_or in H0.\n  inversion H0; crush.\nQed.\nHint Resolve not_in_app_comm.\n\nLemma not_in_remove :\n  forall A (x : A) y xs,\n  ~ In x (y :: xs) ->\n  ~ In x xs /\\ x <> y.\nProof using.\n  induction xs; crush.\nQed.\nHint Resolve not_in_remove.\n\nLemma distinct_rotate_back_one :\n  forall A (x : A) xs,\n  distinct (x :: xs) ->\n  distinct (xs ++ [x]).\nProof using.\n  induction xs; intros; crush.\n  apply distinct_remove in H.\n  destruct H.\n  eapply distinct_many.\n  instantiate (1:=xs ++ [x]).\n  instantiate (1:=a).\n  crush.\n  crush.\n  apply List.in_app_iff in H1.\n  destruct H1.\n  - inv H; crush.\n  - inv H0; crush.\n  - apply IHxs.\n    apply List.not_in_cons in H0.\n    destruct H0.\n    inv H; crush.\n    eapply distinct_many.\n    instantiate (1:=xs').\n    instantiate (1:=x).\n    crush.\n    crush.\n    crush.\nQed.\n\nLemma distinct_rotate_back :\n  forall A (x : A) xs ys,\n  distinct (xs ++ x :: ys) ->\n  distinct (xs ++ ys ++ [x]).\nProof using.\n  induction xs; intros.\n  - simpl.\n    apply distinct_rotate_back_one.\n    crush.\n  - simpl in *.\n    apply distinct_remove in H.\n    eapply distinct_many.\n    instantiate (1:=(xs ++ ys ++ [x])).\n    instantiate (1:=a).\n    crush.\n    destruct H.\n    crush.\n    assert (In a (xs ++ x :: ys)).\n    apply List.in_app_iff in H1.\n    destruct H1.\n    crush.\n    apply List.in_app_iff in H1.\n    destruct H1.\n    crush.\n    crush.\n    crush.\n    apply IHxs.\n    crush.\nQed.\n\nLemma distinct_rotate :\n  forall A (x : A) xs ys,\n  distinct (x :: xs ++ ys) ->\n  distinct (xs ++ x :: ys).\nProof using.\n  induction xs; intros; crush.\n  apply distinct_remove in H; destruct H.\n  apply distinct_remove in H; destruct H.\n  crush.\n  assert (distinct (x :: xs ++ ys)).\n  eapply distinct_many; crush.\n  apply IHxs in H0.\n  apply distinct_many with (x := a) (xs' := xs ++ x :: ys); crush.\n  apply List.in_app_or in H4; destruct H4; crush.\nQed.\nHint Resolve distinct_rotate.\n\nLemma distinct_rotate_rev :\n  forall A (x : A) xs ys,\n  distinct (xs ++ x :: ys) ->\n  distinct (x :: xs ++ ys).\nProof using.\n  induction xs; intros; crush.\n  apply distinct_remove in H; destruct H.\n  apply IHxs in H.\n  apply distinct_remove in H; destruct H.\n  assert (distinct (a :: xs ++ ys)).\n  eapply distinct_many; crush.\n  apply List.in_app_or in H2; destruct H2; crush.\n  apply distinct_many with (x := x) (xs' := a :: xs ++ ys); crush.\nQed.\nHint Resolve distinct_rotate.\n\nLemma distinct_app_comm :\n  forall A (xs : list A) ys,\n  distinct (xs ++ ys) ->\n  distinct (ys ++ xs).\nProof using.\n  induction xs; intros ys Ih.\n  - rewrite List.app_nil_r; assumption.\n  - simpl in Ih.\n    apply distinct_remove in Ih.\n    destruct Ih.\n    apply IHxs in H.\n    apply not_in_app_comm in H0.\n    apply distinct_rotate.\n    eapply distinct_many; crush.\nQed.\nHint Resolve distinct_app_comm.\n\nLemma distinct_remove_middle :\n  forall A (x : A) xs ys,\n  distinct (xs ++ [x] ++ ys) ->\n  distinct (xs ++ ys).\nProof using.\n  intros.\n  assert ([x] ++ ys = x :: ys) by crush.\n  rewrite H0 in H.\n  apply distinct_rotate_rev in H.\n  apply distinct_remove in H.\n  crush.\nQed.\nHint Resolve distinct_remove_middle.\n\nLemma in_empty :\n  forall A (x : A),\n  In x [] -> False.\nProof using.\n  intros A.\n  unfold In.\n  auto.\nQed.\nHint Immediate in_empty.\n\nLemma distinct_rotate_front :\n  forall A (x : A) y xs,\n  distinct (x :: y :: xs) ->\n  distinct (y :: x :: xs).\nProof using.\n  intros.\n  assert (x :: y :: xs = [x] ++ y :: xs) by crush.\n  rewrite H0 in H.\n  clear H0.\n  apply distinct_rotate_rev in H.\n  crush.\nQed.\n\nLemma distinct_concat :\n  forall A (xs : list A) ys,\n  distinct (xs ++ ys) ->\n  distinct xs /\\ distinct ys.\nProof using.\n  intros A xs.\n  induction xs; intros.\n  - simpl in H. split; crush.\n  - split. simpl in H. eapply distinct_many. crush.\n    inversion H.\n    * intuition.\n      assert (xs = []).\n      destruct xs.\n      + reflexivity.\n      + inversion H2.\n      + crush.\n    * assert (a = x) by crush.\n      crush.\n    * apply distinct_remove in H.\n      destruct H.\n      eapply IHxs in H.\n      inversion H.\n      assumption.\n    * simpl in H.\n      apply distinct_remove in H.\n      destruct H.\n      eapply IHxs in H.\n      inversion H.\n      assumption.\nQed.\nHint Resolve distinct_concat.\n\nLemma distinct_center :\n  forall {A : Type} (xs : list A) x ys xs' ys' l l',\n  distinct l ->\n  l = l' ->\n  l = xs ++ x :: ys ->\n  l = xs' ++ x :: ys' ->\n  xs = xs' /\\ ys = ys'.\nProof using.\n  induction xs; intros.\n  - simpl in *.\n    subst.\n    destruct xs'.\n    + crush.\n    + inv H2.\n      rewrite List.app_comm_cons in H.\n      apply distinct_rotate_rev in H.\n      inversion H; subst.\n      inv H0.\n      crush.\n  - simpl in *.\n    subst.\n    destruct xs'.\n    + simpl in H2.\n      rewrite List.app_comm_cons in H.\n      apply distinct_rotate_rev in H.\n      inv H2.\n      inversion H; subst.\n      inv H0.\n      crush.\n    + simpl in *.\n      inv H2.\n      eapply IHxs in H3; eauto.\n      * destruct H3; split; eauto; crush.\n      * inversion H; crush.\nQed.\n", "meta": {"author": "philipdexter", "repo": "ourlang", "sha": "b7421f5790bb829381bf737dbd9210d977d0aca5", "save_path": "github-repos/coq/philipdexter-ourlang", "path": "github-repos/coq/philipdexter-ourlang/ourlang-b7421f5790bb829381bf737dbd9210d977d0aca5/OperationalSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.2135808561356787}}
{"text": "Require Import Verdi.Verdi.\nRequire Import Verdi.VarD.\nRequire Import Verdi.PartialMapSimulations.\nRequire Import Cheerios.Cheerios.\nRequire Import VerdiRaft.Raft.\n\nRequire Import VerdiRaft.CommonDefinitions.\nRequire Import VerdiRaft.Linearizability.\nRequire Import VerdiRaft.RaftLinearizableProofs.\n\nRequire Import VerdiRaft.EndToEndLinearizability.\nRequire Import Verdi.SerializedMsgParamsCorrect.\n\nRequire Import VerdiRaft.VarDRaftSerialized.\n\nSection VarDSerializedCorrect.\n  Variable n : nat.\n\n  Instance raft_params : RaftParams VarD.vard_base_params :=\n    raft_params n.\n\n  Instance base_params : BaseParams :=\n    transformed_base_params n.\n\n  Instance multi_params : MultiParams _ :=\n    transformed_multi_params n.\n\n  Instance failure_params : FailureParams _ :=\n    transformed_failure_params n.\n\n  Lemma correct_input_correct_filterMap_trace_non_empty_out :\n    forall tr,\n      input_correct tr ->\n      input_correct (filterMap trace_non_empty_out tr).\n  Proof using.\n    induction tr; simpl; intro H_inp; auto.\n    destruct a, s; simpl.\n    - assert (H_inp': input_correct tr).\n        intros client id i0 i1 h h' H_in H_in'.\n        eapply H_inp; right; eauto.\n      concludes.\n      intros client id i0 i1 h h' H_in H_in'.\n      simpl in *.\n      break_or_hyp; break_or_hyp.\n      * find_injection; find_injection; auto.\n      * find_injection.\n        eapply H_inp.\n        + right.\n          find_apply_lem_hyp In_filterMap.\n          break_exists_name e.\n          break_and.\n          destruct e, s; simpl in *; [ find_injection; eauto | destruct l; congruence ].\n        + left; eauto.\n      * find_injection.\n        eapply H_inp.\n        + left; eauto.\n        + right.\n          find_apply_lem_hyp In_filterMap.\n          break_exists_name e.\n          break_and.\n          destruct e, s; simpl in *; [ find_injection; eauto | destruct l; congruence ].\n       * eapply IHtr; eauto.\n     - destruct l.\n       * apply IHtr.\n         intros client id i0 i1 h h' H_in H_in'.\n         eapply H_inp; right; eauto.\n       * assert (H_inp': input_correct tr).\n           intros client id i0 i1 h h' H_in H_in'.\n           eapply H_inp; right; eauto.\n         concludes.\n         intros client id i0 i1 h h' H_in H_in'.\n         simpl in *.\n         break_or_hyp; [ find_inversion | idtac ].\n         break_or_hyp; [ find_inversion | idtac ].\n         eapply IHtr; eauto.\n  Qed.\n\n  Lemma correct_filterMap_trace_non_empty_out_input_correct :\n    forall tr,\n      input_correct (filterMap trace_non_empty_out tr) ->\n      input_correct tr.\n  Proof using.\n    induction tr; simpl; auto.\n    destruct a, s; simpl; intro H_inp.\n    - assert (H_inp': input_correct (filterMap trace_non_empty_out tr)).\n        intros client id i0 i1 h h' H_in H_in'.\n        eapply H_inp; right; eauto.\n      concludes.\n      intros client id i0 i1 h h' H_in H_in'.\n      simpl in *.\n      break_or_hyp; break_or_hyp.\n      * find_injection; find_injection; auto.\n      * find_injection.\n        eapply H_inp; [ idtac | left; eauto ].\n        right.\n        eapply filterMap_In; eauto.\n        simpl; eauto.\n      * find_injection.\n        eapply H_inp; [ left; eauto | idtac ].\n        right.\n        eapply filterMap_In; eauto.\n        simpl; eauto.\n      * eapply IHtr; eauto.\n    - destruct l.\n      * intros client id i0 i1 h h' H_in H_in'.\n        simpl in *.\n        break_or_hyp; [ find_inversion | idtac ].\n        break_or_hyp; [ find_inversion | idtac ].\n        eapply IHtr; eauto.\n      * assert (H_inp': input_correct (filterMap trace_non_empty_out tr)).\n          intros client id i0 i1 h h' H_in H_in'.\n          eapply H_inp; right; eauto.\n        concludes.\n        intros client id i0 i1 h h' H_in H_in'.\n        simpl in *.\n        break_or_hyp; [ find_inversion | idtac ].\n        break_or_hyp; [ find_inversion | idtac ].\n        eapply IHtr; eauto.\n  Qed.\n\n  Lemma input_correct_filterMap_trace_non_empty_out :\n    forall tr tr',\n      input_correct tr ->\n      filterMap trace_non_empty_out tr = filterMap trace_non_empty_out tr' ->\n      input_correct tr'.\n  Proof using.\n    intros tr tr' H_in H_eq.\n    apply correct_filterMap_trace_non_empty_out_input_correct.\n    rewrite <- H_eq.\n    apply correct_input_correct_filterMap_trace_non_empty_out; auto.\n  Qed.\n\n  Lemma get_input_tr_filterMap_trace_non_empty_out :\n    forall tr,\n      get_input tr = get_input (filterMap trace_non_empty_out tr).\n  Proof using.\n    induction tr; simpl; auto.\n    destruct a, s; simpl.\n    - rewrite IHtr; auto.\n    - destruct l; auto.\n  Qed.\n\n  Lemma get_output_tr_filterMap_trace_non_empty_out :\n    forall tr,\n      get_output tr = get_output (filterMap trace_non_empty_out tr).\n  Proof using.\n    induction tr; simpl; auto.\n    destruct a, s; simpl.\n    - rewrite IHtr; auto.\n    - destruct l; auto.\n      rewrite IHtr; auto.\n  Qed.\n\n  Lemma exported_filterMap_trace_non_empty_out : \n    forall tr tr' l tr1,\n      exported (get_input tr') (get_output tr') l tr1 ->\n      filterMap trace_non_empty_out tr = filterMap trace_non_empty_out tr' ->\n      exported (get_input tr) (get_output tr) l tr1.\n  Proof using.\n    intros tr tr' l tr1 H_exp H_eq.\n    rewrite get_input_tr_filterMap_trace_non_empty_out in H_exp.\n    rewrite get_output_tr_filterMap_trace_non_empty_out in H_exp.\n    rewrite <- H_eq in H_exp.\n    rewrite <- get_input_tr_filterMap_trace_non_empty_out in H_exp.\n    rewrite <- get_output_tr_filterMap_trace_non_empty_out in H_exp.\n    auto.\n  Qed.\n\n  Lemma import_exported_filterMap_trace_non_empty_out : \n    forall tr,\n      import tr = import (filterMap trace_non_empty_out tr).\n  Proof using.\n    induction tr; simpl; auto.\n    destruct a, s; simpl.\n    - rewrite IHtr; auto.\n    - rewrite IHtr.\n      destruct l; auto.\n  Qed.\n\n  Lemma equivalent_filterMap_trace_non_empty_out :\n    forall tr tr' l,\n      equivalent key (import tr') l ->\n      filterMap trace_non_empty_out tr = filterMap trace_non_empty_out tr' ->\n      equivalent key (import tr) l.\n  Proof using.\n    intros tr tr' l H_equ H_eq.\n    rewrite import_exported_filterMap_trace_non_empty_out.\n    rewrite H_eq.\n    rewrite <- import_exported_filterMap_trace_non_empty_out.\n    auto.\n  Qed.\n\n  Theorem vard_raft_serialized_linearizable :\n    forall failed net tr,\n      input_correct tr ->\n      step_failure_star step_failure_init (failed, net) tr ->\n      exists l tr1 st,\n        equivalent _ (import tr) l /\\\n        exported (get_input tr) (get_output tr) l tr1 /\\\n        step_1_star init st tr1.\n  Proof using.\n    intros failed net tr H_inp H_step.\n    apply step_failure_deserialized_simulation_star in H_step.\n    break_exists_name tr'.\n    break_and.\n    find_apply_lem_hyp raft_linearizable.\n    - break_exists_name l.\n      break_exists_name tr1.\n      break_exists_name st.\n      break_and.\n      exists l, tr1, st.\n      split.\n      * eapply equivalent_filterMap_trace_non_empty_out; eauto.\n      * split; auto. eapply exported_filterMap_trace_non_empty_out; eauto.\n    - eapply input_correct_filterMap_trace_non_empty_out; eauto.\n  Qed.\nEnd VarDSerializedCorrect.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/systems/VarDRaftSerializedCorrect.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213070736461, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.21358085613567868}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nFrom Fairness Require Import ITreeLib IProp IPM ModSim ModSimNat PCM.\nFrom Fairness Require PCMLarge.\nRequire Import Program.\n\nSet Implicit Arguments.\n\n\nSection SIM.\n  Context `{Σ: GRA.t}.\n\n  Variable state_src: Type.\n  Variable state_tgt: Type.\n\n  Variable ident_src: ID.\n  Variable ident_tgt: ID.\n\n  Variable wf_src: WF.\n\n  Let srcE := programE ident_src state_src.\n  Let tgtE := programE ident_tgt state_tgt.\n\n  Let shared_rel := TIdSet.t -> (@imap ident_src wf_src) -> (@imap (sum_tid ident_tgt) nat_wf) -> state_src -> state_tgt -> iProp.\n\n  Definition liftI (R: shared_rel): (TIdSet.t *\n                               (@imap ident_src wf_src) *\n                               (@imap (sum_tid ident_tgt) nat_wf) *\n                               state_src *\n                               state_tgt) -> Σ -> Prop :=\n        fun '(ths, im_src, im_tgt, st_src, st_tgt) r_shared =>\n          R ths im_src im_tgt st_src st_tgt r_shared.\n\n  Let liftRR R_src R_tgt (RR: R_src -> R_tgt -> shared_rel):\n    R_src -> R_tgt -> Σ -> (TIdSet.t *\n                              (@imap ident_src wf_src) *\n                              (@imap (sum_tid ident_tgt) nat_wf) *\n                              state_src *\n                              state_tgt) -> Prop :=\n        fun r_src r_tgt r_ctx '(ths, im_src, im_tgt, st_src, st_tgt) =>\n          exists r,\n            (<<WF: URA.wf (r ⋅ r_ctx)>>) /\\\n              RR r_src r_tgt ths im_src im_tgt st_src st_tgt r.\n\n  Variable tid: thread_id.\n  Variable I: shared_rel.\n\n  Let rel := (forall R_src R_tgt (Q: R_src -> R_tgt -> shared_rel), bool -> bool -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel).\n\n  Let gf := (fun r => pind9 ((@__lsim (to_LURA Σ)) _ _ _ _ _ _ (liftI I) tid r) top9).\n  Let gf_mon: monotone9 gf.\n  Proof.\n    eapply lsim_mon.\n  Qed.\n  Hint Resolve gf_mon: paco.\n\n  Variant unlift (r: rel):\n    forall R_src R_tgt (RR: R_src -> R_tgt -> Σ ->\n                            (TIdSet.t *\n                               (@imap ident_src wf_src) *\n                               (@imap (sum_tid ident_tgt) nat_wf) *\n                               state_src *\n                               state_tgt) -> Prop),\n      bool -> bool -> Σ -> itree srcE R_src -> itree tgtE R_tgt ->\n      (TIdSet.t *\n         (@imap ident_src wf_src) *\n         (@imap (sum_tid ident_tgt) nat_wf) *\n         state_src *\n         state_tgt) -> Prop :=\n    | unlift_intro\n        R_src R_tgt Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt r_ctx r_own\n        (REL: r R_src R_tgt Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt r_own)\n        (WF: URA.wf (r_own ⋅ r_ctx))\n      :\n      unlift r (liftRR Q) ps pt r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  .\n\n  Program Definition isim: rel -> rel -> rel :=\n    fun\n      r g\n      R_src R_tgt Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt =>\n      iProp_intro\n        (fun r_own =>\n           forall r_ctx (WF: URA.wf (r_own ⋅ r_ctx)),\n             gpaco9 gf (cpn9 gf) (@unlift r) (@unlift g) _ _ (liftRR Q) ps pt r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)) _.\n  Next Obligation.\n  Proof.\n    ii. ss. eapply H.\n    eapply URA.wf_extends; eauto. eapply URA.extends_add; eauto.\n  Qed.\n\n  Tactic Notation \"muclo\" uconstr(H) :=\n    eapply gpaco9_uclo; [auto with paco|apply H|].\n\n  Lemma isim_upd r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (#=> (isim r g Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt))\n      (isim r g Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    rr in H. autorewrite with iprop in H.\n    ii. hexploit H; eauto. i. des. eauto.\n  Qed.\n\n  Global Instance isim_elim_upd\n         r g R_src R_tgt\n         (Q: R_src -> R_tgt -> shared_rel)\n         ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt p\n         P\n    :\n    ElimModal True p false (#=> P) P (isim r g Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt) (isim r g Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt).\n  Proof.\n    unfold ElimModal. rewrite bi.intuitionistically_if_elim.\n    i. iIntros \"[H0 H1]\".\n    iApply isim_upd. iMod \"H0\". iModIntro.\n    iApply \"H1\". iFrame.\n  Qed.\n\n  Lemma Ladd (a b: Σ): @PCMLarge.URA.add (to_LURA Σ) a b = URA.add a b.\n  Proof.\n    unfold PCMLarge.URA.add. PCMLarge.unseal \"ra\". ur. auto.\n  Qed.\n\n  Lemma Lwf (a: Σ): @PCMLarge.URA.wf (to_LURA Σ) a = URA.wf a.\n  Proof.\n    unfold PCMLarge.URA.wf. PCMLarge.unseal \"ra\". ur. auto.\n  Qed.\n\n  Lemma Lunit: @PCMLarge.URA.unit (to_LURA Σ) = URA.unit.\n  Proof.\n    Local Transparent PCMLarge.URA.unit.\n    unfold PCMLarge.URA.unit. PCMLarge.unseal \"ra\". ur. auto.\n  Qed.\n\n  Lemma isim_wand r g R_src R_tgt\n        (Q0 Q1: R_src -> R_tgt -> shared_rel)\n        ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      ((∀ r_src r_tgt ths im_src im_tgt st_src st_tgt,\n           ((Q0 r_src r_tgt ths im_src im_tgt st_src st_tgt) -∗ #=> (Q1 r_src r_tgt ths im_src im_tgt st_src st_tgt))) ** (isim r g Q0 ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt))\n      (isim r g Q1 ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    rr in H. autorewrite with iprop in H. des. subst.\n    ii. eapply gpaco9_uclo; [auto with paco|apply lsim_frameC_spec|].\n    econs.\n    instantiate (1:=a).\n    eapply gpaco9_uclo; [auto with paco|apply lsim_monoC_spec|].\n    econs.\n    2:{ eapply H1. r_wf WF0. rewrite Ladd. r_solve. }\n    unfold liftRR. i. subst. des_ifs. des.\n    rr in H0. autorewrite with iprop in H0. specialize (H0 r_src).\n    rr in H0. autorewrite with iprop in H0. specialize (H0 r_tgt).\n    rr in H0. autorewrite with iprop in H0. specialize (H0 t).\n    rr in H0. autorewrite with iprop in H0. specialize (H0 i0).\n    rr in H0. autorewrite with iprop in H0. specialize (H0 i).\n    rr in H0. autorewrite with iprop in H0. specialize (H0 s0).\n    rr in H0. autorewrite with iprop in H0. specialize (H0 s).\n    rr in H0. autorewrite with iprop in H0.\n    hexploit (H0 r0); eauto.\n    { eapply URA.wf_mon. instantiate (1:=r_ctx'). r_wf WF1. rewrite Ladd. r_solve. }\n    i. rr in H. autorewrite with iprop in H.\n    hexploit H.\n    { instantiate (1:=r_ctx'). r_wf WF1. rewrite Ladd. r_solve. }\n    i. des. esplits; eauto.\n  Qed.\n\n  Lemma isim_mono r g R_src R_tgt\n        (Q0 Q1: R_src -> R_tgt -> shared_rel)\n        (MONO: forall r_src r_tgt ths im_src im_tgt st_src st_tgt,\n            bi_entails\n              (Q0 r_src r_tgt ths im_src im_tgt st_src st_tgt)\n              (#=> (Q1 r_src r_tgt ths im_src im_tgt st_src st_tgt)))\n        ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (isim r g Q0 ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n      (isim r g Q1 ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    iIntros. iApply isim_wand. iFrame.\n    iIntros. iApply MONO. eauto.\n  Qed.\n\n  Lemma isim_frame r g R_src R_tgt\n        P (Q: R_src -> R_tgt -> shared_rel)\n        ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (P ** isim r g Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n      (isim r g (fun r_src r_tgt ths im_src im_tgt st_src st_tgt =>\n                   P ** Q r_src r_tgt ths im_src im_tgt st_src st_tgt)\n            ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    iIntros \"[H0 H1]\". iApply isim_wand. iFrame.\n    iIntros. iModIntro. iFrame.\n  Qed.\n\n  Lemma isim_bind r g R_src R_tgt S_src S_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt\n        (itr_src: itree srcE S_src) (itr_tgt: itree tgtE S_tgt)\n        ktr_src ktr_tgt\n        ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (isim r g (fun s_src s_tgt ths im_src im_tgt st_src st_tgt =>\n                   isim r g Q false false (ktr_src s_src) (ktr_tgt s_tgt) ths im_src im_tgt st_src st_tgt) ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n      (isim r g Q ps pt (itr_src >>= ktr_src) (itr_tgt >>= ktr_tgt) ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. eapply gpaco9_uclo; [auto with paco|apply lsim_bindC_spec|].\n    econs.\n    eapply gpaco9_uclo; [auto with paco|apply lsim_monoC_spec|].\n    econs.\n    2:{ eapply H; eauto. }\n    unfold liftRR. i. des_ifs. des.\n    eapply gpaco9_uclo; [auto with paco|apply lsim_monoC_spec|].\n    econs.\n    2:{ eapply RET0; eauto. }\n    unfold liftRR. i. des_ifs.\n  Qed.\n\n  Lemma isim_ret r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt\n        r_src r_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (Q r_src r_tgt ths im_src im_tgt st_src st_tgt)\n      (isim r g Q ps pt (Ret r_src) (Ret r_tgt) ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_ret. unfold liftRR. esplits; eauto.\n  Qed.\n\n  Lemma isim_tauL r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (isim r g Q true pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n      (isim r g Q ps pt (Tau itr_src) itr_tgt ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_tauL. muclo lsim_resetC_spec. econs; eauto.\n  Qed.\n\n  Lemma isim_tauR r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (isim r g Q ps true itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n      (isim r g Q ps pt itr_src (Tau itr_tgt) ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_tauR. muclo lsim_resetC_spec. econs; eauto.\n  Qed.\n\n  Lemma isim_chooseL X r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt ktr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (∃ x, isim r g Q true pt (ktr_src x) itr_tgt ths im_src im_tgt st_src st_tgt)\n      (isim r g Q ps pt (trigger (Choose X) >>= ktr_src) itr_tgt ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_chooseL.\n    rr in H. autorewrite with iprop in H. des.\n    esplits; eauto.\n  Qed.\n\n  Lemma isim_chooseR X r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt itr_src ktr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (∀ x, isim r g Q ps true itr_src (ktr_tgt x) ths im_src im_tgt st_src st_tgt)\n      (isim r g Q ps pt itr_src (trigger (Choose X) >>= ktr_tgt) ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_chooseR.\n    rr in H. autorewrite with iprop in H.\n    i. econs; [eapply H|..]; eauto.\n  Qed.\n\n  Lemma isim_rmwL X rmw r g R_src R_tgt\n    (Q : R_src -> R_tgt -> shared_rel)\n    ps pt ktr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    : bi_entails\n        (isim r g Q true pt (ktr_src (snd (rmw st_src) : X)) itr_tgt ths im_src im_tgt (fst (rmw st_src)) st_tgt)\n        (isim r g Q ps pt (trigger (Rmw rmw) >>= ktr_src) itr_tgt ths im_src im_tgt st_src st_tgt).\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_rmwL. muclo lsim_resetC_spec. econs; [eapply H|..]; eauto.\n  Qed.\n\n  Lemma isim_rmwR X rmw r g R_src R_tgt\n    (Q : R_src -> R_tgt -> shared_rel)\n    ps pt itr_src ktr_tgt ths im_src im_tgt st_src st_tgt\n    : bi_entails\n        (isim r g Q ps true itr_src (ktr_tgt (snd (rmw st_tgt) : X)) ths im_src im_tgt st_src (fst (rmw st_tgt)))\n        (isim r g Q ps pt itr_src (trigger (Rmw rmw) >>= ktr_tgt) ths im_src im_tgt st_src st_tgt).\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_rmwR. muclo lsim_resetC_spec. econs; [eapply H|..]; eauto.\n  Qed.\n\n  Lemma isim_tidL r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt ktr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (isim r g Q true pt (ktr_src tid) itr_tgt ths im_src im_tgt st_src st_tgt)\n      (isim r g Q ps pt (trigger GetTid >>= ktr_src) itr_tgt ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_tidL. muclo lsim_resetC_spec. econs; [eapply H|..]; eauto.\n  Qed.\n\n  Lemma isim_tidR r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt itr_src ktr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (isim r g Q ps true itr_src (ktr_tgt tid) ths im_src im_tgt st_src st_tgt)\n      (isim r g Q ps pt itr_src (trigger GetTid >>= ktr_tgt) ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_tidR. muclo lsim_resetC_spec. econs; [eapply H|..]; eauto.\n  Qed.\n\n  Lemma isim_fairL f r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt ktr_src itr_tgt ths im_src0 im_tgt st_src st_tgt\n    :\n    bi_entails\n      (∃ im_src1, ⌜fair_update im_src0 im_src1 f⌝ ∧ isim r g Q true pt (ktr_src tt) itr_tgt ths im_src1 im_tgt st_src st_tgt)\n      (isim r g Q ps pt (trigger (Fair f) >>= ktr_src) itr_tgt ths im_src0 im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_fairL.\n    rr in H. autorewrite with iprop in H. des.\n    rr in H. autorewrite with iprop in H. des.\n    rr in H. autorewrite with iprop in H.\n    esplits; eauto.\n  Qed.\n\n  Lemma isim_fairR f r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt itr_src ktr_tgt ths im_src im_tgt0 st_src st_tgt\n    :\n    bi_entails\n      (∀ im_tgt1, ⌜fair_update im_tgt0 im_tgt1 (prism_fmap inrp f)⌝ -* isim r g Q ps true itr_src (ktr_tgt tt) ths im_src im_tgt1 st_src st_tgt)\n      (isim r g Q ps pt itr_src (trigger (Fair f) >>= ktr_tgt) ths im_src im_tgt0 st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_fairR. i.\n    rr in H. autorewrite with iprop in H.\n    hexploit H; eauto. i.\n    rr in H0. autorewrite with iprop in H0.\n    hexploit (H0 URA.unit); eauto.\n    { rewrite URA.unit_id. eapply URA.wf_mon; eauto. }\n    { rr. autorewrite with iprop. eauto. }\n    i. muclo lsim_resetC_spec. econs; [eapply H1|..]; eauto. r_wf WF0.\n  Qed.\n\n  Lemma isim_UB r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt ktr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (True)\n      (isim r g Q ps pt (trigger Undefined >>= ktr_src) itr_tgt ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_UB.\n  Qed.\n\n  Lemma isim_observe fn args r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt ktr_src ktr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (∀ ret, isim g g Q true true (ktr_src ret) (ktr_tgt ret) ths im_src im_tgt st_src st_tgt)\n      (isim r g Q ps pt (trigger (Observe fn args) >>= ktr_src) (trigger (Observe fn args) >>= ktr_tgt) ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. gstep. rr. eapply pind9_fold.\n    eapply lsim_observe; eauto.\n    i. rr in H. autorewrite with iprop in H.\n    muclo lsim_resetC_spec. econs; [eapply H|..]; eauto.\n  Qed.\n\n  Lemma isim_yieldL r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt ktr_src ktr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (isim r g Q true pt (ktr_src tt) (trigger (Yield) >>= ktr_tgt) ths im_src im_tgt st_src st_tgt)\n      (isim r g Q ps pt (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_yieldL. muclo lsim_resetC_spec. econs; [eapply H|..]; eauto.\n  Qed.\n\n  Lemma isim_yieldR r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt ktr_src ktr_tgt ths0 im_src0 im_tgt0 st_src0 st_tgt0\n    :\n    bi_entails\n      (I ths0 im_src0 im_tgt0 st_src0 st_tgt0 ** (∀ ths1 im_src1 im_tgt1 st_src1 st_tgt1 im_tgt2, I ths1 im_src1 im_tgt1 st_src1 st_tgt1 -* ⌜fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths1))⌝ -* isim r g Q ps true (trigger (Yield) >>= ktr_src) (ktr_tgt tt) ths1 im_src1 im_tgt2 st_src1 st_tgt1))\n      (isim r g Q ps pt (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) ths0 im_src0 im_tgt0 st_src0 st_tgt0)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    rr in H. autorewrite with iprop in H. des. subst.\n    ii. muclo lsim_indC_spec.\n    eapply lsim_yieldR; eauto.\n    { rewrite Lwf. repeat rewrite Ladd. eauto. }\n    i. rr in H1. autorewrite with iprop in H1. specialize (H1 ths1).\n    rr in H1. autorewrite with iprop in H1. specialize (H1 im_src1).\n    rr in H1. autorewrite with iprop in H1. specialize (H1 im_tgt1).\n    rr in H1. autorewrite with iprop in H1. specialize (H1 st_src1).\n    rr in H1. autorewrite with iprop in H1. specialize (H1 st_tgt1).\n    rr in H1. autorewrite with iprop in H1. specialize (H1 im_tgt2).\n    rr in H1. autorewrite with iprop in H1.\n    hexploit (H1 r_shared1); eauto.\n    { eapply URA.wf_mon. instantiate (1:=r_ctx1). rewrite Lwf in VALID. r_wf VALID.\n      repeat rewrite Ladd. r_solve.\n    }\n    i. rr in H. autorewrite with iprop in H. hexploit (H URA.unit); eauto.\n    { eapply URA.wf_mon. instantiate (1:=r_ctx1).\n      rewrite Lwf in VALID. r_wf VALID.\n      repeat rewrite Ladd. r_solve.\n    }\n    { rr. autorewrite with iprop. eauto. }\n    i. muclo lsim_resetC_spec. econs; [eapply H2|..]; eauto.\n    rewrite Lwf in VALID. r_wf VALID.\n    repeat rewrite Ladd. r_solve.\n  Qed.\n\n  Lemma isim_sync r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt ktr_src ktr_tgt ths0 im_src0 im_tgt0 st_src0 st_tgt0\n    :\n    bi_entails\n      (I ths0 im_src0 im_tgt0 st_src0 st_tgt0 ** (∀ ths1 im_src1 im_tgt1 st_src1 st_tgt1 im_tgt2, I ths1 im_src1 im_tgt1 st_src1 st_tgt1 -* ⌜fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths1))⌝ -* isim g g Q true true (ktr_src tt) (ktr_tgt tt) ths1 im_src1 im_tgt2 st_src1 st_tgt1))\n      (isim r g Q ps pt (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) ths0 im_src0 im_tgt0 st_src0 st_tgt0)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    rr in H. autorewrite with iprop in H. des. subst.\n    ii. gstep. eapply pind9_fold. eapply lsim_sync; eauto. i.\n    { rewrite Lwf. repeat rewrite Ladd. eauto. }\n    i.\n    rr in H1. autorewrite with iprop in H1. specialize (H1 ths1).\n    rr in H1. autorewrite with iprop in H1. specialize (H1 im_src1).\n    rr in H1. autorewrite with iprop in H1. specialize (H1 im_tgt1).\n    rr in H1. autorewrite with iprop in H1. specialize (H1 st_src1).\n    rr in H1. autorewrite with iprop in H1. specialize (H1 st_tgt1).\n    rr in H1. autorewrite with iprop in H1. specialize (H1 im_tgt2).\n    rr in H1. autorewrite with iprop in H1.\n    hexploit (H1 r_shared1); eauto.\n    { eapply URA.wf_mon. instantiate (1:=r_ctx1).\n      rewrite Lwf in VALID. r_wf VALID.\n      repeat rewrite Ladd. r_solve.\n    }\n    i. rr in H. autorewrite with iprop in H. hexploit (H URA.unit); eauto.\n    { eapply URA.wf_mon. instantiate (1:=r_ctx1).\n      rewrite Lwf in VALID. r_wf VALID.\n      repeat rewrite Ladd. r_solve.\n    }\n    { rr. autorewrite with iprop. eauto. }\n    i. muclo lsim_resetC_spec. econs; [eapply H2|..]; eauto.\n    rewrite Lwf in VALID. r_wf VALID.\n    repeat rewrite Ladd. r_solve.\n  Qed.\n\n  Lemma isim_base r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (@r _ _ Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n      (isim r g Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop.\n    ii. gbase. econs; eauto.\n  Qed.\n\n  Lemma isim_reset r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (isim r g Q false false itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n      (isim r g Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. rr in H. muclo lsim_resetC_spec. econs; [eapply H|..]; eauto.\n  Qed.\n\n  Lemma isim_progress r g R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        itr_src itr_tgt ths im_src im_tgt st_src st_tgt\n    :\n    bi_entails\n      (isim g g Q false false itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n      (isim r g Q true true itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. gstep. rr. eapply pind9_fold.\n    eapply lsim_progress; eauto.\n  Qed.\n\n  Lemma unlift_mon (r0 r1: rel)\n        (MON: forall R_src R_tgt (Q: R_src -> R_tgt -> shared_rel)\n                     ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt,\n            bi_entails\n              (@r0 _ _ Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n              (#=> (@r1 _ _ Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)))\n    :\n    unlift r0 <9= unlift r1.\n  Proof.\n    i. dependent destruction PR.\n    hexploit MON; eauto. i.\n    rr in H. autorewrite with iprop in H.\n    hexploit H; [|eauto|..].\n    { eapply URA.wf_mon. eauto. }\n    i. rr in H0. autorewrite with iprop in H0.\n    hexploit H0; eauto. i. des. econs; eauto.\n  Qed.\n\n  Lemma isim_mono_knowledge (r0 g0 r1 g1: rel) R_src R_tgt\n        (Q: R_src -> R_tgt -> shared_rel)\n        ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt\n        (MON0: forall R_src R_tgt (Q: R_src -> R_tgt -> shared_rel)\n                      ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt,\n            bi_entails\n              (@r0 _ _ Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n              (#=> (@r1 _ _ Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)))\n        (MON1: forall R_src R_tgt (Q: R_src -> R_tgt -> shared_rel)\n                      ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt,\n            bi_entails\n              (@g0 _ _ Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n              (#=> (@g1 _ _ Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)))\n    :\n    bi_entails\n      (isim r0 g0 Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n      (isim r1 g1 Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n  .\n  Proof.\n    rr. autorewrite with iprop. i.\n    ii. rr in H. hexploit H; eauto. i.\n    eapply gpaco9_mon; eauto.\n    { eapply unlift_mon; eauto. }\n    { eapply unlift_mon; eauto. }\n  Qed.\n\n  Lemma isim_coind A\n        (R_src: forall (a: A), Type)\n        (R_tgt: forall (a: A), Type)\n        (Q: forall (a: A), R_src a -> R_tgt a -> shared_rel)\n        (ps pt: forall (a: A), bool)\n        (itr_src : forall (a: A), itree srcE (R_src a))\n        (itr_tgt : forall (a: A), itree tgtE (R_tgt a))\n        (ths: forall (a: A), TIdSet.t)\n        (im_src: forall (a: A), imap ident_src wf_src)\n        (im_tgt: forall (a: A), imap (sum_tid ident_tgt) nat_wf)\n        (st_src: forall (a: A), state_src)\n        (st_tgt: forall (a: A), state_tgt)\n        (P: forall (a: A), iProp)\n        (r g0: rel)\n        (COIND: forall (g1: rel) a, bi_entails (□((∀ R_src R_tgt (Q: R_src -> R_tgt -> shared_rel)\n                                                     ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt,\n                                                      @g0 R_src R_tgt Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt -* @g1 R_src R_tgt Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n                                                    **\n                                                    (∀ a, P a -* @g1 (R_src a) (R_tgt a) (Q a) (ps a) (pt a) (itr_src a) (itr_tgt a) (ths a) (im_src a) (im_tgt a) (st_src a) (st_tgt a))) ** P a) (isim r g1 (Q a) (ps a) (pt a) (itr_src a) (itr_tgt a) (ths a) (im_src a) (im_tgt a) (st_src a) (st_tgt a)))\n    :\n    (forall a, bi_entails (P a) (isim r g0 (Q a) (ps a) (pt a) (itr_src a) (itr_tgt a) (ths a) (im_src a) (im_tgt a) (st_src a) (st_tgt a))).\n  Proof.\n    i. rr. autorewrite with iprop. ii. clear WF.\n    revert a r0 H r_ctx WF0. gcofix CIH. i.\n    epose (fun R_src R_tgt (Q: R_src -> R_tgt -> shared_rel)\n               ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt =>\n             @iProp_intro _ (fun r_own => forall r_ctx (WF: URA.wf (r_own ⋅ r_ctx)),\n                                 gpaco9 gf (cpn9 gf) r0 r0 R_src R_tgt (liftRR Q) ps pt r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)) _).\n    hexploit (COIND i a). subst i. clear COIND. i.\n    rr in H. autorewrite with iprop in H. hexploit H.\n    { instantiate (1:=r1). eapply URA.wf_mon; eauto. }\n    { rr. autorewrite with iprop.\n      exists URA.unit, r1. splits; auto.\n      { r_solve. }\n      rr. autorewrite with iprop. esplits.\n      { rr. autorewrite with iprop. ss. }\n      rr. autorewrite with iprop.\n      rr. autorewrite with iprop.\n      exists URA.unit, URA.unit. splits.\n      { rewrite URA.unit_core. r_solve. }\n      { do 13 (rr; autorewrite with iprop; i).\n        ss. i. gbase. eapply CIH0. econs; eauto. r_wf WF.\n      }\n      { do 2 (rr; autorewrite with iprop; i).\n        ss. i. gbase. eapply CIH; eauto. r_wf WF.\n      }\n    }\n    clear H. i. eapply gpaco9_gpaco.\n    { auto. }\n    eapply gpaco9_mon.\n    { eapply H. eauto. }\n    { i. gbase. eauto. }\n    { i. dependent destruction PR. subst.\n      rr in REL. eapply gpaco9_mon.\n      { eapply REL; eauto. }\n      { eauto. }\n      { eauto. }\n    }\n    Unshelve.\n    { i. ss. i. eapply H; eauto.\n      eapply URA.wf_extends; eauto. eapply URA.extends_add; eauto.\n    }\n  Qed.\n\nEnd SIM.\n\nFrom Fairness Require Export NatMapRALarge StateRA FairRA MonotonePCM.\nRequire Import Coq.Sorting.Mergesort.\n\nSection STATE.\n  Context `{Σ: GRA.t}.\n\n  Variable state_src: Type.\n  Variable state_tgt: Type.\n\n  Variable ident_src: ID.\n  Variable ident_tgt: ID.\n\n  Let srcE := programE ident_src state_src.\n  Let tgtE := programE ident_tgt state_tgt.\n\n  Let shared_rel := TIdSet.t -> (@imap ident_src owf) -> (@imap (sum_tid ident_tgt) nat_wf) -> state_src -> state_tgt -> iProp.\n\n  Variable Invs: list iProp.\n\n  Definition topset: mset := List.seq 0 (List.length Invs).\n\n  Context `{MONORA: @GRA.inG monoRA Σ}.\n  Context `{THDRA: @GRA.inG ThreadRA Σ}.\n  Context `{STATESRC: @GRA.inG (stateSrcRA state_src) Σ}.\n  Context `{STATETGT: @GRA.inG (stateTgtRA state_tgt) Σ}.\n  Context `{IDENTSRC: @GRA.inG (identSrcRA ident_src) Σ}.\n  Context `{IDENTTGT: @GRA.inG (identTgtRA ident_tgt) Σ}.\n  Context `{OBLGRA: @GRA.inG ObligationRA.t Σ}.\n  Context `{ARROWRA: @GRA.inG (ArrowRA ident_tgt) Σ}.\n  Context `{EDGERA: @GRA.inG EdgeRA Σ}.\n  Context `{ONESHOTRA: @GRA.inG (@FiniteMap.t (OneShot.t unit)) Σ}.\n\n  Definition St_src (st_src: state_src): iProp :=\n    OwnM (Auth.white (Excl.just (Some st_src): @Excl.t (option state_src)): stateSrcRA state_src).\n\n  Definition St_tgt (st_tgt: state_tgt): iProp :=\n    OwnM (Auth.white (Excl.just (Some st_tgt): @Excl.t (option state_tgt)): stateTgtRA state_tgt).\n\n  Definition default_initial_res\n    : Σ :=\n    (@GRA.embed _ _ THDRA (Auth.black (Some (NatMap.empty unit): NatMapRALarge.t unit)))\n      ⋅\n      (@GRA.embed _ _ STATESRC (Auth.black (Excl.just None: @Excl.t (option state_src)) ⋅ (Auth.white (Excl.just None: @Excl.t (option state_src)): stateSrcRA state_src)))\n      ⋅\n      (@GRA.embed _ _ STATETGT (Auth.black (Excl.just None: @Excl.t (option state_tgt)) ⋅ (Auth.white (Excl.just None: @Excl.t (option state_tgt)): stateTgtRA state_tgt)))\n      ⋅\n      (@GRA.embed _ _ IDENTSRC (@FairRA.source_init_resource ident_src))\n      ⋅\n      (@GRA.embed _ _ IDENTTGT ((fun _ => Fuel.black 0 1%Qp): identTgtRA ident_tgt))\n      ⋅\n      (@GRA.embed _ _ ARROWRA ((fun _ => OneShot.pending _ 1%Qp): ArrowRA ident_tgt))\n      ⋅\n      (@GRA.embed _ _ EDGERA ((fun _ => OneShot.pending _ 1%Qp): EdgeRA))\n  .\n\n  Lemma duty_to_black\n        (i: id_sum nat ident_tgt)\n    :\n    (ObligationRA.duty i [])\n      -∗\n      FairRA.black_ex i 1%Qp.\n  Proof.\n    iIntros \"[% [% [[H0 [H1 %]] %]]]\". destruct rs; ss. subst. auto.\n  Qed.\n\n  Lemma black_to_duty\n        (i: id_sum nat ident_tgt)\n    :\n    (FairRA.black_ex i 1%Qp)\n      -∗\n      (ObligationRA.duty i []).\n  Proof.\n    iIntros \"H\". iExists _, _. iFrame. iSplit.\n    { iSplit.\n      { iApply list_prop_sum_nil. }\n      { auto. }\n    }\n    { auto. }\n  Qed.\n\n  Lemma own_threads_init ths\n    :\n    (OwnM (Auth.black (Some (NatMap.empty unit): NatMapRALarge.t unit)))\n      -∗\n      (#=>\n         ((OwnM (Auth.black (Some ths: NatMapRALarge.t unit)))\n            **\n            (natmap_prop_sum ths (fun tid _ => own_thread tid)))).\n  Proof.\n    pattern ths. revert ths. eapply nm_ind.\n    { iIntros \"OWN\". iModIntro. iFrame. }\n    i. iIntros \"OWN\".\n    iPoseProof (IH with \"OWN\") as \"> [OWN SUM]\".\n    iPoseProof (OwnM_Upd with \"OWN\") as \"> [OWN0 OWN1]\".\n    { eapply Auth.auth_alloc. eapply (@NatMapRALarge.add_local_update unit m k v); eauto. }\n    iModIntro. iFrame. destruct v. iApply (natmap_prop_sum_add with \"SUM OWN1\").\n  Qed.\n\n  Lemma default_initial_res_init\n    :\n    (Own (default_initial_res))\n      -∗\n      (∀ ths st_src st_tgt im_tgt o,\n          #=> (∃ im_src,\n                  (default_I ths im_src im_tgt st_src st_tgt)\n                    **\n                    (natmap_prop_sum ths (fun tid _ => ObligationRA.duty (inl tid) []))\n                    **\n                    (natmap_prop_sum ths (fun tid _ => own_thread tid))\n                    **\n                    (FairRA.whites (fun _ => True: Prop) o)\n                    **\n                    (FairRA.blacks (fun i => match i with | inr _ => True | _ => False end: Prop))\n                    **\n                    (St_src st_src)\n                    **\n                    (St_tgt st_tgt)\n      )).\n  Proof.\n    iIntros \"OWN\" (? ? ? ? ?).\n    iDestruct \"OWN\" as \"[[[[[[OWN0 [OWN1 OWN2]] [OWN3 OWN4]] OWN5] OWN6] OWN7] OWN8]\".\n    iPoseProof (black_white_update with \"OWN1 OWN2\") as \"> [OWN1 OWN2]\".\n    iPoseProof (black_white_update with \"OWN3 OWN4\") as \"> [OWN3 OWN4]\".\n    iPoseProof (OwnM_Upd with \"OWN6\") as \"> OWN6\".\n    { instantiate (1:=FairRA.target_init_resource im_tgt).\n      unfold FairRA.target_init_resource.\n      erewrite ! (@unfold_pointwise_add (id_sum nat ident_tgt) (Fuel.t nat)).\n      apply pointwise_updatable. i.\n      rewrite URA.add_comm. exact (@Fuel.success_update nat _ 0 (im_tgt a)).\n    }\n    iPoseProof (FairRA.target_init with \"OWN6\") as \"[[H0 H1] H2]\".\n    iPoseProof (FairRA.source_init with \"OWN5\") as \"> [% [H3 H4]]\".\n    iExists f. unfold default_I. iFrame.\n    iPoseProof (own_threads_init with \"OWN0\") as \"> [OWN0 H]\". iFrame.\n    iModIntro. iSplitR \"H1\"; [iSplitL \"OWN8\"|].\n    { iExists _. iSplitL.\n      { iApply (OwnM_extends with \"OWN8\"). instantiate (1:=[]).\n        apply pointwise_extends. i. destruct a; ss; reflexivity.\n      }\n      { ss. }\n    }\n    { iExists _. iSplitL.\n      { iApply (OwnM_extends with \"OWN7\"). instantiate (1:=[]).\n        apply pointwise_extends. i. destruct a; ss; reflexivity.\n      }\n      { ss. }\n    }\n    { iApply natmap_prop_sum_impl; [|eauto]. i. ss. iApply black_to_duty. }\n  Qed.\n\n  Let I: shared_rel :=\n        fun ths im_src im_tgt st_src st_tgt =>\n          default_I ths im_src im_tgt st_src st_tgt ** mset_all (nth_default True%I Invs) topset.\n\n  Let rel := (forall R_src R_tgt (Q: R_src -> R_tgt -> iProp), bool -> bool -> itree srcE R_src -> itree tgtE R_tgt -> iProp).\n\n  Variable tid: thread_id.\n\n  Let unlift_rel\n      (r: forall R_src R_tgt (Q: R_src -> R_tgt -> shared_rel), bool -> bool -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel): rel :=\n        fun R_src R_tgt Q ps pt itr_src itr_tgt =>\n          (∀ ths im_src im_tgt st_src st_tgt,\n              (default_I_past tid ths im_src im_tgt st_src st_tgt ** mset_all (nth_default True%I Invs) topset)\n                -*\n                (@r R_src R_tgt (fun r_src r_tgt ths im_src im_tgt st_src st_tgt => (default_I_past tid ths im_src im_tgt st_src st_tgt ** mset_all (nth_default True%I Invs) topset) ** Q r_src r_tgt) ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt))%I.\n\n  Let lift_rel (rr: rel):\n    forall R_src R_tgt (QQ: R_src -> R_tgt -> shared_rel), bool -> bool -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n        fun R_src R_tgt QQ ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt =>\n          (∃ (Q: R_src -> R_tgt -> iProp)\n             (EQ: QQ = (fun r_src r_tgt ths im_src im_tgt st_src st_tgt =>\n                          (default_I_past tid ths im_src im_tgt st_src st_tgt ** mset_all (nth_default True%I Invs) topset) ** Q r_src r_tgt)),\n              rr R_src R_tgt Q ps pt itr_src itr_tgt ** (default_I_past tid ths im_src im_tgt st_src st_tgt ** mset_all (nth_default True%I Invs) topset))%I.\n\n  Let unlift_rel_base r\n    :\n    forall R_src R_tgt Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt,\n      (r R_src R_tgt Q ps pt itr_src itr_tgt)\n        -∗\n        (default_I_past tid ths im_src im_tgt st_src st_tgt ** mset_all (nth_default True%I Invs) topset)\n        -∗\n        (lift_rel\n           r\n           (fun r_src r_tgt ths im_src im_tgt st_src st_tgt => (default_I_past tid ths im_src im_tgt st_src st_tgt ** mset_all (nth_default True%I Invs) topset) ** Q r_src r_tgt)\n           ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt).\n  Proof.\n    unfold lift_rel, unlift_rel. i.\n    iIntros \"H D\". iExists _, _. Unshelve.\n    { iFrame. }\n    { auto. }\n  Qed.\n\n  Let unlift_lift r\n    :\n    forall R_src R_tgt Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt,\n      (lift_rel (unlift_rel r) Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n        ⊢ (r R_src R_tgt Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt).\n  Proof.\n    unfold lift_rel, unlift_rel. i.\n    iIntros \"[% [% [H D]]]\". subst.\n    iApply (\"H\" with \"D\").\n  Qed.\n\n  Let lift_unlift (r0: rel) (r1: forall R_src R_tgt (Q: R_src -> R_tgt -> shared_rel), bool -> bool -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n    :\n    bi_entails\n      (∀ R_src R_tgt (Q: R_src -> R_tgt -> shared_rel) ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt,\n          @lift_rel r0 R_src R_tgt Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt -* r1 R_src R_tgt Q ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n      (∀ R_src R_tgt Q ps pt itr_src itr_tgt, r0 R_src R_tgt Q ps pt itr_src itr_tgt -* unlift_rel r1 Q ps pt itr_src itr_tgt).\n  Proof.\n    unfold lift_rel, unlift_rel.\n    iIntros \"IMPL\" (? ? ? ? ? ? ?) \"H\". iIntros (? ? ? ? ?) \"D\".\n    iApply \"IMPL\". iExists _, _. Unshelve.\n    { iFrame. }\n    { auto. }\n  Qed.\n\n  Let lift_rel_mon (rr0 rr1: rel)\n      (MON: forall R_src R_tgt Q ps pt itr_src itr_tgt,\n          bi_entails\n            (rr0 R_src R_tgt Q ps pt itr_src itr_tgt)\n            (#=> rr1 R_src R_tgt Q ps pt itr_src itr_tgt))\n    :\n    forall R_src R_tgt (QQ: R_src -> R_tgt -> shared_rel) ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt,\n      bi_entails\n        (lift_rel rr0 QQ ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt)\n        (#=> lift_rel rr1 QQ ps pt itr_src itr_tgt ths im_src im_tgt st_src st_tgt).\n  Proof.\n    unfold lift_rel. i.\n    iIntros \"[% [% [H D]]]\". subst.\n    iPoseProof (MON with \"H\") as \"> H\".\n    iModIntro. iExists _, _. Unshelve.\n    { iFrame. }\n    { auto. }\n  Qed.\n\n  Definition stsim (E: mset): rel -> rel -> rel :=\n    fun r g\n        R_src R_tgt Q ps pt itr_src itr_tgt =>\n      (∀ ths im_src im_tgt st_src st_tgt,\n          (default_I_past tid ths im_src im_tgt st_src st_tgt ** mset_all (nth_default True%I Invs) E)\n            -*\n            (isim\n               tid\n               I\n               (lift_rel r)\n               (lift_rel g)\n               (fun r_src r_tgt ths im_src im_tgt st_src st_tgt => (default_I_past tid ths im_src im_tgt st_src st_tgt ** mset_all (nth_default True%I Invs) topset) ** Q r_src r_tgt)\n               ps pt itr_src itr_tgt\n               ths im_src im_tgt st_src st_tgt))%I\n  .\n\n  Record mytype\n         (A: Type) :=\n    mk_mytype {\n        comp_a: A;\n        comp_ths: TIdSet.t;\n        comp_im_src: imap ident_src owf;\n        comp_im_tgt: imap (sum_tid ident_tgt) nat_wf;\n        comp_st_src: state_src;\n        comp_st_tgt: state_tgt;\n      }.\n\n\n\n\n\n  Lemma stsim_discard E1 E0 r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src itr_tgt\n        (TOP: mset_sub E0 E1)\n    :\n    (stsim E0 r g Q ps pt itr_src itr_tgt)\n      -∗\n      (stsim E1 r g Q ps pt itr_src itr_tgt)\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"[D I]\".\n    iPoseProof (mset_all_sub with \"I\") as \"[I RESTORE]\"; [eauto|].\n    iPoseProof (\"H\" with \"[D I]\") as \"H\".\n    { iFrame. }\n    iApply isim_wand. iFrame.\n    iIntros (? ? ? ? ? ? ?) \"[[D I] Q]\".\n    iModIntro. iFrame.\n  Qed.\n\n  Lemma stsim_base E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src itr_tgt\n        (TOP: mset_sub topset E)\n    :\n    (@r _ _ Q ps pt itr_src itr_tgt)\n      -∗\n      (stsim E r g Q ps pt itr_src itr_tgt)\n  .\n  Proof.\n    rewrite <- stsim_discard; [|eassumption].\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n    iApply isim_base.\n    iApply (unlift_rel_base with \"H D\").\n  Qed.\n\n  Lemma stsim_mono_knowledge E (r0 g0 r1 g1: rel) R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src itr_tgt\n        (MON0: forall R_src R_tgt (Q: R_src -> R_tgt -> iProp)\n                      ps pt itr_src itr_tgt,\n            (@r0 _ _ Q ps pt itr_src itr_tgt)\n              -∗\n              (#=> (@r1 _ _ Q ps pt itr_src itr_tgt)))\n        (MON1: forall R_src R_tgt (Q: R_src -> R_tgt -> iProp)\n                      ps pt itr_src itr_tgt,\n            (@g0 _ _ Q ps pt itr_src itr_tgt)\n              -∗\n              (#=> (@g1 _ _ Q ps pt itr_src itr_tgt)))\n    :\n    bi_entails\n      (stsim E r0 g0 Q ps pt itr_src itr_tgt)\n      (stsim E r1 g1 Q ps pt itr_src itr_tgt)\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n    iApply isim_mono_knowledge.\n    { eapply lift_rel_mon. eauto. }\n    { eapply lift_rel_mon. eauto. }\n    iApply (\"H\" with \"D\").\n  Qed.\n\n  Lemma stsim_coind E A\n        (R_src: forall (a: A), Type)\n        (R_tgt: forall (a: A), Type)\n        (Q: forall (a: A), R_src a -> R_tgt a -> iProp)\n        (ps pt: forall (a: A), bool)\n        (itr_src : forall (a: A), itree srcE (R_src a))\n        (itr_tgt : forall (a: A), itree tgtE (R_tgt a))\n        (P: forall (a: A), iProp)\n        (r g0: rel)\n        (TOP: mset_sub topset E)\n        (COIND: forall (g1: rel) a,\n            (□((∀ R_src R_tgt (Q: R_src -> R_tgt -> iProp)\n                  ps pt itr_src itr_tgt,\n                   @g0 R_src R_tgt Q ps pt itr_src itr_tgt -* @g1 R_src R_tgt Q ps pt itr_src itr_tgt)\n                 **\n                 (∀ a, P a -* @g1 (R_src a) (R_tgt a) (Q a) (ps a) (pt a) (itr_src a) (itr_tgt a))))\n              -∗\n              (P a)\n              -∗\n              (stsim topset r g1 (Q a) (ps a) (pt a) (itr_src a) (itr_tgt a)))\n    :\n    (forall a, bi_entails (P a) (stsim E r g0 (Q a) (ps a) (pt a) (itr_src a) (itr_tgt a))).\n  Proof.\n    cut (forall (m: mytype A),\n            bi_entails\n              ((fun m => P m.(comp_a) ** (default_I_past tid m.(comp_ths) m.(comp_im_src) m.(comp_im_tgt) m.(comp_st_src) m.(comp_st_tgt) ** mset_all (nth_default True%I Invs) topset)) m)\n              (isim tid I (lift_rel r) (lift_rel g0) ((fun m => fun r_src r_tgt ths im_src im_tgt st_src st_tgt => (default_I_past tid ths im_src im_tgt st_src st_tgt ** mset_all (nth_default True%I Invs) topset) ** Q m.(comp_a) r_src r_tgt) m)\n                    ((fun m => ps m.(comp_a)) m) ((fun m => pt m.(comp_a)) m) ((fun m => itr_src m.(comp_a)) m) ((fun m => itr_tgt m.(comp_a)) m) (comp_ths m) (comp_im_src m) (comp_im_tgt m) (comp_st_src m) (comp_st_tgt m))).\n    { ss. i. rewrite <- stsim_discard; [|eassumption].\n      unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n      specialize (H (mk_mytype a ths im_src im_tgt st_src st_tgt)). ss.\n      iApply H. iFrame.\n    }\n    eapply isim_coind. i. iIntros \"[# CIH [H D]]\".\n    unfold stsim in COIND.\n    iAssert (□((∀ R_src R_tgt (Q: R_src -> R_tgt -> iProp)\n                  ps pt itr_src itr_tgt,\n                   @g0 R_src R_tgt Q ps pt itr_src itr_tgt -* @unlift_rel g1 R_src R_tgt Q ps pt itr_src itr_tgt)\n                 **\n                 (∀ a, P a -* @unlift_rel g1 (R_src a) (R_tgt a) (Q a) (ps a) (pt a) (itr_src a) (itr_tgt a))))%I with \"[CIH]\" as \"CIH'\".\n    { iPoseProof \"CIH\" as \"# [CIH0 CIH1]\". iModIntro. iSplitL.\n      { iApply (lift_unlift with \"CIH0\"). }\n      { iIntros. unfold unlift_rel. iIntros.\n        iSpecialize (\"CIH1\" $! (mk_mytype _ _ _ _ _ _)). ss.\n        iApply \"CIH1\". iFrame.\n      }\n    }\n    iPoseProof (COIND with \"CIH' H D\") as \"H\".\n    iApply (isim_mono_knowledge with \"H\").\n    { auto. }\n    { i. iIntros \"H\". iModIntro. iApply unlift_lift. auto. }\n  Qed.\n\n  Lemma stsim_upd E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src itr_tgt\n    :\n    (#=> (stsim E r g Q ps pt itr_src itr_tgt))\n      -∗\n      (stsim E r g Q ps pt itr_src itr_tgt)\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\". iMod \"H\".\n    iApply \"H\". auto.\n  Qed.\n\n  Global Instance stsim_elim_upd\n         E r g R_src R_tgt\n         (Q: R_src -> R_tgt -> iProp)\n         ps pt itr_src itr_tgt p\n         P\n    :\n    ElimModal True p false (#=> P) P (stsim E r g Q ps pt itr_src itr_tgt) (stsim E r g Q ps pt itr_src itr_tgt).\n  Proof.\n    typeclasses eauto.\n  Qed.\n\n  Lemma stsim_mupd E0 E1 r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src itr_tgt\n    :\n    (MUpd (nth_default True%I Invs) (fairI (ident_tgt:=ident_tgt)) E0 E1 (stsim E1 r g Q ps pt itr_src itr_tgt))\n      -∗\n      (stsim E0 r g Q ps pt itr_src itr_tgt)\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"[[% [% [[D X0] X1]]] C]\".\n    iAssert (fairI (ident_tgt:=ident_tgt) ** mset_all (nth_default True%I Invs) E0) with \"[X0 X1 C]\" as \"C\".\n    { iFrame. }\n    iMod (\"H\" with \"C\") as \"[[[X0 X1] C] H]\".\n    iApply \"H\". iFrame. iExists _. iFrame. auto.\n  Qed.\n\n  Lemma stsim_mupd_weaken E0 E1 r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src itr_tgt\n        (SUB: mset_sub E0 E1)\n    :\n    (MUpd (nth_default True%I Invs) (fairI (ident_tgt:=ident_tgt)) E0 E0 (stsim E1 r g Q ps pt itr_src itr_tgt))\n      -∗\n      (stsim E1 r g Q ps pt itr_src itr_tgt)\n  .\n  Proof.\n    iIntros \"H\". iApply stsim_mupd. iApply MUpd_mask_mono; eauto.\n  Qed.\n\n  Global Instance stsim_elim_mupd_gen\n         E0 E1 E2 r g R_src R_tgt\n         (Q: R_src -> R_tgt -> iProp)\n         ps pt itr_src itr_tgt p\n         P\n    :\n    ElimModal (mset_sub E0 E2) p false (MUpd (nth_default True%I Invs) (fairI (ident_tgt:=ident_tgt)) E0 E1 P) P (stsim E2 r g Q ps pt itr_src itr_tgt) (stsim (NatSort.sort (E1 ++ mset_minus E2 E0)) r g Q ps pt itr_src itr_tgt).\n  Proof.\n    unfold ElimModal. rewrite bi.intuitionistically_if_elim.\n    i. iIntros \"[H0 H1]\".\n    iPoseProof (MUpd_mask_frame_r with \"H0\") as \"H0\".\n    iPoseProof (MUpd_permutation with \"H0\") as \"H0\".\n    { eapply mset_minus_add_eq; eauto. }\n    { reflexivity. }\n    iApply stsim_mupd. iMod \"H0\".\n    iPoseProof (\"H1\" with \"H0\") as \"H\".\n    iModIntro. iApply (stsim_discard with \"H\").\n    rewrite <- NatSort.Permuted_sort. reflexivity.\n  Qed.\n\n  Global Instance stsim_elim_mupd_eq\n         E1 E2 r g R_src R_tgt\n         (Q: R_src -> R_tgt -> iProp)\n         ps pt itr_src itr_tgt p\n         P\n    :\n    ElimModal (mset_sub E1 E2) p false (MUpd (nth_default True%I Invs) (fairI (ident_tgt:=ident_tgt)) E1 E1 P) P (stsim E2 r g Q ps pt itr_src itr_tgt) (stsim E2 r g Q ps pt itr_src itr_tgt).\n  Proof.\n    unfold ElimModal. rewrite bi.intuitionistically_if_elim.\n    i. iIntros \"[H0 H1]\".\n    iApply stsim_mupd_weaken.\n    { eauto. }\n    iMod \"H0\". iModIntro. iApply (\"H1\" with \"H0\").\n  Qed.\n\n  Global Instance stsim_elim_mupd\n         E1 E2 r g R_src R_tgt\n         (Q: R_src -> R_tgt -> iProp)\n         ps pt itr_src itr_tgt p\n         P\n    :\n    ElimModal True p false (MUpd (nth_default True%I Invs) (fairI (ident_tgt:=ident_tgt)) E1 E2 P) P (stsim E1 r g Q ps pt itr_src itr_tgt) (stsim E2 r g Q ps pt itr_src itr_tgt).\n  Proof.\n    unfold ElimModal. rewrite bi.intuitionistically_if_elim.\n    i. iIntros \"[H0 H1]\".\n    iApply stsim_mupd. iMod \"H0\".\n    iModIntro. iApply (\"H1\" with \"H0\").\n  Qed.\n\n  Global Instance stsim_add_modal_mupd\n         E r g R_src R_tgt\n         (Q: R_src -> R_tgt -> iProp)\n         ps pt itr_src itr_tgt\n         P\n    :\n    AddModal (MUpd (nth_default True%I Invs) (fairI (ident_tgt:=ident_tgt)) E E P) P (stsim E r g Q ps pt itr_src itr_tgt).\n  Proof.\n    unfold AddModal. iIntros \"[> H0 H1]\". iApply (\"H1\" with \"H0\").\n  Qed.\n\n  Global Instance stsim_elim_iupd_edge\n         E r g R_src R_tgt\n         (Q: R_src -> R_tgt -> iProp)\n         ps pt itr_src itr_tgt p\n         P\n    :\n    ElimModal True p false (#=(ObligationRA.edges_sat)=> P) P (stsim E r g Q ps pt itr_src itr_tgt) (stsim E r g Q ps pt itr_src itr_tgt).\n  Proof.\n    unfold ElimModal. rewrite bi.intuitionistically_if_elim.\n    i. iIntros \"[H0 H1]\" (? ? ? ? ?) \"[[% [% D]] C]\".\n    iPoseProof (IUpd_sub_mon with \"[] H0 D\") as \"> [D P]\"; auto.\n    { iApply edges_sat_sub. }\n    iApply (\"H1\" with \"P\"). iFrame. iExists _. eauto.\n  Qed.\n\n  Global Instance stsim_elim_iupd_arrow\n         E r g R_src R_tgt\n         (Q: R_src -> R_tgt -> iProp)\n         ps pt itr_src itr_tgt p\n         P\n    :\n    ElimModal True p false (#=(ObligationRA.arrows_sat (Id:=sum_tid ident_tgt))=> P) P (stsim E r g Q ps pt itr_src itr_tgt) (stsim E r g Q ps pt itr_src itr_tgt).\n  Proof.\n    unfold ElimModal. rewrite bi.intuitionistically_if_elim.\n    i. iIntros \"[H0 H1]\" (? ? ? ? ?) \"[[% [% D]] C]\".\n    iPoseProof (IUpd_sub_mon with \"[] H0 D\") as \"> [D P]\"; auto.\n    { iApply arrows_sat_sub. }\n    iApply (\"H1\" with \"P\"). iFrame. iExists _. eauto.\n  Qed.\n\n  Global Instance mupd_elim_iupd_edge\n         P Q E1 E2 p Inv\n    :\n    ElimModal True p false (#=(ObligationRA.edges_sat)=> P) P (MUpd Inv (fairI (ident_tgt:=ident_tgt)) E1 E2 Q) (MUpd Inv (fairI (ident_tgt:=ident_tgt)) E1 E2 Q).\n  Proof.\n    unfold ElimModal. rewrite bi.intuitionistically_if_elim.\n    i. iIntros \"[H0 H1]\".\n    iPoseProof (IUpd_sub_mon with \"[] H0\") as \"H0\".\n    { iApply SubIProp_sep_l. }\n    iMod \"H0\". iApply (\"H1\" with \"H0\").\n  Qed.\n\n  Global Instance mupd_elim_iupd_arrow\n         P Q E1 E2 p Inv\n    :\n    ElimModal True p false (#=(ObligationRA.arrows_sat (Id:=sum_tid ident_tgt))=> P) P (MUpd Inv (fairI (ident_tgt:=ident_tgt)) E1 E2 Q) (MUpd Inv (fairI (ident_tgt:=ident_tgt)) E1 E2 Q).\n  Proof.\n    unfold ElimModal. rewrite bi.intuitionistically_if_elim.\n    i. iIntros \"[H0 H1]\".\n    iPoseProof (IUpd_sub_mon with \"[] H0\") as \"H0\".\n    { iApply SubIProp_sep_r. }\n    iMod \"H0\". iApply (\"H1\" with \"H0\").\n  Qed.\n\n  Lemma stsim_wand E r g R_src R_tgt\n        (Q0 Q1: R_src -> R_tgt -> iProp)\n        ps pt itr_src itr_tgt\n    :\n    (stsim E r g Q0 ps pt itr_src itr_tgt)\n      -∗\n      (∀ r_src r_tgt,\n          ((Q0 r_src r_tgt) -∗ #=> (Q1 r_src r_tgt)))\n      -∗\n      (stsim E r g Q1 ps pt itr_src itr_tgt)\n  .\n  Proof.\n    unfold stsim. iIntros \"H0 H1\" (? ? ? ? ?) \"D\".\n    iApply isim_wand.\n    iPoseProof (\"H0\" $! _ _ _ _ _ with \"D\") as \"H0\".\n    iSplitR \"H0\"; [|auto]. iIntros (? ? ? ? ? ? ?) \"[D H0]\".\n    iPoseProof (\"H1\" $! _ _ with \"H0\") as \"> H0\". iModIntro. iFrame.\n  Qed.\n\n  Lemma stsim_mono E r g R_src R_tgt\n        (Q0 Q1: R_src -> R_tgt -> iProp)\n        (MONO: forall r_src r_tgt,\n            (Q0 r_src r_tgt)\n              -∗\n              (#=> (Q1 r_src r_tgt)))\n        ps pt itr_src itr_tgt\n    :\n    (stsim E r g Q0 ps pt itr_src itr_tgt)\n      -∗\n      (stsim E r g Q1 ps pt itr_src itr_tgt)\n  .\n  Proof.\n    iIntros \"H\". iApply (stsim_wand with \"H\").\n    iIntros. iApply MONO. auto.\n  Qed.\n\n  Lemma stsim_frame E r g R_src R_tgt\n        P (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src itr_tgt\n    :\n    (stsim E r g Q ps pt itr_src itr_tgt)\n      -∗\n      P\n      -∗\n      (stsim E r g (fun r_src r_tgt => P ** Q r_src r_tgt) ps pt itr_src itr_tgt)\n  .\n  Proof.\n    iIntros \"H0 H1\". iApply (stsim_wand with \"H0\").\n    iIntros. iModIntro. iFrame.\n  Qed.\n\n  Lemma stsim_bind_top E r g R_src R_tgt S_src S_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt (itr_src: itree srcE S_src) (itr_tgt: itree tgtE S_tgt)\n        ktr_src ktr_tgt\n    :\n    (stsim E r g (fun s_src s_tgt => stsim topset r g Q false false (ktr_src s_src) (ktr_tgt s_tgt)) ps pt itr_src itr_tgt)\n      -∗\n      (stsim E r g Q ps pt (itr_src >>= ktr_src) (itr_tgt >>= ktr_tgt))\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n    iPoseProof (\"H\" $! _ _ _ _ _ with \"D\") as \"H\".\n    iApply isim_bind. iApply (isim_mono with \"H\").\n    iIntros (? ? ? ? ? ? ?) \"[[D I] H]\".\n    iApply (\"H\" $! _ _ _ _ _ with \"[D I]\"). iFrame.\n  Qed.\n\n  Lemma stsim_ret E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt r_src r_tgt\n    :\n    (MUpd (nth_default True%I Invs) (fairI (ident_tgt:=ident_tgt)) E topset (Q r_src r_tgt))\n      -∗\n      (stsim E r g Q ps pt (Ret r_src) (Ret r_tgt))\n  .\n  Proof.\n    iIntros \"> H\".\n    unfold stsim. iIntros (? ? ? ? ?) \"D\".\n    iApply isim_ret. iFrame.\n  Qed.\n\n  Lemma stsim_tauL E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src itr_tgt\n    :\n    (stsim E r g Q true pt itr_src itr_tgt)\n      -∗\n      (stsim E r g Q ps pt (Tau itr_src) itr_tgt)\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n    iPoseProof (\"H\" $! _ _ _ _ _ with \"D\") as \"H\".\n    iApply isim_tauL. iFrame.\n  Qed.\n\n  Lemma stsim_tauR E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src itr_tgt\n    :\n    (stsim E r g Q ps true itr_src itr_tgt)\n      -∗\n      (stsim E r g Q ps pt itr_src (Tau itr_tgt))\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n    iPoseProof (\"H\" $! _ _ _ _ _ with \"D\") as \"H\".\n    iApply isim_tauR. iFrame.\n  Qed.\n\n  Lemma stsim_chooseL E X r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src itr_tgt\n    :\n    (∃ x, stsim E r g Q true pt (ktr_src x) itr_tgt)\n      -∗\n      (stsim E r g Q ps pt (trigger (Choose X) >>= ktr_src) itr_tgt)\n  .\n  Proof.\n    unfold stsim. iIntros \"[% H]\" (? ? ? ? ?) \"D\".\n    iPoseProof (\"H\" $! _ _ _ _ _ with \"D\") as \"H\".\n    iApply isim_chooseL. iExists _. iFrame.\n  Qed.\n\n  Lemma stsim_chooseR E X r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src ktr_tgt\n    :\n    (∀ x, stsim E r g Q ps true itr_src (ktr_tgt x))\n      -∗\n      (stsim E r g Q ps pt itr_src (trigger (Choose X) >>= ktr_tgt))\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n    iApply isim_chooseR. iIntros (?).\n    iPoseProof (\"H\" $! _ _ _ _ _ _ with \"D\") as \"H\". iFrame.\n  Qed.\n\n  Lemma stsim_rmwL E X rmw r g R_src R_tgt\n    (Q : R_src -> R_tgt -> iProp)\n    ps pt ktr_src itr_tgt st_src\n    :\n    (St_src st_src)\n    -∗ (St_src (fst (rmw st_src)) -∗ stsim E r g Q true pt (ktr_src (snd (rmw st_src) : X)) itr_tgt)\n    -∗ stsim E r g Q ps pt (trigger (Rmw rmw) >>= ktr_src) itr_tgt.\n  Proof.\n    unfold stsim. iIntros \"H0 H1\" (? ? ? ? ?) \"[D C]\". iApply isim_rmwL.\n    iAssert (⌜st_src0 = st_src⌝)%I as \"%\".\n    { iApply (default_I_past_get_st_src with \"D H0\"); eauto. }\n    subst.\n    iPoseProof (default_I_past_update_st_src with \"D H0\") as \"> [D H0]\".\n    iApply (\"H1\" with \"D [H0 C]\"). iFrame.\n  Qed.\n\n  Lemma stsim_rmwR E X rmw r g R_src R_tgt\n    (Q : R_src -> R_tgt -> iProp)\n    ps pt itr_src ktr_tgt st_tgt\n    :\n    (St_tgt st_tgt)\n    -∗ (St_tgt (fst (rmw st_tgt)) -∗ stsim E r g Q ps true itr_src (ktr_tgt (snd (rmw st_tgt) : X)))\n    -∗ stsim E r g Q ps pt itr_src (trigger (Rmw rmw) >>= ktr_tgt).\n  Proof.\n    unfold stsim. iIntros \"H0 H1\" (? ? ? ? ?) \"[D C]\". iApply isim_rmwR.\n    iAssert (⌜st_tgt0 = st_tgt⌝)%I as \"%\".\n    { iApply (default_I_past_get_st_tgt with \"D H0\"); eauto. }\n    subst.\n    iPoseProof (default_I_past_update_st_tgt with \"D H0\") as \"> [D H0]\".\n    iApply (\"H1\" with \"D [H0 C]\"). iFrame.\n  Qed.\n\n  Lemma stsim_getL X (p : state_src -> X) E st r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src itr_tgt\n    :\n    ((St_src st) ∧\n       (stsim E r g Q true pt (ktr_src (p st)) itr_tgt))\n      -∗\n      (stsim E r g Q ps pt (trigger (Get p) >>= ktr_src) itr_tgt)\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"[D C]\".\n    rewrite get_rmw. iApply isim_rmwL.\n    iAssert (⌜st_src = st⌝)%I as \"%\".\n    { iDestruct \"H\" as \"[H _]\". iApply (default_I_past_get_st_src with \"D\"); eauto. }\n    subst. iDestruct \"H\" as \"[_ H]\". iApply (\"H\" with \"[D C]\"). iFrame.\n  Qed.\n\n  Lemma stsim_getR X (p : state_tgt -> X) E st r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src ktr_tgt\n    :\n    ((St_tgt st) ∧\n       (stsim E r g Q ps true itr_src (ktr_tgt (p st))))\n      -∗\n      (stsim E r g Q ps pt itr_src (trigger (Get p) >>= ktr_tgt))\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"[D C]\".\n    rewrite get_rmw. iApply isim_rmwR.\n    iAssert (⌜st_tgt = st⌝)%I as \"%\".\n    { iDestruct \"H\" as \"[H _]\". iApply (default_I_past_get_st_tgt with \"D\"); eauto. }\n    subst. iDestruct \"H\" as \"[_ H]\". iApply (\"H\" with \"[D C]\"). iFrame.\n  Qed.\n\n  Lemma stsim_tidL E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src itr_tgt\n    :\n    (stsim E r g Q true pt (ktr_src tid) itr_tgt)\n      -∗\n      (stsim E r g Q ps pt (trigger GetTid >>= ktr_src) itr_tgt)\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n    iApply isim_tidL. iApply (\"H\" with \"D\").\n  Qed.\n\n  Lemma stsim_tidR E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src ktr_tgt\n    :\n    (stsim E r g Q ps true itr_src (ktr_tgt tid))\n      -∗\n      (stsim E r g Q ps pt itr_src (trigger GetTid >>= ktr_tgt))\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n    iApply isim_tidR. iApply (\"H\" with \"D\").\n  Qed.\n\n  Lemma stsim_fairL o lf ls\n        E fm r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src itr_tgt\n        (FAIL: forall i (IN: fm i = Flag.fail), List.In i lf)\n        (SUCCESS: forall i (IN: List.In i ls), fm i = Flag.success)\n    :\n    (list_prop_sum (fun i => FairRA.white i Ord.one) lf)\n      -∗\n      ((list_prop_sum (fun i => FairRA.white i o) ls) -∗ (stsim E r g Q true pt (ktr_src tt) itr_tgt))\n      -∗\n      (stsim E r g Q ps pt (trigger (Fair fm) >>= ktr_src) itr_tgt).\n  Proof.\n    unfold stsim. iIntros \"OWN H\" (? ? ? ? ?) \"[D C]\".\n    iPoseProof (default_I_past_update_ident_source with \"D OWN\") as \"> [% [[% WHITES] D]]\".\n    { eauto. }\n    { eauto. }\n    iPoseProof (\"H\" with \"WHITES [D C]\") as \"H\".\n    { iFrame. }\n    iApply isim_fairL. iExists _. iSplit; eauto.\n  Qed.\n\n  Lemma stsim_fairR lf ls\n        E fm r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src ktr_tgt\n        (SUCCESS: forall i (IN: fm i = Flag.success), List.In i (List.map fst ls))\n        (FAIL: forall i (IN: List.In i lf), fm i = Flag.fail)\n        (NODUP: List.NoDup lf)\n    :\n    (list_prop_sum (fun '(i, l) => ObligationRA.duty (inr i) l ** ObligationRA.tax l) ls)\n      -∗\n      ((list_prop_sum (fun '(i, l) => ObligationRA.duty (inr i) l) ls)\n         -*\n         (list_prop_sum (fun i => FairRA.white (Id:=_) (inr i) 1) lf)\n         -*\n         stsim E r g Q ps true itr_src (ktr_tgt tt))\n      -∗\n      (stsim E r g Q ps pt itr_src (trigger (Fair fm) >>= ktr_tgt))\n  .\n  Proof.\n    unfold stsim. iIntros \"OWN H\"  (? ? ? ? ?) \"[D C]\".\n    iApply isim_fairR. iIntros (?) \"%\".\n    iPoseProof (default_I_past_update_ident_target with \"D OWN\") as \"> [[DUTY WHITE] D]\".    { eauto. }\n    { eauto. }\n    { eauto. }\n    { eauto. }\n    iApply (\"H\" with \"DUTY WHITE\"). iFrame.\n  Qed.\n\n  Lemma stsim_fairR_simple lf ls\n        E fm r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src ktr_tgt\n        (SUCCESS: forall i (IN: fm i = Flag.success), List.In i ls)\n        (FAIL: forall i (IN: List.In i lf), fm i = Flag.fail)\n        (NODUP: List.NoDup lf)\n    :\n    (list_prop_sum (fun i => FairRA.black_ex (inr i) 1) ls)\n      -∗\n      ((list_prop_sum (fun i => FairRA.black_ex (inr i) 1) ls)\n         -*\n         (list_prop_sum (fun i => FairRA.white (Id:=_) (inr i) 1) lf)\n         -*\n         stsim E r g Q ps true itr_src (ktr_tgt tt))\n      -∗\n      (stsim E r g Q ps pt itr_src (trigger (Fair fm) >>= ktr_tgt))\n  .\n  Proof.\n    iIntros \"A B\". iApply (stsim_fairR with \"[A]\"); eauto.\n    { instantiate (1:= List.map (fun i => (i, [])) ls). i. specialize (SUCCESS _ IN). rewrite List.map_map. ss.\n      replace (List.map (λ x : ident_tgt, x) ls) with ls; auto. clear. induction ls; ss; eauto. f_equal. auto.\n    }\n    { iApply list_prop_sum_map. 2: iFrame. i. ss. iIntros \"BLK\". iSplitL; auto. iApply black_to_duty. auto. }\n    { iIntros \"S F\". iApply (\"B\" with \"[S]\"). 2: iFrame. iApply list_prop_sum_map_inv. 2: iFrame.\n      i; ss. iIntros \"D\". iApply duty_to_black. iFrame.\n    }\n  Qed.\n\n  Lemma stsim_UB E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src itr_tgt\n    :\n    ⊢ (stsim E r g Q ps pt (trigger Undefined >>= ktr_src) itr_tgt)\n  .\n  Proof.\n    unfold stsim. iIntros (? ? ? ? ?) \"D\".\n    iApply isim_UB. auto.\n  Qed.\n\n  Lemma stsim_observe E fn args r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src ktr_tgt\n    :\n    (∀ ret, stsim E g g Q true true (ktr_src ret) (ktr_tgt ret))\n      -∗\n      (stsim E r g Q ps pt (trigger (Observe fn args) >>= ktr_src) (trigger (Observe fn args) >>= ktr_tgt))\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n    iApply isim_observe. iIntros (?). iApply (\"H\" with \"D\").\n  Qed.\n\n  Lemma stsim_yieldL E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src ktr_tgt\n    :\n    (stsim E r g Q true pt (ktr_src tt) (trigger (Yield) >>= ktr_tgt))\n      -∗\n      (stsim E r g Q ps pt (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt))\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n    iApply isim_yieldL. iApply (\"H\" with \"D\").\n  Qed.\n\n  Lemma stsim_yieldR_strong E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src ktr_tgt l\n    :\n    (ObligationRA.duty (inl tid) l ** ObligationRA.tax l)\n      -∗\n      ((ObligationRA.duty (inl tid) l)\n         -*\n         (FairRA.white_thread (_Id:=_))\n         -*\n         (MUpd (nth_default True%I Invs) (fairI (ident_tgt:=ident_tgt)) E topset\n               (stsim topset r g Q ps true (trigger (Yield) >>= ktr_src) (ktr_tgt tt))))\n      -∗\n      (stsim E r g Q ps pt (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt))\n  .\n  Proof.\n    iIntros \"H K\".\n    unfold stsim. iIntros (? ? ? ? ?) \"[D C]\".\n    iPoseProof (default_I_past_update_ident_thread with \"D H\") as \"> [[B W] [[[[[[D0 D1] D2] D3] D4] D5] D6]]\".\n    iAssert ((fairI (ident_tgt:=ident_tgt)) ** mset_all (nth_default True%I Invs) E) with \"[C D5 D6]\" as \"C\".\n    { iFrame. }\n    iPoseProof (\"K\" with \"B W C\") as \"> [[[D5 D6] C] K]\".\n    iApply isim_yieldR. unfold I. iFrame.\n    iIntros (? ? ? ? ? ?) \"[D C] %\".\n    iApply (\"K\" with \"[D C]\"). iFrame. iExists _. eauto.\n  Qed.\n\n  Lemma stsim_sync_strong E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src ktr_tgt l\n    :\n    (ObligationRA.duty (inl tid) l ** ObligationRA.tax l)\n      -∗\n      ((ObligationRA.duty (inl tid) l)\n         -*\n         (FairRA.white_thread (_Id:=_))\n         -*\n         (MUpd (nth_default True%I Invs) (fairI (ident_tgt:=ident_tgt)) E topset\n               (stsim topset g g Q true true (ktr_src tt) (ktr_tgt tt))))\n      -∗\n      (stsim E r g Q ps pt (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt)).\n  Proof.\n    iIntros \"H K\".\n    unfold stsim. iIntros (? ? ? ? ?) \"[D C]\".\n    iPoseProof (default_I_past_update_ident_thread with \"D H\") as \"> [[B W] [[[[[[D0 D1] D2] D3] D4] D5] D6]]\".\n    iAssert ((fairI (ident_tgt:=ident_tgt)) ** mset_all (nth_default True%I Invs) E) with \"[C D5 D6]\" as \"C\".\n    { iFrame. }\n    iPoseProof (\"K\" with \"B W C\") as \"> [[[D5 D6] C] K]\".\n    iApply isim_sync. unfold I. iFrame.\n    iIntros (? ? ? ? ? ?) \"[D C] %\".\n    iApply (\"K\" with \"[D C]\"). iFrame. iExists _. eauto.\n  Qed.\n\n  Lemma stsim_yieldR E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src ktr_tgt l\n        (TOP: mset_sub topset E)\n    :\n    (ObligationRA.duty (inl tid) l ** ObligationRA.tax l)\n      -∗\n      ((ObligationRA.duty (inl tid) l)\n         -*\n         (FairRA.white_thread (_Id:=_))\n         -*\n         stsim topset r g Q ps true (trigger (Yield) >>= ktr_src) (ktr_tgt tt))\n      -∗\n      (stsim E r g Q ps pt (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt))\n  .\n  Proof.\n    iIntros \"H K\". iApply stsim_discard; [eassumption|].\n    iApply (stsim_yieldR_strong with \"H\"). iIntros \"DUTY WHITE\".\n    iModIntro. iApply (\"K\" with \"DUTY WHITE\").\n  Qed.\n\n  Lemma stsim_sync E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src ktr_tgt l\n        (TOP: mset_sub topset E)\n    :\n    (ObligationRA.duty (inl tid) l ** ObligationRA.tax l)\n      -∗\n      ((ObligationRA.duty (inl tid) l)\n         -*\n         (FairRA.white_thread (_Id:=_))\n         -*\n         stsim topset g g Q true true (ktr_src tt) (ktr_tgt tt))\n      -∗\n      (stsim E r g Q ps pt (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt)).\n  Proof.\n    iIntros \"H K\". iApply stsim_discard; [eassumption|].\n    iApply (stsim_sync_strong with \"H\"). iIntros \"DUTY WHITE\".\n    iModIntro. iApply (\"K\" with \"DUTY WHITE\").\n  Qed.\n\n\n  (* Note:  *)\n  (*   MUpd _ fairI topset topset P *)\n  (*        is a generalized version of I * (I -* P) *)\n  Lemma stsim_yieldR_simple E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src ktr_tgt\n        (TOP: mset_sub topset E)\n    :\n    MUpd (nth_default True%I Invs) (fairI (ident_tgt:=ident_tgt)) topset topset\n         ((FairRA.black_ex (inl tid) 1)\n            **\n            ((FairRA.black_ex (inl tid) 1)\n               -*\n               (FairRA.white_thread (_Id:=_))\n               -*\n               stsim topset r g Q ps true (trigger (Yield) >>= ktr_src) (ktr_tgt tt)))\n         -∗\n         (stsim E r g Q ps pt (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt))\n  .\n  Proof.\n    iIntros \"> [H K]\". iApply (stsim_yieldR with \"[H]\").\n    { auto. }\n    { iPoseProof (black_to_duty with \"H\") as \"H\". iFrame. }\n    iIntros \"B W\". iApply (\"K\" with \"[B] [W]\"); ss.\n    { iApply duty_to_black. auto. }\n  Qed.\n\n  Lemma stsim_sync_simple E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt ktr_src ktr_tgt\n        (TOP: mset_sub topset E)\n    :\n    MUpd (nth_default True%I Invs) (fairI (ident_tgt:=ident_tgt)) topset topset\n         ((FairRA.black_ex (inl tid) 1)\n            **\n            ((FairRA.black_ex (inl tid) 1)\n               -*\n               (FairRA.white_thread (_Id:=_))\n               -*\n               stsim topset g g Q true true (ktr_src tt) (ktr_tgt tt)))\n      -∗\n      (stsim E r g Q ps pt (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt)).\n  Proof.\n    iIntros \"> [H K]\". iApply (stsim_sync with \"[H]\").\n    { auto. }\n    { iPoseProof (black_to_duty with \"H\") as \"H\". iFrame. }\n    iIntros \"B W\". iApply (\"K\" with \"[B] [W]\"); ss.\n    { iApply duty_to_black. auto. }\n  Qed.\n\n  Lemma stsim_sort E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src itr_tgt\n    :\n    (stsim (NatSort.sort E) r g Q ps pt itr_src itr_tgt)\n      -∗\n      (stsim E r g Q ps pt itr_src itr_tgt)\n  .\n  Proof.\n    iApply stsim_discard.\n    rewrite <- NatSort.Permuted_sort. reflexivity.\n  Qed.\n\n  Lemma stsim_reset E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        ps pt itr_src itr_tgt\n    :\n    (stsim E r g Q false false itr_src itr_tgt)\n      -∗\n      (stsim E r g Q ps pt itr_src itr_tgt)\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n    iApply isim_reset. iApply (\"H\" with \"D\").\n  Qed.\n\n  Lemma stsim_progress E r g R_src R_tgt\n        (Q: R_src -> R_tgt -> iProp)\n        itr_src itr_tgt\n    :\n    (stsim E g g Q false false itr_src itr_tgt)\n      -∗\n      (stsim E r g Q true true itr_src itr_tgt)\n  .\n  Proof.\n    unfold stsim. iIntros \"H\" (? ? ? ? ?) \"D\".\n    iApply isim_progress. iApply (\"H\" with \"D\").\n  Qed.\n\n  Definition ibot5 { T0 T1 T2 T3 T4} (x0: T0) (x1: T1 x0) (x2: T2 x0 x1) (x3: T3 x0 x1 x2) (x4: T4 x0 x1 x2 x3): iProp := False.\n  Definition ibot7 { T0 T1 T2 T3 T4 T5 T6} (x0: T0) (x1: T1 x0) (x2: T2 x0 x1) (x3: T3 x0 x1 x2) (x4: T4 x0 x1 x2 x3) (x5: T5 x0 x1 x2 x3 x4) (x6: T6 x0 x1 x2 x3 x4 x5): iProp := False.\n\nEnd STATE.\n\nFrom Fairness Require Export Red IRed.\n\nLtac lred := repeat (prw _red_gen 1 2 0).\nLtac rred := repeat (prw _red_gen 1 1 0).\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/src/logic/Weakest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.21353194140454754}}
{"text": "From Perennial.goose_lang Require Import prelude.\nFrom Perennial.goose_lang Require Export ffi.grove_prelude.\nFrom Perennial.program_proof Require Import proof_prelude.\nFrom Perennial.goose_lang.ffi Require Export grove_ffi_time_axiom.\nFrom Perennial.base_logic.lib Require Import ghost_var.\nFrom Goose.github_com.mit_pdos.gokv Require Import minlease.\nFrom iris.bi.lib Require Import fixpoint.\nFrom Perennial.base_logic Require Import lib.saved_prop.\nFrom Perennial.program_proof Require Import std_proof.\n\nSection proof.\n\nContext `{!heapGS Σ}.\nContext `{!ghost_varG Σ u64}.\nContext `{!ghost_varG Σ ()}.\nContext `{!savedPropG Σ }.\n\nContext {γtime:gname}.\n\nNotation is_time_lb := (is_time_lb γtime).\nNotation own_time := (own_time γtime).\n\n(* Q is the lease obligation *)\nDefinition underLease (N:namespace) (leaseExpiration:u64) (P:iProp Σ) (Q:iProp Σ) : iProp Σ :=\n  ∃ γprop γpostLeastTok,\n  saved_prop_own γprop (DfracOwn (1/2)) P ∗\n  inv N (∃ P',\n    saved_prop_own γprop (DfracOwn (1/2)) P' ∗\n    (P' ∗ (P' -∗ Q) ∨ is_time_lb leaseExpiration ∗ ghost_var γpostLeastTok 1 ())\n  ).\n\n(* Doesn't seem useful\nLemma underLease_mono P' P Q e N :\n  (P -∗ P') -∗\n  (P' -∗ Q) -∗\n  underLease N e P Q -∗\n  underLease N e P' Q\n.\nProof.\nAdmitted. *)\n\nLemma lease_acc_update N e P Q :\n  underLease N e P Q -∗\n  £ 1 -∗\n  £ 1 -∗\n  ∀ (t:u64),\n  ⌜int.nat t < int.nat e⌝ →\n  own_time t ={↑N,∅}=∗\n  (P ∗ (∀ P', P' -∗ (P' -∗ Q) ={∅,↑N}=∗ own_time t ∗ underLease N e P' Q))\n.\nProof.\n  iIntros \"Hlease Hlc Hlc2\".\n  iIntros (?) \"%Hineq Htime\".\n  iDestruct \"Hlease\" as (γprop ?) \"[Hprop #Hinv]\".\n  iInv \"Hinv\" as \"Hi\" \"Hclose\".\n  iMod (lc_fupd_elim_later with \"Hlc Hi\") as \"Hi\".\n  iDestruct \"Hi\" as (?) \"[Hprop2 Hi]\".\n  iDestruct (saved_prop_agree with \"Hprop Hprop2\") as \"#Hagree1\".\n  iMod (lc_fupd_elim_later with \"Hlc2 Hagree1\") as \"#Hagree\".\n  replace (↑N ∖ ↑N) with (∅:coPset) by set_solver.\n  iModIntro.\n  iDestruct \"Hi\" as \"[[HP HQwand]|[Hbad HpostLeastTok]]\"; last first.\n  {\n    iDestruct (mono_nat_lb_own_valid with \"Htime Hbad\") as %[_ Hbad].\n    exfalso.\n    word.\n  }\n  iSplitL \"HP\".\n  {\n    by iRewrite \"Hagree\".\n  }\n  iIntros (R) \"HR HRwandQ\".\n  iMod (saved_prop_update_2 R with \"Hprop Hprop2\") as \"[Hprop Hprop2]\".\n  { apply Qp.half_half. }\n  iFrame \"Htime\".\n  iMod (\"Hclose\" with \"[HRwandQ HR Hprop2]\").\n  {\n    iNext.\n    iExists _; iFrame \"Hprop2\".\n    iLeft.\n    iFrame.\n  }\n  iModIntro.\n  iExists _, _; iFrame \"∗#\".\nQed.\n\nDefinition postLease (N:namespace) (leaseExpiration:u64) (Q:iProp Σ) : iProp Σ :=\n  is_time_lb leaseExpiration ={↑N}=∗ ▷ Q\n.\n\nLemma lease_alloc e Q N P :\n  P -∗ (P -∗ Q) ={↑N}=∗\n  underLease N e P Q ∗\n  postLease N e Q\n.\nProof.\n  iIntros \"HP Hwand\".\n  iMod (saved_prop_alloc P (DfracOwn 1)) as (γprop) \"[Hprop Hprop2]\".\n  { done. }\n  iMod (ghost_var_alloc ()) as (γpostLeaseTok) \"HpostLeaseTok\".\n  iAssert (|={↑N}=>\n  inv N (∃ P',\n    saved_prop_own γprop (DfracOwn (1/2)) P' ∗\n    (P' ∗ (P' -∗ Q) ∨ is_time_lb e ∗ ghost_var γpostLeaseTok 1 ())\n  ))%I with \"[HP Hwand Hprop2]\" as \">#Hinv\".\n  {\n    iMod (inv_alloc with \"[-]\") as \"$\"; last done.\n    iNext.\n    iExists _; iFrame \"Hprop2\".\n    iLeft. iFrame.\n  }\n  iModIntro.\n  iSplitL \"Hprop\".\n  {\n    iExists _, _; iFrame \"∗#\".\n  }\n  iIntros \"Hlb\".\n  iInv \"Hinv\" as \"Hi\" \"Hclose\".\n  iDestruct \"Hi\" as (?) \"[Hprop HP]\".\n  iDestruct \"HP\" as \"[HP |[_ >Hbad]]\"; last first.\n  {\n    iDestruct (ghost_var_valid_2 with \"Hbad HpostLeaseTok\") as %[Hbad _].\n    exfalso.\n    done.\n  }\n  iDestruct \"HP\" as \"[HP HPwand]\".\n  iDestruct (later_wand with \"HPwand\") as \"HPwand\".\n  iMod (\"Hclose\" with \"[Hprop HpostLeaseTok Hlb]\").\n  {\n    iExists _; iFrame.\n    iRight.\n    iFrame.\n  }\n  iApply \"HPwand\".\n  done.\nQed.\n\n(* P are resources you can access and modify at the moment you check that the\n   lease is unexpired.\n *)\n\nDefinition own_Server s γ : iProp Σ :=\n  ∃ (v:u64),\n  \"Hval\" ∷ s ↦[Server :: \"val\"] #v ∗\n  \"Hauth\" ∷ ghost_var γ (1/2) v\n.\n\n\nDefinition LEASE_EXP := U64 10.\n\nDefinition minleaseN := nroot .@ \"minlease\".\n\nDefinition is_Server s γ : iProp Σ :=\n  ∃ mu,\n  \"#Hmu\" ∷ readonly (s ↦[Server :: \"mu\"] mu) ∗\n  \"#HleaseExpiration\" ∷ readonly (s ↦[Server :: \"leaseExpiration\"] #LEASE_EXP) ∗\n  \"#HmuInv\" ∷ is_lock minleaseN mu (own_Server s γ)\n.\n\nLemma wp_Put s (v:u64) γ Φ :\nis_Server s γ -∗\n(|={⊤,∅}=> ∃ (oldv:u64), ghost_var γ (1/2) oldv ∗\n(ghost_var γ (1/2) v ={∅,⊤}=∗ Φ #()) )-∗\n  WP Server__Put #s #v {{ Φ }}\n.\nProof.\n  iIntros \"Hsrv Hupd\".\n  iNamed \"Hsrv\".\n  wp_lam.\n  wp_pures.\n  wp_loadField.\n  wp_apply (acquire_spec with \"HmuInv\").\n  iIntros \"[Hlocked Hown]\".\n  iNamed \"Hown\".\n  wp_pures.\n  wp_storeField.\n  wp_loadField.\n\n  iApply fupd_wp.\n  iMod \"Hupd\" as (?) \"[Hval2 Hupd]\".\n  iMod (ghost_var_update_2 with \"Hauth Hval2\") as \"[Hauth Hval2]\".\n  { apply Qp.half_half. }\n  iMod (\"Hupd\" with \"Hval2\") as \"HΦ\".\n  iModIntro.\n  wp_apply (release_spec with \"[-HΦ]\").\n  {\n    iFrame \"HmuInv Hlocked\".\n    iNext.\n    repeat iExists _; iFrame \"∗#%\".\n  }\n  wp_pures.\n  by iFrame.\nQed.\n\nLemma wp_Get s γ Φ :\nis_Server s γ -∗\n(|={⊤,∅}=> ∃ (v:u64), ghost_var γ (1/2) v ∗\n(ghost_var γ (1/2) v ={∅,⊤}=∗ Φ #v) )-∗\n  WP Server__Get #s {{ Φ }}\n.\nProof.\n  iIntros \"Hsrv Hupd\".\n  iNamed \"Hsrv\".\n  wp_lam.\n  wp_pures.\n  wp_loadField.\n  wp_apply (acquire_spec with \"HmuInv\").\n  iIntros \"[Hlocked Hown]\".\n  iNamed \"Hown\".\n  wp_pures.\n  wp_loadField.\n  wp_loadField.\n\n  iApply fupd_wp.\n  iMod \"Hupd\" as (?) \"[Hval2 Hupd]\".\n  iDestruct (ghost_var_valid_2 with \"Hauth Hval2\") as %[_ ->].\n  iMod (\"Hupd\" with \"Hval2\") as \"HΦ\".\n  iModIntro.\n  wp_apply (release_spec with \"[-HΦ]\").\n  {\n    iFrame \"HmuInv Hlocked\".\n    iNext.\n    repeat iExists _; iFrame \"∗#%\".\n  }\n  wp_pures.\n  by iFrame.\nQed.\n\nLemma wp_StartServer γ :\n  {{{\n      \"Hlease\" ∷ underLease minleaseN LEASE_EXP (ghost_var γ (1/2) (U64 0)) (∃ (v:u64), (ghost_var γ (1/2) v)) ∗\n      \"Hauth\" ∷ ghost_var γ (1/2) (U64 0)\n  }}}\n    StartServer #()\n  {{{\n        s, RET #s; is_Server s γ\n  }}}\n.\nProof.\n  iIntros (Φ) \"Hpre HΦ\".\n  iNamed \"Hpre\".\n  wp_lam.\n  wp_apply (wp_allocStruct).\n  { repeat constructor. }\n  iIntros (?) \"Hl\".\n  iDestruct (struct_fields_split with \"Hl\") as \"HH\".\n  iNamed \"HH\".\n  wp_pures.\n  wp_apply (wp_new_free_lock).\n  iIntros (mu) \"HmuInv\".\n  wp_storeField.\n  wp_storeField.\n  wp_storeField.\n  iMod (readonly_alloc_1 with \"mu\") as \"#Hmu\".\n  iMod (readonly_alloc_1 with \"leaseExpiration\") as \"#HleaseExpiration\".\n\n  iAssert (|={⊤}=> is_Server l γ)%I with \"[-HΦ Hlease]\" as \">#Hsrv\".\n  {\n    repeat iExists _.\n    iFrame \"∗#%\".\n    iDestruct (alloc_lock with \"HmuInv [-]\") as \"$\".\n    iNext.\n    repeat iExists _; iFrame \"∗#%\".\n  }\n\n  wp_apply (wp_fork with \"[-HΦ]\").\n  {\n    iNext.\n    wp_pure1_credit \"Hlc1\".\n    wp_pure1_credit \"Hlc2\".\n    wp_pures.\n    iAssert  ( ∃ v,\n      \"Hlease\" ∷ underLease minleaseN LEASE_EXP (ghost_var γ (1 / 2) v%Z)\n               (∃ v' : u64, ghost_var γ (1 / 2) v')\n               )%I with \"[Hlease]\" as \"HH\" .\n    { iExists _. iFrame. }\n    wp_forBreak_cond.\n    wp_pures.\n    wp_lam.\n    iClear \"Hmu HleaseExpiration\".\n    iNamed \"Hsrv\".\n    wp_loadField.\n    wp_apply (acquire_spec with \"HmuInv\").\n    iIntros \"[Hlocked Hown]\".\n    wp_pures.\n    wp_apply (wp_GetTimeRange γtime).\n    iIntros (low high t) \"%Hineq1 %Hineq2 Htime\".\n    iNamed \"HH\".\n\n    destruct (decide (int.nat LEASE_EXP < int.nat high)).\n    2:{ (* case: lease is not expired *)\n      iDestruct (lease_acc_update with \"Hlease Hlc1 Hlc2\") as \"HH\".\n      iDestruct (\"HH\" $! t with \"[%] Htime\") as \"HH\".\n      { word. }\n      iMod (fupd_mask_subseteq _) as \"Hmask\"; last iMod \"HH\".\n      { set_solver. }\n      iNamed \"Hown\".\n      iDestruct \"HH\" as \"[Hval2 HcloseLease]\".\n      iDestruct (ghost_var_valid_2 with \"Hauth Hval2\") as %[_ ->].\n      iMod (ghost_var_update_2 (word.add v 1) with \"Hauth Hval2\") as \"[Hauth Hval2]\".\n      { apply Qp.half_half. }\n\n      iMod (\"HcloseLease\" $!_ with \"Hval2 []\") as \"[Htime Hlease]\".\n      {\n        iIntros. iExists _; iFrame.\n      }\n      iMod \"Hmask\".\n      iModIntro.\n      iFrame \"Htime\".\n      wp_pure1_credit \"Hlc1\".\n      wp_pure1_credit \"Hlc2\".\n      wp_loadField.\n      wp_pures.\n      wp_bind (If (#(bool_decide _)) _ _).\n      wp_if_destruct.\n      1:{\n        exfalso.\n        word.\n      }\n      wp_loadField.\n      wp_apply (wp_SumAssumeNoOverflow).\n      iIntros \"%Hoverflow\".\n      wp_storeField.\n      wp_loadField.\n      wp_apply (release_spec with \"[-Hlease Hlc1 Hlc2]\").\n      {\n        iFrame \"HmuInv Hlocked\".\n        repeat iExists _; iFrame \"∗#%\".\n      }\n      wp_pures.\n      iLeft.\n      iModIntro.\n      iSplitR; first done.\n      iFrame.\n      iExists _.\n      iFrame.\n    }\n    (* Otherwise, lease has expired *)\n    iModIntro.\n    iFrame.\n    wp_pures.\n    wp_loadField.\n    wp_pures.\n    wp_bind (If (#(bool_decide _)) _ _).\n    wp_if_destruct.\n    2:{ exfalso. word. }\n    wp_loadField.\n    wp_apply (release_spec with \"[-Hlease]\").\n    {\n      iFrame \"HmuInv Hlocked\". iFrame.\n    }\n    wp_pures.\n    iRight.\n    iModIntro.\n    done.\n  }\n  wp_pures.\n  iModIntro.\n  iApply \"HΦ\".\n  done.\nQed.\n\nLemma wp_client s γ :\n  {{{\n      \"#Hsrv\" ∷ is_Server s γ ∗\n      \"HpostLease\" ∷ postLease minleaseN LEASE_EXP (∃ (v':u64), ghost_var γ (1/2) v')\n  }}}\n    client #s\n  {{{\n      RET #(); True\n  }}}\n.\nProof.\n  iIntros (Φ) \"Hpre HΦ\".\n  iNamed \"Hpre\".\n  wp_call.\n  wp_forBreak.\n  wp_pures.\n  wp_apply (wp_GetTimeRange γtime).\n  iIntros (low high t Hineq1 Hineq) \"Htime\".\n\n  iAssert (_) with \"Hsrv\" as \"Hsrv2\".\n  iNamed \"Hsrv2\".\n\n  destruct (decide (int.nat LEASE_EXP < int.nat low)).\n  {\n    iDestruct (mono_nat_lb_own_get with \"Htime\") as \"#Hlb\".\n    unfold postLease.\n    iMod (fupd_mask_subseteq _) as \"Hmask\";\n      last iMod (\"HpostLease\" with \"[Hlb]\") as \"HpostLease\".\n    { set_solver. }\n    { iApply mono_nat_lb_own_le; last iFrame \"#\". word. }\n    iMod \"Hmask\" as \"_\".\n    iModIntro.\n    iFrame \"Htime\".\n    wp_pures.\n    iDestruct \"HpostLease\" as (?) \"Hghost\".\n    wp_loadField.\n    wp_pures.\n    wp_if_destruct.\n    2:{ exfalso. word. }\n    iModIntro.\n    iRight.\n    iSplitR; first done.\n    wp_pures.\n    wp_apply (wp_Get with \"Hsrv\").\n    iApply fupd_mask_intro.\n    { set_solver. }\n    iIntros \"Hmask\".\n    iExists _; iFrame.\n    iIntros \"Hvar\".\n    iMod \"Hmask\" as \"_\".\n    iModIntro.\n    wp_pures.\n    wp_apply wp_SumAssumeNoOverflow.\n    iIntros (HnoOverflow).\n    wp_pures.\n    wp_apply (wp_Put with \"Hsrv\").\n    iApply fupd_mask_intro.\n    { set_solver. }\n    iIntros \"Hmask\".\n    iExists _; iFrame.\n    iIntros \"Hvar\".\n    iMod \"Hmask\" as \"_\".\n    iModIntro.\n    wp_pures.\n    wp_apply (wp_Get with \"Hsrv\").\n    iApply fupd_mask_intro.\n    { set_solver. }\n    iIntros \"Hmask\".\n    iExists _; iFrame.\n    iIntros \"Hvar\".\n    iMod \"Hmask\" as \"_\".\n    iModIntro.\n    wp_pures.\n    wp_apply (wp_Assert).\n    { apply bool_decide_true. done. }\n    wp_pures.\n    iModIntro.\n    by iApply \"HΦ\".\n  }\n  { (* loop and wait for server's lease to expire *)\n    iFrame \"Htime\".\n    iModIntro.\n    wp_pures.\n    wp_loadField.\n    wp_pures.\n    wp_if_destruct.\n    { exfalso. word. }\n    wp_loadField.\n    wp_apply wp_Sleep.\n    wp_pures.\n    iLeft.\n    iFrame.\n    done.\n  }\nQed.\n\nLemma wp_main :\n  {{{\n       True\n  }}}\n    main #()\n  {{{\n        RET #(); True\n  }}}\n.\nProof using Type* γtime.\n  iIntros (Φ) \"_ HΦ\".\n  wp_lam.\n  iMod (ghost_var_alloc (U64 0)) as (γ) \"[Hvar Hvar2]\".\n  iApply fupd_wp.\n  iMod (fupd_mask_subseteq (↑minleaseN)) as \"Hmask\".\n  { set_solver. }\n  iMod (lease_alloc LEASE_EXP (∃ v:u64, ghost_var γ (1/2) v) with \"Hvar2 []\") as \"[Hlease HpostLease]\".\n  { iIntros. iExists _; iFrame. }\n  iMod \"Hmask\".\n  iModIntro.\n  wp_apply (wp_StartServer with \"[$Hlease $Hvar]\").\n  iIntros (s) \"#Hsrv\".\n  wp_pures.\n  wp_apply (wp_client with \"[$Hsrv $HpostLease]\").\n  wp_pures.\n  iModIntro.\n  by iApply \"HΦ\".\nQed.\n\nEnd proof.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/minlease/proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.21347788529698888}}
{"text": "(*\n * © 2020 Massachusetts Institute of Technology.\n * MIT Proprietary, Subject to FAR52.227-11 Patent Rights - Ownership by the Contractor (May 2014)\n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n     Eqdep\n     List\n     Lia.\n\nFrom SPICY Require Import\n     MyPrelude\n     Maps\n     ChMaps\n     Messages\n     Keys\n     Automation\n     Tactics\n     Simulation\n     SyntacticallySafe\n     AdversaryUniverse\n\n     ModelCheck.Commutation\n     ModelCheck.InvariantSearch\n     ModelCheck.ProtocolFunctions\n     ModelCheck.ModelCheck\n     ModelCheck.SilentStepElimination\n     ModelCheck.SteppingTactics\n     ModelCheck.UniverseInversionLemmas\n.\n\nFrom protocols Require Import\n     PGP.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations\n       SimulationAutomation.\n\nSet Implicit Arguments.\n\nOpen Scope protocol_scope.\n\n\nModule PGPProtocolSecure <: AutomatedSafeProtocolSS.\n\n  Import PGPProtocol.\n\n  Definition t__hon := Nat.\n  Definition t__adv := Unit.\n  Definition b := tt.\n  Definition iu0  := ideal_univ_start.\n  Definition ru0  := real_univ_start.\n\n  #[export] Hint Unfold t__hon t__adv b ru0 iu0 ideal_univ_start real_univ_start : core.\n\n  Lemma finitelyRuns : exists n, runningTimeMeasure ru0 n.\n  Proof.\n    autounfold; simpl.\n    eexists.\n    econstructor; simpl; find_runtime.\n\n    Unshelve.\n    all: exact 0.\n  Qed.\n\n  Lemma typechecks : syntactically_safe_U ru0.\n  Proof.\n    unfold syntactically_safe_U; intros.\n    autounfold\n    ; subst\n    ; simpl in *.\n\n    unfold compute_ids; simpl.\n    \n    focus_user; simpl\n    ; try solve [ do 2 eexists; split\n                  ; [ unshelve (repeat typechecks1)\n                      ; match goal with\n                        | [ |- bool ] => exact true\n                        | [ |- list safe_typ ] => exact []\n                        end\n                    | repeat verify_context_soundness ] ].\n\n    Unshelve.\n    all : exact TyDontCare.\n  Qed.\n    \n  Lemma summarizable : exists summaries, summarize_univ ru0 summaries.\n  Proof.\n    autounfold; unfold summarize_univ; simpl; intros.\n    unshelve (\n        eexists; intros; focus_user; simpl\n        ; (exists useless_summary; split; [ build_summary |]; eauto using useless_summary_summarizes)\n      ) ; exact $0.\n  Qed.\n    \n  Lemma lameness : @lameAdv t__adv b (RealWorld.adversary ru0).\n  Proof.\n    unfold lameAdv; autounfold; simpl; eauto.\n  Qed.\n\n  Import Gen Tacs.\n\n  Locate safety_inv.\n\n  Set Ltac Profiling.\n\n  Lemma safe_invariant :\n    invariantFor\n      {| Initial := {(ru0, iu0, true)}; Step := @stepSS t__hon t__adv  |}\n      (@noresends_inv t__hon t__adv).\n  Proof.\n    unfold invariantFor\n    ; unfold Initial, Step\n    ; intros\n    ; simpl in *\n    ; split_ors\n    ; try contradiction\n    ; subst.\n\n    autounfold in H0\n    ; unfold fold_left, fst, snd in *.\n    unfold real_users, ideal_users, mkrUsr, userProto, userKeys, userId, mkiUsr in *; rwuf.\n\n    time (\n        repeat transition_system_step\n      ).\n      \n    Unshelve.\n    all: eauto.\n  Qed.\n\n  Show Ltac Profile.\n      \n  Lemma U_good : @universe_starts_sane _ Unit b ru0.\n  Proof.\n    autounfold;\n      unfold universe_starts_sane; simpl.\n    repeat (apply conj); intros; eauto.\n    - focus_user; auto.\n    - econstructor.\n    - unfold AdversarySafety.keys_honest; rewrite Forall_natmap_forall; intros.\n      unfold mkrUsr; simpl.\n      rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty; eauto.\n    - unfold lameAdv; simpl; eauto.\n  Qed.\n\n  Lemma universe_starts_safe : universe_ok ru0.\n  Proof.\n    pose proof (adversary_is_lame_adv_univ_ok_clauses U_good).\n    \n    unfold universe_ok\n    ; autounfold\n    ; simpl\n    ; intuition eauto\n    .\n\n    - econstructor; eauto.\n    - unfold keys_and_permissions_good; solve_simple_maps; intuition eauto.\n      solve_simple_maps; eauto.\n\n      rewrite Forall_natmap_forall; intros.\n\n      solve_simple_maps; simpl\n      ; unfold permission_heap_good; intros;\n        solve_simple_maps; solve_concrete_maps; eauto.\n\n    - unfold user_cipher_queues_ok.\n      rewrite Forall_natmap_forall; intros.\n      focus_user\n      ; simpl in *; econstructor; eauto.\n\n    - unfold honest_nonces_ok, honest_user_nonces_ok, honest_nonces_ok\n      ; repeat simple apply conj\n      ; intros\n      ; clean_map_lookups\n      ; intros\n      ; focus_user\n      ; try contradiction; try discriminate; simpl;\n        repeat (apply conj); intros; clean_map_lookups; eauto.\n\n    - unfold honest_users_only_honest_keys; intros.\n      focus_user;\n        subst;\n        simpl in *;\n        clean_map_lookups;\n        unfold mkrUsr; simpl; \n          rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty;\n          eauto;\n          simpl in *;\n          solve_concrete_perm_merges;\n          solve_concrete_maps;\n          solve_simple_maps;\n          eauto.\n  Qed.\nEnd PGPProtocolSecure.\n\n(* Module ProtoCorrect := SSProtocolSimulates (PGPProtocolSecure). *)\n(* Print Assumptions ProtoCorrect.protocol_with_adversary_could_generate_spec. *)\n", "meta": {"author": "mit-ll", "repo": "SPICY", "sha": "ad89c31a093ed2e0b7b4ef55c87ec9b175749fe0", "save_path": "github-repos/coq/mit-ll-SPICY", "path": "github-repos/coq/mit-ll-SPICY/SPICY-ad89c31a093ed2e0b7b4ef55c87ec9b175749fe0/protocols/Verification/PGPSecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.21342834157767898}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import CtxtSwitchAux.Spec.\nRequire Import AbsAccessor.Spec.\nRequire Import CtxtSwitch.Specs.restore_ns_state.\nRequire Import CtxtSwitch.LowSpecs.restore_ns_state.\nRequire Import CtxtSwitch.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       restore_ns_state_sysreg_state_spec\n       get_ns_state_spec\n       sysreg_write_spec\n    .\n\n  Lemma restore_realm_state_spec_exists:\n    forall habd habd'  labd\n      (Hspec: restore_ns_state_spec  habd = Some habd')\n      (Hrel: relate_RData habd labd),\n    exists labd', restore_ns_state_spec0  labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque ptr_eq.\n    intros. destruct Hrel.\n    unfold restore_ns_state_spec, restore_ns_state_spec0 in *.\n    repeat autounfold in *. simpl in *.\n    hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec;\n      repeat destruct_con; bool_rel; simpl in *; srewrite;\n        repeat (simpl_htarget; grewrite; simpl in * ).\n    destruct regs_is_int64_dec in *. autounfold in e. repeat rewrite e.\n    repeat simpl_update_reg.\n    eexists; split. reflexivity. constructor. reflexivity.\n    inv C.\n  Qed.\n\nEnd Refine.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/CtxtSwitch/RefProof/restore_realm_state.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21342241572092177}}
{"text": "Require Import Coq.Strings.String.\nRequire Import bedrock2.Syntax.\nRequire Import bedrock2.Map.Separation.\nRequire Import bedrock2.Map.SeparationLogic.\nRequire Import coqutil.Map.Interface coqutil.Map.Properties.\nRequire Import coqutil.Word.Interface coqutil.Word.Properties.\nRequire Import coqutil.Datatypes.PropSet.\nRequire Import Coq.Lists.List. (* after SeparationLogic *)\nRequire Import Crypto.Bedrock.Field.Common.Types.\nRequire Import Crypto.Bedrock.Field.Translation.Proofs.Equivalence.\nRequire Import Crypto.Bedrock.Field.Translation.Proofs.UsedVarnames.\nRequire Import Crypto.Bedrock.Field.Translation.Proofs.VarnameSet.\nRequire Import Crypto.Bedrock.Field.Common.Tactics.\nRequire Import Crypto.Bedrock.Field.Common.Util.\nRequire Import Crypto.Language.API.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.Tactics.DestructHead.\n\nImport API.Compilers.\nImport ListNotations Types.Notations.\n\nSection OnlyDiffer.\n  Context \n    {width BW word mem locals env ext_spec varname_gen error}\n   `{parameters_sentinel : @parameters width BW word mem locals env ext_spec varname_gen error}.\n  Context {ok : ok}.\n  Local Existing Instance Types.rep.Z.\n\n  Lemma equiv_Z_only_differ_iff1\n        {listZ : rep.rep base_listZ}\n        locals1 locals2 vset (varname : base_ltype base_Z) s x :\n    map.only_differ locals1 vset locals2 ->\n    disjoint vset (varname_set_base varname) ->\n    Lift1Prop.iff1\n      (rep.equiv x (rep.rtype_of_ltype varname) s locals1)\n      (rep.equiv x (rep.rtype_of_ltype varname) s locals2).\n  Proof.\n    cbn [varname_set_base\n           rep.varname_set rep.equiv rep.rtype_of_ltype rep.Z].\n    cbv [WeakestPrecondition.dexpr].\n    rewrite <-disjoint_singleton_r_iff by eauto using string_dec.\n    split; intros; sepsimpl; subst; eexists; sepsimpl; eauto;\n      eapply expr_untouched; eauto using @only_differ_sym with typeclass_instances.\n  Qed.\n\n  Lemma equiv_Z_only_differ_undef {listZ:rep.rep base_listZ} :\n    forall x y s locals locals' vset,\n      map.only_differ locals vset locals' ->\n      map.undef_on locals vset ->\n      Lift1Prop.impl1\n        (equivalent_base (t:=base_Z) x y s locals)\n        (equivalent_base x y s locals').\n  Proof.\n    cbv [equivalent_base rep.equiv rep.Z WeakestPrecondition.dexpr].\n    repeat intro; sepsimpl; subst; eexists; sepsimpl; eauto.\n    eauto using expr_only_differ_undef.\n  Qed.\n\n  Section Local.\n    Local Existing Instance rep.listZ_local.\n\n    Lemma equiv_listZ_only_differ_local : forall\n          locals1 locals2 vset (varnames : base_ltype base_listZ) s x (mem : mem),\n      map.only_differ locals1 vset locals2 ->\n      disjoint vset (varname_set_base varnames) ->\n      rep.equiv x (rep.rtype_of_ltype varnames) s locals1 mem ->\n      rep.equiv x (rep.rtype_of_ltype varnames) s locals2 mem.\n    Proof.\n      intros *.\n      cbn [rep.equiv rep.rtype_of_ltype rep.listZ_local\n                     varname_set rep.varname_set].\n      rewrite !Forall.Forall2_map_r_iff.\n      revert x; induction varnames; intros;\n        match goal with H : Forall2 _ _ _ |- _ =>\n                        inversion H; subst; clear H end;\n        [ solve [eauto] | ].\n      cbn [fold_right] in *; cbv [emp] in *. cleanup.\n      constructor.\n      { eapply equiv_Z_only_differ_iff1;\n          cbn [rep.equiv rep.Z]; cbv [emp];\n            destruct_head'_and;\n            eauto using @only_differ_sym with typeclass_instances.\n        cbv [varname_set rep.varname_set rep.Z] in *.\n        match goal with H : disjoint _ _ |- _ =>\n                        apply disjoint_union_r_iff in H;\n                          cleanup\n        end. eauto. }\n      { apply IHvarnames; eauto.\n        match goal with H : disjoint _ _ |- _ =>\n                        apply disjoint_union_r_iff in H;\n                          cleanup\n        end. eauto. }\n    Qed.\n\n    Lemma equiv_listZ_only_differ_local_iff1\n          locals1 locals2 vset (varnames : base_ltype base_listZ) s x :\n      map.only_differ locals1 vset locals2 ->\n      disjoint vset (varname_set_base varnames) ->\n      Lift1Prop.iff1\n        (rep.equiv x (rep.rtype_of_ltype varnames) s locals1)\n        (rep.equiv x (rep.rtype_of_ltype varnames) s locals2).\n    Proof.\n      cbv [Lift1Prop.iff1]; split; intros;\n        eapply equiv_listZ_only_differ_local;\n        eauto using @only_differ_sym with typeclass_instances.\n    Qed.\n\n    Lemma equiv_listZ_only_differ_undef_local :\n      forall x y s locals locals' vset,\n        map.only_differ locals vset locals' ->\n        map.undef_on locals vset ->\n        Lift1Prop.impl1\n          (equivalent_base (t:=base_listZ) x y s locals)\n          (equivalent_base x y s locals').\n    Proof.\n      cbn [equivalent_base rep.equiv rep.listZ_local]; intros; sepsimpl.\n      repeat intro; sepsimpl.\n      eapply Forall.Forall2_Proper_impl;\n        try eassumption; try reflexivity; repeat intro.\n      eapply (equiv_Z_only_differ_undef (listZ:=rep.listZ_local)); eauto.\n    Qed.\n  End Local.\n\n  Section InMemory.\n    Local Existing Instance rep.listZ_mem.\n\n    Lemma equiv_listZ_only_differ_mem\n          locals1 locals2 vset (varnames : base_ltype base_listZ) s x :\n          forall (mem : mem),\n      map.only_differ locals1 vset locals2 ->\n      disjoint vset (varname_set_base varnames) ->\n      rep.equiv x (rep.rtype_of_ltype varnames) s locals1 mem ->\n      rep.equiv x (rep.rtype_of_ltype varnames) s locals2 mem.\n    Proof.\n      intros *.\n      cbn [rep.equiv rep.rtype_of_ltype rep.listZ_mem\n                     varname_set rep.varname_set].\n      intros.\n      repeat match goal with\n               H : Lift1Prop.ex1 _ _ |- Lift1Prop.ex1 _ _ =>\n               let x := fresh in\n               destruct H as [x ?]; exists x\n             end.\n      eapply Proper_sep_iff1; [ | reflexivity | eassumption ].\n      cancel.\n      eapply equiv_Z_only_differ_iff1; eauto using @only_differ_sym with typeclass_instances.\n    Qed.\n\n    Lemma equiv_listZ_only_differ_mem_iff1\n          locals1 locals2 vset (varnames : base_ltype base_listZ) s x :\n      map.only_differ locals1 vset locals2 ->\n      disjoint vset (varname_set_base varnames) ->\n      Lift1Prop.iff1\n        (rep.equiv x (rep.rtype_of_ltype varnames) s locals1)\n        (rep.equiv x (rep.rtype_of_ltype varnames) s locals2).\n    Proof.\n      cbv [Lift1Prop.iff1]; split; intros;\n        eapply equiv_listZ_only_differ_mem;\n        eauto using @only_differ_sym with typeclass_instances.\n    Qed.\n\n    Lemma equiv_listZ_only_differ_undef_mem :\n      forall x y s locals locals' vset,\n        map.only_differ locals vset locals' ->\n        map.undef_on locals vset ->\n        Lift1Prop.impl1\n          (equivalent_base\n             (t:=base_listZ) (listZ:=rep.listZ_mem)\n             x y s locals)\n          (equivalent_base x y s locals').\n    Proof.\n      cbn [equivalent_base rep.equiv rep.listZ_mem]; intros; sepsimpl.\n      repeat intro; sepsimpl. eexists.\n      repeat intro; sepsimpl. eexists.\n      eapply Proper_sep_impl1; [ | reflexivity | eassumption ].\n      repeat intro; sepsimpl; eauto.\n      eapply (equiv_Z_only_differ_undef (listZ:=rep.listZ_mem)); eauto.\n    Qed.\n\n    Lemma equiv_nil_iff1 y s : forall (locals : locals),\n      Lift1Prop.iff1\n        (rep.equiv (rep:=rep.listZ_mem) [] y s locals)\n        (Lift1Prop.ex1\n           (fun x => rep.equiv (rep:=rep.Z) x y tt locals)).\n    Proof.\n      cbn [rep.equiv rep.listZ_mem rep.Z].\n      intro; split; intros;\n        repeat match goal with\n               | _ => progress subst\n               | _ => progress cbn [Array.array map] in *\n               | _ => progress sepsimpl\n               | H : map _ _ = [] |- _ =>\n                 apply map_eq_nil in H\n               | _ => rewrite word.of_Z_unsigned in *\n               | |- _ /\\ _ => split\n               | |- Lift1Prop.ex1 _ _ => eexists\n               | |- emp _ _ => cbv [emp]\n               | _ => solve [apply word.unsigned_range]\n               | _ => solve [eauto using map_nil]\n               end.\n    Qed.\n\n    Lemma varname_set_listonly_listexcl {t} (names : _ t) :\n      sameset\n        (varname_set_base names)\n        (union (varname_set_listonly names)\n               (varname_set_listexcl names)).\n    Proof.\n      induction t;\n        cbn [fst snd varname_set_base varname_set_listexcl\n                 varname_set_listonly];\n        break_match; intros;\n          rewrite ?union_empty_l, ?union_empty_r;\n          try reflexivity; [ ].\n      rewrite IHt1, IHt2.\n      clear. firstorder idtac.\n    Qed.\n\n    Lemma varname_set_listexcl_subset {t} (names : base_ltype t) :\n      subset (varname_set_listexcl names) (varname_set_base names).\n    Proof.\n      rewrite varname_set_listonly_listexcl.\n      clear. firstorder idtac.\n    Qed.\n  End InMemory.\n\n  Section Generic.\n    Context {listZ : rep.rep base_listZ}\n            (equiv_listZ_only_differ_undef :\n               forall x y s locals1 locals2 vset,\n                 map.only_differ locals1 vset locals2 ->\n                 map.undef_on locals1 vset ->\n                 Lift1Prop.impl1\n                   (rep.equiv (rep:=listZ) x y s locals1)\n                   (rep.equiv x y s locals2))\n            (equiv_listZ_only_differ :\n               forall\n                 locals1 locals2 vset\n                 (varnames : base_ltype base_listZ) s x mem,\n                 map.only_differ locals1 vset locals2 ->\n                 disjoint vset (varname_set_base varnames) ->\n                 rep.equiv x (rep.rtype_of_ltype varnames) s locals1 mem ->\n                 rep.equiv x (rep.rtype_of_ltype varnames) s locals2 mem).\n\n    Lemma equivalent_only_differ {t}\n          locals1 locals2 vset (varnames : base_ltype t) s x :\n      map.only_differ locals1 vset locals2 ->\n      disjoint vset (varname_set_base varnames) ->\n      forall mem,\n        equivalent_base x (base_rtype_of_ltype varnames) s locals1 mem ->\n        equivalent_base x (base_rtype_of_ltype varnames) s locals2 mem.\n    Proof.\n      intros Hdiffer Hexcl.\n      induction t;\n        cbn [fst snd rtype_of_ltype varname_set_base equivalent_base] in *;\n        intros; break_match; destruct_head'_and; try tauto.\n      { (* base case *)\n        eapply equiv_Z_only_differ_iff1; eauto using @only_differ_sym with typeclass_instances. }\n      { (* prod case *)\n        match goal with H : disjoint _ (union _ _) |- _ =>\n                        apply disjoint_union_r_iff in H\n        end.\n        cleanup.\n        eapply Proper_sep_impl1; [ | | eassumption]; repeat intro; eauto.\n        { apply IHt1; eauto. }\n        { apply IHt2; eauto. } }\n      { (* list case *)\n        eapply equiv_listZ_only_differ; eauto. }\n    Qed.\n\n    Lemma equivalent_only_differ_iff1 {t}\n          locals1 locals2 vset (varnames : base_ltype t) s x :\n      map.only_differ locals1 vset locals2 ->\n      disjoint vset (varname_set_base varnames) ->\n      Lift1Prop.iff1\n        (equivalent_base x (base_rtype_of_ltype varnames) s locals1)\n        (equivalent_base x (base_rtype_of_ltype varnames) s locals2).\n    Proof.\n      repeat intro. split; intros.\n      all:eapply equivalent_only_differ; eauto using @only_differ_sym with typeclass_instances.\n    Qed.\n\n    Lemma equivalent_args_only_differ {t}\n          locals1 locals2 vset\n          (argnames : type.for_each_lhs_of_arrow ltype t)\n          s x :\n      map.only_differ locals1 vset locals2 ->\n      disjoint vset (varname_set_args argnames) ->\n      let argvalues :=\n          type.map_for_each_lhs_of_arrow\n            rtype_of_ltype argnames in\n      forall m,\n        equivalent_args x argvalues s locals1 m ->\n        equivalent_args x argvalues s locals2 m.\n    Proof.\n      induction t;\n        cbv [Lift1Prop.iff1];\n        cbn [fst snd rtype_of_ltype varname_set_args\n                 type.map_for_each_lhs_of_arrow\n                 equivalent_args];\n        intros; break_match; cbn [fst snd] in *;\n          try tauto; [ ].\n      intros; cleanup; subst.\n      repeat match goal with\n             | |- _ /\\ _ => split\n             | |- exists _, _ => eexists\n             | _ => solve [eauto]\n             end;\n        [ eapply Proper_sep_iff1;\n          [ eapply equivalent_only_differ_iff1\n          | reflexivity | eassumption ] | eapply IHt2 ];\n        eauto using @only_differ_sym with typeclass_instances.\n      all:match goal with\n          | H : disjoint _ (union _ _) |- _ =>\n            apply disjoint_union_r_iff in H;\n              cleanup; eauto\n          end.\n    Qed.\n\n    Lemma equivalent_only_differ_undef {t} :\n      forall locals1 locals2 vset x y s,\n        map.only_differ locals1 vset locals2 ->\n        map.undef_on locals1 vset ->\n        Lift1Prop.impl1\n          (equivalent_base (t:=t) x y s locals1)\n          (equivalent_base x y s locals2).\n    Proof.\n      induction t;\n        cbn [equivalent_base];\n        break_match; intros; try reflexivity; [ | | ].\n      { eapply equiv_Z_only_differ_undef; eauto. }\n      { apply Proper_sep_impl1; eauto. }\n      { eapply equiv_listZ_only_differ_undef; eauto. }\n    Qed.\n  End Generic.\nEnd OnlyDiffer.\nGlobal Hint Resolve\n     equiv_listZ_only_differ_undef_local\n     equiv_listZ_only_differ_undef_mem\n     equiv_listZ_only_differ_local\n     equiv_listZ_only_differ_mem : equiv.\n\nSection ContextEquivalence.\n  Context \n    {width BW word mem locals env ext_spec varname_gen error}\n   `{parameters_sentinel : @parameters width BW word mem locals env ext_spec varname_gen error}.\n  Context {ok : ok}.\n  Local Existing Instance Types.rep.Z.\n\n  Section Local.\n    Local Existing Instance Types.rep.listZ_local.\n\n    (* 3-way equivalence (for single elements of the context list G\n       from wf3 preconditions) *)\n    Definition equiv3 {var1}\n               (locals : Interface.map.rep (map:=locals))\n               (x : {t : API.type\n                         & (var1 t * API.interp_type t * ltype t)%type})\n      : Prop :=\n      match x with\n      | existT (type.base b) (w, x, y) =>\n        locally_equivalent x (base_rtype_of_ltype y) locals\n      | existT (type.arrow _ _) _ => False (* no functions allowed *)\n      end.\n\n    Definition context_equiv {var1} G locals\n      : Prop := Forall (equiv3 (var1:= var1) locals) G.\n\n    Fixpoint context_varname_set {var1}\n             (G : list {t : API.type & (var1 t * API.interp_type t * ltype t)%type})\n      : PropSet.set string :=\n      match G with\n      | (existT (type.base b) (w, x, y)) :: G' =>\n        union (varname_set y) (context_varname_set G')\n      |  _ => PropSet.empty_set (* no functions allowed *)\n      end.\n\n    Lemma varname_set_local x :\n      sameset\n        (rep.varname_set (rep:=rep.listZ_local) x)\n        (of_list x).\n    Proof.\n      apply sameset_iff.\n      cbn [rep.varname_set rep.listZ_local rep.Z].\n      induction x; cbn [fold_right of_list In];\n        [ solve [firstorder idtac] | ].\n      intros. cbv [of_list] in *.\n      rewrite <-IHx. firstorder idtac.\n    Qed.\n  End Local.\n\n  Lemma equivalent_not_in_context {var1} locals1 locals2 vset x :\n    map.only_differ locals1 vset locals2 ->\n    disjoint vset (@context_varname_set var1 (x :: nil)) ->\n    equiv3 locals1 x ->\n    equiv3 locals2 x.\n  Proof.\n    intros; cbv [equiv3 context_varname_set locally_equivalent] in *.\n    destruct x as [x [ [? ?] ?] ]; destruct x; [ | tauto ].\n    eapply equivalent_only_differ; eauto with equiv.\n    match goal with H : _ |- _ =>\n                    apply disjoint_union_r_iff in H end.\n    cleanup; eauto.\n  Qed.\n\n  Lemma equivalent_not_in_context_forall {var1} locals1 locals2 vset G :\n    map.only_differ locals1 vset locals2 ->\n    disjoint vset (@context_varname_set var1 G) ->\n    Forall (equiv3 locals1) G ->\n    Forall (equiv3 locals2) G.\n  Proof.\n    induction G; intros; constructor;\n      repeat match goal with\n             | _ => progress cbn [context_varname_set equiv3] in *\n             | _ => progress break_match_hyps\n             | H : disjoint _ (union _ _) |- _ =>\n               apply disjoint_union_r_iff in H; cleanup\n             | H : Forall _ (_ :: _) |- _ =>\n               inversion H; subst; clear H\n             | _ => tauto\n             | _ => eapply equivalent_only_differ;\n                      solve [eauto with equiv]\n             end.\n  Qed.\nEnd ContextEquivalence.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Bedrock/Field/Translation/Proofs/EquivalenceProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2132065903854601}}
{"text": "Require Import Lists.List Lists.ListSet Vector Arith.PeanoNat RcSyntax AbstractRelation Bool.Sumbool Tribool JMeq \n  FunctionalExtensionality ProofIrrelevance Eqdep_dec EqdepFacts Omega Util Common Syntax SemFacts RelFacts Eval \n  Semantics RcSemantics.\n\nModule RcToSql (Sem : SEM) (Rc : RC) (Sql : SQL).\n  Import Db.\n  Import Rc.\n  Import Sql.\n\n  Module RF := RelFacts.Facts Sql.\n  Module SF := SemFacts.Facts.\n  Import RF.\n  Import SF.\n\n(*\n  Module S2 := Sem2 Db.\n  Module S3 := Sem3 Db.\n  Module SQLSem2 := SQLSemantics Db S2 Sql.\n  Module SQLSem3 := SQLSemantics Db S3 Sql.\n*)\n\n  Module RCSem := RcSemantics Sem Rc.\n  Module SQLSem := SQLSemantics Sem Sql.\n\n  Fixpoint undo_bigunion q :=\n    match q with\n    | nil b s => Some ((b, s), List.nil)\n    | union q1 q2 => bind (undo_bigunion q2) (fun r => Some ((fst (fst r), snd (fst r)), q1::snd r))\n    | _ => None\n    end.\n\n  Definition sql_nil s : prequery :=\n    select false (List.map (fun a => (tmnull, a)) s) List.nil cndfalse.\n\n  Fixpoint sql_bigunion b s ql :=\n    match ql with\n    | List.nil => sql_nil s\n    | q::List.nil => q\n    | q::ql0 => qunion b q (sql_bigunion b s ql0)\n    end.\n\n  Definition sql_select b tup ql c :=\n    select b tup ql c.\n\n  Definition sql_distinct T s := selstar true (((T,s)::List.nil)::List.nil) cndtrue.\n\n(*\n  Fixpoint undo_multicomprn q :=\n    match q with\n    | comprn q1 q2 => \n        bind (undo_multicomprn q1) (fun r => Some (fst r, (fst (snd r), snd (snd r) ++ (q2::List.nil))))\n    | single b tup => Some (b, (tup, List.nil))\n    | _ => None\n    end.\n\n  Definition xlate_ncoll_fix r :=\n    (* FIXME the 0s below are wrong: we need to know the arity of the query *)\n    bind r (fun r' =>\n    let b := fst (fst r') in let s := snd (fst r') in let ql := snd r' in\n    Some (sql_bigunion b s ql)).\n\n  Definition xlate_ndisjunct_fix r :=\n    bind r (fun r' =>\n     let b := fst r' in let tup := fst (snd r') in let ql := snd (snd r') in\n     Some (sql_select b tup ql)).\n\n*)\n\n  Definition sql_empty q s := cndnot (cndex (selstar false (((tbquery q,s)::List.nil)::List.nil) cndtrue)).\n\n(*\n  Axiom rcschema : Rc.tm -> option Scm.\n  Axiom rcdistinct : Rc.tm -> option bool.\n*)\n\n  (* normal form translation *)\n  Inductive j_base_x (d : Db.D) : list Scm -> Rc.tm -> Sql.pretm -> Prop :=\n  | jbx_cst  : forall g c, j_base_x d g (cst c) (tmconst c)\n  | jbx_null : forall g, j_base_x d g null tmnull\n  | jbx_proj : forall g n x,\n      (* the assumption on well-formedness wrt the context can be provided separately *)\n      (* List.nth_error g n = Some s -> j_var x s -> *)\n      j_base_x d g (proj (var n) x) (tmvar (n,x)).\n\n  Inductive j_basel_x (d : Db.D) : list Scm -> list Rc.tm -> list Sql.pretm -> Prop :=\n  | j_blx_nil : forall g, j_basel_x d g List.nil List.nil\n  | j_blx_cons : forall g t tml,\n      forall t' tml',\n      j_base_x d g t t' ->\n      j_basel_x d g tml tml' ->\n      j_basel_x d g (t::tml) (t'::tml').\n\n  Inductive j_tuple_x (d : Db.D) : list Scm -> Rc.tm -> Scm -> list Sql.pretm -> Prop :=\n  | jtx_mktup : forall g bl, \n      forall tl',\n      List.NoDup (List.map fst bl) ->\n      j_basel_x d g (List.map snd bl) tl' ->\n      j_tuple_x d g (mktup bl) (List.map fst bl) tl'.\n\n  Inductive j_cond_x (d : Db.D) : list Scm -> Rc.tm -> Sql.precond -> Prop :=\n  | jbx_empty : forall g q b,\n      forall q' s,\n      j_coll_x d g q b s q' \n      -> j_cond_x d g (empty b q) (sql_empty q' s)\n  | jwx_pred : forall g n p tl,\n      forall tl',\n      j_basel_x d g tl tl' -> length tl = n ->\n      j_cond_x d g (pred n p tl) (cndpred n p tl')\n  | jwx_true : forall g, j_cond_x d g rctrue cndtrue\n  | jws_false : forall g, j_cond_x d g rcfalse cndfalse\n  | jws_isnull : forall g t,\n      forall t', j_base_x d g t t' ->\n      j_cond_x d g (isnull t) (cndnull true t')\n  | jws_istrue : forall g c,\n      forall c', j_cond_x d g c c' ->\n      j_cond_x d g (istrue c) (cndistrue c')\n  | jws_and : forall g c1 c2,\n      forall c1' c2', j_cond_x d g c1 c1' -> j_cond_x d g c2 c2' ->\n      j_cond_x d g (rcand c1 c2) (cndand c1' c2')\n  | jws_or : forall g c1 c2,\n      forall c1' c2', j_cond_x d g c1 c1' -> j_cond_x d g c2 c2' ->\n      j_cond_x d g (rcor c1 c2) (cndor c1' c2')\n  | jws_not : forall g c,\n      forall c', j_cond_x d g c c' ->\n      j_cond_x d g (rcnot c) (cndnot c')\n\n\n  with j_coll_x (d : Db.D) : list Scm -> Rc.tm -> bool -> Scm -> Sql.prequery -> Prop :=\n  | jcx_nil : forall g b s, \n      List.NoDup s -> j_coll_x d g (nil b s) b s (sql_nil s)\n  | jcx_disjunct : forall g t,\n      forall b s tl' c' Bl',\n      (* not union is implicity in j_disjunct_x *)\n      j_disjunct_x d g t b s tl' c' Bl'  ->\n      j_coll_x d g t b s (sql_select b (List.combine tl' s) Bl' c')\n  | jcx_union : forall g t1 t2,\n      forall b s tl1' c' Bl1' q2' ,\n      j_disjunct_x d g t1 b s tl1' c' Bl1' ->\n      j_coll_x d g t2 b s q2' ->\n      j_coll_x d g (union t1 t2) b s (qunion (negb b) (sql_select b (List.combine tl1' s) Bl1' c') q2')\n\n  with j_disjunct_x (d : Db.D) : list Scm -> Rc.tm -> bool -> Scm -> list Sql.pretm -> Sql.precond -> list (list (Sql.pretb * Scm)) -> Prop :=\n  | jdx_single : forall g b tup c,\n      forall s tl' c',\n      j_tuple_x d g tup s tl' -> j_cond_x d g c c' ->\n      j_disjunct_x d g (cwhere (single b tup) c) b s tl' c' List.nil\n  | jdx_comprn : forall g q1 q2,\n      forall b s s2 tl1' c' Bl1' T2',\n      j_gen_x d g q2 b s2 T2' ->\n      j_disjunct_x d (s2::g) q1 b s tl1' c' Bl1' ->\n      j_disjunct_x d g (comprn q1 q2) b s tl1' c' (((T2', s2)::List.nil) :: Bl1')\n\n  with j_gen_x (d : Db.D) : list Scm -> Rc.tm -> bool -> Scm -> Sql.pretb -> Prop :=\n  | jgx_tab : forall g x,\n      forall s, Db.db_schema d x = Some s ->\n      j_gen_x d g (tab x) false s (tbbase x)\n  | jgx_diff : forall g q1 q2,\n      forall s q1' q2',\n      j_coll_x d g q1 false s q1' ->\n      j_coll_x d g q2 false s q2' ->\n      j_gen_x d g (diff q1 q2) false s (tbquery (qexcept true q1' q2'))\n  | jgx_dtab : forall g x,\n      forall s, Db.db_schema d x = Some s ->\n      j_gen_x d g (dist (tab x)) true s (tbquery (sql_distinct (tbbase x) s))\n  | jgx_ddiff : forall g q1 q2,\n      forall s q1' q2',\n      j_coll_x d g q1 false s q1' ->\n      j_coll_x d g q2 false s q2' ->\n      j_gen_x d g (dist (diff q1 q2)) true s (tbquery (sql_distinct (tbquery (qexcept true q1' q2')) s))\n  | jgx_prom : forall g q,\n      forall s q',\n      j_coll_x d g q true s q' -> \n      j_gen_x d g (prom q) false s (tbquery q')\n  .\n\n  Derive Inversion jbx_proj_inv with (forall d g n x t', j_base_x d g (proj (var n) x) t') Sort Prop.\n  Derive Inversion jbx_empty_inv with (forall d g b q t', j_base_x d g (empty b q) t') Sort Prop.\n  Derive Inversion jblx_nil_inv with (forall d g tml', j_basel_x d g List.nil tml') Sort Prop.\n  Derive Inversion jblx_cons_inv with (forall d g t tml tml', j_basel_x d g (t::tml) tml') Sort Prop.\n  Derive Inversion jtx_mktup_inv with (forall d g bl s tml', j_tuple_x d g (mktup bl) s tml') Sort Prop.\n  Derive Inversion jwx_pred_inv with (forall d g n p tl c, j_cond_x d g (pred n p tl) c) Sort Prop.\n  Derive Inversion jcx_nil_inv with (forall d g b s b' s' q', j_coll_x d g (nil b s) b' s' q') Sort Prop.\n  (* Derive Inversion jcx_disjunct_inv we should know that j_disjunct_x holds and invert that one *)\n  Derive Inversion jcx_union_inv with (forall d g t1 t2 b s q', j_coll_x d g (union t1 t2) b s q') Sort Prop.\n  Derive Inversion jdx_single_inv with (forall d g b tup c b' s' tl' c' Bl', j_disjunct_x d g (cwhere (single b tup) c) b' s' tl' c' Bl') Sort Prop.\n  Derive Inversion jdx_comprn_inv with (forall d g t1 t2 b s tl' c' Bl', j_disjunct_x d g (comprn t1 t2) b s tl' c' Bl') Sort Prop.\n  Derive Inversion jgx_tab_inv with (forall d g x b s T', j_gen_x d g (tab x) b s T') Sort Prop.\n  Derive Inversion jgx_diff_inv with (forall d g t1 t2 b s T', j_gen_x d g (diff t1 t2) b s T') Sort Prop.\n  Derive Inversion jgx_dtab_inv with (forall d g x b s T', j_gen_x d g (dist (tab x)) b s T') Sort Prop.\n  Derive Inversion jgx_ddiff_inv with (forall d g t1 t2 b s T', j_gen_x d g (dist (diff t1 t2)) b s T') Sort Prop.\n  Derive Inversion jgx_prom_inv with (forall d g t b s T', j_gen_x d g (prom t) b s T') Sort Prop.\n\n  Scheme jwx_ind_mut   := Induction for j_cond_x      Sort Prop\n  with   jcx_ind_mut   := Induction for j_coll_x      Sort Prop\n  with   jdx_ind_mut   := Induction for j_disjunct_x  Sort Prop\n  with   jgx_ind_mut   := Induction for j_gen_x       Sort Prop.\n\n  Combined Scheme j_x_ind_mut from jwx_ind_mut, jcx_ind_mut, jdx_ind_mut, jgx_ind_mut.\n\n  Lemma j_basel_x_length : forall d G tl tl', j_basel_x d G tl tl' -> length tl = length tl'.\n  Proof.\n    intros d G tl tl' H. induction H; simpl; intuition.\n  Qed.\n\n  Lemma j_tuple_x_length : forall d G t s tl', j_tuple_x d G t s tl' -> length s = length tl'.\n  Proof.\n    intros d G t s tl' H. inversion H; simpl; subst.\n    generalize (j_basel_x_length _ _ _ _ H1). do 2 rewrite map_length. intuition.\n  Qed.\n\n  Lemma j_disjunct_x_length : forall d G t b s tl c Bl,\n    j_disjunct_x d G t b s tl c Bl ->\n    List.length s = List.length tl.\n  Proof.\n    intros d G t b s qt c Bl H.\n    eapply (jdx_ind_mut _\n          (fun G0 t0 t0' _ => True)\n          (fun G0 t0 b0 s0 q0 _ => True)\n          (fun G0 t0 b0 s0 tml0 _ Bl0 _ => length s0 = length tml0)\n          (fun G0 t0 b0 s0 T' _ => True)\n          _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H).\n    Unshelve.\n    all: simpl; intuition.\n    eapply j_tuple_x_length. exact j.\n  Qed.\n\n  Lemma j_coll_x_nodup_schema : forall d G t b s qt,\n    j_coll_x d G t b s qt ->\n    NoDup s.\n  Proof.\n    intros d G t b s qt Hx.\n    eapply (jcx_ind_mut _\n          (fun G0 t0 t0' _ => True)\n          (fun G0 t0 b0 s0 q0 _ => NoDup s0)\n          (fun G0 t0 b0 s0 tml0 _ Bl0 _ => NoDup s0)\n          (fun G0 t0 b0 s0 T' _ => True)\n          _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Hx).\n    Unshelve.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl. intros. inversion j. exact H0.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n  Qed.\n\n  Lemma j_tuple_x_sem_eq : forall d G t s tml',\n    j_tuple_x d G t s tml' ->\n    forall s' St, RCSem.j_tuple_sem d G t s' St -> s = s'.\n  Proof.\n    intros d G t s tml' H. inversion H; subst.\n    intros s' St H'. inversion H'; subst.\n    apply map_fst_combine. exact H6.\n  Qed.\n\n  Lemma j_coll_x_sem_eq : forall d G t b s qt,\n    j_coll_x d G t b s qt ->\n    forall b' s' St, RCSem.j_coll_sem d G t b' s' St ->\n    b = b' /\\ s = s'.\n  Proof.\n    intros d G t b s qt Hx.\n    eapply (jcx_ind_mut _\n          (fun G0 t0 t0' _ => True)\n          (fun G0 t0 b0 s0 q0 _ => forall b' s' St, RCSem.j_coll_sem d G0 t0 b' s' St -> b0 = b' /\\ s0 = s')\n          (fun G0 t0 b0 s0 tml0 _ Bl0 _ => forall b' s' St, RCSem.j_disjunct_sem d G0 t0 b' s' St -> b0 = b' /\\ s0 = s')\n          (fun G0 t0 b0 s0 T' _ => forall b' s' St, RCSem.j_gen_sem d G0 t0 b' s' St -> b0 = b' /\\ s0 = s')\n          _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ Hx).\n    Unshelve.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intuition.\n    + simpl; intros g0 b0 s0 Hnd b' s' St Hsem. inversion Hsem; subst. intuition. inversion H4.\n    + simpl. intros g0 t0 b0 s0 tml' c' Bl' Ht0 IHt0 b' s' St Hsem. inversion Hsem; subst; inversion Ht0; subst.\n      eapply IHt0. exact H4.\n      eapply IHt0. exact H4.\n    + simpl. intros g0 t1 t2 b0 s0 tml' c' Bl1' q2' Ht1 IHt1 Ht2 IHt2 b' s' St Hsem. inversion Hsem; subst.\n      inversion H4.\n      eapply IHt2. exact H7.\n    + simpl. intros g0 b0 t0 c0 s0 tml' c' Ht0 Hc' _ b' s' St Hsem. inversion Hsem; subst; intuition.\n      eapply j_tuple_x_sem_eq. exact Ht0. exact H5.\n    + simpl. intros G0 q1 q2 b0 s0 s1 tl1' c' Bl1' T2' Hq2 IHq2 Hq1 IHq1 b' s' St Hsem. inversion Hsem; subst.\n      destruct (IHq2 _ _ _ H5); subst. intuition.\n      destruct (IHq1 _ _ _ H6); subst. reflexivity.\n    + simpl. intros G0 x s0 Hs0 b' s' St Hsem. inversion Hsem; subst. clear H4.\n      rewrite Hs0 in e; injection e; intuition.\n    + simpl. intros G0 q1 q2 s0 q1' q2' Hq1 IHq1 Hq2 IHq2 b' s' St Hsem. inversion Hsem; subst.\n      destruct (IHq1 _ _ _ H5); intuition.\n    + simpl. intros G0 x s0 Hs0 b' s' St Hsem. inversion Hsem; subst. clear H4.\n      rewrite Hs0 in e; injection e; intuition.\n    + simpl. intros G0 q1 q2 s0 q1' q2' Hq1 IHq1 Hq2 IHq2 b' s' St Hsem. inversion Hsem; subst.\n      destruct (IHq1 _ _ _ H5); intuition.\n    + simpl. intros G0 q s0 q' Hq IHq b' s' St Hsem. inversion Hsem; subst.\n      destruct (IHq _ _ _ H4). intuition.\n  Qed.\n\n  Lemma j_coll_x_sem_eq_bool : forall d G t b s qt b' s' St,\n    j_coll_x d G t b s qt -> RCSem.j_coll_sem d G t b' s' St ->\n    b = b'.\n  Proof.\n    intros. destruct (j_coll_x_sem_eq _ _ _ _ _ _ H _ _ _ H0). intuition.\n  Qed.\n\n  Lemma j_coll_x_sem_eq_scm : forall d G t b s qt b' s' St,\n    j_coll_x d G t b s qt -> RCSem.j_coll_sem d G t b' s' St ->\n    s = s'.\n  Proof.\n    intros. destruct (j_coll_x_sem_eq _ _ _ _ _ _ H _ _ _ H0). intuition.\n  Qed.\n\n  Lemma base_rcsem_to_sqlsem : forall d G t St,\n    RCSem.j_base_sem d G t St ->\n    forall t', j_base_x d G t t' ->\n    exists St', SQLSem.j_tm_sem G t' St' /\\ forall h, St' h ~= St h.\n  Proof.\n  intros d G t St H. elim H; simpl.\n  + intros G0 c t' j; clear H. inversion j; subst.\n    eexists; split. constructor. simpl; reflexivity.\n  + intros G0 t' j; clear H. inversion j; subst.\n    eexists; split. constructor. simpl; reflexivity.\n  + intros G0 i a Sia j. clear H; intros t0' H.\n    inversion H; subst. elim j; intros.\n    - eexists; split. constructor. constructor. exact H0.\n      reflexivity.\n    - decompose record H1; rename x into Sp.\n      eexists; split. constructor. constructor. exact H0. intuition.\n  Qed.\n\n  Lemma basel_rcsem_to_sqlsem : forall d G tl Stl,\n    RCSem.j_basel_sem d G tl Stl ->\n    forall tl', j_basel_x d G tl tl' ->\n    exists Stl', SQLSem.j_tml_sem G tl' Stl' /\\ forall h, Stl' h ~= Stl h.\n  Proof.\n    intros d G tl Stl H. elim H; simpl.\n    + intros G0. clear H; intros tml0' H.\n      inversion H; subst. eexists; split. constructor. simpl; intro. reflexivity.\n    + intros G0 t0 tml0 St0 Stml0 jt0 jtml0 IHtml0. clear H; intros tml0' H.\n      inversion H; subst. decompose record (base_rcsem_to_sqlsem _ _ _ _ jt0 _ H3); rename x into St'.\n      decompose record (IHtml0 _ H5); rename x into Stml'.\n      eexists; split. constructor. exact H1. exact H4.\n      simpl; intro. rewrite H2. \n      clear jtml0 IHtml0. generalize dependent Stml0. replace (length tml0) with (length tml').\n      intros. rewrite H6. reflexivity.\n      symmetry; apply (j_basel_x_length _ _ _ _ H5).\n  Qed.\n\n  Lemma tuple_rcsem_to_sqlsem : forall d G t s St,\n    RCSem.j_tuple_sem d G t s St ->\n    forall tml', j_tuple_x d G t s tml' ->\n      exists Stml', SQLSem.j_tml_sem G tml' Stml' /\\ forall h, Stml' h ~= St h.\n  Proof.\n    intros d G t s St H. inversion H; subst.\n    intros tml' Html'. inversion Html'; subst.\n    enough (List.map snd (combine s bl) = bl). rewrite H3 in H7.\n    decompose record (basel_rcsem_to_sqlsem _ _ _ _ H6 _ H7); rename x into Stml'.\n    eexists; split. exact H9.\n    apply (existT_eq_elim H0); intros. apply (existT_eq_elim (JMeq_eq H11)); intros.\n    rewrite <- H13. symmetry. apply cast_fun_app_JM; try intuition.\n    rewrite (j_tuple_x_length _ _ _ _ _ Html'); reflexivity.\n    rewrite <- H14. symmetry; apply H10.\n    apply map_snd_combine. exact H2.\n  Qed.\n\n  Lemma tml_sem_tmlist_of_ctx_eq s G :\n    forall s0 Stml,\n      SQLSem.j_tml_sem ((s0++s)::G) (tmlist_of_ctx (s::List.nil)) Stml ->\n        Stml ~= fun h => Evl.tuple_of_env (s::List.nil) (Evl.env_skip (@Evl.subenv1 ((s0 ++ s)::List.nil) G h)).\n  Proof.\n    elim s.\n    + simpl. unfold tmlist_of_ctx. simpl. intros.\n      eapply (SQLSem.j_tml_nil_sem _ _ (fun _ _ => _) _ H). Unshelve.\n      simpl. intros _ Heq. eapply (existT_eq_elim Heq); clear Heq; intros _ Heq.\n      symmetry. eapply (JMeq_trans _ Heq). Unshelve.\n      apply funext_JMeq. reflexivity. reflexivity.\n      intros h1 h2 Hh; subst.\n      eapply (Vector.case0 (fun x => x ~= _)). reflexivity.\n    + simpl. unfold tmlist_of_ctx. simpl. intros.\n      eapply (SQLSem.j_tml_cons_sem _ _ _ _ (fun _ _ _ _ => _ ~= _) _ H0). Unshelve.\n      simpl; intros; subst. eapply (existT_eq_elim H6); clear H6; intros _ H6.\n      symmetry. eapply (JMeq_trans _ H6). Unshelve.\n      apply funext_JMeq. reflexivity. simpl. f_equal; f_equal. rewrite app_length. rewrite map_length. reflexivity.\n      intros h1 h2 Hh; subst.\n      inversion H2. subst.\n      enough (Evl.j_fvar_sem ((s0 ++ a :: l) :: G) 0 a St) as H7'.\n      generalize (Evl.j_fvar_sem_inside_eq _ _ _ _ _ H7'). intro Ht.\n      (* Ht is what we need for the hd *)\n      enough (exists Stml', SQLSem.j_tml_sem (((s0 ++ a :: List.nil) ++ l)::G) (List.map (fun x => tmvar (0,x)) l ++ List.nil) Stml' /\\ Stml' ~= Stml0).\n      decompose record H3. rename x into Stml'; clear H3.\n      generalize (H _ _ H6). intro Html.\n      rewrite (Vector.eta (Evl.tuple_of_env _ (Evl.env_skip (@Evl.subenv1 ((s0++a::l)::List.nil) _ h2)))).\n      apply cons_equal.\n      - rewrite Ht. apply Evl.hd_tuple_of_env.\n      - rewrite app_length. rewrite map_length. reflexivity.\n      - rewrite (Evl.tl_tuple_of_env a l List.nil _).\n        enough (exists (h : Evl.env (((s0 ++ a :: List.nil) ++ l) :: G)), h ~= h2).\n        decompose record H3; clear H3; rename x into h.\n        apply (@JMeq_trans _ _ _ _ (Stml' h)).\n        apply (@JMeq_trans _ _ _ _ \n          (Evl.tuple_of_env (l::List.nil) (Evl.env_skip (@Evl.subenv1 (((s0 ++ a :: List.nil)++l)::List.nil) _ h)))).\n        apply (f_JMeq _ _ (Evl.tuple_of_env (l::List.nil))). apply JMeq_eq.\n        rewrite <- Evl.env_skip_single. symmetry. apply Evl.env_skip_skip.\n        eapply (f_JMequal (@Evl.subenv1 (((s0++a::List.nil)++l)::List.nil) G) (@Evl.subenv1 ((s0++a::l)::List.nil) G)).\n        simpl. rewrite <- app_assoc. reflexivity. exact H5.\n        erewrite (f_JMequal _ _ h h Html JMeq_refl). reflexivity.\n        eapply (f_JMequal Stml' Stml0 h h2 H8 H5).\n        rewrite <- app_assoc. exists h2. reflexivity.\n        Unshelve.\n        rewrite <- app_assoc. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        rewrite <- app_assoc, app_length, map_length. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n      - rewrite <- app_assoc. eexists. split. exact H4. reflexivity.\n      - exact H7.\n  Qed.\n\n  Lemma tml_sem_tmlist_of_ctx s G :\n    forall s0, NoDup (s0++s) -> exists Stml,\n      SQLSem.j_tml_sem ((s0++s)::G) (tmlist_of_ctx (s::List.nil)) Stml.\n  Proof.\n    induction s; intros.\n    + simpl. eexists. constructor.\n    + simpl.\n      enough (exists Stml', SQLSem.j_tml_sem ((s0 ++ a :: s)::G) (tmlist_of_ctx (s::List.nil)) Stml').\n      decompose record H0; rename x into Stml.\n      decompose record (Evl.j_fvar_sem_inside _ _ _ G H); rename x into Sa.\n      eexists. constructor. constructor. exact H2.\n      exact H1. replace (s0 ++ a :: s) with ((s0 ++ a :: List.nil) ++ s).\n      apply IHs. rewrite <- app_assoc. exact H. rewrite <- app_assoc. reflexivity.\n  Qed.\n\n  Lemma sum_id : forall m n (f : Rel.T m -> Rel.T n) r,\n     m = n ->\n     (forall x, f x ~= x) ->\n     Rel.sum r f ~= r.\n  Proof.\n    intros. subst. apply eq_JMeq. eapply Rel.p_ext.\n    intros v. rewrite Rel.p_sum.\n    replace (fun x => Rel.T_eqb (f x) v) with (fun v' => Rel.T_eqb v' v).\n    eapply filter_supp_elim; simpl; intro.\n    + omega.\n    + destruct (or_eq_lt_n_O (Rel.memb r v)); intuition.\n      contradiction H. apply Rel.p_fs. exact H1.\n    + extensionality v'. rewrite H0. reflexivity.\n  Qed.\n\n  Lemma env_skip_nil : forall s' G' h', @Evl.env_skip s' G' List.nil h' = h'.\n  Proof.\n    intros. reflexivity.\n  Qed.\n\n  Lemma qunion_sem d G s b q1 q2 :\n    forall Sq1 Sq2,\n    SQLSem.j_q_sem d G s q1 Sq1 ->\n    SQLSem.j_q_sem d G s q2 Sq2 ->\n    exists Sq, SQLSem.j_q_sem d G s (qunion b q1 q2) Sq\n      /\\ forall h, Sq h = if b then(Rel.plus (Sq1 h) (Sq2 h)) else (Rel.flat (Rel.plus (Sq1 h) (Sq2 h))).\n  Proof.\n    intros. eexists; split. constructor. exact H. exact H0.\n    simpl. intro. reflexivity.\n  Qed.\n\n(*\n  Lemma sql_select_sem d G s b tl Bl c :\n    length tl = length s ->\n    forall G1 SBl Sc Stl,\n     SQLSem.j_btbl_sem d G G1 Bl SBl ->\n     SQLSem.j_cond_sem d (G1 ++ G) c Sc ->\n     SQLSem.j_tml_sem (G1 ++ G) tl Stl ->\n    exists Sq, SQLSem.j_q_sem d G s (sql_select b (combine tl s) Bl c) Sq\n    /\\ forall h, Sq h ~= let S1 := SBl h in\n                  let p  := fun Vl => Sem.is_btrue (Sc (Evl.env_app _ _ (Evl.env_of_tuple G1 Vl) h)) in\n                  let S2 := Rel.sel S1 p in\n                  let f  := fun Vl => Stl(Evl.env_app _ _ (Evl.env_of_tuple G1 Vl) h) in\n                  let S := Rel.sum S2 f\n                  in if b then Rel.flat S else S.\n  Proof.\n    intro. rewrite <- (map_fst_combine _ _ _ _ H) at .\n    intros. eexists; split. constructor. exact H0. exact H1.\n      rewrite map_fst_combine.\n*)\n\n  Lemma sql_distinct_sem d G s T ST :\n    NoDup s -> SQLSem.j_tb_sem d G s T ST ->\n    exists Sq, SQLSem.j_q_sem d G s (sql_distinct T s) Sq\n      /\\ forall h, Sq h = Rel.flat (ST h).\n  Proof.\n    intros. decompose record (tml_sem_tmlist_of_ctx s G List.nil H); rename x into Stml.\n    eexists; split.\n      constructor. constructor. constructor. exact H0. constructor. reflexivity.\n      constructor. constructor. exact H1. simpl. rewrite app_nil_r. reflexivity.\n      Unshelve. shelve.\n      simpl. rewrite length_tmlist. simpl. rewrite app_nil_r. reflexivity.\n      simpl. rewrite <- plus_n_O. reflexivity.\n      reflexivity.\n    Unshelve.\n    intro; simpl. f_equal.\n    apply JMeq_eq. apply cast_JMeq.\n    eapply (JMeq_trans (sum_id _ _ _ _ _ _)).\n    erewrite sel_true.\n    eapply (JMeq_trans (rsum_id _ _ _ _ _ _)).\n    apply Rel_times_Rone.\n    intros; simpl. apply Sem.is_btrue_btrue.\n    Unshelve.\n    + rewrite length_tmlist; simpl; rewrite app_length; reflexivity.\n    + intro Vl; simpl.\n      enough (forall h0, Stml h0 ~= Evl.tuple_of_env (s::List.nil) (Evl.env_skip (@Evl.subenv1 ((List.nil ++ s)::List.nil) G h0))).\n      eapply (JMeq_trans (H2 _)). \n      rewrite env_skip_nil. rewrite subenv1_app. unfold Evl.env_app; simpl. unfold Evl.tuple_of_env; simpl.\n      apply cast_JMeq. rewrite app_nil_r. eapply (JMeq_trans (Evl.of_list_to_list_opp _ _ _)).\n      apply (split_ind Vl). intros; subst. apply (Vector.case0 (fun v0 => fst (v1, v0) ~= append v1 v0)).\n      symmetry. apply vector_append_nil_r.\n      intro. eapply (f_JMequal Stml (fun h1 => Evl.tuple_of_env (s::List.nil) (Evl.env_skip (@Evl.subenv1 ((List.nil ++ s)::List.nil) G h1))) _ _ _ _).\n        Unshelve.\n        reflexivity. simpl. rewrite length_tmlist. simpl. rewrite app_length. reflexivity.\n        eapply tml_sem_tmlist_of_ctx_eq. exact H1. reflexivity.\n    + reflexivity.\n    + intros. simpl. apply cast_JMeq. apply Rel_Rone_times.\n  Qed.\n\n  Lemma eq_plus_dep m n (e : m = n) :\n    forall (r1 r2 : Rel.R m) (r1' r2' : Rel.R n),\n    r1 ~= r1' -> r2 ~= r2' -> Rel.plus r1 r2 ~= Rel.plus r1' r2'.\n  Proof.\n    rewrite e. intros. rewrite H, H0. reflexivity.\n  Qed.\n\n  Lemma eq_flat_dep m n (e : m = n) :\n    forall (r1 : Rel.R m) (r2 : Rel.R n),\n    r1 ~= r2 -> Rel.flat r1 ~= Rel.flat r2.\n  Proof.\n    rewrite e. intros. rewrite H. reflexivity.\n  Qed.\n\n  Lemma sql_null_tml_sem G s :\n    exists Stml,\n    SQLSem.j_tml_sem G (List.map fst (List.map (fun a : Name => (NULL, a)) s)) Stml.\n  Proof.\n    induction s; simpl.\n    + eexists. constructor.\n    + decompose record IHs; rename x into Stml; clear IHs.\n      eexists. constructor. constructor. exact H.\n  Qed.\n\n  Lemma sql_nil_sem d G s :\n    exists Snil,\n    SQLSem.j_q_sem d G s (sql_nil s) Snil /\\ (forall h, Snil h ~= RCSem.sem_nil (length s)).\n  Proof.\n    decompose record (sql_null_tml_sem G s); rename x into Snull.\n    enough (length (List.map fst (List.map (fun a : Name => (NULL, a)) s)) = length s).\n    eexists; split. constructor. constructor. constructor. exact H.\n    elim s; simpl; intuition. rewrite <- H1. reflexivity.\n    simpl. intro. apply cast_JMeq.\n    apply p_ext_dep. exact H0.\n    intros. transitivity 0.\n    + rewrite Rel.p_sum. \n      replace (Rel.supp (Rel.sel Rel.Rone (fun _ => Sem.is_btrue Sem.bfalse))) with (@List.nil (Rel.T 0)). \n      reflexivity. \n      symmetry. destruct (Rel.supp (Rel.sel Rel.Rone (fun _ => Sem.is_btrue Sem.bfalse))) eqn:e. reflexivity.\n      assert (Rel.memb (Rel.sel Rel.Rone (fun _ : Rel.T 0 => Sem.is_btrue Sem.bfalse)) t > 0).\n      apply Rel.p_fs_r. rewrite e. constructor. reflexivity.\n      erewrite Rel.p_self in H2. contradiction (lt_irrefl _ H2).\n      apply Sem.is_btrue_bfalse.\n      Unshelve. rewrite H0. reflexivity.\n    + unfold RCSem.sem_nil. rewrite Rel.p_self. reflexivity. reflexivity.\n    + elim s; simpl; intuition.\n  Qed.\n\n  Lemma flat_sem_nil n : Rel.flat (RCSem.sem_nil n) = RCSem.sem_nil n.\n  Proof.\n    apply Rel.p_ext; intros. rewrite Rel.p_flat.\n    replace (Rel.memb (RCSem.sem_nil n) t) with O. reflexivity.\n    symmetry; unfold RCSem.sem_nil. rewrite sel_false. apply Rel.p_nil.\n    intros; reflexivity.\n  Qed.\n\n  Lemma sum_Rnil_sem_nil n (f : Rel.T 0 -> Rel.T n) : Rel.sum Rel.Rnil f = RCSem.sem_nil n.\n  Proof.\n    apply Rel.p_ext; intros.\n    unfold RCSem.sem_nil. rewrite sel_false; try intuition. rewrite Rel.p_nil.\n    rewrite Rel.p_sum. replace (Rel.supp Rel.Rnil) with (@List.nil (Rel.T 0)). reflexivity.\n    destruct (Rel.supp Rel.Rnil) eqn:e; intuition.\n    generalize (Rel.p_fs_r _ Rel.Rnil t0). rewrite Rel.p_nil, e. simpl; intro.\n    assert (t0 = t0 \\/ List.In t0 l). intuition. generalize (H H0). intro. inversion H1.\n  Qed.\n\n  Theorem j_tml_sem_fun_dep :\n    forall G tml Stml, SQLSem.j_tml_sem G tml Stml -> forall G0 tml0 Stml0, G = G0 -> tml = tml0 -> \n      SQLSem.j_tml_sem G0 tml0 Stml0 -> Stml ~= Stml0.\n  Proof.\n    intros; subst. apply eq_JMeq. apply (SQLSem.j_tml_sem_fun _ _ _ H _ H2).\n  Qed.\n\n  Theorem rcsem_to_sqlsem : forall d G t b s St,\n    RCSem.j_coll_sem d G t b s St ->\n    forall qt, j_coll_x d G t b s qt ->\n    exists Sqt, SQLSem.j_q_sem d G s qt Sqt /\\ forall h, Sqt h ~= St h.\n  Proof.\n    intros d G t b s St H.\n    eapply (RCSem.jcs_ind_mut _\n          (fun G0 t0 S0 _ => forall ct0, j_cond_x d G0 t0 ct0 ->\n            exists Sct0, SQLSem.j_cond_sem d G0 ct0 Sct0 /\\ forall h, Sct0 h ~= S0 h)\n          (fun G0 t0 b0 s0 S0 _ => forall qt0, j_coll_x d G0 t0 b0 s0 qt0 ->\n            exists Sqt0, SQLSem.j_q_sem d G0 s0 qt0 Sqt0 /\\ forall h, Sqt0 h ~= S0 h)\n          (fun G0 t0 b0 s0 S0 _ => forall tml0' c0' Bl0', j_disjunct_x d G0 t0 b0 s0 tml0' c0' Bl0' -> \n            exists G1 Stml0' Sc0' SBl0',\n              SQLSem.j_tml_sem (G1 ++ G0) tml0' Stml0' /\\ SQLSem.j_cond_sem d (G1 ++ G0) c0' Sc0'\n              /\\ SQLSem.j_btbl_sem d G0 G1 Bl0' SBl0'\n              /\\ forall h, \n                  (let S1 := SBl0' h in\n                  let p  := fun Vl => Sem.is_btrue (Sc0' (Evl.env_app _ _ (Evl.env_of_tuple G1 Vl) h)) in\n                  let S2 := Rel.sel S1 p in\n                  let f  := fun Vl => Stml0' (Evl.env_app _ _ (Evl.env_of_tuple G1 Vl) h) in\n                  let S := Rel.sum S2 f\n                  in if b0 then Rel.flat S else S)\n                  ~= S0 h)\n(*\n            exists Sqt0, SQLSem2.j_q_sem d G0 s0 (sql_select b0 (List.combine tml0' s0) Bl0') Sqt0\n              /\\ forall h, Sqt0 h ~= S0 h)\n*)\n          (fun G0 t0 b0 s0 S0 _ => forall st0 Tt0, j_gen_x d G0 t0 b0 st0 Tt0 ->\n            s0 = st0 /\\\n            exists STt0, SQLSem.j_tb_sem d G0 s0 Tt0 STt0\n              /\\ forall h, STt0 h ~= S0 h)\n          _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H).\n  Unshelve.\n  (*-- mutual induction cases: base --*)\n  + simpl. intros G0 q0 b0 s0 Sq0 Hq0 IHq0. clear H; intros ct0 H.\n    inversion H; subst.\n    destruct (j_coll_x_sem_eq _ _ _ _ _ _ H4 _ _ _ Hq0); subst.\n    decompose record (IHq0 _ H4). rename x into Sq'.\n    eexists; split. constructor. constructor. constructor. constructor. constructor. constructor. exact H2.\n    constructor. reflexivity. constructor. constructor.\n    simpl. intro. apply eq_JMeq.\n    enough (forall x, Sem.of_bool (x =? 0) = Sem.bneg (Sem.of_bool (0 <? x))).\n    unfold RCSem.sem_empty. rewrite H1. f_equal. f_equal. f_equal.\n    rewrite sel_true. apply eq_card_dep. \n      omega. Unshelve. Focus 4. reflexivity. Focus 4. reflexivity. \n    simpl.\n    apply (@trans_JMeq _ _ _ _ (Rel.rsum (Sq' h) (fun Vl => Rel.Rsingle Vl))).\n      apply eq_rsum_dep. omega. omega. apply Rel_times_Rone.\n      apply funext_JMeq. f_equal; omega. f_equal; omega. intros.\n      apply (trans_JMeq (Rel_Rone_times _ _)).\n      eapply (f_JMequal (@Rel.Rsingle (length s0 + 0)) (@Rel.Rsingle _)).\n      apply (f_JMeq _ _ Rel.Rsingle). Unshelve. \n      rewrite plus_n_O. reflexivity. exact H5.\n      4: { rewrite <- plus_n_O; reflexivity. }\n      4: { rewrite <- plus_n_O; reflexivity. }\n    rewrite rsum_single. apply H3.\n    intros _ _. apply Sem.is_btrue_btrue.\n    intro. rewrite Sem.bneg_of_bool. destruct x; reflexivity.\n  + simpl. intros G0 n0 p0 tml0 Stml0 Hlen Html0. clear H; intros ct0 H.\n    inversion H; subst.\n    decompose record (basel_rcsem_to_sqlsem _ _ _ _ Html0 _ H5). rename x into Stl'.\n    apply (existT_eq_elim H1). intros _ Hp. subst; clear H1.\n    enough (length tl' = length tml0).\n    eexists; split. constructor. exact H2. \n      Unshelve. shelve. shelve. exact H0. Unshelve.\n    clear H2. generalize dependent Stl'. rewrite H0. intros.\n    rewrite H3. reflexivity.\n    rewrite (j_basel_x_length _ _ _ _ H5). reflexivity.\n  + simpl. intros G0. clear H; intros ct0 H.\n    inversion H; subst. eexists; split. constructor. simpl; intuition.\n  + simpl. intros G0. clear H; intros ct0 H.\n    inversion H; subst. eexists; split. constructor. simpl; intuition.\n  + simpl. intros G0 t0 St0 Ht0. clear H; intros ct0 H.\n    inversion H; subst.\n    decompose record (base_rcsem_to_sqlsem _ _ _ _ Ht0 _ H2). rename x into St'.\n    eexists; split. constructor. exact H1. simpl; intro. rewrite H3. reflexivity.\n  + simpl. intros G0 c Sc. clear H; intros Hc IHc c0 H.\n    inversion H; subst. decompose record (IHc _ H2).\n    eexists; split. constructor. exact H1.\n    intro; simpl. rewrite H3. reflexivity.\n  + simpl. intros G0 c1 c2 Sc1 Sc2. clear H; intros Hc1 IHc1 Hc2 IHc2 c' H.\n    inversion H; subst.\n    decompose record (IHc1 _ H3). clear IHc1; rename x into Sc1'; rename H1 into IHc1.\n    decompose record (IHc2 _ H5). clear IHc2; rename x into Sc2'; rename H1 into IHc2.\n    eexists; split. constructor. exact IHc1. exact IHc2.\n    simpl; intro. rewrite H2, H4. reflexivity.\n  + simpl. intros G0 c1 c2 Sc1 Sc2. clear H; intros Hc1 IHc1 Hc2 IHc2 c' H.\n    inversion H; subst.\n    decompose record (IHc1 _ H3). clear IHc1; rename x into Sc1'; rename H1 into IHc1.\n    decompose record (IHc2 _ H5). clear IHc2; rename x into Sc2'; rename H1 into IHc2.\n    eexists; split. constructor. exact IHc1. exact IHc2.\n    simpl; intro. rewrite H2, H4. reflexivity.\n  + simpl. intros G0 c Sc. clear H; intros Hc IHc c0 H.\n    inversion H; subst.\n    decompose record (IHc _ H2). clear IHc; rename x into Sc1; rename H1 into IHc.\n    eexists; split. constructor. exact IHc.\n    simpl; intro. rewrite H3. reflexivity.\n  (*-- mutual inuction cases: collection --*)\n  + simpl; intros G0 b0 s0 Hnd. simpl. clear H; intros qt0 H.\n    eapply (jcx_nil_inv _ _ _ _ _ _ _ \n             (fun dd GG bb ss bb' ss' qq' =>\n               exists Sqt0, SQLSem.j_q_sem d GG ss' qq' Sqt0 /\\\n               forall h, Sqt0 h ~= RCSem.sem_nil (length ss'))\n               _ _ H). Unshelve.\n    - simpl; intros; subst; clear H4 H5. apply sql_nil_sem.\n    - simpl; intros; subst. inversion H1.\n  + simpl; intros G0 t0 b0 s0 St0 jt0 IHt0. clear H; intros qt0 H.\n    inversion H; subst.\n    - inversion jt0.\n    - decompose record (IHt0 _ _ _ H0); rename x into G1; rename x0 into Stl'; rename x1 into SBl'.\n      enough (exists Stl'', SQLSem.j_tml_sem (G1 ++ G0) (List.map fst (List.combine tl' s0)) Stl'').\n      decompose record H4; rename x into Stml''. eexists; split. constructor.\n      * exact H3.\n      * exact H2.\n      * exact H6.\n      * symmetry; eapply map_snd_combine. symmetry; apply (j_disjunct_x_length _ _ _ _ _ _ _ _ H0).\n      * intro. generalize (j_disjunct_x_length _ _ _ _ _ _ _ _ H0); intro.\n        rewrite <- H5. simpl. destruct b0; simpl.\n        ++ apply eq_flat_dep. apply H7.\n           apply cast_JMeq. apply eq_sum_dep; intuition.\n           erewrite map_fst_combine. reflexivity. symmetry; apply H7.\n           generalize dependent Stml''. erewrite map_fst_combine. intuition.\n           rewrite (SQLSem.j_tml_sem_fun _ _ _ H1 _ H6). reflexivity.\n           rewrite H7; reflexivity.\n        ++ apply cast_JMeq. apply eq_sum_dep; intuition.\n           erewrite map_fst_combine. reflexivity. symmetry; apply H7.\n           generalize dependent Stml''. erewrite map_fst_combine. intuition.\n           rewrite (SQLSem.j_tml_sem_fun _ _ _ H1 _ H6). reflexivity.\n           rewrite H7; reflexivity.\n      * replace (List.map fst (combine tl' s0)) with tl'. eexists; exact H1.\n        symmetry; apply map_fst_combine. symmetry; apply (j_disjunct_x_length _ _ _ _ _ _ _ _ H0).\n        Unshelve.\n        generalize (j_disjunct_x_length _ _ _ _ _ _ _ _ H0); intro Hlen.\n        erewrite map_fst_combine. rewrite Hlen; reflexivity. rewrite Hlen; reflexivity.\n    - inversion jt0.\n  + simpl; intros G0 t1 t2 b0 s0 St1 St2 jt1 IHt1 jt2 IHt2. clear H; intros qt0 H.\n    eapply (jcx_union_inv _ _ _ _ _ _ _\n             (fun dd GG tt1 tt2 bb ss qq' =>\n               exists Sqt0, SQLSem.j_q_sem d G0 ss qq' Sqt0 /\\\n               forall h, Sqt0 h ~= (if b0 then Rel.flat (Rel.plus (St1 h) (St2 h)) else Rel.plus (St1 h) (St2 h)))\n             _ _ H). Unshelve.\n    - simpl; intros; subst. inversion H1.\n    - simpl; intros; subst; clear H0.\n      decompose record (IHt2 _ H7); clear IHt2; rename x into Sq2'.\n      decompose record (IHt1 _ _ _ H3); clear IHt1. \n      rename x into G1; rename x0 into Stl1'; rename x1 into Sc'; rename x2 into SBl1'.\n      enough (exists Stl1'', SQLSem.j_tml_sem (G1 ++ G0) (List.map fst (combine tl1' s0)) Stl1'').\n      decompose record H6; clear H6; rename x into Stl1''.\n      assert (length tl1' = length s0). symmetry. apply (j_disjunct_x_length _ _ _ _ _ _ _ _ H3).\n      epose (Hq := (SQLSem.jqs_sel _ _ b0 _ _ _ _ _ _ _ s0 _ H5 H4 H9 _)).\n        Unshelve. shelve. shelve. \n        rewrite (map_fst_combine _ _ _ _ H6), H6; reflexivity.\n        rewrite (map_snd_combine _ _ _ _ H6); reflexivity.\n        Unshelve.\n      clearbody Hq.\n      decompose record (qunion_sem _ _ _ (negb b0) _ _ _ _ Hq H1); rename x into Squ.\n      exists Squ; split. exact H11.\n      intro. rewrite H12; clear H12. destruct b0; simpl.\n      * apply eq_JMeq. f_equal. apply JMeq_eq. apply eq_plus_dep. reflexivity.\n        rewrite <- H8. apply eq_flat_dep. symmetry; exact H6.\n        apply cast_JMeq. generalize dependent Stl1''. rewrite (map_fst_combine _ _ _ _ H6). intros.\n        rewrite (SQLSem.j_tml_sem_fun _ _ _ H0 _ H9). reflexivity.\n        apply H2.\n      * eapply eq_plus_dep. reflexivity.\n        apply cast_JMeq. rewrite <- H8.\n        generalize dependent Stl1''. rewrite (map_fst_combine _ _ _ _ H6). intros.\n        rewrite (SQLSem.j_tml_sem_fun _ _ _ H0 _ H9). reflexivity.\n        apply H2.\n      * replace (List.map fst (combine tl1' s0)) with tl1'. eexists; exact H0.\n        symmetry. apply map_fst_combine. symmetry. apply (j_disjunct_x_length _ _ _ _ _ _ _ _ H3).\n  (*-- mutual induction cases: disjunct --*)\n  + simpl; intros G0 b0 tup c stup Stup Sc jtup jc IHc. clear H; intros tml0' c0' Bl0' H.\n    inversion H; simpl; subst. clear H3.\n    decompose record (tuple_rcsem_to_sqlsem _ _ _ _ _ jtup _ H9). rename x into Stml0'.\n    decompose record (IHc _ H10). rename x into Sc0'.\n    exists List.nil. eexists. eexists. eexists. split. exact H1.\n    split. exact H3.\n    split. constructor. intro. simpl. rewrite env_app_nil_l.\n    (* TODO : lemmatize *)\n    generalize (j_disjunct_x_length _ _ _ _ _ _ _ _ H). intro Hlen. \n    rewrite H4. destruct (Sem.is_btrue (Sc h)).\n    - rewrite sel_true. rewrite sum_Rone_Rsingle, flat_Rsingle.\n      clear jtup. generalize dependent Stup. rewrite Hlen; intros. rewrite H2. destruct b0; reflexivity.\n      reflexivity.\n    - rewrite sel_false. rewrite sum_Rnil_sem_nil, flat_sem_nil, Hlen. destruct b0; reflexivity. intuition.\n  + simpl; intros G0 q1 q2 b0 sq2 Sq2 sq1 Sq1 e jq2 IHq2 jq1 IHq1. clear H; intros tml0' c0' Bl0' H.\n    inversion H; subst.\n    simpl; intros; subst. decompose record (IHq2 _ _ H3); rename x into ST2'; subst.\n    decompose record (IHq1 _ _ _ H9); rename x into G1; rename x0 into Stml0'; rename x1 into Sc0'; rename x2 into SBl1'.\n    enough (exists Stml0'', SQLSem.j_tml_sem ((G1 ++ (s2 :: List.nil)) ++ G0) tml0' Stml0'').\n    decompose record H6; rename x into Stml0''.\n    enough (exists Sc0'', SQLSem.j_cond_sem d ((G1 ++ (s2 :: List.nil)) ++ G0) c0' Sc0'').\n    decompose record H10; rename x into Sc0''.\n    eexists; eexists; eexists; eexists. split. exact H8.\n    split. exact H11.\n    split. constructor. constructor. exact H1. constructor. reflexivity. exact H5.\n    simpl; intros; subst. shelve.\n    rewrite <- app_assoc; eexists; exact H2.\n    rewrite <- app_assoc; eexists; exact H0.\n    Unshelve.\n    f_equal. do 3 rewrite <- length_concat_list_sum. rewrite concat_app. rewrite app_length. omega.\n    reflexivity.\n    (* involved equational reasoning *)\n    generalize H7; clear H7. destruct b0; intro H7.\n    - generalize (j_disjunct_x_length _ _ _ _ _ _ _ _ H9); intro Hlen. \n      rewrite eq_sum_rsum.\n      rewrite sel_rsum. rewrite rsum_rsum.\n      apply (@JMeq_trans _ _ _ _ (Rel.flat (Rel.rsum (Sq2 h) (fun Vl : Rel.T (length s2) => Rel.sum\n       (Rel.sel\n          (SBl1'\n             (Evl.env_app (s2 :: Datatypes.nil) G0\n                (Evl.env_of_tuple (s2 :: Datatypes.nil) (cast (Rel.T (length s2)) (Rel.T (length s2 + 0)) e Vl)) h))\n          (fun Wl : Rel.T (list_sum (List.map (length (A:=Name)) G1)) =>\n           Sem.is_btrue\n             (Sc0'\n                (Evl.env_app G1 (s2 :: G0) (Evl.env_of_tuple G1 Wl)\n                   (Evl.env_app (s2 :: Datatypes.nil) G0\n                      (Evl.env_of_tuple (s2 :: Datatypes.nil)\n                         (cast (Rel.T (length s2)) (Rel.T (length s2 + 0)) e Vl)) h)))))\n       (fun Wl : Rel.T (list_sum (List.map (length (A:=Name)) G1)) =>\n        Stml0'\n          (Evl.env_app G1 (s2 :: G0) (Evl.env_of_tuple G1 Wl)\n             (Evl.env_app (s2 :: Datatypes.nil) G0\n                (Evl.env_of_tuple (s2 :: Datatypes.nil) (cast (Rel.T (length s2)) (Rel.T (length s2 + 0)) e Vl)) h))) )))).\n      * apply eq_flat_dep. reflexivity.\n        apply eq_rsum_dep.\n          omega. reflexivity. apply cast_JMeq. apply (JMeq_trans (Rel_times_Rone _ _)). apply H4.\n        apply funext_JMeq. rewrite e; reflexivity. reflexivity.\n        intros. rewrite eq_sum_rsum.\n        enough (Rel.T (list_sum (List.map (length (A:=Name)) G1) + (length s2 + 0))\n                = Rel.T (list_sum (List.map (length (A:=Name)) (G1 ++ s2::List.nil)))).\n        apply (@JMeq_trans _ _ _ _\n          (Rel.rsum\n            (Rel.sel (Rel.times (SBl1' (Evl.env_app _ _ (Evl.env_of_tuple (s2::List.nil) x) h)) (Rel.Rsingle x))\n              (fun Vl => Sem.is_btrue (Sc0'' (Evl.env_app _ _ (Evl.env_of_tuple (G1++s2::List.nil) (cast _ _ H13 Vl)) h))))\n            (fun x0 => Rel.Rsingle (Stml0'' (Evl.env_app _ _ (Evl.env_of_tuple (G1 ++ s2 :: Datatypes.nil) (cast _ _ H13 x0)) h))))).\n        apply eq_rsum_dep.\n          do 2 rewrite <- length_concat_list_sum. rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n          reflexivity.\n        apply eq_sel_dep.\n          do 2 rewrite <- length_concat_list_sum. rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        apply cast_JMeq. apply eq_times_dep. reflexivity. reflexivity.\n        apply eq_JMeq. f_equal. reflexivity.\n        apply funext_JMeq. do 2 rewrite <- length_concat_list_sum. rewrite concat_app. rewrite app_length. simpl. rewrite app_length. simpl. reflexivity.\n        reflexivity.\n        intros. apply eq_JMeq. f_equal. f_equal. apply Evl.env_eq. simpl. f_equal. f_equal. f_equal.\n        symmetry. apply JMeq_eq. apply cast_JMeq. symmetry. exact H14.\n        apply funext_JMeq. do 2 rewrite <- length_concat_list_sum. rewrite concat_app. rewrite app_length. simpl. rewrite app_length. simpl. reflexivity.\n        reflexivity.\n        intros. apply eq_JMeq. f_equal. f_equal. apply Evl.env_eq. simpl. f_equal. f_equal. f_equal.\n        symmetry. apply JMeq_eq. apply cast_JMeq. symmetry. exact H14.\n\n        rewrite sel_times_single. rewrite rsum_times_single.\n        apply eq_rsum_dep; try reflexivity. apply eq_sel_dep; try reflexivity.\n        apply (f_JMeq _ _ SBl1'). f_equal. f_equal. apply JMeq_eq. symmetry; apply cast_JMeq; symmetry. exact H12.\n        apply eq_JMeq. extensionality Vl. f_equal. apply JMeq_eq. eapply (f_JMequal Sc0'' Sc0').\n        eapply (SQLSem.jc_sem_fun_dep _ _ _ _ H11 _ _ _ _ _ H2). Unshelve.\n        apply Evl.env_JMeq. rewrite <- app_assoc. reflexivity. simpl. rewrite app_assoc. f_equal.\n        do 2 rewrite projT1_env_of_tuple.\n        transitivity (to_list (append Vl x)).\n        apply JMeq_eq. eapply (f_JMequal (@to_list _ _) (@to_list _ _)).\n        eapply (f_JMeq _ _ (@to_list _)). do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        apply cast_JMeq. reflexivity.\n        rewrite to_list_append. f_equal.\n        generalize dependent y. rewrite e. simpl. intros. rewrite H12.\n        rewrite app_nil_r. apply JMeq_eq. eapply (f_JMequal (@to_list _ _) (@to_list _ _)).\n          eapply (f_JMeq _ _ (@to_list _)). omega. symmetry. apply fst_split_0_r.\n        apply eq_JMeq. extensionality Vl.\n        f_equal. apply JMeq_eq. eapply (f_JMequal Stml0'' Stml0').\n        eapply (j_tml_sem_fun_dep _ _ _ H8 _ _ _ _ _ H0). Unshelve.\n        apply Evl.env_JMeq. rewrite <- app_assoc. reflexivity. simpl. rewrite app_assoc. f_equal.\n        do 2 rewrite projT1_env_of_tuple.\n        transitivity (to_list (append Vl x)).\n        apply JMeq_eq. eapply (f_JMequal (@to_list _ _) (@to_list _ _)).\n        eapply (f_JMeq _ _ (@to_list _)). do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        apply cast_JMeq. reflexivity.\n        rewrite to_list_append. f_equal.\n        generalize dependent y. rewrite e. simpl. intros. rewrite H12.\n        rewrite app_nil_r. apply JMeq_eq. eapply (f_JMequal (@to_list _ _) (@to_list _ _)).\n          eapply (f_JMeq _ _ (@to_list _)). omega. symmetry. apply fst_split_0_r.\n        do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        reflexivity.\n        do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        f_equal. omega.\n        apply funext_JMeq. f_equal. omega. reflexivity. intuition.\n        rewrite <- app_assoc. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        reflexivity.\n        Unshelve.\n        do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        f_equal. omega.\n        apply funext_JMeq. f_equal. omega. reflexivity. intuition.\n      * apply (@trans_JMeq _ _ _ _ \n          (Rel.flat\n            (Rel.rsum (Sq2 h)\n               (fun Vl : Rel.T (length s2) => Rel.flat (\n                Rel.sum\n                  (Rel.sel\n                     (SBl1'\n                        (Evl.env_app (s2 :: Datatypes.nil) G0\n                           (Evl.env_of_tuple (s2 :: Datatypes.nil)\n                              (cast (Rel.T (length s2)) (Rel.T (length s2 + 0)) e Vl)) h))\n                     (fun Wl : Rel.T (list_sum (List.map (length (A:=Name)) G1)) =>\n                      Sem.is_btrue\n                        (Sc0'\n                           (Evl.env_app G1 (s2 :: G0) (Evl.env_of_tuple G1 Wl)\n                              (Evl.env_app (s2 :: Datatypes.nil) G0\n                                 (Evl.env_of_tuple (s2 :: Datatypes.nil)\n                                    (cast (Rel.T (length s2)) (Rel.T (length s2 + 0)) e Vl)) h)))))\n                  (fun Wl : Rel.T (list_sum (List.map (length (A:=Name)) G1)) =>\n                   Stml0'\n                     (Evl.env_app G1 (s2 :: G0) (Evl.env_of_tuple G1 Wl)\n                        (Evl.env_app (s2 :: Datatypes.nil) G0\n                           (Evl.env_of_tuple (s2 :: Datatypes.nil)\n                              (cast (Rel.T (length s2)) (Rel.T (length s2 + 0)) e Vl)) h)))))))).\n      erewrite (flat_rsum_flat _ \n        (fun Vl => Rel.sum (Rel.sel\n              (SBl1' (Evl.env_app _ _ (Evl.env_of_tuple (s2 :: Datatypes.nil) (cast _ _ e Vl)) h))\n              (fun Wl  => Sem.is_btrue (Sc0' (Evl.env_app _ _ (Evl.env_of_tuple G1 Wl) \n                (Evl.env_app _ _ (Evl.env_of_tuple (s2 :: Datatypes.nil) (cast _ _ e Vl)) h)))))\n          (fun Wl => Stml0' (Evl.env_app _ _ (Evl.env_of_tuple G1 Wl) (Evl.env_app _ _\n             (Evl.env_of_tuple (s2 :: Datatypes.nil) (cast _ _ e Vl)) h))))). reflexivity.\n      eapply (f_JMequal (@Rel.flat _) (@Rel.flat _)). Unshelve.\n      rewrite Hlen. reflexivity.\n      eapply (f_JMequal (Rel.rsum (Sq2 h)) (Rel.rsum (Sq2 h))).\n      rewrite Hlen. reflexivity.\n      apply funext_JMeq; try reflexivity. rewrite Hlen; reflexivity.\n      intros. subst. apply H7.\n      rewrite Hlen; reflexivity.\n      rewrite Hlen; reflexivity.\n      Unshelve. rewrite Hlen. reflexivity. rewrite Hlen. reflexivity.\n\n    - generalize (j_disjunct_x_length _ _ _ _ _ _ _ _ H9); intro Hlen. \n      rewrite eq_sum_rsum. \n      rewrite sel_rsum. rewrite rsum_rsum.\n      apply (@JMeq_trans _ _ _ _ (Rel.rsum (Sq2 h) (fun Vl : Rel.T (length s2) => Rel.sum\n       (Rel.sel\n          (SBl1'\n             (Evl.env_app (s2 :: Datatypes.nil) G0\n                (Evl.env_of_tuple (s2 :: Datatypes.nil) (cast (Rel.T (length s2)) (Rel.T (length s2 + 0)) e Vl)) h))\n          (fun Wl : Rel.T (list_sum (List.map (length (A:=Name)) G1)) =>\n           Sem.is_btrue\n             (Sc0'\n                (Evl.env_app G1 (s2 :: G0) (Evl.env_of_tuple G1 Wl)\n                   (Evl.env_app (s2 :: Datatypes.nil) G0\n                      (Evl.env_of_tuple (s2 :: Datatypes.nil)\n                         (cast (Rel.T (length s2)) (Rel.T (length s2 + 0)) e Vl)) h)))))\n       (fun Wl : Rel.T (list_sum (List.map (length (A:=Name)) G1)) =>\n        Stml0'\n          (Evl.env_app G1 (s2 :: G0) (Evl.env_of_tuple G1 Wl)\n             (Evl.env_app (s2 :: Datatypes.nil) G0\n                (Evl.env_of_tuple (s2 :: Datatypes.nil) (cast (Rel.T (length s2)) (Rel.T (length s2 + 0)) e Vl)) h)))))).\n      * apply eq_rsum_dep.\n          omega. reflexivity. apply cast_JMeq. apply (JMeq_trans (Rel_times_Rone _ _)). apply H4.\n        apply funext_JMeq. rewrite e; reflexivity. reflexivity.\n        intros. rewrite eq_sum_rsum.\n        enough (Rel.T (list_sum (List.map (length (A:=Name)) G1) + (length s2 + 0))\n                = Rel.T (list_sum (List.map (length (A:=Name)) (G1 ++ s2::List.nil)))).\n        apply (@JMeq_trans _ _ _ _\n          (Rel.rsum\n            (Rel.sel (Rel.times (SBl1' (Evl.env_app _ _ (Evl.env_of_tuple (s2::List.nil) x) h)) (Rel.Rsingle x))\n              (fun Vl => Sem.is_btrue (Sc0'' (Evl.env_app _ _ (Evl.env_of_tuple (G1++s2::List.nil) (cast _ _ H13 Vl)) h))))\n            (fun x0 => Rel.Rsingle (Stml0'' (Evl.env_app _ _ (Evl.env_of_tuple (G1 ++ s2 :: Datatypes.nil) (cast _ _ H13 x0)) h))))).\n        apply eq_rsum_dep.\n          do 2 rewrite <- length_concat_list_sum. rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n          reflexivity.\n        apply eq_sel_dep.\n          do 2 rewrite <- length_concat_list_sum. rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        apply cast_JMeq. apply eq_times_dep; try reflexivity.\n        apply funext_JMeq. do 2 rewrite <- length_concat_list_sum. rewrite concat_app. rewrite app_length. simpl. rewrite app_length. simpl. reflexivity.\n        reflexivity.\n        intros. apply eq_JMeq. f_equal. f_equal. apply Evl.env_eq. simpl. f_equal. f_equal. f_equal.\n        symmetry. apply JMeq_eq. apply cast_JMeq. symmetry. exact H14.\n        apply funext_JMeq. do 2 rewrite <- length_concat_list_sum. rewrite concat_app. rewrite app_length. simpl. rewrite app_length. simpl. reflexivity.\n        reflexivity.\n        intros. apply eq_JMeq. f_equal. f_equal. apply Evl.env_eq. simpl. f_equal. f_equal. f_equal.\n        symmetry. apply JMeq_eq. apply cast_JMeq. symmetry. exact H14.\n\n        rewrite sel_times_single. rewrite rsum_times_single.\n        apply eq_rsum_dep; try reflexivity. apply eq_sel_dep; try reflexivity.\n        apply (f_JMeq _ _ SBl1'). f_equal. f_equal. apply JMeq_eq. symmetry; apply cast_JMeq; symmetry. exact H12.\n        apply eq_JMeq. extensionality Vl. f_equal. apply JMeq_eq. eapply (f_JMequal Sc0'' Sc0').\n        eapply (SQLSem.jc_sem_fun_dep _ _ _ _ H11 _ _ _ _ _ H2). Unshelve.\n        apply Evl.env_JMeq. rewrite <- app_assoc. reflexivity. simpl. rewrite app_assoc. f_equal.\n        do 2 rewrite projT1_env_of_tuple.\n        transitivity (to_list (append Vl x)).\n        apply JMeq_eq. eapply (f_JMequal (@to_list _ _) (@to_list _ _)).\n        eapply (f_JMeq _ _ (@to_list _)). do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        apply cast_JMeq. reflexivity.\n        rewrite to_list_append. f_equal.\n        generalize dependent y. rewrite e. simpl. intros. rewrite H12. \n        rewrite app_nil_r. apply JMeq_eq. eapply (f_JMequal (@to_list _ _) (@to_list _ _)).\n          eapply (f_JMeq _ _ (@to_list _)). omega. symmetry. apply fst_split_0_r.\n        apply eq_JMeq. extensionality Vl.\n        f_equal. apply JMeq_eq. eapply (f_JMequal Stml0'' Stml0').\n        eapply (j_tml_sem_fun_dep _ _ _ H8 _ _ _ _ _ H0). Unshelve.\n        apply Evl.env_JMeq. rewrite <- app_assoc. reflexivity. simpl. rewrite app_assoc. f_equal.\n        do 2 rewrite projT1_env_of_tuple.\n        transitivity (to_list (append Vl x)).\n        apply JMeq_eq. eapply (f_JMequal (@to_list _ _) (@to_list _ _)).\n        eapply (f_JMeq _ _ (@to_list _)). do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        apply cast_JMeq. reflexivity.\n        rewrite to_list_append. f_equal.\n        generalize dependent y. rewrite e. simpl. intros. rewrite H12.\n        rewrite app_nil_r. apply JMeq_eq. eapply (f_JMequal (@to_list _ _) (@to_list _ _)).\n          eapply (f_JMeq _ _ (@to_list _)). omega. symmetry. apply fst_split_0_r.\n        do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        reflexivity.\n        do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        f_equal. omega. apply funext_JMeq; try reflexivity. f_equal. omega.\n        rewrite <- app_assoc. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        rewrite <- app_assoc. reflexivity.\n        reflexivity.\n        Unshelve.\n        do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        do 2 rewrite <- length_concat_list_sum.\n        rewrite concat_app. rewrite app_length. simpl. rewrite app_length. reflexivity.\n        f_equal. omega. apply funext_JMeq; try reflexivity. f_equal. omega.\n      * assert (length tml0' = length sq1). rewrite Hlen. reflexivity.\n        eapply (f_JMequal (Rel.rsum (Sq2 h)) (Rel.rsum (Sq2 h))).\n        rewrite H12. reflexivity.\n        apply funext_JMeq; try reflexivity. rewrite H12; reflexivity.\n        intros. subst. apply H7. \n        Unshelve. rewrite H12; reflexivity. rewrite H12; reflexivity.\n  (*-- mutual induction cases: gen --*)\n  + simpl; intros G0 x0 s0 e0. clear H; intros st0 Tt0 Hx0.\n    inversion Hx0; subst. rewrite e0 in H1. injection H1; intuition.\n    eexists; split. constructor. Unshelve. \n    intro; reflexivity.\n  + simpl; intros G0 t0 s0 St0 jt0 IHt0. clear H; intros st0 Tt0 Ht0.\n    inversion Ht0; subst. enough (s0 = st0). subst. decompose record (IHt0 _ H1); subst; rename x into Sq'.\n    intuition. eexists; split. constructor; exact H0. exact H2.\n    rewrite (j_coll_x_sem_eq_scm _ _ _ _ _ _ _ _ _ H1 jt0); reflexivity.\n  + simpl; intros G0 t1 t2 s0 St1 St2 jt1 IHt1 jt2 IHt2. clear H. intros st0 Tt0 H.\n    inversion H; subst. enough (s0 = st0). subst.\n    decompose record (IHt1 _ H3). decompose record (IHt2 _ H4). rename x into Sq1'; rename x0 into Sq2'.\n    intuition. eexists; split. constructor. constructor. exact H1. exact H5.\n    simpl; intro. rewrite H2, H6. reflexivity.\n    rewrite (j_coll_x_sem_eq_scm _ _ _ _ _ _ _ _ _ H3 jt1); reflexivity.\n  + simpl; intros G0 x0 s0 e0. clear H; intros st0 Tt0 Hx0.\n    inversion Hx0; subst. rewrite e0 in H1. injection H1; intuition.\n    generalize e0; clear e0; rewrite H; intro.\n    assert (NoDup st0). apply (db_schema_nodup _ _ _ e0).\n    epose (Hq := (sql_distinct_sem d G0 st0 (tbbase x0) _ _ _)); clearbody Hq.\n      Unshelve. shelve. shelve. exact H0. constructor.\n      Unshelve. decompose record Hq; clear Hq; rename x into Sq.\n    eexists; split. constructor. exact H3. intro; apply eq_JMeq; apply H4.\n  + simpl; intros G0 t1 t2 s0 St1 St2 jt1 IHt1 jt2 IHt2. clear H. intros st0 Tt0 H.\n    inversion H; subst. enough (s0 = st0). subst.\n    decompose record (IHt1 _ H3). decompose record (IHt2 _ H4). rename x into Sq1'; rename x0 into Sq2'.\n    intuition. \n    assert (NoDup st0). apply (j_coll_x_nodup_schema _ _ _ _ _ _ H3).\n    epose (Hq := (sql_distinct_sem d G0 st0 (tbquery (q1' EXCEPT ALL q2')) _ _ _)); clearbody Hq.\n      Unshelve. shelve. shelve. shelve. exact H0. constructor. constructor. exact H1. exact H5.\n      Unshelve. decompose record Hq; clear Hq; rename x into Sq.\n    eexists; split. constructor. exact H8. intro; rewrite <- H2, <- H6, H9; reflexivity.\n    rewrite (j_coll_x_sem_eq_scm _ _ _ _ _ _ _ _ _ H3 jt1); reflexivity.\n  Qed.\n\nEnd RcToSql.", "meta": {"author": "wricciot", "repo": "nullSQL", "sha": "bdc482ca138b2807334c14de2103abb67e03423a", "save_path": "github-repos/coq/wricciot-nullSQL", "path": "github-repos/coq/wricciot-nullSQL/nullSQL-bdc482ca138b2807334c14de2103abb67e03423a/RcToSQL.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21320659038546008}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssrZ ZArith_ext seq_ext machine_int multi_int.\nImport MachineInt.\nRequire Import mips_bipl mapstos.\nImport mips_bipl.expr_m.\nImport mips_bipl.assert_m.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope mips_assert_scope.\n\n(** construct a heap from a list of int 32's *)\n\nDefinition list2heap (a : nat) (l : list (int 32)) : heap.t :=\n  map_prop_m.mk_finmap (zip (iota a (size l)) l).\n\nLemma dom_list2heap l x : heap.dom (list2heap x l) = iota x (size l).\nProof.\nrewrite /list2heap -heap.elts_dom map_prop_m.elts_mk_finmap; last first.\n  rewrite unzip1_zip /= ?size_iota //; by apply ordset.ordered_iota.\nby rewrite -/(unzip1 _) unzip1_zip // size_iota.\nQed.\n\nLemma cdom_list2heap l x : heap.cdom (list2heap x l) = l.\nProof.\nrewrite /list2heap -heap.elts_cdom map_prop_m.elts_mk_finmap; last first.\n  rewrite unzip1_zip /= ?size_iota //; by apply ordset.ordered_iota.\nby rewrite -/(unzip2 _) unzip2_zip // size_iota.\nQed.\n\nLemma disj_list2heap l n h : disj (iota n (size l)) (heap.dom h) -> list2heap n l # h.\nProof. move=> ?; by rewrite heap.disjE; apply/seq_ext.disP; rewrite dom_list2heap. Qed.\n\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope mips_expr_scope.\n\nLemma mapstos_list2heap : forall l n e s, u2Z ( [ e ]e_ s ) = 4 * Z_of_nat n ->\n  u2Z ( [ e ]e_ s ) + 4 * (Z_of_nat (size l) - 1) < Zbeta 1 ->\n  (e |--> l) s (list2heap n l).\nProof.\nelim=> [n e s e_mod e_fit | hd tl IH v n0 s Hv Hn /=].\n- split; last by [].\n  apply Zdivide_mod.\n  exists (Z_of_nat n); by rewrite mulZC.\n- destruct tl as [|i tl].\n  + rewrite /list2heap /= heap.unionhe.\n    exists (heap.sing v hd), heap.emp; split; first by apply heap.disjhe.\n    split; first by rewrite heap.unionhe.\n    split; first by exists v.\n    split; last by [].\n    apply u2Z_add_mod => //.\n    apply Zdivide_mod.\n    exists (Z_of_nat v); by rewrite mulZC.\n  + rewrite [i :: _]lock /list2heap /= -lock.\n    apply assert_m.con_cons.\n    * apply heap.disj_sym, disj_list2heap.\n      apply/disP; by rewrite heap.dom_sing dis_seq_singl.\n    * by exists v.\n    * apply (mapstos_ext (int_e ([ n0 ]e_s `+ four32)) s) => //.\n      apply IH.\n      - rewrite u2Z_add_Z2u //; last first.\n          rewrite (_ : Z_of_nat _ - 1 = 1 + Z_of_nat (size tl)) in Hn; last first.\n            rewrite [size _]/=; omegaz.\n          rewrite -Zbeta1E; lia.\n        rewrite Z_S Hv; ring.\n      - rewrite u2Z_add_Z2u //; last first.\n          rewrite !Z_S in Hn; rewrite -Zbeta1E; lia.\n        rewrite (_ : Z_of_nat _ - 1 = Z_of_nat (size (i :: tl))) in Hn; last by rewrite [size _]/=; omegaz.\n        lia.\nQed.\n\nLemma mapstos_inv_list2heap : forall l e s h, (e |--> l) s h ->\n  u2Z ( [ e ]e_ s) + 4 * Z_of_nat (size l) < Zbeta 1 ->\n  h = list2heap '|u2Z ( [ e ]e_ s `>> 2)| l.\nProof.\nelim=> [e s h Hmem Hfit /= | hd tl IH e s h].\n- rewrite /= in Hmem.\n  by case: Hmem.\n- rewrite [assert_m.mapstos _ _]/=.\n  case=> h1 [h2 [Hdisj [Hunion [Hmem1 Hmem2]]]] Hinmem.\n  case: Hmem1 => loc [H1 H2].\n  rewrite /= in H2 *.\n  have -> : '|u2Z ( [ e ]e_ s `>> 2)| = loc.\n    rewrite (@shrl_2 _ (Z_of_nat loc)) // Z2uK //.\n    by rewrite Zabs_nat_Z_of_nat.\n    split; first by apply Zle_0_nat.\n    move: (max_u2Z ( [ e ]e_ s)).\n    rewrite H1 (_ : 2 ^^ 32 = 2 ^^ 30 * 4) // mulZC => X.\n    apply Zmult_gt_0_lt_reg_r in X => //; lia.\n  rewrite /list2heap /=.\n  have <- : '|u2Z ([ e ]e_ s `+ four32 `>> 2)| = S loc.\n    move: (@u2Z_shrl _ ([ e ]e_ s `+ four32) 2 refl_equal) => // X.\n    rewrite [_ ^^ _]/= (@u2Z_rem'' _ _ _ (1 + Z_of_nat loc)) in X; last first.\n      rewrite u2Z_add_Z2u // H1.\n      + rewrite [_ ^^ _]/=; ring.\n      + rewrite Z_S in Hinmem; rewrite -Zbeta1E; lia.\n    rewrite addZ0 u2Z_add_Z2u // in X; last first.\n      rewrite Z_S in Hinmem; rewrite -Zbeta1E; lia.\n    have -> : u2Z (eval e s `+ four32 `>> 2) = 1 + Z_of_nat loc by lia.\n    rewrite Zabs_nat_Zplus //; last exact/Zle_0_nat.\n    by rewrite Zabs_nat_Z_of_nat.\n  move: {IH}(IH _ _ _ Hmem2).\n  rewrite /list2heap.\n  move=> <- //; last first.\n    rewrite [eval _ _]/= u2Z_add_Z2u //.\n    + rewrite [size _]/= Z_S in Hinmem; lia.\n    + rewrite Z_S in Hinmem; rewrite -Zbeta1E; lia.\n  by rewrite -H2.\nQed.\n\nLemma inv_list2heap P l e s h : (P ** e |--> l) s h ->\n  u2Z ([e ]e_ s) + 4 * Z_of_nat (size l) < Zbeta 1 ->\n  @seq_ext.inc heap.l\n  (iota '|u2Z ([ e ]e_ s) / 4| (size l))\n  (heap.dom h).\nProof.\nmove=> Hmem Hfit.\ncase: Hmem => h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]].\napply mapstos_inv_list2heap in Hh2 => //.\nrewrite h1Uh2.\nset d := iota _ _.\nrewrite (_ : d = heap.dom h2).\n  apply/seq_ext.incP => i Hi.\n  apply/seq_ext.inP.\n  rewrite heap.unionC //.\n  apply heap.in_dom_union_L.\n  by apply/seq_ext.inP.\nby rewrite /d Hh2 dom_list2heap u2Z_shrl'.\nQed.\n\nLemma mapstos_inv_proj_list2heap P l e s h : (P ** e |--> l) s h ->\n  u2Z ( [ e ]e_ s) + 4 * Z_of_nat (size l) < Zbeta 1 ->\n  heap.proj h (iota '|(u2Z ([ e ]e_ s) / 4)| (size l)) =\n  list2heap '|u2Z ( [ e ]e_ s `>> 2)| l.\nProof.\nmove=> HP Hfit.\ncase: HP => h1 [h2 [h1dh2 [h1Uh2 [Hh1 Hh2]]]].\napply mapstos_inv_list2heap in Hh2 => //.\nrewrite h1Uh2.\nset d2 := iota _ _.\nhave -> : d2 = heap.dom h2 by rewrite /d2 Hh2 dom_list2heap u2Z_shrl'.\nrewrite heap.proj_union_R_dom; last exact/heap.disj_sym.\nby rewrite heap.proj_itself.\nQed.\n\nLocal Close Scope zarith_ext_scope.\n\n(** extract a list of contiguous int 32's from a heap *)\n\nDefinition heap2list (b : heap.l) (n : nat) (h : heap.t) : list heap.v :=\n  heap.cdom (heap.proj h (seq.iota b n)).\n\nLemma len_heap2list : forall (n : nat) (a : heap.l) h,\n  List.incl (iota a n : list heap.l) (heap.dom h) -> size (heap2list a n h) = n.\nProof.\nmove=> n a h H.\nhave {}H : seq_ext.inc (seq.iota a n : seq.seq ssrnat.nat_eqType) (heap.dom h).\n  by apply/seq_ext.incP.\napply heap.dom_proj_exact in H; last first.\n  by apply ordset.ordered_iota.\nby rewrite /heap2list heap.size_cdom_dom H seq.size_iota.\nQed.\n\nLemma heap2list2heap : forall n z l, size l = n -> heap2list z n (list2heap z l) = l.\nProof.\nelim => [z [] //= _ | n IH z [|h t] // [len_t] ].\n- by rewrite /heap2list heap.proj_emp heap.cdom_emp.\n- rewrite /heap2list /list2heap /= heap.proj_union_sing; last first.\n    by rewrite seq.in_cons eqxx.\n  rewrite heap.cdom_union_sing /=.\n  + congr cons.\n    rewrite heap.dom_proj_cons.\n    * exact: IH.\n    * by rewrite dom_list2heap // mem_iota ltnn.\n  + apply order.lt_lb => m.\n    case/heap.in_dom_proj_inter => Hm1 Hm2.\n    rewrite dom_list2heap // in Hm1.\n    rewrite /heap.ltl /order.NatOrder.ltA /ltn /=.\n    move: Hm1.\n    by rewrite mem_iota => /andP[].\nQed.\n\n(* TODO: generalize? *)\nLemma heap2list_list2heap_union n z l h : size l = n ->\n  list2heap z l # h ->\n  heap2list z n (list2heap z l \\U h) = heap2list z n (list2heap z l).\nProof.\nmove=> Hn Hdisj.\nrewrite /heap2list.\nmove: (dom_list2heap l z).\nrewrite Hn => <-.\nby rewrite heap.proj_union_L_dom // heap.proj_itself.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/cryptoasm/encode_decode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21320659038546008}}
{"text": "(* Default settings (from HsToCoq.Coq.Preamble) *)\n\nGeneralizable All Variables.\n\nUnset Implicit Arguments.\nSet Maximal Implicit Insertion.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Coq.Program.Tactics.\nRequire Coq.Program.Wf.\n\n(* Preamble *)\n\nRequire BitTerminationProofs.\n\n(* Converted imports: *)\n\nRequire Coq.Init.Peano.\nRequire Coq.NArith.BinNat.\nRequire Coq.Numbers.BinNums.\nRequire Data.Bits.\nRequire Data.Foldable.\nRequire Data.Maybe.\nRequire Data.Tuple.\nRequire GHC.Base.\nRequire GHC.Err.\nRequire GHC.Num.\nRequire GHC.Wf.\nRequire Utils.Containers.Internal.BitUtil.\nImport Data.Bits.Notations.\nImport GHC.Base.Notations.\nImport GHC.Num.Notations.\n\n(* Converted type declarations: *)\n\nDefinition Prefix :=\n  Coq.Numbers.BinNums.N.\n\nDefinition Nat :=\n  Coq.Numbers.BinNums.N.\n\nDefinition Mask :=\n  Coq.Numbers.BinNums.N.\n\nDefinition Key :=\n  Coq.Numbers.BinNums.N%type.\n\nDefinition BitMap :=\n  Coq.Numbers.BinNums.N.\n\nInductive IntSet : Type\n  := Bin : Prefix -> Mask -> IntSet -> IntSet -> IntSet\n  |  Tip : Prefix -> BitMap -> IntSet\n  |  Nil : IntSet.\n\nInductive Stack : Type\n  := Push : Prefix -> IntSet -> Stack -> Stack\n  |  Nada : Stack.\n\nInstance Default__IntSet : GHC.Err.Default IntSet :=\n  GHC.Err.Build_Default _ Nil.\n\nInstance Default__Stack : GHC.Err.Default Stack := GHC.Err.Build_Default _ Nada.\n\n(* Midamble *)\n\n(** Additional definitions for termination proof *)\n\nFixpoint size_nat (t : IntSet) : nat :=\n  match t with\n  | Bin _ _ l r => S (size_nat l + size_nat r)%nat\n  | Tip _ bm => 0\n  | Nil => 0\n  end.\n\nRequire Omega.\nLtac termination_by_omega :=\n  Coq.Program.Tactics.program_simpl;\n  simpl;Omega.omega.\n\n\nRequire Import Coq.NArith.NArith.\n(* Z.ones 6 = 64-1 *)\n(* Definition suffixBitMask := Coq.NArith.BinNat.N.ones 6%N. *)\n\n(* Converted value declarations: *)\n\nDefinition zero : Coq.Numbers.BinNums.N -> Mask -> bool :=\n  fun i m => ((i) Data.Bits..&.(**) (m)) GHC.Base.== #0.\n\nDefinition tip : Prefix -> BitMap -> IntSet :=\n  fun arg_0__ arg_1__ =>\n    match arg_0__, arg_1__ with\n    | _, num_2__ =>\n        if num_2__ GHC.Base.== #0 : bool then Nil else\n        match arg_0__, arg_1__ with\n        | kx, bm => Tip kx bm\n        end\n    end.\n\nDefinition suffixBitMask :=\n  Coq.NArith.BinNat.N.ones 6.\n\nDefinition suffixOf : Coq.Numbers.BinNums.N -> Coq.Numbers.BinNums.N :=\n  fun x => x Data.Bits..&.(**) suffixBitMask.\n\nDefinition splitRoot : IntSet -> list IntSet :=\n  fun arg_0__ =>\n    match arg_0__ with\n    | Nil => nil\n    | (Tip _ _ as x) => cons x nil\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool then cons r (cons l nil) else\n        cons l (cons r nil)\n    end.\n\nDefinition size : IntSet -> Coq.Numbers.BinNums.N :=\n  let fix go arg_0__ arg_1__\n            := match arg_0__, arg_1__ with\n               | acc, Bin _ _ l r => go (go acc l) r\n               | acc, Tip _ bm =>\n                   acc GHC.Num.+ Utils.Containers.Internal.BitUtil.bitcount #0 bm\n               | acc, Nil => acc\n               end in\n  go #0.\n\nDefinition shorter : Mask -> Mask -> bool :=\n  fun m1 m2 => (m1) GHC.Base.> (m2).\n\nDefinition revNat : Nat -> Nat :=\n  fun x1 =>\n    let 'x2 := ((Utils.Containers.Internal.BitUtil.shiftRL x1 #1) Data.Bits..&.(**)\n                  #6148914691236517205) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x1 Data.Bits..&.(**)\n                                                             #6148914691236517205) #1) in\n    let 'x3 := ((Utils.Containers.Internal.BitUtil.shiftRL x2 #2) Data.Bits..&.(**)\n                  #3689348814741910323) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x2 Data.Bits..&.(**)\n                                                             #3689348814741910323) #2) in\n    let 'x4 := ((Utils.Containers.Internal.BitUtil.shiftRL x3 #4) Data.Bits..&.(**)\n                  #1085102592571150095) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x3 Data.Bits..&.(**)\n                                                             #1085102592571150095) #4) in\n    let 'x5 := ((Utils.Containers.Internal.BitUtil.shiftRL x4 #8) Data.Bits..&.(**)\n                  #71777214294589695) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x4 Data.Bits..&.(**)\n                                                             #71777214294589695) #8) in\n    let 'x6 := ((Utils.Containers.Internal.BitUtil.shiftRL x5 #16) Data.Bits..&.(**)\n                  #281470681808895) Data.Bits..|.(**)\n                 (Utils.Containers.Internal.BitUtil.shiftLL (x5 Data.Bits..&.(**)\n                                                             #281470681808895) #16) in\n    (Utils.Containers.Internal.BitUtil.shiftRL x6 #32) Data.Bits..|.(**)\n    (Utils.Containers.Internal.BitUtil.shiftLL x6 #32).\n\nDefinition prefixOf : Coq.Numbers.BinNums.N -> Prefix :=\n  fun x => Coq.NArith.BinNat.N.ldiff x suffixBitMask.\n\nDefinition null : IntSet -> bool :=\n  fun arg_0__ => match arg_0__ with | Nil => true | _ => false end.\n\nDefinition nequal : IntSet -> IntSet -> bool :=\n  fix nequal arg_0__ arg_1__\n        := match arg_0__, arg_1__ with\n           | Bin p1 m1 l1 r1, Bin p2 m2 l2 r2 =>\n               orb (m1 GHC.Base./= m2) (orb (p1 GHC.Base./= p2) (orb (nequal l1 l2) (nequal r1\n                                                                      r2)))\n           | Tip kx1 bm1, Tip kx2 bm2 => orb (kx1 GHC.Base./= kx2) (bm1 GHC.Base./= bm2)\n           | Nil, Nil => false\n           | _, _ => true\n           end.\n\nDefinition maskW : Nat -> Nat -> Prefix :=\n  fun i m => Coq.NArith.BinNat.N.ldiff i (2 * m - 1 % N).\n\nDefinition mask : Coq.Numbers.BinNums.N -> Mask -> Prefix :=\n  fun i m => maskW (i) (m).\n\nDefinition match_ : Coq.Numbers.BinNums.N -> Prefix -> Mask -> bool :=\n  fun i p m => (mask i m) GHC.Base.== p.\n\nDefinition nomatch : Coq.Numbers.BinNums.N -> Prefix -> Mask -> bool :=\n  fun i p m => (mask i m) GHC.Base./= p.\n\nDefinition subsetCmp : IntSet -> IntSet -> comparison :=\n  fix subsetCmp arg_0__ arg_1__\n        := match arg_0__, arg_1__ with\n           | (Bin p1 m1 l1 r1 as t1), Bin p2 m2 l2 r2 =>\n               let subsetCmpEq :=\n                 match pair (subsetCmp l1 l2) (subsetCmp r1 r2) with\n                 | pair Gt _ => Gt\n                 | pair _ Gt => Gt\n                 | pair Eq Eq => Eq\n                 | _ => Lt\n                 end in\n               let subsetCmpLt :=\n                 if nomatch p1 p2 m2 : bool then Gt else\n                 if zero p1 m2 : bool then subsetCmp t1 l2 else\n                 subsetCmp t1 r2 in\n               if shorter m1 m2 : bool then Gt else\n               if shorter m2 m1 : bool\n               then match subsetCmpLt with\n                    | Gt => Gt\n                    | _ => Lt\n                    end else\n               if p1 GHC.Base.== p2 : bool then subsetCmpEq else\n               Gt\n           | _, _ =>\n               match arg_0__, arg_1__ with\n               | Bin _ _ _ _, _ => Gt\n               | Tip kx1 bm1, Tip kx2 bm2 =>\n                   if kx1 GHC.Base./= kx2 : bool then Gt else\n                   if bm1 GHC.Base.== bm2 : bool then Eq else\n                   if Data.Bits.xor bm1 (bm1 Data.Bits..&.(**) bm2) GHC.Base.== #0 : bool\n                   then Lt else\n                   Gt\n               | (Tip kx _ as t1), Bin p m l r =>\n                   if nomatch kx p m : bool then Gt else\n                   if zero kx m : bool then match subsetCmp t1 l with | Gt => Gt | _ => Lt end else\n                   match subsetCmp t1 r with\n                   | Gt => Gt\n                   | _ => Lt\n                   end\n               | Tip _ _, Nil => Gt\n               | Nil, Nil => Eq\n               | Nil, _ => Lt\n               end\n           end.\n\nDefinition isSubsetOf : IntSet -> IntSet -> bool :=\n  fix isSubsetOf arg_0__ arg_1__\n        := match arg_0__, arg_1__ with\n           | (Bin p1 m1 l1 r1 as t1), Bin p2 m2 l2 r2 =>\n               if shorter m1 m2 : bool then false else\n               if shorter m2 m1 : bool\n               then andb (match_ p1 p2 m2) (if zero p1 m2 : bool\n                          then isSubsetOf t1 l2\n                          else isSubsetOf t1 r2) else\n               andb (p1 GHC.Base.== p2) (andb (isSubsetOf l1 l2) (isSubsetOf r1 r2))\n           | _, _ =>\n               match arg_0__, arg_1__ with\n               | Bin _ _ _ _, _ => false\n               | Tip kx1 bm1, Tip kx2 bm2 =>\n                   andb (kx1 GHC.Base.== kx2) (Data.Bits.xor bm1 (bm1 Data.Bits..&.(**) bm2)\n                         GHC.Base.==\n                         #0)\n               | (Tip kx _ as t1), Bin p m l r =>\n                   if nomatch kx p m : bool then false else\n                   if zero kx m : bool then isSubsetOf t1 l else\n                   isSubsetOf t1 r\n               | Tip _ _, Nil => false\n               | Nil, _ => true\n               end\n           end.\n\nDefinition isProperSubsetOf : IntSet -> IntSet -> bool :=\n  fun t1 t2 => match subsetCmp t1 t2 with | Lt => true | _ => false end.\n\nDefinition indexOfTheOnlyBit :=\n  fun x => Coq.NArith.BinNat.N.log2 x.\n\nDefinition lowestBitSet : Nat -> Coq.Numbers.BinNums.N :=\n  fun x => indexOfTheOnlyBit (Utils.Containers.Internal.BitUtil.lowestBitMask x).\n\nDefinition unsafeFindMin : IntSet -> option Key :=\n  fix unsafeFindMin arg_0__\n        := match arg_0__ with\n           | Nil => None\n           | Tip kx bm => Some (kx GHC.Num.+ lowestBitSet bm)\n           | Bin _ _ l _ => unsafeFindMin l\n           end.\n\nDefinition highestBitSet : Nat -> Coq.Numbers.BinNums.N :=\n  fun x => indexOfTheOnlyBit (Utils.Containers.Internal.BitUtil.highestBitMask x).\n\nDefinition unsafeFindMax : IntSet -> option Key :=\n  fix unsafeFindMax arg_0__\n        := match arg_0__ with\n           | Nil => None\n           | Tip kx bm => Some (kx GHC.Num.+ highestBitSet bm)\n           | Bin _ _ _ r => unsafeFindMax r\n           end.\n\nDefinition revNatSafe n :=\n  Coq.NArith.BinNat.N.modulo (revNat n) (Coq.NArith.BinNat.N.pow 2 64).\n\nProgram Definition foldrBits {a}\n           : Coq.Numbers.BinNums.N ->\n             (Coq.Numbers.BinNums.N -> a -> a) -> a -> Nat -> a :=\n          fun prefix f z bitmap =>\n            let go :=\n              GHC.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                               Coq.NArith.BinNat.N.to_nat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                               match arg_0__, arg_1__ with\n                               | num_2__, acc =>\n                                   if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                                   match arg_0__, arg_1__ with\n                                   | bm, acc =>\n                                       let bitmask := Utils.Containers.Internal.BitUtil.lowestBitMask bm in\n                                       let bi := indexOfTheOnlyBit bitmask in\n                                       go (Data.Bits.xor bm bitmask) ((f ((prefix GHC.Num.+ (#64 GHC.Num.- #1))\n                                                                          GHC.Num.-\n                                                                          bi)) acc)\n                                   end\n                               end) in\n            go (revNatSafe bitmap) z.\nSolve Obligations with (BitTerminationProofs.termination_foldl).\n\nProgram Definition foldr'Bits {a}\n           : Coq.Numbers.BinNums.N ->\n             (Coq.Numbers.BinNums.N -> a -> a) -> a -> Nat -> a :=\n          fun prefix f z bitmap =>\n            let go :=\n              GHC.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                               Coq.NArith.BinNat.N.to_nat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                               match arg_0__, arg_1__ with\n                               | num_2__, acc =>\n                                   if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                                   match arg_0__, arg_1__ with\n                                   | bm, acc =>\n                                       let bitmask := Utils.Containers.Internal.BitUtil.lowestBitMask bm in\n                                       let bi := indexOfTheOnlyBit bitmask in\n                                       go (Data.Bits.xor bm bitmask) ((f ((prefix GHC.Num.+ (#64 GHC.Num.- #1))\n                                                                          GHC.Num.-\n                                                                          bi)) acc)\n                                   end\n                               end) in\n            go (revNatSafe bitmap) z.\nSolve Obligations with (BitTerminationProofs.termination_foldl).\n\nDefinition foldr' {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | z', Nil => z'\n                 | z', Tip kx bm => foldr'Bits kx f z' bm\n                 | z', Bin _ _ l r => go (go z' r) l\n                 end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z l) r else go (go z r) l\n      | _ => go z t\n      end.\n\nDefinition foldr {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | z', Nil => z'\n                 | z', Tip kx bm => foldrBits kx f z' bm\n                 | z', Bin _ _ l r => go (go z' r) l\n                 end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z l) r else go (go z r) l\n      | _ => go z t\n      end.\n\nDefinition foldrFB {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  foldr.\n\nDefinition toAscList : IntSet -> list Key :=\n  foldr cons nil.\n\nDefinition toList : IntSet -> list Key :=\n  toAscList.\n\nProgram Definition foldlBits {a}\n           : Coq.Numbers.BinNums.N ->\n             (a -> Coq.Numbers.BinNums.N -> a) -> a -> Nat -> a :=\n          fun prefix f z bitmap =>\n            let go :=\n              GHC.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                               Coq.NArith.BinNat.N.to_nat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                               match arg_0__, arg_1__ with\n                               | num_2__, acc =>\n                                   if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                                   match arg_0__, arg_1__ with\n                                   | bm, acc =>\n                                       let bitmask := Utils.Containers.Internal.BitUtil.lowestBitMask bm in\n                                       let bi := indexOfTheOnlyBit bitmask in\n                                       go (Data.Bits.xor bm bitmask) (f acc (prefix GHC.Num.+ bi))\n                                   end\n                               end) in\n            go bitmap z.\nSolve Obligations with (BitTerminationProofs.termination_foldl).\n\nProgram Definition foldl'Bits {a}\n           : Coq.Numbers.BinNums.N ->\n             (a -> Coq.Numbers.BinNums.N -> a) -> a -> Nat -> a :=\n          fun prefix f z bitmap =>\n            let go :=\n              GHC.Wf.wfFix2 Coq.Init.Peano.lt (fun arg_0__ arg_1__ =>\n                               Coq.NArith.BinNat.N.to_nat arg_0__) _ (fun arg_0__ arg_1__ go =>\n                               match arg_0__, arg_1__ with\n                               | num_2__, acc =>\n                                   if Bool.Sumbool.sumbool_of_bool (num_2__ GHC.Base.== #0) then acc else\n                                   match arg_0__, arg_1__ with\n                                   | bm, acc =>\n                                       let bitmask := Utils.Containers.Internal.BitUtil.lowestBitMask bm in\n                                       let bi := indexOfTheOnlyBit bitmask in\n                                       go (Data.Bits.xor bm bitmask) (f acc (prefix GHC.Num.+ bi))\n                                   end\n                               end) in\n            go bitmap z.\nSolve Obligations with (BitTerminationProofs.termination_foldl).\n\nDefinition foldl' {a} : (a -> Key -> a) -> a -> IntSet -> a :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | z', Nil => z'\n                 | z', Tip kx bm => foldl'Bits kx f z' bm\n                 | z', Bin _ _ l r => go (go z' l) r\n                 end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z r) l else go (go z l) r\n      | _ => go z t\n      end.\n\nDefinition foldl {a} : (a -> Key -> a) -> a -> IntSet -> a :=\n  fun f z =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | z', Nil => z'\n                 | z', Tip kx bm => foldlBits kx f z' bm\n                 | z', Bin _ _ l r => go (go z' l) r\n                 end in\n    fun t =>\n      match t with\n      | Bin _ m l r => if m GHC.Base.< #0 : bool then go (go z r) l else go (go z l) r\n      | _ => go z t\n      end.\n\nDefinition foldlFB {a} : (a -> Key -> a) -> a -> IntSet -> a :=\n  foldl.\n\nDefinition toDescList : IntSet -> list Key :=\n  foldl (GHC.Base.flip cons) nil.\n\nDefinition fold {b} : (Key -> b -> b) -> b -> IntSet -> b :=\n  foldr.\n\nDefinition equal : IntSet -> IntSet -> bool :=\n  fix equal arg_0__ arg_1__\n        := match arg_0__, arg_1__ with\n           | Bin p1 m1 l1 r1, Bin p2 m2 l2 r2 =>\n               andb (m1 GHC.Base.== m2) (andb (p1 GHC.Base.== p2) (andb (equal l1 l2) (equal r1\n                                                                         r2)))\n           | Tip kx1 bm1, Tip kx2 bm2 => andb (kx1 GHC.Base.== kx2) (bm1 GHC.Base.== bm2)\n           | Nil, Nil => true\n           | _, _ => false\n           end.\n\nDefinition empty : IntSet :=\n  Nil.\n\nDefinition elems : IntSet -> list Key :=\n  toAscList.\n\nProgram Fixpoint disjoint (arg_0__ : IntSet) (arg_1__ : IntSet)\n                          {measure (size_nat arg_0__ + size_nat arg_1__)} : bool\n                   := match arg_0__, arg_1__ with\n                      | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n                          let disjoint2 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then true else\n                            if Bool.Sumbool.sumbool_of_bool (zero p1 m2) then disjoint t1 l2 else\n                            disjoint t1 r2 in\n                          let disjoint1 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then true else\n                            if Bool.Sumbool.sumbool_of_bool (zero p2 m1) then disjoint l1 t2 else\n                            disjoint r1 t2 in\n                          if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then disjoint1 else\n                          if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then disjoint2 else\n                          if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n                          then andb (disjoint l1 l2) (disjoint r1 r2) else\n                          true\n                      | (Bin _ _ _ _ as t1), Tip kx2 bm2 =>\n                          let fix disjointBM arg_11__\n                                    := match arg_11__ with\n                                       | Bin p1 m1 l1 r1 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx2 p1 m1) then true else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx2 m1) then disjointBM l1 else\n                                           disjointBM r1\n                                       | Tip kx1 bm1 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                                           then (bm1 Data.Bits..&.(**) bm2) GHC.Base.== #0 else\n                                           true\n                                       | Nil => true\n                                       end in\n                          disjointBM t1\n                      | Bin _ _ _ _, Nil => true\n                      | Tip kx1 bm1, t2 =>\n                          let fix disjointBM arg_18__\n                                    := match arg_18__ with\n                                       | Bin p2 m2 l2 r2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx1 p2 m2) then true else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx1 m2) then disjointBM l2 else\n                                           disjointBM r2\n                                       | Tip kx2 bm2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                                           then (bm1 Data.Bits..&.(**) bm2) GHC.Base.== #0 else\n                                           true\n                                       | Nil => true\n                                       end in\n                          disjointBM t2\n                      | Nil, _ => true\n                      end.\nSolve Obligations with (termination_by_omega).\n\nDefinition branchMask : Prefix -> Prefix -> Mask :=\n  fun p1 p2 =>\n    Coq.NArith.BinNat.N.pow 2 (Coq.NArith.BinNat.N.log2 (Coq.NArith.BinNat.N.lxor p1\n                                                                                  p2)).\n\nDefinition link : Prefix -> IntSet -> Prefix -> IntSet -> IntSet :=\n  fun p1 t1 p2 t2 =>\n    let m := branchMask p1 p2 in\n    let p := mask p1 m in if zero p1 m : bool then Bin p m t1 t2 else Bin p m t2 t1.\n\nDefinition insertBM : Prefix -> BitMap -> IntSet -> IntSet :=\n  fix insertBM arg_0__ arg_1__ arg_2__\n        := match arg_0__, arg_1__, arg_2__ with\n           | kx, bm, (Bin p m l r as t) =>\n               if nomatch kx p m : bool then link kx (Tip kx bm) p t else\n               if zero kx m : bool then Bin p m (insertBM kx bm l) r else\n               Bin p m l (insertBM kx bm r)\n           | kx, bm, (Tip kx' bm' as t) =>\n               if kx' GHC.Base.== kx : bool then Tip kx' (bm Data.Bits..|.(**) bm') else\n               link kx (Tip kx bm) kx' t\n           | kx, bm, Nil => Tip kx bm\n           end.\n\nProgram Fixpoint union (arg_0__ : IntSet) (arg_1__ : IntSet) {measure (size_nat\n                        arg_0__ +\n                        size_nat arg_1__)} : IntSet\n                   := match arg_0__, arg_1__ with\n                      | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n                          let union2 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then link p1 t1 p2 t2 else\n                            if Bool.Sumbool.sumbool_of_bool (zero p1 m2)\n                            then Bin p2 m2 (union t1 l2) r2 else\n                            Bin p2 m2 l2 (union t1 r2) in\n                          let union1 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then link p1 t1 p2 t2 else\n                            if Bool.Sumbool.sumbool_of_bool (zero p2 m1)\n                            then Bin p1 m1 (union l1 t2) r1 else\n                            Bin p1 m1 l1 (union r1 t2) in\n                          if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then union1 else\n                          if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then union2 else\n                          if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n                          then Bin p1 m1 (union l1 l2) (union r1 r2) else\n                          link p1 t1 p2 t2\n                      | (Bin _ _ _ _ as t), Tip kx bm => insertBM kx bm t\n                      | (Bin _ _ _ _ as t), Nil => t\n                      | Tip kx bm, t => insertBM kx bm t\n                      | Nil, t => t\n                      end.\nSolve Obligations with (termination_by_omega).\n\nDefinition unions {f} `{Data.Foldable.Foldable f} : f IntSet -> IntSet :=\n  fun xs => Data.Foldable.foldl' union empty xs.\n\nDefinition bitmapOfSuffix : Coq.Numbers.BinNums.N -> BitMap :=\n  fun s => Utils.Containers.Internal.BitUtil.shiftLL #1 s.\n\nDefinition bitmapOf : Coq.Numbers.BinNums.N -> BitMap :=\n  fun x => bitmapOfSuffix (suffixOf x).\n\nDefinition insert : Key -> IntSet -> IntSet :=\n  fun x => insertBM (prefixOf x) (bitmapOf x).\n\nDefinition fromList : list Key -> IntSet :=\n  fun xs => let ins := fun t x => insert x t in Data.Foldable.foldl' ins empty xs.\n\nDefinition map : (Key -> Key) -> IntSet -> IntSet :=\n  fun f => fromList GHC.Base.∘ (GHC.Base.map f GHC.Base.∘ toList).\n\nDefinition lookupGE : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | def, Bin p m l r =>\n                     if nomatch x p m : bool\n                     then if x GHC.Base.< p : bool\n                          then unsafeFindMin l\n                          else unsafeFindMin def else\n                     if zero x m : bool then go r l else\n                     go def r\n                 | def, Tip kx bm =>\n                     let maskGE :=\n                       (Coq.NArith.BinNat.N.ldiff (Coq.NArith.BinNat.N.ones (64 % N))\n                                                  (Coq.NArith.BinNat.N.pred (bitmapOf x))) Data.Bits..&.(**)\n                       bm in\n                     if prefixOf x GHC.Base.< kx : bool then Some (kx GHC.Num.+ lowestBitSet bm) else\n                     if andb (prefixOf x GHC.Base.== kx) (maskGE GHC.Base./= #0) : bool\n                     then Some (kx GHC.Num.+ lowestBitSet maskGE) else\n                     unsafeFindMin def\n                 | def, Nil => unsafeFindMin def\n                 end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go Nil l\n             else go l r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition lookupGT : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | def, Bin p m l r =>\n                     if nomatch x p m : bool\n                     then if x GHC.Base.< p : bool\n                          then unsafeFindMin l\n                          else unsafeFindMin def else\n                     if zero x m : bool then go r l else\n                     go def r\n                 | def, Tip kx bm =>\n                     let maskGT :=\n                       (Coq.NArith.BinNat.N.ldiff (Coq.NArith.BinNat.N.ones (64 % N))\n                                                  (Coq.NArith.BinNat.N.pred (Utils.Containers.Internal.BitUtil.shiftLL\n                                                                             (bitmapOf x) #1))) Data.Bits..&.(**)\n                       bm in\n                     if prefixOf x GHC.Base.< kx : bool then Some (kx GHC.Num.+ lowestBitSet bm) else\n                     if andb (prefixOf x GHC.Base.== kx) (maskGT GHC.Base./= #0) : bool\n                     then Some (kx GHC.Num.+ lowestBitSet maskGT) else\n                     unsafeFindMin def\n                 | def, Nil => unsafeFindMin def\n                 end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go Nil l\n             else go l r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition lookupLE : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | def, Bin p m l r =>\n                     if nomatch x p m : bool\n                     then if x GHC.Base.< p : bool\n                          then unsafeFindMax def\n                          else unsafeFindMax r else\n                     if zero x m : bool then go def l else\n                     go l r\n                 | def, Tip kx bm =>\n                     let maskLE :=\n                       ((Utils.Containers.Internal.BitUtil.shiftLL (bitmapOf x) #1) GHC.Num.- #1)\n                       Data.Bits..&.(**)\n                       bm in\n                     if prefixOf x GHC.Base.> kx : bool\n                     then Some (kx GHC.Num.+ highestBitSet bm) else\n                     if andb (prefixOf x GHC.Base.== kx) (maskLE GHC.Base./= #0) : bool\n                     then Some (kx GHC.Num.+ highestBitSet maskLE) else\n                     unsafeFindMax def\n                 | def, Nil => unsafeFindMax def\n                 end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go r l\n             else go Nil r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition lookupLT : Key -> IntSet -> option Key :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | def, Bin p m l r =>\n                     if nomatch x p m : bool\n                     then if x GHC.Base.< p : bool\n                          then unsafeFindMax def\n                          else unsafeFindMax r else\n                     if zero x m : bool then go def l else\n                     go l r\n                 | def, Tip kx bm =>\n                     let maskLT := (bitmapOf x GHC.Num.- #1) Data.Bits..&.(**) bm in\n                     if prefixOf x GHC.Base.> kx : bool\n                     then Some (kx GHC.Num.+ highestBitSet bm) else\n                     if andb (prefixOf x GHC.Base.== kx) (maskLT GHC.Base./= #0) : bool\n                     then Some (kx GHC.Num.+ highestBitSet maskLT) else\n                     unsafeFindMax def\n                 | def, Nil => unsafeFindMax def\n                 end in\n    let j_12__ := go Nil t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then go r l\n             else go Nil r else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition member : Key -> IntSet -> bool :=\n  fun x =>\n    let fix go arg_0__\n              := match arg_0__ with\n                 | Bin p m l r =>\n                     if nomatch x p m : bool then false else\n                     if zero x m : bool then go l else\n                     go r\n                 | Tip y bm =>\n                     andb (prefixOf x GHC.Base.== y) ((bitmapOf x Data.Bits..&.(**) bm) GHC.Base./=\n                           #0)\n                 | Nil => false\n                 end in\n    go.\n\nDefinition notMember : Key -> IntSet -> bool :=\n  fun k => negb GHC.Base.∘ member k.\n\nDefinition singleton : Key -> IntSet :=\n  fun x => Tip (prefixOf x) (bitmapOf x).\n\nDefinition split : Key -> IntSet -> (IntSet * IntSet)%type :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | x', (Bin p m l r as t') =>\n                     if match_ x' p m : bool\n                     then if zero x' m : bool\n                          then let 'pair lt gt := go x' l in\n                               pair lt (union gt r)\n                          else let 'pair lt gt := go x' r in\n                               pair (union lt l) gt else\n                     if x' GHC.Base.< p : bool\n                     then (pair Nil t')\n                     else (pair t' Nil)\n                 | x', (Tip kx' bm as t') =>\n                     let lowerBitmap := bitmapOf x' GHC.Num.- #1 in\n                     let higherBitmap :=\n                       Coq.NArith.BinNat.N.ldiff (Coq.NArith.BinNat.N.ones (64 % N)) (lowerBitmap\n                                                  GHC.Num.+\n                                                  bitmapOf x') in\n                     if kx' GHC.Base.> x' : bool then (pair Nil t') else\n                     if kx' GHC.Base.< prefixOf x' : bool then (pair t' Nil) else\n                     pair (tip kx' (bm Data.Bits..&.(**) lowerBitmap)) (tip kx' (bm Data.Bits..&.(**)\n                                                                                 higherBitmap))\n                 | _, Nil => (pair Nil Nil)\n                 end in\n    let j_21__ := let 'pair lt gt := go x t in pair lt gt in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then let 'pair lt gt := go x l in\n                  let lt' := union lt r in pair lt' gt\n             else let 'pair lt gt := go x r in\n                  let gt' := union gt l in pair lt gt' else\n        j_21__\n    | _ => j_21__\n    end.\n\nDefinition splitMember : Key -> IntSet -> (IntSet * bool * IntSet)%type :=\n  fun x t =>\n    let fix go arg_0__ arg_1__\n              := match arg_0__, arg_1__ with\n                 | x', (Bin p m l r as t') =>\n                     if match_ x' p m : bool\n                     then if zero x' m : bool\n                          then let 'pair (pair lt fnd) gt := go x' l in\n                               pair (pair lt fnd) (union gt r)\n                          else let 'pair (pair lt fnd) gt := go x' r in\n                               pair (pair (union lt l) fnd) gt else\n                     if x' GHC.Base.< p : bool\n                     then pair (pair Nil false) t'\n                     else pair (pair t' false) Nil\n                 | x', (Tip kx' bm as t') =>\n                     let bitmapOfx' := bitmapOf x' in\n                     let lowerBitmap := bitmapOfx' GHC.Num.- #1 in\n                     let higherBitmap :=\n                       Coq.NArith.BinNat.N.ldiff (Coq.NArith.BinNat.N.ones (64 % N)) (lowerBitmap\n                                                  GHC.Num.+\n                                                  bitmapOfx') in\n                     if kx' GHC.Base.> x' : bool then pair (pair Nil false) t' else\n                     if kx' GHC.Base.< prefixOf x' : bool then pair (pair t' false) Nil else\n                     let gt := tip kx' (bm Data.Bits..&.(**) higherBitmap) in\n                     let found := (bm Data.Bits..&.(**) bitmapOfx') GHC.Base./= #0 in\n                     let lt := tip kx' (bm Data.Bits..&.(**) lowerBitmap) in pair (pair lt found) gt\n                 | _, Nil => pair (pair Nil false) Nil\n                 end in\n    let j_22__ := go x t in\n    match t with\n    | Bin _ m l r =>\n        if m GHC.Base.< #0 : bool\n        then if x GHC.Base.>= #0 : bool\n             then let 'pair (pair lt fnd) gt := go x l in\n                  let lt' := union lt r in pair (pair lt' fnd) gt\n             else let 'pair (pair lt fnd) gt := go x r in\n                  let gt' := union gt l in pair (pair lt fnd) gt' else\n        j_22__\n    | _ => j_22__\n    end.\n\nDefinition bin : Prefix -> Mask -> IntSet -> IntSet -> IntSet :=\n  fun arg_0__ arg_1__ arg_2__ arg_3__ =>\n    match arg_0__, arg_1__, arg_2__, arg_3__ with\n    | _, _, l, Nil => l\n    | _, _, Nil, r => r\n    | p, m, l, r => Bin p m l r\n    end.\n\nDefinition deleteBM : Prefix -> BitMap -> IntSet -> IntSet :=\n  fix deleteBM arg_0__ arg_1__ arg_2__\n        := match arg_0__, arg_1__, arg_2__ with\n           | kx, bm, (Bin p m l r as t) =>\n               if nomatch kx p m : bool then t else\n               if zero kx m : bool then bin p m (deleteBM kx bm l) r else\n               bin p m l (deleteBM kx bm r)\n           | kx, bm, (Tip kx' bm' as t) =>\n               if kx' GHC.Base.== kx : bool\n               then tip kx (Data.Bits.xor bm' (bm' Data.Bits..&.(**) bm)) else\n               t\n           | _, _, Nil => Nil\n           end.\n\nDefinition delete : Key -> IntSet -> IntSet :=\n  fun x => deleteBM (prefixOf x) (bitmapOf x).\n\nProgram Fixpoint difference (arg_0__ : IntSet) (arg_1__ : IntSet)\n                            {measure (size_nat arg_0__ + size_nat arg_1__)} : IntSet\n                   := match arg_0__, arg_1__ with\n                      | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n                          let difference2 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then t1 else\n                            if Bool.Sumbool.sumbool_of_bool (zero p1 m2) then difference t1 l2 else\n                            difference t1 r2 in\n                          let difference1 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then t1 else\n                            if Bool.Sumbool.sumbool_of_bool (zero p2 m1)\n                            then bin p1 m1 (difference l1 t2) r1 else\n                            bin p1 m1 l1 (difference r1 t2) in\n                          if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then difference1 else\n                          if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then difference2 else\n                          if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n                          then bin p1 m1 (difference l1 l2) (difference r1 r2) else\n                          t1\n                      | (Bin _ _ _ _ as t), Tip kx bm => deleteBM kx bm t\n                      | (Bin _ _ _ _ as t), Nil => t\n                      | (Tip kx bm as t1), t2 =>\n                          let fix differenceTip arg_12__\n                                    := match arg_12__ with\n                                       | Bin p2 m2 l2 r2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx p2 m2) then t1 else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx m2) then differenceTip l2 else\n                                           differenceTip r2\n                                       | Tip kx2 bm2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx GHC.Base.== kx2)\n                                           then tip kx (Data.Bits.xor bm (bm Data.Bits..&.(**) bm2)) else\n                                           t1\n                                       | Nil => t1\n                                       end in\n                          differenceTip t2\n                      | Nil, _ => Nil\n                      end.\nSolve Obligations with (termination_by_omega).\n\nDefinition op_zrzr__ : IntSet -> IntSet -> IntSet :=\n  fun m1 m2 => difference m1 m2.\n\nNotation \"'_\\\\_'\" := (op_zrzr__).\n\nInfix \"\\\\\" := (_\\\\_) (at level 99).\n\nDefinition filter : (Key -> bool) -> IntSet -> IntSet :=\n  fix filter predicate t\n        := let bitPred :=\n             fun kx bm bi =>\n               if predicate (kx GHC.Num.+ bi) : bool\n               then bm Data.Bits..|.(**) bitmapOfSuffix bi else\n               bm in\n           match t with\n           | Bin p m l r => bin p m (filter predicate l) (filter predicate r)\n           | Tip kx bm => tip kx (foldl'Bits #0 (bitPred kx) #0 bm)\n           | Nil => Nil\n           end.\n\nProgram Fixpoint intersection (arg_0__ : IntSet) (arg_1__ : IntSet)\n                              {measure (size_nat arg_0__ + size_nat arg_1__)} : IntSet\n                   := match arg_0__, arg_1__ with\n                      | (Bin p1 m1 l1 r1 as t1), (Bin p2 m2 l2 r2 as t2) =>\n                          let intersection2 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p1 p2 m2) then Nil else\n                            if Bool.Sumbool.sumbool_of_bool (zero p1 m2) then intersection t1 l2 else\n                            intersection t1 r2 in\n                          let intersection1 :=\n                            if Bool.Sumbool.sumbool_of_bool (nomatch p2 p1 m1) then Nil else\n                            if Bool.Sumbool.sumbool_of_bool (zero p2 m1) then intersection l1 t2 else\n                            intersection r1 t2 in\n                          if Bool.Sumbool.sumbool_of_bool (shorter m1 m2) then intersection1 else\n                          if Bool.Sumbool.sumbool_of_bool (shorter m2 m1) then intersection2 else\n                          if Bool.Sumbool.sumbool_of_bool (p1 GHC.Base.== p2)\n                          then bin p1 m1 (intersection l1 l2) (intersection r1 r2) else\n                          Nil\n                      | (Bin _ _ _ _ as t1), Tip kx2 bm2 =>\n                          let fix intersectBM arg_11__\n                                    := match arg_11__ with\n                                       | Bin p1 m1 l1 r1 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx2 p1 m1) then Nil else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx2 m1) then intersectBM l1 else\n                                           intersectBM r1\n                                       | Tip kx1 bm1 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                                           then tip kx1 (bm1 Data.Bits..&.(**) bm2) else\n                                           Nil\n                                       | Nil => Nil\n                                       end in\n                          intersectBM t1\n                      | Bin _ _ _ _, Nil => Nil\n                      | Tip kx1 bm1, t2 =>\n                          let fix intersectBM arg_18__\n                                    := match arg_18__ with\n                                       | Bin p2 m2 l2 r2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (nomatch kx1 p2 m2) then Nil else\n                                           if Bool.Sumbool.sumbool_of_bool (zero kx1 m2) then intersectBM l2 else\n                                           intersectBM r2\n                                       | Tip kx2 bm2 =>\n                                           if Bool.Sumbool.sumbool_of_bool (kx1 GHC.Base.== kx2)\n                                           then tip kx1 (bm1 Data.Bits..&.(**) bm2) else\n                                           Nil\n                                       | Nil => Nil\n                                       end in\n                          intersectBM t2\n                      | Nil, _ => Nil\n                      end.\nSolve Obligations with (termination_by_omega).\n\nDefinition maxView : IntSet -> option (Key * IntSet)%type :=\n  fun t =>\n    let fix go arg_0__\n              := match arg_0__ with\n                 | Bin p m l r => let 'pair result r' := go r in pair result (bin p m l r')\n                 | Tip kx bm =>\n                     let 'bi := highestBitSet bm in\n                     pair (kx GHC.Num.+ bi) (tip kx (Data.Bits.xor bm (bm Data.Bits..&.(**)\n                                                                    bitmapOfSuffix bi)))\n                 | Nil => pair (0 % N) Nil\n                 end in\n    let j_12__ := Some (go t) in\n    match t with\n    | Nil => None\n    | Bin p m l r =>\n        if m GHC.Base.< #0 : bool\n        then let 'pair result l' := go l in\n             Some (pair result (bin p m l' r)) else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition deleteMax : IntSet -> IntSet :=\n  Data.Maybe.maybe Nil Data.Tuple.snd GHC.Base.∘ maxView.\n\nDefinition minView : IntSet -> option (Key * IntSet)%type :=\n  fun t =>\n    let fix go arg_0__\n              := match arg_0__ with\n                 | Bin p m l r => let 'pair result l' := go l in pair result (bin p m l' r)\n                 | Tip kx bm =>\n                     let 'bi := lowestBitSet bm in\n                     pair (kx GHC.Num.+ bi) (tip kx (Data.Bits.xor bm (bm Data.Bits..&.(**)\n                                                                    bitmapOfSuffix bi)))\n                 | Nil => pair (0 % N) Nil\n                 end in\n    let j_12__ := Some (go t) in\n    match t with\n    | Nil => None\n    | Bin p m l r =>\n        if m GHC.Base.< #0 : bool\n        then let 'pair result r' := go r in\n             Some (pair result (bin p m l r')) else\n        j_12__\n    | _ => j_12__\n    end.\n\nDefinition deleteMin : IntSet -> IntSet :=\n  Data.Maybe.maybe Nil Data.Tuple.snd GHC.Base.∘ minView.\n\nDefinition partition : (Key -> bool) -> IntSet -> (IntSet * IntSet)%type :=\n  fun predicate0 t0 =>\n    let fix go predicate t\n              := let bitPred :=\n                   fun kx bm bi =>\n                     if predicate (kx GHC.Num.+ bi) : bool\n                     then bm Data.Bits..|.(**) bitmapOfSuffix bi else\n                     bm in\n                 match t with\n                 | Bin p m l r =>\n                     let 'pair r1 r2 := go predicate r in\n                     let 'pair l1 l2 := go predicate l in\n                     pair (bin p m l1 r1) (bin p m l2 r2)\n                 | Tip kx bm =>\n                     let bm1 := foldl'Bits #0 (bitPred kx) #0 bm in\n                     pair (tip kx bm1) (tip kx (Data.Bits.xor bm bm1))\n                 | Nil => (pair Nil Nil)\n                 end in\n    id (go predicate0 t0).\n\n(* Skipping all instances of class `Control.DeepSeq.NFData', including\n   `Data.IntSet.Internal.NFData__IntSet' *)\n\n(* Skipping all instances of class `GHC.Read.Read', including\n   `Data.IntSet.Internal.Read__IntSet' *)\n\n(* Skipping all instances of class `GHC.Show.Show', including\n   `Data.IntSet.Internal.Show__IntSet' *)\n\nLocal Definition Ord__IntSet_compare : IntSet -> IntSet -> comparison :=\n  fun s1 s2 => GHC.Base.compare (toAscList s1) (toAscList s2).\n\nLocal Definition Ord__IntSet_op_zl__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base.== Lt.\n\nLocal Definition Ord__IntSet_op_zlze__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base./= Gt.\n\nLocal Definition Ord__IntSet_op_zg__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base.== Gt.\n\nLocal Definition Ord__IntSet_op_zgze__ : IntSet -> IntSet -> bool :=\n  fun x y => Ord__IntSet_compare x y GHC.Base./= Lt.\n\nLocal Definition Ord__IntSet_max : IntSet -> IntSet -> IntSet :=\n  fun x y => if Ord__IntSet_op_zlze__ x y : bool then y else x.\n\nLocal Definition Ord__IntSet_min : IntSet -> IntSet -> IntSet :=\n  fun x y => if Ord__IntSet_op_zlze__ x y : bool then x else y.\n\nLocal Definition Eq___IntSet_op_zeze__ : IntSet -> IntSet -> bool :=\n  fun t1 t2 => equal t1 t2.\n\nLocal Definition Eq___IntSet_op_zsze__ : IntSet -> IntSet -> bool :=\n  fun t1 t2 => nequal t1 t2.\n\nProgram Instance Eq___IntSet : GHC.Base.Eq_ IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zeze____ := Eq___IntSet_op_zeze__ ;\n           GHC.Base.op_zsze____ := Eq___IntSet_op_zsze__ |}.\n\nProgram Instance Ord__IntSet : GHC.Base.Ord IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zl____ := Ord__IntSet_op_zl__ ;\n           GHC.Base.op_zlze____ := Ord__IntSet_op_zlze__ ;\n           GHC.Base.op_zg____ := Ord__IntSet_op_zg__ ;\n           GHC.Base.op_zgze____ := Ord__IntSet_op_zgze__ ;\n           GHC.Base.compare__ := Ord__IntSet_compare ;\n           GHC.Base.max__ := Ord__IntSet_max ;\n           GHC.Base.min__ := Ord__IntSet_min |}.\n\n(* Skipping all instances of class `Data.Data.Data', including\n   `Data.IntSet.Internal.Data__IntSet' *)\n\nLocal Definition Semigroup__IntSet_op_zlzlzgzg__ : IntSet -> IntSet -> IntSet :=\n  union.\n\nProgram Instance Semigroup__IntSet : GHC.Base.Semigroup IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.op_zlzlzgzg____ := Semigroup__IntSet_op_zlzlzgzg__ |}.\n\nLocal Definition Monoid__IntSet_mappend : IntSet -> IntSet -> IntSet :=\n  _GHC.Base.<<>>_.\n\nLocal Definition Monoid__IntSet_mconcat : list IntSet -> IntSet :=\n  unions.\n\nLocal Definition Monoid__IntSet_mempty : IntSet :=\n  empty.\n\nProgram Instance Monoid__IntSet : GHC.Base.Monoid IntSet :=\n  fun _ k__ =>\n    k__ {| GHC.Base.mappend__ := Monoid__IntSet_mappend ;\n           GHC.Base.mconcat__ := Monoid__IntSet_mconcat ;\n           GHC.Base.mempty__ := Monoid__IntSet_mempty |}.\n\n(* Skipping all instances of class `GHC.Exts.IsList', including\n   `Data.IntSet.Internal.IsList__IntSet' *)\n\nModule Notations.\nNotation \"'_Data.IntSet.Internal.\\\\_'\" := (op_zrzr__).\nInfix \"Data.IntSet.Internal.\\\\\" := (_\\\\_) (at level 99).\nEnd Notations.\n\n(* External variables:\n     Bool.Sumbool.sumbool_of_bool Eq Gt Lt N None Some andb bool comparison cons\n     false id list negb nil op_zm__ op_zp__ op_zt__ op_zv__ option orb pair size_nat\n     true Coq.Init.Peano.lt Coq.NArith.BinNat.N.ldiff Coq.NArith.BinNat.N.log2\n     Coq.NArith.BinNat.N.lxor Coq.NArith.BinNat.N.modulo Coq.NArith.BinNat.N.ones\n     Coq.NArith.BinNat.N.pow Coq.NArith.BinNat.N.pred Coq.NArith.BinNat.N.to_nat\n     Coq.Numbers.BinNums.N Data.Bits.op_zizazi__ Data.Bits.op_zizbzi__ Data.Bits.xor\n     Data.Foldable.Foldable Data.Foldable.foldl' Data.Maybe.maybe Data.Tuple.snd\n     GHC.Base.Eq_ GHC.Base.Monoid GHC.Base.Ord GHC.Base.Semigroup GHC.Base.compare\n     GHC.Base.compare__ GHC.Base.flip GHC.Base.map GHC.Base.mappend__ GHC.Base.max__\n     GHC.Base.mconcat__ GHC.Base.mempty__ GHC.Base.min__ GHC.Base.op_z2218U__\n     GHC.Base.op_zeze__ GHC.Base.op_zeze____ GHC.Base.op_zg__ GHC.Base.op_zg____\n     GHC.Base.op_zgze__ GHC.Base.op_zgze____ GHC.Base.op_zl__ GHC.Base.op_zl____\n     GHC.Base.op_zlze____ GHC.Base.op_zlzlzgzg__ GHC.Base.op_zlzlzgzg____\n     GHC.Base.op_zsze__ GHC.Base.op_zsze____ GHC.Err.Build_Default GHC.Err.Default\n     GHC.Num.fromInteger GHC.Num.op_zm__ GHC.Num.op_zp__ GHC.Wf.wfFix2\n     Utils.Containers.Internal.BitUtil.bitcount\n     Utils.Containers.Internal.BitUtil.highestBitMask\n     Utils.Containers.Internal.BitUtil.lowestBitMask\n     Utils.Containers.Internal.BitUtil.shiftLL\n     Utils.Containers.Internal.BitUtil.shiftRL\n*)\n", "meta": {"author": "DavidFHCh", "repo": "Tesis-FTW", "sha": "f84ab8eb92f3984e973ce6a441262d9a8a62e9b0", "save_path": "github-repos/coq/DavidFHCh-Tesis-FTW", "path": "github-repos/coq/DavidFHCh-Tesis-FTW/Tesis-FTW-f84ab8eb92f3984e973ce6a441262d9a8a62e9b0/tesis/hs-to-coq/examples/containers/lib/Data/IntSet/Internal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.21315535495762186}}
{"text": "Require Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Globalenvs.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Locations.\nRequire Import LTL.\nRequire Import Conventions.\n\nRequire Import Linear.\n\nRequire Import mem_lemmas. (*for mem_forward*)\nRequire Import semantics.\nRequire Import val_casted.\nRequire Import BuiltinEffects.\n\nInductive load_frame: Type :=\n| mk_load_frame:\n    forall (rs0: Linear.locset)  (**r location state at program entry *)\n           (f: Linear.function), (**r initial function *)\n    load_frame.\n\n(** Linear execution states. *)\n\nInductive Linear_core: Type :=\n  | Linear_State:\n      forall (stack: list Linear.stackframe) (**r call stack *)\n             (f: Linear.function)            (**r function currently executing *)\n             (sp: val)                       (**r stack pointer *)\n             (c: Linear.code)                (**r current program point *)\n             (rs: Linear.locset)             (**r location state *)\n             (lf: load_frame),           (**r location state at program entry *)\n      Linear_core\n  (*A dummy corestate, to facilitate the stacking proof.*)\n  | Linear_CallstateIn:\n      forall (stack: list Linear.stackframe) (**r call stack *)\n             (f: Linear.fundef)              (**r function to call *)\n             (rs: Linear.locset)             (**r location state at point of call *)\n             (lf: load_frame),           (**r location state at program entry *)\n      Linear_core\n  | Linear_Callstate:\n      forall (stack: list Linear.stackframe) (**r call stack *)\n             (f: Linear.fundef)              (**r function to call *)\n             (rs: Linear.locset)             (**r location state at point of call *)\n             (lf: load_frame),           (**r location state at program entry *)\n      Linear_core\n  | Linear_Returnstate:\n      forall (stack: list Linear.stackframe) (**r call stack *)\n             (retty: option typ)      (**r optional return register int-floatness *)\n             (rs: Linear.locset)             (**r location state at point of return *)\n             (lf: load_frame),           (**r location state at program entry *)\n      Linear_core.\n\nDefinition call_regs' (callee : LTL.locset) (l : loc) :=\n  match l with\n    | R r => callee (R r)\n    | S Local _ _ => Vundef\n    | S Outgoing ofs ty => callee (S Incoming ofs ty)\n    | S Incoming _ _ => Vundef\n  end.\n\nLemma call_regs_regs' callee ofs ty : \n  call_regs' (call_regs callee) (S Outgoing ofs ty) = callee (S Outgoing ofs ty). \nProof. simpl; auto. Qed.\n\n(** [parent_locset0 ls0 cs] returns the mapping of values for locations\n    of the caller function, bottoming out with locset ls0. *)\nDefinition parent_locset0 (ls0: locset) (stack: list Linear.stackframe) : locset :=\n  match stack with\n  | nil => call_regs' ls0\n  | Linear.Stackframe f sp ls c :: stack' => ls\n  end.\n\nSection LINEAR_COOP.\nVariable hf : I64Helpers.helper_functions.\n\nInductive Linear_step (ge:genv): Linear_core -> mem -> Linear_core -> mem -> Prop :=\n  | lin_exec_Lgetstack:\n      forall s f sp sl ofs ty dst b rs m rs' lf,\n      rs' = Locmap.set (R dst) (rs (S sl ofs ty)) (undef_regs (destroyed_by_getstack sl) rs) ->\n      Linear_step ge (Linear_State s f sp (Lgetstack sl ofs ty dst :: b) rs lf) m\n        (Linear_State s f sp b rs' lf) m\n  | lin_exec_Lsetstack:\n      forall s f sp src sl ofs ty b rs m rs' lf,\n      rs' = Locmap.set (S sl ofs ty) (rs (R src)) (undef_regs (destroyed_by_setstack ty) rs) ->\n      Linear_step ge (Linear_State s f sp (Lsetstack src sl ofs ty :: b) rs lf) m\n        (Linear_State s f sp b rs' lf) m\n  | lin_exec_Lop:\n      forall s f sp op args res b rs m v rs' lf,\n      eval_operation ge sp op (reglist rs args) m = Some v ->\n      rs' = Locmap.set (R res) v (undef_regs (destroyed_by_op op) rs) ->\n      Linear_step ge (Linear_State s f sp (Lop op args res :: b) rs lf) m\n        (Linear_State s f sp b rs' lf) m\n  | lin_exec_Lload:\n      forall s f sp chunk addr args dst b rs m a v rs' lf,\n      eval_addressing ge sp addr (reglist rs args) = Some a ->\n      Mem.loadv chunk m a = Some v ->\n      rs' = Locmap.set (R dst) v (undef_regs (destroyed_by_load chunk addr) rs) ->\n      Linear_step ge (Linear_State s f sp (Lload chunk addr args dst :: b) rs lf) m\n        (Linear_State s f sp b rs' lf) m\n  | lin_exec_Lstore:\n      forall s f sp chunk addr args src b rs m m' a rs' lf,\n      eval_addressing ge sp addr (reglist rs args) = Some a ->\n      Mem.storev chunk m a (rs (R src)) = Some m' ->\n      rs' = undef_regs (destroyed_by_store chunk addr) rs ->\n      Linear_step ge (Linear_State s f sp (Lstore chunk addr args src :: b) rs lf) m\n        (Linear_State s f sp b rs' lf) m'\n  | lin_exec_Lcall:\n      forall s f sp sig ros b rs m f' lf,\n      find_function ge ros rs = Some f' ->\n      sig = funsig f' ->\n      Linear_step ge (Linear_State s f sp (Lcall sig ros :: b) rs lf) m\n        (Linear_Callstate (Stackframe f sp rs b:: s) f' rs lf) m\n  | lin_exec_Ltailcall:\n      forall s f stk sig ros b rs m rs' f' m' rs0 f0,\n      rs' = return_regs (parent_locset0 rs0 s) rs ->\n      find_function ge ros rs' = Some f' ->\n      sig = funsig f' ->\n      Mem.free m stk 0 f.(fn_stacksize) = Some m' ->\n      Linear_step ge (Linear_State s f (Vptr stk Int.zero) (Ltailcall sig ros :: b) rs (mk_load_frame rs0 f0)) m\n        (Linear_Callstate s f' rs' (mk_load_frame rs0 f0)) m'\n  | lin_exec_Lbuiltin:\n      forall s f sp rs m ef args res b t vl rs' m' lf,\n      external_call' ef ge (reglist rs args) m t vl m' ->\n      ~ observableEF hf ef ->\n      rs' = Locmap.setlist (map R res) vl (undef_regs (destroyed_by_builtin ef) rs) ->\n      Linear_step ge (Linear_State s f sp (Lbuiltin ef args res :: b) rs lf) m\n         (Linear_State s f sp b rs' lf) m'\n\n(* annotations are observable, so now handled by atExternal\n  | lin_exec_Lannot:\n      forall s f sp rs m ef args b t v m',\n      external_call' ef ge (map rs args) m t v m' ->\n      Linear_step (Linear_State s f sp (Lannot ef args :: b) rs) m\n         (Linear_State s f sp b rs) m'*)\n\n  | lin_exec_Llabel:\n      forall s f sp lbl b rs m lf,\n      Linear_step ge (Linear_State s f sp (Llabel lbl :: b) rs lf) m\n        (Linear_State s f sp b rs lf) m\n  | lin_exec_Lgoto:\n      forall s f sp lbl b rs m b' lf,\n      find_label lbl f.(fn_code) = Some b' ->\n      Linear_step ge (Linear_State s f sp (Lgoto lbl :: b) rs lf) m\n        (Linear_State s f sp b' rs lf) m\n  | lin_exec_Lcond_true:\n      forall s f sp cond args lbl b rs m rs' b' lf,\n      eval_condition cond (reglist rs args) m = Some true ->\n      rs' = undef_regs (destroyed_by_cond cond) rs ->\n      find_label lbl f.(fn_code) = Some b' ->\n      Linear_step ge (Linear_State s f sp (Lcond cond args lbl :: b) rs lf) m\n        (Linear_State s f sp b' rs' lf) m\n  | lin_exec_Lcond_false:\n      forall s f sp cond args lbl b rs m rs' lf,\n      eval_condition cond (reglist rs args) m = Some false ->\n      rs' = undef_regs (destroyed_by_cond cond) rs ->\n      Linear_step ge (Linear_State s f sp (Lcond cond args lbl :: b) rs lf) m\n        (Linear_State s f sp b rs' lf) m\n  | lin_exec_Ljumptable:\n      forall s f sp arg tbl b rs m n lbl b' rs' lf,\n      rs (R arg) = Vint n ->\n      list_nth_z tbl (Int.unsigned n) = Some lbl ->\n      find_label lbl f.(fn_code) = Some b' ->\n      rs' = undef_regs (destroyed_by_jumptable) rs ->\n      Linear_step ge (Linear_State s f sp (Ljumptable arg tbl :: b) rs lf) m\n        (Linear_State s f sp b' rs' lf) m\n  | lin_exec_Lreturn:\n      forall s f stk b rs m m' rs0 f0,\n      let lf := mk_load_frame rs0 f0 in \n      Mem.free m stk 0 f.(fn_stacksize) = Some m' ->\n      Linear_step ge (Linear_State s f (Vptr stk Int.zero) (Lreturn :: b) rs lf) m\n        (Linear_Returnstate s (sig_res (fn_sig f)) (return_regs (parent_locset0 rs0 s) rs) lf) m'\n  (*A dummy corestep, to facilitate the stacking proof.*)\n  | lin_exec_function_internal0:\n      forall s f rs m rs0 f0,\n      Linear_step ge (Linear_CallstateIn s (Internal f) rs (mk_load_frame rs0 f0)) m\n                  (Linear_Callstate s (Internal f) rs (mk_load_frame (call_regs rs0) f0)) m\n  | lin_exec_function_internal:\n      forall s f rs m rs' m' stk lf,\n      Mem.alloc m 0 f.(fn_stacksize) = (m', stk) ->\n      rs' = undef_regs destroyed_at_function_entry (call_regs rs) ->\n      Linear_step ge (Linear_Callstate s (Internal f) rs lf) m\n        (Linear_State s f (Vptr stk Int.zero) f.(fn_code) rs' lf) m'\n\n  | lin_exec_function_external:\n      forall s ef args res rs1 rs2 m t m' lf\n      (OBS: EFisHelper hf ef),\n      args = map rs1 (loc_arguments (ef_sig ef)) ->\n      external_call' ef ge args m t res m' ->\n      rs2 = Locmap.setlist (map R (loc_result (ef_sig ef))) res rs1 ->\n      Linear_step ge (Linear_Callstate s (External ef) rs1 lf) m\n          (Linear_Returnstate s (sig_res (ef_sig ef)) rs2 lf) m'\n\n  | lin_exec_return:\n      forall s f sp lf c rs retty m rs_init,\n      Linear_step ge (Linear_Returnstate (Stackframe f sp lf c :: s) retty rs rs_init) m\n         (Linear_State s f sp c rs rs_init) m.\n\nDefinition init_locset tys args :=\n  Locmap.setlist (loc_arguments_rec tys 0) (encode_longs tys args) (Locmap.init Vundef).\n\nDefinition Linear_initial_core (ge:genv) (v: val) (args:list val): \n           option Linear_core :=match v with\n     | Vptr b i => \n          if Int.eq_dec i Int.zero \n          then match Genv.find_funct_ptr ge b with\n                 | None => None\n                 | Some f => \n                    match f with Internal fi =>\n                     let tyl := sig_args (funsig f) in\n                     if val_has_type_list_func args (sig_args (funsig f))\n                        && vals_defined args\n                        && zlt (4*(2*(Zlength args))) Int.max_unsigned\n                     then let ls0 := init_locset (sig_args (funsig f)) args \n                          in Some (Linear_CallstateIn nil f ls0 (mk_load_frame ls0 fi))\n                     else None\n                    | External _ => None\n                     end\n               end\n          else None\n     | _ => None\n    end.\n(*Compcert's original definition is for initial PROGRAM states\nInductive initial_state (p: program): state -> Prop :=\n  | initial_state_intro: forall b f m0,\n      let ge := Genv.globalenv p in\n      Genv.init_mem p = Some m0 ->\n      Genv.find_symbol ge p.(prog_main) = Some b ->\n      Genv.find_funct_ptr ge b = Some f ->\n      funsig f = mksignature nil (Some Tint) ->\n      initial_state p (Callstate nil f (Locmap.init Vundef) m0).\n*)\n\n(*Maybe generalize to other types?*)\nDefinition Linear_halted (q : Linear_core): option val :=\n    match q with Linear_Returnstate nil _ rs (mk_load_frame _ f) => \n      match sig_res (fn_sig f) with\n      (*Return Tlong, which must be decoded*)\n      | Some Tlong => \n           match loc_result (mksignature nil (Some Tlong)) with\n             | nil => None\n             | r1 :: r2 :: nil => \n                 match decode_longs (Tlong::nil) (rs (R r1)::rs (R r2)::nil) with\n                   | v :: nil => Some v\n                   | _ => None\n                 end\n             | _ => None\n           end\n\n      (*Return a value of any other typ*)\n      | Some retty => \n           match loc_result (mksignature nil (Some retty)) with\n            | nil => None\n            | r :: TL => match TL with \n                           | nil => Some (rs (R r))\n                           | _ :: _ => None\n                         end\n           end\n\n      (*Return Tvoid - modeled as integer return*)\n      | None => Some (rs (R AX))\n      end \n    | _ => None end.\n\n(*Original had this:\nInductive final_state: state -> int -> Prop :=\n  | final_state_intro: forall rs m r retcode,\n      loc_result (mksignature nil (Some Tint)) = r :: nil ->\n      rs (R r) = Vint retcode ->\n      final_state (Returnstate nil rs m) retcode.\n*)\n\nDefinition Linear_at_external (c: Linear_core) : option (external_function * signature * list val) :=\n  match c with\n  | Linear_State _ _ _ _ _ _ => None\n  | Linear_Callstate s f rs _ => \n      match f with\n        | Internal f => None\n        | External ef => \n            if observableEF_dec hf ef\n            then Some (ef, ef_sig ef, decode_longs (sig_args (ef_sig ef)) \n                                   (map rs (loc_arguments (ef_sig ef))))\n            else None\n      end\n  | Linear_CallstateIn _ _ _ _ => None\n  | Linear_Returnstate _ _ _ _ => None\n end.\n\nDefinition Linear_after_external (vret: option val) (c: Linear_core) : option Linear_core :=\n  match c with \n    | Linear_Callstate s f rs lf => \n      match f with\n        | Internal f => None\n        | External ef => \n          match vret with\n            | None => Some (Linear_Returnstate s (sig_res (ef_sig ef))\n                             (Locmap.setlist (map R (loc_result (ef_sig ef))) \n                               (encode_long (sig_res (ef_sig ef)) Vundef) rs) lf)\n            | Some v => Some (Linear_Returnstate s (sig_res (ef_sig ef))\n                               (Locmap.setlist (map R (loc_result (ef_sig ef))) \n                                 (encode_long (sig_res (ef_sig ef)) v) rs) lf)\n          end\n      end\n    | _ => None\n  end.\n\nLemma Linear_corestep_not_at_external ge m q m' q':\n      Linear_step ge q m q' m' -> Linear_at_external q = None.\n  Proof. intros. inv H; try reflexivity. \n  simpl. destruct (observableEF_dec hf ef); simpl; trivial. \n  exfalso. eapply EFhelpers; eassumption. \nQed.\n\nLemma Linear_corestep_not_halted ge m q m' q' :\n       Linear_step ge q m q' m' -> Linear_halted q = None.\n  Proof. intros. inv H; reflexivity. Qed.\n    \nLemma Linear_at_external_halted_excl q:\n      Linear_at_external q = None \\/ Linear_halted q = None.\n   Proof. intros. destruct q; auto. Qed.\n\nLemma Linear_after_at_external_excl retv q q':\n      Linear_after_external retv q = Some q' -> Linear_at_external q' = None.\n  Proof. intros.\n       destruct q; simpl in *; try inv H.\n       destruct f; try inv H1; simpl.\n         destruct retv; inv H0; simpl; trivial.\n  Qed.\n\nDefinition Linear_core_sem : CoreSemantics genv Linear_core mem.\nProof.\n  eapply (@Build_CoreSemantics _ _ _ \n           Linear_initial_core\n           Linear_at_external\n           Linear_after_external\n           Linear_halted\n           Linear_step).\n    apply Linear_corestep_not_at_external.\n    apply Linear_corestep_not_halted.\n    apply Linear_at_external_halted_excl.\nDefined.\n\n(************************NOW SHOW THAT WE ALSO HAVE A COOPSEM******)\n\nLemma Linear_forward : forall g c m c' m' (CS: Linear_step g c m c' m'), \n                    mem_forward m m'.\n  Proof. intros.\n   inv CS; try apply mem_forward_refl.\n         (*Storev*)\n          destruct a; simpl in H0; inv H0. \n          eapply store_forward. eassumption. \n         (*Ltailcall*)\n           eapply free_forward; eassumption.\n         (*Lbuiltin*) \n           inv H. \n           eapply external_call_mem_forward; eassumption.\n         (*Lannot\n           inv H. \n           eapply external_call_mem_forward; eassumption.*)\n         (*free*)\n           eapply free_forward; eassumption.\n         (*internal function*)\n           eapply alloc_forward; eassumption.\n         (*external unobservable function*)\n           inv H0. eapply external_call_mem_forward; eassumption.\nQed.\n\nProgram Definition Linear_coop_sem : \n  CoopCoreSem genv Linear_core.\nProof.\napply Build_CoopCoreSem with (coopsem := Linear_core_sem).\n  apply Linear_forward.\nDefined.\n\nEnd LINEAR_COOP.\n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/backend/Linear_coop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.21315534588246302}}
{"text": "Require Import Omega.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import PromiseConsistent.\nRequire Import ReorderPromise.\nRequire Import ReorderPromises.\nRequire Import MemoryReorder.\nRequire Import MemoryFacts.\nRequire Import Pred.\nRequire Import MemoryProps.\n\nSet Implicit Arguments.\n\n\n\nLemma reorder_read_cancel\n      lc0 mem0\n      lc1 mem1\n      lc2\n      loc1 from1 to1 msg1\n      loc2 to2 val2 released2 ord2\n      (STEP1: Local.read_step lc0 mem0 loc2 to2 val2 released2 ord2 lc1)\n      (STEP2: Local.promise_step lc1 mem0 loc1 from1 to1 msg1 lc2 mem1 Memory.op_kind_cancel)\n  :\n    exists lc1',\n      (<<STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1' mem1 Memory.op_kind_cancel>>) /\\\n      (<<STEP2: Local.read_step lc1' mem1 loc2 to2 val2 released2 ord2 lc2>>).\nProof.\n  inv STEP1. inv STEP2.\n  hexploit MemoryFacts.promise_get1_diff; eauto.\n  { ii. clarify. ss. inv PROMISE.\n    eapply Memory.remove_get0 in MEM. des. clarify. }\n  i. des. esplits; eauto.\nQed.\n\nLemma remove_non_synch_loc loc0 prom0 loc1 from to msg prom1\n      (NONSYNCH: Memory.nonsynch_loc loc0 prom0)\n      (REMOVE: Memory.remove prom0 loc1 from to msg prom1)\n  :\n    Memory.nonsynch_loc loc0 prom1.\nProof.\n  ii. erewrite Memory.remove_o in GET; eauto.\n  des_ifs. exploit NONSYNCH; eauto.\nQed.\n\nLemma remove_non_synch prom0 loc from to msg prom1\n      (NONSYNCH: Memory.nonsynch prom0)\n      (REMOVE: Memory.remove prom0 loc from to msg prom1)\n  :\n    Memory.nonsynch prom1.\nProof.\n  ii. erewrite Memory.remove_o in GET; eauto.\n  des_ifs. exploit NONSYNCH; eauto.\nQed.\n\nLemma reorder_write_cancel\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2 mem2\n      loc1 from1 to1 msg1\n      loc2 from2 to2 val2 releasedm2 released2 ord2 kind2\n      (STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1 sc2 mem1 kind2)\n      (STEP2: Local.promise_step lc1 mem1 loc1 from1 to1 msg1 lc2 mem2 Memory.op_kind_cancel)\n  :\n    exists lc1' mem1',\n      (<<STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1' mem1' Memory.op_kind_cancel>>) /\\\n      (<<STEP2: Local.write_step lc1' sc0 mem1' loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind2>>).\nProof.\n  inv STEP2. inv PROMISE.\n  inv STEP1. ss. inv WRITE.\n  exploit MemoryReorder.remove_remove.\n  { eapply REMOVE. }\n  { eapply PROMISES. } i. des.\n  assert (LOCTS: (loc2, to2) <> (loc1, to1)).\n  { ii. clarify. apply Memory.remove_get0 in MEM. inv PROMISE.\n    - apply Memory.add_get0 in MEM0. des. clarify.\n    - apply Memory.split_get0 in MEM0. des. clarify.\n    - apply Memory.lower_get0 in MEM0. des. clarify.\n    - clarify. }\n  inv PROMISE.\n  - exploit MemoryReorder.add_remove.\n    { eapply LOCTS. }\n    { eapply PROMISES0. }\n    { eauto. } i. des.\n    exploit MemoryReorder.add_remove.\n    { eapply LOCTS. }\n    { eapply MEM0. }\n    { eauto. } i. des.\n    esplits.\n    + econs; eauto.\n    + econs; ss.\n      * econs.\n        { econs 1; eauto.\n          i. erewrite Memory.remove_o in GET; eauto.\n          des_ifs. eapply ATTACH; eauto. }\n        { eauto. }\n      * intros ORD. eapply RELEASE in ORD.\n        eapply remove_non_synch_loc; eauto.\n  - destruct (classic ((loc2, ts3) = (loc1, to1))) as [|LOCTS2]; clarify.\n    { exploit MemoryReorder.split_remove_same.\n      { eapply PROMISES0. }\n      { eauto. } i. des. clarify.\n    }\n    { exploit MemoryReorder.split_remove.\n      { eapply LOCTS. }\n      { eapply LOCTS2. }\n      { eapply PROMISES0. }\n      { eauto. } i. des.\n      exploit MemoryReorder.split_remove.\n      { eapply LOCTS. }\n      { eapply LOCTS2. }\n      { eapply MEM0. }\n      { eauto. } i. des.\n      esplits.\n      + econs; eauto.\n      + econs; ss.\n        * econs.\n          { econs 2; eauto. }\n          { eauto. }\n        * intros ORD. eapply RELEASE in ORD.\n          eapply remove_non_synch_loc; eauto. }\n  - exploit MemoryReorder.lower_remove.\n    { eapply LOCTS. }\n    { eapply PROMISES0. }\n    { eauto. } i. des.\n    exploit MemoryReorder.lower_remove.\n    { eapply LOCTS. }\n    { eapply MEM0. }\n    { eauto. } i. des.\n    esplits.\n    + econs; eauto.\n    + econs; ss.\n      * econs.\n        { econs 3; eauto. }\n        { eauto. }\n      * intros ORD. eapply RELEASE in ORD.\n        eapply remove_non_synch_loc; eauto.\n  - clarify.\nQed.\n\nLemma reorder_fence_cancel\n      lc0 mem0\n      lc1 mem1\n      lc2\n      loc1 from1 to1 msg1\n      ord1 ord2 sc0 sc1\n      (STEP1: Local.fence_step lc0 sc0 ord1 ord2 lc1 sc1)\n      (STEP2: Local.promise_step lc1 mem0 loc1 from1 to1 msg1 lc2 mem1 Memory.op_kind_cancel)\n  :\n    exists lc1',\n      (<<STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1' mem1 Memory.op_kind_cancel>>) /\\\n      (<<STEP2: Local.fence_step lc1' sc0 ord1 ord2 lc2 sc1>>).\nProof.\n  inv STEP1. inv STEP2. ss. esplits.\n  - econs; eauto.\n  - econs; eauto.\n    + inv PROMISE. i. eapply remove_non_synch; eauto.\n    + i. ss. subst. erewrite PROMISES in *; auto.\n      inv PROMISE. eapply Memory.remove_get0 in PROMISES0. des.\n      erewrite Memory.bot_get in *. ss.\nQed.\n\nLemma reorder_step_cancel\n      lang\n      pf1 pf2 e1 e2 th0 th1 th2\n      (STEP1: @Thread.step lang pf1 e1 th0 th1)\n      (STEP2: Thread.step pf2 e2 th1 th2)\n      (CANCEL: ThreadEvent.is_cancel e2):\n  (exists th1',\n    (<<STEP1: Thread.step pf2 e2 th0 th1'>>) /\\\n    (<<STEP2: Thread.step pf1 e1 th1' th2>>)) \\/\n  (th2 = th0 /\\ <<RESERVE: ThreadEvent.is_reserve e1>>)\n.\nProof.\n  unfold ThreadEvent.is_cancel in *. des_ifs.\n  inv STEP2; inv STEP; [|inv LOCAL]. ss.\n  inv STEP1; ss.\n  - inv STEP. ss. exploit reorder_promise_promise_cancel; eauto.\n    i. des; clarify; eauto.\n    left. esplits.\n    + econs 1. econs; eauto.\n    + econs 1. econs; eauto.\n  - left. inv STEP. ss. inv LOCAL0; ss.\n    + esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto; ss.\n    + exploit reorder_read_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto; ss.\n    + exploit reorder_write_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto; ss.\n    + exploit reorder_write_cancel; eauto. i. des.\n      exploit reorder_read_cancel; eauto. i. des.\n      esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto; ss.\n    + exploit reorder_fence_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto; ss.\n    + exploit reorder_fence_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto; ss.\n    + esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto.\n        econs. econs. inv LOCAL1. inv LOCAL. inv PROMISE.\n        ii. ss. erewrite Memory.remove_o in PROMISE; eauto. des_ifs.\n        eapply CONSISTENT; eauto.\nQed.\n\nLemma reorder_step_cancels\n      lang\n      pf e1 th0 th1 th2\n      (STEP1: Thread.step pf e1 th0 th1)\n      (STEPS2: rtc (@Thread.cancel_step lang) th1 th2)\n  :\n    (exists th1',\n        (<<STEPS1: rtc (@Thread.cancel_step lang) th0 th1'>>) /\\\n        (<<STEP2: Thread.step pf e1 th1' th2>>)) \\/\n    ((<<STEPS1: rtc (@Thread.cancel_step lang) th0 th2>>) /\\ (<<RESERVE: ThreadEvent.is_reserve e1>>))\n.\nProof.\n  ginduction STEPS2; i.\n  - esplits; eauto.\n  - inv H. exploit reorder_step_cancel.\n    { eapply STEP1. }\n    { eapply STEP. }\n    { ss. }\n    i. des.\n    { exploit IHSTEPS2; eauto. i. des.\n      - left. esplits.\n        + econs 2.\n          * splits; auto. econs; eauto.\n          * eauto.\n        + eauto.\n      - right. splits; auto. econs 2; eauto. econs; eauto.\n    }\n    { subst. right. esplits; eauto. }\nQed.\n\nLemma reorder_opt_step_cancels\n      lang\n      e1 th0 th1 th2\n      (STEP1: Thread.opt_step e1 th0 th1)\n      (STEPS2: rtc (@Thread.cancel_step lang) th1 th2)\n  :\n    (exists th1',\n        (<<STEPS1: rtc (@Thread.cancel_step lang) th0 th1'>>) /\\\n        (<<STEP2: Thread.opt_step e1 th1' th2>>)) \\/\n    ((<<STEPS1: rtc (@Thread.cancel_step lang) th0 th2>>) /\\ (<<RESERVE: ThreadEvent.is_reserve e1>>)).\nProof.\n  inv STEP1.\n  { left. esplits; eauto. econs 1. }\n  { exploit reorder_step_cancels; eauto. i. des.\n    { left. esplits; eauto. econs 2; eauto. }\n    { right. esplits; eauto. }\n  }\nQed.\n\nLemma reorder_opt_step_cancels2\n      lang\n      e1 th0 th1 th2\n      (STEP1: Thread.opt_step e1 th0 th1)\n      (STEPS2: rtc (@Thread.cancel_step lang) th1 th2)\n  :\n    exists th1' e1',\n      (<<STEPS1: rtc (@Thread.cancel_step lang) th0 th1'>>) /\\\n      (<<STEP2: Thread.opt_step e1' th1' th2>>) /\\\n      __guard__(e1' = e1 \\/ e1' = ThreadEvent.silent /\\ <<RESERVE: ThreadEvent.is_reserve e1>>).\nProof.\n  unguard. inv STEP1.\n  { esplits.\n    { eauto. }\n    { econs 1. }\n    { auto. }\n  }\n  { exploit reorder_step_cancels; eauto. i. des.\n    { esplits; eauto. econs 2; eauto. }\n    { esplits; eauto. econs 1; eauto. }\n  }\nQed.\n\nLemma steps_cancels_not_cancels\n      P lang th0 th2\n      (STEPS: rtc (tau (@pred_step P lang)) th0 th2)\n  :\n    exists th1,\n      (<<STEPS1: rtc (@Thread.cancel_step _) th0 th1>>) /\\\n      (<<STEPS2: rtc (tau (@pred_step (P /1\\ fun e => ~ ThreadEvent.is_cancel e) _)) th1 th2>>)\n.\nProof.\n  ginduction STEPS; i.\n  - esplits; eauto.\n  - inv H. inv TSTEP. inv STEP.\n    hexploit IHSTEPS; eauto. i. des.\n    destruct (classic (ThreadEvent.is_cancel e)).\n    + unfold ThreadEvent.is_cancel in H. des_ifs. esplits.\n      * econs 2.\n        { econs; eauto. }\n        { eapply STEPS1. }\n      * eapply STEPS2.\n    + exploit reorder_step_cancels.\n      { eapply STEP0. }\n      { eapply STEPS1. }\n      i. des; eauto. esplits.\n      * eauto.\n      * econs 2.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { eauto. }\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/prop/ReorderCancel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.21309975204073242}}
{"text": "From oadt.lang_oadt Require Import base syntax semantics.\nFrom oadt.lang_oadt Require Export kind.\nImport syntax.notations semantics.notations kind.notations.\n\nImplicit Types (b : bool) (x X y Y : atom) (L : aset).\n\n(** * Definitions *)\n\n(** ** Typing context (Γ) *)\nNotation tctx := (amap lexpr).\n\nSection typing.\n\n#[local]\nCoercion EFVar : atom >-> expr.\n\nSection fix_gctx.\n\nContext (Σ : gctx).\n\n(** ** Parallel reduction *)\nReserved Notation \"e '⇛' e'\" (at level 40).\n\nInductive pared : expr -> expr -> Prop :=\n| RApp l τ e1 e2 e1' e2' L :\n    e1 ⇛ e1' ->\n    (forall x, x ∉ L -> <{ e2^x }> ⇛ <{ e2'^x }>) ->\n    lc τ ->\n    <{ (\\:{l}τ => e2) e1 }> ⇛ <{ e2'^e1' }>\n| RTApp X τ' τ e e' :\n    Σ !! X = Some (DOADT τ' τ) ->\n    e ⇛ e' ->\n    <{ X@e }> ⇛ <{ τ^e' }>\n| RLet e1 e2 e1' e2' L :\n    e1 ⇛ e1' ->\n    (forall x, x ∉ L -> <{ e2^x }> ⇛ <{ e2'^x }>) ->\n    <{ let e1 in e2 }> ⇛ <{ e2'^e1' }>\n| RFun x T e :\n    Σ !! x = Some (DFun T e) ->\n    <{ gvar x }> ⇛ <{ e }>\n| RProj l b e1 e2 e1' e2' :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    <{ π{l}@b (e1, e2){l} }> ⇛ <{ ite b e1' e2' }>\n| RFold X X' e e' :\n    e ⇛ e' ->\n    <{ unfold<X> (fold<X'> e) }> ⇛ e'\n| RIte b e1 e2 e1' e2' :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    <{ if b then e1 else e2 }> ⇛ <{ ite b e1' e2' }>\n| RCase b τ e0 e1 e2 e0' e1' e2' L1 L2 :\n    e0 ⇛ e0' ->\n    (forall x, x ∉ L1 -> <{ e1^x }> ⇛ <{ e1'^x }>) ->\n    (forall x, x ∉ L2 -> <{ e2^x }> ⇛ <{ e2'^x }>) ->\n    lc τ ->\n    <{ case inj@b<τ> e0 of e1 | e2 }> ⇛ <{ ite b (e1'^e0') (e2'^e0') }>\n(* The rules for oblivous constructs are solely for proof convenience. They are\nnot needed because they are not involved in type-level computation. *)\n| RMux b e1 e2 e1' e2' :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    <{ mux [b] e1 e2 }> ⇛ <{ ite b e1' e2' }>\n(* This rule is needed for confluence. *)\n| ROIte b e1 e2 e1' e2' :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    <{ ~if [b] then e1 else e2 }> ⇛ <{ ite b e1' e2' }>\n| ROCase b ω1 ω2 v v1 v2 e1 e2 e1' e2' L1 L2 :\n    oval v ->\n    ovalty v1 ω1 -> ovalty v2 ω2 ->\n    (forall x, x ∉ L1 -> <{ e1^x }> ⇛ <{ e1'^x }>) ->\n    (forall x, x ∉ L2 -> <{ e2^x }> ⇛ <{ e2'^x }>) ->\n    <{ ~case [inj@b<ω1 ~+ ω2> v] of e1 | e2 }> ⇛\n      <{ ~if [b] then (ite b (e1'^v) (e1'^v1)) else (ite b (e2'^v2) (e2'^v)) }>\n| RSec b :\n    <{ s𝔹 b }> ⇛ <{ [b] }>\n| ROInj b ω v :\n    otval ω -> oval v ->\n    <{ ~inj@b<ω> v }> ⇛ <{ [inj@b<ω> v] }>\n(* Unfortunately I have to spell out all the cases corresponding to [SOIte] for\nproof convenience. *)\n| ROIteApp b e1 e2 e e1' e2' e' :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    e ⇛ e' ->\n    <{ (~if [b] then e1 else e2) e }> ⇛ <{ ~if [b] then e1' e' else e2' e' }>\n| ROIteSec b e1 e2 e1' e2' :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    <{ s𝔹 (~if [b] then e1 else e2) }> ⇛ <{ ~if [b] then s𝔹 e1' else s𝔹 e2' }>\n| ROIteIte b e1 e2 e3 e4 e1' e2' e3' e4' :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    e3 ⇛ e3' ->\n    e4 ⇛ e4' ->\n    <{ if (~if [b] then e1 else e2) then e3 else e4 }> ⇛\n      <{ ~if [b] then (if e1' then e3' else e4') else (if e2' then e3' else e4') }>\n| ROIteProj b b' e1 e2 e1' e2' :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    <{ π@b' (~if [b] then e1 else e2) }> ⇛\n      <{ ~if [b] then π@b' e1' else π@b' e2' }>\n| ROIteCase b e1 e2 e3 e4 e1' e2' e3' e4' L1 L2 :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    (forall x, x ∉ L1 -> <{ e3^x }> ⇛ <{ e3'^x }>) ->\n    (forall x, x ∉ L2 -> <{ e4^x }> ⇛ <{ e4'^x }>) ->\n    <{ case (~if [b] then e1 else e2) of e3 | e4 }> ⇛\n      <{ ~if [b] then (case e1' of e3' | e4') else (case e2' of e3' | e4') }>\n| ROIteUnfold X b e1 e2 e1' e2' :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    <{ unfold<X> (~if [b] then e1 else e2) }> ⇛\n      <{ ~if [b] then unfold<X> e1' else unfold<X> e2' }>\n| RTapeOIte b e1 e2 e1' e2' :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    <{ tape (~if [b] then e1 else e2) }> ⇛ <{ mux [b] (tape e1') (tape e2') }>\n| RTapeOVal v :\n    oval v ->\n    <{ tape v }> ⇛ v\n(* Congruence rules *)\n| RCgrPi l τ1 τ2 τ1' τ2' L :\n    τ1 ⇛ τ1' ->\n    (forall x, x ∉ L -> <{ τ2^x }> ⇛ <{ τ2'^x }>) ->\n    <{ Π:{l}τ1, τ2 }> ⇛ <{ Π:{l}τ1', τ2' }>\n| RCgrAbs l τ e τ' e' L :\n    τ ⇛ τ' ->\n    (forall x, x ∉ L -> <{ e^x }> ⇛ <{ e'^x }>) ->\n    <{ \\:{l}τ => e }> ⇛ <{ \\:{l}τ' => e' }>\n| RCgrApp e1 e2 e1' e2' :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    <{ e1 e2 }> ⇛ <{ e1' e2' }>\n| RCgrTApp X e e' :\n    e ⇛ e' ->\n    <{ X@e }> ⇛ <{ X@e' }>\n| RCgrLet e1 e2 e1' e2' L :\n    e1 ⇛ e1' ->\n    (forall x, x ∉ L -> <{ e2^x }> ⇛ <{ e2'^x }>) ->\n    <{ let e1 in e2 }> ⇛ <{ let e1' in e2' }>\n| RCgrSec e e' :\n    e ⇛ e' ->\n    <{ s𝔹 e }> ⇛ <{ s𝔹 e' }>\n| RCgrIte l e0 e1 e2 e0' e1' e2' :\n    e0 ⇛ e0' ->\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    <{ if{l} e0 then e1 else e2 }> ⇛ <{ if{l} e0' then e1' else e2' }>\n| RCgrProd l τ1 τ2 τ1' τ2' :\n    τ1 ⇛ τ1' ->\n    τ2 ⇛ τ2' ->\n    <{ τ1 *{l} τ2 }> ⇛ <{ τ1' *{l} τ2' }>\n| RCgrPair l e1 e2 e1' e2' :\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    <{ (e1, e2){l} }> ⇛ <{ (e1', e2'){l} }>\n| RCgrProj l b e e' :\n    e ⇛ e' ->\n    <{ π{l}@b e }> ⇛ <{ π{l}@b e' }>\n| RCgrSum l τ1 τ2 τ1' τ2' :\n    τ1 ⇛ τ1' ->\n    τ2 ⇛ τ2' ->\n    <{ τ1 +{l} τ2 }> ⇛ <{ τ1' +{l} τ2' }>\n| RCgrInj l b τ e τ' e' :\n    e ⇛ e' ->\n    τ ⇛ τ' ->\n    <{ inj{l}@b<τ> e }> ⇛ <{ inj{l}@b<τ'> e' }>\n| RCgrCase l e0 e1 e2 e0' e1' e2' L1 L2 :\n    e0 ⇛ e0' ->\n    (forall x, x ∉ L1 -> <{ e1^x }> ⇛ <{ e1'^x }>) ->\n    (forall x, x ∉ L2 -> <{ e2^x }> ⇛ <{ e2'^x }>) ->\n    <{ case{l} e0 of e1 | e2 }> ⇛ <{ case{l} e0' of e1' | e2' }>\n| RCgrFold X e e' :\n    e ⇛ e' ->\n    <{ fold<X> e }> ⇛ <{ fold<X> e' }>\n| RCgrUnfold X e e' :\n    e ⇛ e' ->\n    <{ unfold<X> e }> ⇛ <{ unfold<X> e' }>\n| RCgrMux e0 e1 e2 e0' e1' e2' :\n    e0 ⇛ e0' ->\n    e1 ⇛ e1' ->\n    e2 ⇛ e2' ->\n    <{ mux e0 e1 e2 }> ⇛ <{ mux e0' e1' e2' }>\n| RCgrTape e e' :\n    e ⇛ e' ->\n    <{ tape e }> ⇛ <{ tape e' }>\n(* Reflexive rule *)\n| RRefl e :\n    lc e ->\n    e ⇛ e\n\nwhere \"e1 '⇛' e2\" := (pared e1 e2)\n.\n\nNotation \"e '⇛*' e'\" := (rtc pared e e') (at level 40).\n\n(** ** Expression equivalence *)\n(** We directly define equivalence in terms of parallel reduction. *)\n\n(** This definition is the same as saying two expressions multi-reduce to the\nsame expression (i.e. [pared_equiv_join] below), but easier for induction in\nmost cases. *)\nInductive pared_equiv : expr -> expr -> Prop :=\n| QRRefl e : e ≡ e\n| QRRedL e1 e1' e2 :\n    e1 ⇛ e1' ->\n    e1' ≡ e2 ->\n    e1 ≡ e2\n| QRRedR e1 e2 e2' :\n    e2 ⇛ e2' ->\n    e1 ≡ e2' ->\n    e1 ≡ e2\n\nwhere \"e1 ≡ e2\" := (pared_equiv e1 e2)\n.\n\n(** This is equivalent to [pared_equiv]. *)\nDefinition pared_equiv_join (e1 e2 : expr) : Prop :=\n  exists e, e1 ⇛* e /\\ e2 ⇛* e.\n\n(** ** Typing and kinding *)\n(** They are mutually defined. *)\nReserved Notation \"Γ '⊢' e ':{' l '}' τ\" (at level 40,\n                                          e custom oadt at level 99,\n                                          l constr at level 99,\n                                          τ custom oadt at level 99).\nReserved Notation \"Γ '⊢' τ '::' κ\" (at level 40,\n                                    τ custom oadt at level 99,\n                                    κ custom oadt at level 99).\n\nInductive typing : tctx -> expr -> llabel -> expr -> Prop :=\n| TFVar Γ x l τ κ :\n    Γ !! x = Some (l, τ) ->\n    Γ ⊢ τ :: κ ->\n    Γ ⊢ fvar x :{l} τ\n| TGVar Γ x l τ e :\n    Σ !! x = Some (DFun (l, τ) e) ->\n    Γ ⊢ gvar x :{l} τ\n| TAbs Γ l1 l2 e τ1 τ2 κ L :\n    (forall x, x ∉ L -> <[x:=(l2, τ2)]>Γ ⊢ e^x :{l1} τ1^x) ->\n    Γ ⊢ τ2 :: κ ->\n    Γ ⊢ \\:{l2}τ2 => e :{l1} (Π:{l2}τ2, τ1)\n| TLet Γ l1 l2 e1 e2 τ1 τ2 L :\n    Γ ⊢ e1 :{l1} τ1 ->\n    (forall x, x ∉ L -> <[x:=(l1, τ1)]>Γ ⊢ e2^x :{l2} τ2^x) ->\n    Γ ⊢ let e1 in e2 :{l2} τ2^e1\n| TApp Γ l1 l2 e1 e2 τ1 τ2 :\n    Γ ⊢ e1 :{l1} (Π:{l2}τ2, τ1) ->\n    Γ ⊢ e2 :{l2} τ2 ->\n    Γ ⊢ e1 e2 :{l1} τ1^e2\n| TUnit Γ : Γ ⊢ () :{⊥} 𝟙\n| TLit Γ b : Γ ⊢ lit b :{⊥} 𝔹\n| TSec Γ l e :\n    Γ ⊢ e :{l} 𝔹 ->\n    Γ ⊢ s𝔹 e :{l} ~𝔹\n| TIte Γ l1 l2 l e0 e1 e2 τ κ :\n    Γ ⊢ e0 :{⊥} 𝔹 ->\n    Γ ⊢ e1 :{l1} τ^(lit true) ->\n    Γ ⊢ e2 :{l2} τ^(lit false) ->\n    Γ ⊢ τ^e0 :: κ ->\n    l = l1 ⊔ l2 ->\n    Γ ⊢ if e0 then e1 else e2 :{l} τ^e0\n| TIteNoDep Γ l0 l1 l2 l e0 e1 e2 τ :\n    Γ ⊢ e0 :{l0} 𝔹 ->\n    Γ ⊢ e1 :{l1} τ ->\n    Γ ⊢ e2 :{l2} τ ->\n    l = l0 ⊔ l1 ⊔ l2 ->\n    Γ ⊢ if e0 then e1 else e2 :{l} τ\n| TOIte Γ l1 l2 e0 e1 e2 τ κ :\n    Γ ⊢ e0 :{⊥} ~𝔹 ->\n    Γ ⊢ e1 :{l1} τ ->\n    Γ ⊢ e2 :{l2} τ ->\n    Γ ⊢ τ :: κ ->\n    Γ ⊢ ~if e0 then e1 else e2 :{⊤} τ\n| TInj Γ l b e τ1 τ2 κ :\n    Γ ⊢ e :{l} ite b τ1 τ2 ->\n    Γ ⊢ τ1 + τ2 :: κ ->\n    Γ ⊢ inj@b<τ1 + τ2> e :{l} τ1 + τ2\n| TOInj Γ b e τ1 τ2 :\n    Γ ⊢ e :{⊥} ite b τ1 τ2 ->\n    Γ ⊢ τ1 ~+ τ2 :: *@O ->\n    Γ ⊢ ~inj@b<τ1 ~+ τ2> e :{⊥} τ1 ~+ τ2\n| TCase Γ l1 l2 l e0 e1 e2 τ1 τ2 τ κ L1 L2 :\n    Γ ⊢ e0 :{⊥} τ1 + τ2 ->\n    (forall x, x ∉ L1 -> <[x:=(⊥, τ1)]>Γ ⊢ e1^x :{l1} τ^(inl<τ1 + τ2> x)) ->\n    (forall x, x ∉ L2 -> <[x:=(⊥, τ2)]>Γ ⊢ e2^x :{l2} τ^(inr<τ1 + τ2> x)) ->\n    Γ ⊢ τ^e0 :: κ ->\n    l = l1 ⊔ l2 ->\n    Γ ⊢ case e0 of e1 | e2 :{l} τ^e0\n| TCaseNoDep Γ l0 l1 l2 l e0 e1 e2 τ1 τ2 τ κ L1 L2 :\n    Γ ⊢ e0 :{l0} τ1 + τ2 ->\n    (forall x, x ∉ L1 -> <[x:=(l0, τ1)]>Γ ⊢ e1^x :{l1} τ) ->\n    (forall x, x ∉ L2 -> <[x:=(l0, τ2)]>Γ ⊢ e2^x :{l2} τ) ->\n    Γ ⊢ τ :: κ ->\n    l = l0 ⊔ l1 ⊔ l2 ->\n    Γ ⊢ case e0 of e1 | e2 :{l} τ\n| TOCase Γ l1 l2 e0 e1 e2 τ1 τ2 τ κ L1 L2 :\n    Γ ⊢ e0 :{⊥} τ1 ~+ τ2 ->\n    (forall x, x ∉ L1 -> <[x:=(⊥, τ1)]>Γ ⊢ e1^x :{l1} τ) ->\n    (forall x, x ∉ L2 -> <[x:=(⊥, τ2)]>Γ ⊢ e2^x :{l2} τ) ->\n    Γ ⊢ τ :: κ ->\n    Γ ⊢ ~case e0 of e1 | e2 :{⊤} τ\n| TPair Γ l1 l2 l e1 e2 τ1 τ2 :\n    Γ ⊢ e1 :{l1} τ1 ->\n    Γ ⊢ e2 :{l2} τ2 ->\n    l = l1 ⊔ l2 ->\n    Γ ⊢ (e1, e2) :{l} τ1 * τ2\n| TOPair Γ e1 e2 τ1 τ2 :\n    Γ ⊢ e1 :{⊥} τ1 ->\n    Γ ⊢ e2 :{⊥} τ2 ->\n    Γ ⊢ τ1 :: *@O ->\n    Γ ⊢ τ2 :: *@O ->\n    Γ ⊢ ~(e1, e2) :{⊥} τ1 ~* τ2\n| TProj Γ l b e τ1 τ2 :\n    Γ ⊢ e :{l} τ1 * τ2 ->\n    Γ ⊢ π@b e :{l} ite b τ1 τ2\n| TOProj Γ b e τ1 τ2 :\n    Γ ⊢ e :{⊥} τ1 ~* τ2 ->\n    Γ ⊢ ~π@b e :{⊥} ite b τ1 τ2\n| TFold Γ l X e τ :\n    Σ !! X = Some (DADT τ) ->\n    Γ ⊢ e :{l} τ ->\n    Γ ⊢ fold<X> e :{l} gvar X\n| TUnfold Γ l X e τ :\n    Σ !! X = Some (DADT τ) ->\n    Γ ⊢ e :{l} gvar X ->\n    Γ ⊢ unfold<X> e :{l} τ\n| TMux Γ e0 e1 e2 τ :\n    Γ ⊢ e0 :{⊥} ~𝔹 ->\n    Γ ⊢ e1 :{⊥} τ ->\n    Γ ⊢ e2 :{⊥} τ ->\n    Γ ⊢ τ :: *@O ->\n    Γ ⊢ mux e0 e1 e2 :{⊥} τ\n| TTape Γ l e τ :\n    Γ ⊢ e :{l} τ ->\n    Γ ⊢ τ :: *@O ->\n    Γ ⊢ tape e :{⊥} τ\n(* Typing for runtime expressions is for metatheories. These expressions do not\nappear in source programs. Plus, it is not possible to type them at runtime\nsince they are \"encrypted\" values. *)\n| TBoxedLit Γ b : Γ ⊢ [b] :{⊥} ~𝔹\n| TBoxedInj Γ b v ω :\n    ovalty <{ [inj@b<ω> v] }> ω ->\n    Γ ⊢ [inj@b<ω> v] :{⊥} ω\n(* Type conversion *)\n| TConv Γ l l' e τ τ' κ :\n    Γ ⊢ e :{l'} τ' ->\n    τ' ≡ τ ->\n    Γ ⊢ τ :: κ ->\n    l' ⊑ l ->\n    Γ ⊢ e :{l} τ\n\nwith kinding : tctx -> expr -> kind -> Prop :=\n| KGVar Γ X τ :\n    Σ !! X = Some (DADT τ) ->\n    Γ ⊢ gvar X :: *@P\n| KUnit Γ : Γ ⊢ 𝟙 :: *@A\n| KBool Γ l : Γ ⊢ 𝔹{l} :: ite l *@O *@P\n| KPi Γ l τ1 τ2 κ1 κ2 L :\n    (forall x, x ∉ L -> <[x:=(l, τ1)]>Γ ⊢ τ2^x :: κ2) ->\n    Γ ⊢ τ1 :: κ1 ->\n    Γ ⊢ (Π:{l}τ1, τ2) :: *@M\n| KApp Γ e' e τ X :\n    Σ !! X = Some (DOADT τ e') ->\n    Γ ⊢ e :{⊥} τ ->\n    Γ ⊢ X@e :: *@O\n| KProd Γ τ1 τ2 κ :\n    Γ ⊢ τ1 :: κ ->\n    Γ ⊢ τ2 :: κ ->\n    Γ ⊢ τ1 * τ2 :: (κ ⊔ *@P)\n| KOProd Γ τ1 τ2 :\n    Γ ⊢ τ1 :: *@O ->\n    Γ ⊢ τ2 :: *@O ->\n    Γ ⊢ τ1 ~* τ2 :: *@O\n| KSum Γ τ1 τ2 κ :\n    Γ ⊢ τ1 :: κ ->\n    Γ ⊢ τ2 :: κ ->\n    Γ ⊢ τ1 + τ2 :: (κ ⊔ *@P)\n| KOSum Γ τ1 τ2 :\n    Γ ⊢ τ1 :: *@O ->\n    Γ ⊢ τ2 :: *@O ->\n    Γ ⊢ τ1 ~+ τ2 :: *@O\n| KIte Γ e0 τ1 τ2 :\n    Γ ⊢ e0 :{⊥} 𝔹 ->\n    Γ ⊢ τ1 :: *@O ->\n    Γ ⊢ τ2 :: *@O ->\n    Γ ⊢ if e0 then τ1 else τ2 :: *@O\n| KCase Γ e0 τ1 τ2 τ1' τ2' L1 L2 :\n    Γ ⊢ e0 :{⊥} τ1' + τ2' ->\n    (forall x, x ∉ L1 -> <[x:=(⊥, τ1')]>Γ ⊢ τ1^x :: *@O) ->\n    (forall x, x ∉ L2 -> <[x:=(⊥, τ2')]>Γ ⊢ τ2^x :: *@O) ->\n    Γ ⊢ case e0 of τ1 | τ2 :: *@O\n| KLet Γ e τ τ' L :\n    Γ ⊢ e :{⊥} τ' ->\n    (forall x, x ∉ L -> <[x:=(⊥, τ')]>Γ ⊢ τ^x :: *@O) ->\n    Γ ⊢ let e in τ :: *@O\n| KSub Γ τ κ κ' :\n    Γ ⊢ τ :: κ' ->\n    κ' ⊑ κ ->\n    Γ ⊢ τ :: κ\n\nwhere \"Γ '⊢' e ':{' l '}' τ\" := (typing Γ e l τ)\n  and \"Γ '⊢' τ '::' κ\" := (kinding Γ τ κ)\n.\n\nEnd fix_gctx.\n\n(** Better induction principle. *)\nScheme typing_kinding_ind := Minimality for typing Sort Prop\n  with kinding_typing_ind := Minimality for kinding Sort Prop.\nCombined Scheme typing_kinding_mutind\n         from typing_kinding_ind, kinding_typing_ind.\n\nNotation \"Σ '⊢' e '≡' e'\" := (pared_equiv Σ e e')\n                               (at level 40,\n                                e custom oadt at level 99,\n                                e' custom oadt at level 99).\nNotation \"Σ ; Γ '⊢' e ':{' l '}' τ\" := (typing Σ Γ e l τ)\n                                         (at level 40,\n                                           Γ constr at next level,\n                                           e custom oadt at level 99,\n                                           τ custom oadt at level 99,\n                                           format \"Σ ;  Γ  '⊢'  e  ':{' l '}'  τ\").\nNotation \"Σ ; Γ '⊢' τ '::' κ\" := (kinding Σ Γ τ κ)\n                                   (at level 40,\n                                    Γ constr at next level,\n                                    τ custom oadt at level 99,\n                                    κ custom oadt at level 99).\n\n(** ** Global definitions typing *)\nReserved Notation \"Σ '⊢₁' D\" (at level 40).\n\nInductive gdef_typing : gctx -> gdef -> Prop :=\n| DTADT Σ τ :\n    Σ; ∅ ⊢ τ :: *@P ->\n    Σ ⊢₁ (DADT τ)\n| DTOADT Σ τ e L :\n    Σ; ∅ ⊢ τ :: *@P ->\n    (forall x, x ∉ L -> Σ; ({[x:=(⊥, τ)]}) ⊢ e^x :: *@O) ->\n    Σ ⊢₁ (DOADT τ e)\n| DTFun Σ l τ e κ :\n    Σ; ∅ ⊢ τ :: κ ->\n    Σ; ∅ ⊢ e :{l} τ ->\n    Σ ⊢₁ (DFun (l, τ) e)\n\nwhere \"Σ '⊢₁' D\" := (gdef_typing Σ D)\n.\n\nDefinition gctx_typing (Σ : gctx) : Prop :=\n  map_Forall (fun _ D => Σ ⊢₁ D) Σ.\n\n(** ** Program typing *)\n(** The top level expression should not contain potential leaks. *)\nDefinition program_typing (Σ : gctx) (e : expr) (τ : expr) :=\n  gctx_typing Σ /\\ Σ; ∅ ⊢ e :{⊥} τ.\n\n(** ** Well-formedness of global context *)\n(** Equivalent to [gctx_typing]. Essentially saying all definitions in [Σ] are\nwell-typed. *)\n(* TODO: I should use a weaker assumption in some proofs, such as all global\ndefinitions are locally closed. *)\nDefinition gctx_wf (Σ : gctx) :=\n  map_Forall (fun _ D =>\n                match D with\n                | DADT τ =>\n                  Σ; ∅ ⊢ τ :: *@P\n                | DOADT τ e =>\n                  Σ; ∅ ⊢ τ :: *@P /\\\n                  exists L, forall x, x ∉ L -> Σ; ({[x:=(⊥, τ)]}) ⊢ e^x :: *@O\n                | DFun (l, τ) e =>\n                  Σ; ∅ ⊢ e :{l} τ /\\\n                  exists κ, Σ; ∅ ⊢ τ :: κ\n                end) Σ.\n\nEnd typing.\n\n(** * Notations *)\n(* Unfortunately I have to copy-paste all notations here again. *)\nModule notations.\n\nExport kind.notations.\n\nNotation \"Σ '⊢' e '⇛' e'\" := (pared Σ e e')\n                               (at level 40,\n                                 e custom oadt at level 99,\n                                 e' custom oadt at level 99).\nNotation \"Σ '⊢' e '⇛*' e'\" := (rtc (pared Σ) e e')\n                                (at level 40,\n                                  e custom oadt at level 99,\n                                  e' custom oadt at level 99).\nNotation \"Σ '⊢' e '≡' e'\" := (pared_equiv Σ e e')\n                               (at level 40,\n                                e custom oadt at level 99,\n                                e' custom oadt at level 99).\nNotation \"Σ ; Γ '⊢' e ':{' l '}' τ\" := (typing Σ Γ e l τ)\n                                         (at level 40,\n                                           Γ constr at next level,\n                                           e custom oadt at level 99,\n                                           τ custom oadt at level 99,\n                                           format \"Σ ;  Γ  '⊢'  e  ':{' l '}'  τ\").\nNotation \"Σ ; Γ '⊢' e ':' τ\" := (typing Σ Γ e _ τ)\n                                         (at level 40,\n                                           Γ constr at next level,\n                                           e custom oadt at level 99,\n                                           τ custom oadt at level 99,\n                                           only parsing).\nNotation \"Σ ; Γ '⊢' τ '::' κ\" := (kinding Σ Γ τ κ)\n                                   (at level 40,\n                                    Γ constr at next level,\n                                    τ custom oadt at level 99,\n                                    κ custom oadt at level 99).\n\nNotation \"Σ '⊢₁' D\" := (gdef_typing Σ D) (at level 40).\n\nNotation \"Σ ; e '▷' τ\" := (program_typing Σ e τ)\n                            (at level 40,\n                              e at next level).\n\nNotation \"e '⇛' e'\" := (pared _ e e') (at level 40).\nNotation \"e '⇛*' e'\" := (rtc (pared _) e e') (at level 40).\n\nNotation \"Γ '⊢' e ':{' l '}' τ\" := (typing _ Γ e l τ)\n                                     (at level 40,\n                                       e custom oadt at level 99,\n                                       l constr at level 99,\n                                       τ custom oadt at level 99,\n                                       format \"Γ  '⊢'  e  ':{' l '}'  τ\").\nNotation \"Γ '⊢' e ':' τ\" := (typing _ Γ e _ τ)\n                              (at level 40,\n                                e custom oadt at level 99,\n                                τ custom oadt at level 99,\n                                only parsing).\nNotation \"Γ '⊢' τ '::' κ\" := (kinding _ Γ τ κ)\n                               (at level 40,\n                                 τ custom oadt at level 99,\n                                 κ custom oadt at level 99).\nEnd notations.\n", "meta": {"author": "ccyip", "repo": "oadt", "sha": "e2aa9db42299a8b1562572a07fb8e69056e8df64", "save_path": "github-repos/coq/ccyip-oadt", "path": "github-repos/coq/ccyip-oadt/oadt-e2aa9db42299a8b1562572a07fb8e69056e8df64/theories/lang_oadt/typing.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.21309973867714635}}
{"text": "From Utils     Require Import Defns.\nFrom CompCert  Require Import Coqlib Maps Lattice Kildall Errors.\nFrom PIPE      Require Import TagDomain.\nFrom RTLT      Require Import Language Semantics Policy.\nFrom DeadcodeT Require Import DeadDomain.\nImport ListNotations.\n\nModule Functor (Export Tags  : TagDomain.MiddleEnd)\n               (Export Rules : RTLT.Policy.Sig Tags)\n               (Export Lang  : RTLT.Language.Sig Tags)\n               (Import Sem   : RTLT.Semantics.Sig Tags Rules Lang)\n               (Import Flags : RTLT.Policy.Props Tags Lang Rules).\n\nModule Export DDomain := DeadDomain.Functor Tags Rules Lang Sem.\n\nDefinition add_need_all (r: reg) (ne: nbank) : nbank :=\n  NB.set r Live ne.\n\nFixpoint add_needs_all (rl: list reg) (ne: nbank) : nbank :=\n  match rl with\n  | nil => ne\n  | r1 :: rs => add_need_all r1 (add_needs_all rs ne)\n  end.\n\nDefinition kill (r: reg) (ne: nbank) : nbank := NB.set r Dead ne.\n\nDefinition is_dead_atm (v: nval) : bool :=\n  match v with Dead => true | _ => false end.\n\nDefinition is_dead_rule (ti: tinst) :=\n  (dfs ti) &p (lpcp ti).\n\n\nDefinition transfer (f: function) (pc: node) (after: NA.t) : NA.t :=\n    match f.(body) ! pc with None => NA.bot | Some ti =>\n  match ti with \n  | (Inop _, _) => after\n  | (Imov rs rd _, itag) =>\n      let nrd := nreg after rd in\n      if (is_dead_rule ti) &&p (is_dead_atm nrd) then after\n      else add_need_all rs (if (dnd_ImovTR itag)\n                             then (        kill rd after)\n                             else (add_need_all rd after))\n  | (Imovi _ rd _, _) =>\n      let nrd := nreg after rd in\n      if (is_dead_rule ti) &&p (is_dead_atm nrd) then after\n      else kill rd after\n  | (Iop _ r1 r2 rd _, _) =>\n      let nrd := nreg after rd in\n      if (is_dead_rule ti) &&p (is_dead_atm nrd) then after\n      else add_needs_all [r1; r2] (kill rd after)\n  | (Icond cond r1 r2 s1 s2, _) =>\n      if (is_dead_rule ti) &&p (peq s1 s2) then after else\n        add_needs_all [r1; r2] after\n  | (Icall callee_id args rd _, _) =>\n      add_needs_all args (kill rd after)\n  | (Ireturn r, _) =>\n      add_need_all r after\n  end end.\n\n\nModule DS := Backward_Dataflow_Solver(NA)(NodeSetBackward).\n\nDefinition analyze (f: function): option (PMap.t NA.t) :=\n  DS.fixpoint f.(body) successors_tinst (transfer f).\n\nDefinition transl_instr (an: PMap.t NA.t) (pc: node) (ti: tinst) :=\n  match ti with\n  | (Imov  _   rd ns, _)\n  | (Imovi _   rd ns, _)\n  | (Iop _ _ _ rd ns, _) =>\n      let nrd := nreg (an !! pc) rd in\n      if (is_dead_rule ti) &&p (is_dead_atm nrd)\n      then noop ns else ti\n  | (Icond _ r1 r2 s1 s2, _) =>\n      if (is_dead_rule ti) &&p (peq s1 s2)\n      then noop s1 else ti\n  | _ => ti\n  end.\n\nDefinition transl_function (f: function) : res function :=\n  match analyze f with\n  | Some an =>\n      OK {| arity := f.(arity);\n            params := f.(params);\n            body := PTree.map (transl_instr an ) f.(body);\n            entrypoint := f.(entrypoint);\n            fntag := f.(fntag) |}\n  | None => Error [MSG \"analysis failed\"]\n  end.\n\nLocal Open Scope error_monad_scope.\nFixpoint transl_program (p: program) : res program :=\n  match p with\n  | (i,f) :: tl => do tf <- transl_function f;\n                   do tp <- transl_program tl;\n                     OK ((i,tf) :: tp)\n  | []          => OK []\n  end.\nLocal Close Scope error_monad_scope.\n\n\n\n(* Some utility facts about translation *)\n\nLemma tr_function_preserves : forall {f tf},\n  transl_function f = OK tf ->\n  tf.(fntag) = f.(fntag) /\\\n  tf.(arity) = f.(arity) /\\\n  tf.(entrypoint) = f.(entrypoint) /\\\n  tf.(params) = f.(params).\nProof.\n  intros. unfold transl_function in H.\n  destruct (analyze f); inv H; auto.\nQed.\n\nLemma tr_function_fntag:\n  forall {f tf},\n  transl_function f = OK tf ->\n  tf.(fntag) = f.(fntag).\nProof with auto.\n  intros. destruct (tr_function_preserves H)...\nQed.\n\nLemma tr_function_sig:\n  forall {f tf},\n  transl_function f = OK tf ->\n  tf.(arity) = f.(arity).\nProof with auto.\n  intros. destruct (tr_function_preserves H)\nas [_[? _]]...\nQed.\n\nLemma tr_function_entry:\n  forall {f tf},\n  transl_function f = OK tf ->\n  tf.(entrypoint) = f.(entrypoint).\nProof with auto.\n  intros * H. unfold transl_function in H.\n  destruct (analyze f); inv H; simpl...\nQed.\n\nLemma tr_function_params:\n  forall {f tf},\n  transl_function f = OK tf ->\n  tf.(params) = f.(params).\nProof with auto.\n  intros * H. unfold transl_function in H.\n  destruct (analyze f); inv H; simpl...\nQed.\n\n\n\n\n\n\n\n\n\n\n\nEnd Functor.\n\n(* \n\nport/adapt CC RTL printer / extraction\n\n\nwriteup should be\n  organized by optimization - as the major axis\n  then talk about rule constraints - which may show up under multiple optimizations\n  talk about dead code, CSE, const prop, but some of them will be \"hypothetical\"\n  ?function inlining\n\n\n\n\n\n\n\n\n\n\n *)\n", "meta": {"author": "hope-pdx", "repo": "Tagine-public", "sha": "aa4e91add0de5a2d6bf7162d03064a8f86aebc58", "save_path": "github-repos/coq/hope-pdx-Tagine-public", "path": "github-repos/coq/hope-pdx-Tagine-public/Tagine-public-aa4e91add0de5a2d6bf7162d03064a8f86aebc58/deadcodet/Compiler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038302, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.21305412344365285}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.funcptr.\n\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nLocal Open Scope Z.\nLocal Open Scope logic.\n\nDefinition myspec :=\n  WITH i: Z\n  PRE [ tint ]\n          PROP (Int.min_signed <= i < Int.max_signed)\n          PARAMS (Vint (Int.repr i))\n          SEP ()\n  POST [ tint ]\n         PROP() RETURN (Vint (Int.repr (i+1)))\n          SEP().\n\nDefinition myfunc_spec := DECLARE _myfunc myspec.\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre prog tt gv\n  POST [ tint ] main_post prog gv.\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [\n    myfunc_spec; main_spec]).\n\nLemma body_myfunc: semax_body Vprog Gprog f_myfunc myfunc_spec.\nProof.\nunfold myfunc_spec.\nunfold myspec.\nstart_function.\nforward.\nQed.\n\nLemma body_main: semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function. fold cc_default noattr tint.\nmake_func_ptr _myfunc.\nforward.\n\nforward_call 3.\n  computable.\nforward.\nQed.\n", "meta": {"author": "Ereboas", "repo": "PL-Final-Project", "sha": "442d296ce43a3728e7a8c2b373db2d331a4a4bbf", "save_path": "github-repos/coq/Ereboas-PL-Final-Project", "path": "github-repos/coq/Ereboas-PL-Final-Project/PL-Final-Project-442d296ce43a3728e7a8c2b373db2d331a4a4bbf/code/VST/progs/verif_funcptr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21298526553731986}}
{"text": "Require Import CertiGraph.CertiGC.gc_spec.\n\nLocal Open Scope logic.\n\nLemma data_at_heaptype_eq: forall (sh: share) v h,\n    isptr h -> field_compatible heap_type [StructField _spaces] h ->\n    data_at sh heap_type v h = data_at sh (tarray space_type 12) v h.\nProof.\n  intros. unfold_data_at (data_at _ heap_type _ _). rewrite field_at_data_at. simpl nested_field_type.\n  rewrite field_address_offset; auto. simpl nested_field_offset.\n  rewrite isptr_offset_val_zero; auto.\nQed.\n\nLemma split2_data_at_Tarray_space_type:\n  forall (sh: share) (n n1: Z) (v: list (val * (val * val))) (p: val),\n    0 <= n1 <= n -> n = Zlength v ->\n    data_at sh (tarray space_type n) v p =\n    data_at sh (tarray space_type n1) (sublist 0 n1 v) p *\n    data_at sh (tarray space_type (n - n1)) (sublist n1 n v)\n            (field_address0 (tarray space_type n) [ArraySubsc n1] p).\nProof.\n  intros. pose proof (split2_data_at_Tarray sh space_type n n1) as HS.\n  apply HS with (v' := v); auto.\n  - rewrite Z.le_lteq. right; auto.\n  - rewrite sublist_same; auto.\nQed.\n\nLemma space_array_1_eq: forall (sh: share) (v: (val * (val * val))) (p: val),\n    data_at sh (tarray space_type 1) [v] p = data_at sh space_type v p.\nProof.\n  intros. pose proof (data_at_singleton_array_eq sh space_type). apply H. reflexivity.\nQed.\n\nLemma repeat_cons {t: Type}: forall i (v: t),\n    1 <= i -> repeat v (Z.to_nat i) = v :: repeat v (Z.to_nat (i - 1)).\nProof.\n  intros. replace (Z.to_nat i) with (S (Z.to_nat (i - 1))).\n  - simpl. auto.\n  - rewrite <- Z2Nat.inj_succ by lia. f_equal. lia.\nQed.\n\nLemma Znth_repeat_app {X: Type} {IX: Inhabitant X}: forall i (vh v0 vn: X) l,\n    1 <= i -> Znth i (vh :: repeat v0 (Z.to_nat (i - 1)) ++ vn :: l) = vn.\nProof.\n  intros. rewrite Znth_pos_cons by lia.\n  rewrite app_Znth2 by (rewrite Zlength_repeat; lia).\n  rewrite Zlength_repeat by lia.\n  replace (i - 1 - (i - 1)) with 0 by lia. rewrite Znth_0_cons. reflexivity.\nQed.\n\nLemma upd_Znth_repeat_app {X: Type} {IX: Inhabitant X}:\n  forall i (vh v0 v1 v2: X) l,\n    1 <= i -> upd_Znth i (vh :: repeat v0 (Z.to_nat (i - 1)) ++ v1 :: l) v2 =\n              vh :: repeat v0 (Z.to_nat (i - 1)) ++ v2 :: l.\nProof.\n  intros. rewrite app_comm_cons, upd_Znth_app2.\n  - rewrite app_comm_cons. f_equal.\n    rewrite Zlength_cons, Zlength_repeat by lia.\n    replace (i - Z.succ (i - 1)) with 0 by lia.\n    rewrite upd_Znth0. f_equal.\n  - rewrite Zlength_cons, !Zlength_repeat by lia.\n    replace (Z.succ (i - 1)) with i by lia.\n    pose proof (Zlength_nonneg (v1 :: l)). lia.\nQed.\n\nLemma body_create_heap: semax_body Vprog Gprog f_create_heap create_heap_spec.\nProof.\n  start_function.\n  forward_call (heap_type, gv).\n  Intros h. if_tac.\n  - subst h; forward_if False; [| first [exfalso; now apply H | inversion H ]].\n    unfold all_string_constants; Intros.\n    forward_call. \n    contradiction. \n  - Intros. forward_if True; [contradiction | forward; entailer! |]. Intros.\n    (* make \"data_at sh space_type v h \" in SEP *)\n    assert_PROP (isptr h) by entailer!. remember (Vundef, (Vundef, Vundef)) as vn.\n    assert_PROP (field_compatible heap_type [StructField _spaces] h) by entailer!.\n    replace_SEP 2 (data_at Ews heap_type (default_val heap_type) h) by entailer!.\n    change (default_val heap_type) with\n        (repeat (Vundef, (Vundef, Vundef)) (Z.to_nat 12)).\n    rewrite <- Heqvn. rewrite data_at_heaptype_eq; auto.\n    rewrite (split2_data_at_Tarray_space_type Ews 12 1);\n      [| lia | rewrite Zlength_repeat; lia].\n    rewrite sublist_repeat by lia. simpl repeat at 1.\n    rewrite space_array_1_eq. Intros. forward_call (Ews, h, Z.shiftl 1 16, gv, sh).\n    (* make succeed *)\n    + unfold MAX_SPACE_SIZE. compute; split; [discriminate | reflexivity].\n    + Intros p0. freeze [0;1;2;3;4;6] FR.\n      (* change back to \"data_at sh heap_type v h\" *)\n      rewrite <- space_array_1_eq. rewrite sublist_repeat by lia.\n      change (12 - 1) with 11 at 2.\n      gather_SEP (data_at Ews (tarray space_type 1) _ h)\n                 (data_at Ews (tarray space_type (12 - 1)) _ _).\n      remember (p0, (p0, offset_val (WORD_SIZE * Z.shiftl 1 16) p0)) as vh.\n      remember (vh :: repeat vn (Z.to_nat 11)) as vl.\n      replace [vh] with (sublist 0 1 vl). 2: {\n        subst vl; rewrite sublist_one; try lia.\n        - rewrite Znth_0_cons; auto.\n        - rewrite Zlength_cons, Zlength_repeat; lia.\n      } replace (repeat  vn (Z.to_nat 11)) with (sublist 1 12 vl) by\n          (rewrite Heqvl, sublist_1_cons, sublist_repeat; [reflexivity|lia..]).\n      rewrite <- split2_data_at_Tarray_space_type;\n        [| lia | rewrite Heqvl, Zlength_cons, Zlength_repeat; lia].\n      remember (if Archi.ptr64 then\n                  (Vlong (Int64.repr 0),\n                   (Vlong (Int64.repr 0), Vlong (Int64.repr 0))) else\n                  (Vint (Int.repr 0), (Vint (Int.repr 0), Vint (Int.repr 0)))) as v0.\n      (* change succeed *) subst vl. rewrite <- data_at_heaptype_eq; auto.\n      cbv [Archi.ptr64] in Heqv0.\n      forward_for_simple_bound\n        12\n        (EX i: Z,\n         PROP ( )\n         LOCAL (temp _h h; gvars gv)\n         SEP (data_at Ews heap_type\n                      (vh :: repeat v0 (Z.to_nat (i - 1)) ++\n                          repeat vn (Z.to_nat (12 - i))) h; FRZL FR))%assert.\n      * entailer!.\n      * Opaque Znth. forward. rewrite (repeat_cons (12 - i)) at 2 by lia.\n        rewrite Znth_repeat_app by apply (proj1 H2). rewrite Heqvn at 2.\n        rewrite (repeat_cons (12 - i)) by lia.\n        rewrite upd_Znth_repeat_app by apply (proj1 H2). forward.\n        rewrite Znth_repeat_app by apply (proj1 H2).\n        rewrite upd_Znth_repeat_app by apply (proj1 H2). forward.\n        rewrite Znth_repeat_app by apply (proj1 H2).\n        rewrite upd_Znth_repeat_app by apply (proj1 H2).\n        simpl fst.\n        replace (i + 1 - 1) with i by lia. try rewrite !Int.signed_repr by rep_lia.\n        rewrite <- Heqv0. replace (12 - i - 1) with (12 - (i + 1)) by lia.\n        change (v0 :: repeat vn (Z.to_nat (12 - (i + 1))))\n               with ([v0] ++ repeat vn (Z.to_nat (12 - (i + 1)))).\n        rewrite app_assoc.\n        replace (repeat v0 (Z.to_nat (i - 1)) ++ [v0]) with\n            (repeat v0 (Z.to_nat i)). 1: entailer!.\n        replace [v0] with (repeat v0 (Z.to_nat 1)) by (simpl; auto).\n        rewrite <- repeat_app. f_equal. rewrite <- Z2Nat.inj_add by lia.\n        f_equal. lia.\n      * replace (12 - 12) with 0 by lia. simpl repeat at 2.\n        rewrite app_nil_r. change 12 with MAX_SPACES at 2. thaw FR.\n        change (Z.shiftl 1 16) with NURSERY_SIZE in *.\n        assert (v0 = zero_triple) by (subst v0; unfold zero_triple; reflexivity).\n        rewrite H2. forward. Exists h p0. entailer!. Transparent Znth.\nQed.\n", "meta": {"author": "CertiGraph", "repo": "CertiGraph", "sha": "1be51414c139f8bc16b3e22f72989e454c37ce3c", "save_path": "github-repos/coq/CertiGraph-CertiGraph", "path": "github-repos/coq/CertiGraph-CertiGraph/CertiGraph-1be51414c139f8bc16b3e22f72989e454c37ce3c/CertiGC/verif_create_heap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21298526553731983}}
{"text": "Require Import Omega.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Time.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import MemoryRel.\n\nSet Implicit Arguments.\n\n\nInductive ftau T (step: forall (e:ThreadEvent.t) (e1 e2:T), Prop) (e:ThreadEvent.t) (e1 e2:T): Prop :=\n| ftau_intro\n    (TSTEP: step e e1 e2)\n    (EVENT: ThreadEvent.get_event e = None)\n.\nHint Constructors ftau.\n\nInductive with_pre {A} {E} (step: E -> A -> A -> Prop) bs : option (A*E) ->  A -> Prop :=\n| swp_base:\n  with_pre step bs None bs\n| swp_step\n    pre ms e es\n    (PSTEPS: with_pre step bs pre ms)\n    (PSTEP: step e ms es):\n  with_pre step bs (Some(ms,e)) es\n.\nHint Constructors with_pre.\n\nLemma with_pre_rtc_union\n      A E (step: E -> A -> A -> Prop) c1 c2 pre\n      (STEPS: with_pre step c1 pre c2):\n  rtc (union step) c1 c2.\nProof.\n  ginduction STEPS; s; i; subst; eauto.\n  i. etrans; eauto.\nQed.\n\nLemma rtc_union_with_pre\n      A E (step: E -> A -> A -> Prop) c1 c2\n      (STEPS: rtc (union step) c1 c2):\n  exists pre,\n  with_pre step c1 pre c2.\nProof.\n  apply Operators_Properties.clos_rt_rt1n_iff,\n        Operators_Properties.clos_rt_rtn1_iff in STEPS.\n  induction STEPS.\n  { exists None. eauto. }\n  des. inv H. exists (Some(y,e)). s. eauto.\nQed.\n\nLemma with_pre_rtc_tau\n      A (step: ThreadEvent.t -> A -> A -> Prop) c1 c2 pre\n      (STEPS: with_pre (ftau step) c1 pre c2):\n  rtc (tau step) c1 c2.\nProof.\n  ginduction STEPS; s; i; subst; eauto.\n  i. etrans; eauto.\n  econs 2; [|reflexivity]. inv PSTEP. eauto.\nQed.\n\nLemma rtc_tau_with_pre\n      A (step: ThreadEvent.t -> A -> A -> Prop) c1 c2\n      (STEPS: rtc (tau step) c1 c2):\n  exists pre,\n  with_pre (ftau step) c1 pre c2.\nProof.\n  apply Operators_Properties.clos_rt_rt1n_iff,\n        Operators_Properties.clos_rt_rtn1_iff in STEPS.\n  induction STEPS.\n  { exists None. eauto. }\n  des. inv H. exists (Some(y,e)). eauto.\nQed.\n\nLemma with_pre_implies\n      E A (step step': E -> A -> A -> Prop) c1 c2 pre\n      (IMPL: forall e c1 c2 (STEP: step e c1 c2), step' e c1 c2)\n      (STEPS: with_pre step c1 pre c2):\n  with_pre step' c1 pre c2.\nProof.\n  induction STEPS; eauto.\nQed.\n\nLemma with_pre_trans \n      A E (step: E -> A -> A -> Prop) c1 c2 c3 pre1 pre2\n      (STEPS1: with_pre step c1 pre1 c2)\n      (STEPS2: with_pre step c2 pre2 c3):\n  with_pre step c1 (option_app pre2 pre1) c3.\nProof.\n  ginduction STEPS2; s; i; des; subst; eauto.\nQed.\n\n\nLemma local_simul_fence\n      com prm prm' sc ordr ordw com' sc'\n      (LOCAL: Local.fence_step (Local.mk com prm) sc ordr ordw (Local.mk com' prm') sc'):\n  Local.fence_step (Local.mk com Memory.bot) sc ordr ordw (Local.mk com' Memory.bot) sc'.\nProof.\n  inv LOCAL. econs; eauto.\n  s. i. apply Memory.bot_nonsynch.\nQed.\n\n\nLemma local_simul_write\n      cmp com com' sc sc' mS mT mT' loc from to val relr relw ord kind prm prm'\n      (SUB: mem_sub cmp mS mT)\n      (DISJOINT: Memory.disjoint mS prm)\n      (WRITE: Local.write_step (Local.mk com prm) sc mT loc from to val relr relw ord (Local.mk com' prm') sc' mT' kind):\n  exists mS',\n  Local.write_step (Local.mk com Memory.bot) sc mS loc from to val relr relw ord (Local.mk com' Memory.bot) sc' mS' Memory.op_kind_add.\nProof.\n  set (relw' := relw).\n  assert (RELW_WF: View.opt_wf relw').\n  { inv WRITE. inv WRITE0. inv PROMISE.\n    - inv MEM. inv ADD. auto.\n    - inv MEM. inv SPLIT. auto.\n    - inv MEM. inv LOWER. auto.\n  }\n  inv WRITE.\n  hexploit (@Memory.add_exists Memory.bot loc from to val relw'); eauto.\n  { i. rewrite Memory.bot_get in *. congr. }\n  { eapply MemoryFacts.write_time_lt. eauto. }\n  i. des.\n  hexploit (@Memory.add_exists mS loc from to val relw'); eauto.\n  { i. destruct msg2.\n    inv WRITE0. inv PROMISE.\n    - exploit SUB; eauto. i. des.\n      inv MEM. inv ADD. eauto.\n    - exploit Memory.split_get0; try exact PROMISES; eauto. s. i. des.\n      inv DISJOINT. exploit DISJOINT0; eauto. i. des.\n      symmetry in x. eapply Interval.le_disjoint; eauto. econs; [refl|].\n      inv MEM. inv SPLIT. left. auto.\n    - exploit Memory.lower_get0; try exact PROMISES; eauto. s. i.\n      symmetry. eapply DISJOINT; eauto.\n  }\n  { eapply MemoryFacts.write_time_lt. eauto. }\n  i. des.\n  hexploit (@Memory.remove_exists mem2 loc from to val relw'); eauto.\n  { erewrite Memory.add_o; eauto. condtac; ss. des; congr. }\n  i. des.\n  replace mem1 with Memory.bot in H1; cycle 1.\n  { apply Memory.ext. i.\n    erewrite (@Memory.remove_o mem1); eauto. erewrite (@Memory.add_o mem2); eauto.\n    condtac; ss. des. subst. apply Memory.bot_get.\n  }\n  esplits. econs; eauto.\n  - econs; eauto. econs; eauto.\n    inv WRITE0. by inv PROMISE.\n  - s. i. splits; ss. apply Memory.bot_nonsynch.\nQed.\n\nInductive small_step (withprm: bool) (tid:Ident.t) (e:ThreadEvent.t) (c1:Configuration.t): forall (c2:Configuration.t), Prop :=\n| small_step_intro\n    lang pf st1 st2 lc1 ths2 lc2 sc2 memory2\n    (TID: IdentMap.find tid c1.(Configuration.threads) = Some (existT _ lang st1, lc1))\n    (STEP: Thread.step pf e (Thread.mk _ st1 lc1 c1.(Configuration.sc) c1.(Configuration.memory)) (Thread.mk _ st2 lc2 sc2 memory2))\n    (THS2: ths2 = IdentMap.add tid (existT _ _ st2, lc2) c1.(Configuration.threads))\n    (PFREE: orb withprm pf)\n  :\n  small_step withprm tid e c1 (Configuration.mk ths2 sc2 memory2)\n.\nHint Constructors small_step.\n\nInductive small_opt_step withprm tid e: forall (c1 c2:Configuration.t), Prop :=\n| small_opt_step_none\n    c\n    (EVENT: ThreadEvent.get_event e = None):\n    small_opt_step withprm tid e c c\n| small_opt_step_some\n    c1 c2\n    (STEP: small_step withprm tid e c1 c2):\n    small_opt_step withprm tid e c1 c2\n.\n\nDefinition small_step_evt withprm (tid:Ident.t) (c1 c2:Configuration.t) : Prop :=\n  union (small_step withprm tid) c1 c2.\nHint Unfold small_step_evt.\n\nDefinition small_step_all withprm (c1 c2:Configuration.t) : Prop :=\n  union (small_step_evt withprm) c1 c2.\nHint Unfold small_step_all.\n\nLemma small_step_evt_to_true\n      withprm tid cST1 cST2\n      (STEP: small_step_evt withprm tid cST1 cST2):\n  small_step_evt true tid cST1 cST2.\nProof.\n  destruct withprm; eauto.\n  inv STEP. inv USTEP.\n  econs. econs; eauto.\nQed.\n\nLemma small_step_future\n      e tid c1 c2 withprm\n      (WF1: Configuration.wf c1)\n      (STEP: small_step withprm e tid c1 c2):\n  <<WF2: Configuration.wf c2>> /\\\n  <<FUTURE: Memory.future c1.(Configuration.memory) c2.(Configuration.memory)>> /\\\n  <<SC_FUTURE: TimeMap.le  c1.(Configuration.sc) c2.(Configuration.sc)>>.\nProof.\n  inv WF1. inv WF. inv STEP. ss. clear PFREE.\n  exploit THREADS; ss; eauto. i.\n  exploit Thread.step_future; eauto.\n  s; i; des. splits; [|by eauto|by eauto]. econs; ss. econs.\n  - i. Configuration.simplify.\n    + exploit THREADS; try apply TH1; eauto. i. des.\n      exploit Thread.step_disjoint; eauto. s. i. des.\n      symmetry. auto.\n    + exploit THREADS; try apply TH2; eauto. i. des.\n      exploit Thread.step_disjoint; eauto. i. des.\n      auto.\n    + eapply DISJOINT; [|eauto|eauto]. auto.\n  - i. Configuration.simplify.\n    exploit THREADS; try apply TH; eauto. i.\n    exploit Thread.step_disjoint; eauto. s. i. des.\n    auto.\nQed.\n\nLemma rtc_small_step_future\n      c1 c2 withprm\n      (WF1: Configuration.wf c1)\n      (STEP: rtc (small_step_all withprm) c1 c2):\n  <<WF2: Configuration.wf c2>> /\\\n  <<FUTURE: Memory.future c1.(Configuration.memory) c2.(Configuration.memory)>> /\\\n  <<SC_FUTURE: TimeMap.le  c1.(Configuration.sc) c2.(Configuration.sc)>>.\nProof.\n  revert WF1. induction STEP; i.\n  - splits; eauto; reflexivity.\n  - destruct H. destruct USTEP. \n    exploit small_step_future; eauto. i; des.\n    exploit IHSTEP; eauto. i; des.\n    splits; eauto.\n    + etrans; eauto.\n    + etrans; eauto.\nQed.\n\nLemma thread_step_small_step\n      lang pf e tid threads\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      (TID: IdentMap.find tid threads = Some (existT _ lang st1, lc1))\n      (STEP: Thread.step pf e (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2)):\n  small_step true tid e\n             (Configuration.mk threads sc1 mem1)\n             (Configuration.mk (IdentMap.add tid (existT _ lang st2, lc2) threads) sc2 mem2).\nProof.\n  econs; eauto.\nQed.\n\nLemma thread_step_small_step_aux\n      lang pf e tid threads\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      (STEP: Thread.step pf e (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2)):\n  small_step true tid e\n             (Configuration.mk (IdentMap.add tid (existT _ lang st1, lc1) threads) sc1 mem1)\n             (Configuration.mk (IdentMap.add tid (existT _ lang st2, lc2) threads) sc2 mem2).\nProof.\n  exploit thread_step_small_step; eauto.\n  { eapply IdentMap.Facts.add_eq_o. eauto. }\n  rewrite (IdentMap.add_add_eq tid (existT _ lang st2, lc2)). eauto.\nQed.\n\nLemma rtc_thread_step_rtc_small_step_aux\n      lang tid threads\n      th1 th2\n      (TID: IdentMap.find tid threads = Some (existT _ lang th1.(Thread.state), th1.(Thread.local)))\n      (STEP: (rtc (@Thread.all_step lang)) th1 th2):\n  rtc (small_step_evt true tid)\n      (Configuration.mk threads th1.(Thread.sc) th1.(Thread.memory))\n      (Configuration.mk (IdentMap.add tid (existT _ lang th2.(Thread.state), th2.(Thread.local)) threads) th2.(Thread.sc) th2.(Thread.memory)).\nProof.\n  revert threads TID. induction STEP; i.\n  - apply rtc_refl. f_equal. apply IdentMap.eq_leibniz. ii.\n    rewrite IdentMap.Facts.add_o. condtac; auto. subst. auto.\n  - inv H. inv USTEP. destruct x, y. ss. econs 2.\n    + econs; eauto.\n    + etrans; [eapply IHSTEP|].\n      * apply IdentMap.Facts.add_eq_o. auto.\n      * apply rtc_refl. f_equal. apply IdentMap.eq_leibniz. ii.\n        rewrite ? IdentMap.Facts.add_o. condtac; auto.\nQed.\n\nLemma rtc_thread_step_rtc_small_step\n      lang tid threads\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      (TID: IdentMap.find tid threads = Some (existT _ lang st1, lc1))\n      (STEP: (rtc (@Thread.all_step lang)) (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2)):\n  rtc (small_step_evt true tid)\n      (Configuration.mk threads sc1 mem1)\n      (Configuration.mk (IdentMap.add tid (existT _ lang st2, lc2) threads) sc2 mem2).\nProof.\n  exploit rtc_thread_step_rtc_small_step_aux; eauto. auto.\nQed.\n\nLemma rtc_tau_thread_step_rtc_tau_small_step_aux\n      lang tid threads\n      th1 th2\n      (TID: IdentMap.find tid threads = Some (existT _ lang th1.(Thread.state), th1.(Thread.local)))\n      (STEP: (rtc (@Thread.tau_step lang)) th1 th2):\n  rtc (tau (small_step true tid))\n      (Configuration.mk threads th1.(Thread.sc) th1.(Thread.memory))\n      (Configuration.mk (IdentMap.add tid (existT _ lang th2.(Thread.state), th2.(Thread.local)) threads) th2.(Thread.sc) th2.(Thread.memory)).\nProof.\n  revert threads TID. induction STEP; i.\n  - apply rtc_refl. f_equal. apply IdentMap.eq_leibniz. ii.\n    rewrite IdentMap.Facts.add_o. condtac; auto. subst. auto.\n  - inv H. inv TSTEP. destruct x, y. ss. econs 2.\n    + econs; eauto.\n    + etrans; [eapply IHSTEP|].\n      * apply IdentMap.Facts.add_eq_o. auto.\n      * apply rtc_refl. f_equal. apply IdentMap.eq_leibniz. ii.\n        rewrite ? IdentMap.Facts.add_o. condtac; auto.\nQed.\n\nLemma rtc_tau_thread_step_rtc_tau_small_step\n      lang tid threads\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      (TID: IdentMap.find tid threads = Some (existT _ lang st1, lc1))\n      (STEP: (rtc (@Thread.tau_step lang)) (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2)):\n  rtc (tau (small_step true tid))\n      (Configuration.mk threads sc1 mem1)\n      (Configuration.mk (IdentMap.add tid (existT _ lang st2, lc2) threads) sc2 mem2).\nProof.\n  exploit rtc_tau_thread_step_rtc_tau_small_step_aux; eauto. auto.\nQed.\n\nLemma tau_pf_step_small_step\n      lang tid threads\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      (TID: IdentMap.find tid threads = Some (existT _ lang st1, lc1))\n      (STEP: tau (Thread.step true) (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2)):\n  small_step_evt false tid \n             (Configuration.mk threads sc1 mem1)\n             (Configuration.mk (IdentMap.add tid (existT _ lang st2, lc2) threads) sc2 mem2).\nProof.\n  inv STEP. econs. econs; eauto.\nQed.\n\nLemma tau_pf_step_small_step_aux\n      lang tid threads\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      (STEP: tau (Thread.step true) (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2)):\n  small_step_evt false tid\n             (Configuration.mk (IdentMap.add tid (existT _ lang st1, lc1) threads) sc1 mem1)\n             (Configuration.mk (IdentMap.add tid (existT _ lang st2, lc2) threads) sc2 mem2).\nProof.\n  exploit tau_pf_step_small_step; eauto.\n  { eapply IdentMap.Facts.add_eq_o. eauto. }\n  rewrite (IdentMap.add_add_eq tid (existT _ lang st2, lc2)). eauto.\nQed.\n\nLemma rtc_tau_pf_step_rtc_small_step_aux\n      lang tid threads\n      th1 th2\n      (TID: IdentMap.find tid threads = Some (existT _ lang th1.(Thread.state), th1.(Thread.local)))\n      (STEP: (rtc (tau (@Thread.step lang true))) th1 th2):\n  rtc (small_step_evt false tid)\n      (Configuration.mk threads th1.(Thread.sc) th1.(Thread.memory))\n      (Configuration.mk (IdentMap.add tid (existT _ lang th2.(Thread.state), th2.(Thread.local)) threads) th2.(Thread.sc) th2.(Thread.memory)).\nProof.\n  revert threads TID. induction STEP; i.\n  - apply rtc_refl. f_equal. apply IdentMap.eq_leibniz. ii.\n    rewrite IdentMap.Facts.add_o. condtac; auto. subst. auto.\n  - inv H. destruct x, y. ss. econs 2.\n    + econs; eauto.\n    + etrans; [eapply IHSTEP|].\n      * apply IdentMap.Facts.add_eq_o. auto.\n      * apply rtc_refl. f_equal. apply IdentMap.eq_leibniz. ii.\n        rewrite ? IdentMap.Facts.add_o. condtac; auto.\nQed.\n\nLemma rtc_tau_pf_step_rtc_small_step\n      lang tid threads\n      st1 lc1 sc1 mem1\n      st2 lc2 sc2 mem2\n      (TID: IdentMap.find tid threads = Some (existT _ lang st1, lc1))\n      (STEP: (rtc (tau (@Thread.step lang true))) (Thread.mk lang st1 lc1 sc1 mem1) (Thread.mk lang st2 lc2 sc2 mem2)):\n  rtc (small_step_evt false tid)\n      (Configuration.mk threads sc1 mem1)\n      (Configuration.mk (IdentMap.add tid (existT _ lang st2, lc2) threads) sc2 mem2).\nProof.\n  exploit rtc_tau_pf_step_rtc_small_step_aux; eauto. \n  eauto.\nQed.\n\nLemma step_small_steps\n      e tid c1 c3\n      (STEP: Configuration.step e tid c1 c3)\n      (WF1: Configuration.wf c1)\n      (CONSISTENT1: Configuration.consistent c1):\n  exists c2 te,\n    <<STEPS: rtc (tau (small_step true tid)) c1 c2>> /\\\n    <<STEP: small_step true tid te c2 c3>> /\\\n    <<EVENT: e = ThreadEvent.get_event te>> /\\\n    <<WF2: Configuration.wf c2>> /\\\n    <<WF3: Configuration.wf c3>> /\\\n    <<CONSISTENT3: Configuration.consistent c3>>.\nProof.\n  exploit Configuration.step_future; eauto. i. des.\n  inv STEP. destruct c1, e2. ss.\n  exploit rtc_tau_thread_step_rtc_tau_small_step; eauto. i. des.\n  exploit thread_step_small_step_aux; eauto. i. des.\n  esplits; eauto.\n  eapply rtc_small_step_future; try exact WF1.\n  eapply rtc_implies, x0. i. inv H. eauto.\nQed.\n\nLemma small_step_find\n      tid1 tid2 c1 c2 e withprm\n      (STEP: small_step withprm tid1 e c1 c2)\n      (TID: tid1 <> tid2):\n  IdentMap.find tid2 c1.(Configuration.threads) = IdentMap.find tid2 c2.(Configuration.threads).\nProof.\n  inv STEP. s.\n  rewrite IdentMap.gso; eauto.\nQed.\n\nLemma rtc_small_step_find\n      tid1 tid2 c1 c2 withprm\n      (STEP: rtc (small_step_evt withprm tid1) c1 c2)\n      (TID: tid1 <> tid2):\n  IdentMap.find tid2 c1.(Configuration.threads) = IdentMap.find tid2 c2.(Configuration.threads).\nProof.\n  induction STEP; auto. \n  inv H. rewrite <-IHSTEP.\n  eauto using small_step_find.\nQed.\n\nLemma thread_step_tview_le\n     lang pf e (t1 t2: @Thread.t lang)\n     (STEP: Thread.step pf e t1 t2)\n     (LOCALWF: Local.wf t1.(Thread.local) t1.(Thread.memory))\n     (SCWF: Memory.closed_timemap t1.(Thread.sc) t1.(Thread.memory))\n     (MEMWF: Memory.closed t1.(Thread.memory)):\n  TView.le t1.(Thread.local).(Local.tview) t2.(Thread.local).(Local.tview).\nProof.\n  eapply Thread.step_future; eauto.\nQed.\n\nLemma rtc_small_step_tview_le\n     c1 c2 tid lst1 lst2 lc1 lc2 withprm\n     (STEPS: rtc (small_step_evt withprm tid) c1 c2)\n     (THREAD1: IdentMap.find tid c1.(Configuration.threads) = Some (lst1, lc1))\n     (THREAD2: IdentMap.find tid c2.(Configuration.threads) = Some (lst2, lc2))\n     (WF: Configuration.wf c1):\n  TView.le lc1.(Local.tview) lc2.(Local.tview).\nProof.\n  ginduction STEPS; i.\n  - rewrite THREAD1 in THREAD2. depdes THREAD2. reflexivity.\n  - inv H. exploit small_step_future; eauto.\n    intros [WF2 _].\n    inv WF.\n    destruct USTEP. rewrite THREAD1 in TID. depdes TID.\n    etrans; [apply (thread_step_tview_le STEP)|]; eauto.\n    eapply WF0; eauto.\n    eapply IHSTEPS; eauto.\n    s. subst. rewrite IdentMap.gss. eauto.\nQed.\n\nLemma small_step_write_lt\n      tid c c1 e lst lc loc from ts val rel ord withprm\n      (STEP: small_step withprm tid e c c1)\n      (EVENT: ThreadEvent.is_writing e = Some (loc, from, ts, val, rel, ord))\n      (THREAD: IdentMap.find tid (Configuration.threads c) = Some (lst, lc)):\n  Time.lt (lc.(Local.tview).(TView.cur).(View.rlx) loc) ts.\nProof.\n  inv STEP. rewrite THREAD in TID. inv TID.\n  inv STEP0; inv STEP; ss. inv LOCAL; ss; inv EVENT.\n  - inv LOCAL0. apply WRITABLE.\n  - eapply TimeFacts.le_lt_lt; cycle 1.\n    + inv LOCAL2. inv WRITABLE. apply TS.\n    + inv LOCAL1. s. do 2 (etrans; [|apply TimeMap.join_l]). refl.\nQed.\n\nLemma small_step_promise_decr\n      tid tid' loc ts e c1 c2 lst2 lc2 from2 msg2\n      (STEPT: small_step false tid e c1 c2)\n      (FIND2: IdentMap.find tid' c2.(Configuration.threads) = Some (lst2,lc2))\n      (PROMISES: Memory.get loc ts lc2.(Local.promises) = Some (from2, msg2)):\n  exists lst1 lc1 from1 msg1,\n  <<FIND1: IdentMap.find tid' c1.(Configuration.threads) = Some (lst1,lc1)>> /\\\n  <<PROMISES: Memory.get loc ts lc1.(Local.promises) = Some (from1, msg1)>>.\nProof.\n  inv STEPT; ss.\n  revert FIND2. rewrite IdentMap.gsspec. condtac.\n  - i. inv FIND2.\n    inv STEP; inv STEP0;\n      (try inv LOCAL);\n      (try inv LOCAL0);\n      (try by esplits; eauto).\n    + ss. apply promise_pf_inv in PFREE; eauto. des. subst. inv PROMISE.\n      destruct msg2. exploit Memory.op_get_inv; eauto.\n      { econs 3. eauto. }\n      i. des.\n      * subst. esplits; eauto. eapply Memory.lower_get0. eauto.\n      * esplits; eauto.\n    + inv WRITE.\n      revert PROMISES. erewrite Memory.remove_o; eauto. condtac; ss.\n      guardH o. i. destruct msg2.\n      exploit MemoryFacts.MemoryFacts.promise_get_promises_inv_diff; eauto.\n      { ii. inv H. unguardH o. des; congr. }\n      i. des. esplits; eauto.\n    + inv LOCAL1.\n      inv LOCAL2. inv WRITE.\n      revert PROMISES. erewrite Memory.remove_o; eauto. condtac; ss.\n      guardH o. i. destruct msg2.\n      exploit MemoryFacts.MemoryFacts.promise_get_promises_inv_diff; eauto.\n      { ii. inv H. unguardH o. des; congr. }\n      i. des. esplits; eauto.\n  - i. esplits; eauto.\nQed.\n\nCorollary small_step_promise_decr_bot\n      tid tid' e c1 c2 lst1 lc1 lst2 lc2\n      (STEPT: small_step false tid e c1 c2)\n      (FIND1: IdentMap.find tid' c1.(Configuration.threads) = Some (lst1,lc1))\n      (FIND2: IdentMap.find tid' c2.(Configuration.threads) = Some (lst2,lc2))\n      (PROMISES: lc1.(Local.promises) = Memory.bot):\n  lc2.(Local.promises) = Memory.bot.\nProof.\n  apply Memory.ext. i. setoid_rewrite Cell.bot_get.\n  destruct (Memory.get loc ts (Local.promises lc2)) as [[from msg]|] eqn: EQ; eauto.\n  exploit small_step_promise_decr; eauto.\n  i; des. rewrite FIND0 in FIND1. inv FIND1.\n  rewrite PROMISES in *. \n  setoid_rewrite Cell.bot_get in PROMISES0. done.\nQed.\n\nLemma small_steps_promise_decr\n      tid' loc ts c1 c2 lst2 lc2 from2 msg2\n      (STEPT: rtc (small_step_all false) c1 c2)\n      (FIND2: IdentMap.find tid' c2.(Configuration.threads) = Some (lst2,lc2))\n      (PROMISES: Memory.get loc ts lc2.(Local.promises) = Some (from2, msg2)):\n  exists lst1 lc1 from1 msg1,\n  <<FIND1: IdentMap.find tid' c1.(Configuration.threads) = Some (lst1,lc1)>> /\\\n  <<PROMISES: Memory.get loc ts lc1.(Local.promises) = Some (from1, msg1)>>.\nProof.\n  move STEPT at top. revert_until STEPT.\n  apply rtc_reverse in STEPT. induction STEPT.\n  - i. esplits; eauto.\n  - inv H. inv USTEP. i. exploit small_step_promise_decr; eauto. i. des.\n    exploit IHSTEPT; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-coq", "sha": "bff53239c51681ea653745cebf3b30ddd38f97ba", "save_path": "github-repos/coq/snu-sf-promising-coq", "path": "github-repos/coq/snu-sf-promising-coq/promising-coq-bff53239c51681ea653745cebf3b30ddd38f97ba/src/drf/SmallStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.21298312716208087}}
{"text": "Require Import Bool String List.\nRequire Import Lib.CommonTactics Lib.ilist Lib.Word.\nRequire Import Lib.Struct Lib.FMap Lib.StringEq Lib.Indexer.\nRequire Import Kami.Syntax Kami.Semantics Kami.RefinementFacts Kami.Renaming Kami.Wf.\nRequire Import Kami.Renaming Kami.Specialize Kami.Inline Kami.InlineFacts Kami.Decomposition.\nRequire Import Kami.Tactics Kami.Notations Kami.PrimBram.\nRequire Import Ex.MemTypes Ex.SC Ex.NativeFifo Ex.MemAsync Ex.ProcFetch Ex.ProcFInl.\nRequire Import Eqdep ProofIrrelevance.\n\nSet Implicit Arguments.\n\nSection Invariants.\n  Variables addrSize iaddrSize instBytes dataBytes rfIdx: nat.\n\n  Variables (fetch: AbsFetch addrSize iaddrSize instBytes dataBytes).\n\n  Variable (f2dElt: Kind).\n  Variable (f2dPack:\n              forall ty,\n                Expr ty (SyntaxKind (Data instBytes)) -> (* rawInst *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* curPc *)\n                Expr ty (SyntaxKind (Pc addrSize)) -> (* nextPc *)\n                Expr ty (SyntaxKind Bool) -> (* epoch *)\n                Expr ty (SyntaxKind f2dElt)).\n  Variables\n    (f2dRawInst: forall ty, fullType ty (SyntaxKind f2dElt) ->\n                            Expr ty (SyntaxKind (Data instBytes)))\n    (f2dCurPc: forall ty, fullType ty (SyntaxKind f2dElt) ->\n                          Expr ty (SyntaxKind (Pc addrSize)))\n    (f2dNextPc: forall ty, fullType ty (SyntaxKind f2dElt) ->\n                           Expr ty (SyntaxKind (Pc addrSize)))\n    (f2dEpoch: forall ty, fullType ty (SyntaxKind f2dElt) ->\n                          Expr ty (SyntaxKind Bool)).\n\n  Context {indexSize tagSize: nat}.\n  Variables (getIndex: forall ty, fullType ty (SyntaxKind (Bit addrSize)) ->\n                                  Expr ty (SyntaxKind (Bit indexSize)))\n            (getTag: forall ty, fullType ty (SyntaxKind (Bit addrSize)) ->\n                                Expr ty (SyntaxKind (Bit tagSize))).\n\n  Variables (pcInit : ConstT (Pc addrSize)).\n  \n  Definition fetchICacheInl :=\n    projT1 (fetchICacheInl fetch f2dPack getIndex getTag pcInit).\n\n  Record fetchICache_inv (o: RegsT) : Prop :=\n    { pcv : fullType type (SyntaxKind (Pc addrSize));\n      Hpcv : M.find \"pc\"%string o = Some (existT _ _ pcv);\n      pinitv : fullType type (SyntaxKind Bool);\n      Hpinitv : M.find \"pinit\"%string o = Some (existT _ _ pinitv);\n      pinitRqv : fullType type (SyntaxKind Bool);\n      HpinitRqv : M.find \"pinitRq\"%string o = Some (existT _ _ pinitRqv);\n      pinitRqOfsv : fullType type (SyntaxKind (Bit iaddrSize));\n      HpinitRqOfsv : M.find \"pinitRqOfs\"%string o = Some (existT _ _ pinitRqOfsv);\n      pinitRsOfsv : fullType type (SyntaxKind (Bit iaddrSize));\n      HpinitRsOfsv : M.find \"pinitRsOfs\"%string o = Some (existT _ _ pinitRsOfsv);\n      fepochv : fullType type (SyntaxKind Bool);\n      Hfepochv : M.find \"fEpoch\"%string o = Some (existT _ _ fepochv);\n      pcuv : fullType type (SyntaxKind Bool);\n      Hpcuv : M.find \"pcUpdated\"%string o = Some (existT _ _ pcuv);\n            \n      bramv : fullType type (SyntaxKind (Vector (Data instBytes) iaddrSize));\n      Hbramv : M.find \"pgm\"--\"bram\" o = Some (existT _ _ bramv);\n      breadv : fullType type (bramReadValK (Data instBytes) type);\n      Hbreadv : M.find \"pgm\"--\"readVal\" o = Some (existT _ _ breadv);\n\n      Hinv0 : pinitv = false -> breadv = None;\n      Hinv1 : pinitv = true -> pcuv = false ->\n              match breadv with\n              | Some val => val = bramv (evalExpr (toIAddr _ pcv))\n              | None => True\n              end\n    }.\n\n  Ltac fetchICache_inv_old :=\n    repeat match goal with\n           | [H: fetchICache_inv _ |- _] => destruct H\n           end;\n    kinv_red.\n\n  Ltac fetchICache_inv_new :=\n    econstructor; (* let's prove that the invariant holds for the next state *)\n    try (findReify; (reflexivity || eassumption); fail);\n    kinv_red; (* unfolding invariant definitions *)\n    try eassumption; intros; try reflexivity.\n    (* intuition kinv_simpl; intuition idtac. *)\n\n  Ltac fetchICache_inv_tac := fetchICache_inv_old; fetchICache_inv_new.\n\n  Lemma fetchICache_inv_ok':\n    forall init n ll,\n      init = initRegs (getRegInits fetchICacheInl) ->\n      Multistep fetchICacheInl init n ll ->\n      fetchICache_inv n.\n  Proof. (* SKIP_PROOF_ON\n    induction 2.\n\n    - fetchICache_inv_old.\n      unfold getRegInits, fetchICacheInl, ProcFInl.fetchICacheInl, projT1.\n      fetchICache_inv_new.\n\n    - kinvert.\n      + mred.\n      + mred.\n      + kinv_dest_custom fetchICache_inv_tac.\n      + kinv_dest_custom fetchICache_inv_tac.\n      + kinv_dest_custom fetchICache_inv_tac.\n      + kinv_dest_custom fetchICache_inv_tac.\n      + kinv_dest_custom fetchICache_inv_tac.\n      + kinv_dest_custom fetchICache_inv_tac.\n      + kinv_dest_custom fetchICache_inv_tac.\n      + kinv_dest_custom fetchICache_inv_tac.\n        END_SKIP_PROOF_ON *) apply cheat.\n  Qed.\n\n  Lemma fetchICache_inv_ok:\n    forall o,\n      reachable o fetchICacheInl ->\n      fetchICache_inv o.\n  Proof.\n    intros; inv H; inv H0.\n    eapply fetchICache_inv_ok'; eauto.\n  Qed.\n\nEnd Invariants.\n\n", "meta": {"author": "mit-plv", "repo": "kami", "sha": "cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0", "save_path": "github-repos/coq/mit-plv-kami", "path": "github-repos/coq/mit-plv-kami/kami-cb9e8bf8ed7faf79de6af828d6c587ffbf2b6ca0/Kami/Ex/ProcFInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.21298311792470495}}
{"text": "(* This code is copyrighted by its authors; it is distributed under  *)\n(* the terms of the LGPL license (see LICENSE and description files) *)\n\n(****************************************************************************)\n(*                                                                          *)\n(*                                                                          *)\n(*                Solange Coupet-Grimal & Line Jakubiec-Jamet               *)\n(*                                                                          *)\n(*                                                                          *)\n(*             Laboratoire d'Informatique Fondamentale de Marseille         *)\n(*                   CMI et Faculté des Sciences de Luminy                  *)\n(*                                                                          *)\n(*           e-mail:{Solange.Coupet,Line.Jakubiec}@lif.univ-mrs.fr          *)\n(*                                                                          *)\n(*                                                                          *)\n(*                            Developped in Coq v6                          *)\n(*                            Ported to Coq v7                              *)\n(*                            Translated to Coq v8                          *)\n(*                                                                          *)\n(*                             July 12nd 2005                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                         Arbiter4_Proof_lemmas.v                          *)\n(****************************************************************************)\n \n\nRequire Export Lemmas_Comb_Behaviour.\nRequire Export Lemmas_Struct.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n  \nDefinition d_Map_List4_pdt_Grant (l : d_list (d_list bool 4) 4)\n  (g : d_list (bool * bool) 4) :=\n  d_map (List2_pdt (A:=bool))\n    (d_map2 Grant_for_Out l\n       (List4 (List2 (fst (Fst_of_l4 g)) (snd (Fst_of_l4 g)))\n          (List2 (fst (Scd_of_l4 g)) (snd (Scd_of_l4 g)))\n          (List2 (fst (Thd_of_l4 g)) (snd (Thd_of_l4 g)))\n          (List2 (fst (Fth_of_l4 g)) (snd (Fth_of_l4 g))))).\n\n\n\nLemma ltReq_false_G1 :\n forall (l : d_list (d_list bool 4) 4) (g1 g1' g2 g2' g3 g3' g4 g4' : bool),\n Ackor (Fst_of_l4 l) = false ->\n Fst_of_l4\n   (d_Map_List4_pdt_Grant l (List4 (g1, g1') (g2, g2') (g3, g3') (g4, g4'))) =\n (g1, g1').\nintros.\nunfold d_Map_List4_pdt_Grant in |- *.\nunfold Fst_of_l4 in |- *; simpl in |- *.\nunfold Grant_for_Out in |- *; unfold SuccessfulInput in |- *;\n unfold RequestsToArbitrate in |- *.\nreplace (Fst_of_l4 (d_Head l)) with false.\nreplace (Scd_of_l4 (d_Head l)) with false.\nreplace (Thd_of_l4 (d_Head l)) with false.\nreplace (Fth_of_l4 (d_Head l)) with false; simpl in |- *.\nreplace (Convert_port_list2 (Convert_list2_port (List2 g1 g1'))) with\n (List2 g1 g1').\nauto.\nunfold Convert_list2_port in |- *; unfold Convert_port_list2 in |- *;\n simpl in |- *.\nelim g1; elim g1'; simpl in |- *; auto.\napply sym_equal; apply Ackor_false_fth; auto.\napply sym_equal; apply Ackor_false_thd; auto.\napply sym_equal; apply Ackor_false_scd; auto.\napply sym_equal; apply Ackor_false_fst; auto.\nQed.\n\n\n\nLemma ltReq_false_G2 :\n forall (l : d_list (d_list bool 4) 4) (g1 g1' g2 g2' g3 g3' g4 g4' : bool),\n Ackor (Scd_of_l4 l) = false ->\n Scd_of_l4\n   (d_Map_List4_pdt_Grant l (List4 (g1, g1') (g2, g2') (g3, g3') (g4, g4'))) =\n (g2, g2').\nintros.\nunfold d_Map_List4_pdt_Grant in |- *.\nunfold Scd_of_l4 in |- *; simpl in |- *.\nunfold Grant_for_Out in |- *; unfold SuccessfulInput in |- *;\n unfold RequestsToArbitrate in |- *.\nreplace (Fst_of_l4 (d_Head (d_tl l))) with false.\nreplace (Scd_of_l4 (d_Head (d_tl l))) with false.\nreplace (Thd_of_l4 (d_Head (d_tl l))) with false.\nreplace (Fth_of_l4 (d_Head (d_tl l))) with false; simpl in |- *.\nreplace (Convert_port_list2 (Convert_list2_port (List2 g2 g2'))) with\n (List2 g2 g2').\nauto.\nunfold Convert_list2_port in |- *; unfold Convert_port_list2 in |- *;\n simpl in |- *.\nelim g2; elim g2'; simpl in |- *; auto.\napply sym_equal; apply Ackor_false_fth; auto.\napply sym_equal; apply Ackor_false_thd; auto.\napply sym_equal; apply Ackor_false_scd; auto.\napply sym_equal; apply Ackor_false_fst; auto.\nQed.\n\n\n\nLemma ltReq_false_G3 :\n forall (l : d_list (d_list bool 4) 4) (g1 g1' g2 g2' g3 g3' g4 g4' : bool),\n Ackor (Thd_of_l4 l) = false ->\n Thd_of_l4\n   (d_Map_List4_pdt_Grant l (List4 (g1, g1') (g2, g2') (g3, g3') (g4, g4'))) =\n (g3, g3').\nintros.\nunfold d_Map_List4_pdt_Grant in |- *.\nunfold Thd_of_l4 in |- *; simpl in |- *.\nunfold Grant_for_Out in |- *; unfold SuccessfulInput in |- *;\n unfold RequestsToArbitrate in |- *.\ngeneralize H; clear H.\nelim (non_empty l).\nintros x t; elim t; clear t; intros t H'.\nrewrite H'; simpl in |- *; intro H.\nreplace (Fst_of_l4 (d_Head (d_tl t))) with false.\nreplace (Scd_of_l4 (d_Head (d_tl t))) with false.\nreplace (Thd_of_l4 (d_Head (d_tl t))) with false.\nreplace (Fth_of_l4 (d_Head (d_tl t))) with false; simpl in |- *.\nreplace (Convert_port_list2 (Convert_list2_port (List2 g3 g3'))) with\n (List2 g3 g3').\nauto.\nunfold Convert_list2_port in |- *; unfold Convert_port_list2 in |- *;\n simpl in |- *.\nelim g3; elim g3'; simpl in |- *; auto.\napply sym_equal; apply Ackor_false_fth; auto.\napply sym_equal; apply Ackor_false_thd; auto.\napply sym_equal; apply Ackor_false_scd; auto.\napply sym_equal; apply Ackor_false_fst; auto.\nQed. \n\n\nLemma ltReq_false_G4 :\n forall (l : d_list (d_list bool 4) 4) (g1 g1' g2 g2' g3 g3' g4 g4' : bool),\n Ackor (Fth_of_l4 l) = false ->\n Fth_of_l4\n   (d_Map_List4_pdt_Grant l (List4 (g1, g1') (g2, g2') (g3, g3') (g4, g4'))) =\n (g4, g4').\nintros.\nunfold d_Map_List4_pdt_Grant in |- *.\nunfold Fth_of_l4 in |- *; simpl in |- *.\nunfold Grant_for_Out in |- *; unfold SuccessfulInput in |- *;\n unfold RequestsToArbitrate in |- *.\ngeneralize H; clear H.\nelim (non_empty l).\nintros x t; elim t; clear t; intros t H'.\nelim (non_empty t).\nintros x' t'; elim t'; clear t'; intros t' H''.\nrewrite H'; rewrite H''; simpl in |- *; intro H.\nreplace (Fst_of_l4 (d_Head (d_tl t'))) with false.\nreplace (Scd_of_l4 (d_Head (d_tl t'))) with false.\nreplace (Thd_of_l4 (d_Head (d_tl t'))) with false.\nreplace (Fth_of_l4 (d_Head (d_tl t'))) with false; simpl in |- *.\nreplace (Convert_port_list2 (Convert_list2_port (List2 g4 g4'))) with\n (List2 g4 g4').\nauto.\nunfold Convert_list2_port in |- *; unfold Convert_port_list2 in |- *;\n simpl in |- *.\nelim g4; elim g4'; simpl in |- *; auto.\napply sym_equal; apply Ackor_false_fth; auto.\napply sym_equal; apply Ackor_false_thd; auto.\napply sym_equal; apply Ackor_false_scd; auto.\napply sym_equal; apply Ackor_false_fst; auto.\nQed. \n", "meta": {"author": "coq-contribs", "repo": "fairisle", "sha": "e36087a6b7e52ef3c6dcfdeba1298e8fde1260a0", "save_path": "github-repos/coq/coq-contribs-fairisle", "path": "github-repos/coq/coq-contribs-fairisle/fairisle-e36087a6b7e52ef3c6dcfdeba1298e8fde1260a0/Fairisle/PROOFS/Arbiter4_Proof_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21290269256000527}}
{"text": "(* type_remove *)\nRequire Import Semantics.\nRequire Import Sumbool_dec.\nRequire Import FMapFacts.\nRequire Import OptionMap2.\nRequire Import SemanticsDefinitions.\nRequire Import AccessRights.\nRequire Import AccessRightSets.\nRequire Import RefSets.\nRequire Import References.\nRequire Import Indices.\nRequire Import Capabilities.\nRequire Import Objects.\nRequire Import SystemState.\nRequire Import SemanticsDefinitions.\n\nModule SimpleSemantics (Ref:ReferenceType) (RefS: RefSetType Ref) (Cap:CapabilityType Ref) (Ind:IndexType) (Obj:ObjectType Ref Cap Ind) (Sys:SystemStateType Ref Cap Ind Obj) (SemDefns: SemanticsDefinitionsType Ref Cap Ind Obj Sys) : SemanticsType Ref RefS Cap Ind Obj Sys SemDefns.\n  Import SemDefns.\n  Export SemDefns.\n\n(*  Module RS_Mod := RefSets.Make Ref.\n  Import RS_Mod. *)\n  Import RefS.\n\n\n\n  (* in the following, I'm abusing notation.  \n     We use t as an object, not an index to find the target defining an object.\n     We use c as a capability, not an index in t naming the capability.\n     Likewise with cl for capability lists. *)\n  (* (read a t s): a reads data from t.  *)\n  (* abstract *)\n  Definition do_read (a:Ref.t) (t:Ind.t) (s:Sys.t) : Sys.t := s.\n\n  Theorem read_spec: forall a t s, Sys.eq (do_read a t s) s.\n  Proof.\n    intros.\n    unfold do_read.\n    apply Sys.eq_refl.\n  Qed.\n\n  (* (write a t s): a writes data to t. *)\n  (* abstract *)\n  Definition do_write (a:Ref.t) (t:Ind.t) (s:Sys.t) : Sys.t := s.\n  \n  Theorem write_spec: forall a t s, Sys.eq (do_write a t s) s.\n  Proof.\n    intros.\n    unfold do_write.\n    apply Sys.eq_refl.\n  Qed.\n\n  (* (fetch a t c i s): a fetches c from t and places it at index i. *)\n  (* abstract *)\n  Definition do_fetch (a:Ref.t) (t:Ind.t) (c:Ind.t) (i:Ind.t) (s:Sys.t) : Sys.t :=\n    if (true_bool_of_sumbool (SemDefns.fetch_preReq_dec a t s))\n      then if (true_bool_of_sumbool (SemDefns.option_hasRight_dec (SC.getCap t a s) rd))\n        then (option_map1 (fun tgt => SC.copyCap c tgt i a s) s (SemDefns.option_target (SC.getCap t a s)))\n        else (option_map1 (fun tgt => SC.weakCopyCap c tgt i a s) s (SemDefns.option_target (SC.getCap t a s)))\n      else s.\n\n  Theorem fetch_invalid: forall a t c i s, \n    ~ SemDefns.fetch_preReq a t s -> Sys.eq (do_fetch a t c i s) s.\n  Proof.\n    intros.\n    unfold do_fetch.\n    destruct (SemDefns.fetch_preReq_dec a t s); [contradiction | simpl].\n    apply Sys.eq_refl.\n  Qed.\n  \n  Theorem fetch_read: forall a t c i s,\n    SemDefns.fetch_preReq a t s -> SemDefns.option_hasRight (SC.getCap t a s) rd -> \n    Sys.eq (do_fetch a t c i s)\n         (option_map1 (fun tgt => SC.copyCap c tgt i a s) s (SemDefns.option_target (SC.getCap t a s))).\n  Proof.\n    intros.\n    unfold do_fetch.\n    destruct (SemDefns.fetch_preReq_dec a t s); try contradiction; simpl.\n    destruct (SemDefns.option_hasRight_dec (SC.getCap t a s) rd); try contradiction; simpl.\n    apply Sys.eq_refl.\n  Qed.\n\n  Theorem fetch_weak: forall a t c i s,\n    SemDefns.fetch_preReq a t s -> ~ SemDefns.option_hasRight (SC.getCap t a s) rd -> \n    SemDefns.option_hasRight (SC.getCap t a s) wk  ->\n    Sys.eq (do_fetch a t c i s)\n    (option_map1 (fun tgt => SC.weakCopyCap c tgt i a s) s (SemDefns.option_target (SC.getCap t a s))).\n  Proof.\n    intros.\n    unfold do_fetch.\n    destruct (SemDefns.fetch_preReq_dec a t s); try contradiction; simpl.\n    destruct (SemDefns.option_hasRight_dec (SC.getCap t a s) rd); try contradiction; simpl.\n    apply Sys.eq_refl.\n  Qed.\n\n  Ltac prove_valid_invalid do_X X_preReq_dec a t s :=\n    intros; unfold do_X; destruct (X_preReq_dec a t s); try contradiction; simpl; apply Sys.eq_refl.\n\n  (* (store a t c i s): a stores c to t at index i. *)\n  (* abstract *)\n  Definition do_store (a:Ref.t) (t:Ind.t) (c:Ind.t) (i:Ind.t) (s:Sys.t) : Sys.t :=\n    if (true_bool_of_sumbool (SemDefns.store_preReq_dec a t s))\n      then (option_map1 (fun tgt => SC.copyCap c a i tgt s) s (SemDefns.option_target (SC.getCap t a s)))\n      else s.\n\n  Theorem store_invalid : forall a t c i s, ~ SemDefns.store_preReq a t s -> Sys.eq (do_store a t c i s) s.\n  Proof.\n    prove_valid_invalid do_store SemDefns.store_preReq_dec a t s.\n  Qed.\n  \n  Theorem  store_valid: forall a t c i s, SemDefns.store_preReq a t s -> \n    Sys.eq (do_store a t c i s) \n    (option_map1 (fun tgt => SC.copyCap c a i tgt s) s (SemDefns.option_target (SC.getCap t a s))).\n  Proof.\n    prove_valid_invalid do_store SemDefns.store_preReq_dec a t s.\n  Qed.\n\n  (* (revoke a t c s): a removes capability c from t. *)\n  (* abstract *)\n  Definition do_revoke (a:Ref.t) (t:Ind.t) (c:Ind.t) (s:Sys.t) : Sys.t :=\n    if (true_bool_of_sumbool (SemDefns.revoke_preReq_dec a t s))\n      then (option_map1 (fun tgt => SC.rmCap c tgt s) s (SemDefns.option_target (SC.getCap t a s)))\n      else s.\n\n  Theorem revoke_invalid : forall a t c s, ~ SemDefns.revoke_preReq a t s -> Sys.eq (do_revoke a t c s) s.\n  Proof.\n    prove_valid_invalid do_revoke SemDefns.revoke_preReq_dec a t s.\n  Qed.\n\n  Theorem revoke_valid : forall a t c s, SemDefns.revoke_preReq a t s -> \n    Sys.eq (do_revoke a t c s) \n    (option_map1 (fun tgt => SC.rmCap c tgt s) s (SemDefns.option_target (SC.getCap t a s))).\n  Proof.\n    prove_valid_invalid do_revoke SemDefns.revoke_preReq_dec a t s.\n  Qed.\n\n  (* (send a t cil op_i s): a sends a message to t containing capabilities. \n     The cil is a capability -> index list, and is a list of pairs.\n     Each capability c is stored at index i in t. *)\n  (* abstract *)\n  Definition do_send (a:Ref.t) (t:Ind.t) (cil:list (Ind.t * Ind.t)) (op_i:option Ind.t) (s:Sys.t) : Sys.t :=\n    if (true_bool_of_sumbool (SemDefns.send_preReq_dec a t s))\n      then (option_map1 (fun tgt => SC.copyCapList a tgt cil \n      (option_map1\n             (fun i => \n               SC.addCap i \n               (Cap.mkCap a (ARSet.singleton tx)) \n               tgt \n               s)\n             s \n             op_i)) s (SemDefns.option_target (SC.getCap t a s)))\n      else s.\n\n  Theorem send_invalid : forall a t cil op_i s, ~ SemDefns.send_preReq a t s -> Sys.eq (do_send a t cil op_i s) s.\n  Proof.\n    prove_valid_invalid do_send SemDefns.send_preReq_dec a t s.\n  Qed.\n\n  Theorem send_valid : forall a t cil op_i s, SemDefns.send_preReq a t s -> \n    Sys.eq (do_send a t cil op_i s) \n    (option_map1 \n      (fun tgt => \n        SC.copyCapList a tgt cil \n           (option_map1 \n             (fun i => \n               SC.addCap i \n               (Cap.mkCap a (ARSet.singleton tx)) \n               tgt \n               s)\n             s \n             op_i)) \n      s \n      (SemDefns.option_target (SC.getCap t a s))).\n  Proof.\n    prove_valid_invalid do_send SemDefns.send_preReq_dec a t s.\n  Qed.\n\n  (* (destroy a t s): a destroys t. *)\n  (* abstract *)\n  Definition do_destroy (a:Ref.t) (t:Ind.t) (s:Sys.t) : Sys.t :=\n      if (true_bool_of_sumbool (SemDefns.destroy_preReq_dec a t s))\n      then (option_map1 (fun tgt => SC.set_dead tgt s) s (SemDefns.option_target (SC.getCap t a s)))\n      else s.\n\n  Theorem destroy_invalid: forall a t s, ~ SemDefns.destroy_preReq a t s -> Sys.eq (do_destroy a t s) s.\n  Proof.\n    prove_valid_invalid do_destroy SemDefns.destroy_preReq_dec a t s.\n  Qed.\n\n  Theorem destroy_valid: forall a t s, SemDefns.destroy_preReq a t s -> \n    Sys.eq (do_destroy a t s)\n    (option_map1 (fun tgt => SC.set_dead tgt s) s (SemDefns.option_target (SC.getCap t a s))).\n  Proof.\n    prove_valid_invalid do_destroy SemDefns.destroy_preReq_dec a t s.\n  Qed.\n\n  (* (allocate a n i cil s): a allocates child n,\n     handing it capabilities via cil, and places the child's cap at index i. *)\n  (* abstract *)\n  Definition do_allocate (a:Ref.t) (n:Ref.t) (i:Ind.t) (cil:list (Ind.t * Ind.t)) (s:Sys.t) : Sys.t :=\n    if (true_bool_of_sumbool (SemDefns.allocate_preReq_dec a n s))\n      then\n    (SC.addCap i \n      (Cap.mkCap n \n        (ARSet.add rd \n          (ARSet.add wr \n            (ARSet.add wk\n              (ARSet.singleton tx))))) a \n    (SC.copyCapList a n cil \n      (SC.set_alive n (SC.updateObj n (Obj.MapS.empty _) \n        (SC.rmCapsByTarget n s)))))\n    else s.\n  Theorem allocate_invalid: forall a n i cil s, ~ SemDefns.allocate_preReq a n s -> Sys.eq (do_allocate a n i cil s) s.\n  Proof.\n    prove_valid_invalid do_allocate SemDefns.allocate_preReq_dec a n s.\n  Qed.\n\n  Theorem allocate_valid: forall a n i cil s, SemDefns.allocate_preReq a n s ->\n    Sys.eq (do_allocate a n i cil s)\n    (SC.addCap i \n      (Cap.mkCap n all_rights) a \n    (SC.copyCapList a n cil \n      (SC.set_alive n (SC.updateObj n (Obj.MapS.empty _) \n        (SC.rmCapsByTarget n s))))).\n  Proof.\n    prove_valid_invalid do_allocate SemDefns.allocate_preReq_dec a n s.\n  Qed.\n\n\n  Inductive operation : Type :=\n  | read: Ref.t -> Ind.t  -> operation\n  | write: Ref.t -> Ind.t -> operation\n  | fetch: Ref.t -> Ind.t -> Ind.t -> Ind.t -> operation\n  | store: Ref.t -> Ind.t -> Ind.t -> Ind.t -> operation\n  | revoke: Ref.t -> Ind.t -> Ind.t -> operation\n  | send: Ref.t -> Ind.t -> list (Ind.t * Ind.t) -> option Ind.t -> operation\n  | allocate: Ref.t -> Ref.t -> Ind.t -> list (Ind.t * Ind.t) -> operation\n  | destroy: Ref.t -> Ind.t -> operation.\n  \n  Inductive do_op_spec : operation -> (Sys.t -> Sys.t) -> Prop :=\n    | do_op_spec_read: forall a t, do_op_spec (read a t) (do_read a t)\n    | do_op_spec_write: forall a t, do_op_spec (write a t) (do_write a t)\n    | do_op_spec_fetch: forall a t c i, do_op_spec (fetch a t c i) (do_fetch a t c i)\n    | do_op_spec_store: forall a t c i, do_op_spec (store a t c i) (do_store a t c i)\n    | do_op_spec_revoke: forall a t c, do_op_spec (revoke a t c) (do_revoke a t c)\n    | do_op_spec_send: forall a t cil op_i, do_op_spec (send a t cil op_i) (do_send a t cil op_i)\n    | do_op_spec_allocate: forall a t i cil, do_op_spec (allocate a t i cil) (do_allocate a t i cil)\n    | do_op_spec_destroy: forall a t, do_op_spec (destroy a t) (do_destroy a t).\n\n  Hint Constructors do_op_spec.\n\n  Definition do_op op s:=\n    match op with\n      | read a t => do_read a t s\n      | write a t => do_write a t s\n      | fetch a t c i => do_fetch a t c i s\n      | store a t c i => do_store a t c i s\n      | revoke a t c => do_revoke a t c s\n      | send a t cil op_i => do_send a t cil op_i s\n      | allocate a n i cil => do_allocate a n i cil s\n      | destroy a t => do_destroy a t s\n    end.\n\n  Theorem do_op_spec_do_op: forall op,\n    do_op_spec op (do_op op).\n  Proof.\n    intros.\n    destruct op; unfold do_op; constructor.\n  Qed.\n\n  Definition add_option_target s a t r_set := (option_map1 (fun tgt => RefSet.add tgt r_set) r_set (SemDefns.option_target (SC.getCap t a s))).\n  \n  Inductive read_from_def s: operation -> RefSet.t -> Prop :=\n  | read_from_read_valid : forall a t x, \n    SemDefns.read_preReq a t s ->\n    RefSet.Equal (add_option_target s a t (RefSet.singleton a)) x ->\n    read_from_def s (read a t) x\n  | read_from_read_invalid : forall a t x, \n    ~ SemDefns.read_preReq a t s ->\n    RefSet.Empty x ->\n    read_from_def s (read a t) x\n\n  | read_from_write_valid: forall a t x,\n    SemDefns.write_preReq a t s ->\n    RefSet.Equal (RefSet.singleton a) x ->\n    read_from_def s (write a t) x\n  | read_from_write_invalid: forall a t x,\n    ~ SemDefns.write_preReq a t s ->\n    RefSet.Empty x ->\n    read_from_def s (write a t) x\n\n  | read_from_fetch_valid : forall a t c i x, \n    SemDefns.fetch_preReq a t s ->\n    RefSet.Equal (add_option_target s a t (RefSet.singleton a)) x ->\n    read_from_def s (fetch a t c i) x\n  | read_from_fetch_invalid : forall a t c i x, \n    ~ SemDefns.fetch_preReq a t s ->\n    RefSet.Empty x ->\n    read_from_def s (fetch a t c i) x\n\n  | read_from_store_valid: forall a t c i x,\n    SemDefns.store_preReq a t s ->\n    RefSet.Equal (RefSet.singleton a) x ->\n    read_from_def s (store a t c i) x\n  | read_from_store_invalid: forall a t c i x,\n    ~ SemDefns.store_preReq a t s ->\n    RefSet.Empty x ->\n    read_from_def s (store a t c i) x\n\n  | read_from_revoke_valid: forall a t c x, \n    SemDefns.revoke_preReq a t s ->\n    RefSet.Equal (RefSet.singleton a) x ->\n    read_from_def s (revoke a t c) x\n  | read_from_revoke_invalid: forall a t c x, \n    ~ SemDefns.revoke_preReq a t s ->\n    RefSet.Empty x ->\n    read_from_def s (revoke a t c) x\n\n  | read_from_send_valid: forall a t cil op_i x, \n    SemDefns.send_preReq a t s ->\n    RefSet.Equal (RefSet.singleton a) x ->\n    read_from_def s (send a t cil op_i) x\n  | read_from_send_invalid: forall a t cil op_i x, \n    ~ SemDefns.send_preReq a t s ->\n    RefSet.Empty x ->\n    read_from_def s (send a t cil op_i) x\n\n  | read_from_allocate_valid: forall a n i cil x, \n    SemDefns.allocate_preReq a n s ->\n    RefSet.Equal (RefSet.singleton a) x ->\n    read_from_def s (allocate a n i cil) x\n  | read_from_allocate_invalid: forall a n i cil x, \n    ~ SemDefns.allocate_preReq a n s ->\n    RefSet.Empty x ->\n    read_from_def s (allocate a n i cil) x\n\n  | read_from_destroy_valid: forall a t x, \n    SemDefns.destroy_preReq a t s ->\n    RefSet.Equal (RefSet.singleton a) x ->\n    read_from_def s (destroy a t) x\n  | read_from_destroy_invalid: forall a t x, \n    ~ SemDefns.destroy_preReq a t s ->\n    RefSet.Empty x ->\n    read_from_def s (destroy a t) x.\n\n  Inductive wrote_to_def s: operation -> RefSet.t -> Prop :=\n  | wrote_to_read_valid : forall a t x, \n    SemDefns.read_preReq a t s ->\n    RefSet.Equal (RefSet.singleton a) x -> \n    wrote_to_def s (read a t) x\n  | wrote_to_read_invalid : forall a t x, \n    ~ SemDefns.read_preReq a t s ->\n    RefSet.Empty x ->\n    wrote_to_def s (read a t) x\n\n  | wrote_to_write_valid: forall a t x,\n    SemDefns.write_preReq a t s ->\n    RefSet.Equal (add_option_target s a t RefSet.empty) x ->\n    wrote_to_def s (write a t) x\n  | wrote_to_write_invalid: forall a t x,\n    ~ SemDefns.write_preReq a t s ->\n    RefSet.Empty x ->\n    wrote_to_def s (write a t) x\n\n  | wrote_to_fetch_valid : forall a t c i x, \n    SemDefns.fetch_preReq a t s ->\n    RefSet.Equal (RefSet.singleton a) x -> \n    wrote_to_def s (fetch a t c i) x\n  | wrote_to_fetch_invalid : forall a t c i x, \n    ~ SemDefns.fetch_preReq a t s ->\n    RefSet.Empty x ->\n    wrote_to_def s (fetch a t c i) x\n\n  | wrote_to_store_valid: forall a t c i x, \n    SemDefns.store_preReq a t s ->\n    RefSet.Equal (add_option_target s a t RefSet.empty) x -> \n    wrote_to_def s (store a t c i) x\n  | wrote_to_store_invalid: forall a t c i x, \n    ~ SemDefns.store_preReq a t s ->\n    RefSet.Empty x ->\n    wrote_to_def s (store a t c i) x\n\n  | wrote_to_revoke_valid: forall a t c x, \n    SemDefns.revoke_preReq a t s ->\n    RefSet.Equal (add_option_target s a t RefSet.empty) x -> \n    wrote_to_def s (revoke a t c) x\n  | wrote_to_revoke_invalid: forall a t c x, \n    ~ SemDefns.revoke_preReq a t s ->\n    RefSet.Empty x ->\n    wrote_to_def s (revoke a t c) x\n\n  | wrote_to_send_valid: forall a t cil op_i x,\n    SemDefns.send_preReq a t s ->\n    RefSet.Equal (add_option_target s a t RefSet.empty) x -> \n    wrote_to_def s (send a t cil op_i) x\n  | wrote_to_send_invalid: forall a t cil op_i x,\n    ~ SemDefns.send_preReq a t s ->\n    RefSet.Empty x ->\n    wrote_to_def s (send a t cil op_i) x\n\n  | wrote_to_allocate_valid: forall a n i cil x, \n    SemDefns.allocate_preReq a n s ->\n    RefSet.Equal (RefSet.add n (RefSet.singleton a)) x -> \n    wrote_to_def s (allocate a n i cil) x\n  | wrote_to_allocate_invalid: forall a n i cil x, \n    ~ SemDefns.allocate_preReq a n s ->\n    RefSet.Empty x ->\n    wrote_to_def s (allocate a n i cil) x\n\n  | wrote_to_destroy_valid: forall a t x, \n    SemDefns.destroy_preReq a t s ->\n    RefSet.Equal (RefSet.singleton a) x -> \n    wrote_to_def s (destroy a t) x\n  | wrote_to_destroy_invalid: forall a t x,\n    ~ SemDefns.destroy_preReq a t s -> \n    RefSet.Empty x ->\n    wrote_to_def s (destroy a t) x.\n\n  (*abstract*)\n  Definition read_from s op :=\n    match op with\n      | read a t => if (SemDefns.read_preReq_dec a t s) \n        then add_option_target s a t (RefSet.singleton a)\n        else RefSet.empty\n      | write a t => if (SemDefns.write_preReq_dec a t s)\n        then RefSet.singleton a\n        else RefSet.empty\n      | fetch a t c i => if (SemDefns.fetch_preReq_dec a t s) \n        then add_option_target s a t (RefSet.singleton a)\n        else RefSet.empty\n      | store a t c i => if SemDefns.store_preReq_dec a t s\n        then RefSet.singleton a\n        else RefSet.empty\n      | revoke a t c => if SemDefns.revoke_preReq_dec a t s\n        then RefSet.singleton a\n        else RefSet.empty\n      | send a t cil opt_i => if SemDefns.send_preReq_dec a t s\n        then RefSet.singleton a\n        else RefSet.empty\n      | allocate a n i cil => if SemDefns.allocate_preReq_dec a n s\n        then RefSet.singleton a\n        else RefSet.empty\n      | destroy a t => if SemDefns.destroy_preReq_dec a t s\n        then RefSet.singleton a\n        else RefSet.empty\n    end.\n\n\n    Ltac solve_apply_16_constructors remainder :=\n      solve [constructor 1; remainder\n        | constructor 2; remainder\n        | constructor 3; remainder\n        | constructor 4; remainder\n        | constructor 5; remainder\n        | constructor 6; remainder\n        | constructor 7; remainder\n        | constructor 8; remainder\n        | constructor 9; remainder\n        | constructor 10; remainder\n        | constructor 11; remainder\n        | constructor 12; remainder\n        | constructor 13; remainder\n        | constructor 14; remainder\n        | constructor 15; remainder\n        | constructor 16; remainder\n      ].\n\n  Theorem read_from_spec : forall s op ob_list,\n    read_from_def s op ob_list <-> \n    RefSet.Equal (read_from s op) ob_list.\n  Proof.\n\n    (* these will be deleted by typeify2.pl as they are in a proof body *)\n    Ltac reduce_dec dec :=\n      let Hcase := fresh \"Hcase\" in\n        case dec; intros Hcase; try contradiction.\n    Ltac solve_reduce_tail H0 := solve[ auto| eapply RefSetProps.empty_is_empty_1 in H0; \n              eapply RefSet.eq_sym; auto].\n    Ltac reduce_and_solve dec H0 := reduce_dec dec; solve_reduce_tail H0.\n    Ltac empty_solution := auto; apply RefSetProps.empty_is_empty_2; apply RefSet.eq_sym; auto.\n    Ltac reduce_and_solve2 dec := reduce_dec dec; [intros H; solve_apply_16_constructors auto\n      | intros H; solve_apply_16_constructors empty_solution].\n\n\n    intros; split; intros.\n    destruct H; unfold read_from;\n      try solve [reduce_and_solve (send_preReq_dec a t s) H0\n      | reduce_and_solve (read_preReq_dec a t s) H0\n      | reduce_and_solve (write_preReq_dec a t s) H0\n      | reduce_and_solve (fetch_preReq_dec a t s) H0\n      | reduce_and_solve (store_preReq_dec a t s) H0\n      | reduce_and_solve (revoke_preReq_dec a t s) H0\n      | reduce_and_solve (allocate_preReq_dec a n s) H0\n      | reduce_and_solve (destroy_preReq_dec a t s) H0\n      ].\n\n    revert H; unfold read_from in *; destruct op;\n\n      try solve \n        [ reduce_and_solve2 (send_preReq_dec t t0 s)\n          | reduce_and_solve2 (read_preReq_dec t t0 s)\n          | reduce_and_solve2 (write_preReq_dec t t0 s)\n          | reduce_and_solve2 (fetch_preReq_dec t t0 s)\n          | reduce_and_solve2 (store_preReq_dec t t0 s)\n          | reduce_and_solve2 (revoke_preReq_dec t t0 s)\n          | reduce_and_solve2 (allocate_preReq_dec t t0 s)\n          | reduce_and_solve2 (destroy_preReq_dec t t0 s)\n        ].\n\n  Qed.\n\n  (*abstract*)\n  Definition wrote_to s op :=\n    match op with\n      | read a t =>  if (SemDefns.read_preReq_dec a t s) \n        then RefSet.singleton a\n        else RefSet.empty\n      | write a t =>  if (SemDefns.write_preReq_dec a t s) \n        then add_option_target s a t RefSet.empty\n        else RefSet.empty\n      | fetch a t c i =>  if (SemDefns.fetch_preReq_dec a t s) \n        then RefSet.singleton a\n        else RefSet.empty\n      | store a t c i => if (SemDefns.store_preReq_dec a t s) \n        then add_option_target s a t RefSet.empty\n        else RefSet.empty\n      | revoke a t c => if (SemDefns.revoke_preReq_dec a t s) \n        then add_option_target s a t RefSet.empty\n        else RefSet.empty\n      | send a t cil opt_i => if (SemDefns.send_preReq_dec a t s) \n        then add_option_target s a t RefSet.empty\n        else RefSet.empty\n      | allocate a n i cil => if (SemDefns.allocate_preReq_dec a n s) \n        then RefSet.add n (RefSet.singleton a)\n        else RefSet.empty\n      | destroy a t => if (SemDefns.destroy_preReq_dec a t s) \n        then RefSet.singleton a\n        else RefSet.empty\n    end.\n\n  Theorem wrote_to_spec : forall s op ob_list,\n    wrote_to_def s op ob_list <-> \n    RefSet.Equal (wrote_to s op) ob_list.\n  Proof.\n    intros; split; intros.\n\n    destruct H; unfold wrote_to;\n      try solve [reduce_and_solve (send_preReq_dec a t s) H0\n      | reduce_and_solve (read_preReq_dec a t s) H0\n      | reduce_and_solve (write_preReq_dec a t s) H0\n      | reduce_and_solve (fetch_preReq_dec a t s) H0\n      | reduce_and_solve (store_preReq_dec a t s) H0\n      | reduce_and_solve (revoke_preReq_dec a t s) H0\n      | reduce_and_solve (allocate_preReq_dec a n s) H0\n      | reduce_and_solve (destroy_preReq_dec a t s) H0\n      ].\n    \n    revert H; unfold wrote_to in *; destruct op;\n      try solve \n        [ reduce_and_solve2 (send_preReq_dec t t0 s)\n          | reduce_and_solve2 (read_preReq_dec t t0 s)\n          | reduce_and_solve2 (write_preReq_dec t t0 s)\n          | reduce_and_solve2 (fetch_preReq_dec t t0 s)\n          | reduce_and_solve2 (store_preReq_dec t t0 s)\n          | reduce_and_solve2 (revoke_preReq_dec t t0 s)\n          | reduce_and_solve2 (allocate_preReq_dec t t0 s)\n          | reduce_and_solve2 (destroy_preReq_dec t t0 s)\n        ].\n\nQed.\n\nEnd SimpleSemantics.\n\n\n", "meta": {"author": "doerrie", "repo": "confinement-proof", "sha": "db7bfb3522990d0820de64f13baa97b67e694c44", "save_path": "github-repos/coq/doerrie-confinement-proof", "path": "github-repos/coq/doerrie-confinement-proof/confinement-proof-db7bfb3522990d0820de64f13baa97b67e694c44/SemanticsImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.38121957328625583, "lm_q1q2_score": 0.2128451785347292}}
{"text": "Require Import erasure.   \nRequire Import progStepImpliesSpec. \nRequire Import progStepWF. \n\n(*Definitions*)\nCoInductive ParDiverge : pHeap -> pPool -> Prop :=\n|divergeStep : forall T1 T2 T2' H H',\n                 pstep H T1 T2 (pOK H' T1 T2') -> \n                 ParDiverge H' (pUnion T1 T2') -> ParDiverge H (pUnion T1 T2)\n.\n\nCoInductive ParDiverge' : pHeap -> pPool -> Prop :=\n|divergeStep' : forall H H' T T',\n                 pstepPlus H T H' T' -> ParDiverge' H' T' -> ParDiverge' H T. \n\nTheorem ParDivergeEq : forall H T, ParDiverge H T <-> ParDiverge' H T. \nProof. \n  intros. split; intros. \n  {genDeps{T; H}. cofix. intros. inv H0. econstructor. econstructor. eauto. \n   constructor. eapply ParDivergeEq; eassumption. }\n  {genDeps{T; H}. cofix CH. intros. inv H0. inv H2. inv H4. \n   {econstructor. eassumption. eapply CH. eauto. }\n   {assert(ParDiverge' H'0 (pUnion T t0)). econstructor. econstructor. \n    eassumption. eassumption. assumption. econstructor. eassumption. \n    eapply CH. rewrite <- H2. eauto. }\n  }\nQed. \n\nTheorem eActTerm : forall x, exists M, actionTerm x M. \nProof.\n  intros. destruct x; repeat econstructor. \nQed. \n\nLtac actTermTac x := assert(exists M, actionTerm x M) by apply eActTerm; invertHyp. \n\nTheorem getLastApp : forall (T:Type) a c (b:T),\n                       last(a++[b]) c = b.\nProof.\n  induction a; intros. \n  {simpl. auto. }\n  {simpl. destruct (a0++[b]) eqn:eq. \n   {invertListNeq. }\n   {rewrite <- eq. eauto. }\n  }\nQed. \n\nTheorem unspecLastActPool : forall tid s a s2 M' M, \n                         actionTerm a M' ->\n                         unspecPool(tSingleton(tid,unlocked(s++[a]),s2,M)) = \n                         tSingleton(tid,unlocked nil,s2,M'). \nProof.\n  induction s; intros. \n  {simpl. inv H; auto. }\n  {simpl. destruct (s++[a0])eqn:eq. \n   {invertListNeq. }\n   {rewrite <- eq. rewrite getLastApp. inv H; auto. }\n  }\nQed. \n\nTheorem actionTrmConsSame'' : forall a M' N s1 s2 tid,\n                             actionTerm a M' -> \n                             unspecPool(tSingleton(tid,unlocked s1,s2,M')) = \n                             unspecPool(tSingleton(tid,aCons a (unlocked s1),s2,N)). \nProof.\n  induction s1; intros. \n  {simpl. inv H; auto.  }\n  {simpl. destruct s1. auto. erewrite getLastNonEmpty; eauto. }\nQed. \n\nTheorem actionTrmConsSame' : forall a M' N s1 s2 tid,\n                             actionTerm a M' -> \n                             unspecPool(tSingleton(tid,s1,s2,M')) = \n                             unspecPool(tSingleton(tid,aCons a s1,s2,N)). \nProof.\n  intros. destruct s1; auto. apply actionTrmConsSame''. auto. \nQed. \n\nTheorem unspecEmpty : forall tid s1 s2 M, \n                unspecPool(tSingleton(tid,locked s1,s2,M)) = (Empty_set thread).\nProof.\n  intros. simpl. auto. \nQed. \n\nLtac sswfHelper := eapply spec_multi_trans;[eassumption|econstructor].\n\nHint Constructors actionTerm spec_multistep. \n\nTheorem specStepWF : forall H T H' t t',\n                       wellFormed H (tUnion T t) -> spec_step H T t H' T t' ->\n                       wellFormed H' (tUnion T t'). \nProof.\n  intros. inv H1. \n  {inv H0. econstructor. rewrite unspecUnionComm in *. destruct s1. \n   {simpl in *. sswfHelper; auto. eapply SBasicStep; eauto. }\n   {destructLast l. inv H3. invertHyp. actTermTac x. erewrite unspecLastActPool in *; eauto. \n    sswfHelper; eauto. eapply SBasicStep; eauto. }\n   {simpl in *. sswfHelper; eauto. eapply SBasicStep; eauto. }\n  }\n  {unfoldTac. inv H0. econstructor. rewrite coupleUnion. repeat rewrite unspecUnionComm in *.\n   destruct b. \n   {simpl in *. sswfHelper. eapply SFork; eauto. constructor. }\n   {erewrite <- actionTrmConsSame'. rewrite unspecEmpty. unfoldTac. rewrite union_empty_r. \n    sswfHelper. eapply SFork; eauto. constructor. auto. }\n   {simpl in *.  sswfHelper. eapply SFork; eauto. constructor. }\n  }\n  {inv H0. econstructor. rewrite unspecUnionComm in *. destruct b. \n   {simpl in *. erewrite unspecHeapRBRead; eauto. sswfHelper. eapply SGet; eauto. constructor. }\n   {erewrite unspecHeapRBRead; eauto. erewrite <- actionTrmConsSame'; auto. sswfHelper. \n    eapply SGet; eauto. constructor. }\n   {simpl in *. erewrite unspecHeapRBRead; eauto. sswfHelper. eapply SGet; eauto. constructor. }\n  }\n  {inv H0. constructor. rewrite unspecHeapAddWrite; auto. rewrite unspecUnionComm in *.\n   destruct b. \n   {simpl in *. sswfHelper. eapply SPut; eauto. constructor. }\n   {erewrite <- actionTrmConsSame'; eauto. sswfHelper. eapply SPut; eauto. constructor. }\n   {simpl in *. sswfHelper. eapply SPut; eauto. constructor. }\n  }\n  {inv H0. constructor. rewrite unspecHeapExtend. rewrite unspecUnionComm in *. destruct b. \n   {sswfHelper. eapply SNew; eauto. constructor. }\n   {erewrite <- actionTrmConsSame'; eauto. sswfHelper. eapply SNew; eauto. constructor. }\n   {sswfHelper. eapply SNew; eauto. constructor. }\n  }\n  {inv H0. constructor. unfoldTac. rewrite coupleUnion. repeat rewrite unspecUnionComm in *. \n   rewrite unspecEmpty. unfoldTac. rewrite union_empty_r. destruct b. \n   {sswfHelper. eapply SSpec; eauto. constructor. }\n   {erewrite <- actionTrmConsSame'; eauto. sswfHelper. eapply SSpec; eauto. constructor. }\n   {sswfHelper. eapply SSpec; eauto. constructor. }\n  }\nQed. \n\nTheorem specMultiWF : forall H T H' T', wellFormed H T -> spec_multistep H T H' T' ->\n                                        wellFormed H' T'. \nProof.\n  intros. induction H1. \n  {auto. }\n  {eapply specStepWF in H; eauto. }\nQed. \n\nTheorem pstepDiffUnused : forall H H' T T' t t',\n                            pstep H T t (pOK H' T t') ->\n                            pstep H T' t (pOK H' T' t'). \nProof.\n  intros. Hint Constructors pstep. inv H0; eauto. \nQed. \n\nTheorem pstepSingleton : forall H T1 T2 H' T2', \n                           pstep H T1 T2 (pOK H' T1 T2') -> exists t, T2 = Single ptrm t. \nProof.\n  intros. inv H0; eauto. \nQed.\n \nCoInductive SpecDiverge : sHeap -> pool-> Prop :=\n|specDiverge : forall T1 T2 T2' H H' H'' T,\n                 spec_multistep H T H' (tUnion T1 T2) -> \n                 prog_step H' T1 T2 (OK H'' T1 T2') -> \n                 SpecDiverge H'' (tUnion T1 T2') -> SpecDiverge H T.\n\nTheorem SpecDivergeParDiverge' : forall H T,\n                wellFormed H T -> \n                SpecDiverge H T -> ParDiverge' (eraseHeap H) (erasePool T). \nProof.\n  cofix CH. intros. inv H1. copy H3. apply specMultiWF in H3; auto. \n  eapply spec_multistepErase in H1. invertHyp. rewrite H6. rewrite H2.\n  rewrite eraseUnionComm in *. copy H4. apply prog_specImpliesNonSpec in H4; auto. \n  invertHyp.  apply prog_stepWF in H1; auto. rewrite eraseUnionComm in *. \n  econstructor. eassumption. eapply CH. eauto. eauto. \nQed. \n\nTheorem SpecDivergeParDiverge : forall H T,\n              wellFormed H T -> \n              SpecDiverge H T -> ParDiverge (eraseHeap H) (erasePool T). \nProof.\n  intros. apply SpecDivergeParDiverge' in H1. rewrite ParDivergeEq. auto. auto. \nQed. \n\n\n\n\n\n\n\n\n", "meta": {"author": "lexxx320", "repo": "PersonalProjects", "sha": "bc83fb250467b013d9db9fe535ff7bd314632d4c", "save_path": "github-repos/coq/lexxx320-PersonalProjects", "path": "github-repos/coq/lexxx320-PersonalProjects/PersonalProjects-bc83fb250467b013d9db9fe535ff7bd314632d4c/newest/SpecDivergeParDiverge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.21284517460963137}}
{"text": "From iris.base_logic.lib Require Export invariants.\nFrom iris.proofmode Require Import tactics.\nSet Default Proof Using \"Type\".\n\nDefinition vs `{invG Σ} (E1 E2 : coPset) (P Q : iProp Σ) : iProp Σ :=\n  (□ (P -∗ |={E1,E2}=> Q))%I.\nArguments vs {_ _} _ _ _%I _%I.\n\nInstance: Params (@vs) 4.\nNotation \"P ={ E1 , E2 }=> Q\" := (vs E1 E2 P Q)\n  (at level 99, E1,E2 at level 50, Q at level 200,\n   format \"P  ={ E1 , E2 }=>  Q\") : uPred_scope.\nNotation \"P ={ E }=> Q\" := (P ={E,E}=> Q)%I\n  (at level 99, E at level 50, Q at level 200,\n   format \"P  ={ E }=>  Q\") : uPred_scope.\n\nNotation \"P ={ E1 , E2 }=> Q\" := (P ={E1,E2}=> Q)%I\n  (at level 99, E1,E2 at level 50, Q at level 200,\n   format \"P  ={ E1 , E2 }=>  Q\") : stdpp_scope.\nNotation \"P ={ E }=> Q\" := (P ={E}=> Q)%I\n  (at level 99, E at level 50, Q at level 200,\n   format \"P  ={ E }=>  Q\") : stdpp_scope.\n\nSection vs.\nContext `{invG Σ}.\nImplicit Types P Q R : iProp Σ.\nImplicit Types N : namespace.\n\nGlobal Instance vs_ne E1 E2 : NonExpansive2 (vs E1 E2).\nProof. solve_proper. Qed.\n\nGlobal Instance vs_proper E1 E2 : Proper ((≡) ==> (≡) ==> (≡)) (vs E1 E2).\nProof. apply ne_proper_2, _. Qed.\n\nLemma vs_mono E1 E2 P P' Q Q' :\n  (P ⊢ P') → (Q' ⊢ Q) → (P' ={E1,E2}=> Q') ⊢ P ={E1,E2}=> Q.\nProof. by intros HP HQ; rewrite /vs -HP HQ. Qed.\n\nGlobal Instance vs_mono' E1 E2 : Proper (flip (⊢) ==> (⊢) ==> (⊢)) (vs E1 E2).\nProof. solve_proper. Qed.\n\nLemma vs_false_elim E1 E2 P : False ={E1,E2}=> P.\nProof. iIntros \"!# []\". Qed.\nLemma vs_timeless E P : Timeless P → ▷ P ={E}=> P.\nProof. by iIntros (?) \"!# > ?\". Qed.\n\nLemma vs_transitive E1 E2 E3 P Q R :\n  (P ={E1,E2}=> Q) ∧ (Q ={E2,E3}=> R) ⊢ P ={E1,E3}=> R.\nProof.\n  iIntros \"#[HvsP HvsQ] !# HP\".\n  iMod (\"HvsP\" with \"HP\") as \"HQ\". by iApply \"HvsQ\".\nQed.\n\nLemma vs_reflexive E P : P ={E}=> P.\nProof. by iIntros \"!# HP\". Qed.\n\nLemma vs_impl E P Q : □ (P → Q) ⊢ P ={E}=> Q.\nProof. iIntros \"#HPQ !# HP\". by iApply \"HPQ\". Qed.\n\nLemma vs_frame_l E1 E2 P Q R : (P ={E1,E2}=> Q) ⊢ R ∗ P ={E1,E2}=> R ∗ Q.\nProof. iIntros \"#Hvs !# [$ HP]\". by iApply \"Hvs\". Qed.\n\nLemma vs_frame_r E1 E2 P Q R : (P ={E1,E2}=> Q) ⊢ P ∗ R ={E1,E2}=> Q ∗ R.\nProof. iIntros \"#Hvs !# [HP $]\". by iApply \"Hvs\". Qed.\n\nLemma vs_mask_frame_r E1 E2 Ef P Q :\n  E1 ## Ef → (P ={E1,E2}=> Q) ⊢ P ={E1 ∪ Ef,E2 ∪ Ef}=> Q.\nProof.\n  iIntros (?) \"#Hvs !# HP\". iApply fupd_mask_frame_r; auto. by iApply \"Hvs\".\nQed.\n\nLemma vs_inv N E P Q R :\n  ↑N ⊆ E → inv N R ∗ (▷ R ∗ P ={E∖↑N}=> ▷ R ∗ Q) ⊢ P ={E}=> Q.\nProof.\n  iIntros (?) \"#[? Hvs] !# HP\". iInv N as \"HR\" \"Hclose\".\n  iMod (\"Hvs\" with \"[HR HP]\") as \"[? $]\"; first by iFrame.\n  by iApply \"Hclose\".\nQed.\n\nLemma vs_alloc N P : ▷ P ={↑N}=> inv N P.\nProof. iIntros \"!# HP\". by iApply inv_alloc. Qed.\n\nLemma wand_fupd_alt E1 E2 P Q : (P ={E1,E2}=∗ Q) ⊣⊢ ∃ R, R ∗ (P ∗ R ={E1,E2}=> Q).\nProof. rewrite uPred.wand_alt. by setoid_rewrite uPred.persistently_impl_wand. Qed.\nEnd vs.\n", "meta": {"author": "jtassarotti", "repo": "polaris", "sha": "c7873f05214351d54cacf3d8482625ee33ad3288", "save_path": "github-repos/coq/jtassarotti-polaris", "path": "github-repos/coq/jtassarotti-polaris/polaris-c7873f05214351d54cacf3d8482625ee33ad3288/theories/base_logic/lib/viewshifts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.21284517460963134}}
{"text": "From Hammer Require Import Hammer.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nFrom Coq Require Import List Syntax.\nFrom compcert Require Import Alphabet.\nFrom compcert Require Grammar.\nFrom compcert Require Automaton.\nFrom compcert Require Interpreter.\nFrom Coq.ssr Require Import ssreflect.\n\nModule Make(Import A:Automaton.T) (Import Inter:Interpreter.T A).\n\n\n\n\n\nSection Init.\n\nVariable init:initstate.\n\n\nInductive word_has_stack_semantics:\nforall (word:list token) (stack:stack), Prop :=\n| Nil_stack_whss: word_has_stack_semantics [] []\n| Cons_stack_whss:\nforall (wordq:list token) (stackq:stack),\nword_has_stack_semantics wordq stackq ->\n\nforall (wordt:list token) (s:noninitstate)\n(pt:parse_tree (last_symb_of_non_init_state s) wordt),\n\nword_has_stack_semantics\n(wordq++wordt) (existT noninitstate_type s (pt_sem pt)::stackq).\n\n\nLemma pop_spec_ptl A symbols_to_pop action word_stk stk (res : A) stk' :\npop_spec symbols_to_pop stk action stk' res ->\nword_has_stack_semantics word_stk stk ->\nexists word_stk' word_res (ptl:parse_tree_list symbols_to_pop word_res),\n(word_stk' ++ word_res = word_stk)%list /\\\nword_has_stack_semantics word_stk' stk' /\\\nptl_sem ptl action = res.\nProof. hammer_hook \"Interpreter_correct\" \"Interpreter_correct.Make.pop_spec_ptl\".\nintros Hspec. revert word_stk.\ninduction Hspec as [stk sem|symbols_to_pop st stk action sem stk' res Hspec IH];\nintros word_stk Hword_stk.\n- exists word_stk, [], Nil_ptl. rewrite -app_nil_end. eauto.\n- inversion Hword_stk. subst_existT.\nedestruct IH as (word_stk' & word_res & ptl & ? & Hword_stk'' & ?); [eassumption|].\nsubst. eexists word_stk', (word_res ++ _)%list, (Cons_ptl ptl _).\nsplit; [|split]=>//. rewrite app_assoc //.\nQed.\n\n\nLemma reduce_step_invariant (stk:stack) (prod:production) Hv Hi word buffer :\nword_has_stack_semantics word stk ->\nmatch reduce_step init stk prod buffer Hv Hi with\n| Accept_sr sem buffer_new =>\nexists pt : parse_tree (NT (start_nt init)) word,\nbuffer = buffer_new /\\ pt_sem pt = sem\n| Progress_sr stk' buffer_new =>\nbuffer = buffer_new /\\ word_has_stack_semantics word stk'\n| Fail_sr => True\nend.\nProof. hammer_hook \"Interpreter_correct\" \"Interpreter_correct.Make.reduce_step_invariant\".\nintros Hword_stk. unfold reduce_step.\nmatch goal with\n| |- context [pop_state_valid init ?stp stk ?x1 ?x2 ?x3 ?x4 ?x5] =>\ngeneralize (pop_state_valid init stp stk x1 x2 x3 x4 x5)\nend.\ndestruct pop as [stk' sem] eqn:Hpop=>/= Hv'.\napply pop_spec_ok in Hpop. apply pop_spec_ptl with (word_stk := word) in Hpop=>//.\ndestruct Hpop as (word1 & word2 & ptl & <- & Hword1 & <-).\ngeneralize (reduce_step_subproof1 init stk prod Hv stk' (fun _ : True => Hv')).\ndestruct goto_table as [[st' EQ]|].\n- intros _. split=>//.\nchange (ptl_sem ptl (prod_action prod)) with (pt_sem (Non_terminal_pt prod ptl)).\ngeneralize (Non_terminal_pt prod ptl). rewrite ->EQ. intros pt. by constructor.\n- intros Hstk'. destruct Hword1; [|by destruct Hstk'].\ngeneralize (reduce_step_subproof0 init prod [] (fun _ : True => Hstk')).\nsimpl in Hstk'. rewrite -Hstk' // => EQ. rewrite cast_eq.\nexists (Non_terminal_pt prod ptl). by split.\nQed.\n\n\nLemma step_invariant stk word buffer safe Hi :\nword_has_stack_semantics word stk ->\nmatch step safe init stk buffer Hi with\n| Accept_sr sem buffer_new =>\nexists word_new (pt:parse_tree (NT (start_nt init)) word_new),\n(word ++ buffer = word_new ++ buffer_new)%buf /\\\npt_sem pt = sem\n| Progress_sr stk_new buffer_new =>\nexists word_new,\n(word ++ buffer = word_new ++ buffer_new)%buf /\\\nword_has_stack_semantics word_new stk_new\n| Fail_sr => True\nend.\nProof. hammer_hook \"Interpreter_correct\" \"Interpreter_correct.Make.step_invariant\".\nintros Hword_stk. unfold step.\ngeneralize (reduce_ok safe (state_of_stack init stk)).\ndestruct action_table as [prod|awt].\n- intros Hv.\napply (reduce_step_invariant stk prod (fun _ => Hv) Hi word buffer) in Hword_stk.\ndestruct reduce_step=>//.\n+ destruct Hword_stk as (pt & <- & <-); eauto.\n+ destruct Hword_stk as [<- ?]; eauto.\n- destruct buffer as [tok buffer]=>/=.\nmove=> /(_ (token_term tok)) Hv. destruct (awt (token_term tok)) as [st EQ|prod|]=>//.\n+ eexists _. split; [by apply app_buf_assoc with (l2 := [_])|].\nchange (token_sem tok) with (pt_sem (Terminal_pt tok)).\ngeneralize (Terminal_pt tok). generalize [tok].\nrewrite -> EQ=>word' pt /=. by constructor.\n+ apply (reduce_step_invariant stk prod (fun _ => Hv) Hi word (tok::buffer))\nin Hword_stk.\ndestruct reduce_step=>//.\n* destruct Hword_stk as (pt & <- & <-); eauto.\n* destruct Hword_stk as [<- ?]; eauto.\nQed.\n\n\nLemma parse_fix_invariant stk word buffer safe log_n_steps Hi :\nword_has_stack_semantics word stk ->\nmatch proj1_sig (parse_fix safe init stk buffer log_n_steps Hi) with\n| Accept_sr sem buffer_new =>\nexists word_new (pt:parse_tree (NT (start_nt init)) word_new),\n(word ++ buffer = word_new ++ buffer_new)%buf /\\\npt_sem pt = sem\n| Progress_sr stk_new buffer_new =>\nexists word_new,\n(word ++ buffer = word_new ++ buffer_new)%buf /\\\nword_has_stack_semantics word_new stk_new\n| Fail_sr => True\nend.\nProof. hammer_hook \"Interpreter_correct\" \"Interpreter_correct.Make.parse_fix_invariant\".\nrevert stk word buffer Hi.\ninduction log_n_steps as [|log_n_steps IH]=>/= stk word buffer Hi Hstk;\n[by apply step_invariant|].\nassert (IH1 := IH stk word buffer Hi Hstk).\ndestruct parse_fix as [[] Hi']=>/=; try by apply IH1.\ndestruct IH1 as (word' & -> & Hstk')=>//. by apply IH.\nQed.\n\n\nTheorem parse_correct safe buffer log_n_steps:\nmatch parse safe init buffer log_n_steps with\n| Parsed_pr sem buffer_new =>\nexists word_new (pt:parse_tree (NT (start_nt init)) word_new),\nbuffer = (word_new ++ buffer_new)%buf /\\\npt_sem pt = sem\n| _ => True\nend.\nProof. hammer_hook \"Interpreter_correct\" \"Interpreter_correct.Make.parse_correct\".\nunfold parse.\nassert (Hparse := parse_fix_invariant [] [] buffer safe log_n_steps\n(parse_subproof init)).\ndestruct proj1_sig=>//. apply Hparse. constructor.\nQed.\n\nEnd Init.\n\nEnd Make.\n", "meta": {"author": "lukaszcz", "repo": "coqhammer-eval", "sha": "e7a30119c1470623125728006fd1299641192a60", "save_path": "github-repos/coq/lukaszcz-coqhammer-eval", "path": "github-repos/coq/lukaszcz-coqhammer-eval/coqhammer-eval-e7a30119c1470623125728006fd1299641192a60/compcert/Interpreter_correct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.21284517460963134}}
{"text": "Require Import mlattice id_and_loc.\nRequire Import LibTactics tactics.\n\nRequire Import mlattice.\nModule Language (L: Lattice).\n  Import L.\n  Module ProdL := ProductLattice L LH.\n  Module ProdLatProp := LatticeProperties ProdL.\n  Module LHLatProp := LatticeProperties LH.\n  Definition level := ProdL.T.\n  Definition level_proj1 := L.T.\n  \n  Inductive op := Plus | Mult.\n  \n  Inductive expr :=\n  | Const: nat -> expr\n  | Var: id -> expr\n  | BinOp: op -> expr -> expr -> expr.\n  \n  Inductive cmd  :=\n  | Skip: cmd\n  | Stop: cmd\n  | Assign: id -> expr -> cmd\n  | If: expr -> cmd -> cmd -> cmd\n  | While: expr -> cmd -> cmd\n  | Seq: cmd -> cmd -> cmd\n  | At: level_proj1 -> expr -> cmd -> cmd\n  | BackAt: level_proj1 -> nat -> cmd\n  | NewArr: id -> level_proj1 -> expr -> expr -> cmd\n  | SetArr: id -> expr -> expr -> cmd\n  | GetArr: id -> id -> expr -> cmd\n  | Time: id -> cmd\n  | TimeOut: cmd.\n  \nNotation \"'STOP'\" := Stop (only parsing).\nNotation \"'SKIP'\" := Skip (only parsing).\nNotation \"x '::=' e\" := (Assign x e) (at level 80).\nNotation \"c1 ';;' c2\":= (Seq c1 c2)  (at level 80, right associativity).\nNotation \"'WHILE' b 'DO' c 'END'\" :=\n  (While b c) (at level 80, right associativity).\nNotation \"'IFB' e 'THEN' c1 'ELSE' c2 'FI'\" :=\n  (If e c1 c2) (at level 80, right associativity).\nNotation \"'AT' ℓ 'FOR' e 'DO' c\" :=\n  (At ℓ e c) (at level 80).\nNotation \"'BACKAT' ℓ 'WHEN' n 'DO' c\" :=\n    (BackAt ℓ n c) (at level 80).\nNotation \"'SET' x '[' e1 ']'  'TO' e2 \" :=\n  (SetArr x e1 e2) (at level 80).\nNotation \"'GET' x 'FROM' y '[' e ']'\" :=\n    (GetArr x y e) (at level 80).\nNotation \"'TIME' '(' x ')'\" := (Time x).\nNotation \"'TIMEOUT'\" := TimeOut.\n\nInductive value :=\n| ValNum: nat -> value\n| ValLoc: loc -> value.\n\nEnd Language.", "meta": {"author": "MathiasVP", "repo": "ni-formal-gc", "sha": "07899c51af76b237d382dc825904fc9158cd905d", "save_path": "github-repos/coq/MathiasVP-ni-formal-gc", "path": "github-repos/coq/MathiasVP-ni-formal-gc/ni-formal-gc-07899c51af76b237d382dc825904fc9158cd905d/language.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21280747026296798}}
{"text": "Require Import Bool List String Peano_dec Lia.\nRequire Import Common FMap IndexSupport HVector Syntax Topology Semantics SemFacts StepM.\nRequire Import Invariant TrsInv Simulation Serial SerialFacts.\nRequire Import RqRsLang RqRsCorrect.\n\nRequire Import Ex.Spec Ex.SpecInds Ex.Template.\nRequire Import Ex.Mesi Ex.Mesi.Mesi.\n\nSet Implicit Arguments.\n\nImport PropMonadNotations.\nImport CaseNotations.\n\nLocal Open Scope list.\nLocal Open Scope hvec.\nLocal Open Scope fmap.\n\n#[global] Existing Instance Mesi.ImplOStateIfc.\n\nSection ObjInv.\n  Variable topo: DTree.\n\n  Definition MesiUpLockObjInv (oidx: IdxT): ObjInv :=\n    fun ost orq =>\n      (rqiu <+- orq@[upRq];\n      rmsg <+- rqiu.(rqi_msg);\n      match case rmsg.(msg_id) on idx_dec default True with\n      | mesiRqS:\n          ost#[owned] = false /\\ ost#[status] <= mesiI /\\\n          ost#[dir].(dir_st) <= mesiS\n      | mesiRqM:\n          ost#[owned] = false /\\ ost#[status] <= mesiS /\\\n          ost#[dir].(dir_st) <= mesiS\n      end).\n\n  Definition DownLockFromChild (oidx: IdxT) (rqid: RqInfo Msg) :=\n    exists cidx,\n      rqid.(rqi_midx_rsb) = Some (downTo cidx) /\\\n      parentIdxOf topo cidx = Some oidx.\n\n  Definition DownLockFromParent (oidx: IdxT) (rqid: RqInfo Msg) :=\n    rqid.(rqi_midx_rsb) = Some (rsUpFrom oidx).\n\n  Definition MesiDownLockObjInv (oidx: IdxT): ObjInv :=\n    fun ost orq =>\n      (rqid <+- orq@[downRq];\n      rmsg <+- rqid.(rqi_msg);\n      match case rmsg.(msg_id) on idx_dec default True with\n      | mesiRqS: DownLockFromChild oidx rqid /\\\n                 ost#[status] <= mesiI /\\ mesiE <= ost#[dir].(dir_st) <= mesiM /\\\n                 In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n                 map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]\n      | mesiRqM: DownLockFromChild oidx rqid /\\\n                 ost#[status] <= mesiS /\\\n                 ((ost#[owned] = true /\\ ost#[dir].(dir_st) = mesiS /\\\n                   SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n                   (rsb <+- rqid.(rqi_midx_rsb);\n                   map fst rqid.(rqi_rss) =\n                   map rsUpFrom (remove idx_dec (objIdxOf rsb) ost#[dir].(dir_sharers)))) \\/\n                  (mesiE <= ost#[dir].(dir_st) <= mesiM /\\\n                   In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n                   map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]))\n      | mesiDownRqS: DownLockFromParent oidx rqid /\\\n                     ost#[status] <= mesiI /\\ mesiE <= ost#[dir].(dir_st) <= mesiM /\\\n                     In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n                     map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]\n      | mesiDownRqIS: DownLockFromParent oidx rqid /\\\n                      ost#[dir].(dir_st) = mesiS /\\\n                      SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n                      map fst rqid.(rqi_rss) = map rsUpFrom ost#[dir].(dir_sharers)\n      | mesiDownRqIM: DownLockFromParent oidx rqid /\\\n                      ((ost#[dir].(dir_st) = mesiS /\\\n                        SubList ost#[dir].(dir_sharers) (subtreeChildrenIndsOf topo oidx) /\\\n                        map fst rqid.(rqi_rss) = map rsUpFrom ost#[dir].(dir_sharers)) \\/\n                       (mesiE <= ost#[dir].(dir_st) <= mesiM /\\\n                        In ost#[dir].(dir_excl) (subtreeChildrenIndsOf topo oidx) /\\\n                        map fst rqid.(rqi_rss) = [rsUpFrom ost#[dir].(dir_excl)]))\n      end).\n\n  Definition MesiObjInvs (oidx: IdxT): ObjInv :=\n    fun ost orq =>\n      MesiUpLockObjInv oidx ost orq /\\\n      MesiDownLockObjInv oidx ost orq.\n\nEnd ObjInv.\n\nLtac disc_mesi_obj_invs :=\n  repeat\n    match goal with\n    | [H: MesiObjInvs _ _ _ _ |- _] => destruct H\n    | [H: MesiUpLockObjInv _ _ _ |- _] =>\n      red in H; mred; simpl in H; disc_rule_conds_const\n    | [H: MesiDownLockObjInv _ _ _ _ |- _] =>\n      red in H; mred; simpl in H; disc_rule_conds_const\n    | [Hmsg: msg_id ?rmsg = _, H: context [msg_id ?rmsg] |- _] =>\n      rewrite Hmsg in H; simpl in H\n    end.\n\n", "meta": {"author": "mit-plv", "repo": "hemiola", "sha": "1984b4de903259ce2d7abda737e76e16e6436dee", "save_path": "github-repos/coq/mit-plv-hemiola", "path": "github-repos/coq/mit-plv-hemiola/hemiola-1984b4de903259ce2d7abda737e76e16e6436dee/src/Ex/Mesi/MesiObjInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.35220179564702847, "lm_q1q2_score": 0.21270588130813958}}
{"text": "Require Import Coq.Logic.Classical_Prop.\n\nRequire Import SpecCert.Address.\nRequire Import SpecCert.Cache.\nRequire Import SpecCert.Formalism.\nRequire Import SpecCert.Interval.\nRequire Import SpecCert.Map.\nRequire Import SpecCert.Memory.\nRequire Import SpecCert.Smm.Delta.Invariant.\nRequire Import SpecCert.Smm.Delta.Preserve.Architecture.\nRequire Import SpecCert.Smm.Software.\nRequire Import SpecCert.x86.\n\nLemma write_strat_uc\n      (pa: PhysicalAddress)\n      (v:  Value)\n  : partial_preserve (Write pa v)\n                     (fun a => resolve_cache_strategy (proc a) pa = Uncachable)\n                     inv.\nProof.\n  unfold partial_preserve.\n  intros a a' Hinv Hsmm_strat Hpre Hpost.\n  unfold x86_postcondition, write_post in Hpost.\n  rewrite Hsmm_strat in Hpost.\n  unfold write_uncachable in Hpost.\n  apply (update_memory_content_with_context_preserves_inv a a' pa v Hinv Hpost).\nQed.\n\nLemma write_strat_sh\n      (pa: PhysicalAddress)\n      (v: Value)\n  : partial_preserve (Write pa v)\n                     (fun a => resolve_cache_strategy (proc a) pa = SmrrHit)\n                     inv.\nProof.\n  unfold partial_preserve.\n  intros a a' Hinv Hsmm_strat Hpre Hpost.\n  unfold x86_postcondition, write_post in Hpost.\n  rewrite Hsmm_strat in Hpost.\n  unfold write_smrrhit in Hpost.\n  rewrite Hpost.\n  exact Hinv.\nQed.\n\nLemma write_strat_smrr_wb\n      (pa: PhysicalAddress)\n      (v:  Value)\n  : partial_preserve (Write pa v)\n                     (fun a => is_inside_smrr (proc a) pa\n                            /\\ smm_strategy (smrr (proc a)) = WriteBack)\n                     inv.\nProof.\n  unfold partial_preserve.\n  intros a a' Hinv [Hinside_smrr Hsmm_strat] Hpre Hpost.\n  unfold x86_postcondition, write_post, resolve_cache_strategy in Hpost.\n  destruct is_inside_smrr_dec; [| intuition ].\n  destruct is_in_smm_dec as [Hin_smm|Hnot].\n  + rewrite Hsmm_strat in Hpost.\n    unfold write_writeback in Hpost.\n    assert (is_inside_smram pa -> is_in_smm (proc a)); [\n        intro Hin;\n        exact Hin_smm |].\n    destruct cache_hit_dec.\n    * apply (update_cache_content_with_context_preserves_inv a a' pa v Hinv H Hpost).\n    * remember (load_in_cache_from_memory a pa) as a''.\n      assert (inv a'') as Hinv''; [\n          apply (load_in_cache_from_memory_preserves_inv a a'' pa Hinv H Heqa'') |].\n      assert (proc a = proc a'').\n      apply load_in_cache_from_memory_changes_only_mem_and_cache in Heqa'' as [Hproc Hmc].\n      rewrite <- Hproc.\n      reflexivity.\n      assert (is_in_smm (proc a'')).\n      rewrite <- H0.\n      exact Hin_smm.\n      assert (is_inside_smram pa -> is_in_smm (proc a'')); [\n        intro Hin;\n          exact H1 |].\n      rewrite (context_is_preserves a a'' H0) in Hpost.\n      eapply (update_cache_content_with_context_preserves_inv a'' a' pa v Hinv'' H2 Hpost).\n  + unfold write_smrrhit in Hpost.\n    rewrite Hpost.\n    exact Hinv.\nQed.\n\nLemma write_not_smrr\n      (pa: PhysicalAddress)\n      (v: Value)\n  : partial_preserve (Write pa v)\n                     (fun a => ~ is_inside_smrr (proc a) pa)\n                     inv.\nProof.\n  unfold partial_preserve.\n  intros a a' Hinv Hnot_inside_smrr Hpre Hpost.\n  unfold x86_postcondition in Hpost;\n  unfold x86_precondition in Hpre.\n  assert (write_post smm_context pa v a a') as Hx; [unfold x86_postcondition in Hpost; exact Hpost |].\n  remember (resolve_cache_strategy (proc a) pa) as strat.\n  unfold write_post in Hpost.\n  assert (strat = strategy (proc a)).\n  unfold resolve_cache_strategy in Heqstrat.\n  destruct is_inside_smrr_dec; [ intuition |].\n  exact Heqstrat.\n  case_eq (resolve_cache_strategy (proc a) pa); intro Hres; rewrite Hres in Hpost.\n  + apply (write_strat_uc pa v a a' Hinv Hres Hpre Hx).\n  + destruct (is_inside_smrr_dec (proc a) pa); [ intuition |].\n    unfold write_writeback in Hpost.\n    assert (is_inside_smram pa -> is_in_smm (proc a)).\n    intro Hfalse.\n    destruct Hinv as [Hsmramc [Hsmram [Hsmrr Hclean]]].\n    apply Hsmrr in Hfalse.\n    apply n in Hfalse.\n    destruct Hfalse.\n    destruct (cache_hit_dec (cache a) pa).\n    * apply (update_cache_content_with_context_preserves_inv a a' pa v Hinv H0 Hpost).\n    * apply (load_then_update_cache_with_context_preserves_inv a a' pa v Hinv H0 Hpost).\n + apply (write_strat_sh pa v a a' Hinv Hres Hpre Hx).\nQed.\n\nLemma write_inv\n      (pa: PhysicalAddress)\n      (v: Value)\n  : preserve (Write pa v) inv.\nProof.\n  unfold preserve.\n  intros a a' Hinv Htrans.\n  destruct (is_inside_smrr_dec (proc a) pa).\n  + case_eq (resolve_cache_strategy (proc a) pa); intro Hres.\n    * apply (write_strat_uc pa v a a' Hinv Hres Htrans).\n    * assert (is_inside_smrr (proc a) pa /\\ smm_strategy (smrr (proc a)) = WriteBack).\n      split; [ exact i |].\n      unfold resolve_cache_strategy in Hres.\n      destruct is_inside_smrr_dec; [| intuition ].\n      destruct is_in_smm_dec; [| discriminate Hres ].\n      exact Hres.\n      apply (write_strat_smrr_wb pa v a a' Hinv H Htrans).\n    * apply (write_strat_sh pa v a a' Hinv Hres Htrans).\n  + apply (write_not_smrr pa v a a' Hinv n Htrans).\nQed.\n", "meta": {"author": "lthms", "repo": "speccert", "sha": "8c1edfb173548af0e9ca3c4e24d43726401fdb71", "save_path": "github-repos/coq/lthms-speccert", "path": "github-repos/coq/lthms-speccert/speccert-8c1edfb173548af0e9ca3c4e24d43726401fdb71/src/Smm/Delta/Preserve/Write.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.21270586807373232}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import PromiseConsistent.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\n\nSet Implicit Arguments.\n\n\nSection SimulationThread.\n  Definition SIM_TERMINAL (lang_src lang_tgt:language) :=\n    forall (st_src:(Language.state lang_src)) (st_tgt:(Language.state lang_tgt)), Prop.\n\n  Definition SIM_THREAD :=\n    forall (lang_src lang_tgt:language) (sim_terminal: SIM_TERMINAL lang_src lang_tgt)\n      (st1_src:(Language.state lang_src)) (lc1_src:Local.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n      (st1_tgt:(Language.state lang_tgt)) (lc1_tgt:Local.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t), Prop.\n\n  Definition _sim_thread_step\n             (lang_src lang_tgt:language)\n             (sim_thread: forall (st1_src:(Language.state lang_src)) (lc1_src:Local.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n                                 (st1_tgt:(Language.state lang_tgt)) (lc1_tgt:Local.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t), Prop)\n             st1_src lc1_src sc1_src mem1_src\n             st1_tgt lc1_tgt sc1_tgt mem1_tgt\n    :=\n    forall pf_tgt e_tgt st3_tgt lc3_tgt sc3_tgt mem3_tgt\n      (STEP_TGT: Thread.step pf_tgt e_tgt\n                             (Thread.mk _ st1_tgt lc1_tgt sc1_tgt mem1_tgt)\n                             (Thread.mk _ st3_tgt lc3_tgt sc3_tgt mem3_tgt)),\n      <<FAILURE: Thread.steps_failure (Thread.mk _ st1_src lc1_src sc1_src mem1_src)>> \\/\n      exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n        <<FAILURE: ThreadEvent.get_machine_event e_tgt <> MachineEvent.failure>> /\\\n        <<STEPS: rtc (@Thread.tau_step _)\n                     (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                     (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n        <<STEP_SRC: Thread.opt_step e_src\n                                    (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                                    (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n        <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n        <<SC3: TimeMap.le sc3_src sc3_tgt>> /\\\n        <<MEMORY3: sim_memory mem3_src mem3_tgt>> /\\\n        <<SIM: sim_thread st3_src lc3_src sc3_src mem3_src st3_tgt lc3_tgt sc3_tgt mem3_tgt>>.\n\n  Definition _sim_thread\n             (sim_thread: SIM_THREAD)\n             (lang_src lang_tgt:language)\n             (sim_terminal: SIM_TERMINAL lang_src lang_tgt)\n             (st1_src:(Language.state lang_src)) (lc1_src:Local.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n             (st1_tgt:(Language.state lang_tgt)) (lc1_tgt:Local.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t): Prop :=\n    forall sc1_src mem1_src\n      sc1_tgt mem1_tgt\n      (SC: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY: sim_memory mem1_src mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc0_src sc1_src)\n      (SC_FUTURE_TGT: TimeMap.le sc0_tgt sc1_tgt)\n      (MEM_FUTURE_SRC: Memory.future_weak mem0_src mem1_src)\n      (MEM_FUTURE_TGT: Memory.future_weak mem0_tgt mem1_tgt)\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed mem1_tgt)\n      (CONS_TGT: Local.promise_consistent lc1_tgt),\n      <<TERMINAL:\n        forall (TERMINAL_TGT: (Language.is_terminal lang_tgt) st1_tgt),\n          <<FAILURE: Thread.steps_failure (Thread.mk _ st1_src lc1_src sc1_src mem1_src)>> \\/\n          exists st2_src lc2_src sc2_src mem2_src,\n            <<STEPS: rtc (@Thread.tau_step _)\n                         (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                         (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n            <<SC: TimeMap.le sc2_src sc1_tgt>> /\\\n            <<MEMORY: sim_memory mem2_src mem1_tgt>> /\\\n            <<TERMINAL_SRC: (Language.is_terminal lang_src) st2_src>> /\\\n            <<LOCAL: sim_local SimPromises.bot lc2_src lc1_tgt>> /\\\n            <<TERMINAL: sim_terminal st2_src st1_tgt>>>> /\\\n      <<PROMISES:\n        forall (PROMISES_TGT: (Local.promises lc1_tgt) = Memory.bot),\n          <<FAILURE: Thread.steps_failure (Thread.mk _ st1_src lc1_src sc1_src mem1_src)>> \\/\n          exists st2_src lc2_src sc2_src mem2_src,\n            <<STEPS: rtc (@Thread.tau_step _)\n                         (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                         (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n            <<PROMISES_SRC: (Local.promises lc2_src) = Memory.bot>>>> /\\\n      <<STEP: _sim_thread_step _ _ (@sim_thread lang_src lang_tgt sim_terminal)\n                               st1_src lc1_src sc1_src mem1_src\n                               st1_tgt lc1_tgt sc1_tgt mem1_tgt>>.\n\n  Lemma _sim_thread_mon: monotone11 _sim_thread.\n  Proof.\n    ii. exploit IN; try apply SC; eauto. i. des.\n    splits; eauto. ii.\n    exploit STEP; eauto. i. des; eauto.\n    right. esplits; eauto.\n  Qed.\n  Hint Resolve _sim_thread_mon: paco.\n\n  Definition sim_thread: SIM_THREAD := paco11 _sim_thread bot11.\n\n  Lemma sim_thread_mon\n        (lang_src lang_tgt:language)\n        (sim_terminal1 sim_terminal2: SIM_TERMINAL lang_src lang_tgt)\n        (SIM: sim_terminal1 <2= sim_terminal2):\n    sim_thread sim_terminal1 <8= sim_thread sim_terminal2.\n  Proof.\n    pcofix CIH. i. punfold PR. pfold. ii.\n    exploit PR; try apply SC; eauto. i. des.\n    splits; auto.\n    - i. exploit TERMINAL; eauto. i. des; eauto.\n      right. esplits; eauto.\n    - ii. exploit STEP; eauto. i. des; eauto.\n      inv SIM0; [|done].\n      right. esplits; eauto.\n  Qed.\nEnd SimulationThread.\n#[export] Hint Resolve _sim_thread_mon: paco.\n\n\nLemma sim_thread_step\n      lang_src lang_tgt\n      sim_terminal\n      pf_tgt e_tgt\n      st1_src lc1_src sc1_src mem1_src\n      st1_tgt lc1_tgt sc1_tgt mem1_tgt\n      st3_tgt lc3_tgt sc3_tgt mem3_tgt\n      (STEP: @Thread.step lang_tgt pf_tgt e_tgt\n                          (Thread.mk _ st1_tgt lc1_tgt sc1_tgt mem1_tgt)\n                          (Thread.mk _ st3_tgt lc3_tgt sc3_tgt mem3_tgt))\n      (SC: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY: sim_memory mem1_src mem1_tgt)\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed mem1_tgt)\n      (CONS_TGT: Local.promise_consistent lc3_tgt)\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src st1_tgt lc1_tgt sc1_tgt mem1_tgt):\n  <<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src sc1_src mem1_src)>> \\/\n  exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n    <<FAILURE: ThreadEvent.get_machine_event e_tgt <> MachineEvent.failure>> /\\\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<STEP: Thread.opt_step e_src\n                            (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                            (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n    <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n    <<SC: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEMORY: sim_memory mem3_src mem3_tgt>> /\\\n    <<WF_SRC: Local.wf lc3_src mem3_src>> /\\\n    <<WF_TGT: Local.wf lc3_tgt mem3_tgt>> /\\\n    <<SC_SRC: Memory.closed_timemap sc3_src mem3_src>> /\\\n    <<SC_TGT: Memory.closed_timemap sc3_tgt mem3_tgt>> /\\\n    <<MEM_SRC: Memory.closed mem3_src>> /\\\n    <<MEM_TGT: Memory.closed mem3_tgt>> /\\\n    <<SIM: sim_thread sim_terminal st3_src lc3_src sc3_src mem3_src st3_tgt lc3_tgt sc3_tgt mem3_tgt>>.\nProof.\n  hexploit step_promise_consistent; eauto. s. i.\n  punfold SIM. exploit SIM; eauto; try refl. i. des.\n  exploit Thread.step_future; eauto. s. i. des.\n  exploit STEP0; eauto. i. des; eauto.\n  inv SIM0; [|done]. right.\n  exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n  exploit Thread.opt_step_future; eauto. s. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_thread_opt_step\n      lang_src lang_tgt\n      sim_terminal\n      e_tgt\n      st1_src lc1_src sc1_src mem1_src\n      st1_tgt lc1_tgt sc1_tgt mem1_tgt\n      st3_tgt lc3_tgt sc3_tgt mem3_tgt\n      (STEP: @Thread.opt_step lang_tgt e_tgt\n                              (Thread.mk _ st1_tgt lc1_tgt sc1_tgt mem1_tgt)\n                              (Thread.mk _ st3_tgt lc3_tgt sc3_tgt mem3_tgt))\n      (SC: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY: sim_memory mem1_src mem1_tgt)\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed mem1_tgt)\n      (CONS_TGT: Local.promise_consistent lc3_tgt)\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src st1_tgt lc1_tgt sc1_tgt mem1_tgt):\n  <<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src sc1_src mem1_src)>> \\/\n  exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n    <<FAILURE: ThreadEvent.get_machine_event e_tgt <> MachineEvent.failure>> /\\\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<STEP: Thread.opt_step e_src\n                            (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                            (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n    <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n    <<SC: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEMORY: sim_memory mem3_src mem3_tgt>> /\\\n    <<WF_SRC: Local.wf lc3_src mem3_src>> /\\\n    <<WF_TGT: Local.wf lc3_tgt mem3_tgt>> /\\\n    <<SC_SRC: Memory.closed_timemap sc3_src mem3_src>> /\\\n    <<SC_TGT: Memory.closed_timemap sc3_tgt mem3_tgt>> /\\\n    <<MEM_SRC: Memory.closed mem3_src>> /\\\n    <<MEM_TGT: Memory.closed mem3_tgt>> /\\\n    <<SIM: sim_thread sim_terminal st3_src lc3_src sc3_src mem3_src st3_tgt lc3_tgt sc3_tgt mem3_tgt>>.\nProof.\n  inv STEP.\n  - right. esplits; eauto; ss. econs 1.\n  - eapply sim_thread_step; eauto.\nQed.\n\nLemma sim_thread_rtc_step\n      lang_src lang_tgt\n      sim_terminal\n      st1_src lc1_src sc1_src mem1_src\n      e1_tgt e2_tgt\n      (STEPS: rtc (@Thread.tau_step lang_tgt) e1_tgt e2_tgt)\n      (SC: TimeMap.le sc1_src (Thread.sc e1_tgt))\n      (MEMORY: sim_memory mem1_src (Thread.memory e1_tgt))\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed (Thread.memory e1_tgt))\n      (CONS_TGT: Local.promise_consistent (Thread.local e2_tgt))\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src (Thread.state e1_tgt) (Thread.local e1_tgt) (Thread.sc e1_tgt) (Thread.memory e1_tgt)):\n  <<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src sc1_src mem1_src)>> \\/\n  exists st2_src lc2_src sc2_src mem2_src,\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<SC: TimeMap.le sc2_src (Thread.sc e2_tgt)>> /\\\n    <<MEMORY: sim_memory mem2_src (Thread.memory e2_tgt)>> /\\\n    <<WF_SRC: Local.wf lc2_src mem2_src>> /\\\n    <<WF_TGT: Local.wf (Thread.local e2_tgt) (Thread.memory e2_tgt)>> /\\\n    <<SC_SRC: Memory.closed_timemap sc2_src mem2_src>> /\\\n    <<SC_TGT: Memory.closed_timemap (Thread.sc e2_tgt) (Thread.memory e2_tgt)>> /\\\n    <<MEM_SRC: Memory.closed mem2_src>> /\\\n    <<MEM_TGT: Memory.closed (Thread.memory e2_tgt)>> /\\\n    <<SIM: sim_thread sim_terminal st2_src lc2_src sc2_src mem2_src (Thread.state e2_tgt) (Thread.local e2_tgt) (Thread.sc e2_tgt) (Thread.memory e2_tgt)>>.\nProof.\n  revert SC MEMORY WF_SRC WF_TGT SC_SRC SC_TGT MEM_SRC MEM_TGT SIM.\n  revert st1_src lc1_src sc1_src mem1_src.\n  induction STEPS; i.\n  { right. esplits; eauto. }\n  inv H. inv TSTEP. destruct x, y. ss.\n  exploit Thread.step_future; eauto. s. i. des.\n  hexploit rtc_tau_step_promise_consistent; eauto. s. i.\n  exploit sim_thread_step; eauto. i. des; eauto.\n  exploit IHSTEPS; eauto. i. des.\n  - left. inv FAILURE0. des.\n    unfold Thread.steps_failure. esplits; [|eauto|eauto].\n    etrans; eauto. etrans; eauto. inv STEP0; eauto.\n    econs 2; eauto. econs.\n    + econs. eauto.\n    + destruct e, e_src; ss.\n  - right. destruct z. ss.\n    esplits; try apply MEMORY1; eauto.\n    etrans; [eauto|]. etrans; [|eauto]. inv STEP0; eauto.\n    econs 2; eauto. econs.\n    + econs. eauto.\n    + destruct e, e_src; ss.\nQed.\n\nLemma sim_thread_plus_step\n      lang_src lang_tgt\n      sim_terminal\n      pf_tgt e_tgt\n      st1_src lc1_src sc1_src mem1_src\n      e1_tgt e2_tgt e3_tgt\n      (STEPS: rtc (@Thread.tau_step lang_tgt) e1_tgt e2_tgt)\n      (STEP: @Thread.step lang_tgt pf_tgt e_tgt e2_tgt e3_tgt)\n      (SC: TimeMap.le sc1_src (Thread.sc e1_tgt))\n      (MEMORY: sim_memory mem1_src (Thread.memory e1_tgt))\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed (Thread.memory e1_tgt))\n      (CONS_TGT: Local.promise_consistent (Thread.local e3_tgt))\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src (Thread.state e1_tgt) (Thread.local e1_tgt) (Thread.sc e1_tgt) (Thread.memory e1_tgt)):\n  <<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src sc1_src mem1_src)>> \\/\n  exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n    <<FAILURE: ThreadEvent.get_machine_event e_tgt <> MachineEvent.failure>> /\\\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<STEP: Thread.opt_step e_src\n                            (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                            (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n    <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n    <<SC: TimeMap.le sc3_src (Thread.sc e3_tgt)>> /\\\n    <<MEMORY: sim_memory mem3_src (Thread.memory e3_tgt)>> /\\\n    <<WF_SRC: Local.wf lc3_src mem3_src>> /\\\n    <<WF_TGT: Local.wf (Thread.local e3_tgt) (Thread.memory e3_tgt)>> /\\\n    <<SC_SRC: Memory.closed_timemap sc3_src mem3_src>> /\\\n    <<SC_TGT: Memory.closed_timemap (Thread.sc e3_tgt) (Thread.memory e3_tgt)>> /\\\n    <<MEM_SRC: Memory.closed mem3_src>> /\\\n    <<MEM_TGT: Memory.closed (Thread.memory e3_tgt)>> /\\\n    <<SIM: sim_thread sim_terminal st3_src lc3_src sc3_src mem3_src (Thread.state e3_tgt) (Thread.local e3_tgt) (Thread.sc e3_tgt) (Thread.memory e3_tgt)>>.\nProof.\n  destruct e1_tgt, e2_tgt, e3_tgt. ss.\n  exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n  hexploit step_promise_consistent; eauto. s. i.\n  exploit sim_thread_rtc_step; eauto. s. i. des; eauto.\n  exploit Thread.rtc_tau_step_future; try exact STEPS0; eauto. s. i. des.\n  exploit sim_thread_step; try exact STEP; try exact SIM0; eauto. s. i. des.\n  - left. inv FAILURE. des.\n    unfold Thread.steps_failure. esplits; [|eauto|eauto].\n    etrans; eauto.\n  - right. rewrite STEPS1 in STEPS0.\n    esplits; try exact STEPS0; try exact STEP0; eauto.\nQed.\n\nLemma sim_thread_future\n      lang_src lang_tgt\n      sim_terminal\n      st_src lc_src sc1_src sc2_src mem1_src mem2_src\n      st_tgt lc_tgt sc1_tgt sc2_tgt mem1_tgt mem2_tgt\n      (SIM: @sim_thread lang_src lang_tgt sim_terminal st_src lc_src sc1_src mem1_src st_tgt lc_tgt sc1_tgt mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc1_src sc2_src)\n      (SC_FUTURE_TGT: TimeMap.le sc1_tgt sc2_tgt)\n      (MEM_FUTURE_SRC: Memory.future_weak mem1_src mem2_src)\n      (MEM_FUTURE_TGT: Memory.future_weak mem1_tgt mem2_tgt):\n  sim_thread sim_terminal st_src lc_src sc2_src mem2_src st_tgt lc_tgt sc2_tgt mem2_tgt.\nProof.\n  pfold. ii.\n  punfold SIM. exploit SIM; (try by etrans; eauto); eauto.\nQed.\n\n\nLemma cap_property\n      mem1 mem2 lc sc\n      (CAP: Memory.cap mem1 mem2)\n      (WF: Local.wf lc mem1)\n      (SC: Memory.closed_timemap sc mem1)\n      (CLOSED: Memory.closed mem1):\n  <<FUTURE: Memory.future_weak mem1 mem2>> /\\\n  <<WF: Local.wf lc mem2>> /\\\n  <<SC: Memory.closed_timemap sc mem2>> /\\\n  <<CLOSED: Memory.closed mem2>>.\nProof.\n  splits.\n  - eapply Memory.cap_future_weak; eauto.\n  - eapply Local.cap_wf; eauto.\n  - eapply Memory.cap_closed_timemap; eauto.\n  - eapply Memory.cap_closed; eauto.\nQed.\n\n(* TODO: remove *)\n\nLemma sc_property\n      sc1 sc2 mem\n      (MAX: Memory.max_concrete_timemap mem sc2)\n      (SC1: Memory.closed_timemap sc1 mem)\n      (MEM: Memory.closed mem):\n  <<SC2: Memory.closed_timemap sc2 mem>> /\\\n  <<LE: TimeMap.le sc1 sc2>>.\nProof.\n  splits.\n  - eapply Memory.max_concrete_timemap_closed; eauto.\n  - eapply Memory.max_concrete_timemap_spec; eauto.\nQed.\n\nLemma sim_thread_consistent\n      lang_src lang_tgt\n      sim_terminal\n      st_src lc_src sc_src mem_src\n      st_tgt lc_tgt sc_tgt mem_tgt\n      (SIM: sim_thread sim_terminal st_src lc_src sc_src mem_src st_tgt lc_tgt sc_tgt mem_tgt)\n      (SC: TimeMap.le sc_src sc_tgt)\n      (MEMORY: sim_memory mem_src mem_tgt)\n      (WF_SRC: Local.wf lc_src mem_src)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src mem_src)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src)\n      (MEM_TGT: Memory.closed mem_tgt)\n      (CONSISTENT: Thread.consistent (Thread.mk lang_tgt st_tgt lc_tgt sc_tgt mem_tgt)):\n  Thread.consistent (Thread.mk lang_src st_src lc_src sc_src mem_src).\nProof.\n  hexploit consistent_promise_consistent; eauto. s. i.\n  generalize SIM. intro X.\n  punfold X. exploit X; eauto; try refl. i. des.\n  ii. ss.\n  exploit Memory.cap_exists; try exact MEM_TGT. i. des.\n  exploit cap_property; try exact CAP; eauto. i. des.\n  exploit cap_property; try exact CAP0; eauto. i. des.\n  exploit sim_memory_cap; try exact MEMORY; eauto. i. des.\n  exploit CONSISTENT; eauto. s. i. des.\n  - left. inv FAILURE. des.\n    exploit sim_thread_future; try exact SIM; try exact FUTURE; try exact FUTURE0; try refl. i.\n    exploit sim_thread_plus_step; try exact STEPS; try exact FAILURE; try exact x2; eauto; try refl.\n    { inv STEP_FAILURE; inv STEP0; ss. inv LOCAL; ss; inv LOCAL0; ss. }\n    i. des; ss.\n  - hexploit Local.bot_promise_consistent; eauto. i.\n    exploit sim_thread_future; try exact SIM; try exact FUTURE; try exact FUTURE0; try refl. i.\n    exploit sim_thread_rtc_step; try apply STEPS; try exact x1; eauto; try refl. i. des; eauto.\n    destruct e2. ss.\n    punfold SIM0. exploit SIM0; eauto; try refl. i. des.\n    exploit PROMISES1; eauto. i. des.\n    + left. unfold Thread.steps_failure in *. des.\n      esplits; [|eauto|eauto]. etrans; eauto.\n    + right. eexists (Thread.mk _ _ _ _ _). splits; [|eauto].\n      etrans; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/transformation/SimThread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318194686359, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.21270586715875425}}
{"text": "(* !!! WARNING: AUTO GENERATED. DO NOT MODIFY !!! *)\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Equality.\n\nRequire Export Metalib.Metatheory.\nRequire Export Metalib.LibLNgen.\n\nRequire Export syntax_ott.\n\n(** NOTE: Auxiliary theorems are hidden in generated documentation.\n    In general, there is a [_rec] version of every lemma involving\n    [open] and [close]. *)\n\n\n(* *********************************************************************** *)\n(** * Induction principles for nonterminals *)\n\nScheme typ_ind' := Induction for typ Sort Prop.\n\nDefinition typ_mutind :=\n  fun H1 H2 H3 H4 H5 H6 =>\n  typ_ind' H1 H2 H3 H4 H5 H6.\n\nScheme typ_rec' := Induction for typ Sort Set.\n\nDefinition typ_mutrec :=\n  fun H1 H2 H3 H4 H5 H6 =>\n  typ_rec' H1 H2 H3 H4 H5 H6.\n\nScheme co_ind' := Induction for co Sort Prop.\n\nDefinition co_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 =>\n  co_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13.\n\nScheme co_rec' := Induction for co Sort Set.\n\nDefinition co_mutrec :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 =>\n  co_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13.\n\nScheme exp_ind' := Induction for exp Sort Prop.\n\nDefinition exp_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 =>\n  exp_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11.\n\nScheme exp_rec' := Induction for exp Sort Set.\n\nDefinition exp_mutrec :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 =>\n  exp_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11.\n\n\n(* *********************************************************************** *)\n(** * Close *)\n\nFixpoint close_exp_wrt_exp_rec (n1 : nat) (x1 : var) (e1 : exp) {struct e1} : exp :=\n  match e1 with\n    | trm_var_f x2 => if (x1 == x2) then (trm_var_b n1) else (trm_var_f x2)\n    | trm_var_b n2 => if (lt_ge_dec n2 n1) then (trm_var_b n2) else (trm_var_b (S n2))\n    | trm_unit => trm_unit\n    | trm_lit i1 => trm_lit i1\n    | trm_abs e2 => trm_abs (close_exp_wrt_exp_rec (S n1) x1 e2)\n    | trm_app e2 e3 => trm_app (close_exp_wrt_exp_rec n1 x1 e2) (close_exp_wrt_exp_rec n1 x1 e3)\n    | trm_pair e2 e3 => trm_pair (close_exp_wrt_exp_rec n1 x1 e2) (close_exp_wrt_exp_rec n1 x1 e3)\n    | trm_rcd l1 e2 => trm_rcd l1 (close_exp_wrt_exp_rec n1 x1 e2)\n    | trm_proj e2 l1 => trm_proj (close_exp_wrt_exp_rec n1 x1 e2) l1\n    | trm_capp c1 e2 => trm_capp c1 (close_exp_wrt_exp_rec n1 x1 e2)\n  end.\n\nDefinition close_exp_wrt_exp x1 e1 := close_exp_wrt_exp_rec 0 x1 e1.\n\n\n(* *********************************************************************** *)\n(** * Size *)\n\nFixpoint size_typ (T1 : typ) {struct T1} : nat :=\n  match T1 with\n    | a_nat => 1\n    | a_unit => 1\n    | a_arrow T2 T3 => 1 + (size_typ T2) + (size_typ T3)\n    | a_prod T2 T3 => 1 + (size_typ T2) + (size_typ T3)\n    | a_rcd l1 T2 => 1 + (size_typ T2)\n  end.\n\nFixpoint size_co (c1 : co) {struct c1} : nat :=\n  match c1 with\n    | co_id => 1\n    | co_trans c2 c3 => 1 + (size_co c2) + (size_co c3)\n    | co_top => 1\n    | co_arr c2 c3 => 1 + (size_co c2) + (size_co c3)\n    | co_pair c2 c3 => 1 + (size_co c2) + (size_co c3)\n    | co_proj1 => 1\n    | co_proj2 => 1\n    | co_distArr => 1\n    | co_distRcd l1 => 1\n    | co_rcd l1 c2 => 1 + (size_co c2)\n    | co_topArr => 1\n    | co_topRcd l1 => 1\n  end.\n\nFixpoint size_exp (e1 : exp) {struct e1} : nat :=\n  match e1 with\n    | trm_var_f x1 => 1\n    | trm_var_b n1 => 1\n    | trm_unit => 1\n    | trm_lit i1 => 1\n    | trm_abs e2 => 1 + (size_exp e2)\n    | trm_app e2 e3 => 1 + (size_exp e2) + (size_exp e3)\n    | trm_pair e2 e3 => 1 + (size_exp e2) + (size_exp e3)\n    | trm_rcd l1 e2 => 1 + (size_exp e2)\n    | trm_proj e2 l1 => 1 + (size_exp e2)\n    | trm_capp c1 e2 => 1 + (size_co c1) + (size_exp e2)\n  end.\n\n\n(* *********************************************************************** *)\n(** * Degree *)\n\n(** These define only an upper bound, not a strict upper bound. *)\n\nInductive degree_exp_wrt_exp : nat -> exp -> Prop :=\n  | degree_wrt_exp_trm_var_f : forall n1 x1,\n    degree_exp_wrt_exp n1 (trm_var_f x1)\n  | degree_wrt_exp_trm_var_b : forall n1 n2,\n    lt n2 n1 ->\n    degree_exp_wrt_exp n1 (trm_var_b n2)\n  | degree_wrt_exp_trm_unit : forall n1,\n    degree_exp_wrt_exp n1 (trm_unit)\n  | degree_wrt_exp_trm_lit : forall n1 i1,\n    degree_exp_wrt_exp n1 (trm_lit i1)\n  | degree_wrt_exp_trm_abs : forall n1 e1,\n    degree_exp_wrt_exp (S n1) e1 ->\n    degree_exp_wrt_exp n1 (trm_abs e1)\n  | degree_wrt_exp_trm_app : forall n1 e1 e2,\n    degree_exp_wrt_exp n1 e1 ->\n    degree_exp_wrt_exp n1 e2 ->\n    degree_exp_wrt_exp n1 (trm_app e1 e2)\n  | degree_wrt_exp_trm_pair : forall n1 e1 e2,\n    degree_exp_wrt_exp n1 e1 ->\n    degree_exp_wrt_exp n1 e2 ->\n    degree_exp_wrt_exp n1 (trm_pair e1 e2)\n  | degree_wrt_exp_trm_rcd : forall n1 l1 e1,\n    degree_exp_wrt_exp n1 e1 ->\n    degree_exp_wrt_exp n1 (trm_rcd l1 e1)\n  | degree_wrt_exp_trm_proj : forall n1 e1 l1,\n    degree_exp_wrt_exp n1 e1 ->\n    degree_exp_wrt_exp n1 (trm_proj e1 l1)\n  | degree_wrt_exp_trm_capp : forall n1 c1 e1,\n    degree_exp_wrt_exp n1 e1 ->\n    degree_exp_wrt_exp n1 (trm_capp c1 e1).\n\nScheme degree_exp_wrt_exp_ind' := Induction for degree_exp_wrt_exp Sort Prop.\n\nDefinition degree_exp_wrt_exp_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 =>\n  degree_exp_wrt_exp_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11.\n\nHint Constructors degree_exp_wrt_exp : core lngen.\n\n\n(* *********************************************************************** *)\n(** * Local closure (version in [Set], induction principles) *)\n\nInductive lc_set_exp : exp -> Set :=\n  | lc_set_trm_var_f : forall x1,\n    lc_set_exp (trm_var_f x1)\n  | lc_set_trm_unit :\n    lc_set_exp (trm_unit)\n  | lc_set_trm_lit : forall i1,\n    lc_set_exp (trm_lit i1)\n  | lc_set_trm_abs : forall e1,\n    (forall x1 : var, lc_set_exp (open_exp_wrt_exp e1 (trm_var_f x1))) ->\n    lc_set_exp (trm_abs e1)\n  | lc_set_trm_app : forall e1 e2,\n    lc_set_exp e1 ->\n    lc_set_exp e2 ->\n    lc_set_exp (trm_app e1 e2)\n  | lc_set_trm_pair : forall e1 e2,\n    lc_set_exp e1 ->\n    lc_set_exp e2 ->\n    lc_set_exp (trm_pair e1 e2)\n  | lc_set_trm_rcd : forall l1 e1,\n    lc_set_exp e1 ->\n    lc_set_exp (trm_rcd l1 e1)\n  | lc_set_trm_proj : forall e1 l1,\n    lc_set_exp e1 ->\n    lc_set_exp (trm_proj e1 l1)\n  | lc_set_trm_capp : forall c1 e1,\n    lc_set_exp e1 ->\n    lc_set_exp (trm_capp c1 e1).\n\nScheme lc_exp_ind' := Induction for lc_exp Sort Prop.\n\nDefinition lc_exp_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 =>\n  lc_exp_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10.\n\nScheme lc_set_exp_ind' := Induction for lc_set_exp Sort Prop.\n\nDefinition lc_set_exp_mutind :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 =>\n  lc_set_exp_ind' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10.\n\nScheme lc_set_exp_rec' := Induction for lc_set_exp Sort Set.\n\nDefinition lc_set_exp_mutrec :=\n  fun H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 =>\n  lc_set_exp_rec' H1 H2 H3 H4 H5 H6 H7 H8 H9 H10.\n\nHint Constructors lc_exp : core lngen.\n\nHint Constructors lc_set_exp : core lngen.\n\n\n(* *********************************************************************** *)\n(** * Body *)\n\nDefinition body_exp_wrt_exp e1 := forall x1, lc_exp (open_exp_wrt_exp e1 (trm_var_f x1)).\n\nHint Unfold body_exp_wrt_exp.\n\n\n(* *********************************************************************** *)\n(** * Tactic support *)\n\n(** Additional hint declarations. *)\n\nHint Resolve @plus_le_compat : lngen.\n\n(** Redefine some tactics. *)\n\nLtac default_case_split ::=\n  first\n    [ progress destruct_notin\n    | progress destruct_sum\n    | progress safe_f_equal\n    ].\n\n\n(* *********************************************************************** *)\n(** * Theorems about [size] *)\n\nLtac default_auto ::= auto with arith lngen; tauto.\nLtac default_autorewrite ::= fail.\n\n(* begin hide *)\n\nLemma size_typ_min_mutual :\n(forall T1, 1 <= size_typ T1).\nProof.\napply_mutual_ind typ_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma size_typ_min :\nforall T1, 1 <= size_typ T1.\nProof.\npose proof size_typ_min_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_typ_min : lngen.\n\n(* begin hide *)\n\nLemma size_co_min_mutual :\n(forall c1, 1 <= size_co c1).\nProof.\napply_mutual_ind co_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma size_co_min :\nforall c1, 1 <= size_co c1.\nProof.\npose proof size_co_min_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_co_min : lngen.\n\n(* begin hide *)\n\nLemma size_exp_min_mutual :\n(forall e1, 1 <= size_exp e1).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma size_exp_min :\nforall e1, 1 <= size_exp e1.\nProof.\npose proof size_exp_min_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_exp_min : lngen.\n\n(* begin hide *)\n\nLemma size_exp_close_exp_wrt_exp_rec_mutual :\n(forall e1 x1 n1,\n  size_exp (close_exp_wrt_exp_rec n1 x1 e1) = size_exp e1).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_exp_close_exp_wrt_exp_rec :\nforall e1 x1 n1,\n  size_exp (close_exp_wrt_exp_rec n1 x1 e1) = size_exp e1.\nProof.\npose proof size_exp_close_exp_wrt_exp_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_exp_close_exp_wrt_exp_rec : lngen.\nHint Rewrite size_exp_close_exp_wrt_exp_rec using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma size_exp_close_exp_wrt_exp :\nforall e1 x1,\n  size_exp (close_exp_wrt_exp x1 e1) = size_exp e1.\nProof.\nunfold close_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve size_exp_close_exp_wrt_exp : lngen.\nHint Rewrite size_exp_close_exp_wrt_exp using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma size_exp_open_exp_wrt_exp_rec_mutual :\n(forall e1 e2 n1,\n  size_exp e1 <= size_exp (open_exp_wrt_exp_rec n1 e2 e1)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_exp_open_exp_wrt_exp_rec :\nforall e1 e2 n1,\n  size_exp e1 <= size_exp (open_exp_wrt_exp_rec n1 e2 e1).\nProof.\npose proof size_exp_open_exp_wrt_exp_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_exp_open_exp_wrt_exp_rec : lngen.\n\n(* end hide *)\n\nLemma size_exp_open_exp_wrt_exp :\nforall e1 e2,\n  size_exp e1 <= size_exp (open_exp_wrt_exp e1 e2).\nProof.\nunfold open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve size_exp_open_exp_wrt_exp : lngen.\n\n(* begin hide *)\n\nLemma size_exp_open_exp_wrt_exp_rec_var_mutual :\n(forall e1 x1 n1,\n  size_exp (open_exp_wrt_exp_rec n1 (trm_var_f x1) e1) = size_exp e1).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma size_exp_open_exp_wrt_exp_rec_var :\nforall e1 x1 n1,\n  size_exp (open_exp_wrt_exp_rec n1 (trm_var_f x1) e1) = size_exp e1.\nProof.\npose proof size_exp_open_exp_wrt_exp_rec_var_mutual as H; intuition eauto.\nQed.\n\nHint Resolve size_exp_open_exp_wrt_exp_rec_var : lngen.\nHint Rewrite size_exp_open_exp_wrt_exp_rec_var using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma size_exp_open_exp_wrt_exp_var :\nforall e1 x1,\n  size_exp (open_exp_wrt_exp e1 (trm_var_f x1)) = size_exp e1.\nProof.\nunfold open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve size_exp_open_exp_wrt_exp_var : lngen.\nHint Rewrite size_exp_open_exp_wrt_exp_var using solve [auto] : lngen.\n\n\n(* *********************************************************************** *)\n(** * Theorems about [degree] *)\n\nLtac default_auto ::= auto with lngen; tauto.\nLtac default_autorewrite ::= fail.\n\n(* begin hide *)\n\nLemma degree_exp_wrt_exp_S_mutual :\n(forall n1 e1,\n  degree_exp_wrt_exp n1 e1 ->\n  degree_exp_wrt_exp (S n1) e1).\nProof.\napply_mutual_ind degree_exp_wrt_exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma degree_exp_wrt_exp_S :\nforall n1 e1,\n  degree_exp_wrt_exp n1 e1 ->\n  degree_exp_wrt_exp (S n1) e1.\nProof.\npose proof degree_exp_wrt_exp_S_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_exp_wrt_exp_S : lngen.\n\nLemma degree_exp_wrt_exp_O :\nforall n1 e1,\n  degree_exp_wrt_exp O e1 ->\n  degree_exp_wrt_exp n1 e1.\nProof.\ninduction n1; default_simp.\nQed.\n\nHint Resolve degree_exp_wrt_exp_O : lngen.\n\n(* begin hide *)\n\nLemma degree_exp_wrt_exp_close_exp_wrt_exp_rec_mutual :\n(forall e1 x1 n1,\n  degree_exp_wrt_exp n1 e1 ->\n  degree_exp_wrt_exp (S n1) (close_exp_wrt_exp_rec n1 x1 e1)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_exp_wrt_exp_close_exp_wrt_exp_rec :\nforall e1 x1 n1,\n  degree_exp_wrt_exp n1 e1 ->\n  degree_exp_wrt_exp (S n1) (close_exp_wrt_exp_rec n1 x1 e1).\nProof.\npose proof degree_exp_wrt_exp_close_exp_wrt_exp_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_exp_wrt_exp_close_exp_wrt_exp_rec : lngen.\n\n(* end hide *)\n\nLemma degree_exp_wrt_exp_close_exp_wrt_exp :\nforall e1 x1,\n  degree_exp_wrt_exp 0 e1 ->\n  degree_exp_wrt_exp 1 (close_exp_wrt_exp x1 e1).\nProof.\nunfold close_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve degree_exp_wrt_exp_close_exp_wrt_exp : lngen.\n\n(* begin hide *)\n\nLemma degree_exp_wrt_exp_close_exp_wrt_exp_rec_inv_mutual :\n(forall e1 x1 n1,\n  degree_exp_wrt_exp (S n1) (close_exp_wrt_exp_rec n1 x1 e1) ->\n  degree_exp_wrt_exp n1 e1).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp; eauto with lngen.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_exp_wrt_exp_close_exp_wrt_exp_rec_inv :\nforall e1 x1 n1,\n  degree_exp_wrt_exp (S n1) (close_exp_wrt_exp_rec n1 x1 e1) ->\n  degree_exp_wrt_exp n1 e1.\nProof.\npose proof degree_exp_wrt_exp_close_exp_wrt_exp_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_exp_wrt_exp_close_exp_wrt_exp_rec_inv : lngen.\n\n(* end hide *)\n\nLemma degree_exp_wrt_exp_close_exp_wrt_exp_inv :\nforall e1 x1,\n  degree_exp_wrt_exp 1 (close_exp_wrt_exp x1 e1) ->\n  degree_exp_wrt_exp 0 e1.\nProof.\nunfold close_exp_wrt_exp; eauto with lngen.\nQed.\n\nHint Immediate degree_exp_wrt_exp_close_exp_wrt_exp_inv : lngen.\n\n(* begin hide *)\n\nLemma degree_exp_wrt_exp_open_exp_wrt_exp_rec_mutual :\n(forall e1 e2 n1,\n  degree_exp_wrt_exp (S n1) e1 ->\n  degree_exp_wrt_exp n1 e2 ->\n  degree_exp_wrt_exp n1 (open_exp_wrt_exp_rec n1 e2 e1)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_exp_wrt_exp_open_exp_wrt_exp_rec :\nforall e1 e2 n1,\n  degree_exp_wrt_exp (S n1) e1 ->\n  degree_exp_wrt_exp n1 e2 ->\n  degree_exp_wrt_exp n1 (open_exp_wrt_exp_rec n1 e2 e1).\nProof.\npose proof degree_exp_wrt_exp_open_exp_wrt_exp_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_exp_wrt_exp_open_exp_wrt_exp_rec : lngen.\n\n(* end hide *)\n\nLemma degree_exp_wrt_exp_open_exp_wrt_exp :\nforall e1 e2,\n  degree_exp_wrt_exp 1 e1 ->\n  degree_exp_wrt_exp 0 e2 ->\n  degree_exp_wrt_exp 0 (open_exp_wrt_exp e1 e2).\nProof.\nunfold open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve degree_exp_wrt_exp_open_exp_wrt_exp : lngen.\n\n(* begin hide *)\n\nLemma degree_exp_wrt_exp_open_exp_wrt_exp_rec_inv_mutual :\n(forall e1 e2 n1,\n  degree_exp_wrt_exp n1 (open_exp_wrt_exp_rec n1 e2 e1) ->\n  degree_exp_wrt_exp (S n1) e1).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp; eauto with lngen.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma degree_exp_wrt_exp_open_exp_wrt_exp_rec_inv :\nforall e1 e2 n1,\n  degree_exp_wrt_exp n1 (open_exp_wrt_exp_rec n1 e2 e1) ->\n  degree_exp_wrt_exp (S n1) e1.\nProof.\npose proof degree_exp_wrt_exp_open_exp_wrt_exp_rec_inv_mutual as H; intuition eauto.\nQed.\n\nHint Immediate degree_exp_wrt_exp_open_exp_wrt_exp_rec_inv : lngen.\n\n(* end hide *)\n\nLemma degree_exp_wrt_exp_open_exp_wrt_exp_inv :\nforall e1 e2,\n  degree_exp_wrt_exp 0 (open_exp_wrt_exp e1 e2) ->\n  degree_exp_wrt_exp 1 e1.\nProof.\nunfold open_exp_wrt_exp; eauto with lngen.\nQed.\n\nHint Immediate degree_exp_wrt_exp_open_exp_wrt_exp_inv : lngen.\n\n\n(* *********************************************************************** *)\n(** * Theorems about [open] and [close] *)\n\nLtac default_auto ::= auto with lngen brute_force; tauto.\nLtac default_autorewrite ::= fail.\n\n(* begin hide *)\n\nLemma close_exp_wrt_exp_rec_inj_mutual :\n(forall e1 e2 x1 n1,\n  close_exp_wrt_exp_rec n1 x1 e1 = close_exp_wrt_exp_rec n1 x1 e2 ->\n  e1 = e2).\nProof.\napply_mutual_ind exp_mutind;\nintros; match goal with\n          | |- _ = ?term => destruct term\n        end;\ndefault_simp; eauto with lngen.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_exp_wrt_exp_rec_inj :\nforall e1 e2 x1 n1,\n  close_exp_wrt_exp_rec n1 x1 e1 = close_exp_wrt_exp_rec n1 x1 e2 ->\n  e1 = e2.\nProof.\npose proof close_exp_wrt_exp_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate close_exp_wrt_exp_rec_inj : lngen.\n\n(* end hide *)\n\nLemma close_exp_wrt_exp_inj :\nforall e1 e2 x1,\n  close_exp_wrt_exp x1 e1 = close_exp_wrt_exp x1 e2 ->\n  e1 = e2.\nProof.\nunfold close_exp_wrt_exp; eauto with lngen.\nQed.\n\nHint Immediate close_exp_wrt_exp_inj : lngen.\n\n(* begin hide *)\n\nLemma close_exp_wrt_exp_rec_open_exp_wrt_exp_rec_mutual :\n(forall e1 x1 n1,\n  x1 `notin` fv_exp e1 ->\n  close_exp_wrt_exp_rec n1 x1 (open_exp_wrt_exp_rec n1 (trm_var_f x1) e1) = e1).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_exp_wrt_exp_rec_open_exp_wrt_exp_rec :\nforall e1 x1 n1,\n  x1 `notin` fv_exp e1 ->\n  close_exp_wrt_exp_rec n1 x1 (open_exp_wrt_exp_rec n1 (trm_var_f x1) e1) = e1.\nProof.\npose proof close_exp_wrt_exp_rec_open_exp_wrt_exp_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_exp_wrt_exp_rec_open_exp_wrt_exp_rec : lngen.\nHint Rewrite close_exp_wrt_exp_rec_open_exp_wrt_exp_rec using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma close_exp_wrt_exp_open_exp_wrt_exp :\nforall e1 x1,\n  x1 `notin` fv_exp e1 ->\n  close_exp_wrt_exp x1 (open_exp_wrt_exp e1 (trm_var_f x1)) = e1.\nProof.\nunfold close_exp_wrt_exp; unfold open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve close_exp_wrt_exp_open_exp_wrt_exp : lngen.\nHint Rewrite close_exp_wrt_exp_open_exp_wrt_exp using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma open_exp_wrt_exp_rec_close_exp_wrt_exp_rec_mutual :\n(forall e1 x1 n1,\n  open_exp_wrt_exp_rec n1 (trm_var_f x1) (close_exp_wrt_exp_rec n1 x1 e1) = e1).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_exp_wrt_exp_rec_close_exp_wrt_exp_rec :\nforall e1 x1 n1,\n  open_exp_wrt_exp_rec n1 (trm_var_f x1) (close_exp_wrt_exp_rec n1 x1 e1) = e1.\nProof.\npose proof open_exp_wrt_exp_rec_close_exp_wrt_exp_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_exp_wrt_exp_rec_close_exp_wrt_exp_rec : lngen.\nHint Rewrite open_exp_wrt_exp_rec_close_exp_wrt_exp_rec using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma open_exp_wrt_exp_close_exp_wrt_exp :\nforall e1 x1,\n  open_exp_wrt_exp (close_exp_wrt_exp x1 e1) (trm_var_f x1) = e1.\nProof.\nunfold close_exp_wrt_exp; unfold open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve open_exp_wrt_exp_close_exp_wrt_exp : lngen.\nHint Rewrite open_exp_wrt_exp_close_exp_wrt_exp using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma open_exp_wrt_exp_rec_inj_mutual :\n(forall e2 e1 x1 n1,\n  x1 `notin` fv_exp e2 ->\n  x1 `notin` fv_exp e1 ->\n  open_exp_wrt_exp_rec n1 (trm_var_f x1) e2 = open_exp_wrt_exp_rec n1 (trm_var_f x1) e1 ->\n  e2 = e1).\nProof.\napply_mutual_ind exp_mutind;\nintros; match goal with\n          | |- _ = ?term => destruct term\n        end;\ndefault_simp; eauto with lngen.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_exp_wrt_exp_rec_inj :\nforall e2 e1 x1 n1,\n  x1 `notin` fv_exp e2 ->\n  x1 `notin` fv_exp e1 ->\n  open_exp_wrt_exp_rec n1 (trm_var_f x1) e2 = open_exp_wrt_exp_rec n1 (trm_var_f x1) e1 ->\n  e2 = e1.\nProof.\npose proof open_exp_wrt_exp_rec_inj_mutual as H; intuition eauto.\nQed.\n\nHint Immediate open_exp_wrt_exp_rec_inj : lngen.\n\n(* end hide *)\n\nLemma open_exp_wrt_exp_inj :\nforall e2 e1 x1,\n  x1 `notin` fv_exp e2 ->\n  x1 `notin` fv_exp e1 ->\n  open_exp_wrt_exp e2 (trm_var_f x1) = open_exp_wrt_exp e1 (trm_var_f x1) ->\n  e2 = e1.\nProof.\nunfold open_exp_wrt_exp; eauto with lngen.\nQed.\n\nHint Immediate open_exp_wrt_exp_inj : lngen.\n\n\n(* *********************************************************************** *)\n(** * Theorems about [lc] *)\n\nLtac default_auto ::= auto with lngen brute_force; tauto.\nLtac default_autorewrite ::= autorewrite with lngen.\n\n(* begin hide *)\n\nLemma degree_exp_wrt_exp_of_lc_exp_mutual :\n(forall e1,\n  lc_exp e1 ->\n  degree_exp_wrt_exp 0 e1).\nProof.\napply_mutual_ind lc_exp_mutind;\nintros;\nlet x1 := fresh \"x1\" in pick_fresh x1;\nrepeat (match goal with\n          | H1 : _, H2 : _ |- _ => specialize H1 with H2\n        end);\ndefault_simp; eauto with lngen.\nQed.\n\n(* end hide *)\n\nLemma degree_exp_wrt_exp_of_lc_exp :\nforall e1,\n  lc_exp e1 ->\n  degree_exp_wrt_exp 0 e1.\nProof.\npose proof degree_exp_wrt_exp_of_lc_exp_mutual as H; intuition eauto.\nQed.\n\nHint Resolve degree_exp_wrt_exp_of_lc_exp : lngen.\n\n(* begin hide *)\n\nLemma lc_exp_of_degree_size_mutual :\nforall i1,\n(forall e1,\n  size_exp e1 = i1 ->\n  degree_exp_wrt_exp 0 e1 ->\n  lc_exp e1).\nProof.\nintros i1; pattern i1; apply lt_wf_rec;\nclear i1; intros i1 H1;\napply_mutual_ind exp_mutind;\ndefault_simp;\n(* non-trivial cases *)\nconstructor; default_simp; eapply_first_lt_hyp;\n(* instantiate the size *)\nmatch goal with\n  | |- _ = _ => reflexivity\n  | _ => idtac\nend;\ninstantiate;\n(* everything should be easy now *)\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma lc_exp_of_degree :\nforall e1,\n  degree_exp_wrt_exp 0 e1 ->\n  lc_exp e1.\nProof.\nintros e1; intros;\npose proof (lc_exp_of_degree_size_mutual (size_exp e1));\nintuition eauto.\nQed.\n\nHint Resolve lc_exp_of_degree : lngen.\n\nLtac typ_lc_exists_tac :=\n  repeat (match goal with\n            | H : _ |- _ =>\n              fail 1\n          end).\n\nLtac co_lc_exists_tac :=\n  repeat (match goal with\n            | H : _ |- _ =>\n              fail 1\n          end).\n\nLtac exp_lc_exists_tac :=\n  repeat (match goal with\n            | H : _ |- _ =>\n              let J1 := fresh in pose proof H as J1; apply degree_exp_wrt_exp_of_lc_exp in J1; clear H\n          end).\n\nLemma lc_trm_abs_exists :\nforall x1 e1,\n  lc_exp (open_exp_wrt_exp e1 (trm_var_f x1)) ->\n  lc_exp (trm_abs e1).\nProof.\nintros; exp_lc_exists_tac; eauto with lngen.\nQed.\n\nHint Extern 1 (lc_exp (trm_abs _)) =>\n  let x1 := fresh in\n  pick_fresh x1;\n  apply (lc_trm_abs_exists x1).\n\nLemma lc_body_exp_wrt_exp :\nforall e1 e2,\n  body_exp_wrt_exp e1 ->\n  lc_exp e2 ->\n  lc_exp (open_exp_wrt_exp e1 e2).\nProof.\nunfold body_exp_wrt_exp;\ndefault_simp;\nlet x1 := fresh \"x\" in\npick_fresh x1;\nspecialize_all x1;\nexp_lc_exists_tac;\neauto with lngen.\nQed.\n\nHint Resolve lc_body_exp_wrt_exp : lngen.\n\nLemma lc_body_trm_abs_1 :\nforall e1,\n  lc_exp (trm_abs e1) ->\n  body_exp_wrt_exp e1.\nProof.\ndefault_simp.\nQed.\n\nHint Resolve lc_body_trm_abs_1 : lngen.\n\n(* begin hide *)\n\nLemma lc_exp_unique_mutual :\n(forall e1 (proof2 proof3 : lc_exp e1), proof2 = proof3).\nProof.\napply_mutual_ind lc_exp_mutind;\nintros;\nlet proof1 := fresh \"proof1\" in\nrename_last_into proof1; dependent destruction proof1;\nf_equal; default_simp; auto using @functional_extensionality_dep with lngen.\nQed.\n\n(* end hide *)\n\nLemma lc_exp_unique :\nforall e1 (proof2 proof3 : lc_exp e1), proof2 = proof3.\nProof.\npose proof lc_exp_unique_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_exp_unique : lngen.\n\n(* begin hide *)\n\nLemma lc_exp_of_lc_set_exp_mutual :\n(forall e1, lc_set_exp e1 -> lc_exp e1).\nProof.\napply_mutual_ind lc_set_exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma lc_exp_of_lc_set_exp :\nforall e1, lc_set_exp e1 -> lc_exp e1.\nProof.\npose proof lc_exp_of_lc_set_exp_mutual as H; intuition eauto.\nQed.\n\nHint Resolve lc_exp_of_lc_set_exp : lngen.\n\n(* begin hide *)\n\nLemma lc_set_exp_of_lc_exp_size_mutual :\nforall i1,\n(forall e1,\n  size_exp e1 = i1 ->\n  lc_exp e1 ->\n  lc_set_exp e1).\nProof.\nintros i1; pattern i1; apply lt_wf_rec;\nclear i1; intros i1 H1;\napply_mutual_ind exp_mutrec;\ndefault_simp;\ntry solve [assert False by default_simp; tauto];\n(* non-trivial cases *)\nconstructor; default_simp;\ntry first [apply lc_set_co_of_lc_co\n | apply lc_set_exp_of_lc_exp];\ndefault_simp; eapply_first_lt_hyp;\n(* instantiate the size *)\nmatch goal with\n  | |- _ = _ => reflexivity\n  | _ => idtac\nend;\ninstantiate;\n(* everything should be easy now *)\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma lc_set_exp_of_lc_exp :\nforall e1,\n  lc_exp e1 ->\n  lc_set_exp e1.\nProof.\nintros e1; intros;\npose proof (lc_set_exp_of_lc_exp_size_mutual (size_exp e1));\nintuition eauto.\nQed.\n\nHint Resolve lc_set_exp_of_lc_exp : lngen.\n\n\n(* *********************************************************************** *)\n(** * More theorems about [open] and [close] *)\n\nLtac default_auto ::= auto with lngen; tauto.\nLtac default_autorewrite ::= fail.\n\n(* begin hide *)\n\nLemma close_exp_wrt_exp_rec_degree_exp_wrt_exp_mutual :\n(forall e1 x1 n1,\n  degree_exp_wrt_exp n1 e1 ->\n  x1 `notin` fv_exp e1 ->\n  close_exp_wrt_exp_rec n1 x1 e1 = e1).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma close_exp_wrt_exp_rec_degree_exp_wrt_exp :\nforall e1 x1 n1,\n  degree_exp_wrt_exp n1 e1 ->\n  x1 `notin` fv_exp e1 ->\n  close_exp_wrt_exp_rec n1 x1 e1 = e1.\nProof.\npose proof close_exp_wrt_exp_rec_degree_exp_wrt_exp_mutual as H; intuition eauto.\nQed.\n\nHint Resolve close_exp_wrt_exp_rec_degree_exp_wrt_exp : lngen.\nHint Rewrite close_exp_wrt_exp_rec_degree_exp_wrt_exp using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma close_exp_wrt_exp_lc_exp :\nforall e1 x1,\n  lc_exp e1 ->\n  x1 `notin` fv_exp e1 ->\n  close_exp_wrt_exp x1 e1 = e1.\nProof.\nunfold close_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve close_exp_wrt_exp_lc_exp : lngen.\nHint Rewrite close_exp_wrt_exp_lc_exp using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma open_exp_wrt_exp_rec_degree_exp_wrt_exp_mutual :\n(forall e2 e1 n1,\n  degree_exp_wrt_exp n1 e2 ->\n  open_exp_wrt_exp_rec n1 e1 e2 = e2).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma open_exp_wrt_exp_rec_degree_exp_wrt_exp :\nforall e2 e1 n1,\n  degree_exp_wrt_exp n1 e2 ->\n  open_exp_wrt_exp_rec n1 e1 e2 = e2.\nProof.\npose proof open_exp_wrt_exp_rec_degree_exp_wrt_exp_mutual as H; intuition eauto.\nQed.\n\nHint Resolve open_exp_wrt_exp_rec_degree_exp_wrt_exp : lngen.\nHint Rewrite open_exp_wrt_exp_rec_degree_exp_wrt_exp using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma open_exp_wrt_exp_lc_exp :\nforall e2 e1,\n  lc_exp e2 ->\n  open_exp_wrt_exp e2 e1 = e2.\nProof.\nunfold open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve open_exp_wrt_exp_lc_exp : lngen.\nHint Rewrite open_exp_wrt_exp_lc_exp using solve [auto] : lngen.\n\n\n(* *********************************************************************** *)\n(** * Theorems about [fv] *)\n\nLtac default_auto ::= auto with set lngen; tauto.\nLtac default_autorewrite ::= autorewrite with lngen.\n\n(* begin hide *)\n\nLemma fv_exp_close_exp_wrt_exp_rec_mutual :\n(forall e1 x1 n1,\n  fv_exp (close_exp_wrt_exp_rec n1 x1 e1) [=] remove x1 (fv_exp e1)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_exp_close_exp_wrt_exp_rec :\nforall e1 x1 n1,\n  fv_exp (close_exp_wrt_exp_rec n1 x1 e1) [=] remove x1 (fv_exp e1).\nProof.\npose proof fv_exp_close_exp_wrt_exp_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_exp_close_exp_wrt_exp_rec : lngen.\nHint Rewrite fv_exp_close_exp_wrt_exp_rec using solve [auto] : lngen.\n\n(* end hide *)\n\nLemma fv_exp_close_exp_wrt_exp :\nforall e1 x1,\n  fv_exp (close_exp_wrt_exp x1 e1) [=] remove x1 (fv_exp e1).\nProof.\nunfold close_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve fv_exp_close_exp_wrt_exp : lngen.\nHint Rewrite fv_exp_close_exp_wrt_exp using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma fv_exp_open_exp_wrt_exp_rec_lower_mutual :\n(forall e1 e2 n1,\n  fv_exp e1 [<=] fv_exp (open_exp_wrt_exp_rec n1 e2 e1)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_exp_open_exp_wrt_exp_rec_lower :\nforall e1 e2 n1,\n  fv_exp e1 [<=] fv_exp (open_exp_wrt_exp_rec n1 e2 e1).\nProof.\npose proof fv_exp_open_exp_wrt_exp_rec_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_exp_open_exp_wrt_exp_rec_lower : lngen.\n\n(* end hide *)\n\nLemma fv_exp_open_exp_wrt_exp_lower :\nforall e1 e2,\n  fv_exp e1 [<=] fv_exp (open_exp_wrt_exp e1 e2).\nProof.\nunfold open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve fv_exp_open_exp_wrt_exp_lower : lngen.\n\n(* begin hide *)\n\nLemma fv_exp_open_exp_wrt_exp_rec_upper_mutual :\n(forall e1 e2 n1,\n  fv_exp (open_exp_wrt_exp_rec n1 e2 e1) [<=] fv_exp e2 `union` fv_exp e1).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma fv_exp_open_exp_wrt_exp_rec_upper :\nforall e1 e2 n1,\n  fv_exp (open_exp_wrt_exp_rec n1 e2 e1) [<=] fv_exp e2 `union` fv_exp e1.\nProof.\npose proof fv_exp_open_exp_wrt_exp_rec_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_exp_open_exp_wrt_exp_rec_upper : lngen.\n\n(* end hide *)\n\nLemma fv_exp_open_exp_wrt_exp_upper :\nforall e1 e2,\n  fv_exp (open_exp_wrt_exp e1 e2) [<=] fv_exp e2 `union` fv_exp e1.\nProof.\nunfold open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve fv_exp_open_exp_wrt_exp_upper : lngen.\n\n(* begin hide *)\n\nLemma fv_exp_subst_exp_fresh_mutual :\n(forall e1 e2 x1,\n  x1 `notin` fv_exp e1 ->\n  fv_exp (subst_exp e2 x1 e1) [=] fv_exp e1).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_exp_subst_exp_fresh :\nforall e1 e2 x1,\n  x1 `notin` fv_exp e1 ->\n  fv_exp (subst_exp e2 x1 e1) [=] fv_exp e1.\nProof.\npose proof fv_exp_subst_exp_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_exp_subst_exp_fresh : lngen.\nHint Rewrite fv_exp_subst_exp_fresh using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma fv_exp_subst_exp_lower_mutual :\n(forall e1 e2 x1,\n  remove x1 (fv_exp e1) [<=] fv_exp (subst_exp e2 x1 e1)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_exp_subst_exp_lower :\nforall e1 e2 x1,\n  remove x1 (fv_exp e1) [<=] fv_exp (subst_exp e2 x1 e1).\nProof.\npose proof fv_exp_subst_exp_lower_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_exp_subst_exp_lower : lngen.\n\n(* begin hide *)\n\nLemma fv_exp_subst_exp_notin_mutual :\n(forall e1 e2 x1 x2,\n  x2 `notin` fv_exp e1 ->\n  x2 `notin` fv_exp e2 ->\n  x2 `notin` fv_exp (subst_exp e2 x1 e1)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_exp_subst_exp_notin :\nforall e1 e2 x1 x2,\n  x2 `notin` fv_exp e1 ->\n  x2 `notin` fv_exp e2 ->\n  x2 `notin` fv_exp (subst_exp e2 x1 e1).\nProof.\npose proof fv_exp_subst_exp_notin_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_exp_subst_exp_notin : lngen.\n\n(* begin hide *)\n\nLemma fv_exp_subst_exp_upper_mutual :\n(forall e1 e2 x1,\n  fv_exp (subst_exp e2 x1 e1) [<=] fv_exp e2 `union` remove x1 (fv_exp e1)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp; fsetdec.\nQed.\n\n(* end hide *)\n\nLemma fv_exp_subst_exp_upper :\nforall e1 e2 x1,\n  fv_exp (subst_exp e2 x1 e1) [<=] fv_exp e2 `union` remove x1 (fv_exp e1).\nProof.\npose proof fv_exp_subst_exp_upper_mutual as H; intuition eauto.\nQed.\n\nHint Resolve fv_exp_subst_exp_upper : lngen.\n\n\n(* *********************************************************************** *)\n(** * Theorems about [subst] *)\n\nLtac default_auto ::= auto with lngen brute_force; tauto.\nLtac default_autorewrite ::= autorewrite with lngen.\n\n(* begin hide *)\n\nLemma subst_exp_close_exp_wrt_exp_rec_mutual :\n(forall e2 e1 x1 x2 n1,\n  degree_exp_wrt_exp n1 e1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_exp e1 ->\n  subst_exp e1 x1 (close_exp_wrt_exp_rec n1 x2 e2) = close_exp_wrt_exp_rec n1 x2 (subst_exp e1 x1 e2)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_exp_close_exp_wrt_exp_rec :\nforall e2 e1 x1 x2 n1,\n  degree_exp_wrt_exp n1 e1 ->\n  x1 <> x2 ->\n  x2 `notin` fv_exp e1 ->\n  subst_exp e1 x1 (close_exp_wrt_exp_rec n1 x2 e2) = close_exp_wrt_exp_rec n1 x2 (subst_exp e1 x1 e2).\nProof.\npose proof subst_exp_close_exp_wrt_exp_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_exp_close_exp_wrt_exp_rec : lngen.\n\nLemma subst_exp_close_exp_wrt_exp :\nforall e2 e1 x1 x2,\n  lc_exp e1 ->  x1 <> x2 ->\n  x2 `notin` fv_exp e1 ->\n  subst_exp e1 x1 (close_exp_wrt_exp x2 e2) = close_exp_wrt_exp x2 (subst_exp e1 x1 e2).\nProof.\nunfold close_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve subst_exp_close_exp_wrt_exp : lngen.\n\n(* begin hide *)\n\nLemma subst_exp_degree_exp_wrt_exp_mutual :\n(forall e1 e2 x1 n1,\n  degree_exp_wrt_exp n1 e1 ->\n  degree_exp_wrt_exp n1 e2 ->\n  degree_exp_wrt_exp n1 (subst_exp e2 x1 e1)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_exp_degree_exp_wrt_exp :\nforall e1 e2 x1 n1,\n  degree_exp_wrt_exp n1 e1 ->\n  degree_exp_wrt_exp n1 e2 ->\n  degree_exp_wrt_exp n1 (subst_exp e2 x1 e1).\nProof.\npose proof subst_exp_degree_exp_wrt_exp_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_exp_degree_exp_wrt_exp : lngen.\n\n(* begin hide *)\n\nLemma subst_exp_fresh_eq_mutual :\n(forall e2 e1 x1,\n  x1 `notin` fv_exp e2 ->\n  subst_exp e1 x1 e2 = e2).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_exp_fresh_eq :\nforall e2 e1 x1,\n  x1 `notin` fv_exp e2 ->\n  subst_exp e1 x1 e2 = e2.\nProof.\npose proof subst_exp_fresh_eq_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_exp_fresh_eq : lngen.\nHint Rewrite subst_exp_fresh_eq using solve [auto] : lngen.\n\n(* begin hide *)\n\nLemma subst_exp_fresh_same_mutual :\n(forall e2 e1 x1,\n  x1 `notin` fv_exp e1 ->\n  x1 `notin` fv_exp (subst_exp e1 x1 e2)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_exp_fresh_same :\nforall e2 e1 x1,\n  x1 `notin` fv_exp e1 ->\n  x1 `notin` fv_exp (subst_exp e1 x1 e2).\nProof.\npose proof subst_exp_fresh_same_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_exp_fresh_same : lngen.\n\n(* begin hide *)\n\nLemma subst_exp_fresh_mutual :\n(forall e2 e1 x1 x2,\n  x1 `notin` fv_exp e2 ->\n  x1 `notin` fv_exp e1 ->\n  x1 `notin` fv_exp (subst_exp e1 x2 e2)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_exp_fresh :\nforall e2 e1 x1 x2,\n  x1 `notin` fv_exp e2 ->\n  x1 `notin` fv_exp e1 ->\n  x1 `notin` fv_exp (subst_exp e1 x2 e2).\nProof.\npose proof subst_exp_fresh_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_exp_fresh : lngen.\n\nLemma subst_exp_lc_exp :\nforall e1 e2 x1,\n  lc_exp e1 ->\n  lc_exp e2 ->\n  lc_exp (subst_exp e2 x1 e1).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_exp_lc_exp : lngen.\n\n(* begin hide *)\n\nLemma subst_exp_open_exp_wrt_exp_rec_mutual :\n(forall e3 e1 e2 x1 n1,\n  lc_exp e1 ->\n  subst_exp e1 x1 (open_exp_wrt_exp_rec n1 e2 e3) = open_exp_wrt_exp_rec n1 (subst_exp e1 x1 e2) (subst_exp e1 x1 e3)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_exp_open_exp_wrt_exp_rec :\nforall e3 e1 e2 x1 n1,\n  lc_exp e1 ->\n  subst_exp e1 x1 (open_exp_wrt_exp_rec n1 e2 e3) = open_exp_wrt_exp_rec n1 (subst_exp e1 x1 e2) (subst_exp e1 x1 e3).\nProof.\npose proof subst_exp_open_exp_wrt_exp_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_exp_open_exp_wrt_exp_rec : lngen.\n\n(* end hide *)\n\nLemma subst_exp_open_exp_wrt_exp :\nforall e3 e1 e2 x1,\n  lc_exp e1 ->\n  subst_exp e1 x1 (open_exp_wrt_exp e3 e2) = open_exp_wrt_exp (subst_exp e1 x1 e3) (subst_exp e1 x1 e2).\nProof.\nunfold open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve subst_exp_open_exp_wrt_exp : lngen.\n\nLemma subst_exp_open_exp_wrt_exp_var :\nforall e2 e1 x1 x2,\n  x1 <> x2 ->\n  lc_exp e1 ->\n  open_exp_wrt_exp (subst_exp e1 x1 e2) (trm_var_f x2) = subst_exp e1 x1 (open_exp_wrt_exp e2 (trm_var_f x2)).\nProof.\nintros; rewrite subst_exp_open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve subst_exp_open_exp_wrt_exp_var : lngen.\n\n(* begin hide *)\n\nLemma subst_exp_spec_rec_mutual :\n(forall e1 e2 x1 n1,\n  subst_exp e2 x1 e1 = open_exp_wrt_exp_rec n1 e2 (close_exp_wrt_exp_rec n1 x1 e1)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_exp_spec_rec :\nforall e1 e2 x1 n1,\n  subst_exp e2 x1 e1 = open_exp_wrt_exp_rec n1 e2 (close_exp_wrt_exp_rec n1 x1 e1).\nProof.\npose proof subst_exp_spec_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_exp_spec_rec : lngen.\n\n(* end hide *)\n\nLemma subst_exp_spec :\nforall e1 e2 x1,\n  subst_exp e2 x1 e1 = open_exp_wrt_exp (close_exp_wrt_exp x1 e1) e2.\nProof.\nunfold close_exp_wrt_exp; unfold open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve subst_exp_spec : lngen.\n\n(* begin hide *)\n\nLemma subst_exp_subst_exp_mutual :\n(forall e1 e2 e3 x2 x1,\n  x2 `notin` fv_exp e2 ->\n  x2 <> x1 ->\n  subst_exp e2 x1 (subst_exp e3 x2 e1) = subst_exp (subst_exp e2 x1 e3) x2 (subst_exp e2 x1 e1)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_exp_subst_exp :\nforall e1 e2 e3 x2 x1,\n  x2 `notin` fv_exp e2 ->\n  x2 <> x1 ->\n  subst_exp e2 x1 (subst_exp e3 x2 e1) = subst_exp (subst_exp e2 x1 e3) x2 (subst_exp e2 x1 e1).\nProof.\npose proof subst_exp_subst_exp_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_exp_subst_exp : lngen.\n\n(* begin hide *)\n\nLemma subst_exp_close_exp_wrt_exp_rec_open_exp_wrt_exp_rec_mutual :\n(forall e2 e1 x1 x2 n1,\n  x2 `notin` fv_exp e2 ->\n  x2 `notin` fv_exp e1 ->\n  x2 <> x1 ->\n  degree_exp_wrt_exp n1 e1 ->\n  subst_exp e1 x1 e2 = close_exp_wrt_exp_rec n1 x2 (subst_exp e1 x1 (open_exp_wrt_exp_rec n1 (trm_var_f x2) e2))).\nProof.\napply_mutual_ind exp_mutrec;\ndefault_simp.\nQed.\n\n(* end hide *)\n\n(* begin hide *)\n\nLemma subst_exp_close_exp_wrt_exp_rec_open_exp_wrt_exp_rec :\nforall e2 e1 x1 x2 n1,\n  x2 `notin` fv_exp e2 ->\n  x2 `notin` fv_exp e1 ->\n  x2 <> x1 ->\n  degree_exp_wrt_exp n1 e1 ->\n  subst_exp e1 x1 e2 = close_exp_wrt_exp_rec n1 x2 (subst_exp e1 x1 (open_exp_wrt_exp_rec n1 (trm_var_f x2) e2)).\nProof.\npose proof subst_exp_close_exp_wrt_exp_rec_open_exp_wrt_exp_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_exp_close_exp_wrt_exp_rec_open_exp_wrt_exp_rec : lngen.\n\n(* end hide *)\n\nLemma subst_exp_close_exp_wrt_exp_open_exp_wrt_exp :\nforall e2 e1 x1 x2,\n  x2 `notin` fv_exp e2 ->\n  x2 `notin` fv_exp e1 ->\n  x2 <> x1 ->\n  lc_exp e1 ->\n  subst_exp e1 x1 e2 = close_exp_wrt_exp x2 (subst_exp e1 x1 (open_exp_wrt_exp e2 (trm_var_f x2))).\nProof.\nunfold close_exp_wrt_exp; unfold open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve subst_exp_close_exp_wrt_exp_open_exp_wrt_exp : lngen.\n\nLemma subst_exp_trm_abs :\nforall x2 e2 e1 x1,\n  lc_exp e1 ->\n  x2 `notin` fv_exp e1 `union` fv_exp e2 `union` singleton x1 ->\n  subst_exp e1 x1 (trm_abs e2) = trm_abs (close_exp_wrt_exp x2 (subst_exp e1 x1 (open_exp_wrt_exp e2 (trm_var_f x2)))).\nProof.\ndefault_simp.\nQed.\n\nHint Resolve subst_exp_trm_abs : lngen.\n\n(* begin hide *)\n\nLemma subst_exp_intro_rec_mutual :\n(forall e1 x1 e2 n1,\n  x1 `notin` fv_exp e1 ->\n  open_exp_wrt_exp_rec n1 e2 e1 = subst_exp e2 x1 (open_exp_wrt_exp_rec n1 (trm_var_f x1) e1)).\nProof.\napply_mutual_ind exp_mutind;\ndefault_simp.\nQed.\n\n(* end hide *)\n\nLemma subst_exp_intro_rec :\nforall e1 x1 e2 n1,\n  x1 `notin` fv_exp e1 ->\n  open_exp_wrt_exp_rec n1 e2 e1 = subst_exp e2 x1 (open_exp_wrt_exp_rec n1 (trm_var_f x1) e1).\nProof.\npose proof subst_exp_intro_rec_mutual as H; intuition eauto.\nQed.\n\nHint Resolve subst_exp_intro_rec : lngen.\nHint Rewrite subst_exp_intro_rec using solve [auto] : lngen.\n\nLemma subst_exp_intro :\nforall x1 e1 e2,\n  x1 `notin` fv_exp e1 ->\n  open_exp_wrt_exp e1 e2 = subst_exp e2 x1 (open_exp_wrt_exp e1 (trm_var_f x1)).\nProof.\nunfold open_exp_wrt_exp; default_simp.\nQed.\n\nHint Resolve subst_exp_intro : lngen.\n\n\n(* *********************************************************************** *)\n(** * \"Restore\" tactics *)\n\nLtac default_auto ::= auto; tauto.\nLtac default_autorewrite ::= fail.\n", "meta": {"author": "bixuanzju", "repo": "nested-composition", "sha": "ad28fa624959b2196b95bd407d3dae2c481c118b", "save_path": "github-repos/coq/bixuanzju-nested-composition", "path": "github-repos/coq/bixuanzju-nested-composition/nested-composition-ad28fa624959b2196b95bd407d3dae2c481c118b/coq/target_inf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.21261925810785234}}
{"text": "\n\nRequire Export oeuf.HList oeuf.Utopia oeuf.SourceLifted oeuf.SourceValues oeuf.CompilationUnit.\nRequire Export OeufPlugin.OeufPlugin.\nRequire Export oeuf.Common oeuf.EricTact.\nRequire oeuf.Pretty.\n\nRequire Export compcert.lib.Coqlib.\n\nRequire Import List.\nImport ListNotations.\n\nDefinition cu_denote\n{a b : SourceLifted.type }\n{ttypes : list\n              (SourceLifted.type *\n               list SourceLifted.type *\n               SourceLifted.type)}\n    (exprs : genv ((a,[],b) :: ttypes)) \n\n:=\n  hhead (genv_denote exprs) hnil.\n\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/demos/word_freq/src/OeufDefs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.21261925810785232}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nFrom Fairness Require Import Axioms WFLibLarge ITreeLib.\nFrom Fairness Require Export Event.\nFrom Coq Require Import Classes.RelationClasses.\n\nSet Implicit Arguments.\n\nSection OBS.\n\n  Variant obsE: Type :=\n    | obsE_syscall (fn: nat) (args: list nat) (retv: nat)\n  .\n\nEnd OBS.\n\nModule Tr.\n  CoInductive t {R}: Type :=\n  | done (retv: R)\n  | spin\n  | ub\n  | nb\n  | cons (hd: obsE) (tl: t)\n  .\n  Infix \"##\" := cons (at level 60, right associativity).\n\n  Fixpoint app {R} (pre: list obsE) (bh: @t R): t :=\n    match pre with\n    | [] => bh\n    | hd :: tl => cons hd (app tl bh)\n    end\n  .\n\n  Lemma fold_app\n        R s pre tl\n    :\n      (cons s (app pre tl)) = @app R (s :: pre) tl\n  .\n  Proof. reflexivity. Qed.\n\n  Definition prefix {R} (pre: list obsE) (bh: @t R): Prop :=\n    exists tl, <<PRE: app pre tl = bh>>\n  .\n\n  Definition ob R (s: @t R): t :=\n    match s with\n    | done retv => done retv\n    | spin => spin\n    | ub => ub\n    | nb => nb\n    | cons obs tl => cons obs tl\n    end.\n\n  Lemma ob_eq : forall R (s: @t R), s = ob s.\n    destruct s; reflexivity.\n  Qed.\n\n\n  (** tr equivalence *)\n  Variant _eq\n          (eq: forall R, (@t R) -> (@t R) -> Prop)\n          R\n    :\n    (@t R) -> (@t R) -> Prop :=\n    | eq_done\n        retv\n      :\n      _eq eq (done retv) (done retv)\n    | eq_spin\n      :\n      _eq eq spin spin\n    | eq_ub\n      :\n      _eq eq ub ub\n    | eq_nb\n      :\n      _eq eq nb nb\n    | eq_obs\n        obs tl1 tl2\n        (TL: eq _ tl1 tl2)\n      :\n      _eq eq (cons obs tl1) (cons obs tl2)\n  .\n\n  Definition eq: forall (R: Type), (@t R) -> (@t R) -> Prop := paco3 _eq bot3.\n\n  Lemma eq_mon: monotone3 _eq.\n  Proof.\n    ii. inv IN. all: econs; eauto.\n  Qed.\n\n  Local Hint Resolve Tr.eq_mon: paco.\n\n  Global Program Instance eq_equiv {R}: Equivalence (@eq R).\n  Next Obligation.\n    pcofix CIH. i. destruct x; try (pfold; econs; eauto).\n  Qed.\n  Next Obligation.\n    pcofix CIH. i.\n    unfold eq in H0. punfold H0.\n    inv H0.\n    1,2,3,4: pfold; econs; eauto.\n    - pfold. econs; eauto. right. eapply CIH. pclearbot. auto.\n  Qed.\n  Next Obligation.\n    pcofix CIH. i.\n    unfold eq in H0, H1. punfold H0. punfold H1. inv H0; inv H1.\n    1,2,3,4: pfold; econs; eauto.\n    pclearbot. pfold. econs. right. eapply CIH; eauto.\n  Qed.\n\nEnd Tr.\n#[export] Hint Constructors Tr._eq: core.\n#[export] Hint Unfold Tr.eq: core.\n#[export] Hint Resolve Tr.eq_mon: paco.\n#[export] Hint Resolve cpn3_wcompat: paco.\n\nSection STS.\n\n  Definition state {id} {R} := itree (@eventE id) R.\n\n  (* Context {Ident: ID}. *)\n  Variable id: ID.\n  Variable wf: WF.\n\n  Definition imap := id -> wf.(T).\n\n  Definition soft_update (m0 m1: imap): Prop :=\n    forall i, wf.(le) (m1 i) (m0 i).\n\n  Global Program Instance soft_update_Reflexive: Reflexive soft_update.\n  Next Obligation.\n    ii. reflexivity.\n  Qed.\n\n  Definition fair_update (m0 m1: imap) (f: fmap id): Prop :=\n    forall i, match f i with\n         | Flag.fail => wf.(lt) (m1 i) (m0 i)\n         | Flag.emp => (m1 i) = (m0 i)\n         | Flag.success => True\n         end.\n\nEnd STS.\n\nModule Beh.\n\nDefinition t {R}: Type := @Tr.t R -> Prop.\n(* Definition improves {R} (src tgt: @t R): Prop := tgt <1= src. *)\n\nSection BEHAVES.\n\n  (* Context {Ident: ID}. *)\n  Variable id: ID.\n  Variable wf: WF.\n\n  Variant _diverge_index\n          (diverge_index: forall (R: Type) (idx: imap id wf) (itr: @state _ R), Prop)\n          (R: Type)\n    :\n    forall (idx: imap id wf) (itr: @state _ R), Prop :=\n    | diverge_index_tau\n        itr idx0\n        (DIV: diverge_index _ idx0 itr)\n      :\n      _diverge_index diverge_index idx0 (Tau itr)\n    | diverge_index_choose\n        X ktr x idx0\n        (DIV: diverge_index _ idx0 (ktr x))\n      :\n      _diverge_index diverge_index idx0 (Vis (Choose X) ktr)\n    | diverge_index_fair\n        fmap ktr idx0 idx1\n        (DIV: diverge_index _ idx1 (ktr tt))\n        (FAIR: fair_update idx0 idx1 fmap)\n      :\n      _diverge_index diverge_index idx0 (Vis (Fair fmap) ktr)\n    | diverge_index_ub\n        ktr idx0\n      :\n      _diverge_index diverge_index idx0 (Vis Undefined ktr)\n  .\n\n  Lemma diverge_index_mon: monotone3 _diverge_index.\n  Proof.\n    ii. inv IN.\n    - econs 1; eauto.\n    - econs 2; eauto.\n    - econs 3; eauto.\n    - econs 4; eauto.\n  Qed.\n\n  Definition diverge_index: forall (R: Type) (idx: imap id wf) (itr: state), Prop := paco3 _diverge_index bot3.\n\n  Hint Constructors _diverge_index: core.\n  Hint Unfold diverge_index: core.\n  Hint Resolve diverge_index_mon: paco.\n  Hint Resolve cpn3_wcompat: paco.\n\n  Definition diverge (R: Type) (itr: @state _ R): Prop :=\n    exists idx, diverge_index idx itr.\n\n\n\n  Inductive _of_state\n            (of_state: forall (R: Type), (imap id wf) -> (@state _ R) -> (@Tr.t R) -> Prop)\n            (R: Type)\n    :\n    (imap id wf) -> (@state _ R) -> Tr.t -> Prop :=\n  | done\n      imap0 retv\n    :\n    _of_state of_state imap0 (Ret retv) (Tr.done retv)\n  | spin\n      imap0 st0\n      (SPIN: diverge_index imap0 st0)\n    :\n    _of_state of_state imap0 st0 (Tr.spin)\n  | nb\n      imap0 st0\n    :\n    _of_state of_state imap0 st0 (Tr.nb)\n  | obs\n      imap0 fn args rv ktr tl\n      (TL: of_state _ imap0 (ktr rv) tl)\n    :\n    _of_state of_state imap0 (Vis (Observe fn args) ktr) (Tr.cons (obsE_syscall fn args rv) tl)\n\n  | tau\n      imap0 itr tr\n      (STEP: _of_state of_state imap0 itr tr)\n    :\n    _of_state of_state imap0 (Tau itr) tr\n  | choose\n      imap0 X ktr x tr\n      (STEP: _of_state of_state imap0 (ktr x) tr)\n    :\n    _of_state of_state imap0 (Vis (Choose X) ktr) tr\n  | fair\n      imap0 imap1 fmap ktr tr\n      (STEP: _of_state of_state imap1 (ktr tt) tr)\n      (FMAP: fair_update imap0 imap1 fmap)\n    :\n    _of_state of_state imap0 (Vis (Fair fmap) ktr) tr\n\n  | ub\n      imap0 ktr tr\n    :\n    _of_state of_state imap0 (Vis Undefined ktr) tr\n  .\n\n  Definition of_state: forall (R: Type),  (imap id wf) -> state -> Tr.t -> Prop := paco4 _of_state bot4.\n\n  Theorem of_state_ind:\n    forall (r: forall (R: Type), (imap id wf) -> state -> Tr.t -> Prop) R (P: (imap id wf) -> state -> Tr.t -> Prop),\n      (forall imap0 retv, P imap0 (Ret retv) (Tr.done retv)) ->\n      (forall imap0 st0, diverge_index imap0 st0 -> P imap0 st0 Tr.spin) ->\n      (forall imap0 st0, P imap0 st0 Tr.nb) ->\n      (forall imap0 fn args rv ktr tl\n         (TL: r _ imap0 (ktr rv) tl)\n        ,\n          P imap0 (Vis (Observe fn args) ktr) (Tr.cons (obsE_syscall fn args rv) tl)) ->\n      (forall imap0 itr tr\n         (STEP: _of_state r imap0 itr tr)\n         (IH: P imap0 itr tr)\n        ,\n          P imap0 (Tau itr) tr) ->\n      (forall imap0 X ktr x tr\n         (STEP: _of_state r imap0 (ktr x) tr)\n         (IH: P imap0 (ktr x) tr)\n        ,\n          P imap0 (Vis (Choose X) ktr) tr) ->\n      (forall imap0 imap1 fmap ktr tr\n         (STEP: _of_state r imap1 (ktr tt) tr)\n         (FAIR: fair_update imap0 imap1 fmap)\n         (IH: P imap1 (ktr tt) tr)\n        ,\n          P imap0 (Vis (Fair fmap) ktr) tr) ->\n      (forall imap0 ktr tr, P imap0 (Vis Undefined ktr) tr) ->\n      forall i s t, @_of_state r R i s t -> P i s t.\n  Proof.\n    fix IH 15. i.\n    inv H7; eauto.\n    - eapply H3; eauto. eapply IH; eauto.\n    - eapply H4; eauto. eapply IH; eauto.\n    - eapply H5; eauto. eapply IH; eauto.\n  Qed.\n\n  Lemma of_state_mon: monotone4 _of_state.\n  Proof.\n    ii. induction IN using of_state_ind; eauto.\n    - econs 1; eauto.\n    - econs 2; eauto.\n    - econs 3; eauto.\n    - econs 4; eauto.\n    - econs 5; eauto.\n    - econs 6; eauto.\n    - econs 7; eauto.\n    - econs 8; eauto.\n  Qed.\n\n  Hint Constructors _of_state: core.\n  Hint Unfold of_state: core.\n  Hint Resolve of_state_mon: paco.\n  Hint Resolve cpn4_wcompat: paco.\n\n  (****************************************************)\n  (*********************** upto ***********************)\n  (****************************************************)\n\n  Variant diverge_imap_le_ctx\n          (diverge_index: forall R, (imap id wf) -> (@state id R) -> Prop)\n          R\n    :\n    (imap id wf) -> (@state id R) -> Prop :=\n    | diverge_imap_le_ctx_intro\n        imap0 imap1 st\n        (DIV: @diverge_index R imap1 st)\n        (IMAP: soft_update imap0 imap1)\n      :\n      diverge_imap_le_ctx diverge_index imap0 st.\n\n  Lemma diverge_imap_le_ctx_mon: monotone3 diverge_imap_le_ctx.\n  Proof. ii. inv IN. econs 1; eauto. Qed.\n\n  Hint Resolve diverge_imap_le_ctx_mon: paco.\n\n  Lemma diverge_imap_le_ctx_wrespectful: wrespectful3 _diverge_index diverge_imap_le_ctx.\n  Proof.\n    econs; eauto with paco.\n    i. inv PR. dup DIV. apply GF in DIV. inv DIV; eauto.\n    { econs 1. eapply rclo3_clo_base. econs 1; eauto. }\n    { econs 2. eapply rclo3_clo_base. econs 1; eauto. }\n    { econs 3. eapply rclo3_clo_base. econs 1. eauto.\n      instantiate (1:=fun i => match fmap i with\n                            | Flag.fail => match excluded_middle_informative (x1 i = imap1 i) with\n                                          | left _ => idx1 i\n                                          | right _ => imap1 i\n                                          end\n                            | Flag.emp => x1 i\n                            | Flag.success => idx1 i\n                            end).\n      - unfold fair_update, soft_update in *. i. specialize (IMAP i). specialize (FAIR i).\n        des_ifs; ss. left; auto. right; auto. rewrite FAIR. auto. left; auto.\n      - unfold fair_update, soft_update in *. i. specialize (IMAP i). specialize (FAIR i).\n        des_ifs. rewrite e. auto. unfold le in IMAP. des; auto. rewrite IMAP in n; ss.\n    }\n  Qed.\n\n  Lemma diverge_imap_le_ctx_spec: diverge_imap_le_ctx <4= gupaco3 _diverge_index (cpn3 _diverge_index).\n  Proof. i. eapply wrespect3_uclo; eauto with paco. eapply diverge_imap_le_ctx_wrespectful. Qed.\n\n\n\n  Variant imap_le_ctx\n          (of_state: forall R, (imap id wf) -> (@state id R) -> (@Tr.t R) -> Prop)\n          R\n    :\n    (imap id wf) -> (@state id R) -> (@Tr.t R) -> Prop :=\n    | imap_le_ctx_intro\n        imap0 imap1 st tr\n        (BEH: @of_state R imap1 st tr)\n        (IMAP: soft_update imap0 imap1)\n      :\n      imap_le_ctx of_state imap0 st tr.\n\n  Lemma imap_le_ctx_mon: monotone4 imap_le_ctx.\n  Proof. ii. inv IN. econs 1; eauto. Qed.\n\n  Hint Resolve imap_le_ctx_mon: paco.\n\n  Lemma imap_le_ctx_wrespectful: wrespectful4 _of_state imap_le_ctx.\n  Proof.\n    econs; eauto with paco.\n    i. inv PR. apply GF in BEH. depgen x1. induction BEH; i; eauto.\n    { econs 2. ginit. guclo diverge_imap_le_ctx_spec. econs; eauto. gstep. punfold SPIN.\n      eapply diverge_index_mon; eauto. i. gfinal. pclearbot. auto.\n    }\n    { econs. eapply rclo4_clo_base. econs; eauto. }\n    { econs. eapply IHBEH.\n      instantiate (1:=fun i => match fmap i with\n                            | Flag.fail => match excluded_middle_informative (x1 i = imap0 i) with\n                                          | left _ => imap1 i\n                                          | right _ => imap0 i\n                                          end\n                            | Flag.emp => x1 i\n                            | Flag.success => imap1 i\n                            end).\n      - unfold fair_update, soft_update in *. i. specialize (IMAP i). specialize (FMAP i).\n        des_ifs; ss. left; auto. right; auto. rewrite FMAP. auto. left; auto.\n      - unfold fair_update, soft_update in *. i. specialize (IMAP i). specialize (FMAP i).\n        des_ifs. rewrite e. auto. unfold le in IMAP. des; auto. rewrite IMAP in n; ss.\n    }\n  Qed.\n\n  Lemma imap_le_ctx_spec: imap_le_ctx <5= gupaco4 _of_state (cpn4 _of_state).\n  Proof. i. eapply wrespect4_uclo; eauto with paco. eapply imap_le_ctx_wrespectful. Qed.\n\n\n\n  Variant of_state_indC\n          (of_state: forall R, (imap id wf) -> (@state _ R) -> (@Tr.t R) -> Prop)\n          R\n    :\n    (imap id wf) -> (@state _ R) -> (@Tr.t R) -> Prop :=\n  | of_state_indC_done\n      imap0 retv\n    :\n    of_state_indC of_state imap0 (Ret retv) (Tr.done retv)\n  | of_state_indC_spin\n      imap0 st0\n      (SPIN: diverge_index imap0 st0)\n    :\n    of_state_indC of_state imap0 st0 (Tr.spin)\n  | of_state_indC_nb\n      imap0 st0\n    :\n    of_state_indC of_state imap0 st0 (Tr.nb)\n  | of_state_indC_obs\n      imap0 fn args rv ktr tl\n      (TL: of_state _ imap0 (ktr rv) tl)\n    :\n    of_state_indC of_state imap0 (Vis (Observe fn args) ktr) (Tr.cons (obsE_syscall fn args rv) tl)\n\n  | of_state_indC_tau\n      imap0 itr tr\n      (STEP: of_state _ imap0 itr tr)\n    :\n    of_state_indC of_state imap0 (Tau itr) tr\n  | of_state_indC_choose\n      imap0 X ktr x tr\n      (STEP: of_state _ imap0 (ktr x) tr)\n    :\n    of_state_indC of_state imap0 (Vis (Choose X) ktr) tr\n  | of_state_indC_fair\n      imap0 imap1 fmap ktr tr\n      (STEP: of_state _ imap1 (ktr tt) tr)\n      (FMAP: fair_update imap0 imap1 fmap)\n    :\n    of_state_indC of_state imap0 (Vis (Fair fmap) ktr) tr\n\n  | of_state_indC_ub\n      imap0 ktr tr\n    :\n    of_state_indC of_state imap0 (Vis Undefined ktr) tr\n  .\n\n  Lemma of_state_indC_mon: monotone4 of_state_indC.\n  Proof. ii. inv IN; econs; eauto. Qed.\n\n  Hint Resolve of_state_indC_mon: paco.\n\n  Lemma of_state_indC_wrespectful: wrespectful4 _of_state of_state_indC.\n  Proof.\n    econs; eauto with paco.\n    i. inv PR; eauto.\n    { econs; eauto. eapply rclo4_base. eauto. }\n    { econs; eauto. eapply of_state_mon; eauto. i. eapply rclo4_base. auto. }\n    { econs; eauto. eapply of_state_mon; eauto. i. eapply rclo4_base. auto. }\n    { econs; eauto. eapply of_state_mon; eauto. i. eapply rclo4_base. auto. }\n  Qed.\n\n  Lemma of_state_indC_spec: of_state_indC <5= gupaco4 _of_state (cpn4 _of_state).\n  Proof. i. eapply wrespect4_uclo; eauto with paco. eapply of_state_indC_wrespectful. Qed.\n\n\n\n  (**********************************************************)\n  (*********************** properties ***********************)\n  (**********************************************************)\n\n  Lemma prefix_closed_state\n        R i0 st0 pre bh\n        (BEH: of_state i0 st0 bh)\n        (PRE: Tr.prefix pre bh)\n    :\n    <<NB: @of_state R i0 st0 (Tr.app pre Tr.nb)>>\n  .\n  Proof.\n    revert_until Ident. pcofix CIH. i. punfold BEH. rr in PRE. des; subst.\n    destruct pre; ss; clarify.\n    { pfold. econs; eauto. }\n    remember (Tr.cons o (Tr.app pre tl)) as tmp. revert Heqtmp.\n    induction BEH using of_state_ind; ii; ss; clarify.\n    - pclearbot. pfold. econs; eauto. right. eapply CIH; eauto. rr; eauto.\n    - pfold. econs 5; eauto. hexploit IHBEH; eauto. intro A. punfold A.\n    - pfold. econs 6; eauto. hexploit IHBEH; eauto. intro A. punfold A.\n    - pfold. econs 7; eauto. hexploit IHBEH; eauto. intro A. punfold A.\n    - pfold. econs 8; eauto.\n  Qed.\n\n  Lemma nb_bottom\n        R i0 st0\n    :\n    <<NB: @of_state R i0 st0 Tr.nb>>\n  .\n  Proof. pfold. econs; eauto. Qed.\n\n  Lemma ub_top\n        R i0 st0\n        (UB: @of_state R i0 st0 Tr.ub)\n    :\n    forall beh, of_state i0 st0 beh\n  .\n  Proof.\n    pfold. i. punfold UB.\n    remember Tr.ub as tmp. revert Heqtmp.\n    induction UB using of_state_ind; ii; ss; clarify.\n    - econs; eauto.\n    - econs 6; eauto.\n    - econs 7; eauto.\n  Qed.\n\n  Lemma beh_tau0\n        R i0 itr tr\n        (BEH: @of_state R i0 itr tr)\n    :\n    <<BEH: of_state i0 (Tau itr) tr>>\n  .\n  Proof.\n    ginit. guclo of_state_indC_spec. econs; eauto. gfinal. eauto.\n  Qed.\n\n  Lemma beh_tau\n        R i0 i1 itr tr\n        (IMAP: soft_update i0 i1)\n        (BEH: @of_state R i1 itr tr)\n    :\n    <<BEH: of_state i0 (Tau itr) tr>>\n  .\n  Proof.\n    ginit. guclo imap_le_ctx_spec. econs; eauto. guclo of_state_indC_spec. econs; eauto. gfinal. eauto.\n  Qed.\n\n  Lemma beh_choose0\n        R i0 X ktr x tr\n        (BEH: @of_state R i0 (ktr x) tr)\n    :\n    <<BEH: of_state i0 (Vis (Choose X) ktr) tr>>\n  .\n  Proof.\n    ginit. guclo of_state_indC_spec. econs; eauto. gfinal. eauto.\n  Qed.\n\n  Lemma beh_choose\n        R i0 i1 X ktr x tr\n        (IMAP: soft_update i0 i1)\n        (BEH: @of_state R i1 (ktr x) tr)\n    :\n    <<BEH: of_state i0 (Vis (Choose X) ktr) tr>>\n  .\n  Proof.\n    ginit. guclo imap_le_ctx_spec. econs; eauto. guclo of_state_indC_spec. econs; eauto. gfinal. eauto.\n  Qed.\n\n  Lemma beh_fair\n        R i0 i1 f ktr tr\n        (FAIR: fair_update i0 i1 f)\n        (BEH: @of_state R i1 (ktr tt) tr)\n    :\n    <<BEH: of_state i0 (Vis (Fair f) ktr) tr>>\n  .\n  Proof.\n    ginit. guclo of_state_indC_spec. econs; eauto. gfinal. eauto.\n  Qed.\n\n\n\n  Theorem of_state_ind2:\n    forall R (P: (imap id wf) -> state -> Tr.t -> Prop),\n      (forall imap0 retv, P imap0 (Ret retv) (Tr.done retv)) ->\n      (forall imap0 st0, diverge_index imap0 st0 -> P imap0 st0 Tr.spin) ->\n      (forall imap0 st0, P imap0 st0 Tr.nb) ->\n      (forall imap0 fn args rv ktr tl\n         (TL: of_state imap0 (ktr rv) tl)\n        ,\n          P imap0 (Vis (Observe fn args) ktr) (Tr.cons (obsE_syscall fn args rv) tl)) ->\n      (forall imap0 itr tr\n         (STEP: of_state imap0 itr tr)\n         (IH: P imap0 itr tr)\n        ,\n          P imap0 (Tau itr) tr) ->\n      (forall imap0 X ktr x tr\n         (STEP: of_state imap0 (ktr x) tr)\n         (IH: P imap0 (ktr x) tr)\n        ,\n          P imap0 (Vis (Choose X) ktr) tr) ->\n      (forall imap0 imap1 fmap ktr tr\n         (STEP: of_state imap1 (ktr tt) tr)\n         (FAIR: fair_update imap0 imap1 fmap)\n         (IH: P imap1 (ktr tt) tr)\n        ,\n          P imap0 (Vis (Fair fmap) ktr) tr) ->\n      (forall imap0 ktr tr, P imap0 (Vis Undefined ktr) tr) ->\n      forall i s t, (@of_state R i s t) -> P i s t.\n  Proof.\n    i. eapply of_state_ind; eauto.\n    { i. eapply H3; eauto. pfold. eapply of_state_mon; eauto. }\n    { i. eapply H4; eauto. pfold. eapply of_state_mon; eauto. }\n    { i. eapply H5; eauto. pfold. eapply of_state_mon; eauto. }\n    { punfold H7. eapply of_state_mon; eauto. i. pclearbot. eauto. }\n  Qed.\n\nEnd BEHAVES.\n\nDefinition improves {ids idt: ID} {wfs wft: WF} {R} (src: @state ids R) (tgt: @state idt R): Prop :=\n  forall tr, (forall (mtgt: @imap idt wft),\n            (exists (msrc: @imap ids wfs), of_state mtgt tgt tr -> of_state msrc src tr)).\n\nEnd Beh.\n#[export] Hint Unfold Beh.improves: core.\n#[export] Hint Constructors Beh._diverge_index: core.\n#[export] Hint Unfold Beh.diverge_index: core.\n#[export] Hint Resolve Beh.diverge_index_mon: paco.\n#[export] Hint Constructors Beh._of_state: core.\n#[export] Hint Unfold Beh.of_state: core.\n#[export] Hint Resolve Beh.of_state_mon: paco.\n\n#[export] Hint Resolve cpn3_wcompat: paco.\n#[export] Hint Resolve cpn4_wcompat: paco.\n\nRequire Import Setoid Morphisms.\n\nGlobal Program Instance Proper_Beh_of_state\n       {id: ID} {wf: WF} {R} (im: imap id wf) (st: @state id R):\n  Proper (Tr.eq (R:=R) ==> flip impl) (Beh.of_state im st).\nNext Obligation.\n  ii. rename H into EQ, H0 into BEH, x into tr1, y into tr2.\n  ginit. revert_until R. gcofix CIH. i.\n  depgen tr1. induction BEH using @Beh.of_state_ind2; i; eauto.\n  { punfold EQ; inv EQ. gfinal; right. pfold. econs. }\n  { punfold EQ; inv EQ. gfinal; right. pfold. econs; eauto. }\n  { punfold EQ; inv EQ. gfinal; right. pfold. econs; eauto. }\n  { punfold EQ; inv EQ. pclearbot. gfinal; right. pfold. econs; eauto. }\n  { guclo Beh.of_state_indC_spec. econs. eauto. }\n  { guclo Beh.of_state_indC_spec. econs. eauto. }\n  { guclo Beh.of_state_indC_spec. econs; eauto. }\n  { guclo Beh.of_state_indC_spec. econs; eauto. }\nQed.\n\n\nRequire Import Program.\n\nSection IMAPAUX1.\n\n  Variable wf: WF.\n\n  Definition imap_proj_id1 {id1 id2: ID} (im: @imap (id_sum id1 id2) wf): @imap id1 wf := fun i => im (inl i).\n  Definition imap_proj_id2 {id1 id2: ID} (im: @imap (id_sum id1 id2) wf): @imap id2 wf := fun i => im (inr i).\n  Definition imap_proj_id {id1 id2: ID} (im: @imap (id_sum id1 id2) wf): prod (@imap id1 wf) (@imap id2 wf) :=\n    (imap_proj_id1 im, imap_proj_id2 im).\n\n  Definition imap_sum_id {id1 id2: ID} (im: prod (@imap id1 wf) (@imap id2 wf)): @imap (id_sum id1 id2) wf :=\n    fun i => match i with | inl il => (fst im) il | inr ir => (snd im) ir end.\n\n  Lemma imap_sum_proj_id_inv1\n        id1 id2\n        (im1: @imap id1 wf)\n        (im2: @imap id2 wf)\n    :\n    imap_proj_id (imap_sum_id (im1, im2)) = (im1, im2).\n  Proof. reflexivity. Qed.\n\n  Lemma imap_sum_proj_id_inv2\n        id1 id2\n        (im: @imap (id_sum id1 id2) wf)\n    :\n    imap_sum_id (imap_proj_id im) = im.\n  Proof. extensionality i. unfold imap_sum_id. des_ifs. Qed.\n\n  Lemma imap_proj_update_l\n        id1 id2 f\n        (im0 im1: @imap (id_sum id1 id2) wf)\n        (UPD: fair_update im0 im1 (prism_fmap inlp f))\n    :\n    (<<LEFT: fair_update (imap_proj_id1 im0) (imap_proj_id1 im1) f>>) /\\\n      (<<RIGHT: imap_proj_id2 im0 = imap_proj_id2 im1>>)\n  .\n  Proof.\n    split.\n    { ii. specialize (UPD (inl i)).\n      unfold prism_fmap in UPD; ss.\n    }\n    { rr. extensionality i. specialize (UPD (inr i)).\n      unfold prism_fmap in UPD; ss.\n    }\n  Qed.\n\n  Lemma imap_proj_update_r\n        id1 id2 f\n        (im0 im1: @imap (id_sum id1 id2) wf)\n        (UPD: fair_update im0 im1 (prism_fmap inrp f))\n    :\n    (<<RIGHT: fair_update (imap_proj_id2 im0) (imap_proj_id2 im1) f>>) /\\\n      (<<LEFT: imap_proj_id1 im0 = imap_proj_id1 im1>>)\n  .\n  Proof.\n    split.\n    { ii. specialize (UPD (inr i)).\n      unfold prism_fmap in UPD; ss.\n    }\n    { rr. extensionality i. specialize (UPD (inl i)).\n      unfold prism_fmap in UPD; ss.\n    }\n  Qed.\nEnd IMAPAUX1.\n\n\nSection IMAPAUX2.\n\n  Variable id: ID.\n\n  Definition imap_proj_wf1 {wf1 wf2: WF} (im: @imap id (double_rel_WF wf1 wf2)): @imap id wf1 := fun i => fst (im i).\n  Definition imap_proj_wf2 {wf1 wf2: WF} (im: @imap id (double_rel_WF wf1 wf2)): @imap id wf2 := fun i => snd (im i).\n  Definition imap_proj_wf {wf1 wf2: WF} (im: @imap id (double_rel_WF wf1 wf2)): prod (@imap id wf1) (@imap id wf2) :=\n    (imap_proj_wf1 im, imap_proj_wf2 im).\n\n  Definition imap_sum_wf {wf1 wf2: WF} (im: prod (@imap id wf1) (@imap id wf2)): @imap id (double_rel_WF wf1 wf2) :=\n    fun i => (fst im i, snd im i).\n\n  Lemma imap_sum_proj_wf_inv1\n        wf1 wf2\n        (im1: @imap id wf1)\n        (im2: @imap id wf2)\n    :\n    imap_proj_wf (imap_sum_wf (im1, im2)) = (im1, im2).\n  Proof. reflexivity. Qed.\n\n  Lemma imap_sum_proj_wf_inv2\n        wf1 wf2\n        (im: @imap id (double_rel_WF wf1 wf2))\n    :\n    imap_sum_wf (imap_proj_wf im) = im.\n  Proof.\n    extensionality i. unfold imap_sum_wf, imap_proj_wf, imap_proj_wf1, imap_proj_wf2. ss. destruct (im i); ss.\n  Qed.\n\nEnd IMAPAUX2.\n\nSection IMAPCOMB.\n\n  Definition imap_comb {id1 id2: ID} {wf1 wf2: WF} (im1: imap id1 wf1) (im2: imap id2 wf2):\n    imap (id_sum id1 id2) (sum_WF wf1 wf2) :=\n    fun i => match i with\n          | inl il => inl (im1 il)\n          | inr ir => inr (im2 ir)\n          end.\n\n  Definition imap_is_comb {id1 id2: ID} {wf1 wf2: WF}\n             (im: imap (id_sum id1 id2) (sum_WF wf1 wf2)) :=\n    exists (im1: imap id1 wf1) (im2: imap id2 wf2), im = imap_comb im1 im2.\n\nEnd IMAPCOMB.\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/src/semantics/FairBeh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.21261925810785232}}
{"text": " (*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n  Copyright 2017 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Vincent Rahli\n\n*)\n\nRequire Export cnterm.\nRequire Export substc_more.\nRequire Export per_props_equality.\nRequire Export cequiv_cnterm.\nRequire Export sequents2.\nRequire Export lsubstc_vars.\n\n\nLemma member_nout_implies {o} :\n  forall lib (t : @CTerm o),\n    member lib t mkc_nout\n    -> {u : CNTerm , ccequivc lib t (cnterm2cterm u)}.\nProof.\n  introv mem.\n  apply equality_in_nout in mem; exrepnd.\n  exists (cterm2cnterm u mem1).\n  autorewrite with slow; auto.\nQed.\n\nLemma member_nout_iff {o} :\n  forall lib (t : @CTerm o),\n    member lib t mkc_nout\n    <=> {u : CNTerm , ccequivc lib t (cnterm2cterm u)}.\nProof.\n  introv; split; intro h; try (apply member_nout_implies; auto);[].\n  exrepnd.\n  apply equality_in_nout.\n  exists (cnterm2cterm u); dands; eauto 3 with slow.\nQed.\n\nLemma reduces_toc_eapply_ntseqc2ntseq {o} :\n  forall lib s (t u : @CTerm o),\n    reduces_toc lib t u\n    -> reduces_toc\n         lib\n         (mkc_eapply (ntseqc2ntseq s) t)\n         (mkc_eapply (ntseqc2ntseq s) u).\nProof.\n  introv r.\n  destruct_cterms.\n  allunfold @reduces_toc; allsimpl.\n  apply implies_eapply_red_aux; eauto 3 with slow.\nQed.\n\nLemma get_cterm_cnterm2cterm_is_ntseqc2seq {o} :\n  forall (f : @ntseqc o) k,\n    get_cterm (cnterm2cterm (f k)) = ntseqc2seq f k.\nProof.\n  introv.\n  unfold cnterm2cterm, ntseqc2seq; simpl.\n  remember (f k) as t; destruct t; simpl; auto.\nQed.\n\nLemma reduces_toc_ntseqc2ntseq_step {o} :\n  forall lib (f : @ntseqc o) k,\n    reduces_toc lib (mkc_eapply (ntseqc2ntseq f) (mkc_nat k)) (cnterm2cterm (f k)).\nProof.\n  introv.\n  unfold reduces_toc; simpl.\n  apply reduces_to_if_step.\n  csunf; simpl.\n  dcwf h; simpl; boolvar; try omega.\n  rewrite Znat.Nat2Z.id.\n  rewrite get_cterm_cnterm2cterm_is_ntseqc2seq; auto.\nQed.\n\nLemma implies_approx_eapply {p} :\n  forall lib f g a b,\n    approx lib f g\n    -> @approx p lib a b\n    -> approx lib (mk_eapply f a) (mk_eapply g b).\nProof.\n  introv H1p H2p.\n  applydup @approx_relates_only_progs in H1p.\n  applydup @approx_relates_only_progs in H2p.\n  repnd.\n  repeat (prove_approx);sp.\nQed.\n\nLemma implies_cequivc_eapply {o} :\n  forall lib (f g a b : @CTerm o),\n    cequivc lib f g\n    -> cequivc lib a b\n    -> cequivc lib (mkc_eapply f a) (mkc_eapply g b).\nProof.\n  unfold cequivc.\n  introv H1c H2c.\n  destruct_cterms.\n  allsimpl.\n  apply isprogram_eq in i0.\n  allrw @isprog_eq.\n  repnud H1c.\n  repnud H2c.\n  repnd.\n  split; apply implies_approx_eapply; auto.\nQed.\n\n\n(*\n\n   forall m : nat, squash (exists n : NUBase, P(m,n))\n\n   implies\n\n   squash (exists f : nat -> NUBase, forall m : nat, squash (P (m, f m)))\n\n *)\nLemma axiom_of_choice_0NUB {o} :\n  forall lib f m n (P : @CTerm o),\n    n <> m\n    -> f <> m\n    -> (forall a b,\n          member lib a mkc_tnat\n          -> member lib b mkc_nout\n          -> type lib (mkc_apply2 P a b))\n    -> inhabited_type\n         lib\n         (mkc_forall\n            mkc_tnat\n            m\n            (mkcv_squash\n               [m]\n               (mkcv_exists\n                  [m]\n                  (mkcv_nout [m])\n                  n\n                  (mkcv_apply2 [n,m]\n                               (mk_cv [n,m] P)\n                               (mk_cv_app_l [n] [m] (mkc_var m))\n                               (mk_cv_app_r [m] [n] (mkc_var n))))))\n    -> inhabited_type\n         lib\n         (mkc_exists\n            nat2nout\n            f\n            (mkcv_forall\n               [f]\n               (mk_cv [f] mkc_tnat)\n               m\n               (mkcv_squash\n                  [m,f]\n                  (mkcv_apply2 [m,f]\n                               (mk_cv [m,f] P)\n                               (mk_cv_app_r [f] [m] (mkc_var m))\n                               (mkcv_apply [m,f]\n                                           (mk_cv_app_l [m] [f] (mkc_var f))\n                                           (mk_cv_app_r [f] [m] (mkc_var m))))))).\nProof.\n  introv d1 d2 impp inh.\n\n  unfold mkc_forall in inh.\n  apply inhabited_function in inh.\n  repnd.\n  clear inh0 inh1.\n  exrepnd.\n\n  assert (forall k : CTerm,\n            member lib k mkc_tnat\n            -> inhabited_type\n                 lib\n                 (mkc_exists\n                    mkc_nout\n                    n\n                    (mkcv_apply2\n                       [n]\n                       (mk_cv [n] P)\n                       (mk_cv [n] k)\n                       (mkc_var n)))) as q.\n  { introv mem.\n    pose proof (inh0 k k) as h.\n    autodimp h hyp.\n    allrw @substc_mkcv_squash.\n    rw @equality_in_mkc_squash in h.\n    repnd.\n    rw @mkcv_exists_substc in h; auto.\n    allrw @mkcv_nout_substc.\n    allrw @substc2_apply2.\n    allrw @substc2_mk_cv_app_l.\n    rw @substc2_mk_cv_app_r in h; auto.\n    allrw @substc2_mk_cv.\n    allrw @mkc_var_substc.\n    auto.\n  }\n  clear inh0.\n\n  assert (forall k : CTerm,\n            member lib k mkc_tnat\n            -> {j : CTerm\n                , member lib j mkc_nout\n                # inhabited_type lib (mkc_apply2 P k j)}) as h.\n  { introv mem.\n    apply q in mem; clear q.\n    apply inhabited_exists in mem; repnd.\n    clear mem0 mem1.\n    exrepnd.\n    exists a; dands; auto.\n    allrw @mkcv_apply2_substc.\n    allrw @csubst_mk_cv.\n    allrw @mkc_var_substc.\n    auto.\n  }\n  clear q.\n\n  (* First use FunctionalChoice_on to get an existential (a Coq function from terms to terms) *)\n\n  pose proof (FunctionalChoice_on\n                {k : CTerm & member lib k mkc_tnat}\n                (@CTerm o)\n                (fun k j =>\n                   member lib j mkc_nout\n                   # inhabited_type lib (mkc_apply2 P (projT1 k) j)))\n    as fc.\n  simphyps.\n  autodimp fc hyp; tcsp;[].\n  exrepnd.\n  clear h.\n  rename fc0 into fc.\n\n  pose proof (FunctionalChoice_on\n                {k : CTerm & member lib k mkc_nout}\n                (@CNTerm o)\n                (fun k j => ((projT1 k) ~=~(lib) (cnterm2cterm j))))\n    as fcn.\n  simphyps.\n  autodimp fcn hyp; tcsp;[sp; simpl; apply member_nout_implies; auto; fail|].\n  exrepnd.\n  rename fcn0 into fcn.\n\n  assert {c : ntseqc\n          & forall a : CTerm,\n              member lib a mkc_tnat\n              -> (member lib (mkc_eapply (ntseqc2ntseq c) a) mkc_nout\n                  # inhabited_type lib (mkc_apply2 P a (mkc_eapply (ntseqc2ntseq c) a)))} as fs.\n  { exists (fun n =>\n              f2 (existT\n                    _\n                    (f1 (existT _ (mkc_nat n) (nat_in_nat lib n)))\n                    (fst (fc (existT _ (mkc_nat n) (nat_in_nat lib n)))))).\n    introv mem.\n    dands.\n\n    - apply member_tnat_iff in mem; exrepnd.\n      allrw @computes_to_valc_iff_reduces_toc; repnd.\n      eapply member_respects_reduces_toc;[apply reduces_toc_eapply_ntseqc2ntseq;exact mem1|].\n\n      eapply member_respects_reduces_toc;\n        [apply reduces_toc_ntseqc2ntseq_step|].\n\n      simpl.\n      apply member_nout_iff.\n      eexists; spcast; apply cequivc_refl.\n\n    - apply member_tnat_iff in mem; exrepnd.\n      pose proof (nat_in_nat lib k) as mk.\n\n      eapply inhabited_type_cequivc;\n        [apply implies_cequivc_apply2;\n          [apply cequivc_refl\n          |apply cequivc_sym;apply computes_to_valc_implies_cequivc;eauto\n          |apply implies_cequivc_eapply;\n            [apply cequivc_refl\n            |apply cequivc_sym;apply computes_to_valc_implies_cequivc;eauto\n            ]\n          ]\n        |].\n\n      eapply inhabited_type_cequivc;\n        [apply implies_cequivc_apply2;\n          [apply cequivc_refl\n          |apply cequivc_refl\n          |apply cequivc_sym;\n            apply reduces_toc_implies_cequivc;\n            apply reduces_toc_ntseqc2ntseq_step\n          ]\n        |].\n      simpl.\n      remember (fc exI(mkc_nat k, nat_in_nat lib k)) as fck.\n      exrepnd.\n      allsimpl.\n\n      pose proof (fcn exI(f1 exI(mkc_nat k, nat_in_nat lib k), fck0)) as xx.\n      simpl in xx; spcast.\n      eapply inhabited_type_cequivc;\n        [apply implies_cequivc_apply2;\n          [apply cequivc_refl\n          |apply cequivc_refl\n          |eauto]\n        |].\n      auto.\n  }\n  clear f1 fc f2 fcn.\n  exrepnd.\n\n  (* then \"convert\" the Coq function into a Nuprl function *)\n\n  apply inhabited_product.\n\n  dands; eauto 3 with slow.\n\n  { introv eqf.\n    unfold mkcv_forall.\n    repeat (rw @substc_mkcv_function; auto).\n    allrw @csubst_mk_cv.\n    apply tequality_function.\n    dands; eauto 3 with slow.\n    { apply tnat_type. }\n\n    introv eqn.\n    allrw @substcv_as_substc2.\n    allrw @substc2_squash.\n    allrw @substc2_apply2.\n    allrw @substc_mkcv_squash.\n    allrw @mkcv_apply2_substc.\n    allrw @substc2_mk_cv.\n    allrw @csubst_mk_cv.\n    repeat (rw @substc2_mk_cv_app_r; auto).\n    allrw @substc2_apply.\n    repeat (rw @substc2_mk_cv_app_l; auto).\n    repeat (rw @substc2_mk_cv_app_r; auto).\n    allrw @mkcv_apply_substc.\n    allrw @mkc_var_substc.\n    allrw @csubst_mk_cv.\n\n    apply tequality_mkc_squash.\n    apply type_respects_cequivc_left.\n\n    { apply implies_cequivc_apply2; auto.\n      { apply equality_int_nat_implies_cequivc; auto.\n        apply equality_sym; auto. }\n      { eapply equality_nat2nout_apply in eqf;[|exact eqn].\n        apply cequiv_stable.\n        apply equality_in_nout in eqf; exrepnd; spcast.\n        eapply cequivc_trans; eauto.\n        apply cequivc_sym; auto. }\n    }\n\n    { apply impp; eauto 3 with slow.\n      { apply equality_sym in eqn; apply equality_refl in eqn; auto. }\n      { eapply equality_nat2nout_apply in eqf;[|exact eqn].\n        apply equality_sym in eqf; apply equality_refl in eqf; auto. }\n    }\n  }\n\n  { exists (ntseqc2ntseq c).\n    unfold mkcv_forall.\n    repeat (rw @substc_mkcv_function; auto).\n    allrw @csubst_mk_cv.\n    allrw @substcv_as_substc2.\n    allrw @substc2_squash.\n    allrw @substc2_apply2.\n    allrw @substc2_mk_cv.\n    repeat (rw @substc2_mk_cv_app_r; auto).\n    allrw @substc2_apply.\n    repeat (rw @substc2_mk_cv_app_l; auto).\n    repeat (rw @substc2_mk_cv_app_r; auto).\n    allrw @mkc_var_substc.\n\n    dands.\n\n    { apply member_ntseqc2ntseq_nat2nout. }\n\n    { apply inhabited_function; dands; eauto 3 with slow.\n\n      - introv eqn.\n        allrw @substc_mkcv_squash.\n        allrw @mkcv_apply2_substc.\n        allrw @mkcv_apply_substc.\n        allrw @csubst_mk_cv.\n        allrw @mkc_var_substc.\n\n        apply tequality_mkc_squash.\n        apply type_respects_cequivc_left.\n\n        { apply implies_cequivc_apply2; auto.\n          { apply equality_int_nat_implies_cequivc; auto.\n            apply equality_sym; auto. }\n          { apply implies_cequivc_apply; auto.\n            apply equality_int_nat_implies_cequivc; auto.\n            apply equality_sym; auto. }\n        }\n\n        { apply impp; eauto 3 with slow.\n          { apply equality_sym in eqn; apply equality_refl in eqn; auto. }\n          { pose proof (member_ntseqc2ntseq_nat2nout lib c) as eqf.\n            eapply equality_nat2nout_apply in eqf;[|exact eqn].\n            apply equality_sym in eqf; apply equality_refl in eqf; auto. }\n        }\n\n      - exists (@mkc_lam o nvarx (mkcv_axiom nvarx)).\n        introv eqn.\n        allrw @substc_mkcv_squash.\n        allrw @mkcv_apply2_substc.\n        allrw @mkcv_apply_substc.\n        allrw @csubst_mk_cv.\n        allrw @mkc_var_substc.\n\n        applydup @equality_int_nat_implies_cequivc in eqn.\n        apply equality_refl in eqn.\n        eapply equality_respects_cequivc_right;\n          [apply implies_cequivc_apply;\n            [apply cequivc_refl\n            |exact eqn0]\n          |].\n        rw @member_eq.\n\n        eapply member_respects_cequivc;\n          [apply cequivc_sym;\n            apply cequivc_beta\n          |].\n        rw @substc_mkcv_axiom.\n\n        apply equality_in_mkc_squash; dands; spcast;\n        try (apply computes_to_valc_refl; eauto 3 with slow).\n\n        pose proof (fs0 a eqn) as q; repnd.\n\n        eapply inhabited_type_cequivc;[|exact q].\n        apply implies_cequivc_apply2; auto.\n        apply cequivc_sym.\n        apply reduces_toc_implies_cequivc.\n        destruct_cterms.\n        unfold reduces_toc; simpl.\n        apply reduces_to_if_step; csunf; simpl; auto.\n    }\n  }\nQed.\n\n\nDefinition rule_AC0NUB {o}\n           (P e : @NTerm o)\n           (f m n : NVar)\n           (H : barehypotheses)\n           (i : nat) :=\n    mk_rule\n      (mk_baresequent H (mk_conclax (mk_squash (mk_exists (mk_nat2nout) f (mk_forall mk_tnat n (mk_squash (mk_apply2 P (mk_var n) (mk_apply (mk_var f) (mk_var n)))))))))\n      [ mk_baresequent H (mk_concl (mk_forall mk_tnat n (mk_squash (mk_exists mk_nout m (mk_apply2 P (mk_var n) (mk_var m))))) e),\n        mk_baresequent H (mk_conclax (mk_member P (mk_fun mk_tnat (mk_fun mk_nout (mk_uni i))))) ]\n      [].\n\nLemma rule_AC0NUB_true3 {p} :\n  forall lib\n         (P e : NTerm)\n         (f m n : NVar)\n         (H : @barehypotheses p)\n         (i : nat)\n         (d1 : n <> m)\n         (d2 : f <> n)\n         (d3 : !LIn f (free_vars P))\n         (d4 : !LIn m (free_vars P))\n         (d5 : !LIn n (free_vars P)),\n    rule_true3 lib (rule_AC0NUB P e f m n H i).\nProof.\n  unfold rule_AC0NUB, rule_true3, wf_bseq, closed_type_baresequent, closed_extract_baresequent; simpl.\n  intros; repnd.\n  clear cargs.\n\n  (* We prove the well-formedness of things *)\n  destseq; allsimpl.\n  dLin_hyp.\n  rename Hyp into hyp1.\n  destruct hyp1 as [wc1 hyp1].\n  rename Hyp0 into hyp2.\n  destruct hyp2 as [wc2 hyp2].\n  destseq; allsimpl; proof_irr; GC.\n\n  assert (wf_csequent ((H)\n                         ||- (mk_conclax\n                                (mk_squash\n                                   (mk_exists\n                                      mk_nat2nout\n                                      f\n                                      (mk_forall\n                                         mk_tnat\n                                         n\n                                         (mk_squash\n                                            (mk_apply2\n                                               P\n                                               (mk_var n)\n                                               (mk_apply\n                                                  (mk_var f)\n                                                  (mk_var n)))))))))) as wfc.\n  { clear hyp1 hyp2.\n    unfold wf_csequent, closed_type, closed_extract, wf_sequent, wf_concl; simpl.\n    dwfseq.\n    rw @vswf_hypotheses_nil_eq.\n    dands; tcsp.\n  }\n\n  exists wfc.\n  unfold wf_csequent, wf_sequent, wf_concl in wfc; allsimpl; repnd; proof_irr; GC.\n\n  vr_seq_true.\n\n  vr_seq_true in hyp1.\n  pose proof (hyp1 s1 s2 eqh sim) as hh; exrepnd; clear hyp1.\n  vr_seq_true in hyp2.\n  pose proof (hyp2 s1 s2 eqh sim) as qq; exrepnd; clear hyp2.\n\n  allunfold @mk_forall.\n  allunfold @mk_exists.\n  allunfold @mk_nat2nout.\n\n  lsubst_tac.\n  allapply @member_if_inhabited.\n  apply tequality_mkc_member_implies_sp in qq0; auto;[].\n  allrw @tequality_mkc_member; repnd.\n\n  lsubst_tac.\n  allrw @lsubstc_mkc_tnat.\n  allrw @lsubstc_mk_nout.\n\n  pose proof (axiom_of_choice_0NUB lib f n m (lsubstc P wt s1 ct1)) as ac.\n  repeat (autodimp ac hyp).\n\n  - (* from qq1 *)\n    introv m1 m2.\n    apply equality_in_fun in qq1; repnd.\n    pose proof (qq1 a a) as h.\n    autodimp h hyp.\n    lsubst_tac.\n    allrw @lsubstc_mkc_tnat.\n    allrw @lsubstc_mk_nout.\n    apply equality_in_fun in h; repnd.\n    pose proof (h b b) as q.\n    autodimp q hyp.\n    apply equality_in_uni in q; auto.\n    allrw <- @mkc_apply2_eq; auto.\n\n  - (* from hh1 *)\n    apply equality_refl in hh1.\n    exists (lsubstc e wfce0 s1 pt0).\n\n    repeat lsubstc_vars_as_mkcv.\n    allrw @lsubstc_mk_nout.\n    auto.\n\n  - repeat lsubstc_vars_as_mkcv.\n    allrw @lsubstc_mk_nout.\n\n    dands;\n      [|apply equality_in_mkc_squash; dands; spcast;\n        try (apply computes_to_valc_refl; eauto 3 with slow);\n        allunfold @mkc_exists; allunfold @mkcv_forall;\n        eapply inhabited_type_respects_alphaeqc;[|exact ac];\n        apply alphaeqc_mkc_product1;\n        apply alphaeqc_sym;\n        fold (@mk_nat2nout p);\n        rewrite lsubstc_mk_nat2nout;\n        eauto 3 with slow];[].\n\n    apply tequality_mkc_squash.\n\n    eapply tequality_respects_alphaeqc_left;\n      [apply alphaeqc_mkc_product1;\n        apply alphaeqc_sym;\n        fold (@mk_nat2nout p);\n        rewrite lsubstc_mk_nat2nout;\n        eauto 3 with slow\n      |].\n    eapply tequality_respects_alphaeqc_right;\n      [apply alphaeqc_mkc_product1;\n        apply alphaeqc_sym;\n        fold (@mk_nat2nout p);\n        rewrite lsubstc_mk_nat2nout;\n        eauto 3 with slow\n      |].\n    apply tequality_product; dands.\n    { apply type_nat2nout. }\n\n    introv eqf.\n    repeat (rw @substc_mkcv_function; auto;[]).\n    allrw @mkcv_tnat_substc.\n    allrw @substcv_as_substc2.\n    allrw @substc2_squash.\n    allrw @substc2_apply2.\n    allrw @substc2_apply.\n    allrw @substc2_mk_cv.\n    repeat (rw @substc2_mk_cv_app_r; auto;[]).\n    repeat (rw @substc2_mk_cv_app_l; auto;[]).\n    allrw @mkc_var_substc.\n\n    apply tequality_function; dands.\n    { apply tnat_type. }\n\n    introv eqn.\n    allrw @substc_mkcv_squash.\n    allrw @mkcv_apply2_substc.\n    allrw @mkcv_apply_substc.\n    allrw @csubst_mk_cv.\n    allrw @mkc_var_substc.\n\n    apply tequality_mkc_squash.\n    apply equality_in_fun in qq0; repnd.\n    applydup qq0 in eqn.\n    lsubst_tac.\n    apply equality_in_fun in eqn0; repnd.\n    pose proof (eqn0 (mkc_apply a a0) (mkc_apply a' a'0)) as q.\n    allrw @lsubstc_mkc_tnat.\n    allrw @lsubstc_mk_nout.\n    autodimp q hyp.\n    { apply equality_nat2nout_apply; auto. }\n    allrw <- @mkc_apply2_eq.\n    apply equality_in_uni in q; auto.\nQed.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/axiom_choice/axiom_choice_gen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555714, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2124723074893235}}
{"text": "From iris.proofmode Require Import tactics.\nFrom mwp.mwp_modalities Require Import mwp_step_fupd.\nFrom mwp.mwp_modalities.ni_logrel Require Import mwp_left mwp_right ni_logrel_lemmas\n     mwp_logrel_fupd ni_logrel_fupd_lemmas.\nFrom logrel_ifc.lambda_sec Require Export lattice fundamental_binary notation.\n\n(* This is an implicit variation of [refs.v] where we leak (temporarily)\n   information through an implicit flow but fix it before returning. *)\nDefinition prog : expr:=\n  (if: !$1 = 42 then $0 <- 1 else $0 <- 0);; $0 <- 0.\n\nLocal Instance tpSecurityLatticeH : SecurityLattice tplabel := { ζ := L }.\nNotation H := (LLabel H).\nNotation L := (LLabel L).\n\nSection related.\n  Context `{!secG Σ}.\n\n  Lemma prog_related :\n    [TRef (TNat @ L) @ L; TRef (TNat @ H) @ L] ⊨ prog ≤ₗ prog : TUnit @ L.\n  Proof.\n    iIntros (θ ρ vvs Hpers) \"[#Hcoh Henv]\".\n    iDestruct (interp_env_length with \"Henv\") as %H.\n    do 2 (destruct vvs; [done|]); clear H.\n    iDestruct (interp_env_cons with \"Henv\") as \"[Hlow Henv']\".\n    iDestruct (interp_env_cons with \"Henv'\") as \"[Hhigh _]\".\n    rewrite !interp_sec_def !bool_decide_eq_true_2 // !interp_ref_def.\n    iDestruct \"Hlow\" as ([l1 l2]) \"[-> #Hlow] /=\".\n    iDestruct \"Hhigh\" as ([h1 h2]) \"[-> #Hhigh] /=\".\n    rewrite /interp_expr /=.\n    iApply (mwp_left_strong_bind _ _ (fill [BinOpLCtx _ _; IfCtx _ _; SeqCtx _])\n                                (fill [BinOpLCtx _ _; IfCtx _ _; SeqCtx _])); simpl.\n    iApply (mwp_double_atomic_lr _ _ StronglyAtomic).\n    iInv (nroot.@(h1,h2)) as \"Hh\" \"Hclose !>\".\n    iDestruct \"Hh\" as (v1 v2) \"(>Hh1 & >Hh2 & #Hv) /=\".\n    rewrite !loc_to_val.\n    iApply (@mwp_step_fupd_load _ secG_un_left); [done|].\n    iFrame. iIntros \"!> Hh1\".\n    iApply (@mwp_fupd_load _ secG_un_right); [done|].\n    iFrame. iIntros \"Hh2 /=\".\n    iMod (\"Hclose\" with \"[-]\") as \"_\".\n    { iExists _,_. iFrame. iFrame \"#\". }\n    iModIntro.\n    iDestruct (secbin_subsumes_secun with \"[$Hcoh $Hv]\") as \"[#Hv1 #Hv2] /=\".\n    rewrite ![⌊ TNat @ _ ⌋ₛ _ _]interp_un_sec_def !interp_un_nat_def.\n    iDestruct \"Hv1\" as (n1) \"->\". iDestruct \"Hv2\" as (n2) \"->\".\n    iApply (mwp_left_strong_bind _ _ (fill [IfCtx _ _; SeqCtx _])\n                                (fill [IfCtx _ _; SeqCtx _])); simpl.\n    rewrite !nat_to_val.\n    iApply mwp_left_pure_step; [done|].\n    iApply mwp_left_pure_step_index; [done|]. simpl.\n    iApply (mwp_value mwp_binary); umods.\n    iApply (mwp_value (mwpd_right SI_right)); umods.\n    do 2 iModIntro.\n    iApply ni_logrel_fupd_ni_logrel. iSplit.\n    { iLeft. iIntros (σ) \"Hσ\".\n      iMod (fupd_mask_subseteq ∅) as \"Hclose\"; first set_solver.\n      iModIntro. iPureIntro.\n      eapply (fill_reducible [SeqCtx _]).\n      apply head_prim_reducible.\n      case_bool_decide; eexists [],_,_,[]; by econstructor. }\n    iInv (nroot.@(l1,l2)) as \"Hl\" \"HcloseI\".\n    iDestruct \"Hl\" as (w1 w2) \"(Hl1 & Hl2 & _) /=\".\n    do 2 iModIntro.\n    iApply mwp_un_bi_fupd_lr.\n    iApply (mwp_fupd_bind _ (fill [SeqCtx _])).\n    case_bool_decide.\n    - (* left then branch *)\n      iApply mwp_fupd_pure_step; [done|].\n      rewrite !loc_to_val !nat_to_val.\n      iApply ((@mwp_fupd_store _ secG_un_left)); [done|].\n      iFrame. iIntros \"Hl1\".\n      iApply mwp_fupd_pure_step; [done|].\n      iApply ((@mwp_fupd_store _ secG_un_left)); [done|].\n      iFrame. iIntros \"Hl1\".\n      case_bool_decide.\n      + (* right then branch *)\n        iApply (mwp_fupd_bind _ (fill [SeqCtx _])).\n        iApply (mwp_fupd_pure_step); [done|].\n        iApply ((@mwp_fupd_store _ secG_un_right)); [done|].\n        iFrame. iIntros \"Hl2\".\n        iApply mwp_fupd_pure_step; [done|].\n        iApply ((@mwp_fupd_store _ secG_un_right)); [done|].\n        iFrame. iIntros \"Hl2\".\n        iMod (\"HcloseI\" with \"[-]\") as \"_\".\n        { iExists _,_. iModIntro. iFrame. unats.\n          rewrite [bool_decide (⌊ L ⌋ₗ ρ ⊑ ζ)]bool_decide_eq_true_2 //=; auto. }\n        iIntros \"!> /=\".\n        rewrite [⟦ () @ L ⟧ₛ _ _ _]interp_sec_def interp_unit_def\n                bool_decide_eq_true_2 //.\n      + (* right else branch *)\n        iApply (mwp_fupd_bind _ (fill [SeqCtx _])).\n        iApply (mwp_fupd_pure_step); [done|].\n        iApply ((@mwp_fupd_store _ secG_un_right)); [done|].\n        iFrame. iIntros \"Hl2\".\n        iApply mwp_fupd_pure_step; [done|].\n        iApply ((@mwp_fupd_store _ secG_un_right)); [done|].\n        iFrame. iIntros \"Hl2\".\n        iMod (\"HcloseI\" with \"[-]\") as \"_\".\n        { iExists _,_. iModIntro. iFrame. unats.\n          rewrite [bool_decide (⌊ L ⌋ₗ ρ ⊑ ζ)]bool_decide_eq_true_2 //=; auto. }\n        iIntros \"!> /=\".\n        rewrite [⟦ () @ L ⟧ₛ _ _ _]interp_sec_def interp_unit_def\n                bool_decide_eq_true_2 //.\n    - (* left else branch - identical to above *)\n      iApply mwp_fupd_pure_step; [done|].\n      rewrite !loc_to_val !nat_to_val.\n      iApply ((@mwp_fupd_store _ secG_un_left)); [done|].\n      iFrame. iIntros \"Hl1\".\n      iApply mwp_fupd_pure_step; [done|].\n      iApply ((@mwp_fupd_store _ secG_un_left)); [done|].\n      iFrame. iIntros \"Hl1\".\n      case_bool_decide.\n      + (* right then branch *)\n        iApply (mwp_fupd_bind _ (fill [SeqCtx _])).\n        iApply (mwp_fupd_pure_step); [done|].\n        iApply ((@mwp_fupd_store _ secG_un_right)); [done|].\n        iFrame. iIntros \"Hl2\".\n        iApply mwp_fupd_pure_step; [done|].\n        iApply ((@mwp_fupd_store _ secG_un_right)); [done|].\n        iFrame. iIntros \"Hl2\".\n        iMod (\"HcloseI\" with \"[-]\") as \"_\".\n        { iExists _,_. iModIntro. iFrame. unats.\n          rewrite [bool_decide (⌊ L ⌋ₗ ρ ⊑ ζ)]bool_decide_eq_true_2 //=; auto. }\n        iIntros \"!> /=\".\n        rewrite [⟦ () @ L ⟧ₛ _ _ _]interp_sec_def interp_unit_def\n                bool_decide_eq_true_2 //.\n      + (* right else branch *)\n        iApply (mwp_fupd_bind _ (fill [SeqCtx _])).\n        iApply (mwp_fupd_pure_step); [done|].\n        iApply ((@mwp_fupd_store _ secG_un_right)); [done|].\n        iFrame. iIntros \"Hl2\".\n        iApply mwp_fupd_pure_step; [done|].\n        iApply ((@mwp_fupd_store _ secG_un_right)); [done|].\n        iFrame. iIntros \"Hl2\".\n        iMod (\"HcloseI\" with \"[-]\") as \"_\".\n        { iExists _,_. iModIntro. iFrame. unats.\n          rewrite [bool_decide (⌊ L ⌋ₗ ρ ⊑ ζ)]bool_decide_eq_true_2 //=; auto. }\n        iIntros \"!> /=\".\n        rewrite [⟦ () @ L ⟧ₛ _ _ _]interp_sec_def interp_unit_def\n                bool_decide_eq_true_2 //.\n  Qed.\n\nEnd related.\n", "meta": {"author": "logsem", "repo": "iris-tini", "sha": "1f3440dc1a992329635a25b1fd81703cd058c817", "save_path": "github-repos/coq/logsem-iris-tini", "path": "github-repos/coq/logsem-iris-tini/iris-tini-1f3440dc1a992329635a25b1fd81703cd058c817/theories/examples/refs_implicit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.21247230174906312}}
{"text": "(*! Regression test for signed shifts !*)\nRequire Import Koika.Frontend.\n\nInductive idx := r3 | r4 | r5 | r6 | r7 | r8 | r9 | r10 | r11 | r12 | r13 | r14 | r15 | r16.\nInductive reg_t := cond | r_l (_: idx) | r_r (_: idx) | r_out (_: idx).\n\nInductive rule_name_t := rl.\n\nDefinition R (reg: reg_t) : type :=\n  match reg with\n  | cond => bits_t 1\n  | _ => bits_t 32\n  end.\n\nDefinition r (reg: reg_t) : R reg :=\n  match reg with\n  | cond => Ob~1\n  | r_l r3 => Ob~1~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0\n  | r_r r3 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1\n  | r_l r4 => Ob~1~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0\n  | r_r r4 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1~1~1\n  | r_l r5 => Ob~1~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0\n  | r_r r5 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1~1~1~0\n  | r_l r6 => Ob~1~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1\n  | r_r r6 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1~1~1~1~1\n  | r_l r7 => Ob~0~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1\n  | r_r r7 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0\n  | r_l r8 => Ob~0~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1\n  | r_r r8 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1\n  | r_l r9 => Ob~0~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1\n  | r_r r9 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1~1~1\n  | r_l r10 => Ob~0~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1\n  | r_r r10 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1~1~1~0\n  | r_l r11 => Ob~0~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1\n  | r_r r11 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1~1~1~1~1\n  | r_l r12 => Ob~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1\n  | r_r r12 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0\n  | r_l r13 => Ob~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1\n  | r_r r13 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1\n  | r_l r14 => Ob~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1\n  | r_r r14 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1~1~1\n  | r_l r15 => Ob~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1\n  | r_r r15 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1~1~1~0\n  | r_l r16 => Ob~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1\n  | r_r r16 => Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1~1~1~1~1\n  | r_out _ => Bits.zero\n  end.\n\nDefinition urules (rl: rule_name_t) : uaction reg_t empty_ext_fn_t :=\n  {{\n      write0(r_out r3, if read0(cond)\n                       then (read0(r_l r3) >>> read0(r_r r3)) >>> read0(r_r r3)\n                       else (read0(r_l r3) >> read0(r_r r3)) >> read0(r_r r3));\n      (* Ob~1~1~1~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0 *)\n\n      write0(r_out r4, if read0(cond)\n                       then (read0(r_l r4) >>> read0(r_r r4)) >>> read0(r_r r4)\n                       else (read0(r_l r4) >> read0(r_r r4)) >> read0(r_r r4));\n      (* Ob~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0 *)\n\n      write0(r_out r5, if read0(cond)\n                       then (read0(r_l r5) >>> read0(r_r r5)) >>> read0(r_r r5)\n                       else (read0(r_l r5) >> read0(r_r r5)) >> read0(r_r r5));\n      (* Ob~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~0~0~0 *)\n\n      write0(r_out r6, if read0(cond)\n                       then (read0(r_l r6) >>> read0(r_r r6)) >>> read0(r_r r6)\n                       else (read0(r_l r6) >> read0(r_r r6)) >> read0(r_r r6));\n      (* Ob~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1 *)\n\n      write0(r_out r7, if read0(cond)\n                       then (read0(r_l r7) >>> read0(r_r r7)) >>> read0(r_r r7)\n                       else (read0(r_l r7) >> read0(r_r r7)) >> read0(r_r r7));\n      (* Ob~0~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1 *)\n\n      write0(r_out r8, if read0(cond)\n                       then (read0(r_l r8) >>> read0(r_r r8)) >>> read0(r_r r8)\n                       else (read0(r_l r8) >> read0(r_r r8)) >> read0(r_r r8));\n      (* Ob~0~0~0~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1 *)\n\n      write0(r_out r9, if read0(cond)\n                       then (read0(r_l r9) >>> read0(r_r r9)) >>> read0(r_r r9)\n                       else (read0(r_l r9) >> read0(r_r r9)) >> read0(r_r r9));\n      (* Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1 *)\n\n      write0(r_out r10, if read0(cond)\n                        then (read0(r_l r10) >>> read0(r_r r10)) >>> read0(r_r r10)\n                        else (read0(r_l r10) >> read0(r_r r10)) >> read0(r_r r10));\n      (* Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~1~1~1 *)\n\n      write0(r_out r11, if read0(cond)\n                        then (read0(r_l r11) >>> read0(r_r r11)) >>> read0(r_r r11)\n                        else (read0(r_l r11) >> read0(r_r r11)) >> read0(r_r r11));\n      (* Ob~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0~0 *)\n\n      write0(r_out r12, if read0(cond)\n                        then (read0(r_l r12) >>> read0(r_r r12)) >>> read0(r_r r12)\n                        else (read0(r_l r12) >> read0(r_r r12)) >> read0(r_r r12));\n      (* Ob~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1 *)\n\n      write0(r_out r13, if read0(cond)\n                        then (read0(r_l r13) >>> read0(r_r r13)) >>> read0(r_r r13)\n                        else (read0(r_l r13) >> read0(r_r r13)) >> read0(r_r r13));\n      (* Ob~1~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0 *)\n\n      write0(r_out r14, if read0(cond)\n                        then (read0(r_l r14) >>> read0(r_r r14)) >>> read0(r_r r14)\n                        else (read0(r_l r14) >> read0(r_r r14)) >> read0(r_r r14));\n      (* Ob~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~0~0~0~0~0~0~1~1~0~0~0~0~0~0~1~1~0 *)\n\n      write0(r_out r15, if read0(cond)\n                        then (read0(r_l r15) >>> read0(r_r r15)) >>> read0(r_r r15)\n                        else (read0(r_l r15) >> read0(r_r r15)) >> read0(r_r r15));\n      (* Ob~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~0~0~0 *)\n\n      write0(r_out r16, if read0(cond)\n                        then (read0(r_l r16) >>> read0(r_r r16)) >>> read0(r_r r16)\n                        else (read0(r_l r16) >> read0(r_r r16)) >> read0(r_r r16));\n      (* Ob~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1~1 *)\n\n      write0(cond, !read0(cond))\n  }}.\n\nDefinition rules :=\n  tc_rules R empty_Sigma urules.\n\nDefinition sched : scheduler :=\n  rl |> done.\n\nDefinition sched_result :=\n  tc_compute (interp_scheduler (ContextEnv.(create) r) empty_sigma rules sched).\n\nDefinition external (r: rule_name_t) := false.\n\nDefinition sched_circuits :=\n  compile_scheduler rules external sched.\n\nDefinition sched_circuits_result :=\n  tc_compute (interp_circuits empty_sigma sched_circuits (lower_r (ContextEnv.(create) r))).\n\nDefinition package :=\n  {| ip_koika := {| koika_reg_types := R;\n                   koika_reg_init := r;\n                   koika_ext_fn_types := empty_Sigma;\n                   koika_rules := rules;\n                   koika_rule_external := external;\n                   koika_scheduler := sched;\n                   koika_module_name := \"shifts\" |};\n\n     ip_sim := {| sp_ext_fn_specs := empty_ext_fn_props;\n                 sp_prelude := None |};\n\n     ip_verilog := {| vp_ext_fn_specs := empty_ext_fn_props |} |}.\n\nDefinition prog := Interop.Backends.register package.\nExtraction \"shifts.ml\" prog.\n", "meta": {"author": "mit-plv", "repo": "koika", "sha": "c758c7b0092186f76ed858f4137366cc62f7a04a", "save_path": "github-repos/coq/mit-plv-koika", "path": "github-repos/coq/mit-plv-koika/koika-c758c7b0092186f76ed858f4137366cc62f7a04a/tests/shifts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3702253995442529, "lm_q1q2_score": 0.2123903230060127}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import FulfillStep.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import SimThread.\nRequire Import Compatibility.\n\nRequire Import SplitAcq.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\n\nDefinition local_acqrel (lc:Local.t) :=\n  (Local.mk (TView.write_fence_tview\n               (TView.read_fence_tview (Local.tview lc) Ordering.acqrel)\n               TimeMap.bot\n               Ordering.acqrel)\n            (Local.promises lc)).\n\nLemma sim_local_promise_acqrel\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt mem2_tgt\n      loc from to msg kind\n      (STEP_TGT: Local.promise_step lc1_tgt mem1_tgt loc from to msg lc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src (local_acqrel lc1_tgt))\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src mem2_src,\n    <<STEP_SRC: Local.promise_step lc1_src mem1_src loc from to msg lc2_src mem2_src kind>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acqrel lc2_tgt)>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit SimPromises.promise_bot; eauto.\n  { apply WF1_SRC. }\n  { apply WF1_TGT. }\n  i. des.\n  exploit Memory.promise_future; try apply PROMISE_SRC; try apply WF1_SRC; eauto.\n  { destruct msg; ss. inv CLOSED. econs.\n    eapply sim_memory_closed_opt_view; eauto. }\n  i. des.\n  esplits; eauto.\n  - econs; eauto.\n    destruct msg; ss. inv CLOSED. econs.\n    eapply sim_memory_closed_opt_view; eauto.\n  - econs; eauto.\nQed.\n\nLemma sim_local_fulfill_acqrel\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      loc from to val releasedm_src releasedm_tgt released ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF: View.opt_wf releasedm_src)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT: Time.le (View.rlx (View.unwrap releasedm_tgt) loc) from)\n      (WF_RELM_TGT: View.opt_wf releasedm_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (ORD_TGT: Ordering.le ord_tgt Ordering.acqrel)\n      (STEP_TGT: fulfill_step lc1_tgt sc1_tgt loc from to val releasedm_tgt released ord_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_local SimPromises.bot lc1_src (local_acquired lc1_tgt))\n      (ACQUIRED1: View.le (TView.cur (Local.tview lc1_src))\n                          (View.join (TView.cur (Local.tview lc1_tgt)) (View.unwrap releasedm_tgt)))\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: fulfill_step lc1_src sc1_src loc from to val releasedm_src released ord_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acqrel lc2_tgt)>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  inv STEP_TGT.\n  assert (RELT_LE:\n   View.opt_le\n     (TView.write_released (Local.tview lc1_src) sc1_src loc to releasedm_src ord_src)\n     (TView.write_released (Local.tview lc1_tgt) sc2_tgt loc to releasedm_tgt ord_tgt)).\n  { unfold TView.write_released, TView.write_tview. ss. viewtac.\n    repeat (condtac; aggrtac;\n            try match goal with\n                | [|- View.opt_le _ _] => econs\n                end);\n      try apply WF1_TGT.\n    - etrans; eauto. aggrtac.\n    - etrans; [apply WF1_SRC|]. etrans; eauto. aggrtac.\n    - etrans; [apply LOCAL1|]. aggrtac.\n  }\n  assert (RELT_WF:\n   View.opt_wf (TView.write_released (Local.tview lc1_src) sc1_src loc to releasedm_src ord_src)).\n  { unfold TView.write_released. condtac; econs.\n    repeat (try condtac; viewtac; try apply WF1_SRC).\n  }\n  exploit SimPromises.remove_bot; try exact REMOVE;\n    try exact MEM1; try apply LOCAL1; eauto.\n  { econs. ss. }\n  { apply WF1_SRC. }\n  { apply WF1_TGT. }\n  { apply WF1_TGT. }\n  i. des. esplits.\n  - econs; eauto.\n    inv WRITABLE. econs.\n    eapply TimeFacts.le_lt_lt; [apply ACQUIRED1|]. viewtac.\n    eapply TimeFacts.le_lt_lt; eauto.\n  - econs; eauto. s.\n    unfold TView.write_tview, TView.write_fence_tview, TView.read_fence_tview. ss.\n    econs; ss; repeat (condtac; aggrtac).\n    all: try by destruct ord_src, ord_tgt.\n    all: try by apply WF1_TGT.\n    + etrans; [apply LOCAL1|]. repeat (try condtac; aggrtac).\n    + etrans; [apply LOCAL1|]. aggrtac.\n      etrans; [apply WF1_TGT|]. etrans; [apply WF1_TGT|]. aggrtac.\n    + etrans; [apply LOCAL1|]. aggrtac.\n      etrans; [apply WF1_TGT|]. etrans; [apply WF1_TGT|]. aggrtac.\n    + etrans; [apply LOCAL1|]. repeat (try condtac; aggrtac).\n      etrans; [apply WF1_TGT|]. etrans; [apply WF1_TGT|]. aggrtac.\n    + etrans; [apply LOCAL1|]. ss. condtac; aggrtac.\n    + etrans; [apply LOCAL1|]. aggrtac.\n  - ss.\nQed.\n\nLemma sim_local_write_acqrel\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt mem2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt kind\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_SRC_WF: View.opt_wf releasedm_src)\n      (RELM_SRC_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT_WF: View.opt_wf releasedm_tgt)\n      (RELM_TGT_CLOSED: Memory.closed_opt_view releasedm_tgt mem1_tgt)\n      (RELM_TGT: Time.le (View.rlx (View.unwrap releasedm_tgt) loc) from)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (ORD_TGT: Ordering.le ord_tgt Ordering.acqrel)\n      (STEP_TGT: Local.write_step lc1_tgt sc1_tgt mem1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt sc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src (local_acquired lc1_tgt))\n      (ACQUIRED1: View.le (TView.cur (Local.tview lc1_src))\n                          (View.join (TView.cur (Local.tview lc1_tgt)) (View.unwrap releasedm_tgt)))\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists released_src lc2_src sc2_src mem2_src,\n    <<STEP_SRC: Local.write_step lc1_src sc1_src mem1_src loc from to val releasedm_src released_src ord_src lc2_src sc2_src mem2_src kind>> /\\\n    <<REL2: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acqrel lc2_tgt)>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit sim_local_promise_acquired; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  hexploit sim_local_fulfill_acqrel; try apply STEP2;\n    try apply LOCAL2; try apply MEM2; eauto.\n  { eapply Memory.future_closed_opt_view; eauto. }\n  { inv STEP_SRC. inv STEP1. ss. }\n  i. des.\n  exploit promise_fulfill_write_sim_memory; try exact STEP_SRC; try exact STEP_SRC0; eauto.\n  { i. hexploit ORD0; eauto.\n    i. des. splits; auto. eapply sim_local_nonsynch_loc; eauto.\n  }\n  i. des. esplits; eauto. etrans; eauto.\nQed.\n\n\nInductive split_acqrel: forall (i1 i2:Instr.t), Prop :=\n| split_acqrel_load\n    r l:\n    split_acqrel (Instr.load r l Ordering.acqrel) (Instr.load r l Ordering.relaxed)\n| split_acqrel_update\n    r l rmw ow\n    (OW: Ordering.le ow Ordering.acqrel):\n    split_acqrel (Instr.update r l rmw Ordering.acqrel ow) (Instr.update r l rmw Ordering.relaxed ow)\n.\n\nInductive sim_acqrel: forall (st_src:(Language.state lang)) (lc_src:Local.t) (sc1_src:TimeMap.t) (mem1_src:Memory.t)\n                        (st_tgt:(Language.state lang)) (lc_tgt:Local.t) (sc1_tgt:TimeMap.t) (mem1_tgt:Memory.t), Prop :=\n| sim_acqrel_intro\n    rs\n    lc1_src sc1_src mem1_src\n    lc1_tgt sc1_tgt mem1_tgt\n    (LOCAL: sim_local SimPromises.bot lc1_src (local_acqrel lc1_tgt))\n    (SC: TimeMap.le sc1_src sc1_tgt)\n    (MEMORY: sim_memory mem1_src mem1_tgt)\n    (WF_SRC: Local.wf lc1_src mem1_src)\n    (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n    (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n    (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n    (MEM_SRC: Memory.closed mem1_src)\n    (MEM_TGT: Memory.closed mem1_tgt):\n    sim_acqrel\n      (State.mk rs []) lc1_src sc1_src mem1_src\n      (State.mk rs [Stmt.instr (Instr.fence Ordering.acqrel Ordering.acqrel)]) lc1_tgt sc1_tgt mem1_tgt\n.\n\nLemma sim_acqrel_mon\n      st_src lc_src sc1_src mem1_src\n      st_tgt lc_tgt sc1_tgt mem1_tgt\n      sc2_src mem2_src\n      sc2_tgt mem2_tgt\n      (SIM1: sim_acqrel st_src lc_src sc1_src mem1_src\n                          st_tgt lc_tgt sc1_tgt mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc1_src sc2_src)\n      (SC_FUTURE_TGT: TimeMap.le sc1_tgt sc2_tgt)\n      (MEM_FUTURE_SRC: Memory.future_weak mem1_src mem2_src)\n      (MEM_FUTURE_TGT: Memory.future_weak mem1_tgt mem2_tgt)\n      (SC1: TimeMap.le sc2_src sc2_tgt)\n      (MEM1: sim_memory mem2_src mem2_tgt)\n      (WF_SRC: Local.wf lc_src mem2_src)\n      (WF_TGT: Local.wf lc_tgt mem2_tgt)\n      (SC_SRC: Memory.closed_timemap sc2_src mem2_src)\n      (SC_TGT: Memory.closed_timemap sc2_tgt mem2_tgt)\n      (MEM_SRC: Memory.closed mem2_src)\n      (MEM_TGT: Memory.closed mem2_tgt):\n  sim_acqrel st_src lc_src sc2_src mem2_src\n               st_tgt lc_tgt sc2_tgt mem2_tgt.\nProof.\n  inv SIM1. econs; eauto.\nQed.\n\nLemma sim_acqrel_step\n      st1_src lc1_src sc1_src mem1_src\n      st1_tgt lc1_tgt sc1_tgt mem1_tgt\n      (SIM: sim_acqrel st1_src lc1_src sc1_src mem1_src\n                         st1_tgt lc1_tgt sc1_tgt mem1_tgt):\n  _sim_thread_step lang lang ((sim_thread (sim_terminal eq)) \\8/ sim_acqrel)\n                   st1_src lc1_src sc1_src mem1_src\n                   st1_tgt lc1_tgt sc1_tgt mem1_tgt.\nProof.\n  inv SIM. ii.\n  inv STEP_TGT; [inv STEP|inv STEP; inv LOCAL0];\n    try (inv STATE; inv INSTR; inv SPLIT); ss.\n  - (* promise *)\n    right.\n    exploit Local.promise_step_future; eauto. i. des.\n    exploit sim_local_promise_acqrel; try exact LOCAL; eauto. i. des.\n    exploit Local.promise_step_future; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs. econs; eauto.\n    + eauto.\n    + right. econs; eauto.\n  - (* fence *)\n    right.\n    exploit Local.fence_step_future; eauto. i. des.\n    inv STATE. inv INSTR. inv LOCAL1. ss.\n    esplits; (try by econs 1); eauto; ss.\n    left. eapply paco9_mon; [apply sim_stmts_nil|]; ss.\nQed.\n\nLemma sim_acqrel_sim_thread:\n  sim_acqrel <8= (sim_thread (sim_terminal eq)).\nProof.\n  pcofix CIH. i. pfold. ii. ss. splits; ss; ii.\n  - inv TERMINAL_TGT. inv PR; ss.\n  - right. esplits; eauto.\n    inv PR. eapply sim_local_memory_bot; eauto.\n  - exploit sim_acqrel_mon; eauto. i. des.\n    exploit sim_acqrel_step; eauto. i. des; eauto.\n    + right. esplits; eauto.\n      left. eapply paco9_mon; eauto. ss.\n    + right. esplits; eauto.\nQed.\n\nLemma split_acqrel_sim_stmts\n      i_src i_tgt\n      (SPLIT: split_acqrel i_src i_tgt):\n  sim_stmts eq\n            [Stmt.instr i_src]\n            [Stmt.instr i_tgt; Stmt.instr (Instr.fence Ordering.acqrel Ordering.acqrel)]\n            eq.\nProof.\n  pcofix CIH. ii. subst. pfold. ii. splits; ii.\n  { inv TERMINAL_TGT. }\n  { right. esplits; eauto.\n    inv LOCAL. apply SimPromises.sem_bot_inv in PROMISES; auto. rewrite PROMISES. auto.\n  }\n  right.\n  inv STEP_TGT; [inv STEP|inv STEP; inv LOCAL0];\n    try (inv STATE; inv INSTR; inv SPLIT); ss.\n  - (* promise *)\n    exploit sim_local_promise; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    econs 2. econs 1; eauto. econs; eauto. eauto.\n  - (* load *)\n    exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read_acquired; eauto. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs 2. econs; cycle 1.\n      * econs 2. eauto.\n      * econs. econs.\n    + auto.\n    + left. eapply paco9_mon; [apply sim_acqrel_sim_thread|]; ss.\n      econs; ss. inv LOCAL2. econs; ss.\n      etrans; eauto. apply TViewFacts.write_fence_tview_incr.\n      eapply TViewFacts.read_fence_future; apply WF2.\n  - (* update-load *)\n    exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read_acquired; eauto. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs 2. econs; cycle 1.\n      * econs 2. eauto.\n      * econs. econs. eauto.\n    + auto.\n    + left. eapply paco9_mon; [apply sim_acqrel_sim_thread|]; ss.\n      econs; ss. inv LOCAL2. econs; ss.\n      etrans; eauto. apply TViewFacts.write_fence_tview_incr.\n      eapply TViewFacts.read_fence_future; apply WF2.\n  - (* update *)\n    exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read_acquired; eauto. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    exploit Local.write_step_future; eauto. i. des.\n    hexploit sim_local_write_acqrel; try exact LOCAL2; try exact SC; eauto; try refl.\n    { inv LOCAL1. inv MEM_TGT. exploit CLOSED; eauto. i. des.\n      inv MSG_TS. ss. }\n    { inv STEP_SRC. inv LOCAL1. ss. repeat (condtac; aggrtac).\n      - rewrite <- ? View.join_l. apply LOCAL.\n      - apply WF_TGT.\n      - unfold TimeMap.join. rewrite <- Time.join_l. rewrite <- Time.join_l. rewrite <- Time.join_r.\n        unfold View.singleton_ur_if. condtac; ss. unfold TimeMap.singleton, LocFun.add.\n        condtac; ss. refl.\n    }\n    i. des.\n    exploit Local.write_step_future; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs 2. econs; cycle 1.\n      * econs 4; eauto.\n      * econs. econs. eauto.\n    + auto.\n    + left. eapply paco9_mon; [apply sim_acqrel_sim_thread|]; ss.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/opt/SplitAcqRel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.21239030423941999}}
{"text": "(* Default settings (from HsToCoq.Coq.Preamble) *)\n\nGeneralizable All Variables.\n\nUnset Implicit Arguments.\nSet Maximal Implicit Insertion.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nRequire Coq.Program.Tactics.\nRequire Coq.Program.Wf.\n\n(* Converted imports: *)\n\nRequire Coq.Numbers.BinNums.\nRequire Data.Bits.\nRequire Data.Foldable.\nRequire Data.IntSet.Internal.\nRequire GHC.Base.\nRequire GHC.Num.\nImport Data.Bits.Notations.\nImport GHC.Base.Notations.\nImport GHC.Num.Notations.\n\n(* No type declarations to convert. *)\n\n(* Converted value declarations: *)\n\nDefinition validTipPrefix : Data.IntSet.Internal.Prefix -> bool :=\n  fun p => (#63 Data.Bits..&.(**) p) GHC.Base.== #0.\n\nDefinition tipsValid : Data.IntSet.Internal.IntSet -> bool :=\n  fix tipsValid t\n        := match t with\n           | Data.IntSet.Internal.Nil => true\n           | (Data.IntSet.Internal.Tip p b as tip) => validTipPrefix p\n           | Data.IntSet.Internal.Bin _ _ l r => andb (tipsValid l) (tipsValid r)\n           end.\n\nDefinition nilNeverChildOfBin : Data.IntSet.Internal.IntSet -> bool :=\n  fun t =>\n    let fix noNilInSet t'\n              := match t' with\n                 | Data.IntSet.Internal.Nil => false\n                 | Data.IntSet.Internal.Tip _ _ => true\n                 | Data.IntSet.Internal.Bin _ _ l' r' => andb (noNilInSet l') (noNilInSet r')\n                 end in\n    match t with\n    | Data.IntSet.Internal.Nil => true\n    | Data.IntSet.Internal.Tip _ _ => true\n    | Data.IntSet.Internal.Bin _ _ l r => andb (noNilInSet l) (noNilInSet r)\n    end.\n\nDefinition maskRespected : Data.IntSet.Internal.IntSet -> bool :=\n  fix maskRespected t\n        := match t with\n           | Data.IntSet.Internal.Nil => true\n           | Data.IntSet.Internal.Tip _ _ => true\n           | Data.IntSet.Internal.Bin _ binMask l r =>\n               andb (Data.Foldable.all (fun x => Data.IntSet.Internal.zero x binMask)\n                     (Data.IntSet.Internal.elems l)) (andb (Data.Foldable.all (fun x =>\n                                                                                 negb (Data.IntSet.Internal.zero x\n                                                                                       binMask))\n                                                            (Data.IntSet.Internal.elems r)) (andb (maskRespected l)\n                                                                                                  (maskRespected r)))\n           end.\n\nDefinition maskPowerOfTwo : Data.IntSet.Internal.IntSet -> bool :=\n  fix maskPowerOfTwo t\n        := match t with\n           | Data.IntSet.Internal.Nil => true\n           | Data.IntSet.Internal.Tip _ _ => true\n           | Data.IntSet.Internal.Bin _ m l r =>\n               andb (Utils.Containers.Internal.BitUtil.bitcount #0 (m) GHC.Base.== #1) (andb\n                     (maskPowerOfTwo l) (maskPowerOfTwo r))\n           end.\n\nDefinition commonPrefix : Data.IntSet.Internal.IntSet -> bool :=\n  fix commonPrefix t\n        := let sharedPrefix\n            : Data.IntSet.Internal.Prefix -> Coq.Numbers.BinNums.N -> bool :=\n             fun p a => p GHC.Base.== (p Data.Bits..&.(**) a) in\n           match t with\n           | Data.IntSet.Internal.Nil => true\n           | Data.IntSet.Internal.Tip _ _ => true\n           | (Data.IntSet.Internal.Bin p _ l r as b) =>\n               andb (Data.Foldable.all (sharedPrefix p) (Data.IntSet.Internal.elems b)) (andb\n                     (commonPrefix l) (commonPrefix r))\n           end.\n\nDefinition valid : Data.IntSet.Internal.IntSet -> bool :=\n  fun t =>\n    andb (nilNeverChildOfBin t) (andb (maskPowerOfTwo t) (andb (commonPrefix t)\n                                                               (andb (maskRespected t) (tipsValid t)))).\n\n(* External variables:\n     andb bool false negb true Coq.Numbers.BinNums.N Data.Bits.op_zizazi__\n     Data.Foldable.all Data.IntSet.Internal.Bin Data.IntSet.Internal.IntSet\n     Data.IntSet.Internal.Nil Data.IntSet.Internal.Prefix Data.IntSet.Internal.Tip\n     Data.IntSet.Internal.elems Data.IntSet.Internal.zero GHC.Base.op_zeze__\n     GHC.Num.fromInteger Utils.Containers.Internal.BitUtil.bitcount\n*)\n", "meta": {"author": "DavidFHCh", "repo": "Tesis-FTW", "sha": "f84ab8eb92f3984e973ce6a441262d9a8a62e9b0", "save_path": "github-repos/coq/DavidFHCh-Tesis-FTW", "path": "github-repos/coq/DavidFHCh-Tesis-FTW/Tesis-FTW-f84ab8eb92f3984e973ce6a441262d9a8a62e9b0/tesis/hs-to-coq/examples/containers/lib/IntSetValidity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2123836911449199}}
{"text": "Require Import MirrorCore.Reify.Reify.\nRequire Import MirrorCore.Lambda.Expr.\n\nRequire Import MirrorCharge.Java.JavaFunc.\nRequire Import MirrorCharge.Java.JavaType.\nRequire Import MirrorCharge.ModularFunc.ILogicFunc.\nRequire Import MirrorCharge.ModularFunc.BILogicFunc.\nRequire Import MirrorCharge.ModularFunc.LaterFunc.\nRequire Import MirrorCharge.ModularFunc.BaseFunc.\nRequire Import MirrorCharge.ModularFunc.ListFunc.\nRequire Import MirrorCharge.ModularFunc.OpenFunc.\nRequire Import MirrorCharge.ModularFunc.EmbedFunc.\n\nRequire Import Charge.Open.Stack.\nRequire Import Charge.Open.Subst.\nRequire Import Charge.Open.OpenILogic.\n\nRequire Import Charge.Logics.BILogic.\nRequire Import Charge.Logics.Later.\n\nRequire Import Java.Logic.AssertionLogic.\nRequire Import Java.Logic.SpecLogic.\nRequire Import Java.Language.Program.\nRequire Import Java.Language.Lang.\nRequire Import Java.Semantics.OperationalSemantics.\n\nRequire Import ExtLib.Structures.Applicative.\n\nReify Declare Patterns patterns_java_typ := typ.\n\nReify Declare Patterns patterns_java := (ExprCore.expr typ func).\n\nLocal Instance Applicative_Fun A : Applicative (Fun A) :=\n{ pure := fun _ x _ => x\n; ap := fun _ _ f x y => (f y) (x y)\n}.\n\n(*\nReify Declare Patterns const_for_cmd += ((RHasType cmd ?0) => (fun (c : id cmd) => mkCmd [c] : expr typ func)).\n*)\n\nRequire Import MirrorCore.Reify.Reify.\n\nAxiom t : Type.\nReify Declare Patterns t_pat := t.\n\n\n\nReify Declare Syntax t_cmd :=\n{ (@Patterns.CPatterns t t_pat) }.\n\n\nReify Declare Syntax reify_imp_typ :=\n  { \n  \t(@Patterns.CPatterns typ patterns_java_typ)\n  }.\n\nReify Declare Typed Table term_table : BinNums.positive => reify_imp_typ.\n\nCheck term_table.\n\nLocate exprD.\n\nRequire Import MirrorCore.ExprI.\n\nCheck @exprD.\nPrint Expr.\nPrint RType.\nLet Ext x := @ExprCore.Inj typ func (inl (inl (inl (inl (inl (inl (inl (inl x)))))))).\n\nReify Declare Syntax reify_imp :=\n  { (@Patterns.CFirst _\n  \t\t((@Patterns.CVar _ (@ExprCore.Var typ func)) ::\n  \t     (@Patterns.CPatterns _ patterns_java) ::\n         (@Patterns.CApp _ (@ExprCore.App typ func)) ::\n    \t (@Patterns.CAbs _ reify_imp_typ (@ExprCore.Abs typ func)) ::\n    \t (@Patterns.CTypedTable _ _ _ term_table Ext) :: nil))\n  }.\n\nDefinition stack_get (x : Lang.var) (s : stack) := s x.\n\nNotation \"'ap_eq' '[' x ',' y ']'\" :=\n\t (ap (T := Fun stack) (ap (T := Fun stack) (pure (T := Fun stack) (@eq val)) x) y).\nNotation \"'ap_pointsto' '[' x ',' f ',' e ']'\" := \n\t(ap (T := Fun stack) (ap (T := Fun stack) (ap (T := Fun stack) \n\t\t(pure (T := Fun stack) pointsto) (stack_get x)) \n\t\t\t(pure (T := Fun stack) f)) e).\nNotation \"'ap_typeof' '[' e ',' C ']'\" :=\n\t(ap (T := Fun stack) \n\t    (ap (T := Fun stack) \n\t        (pure (T := Fun stack) typeof) \n\t        (pure (T := Fun stack) C))\n\t    e).\n\nDefinition set_fold_fun (x f : String.string) (P : sasn) :=\n\tap_pointsto [x, f, pure null] ** P.\n\nLet _Inj := @ExprCore.Inj typ func.\n\nRequire Import Java.Examples.ListModel.\n(*\nReify Seed Typed Table term_table += 1 => [ (tyArr tyVal (tyArr (tyList tyVal) tyAsn)) , List ].\nReify Seed Typed Table term_table += 2 => [ (tyArr tyVal (tyArr (tyList tyVal) tyAsn)) , NodeList ].\n*)\n\nLocal Notation \"x @ y\" := (@RApp x y) (only parsing, at level 30).\nLocal Notation \"'!!' x\" := (@RExact _ x) (only parsing, at level 25).\nLocal Notation \"'?' n\" := (@RGet n RIgnore) (only parsing, at level 25).\nLocal Notation \"'?!' n\" := (@RGet n RConst) (only parsing, at level 25).\nLocal Notation \"'#'\" := RIgnore (only parsing, at level 0).\n\nReify Pattern patterns_java_typ += (@RImpl (?0) (?1)) => (fun (a b : function reify_imp_typ) => tyArr a b).\n\nReify Pattern patterns_java_typ += (!! asn)  => tyAsn.\nReify Pattern patterns_java_typ += (!! sasn) => tySasn.\nReify Pattern patterns_java_typ += (!! (@vlogic Lang.var val)) => tyPure.\nReify Pattern patterns_java_typ += (!! Prop) => tyProp.\nReify Pattern patterns_java_typ += (!! spec) => tySpec.\n\nReify Pattern patterns_java_typ += (!! @prod @ ?0 @ ?1) => (fun (x y : function reify_imp_typ) => tyPair x y).\nReify Pattern patterns_java_typ += (!! (@list String.string)) => tyVarList.\nReify Pattern patterns_java_typ += (!! (@list field)) => tyFields.\nReify Pattern patterns_java_typ += (!! (@list (@Open.expr (Lang.var) val))) => tyVarList.\nReify Pattern patterns_java_typ += (!! (@list (Lang.var * @Open.expr (Lang.var) val))) => tySubstList.\nReify Pattern patterns_java_typ += (!! (@substlist Lang.var val)) => tySubstList.\nReify Pattern patterns_java_typ += (!! @list @ ?0) => (fun x : function reify_imp_typ => tyList x).\nReify Pattern patterns_java_typ += (!! nat) => tyNat.\nReify Pattern patterns_java_typ += (!! val) => tyVal.\nReify Pattern patterns_java_typ += (!! bool) => tyBool.\nReify Pattern patterns_java_typ += (!! field) => tyString.\nReify Pattern patterns_java_typ += (!! class) => tyString.\nReify Pattern patterns_java_typ += (!! @Open.open Lang.var val asn) => tySasn.\nReify Pattern patterns_java_typ += (!! @Open.open Lang.var val Prop) => tyPure.\nReify Pattern patterns_java_typ += (!! Lang.var) => tyString.\nReify Pattern patterns_java_typ += (!! String.string) => tyString.\nReify Pattern patterns_java_typ += (!! Program) => tyProg.\nReify Pattern patterns_java_typ += (!! stack) => tyStack.\nReify Pattern patterns_java_typ += (!! @Stack.stack Lang.var val) => tyStack.\nReify Pattern patterns_java_typ += (!! cmd) => tyCmd.\nReify Pattern patterns_java_typ += (!! dexpr) => tyExpr.\nReify Pattern patterns_java_typ += (!! (@Open.expr Lang.var val)) => tyExpr.\nReify Pattern patterns_java_typ += (!! @Subst.subst (String.string) val) => tySubst.\n\nReify Pattern patterns_java_typ += (!! Fun @ ?0 @ ?1) => (fun (a b : function reify_imp_typ) => tyArr a b).\n\nReify Pattern patterns_java += (RHasType String.string (?0)) => (fun (s : id String.string) => mkString (func := func) (typ := typ) s).\nReify Pattern patterns_java += (RHasType field (?0)) => (fun (f : id field) => mkString (func := func) f).\nReify Pattern patterns_java += (RHasType Lang.var (?0)) => (fun (f : id Lang.var) => mkString (func := func) f).\nReify Pattern patterns_java += (RHasType val (?0)) => (fun (v : id val) => mkVal v).\nReify Pattern patterns_java += (RHasType bool (?0)) => (fun (b : id bool) => mkBool (func := func) b).\nReify Pattern patterns_java += (RHasType nat (?0)) => (fun (n : id nat) => mkNat (func := func) n).\nReify Pattern patterns_java += (RHasType cmd (?0)) => (fun (c : id cmd) => mkCmd c).\nReify Pattern patterns_java += (RHasType dexpr (?0)) => (fun (e : id dexpr) => mkDExpr e).\nReify Pattern patterns_java += (RHasType Program (?0)) => (fun (P : id Program) => mkProg P).\nReify Pattern patterns_java += (RHasType (list field) (?0)) => (fun (fs : id (list field)) => mkFields fs).\nReify Pattern patterns_java += (RHasType class (?0)) => (fun (c : id class) => mkString (func := func) c).\n\nReify Pattern patterns_java += (RHasType (@list dexpr) (?0)) => (fun (es : id (@list dexpr)) => mkExprList es).\nReify Pattern patterns_java += (RHasType (@list String.string) (?0)) => (fun (vs : id (@list String.string)) => mkVarList vs).\nReify Pattern patterns_java += (!! (@eq) @ ?0) => (fun (x : function reify_imp_typ) => fEq (func := expr typ func) x).\n\n(** Intuitionistic Operators **)\nReify Pattern patterns_java += (!! @ILogic.lentails @ ?0 @ #) => (fun (x : function reify_imp_typ) => fEntails (func := expr typ func) x).\nReify Pattern patterns_java += (!! @ILogic.ltrue @ ?0 @ #) => (fun (x : function reify_imp_typ) => mkTrue (func := func) x).\nReify Pattern patterns_java += (!! @ILogic.lfalse @ ?0 @ #) => (fun (x : function reify_imp_typ) => mkFalse (func := func) x).\nReify Pattern patterns_java += (!! @ILogic.land @ ?0 @ #) => (fun (x : function reify_imp_typ) => fAnd (func := expr typ func) x).\nReify Pattern patterns_java += (!! @ILogic.lor @ ?0 @ #) => (fun (x : function reify_imp_typ) => fOr (func := expr typ func) x).\nReify Pattern patterns_java += (!! @ILogic.limpl @ ?0 @ #) => (fun (x : function reify_imp_typ) => fImpl (func := expr typ func) x).\n\nReify Pattern patterns_java += (!! @ILogic.lexists @ ?0 @ # @ ?1) => (fun (x y : function reify_imp_typ) => fExists (func := expr typ func) y x).\n\nReify Pattern patterns_java += (!! @ILogic.lforall @ ?0 @ # @ ?1) => (fun (x y : function reify_imp_typ) => fForall (func := expr typ func) y x).\n(** Embedding Operators **)\nReify Pattern patterns_java += (!! @ILEmbed.embed @ ?0 @ ?1 @ #) => (fun (x y : function reify_imp_typ) => fEmbed (func := expr typ func) x y).\n\nReify Pattern patterns_java += (!! @pair @ ?0 @ ?1) => (fun (x y : function reify_imp_typ) => fPair (func := expr typ func) x y).\n\n(** Special cases for Coq's primitives **)\nReify Pattern patterns_java += (!! True) => (mkTrue (func := func) tyProp).\nReify Pattern patterns_java += (!! False) => (mkFalse (func := func) tyProp).\nReify Pattern patterns_java += (!! and) => (fAnd (func := expr typ func) tyProp).\n\nReify Pattern patterns_java += (!! or) => (fOr (func := expr typ func) tyProp).\n\nReify Pattern patterns_java += (!! ex @ ?0) => (fun (x : function reify_imp_typ) => fExists (func := expr typ func) x tyProp).\n\nReify Pattern patterns_java += (RPi (?0) (?1)) => (fun (x : function reify_imp_typ) (y : function reify_imp) =>\n                                                   ExprCore.App (fForall (func := expr typ func) x tyProp) (ExprCore.Abs x y)).\n\nReify Pattern patterns_java += (RImpl (?0) (?1)) => (fun (x y : function reify_imp) => \n\tExprCore.App (ExprCore.App (fImpl (func := expr typ func) tyProp) x) y).\n\n(** Separation Logic Operators **)\nReify Pattern patterns_java += (!! @BILogic.sepSP @ ?0 @ #) => (fun (x : function reify_imp_typ) => (fStar (func := expr typ func) x)).\nReify Pattern patterns_java += (!! @BILogic.wandSP @ ?0 @ #) => (fun (x : function reify_imp_typ) => (fWand (func := expr typ func) x)).\nReify Pattern patterns_java += (!! @BILogic.empSP @ ?0 @ #) => (fun (x : function reify_imp_typ) => (mkEmp (func := func) x)).\n\nReify Pattern patterns_java += (!! @Later.illater @ ?0 @ #) => (fun (x : function reify_imp_typ) => (fLater (func := expr typ func) x)).\n\nReify Pattern patterns_java += (!! method_spec) => (fMethodSpec).\n\n(** Program Logic **)\n\n\nReify Pattern patterns_java += (!! triple) => (fTriple).\nReify Pattern patterns_java += (!! eval @ (RHasType dexpr (?0))) => (fun e : id dexpr => evalDExpr e).\nReify Pattern patterns_java += (!! stack_get) => (fStackGet (typ := typ) (func := expr typ func)).\nReify Pattern patterns_java += (!! stack_add (val := val)) => (fStackSet (typ := typ) (func := expr typ func)).\n\nReify Pattern patterns_java += (!! pointsto) => (fPointsto).\nReify Pattern patterns_java += (!! prog_eq) => (fProgEq).\nReify Pattern patterns_java += (!! typeof) => (fTypeOf).\n\nReify Pattern patterns_java += (!! (@substl_trunc Lang.var val _)) => (fTruncSubst (func := expr typ func) (typ := typ)).\nReify Pattern patterns_java += (!! (@substl Lang.var val _)) => (fSubst (func := expr typ func) (typ := typ)).\n\nReify Pattern patterns_java += (!! @nil @ ?0) => (fun (x : function reify_imp_typ) => (fNil (func := expr typ func) x)).\nReify Pattern patterns_java += (!! @cons @ ?0) => (fun (x : function reify_imp_typ) => (fCons (func := expr typ func) x)).\nReify Pattern patterns_java += (!! @length @ ?0) => (fun (x : function reify_imp_typ) => (fLength (func := expr typ func) x)).\nReify Pattern patterns_java += (!! @zip @ ?0 @ ?1) => (fun (x y : function reify_imp_typ) => (fZip (func := expr typ func) x y)).\nReify Pattern patterns_java += (!! @map @ ?0 @ ?1) => (fun (x y : function reify_imp_typ) => (fMap (func := expr typ func) x y)).\nReify Pattern patterns_java += (!! @fold_right @ ?0 @ ?1) => (fun (x y : function reify_imp_typ) => (fFold (func := expr typ func) x y)).\n\nReify Pattern patterns_java += (!! (@apply_subst Lang.var val) @ ?0) => (fun (x : function reify_imp_typ) => fApplySubst (func := expr typ func) x).\nReify Pattern patterns_java += (!! @subst1 Lang.var val _) => (fSingleSubst (func := expr typ func)).\nReify Pattern patterns_java += (!! @field_lookup) => (fFieldLookup).\n(** Applicative **)\nReify Pattern patterns_java += (!! @Applicative.ap @ !! (Fun stack) @ # @ ?0 @ ?1) => (fun (x y : function reify_imp_typ) => fAp (func := expr typ func) x y).\nReify Pattern patterns_java += (!! @Applicative.pure @ !! (Fun stack) @ # @ ?0) => (fun (x : function reify_imp_typ) => fConst (func := expr typ func) x).\n\nLet elem_ctor : forall x : typ, typD x -> @SymEnv.function _ _ :=\n  @SymEnv.F _ _.\n\nLtac reify_imp e :=\n  let k fs e :=\n      pose e in\n  reify_expr reify_imp k\n             [ (fun (y : @mk_dvar_map _ _ _ _ term_table elem_ctor) => True) ]\n             [ e ].\n\nRequire Import ILogic.\n\nGoal (forall (Pr : Program) (C : class) (v : val) (fields : list field), True).\n  intros Pr C v fields.\n  reify_imp (typeof C v).\n\n  reify_imp (field_lookup).\n  reify_imp (field_lookup Pr C fields).\n\n  pose ((fun (_ : @Stack.stack Lang.var val) => null) : @Open.expr Lang.var val) as e2.\n  pose ((fun (_ : stack) => null) : stack -> val) as e3.\n\n\n  reify_imp (pure (T := Fun stack) pointsto).\n\n  reify_imp (fun a b c => pointsto a b c).\n\n  reify_imp e2.\n\n  reify_imp e3.\n\n  reify_imp (ap (T := Fun stack) (ap (T := Fun stack) (pure (@eq val)) e2) e2).\n\n  pose (E_val (vint 3)) as d.\n\n  reify_imp ((ap (ap (T := Fun stack) (pure (@eq val)) (eval d)) (pure (vbool true)))).\n  \n  generalize String.EmptyString. intro c.\n   reify_imp (ltrue |-- {[ ltrue ]} cread c c c {[ ltrue ]}).\n\n  reify_imp cskip.\n\n  reify_imp (forall P, P /\\ P).\n\n  reify_imp (forall x : nat, x = x).\n  reify_imp (exists x : nat, x = x).\n  reify_imp (@map nat nat).\n  reify_imp (@subst1 Lang.var val _).\n  reify_imp (cseq cskip cskip).\n  \n  reify_imp (ILogic.lentails True True).\n\n  reify_imp ((True -> False) -> True).\n  reify_imp (forall P Q, P /\\ Q).\n  reify_imp (forall P : sasn, ILogic.lentails ILogic.ltrue P).\n  reify_imp (forall (G : spec) (P Q : sasn), ILogic.lentails G (triple P Q cskip)).\n  generalize (String.EmptyString : String.string).\n  intro x.\n\n  reify_imp stack_get.\n\n  reify_imp (stack_get x).\n\n  reify_imp (x = x).\n\n  reify_imp (@ltrue sasn _).\n  exact I.\n\nDefined.\n\nLtac reify_aux e n :=\n  let k fs e :=\n      pose e as n in\n  reify_expr reify_imp k\n             [ (fun (y : @mk_dvar_map _ _ _ _ term_table elem_ctor) => True) ]\n             [ e ].\n", "meta": {"author": "jesper-bengtson", "repo": "MirrorCharge", "sha": "cb0fe1da80be70ba4b744d4178a4e6e3afa38e62", "save_path": "github-repos/coq/jesper-bengtson-MirrorCharge", "path": "github-repos/coq/jesper-bengtson-MirrorCharge/MirrorCharge-cb0fe1da80be70ba4b744d4178a4e6e3afa38e62/MirrorCharge!/src/MirrorCharge/Java/Reify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2123836911449199}}
{"text": "(******************************************************************************)\n(** * A compilation correctness proof from the Promising2 memory model to\n      the IMM memory model. *)\n(******************************************************************************)\nRequire Import Omega.\nFrom hahn Require Import Hahn.\nRequire Import PromisingLib.\nFrom Promising2 Require Import TView View Time Event Cell Thread Memory Configuration Local.\nFrom imm Require Import Prog.\nFrom imm Require Import ProgToExecution.\nFrom imm Require Import Events.\nFrom imm Require Import Execution.\nFrom imm Require Import imm_s.\nFrom imm Require Import CombRelations.\nFrom imm Require Import ProgToExecutionProperties.\nFrom imm Require Import RMWinstrProps.\nFrom imm Require Import AuxRel2.\n\nRequire Import SimulationRel.\nRequire Import PlainStepBasic.\nRequire Import SimulationPlainStep.\nRequire Import MaxValue.\nRequire Import SimState.\nRequire Import Event_imm_promise.\nRequire Import PromiseOutcome.\nRequire Import CertGraphInit.\nRequire Import MemoryAux.\nRequire Import PromiseLTS.\nFrom imm Require Import Traversal.\nFrom imm Require Import TraversalConfig.\nRequire Import ExtSimTraversal.\nRequire Import ExtSimTraversalProperties.\nRequire Import ExtTraversalConfig.\nRequire Import ExtTraversal.\nRequire Import ExtTraversalCounting.\nRequire Import SimulationPlainStepAux.\nRequire Import FtoCoherent.\nRequire Import AuxTime.\n\nSet Implicit Arguments.\nRemove Hints plus_n_O.\n\nLemma istep_nil_eq_silent thread :\n  istep thread nil ≡\n  lts_step thread ProgramEvent.silent.\nProof using.\n  unfold lts_step. unfold lab_imm_promise.\n  split; [|basic_solver].\n  unfolder. ins. exists nil. eauto.\nQed.\n\n(* TODO: move *)\nLemma InAE A x (l : list A) : SetoidList.InA eq x l <-> In x l.\nProof using.\n  split; [by induction 1; desf; ins; eauto|].\n  induction l; ins; desf; eauto using SetoidList.InA.\nQed.\n\n(* TODO: move *)\nLemma NoDupAE A (l : list A) : SetoidList.NoDupA eq l <-> NoDup l.\nProof using.\n  split; induction 1; constructor; eauto; rewrite InAE in *; eauto.\nQed.\n\n(* TODO: move *)\nLemma NoDup_map_NoDupA A B (f : A -> B) l :\n  SetoidList.NoDupA (fun p p' => f p = f p') l ->\n  NoDup (map f l).\nProof using.\n  induction 1; ins; constructor; eauto.\n  clear -H; intro M; destruct H; induction l; ins; desf;\n    eauto using SetoidList.InA.\nQed.\n\n(* TODO: move to to imm/RMWinstrProps.v. *)\nLemma dom_rmw_in_rex_thread_steps thread s s'\n      (RMWREX : rmw_is_rex_instrs s.(instrs))\n      (WF : wf_thread_state thread s)\n      (STEPS : (step thread)^* s s')\n      (SS : dom_rmw_in_rex s) :\n  dom_rmw_in_rex s'.\nProof using.\n  apply clos_rt_rtn1_iff in STEPS.\n  induction STEPS; auto.\n  apply clos_rt_rtn1_iff in STEPS.\n  eapply dom_rmw_in_rex_thread_step with (s:=y); eauto.\n  { erewrite steps_preserve_instrs; eauto. }\n  eapply wf_thread_state_steps; eauto.\nQed.\n\nDefinition execution_final_memory (G : execution) final_memory :=\n  forall l,\n    (⟪ NO : forall e (EE : acts_set G e), loc G.(lab) e <> Some l ⟫ /\\\n     ⟪ ZERO : final_memory l = 0 ⟫) \\/\n    exists w,\n      ⟪ ACTS : G.(acts_set) w ⟫ /\\\n      ⟪ WW   : is_w G.(lab) w ⟫ /\\\n      ⟪ LOC  : loc  G.(lab) w = Some l ⟫ /\\\n      ⟪ VAL  : val  G.(lab) w = Some (final_memory l) ⟫ /\\\n      ⟪ LAST : ~ (exists w', G.(co) w w') ⟫.\n\nNotation \"'NTid_' t\" := (fun x => tid x <> t) (at level 1).\nNotation \"'Tid_' t\"  := (fun x => tid x =  t) (at level 1).\n\nLemma cert_sim_step G sc thread PC T T' f_to f_from smode\n      (WF : Wf G) (IMMCON : imm_consistent G sc)\n      (STEP : ext_isim_trav_step G sc thread T T')\n      (SIMREL : simrel_thread G sc PC (etc_TC T) (reserved T) f_to f_from thread smode)\n      (NCOV : NTid_ thread ∩₁ G.(acts_set) ⊆₁ ecovered T) :\n    exists PC' f_to' f_from',\n      ⟪ PSTEP : (plain_step MachineEvent.silent thread)＊ PC PC' ⟫ /\\\n      ⟪ SIMREL : simrel_thread G sc PC' (etc_TC T') (reserved T') f_to' f_from' thread smode ⟫.\nProof using.\n  destruct T as [T S].\n  destruct T' as [T' S'].\n  unfold ecovered in *. simpls.\n  eapply plain_sim_step in STEP; eauto.\n  desf. eexists. eexists. eexists. splits; eauto.\nQed.\n\nLemma cert_sim_steps G sc thread PC T T' f_to f_from smode\n      (WF : Wf G) (IMMCON : imm_consistent G sc)\n      (STEPS : (ext_isim_trav_step G sc thread)⁺ T T')\n      (SIMREL : simrel_thread G sc PC (etc_TC T) (reserved T) f_to f_from thread smode)\n      (NCOV : NTid_ thread ∩₁ G.(acts_set) ⊆₁ ecovered T) :\n    exists PC' f_to' f_from',\n      ⟪ PSTEP : (plain_step MachineEvent.silent thread)＊ PC PC' ⟫ /\\\n      ⟪ SIMREL : simrel_thread G sc PC' (etc_TC T') (reserved T') f_to' f_from' thread  smode ⟫.\nProof using.\n  generalize dependent f_from.\n  generalize dependent f_to.\n  generalize dependent PC.\n  induction STEPS.\n  { ins. eapply cert_sim_step in H; eauto. }\n  ins.\n  apply IHSTEPS1 in SIMREL; auto.\n  desf.\n  apply IHSTEPS2 in SIMREL0; auto.\n  { desf. eexists. eexists. eexists. splits.\n    2: by eauto.\n    eapply rt_trans; eauto. }\n  etransitivity; eauto.\n  eapply ext_sim_trav_steps_covered_le with (G:=G) (sc:=sc).\n  apply inclusion_t_rt.\n  generalize STEPS1. clear.\n  generalize dependent y. generalize dependent x.\n  apply inclusion_t_t.\n  unfold ext_sim_trav_step.\n  basic_solver.\nQed.\n\nLemma cert_simulation G sc thread PC T S f_to f_from\n      (WF : Wf G) (IMMCON : imm_consistent G sc)\n      (SIMREL : simrel_thread G sc PC T S f_to f_from thread sim_certification)\n      (NCOV : NTid_ thread ∩₁ G.(acts_set) ⊆₁ covered T) :\n  exists T' S' PC' f_to' f_from',\n    ⟪ FINALT : G.(acts_set) ⊆₁ covered T' ⟫ /\\\n    ⟪ PSTEP  : (plain_step MachineEvent.silent thread)＊ PC PC' ⟫ /\\\n    ⟪ SIMREL : simrel_thread G sc PC' T' S' f_to' f_from' thread sim_certification⟫.\nProof using.\n  assert (etc_coherent G sc (mkETC T S)) as ETCCOH.\n  { apply SIMREL. }\n  generalize (sim_step_cov_full_traversal WF IMMCON ETCCOH NCOV); intros H.\n  destruct H as [T'].\n  1,2: by apply SIMREL.\n  desc.\n  destruct T' as [T' S'].\n  exists T', S'. apply rtE in H.\n  destruct H as [H|H].\n  { red in H. desf.\n    eexists. eexists. eexists.\n    splits; eauto.\n    apply rtE. left. red. eauto. }\n  eapply cert_sim_steps in H; auto.\n  2: by eauto.\n  desf. eexists. eexists. eexists. splits; eauto.\nQed.\n\nLemma simrel_thread_bigger_sc_memory G sc T S thread f_to f_from threads memory\n      sc_view memory' sc_view'\n      lang state local\n      (WF : Wf G) (IMMCON : imm_consistent G sc)\n      (THREAD     : IdentMap.find thread threads = Some (existT _ lang state, local))\n      (INHAB      : Memory.inhabited memory' )\n      (CLOSED_MEM : Memory.closed memory')\n      (MEM_LE : Memory.le memory memory')\n      (SС_CLOSED  : Memory.closed_timemap sc_view' memory')\n      (SIMREL : simrel_thread G sc (Configuration.mk threads sc_view memory )\n                              T S f_to f_from thread  sim_certification) :\n  simrel_thread G sc (Configuration.mk threads sc_view' memory') T S f_to f_from\n                thread sim_certification.\nProof using.\n  cdes SIMREL. cdes COMMON. cdes LOCAL.\n  red; splits; red; splits; eauto; ins.\n  { ins. etransitivity.\n    { eapply PROM_IN_MEM; eauto. }\n    done. }\n  eexists. eexists. eexists; eauto. splits; eauto.\n  3: by eapply memory_close_le; eauto.\n  2: { red. ins. edestruct SIM_RES_MEM as [rel_opt H]; eauto. }\n  red. ins.\n  edestruct SIM_MEM as [rel_opt H]; eauto.\n  simpls. desf.\n  exists rel_opt; splits; eauto.\n  { eapply memory_closed_timemap_le; eauto. }\n  ins. destruct H1; eauto. unnw. desc.\n  splits; auto.\n  exists p_rel. splits; auto.\n  desf; [by left| right].\n  apply MEM_LE in H5.\n  exists p; splits; auto.\n  exists p_v; splits; auto.\nQed.\n\nSection PromiseToIMM.\n  \nVariable prog : Prog.t.\nHypothesis TNONULL : ~ IdentMap.In tid_init prog.\n\nVariable G : execution.\nVariable final_memory : location -> value.\n\nHypothesis ALLRLX  : G.(acts_set) \\₁ is_init ⊆₁ (fun a => is_true (is_rlx G.(lab) a)).\nHypothesis FRELACQ : G.(acts_set) ∩₁ (fun a => is_true (is_f G.(lab) a)) ⊆₁ (fun a => is_true (is_ra G.(lab) a)).\n\nHypothesis EFM : execution_final_memory G final_memory.\n\nHypothesis PROG_EX : program_execution prog G.\nHypothesis RMWREX  : forall thread linstr\n                            (IN : Some linstr = IdentMap.find thread prog),\n    rmw_is_rex_instrs linstr.\nHypothesis WF : Wf G.\nVariable sc : relation actid.\nHypothesis IMMCON : imm_consistent G sc.\n\nLemma conf_steps_preserve_thread tid PC PC'\n      (STEPS : (plain_step MachineEvent.silent tid)＊ PC PC') :\n  forall lang state local\n         (THREAD  : IdentMap.find tid PC.(Configuration.threads) =\n                    Some (existT _ lang  state , local)),\n  exists lang' state' local',\n    IdentMap.find tid PC'.(Configuration.threads) =\n    Some (existT _ lang' state', local').\nProof using.\n  induction STEPS.\n  2: { ins. eauto. }\n  { destruct H.\n    simpls. rewrite IdentMap.gss. eauto. }\n  ins. edestruct IHSTEPS1; eauto. desc.\n  eapply IHSTEPS2; eauto.\nQed.\n\nLemma conf_steps_preserve_lang tid PC PC'\n      (STEPS : (plain_step MachineEvent.silent tid)＊ PC PC') :\n  forall lang  state  local lang' state' local'\n         (THREAD  : IdentMap.find tid PC.(Configuration.threads) =\n                    Some (existT _ lang  state , local))\n         (THREAD' : IdentMap.find tid PC'.(Configuration.threads) =\n                    Some (existT _ lang' state', local')),\n    lang = lang'.\nProof using.\n  induction STEPS.\n  2: { ins. rewrite THREAD' in THREAD. inv THREAD. }\n  { destruct H.\n    simpls. rewrite IdentMap.gss.\n    ins. desf. }\n  ins.\n  edestruct conf_steps_preserve_thread with (PC':=y); eauto. desc.\n  etransitivity.\n  { eapply IHSTEPS1; eauto. }\n  eapply IHSTEPS2; eauto.\nQed.\n\nLemma conf_steps_to_thread_steps tid PC PC'\n      (STEPS : (plain_step MachineEvent.silent tid)＊ PC PC') :\n  forall lang state local\n         state' local' ts ts' \n         (THREAD  : IdentMap.find tid PC.(Configuration.threads) =\n                    Some (existT _ lang state, local))\n         (THREAD' : IdentMap.find tid PC'.(Configuration.threads) =\n                    Some (existT _ lang state', local'))\n         (TS  : ts  = Thread.mk lang state local\n                                PC.(Configuration.sc) PC.(Configuration.memory))\n         (TS' : ts' = Thread.mk lang state' local'\n                                PC'.(Configuration.sc) PC'.(Configuration.memory)),\n    rtc (Thread.tau_step (lang:=lang)) ts ts'.\nProof using.\n  induction STEPS.\n  2: { ins. apply rtc_refl.\n       rewrite TS, TS'.\n       rewrite THREAD' in THREAD. inv THREAD. }\n  { set (pe := MachineEvent.silent) in H.\n    assert (pe = MachineEvent.silent) as HH.\n    { done. }\n    destruct H.\n    simpls. rewrite IdentMap.gss.\n    ins. desf. eapply rtc_n1; eauto.\n    red. econstructor.\n    { econstructor; eauto. }\n    done. }\n  ins.\n  edestruct conf_steps_preserve_thread with (PC':=y); eauto. desc.\n  assert (x0 = lang); subst.\n  { eapply conf_steps_preserve_lang; eauto. }\n  etransitivity.\n  { eapply IHSTEPS1; eauto. }\n  eapply IHSTEPS2; eauto.\nQed.\n\nLemma event_to_prog_thread e (ACT : acts_set G e) (NINIT : ~ is_init e) :\n  IdentMap.In (tid e) prog.\nProof using PROG_EX.\n  red in PROG_EX.\n  destruct PROG_EX as [HH OO].\n  destruct (HH e ACT) as [|AA]; [by desf|done].\nQed.\n\nLemma dom_rmw_in_R_ex : dom_rel (rmw G) ⊆₁ (fun a : actid => R_ex (lab G) a).\nProof using PROG_EX RMWREX WF.\n  red in PROG_EX.\n  intros x H.\n  destruct H as [y RMW].\n  assert (acts_set G x) as EX.\n  { apply (dom_l WF.(wf_rmwE)) in RMW.\n    apply seq_eqv_l in RMW. desf. }\n  rename PROG_EX into HH. destruct HH as [PROG_EX PEX].\n  specialize (PROG_EX x EX).\n  destruct PROG_EX as [INIT|TH]. \n  { exfalso. apply (rmw_from_non_init WF) in RMW.\n    apply seq_eqv_l in RMW. desf. }\n  apply IdentMap.Facts.in_find_iff in TH.\n  destruct (IdentMap.find (tid x) prog) eqn: INP.\n  2: done.\n  symmetry in INP.\n  set (PP:=INP).\n  apply PEX in PP. desc. subst.\n  red in PP. desc.\n  rewrite <- PEQ in *.\n  assert (acts_set s.(ProgToExecution.G) x) as SX.\n  { apply PP0.(tr_acts_set). by split. }\n  unfold R_ex.\n  assert (lab G x = lab (ProgToExecution.G s) x) as LL.\n  { eapply lab_thread_eq_thread_restricted_lab; eauto. }\n  assert (s.(ProgToExecution.G).(rmw) x y) as SRMW.\n  { apply PP0.(tr_rmw).\n    simpls. apply seq_eqv_l; split; auto.\n    apply seq_eqv_r. split; auto.\n    apply WF.(wf_rmwt) in RMW. symmetry. apply RMW. }\n  assert (dom_rmw_in_rex s) as YY.\n  2: { specialize (YY x). rewrite LL.\n       apply YY. by exists y. }\n  apply RMWREX in INP.\n  eapply dom_rmw_in_rex_thread_steps; eauto.\n  { unfold init; simpls. }\n  { apply wf_thread_state_init. }\n  red. unfold init. simpls. clear. basic_solver.\nQed.\n\nLemma simrel_init :\n  simrel G sc (conf_init prog)\n         (init_trav G) (is_init ∩₁ acts_set G)\n         (fun _ => tid_init) (fun _ => tid_init).\nProof using ALLRLX IMMCON PROG_EX TNONULL WF FRELACQ RMWREX.\n  red; splits; red; splits; auto.\n  { by apply ext_init_trav_coherent. }\n  { simpls. basic_solver. }\n  { ins. split; intros [INIT GG]; exfalso.\n    { apply WF.(init_w) in INIT.\n      apply (dom_l WF.(wf_rmwD)) in RMW.\n      apply seq_eqv_l in RMW.\n      type_solver. }\n    apply WF.(rmw_in_sb) in RMW.\n    apply no_sb_to_init in RMW.\n    apply seq_eqv_r in RMW. desf. }\n  { ins.\n    unfold Threads.init.\n    rewrite IdentMap.Facts.map_o.\n    unfold init_threads.\n    rewrite IdentMap.gmapi.\n    assert (IdentMap.In (tid e) prog) as INE.\n    { by apply event_to_prog_thread. }\n    assert (exists linstr, IdentMap.find (tid e) prog = Some linstr)\n      as [linstr LI].\n    { apply IdentMap.Facts.in_find_iff in INE.\n      destruct (IdentMap.find (tid e) prog) eqn: H; desf.\n      eauto. }\n    rewrite LI. simpls. eauto. }\n  { ins. unfold init_threads, Threads.init in *.\n    rewrite IdentMap.Facts.map_o in TID.\n    rewrite IdentMap.gmapi in TID.\n    destruct (IdentMap.find thread' prog) eqn: HH; simpls.\n    inv TID. unfold Local.init. simpls.\n    apply Memory.bot_le. }\n  { assert (complete G) as CG.\n    { apply IMMCON. }\n    assert (Execution_eco.sc_per_loc G) as ESC.\n    { apply imm_s_hb.coherence_sc_per_loc. apply IMMCON. }\n    red. splits; simpls.\n    { ins. destruct H. desf. }\n    all: ins; exfalso.\n    apply Execution_eco.no_co_to_init in H1; auto.\n    apply seq_eqv_r in H1.\n    destruct H0. desf. }\n  { ins. }\n  { ins.\n    unfold LocFun.find, TimeMap.bot.\n    apply max_value_empty.\n    unfold S_tm, S_tmr.\n    ins. intros HH.\n    destruct HH as [y HH].\n    apply seq_eqv_l in HH. destruct HH as [_ HH].\n    destruct HH as [z [_ HH]].\n    destruct HH as [w [_ HH]].\n    apply seq_eqv_r in HH. destruct HH as [HH [AA BB]].\n    red in HH. destruct HH as [CC [HH _]]. subst.\n    apply WF.(init_w) in AA.\n    type_solver. }\n  { apply dom_rmw_in_R_ex. }\n  { red. splits; ins.\n    3: { match goal with\n         | H : co _ _ _ |- _ => rename H into CO\n         end.\n         apply Execution_eco.no_co_to_init in CO; auto.\n         2: { apply imm_s_hb.coherence_sc_per_loc.\n              apply IMMCON. }\n         unfolder in *. desf. }\n    2: { red. ins. apply memory_init_o in MSG. desf. }\n    red; ins. unfold Memory.init in MSG.\n    unfold Memory.get in MSG.\n    unfold Cell.init in MSG.\n    unfold Cell.get in MSG; simpls.\n    unfold Cell.Raw.init in MSG.\n    destruct (classic (to = Time.bot)) as [|NEQ]; subst.\n    2: { rewrite DenseOrder.DOMap.singleton_neq in MSG; auto.\n         inv MSG. }\n    rewrite DenseOrder.DOMap.singleton_eq in MSG. inv MSG.\n    left. by split. }\n  { unfold conf_init, Configuration.init.\n    simpls.\n    edestruct TView.bot_closed.\n    unfold TView.bot, View.bot in *; simpls.\n    destruct CUR. simpls. }\n  { simpls. apply Memory.init_closed. }\n  simpls.\n  apply IdentMap.Facts.in_find_iff in TP.\n  destruct (IdentMap.find thread (Threads.init (init_threads prog))) eqn: HH; simpls.\n  clear TP.\n  unfold Threads.init in *.\n  rewrite IdentMap.Facts.map_o in *.\n  unfold init_threads in *.\n  rewrite IdentMap.gmapi in *.\n  destruct (IdentMap.find thread prog) eqn: UU; simpls.\n  inv HH. clear HH.\n  simpls.\n  exists (init l), (Local.init); splits; auto.\n  { red; ins; desf; apply TNONULL, IdentMap.Facts.in_find_iff; congruence. }\n  { apply wf_thread_state_init. }\n  { symmetry in UU. apply RMWREX in UU. unfold init. simpls. }\n  { ins. left. apply Memory.bot_get. }\n  { red. ins.\n    unfold Local.init in *. simpls. \n    rewrite Memory.bot_get in PROM. inv PROM. }\n  { red. ins. rewrite Memory.bot_get in RES. inv RES. }\n  { red; simpls.\n    unfold Memory.init. unfold Memory.get. unfold Cell.init.\n    unfold Cell.get; simpls. unfold Cell.Raw.init.\n    rewrite DenseOrder.DOMap.singleton_eq.\n    exists None. splits; ins.\n    { unfold Message.elt.\n      assert (v = 0); [|by desf].\n      destruct ISSB as [II _].\n      destruct b.\n      2: by inv II.\n      unfold val in VAL.\n      rewrite WF.(wf_init_lab) in VAL.\n      inv VAL. }\n    { red. splits; auto.\n      { right. splits; auto. apply ISSB. }\n      red. ins. unfold LocFun.find, TimeMap.bot.\n      apply max_value_bot_f. }\n    red. unfold View.unwrap, View.bot, TimeMap.bot. simpls.\n    ins. eexists. eexists. eexists.\n    unfold Memory.get, Cell.get. simpls. }\n  { red; simpls. }\n  { unfold Local.init. simpls.\n    unfold TView.bot. red; simpls.\n    unfold View.bot.\n    splits; simpls; red.\n    all: unfold LocFun.find, TimeMap.bot; simpls.\n    all: ins.\n    all: apply max_value_bot_f. }\n  { unfold Local.init. simpls. }\n  { unfold Local.init. simpls. red.\n    unfold TView.bot; simpls. splits; ins.\n    all: apply Memory.closed_timemap_bot.\n    all: red; ins. }\n  red. splits.\n  { ins. split; ins; [|omega].\n    destruct H as [H _]. simpls. }\n  unfold sim_state_helper.\n  red in PROG_EX. destruct PROG_EX as [HH YY].\n  symmetry in UU. apply YY in UU.\n  desc. red in UU. desc.\n  eexists. splits; eauto. by subst.\nQed.\n\nDefinition thread_is_terminal ths tid :=\n  forall (lang : Language.t ProgramEvent.t) st lc\n         (LLH : IdentMap.find tid ths =\n                Some (existT (fun lang => Language.state lang) lang st, lc)),\n    ⟪ NOTS : Language.is_terminal lang st ⟫ /\\\n    ⟪ NOPROM : Local.is_terminal lc ⟫.\n\nLemma sim_thread_covered_exists_terminal PC thread T S f_to f_from\n      (FINALT : Tid_ thread ∩₁ acts_set G ⊆₁ covered T)\n      (SIMREL : simrel G sc PC T S f_to f_from) :\n  exists PC',\n    ⟪ STEP : (conf_step)^? PC PC' ⟫ /\\\n    ⟪ SIMREL : simrel G sc PC' T S f_to f_from ⟫ /\\\n    ⟪ SAMENUM : Permutation (map fst (IdentMap.elements (Configuration.threads PC))) \n                            (map fst (IdentMap.elements (Configuration.threads PC'))) ⟫ /\\ \n    ⟪ TERMINAL  : thread_is_terminal PC'.(Configuration.threads) thread ⟫ /\\\n    ⟪ PTERMINAL :\n      forall thread' (TT : thread_is_terminal PC.(Configuration.threads) thread'),\n        thread_is_terminal PC'.(Configuration.threads) thread' ⟫.\nProof using All.\n  cdes SIMREL.\n  destruct (IdentMap.find thread (Configuration.threads PC)) as [j|] eqn: QQ.\n  2: { exists PC. splits; auto.\n       red. ins.\n       clear -QQ LLH.\n       (* This trick is needed due to an implicit parameter which could be seen\n          by `Set Printing All.` *)\n       match goal with\n       | H1 : ?A = None,\n         H2 : ?B = Some _ |- _ =>\n         assert (A = B) as AA\n       end.\n       { unfold language. done. }\n       rewrite AA in QQ.\n       destruct (IdentMap.find thread (Configuration.threads PC)); desf. }\n  assert (IdentMap.In thread (Configuration.threads PC)) as YY.\n  { apply IdentMap.Facts.in_find_iff. by rewrite QQ. }\n  apply THREADS in YY. cdes YY.\n  cdes STATE. cdes STATE1.\n  assert (Local.promises local = Memory.bot) as PBOT.\n  { red in SIM_PROM.\n    eapply Memory.ext. ins.\n    rewrite Memory.bot_get.\n    destruct (Memory.get loc ts (Local.promises local)) eqn: H; auto.\n    destruct p as [from msg].\n    destruct msg as [v msg|].\n    { eapply SIM_PROM in H; eauto.\n      desc.\n      exfalso. apply NCOV. by apply FINALT. }\n    eapply SIM_RPROM in H; eauto. desc.\n    exfalso.\n    apply NOISS. eapply w_covered_issued.\n    { apply COMMON. }\n    split.\n    { eapply reservedW; auto.\n      { apply COMMON. }\n      done. }\n    apply FINALT. by split. }\n  assert (Local.is_terminal local) as LCTR by (constructor; auto).\n  assert (wf_thread_state thread state') as GPC'.\n  { eapply wf_thread_state_steps; eauto. }\n  assert (acts_set (ProgToExecution.G state') ⊆₁\n          acts_set (ProgToExecution.G state)) as PP.\n  { intros x HH. set (HH' := HH).\n    apply GPC'.(acts_rep) in HH'.\n    desc. rewrite REP in *. clear x REP.\n    assert (covered T (ThreadEvent thread index)) as CC.\n    { apply FINALT. split; auto.\n      apply TEH in HH. apply HH. }\n    apply PCOV in CC. by apply GPC.(acts_clos). }\n  assert ((istep thread nil)＊ state state') as KK.\n  { apply steps_same_E_empty_in; auto. }\n  assert ((lts_step thread ProgramEvent.silent)＊ state state') as HH.\n  { by hahn_rewrite <- istep_nil_eq_silent. }\n  assert (state'.(eindex) = state.(eindex)) as EII.\n  { eapply steps_same_eindex; eauto. }\n  rename STEPS into STEPSAA.\n  rename HH into STEPS.\n\n  assert (forall A (a b : A), Some a = Some b -> a = b) as XBB.\n  { ins. inv H. }\n  assert (forall A (a b : A) B (c : B), (a, c) = (b, c) -> a = b) as XBB1.\n  { ins. inv H. }\n\n  apply rtE in STEPS. destruct STEPS as [EQ|STEPS].\n  { red in EQ. desf. exists PC. splits; auto.\n    red. ins.\n    destruct (IdentMap.find thread (Configuration.threads PC)) eqn: HH.\n    2: { clear -LLH0 LLH HH.\n         unfold language in *.\n         desf. }\n    inv LLH.\n    unfold language in *; simpls.\n    rewrite HH in LLH0. inv LLH0.\n    assert (state' = st); subst.\n    { clear -LLH0 XBB XBB1. simpl in *.\n      apply XBB in LLH0.\n      apply XBB1 in LLH0. desf. }\n    splits; auto. red. simpls.\n      by apply TERMINAL. }\n  assert \n  (thread_is_terminal\n     (IdentMap.add thread (existT (@Language.state ProgramEvent.t) (thread_lts thread) state', local)\n                   (Configuration.threads PC)) thread) as TT.\n  { red. ins. rewrite IdentMap.gss in LLH0. inv LLH0.\n    assert (state' = st); subst.\n    { clear -LLH0 XBB XBB1. simpl in *.\n      apply XBB in LLH0.\n      apply XBB1 in LLH0. desf. }\n    splits; auto. red. simpls.\n      by apply TERMINAL. }\n\n  eexists. splits.\n  { apply r_step. eexists. exists thread.\n    apply ct_end in STEPS.\n    destruct STEPS as [state'' [STEPS STEP]].\n    eapply Configuration.step_normal.\n    { eauto. }\n    { eapply rtc_lang_tau_step_rtc_thread_tau_step.\n      unfold Language.Language.step. simpls.\n      apply clos_rt_rt1n. apply STEPS. }\n    { apply Thread.step_program.\n      constructor. simpls.\n      2: by apply Local.step_silent. \n      apply STEP. }\n    { done. }\n    red. ins. splits; eauto. }\n  2: { ins; clear - QQ.\n       apply NoDup_Permutation; eauto using NoDup_map_NoDupA, IdentMap.elements_3w.\n       ins; rewrite !in_map_iff; split; intros ([i v] & <- & IN); ins;\n         apply IdentMap.elements_complete in IN;\n       destruct (positive_eq_dec i thread); desf; rewrite ?IdentMap.gss, ?IdentMap.gso in *; ins; desf.\n         by eexists (_, _); split; ins; apply IdentMap.elements_correct, IdentMap.gss.\n         eby eexists (_, _); split; ins; apply IdentMap.elements_correct; rewrite IdentMap.gso.\n       all: eexists (_, _); split; ins; eauto using IdentMap.elements_correct.\n     }\n  2: done. \n  2: { ins. red. destruct (classic (thread' = thread)) as [|NEQ]; subst; ins.\n       rewrite IdentMap.gso in *; auto. }\n  cdes COMMON. simpls.\n  red. splits; red; splits; auto.\n  { ins. destruct (classic (thread = tid e)); subst.\n    2: by rewrite IdentMap.gso; auto.\n    rewrite IdentMap.gss. eauto. }\n  { ins. destruct (classic (thread' = thread)); subst.\n    { rewrite IdentMap.gss in *. inv TID.\n      eapply PROM_IN_MEM; eauto. }\n    rewrite IdentMap.gso in *; auto.\n    eapply PROM_IN_MEM; eauto. }\n  simpls.\n  destruct (classic (thread0 = thread)) as [|NEQ]; subst.\n  { rewrite IdentMap.gss. \n    eexists; eexists. splits.\n    1,4: done.\n    all: eauto.\n    { erewrite steps_preserve_instrs; eauto. }\n    { ins. left. rewrite PBOT. apply Memory.bot_get. }\n    red. splits.\n    { by rewrite EII. }\n    eexists. red. splits; eauto. apply rt_refl. }\n  apply IdentMap.Facts.in_find_iff in TP.\n  rewrite IdentMap.gso in *; auto.\n  destruct (IdentMap.find thread0 (Configuration.threads PC)) as [k|] eqn:AA; [|done].\n  assert (IdentMap.In thread0 (Configuration.threads PC)) as BB.\n  { apply IdentMap.Facts.in_find_iff. by rewrite AA. }\n  apply THREADS in BB.\n  destruct k.  destruct s.\n  cdes BB. eexists. eexists. splits; eauto.\n  { by rewrite <- AA. }\n  ins. destruct (classic (thread' = thread)) as [|NN].\n  { subst. rewrite IdentMap.gss in *. inv TID'.\n    right. rewrite PBOT. apply Memory.bot_get. }\n  rewrite IdentMap.gso in TID'; auto.\n  eapply PROM_DISJOINT0; eauto.\nQed. \n\nLemma sim_covered_exists_terminal T S PC f_to f_from\n      (FINALT : acts_set G ⊆₁ covered T)\n      (SIMREL : simrel G sc PC T S f_to f_from) :\n  exists PC',\n    ⟪ STEPS : conf_step＊ PC PC' ⟫ /\\\n    ⟪ SIMREL : simrel G sc PC' T S f_to f_from ⟫ /\\\n    ⟪ TERMINAL : Configuration.is_terminal PC' ⟫.\nProof using All.\n  assert\n    (exists l, \n         length (filterP (fun x => ~ thread_is_terminal (PC.(Configuration.threads)) x)\n                   (map fst (IdentMap.elements PC.(Configuration.threads))))\n         = l)\n     as [l LL] by eauto.\n  generalize dependent PC.\n  induction l using (well_founded_ind lt_wf); ins; desf.\n  destruct (classic (\n      forall x (ELEM: In x (IdentMap.elements PC.(Configuration.threads))), \n        Language.is_terminal (projT1 (fst (snd x))) (projT2 (fst (snd x))) /\\\n        Local.is_terminal (snd (snd x))\n    )) as [Y|Y].\n     eexists; splits; eauto using rt_refl.\n     by repeat red; ins; apply IdentMap.elements_correct, Y in FIND; ins. \n  apply not_all_ex_not in Y; destruct Y as ([i v] & Y).\n  apply imply_to_and in Y; destruct Y as (FIND & Y); ins.\n  assert (IN:=FIND); apply IdentMap.elements_complete in FIND.\n  forward eapply sim_thread_covered_exists_terminal with (thread := i) as X; desc; eauto.\n    by rewrite FINALT; unfolder; ins; desf.\n  eapply H in SIMREL0; ins; desc.\n    by eexists; splits; eauto; apply cr_rt; red; eauto.\n\n  \n  clear - STEP SAMENUM IN FIND Y TERMINAL PTERMINAL.\n  assert (L: forall l, length (filterP (fun x => ~ thread_is_terminal (Configuration.threads PC') x) l)\n          <= length (filterP (fun x => ~ thread_is_terminal (Configuration.threads PC) x) l)).\n    clear - PTERMINAL; induction l; ins; desf; ins; eauto; try omega.\n    exfalso; specialize (PTERMINAL a); tauto.\n  rewrite SAMENUM.\n  apply in_split_perm in IN; desc; rewrite IN in SAMENUM; ins; rewrite <- SAMENUM; ins. \n  desf; ins. \n  2: by destruct v as ((lang,st),lc); destruct Y; apply NNPP in n0; apply n0 in FIND; ins.\n  clear Y.\n  auto using le_lt_n_Sm, plus_le_compat.\nQed.\n\nLemma same_final_memory T S PC f_to f_from\n      (FINALT : acts_set G ⊆₁ covered T)\n      (SIMREL : simrel G sc PC T S f_to f_from) :\n  forall l,\n    final_memory_state (Configuration.memory PC) l = Some (final_memory l).\nProof using All.\n  assert (etc_coherent G sc (mkETC T S)) as ETCCOH by apply SIMREL.\n  assert (tc_coherent G sc T) as TCCOH by apply ETCCOH.\n  ins. unfold final_memory_state.\n  cdes SIMREL. cdes COMMON.\n  edestruct (Memory.max_ts_spec l) as [AA _].\n  { apply INHAB. }\n  red in AA. desc.\n  rewrite AA. simpls.\n  destruct msg as [val msg|].\n  2: { desc. eapply HMEM in AA. desc.\n       exfalso.\n       apply NOISS. eapply w_covered_issued; eauto.\n       split.\n       { by apply (reservedW WF ETCCOH). }\n         by apply FINALT. }\n  assert (val = final_memory l); [|by subst].\n  desc. red in MEM.\n  set (BB := AA).\n  apply MEM in BB.\n  destruct BB as [[BB YY]|].\n  { rewrite BB in *. specialize (INHAB l).\n    rewrite INHAB in AA. inv AA.\n    destruct (EFM l); desc; auto.\n    assert (is_init w) as II.\n    2: { unfold val in VAL.\n         destruct w; [|by desf].\n         rewrite WF.(wf_init_lab) in VAL.\n         inv VAL. }\n    assert (issued T w) as WISS.\n    { eapply w_covered_issued; eauto.\n      split; auto. }\n    assert (S w) as WS.\n    { by apply ETCCOH.(etc_I_in_S). }\n    destruct (classic (is_init w)) as [|NINIT]; auto.\n    exfalso.\n    destruct (THREAD w) as [langst TT]; auto.\n    assert (IdentMap.In (tid w) (Configuration.threads PC)) as NN.\n    { destruct (THREAD w); auto.\n      apply IdentMap.Facts.in_find_iff.\n        by rewrite H. }\n    apply THREADS in NN. cdes NN.\n    assert (SS := SIM_MEM).\n    edestruct SS as [rel_opt]; eauto.\n    simpls. desc.\n    destruct (classic (f_to w = Time.bot)) as [FEQ|FNEQ].\n    { rewrite FEQ in *. rewrite INMEM in INHAB.\n      inv INHAB. cdes FCOH.\n      apply TTOFROM in NINIT; auto. \n      rewrite FEQ in NINIT. rewrite H0 in NINIT.\n        by apply Time.lt_strorder in NINIT. }\n    apply Memory.max_ts_spec in INMEM.\n    destruct INMEM as [_ CC].\n    rewrite BB in CC. apply Time.le_lteq in CC.\n    destruct CC as [CC|]; [|by desf].\n      by apply time_lt_bot in CC. }\n  desc. edestruct (@EFM l); desc.\n  { by apply NO in LOC. }\n  destruct (classic (is_init w)) as [INIT|NINIT].\n  { assert (f_to w = Time.bot) as BB.\n    { apply FCOH. by split. }\n    destruct (classic (b = w)) as [|NEQ]; subst.\n    2: { edestruct WF.(wf_co_total) as [CO|CO]; eauto.\n         1,2: split; [split|]; auto.\n         { apply TCCOH in ISS. apply ISS. }\n         { by rewrite LOC. }\n         { exfalso. apply Execution_eco.no_co_to_init in CO; auto.\n           2: { apply imm_s_hb.coherence_sc_per_loc. apply IMMCON. }\n           apply seq_eqv_r in CO. desf. }\n         exfalso. apply LAST. eauto. }\n    rewrite BB in *. rewrite <- TO in *.\n    rewrite INHAB in AA. inv AA.\n    destruct w; simpls.\n    unfold val in VAL. rewrite WF.(wf_init_lab) in VAL.\n    inv VAL. }\n  assert (IdentMap.In (tid w) (Configuration.threads PC)) as NN.\n  { destruct (THREAD w); auto.\n    apply IdentMap.Facts.in_find_iff.\n      by rewrite H. }\n  apply THREADS in NN. cdes NN.\n  assert (SS := SIM_MEM).\n  assert (issued T w) as IIW.\n  { eapply w_covered_issued; eauto. split; auto. }\n  edestruct SS with (b:=w) as [rel_opt]; eauto.\n  simpls. desc. clear H1.\n  destruct (classic (b = w)) as [|NEQ]; subst.\n  { rewrite <- TO in *. rewrite INMEM in AA. inv AA. }\n  edestruct WF.(wf_co_total) as [CO|CO]; eauto.\n  1,2: split; [split|]; auto.\n  { apply TCCOH in ISS. apply ISS. }\n  { by rewrite LOC. }\n  2: { exfalso. apply LAST. eauto. }\n  assert (S b) as BS.\n  { by apply ETCCOH.(etc_I_in_S). }\n  assert (S w) as WS.\n  { by apply ETCCOH.(etc_I_in_S). }\n  eapply f_to_co_mon with (I:=S) in CO; eauto.\n  apply Memory.max_ts_spec in INMEM.\n  destruct INMEM as [_ CC].\n  rewrite <- TO in CC.\n  exfalso. eapply Time.lt_strorder.\n  eapply TimeFacts.lt_le_lt; eauto.\nQed.\n\nLemma sim_step PC T S T' S' f_to f_from\n      (STEP : ext_sim_trav_step G sc (mkETC T S) (mkETC T' S'))\n      (SIMREL : simrel G sc PC T S f_to f_from) :\n    exists PC' f_to' f_from',\n      ⟪ PSTEP : (conf_step)^? PC PC' ⟫ /\\\n      ⟪ SIMREL : simrel G sc PC' T' S' f_to' f_from' ⟫.\nProof using All.\n  destruct STEP as [thread STEP].\n  cdes SIMREL. cdes COMMON.\n  eapply plain_sim_step in STEP; eauto.\n  2: { split; eauto. apply THREADS.\n       assert (exists e, thread = tid e /\\ acts_set G e /\\ ~ is_init e) as [e].\n       { apply ext_sim_trav_step_to_step in STEP.\n         desc. exists e.\n         assert (acts_set G e) as EE.\n         { eapply ext_itrav_stepE; eauto. }\n         splits; auto.\n         eapply ext_itrav_step_ninit; eauto. }\n       cdes COMMON. subst.\n       destruct (THREAD e); auto.\n       apply IdentMap.Facts.in_find_iff.\n         by rewrite H. }\n  desf. exists PC'. exists f_to'. exists f_from'. splits.\n  2: { apply SIMREL0; eauto. }\n\n  apply rtE in PSTEP.\n  destruct PSTEP as [[HH]|PSTEP]; subst.\n  { by constructor. }\n  apply plain_step_ct_in_plain_step in PSTEP.\n  right.\n  red. exists MachineEvent.silent. exists thread.\n  destruct PSTEP. econstructor; eauto.\n  red; simpls. ins. right.\n  \n  edestruct cert_graph_init as [G' [sc'' [T'' [S'' HH]]]]; eauto.\n  desc.\n\n  set (PC := (Configuration.mk (IdentMap.add\n                                  tid (existT _ lang st3, lc3)\n                                  (Configuration.threads c1))\n                               sc1 mem1)).\n\n  edestruct (@cert_simulation G' sc'' tid PC T'' S'' f_to' f_from') as [T''' HH].\n  all: try by desf; eauto.\n  { unfold PC. eapply simrel_thread_bigger_sc_memory; eauto.\n    { rewrite IdentMap.gss; eauto. }\n    { eapply inhabited_le.\n      { apply CAP. }\n      apply SIMREL_THREAD. }\n    { eapply Memory.cap_closed; eauto. apply SIMREL_THREAD. }\n    { apply CAP. }\n      by apply Memory.max_full_timemap_closed. }\n  desc.\n\n  assert\n    (exists langst local,\n        ⟪ THREAD :\n            Basic.IdentMap.find tid PC'.(Configuration.threads) =\n            Some (langst, local)\n        ⟫ /\\\n        ⟪ EMPTY : Local.promises local = Memory.bot ⟫)\n    as HH.\n  { cdes SIMREL2. cdes LOCAL.\n    exists (existT _ (thread_lts tid) state). exists local.\n    splits; auto.\n    red in SIM_PROM. apply Memory.ext.\n    ins. rewrite Memory.bot_get.\n    destruct (Memory.get loc ts (Local.promises local)) eqn: HH; auto.\n    exfalso.\n    destruct p as [from msg]. destruct msg.\n    { eapply SIM_PROM in HH; eauto.\n      desc. apply NCOV. by apply FINALT. }\n    eapply SIM_RPROM in HH; eauto.\n    desc.\n    apply NOISS. eapply w_covered_issued.\n    { apply COMMON0. }\n    split.\n    { eapply reservedW; auto.\n      { apply COMMON0. }\n      done. }\n    apply FINALT. eapply etc_S_in_E.\n    { apply COMMON0. }\n    done. }\n\n  desc.\n  destruct langst as [lang' state'].\n  assert (lang' = lang); subst.\n  { symmetry.\n    eapply conf_steps_preserve_lang; eauto.\n    unfold PC.\n    simpls. rewrite IdentMap.gss. eauto. }\n  eapply conf_steps_to_thread_steps in PSTEP; eauto.\n  2: { unfold PC. simpls. rewrite IdentMap.gss. eauto. }\n  eexists. splits.\n  { apply PSTEP. }\n  simpls.\nQed.\n\nLemma sim_steps PC TS TS' f_to f_from\n      (TCSTEPS : (ext_sim_trav_step G sc)⁺ TS TS')\n      (SIMREL  : simrel G sc PC (etc_TC TS) (reserved TS) f_to f_from) :\n    exists PC' f_to' f_from',\n      ⟪ PSTEP : conf_step＊ PC PC' ⟫ /\\\n      ⟪ SIMREL : simrel G sc PC' (etc_TC TS') (reserved TS') f_to' f_from' ⟫.\nProof using All.\n  generalize dependent f_from.\n  generalize dependent f_to.\n  generalize dependent PC.\n  induction TCSTEPS.\n  { ins. desf.\n    destruct x as [T S].\n    destruct y as [T' S'].\n    eapply sim_step in H; eauto. desf.\n    do 3 eexists. splits; eauto. by eapply inclusion_r_rt; eauto. }\n  ins.\n  eapply IHTCSTEPS1 in SIMREL.\n  desc.\n  eapply IHTCSTEPS2 in SIMREL0.\n  desf. eexists. eexists. eexists. splits.\n  2: eauto.\n  eapply rt_trans; eauto. \nQed.\n\nLemma simulation :\n  exists T S PC f_to f_from,\n    ⟪ FINALT : G.(acts_set) ⊆₁ covered T ⟫ /\\\n    ⟪ PSTEP  : conf_step＊ (conf_init prog) PC ⟫ /\\\n    ⟪ SIMREL : simrel G sc PC T S f_to f_from ⟫.\nProof using All.\n  generalize (sim_traversal WF IMMCON); ins; desc.\n  destruct T as [T S].\n  exists T, S. apply rtE in H.\n  destruct H as [H|H].\n  { red in H. desf.\n    eexists. eexists. eexists.\n    splits; auto.\n    { apply rtE. left. red. eauto. }\n    unfold ext_init_trav in *. inv H.\n    apply simrel_init. }\n  eapply sim_steps in H.\n  2: by apply simrel_init.\n  desf.\n  eexists. eexists. eexists.\n  splits; eauto.\nQed.\n\nTheorem promise2imm : promise_allows prog final_memory.\nProof using All.\n  red.\n  destruct simulation as [T [PC H]]. desc.\n  edestruct sim_covered_exists_terminal as [PC']; eauto.\n  desc.\n  exists PC'. splits; eauto.\n  { eapply rt_trans; eauto. }\n  eapply same_final_memory; eauto. \nQed.\n\nEnd PromiseToIMM.\n", "meta": {"author": "weakmemory", "repo": "promising2ToImm", "sha": "8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c", "save_path": "github-repos/coq/weakmemory-promising2ToImm", "path": "github-repos/coq/weakmemory-promising2ToImm/promising2ToImm-8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c/src/compilation/PromiseToimm_s.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2123836911449199}}
{"text": "From iris.algebra Require Import\n  proofmode_classes.\n\nFrom caml5 Require Import\n  prelude.\nFrom caml5.algebra Require Export\n  base.\nFrom caml5.algebra Require Import\n  Z_max\n  lib.auth_option.\n\nImplicit Types n m p : Z.\n\nDefinition auth_Z_max :=\n  auth_option Z_max_R.\nDefinition auth_Z_max_R :=\n  auth_option_R Z_max_R.\nDefinition auth_Z_max_UR :=\n  auth_option_UR Z_max_R.\n\nDefinition auth_Z_max_auth dq n : auth_Z_max_UR :=\n  ●O{dq} Build_Z_max n ⋅ ◯O Build_Z_max n.\nDefinition auth_Z_max_frag n : auth_Z_max_UR :=\n  ◯O Build_Z_max n.\n\n#[global] Instance auth_Z_max_cmra_discrete :\n  CmraDiscrete auth_Z_max_R.\nProof.\n  apply _.\nQed.\n\n#[global] Instance auth_Z_max_auth_core_id n :\n  CoreId (auth_Z_max_auth DfracDiscarded n).\nProof.\n  apply _.\nQed.\n#[global] Instance auth_Z_max_frag_core_id n :\n  CoreId (auth_Z_max_frag n).\nProof.\n  apply _.\nQed.\n\nLemma auth_Z_max_auth_dfrac_op dq1 dq2 n :\n  auth_Z_max_auth (dq1 ⋅ dq2) n ≡ auth_Z_max_auth dq1 n ⋅ auth_Z_max_auth dq2 n.\nProof.\n  rewrite /auth_Z_max_auth auth_option_auth_dfrac_op.\n  rewrite (comm _ (●O{dq2} _)) -!assoc (assoc _ (◯O _)) -core_id_dup (comm _ (◯O _)) //.\nQed.\n#[global] Instance auth_Z_max_auth_dfrac_is_op dq dq1 dq2 n :\n  IsOp dq dq1 dq2 →\n  IsOp' (auth_Z_max_auth dq n) (auth_Z_max_auth dq1 n) (auth_Z_max_auth dq2 n).\nProof.\n  rewrite /IsOp' /IsOp => ->. rewrite auth_Z_max_auth_dfrac_op //.\nQed.\n\nLemma auth_Z_max_frag_op n1 n2 :\n  auth_Z_max_frag (n1 `max` n2) = auth_Z_max_frag n1 ⋅ auth_Z_max_frag n2.\nProof.\n  rewrite -auth_option_frag_op Z_max_op_eq //.\nQed.\n#[global] Instance auth_Z_max_frag_is_op n n1 n2 :\n  IsOp (Build_Z_max n) (Build_Z_max n1) (Build_Z_max n2) →\n  IsOp' (auth_Z_max_frag n) (auth_Z_max_frag n1) (auth_Z_max_frag n2).\nProof.\n  rewrite /IsOp' /IsOp /auth_Z_max_frag => -> //.\nQed.\n\nLemma auth_Z_max_auth_frag_op dq n :\n  auth_Z_max_auth dq n ≡ auth_Z_max_auth dq n ⋅ auth_Z_max_frag n.\nProof.\n  rewrite -!assoc -auth_option_frag_op -core_id_dup //.\nQed.\n\nLemma auth_Z_max_frag_op_le n n' :\n  (n' ≤ n)%Z →\n  auth_Z_max_frag n = auth_Z_max_frag n' ⋅ auth_Z_max_frag n.\nProof.\n  intros. rewrite -auth_Z_max_frag_op Z.max_r //.\nQed.\n\nLemma auth_Z_max_auth_dfrac_valid dq n :\n  ✓ auth_Z_max_auth dq n ↔\n  ✓ dq.\nProof.\n  rewrite auth_option_both_dfrac_valid_discrete /=. naive_solver.\nQed.\nLemma auth_Z_max_auth_valid n :\n  ✓ auth_Z_max_auth (DfracOwn 1) n.\nProof.\n  rewrite auth_Z_max_auth_dfrac_valid //.\nQed.\n\nLemma auth_Z_max_auth_dfrac_op_valid dq1 n1 dq2 n2 :\n  ✓ (auth_Z_max_auth dq1 n1 ⋅ auth_Z_max_auth dq2 n2) ↔\n  ✓ (dq1 ⋅ dq2) ∧ n1 = n2.\nProof.\n  rewrite /auth_Z_max_auth (comm _ (●O{dq2} _)) -!assoc (assoc _ (◯O _)).\n  rewrite -auth_option_frag_op (comm _ (◯O _)) assoc. split.\n  - move => /cmra_valid_op_l /auth_option_auth_dfrac_op_valid. naive_solver.\n  - intros [? ->]. rewrite -core_id_dup -auth_option_auth_dfrac_op.\n    apply auth_option_both_dfrac_valid_discrete. naive_solver.\nQed.\nLemma auth_Z_max_auth_op_valid n1 n2 :\n  ✓ (auth_Z_max_auth (DfracOwn 1) n1 ⋅ auth_Z_max_auth (DfracOwn 1) n2) ↔\n  False.\nProof.\n  rewrite auth_Z_max_auth_dfrac_op_valid. naive_solver.\nQed.\n\nLemma auth_Z_max_both_dfrac_valid dq n m :\n  ✓ (auth_Z_max_auth dq n ⋅ auth_Z_max_frag m) ↔\n  ✓ dq ∧ (m ≤ n)%Z.\nProof.\n  rewrite -assoc -auth_option_frag_op auth_option_both_dfrac_valid_discrete.\n  rewrite Z_max_included Z_max_op_eq /=. naive_solver lia.\nQed.\nLemma auth_Z_max_both_valid n m :\n  ✓ (auth_Z_max_auth (DfracOwn 1) n ⋅ auth_Z_max_frag m) ↔\n  (m ≤ n)%Z.\nProof.\n  rewrite auth_Z_max_both_dfrac_valid dfrac_valid_own. naive_solver.\nQed.\n\nLemma auth_Z_max_frag_mono n1 n2 :\n  (n1 ≤ n2)%Z →\n  auth_Z_max_frag n1 ≼ auth_Z_max_frag n2.\nProof.\n  intros. apply auth_option_frag_mono, Z_max_included. done.\nQed.\n\nLemma auth_Z_max_included dq n :\n  auth_Z_max_frag n ≼ auth_Z_max_auth dq n.\nProof.\n  apply cmra_included_r.\nQed.\n\nLemma auth_Z_max_auth_persist dq n :\n  auth_Z_max_auth dq n ~~> auth_Z_max_auth DfracDiscarded n.\nProof.\n  eapply cmra_update_op_proper; last done.\n  eapply auth_option_auth_persist.\nQed.\nLemma auth_Z_max_auth_update {n} n' :\n  (n ≤ n')%Z →\n  auth_Z_max_auth (DfracOwn 1) n ~~> auth_Z_max_auth (DfracOwn 1) n'.\nProof.\n  intros. apply auth_option_both_update, Z_max_local_update. done.\nQed.\n\n#[global] Opaque auth_Z_max_auth.\n#[global] Opaque auth_Z_max_frag.\n", "meta": {"author": "clef-men", "repo": "caml5", "sha": "0de06d5792138eb17877ed1536a0401b7a322ee2", "save_path": "github-repos/coq/clef-men-caml5", "path": "github-repos/coq/clef-men-caml5/caml5-0de06d5792138eb17877ed1536a0401b7a322ee2/theories/algebra/lib/auth_Z_max.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.36296919173767833, "lm_q1q2_score": 0.2123736982779093}}
{"text": "Require Import Rupicola.Lib.Api.\nRequire Import Ensembles.\n\nModule ND.\n  Definition M A := A -> Prop.\n\n  Ltac s :=\n    apply Extensionality_Ensembles; unfold Same_set, Included, In;\n    firstorder congruence.\n\n  Global Program Instance MonadM : Monad M :=\n    {| mret {A} (a: A) := fun a' => a' = a;\n       mbind {A B} (ma: M A) (k: A -> M B) :=\n         fun b => exists a, ma a /\\ k a b |}.\n  Obligation 1. Proof. s. Qed.\n  Obligation 2. Proof. s. Qed.\n  Obligation 3. Proof. s. Qed.\n\n  Definition pick {A} (P: A -> Prop) : M A := P.\nEnd ND.\n\nImport ND.\n\nNotation \"'let/+' x 'as' nm := val 'in' body\" :=\n  (mbindn [nm] val (fun x => body))\n    (at level 200, x name, body at level 200,\n     format \"'[hv' 'let/+'  x  'as'  nm  :=  val  'in' '//' body ']'\").\n\nNotation \"'let/+' x := val 'in' body\" :=\n  (mbindn [IdentParsing.TC.ident_to_string x] val (fun x => body))\n    (at level 200, x name, body at level 200,\n     only parsing).\n\nNotation \"%{ x | P }\" :=\n  (pick (fun x => P))\n    (at level 0, x pattern at level 99).\n\nNotation \"%{ x : A | P }\" :=\n  (pick (A := A) (fun x => P))\n    (at level 0, x pattern at level 99).\n\nDefinition ndbind {A} (c: M A) (pred: A -> Prop) :=\n  exists a, c a /\\ pred a.\n\nNotation ndspec := ndbind.\n\nLemma ndbind_bindn {A B} pred vars (c: M A) a (k : A -> M B):\n  c a ->\n  ndbind (k a) pred ->\n  ndbind (mbindn vars c k) pred.\nProof. unfold ndspec, mbindn, mbind. simpl. firstorder idtac. Qed.\n\nSection with_parameters.\n  Context {width: Z} {BW: Bitwidth width} {word: word.word width} {mem: map.map word Byte.byte}.\n  Context {locals: map.map String.string word}.\n  Context {env: map.map String.string (list String.string * list String.string * Syntax.cmd)}.\n  Context {ext_spec: bedrock2.Semantics.ExtSpec}.\n  Context {word_ok : word.ok word} {mem_ok : map.ok mem}.\n  Context {locals_ok : map.ok locals}.\n  Context {env_ok : map.ok env}.\n  Context {ext_spec_ok : Semantics.ext_spec.ok ext_spec}.\n\n  Definition ndspec_k {A} (pred: A -> predicate) (c: M A) : predicate :=\n    fun tr mem locals => ndspec c (fun a => pred a tr mem locals).\n\n  Lemma WeakestPrecondition_ndspec_k_bindn {A B} funcs prog t m l post\n        vars (c: M A) a (k: A -> M B) :\n    c a ->\n    WeakestPrecondition.program funcs prog t m l (ndspec_k post (k a)) ->\n    WeakestPrecondition.program funcs prog t m l (ndspec_k post (mbindn vars c k)).\n  Proof.\n    unfold ndspec_k; intros.\n    eapply WeakestPrecondition_weaken; [ | eauto].\n    eauto using ndbind_bindn.\n  Qed.\n\n  Lemma compile_setup_ndspec_k : forall {tr mem locals functions},\n    forall {A} {pred: A -> _ -> predicate}\n      {spec: M A} {cmd}\n      retvars,\n\n      (let pred a := wp_bind_retvars retvars (pred a) in\n       <{ Trace := tr;\n          Memory := mem;\n          Locals := locals;\n          Functions := functions }>\n       cmd\n       <{ ndspec_k pred spec }>) ->\n      <{ Trace := tr;\n         Memory := mem;\n         Locals := locals;\n         Functions := functions }>\n      cmd\n      <{ (fun spec =>\n            wp_bind_retvars\n              retvars\n              (fun rets tr' mem' locals' =>\n                 ndspec spec (fun a => pred a rets tr' mem' locals')))\n           spec }>.\n  Proof.\n    intros; unfold ndbind, wp_bind_retvars in *.\n    use_hyp_with_matching_cmd; cbv beta in *.\n    clear - H0; firstorder.\n  Qed.\nEnd with_parameters.\n\n#[export] Hint Resolve compile_setup_ndspec_k : compiler_setup_post.\n#[export] Hint Unfold ndspec_k ndspec ndbind: compiler_cleanup_post.\n#[export] Hint Extern 1 (mret _ _) => reflexivity : compiler_side_conditions.\n", "meta": {"author": "mit-plv", "repo": "rupicola", "sha": "3f59b3d2404ce425ddf4fd55ad2314996a573dc3", "save_path": "github-repos/coq/mit-plv-rupicola", "path": "github-repos/coq/mit-plv-rupicola/rupicola-3f59b3d2404ce425ddf4fd55ad2314996a573dc3/src/Rupicola/Examples/Nondeterminism/NonDeterminism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.3208213138121609, "lm_q1q2_score": 0.2123589709517575}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*              Layers of VM: UCtxtIntro                               *)\n(*                                                                     *)\n(*          Provide the abstraction of user contex                     *)\n(*                                                                     *)\n(*          Haozhong Zhang <haozhong.zhang@yale.edu>                   *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file defines the abstract data and the primitives for the UCtxtIntro layer,\nwhich will introduce the primtives of thread*)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import LoadStoreSem2.\nRequire Import XOmega.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealSMSPool.\nRequire Import CalRealProcModule.\n\nRequire Import INVLemmaMemory.\nRequire Import INVLemmaThread.\nRequire Import INVLemmaProc.\n\nRequire Import AbstractDataType.\nRequire Export PIPC.\nRequire Export PUCtxtIntroDef.\n\n(** * Abstract Data and Primitives at this layer*)\nSection WITHMEM.\n\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n\n  (** **Definition of the raw data at MPTBit layer*)\n  (*Record RData :=\n    mkRData {\n        HP: flatmem; (**r we model the memory from 1G to 3G as heap*)\n        ti: trapinfo; (**r abstract of CR2, stores the address where page fault happens*)\n        pe: bool; (**r abstract of CR0, indicates whether the paging is enabled or not*)\n        ikern: bool; (**r pure logic flag, shows whether it's in kernel mode or not*)\n        ihost: bool; (**r logic flag, shows whether it's in the host mode or not*)         \n        AT: ATable; (**r allocation table*)\n        nps: Z; (**r number of the pages*)\n\n        PT: Z; (**r the current page table index*)\n        ptpool: PTPool; (**r page table pool*)\n        ipt: bool; (**r pure logic flag, shows whether it's using the kernel's page table*)\n        pb : PTBitMap; (**r [page table bit map], indicating which page table has been used*)\n\n        kctxt: KContextPool; (**r kernel context pool*)\n        abtcb: AbTCBPool; (**r thread control blocks pool*)\n        abq: AbQueuePool; (**r thread queue pool*)\n        cid: Z; (**r current thread id*) \n\n        chpool : ChanPool; (**r the channel pool for IPC*)\n        uctxt : UContextPool (**r user context pool*)\n      }.*)\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  (** * Proofs that the primitives satisfies the invariants at this layer *)\n  Section INV.\n    \n    Global Instance uctx_set_inv: PreservesInvariants uctx_set_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n      eapply uctxt_inject_neutral_gss; eauto.\n      eapply uctxt_inject_neutral0_gss; eauto.\n      eapply uctxt_inject_neutral0_Vint.\n    Qed.\n\n    Global Instance uctx_set_eip_inv: UCTXSetEIPInvariants uctx_set_eip_spec.\n    Proof.\n      constructor; intros. \n      - (* low level inv *)\n        inv H1. functional inversion H; inv H.\n        constructor; trivial.\n        eapply uctxt_inject_neutral_gss; eauto.\n        eapply uctxt_inject_neutral0_gss; eauto.\n        eapply uctxt_inject_neutral0_Vptr_flat; eauto.\n      - (* high level inv *)\n        inv H0. functional inversion H; inv H.\n        constructor; trivial.\n      - (* kernel mode *)\n        functional inversion H; inv H.\n        constructor; trivial.\n    Qed.\n\n    Global Instance save_uctx_inv: SaveUCtxInvariants save_uctx_spec.\n    Proof.\n      constructor; intros. \n      - (* low level inv *)\n        inv H0. functional inversion H; inv H.\n        constructor; trivial.\n        eapply uctxt_inject_neutral_gss; eauto.\n        repeat eapply uctxt_inject_neutral0_gss; \n          try eapply uctxt_inject_neutral0_Vint.\n        apply uctxt_inject_neutral0_init; eauto.\n      - (* high level inv *)\n        inv H0. functional inversion H; inv H.\n        constructor; trivial.\n      - (* kernel mode *)\n        functional inversion H; inv H.\n        constructor; trivial.\n    Qed.\n\n    Global Instance restore_uctx_inv: RestoreUCtxInvariants restore_uctx_spec.\n    Proof.\n      constructor; intros. \n      - (* low level inv *)\n        inv H0. functional inversion H; inv H.\n        constructor; trivial.\n      - (* high level inv *)\n        inv H0. functional inversion H; inv H.\n        subst. constructor; auto; simpl in *; intros; try congruence.\n    Qed.\n    \n  End INV.\n\n  (** * Layer Definition *)\n  Definition puctxtintro_fresh_c : compatlayer (cdata RData) :=\n    uctx_get ↦ gensem uctx_get_spec\n             ⊕ uctx_set ↦ gensem uctx_set_spec\n             ⊕ uctx_set_eip ↦ uctx_set_eip_compatsem uctx_set_eip_spec\n             ⊕ save_uctx ↦ save_uctx_compatsem save_uctx_spec.\n\n  Definition puctxtintro_fresh_asm : compatlayer (cdata RData) :=\n    restore_uctx ↦ primcall_restoreuctx_compatsem restore_uctx_spec cid\n                 ⊕ elf_load ↦ elf_load_compatsem.\n\n  Definition puctxtintro_passthrough : compatlayer (cdata RData) :=\n    fload ↦ gensem fload_spec\n          ⊕ fstore ↦ gensem fstore_spec\n          ⊕ vmxinfo_get ↦ gensem vmxinfo_get_spec\n          ⊕ device_output ↦ gensem device_output_spec\n          ⊕ pfree ↦ gensem pfree_spec\n          ⊕ set_pt ↦ gensem setPT_spec\n          ⊕ pt_read ↦ gensem ptRead_spec\n          ⊕ pt_resv ↦ gensem ptResv_spec\n          ⊕ shared_mem_status ↦ gensem shared_mem_status_spec\n          ⊕ offer_shared_mem ↦ gensem offer_shared_mem_spec\n\n          ⊕ get_curid ↦ gensem get_curid_spec\n          ⊕ thread_spawn ↦ dnew_compatsem thread_spawn_spec\n          ⊕ thread_wakeup ↦ gensem thread_wakeup_spec\n          (*⊕ is_chan_ready ↦ gensem is_chan_ready_spec\n          ⊕ sendto_chan ↦ gensem sendto_chan_spec\n          ⊕ receive_chan ↦ gensem receive_chan_spec*)\n          ⊕ syncreceive_chan ↦ gensem syncreceive_chan_spec\n          ⊕ syncsendto_chan_pre ↦ gensem syncsendto_chan_pre_spec\n          ⊕ syncsendto_chan_post ↦ gensem syncsendto_chan_post_spec\n\n          ⊕ proc_init ↦ gensem proc_init_spec\n\n          ⊕ pt_in ↦ primcall_general_compatsem' ptin_spec (prim_ident:= pt_in)\n          ⊕ pt_out ↦ primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)\n          ⊕ container_get_nchildren ↦ gensem container_get_nchildren_spec\n          ⊕ container_get_quota ↦ gensem container_get_quota_spec\n          ⊕ container_get_usage ↦ gensem container_get_usage_spec\n          ⊕ container_can_consume ↦ gensem container_can_consume_spec\n          ⊕ container_alloc ↦ gensem alloc_spec\n          ⊕ trap_in ↦ primcall_general_compatsem trapin_spec\n          ⊕ host_in ↦ primcall_general_compatsem hostin_spec\n          ⊕ host_out ↦ primcall_general_compatsem hostout_spec\n          ⊕ trap_get ↦ primcall_trap_info_get_compatsem trap_info_get_spec\n          ⊕ trap_set ↦ primcall_trap_info_ret_compatsem trap_info_ret_spec\n\n          ⊕ thread_yield ↦ primcall_thread_schedule_compatsem thread_yield_spec (prim_ident:= thread_yield)\n          ⊕ thread_sleep ↦ primcall_thread_transfer_compatsem thread_sleep_spec\n\n          ⊕ accessors ↦ {| exec_load := (@exec_loadex _ _ Hmwd); \n                           exec_store := (@exec_storeex _ _ Hmwd) |}.\n\n  Definition puctxtintro : compatlayer (cdata RData) :=\n    (puctxtintro_fresh_c ⊕ puctxtintro_fresh_asm) ⊕ puctxtintro_passthrough.\n\n(*Definition puctxtintro_impl : compatlayer (cdata RData) :=\n    thread_spawn ↦ dnew_compatsem (dnew := thread_spawn_spec)\n      ⊕ uctx_set ↦ gensem uctx_set_spec\n      ⊕ uctx_set_eip ↦ uctx_set_eip_compatsem\n      ⊕ elf_load ↦ elf_load_compatsem.\n  Definition puctxtintro_rest : compatlayer (cdata RData) :=\n    uctx_get ↦ gensem uctx_get_spec\n      ⊕ save_uctx ↦ save_uctx_compatsem\n      ⊕ restore_uctx ↦ primcall_restoreuctx_compatsem\n      ⊕ palloc ↦ gensem palloc_spec\n      ⊕ pfree ↦ gensem pfree_spec\n      ⊕ set_pt ↦ gensem setPT_spec\n      ⊕ pt_read ↦ gensem ptRead_spec\n      ⊕ pt_resv ↦ gensem ptResv_spec\n      ⊕ pt_in ↦ primcall_general_compatsem' (prim_generic:= ptin_spec) (prim_ident:= pt_in)\n      ⊕ pt_out ↦ primcall_general_compatsem' (prim_generic:= ptout_spec) (prim_ident:= pt_out)\n      ⊕ trap_in ↦ primcall_general_compatsem (prim_generic:= trapin_spec)\n      ⊕ host_in ↦ primcall_general_compatsem (prim_generic:= hostin_spec)\n      ⊕ host_out ↦ primcall_general_compatsem (prim_generic:= hostout_spec)\n      ⊕ trap_get ↦ primcall_trap_info_get_compatsem (trap_info_get:= trap_info_get_spec)\n      ⊕ trap_set ↦ primcall_trap_info_ret_compatsem (trap_info_ret:= trap_info_ret_spec)\n      ⊕ get_curid ↦ gensem get_curid_spec\n      ⊕ thread_kill ↦ gensem thread_kill_spec\n      ⊕ thread_wakeup ↦ gensem thread_wakeup_spec\n      ⊕ thread_yield ↦ primcall_thread_schedule_compatsem (thread_schedule:= thread_yield_spec) (prim_ident:= thread_yield)\n      ⊕ thread_sleep ↦ primcall_thread_transfer_compatsem (thread_transfer:= thread_sleep_spec)\n      ⊕ is_chan_ready ↦ gensem is_chan_ready_spec\n      ⊕ sendto_chan ↦ gensem sendto_chan_spec\n      ⊕ receive_chan ↦ gensem receive_chan_spec\n      ⊕ proc_init ↦ gensem proc_init_spec\n      ⊕ accessors ↦ {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.\n\n  Lemma puctxtintro_impl_eq : puctxtintro ≡ puctxtintro_impl ⊕ puctxtintro_rest.\n  Proof. reflexivity. Qed.\n\n  Definition semantics := LAsm.Lsemantics puctxtintro.*)\n\nEnd WITHMEM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/proc/PUCtxtIntro.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.21234005385291405}}
{"text": "(*\n * Copyright (c) 2017-present,\n * Programming Research Laboratory (ROPAS), Seoul National University, Korea\n * This software is distributed under the term of the BSD-3 clause license.\n *)\n(** * Abstract domain (context-sen) *)\n\nSet Implicit Arguments.\n\nRequire Import UserProofType.\nRequire DomCon.\nRequire Import SemCommon.\n\nModule Make (Import PInput : PINPUT).\n\nLocal Open Scope type.\n\nDefinition index_t : Type := InterNode.t * mem_pos * list InterNode.t.\n\nDefinition state_t : Type := index_t -> Mem.t.\n\nDefinition node_of_index (idx : index_t) : InterNode.t := fst (fst idx).\n\nDefinition pos_of_index (idx : index_t) : mem_pos := snd (fst idx).\n\nDefinition call_nodes_of_index (idx : index_t) : list InterNode.t := snd idx.\n\nSection Wf.\n\nVariable pgm : InterCfg.t.\n\nDefinition wf_call (calln : InterNode.t) : Prop :=\n  exists retn, Some retn = InterCfg.returnof pgm calln.\n\nDefinition wf_calls (calls : list InterNode.t) : Prop :=\n  List.Forall wf_call calls.\n\nDefinition wf_index (idx : index_t) : Prop :=\n  wf_calls (call_nodes_of_index idx).\n\nDefinition wf_state (s : state_t) : Prop :=\n  forall idx (Hidx : not (wf_index idx)), Mem.eq (s idx) Mem.bot.\n\nEnd Wf.\n\nLocal Close Scope type.\n\nEnd Make.\n", "meta": {"author": "ropas", "repo": "zooberry", "sha": "17b1cb1a44c2a796d6b7d85c2026b142685d291b", "save_path": "github-repos/coq/ropas-zooberry", "path": "github-repos/coq/ropas-zooberry/zooberry-17b1cb1a44c2a796d6b7d85c2026b142685d291b/spec/Proof/DomSen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21231062866679962}}
{"text": "Require Coq.Structures.Equalities.\nRequire Coq.FSets.FSetAVL.\nRequire Coq.FSets.FSetWeakList.\nRequire Coq.FSets.FMapFacts.\n\nRequire Genevan.ProtoIdentifier.\nRequire Genevan.ProtoName.\nRequire Genevan.ProtoPeer.Peer.\nRequire Genevan.ProtoPeer.Collection.\n\nRecord t := {\n  supports : ProtoIdentifier.t\n}.\n\nModule ClientHandlerPeer : Peer.T with Definition t := t.\n  Definition t        := t.\n  Definition eq       := @Logic.eq t.\n  Definition eq_refl  := @Logic.eq_refl t.\n  Definition eq_sym   := @Logic.eq_sym t.\n  Definition eq_trans := @Logic.eq_trans t.\n\n  #[local]\n  Instance eq_equiv : RelationClasses.Equivalence eq := { }.\n\n  Theorem eq_dec : forall x y : t, {eq x y} + {~ eq x y}.\n  Proof.\n    intros x y.\n    destruct x as [xi].\n    destruct y as [yi].\n    destruct (ProtoIdentifier.Dec.eq_dec xi yi) as [HL|HR]. {\n      left; rewrite HL; reflexivity.\n    } {\n      right.\n      intro H_contra.\n      assert (xi = yi) by congruence.\n      contradiction.\n    }\n  Qed.\n\n  Definition supports (c : t) : ProtoIdentifier.t := supports c.\nEnd ClientHandlerPeer.\n\nModule Sets : FSetInterface.WS \n  with Definition E.t  := t\n  with Definition E.eq := ClientHandlerPeer.eq\n:= FSetWeakList.Make ClientHandlerPeer.\n\nModule ClientHandlerCollection :=\n  ProtoPeer.Collection.Make ClientHandlerPeer Sets.\n", "meta": {"author": "io7m", "repo": "genevan", "sha": "3a4baf90ecbc72b86f435352623a18ea3755a7cf", "save_path": "github-repos/coq/io7m-genevan", "path": "github-repos/coq/io7m-genevan/genevan-3a4baf90ecbc72b86f435352623a18ea3755a7cf/com.io7m.genevan.core/src/main/coq/Genevan/ProtoClientHandler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21231062866679962}}
{"text": "From iris.proofmode Require Import coq_tactics reduction.\nFrom iris.proofmode Require Export tactics.\nFrom iris.program_logic Require Import atomic.\nFrom iris.heap_lang Require Export tactics derived_laws.\nFrom iris.heap_lang Require Import notation.\nFrom iris Require Import options.\nImport uPred.\n\nLemma tac_wp_expr_eval `{!heapG Σ} Δ s E Φ e e' :\n  (∀ (e'':=e'), e = e'') →\n  envs_entails Δ (WP e' @ s; E {{ Φ }}) → envs_entails Δ (WP e @ s; E {{ Φ }}).\nProof. by intros ->. Qed.\nLemma tac_twp_expr_eval `{!heapG Σ} Δ s E Φ e e' :\n  (∀ (e'':=e'), e = e'') →\n  envs_entails Δ (WP e' @ s; E [{ Φ }]) → envs_entails Δ (WP e @ s; E [{ Φ }]).\nProof. by intros ->. Qed.\n\nTactic Notation \"wp_expr_eval\" tactic3(t) :=\n  iStartProof;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    eapply tac_wp_expr_eval;\n      [let x := fresh in intros x; t; unfold x; reflexivity|]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    eapply tac_twp_expr_eval;\n      [let x := fresh in intros x; t; unfold x; reflexivity|]\n  | _ => fail \"wp_expr_eval: not a 'wp'\"\n  end.\n\nLemma tac_wp_pure `{!heapG Σ} Δ Δ' s E K e1 e2 φ n Φ :\n  PureExec φ n e1 e2 →\n  φ →\n  MaybeIntoLaterNEnvs n Δ Δ' →\n  envs_entails Δ' (WP (fill K e2) @ s; E {{ Φ }}) →\n  envs_entails Δ (WP (fill K e1) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ??? HΔ'. rewrite into_laterN_env_sound /=.\n  rewrite HΔ' -lifting.wp_pure_step_later //.\nQed.\nLemma tac_twp_pure `{!heapG Σ} Δ s E K e1 e2 φ n Φ :\n  PureExec φ n e1 e2 →\n  φ →\n  envs_entails Δ (WP (fill K e2) @ s; E [{ Φ }]) →\n  envs_entails Δ (WP (fill K e1) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=> ?? ->. rewrite -total_lifting.twp_pure_step //.\nQed.\n\nLemma tac_wp_value `{!heapG Σ} Δ s E Φ v :\n  envs_entails Δ (Φ v) → envs_entails Δ (WP (Val v) @ s; E {{ Φ }}).\nProof. rewrite envs_entails_eq=> ->. by apply wp_value. Qed.\nLemma tac_twp_value `{!heapG Σ} Δ s E Φ v :\n  envs_entails Δ (Φ v) → envs_entails Δ (WP (Val v) @ s; E [{ Φ }]).\nProof. rewrite envs_entails_eq=> ->. by apply twp_value. Qed.\n\nLtac wp_expr_simpl := wp_expr_eval simpl.\n\nLtac wp_value_head :=\n  first [eapply tac_wp_value || eapply tac_twp_value].\n\nLtac wp_finish :=\n  wp_expr_simpl;      (* simplify occurences of subst/fill *)\n  try wp_value_head;  (* in case we have reached a value, get rid of the WP *)\n  pm_prettify.        (* prettify ▷s caused by [MaybeIntoLaterNEnvs] and\n                         λs caused by wp_value *)\n\nLtac solve_vals_compare_safe :=\n  (* The first branch is for when we have [vals_compare_safe] in the context.\n     The other two branches are for when either one of the branches reduces to\n     [True] or we have it in the context. *)\n  fast_done || (left; fast_done) || (right; fast_done).\n\n(** The argument [efoc] can be used to specify the construct that should be\nreduced. For example, you can write [wp_pure (EIf _ _ _)], which will search\nfor an [EIf _ _ _] in the expression, and reduce it.\n\nThe use of [open_constr] in this tactic is essential. It will convert all holes\n(i.e. [_]s) into evars, that later get unified when an occurences is found\n(see [unify e' efoc] in the code below). *)\nTactic Notation \"wp_pure\" open_constr(efoc) :=\n  iStartProof;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    let e := eval simpl in e in\n    reshape_expr e ltac:(fun K e' =>\n      unify e' efoc;\n      eapply (tac_wp_pure _ _ _ _ K e');\n      [iSolveTC                       (* PureExec *)\n      |try solve_vals_compare_safe    (* The pure condition for PureExec -- handles trivial goals, including [vals_compare_safe] *)\n      |iSolveTC                       (* IntoLaters *)\n      |wp_finish                      (* new goal *)\n      ])\n    || fail \"wp_pure: cannot find\" efoc \"in\" e \"or\" efoc \"is not a redex\"\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    let e := eval simpl in e in\n    reshape_expr e ltac:(fun K e' =>\n      unify e' efoc;\n      eapply (tac_twp_pure _ _ _ K e');\n      [iSolveTC                       (* PureExec *)\n      |try solve_vals_compare_safe    (* The pure condition for PureExec *)\n      |wp_finish                      (* new goal *)\n      ])\n    || fail \"wp_pure: cannot find\" efoc \"in\" e \"or\" efoc \"is not a redex\"\n  | _ => fail \"wp_pure: not a 'wp'\"\n  end.\n\n(* TODO: do this in one go, without [repeat]. *)\nLtac wp_pures :=\n  iStartProof;\n  repeat (wp_pure _; []). (* The `;[]` makes sure that no side-condition\n                             magically spawns. *)\n\n(** Unlike [wp_pures], the tactics [wp_rec] and [wp_lam] should also reduce\nlambdas/recs that are hidden behind a definition, i.e. they should use\n[AsRecV_recv] as a proper instance instead of a [Hint Extern].\n\nWe achieve this by putting [AsRecV_recv] in the current environment so that it\ncan be used as an instance by the typeclass resolution system. We then perform\nthe reduction, and finally we clear this new hypothesis. *)\nTactic Notation \"wp_rec\" :=\n  let H := fresh in\n  assert (H := AsRecV_recv);\n  wp_pure (App _ _);\n  clear H.\n\nTactic Notation \"wp_if\" := wp_pure (If _ _ _).\nTactic Notation \"wp_if_true\" := wp_pure (If (LitV (LitBool true)) _ _).\nTactic Notation \"wp_if_false\" := wp_pure (If (LitV (LitBool false)) _ _).\nTactic Notation \"wp_unop\" := wp_pure (UnOp _ _).\nTactic Notation \"wp_binop\" := wp_pure (BinOp _ _ _).\nTactic Notation \"wp_op\" := wp_unop || wp_binop.\nTactic Notation \"wp_lam\" := wp_rec.\nTactic Notation \"wp_let\" := wp_pure (Rec BAnon (BNamed _) _); wp_lam.\nTactic Notation \"wp_seq\" := wp_pure (Rec BAnon BAnon _); wp_lam.\nTactic Notation \"wp_proj\" := wp_pure (Fst _) || wp_pure (Snd _).\nTactic Notation \"wp_case\" := wp_pure (Case _ _ _).\nTactic Notation \"wp_match\" := wp_case; wp_pure (Rec _ _ _); wp_lam.\nTactic Notation \"wp_inj\" := wp_pure (InjL _) || wp_pure (InjR _).\nTactic Notation \"wp_pair\" := wp_pure (Pair _ _).\nTactic Notation \"wp_closure\" := wp_pure (Rec _ _ _).\n\nLemma tac_wp_bind `{!heapG Σ} K Δ s E Φ e f :\n  f = (λ e, fill K e) → (* as an eta expanded hypothesis so that we can `simpl` it *)\n  envs_entails Δ (WP e @ s; E {{ v, WP f (Val v) @ s; E {{ Φ }} }})%I →\n  envs_entails Δ (WP fill K e @ s; E {{ Φ }}).\nProof. rewrite envs_entails_eq=> -> ->. by apply: wp_bind. Qed.\nLemma tac_twp_bind `{!heapG Σ} K Δ s E Φ e f :\n  f = (λ e, fill K e) → (* as an eta expanded hypothesis so that we can `simpl` it *)\n  envs_entails Δ (WP e @ s; E [{ v, WP f (Val v) @ s; E [{ Φ }] }])%I →\n  envs_entails Δ (WP fill K e @ s; E [{ Φ }]).\nProof. rewrite envs_entails_eq=> -> ->. by apply: twp_bind. Qed.\n\nLtac wp_bind_core K :=\n  lazymatch eval hnf in K with\n  | [] => idtac\n  | _ => eapply (tac_wp_bind K); [simpl; reflexivity|reduction.pm_prettify]\n  end.\nLtac twp_bind_core K :=\n  lazymatch eval hnf in K with\n  | [] => idtac\n  | _ => eapply (tac_twp_bind K); [simpl; reflexivity|reduction.pm_prettify]\n  end.\n\nTactic Notation \"wp_bind\" open_constr(efoc) :=\n  iStartProof;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' => unify e' efoc; wp_bind_core K)\n    || fail \"wp_bind: cannot find\" efoc \"in\" e\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' => unify e' efoc; twp_bind_core K)\n    || fail \"wp_bind: cannot find\" efoc \"in\" e\n  | _ => fail \"wp_bind: not a 'wp'\"\n  end.\n\n(** Heap tactics *)\nSection heap.\nContext `{!heapG Σ}.\nImplicit Types P Q : iProp Σ.\nImplicit Types Φ : val → iProp Σ.\nImplicit Types Δ : envs (uPredI (iResUR Σ)).\nImplicit Types v : val.\nImplicit Types z : Z.\n\nLemma tac_wp_allocN Δ Δ' s E j K v n Φ :\n  (0 < n)%Z →\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  (∀ l,\n    match envs_app false (Esnoc Enil j (array l 1 (replicate (Z.to_nat n) v))) Δ' with\n    | Some Δ'' =>\n       envs_entails Δ'' (WP fill K (Val $ LitV $ LitLoc l) @ s; E {{ Φ }})\n    | None => False\n    end) →\n  envs_entails Δ (WP fill K (AllocN (Val $ LitV $ LitInt n) (Val v)) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ? ? HΔ.\n  rewrite -wp_bind. eapply wand_apply; first exact: wp_allocN.\n  rewrite left_id into_laterN_env_sound; apply later_mono, forall_intro=> l.\n  specialize (HΔ l).\n  destruct (envs_app _ _ _) as [Δ''|] eqn:HΔ'; [ | contradiction ].\n  rewrite envs_app_sound //; simpl.\n  apply wand_intro_l. by rewrite (sep_elim_l (l ↦∗ _)%I) right_id wand_elim_r.\nQed.\nLemma tac_twp_allocN Δ s E j K v n Φ :\n  (0 < n)%Z →\n  (∀ l,\n    match envs_app false (Esnoc Enil j (array l 1 (replicate (Z.to_nat n) v))) Δ with\n    | Some Δ' =>\n       envs_entails Δ' (WP fill K (Val $ LitV $ LitLoc l) @ s; E [{ Φ }])\n    | None => False\n    end) →\n  envs_entails Δ (WP fill K (AllocN (Val $ LitV $ LitInt n) (Val v)) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=> ? HΔ.\n  rewrite -twp_bind. eapply wand_apply; first exact: twp_allocN.\n  rewrite left_id. apply forall_intro=> l.\n  specialize (HΔ l).\n  destruct (envs_app _ _ _) as [Δ'|] eqn:HΔ'; [ | contradiction ].\n  rewrite envs_app_sound //; simpl.\n  apply wand_intro_l. by rewrite (sep_elim_l (l ↦∗ _)%I) right_id wand_elim_r.\nQed.\n\nLemma tac_wp_alloc Δ Δ' s E j K v Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  (∀ l,\n    match envs_app false (Esnoc Enil j (l ↦ v)) Δ' with\n    | Some Δ'' =>\n       envs_entails Δ'' (WP fill K (Val $ LitV l) @ s; E {{ Φ }})\n    | None => False\n    end) →\n  envs_entails Δ (WP fill K (Alloc (Val v)) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ? HΔ.\n  rewrite -wp_bind. eapply wand_apply; first exact: wp_alloc.\n  rewrite left_id into_laterN_env_sound; apply later_mono, forall_intro=> l.\n  specialize (HΔ l).\n  destruct (envs_app _ _ _) as [Δ''|] eqn:HΔ'; [ | contradiction ].\n  rewrite envs_app_sound //; simpl.\n  apply wand_intro_l. by rewrite (sep_elim_l (l ↦ v)%I) right_id wand_elim_r.\nQed.\nLemma tac_twp_alloc Δ s E j K v Φ :\n  (∀ l,\n    match envs_app false (Esnoc Enil j (l ↦ v)) Δ with\n    | Some Δ' =>\n       envs_entails Δ' (WP fill K (Val $ LitV $ LitLoc l) @ s; E [{ Φ }])\n    | None => False\n    end) →\n  envs_entails Δ (WP fill K (Alloc (Val v)) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=> HΔ.\n  rewrite -twp_bind. eapply wand_apply; first exact: twp_alloc.\n  rewrite left_id. apply forall_intro=> l.\n  specialize (HΔ l).\n  destruct (envs_app _ _ _) as [Δ''|] eqn:HΔ'; [ | contradiction ].\n  rewrite envs_app_sound //; simpl.\n  apply wand_intro_l. by rewrite (sep_elim_l (l ↦ v)%I) right_id wand_elim_r.\nQed.\n\nLemma tac_wp_free Δ Δ' s E i K l v Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦ v)%I →\n  (let Δ'' := envs_delete false i false Δ' in\n   envs_entails Δ'' (WP fill K (Val $ LitV LitUnit) @ s; E {{ Φ }})) →\n  envs_entails Δ (WP fill K (Free (LitV l)) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ? Hlk Hfin.\n  rewrite -wp_bind. eapply wand_apply; first exact: wp_free.\n  rewrite into_laterN_env_sound -later_sep envs_lookup_split //; simpl.\n  rewrite -Hfin wand_elim_r (envs_lookup_sound' _ _ _ _ _ Hlk).\n  apply later_mono, sep_mono_r, wand_intro_r. rewrite right_id //.\nQed.\nLemma tac_twp_free Δ s E i K l v Φ :\n  envs_lookup i Δ = Some (false, l ↦ v)%I →\n  (let Δ' := envs_delete false i false Δ in\n   envs_entails Δ' (WP fill K (Val $ LitV LitUnit) @ s; E [{ Φ }])) →\n  envs_entails Δ (WP fill K (Free (LitV l)) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=> Hlk Hfin.\n  rewrite -twp_bind. eapply wand_apply; first exact: twp_free.\n  rewrite envs_lookup_split //; simpl.\n  rewrite -Hfin wand_elim_r (envs_lookup_sound' _ _ _ _ _ Hlk).\n  apply sep_mono_r, wand_intro_r. rewrite right_id //.\nQed.\n\nLemma tac_wp_load Δ Δ' s E i K l q v Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦{q} v)%I →\n  envs_entails Δ' (WP fill K (Val v) @ s; E {{ Φ }}) →\n  envs_entails Δ (WP fill K (Load (LitV l)) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ???.\n  rewrite -wp_bind. eapply wand_apply; first exact: wp_load.\n  rewrite into_laterN_env_sound -later_sep envs_lookup_split //; simpl.\n  by apply later_mono, sep_mono_r, wand_mono.\nQed.\nLemma tac_twp_load Δ s E i K l q v Φ :\n  envs_lookup i Δ = Some (false, l ↦{q} v)%I →\n  envs_entails Δ (WP fill K (Val v) @ s; E [{ Φ }]) →\n  envs_entails Δ (WP fill K (Load (LitV l)) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=> ??.\n  rewrite -twp_bind. eapply wand_apply; first exact: twp_load.\n  rewrite envs_lookup_split //; simpl.\n  by apply sep_mono_r, wand_mono.\nQed.\n\nLemma tac_wp_store Δ Δ' s E i K l v v' Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦ v)%I →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ v')) Δ' with\n  | Some Δ'' => envs_entails Δ'' (WP fill K (Val $ LitV LitUnit) @ s; E {{ Φ }})\n  | None => False\n  end →\n  envs_entails Δ (WP fill K (Store (LitV l) (Val v')) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ???.\n  destruct (envs_simple_replace _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  rewrite -wp_bind. eapply wand_apply; first by eapply wp_store.\n  rewrite into_laterN_env_sound -later_sep envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply later_mono, sep_mono_r, wand_mono.\nQed.\nLemma tac_twp_store Δ s E i K l v v' Φ :\n  envs_lookup i Δ = Some (false, l ↦ v)%I →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ v')) Δ with\n  | Some Δ' => envs_entails Δ' (WP fill K (Val $ LitV LitUnit) @ s; E [{ Φ }])\n  | None => False\n  end →\n  envs_entails Δ (WP fill K (Store (LitV l) v') @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq. intros.\n  destruct (envs_simple_replace _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  rewrite -twp_bind. eapply wand_apply; first by eapply twp_store.\n  rewrite envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply sep_mono_r, wand_mono.\nQed.\n\nLemma tac_wp_cmpxchg Δ Δ' s E i K l v v1 v2 Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦ v)%I →\n  vals_compare_safe v v1 →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ v2)) Δ' with\n  | Some Δ'' =>\n     v = v1 →\n     envs_entails Δ'' (WP fill K (Val $ PairV v (LitV $ LitBool true)) @ s; E {{ Φ }})\n  | None => False\n  end →\n  (v ≠ v1 →\n   envs_entails Δ' (WP fill K (Val $ PairV v (LitV $ LitBool false)) @ s; E {{ Φ }})) →\n  envs_entails Δ (WP fill K (CmpXchg (LitV l) (Val v1) (Val v2)) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ??? Hsuc Hfail.\n  destruct (envs_simple_replace _ _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  destruct (decide (v = v1)) as [Heq|Hne].\n  - rewrite -wp_bind. eapply wand_apply.\n    { eapply wp_cmpxchg_suc; eauto. }\n    rewrite into_laterN_env_sound -later_sep /= {1}envs_simple_replace_sound //; simpl.\n    apply later_mono, sep_mono_r. rewrite right_id. apply wand_mono; auto.\n  - rewrite -wp_bind. eapply wand_apply.\n    { eapply wp_cmpxchg_fail; eauto. }\n    rewrite into_laterN_env_sound -later_sep /= {1}envs_lookup_split //; simpl.\n    apply later_mono, sep_mono_r. apply wand_mono; auto.\nQed.\nLemma tac_twp_cmpxchg Δ s E i K l v v1 v2 Φ :\n  envs_lookup i Δ = Some (false, l ↦ v)%I →\n  vals_compare_safe v v1 →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ v2)) Δ with\n  | Some Δ' =>\n     v = v1 →\n     envs_entails Δ' (WP fill K (Val $ PairV v (LitV $ LitBool true)) @ s; E [{ Φ }])\n  | None => False\n  end →\n  (v ≠ v1 →\n   envs_entails Δ (WP fill K (Val $ PairV v (LitV $ LitBool false)) @ s; E [{ Φ }])) →\n  envs_entails Δ (WP fill K (CmpXchg (LitV l) v1 v2) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=> ?? Hsuc Hfail.\n  destruct (envs_simple_replace _ _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  destruct (decide (v = v1)) as [Heq|Hne].\n  - rewrite -twp_bind. eapply wand_apply.\n    { eapply twp_cmpxchg_suc; eauto. }\n    rewrite /= {1}envs_simple_replace_sound //; simpl.\n    apply sep_mono_r. rewrite right_id. apply wand_mono; auto.\n  - rewrite -twp_bind. eapply wand_apply.\n    { eapply twp_cmpxchg_fail; eauto. }\n    rewrite /= {1}envs_lookup_split //; simpl.\n    apply sep_mono_r. apply wand_mono; auto.\nQed.\n\nLemma tac_wp_cmpxchg_fail Δ Δ' s E i K l q v v1 v2 Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦{q} v)%I →\n  v ≠ v1 → vals_compare_safe v v1 →\n  envs_entails Δ' (WP fill K (Val $ PairV v (LitV $ LitBool false)) @ s; E {{ Φ }}) →\n  envs_entails Δ (WP fill K (CmpXchg (LitV l) v1 v2) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ?????.\n  rewrite -wp_bind. eapply wand_apply; first exact: wp_cmpxchg_fail.\n  rewrite into_laterN_env_sound -later_sep envs_lookup_split //; simpl.\n  by apply later_mono, sep_mono_r, wand_mono.\nQed.\nLemma tac_twp_cmpxchg_fail Δ s E i K l q v v1 v2 Φ :\n  envs_lookup i Δ = Some (false, l ↦{q} v)%I →\n  v ≠ v1 → vals_compare_safe v v1 →\n  envs_entails Δ (WP fill K (Val $ PairV v (LitV $ LitBool false)) @ s; E [{ Φ }]) →\n  envs_entails Δ (WP fill K (CmpXchg (LitV l) v1 v2) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq. intros. rewrite -twp_bind.\n  eapply wand_apply; first exact: twp_cmpxchg_fail.\n  rewrite envs_lookup_split //=. by do 2 f_equiv.\nQed.\n\nLemma tac_wp_cmpxchg_suc Δ Δ' s E i K l v v1 v2 Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦ v)%I →\n  v = v1 → vals_compare_safe v v1 →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ v2)) Δ' with\n  | Some Δ'' =>\n     envs_entails Δ'' (WP fill K (Val $ PairV v (LitV $ LitBool true)) @ s; E {{ Φ }})\n  | None => False\n  end →\n  envs_entails Δ (WP fill K (CmpXchg (LitV l) v1 v2) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ?????; subst.\n  destruct (envs_simple_replace _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  rewrite -wp_bind. eapply wand_apply.\n  { eapply wp_cmpxchg_suc; eauto. }\n  rewrite into_laterN_env_sound -later_sep envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply later_mono, sep_mono_r, wand_mono.\nQed.\nLemma tac_twp_cmpxchg_suc Δ s E i K l v v1 v2 Φ :\n  envs_lookup i Δ = Some (false, l ↦ v)%I →\n  v = v1 → vals_compare_safe v v1 →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ v2)) Δ with\n  | Some Δ' =>\n     envs_entails Δ' (WP fill K (Val $ PairV v (LitV $ LitBool true)) @ s; E [{ Φ }])\n  | None => False\n  end →\n  envs_entails Δ (WP fill K (CmpXchg (LitV l) v1 v2) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=>????; subst.\n  destruct (envs_simple_replace _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  rewrite -twp_bind. eapply wand_apply.\n  { eapply twp_cmpxchg_suc; eauto. }\n  rewrite envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply sep_mono_r, wand_mono.\nQed.\n\nLemma tac_wp_faa Δ Δ' s E i K l z1 z2 Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦ LitV z1)%I →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ LitV (LitInt (z1 + z2)))) Δ' with\n  | Some Δ'' => envs_entails Δ'' (WP fill K (Val $ LitV z1) @ s; E {{ Φ }})\n  | None => False\n  end →\n  envs_entails Δ (WP fill K (FAA (LitV l) (LitV z2)) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ???.\n  destruct (envs_simple_replace _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  rewrite -wp_bind. eapply wand_apply; first exact: (wp_faa _ _ _ z1 z2).\n  rewrite into_laterN_env_sound -later_sep envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply later_mono, sep_mono_r, wand_mono.\nQed.\nLemma tac_twp_faa Δ s E i K l z1 z2 Φ :\n  envs_lookup i Δ = Some (false, l ↦ LitV z1)%I →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ LitV (LitInt (z1 + z2)))) Δ with\n  | Some Δ' => envs_entails Δ' (WP fill K (Val $ LitV z1) @ s; E [{ Φ }])\n  | None => False\n  end →\n  envs_entails Δ (WP fill K (FAA (LitV l) (LitV z2)) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=> ??.\n  destruct (envs_simple_replace _ _ _) as [Δ'|] eqn:HΔ'; [ | contradiction ].\n  rewrite -twp_bind. eapply wand_apply; first exact: (twp_faa _ _ _ z1 z2).\n  rewrite envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply sep_mono_r, wand_mono.\nQed.\nEnd heap.\n\n(** Evaluate [lem] to a hypothesis [H] that can be applied, and then run\n[wp_bind K; tac H] for every possible evaluation context.  [tac] can do\n[iApplyHyp H] to actually apply the hypothesis.  TC resolution of [lem] premises\nhappens *after* [tac H] got executed. *)\nTactic Notation \"wp_apply_core\" open_constr(lem) tactic3(tac) :=\n  wp_pures;\n  iPoseProofCore lem as false (fun H =>\n    lazymatch goal with\n    | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n      reshape_expr e ltac:(fun K e' =>\n        wp_bind_core K; tac H) ||\n      lazymatch iTypeOf H with\n      | Some (_,?P) => fail \"wp_apply: cannot apply\" P\n      end\n    | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n      reshape_expr e ltac:(fun K e' =>\n        twp_bind_core K; tac H) ||\n      lazymatch iTypeOf H with\n      | Some (_,?P) => fail \"wp_apply: cannot apply\" P\n      end\n    | _ => fail \"wp_apply: not a 'wp'\"\n    end).\nTactic Notation \"wp_apply\" open_constr(lem) :=\n  wp_apply_core lem (fun H => iApplyHyp H; try iNext; try wp_expr_simpl).\n(** Tactic tailored for atomic triples: the first, simple one just runs\n[iAuIntro] on the goal, as atomic triples always have an atomic update as their\npremise.  The second one additionaly does some framing: it gets rid of [Hs] from\nthe context, which is intended to be the non-laterable assertions that iAuIntro\nwould choke on.  You get them all back in the continuation of the atomic\noperation. *)\nTactic Notation \"awp_apply\" open_constr(lem) :=\n  wp_apply_core lem (fun H => iApplyHyp H);\n  last iAuIntro.\nTactic Notation \"awp_apply\" open_constr(lem) \"without\" constr(Hs) :=\n  wp_apply_core lem (fun H => iApply wp_frame_wand_l; iSplitL Hs; [iAccu|iApplyHyp H]);\n  last iAuIntro.\n\nTactic Notation \"wp_alloc\" ident(l) \"as\" constr(H) :=\n  let Htmp := iFresh in\n  let finish _ :=\n    first [intros l | fail 1 \"wp_alloc:\" l \"not fresh\"];\n    pm_reduce;\n    lazymatch goal with\n    | |- False => fail 1 \"wp_alloc:\" H \"not fresh\"\n    | _ => iDestructHyp Htmp as H; wp_finish\n    end in\n  wp_pures;\n  (** The code first tries to use allocation lemma for a single reference,\n     ie, [tac_wp_alloc] (respectively, [tac_twp_alloc]).\n     If that fails, it tries to use the lemma [tac_wp_allocN]\n     (respectively, [tac_twp_allocN]) for allocating an array.\n     Notice that we could have used the array allocation lemma also for single\n     references. However, that would produce the resource l ↦∗ [v] instead of\n     l ↦ v for single references. These are logically equivalent assertions\n     but are not equal. *)\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    let process_single _ :=\n        first\n          [reshape_expr e ltac:(fun K e' => eapply (tac_wp_alloc _ _ _ _ Htmp K))\n          |fail 1 \"wp_alloc: cannot find 'Alloc' in\" e];\n        [iSolveTC\n        |finish ()]\n    in\n    let process_array _ :=\n        first\n          [reshape_expr e ltac:(fun K e' => eapply (tac_wp_allocN _ _ _ _ Htmp K))\n          |fail 1 \"wp_alloc: cannot find 'Alloc' in\" e];\n        [idtac|iSolveTC\n         |finish ()]\n    in (process_single ()) || (process_array ())\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    let process_single _ :=\n        first\n          [reshape_expr e ltac:(fun K e' => eapply (tac_twp_alloc _ _ _ Htmp K))\n          |fail 1 \"wp_alloc: cannot find 'Alloc' in\" e];\n        finish ()\n    in\n    let process_array _ :=\n        first\n          [reshape_expr e ltac:(fun K e' => eapply (tac_twp_allocN _ _ _ Htmp K))\n          |fail 1 \"wp_alloc: cannot find 'Alloc' in\" e];\n        [idtac\n        |finish ()]\n    in (process_single ()) || (process_array ())\n  | _ => fail \"wp_alloc: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_alloc\" ident(l) :=\n  wp_alloc l as \"?\".\n\nTactic Notation \"wp_free\" :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_free: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_free _ _ _ _ _ K))\n      |fail 1 \"wp_free: cannot find 'Free' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |pm_reduce; wp_finish]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_free _ _ _ _ K))\n      |fail 1 \"wp_free: cannot find 'Free' in\" e];\n    [solve_mapsto ()\n    |pm_reduce; wp_finish]\n  | _ => fail \"wp_free: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_load\" :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_load: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_load _ _ _ _ _ K))\n      |fail 1 \"wp_load: cannot find 'Load' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |wp_finish]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_load _ _ _ _ K))\n      |fail 1 \"wp_load: cannot find 'Load' in\" e];\n    [solve_mapsto ()\n    |wp_finish]\n  | _ => fail \"wp_load: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_store\" :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_store: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_store _ _ _ _ _ K))\n      |fail 1 \"wp_store: cannot find 'Store' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |pm_reduce; first [wp_seq|wp_finish]]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_store _ _ _ _ K))\n      |fail 1 \"wp_store: cannot find 'Store' in\" e];\n    [solve_mapsto ()\n    |pm_reduce; first [wp_seq|wp_finish]]\n  | _ => fail \"wp_store: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_cmpxchg\" \"as\" simple_intropattern(H1) \"|\" simple_intropattern(H2) :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_cmpxchg: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_cmpxchg _ _ _ _ _ K))\n      |fail 1 \"wp_cmpxchg: cannot find 'CmpXchg' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |try solve_vals_compare_safe\n    |pm_reduce; intros H1; wp_finish\n    |intros H2; wp_finish]\n  | |- envs_entails _ (twp ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_cmpxchg _ _ _ _ K))\n      |fail 1 \"wp_cmpxchg: cannot find 'CmpXchg' in\" e];\n    [solve_mapsto ()\n    |try solve_vals_compare_safe\n    |pm_reduce; intros H1; wp_finish\n    |intros H2; wp_finish]\n  | _ => fail \"wp_cmpxchg: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_cmpxchg_fail\" :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_cmpxchg_fail: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_cmpxchg_fail _ _ _ _ _ K))\n      |fail 1 \"wp_cmpxchg_fail: cannot find 'CmpXchg' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |try (simpl; congruence) (* value inequality *)\n    |try solve_vals_compare_safe\n    |wp_finish]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_cmpxchg_fail _ _ _ _ K))\n      |fail 1 \"wp_cmpxchg_fail: cannot find 'CmpXchg' in\" e];\n    [solve_mapsto ()\n    |try (simpl; congruence) (* value inequality *)\n    |try solve_vals_compare_safe\n    |wp_finish]\n  | _ => fail \"wp_cmpxchg_fail: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_cmpxchg_suc\" :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_cmpxchg_suc: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_cmpxchg_suc _ _ _ _ _ K))\n      |fail 1 \"wp_cmpxchg_suc: cannot find 'CmpXchg' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |try (simpl; congruence) (* value equality *)\n    |try solve_vals_compare_safe\n    |pm_reduce; wp_finish]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_cmpxchg_suc _ _ _ _ K))\n      |fail 1 \"wp_cmpxchg_suc: cannot find 'CmpXchg' in\" e];\n    [solve_mapsto ()\n    |try (simpl; congruence) (* value equality *)\n    |try solve_vals_compare_safe\n    |pm_reduce; wp_finish]\n  | _ => fail \"wp_cmpxchg_suc: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_faa\" :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_faa: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_faa _ _ _ _ _ K))\n      |fail 1 \"wp_faa: cannot find 'FAA' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |pm_reduce; wp_finish]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_faa _ _ _ _ K))\n      |fail 1 \"wp_faa: cannot find 'FAA' in\" e];\n    [solve_mapsto ()\n    |pm_reduce; wp_finish]\n  | _ => fail \"wp_faa: not a 'wp'\"\n  end.\n", "meta": {"author": "SkySkimmer", "repo": "iris", "sha": "186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5", "save_path": "github-repos/coq/SkySkimmer-iris", "path": "github-repos/coq/SkySkimmer-iris/iris-186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5/theories/heap_lang/proofmode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21231062866679956}}
{"text": "Require Import RelationClasses.\nRequire Import List.\n\nRequire Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Basic.\nRequire Import Axioms.\nRequire Import Loc.\nRequire Import Language.\nRequire Export ZArith.\n\nRequire Import Event.\nRequire Import Syntax.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import LibTactics. \nRequire Import Coqlib.\n\n(** * Semantics of the CSimpRTL *)\n\n(* This file defines the semantics of concurrent simple RTL language (RTL) *)\n\n(* The semantics of CSimpRTL is a set of transitions on the thread-local state *)\n\n(** ** Register File *)\nModule RegFile.\n  (** Register file is a total map from register to value. *)\n  Definition t := RegFun.t int.\n\n  (** Register file initialization *)\n  Definition init := RegFun.init Int.zero.\n\n  Fixpoint eval_expr (e: Inst.expr) (rf: t): int := \n      match e with \n      | Inst.expr_val val => val\n      | Inst.expr_reg r => RegFun.find r rf\n      | Inst.expr_op2 op e1 e2 => Op2.eval op (eval_expr e1 rf) (eval_expr e2 rf)\n      end.    \n\nEnd RegFile.\n\nLemma expr_eval_eq:\n  forall e R_t R_s\n    (REG_EQ: forall r, RegSet.In r (Inst.regs_of_expr e) ->\n                  RegFun.find r R_t = RegFun.find r R_s),\n    RegFile.eval_expr e R_t = RegFile.eval_expr e R_s.\nProof.\n  induction e; ii; ss; eauto.\n  - exploit REG_EQ; eauto. eapply RegSet.singleton_spec; eauto.\n  - specialize (IHe1 R_t R_s).\n    exploit IHe1; eauto. ii. eapply REG_EQ; eauto.\n    eapply RegSet.union_spec; eauto. introv EVAL_REG1.\n    specialize (IHe2 R_t R_s).\n    exploit IHe2; eauto. ii. eapply REG_EQ; eauto.\n    eapply RegSet.union_spec; eauto. introv EVAL_REG2.\n    rewrite EVAL_REG1, EVAL_REG2. eauto.\nQed.\n\n(** ** Continuation *)\nModule Continuation.\n    Inductive t := \n    | done\n    | stack (regs: RegFile.t) (blk: BBlock.t) (cdhp: CodeHeap) (cont: t)\n    .\nEnd Continuation.\n\n(** ** Thread-Local State and State Transitions *)\n(** Thread-local state includes:\n    - regs: register file;\n    - blk: current basic block;\n    - cdhp: codeheap for current function;\n    - cont: continuation, which acts as a call stack;\n    - code: whole program *)\nModule State. \n    Structure t := mk {\n        regs: RegFile.t;\n        blk: BBlock.t;\n        cdhp: CodeHeap;\n        cont: Continuation.t;\n        code: Code;   \n    }.\n\n    Definition init(code:Code) (f:Language.fid) : option t :=\n      match (code!f) with\n      | Some (ch, fentry) =>\n        match (ch!fentry) with\n        | Some b => Some (mk RegFile.init b ch Continuation.done code)\n        | _ => None\n        end\n      | _ => None\n      end.\n\n    Definition is_terminal (s: t): Prop:= \n        (blk s) = BBlock.ret /\\ (cont s) = Continuation.done.\n    \n    (** transform a `int32` to Loc.t (which is `positive` indeed) *)\n    Definition int2loc (i: int) : Loc.t := Z.to_pos (Int.unsigned i).\n\n    Notation \"[[ i ]]\" := (int2loc i) (at level 75, right associativity).\n\n    (** State transitions *)\n    Inductive step: forall (e:ProgramEvent.t) (s1:t) (s2:t), Prop :=\n    | step_skip\n        rf b b' ch cont code\n        (BLK: b = Inst.skip ## b')\n        :\n        step ProgramEvent.silent\n             (mk rf b ch cont code)\n             (mk rf b' ch cont code)\n    | step_assign\n        r e rf rf' b b' ch cont code\n        (BLK: b = (Inst.assign r e) ## b')\n        (REGFILE: rf' = RegFun.add r (RegFile.eval_expr e rf) rf)\n        :\n        step ProgramEvent.silent\n            (mk rf b ch cont code)\n            (mk rf' b' ch cont code)\n    | step_load\n        r loc or v rf rf' b b' ch cont code\n        (BLK: b = (Inst.load r loc or) ## b')\n        (REGFILE: rf' = RegFun.add r v rf)\n        :\n        step (ProgramEvent.read loc v or) \n            (mk rf b ch cont code)\n            (mk rf' b' ch cont code)\n    | step_store\n        loc e ow v  rf b b' ch cont code\n        (BLK: b = (Inst.store loc e ow) ## b')\n        (VAL: RegFile.eval_expr e rf = v)\n        :\n        step (ProgramEvent.write loc v ow) \n            (mk rf b ch cont code)\n            (mk rf b' ch cont code)     \n    | step_out  \n        e v rf b b' ch cont code\n        (BLK: b = (Inst.print e) ## b')\n        (VAL: RegFile.eval_expr e rf = v)\n        :\n        step (ProgramEvent.syscall (Event.mk v)) \n            (mk rf b ch cont code)\n            (mk rf b' ch cont code)    \n    | step_cas_same\n        r loc er ew or ow vr vw rf rf' b b' ch cont code\n        (BLK: b = (Inst.cas r loc er ew or ow) ## b')\n        (ATOMIC: or <> Ordering.plain )\n        (VALR: RegFile.eval_expr er rf = vr)\n        (VALW: RegFile.eval_expr ew rf = vw)\n        (REGFILE: rf' = RegFun.add r Int.one rf)\n        :\n        step (ProgramEvent.update loc vr vw or ow) \n            (mk rf b ch cont code)\n            (mk rf' b' ch cont code)   \n    | step_cas_flip\n        r loc er ew or ow vr' vr vw rf rf' b b' ch cont code\n        (BLK: b = (Inst.cas r loc er ew or ow) ## b')\n        (ATOMIC: or <> Ordering.plain )\n        (VALR: RegFile.eval_expr er rf = vr')\n        (VALW: RegFile.eval_expr ew rf = vw)\n        (TEST: Int.cmp Cne vr vr')\n        (REGFILE: rf' = RegFun.add r Int.zero rf)\n        :\n        step (ProgramEvent.read loc vr or) \n            (mk rf b ch cont code)\n            (mk rf' b' ch cont code)   \n    | step_call \n        rf (code:Code) (b:BBlock.t) b' f fret f0 b b0 ch ch0 cont cont0  \n        (BLK: b = BBlock.call f fret)\n        (FIND_FUNC: (code!f) = Some (ch0, f0))\n        (ENTRY_BLK: (ch0!f0) = Some (b0))\n        (STACK: ch!fret = Some (b'))\n        (CONT: cont0 = (Continuation.stack rf b' ch cont))\n        :\n        step ProgramEvent.silent \n            (mk rf b ch cont code)\n            (mk (RegFile.init) b0 ch0 cont0 code)    \n    | step_ret \n        b rf rf0 b0 ch0 cont0 ch cont code\n        (BLK: b = BBlock.ret)\n        (CONT: cont = (Continuation.stack rf0 b0 ch0 cont0))\n        :\n        step (ProgramEvent.silent) \n            (mk rf b ch cont code)\n            (mk rf0 b0 ch0 cont0 code) \n    | step_fence_rel\n        b rf ch b' cont code\n        (BLK: b = (Inst.fence_rel) ## b')\n        :\n        step (ProgramEvent.fence (Ordering.relaxed) (Ordering.acqrel))\n            (mk rf b ch cont code)\n            (mk rf b' ch cont code)   \n    | step_fence_acq\n        b rf ch b' cont code\n        (BLK: b = (Inst.fence_acq) ## b')\n        :\n        step (ProgramEvent.fence (Ordering.acqrel) (Ordering.relaxed))\n            (mk rf b ch cont code)\n            (mk rf b' ch cont code)  \n    | step_fence_sc\n        b rf ch b' cont code\n        (BLK: b = (Inst.fence_sc) ## b')\n        :\n        step (ProgramEvent.fence (Ordering.relaxed) (Ordering.seqcst))\n            (mk rf b ch cont code)\n            (mk rf b' ch cont code)  \n    | step_jmp\n        b f rf ch b' cont code\n        (BLK: b = BBlock.jmp f)\n        (TGT: ch!f = Some (b'))\n        :\n        step (ProgramEvent.silent) \n            (mk rf b ch cont code)\n            (mk rf b' ch cont code)   \n    | step_be \n        b e f1 f2 rf v ch b' cont code\n        (BLK: b = BBlock.be e f1 f2)\n        (COND: RegFile.eval_expr e rf = v)\n        (BRANCH: (ch!f1 = Some (b') /\\ Int.eq v Int.zero) \\/\n                (ch!f2 = Some (b') /\\ Int.cmp Cne v Int.zero))\n        :\n        step (ProgramEvent.silent) \n            (mk rf b ch cont code)\n            (mk rf b' ch cont code)   \n    .\nEnd State. \n\nProgram Definition rtl_lang:Language.t :=\n  Language.mk\n    State.init\n    State.is_terminal\n    State.step _ _ _.\nNext Obligation. \n(** prove determinacy of rtl language (required by Language.v) on thread-local transition*)\n  inv STEP1; try solve [inv STEP2; inv BLK; tryfalse; eauto];\n    inv STEP2; inv BLK; tryfalse.\n  {\n    right. left.\n    exists or0 loc0 v v0; eauto.\n  }\n  {\n    eauto.\n  }\n  { \n    right; right; left.\n    exists or0 ow0 loc0.\n    exists (RegFile.eval_expr er0 rf) (RegFile.eval_expr ew0 rf) vr.\n    eauto.\n  }\n  {\n    right; right; right.\n    exists or0 ow0 loc0.\n    exists (RegFile.eval_expr er0 rf) (RegFile.eval_expr ew0 rf) vr.\n    eauto.\n  }\n  { \n    right; left.\n    exists or0 loc0 vr vr0.\n    eauto.\n  }\n  {\n    left. split; eauto.\n    rewrite FIND_FUNC in FIND_FUNC0. inv FIND_FUNC0.\n    rewrite ENTRY_BLK in ENTRY_BLK0. inv ENTRY_BLK0.\n    rewrite STACK in STACK0. inv STACK0.\n    eauto.\n  }\n  {\n    inv CONT; eauto.\n  }\n  {\n    rewrite TGT in TGT0. inv TGT0; eauto.\n  }\n  {\n    left; eauto.\n    destruct BRANCH; destruct BRANCH0.\n    {\n      destruct H, H0.\n      rewrite H in H0; inv H0; eauto.\n    }\n    { \n      destruct H, H0.\n      unfolds Int.cmp, Int.eq.\n      destruct (Coqlib.zeq (Int.unsigned (RegFile.eval_expr e0 rf)) (Int.unsigned Int.zero)); tryfalse.\n    }\n    {\n      destruct H, H0.\n      unfolds Int.cmp, Int.eq.\n      destruct (Coqlib.zeq (Int.unsigned (RegFile.eval_expr e0 rf)) (Int.unsigned Int.zero)); tryfalse.\n    }\n    {\n      destruct H, H0.\n      rewrite H in H0; inv H0; eauto.\n    }\n  }\nQed. \nNext Obligation.\n  inv READ.\n  eexists. left.\n  {\n    econs; eauto.\n  }\n  {\n    destruct (classic (Int.cmp Cne val' (RegFile.eval_expr er rf))).\n    {\n      eexists.\n      left. eapply State.step_cas_flip; eauto.\n    }\n    {\n      unfold Int.cmp in H.\n      unfold negb in H.\n      destruct (Int.eq val' (RegFile.eval_expr er rf)) eqn:Heqe; ss.\n      eapply Int.same_if_eq in Heqe; subst.\n      eexists.\n      right.\n      do 2 eexists.\n      econs; eauto.\n    }\n  }\nQed.\nNext Obligation.\n  inv UPDATE.\n  destruct (classic (Int.cmp Cne val' (RegFile.eval_expr er rf))).\n  {\n    eexists.\n    left.\n    eapply State.step_cas_flip; eauto.\n  }\n  {\n    unfold Int.cmp in H.\n    unfold negb in H.\n    destruct (Int.eq val' (RegFile.eval_expr er rf)) eqn:Heqe; ss.\n    eapply Int.same_if_eq in Heqe; subst.\n    eexists.\n    right.\n    econs; eauto.\n  }\nQed.\n\n\nLemma regs_add_neg\n      r (v: Const.t) r' regs\n      (NEQ: r <> r'):\n  (RegFun.add r v regs) r' = regs r'.\nProof.\n  assert(RegFun.find r' (RegFun.add r v regs) = regs r').\n  rewrite RegFun.add_spec_neq; eauto.\n  unfold LocFun.find in *. eauto.\nQed.\n\nLemma regs_add_nonfree_var_eq_eval_expr:\n  forall expr regs r val,\n  ~(RegSet.mem r (Inst.regs_of_expr expr)) ->\n  RegFile.eval_expr expr regs = RegFile.eval_expr expr (RegFun.add r val regs).\nProof.\n  induction expr.\n  -\n   intros. unfold RegFile.eval_expr. trivial.\n  -\n  intros. unfold RegFile.eval_expr.\n  assert (r <> reg). {\n    unfolds Inst.regs_of_expr.\n    intro.\n    apply H.\n    rewrite H0.\n    rewrite RegSet.Facts.singleton_b.\n    unfold RegSet.Facts.eqb.\n    des_ifs.\n  }\n  unfold RegFun.find in *.\n  rewrite regs_add_neg; trivial.\n  -\n    intros.\n    unfold RegFile.eval_expr. unfold Op2.eval.\n    rewrite <- IHexpr1; trivial.\n    rewrite <- IHexpr2; trivial.\n    * \n    unfold Inst.regs_of_expr in H.\n    fold Inst.regs_of_expr in H. \n    rewrite RegSet.Facts.union_b in H.\n    unfold \"||\" in H.\n    intro.\n    apply H.\n    des_ifs.\n    *\n    unfold Inst.regs_of_expr in H.\n    fold Inst.regs_of_expr in H. \n    rewrite RegSet.Facts.union_b in H.\n    unfold \"||\" in H.\n    intro.\n    apply H.\n    des_ifs.\nQed.\n\n\n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/rtl/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.34510528442897664, "lm_q1q2_score": 0.2122700741966984}}
{"text": "Require Import Omega.\nRequire Import RelationClasses.\n\nRequire Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Axioms.\nRequire Import Basic.\nRequire Import DataStructure.\nRequire Import DenseOrder.\nRequire Import Language.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import PromiseConsistent.\nRequire Import ReorderPromise.\nRequire Import MemoryReorder.\nRequire Import MemoryFacts.\nRequire Import WFConfig.\nRequire Import MemoryProps.\n\nSet Implicit Arguments.\n\nLemma reserve_sc_nochange\n      lang (e e': Thread.t lang) lo\n      (RSVs: rtc (Thread.reserve_step lo) e e'):\n  (Thread.sc e) = (Thread.sc e') /\\ (Thread.state e) = (Thread.state e').\nProof.\n  induction RSVs; ii; eauto.\n  inv H. inv STEP; ss.\nQed.\n  \nLemma reorder_reserve_promise\n      prom0 mem0\n      prom1 mem1\n      prom2 mem2\n      loc1 from1 to1\n      loc2 from2 to2 msg2 kind2\n      (STEP1: Memory.promise prom0 mem0 loc1 from1 to1 Message.reserve prom1 mem1 Memory.op_kind_add)\n      (STEP2: Memory.promise prom1 mem1 loc2 from2 to2 msg2 prom2 mem2 kind2):\n  (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ msg2 = Message.reserve /\\ kind2 = Memory.op_kind_cancel /\\\n   prom0 = prom2 /\\ mem0 = mem2) \\/\n  (exists prom1' mem1',\n      <<STEP1: Memory.promise prom0 mem0 loc2 from2 to2 msg2 prom1' mem1' kind2>> /\\\n      <<STEP2: Memory.promise prom1' mem1' loc1 from1 to1 Message.reserve prom2 mem2 Memory.op_kind_add>>).\nProof.\n  inv STEP1. inv STEP2; ss.\n  - (* reserve/add *)\n    exploit MemoryReorder.add_add; try exact PROMISES; try exact PROMISES0; eauto. i. des.\n    exploit MemoryReorder.add_add; try exact MEM; try exact MEM0; eauto. i. des.\n    right. esplits.\n    + econs; eauto; try congr.\n      i. exploit Memory.add_get1; try exact MEM; eauto.\n    + econs; eauto. ss.\n  - (* reserve/split *)\n    exploit MemoryReorder.add_split; try exact PROMISES; try exact PROMISES0; eauto. i.\n    des; clarify.\n    + exploit MemoryReorder.add_split; try exact MEM; try exact MEM0; eauto. i. des; [congr|].\n      right. esplits.\n      * econs 2; eauto.\n      * econs; eauto. ss.\n  - (* reserve/lower *)\n    des. subst.\n    exploit MemoryReorder.add_lower; try exact PROMISES; try exact PROMISES0; eauto. i.\n    des; clarify.\n    + exploit MemoryReorder.add_lower; try exact MEM; try exact MEM0; eauto. i. des; [congr|].\n      right. esplits.\n      * econs; eauto.\n      * econs; eauto. ss.\n  - (* reserve/cancel *)\n    destruct (classic ((loc1, to1) = (loc2, to2))).\n    + inv H.\n      exploit MemoryReorder.add_remove_same; try exact PROMISES0; eauto. i. des. subst.\n      exploit MemoryReorder.add_remove_same; try exact MEM0; eauto. i. des. subst.\n      left. splits; auto.\n    + exploit MemoryReorder.add_remove; try exact PROMISES0; eauto. i. des.\n      exploit MemoryReorder.add_remove; try exact MEM0; eauto. i. des.\n      right. esplits; eauto. econs; eauto. ss.\nQed.\n\nLemma reorder_promise_reserve_promise\n      lc0 mem0\n      lc1 mem1\n      lc2 mem2\n      loc1 from1 to1\n      loc2 from2 to2 msg2 kind2\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.promise_step lc1 mem1 loc2 from2 to2 msg2 lc2 mem2 kind2):\n  (loc1 = loc2 /\\ from1 = from2 /\\ to1 = to2 /\\ msg2 = Message.reserve /\\ kind2 = Memory.op_kind_cancel /\\\n   lc0 = lc2 /\\ mem0 = mem2) \\/\n  (exists lc1' mem1',\n      <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc1' mem1' kind2>> /\\\n      <<STEP2: Local.promise_step lc1' mem1' loc1 from1 to1 Message.reserve lc2 mem2 Memory.op_kind_add>>).\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit reorder_reserve_promise; eauto. i. des; subst.\n  { left. splits; auto. destruct lc0; auto. }\n  right. esplits.\n  { econs; eauto. inv STEP2.\n    \n    \n    eapply memory_concrete_le_closed_msg; try apply CLOSED0.\n    ii. erewrite (@Memory.add_o mem2 mem1') in GET; eauto. des_ifs. }\n  { econs; eauto. }\nQed.\n\nLemma add_non_synch_loc loc0 prom0 loc1 from to msg prom1\n      (NONSYNCH: Memory.nonsynch_loc loc0 prom1)\n      (ADD: Memory.add prom0 loc1 from to msg prom1)\n  :\n    Memory.nonsynch_loc loc0 prom0.\nProof.\n  ii. eapply Memory.add_get1 in GET; eauto.\n  des_ifs. exploit NONSYNCH; eauto.\nQed.\n\nLemma reserve_non_synch_loc loc0 prom0 loc1 from to prom1\n      (NONSYNCH: Memory.nonsynch_loc loc0 prom0)\n      (RSV: Memory.add prom0 loc1 from to Message.reserve prom1)\n  :\n    Memory.nonsynch_loc loc0 prom1.\nProof.\n  ii. erewrite Memory.add_o in GET; eauto.\n  destruct (loc_ts_eq_dec (loc0, t) (loc1, to)).\n  inv GET; ss; des; subst.\n  ss.\n  exploit NONSYNCH; eauto.\nQed.\n\nLemma add_non_synch prom0 loc from to msg prom1\n      (NONSYNCH: Memory.nonsynch prom1)\n      (ADD: Memory.add prom0 loc from to msg prom1)\n  :\n    Memory.nonsynch prom0.\nProof.\n  ii. eapply Memory.add_get1 in GET; eauto.\n  des_ifs. exploit NONSYNCH; eauto.\nQed.\n\nLemma reserve_non_synch prom0 loc from to prom1\n      (NONSYNCH: Memory.nonsynch prom0)\n      (RSV: Memory.add prom0 loc from to Message.reserve prom1)\n  :\n    Memory.nonsynch prom1.\nProof.\n  ii. erewrite Memory.add_o in GET; eauto.\n  des_ifs; ss.\n  exploit NONSYNCH; eauto.\nQed.\n\nLemma reorder_reserve_fence\n      lc0 mem0\n      lc1 mem1\n      lc2\n      loc1 from1 to1\n      ord1 ord2 sc0 sc1\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.fence_step lc1 sc0 ord1 ord2 lc2 sc1)\n  :\n    exists lc1',\n      (<<STEP1: Local.fence_step lc0 sc0 ord1 ord2 lc1' sc1>>) /\\\n      (<<STEP2: Local.promise_step lc1' mem0 loc1 from1 to1 Message.reserve lc2 mem1 Memory.op_kind_add>>).\nProof.\n  inv STEP1. inv STEP2. ss. esplits.\n  - econs; eauto.\n    + inv PROMISE. i. eapply add_non_synch; eauto.\n    + i. ss. subst. erewrite PROMISES in *; auto.\n      inv PROMISE. eapply Memory.add_get0 in PROMISES0. des.\n      erewrite Memory.bot_get in *. ss.\n  - econs; eauto.\nQed.\n\nLemma reorder_reserve_read\n      lc0 mem0\n      lc1 mem1\n      lc2\n      loc1 from1 to1\n      loc2 to2 val2 released2 ord2 lo\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.read_step lc1 mem1 loc2 to2 val2 released2 ord2 lc2 lo)\n  :\n    exists lc1',\n      (<<STEP1: Local.read_step lc0 mem0 loc2 to2 val2 released2 ord2 lc1' lo>>) /\\\n      (<<STEP2: Local.promise_step lc1' mem0 loc1 from1 to1 Message.reserve lc2 mem1 Memory.op_kind_add>>).\nProof.\n  inv STEP1. inv STEP2. esplits; eauto.\n  { econs; eauto. inv PROMISE.\n    erewrite Memory.add_o in GET; eauto. des_ifs. eauto. }\n  { econs; eauto. }\nQed.\n\nLemma reorder_reserve_write\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2 mem2\n      loc1 from1 to1\n      loc2 from2 to2 val2 releasedm2 released2 ord2 kind2 lo\n      (STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 Message.reserve lc1 mem1 Memory.op_kind_add)\n      (STEP2: Local.write_step lc1 sc0 mem1 loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind2 lo)\n  :\n    exists lc1' mem1',\n      (<<STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1' sc2 mem1' kind2 lo>>) /\\\n      (<<STEP2: Local.promise_step lc1' mem1' loc1 from1 to1 Message.reserve lc2 mem2 Memory.op_kind_add>>).\nProof.\n  inv STEP1. inv STEP2. ss. inv WRITE.\n  exploit reorder_reserve_promise.\n  { eapply PROMISE. }\n  { eapply PROMISE0. }\n  i. des; clarify.\n  i. des; clarify.\n  assert (LOCTS: (loc1, to1) <> (loc2, to2)).\n  { ii. clarify. inv PROMISE.\n    eapply Memory.add_get0 in MEM. des. inv PROMISE0; ss.\n    { eapply Memory.add_get0 in MEM. des. clarify. }\n    { des. subst. eapply Memory.split_get0 in MEM. des. clarify. }\n    { des. subst. eapply Memory.lower_get0 in MEM. des. clarify. }\n  }\n  exploit MemoryReorder.add_remove; eauto.\n  { inv STEP2. eauto. }\n  i. des. esplits.\n  { econs; eauto. i. inv PROMISE. eapply add_non_synch_loc; eauto. }\n  { econs; eauto. ss. inv STEP2. econs; eauto. }\nQed.\n\nLemma reorder_promise_add_reserve\n      lc1 mem1 loc1 from1 to1 val released\n      lc2 mem2 loc2 from2 to2 lc3 mem3\n      (PRM_ADD: Local.promise_step lc1 mem1 loc1 from1 to1 (Message.concrete val released) lc2 mem2 Memory.op_kind_add)\n      (RSV: Local.promise_step lc2 mem2 loc2 from2 to2 Message.reserve lc3 mem3 Memory.op_kind_add):\n  (exists lc' mem',\n      Local.promise_step lc1 mem1 loc2 from2 to2 Message.reserve lc' mem' Memory.op_kind_add /\\\n      Local.promise_step lc' mem' loc1 from1 to1 (Message.concrete val released) lc3 mem3 Memory.op_kind_add) \\/\n  (loc1 = loc2 /\\ to1 = from2).\nProof.\n  inv PRM_ADD; inv RSV; ss.\n  inv PROMISE; inv PROMISE0; ss.\n  exploit MemoryReorder.add_add; [eapply PROMISES | eapply PROMISES0 | eauto..].\n  ii. des.\n  exploit MemoryReorder.add_add; [eapply MEM | eapply MEM0 | eauto..].\n  ii; des.\n  destruct (classic (to1 = from2)); subst.\n  {\n    destruct (classic (loc1 = loc2)); subst.\n    {\n      (* attach implies not reorder *)\n      eauto.\n    }\n    {\n      (* not attach implies reorder *)\n      left.\n      do 2 eexists.\n      split.\n      econstructor. econstructor; eauto.\n      ii; ss.\n      ss.\n      ss.\n      econstructor; eauto.\n      econstructor; eauto.\n      ii.\n      inv MSG. \n      clear - ATTACH ADD0 GET H.\n      exploit ATTACH; eauto.\n      instantiate (2 := to'); instantiate (1 := msg').\n      erewrite Memory.add_o in GET; eauto.\n      destruct (loc_ts_eq_dec (loc1, to') (loc2, to2)); subst; ss.\n      des; ss.\n      eapply Memory.add_closed_message with (mem1 := mem2); eauto.\n    }\n  }\n  {\n    (* not attach implies reorder *)\n    destruct (classic (loc1 = loc2)); subst.\n    {\n      left.\n      do 2 eexists.\n      split.\n      econstructor. econstructor; eauto.\n      ii; ss.\n      ss.\n      ss.\n      econstructor; eauto.\n      econstructor; eauto.\n      ii.\n      inv MSG.\n      clear - ATTACH ADD0 GET H.\n      destruct (classic (to' = to2)); subst.\n      {\n        eapply Memory.add_get0 in ADD0; des.\n        rewrite GET1 in GET; inv GET; ss.\n      }\n      {\n        exploit ATTACH; eauto.\n        instantiate (2 := to'); instantiate (1 := msg').\n        erewrite Memory.add_o in GET; eauto.\n        destruct (loc_ts_eq_dec (loc2, to') (loc2, to2)); subst; ss.\n        des; subst; ss.\n      }\n      eapply Memory.add_closed_message with (mem1 := mem2); eauto.\n    }\n    {\n      left.\n      do 2 eexists.\n      split.\n      econstructor. econstructor; eauto.\n      ii; ss.\n      ss.\n      ss.\n      econstructor; eauto.\n      econstructor; eauto.\n      ii.\n      inv MSG.\n      clear - ATTACH ADD0 GET H.\n      exploit ATTACH; eauto.\n      instantiate (2 := to'); instantiate (1 := msg').\n      erewrite Memory.add_o in GET; eauto.\n      destruct (loc_ts_eq_dec (loc1, to') (loc2, to2)); subst; ss.\n      inv GET.\n      des; subst; ss.\n      eapply Memory.add_closed_message with (mem1 := mem2); eauto.\n    }\n  }\nQed.\n\nLemma reorder_promise_add_reserve_step_attached\n      lc1 mem1 loc from ts val released lc2 mem2\n      to lc3 mem3 loc' from' to' lc4 mem4 \n      (PROMISE: Local.promise_step lc1 mem1 loc from ts (Message.concrete val released) lc2 mem2 Memory.op_kind_add)\n      (RSV_ATTACH: Local.promise_step lc2 mem2 loc ts to Message.reserve lc3 mem3 Memory.op_kind_add)\n      (RSV: Local.promise_step lc3 mem3 loc' from' to' Message.reserve lc4 mem4 Memory.op_kind_add):\n  exists lc' mem' lc'' mem'',\n    Local.promise_step lc1 mem1 loc' from' to' Message.reserve lc' mem' Memory.op_kind_add /\\\n    Local.promise_step lc' mem' loc from ts (Message.concrete val released) lc'' mem'' Memory.op_kind_add /\\\n    Local.promise_step lc'' mem'' loc ts to Message.reserve lc4 mem4 Memory.op_kind_add.\nProof.\n  exploit reorder_promise_reserve_promise; [eapply RSV_ATTACH | eapply RSV | eauto..]. ii.\n  des; ss.\n  exploit reorder_promise_add_reserve; [eapply PROMISE | eapply STEP1 | eauto..]. ii.\n  des; ss.\n  do 4 eexists; eauto.\n  subst.\n  clear - RSV_ATTACH RSV.\n  inv RSV_ATTACH; inv RSV.\n  inv PROMISE; inv PROMISE0.\n  clear - MEM MEM0.\n  destruct (loc_ts_eq_dec (loc', to) (loc', to')); ss.\n  {\n    des; ss.\n    exploit MemoryReorder.add_add; [eapply MEM | eapply MEM0 | eauto..].\n    ii; des.\n    subst.\n    contradiction LOCTS; eauto.\n  }\n  {\n    des; ss.\n    assert(LT1: Time.lt from' to).\n    {\n      clear - MEM.\n      inv MEM.\n      inv ADD; eauto.\n    }\n    assert(LT2: Time.lt from' to').\n    {\n      clear - MEM0.\n      inv MEM0.\n      inv ADD; eauto.\n    }\n    eapply Memory.add_get0 in MEM; des.\n    inv MEM0.\n    inv ADD.\n    unfold Memory.get in GET0.\n    unfold Cell.get in GET0.\n    eapply DISJOINT in GET0; eauto.\n    clear - GET0 LT1 LT2.\n    unfold Interval.disjoint in *.\n    destruct(Time.le_lt_dec to' to).\n    {\n      specialize (GET0 to').\n      exploit GET0; ss.\n      econstructor; ss; eauto.\n      eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1; eauto.\n    }\n    {\n      specialize (GET0 to).\n      exploit GET0; ss.\n      econstructor; ss; eauto.\n      eapply Time.le_lteq; eauto.\n      econstructor; ss.\n      eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1; eauto.\n    }\n  }\nQed.\n  \nLemma reorder_promise_add_reservations_attached:\n  forall n lang lc1 mem1 loc from ts val released lc2 mem2\n    to lc3 mem3 st sc e'' lo\n    (PROMISE: Local.promise_step lc1 mem1 loc from ts (Message.concrete val released) lc2 mem2 Memory.op_kind_add)\n    (RSV_ATTACH: Local.promise_step lc2 mem2 loc ts to Message.reserve lc3 mem3 Memory.op_kind_add)\n    (RSVs: rtcn (Thread.reserve_step lo) n (Thread.mk lang st lc3 sc mem3) e''),\n  exists lc' mem' lc'' mem''  lc4 mem4,\n    rtc (Thread.reserve_step lo) (Thread.mk lang st lc1 sc mem1) (Thread.mk lang st lc' sc mem') /\\\n    Local.promise_step lc' mem' loc from ts (Message.concrete val released) lc'' mem'' Memory.op_kind_add /\\\n    Local.promise_step lc'' mem'' loc ts to Message.reserve lc4 mem4 Memory.op_kind_add /\\\n    e'' = Thread.mk lang st lc4 sc mem4.\nProof.\n  induction n; ii.\n  - inv RSVs; eauto.\n    do 6 eexists; eauto.\n  - inv RSVs.\n    inv A12.\n    inv STEP.\n    exploit reorder_promise_add_reserve_step_attached; [eapply PROMISE | eapply RSV_ATTACH | eapply LOCAL | eauto..].\n    ii; des.\n    exploit IHn; [eapply x1 | eapply x2 | eapply A23 | eauto..].\n    ii; des; subst.\n    do 6 eexists.\n    split.\n    eapply Relation_Operators.rt1n_trans; [idtac | eapply x | eauto..].\n    econstructor; eauto.\n    econstructor; eauto.\n    split; eauto.\nQed. \n\nLemma reorder_promise_split_reserve\n      lc1 mem1 loc1 from1 to1 val released ts msg\n      lc2 mem2 loc2 from2 to2 lc3 mem3\n      (PRM_ADD: Local.promise_step lc1 mem1 loc1 from1 to1 (Message.concrete val released) lc2 mem2\n                                   (Memory.op_kind_split ts msg))\n      (RSV: Local.promise_step lc2 mem2 loc2 from2 to2 Message.reserve lc3 mem3 Memory.op_kind_add):\n  (exists lc' mem',\n      Local.promise_step lc1 mem1 loc2 from2 to2 Message.reserve lc' mem' Memory.op_kind_add /\\\n      Local.promise_step lc' mem' loc1 from1 to1 (Message.concrete val released) lc3 mem3\n                         (Memory.op_kind_split ts msg)).\nProof.\n  inv PRM_ADD; inv RSV; ss.\n  inv PROMISE; inv PROMISE0.\n  des; subst.\n  exploit MemoryReorder.split_add; [eapply PROMISES | eapply PROMISES0 | eauto..].\n  ii; des; subst.\n  exploit MemoryReorder.split_add; [eapply MEM | eapply MEM0 | eauto..].\n  ii; des; subst.\n  do 2 eexists.\n  split.\n  econstructor.\n  econstructor.\n  eapply ADD1.\n  eapply ADD0.\n  ss.\n  ii; ss.\n  ss.\n  ss.\n  econstructor; eauto.\n  econstructor; eauto.\n  eapply Memory.add_closed_message; eauto.\nQed.\n\nLemma reorder_promise_lower_reserve\n      lc1 mem1 loc1 from1 to1 val released msg\n      lc2 mem2 loc2 from2 to2 lc3 mem3\n      (PRM_ADD: Local.promise_step lc1 mem1 loc1 from1 to1 (Message.concrete val released) lc2 mem2\n                                   (Memory.op_kind_lower msg))\n      (RSV: Local.promise_step lc2 mem2 loc2 from2 to2 Message.reserve lc3 mem3 Memory.op_kind_add):\n  (exists lc' mem',\n      Local.promise_step lc1 mem1 loc2 from2 to2 Message.reserve lc' mem' Memory.op_kind_add /\\\n      Local.promise_step lc' mem' loc1 from1 to1 (Message.concrete val released) lc3 mem3\n                         (Memory.op_kind_lower msg)).\nProof.\n  inv PRM_ADD; inv RSV; ss.\n  inv PROMISE; inv PROMISE0.\n  exploit MemoryReorder.lower_add; [eapply PROMISES | eapply PROMISES0 | eauto..].\n  ii; des.\n  exploit MemoryReorder.lower_add; [eapply MEM | eapply MEM0 | eauto..].\n  ii; des.\n  do 2 eexists.\n  split.\n  econstructor.\n  econstructor.\n  eapply ADD1. eapply ADD0. ss.\n  ii; ss. ss. ss.\n  econstructor; eauto.\n  eapply Memory.add_closed_message; eauto.\nQed.\n  \nLemma reorder_promise_step_reserve_steps:\n  forall n lang (e e' e'': Thread.t lang) pf te lo\n    (PROMISE: Thread.promise_step pf te e e')\n    (RSVs: rtcn (Thread.reserve_step lo) n e' e'')\n    (NO_RSV_CCL: Thread.not_rsv_ccl_scfence te = true),\n    (exists e0, rtc (Thread.reserve_step lo) e e0 /\\ Thread.promise_step pf te e0 e'') \\/\n    (exists e0 e1 loc to ts from msg,\n        rtc (Thread.reserve_step lo) e e0 /\\\n        Thread.promise_step pf te e0 e1 /\\ te = ThreadEvent.promise loc from ts msg Memory.op_kind_add /\\ \n        Thread.promise_step false (ThreadEvent.promise loc ts to Message.reserve Memory.op_kind_add) e1 e'').\nProof.\n  induction n; ii.\n  - inv RSVs; eauto.\n  - inv RSVs. inv A12. \n    inv PROMISE; inv STEP; ss. \n    destruct msg; ss.\n    destruct kind; ss.\n    {\n      (* promise add / reserve *)\n      exploit reorder_promise_add_reserve; eauto. ii.\n      des.\n      { \n        eapply IHn with (e := Thread.mk lang st lc' sc1 mem') (pf := false)\n                        (te := ThreadEvent.promise loc0 from0 to0 (Message.concrete val released) Memory.op_kind_add)\n          in A23; eauto.\n        des.\n        {\n          left.\n          eexists.\n          split.\n          eapply Relation_Operators.rt1n_trans; eauto.\n          econstructor; eauto.\n          econstructor; eauto.\n          eauto.\n        }\n        {\n          inv A1; ss.\n          right.\n          do 7 eexists.\n          split.\n          eapply Relation_Operators.rt1n_trans; [|eapply A23]; eauto.\n          econstructor; eauto.\n          econstructor; eauto.\n          split; eauto.\n        }\n        econstructor; eauto.\n      }\n      {\n        subst.\n        right.\n        exploit reorder_promise_add_reservations_attached; [eapply LOCAL | eapply LOCAL0 | eapply A23 | eauto..].\n        ii; des; subst.\n        do 7 eexists.\n        split.\n        eapply x0.\n        split.\n        econstructor; eauto.\n        split.\n        econstructor; eauto.\n        econstructor; eauto.\n      }\n    }\n    {\n      (* promise split / reserve *)\n      exploit reorder_promise_split_reserve; eauto.\n      ii; des.\n      eapply IHn with (e := Thread.mk lang st lc' sc1 mem')\n                      (te := ThreadEvent.promise loc0 from0 to0 (Message.concrete val released)\n                                                 (Memory.op_kind_split ts3 msg3)) in A23; eauto.\n      des.\n      {\n        left.\n        eexists.\n        split.\n        eapply Relation_Operators.rt1n_trans; [idtac | eapply A23]; eauto.\n        econstructor; eauto.\n        econstructor; eauto.\n        eauto.\n      }\n      {\n        right.\n        inv A1.\n      }\n      econstructor; eauto.\n    }\n    {\n      (* promise lower / reserve *)\n      exploit reorder_promise_lower_reserve; [eapply LOCAL | eapply LOCAL0 | eauto..].\n      ii; des.\n      eapply IHn with (e := Thread.mk lang st lc' sc1 mem')\n                      (te := ThreadEvent.promise loc0 from0 to0 (Message.concrete val released)\n                                                 (Memory.op_kind_lower msg1)) in A23; eauto.\n      des.\n      {\n        left.\n        eexists.\n        split.\n        eapply Relation_Operators.rt1n_trans; [idtac | eapply A23]; eauto.\n        econstructor; eauto.\n        econstructor; eauto.\n        eauto.\n      }\n      {\n        right.\n        do 7 eexists.\n        split.\n        eapply Relation_Operators.rt1n_trans; [idtac | eapply A23]; eauto.\n        econstructor; eauto.\n        econstructor; eauto.\n        split.\n        eauto.\n        split; eauto.\n      }\n      econstructor; eauto.\n    }\n    {\n      (* promise reserve: contradiction *)\n      destruct kind; ss.\n      clear - LOCAL.\n      inv LOCAL.\n      inv PROMISE.\n      des; ss.\n      inv LOCAL.\n      inv PROMISE; ss.\n      des; ss; subst.\n      inv PROMISES.\n      inv LOWER.\n      clear - MSG_LE.\n      inv MSG_LE.\n    }\nQed.\n\nLemma reorder_read_reservation\n      lc1 mem1 loc to val released ord lc2 lo\n      loc2 from2 to2 lc3 mem3\n      (READ: Local.read_step lc1 mem1 loc to val released ord lc2 lo)\n      (PROMISE: Local.promise_step lc2 mem1 loc2 from2 to2 Message.reserve lc3 mem3 Memory.op_kind_add):\n  exists lc',\n    Local.promise_step lc1 mem1 loc2 from2 to2 Message.reserve lc' mem3 Memory.op_kind_add /\\\n    Local.read_step lc' mem3 loc to val released ord lc3 lo.\nProof.\n  inv READ; inv PROMISE; ss.\n  inv PROMISE0.\n  destruct lc1; ss.\n  eexists.\n  split.\n  econstructor; eauto.\n  econstructor; eauto.\n  eapply Memory.add_get1; eauto.\nQed.\n\nLemma reorder_read_reserve_steps:\n  forall n lang st\n    lc1 mem1 loc to val released ord lo\n    sc2 lc2 lc2' mem2 sc2'\n    (READ: Local.read_step lc1 mem1 loc to val released ord lc2 lo)\n    (RSVs: rtcn (Thread.reserve_step lo) n (Thread.mk lang st lc2 sc2 mem1) (Thread.mk lang st lc2' sc2' mem2)),\n  exists lc',\n    rtc (Thread.reserve_step lo) (Thread.mk lang st lc1 sc2 mem1) (Thread.mk lang st lc' sc2' mem2) /\\\n    Local.read_step lc' mem2 loc to val released ord lc2' lo.\nProof.\n  induction n; ii.\n  - inv RSVs.\n    eexists. split; eauto.\n  - inv RSVs.\n    inv A12. inv STEP.\n    eapply reorder_read_reservation in READ; eauto.\n    des.\n    eapply IHn in A23; eauto.\n    des; eauto.\n    eexists.\n    split; [idtac | eapply A0].\n    eapply Relation_Operators.rt1n_trans; [idtac | eapply A23]; eauto.\n    econstructor; eauto.\n    econstructor; eauto.\nQed.\n\nLemma reorder_write_reserve\n      lc1 sc1 mem1 loc1 from1 to1 val releasedr releasedw ord\n      lc2 sc2 mem2 kind lo\n      loc2 from2 to2 lc3 mem3\n      (WRITE: Local.write_step lc1 sc1 mem1 loc1 from1 to1 val releasedr releasedw ord lc2 sc2 mem2 kind lo)\n      (RSV: Local.promise_step lc2 mem2 loc2 from2 to2 Message.reserve lc3 mem3 Memory.op_kind_add):\n  (exists lc' mem',\n      Local.promise_step lc1 mem1 loc2 from2 to2 Message.reserve lc' mem' Memory.op_kind_add /\\\n      Local.write_step lc' sc1 mem' loc1 from1 to1 val releasedr releasedw ord lc3 sc2 mem3 kind lo) \\/\n  (loc1 = loc2 /\\ to1 = from2 /\\ kind = Memory.op_kind_add).\nProof.\n  inv WRITE; inv RSV; ss.\n  inv WRITE0; inv PROMISE.\n  inv PROMISE0.\n  - (* add *)\n    destruct (classic (loc1 = loc2)); subst.\n    {\n      destruct (Time.le_lt_dec to2 from1).\n      {  \n        exploit MemoryReorder.remove_add_disjts; [eapply REMOVE | eapply PROMISES | eauto..].\n        ii. des. rename mem1' into promises1'.\n        exploit MemoryReorder.add_add; [eapply PROMISES0 | eapply x0 | eauto..].\n        ii. des. rename mem1' into promises'.\n        exploit MemoryReorder.add_add; [eapply MEM0 | eapply MEM | eauto..].\n        ii. des. \n        left.\n        do 2 eexists. split. \n        econstructor.\n        econstructor. \n        eapply ADD1.\n        eapply ADD0.\n        ss.\n        ii; ss.\n        ss.\n        ss.\n        econstructor; eauto; ss.\n        econstructor.\n        econstructor.\n        eapply ADD2.\n        eapply ADD3.\n        ss. \n        ii. inv MSG.\n        assert(Time.lt to2 to1).\n        {\n          clear - l ADD3.\n          inv ADD3.\n          inv ADD.\n          eapply DenseOrderFacts.le_lt_lt; eauto.\n        }\n        assert(Time.lt to2 to').\n        { \n          eapply Memory.get_ts in GET.\n          clear - GET H. des; subst; ss.\n          eapply Time.Time.lt_strorder_obligation_2; eauto.\n        }\n        exploit Memory.add_o; [eapply ADD0 | eauto..].\n        instantiate (2 := loc2); instantiate (1 := to').\n        des_if; ss.\n        des; subst.\n        eapply Time.Time.lt_strorder_obligation_1 in H0; ss.\n        ii.\n        rewrite x2 in GET.\n        eapply ATTACH0 in GET; ss.\n        ss.\n        i.\n        eapply RELEASE in H.\n        eapply reserve_non_synch_loc; eauto.\n      }\n      {\n        assert(Time.le to1 from2).\n        {  \n          destruct (Time.le_lt_dec to1 from2); eauto.\n          clear - MEM0 MEM l l0.\n          inv MEM.\n          inv ADD.\n          dup MEM0.\n          eapply Memory.add_get0 in MEM1; des.\n          unfold Memory.get in GET0.\n          unfold Cell.get in GET0.\n          eapply DISJOINT in GET0.\n          unfold Interval.disjoint in GET0.\n          destruct (Time.le_lt_dec to1 to2).\n          specialize (GET0 to1).\n          exploit GET0; ss.\n          inv MEM0.\n          inv ADD.\n          econstructor; eauto; ss.\n          eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1; eauto.\n          specialize (GET0 to2).\n          exploit GET0; ss.\n          econstructor; ss.\n          eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1; eauto.\n          econstructor; ss.\n          eapply Time.le_lteq; ss; eauto.\n        }\n        destruct (classic (to1 = from2)); subst.\n        right.\n        eapply Memory.add_get0 in MEM0; des; eauto. \n        exploit MemoryReorder.remove_add_disjts; [eapply REMOVE | eapply PROMISES | eauto..].\n        ii. des. rename mem1' into promises1'.\n        exploit MemoryReorder.add_add; [eapply PROMISES0 | eapply x0 | eauto..].\n        ii. des. rename mem1' into promises'.\n        exploit MemoryReorder.add_add; [eapply MEM0 | eapply MEM | eauto..].\n        ii. des.\n        left.\n        do 2 eexists.\n        split.\n        econstructor.\n        econstructor.\n        eapply ADD1.\n        eapply ADD0.\n        ss.\n        ii; ss.\n        ss.\n        ss.\n        econstructor; eauto.\n        econstructor; ss.\n        econstructor.\n        eapply ADD2.\n        eapply ADD3.\n        ss.\n        ii.\n        inv MSG.\n        assert(to' <> to2).\n        {\n          intro; subst.\n          eapply Memory.add_get0 in ADD0; des.\n          rewrite GET1 in GET; inv GET; ss.\n        }\n        exploit Memory.add_o; [eapply ADD0 | eauto..].\n        instantiate(2 := loc2); instantiate(1 := to'); eauto.\n        des_if; ss; subst.\n        des; subst; ss.\n        ii.\n        rewrite x2 in GET.\n        eauto.\n        ss.\n        ss; i.\n        eapply RELEASE in H1.\n        eapply reserve_non_synch_loc; eauto.\n      }\n    }\n    {\n      exploit MemoryReorder.remove_add_disjloc; [eapply REMOVE | eapply PROMISES | eauto..].\n      ii; des. rename mem1' into promises1'.\n      exploit MemoryReorder.add_add; [eapply PROMISES0 | eapply x0 | eauto..].\n      ii; des.\n      exploit MemoryReorder.add_add; [eapply MEM0 | eapply MEM | eauto..].\n      ii; des.\n      left.\n      do 2 eexists.\n      split.\n      econstructor.\n      econstructor.\n      eapply ADD1.\n      eapply ADD0.\n      ss.\n      ii; ss.\n      ss.\n      ss.\n      econstructor; eauto.\n      econstructor.\n      econstructor.\n      eapply ADD2.\n      eapply ADD3.\n      ss.\n      ii.\n      inv MSG.  \n      exploit Memory.add_o; [eapply ADD0 | eauto..].\n      instantiate (2 := loc1); instantiate (1 := to').\n      des_if; ss.\n      des; ss.\n      ii.\n      rewrite x2 in GET.\n      eauto.\n      ss.\n      i; ss.\n      eapply RELEASE in H0.\n      eapply reserve_non_synch_loc; eauto.\n    }\n  - (* split *)\n    des; subst; ss.\n    inv RESERVE.\n    destruct (classic (loc1 = loc2)); subst.\n    { \n      destruct (Time.le_lt_dec to2 from1).\n      {  \n        exploit MemoryReorder.remove_add_disjts; [eapply REMOVE | eapply PROMISES | eauto..].\n        ii. des. rename mem1' into promises1'.\n        exploit MemoryReorder.split_add; [eapply PROMISES0 | eapply x0 | eauto..].\n        ii. des. rename mem1' into promises'.\n        exploit MemoryReorder.split_add; [eapply MEM0 | eapply MEM | eauto..].\n        ii. des. \n        left.\n        do 2 eexists. split. \n        econstructor.\n        econstructor. \n        eapply ADD1.\n        eapply ADD0.\n        ss.\n        ii; ss.\n        ss.\n        ss.\n        econstructor; eauto; ss.\n        econstructor.\n        econstructor.\n        eapply SPLIT2.\n        eapply SPLIT0.\n        ss.\n        do 2 eexists; eauto.\n        do 2 eexists; eauto.\n        eapply x1.\n        i.\n        eapply RELEASE in H.\n        eapply reserve_non_synch_loc; eauto.\n      }\n      { \n        assert(Time.lt to1 from2).\n        {\n          assert(Time.lt to1 ts3).\n          {\n            inv MEM0.\n            inv SPLIT; eauto.\n          }\n          destruct (Time.le_lt_dec ts3 from2); eauto.\n          eapply DenseOrderFacts.lt_le_lt; eauto.\n          inv MEM.\n          inv ADD.\n          eapply Memory.split_get0 in MEM0; des.\n          destruct (Time.le_lt_dec ts3 to2).\n          unfold Memory.get in GET2.\n          unfold Cell.get in GET2.\n          eapply DISJOINT in GET2.\n          unfold Interval.disjoint in GET2.\n          specialize (GET2 ts3).\n          exploit GET2.\n          econstructor; eauto.\n          econstructor; ss; eauto.\n          eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1; eauto.\n          ii; ss.\n          destruct (Time.le_lt_dec to2 to1). \n          unfold Memory.get in GET1.\n          unfold Cell.get in GET1.\n          eapply DISJOINT in GET1.\n          unfold Interval.disjoint in GET1.\n          specialize (GET1 to2).\n          exploit GET1.\n          econstructor; eauto; ss.\n          eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1; eauto.\n          econstructor; ss; eauto.\n          ii; ss. \n          unfold Memory.get in GET2.\n          unfold Cell.get in GET2.\n          eapply DISJOINT in GET2.\n          unfold Interval.disjoint in GET2.\n          specialize (GET2 to2).\n          exploit GET2.\n          econstructor; eauto; ss.\n          eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1; eauto.\n          econstructor; ss; eauto.\n          eapply Time.le_lteq; ss; eauto.          \n          ii; ss.\n        } \n        exploit MemoryReorder.remove_add_disjts; [eapply REMOVE | eapply PROMISES | eauto..].\n        right. eapply Time.le_lteq; eauto.\n        ii; des. \n        exploit MemoryReorder.split_add; [eapply PROMISES0 | eapply x0 | eauto..].\n        ii; des.\n        exploit MemoryReorder.split_add; [eapply MEM0 | eapply MEM | eauto..].\n        ii; des.\n        left.\n        do 2 eexists.\n        split.\n        econstructor.\n        econstructor.\n        eapply ADD1. eapply ADD0.\n        ss.\n        ii; ss.\n        ss.\n        ss.\n        econstructor; eauto.\n        econstructor.\n        econstructor.\n        eapply SPLIT2.\n        eapply SPLIT0.\n        ss.\n        do 2 eexists; eauto.\n        do 2 eexists; eauto.\n        eauto.\n        i; ss.\n        eapply RELEASE in H0.\n        eapply reserve_non_synch_loc; eauto.\n      }\n    }\n    {\n      exploit MemoryReorder.remove_add_disjloc; [eapply REMOVE | eapply PROMISES | eauto..].\n      ii; des. rename mem1' into promises1'.\n      exploit MemoryReorder.split_add; [eapply PROMISES0 | eapply x0 | eauto..].\n      ii; des.\n      exploit MemoryReorder.split_add; [eapply MEM0 | eapply MEM | eauto..].\n      ii; des.\n      left.\n      do 2 eexists.\n      split.\n      econstructor.\n      econstructor.\n      eapply ADD1.\n      eapply ADD0.\n      ss.\n      ii; ss.\n      ss.\n      ss.\n      econstructor; eauto.\n      econstructor.\n      econstructor.\n      eapply SPLIT2.\n      eapply SPLIT0.\n      ss.\n      do 2 eexists; eauto.\n      do 2 eexists; eauto.\n      eauto.\n      i.\n      eapply RELEASE in H0.\n      eapply reserve_non_synch_loc; eauto.\n    }\n  - (* lower *)\n    des; subst.\n    destruct (classic (loc1 = loc2)); subst.\n    {\n      destruct (Time.le_lt_dec to2 from1).\n      {  \n        exploit MemoryReorder.remove_add_disjts; [eapply REMOVE | eapply PROMISES | eauto..].\n        ii. des. rename mem1' into promises1'.\n        exploit MemoryReorder.lower_add; [eapply PROMISES0 | eapply x0 | eauto..].\n        ii. des. rename mem1' into promises'.\n        exploit MemoryReorder.lower_add; [eapply MEM0 | eapply MEM | eauto..].\n        ii. des. \n        left.\n        do 2 eexists. split. \n        econstructor.\n        econstructor. \n        eapply ADD1.\n        eapply ADD0.\n        ss.\n        ii; ss.\n        ss.\n        ss.\n        econstructor; eauto; ss.\n        i. eapply RELEASE in H.\n        eapply reserve_non_synch_loc; eauto.\n      }\n      { \n        assert(Time.le to1 from2).\n        {  \n          destruct (Time.le_lt_dec to1 from2); eauto.\n          clear - MEM0 MEM l l0.\n          inv MEM.\n          inv ADD.\n          dup MEM0.\n          eapply Memory.lower_get0 in MEM1; des.\n          unfold Memory.get in GET0.\n          unfold Cell.get in GET0.\n          eapply DISJOINT in GET0.\n          unfold Interval.disjoint in GET0.\n          destruct (Time.le_lt_dec to2 to1).\n          specialize (GET0 to2).\n          exploit GET0; ss.\n          econstructor; ss; eauto.\n          eapply Time.le_lteq; ss; eauto.\n          eapply Memory.get_ts in GET.\n          specialize (GET0 to1).\n          exploit GET0.\n          econstructor; ss; eauto.\n          eapply Time.le_lteq; ss; eauto.\n          des; subst.\n          cut(Time.le Time.bot from2); ii.\n          eapply TimeFacts.lt_le_lt in l0; eauto.\n          eapply DenseOrder.DenseOrder.lt_strorder_obligation_1 in l0; ss.\n          eapply Time.bot_spec.\n          econstructor; ss; eauto.\n          eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1; eauto.\n          ii; ss.\n        }\n        exploit MemoryReorder.remove_add_disjts; [eapply REMOVE | eapply PROMISES | eauto..].\n        ii. des. rename mem1' into promises1'.\n        exploit MemoryReorder.lower_add; [eapply PROMISES0 | eapply x0 | eauto..].\n        ii. des. rename mem1' into promises'.\n        exploit MemoryReorder.lower_add; [eapply MEM0 | eapply MEM | eauto..].\n        ii. des.\n        left.\n        do 2 eexists.\n        split.\n        econstructor.\n        econstructor.\n        eapply ADD1.\n        eapply ADD0.\n        ss.\n        ii; ss.\n        ss.\n        ss.\n        econstructor; eauto.\n        ss; i.\n        eapply RELEASE in H0.\n        eapply reserve_non_synch_loc; eauto.\n      }\n    }\n    {\n      exploit MemoryReorder.remove_add_disjloc; [eapply REMOVE | eapply PROMISES | eauto..].\n      ii; des. rename mem1' into promises1'.\n      exploit MemoryReorder.lower_add; [eapply PROMISES0 | eapply x0 | eauto..].\n      ii; des.\n      exploit MemoryReorder.lower_add; [eapply MEM0 | eapply MEM | eauto..].\n      ii; des.\n      left.\n      do 2 eexists.\n      split.\n      econstructor.\n      econstructor.\n      eapply ADD1.\n      eapply ADD0.\n      ss.\n      ii; ss.\n      ss.\n      ss.\n      econstructor; eauto.\n      i; ss.\n      eapply RELEASE in H0.\n      eapply reserve_non_synch_loc; eauto.\n    }\n  - (* reserve contradiction *)\n    ss.\nQed.\n\nLemma reorder_write_reserve_steps_attached:\n  forall n lo\n    lc1 sc1 mem1 loc from ts val releasedr releasedw ord\n    lc2 sc2 to mem2 lc3 mem3 lang st st' e''\n    (WRITE: Local.write_step lc1 sc1 mem1 loc from ts val releasedr releasedw ord lc2 sc2 mem2\n                             Memory.op_kind_add lo)\n    (RSV: Local.promise_step lc2 mem2 loc ts to Message.reserve lc3 mem3 Memory.op_kind_add)\n    (RSVs: rtcn (Thread.reserve_step lo) n (Thread.mk lang st lc3 sc2 mem3) e''),    \n  exists lc' sc' mem' lc'' sc'' mem'',\n    rtc (Thread.reserve_step lo) (Thread.mk lang st' lc1 sc1 mem1) (Thread.mk lang st' lc' sc' mem') /\\\n    Local.write_step lc' sc' mem' loc from ts val releasedr releasedw ord lc'' sc'' mem''\n                     Memory.op_kind_add lo /\\\n    Local.promise_step lc'' mem'' loc ts to Message.reserve\n                       (Thread.local e'') (Thread.memory e'') Memory.op_kind_add /\\ (Thread.sc e'' = sc1).\nProof.\n  induction n; intros.\n  - inv RSVs; eauto.\n    assert(SC: sc1 = sc2). { inv WRITE; ss. }\n    do 6 eexists.\n    split; eauto.\n  - inv RSVs.\n    assert(SC: sc1 = sc2). { inv WRITE; ss. }\n    inv A12.\n    inv STEP.\n    destruct (classic (loc = loc0)); subst.\n    {\n      assert(Time.le to0 from \\/ Time.le to from0).\n      {\n        clear - RSV WRITE LOCAL.\n        inv RSV; inv WRITE; inv LOCAL; ss.\n        inv PROMISE; inv WRITE0; inv PROMISE0.\n        inv PROMISE; ss.\n        assert(Time.lt ts to).\n        {\n          inv MEM.\n          inv ADD; eauto.\n        }\n        exploit add_succeed_wf; [eapply MEM0 | eauto..].\n        ii; des. \n        eapply Memory.add_get0 in MEM1; eauto; des.\n        eapply Memory.add_get1 in GET0; eauto.         \n        eapply Memory.add_get0 in MEM; eauto; des.\n        eapply DISJOINT in GET0.\n        eapply DISJOINT in GET2.\n        clear - GET2 GET0 TO1 H.\n        destruct(Time.le_lt_dec to0 from); eauto.\n        destruct(Time.le_lt_dec to from0); eauto.\n        destruct(Time.le_lt_dec to0 ts).\n        {\n          unfold Interval.disjoint in GET0.\n          specialize (GET0 to0).\n          exploit GET0.\n          econstructor; ss; eauto.\n          eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1; eauto.\n          econstructor; ss; eauto.\n          ii; ss.\n        }\n        {\n          destruct(Time.le_lt_dec to0 to).\n          { \n            unfold Interval.disjoint in GET2.\n            specialize (GET2 to0).\n            exploit GET2. \n            econstructor; ss; eauto.\n            eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1; eauto.\n            econstructor; ss; eauto.\n            ii; ss.\n          }\n          {\n            \n            unfold Interval.disjoint in GET2.\n            specialize (GET2 to).\n            exploit GET2.\n            econstructor; ss; eauto.\n            eapply Time.le_lteq; ss; eauto.\n            econstructor; ss; eauto.\n            eapply DenseOrder.DenseOrder_le_PreOrder_obligation_1; eauto.\n            ii; ss.\n          }\n        }\n      }\n      exploit reorder_promise_reserve_promise; [eapply RSV | eapply LOCAL | eauto..].\n      ii; des; subst; ss.\n      exploit reorder_write_reserve; [eapply WRITE | eapply STEP1 | eauto..]. \n      ii; des.\n      {\n        eapply IHn in A23.\n        2: eapply x1.\n        2: eapply STEP2.\n        des.\n        do 6 eexists.\n        split.\n        eapply Relation_Operators.rt1n_trans; [idtac | eapply A23].\n        econstructor; eauto.\n        econstructor; eauto.\n        split; eauto.\n      }\n      {\n        assert(Time.lt from0 to0).\n        {\n          clear - LOCAL.\n          inv LOCAL. inv PROMISE.\n          inv MEM. inv ADD; eauto.\n        }\n        assert(Time.lt from ts).\n        {\n          clear - WRITE.\n          inv WRITE. inv WRITE0. inv PROMISE.\n          inv MEM. inv ADD; eauto.\n        }\n        subst. clear - H H1 H0.\n        eapply DenseOrderFacts.le_lt_lt in H; eauto.\n        eapply DenseOrder.DenseOrder.lt_strorder_obligation_2 in H; eauto.\n        eapply H in H0; eauto.\n        eapply DenseOrder.DenseOrder.lt_strorder_obligation_1 in H0; ss.\n      }\n\n      exploit reorder_write_reserve; [eapply WRITE | eapply STEP1 | eauto..]. \n      ii; des.\n      {\n        eapply IHn in A23.\n        2: eapply x1.\n        2: eapply STEP2.\n        des.\n        do 6 eexists.\n        split.\n        eapply Relation_Operators.rt1n_trans; [idtac | eapply A23].\n        econstructor; eauto.\n        econstructor; eauto.\n        split; eauto.\n      }\n      {\n        assert(Time.lt ts to).\n        {\n          clear - STEP2.\n          inv STEP2. inv PROMISE. inv MEM.\n          inv ADD; eauto.\n        }\n        assert(Time.lt ts from0).\n        {\n          eapply DenseOrderFacts.lt_le_lt; eauto.\n        }\n        subst.\n        eapply DenseOrder.DenseOrder.lt_strorder_obligation_1 in H1; ss.\n      }\n    }\n    {\n      exploit reorder_promise_reserve_promise; [eapply RSV | eapply LOCAL | eauto..].\n      ii; des; subst; ss.\n      exploit reorder_write_reserve; [eapply WRITE | eapply STEP1 | eauto..].\n      ii; des; subst; ss.\n      eapply IHn in A23.\n      2: eapply x1.\n      2: eapply STEP2.\n      des.\n      do 6 eexists.\n      split.\n      eapply Relation_Operators.rt1n_trans; [idtac | eapply A23].\n      econstructor; eauto.\n      econstructor; eauto.\n      split; eauto.\n    }\nQed.\n\nLemma reorder_fence_reserve\n      lc1 sc1 mem1 ordr ordw lc2 sc2\n      loc2 from2 to2 lc3 mem3\n      (FENCE: Local.fence_step lc1 sc1 ordr ordw lc2 sc2)\n      (NOSC: ordw <> Ordering.seqcst)\n      (PROMISE: Local.promise_step lc2 mem1 loc2 from2 to2 Message.reserve lc3 mem3 Memory.op_kind_add):\n  exists lc',\n    Local.promise_step lc1 mem1 loc2 from2 to2 Message.reserve lc' mem3 Memory.op_kind_add /\\\n    Local.fence_step lc' sc1 ordr ordw lc3 sc2.\nProof.\n  inv FENCE.\n  inv PROMISE; ss.\n  eexists.\n  split.\n  econstructor; eauto.\n  econstructor; eauto; ss.\n  intro.\n  eapply RELEASE in H.\n  inv PROMISE0.\n  eapply reserve_non_synch; eauto.\nQed. \n  \nLemma reorder_program_step_reserve_steps:\n  forall n lang (e e' e'': Thread.t lang) te lo\n    (PROG: Thread.program_step te lo e e')\n    (RSVs: rtcn (Thread.reserve_step lo) n e' e'')\n    (NOSC: ~(exists ordr, te = ThreadEvent.fence ordr Ordering.seqcst))\n    (NO_OUT: ThreadEvent.get_machine_event te = MachineEvent.silent),\n    (exists e0, rtc (Thread.reserve_step lo) e e0 /\\ Thread.program_step te lo e0 e'') \\/\n    (exists e0 e1 loc to ts from val released ordw,\n        rtc (Thread.reserve_step lo) e e0 /\\\n        Thread.program_step te lo e0 e1 /\\ te = ThreadEvent.write loc from ts val released ordw /\\\n        Thread.promise_step false (ThreadEvent.promise loc ts to Message.reserve Memory.op_kind_add) e1 e'') \\/\n    (exists e0 e1 loc to ts from valr valw releasedr releasedw ordr ordw,\n        rtc (Thread.reserve_step lo) e e0 /\\\n        Thread.program_step te lo e0 e1 /\\\n        te = ThreadEvent.update loc from ts valr valw releasedr releasedw ordr ordw /\\\n        Thread.promise_step false (ThreadEvent.promise loc ts to Message.reserve Memory.op_kind_add) e1 e'').\nProof.\n  induction n; intros.\n  - inv RSVs; eauto.\n  - inv RSVs.\n    inv PROG; ss.\n    inv LOCAL.\n    {\n      (* silent *)\n      left.\n      inv A12.\n      inv STEP.  \n      eapply IHn with (e := Thread.mk lang st1 lc0 sc2 mem0)\n                      (te := ThreadEvent.silent) in A23; eauto.\n      des.\n      {\n        eexists.\n        split.\n        eapply Relation_Operators.rt1n_trans; [idtac | eapply A23]; eauto.\n        econstructor; eauto.\n        econstructor; eauto.\n        ss.\n      }\n      ss. ss.      \n    }\n    {\n      (* read *)\n      inv A12.\n      inv STEP.\n      exploit reorder_read_reservation; [eapply LOCAL0 | eapply LOCAL | eauto..].\n      ii; des.\n      eapply IHn with (e := Thread.mk lang st1 lc' sc2 mem0)\n                      (te := ThreadEvent.read loc ts val released ord) in A23; eauto.\n      des.\n      {\n        left.\n        eexists.\n        split.\n        eapply Relation_Operators.rt1n_trans; [idtac | eapply A23]; eauto.\n        econstructor; eauto.\n        econstructor; eauto.\n        ss.\n      }\n      ss. ss.\n    }\n    {\n      (* write *)\n      inv A12.\n      inv STEP.\n      exploit reorder_write_reserve; [eapply LOCAL0 | eapply LOCAL | eauto..]. \n      ii; des.\n      { \n        eapply IHn with (e := Thread.mk lang st1 lc' sc1 mem')\n                        (te := ThreadEvent.write loc from to val released ord) in A23; eauto. \n        des. \n        {\n          left.\n          eexists.\n          split.\n          eapply Relation_Operators.rt1n_trans; [idtac | eapply A23]; eauto.\n          econstructor; eauto.\n          econstructor; eauto.\n          ss.\n        }\n        { \n          right. left.\n          ss.\n          do 9 eexists.\n          split.\n          eapply Relation_Operators.rt1n_trans; [idtac | eapply A23]; eauto.\n          econstructor; eauto.\n          econstructor; eauto.\n          split; eauto.\n        }\n        ss.\n      }\n      {\n        subst.\n        destruct e''.\n        dup A23.\n        eapply rtcn_rtc in A0.\n        eapply reserve_sc_nochange in A0; ss; des; subst.\n        eapply reorder_write_reserve_steps_attached with (st' := st1) in A23; eauto.\n        ii; des.\n        right. left.\n        do 9 eexists.\n        split; eauto.\n        split; eauto.\n        split; eauto.\n        instantiate (1 := to0).\n        ss; subst.\n        assert(sc' = sc'').\n        {\n          clear - A0.\n          inv A0; eauto.\n        }\n        subst. \n        eapply reserve_sc_nochange in A23. ss; des; subst.\n        econstructor; eauto.\n      }\n    }\n    {\n      (* update *)\n      inv A12. inv STEP.\n      exploit reorder_write_reserve; [eapply LOCAL2 | eapply LOCAL | eauto..].\n      ii; des.\n      {\n        (* not attach *)\n        exploit reorder_read_reservation; [eapply LOCAL1 | eapply x0 | eauto..].\n        ii; des.\n        eapply IHn with (e := Thread.mk lang st1 lc'0 sc1 mem') in A23; eauto.\n        des.\n        {\n          left.\n          eexists.\n          split.\n          eapply Relation_Operators.rt1n_trans; [idtac | eapply A23 | eauto..].\n          econstructor; eauto.\n          econstructor; eauto.\n          eauto.\n        }\n        {\n          ss.\n        }\n        {\n          inv A1.\n          right; right.\n          do 12 eexists.\n          split.\n          eapply Relation_Operators.rt1n_trans; [idtac | eapply A23 | eauto..].\n          econstructor; eauto.\n          econstructor; eauto.\n          eauto.\n        }\n      }\n      {\n        (* attach *)\n        subst.\n        exploit reorder_write_reserve_steps_attached; [eapply LOCAL2 | eapply LOCAL | eauto..].\n        instantiate (1 := st1). ii; des.\n        eapply rtc_rtcn in x0. destruct x0.\n        exploit reorder_read_reserve_steps; [eapply LOCAL1 | eapply H | eauto..].\n        ii; des.\n        right; right.\n        eapply rtcn_rtc in A23.\n        destruct e''; ss; subst.\n        eapply reserve_sc_nochange in A23.\n        ss; des; subst.\n        do 12 eexists.\n        split; [eapply x4 | eauto..].\n        split; eauto. \n        split; eauto. \n        instantiate (1 := to). \n        eapply reserve_sc_nochange in x4; ss; des; subst.\n        inv x1; ss.\n      }\n    }\n    {\n      (* fence *)\n      inv A12. inv STEP. \n      exploit reorder_fence_reserve; [eapply LOCAL0 | idtac | eapply LOCAL | eauto..].\n      clear - NOSC; intro; subst.\n      contradiction NOSC; eauto.\n      ii; des.\n      eapply IHn with (e := Thread.mk lang st1 lc' sc1 mem0) in A23; eauto.\n      des.\n      {\n        left. \n        eexists. split. \n        eapply Relation_Operators.rt1n_trans; [idtac | eapply A23 | eauto..].\n        econstructor; eauto.\n        econstructor; eauto.\n        eauto.\n      }\n      ss. ss.\n    }\n    {\n      (* output *)\n      ss.\n    }\nQed.\n\nLemma reorder_lower_step_reserve_steps:\n  forall n lang (e e' e'': Thread.t lang) te lo\n    (PROG: Thread.promise_step true te e e')\n    (RSVs: rtcn (Thread.reserve_step lo) n e' e'')\n    (NOCCL: ~ThreadEvent.is_cancel te),\n    (exists e0, rtc (Thread.reserve_step lo) e e0 /\\ Thread.promise_step true te e0 e'').\nProof.\n  induction n; intros.\n  - inv RSVs; eauto.\n  - inv RSVs. \n    cut (rtcn (Thread.reserve_step lo) 1%nat e' a2). i.\n    exploit reorder_promise_step_reserve_steps; [eapply PROG | eapply H | eauto ..].\n    inv PROG.\n    destruct kind; ss.\n    destruct msg1; ss.\n    destruct msg; ss.\n    destruct msg; ss. inv LOCAL. inv PROMISE. ss.\n    ii.\n    des; ss. \n    eapply IHn in x1; eauto. des.\n    eexists. split. \n    eapply Basic.rtc_PreOrder_obligation_2; [eapply x0 | eapply x1].\n    eauto.\n    subst.\n    inv PROG; ss.\n    econs; eauto.\nQed.\n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/promising/prop/ReorderReserve.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3451052776934245, "lm_q1q2_score": 0.21227006518372507}}
{"text": "(****************************************************************************)\n(* Copyright (c) Facebook, Inc. and its affiliates.                         *)\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(****************************************************************************)\nFrom mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq fintype path choice.\nRequire Import Eqdep.\nFrom fcsl\nRequire Import pred prelude ordtype pcm finmap unionmap heap.\nFrom LibraChain\nRequire Import SeqFacts Chains HashSign Blocks.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(* A formalization of a block forests *)\n\n(************************************************************)\n(******************* <parameters> ***************************)\n(************************************************************)\nSection State.\n\nVariable Hash : countType.\nVariables (PublicKey: countType) (Signature: countType) (Address: hashType PublicKey).\n\nVariables (Command NodeTime: countType).\n\n(* The Block Data (w/o signatures) *)\nNotation BDataType := (BlockData Hash Signature Address Command NodeTime).\n\nVariable hashB: BDataType -> Hash.\nHypothesis inj_hashB: injective hashB.\n\nVariable verifB: Hash -> PublicKey -> Signature -> bool.\n\n(* Block Type : block data with signatures *)\nNotation BType := (BlockType inj_hashB verifB).\nNotation QC := (QuorumCert Hash Signature (Phant Address)).\n\nImplicit Type b: BDataType.\n\nParameter GenesisBlock : BType.\n\nDefinition genesis_round := (round GenesisBlock).\n\nImplicit Type (bd: BDataType).\n\nDefinition qc_of bd := (proof bd).\nDefinition qc_hash bd := (block_hash (qc_vote_data (qc_of bd))).\nDefinition qc_round bd := (block_round (qc_vote_data (qc_of bd))).\nDefinition qc_parent_hash bd := (parent_block_hash (qc_vote_data (qc_of bd))).\nDefinition qc_parent_round bd := (parent_block_round (qc_vote_data (qc_of bd))).\n\nDefinition parent b1 b2 := (hashB b1 == qc_hash b2) && (round b1 == qc_round b2) && (qc_hash b1 == qc_parent_hash b2) && (qc_round b1 == qc_parent_round b2).\nDefinition chained (bc: seq BType):= path [eta parent: rel BType] GenesisBlock bc.\n\nLemma rounds_transitive:\n  transitive (fun b1 b2 => (round b1) < (round b2)).\nProof.\nby move=> b1 b2 b3; apply ltn_trans.\nQed.\n\nLemma rounds_irreflexive:\n  irreflexive (fun b1 b2 => (round b1) < (round b2)).\nProof. by move=> b; rewrite ltnn. Qed.\n\n(************************************************************)\n(** Consensus State                                        **)\n(************************************************************)\n\nRecord ConsensusState := mkConsensusState {\n  last_vote_round: nat;\n  preferred_block_round: nat;\n}.\n\nDefinition consensusstate2nats (cs: ConsensusState) :=\n  let: mkConsensusState lvr pvr := cs in (lvr, pvr).\n\nDefinition nats2consensusstate (nats: nat * nat) :=\n  let: (lvr, pbr) := nats in mkConsensusState lvr pbr.\n\nLemma can_cs_nats: ssrfun.cancel consensusstate2nats nats2consensusstate.\nProof. by move => []. Qed.\n\nDefinition cs_eqMixin := CanEqMixin can_cs_nats.\nCanonical cs_eqType := EqType _ cs_eqMixin.\nDefinition cs_choiceMixin := CanChoiceMixin can_cs_nats.\nCanonical cs_choiceType := ChoiceType _ cs_choiceMixin.\nDefinition cs_countMixin := CanCountMixin can_cs_nats.\nCanonical cs_countType := CountType _ cs_countMixin.\n\nDefinition genesis_state := mkConsensusState genesis_round genesis_round.\n\nImplicit Type state: ConsensusState.\n\nDefinition update state (qc: QC) :=\n  let: round := (parent_block_round (qc_vote_data qc)) in\n  if (round > preferred_block_round state) then\n    mkConsensusState (last_vote_round state) (round)\n  else\n    state.\n\nLemma update_eq_lvr state qc :\n  last_vote_round (update state qc) = last_vote_round state.\nProof.\nrewrite /update.\nby case (parent_block_round (qc_vote_data qc) > preferred_block_round state).\nQed.\n\nLemma update_pbr_geq state qc :\n  preferred_block_round state <= preferred_block_round (update state qc).\nProof.\nrewrite /update.\ncase H: (parent_block_round (qc_vote_data qc) > preferred_block_round state) => //.\nby move/ltnW: H => ->.\nQed.\n\nLemma update_qc_gt state qc :\n  parent_block_round (qc_vote_data qc) <= preferred_block_round (update state qc).\nProof.\nrewrite /update; case H: (preferred_block_round state < (parent_block_round (qc_vote_data qc))) => //.\nby rewrite leqNgt H.\nQed.\n\nLemma update_pbr_P state qc:\n  reflect (preferred_block_round (update state qc) = parent_block_round (qc_vote_data qc))\n          (preferred_block_round state <= parent_block_round (qc_vote_data qc)).\nProof.\napply: (iffP idP); rewrite /update;\ncase H: (parent_block_round (qc_vote_data qc) > preferred_block_round state);\nrewrite leq_eqVlt H ?orbF ?orbT //; move/eqP=> //.\nQed.\n\nLemma update_maxn state qc:\n  update state qc =\n  mkConsensusState (last_vote_round state)\n                   (maxn (preferred_block_round state) (parent_block_round (qc_vote_data qc))).\nProof.\nrewrite /update /maxn; case: ((preferred_block_round state) < (parent_block_round (qc_vote_data qc))) => //=.\nby case state.\nQed.\n\n(************************************************************)\n(** Voting after update with the QC                        **)\n(************************************************************)\n\nDefinition votable state b :=\n  let: (rd, qcr, lvr, pbr) :=\n     ((round b), (qc_round b),\n     (last_vote_round state),\n     (preferred_block_round state)) in [&& rd > lvr & qcr >= pbr].\n\nLemma votable_updateP state b:\n  reflect (votable (update state (qc_of b)) b)\n  (votable state b && (qc_round b >= qc_parent_round b)).\nProof.\n  apply: (iffP andP); rewrite /votable update_eq_lvr.\n- rewrite /update; case (preferred_block_round state < parent_block_round (qc_vote_data (qc_of b)));\n  move=> [H1 H2]; move/andP: H1=> [-> H1] //; rewrite ltnW //.\n- move/andP => [->] //= H.\n  apply/andP; rewrite (leq_trans (update_pbr_geq _ _) H) //=.\n  by apply: (leq_trans (update_qc_gt state _)).\nQed.\n\nLemma votable_update_round_geq state b:\n  (votable (update state (qc_of b)) b) =\n  (votable state b && (qc_round b >= qc_parent_round b)).\nProof.\nby apply/(sameP idP); apply: votable_updateP.\nQed.\n\nDefinition voting_rule state (b: BDataType) :=\n  let after_update := update state (qc_of b) in\n  if votable (after_update) b then\n    let newState :=\n        mkConsensusState (round b) (preferred_block_round after_update)\n    in\n    (newState, true)\n  else (after_update, false).\n\nDefinition voted_on state b := (voting_rule state b).2.\n\nLemma voted_on_votable state b:\n  voted_on state b = votable (update state (qc_of b)) b.\nProof.\nrewrite /voted_on /voting_rule.\nby case: (votable (update state (qc_of b)) b) => //.\nQed.\n\nLemma voted_br_gt_qcr state b:\n  voted_on state b ->\n  qc_round b >= qc_parent_round b.\nProof.\nrewrite /voted_on /voting_rule.\ncase H: (votable (update state (qc_of b)) b).\n- by move/votable_updateP: H; move/andP => [_ ->].\n- by rewrite /update; case (preferred_block_round state < _).\nQed.\n\nLemma voted_pr_gt_qcr state b:\n  voted_on state b ->\n  qc_round b >= preferred_block_round state.\nProof.\nrewrite /voted_on /voting_rule.\ncase H: (votable (update state (qc_of b)) b).\n- by move/votable_updateP: H; rewrite andbC /=; move/andP=>[_]; move/andP=>[_ ->].\n- by rewrite /update; case (preferred_block_round state < _).\nQed.\n\nLemma ineq_voted_on state b:\n  (voted_on state b) = [&& (round b > last_vote_round state),\n                         (qc_round b >= preferred_block_round state) &\n                         (qc_round b >= qc_parent_round b)].\nProof.\nby rewrite voted_on_votable votable_update_round_geq /votable -andbA.\nQed.\n\n\nLemma vote_genesis_N: voted_on genesis_state GenesisBlock = false.\nProof.\nby rewrite voted_on_votable /votable update_eq_lvr /= /genesis_round ltnn.\nQed.\n\nDefinition next_state state b := (voting_rule state b).1.\n\nLemma next_state_pbr_update state b :\n  preferred_block_round (next_state state b) = preferred_block_round (update state (qc_of b)).\nProof.\nby rewrite /next_state /voting_rule; case (votable (update state (qc_of b)) b).\nQed.\n\nLemma next_state_pbr_geq state b:\n  preferred_block_round state <= preferred_block_round (next_state state b).\nProof.\nby rewrite next_state_pbr_update update_pbr_geq.\nQed.\n\nLemma next_state_lvr_voted state b :\n  reflect (last_vote_round state < last_vote_round (next_state state b)) (voted_on state b).\nProof.\nrewrite /next_state /voting_rule -voted_on_votable; apply: (iffP idP).\n- move=>H; rewrite (H)=>//=; move:H; rewrite ineq_voted_on.\n  by move/andP=>[-> _].\n- by case: (voted_on state b); rewrite // update_eq_lvr ltnn.\nQed.\n\nLemma next_state_lvr_round state b:\n  voted_on state b -> last_vote_round (next_state state b) = round b.\nProof.\nby rewrite voted_on_votable /next_state /voting_rule=>-> /=.\nQed.\n\nLemma next_state_lvr_static state b:\n  ~~ voted_on state b -> last_vote_round (next_state state b) = last_vote_round state.\nProof.\nrewrite voted_on_votable /next_state /voting_rule.\nby move/negbTE=>->; rewrite update_eq_lvr.\nQed.\n\nLemma next_state_lvr_if state b:\n  next_state state b =\n  let: pbr:= preferred_block_round (update state (qc_of b)) in\n     if (voted_on state b) then\n       mkConsensusState (round b) pbr\n     else\n       mkConsensusState (last_vote_round state) pbr.\nProof.\nrewrite /next_state /voting_rule -voted_on_votable /=; case H: (voted_on state b)=> //=.\nby rewrite update_maxn /=.\nQed.\n\nLemma next_state_lvr_leq state b:\n  last_vote_round state <= last_vote_round (next_state state b).\nProof.\ncase H: (voted_on state b).\n- by rewrite leq_eqVlt; move/next_state_lvr_voted: H=>->; rewrite orbT.\n- by rewrite /next_state /voting_rule -voted_on_votable H update_eq_lvr.\nQed.\n\nLemma next_state_maxn state b:\n  (next_state state b) =\n  let: u_pbr := (maxn (preferred_block_round state) (qc_parent_round b)) in\n  mkConsensusState\n    (if (round b >= (last_vote_round state).+1) && (qc_round b >= u_pbr) then round b else last_vote_round state)\n    u_pbr.\nProof.\nrewrite /next_state /voting_rule update_maxn.\nset pbr:= (maxn (preferred_block_round state) (qc_parent_round b)).\nrewrite /votable /=.\nby case H: ((last_vote_round state < round b) && (pbr <= qc_round b)).\nQed.\n\nLemma pbr_next_stateC state b c:\n  preferred_block_round (next_state (next_state state b) c) =\n  preferred_block_round (next_state (next_state state c) b).\nProof.\nrewrite (next_state_maxn (next_state state c) b) next_state_maxn /=.\nby rewrite !next_state_maxn /= maxnAC.\nQed.\n\nLemma voting_next_voted state b :\n  voting_rule state b = (next_state state b, voted_on state b).\nProof.\nby apply surjective_pairing.\nQed.\n\nLemma voting_next_N state b: voted_on (next_state state b) b = false.\nProof.\nrewrite voted_on_votable votable_update_round_geq /votable.\nrewrite {1}/next_state /voting_rule.\ncase H:(votable (update state (qc_of b)) b) => /=; first by rewrite ltnn.\nrewrite /votable -next_state_pbr_update in H.\nby rewrite H andFb.\nQed.\n\nLemma voting_update_progress state qc x:\n  voted_on (update state qc) x -> voted_on state x.\nProof.\nrewrite 2!ineq_voted_on update_maxn /= geq_max.\nby move/andP=>[->]; move/andP =>[H ->]; move/andP: H=>[-> _].\nQed.\n\nLemma voting_progress state b x:\n  voted_on (next_state state b) x -> voted_on state x.\nProof.\nrewrite 2!ineq_voted_on; move/andP=> [Hlvr]; move/andP=> [Hpbr Hbr].\nrewrite (leq_ltn_trans (next_state_lvr_leq _ _) Hlvr).\nby rewrite (leq_trans (next_state_pbr_geq _ _) Hpbr) /=.\nQed.\n\nLemma voting_gt state b x:\n  voted_on (next_state state b) x ->\n  ~~ voted_on state b || (round b < round x).\nProof.\nmove=> H; move: (H); rewrite ineq_voted_on; move/andP=> [Hlvr _].\ncase I: (voted_on state b)=> //.\nby rewrite (next_state_lvr_round I) in Hlvr.\nQed.\n\nLemma non_voted_on_update state b x:\n  ~~ voted_on state b ->\n  voted_on (next_state state b) x = voted_on (update state (qc_of b)) x.\nProof.\nrewrite next_state_lvr_if; move/negbTE=>->.\nby rewrite update_maxn.\nQed.\n\nLemma pbr_update_next state b x:\n  preferred_block_round (update (next_state state b) (qc_of x)) =\n  preferred_block_round (update (update state (qc_of b)) (qc_of x)).\nProof.\nby rewrite next_state_maxn !update_maxn /=.\nQed.\n\nLemma voted_next_update state b x:\n  voted_on (next_state state b) x ->\n  voted_on (update state (qc_of b)) x.\nProof.\nmove=> H; move/voting_progress: (H); rewrite ineq_voted_on; move/andP=> [Hs _].\nmove: H; rewrite ineq_voted_on next_state_pbr_update.\nmove/andP=>[Hlvr]; move/andP=> [H1 H2].\nby rewrite ineq_voted_on update_eq_lvr Hs H1 H2.\nQed.\n\nLemma next_state_updateC state qc x:\n  voted_on (update state qc) x ->\n  next_state (update state (qc)) x =\n  update (next_state state x) qc.\nProof.\nmove => H; rewrite /next_state /voting_rule -2!voted_on_votable H.\nby move/voting_update_progress: H=> -> /=; rewrite !update_maxn /= maxnAC.\nQed.\n\nLemma voted_on_maxn state b:\n  (voted_on state b) =\n  (round b >=  (last_vote_round state).+1) && (qc_round b >= maxn (preferred_block_round state)\n               (qc_parent_round b)).\nProof.\nby rewrite !geq_max  ineq_voted_on.\nQed.\n\n(************************************************************)\n(** Voting in Sequence                                     **)\n(************************************************************)\n\nImplicit Type bseq: seq BDataType.\n\n(* node_processing is a slight modification on a scanleft of the voting rules\nover a seq of block *)\nFixpoint process_aux state bseq res :=\n  if bseq is x::s then\n    let: (new_state, vote) := (voting_rule state x) in\n    process_aux new_state s ((state, vote) :: res)\n  else\n    (state, rev res).\n\nDefinition node_processing state bseq := process_aux state bseq [::].\n\nLemma size_process_aux state bseq res: size (process_aux state bseq res).2 = size bseq + size res.\nProof.\nelim:bseq res state => [|x xs IHs] res state.\n- by rewrite size_rev add0n.\n- by rewrite /= voting_next_voted IHs /= addSnnS.\nQed.\n\nLemma size_processing state bseq : size (node_processing state bseq).2 = size bseq.\nProof.\nby rewrite /node_processing size_process_aux addn0.\nQed.\n\nLemma processing_aux_state_res_irrel state bseq rs1 rs2:\n  (process_aux state bseq rs1).1 = (process_aux state bseq rs2).1.\nProof.\nelim: bseq state rs1 rs2 => [|b bs IHb] state rs1 rs2 //=; rewrite voting_next_voted.\nby apply:IHb.\nQed.\n\nLemma processing_aux_rcons state bseq r rs:\n  (process_aux state bseq (rcons rs r)).2 =\n  r :: (process_aux state bseq rs).2.\nProof.\nelim: bseq r rs state =>[| b bs IHb] r rs state => /=.\n- by rewrite rev_rcons.\n- by rewrite voting_next_voted -IHb -rcons_cons.\nQed.\n\nLemma processing_aux_rev state bseq res:\n  (process_aux state bseq res).2 =\n  rev res ++ (process_aux state bseq [::]).2.\nProof.\nmove: res bseq state; apply: last_ind=> [|rs r IHr] bseq state.\n- by [].\n- by rewrite processing_aux_rcons IHr rev_rcons.\nQed.\n\nLemma processing_aux_cons state b bs:\n  (process_aux state (b::bs) [::]).2 =\n  (state, voted_on state b) :: (process_aux (next_state state b) bs [::]).2.\nProof.\nrewrite /= voting_next_voted -[[:: (state, voted_on _ _)]]cat0s cats1.\nby rewrite processing_aux_rcons.\nQed.\n\nLemma processing_aux_cons2 state b bs:\n  (process_aux state (b::bs) [::]) =\n  let: (f_state, vbs) := (process_aux (next_state state b) bs [::]) in\n  (f_state, (state, voted_on state b) ::vbs).\nProof.\nrewrite /= voting_next_voted -[[:: (state, voted_on _ _)]]cat0s cats1.\nrewrite [process_aux _ bs [::]]surjective_pairing -processing_aux_cons /=.\nrewrite (processing_aux_state_res_irrel _ _ [::] [:: (state, voted_on state b)]).\nby rewrite voting_next_voted -surjective_pairing.\nQed.\n\nLemma node_processing_cons state b bs:\n  (node_processing state (b::bs)).2 =\n  (state, voted_on state b) :: (node_processing (next_state state b) bs).2.\nProof.\nby rewrite processing_aux_cons.\nQed.\n\nLemma node_processing_cons2 state b bs:\n  (node_processing state (b::bs)) =\n  let: (final_state, bsvotes) := node_processing (next_state state b) bs in\n  (final_state, (state, voted_on state b)::bsvotes).\nProof.\nby  rewrite /node_processing processing_aux_cons2.\nQed.\n\nLemma node_processing_cons1 state b bs:\n  (node_processing state (b::bs)).1 =\n  (node_processing (next_state state b) bs).1.\nProof.\ncase: bs state b=>[|x s ]=>state b; rewrite node_processing_cons2 //=.\nby rewrite [node_processing _ _]surjective_pairing /=.\nQed.\n\nLemma node_processing_cat_cps state bs1 bs2 :\n  (node_processing state (bs1 ++ bs2)) =\n  let: (state1, seq1) := (node_processing state bs1) in\n  let: (state2, seq2) := (node_processing state1 bs2) in\n  (state2, seq1 ++ seq2).\nProof.\nelim: bs1 state =>[| b bs IHb] state /=.\n- by rewrite {2}[node_processing _ _]surjective_pairing -surjective_pairing.\nrewrite 2!node_processing_cons2 IHb [node_processing (next_state _ _) _]surjective_pairing /=.\nby rewrite [node_processing _  _]surjective_pairing.\nQed.\n\nLemma node_processing_rcons state bs b:\n  (next_state (node_processing state bs).1 b) =\n  (node_processing state (rcons bs b)).1.\nProof.\nrewrite -cats1 node_processing_cat_cps /=.\nrewrite {2}[node_processing _ _]surjective_pairing /=.\nrewrite [node_processing _ [::b]]surjective_pairing /=.\nby rewrite node_processing_cons1 /=.\nQed.\n\nLemma voting_progress_seq state bs b:\n  voted_on (node_processing state bs).1 b -> voted_on state b.\nProof.\nelim: bs state b => [|x s IHs] state b //=.\nrewrite node_processing_cons1.\nmove/IHs; apply voting_progress.\nQed.\n\n(************************************************************)\n(** Consensus State Comparators                            **)\n(************************************************************)\n\nDefinition comparator state1 :=\n  ((last_vote_round state1).+1, (preferred_block_round state1)).\n\nDefinition state_compare state1 state2 :=\n  ((comparator state1).1 <= (comparator state2).1) && ((comparator state1).2 <= (comparator state2).2).\n\nDeclare Scope state_scope.\nDelimit Scope state_scope with STATE.\nOpen Scope state_scope.\n\nNotation \"state1 <% state2\" := (state_compare state1 state2) (at level 40) :state_scope.\n\nLemma comparators_reflexive:\n  reflexive state_compare.\nProof.\nby move => x; rewrite /state_compare 2!leqnn.\nQed.\n\nLemma comparators_transitive:\n  transitive state_compare.\nProof.\nmove => s2 s1 s3 H12 H23; move/andP: H12=> [H12fst H12snd].\nmove/andP: H23=> [H23fst H23snd]; rewrite /state_compare (leq_trans H12fst H23fst).\nby rewrite (leq_trans H12snd).\nQed.\n\nLemma voting_comparator state x:\n  (voted_on state x) ->\n  (comparator (next_state state x) = ((round x).+1, (maxn (comparator state).2 (qc_parent_round x)))).\nProof.\nrewrite next_state_lvr_if fun_if /comparator /= =>H.\nby rewrite H update_maxn /= maxnC.\nQed.\n\nLemma non_voting_comparator state x:\n  ~~ voted_on state x ->\n  comparator (next_state state x) = ((comparator state).1, (maxn (comparator state).2 (qc_parent_round x))).\nProof.\nmove=>Hnv; rewrite next_state_lvr_if; move/negbTE: (Hnv)=>->.\nby rewrite /comparator update_maxn /=.\nQed.\n\nLemma voting_comparatorE state x:\n  comparator (next_state state x) =\n  if (voted_on state x) then\n    ((round x).+1, (maxn (comparator state).2 (qc_parent_round x)))\n  else\n    ((comparator state).1, (maxn (comparator state).2 (qc_parent_round x))).\nProof.\nby case H:(voted_on state x); [rewrite (voting_comparator H)| rewrite (non_voting_comparator (negbT H))].\nQed.\n\nLemma voting_comparator_eq state b:\n    (voted_on state b) =\n    ((comparator state).1 <= round b) && ((comparator state).2 <= (qc_round b)) && ((qc_parent_round b) <= qc_round b).\nProof.\nby  rewrite /comparator ineq_voted_on /= andbA.\nQed.\n\nLemma voting_gt_compare state1 state2 x:\n  state1 <% state2 -> voted_on state2 x -> voted_on state1 x.\nProof.\nmove=> H; rewrite 2!voted_on_maxn.\nmove/andP=> [Hlv2 Hpr2]; move/andP: H=> [Hlv12 Hpr12].\nrewrite (leq_trans Hlv12 Hlv2) /=; move:Hpr2; rewrite 2!geq_max.\nby move/andP=> [Hpr2 ->]; rewrite (leq_trans Hpr12 Hpr2).\nQed.\n\nLemma voting_gt_compareN state1 state2 x:\n  state1 <% state2 -> ~~ voted_on state1 x -> ~~ voted_on state2 x.\nProof.\nby move=>H; apply: contra; apply: voting_gt_compare.\nQed.\n\nLemma voting_next_gt state x:\n  state <% (next_state state x).\nProof.\nrewrite next_state_lvr_if.\ncase Hx:(voted_on state x); rewrite /state_compare /=.\n- move/idP: Hx; rewrite voted_on_maxn.\n  rewrite geq_max; move/andP=> [Hlv Hpr].\n  by rewrite update_maxn /= leq_max leqnn orTb andbT ltnW.\nby rewrite update_maxn /= leq_max 2!leqnn orTb andTb.\nQed.\n\nLemma node_processing_sorted state bs:\n  sorted (fun s1 s2 => s1 <% s2) (unzip1 (node_processing state bs).2).\nProof.\nmove: state; elim: bs=>[| b bs IHb] state //.\nrewrite node_processing_cons; move:(IHb (next_state state b)); rewrite /path /sorted /=.\ncase H: (unzip1 (node_processing (next_state state b) bs).2) =>// [x xs].\nrewrite /path -/(path _ _ _)=>-> /=; move:H; case bs=> [|y ys]//=.\nrewrite andbT node_processing_cons /=; move/eqP; rewrite eqseq_cons.\nby move/andP=>[/eqP<- _]; apply: voting_next_gt.\nQed.\n\nLemma node_processing_head state bs:\n  unzip1 (node_processing state bs).2 = (if bs is x::xs then state :: unzip1 (node_processing (next_state state x) xs).2 else [::]).\nProof.\nby case: bs=> [|x xs]//=; rewrite node_processing_cons /=.\nQed.\n\nLemma node_processing_path state bs:\n  path (fun s1 s2 => s1 <% s2) state (unzip1 (node_processing state bs).2).\nProof.\nmove: (node_processing_sorted state bs); rewrite node_processing_head.\nrewrite /sorted; case: bs=>[|b bs] //=; by rewrite comparators_reflexive.\nQed.\n\nLemma node_processing_last s0 state bs b:\n  last s0 (unzip1 (node_processing state (rcons bs b)).2) = (node_processing state bs).1.\nProof.\nelim: bs state s0 =>[| x s IHs] state s0 //=; first by rewrite node_processing_cons.\nrewrite node_processing_cons node_processing_cons1 /unzip1 map_cons /= -/unzip1.\nby rewrite (IHs (next_state state x)).\nQed.\n\n(************************************************************)\n(** Sequence of blocks which a node voted on             **)\n(************************************************************)\n\nDefinition voted_in_processing state bseq :=\n  mask (unzip2 (node_processing state bseq).2) bseq.\n\nLemma voted_in_processing_cat_cps state bs1 bs2:\n  (voted_in_processing state (bs1 ++ bs2)) =\n  let: b1 := (voted_in_processing state bs1) in\n  let: b2 := (voted_in_processing (node_processing state bs1).1 bs2) in\n  b1 ++ b2.\nProof.\nrewrite /voted_in_processing node_processing_cat_cps /=.\nrewrite 2![node_processing _ _]surjective_pairing /=.\nrewrite -mask_cat; last by rewrite size_map size_processing.\nby rewrite -map_cat /unzip2.\nQed.\n\nLemma voted_in_processing_cons state b bs:\n  (voted_in_processing state (b::bs)) =\n  (nseq (voted_on state b) b ++ (voted_in_processing (next_state state b) bs)).\nProof.\nby rewrite /voted_in_processing node_processing_cons mask_cons.\nQed.\n\nLemma comparator_next state1 state2 b:\n  comparator state1 = comparator state2\n  -> comparator (next_state state1 b) = comparator (next_state state2 b).\nProof.\nmove=> H12; case H1: (voted_on state1 b); move: (H1); rewrite voting_comparator_eq H12 -voting_comparator_eq=> H2.\n- by rewrite (voting_comparator H1) (voting_comparator H2) /=; move/eqP: H12; rewrite xpair_eqE; move/andP =>[_]; move/eqP=>->.\nby rewrite (non_voting_comparator (negbT H1)) (non_voting_comparator (negbT H2)) H12.\nQed.\n\nLemma comparator_processing state1 state2 bseq:\n  comparator state1 = comparator state2\n  -> comparator (node_processing state1 bseq).1 = comparator (node_processing state2 bseq).1.\nProof.\nelim: bseq state1 state2 =>[| x s IHs] state1 state2 H12 //.\nby rewrite 2!node_processing_cons1 (IHs _ _ (comparator_next x H12)).\nQed.\n\nLemma next_state_repeat state b:\n  (next_state (next_state state b) b) = (next_state state b).\nProof.\nrewrite next_state_lvr_if voting_next_N update_maxn next_state_pbr_update update_maxn  /= -maxnA maxnn.\nmove: (next_state_pbr_update state b); rewrite update_maxn {2}/preferred_block_round=><-.\nhave H: forall s, s = {| last_vote_round := (last_vote_round s);\n                    preferred_block_round:= (preferred_block_round s)|}; first by case.\nby rewrite {3}(H (next_state state b)).\nQed.\n\nLemma voted_on_already state bs1 b:\n  b \\in bs1 ->\n  voted_on (node_processing state bs1).1 b = false.\nProof.\nelim/last_ind: bs1 state b => [|s x IHs] state b //=.\nrewrite mem_rcons inE -node_processing_rcons; move/orP=>[Hb|Hb].\n- by rewrite (eqP Hb) voting_next_N.\n- apply/negbTE; rewrite (voting_gt_compareN (voting_next_gt _ x) _) //.\n  by apply/negbT; apply: IHs.\nQed.\n\nLemma updated_already state bs1 b:\n  b \\in bs1 ->\n  update (node_processing state bs1).1 (qc_of b) = (node_processing state bs1).1.\nProof.\nhave H: forall s, s = {| last_vote_round := (last_vote_round s);\n                    preferred_block_round:= (preferred_block_round s)|}; first by case.\nrewrite update_maxn=> Hb.\nhave Hpr: (preferred_block_round (node_processing state bs1).1 >= qc_parent_round b);\n  last by move/maxn_idPl: Hpr=>->; symmetry; exact:H.\nmove: {H} Hb; elim/last_ind: bs1 state b => [|s x IHs] state b //.\nrewrite mem_rcons inE -node_processing_rcons next_state_pbr_update update_maxn leq_max.\nmove/orP=>[Hb|Hb]; rewrite -/(qc_parent_round _) ?(eqP Hb) ?leqnn ?orbT //.\nby rewrite IHs.\nQed.\n\nLemma next_state_already state bs1 b:\n  b \\in bs1 ->\n  (next_state (node_processing state bs1).1 b) = (node_processing state bs1).1.\nProof.\nmove=> Hb; rewrite next_state_lvr_if (voted_on_already _ Hb) updated_already //; symmetry.\nhave H: forall s, s = {| last_vote_round := (last_vote_round s);\n                    preferred_block_round:= (preferred_block_round s)|}; first by case.\nby apply H.\nQed.\n\nLemma comparator_repeat state b:\n  comparator (next_state (next_state state b) b) =\n  comparator (next_state state b).\nProof.\nby rewrite next_state_repeat.\nQed.\n\nLemma voted_in_processing_comparison state1 state2 bs:\n  comparator state1 = comparator state2 ->\n  voted_in_processing state1 bs = voted_in_processing state2 bs.\nProof.\nelim: bs state1 state2=>[| x s IHs] state1 state2 H12 //.\nrewrite /voted_in_processing 2!node_processing_cons 2!mask_cons.\nrewrite -/(map snd) -/unzip2 -2!/(voted_in_processing (next_state _ x) s).\nrewrite (IHs _ _ (comparator_next x H12)) /=.\nby rewrite 2!voting_comparator_eq H12.\nQed.\n\nLemma voted_in_processing_repeat state b bs:\n  voted_in_processing (next_state state b) (b:: bs) =\n  voted_in_processing (next_state state b) (bs).\nProof.\nrewrite /voted_in_processing !node_processing_cons !mask_cons.\nby rewrite voting_next_N next_state_repeat.\nQed.\n\nLemma voted_in_processing_already_cat state b bs1 bs2:\n  b \\in bs1 ->\n  voted_in_processing state (bs1 ++ b::bs2) =\n  voted_in_processing state (bs1 ++ bs2).\nProof.\nrewrite voted_in_processing_cat_cps voted_in_processing_cons=> Hb.\nby rewrite (next_state_already _ Hb) (voted_on_already _ Hb) /= voted_in_processing_cat_cps.\nQed.\n\nLemma voted_in_processing_already state b bs1 bs2:\n  b \\in bs1 ->\n        voted_in_processing (node_processing state bs1).1 (b::bs2) =\n        voted_in_processing (node_processing state bs1).1 bs2.\nrewrite voted_in_processing_cons=> Hb.\nby rewrite (next_state_already _ Hb) (voted_on_already _ Hb) /=.\nQed.\n\nLemma voted_in_pred_cat state bs1 bs2 b:\n  b \\in bs1 ->\n        voted_in_processing (node_processing state bs1).1 bs2 =\n        voted_in_processing (node_processing state bs1).1 (filter (predC1 b) bs2).\nProof.\nelim: bs2 state bs1 b =>[|x xs IHs] state bs1 b Hbin //=.\ncase Hbx: (x == b)=>/=.\n- by rewrite (voted_in_processing_already _ _ ) ?(IHs _ _ b) // (eqP Hbx).\nrewrite 2!voted_in_processing_cons; apply/eqP; rewrite eqseq_cat; last by [].\nrewrite eq_refl node_processing_rcons andTb; apply/eqP/IHs.\nby rewrite mem_rcons inE Hbin orbT.\nQed.\n\nLemma voted_in_predC1 state b bs:\n  voted_in_processing (next_state state b) (bs) =\n  voted_in_processing (next_state state b) (filter (predC1 b) bs).\nProof.\nhave H: (next_state state b) = ((node_processing state [:: b]).1).\n- by rewrite -[[:: b]]cat0s cats1 -node_processing_rcons /=.\nrewrite H; apply: voted_in_pred_cat.\nby rewrite inE.\nQed.\n\nLemma voted_in_rundup state bs:\n  voted_in_processing state bs = voted_in_processing state (rundup bs).\nProof.\nelim: bs state =>[| x s IHs] state //=.\nrewrite /voted_in_processing 2!node_processing_cons /unzip2 map_cons mask_cons.\nrewrite -/(voted_in_processing (next_state state x) s) IHs .\nrewrite mask_cons -/(map snd) -/unzip2 -/(voted_in_processing (next_state state x) _).\nby rewrite -voted_in_predC1.\nQed.\n\nLemma voted_in_processing_idx state bseq b:\n  (b \\in (voted_in_processing state bseq)) =\n  (voted_on (nth state (unzip1 (node_processing state bseq).2) (index b bseq) ) b && (b \\in bseq)).\nProof.\nrewrite voted_in_rundup.\nelim: bseq b state =>[| bb bbs IHbb] b state /=.\n- by rewrite in_nil andbF.\nrewrite /voted_in_processing /= 2!node_processing_cons /unzip2 mask_cons -/(map snd) /=.\ncase H: (bb == b).\n- move/eqP: H=> ->; rewrite in_cons eqxx.\n  case H2: (voted_on state b); first by rewrite in_cons eqxx orTb andbT.\n  rewrite /=; apply: negbTE; apply: contraT; move/negPn=>H.\n  by move: (mem_mask H); rewrite mem_filter /= eq_refl.\nrewrite mem_cat mem_nseq in_cons eq_sym H andbF 2!orFb.\nrewrite -/unzip2 -/(voted_in_processing (next_state state bb) _).\nrewrite -voted_in_predC1 IHbb /=; case Hbbs: (b\\in bbs); last by rewrite 2!andbF.\nrewrite (nth_in_default_irrel (next_state state bb) state _); first by [].\nby rewrite size_map size_processing index_mem.\nQed.\n\nLemma voted_in_processing_exists state bseq b:\n  (b \\in voted_in_processing state bseq) ->\n  exists s, (s \\in (unzip1 (node_processing state bseq).2)) && (voted_on s b) && (b \\in bseq).\nProof.\nrewrite voted_in_processing_idx.\nmove/andP => [H Hb]; exists (nth state (unzip1 (node_processing state bseq).2) (index b bseq)).\nrewrite H Hb 2!andbT; apply/(nthP state); exists (index b bseq)=> //.\nby rewrite size_map size_processing index_mem.\nQed.\n\nLemma voted_in_processing_sorted state bseq:\n  (sorted (fun b1 b2 => round b1 < round b2) (voted_in_processing state bseq)).\nProof.\nmove: state; elim bseq => [| b bs] //; rewrite /sorted=> IHs state //.\nrewrite voted_in_processing_cons.\ncase Hv: (voted_on state b)=> //=.\nmove: (IHs (next_state state b)).\n  case H:((voted_in_processing (next_state state b) bs))=> //= [x xs]->.\nrewrite andbT (@leq_trans (last_vote_round (next_state state b)).+1)=> //.\n- by rewrite next_state_lvr_if Hv ltnS.\nmove: (mem_head x xs); rewrite -H; move/voted_in_processing_exists=> [s].\nmove/andP=> [Hs]; move/andP: Hs=> [Hs]; rewrite voting_comparator_eq; move/andP => [Hlt Hbr] Hx.\nmove/andP:(Hlt)=> [Hlt1 _]; apply: (leq_trans _ Hlt1); move: (node_processing_sorted (next_state state b) (bs)); rewrite /sorted.\ncase Hunz1: (unzip1 (node_processing (next_state state b) bs).2) => [|y ys]; first by move: Hs; rewrite Hunz1 in_nil.\nmove: (Hunz1); rewrite node_processing_head; case Hbs: bs => [|z zs]; first by move: Hx; rewrite Hbs in_nil.\nmove/eqP; rewrite eqseq_cons; move/andP=>[Hy Hys]; rewrite -(eqP Hy).\nmove/(order_path_min comparators_transitive); move/allP; rewrite Hunz1 in Hs.\nmove: Hs; rewrite in_cons; case Hsy: (s == y).\nby move/eqP: Hsy=>->; move/eqP: Hy=><-.\nby move/orP=>[//|] Hin Hcomp; move/andP: (Hcomp _ Hin)=>[-> _].\nQed.\n\nLemma voted_in_processing_qc_parent_sorted state bseq:\n  (sorted (fun b1 b2 => qc_parent_round b1 <= qc_round b2)) (voted_in_processing state bseq).\nProof.\nmove: state; elim bseq => [| b bs] //; rewrite /sorted=> IHs state //.\nrewrite voted_in_processing_cons.\ncase Hv: (voted_on state b)=> //=.\nmove: (IHs (next_state state b)).\n  case H:((voted_in_processing (next_state state b) bs))=> //= [x xs]->.\nrewrite andbT (@leq_trans (preferred_block_round (next_state state b)))=> //.\n-  by rewrite next_state_pbr_update update_maxn leq_maxr.\nmove: (mem_head x xs); rewrite -H; move/voted_in_processing_exists=> [s].\nmove/andP=> [Hs]; move/andP: Hs=> [Hs]; rewrite voting_comparator_eq; move/andP => [Hlt Hbr] Hx.\nmove/andP:(Hlt)=> [_ Hleq1]; apply: (leq_trans _ Hleq1); move: (node_processing_sorted (next_state state b) (bs)); rewrite /sorted.\ncase Hunz1: (unzip1 (node_processing (next_state state b) bs).2) => [|y ys]; first by move: Hs; rewrite Hunz1 in_nil.\nmove: (Hunz1); rewrite node_processing_head; case Hbs: bs => [|z zs]; first by move: Hx; rewrite Hbs in_nil.\nmove/eqP; rewrite eqseq_cons; move/andP=>[Hy Hys]; rewrite -(eqP Hy).\nmove/(order_path_min comparators_transitive); move/allP; rewrite Hunz1 in Hs.\nmove: Hs; rewrite in_cons; case Hsy: (s == y).\nby move/eqP: Hsy=>->; move/eqP: Hy=><-.\nby move/orP=>[//|] Hin Hcomp; move/andP: (Hcomp _ Hin)=>[_ ->].\nQed.\n\nLemma voted_in_processing_subseq_qc_parent_rel state bseq b1 b2:\n  subseq [:: b1; b2] (voted_in_processing state bseq) ->\n  qc_parent_round b1 <= qc_round b2.\nProof.\nmove: state b1 b2; elim: bseq => [|b bs Hbs] //= state b1 b2; rewrite voted_in_processing_cons.\ncase Hvotb: (voted_on state b)=>/=; last by move/Hbs.\ncase Hb1b: (b1 == b); last by move/Hbs.\nrewrite sub1seq (eqP Hb1b).\nmove/voted_in_processing_exists => [s /andP[/andP[Hs Hvotsb2] Hb2]].\nmove: (order_path_min comparators_transitive (node_processing_path (next_state state b) bs)).\nmove/allP; move/(_ _ Hs); move/andP=>[_]; rewrite (voting_comparator Hvotb) /= geq_max; move/andP=>[_].\nmove: Hvotsb2; rewrite ineq_voted_on; move/andP=>[_]; move/andP=> [H _] Hb.\napply:(leq_trans Hb H).\nQed.\n\nLemma voted_in_processing_uniq state bseq:\n  uniq (voted_in_processing state bseq).\nProof.\napply (sorted_uniq rounds_transitive rounds_irreflexive).\napply voted_in_processing_sorted.\nQed.\n\nLemma voted_in_processing_both state bseq b1 b2:\n  (b1 != b2) ->\n  (b1 \\in (voted_in_processing state bseq)) ->\n  (b2 \\in (voted_in_processing state bseq)) ->\n  (round b1 <= round b2) ->\n  subseq ([:: b1; b2]) (voted_in_processing state bseq).\nProof.\nmove => Hneq H1 H2 H12; move: (cat_take_drop_in H1); move/eqP=> Hsplit.\nmove: (H2); rewrite -{1}Hsplit; rewrite mem_cat in_cons eq_sym.\nmove/negbTE: Hneq=>->; rewrite orFb; move/orP=>[|].\n- rewrite -sub1seq=> H13; move: (subseq_refl [:: b1])=> H24; move: {H13 H24}(cat_subseq H13 H24)=> Hpref.\n  move: (subseq_trans Hpref (prefix_subseq _ (drop (index b1 (voted_in_processing state bseq)).+1 (voted_in_processing state bseq)))).\n  rewrite cat1s -catA cat1s Hsplit=> Hsub; move/subseq_sorted: Hsub; move/(_ _ _ (voted_in_processing_sorted state bseq)).\n  by move/(_ rounds_transitive); rewrite /= ltnNge H12.\nrewrite -sub1seq=> H24; move: (subseq_refl [::b1])=> H13; move: {H13 H24}(cat_subseq H13 H24)=> Hpref.\nmove: (subseq_trans Hpref (suffix_subseq (take (index b1 (voted_in_processing state bseq)) (voted_in_processing state bseq)) _)).\nby rewrite 2!cat1s Hsplit.\nQed.\n\nLemma voted_in_processing_ltn state bseq b1 b2:\n  (b1 != b2) ->\n  (b1 \\in (voted_in_processing state bseq)) ->\n  (b2 \\in (voted_in_processing state bseq)) ->\n  (round b1 <= round b2) ->\n  round b1 < round b2.\nProof.\nmove => Hneq Hb1 Hb2 Hb12; move:(voted_in_processing_both Hneq Hb1 Hb2 Hb12)=> Hsub.\nmove/subseq_sorted: Hsub; move/(_ _ _ (voted_in_processing_sorted state bseq)).\nby move/(_ rounds_transitive) => /=; rewrite andbT.\nQed.\n\n\n(************************************************************)\n(** Node Aggregation                                       **)\n(************************************************************)\n\n\nDefinition node_aggregator bseq :=\n  (foldl (fun stateNvote => voting_rule stateNvote.1) (genesis_state,false) bseq).1.\n\nDefinition commit_rule state (qc: QC)(bround: nat) :=\n  let: potential_commit_round := (parent_block_round (qc_vote_data qc)) in\n  if (potential_commit_round.+1 == (block_round (qc_vote_data qc))) &&\n        ((block_round (qc_vote_data qc)).+1 == bround) then\n    Some(potential_commit_round)\n  else None.\n\nEnd State.\n", "meta": {"author": "novifinancial", "repo": "LibraChain", "sha": "ac695b9ca063c5e48130cf4a19f8b5bd9b61f56a", "save_path": "github-repos/coq/novifinancial-LibraChain", "path": "github-repos/coq/novifinancial-LibraChain/LibraChain-ac695b9ca063c5e48130cf4a19f8b5bd9b61f56a/Structures/ConsensusState.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.32766830082071396, "lm_q1q2_score": 0.21226294580706115}}
{"text": "From stdpp Require Import base gmap.\nFrom mathcomp Require Import ssreflect.\nFrom stdpp Require Import namespaces.\nFrom iris.algebra Require Import agree auth csum gset gmap excl namespace_map frac.\nFrom iris.heap_lang Require Import notation proofmode.\nFrom cryptis Require Import lib term cryptis primitives tactics session.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSection DH.\n\nContext `{!cryptisG Σ, !heapG Σ}.\nNotation iProp := (iProp Σ).\n\nImplicit Types t : term.\n\nImplicit Types Ψ : val → iProp.\nImplicit Types kA kB : term.\n\nVariable P : term → iProp.\n\nDefinition dh_publ t : iProp :=\n  ∃ g a, ⌜t = TExp g [a]⌝ ∧ □ P t.\n\nDefinition dh_seed t : iProp :=\n  sterm t ∧\n  □ (pterm t ↔ ▷ False) ∧\n  □ (∀ t', dh_pred t t' ↔ ▷ □ dh_publ t').\n\nLemma dh_seed_elim0 a :\n  dh_seed a -∗\n  pterm a -∗\n  ▷ False.\nProof.\niIntros \"#(_ & aP & _) #p_t\".\nby iApply \"aP\".\nQed.\n\nLemma dh_seed_elim1 g a :\n  dh_seed a -∗\n  pterm (TExp g [a]) -∗\n  ▷ P (TExp g [a]).\nProof.\niIntros \"#aP #p_t\".\nrewrite pterm_TExp1.\niDestruct \"p_t\" as \"(_ & _ & [contra | p_t])\".\n  by iPoseProof (@dh_seed_elim0 with \"aP contra\") as \">[]\".\niDestruct \"aP\" as \"(_ & _ & #aP)\".\niSpecialize (\"aP\" with \"p_t\"); iModIntro.\niDestruct \"aP\" as (g' a') \"# [%e aP]\".\nby case/TExp_inj: e => _ /Permutation_singleton [] ->; eauto.\nQed.\n\nLemma dh_seed_elim2 g a t :\n  dh_seed a -∗\n  pterm (TExp g [a; t]) -∗\n  ◇ (pterm (TExp g [a]) ∧ pterm t).\nProof.\niIntros \"#aP #p_t\".\nrewrite pterm_TExp2.\niDestruct \"p_t\" as \"[p_t|[[_ contra]|p_t]]\"; eauto.\n  by iPoseProof (@dh_seed_elim0 with \"aP contra\") as \">[]\".\niDestruct \"p_t\" as \"(_ & p_t & _)\".\niDestruct \"aP\" as \"(_ & _ & #aP)\".\niPoseProof (\"aP\" with \"p_t\") as \"{p_t} p_t\".\niAssert (▷ False)%I as \">[]\".\niModIntro.\niDestruct \"p_t\" as (g' a') \"(%e & _)\".\nby case/TExp_inj: e => _ /Permutation_length.\nQed.\n\nLemma dh_pterm_TExp g a :\n  sterm g -∗\n  dh_seed a -∗\n  ▷ □ P (TExp g [a]) -∗\n  pterm (TExp g [a]).\nProof.\niIntros \"#gP #(? & ? & aP) #P_a\".\nrewrite pterm_TExp1; do !iSplit => //.\nby iRight; iApply \"aP\"; iModIntro; iExists _, _; eauto.\nQed.\n\nDefinition dh_meta `{Countable L} t N (x : L) : iProp :=\n  (∃ g a, ⌜t = TExp g [a]⌝ ∧ nonce_meta a N x)%I.\n\nDefinition dh_meta_token t E : iProp :=\n  (∃ g a, ⌜t = TExp g [a]⌝ ∧ nonce_meta_token a E)%I.\n\nProgram Global Instance dh_term_meta :\n  TermMeta (@dh_meta) dh_meta_token.\n\nNext Obligation.\niIntros (L ?? E t x N sub).\niDestruct 1 as (g a) \"[-> token]\".\niMod (term_meta_set _ _ x with \"token\") as \"meta\"; eauto.\nby rewrite /dh_meta; eauto.\nQed.\n\nNext Obligation.\niIntros (L ?? t x N E sub).\niDestruct 1 as (g a) \"[-> token]\".\niDestruct 1 as (??)  \"[%e  meta]\".\nmove/TExp_inj: e => [_ /Permutation_singleton [<-]].\nby iApply (term_meta_meta_token with \"token meta\").\nQed.\n\nNext Obligation.\niIntros (L ?? t N x1 x2).\niDestruct 1 as (g a) \"[-> meta1]\".\niDestruct 1 as (??)  \"[%e meta2]\".\nmove/TExp_inj: e => [_ /Permutation_singleton [<-]].\nby iApply (term_meta_agree with \"meta1 meta2\").\nQed.\n\nNext Obligation.\nrewrite /dh_meta /dh_meta_token.\nmove=> t E1 E2 sub; iSplit.\n- iDestruct 1 as (g a) \"[-> token]\".\n  rewrite [nonce_meta_token _ _](term_meta_token_difference a E1 E2) //.\n  by iDestruct \"token\" as \"[token1 token2]\"; iSplitL \"token1\"; eauto.\n- iDestruct 1 as \"[token1 token2]\".\n  iDestruct \"token1\" as (g a) \"[-> token1]\".\n  iDestruct \"token2\" as (??) \"[%e token2]\".\n  move/TExp_inj: e => [_ /Permutation_singleton [<-]].\n  iExists _, _; iSplit => //.\n  rewrite (term_meta_token_difference _ E1 E2) //.\n  by iSplitL \"token1\".\nQed.\n\nDefinition mkdh : val := mknonce.\n\nLemma wp_mkdh g E (Ψ : val → iProp) :\n  (∀ a, sterm a -∗\n        dh_seed a -∗\n        dh_meta_token (TExp g [a]) ⊤ -∗\n        Ψ a) -∗\n  WP mkdh #() @ E {{ Ψ }}.\nProof.\niIntros \"post\"; iApply (wp_mknonce _ (λ _, False%I) dh_publ).\niIntros (a) \"#s_a #(aP1 & aP2) #? token\"; iApply \"post\" => //.\ndo !iSplit => //.\niModIntro; iSplit.\n- by iIntros \"H\"; iSpecialize (\"aP1\" with \"H\"); iModIntro.\n- by iIntros \"#?\"; iApply \"aP2\"; iModIntro.\n- by iExists g, a; eauto.\nQed.\n\nEnd DH.\n", "meta": {"author": "arthuraa", "repo": "cryptis", "sha": "056d1fb93b8d8395b0c19639edb961d4919c63f6", "save_path": "github-repos/coq/arthuraa-cryptis", "path": "github-repos/coq/arthuraa-cryptis/cryptis-056d1fb93b8d8395b0c19639edb961d4919c63f6/dh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3775406758018019, "lm_q1q2_score": 0.21224449606431653}}
{"text": "Require Import Verdi.Verdi.\nRequire Import Verdi.LabeledNet.\nRequire Import Verdi.TotalMapSimulations.\n\nRequire Import InfSeqExt.infseq.\nRequire Import InfSeqExt.map.\nRequire Import InfSeqExt.exteq.\n\nRequire Import FunctionalExtensionality.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import Verdi.Ssrexport.\n\nSet Implicit Arguments.\n\nClass LabeledMultiParamsLabelTotalMap\n (B0 : BaseParams) (B1 : BaseParams)\n (P0 : LabeledMultiParams B0) (P1 : LabeledMultiParams B1) :=\n  {    \n    tot_map_label : @label B0 P0 -> @label B1 P1\n  }.\n\nSection LabeledTotalMapDefs.\n\nContext {base_fst : BaseParams}.\nContext {base_snd : BaseParams}.\nContext {labeled_multi_fst : LabeledMultiParams base_fst}.\nContext {labeled_multi_snd : LabeledMultiParams base_snd}.\nContext {label_map : LabeledMultiParamsLabelTotalMap labeled_multi_fst labeled_multi_snd}.\n\nDefinition tot_mapped_lb_net_handlers_label me src m st :=\n  let '(lb, out, st', ps) := lb_net_handlers me src m st in tot_map_label lb.\n\nDefinition tot_mapped_lb_input_handlers_label me inp st :=\n  let '(lb, out, st', ps) := lb_input_handlers me inp st in tot_map_label lb.\n\nEnd LabeledTotalMapDefs.\n\nClass LabeledMultiParamsTotalMapCongruency\n  (B0 : BaseParams) (B1 : BaseParams)\n  (P0 : LabeledMultiParams B0) (P1 : LabeledMultiParams B1)\n  (B : BaseParamsTotalMap B0 B1) \n  (N : MultiParamsNameTotalMap (@unlabeled_multi_params _ P0) (@unlabeled_multi_params _ P1))\n  (P : MultiParamsMsgTotalMap (@unlabeled_multi_params _ P0) (@unlabeled_multi_params _ P1))\n  (L : LabeledMultiParamsLabelTotalMap P0 P1) : Prop :=\n  {\n    tot_lb_net_handlers_eq : forall me src m st out st' ps lb, \n      lb_net_handlers (tot_map_name me) (tot_map_name src) (tot_map_msg m) (tot_map_data st) = (lb, out, st', ps)  ->\n      tot_mapped_lb_net_handlers_label me src m st = lb ;\n    tot_lb_input_handlers_eq : forall me inp st out st' ps lb, \n      lb_input_handlers (tot_map_name me) (tot_map_input inp) (tot_map_data st) = (lb, out, st', ps) ->\n      tot_mapped_lb_input_handlers_label me inp st = lb ;\n    tot_lb_label_silent_fst_snd : tot_map_label label_silent = label_silent\n  }.\n\nSection TotalMapExecutionSimulations.\n\nContext {base_fst : BaseParams}.\nContext {base_snd : BaseParams}.\nContext {labeled_multi_fst : LabeledMultiParams base_fst}.\nContext {labeled_multi_snd : LabeledMultiParams base_snd}.\nContext {base_map : BaseParamsTotalMap base_fst base_snd}.\nContext {name_map : MultiParamsNameTotalMap (@unlabeled_multi_params _ labeled_multi_fst) (@unlabeled_multi_params _ labeled_multi_snd)}.\nContext {msg_map : MultiParamsMsgTotalMap (@unlabeled_multi_params _ labeled_multi_fst) (@unlabeled_multi_params _ labeled_multi_snd)}.\nContext {label_map : LabeledMultiParamsLabelTotalMap labeled_multi_fst labeled_multi_snd}.\nContext {name_map_bijective : MultiParamsNameTotalMapBijective name_map}.\nContext {multi_map_congr : MultiParamsTotalMapCongruency base_map name_map msg_map}.\nContext {multi_map_lb_congr : LabeledMultiParamsTotalMapCongruency base_map name_map msg_map label_map}.\n\nHypothesis tot_map_label_injective :\n  forall l l', tot_map_label l = tot_map_label l' -> l = l'.\n\n(* lb_step_failure *)\n\nTheorem lb_step_failure_tot_mapped_simulation_1 :\n  forall net net' failed failed' lb tr,\n    @lb_step_failure _ labeled_multi_fst (failed, net) lb (failed', net') tr ->\n    @lb_step_failure _ labeled_multi_snd (List.map tot_map_name failed, tot_map_net net) (tot_map_label lb) (List.map tot_map_name failed', tot_map_net net') (List.map tot_map_trace_occ tr).\nProof using name_map_bijective multi_map_lb_congr multi_map_congr.\nmove => net net' failed failed' lb tr H_step.\ninvcs H_step => //=.\n- have ->: tot_map_name (pDst p) = pDst (tot_map_packet p) by destruct p.\n  apply: (@LabeledStepFailure_deliver _ _ _ _ _ _ (List.map tot_map_packet xs) (List.map tot_map_packet ys) (List.map tot_map_output out) (tot_map_data d) (@tot_map_name_msgs _ _ _ _ _ msg_map l)).\n  * rewrite /tot_map_net /=.\n    find_rewrite.\n    by rewrite map_app.\n  * destruct p.\n    simpl in *.\n    exact: not_in_failed_not_in.\n  * destruct p.\n    simpl in *.\n    rewrite tot_map_name_inv_inverse.\n    have H_q := @tot_net_handlers_eq _ _ _ _ _ _ _ multi_map_congr pDst pSrc pBody (nwState net pDst).\n    rewrite /tot_mapped_net_handlers /net_handlers /= /unlabeled_net_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @tot_lb_net_handlers_eq _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ Heqp1.\n    rewrite /tot_mapped_lb_net_handlers_label in H_q'.\n    repeat break_let.\n    by repeat tuple_inversion.\n  * rewrite /tot_map_net /= 2!map_app -(@tot_map_update_packet_eq _ _ _ _ _ _ _ name_map_bijective).\n    destruct p.\n    by rewrite tot_map_packet_map_eq.\n- apply: (@LabeledStepFailure_input _ _ _ _ _ _ _ _ (tot_map_data d) (tot_map_name_msgs l)).\n  * exact: not_in_failed_not_in.\n  * rewrite /tot_map_net /= tot_map_name_inv_inverse.\n    have H_q := @tot_input_handlers_eq _ _ _ _ _ _ _ multi_map_congr h inp (nwState net h).\n    rewrite /tot_mapped_input_handlers /= /unlabeled_input_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @tot_lb_input_handlers_eq _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ Heqp1.\n    rewrite /tot_mapped_lb_input_handlers_label in H_q'.\n    repeat break_let.\n    by repeat tuple_inversion.\n  * by rewrite /tot_map_net /= map_app tot_map_packet_map_eq -(@tot_map_update_eq _ _ _ _ _ _ name_map_bijective).\n- rewrite tot_lb_label_silent_fst_snd.\n  exact: LabeledStepFailure_stutter.\nQed.\n\nDefinition tot_map_net_event e :=\n{| evt_a := (List.map tot_map_name (fst e.(evt_a)), tot_map_net (snd e.(evt_a))) ;\n   evt_l := tot_map_label e.(evt_l) ;\n   evt_trace := List.map tot_map_trace_occ e.(evt_trace) |}.\n\nLemma tot_map_net_event_map_unfold : forall s,\n Cons (tot_map_net_event (hd s)) (map tot_map_net_event (tl s)) = map tot_map_net_event s.\nProof using.\nby move => s; rewrite -map_Cons /= -{3}(recons s).\nQed.\n\nLemma lb_step_trace_execution_lb_step_failure_tot_map_net_infseq : forall s,\n  lb_step_execution lb_step_failure s ->\n  lb_step_execution lb_step_failure (map tot_map_net_event s).\nProof using name_map_bijective multi_map_lb_congr multi_map_congr.\ncofix c.\nmove => s H_exec.\nrewrite -tot_map_net_event_map_unfold {1}/tot_map_net_event /=.\ninversion H_exec; subst => /=.\nrewrite -tot_map_net_event_map_unfold /= /tot_map_net_event /=.\napply: (@Cons_lb_step_exec _ _ _ _ _ _ (List.map tot_map_trace_occ tr)) => /=.\n- apply: lb_step_failure_tot_mapped_simulation_1.\n  have <-: evt_a e = (fst (evt_a e), snd (evt_a e)) by destruct e, evt_a.\n  by have <-: evt_a e' = (fst (evt_a e'), snd (evt_a e')) by destruct e', evt_a.\n- simpl in *.\n  find_rewrite.\n  by rewrite map_app.\n- set e0 := {| evt_a := _ ; evt_l := _ ; evt_trace := _ |}.\n  have ->: e0 = tot_map_net_event e' by [].\n  pose s' := Cons e' s0.\n  rewrite (tot_map_net_event_map_unfold s').\n  exact: c.\nQed.\n\nLemma tot_map_net_label_event_inf_often_occurred :\n  forall l s,\n    inf_often (now (occurred l)) s ->\n    inf_often (now (occurred (tot_map_label l))) (map tot_map_net_event s).\nProof using.\nmove => l.\napply: always_map.\napply: eventually_map.\ncase => e s.\nrewrite /= /occurred /=.\nmove => H_eq.\nby rewrite H_eq.\nQed.\n\nLemma tot_map_net_label_event_inf_often_occurred_conv :\n  forall l s,\n    inf_often (now (occurred (tot_map_label l))) (map tot_map_net_event s) ->\n    inf_often (now (occurred l)) s.\nProof using tot_map_label_injective.\nmove => l.\napply: always_map_conv.\napply: eventually_map_conv => //.\n- rewrite /extensional /=.\n  case => e s1.\n  case => e' s2.\n  move => H_eq.\n  by inversion H_eq; subst_max.\n- rewrite /extensional /=.\n  case => e s1.\n  case => e' s2.\n  move => H_eq.\n  by inversion H_eq; subst_max.\n- case => e s.\n  rewrite /= /occurred /=.\n  move => H_eq.\n  exact: tot_map_label_injective.\nQed.\n\nContext {fail_fst : FailureParams (@unlabeled_multi_params _ labeled_multi_fst)}.\nContext {fail_snd : FailureParams (@unlabeled_multi_params _ labeled_multi_snd)}.\nContext {fail_map_congr : FailureParamsTotalMapCongruency fail_fst fail_snd base_map}.\n\nLemma tot_map_net_hd_step_failure_star_always : \n  forall s, event_step_star step_failure step_failure_init (hd s) ->\n       lb_step_execution lb_step_failure s ->\n       always (now (event_step_star step_failure step_failure_init)) (map tot_map_net_event s).\nProof using name_map_bijective multi_map_lb_congr multi_map_congr fail_map_congr.\ncase => e s H_star H_exec.\napply: step_failure_star_lb_step_execution.\n  rewrite /=.\n  rewrite /tot_map_net_event /= /event_step_star /=.\n  apply: step_failure_tot_mapped_simulation_star_1.\n  by have <-: evt_a e = (fst (evt_a e), snd (evt_a e)) by destruct e, evt_a.\nexact: lb_step_trace_execution_lb_step_failure_tot_map_net_infseq.\nQed.\n\n(* lb_step_ordered_failure *)\n\nTheorem lb_step_ordered_failure_tot_mapped_simulation_1 :\n  forall net net' failed failed' lb tr,\n    @lb_step_ordered_failure _ labeled_multi_fst (failed, net) lb (failed', net') tr ->\n    @lb_step_ordered_failure _ labeled_multi_snd (List.map tot_map_name failed, tot_map_onet net) (tot_map_label lb) (List.map tot_map_name failed', tot_map_onet net') (List.map tot_map_trace tr).\nProof using name_map_bijective multi_map_lb_congr multi_map_congr.\nmove => net net' failed failed' lb tr H_step.\ninvcs H_step => //=.\n- apply (@LabeledStepOrderedFailure_deliver _ _ _ _ _ _ (@tot_map_msg _ _ _ _ msg_map m) (List.map (@tot_map_msg _ _ _ _ msg_map) ms) (List.map tot_map_output out) (tot_map_data d) (@tot_map_name_msgs _ _ _ _ _ msg_map l) (@tot_map_name _ _ _ _ name_map from) (@tot_map_name _ _ _ _ name_map to)) => //=.\n  * rewrite /tot_map_onet /=.\n    rewrite 2!tot_map_name_inv_inverse.\n    by find_rewrite.\n  * exact: not_in_failed_not_in.\n  * rewrite /tot_map_onet /= tot_map_name_inv_inverse.\n    have H_q := @tot_net_handlers_eq _ _ _ _ _ _ _ multi_map_congr to from m (onwState net to).\n    rewrite /tot_mapped_net_handlers /net_handlers /= /unlabeled_net_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @tot_lb_net_handlers_eq _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ Heqp1.\n    rewrite /tot_mapped_lb_net_handlers_label in H_q'.\n    repeat break_let.\n    by repeat tuple_inversion.\n  * rewrite /tot_map_onet /=.         \n    rewrite (@collate_tot_map_update2_eq _ _ _ _ _ _ name_map_bijective).\n    set f1 := fun _ => tot_map_data _.\n    set f2 := update _ _ _ _.\n    have H_eq_f: f1 = f2.\n      rewrite /f1 /f2.\n      apply functional_extensionality => n.\n      rewrite /update.\n      break_if; break_if => //; first by rewrite -e tot_map_name_inverse_inv in n0.\n      by rewrite e tot_map_name_inv_inverse in n0.\n    by rewrite H_eq_f.\n  * by rewrite (@map_tot_map_trace_eq _ _ _ _ _ name_map).\n- rewrite /tot_map_onet /=.\n  apply (@LabeledStepOrderedFailure_input _ _ (@tot_map_name _ _ _ _ name_map h) _ _ _ _ (List.map tot_map_output out) (tot_map_input inp) (tot_map_data d) (@tot_map_name_msgs _ _ _ _ _ msg_map l)).\n  * exact: not_in_failed_not_in.\n  * rewrite /tot_map_onet /= tot_map_name_inv_inverse.\n    have H_q := @tot_input_handlers_eq _ _ _ _ _ _ _ multi_map_congr h inp (onwState net h).\n    rewrite /tot_mapped_input_handlers /= /unlabeled_input_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @tot_lb_input_handlers_eq _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ Heqp1.\n    rewrite /tot_mapped_lb_input_handlers_label in H_q'.\n    repeat break_let.\n    by repeat tuple_inversion.\n  * rewrite /tot_map_onet /=.\n    rewrite (@collate_tot_map_eq _ _ _ _ _ _ name_map_bijective).\n    set f1 := fun _ => tot_map_data _.\n    set f2 := update _ _ _ _.\n    have H_eq_f: f1 = f2.\n      rewrite /f1 /f2.\n      apply functional_extensionality => n.\n      rewrite /update.\n      break_if; break_if => //; first by rewrite -e tot_map_name_inverse_inv in n0.\n      by rewrite e tot_map_name_inv_inverse in n0.\n    by rewrite H_eq_f.\n  * by rewrite (@map_tot_map_trace_eq _ _ _ _ _ name_map).\n- rewrite tot_lb_label_silent_fst_snd.\n  exact: LabeledStepOrderedFailure_stutter.\nQed.\n\nDefinition tot_map_onet_event e :=\n{| evt_a := (List.map tot_map_name (fst e.(evt_a)), tot_map_onet (snd e.(evt_a))) ;\n   evt_l := tot_map_label e.(evt_l) ;\n   evt_trace := List.map tot_map_trace e.(evt_trace) |}.\n\nLemma tot_map_onet_event_map_unfold : forall s,\n Cons (tot_map_onet_event (hd s)) (map tot_map_onet_event (tl s)) = map tot_map_onet_event s.\nProof using.\nby move => s; rewrite -map_Cons /= -{3}(recons s).\nQed.\n\nLemma lb_step_execution_lb_step_ordered_failure_tot_map_onet_infseq : forall s,\n  lb_step_execution lb_step_ordered_failure s ->\n  lb_step_execution lb_step_ordered_failure (map tot_map_onet_event s).\nProof using name_map_bijective multi_map_lb_congr multi_map_congr.\ncofix c.\nmove => s H_exec.\nrewrite -tot_map_onet_event_map_unfold {1}/tot_map_onet_event /=.\ninversion H_exec; subst => /=.\nrewrite -tot_map_onet_event_map_unfold /= /tot_map_onet_event /=.\napply: (@Cons_lb_step_exec _ _ _ _ _ _ (List.map tot_map_trace tr)) => /=.\n- apply: lb_step_ordered_failure_tot_mapped_simulation_1.\n  have <-: evt_a e = (fst (evt_a e), snd (evt_a e)) by destruct e, evt_a.\n  by have <-: evt_a e' = (fst (evt_a e'), snd (evt_a e')) by destruct e', evt_a.\n- simpl in *.\n  find_rewrite.\n  by rewrite map_app.\n- set e0 := {| evt_a := _ ; evt_l := _ ; evt_trace := _ |}.\n  have ->: e0 = tot_map_onet_event e' by [].\n  pose s' := Cons e' s0.\n  rewrite (tot_map_onet_event_map_unfold s').\n  exact: c.\nQed.\n\nLemma tot_map_onet_label_event_inf_often_occurred :\n  forall l s,\n    inf_often (now (occurred l)) s ->\n    inf_often (now (occurred (tot_map_label l))) (map tot_map_onet_event s).\nProof using.\nmove => l.\napply: always_map.\napply: eventually_map.\ncase => e s.\nrewrite /= /occurred /=.\nmove => H_eq.\nby rewrite H_eq.\nQed.\n\nLemma tot_map_onet_label_event_inf_often_occurred_conv :\n  forall l s,\n    inf_often (now (occurred (tot_map_label l))) (map tot_map_onet_event s) ->\n    inf_often (now (occurred l)) s.\nProof using tot_map_label_injective.\nmove => l.\napply: always_map_conv.\napply: eventually_map_conv => //.\n- rewrite /extensional /=.\n  case => e s1.\n  case => e' s2.\n  move => H_eq.\n  by inversion H_eq; subst_max.\n- rewrite /extensional /=.\n  case => e s1.\n  case => e' s2.\n  move => H_eq.\n  by inversion H_eq; subst_max.\n- case => e s.\n  rewrite /= /occurred /=.\n  move => H_eq.\n  exact: tot_map_label_injective.\nQed.  \n\nContext {overlay_fst : NameOverlayParams (@unlabeled_multi_params _ labeled_multi_fst)}.\nContext {overlay_snd : NameOverlayParams (@unlabeled_multi_params _ labeled_multi_snd)}.\nContext {overlay_map_congr : NameOverlayParamsTotalMapCongruency overlay_fst overlay_snd name_map}.\n\nContext {fail_msg_fst : FailMsgParams (@unlabeled_multi_params _ labeled_multi_fst)}.\nContext {fail_msg_snd : FailMsgParams (@unlabeled_multi_params _ labeled_multi_snd)}.\nContext {fail_msg_map_congr : FailMsgParamsTotalMapCongruency fail_msg_fst fail_msg_snd msg_map}.\n  \nLemma tot_map_onet_hd_step_ordered_failure_star_always : \n  forall s, event_step_star step_ordered_failure step_ordered_failure_init (hd s) ->\n       lb_step_execution lb_step_ordered_failure s ->\n       always (now (event_step_star step_ordered_failure step_ordered_failure_init)) (map tot_map_onet_event s).\nProof using overlay_map_congr name_map_bijective multi_map_lb_congr multi_map_congr fail_msg_map_congr.\ncase => e s H_star H_exec.\napply: step_ordered_failure_star_lb_step_execution; last exact: lb_step_execution_lb_step_ordered_failure_tot_map_onet_infseq.\nrewrite /= /tot_map_onet_event /= /event_step_star /=.\napply: step_ordered_failure_tot_mapped_simulation_star_1.\nby have <-: evt_a e = (fst (evt_a e), snd (evt_a e)) by destruct e, evt_a.\nQed.\n\n(* lb_step_ordered_dynamic_failure *)\n\nTheorem lb_step_ordered_dynamic_failure_tot_mapped_simulation_1 :\n  forall net net' failed failed' lb tr,\n    @lb_step_ordered_dynamic_failure _ labeled_multi_fst (failed, net) lb (failed', net') tr ->\n    @lb_step_ordered_dynamic_failure _ labeled_multi_snd (List.map tot_map_name failed, tot_map_odnet net) (tot_map_label lb) (List.map tot_map_name failed', tot_map_odnet net') (List.map tot_map_trace tr).\nProof using name_map_bijective multi_map_lb_congr multi_map_congr.\nmove => net net' failed failed' lb tr H_step.\ninvcs H_step => //=.\n- rewrite /tot_map_odnet /=.\n  apply (@LabeledStepOrderedDynamicFailure_deliver _ _ _ _ _ _ (@tot_map_msg _ _ _ _ msg_map m) (List.map (@tot_map_msg _ _ _ _ msg_map) ms) (List.map tot_map_output out) (tot_map_data d) (tot_map_data d') (@tot_map_name_msgs _ _ _ _ _ msg_map l) (@tot_map_name _ _ _ _ name_map from) (@tot_map_name _ _ _ _ name_map to)) => //=.\n  * exact: not_in_failed_not_in.\n  * exact: in_failed_in. \n  * rewrite tot_map_name_inv_inverse.\n    by find_rewrite.\n  * rewrite 2!tot_map_name_inv_inverse.\n    by find_rewrite.\n  * have H_q := @tot_net_handlers_eq _ _ _ _ _ _ _ multi_map_congr to from m d.\n    rewrite /tot_mapped_net_handlers /net_handlers /= /unlabeled_net_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @tot_lb_net_handlers_eq _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ _ Heqp1.\n    rewrite /tot_mapped_lb_net_handlers_label in H_q'.\n    repeat break_let.\n    by repeat tuple_inversion.\n  * rewrite (@collate_tot_map_update2_eq _ _ _ _ _ _ name_map_bijective).\n    set f1 := fun _ => match _ with _ => _ end.\n    set f2 := update _ _ _ _.\n    have H_eq_f: f1 = f2.\n      rewrite /f1 /f2 /update.\n      apply functional_extensionality => dst.\n      repeat break_if => //=; first by rewrite -e tot_map_name_inverse_inv in n.\n      by rewrite e tot_map_name_inv_inverse in n.\n    by rewrite H_eq_f.\n  * by rewrite (@map_tot_map_trace_eq _ _ _ _ _ name_map).\n- rewrite /tot_map_odnet /=.\n  apply (@LabeledStepOrderedDynamicFailure_input _ _ (@tot_map_name _ _ _ _ name_map h) _ _ _ _ (List.map tot_map_output out) (tot_map_input inp) (tot_map_data d) (tot_map_data d') (@tot_map_name_msgs _ _ _ _ _ msg_map l)) => //=.\n  * exact: not_in_failed_not_in.\n  * exact: in_failed_in. \n  * rewrite tot_map_name_inv_inverse.\n    by find_rewrite.\n  * have H_q := @tot_input_handlers_eq _ _ _ _ _ _ _ multi_map_congr h inp d.\n    rewrite /tot_mapped_input_handlers /= /unlabeled_input_handlers in H_q.\n    repeat break_let.\n    repeat tuple_inversion.\n    have H_q' := @tot_lb_input_handlers_eq _ _ _ _ _ _ _ _ multi_map_lb_congr _ _ _ _ _ _ _ Heqp1.\n    rewrite /tot_mapped_lb_input_handlers_label in H_q'.\n    repeat break_let.\n    by repeat tuple_inversion.\n  * rewrite (@collate_tot_map_eq _ _ _ _ _ _ name_map_bijective).\n    set f1 := fun _ => match _ with _ => _ end.\n    set f2 := update _ _ _ _.\n    have H_eq_f: f1 = f2.\n      rewrite /f1 /f2 /update.\n      apply functional_extensionality => n.\n      repeat break_match; try by congruence.\n      * by rewrite e tot_map_name_inv_inverse in n0.\n      * by rewrite -e tot_map_name_inverse_inv in n0.\n      * by rewrite e tot_map_name_inv_inverse in n0.\n    by rewrite H_eq_f.\n  * by rewrite (@map_tot_map_trace_eq _ _ _ _ _ name_map).\n- rewrite tot_lb_label_silent_fst_snd.\n  exact: LabeledStepOrderedDynamicFailure_stutter.\nQed.\n\nDefinition tot_map_odnet_event e :=\n{| evt_a := (List.map tot_map_name (fst e.(evt_a)), tot_map_odnet (snd e.(evt_a))) ;\n   evt_l := tot_map_label e.(evt_l) ;\n   evt_trace := List.map tot_map_trace e.(evt_trace) |}.\n\nLemma tot_map_odnet_event_map_unfold : forall s,\n Cons (tot_map_odnet_event (hd s)) (map tot_map_odnet_event (tl s)) = map tot_map_odnet_event s.\nProof using.\nby move => s; rewrite -map_Cons /= -{3}(recons s).\nQed.\n\nLemma lb_step_execution_lb_step_ordered_dynamic_failure_tot_map_odnet_infseq : forall s,\n  lb_step_execution lb_step_ordered_dynamic_failure s ->\n  lb_step_execution lb_step_ordered_dynamic_failure (map tot_map_odnet_event s).\nProof using name_map_bijective multi_map_lb_congr multi_map_congr.\ncofix c.\nmove => s H_exec.\nrewrite -tot_map_odnet_event_map_unfold {1}/tot_map_odnet_event /=.\ninversion H_exec; subst => /=.\nrewrite -tot_map_odnet_event_map_unfold /= /tot_map_odnet_event /=.\napply: (@Cons_lb_step_exec _ _ _ _ _ _ (List.map tot_map_trace tr)) => /=.\n- apply: lb_step_ordered_dynamic_failure_tot_mapped_simulation_1.\n  have <-: evt_a e = (fst (evt_a e), snd (evt_a e)) by destruct e, evt_a.\n  by have <-: evt_a e' = (fst (evt_a e'), snd (evt_a e')) by destruct e', evt_a.\n- simpl in *.\n  find_rewrite.\n  by rewrite map_app.\n- set e0 := {| evt_a := _ ; evt_l := _ ; evt_trace := _ |}.\n  have ->: e0 = tot_map_odnet_event e' by [].\n  pose s' := Cons e' s0.\n  rewrite (tot_map_odnet_event_map_unfold s').\n  exact: c.\nQed.\n\nLemma tot_map_odnet_label_event_inf_often_occurred :\n  forall l s,\n    inf_often (now (occurred l)) s ->\n    inf_often (now (occurred (tot_map_label l))) (map tot_map_odnet_event s).\nProof using.\nmove => l.\napply: always_map.\napply: eventually_map.\ncase => e s.\nrewrite /= /occurred /=.\nmove => H_eq.\nby rewrite H_eq.\nQed.\n\nLemma tot_map_odnet_label_event_inf_often_occurred_conv :\n  forall l s,\n    inf_often (now (occurred (tot_map_label l))) (map tot_map_odnet_event s) ->\n    inf_often (now (occurred l)) s.\nProof using tot_map_label_injective.\nmove => l.\napply: always_map_conv.\napply: eventually_map_conv => //.\n- rewrite /extensional /=.\n  case => e s1.\n  case => e' s2.\n  move => H_eq.\n  by inversion H_eq; subst_max.\n- rewrite /extensional /=.\n  case => e s1.\n  case => e' s2.\n  move => H_eq.\n  by inversion H_eq; subst_max.\n- case => e s.\n  rewrite /= /occurred /=.\n  move => H_eq.\n  exact: tot_map_label_injective.\nQed.\n\nContext {new_msg_fst : NewMsgParams (@unlabeled_multi_params _ labeled_multi_fst)}.\nContext {new_msg_snd : NewMsgParams (@unlabeled_multi_params _ labeled_multi_snd)}.\nContext {new_msg_map_congr : NewMsgParamsTotalMapCongruency new_msg_fst new_msg_snd msg_map}.\n\nLemma tot_map_odnet_hd_step_ordered_dynamic_failure_star_always : \n  forall s, event_step_star step_ordered_dynamic_failure step_ordered_dynamic_failure_init (hd s) ->\n       lb_step_execution lb_step_ordered_dynamic_failure s ->\n       always (now (event_step_star step_ordered_dynamic_failure step_ordered_dynamic_failure_init)) (map tot_map_odnet_event s).\nProof using overlay_map_congr new_msg_map_congr name_map_bijective multi_map_lb_congr multi_map_congr fail_msg_map_congr.\ncase => e s H_star H_exec.\napply: step_ordered_dynamic_failure_star_lb_step_execution; last exact: lb_step_execution_lb_step_ordered_dynamic_failure_tot_map_odnet_infseq.\nrewrite /= /tot_map_odnet_event /= /event_step_star /=.\napply: step_ordered_dynamic_failure_tot_mapped_simulation_star_1.\nby have <-: evt_a e = (fst (evt_a e), snd (evt_a e)) by destruct e, evt_a.\nQed.\n\nEnd TotalMapExecutionSimulations.\n", "meta": {"author": "uwplse", "repo": "verdi", "sha": "4f1f3ed37e372c05ce0249a93162d0f25e3e20c4", "save_path": "github-repos/coq/uwplse-verdi", "path": "github-repos/coq/uwplse-verdi/verdi-4f1f3ed37e372c05ce0249a93162d0f25e3e20c4/core/TotalMapExecutionSimulations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.2121959391002966}}
{"text": "Require Import msl.msl_standard.\nRequire Import msl.Coqlib2.\nRequire Import msl.rmaps.\nRequire Import msl.rmaps_lemmas.\nRequire Import language.\nRequire Import seplogic.\n\nHint Extern 3 (list_nodups _ = true) => (compute; reflexivity).\nHint Extern 3 (typecheck _ _ = true) => (compute; reflexivity).\nHint Extern 3 (expcheck _ _ = true) => (compute; reflexivity).\nHint Resolve andb_true_intro.\n\nObligation Tactic := idtac.\n\nModule Semax : SEMAX.\n\nLocal Open Scope pred.\n\n(******  CONSTRUCTION OF rmap FOR THE CONT LANGUAGE *****)\nInductive kind := VAL: adr -> kind | FUN: list var -> kind.\n\nModule AV0 <: ADR_VAL0.\n Definition address := adr.\n Definition some_address := 0.\n Definition kind := kind.\nEnd AV0.\n\nModule AV := SimpleAdrVal AV0.\nModule R := Rmaps AV.\nModule RML := Rmaps_Lemmas R.\nExport RML. Export R.\nInstance Cross_rmap : Cross_alg rmap := Cross_rmap_simple (fun _ => I).\n\nObligation Tactic := idtac.\n\n(******  MAPSTO AND RELATED OPERATORS *****)\n\nProgram Definition mapsto (v1 v2: adr) : pred rmap :=\n  fun w => forall i,\n         if eq_dec i v1 then w @ i = YES pfullshare (VAL v2) NoneP else identity (w @ i).\nNext Obligation.\n intros. intros ? ? ? ?.\n  intro i; specialize (H0 i).\n  destruct (eq_dec i v1).\n  apply (age1_YES _ _ _ _ _ H); auto.\n  destruct (identity_resource (a @ i)) as [? _]. specialize (H1 H0).\n  apply identity_resource. \n  generalize (age1_resource_at _ _ H i (a @ i)); intro.\n  generalize (resource_at_approx a i); intro. \n  destruct (a @ i); try contradiction.\n  rewrite H2; simpl in *; auto.\n  rewrite H2; simpl in *; auto.\nQed.\n\nLemma mapsto_conflict:\n   forall a b c, mapsto a b  *  mapsto a c |-- FF.\n  Proof.\n    intros.\n    intros w  [w1 [w2 [? [? ?]]]]; hnf.\n    specialize (H0 a). specialize (H1 a).\n    rewrite if_true in * by auto.\n    apply (resource_at_join _ _ _ a) in H.\n    rewrite H0 in H; rewrite H1 in H; inv H.\n    pfullshare_join.\n Qed.\n\nLemma singleton_rmap_OK: \n   forall v v' m,  \n       resource_fmap (approx (level m))\n            oo (fun i => if eq_dec i v then YES pfullshare (VAL v') NoneP else core m @  i) =\n    (fun i => if eq_dec i v then YES pfullshare (VAL v') NoneP else core m @ i).\nProof.\n  intros; extensionality i; unfold compose; simpl.\n  destruct (eq_dec i v). \n  unfold resource_fmap. f_equal. apply preds_fmap_NoneP.\n  rewrite <- level_core.\n  symmetry; apply resource_at_approx.\nQed.\n\nDefinition singleton_rmap  (v v': adr) (m: rmap) : rmap :=\n  proj1_sig \n  (make_rmap (fun i => if eq_dec i v then YES pfullshare (VAL v') NoneP  else core m @ i ) \n    I (level m) (singleton_rmap_OK _ _ m)).\n\nLemma singleton_rmap_level: forall x y m,\n      level (singleton_rmap x y m) = level m.\nProof. \n  intros.  apply level_make_rmap.\nQed.\n\nLemma singleton_rmap_mapsto:\n   forall x y n, app_pred (mapsto x y) (singleton_rmap x y n).\n Proof.\n  intros. hnf. simpl snd.\n  unfold singleton_rmap.\n  intro; repeat rewrite resource_at_make_rmap.\n  change AV.address with adr.\n destruct (eq_dec i x); auto.\n apply resource_at_core_identity.\nQed.\n\nLocal Open Scope pred.\n\nLemma mapsto_uniq: forall (x y: adr) w w', core w = core w' -> mapsto x y w -> mapsto x y w' -> w=w'.\nProof.\n  intros.\n apply rmap_ext.\n assert (level (core w) = level (core w')) by congruence.\n do 2 rewrite level_core in H2. auto.\n intro. \n specialize (H0 l); specialize (H1 l).\n destruct (@eq_dec adr _ l x); try congruence.\n apply identity_unit_equiv in H0.\n apply unit_core in H0.\n apply identity_unit_equiv in H1.\n apply unit_core in H1.\n rewrite core_resource_at in *. congruence.\nQed.\n\nLemma mapsto_e1: forall v1 v2 w,\n       app_pred (mapsto v1 v2 * TT) w ->\n       w @ v1 = YES pfullshare (VAL v2) NoneP.\nProof.\n intros.\n destruct H as [w1 [w2 [? [? ?]]]].\n hnf in H0.\n specialize (H0 v1).\n apply (resource_at_join _ _ _ v1) in H.\n rewrite if_true in H0 by auto. rewrite H0 in H.\napply join_YES_pfullshare1 in H. inv H; auto.\nQed.\n\nDefinition assert := env -> pred rmap.\nBind Scope pred with assert.\n\n(****** PROGRAM SAFETY AS A SEPARATION-LOGIC PREDICATE *)\n\nProgram Definition cohere (concrete: heap) : pred rmap :=\n fun w =>\n forall p v, heap_get (concrete) p = Some v  <->\n                 w @ p = YES pfullshare (VAL v) NoneP.\nNext Obligation.\n  unfold hereditary; intros.\n  rewrite H0. \n  apply age1_YES; auto.\nQed.\n\n\nProgram Definition assert_safe \n     (p: program) (vars: varset) (ctl: control) : assert :=\n  fun s w => forall s' h, varcompat vars s' -> \n                   locals2env s' = s -> cohere h w -> safeN p (s',h,ctl) (level w).\n Next Obligation.\n  unfold hereditary; intros.\n  eapply safeN_less; [ | apply H0]; auto. subst.\n  apply age_level in H.   rewrite H. change R.rmap with rmap. omega.\n  clear - H H3. hnf in H3|-*. intros. rewrite H3.\n    generalize (age1_YES _ _ p pfullshare (VAL v) H); intros.\n  intuition.\n Qed.\n\nLemma assert_safe0: \n        forall p vars k s w, \n           (forall w', age w w' -> app_pred (assert_safe p vars k s) w) ->\n            app_pred (assert_safe p vars k s) w.\nProof.\n  intros.\n  case_eq (age1 w); intros.\n  apply (H _ H0).\n  hnf; repeat intro.\n  rewrite age1_level0 in H0. rewrite H0. hnf. econstructor; reflexivity.\nQed.\n\n(******* FUNASSERT, MAKE_WORLD ********************)\n\nDefinition funspec := (list var * assert)%type.\nDefinition funspecs := table adr funspec.\n\nDefinition unpack (P: list adr -> pred rmap) (vl: listprod (@cons Type (list adr) nil)):  pred rmap := P (fst vl).\n\nDefinition call (P: list var * assert) (vl: list adr) : pred rmap := \n     (!! (length vl = length (fst P)) && snd P (arguments (fst P) vl)).\n\nProgram Definition cont (nP: funspec)  (v: adr) : pred rmap :=\n  fun w => w @ v = PURE (FUN (fst nP)) (preds_fmap (approx (level w)) (SomeP (list adr::nil) \n             (unpack (call nP)))).\nNext Obligation.\n intros; intro; intros.\n  apply (age1_resource_at a a' H v (PURE (FUN (fst nP)) _));   simpl; auto.\nQed.\n\nDefinition funassert (G: funspecs) : pred rmap := \n   (ALL  i:_, ALL P:_,  !! (table_get G i = Some P) --> cont P i)  && \n   (ALL  i:_, ALL P:_,  cont P i --> !! exists P', table_get G i = Some P').\n\nDefinition make_world_aux (G: funspecs) (h: heap) (n: nat) (a: adr) : resource :=\n   match table_get G a with\n   | Some P => PURE (FUN (fst P))\n                               (preds_fmap (approx n) \n                                      (SomeP (@cons Type (list adr) nil) (unpack (call P))))\n   | None => match heap_get h a with\n                     | Some v => YES pfullshare (VAL v) NoneP\n                     | None => NO\n                    end\n   end.\n\nLemma make_world_aux_OK:\n  forall G h n, \n         resource_fmap (approx n) oo make_world_aux G h n =  make_world_aux G h n.\nProof.\n intros.\n extensionality v; \n unfold make_world_aux, compose.\n destruct (table_get G v). destruct f as [nargs P]. simpl.\n f_equal. f_equal. rewrite <- compose_assoc. rewrite approx_oo_approx. auto.\n destruct (heap_get h v); auto.\n unfold resource_fmap.\n f_equal. apply preds_fmap_NoneP.\nQed.  \n\nDefinition make_world (G: funspecs) (h: heap) (n: nat) : rmap :=\n    proj1_sig (make_rmap (make_world_aux G h n) I n (make_world_aux_OK _ _ _)).\n\nLemma level_make_world:\n  forall h G n, level (make_world G h n) = n.\nProof.\n intros; simpl.\n apply level_make_rmap.\nQed.\n\nInductive match_specs: forall (p: program) (G: funspecs), Prop :=\n| match_specs_nil: match_specs nil nil\n| match_specs_cons: forall i vars f p' P G',\n         not (In i (map (@fst _ _) p')) ->\n         match_specs p' G' ->\n         typecheck vars f = true ->\n         match_specs ((i,(vars,f))::p') ((i,P)::G').\n\nLemma match_specs_boundary:\n   forall p G i, \n   match_specs p G -> i >= boundary p -> table_get G i = None.\nProof.\n  induction 1. intros. reflexivity.\n  intros. simpl in *. \n  destruct (@eq_dec adr _ i i0). subst.\n  clear - H2. destruct (boundary p'). elimtype False; omega.\n generalize (Max.le_max_l i0 n); intro. elimtype False. omega.\n apply IHmatch_specs.\n destruct (boundary p'); try omega.\n generalize (Max.le_max_r i0 n0);  omega.\nQed.\n\nLemma funassert_e:  forall G i f,\n      table_get G i = Some f -> \n      funassert G |-- cont f i.\nProof.\n  intros.\n  unfold funassert.\n  apply andp_left1.\n  intros w ?. apply H0; auto.\nQed.\n\nLemma funassert_make_world: forall p G n,\n         app_pred (funassert G) (make_world G (initial_heap p) n).\nProof.\n intros ? ? ?.\n forget (initial_heap p) as h.\n split.\n intros i P w ? ?.\n hnf in H0.\n eapply pred_nec_hereditary; try apply H.\n clear w H.\n hnf. unfold make_world; simpl. rewrite resource_at_make_rmap.\n unfold make_world_aux. rewrite H0.\n f_equal. simpl. f_equal. rewrite level_make_rmap.\n reflexivity.\n intros i P w ? ?.\n hnf.\n case_eq (table_get G i); intros. eauto.\n elimtype False.\n hnf in H0.\n case_eq (make_world G h n @ i); intros.\n apply (necR_NO _ _ i H) in H2. inversion2 H0 H2.\n apply (necR_YES _ _ i _ _ _ H) in H2. inversion2 H2 H0.\n clear dependent w.\n unfold make_world in H2.\n rewrite resource_at_make_rmap in H2. unfold make_world_aux in H2.\n rewrite H1 in H2. destruct (heap_get h i); inv H2.\nQed.\n\nLemma cohere_make_world: \n  forall p G n,  \n      match_specs p G ->\n     app_pred (cohere (initial_heap p)) (make_world G (initial_heap p) n).\nProof.\n intros.\n hnf.\n intros. unfold make_world, make_world_aux; simpl. rewrite resource_at_make_rmap.\n unfold  initial_heap. simpl. unfold heap_get.\n  rename p0 into i.\n destruct (lt_dec i (boundary p)).\n split; intro. inv H0. elimtype False.\n revert H0; case_eq (table_get G i); intros. destruct f as [nargs P].\n inv H1. inv H1.\n rewrite (match_specs_boundary p G i); auto; try omega.\n split; intro Hx; inv Hx; auto.\nQed.\n\nLemma funassert_get:\n  forall G v nP,  funassert  G && cont nP v |--\n                      EX P':assert, (ALL vl:list adr, |> ! (call nP vl <=> call (fst nP,P') vl)) && !! (table_get G v = Some (fst nP,P')).\nProof.\n intros. intros w [? ?].\n destruct H.\n specialize (H v); specialize (H1 v).\n specialize (H1 _ _ (necR_refl _) H0).\n destruct H1 as [[args P'] ?].\n exists P'.\n specialize (H _ _ (necR_refl _) H1).\n split.\n Focus 2. hnf in H,H0. inversion2 H H0. apply H1.\n clear H1. rename H into H99. rename H0 into H97.\n hnf in H99,H97. rewrite H99 in H97.  apply PURE_inj in H97. destruct H97 as [H H97].\n simpl in H. destruct nP as [na P]. inv H.\n intro vl. intros w' ? w'' ?.\n  assert (level w'' < level w). do 3 red in H. apply laterR_level in H. \n       apply le_lt_trans with (level w'); auto.\n simpl fst.\n  split; intros w''' ? ?.  \n match type of H97 with ?A = _ => assert (app_pred (A (vl,tt)) w''') end.\n  rewrite H97.\n split.\n  change rmap with R.rmap in *.\n  change ag_rmap with R.ag_rmap in *. \n  apply necR_level in H2; omega.\n apply H3.\n  destruct H4. apply H5.\n match type of H97 with _ = ?A => assert (app_pred (A (vl,tt)) w''') end.\n  rewrite <- H97.\n split.\n  change rmap with R.rmap in *.\n  change ag_rmap with R.ag_rmap in *. \n  apply necR_level in H2; omega.\n apply H3.\n  destruct H4. apply H5.\nQed.\n\nLemma cont_core: forall P i w, app_pred (cont P i) w <-> app_pred (cont P i) (core w).\nProof.\n intros.\n unfold cont. simpl. rewrite <- core_resource_at.\n split; intro. rewrite H.\n clear. symmetry. rewrite level_core. apply unit_core; constructor.\n rewrite level_core in H.\n generalize (core_unit (w @ i)); intro.\n rewrite H in H0.\n inv H0; auto.\nQed.\n\nLemma funassert_core: forall G w, app_pred (funassert G) w <-> app_pred (funassert G) (core w).\nProof.\n intros.\n split; intros [? ?]; split; intros i P w' ? ?.\n specialize (H i P _ (necR_refl _) H2).\n apply cont_core in H. eapply pred_nec_hereditary; eauto.\n generalize (core_unit w); intro.\n unfold unit_for in H3.\n eapply nec_join in H3; eauto.\n destruct H3 as [y' [z' [? [? ?]]]].\n generalize (necR_linear' H4 H5); intro.\n spec H6. apply join_level in H3. destruct H3; congruence.\n subst z'. clear H5.\n specialize (H0 i P _ H4).\n apply join_core in H3. rewrite cont_core in H2. rewrite H3 in H2. rewrite <- cont_core in H2.\n specialize (H0 H2). apply H0.\n assert (necR (core w) (core w')).\n generalize (core_unit w); intro.\n unfold unit_for in H3.\n apply join_comm in H3.\n eapply nec_join in H3; eauto.\n destruct H3 as [y' [z' [? [? ?]]]].\n generalize (necR_linear' H1 H5); intro.\n spec H6. apply join_level in H3. destruct H3; congruence. subst z'.\n apply join_comm in H3.\n generalize (unit_identity _ H3); intro.\n apply identity_unit_equiv in H6. apply unit_core in H6.\n apply join_core in H3. rewrite H6 in H4. rewrite H3 in H4; auto.\n specialize (H i P _ H3 H2).\n apply cont_core in H; auto.\n assert (necR (core w) (core w')).\n generalize (core_unit w); intro.\n unfold unit_for in H3.\n apply join_comm in H3.\n eapply nec_join in H3; eauto.\n destruct H3 as [y' [z' [? [? ?]]]].\n generalize (necR_linear' H1 H5); intro.\n spec H6. apply join_level in H3. destruct H3; congruence. subst z'.\n apply join_comm in H3.\n generalize (unit_identity _ H3); intro.\n apply identity_unit_equiv in H6. apply unit_core in H6.\n apply join_core in H3. rewrite H6 in H4. rewrite H3 in H4; auto.\n specialize (H0 i P _ H3).\n apply H0. rewrite <- cont_core; auto.\nQed.\n\n\n(**************** ALLOCPOOL ***************************)\n\n\nProgram Definition allocpool (b: adr) : pred rmap :=\n   fun w => b>0 /\\ forall i, if lt_dec i b then identity (w @ i) else w @ i = YES pfullshare (VAL 0) NoneP.\nNext Obligation.\n intros. intro; intros.\n  destruct H0; split; auto.\n intro i; specialize (H1 i).\n destruct (lt_dec i b).\n  eapply age1_resource_at_identity; eauto.\n apply (age1_YES _ _ _ _ _ H); auto.\nQed.\n\nLemma allocpool_make_world: forall p G n,\n          match_specs p G ->\n          app_pred (allocpool (boundary p)) (make_world G (initial_heap p) n).\nProof.\n  unfold make_world; intros.\n  rename H into H'.\n unfold initial_locals,initial_heap  in *.\n split.\n destruct p; simpl. omega. destruct p. destruct (boundary p0); omega. \n intro loc.\n destruct (make_rmap\n        (make_world_aux G\n           (fun i : adr => if lt_dec i (boundary p) then None else Some 0) n)\n        I n\n        (make_world_aux_OK G\n           (fun i : adr => if lt_dec i (boundary p) then None else Some 0) n)) as [? [? ?]];\n  simpl in *. rewrite e0. unfold make_world_aux.\n unfold heap_get.\n destruct (lt_dec loc (boundary p)).\n destruct (table_get G loc);  apply identity_resource; auto.\n rewrite (match_specs_boundary p G loc); auto.\n omega.\nQed.\n\nLemma alloc: forall b, allocpool b = ((!! (b > 0) && mapsto b 0) * allocpool (S b)).\nProof.\n intros. apply pred_ext.\n  intros w ?.\n destruct H as [H' H]. \n  destruct (deallocate w \n                   (fun i => if lt_dec b i then NO else w @ i) \n                   (fun i => if eq_dec b i then NO else w @ i)\n               I I) as [w1 [w2 [? ?]]].\n intro l; specialize (H l).\n destruct (eq_dec b l). subst. rewrite if_false by omega. rewrite if_false in H by omega.\n rewrite H; constructor.\n destruct (lt_dec b l).\n rewrite if_false in H by omega.\n rewrite H; constructor.\n rewrite if_true in H.\n apply identity_unit_equiv in H. apply H.\n unfold adr in *; omega.\n exists w1; exists w2; split3; auto.\n split; auto.\n intro i. apply (resource_at_join _ _ _ i) in H0. specialize (H i). rewrite H1 in *.\n clear w1 H1.\n destruct (lt_dec b i).\n rewrite if_false by omega. apply NO_identity.\n destruct (eq_dec i b). subst. rewrite if_false in H by omega. auto.\n rewrite if_true in H. auto.\n unfold adr in *; omega.\n split. omega.\n intro i. apply (resource_at_join _ _ _ i) in H0. specialize (H i). rewrite H1 in *.\n clear w1 H1.\n destruct (lt_dec b i).\n rewrite if_false by omega. rewrite if_false in H by omega. rewrite H in H0. inv H0; auto.\n rewrite if_true by omega.\n destruct (eq_dec i b). subst. rewrite if_false in H by omega. rewrite H in H0; inv H0; auto.\n apply NO_identity. pfullshare_join.\n rewrite if_true in H by (unfold adr in *; omega).\n apply H in H0. rewrite H0; auto.\n\n  intros w [w1 [w2 [? [? ?]]]].\n  destruct H0 as [H0' H0]. destruct H1 as [_ H1].\n split; auto.\n  intro i. specialize (H0 i); specialize (H1 i). apply (resource_at_join _ _ _ i) in H.\n  destruct (lt_dec i b). rewrite if_true in H1 by omega.\n  rewrite if_false in H0 by omega. apply H0 in H. rewrite <- H; auto.\n  destruct (@eq_dec adr _ i b). subst. rewrite H0 in H. rewrite if_true in H1 by omega.\n  apply join_comm in H. apply H1 in H. auto.\n  rewrite if_false in H1. rewrite H1 in H. apply H0 in H. auto.\n  unfold AV.address, AV0.address, adr in *. omega.\nQed.\n\nRequire msl.seplog msl.alg_seplog.\nDefinition mpred : Type := predicates_hered.pred rmap.\nInstance Nm: seplog.NatDed mpred := alg_seplog.algNatDed rmap.\nInstance Sm: seplog.SepLog mpred := alg_seplog.algSepLog rmap.\nInstance Cm: seplog.ClassicalSep mpred := alg_seplog.algClassicalSep rmap.\nInstance Im: seplog.Indir mpred := alg_seplog.algIndir rmap.\nInstance Rm: alg_seplog.RecIndir mpred := alg_seplog.algRecIndir rmap.\nInstance SIm: seplog.SepIndir mpred := alg_seplog.algSepIndir rmap.\nInstance SRm: alg_seplog.SepRec mpred := alg_seplog.algSepRec rmap.\n\nDefinition guard (p: program) (G: funspecs) (vars: varset) (P : assert) (k: control) : pred nat :=\n     ALL s:env, P s && funassert G >=> assert_safe p vars k s.\n\nRecord semaxArg :Type := SemaxArg {\n sa_vars: varset;\n sa_P: assert;\n sa_c: control\n}.\n\nDefinition believe (semax: semaxArg -> pred nat) \n      (p: program) (P: funspec) (f: adr) : pred nat :=\n      EX k: list var * control, \n        !!(table_get p f = Some k /\\ length (fst k) = length (fst P) /\\ list_norepet (fst k)) &&\n      |> semax (SemaxArg (fst k) (fun s => call P (map s (fst k))) (snd k)).\n\nDefinition believe_all (semax: semaxArg -> pred nat) (G: funspecs) (p: program) (G': funspecs) : pred nat :=\n  ALL v:adr, ALL args: list var, ALL P: assert,\n     !! (table_get G' v = Some (args,P)) -->\n     believe semax p (args, fun s => P s && funassert G) v.\n\nDefinition semax_ (semax: semaxArg -> pred nat) (a: semaxArg) : pred nat :=\n match a with SemaxArg vars P c =>\n     ALL p: program, ALL G: funspecs, believe_all semax G p G --> guard p G vars P c\n  end.\n\nLemma prop_imp {A}{agA: ageable A}: \n  forall (P: Prop) (Q: pred A) w, (P -> app_pred Q w) -> app_pred (!!P --> Q) w.\nProof. repeat intro. specialize (H H1). eapply pred_nec_hereditary; eauto.\nQed.\n\n\nLemma HOcontractive_semax_ : HOcontractive semax_.\nProof.\n  auto 50 with contractive.\nQed.\n\nDefinition semax'  := HORec semax_.\n\nLemma semax'_unfold: forall vars P c,\n     semax' (SemaxArg vars P c) = \n         ALL p: program, ALL G:funspecs, believe_all semax' G p G --> guard p G vars P c.\nProof.\n  intros. \n  unfold semax' at 1. rewrite HORec_fold_unfold; auto.\n  apply HOcontractive_semax_.\nQed.\n\nDefinition semax vars (G: funspecs) (P: assert) (k: control) : Prop := \n       typecheck vars k = true /\\ forall n,  semax' (SemaxArg vars (fun s => P s && funassert G) k) n.\n\nDefinition semax_func (G: funspecs) (p: program) (G': funspecs) :=\n    match_specs p G' /\\ \n    forall n, believe_all semax' G p G' n.\n\nLemma semax_func_nil: forall G, semax_func G nil nil.\nProof. split; repeat intro. constructor. inv H0. Qed.\n\nLemma semax_func_cons: \n   forall  fs id f vars P (G G': funspecs),\n      inlist id (map (@fst adr (list var * control)) fs) = false ->\n      list_nodups vars = true ->\n      length vars = length (fst P) ->\n      semax vars G (fun s => call P (map s vars)) f ->\n      semax_func G fs G' ->\n      semax_func G ((id, (vars,f))::fs) ((id, P) :: G').\nProof.\nintros until G'. intros H0 H Hlen ? ?.\napply inlist_notIn in H0.\ndestruct H2.\nsplit.\nconstructor; auto.\ndestruct H1; auto.\nintro.\nspecialize (H3 n).\nintros b nargs' Q.\nspecialize (H3 b nargs' Q).\nintros ? ? ?.\ndestruct (eq_dec id b).\nsubst.\nFocus 2.\nspecialize (H3 _ H4).\nspec H3.\nclear - H5 n0.\nhnf in H5|-*.\nunfold table_get  in H5; fold @table_get in H5.\nrewrite if_false in H5; auto.\nclear H5.\ndestruct H3 as [k [? ?]]; exists k; split; auto.\nunfold table_get; fold @table_get.\nrewrite if_false; auto.\n(* End Focus 2 *)\nunfold table_get in H5; fold @table_get in H5.\nrewrite if_true in H5; auto.\nsimpl in H5.\ninv H5.\nexists (vars,f).\nsplit.\nsimpl.\nrewrite if_true; auto. split; auto. split; auto. apply nodups_norepet. auto.\nsimpl fst; simpl snd.\nhnf; intros.\ndestruct H1 as [_ H1].\nspecialize (H1 a'0).\nreplace (fun s : env =>\n           call (nargs', fun s0 : env => Q s0 && funassert G) (map s vars))\n with (fun s : env => call (nargs', Q) (map s vars) && funassert G).\napply H1.\nextensionality s. forget (map s vars) as vl.\nclear.\napply pred_ext; intros ? ?.\ndestruct H as [[? ?] ?].\nsplit. apply H. simpl snd in *. split; auto.\ndestruct H. simpl fst in *; simpl snd in *.\ndestruct H0; split; auto. split; auto.\nQed.\n\nLemma semax_G:\n   forall vars G P c, semax vars G (fun s => P s && funassert G) c -> semax vars G P c.\nProof. \n  intros. destruct H; split; auto.\n  intro; specialize (H0 n).\n  replace (fun s : env => P s && funassert G) with (fun s : env => P s && funassert G && funassert G);\n       auto.\n  extensionality s.\n  rewrite andp_assoc. f_equal. apply andp_dup.\nQed.\n\nLemma semax_go:  forall vars G (P: funspec) x ys,   \n    typecheck vars (Go x ys) = true ->\n    semax vars G (fun s => cont P (eval x s) && call P (eval_list ys s)) (Go x ys) .\nProof.\n intros. rename H into TC.\n  split; auto.\n   intro n; hnf.\n   rewrite semax'_unfold.\n  intros p G0.\n  hnf. intros n' ? ?.\n  clear n H.\n  intros s w ? w' ?.\n  rewrite andp_assoc.\n  intros [[H4 H5] [_ GUARDIAN]].\n  pose (H3:=True).\n  clear G. rename G0 into G.\n  remember (eval x s) as v'.\n  destruct (funassert_get G v' P w') as [P' [H2 H2']].\n  split; auto.\n  generalize (H0 _ _ _ _ (necR_refl _) H2'); intro. clear H2'.\n  destruct H6 as [[formals k] [[H6 [H6' H6'']] ?]]. \n  hnf in H6.\n rewrite semax'_unfold in H7.\n  apply assert_safe0; intros w'' Hw''.\n  assert (LATER: laterR n' (level w'')).\n    apply later_nat; apply necR_level in H1; apply age_level in Hw''.\n   unfold R.rmap in *; omega. specialize (H2 (eval_list ys s)).\n  red in H2. red in H2. red in H2.\n  specialize (H2 _ (t_step _ _ _ _ Hw'' )).\n  specialize (H7 _ LATER).\n  apply (pred_nec_hereditary _ _ _ (laterR_necR LATER)) in H0.\n  specialize (H7 p G _ (necR_refl _) H0). clear H0.\n  simpl fst in *. simpl snd in *.\n  do 3 red in H2.\n  apply (pred_hereditary _ _ _ Hw'') in H5.\n  specialize (H2 _ (le_refl _)).\n  specialize (H7 (locals2env (mk_locals formals (eval_list ys s))) _ (le_refl _) _ (necR_refl _)).\n  clear n' H LATER.\n  intros ? ? VC L H. rewrite <- L in *. clear L s. rename s' into s.\n  assert (step p (s,h, Go x ys) = Some ((mk_locals formals (eval_list ys (locals2env s)), h), k)).\n  simpl.\n  simpl typecheck in TC.\n  rewrite andb_true_iff in TC; destruct TC as [TC1 TC2].\n  rewrite (eval_expr_get vars s h x); auto. rewrite <- Heqv'.\n  simpl. rewrite H6.  simpl. \n  rewrite (eval_expr_get_list vars s h ys); auto.\n  rename Hw'' into H12.\n  rewrite (age_level _ _ H12).\n  rewrite (safeN_step _ _ _ _ H0).\n  clear w H1.\n  pose (H11:=True).\n  spec H7.\n  eapply pred_hereditary in GUARDIAN; eauto.\n  split; auto.\n  split.\n  hnf. rewrite map_length. simpl fst. auto.\n  split; auto.\n  destruct H2 as [? _]. \n  specialize (H1 _ (necR_refl _) H5).\n  simpl.\n  unfold call in H1. simpl in H1.\n  Transparent arguments.\n  unfold arguments in *.\n  Opaque arguments.\n  replace (map (locals2env (mk_locals formals (eval_list ys (locals2env s)))) formals)\n     with (eval_list ys (locals2env s)); [ apply H1 | ].\n  destruct H5 as [Hlen H5]. hnf in Hlen.\n  assert (length (eval_list ys (locals2env s)) = length formals).\n    rewrite H6'. auto.\n  forget (eval_list ys (locals2env s)) as vs.\n  clear - H2 H6''.\n  revert vs H2; induction H6''; intros; destruct vs; inv H2; simpl; auto.\n  f_equal. unfold locals2env; simpl. rewrite if_true by auto. auto.\n pattern vs at 1; rewrite (IHH6'' vs) by auto.\n forget (mk_locals tl vs) as y.\n clear - H. induction tl; simpl; auto. f_equal; simpl.\n unfold locals2env; simpl.\n rewrite if_false by (contradict H; simpl in *; intuition). auto.\n apply IHtl. intuition.\n  apply H7; auto.\n  apply varcompat_mk_locals. unfold eval_list. rewrite map_length. rewrite H6'; auto.\n  destruct H5 as [H5 _]; hnf in H5.\n  rewrite <- H5.\n  clear. induction ys; simpl; omega.\n  eapply pred_hereditary; eauto.\nQed.\n\nLemma semax_assign: forall x y c vars G P,\n    expcheck vars y = true ->\n    semax (vs_add x vars) G P c -> \n    semax vars G (fun s => |> subst x (eval y s) P s) (Do x := y ; c).\nProof.\n intros until P; intros TC [TC' ?].\n split.\n simpl in *. destruct y; inv TC; simpl; auto; try rewrite TC'; try rewrite H1; auto.\n intro; intros.\n unfold subst.\n rewrite semax'_unfold.\n intros p G' n' ? ? s w ? w' ? [[H6 H6'] H4].\n pose (H5:=True).\n apply assert_safe0; intros w'' ?.\n intros s' h VC L ?. rewrite <- L in *; clear L s; rename s' into s.\n generalize (age_level _ _ H7); intro. rewrite H9.\n apply (pred_hereditary _ _ _ H7) in H8.\n specialize (H6 _ (t_step _ _ _ _ H7)).\n apply (pred_hereditary _ _ _ H7) in H4.\n assert (necR n' (level w')). apply necR_trans with (level w); auto.\n apply nec_nat. auto. apply necR_level'. auto.\n apply (pred_nec_hereditary _ _ _ H10) in H1.\n clear n' w H3 H2 H0 H10.\n hnf in H5.\n assert (step p ((s,h), Do (Var x) := y; c) = Some ((table_set x (eval y (locals2env s)) s, h), c)).\n simpl. rewrite (eval_expr_get vars s h y); auto.\n apply (safeN_step _ _ _ _ H0).\n  specialize (H (@level _ ag_rmap w')). rewrite semax'_unfold in H.\n specialize (H p G' _ (necR_refl _) H1).\n specialize (H (locals2env (@table_set var _ EqDec_var x (eval y (locals2env s)) s))).\n specialize (H w''). spec H; [rewrite H9; omega | ].\n specialize (H _ (necR_refl _)).\n spec H. split; auto. \n replace  (locals2env (table_set x (eval y (locals2env s)) s))\n   with (env_set (locals2env s) x (eval y (locals2env s))); auto.\n  split; [ auto | eapply pred_hereditary; eauto]. \n  clear.\n   extensionality i. unfold env_set. unfold locals2env at 3.\n   destruct (eq_dec i x). subst. rewrite table_gss; auto. rewrite table_gso; auto.\n apply H; auto.\n  clear - VC.\n  intros i ?. destruct (eq_dec i x). subst. rewrite table_gss. congruence.\n  rewrite table_gso by auto. apply (VC i).\n  unfold vs_mem in H. apply ListSet.set_mem_correct1 in H.\n  apply ListSet.set_mem_correct2. unfold vs_add in H.\n  apply ListSet.set_add_elim2 in H; auto.\nQed.\n\nLemma semax_if: forall x c1 c2 vars G (P: assert),\n    expcheck vars x = true ->\n    semax vars G (fun s => !!(eval x s <> 0) && P s) c1 ->\n    semax vars G (fun s => !! (eval x s = 0) && P s) c2 ->\n    semax vars G P (If x Then c1 Else c2).\nProof.\n intros. rename H into TC.\n destruct H0 as [TC0 H]; destruct H1 as [TC1 H'].\n split.\n simpl; auto.\n intro.\n rewrite semax'_unfold.\n intros p G' n' ? ? s w ? w' ? [H5 H4].\n pose (H6:=True).\n apply assert_safe0; intros w'' ?.\n intros s' h VC L ?. rewrite <- L in *; clear L s; rename s' into s.\n generalize (age_level _ _ H7); intro. rewrite H9.\n destruct (eq_dec (eval x (locals2env s)) 0).\n (* zero *)\n clear H; rename H' into H.\n subst.\n assert (step p ((s,h), If x Then c1 Else c2) = Some ((s,h), c2)).\n simpl. rewrite (eval_expr_get vars s h x); auto.\n rewrite e; simpl; auto.\n apply (safeN_step _ _ _ _ H10).\n specialize (H n'). rewrite semax'_unfold in H.\n assert (necR n' (level w')). apply necR_trans with (level w); auto.\n apply nec_nat. auto. apply necR_level'. auto.\n specialize (H p G' _ H11 (pred_nec_hereditary _ _ _ H11 H1)).\n specialize (H (locals2env s) w'').\n spec H. omega.\n specialize (H _ (necR_refl _)).\n spec H.\n  rewrite andp_comm.\n split. eapply pred_hereditary; eauto.\n apply (pred_hereditary _ _ _ H7) in H5.\n rewrite andp_assoc; split; [ |  apply H5].\n hnf; auto.\n apply H; auto.\n apply (pred_nec_hereditary _ _ _ (rt_step _ _ _ _ H7)); auto. \n (* nonzero *)\n subst.\n assert (step p ((s,h), If x Then c1 Else c2) = Some ((s,h), c1)).\n simpl. rewrite (eval_expr_get vars s h x); auto. simpl.  rewrite if_false; auto.\n apply (safeN_step _ _ _ _ H10).\n specialize (H n'). rewrite semax'_unfold in H.\n assert (necR n' (level w')). apply necR_trans with (level w); auto.\n apply nec_nat. auto. apply necR_level'. auto.\n specialize (H p G' _ H11 (pred_nec_hereditary _ _ _ H11 H1)).\n specialize (H (locals2env s) w'').\n spec H. omega.\n specialize (H _ (necR_refl _)).\n spec H.\n rewrite andp_comm.\n split. eapply pred_hereditary; eauto.\n apply (pred_hereditary _ _ _ H7) in H5.\n rewrite andp_assoc; split; [ |  apply H5].\n hnf; auto.\n apply H; auto.\n apply (pred_nec_hereditary _ _ _ (rt_step _ _ _ _ H7)); auto. \nQed.\n\nLemma semax_load: forall x y z c vars G P,\n    expcheck vars y = true ->\n    semax (vs_add x vars) G P c -> \n    semax vars G (fun s => ((mapsto (eval y s) z) * TT) && |> subst x z P s)\n               (Do x := Mem y ; c).\nProof.\n intros until P. intros TC [TC' ?].\n split.\n simpl; auto.\n intro n.\n rewrite semax'_unfold.\n intros p G' n' ? ? s w ? w' ? [H5 H4].\n destruct H5 as [[? HP] HG].\n unfold subst in HP.\n apply assert_safe0; intros w'' H7.\n specialize (HP _ (t_step _ _ _ _ H7)).\n intros s' h VC L ?. rewrite <- L in *; clear s L; rename s' into s.\n generalize (age_level _ _ H7); intro. rewrite H8.\n assert (step p ((s,h), Do x := Mem y; c) = Some ((table_set x z s, h), c)).\n simpl. rewrite (eval_expr_get vars s h y); auto. simpl.\n replace (heap_get h (eval y (locals2env s))) with (Some z).\n auto.\n symmetry.\n apply H6. apply mapsto_e1; auto.\n apply (safeN_step _ _ _ _ H9). clear H9.\n specialize (H n'). rewrite semax'_unfold in H.\n assert (necR n' (level w')). apply necR_trans with (level w); auto.\n apply nec_nat. auto. apply necR_level'. auto.\n specialize (H p G' _ H9 (pred_nec_hereditary _ _ _ H9 H1)).\n specialize (H (locals2env (@table_set _ _ EqDec_var x z s)) w'').\n spec H.    unfold R.rmap in *; omega. \n specialize (H _ (necR_refl _)).\n spec H. split; [split|].\n  rewrite locals2env_table_set. eauto.\n  eapply pred_hereditary; eauto.\n  eapply pred_hereditary; eauto.\n apply H; auto.\n apply varcompat_add; auto.\n eapply pred_hereditary; eauto.\nQed.\n\nLemma semax_store: forall x y v c vars G (P: assert),\n    expcheck vars x = true ->\n    expcheck vars y = true ->\n    semax vars G (fun s => mapsto (eval x s) (eval y s) * P s) c ->\n    semax vars G (fun s => mapsto (eval x s) v  * P s)  (Do Mem x  := y ; c).\nProof.\n intros until P; intros TCx TCy [TC ?].\n split.\n simpl; auto.\n intro. rewrite semax'_unfold.\n intros p G' n' ? ? s w ? w' ? [[H5 H6] H4].\n apply assert_safe0; intros w'' ?.\n intros s' h VC L ?. rewrite <- L in *; clear L s; rename s' into s.\n generalize (age_level _ _ H7); intro. rewrite H9.\n assert (step p ((s,h), Do Mem x := y; c) = Some ((s, heap_set (eval x (locals2env s)) (eval y (locals2env s)) h), c)).\n simpl. rewrite (eval_expr_get vars s h y); auto. rewrite (eval_expr_get vars s h x); auto.\n apply (safeN_step _ _ _ _ H10).\n specialize (H n'). rewrite semax'_unfold in H.\n assert (necR n' (level w')). apply necR_trans with (level w); auto.\n apply nec_nat. auto. apply necR_level'. auto.\n specialize (H p G' _ H11 (pred_nec_hereditary _ _ _ H11 H1)).\n apply (pred_hereditary _ (level w') (level w'')) in H;\n   [ |  apply age_level in H7; rewrite H7; hnf; simpl; auto].\n apply (pred_hereditary _ _ _ H7) in H5.\n apply (pred_hereditary _ _ _ H7) in H6.\n apply (pred_hereditary _ _ _ H7) in H4.\n apply (pred_hereditary _ _ _ H7) in H8.\n clear H1; pose (H1:=True). clear n H0. pose (H0:=True).\n clear n' H2 H11. pose (H2:=True). pose (H11:=True).\n simpl in H8.\nclear w' H7 H9 H3. \n pose (H7:=True); pose (H9:=True); pose (H3:=True).\n clear H0 H1.\n destruct H5 as [wa [wb [H0 [HP H1]]]].\n pose (m' := singleton_rmap (eval x (locals2env s)) (eval y (locals2env s)) w'').\n assert (joins m' wb).\n apply resource_at_joins2. unfold m'.\n rewrite singleton_rmap_level.\n apply join_level in H0. destruct H0. auto.\n unfold m'. intro i.\n clear - HP H0.\n apply (resource_at_join _ _ _ i) in H0.\n specialize (HP i).\n unfold singleton_rmap. rewrite resource_at_make_rmap.\n destruct (eq_dec i (eval x (locals2env s))). subst; rewrite if_true in HP; auto.\n exists (YES pfullshare (VAL (eval y (locals2env s))) NoneP).\n rewrite HP in *. inv H0; try pfullshare_join. constructor.\n rewrite if_false in HP by auto. \n exists (wb @ i). \n apply HP in H0. rewrite H0.\n rewrite <- core_resource_at. apply core_unit.\n destruct H5 as [ww H12].\n replace (level w'') with (level ww) in H.\n Focus 2.\n transitivity (level wb).\n apply join_level in H12. destruct H12 as [H12 H13]. symmetry ; apply H13.\n apply join_level in H0; destruct H0; auto.\n specialize (H (locals2env s) ww).\n spec H. simpl. apply le_refl.\n specialize (H _ (necR_refl _)).\n spec H. rewrite andp_assoc. rewrite andp_comm.\n clear - H4 H0 HP H12 H6 H1.\n assert (app_pred ((mapsto (eval x (locals2env s)) v * TT) && (funassert G && funassert G')) w'').\n split; auto. exists wa; exists wb; split3; auto. split; auto.\n destruct H as [? _].\n split.\n apply join_comm in H0. apply join_comm in H12. apply join_core in H0. apply join_core in H12.\n apply funassert_core in H6. apply funassert_core in H4. rewrite H12 in H0.\n split; apply funassert_core; rewrite H0; auto.\n destruct H as [wa' [wb' [? [? ?]]]].\n assert (wa' = wa). eapply mapsto_uniq; eauto.\n apply join_core in H0; apply join_core in H. rewrite H0; rewrite H. auto. \n subst wa'. generalize (join_canc (join_comm H0) (join_comm H)); intro; subst wb'.\n  generalize (singleton_rmap_mapsto (eval x (locals2env s)) (eval y (locals2env s)) w''); intro.\n assert (app_pred (mapsto (eval x (locals2env s)) (eval y (locals2env s)) * (TT && (funassert G && funassert G'))) ww).\n exists m'; exists wb; split3; auto.\n split; auto.\n apply join_comm in H0. apply join_comm in H12. apply join_core in H0. apply join_core in H12.\n  apply funassert_core in H6. apply funassert_core in H4.\n split; apply funassert_core; rewrite H0; auto.\n exists m'; exists wb; split3; auto.\n replace (level w'') with (level ww).\n Focus 2. simpl. transitivity (level wb).\n clear - H12; apply join_level in H12; destruct H12; symmetry; apply H0.\n clear - H0; apply join_level in H0; destruct H0; apply H0.\n apply H; auto.\n intros i v0. specialize (HP i).\n simpl.\n apply (resource_at_join _ _ _ i) in H12.\n unfold m' in *; clear m'.\n unfold singleton_rmap in H12.\n rewrite resource_at_make_rmap in H12.\n change AV.address with adr in H12.\n  specialize (H8 i v0). simpl in H8. \n\n  destruct (eq_dec i (eval x (locals2env s))). \n  subst. rewrite heap_gss.\n  apply join_unit2_e in H12. rewrite <- H12.\n  split; intro Hx; inv Hx; auto.\n  apply YES_join_full in H12; auto.\n  rewrite H12. apply NO_identity.\n  apply join_unit1_e in H12; [ | rewrite <- core_resource_at; apply core_identity].\n  rewrite heap_gso; auto. \n apply (resource_at_join _ _ _ i) in H0.\n rewrite <- H12.\n apply HP in H0. rewrite H0; auto.\nQed.\n\nLemma semax_pre: \n  forall P P' vars G c, (forall s, P s |-- P' s) -> semax vars G P' c -> semax vars G P c.\nProof.\n intros. destruct H0 as [TC H0]; split; auto.\n intro n; specialize (H0 n).\n rewrite semax'_unfold in *.\n intros p G'. specialize (H0 p G').\n intros n' ? ?. specialize (H0 _ H1 H2).\n intros s w ? ? ? ?. specialize (H0 s _ H3 _ H4).\n apply H0.\n destruct H5; split; auto. destruct H5;  split; auto. apply H; auto.\nQed.\n\n\nLemma semax_exp: forall {A} vars G (P: A -> assert) c,\n    typecheck vars c = true ->\n    (forall v:A, semax vars G (P v) c) ->\n    semax vars G (fun s => EX v:A, (P v s)) c.\nProof.\n intros ? ? ? ? ? TC ?.\n split; auto. \n intro.\n rewrite semax'_unfold.\n intros p G'. intros n' ? ?.\n intros s. intros ? ?. intros ? ?. intros [[[v ?] ?] ?].\n specialize (H v). destruct H as [_ H].\n rewrite semax'_unfold in H. eapply H; eauto. split; auto. split; auto.\nQed.\n\nLemma semax_exp': forall {A} (any: A) vars G (P: A -> assert) c,\n    (forall v:A, semax vars G (P v) c) ->\n    semax vars G (fun s => EX v:A, (P v s)) c.\nProof.\n intros ? ? ? ? ? ?.\n split; auto. \n destruct (H any); auto.\n intro.\n rewrite semax'_unfold.\n intros p G'. intros n' ? ?.\n intros s. intros ? ?. intros ? ?. intros [[[v ?] ?] ?].\n specialize (H v). destruct H as [_ H].\n rewrite semax'_unfold in H. eapply H; eauto. split; auto. split; auto.\nQed.\n\nLemma semax_prop:\n  forall (R: Prop) vars G P c,\n      typecheck vars c = true ->\n      (R -> semax vars G P c) ->\n      semax vars G (fun s => !! R && P s) c.\nProof.\n  intros R vars G P c TC ?. split; auto. intro n.  rewrite semax'_unfold. intros p G'.\n  intros n' ? ? b w ? w' ? [[[? ?] ?] ?].\n  destruct (H H4).\n  specialize (H9 n). rewrite semax'_unfold in H9.\n  eapply H9; eauto. split; auto. split; auto.\nQed.\n\nDefinition program_proved (p: program) :=\n   exists G, semax_func G p G  /\\ table_get G 0 = Some (0::nil, fun s => allocpool (eval (Var 0) s)).\n\nLemma semax_sound: \n  forall p, program_proved p -> forall n, run p n <> None.\nProof.\n  intros.\n  destruct H as [G [[? ?] ?]].\n  generalize (funassert_make_world p G n); intro.\n  destruct (semax_go nil G  (0::nil, fun s => allocpool (eval (Var 0) s))\n                (Const 0) (Const (boundary p) :: nil) (eq_refl _)) as [_ ?].\n  specialize (H3 n).\n  rewrite semax'_unfold in H3.\n  specialize (H3 p G _ (necR_refl _) (H0 _) (locals2env nil) \n                    (make_world G (initial_heap p) n)).\n  spec H3. rewrite level_make_world. auto.\n  specialize (H3 _ (necR_refl _)).\n  spec H3.\n  split; auto.\n  split; auto.\n  split.\n  apply (funassert_e _ _ _ H1 _ H2).\n  unfold call.\n  Transparent arguments. unfold arguments. Opaque arguments.\n  simpl snd.\n  unfold locals2env, table_get. rewrite if_true; auto.\n  split. simpl; auto.\n  apply allocpool_make_world; auto.\n  hnf in H3.\n  specialize (H3 nil (initial_heap p)).\n  spec H3. intros i ?. inv H4.\n  spec H3. auto.\n  spec H3. apply cohere_make_world; auto.\n  unfold run; intro.\n  destruct H3 as [sk' ?].\n  rewrite level_make_world in H3. \n unfold locals,table, var,adr in H3,H4. rewrite H3 in H4; inv H4.\nQed.\n\nEnd Semax.\n", "meta": {"author": "abakst", "repo": "art-theory", "sha": "a51e8b5e00cbeb0cfec9815e179ff0d69eb4a27f", "save_path": "github-repos/coq/abakst-art-theory", "path": "github-repos/coq/abakst-art-theory/art-theory-a51e8b5e00cbeb0cfec9815e179ff0d69eb4a27f/vst/examples/cont/model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.21219593807007364}}
{"text": "\n\nSection OBSOLETE.\nImport Classical_Prop Classical_Pred_Type.\nTheorem OrdPair_inj_left :\n forall a b c d : Ens, EQ (OrdPair a b) (OrdPair c d)->(EQ a c/\\EQ b d).\nProof.\nunfold OrdPair in |- *.\nintros.\n  assert (e2 : EQ (Paire (Sing a) (Paire a a)) \n                  (Sing  (Sing a)) ).\n   repeat apply Paire_sound_right. apply EQ_refl.\ndestruct (classic (EQ a b)).\n+ assert (e1 : EQ (Paire (Sing a) (Paire a b)) \n                  (Paire (Sing a) (Paire a a))).\n   repeat apply Paire_sound_right. apply EQ_sym; assumption.\n\n  assert (e3 := EQ_tran _ _ _ e1 e2).\n  assert (e4 := EQ_tran _ _ _ (EQ_sym _ _ e3 ) H).\n(*assert (j: EQ (Sing (Sing a)) (Paire (Sing c) (Paire c d))).\napply Paire_sound.*)\n  apply SingEqPair in e4 as [H1 H2].\n  (*apply SingEqPair in H1 as [Ha1 Ha2].*)\n  apply SingEqPair in H2 as [P1 P2].\n  split. assumption. apply EQ_tran with (E2:=a). apply EQ_sym, H0.\n  apply P2.\n+ assert (e1: IN (Paire c d) (Paire (Sing c) (Paire c d))).\n   auto with zfc.\n  apply IN_sound_right with (1:=EQ_sym _ _ H) in e1.\n  apply Paire_IN in e1 as [A1|A2].\n  - apply EQ_sym , SingEqPair in A1 as [B1 B2].\n  split. exact B1.\n  assert (e23:EQ (Paire (Sing c) (Paire c d)) (Paire (Sing a) (Paire a a))).\n   apply Paire_sound.\n   apply Sing_sound, EQ_sym, B1.\n   apply Paire_sound; apply EQ_sym; assumption.\n  assert(K:=EQ_tran _ _ _ e23 e2).\n  assert(R:=EQ_tran _ _ _ H K). apply EQ_sym in R.\n  apply SingEqPair in R as [R1 R2].\n  apply SingEqPair in R2 as [R2 R3].\n  destruct (H0 R3).\n - apply Paire_EQ_cases in A2 as [[q1|q2] [q3|q4]].\n(* [v1 v2].\n   destruct (classic (EQ a c)).\n   split. assumption.\n   destruct (classic (EQ b d)).\n   \n  - \napply Paire_IN in A2 as [B1|B2].\n(*  assert (e2: EQ (Paire (Sing c) (Paire c d)) (Paire (Sing a) (Paire c d))).\n  apply Paire_sound_left.\n  apply Sing_sound, EQ_sym, B1.\n  assert (e3: EQ (Paire (Sing a) (Paire c d)) (Paire (Sing a) (Paire a a))).\n*)\n\n  apply Sing_sound. EQ_sym, B1.\nunshelve eapply EQ_tran (E2:=) in H.\n!!!\napply EQ_tran\napply axExt; intro z; split; intro q.\n simpl in |- *. *)\n Abort.\nEnd OBSOLETE.", "meta": {"author": "georgydunaev", "repo": "Jech", "sha": "f9cc87376d82c4e2ba4d2adcea2352ebb433e8e3", "save_path": "github-repos/coq/georgydunaev-Jech", "path": "github-repos/coq/georgydunaev-Jech/Jech-f9cc87376d82c4e2ba4d2adcea2352ebb433e8e3/purgatorium/trash00.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.3106943895971202, "lm_q1q2_score": 0.2120718257558479}}
{"text": "(* From Undecidability.Shared.Libs.PSL Require Import FinTypes Vectors.\nFrom Undecidability.L Require Import TM.TMinL.TMinL_extract.\nFrom Undecidability.TM Require Import Compiler_facts Compiler_spec. *)\nFrom Undecidability.L.Datatypes Require Import LNat Lists LProd LFinType LVector.\nFrom Undecidability.L Require Import Functions.FinTypeLookup Functions.EqBool.\nFrom Undecidability Require Import TMEncoding.\n\nRequire Import Undecidability.L.TM.TMinL.TMinL_extract.\nRequire Import Undecidability.L.Functions.UnboundIteration.\nFrom Undecidability.TM Require Import TM TM_alt TM_facts.\nRequire Import Undecidability.L.Util.L_facts.\nFrom Undecidability.L.Datatypes Require Import LNat.\n\nImport L_Notations.\n\nNotation PAIR := (lam (lam (lam (0 2 1)))).\nNotation PAIR_ x y := (lam (0 x y)).\n\nSection TimeInvarianceNF.\n\nImport HOAS_Notations.\n\nVariable Σ : finType.\n\nLet reg_sig := @encodable_finType Σ.\nExisting Instance reg_sig.\n\nVariable n_tps : nat.\n\nDefinition s_sim : term := Eval cbn -[enc] in [L_HOAS (λ M_q0 tps, ha M_q0 (λ M q0, !!uiter M (!!PAIR q0 tps)))]. \n\nVariable M : TM Σ n_tps.\nVariables (q q' : state M) (t t' : tapes Σ n_tps).\n\nLet reg_state := @encodable_finType (state M).\nExisting Instance reg_state.\n\nDefinition step_fun := (fun cfg : mconfig Σ (state M) n_tps =>\n                          if haltConf cfg then inr (ctapes cfg) else inl (TM_facts.step cfg)).\n\nNotation STEPTIME := (haltTime M + n_tps* 130+ transTime M + 185). \n\nInstance step_fun_comp : computableTime' step_fun (fun _ _ => (STEPTIME,tt)).\nProof.\n  extract. solverec. \nQed.\n\nLemma TimeInvarianceNF_forward i :\n    loopSumM (M := M) (mk_mconfig q t) i = Some (mk_mconfig q' t') ->\n    evalLe (7 + i * (STEPTIME + 11) ) (s_sim (PAIR_ (ext step_fun) (enc q)) (enc t)) (enc t').\nProof.\n  intros H.\n  assert (Hi : loopSum i step_fun (mk_mconfig q t) = Some t').\n  { clear - H.  revert H. generalize (mk_mconfig q t). intros cfg H.\n    induction i in H, cfg,t'|-*; cbn in *.\n    - congruence.\n    - unfold step_fun. destruct haltConf. inv H. reflexivity.\n      eapply IHi. eapply H.\n  }\n  eapply evalLe_trans. unfold s_sim. Lsimpl. reflexivity.\n  unshelve eapply uiter_sound in Hi. exact _. exact _. 2: eapply step_fun_comp.\n  unfold s_sim. eapply evalIn_mono. econstructor. 2:Lproc. destruct Hi as [Hi ?].\n  unfold enc at 1 in Hi. cbn in Hi. unfold enc at 1 in Hi. cbn in Hi.\n  Lsimpl. reflexivity. rewrite <- plus_n_O.\n  clear. fold (transTime M).\n  change (  uiterTime step_fun\n    (fun (_ : mconfig Σ (state M) n_tps) (_ : unit) =>\n     (haltTime M + n_tps * 130 +\n      transTime M + 185, tt)) i (mk_mconfig q t) <= i * (STEPTIME + 11)).\n  generalize STEPTIME as C. intros C. generalize (mk_mconfig q t). intros cfg. induction i in cfg |- *.\n  - cbn. lia. \n  - cbn. destruct _. rewrite IHi. lia. lia.\nQed.\n\nLemma TimeInvarianceNF_backward v :\n  eval (s_sim (PAIR_ (ext step_fun) (enc q)) (enc t)) v -> exists q' t' i, loopSumM (M := M) (mk_mconfig q t) i = Some (mk_mconfig q' t').\nProof.\n  intros H.\n  assert ((s_sim (PAIR_ (ext step_fun) (enc q)) (enc t)) >* uiter (ext step_fun) (lam (O (enc q) (enc t)))).\n  { clear H.\n    unfold s_sim. now Lsimpl. }\n  rewrite H0 in H. clear H0.\n  change (lam (O (enc q) (enc t))) with (enc (mk_mconfig q t)) in H. \n  eapply uiter_complete in H as (n & tps' & H). clear t'. rename tps' into t'.\n  revert H. generalize (mk_mconfig q t) as cfg. intros cfg H.\n  induction n in cfg, H |- *; cbn in *.\n  - congruence.\n  - destruct step_fun eqn:E.\n    + eapply IHn in H as (q'' & t'' & i & IH). exists q'', t'', (S i). rewrite <- IH.\n      cbn.\n      unfold step_fun in E.\n      destruct haltConf; try congruence; try inv E.\n      reflexivity.\n    + inv H. unfold step_fun in E.\n      destruct haltConf eqn:EE; try congruence. inv E.\n      exists (cstate cfg), (ctapes cfg), 1. cbn. rewrite EE. now destruct cfg.\nQed.\n\nEnd TimeInvarianceNF.\n\nDefinition sizeTM Σ n (M : TM Σ n) := (haltTime M + n* 130+ transTime M + 185 + 11).\n\nDefinition encTM {n} {Σ : finType} : TM Σ n -> term.\nProof.\n  pose (reg_sig := @encodable_finType Σ).\n  intros M.\n  pose (reg_state := @encodable_finType (state M)).\n  unshelve refine (PAIR_ (extT (step_fun (M := M))) (enc (start M))). 3:eapply step_fun_comp.\nDefined.\n\nDefinition encTps  {n} {Σ : finType} : tapes Σ n -> term.\nProof.\n  pose (reg_sig := @encodable_finType Σ).\n  intros tps. exact (enc tps).  \nDefined.\n\nTheorem TimeInvarianceThesis_wrt_Termination_TM_to_L : let C := 10 in\n  forall n (Σ : finType), forall M : TM Σ n, forall tps,\n          (forall tps' i q',\n              loopM (mk_mconfig (start M) tps) i = Some (mk_mconfig q' tps') ->\n              evalLe (C * (S i) * sizeTM M + C) (s_sim (encTM M) (encTps tps)) (encTps tps')) /\\\n          (forall v, eval (s_sim (encTM M) (encTps tps)) v -> exists q' tps' i, loopM (mk_mconfig (start M) tps) i = Some (mk_mconfig q' tps')).\nProof.\n  intros C n Σ. subst C.\n  pose (reg_sig := @encodable_finType Σ).\n  intros M tps. split.\n  - intros tps' i q' H.\n    rewrite loopSumM_loopM_iff in H.\n    eapply TimeInvarianceNF_forward in H.\n    eapply evalLe_trans_rev with (k := 7) in H as (H1 & H & _).\n    2:{ unfold s_sim. Lsimpl. } cbn -[mult].\n    unfold s_sim. unfold encTM, encTps.\n    eapply evalIn_mono. Lsimpl. eapply (evalIn_refl 0). Lproc.\n    fold (sizeTM M). ring_simplify. lia.\n  - intros v (q' & t' & [] & H) % TimeInvarianceNF_backward. inv H. setoid_rewrite loopSumM_loopM_iff. eauto.\nQed.\n", "meta": {"author": "uds-psl", "repo": "time-invariance-thesis-for-L", "sha": "41f4eb1f788cc4f096d9c7c286c9ca907588859f", "save_path": "github-repos/coq/uds-psl-time-invariance-thesis-for-L", "path": "github-repos/coq/uds-psl-time-invariance-thesis-for-L/time-invariance-thesis-for-L-41f4eb1f788cc4f096d9c7c286c9ca907588859f/theories/L/TM/TimeInvarianceTermination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21197695174630618}}
{"text": "From ExtLib Require Export\n     Extras.\nFrom JSON Require Export\n     JSON.\nExport\n  FunNotation\n  ListNotations.\n\nClass JEncode T := encode : T -> json.\n\n#[global]\nInstance JEncode__json   : JEncode json := id.\n#[global]\nInstance JEncode__unit   : JEncode unit := const JSON__Null.\n#[global]\nInstance JEncode__String : JEncode string := JSON__String.\n#[global]\nInstance JEncode__Z      : JEncode Z := JSON__Number.\n#[global]\nInstance JEncode__N      : JEncode N := encode ∘ Z.of_N.\n#[global]\nInstance JEncode__nat    : JEncode nat := encode ∘ Z.of_nat.\n#[global]\nInstance JEncode__bool   : JEncode bool :=\n  fun b : bool => if b then JSON__True else JSON__False.\n\n#[global]\nInstance JEncode__list {T} `{JEncode T} : JEncode (list T) :=\n  JSON__Array ∘ map encode.\n\n#[global]\nInstance JEncode__option {T} `{JEncode T} : JEncode (option T) :=\n  fun x => if x is Some x then encode x else JSON__Object [].\n\nDefinition jkv' (k : string) (v : json) : json :=\n  JSON__Object [(k, v)].\n\nDefinition jkv (k : string) (v : json) : json :=\n  if v is JSON__Object [] then JSON__Object [] else jkv' k v.\n\nDefinition jobj' {T} (encode : T -> json) (k : string) (v : T) : json :=\n  jkv k $ encode v.\n\nDefinition jobj {T} `{JEncode T} : string -> JEncode T := jobj' encode.\n", "meta": {"author": "liyishuai", "repo": "coq-json", "sha": "9d08bb95f62806a84ee75df8ddcc834da2fb6569", "save_path": "github-repos/coq/liyishuai-coq-json", "path": "github-repos/coq/liyishuai-coq-json/coq-json-9d08bb95f62806a84ee75df8ddcc834da2fb6569/Encode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.21197695174630615}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import AbsAccessor.Spec.\nRequire Import BaremoreService.Specs.asc_mark_nonsecure.\nRequire Import BaremoreService.LowSpecs.asc_mark_nonsecure.\nRequire Import BaremoreService.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       addr_to_gidx_spec\n       check_granule_idx_spec\n       find_spinlock_spec\n       spinlock_acquire_spec\n       get_pas_spec\n       set_pas_spec\n       tlbi_by_pa_spec\n       spinlock_release_spec\n    .\n\n  Lemma asc_mark_nonsecure_spec_exists:\n    forall habd habd'  labd addr res\n           (Hspec: asc_mark_nonsecure_spec addr habd = Some (habd', res))\n            (Hrel: relate_RData habd labd),\n    exists labd', asc_mark_nonsecure_spec0 addr labd = Some (labd', res) /\\ relate_RData habd' labd'.\n  Proof.\n    intros. destruct Hrel. inv id_rdata.\n    unfold asc_mark_nonsecure_spec0, asc_mark_nonsecure_spec in *.\n    repeat autounfold in *.\n    hsimpl_hyp Hspec; inv Hspec; simpl in *;\n      extract_prop_dec; repeat destruct_con; bool_rel; simpl in *;\n        repeat (simpl_htarget; grewrite; simpl);\n        try (destruct_if; repeat destruct_dis; bool_rel; try omega);\n        repeat (solve_bool_range; grewrite);\n        repeat simpl_field;\n        eexists; (split; [reflexivity| constructor; try reflexivity]).\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/BaremoreService/RefProof/asc_mark_nonsecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.21197695174630615}}
{"text": "From Coq Require Import Lia.\nFrom Coq Require Import List. Import ListNotations.\nFrom Coq Require Import Logic.Decidable.\nFrom Coq Require Import ZArith.\nFrom ConCert.Utils Require Import Automation.\nFrom ConCert.Utils Require Import RecordUpdate.\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Execution Require Import ResultMonad.\n\nSection BuildUtils.\nContext {BaseTypes : ChainBase}.\n\n(* The empty state is always reachable *)\nLemma reachable_empty_state :\n  reachable empty_state.\nProof.\n  repeat constructor.\nQed.\n\n(* Transitivity property of reachable and ChainTrace *)\nLemma reachable_trans from to :\n  reachable from -> ChainTrace from to -> reachable to.\nProof.\n  intros [].\n  constructor.\n  now eapply ChainedList.clist_app.\nQed.\n\n(* Transitivity property of reachable and ChainStep *)\nLemma reachable_step from to :\n  reachable from -> ChainStep from to -> reachable to.\nProof.\n  intros [].\n  now do 2 econstructor.\nQed.\n\n(* If a state is reachable then the finalized_height cannot be larger than the chain_height *)\nLemma finalized_heigh_chain_height bstate :\n  reachable bstate ->\n  finalized_height bstate < S (chain_height bstate).\nProof.\n  intros [trace].\n  remember empty_state.\n  induction trace as [ | Heq from to trace IH step ]; subst.\n  - auto.\n  - destruct_chain_step;\n    try destruct_action_eval;\n    rewrite_environment_equiv;\n    auto.\n    + now inversion valid_header.\nQed.\n\n(* If a state is reachable and contract state is stored on an address\n    then that address must also have some contract deployed to it *)\nLemma contract_states_deployed to (addr : Address) (state : SerializedValue) :\n  reachable to ->\n  env_contract_states to addr = Some state ->\n  exists wc, env_contracts to addr = Some wc.\nProof.\n  intros [trace].\n  remember empty_state.\n  induction trace as [ | Heq from to trace IH step ];\n    subst; intros.\n  - discriminate.\n  - destruct_chain_step;\n      only 2: destruct_action_eval;\n      rewrite_environment_equiv;\n      setoid_rewrite env_eq; cbn in *;\n      destruct_address_eq; now subst.\nQed.\n\n(* If a state is reachable and contract state is stored on an address\n    then that address must be a contract address *)\nLemma contract_states_addr_format to (addr : Address) (state : SerializedValue) :\n  reachable to ->\n  env_contract_states to addr = Some state ->\n  address_is_contract addr = true.\nProof.\n  intros ? deployed_state.\n  apply contract_states_deployed in deployed_state as []; auto.\n  now eapply contract_addr_format.\nQed.\n\nHint Resolve reachable_empty_state\n             reachable_trans\n             reachable_step : core.\n\n(* A state `to` is reachable through `mid` if `mid` is reachable and there exists a trace\n    from `mid` to `to`. This captures that there is a valid execution ending up in `to`\n    and going through the state `mid` at some point *)\nDefinition reachable_through mid to := reachable mid /\\ inhabited (ChainTrace mid to).\n\n(* A state is always reachable through itself *)\nLemma reachable_through_refl : forall bstate,\n  reachable bstate -> reachable_through bstate bstate.\nProof.\n  intros bstate reach.\n  split; auto.\n  do 2 constructor.\nQed.\n\n(* Transitivity property of reachable_through and ChainStep *)\nLemma reachable_through_trans' : forall from mid to,\n  reachable_through from mid -> ChainStep mid to -> reachable_through from to.\nProof.\n  intros * [reach [trace]] step.\n  repeat (econstructor; eauto).\nQed.\n\n(* Transitivity property of reachable_through *)\nLemma reachable_through_trans : forall from mid to,\n  reachable_through from mid -> reachable_through mid to -> reachable_through from to.\nProof.\n  intros * [[trace_from] [trace_mid]] [_ [trace_to]].\n  do 2 constructor.\n  assumption.\n  now eapply ChainedList.clist_app.\nQed.\n\n(* Reachable_through can also be constructed from ChainStep instead of a\n   ChainTrace since a ChainTrace can be constructed from a ChainStep *)\nLemma reachable_through_step : forall from to,\n  reachable from -> ChainStep from to -> reachable_through from to.\nProof.\n  intros * reach_from step.\n  apply reachable_through_refl in reach_from.\n  now eapply reachable_through_trans'.\nQed.\n\n(* Any ChainState that is reachable through another ChainState is reachable *)\nLemma reachable_through_reachable : forall from to,\n  reachable_through from to -> reachable to.\nProof.\n  intros * [[trace_from] [trace_to]].\n  constructor.\n  now eapply ChainedList.clist_app.\nQed.\n\nHint Resolve reachable_through_refl\n             reachable_through_trans'\n             reachable_through_trans\n             reachable_through_step\n             reachable_through_reachable : core.\n\n(* If a state has a contract deployed to some addr then any other state\n    reachable through the first state must also have the same contract\n    deployed to the same addr *)\nLemma reachable_through_contract_deployed : forall from to addr wc,\n  reachable_through from to -> env_contracts from addr = Some wc ->\n    env_contracts to addr = Some wc.\nProof.\n  intros * [reach [trace]] deployed.\n  induction trace as [ | from mid to trace IH step ].\n  - assumption.\n  - destruct_chain_step;\n      only 2: destruct_action_eval;\n      rewrite_environment_equiv; cbn;\n      destruct_address_eq; subst; try easy.\n    now rewrite IH in not_deployed by assumption.\nQed.\n\n(* If a state has a contract state on some addr then any other state\n    reachable through the first state must also have the some contract\n    state on the same addr *)\nLemma reachable_through_contract_state : forall from to addr cstate,\n  reachable_through from to -> env_contract_states from addr = Some cstate ->\n    exists new_cstate, env_contract_states to addr = Some new_cstate.\nProof.\n  intros * [reachable [trace]] deployed_state.\n  generalize dependent cstate.\n  induction trace as [ | from mid to trace IH step ];\n    intros cstate deployed_state.\n  - now eexists.\n  - destruct_chain_step;\n      only 2: destruct_action_eval;\n      try rewrite_environment_equiv;\n      try setoid_rewrite env_eq;\n      cbn in *;\n      destruct_address_eq; now subst.\nQed.\n\n(* If a state is reachable through another state then it cannot have a lower chain height *)\nLemma reachable_through_chain_height : forall from to,\n  reachable_through from to -> from.(chain_height) <= to.(chain_height).\nProof.\n  intros * [reachable [trace]].\n  induction trace as [ | from mid to trace IH step ].\n  - apply Nat.le_refl.\n  - destruct_chain_step;\n    try destruct_action_eval;\n    rewrite_environment_equiv; cbn; auto.\n    + now inversion valid_header.\nQed.\n\n(* If a state is reachable through another state then it cannot have a lower current slot *)\nLemma reachable_through_current_slot : forall from to,\n  reachable_through from to -> from.(current_slot) <= to.(current_slot).\nProof.\n  intros * [reachable [trace]].\n  induction trace as [ | from mid to trace IH step ].\n  - apply Nat.le_refl.\n  - destruct_chain_step;\n    try destruct_action_eval;\n    rewrite_environment_equiv; cbn; auto.\n    + now inversion valid_header.\nQed.\n\n(* If a state is reachable through another state then it cannot have a lower finalized height *)\nLemma reachable_through_finalized_height : forall from to,\n  reachable_through from to -> from.(finalized_height) <= to.(finalized_height).\nProof.\n  intros * [reachable [trace]].\n  induction trace as [ | from mid to trace IH step ].\n  - apply Nat.le_refl.\n  - destruct_chain_step;\n    try destruct_action_eval;\n    rewrite_environment_equiv; cbn; auto.\n    + now inversion valid_header.\nQed.\n\n(* Initial contract balance will always be positive in reachable states *)\nLemma deployment_amount_nonnegative : forall {Setup : Type} `{Serializable Setup}\n                                      bstate caddr dep_info\n                                      (trace : ChainTrace empty_state bstate),\n  deployment_info Setup trace caddr = Some dep_info ->\n  (0 <= dep_info.(deployment_amount))%Z.\nProof.\n  intros * deployment_info_some.\n  remember empty_state.\n  induction trace; subst.\n  - discriminate.\n  - destruct_chain_step; auto.\n    destruct_action_eval; auto.\n    cbn in deployment_info_some.\n    destruct_address_eq; auto.\n    destruct_match in deployment_info_some;\n      try congruence.\n    inversion_clear deployment_info_some.\n    now apply Z.ge_le.\nQed.\n\nDefinition receiver_can_receive_transfer (bstate : ChainState) act_body :=\n  match act_body with\n  | act_transfer to _ => address_is_contract to = false \\/\n    (exists wc state,\n      env_contracts bstate to = Some wc /\\\n      env_contract_states bstate to = Some state /\\\n      forall (bstate_new : ChainState) ctx, exists new_state, wc_receive wc bstate_new ctx state None = Ok (new_state, []))\n  | _ => True\n  end.\n\n(* This axiom states that for any reachable state and any contract it is\n    decidable whether or not there is an address where the contract can be deployed to.\n   This is not provable in general with the assumption ChainBase makes about\n    addresses and the function address_is_contract. However, this should be\n    provable in any sensible instance of ChainBase *)\nAxiom deployable_address_decidable : forall bstate wc setup act_origin act_from amount,\n  reachable bstate ->\n  decidable (exists addr state, address_is_contract addr = true\n            /\\ env_contracts bstate addr = None\n            /\\ wc_init wc\n                  (transfer_balance act_from addr amount bstate)\n                  (build_ctx act_origin act_from addr amount amount)\n                  setup = Ok state).\n\nLtac action_not_decidable :=\n  right; intro;\n  match goal with\n  | H : exists bstate new_acts, inhabited (ActionEvaluation _ _ bstate new_acts) |- False =>\n    destruct H as [bstate_new [new_acts [action_evaluation]]];\n    destruct_action_eval; try congruence\n  end; repeat\n  match goal with\n  | H : {| act_origin := _; act_from := _; act_body := _ |} = {| act_origin := _; act_from := _; act_body := match ?msg with | Some _ => _ | None =>_ end |} |- False =>\n    destruct msg\n  | H : {| act_origin := _; act_from := _; act_body := _ |} = {| act_origin := _; act_from := _; act_body := _ |} |- False =>\n    inversion H; subst; clear H\n  end.\n\nLtac action_decidable :=\n  left; do 2 eexists; constructor;\n  match goal with\n  | H : wc_receive _ _ _ _ ?m = Ok _ |- _ => eapply (eval_call _ _ _ _ _ m)\n  | H : wc_init _ _ _ _ = Ok _ |- _ => eapply eval_deploy\n  | H : context [act_transfer _ _] |- _ => eapply eval_transfer\n  end;\n  eauto; try now constructor.\n\nLtac rewrite_balance :=\n  match goal with\n  | H := context [if (_ =? ?to)%address then _ else _ ],\n    H2 : Environment |- _ =>\n    assert (new_to_balance_eq : env_account_balances H2 to = H);\n    [ try rewrite_environment_equiv; cbn; unfold H; destruct_address_eq; try congruence; lia |\n    now rewrite <- new_to_balance_eq in *]\n  end.\n\n(* For any reachable state and an action it is decidable if it is\n    possible to evaluate the action in the state *)\nOpen Scope Z_scope.\nLemma action_evaluation_decidable : forall bstate act,\n  reachable bstate ->\n  decidable (exists bstate' new_acts, inhabited (ActionEvaluation bstate act bstate' new_acts)).\nProof.\n  intros * reach.\n  destruct act eqn:Hact.\n  destruct act_body;\n    (destruct (amount >=? 0) eqn:amount_positive;\n    [destruct (amount <=? env_account_balances bstate act_from) eqn:balance |\n      action_not_decidable; now rewrite Z.geb_leb, Z.leb_gt in amount_positive (* Eliminate cases where amount is negative *)];\n    [| action_not_decidable; now rewrite Z.leb_gt in balance ]); (* Eliminate cases where sender does not have enough balance *)\n  try (destruct (address_is_contract to) eqn:to_is_contract;\n    [destruct (env_contracts bstate to) eqn:to_contract;\n    [destruct (env_contract_states bstate to) eqn:contract_state |] |]);\n  try now action_not_decidable. (* Eliminate cases with obvious contradictions *)\n  all : rewrite Z.geb_leb, <- Zge_is_le_bool in amount_positive.\n  all : rewrite Z.leb_le in balance.\n  - (* act_body = act_transfer to amount *)\n    pose (new_to_balance := if (address_eqb act_from to)\n                         then (env_account_balances bstate to)\n                         else (env_account_balances bstate to) + amount).\n    destruct (wc_receive w\n        (transfer_balance act_from to amount bstate)\n        (build_ctx act_origin act_from to new_to_balance amount)\n        s None) eqn:receive.\n    + (* Case: act_transfer is evaluable by eval_call *)\n      destruct t.\n      pose (bstate' := (set_contract_state to s0\n                       (transfer_balance act_from to amount bstate))).\n      action_decidable.\n      rewrite_balance.\n    + (* Case: act_transfer is not evaluable by eval_call\n          because wc_receive returned None *)\n      action_not_decidable.\n      rewrite_balance.\n  - (* act_body = act_transfer to amount *)\n    (* Case: act_transfer is evaluable by eval_transfer *)\n    pose (bstate' := (transfer_balance act_from to amount bstate)).\n    action_decidable.\n  - (* act_body = act_call to amount msg *)\n    pose (new_to_balance := if (address_eqb act_from to)\n                         then (env_account_balances bstate to)\n                         else (env_account_balances bstate to) + amount).\n    destruct (wc_receive w\n        (transfer_balance act_from to amount bstate)\n        (build_ctx act_origin act_from to new_to_balance amount)\n        s (Some msg)) eqn:receive.\n    + (* Case: act_call is evaluable by eval_call *)\n      destruct t.\n      pose (bstate' := (set_contract_state to s0\n                       (transfer_balance act_from to amount bstate))).\n      action_decidable.\n      rewrite_balance.\n    + (* Case: act_call is not evaluable by eval_call\n          because wc_receive returned None *)\n      action_not_decidable.\n      rewrite_balance.\n  - (* act_body = act_call to amount msg *)\n    (* Case: contradiction *)\n    action_not_decidable.\n    now apply contract_addr_format in deployed; auto.\n  - (* act_body = act_deploy amount c setup *)\n    apply deployable_address_decidable\n      with (wc := c) (setup := setup) (act_origin := act_origin)\n      (act_from := act_from) (amount := amount)\n      in reach.\n    destruct reach as [[to [state [to_is_contract_addr [to_not_deployed init]]]] | no_deployable_addr].\n    + (* Case: act_deploy is evaluable by eval_deploy *)\n      pose (bstate' := (set_contract_state to state\n                       (add_contract to c\n                       (transfer_balance act_from to amount bstate)))).\n      action_decidable.\n    + (* Case: act_deploy is not evaluable by eval_deploy\n          because no there is no available contract address\n          that this contract can be deployed to *)\n      action_not_decidable.\n      apply no_deployable_addr.\n      eauto.\nQed.\nClose Scope Z_scope.\n\n(* Property stating that an action does not produce any new action when evaluated *)\nDefinition produces_no_new_acts act : Prop :=\n  forall bstate bstate' new_acts, ActionEvaluation bstate act bstate' new_acts -> new_acts = [].\n\n(* Property on a ChainState queue stating all actions are from accounts and produces\n    no new actions when evaluated. This ensures that the queue can be emptied successfully *)\nDefinition emptyable queue : Prop :=\n  Forall act_is_from_account queue /\\\n  Forall produces_no_new_acts queue.\n\n(* An empty queue is always emptyable *)\nLemma empty_queue_is_emptyable : emptyable [].\nProof.\n  now constructor.\nQed.\n\n(* A subset of an emptyable queue is also emptyable *)\nLemma emptyable_cons : forall x l,\n  emptyable (x :: l) -> emptyable l.\nProof.\n  intros * [acts_from_account no_new_acts].\n  apply Forall_inv_tail in acts_from_account.\n  now apply Forall_inv_tail in no_new_acts.\nQed.\n\n(* For any reachable state it is possible to empty the chain_state_queue\n    if the queue only contains action that satisfy the following\n    1) the action is from a user and not a contract\n    2) the action does not produce any actions when evaluated\n   For any property that holds on the starting state this also hold on\n    the state with an empty queue if it can be proven that the property\n    holds after evaluating any action.\n*)\nLemma empty_queue : forall bstate (P : ChainState -> Prop),\n  reachable bstate ->\n  emptyable (chain_state_queue bstate) ->\n  P bstate ->\n  (forall (bstate bstate' : ChainState) act acts, reachable bstate -> reachable bstate' -> P bstate ->\n    chain_state_queue bstate = act :: acts -> chain_state_queue bstate' = acts ->\n    (inhabited (ActionEvaluation bstate act bstate' []) \\/ EnvironmentEquiv bstate bstate') -> P bstate' ) ->\n    exists bstate', reachable_through bstate bstate' /\\ P bstate' /\\ (chain_state_queue bstate') = [].\nProof.\n  intros * reach [acts_from_account no_new_acts].\n  remember (chain_state_queue bstate) as queue.\n  generalize dependent bstate.\n  induction queue; intros bstate reach Hqueue_eq HP HP_preserved.\n  - (* Case: queue is already empty, thus we are already done *)\n    now eexists.\n  - (* Case: queue contains at least one action,\n        thus we need to either discard or evaluate it *)\n    apply list.Forall_cons_1 in acts_from_account as [act_from_a acts_from_account].\n    apply list.Forall_cons_1 in no_new_acts as [no_new_acts_from_a no_new_acts].\n    edestruct action_evaluation_decidable as\n      [[mid_env [new_acts [action_evaluation]]] | no_action_evaluation]; eauto.\n    + (* Case: the action is evaluable *)\n      pose (build_chain_state mid_env (new_acts ++ queue)) as mid.\n      assert (step : ChainStep bstate mid) by (now eapply step_action).\n      apply no_new_acts_from_a in action_evaluation as new_acts_eq; subst.\n      eapply HP_preserved with (bstate' := mid) in HP; eauto.\n      apply IHqueue in HP as [to [reachable_through [P_to queue_to]]]; subst; eauto.\n      now exists to.\n    + (* Case: the action not is evaluable *)\n      pose (bstate<| chain_state_queue := queue |>) as mid.\n      assert (step : ChainStep bstate mid).\n      { eapply step_action_invalid; try easy.\n        intros. apply no_action_evaluation.\n        now do 2 eexists.\n      }\n      apply reachable_step in step as reachable_mid; eauto.\n      apply IHqueue in reachable_mid as [to [reachable_through [P_to queue_to]]]; eauto.\n      exists to.\n      intuition.\n      eauto.\n      eapply (HP_preserved bstate mid); eauto.\n      now right.\nQed.\n\n(* wc_receive and contract receive are equivalent *)\nLemma wc_receive_to_receive : forall {Setup Msg State Error : Type}\n                                    `{Serializable Setup}\n                                    `{Serializable Msg}\n                                    `{Serializable State}\n                                    `{Serializable Error}\n                                    (contract : Contract Setup Msg State Error)\n                                    chain cctx cstate msg new_cstate new_acts,\n  contract.(receive) chain cctx cstate (Some msg) = Ok (new_cstate, new_acts) <->\n  wc_receive contract chain cctx ((@serialize State _) cstate) (Some ((@serialize Msg _) msg)) = Ok ((@serialize State _) new_cstate, new_acts).\nProof.\n  split; intros receive_some.\n  - cbn.\n    rewrite !deserialize_serialize.\n    cbn.\n    now rewrite receive_some.\n  - apply wc_receive_strong in receive_some as\n      (prev_state' & msg' & new_state' & prev_state_eq & msg_eq & new_state_eq & receive_some).\n    apply serialize_injective in new_state_eq. subst.\n    rewrite deserialize_serialize in prev_state_eq.\n    inversion prev_state_eq. subst.\n    destruct msg' eqn:Hmsg.\n    + cbn in msg_eq.\n      now rewrite deserialize_serialize in msg_eq.\n    + inversion msg_eq.\nQed.\n\n(* wc_init and contract init are equivalent *)\nLemma wc_init_to_init : forall {Setup Msg State Error : Type}\n                               `{Serializable Setup}\n                               `{Serializable Msg}\n                               `{Serializable State}\n                               `{Serializable Error}\n                               (contract : Contract Setup Msg State Error)\n                               chain cctx cstate setup,\n  contract.(init) chain cctx setup = Ok cstate <->\n  wc_init contract chain cctx ((@serialize Setup _) setup) = Ok ((@serialize State _) cstate).\nProof.\n  split; intros init_some.\n  - cbn.\n    rewrite deserialize_serialize.\n    cbn.\n    now rewrite init_some.\n  - apply wc_init_strong in init_some as\n      (setup_strong & result_strong & serialize_setup & serialize_result & init_some).\n    apply serialize_injective in serialize_result. subst.\n    rewrite deserialize_serialize in serialize_setup.\n    now inversion serialize_setup.\nQed.\n\nOpen Scope Z_scope.\n(* Lemma showing that there exists a future ChainState with an added block *)\nLemma add_block : forall bstate reward creator acts slot_incr,\n  reachable bstate ->\n  chain_state_queue bstate = [] ->\n  address_is_contract creator = false ->\n  reward >= 0->\n  (slot_incr > 0)%nat ->\n  Forall act_is_from_account acts ->\n  Forall act_origin_is_eq_from acts ->\n    (exists bstate',\n       reachable_through bstate bstate'\n    /\\ chain_state_queue bstate' = acts\n    /\\ EnvironmentEquiv\n        bstate'\n        (add_new_block_to_env {| block_height := S (chain_height bstate);\n          block_slot := current_slot bstate + slot_incr;\n          block_finalized_height := finalized_height bstate;\n          block_creator := creator;\n          block_reward := reward; |} bstate)).\nProof.\n  intros * reach queue creator_not_contract\n    reward_positive slot_incr_positive\n    acts_from_accounts origins_from_accounts.\n  pose (header :=\n    {| block_height := S (chain_height bstate);\n       block_slot := current_slot bstate + slot_incr;\n       block_finalized_height := finalized_height bstate;\n       block_creator := creator;\n       block_reward := reward; |}).\n  pose (bstate_with_acts := (bstate<|chain_state_queue := acts|>\n                                   <|chain_state_env := add_new_block_to_env header bstate|>)).\n  assert (step_with_acts : ChainStep bstate bstate_with_acts).\n  { eapply step_block; try easy.\n    - constructor; try easy.\n      + cbn. lia.\n      + split; try (cbn; lia). cbn.\n        now apply finalized_heigh_chain_height.\n  }\n  exists bstate_with_acts.\n  split; eauto.\n  split; eauto.\n  constructor; try reflexivity.\nQed.\n\n(* Lemma showing that there exists a future ChainState with the\n    same contract states where the current slot is <slot> *)\nLemma forward_time_exact : forall bstate reward creator slot,\n  reachable bstate ->\n  chain_state_queue bstate = [] ->\n  address_is_contract creator = false ->\n  reward >= 0 ->\n  (current_slot bstate < slot)%nat ->\n    (exists bstate' header,\n       reachable_through bstate bstate'\n    /\\ IsValidNextBlock header bstate\n    /\\ (slot = current_slot bstate')%nat\n    /\\ chain_state_queue bstate' = []\n    /\\ EnvironmentEquiv\n        bstate'\n        (add_new_block_to_env header bstate)).\nProof.\n  intros bstate reward creator slot reach queue\n    creator_not_contract reward_positive slot_not_hit.\n  eapply add_block with (slot_incr := (slot - current_slot bstate)%nat) in reach as new_block; try easy.\n  destruct new_block as [bstate_with_act [reach' [queue' env_eq]]].\n  do 2 eexists.\n  split; eauto.\n  do 3 try split; only 9: apply env_eq; eauto; cbn; try lia.\n  - now apply finalized_heigh_chain_height.\n  - rewrite_environment_equiv. cbn. lia.\nQed.\n\n(* Lemma showing that there exists a future ChainState with the\n    same contract states where the current slot is at least <slot> *)\nLemma forward_time : forall bstate reward creator slot,\n  reachable bstate ->\n  chain_state_queue bstate = [] ->\n  address_is_contract creator = false ->\n  reward >= 0 ->\n    (exists bstate' header,\n       reachable_through bstate bstate'\n    /\\ IsValidNextBlock header bstate\n    /\\ (slot <= current_slot bstate')%nat\n    /\\ chain_state_queue bstate' = []\n    /\\ EnvironmentEquiv\n        bstate'\n        (add_new_block_to_env header bstate)).\nProof.\n  intros * reach queue creator_not_contract reward_positive.\n  destruct (slot - current_slot bstate)%nat eqn:slot_hit.\n  - eapply add_block with (slot_incr := 1%nat) in reach as new_block; try easy.\n    destruct new_block as [bstate_with_act [reach' [queue' env_eq]]].\n    do 2 eexists.\n    split; eauto.\n    do 3 try split; only 9: apply env_eq; eauto; cbn; try lia.\n    + now apply finalized_heigh_chain_height.\n    + apply NPeano.Nat.sub_0_le in slot_hit.\n      rewrite_environment_equiv. cbn. lia.\n  - specialize forward_time_exact with (slot := slot) as\n      (bstate' & header & reach' & header_valid & slot_hit' & queue' & env_eq);\n      try easy.\n    do 2 eexists.\n    split; eauto.\n    intuition.\nQed.\n\n(* Lemma showing that there exists a future ChainState\n    where the contract call is evaluated *)\nLemma evaluate_action : forall {Setup Msg State Error : Type}\n                              `{Serializable Setup}\n                              `{Serializable Msg}\n                              `{Serializable State}\n                              `{Serializable Error}\n                               (contract : Contract Setup Msg State Error)\n                               bstate origin from caddr amount msg acts new_acts\n                               cstate new_cstate,\n  reachable bstate ->\n  chain_state_queue bstate = {| act_from := from;\n                                act_origin := origin;\n                                act_body := act_call caddr amount ((@serialize Msg _) msg) |} :: acts ->\n  amount >= 0 ->\n  env_account_balances bstate from >= amount ->\n  env_contracts bstate caddr = Some (contract : WeakContract) ->\n  env_contract_states bstate caddr = Some ((@serialize State _) cstate) ->\n  Blockchain.receive contract (transfer_balance from caddr amount bstate)\n                     (build_ctx origin from caddr (if (address_eqb from caddr)\n                         then (env_account_balances bstate caddr)\n                         else (env_account_balances bstate caddr) + amount) amount)\n                     cstate (Some msg) = Ok (new_cstate, new_acts) ->\n    (exists bstate',\n       reachable_through bstate bstate'\n    /\\ env_contract_states bstate' caddr = Some ((@serialize State _) new_cstate)\n    /\\ chain_state_queue bstate' = (map (build_act origin caddr) new_acts) ++ acts\n    /\\ EnvironmentEquiv\n        bstate'\n        (set_contract_state caddr ((@serialize State _) new_cstate) (transfer_balance from caddr amount bstate))).\nProof.\n  intros * reach queue amount_nonnegative enough_balance%Z.ge_le\n    deployed deployed_state receive_some.\n  pose (new_to_balance := if (address_eqb from caddr)\n                         then (env_account_balances bstate caddr)\n                         else (env_account_balances bstate caddr) + amount).\n  pose (bstate' := (bstate<|chain_state_queue := (map (build_act origin caddr) new_acts) ++ acts|>\n                          <|chain_state_env := set_contract_state caddr ((@serialize State _) new_cstate)\n                                                  (transfer_balance from caddr amount bstate)|>)).\n  assert (new_to_balance_eq : env_account_balances bstate' caddr = new_to_balance) by\n   (cbn; destruct_address_eq; easy).\n  assert (step : ChainStep bstate bstate').\n  - eapply step_action; eauto.\n    eapply eval_call with (msg := Some ((@serialize Msg _) msg)); eauto.\n    + rewrite new_to_balance_eq.\n      now apply wc_receive_to_receive in receive_some.\n    + constructor; reflexivity.\n  - exists bstate'.\n    split; eauto.\n    repeat split; eauto.\n    cbn.\n    now destruct_address_eq.\nQed.\n\n(* Lemma showing that there exists a future ChainState\n    where the transfer action is evaluated *)\nLemma evaluate_transfer : forall bstate origin from to amount acts,\n  reachable bstate ->\n  chain_state_queue bstate = {| act_from := from;\n                                act_origin := origin;\n                                act_body := act_transfer to amount |} :: acts ->\n  amount >= 0 ->\n  env_account_balances bstate from >= amount ->\n  address_is_contract to = false ->\n    (exists bstate',\n       reachable_through bstate bstate'\n    /\\ chain_state_queue bstate' = acts\n    /\\ EnvironmentEquiv\n        bstate'\n        (transfer_balance from to amount bstate)).\nProof.\n  intros * reach queue amount_nonnegative enough_balance%Z.ge_le to_not_contract.\n  pose (bstate' := (bstate<|chain_state_queue := acts|>\n                          <|chain_state_env := (transfer_balance from to amount bstate)|>)).\n  assert (step : ChainStep bstate bstate').\n  - eapply step_action with (new_acts := []); eauto.\n    eapply eval_transfer; eauto.\n    constructor; reflexivity.\n  - eexists bstate'.\n    split; eauto.\n    repeat split; eauto.\nQed.\n\n(* Lemma showing that if an action in the queue is invalid then\n    there exists a future ChainState with the same environment\n    where that action is discarded *)\nLemma discard_invalid_action : forall bstate act acts,\n  reachable bstate ->\n  chain_state_queue bstate = act :: acts ->\n  act_is_from_account act ->\n  (forall (bstate0 : Environment) (new_acts : list Action), ActionEvaluation bstate act bstate0 new_acts -> False) ->\n    (exists bstate',\n       reachable_through bstate bstate'\n    /\\ chain_state_queue bstate' = acts\n    /\\ EnvironmentEquiv\n        bstate'\n        bstate).\nProof.\n  intros * reach queue act_from_account no_action_evaluation.\n  pose (bstate' := (bstate<|chain_state_queue := acts|>)).\n  assert (step : ChainStep bstate bstate').\n  - eapply step_action_invalid; eauto.\n    constructor; reflexivity.\n  - eexists bstate'.\n    split; eauto.\n    repeat split; eauto.\nQed.\n\n(* Lemma showing that for any permutation of the queue there\n    exists a future ChainState with the same environment\n    end the queue permuted *)\nLemma permute_queue : forall bstate acts acts_permuted,\n  reachable bstate ->\n  chain_state_queue bstate = acts ->\n  Permutation.Permutation acts acts_permuted ->\n    (exists bstate',\n       reachable_through bstate bstate'\n    /\\ chain_state_queue bstate' = acts_permuted\n    /\\ EnvironmentEquiv\n        bstate'\n        bstate).\nProof.\n  intros * reach queue perm.\n  pose (bstate' := (bstate<|chain_state_queue := acts_permuted|>)).\n  assert (step : ChainStep bstate bstate').\n  - eapply step_permute.\n    + econstructor; eauto.\n    + now rewrite queue.\n  - eexists bstate'.\n    split; eauto.\n    repeat split; eauto.\nQed.\n\n(* Lemma showing that there exists a future ChainState\n    where the contract is deployed *)\nLemma deploy_contract : forall {Setup Msg State Error : Type}\n                              `{Serializable Setup}\n                              `{Serializable Msg}\n                              `{Serializable State}\n                              `{Serializable Error}\n                               (contract : Contract Setup Msg State Error)\n                               bstate origin from caddr amount acts setup cstate,\n  reachable bstate ->\n  chain_state_queue bstate = {| act_from := from;\n                                act_origin := origin;\n                                act_body := act_deploy amount contract ((@serialize Setup _) setup) |} :: acts ->\n  amount >= 0 ->\n  env_account_balances bstate from >= amount ->\n  address_is_contract caddr = true ->\n  env_contracts bstate caddr = None ->\n  Blockchain.init contract\n        (transfer_balance from caddr amount bstate)\n        (build_ctx origin from caddr amount amount)\n        setup = Ok cstate ->\n    (exists bstate' (trace : ChainTrace empty_state bstate'),\n       reachable_through bstate bstate'\n    /\\ env_contracts bstate' caddr = Some (contract : WeakContract)\n    /\\ env_contract_states bstate' caddr = Some ((@serialize State _) cstate)\n    /\\ deployment_info Setup trace caddr = Some (build_deployment_info origin from amount setup)\n    /\\ chain_state_queue bstate' = acts\n    /\\ EnvironmentEquiv\n        bstate'\n        (set_contract_state caddr ((@serialize State _) cstate)\n        (add_contract caddr contract\n        (transfer_balance from caddr amount bstate)))).\nProof.\n  intros * reach queue amount_nonnegative enough_balance%Z.ge_le\n    caddr_is_contract not_deployed init_some.\n  pose (bstate' := (bstate<|chain_state_queue := acts|>\n                          <|chain_state_env :=\n                            (set_contract_state caddr ((@serialize State _) cstate)\n                            (add_contract caddr contract\n                            (transfer_balance from caddr amount bstate)))|>)).\n  assert (step : ChainStep bstate bstate').\n  - eapply step_action with (new_acts := []); eauto.\n    eapply eval_deploy; eauto.\n    + now apply wc_init_to_init in init_some.\n    + constructor; reflexivity.\n  - exists bstate'.\n    destruct reach as [trace].\n    exists (ChainedList.snoc trace step).\n    split; eauto.\n    repeat split; eauto;\n    try (cbn; now destruct_address_eq).\n    cbn. destruct_chain_step; try congruence.\n    + destruct_action_eval;\n        try congruence; cbn in *; subst; rewrite queue in queue_prev; inversion queue_prev; subst.\n      * destruct_address_eq.\n        -- now rewrite deserialize_serialize.\n        -- inversion env_eq.\n           cbn in contracts_eq.\n           specialize (contracts_eq caddr).\n           now rewrite address_eq_refl, address_eq_ne in contracts_eq.\n      * now destruct msg.\n    + exfalso. eapply no_eval.\n      rewrite queue in queue_prev.\n      inversion queue_prev.\n      eapply eval_deploy; eauto.\n      * now apply wc_init_to_init in init_some.\n      * now constructor.\n    + rewrite <- env_eq in not_deployed.\n      cbn in not_deployed.\n      now destruct_address_eq.\nQed.\nClose Scope Z_scope.\n\nLemma step_reachable_through_exists : forall from mid (P : ChainState -> Prop),\n  reachable_through from mid ->\n  (exists to : ChainState, reachable_through mid to /\\ P to) ->\n  (exists to : ChainState, reachable_through from to /\\ P to).\nProof.\n  intros * reach [to [reach_ HP]].\n  now exists to.\nQed.\n\nEnd BuildUtils.\n\nGlobal Hint Resolve reachable_through_refl\n             reachable_through_trans'\n             reachable_through_trans\n             reachable_through_step\n             reachable_through_reachable : core.\n\nGlobal Hint Resolve reachable_through_refl\n             reachable_through_trans'\n             reachable_through_trans\n             reachable_through_step\n             reachable_through_reachable : core.\n\nLocal Ltac update_fix term1 term2 H H_orig H' :=\n  match H with\n  | context G [ term1 ] =>\n    let x := context G [ term2 ] in\n      update_fix term1 term2 x H_orig H'\n  | _ =>\n    let h := fresh \"H\" in\n      assert H; [H' | clear H_orig; rename h into H_orig]\n  end.\n\n(* Replaces all occurrences of <term1> with <term2> in hypothesis <H>\n    using tactic <H'> to prove the old hypothesis implies the updated *)\nLocal Ltac update_ term1 term2 H H' :=\n  match type of H with\n  | context G [ term1 ] =>\n    let x := context G [ term2 ] in\n      update_fix term1 term2 x H H'\n  end.\n\nTactic Notation \"update\" constr(t1) \"with\" constr(t2) \"in\" hyp(H) := update_ t1 t2 H ltac:(try (cbn; easy)).\nTactic Notation \"update\" constr(t1) \"with\" constr(t2) \"in\" hyp(H) \"by\" tactic(G) := update_ t1 t2 H G.\nTactic Notation \"update\" constr(t2) \"in\" hyp(H) := let t1 := type of H in update_ t1 t2 H ltac:(try (cbn; easy)).\nTactic Notation \"update\" constr(t2) \"in\" hyp(H) \"by\" tactic(G) := let t1 := type of H in update_ t1 t2 H G.\n\nLocal Ltac only_on_match tac :=\n  match goal with\n  | |- exists bstate', reachable_through ?bstate bstate' /\\ _ => tac\n  | |- _ => idtac\n  end.\n\nLocal Ltac update_chainstate bstate1 bstate2 :=\n  match goal with\n  | H : reachable bstate1 |- _ => clear H\n  | H : chain_state_queue bstate1 = _ |- _ => clear H\n  | H : IsValidNextBlock _ bstate1.(chain_state_env).(env_chain) |- _ => clear H\n  | H : reachable_through bstate1 bstate2 |- _ =>\n      update (reachable bstate2) in H\n  | H : env_contracts bstate1.(chain_state_env) _ = Some _ |- _ =>\n      update bstate1 with bstate2 in H by (now rewrite_environment_equiv)\n  | H : env_contract_states bstate1.(chain_state_env) _ = Some _ |- _ =>\n      update bstate1 with bstate2 in H by (now rewrite_environment_equiv)\n  | H : context [ bstate1 ] |- _ =>\n    match type of H with\n    | EnvironmentEquiv _ _ => fail 1\n    | _ => update bstate1 with bstate2 in H by (try (rewrite_environment_equiv; cbn; easy))\n    end\n  end;\n  only_on_match ltac:(progress update_chainstate bstate1 bstate2).\n\n(* Tactic for updating goal and all occurrences of an old ChainState\n    after adding a future ChainState to the environment. *)\nLtac update_all :=\n  match goal with\n  | Hreach : reachable_through ?bstate1 ?bstate2,\n    Henv_eq : EnvironmentEquiv ?bstate2.(chain_state_env) (add_new_block_to_env ?header ?bstate1.(chain_state_env)) |-\n    exists bstate3, reachable_through ?bstate1 bstate3 /\\ _ =>\n      apply (step_reachable_through_exists bstate1 bstate2); auto;\n      update_chainstate bstate1 bstate2;\n      only_on_match ltac:(\n        clear Henv_eq;\n        (try clear dependent header);\n        clear dependent bstate1)\n  | Hreach : reachable_through ?bstate1 ?bstate2,\n    Henv_eq : EnvironmentEquiv ?bstate2.(chain_state_env) _ |-\n    exists bstate3, reachable_through ?bstate1 bstate3 /\\ _ =>\n      apply (step_reachable_through_exists bstate1 bstate2); auto;\n      update_chainstate bstate1 bstate2;\n      only_on_match ltac:(\n        clear Henv_eq;\n        clear dependent bstate1)\n  | Hreach : reachable_through ?bstate1 ?bstate2 |-\n    exists bstate3, reachable_through ?bstate1 bstate3 /\\ _ =>\n      apply (step_reachable_through_exists bstate1 bstate2); auto;\n      update (reachable bstate2) in Hreach;\n      only_on_match ltac:(clear dependent bstate1)\n  end.\n\nLtac forward_time slot_ :=\n  let new_bstate := fresh \"bstate\" in\n  let new_header := fresh \"header\" in\n  let new_header_valid := fresh \"header_valid\" in\n  let new_reach := fresh \"reach\" in\n  let new_queue := fresh \"queue\" in\n  let new_env_eq := fresh \"env_eq\" in\n  let new_slot_hit := fresh \"slot_hit\" in\n  match goal with\n  | Hqueue : (chain_state_queue ?bstate) = [],\n    Hreach : reachable ?bstate |-\n    exists bstate', reachable_through ?bstate bstate' /\\ _ =>\n      specialize (forward_time bstate) with (slot := slot_)\n        as [new_bstate [new_header [new_reach [new_header_valid [new_slot_hit [new_queue new_env_eq]]]]]]\n  end.\n\nLtac forward_time_exact slot_ :=\n  let new_bstate := fresh \"bstate\" in\n  let new_header := fresh \"header\" in\n  let new_header_valid := fresh \"header_valid\" in\n  let new_reach := fresh \"reach\" in\n  let new_queue := fresh \"queue\" in\n  let new_env_eq := fresh \"env_eq\" in\n  let new_slot_hit := fresh \"slot_hit\" in\n  match goal with\n  | Hqueue : (chain_state_queue ?bstate) = [],\n    Hreach : reachable ?bstate |-\n    exists bstate', reachable_through ?bstate bstate' /\\ _ =>\n      specialize (forward_time_exact bstate) with (slot := slot_)\n        as [new_bstate [new_header [new_reach [new_header_valid [new_slot_hit [new_queue new_env_eq]]]]]]\n  end.\n\nLtac add_block acts_ slot_ :=\n  let new_bstate := fresh \"bstate\" in\n  let new_reach := fresh \"reach\" in\n  let new_queue := fresh \"queue\" in\n  let new_env_eq := fresh \"env_eq\" in\n  match goal with\n  | Hqueue : (chain_state_queue ?bstate) = [],\n    Hreach : reachable ?bstate |-\n    exists bstate', reachable_through ?bstate bstate' /\\ _ =>\n      specialize add_block with (acts := acts_) (slot_incr := slot_)\n        as [new_bstate [new_reach [new_queue new_env_eq]]];\n      [apply Hreach | apply Hqueue| | | | | |]\n  end.\n\nLtac evaluate_action contract_ :=\n  let new_bstate := fresh \"bstate\" in\n  let new_reach := fresh \"reach\" in\n  let new_deployed_state := fresh \"deployed_state\" in\n  let new_queue := fresh \"queue\" in\n  let new_env_eq := fresh \"env_eq\" in\n  match goal with\n  | Hqueue : (chain_state_queue ?bstate) = _,\n    Hreach : reachable ?bstate |-\n    exists bstate', reachable_through ?bstate bstate' /\\ _ =>\n      specialize (evaluate_action contract_) as\n        [new_bstate [new_reach [new_deployed_state [new_queue new_env_eq]]]];\n      [apply Hreach | rewrite Hqueue | | | | | | ]\n  end.\n\nLtac evaluate_transfer :=\n  let new_bstate := fresh \"bstate\" in\n  let new_reach := fresh \"reach\" in\n  let new_queue := fresh \"queue\" in\n  let new_env_eq := fresh \"env_eq\" in\n  match goal with\n  | Hqueue : (chain_state_queue ?bstate) = _,\n    Hreach : reachable ?bstate |-\n    exists bstate', reachable_through ?bstate bstate' /\\ _ =>\n      specialize evaluate_transfer as\n        [new_bstate [new_reach [new_queue new_env_eq]]];\n      [apply Hreach | rewrite Hqueue | | | | ]\n  end.\n\nLtac discard_invalid_action :=\n  let new_bstate := fresh \"bstate\" in\n  let new_reach := fresh \"reach\" in\n  let new_queue := fresh \"queue\" in\n  let new_env_eq := fresh \"env_eq\" in\n  match goal with\n  | Hqueue : (chain_state_queue ?bstate) = _,\n    Hreach : reachable ?bstate |-\n    exists bstate', reachable_through ?bstate bstate' /\\ _ =>\n      specialize discard_invalid_action as\n        [new_bstate [new_reach [new_queue new_env_eq]]];\n      [apply Hreach | rewrite Hqueue | | | ]\n  end.\n\nLtac empty_queue H :=\n  let new_bstate := fresh \"bstate\" in\n  let new_reach := fresh \"reach\" in\n  let new_queue := fresh \"queue\" in\n  let temp_H := fresh \"H\" in\n  let temp_eval := fresh \"eval\" in\n   match goal with\n  | Hempty : emptyable (chain_state_queue ?bstate),\n    Hreach : reachable ?bstate |-\n    exists bstate', reachable_through ?bstate bstate' /\\ _ =>\n      pattern (bstate) in H;\n      match type of H with\n      | ?f bstate =>\n        specialize (empty_queue bstate f) as\n          [new_bstate [new_reach [temp_H new_queue]]];\n        [apply Hreach | apply Hempty | apply H |\n        clear H;\n        intros ?bstate_from ?bstate_to ?act ?acts ?reach_from ?reach_to\n          H ?queue_from ?queue_to [[temp_eval] | ?env_eq];\n          only 1: destruct_action_eval |\n        clear H; rename temp_H into H]\n      end\n  end.\n\nLtac deploy_contract contract_ :=\n  let new_bstate := fresh \"bstate\" in\n  let new_reach := fresh \"reach\" in\n  let new_deployed_state := fresh \"deployed_state\" in\n  let new_contract_deployed := fresh \"contract_deployed\" in\n  let new_queue := fresh \"queue\" in\n  let new_env_eq := fresh \"env_eq\" in\n  let new_cstate := fresh \"cstate\" in\n  let contract_not_deployed := fresh \"trace\" in\n  let deploy_info := fresh \"deploy_info\" in\n  match goal with\n  | Hqueue : (chain_state_queue ?bstate) = _,\n    Hreach : reachable ?bstate,\n    Haddress : address_is_contract ?caddr = true,\n    Hdeployed : env_contracts ?bstate.(chain_state_env) ?caddr = None |-\n    exists bstate', reachable_through ?bstate bstate' /\\ _ =>\n      specialize (deploy_contract contract_) as\n        (new_bstate & trace & new_reach & new_contract_deployed &\n          new_deployed_state & deploy_info & new_queue & new_env_eq);\n      [apply Hreach | rewrite Hqueue | | |\n       apply Haddress | apply Hdeployed | |\n       clear Haddress Hdeployed;\n       match type of new_deployed_state with\n       | env_contract_states _ _ = Some ((@serialize _ _) ?state) => remember state as new_cstate\n       end\n       ]\n  end.\n", "meta": {"author": "AU-COBRA", "repo": "ConCert", "sha": "55ffd996fe89d41677a2ff368d3a5e4be1e997b7", "save_path": "github-repos/coq/AU-COBRA-ConCert", "path": "github-repos/coq/AU-COBRA-ConCert/ConCert-55ffd996fe89d41677a2ff368d3a5e4be1e997b7/execution/theories/BuildUtils.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21197695174630615}}
{"text": "Require Import Memory.\nRequire Import Values.\nRequire Import Coqlib.\nRequire Import Integers.\nRequire Import AST.\nRequire Import Znumtheory.\nRequire Import vellvm_tactics.\n\nModule MoreMem.\n\nExport Mem.\n\nTransparent load alloc.\n\nDefinition meminj : Type := block -> option (block * Z).\n\n(** A memory injection defines a relation between values that is the\n  identity relation, except for pointer values which are shifted\n  as prescribed by the memory injection. *)\n\nInductive val_inject (mi: meminj): val -> val -> Prop :=\n  | val_inject_int:\n      forall wz i, val_inject mi (Vint wz i) (Vint wz i)\n  | val_inject_float:\n      forall f, val_inject mi (Vfloat f) (Vfloat f)\n  | val_inject_ptr:\n      forall b1 ofs1 b2 ofs2 delta,\n      mi b1 = Some (b2, delta) ->\n      ofs2 = Int.add 31 ofs1 (Int.repr 31 delta) ->\n      val_inject mi (Vptr b1 ofs1) (Vptr b2 ofs2)\n  | val_inject_inttoptr:\n      forall i, val_inject mi (Vinttoptr i) (Vinttoptr i)\n  | val_inject_undef: val_inject mi Vundef Vundef.\n\nHint Resolve val_inject_int val_inject_float val_inject_ptr val_inject_inttoptr \n             val_inject_undef.\n\nInductive val_list_inject (mi: meminj): list val -> list val-> Prop:= \n  | val_nil_inject :\n      val_list_inject mi nil nil\n  | val_cons_inject : forall v v' vl vl' , \n      val_inject mi v v' -> val_list_inject mi vl vl'->\n      val_list_inject mi (v :: vl) (v' :: vl').  \n\nHint Resolve val_nil_inject val_cons_inject.\n\n(* Properties of val_inject *)\nLemma val_load_result_inject:\n  forall f chunk v1 v2,\n  val_inject f v1 v2 ->\n  val_inject f (Val.load_result chunk v1) (Val.load_result chunk v2).\nProof.\n  intros. inv H; destruct chunk; simpl; try econstructor; eauto.\n    destruct (eq_nat_dec n 31); try econstructor; eauto.\n    destruct (eq_nat_dec n 31); try econstructor; eauto.\nQed.\n\nLemma val_load_result_inject_2: forall (f : block -> option (block * Z))\n  (v : val) (m : memory_chunk) (Hchk : Val.has_chunk v m)\n  (Hinj : val_inject f (Val.load_result m v) (Val.load_result m v)),\n  val_inject f v v.\nProof.\n  intros.\n  destruct m, v; try inv Hchk; auto.\nQed.\n\nLemma val_inject__has_chunkb: forall mi v1 v2 m\n  (H : val_inject mi v1 v2),\n  Val.has_chunkb v1 m = Val.has_chunkb v2 m.\nProof. intros. inv H; auto. Qed.\n\n(** Monotone evolution of a memory injection. *)\n\nDefinition inject_incr (f1 f2: meminj) : Prop :=\n  forall b b' delta, f1 b = Some(b', delta) -> f2 b = Some(b', delta).\n\nLemma inject_incr_refl :\n   forall f , inject_incr f f .\nProof. unfold inject_incr. auto. Qed.\n\nLemma inject_incr_trans :\n  forall f1 f2 f3, \n  inject_incr f1 f2 -> inject_incr f2 f3 -> inject_incr f1 f3 .\nProof .\n  unfold inject_incr; intros. eauto. \nQed.\n\nLemma val_inject_incr:\n  forall f1 f2 v v',\n  inject_incr f1 f2 ->\n  val_inject f1 v v' ->\n  val_inject f2 v v'.\nProof.\n  intros. inv H0; eauto.\nQed.\n\nLemma val_list_inject_incr:\n  forall f1 f2 vl vl' ,\n  inject_incr f1 f2 -> val_list_inject f1 vl vl' ->\n  val_list_inject f2 vl vl'.\nProof.\n  induction vl; intros; inv H0. auto.\n  constructor. eapply val_inject_incr; eauto. auto.\nQed.\n\nHint Resolve inject_incr_refl val_inject_incr val_list_inject_incr.\n\nInductive memval_inject (f: meminj): memval -> memval -> Prop :=\n  | memval_inject_byte:\n      forall wz n, memval_inject f (Byte wz n) (Byte wz n)\n  | memval_inject_ptr:\n      forall b1 ofs1 b2 ofs2 delta n,\n      f b1 = Some (b2, delta) ->\n      ofs2 = Int.add 31 ofs1 (Int.repr 31 delta) ->\n      memval_inject f (Pointer b1 ofs1 n) (Pointer b2 ofs2 n)\n  | memval_inject_inttoptr:\n      forall i n, memval_inject f (IPointer i n) (IPointer i n)\n  | memval_inject_undef: memval_inject f Undef Undef.\n\n(* Properties of memval_inject. *)\nLemma memval_inject_incr: forall f f' v1 v2, \n  memval_inject f v1 v2 -> inject_incr f f' -> memval_inject f' v1 v2.\nProof.\n  intros. inv H; econstructor. rewrite (H0 _ _ _ H1). reflexivity. auto.\nQed.\n\nLemma inj_bytes_inject:\n  forall f wz bl, \n    list_forall2 (memval_inject f) (inj_bytes wz bl) (inj_bytes wz bl).\nProof.\n  induction bl; constructor; auto. constructor.\nQed.\n\nLemma repeat_Undef_inject_self:\n  forall f n,\n  list_forall2 (memval_inject f) (list_repeat n Undef) (list_repeat n Undef).\nProof.\n  induction n; simpl; constructor; auto. constructor.\nQed.  \n\n(* Properties of proj_bytes. *)\nLemma proj_bytes_inject_some:\n  forall f vl vl',\n  list_forall2 (memval_inject f) vl vl' ->\n  forall n bl,\n  proj_bytes n vl = Some bl ->\n  proj_bytes n vl' = Some bl.\nProof.\n  induction 1; simpl. congruence.\n  inv H; try congruence.\n\n  intros.\n  destruct (eq_nat_dec wz n0); auto.\n  remember (proj_bytes n0 al) as R.\n  destruct R.\n    inv H. rewrite (IHlist_forall2 n0 l); auto.\n    congruence.      \nQed.\n\nLemma proj_bytes_inject_none:\n  forall f vl vl',\n  list_forall2 (memval_inject f) vl vl' ->\n  forall n,\n  proj_bytes n vl = None ->\n  proj_bytes n vl' = None.\nProof.\n  induction 1; simpl. congruence.\n  inv H; try congruence.\n\n  intros.\n  destruct (eq_nat_dec wz n0); auto.\n  remember (proj_bytes n0 al) as R.\n  destruct R.\n    inv H. rewrite (IHlist_forall2 n0); auto.\nQed.\n\nLemma proj_bytes_not_inject:\n  forall f vl vl',\n  list_forall2 (memval_inject f) vl vl' ->\n  forall n,\n  proj_bytes n vl = None -> proj_bytes n vl' <> None -> In Undef vl.\nProof.\n  induction 1; simpl; intros.\n    congruence.\n    inv H; try congruence; auto.\n    destruct (eq_nat_dec wz n); subst; auto.\n      remember (proj_bytes n al) as R.\n      remember (proj_bytes n bl) as R'.\n      destruct R; destruct R';\n        try solve [inversion H1 | inversion H2 | contradict H2; auto].\n        right. eapply IHlist_forall2; eauto.\n          rewrite <- HeqR'. intro. inversion H.          \n      contradict H2; auto.\nQed.\n\n(* Properties of proj_pointer *)\nDefinition meminj_no_overlap (f: meminj) : Prop :=\n  forall b1 b1' delta1 b2 b2' delta2,\n  b1 <> b2 ->\n  f b1 = Some (b1', delta1) ->\n  f b2 = Some (b2', delta2) ->\n  b1' <> b2'.\n\nLemma meminj_no_overlap_spec : forall f b1 b d1 b2 d2,\n  meminj_no_overlap f -> f b1 = Some (b, d1) -> f b2 = Some (b, d2) ->\n  b1 = b2 /\\ d1 = d2.\nProof.\n  intros.\n  destruct (zeq b1 b2); subst.\n    rewrite H1 in H0.\n    inv H0. split; auto.\n\n    elimtype False. unfold meminj_no_overlap in H.\n    eapply H in n; eauto.\nQed.\n\nLemma check_pointer_inject_true:\n  forall f vl vl',\n  list_forall2 (memval_inject f) vl vl' ->\n  forall n b ofs b' delta,\n  check_pointer n b ofs vl = true ->\n  f b = Some(b', delta) ->\n  check_pointer n b' (Int.add 31 ofs (Int.repr 31 delta)) vl' = true.\nProof.\n  induction 1; intros; destruct n; simpl in *; auto.\n  inv H; auto.\n  destruct (andb_prop _ _ H1). destruct (andb_prop _ _ H).\n  destruct (andb_prop _ _ H5).\n  assert (n = n0) by (apply beq_nat_true; auto).\n  assert (b = b0) by (eapply proj_sumbool_true; eauto).\n  assert (ofs = ofs1) by (eapply proj_sumbool_true; eauto).\n  subst. rewrite H3 in H2; inv H2.\n  unfold proj_sumbool. rewrite dec_eq_true. rewrite dec_eq_true.\n  rewrite <- beq_nat_refl. simpl. eauto.\nQed.\n\nDefinition meminj_zero_delta (f: meminj) : Prop :=\n  forall b b' delta, f b = Some(b', delta) -> delta = 0.\n\nLemma check_pointer_inject_false:\n  forall f vl vl',\n  list_forall2 (memval_inject f) vl vl' ->\n  meminj_no_overlap f ->\n  meminj_zero_delta f ->\n  forall n b ofs b' delta,\n  check_pointer n b ofs vl = false ->\n  f b = Some(b', delta) ->\n  check_pointer n b' (Int.add 31 ofs (Int.repr 31 delta)) vl' = false.\nProof.\n  induction 1; intros; destruct n; simpl in *; auto.\n  inv H; auto.\n  apply andb_false_elim in H3.\n  destruct H3 as [H3 | H3].\n    apply andb_false_elim in H3.\n    destruct H3 as [H3 | H3].\n      apply andb_false_elim in H3.\n      destruct H3 as [H3 | H3].  \n        apply andb_false_intro1.\n        apply andb_false_intro1.\n        apply andb_false_intro1.\n        unfold eq_block in *.\n        destruct (zeq b b0); subst; inv H3.\n        unfold meminj_no_overlap in H1.\n        eapply H1 in n1; eauto.\n        destruct (zeq b' b2); subst; try solve [contradict n1; auto | auto].\n\n        apply andb_false_intro1.\n        apply andb_false_intro1.\n        apply andb_false_intro2.\n        apply H2 in H4. apply H2 in H5. subst.\n        rewrite Int.add_zero. rewrite Int.add_zero. auto.\n      apply andb_false_intro1.\n      apply andb_false_intro2; auto.\n    eauto using andb_false_intro2.\nQed.\n\nLemma check_ipointer_inject_true:\n  forall f vl vl',\n  list_forall2 (memval_inject f) vl vl' ->\n  forall n i,\n  check_ipointer n i vl = true ->\n  check_ipointer n i vl' = true. \nProof.\n  induction 1; intros; destruct n; simpl in *; auto. \n  inv H; auto.\n\n  destruct (andb_prop _ _ H1). destruct (andb_prop _ _ H).\n  apply IHlist_forall2 in H2.\n  congruence.\nQed.\n\nLemma check_ipointer_inject_false:\n  forall f vl vl',\n  list_forall2 (memval_inject f) vl vl' ->\n  forall n i,\n  check_ipointer n i vl = false ->\n  check_ipointer n i vl' = false. \nProof.\n  induction 1; intros; destruct n; simpl in *; auto. \n  inv H; auto.\n\n  apply andb_false_elim in H1.\n  destruct H1; auto using andb_false_intro1.\n    apply IHlist_forall2 in e.\n    auto using andb_false_intro2.\nQed.\n\nLemma proj_ipointer_inject:\n  forall f vl1 vl2,\n  list_forall2 (memval_inject f) vl1 vl2 ->\n  val_inject f (proj_ipointer vl1) (proj_ipointer vl2).\nProof.\n  intros. unfold proj_ipointer.\n  inversion H; subst. auto. inversion H0; subst; auto.\n  case_eq (check_ipointer (size_chunk_nat Mint32) i \n             (IPointer i n :: al)); intros.\n  exploit check_ipointer_inject_true. eexact H. eauto. eauto. \n  intro. rewrite H3. econstructor; eauto. \n\n  exploit check_ipointer_inject_false. eexact H. eauto. eauto. \n  intro. rewrite H3. econstructor; eauto. \nQed.\n\nLemma proj_pointer_inject:\n  forall f vl1 vl2,\n  meminj_no_overlap f ->\n  meminj_zero_delta f ->\n  list_forall2 (memval_inject f) vl1 vl2 ->\n  val_inject f (proj_pointer vl1) (proj_pointer vl2).\nProof.\n  intros f v11 v12 J1 J2 H. unfold proj_pointer.\n  inversion H; subst. auto. inversion H0; subst; auto.\n  case_eq (check_pointer (size_chunk_nat Mint32) b0 ofs1 \n             (Pointer b0 ofs1 n :: al)); intros.\n\n  exploit check_pointer_inject_true; eauto.\n  intro. rewrite H4. econstructor; eauto. \n\n  exploit check_pointer_inject_false; eauto. \n  intro. rewrite H4. econstructor; eauto. \nQed.\n\nLemma proj_pointer_undef:\n  forall vl, In Undef vl -> proj_pointer vl = Vundef.\nProof.\n  intros; unfold proj_pointer.\n  destruct vl; auto. destruct m; auto. \n  rewrite check_pointer_undef. auto. auto.\nQed.\n\nLemma proj_ipointer_undef:\n  forall vl, In Undef vl -> proj_ipointer vl = Vundef.\nProof.\n  intros; unfold proj_ipointer.\n  destruct vl; auto. destruct m; auto. \n  rewrite check_ipointer_undef. auto. auto.\nQed.\n\n(* Properties of encode/decode val *)\nTheorem encode_val_inject:\n  forall f v1 v2 chunk,\n  val_inject f v1 v2 ->\n  list_forall2 (memval_inject f) (encode_val chunk v1) (encode_val chunk v2).\nProof.\n  intros. inv H; simpl.\n    apply inj_bytes_inject.\n    apply inj_bytes_inject.\n\n    destruct chunk; try apply repeat_Undef_inject_self.\n    destruct (eq_nat_dec n 31); subst; try apply repeat_Undef_inject_self.\n      simpl; repeat econstructor; auto.\n\n    destruct chunk; try apply repeat_Undef_inject_self.\n    destruct (eq_nat_dec n 31); subst; try apply repeat_Undef_inject_self.\n      unfold inj_ipointer; simpl; repeat econstructor; auto.\n\n    destruct chunk; try apply repeat_Undef_inject_self.\nQed.\n\nTheorem decode_val_inject:\n  forall f vl1 vl2 chunk,\n  meminj_no_overlap f ->\n  meminj_zero_delta f ->\n  list_forall2 (memval_inject f) vl1 vl2 ->\n  val_inject f (decode_val chunk vl1) (decode_val chunk vl2).\nProof.\n  intros f vl1 vl2 chunk JJ JJ2 H. unfold decode_val.\n  case_eq (proj_bytes (wz_of_chunk chunk) vl1); intros.\n    exploit proj_bytes_inject_some; eauto. intros. rewrite H1.\n    destruct chunk; constructor.\n \n    exploit proj_bytes_inject_none; eauto. intros. rewrite H1.\n    destruct chunk; auto.\n    destruct (eq_nat_dec n 31); subst; auto.\n      assert (H2 := H).\n      apply proj_pointer_inject in H2; auto.\n      destruct (@proj_pointer_inv vl1) as [J1 | [b1 [ofs1 J1]]]; rewrite J1.\n        rewrite J1 in H2. inv H2.\n        apply proj_ipointer_inject; auto.\n\n        rewrite J1 in H2. inv H2. eauto.\nQed.\n\nRecord mem_inj (f: meminj) (m1 m2: mem) : Prop :=\n  mk_mem_inj {\n    mi_access:\n      forall b1 b2 delta chunk ofs p,\n      f b1 = Some(b2, delta) ->\n      valid_access m1 chunk b1 ofs p ->\n      valid_access m2 chunk b2 (ofs + delta) p;\n    mi_memval:\n      forall b1 ofs b2 delta,\n      f b1 = Some(b2, delta) ->\n      perm m1 b1 ofs Nonempty ->\n      memval_inject f (m1.(mem_contents) b1 ofs) (m2.(mem_contents) b2 (ofs + delta))\n  }.\n\n(** Preservation of permissions *)\n\nLemma perm_inj:\n  forall f m1 m2 b1 ofs p b2 delta,\n  mem_inj f m1 m2 ->\n  perm m1 b1 ofs p ->\n  f b1 = Some(b2, delta) ->\n  perm m2 b2 (ofs + delta) p.\nProof.\n  intros. \n  assert (valid_access m1 (Mint 7) b1 ofs p).\n    split. red; intros. simpl in H2. rewrite bytesize_chunk_7_eq_1 in H2. replace ofs0 with ofs by omega. auto.\n    simpl. apply Zone_divide.\n  exploit mi_access; eauto. intros [A B].\n  apply A. simpl; rewrite bytesize_chunk_7_eq_1; omega. \nQed.\n\n(** Preservation of loads. *)\n\nLemma getN_inj:\n  forall f m1 m2 b1 b2 delta,\n  mem_inj f m1 m2 ->\n  f b1 = Some(b2, delta) ->\n  forall n ofs,\n  range_perm m1 b1 ofs (ofs + Z_of_nat n) Readable ->\n  list_forall2 (memval_inject f) \n               (getN n ofs (m1.(mem_contents) b1))\n               (getN n (ofs + delta) (m2.(mem_contents) b2)).\nProof.\n  induction n; intros; simpl.\n  constructor.\n  rewrite inj_S in H1. \n  constructor. \n  eapply mi_memval; eauto.\n  apply perm_implies with Readable.\n  apply H1. omega. constructor. \n  replace (ofs + delta + 1) with ((ofs + 1) + delta) by omega.\n  apply IHn. red; intros; apply H1; omega. \nQed.\n\nLemma load_inj:\n  forall f m1 m2 chunk b1 ofs b2 delta v1,\n  meminj_no_overlap f ->\n  meminj_zero_delta f ->\n  mem_inj f m1 m2 ->\n  load chunk m1 b1 ofs = Some v1 ->\n  f b1 = Some (b2, delta) ->\n  exists v2, load chunk m2 b2 (ofs + delta) = Some v2 /\\ val_inject f v1 v2.\nProof.\n  intros f m1 m2 chunk b1 ofs b2 delta v1 J1 J2 H H0 H1.\n  exists (decode_val chunk (getN (size_chunk_nat chunk) (ofs + delta) (m2.(mem_contents) b2))).\n  split. unfold load. apply pred_dec_true.  \n  eapply mi_access; eauto with mem. \n  exploit load_result; eauto. intro. rewrite H2. \n  apply decode_val_inject; auto. apply getN_inj; auto. \n  rewrite <- size_chunk_conv. exploit load_valid_access; eauto. \n  intros [A B]. auto.\nQed.\n\n(** Preservation of stores. *)\n\nLemma setN_inj:\n  forall (access: Z -> Prop) delta f vl1 vl2,\n  list_forall2 (memval_inject f) vl1 vl2 ->\n  forall p c1 c2,\n  (forall q, access q -> memval_inject f (c1 q) (c2 (q + delta))) ->\n  (forall q, access q -> memval_inject f ((setN vl1 p c1) q) \n                                         ((setN vl2 (p + delta) c2) (q + delta))).\nProof.\n  induction 1; intros; simpl. \n  auto.\n  replace (p + delta + 1) with ((p + 1) + delta) by omega.\n  apply IHlist_forall2; auto. \n  intros. unfold update at 1. destruct (zeq q0 p). subst q0.\n  rewrite update_s. auto.\n  rewrite update_o. auto. omega.\nQed.\n\nLemma store_mapped_inj:\n  forall f chunk m1 b1 ofs v1 n1 m2 b2 delta v2,\n  mem_inj f m1 m2 ->\n  store chunk m1 b1 ofs v1 = Some n1 ->\n  meminj_no_overlap f ->\n  f b1 = Some (b2, delta) ->\n  val_inject f v1 v2 ->\n  exists n2,\n    store chunk m2 b2 (ofs + delta) v2 = Some n2\n    /\\ mem_inj f n1 n2.\nProof.\n  intros. inversion H. \n  assert (valid_access m2 chunk b2 (ofs + delta) Writable).\n    eapply mi_access0; eauto with mem.\n  destruct (valid_access_store _ _ _ _ v2 H4) as [n2 STORE]. \n  exists n2; split. eauto.\n  constructor.\n(* access *)\n  intros.\n  eapply store_valid_access_1; [apply STORE |].\n  eapply mi_access0; eauto.\n  eapply store_valid_access_2; [apply H0 |]. auto.\n(* mem_contents *)\n  intros.\n  assert (perm m1 b0 ofs0 Nonempty). eapply perm_store_2; eauto. \n  rewrite (store_mem_contents _ _ _ _ _ _ H0).\n  rewrite (store_mem_contents _ _ _ _ _ _ STORE).\n  unfold update. \n  destruct (zeq b0 b1). subst b0.\n  (* block = b1, block = b2 *)\n  assert (b3 = b2) by congruence. subst b3.\n  assert (delta0 = delta) by congruence. subst delta0.\n  rewrite zeq_true.\n  apply setN_inj with (access := fun ofs => perm m1 b1 ofs Nonempty).\n  apply encode_val_inject; auto. auto. auto. \n  destruct (zeq b3 b2). subst b3.\n  (* block <> b1, block = b2 *)\n  rewrite setN_other. auto.\n  rewrite encode_val_length. rewrite <- size_chunk_conv. intros. \n  assert (b2 <> b2).\n    eapply H1; eauto. \n  congruence.\n  (* block <> b1, block <> b2 *)\n  eauto.\nQed.\n\nLemma store_unmapped_inj:\n  forall f chunk m1 b1 ofs v1 n1 m2,\n  mem_inj f m1 m2 ->\n  store chunk m1 b1 ofs v1 = Some n1 ->\n  f b1 = None ->\n  mem_inj f n1 m2.\nProof.\n  intros. inversion H.\n  constructor.\n(* access *)\n  eauto with mem.\n(* mem_contents *)\n  intros. \n  rewrite (store_mem_contents _ _ _ _ _ _ H0).\n  rewrite update_o. eauto with mem. \n  congruence.\nQed.\n\nLemma store_outside_inj:\n  forall f m1 m2 chunk b ofs v m2',\n  mem_inj f m1 m2 ->\n  (forall b' delta ofs',\n    f b' = Some(b, delta) ->\n    perm m1 b' ofs' Nonempty ->\n    ofs' + delta < ofs \\/ ofs' + delta >= ofs + size_chunk chunk) ->\n  store chunk m2 b ofs v = Some m2' ->\n  mem_inj f m1 m2'.\nProof.\n  intros. inversion H. constructor.\n(* access *)\n  eauto with mem.\n(* mem_contents *)\n  intros. \n  rewrite (store_mem_contents _ _ _ _ _ _ H1).\n  unfold update. destruct (zeq b2 b). subst b2.\n  rewrite setN_outside. auto. \n  rewrite encode_val_length. rewrite <- size_chunk_conv. \n  eapply H0; eauto. \n  eauto with mem.\nQed.\n\n(** Preservation of allocations *)\n\nLemma alloc_right_inj:\n  forall f m1 m2 lo hi b2 m2',\n  mem_inj f m1 m2 ->\n  alloc m2 lo hi = (m2', b2) ->\n  mem_inj f m1 m2'.\nProof.\n  intros. injection H0. intros NEXT MEM.\n  inversion H. constructor.\n(* access *)\n  intros. eauto with mem. \n(* mem_contents *)\n  intros.\n  assert (valid_access m2 (Mint 7) b0 (ofs + delta) Nonempty).\n    eapply mi_access0; eauto.\n    split. simpl. red; intros. rewrite bytesize_chunk_7_eq_1 in H3. assert (ofs0 = ofs) by omega. congruence.\n    simpl. apply Zone_divide. \n  assert (valid_block m2 b0) by eauto with mem.\n  rewrite <- MEM; simpl. rewrite update_o. eauto with mem.\n  rewrite NEXT. apply sym_not_equal. eauto with mem. \nQed.\n\n(** Preservation of frees *)\n\nLemma free_right_inj:\n  forall f m1 m2 b lo hi m2',\n  mem_inj f m1 m2 ->\n  free m2 b lo hi = Some m2' ->\n  (forall b1 delta ofs p,\n    f b1 = Some(b, delta) -> perm m1 b1 ofs p ->\n    lo <= ofs + delta < hi -> False) ->\n  mem_inj f m1 m2'.\nProof.\n  intros. exploit free_result; eauto. intro FREE. inversion H. constructor.\n(* access *)\n  intros. exploit mi_access0; eauto. intros [RG AL]. split; auto.\n  red; intros. eapply perm_free_1; eauto. \n  destruct (zeq b2 b); auto. subst b. right.\n  destruct (zlt ofs0 lo); auto. destruct (zle hi ofs0); auto.\n  elimtype False. eapply H1 with (ofs := ofs0 - delta). eauto. \n  apply H3. omega. omega.\n(* mem_contents *)\n  intros. rewrite FREE; simpl.\n  specialize (mi_memval0 _ _ _ _ H2 H3).\n  assert (b=b2 /\\ lo <= ofs+delta < hi \\/ (b<>b2 \\/ ofs+delta<lo \\/ hi <= ofs+delta)) by (unfold block; omega).\n  destruct H4. destruct H4. subst b2.\n  specialize (H1 _ _ _ _ H2 H3). elimtype False; auto.\n  rewrite (clearN_out _ _ _ _ _ _ H4); auto.\nQed.\n\nLemma free_inj:\n  forall f m1 m2 b1 b2 delta lo hi m1' m2',\n  meminj_no_overlap f ->\n  meminj_zero_delta f ->\n  mem_inj f m1 m2 ->\n  free m1 b1 lo hi = Some m1' ->\n  free m2 b2 (lo+delta) (hi+delta) = Some m2' ->\n  f b1 = Some (b2, delta) ->\n  mem_inj f m1' m2'.\nProof.\n  intros f m1 m2 b1 b2 delta lo hi m1' m2' J J' H H0 H1 H2.\n  exploit free_result; eauto. \n  intro FREE. inversion H. constructor.\n(* access *)\n  intros.\n  assert (valid_access m2 chunk b3 (ofs + delta0) p) as [RG AL] \n  by (exploit mi_access0; eauto with mem).\n\n  split; auto.\n  red; intros. eapply perm_free_1; eauto.\n  destruct (zeq b3 b2); auto.\n    subst b2. right.\n    destruct (zlt ofs0 (lo + delta)); auto.\n    destruct (zle (hi + delta) ofs0); auto.\n    destruct (@meminj_no_overlap_spec f b0 b3 delta0 b1 delta J H3 H2)\n      as [G1 G2]; subst.\n    assert (lo <= ofs0 - delta < hi) as J1.\n      clear - g g0. auto with zarith.\n    assert (ofs <= ofs0 - delta < ofs + size_chunk chunk) as J2.\n      clear - H5. auto with zarith.\n    destruct H4 as [H41 H42].\n    apply H41 in J2.\n    eapply perm_free_2 with (p:=p) in J1; eauto.\n    congruence.\n\n(* mem_contents *) \n  intros. rewrite FREE; simpl.\n  assert (FREE':=H0). apply free_result in FREE'.\n  rewrite FREE'; simpl.   \n  assert (b0=b1 /\\ lo <= ofs < hi \\/ (b1<>b0 \\/ ofs<lo \\/ hi <= ofs)) as J1\n    by (unfold block; omega).\n  assert (b2=b3 /\\ lo+delta <= ofs+delta < hi+delta \\/ \n    (b2<>b3 \\/ ofs+delta<lo+delta \\/ hi+delta <= ofs+delta)) \n    as J2 by (unfold block; omega).\n  destruct J1 as [J1 | J1].\n    destruct J1 as [J11 J12]; subst.\n    eapply perm_free_2 with (p:=Nonempty) in H0; eauto.\n    congruence.\n\n    rewrite (clearN_out _ _ _ _ _ _ J1).\n    destruct J2 as [J2 | J2].\n      destruct J2 as [J21 J22]; subst.\n      destruct (@meminj_no_overlap_spec f b0 b3 delta0 b1 delta J H3 H2)\n        as [G1 G2]; subst.\n      assert (lo <= ofs < hi) as EQ.\n        clear - J22. auto with zarith.\n      clear - J1 EQ.\n      destruct J1 as [J1 | J1]; try solve [congruence].\n      contradict EQ; auto with zarith.\n\n      assert (W1:=H2). apply J' in W1. subst.\n      assert (W2:=H3). apply J' in W2. subst.\n      rewrite (clearN_out _ _ _ _ _ _ J2).\n      eapply perm_free_3 in H4; eauto.\nQed.\n\nGlobal Opaque load alloc.\n\nLemma free_left_nonmap_inj:\n  forall f m1 m2 b lo hi m1' (Hprop: f b = None),\n  mem_inj f m1 m2 ->\n  Mem.free m1 b lo hi = Some m1' ->\n  mem_inj f m1' m2.\nProof.\n  intros. exploit Mem.free_result; eauto. intro FREE. inversion H. constructor.\n(* access *)\n  intros. eauto with mem.\n(* mem_contents *)\n  intros. rewrite FREE; simpl.\n  assert (b=b1 /\\ lo <= ofs < hi \\/ (b<>b1 \\/ ofs<lo \\/ hi <= ofs))\n    by (unfold Values.block; omega).\n  destruct H3.\n    destruct H3. subst b1. uniq_result.\n\n    rewrite (Mem.clearN_out _ _ _ _ _ _ H3).\n    apply mi_memval; auto.\n    eapply Mem.perm_free_3; eauto.\nQed.\n\nEnd MoreMem.\n\n", "meta": {"author": "vellvm", "repo": "vellvm-legacy", "sha": "e4c22d795974ba7c768c18b74fa098b0be2f86f7", "save_path": "github-repos/coq/vellvm-vellvm-legacy", "path": "github-repos/coq/vellvm-vellvm-legacy/vellvm-legacy-e4c22d795974ba7c768c18b74fa098b0be2f86f7/src/Vellvm/memory_sim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21197695174630615}}
{"text": "(*\n * Copyright (c) 2009-2011, Andrew Appel, Robert Dockins and Aquinas Hobor.\n *\n *)\n\nRequire Import msl.base.\nRequire Import msl.sepalg.\nRequire Import msl.psepalg.\nRequire Import msl.sepalg_generators.\nRequire Import msl.cjoins.\nRequire Import msl.eq_dec.\n\n(** The cross split axiom looks unwieldly,\n    but here we show that it arises naturally\n    as a kind of distributivity property.\n    Cross split can be rendered, with some accuracy,\n    as \"the separation algebra is distributive.\"\n *)\n\n  (** This definition mirrors the definition of\n      distributivity in a join-semilattice.  This\n      definition generalizes the standard notion of\n      distributivity in a lattice, but only mentions\n      of the lattice operators.  Here we transplant\n      the semilattice definition into the setting\n      of separation algebras.\n    *)\n  Definition sa_distributive (A: Type) {JOIN: Join A} :=\n    forall a b x z,\n      join a b z ->\n      constructive_join_sub x z ->\n      {a' : A & {b' : A &\n           (constructive_join_sub a' a * constructive_join_sub b' b * join a' b' x)%type}}.\n\n(*\n  (** We define this weaker version of cross-split\n      in order to show that the sa_distributive\n      axiom is equivalent. The ordinary cross_split\n      is more constructive (it uses a sigma type rather\n      than 'exists'), so we have to weaken it to show\n      the correspondence.  We could, instead, define\n      and use a constructive version of join_sub.\n    *)\n  Definition weak_cross_split `{sepalg A} :=\n    forall a b c d z : A,\n      join a b z ->\n      join c d z ->\n      exists x:(A*A*A*A), match x with (ac,ad,bc,bd) =>\n         join ac ad a /\\\n         join bc bd b /\\\n         join ac bc c /\\\n         join ad bd d\n       end.\n*)\n\n  (** Here we show that the cross split axiom is\n      the same as the statement of distributivity\n      for join semilattices transliterated into the\n      setting of separation algebras.\n    *)\n  Theorem cross_split_distibutive {A} `{Perm_alg A}{SA: Sep_alg A}{CS: Cross_alg A} :\n          sa_distributive A.\n  Proof.\n    intros ? ? ? ? H1 [x0 H2].\n    destruct (CS _ _ _ _ _ H1 H2) as [[[[? ?] ?] ?] ?].\n    intuition eauto.\n    exists a0.\n    exists a2.\n    intuition eauto.\n    econstructor; eauto.\n    econstructor; eauto.\n  Qed.\n\n  Theorem distributive_cross_split {A} `{Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}:\n     sa_distributive A -> Cross_alg A.\n  Proof.\n    intros H0.\n    repeat intro.\n    hnf in H0.\n    destruct (H0 a b c z H1) as [a' [b' [[?H ?H] ?H]]].\n    exists d; auto.\n    destruct H3 as [q ?H].\n    destruct H4 as [w ?H].\n    exists (a',q,b',w). split; auto. split; auto. split; auto.\n    destruct (join_assoc H3 H1) as [f [? ?]].\n    apply join_comm in H6.\n    destruct (join_assoc H4 H6) as [g [? ?]].\n    assert (H10: g = d); [ | rewrite H10 in *; auto].\n    apply join_comm in H7.\n    apply join_comm in H9.\n    destruct (join_assoc H9 H7) as [h [? ?]].\n    generalize (join_eq H5 (join_comm H10)); intro.\n    rewrite <- H12 in *; clear H12 h.\n    eapply join_canc; eauto.\n  Qed.\n\n(** NOTICE ABOUT REDUNDANT LEMMAS:\n Since sa_distribute <-> cross_split, many of the proofs below are redundant.\n This was part of an experiment to see whether, in general, sa_distributive is\n simpler to prove than cross_split.  Short answer:  not really.\n*)\n\nLemma distributive_equiv: forall A, @sa_distributive  _ (@Join_equiv A).\nProof.\n  repeat intro.\n destruct H; subst.\n exists x; exists x; repeat split; auto.\nQed.\n\nLemma cross_split_equiv : forall A,  @Cross_alg _ (@Join_equiv A).\nProof.\n  repeat intro.\n  destruct H; destruct H0. subst. exists (((z,z),z),z). repeat split; auto.\nQed.\n\nLemma distributive_fun: forall A (JOIN: Join A) (key: Type),\n               sa_distributive A -> @sa_distributive (key -> A) (Join_fun key A JOIN).\nProof.\nunfold sa_distributive; intros.\nassert (forall k, constructive_join_sub (x k) (z k)).\ndestruct X0 as [y ?].\nintro k; exists (y k); auto.\nassert (J := fun (k: key) => X (a k) (b k) (x k) (z k) (H k) (X1 k)).\nclear X.\nexists (fun k => projT1 (J k)).\nexists (fun k => projT1 (projT2 (J k))).\nsplit; [split|].\nexists (fun k => proj1_sig (fst (fst (projT2 (projT2 (J k))))));\nintro k; destruct (J k) as [ak' [bk' [[c c0] j]]];  simpl; destruct c; auto.\nexists (fun k => proj1_sig (snd (fst (projT2 (projT2 (J k))))));\nintro k; destruct (J k) as [ak' [bk' [[c c0] j]]];  simpl; destruct c0; auto.\nintro k; destruct (J k) as [ak' [bk' [[c c0] j]]]; simpl; auto.\nQed.\n\nInstance cross_split_fun: forall A (JOIN: Join A) (key: Type),\n          Cross_alg A -> Cross_alg (key -> A).\nProof.\nrepeat intro.\npose (f (x: key) := projT1 (X (a x) (b x) (c x) (d x) (z x) (H x) (H0 x))).\npose (g (x: key) := projT2 (X (a x) (b x) (c x) (d x) (z x) (H x) (H0 x))).\npose (ac (x: key) := fst (fst (fst (f x)))).\npose (ad (x: key) := snd (fst (fst (f x)))).\npose (bc (x: key) := snd (fst (f x))).\npose (bd (x: key) := snd (f x)).\nexists (ac,ad,bc,bd).\nunfold ac, ad, bc, bd, f; clear ac ad bc bd f.\nrepeat split; intro x; simpl;\ngeneralize (g x);  destruct (projT1 (X (a x) (b x) (c x) (d x) (z x) (H x) (H0 x))) as [[[? ?] ?] ?]; simpl; intuition.\nQed.\n\nLemma sa_distributive_prod : forall A B saA saB,\n  @sa_distributive A saA ->\n  @sa_distributive B saB ->\n  @sa_distributive (A * B) (Join_prod A _ B _).\nProof.\n intros.\n intros [a1 a2] [b1 b2] [c1 c2] [z1 z2] [? ?].\n intros [[d1 d2] [? ?]].\n simpl in *.\n destruct (X a1 b1 c1 z1 H) as [a1' [b1' [[[u1 ?] [v1 ?]] ?]]]. exists d1; auto.\n destruct (X0 a2 b2 c2 z2 H0) as [a2' [b2' [[[u2 ?] [v2 ?]] ?]]]. exists d2; auto.\n exists (a1',a2'). exists (b1',b2').\n split; [split|].\n exists (u1,u2); split; auto.\n exists (v1,v2); split; auto.\n split; auto.\nQed.\n\nInstance Cross_prod : forall A B saA saB,\n  @Cross_alg A saA ->\n  @Cross_alg B saB ->\n  @Cross_alg (A * B) (Join_prod _ saA _ saB).\nProof.\n  repeat intro.\n  destruct a as [a1 a2].\n  destruct b as [b1 b2].\n  destruct c as [c1 c2].\n  destruct d as [d1 d2].\n  destruct z as [z1 z2].\n  destruct H.\n  destruct H0.\n  simpl in *.\n  destruct (X a1 b1 c1 d1 z1)\n    as [p ?]; auto.\n  destruct p as [[[s1 p1] q1] r1].\n  destruct (X0 a2 b2 c2 d2 z2)\n    as [p ?]; auto.\n  destruct p as [[[s2 p2] q2] r2].\n  exists ((s1,s2),(p1,p2),(q1,q2),(r1,r2)).\n  simpl; intuition; (split; simpl; auto).\nQed.\n\nLemma sa_distributive_bij : forall A B JA bij,\n  @sa_distributive A JA ->\n  @sa_distributive B (Join_bij A JA B bij).\nProof.\n repeat intro.\n destruct X0 as [u ?]. unfold Join_bij; simpl.\n destruct bij. simpl.\n destruct (X (bij_g a) (bij_g b) (bij_g x) (bij_g z)) as [a' [b' [[[? ?] [? ?]] ?]]]; auto.\n exists (bij_g u); auto.\n exists (bij_f a'); exists (bij_f b'); split; [split|].\n exists (bij_f x0); hnf; repeat rewrite bij_gf; auto.\n exists (bij_f x1); hnf; repeat rewrite bij_gf; auto.\n hnf; repeat rewrite bij_gf; auto.\nQed.\n\nLemma Cross_bij : forall A B JA bij,\n  @Cross_alg A  JA ->\n  @Cross_alg B (Join_bij A JA B bij).\nProof.\n  repeat intro. unfold join, Join_bij in *.\n  destruct bij. simpl in *.\n  destruct (X (bij_g a) (bij_g b) (bij_g c) (bij_g d) (bij_g z)); auto.\n  destruct x as [[[s p] q] r].\n  exists (bij_f s,bij_f p,bij_f q,bij_f r).\n  simpl.\n  repeat rewrite bij_gf.\n  auto.\nQed.\n\nLemma constructive_join_sub_smash {A} {JA: Join A}{PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A}:\n  (forall x:A, {identity x}+{~identity x}) ->\n  forall a c : lifted JA,\n    constructive_join_sub (proj1_sig a) (proj1_sig c) ->\n    @constructive_join_sub (option (lifted JA)) _ (Some a) (Some c).\nProof.\nintros.\ndestruct X0 as [b ?].\ndestruct (X b).\nassert (a=c).\ndestruct a; destruct c. apply exist_ext.\nsimpl in j.\neapply join_eq; try apply j. apply join_comm; apply identity_unit; eauto.\nsubst c.\nexists None; constructor.\nexists (Some (mk_lifted _ (nonidentity_nonunit n))).\nconstructor.\ndestruct a; destruct c; simpl in *.\nauto.\nQed.\n\nLemma sa_distributive_smash : forall A JA {PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A},\n  (forall x:A, {identity x}+{~identity x}) ->\n  @sa_distributive A JA ->\n  sa_distributive (option (lifted JA)).\nProof.\nintros. unfold Join_lower, Join_lift; simpl.\nintros [[a Ha]|].\n2: intros; assert (b=z) by (inv H; auto); subst z; exists None; exists x;\n    split; [split|]; auto; [ econstructor  | ]; constructor.\nintros [[b Hb]|].\n2: intros b [[z Hz]|] ? ?;\n [assert (a=z) by (inv H; auto); subst z; clear H;\n   rewrite (proof_irr Hz Ha) in X1; clear Hz; exists b; exists None;\n    split; [split|]; auto\n | elimtype False; inv H];\n  [ econstructor  | ]; constructor.\nintros [[c Hc]|].\n2: intros ? ? ?; exists None; exists None; split; [split|]; econstructor; econstructor.\nintros [[z Hz]|] H Hj.\n2: elimtype False; inv H.\ndestruct (X0 a b c z) as [a' [b' [[? ?] ?]]].\ninv H. apply H3.\ninversion Hj.\ndestruct x.\nexists (lifted_obj l). inv H0.  apply H4.\nassert (c=z) by (inv H0; auto). replace c with z.\napply constructive_join_sub_refl.\ndestruct (X a') as [Pa'|Pa']; [exists None | exists (Some (mk_lifted _ (nonidentity_nonunit Pa'))) ].\nassert (b'=c) by (eapply join_eq; try apply j; apply identity_unit; eauto).\nsubst b'.\nexists (Some (mk_lifted c Hc)).\nsplit; [split|]; eauto. econstructor; econstructor.\napply constructive_join_sub_smash; auto.\nconstructor.\ndestruct (X b') as [Pb'|Pb']; [exists None | exists (Some (mk_lifted _ (nonidentity_nonunit Pb')))].\nsplit; [split|]; eauto.\napply constructive_join_sub_smash; auto.\neconstructor; econstructor.\napply join_unit2. econstructor; eauto.\nf_equal. apply exist_ext.\nsymmetry. eapply join_eq. eapply join_comm; apply j.  apply identity_unit; eauto.\nsplit; [split|]; eauto.\napply constructive_join_sub_smash; auto.\napply constructive_join_sub_smash; auto.\nconstructor; auto.\nQed.\n\nLemma Cross_smash : forall A (JA: Join A) {PA: Perm_alg A}{SA: Sep_alg A}{CA: Canc_alg A},\n  (forall x:A, {identity x}+{~identity x}) ->\n  Cross_alg A ->\n  Cross_alg (option (lifted JA)).\nProof.\n  intros.\n  hnf; intros.\n  destruct a as [[a Na] | ].\nFocus 2.\n  apply join_unit1_e in H; [ | apply None_identity]. subst z.\n  exists (None,None,c,d); repeat split; auto; constructor; auto.\n  destruct b as [[b Nb] | ].\nFocus 2.\n  apply join_unit2_e in H; [ | apply None_identity]. subst z.\n  exists (c,d,None,None); repeat split; auto; constructor; auto.\n  destruct c as [[c Nc] | ].\nFocus 2.\n  apply join_unit1_e in H0; [ | apply None_identity]. subst z.\n  exists (None, Some (exist nonunit _ Na), None, Some (exist nonunit _ Nb));\n     repeat split; auto; constructor.\n  destruct d as [[d Nd] | ].\nFocus 2.\n  apply join_unit2_e in H0; [ | apply None_identity]. subst z.\n  exists (Some (exist nonunit _ Na), None,Some (exist nonunit _ Nb),None); repeat split; auto; constructor; auto.\n\n  destruct z as [[z Nz] | ]; [ | elimtype False; inv H].\n  destruct (X0 a b c d z) as [[[[ac ad] bc] bd] [? [? [? ?]]]]; try (inv H; inv H0; auto). clear H H0.\n  destruct (X ac) as [Nac | Nac ].\n  apply Nac in H1. subst ad. apply Nac in H3. subst bc.\n  destruct (X bd) as [Nbd | Nbd].\n  apply join_unit2_e in H4; auto. subst d.\n  apply join_unit2_e in H2; auto. subst c.\n  rewrite (proof_irr Nd Na) in *. rewrite (proof_irr Nc Nb) in *.\n  exists (None, Some (exist nonunit a Na), Some (exist nonunit b Nb), None);\n    repeat split; auto;  constructor.\n  exists (None, Some (exist nonunit a Na), Some (exist nonunit c Nc),\n      Some (exist nonunit bd (nonidentity_nonunit Nbd))).\n  repeat split; auto;  try constructor. apply H2. apply H4.\n  destruct (X ad) as [Nad | Nad].\n  apply join_unit2_e in H1; auto. subst ac.\n  apply join_unit1_e in H4; auto. subst bd.\n  destruct (X bc) as [Nbc | Nbc].\n  apply join_unit2_e in H3; auto. subst c.\n  apply join_unit1_e in H2; auto. subst d.\n  rewrite (proof_irr Nd Nb) in *. rewrite (proof_irr Nc Na) in *.\n  exists (Some (exist nonunit a Na), None, None, Some (exist nonunit b Nb));\n    repeat split; auto; constructor.\n  apply nonidentity_nonunit in Nbc.\n  exists (Some (exist nonunit a Na), None, Some (exist nonunit _ Nbc), Some (exist nonunit d Nd));\n    repeat split; auto; constructor. apply H2. apply H3.\n  destruct (X bc) as [Nbc | Nbc].\n  apply join_unit2_e in H3; auto. subst ac.\n  apply join_unit1_e in H2; auto. subst bd.\n  apply nonidentity_nonunit in Nad.\n  exists (Some (exist nonunit c Nc), Some (exist nonunit _ Nad), None, Some (exist nonunit b Nb));\n    repeat split; auto; try constructor. apply H1. apply H4.\n  destruct (X bd) as [Nbd | Nbd].\n  apply join_unit2_e in H2; auto. subst bc.\n  apply join_unit2_e in H4; auto. subst ad.\n  apply nonidentity_nonunit in Nbc.   apply nonidentity_nonunit in Nad.\n    apply nonidentity_nonunit in Nac.\n  exists (Some (exist nonunit ac Nac), Some (exist nonunit d Nd),\n             Some (exist nonunit b Nb), None).\n    repeat split; auto; try constructor. apply H1. apply H3.\n  apply nonidentity_nonunit in Nbc.   apply nonidentity_nonunit in Nad.\n    apply nonidentity_nonunit in Nac. apply nonidentity_nonunit in Nbd.\n  exists (Some (exist nonunit ac Nac), Some (exist nonunit ad Nad),\n             Some (exist nonunit bc Nbc), Some (exist nonunit bd Nbd)).\n  repeat split; constructor; assumption.\nQed.\n\nLemma cross_split_fpm : forall A B\n      (JB: Join B) (PB: Perm_alg B)(SB : Sep_alg B)(CB: Canc_alg B)\n  (Bdec: forall x:B, {identity x}+{~identity x}) ,\n  Cross_alg B  ->\n  Cross_alg (fpm A (lifted JB)) .\nProof.\n  intros.\n  assert (Cross_alg (A -> option (lifted JB))).\n  apply cross_split_fun. apply Cross_smash; auto.\n\n  hnf. intros [a Ha] [b Hb] [c Hc] [d Hd] [z Hz].\n  simpl; intros.\n  destruct (X0 a b c d z); auto.\n  destruct x as [[[s p] q] r].\n  decompose [and] y; clear y.\n  assert (Hs : finMap s).\n  destruct Ha.\n  exists x.\n  intros.\n  spec H1 a0.\n  rewrite e in H1; auto. inv H1; auto.\n  assert (Hq : finMap q).\n  destruct Hb.\n  exists x.\n  intros.\n  spec H3 a0. inv H3; auto. rewrite H9; rewrite e; auto.\n  rewrite e in H8; auto. inv H8.\n  assert (Hr : finMap r).\n  destruct Hb.\n  exists x.\n  intros.\n  spec H3 a0.\n  rewrite e in H3; auto. inv H3; auto.\n  assert (Hp : finMap p).\n  destruct Hd.\n  exists x. intros. spec H5 a0. rewrite e in H5; auto. inv H5; auto.\n  exists (exist _ s Hs, exist _ p Hp, exist _ q Hq, exist _ r Hr).\n  simpl; intuition.\nQed.\n\nLemma Cross_fpm (A B: Type){JB: Join B} {PB: Perm_alg B}{PosB : Pos_alg B}\n  {CrB: Cross_alg B}:   Cross_alg (fpm A B) .\n (* Warning: This lemma is valid, but it's not clear that it's useful *)\nProof.\n  intros.\n  assert (Cross_alg (A -> option B)).\n  apply cross_split_fun.\n  unfold Cross_alg.\n  destruct a as [a |]. destruct b as [b|]. destruct c as [c|]. destruct d as [d|].\n  destruct z as [z|].\n  intros.\n  hnf in H.\n  assert (join a b z) by (clear - H; inv H; auto).\n  assert (join c d z) by (clear - H0; inv H0; auto).\n  clear H H0.\n  destruct (CrB _ _ _ _ _ H1 H2) as [[[[s p] q] r] [? [? [? ?]]]].\n  exists (Some s, Some p, Some q, Some r); repeat split; try constructor; auto.\n  intros. elimtype False; inv H.\n  intros. assert (z = Some c) by (clear - H0; inv H0; auto).\n  subst. assert (join a b c) by   (clear - H; inv H; auto).\n  exists (Some a, None, Some b, None); repeat split; try constructor; auto.\n  intros.\n  destruct d as [d|].\n  assert (z=Some d) by (clear - H0; inv H0; auto). subst z.\n  exists (None, Some a, None, Some b); repeat split; try constructor; auto.\n  clear - H; inv H; auto.\n  elimtype False; inv H0; inv H.\n  destruct c as [c|]. destruct d as [d|].\n  intros.\n  assert (z = Some a) by (clear - H; inv H; auto). subst z.\n  exists (Some c, Some d, None, None); repeat split; try constructor; eauto.\n  inv H0; auto.\n  intros. assert (z = Some a) by (clear - H; inv H; auto). subst.\n  assert (a=c) by (clear - H0; inv H0; auto). subst c.\n  exists (Some a, None, None, None); repeat split; try constructor; auto.\n  intros.\n  assert (z=d) by (clear - H0; inv H0; auto). subst d.\n  assert (z = Some a) by (inv H; auto).\n  subst.\n  exists (None, Some a, None, None); repeat split; try constructor; auto.\n  destruct b as [b|]. destruct c as [c|]. destruct d as [d|].\n  intros.\n  assert (z=Some b) by (inv H; auto). subst.\n  exists (None, None, Some c, Some d); repeat split; try constructor; auto.\n  inv H0; auto.\n  intros.\n  assert (z = Some b) by (inv H; auto); subst.\n  assert (c=b) by (inv H0; auto); subst.\n  exists (None, None, Some b, None); repeat split; try constructor; auto.\n  intros.\n  assert (z=d) by (clear - H0; inv H0; auto). subst d.\n  assert (z=Some b) by (inv H; auto). subst.\n  exists (None, None, None, Some b); repeat split; try constructor; auto.\n  intros. assert (z=None) by (inv H; auto).\n  subst.\n  exists (None, None, None, None).\n  inv H0; repeat split; constructor.\n\n  intros [a Ha] [b Hb] [c Hc] [d Hd] [z Hz].\n  simpl; intros.\n  unfold Cross_alg in X.\n  destruct (X (fun x => a x) b c d z); auto.\n  destruct x as [[[s p] q] r].\n  decompose [and] y; clear y.\n  assert (Hs : finMap s).\n  destruct Ha.\n  exists x.\n  intros.\n  spec H1 a0.\n  rewrite e in H1; auto. inv H1; auto.\n  assert (Hq : finMap q).\n  destruct Hb.\n  exists x.\n  intros.\n  spec H3 a0. inv H3; auto. rewrite H9; rewrite e; auto.\n  rewrite e in H8; auto. inv H8.\n  assert (Hr : finMap r).\n  destruct Hb.\n  exists x.\n  intros.\n  spec H3 a0.\n  rewrite e in H3; auto. inv H3; auto.\n  assert (Hp : finMap p).\n  destruct Hd.\n  exists x. intros. spec H5 a0. rewrite e in H5; auto. inv H5; auto.\n  exists (exist _ s Hs, exist _ p Hp, exist _ q Hq, exist _ r Hr).\n  simpl; intuition.\nQed.\n\nDefinition opposite_bij {A B} (b: bijection A B) : bijection B A :=\n Bijection _ _ (bij_g _ _ b) (bij_f _ _ b) (bij_gf _ _ b) (bij_fg _ _ b).\n\nLemma Cross_bij' : forall A B JA JB bij,\n  @Cross_alg B JB ->\n   JB =  (Join_bij A JA B bij) ->\n  @Cross_alg A  JA.\nProof.\n  repeat intro. subst. unfold join, Join_bij in *.\n  destruct bij. simpl in *.\n  destruct (X (bij_f a) (bij_f b) (bij_f c) (bij_f d) (bij_f z)).\n  red. repeat rewrite bij_gf; auto.\n  red. repeat rewrite bij_gf; auto.\n  destruct x as [[[s p] q] r].\n  exists (bij_g s,bij_g p,bij_g q,bij_g r).\n  unfold join in y.\n  repeat rewrite bij_gf in y.\n  auto.\nQed.\n\nDefinition option_bij {A B} (D: bijection A B) : bijection (option A) (option B).\n apply\n (Bijection (option A) (option B)\n    (fun a => match a with Some a' => Some (bij_f _ _ D a') | None => None end)\n    (fun b => match b with Some b' => Some (bij_g _ _ D b') | None => None end)).\n intros. destruct x; simpl; auto. rewrite bij_fg. auto.\n intros. destruct x; simpl; auto. rewrite bij_gf. auto.\nDefined.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/msl/cross_split.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21197695174630615}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*                 Xavier Leroy, INRIA Paris                           *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness of instruction selection for 64-bit integer operations *)\n\nRequire Import String Coqlib Maps Integers Floats Errors.\nRequire Archi.\nRequire Import AST Values Memory Globalenvs Events.\nRequire Import Cminor Op CminorSel.\nRequire Import SelectOp SelectOpproof SplitLong SplitLongproof.\nRequire Import SelectLong.\n\nLocal Open Scope cminorsel_scope.\nLocal Open Scope string_scope.\n\n(** * Correctness of the instruction selection functions for 64-bit operators *)\n\nSection CMCONSTR.\nContext mem `{external_calls_prf: ExternalCalls mem}.\nContext `{i64_helpers_correct_prf: !I64HelpersCorrect mem}.\n\nVariable prog: program.\nVariable hf: helper_functions.\nHypothesis HELPERS: helper_functions_declared prog hf.\nLet ge := Genv.globalenv prog.\nVariable sp: val.\nVariable e: env.\nVariable m: mem.\n\nDefinition unary_constructor_sound (cstr: expr -> expr) (sem: val -> val) : Prop :=\n  forall le a x,\n  eval_expr ge sp e m le a x ->\n  exists v, eval_expr ge sp e m le (cstr a) v /\\ Val.lessdef (sem x) v.\n\nDefinition binary_constructor_sound (cstr: expr -> expr -> expr) (sem: val -> val -> val) : Prop :=\n  forall le a x b y,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  exists v, eval_expr ge sp e m le (cstr a b) v /\\ Val.lessdef (sem x y) v.\n\nDefinition partial_unary_constructor_sound (cstr: expr -> expr) (sem: val -> option val) : Prop :=\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  sem x = Some y ->\n  exists v, eval_expr ge sp e m le (cstr a) v /\\ Val.lessdef y v.\n\nDefinition partial_binary_constructor_sound (cstr: expr -> expr -> expr) (sem: val -> val -> option val) : Prop :=\n  forall le a x b y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  sem x y = Some z ->\n  exists v, eval_expr ge sp e m le (cstr a b) v /\\ Val.lessdef z v.\n\nTheorem eval_longconst:\n  forall le n, eval_expr ge sp e m le (longconst n) (Vlong n).\nProof.\n  unfold longconst; intros; destruct Archi.splitlong.\n  apply SplitLongproof.eval_longconst.\n  EvalOp.\nQed.\n\nLemma is_longconst_sound:\n  forall v a n le,\n  is_longconst a = Some n -> eval_expr ge sp e m le a v -> v = Vlong n.\nProof with (try discriminate).\n  intros. unfold is_longconst in *. destruct Archi.splitlong.\n  eapply SplitLongproof.is_longconst_sound; eauto.\n  assert (a = Eop (Olongconst n) Enil).\n  { destruct a... destruct o... destruct e0... congruence. }\n  subst a. InvEval. auto.\nQed.\n\nTheorem eval_intoflong: unary_constructor_sound intoflong Val.loword.\nProof.\n  unfold intoflong; destruct Archi.splitlong. apply SplitLongproof.eval_intoflong.\n  red; intros. destruct (is_longconst a) as [n|] eqn:C.\n- TrivialExists. simpl. erewrite (is_longconst_sound x) by eauto. auto.\n- TrivialExists.\nQed.\n\nTheorem eval_longofintu: unary_constructor_sound longofintu Val.longofintu.\nProof.\n  unfold longofintu; destruct Archi.splitlong. apply SplitLongproof.eval_longofintu.\n  red; intros. destruct (is_intconst a) as [n|] eqn:C.\n- econstructor; split. apply eval_longconst.\n  exploit is_intconst_sound; eauto. intros; subst x. auto.\n- TrivialExists.\nQed.\n\nTheorem eval_longofint: unary_constructor_sound longofint Val.longofint.\nProof.\n  unfold longofint; destruct Archi.splitlong. apply SplitLongproof.eval_longofint.\n  red; intros. destruct (is_intconst a) as [n|] eqn:C.\n- econstructor; split. apply eval_longconst.\n  exploit is_intconst_sound; eauto. intros; subst x. auto.\n- TrivialExists.\nQed.\n\nTheorem eval_notl: unary_constructor_sound notl Val.notl.\nProof.\n  unfold notl; destruct Archi.splitlong. apply SplitLongproof.eval_notl.\n  red; intros. destruct (notl_match a).\n- InvEval. econstructor; split. apply eval_longconst. auto.\n- InvEval. subst. exists v1; split; auto. destruct v1; simpl; auto. rewrite Int64.not_involutive; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_andlimm: forall n, unary_constructor_sound (andlimm n) (fun v => Val.andl v (Vlong n)).\nProof.\n  unfold andlimm; intros; red; intros.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero.\n  exists (Vlong Int64.zero); split. apply eval_longconst.\n  subst. destruct x; simpl; auto. rewrite Int64.and_zero; auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.mone.\n  exists x; split. assumption.\n  subst. destruct x; simpl; auto. rewrite Int64.and_mone; auto.\n  destruct (andlimm_match a); InvEval; subst.\n- econstructor; split. apply eval_longconst. simpl. rewrite Int64.and_commut; auto.\n- TrivialExists. simpl. rewrite Val.andl_assoc. rewrite Int64.and_commut; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_andl: binary_constructor_sound andl Val.andl.\nProof.\n  unfold andl; destruct Archi.splitlong. apply SplitLongproof.eval_andl.\n  red; intros. destruct (andl_match a b).\n- InvEval. rewrite Val.andl_commut. apply eval_andlimm; auto.\n- InvEval. apply eval_andlimm; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_orlimm: forall n, unary_constructor_sound (orlimm n) (fun v => Val.orl v (Vlong n)).\nProof.\n  unfold orlimm; intros; red; intros.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero.\n  exists x; split; auto. subst. destruct x; simpl; auto. rewrite Int64.or_zero; auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.mone.\n  econstructor; split. apply eval_longconst. subst. destruct x; simpl; auto. rewrite Int64.or_mone; auto.\n  destruct (orlimm_match a); InvEval; subst.\n- econstructor; split. apply eval_longconst. simpl. rewrite Int64.or_commut; auto.\n- TrivialExists. simpl. rewrite Val.orl_assoc. rewrite Int64.or_commut; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_orl: binary_constructor_sound orl Val.orl.\nProof.\n  unfold orl; destruct Archi.splitlong. apply SplitLongproof.eval_orl.\n  red; intros.\n  assert (DEFAULT: exists v, eval_expr ge sp e m le (Eop Oorl (a:::b:::Enil)) v /\\ Val.lessdef (Val.orl x y) v) by TrivialExists.\n  assert (ROR: forall v n1 n2,\n    Int.add n1 n2 = Int64.iwordsize' ->\n    Val.lessdef (Val.orl (Val.shll v (Vint n1)) (Val.shrlu v (Vint n2)))\n                (Val.rorl v (Vint n2))).\n  { intros. destruct v; simpl; auto.\n    destruct (Int.ltu n1 Int64.iwordsize') eqn:N1; auto.\n    destruct (Int.ltu n2 Int64.iwordsize') eqn:N2; auto.\n    simpl. rewrite <- Int64.or_ror'; auto. }\n  destruct (orl_match a b).\n- InvEval. rewrite Val.orl_commut. apply eval_orlimm; auto.\n- InvEval. apply eval_orlimm; auto.\n- predSpec Int.eq Int.eq_spec (Int.add n1 n2) Int64.iwordsize'; auto.\n  destruct (same_expr_pure t1 t2) eqn:?; auto.\n  InvEval. exploit eval_same_expr; eauto. intros [EQ1 EQ2]; subst.\n  exists (Val.rorl v0 (Vint n2)); split. EvalOp. apply ROR; auto.\n- predSpec Int.eq Int.eq_spec (Int.add n1 n2) Int64.iwordsize'; auto.\n  destruct (same_expr_pure t1 t2) eqn:?; auto.\n  InvEval. exploit eval_same_expr; eauto. intros [EQ1 EQ2]; subst.\n  exists (Val.rorl v1 (Vint n2)); split. EvalOp. rewrite Val.orl_commut. apply ROR; auto.\n- apply DEFAULT.\nQed.\n\nTheorem eval_xorlimm: forall n, unary_constructor_sound (xorlimm n) (fun v => Val.xorl v (Vlong n)).\nProof.\n  unfold xorlimm; intros; red; intros.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero.\n  exists x; split; auto. subst. destruct x; simpl; auto. rewrite Int64.xor_zero; auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.mone.\n  replace (Val.xorl x (Vlong n)) with (Val.notl x). apply eval_notl; auto.\n  subst n. destruct x; simpl; auto.\n  destruct (xorlimm_match a); InvEval; subst.\n- econstructor; split. apply eval_longconst. simpl. rewrite Int64.xor_commut; auto.\n- TrivialExists. simpl. rewrite Val.xorl_assoc. rewrite Int64.xor_commut; auto.\n- TrivialExists. simpl. destruct v1; simpl; auto. unfold Int64.not.\n  rewrite Int64.xor_assoc. apply f_equal. apply f_equal. apply f_equal.\n  apply Int64.xor_commut.\n- TrivialExists.\nQed.\n\nTheorem eval_xorl: binary_constructor_sound xorl Val.xorl.\nProof.\n  unfold xorl; destruct Archi.splitlong. apply SplitLongproof.eval_xorl.\n  red; intros. destruct (xorl_match a b).\n- InvEval. rewrite Val.xorl_commut. apply eval_xorlimm; auto.\n- InvEval. apply eval_xorlimm; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_shllimm: forall n, unary_constructor_sound (fun e => shllimm e n) (fun v => Val.shll v (Vint n)).\nProof.\n  intros; unfold shllimm. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shllimm; auto.\n  red; intros.\n  predSpec Int.eq Int.eq_spec n Int.zero.\n  exists x; split; auto. subst n; destruct x; simpl; auto.\n  destruct (Int.ltu Int.zero Int64.iwordsize'); auto.\n  change (Int64.shl' i Int.zero) with (Int64.shl i Int64.zero). rewrite Int64.shl_zero; auto.\n  destruct (Int.ltu n Int64.iwordsize') eqn:LT; simpl.\n  assert (DEFAULT: exists v, eval_expr ge sp e m le (Eop (Oshllimm n) (a:::Enil)) v\n                         /\\  Val.lessdef (Val.shll x (Vint n)) v) by TrivialExists.\n  destruct (shllimm_match a); InvEval.\n- TrivialExists. simpl; rewrite LT; auto.\n- destruct (Int.ltu (Int.add n n1) Int64.iwordsize') eqn:LT'; auto.\n  subst. econstructor; split. EvalOp. simpl; eauto.\n  destruct v1; simpl; auto. rewrite LT'.\n  destruct (Int.ltu n1 Int64.iwordsize') eqn:LT1; auto.\n  simpl; rewrite LT. rewrite Int.add_commut, Int64.shl'_shl'; auto. rewrite Int.add_commut; auto.\n- destruct (shift_is_scale n); auto.\n  TrivialExists. simpl. destruct v1; simpl; auto.\n  rewrite LT. rewrite ! Int64.repr_unsigned. rewrite Int64.shl'_one_two_p.\n  rewrite ! Int64.shl'_mul_two_p.  rewrite Int64.mul_add_distr_l. auto.\n- destruct (shift_is_scale n); auto.\n  TrivialExists. simpl. destruct x; simpl; auto.\n  rewrite LT. rewrite ! Int64.repr_unsigned. rewrite Int64.shl'_one_two_p.\n  rewrite ! Int64.shl'_mul_two_p. rewrite Int64.add_zero. auto.\n- TrivialExists. constructor; eauto. constructor. EvalOp. simpl; eauto. constructor. auto.\nQed.\n\nTheorem eval_shrluimm: forall n, unary_constructor_sound (fun e => shrluimm e n) (fun v => Val.shrlu v (Vint n)).\nProof.\n  intros; unfold shrluimm. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shrluimm; auto.\n  red; intros.\n  predSpec Int.eq Int.eq_spec n Int.zero.\n  exists x; split; auto. subst n; destruct x; simpl; auto.\n  destruct (Int.ltu Int.zero Int64.iwordsize'); auto.\n  change (Int64.shru' i Int.zero) with (Int64.shru i Int64.zero). rewrite Int64.shru_zero; auto.\n  destruct (Int.ltu n Int64.iwordsize') eqn:LT; simpl.\n  assert (DEFAULT: exists v, eval_expr ge sp e m le (Eop (Oshrluimm n) (a:::Enil)) v\n                         /\\  Val.lessdef (Val.shrlu x (Vint n)) v) by TrivialExists.\n  destruct (shrluimm_match a); InvEval.\n- TrivialExists. simpl; rewrite LT; auto.\n- destruct (Int.ltu (Int.add n n1) Int64.iwordsize') eqn:LT'; auto.\n  subst. econstructor; split. EvalOp. simpl; eauto.\n  destruct v1; simpl; auto. rewrite LT'.\n  destruct (Int.ltu n1 Int64.iwordsize') eqn:LT1; auto.\n  simpl; rewrite LT. rewrite Int.add_commut, Int64.shru'_shru'; auto. rewrite Int.add_commut; auto.\n- apply DEFAULT.\n- TrivialExists. constructor; eauto. constructor. EvalOp. simpl; eauto. constructor. auto.\nQed.\n\nTheorem eval_shrlimm: forall n, unary_constructor_sound (fun e => shrlimm e n) (fun v => Val.shrl v (Vint n)).\nProof.\n  intros; unfold shrlimm. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shrlimm; auto.\n  red; intros.\n  predSpec Int.eq Int.eq_spec n Int.zero.\n  exists x; split; auto. subst n; destruct x; simpl; auto.\n  destruct (Int.ltu Int.zero Int64.iwordsize'); auto.\n  change (Int64.shr' i Int.zero) with (Int64.shr i Int64.zero). rewrite Int64.shr_zero; auto.\n  destruct (Int.ltu n Int64.iwordsize') eqn:LT; simpl.\n  assert (DEFAULT: exists v, eval_expr ge sp e m le (Eop (Oshrlimm n) (a:::Enil)) v\n                         /\\  Val.lessdef (Val.shrl x (Vint n)) v) by TrivialExists.\n  destruct (shrlimm_match a); InvEval.\n- TrivialExists. simpl; rewrite LT; auto.\n- destruct (Int.ltu (Int.add n n1) Int64.iwordsize') eqn:LT'; auto.\n  subst. econstructor; split. EvalOp. simpl; eauto.\n  destruct v1; simpl; auto. rewrite LT'.\n  destruct (Int.ltu n1 Int64.iwordsize') eqn:LT1; auto.\n  simpl; rewrite LT. rewrite Int.add_commut, Int64.shr'_shr'; auto. rewrite Int.add_commut; auto.\n- apply DEFAULT.\n- TrivialExists. constructor; eauto. constructor. EvalOp. simpl; eauto. constructor. auto.\nQed.\n\nTheorem eval_shll: binary_constructor_sound shll Val.shll.\nProof.\n  unfold shll. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shll; auto.\n  red; intros. destruct (is_intconst b) as [n2|] eqn:C.\n- exploit is_intconst_sound; eauto. intros EQ; subst y. apply eval_shllimm; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_shrlu: binary_constructor_sound shrlu Val.shrlu.\nProof.\n  unfold shrlu. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shrlu; auto.\n  red; intros. destruct (is_intconst b) as [n2|] eqn:C.\n- exploit is_intconst_sound; eauto. intros EQ; subst y. apply eval_shrluimm; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_shrl: binary_constructor_sound shrl Val.shrl.\nProof.\n  unfold shrl. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shrl; auto.\n  red; intros. destruct (is_intconst b) as [n2|] eqn:C.\n- exploit is_intconst_sound; eauto. intros EQ; subst y. apply eval_shrlimm; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_negl: unary_constructor_sound negl Val.negl.\nProof.\n  unfold negl. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_negl; auto.\n  red; intros. destruct (is_longconst a) as [n|] eqn:C.\n- exploit is_longconst_sound; eauto. intros EQ; subst x.\n  econstructor; split. apply eval_longconst. auto.\n- TrivialExists.\nQed.\n\nTheorem eval_addlimm: forall n, unary_constructor_sound (addlimm n) (fun v => Val.addl v (Vlong n)).\nProof.\n  unfold addlimm; intros; red; intros.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero.\n  subst. exists x; split; auto.\n  destruct x; simpl; rewrite ?Int64.add_zero, ?Ptrofs.add_zero; auto.\n  destruct (addlimm_match a); InvEval.\n- econstructor; split. apply eval_longconst. rewrite Int64.add_commut; auto.\n- inv H. simpl in H6. TrivialExists. simpl.\n  erewrite eval_offset_addressing_total_64 by eauto. rewrite Int64.repr_signed; auto.\n- TrivialExists. simpl. rewrite Int64.repr_signed; auto.\nQed.\n\nTheorem eval_addl: binary_constructor_sound addl Val.addl.\nProof.\n  assert (A: forall x y, Int64.repr (x + y) = Int64.add (Int64.repr x) (Int64.repr y)).\n  { intros; apply Int64.eqm_samerepr; auto with ints. }\n  assert (B: forall id ofs n, Archi.ptr64 = true ->\n             Genv.symbol_address ge id (Ptrofs.add ofs (Ptrofs.repr n)) =\n             Val.addl (Genv.symbol_address ge id ofs) (Vlong (Int64.repr n))).\n  { intros. replace (Ptrofs.repr n) with (Ptrofs.of_int64 (Int64.repr n)) by auto with ptrofs.\n    apply Genv.shift_symbol_address_64; auto. }\n  unfold addl. destruct Archi.splitlong eqn:SL.\n  apply SplitLongproof.eval_addl. eauto. apply Archi.splitlong_ptr32; auto.\n  red; intros; destruct (addl_match a b); InvEval.\n- rewrite Val.addl_commut. apply eval_addlimm; auto.\n- apply eval_addlimm; auto.\n- subst. TrivialExists. simpl. rewrite A, Val.addl_permut_4. auto.\n- subst. TrivialExists. simpl. rewrite A, Val.addl_assoc. decEq; decEq. rewrite Val.addl_permut. auto.\n- subst. TrivialExists. simpl. rewrite A, Val.addl_permut_4. rewrite <- Val.addl_permut. rewrite <- Val.addl_assoc. auto.\n- subst. TrivialExists. simpl. rewrite Val.addl_commut; auto.\n- subst. TrivialExists.\n- subst. TrivialExists. simpl. rewrite ! Val.addl_assoc. rewrite (Val.addl_commut y). auto.\n- subst. TrivialExists. simpl. rewrite ! Val.addl_assoc. auto.\n- TrivialExists. simpl.\n  unfold Val.addl. destruct Archi.ptr64, x, y; auto.\n  + rewrite Int64.add_zero; auto.\n  + rewrite Ptrofs.add_assoc, Ptrofs.add_zero. auto.\n  + rewrite Ptrofs.add_assoc, Ptrofs.add_zero. auto.\n  + rewrite Int64.add_zero; auto.\nQed.\n\nTheorem eval_subl: binary_constructor_sound subl Val.subl.\nProof.\n  unfold subl. destruct Archi.splitlong eqn:SL.\n  apply SplitLongproof.eval_subl. eauto. apply Archi.splitlong_ptr32; auto.\n  red; intros; destruct (subl_match a b); InvEval.\n- rewrite Val.subl_addl_opp. apply eval_addlimm; auto.\n- subst. rewrite Val.subl_addl_l. rewrite Val.subl_addl_r.\n  rewrite Val.addl_assoc. simpl. rewrite Int64.add_commut. rewrite <- Int64.sub_add_opp.\n  replace (Int64.repr (n1 - n2)) with (Int64.sub (Int64.repr n1) (Int64.repr n2)).\n  apply eval_addlimm; EvalOp.\n  apply Int64.eqm_samerepr; auto with ints.\n- subst. rewrite Val.subl_addl_l. apply eval_addlimm; EvalOp.\n- subst. rewrite Val.subl_addl_r.\n  replace (Int64.repr (-n2)) with (Int64.neg (Int64.repr n2)).\n  apply eval_addlimm; EvalOp.\n  apply Int64.eqm_samerepr; auto with ints.\n- TrivialExists.\nQed.\n\nTheorem eval_mullimm_base: forall n, unary_constructor_sound (mullimm_base n) (fun v => Val.mull v (Vlong n)).\nProof.\n  intros; unfold mullimm_base. red; intros.\n  generalize (Int64.one_bits'_decomp n); intros D.\n  destruct (Int64.one_bits' n) as [ | i [ | j [ | ? ? ]]] eqn:B.\n- TrivialExists.\n- replace (Val.mull x (Vlong n)) with (Val.shll x (Vint i)).\n  apply eval_shllimm; auto.\n  simpl in D. rewrite D, Int64.add_zero. destruct x; simpl; auto.\n  rewrite (Int64.one_bits'_range n) by (rewrite B; auto with coqlib).\n  rewrite Int64.shl'_mul; auto.\n- set (le' := x :: le).\n  assert (A0: eval_expr ge sp e m le' (Eletvar O) x) by (constructor; reflexivity).\n  exploit (eval_shllimm i). eexact A0. intros (v1 & A1 & B1).\n  exploit (eval_shllimm j). eexact A0. intros (v2 & A2 & B2).\n  exploit (eval_addl). eexact A1. eexact A2. intros (v3 & A3 & B3).\n  exists v3; split. econstructor; eauto.\n  rewrite D. simpl. rewrite Int64.add_zero. destruct x; auto.\n  simpl in *.\n  rewrite (Int64.one_bits'_range n) in B1 by (rewrite B; auto with coqlib).\n  rewrite (Int64.one_bits'_range n) in B2 by (rewrite B; auto with coqlib).\n  inv B1; inv B2. simpl in B3; inv B3.\n  rewrite Int64.mul_add_distr_r. rewrite <- ! Int64.shl'_mul. auto.\n- TrivialExists.\nQed.\n\nTheorem eval_mullimm: forall n, unary_constructor_sound (mullimm n) (fun v => Val.mull v (Vlong n)).\nProof.\n  unfold mullimm. intros; red; intros.\n  destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_mullimm; eauto.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero.\n  exists (Vlong Int64.zero); split. apply eval_longconst.\n  destruct x; simpl; auto. subst n; rewrite Int64.mul_zero; auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.one.\n  exists x; split; auto.\n  destruct x; simpl; auto. subst n; rewrite Int64.mul_one; auto.\n  destruct (mullimm_match a); InvEval.\n- econstructor; split. apply eval_longconst. rewrite Int64.mul_commut; auto.\n- exploit (eval_mullimm_base n); eauto. intros (v2 & A2 & B2).\n  exploit (eval_addlimm (Int64.mul n (Int64.repr n2))). eexact A2. intros (v3 & A3 & B3).\n  exists v3; split; auto.\n  destruct v1; simpl; auto.\n  simpl in B2; inv B2. simpl in B3; inv B3. rewrite Int64.mul_add_distr_l.\n  rewrite (Int64.mul_commut n). auto.\n- apply eval_mullimm_base; auto.\nQed.\n\nTheorem eval_mull: binary_constructor_sound mull Val.mull.\nProof.\n  unfold mull. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_mull; auto.\n  red; intros; destruct (mull_match a b); InvEval.\n- rewrite Val.mull_commut. apply eval_mullimm; auto.\n- apply eval_mullimm; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_mullhu:\n  forall n, unary_constructor_sound (fun a => mullhu a n) (fun v => Val.mullhu v (Vlong n)).\nProof.\n  unfold mullhu; intros. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_mullhu; auto.\n  red; intros. TrivialExists. constructor. eauto. constructor. apply eval_longconst. constructor. auto.\nQed.\n\nTheorem eval_mullhs:\n  forall n, unary_constructor_sound (fun a => mullhs a n) (fun v => Val.mullhs v (Vlong n)).\nProof.\n  unfold mullhs; intros. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_mullhs; auto.\n  red; intros. TrivialExists. constructor. eauto. constructor. apply eval_longconst. constructor. auto.\nQed.\n\nTheorem eval_shrxlimm:\n  forall le a n x z,\n  eval_expr ge sp e m le a x ->\n  Val.shrxl x (Vint n) = Some z ->\n  exists v, eval_expr ge sp e m le (shrxlimm a n) v /\\ Val.lessdef z v.\nProof.\n  unfold shrxlimm; intros. destruct Archi.splitlong eqn:SL.\n+ eapply SplitLongproof.eval_shrxlimm; eauto using Archi.splitlong_ptr32.\n+ predSpec Int.eq Int.eq_spec n Int.zero.\n- subst n. destruct x; simpl in H0; inv H0. econstructor; split; eauto.\n  change (Int.ltu Int.zero (Int.repr 63)) with true. simpl. rewrite Int64.shrx'_zero; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_divls_base: partial_binary_constructor_sound divls_base Val.divls.\nProof.\n  unfold divls_base; red; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_divls_base; eauto.\n  TrivialExists.\nQed.\n\nTheorem eval_modls_base: partial_binary_constructor_sound modls_base Val.modls.\nProof.\n  unfold modls_base; red; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_modls_base; eauto.\n  TrivialExists.\nQed.\n\nTheorem eval_divlu_base: partial_binary_constructor_sound divlu_base Val.divlu.\nProof.\n  unfold divlu_base; red; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_divlu_base; eauto.\n  TrivialExists.\nQed.\n\nTheorem eval_modlu_base: partial_binary_constructor_sound modlu_base Val.modlu.\nProof.\n  unfold modlu_base; red; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_modlu_base; eauto.\n  TrivialExists.\nQed.\n\nTheorem eval_cmplu:\n  forall c le a x b y v,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.cmplu (Mem.valid_pointer m) c x y = Some v ->\n  eval_expr ge sp e m le (cmplu c a b) v.\nProof.\n  unfold cmplu; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_cmplu; eauto using Archi.splitlong_ptr32.\n  unfold Val.cmplu in H1.\n  destruct (Val.cmplu_bool (Mem.valid_pointer m) c x y) as [vb|] eqn:C; simpl in H1; inv H1.\n  destruct (is_longconst a) as [n1|] eqn:LC1; destruct (is_longconst b) as [n2|] eqn:LC2;\n  try (assert (x = Vlong n1) by (eapply is_longconst_sound; eauto));\n  try (assert (y = Vlong n2) by (eapply is_longconst_sound; eauto));\n  subst.\n- simpl in C; inv C. EvalOp. destruct (Int64.cmpu c n1 n2); reflexivity.\n- EvalOp. simpl. rewrite Val.swap_cmplu_bool. rewrite C; auto.\n- EvalOp. simpl; rewrite C; auto.\n- EvalOp. simpl; rewrite C; auto.\nQed.\n\nTheorem eval_cmpl:\n  forall c le a x b y v,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.cmpl c x y = Some v ->\n  eval_expr ge sp e m le (cmpl c a b) v.\nProof.\n  unfold cmpl; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_cmpl; eauto.\n  unfold Val.cmpl in H1.\n  destruct (Val.cmpl_bool c x y) as [vb|] eqn:C; simpl in H1; inv H1.\n  destruct (is_longconst a) as [n1|] eqn:LC1; destruct (is_longconst b) as [n2|] eqn:LC2;\n  try (assert (x = Vlong n1) by (eapply is_longconst_sound; eauto));\n  try (assert (y = Vlong n2) by (eapply is_longconst_sound; eauto));\n  subst.\n- simpl in C; inv C. EvalOp. destruct (Int64.cmp c n1 n2); reflexivity.\n- EvalOp. simpl. rewrite Val.swap_cmpl_bool. rewrite C; auto.\n- EvalOp. simpl; rewrite C; auto.\n- EvalOp. simpl; rewrite C; auto.\nQed.\n\nTheorem eval_longoffloat: partial_unary_constructor_sound longoffloat Val.longoffloat.\nProof.\n  unfold longoffloat; red; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_longoffloat; eauto.\n  TrivialExists.\nQed.\n\nTheorem eval_floatoflong: partial_unary_constructor_sound floatoflong Val.floatoflong.\nProof.\n  unfold floatoflong; red; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_floatoflong; eauto.\n  TrivialExists.\nQed.\n\nTheorem eval_longofsingle: partial_unary_constructor_sound longofsingle Val.longofsingle.\nProof.\n  unfold longofsingle; red; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_longofsingle; eauto.\n  TrivialExists.\nQed.\n\nTheorem eval_singleoflong: partial_unary_constructor_sound singleoflong Val.singleoflong.\nProof.\n  unfold singleoflong; red; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_singleoflong; eauto.\n  TrivialExists.\nQed.\n\nEnd CMCONSTR.\n", "meta": {"author": "CertiKOS", "repo": "compcert.old", "sha": "1fbd4e9beeb9e58b15f7f20ab1c949f6381a4105", "save_path": "github-repos/coq/CertiKOS-compcert.old", "path": "github-repos/coq/CertiKOS-compcert.old/compcert.old-1fbd4e9beeb9e58b15f7f20ab1c949f6381a4105/x86/SelectLongproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.21197695174630612}}
{"text": "Require Import oeuf.Common oeuf.Monads.\nRequire Import oeuf.Metadata.\nRequire String.\nRequire Import oeuf.ListLemmas.\nRequire Import oeuf.StepLib.\nRequire Import oeuf.HigherValue.\n\nRequire Import Psatz.\n\nRequire oeuf.ElimFunc4.\nRequire oeuf.SelfClose.\n\nModule A := ElimFunc4.\nModule B := SelfClose.\n\n\n\nDefinition compile :=\n    let fix go e :=\n        let fix go_list es :=\n            match es with\n            | [] => []\n            | e :: es => go e :: go_list es\n            end in\n        match e with\n        | A.Value v => B.Value v\n        | A.Arg => B.Arg\n        | A.UpVar n => B.Deref B.Self n\n        | A.Deref e off => B.Deref (go e) off\n        | A.Call f a => B.Call (go f) (go a)\n        | A.MkConstr tag args => B.MkConstr tag (go_list args)\n        | A.Elim loop cases target => B.Elim (go loop) (go_list cases) (go target)\n        | A.MkClose fname free => B.MkClose fname (go_list free)\n        | A.OpaqueOp op args => B.OpaqueOp op (go_list args)\n        end in go.\n\nDefinition compile_list :=\n    let go := compile in\n    let fix go_list es :=\n        match es with\n        | [] => []\n        | e :: es => go e :: go_list es\n        end in go_list.\n\nLtac refold_compile :=\n    fold compile_list in *.\n\n\nDefinition compile_cu (cu : list A.expr * list metadata) : list B.expr * list metadata :=\n    let '(exprs, metas) := cu in\n    let exprs' := compile_list exprs in\n    (exprs', metas).\n\n\nLemma compile_list_Forall : forall aes bes,\n    compile_list aes = bes ->\n    Forall2 (fun a b => compile a = b) aes bes.\ninduction aes; destruct bes; intros0 Hcomp; simpl in Hcomp; try discriminate.\n- constructor.\n- invc Hcomp. eauto.\nQed.\n\nLemma compile_list_length : forall es,\n    length (compile_list es) = length es.\nintros. induction es.\n- reflexivity.\n- simpl. f_equal. eauto.\nQed.\n\n\n\nInductive I_expr : A.expr -> B.expr -> Prop :=\n| IArg : I_expr A.Arg B.Arg\n| IUpVar : forall n,\n        I_expr (A.UpVar n)\n               (B.Deref B.Self n)\n| IDeref : forall ae be off,\n        I_expr ae be ->\n        I_expr (A.Deref ae off)\n               (B.Deref be off)\n| ICall : forall af aa bf ba,\n        I_expr af bf ->\n        I_expr aa ba ->\n        I_expr (A.Call af aa) (B.Call bf ba)\n| IConstr : forall tag aargs bargs,\n        Forall2 I_expr aargs bargs ->\n        I_expr (A.MkConstr tag aargs) (B.MkConstr tag bargs)\n| IElim : forall aloop bloop acases bcases atarget btarget,\n        I_expr aloop bloop ->\n        Forall2 I_expr acases bcases ->\n        I_expr atarget btarget ->\n        I_expr (A.Elim aloop acases atarget) (B.Elim bloop bcases btarget)\n| IClose : forall fname afree bfree,\n        Forall2 (I_expr) afree bfree ->\n        I_expr (A.MkClose fname afree) (B.MkClose fname bfree)\n| IValue : forall v,\n        I_expr (A.Value v) (B.Value v)\n| IOpaqueOp : forall op aargs bargs,\n        Forall2 I_expr aargs bargs ->\n        I_expr (A.OpaqueOp op aargs) (B.OpaqueOp op bargs)\n.\n\nInductive I : A.state -> B.state -> Prop :=\n| IRun : forall ae al ak be ba fname free bk,\n        I_expr ae be -> (* current expressions match *)\n        al = (ba :: free) -> (* arg and local environments match *)\n        (forall v, (* closures match when given a value *)\n            I (ak v) (bk v)) ->\n        I (A.Run ae al ak) (B.Run be ba (Close fname free) bk)\n\n| IStop : forall v,\n        I (A.Stop v) (B.Stop v).\n\n\n\nLemma I_expr_value : forall a b,\n    I_expr a b ->\n    A.is_value a ->\n    B.is_value b.\ninduction a using A.expr_ind'; intros0 II Aval; invc Aval; invc II.\n- constructor. \nQed.\nHint Resolve I_expr_value.\n\nLemma I_expr_value' : forall b a,\n    I_expr a b ->\n    B.is_value b ->\n    A.is_value a.\ninduction b using B.expr_ind'; intros0 II Bval; invc Bval; invc II.\n- constructor. \nQed.\n\nLemma I_expr_not_value : forall a b,\n    I_expr a b ->\n    ~A.is_value a ->\n    ~B.is_value b.\nintros. intro. fwd eapply I_expr_value'; eauto.\nQed.\nHint Resolve I_expr_not_value.\n\n\nLemma I_expr_not_value' : forall a b,\n    I_expr a b ->\n    ~B.is_value b ->\n    ~A.is_value a.\nintros. intro. fwd eapply I_expr_value; eauto.\nQed.\n\nLemma Forall_I_expr_value : forall aes bes,\n    Forall2 I_expr aes bes ->\n    Forall A.is_value aes ->\n    Forall B.is_value bes.\nintros. list_magic_on (aes, (bes, tt)).\nQed.\nHint Resolve Forall_I_expr_value.\n\nLemma I_expr_map_value : forall vs bes,\n    Forall2 I_expr (map A.Value vs) bes ->\n    bes = map B.Value vs.\ninduction vs; intros0 II; invc II.\n- reflexivity.\n- simpl. f_equal.\n  + on >I_expr, invc. reflexivity.\n  + apply IHvs. eauto.\nQed.\n\n\nTheorem compile_I_expr : forall ae be,\n    compile ae = be ->\n    I_expr ae be.\ninduction ae using A.expr_rect_mut with\n    (Pl := fun aes => forall bes,\n        compile_list aes = bes ->\n        Forall2 I_expr aes bes);\nintros0 Hcomp;\nsimpl in Hcomp; refold_compile; try rewrite <- Hcomp in *;\ntry solve [eauto | constructor; eauto].\nQed.\n\nLtac i_ctor := intros; constructor; eauto.\nLtac i_lem H := intros; eapply H; eauto.\n\nTheorem I_sim : forall AE BE a a' b,\n    compile_list AE = BE ->\n    I a b ->\n    A.sstep AE a a' ->\n    exists b',\n        B.splus BE b b' /\\\n        I a' b'.\n\ndestruct a as [ae al ak | ae];\nintros0 Henv II Astep; [ | solve [invc Astep] ].\n\ninv Astep; invc II; try on (I_expr _ _), invc.\n\n- (* SArg *)\n  eexists. split. eapply B.SPlusOne, B.SArg.\n  simpl in *. inject_some. eauto.\n\n- (* SUpVar *)\n  eexists. split.\n    { eapply B.SPlusCons. eapply B.SDerefStep. inversion 1.\n      eapply B.SPlusCons. eapply B.SSelf.\n      eapply B.SPlusOne.  eapply B.SDerefinateClose; eauto. }\n  eauto.\n\n- (* SDerefStep *)\n  eexists. split. eapply B.SPlusOne, B.SDerefStep; eauto.\n  i_ctor. i_ctor. i_ctor. i_ctor.\n\n- (* SDerefinate *)\n  on (I_expr (A.Value (Constr _ _)) _), invc.\n\n  eexists. split. eapply B.SPlusOne, B.SDerefinateConstr; eauto.\n  eauto.\n\n- (* SCloseStep *)\n  on _, invc_using Forall2_3part_inv.\n  eexists. split. eapply B.SPlusOne, B.SCloseStep; eauto.\n  i_ctor. i_ctor. i_ctor.\n  i_lem Forall2_app. i_lem Forall2_app. i_ctor. i_ctor.\n\n- (* SCloseDone *)\n  fwd i_lem I_expr_map_value. subst.\n  eexists. split. eapply B.SPlusOne, B.SCloseDone; eauto.\n  eauto.\n\n- (* SConstrStep *)\n  on _, invc_using Forall2_3part_inv.\n  eexists. split. eapply B.SPlusOne, B.SConstrStep; eauto.\n  i_ctor. i_ctor. i_ctor.\n  i_lem Forall2_app. i_lem Forall2_app. i_ctor. i_ctor.\n\n- (* SConstrDone *)\n  fwd i_lem I_expr_map_value. subst.\n  eexists. split. eapply B.SPlusOne, B.SConstrDone; eauto.\n  eauto.\n\n- (* SOpaqueOpStep *)\n  on _, invc_using Forall2_3part_inv.\n  eexists. split. eapply B.SPlusOne, B.SOpaqueOpStep; eauto.\n  i_ctor. i_ctor. i_ctor.\n  i_lem Forall2_app. i_lem Forall2_app. i_ctor. i_ctor.\n\n- (* SOpaqueOpDone *)\n  fwd i_lem I_expr_map_value. subst.\n  eexists. split. eapply B.SPlusOne, B.SOpaqueOpDone; eauto.\n  eauto.\n\n- (* SCallL *)\n  eexists. split. eapply B.SPlusOne, B.SCallL; eauto.\n  i_ctor. i_ctor. i_ctor. i_ctor.\n\n- (* SCallR *)\n  eexists. split. eapply B.SPlusOne, B.SCallR; eauto.\n  i_ctor. i_ctor. i_ctor. i_ctor.\n\n- (* SMakeCall *)\n  on (I_expr (A.Value (Close _ _)) _), invc.\n\n  fwd eapply Forall2_nth_error_ex with (xs := AE) (ys := compile_list AE); eauto.\n    { eapply compile_list_Forall. reflexivity. }\n    break_exists. break_and.\n  eexists. split.\n  eapply B.SPlusOne.\n  on (I_expr _ _ ), invc.\n  try eapply B.SMakeCall; eauto using compile_I_expr.\n  i_ctor.\n  eauto using compile_I_expr.\n\n- (* SElimStepLoop *)\n  eexists. split. eapply B.SPlusOne. i_lem B.SElimStepLoop.\n  i_ctor. i_ctor. i_ctor. i_ctor.\n\n- (* SElimStep *)\n  eexists. split. eapply B.SPlusOne. i_lem B.SElimStep.\n  i_ctor. i_ctor. i_ctor. i_ctor.\n\n- (* SEliminate *)\n  fwd i_lem Forall2_nth_error_ex as HH. destruct HH as (bcase & ? & ?).\n  on (I_expr (A.Value _) _), invc.\n\n  eexists. split. eapply B.SPlusOne. i_lem B.SEliminate.\n  i_ctor. i_ctor; i_ctor.\nQed.  \n\nLemma compile_cu_Forall : forall A Ameta B Bmeta,\n    compile_cu (A, Ameta) = (B, Bmeta) ->\n    Forall2 (fun a b => compile a = b) A B.\nintros. simpl in *. inject_pair.\neapply compile_list_Forall. auto.\nQed.\n\nLemma compile_cu_metas : forall A Ameta B Bmeta,\n    compile_cu (A, Ameta) = (B, Bmeta) ->\n    Ameta = Bmeta.\nsimpl. inversion 1. break_bind_option. inject_some. auto.\nQed.\n\nRequire oeuf.Semantics.\n\nSection Preservation.\n\n  Variable prog : A.prog_type.\n  Variable tprog : B.prog_type.\n\n  Hypothesis TRANSF : compile_cu prog = tprog.\n\n  Theorem fsim :\n    Semantics.forward_simulation (A.semantics prog) (B.semantics tprog).\n  Proof.\n    destruct prog as [A Ameta], tprog as [B Bmeta].\n    fwd eapply compile_cu_Forall; eauto.\n    fwd eapply compile_cu_metas; eauto.\n\n    eapply Semantics.forward_simulation_plus with\n        (match_states := I)\n        (match_values := @eq value).\n\n    - simpl. intros. on >B.is_callstate, invc. simpl in *.\n        destruct ltac:(i_lem Forall2_nth_error_ex') as (abody & ? & ?).\n      eexists. split. 1: econstructor. all: eauto.\n      + i_lem compile_I_expr. \n      + i_ctor.\n      + i_ctor.\n\n    - intros0 II Afinal. invc Afinal. invc II.\n      eexists; split; eauto.\n      i_ctor.\n\n    - simpl. eauto.\n    - simpl. intros. tauto.\n\n    - intros0 Astep. intros0 II.\n      eapply splus_semantics_sim, I_sim; try eassumption.\n      simpl. simpl in TRANSF. congruence.\n      \n  Qed.\n\nEnd Preservation.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/SelfCloseComp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21193546183681844}}
{"text": "(** In this file, we repackage an instance for\n[compcert.backend.ValueDomain.MMatch] for the concrete memory\nmodel implemented in [compcertx.common.MemimplX]. \n\nIndeed, those two memory models are different as they use different\nimplementations of [inject_neutral].\n\nFortunately, [MMatch] does not use [inject_neutral], so we have nothing to prove. We just need to unpack/repack.\n*)\n\nRequire compcert.backend.ValueDomainImpl.\nRequire MemimplX.\n\nImport Coqlib.\nExport ValueDomain.\nExport MemimplX.\nImport ValueDomainImpl.\n\nLemma mmatch_inj:\n   forall (bc : block_classification) (m : Memimpl.mem) (am : amem),\n   ValueDomain.mmatch bc m am ->\n   bc_below bc (Mem.nextblock m) -> Mem.inject (inj_of_bc bc) m m.\nProof.\n  intros. eapply ValueDomainImpl.mmatch_inj; eauto.\n  instantiate (1 := am). inversion H; constructor; auto.\nQed.\n\nGlobal Instance mmatch_prf: MMatch Memimpl.mem (memory_model_ops := MemimplX.memory_model_ops).\nProof.  \n  econstructor.\n  exact mmatch_stack.\n  exact mmatch_glob.\n  exact mmatch_nonstack.\n  exact mmatch_top.\n  exact mmatch_below.\n  exact load_sound.\n  exact store_sound.\n  exact loadbytes_sound.\n  exact storebytes_sound.\n  exact mmatch_ext.\n  exact mmatch_free.\n  exact mmatch_top'.\n  exact mbeq_sound.\n  exact mmatch_lub_l.\n  exact mmatch_lub_r.\n  exact mmatch_inj.\n  exact mmatch_inj_top.\nQed.\n", "meta": {"author": "DeepSpec", "repo": "dsss17", "sha": "826ec5edd67b3a3426fa48d7888dee10a973c2dc", "save_path": "github-repos/coq/DeepSpec-dsss17", "path": "github-repos/coq/DeepSpec-dsss17/dsss17-826ec5edd67b3a3426fa48d7888dee10a973c2dc/CAL/compcertx/backend/ValueDomainImplX.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21193546183681844}}
{"text": "Require Import SyntaxProp.\nRequire Import StaticProp.\nRequire Import DynamicProp.\nRequire Import WellFormednessProp.\n\nLemma actor_progress :\n  forall M H n l L C Q e id,\n    wf_cfg (M, H, n) ->\n    wf_actor M H id (l, L, C, Q, e) ->\n    id < length H ->\n    (exists M' H' n' e', id / (M, H, n) ; e ==> (M', H', n') ; e') \\/ is_val e.\nProof with eauto 6 using is_val, step_actor, is_econtext.\n  introv wfCfg wfActor Hlt.\n  assert (exists t, empty |- e \\in t) as [t hasType].\n    inv wfActor...\n  remember empty as Gamma.\n  hasType_cases(induction hasType) Case; subst...\n  + Case \"T_Var\".\n    inv Hlookup.\n  + Case \"T_AtStart\".\n    eapply wf_actor_ctx with (ctx := ctx_atstart) in wfActor as wfActor'...\n    crush.\n    - eapply EvalContext in H0...\n    - left. destruct a; inv Hactive.\n      * SCase \"Actor\".\n        inv H0; try solve[inv hasType].\n        find_actor id. remember (C0 id0) as conv...\n        symmetry in Heqconv. destruct conv.\n        ++ repeat eexists. eapply EvalAtomicStartActorFail...\n        ++ assert (id0 < length H) as Hlt\n               by (inv wfActor; simpls; eauto).\n           find_actor id0. heap_case id id0.\n           -- repeat eexists. eapply EvalAtomicStartActor; hauto.\n           -- repeat eexists. eapply EvalAtomicStartActor...\n              rewrite lookup_heapUpdate_neq...\n      * SCase \"Bestowed\".\n        inv H0; try solve[inv hasType].\n        find_actor id. remember (C0 id0) as conv...\n        symmetry in Heqconv. destruct conv.\n        ++ repeat eexists. eapply EvalAtomicStartBestowedFail...\n        ++ assert (id0 < length H) as Hlt.\n             inv wfActor. simpls. specializes H13 l0 id0 ___.\n             find_actor id0. heap_case id id0.\n           -- repeat eexists. eapply EvalAtomicStartBestowed; hauto.\n           -- repeat eexists. eapply EvalAtomicStartBestowed...\n              rewrite lookup_heapUpdate_neq...\n  + Case \"T_AtEnd\".\n    eapply wf_actor_ctx with (ctx := ctx_atend) in wfActor as wfActor'...\n    crush.\n    - eapply EvalContext in H0...\n    - left. destruct a; inv Hactive.\n      * SCase \"Actor\".\n        inv H0; try solve[inv hasType].\n        find_actor id. remember (C0 id0) as conv...\n        symmetry in Heqconv. destruct conv.\n        ++ inverts wfCfg as wfH _ _ _.\n           inverts wfH as _ _ wfActors.\n           eapply wfActors in Hlookup as wfActor''.\n           inv wfActor''.\n           assert (exists Q, M q = Some (Q, id0)) as [?Q HM]...\n           repeat eexists. eapply EvalAtomicEndActor...\n        ++ repeat eexists. eapply EvalAtomicEndActorFail...\n      * SCase \"Bestowed\".\n        inv H0; try solve[inv hasType].\n        find_actor id. remember (C0 id0) as conv...\n        symmetry in Heqconv. destruct conv.\n        ++ inverts wfCfg as wfH _ _ _.\n           inverts wfH as _ _ wfActors.\n           eapply wfActors in Hlookup as wfActor''.\n           inv wfActor''.\n           assert (exists Q, M q = Some (Q, id0)) as [?Q HM]...\n           repeat eexists. eapply EvalAtomicEndBestowed...\n        ++ repeat eexists. eapply EvalAtomicEndBestowedFail...\n  + Case \"T_NewPassive\".\n    left. find_actor id...\n  + Case \"T_Mutate\".\n    apply wf_actor_ctx in wfActor...\n    crush.\n    - left...\n    - inv H0; inv hasType...\n  + Case \"T_Bestow\".\n    apply wf_actor_ctx in wfActor...\n    crush.\n    - left...\n    - inv H0; inv hasType...\n  + Case \"T_Apply\".\n    apply wf_actor_ctx with (ctx := ctx_appl e2) in wfActor as wfActor'...\n    crush.\n    - apply EvalContext with (ctx := ctx_appl e2) in H0...\n    - apply wf_actor_ctx with (ctx := ctx_appr e1) in wfActor as wfActor''...\n      crush.\n      * apply EvalContext with (ctx := ctx_appr e1) in H1...\n      * inv H0; try solve[inv hasType1]...\n        constructors...\n  + Case \"T_Send\".\n    apply wf_actor_ctx with (ctx := ctx_send x TPas e') in wfActor as wfActor'...\n    crush.\n    - apply EvalContext with (ctx := ctx_send x TPas e') in H1...\n    - left. unfold is_active in Hactive.\n      destruct a; inv Hactive.\n      * SCase \"ActorSend\".\n        inv H1; try solve[inv hasType1]...\n        inv wfActor'. simpls.\n        find_actor id.\n        remember (C0 id0) as conv.\n        symmetry in Heqconv.\n        destruct conv.\n        ++ SSCase \"Atomic\".\n           inverts wfCfg as wfH _ _ _.\n           inverts wfH as _ _ wfActors.\n           eapply wfActors in Hlookup as wfActor''.\n           inv wfActor''.\n           assert (exists Q, M q = Some (Q, id0)) as [?Q HM]...\n           repeat eexists. eapply EvalSendActorAtomic; hauto.\n        ++ SSCase \"Regular\".\n           assert (id0 < length H) as Hlt'...\n           find_actor id0...\n           repeat eexists... eapply EvalSendActor; hauto.\n      * SCase \"BestowedSend\".\n        inv H1; try solve[inv hasType1]...\n        inv wfActor'. simpls.\n        find_actor id.\n        remember (C0 id0) as conv.\n        symmetry in Heqconv.\n        destruct conv.\n        ++ SSCase \"Atomic\".\n           inverts wfCfg as wfH _ _ _.\n           inverts wfH as _ _ wfActors.\n           eapply wfActors in Hlookup as wfActor''.\n           inv wfActor''.\n           assert (exists Q, M q = Some (Q, id0)) as [?Q HM]...\n           repeat eexists. eapply EvalSendBestowedAtomic; hauto.\n        ++ SSCase \"Regular\".\n           assert (id0 < length H) as Hlt' by\n             specializes H14 l0 id0 ___.\n           find_actor id0...\n           repeat eexists... eapply EvalSendBestowed; hauto.\nQed.\n\nTheorem progress :\n  forall M H n id,\n    wf_cfg (M, H, n) ->\n    id < length H ->\n    (exists cfg', step id (M, H, n) cfg') \\/ actor_done (M, H, n) id.\nProof with eauto using step, step_preserves_this.\n  introv wfCfg Hlt.\n  assert (exists a, heapLookup H id = Some a) as [a Hlookup].\n    apply heapLookup_lt in Hlt...\n  destruct_actor a.\n  assert (wf_actor M H id (l, L, C, Q, e)) as wfActor.\n    inverts wfCfg as wfH _ _ _. inverts wfH as [_ _ wfActors]...\n  assert (wf_queueMap M H) as wfM\n    by (inv wfCfg; eauto).\n  apply actor_progress with (l := l) (L := L) (C := C) (Q := Q) (e := e) (id := id) in wfCfg as Halt...\n  inv Halt as [Hex | Hdone].\n  + Case \"e steps\".\n    left.\n    inv Hex as [M' [H' [n' [e' Hstep]]]].\n    assert (exists L' C' Q' e'', heapLookup H' id = Some (l, L', C', Q', e'')) as Hlookup'...\n    destruct Hlookup' as [? [? [? [? ?]]]].\n    eapply EvalActorRun in Hstep...\n  + Case \"is_val e\".\n    destruct Q.\n    - SCase \"Q empty\".\n      right.\n      unfolds. rewrite Hlookup.\n      constructors...\n    - SCase \"Q non-empty\".\n      destruct m.\n      * SSCase \"Regular message\".\n        left. eexists. eapply EvalActorMsg...\n      * SSCase \"Atomic\".\n        inverts wfActor as _ _ wfQueue.\n        assert (wf_msg M H L id (Atomic q)) as wfMsg\n            by (specializes wfQueue (Atomic q) ___; constructors; eauto).\n        inverts wfMsg as HM. destruct Q0.\n        ++ right... unfolds. hauto. constructors...\n        ++ destruct m.\n           -- left. eexists. eapply EvalActorPrivateMsg...\n           -- eapply wfM in HM as [Hneq [Hend [?L wfQueue']]]; hauto.\n              specializes Hneq (Atomic q0) q0 ___. constructors...\n              contradiction.\n           -- left. eexists... eapply EvalActorPrivateEnd...\n      * SSCase \"EndAtomic (absurd)\".\n        inverts wfActor as _ _ _ Hneq.\n        specializes Hneq EndAtomic ___. constructors...\n        contradiction.\nQed.\n", "meta": {"author": "EliasC", "repo": "bestow-atomic", "sha": "8e057e88cc138116179b677fd4ce1dd015f7eede", "save_path": "github-repos/coq/EliasC-bestow-atomic", "path": "github-repos/coq/EliasC-bestow-atomic/bestow-atomic-8e057e88cc138116179b677fd4ce1dd015f7eede/private/Progress.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.384912151539776, "lm_q1q2_score": 0.2119354600449375}}
{"text": "Require Export Program.Basics. Open Scope program_scope.\nFrom Paco Require Import paco.\nFrom Paco Require Import paconotation_internal paco_internal pacotac_internal.\nFrom Paco Require Export paconotation.\nFrom Fairness Require Import pind_internal.\nSet Implicit Arguments.\n\nSection PIND13.\n\nVariable T0 : Type.\nVariable T1 : forall (x0: @T0), Type.\nVariable T2 : forall (x0: @T0) (x1: @T1 x0), Type.\nVariable T3 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1), Type.\nVariable T4 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2), Type.\nVariable T5 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3), Type.\nVariable T6 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4), Type.\nVariable T7 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5), Type.\nVariable T8 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6), Type.\nVariable T9 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7), Type.\nVariable T10 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8), Type.\nVariable T11 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8) (x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9), Type.\nVariable T12 : forall (x0: @T0) (x1: @T1 x0) (x2: @T2 x0 x1) (x3: @T3 x0 x1 x2) (x4: @T4 x0 x1 x2 x3) (x5: @T5 x0 x1 x2 x3 x4) (x6: @T6 x0 x1 x2 x3 x4 x5) (x7: @T7 x0 x1 x2 x3 x4 x5 x6) (x8: @T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: @T9 x0 x1 x2 x3 x4 x5 x6 x7 x8) (x10: @T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9) (x11: @T11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10), Type.\n\n(** ** Predicates of Arity 13\n*)\n\nDefinition pind13(gf : rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 -> rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12)(r: rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12) : rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 :=\n  @curry13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 (pind (fun R0 => @uncurry13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 (gf (@curry13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 R0))) (@uncurry13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 r)).\n\nDefinition upind13(gf : rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 -> rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12)(r: rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12) := pind13 gf r /13\\ r.\nArguments pind13 : clear implicits.\nArguments upind13 : clear implicits.\n#[local] Hint Unfold upind13 : core.\n\nLemma monotone13_inter (gf gf': rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 -> rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12)\n      (MON1: monotone13 gf)\n      (MON2: monotone13 gf'):\n  monotone13 (gf /14\\ gf').\nProof.\n  red; intros. destruct IN. split; eauto.\nQed.\n\nLemma _pind13_mon_gen (gf gf': rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 -> rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12) r r'\n    (LEgf: gf <14= gf')\n    (LEr: r <13= r'):\n  pind13 gf r <13== pind13 gf' r'.\nProof.\n  apply curry_map13. red; intros. eapply pind_mon_gen. apply PR.\n  - intros. apply LEgf, PR0.\n  - intros. apply LEr, PR0.\nQed.\n\nLemma pind13_mon_gen (gf gf': rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 -> rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12) r r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12\n    (REL: pind13 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)\n    (LEgf: gf <14= gf')\n    (LEr: r <13= r'):\n  pind13 gf' r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12.\nProof.\n  eapply _pind13_mon_gen; [apply LEgf | apply LEr | apply REL].\nQed.\n\nLemma pind13_mon_bot (gf gf': rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 -> rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12) r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12\n    (REL: pind13 gf bot13 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)\n    (LEgf: gf <14= gf'):\n  pind13 gf' r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12.\nProof.\n  eapply pind13_mon_gen; [apply REL | apply LEgf | intros; contradiction PR].\nQed.\n\nDefinition top13 { T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12} (x0: T0) (x1: T1 x0) (x2: T2 x0 x1) (x3: T3 x0 x1 x2) (x4: T4 x0 x1 x2 x3) (x5: T5 x0 x1 x2 x3 x4) (x6: T6 x0 x1 x2 x3 x4 x5) (x7: T7 x0 x1 x2 x3 x4 x5 x6) (x8: T8 x0 x1 x2 x3 x4 x5 x6 x7) (x9: T9 x0 x1 x2 x3 x4 x5 x6 x7 x8) (x10: T10 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9) (x11: T11 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10) (x12: T12 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11) := True.\n\nLemma pind13_mon_top (gf gf': rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 -> rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12) r x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12\n    (REL: pind13 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)\n    (LEgf: gf <14= gf'):\n  pind13 gf' top13 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12.\nProof.\n  eapply pind13_mon_gen; eauto. red. auto.\nQed.\n\nLemma upind13_mon_gen (gf gf': rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 -> rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12) r r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12\n    (REL: upind13 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)\n    (LEgf: gf <14= gf')\n    (LEr: r <13= r'):\n  upind13 gf' r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12.\nProof.\n  destruct REL. split; eauto.\n  eapply pind13_mon_gen; [apply H | apply LEgf | apply LEr].\nQed.\n\nLemma upind13_mon_bot (gf gf': rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 -> rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12) r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12\n    (REL: upind13 gf bot13 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)\n    (LEgf: gf <14= gf'):\n  upind13 gf' r' x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12.\nProof.\n  eapply upind13_mon_gen; [apply REL | apply LEgf | intros; contradiction PR].\nQed.\n\nLemma upind13mon_top (gf gf': rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 -> rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12) r x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12\n    (REL: upind13 gf r x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12)\n    (LEgf: gf <14= gf'):\n  upind13 gf' top13 x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12.\nProof.\n  eapply upind13_mon_gen; eauto. red. auto.\nQed.\n\nSection Arg13.\n\nVariable gf : rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 -> rel13 T0 T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12.\nArguments gf : clear implicits.\n\nTheorem _pind13_mon: _monotone13 (pind13 gf).\nProof.\n  red; intros. eapply curry_map13, _pind_mon; apply uncurry_map13; assumption.\nQed.\n\nTheorem _pind13_acc: forall\n  l r (OBG: forall rr (DEC: rr <13== r) (IH: rr <13== l), pind13 gf rr <13== l),\n  pind13 gf r <13== l.\nProof.\n  intros. apply curry_adjoint2_13.\n  eapply _pind_acc. intros.\n  apply curry_adjoint2_13 in DEC. apply curry_adjoint2_13 in IH.\n  apply curry_adjoint1_13.\n  eapply le13_trans. 2: eapply (OBG _ DEC IH).\n  apply curry_map13.\n  apply _pind_mon; try apply le1_refl; apply curry_bij2_13.\nQed.\n\nTheorem _pind13_mult_strong: forall r,\n  pind13 gf r <13== pind13 gf (upind13 gf r).\nProof.\n  intros. apply curry_map13.\n  eapply le1_trans; [eapply _pind_mult_strong |].\n  apply _pind_mon; intros [] H. apply H.\nQed.\n\nTheorem _pind13_fold: forall r,\n  gf (upind13 gf r) <13== pind13 gf r.\nProof.\n  intros. apply uncurry_adjoint1_13.\n  eapply le1_trans; [| apply _pind_fold]. apply le1_refl.\nQed.\n\nTheorem _pind13_unfold: forall (MON: _monotone13 gf) r,\n  pind13 gf r <13== gf (upind13 gf r).\nProof.\n  intros. apply curry_adjoint2_13.\n  eapply _pind_unfold; apply monotone13_map; assumption.\nQed.\n\nTheorem pind13_acc: forall\n  l r (OBG: forall rr (DEC: rr <13= r) (IH: rr <13= l), pind13 gf rr <13= l),\n  pind13 gf r <13= l.\nProof.\n  apply _pind13_acc.\nQed.\n\nTheorem pind13_mon: monotone13 (pind13 gf).\nProof.\n  apply monotone13_eq.\n  apply _pind13_mon.\nQed.\n\nTheorem upind13_mon: monotone13 (upind13 gf).\nProof.\n  red; intros.\n  destruct IN. split; eauto.\n  eapply pind13_mon. apply H. apply LE.\nQed.\n\nTheorem pind13_mult_strong: forall r,\n  pind13 gf r <13= pind13 gf (upind13 gf r).\nProof.\n  apply _pind13_mult_strong.\nQed.\n\nCorollary pind13_mult: forall r,\n  pind13 gf r <13= pind13 gf (pind13 gf r).\nProof. intros; eapply pind13_mult_strong in PR. eapply pind13_mon; eauto. intros. destruct PR0. eauto. Qed.\n\nTheorem pind13_fold: forall r,\n  gf (upind13 gf r) <13= pind13 gf r.\nProof.\n  apply _pind13_fold.\nQed.\n\nTheorem pind13_unfold: forall (MON: monotone13 gf) r,\n  pind13 gf r <13= gf (upind13 gf r).\nProof.\n  intro. eapply _pind13_unfold; apply monotone13_eq; assumption.\nQed.\n\nEnd Arg13.\n\nArguments pind13_acc : clear implicits.\nArguments pind13_mon : clear implicits.\nArguments upind13_mon : clear implicits.\nArguments pind13_mult_strong : clear implicits.\nArguments pind13_mult : clear implicits.\nArguments pind13_fold : clear implicits.\nArguments pind13_unfold : clear implicits.\n\nEnd PIND13.\n\nGlobal Opaque pind13.\n\n#[export] Hint Unfold upind13 : core.\n#[export] Hint Resolve pind13_fold : core.\n#[export] Hint Unfold monotone13 : core.\n\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/pico/pind13.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2119354592750567}}
{"text": "(* *****************************************************************)\n(*                                                                 *)\n(*               Verified polyhedral AST generation                *)\n(*                                                                 *)\n(*                 Nathanaël Courant, Inria Paris                  *)\n(*                                                                 *)\n(*  Copyright Inria. All rights reserved. This file is distributed *)\n(*  under the terms of the GNU Lesser General Public License as    *)\n(*  published by the Free Software Foundation, either version 2.1  *)\n(*  of the License, or (at your option) any later version.         *)\n(*                                                                 *)\n(* *****************************************************************)\n\nRequire Import Result.\nRequire Import Vpl.Impure Vpl.Debugging.\nRequire Import ImpureOperations.\nRequire Import Semantics.\n\nRequire Vpl.ImpureConfig.\n\nModule CoreAlarmed := AlarmImpureMonad Vpl.ImpureConfig.Core.\nExport CoreAlarmed.\n\nModule Export ImpOps := ImpureOps CoreAlarmed.\nModule Export IIS := IterImpureSemantics CoreAlarmed.\n\nDefinition res_to_alarm {A : Type} (d : A) (x : result A) : imp A :=\n  match x with\n  | Ok a => pure a\n  | Err s => alarm s (failwith INTERN s d)\n  end.\n\nLemma res_to_alarm_correct :\n  forall (A : Type) (d : A) (x : result A) (y : A),\n    mayReturn (res_to_alarm d x) y -> x = Ok y.\nProof.\n  intros A d x y. destruct x; simpl.\n  - intros H. f_equal. apply mayReturn_pure. auto.\n  - intros H. apply mayReturn_alarm in H. tauto.\nQed.\n", "meta": {"author": "Ekdohibs", "repo": "PolyGen", "sha": "4312b2188db58d3690721b23004e96e18c266027", "save_path": "github-repos/coq/Ekdohibs-PolyGen", "path": "github-repos/coq/Ekdohibs-PolyGen/PolyGen-4312b2188db58d3690721b23004e96e18c266027/ImpureAlarmConfig.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543457, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21193545927505666}}
{"text": "(** * Every parse tree has a corresponding minimal parse tree *)\nRequire Import Coq.Strings.String Coq.Lists.List Coq.Program.Program Coq.Classes.RelationClasses Coq.Classes.Morphisms Coq.Setoids.Setoid Coq.Arith.Compare_dec.\nRequire Import Coq.Program.Wf Coq.Arith.Wf_nat.\nRequire Import Parsers.ContextFreeGrammar Parsers.ContextFreeGrammarProperties Parsers.WellFoundedParse.\nRequire Export Parsers.MinimalParse.\nRequire Import Common Common.Wf.\n\nSet Implicit Arguments.\nLocal Open Scope string_like_scope.\n\nLocal Notation \"f ∘ g\" := (fun x => f (g x)).\n\nSection cfg.\n  Context CharType (String : string_like CharType) (G : grammar CharType).\n  Context (names_listT : Type)\n          (initial_names_data : names_listT)\n          (is_valid_name : names_listT -> string -> bool)\n          (remove_name : names_listT -> string -> names_listT)\n          (names_listT_R : names_listT -> names_listT -> Prop)\n          (remove_name_dec : forall ls name,\n                               is_valid_name ls name = true\n                               -> names_listT_R (remove_name ls name) ls)\n          (remove_name_1\n           : forall ls ps ps',\n               is_valid_name (remove_name ls ps) ps' = true\n               -> is_valid_name ls ps' = true)\n          (remove_name_2\n           : forall ls ps ps',\n               is_valid_name (remove_name ls ps) ps' = false\n               <-> is_valid_name ls ps' = false \\/ ps = ps')\n          (ntl_wf : well_founded names_listT_R).\n\n  Context (names_listT_R_respectful : forall x y,\n                                        sub_names_listT is_valid_name x y\n                                        -> x <> y\n                                        -> names_listT_R x y).\n\n  Local Notation minimal_parse_of_production := (@minimal_parse_of_production CharType String G names_listT initial_names_data is_valid_name remove_name).\n  Local Notation minimal_parse_of := (@minimal_parse_of CharType String G names_listT initial_names_data is_valid_name remove_name).\n  Local Notation minimal_parse_of_name := (@minimal_parse_of_name CharType String G names_listT initial_names_data is_valid_name remove_name).\n  Local Notation minimal_parse_of_item := (@minimal_parse_of_item CharType String G names_listT initial_names_data is_valid_name remove_name).\n\n  Lemma strle_from_min_parse_of_production {str0 valid strs pats}\n        (p1 : minimal_parse_of_production str0 valid strs pats)\n  : strs ≤s str0.\n  Proof.\n    destruct p1; trivial; [].\n    destruct (stringlike_dec str0 (Empty _)) as [|n];\n      subst; [ reflexivity | left ].\n    rewrite Length_Empty.\n    case_eq (Length str0); intro H; [ exfalso | ];\n    eauto using Empty_Length with arith.\n  Qed.\n\n  Definition parse_of_item_name__of__minimal_parse_of_name'\n             (parse_of__of__minimal_parse_of\n              : forall str0 valid str prods,\n                  @minimal_parse_of str0 valid str prods -> parse_of String G str prods)\n             {str0 valid str name} (p : @minimal_parse_of_name str0 valid str name)\n  : parse_of_item String G str (NonTerminal _ name)\n    := ParseNonTerminal\n         name\n         (@parse_of__of__minimal_parse_of\n            _ _ _ _\n            (match p as p in (@MinimalParse.minimal_parse_of_name _ _ _ _ _ _ _ str0 valid str name)\n                   return minimal_parse_of (match p with\n                                              | MinParseNonTerminalStrLt _ _ _ _ _ _ => _\n                                              | MinParseNonTerminalStrEq _ _ _ _ _ => _\n                                            end)\n                                           (match p with\n                                              | MinParseNonTerminalStrLt _ _ _ _ _ _ => _\n                                              | MinParseNonTerminalStrEq _ _ _ _ _ => _\n                                            end)\n                                           str (Lookup G name) with\n               | MinParseNonTerminalStrLt str0 valid name str pf p' => p'\n               | MinParseNonTerminalStrEq str valid name H p' => p'\n             end)).\n\n  Definition parse_of_item__of__minimal_parse_of_item'\n             (parse_of__of__minimal_parse_of\n              : forall str0 valid str prods,\n                  @minimal_parse_of str0 valid str prods -> parse_of String G str prods)\n             {str0 valid str it} (p : @minimal_parse_of_item str0 valid str it)\n  : parse_of_item String G str it\n    := match p in (@MinimalParse.minimal_parse_of_item _ _ _ _ _ _ _ str0 valid str it) return parse_of_item String G str it with\n         | MinParseTerminal str0 valid x\n           => ParseTerminal String G x\n         | MinParseNonTerminal str0 valid _ _ p'\n           => @parse_of_item_name__of__minimal_parse_of_name' (@parse_of__of__minimal_parse_of) _ _ _ _ p'\n       end.\n\n  Fixpoint parse_of__of__minimal_parse_of {str0 valid str pats} (p : @minimal_parse_of str0 valid str pats)\n  : parse_of String G str pats\n    := match p with\n         | MinParseHead str0 valid str pat pats p'\n           => ParseHead pats (parse_of_production__of__minimal_parse_of_production p')\n         | MinParseTail str0 valid str pat pats p'\n           => ParseTail pat (parse_of__of__minimal_parse_of p')\n       end\n  with parse_of_production__of__minimal_parse_of_production {str0 valid str pat} (p : @minimal_parse_of_production str0 valid str pat)\n       : parse_of_production String G str pat\n       := match p with\n            | MinParseProductionNil str0 valid\n              => ParseProductionNil _ _\n            | MinParseProductionCons str0 valid str strs pat pats pf p' p''\n              => ParseProductionCons\n                   (parse_of_item__of__minimal_parse_of_item' (@parse_of__of__minimal_parse_of) p')\n                   (parse_of_production__of__minimal_parse_of_production p'')\n          end.\n\n  Definition parse_of_item_name__of__minimal_parse_of_name\n  : forall {str0 valid str name} (p : @minimal_parse_of_name str0 valid str name),\n      parse_of_item String G str (NonTerminal _ name)\n    := @parse_of_item_name__of__minimal_parse_of_name' (@parse_of__of__minimal_parse_of).\n\n  Definition parse_of_item__of__minimal_parse_of_item\n  : forall {str0 valid str it},\n      @minimal_parse_of_item str0 valid str it\n      -> parse_of_item String G str it\n    := @parse_of_item__of__minimal_parse_of_item' (@parse_of__of__minimal_parse_of).\n\n  Section contract.\n    Local Hint Constructors MinimalParse.minimal_parse_of_name.\n\n    Definition contract_minimal_parse_of_name_lt\n               {str0 str valid valid' name}\n               (Hlt : Length str < Length str0)\n               (p : @minimal_parse_of_name str0 valid str name)\n    : @minimal_parse_of_name str0 valid' str name.\n    Proof.\n      destruct p.\n      { constructor (assumption). }\n      { exfalso; clear -Hlt; omega. }\n    Defined.\n\n    Definition contract_minimal_parse_of_item_lt\n               {str0 str valid valid' it}\n               (Hlt : Length str < Length str0)\n               (p : @minimal_parse_of_item str0 valid str it)\n    : @minimal_parse_of_item str0 valid' str it.\n    Proof.\n      destruct p as [p|p].\n      { constructor. }\n      { constructor (eapply contract_minimal_parse_of_name_lt; eassumption). }\n    Defined.\n\n    Definition contract_minimal_parse_of_production_lt\n               {str0 str valid valid' pat}\n               (Hlt : Length str < Length str0)\n               (p : @minimal_parse_of_production str0 valid str pat)\n    : @minimal_parse_of_production str0 valid' str pat.\n    Proof.\n      induction p.\n      { constructor. }\n      { constructor;\n        try first [ eapply contract_minimal_parse_of_item_lt; try eassumption\n                  | eapply IHp; try eassumption\n                  | assumption ];\n        clear -Hlt;\n        abstract (\n            rewrite <- Length_correct in Hlt;\n            eauto using le_S, Lt.le_lt_trans, Plus.le_plus_l, Plus.le_plus_r with nocore\n          ). }\n    Defined.\n\n    Definition contract_minimal_parse_of_lt\n               {str0 str valid valid' pats}\n               (Hlt : Length str < Length str0)\n               (p : @minimal_parse_of str0 valid str pats)\n    : @minimal_parse_of str0 valid' str pats.\n    Proof.\n      induction p.\n      { constructor (eapply contract_minimal_parse_of_production_lt; eassumption). }\n      { constructor (eapply IHp; assumption). }\n    Defined.\n\n    Section contract_eq.\n      Lemma parse_of_contract_minimal_parse_of_item_lt\n            {str0 str : String} {valid valid' : names_listT}\n            {Hlt : Length str < Length str0}\n            {it}\n            (p : @minimal_parse_of_item str0 valid str it)\n      : parse_of_item__of__minimal_parse_of_item\n          (contract_minimal_parse_of_item_lt (valid' := valid') Hlt p)\n        = parse_of_item__of__minimal_parse_of_item p.\n      Proof.\n        destruct_head MinimalParse.minimal_parse_of_item; simpl; try reflexivity.\n        destruct_head MinimalParse.minimal_parse_of_name; try reflexivity.\n        unfold False_rect.\n        match goal with\n          | [ |- appcontext[match ?e with end] ] => destruct e\n        end.\n      Qed.\n\n      Lemma parse_of_contract_minimal_parse_of_production_lt\n            {str0 str : String} {valid valid' : names_listT}\n            {Hlt : Length str < Length str0}\n            {pat}\n            (p : @minimal_parse_of_production str0 valid str pat)\n      : parse_of_production__of__minimal_parse_of_production\n          (contract_minimal_parse_of_production_lt (valid' := valid') Hlt p)\n        = parse_of_production__of__minimal_parse_of_production p.\n      Proof.\n        induction p; simpl; try reflexivity.\n        rewrite IHp, parse_of_contract_minimal_parse_of_item_lt.\n        reflexivity.\n      Qed.\n\n      Lemma parse_of_contract_minimal_parse_of_lt\n            {str0 str : String} {valid valid' : names_listT}\n            {Hlt : Length str < Length str0}\n            {pats}\n            (p : @minimal_parse_of str0 valid str pats)\n      : parse_of__of__minimal_parse_of\n          (contract_minimal_parse_of_lt (valid' := valid') Hlt p)\n        = parse_of__of__minimal_parse_of p.\n      Proof.\n        induction p; simpl;\n        progress rewrite ?IHp, ?parse_of_contract_minimal_parse_of_production_lt;\n        reflexivity.\n      Qed.\n    End contract_eq.\n  End contract.\n\n  (** Re-add this so rewrite works *)\n  Global Add Parametric Morphism : remove_name\n  with signature (sub_names_listT is_valid_name) ==> eq ==> (sub_names_listT is_valid_name)\n    as remove_name_mor.\n  Proof.\n    intros; apply (@remove_name_mor); try assumption; reflexivity.\n  Qed.\n\n  Definition expand_minimal_parse_of_name'\n             (expand_minimal_parse_of\n              : forall {str0 str0' valid valid' str prods}\n                       (Hstr : str0 ≤s str0')\n                       (H : sub_names_listT is_valid_name valid valid')\n                       (Hinit : sub_names_listT is_valid_name valid' initial_names_data)\n                       (p : @minimal_parse_of str0 valid str prods),\n                  @minimal_parse_of str0' valid' str prods)\n             {str0 str0' valid valid' str name}\n             (Hstr : str0 ≤s str0')\n             (H : sub_names_listT is_valid_name valid valid')\n             (Hinit : sub_names_listT is_valid_name valid' initial_names_data)\n             (p : @minimal_parse_of_name str0 valid str name)\n  : @minimal_parse_of_name str0' valid' str name.\n  Proof.\n    destruct p;\n    first [ apply MinParseNonTerminalStrLt;\n            solve [ eapply length_le_trans; eassumption\n                  | assumption ]\n          | idtac ]; [].\n    { destruct (strle_to_sumbool _ Hstr); subst;\n      [ apply MinParseNonTerminalStrLt\n      | apply MinParseNonTerminalStrEq ];\n      solve [ assumption\n            | apply H; assumption\n            | eapply expand_minimal_parse_of; [ .. | eassumption ];\n              solve [ reflexivity\n                    | rewrite ?H, ?Hinit;\n                      eauto using sub_names_listT_remove;\n                      reflexivity ] ]. }\n  Defined.\n\n  Definition expand_minimal_parse_of_item'\n             (expand_minimal_parse_of\n              : forall {str0 str0' valid valid' str prods}\n                       (Hstr : str0 ≤s str0')\n                       (H : sub_names_listT is_valid_name valid valid')\n                       (Hinit : sub_names_listT is_valid_name valid' initial_names_data)\n                       (p : @minimal_parse_of str0 valid str prods),\n                  @minimal_parse_of str0' valid' str prods)\n             {str0 str0' valid valid' str it}\n             (Hstr : str0 ≤s str0')\n             (H : sub_names_listT is_valid_name valid valid')\n             (Hinit : sub_names_listT is_valid_name valid' initial_names_data)\n             (p : @minimal_parse_of_item str0 valid str it)\n  : @minimal_parse_of_item str0' valid' str it.\n  Proof.\n    destruct p.\n    { apply MinParseTerminal. }\n    { apply MinParseNonTerminal; [].\n      eapply expand_minimal_parse_of_name'; [..| eassumption ];\n      try assumption. }\n  Defined.\n\n  Fixpoint expand_minimal_parse_of\n           {str0 str0' valid valid' str pats}\n           (Hstr : str0 ≤s str0')\n           (H : sub_names_listT is_valid_name valid valid')\n           (Hinit : sub_names_listT is_valid_name valid' initial_names_data)\n           (p : @minimal_parse_of str0 valid str pats)\n  : @minimal_parse_of str0' valid' str pats\n    := match p in (@MinimalParse.minimal_parse_of _ _ _ _ _ _ _ str0 valid str pats)\n             return (str0 ≤s str0'\n                     -> sub_names_listT is_valid_name valid valid'\n                     -> @minimal_parse_of str0' valid' str pats)\n       with\n         | MinParseHead str0 valid str pat pats p'\n           => fun Hstr H => MinParseHead pats (expand_minimal_parse_of_production Hstr H Hinit p')\n         | MinParseTail str0 valid str pat pats p'\n           => fun Hstr H => MinParseTail pat (expand_minimal_parse_of Hstr H Hinit p')\n       end Hstr H\n  with expand_minimal_parse_of_production\n         {str0 str0' valid valid' str pat}\n         (Hstr : str0 ≤s str0')\n         (H : sub_names_listT is_valid_name valid valid')\n         (Hinit : sub_names_listT is_valid_name valid' initial_names_data)\n         (p : @minimal_parse_of_production str0 valid str pat)\n       : @minimal_parse_of_production str0' valid' str pat\n       := match p in (@MinimalParse.minimal_parse_of_production _ _ _ _ _ _ _ str0 valid str pats)\n                return (str0 ≤s str0' -> sub_names_listT is_valid_name valid valid' -> minimal_parse_of_production str0' valid' str pats)\n          with\n            | MinParseProductionNil str0 valid\n              => fun _ _ => MinimalParse.MinParseProductionNil _ _ _ _ _ _ _\n            | MinParseProductionCons str0 valid str strs pat pats pf p' p''\n              => fun Hstr H => MinParseProductionCons\n                                 (transitivity pf Hstr)\n                                 (expand_minimal_parse_of_item' (@expand_minimal_parse_of) Hstr H Hinit p')\n                                 (expand_minimal_parse_of_production Hstr H Hinit p'')\n          end Hstr H.\n\n  Definition expand_minimal_parse_of_name\n  : forall {str0 str0' valid valid' str name}\n           (Hstr : str0 ≤s str0')\n           (H : sub_names_listT is_valid_name valid valid')\n           (Hinit : sub_names_listT is_valid_name valid' initial_names_data)\n           (p : @minimal_parse_of_name str0 valid str name),\n      @minimal_parse_of_name str0' valid' str name\n    := @expand_minimal_parse_of_name' (@expand_minimal_parse_of).\n\n  Definition expand_minimal_parse_of_item\n  : forall {str0 str0' valid valid' str it}\n           (Hstr : str0 ≤s str0')\n           (H : sub_names_listT is_valid_name valid valid')\n           (Hinit : sub_names_listT is_valid_name valid' initial_names_data)\n           (p : @minimal_parse_of_item str0 valid str it),\n      @minimal_parse_of_item str0' valid' str it\n    := @expand_minimal_parse_of_item' (@expand_minimal_parse_of).\n\n  Section minimize.\n    Let P : String -> string -> Prop\n      := fun _ p => is_valid_name initial_names_data p = true.\n\n    Let alt_option h valid str\n      := { name : _ & (is_valid_name valid name = false /\\ P str name)\n                      * { p : parse_of String G str (Lookup G name)\n                              & (size_of_parse p < h)\n                                * Forall_parse_of P p } }%type.\n\n    Lemma not_alt_all {h str} (ps : alt_option h initial_names_data str)\n    : False.\n    Proof.\n      subst P; simpl in *.\n      destruct ps as [ ? [ H' _ ] ].\n      revert H'; clear; intros [? ?].\n      congruence.\n    Qed.\n\n    Definition alt_all_elim {h str T} (ps : T + alt_option h initial_names_data str)\n    : T.\n    Proof.\n      destruct ps as [|ps]; [ assumption | exfalso ].\n      eapply not_alt_all; eassumption.\n    Defined.\n\n    Definition expand_alt_option' {h h' str str' valid valid'}\n               (H : h <= h') (H' : sub_names_listT is_valid_name valid' valid) (H'' : str = str')\n    : alt_option h valid str -> alt_option h' valid' str'.\n    Proof.\n      hnf in H'; unfold alt_option.\n      repeat match goal with\n               | [ |- sigT _ -> _ ] => intros []\n               | [ |- sig _ -> _ ] => intros []\n               | [ |- prod _ _ -> _ ] => intros []\n               | [ |- and _ _ -> _ ] => intros []\n               | _ => intro\n               | _ => progress subst\n               | [ |- sigT _ ] => esplit\n               | [ |- sig _ ] => esplit\n               | [ |- prod _ _ ] => esplit\n               | [ |- and _ _ ] => esplit\n               | [ H : _ = false |- _ = false ]\n                 => apply Bool.not_true_iff_false in H;\n                   apply Bool.not_true_iff_false;\n                   intro; apply H\n               | _ => eapply H'; eassumption\n               | _ => assumption\n               | [ |- _ < _ ] => eapply Lt.lt_trans; eassumption\n               | [ |- _ < _ ] => eapply Lt.lt_le_trans; eassumption\n             end.\n    Defined.\n\n    Definition expand_alt_option {h h' str str' valid valid'}\n               (H : h < h') (H' : sub_names_listT is_valid_name valid' valid) (H'' : str = str')\n    : alt_option h valid str -> alt_option h' valid' str'.\n    Proof.\n      apply expand_alt_option'; try assumption.\n      apply Lt.lt_le_weak; assumption.\n    Defined.\n\n    Section wf_parts.\n      Let of_parse_item_T' h\n          {str0 str : String} (pf : str ≤s str0)\n          (valid : names_listT) {it : item CharType}\n          (p : parse_of_item String G str it)\n        := forall (p_small : size_of_parse_item p < h),\n             sub_names_listT is_valid_name valid initial_names_data\n             -> Forall_parse_of_item P p\n             -> ({ p' : @minimal_parse_of_item str0 valid str it\n                        & (size_of_parse_item (parse_of_item__of__minimal_parse_of_item p') <= size_of_parse_item p)\n                          * Forall_parse_of_item P (parse_of_item__of__minimal_parse_of_item p') })%type\n                + alt_option (size_of_parse_item p) valid str.\n\n      Let of_parse_item_T str0 h\n        := forall str pf valid it p, @of_parse_item_T' h str0 str pf valid it p.\n\n      Let of_parse_production_T' h\n          {str0 str : String} (pf : str ≤s str0)\n          (valid : names_listT) {pat : production CharType}\n          (p : parse_of_production String G str pat)\n        := forall (p_small : size_of_parse_production p < h),\n             sub_names_listT is_valid_name valid initial_names_data\n             -> Forall_parse_of_production P p\n             -> ({ p' : @minimal_parse_of_production str0 valid str pat\n                        & (size_of_parse_production (parse_of_production__of__minimal_parse_of_production p') <= size_of_parse_production p)\n                          * Forall_parse_of_production P (parse_of_production__of__minimal_parse_of_production p') })%type\n                + alt_option (size_of_parse_production p) valid str.\n\n      Let of_parse_production_T str0 h\n        := forall str pf valid pat p, @of_parse_production_T' h str0 str pf valid pat p.\n\n      Let of_parse_T' h\n          {str0 str : String} (pf : str ≤s str0)\n          (valid : names_listT) {pats : productions CharType}\n          (p : parse_of String G str pats)\n        := forall (p_small : size_of_parse p < h),\n             sub_names_listT is_valid_name valid initial_names_data\n             -> Forall_parse_of P p\n             -> ({ p' : @minimal_parse_of str0 valid str pats\n                        & (size_of_parse (parse_of__of__minimal_parse_of p') <= size_of_parse p)\n                          * Forall_parse_of P (parse_of__of__minimal_parse_of p') })%type\n                + alt_option (size_of_parse p) valid str.\n\n      Let of_parse_T str0 h\n        := forall str pf valid pats p, @of_parse_T' h str0 str pf valid pats p.\n\n      Let of_parse_name_T {str0 str valid name} (p : parse_of String G str (Lookup G name)) h\n        := size_of_parse_item (ParseNonTerminal name p) < h\n           -> str ≤s str0\n           -> sub_names_listT is_valid_name valid initial_names_data\n           -> Forall_parse_of_item P (ParseNonTerminal name p)\n           -> ({ p' : @minimal_parse_of_name str0 valid str name\n                      & (size_of_parse_item (parse_of_item__of__minimal_parse_of_item (MinParseNonTerminal p')) <= size_of_parse_item (ParseNonTerminal name p))\n                        * Forall_parse_of_item P (parse_of_item__of__minimal_parse_of_item (MinParseNonTerminal p')) })%type\n              + alt_option (size_of_parse_item (ParseNonTerminal name p)) valid str.\n\n      Section item.\n        Context {str0 str : String} {valid : names_listT}.\n\n        Definition minimal_parse_of_item__of__parse_of_item\n                   h\n                   (minimal_parse_of_name__of__parse_of_name\n                    : forall h' (pf : h' < S (S h)) {str0 str valid name}\n                             (p : parse_of String G str (Lookup G name)),\n                        @of_parse_name_T str0 str valid name p h')\n        : of_parse_item_T str h.\n        Proof.\n          intros str' pf valid' pats p H_h Hinit' H_forall.\n          destruct h as [|h']; [ exfalso; omega | ].\n          destruct p as [|name' str'' p'].\n          { left.\n            eexists (@MinimalParse.MinParseTerminal _ _ _ _ _ _ _ _ _ _);\n              split; simpl; constructor. }\n          { edestruct (fun pf => @minimal_parse_of_name__of__parse_of_name (S h') pf str _ valid' _ p') as [ [p'' H''] | p'' ];\n            try solve [ repeat (apply Lt.lt_n_Sn || apply Lt.lt_S)\n                      | exact Hinit'\n                      | exact H_h\n                      | exact H_forall\n                      | exact pf ];\n            [|];\n            [ left | right ].\n            { exists (MinParseNonTerminal p'').\n              simpl in *.\n              exact H''. }\n            { exact p''. } }\n        Defined.\n      End item.\n\n      Section production.\n        Context {str0 str : String} {valid : names_listT}.\n\n        Local Ltac min_parse_prod_t' :=\n          idtac;\n          match goal with\n            | _ => assumption\n            | [ |- ?R ?x ?x ]\n              => reflexivity\n            | _ => progress destruct_head prod\n            | [ H : False |- _ ]\n              => solve [ destruct H ]\n            | _ => progress simpl\n            | _ => progress rewrite ?parse_of_contract_minimal_parse_of_item_lt, ?parse_of_contract_minimal_parse_of_production_lt, ?parse_of_contract_minimal_parse_of_lt\n            | [ |- context G[size_of_parse_production (ParseProductionCons ?a ?b)] ]\n              => let G' := context G[S (size_of_parse_item a + size_of_parse_production b)] in\n                 change G'\n            | [ H : alt_option _ initial_names_data _ |- _ ]\n              => apply not_alt_all in H\n            | [ p0 : minimal_parse_of_item _ _ ?s0 ?pat,\n                     p1 : minimal_parse_of_production _ _ ?s1 ?pats,\n                          H : ?s0 ++ ?s1 ≤s ?s'\n                |- ({ p' : minimal_parse_of_production ?s' _ (?s0 ++ ?s1) (?pat :: ?pats) & _ } + _)%type ]\n              => left; exists (MinParseProductionCons H p0 p1)\n            | [ p0 : minimal_parse_of_item ?s' _ ?s0 ?pat,\n                     p1 : minimal_parse_of_production ?s' _ ?s1 ?pats,\n                          H : ?s0 ++ ?s1 ≤s ?s',\n                              H' : Length ?s0 < Length ?s'\n                |- ({ p' : minimal_parse_of_production ?s' ?v (?s0 ++ ?s1) (?pat :: ?pats) & _ } + _)%type ]\n              => left; exists (MinParseProductionCons\n                                 H\n                                 (contract_minimal_parse_of_item_lt (valid' := v) H' p0)\n                                 p1)\n            | [ p0 : minimal_parse_of_item ?s' _ ?s0 ?pat,\n                     p1 : minimal_parse_of_production ?s' _ ?s1 ?pats,\n                          H : ?s0 ++ ?s1 ≤s ?s',\n                              H' : Length ?s1 < Length ?s'\n                |- ({ p' : minimal_parse_of_production ?s' ?v (?s0 ++ ?s1) (?pat :: ?pats) & _ } + _)%type ]\n              => left; exists (MinParseProductionCons\n                                 H\n                                 p0\n                                 (contract_minimal_parse_of_production_lt (valid' := v) H' p1))\n            | [ p0 : minimal_parse_of_item ?s' _ ?s0 ?pat,\n                     p1 : minimal_parse_of_production ?s' _ ?s1 ?pats,\n                          H : ?s0 ++ ?s1 ≤s ?s',\n                              H' : Length ?s0 < Length ?s',\n                                   H'' : Length ?s1 < Length ?s'\n                |- ({ p' : minimal_parse_of_production ?s' ?v (?s0 ++ ?s1) (?pat :: ?pats) & _ } + _)%type ]\n              => left; exists (MinParseProductionCons\n                                 H\n                                 (contract_minimal_parse_of_item_lt (valid' := v) H' p0)\n                                 (contract_minimal_parse_of_production_lt (valid' := v) H'' p1))\n            | [ |- (_ * _)%type ]\n              => split\n            | [ H : _ <= _ |- _ <= _ ] => apply H\n            | _ => apply Le.le_n_S\n            | _ => apply Plus.plus_le_compat\n            | [ H0 : Forall_parse_of_item _ _,\n                     H1 : Forall_parse_of_production _ _\n                |- Forall_parse_of_production _ _ ]\n              => exact (H0, H1)\n            | [ H : alt_option _ ?v ?x\n                |- (_ + alt_option _ ?v (?x ++ Empty _))%type ]\n              => right; eapply expand_alt_option'; [ .. | exact H ]\n            | [ H : alt_option _ ?v ?x\n                |- (_ + alt_option _ ?v (Empty _ ++ ?x))%type ]\n              => right; eapply expand_alt_option'; [ .. | exact H ]\n            | [ |- _ = _ ]\n              => progress rewrite ?LeftId, ?RightId\n            | _\n              => solve [ eauto using le_S, Le.le_trans, Plus.le_plus_l, Plus.le_plus_r with nocore ]\n          end.\n        Local Ltac min_parse_prod_pose_t' :=\n          idtac;\n          match goal with\n            | [ H : ?a <> Empty _,\n                    H' : ?a ++ _ ≤s _ |- _ ]\n              => unique pose proof (strle_to_lt_nonempty_r H H')\n            | [ H : ?a <> Empty _,\n                    H' : _ ++ ?a ≤s _ |- _ ]\n              => unique pose proof (strle_to_lt_nonempty_l H H')\n          end.\n        Local Ltac min_parse_prod_pose_t := repeat min_parse_prod_pose_t'.\n        Local Ltac min_parse_prod_t := repeat min_parse_prod_t'.\n\n        (** This is the proof where we pay the proof for conceptual\n            mismatch.  We are, conceptually, simultaneously\n            \"minimizing parse trees\" and \"producing parse traces\".  It\n            is marginally nicer(!!) to contain the ugliness in this\n            single proof, rather than have it infect everything.  So\n            we must conceptually minimize the passed parse tree while\n            in fact building a trace of the parse algorithm.  To do\n            this, in the cons case, we need to figure out how we're\n            decreasing.  According with conceptual minimization, when\n            we have parsed [s0 ++ s1] as a cons of [p0] and [p1],\n            having a smaller parse tree for, say [s0], with any other\n            pattern, does us no good, unless [s1] is empty (and [s0 =\n            s0 ++ s1]), when we can simply pass that smaller parse up\n            the function call tree.  So we must eliminate the\n            \"alternate\" option, by expanding the valid list to the\n            initial data.  Luckily(?!), in the case where [s1] is\n            non-empty, [s0] is strictly smaller than [s0 ++ s1], and\n            thus we can rebuild the minimal parse tree to contract it.\n            This, finally, allows us to either build a minimal parse\n            tree for the thing we are asked about (or to contract the\n            \"alternate option\" parse tree, passing it back up?). *)\n\n        Fixpoint minimal_parse_of_production__of__parse_of_production\n                 h\n                 (minimal_parse_of_name__of__parse_of_name\n                  : forall h' (pf : h' < S (S h)) {str0 str valid name}\n                           (p : parse_of String G str (Lookup G name)),\n                      @of_parse_name_T str0 str valid name p h')\n                 {struct h}\n        : of_parse_production_T str h.\n        Proof.\n          intros str' pf valid' pats p H_h Hinit' H_forall.\n          destruct h as [|h']; [ exfalso; omega | ].\n          destruct p as [| str' strs' str'' pat' p0' p1' ].\n          { clear minimal_parse_of_production__of__parse_of_production.\n            left.\n            eexists (@MinimalParse.MinParseProductionNil _ _ _ _ _ _ _ _ _);\n              repeat (reflexivity || esplit). }\n          { specialize (fun h' pf\n                        => @minimal_parse_of_name__of__parse_of_name\n                             h' (transitivity pf (Lt.lt_n_Sn _))).\n            change (S ((size_of_parse_item p0')\n                       + (size_of_parse_production p1'))\n                    < S h') in H_h.\n            apply Lt.lt_S_n in H_h.\n            pose proof (Lt.le_lt_trans _ _ _ (Plus.le_plus_l _ _) H_h) as H_h0.\n            pose proof (Lt.le_lt_trans _ _ _ (Plus.le_plus_r _ _) H_h) as H_h1.\n            clear H_h.\n            pose proof (fun valid Hinit => @minimal_parse_of_item__of__parse_of_item _ h'  minimal_parse_of_name__of__parse_of_name _ (transitivity (str_le1_append _ _ _) pf) valid _ p0' H_h0 Hinit (fst H_forall)) as p_it.\n            pose proof (fun valid Hinit => @minimal_parse_of_production__of__parse_of_production h' minimal_parse_of_name__of__parse_of_name _ (transitivity (str_le2_append _ _ _) pf) valid _ p1' H_h1 Hinit (snd H_forall)) as p_prod.\n            destruct (stringlike_dec str' (Empty _)), (stringlike_dec str'' (Empty _));\n              subst.\n            { (* empty, empty *)\n              specialize (p_it valid' Hinit'); specialize (p_prod valid' Hinit').\n              destruct p_it as [ [ p0'' H0''] |], p_prod as [ [ p1'' H1'' ] |];\n                [ | | | ];\n                min_parse_prod_t. }\n            { (* empty, nonempty *)\n              specialize (p_it initial_names_data (reflexivity _)); specialize (p_prod valid' Hinit').\n              destruct p_it as [ [ p0'' H0''] |], p_prod as [ [ p1'' H1'' ] |];\n                [ | | | ];\n                min_parse_prod_t;\n                min_parse_prod_pose_t;\n                min_parse_prod_t. }\n            { (* nonempty, empty *)\n              specialize (p_it valid' Hinit'); specialize (p_prod initial_names_data (reflexivity _)).\n              destruct p_it as [ [ p0'' H0''] |], p_prod as [ [ p1'' H1'' ] |];\n                [ | | | ];\n                min_parse_prod_t;\n                min_parse_prod_pose_t;\n                min_parse_prod_t. }\n            { (* nonempty, nonempty *)\n              specialize (p_it initial_names_data (reflexivity _)); specialize (p_prod initial_names_data (reflexivity _)).\n              destruct p_it as [ [ p0'' H0''] |], p_prod as [ [ p1'' H1'' ] |];\n                [ | | | ];\n                min_parse_prod_t;\n                min_parse_prod_pose_t;\n                min_parse_prod_t. } }\n        Defined.\n      End production.\n\n      Section productions.\n        Context {str0 str : String} {valid : names_listT}.\n\n        Fixpoint minimal_parse_of_productions__of__parse_of_productions\n                 h\n                 (minimal_parse_of_name__of__parse_of_name\n                  : forall h' (pf : h' < S h) {str0 str valid name}\n                           (p : parse_of String G str (Lookup G name)),\n                      @of_parse_name_T str0 str valid name p h')\n                 {struct h}\n        : of_parse_T str h.\n        Proof.\n          intros str' pf valid' pats p H_h Hinit' H_forall.\n          destruct h as [|h']; [ exfalso; omega | ].\n          destruct p as [str' pat pats p' | str' pat pats p'].\n          { clear minimal_parse_of_productions__of__parse_of_productions.\n            edestruct (@minimal_parse_of_production__of__parse_of_production _ h' minimal_parse_of_name__of__parse_of_name _ pf valid' _ p') as [ [p'' p''H] | [name' H'] ];\n            try solve [ exact (Lt.lt_S_n _ _ H_h)\n                      | exact H_forall\n                      | exact Hinit' ];\n            [|].\n            { left.\n              exists (MinParseHead pats p'').\n              simpl.\n              split;\n                solve [ exact (Le.le_n_S _ _ (fst p''H))\n                      | exact (snd p''H) ]. }\n            { right.\n              exists name'.\n              split;\n                try solve [ exact (fst H') ];\n                [].\n              exists (projT1 (snd H'));\n                split;\n                try solve [ exact (snd (projT2 (snd H')))\n                          | exact (Lt.lt_S _ _ (fst (projT2 (snd H')))) ]. } }\n          { specialize (fun h' pf\n                        => @minimal_parse_of_name__of__parse_of_name\n                             h' (transitivity pf (Lt.lt_n_Sn _))).\n            edestruct (minimal_parse_of_productions__of__parse_of_productions h'  minimal_parse_of_name__of__parse_of_name _ pf valid' _ p') as [ [p'' p''H] | [name' H'] ];\n            try solve [ exact (Lt.lt_S_n _ _ H_h)\n                      | exact Hinit'\n                      | exact H_forall ];\n            [|].\n            { left.\n              exists (MinParseTail pat p'').\n              simpl.\n              split;\n                solve [ exact (Le.le_n_S _ _ (fst p''H))\n                      | exact (snd p''H) ]. }\n            { right.\n              exists name'.\n              split;\n                try solve [ exact (fst H') ];\n                [].\n              exists (projT1 (snd H'));\n                split;\n                try solve [ exact (snd (projT2 (snd H')))\n                          | exact (Lt.lt_S _ _ (fst (projT2 (snd H')))) ]. } }\n        Defined.\n      End productions.\n\n      Section name.\n        Section step.\n          Definition minimal_parse_of_name__of__parse_of_name_step\n                     h\n                     (minimal_parse_of_name__of__parse_of_name\n                      : forall h' (pf : h' < h) {str0 str valid name}\n                               (p : parse_of String G str (Lookup G name)),\n                          @of_parse_name_T str0 str valid name p h')\n                     {str0 str valid name}\n                     (p : parse_of String G str (Lookup G name))\n          : @of_parse_name_T str0 str valid name p h.\n          Proof.\n            destruct h as [|h]; [ clear; repeat intro; exfalso; omega | ].\n            intros pf Hstr Hinit' H_forall.\n            let H := match goal with H : str ≤s str0 |- _ => constr:H end in\n            destruct (strle_to_sumbool _ H) as [pf_lt|pf_eq].\n            { (** [str] got smaller, so we reset the valid names list *)\n              destruct (@minimal_parse_of_productions__of__parse_of_productions str h minimal_parse_of_name__of__parse_of_name str (reflexivity _) initial_names_data (Lookup G name) p (Lt.lt_S_n _ _ pf) (reflexivity _) (snd H_forall)) as [p'|p'].\n              { left.\n                exists (MinParseNonTerminalStrLt _ valid _ pf_lt (projT1 p'));\n                  simpl.\n                simpl in *.\n                split;\n                  [ exact (Le.le_n_S _ _ (fst (projT2 p')))\n                  | split;\n                    [ exact (fst H_forall)\n                    | exact (snd (projT2 p')) ] ]. }\n              { simpl.\n                right; eapply expand_alt_option; [..| exact p' ];\n                solve [ apply Lt.lt_n_Sn\n                      | assumption\n                      | reflexivity ]. } }\n            { (** [str] didn't get smaller, so we cache the fact that we've hit this name already *)\n              destruct (Sumbool.sumbool_of_bool (is_valid_name valid name)) as [ Hvalid | Hinvalid ].\n              { destruct (@minimal_parse_of_productions__of__parse_of_productions str h minimal_parse_of_name__of__parse_of_name str (reflexivity _) (remove_name valid name) (Lookup G name) p (Lt.lt_S_n _ _ pf) (transitivity (R := sub_names_listT is_valid_name) (@sub_names_listT_remove _ is_valid_name _ remove_name_1 _ _) Hinit') (snd H_forall)) as [p'|p'].\n                { left.\n                  subst str.\n                  eexists (@MinimalParse.MinParseNonTerminalStrEq _ _ _ _ _ _ _ _ _ _ Hvalid (projT1 p')).\n                  simpl in *.\n                  split;\n                    [ exact (Le.le_n_S _ _ (fst (projT2 p')))\n                    | split;\n                      [ exact (fst H_forall)\n                      | exact (snd (projT2 p')) ] ]. }\n                { destruct p' as [name' p'].\n                  destruct (string_dec name name') as [|n].\n                  { subst name; simpl in *.\n                    edestruct (@minimal_parse_of_name__of__parse_of_name (S (size_of_parse p)) pf str0 _ valid name' (projT1 (snd p'))) as [p''|p''];\n                    try solve [ apply Lt.lt_n_S, (fst (projT2 (snd p')))\n                              | subst; reflexivity\n                              | assumption\n                              | split; [ exact (proj2 (fst p'))\n                                       | exact (snd (projT2 (snd p'))) ] ];\n                    [|].\n                    { left.\n                      exists (projT1 p'').\n                      split.\n                      { etransitivity;\n                        [ exact (fst (projT2 p''))\n                        | exact (Lt.lt_le_weak _ _ (Lt.lt_n_S _ _ (fst (projT2 (snd p'))))) ]. }\n                      { exact (snd (projT2 p'')). } }\n                    { right.\n                      exists (projT1 p'').\n                      split;\n                        [ exact (fst (projT2 p''))\n                        | ].\n                      exists (projT1 (snd (projT2 p''))).\n                      split;\n                        [ etransitivity;\n                          [ exact (fst (projT2 (snd (projT2 p''))))\n                          | exact (Lt.lt_n_S _ _ (fst (projT2 (snd p')))) ]\n                        | exact (snd (projT2 (snd (projT2 p'')))) ]. } }\n                  { right.\n                    exists name'.\n                    destruct p' as [p'H p'p].\n                    split.\n                    { rewrite remove_name_5 in p'H by assumption.\n                      exact p'H. }\n                    { exists (projT1 p'p).\n                      split; [ exact (Lt.lt_S _ _ (fst (projT2 p'p)))\n                             | exact (snd (projT2 p'p)) ]. } } } }\n              { (** oops, we already saw this name in the past.  ABORT! *)\n                right.\n                exists name.\n                destruct H_forall.\n                split; [ split; assumption\n                       | ].\n                exists p.\n                split; solve [ assumption\n                             | apply Lt.lt_n_Sn ]. } }\n          Defined.\n        End step.\n\n        Section wf.\n          Definition minimal_parse_of_name__of__parse_of_name\n          : forall h\n                   {str0 str valid name}\n                   (p : parse_of String G str (Lookup G name)),\n              @of_parse_name_T str0 str valid name p h\n            := @Fix\n                 _ lt lt_wf\n                 (fun h => forall {str0 str valid name}\n                                  (p : parse_of String G str (Lookup G name)),\n                             @of_parse_name_T str0 str valid name p h)\n                 (@minimal_parse_of_name__of__parse_of_name_step).\n        End wf.\n      End name.\n    End wf_parts.\n  End minimize.\nEnd cfg.\n", "meta": {"author": "JasonGross", "repo": "adt-synthesis", "sha": "30a5cd361af029f42864e103a5a604ffa9ee07a7", "save_path": "github-repos/coq/JasonGross-adt-synthesis", "path": "github-repos/coq/JasonGross-adt-synthesis/adt-synthesis-30a5cd361af029f42864e103a5a604ffa9ee07a7/src/Parsers/MinimalParseOfParse.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.2119354561599388}}
{"text": "Require Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Smallstep.\nRequire Import GlobalenvsC.\nRequire Import LinkingC.\nRequire Import CoqlibC.\nRequire Import sflib.\n\nRequire Import ModSem Mod Skeleton System.\nRequire Export Syntax.\n\nSet Implicit Arguments.\n\n\n\n\n\n\n\n\n\nModule Frame.\n\n  Record t: Type := mk {\n    ms: ModSem.t;\n    st: ms.(ModSem.state); (* local state *)\n  }.\n\n  Definition update_st (fr0: t) (st0: fr0.(ms).(ModSem.state)): t := (mk fr0.(ms) st0).\n\nEnd Frame.\n\n\n\nModule Ge.\n\n  (* NOTE: Ge.(snd) is not used in semantics. It seems it is just for convenience in meta theory *)\n  Definition t: Type := (list ModSem.t * SkEnv.t).\n\n  Inductive find_fptr_owner (ge: t) (fptr: val) (ms: ModSem.t): Prop :=\n  | find_fptr_owner_intro\n      (MODSEM: In ms (fst ge))\n      if_sig\n      (INTERNAL: Genv.find_funct ms.(ModSem.skenv) fptr = Some (Internal if_sig)).\n\n  Inductive disjoint (ge: t): Prop :=\n  | disjoint_intro\n      (DISJOINT: forall fptr ms0 ms1\n          (FIND0: ge.(find_fptr_owner) fptr ms0)\n          (FIND1: ge.(find_fptr_owner) fptr ms1),\n          ms0 = ms1).\n\nEnd Ge.\n\nInductive state: Type :=\n| Callstate\n    (args: Args.t)\n    (frs: list Frame.t)\n| State\n    (frs: list Frame.t).\n\nInductive step (ge: Ge.t): state -> trace -> state -> Prop :=\n| step_call\n    fr0 frs args\n    (AT: fr0.(Frame.ms).(ModSem.at_external) fr0.(Frame.st) args):\n    step ge (State (fr0 :: frs))\n         E0 (Callstate args (fr0 :: frs))\n\n| step_init\n    args frs ms st_init\n    (MSFIND: ge.(Ge.find_fptr_owner) (Args.get_fptr args) ms)\n    (INIT: ms.(ModSem.initial_frame) args st_init):\n    step ge (Callstate args frs)\n         E0 (State ((Frame.mk ms st_init) :: frs))\n\n| step_internal\n    fr0 frs tr st0\n    (STEP: Step (fr0.(Frame.ms)) fr0.(Frame.st) tr st0):\n    step ge (State (fr0 :: frs))\n         tr (State (((Frame.update_st fr0) st0) :: frs))\n| step_return\n    fr0 fr1 frs retv st0\n    (FINAL: fr0.(Frame.ms).(ModSem.final_frame) fr0.(Frame.st) retv)\n    (AFTER: fr1.(Frame.ms).(ModSem.after_external) fr1.(Frame.st) retv st0):\n    step ge (State (fr0 :: fr1 :: frs))\n         E0 (State (((Frame.update_st fr1) st0) :: frs)).\n\n\n\n\nSection SEMANTICS.\n\n  Variable p: program.\n\n  Definition link_sk: option Sk.t := link_list (List.map Mod.sk p).\n\n  Definition skenv_fill_internals (skenv: SkEnv.t): SkEnv.t :=\n    (Genv_map_defs skenv) (fun _ gd => Some\n                                      match gd with\n                                      | Gfun (External ef) => (Gfun (Internal (ef_sig ef)))\n                                      | Gfun _ => gd\n                                      | Gvar gv => gd\n                                      end).\n\n  Definition load_system (skenv: SkEnv.t): (ModSem.t * SkEnv.t) :=\n    (System.modsem skenv, (skenv_fill_internals skenv)).\n\n  Definition load_modsems (skenv: SkEnv.t): list ModSem.t := List.map ((flip Mod.modsem) skenv) p.\n\n  Definition load_genv (init_skenv: SkEnv.t): Ge.t :=\n    let (system, skenv) := load_system init_skenv in\n    (system :: (load_modsems init_skenv), init_skenv).\n\n  (* Making dummy_module that calls main? => Then what is sk of it? Memory will be different with physical linking *)\n  Inductive initial_state: state -> Prop :=\n  | initial_state_intro\n      sk_link skenv_link m_init fptr_init\n      (INITSK: link_sk = Some sk_link)\n      (INITSKENV: (Sk.load_skenv sk_link) = skenv_link)\n      (INITMEM: (Sk.load_mem sk_link) = Some m_init)\n      (FPTR: fptr_init = (Genv.symbol_address skenv_link sk_link.(prog_main) Ptrofs.zero))\n      (SIG: (Genv.find_funct skenv_link) fptr_init = Some (Internal signature_main))\n      (WF: forall md (IN: In md p), <<WF: Sk.wf md>>):\n      initial_state (Callstate (Args.mk fptr_init [] m_init) []).\n\n  Inductive final_state: state -> int -> Prop :=\n  | final_state_intro\n      fr0 retv i\n      (FINAL: fr0.(Frame.ms).(ModSem.final_frame) fr0.(Frame.st) retv)\n      (INT: (Retv.v retv) = Vint i):\n      final_state (State [fr0]) i.\n\n  Definition sem: semantics :=\n    (Semantics_gen (fun _ => step) initial_state final_state\n                   (match link_sk with\n                    | Some sk_link => load_genv (Sk.load_skenv sk_link)\n                    | None => (nil, SkEnv.empty)\n                    end)\n                   (* NOTE: The symbolenv here is never actually evoked in our semantics. Putting this value is merely for our convenience. (lifting receptive/determinate) Whole proof should be sound even if we put dummy data here. *)\n                   (match link_sk with\n                    | Some sk_link => (Sk.load_skenv sk_link)\n                    | None => SkEnv.empty\n                    end)).\n  (* Note: I don't want to make it option type. If it is option type, there is a problem. *)\n  (* I have to state this way:\n```\nVariable sem_src: semantics.\nHypothesis LOADSRC: load p_src = Some sem_src.\n```\nThen, sem_src.(state) is not evaluatable.\n   *)\n  (* However, if it is not option type.\n```\nLet sem_src := semantics prog.\n```\nThen, sem_src.(state) is evaluatable.\n   *)\n\nEnd SEMANTICS.\n\nHint Unfold link_sk load_modsems load_genv.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/compose/Sem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21193545340226322}}
{"text": "(* GENERIC *)\n\nRequire Export MinBFTg.\nRequire Export ComponentSM10.\n\n\nSection MinBFTdeq.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext        }.\n  Context { minbft_context      : MinBFT_context      }.\n  Context { m_initial_keys      : MinBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys   }.\n  Context { usig_hash           : USIG_hash           }.\n  Context { minbft_auth         : MinBFT_auth         }.\n\n  Context { ti : TrustedInfo }.\n\n\n  Lemma Bare_Reply_Deq : Deq Bare_Reply.\n  Proof.\n    repeat introv.\n    destruct x as [c1 t1 m1 v1], y as [c2 t2 m2 v2].\n    destruct (Request_Deq c1 c2); subst; prove_dec.\n    destruct (deq_nat t1 t2); subst; prove_dec.\n    destruct (rep_deq m1 m2); subst; prove_dec.\n    destruct (ViewDeq v1 v2); subst; prove_dec.\n  Defined.\n\n  Lemma Reply_Deq : Deq Reply.\n  Proof.\n    repeat introv.\n    destruct x as [r1 a1], y as [r2 a2].\n    destruct (Bare_Reply_Deq r1 r2); subst; prove_dec.\n    destruct (Tokens_dec a1 a2); subst; prove_dec.\n  Defined.\n\n  Lemma Bare_Prepare_Deq : Deq Bare_Prepare.\n  Proof.\n    repeat introv.\n    destruct x as [c1 t1 m1 v1], y as [c2 t2 m2 v2].\n    destruct (ViewDeq c1 c2); subst; prove_dec.\n    destruct (Request_Deq t1 t2); subst; prove_dec.\n  Defined.\n\n  Lemma Prepare_Deq : Deq Prepare.\n  Proof.\n    repeat introv.\n    destruct x as [r1 a1], y as [r2 a2].\n    destruct (Bare_Prepare_Deq r1 r2); subst; prove_dec.\n    destruct (UI_dec a1 a2); subst; prove_dec.\n  Defined.\n\n  Lemma Bare_Commit_Deq : Deq Bare_Commit.\n  Proof.\n    repeat introv.\n    destruct x as [c1 t1 m1 v1], y as [c2 t2 m2 v2].\n    destruct (ViewDeq c1 c2); subst; prove_dec.\n    destruct (Request_Deq t1 t2); subst; prove_dec.\n    destruct (UI_dec m1 m2); subst; prove_dec.\n  Defined.\n\n  Lemma Commit_Deq : Deq Commit.\n  Proof.\n    repeat introv.\n    destruct x as [r1 a1], y as [r2 a2].\n    destruct (Bare_Commit_Deq r1 r2); subst; prove_dec.\n    destruct (UI_dec a1 a2); subst; prove_dec.\n  Defined.\n\n  Lemma Accept_Deq : Deq Accept.\n  Proof.\n    repeat introv.\n    destruct x as [c1 t1 m1 v1], y as [c2 t2 m2 v2].\n    destruct (Request_Deq c1 c2); subst; prove_dec.\n    destruct (deq_nat t1 t2); subst; prove_dec.\n  Defined.\n\n  Lemma msg_deq : Deq msg.\n  Proof.\n    introv.\n    destruct x, y; simpl in *; subst; prove_dec.\n    { destruct (Request_Deq m m0); subst; prove_dec. }\n    { destruct (Reply_Deq m m0); subst; prove_dec. }\n    { destruct (Prepare_Deq p p0); subst; prove_dec. }\n    { destruct (Commit_Deq c c0); subst; prove_dec. }\n    { destruct (Accept_Deq a a0); subst; prove_dec. }\n    { destruct (string_dec s s0); subst; prove_dec. }\n  Qed.\n\n  Lemma ti_deq : Deq (trigger_info msg).\n  Proof.\n    introv; destruct x as [u1| |i1], y as [u2| |i2]; subst; prove_dec.\n    { destruct (msg_deq u1 u2); subst; prove_dec. }\n    { destruct i1 as [cn1 i1], i1 as [x|], i2 as [cn2 i2], i2 as [y|]; simpl in *; repnd; simpl in *;\n        destruct (PreCompNameDeq cn1 cn2); subst; prove_dec.\n      { destruct (ViewDeq x2 y2); subst; prove_dec.\n        destruct (Request_Deq x1 y1); subst; prove_dec.\n        destruct (deq_nat x0 y0); subst; prove_dec.\n        destruct (deq_nat x y); subst; prove_dec. }\n      { destruct (ViewDeq msgui4 msgui2); subst; prove_dec.\n        destruct (Request_Deq msgui3 msgui1); subst; prove_dec.\n        destruct (UI_dec msgui msgui0); subst; prove_dec. } }\n  Qed.\n\nEnd MinBFTdeq.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MinBFTdeq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2119354534022632}}
{"text": "Require Export Process.\n(* easier to deal with monads? *)\nRequire Export FunctionalExtensionality.\nRequire Export tactics2.\nRequire Export Ref.\n\nRequire Export String.\nRequire Export Peano.\nRequire Export List.\n\n\nSection ComponentSM.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { pd  : @Data }.\n  Context { pn  : @Node }.\n  Context { pk  : @Key }.\n  Context { pat : @AuthTok }.\n  Context { paf : @AuthFun pn pk pat pd }.\n  Context { pm  : @Msg }.\n  Context { pda : @DataAuth pd pn }.\n  Context { cad : ContainedAuthData }.\n  Context { gms : MsgStatus }.\n  Context { dtc : @DTimeContext }.\n  Context { qc  : @Quorum_context pn }.\n  Context { iot : @IOTrustedFun }.\n\n\n  Definition CompNameLevel := nat.\n  Definition CompNameState := nat.\n  Definition CompNameTrust := bool.\n\n  Definition CompNameKindDeq  : Deq CompNameKind  := String.string_dec.\n  Definition CompNameSpaceDeq : Deq CompNameSpace := deq_nat.\n  Definition CompNameStateDeq : Deq CompNameSpace := deq_nat.\n  Definition CompNameTrustDeq : Deq CompNameTrust := bool_dec.\n\n  (* TODO:use [TrustTag] instead of [bool] *)\n  Inductive TrustTag :=\n  | tt_TRUSTED\n  | tt_UNTRUSTED.\n\n  Record CompName :=\n    MkCompName\n      {\n        comp_name_pre   :> PreCompName;\n        comp_name_trust : CompNameTrust (* TrustTag *);\n      }.\n\n  Definition MkCN\n             (k : CompNameKind)\n             (s : CompNameSpace)\n             (t : CompNameTrust)\n    : CompName :=\n    MkCompName (MkPreCompName k s) t.\n\n  Lemma CompNameDeq : Deq CompName.\n  Proof.\n    introv; unfold deceq; destruct x as [[n1 s1] b1], y as [[n2 s2] b2].\n    destruct (CompNameKindDeq n1 n2);\n      destruct (CompNameSpaceDeq s1 s2);\n      destruct (CompNameTrustDeq b1 b2);\n      prove_dec.\n  Defined.\n\n  (* component *)\n  Record p_nproc (p : CompName -> Type) :=\n    MkPProc\n      {\n        pp_name : CompName;\n        pp_proc : p pp_name;\n      }.\n  Global Arguments MkPProc [p] _ _.\n  Global Arguments pp_name [p] _.\n  Global Arguments pp_proc [p] _.\n  (* list of components *)\n  Definition p_procs (p : CompName -> Type) := list (p_nproc p).\n\n  Lemma decomp_p_nproc :\n    forall {p : CompName -> Type} {cn : CompName} {p1 p2 : p cn},\n      MkPProc cn p1 = MkPProc cn p2 -> p1 = p2.\n  Proof.\n    introv h.\n    inversion h as [xx].\n    apply inj_pair2_eq_dec in xx; auto.\n    apply CompNameDeq.\n  Qed.\n\n  (* monad of the component *)\n  Definition M_p (p : CompName -> Type) (PO : Type) :=\n    p_procs p -> (p_procs p * PO)%type.\n\n  (* monad update function of the component that can halt *)\n  Definition MP_Update (p : CompName -> Type) (I O S : Type) :=\n    S -> I -> M_p p (option S * O).\n\n  (* component interface;\n     we need cio_I ans cio_O because USIG does not take messages as input and\n     it does not return Directed messages as output *)\n  Record ComponentIO :=\n    MkComponentIO\n      {\n        cio_I : Type;\n        cio_O : Type;\n        cio_default_O : cio_O;\n      }.\n\n  (* component that works with DirectedMsgs *)\n  Definition CIOmsg : ComponentIO :=\n    MkComponentIO msg DirectedMsgs [].\n\n  Definition CIOtrusted (cn : PreCompName) : ComponentIO :=\n    MkComponentIO\n      (iot_input (iot_fun cn))\n      (iot_output (iot_fun cn))\n      (iot_def_output (iot_fun cn)).\n\n  (* A default CIO *)\n  Definition CIOdef : ComponentIO :=\n    MkComponentIO unit unit tt.\n\n  (* A [nat] CIO *)\n  Definition CIOnat : ComponentIO :=\n    MkComponentIO nat nat 0.\n\n  (* A [bool] CIO *)\n  Definition CIObool : ComponentIO :=\n    MkComponentIO bool bool true.\n\n  (* interface of the single component *)\n  Class baseFunIO :=\n    MkBaseFunIO\n      {\n        bfio : CompName -> ComponentIO;\n      }.\n\n  Context { base_fun_io : baseFunIO }.\n\n  Class baseStateFun :=\n    MkBaseStateFun\n      {\n        bsf : CompName -> Type;\n      }.\n\n  Context { base_state_fun : baseStateFun }.\n\n  Class trustedStateFun :=\n    MkTrustedStateFun\n      {\n        tsf : PreCompName -> Type;\n      }.\n\n  Context { trusted_state_fun : trustedStateFun }.\n\n  (* interface of the single component;\n     all components with same name have same input/output behavior  *)\n  Class funIO :=\n    MkFunIO\n      {\n        fio : CompName -> ComponentIO;\n      }.\n\n  Class stateFun :=\n    MkStateFun\n      {\n        sf : CompName -> Type;\n      }.\n\n  (* unit state *)\n\n  (* \"MSG\" components must have a msg interface *)\n  Definition msg_comp_name_kind  : CompNameKind  := \"MSG\".\n  Definition msg_comp_name_state : CompNameState := 0.\n  Definition msg_comp_name_trust : CompNameTrust := false.\n  Definition msg_comp_name space : CompName :=\n    MkCN\n      msg_comp_name_kind\n      space\n      msg_comp_name_trust.\n\n  (* \"UNIT\",0 components must have a unit interface and a [unit] state *)\n  Definition unit_comp_name_kind  : CompNameKind  := \"UNIT\".\n  Definition unit_comp_name_space : CompNameSpace := 1.\n  Definition unit_comp_name_trust : CompNameTrust := false.\n  Definition unit_comp_name_state : CompNameState := 0.\n  Definition unit_comp_name : CompName :=\n    MkCN\n      unit_comp_name_kind\n      unit_comp_name_space\n      unit_comp_name_trust.\n\n  (* \"NAT\",0 components must have a unit interface and a [nat] state *)\n  Definition nat_comp_name_kind  : CompNameKind  := \"NAT\".\n  Definition nat_comp_name_space : CompNameSpace := 0.\n  Definition nat_comp_name_state : CompNameState := 0.\n  Definition nat_comp_name_trust : CompNameTrust := false.\n  Definition nat_comp_name : CompName :=\n    MkCN\n      nat_comp_name_kind\n      nat_comp_name_space\n      nat_comp_name_trust.\n\n  (* \"BOOL\",0 components must have a unit interface and a [bool] state *)\n  Definition bool_comp_name_kind  : CompNameKind := \"BOOL\".\n  Definition bool_comp_name_space : CompNameSpace := 0.\n  Definition bool_comp_name_state : CompNameState := 0.\n  Definition bool_comp_name_trust : CompNameTrust := false.\n  Definition bool_comp_name : CompName :=\n    MkCN\n      bool_comp_name_kind\n      bool_comp_name_space\n      bool_comp_name_trust.\n\n  (* \"MSG\",1 components must have a msg interface and a unit state *)\n  Definition munit_comp_name : CompName := msg_comp_name 1.\n\n  Definition key_comp_name_kind  : CompNameKind := \"KEY\".\n\n  (* We override here some IO interfaces:\n       - \"MSG\"   components must have the [CIOmsg] IO interface\n       - \"UNIT\"  components must have the [CIOdef] IO interface\n       - \"NAT\"   components must have the [CIOnat] IO interface\n       - \"BOOL\"  components must have the [CIObool] IO interface\n       - trusted components must have the [CIOtrusted] IO interface\n   *)\n  Definition funIOd_msg_nm (nm : CompName) :=\n    if comp_name_trust nm then CIOtrusted nm\n    else if CompNameKindDeq (comp_name_kind nm) msg_comp_name_kind then CIOmsg\n         else if CompNameKindDeq (comp_name_kind nm) unit_comp_name_kind then CIOdef\n              else if CompNameKindDeq (comp_name_kind nm) nat_comp_name_kind then CIOnat\n                   else if CompNameKindDeq (comp_name_kind nm) bool_comp_name_kind then CIObool\n                        else bfio nm.\n\n  (* We constrain here that components with named [msg_comp_name] have to be\n     message components, i.e., taking in messages and returning directed messages *)\n  Global Instance funIOd_msg : funIO :=\n    MkFunIO funIOd_msg_nm.\n\n  (* We override here some types of states:\n       - \"UNIT\"  components must have a state of type [unit]\n       - \"NAT\"   components must have a state of type [nat]\n       - \"BOOL\"  components must have a state of type [nat]\n       - \"KEY\"   components must have a state of type [local_key_map]\n       - trusted components must have a state of type [tsf]\n   *)\n  Definition statefund_nm (nm : CompName) : Type :=\n    if comp_name_trust nm then tsf nm\n    else if CompNameSpaceDeq (comp_name_space nm) unit_comp_name_space then unit\n         else if CompNameKindDeq (comp_name_kind nm) nat_comp_name_kind then nat\n              else if CompNameKindDeq (comp_name_kind nm) bool_comp_name_kind then bool\n                   else if CompNameKindDeq (comp_name_kind nm) key_comp_name_kind then local_key_map\n                        else bsf nm.\n\n  Global Instance stateFund : stateFun :=\n    MkStateFun statefund_nm.\n\n\n  (* ====== Lookup table ====== *)\n  (* This is used to register state machines when not using the monad\n     The Boolean is redundant, it says whether [cn] is trusted, which is already part of [cn] *)\n  Definition lookup_table : ref (list {cn : CompName & {b : bool & cio_I (fio cn) -> (unit * cio_O (fio cn))}}) :=\n    ref_cons [].\n\n  Definition update_lookup\n             (level   : nat)\n             (name    : CompName)\n             (sm      : cio_I (fio name) -> (unit * cio_O (fio name))) :=\n    update_ref\n      lookup_table\n      ((existT _ name (existT _ (comp_name_trust name) sm)) :: get_ref lookup_table).\n  (* ====== ======= *)\n\n\n  (* state machine as monad -- one level state machine*)\n  Record MP_StateMachine (p : CompName -> Type) (cn : CompName) : Type :=\n    MkMPSM\n      {\n        sm_update :> MP_Update p (cio_I (fio cn)) (cio_O (fio cn)) (sf cn);\n        sm_state  : sf cn;\n      }.\n  Global Arguments MkMPSM    [p] [cn] _ _.\n  Global Arguments sm_update [p] [cn] _ _ _ _.\n  Global Arguments sm_state  [p] [cn] _.\n\n  Definition NFalse (cn : CompName) : Type := False.\n\n  Inductive sm_or (A B : Type) : Type :=\n  | sm_or_at (a : A)\n  | sm_or_sm (b : B).\n  Global Arguments sm_or_at [A] [B] _.\n  Global Arguments sm_or_sm [A] [B] _.\n\n  Notation \"A \\+/ B\" := (sm_or A B) (at level 70).\n\n  (* Cumulative hierarchy of state machines *)\n  Fixpoint M_StateMachine (n : nat) (cn : CompName) : Type :=\n    match n with\n    | 0 => False (*MP_StateMachine NFalse cn*)\n    | S n => MP_StateMachine (M_StateMachine n) cn \\+/ M_StateMachine n cn\n    end.\n\n  (* list of state machines; each state machine can have several levels *)\n  Definition n_proc := M_StateMachine.\n  Definition n_nproc (n : nat) := p_nproc (n_proc n).\n  Definition n_procs (n : nat) := list (n_nproc n).\n\n  (* a state machine exactly at level [S n] *)\n  Definition n_proc_at (n : nat) (cn : CompName) := MP_StateMachine (n_proc n) cn.\n\n  (* monad of the list of state machines; each state machine can have several levels *)\n  Definition M_n (n : nat) (PO : Type) := n_procs n -> (n_procs n * PO)%type.\n\n  (* monad update function that can halt *)\n  Definition M_Update (n : nat) (nm : CompName) (S : Type) :=\n    S -> cio_I (fio nm) -> M_n n (option S * cio_O (fio nm)).\n\n  (* return state and output ? *)\n  Definition ret {A} (n : nat) (a : A) : M_n n A := fun s => (s, a).\n\n  (* enables combining multiple state machine monads *)\n  Definition bind {A B} {n:nat} (m : M_n n A) (f : A -> M_n n B) : M_n n B :=\n    fun s =>\n      let (s1,a) := m s in\n      let (s2,b) := f a s1 in\n      (s2,b).\n\n  Notation \"a >>= f\" := (bind a f) (at level 80).\n\n  Definition bind_pair {A B C} {n:nat} (m : M_n n (A * B)) (f : A -> B -> M_n n C) : M_n n C :=\n    m >>= fun p => let (a,b) := p in f a b.\n\n  Notation \"a >>>= f\" := (bind_pair a f) (at level 80).\n\n  Lemma bind_bind :\n    forall {n} {A B C} (m : M_n n A) (f : A -> M_n n B) (g : B -> M_n n C),\n      ((m >>= f) >>= g)\n      = (m >>= (fun a => ((f a) >>= g))).\n  Proof.\n    introv; apply functional_extensionality; introv; simpl.\n    unfold bind; simpl.\n    destruct (m x).\n    destruct (f a n0).\n    destruct (g b n1); auto.\n  Qed.\n\n  (* in a list of monad processes, find the one that has a Component Name nm *)\n  Fixpoint find_name {n:nat} (nm : CompName) (l : n_procs n) : option (n_proc n nm) :=\n    match l with\n    | [] => None\n    | MkPProc m pr :: rest =>\n      match CompNameDeq m nm with\n      | left q => Some (eq_rect _ _ pr _ q)\n      | right _ => find_name nm rest\n      end\n    end.\n\n  Definition at2sm\n             {n  : nat}\n             {cn : CompName}\n             (p  : n_proc_at n cn) : n_proc (S n) cn :=\n    sm_or_at p.\n\n  Definition MP_defSM\n             (cn : CompName)\n             (n  : nat)\n             (d  : sf cn) : n_proc_at n cn :=\n    MkMPSM\n      (fun s i p => (p, (None, cio_default_O (fio cn))))\n      d.\n\n  Definition M_defSM\n             (nm : CompName)\n             (n  : nat)\n             (d  : sf nm) : n_proc 1 nm :=\n    at2sm\n      (MkMPSM\n         (fun s i p => (p, (None, cio_default_O (fio nm))))\n         d).\n\n  (* incr of one level state machine monad *)\n  Definition incr_n_proc {n} {nm} (p : n_proc n nm) : n_proc (S n) nm := sm_or_sm p.\n\n  (* incr of state machine monad -each state machine can have multiple levels *)\n  Definition incr_n_nproc {n} (p : n_nproc n) : n_nproc (S n) :=\n    match p with\n    | MkPProc m q =>\n      MkPProc m (incr_n_proc q)\n    end.\n\n  (* incr list of state machine monads -- each state machine can have multiple levels *)\n  Definition incr_n_procs {n} (ps : n_procs n) : n_procs (S n) :=\n    map incr_n_nproc ps.\n\n(*  (* halted monad of the state machine -- each state machine that can have several levels*)\n  Fixpoint M_haltedSM_n {S}\n           (n  : nat)\n           (nm : CompName)\n           (d  : S) : n_proc n nm :=\n    match n with\n    | 0 => M_haltedSM nm d\n    | S m => incr_n_proc (M_haltedSM_n m nm d)\n    end.*)\n\n  Definition decr_n_proc {n} {nm} : n_proc n nm -> option (n_proc (Init.Nat.pred n) nm) :=\n    match n with\n    | 0 => fun p => match p with end\n    | S m => fun p =>\n               match p with\n               | sm_or_at _ => None\n               | sm_or_sm q => Some q\n               end\n    end.\n\n  Definition decr_n_nproc {n} (np : n_nproc n) : option (n_nproc (Init.Nat.pred n)) :=\n    match np with\n    | MkPProc m p =>\n      match decr_n_proc p with\n      | Some q => Some (MkPProc m q)\n      | None => None\n      end\n    end.\n\n  Definition decr_n_procs {n} (ps : n_procs n) : n_procs (Init.Nat.pred n) :=\n    mapOption decr_n_nproc ps.\n\n  Definition incr_pred_n_proc {n} {nm} : n_proc (pred n) nm -> n_proc n nm :=\n    match n with\n    | 0 => fun p => match p with end\n    | S m => fun p => sm_or_sm p\n    end.\n\n  Definition incr_pred_n_nproc {n} (p : n_nproc (pred n)) : n_nproc n :=\n    match p with\n    | MkPProc m q =>\n      MkPProc m (incr_pred_n_proc q)\n    end.\n\n  Definition incr_pred_n_procs {n} (ps : n_procs (pred n)) : n_procs n :=\n    map incr_pred_n_nproc ps.\n\n  Definition update_state {n} {cn} (sm : n_proc_at n cn) (s : sf cn) : n_proc_at n cn :=\n    MkMPSM\n      (sm_update sm)\n      s.\n\n  (* lift form state to state machine; here x is sub-component with state and output*)\n  Definition app_n_proc_at {n} {nm}\n             (sm : n_proc_at n nm)\n             (i  : cio_I (fio nm))\n    : M_n n (option (n_proc_at n nm) * cio_O (fio nm)) :=\n    (sm_update sm (sm_state sm) i)\n      >>>=\n      fun ops o => ret _ (option_map (update_state sm) ops, o).\n\n  Definition lift_M_O {m} {nm} {O}\n             (x : M_n m (n_proc_at m nm * O))\n    : M_n m (n_proc (S m) nm * O) :=\n    x >>>= fun q o => ret _ (at2sm q, o).\n\n(*  Definition lift_M {m} {nm} (x : M_p (n_proc m) (n_proc_at m nm))\n    : M_n m (n_proc (S m) nm) :=\n    x >>= fun q => ret _ (at2sm q).*)\n\n  (* Part of the monad *)\n  Definition M_on_pred {n} {O} (m : M_n (pred n) O) : M_n n O :=\n    fun (ps : n_procs n) =>\n      let (ps', o') := m (decr_n_procs ps)\n      in (incr_pred_n_procs ps', o').\n\n  Definition lift_M_O2 {n} {nm} {O} (m : M_n (pred n) (n_proc n nm * O))\n    : M_n n (n_proc (S n) nm * O) :=\n    M_on_pred m >>>= fun sm o => ret _ (incr_n_proc sm,o).\n\n  Definition lift_M2 {n} {nm} (m : M_n (pred n) (n_proc n nm))\n    : M_n n (n_proc (S n) nm) :=\n    M_on_pred m >>= fun sm => ret _ (incr_n_proc sm).\n\n(*  (* replace subprocess *)\n  Fixpoint replace_sub {n} {nm}\n           (ps : n_procs n)\n           (p  : n_proc n nm) : n_procs n :=\n    match ps with\n    | [] => []\n    | MkPProc m q :: rest =>\n      if CompNameDeq nm m then MkPProc nm p :: rest\n      else MkPProc m q :: replace_sub rest p\n    end.\n\n  (* replace subprocesses in a list: copy from [l] into [ps] *)\n  Fixpoint replace_subs {n} (ps : n_procs n) (l : n_procs n) : n_procs n :=\n    match l with\n    | [] => ps\n    | p :: rest =>\n      match p with\n      | MkPProc nm q => replace_subs (replace_sub ps q) rest\n      end\n    end.*)\n\n  Fixpoint remove_name {n}\n           (ps : n_procs n)\n           (cn : CompName) : n_procs n :=\n    match ps with\n    | [] => []\n    | p :: rest =>\n      if CompNameDeq cn (pp_name p) then rest\n      else p :: remove_name rest cn\n    end.\n\n  (* removes subprocesses in a list: removes [l] from [ps] *)\n  Fixpoint remove_names {n} (ps : n_procs n) (l : list CompName) : n_procs n :=\n    match l with\n    | [] => ps\n    | cn :: rest => remove_names (remove_name ps cn) rest\n    end.\n\n  Definition get_names {n} (l : n_procs n) : list CompName :=\n    map (fun p => pp_name p) l.\n\n  Definition remove_subs {n m} (ps : n_procs n) (l : n_procs m) : n_procs n :=\n    remove_names ps (get_names l).\n\n  (* NOTE: The order is going to be preserved if the components\n     are ordered in decreasing order of level *)\n  Definition update_subs {n} (ps : n_procs (S n)) (ps' : n_procs n) : n_procs (S n) :=\n    remove_subs ps ps' ++ incr_n_procs ps'.\n\n  (* Part of the monad *)\n  Definition M_on_decr {n} {O} (m : M_n n O) : M_n (S n) O :=\n    fun (ps : n_procs (S n)) =>\n      let (ps', o') := m (decr_n_procs ps)\n      in (update_subs ps ps', o').\n\n  Fixpoint sm2level {n} {nm} : n_proc n nm -> nat :=\n    match n return n_proc n nm -> nat with\n    | 0 => fun p => match p with end\n    | S m => fun p =>\n               match p with\n               | sm_or_at q => m\n               | sm_or_sm q => sm2level q\n               end\n    end.\n\n  Fixpoint M_on_sm {n} {cn} {A} :\n    forall (sm : n_proc n cn) (f : n_proc_at (sm2level sm) cn -> M_n (sm2level sm) A), M_n n A :=\n    match n with\n    | 0 => fun sm f => match sm with end\n    | S n =>\n      fun sm =>\n        match sm with\n        | sm_or_at p => fun f => M_on_decr (f p)\n        | sm_or_sm q => fun f => M_on_decr (M_on_sm q f)\n        end\n    end.\n\n(*  Definition lift_sm_O {m} {nm} {O}\n             (x : M_n m (n_proc_at m nm * O))\n    : M_n m (n_proc m nm * O) :=\n    x >>>= fun q o => ret _ (at2sm q, o).*)\n\n  Definition lift_M_1 {m} {nm} {O}\n             (x : M_n m (option (n_proc_at m nm) * O))\n    : M_n (S m) (option (n_proc (S m) nm) * O) :=\n    M_on_decr x >>>= fun q o => ret _ (option_map at2sm q, o).\n\n  Definition lift_M_2 {n} {nm} {O} (m : M_n n (option (n_proc n nm) * O))\n    : M_n (S n) (option (n_proc (S n) nm) * O) :=\n    M_on_decr m >>>= fun sm o => ret _ (option_map incr_n_proc sm,o).\n\n  Fixpoint app_m_proc {n} {nm}\n    : n_proc n nm\n      -> cio_I (fio nm)\n      -> M_n n (option (n_proc n nm) * cio_O (fio nm)) :=\n    match n return n_proc n nm -> cio_I (fio nm) -> M_n n (option (n_proc n nm) * cio_O (fio nm)) with\n    | 0 =>\n      fun pr i => match pr with end\n    | S m =>\n      fun pr i =>\n        match pr with\n        | sm_or_at sm => lift_M_1 (app_n_proc_at sm i)\n        | sm_or_sm pr' => lift_M_2 (app_m_proc pr' i)\n        end\n    end.\n\n  Fixpoint replace_name {n:nat} {nm : CompName} (pr : n_proc n nm) (l : n_procs n) : n_procs n :=\n    match l with\n    | [] => []\n    | MkPProc m q :: rest =>\n      if CompNameDeq m nm then MkPProc nm pr :: rest\n      else MkPProc m q :: replace_name pr rest\n    end.\n\n  Definition replace_name_op {n:nat} {cn : CompName} (o : option (n_proc n cn)) (l : n_procs n) : n_procs n :=\n    match o with\n    | Some p => replace_name p l\n    | None => remove_name l cn\n    end.\n\n  Definition call_proc {n:nat} (nm : CompName) (i : cio_I (fio nm)) : M_n n (cio_O (fio nm)) :=\n    fun (l : n_procs n) =>\n      match find_name nm l with\n      | Some pr =>\n        match app_m_proc pr i l with\n        | (l',(pr',o)) => (replace_name_op pr' l',o)\n        end\n      | None => (l,cio_default_O (fio nm))\n      end.\n\n  (* We had to break the abstraction because Coq didn't like [build_m_process]. *)\n  Definition build_mp_sm {n}\n             {nm  : CompName}\n             (upd : M_Update n nm (sf nm))\n             (s   : sf nm) : n_proc_at n nm :=\n    MkMPSM upd s.\n\n  Definition build_m_sm {n}\n             {nm  : CompName}\n             (upd : M_Update n nm (sf nm))\n             (s   : sf nm) : n_proc (S n) nm :=\n    at2sm (build_mp_sm upd s).\n\n  (*Fixpoint run_n_proc {n} {nm} (p : n_proc n nm) (l : list (cio_I (fio nm)))\n    : M_n n (list (cio_O (fio nm)) * n_proc n nm) :=\n    match l with\n    | [] => ret _ ([], p)\n    | i :: rest =>\n      (app_m_proc p i)\n        >>>= fun p' o =>\n               (run_n_proc p' rest)\n                 >>>= fun outs p'' => ret _ (o :: outs, p'')\n    end.*)\n\n(*  (* extracts the type of states by going down a state machine until an MP machine *)\n  Fixpoint sm2S {n} {nm} : n_proc n nm -> Type :=\n    match n return n_proc n nm -> Type with\n    | 0 => fun p => match p with end\n    | S m => fun p =>\n               match p with\n               | inl q => sm_S q\n               | inr q => sm2S q\n               end\n    end.*)\n\n  Fixpoint sm2state {n} {nm} : forall (sm : n_proc n nm), sf nm :=\n    match n return forall (sm : n_proc n nm), sf nm with\n    | 0 => fun p => match p with end\n    | S m => fun p =>\n               match p with\n               | sm_or_at q => sm_state q\n               | sm_or_sm q => sm2state q\n               end\n    end.\n\n  (*Inductive LSstatus :=\n  | ls_is_ok\n  | ls_is_byz.*)\n\n  (* the [space] is the space of the main component, which should be of kind \"MAIN\" *)\n  Definition LocalSystem\n             (L : CompNameLevel)\n             (S : CompNameSpace) := n_procs L.\n\n  Definition defaultLocalSystem : LocalSystem 0 1 := [].\n\n(*  Definition upd_ls_main {L} {S} (ls : LocalSystem L S) (m : n_proc_at _ _) : LocalSystem L S :=\n    MkLocalSystem\n      m\n      (ls_subs ls)\n      (ls_status ls).\n\n  Definition upd_ls_main_state {L} {S} (ls : LocalSystem L S) (s : sf _) : LocalSystem L S :=\n    MkLocalSystem\n      (update_state (ls_main ls) s)\n      (ls_subs ls)\n      (ls_status ls).\n\n  Definition upd_ls_subs {L} {S} (ls : LocalSystem L S) (ss : n_procs _) : LocalSystem L S :=\n    MkLocalSystem\n      (ls_main ls)\n      ss\n      (ls_status ls).*)\n\n  Definition is_trusted {n} (comp : n_nproc n) : bool :=\n    comp_name_trust (pp_name comp).\n\n  Fixpoint remove_non_trusted {n} (l : n_procs n) : n_procs n :=\n    match l with\n    | [] => []\n    | comp :: rest =>\n      if is_trusted comp then comp :: remove_non_trusted rest\n      else remove_non_trusted rest\n    end.\n\n(*  Definition upd_ls_byz {L} {S} (ls : LocalSystem L S) : LocalSystem L S :=\n    MkLocalSystem\n      (ls_main ls) (* the main component becomes useless now *)\n      (remove_non_trusted (ls_subs ls))\n      ls_is_byz.*)\n\n(*  Definition upd_ls_main_state_and_subs\n             {L} {S}\n             (ls : LocalSystem L S)\n             (s  : sf _)\n             (ss : n_procs _) : LocalSystem _ _ :=\n    MkLocalSystem\n      (update_state (ls_main ls) s)\n      ss\n      (ls_status ls).*)\n\n(*  Definition if_ls_is_ok_opt {L S} (ls : LocalSystem L S) {A} (a : option A) : option A :=\n    match ls_status ls with\n    | ls_is_ok => a\n    | ls_is_byz => None\n    end.*)\n\n(*  Record message_local_system_constraint (s : LocalSystem) :=\n    MkMessageLocalSystemConstratin\n      {\n        mlsc_I : cio_I (fio (projT1 (ls_main s))) = msg;\n        mlsc_O : cio_O (fio (projT1 (ls_main s))) = DirectedMsgs;\n      }.*)\n\n  (*Definition run_local_system (s : LocalSystem) (l : list (cio_I (fio msg_comp_name))) :=\n    run_n_proc (ls_main s) l (ls_subs s).*)\n\n  (*Definition M_NStateMachine (nm : CompName) (n : nat) := name -> n_proc n nm.*)\n\n  Record funLevelSpace :=\n    MkFunLevelSpace\n      {\n        fls_level : name -> CompNameLevel;\n        fls_space : name -> CompNameSpace;\n      }.\n\n  Definition M_USystem (F : funLevelSpace) :=\n    forall (n : name), LocalSystem (fls_level F n) (fls_space F n).\n\n(*  Definition message_system_constraint (sys : M_USystem) :=\n    forall nm, message_local_system_constraint (sys nm).*)\n\n  (* This is a system with a constraint that the main component takes in messages\n     and outputs directed messages *)\n(*  Record M_MUSystem :=\n    MkMMUSystem\n      {\n        msys_sys  :> M_USystem;\n        msys_cond : message_system_constraint msys_sys;\n      }.*)\n\n  Definition M_on_some\n             {n A B}\n             (f : A -> M_n n (option B))\n             (xop : option A) : M_n n (option B) :=\n    match xop with\n    | Some a => f a\n    | None => ret _ None\n    end.\n\n  Notation \"a >>o>> f\" := (M_on_some f a) (at level 80).\n\n  Definition bind_some {A B} {n:nat}\n             (m : M_n n (option A))\n             (f : A -> M_n n (option B)) : M_n n (option B) :=\n    m >>= fun x => x >>o>> f.\n\n  Notation \"a >>o= f\" := (bind_some a f) (at level 80).\n\n  Definition M_op_update {S} {n} {nm}\n             (upd : M_Update n nm S)\n             (s   : S)\n             (o   : option (cio_I (fio nm)))\n    : M_n n (option (option S * cio_O (fio nm))) :=\n    o >>o>> (fun i => (upd s i) >>= fun so => ret _ (Some so)).\n\n  Definition M_op_state {S} {n} {nm}\n             (upd : M_Update n nm S)\n             (s   : S)\n             (o   : option (cio_I (fio nm)))\n    : M_n n (option S) :=\n    o >>o>> (fun i => (upd s i) >>= fun so => ret _ (fst so)).\n\n  (* never used\n  Definition M_op_op_update {S} {n} {nm}\n             (upd : M_Update n nm S)\n             (s   : S)\n             (o   : option (cio_I (fio nm)))\n    : option (M_n n (option S * cio_O (fio nm))) :=\n    match o with\n    | Some i => Some (upd s i)\n    | None => None\n    end.\n\n  Definition M_op_sm_update {n} {nm}\n             (sm  : n_proc n nm)\n             (iop : option (cio_I (fio nm)))\n    : M_n (pred n) (option (n_proc n nm * cio_O (fio nm))) :=\n    match iop with\n    | Some i => match app_m_proc sm i with\n                | Some x => x >>= fun x => ret _ (Some x)\n                | None => ret _ None\n                end\n    | None => ret _ None\n    end. *)\n\n  (* Note: the monad is taking care of calling the lower levels *)\n  (* TODO: We currently return None either if the input is unavailable or\n       if the machine stops.  We should distinguish the 2. *)\n(*  Fixpoint M_run_update_on_list {S} {n} {nm}\n           (s   : S)\n           (upd : M_Update n nm S)\n           (l   : oplist (cio_I (fio nm))) : M_n n (option S) :=\n    match l with\n    | [] => ret _ (Some s)\n    | aop :: l =>\n      aop >>o>>\n          fun a =>\n            (upd s a) >>= fun so =>\n                            (fst so) >>o>>\n                                     fun s' => M_run_update_on_list s' upd l\n    end.*)\n\n(*  Definition sm2update {n} {cn} : forall (sm : n_proc n cn), MP_Update (n_proc (sm2level sm)) (cio_I (fio cn)) (cio_O (fio cn)) (sm2S sm).\n  Proof.\n    induction n; introv; simpl in *.\n\n    - destruct sm.\n\n    - destruct sm; simpl in *.\n\n      + exact (sm_update m).\n\n      + apply IHn.\n  Qed.*)\n\n  Fixpoint sm2update {n} {cn}\n    : forall (sm : n_proc n cn), M_Update (sm2level sm) cn (sf cn) :=\n    match n with\n    | 0 => fun sm => match sm with end\n    | S m => fun sm =>\n               match sm with\n               | sm_or_at q => sm_update q\n               | sm_or_sm q => sm2update q\n               end\n    end.\n\n(*  Definition M_run_sm_on_inputs {n} {nm}\n             (sm : n_proc n nm)\n             (l  : oplist (cio_I (fio nm))) : M_n n (option (sf nm)) :=\n    M_on_sm\n      sm\n      (fun p => M_run_update_on_list (sm_state p) (sm_update p) l).*)\n\n  Definition M_run_sm_on_input {n} {nm}\n             (sm : n_proc n nm)\n             (i  : cio_I (fio nm)) : M_n n (option (sf nm) * cio_O (fio nm)) :=\n    M_on_sm\n      sm\n      (fun p => (sm_update p (sm_state p) i)).\n\n  Definition M_fst {n} {A} {B} (m : M_n n (A * B)) : M_n n A :=\n    m >>= fun so => ret _ (fst so).\n\n  Definition M_snd {n} {A} {B} (m : M_n n (A * B)) : M_n n B :=\n    m >>= fun so => ret _ (snd so).\n\n(*  Fixpoint M_run_sm_on_list_p {n} {nm}\n           (sm : n_proc n nm)\n           (l  : oplist (cio_I (fio nm))) : M_n (pred n) (option (n_proc n nm)) :=\n    match l with\n    | [] => ret _ (Some sm)\n    | aop :: l =>\n      aop >>o>> fun a =>\n                  (app_m_proc sm a)\n                    >>o>> fun f => f >>= fun so => M_run_sm_on_list_p (fst so) l\n    end.*)\n\n  (* never used\n  Definition lift_M3 {n} {O} (m : M_n (pred n) O)\n    : M_n (pred (S n)) O :=\n    fun (ps : n_procs n) =>\n      match m (decr_n_procs ps) with\n      | (ps',o) => (incr_pred_n_procs ps', o)\n      end.\n\n  Fixpoint app_m_proc_state {n} {nm}\n    : forall (sm : n_proc n nm),\n      cio_I (fio nm)\n      -> option (M_n (pred n) (option (sm2S sm) * cio_O (fio nm))) :=\n    match n return forall (sm : n_proc n nm), cio_I (fio nm) -> option (M_n (pred n) (option (sm2S sm) * cio_O (fio nm))) with\n    | 0 =>\n      fun pr i =>\n        (*Some (lift_M (sm_s_to_sm pr (sm_update pr (sm_state pr) i)))*)\n        None\n    | S m =>\n      fun pr =>\n        match pr with\n        | inl sm => fun i => Some (sm_update sm (sm_state sm) i)\n        | inr pr' => fun i => option_map lift_M3 (app_m_proc_state pr' i)\n        end\n    end.\n   *)\n\n  (*Fixpoint M_run_sm_on_list_state {n} {nm}\n           (sm : n_proc n nm)\n           (l  : oplist (cio_I (fio nm))) : M_n (pred n) (option (sm2S sm)) :=\n    match l with\n    | [] => ret _ (Some (sm2state sm))\n    | Some a :: l =>\n      match app_m_proc_state sm a with\n      | Some f => f >>= fun so => let (sm',_) := so in M_run_sm_on_list_state sm' l\n      | None => ret _ None\n      end\n    | None :: _ => ret _ None\n    end.*)\n\n\n  Definition op_state_out (S : Type) := option (option S * DirectedMsgs).\n\n(*  Definition M_run_update_on_event {S} {n} {k}\n             (s    : S)\n             (upd  : M_Update n (main_comp_name k) S)\n             {eo   : EventOrdering}\n             (e    : Event) : M_n n (op_state_out S) :=\n    (M_run_update_on_list s upd (map trigger_op (@localPreds pn pk pm _ _ eo e)))\n      >>o= fun s => M_op_update upd s (trigger_op e).*)\n\n(*  Definition M_run_sm_on_event {n} {k}\n             (sm : n_proc n (main_comp_name k))\n             {eo : EventOrdering}\n             (e  : Event) : M_n n (op_state_out (sf (main_comp_name k))) :=\n    M_on_sm sm (fun p => M_run_update_on_event (sm_state p) (sm_update p) e).*)\n\n  (*Definition M_run_sm_on_event {n} {k}\n             (sm : n_proc n (main_comp_name k))\n             {eo : EventOrdering}\n             (e  : Event) : M_n (sm2level sm) (op_state_out (sf (main_comp_name k))) :=\n    M_run_update_on_event (sm2state sm) (sm2update sm) e.*)\n\n(*  Definition M_state_sm_on_event {n} {k}\n             (sm : n_proc n (main_comp_name k))\n             {eo : EventOrdering}\n             (e  : Event) : M_n n (option (sf (main_comp_name k))) :=\n  (M_run_sm_on_event sm e)\n    >>o= fun p => ret _ (fst p).*)\n\n(*  Definition M_state_sm_before_event {n} {k}\n             (sm : n_proc n (main_comp_name k))\n             {eo : EventOrdering}\n             (e  : Event) : M_n n (option (sf (main_comp_name k))) :=\n    M_run_sm_on_inputs sm (map trigger_op (@localPreds pn pk pm _ _ eo e)).*)\n\n\n\n  (******************************************)\n  (* *** state of local system on event *** *)\n  (******************************************)\n\n  Fixpoint update_state_m {n} {cn} :\n    forall (sm : n_proc n cn)\n           (s  : sf cn), n_proc n cn :=\n    match n with\n    | 0 => fun sm s => match sm with end\n    | S m =>\n      fun sm s =>\n        match sm with\n        | sm_or_at p => sm_or_at (update_state p s)\n        | sm_or_sm q => sm_or_sm (update_state_m q s)\n        end\n    end.\n\n  Lemma n_procs_to_level_update_state_sm\n        {lvl} {cn}\n        {p : n_proc lvl cn}\n        (s : sf cn)\n        (l : n_procs (sm2level p)) : n_procs (sm2level (update_state_m p s)).\n  Proof.\n    induction lvl; simpl in *; auto; destruct p; auto.\n  Defined.\n\n  Definition M_break {n} {S} {O}\n             (sm   : M_n n S)\n             (subs : n_procs n)\n             (F    : n_procs n -> S -> O) : O :=\n    let (subs', out) := sm subs in F subs' out.\n\n  (* by default main components are not trusted *)\n\n  (* m : missing *)\n  Definition on_comp {n}\n             (l : n_procs n)\n             {cn} {A}\n             (f : n_proc n cn -> A) (m : A) :  A :=\n    match find_name cn l with\n    | Some comp => f comp\n    | None => m\n    end.\n\n  (* m <= n *)\n  Fixpoint select_n_proc {n} {cn} m : n_proc n cn -> option (n_proc m cn) :=\n    match deq_nat n m with\n    | left q => fun p => Some (eq_rect _ (fun n => n_proc n cn) p _ q)\n    | right q =>\n      match n with\n      | 0 => fun p => match p with end\n      | S k =>\n        fun p =>\n          match p with\n          | sm_or_at q => None\n          | sm_or_sm q => select_n_proc m q\n          end\n      end\n    end.\n\n  Definition select_n_nproc {n} m (p : n_nproc n) : option (n_nproc m) :=\n    match p with\n    | MkPProc cn p => option_map (MkPProc cn) (select_n_proc m p)\n    end.\n\n  Definition select_n_procs {n} m (ps : n_procs n) : n_procs m :=\n    mapOption (select_n_nproc m) ps.\n\n  Fixpoint lift_n_proc {n} {cn} j : n_proc n cn -> n_proc (j + n) cn :=\n    match j with\n    | 0 => fun p => p\n    | S k => fun p => incr_n_proc (lift_n_proc k p)\n    end.\n\n  Definition lift_n_nproc {n} j (p : n_nproc n) : n_nproc (j + n) :=\n    match p with\n    | MkPProc cn p => MkPProc cn (lift_n_proc j p)\n    end.\n\n  Definition lift_n_procs {n} j (l : n_procs n) : n_procs (j + n) :=\n    map (lift_n_nproc j) l.\n\n  Lemma select_n_proc_trivial :\n    forall {n} {cn} (p : n_proc n cn),\n      select_n_proc n p = Some p.\n  Proof.\n    introv.\n    destruct n; simpl; auto;[].\n    destruct (deq_nat n n); simpl; tcsp.\n    pose proof (UIP_refl_nat _ e) as q; subst; simpl; auto.\n  Qed.\n  Hint Rewrite @select_n_proc_trivial : comp.\n\n  Lemma select_n_procs_trivial :\n    forall {n} (subs : n_procs n),\n      select_n_procs n subs = subs.\n  Proof.\n    introv; unfold select_n_procs.\n    induction subs; simpl; auto.\n    rewrite IHsubs.\n    destruct a; simpl in *.\n    autorewrite with comp; simpl; auto.\n  Qed.\n  Hint Rewrite @select_n_procs_trivial : comp.\n\n  Lemma lift_n_procs_0 :\n    forall {n} (subs : n_procs n),\n      lift_n_procs 0 subs = subs.\n  Proof.\n    introv; unfold lift_n_procs.\n    induction subs; simpl in *; tcsp.\n    rewrite IHsubs.\n    destruct a; simpl; auto.\n  Qed.\n  Hint Rewrite @lift_n_procs_0 : comp.\n\n  Lemma mapOption_fun_Some :\n    forall {A} (l : list A),\n      mapOption (fun p => Some p) l = l.\n  Proof.\n    induction l; simpl; auto.\n    rewrite IHl; auto.\n  Qed.\n  Hint Rewrite @mapOption_fun_Some : list.\n\n  Lemma mapOption_fun_None :\n    forall {A B} (l : list A),\n      mapOption (fun _ => @None B) l = [].\n  Proof.\n    induction l; simpl; auto.\n  Qed.\n  Hint Rewrite @mapOption_fun_None : list.\n\n  Lemma select_n_proc_lt :\n    forall cn n m (p : n_proc n cn),\n      n < m\n      -> select_n_proc m p = None.\n  Proof.\n    induction n; introv ltm; simpl in *; tcsp.\n    destruct p as [p|p]; simpl in *.\n\n    { destruct m; try omega.\n      destruct (deq_nat n m); subst; try omega; auto. }\n\n    destruct m; try omega.\n    destruct (deq_nat n m); subst; try omega; auto.\n    apply IHn; auto; try omega.\n  Qed.\n\n  Lemma select_n_proc_S_sm_implies :\n    forall cn n m (p : n_proc n cn) (q : n_proc m cn),\n      select_n_proc (S m) p = Some (sm_or_sm q)\n      -> select_n_proc m p = Some q.\n  Proof.\n    induction n; introv sel; simpl in *; tcsp.\n    fold M_StateMachine in *.\n    fold n_proc in *.\n    destruct m; simpl.\n\n    { destruct (deq_nat n 0); subst; simpl in *; tcsp. }\n\n    destruct (deq_nat n (S m)); subst.\n\n    { simpl in sel; inversion sel; subst.\n      destruct (deq_nat (S m) m); try omega.\n      simpl.\n      destruct (deq_nat m m); try omega.\n      pose proof (UIP_refl_nat _ e) as w; subst; simpl; auto. }\n\n    destruct p; ginv.\n    destruct (deq_nat n m); subst; tcsp;[|].\n\n    { rewrite select_n_proc_lt in sel; ginv; try omega. }\n\n    apply IHn in sel; auto.\n  Qed.\n\n  Lemma select_n_proc_select_n_proc_le :\n    forall cn k n m (p : n_proc k cn) q r,\n      n <= m\n      -> select_n_proc m p = Some q\n      -> select_n_proc n q = Some r\n      -> select_n_proc n p = Some r.\n  Proof.\n    induction k; introv le sela selb; simpl in *; tcsp;[].\n    destruct m; simpl in *; tcsp;[].\n    destruct n; simpl in *; tcsp;[].\n    destruct (deq_nat k m); subst; ginv;[].\n    destruct p as [p|p]; ginv;[].\n    destruct (deq_nat m n); subst; ginv; try omega;[|].\n\n    { destruct (deq_nat k n); subst; try omega; auto. }\n\n    destruct q as [q|q]; ginv;[].\n    destruct (deq_nat k n); subst; try omega; auto.\n\n    { simpl in *.\n      apply select_n_proc_S_sm_implies in sela.\n      pose proof (IHk (S n) m p q r) as IHk.\n      repeat (autodimp IHk hyp); try omega;[].\n      destruct r.\n      { rewrite select_n_proc_lt in IHk; ginv; try omega. }\n      apply select_n_proc_S_sm_implies in IHk.\n      rewrite select_n_proc_trivial in IHk.\n      inversion IHk; auto. }\n\n    { apply select_n_proc_S_sm_implies in sela.\n      pose proof (IHk (S n) m p q r) as IHk.\n      repeat (autodimp IHk hyp); try omega. }\n  Qed.\n\n  Lemma select_n_proc_some_at_implies :\n    forall cn k n m (p : n_proc k cn) (q : n_proc_at m cn),\n      n <= m\n      -> select_n_proc (S m) p = Some (sm_or_at q)\n      -> select_n_proc n p = None.\n  Proof.\n    induction k; introv lem sel; simpl in *; tcsp;[].\n    destruct (deq_nat k m); subst.\n\n    { simpl in *; inversion sel; subst; simpl in *; clear sel.\n      destruct n; auto.\n      destruct (deq_nat m n); subst; auto; try omega. }\n\n    destruct p; ginv.\n    destruct n.\n\n    { eapply IHk; eauto. }\n\n    destruct (deq_nat k n); subst; try omega; simpl; auto.\n\n    { rewrite select_n_proc_lt in sel; try omega; ginv. }\n\n    pose proof (IHk (S n) m b q) as IHk.\n    repeat (autodimp IHk hyp).\n  Qed.\n\n  Lemma select_n_proc_select_n_proc_le2 :\n    forall cn k n m (p : n_proc k cn) q,\n      n <= m\n      -> select_n_proc m p = Some q\n      -> select_n_proc n q = None\n      -> select_n_proc n p = None.\n  Proof.\n    induction k; introv le sela selb; simpl in *; tcsp;[].\n    destruct m; simpl in *; tcsp;[].\n    destruct n; simpl in *; tcsp;[|].\n\n    { destruct (deq_nat k m); subst; ginv;[].\n      destruct p; ginv;[].\n      destruct q; ginv.\n      { clear IHk.\n        destruct k; simpl in *; tcsp.\n        destruct (deq_nat k m); subst; try omega; ginv; auto.\n        destruct b; ginv.\n        pose proof (select_n_proc_some_at_implies cn k 0 m b a) as w.\n        repeat (autodimp w hyp); try omega. }\n      apply select_n_proc_S_sm_implies in sela.\n      pose proof (IHk 0 m b b0) as IHk.\n      repeat (autodimp IHk hyp); try omega. }\n\n    destruct (deq_nat k m); subst; try omega; ginv;[].\n    destruct (deq_nat m n); subst; try omega; ginv;[].\n    destruct (deq_nat k n); subst; try omega; ginv.\n\n    { simpl.\n      destruct p; ginv.\n      rewrite select_n_proc_lt in sela; try omega; ginv. }\n\n    destruct p; ginv;[].\n    destruct q; ginv.\n\n    { pose proof (select_n_proc_some_at_implies cn k (S n) m b a) as w.\n      repeat (autodimp w hyp); try omega. }\n\n    pose proof (IHk (S n) (S m) b (sm_or_sm b0)) as IHk.\n    repeat (autodimp IHk hyp).\n    simpl.\n    destruct (deq_nat m n); try omega; auto.\n  Qed.\n\n  Lemma select_n_proc_none_implies :\n    forall cn k n m (p : n_proc k cn),\n      m <= k\n      -> n <= m\n      -> select_n_proc m p = None\n      -> select_n_proc n p = None.\n  Proof.\n    induction k; introv lek lem sel; simpl in *; tcsp;[].\n    destruct m; simpl in *; tcsp.\n\n    { destruct n; auto; try omega. }\n\n    destruct n; simpl in *; tcsp;[|].\n\n    { destruct (deq_nat k m); subst; ginv;[].\n      destruct p; ginv; auto;[].\n      pose proof (IHk 0 (S m) b) as IHk.\n      repeat (autodimp IHk hyp); try omega. }\n\n    destruct (deq_nat k m); subst; try omega; ginv;[].\n    destruct (deq_nat k n); subst; try omega; ginv.\n\n    { simpl.\n      destruct p; ginv; auto.\n      pose proof (IHk (S n) (S m) b) as IHk; repeat (autodimp IHk hyp); try omega. }\n  Qed.\n\n  Lemma select_n_procs_select_n_procs_le :\n    forall n m k (subs : n_procs k),\n      m <= k\n      -> n <= m\n      -> select_n_procs n (select_n_procs m subs)\n         = select_n_procs n subs.\n  Proof.\n    unfold select_n_procs.\n    induction subs; introv ltk lem; simpl in *; auto.\n    repeat (autodimp IHsubs hyp).\n    destruct a as [cn p]; simpl.\n    remember (select_n_proc m p) as w; symmetry in Heqw; destruct w; simpl.\n\n    { remember (select_n_proc n n0) as z; symmetry in Heqz; destruct z; simpl.\n\n      { pose proof (select_n_proc_select_n_proc_le cn k n m p n0 n1) as q.\n        repeat (autodimp q hyp);[].\n        rewrite q; simpl.\n        rewrite IHsubs; auto. }\n\n      rewrite IHsubs.\n      pose proof (select_n_proc_select_n_proc_le2 cn k n m p n0) as q.\n      repeat (autodimp q hyp).\n      rewrite q; simpl; auto. }\n\n    rewrite IHsubs; clear IHsubs.\n\n    remember (select_n_proc n p) as z; symmetry in Heqz; destruct z; simpl; auto;[].\n    pose proof (select_n_proc_none_implies cn k n m p) as q.\n    repeat (autodimp q hyp); try omega.\n    rewrite q in Heqz; ginv.\n  Qed.\n\n  Lemma select_n_nproc_succ :\n    forall {cn} {k} (p : n_proc (S k) cn),\n      select_n_proc k p\n      = match p with\n        | sm_or_at q => None\n        | sm_or_sm q => Some q\n        end.\n  Proof.\n    introv.\n    unfold select_n_proc.\n    destruct (deq_nat (S k) k); try omega.\n    destruct p; auto.\n    destruct k.\n    { simpl; auto. }\n    destruct (deq_nat (S k) (S k)); auto; try omega.\n    pose proof (UIP_refl_nat _ e) as w; subst; simpl; auto.\n  Qed.\n\n  Lemma decr_n_procs_as_select_n_procs :\n    forall {k} (subs : n_procs (S k)),\n      decr_n_procs subs = select_n_procs k subs.\n  Proof.\n    introv; simpl.\n    unfold decr_n_procs, select_n_procs.\n    induction subs; simpl; auto.\n    destruct a as [cn p].\n    unfold select_n_nproc at 1.\n    rewrite select_n_nproc_succ.\n    simpl.\n    destruct p; simpl in *; auto.\n    unfold n_procs in *; rewrite IHsubs; auto.\n  Qed.\n\n  Definition M_run_ls_on_input\n             {n}\n             (ls : n_procs n)\n             cn\n             (i  : cio_I (fio cn)) : n_procs n * option (cio_O (fio cn)) :=\n    on_comp\n      ls\n      (fun main =>\n         M_break\n           (M_run_sm_on_input main i)\n           ls\n           (fun subs out =>\n              (match fst out with\n               | Some s => replace_name (update_state_m main s) subs\n               | None => remove_name subs cn\n               end,\n               Some (snd out))))\n      (* We simply return the local system if we cannot find the component *)\n      (ls, None).\n\n  Definition to_snd_default\n             {A} {cn}\n             (x : A * option (cio_O (fio cn))) : A * cio_O (fio cn) :=\n    match x with\n    | (a, Some o) => (a,o)\n    | (a, None) => (a,cio_default_O _)\n    end.\n\n  Lemma UIP_refl_CompName :\n    forall (n : CompName) (x : n = n), x = eq_refl.\n  Proof.\n    introv; apply UIPReflDeq; auto.\n    apply CompNameDeq.\n  Qed.\n\n  Lemma UIP_refl_CompNameKind :\n    forall (k : CompNameKind) (x : k = k), x = eq_refl.\n  Proof.\n    introv; apply UIPReflDeq; auto.\n    apply CompNameKindDeq.\n  Qed.\n\n  Lemma UIP_refl_CompNameSpace :\n    forall (s : CompNameSpace) (x : s = s), x = eq_refl.\n  Proof.\n    introv; apply UIPReflDeq; auto.\n    apply CompNameSpaceDeq.\n  Qed.\n\n  Lemma UIP_refl_CompNameState :\n    forall (s : CompNameState) (x : s = s), x = eq_refl.\n  Proof.\n    introv; apply UIPReflDeq; auto.\n    apply CompNameStateDeq.\n  Qed.\n\n  Lemma implies_find_name_decr_n_procs :\n    forall {cn} {n} (l : n_procs (S n)) (b : n_proc n cn),\n      find_name cn l = Some (sm_or_sm b)\n      -> find_name cn (decr_n_procs l) = Some b.\n  Proof.\n    induction l; introv h; simpl in *; tcsp.\n    destruct a as [cn' p']; simpl in *; dest_cases w; subst; simpl in *; ginv.\n\n    { inversion h; subst; simpl in *; clear h; dest_cases w.\n      rewrite (UIP_refl_CompName _ w); simpl; auto. }\n\n    {apply IHl in h; clear IHl; unfold decr_n_procs in *; simpl in *.\n     destruct p'; simpl in *; tcsp; dest_cases w. }\n  Qed.\n\n  Definition nested2state\n             {A} {n} {cn} {B}\n             (x : A * (option (n_proc n cn) * B)) : A * (option (sf cn) * B) :=\n    match x with\n    | (a, (pop, b)) => (a,(option_map sm2state pop,b))\n    end.\n\n  Lemma app_m_proc_as_M_on_sm :\n    forall {n} {cn} (p : n_proc n cn) i (l : n_procs n),\n      nested2state (app_m_proc p i l)\n      = M_on_sm p (fun a => sm_update a (sm_state a) i) l.\n  Proof.\n    induction n; introv; simpl in *; tcsp.\n    destruct p; simpl in *; tcsp.\n\n    { unfold lift_M_1, app_n_proc_at, bind_pair, bind, M_on_decr; simpl.\n      remember (sm_update a (sm_state a) i (decr_n_procs l)) as u; symmetry in Hequ; repnd; simpl in *.\n      destruct u1; simpl in *; tcsp. }\n\n    unfold lift_M_2, bind_pair, bind, M_on_decr; simpl.\n    pose proof (IHn cn b i (decr_n_procs l)) as IHn.\n    rewrite <- IHn; clear IHn.\n    remember (app_m_proc b i (decr_n_procs l)) as u; symmetry in Hequ; repnd; simpl in *.\n    f_equal.\n    f_equal.\n    destruct u1; simpl; tcsp.\n  Qed.\n\n  Lemma update_state_if_app_m_proc :\n    forall {n} {cn} (p : n_proc n cn) i l k q o,\n      app_m_proc p i l = (k, (Some q, o))\n      -> update_state_m p (sm2state q) = q.\n  Proof.\n    induction n; introv h; simpl in *; tcsp.\n    destruct p; simpl in *; tcsp.\n\n    { unfold lift_M_1, bind_pair, bind, M_on_decr in h.\n      remember (app_n_proc_at a i (decr_n_procs l)) as u; symmetry in Hequ; repnd; simpl in *.\n      inversion h; subst; simpl in *; clear h.\n      rename_hyp_with @at2sm h.\n      apply option_map_Some in h; exrepnd; subst; simpl in *.\n      unfold app_n_proc_at, bind_pair, bind in Hequ.\n      remember (sm_update a (sm_state a) i (decr_n_procs l)) as z; symmetry in Heqz.\n      repnd; simpl in *; ginv.\n      inversion Hequ; subst; simpl in *; tcsp; clear Hequ.\n      rename_hyp_with @update_state h.\n      apply option_map_Some in h; exrepnd; subst; simpl in *; tcsp. }\n\n    unfold lift_M_2, bind_pair, bind, M_on_decr in h.\n    remember (app_m_proc b i (decr_n_procs l)) as u; symmetry in Hequ; repnd; simpl in *.\n    inversion h; subst; simpl in *; clear h.\n    rename_hyp_with @option_map h.\n    apply option_map_Some in h; exrepnd; subst; simpl in *.\n    apply IHn in Hequ; rewrite Hequ; auto.\n  Qed.\n\n  (* TODO: I defined a separate [M_run_ls_on_input] to reason about local system, but\n     it's essentially the same as [call_proc]:\n   *)\n  Lemma M_run_ls_on_input_as_call_proc :\n    forall {n}\n           (ls : n_procs n)\n           cn\n           (i  : cio_I (fio cn)),\n      to_snd_default (M_run_ls_on_input ls cn i)\n      = call_proc cn i ls.\n  Proof.\n    introv.\n    unfold M_run_ls_on_input, call_proc, M_run_sm_on_input, LocalSystem, M_break, on_comp in *; simpl in *.\n    dest_cases w; rev_Some.\n    pose proof (app_m_proc_as_M_on_sm w i ls) as q.\n    simpl in *; rewrite <- q; clear q.\n    remember (app_m_proc w i ls) as u; symmetry in Hequ; repnd; simpl in *.\n    f_equal.\n    destruct u1; simpl in *; tcsp.\n    f_equal.\n    apply update_state_if_app_m_proc in Hequ; auto.\n  Qed.\n\n  Definition on_some\n             {A B}\n             (xop : option A)\n             (f : A -> option B) : option B :=\n    map_option f xop.\n\n  Definition M_run_ls_on_input_ls\n             {n}\n             (ls : n_procs n)\n             cn\n             (i  : cio_I (fio cn)) : n_procs n :=\n    fst (M_run_ls_on_input ls cn i).\n\n  Definition M_run_ls_on_input_out\n             {n}\n             (ls : n_procs n)\n             cn\n             (i  : cio_I (fio cn)) : option (cio_O (fio cn)) :=\n    snd (M_run_ls_on_input ls cn i).\n\n  Fixpoint M_run_ls_on_op_inputs\n           {n}\n           (ls : n_procs n)\n           cn\n           (l  : oplist (cio_I (fio cn))) : option (n_procs n) :=\n    match l with\n    | [] => Some ls\n    | mop :: l =>\n      on_some\n        mop\n        (fun m =>\n           let ls' := M_run_ls_on_input_ls ls cn m in\n           M_run_ls_on_op_inputs ls' cn l)\n    end.\n\n  Fixpoint M_run_ls_on_inputs\n           {n}\n           (ls : n_procs n)\n           cn\n           (l  : list (cio_I (fio cn))) : n_procs n :=\n    match l with\n    | [] => ls\n    | m :: l =>\n      let ls' := M_run_ls_on_input_ls ls cn m in\n      M_run_ls_on_inputs ls' cn l\n    end.\n\n  Definition M_run_ls_before_event\n             {L S}\n             (ls : LocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event) : option (LocalSystem L S) :=\n    M_run_ls_on_op_inputs ls (msg_comp_name S) (map trigger_op (@localPreds pn pk pm _ _ eo e)).\n\n  Definition M_run_ls_on_event\n             {L S}\n             (ls : LocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event) : option (LocalSystem L S) :=\n    on_some\n      (M_run_ls_before_event ls e)\n      (fun ls' =>\n         option_map\n           (M_run_ls_on_input_ls ls' (msg_comp_name S))\n           (trigger_op e)).\n\n\n  (*Lemma break_M_run_ls_before_event :\n    forall (ls  : LocalSystem)\n           {eo  : EventOrdering}\n           (e   : Event)\n           (ls' : LocalSystem),\n      M_run_ls_before_event ls e = Some ls'\n      -> exists s,\n        M_state_sm_before_event (n_proc_at2nproc (ls_main ls)) e (ls_subs ls)\n        = (ls_subs ls', Some (sm_state (ls_main ls'))).*)\n\n\n  Definition state_of_component\n             {L}\n             (cn : CompName)\n             (ls : n_procs L) : option (sf cn) :=\n    option_map sm2state (find_name cn ls).\n\n  Definition on_state_of_component\n             {L}\n             (cn : CompName)\n             (ls : n_procs L)\n             (F  : sf cn -> Prop) : Prop :=\n    match state_of_component cn ls with\n    | Some s => F s\n    | None => True\n    end.\n\n  Definition cn2space (cn : CompName) : CompNameSpace :=\n    comp_name_space cn.\n\n  Definition sm2ls {n} {cn} (p : n_proc n cn) : LocalSystem n (cn2space cn) :=\n    [MkPProc cn p].\n\n  Definition M_comp_ls_on_op_inputs {n}\n             (ls : n_procs n)\n             cn\n             (l : oplist (cio_I (fio cn))) : option (n_proc n cn) :=\n    on_some\n      (M_run_ls_on_op_inputs ls cn l)\n      (find_name cn).\n\n  Definition M_comp_ls_on_inputs {n}\n             (ls : n_procs n)\n             cn\n             (l : list (cio_I (fio cn))) : option (n_proc n cn) :=\n    find_name cn (M_run_ls_on_inputs ls cn l).\n\n  Definition M_state_ls_on_op_inputs {n}\n             (ls : n_procs n)\n             cn\n             (l : oplist (cio_I (fio cn))) : option (sf cn) :=\n    on_some\n      (M_run_ls_on_op_inputs ls cn l)\n      (state_of_component cn).\n\n  Definition M_state_ls_on_inputs {n}\n             (ls : n_procs n)\n             cn\n             (l : list (cio_I (fio cn))) : option (sf cn) :=\n    state_of_component cn (M_run_ls_on_inputs ls cn l).\n\n  Lemma M_state_ls_on_op_inputs_as_comp :\n    forall {n}\n           (ls : n_procs n)\n           cn\n           (l : oplist (cio_I (fio cn))),\n      M_state_ls_on_op_inputs ls cn l\n      = option_map\n          sm2state\n          (M_comp_ls_on_op_inputs ls cn l).\n  Proof.\n    introv; unfold M_state_ls_on_op_inputs, M_comp_ls_on_op_inputs.\n    remember (M_run_ls_on_op_inputs ls cn l) as x; destruct x; simpl; auto.\n  Qed.\n\n  Lemma M_state_ls_on_inputs_as_comp :\n    forall {n}\n           (ls : n_procs n)\n           cn\n           (l : list (cio_I (fio cn))),\n      M_state_ls_on_inputs ls cn l\n      = option_map\n          sm2state\n          (M_comp_ls_on_inputs ls cn l).\n  Proof.\n    introv; unfold M_state_ls_on_inputs, M_comp_ls_on_inputs.\n    remember (M_run_ls_on_inputs ls cn l) as x; destruct x; simpl; auto.\n  Qed.\n\n  Definition M_state_ls_on_event\n             {L S}\n             (ls : LocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event)\n             (cn : CompName) : option (sf cn) :=\n    map_option\n      (state_of_component cn)\n      (M_run_ls_on_event ls e).\n\n  Definition M_state_ls_before_event\n             {L S}\n             (ls : LocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event)\n             (cn : CompName) : option (sf cn) :=\n    map_option\n      (state_of_component cn)\n      (M_run_ls_before_event ls e).\n\n  Definition M_state_sys_on_event\n             {F}\n             (sys : M_USystem F)\n             {eo  : EventOrdering}\n             (e   : Event)\n             (cn  : CompName) : option (sf cn) :=\n    M_state_ls_on_event (sys (loc e)) e cn.\n\n  Definition M_state_sys_before_event\n             {F}\n             (sys : M_USystem F)\n             {eo  : EventOrdering}\n             (e   : Event)\n             (cn  : CompName) : option (sf cn) :=\n    M_state_ls_before_event (sys (loc e)) e cn.\n\n(*  Definition M_run_local_system_on_event\n             (ls : LocalSystem)\n             {eo : EventOrdering}\n             (e  : Event) : option LocalSystem :=\n    match ls with\n    | MkLocalSystem lvl space main subs =>\n      match trigger e with\n      | Some i =>\n        let (subs',out) := sm_update main (sm_state main) i subs in\n        let (sop,o) := out in\n        match sop with\n        | Some s => Some (MkLocalSystem lvl space (update_state main s) subs')\n        | None => None\n        end\n      | None => None\n      end\n    end.*)\n\n  Definition M_run_ls_on_this_one_event\n             {L S}\n             (ls : LocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event) : option (LocalSystem L S) :=\n    option_map\n      (M_run_ls_on_input_ls ls (msg_comp_name S))\n      (trigger_op e).\n\n  Lemma crazy_bind_option1 :\n    forall {n A O} (F : A -> M_n n (option A ## O)),\n      (fun a : option A =>\n         (a >>o>>\n            (fun s : A => (F s) >>= (fun so : option A ## O => ret _ (Some so))))\n           >>o= fun p : option A ## O => ret _ (fst p))\n      = fun (a : option A) =>\n          a >>o>> fun s => F s >>= fun x => ret _ (fst x).\n  Proof.\n    introv.\n    apply functional_extensionality; introv; simpl.\n    apply functional_extensionality; introv; simpl.\n    unfold bind_some, bind, M_on_some; simpl.\n    destruct x; simpl; auto.\n    destruct (F a x0); simpl; auto.\n  Qed.\n  Hint Rewrite @crazy_bind_option1 : comp.\n\n  Definition bind_ret :\n    forall {n} {A B} (a : A) (f : A-> M_n n B),\n      ((ret n a) >>= f) = f a.\n  Proof.\n    introv.\n    apply functional_extensionality; introv; simpl.\n    unfold bind; simpl.\n    destruct (f a x); auto.\n  Qed.\n  Hint Rewrite @bind_ret : comp.\n\n  Definition bind_ret_fun :\n    forall {n} {A B X} (F : X -> A) (f : A-> M_n n B),\n      (fun x => (ret n (F x)) >>= f) = (fun x => f (F x)).\n  Proof.\n    introv.\n    apply functional_extensionality; introv; simpl; autorewrite with comp; auto.\n  Qed.\n  Hint Rewrite @bind_ret_fun : comp.\n\n  Lemma M_on_some_some :\n    forall {n A B} a (f : A -> M_n n (option B)),\n      ((Some a) >>o>> f) = f a.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite @M_on_some_some : comp.\n\n  Lemma M_on_some_some_fun :\n    forall {n A B X} (x : X) (F : X -> A) (f : A -> M_n n (option B)),\n      (fun x => (Some (F x)) >>o>> f) = (fun x => f (F x)).\n  Proof.\n    tcsp.\n  Qed.\n  (*Hint Rewrite @M_on_some_some_fun : comp.*)\n\n  Lemma eq_M_break :\n    forall {n} {S} {O}\n           (sm   : M_n n S)\n           (subs : n_procs n)\n           (F G  : n_procs n -> S -> O),\n      (forall subs' s, F subs' s = G subs' s)\n      -> M_break sm subs F = M_break sm subs G.\n  Proof.\n    introv imp.\n    f_equal.\n    apply functional_extensionality; introv.\n    apply functional_extensionality; introv; auto.\n  Qed.\n\n  Lemma M_break_bind :\n    forall {n A B O}\n           (a    : M_n n A)\n           (G    : A -> M_n n B)\n           (subs : n_procs n)\n           (F    : n_procs n -> B -> O),\n      M_break\n        (a >>= G)\n        subs\n        F\n      = M_break\n          a\n          subs\n          (fun subs' x =>\n             M_break\n               (G x)\n               subs'\n               F).\n  Proof.\n    introv.\n    unfold M_break, bind; simpl.\n    destruct (a subs); auto.\n    destruct (G a0 n0); auto.\n  Qed.\n  Hint Rewrite @M_break_bind : comp.\n\n  Lemma M_break_bind_pair :\n    forall {n A B C O}\n           (a    : M_n n (A * B))\n           (G    : A -> B -> M_n n C)\n           (subs : n_procs n)\n           (F    : n_procs n -> C -> O),\n      M_break\n        (a >>>= G)\n        subs\n        F\n      = M_break\n          a\n          subs\n          (fun subs' x =>\n             M_break\n               (G (fst x) (snd x))\n               subs'\n               F).\n  Proof.\n    introv.\n    unfold bind_pair.\n    rewrite M_break_bind; auto.\n    apply eq_M_break; introv; repnd; subst; auto.\n  Qed.\n  Hint Rewrite @M_break_bind_pair : comp.\n\n  Lemma M_break_bind_ret :\n    forall {n A B O}\n           (a    : M_n n A)\n           (G    : A -> B)\n           (subs : n_procs n)\n           (F    : n_procs n -> B -> O),\n      M_break\n        (a >>= fun p => ret _ (G p))\n        subs\n        F\n      = M_break\n          a\n          subs\n          (fun subs' x => F subs' (G x)).\n  Proof.\n    introv.\n    unfold M_break, bind; simpl.\n    destruct (a subs); auto.\n  Qed.\n  Hint Rewrite @M_break_bind_ret : comp.\n\n  Lemma crazy_bind_option2 :\n    forall {n nm A} a (upd : M_Update n nm A) (o : option (cio_I (fio nm))),\n      ((a >>o= fun s : A => M_op_update upd s o)\n         >>o= fun p : option A ## cio_O (fio nm) => ret n (fst p))\n      = (a >>o= fun s => M_op_state upd s o).\n  Proof.\n    introv; apply functional_extensionality; introv; simpl.\n    unfold M_op_update, M_op_state, bind_some, bind, M_on_some, ret; simpl.\n    destruct (a x); simpl.\n    destruct o0; auto.\n    destruct o; auto.\n    destruct (upd a0 c n0); auto.\n  Qed.\n  Hint Rewrite @crazy_bind_option2 : comp.\n\n  Lemma map_option_M_break :\n    forall {n} {S} {O} {X}\n           (sm   : M_n n S)\n           (subs : n_procs n)\n           (F    : n_procs n -> S -> option O)\n           (G    : O -> option X),\n      map_option G (M_break sm subs F)\n      = M_break sm subs (fun subs' s => map_option G (F subs' s)).\n  Proof.\n    introv.\n    unfold map_option, M_break.\n    destruct (sm subs).\n    destruct (F n0 s); auto.\n  Qed.\n\n  Lemma map_option_swap :\n    forall {A B C} (a : option A) (b : option B) (F : A -> B -> option C),\n      map_option\n        (fun a =>\n           map_option\n             (fun b => F a b)\n             b)\n        a\n      = map_option\n          (fun b =>\n             map_option\n               (fun a => F a b)\n               a)\n          b.\n  Proof.\n    introv; unfold map_option.\n    destruct a, b; simpl; auto.\n  Qed.\n\n  Lemma M_break_M_on_some_option_map :\n    forall {A n S O}\n           (a    : option A)\n           (sm   : A -> M_n n (option S))\n           (subs : n_procs n)\n           (F    : n_procs n -> option S -> option O),\n      (forall subs', F subs' None = None)\n      -> M_break\n           (a >>o>> sm)\n           subs\n           F\n         = map_option\n             (fun a => M_break (sm a) subs F)\n             a.\n  Proof.\n    introv imp.\n    unfold option_map, map_option, M_break, M_on_some, ret.\n    destruct a; auto.\n  Qed.\n\n  Lemma M_break_ret :\n    forall {n A O}\n           (a    : A)\n           (subs : n_procs n)\n           (F    : n_procs n -> A -> O),\n      M_break\n        (ret _ a)\n        subs\n        F\n      = F subs a.\n  Proof.\n    auto.\n  Qed.\n  Hint Rewrite @M_break_ret : comp.\n\n  Definition bind_some_ret_some :\n    forall {n} {A B} (a : A) (f : A -> M_n n (option B)),\n      ((ret n (Some a)) >>o= f) = f a.\n  Proof.\n    introv.\n    apply functional_extensionality; introv; simpl.\n    unfold bind_some, bind; simpl.\n    destruct (f a x); auto.\n  Qed.\n  Hint Rewrite @bind_some_ret_some : comp.\n\n  Definition bind_some_ret_some_fun :\n    forall {n} {T A B} (f : A -> M_n n (option B)) (F : T -> A),\n      (fun a => ((ret n (Some (F a))) >>o= f)) = fun x => f (F x).\n  Proof.\n    introv.\n    apply functional_extensionality; introv; simpl; autorewrite with comp; auto.\n  Qed.\n  Hint Rewrite @bind_some_ret_some_fun : comp.\n\n  Lemma bind_bind_some :\n    forall {n} {A B C} (m : M_n n A) (f : A -> M_n n (option B)) (g : B -> M_n n (option C)),\n      ((m >>= f) >>o= g)\n      = (m >>= (fun a => ((f a) >>o= g))).\n  Proof.\n    introv; apply functional_extensionality; introv; simpl.\n    unfold bind_some, bind, M_on_some; simpl.\n    destruct (m x).\n    destruct (f a n0).\n    destruct o; simpl; auto.\n    destruct (g b n1); auto.\n  Qed.\n\n  Lemma M_break_bind_some :\n    forall {n A B O}\n           (a    : M_n n (option A))\n           (G    : A -> M_n n (option B))\n           (subs : n_procs n)\n           (F    : n_procs n -> option B -> option O),\n      (forall subs, F subs None = None)\n      -> M_break\n           (a >>o= G)\n           subs\n           F\n         = M_break\n             a\n             subs\n             (fun subs' (aop : option A) =>\n                map_option\n                  (fun (a : A) => M_break (G a) subs' F)\n                  aop).\n  Proof.\n    introv imp.\n    unfold M_break, bind_some, bind, M_on_some; simpl.\n    destruct (a subs); auto.\n    destruct o; simpl; auto.\n    destruct (G a0 n0); auto.\n  Qed.\n\n  Lemma M_break_bind_some_ret :\n    forall {n A B O}\n           (a    : M_n n (option A))\n           (G    : A -> option B)\n           (subs : n_procs n)\n           (F    : n_procs n -> option B -> option O),\n      (forall subs, F subs None = None)\n      -> M_break\n           (a >>o= fun p => ret _ (G p))\n           subs\n           F\n         = M_break\n             a\n             subs\n             (fun subs' aop => map_option (fun a => F subs' (G a)) aop).\n  Proof.\n    introv imp.\n    rewrite M_break_bind_some; auto.\n  Qed.\n\n  Ltac auto_rw_bind :=\n    repeat (repeat (first [rewrite bind_bind\n                          |rewrite bind_bind_some\n                          ]\n                   );\n            repeat (first [rewrite M_break_bind_ret;[|simpl;tcsp];[]\n                          |rewrite M_break_bind_some_ret;[|simpl;tcsp];[]\n                          ]\n                   );\n            autorewrite with comp;\n            simpl;\n            auto).\n\n  Definition bind_some_ret_some_fun2 :\n    forall {n} {T A B} (f : T -> A -> M_n n (option B)) (F : T -> A),\n      (fun a => ((ret n (Some (F a))) >>o= f a)) = fun x => (f x) (F x).\n  Proof.\n    introv.\n    apply functional_extensionality; introv; simpl; autorewrite with comp; auto.\n  Qed.\n  Hint Rewrite @bind_some_ret_some_fun2 : comp.\n\n  Lemma M_on_sm_bind_ret_const :\n    forall {n cn A B}\n           (sm : n_proc n cn)\n           (f  : n_proc_at (sm2level sm) cn -> M_n (sm2level sm) A)\n           (g  :  A -> B),\n      M_on_sm sm (fun x => (f x) >>= (fun y => ret _ (g y)))\n      = ((M_on_sm sm f) >>= fun y => ret _ (g y)).\n  Proof.\n    induction n; introv; simpl; tcsp; destruct sm; simpl; auto.\n\n    { unfold M_on_decr, bind; simpl.\n      apply functional_extensionality; introv; simpl.\n      destruct (f a (decr_n_procs x)); auto. }\n\n    rewrite IHn.\n    unfold M_on_decr, bind; simpl.\n    apply functional_extensionality; introv; simpl.\n    destruct (M_on_sm b f (decr_n_procs x)); auto.\n  Qed.\n  Hint Rewrite @M_on_sm_bind_ret_const : comp.\n\n(*  Lemma M_break_map_option_M_on_sm_ret_None :\n    forall {n cn A B}\n           (sm : n_proc n cn)\n           subs\n           (f : n_procs n -> A -> option B),\n      M_break (M_on_sm sm (fun x => ret _ None)) subs (fun subs' x => map_option (f subs') x)\n      = None.\n  Proof.\n    induction n; introv; simpl; tcsp; destruct sm; simpl; auto.\n    unfold M_break, M_on_decr in *; simpl in *.\n    pose proof (IHn _ _ _ b (decr_n_procs subs) (fun ps a => f (incr_n_procs ps) a)) as IHn.\n    dest_cases w; auto.\n    destruct w1; simpl in *; auto.\n  Qed.\n  Hint Rewrite @M_break_map_option_M_on_sm_ret_None : comp.*)\n\n  Lemma M_run_ls_on_event_unroll :\n    forall {L S}\n           (ls : LocalSystem L S)\n           {eo : EventOrdering}\n           (e  : Event),\n      M_run_ls_on_event ls e\n      = if dec_isFirst e\n        then M_run_ls_on_this_one_event ls e\n        else\n          map_option\n            (fun ls => M_run_ls_on_this_one_event ls e)\n            (M_run_ls_before_event ls e).\n  Proof.\n    introv.\n    unfold M_run_ls_on_event; simpl.\n    destruct (dec_isFirst e); simpl.\n    { unfold M_run_ls_before_event.\n      rewrite isFirst_implies_localPreds_eq; simpl; auto. }\n    remember (M_run_ls_before_event ls e) as x; destruct x; simpl; auto.\n  Qed.\n\n  Lemma M_on_some_ret_some :\n    forall {n A} (a : option A),\n      (a >>o>> fun a => ret n (Some a))\n      = ret _ a.\n  Proof.\n    destruct a; simpl; auto.\n  Qed.\n  Hint Rewrite @M_on_some_ret_some : comp.\n\n  Lemma M_on_some_ret_some_fun :\n    forall {n A B} (F : B -> option A),\n      (fun x => F x >>o>> fun a => ret n (Some a))\n      = fun x => ret _ (F x).\n  Proof.\n    introv; apply functional_extensionality; introv; autorewrite with comp; auto.\n  Qed.\n  Hint Rewrite @M_on_some_ret_some_fun : comp.\n\n  Lemma eq_bind :\n    forall {A B} {n:nat} (m : M_n n A) (f g : A -> M_n n B),\n      (forall a, f a = g a)\n      -> (m >>= f) = (m >>= g).\n  Proof.\n    introv imp; apply functional_extensionality; introv; unfold bind; simpl; auto.\n    destruct (m x); auto.\n    rewrite imp; auto.\n  Qed.\n\n  Lemma eq_M_on_some :\n    forall {A B} {n:nat} (m : option A) (f g : A -> M_n n (option B)),\n      (forall a, f a = g a)\n      -> (m >>o>> f) = (m >>o>> g).\n  Proof.\n    introv imp; apply functional_extensionality; introv; unfold M_on_some; simpl; auto.\n    destruct m; auto.\n    rewrite imp; auto.\n  Qed.\n\n  Lemma M_on_some_bind_M_on_some :\n    forall {n A B C}\n           (xop : option A)\n           (f : A -> M_n n (option B))\n           (g : B -> M_n n (option C)),\n      ((xop >>o>> f) >>= fun x => x >>o>> g)\n      = (xop >>o>> fun a => f a >>= fun y => y >>o>> g).\n  Proof.\n    introv.\n    apply functional_extensionality; introv; simpl.\n    destruct xop; simpl; auto.\n  Qed.\n\n  Lemma M_break_M_op_state :\n    forall {n} {nm} {S} {O}\n           (upd  : M_Update n nm S)\n           (s    : S)\n           (i    : option (cio_I (fio nm)))\n           (subs : n_procs n)\n           (F    : n_procs n -> _ -> option O),\n      (forall subs', F subs' None = None)\n      -> M_break\n           (M_op_state upd s i)\n           subs\n           F\n         = map_option\n             (fun i => M_break (upd s i) subs (fun subs' s => F subs' (fst s)))\n             i.\n  Proof.\n    introv imp.\n    unfold M_break; destruct i; simpl; auto.\n    unfold bind; simpl.\n    destruct (upd s c subs); auto.\n  Qed.\n\n  Lemma bind_some_bind_M_on_some :\n    forall {n} {A B C}\n           (m : M_n n (option A))\n           (f : A -> M_n n (option B))\n           (g : B -> M_n n (option C)),\n      ((m >>o= f) >>= (fun b => b >>o>> g))\n      = (m >>o= fun a => (f a) >>= fun b => b >>o>> g).\n  Proof.\n    introv; apply functional_extensionality; introv; simpl.\n    unfold bind_some, bind, M_on_some; simpl.\n    destruct (m x).\n    destruct o; simpl; auto.\n    destruct (f a n0).\n    destruct o; simpl; auto.\n    destruct (g b n1); auto.\n  Qed.\n\n  Lemma bind_some_bind_some :\n    forall {n A B C}\n           (a : M_n n (option A))\n           (f : A -> M_n n (option B))\n           (g : B -> M_n n (option C)),\n      ((a >>o= f) >>o= g)\n      = (a >>o= (fun a => (f a) >>o= g)).\n  Proof.\n    introv; unfold bind_some.\n    rewrite bind_bind.\n    apply eq_bind; introv.\n    rewrite M_on_some_bind_M_on_some; auto.\n  Qed.\n\n  Lemma M_on_some_bind_some :\n    forall {n A B C}\n           (a : option A)\n           (f : A -> M_n n (option B))\n           (g : B -> M_n n (option C)),\n      ((a >>o>> f) >>o= g)\n      = (a >>o>> (fun a => (f a) >>o= g)).\n  Proof.\n    introv; unfold M_on_some, bind_some.\n    destruct a; simpl; auto.\n  Qed.\n\n  Lemma eq_bind_some :\n    forall {A B} {n:nat} (m : M_n n (option A)) (f g : A -> M_n n (option B)),\n      (forall a, f a = g a)\n      -> (m >>o= f) = (m >>o= g).\n  Proof.\n    introv imp; apply functional_extensionality; introv.\n    unfold bind_some, bind, M_on_some; simpl; auto.\n    destruct (m x); auto.\n    destruct o; simpl; auto.\n    rewrite imp; auto.\n  Qed.\n\n(*  Lemma M_run_update_on_list_snoc :\n    forall {S} {n} {nm}\n           (upd : M_Update n nm S)\n           (l : oplist (cio_I (fio nm)))\n           (s : S)\n           (x : option (cio_I (fio nm))),\n      M_run_update_on_list s upd (snoc l x)\n      = ((M_run_update_on_list s upd l)\n           >>o= fun s => M_op_state upd s x).\n  Proof.\n    induction l; introv; simpl; auto.\n\n    {\n      destruct x; simpl; auto.\n      autorewrite with comp; auto.\n    }\n\n    destruct a; auto;[]; autorewrite with comp.\n    auto_rw_bind.\n    apply eq_bind; introv.\n    rewrite M_on_some_bind_some.\n    apply eq_M_on_some; introv; auto.\n  Qed.*)\n\n  Lemma M_run_ls_on_op_inputs_snoc :\n    forall {L S}\n           (ls : LocalSystem L S)\n           {cn}\n           (i  : option (cio_I (fio cn)))\n           (l  : oplist (cio_I (fio cn))),\n      M_run_ls_on_op_inputs ls cn (snoc l i)\n      = on_some\n          (M_run_ls_on_op_inputs ls cn l)\n          (fun ls' => option_map (M_run_ls_on_input_ls ls' cn) i).\n  Proof.\n    introv; revert ls; induction l; introv; simpl; auto.\n    unfold on_some.\n    rewrite map_option_map_option.\n    destruct a; simpl in *; auto.\n    rewrite IHl; auto.\n  Qed.\n\n  Lemma M_run_ls_on_inputs_snoc :\n    forall {L S}\n           (ls : LocalSystem L S)\n           {cn}\n           (i  : cio_I (fio cn))\n           (l  : list (cio_I (fio cn))),\n      M_run_ls_on_inputs ls cn (snoc l i)\n      = let ls' := M_run_ls_on_inputs ls cn l\n        in M_run_ls_on_input_ls ls' cn i.\n  Proof.\n    introv; revert ls; induction l; introv; simpl; auto.\n  Qed.\n\n  Lemma M_run_ls_before_event_unroll :\n    forall {L S}\n           (ls : LocalSystem L S)\n           {eo : EventOrdering}\n           (e  : Event),\n      M_run_ls_before_event ls e\n      = if dec_isFirst e\n        then Some ls\n        else map_option\n               (fun ls => M_run_ls_on_this_one_event ls (local_pred e))\n               (M_run_ls_before_event ls (local_pred e)).\n  Proof.\n    introv.\n    unfold M_run_ls_before_event.\n    destruct (dec_isFirst e) as [d|d].\n\n    { rewrite isFirst_implies_localPreds_eq; simpl; auto. }\n\n    rewrite (localPreds_unroll e) at 1; auto; simpl.\n    rewrite map_snoc; simpl.\n    rewrite M_run_ls_on_op_inputs_snoc.\n\n    unfold on_some, map_option; dest_cases w.\n  Qed.\n\n  Lemma M_run_ls_before_event_as_M_run_ls_on_event_pred :\n    forall {L S}\n           (ls : LocalSystem L S)\n           {eo : EventOrdering}\n           (e  : Event),\n      ~ isFirst e\n      -> M_run_ls_before_event ls e = M_run_ls_on_event ls (local_pred e).\n  Proof.\n    introv ni.\n    rewrite M_run_ls_on_event_unroll.\n    rewrite M_run_ls_before_event_unroll.\n\n    destruct (dec_isFirst e) as [d1|d1]; tcsp;[].\n    destruct (dec_isFirst (local_pred e)) as [d2|d2]; tcsp;[].\n\n    rewrite M_run_ls_before_event_unroll.\n    destruct (dec_isFirst (local_pred e)); tcsp; GC.\n  Qed.\n\n  Lemma M_run_ls_before_event_unroll_on :\n    forall {L S}\n           (ls : LocalSystem L S)\n           {eo : EventOrdering}\n           (e  : Event),\n      M_run_ls_before_event ls e\n      = if dec_isFirst e\n        then Some ls\n        else M_run_ls_on_event ls (local_pred e).\n  Proof.\n    introv.\n    destruct (dec_isFirst e) as [d|d];\n      [|apply M_run_ls_before_event_as_M_run_ls_on_event_pred;auto].\n    rewrite M_run_ls_before_event_unroll.\n    destruct (dec_isFirst e); tcsp.\n  Qed.\n\n  Lemma M_state_sys_before_event_as_M_state_sys_on_event_pred :\n    forall {F}\n           (sys : M_USystem F)\n           {eo  : EventOrdering}\n           (e   : Event)\n           (cn  : CompName),\n      ~ isFirst e\n      -> M_state_sys_before_event sys e cn = M_state_sys_on_event sys (local_pred e) cn.\n  Proof.\n    introv nfst.\n    unfold M_state_sys_on_event.\n    unfold M_state_sys_before_event.\n    autorewrite with eo.\n    unfold M_state_ls_on_event.\n    unfold M_state_ls_before_event.\n    rewrite M_run_ls_before_event_as_M_run_ls_on_event_pred; auto.\n  Qed.\n\n  Lemma M_state_sys_before_event_if_on_event_direct_pred :\n    forall {cn  : CompName}\n           {eo : EventOrdering}\n           (e1 e2 : Event)\n           {F}\n           (sys : M_USystem F)\n           (s   : sf cn),\n      e1 ⊂ e2\n      -> M_state_sys_on_event sys e1 cn = Some s\n      -> M_state_sys_before_event sys e2 cn = Some s.\n  Proof.\n    introv lte eqst.\n    applydup pred_implies_local_pred in lte; subst.\n    rewrite M_state_sys_before_event_as_M_state_sys_on_event_pred; eauto 2 with eo.\n  Qed.\n  Hint Resolve M_state_sys_before_event_if_on_event_direct_pred : proc.\n\n  Lemma M_state_sys_before_event_unfold :\n    forall {F}\n           (sys : M_USystem F)\n           {eo  : EventOrdering}\n           (e   : Event)\n           (cn  : CompName),\n      M_state_sys_before_event sys e cn\n      = map_option\n          (state_of_component cn)\n          (M_run_ls_before_event (sys (loc e)) e).\n  Proof.\n    tcsp.\n  Qed.\n\n  Lemma M_state_sys_on_event_unfold :\n    forall {F}\n           (sys : M_USystem F)\n           {eo  : EventOrdering}\n           (e   : Event)\n           (cn  : CompName),\n      M_state_sys_on_event sys e cn\n      = map_option\n          (state_of_component cn)\n          (M_run_ls_on_event (sys (loc e)) e).\n  Proof.\n    tcsp.\n  Qed.\n\n  Lemma M_run_ls_before_event_is_first :\n    forall {L S} {eo : EventOrdering} (e : Event) (ls : LocalSystem L S),\n      isFirst e\n      -> M_run_ls_before_event ls e = Some ls.\n  Proof.\n    introv isf.\n    unfold M_run_ls_before_event;simpl.\n    rewrite isFirst_implies_localPreds_eq; auto; simpl.\n  Qed.\n\n  Lemma M_state_sys_on_event_unfold_before :\n    forall {F}\n           (sys : M_USystem F)\n           {eo  : EventOrdering}\n           (e   : Event)\n           (cn  : CompName),\n      M_state_sys_on_event sys e cn\n      = map_option\n          (fun ls => map_option\n                       (state_of_component cn)\n                       (M_run_ls_on_this_one_event ls e))\n          (M_run_ls_before_event (sys (loc e)) e).\n  Proof.\n    introv.\n    unfold M_state_sys_on_event.\n    unfold M_state_ls_on_event.\n    rewrite M_run_ls_on_event_unroll.\n    destruct (dec_isFirst e) as [d|d]; tcsp.\n\n    { rewrite M_run_ls_before_event_is_first; auto. }\n\n    unfold map_option.\n    remember (M_run_ls_before_event (sys (loc e)) e) as xx; destruct xx; auto.\n  Qed.\n\n\n(*  Lemma state_sm_on_event_unroll2 :\n    forall (sys : M_USystem)\n           {eo  : EventOrdering}\n           (e   : Event)\n           (cn  : CompName),\n      M_state_sys_on_event sys e cn\n      = map_option\n          (fun s => op_state sm s (trigger e) (time e))\n          (M_state_sys_before_event sys e cn).\n  Proof.\n    introv.\n    rewrite <- ite_first_state_sm_on_event_as_before.\n    unfold ite_first.\n    rewrite state_sm_on_event_unroll.\n    destruct (dec_isFirst e); simpl; auto.\n  Qed.*)\n\n  (* *** END *** *)\n  (******************************************)\n\n\n\n  Definition remove_proc\n             (cn : CompName)\n             {n} {A}\n             (x : M_n n A) : M_n n A :=\n    fun ps => x (remove_name ps cn).\n\n  Definition spawn_proc\n             {n}\n             (p : n_nproc n)\n             {A}\n             (x : M_n n A) : M_n n A :=\n    fun ps => x (p :: ps).\n\n  Definition spawn_proc_once\n             {n}\n             (p : n_nproc n)\n             {A}\n             (x : M_n n A) : M_n n A :=\n    fun ps => x (match find_name (pp_name p) ps with\n                 | Some _ => ps\n                 | None => p :: ps\n                 end).\n\n\n\n  (******************************************)\n  (* ====== A ====== *)\n  Definition Aname : CompName := MkCN \"NAT\" 2 false.\n  Definition A_update : M_Update 0 Aname _ :=\n    fun (s : nat) (i : nat) =>\n        (ret _ (Some (s + i), s + i)).\n  Definition A : n_proc 1 _ := build_m_sm A_update 0.\n\n  (* ====== B ====== *)\n  Definition Bname : CompName := MkCN \"NAT\" 3 false.\n  Definition B_update : M_Update 1 Bname _ :=\n    fun s i =>\n      spawn_proc_once\n        (MkPProc _ A)\n        (*remove_proc Aname*)\n        ((call_proc Aname i)\n           >>= fun out =>\n                 ret _ (Some (s + out + 1), s + out + 1)).\n  Definition B : n_proc _ _ := build_m_sm B_update 0.\n\n  (* ====== C ====== *)\n  Definition Cname : CompName := MkCN \"NAT\" 4 false.\n  Definition C_update : M_Update 2 Cname _ :=\n    fun s i =>\n      (call_proc Bname i)\n        >>= fun out1 =>\n              (call_proc Bname i)\n                >>= fun out2 =>\n                      ret _ (Some (s + out1 + out2 + 2), s + out1 + out2 + 2).\n  Definition C : n_proc _ _ := build_m_sm C_update 0.\n\n  (* ====== Main ====== *)\n  Definition Mname : CompName := MkCN \"NAT\" 5 false.\n  Definition M_update : M_Update 3 Mname nat :=\n    fun s i =>\n      (call_proc Cname i)\n        >>= (fun out => ret _ (Some s, out)).\n  Definition M : n_proc _ _ := build_m_sm M_update 0.\n\n\n  (* ====== Local System ====== *)\n\n  Definition ex_ls : LocalSystem 4 5 :=\n    [\n      (*MkPProc _ (incr_n_proc (incr_n_proc (incr_n_proc A))),*)\n      MkPProc _ (incr_n_proc (incr_n_proc B)),\n      MkPProc _ (incr_n_proc C),\n      MkPProc _ M\n    ].\n\n\n  Definition ex_test1 := M_run_ls_on_input_out ex_ls Mname 17.\n  Eval compute in (ex_test1 = Some 73).\n\n  Definition ex_test2 := let ls := M_run_ls_on_input_ls ex_ls Mname 17 in\n                         M_run_ls_on_input_out ls Mname 17.\n  Eval compute in (ex_test2 = Some 354).\n  (******************************************)\n\n\n\n\n  (***************************)\n\n(*  Definition M_output_sm_on_event {n} {k}\n             (sm : n_proc n (main_comp_name k))\n             {eo : EventOrdering}\n             (e  : Event) : M_n (sm2level sm) (option DirectedMsgs) :=\n    (M_run_sm_on_event sm e)\n      >>o= fun x => ret _ (Some (snd x)).*)\n\n(*  Definition system2level\n             {eo : EventOrdering}\n             (e  : Event) : nat := fls_level (loc e).*)\n\n(*  Definition system2space\n             {eo : EventOrdering}\n             (e  : Event) : nat := fls_space (loc e).*)\n\n  Definition system2local\n             {eo  : EventOrdering}\n             (e   : Event)\n             {F}\n             (sys : M_USystem F)\n    : LocalSystem (fls_level F (loc e)) (fls_space F (loc e)) :=\n    sys (loc e).\n\n(*  Fixpoint app_m_proc_to_subs {n} {nm}\n    : n_proc n nm -> M_n (pred n) (n_proc n nm) :=\n    match n return n_proc n nm -> M_n (pred n) (n_proc n nm) with\n    | 0 => fun pr ps => (ps, pr)\n    | S m =>\n      fun pr =>\n        match pr with\n        | inl sm => fun ps => lift_M sm ps\n        | inr pr' => fun ps => (ps,pr) (*lift_M2 (app_m_proc_to_subs pr')*)\n        end\n    end.*)\n\n(*  Definition system2main_local\n             {eo  : EventOrdering}\n             (e   : Event)\n             (sys : M_USystem) (*: n_proc (S (system2level e sys)) msg_comp_name*) :=\n    let local := sys (loc e) in\n    ls_main local (ls_subs local).*)\n\n\n\n\n(*\n  Definition system2main_local\n             {eo  : EventOrdering}\n             (e   : Event)\n             (sys : M_USystem) : n_proc (S (system2level e sys)) (msg_comp_name (system2space e sys)) :=\n    ls_main (sys (loc e)).\n\n  Definition MM_run_system_on_event_sm\n             (sys : M_USystem)\n             {eo  : EventOrdering}\n             (e   : Event)\n    : M_n (sm2level (system2main_local e sys))\n          (option (option (sf (msg_comp_name (system2space e sys))) * DirectedMsgs)) :=\n    M_run_sm_on_event (system2main_local e sys) e.\n\n  Definition M_run_system_on_event_sm\n             (sys : M_USystem)\n             {eo  : EventOrdering}\n             (e   : Event)\n    : n_procs (sm2level (system2main_local e sys))\n      * (option (option (sf (msg_comp_name (system2space e sys))) * DirectedMsgs)) :=\n    MM_run_system_on_event_sm sys e (ls_subs (sys (loc e))).\n\n  Definition MM_output_system_on_event\n             (sys : M_USystem)\n             {eo  : EventOrdering}\n             (e   : Event) : M_n (sm2level (system2main_local e sys)) (option DirectedMsgs) :=\n    (MM_run_system_on_event_sm sys e)\n      >>= fun x =>\n            match x with\n            | Some (sm',msgs) => ret _ (Some msgs)\n            | None => ret _ None\n            end.\n\n  Definition M_output_system_on_event\n             (sys : M_USystem)\n             {eo  : EventOrdering}\n             (e   : Event) : option DirectedMsgs :=\n    snd (MM_output_system_on_event sys e (ls_subs (sys (loc e)))).\n\n  (* apply history with last event *)\n  Definition MM_output_system_on_event_ldata\n             (sys : M_USystem)\n             {eo  : EventOrdering}\n             (e   : Event) : M_n (sm2level (system2main_local e sys)) DirectedMsgs :=\n    (MM_output_system_on_event sys e)\n      >>= fun x =>\n            match x with\n            | Some msgs => ret _ msgs\n            | None => ret _ []\n            end.\n\n  Definition M_output_system_on_event_ldata\n             (sys : M_USystem)\n             {eo  : EventOrdering}\n             (e   : Event) : DirectedMsgs :=\n    snd (MM_output_system_on_event_ldata sys e (ls_subs (sys (loc e)))).\n\n  Definition M_state_system_on_event\n             (sys : M_USystem)\n             {eo  : EventOrdering}\n             (e   : Event)\n    : n_procs (sm2level (system2main_local e sys))\n      * option (sf (msg_comp_name (system2space e sys))) :=\n    M_state_sm_on_event (system2main_local e sys) e (ls_subs (sys (loc e))).\n\n  Definition M_state_system_on_event_main\n             (sys : M_USystem)\n             {eo  : EventOrdering}\n             (e   : Event)\n    : option (sf (msg_comp_name (system2space e sys))) :=\n    snd (M_state_system_on_event sys e).\n*)\n\n\n\n  (* ============== Constraint on types of states ============== *)\n\n(*  Definition StateConstraint := CompName -> option Type.\n\n  Fixpoint sm_satisfies_type_constraint (T : Type) {n : nat} {nm : CompName} : n_proc n nm -> Prop :=\n    match n with\n    | 0 => fun sm => True\n    | S n =>\n      fun sm =>\n        match sm with\n        | inl x => sm_S x = T\n        | inr x => sm_satisfies_type_constraint T x\n        end\n    end.\n\n  Definition nsm_satisfies_type_constraint (C : StateConstraint) {n : nat} (nsm : {cn : CompName & n_proc n cn}) : Prop :=\n    let (name, sm) := nsm in\n    match C name with\n    | Some T => sm_satisfies_type_constraint T sm\n    | None => True\n    end.\n\n  Definition local_system_satisfies_type_constraint (C : StateConstraint) (sys : LocalSystem) :=\n    forall sm, In sm (ls_subs sys) -> nsm_satisfies_type_constraint C sm.\n\n  Definition system_satisfies_type_constraint (C : StateConstraint) (sys : M_USystem) :=\n    forall n, local_system_satisfies_type_constraint C (sys n).\n\n\n  Definition is_key_name (name : CompName) : bool :=\n    if CompNameKindDeq (comp_name_kind name) key_comp_name_kind\n    then true\n    else false.\n\n  (*Definition key_state_constraint : StateConstraint :=\n    fun n => if is_key_name n then Some local_key_map else None.*)\n\n  Definition sm_key_constraint {n : nat} {nm : CompName} : n_proc n nm -> Prop :=\n    sm_satisfies_type_constraint local_key_map.\n\n  Definition nsm_key_constraint {n : nat} (nsm : {cn : CompName & n_proc n cn}) : Prop :=\n    let (name, sm) := nsm in\n    if CompNameKindDeq (comp_name_kind name) key_comp_name_kind\n    then sm_key_constraint sm\n    else True.\n\n  Definition local_system_key_constraint (sys : LocalSystem) :=\n    forall sm, In sm (ls_subs sys) -> nsm_key_constraint sm.\n\n  Definition system_key_constraint (sys : M_USystem) :=\n    forall n, local_system_key_constraint (sys n).*)\n\n  (* ==============  ==============  ============== *)\n\n\n\n  Definition find_state_machine_with_name {n}\n             (L  : n_procs n)\n             (cn : CompName) : option (sf cn) :=\n    state_of_component cn L.\n\n(*  Definition M_state_system_on_event_sub\n           (sys : M_USystem)\n           {eo  : EventOrdering}\n           (e   : Event)\n           (cn  : CompName) : option (sf cn) :=\n    find_state_machine_with_name (fst (M_state_system_on_event sys e)) cn.*)\n\n  Definition pbind {A} {n:nat} (m : M_n n A) (f : A -> M_n n Prop) : Prop :=\n    forall s,\n      let (s1,a) := m s in\n      let (s2,b) := f a s1 in\n      b.\n  Notation \"a >p>= f\" := (pbind a f) (at level 80).\n\n  (*Open Scope eo.*)\n\n  (*Definition AXIOM_M_authenticated_messages_were_sent_or_byz\n             (sys : M_USystem)\n             (F : forall (eo : EventOrdering) (e : Event), M_n (sm2level (system2main_local e sys)) DirectedMsgs) :=\n    forall {eo : EventOrdering} e (a : AuthenticatedData),\n      In a (bind_op_list get_contained_authenticated_data (trigger e))\n      (* if we didn't verify the message then it could come from a Byzantine\n         node that is impersonating someone else, without the logic knowing it *)\n      -> verify_authenticated_data (loc e) a (keys e) = true\n      -> exists e',\n        e' ≺ e (* event e was triggered by an earlier send event e' *)\n\n        (* e' generated the authentication code *)\n        (* QUESTION: Should we say instead that the message was authenticated\n           using a subset of the keys? *)\n        /\\ am_auth a = authenticate (am_data a) (keys e')\n\n        /\\\n        (\n          (\n            exists m dst delay,\n\n              In a (get_contained_authenticated_data m)\n\n              /\\\n              (* e' sent the message to some node \"dst\"\n                 following the protocol as described by F\n                 (only if the message is the message is internal though),\n                 which eventually got to e *)\n              (is_protocol_message m = true\n               -> ((F eo e') >p>= (fun msgs => ret _ (In (MkDMsg m dst delay) msgs))))\n\n              /\\\n              (* e' is the node mentioned in the authenticated message *)\n              data_auth (loc e) (am_data a) = Some (loc e')\n          )\n\n          \\/\n\n          (* e' is not the node mentioned in the authenticated message\n             because he got the keys of some other e''\n           *)\n          (\n            exists e'',\n              e'' ≼ e'\n              /\\\n              (* e' is byzantine because it's using the keys of e'' *)\n              isByz e'\n              /\\\n              (* e'' is byzantine because it lost it keys *)\n              isByz e''\n              /\\\n                (* the sender mentioned in m is actually e'' and not e' but e' sent the message impersonating e''...what a nerve! *)\n              data_auth (loc e) (am_data a) = Some (loc e'')\n              /\\\n              (* e' got the key for (loc e) from e'' *)\n              got_key_for (loc e) (keys e'') (keys e')\n          )\n        ).*)\n\n(*  Definition AXIOM_M_correct_keys {n}\n             (sm : name -> n_proc n msg_comp_name)\n             (K  : forall (i : name), sm2S (sm i) -> local_key_map)\n             (eo : EventOrdering) : Prop :=\n    forall (e : Event) (i : name) st,\n      has_correct_trace_before e i\n      -> M_state_sm_before_event (sm i) e = st\n      -> st >p>= (fun sop => match sop with\n                             | Some s => ret _ (keys e = K i s)\n                             | None => ret _ True\n                             end).*)\n\n\n  Definition sub_sending_key (sk1 sk2 : DSKey) : Prop :=\n    subset (dsk_dst sk1) (dsk_dst sk2) /\\ dsk_key sk1 = dsk_key sk2.\n\n  Definition sub_sending_keys (l1 l2 : list DSKey) : Prop :=\n    forall sk1,\n      In sk1 l1\n      ->\n      exists sk2,\n        In sk2 l2\n        /\\ sub_sending_key sk1 sk2.\n\n  Definition sub_receiving_key (rk1 rk2 : DRKey) : Prop :=\n    subset (drk_dst rk1) (drk_dst rk2) /\\ drk_key rk1 = drk_key rk2.\n\n  Definition sub_receiving_keys (l1 l2 : list DRKey) : Prop :=\n    forall rk1,\n      In rk1 l1\n      ->\n      exists rk2,\n        In rk2 l2\n        /\\ sub_receiving_key rk1 rk2.\n\n  Definition sub_local_key_map (k1 k2 : local_key_map) : Prop :=\n    sub_sending_keys (lkm_sending_keys k1) (lkm_sending_keys k2)\n    /\\ sub_receiving_keys (lkm_receiving_keys k1) (lkm_receiving_keys k2).\n\n  Lemma sub_local_key_map_preserves_in_lookup_receiving_keys :\n    forall ks1 ks2 x n,\n      sub_local_key_map ks1 ks2\n      -> In x (lookup_receiving_keys ks1 n)\n      -> In x (lookup_receiving_keys ks2 n).\n  Proof.\n    introv sub i.\n    unfold lookup_receiving_keys in *; allrw in_map_iff; exrepnd; subst.\n    unfold lookup_drkeys in *.\n    allrw @filter_In; repnd; dest_cases x; GC.\n    apply sub in i1; exrepnd.\n    unfold sub_receiving_key in *; repnd.\n    exists rk2; dands; auto.\n    apply filter_In; dands; auto; dest_cases y.\n  Qed.\n  Hint Resolve sub_local_key_map_preserves_in_lookup_receiving_keys : eo.\n\n  Lemma verify_authenticated_data_if_sub_keys :\n    forall (ks1 ks2 : local_key_map) n a,\n      sub_local_key_map ks1 ks2\n      -> verify_authenticated_data n a ks1 = true\n      -> verify_authenticated_data n a ks2 = true.\n  Proof.\n    introv sub verif.\n    unfold verify_authenticated_data in *.\n    remember (data_auth n a) as da; symmetry in Heqda; destruct da; ginv.\n    unfold verify_authenticated_data_keys in *.\n    allrw existsb_exists; exrepnd.\n    exists x; dands; auto; eauto 3 with eo.\n  Qed.\n  Hint Resolve verify_authenticated_data_if_sub_keys : eo.\n\n  Lemma local_happened_before_implies_history_app :\n    forall {eo : EventOrdering} (e1 e2 : Event),\n      e1 ⊑ e2\n      -> exists l, History(e2) = History(e1) ++ l.\n  Proof.\n    intros eo e1.\n    induction e2 as [e2 ind] using predHappenedBeforeInd;[]; introv lte.\n    apply localHappenedBeforeLe_implies_or2 in lte; repndors; subst.\n\n    { exists ([] : list Event); autorewrite with list; auto. }\n\n    apply local_implies_pred_or_local in lte; repndors; exrepnd.\n\n    { applydup pred_implies_not_first in lte.\n      rewrite (localPreds_unroll e2); auto.\n      exists [local_pred e2].\n      rewrite snoc_as_app; f_equal; f_equal.\n      unfold local_pred; rewrite lte; auto. }\n\n    pose proof (ind e) as ind; repeat (autodimp ind hyp); eauto 3 with eo; exrepnd.\n    applydup pred_implies_not_first in lte1.\n    rewrite (localPreds_unroll e2); auto.\n    unfold local_pred; rewrite lte1.\n    rewrite ind0.\n    exists (snoc l e).\n    rewrite app_snoc; auto.\n  Qed.\n\n(*  Lemma M_run_update_on_list_app :\n    forall {S} {n} {nm}\n           (upd : M_Update n nm S)\n           (l k : oplist (cio_I (fio nm)))\n           (s : S),\n      M_run_update_on_list s upd (l ++ k)\n      = ((M_run_update_on_list s upd l)\n           >>o= fun s => M_run_update_on_list s upd k).\n  Proof.\n    induction l; introv; simpl; auto; autorewrite with comp in *; auto;[].\n    rewrite M_on_some_bind_some.\n    apply eq_M_on_some; introv.\n    rewrite bind_bind_some.\n    apply eq_bind; introv.\n    rewrite M_on_some_bind_some.\n    apply eq_M_on_some; introv; auto.\n  Qed.*)\n\n  Lemma local_happened_before_implies_history_app2 :\n    forall {eo : EventOrdering} (e1 e2 : Event),\n      e1 ⊏ e2\n      -> exists l, History(e2) = History(e1) ++ e1 :: l.\n  Proof.\n    intros eo e1.\n    induction e2 as [e2 ind] using predHappenedBeforeInd;[]; introv lte.\n\n    apply local_implies_pred_or_local in lte; repndors; exrepnd.\n\n    { applydup pred_implies_not_first in lte.\n      rewrite (localPreds_unroll e2); auto.\n      exists ([] : list Event).\n      unfold local_pred.\n      rewrite lte.\n      rewrite snoc_as_app; auto. }\n\n    pose proof (ind e) as ind; repeat (autodimp ind hyp); eauto 3 with eo; exrepnd.\n    applydup pred_implies_not_first in lte1.\n    rewrite (localPreds_unroll e2); auto.\n    unfold local_pred; rewrite lte1.\n    rewrite ind0.\n    exists (snoc l e).\n    rewrite <- snoc_cons.\n    rewrite app_snoc; auto.\n  Qed.\n\n(*  Lemma M_on_some_bind_M_on_some_fun :\n    forall {n A B C}\n           (f : A -> M_n n (option B))\n           (g : B -> M_n n (option C)),\n      (fun xop => (xop >>o>> f) >>= fun x => x >>o>> g)\n      = (fun xop => xop >>o>> fun a => f a >>= fun y => y >>o>> g).\n  Proof.\n    introv; apply functional_extensionality; introv; simpl.\n    apply M_on_some_bind_M_on_some.\n  Qed.*)\n\n(*  Lemma M_run_update_on_list_snoc_fun :\n    forall {S} {n} {nm}\n           (upd : M_Update n nm S)\n           (l : oplist (cio_I (fio nm)))\n           (x : option (cio_I (fio nm))),\n      (fun s => M_run_update_on_list s upd (snoc l x))\n      = (fun s => (M_run_update_on_list s upd l)\n                    >>o= fun s => M_op_state upd s x).\n  Proof.\n    introv; apply functional_extensionality; introv.\n    apply M_run_update_on_list_snoc.\n  Qed.*)\n\n  Definition similar_sms_at {cn} {k} (p1 p2 : n_proc_at k cn) : Prop :=\n    sm_update p1 = sm_update p2.\n\n  Lemma similar_sms_at_refl :\n    forall cn k (p : n_proc_at k cn),\n      similar_sms_at p p.\n  Proof.\n    introv; split; auto.\n  Qed.\n  Hint Resolve similar_sms_at_refl : comp.\n\n  Lemma similar_sms_at_sym :\n    forall cn k (p1 p2 : n_proc_at k cn),\n      similar_sms_at p1 p2\n      -> similar_sms_at p2 p1.\n  Proof.\n    introv h; unfold similar_sms_at in *; tcsp.\n  Qed.\n  Hint Resolve similar_sms_at_sym : comp.\n\n  Lemma similar_sms_at_trans :\n    forall cn k (p1 p2 p3 : n_proc_at k cn),\n      similar_sms_at p1 p2\n      -> similar_sms_at p2 p3\n      -> similar_sms_at p1 p3.\n  Proof.\n    introv h q; unfold similar_sms_at in *; repnd; dands; try congruence.\n  Qed.\n  Hint Resolve similar_sms_at_trans : comp.\n\n  Fixpoint similar_sms {cn} {k} : n_proc k cn -> n_proc k cn -> Prop :=\n    match k with\n    | 0 => fun sm1 sm2 => False\n    | S n =>\n      fun sm1 sm2 =>\n        match sm1, sm2 with\n        | sm_or_at p1, sm_or_at p2 => similar_sms_at p1 p2\n        | sm_or_sm p1, sm_or_sm p2 => similar_sms p1 p2\n        | _, _ => False\n        end\n    end.\n\n  Inductive similar_procs : forall {n m}, n_nproc n -> n_nproc m -> Prop :=\n  | sim_procs :\n      forall {k cn} (p1 : n_proc k cn) (p2 : n_proc k cn),\n        similar_sms p1 p2\n        -> similar_procs (MkPProc cn p1) (MkPProc cn p2).\n  Hint Constructors similar_procs.\n\n  Inductive similar_subs {n m} : n_procs n -> n_procs m -> Prop :=\n  | sim_subs_nil : similar_subs [] []\n  | sim_subs_cons :\n      forall (p1   : n_nproc n)\n             (p2   : n_nproc m)\n             (ps1  : n_procs n)\n             (ps2  : n_procs m)\n             (simp : similar_procs p1 p2)\n             (sims : similar_subs ps1 ps2),\n        similar_subs (p1 :: ps1) (p2 :: ps2).\n  Hint Constructors similar_subs.\n\n  Lemma similar_procs_implies_same_level :\n    forall {n m} (p1 : n_nproc n) (p2 : n_nproc m),\n      similar_procs p1 p2 -> n = m.\n  Proof.\n    introv sim.\n    inversion sim; auto.\n  Qed.\n\n  Lemma similar_procs_implies_same_name :\n    forall {n m} (p1 : n_nproc n) (p2 : n_nproc m),\n      similar_procs p1 p2 -> pp_name p1 = pp_name p2.\n  Proof.\n    introv sim.\n    inversion sim; auto; subst; simpl in *.\n    match goal with\n    | [ H : context[p1] |- _ ] => rename H into h1\n    end.\n    apply Eqdep.EqdepTheory.inj_pair2 in h1; subst; simpl in *; auto.\n  Qed.\n\n  Lemma similar_procs_implies_same_proc :\n    forall {n} cn (p1 : n_proc n cn) (p2 : n_proc n cn),\n      similar_procs (MkPProc cn p1) (MkPProc cn p2) -> similar_sms p1 p2.\n  Proof.\n    introv sim.\n    inversion sim; auto; subst; simpl in *.\n    match goal with\n    | [ H : context[p1] |- _ ] => rename H into h1\n    end.\n    match goal with\n    | [ H : context[p2] |- _ ] => rename H into h2\n    end.\n    apply Eqdep.EqdepTheory.inj_pair2 in h1; subst; simpl in *; auto.\n    apply Eqdep.EqdepTheory.inj_pair2 in h1; subst; simpl in *; auto.\n    apply Eqdep.EqdepTheory.inj_pair2 in h2; subst; simpl in *; auto.\n    apply Eqdep.EqdepTheory.inj_pair2 in h2; subst; simpl in *; auto.\n  Qed.\n\n  Lemma similar_subs_implies_same_level :\n    forall {n m} (subs1 : n_procs n) (subs2 : n_procs m),\n      0 < length subs1\n      -> similar_subs subs1 subs2\n      -> n = m.\n  Proof.\n    introv len sim.\n    destruct subs1; simpl in *; ginv; try omega;[].\n    inversion sim; subst; clear sim.\n    apply similar_procs_implies_same_level in simp; auto.\n  Qed.\n\n  Lemma similar_sms_refl :\n    forall {n cn} (sm : n_proc n cn), similar_sms sm sm.\n  Proof.\n    induction n; introv; destruct sm; eauto; constructor; auto.\n  Qed.\n  Hint Resolve similar_sms_refl : comp.\n\n  Lemma similar_procs_refl :\n    forall {n} (p : n_nproc n), similar_procs p p.\n  Proof.\n    destruct p; constructor; eauto 3 with comp.\n  Qed.\n  Hint Resolve similar_procs_refl : comp.\n\n  Lemma similar_subs_refl :\n    forall {n} (subs : n_procs n), similar_subs subs subs.\n  Proof.\n    induction subs; eauto;[].\n    constructor; eauto 3 with comp.\n  Qed.\n  Hint Resolve similar_subs_refl : comp.\n\n  Lemma similar_sms_sym :\n    forall {n} {cn} (sm1 sm2 : n_proc n cn),\n      similar_sms sm1 sm2\n      -> similar_sms sm2 sm1.\n  Proof.\n    induction n; introv h; auto; simpl in *.\n    destruct sm1, sm2; tcsp; eauto 3 with comp.\n  Qed.\n  Hint Resolve similar_sms_sym : comp.\n\n  Lemma similar_procs_sym :\n    forall {n} {m} (p1 : n_nproc n) (p2 : n_nproc m),\n      similar_procs p1 p2\n      -> similar_procs p2 p1.\n  Proof.\n    introv h; induction h; auto.\n    constructor; eauto 3 with comp.\n  Qed.\n  Hint Resolve similar_procs_sym : comp.\n\n  Lemma similar_subs_sym :\n    forall {n} {m} (subs1 : n_procs n) (subs2 : n_procs m),\n      similar_subs subs1 subs2\n      -> similar_subs subs2 subs1.\n  Proof.\n    introv h; induction h; auto.\n    constructor; eauto 3 with comp.\n  Qed.\n  Hint Resolve similar_subs_sym : comp.\n\n  Lemma similar_sms_trans :\n    forall {n} {cn} (sm1 sm2 sm3 : n_proc n cn),\n      similar_sms sm1 sm2\n      -> similar_sms sm2 sm3\n      -> similar_sms sm1 sm3.\n  Proof.\n    induction n; introv h q; simpl in *; tcsp.\n    destruct sm1, sm2, sm3; simpl in *; repnd; tcsp; eauto;[].\n    destruct a0, a1; simpl in *; subst; dands; auto; eauto 3 with comp.\n  Qed.\n  Hint Resolve similar_sms_trans : comp.\n\n  Lemma similar_procs_trans :\n    forall {n} {m} {k} (p1 : n_nproc n) (p2 : n_nproc m) (p3 : n_nproc k),\n      similar_procs p1 p2\n      -> similar_procs p2 p3\n      -> similar_procs p1 p3.\n  Proof.\n    introv h q.\n    destruct h as [? ? ? ? h].\n    destruct p3 as [n3 p3].\n    inversion q; subst; GC.\n    constructor.\n    eapply similar_sms_trans;[eauto|].\n    clear dependent p1.\n    clear dependent p4.\n    clear dependent p5.\n    inversion q; subst.\n\n    match goal with\n    | [ H : context[p2] |- _ ] => rename H into h1\n    end.\n    match goal with\n    | [ H : context[p3] |- _ ] => rename H into h2\n    end.\n    apply Eqdep.EqdepTheory.inj_pair2 in h1.\n    apply Eqdep.EqdepTheory.inj_pair2 in h1.\n    apply Eqdep.EqdepTheory.inj_pair2 in h2.\n    apply Eqdep.EqdepTheory.inj_pair2 in h2.\n    subst; auto.\n  Qed.\n  Hint Resolve similar_procs_trans : comp.\n\n  Lemma similar_subs_trans :\n    forall {n} {m} {k} (subs1 : n_procs n) (subs2 : n_procs m) (subs3 : n_procs k),\n      similar_subs subs1 subs2\n      -> similar_subs subs2 subs3\n      -> similar_subs subs1 subs3.\n  Proof.\n    introv h; revert k subs3; induction h; introv q; auto;\n      inversion q; subst; auto.\n    constructor; eauto 3 with comp.\n  Qed.\n  Hint Resolve similar_subs_trans : comp.\n\n  Lemma M_break_preserves_similar_subs :\n    forall {n} {S} {Lv} {Sp}\n           (sm   : M_n n S)\n           (subs : n_procs n)\n           (F    : n_procs n -> S -> option (LocalSystem _ _))\n           (ls   : LocalSystem Lv Sp),\n      (forall subs1 subs2 out,\n          sm subs1 = (subs2, out)\n          -> similar_subs subs subs1\n          -> similar_subs subs1 subs2)\n      -> (forall subs' out ls,\n             F subs' out = Some ls\n             -> similar_subs subs subs'\n             -> similar_subs subs' ls)\n      -> M_break sm subs F = Some ls\n      -> similar_subs subs ls.\n  Proof.\n    introv impsm impF h.\n    unfold M_break in h.\n    remember (sm subs) as k; repnd; symmetry in Heqk.\n    apply impsm in Heqk; eauto 3 with comp.\n  Qed.\n\n(*  Lemma M_run_update_on_list_preserves_subs :\n    forall {n : nat} {nm : CompName} {S : Type} {Lv Sp}\n           (l  : oplist (cio_I (fio nm)))\n           (s  : S)\n           (sm : M_Update n nm S)\n           subs F\n           (ls : LocalSystem Lv Sp),\n      (forall s i subs1 subs2 out, sm s i subs1 = (subs2, out) -> similar_subs subs subs1 -> similar_subs subs1 subs2)\n      -> (forall subs' out ls, F subs' out = Some ls -> similar_subs subs subs' -> similar_subs subs' (ls_subs ls))\n      -> (forall subs, F subs None = None)\n      -> M_break (M_run_update_on_list s sm l) subs F = Some ls\n      -> similar_subs subs ls.\n  Proof.\n    induction l; introv impsm impF fnone h; simpl in *; autorewrite with comp in *; simpl in *; ginv;\n      simpl in *; eauto 3 with comp;[].\n\n    rewrite M_break_M_on_some_option_map in h; simpl; auto;[].\n    apply map_option_Some in h; exrepnd; subst; simpl in *.\n    symmetry in h0.\n\n    rewrite M_break_bind in h0.\n    erewrite eq_M_break in h0;\n      [|introv;rewrite @M_break_M_on_some_option_map;[reflexivity|];simpl;auto].\n\n    eapply M_break_preserves_similar_subs;[| |eauto];[|]; simpl.\n\n    { introv h; eapply impsm; eauto. }\n\n    introv h sim.\n    apply map_option_Some in h; exrepnd; simpl in *; subst.\n    symmetry in h1.\n\n    apply IHl in h1; auto.\n\n    { introv h q; eapply impsm; eauto; eauto 3 with comp. }\n\n    { introv h q; eapply impF; eauto; eauto 3 with comp. }\n  Qed.*)\n\n  Lemma similar_subs_preserves_find_name :\n    forall {n} cn (subs1 subs2 : n_procs n) s,\n      similar_subs subs1 subs2\n      -> find_name cn subs1 = Some s\n      -> exists s', find_name cn subs2 = Some s' /\\ similar_sms s s'.\n  Proof.\n    induction subs1; introv sim h; simpl in *; ginv;[].\n    inversion sim; subst; clear sim.\n    inversion simp; clear simp; auto; subst; simpl in *.\n    match goal with\n    | [ H : context[p1] |- _ ] => rename H into h1\n    end.\n    match goal with\n    | [ H : context[p2] |- _ ] => rename H into h2\n    end.\n    apply Eqdep.EqdepTheory.inj_pair2 in h1; subst; simpl in *; auto.\n    apply Eqdep.EqdepTheory.inj_pair2 in h2; subst; simpl in *; auto.\n    dest_cases w; subst; simpl in *; ginv; eauto.\n  Qed.\n\n  Lemma state_of_component_if_similar :\n    forall {n} cn (subs1 subs2 : n_procs n) s,\n      similar_subs subs1 subs2\n      -> state_of_component cn subs1 = Some s\n      -> exists s', state_of_component cn subs2 = Some s'.\n  Proof.\n    introv sim h.\n    unfold state_of_component in *.\n    apply option_map_Some in h; exrepnd; subst.\n    eapply similar_subs_preserves_find_name in h1;[|eauto].\n    exrepnd; rewrite h1; simpl; eauto.\n  Qed.\n  Hint Resolve state_of_component_if_similar : comp.\n\n  (* TODO: why is that just for the main component? *)\n  Definition ls_preserves_subs {n} (ls : n_procs n) :=\n    forall (cn : CompName) (i : cio_I (fio cn)) (ls0 : n_procs n),\n      similar_subs ls ls0\n      -> similar_subs ls0 (M_run_ls_on_input_ls ls0 cn i).\n\n  Definition sys_preserves_subs {F} (sys : M_USystem F) :=\n    forall cn, ls_preserves_subs (sys cn).\n\n  Lemma M_run_ls_on_input_preserves_ls_preserves_subs :\n    forall {n} (ls : n_procs n) cn i,\n      ls_preserves_subs ls\n      -> ls_preserves_subs (M_run_ls_on_input_ls ls cn i).\n  Proof.\n    introv pres sim.\n    apply pres; eauto 3 with comp.\n  Qed.\n\n  Lemma M_run_ls_on_inputs_preserves_ls_preserves_subs :\n    forall {n} cn l (ls1 ls2 : n_procs n),\n      M_run_ls_on_op_inputs ls1 cn l = Some ls2\n      -> ls_preserves_subs ls1\n      -> ls_preserves_subs ls2.\n  Proof.\n    induction l; introv run1 pres sim; simpl in *; tcsp; ginv; eauto 3 with comp.\n    apply map_option_Some in run1; exrepnd; subst; rev_Some.\n    apply IHl in run0; eauto 3 with comp.\n    eapply M_run_ls_on_input_preserves_ls_preserves_subs; eauto.\n  Qed.\n\n  Lemma ls_preserves_subs_implies_M_run_update_on_list :\n    forall {n} cn L (ls : n_procs n) ls',\n      ls_preserves_subs ls\n      -> M_run_ls_on_op_inputs ls cn L = Some ls'\n      -> similar_subs ls ls'.\n  Proof.\n    induction L; introv pres q; simpl in *; autorewrite with comp;\n      tcsp; ginv; eauto 3 with comp.\n    apply map_option_Some in q; exrepnd; subst; simpl in *; rev_Some.\n    apply IHL in q0; eauto 4 with comp.\n    eapply M_run_ls_on_input_preserves_ls_preserves_subs; eauto.\n  Qed.\n  Hint Resolve ls_preserves_subs_implies_M_run_update_on_list : comp.\n\n(*  Lemma ls_preserves_subs_implies_M_run_update_on_list2 :\n    forall {Lv Sp} (ls : LocalSystem Lv Sp) L s,\n      ls_preserves_subs ls\n      -> M_break\n           (M_run_update_on_list\n              s\n              (sm_update (ls_main ls))\n              L)\n           (ls_subs ls)\n         (fun subs2 _ => similar_subs (ls_subs ls) subs2).\n  Proof.\n    introv pres.\n    pose proof (ls_preserves_subs_implies_M_run_update_on_list ls L s (ls_subs ls) pres) as q.\n    unfold M_break in *; dest_cases w; apply q; eauto 3 with comp.\n  Qed.\n  Hint Resolve ls_preserves_subs_implies_M_run_update_on_list2 : comp.*)\n\n  Lemma M_run_ls_on_op_inputs_app :\n    forall {n}\n           (ls : n_procs n)\n           {cn}\n           (l k : oplist (cio_I (fio cn))),\n      M_run_ls_on_op_inputs ls cn (l ++ k)\n      = on_some\n          (M_run_ls_on_op_inputs ls cn l)\n          (fun ls' => M_run_ls_on_op_inputs ls' cn k).\n  Proof.\n    introv; revert ls k; induction l; introv; simpl; auto.\n    unfold on_some.\n    rewrite map_option_map_option.\n    destruct a; simpl; auto.\n    unfold option_compose2; simpl.\n    rewrite IHl; auto.\n  Qed.\n\n  Lemma M_run_ls_on_inputs_app :\n    forall {n}\n           (ls : n_procs n)\n           {cn}\n           (l k : list (cio_I (fio cn))),\n      M_run_ls_on_inputs ls cn (l ++ k)\n      = let ls' := M_run_ls_on_inputs ls cn l in\n        M_run_ls_on_inputs ls' cn k.\n  Proof.\n    introv; revert ls k; induction l; introv; simpl; auto.\n  Qed.\n\n  Lemma M_state_sys_on_event_some_between :\n    forall {eo : EventOrdering} (e1 e2 : Event) {F} (sys : M_USystem F) cn (s : sf cn),\n      sys_preserves_subs sys\n      -> e1 ⊑ e2\n      -> M_state_sys_on_event sys e2 cn = Some s\n      -> exists s', M_state_sys_on_event sys e1 cn = Some s'.\n  Proof.\n    introv pres lte eqs.\n    apply localHappenedBeforeLe_implies_or2 in lte; repndors; subst.\n    { eexists; eauto. }\n\n    unfold M_state_sys_on_event in *; simpl in *.\n\n    assert (loc e1 = loc e2) as eqloc by eauto 3 with eo.\n    rewrite <- eqloc in eqs.\n\n    pose proof (pres (loc e1)) as pres.\n    remember (sys (loc e1)) as ls; clear Heqls.\n    clear sys.\n\n    unfold M_state_ls_on_event in *; simpl in *.\n    unfold M_run_ls_on_event in *; simpl in *.\n    unfold M_run_ls_before_event in *; simpl in *.\n\n    apply map_option_Some in eqs; exrepnd; rev_Some.\n    apply map_option_Some in eqs1; exrepnd; rev_Some.\n    apply map_option_Some in eqs2; exrepnd; rev_Some; ginv.\n\n    pose proof (local_happened_before_implies_history_app2 _ _ lte) as q; exrepnd.\n\n    assert (History(e1) ++ e1 :: l = snoc (History(e1)) e1 ++ l) as eqx.\n    { simpl.\n      rewrite snoc_as_app.\n      rewrite <- app_assoc; simpl; auto. }\n    rewrite eqx in q0; clear eqx.\n    rewrite q0 in eqs1; clear q0.\n\n    rewrite map_app in eqs1.\n    rewrite map_snoc in eqs1.\n    rewrite M_run_ls_on_op_inputs_app in eqs1.\n    rewrite M_run_ls_on_op_inputs_snoc in eqs1.\n    apply map_option_Some in eqs1; exrepnd; rev_Some.\n    apply map_option_Some in eqs1; exrepnd; rev_Some.\n    apply map_option_Some in eqs4; exrepnd; rev_Some; ginv.\n\n    allrw; simpl in *.\n\n    applydup @M_run_ls_on_inputs_preserves_ls_preserves_subs in eqs1 as pres1; auto;[].\n    pose proof (M_run_ls_on_input_preserves_ls_preserves_subs a2 (msg_comp_name (fls_space F (loc e1))) a3) as pres2; autodimp pres2 hyp.\n    applydup @M_run_ls_on_inputs_preserves_ls_preserves_subs in eqs3 as pres3; auto;[].\n\n    applydup @ls_preserves_subs_implies_M_run_update_on_list in eqs3 as sim1; auto;[].\n    pose proof (pres3 (msg_comp_name (fls_space F(loc e1))) a1 a0) as sim2; autodimp sim2 hyp; eauto 3 with comp.\n\n    eapply similar_subs_trans in sim2;[|exact sim1].\n    apply similar_subs_sym in sim2.\n    eapply state_of_component_if_similar in eqs0; try exact sim2; auto.\n  Qed.\n\n  Definition M_output_ls_on_this_one_event\n             {Lv Sp}\n             (ls : LocalSystem Lv Sp)\n             {eo : EventOrdering}\n             (e  : Event) : DirectedMsgs :=\n    olist2list\n      (on_some\n         (trigger_op e)\n         (M_run_ls_on_input_out ls (msg_comp_name Sp))).\n\n  Definition M_output_ls_on_event\n             {Lv Sp}\n             (ls : LocalSystem Lv Sp)\n             {eo : EventOrdering}\n             (e  : Event) : DirectedMsgs :=\n    olist2list\n      (option_map\n         (fun ls' => M_output_ls_on_this_one_event ls' e)\n         (M_run_ls_before_event ls e)).\n\n  Definition M_output_sys_on_event\n             {F}\n             (sys : M_USystem F)\n             {eo  : EventOrdering}\n             (e   : Event) : DirectedMsgs :=\n    M_output_ls_on_event (sys (loc e)) e.\n\n  (* REDO WITHOUT UNFOLDING MONAD *)\n  Lemma M_output_ls_on_event_as_run_before :\n    forall {Lv Sp}\n           (ls : LocalSystem Lv Sp)\n           {eo : EventOrdering}\n           (e  : Event),\n      M_output_ls_on_event ls e\n      = match M_run_ls_before_event ls e with\n        | Some ls' => M_output_ls_on_this_one_event ls' e\n        | None => []\n        end.\n  Proof.\n    introv.\n    unfold M_output_ls_on_event.\n    remember (M_run_ls_before_event ls e) as run; destruct run; simpl; auto.\n  Qed.\n\n  Lemma M_output_ls_on_event_as_run :\n    forall {Lv Sp}\n           (ls : LocalSystem Lv Sp)\n           {eo : EventOrdering}\n           (e  : Event)\n           (m  : DirectedMsg),\n      In m (M_output_ls_on_event ls e)\n      <->\n      exists (ls' : LocalSystem _ _),\n        M_run_ls_before_event ls e = Some ls'\n        /\\ In m (M_output_ls_on_this_one_event ls' e).\n  Proof.\n    introv.\n    rewrite M_output_ls_on_event_as_run_before.\n    remember (M_run_ls_before_event ls e) as w; symmetry in Heqw.\n    destruct w; simpl; split; intro h; exrepnd; tcsp; ginv;[].\n    eexists; dands; eauto.\n  Qed.\n\n  Lemma M_output_ls_on_event_implies_run :\n    forall {Lv Sp}\n           (ls : LocalSystem Lv Sp)\n           {eo : EventOrdering}\n           (e  : Event)\n           (m  : DirectedMsg),\n      In m (M_output_ls_on_event ls e)\n      ->\n      exists (ls' : LocalSystem _ _),\n        M_run_ls_before_event ls e = Some ls'\n        /\\ In m (M_output_ls_on_this_one_event ls' e).\n  Proof.\n    introv h.\n    apply M_output_ls_on_event_as_run; auto.\n  Qed.\n\n\n  (* XXXXXXXXXXXXXXXXXX *)\n\n  (*\n  (* FIX THE NEXT 4 DEFINITIONS! *)\n\n  (* we have to rewrite [AXIOM_authenticated_messages_were_sent_or_byz]\n     so that not all keys are used to authenticated the data at [e'] *)\n  Definition included_keys_proc\n             {n} {nm} : n_proc n nm -> local_key_map -> Prop :\n      match nm with\n      | MkCompName \"KEY\" _ =>\n        fun sm ks => sm2state sm\n      | _ => fun sm ks => True\n      end.\n\n\n  Definition included_keys_nproc\n             {n}\n             (p  : n_nproc n)\n             (ks : local_key_map) : Prop :\n      let (nm,sm) := p in\n      included_keys_proc sm ks\n\n  Fixpoint included_keys\n           {n}\n           (l  : n_procs n)\n           (ks : local_key_map) : Prop :=\n    match l with\n    | [] => True\n    | p :: ps => included_keys_nproc p ks /\\ included_keys ps ks\n    end.\n\n  (* get all keys from the KEY components *)\n  Definition AXIOM_M_correct_keys_local_sys\n             (sys : LocalSystem)\n             {eo  : EventOrdering}\n             (e   : Event) : Prop :=\n    forall st,\n      M_state_sm_before_event (ls_main sys) e = st\n      -> st >p>= (fun sop => match sop with\n                             | Some s => ret _ (keys e = K s)\n                             | None => ret _ True\n                             end).\n\n  Definition AXIOM_M_correct_keys_sys\n             (sys : M_USystem)\n             {eo  : EventOrdering}\n             (K   : system_key_constraint sys) : Prop :=\n    forall e (i : name) e',\n      has_correct_trace_before e i\n      -> e' ≼ e\n      -> loc e' = i\n      -> AXIOM_M_correct_keys_local_sys (sys i) e' (K i).\n*)\n\n\n(*  Definition AXIOM_M_authenticated_messages_were_sent_or_byz_usys\n             (eo : EventOrdering) (s : M_USystem) :=\n    fun p =>\n      @AXIOM_authenticated_messages_were_sent_or_byz\n        pd\n        pn\n        pk\n        pat\n        paf\n        pm\n        dtc\n        eo\n        pda\n        cad\n        gms\n        (fun eo e => snd (M_output_system_on_event_ldata s e p)).*)\n\n  (* ============== Computations on Byzantine events ============== *)\n\n  Fixpoint sm2at {n} {cn}\n    : forall (sm : n_proc n cn), n_proc_at (sm2level sm) cn :=\n    match n with\n    | 0 => fun sm => match sm with end\n    | S m => fun sm =>\n               match sm with\n               | sm_or_at q => q\n               | sm_or_sm q => sm2at q\n               end\n    end.\n\n  Record trustedSM :=\n    MktrustedSM\n      {\n        tsm_level : nat;\n        tsm_kind  : CompNameKind;\n        tsm_space : CompNameSpace;\n        tsm_sm    : n_proc_at tsm_level (MkCN tsm_kind tsm_space true);\n      }.\n\n  Definition tsm2pcn (tsm : trustedSM) : PreCompName :=\n    MkPreCompName (tsm_kind tsm) (tsm_space tsm).\n  Coercion tsm2pcn : trustedSM >-> PreCompName.\n\n  Definition state_of_trusted (tsm : trustedSM) : tsf tsm :=\n    sm_state (tsm_sm tsm).\n\n  Definition updateTrustedSM (tsm : trustedSM) : tsf tsm -> trustedSM :=\n    match tsm with\n    | MktrustedSM l k s sm => fun new => MktrustedSM l k s (update_state sm new)\n    end.\n\n(*  Definition haltTrustedSM (tsm : trustedSM) : trustedSM :=\n    match tsm with\n    | MktrustedSM l k s sm => MktrustedSM l k s (halt_machine sm)\n    end.*)\n\n  Fixpoint find_trusted {n:nat} (l : n_procs n) : n_procs n :=\n    match l with\n    | [] => []\n    | comp :: rest =>\n      if is_trusted comp then comp :: find_trusted rest\n      else find_trusted rest\n    end.\n\n  Definition find_trusted_sub {L S} (ls : LocalSystem L S) : n_procs L :=\n    find_trusted ls.\n\n  (* We run the trusted with no subcomponents *)\n(*  Definition run_trustedSM_on_trigger_info {D}\n             (tsm : trustedSM)\n             (ti  : trigger_info D) : trustedSM * iot_output (iot_fun tsm) :=\n    match ti with\n    | trigger_info_data d => (tsm, iot_def_output)\n    | trigger_info_arbitrary => (tsm, iot_def_output)\n    | trigger_info_trusted i =>\n      match sm_update (tsm_sm tsm) (state_of_trusted tsm) i [] with\n      | (_, (Some s, out)) => (updateTrustedSM tsm s, out)\n      | (_, (None, out)) => (haltTrustedSM tsm, out)\n      end\n    end.*)\n\n(*  Fixpoint run_trustedSM_on_trigger_info_list {D}\n           (tsm : trustedSM)\n           (l   : list (trigger_info D)) : trustedSM :=\n    match l with\n    | [] => tsm\n    | ti :: l =>\n      run_trustedSM_on_trigger_info_list\n        (fst (run_trustedSM_on_trigger_info tsm ti))\n        l\n    end.*)\n\n(*  Definition M_find_trusted {n} : M_n n (option trustedSM) :=\n    fun subs => ([], find_trusted subs).*)\n\n(*  Definition run_trusted_on_trigger_info_list {n} {D}\n             (l : list (trigger_info D)) : M_n n (option trustedSM) :=\n    M_find_trusted\n      >>o= fun tsm => ret _ (Some (run_trustedSM_on_trigger_info_list tsm l)).*)\n\n(*  Definition M_trusted (T : Type) := T [+] trustedSM.\n  Definition M_trusted_with_out (T : Type) := (option T * DirectedMsgs) [+] (trustedSM * iot_output).\n  Definition M_trusted_out (T : Type) := T [+] iot_output.\n  Definition M_trusted_msgs := M_trusted_out DirectedMsgs.\n\n  Definition on_M_trusted {T} {A}\n             (x : M_trusted T)\n             (F : T -> A)\n             (G : trustedSM -> A) : A :=\n    match x with\n    | inl t => F t\n    | inr tsm => G tsm\n    end.\n\n  Definition on_M_trusted_out {T} {A}\n             (x : M_trusted_out T)\n             (F : T -> A)\n             (G : iot_output -> A) : A :=\n    match x with\n    | inl t => F t\n    | inr tsm => G tsm\n    end.\n\n  Definition on_M_trusted_with_out {T} {A}\n             (x : M_trusted_with_out T)\n             (F : (option T * DirectedMsgs) -> A)\n             (G : (trustedSM * iot_output) -> A) : A :=\n    match x with\n    | inl t => F t\n    | inr tsm => G tsm\n    end.\n\n  (* non-trusted *)\n  Definition M_nt {T : Type} (t : T) : M_trusted T := inl t.\n  (* trusted *)\n  Definition M_t {T : Type} (tsm : trustedSM) : M_trusted T := inr tsm.\n\n  (* non-trusted with output *)\n  Definition M_nt_w_o {T : Type} (t : option T * DirectedMsgs) : M_trusted_with_out T := inl t.\n  (* trusted with ouput *)\n  Definition M_t_w_o {T : Type} (x : trustedSM * iot_output) : M_trusted_with_out T := inr x.\n\n  (* non-trusted output *)\n  Definition M_nt_o {T : Type} (t : T) : M_trusted_out T := inl t.\n  (* trusted ouput *)\n  Definition M_t_o {T : Type} (x : iot_output) : M_trusted_out T := inr x.\n\n  Definition to_op_M_trusted {T} (mt : M_trusted_with_out T) : option (M_trusted T) :=\n    on_M_trusted_with_out\n      mt\n      (fun x => option_map M_nt (fst x))\n      (fun x => Some (M_t (fst x))).\n\n  Definition to_M_trusted_out {T} (mt : M_trusted_with_out T) : M_trusted_msgs :=\n    on_M_trusted_with_out\n      mt\n      (fun x => M_nt_o (snd x))\n      (fun x => M_t_o (snd x)).\n\n  Definition M_run_trusted_on_trigger_info_list {n} {S} {D}\n             (l : list (trigger_info D)) : M_n n (option (M_trusted S)) :=\n    (run_trusted_on_trigger_info_list l)\n      >>o= fun tsm => ret _ (Some (M_t tsm)).*)\n\n(*  (* As opposed to [M_run_update_on_list] below, this one starts running the (first)\n     trusted component as soon as we encounter an abnormal event, discarding the\n     other subcomponents (meaning that a trusted component cannot use other components\n     with this simple implementation).  Once we start running the trusted component,\n     the normal events are considered as arbitrary/byzantine events. *)\n  Fixpoint M_byz_run_update_on_list {S} {n} {cn}\n           (s   : S)\n           (upd : M_Update n cn S)\n           (l   : list (trigger_info (cio_I (fio cn)))) : M_n n (option (M_trusted S)) :=\n    match l with\n    | [] => ret _ (Some (M_nt s))\n    | ti :: k =>\n      if_trigger_info_data\n        ti\n        (fun m =>\n           (upd s m)\n             >>= fun so =>\n                   (fst so)\n                     >>o>> fun s' => M_byz_run_update_on_list s' upd k)\n        (M_run_trusted_on_trigger_info_list l)\n    end.\n\n  Definition M_op2M_trusted_with_out {n} {T}\n             (p : M_n n (op_state_out T))\n    : M_n n (option (M_trusted_with_out T)) :=\n    p >>o= fun t => ret _ (Some (M_nt_w_o t)).\n\n  Definition M_byz_run_update_on_event {S} {n} {k}\n             (s   : S)\n             (upd : M_Update n (msg_comp_name k) S)\n             {eo  : EventOrdering}\n             (e   : Event) : M_n n (option (M_trusted_with_out S)) :=\n    (M_byz_run_update_on_list s upd (map trigger (@localPreds pn pk pm _ _ eo e)))\n      >>o= fun mt =>\n             on_M_trusted\n               mt\n               (fun s =>\n                  if_trigger_info_data\n                    (trigger e)\n                    (fun m => (upd s m) >>= fun so => ret _ (Some (M_nt_w_o so)))\n                    (M_find_trusted >>o= fun tsm => ret _ (Some (M_t_w_o (run_trustedSM_on_trigger_info tsm (trigger e))))))\n               (fun tsm => ret _ (Some (M_t_w_o (run_trustedSM_on_trigger_info tsm (trigger e))))).\n\n  Definition M_byz_run_sm_on_event {n} {k}\n             (sm : n_proc n (msg_comp_name k))\n             {eo : EventOrdering}\n             (e  : Event)\n    : M_n (sm2level sm) (option (M_trusted_with_out (sf (msg_comp_name k)))) :=\n    M_byz_run_update_on_event (sm2state sm) (sm2update sm) e.\n\n  Definition M_byz_output_sm_on_event {n} {k}\n             (sm : n_proc n (msg_comp_name k))\n             {eo : EventOrdering}\n             (e  : Event)\n    : M_n (sm2level sm) (option M_trusted_msgs) :=\n    (M_byz_run_sm_on_event sm e)\n      >>o= fun mt => ret _ (Some (to_M_trusted_out mt)).\n\n  Definition on_Some_t_o {T} (op : option T) (f : T -> M_trusted_msgs):=\n    match op with\n    | Some t => f t\n    | None => M_nt_o []\n    end.*)\n\n  (*Definition to_opt_snd\n             {A B}\n             (x : A * B)\n    : A * option B :=\n    let (a,b) := x in (a, Some b).*)\n\n(*  Definition M_byz_run_ls_on_input\n             {lvl Sp}\n             (ls : LocalSystem lvl Sp)\n             cn\n             (i  : cio_I (fio cn)) : option (LocalSystem lvl cn) * option (cio_O (fio cn)) :=\n    match ls_status ls with\n    | ls_is_ok  => to_opt_snd (M_run_ls_on_input ls i)\n    | ls_is_byz => (Some (upd_ls_byz ls), None)\n    end.*)\n\n  Definition pre2trusted (p : PreCompName) : CompName :=\n    MkCompName p true.\n\n  Definition trigger_info2out {A} cn (i : trigger_info A) : Type :=\n    match i with\n    | trigger_info_data _ => cio_O (fio cn)\n    | trigger_info_arbitrary => False\n    | trigger_info_trusted j => iot_output (iot_fun (it_name j))\n    end.\n\n  Definition event2out space {eo : EventOrdering} (e : Event) : Type :=\n    trigger_info2out (msg_comp_name space) (trigger e).\n\n  Inductive M_byz_output {A} cn (i : trigger_info A) :=\n  | m_byz_output_msg   (m : cio_O (fio cn))\n  | m_byz_output_event (j : trigger_info2out cn i)\n  | m_byz_output_no.\n\n  Definition event2M_byz_output space {eo : EventOrdering} (e : Event) :=\n    M_byz_output (msg_comp_name space) (trigger e).\n\n(*  Definition event2out_to_byz {Sp} {eo : EventOrdering} {e}\n             (x : event2out Sp e) : event2M_byz_output Sp e.\n  Proof.\n    unfold event2out, event2M_byz_output in *.\n    destruct (trigger e).\n    { exact (m_byz_output_msg _ _ x). }\n    { destruct x. }\n    { exact (m_byz_output_event _ _ x). }\n  Defined.\n\n  Definition op_event2out_to_byz {Sp} {eo : EventOrdering} {e}\n             (x : option (event2out Sp e))\n    : event2M_byz_output Sp e :=\n    match x with\n    | Some z => event2out_to_byz z\n    | None => m_byz_output_no _ _\n    end.*)\n\n(*  Definition trigger_info2state {A} cn (i : trigger_info A) : Type :=\n    match i with\n    | trigger_info_data d => sf cn\n    | trigger_info_arbitrary => False\n    | trigger_info_trusted j => sf (pre2trusted (it_name j))\n    end.\n\n  Definition event2state cn {eo : EventOrdering} (e : Event) : Type :=\n    trigger_info2out cn (trigger e).*)\n\n  Fixpoint procs2byz {n} (ls : n_procs n) : n_procs n :=\n    match ls with\n    | [] => []\n    | comp :: rest =>\n      if is_trusted comp then comp :: procs2byz rest\n      else procs2byz rest\n    end.\n\n  Definition M_run_ls_on_trusted\n             {n}\n             (ls : n_procs n)\n             (i  : ITrusted) : n_procs n * option (cio_O (fio (pre2trusted (it_name i)))) :=\n    M_run_ls_on_input ls (pre2trusted (it_name i)) (it_input i).\n\n  Definition M_byz_run_ls_on_input\n             {n}\n             (ls : n_procs n)\n             cn\n             (i  : trigger_info (cio_I (fio cn)))\n    : n_procs n * option (trigger_info2out cn i) :=\n    match i with\n    | trigger_info_data d => M_run_ls_on_input ls cn d\n    | trigger_info_arbitrary => (procs2byz ls, None)\n    | trigger_info_trusted j => M_run_ls_on_trusted (procs2byz ls) j\n    end.\n\n  Definition to_snd_byz_msg\n             {A} {B} {i : trigger_info B} {cn}\n             (x : A * option (cio_O (fio cn)))\n  : A * M_byz_output cn i :=\n    match x with\n    | (a,Some o) => (a,m_byz_output_msg _ _ o)\n    | (a,None) => (a,m_byz_output_msg _ _ (cio_default_O (fio cn)))\n    end.\n\n  Lemma mk_ti2out_trusted\n        {A : Type} {cn : CompName} {t : ITrusted}\n        (x : iot_output (iot_fun (it_name t)))\n    : @trigger_info2out A cn (trigger_info_trusted t).\n  Proof.\n    exact x.\n  Defined.\n\n  Lemma to_snd_byz_event\n        {I A : Type} {cn : CompName}{t : ITrusted}\n        (x : A * option (iot_output (iot_fun (it_name t))))\n    : A * @M_byz_output I cn (trigger_info_trusted t).\n  Proof.\n    destruct x as [a o]; simpl in *.\n    destruct o as [o|].\n    { exact (a,m_byz_output_event _ _ (mk_ti2out_trusted o)). }\n    { exact (a,m_byz_output_no _ _). }\n  Defined.\n\n  (*(* Similar to [M_byz_run_ls_on_trig], but tags the output here *)\n  Definition M_byz_run_ls_on_input_B\n             {Lv Sp}\n             (ls : LocalSystem Lv Sp)\n             cn\n             (i  : trigger_info (cio_I (fio cn)))\n    : LocalSystem Lv Sp * M_byz_output cn i :=\n    match i with\n    | trigger_info_data d => to_snd_byz_msg (M_run_ls_on_input ls cn d)\n    | trigger_info_arbitrary => (ls2byz ls, m_byz_output_no _ _)\n    | trigger_info_trusted j => to_snd_byz_event (M_run_ls_on_trusted (ls2byz ls) j)\n    end.*)\n\n  Definition M_byz_run_ls_on_one_event\n             {Lv Sp}\n             (ls : LocalSystem Lv Sp)\n             {eo : EventOrdering}\n             (e  : Event)\n    : LocalSystem Lv Sp * option (event2out Sp e) :=\n    M_byz_run_ls_on_input ls (msg_comp_name Sp) (trigger e).\n\n  (*Definition M_byz_run_ls_on_one_event_B\n             {Lv Sp}\n             (ls : LocalSystem Lv Sp)\n             {eo : EventOrdering}\n             (e  : Event)\n    : LocalSystem Lv Sp * event2M_byz_output Sp e :=\n    M_byz_run_ls_on_input_B ls (msg_comp_name Sp) (trigger e).*)\n\n  Fixpoint M_byz_run_ls_on_inputs\n           {n}\n           (ls : n_procs n)\n           cn\n           (l  : list (trigger_info (cio_I (fio cn))))\n    : n_procs n :=\n    match l with\n    | [] => ls\n    | i :: rest =>\n      let ls' := fst (M_byz_run_ls_on_input ls cn i) in\n      M_byz_run_ls_on_inputs ls' cn rest\n    end.\n\n  Definition M_byz_run_ls_before_event\n             {Lv Sp}\n             (ls : LocalSystem Lv Sp)\n             {eo : EventOrdering}\n             (e  : Event) : LocalSystem Lv Sp :=\n    M_byz_run_ls_on_inputs\n      ls\n      (msg_comp_name Sp)\n      (map trigger (@localPreds pn pk pm _ _ eo e)).\n\n  Definition M_byz_output_ls_on_event\n             {L S}\n             (ls : LocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event) : option (event2out S e) :=\n    let ls' := M_byz_run_ls_before_event ls e in\n    snd (M_byz_run_ls_on_one_event ls' e).\n\n  (*Definition M_byz_output_ls_on_event_B\n             {L S}\n             (ls : LocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event) : event2M_byz_output S e :=\n    let ls' := M_byz_run_ls_before_event ls e in\n    snd (M_byz_run_ls_on_one_event_B ls' e).*)\n\n  Definition M_byz_output_sys_on_event\n             {F}\n             (sys : M_USystem F)\n             {eo  : EventOrdering}\n             (e   : Event) : option (event2out _ e) :=\n    M_byz_output_ls_on_event (sys (loc e)) e.\n\n  (*Definition M_byz_output_sys_on_event_B\n             {F}\n             (sys : M_USystem F)\n             {eo  : EventOrdering}\n             (e   : Event) : event2M_byz_output _ e :=\n    M_byz_output_ls_on_event_B (sys (loc e)) e.*)\n\n(*  Definition M_byz_output_sys_on_event_to_byz\n             {F}\n             (sys : M_USystem F)\n             {eo  : EventOrdering}\n             (e   : Event) : iot_output :=\n    on_M_trusted_out\n      (M_byz_output_sys_on_event sys e)\n      (fun _ => iot_def_output)\n      (fun out => out).*)\n\n(*  Definition M_byz_run_sm_on_list {n} {cn}\n             (sm : n_proc n cn)\n             (l  : list (trigger_info (cio_I (fio cn))))\n    : M_n (sm2level sm) (option (M_trusted (sf cn))) :=\n    M_byz_run_update_on_list (sm2state sm) (sm2update sm) l.*)\n\n(*  Definition M_byz_state_sm_before_event {n} {k}\n             (sm : n_proc n (msg_comp_name k))\n             {eo : EventOrdering}\n             (e  : Event)\n    : M_n (sm2level sm) (option (M_trusted (sf (msg_comp_name k)))) :=\n    M_byz_run_sm_on_list sm (map trigger (@localPreds pn pk pm _ _ eo e)).*)\n\n(*  Definition map_untrusted {T} {A}\n             (x : M_trusted T)\n             (F : T -> A) : M_trusted A :=\n    on_M_trusted x (fun t => M_nt (F t)) M_t.*)\n\n(*  Definition map_untrusted_op {T} {A}\n             (x : M_trusted T)\n             (F : T -> option A) : option (M_trusted A) :=\n    on_M_trusted\n      x\n      (fun t => option_map M_nt (F t))\n      (fun tsm => Some (M_t tsm)).*)\n\n(*  Definition map_op_untrusted {T} {A}\n             (x : option (M_trusted T))\n             (F : T -> A) : option (M_trusted A) :=\n    option_map (fun mt => map_untrusted mt F) x.*)\n\n(*  Definition map_op_untrusted_op {T} {A}\n             (x : option (M_trusted T))\n             (F : T -> option A) : option (M_trusted A) :=\n    map_option (fun mt => map_untrusted_op mt F) x.*)\n\n(*  Definition M_byz_run_ls_before_event\n             {L S}\n             (ls : MLocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event) : option (M_trusted (LocalSystem _ _)) :=\n    M_break\n      (M_byz_state_sm_before_event (at2sm (ls_main ls)) e)\n      (ls_subs ls)\n      (fun subs' out =>\n         map_op_untrusted\n           out\n           (fun s => upd_ls_main_state_and_subs ls s subs')).*)\n\n  Definition M_byz_state_ls_before_event\n             {L S}\n             (ls : LocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event)\n             (cn : CompName) : option (sf cn) :=\n    let ls' := M_byz_run_ls_before_event ls e in\n    state_of_component cn ls'.\n\n  Definition M_byz_state_sys_before_event\n             {F}\n             (sys : M_USystem F)\n             {eo  : EventOrdering}\n             (e   : Event)\n             (cn  : CompName) : option (sf cn) :=\n    M_byz_state_ls_before_event (sys (loc e)) e cn.\n\n(*  Definition state_of_trusted_in_ls {L S} (ls : LocalSystem L S) : option tsf :=\n    option_map state_of_trusted (find_trusted_sub ls).*)\n\n(*  Definition M_byz_state_ls_before_event_of_trusted\n             {L S}\n             (ls : MLocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event) : option tsf :=\n    map_option\n      (fun mt =>\n         on_M_trusted\n           mt\n           state_of_trusted_in_ls\n           (fun tsm => Some (state_of_trusted tsm)))\n      (M_byz_run_ls_before_event ls e).*)\n\n(*  Definition M_byz_state_sys_before_event_of_trusted\n             {F}\n             (sys : M_USystem F)\n             {eo  : EventOrdering}\n             (e   : Event) : option tsf :=\n    M_byz_state_ls_before_event_of_trusted (sys (loc e)) e.*)\n\n(*  Definition M_byz_state_sm_on_event {n} {k}\n             (sm : n_proc n (msg_comp_name k))\n             {eo : EventOrdering}\n             (e  : Event) : M_n (sm2level sm) (option (M_trusted (sf (msg_comp_name k)))) :=\n  (M_byz_run_sm_on_event sm e)\n    >>o= fun mt => ret _ (to_op_M_trusted mt).*)\n\n  Definition M_byz_run_ls_on_event\n             {L S}\n             (ls : LocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event) : LocalSystem L S :=\n    let ls' := M_byz_run_ls_before_event ls e in\n    fst (M_byz_run_ls_on_one_event ls' e).\n\n  Definition M_byz_state_ls_on_event\n             {L S}\n             (ls : LocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event)\n             (cn : CompName) : option (sf cn) :=\n    let ls' := M_byz_run_ls_on_event ls e in\n    state_of_component cn ls'.\n\n  Definition M_byz_state_sys_on_event\n             {F}\n             (sys : M_USystem F)\n             {eo  : EventOrdering}\n             (e   : Event)\n             (cn  : CompName) : option (sf cn) :=\n    M_byz_state_ls_on_event (sys (loc e)) e cn.\n\n(*  Definition M_byz_state_ls_on_event_of_trusted\n             {L S}\n             (ls : MLocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event) : option tsf :=\n    map_option\n      (fun mt =>\n         on_M_trusted\n           mt\n           state_of_trusted_in_ls\n           (fun tsm => Some (state_of_trusted tsm)))\n      (M_byz_run_ls_on_event ls e).*)\n\n(*  Definition M_byz_state_sys_on_event_of_trusted\n             {F}\n             (sys : M_USystem F)\n             {eo  : EventOrdering}\n             (e   : Event) : option tsf :=\n    M_byz_state_ls_on_event_of_trusted (sys (loc e)) e.*)\n\n(*  Lemma M_byz_state_sys_before_event_of_trusted_unfold :\n    forall {F}\n           (sys : M_USystem F)\n           {eo  : EventOrdering}\n           (e   : Event),\n      M_byz_state_sys_before_event_of_trusted sys e\n      = map_option\n          (fun mt =>\n             on_M_trusted\n               mt\n               state_of_trusted_in_ls\n               (fun tsm => Some (state_of_trusted tsm)))\n          (M_byz_run_ls_before_event (sys (loc e)) e).\n  Proof.\n    tcsp.\n  Qed.*)\n\n(*  Lemma map_op_untrusted_option_map_M_nt :\n    forall {T A} (t : option T) (F : T -> A),\n      map_op_untrusted\n        (option_map M_nt t)\n        F\n      = option_map\n          (fun x => M_nt (F x))\n          t.\n  Proof.\n    introv.\n    destruct t; simpl; auto.\n  Qed.\n  Hint Rewrite @map_op_untrusted_option_map_M_nt : comp.*)\n\n(*  Lemma M_break_map_op_untrusted_option_map_M_nt :\n    forall {n S T A}\n           (t    : n_procs n -> S -> option T)\n           (F    : n_procs n -> S -> T -> A)\n           (sm   : M_n n S)\n           (subs : n_procs n),\n      M_break\n        sm subs\n        (fun subs' s =>\n           map_op_untrusted\n             (option_map M_nt (t subs' s))\n             (F subs' s))\n      = M_break\n          sm subs\n          (fun subs' s =>\n             option_map\n               (fun x => M_nt (F subs' s x))\n               (t subs' s)).\n  Proof.\n    introv.\n    apply eq_M_break; introv; autorewrite with comp; auto.\n  Qed.\n  Hint Rewrite @M_break_map_op_untrusted_option_map_M_nt : comp.*)\n\n  Definition M_byz_run_ls_on_this_one_event\n             {L S}\n             (ls : LocalSystem L S)\n             {eo : EventOrdering}\n             (e  : Event) : LocalSystem _ _ :=\n    fst (M_byz_run_ls_on_one_event ls e).\n\n(*  Lemma M_nt_inj :\n    forall {T} (t1 t2 : T),\n      M_nt t1 = M_nt t2\n      -> t1 = t2.\n  Proof.\n    introv h; injection h; auto.\n  Qed.*)\n\n(*  Lemma M_byz_run_ls_on_this_one_event_Some_M_nt_implies :\n    forall {L S}\n           (ls1 : MLocalSystem L S)\n           {eo  : EventOrdering}\n           (e   : Event)\n           (ls2 : MLocalSystem L S),\n      M_byz_run_ls_on_this_one_event ls1 e = Some (M_nt ls2)\n      ->\n      exists m,\n        msg_triggered_event m e\n        /\\ M_break\n             (sm_update (ls_main ls1) (sm_state (ls_main ls1)) m)\n             (ls_subs ls1)\n             (fun subs' out =>\n                option_map\n                  (fun s => upd_ls_main_state_and_subs ls1 s subs')\n                  (fst out)) = Some ls2.\n  Proof.\n    introv h.\n    unfold M_byz_run_ls_on_this_one_event in h.\n    remember (trigger e) as trig; destruct trig; simpl in *;\n      try (complete (apply option_map_Some in h; exrepnd; inversion h0));[].\n\n    exists d; dands; auto; eauto 3 with eo.\n    { unfold msg_triggered_event, trigger_op; allrw <-; simpl; auto. }\n    unfold M_break in *.\n    remember (sm_update (ls_main ls1) (sm_state (ls_main ls1)) d (ls_subs ls1)) as xx.\n    destruct xx; repnd; simpl in *.\n    apply option_map_Some in h; exrepnd; subst; simpl in *.\n    apply M_nt_inj in h0; subst; auto.\n  Qed.*)\n\n(*  Definition M_byz_run_M_trusted_ls_on_this_one_event\n             {L S}\n             (mt : M_trusted (MLocalSystem L S))\n             {eo : EventOrdering}\n             (e  : Event) : option (M_trusted (MLocalSystem L S)) :=\n    on_M_trusted\n      mt\n      (fun ls => M_byz_run_ls_on_this_one_event ls e)\n      (fun tsm => Some (M_t (fst (run_trustedSM_on_trigger_info tsm (trigger e))))).*)\n\n(*  Lemma on_M_trusted_map_untrusted :\n    forall {U T A} (x : M_trusted U) (f : U -> T) (F : T -> A) (G : trustedSM -> A),\n      on_M_trusted (map_untrusted x f) F G\n      = on_M_trusted x (compose F f) G.\n  Proof.\n    introv; unfold map_untrusted, on_M_trusted.\n    destruct x; simpl; auto.\n  Qed.\n  Hint Rewrite @on_M_trusted_map_untrusted : comp.*)\n\n(*  Lemma on_M_trusted_implies_or :\n    forall {T} {A}\n           (x : M_trusted T)\n           (F : T -> A)\n           (G : trustedSM -> A)\n           (a : A),\n      on_M_trusted x F G = a\n      -> (exists t, x = M_nt t /\\ a = F t)\n         \\/ (exists tsm, x = M_t tsm /\\ a = G tsm).\n  Proof.\n    introv h.\n    destruct x; simpl in *; subst; tcsp;[left|right]; eexists; dands; reflexivity.\n  Qed.*)\n\n(*  Lemma on_M_trusted_M_nt :\n    forall {T A} (x : T) (F : T -> A) (G : trustedSM -> A),\n      on_M_trusted (M_nt x) F G = F x.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite @on_M_trusted_M_nt : comp.*)\n\n(*  Lemma on_M_trusted_M_t :\n    forall {T A} (x : trustedSM) (F : T -> A) (G : trustedSM -> A),\n      on_M_trusted (M_t x) F G = G x.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite @on_M_trusted_M_t : comp.*)\n\n(*  Lemma M_break_on_M_trusted :\n    forall {n} {A} {S} {O}\n           (a    : M_trusted A)\n           (f    : A -> M_n n S)\n           (g    : trustedSM -> M_n n S)\n           (subs : n_procs n)\n           (F    : n_procs n -> S -> O),\n      M_break (on_M_trusted a f g) subs F\n      = on_M_trusted\n          a\n          (fun a => M_break (f a) subs F)\n          (fun tsm => M_break (g tsm) subs F).\n  Proof.\n    introv; destruct a; simpl; auto.\n  Qed.*)\n\n(*  Lemma eq_on_M_trusted :\n    forall {T} {A}\n           (x : M_trusted T)\n           (F1 F2 : T -> A)\n           (G1 G2 : trustedSM -> A),\n      (forall t, F1 t = F2 t)\n      -> (forall tsm, G1 tsm = G2 tsm)\n      -> on_M_trusted x F1 G1 = on_M_trusted x F2 G2.\n  Proof.\n    introv impa impb.\n    destruct x; simpl; tcsp.\n  Qed.*)\n\n  Lemma M_break_if_trigger_info_data :\n    forall {n} {S} {O} {D}\n           (a    : trigger_info D)\n           (f    : D -> M_n n S)\n           (g    : M_n n S)\n           (subs : n_procs n)\n           (F    : n_procs n -> S -> O),\n      M_break (if_trigger_info_data a f g) subs F\n      = if_trigger_info_data\n          a\n          (fun a => M_break (f a) subs F)\n          (M_break g subs F).\n  Proof.\n    introv; destruct a; simpl; auto.\n  Qed.\n\n  Lemma eq_if_trigger_info_data :\n    forall {A} {D}\n           (x : trigger_info D)\n           (F1 F2 : D -> A)\n           (G1 G2 : A),\n      (forall t, F1 t = F2 t)\n      -> G1 = G2\n      -> if_trigger_info_data x F1 G1 = if_trigger_info_data x F2 G2.\n  Proof.\n    introv impa impb.\n    destruct x; simpl; tcsp.\n  Qed.\n\n  Lemma M_byz_run_ls_on_event_unroll :\n    forall {L S}\n           (ls : LocalSystem L S)\n           {eo : EventOrdering}\n           (e  : Event),\n      M_byz_run_ls_on_event ls e\n      = if dec_isFirst e\n        then M_byz_run_ls_on_this_one_event ls e\n        else\n          let ls' := M_byz_run_ls_before_event ls e in\n          M_byz_run_ls_on_this_one_event ls' e.\n  Proof.\n    introv.\n    unfold M_byz_run_ls_on_event; simpl.\n    destruct (dec_isFirst e) as [d|d]; simpl in *; auto.\n    unfold M_byz_run_ls_before_event.\n    rewrite isFirst_implies_localPreds_eq; auto.\n  Qed.\n\n  Lemma on_M_some_ret_Some :\n    forall {T} {U} {n} (a : option T) (F : T -> U),\n      (a >>o>> (fun s => ret n (Some (F s))))\n      = ret n (option_map F a).\n  Proof.\n    introv; destruct a; simpl; auto.\n  Qed.\n  Hint Rewrite @on_M_some_ret_Some : comp.\n\n  Lemma bind_some_if_trigger_info_data :\n    forall {n} {S} {O} {D}\n           (a    : trigger_info D)\n           (f    : D -> M_n n (option S))\n           (g    : M_n n (option S))\n           (F    : S -> M_n n (option O)),\n      ((if_trigger_info_data a f g) >>o= F)\n      = if_trigger_info_data\n          a\n          (fun a => (f a) >>o= F)\n          (g >>o= F).\n  Proof.\n    introv; destruct a; simpl; auto.\n  Qed.\n\n(*  Lemma run_trustedSM_on_trigger_info_list_snoc :\n    forall {D} (l : list (trigger_info D)) x (tsm : trustedSM),\n      run_trustedSM_on_trigger_info_list tsm (snoc l x)\n      = fst (run_trustedSM_on_trigger_info\n               (run_trustedSM_on_trigger_info_list tsm l)\n               x).\n  Proof.\n    induction l; introv; simpl; auto.\n  Qed.*)\n\n(*  Lemma M_byz_run_update_on_list_snoc :\n    forall {S} {n} {cn}\n           (upd : M_Update n cn S)\n           (l : list (trigger_info (cio_I (fio cn))))\n           (s : S)\n           (x : trigger_info (cio_I (fio cn))),\n      M_byz_run_update_on_list s upd (snoc l x)\n      = ((M_byz_run_update_on_list s upd l)\n           >>o= fun mt => on_M_trusted\n                            mt\n                            (fun s =>\n                               if_trigger_info_data\n                                 x\n                                 (fun m => (upd s m) >>= fun so => ret _ (option_map M_nt (fst so)))\n                                 (M_find_trusted >>o= fun tsm => ret _ (Some (M_t (fst (run_trustedSM_on_trigger_info tsm x))))))\n                            (fun tsm => ret _ (Some (M_t (fst (run_trustedSM_on_trigger_info tsm x)))))).\n  Proof.\n    induction l; introv; simpl; auto.\n\n    {\n      destruct x; simpl; auto; autorewrite with comp; simpl; auto.\n      { apply eq_bind; introv; repnd; simpl; auto_rw_bind. }\n      { unfold M_run_trusted_on_trigger_info_list; simpl.\n        unfold run_trusted_on_trigger_info_list; simpl.\n        rewrite bind_some_bind_some.\n        apply eq_bind_some; introv; auto_rw_bind. }\n      { unfold M_run_trusted_on_trigger_info_list; simpl.\n        unfold run_trusted_on_trigger_info_list; simpl.\n        rewrite bind_some_bind_some.\n        apply eq_bind_some; introv; auto_rw_bind. }\n    }\n\n    rewrite bind_some_if_trigger_info_data.\n    apply eq_if_trigger_info_data; introv; auto_rw_bind.\n\n    {\n      apply eq_bind; introv.\n      rewrite M_on_some_bind_some.\n      apply eq_M_on_some; introv; auto.\n    }\n\n    simpl.\n    unfold M_run_trusted_on_trigger_info_list; simpl.\n    unfold run_trusted_on_trigger_info_list; simpl.\n    repeat rewrite bind_some_bind_some.\n    apply eq_bind_some; introv; auto_rw_bind.\n    rewrite run_trustedSM_on_trigger_info_list_snoc; auto.\n  Qed.*)\n\n  Lemma M_byz_run_ls_on_inputs_snoc :\n    forall {Lv Sp}\n           (ls : LocalSystem Lv Sp)\n           cn\n           (i  : trigger_info (cio_I (fio cn)))\n           (l  : list (trigger_info (cio_I (fio cn)))),\n      M_byz_run_ls_on_inputs ls cn (snoc l i)\n      = let ls' := M_byz_run_ls_on_inputs ls cn l in\n        fst (M_byz_run_ls_on_input ls' cn i).\n  Proof.\n    introv; revert ls; induction l; introv; simpl; tcsp.\n  Qed.\n\n  Lemma M_byz_run_ls_before_event_unroll :\n    forall {L S}\n           (ls : LocalSystem L S)\n           {eo : EventOrdering}\n           (e  : Event),\n      M_byz_run_ls_before_event ls e\n      = if dec_isFirst e\n        then ls\n        else let ls' := M_byz_run_ls_before_event ls (local_pred e) in\n             M_byz_run_ls_on_this_one_event ls' (local_pred e).\n  Proof.\n    introv.\n    unfold M_byz_run_ls_before_event.\n    destruct (dec_isFirst e) as [d|d]; simpl in *; auto.\n    { rewrite isFirst_implies_localPreds_eq; auto. }\n    rewrite (localPreds_unroll e); auto.\n    rewrite map_snoc; simpl.\n    rewrite @M_byz_run_ls_on_inputs_snoc; auto.\n  Qed.\n\n  Lemma M_byz_run_ls_before_event_as_M_byz_run_ls_on_event_pred :\n    forall {L S}\n           (ls : LocalSystem L S)\n           {eo : EventOrdering}\n           (e  : Event),\n      ~ isFirst e\n      -> M_byz_run_ls_before_event ls e = M_byz_run_ls_on_event ls (local_pred e).\n  Proof.\n    introv ni.\n    rewrite M_byz_run_ls_on_event_unroll.\n    rewrite M_byz_run_ls_before_event_unroll.\n\n    destruct (dec_isFirst e) as [d1|d1]; tcsp;[].\n    destruct (dec_isFirst (local_pred e)) as [d2|d2]; tcsp;[].\n\n    rewrite M_byz_run_ls_before_event_unroll.\n    destruct (dec_isFirst (local_pred e)); tcsp; GC.\n  Qed.\n\n  Lemma M_byz_run_ls_before_event_unroll_on :\n    forall {L S}\n           (ls : LocalSystem L S)\n           {eo : EventOrdering}\n           (e  : Event),\n      M_byz_run_ls_before_event ls e\n      = if dec_isFirst e\n        then ls\n        else M_byz_run_ls_on_event ls (local_pred e).\n  Proof.\n    introv.\n    destruct (dec_isFirst e) as [d|d];\n      [|apply M_byz_run_ls_before_event_as_M_byz_run_ls_on_event_pred;auto].\n    rewrite M_byz_run_ls_before_event_unroll.\n    destruct (dec_isFirst e); tcsp.\n  Qed.\n\n(*  Lemma unroll_M_byz_state_ls_before_event_of_trusted :\n    forall {eo : EventOrdering} (e : Event)\n           {L S} (ls : MLocalSystem L S),\n      M_byz_state_ls_before_event_of_trusted ls e\n      = if dec_isFirst e\n        then state_of_trusted_in_ls ls\n        else M_byz_state_ls_on_event_of_trusted ls (local_pred e).\n  Proof.\n    introv.\n    unfold M_byz_state_ls_before_event_of_trusted.\n    unfold M_byz_state_ls_on_event_of_trusted.\n    rewrite M_byz_run_ls_before_event_unroll_on.\n    destruct (dec_isFirst e); simpl; auto.\n  Qed.*)\n\n\n  Lemma M_byz_run_ls_on_this_one_event_eq :\n    forall {Lv Sp}\n           (ls : LocalSystem Lv Sp)\n           {eo : EventOrdering}\n           (e  : Event),\n      M_byz_run_ls_on_this_one_event ls e\n      = match trigger e with\n        | trigger_info_data d => fst (M_run_ls_on_input ls (msg_comp_name Sp) d)\n        | trigger_info_arbitrary => procs2byz ls\n        | trigger_info_trusted j => fst (M_run_ls_on_trusted (procs2byz ls) j)\n        end.\n  Proof.\n    introv.\n    unfold M_byz_run_ls_on_this_one_event.\n    unfold M_byz_run_ls_on_one_event.\n    remember (M_byz_run_ls_on_input ls (msg_comp_name Sp) (trigger e)) as h; repnd; simpl in *.\n    unfold M_byz_run_ls_on_input in *.\n    destruct (trigger e); simpl in *; ginv; auto.\n  Qed.\n\n  Lemma M_run_ls_on_this_one_event_M_byz_run_ls_on_this_one_event :\n    forall {Lv Sp}\n           {eo      : EventOrdering}\n           (e       : Event)\n           (ls1 ls2 : LocalSystem Lv Sp),\n      M_run_ls_on_this_one_event ls1 e = Some ls2\n      -> M_byz_run_ls_on_this_one_event ls1 e = ls2.\n  Proof.\n    introv h.\n    unfold M_run_ls_on_this_one_event in *.\n    rewrite M_byz_run_ls_on_this_one_event_eq.\n    rewrite option_map_Some in h; exrepnd; rev_Some.\n\n    unfold trigger_op in *.\n    destruct (trigger e) as [d|d|d]; ginv; [].\n    unfold M_run_ls_on_input_ls; simpl in *; auto.\n  Qed.\n\n(*  Lemma M_byz_run_ls_on_this_one_event_M_run_ls_on_this_one_event :\n    forall {L S}\n           {eo      : EventOrdering}\n           (e       : Event)\n           (ls1 ls2 : MLocalSystem L S),\n      M_byz_run_ls_on_this_one_event ls1 e = Some ls2\n      -> M_run_ls_on_this_one_event ls1 e = Some ls2.\n  Proof.\n    introv h.\n    unfold M_run_ls_on_this_one_event in *.\n    unfold M_byz_run_ls_on_this_one_event in *.\n    rewrite map_option_Some.\n\n    (* TODO: do not unfold *)\n    unfold if_trigger_info_data in *.\n    unfold trigger_op in *.\n    unfold ti2op in *.\n    simpl in *.\n    destruct (trigger e) as [d|d|d];\n      try (unfold option_map in *; dest_cases w);[].\n\n    unfold M_break in *. simpl in *.\n\n    eexists; dands; eauto.\n\n    dest_cases w.\n    unfold option_map in *.\n    repnd.\n    simpl in *.\n    destruct w2 as [X|X]; ginv.\n    inversion h; subst; auto.\n  Qed.\n  Hint Resolve M_byz_run_ls_on_this_one_event_M_run_ls_on_this_one_event : comp.\n*)\n\n  Lemma M_run_ls_on_event_M_byz_run_ls_on_event :\n    forall {L S}\n           {eo      : EventOrdering}\n           (e       : Event)\n           (ls1 ls2 : LocalSystem L S),\n      M_run_ls_on_event ls1 e = Some ls2\n      -> M_byz_run_ls_on_event ls1 e = ls2.\n  Proof.\n    intros L S eo e.\n    induction e as [e ind] using predHappenedBeforeInd;[]; introv h.\n    rewrite M_run_ls_on_event_unroll in h.\n    rewrite M_byz_run_ls_on_event_unroll.\n    destruct (dec_isFirst e).\n\n    { eapply M_run_ls_on_this_one_event_M_byz_run_ls_on_this_one_event; eauto. }\n\n    {\n      rewrite M_run_ls_before_event_unroll_on in h.\n      rewrite M_byz_run_ls_before_event_unroll_on.\n      destruct (dec_isFirst e); tcsp;[].\n      apply map_option_Some in h; exrepnd.\n      symmetry in h0.\n      apply ind in h1; eauto 3 with eo; rewrite h1;[]; simpl.\n\n      eapply M_run_ls_on_this_one_event_M_byz_run_ls_on_this_one_event; eauto.\n    }\n  Qed.\n\n  Lemma M_run_ls_on_this_one_event_implies_isCorrect :\n    forall {eo : EventOrdering} (e : Event) {L S} (ls1 ls2 : LocalSystem L S),\n      M_run_ls_on_this_one_event ls1 e = Some ls2\n      -> isCorrect e.\n  Proof.\n    introv h.\n    unfold M_run_ls_on_this_one_event in h.\n    apply map_option_Some in h; exrepnd; rev_Some; simpl in *.\n    eauto 3 with eo.\n  Qed.\n  Hint Resolve M_run_ls_on_this_one_event_implies_isCorrect : comp.\n\n  Lemma M_run_ls_on_event_implies_has_correct_trace_before :\n    forall {eo : EventOrdering} (e : Event) {L S} (ls1 ls2 : LocalSystem L S),\n      M_run_ls_on_event ls1 e = Some ls2\n      -> has_correct_trace_before e (loc e).\n  Proof.\n    intro es.\n    induction e as [e ind] using predHappenedBeforeInd_type; introv h.\n    rewrite M_run_ls_on_event_unroll in h.\n    destruct (dec_isFirst e) as [d|d]; eauto 3 with eo comp;[].\n    apply map_option_Some in h; exrepnd; rev_Some; simpl in *.\n    rewrite M_run_ls_before_event_as_M_run_ls_on_event_pred in h1; auto;[].\n    apply ind in h1; autorewrite with eo in *; eauto 3 with eo comp.\n  Qed.\n  Hint Resolve M_run_ls_on_event_implies_has_correct_trace_before : comp.\n\n  Lemma M_run_ls_on_event_implies_has_correct_trace_bounded :\n    forall {eo : EventOrdering} (e : Event) {L S} (ls1 ls2 : LocalSystem L S),\n      M_run_ls_on_event ls1 e = Some ls2\n      -> has_correct_trace_bounded e.\n  Proof.\n    introv run; apply M_run_ls_on_event_implies_has_correct_trace_before in run; eauto 3 with eo.\n  Qed.\n  Hint Resolve M_run_ls_on_event_implies_has_correct_trace_bounded : comp.\n\n  Lemma M_run_ls_before_event_implies_has_correct_trace_bounded_lt :\n    forall {eo : EventOrdering} (e : Event) {L S} (ls1 ls2 : LocalSystem L S),\n      M_run_ls_before_event ls1 e = Some ls2\n      -> has_correct_trace_bounded_lt e.\n  Proof.\n    introv run.\n    rewrite M_run_ls_before_event_unroll_on in run.\n    destruct (dec_isFirst e); ginv; eauto 3 with comp eo.\n\n  Qed.\n  Hint Resolve M_run_ls_before_event_implies_has_correct_trace_bounded_lt : comp.\n\n(*\n  Lemma M_byz_run_ls_on_event_M_run_ls_on_event :\n    forall {L S}\n           {eo      : EventOrdering}\n           (e       : Event)\n           (ls1 ls2 : LocalSystem L S),\n      M_byz_run_ls_on_event ls1 e = Some (M_nt ls2)\n      -> M_run_ls_on_event ls1 e = Some ls2.\n  Proof.\n    intros L S eo e.\n    induction e as [e ind] using predHappenedBeforeInd;[]; introv h.\n    rewrite M_byz_run_ls_on_event_unroll in h.\n    rewrite M_run_ls_on_event_unroll.\n    destruct (dec_isFirst e).\n\n    { eapply M_byz_run_ls_on_this_one_event_M_run_ls_on_this_one_event; eauto. }\n\n    {\n      rewrite M_run_ls_before_event_unroll_on.\n      rewrite M_byz_run_ls_before_event_unroll_on in h.\n      destruct (dec_isFirst e); tcsp;[].\n      apply map_option_Some in h; exrepnd; rev_Some.\n\n      unfold M_byz_run_M_trusted_ls_on_this_one_event in h0.\n      apply on_M_trusted_implies_or in h0; repndors; exrepnd; subst; ginv;[]; rev_Some.\n      eapply ind in h1; eauto 3 with eo.\n      allrw; simpl; eauto 3 with comp.\n    }\n  Qed.\n  Hint Resolve M_byz_run_ls_on_event_M_run_ls_on_event : comp.\n*)\n\n  Lemma M_byz_state_sys_on_event_if_M_state_sys_on_event :\n    forall {F}\n           (sys : M_USystem F)\n           {eo  : EventOrdering}\n           (e   : Event)\n           (cn  : CompName)\n           (s   : sf cn),\n      M_state_sys_on_event sys e cn = Some s\n      -> M_byz_state_sys_on_event sys e cn = Some s.\n  Proof.\n    introv h.\n    rewrite M_state_sys_on_event_unfold in h.\n    apply map_option_Some in h; exrepnd; symmetry in h0.\n\n    eapply M_run_ls_on_event_M_byz_run_ls_on_event in h1.\n\n    unfold M_byz_state_sys_on_event.\n    unfold M_byz_state_ls_on_event.\n    allrw; auto.\n  Qed.\n  Hint Resolve M_byz_state_sys_on_event_if_M_state_sys_on_event : comp.\n\n(*  Lemma M_byz_state_sys_on_event_implies_M_state_sys_on_event :\n    forall {F}\n           (sys : M_USystem F)\n           {eo  : EventOrdering}\n           (e   : Event)\n           (cn  : CompName)\n           (s   : sf cn),\n      M_byz_state_sys_on_event sys e cn = Some (M_nt s)\n      -> M_state_sys_on_event sys e cn = Some s.\n  Proof.\n    introv h.\n\n    unfold M_byz_state_sys_on_event in *.\n    unfold M_byz_state_ls_on_event in *.\n    unfold map_op_untrusted_op in *.\n    rewrite map_option_Some in h.\n    exrepnd.\n\n    rewrite M_state_sys_on_event_unfold.\n    apply map_option_Some; rev_Some.\n\n    unfold map_untrusted_op in h0; simpl in *.\n    apply on_M_trusted_implies_or in h0; repndors; exrepnd; subst; ginv; rev_Some.\n    apply M_byz_run_ls_on_event_M_run_ls_on_event in h1.\n    allrw.\n    eexists; dands; eauto.\n    apply option_map_Some in h2; exrepnd; ginv.\n  Qed.\n  Hint Resolve M_byz_state_sys_on_event_implies_M_state_sys_on_event : comp.\n*)\n\n  Definition M_byz_output_ls_on_this_one_event\n             {Lv Sp}\n             (ls : LocalSystem Lv Sp)\n             {eo : EventOrdering}\n             (e  : Event) : option (event2out Sp e) :=\n    snd (M_byz_run_ls_on_one_event ls e).\n\n  Lemma M_byz_output_ls_on_event_as_run :\n    forall {Lv Sp}\n           (ls : LocalSystem Lv Sp)\n           {eo : EventOrdering}\n           (e  : Event),\n      M_byz_output_ls_on_event ls e\n      = let ls' := M_byz_run_ls_before_event ls e\n        in M_byz_output_ls_on_this_one_event ls' e.\n  Proof.\n    auto.\n  Qed.\n\n  Lemma M_run_ls_before_event_M_byz_run_ls_before_event :\n    forall {L S}\n           {eo      : EventOrdering}\n           (e       : Event)\n           (ls1 ls2 : LocalSystem L S),\n      M_run_ls_before_event ls1 e = Some ls2\n      -> M_byz_run_ls_before_event ls1 e = ls2.\n  Proof.\n    intros L S eo e.\n    induction e as [e ind] using predHappenedBeforeInd;[]; introv h.\n    rewrite M_run_ls_before_event_unroll in h.\n    rewrite M_byz_run_ls_before_event_unroll.\n    destruct (dec_isFirst e); ginv; auto;[].\n\n    apply map_option_Some in h; exrepnd; rev_Some.\n    apply ind in h1; eauto 3 with eo.\n    allrw; simpl.\n    eapply M_run_ls_on_this_one_event_M_byz_run_ls_on_this_one_event; eauto.\n  Qed.\n\n  (* Use this one instead of the other one *)\n  Lemma M_byz_run_ls_on_event_unroll2 :\n    forall {L S}\n           (ls : LocalSystem L S)\n           {eo : EventOrdering}\n           (e  : Event),\n      M_byz_run_ls_on_event ls e\n      = let ls' := M_byz_run_ls_before_event ls e in\n        M_byz_run_ls_on_this_one_event ls' e.\n  Proof.\n    introv; auto.\n  Qed.\n\n  (* Use this one instead of the other one *)\n  Lemma M_run_ls_on_event_unroll2 :\n    forall {L S}\n           (ls : LocalSystem L S)\n           {eo : EventOrdering}\n           (e  : Event),\n      M_run_ls_on_event ls e\n      = map_option\n            (fun ls => M_run_ls_on_this_one_event ls e)\n            (M_run_ls_before_event ls e).\n  Proof.\n    introv.\n    rewrite M_run_ls_on_event_unroll.\n    rewrite M_run_ls_before_event_unroll_on.\n    destruct (dec_isFirst e); tcsp.\n  Qed.\n\n  Lemma in_M_output_ls_on_this_one_event_implies :\n    forall {eo : EventOrdering} (e : Event)\n           {Lv Sp} (ls : LocalSystem Lv Sp) out,\n      In out (M_output_ls_on_this_one_event ls e)\n      ->\n      exists m comp,\n        trigger_op e = Some m\n        /\\ find_name (msg_comp_name Sp) ls = Some comp\n        /\\ In out (M_break\n                     (M_run_sm_on_input comp m)\n                     ls\n                     (fun subs out => snd out)).\n  Proof.\n    introv i.\n    unfold M_output_ls_on_this_one_event in *.\n    remember (trigger_op e) as trig; symmetry in Heqtrig; destruct trig; simpl in *; ginv; tcsp; eauto.\n    unfold M_run_ls_on_input_out in i.\n    unfold M_run_ls_on_input in i.\n    unfold on_comp in i.\n    dest_cases w.\n    eexists; eexists; dands; eauto.\n    unfold M_break in *; dest_cases w; repnd; simpl in *; auto.\n  Qed.\n\n  Lemma M_break_mp :\n    forall {n} {S}\n           (sm   : M_n n S)\n           (subs : n_procs n)\n           (F G  : n_procs n -> S -> Prop),\n      (forall subs out, F subs out -> G subs out)\n      -> M_break sm subs F\n      -> M_break sm subs G.\n  Proof.\n    introv imp m.\n    unfold M_break in *.\n    dest_cases w; tcsp.\n  Qed.\n\n  Lemma has_correct_trace_before_implies_trigger_eq :\n    forall {eo : EventOrdering} (e : Event),\n      has_correct_trace_before e (loc e)\n      -> exists m, trigger e = trigger_info_data m.\n  Proof.\n    introv cor.\n    pose proof (cor e) as cor; repeat (autodimp cor hyp); eauto 3 with eo.\n    pose proof (cor e) as cor; repeat (autodimp cor hyp); eauto 3 with eo.\n    unfold isCorrect, trigger_op in cor.\n    remember (trigger e) as trig; destruct trig; simpl in *; tcsp; eauto.\n  Qed.\n\n  Lemma M_byz_run_ls_on_this_one_event_as_M_run_ls_on_this_one_event :\n    forall {L S}\n           {eo  : EventOrdering}\n           (e   : Event)\n           (ls1 : LocalSystem L S),\n      has_correct_trace_before e (loc e)\n      -> M_run_ls_on_this_one_event ls1 e\n         = Some (M_byz_run_ls_on_this_one_event ls1 e).\n  Proof.\n    introv cor.\n    unfold M_run_ls_on_this_one_event.\n    unfold M_byz_run_ls_on_this_one_event.\n    unfold M_byz_run_ls_on_one_event.\n    applydup has_correct_trace_before_implies_trigger_eq in cor; exrepnd.\n    unfold trigger_op.\n    remember (M_byz_run_ls_on_input ls1 (msg_comp_name S) (trigger e)) as run; repnd; simpl in *.\n    revert dependent run.\n    rewrite cor1; simpl; introv h.\n    unfold M_run_ls_on_input_ls; rewrite <- h; simpl; auto.\n  Qed.\n\n  Lemma has_correct_trace_bounded_lt_implies_before_local_pred :\n    forall {eo : EventOrdering} (e : Event),\n      ~isFirst e\n      -> has_correct_trace_bounded_lt e\n      -> has_correct_trace_before (local_pred e) (loc e).\n  Proof.\n    introv ni cor h q w.\n    apply cor.\n    assert (e' ⊏ e) as lte; eauto 3 with eo.\n    destruct h as [h|h]; subst; eauto 3 with eo.\n    split; eauto 3 with eo.\n  Qed.\n  Hint Resolve has_correct_trace_bounded_lt_implies_before_local_pred : eo.\n\n  Lemma has_correct_trace_before_local_implies_implies_lt :\n    forall {eo : EventOrdering} (e : Event),\n      has_correct_trace_before (local_pred e) (loc e)\n      -> has_correct_trace_bounded_lt e.\n  Proof.\n    introv cor h.\n    pose proof (cor e') as cor; repeat (autodimp cor hyp); eauto 3 with eo.\n    assert (e' ⊑ (local_pred e)) as lte; eauto 3 with eo.\n    apply localHappenedBefore_implies_le_local_pred; auto.\n  Qed.\n  Hint Resolve has_correct_trace_before_local_implies_implies_lt : eo.\n\n  Lemma M_byz_run_ls_before_event_as_M_run_ls_before_event :\n    forall {L S}\n           {eo  : EventOrdering}\n           (e   : Event)\n           (ls1 : LocalSystem L S),\n      has_correct_trace_bounded_lt e\n      -> M_run_ls_before_event ls1 e\n         = Some (M_byz_run_ls_before_event ls1 e).\n  Proof.\n    intros L S eo e.\n    induction e as [e ind] using predHappenedBeforeInd;[]; introv h.\n    rewrite M_run_ls_before_event_unroll.\n    rewrite M_byz_run_ls_before_event_unroll.\n    destruct (dec_isFirst e); ginv; auto;[].\n\n    rewrite ind; autorewrite with eo; eauto 3 with eo;[].\n    simpl.\n    rewrite M_byz_run_ls_on_this_one_event_as_M_run_ls_on_this_one_event;\n      autorewrite with eo; eauto 3 with eo.\n  Qed.\n\n  (*Lemma correct_implies_byz_output_eq :\n    forall {eo : EventOrdering} (e : Event)\n           {Lv Sp}\n           (ls : LocalSystem Lv Sp),\n      has_correct_trace_before e (loc e)\n      -> M_byz_output_ls_on_event_B ls e\n         = m_byz_output_msg (msg_comp_name Sp) _ (M_output_ls_on_event ls e).\n  Proof.\n    introv cor.\n    unfold M_byz_output_ls_on_event_B.\n    rewrite M_output_ls_on_event_as_run_before.\n    rewrite M_byz_run_ls_before_event_as_M_run_ls_before_event; auto.\n\n    remember (M_byz_run_ls_before_event ls e) as w; clear Heqw.\n    unfold M_byz_run_ls_on_one_event_B.\n    unfold M_output_ls_on_this_one_event.\n    applydup @has_correct_trace_before_implies_trigger_eq in cor; exrepnd.\n\n    unfold event2M_byz_output, trigger_op.\n    rewrite cor1; simpl.\n    unfold M_run_ls_on_input_out; simpl; auto.\n    remember (M_run_ls_on_input w (msg_comp_name Sp) m) as z; repnd; simpl.\n    destruct z; simpl in *; auto.\n  Qed.\n\n  Lemma in_M_output_ls_on_event_implies_byz_eq :\n    forall {eo : EventOrdering} (e : Event)\n           {Lv Sp}\n           (ls : LocalSystem Lv Sp)\n           out,\n      In out (M_output_ls_on_event ls e)\n      -> M_byz_output_ls_on_event_B ls e\n         = m_byz_output_msg (msg_comp_name Sp) _ (M_output_ls_on_event ls e).\n  Proof.\n    introv i.\n    unfold M_byz_output_ls_on_event_B.\n    unfold M_byz_run_ls_on_one_event_B.\n    rewrite M_output_ls_on_event_as_run_before in i.\n    rewrite M_output_ls_on_event_as_run_before.\n    remember (M_run_ls_before_event ls e) as q; symmetry in Heqq; destruct q; simpl in *; tcsp.\n    applydup @M_run_ls_before_event_M_byz_run_ls_before_event in Heqq as w.\n    rewrite w; simpl.\n    applydup @in_M_output_ls_on_this_one_event_implies in i as j; exrepnd.\n    unfold M_output_ls_on_this_one_event.\n    allrw; simpl.\n    applydup trigger_op_Some_implies_trigger_message in j0.\n    unfold event2M_byz_output; simpl.\n    allrw; simpl.\n    unfold M_run_ls_on_input_out; simpl.\n    remember (M_run_ls_on_input l (msg_comp_name Sp) m) as z; repnd; simpl in *; tcsp.\n    destruct z; simpl; auto.\n  Qed.*)\n\n  Lemma dmsg_is_in_out {s} {eo : EventOrdering} {e : Event}\n        (m : DirectedMsg)\n        (o : event2out s e) : Prop.\n  Proof.\n    unfold event2out in o.\n    remember (trigger e) as trig; destruct trig; simpl in *.\n    { exact (In m o). }\n    { destruct o. }\n    { exact False. }\n  Defined.\n\n  Lemma dmsgs_are_out {s} {eo : EventOrdering} {e : Event}\n        (l : DirectedMsgs)\n        (o : event2out s e) : Prop.\n  Proof.\n    unfold event2out in o.\n    remember (trigger e) as trig; destruct trig; simpl in *.\n    { exact (o = l). }\n    { destruct o. }\n    { exact False. }\n  Defined.\n\n  Lemma in_M_output_ls_on_event_implies_byz_eq :\n    forall {eo : EventOrdering} (e : Event)\n           {Lv Sp}\n           (ls : LocalSystem Lv Sp)\n           (m  : DirectedMsg),\n      In m (M_output_ls_on_event ls e)\n      -> exists o,\n        M_byz_output_ls_on_event ls e = Some o\n        /\\ dmsg_is_in_out m o.\n  Proof.\n    introv i.\n    unfold M_byz_output_ls_on_event.\n    apply M_output_ls_on_event_implies_run in i; exrepnd.\n    apply M_run_ls_before_event_M_byz_run_ls_before_event in i1; allrw; simpl.\n    clear i1.\n\n    unfold M_output_ls_on_this_one_event in i0.\n    unfold M_run_ls_on_input_out in i0.\n    unfold M_byz_run_ls_on_one_event.\n    unfold trigger_op, event2out, dmsg_is_in_out in *; simpl in *.\n    remember (trigger e) as trig; clear Heqtrig.\n    destruct trig; simpl in *; tcsp.\n    apply in_olist2list in i0; exrepnd; simpl in *.\n    unfold LocalSystem in *; simpl in *; rewrite i0.\n    eexists; dands; eauto.\n  Qed.\n\n  Lemma eq_cons :\n    forall {T} (x1 x2 : T) l1 l2,\n      x1 :: l1 = x2 :: l2 -> x1 = x2 /\\ l1 = l2.\n  Proof.\n    introv h; inversion h; auto.\n  Qed.\n\n  Lemma incr_n_proc_inj :\n    forall {n} {cn} (p q : n_proc n cn),\n      incr_n_proc p = incr_n_proc q\n      -> p = q.\n  Proof.\n    unfold incr_n_proc; introv h; inversion h; auto.\n  Qed.\n\n  Lemma incr_n_nproc_inj :\n    forall {n} (a b : n_nproc n),\n      incr_n_nproc a = incr_n_nproc b\n      -> a = b.\n  Proof.\n    introv h.\n    destruct a, b; simpl in *.\n    inversion h; subst.\n    apply decomp_p_nproc in h.\n    apply incr_n_proc_inj in h; subst; auto.\n  Qed.\n\n  Lemma incr_n_procs_inj :\n    forall {n} (l k : n_procs n),\n      incr_n_procs l = incr_n_procs k\n      -> l = k.\n  Proof.\n    unfold incr_n_procs.\n    induction l; destruct k; introv h; simpl in *; tcsp.\n    apply eq_cons in h; repnd.\n    apply IHl in h; clear IHl; subst.\n    apply incr_n_nproc_inj in h0; subst; auto.\n  Qed.\n\n  Definition M_byz_output_sys_on_this_one_event\n             {F}\n             (sys : M_USystem F)\n             {eo  : EventOrdering}\n             (e   : Event) : option (event2out (fls_space F (loc e)) e) :=\n    M_byz_output_ls_on_this_one_event (sys (loc e)) e.\n\n  Definition is_trusted_event {eo : EventOrdering} (e : Event) (i : ITrusted) :=\n    trigger e = trigger_info_trusted i.\n\n  Lemma trusted_is_in_out {s} {eo : EventOrdering} {e : Event}\n        {i}\n        (p : is_trusted_event e i)\n        (x : iot_output (iot_fun (it_name i)))\n        (o : event2out s e) : Prop.\n  Proof.\n    unfold event2out in o.\n    unfold is_trusted_event in p.\n    rewrite p in o; simpl in *.\n    exact (x = o).\n  Defined.\n\n  Lemma has_correct_trace_before_implies_isCorrect :\n    forall {eo : EventOrdering} (e : Event),\n      has_correct_trace_before e (loc e) -> isCorrect e.\n  Proof.\n    introv cor; eapply cor; eauto 3 with eo.\n  Qed.\n  Hint Resolve has_correct_trace_before_implies_isCorrect : eo.\n\n  Lemma correct_byz_output_implies :\n    forall {n} {s} (ls : LocalSystem n s) {eo : EventOrdering} (e : Event) (o : event2out s e),\n      has_correct_trace_before e (loc e)\n      -> M_byz_output_ls_on_event ls e = Some o\n      ->\n      exists (i : msg) (msgs : DirectedMsgs),\n        trigger e = trigger_info_data i\n        /\\ dmsgs_are_out msgs o\n        /\\ M_output_ls_on_event ls e = msgs.\n  Proof.\n    introv cor out.\n    applydup has_correct_trace_before_implies_isCorrect in cor.\n    unfold M_byz_output_ls_on_event in *.\n    unfold M_byz_run_ls_on_one_event in *.\n    unfold M_output_ls_on_event in *.\n    unfold event2out, dmsgs_are_out, isCorrect, trigger_op in *; simpl in *.\n    remember (trigger e) as trig; destruct trig; simpl in *; tcsp; GC.\n    exists d o; dands; auto.\n    rewrite M_byz_run_ls_before_event_as_M_run_ls_before_event; auto; simpl.\n    unfold M_output_ls_on_this_one_event.\n    unfold trigger_op; allrw <-; simpl.\n    unfold M_run_ls_on_input_out; simpl in *.\n    unfold LocalSystem in *; rewrite out; simpl; auto.\n    eauto 3 with eo comp.\n  Qed.\n\n  Lemma in_M_output_ls_on_this_one_event_implies_in_byz :\n    forall {eo : EventOrdering} (e : Event) {n} {s} (ls : LocalSystem n s) m,\n      In m (M_output_ls_on_this_one_event ls e)\n      -> exists (o : event2out _ e),\n          M_byz_output_ls_on_this_one_event ls e = Some o /\\ dmsg_is_in_out m o.\n  Proof.\n    introv out.\n    unfold M_output_ls_on_this_one_event in out.\n    apply in_olist2list in out; exrepnd.\n    apply map_option_Some in out1; exrepnd; rev_Some.\n    unfold M_run_ls_on_input_out in out2.\n\n    unfold M_byz_output_ls_on_this_one_event.\n    unfold M_byz_run_ls_on_one_event.\n    apply trigger_op_Some_implies_trigger_message in out1.\n    remember (M_byz_run_ls_on_input ls (msg_comp_name s) (trigger e)) as z; symmetry in Heqz; repnd; simpl in *.\n    revert z Heqz.\n    unfold event2out, dmsg_is_in_out in *; rewrite out1; simpl; introv run.\n    rewrite run in out2; simpl in *; subst; simpl in *.\n    exists l; dands; auto.\n  Qed.\n\n  Lemma in_M_output_sys_on_event_implies_in_byz :\n    forall {eo : EventOrdering} (e : Event) {F} (sys : M_USystem F) m,\n      In m (M_output_sys_on_event sys e)\n      -> exists (o : event2out _ e),\n        M_byz_output_sys_on_event sys e = Some o\n        /\\ dmsg_is_in_out m o.\n  Proof.\n    introv out.\n    apply M_output_ls_on_event_as_run in out; exrepnd.\n    unfold M_byz_output_sys_on_event.\n    rewrite M_byz_output_ls_on_event_as_run.\n    applydup @M_run_ls_before_event_M_byz_run_ls_before_event in out1 as xx.\n    allrw; simpl; clear xx.\n    apply in_M_output_ls_on_this_one_event_implies_in_byz; auto.\n  Qed.\n\n  (*Definition M_byz_output_ls_on_event_trusted\n             {Lv Sp}\n             (ls : LocalSystem Lv Sp)\n             {eo : EventOrdering}\n             (e  : Event)\n             (i  : ITrusted) : option (iot_output (iot_fun (it_name i))) :=\n    snd (M_run_ls_on_trusted\n           (M_byz_run_ls_before_event ls e)\n           i).\n\n  Definition M_byz_output_sys_on_event_trusted\n             {F}\n             (sys : M_USystem F)\n             {eo  : EventOrdering}\n             (e   : Event)\n             (i   : ITrusted) : option (iot_output (iot_fun (it_name i))) :=\n    M_byz_output_ls_on_event_trusted (sys (loc e)) e i.*)\n\nEnd ComponentSM.\n\n\nHint Constructors similar_procs.\nHint Constructors similar_subs.\n\n\nHint Resolve similar_subs_refl : comp.\nHint Resolve similar_sms_refl : comp.\nHint Resolve similar_procs_refl : comp.\nHint Resolve similar_subs_refl : comp.\nHint Resolve similar_sms_sym : comp.\nHint Resolve similar_procs_sym : comp.\nHint Resolve similar_subs_sym : comp.\nHint Resolve similar_sms_trans : comp.\nHint Resolve similar_procs_trans : comp.\nHint Resolve similar_subs_trans : comp.\nHint Resolve state_of_component_if_similar : comp.\nHint Resolve ls_preserves_subs_implies_M_run_update_on_list : comp.\n(*Hint Resolve ls_preserves_subs_implies_M_run_update_on_list2 : comp.*)\nHint Resolve M_run_ls_on_this_one_event_implies_isCorrect : comp.\nHint Resolve M_run_ls_on_event_implies_has_correct_trace_before : comp.\nHint Resolve M_run_ls_on_event_implies_has_correct_trace_bounded : comp.\nHint Resolve M_run_ls_before_event_implies_has_correct_trace_bounded_lt : comp.\n(*Hint Resolve M_byz_run_ls_on_this_one_event_M_run_ls_on_this_one_event : comp.*)\n(*Hint Resolve M_byz_run_ls_on_event_M_run_ls_on_event : comp.*)\nHint Resolve M_byz_state_sys_on_event_if_M_state_sys_on_event : comp.\n(*Hint Resolve M_byz_state_sys_on_event_implies_M_state_sys_on_event : comp.*)\nHint Resolve similar_sms_at_refl : comp.\nHint Resolve similar_sms_at_sym : comp.\nHint Resolve similar_sms_at_trans : comp.\n\n\nHint Rewrite @select_n_proc_trivial : comp.\nHint Rewrite @select_n_procs_trivial : comp.\nHint Rewrite @lift_n_procs_0 : comp.\nHint Rewrite @mapOption_fun_Some : list.\nHint Rewrite @mapOption_fun_None : list.\n\n\nHint Rewrite @crazy_bind_option1 : comp.\nHint Rewrite @bind_ret : comp.\nHint Rewrite @bind_ret_fun : comp.\nHint Rewrite @M_on_some_some : comp.\nHint Rewrite @crazy_bind_option2 : comp.\nHint Rewrite @M_break_ret : comp.\nHint Rewrite @bind_some_ret_some : comp.\nHint Rewrite @bind_some_ret_some_fun : comp.\nHint Rewrite @M_on_some_ret_some : comp.\nHint Rewrite @M_on_some_ret_some_fun : comp.\n(*Hint Rewrite @map_op_untrusted_option_map_M_nt : comp.*)\n(*Hint Rewrite @M_break_map_op_untrusted_option_map_M_nt : comp.*)\n(*Hint Rewrite @on_M_trusted_map_untrusted : comp.*)\nHint Rewrite @on_M_some_ret_Some : comp.\n(*Hint Rewrite @on_M_trusted_M_nt : comp.*)\n(*Hint Rewrite @on_M_trusted_M_t : comp.*)\nHint Rewrite @M_break_bind : comp.\nHint Rewrite @M_break_bind_pair : comp.\nHint Rewrite @M_break_bind_ret : comp.\n\n\nHint Resolve M_state_sys_before_event_if_on_event_direct_pred : proc.\n\n\nHint Resolve sub_local_key_map_preserves_in_lookup_receiving_keys : eo.\nHint Resolve verify_authenticated_data_if_sub_keys : eo.\nHint Resolve has_correct_trace_before_implies_isCorrect : eo.\nHint Resolve has_correct_trace_bounded_lt_implies_before_local_pred : eo.\nHint Resolve has_correct_trace_before_local_implies_implies_lt : eo.\n\n\nDelimit Scope comp with comp.\n\n\nNotation \"a >>= f\"   := (bind a f)      (at level 80).\nNotation \"a >>>= f\"  := (bind_pair a f) (at level 80).\nNotation \"a >p>= f\"  := (pbind a f)     (at level 80).\nNotation \"a >>o>> f\" := (M_on_some f a) (at level 80).\nNotation \"a >>o= f\"  := (bind_some a f) (at level 80).\n\nNotation \"d ∈ sys ⇝ e\" := (In d (M_output_sys_on_event sys e)) (at level 70).\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/model/ComponentSM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2119354534022632}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*              Layers of PM: PThreadInit                              *)\n(*                                                                     *)\n(*          Provide abstraction of Context                             *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*          Yu Guo <yu.guo@yale.edu>                                   *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file defines the abstract data and the primitives for the PThreadInit layer, \nwhich will introduce abstraction of kernel context*)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import LoadStoreSem2.\nRequire Import XOmega.\nRequire Import ObservationImpl.\n\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\nRequire Import liblayers.compat.CompatGenSem.\n\nRequire Import CalRealPTPool.\nRequire Import CalRealPT.\nRequire Import CalRealIDPDE.\nRequire Import CalRealInitPTE.\nRequire Import CalRealSMSPool.\nRequire Import CalRealProcModule.\n\nRequire Import INVLemmaContainer.\nRequire Import INVLemmaMemory.\nRequire Import INVLemmaThread.\n\nRequire Import AbstractDataType.\n\nRequire Export ObjCPU.\nRequire Export ObjFlatMem.\nRequire Export ObjContainer.\nRequire Export ObjVMM.\nRequire Export ObjLMM.\nRequire Export ObjShareMem.\nRequire Export ObjThread.\nRequire Export ObjQueue.\n\n(** * Abstract Data and Primitives at this layer*)\nSection WITHMEM.\n\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n\n  (** **Definition of the invariants at MPTNew layer*)\n  (** [0th page map] is reserved for the kernel thread*)\n  Record high_level_invariant (abd: RData) :=\n    mkInvariant {\n        valid_nps: pg abd = true -> kern_low <= nps abd <= maxpage;\n        valid_AT_kern: pg abd = true -> LAT_kern (LAT abd) (nps abd);\n        valid_AT_usr: pg abd = true -> LAT_usr (LAT abd) (nps abd);\n        valid_kern: ipt abd = false -> pg abd = true;\n        valid_iptt: ipt abd = true -> ikern abd = true; \n        valid_iptf: ikern abd = false -> ipt abd = false; \n        valid_ihost: ihost abd = false -> pg abd = true /\\ ikern abd = true;\n        valid_container: Container_valid (AC abd);\n        valid_pperm_ppage: Lconsistent_ppage (LAT abd) (pperm abd) (nps abd);\n        init_pperm: pg abd = false -> (pperm abd) = ZMap.init PGUndef;\n        valid_PMap: pg abd = true -> \n                    (forall i, 0<= i < num_proc ->\n                               PMap_valid (ZMap.get i (ptpool abd)));\n        (* 0th page map is reserved for the kernel thread*)          \n        valid_PT_kern: pg abd = true -> ipt abd = true -> (PT abd) = 0;\n        valid_PMap_kern: pg abd = true -> PMap_kern (ZMap.get 0 (ptpool abd));\n        valid_PT: pg abd = true -> 0<= PT abd < num_proc;\n        valid_dirty: dirty_ppage (pperm abd) (HP abd);\n\n        valid_idpde: pg abd = true -> IDPDE_init (idpde abd);\n        valid_pperm_pmap: consistent_pmap (ptpool abd) (pperm abd) (LAT abd) (nps abd);\n        valid_pmap_domain: consistent_pmap_domain (ptpool abd) (pperm abd) (LAT abd) (nps abd);\n        valid_lat_domain: consistent_lat_domain (ptpool abd) (LAT abd) (nps abd);\n\n        valid_root: pg abd = true -> cused (ZMap.get 0 (AC abd)) = true;\n\n        valid_TCB: pg abd = true -> TCBCorrect_range (tcb abd)\n\n      }.\n\n  (** ** Definition of the abstract state ops *)\n  Global Instance pthreadinit_data_ops : CompatDataOps RData :=\n    {\n      empty_data := init_adt;\n      high_level_invariant := high_level_invariant;\n      low_level_invariant := low_level_invariant;\n      kernel_mode adt := ikern adt = true /\\ ihost adt = true;\n      observe := ObservationImpl.observe\n    }.\n\n  (** ** Proofs that the initial abstract_data should satisfy the invariants*)    \n  Section Property_Abstract_Data.\n\n    Lemma empty_data_high_level_invariant:\n      high_level_invariant init_adt.\n    Proof.\n      constructor; simpl; intros; auto; try inv H.\n      - apply empty_container_valid.\n      - eapply Lconsistent_ppage_init.\n      - eapply dirty_ppage_init.\n      - eapply consistent_pmap_init.\n      - eapply consistent_pmap_domain_init.\n      - eapply consistent_lat_domain_init.\n    Qed.\n\n    (** ** Definition of the abstract state *)\n    Global Instance pthreadinit_data_prf : CompatData RData.\n    Proof.\n      constructor.\n      - apply low_level_invariant_incr.\n      - apply empty_data_low_level_invariant.\n      - apply empty_data_high_level_invariant.\n    Qed.\n\n  End Property_Abstract_Data.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  (** * Proofs that the primitives satisfies the invariants at this layer *)\n  Section INV.\n\n    Section ALLOC.\n      \n      Lemma alloc_high_level_inv:\n        forall d d' i n,\n          alloc_spec i d = Some (d', n) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        inv H0. constructor; simpl; eauto.\n        - intros; eapply LAT_kern_norm; eauto. eapply _x.\n        - intros; eapply LAT_usr_norm; eauto.\n        - eapply alloc_container_valid'; eauto.\n        - eapply Lconsistent_ppage_norm_alloc; eauto.\n        - intros; congruence.\n        - eapply dirty_ppage_gso_alloc; eauto.\n        - eapply consistent_pmap_gso_at_false; eauto. apply _x.\n        - eapply consistent_pmap_domain_gso_at_false; eauto. apply _x.\n        - eapply consistent_lat_domain_gss_nil; eauto.\n        - zmap_solve.\n      Qed.\n      \n      Lemma alloc_low_level_inv:\n        forall d d' i n n',\n          alloc_spec i d = Some (d', n) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        inv H0. constructor; eauto.\n      Qed.\n\n      Lemma alloc_kernel_mode:\n        forall d d' i n,\n          alloc_spec i d = Some (d', n) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n      Qed.\n\n      Global Instance alloc_inv: PreservesInvariants alloc_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply alloc_low_level_inv; eassumption.\n        - eapply alloc_high_level_inv; eassumption.\n        - eapply alloc_kernel_mode; eassumption.\n      Qed.\n\n    End ALLOC.\n\n    Global Instance pfree_inv: PreservesInvariants pfree_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n      - intros; eapply LAT_kern_norm; eauto. \n      - intros; eapply LAT_usr_norm; eauto.\n      - eapply Lconsistent_ppage_norm_undef; eauto.\n      - eapply dirty_ppage_gso_undef; eauto.\n      - eapply consistent_pmap_gso_pperm_alloc; eauto.\n      - eapply consistent_pmap_domain_gso_at_0; eauto.\n      - eapply consistent_lat_domain_gss_nil; eauto.\n    Qed.\n\n    Global Instance trapin_inv: PrimInvariants trapin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance trapout_inv: PrimInvariants trapout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance hostin_inv: PrimInvariants hostin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance hostout_inv: PrimInvariants hostout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance ptin_inv: PrimInvariants ptin_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance ptout_inv: PrimInvariants ptout_spec.\n    Proof.\n      PrimInvariants_simpl H H0.\n    Qed.\n\n    Global Instance fstore_inv: PreservesInvariants fstore_spec.\n    Proof.\n      split; intros; inv_generic_sem H; inv H0; functional inversion H2.\n      - functional inversion H. split; trivial.        \n      - functional inversion H.\n        split; subst; simpl; \n        try (eapply dirty_ppage_store_unmaped; try reflexivity; try eassumption); trivial. \n      - functional inversion H0.\n        split; simpl; try assumption.\n    Qed.\n\n    Global Instance setPT_inv: PreservesInvariants setPT_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n    Qed.\n\n    Section PTINSERT.\n      \n      Section PTINSERT_PTE.\n\n        Lemma ptInsertPTE_high_level_inv:\n          forall d d' n vadr padr p,\n            ptInsertPTE0_spec n vadr padr p d = Some d' ->\n            high_level_invariant d ->\n            high_level_invariant d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n          inv H0; constructor_gso_simpl_tac; intros.\n          - eapply LAT_kern_norm; eauto. \n          - eapply LAT_usr_norm; eauto.\n          - eapply Lconsistent_ppage_norm; eassumption.\n          - eapply PMap_valid_gso_valid; eauto.\n          - functional inversion H2. functional inversion H1. \n            eapply PMap_kern_gso; eauto.\n          - functional inversion H2. functional inversion H0.\n            eapply consistent_pmap_ptp_same; try eassumption.\n            eapply consistent_pmap_gso_pperm_alloc'; eassumption.\n          - functional inversion H2.\n            eapply consistent_pmap_domain_append; eauto.\n            destruct (ZMap.get pti pdt); try contradiction;\n            red; intros (v0 & p0 & He); contra_inv. \n          - eapply consistent_lat_domain_gss_append; eauto.\n            subst pti; destruct (ZMap.get (PTX vadr) pdt); try contradiction;\n            red; intros (v0 & p0 & He); contra_inv. \n        Qed.\n\n        Lemma ptInsertPTE_low_level_inv:\n          forall d d' n vadr padr p n',\n            ptInsertPTE0_spec n vadr padr p d = Some d' ->\n            low_level_invariant n' d ->\n            low_level_invariant n' d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n          inv H0. constructor; eauto.\n        Qed.\n\n        Lemma ptInsertPTE_kernel_mode:\n          forall d d' n vadr padr p,\n            ptInsertPTE0_spec n vadr padr p d = Some d' ->\n            kernel_mode d ->\n            kernel_mode d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n        Qed.\n\n      End PTINSERT_PTE.\n\n      Section PTALLOCPDE.\n\n        Lemma ptAllocPDE_high_level_inv:\n          forall d d' n vadr v,\n            ptAllocPDE0_spec n vadr d = Some (d', v) ->\n            high_level_invariant d ->\n            high_level_invariant d'.\n        Proof.\n          intros. functional inversion H; subst; eauto. \n          inv H0; constructor_gso_simpl_tac; intros.\n          - eapply LAT_kern_norm; eauto. eapply _x.\n          - eapply LAT_usr_norm; eauto.\n          - eapply alloc_container_valid'; eauto.\n          - apply Lconsistent_ppage_norm_hide; try assumption.\n          - congruence.\n          - eapply PMap_valid_gso_pde_unp; eauto.\n            eapply real_init_PTE_defined.\n          - functional inversion H3. \n            eapply PMap_kern_gso; eauto.\n          - eapply dirty_ppage_gss; eauto.\n          - eapply consistent_pmap_ptp_gss; eauto; apply _x.\n          - eapply consistent_pmap_domain_gso_at_false; eauto; try apply _x.\n            eapply consistent_pmap_domain_ptp_unp; eauto.\n            apply real_init_PTE_unp.\n          - apply consistent_lat_domain_gss_nil; eauto.\n            apply consistent_lat_domain_gso_p; eauto.\n          - zmap_solve.\n        Qed.\n\n        Lemma ptAllocPDE_low_level_inv:\n          forall d d' n vadr v n',\n            ptAllocPDE0_spec n vadr d = Some (d', v) ->\n            low_level_invariant n' d ->\n            low_level_invariant n' d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n          inv H0. constructor; eauto.\n        Qed.\n\n        Lemma ptAllocPDE_kernel_mode:\n          forall d d' n vadr v,\n            ptAllocPDE0_spec n vadr d = Some (d', v) ->\n            kernel_mode d ->\n            kernel_mode d'.\n        Proof.\n          intros. functional inversion H; subst; eauto.\n        Qed.\n\n      End PTALLOCPDE.\n\n      Lemma ptInsert_high_level_inv:\n        forall d d' n vadr padr p v,\n          ptInsert0_spec n vadr padr p d = Some (d', v) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        - eapply ptInsertPTE_high_level_inv; eassumption.\n        - eapply ptAllocPDE_high_level_inv; eassumption.\n        - eapply ptInsertPTE_high_level_inv; try eassumption.\n          eapply ptAllocPDE_high_level_inv; eassumption.\n      Qed.\n\n      Lemma ptInsert_low_level_inv:\n        forall d d' n vadr padr p n' v,\n          ptInsert0_spec n vadr padr p d = Some (d', v) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        - eapply ptInsertPTE_low_level_inv; eassumption.\n        - eapply ptAllocPDE_low_level_inv; eassumption.\n        - eapply ptInsertPTE_low_level_inv; try eassumption.\n          eapply ptAllocPDE_low_level_inv; eassumption.\n      Qed.\n\n      Lemma ptInsert_kernel_mode:\n        forall d d' n vadr padr p v,\n          ptInsert0_spec n vadr padr p d = Some (d', v) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        - eapply ptInsertPTE_kernel_mode; eassumption.\n        - eapply ptAllocPDE_kernel_mode; eassumption.\n        - eapply ptInsertPTE_kernel_mode; try eassumption.\n          eapply ptAllocPDE_kernel_mode; eassumption.\n      Qed.\n\n    End PTINSERT.\n\n    Section PTRESV.\n\n      Lemma ptResv_high_level_inv:\n        forall d d' n vadr p v,\n          ptResv_spec n vadr p d = Some (d', v) ->\n          high_level_invariant d ->\n          high_level_invariant d'.\n      Proof.\n        intros. functional inversion H; subst; eauto. \n        eapply ptInsert_high_level_inv; try eassumption.\n        eapply alloc_high_level_inv; eassumption.\n      Qed.\n\n      Lemma ptResv_low_level_inv:\n        forall d d' n vadr p n' v,\n          ptResv_spec n vadr p d = Some (d', v) ->\n          low_level_invariant n' d ->\n          low_level_invariant n' d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        eapply ptInsert_low_level_inv; try eassumption.\n        eapply alloc_low_level_inv; eassumption.\n      Qed.\n\n      Lemma ptResv_kernel_mode:\n        forall d d' n vadr p v,\n          ptResv_spec n vadr p d = Some (d', v) ->\n          kernel_mode d ->\n          kernel_mode d'.\n      Proof.\n        intros. functional inversion H; subst; eauto.\n        eapply ptInsert_kernel_mode; try eassumption.\n        eapply alloc_kernel_mode; eassumption.\n      Qed.\n\n      Global Instance ptResv_inv: PreservesInvariants ptResv_spec.\n      Proof.\n        preserves_invariants_simpl'.\n        - eapply ptResv_low_level_inv; eassumption.\n        - eapply ptResv_high_level_inv; eassumption.\n        - eapply ptResv_kernel_mode; eassumption.\n      Qed.\n\n    End PTRESV.\n\n    Section OFFER_SHARE.\n\n      Section PTRESV2.\n\n        Lemma ptResv2_high_level_inv:\n          forall d d' n vadr p n' vadr' p' v,\n            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n            high_level_invariant d ->\n            high_level_invariant d'.\n        Proof.\n          intros; functional inversion H; subst; eauto;\n          eapply ptInsert_high_level_inv; try eassumption.\n          - eapply alloc_high_level_inv; eassumption.\n          - eapply ptInsert_high_level_inv; try eassumption.\n            eapply alloc_high_level_inv; eassumption.\n        Qed.\n\n        Lemma ptResv2_low_level_inv:\n          forall d d' n vadr p n' vadr' p' l v,\n            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n            low_level_invariant l d ->\n            low_level_invariant l d'.\n        Proof.\n          intros; functional inversion H; subst; eauto;\n          eapply ptInsert_low_level_inv; try eassumption.\n          - eapply alloc_low_level_inv; eassumption.\n          - eapply ptInsert_low_level_inv; try eassumption.\n            eapply alloc_low_level_inv; eassumption.\n        Qed.\n\n        Lemma ptResv2_kernel_mode:\n          forall d d' n vadr p n' vadr' p' v,\n            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->\n            kernel_mode d ->\n            kernel_mode d'.\n        Proof.\n          intros; functional inversion H; subst; eauto;\n          eapply ptInsert_kernel_mode; try eassumption.\n          - eapply alloc_kernel_mode; eassumption.\n          - eapply ptInsert_kernel_mode; try eassumption.\n            eapply alloc_kernel_mode; eassumption.\n        Qed.\n\n      End PTRESV2.\n\n      Global Instance offer_shared_mem_inv: \n        PreservesInvariants offer_shared_mem_spec.\n      Proof.\n        preserves_invariants_simpl';\n        functional inversion H2; subst; eauto 2; try (inv H0; constructor; trivial; fail).\n        - exploit ptResv2_low_level_inv; eauto.\n          intros HP; inv HP. constructor; trivial.\n        - exploit ptResv2_low_level_inv; eauto.\n          intros HP; inv HP. constructor; trivial.\n        - exploit ptResv2_high_level_inv; eauto.\n          intros HP; inv HP. constructor; trivial.\n        - exploit ptResv2_high_level_inv; eauto.\n          intros HP; inv HP. constructor; trivial.\n        - exploit ptResv2_kernel_mode; eauto.\n        - exploit ptResv2_kernel_mode; eauto.\n      Qed.\n\n    End OFFER_SHARE.\n\n    Global Instance shared_mem_status_inv: \n      PreservesInvariants shared_mem_status_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.\n    Qed.\n\n    Global Instance kctxt_switch_inv: KCtxtSwitchInvariants kctxt_switch_spec.\n    Proof.\n      constructor; intros; functional inversion H. \n      - inv H1. constructor; trivial. \n        eapply kctxt_inject_neutral_gss_mem; eauto.\n      - inv H0. subst. constructor; auto; simpl in *; intros; try congruence.\n    Qed.\n\n    Global Instance kctxt_new_inv: DNewInvariants ObjThread.kctxt_new_spec.\n    Proof.\n      constructor; intros; inv H0;\n      unfold ObjThread.kctxt_new_spec in *; subdestruct; inv H; simpl; auto.\n      - (* low level invariant *)\n        constructor; trivial; intros; simpl in *.\n        eapply kctxt_inject_neutral_gss_flatinj'; eauto.\n        eapply kctxt_inject_neutral_gss_flatinj; eauto.\n\n      - (* high_level_invariant *)\n        constructor; simpl; eauto 2; try congruence; intros.\n        + exploit split_container_valid; eauto.\n          eapply container_split_some; eauto.\n          auto.\n        + unfold update_cusage, update_cchildren; zmap_solve.\n    Qed.\n\n    Global Instance thread_init_inv: PreservesInvariants thread_init_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant.\n      - apply real_nps_range.\n      - apply real_lat_kern_valid.\n      - apply real_lat_usr_valid.\n      - apply real_container_valid.\n      - rewrite init_pperm0; try assumption.\n        apply Lreal_pperm_valid.        \n      - eapply real_pt_PMap_valid; eauto.\n      - apply real_pt_PMap_kern.\n      - omega.\n      - assumption.\n      - apply real_idpde_init.\n      - apply real_pt_consistent_pmap. \n      - apply real_pt_consistent_pmap_domain. \n      - apply Lreal_at_consistent_lat_domain.\n      - apply real_TCB_valid.\n    Qed.\n      \n    Global Instance set_state_inv: PreservesInvariants set_state_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto 2.\n      eapply TCBCorrect_range_gso; eauto.\n    Qed.\n\n    Global Instance set_prev_inv: PreservesInvariants set_prev_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto 2.\n      eapply TCBCorrect_range_gss_prev; eauto.\n    Qed.\n\n    Global Instance set_next_inv: PreservesInvariants set_next_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto 2.\n      eapply TCBCorrect_range_gss_next; eauto.\n    Qed.\n\n    Global Instance clearCR2_inv: PreservesInvariants clearCR2_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n    Qed.\n\n    (*Global Instance thread_free_inv: PreservesInvariants (fun a d => thread_free_spec d a).\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.\n      - destruct (zeq i0 (Int.unsigned i)); subst.\n        + rewrite ZMap.gss. apply PT_init_common_pdt_usr.\n          apply real_free_pt_valid; apply valid_PT_common0; auto.\n        + rewrite ZMap.gso; auto.\n      - destruct (zeq (Int.unsigned i) 0); subst. omega.\n        rewrite ZMap.gso; auto.\n      - destruct (zeq (Int.unsigned i) 0); subst. omega.\n        rewrite ZMap.gso; auto.\n      - unfold PTB_defined in *; intros.\n        destruct (zeq (Int.unsigned i) i0); subst.\n        rewrite ZMap.gss.\n        red; intros HF; inv HF.\n        rewrite ZMap.gso; auto.\n      - unfold TCBCorrect_range in *; intros.\n        unfold TCBCorrect in *.\n        destruct (zeq i0 (Int.unsigned i)); subst.\n        + rewrite ZMap.gss.\n          refine_split'; eauto; omega.\n        + rewrite ZMap.gso; eauto.\n    Qed.*)\n\n    Global Instance flatmem_copy_inv: PreservesInvariants flatmem_copy_spec.\n    Proof.\n      preserves_invariants_simpl low_level_invariant high_level_invariant;      \n      try eapply dirty_ppage_gss_copy; eauto.\n    Qed.\n\n    Global Instance device_output_inv: PreservesInvariants device_output_spec.\n    Proof. \n      preserves_invariants_simpl'' low_level_invariant high_level_invariant; eauto.\n    Qed.\n\n  End INV.\n\n  Definition exec_loadex {F V} := exec_loadex2 (F := F) (V := V).\n\n  Definition exec_storeex {F V} :=  exec_storeex2 (flatmem_store:= flatmem_store) (F := F) (V := V).\n\n  Global Instance flatmem_store_inv: FlatmemStoreInvariant (flatmem_store:= flatmem_store).\n  Proof.\n    split; inversion 1; intros. \n    - functional inversion H0. split; trivial.\n    - functional inversion H1. \n      split; simpl; try (eapply dirty_ppage_store_unmaped'; try reflexivity; try eassumption); trivial.\n  Qed.\n\n  Global Instance trapinfo_set_inv: TrapinfoSetInvariant.\n  Proof.\n    split; inversion 1; intros; constructor; auto.\n  Qed.\n\n  (** * Layer Definition *)\n  Definition pthreadinit_fresh : compatlayer (cdata RData) :=\n    thread_init ↦ gensem thread_init_spec.\n    (*⊕ thread_free ↦ gensem thread_free_spec*)                \n\n  Definition pthreadinit_passthrough : compatlayer (cdata RData) :=\n    fload ↦ gensem fload_spec\n          ⊕ fstore ↦ gensem fstore_spec\n          ⊕ flatmem_copy ↦ gensem flatmem_copy_spec\n          ⊕ vmxinfo_get ↦ gensem vmxinfo_get_spec\n          ⊕ device_output ↦ gensem device_output_spec\n          ⊕ pfree ↦ gensem pfree_spec\n          ⊕ set_pt ↦ gensem setPT_spec\n          ⊕ pt_read ↦ gensem ptRead_spec\n          ⊕ pt_resv ↦ gensem ptResv_spec\n          (*⊕ pt_free ↦ gensem pt_free_spec*)\n          ⊕ kctxt_new ↦ dnew_compatsem ObjThread.kctxt_new_spec\n          ⊕ shared_mem_status ↦ gensem shared_mem_status_spec\n          ⊕ offer_shared_mem ↦ gensem offer_shared_mem_spec\n          ⊕ get_state ↦ gensem get_state_spec\n          ⊕ get_prev ↦ gensem get_prev_spec\n          ⊕ get_next ↦ gensem get_next_spec\n          ⊕ set_state ↦ gensem set_state_spec\n          ⊕ set_prev ↦ gensem set_prev_spec\n          ⊕ set_next ↦ gensem set_next_spec\n\n          ⊕ pt_in ↦ primcall_general_compatsem' ptin_spec (prim_ident:= pt_in)\n          ⊕ pt_out ↦ primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)\n          ⊕ clear_cr2 ↦ gensem clearCR2_spec\n          ⊕ container_get_nchildren ↦ gensem container_get_nchildren_spec\n          ⊕ container_get_quota ↦ gensem container_get_quota_spec\n          ⊕ container_get_usage ↦ gensem container_get_usage_spec\n          ⊕ container_can_consume ↦ gensem container_can_consume_spec\n          ⊕ container_alloc ↦ gensem alloc_spec\n          ⊕ trap_in ↦ primcall_general_compatsem trapin_spec\n          ⊕ trap_out ↦ primcall_general_compatsem trapout_spec\n          ⊕ host_in ↦ primcall_general_compatsem hostin_spec\n          ⊕ host_out ↦ primcall_general_compatsem hostout_spec\n          ⊕ trap_get ↦ primcall_trap_info_get_compatsem trap_info_get_spec\n          ⊕ trap_set ↦ primcall_trap_info_ret_compatsem trap_info_ret_spec\n          ⊕ kctxt_switch ↦ primcall_kctxt_switch_compatsem kctxt_switch_spec\n          ⊕ accessors ↦ {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.\n\n  Definition pthreadinit : compatlayer (cdata RData) := pthreadinit_fresh ⊕ pthreadinit_passthrough.\n\n  (*Definition semantics := LAsm.Lsemantics pthreadinit.*)\n\nEnd WITHMEM.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/proc/PThreadInit.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.3345894478883556, "lm_q1q2_score": 0.21193239041078626}}
{"text": "Require Import VST.concurrency.conclib.\nRequire Import VST.progs.ghost.\n(*Require Import VST.progs.list_dt. Import LsegSpecial.*)\nRequire Import VST.floyd.library.\nRequire Import VST.progs.lock_coupling.\nRequire Import Sorting.\n\nRequire Export VST.floyd.Funspec_old_Notation.\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition acquire_spec := DECLARE _acquire acquire_spec.\nDefinition release_spec := DECLARE _release release_spec.\nDefinition makelock_spec := DECLARE _makelock (makelock_spec _).\nDefinition freelock_spec := DECLARE _freelock (freelock_spec _).\n\nDefinition surely_malloc_spec :=\n DECLARE _surely_malloc\n   WITH n:Z\n   PRE [ _n OF tuint ]\n       PROP (0 <= n <= Int.max_unsigned)\n       LOCAL (temp _n (Vint (Int.repr n)))\n       SEP ()\n    POST [ tptr tvoid ] EX p:_,\n       PROP ()\n       LOCAL (temp ret_temp p)\n       SEP (malloc_token Tsh n p * memory_block Tsh n p).\n\nDefinition tnode := Tstruct _node noattr.\n\nModule ZOrder <: Orders.TotalLeBool.\n  Definition t := Z.\n  Definition leb x y := Z.leb x y.\n  Theorem leb_total : forall x y, leb x y = true \\/ leb y x = true.\n  Proof. intros; destruct (Zle_bool_total x y); auto. Qed.\nEnd ZOrder.\n\nModule Import ZSort := Sort ZOrder.\n\nLemma StronglySorted_imp : forall (R R' : Z -> Z -> Prop) l (HR' : forall x y, R x y -> R' x y)\n  (HR : StronglySorted R l), StronglySorted R' l.\nProof.\n  intros; induction HR; constructor; auto.\n  eapply Forall_impl, H; auto.\nQed.\n\nNotation sorted := (StronglySorted Z.le).\n\nLemma sort_sorted : forall l, sorted (sort l).\nProof.\n  intro; eapply StronglySorted_imp, StronglySorted_sort.\n  - intros.\n    rewrite <- Z.leb_le; auto.\n  - intros ???; apply Zle_bool_trans.\nQed.\n\nInductive set_op := Add (e : Z) | Remove (e : Z).\n\nFixpoint apply_hist S h :=\n  match h with\n  | [] => S\n  | Add e :: h' => if in_dec Z_eq_dec e S then apply_hist S h' else apply_hist (sort (e :: S)) h'\n  | Remove e :: h' => apply_hist (remove Z_eq_dec e S) h'\n  end.\n\nLemma apply_hist_app : forall h1 S h2, apply_hist S (h1 ++ h2) = apply_hist (apply_hist S h1) h2.\nProof.\n  induction h1; auto; simpl; intros.\n  destruct a; auto.\n  destruct (in_dec _ _ _); auto.\nQed.\n\n(* up *)\nLemma In_remove : forall A (a : A) dec l, incl (remove dec a l) l.\nProof.\n  induction l; simpl; auto.\n  destruct (dec a a0).\n  - apply incl_tl; auto.\n  - apply incl_same_head; auto.\nQed.\n\nLemma remove_sorted : forall a l, sorted l -> sorted (remove Z_eq_dec a l).\nProof.\n  induction l; auto; simpl; intro.\n  inv H.\n  destruct (Z.eq_dec a a0); auto.\n  constructor; auto.\n  rewrite Forall_forall in *; intros ? Hin.\n  apply In_remove in Hin; auto.\nQed.\n\nLemma apply_hist_sorted : forall h S, sorted S -> sorted (apply_hist S h).\nProof.\n  induction h; auto; simpl; intros.\n  destruct a.\n  - destruct (in_dec _ _ _); auto.\n    apply IHh, sort_sorted.\n  - apply IHh, remove_sorted; auto.\nQed.\n\nDefinition hist := hist_part set_op.\n\n(*Definition q_lock_pred' (t : type) P p (vals : list (val * reptype t)) head (addc remc : val) lock gsh h :=\n  !!(Zlength vals <= MAX /\\ 0 <= head < MAX /\\ consistent h [] vals) &&\n  (data_at Tsh tqueue (rotate (complete MAX (map fst vals)) head MAX, (vint (Zlength vals),\n                      (vint head, (vint ((head + Zlength vals) mod MAX), (addc, remc))))) p *\n   cond_var Tsh addc * cond_var Tsh remc * malloc_token Tsh (sizeof tqueue_t) p *\n   malloc_token Tsh (sizeof tcond) addc * malloc_token Tsh (sizeof tcond) remc *\n   malloc_token Tsh (sizeof tlock) lock * ghost gsh (Tsh, h) p *\n   fold_right sepcon emp (map (fun x => let '(p, v) := x in \n     !!(P v) && (data_at Tsh t v p * malloc_token Tsh (sizeof t) p)) vals)).\n\nDefinition q_lock_pred A P p lock gsh := EX vals : list (val * reptype A), EX head : Z,\n  EX addc : val, EX remc : val, EX h : hist _, q_lock_pred' A P p vals head addc remc lock gsh h.*)\n\nDefinition node_lock_inv e p := EX n : val, EX l : val,(*EX h : list set_op,*)\n  field_at Tsh tnode [StructField _val] (vint e) p *\n  field_at Tsh tnode [StructField _next] n p * field_at Tsh tnode [StructField _lock] l n *\n  node_lock_inv.\n\nDefinition node_pred sh e p := EX l : val,\n  !!((*sepalg.join gsh1 gsh2 Tsh /\\*) repable_signed e /\\ field_compatible tnode [] p) &&\n  (field_at sh tnode [StructField _lock] l p *\n   lock_inv sh l (node_lock_inv e p) (* * ghost gsh1 (lsh, h) p*)).\n\nDefinition new_node_spec :=\n DECLARE _new_node\n  WITH e : Z\n  PRE [ _e OF tint ]\n   PROP (repable_signed e)\n   LOCAL (temp _e (vint e))\n   SEP ()\n  POST [ tptr tnode ]\n   EX p : val,\n   PROP ()\n   LOCAL (temp ret_temp p)\n   SEP (node_pred Tsh e p).\n\nDefinition del_node_spec :=\n DECLARE _new_node\n  WITH e : Z, p : val\n  PRE [ _n OF tptr tnode ]\n   PROP ()\n   LOCAL (temp _n p)\n   SEP (node_pred Tsh e p)\n  POST [ tvoid ]\n   PROP ()\n   LOCAL ()\n   SEP ().\n\nDefinition tnode_pair := Tstruct _node_pair noattr.\n\nDefinition list_inv sh H h := node_pred sh Int.min_signed H * ghost_hist h H.\n\nDefinition locate_spec :=\n DECLARE _locate\n  WITH e : Z, sh : share, H : val, h : hist\n  PRE [ _e OF tint ]\n   PROP (repable_signed e)\n   LOCAL (temp _e (vint e); gvar _head H)\n   SEP (list_inv sh H h)\n  POST [ tptr tnode_pair ]\n   EX h' : hist, EX p : val, EX n1 : val, EX n2 : val, EX e1 : Z, EX e2 : Z, EX sh : share,\n   PROP (incl h h'; e1 < e <= e2)\n   LOCAL ()\n   SEP (list_inv H h'; data_at Tsh tnode_pair (n1, n2) p; node_pred sh e1 n1;\n        field_at Tsh tnode [StructField _val] (vint e1) n1; field_at Tsh tnode [StructField _next] n2 n1;\n        node_pred sh e2 n2; node_lock_inv e2 n2).\n\nDefinition add_spec :=\n DECLARE _add\n  WITH e : Z, H : val, h : hist\n  PRE [ _e OF tint ]\n   PROP (repable_signed e)\n   LOCAL (temp _e (vint e); gvar _head H)\n   SEP (list_inv H h)\n  POST [ tint ]\n   EX h' : hist, EX S : list Z, EX t' : nat,\n   PROP (incl h h'; apply_hist [] h' = S)\n   LOCAL (temp ret_temp (if in_dec Z_eq_dec e S then 0 else 1))\n   SEP (list_inv H (h' ++ [(t', Add e)]).\n\nDefinition remove_spec :=\n DECLARE _remove\n  WITH e : Z, H : val, h : hist\n  PRE [ _e OF tint ]\n   PROP (repable_signed e)\n   LOCAL (temp _e (vint e); gvar _head H)\n   SEP (list_inv H h)\n  POST [ tint ]\n   EX h' : hist, EX S : list Z, EX t' : nat,\n   PROP (incl h h'; apply_hist [] h' = S)\n   LOCAL (temp ret_temp (if in_dec Z_eq_dec e S then 1 else 0))\n   SEP (list_inv H (h' ++ [(t', Remove e)]).\n\nDefinition main_spec :=\n DECLARE _main\n  WITH u : unit\n  PRE  [] main_pre prog tt nil u\n  POST [ tint ] main_post prog nil u.\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [acquire_spec; release_spec; makelock_spec;\n  freelock_spec; surely_malloc_spec; new_node_spec; del_node_spec; locate_spec; add_spec; remove_spec; main_spec]).\n\nLemma body_surely_malloc: semax_body Vprog Gprog f_surely_malloc surely_malloc_spec.\nProof.\n  start_function. \n  forward_call (* p = malloc(n); *)\n     n.\n  Intros p.\n  forward_if\n  (PROP ( )\n   LOCAL (temp _p p)\n   SEP (malloc_token Tsh n p * memory_block Tsh n p)).\n*\n  if_tac.\n    subst p. entailer!.\n    entailer!.\n*\n    forward_call tt.\n    contradiction.\n*\n    if_tac.\n    + forward. subst p. inv H0.\n    + Intros. forward. entailer!.\n*\n  forward. Exists p; entailer!.\nQed.\n\nLemma ctr_inv_precise : forall p,\n  precise (cptr_lock_inv p).\nProof.\n  intro; eapply derives_precise, data_at__precise with (sh := Ews)(t := tint); auto.\n  intros ? (? & H); apply data_at_data_at_ in H; eauto.\nQed.\n#[export] Hint Resolve ctr_inv_precise.\n\nLemma ctr_inv_positive : forall ctr,\n  positive_mpred (cptr_lock_inv ctr).\nProof.\n  intro; apply ex_positive; auto.\nQed.\n#[export] Hint Resolve ctr_inv_positive.\n\nLemma body_incr: semax_body Vprog Gprog f_incr incr_spec.\nProof.\n  start_function.\n  forward.\n  forward_call (lock, sh, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  unfold cptr_lock_inv at 2; simpl.\n  Intro z.\n  forward.\n  forward.\n  rewrite field_at_isptr; Intros.\n  forward_call (lock, sh, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { lock_props.\n    unfold cptr_lock_inv; Exists (z + 1); entailer!. }\n  forward.\nQed.\n\nLemma body_read : semax_body Vprog Gprog f_read read_spec.\nProof.\n  start_function.\n  forward_call (lock, sh, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  unfold cptr_lock_inv at 2; simpl.\n  Intro z.\n  forward.\n  rewrite data_at_isptr; Intros.\n  forward_call (lock, sh, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { lock_props.\n    unfold cptr_lock_inv; Exists z; entailer!. }\n  forward.\n  Exists z; entailer!.\nQed.\n\nLemma body_thread_func : semax_body Vprog Gprog f_thread_func thread_func_spec.\nProof.\n  start_function.\n  Intros.\n  forward.\n  forward_call (ctr, sh, lock).\n  forward_call (lockt, sh, lock_inv sh lock (cptr_lock_inv ctr), thread_lock_inv sh ctr lock lockt).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { unfold thread_lock_inv; lock_props.\n    rewrite selflock_eq at 2; cancel.\n    eapply derives_trans; [apply lock_inv_later | cancel]. }\n  forward.\nQed.\n\nLemma lock_struct : forall p, data_at_ Ews (Tstruct _lock_t noattr) p |-- data_at_ Ews tlock p.\nProof.\n  intros.\n  unfold data_at_, field_at_; unfold_field_at 1%nat.\n  unfold field_at; simpl.\n  rewrite field_compatible_cons; simpl; entailer.\n  (* temporarily broken *)\nAdmitted.\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\n  name ctr _ctr; name lockt _thread_lock; name lock _ctr_lock.\n  start_function.\n  forward.\n  forward.\n  forward.\n  forward_call (lock, Ews, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { rewrite (sepcon_comm _ (fold_right_sepcon _)); apply sepcon_derives; [cancel | apply lock_struct]. }\n  rewrite field_at_isptr; Intros.\n  forward_call (lock, Ews, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { lock_props.\n    unfold cptr_lock_inv; Exists 0; cancel. }\n  (* need to split off shares for the locks here *)\n  destruct split_Ews as (sh1 & sh2 & ? & ? & Hsh).\n  forward_call (lockt, Ews, thread_lock_inv sh1 ctr lock lockt).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { rewrite (sepcon_comm _ (fold_right_sepcon _)); apply sepcon_derives; [cancel | apply lock_struct]. }\n  get_global_function'' _thread_func.\n  apply extract_exists_pre; intros f_.\n  forward_spawn (val * share * val * val)%type (f_, Vint (Int.repr 0), (ctr, sh1, lock, lockt),\n    fun (x : (val * share * val * val)) (_ : val) => let '(ctr, sh, lock, lockt) := x in\n         !!readable_share sh && emp * lock_inv sh lock (cptr_lock_inv ctr) *\n         lock_inv sh lockt (thread_lock_inv sh ctr lock lockt)).\n  { simpl spawn_pre; entailer!.\n    Exists _args (fun x : val * share * val * val => let '(ctr, sh, lock, lockt) := x in\n      [(_ctr, ctr); (_ctr_lock, lock); (_thread_lock, lockt)]); entailer.\n    rewrite !sepcon_assoc; apply sepcon_derives.\n    { apply derives_refl'. f_equal.\n      unfold NDmk_funspec.\n      apply mk_funspec_congr; auto.\n      apply eq_JMeq.\n      extensionality x x0.\n      destruct x0 as (?, (((?, ?), ?), ?)); simpl.\n      rewrite <- !sepcon_assoc; reflexivity.  }\n    erewrite <- lock_inv_share_join; try apply Hsh; auto.\n    erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto.\n    entailer!. }\n  forward_call (ctr, sh2, lock).\n  forward_call (lockt, sh2, thread_lock_inv sh1 ctr lock lockt).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  forward_call (ctr, sh2, lock).\n  Intro z.\n  forward_call (lock, sh2, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  forward_call (lockt, Ews, sh1, |>lock_inv sh1 lock (cptr_lock_inv ctr), |>thread_lock_inv sh1 ctr lock lockt).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { unfold thread_lock_inv; lock_props.\n    - apply later_positive; auto.\n    - unfold rec_inv.\n      rewrite selflock_eq at 1.\n      rewrite later_sepcon; f_equal.\n      apply lock_inv_later_eq.\n    - rewrite selflock_eq at 2.\n      erewrite <- (lock_inv_share_join _ _ Ews); try apply Hsh; auto; cancel.\n      rewrite sepcon_comm, <- !sepcon_assoc, sepcon_comm.\n      apply sepcon_derives; [apply lock_inv_later | cancel]. }\n  forward_call (lock, Ews, cptr_lock_inv ctr).\n  { apply prop_right; rewrite sem_cast_neutral_ptr; rewrite sem_cast_neutral_ptr; auto. }\n  { lock_props.\n    erewrite sepcon_assoc, lock_inv_share_join; eauto; cancel. }\n  forward.\nQed.\n\nDefinition extlink := ext_link_prog prog.\nDefinition Espec := add_funspecs (Concurrent_Espec unit _ extlink) extlink Gprog.\n#[export] Existing Instance Espec.\n\nLemma prog_correct:\n  semax_prog prog tt Vprog Gprog.\nProof.\nprove_semax_prog.\nrepeat (apply semax_func_cons_ext_vacuous; [reflexivity | reflexivity | ]).\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons_ext.\nsemax_func_cons body_incr.\nsemax_func_cons body_read.\nsemax_func_cons body_thread_func.\nsemax_func_cons body_main.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/verif_lock_coupling.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.21185880808384294}}
{"text": "Require Import Fiat.QueryStructure.Automation.MasterPlan.\nRequire Import Bedrock.Memory.\n\nInstance : Query_eq (Word.word n) :=\n  { A_eq_dec := @Word.weq n }.\nOpaque Word.weq.\nOpaque Word.natToWord.\nOpaque Word.wlt_dec.\nDefinition WordMax (w w' : W) :=\n  if Word.wlt_dec w w' then w' else w.\nDefinition MaxW (rows : Comp (list W)) : Comp (option W) :=\n  FoldAggregateOption WordMax rows.\n\nDefinition VALUE := \"VALUE\".\nDefinition MEASUREMENT_TYPE := \"MEASUREMENT_TYPE\".\nDefinition TIME := \"TIME\".\nDefinition CELL_ID := \"CELL_ID\".\n\nDefinition STATE := \"STATE\".\nDefinition AREA_CODE := \"AREA_CODE\".\nDefinition DETAILS := \"DETAILS\".\nDefinition DAY := \"DAY\".\n\nDefinition WIND := 0.\nDefinition HUMIDITY := 1.\nDefinition TEMPERATURE := 2.\nDefinition PRESSURE := 3.\n\nDefinition MEASUREMENTS := \"MEASUREMENTS\".\nDefinition CELLS := \"CELLS\".\n\nDefinition MeasurementType := W.\n\nDefinition WeatherSchema :=\n  Query Structure Schema\n    [ relation CELLS has\n              schema <CELL_ID :: W,\n                      AREA_CODE :: W,\n                      DETAILS :: W>;\n      relation MEASUREMENTS has\n              schema <CELL_ID :: W,\n                      VALUE :: W,\n                      MEASUREMENT_TYPE :: MeasurementType,\n                      DAY :: W,\n                      TIME :: W> ]\n    enforcing [attribute CELL_ID for MEASUREMENTS references CELLS].\n\n(* Try with three tables (distribution of areas per state) *)\n\nDefinition Init := \"Init\".\nDefinition AddCell := \"AddCell\".\nDefinition AddMeasurement := \"AddMeasurement\".\nDefinition CountCells := \"CountCells\".\nDefinition LocalMax := \"LocalMax\".\n\nDefinition WeatherSpec : ADT _ :=\n  Eval simpl in\n    Def ADT {\n      rep := QueryStructure WeatherSchema,\n    Def Constructor0 Init : rep := empty,,\n\n    Def Method1 AddCell (r : rep) (cell : WeatherSchema#CELLS) : rep * bool :=\n      Insert cell into r!CELLS,\n\n    Def Method1 AddMeasurement (r : rep) (measurement : WeatherSchema#MEASUREMENTS) : rep * bool :=\n      Insert measurement into r!MEASUREMENTS,\n\n    Def Method1 CountCells (r : rep) (area : W) : rep * nat :=\n      cnt <- Count (For (cell in r!CELLS)\n                        Where (area = cell!AREA_CODE)\n                        Return 1);\n    ret (r, cnt),\n\n    Def Method2 LocalMax (r : rep) (areaC : W) (measType : MeasurementType) : rep * (option W) :=\n      max <- MaxW (For (cell in r!CELLS) (measurement in r!MEASUREMENTS)\n            Where (cell!AREA_CODE = areaC)\n            Where (measurement!MEASUREMENT_TYPE = measType)\n            Where (cell!CELL_ID = measurement!CELL_ID)\n            Return measurement!VALUE);\n    ret (r, max)\n}%methDefParsing.\n\nDefinition SharpenedWeatherStation :\n  MostlySharpened WeatherSpec.\nProof.\n  start sharpening ADT.\n  simpl; pose_string_hyps; pose_heading_hyps.\n  start_honing_QueryStructure'.\n  GenerateIndexesForAll EqExpressionAttributeCounter\n  ltac:(fun attrlist =>\n          let attrlist' := eval compute in (PickIndexes _ (CountAttributes' attrlist)) in\n              make_simple_indexes attrlist'\n                                  ltac:(LastCombineCase6 BuildEarlyEqualityIndex)\n                                         ltac:(LastCombineCase5 BuildLastEqualityIndex)).\n  + plan EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n         EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.\n  + plan EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n         EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.\n  + setoid_rewrite refine_For_rev; simplify with monad laws.\n    plan EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n         EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.\n  + setoid_rewrite refine_For_rev; simplify with monad laws.\n    plan EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n         EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.\n  + setoid_rewrite refine_For_rev; simplify with monad laws.\n    plan EqIndexUse createEarlyEqualityTerm createLastEqualityTerm\n         EqIndexUse_dep createEarlyEqualityTerm_dep createLastEqualityTerm_dep.\n  + hone method \"AddMeasurement\".\n    { simpl in *; subst.\n      setoid_rewrite refine_Count; simplify with monad laws.\n      setoid_rewrite app_nil_r;\n        setoid_rewrite map_map; simpl.\n      unfold ilist2_hd at 1; simpl.\n      setoid_rewrite rev_length.\n      setoid_rewrite map_length.\n      setoid_rewrite refine_pick_eq'; simplify with monad laws.\n      repeat setoid_rewrite refine_If_Then_Else_Bind.\n      repeat setoid_rewrite refineEquiv_bind_bind.\n      repeat setoid_rewrite refineEquiv_bind_unit; simpl.\n      unfold H1.\n      eapply refine_under_bind; intros; set_evars.\n      rewrite (CallBagFind_fst H0); simpl.\n      finish honing.\n    }\n    hone method \"CountCells\".\n    { simpl in *; subst; simplify with monad laws.\n      setoid_rewrite refine_Count; simplify with monad laws.\n      unfold H1; eapply refine_under_bind; intros; set_evars.\n      rewrite (CallBagFind_fst H0); simpl.\n      setoid_rewrite refine_pick_eq'; simplify with monad laws.\n      rewrite rev_length.\n      rewrite !map_length.\n      rewrite app_nil_r; simpl.\n      rewrite map_length.\n      finish honing.\n    }\n    hone method \"LocalMax\".\n    { simpl in *; subst; simplify with monad laws.\n      unfold H1; eapply refine_under_bind; intros; set_evars.\n      rewrite (CallBagFind_fst H0); simpl.\n      etransitivity.\n      eapply refine_under_bind_both.\n      eapply (@Join_Comp_Lists_eq WeatherSchema Index (Fin.FS Fin.F1)).\n      intros; finish honing.\n      simplify with monad laws.\n      unfold H2; apply refine_under_bind; set_evars.\n      intros.\n      apply Join_Comp_Lists_eq' in H4; rewrite H4.\n      setoid_rewrite refine_pick_eq'; simplify with monad laws.\n      simpl.\n      finish honing.\n    }\n    simpl.\n\n    simpl; eapply reflexivityT.\n  + unfold CallBagFind, CallBagInsert.\n    pose_headings_all.\n    match goal with\n    | |- appcontext[ @BuildADT (IndexedQueryStructure ?Schema ?Indexes) ] =>\n      FullySharpenQueryStructure Schema Indexes\n    end.\n\nTime Defined.\n\nTime Definition WeatherStationImpl :=\n  Eval simpl in (fst (projT1 SharpenedWeatherStation)).\nPrint WeatherStationImpl.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Examples/QueryStructure/WeatherFacade.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.21185879985868428}}
{"text": "Require Import Coq.Init.Byte Coq.Strings.Byte Coq.Bool.Bvector.\nRequire Import Coq.Init.Nat.\nRequire Import Coq.omega.Omega.\n\nSection HelperDataTypesTypes.\n\nInductive nibble :=\n  |n0\n  |n1\n  |n2\n  |n3\n  |n4\n  |n5\n  |n6\n  |n7\n  |n8\n  |n9\n  |na\n  |nb\n  |nc\n  |nd\n  |ne\n  |nf.\n\nInductive register :=\n  |v0\n  |v1\n  |v2\n  |v3\n  |v4\n  |v5\n  |v6\n  |v7\n  |v8\n  |v9\n  |va\n  |vb\n  |vc\n  |vd\n  |ve\n  |vf.\n\nEnd HelperDataTypesTypes.\n\nSection HelperDataTypesCode.\n\nDefinition n_to_nat (n : nibble) : nat :=\n  match n with\n  |n0 => 0\n  |n1 => 1\n  |n2 => 2\n  |n3 => 3\n  |n4 => 4\n  |n5 => 5\n  |n6 => 6\n  |n7 => 7\n  |n8 => 8\n  |n9 => 9\n  |na => 10\n  |nb => 11\n  |nc => 12\n  |nd => 13\n  |ne => 14\n  |nf => 15\n  end.\n\nDefinition nib_eq (n1 n2 : nibble) : bool :=\n  eqb (n_to_nat n1) (n_to_nat n2).\n\nLocal Notation \"0\" := false.\nLocal Notation \"1\" := true.\n\nDefinition bits_to_n (n :  bool * (bool * (bool * bool))) : nibble :=\n  match n with\n  |(0,(0,(0,0))) => n0\n  |(1,(0,(0,0))) => n1\n  |(0,(1,(0,0))) => n2\n  |(1,(1,(0,0))) => n3\n  |(0,(0,(1,0))) => n4\n  |(1,(0,(1,0))) => n5\n  |(0,(1,(1,0))) => n6\n  |(1,(1,(1,0))) => n7\n  |(0,(0,(0,1))) => n8\n  |(1,(0,(0,1))) => n9\n  |(0,(1,(0,1))) => na\n  |(1,(1,(0,1))) => nb\n  |(0,(0,(1,1))) => nc\n  |(1,(0,(1,1))) => nd\n  |(0,(1,(1,1))) => ne\n  |(1,(1,(1,1))) => nf\n  end.\n\nDefinition byte_to_nib' (data : byte) : (nibble * nibble) := \n  match to_bits data with\n  | (a,(b,(c,(d,(e,(f,(g,h))))))) =>\n    let low  := (e,(f,(g,h))) in \n    let high := (a,(b,(c,d))) in\n    (bits_to_n low, bits_to_n high)\n  end.\n\nDefinition n_to_bits (n : nibble) : bool * (bool * (bool * bool)) :=\n  match n with\n    |n0 => (0, (0 ,(0 , 0)))\n    |n1 => (1 ,(0 ,(0 , 0)))\n    |n2 => (0 ,(1 ,(0 , 0)))\n    |n3 => (1 ,(1 ,(0 , 0)))\n    |n4 => (0 ,(0 ,(1 , 0)))\n    |n5 => (1 ,(0 ,(1 , 0)))\n    |n6 => (0 ,(1 ,(1 , 0)))\n    |n7 => (1 ,(1 ,(1 , 0)))\n    |n8 => (0 ,(0 ,(0 , 1)))\n    |n9 => (1 ,(0 ,(0 , 1)))\n    |na => (0 ,(1 ,(0 , 1)))\n    |nb => (1 ,(1 ,(0 , 1)))\n    |nc => (0 ,(0 ,(1 , 1)))\n    |nd => (1 ,(0 ,(1 , 1)))\n    |ne => (0 ,(1 ,(1 , 1)))\n    |nf => (1 ,(1 ,(1 , 1)))\n  end.\n\nDefinition nib_to_byte (nib_pair : (nibble * nibble)) : byte := \n  match nib_pair with\n  | (nHigh, nLow) =>\n      let '(a, (b, (c, d))) := n_to_bits nHigh in\n      let '(e, (f, (g, h))) := n_to_bits nLow in\n        of_bits (e,(f,(g,(h,(a,(b,(c,d)))))))\n  end.\n\nDefinition byte_to_nib (data : byte) : (nibble * nibble) :=\n   match data with\n     | x00 => (n0, n0)\n     | x01 => (n0, n1)\n     | x02 => (n0, n2)\n     | x03 => (n0, n3)\n     | x04 => (n0, n4)\n     | x05 => (n0, n5)                \n     | x06 => (n0, n6)\n     | x07 => (n0, n7)\n     | x08 => (n0, n8)\n     | x09 => (n0, n9)\n     | x0a => (n0, na)\n     | x0b => (n0, nb)\n     | x0c => (n0, nc)\n     | x0d => (n0, nd)\n     | x0e => (n0, ne)\n     | x0f => (n0, nf)\n     | x10 => (n1, n0)\n     | x11 => (n1, n1)\n     | x12 => (n1, n2)\n     | x13 => (n1, n3)\n     | x14 => (n1, n4)\n     | x15 => (n1, n5)\n     | x16 => (n1, n6)\n     | x17 => (n1, n7)\n     | x18 => (n1, n8)\n     | x19 => (n1, n9)\n     | x1a => (n1, na)\n     | x1b => (n1, nb)\n     | x1c => (n1, nc)\n     | x1d => (n1, nd)\n     | x1e => (n1, ne)\n     | x1f => (n1, nf)\n     | x20 => (n2, n0)\n     | x21 => (n2, n1)\n     | x22 => (n2, n2)\n     | x23 => (n2, n3)\n     | x24 => (n2, n4)\n     | x25 => (n2, n5)\n     | x26 => (n2, n6)\n     | x27 => (n2, n7)\n     | x28 => (n2, n8)\n     | x29 => (n2, n9)\n     | x2a => (n2, na)\n     | x2b => (n2, nb)\n     | x2c => (n2, nc)\n     | x2d => (n2, nd)\n     | x2e => (n2, ne)\n     | x2f => (n2, nf)\n     | x30 => (n3, n0)\n     | x31 => (n3, n1)\n     | x32 => (n3, n2)\n     | x33 => (n3, n3)\n     | x34 => (n3, n4)\n     | x35 => (n3, n5)\n     | x36 => (n3, n6)\n     | x37 => (n3, n7)\n     | x38 => (n3, n8)\n     | x39 => (n3, n9)\n     | x3a => (n3, na)\n     | x3b => (n3, nb)\n     | x3c => (n3, nc)\n     | x3d => (n3, nd)\n     | x3e => (n3, ne)\n     | x3f => (n3, nf)\n     | x40 => (n4, n0)\n     | x41 => (n4, n1)\n     | x42 => (n4, n2)\n     | x43 => (n4, n3)\n     | x44 => (n4, n4)\n     | x45 => (n4, n5)\n     | x46 => (n4, n6)\n     | x47 => (n4, n7)\n     | x48 => (n4, n8)\n     | x49 => (n4, n9)\n     | x4a => (n4, na)\n     | x4b => (n4, nb)\n     | x4c => (n4, nc)\n     | x4d => (n4, nd)\n     | x4e => (n4, ne)\n     | x4f => (n4, nf)\n     | x50 => (n5, n0)\n     | x51 => (n5, n1)\n     | x52 => (n5, n2)\n     | x53 => (n5, n3)\n     | x54 => (n5, n4)\n     | x55 => (n5, n5)\n     | x56 => (n5, n6)\n     | x57 => (n5, n7)\n     | x58 => (n5, n8)\n     | x59 => (n5, n9)\n     | x5a => (n5, na)\n     | x5b => (n5, nb)\n     | x5c => (n5, nc)\n     | x5d => (n5, nd)\n     | x5e => (n5, ne)\n     | x5f => (n5, nf)\n     | x60 => (n6, n0)\n     | x61 => (n6, n1)\n     | x62 => (n6, n2)\n     | x63 => (n6, n3)\n     | x64 => (n6, n4)\n     | x65 => (n6, n5)\n     | x66 => (n6, n6)\n     | x67 => (n6, n7)\n     | x68 => (n6, n8)\n     | x69 => (n6, n9)\n     | x6a => (n6, na)\n     | x6b => (n6, nb)\n     | x6c => (n6, nc)\n     | x6d => (n6, nd)\n     | x6e => (n6, ne)\n     | x6f => (n6, nf)\n     | x70 => (n7, n0)\n     | x71 => (n7, n1)\n     | x72 => (n7, n2)\n     | x73 => (n7, n3)\n     | x74 => (n7, n4)\n     | x75 => (n7, n5)\n     | x76 => (n7, n6)\n     | x77 => (n7, n7)\n     | x78 => (n7, n8)\n     | x79 => (n7, n9)\n     | x7a => (n7, na)\n     | x7b => (n7, nb)\n     | x7c => (n7, nc)\n     | x7d => (n7, nd)\n     | x7e => (n7, ne)\n     | x7f => (n7, nf)\n     | x80 => (n8, n0)\n     | x81 => (n8, n1)\n     | x82 => (n8, n2)\n     | x83 => (n8, n3)\n     | x84 => (n8, n4)\n     | x85 => (n8, n5)\n     | x86 => (n8, n6)\n     | x87 => (n8, n7)\n     | x88 => (n8, n8)\n     | x89 => (n8, n9)\n     | x8a => (n8, na)\n     | x8b => (n8, nb)\n     | x8c => (n8, nc)\n     | x8d => (n8, nd)\n     | x8e => (n8, ne)\n     | x8f => (n8, nf)\n     | x90 => (n9, n0)\n     | x91 => (n9, n1)\n     | x92 => (n9, n2)\n     | x93 => (n9, n3)\n     | x94 => (n9, n4)\n     | x95 => (n9, n5)\n     | x96 => (n9, n6)\n     | x97 => (n9, n7)\n     | x98 => (n9, n8)\n     | x99 => (n9, n9)\n     | x9a => (n9, na)\n     | x9b => (n9, nb)\n     | x9c => (n9, nc)\n     | x9d => (n9, nd)\n     | x9e => (n9, ne)\n     | x9f => (n9, nf)\n     | xa0 => (na, n0)\n     | xa1 => (na, n1)\n     | xa2 => (na, n2)\n     | xa3 => (na, n3)\n     | xa4 => (na, n4)\n     | xa5 => (na, n5)\n     | xa6 => (na, n6)\n     | xa7 => (na, n7)\n     | xa8 => (na, n8)\n     | xa9 => (na, n9)\n     | xaa => (na, na)\n     | xab => (na, nb)\n     | xac => (na, nc)\n     | xad => (na, nd)\n     | xae => (na, ne)\n     | xaf => (na, nf)\n     | xb0 => (nb, n0)\n     | xb1 => (nb, n1)\n     | xb2 => (nb, n2)\n     | xb3 => (nb, n3)\n     | xb4 => (nb, n4)\n     | xb5 => (nb, n5)\n     | xb6 => (nb, n6)\n     | xb7 => (nb, n7)\n     | xb8 => (nb, n8)\n     | xb9 => (nb, n9)\n     | xba => (nb, na)\n     | xbb => (nb, nb)\n     | xbc => (nb, nc)\n     | xbd => (nb, nd)\n     | xbe => (nb, ne)\n     | xbf => (nb, nf)\n     | xc0 => (nc, n0)\n     | xc1 => (nc, n1)\n     | xc2 => (nc, n2)\n     | xc3 => (nc, n3)\n     | xc4 => (nc, n4)\n     | xc5 => (nc, n5)\n     | xc6 => (nc, n6)\n     | xc7 => (nc, n7)\n     | xc8 => (nc, n8)\n     | xc9 => (nc, n9)\n     | xca => (nc, na)\n     | xcb => (nc, nb)\n     | xcc => (nc, nc)\n     | xcd => (nc, nd)\n     | xce => (nc, ne)\n     | xcf => (nc, nf)\n     | xd0 => (nd, n0)\n     | xd1 => (nd, n1)\n     | xd2 => (nd, n2)\n     | xd3 => (nd, n3)\n     | xd4 => (nd, n4)\n     | xd5 => (nd, n5)\n     | xd6 => (nd, n6)\n     | xd7 => (nd, n7)\n     | xd8 => (nd, n8)\n     | xd9 => (nd, n9)\n     | xda => (nd, na)\n     | xdb => (nd, nb)\n     | xdc => (nd, nc)\n     | xdd => (nd, nd)\n     | xde => (nd, ne)\n     | xdf => (nd, nf)\n     | xe0 => (ne, n0)\n     | xe1 => (ne, n1)\n     | xe2 => (ne, n2)\n     | xe3 => (ne, n3)\n     | xe4 => (ne, n4)\n     | xe5 => (ne, n5)\n     | xe6 => (ne, n6)\n     | xe7 => (ne, n7)\n     | xe8 => (ne, n8)\n     | xe9 => (ne, n9)\n     | xea => (ne, na)\n     | xeb => (ne, nb)\n     | xec => (ne, nc)\n     | xed => (ne, nd)\n     | xee => (ne, ne)\n     | xef => (ne, nf)\n     | xf0 => (nf, n0)\n     | xf1 => (nf, n1)\n     | xf2 => (nf, n2)\n     | xf3 => (nf, n3)\n     | xf4 => (nf, n4)\n     | xf5 => (nf, n5)\n     | xf6 => (nf, n6)\n     | xf7 => (nf, n7)\n     | xf8 => (nf, n8)\n     | xf9 => (nf, n9)\n     | xfa => (nf, na)\n     | xfb => (nf, nb)\n     | xfc => (nf, nc)\n     | xfd => (nf, nd)\n     | xfe => (nf, ne)\n     | xff => (nf, nf)\n     end.\n  \nDefinition byte_to_Bvector (b : byte) : Bvector 8 :=\n  match to_bits b with \n  | (a,(b,(c,(d,(e,(f,(g,h))))))) =>\n    [a;b;c;d;e;f;g;h]%vector\n  end.\n\nDefinition Bvector_to_byte (bv : Bvector 8) : byte :=\n  match bv with \n    | [a;b;c;d;e;f;g;h]%vector => \n      of_bits (a,(b,(c,(d,(e,(f,(g,h)))))))\n    | _ => x00\n  end.\n\nDefinition word_to_nat_le (bv : (byte * byte)) : nat :=\n  match bv with\n  | (b1, b2) =>\n    let n1 := to_nat b1 in\n    let n2 := 256 * (to_nat b2) in \n    n1 + n2\n  end.\n\nDefinition word_to_nat_be (bv : (byte * byte)) : nat :=\n  match bv with\n  | (b1, b2) => word_to_nat_le (b2, b1)\n  end.\n\nDefinition nat_to_word_le (n : nat) : (byte * byte) :=\n  let d := div n 256 in\n  let r := modulo n 256 in\n  match of_nat r with\n  | None => (x00,x00)\n  | Some x1 => \n    match of_nat d with\n    | None => (x00,x00)\n    | Some x2 => (x1, x2)\n    end\n  end.\n\nDefinition nat_to_word_be (n : nat) : (byte * byte) :=\n  let nat_to_le := nat_to_word_le n in\n  match nat_to_le with\n    (a,b) => (b,a)\n  end.\n\nDefinition register_to_nib (r : register) :=\n  match r with\n  |v0 => n0\n  |v1 => n1\n  |v2 => n2\n  |v3 => n3\n  |v4 => n4\n  |v5 => n5\n  |v6 => n6\n  |v7 => n7\n  |v8 => n8\n  |v9 => n9\n  |va => na\n  |vb => nb\n  |vc => nc\n  |vd => nd\n  |ve => ne\n  |vf => nf\n  end.\n\nDefinition nib_to_byte_low (nib : nibble) :=\n  nib_to_byte (n0, nib).\n\nDefinition nib_to_byte_high (nib : nibble) :=\n  nib_to_byte (nib, n0).\n\nEnd HelperDataTypesCode.\n\nSection HelperDataTypesProof.\n\nLemma to_nat_less_256 : forall b,\n    to_nat b < 256.\nProof.\n  intros.\n  destruct b ; simpl ; omega.\nQed.\n\nLemma word_to_nat_aux : forall b b0, \n  of_nat ((to_nat b + to_nat b0 * 256) / 256) = Some b0.\nProof.\n  intros. rewrite Nat.div_add ; auto.\n  rewrite Nat.div_small ; [|destruct b ; simpl ; omega].\n  simpl. apply of_to_nat. \nQed.\n  \nLemma word_to_nat_le_soundness : forall w,\n    nat_to_word_le (word_to_nat_le w) = w.\nProof.\n  intro w. destruct w.\n  unfold word_to_nat_le.\n  unfold nat_to_word_le.\n  rewrite PeanoNat.Nat.add_mod ; auto.\n  specialize (PeanoNat.Nat.mod_mul (to_nat b0) 256) as H.\n  rewrite PeanoNat.Nat.mul_comm. rewrite PeanoNat.Nat.mod_mul ; auto.\n  destruct b eqn:E ; simpl ; specialize (word_to_nat_aux b) as H' ;\n  rewrite E in H' ; simpl in H' ; rewrite H' ; reflexivity.\n                                     Qed.\n                                     \nLemma word_to_nat_be_soundness : forall w,\n    nat_to_word_be (word_to_nat_be w) = w.\nProof.\n  intro w. destruct w.\n  unfold word_to_nat_be.\n  unfold nat_to_word_be.\n  rewrite word_to_nat_le_soundness. reflexivity.\nQed.\n                                     \nLemma byte_to_nib_equality : forall b,\n    byte_to_nib' b = byte_to_nib b. \nProof.\n  intros b.\n  destruct b ; auto.\nQed.\n  \nLemma byte_nibble_soundness : forall b,\n    byte_to_nib' (nib_to_byte b) = b.\nProof.\n  intros b. unfold nib_to_byte. unfold byte_to_nib'.\n  destruct b eqn:E. destruct n, n10 ; auto.\nQed.\n\nTheorem byte_to_Bvector_inverse : forall b,\n    Bvector_to_byte (byte_to_Bvector b) = b.\nProof.\n  intros.\n  unfold Bvector_to_byte, byte_to_Bvector.\n  destruct b ; simpl ; reflexivity.\nQed.\n\nEnd HelperDataTypesProof.\n", "meta": {"author": "squeakyrino", "repo": "Lprog-Projeto", "sha": "d5083fbc7d43581dff3387c231cdd5e9430d9fa6", "save_path": "github-repos/coq/squeakyrino-Lprog-Projeto", "path": "github-repos/coq/squeakyrino-Lprog-Projeto/Lprog-Projeto-d5083fbc7d43581dff3387c231cdd5e9430d9fa6/theories/HelperDataTypes.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.2117038736507361}}
{"text": "Require Import Helix.LLVMGen.Correctness_Prelude.\nRequire Import Helix.LLVMGen.StateCounters.\nRequire Import Helix.LLVMGen.Correctness_Invariants.\nRequire Import Helix.LLVMGen.Correctness_NExpr.\n\nImport ListNotations.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nTypeclasses Opaque equiv.\n\nSection MExpr.\n\n  Import ProofMode.\n  Definition invariant_MExpr\n             (e : exp typ) : Rel_cfg_T (mem_block * Int64.int) unit :=\n    fun '(memH, (mb, mb_sz)) '(memV, (ρ, (g, _))) => \n      exists (ptr : Addr.addr), \n        interp_cfg (translate exp_to_instr (denote_exp (Some DTYPE_Pointer) (convert_typ [] e))) g ρ memV ≈\n                   Ret (memV,(ρ,(g,UVALUE_Addr ptr))) /\\ \n        (forall (i : Int64.int) v, mem_lookup (MInt64asNT.to_nat i) mb ≡ Some v -> get_array_cell memV ptr (MInt64asNT.to_nat i) DTYPE_Double ≡ inr (UVALUE_Double v)).\n\n  Record genMExpr_post\n         (s1 s2 : IRState)\n         exp\n         (mi : memoryH) (sti : config_cfg)\n         (mf : memoryH * _) (stf : config_cfg_T unit)\n    : Prop :=\n    {\n    _is_pure : is_pure mi sti mf stf;\n    get_addr : invariant_MExpr exp mf stf ;\n    Gamma_cst : s2 ≡ s1\n    }.\n\n  Lemma genMExpr_correct :\n    forall (* Compiler bits *) (s1 s2: IRState)\n      (* Helix  bits *)   (mexp: MExpr) (σ: evalContext) (memH: memoryH) \n      (* Vellvm bits *)   (exp: exp typ) (c: code typ) (g : global_env) (l : local_env) (memV : memoryV) (τ: typ),\n      genMExpr mexp s1 ≡ inr (s2, (exp, c, τ)) -> (* Compilation succeeds *)\n      state_invariant σ s1 memH (memV, (l, g)) ->\n      no_failure (interp_helix (E := E_cfg) (denoteMExpr σ mexp) memH) -> (* Source semantics defined *)\n      eutt (succ_cfg\n              (\n                lift_Rel_cfg (\n                    state_invariant σ s2) ⩕\n                             genMExpr_post s1 s2 exp memH (memV,(l,g)))\n           )\n           (interp_helix (denoteMExpr σ mexp) memH)\n           (interp_cfg (D.denote_code (convert_typ [] c)) g l memV).\n  Proof.\n    intros * Hgen INV NOFAIL.\n    destruct mexp as [[vid] | mblock]; cbn* in Hgen; simp.\n    unfold denoteMExpr, denotePExpr in *; cbn* in *.\n\n    simp; try_abs. subst.\n    hvred.\n    edestruct memory_invariant_Ptr\n      as (bkH & ptrV & Mem_LU & MEM & INLG & EQ); eauto.\n    cbn.\n    hstep.\n    solve_lu.\n    hvred.\n    apply eutt_Ret; split; [ | split]; cbn; auto.\n    eexists; split; eauto.\n    break_match_goal; cbn.\n    all: vstep; eauto; try reflexivity.\n  Qed.\n\n  Lemma genMExpr_array : forall {s1 s2 m e c t},\n      genMExpr m s1 ≡ inr (s2, (e, c, t)) ->\n      exists sz, t ≡ TYPE_Array sz TYPE_Double.\n  Proof.\n    intros s1 s2 m e c t H.\n    destruct m; cbn in H; inv H.\n    simp.\n    exists sz.\n    reflexivity.\n  Qed.\n\nEnd MExpr.\n", "meta": {"author": "vzaliva", "repo": "helix", "sha": "5d0a71df99722d2011c36156f12b04875df7e1cb", "save_path": "github-repos/coq/vzaliva-helix", "path": "github-repos/coq/vzaliva-helix/helix-5d0a71df99722d2011c36156f12b04875df7e1cb/coq/LLVMGen/Correctness_MExpr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.2117038656580271}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom compcert Require Import Memory Memtype Integers Values Ctypes AST.\nFrom Coq Require Import ZArith Lia.\n\nFrom bpf.comm Require Import Flag rBPFValues Regs BinrBPF State Monad MemRegion rBPFAST rBPFMemType rBPFMonadOp.\nFrom bpf.model Require Import Syntax Decode.\n\nOpen Scope Z_scope.\nOpen Scope monad_scope.\n\n\nDefinition eval_src (s:reg+imm): M state val :=\n  match s with\n  | inl r => eval_reg r\n  | inr i => returnM (Val.longofint (sint32_to_vint i)) (**r the immediate is always int *)\n  end.\n\nDefinition eval_reg32 (r:reg): M state val :=\n  do v <- eval_reg r; returnM (val_intuoflongu v).\n\nDefinition eval_src32 (s:reg+imm): M state val :=\n  match s with\n  | inl r => eval_reg32 r\n  | inr i => returnM (sint32_to_vint i) (**r the immediate is always int *)\n  end.\n\n(*\nDefinition _to_vlong (v: val): val :=\n  match v with\n  | Vlong n => Vlong n (**r Mint64 *)\n  | Vint  n => Vlong (Int64.repr (Int.unsigned n)) (**r Mint8unsigned, Mint16unsigned, Mint32 *) (* (u64) v *)\n  | _       => Vundef\n  end.\n\nDefinition vlong_to_vint_or_vlong (chunk: memory_chunk) (v: val): val :=\n  match v with\n  | Vlong n =>\n    match chunk with\n    | Mint8unsigned | Mint16unsigned | Mint32 => Vint (Int.repr (Int64.unsigned n))\n    | Mint64 => Vlong n\n    | _      => Vundef\n    end\n  | _       => Vundef\n  end. *)\n\nLemma intu_to_long_intu_eq:\n  forall i j, i = Vint j -> val_intuoflongu (Val.longofintu i) = i.\nProof.\n  unfold Val.longofintu, val_intuoflongu.\n  intros.\n  rewrite H.\n  assert (H1: Int64.unsigned (Int64.repr (Int.unsigned j)) = Int.unsigned j).\n  - apply Int64.unsigned_repr.\n    assert (Hrange: 0 <= Int.unsigned j <= Int.max_unsigned). { apply Int.unsigned_range_2. }\n    assert (Hmax: Int.max_unsigned <= Int64.max_unsigned).\n    + unfold Int.max_unsigned, Int64.max_unsigned.\n    unfold Int.modulus, Int64.modulus.\n    unfold Int.wordsize, Int64.wordsize.\n    unfold Wordsize_32.wordsize, Wordsize_64.wordsize.\n    simpl.\n    lia.\n    + lia.\n  - rewrite H1.\n    apply f_equal.\n    apply Int.repr_unsigned.\nQed.\nClose Scope Z_scope.\n\nDefinition val_intuoflonguM (vl: val) : M state val := returnM (val_intuoflongu vl).\n\nDefinition step_alu_binary_operation (a: arch) (bop: binOp) (d :reg) (s: reg+imm): M state unit :=\n  match a with\n  | A32 => \n    do d32 <- eval_reg32 d;\n    do s32 <- eval_src32 s; (**r (u32) DST, (u32) SRC/IMM *)\n    match bop with\n    | BPF_ADD  => upd_reg d (Val.longofintu (Val.add  d32 s32))\n    | BPF_SUB  => upd_reg d (Val.longofintu (Val.sub  d32 s32))\n    | BPF_MUL  => upd_reg d (Val.longofintu (Val.mul  d32 s32))\n    | BPF_DIV  => if comp_ne_32 s32 Vzero then (** run-time checking *)\n                    match Val.divu d32 s32 with (**r Val.divu... *)\n                    | Some res => upd_reg d (Val.longofintu res)\n                    | None     => errorM\n                    end\n                  else\n                    upd_flag BPF_ILLEGAL_DIV\n    | BPF_OR   => upd_reg d (Val.longofintu (Val.or   d32 s32))\n    | BPF_AND  => upd_reg d (Val.longofintu (Val.and  d32 s32))\n    | BPF_LSH  => if compu_lt_32 s32 (Vint (Int.repr 32)) then\n                    upd_reg d (Val.longofintu (Val.shl d32 s32))\n                  else\n                    upd_flag BPF_ILLEGAL_SHIFT  (**r if 's' of 'shl d s' is 's > 32', then there is a acceptable error *)\n    | BPF_RSH  => if compu_lt_32 s32 (Vint (Int.repr 32)) then\n                    upd_reg d (Val.longofintu (Val.shru d32 s32))\n                  else\n                    upd_flag BPF_ILLEGAL_SHIFT  (**r if 's' of 'shru d s' is 's > 32', then there is a acceptable error *)\n    | BPF_MOD  => if comp_ne_32 s32 Vzero then (** run-time checking *)\n                    match Val.modu d32 s32 with\n                    | Some res => upd_reg d (Val.longofintu res)\n                    | None     => errorM\n                    end\n                  else\n                    upd_flag BPF_ILLEGAL_DIV\n    | BPF_XOR  => upd_reg d (Val.longofintu (Val.xor  d32 s32))\n    | BPF_MOV  => upd_reg d (Val.longofintu s32)\n    | BPF_ARSH => if compu_lt_32 s32 (Vint (Int.repr 32)) then\n                    upd_reg d (Val.longofint (Val.shr  d32 s32))\n                  else\n                    upd_flag BPF_ILLEGAL_SHIFT (**r if 's' of 'shr d s' is 's > 32', then there is a acceptable error *)\n    end\n  | A64 =>\n      do d64 <- eval_reg d;\n      do s64 <- eval_src s;\n      match bop with\n      | BPF_ADD  => upd_reg d (Val.addl  d64 s64)\n      | BPF_SUB  => upd_reg d (Val.subl  d64 s64)\n      | BPF_MUL  => upd_reg d (Val.mull  d64 s64)\n      | BPF_DIV  => if compl_ne s64 val64_zero then (** run-time checking *)\n                      match Val.divlu d64 s64 with (**r run-time checking *)\n                      | Some res => upd_reg d res\n                      | None     => errorM\n                      end\n                    else\n                      upd_flag BPF_ILLEGAL_DIV\n      | BPF_OR   => upd_reg d (Val.orl   d64 s64)\n      | BPF_AND  => upd_reg d (Val.andl  d64 s64)\n      (**r we must do type-checking of 's64' first, to ensure it is exactly 'vint' *)\n      | BPF_LSH  => if compu_lt_32 (val_intuoflongu s64) (Vint (Int.repr 64)) then\n                      upd_reg d (Val.shll d64 (val_intuoflongu s64))\n                    else\n                      upd_flag BPF_ILLEGAL_SHIFT  (**r if 's' of 'shl d s' is 's > 64', then there is a acceptable error *)\n      | BPF_RSH  => if compu_lt_32 (val_intuoflongu s64) (Vint (Int.repr 64)) then\n                      upd_reg d (Val.shrlu d64 (val_intuoflongu s64))\n                    else\n                      upd_flag BPF_ILLEGAL_SHIFT  (**r if 's' of 'shr d s' is 's > 64', then there is a acceptable error *)\n      | BPF_MOD  => if compl_ne s64 val64_zero then (** run-time checking *)\n                      match Val.modlu d64 s64 with (**r run-time checking *)\n                      | Some res => upd_reg d res\n                      | None     => errorM\n                      end\n                    else\n                      upd_flag BPF_ILLEGAL_DIV\n(**r to avoid translate option type to C, the refinement version defines a new division:\nDefinition val64_divlu (x y: val): val :=\n  match Val.divlu x y with\n  | Some res => res\n  | None => Vundef\n  end.\nAnd the semantics function does:\n  | op_BPF_DIV64   =>\n    if compl_ne src64 val64_zero then\n      do _ <- upd_reg dst (val64_divlu dst64 src64);\n        upd_flag BPF_OK\n    else\n      upd_flag BPF_ILLEGAL_DIV\n\n *)\n      | BPF_XOR  => upd_reg d (Val.xorl  d64 s64)\n      | BPF_MOV  => upd_reg d s64\n      | BPF_ARSH => if compu_lt_32 (val_intuoflongu s64) (Vint (Int.repr 64)) then\n                      upd_reg d (Val.shrl d64 (val_intuoflongu s64))\n                    else\n                      upd_flag BPF_ILLEGAL_SHIFT  (**r if 's' of 'shru d s' is 's > 64', then there is a acceptable error? *)\n      end\n  end.\n\nDefinition step_branch_cond (c: cond) (d: reg) (s: reg+imm): M state bool :=\n  do dst <- eval_reg d;\n  do src <- eval_src s;\n  returnM (match c with\n  | Eq  => compl_eq   dst src\n  | SEt => complu_set dst src\n  | Ne  => compl_ne   dst src\n  | Gt sign => \n    match sign with\n    | Unsigned => complu_gt dst src\n    | Signed   => compl_gt  dst src\n    end\n  | Ge sign =>\n    match sign with\n    | Unsigned => complu_ge dst src\n    | Signed   => compl_ge  dst src\n    end\n  | Lt sign => \n    match sign with\n    | Unsigned => complu_lt dst src\n    | Signed   => compl_lt  dst src\n    end\n  | Le sign => \n    match sign with\n    | Unsigned => complu_le dst src\n    | Signed   => compl_le  dst src\n    end\n  end).\n\nDefinition get_add (x y: val): M state val := returnM (Val.add x y).\n\nDefinition get_sub (x y: val): M state val := returnM (Val.sub x y).\n\nDefinition get_addr_ofs (x: val) (ofs: int): M state val := returnM (val_intuoflongu (Val.addl x (Val.longofint (sint32_to_vint ofs)))).\n\nDefinition get_start_addr (mr: memory_region): M state val := returnM (start_addr mr).\n\nDefinition get_block_size (mr: memory_region): M state val := returnM (block_size mr).\n\nDefinition get_block_perm (mr: memory_region): M state permission := returnM (block_perm mr).\n\nDefinition is_well_chunk_bool (chunk: memory_chunk) : M state bool :=\n  match chunk with\n  | Mint8unsigned | Mint16unsigned | Mint32 | Mint64 => returnM true\n  | _ => returnM false\n  end.\n\nDefinition check_mem_aux2 (mr: memory_region) (perm: permission) (addr: val) (chunk: memory_chunk): M state val := (*\n  do well_chunk <- is_well_chunk_bool chunk;\n    if well_chunk then *)\n  do start  <- get_start_addr mr;\n  do size   <- get_block_size mr;\n  do mr_perm  <- get_block_perm mr;\n  do lo_ofs <- get_sub addr start;\n  do hi_ofs <- get_add lo_ofs (memory_chunk_to_valu32 chunk);\n    if andb (andb\n              (compu_lt_32 hi_ofs size)\n              (andb (compu_le_32 lo_ofs (memory_chunk_to_valu32_upbound chunk))\n                    (comp_eq_32 Vzero (val32_modu lo_ofs (memory_chunk_to_valu32 chunk)))))\n            (perm_ge mr_perm perm) then\n            returnM (Val.add (block_ptr mr) lo_ofs) (**r Vptr b lo_ofs *)\n    else\n      returnM Vnullptr. (*\n    else\n      returnM Vnullptr. *)\n\nFixpoint check_mem_aux (num: nat) (perm: permission) (chunk: memory_chunk) (addr: val) (mrs: MyMemRegionsType) {struct num}: M state val :=\n  match num with\n  | O => returnM Vnullptr\n  | S n =>\n    do cur_mr   <- get_mem_region n mrs;\n    do check_mem <- check_mem_aux2 cur_mr perm addr chunk;\n    do is_null   <- cmp_ptr32_nullM check_mem;\n      if is_null then\n        check_mem_aux n perm chunk addr mrs\n      else\n        returnM check_mem\n  end.\n\nDefinition check_mem (perm: permission) (chunk: memory_chunk) (addr: val): M state val :=\n  do well_chunk <- is_well_chunk_bool chunk;\n    if well_chunk then\n      do mem_reg_num <- eval_mrs_num;\n      do mrs      <- eval_mrs_regions;\n      do check_mem <- check_mem_aux mem_reg_num perm chunk addr mrs;\n      do is_null   <- cmp_ptr32_nullM check_mem;\n        if is_null then\n          returnM Vnullptr\n        else\n          returnM check_mem\n    else\n      returnM Vnullptr.\n\nDefinition step_load_x_operation (chunk: memory_chunk) (d:reg) (s:reg) (ofs:off): M state unit :=\n  do m    <- eval_mem;\n  do mrs  <- eval_mem_regions;\n  do sv   <- eval_reg s;\n  do addr <- get_addr_ofs sv ofs;\n  do ptr  <- check_mem Readable chunk addr;\n  do is_null   <- cmp_ptr32_nullM ptr;\n    if is_null then\n      upd_flag BPF_ILLEGAL_MEM\n    else\n      do v <- load_mem chunk ptr;\n      do _ <- upd_reg d v; returnM tt\n.\n\nDefinition step_store_operation (chunk: memory_chunk) (d: reg) (s: reg+imm) (ofs: off): M state unit :=\n  do m    <- eval_mem;\n  do mrs  <- eval_mem_regions;\n  do dv   <- eval_reg d;\n  do addr <- get_addr_ofs dv ofs;\n\n    match s with\n    | inl r =>\n      do src <- eval_reg r;\n      do ptr  <- check_mem Writable chunk addr;\n      do is_null   <- cmp_ptr32_nullM ptr;\n        if is_null then\n          upd_flag BPF_ILLEGAL_MEM\n        else\n          do _ <- store_mem_reg ptr chunk src; returnM tt\n    | inr i =>\n      do ptr  <- check_mem Writable chunk addr;\n      do is_null   <- cmp_ptr32_nullM ptr;\n        if is_null then\n          upd_flag BPF_ILLEGAL_MEM\n        else\n          do _ <- store_mem_imm ptr chunk (sint32_to_vint i); returnM tt\n    end\n.\n\nDefinition decodeM (i: int64) : M state instruction := fun st =>\n  match (decode i) with\n  | Some ins => Some (ins, st)\n  | None => None\n  end.\n\nDefinition get_immediate (ins:int64): M state int := returnM (get_immediate ins).\n\nDefinition step : M state unit :=\n  do pc   <- eval_pc;\n  do ins64<- eval_ins pc;\n  do ins  <- decodeM ins64;\n    match ins with\n    | BPF_NEG a d =>\n      match a with\n      | A32 => do d32 <- eval_reg d;\n                 upd_reg d (Val.longofintu (Val.neg (val_intuoflongu d32)))\n      | A64 => do d64 <- eval_reg d;\n                 upd_reg d (Val.negl d64)\n      end\n\n    | BPF_BINARY a bop d s =>\n      step_alu_binary_operation a bop d s\n\n    | BPF_JA ofs => upd_pc (Int.add pc ofs)\n    | BPF_JUMP c d s ofs =>\n      do cond <- step_branch_cond c d s;\n      if cond then\n        upd_pc (Int.add pc ofs)\n      else\n        returnM tt\n\n    | BPF_LDDW_low d i =>\n      do _   <- upd_reg d (Val.longofintu (sint32_to_vint i));\n        returnM tt\n    | BPF_LDDW_high d i =>\n      do d64 <- eval_reg d;\n      do _   <- upd_reg d (Val.orl d64 (Val.shll  (Val.longofintu (sint32_to_vint i)) (sint32_to_vint (Int.repr 32))));\n        returnM tt\n    | BPF_LDX chunk d s ofs =>\n      step_load_x_operation chunk d s ofs\n    | BPF_ST chunk d s ofs =>\n      step_store_operation chunk d s ofs\n\n    | BPF_CALL i => (**r TODO: is this type-casting correct? this style is because of DxInstructions... *)\n      do f_ptr    <- _bpf_get_call (Vint ((Int.repr (Int64.unsigned (Int64.repr (Int.signed i))))));\n      do is_null  <- cmp_ptr32_nullM f_ptr;\n        if is_null then\n          upd_flag BPF_ILLEGAL_CALL\n        else\n          do res  <- exec_function f_ptr;\n            upd_reg R0 (Val.longofintu res)\n    | BPF_RET    => upd_flag BPF_SUCC_RETURN\n    | BPF_ERR    => upd_flag BPF_ILLEGAL_INSTRUCTION\n    end.\n\nFixpoint bpf_interpreter_aux (fuel: nat) {struct fuel}: M state unit :=\n  match fuel with\n  | O => upd_flag BPF_ILLEGAL_LEN\n  | S fuel0 =>\n    do len  <- eval_ins_len;\n    do pc <- eval_pc;\n      if (Int.ltu pc len) then (**r pc < len: pc is less than the length of l *)\n        do _ <- step;\n        do f <- eval_flag;\n          if flag_eq f BPF_OK then\n            do len0 <- eval_ins_len;\n            do pc0 <- eval_pc; (**r step may modify pc: lddw *)\n              if (Int.ltu (Int.add pc0 Int.one) len0) then (**r pc + 1 < len *)\n                do _ <- upd_pc_incr;\n                  bpf_interpreter_aux fuel0\n              else\n                upd_flag BPF_ILLEGAL_LEN\n          else\n            returnM tt\n      else\n        upd_flag BPF_ILLEGAL_LEN\n  end.\n\nDefinition bpf_interpreter (fuel: nat): M state val :=\n  do _        <- bpf_interpreter_aux fuel;\n  do f        <- eval_flag;\n    if flag_eq f BPF_SUCC_RETURN then\n      do res  <- eval_reg R0;\n        returnM res\n    else\n      returnM val64_zero.\n\nClose Scope monad_scope.", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/model/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.33807713081919877, "lm_q1q2_score": 0.21167826537387632}}
{"text": "\n(* an omega groupoid is an omega cat *)\nRequire Import ssreflect ssrfun ssrbool .\n\nFrom Modules Require Import HomotopicalEquality untypeduippackrl TypesAreOmegaGroupoids.FunctionalRelation lib Syntax WfSyntaxBrunerieOnlyContr gtype decl omegagroupoids fullomegagroupoids WfSyntaxBrunerieAllCtx.\nSet Bullet Behavior \"Strict Subproofs\".\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Notation \"⟦ X ⟧V\" := (dTm (w_va X)).\n\nModule B := WfSyntaxBrunerieOnlyContr.\nModule FB := WfSyntaxBrunerieAllCtx.\n\nLocal Notation SB := (B.syntax).\nLocal Notation SF := (FB.syntax).\n\nModule Syn := Syntax.\nLocal Notation \"'WC' S\" := (@Syn.WC _ S) (at level 0).\nLocal Notation \"'WTy' S\" := (@Syn.WTy _ S)(at level 0).\nLocal Notation \"'Wtm' S\":= (@Syn.Wtm _ S)(at level 0).\nLocal Notation \"'WS' S\":= (@Syn.WS _ S)(at level 0).\nLocal Notation \"'SF_WVar' S\":= (FB.WVar S)(at level 0).\nLocal Notation \"'SB_WVar' S\":= (B.WVar S)(at level 0).\n(*\nLocal Notation WTy := (@Syn.WTy _).\nLocal Notation Wtm := (@Syn.Wtm _).\nLocal Notation WS := (@Syn.WS _).\nLocal Notation SC_WVar := (WfSyntaxEricSamOnlyPs.WVar).\nLocal Notation SB_WVar := (WfSyntaxBrunerieOnlyContr.WVar).\n*)\n\n(*\nIndépendemment du pb d'équivalence dont je parle ensuite, de toute manière, je suis obligé de\nredéfinir par récurrence l'interprétation de FB à partir de l'interprétation de B. Donc,\nil faut un inductif pour la relation fonctionnelle, etc... \n\nEst-ce que ça vaut le coup de définir une bonne fois pour toute le schéma d'élimination ?\n\n\n\nMaintenant, pour transformer un modèle de B (Brunerie) vers FB (full brunerie), je suis confronté au\npb suivant :\n- pour B, ⟦ (x : * ) ⟧ = Σ_(γ : ⊤) | G |\n- pour FB, ⟦ (x : * ) ⟧ = | G |\n\nCe qui est un peu relou. Les deux types sont équivalents mais pas égaux strictement.\nDu coup j'ai 2 solutions :\n\n\n+ changer la def de ce que c'est un omega groupoide en demandant non pas une égalité mais une équivalence.\nAppelons cette définition une déf wild. Par contre, on demande ⟦ σ , t ⟧ = ⟦ σ ⟧, ⟦ t ⟧ strictement.\nMais pour l'équivalence, on utilise quelle égalité ??\n\n\n+ avoir les 2 définitions, et montrer qu'un omega groupoide wild induit un omega groupoide normal.\n\n\n\nAutre idée :\nimposer qu'un omega groupoide s'interpréte dans GhSet plutôt que GType.\nEn quoi un type est un omega groupoide ? Etant donné un GType G, on peut considérer sa troncation G'\noù tous les obj ont été tronqués au niveau hSet. On a un morphisme\nJe ne pense pas qu'on puisse tronquer ainsi un GType.\n\n--------------\nIl faudrait montrer qu'un omega groupoide sur G induit un omega groupoide sur G'\n\nMais plus généralement, si on a un morphisme de type globulaire G₁ → G₂, si G₁ est un omega groupoide,\nG₂ ne l'est-il pas également ?\n\nSi ça marche, alors pas besoin de 2TT pour la def d'omega groupoide., mais besoin d'une troncation hSet.\n\nEst-ce légitime de demander des égalités strites dans la def d'omega groupoides ? Oui, ou alors il faut demander à ce que le type globulaire est un hset. Mais alors comment montrer que les types sont\ndes omega groupoides ? Peut-on se passer de 2TT ainsi ? Pas sûr. Mais au moins, cette nouvelle def\nserait moins chiante (avec l'axiome d'univalence, ou alors sans mais en demandant une équivalence plutôt qu'une égalité) pour montrer ce que je veux dans ce fichier.\n\nMais puis je me passer de 2TT ?\n\nCe qui vient après est idiot. J'avais oublié que isEquiv(f) est hprop mais pas Equiv(A,B)\n-----------------------------------------------------------\nNotion d'égalité hétérogène hprop dans hott :\nt : A, u : B\nt ≅ u := ∀ (P : ∀ X:Type, X -> Type), P A t ~ P B u\noù '~' est l'équivalence hprop isEquiv\nt ≅ u -> A ~ B et t ~ u par cette equivalence (prendre P X x = X ~ B et e(x) = b)\n\nMais alors, false ≅ true avec cette égalité.\n\nPeut on donner une définition sans 2TT d'un omega groupoide avec cette égalité malgré tout ?\n\n\n\n *)\n\nFixpoint wCB_C (Γ : Con) (wΓ : WC SC Γ) : WC SB Γ\nwith wCB_T Γ A (wA : WTy SC Γ A) : WTy SB Γ A\nwith wCB_Tm Γ A t (wt : Wtm SC Γ A t) : Wtm SB Γ A t\nwith wCB_V Γ A x (wx : SC_WVar Γ A x) : SB_WVar Γ A x\nwith wCB_S Γ Δ σ (wσ : WS SC Γ Δ σ) : WS SB Γ Δ σ.\n  - destruct wΓ.\n    + constructor.\n    + constructor.\n      * apply:wCB_C => //.\n      * apply:wCB_T => //.\n      * constructor.\n        apply:wCB_V => //.\n  - destruct wA.\n    + constructor.\n      apply:wCB_C => //.\n    + constructor.\n      * apply:wCB_T => //.\n      * apply:wCB_Tm => //.\n      * apply:wCB_Tm => //.\n  - destruct wt.\n    + constructor.\n      by apply:wCB_V => //.\n    + constructor.\n      * apply:wCB_C => //.\n      * apply:wCB_T => //.\n      * apply:wCB_S => //.\n    + rewrite -/((ar  A t u).[σ]T).\n      constructor.\n      * apply:wCB_C => //.\n      * constructor.\n        -- apply:wCB_T => //.\n        -- apply:wCB_Tm => //.\n        -- apply:wCB_Tm => //.\n      * apply:wCB_S => //.\n - destruct wx.\n   + constructor.\n   + constructor.\n     * apply:wCB_V => //.\n     * apply:wCB_Tm => //.\n   + constructor.\n     apply:wCB_Tm => //.\n   + constructor.\n     apply:wCB_Tm => //.\n - destruct wσ.\n   + constructor.\n     apply:wCB_Tm => //.\n   + constructor.\n      * apply:wCB_S => //.\n      * apply:wCB_T => //.\n      * apply:wCB_Tm => //.\n      * apply:wCB_Tm => //.\n      * apply:wCB_Tm => //.\nDefined.\n\nSection GroupoidToCat.\n  Context (d : @Decl _ SB).\n\n  Definition d' : @Decl _ SC :=\n    {|\n      dC := fun Γ  (wΓ : Syn.WC Γ) => ⟦ wCB_C wΓ ⟧C;\n      dTy := fun (Γ : Con) (A : Ty) (wΓ : Syn.WC Γ) (wA : Γ ⊢ A) => ⟦ wCB_T wA ⟧T;\n      dTm := fun (Γ : Con) (A : Ty) (t : Tm) (wΓ : Syn.WC Γ) (wt : Γ ⊢ t : A) (wA : Γ ⊢ A) =>\n               ⟦ wCB_Tm wt ⟧t (wCB_T wA);\n      dS := fun (Γ Δ : Con) (σ : sub) (wσ : WfSyntaxEricSamOnlyPs.WS Γ Δ σ) (wΓ : WfSyntaxEricSamOnlyPs.WC Γ) (wΔ : WfSyntaxEricSamOnlyPs.WC Δ) =>\n              ⟦ wCB_S wσ ⟧S (wCB_C wΓ)(wCB_C wΔ) |}.\n\n  Import omegagroupoids.\n  Lemma isGroupoid_isCat (G : GType)  (gr : isOmegaGroupoid G d) : isOmegaCategory G d'.\n    constructor.\n    - by apply:dC_astar.\n    - intros.\n      apply:(dC_ext gr).\n    - intros.\n      apply:(dT_star gr).\n    - intros.\n      apply:(dT_ar gr).\n    - intros.\n      simpl.\n      apply:JMeq_trans; last by apply:(sb_dTm gr).\n      match goal with\n        [ |- ⟦ ?w1 ⟧t ?w2 γ ≅ ⟦ ?w3 ⟧t ?w4 γ ] =>\n        rewrite (WTm_hp w1 w3) (WTy_hp w2 w4)\n      end.\n      easy.\n    - apply:(dTm_vstar gr).\n    - intros; apply:(dTm_v1 gr).\n      eassumption.\n    - intros; apply:(dTm_v0 gr) => //.\n    - intros; apply:(dTm_vwk gr) => //.\n      eassumption.\n    - intros;apply:(dS_to_star gr) => //.\n    - intros;apply:(dS_to_ext gr) => //.\n      exact:H.\n      exact:H0.\n      exact:H1.\n  Qed.\n\nEnd GroupoidToCat.\n\n", "meta": {"author": "amblafont", "repo": "weak-cat-type", "sha": "064ed13f1a8d4d4c2666ca2190abffd6573c1afe", "save_path": "github-repos/coq/amblafont-weak-cat-type", "path": "github-repos/coq/amblafont-weak-cat-type/weak-cat-type-064ed13f1a8d4d4c2666ca2190abffd6573c1afe/Modules/TypeSystem/OmegaGroupoidIsFull.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.21162564715335558}}
{"text": "From iris.base_logic.lib Require Export fancy_updates.\nFrom iris.program_logic Require Export language.\nFrom iris.bi Require Export weakestpre.\nFrom iris.proofmode Require Import base tactics classes.\nSet Default Proof Using \"Type\".\nImport uPred.\n\nClass irisG' (Λstate : Type) (Σ : gFunctors) := IrisG {\n  iris_invG :> invG Σ;\n  state_interp : Λstate → iProp Σ;\n}.\nNotation irisG Λ Σ := (irisG' (state Λ) Σ).\nGlobal Opaque iris_invG.\n\nDefinition wp_pre `{irisG Λ Σ} (s : stuckness)\n    (wp : coPset -c> expr Λ -c> (val Λ -c> iProp Σ) -c> iProp Σ) :\n    coPset -c> expr Λ -c> (val Λ -c> iProp Σ) -c> iProp Σ := λ E e1 Φ,\n  match to_val e1 with\n  | Some v => |={E}=> Φ v\n  | None => ∀ σ1,\n     state_interp σ1 ={E,∅}=∗ ⌜if s is NotStuck then reducible e1 σ1 else True⌝ ∗\n     ∀ e2 σ2 efs, ⌜prim_step e1 σ1 e2 σ2 efs⌝ ={∅,∅,E}▷=∗\n       state_interp σ2 ∗ wp E e2 Φ ∗\n       [∗ list] ef ∈ efs, wp ⊤ ef (λ _, True)\n  end%I.\n\nLocal Instance wp_pre_contractive `{irisG Λ Σ} s : Contractive (wp_pre s).\nProof.\n  rewrite /wp_pre=> n wp wp' Hwp E e1 Φ.\n  repeat (f_contractive || f_equiv); apply Hwp.\nQed.\n\nDefinition wp_def `{irisG Λ Σ} (s : stuckness) :\n  coPset → expr Λ → (val Λ → iProp Σ) → iProp Σ := fixpoint (wp_pre s).\nDefinition wp_aux `{irisG Λ Σ} : seal (@wp_def Λ Σ _). by eexists. Qed.\nInstance wp' `{irisG Λ Σ} : Wp Λ (iProp Σ) stuckness := wp_aux.(unseal).\nDefinition wp_eq `{irisG Λ Σ} : wp = @wp_def Λ Σ _ := wp_aux.(seal_eq).\n\nSection wp.\nContext `{irisG Λ Σ}.\nImplicit Types s : stuckness.\nImplicit Types P : iProp Σ.\nImplicit Types Φ : val Λ → iProp Σ.\nImplicit Types v : val Λ.\nImplicit Types e : expr Λ.\n\n(* Weakest pre *)\nLemma wp_unfold s E e Φ :\n  WP e @ s; E {{ Φ }} ⊣⊢ wp_pre s (wp (PROP:=iProp Σ)  s) E e Φ.\nProof. rewrite wp_eq. apply (fixpoint_unfold (wp_pre s)). Qed.\n\nGlobal Instance wp_ne s E e n :\n  Proper (pointwise_relation _ (dist n) ==> dist n) (wp (PROP:=iProp Σ) s E e).\nProof.\n  revert e. induction (lt_wf n) as [n _ IH]=> e Φ Ψ HΦ.\n  rewrite !wp_unfold /wp_pre.\n  (* FIXME: figure out a way to properly automate this proof *)\n  (* FIXME: reflexivity, as being called many times by f_equiv and f_contractive\n  is very slow here *)\n  do 18 (f_contractive || f_equiv). apply IH; first lia.\n  intros v. eapply dist_le; eauto with lia.\nQed.\nGlobal Instance wp_proper s E e :\n  Proper (pointwise_relation _ (≡) ==> (≡)) (wp (PROP:=iProp Σ) s E e).\nProof.\n  by intros Φ Φ' ?; apply equiv_dist=>n; apply wp_ne=>v; apply equiv_dist.\nQed.\n\nLemma wp_value' s E Φ v : Φ v ⊢ WP of_val v @ s; E {{ Φ }}.\nProof. iIntros \"HΦ\". rewrite wp_unfold /wp_pre to_of_val. auto. Qed.\nLemma wp_value_inv' s E Φ v : WP of_val v @ s; E {{ Φ }} ={E}=∗ Φ v.\nProof. by rewrite wp_unfold /wp_pre to_of_val. Qed.\n\nLemma wp_strong_mono s1 s2 E1 E2 e Φ Ψ :\n  s1 ⊑ s2 → E1 ⊆ E2 →\n  WP e @ s1; E1 {{ Φ }} -∗ (∀ v, Φ v ={E2}=∗ Ψ v) -∗ WP e @ s2; E2 {{ Ψ }}.\nProof.\n  iIntros (? HE) \"H HΦ\". iLöb as \"IH\" forall (e E1 E2 HE Φ Ψ).\n  rewrite !wp_unfold /wp_pre.\n  destruct (to_val e) as [v|] eqn:?.\n  { iApply (\"HΦ\" with \"[> -]\"). by iApply (fupd_mask_mono E1 _). }\n  iIntros (σ1) \"Hσ\". iMod (fupd_intro_mask' E2 E1) as \"Hclose\"; first done.\n  iMod (\"H\" with \"[$]\") as \"[% H]\".\n  iModIntro. iSplit; [by destruct s1, s2|]. iIntros (e2 σ2 efs Hstep).\n  iMod (\"H\" with \"[//]\") as \"H\". iIntros \"!> !>\". iMod \"H\" as \"($ & H & Hefs)\".\n  iMod \"Hclose\" as \"_\". iModIntro. iSplitR \"Hefs\".\n  - iApply (\"IH\" with \"[//] H HΦ\").\n  - iApply (big_sepL_impl with \"[$Hefs]\"); iIntros \"!#\" (k ef _) \"H\".\n    by iApply (\"IH\" with \"[] H\").\nQed.\n\nLemma fupd_wp s E e Φ : (|={E}=> WP e @ s; E {{ Φ }}) ⊢ WP e @ s; E {{ Φ }}.\nProof.\n  rewrite wp_unfold /wp_pre. iIntros \"H\". destruct (to_val e) as [v|] eqn:?.\n  { by iMod \"H\". }\n  iIntros (σ1) \"Hσ1\". iMod \"H\". by iApply \"H\".\nQed.\nLemma wp_fupd s E e Φ : WP e @ s; E {{ v, |={E}=> Φ v }} ⊢ WP e @ s; E {{ Φ }}.\nProof. iIntros \"H\". iApply (wp_strong_mono s s E with \"H\"); auto. Qed.\n\nLemma wp_atomic s E1 E2 e Φ `{!Atomic (stuckness_to_atomicity s) e} :\n  (|={E1,E2}=> WP e @ s; E2 {{ v, |={E2,E1}=> Φ v }}) ⊢ WP e @ s; E1 {{ Φ }}.\nProof.\n  iIntros \"H\". rewrite !wp_unfold /wp_pre.\n  destruct (to_val e) as [v|] eqn:He.\n  { by iDestruct \"H\" as \">>> $\". }\n  iIntros (σ1) \"Hσ\". iMod \"H\". iMod (\"H\" $! σ1 with \"Hσ\") as \"[$ H]\".\n  iModIntro. iIntros (e2 σ2 efs Hstep).\n  iMod (\"H\" with \"[//]\") as \"H\". iIntros \"!>!>\". iMod \"H\" as \"(Hphy & H & $)\". destruct s.\n  - rewrite !wp_unfold /wp_pre. destruct (to_val e2) as [v2|] eqn:He2.\n    + iDestruct \"H\" as \">> $\". by iFrame.\n    + iMod (\"H\" with \"[$]\") as \"[H _]\". iDestruct \"H\" as %(? & ? & ? & ?).\n      by edestruct (atomic _ _ _ _ Hstep).\n  - destruct (atomic _ _ _ _ Hstep) as [v <-%of_to_val].\n    iMod (wp_value_inv' with \"H\") as \">H\". iFrame \"Hphy\". by iApply wp_value'.\nQed.\n\nLemma wp_step_fupd s E1 E2 e P Φ :\n  to_val e = None → E2 ⊆ E1 →\n  (|={E1,E2}▷=> P) -∗ WP e @ s; E2 {{ v, P ={E1}=∗ Φ v }} -∗ WP e @ s; E1 {{ Φ }}.\nProof.\n  rewrite !wp_unfold /wp_pre. iIntros (-> ?) \"HR H\".\n  iIntros (σ1) \"Hσ\". iMod \"HR\". iMod (\"H\" with \"[$]\") as \"[$ H]\".\n  iIntros \"!>\" (e2 σ2 efs Hstep). iMod (\"H\" $! e2 σ2 efs with \"[% //]\") as \"H\".\n  iIntros \"!>!>\". iMod \"H\" as \"($ & H & $)\".\n  iMod \"HR\". iModIntro. iApply (wp_strong_mono s s E2 with \"H\"); [done..|].\n  iIntros (v) \"H\". by iApply \"H\".\nQed.\n\nLemma wp_bind K `{!LanguageCtx K} s E e Φ :\n  WP e @ s; E {{ v, WP K (of_val v) @ s; E {{ Φ }} }} ⊢ WP K e @ s; E {{ Φ }}.\nProof.\n  iIntros \"H\". iLöb as \"IH\" forall (E e Φ). rewrite wp_unfold /wp_pre.\n  destruct (to_val e) as [v|] eqn:He.\n  { apply of_to_val in He as <-. by iApply fupd_wp. }\n  rewrite wp_unfold /wp_pre fill_not_val //.\n  iIntros (σ1) \"Hσ\". iMod (\"H\" with \"[$]\") as \"[% H]\". iModIntro; iSplit.\n  { iPureIntro. destruct s; last done.\n    unfold reducible in *. naive_solver eauto using fill_step. }\n  iIntros (e2 σ2 efs Hstep).\n  destruct (fill_step_inv e σ1 e2 σ2 efs) as (e2'&->&?); auto.\n  iMod (\"H\" $! e2' σ2 efs with \"[//]\") as \"H\". iIntros \"!>!>\".\n  iMod \"H\" as \"($ & H & $)\". by iApply \"IH\".\nQed.\n\nLemma wp_bind_inv K `{!LanguageCtx K} s E e Φ :\n  WP K e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ v, WP K (of_val v) @ s; E {{ Φ }} }}.\nProof.\n  iIntros \"H\". iLöb as \"IH\" forall (E e Φ). rewrite !wp_unfold /wp_pre.\n  destruct (to_val e) as [v|] eqn:He.\n  { apply of_to_val in He as <-. by rewrite !wp_unfold /wp_pre. }\n  rewrite fill_not_val //.\n  iIntros (σ1) \"Hσ\". iMod (\"H\" with \"[$]\") as \"[% H]\". iModIntro; iSplit.\n  { destruct s; eauto using reducible_fill. }\n  iIntros (e2 σ2 efs Hstep).\n  iMod (\"H\" $! (K e2) σ2 efs with \"[]\") as \"H\"; [by eauto using fill_step|].\n  iIntros \"!>!>\". iMod \"H\" as \"($ & H & $)\". by iApply \"IH\".\nQed.\n\n(** * Derived rules *)\nLemma wp_mono s E e Φ Ψ : (∀ v, Φ v ⊢ Ψ v) → WP e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ Ψ }}.\nProof.\n  iIntros (HΦ) \"H\"; iApply (wp_strong_mono with \"H\"); auto.\n  iIntros (v) \"?\". by iApply HΦ.\nQed.\nLemma wp_stuck_mono s1 s2 E e Φ :\n  s1 ⊑ s2 → WP e @ s1; E {{ Φ }} ⊢ WP e @ s2; E {{ Φ }}.\nProof. iIntros (?) \"H\". iApply (wp_strong_mono with \"H\"); auto. Qed.\nLemma wp_stuck_weaken s E e Φ :\n  WP e @ s; E {{ Φ }} ⊢ WP e @ E ?{{ Φ }}.\nProof. apply wp_stuck_mono. by destruct s. Qed.\nLemma wp_mask_mono s E1 E2 e Φ : E1 ⊆ E2 → WP e @ s; E1 {{ Φ }} ⊢ WP e @ s; E2 {{ Φ }}.\nProof. iIntros (?) \"H\"; iApply (wp_strong_mono with \"H\"); auto. Qed.\nGlobal Instance wp_mono' s E e :\n  Proper (pointwise_relation _ (⊢) ==> (⊢)) (wp (PROP:=iProp Σ) s E e).\nProof. by intros Φ Φ' ?; apply wp_mono. Qed.\n\nLemma wp_value s E Φ e v : IntoVal e v → Φ v ⊢ WP e @ s; E {{ Φ }}.\nProof. intros <-. by apply wp_value'. Qed.\nLemma wp_value_fupd' s E Φ v : (|={E}=> Φ v) ⊢ WP of_val v @ s; E {{ Φ }}.\nProof. intros. by rewrite -wp_fupd -wp_value'. Qed.\nLemma wp_value_fupd s E Φ e v `{!IntoVal e v} :\n  (|={E}=> Φ v) ⊢ WP e @ s; E {{ Φ }}.\nProof. intros. rewrite -wp_fupd -wp_value //. Qed.\nLemma wp_value_inv s E Φ e v : IntoVal e v → WP e @ s; E {{ Φ }} ={E}=∗ Φ v.\nProof. intros <-. by apply wp_value_inv'. Qed.\n\nLemma wp_frame_l s E e Φ R : R ∗ WP e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ v, R ∗ Φ v }}.\nProof. iIntros \"[? H]\". iApply (wp_strong_mono with \"H\"); auto with iFrame. Qed.\nLemma wp_frame_r s E e Φ R : WP e @ s; E {{ Φ }} ∗ R ⊢ WP e @ s; E {{ v, Φ v ∗ R }}.\nProof. iIntros \"[H ?]\". iApply (wp_strong_mono with \"H\"); auto with iFrame. Qed.\n\nLemma wp_frame_step_l s E1 E2 e Φ R :\n  to_val e = None → E2 ⊆ E1 →\n  (|={E1,E2}▷=> R) ∗ WP e @ s; E2 {{ Φ }} ⊢ WP e @ s; E1 {{ v, R ∗ Φ v }}.\nProof.\n  iIntros (??) \"[Hu Hwp]\". iApply (wp_step_fupd with \"Hu\"); try done.\n  iApply (wp_mono with \"Hwp\"). by iIntros (?) \"$$\".\nQed.\nLemma wp_frame_step_r s E1 E2 e Φ R :\n  to_val e = None → E2 ⊆ E1 →\n  WP e @ s; E2 {{ Φ }} ∗ (|={E1,E2}▷=> R) ⊢ WP e @ s; E1 {{ v, Φ v ∗ R }}.\nProof.\n  rewrite [(WP _ @ _; _ {{ _ }} ∗ _)%I]comm; setoid_rewrite (comm _ _ R).\n  apply wp_frame_step_l.\nQed.\nLemma wp_frame_step_l' s E e Φ R :\n  to_val e = None → ▷ R ∗ WP e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ v, R ∗ Φ v }}.\nProof. iIntros (?) \"[??]\". iApply (wp_frame_step_l s E E); try iFrame; eauto. Qed.\nLemma wp_frame_step_r' s E e Φ R :\n  to_val e = None → WP e @ s; E {{ Φ }} ∗ ▷ R ⊢ WP e @ s; E {{ v, Φ v ∗ R }}.\nProof. iIntros (?) \"[??]\". iApply (wp_frame_step_r s E E); try iFrame; eauto. Qed.\n\nLemma wp_wand s E e Φ Ψ :\n  WP e @ s; E {{ Φ }} -∗ (∀ v, Φ v -∗ Ψ v) -∗ WP e @ s; E {{ Ψ }}.\nProof.\n  iIntros \"Hwp H\". iApply (wp_strong_mono with \"Hwp\"); auto.\n  iIntros (?) \"?\". by iApply \"H\".\nQed.\nLemma wp_wand_l s E e Φ Ψ :\n  (∀ v, Φ v -∗ Ψ v) ∗ WP e @ s; E {{ Φ }} ⊢ WP e @ s; E {{ Ψ }}.\nProof. iIntros \"[H Hwp]\". iApply (wp_wand with \"Hwp H\"). Qed.\nLemma wp_wand_r s E e Φ Ψ :\n  WP e @ s; E {{ Φ }} ∗ (∀ v, Φ v -∗ Ψ v) ⊢ WP e @ s; E {{ Ψ }}.\nProof. iIntros \"[Hwp H]\". iApply (wp_wand with \"Hwp H\"). Qed.\nEnd wp.\n\n(** Proofmode class instances *)\nSection proofmode_classes.\n  Context `{irisG Λ Σ}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types Φ : val Λ → iProp Σ.\n\n  Global Instance frame_wp p s E e R Φ Ψ :\n    (∀ v, Frame p R (Φ v) (Ψ v)) →\n    Frame p R (WP e @ s; E {{ Φ }}) (WP e @ s; E {{ Ψ }}).\n  Proof. rewrite /Frame=> HR. rewrite wp_frame_l. apply wp_mono, HR. Qed.\n\n  Global Instance is_except_0_wp s E e Φ : IsExcept0 (WP e @ s; E {{ Φ }}).\n  Proof. by rewrite /IsExcept0 -{2}fupd_wp -except_0_fupd -fupd_intro. Qed.\n\n  Global Instance elim_modal_bupd_wp p s E e P Φ :\n    ElimModal True p false (|==> P) P (WP e @ s; E {{ Φ }}) (WP e @ s; E {{ Φ }}).\n  Proof.\n    by rewrite /ElimModal intuitionistically_if_elim\n      (bupd_fupd E) fupd_frame_r wand_elim_r fupd_wp.\n  Qed.\n\n  Global Instance elim_modal_fupd_wp p s E e P Φ :\n    ElimModal True p false (|={E}=> P) P (WP e @ s; E {{ Φ }}) (WP e @ s; E {{ Φ }}).\n  Proof.\n    by rewrite /ElimModal intuitionistically_if_elim\n      fupd_frame_r wand_elim_r fupd_wp.\n  Qed.\n\n  Global Instance elim_modal_fupd_wp_atomic p s E1 E2 e P Φ :\n    Atomic (stuckness_to_atomicity s) e →\n    ElimModal True p false (|={E1,E2}=> P) P\n            (WP e @ s; E1 {{ Φ }}) (WP e @ s; E2 {{ v, |={E2,E1}=> Φ v }})%I.\n  Proof.\n    intros. by rewrite /ElimModal intuitionistically_if_elim\n      fupd_frame_r wand_elim_r wp_atomic.\n  Qed.\n\n  Global Instance add_modal_fupd_wp s E e P Φ :\n    AddModal (|={E}=> P) P (WP e @ s; E {{ Φ }}).\n  Proof. by rewrite /AddModal fupd_frame_r wand_elim_r fupd_wp. Qed.\n\n  Global Instance elim_acc_wp {X} E1 E2 α β γ e s Φ :\n    Atomic (stuckness_to_atomicity s) e →\n    ElimAcc (X:=X) (fupd E1 E2) (fupd E2 E1)\n            α β γ (WP e @ s; E1 {{ Φ }})\n            (λ x, WP e @ s; E2 {{ v, |={E2}=> β x ∗ (γ x -∗? Φ v) }})%I.\n  Proof.\n    intros ?. rewrite /ElimAcc.\n    iIntros \"Hinner >Hacc\". iDestruct \"Hacc\" as (x) \"[Hα Hclose]\".\n    iApply (wp_wand with \"[Hinner Hα]\"); first by iApply \"Hinner\".\n    iIntros (v) \">[Hβ HΦ]\". iApply \"HΦ\". by iApply \"Hclose\".\n  Qed.\n\n  Global Instance elim_acc_wp_nonatomic {X} E α β γ e s Φ :\n    ElimAcc (X:=X) (fupd E E) (fupd E E)\n            α β γ (WP e @ s; E {{ Φ }})\n            (λ x, WP e @ s; E {{ v, |={E}=> β x ∗ (γ x -∗? Φ v) }})%I.\n  Proof.\n    rewrite /ElimAcc.\n    iIntros \"Hinner >Hacc\". iDestruct \"Hacc\" as (x) \"[Hα Hclose]\".\n    iApply wp_fupd.\n    iApply (wp_wand with \"[Hinner Hα]\"); first by iApply \"Hinner\".\n    iIntros (v) \">[Hβ HΦ]\". iApply \"HΦ\". by iApply \"Hclose\".\n  Qed.\nEnd proofmode_classes.\n", "meta": {"author": "JasonGross", "repo": "iris-coq", "sha": "f891015e2ab48926cec9618b0eadf0c0fec9ba1b", "save_path": "github-repos/coq/JasonGross-iris-coq", "path": "github-repos/coq/JasonGross-iris-coq/iris-coq-f891015e2ab48926cec9618b0eadf0c0fec9ba1b/theories/program_logic/weakestpre.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.21162564311290646}}
{"text": "Require Import Nat.\nRequire Import String.\nRequire Import List.\nFrom mathcomp Require Import all_ssreflect all_algebra.\nFrom LF Require Export lang_spec_declassify type_spec_declassify.\n\nSet Implicit Arguments.\n\nInductive state_equiv_spec (s1 s2:state) (VGamma:venv) (AGamma:aenv) : Prop :=\n| st_equiv_spec : \n  s1.(scmd) = s2.(scmd) ->\n  s1.(ms) = s2.(ms) ->\n  (forall x, VGamma x = Some Public -> s1.(rmap) x = s2.(rmap) x) ->\n  (not s1.(ms) -> \n     (forall x, VGamma x = Some PublicLoad -> s1.(rmap) x = s2.(rmap) x) /\\\n     (forall a, AGamma a = Some APublic -> s1.(mmap) a = s2.(mmap) a)) ->\n  state_equiv_spec s1 s2 VGamma AGamma.\n\n\nDefinition constant_time_spec (VGamma:venv) (AGamma:aenv) (s1 s2:state) := \nforall s1' s2' d l1 l2 n,\nstate_equiv_spec s1 s2 VGamma AGamma ->\nmulti_step_spec s1 d l1 n s1' ->\nmulti_step_spec s2 d l2 n s2' -> \nl1 = l2 /\\ (safe_state s1' <-> safe_state s2').\n\nDefinition extract_declassify_leakage_spec (l : leakage) : option value :=\nmatch l with \n | Ldeclassify v => v\n | _ => None\nend. \n\nFixpoint extract_declassify_leakages_spec (l : seq leakage) : seq (option value) :=\nmatch l with \n | [::] => [::]\n | l :: ls => extract_declassify_leakage_spec l :: extract_declassify_leakages_spec ls\nend.\n\nFixpoint extract_declassify_leakagess_spec (l : seq (seq leakage)) : seq (seq (option value)) :=\nmatch l with \n | [::] => [::]\n | l :: ls => extract_declassify_leakages_spec l :: extract_declassify_leakagess_spec ls\nend.\n\nDefinition constant_time_declassify_spec (VGamma:venv) (AGamma:aenv) (s1 s2:state) := \nforall s1' s2' d l1 l2 n,\nstate_equiv_spec s1 s2 VGamma AGamma ->\nmulti_step_spec s1 d l1 n s1' ->\nmulti_step_spec s2 d l2 n s2' ->\nextract_declassify_leakagess_spec l1 = extract_declassify_leakagess_spec l2 /\\\n(safe_state s1' <-> safe_state s2').\n\nLemma progress : forall VGamma AGamma s,\ntype_cmd VGamma AGamma s.(scmd) ->\nsafe_state s.\nProof.\nmove=> VGamma AGamma [] /= []. \n(* empty *)\n+ by left.\n(* i::c *)\nmove=> i c r m b hty. induction hty. induction H.\n(* Iempty :: c *)\n+ right. \n  exists Dstep.\n  exists [::].\n  exists {| scmd := c0; \n            rmap := r;\n            mmap := m;\n            ms := b |}.\n  by apply Iempty_sem_spec.\n(* x := e:: c*)\n+ right.\n  exists Dstep. \n  exists (if d \n          then [:: Ldeclassify (Some (sem_expr_spec {| scmd := Iassgn x d e :: c0; rmap := r; mmap := m; ms := b |} e))] \n          else [:: Lempty]). \n  exists {| scmd := c0; \n            rmap := update_rmap r x \n                       (sem_expr_spec {| scmd := Iassgn x d e :: c0; rmap := r; mmap := m; ms := b |} e);\n            mmap := m;\n            ms := b |}.\n  by apply Iassgn_sem_spec.\n(* x := a[e]::c *) (* array can be public/secret *) \n+ case: a H0=> a e H0. right. \n  exists (Dload a (sem_expr_spec {| scmd := Iload x d (AA a e) :: c0; rmap := r; mmap := m; ms := b |} e)).\n  exists  (if d \n           then [:: Lindex (sem_expr_spec {| scmd := Iload x d (AA a e) :: c0; rmap := r; mmap := m; ms := b |} e);\n                    Ldeclassify \n                    (Some (Array.get (mmap {| scmd := Iload x d (AA a e) :: c0; rmap := r; mmap := m; ms := b |} a) \n                           (sem_expr_spec {| scmd := Iload x d (AA a e) :: c0; rmap := r; mmap := m; ms := b |} e)))]\n                else [:: Lindex (sem_expr_spec {| scmd := Iload x d (AA a e) :: c0; rmap := r; mmap := m; ms := b |} e)]).\n  exists {| scmd := c0; \n            rmap := update_rmap r x \n                       (Array.get (mmap {| scmd := Iload x d (AA a e) :: c0; rmap := r; mmap := m; ms := b |} a) \n                       (sem_expr_spec {| scmd := Iload x d (AA a e) :: c0; rmap := r; mmap := m; ms := b |} e));\n            mmap := m;\n            ms := b |}.\n  by apply Iload_sem_spec. \n(* a[e] := e *)\n+ case: a H0=> a ei H0. right. \n  exists (Dstore a (sem_expr_spec {| scmd := Istore (AA a ei) d e :: c0; rmap := r; mmap := m; ms := b |} ei)). \n  exists (if d \n          then [:: Lindex (sem_expr_spec {| scmd := Istore (AA a ei) d e :: c0; rmap := r; mmap := m; ms := b |} ei);\n                   Ldeclassify (Some (sem_expr_spec {| scmd := Istore (AA a ei) d e :: c0; rmap := r; mmap := m; ms := b |} e))]\n          else [:: Lindex (sem_expr_spec {| scmd := Istore (AA a ei) d  e :: c0; rmap := r; mmap := m; ms := b |} ei)]).\n  exists {| scmd := c0; \n            rmap := r;\n            mmap := update_mem m a \n                       (sem_expr_spec {| scmd := Istore (AA a ei) d e :: c0; rmap := r; mmap := m; ms := b |} ei) \n                       (sem_expr_spec {| scmd := Istore (AA a ei) d e :: c0; rmap := r; mmap := m; ms := b |} e);\n            ms := b |}.  \n  by apply Istore_sem_spec. \n(* if b i1 i2 *)\n+ case: b0 H=> b0 e1 e2 H. right.\n  exists (Dforce (eval_bool_op b0 \n                 (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |} e1) \n                 (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |} e2))).\n  exists [::(Lbool (eval_bool_op b0 \n                (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |} e1) \n                (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |} e2)))].\n  exists {| scmd := (if (eval_bool_op b0 (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |} e1) \n                                        (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |} e2)) \n                        then i0 \n                        else i') ++ c0; \n            rmap := {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |}.(rmap);\n            mmap := {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |}.(mmap);\n            ms := if (eval_bool_op b0 \n                     (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |} e1) \n                     (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |} e2)) == \n                     (eval_bool_op b0 \n                     (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |} e1) \n                     (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |} e2)) \n                  then {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |}.(ms) else true |}.\n  by apply Iif_sem_spec with b0 e1 e2 (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |} e1) (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i0 i' :: c0; rmap := r; mmap := m; ms := b |} e2).\n(* protect x v *)\n+ right. \n  exists Dstep. \n  exists [::Lempty]. \n  exists {| scmd := c0; \n            rmap := if b then update_rmap r x 0 else update_rmap r x (r y);\n            mmap := m;\n            ms := b |}.\n  by apply Iprotect_sem_spec. \nby left. \nQed.\n\nLemma union_public_eq : forall T T',\nunion_vlevel T T' = Public ->\nT = Public /\\ T' = Public.\nProof.\nunfold union_vlevel. move=> T T'.\ncase: T=> //=.\nby case: T'=> //=.\nQed.\n\nLemma union_publicload_eq : forall T T',\nunion_vlevel T T' = PublicLoad ->\nT = PublicLoad \\/ T = Public.\nProof.\nunfold union_vlevel. move=> T T'.\ncase: T=> //=.\n+ case: T'=> //=. move=> h. by right.\ncase: T' => //=.\n+ move=> h; by left.\nby left.\nQed.\n\nLemma public_subtype_publicload : forall T,\nsub_vlevel T Public = true ->\nsub_vlevel T PublicLoad.\nProof.\nmove=> T ht. by case: T ht=> //=.\nQed.\n\nDefinition public_ms ms := if ms then Public else PublicLoad.\n\nLemma sub_public_always_public : forall T,\nsub_vlevel T Public = true ->\nT = Public.\nProof.\nby move=> [] //=.\nQed.\n\nLemma sub_publicload_public : forall T,\nsub_vlevel T PublicLoad = true ->\nT = Public \\/ T = PublicLoad. \nProof.\nmove=> [] //= ht.\n+ by left.\nby right. \nQed.\n\nLemma sub_sub_vlevel : forall T T',\nsub_vlevel (union_vlevel T T') Public ->\nsub_vlevel T Public /\\ sub_vlevel T' Public.\nProof.\nmove=> T T' h.\nsplit=> //=;\napply sub_public_always_public in h; rewrite /=.\napply union_public_eq in h; by case: h=> ->.\napply union_public_eq in h; by case: h=> _ ->.\nQed.\n\nLemma sub_sub_vlevel' : forall T T',\nsub_vlevel (union_vlevel T T') PublicLoad ->\nsub_vlevel T PublicLoad /\\ sub_vlevel T' PublicLoad.\nProof.\nmove=> T T' h.\nsplit=> //=.\n+ by case: T h=> //=. \ncase: T' h=> //=. by case: T=> //=. \nQed.\n\nLemma expr_equiv_val : forall VGamma AGamma s1 s2 e T,\nstate_equiv_spec s1 s2 VGamma AGamma ->\ntype_expr VGamma e T ->\nsub_vlevel T (public_ms (s1.(ms))) ->\nsem_expr_spec s1 e = sem_expr_spec s2 e.\nProof.\nmove=> VGamma AGamma [] st1 r1 m1 b1 [] st2 r2 m2 b2 e T /= hvar hty hteq.\nmove: hvar. move=> [] /= hst hb hx hms; subst.\ninduction hty.\n+ rewrite /public_ms in hteq. case: b2 hms hteq.\n  + move=> hms hteq. case: T H hteq=> //=.\n    move=> hx' _. by move: (hx x hx').\n  move=> hms hteq. case: T H hteq=> //=.\n  + move=> hx' _. by move: (hx x hx').\n  move=> hxty. have ht : ~ false. + by auto.\n  move: (hms ht)=> [] hr hm _. by move: (hr x hxty).\nrewrite /public_ms /= in hteq. case: b2 hms IHhty1 IHhty2 hteq.\n+ move=> ht /= h1 h2 /= h. apply sub_sub_vlevel in h.\n  case: h=> h1' h2'.\n  case: o=> //=;move: (h1 h1') => ->; by move: (h2 h2') => ->.\nmove=> ht /= h1 h2 /= h. apply sub_sub_vlevel' in h.\ncase: h=> h1' h2'.\ncase: o=> //=;move: (h1 h1') => ->; by move: (h2 h2') => ->.\nQed.\n\nLemma expr_equiv_val_public : forall VGamma s1 s2 e T,\n(forall x ,VGamma x = Some Public ->\n s1.(rmap) x = s2.(rmap) x) ->\ntype_expr VGamma e T ->\nT = Public ->\nsem_expr_spec s1 e = sem_expr_spec s2 e.\nProof.\nmove=> VGamma [] st1 r1 m1 b1 [] st2 r2 m2 b2 e T /= hvar hty hteq.\ninduction hty.\n+ rewrite hteq in H. rewrite /=. by move: (hvar x H)=> ->.\napply union_public_eq in hteq. case: hteq=> h1 h2.\ncase: o=> //=;move: (IHhty1 h1) => ->; by move: (IHhty2 h2) => ->.\nQed.\n\n(* Because our language design is safe: it never goes to a stuck state *)\n(* In speculative semantic it might be diff *)\nLemma safe_lang : forall s,\nsafe_state s.\nProof.\nrewrite /safe_state /= /final_state /=.\nmove=> [] st r m b /=. case: st=> //=.\n+ by left.\nmove=> i c. case: i.\n(* Iempty *)\n+ right. exists Dstep. exists [::]. exists {| scmd := c; rmap := r; mmap := m; ms := b |}.\n  by apply Iempty_sem_spec.\n(* x := e:: c*)\n+ move=> x d e. right.\n  exists Dstep.\n  exists  (if d \n          then [:: Ldeclassify (Some (sem_expr_spec {| scmd := Iassgn x d e :: c; rmap := r; mmap := m; ms := b |} e))] \n          else [:: Lempty]). \n  exists {| scmd := c; \n            rmap := update_rmap r x \n                       (sem_expr_spec {| scmd := Iassgn x d e :: c; rmap := r; mmap := m; ms := b |} e);\n            mmap := m;\n            ms := b |}.\n  by apply Iassgn_sem_spec.\n(* x := a[e]::c *) (* array can be public/secret *)\n+ move=> x d a. case: a=> a e. right. \n  exists (Dload a (sem_expr_spec {| scmd := Iload x d (AA a e) :: c; rmap := r; mmap := m; ms := b |} e)). \n  exists  (if d \n           then [:: Lindex (sem_expr_spec {| scmd := Iload x d (AA a e) :: c; rmap := r; mmap := m; ms := b |} e);\n                    Ldeclassify \n                    (Some (Array.get (mmap {| scmd := Iload x d (AA a e) :: c; rmap := r; mmap := m; ms := b |} a) \n                           (sem_expr_spec {| scmd := Iload x d (AA a e) :: c; rmap := r; mmap := m; ms := b |} e)))]\n                else [:: Lindex (sem_expr_spec {| scmd := Iload x d (AA a e) :: c; rmap := r; mmap := m; ms := b |} e)]).\n  exists {| scmd := c; \n            rmap := update_rmap r x \n                       (Array.get (mmap {| scmd := Iload x d (AA a e) :: c; rmap := r; mmap := m; ms := b |} a) \n                       (sem_expr_spec {| scmd := Iload x d (AA a e) :: c; rmap := r; mmap := m; ms := b |} e));\n            mmap := m;\n            ms := b |}.\n  by apply Iload_sem_spec. \n\n(* a[e] := e *)\n+ move=> a d e. case: a=> a ei. right. \n  exists (Dstore a (sem_expr_spec {| scmd := Istore (AA a ei) d e :: c; rmap := r; mmap := m; ms := b |} ei)).\n  exists (if d \n          then [:: Lindex (sem_expr_spec {| scmd := Istore (AA a ei) d e :: c; rmap := r; mmap := m; ms := b |} ei);\n                   Ldeclassify (Some (sem_expr_spec {| scmd := Istore (AA a ei) d e :: c; rmap := r; mmap := m; ms := b |} e))]\n          else [:: Lindex (sem_expr_spec {| scmd := Istore (AA a ei) d  e :: c; rmap := r; mmap := m; ms := b |} ei)]).\n  exists {| scmd := c; \n            rmap := r;\n            mmap := update_mem m a \n                       (sem_expr_spec {| scmd := Istore (AA a ei) d e :: c; rmap := r; mmap := m; ms := b |} ei) \n                       (sem_expr_spec {| scmd := Istore (AA a ei) d e :: c; rmap := r; mmap := m; ms := b |} e);\n            ms := b |}.  \n  by apply Istore_sem_spec. \n(* if b i1 i2 *)\n+ move=> b0 i1 i2. case: b0=> b0 e1 e2. right.\n  exists (Dforce (eval_bool_op b0 \n                 (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |} e1) \n                 (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |} e2))).\n  exists [::(Lbool (eval_bool_op b0 \n                (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |} e1) \n                (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |} e2)))].\n  exists {| scmd := (if (eval_bool_op b0 (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |} e1) \n                                        (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |} e2)) \n                        then i1 \n                        else i2) ++ c; \n            rmap := {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |}.(rmap);\n            mmap := {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |}.(mmap);\n            ms := if (eval_bool_op b0 \n                     (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |} e1) \n                     (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |} e2)) == \n                     (eval_bool_op b0 \n                     (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |} e1) \n                     (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |} e2)) \n                  then {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |}.(ms) else true |}.\n  by apply Iif_sem_spec with b0 e1 e2 (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |} e1) (sem_expr_spec {| scmd := Iif (Ebool b0 e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := b |} e2).\n(* protect x y *)\n+ move=> x y. right. \n  exists Dstep. \n  exists [::Lempty].\n  exists {| scmd := c; \n            rmap := if b then update_rmap r x 0 else update_rmap r x (r y);\n            mmap := m;\n            ms := b |}.\n  by apply Iprotect_sem_spec. \nQed.\n\nLemma leakage_eq_n : forall s d l n s',\nmulti_step_spec s d l n s' ->\nsize l = n.\nProof.\nmove=> [] st r m b d l n [] st' r' m' b' hmulti.\ninduction hmulti; auto.\nby induction H;rewrite -cat1s size_cat /= IHhmulti add1n /= addn1. \nQed.\n\nLemma type_concat : forall VGamma AGamma c1 c2,\ntype_cmd VGamma AGamma c1 ->\ntype_cmd VGamma AGamma c2 ->\ntype_cmd VGamma AGamma (c1 ++ c2).\nProof.\nmove=> VGamma AGamma c1 c2 hc1 hc2.\ninduction c1; rewrite /=.\n+ by apply hc2.\ninversion hc1; subst.\napply T_seq. \n+ by apply H1.  \napply IHc1. by apply H2.\nQed.\n\nLemma preservation : forall VGamma AGamma s1 d1 l1 s1',\ntype_cmd VGamma AGamma s1.(scmd) ->\nsem_instr_spec s1 d1 l1 s1' ->\ntype_cmd VGamma AGamma s1'.(scmd).\nProof.\nmove=> VGamma AGamma [] st r m b d1 l1 s1' hty hstep.\ninduction hstep.\n(* Iempty *)\n+ rewrite H /= in hty. by inversion hty; (try discriminate); subst.\n(* x := e *)\n+ rewrite /update_rmap /update_map /=. rewrite H in hty.\n  by inversion hty.\n(* if b i1 i2 *)\n+ rewrite H /= in hty. inversion hty; subst.\n  inversion H5; subst.\n  case: ifP=> //=.\n  (* true *)\n  + move=> htrue. by move: (type_concat H4 H6).\n  (* false *)\n  move=> hfalse. by move: (type_concat H7 H6).\n(* x := a[e] *)\n+ rewrite /update_rmap /update_map /=. rewrite H in hty.\n  by inversion hty.\n(* a[e] := e *)\n+ rewrite /update_rmap /update_map /=. rewrite H in hty.\n  by inversion hty.\n(* protect x v *)\nrewrite /update_rmap /update_map /=. rewrite H in hty.\nby inversion hty.\nQed.\n\nLemma step_spec_spec : forall s d l s',\nsem_instr_spec s d l s' ->\ns.(ms) = true ->\ns'.(ms) = true.\nProof.\nmove=> [] st1 r1 m1 ms d l s' hstep /= hms; subst.\ninversion hstep; auto.\nrewrite /= in H6. rewrite /=.\nby case: ifP=> //=.\nQed.\n\nLemma step_deterministic_dir : forall s d l1 s1 l2 s2,\nsem_instr_spec s d l1 s1 ->\nsem_instr_spec s d l2 s2 ->\nl1 = l2 /\\ s1 = s2.\nProof.\nmove=> [] st1 r1 m1 ms1 d l1 s2 l2 s2' hstep hstep'.\ninversion hstep; (try discriminate); subst.\n(* Iempty *)\n+ rewrite /= in H. rewrite H /= in hstep'. \n  inversion hstep'; (try discriminate); subst.\n  rewrite /= in H0 hstep hstep'; subst.\n  split=> //=; by inversion H0.\n(* x := e *)\n+ rewrite /= in H. rewrite H /= in hstep'. \n  inversion hstep'; (try discriminate); subst.\n  rewrite /= in H0 hstep hstep'; subst.\n  split=> //=. by case: H0=> /= h1 h2 h3 h4; subst.\n  by inversion H0.\n(* if b i i' *)\n+ inversion hstep'; (try discriminate); subst.\n  rewrite /= in H H1 hstep hstep'; subst.\n  case: H1=> h1 h2 h3 h4 h5 h6; subst. by split=> //=.\n(* x := a[e] *)\n+ rewrite /= in H. rewrite H /= in hstep'.\n  inversion hstep'; (try discriminate); subst.\n  rewrite /= in H3 H5 hstep hstep'; subst.\n  case: H5=> h1 h2 h3 h4; subst. by split=> //=.\n(* a[e] := e *)\n+ rewrite /= in H. rewrite H /= in hstep'.\n  inversion hstep'; (try discriminate); subst.\n  rewrite /= in H3 H5 hstep hstep'; subst.\n  case: H5=> h1 h2 h3 h4; subst. by split=> //=.\n(* protect *)\nrewrite /= in H. rewrite H /= in hstep'. \ninversion hstep'; (try discriminate); subst.\nsplit=> //=. by case: H0=> h1 h2 h3; subst.\nQed.\n\nDefinition declassify_val_spec (d:bool) ve (v : seq (option value)) : value := \n  if d then (odflt 0 (last None v))\n  else ve.\n\nDefinition build_i_leakage_spec (s: state) (v : seq (option value)) : seq leakage :=\nmatch (nth Iempty (scmd s) 0) with \n | Iempty => [::]\n | Iassgn x d e => if d then [:: Ldeclassify (nth None v 0)] else [:: Lempty]\n | Iload x d (AA a e) => if d then [:: Lindex (sem_expr_spec s e); Ldeclassify (nth None v 1)]\n                              else [:: Lindex (sem_expr_spec s e)]\n | Istore (AA a e) d e' => if d then [:: Lindex (sem_expr_spec s e); Ldeclassify (nth None v 1)] \n                                else [:: Lindex (sem_expr_spec s e)] \n | Iif (Ebool bop e1 e2) i1 i2 => [:: Lbool (eval_bool_op bop (sem_expr_spec s e1) (sem_expr_spec s e2))]\n | Iprotect x y => [:: Lempty]  \nend. \n\nInductive build_state_instr_spec : state -> seq (option value) -> directive -> state -> Prop :=\n| build_next_empty : forall c r m ms,\n                      build_state_instr_spec {| scmd := Iempty :: c; rmap := r; mmap := m; ms := ms |} [::] Dstep\n                      {| scmd := c; rmap := r; mmap := m; ms := ms |}\n| build_next_assgn : forall x d e c r m ms vs,\n                      build_state_instr_spec {| scmd := Iassgn x d e :: c; rmap := r; mmap := m; ms := ms |} vs Dstep\n                      {| scmd := c; \n                         rmap := update_rmap r x \n                                  (declassify_val_spec d \n                                   (sem_expr_spec {| scmd := Iassgn x d e :: c; rmap := r; mmap := m; ms := ms |} e) vs);\n                         mmap := m; ms := ms |}\n| build_next_load : forall x d a e c r m ms vs,\n                    build_state_instr_spec {| scmd := Iload x d (AA a e) :: c; rmap := r; mmap := m; ms := ms |} vs \n                    (Dload a (sem_expr_spec {| scmd := Iload x d (AA a e) :: c; rmap := r; mmap := m; ms := ms |} e))\n                    {| scmd := c; \n                       rmap := update_rmap r x \n                               (declassify_val_spec d (Array.get (m a) \n                               (sem_expr_spec {| scmd := Iload x d (AA a e) :: c; rmap := r; mmap := m; ms := ms |} e)) vs);\n                       mmap := m; \n                       ms := ms |}\n| build_next_store : forall d a e e' c r m ms vs,\n                     build_state_instr_spec {| scmd := Istore (AA a e) d e' :: c; rmap := r; mmap := m; ms := ms |} vs\n                     (Dstore a (sem_expr_spec {| scmd := Istore (AA a e) d e' :: c; rmap := r; mmap := m; ms := ms |} e))\n                      {| scmd := c; \n                         rmap := r;\n                         mmap := update_mem m a \n                                 (sem_expr_spec {| scmd := Istore (AA a e) d e' :: c; rmap := r; mmap := m; ms := ms |}  e) \n                                 (declassify_val_spec d \n                                 (sem_expr_spec {| scmd := Istore (AA a e) d e' :: c; rmap := r; mmap := m; ms := ms |} e') vs);\n                         ms := ms |}\n| build_next_if : forall e1 e2 i1 i2 bop bf c r m ms vs,\n                  build_state_instr_spec {| scmd := Iif (Ebool bop e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := ms |} vs\n                  (Dforce bf)\n                  {| scmd := (if bf then i1 else i2) ++ c; \n                     rmap := r;\n                     mmap := m;\n                     ms := if (eval_bool_op bop \n                               (sem_expr_spec {| scmd := Iif (Ebool bop e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := ms |} e1)\n                               (sem_expr_spec {| scmd := Iif (Ebool bop e1 e2) i1 i2 :: c; rmap := r; mmap := m; ms := ms |} e2)) == bf \n                           then ms \n                           else true |}\n| build_next_protect : forall x y c r m ms vs,\n                       build_state_instr_spec {| scmd := Iprotect x y :: c; rmap := r; mmap := m; ms := ms |} vs\n                       Dstep\n                       {| scmd := c; \n                          rmap := if ms\n                                  then update_rmap r x 0\n                                  else update_rmap r x (r y);\n                          mmap := m;\n                          ms := ms |}.\n\n(*Inductive build_c_leakage_spec : state -> seq (seq (option value)) -> seq (seq leakage) -> Prop :=\n| build_leakage_empty_c_vs : forall r m ms, \n                             build_c_leakage_spec {| scmd := [::]; rmap := r; mmap := m; ms := ms |} [::] [::] \n| build_leakage_seq_c_vs   : forall i c r m ms d v vs s' ls,\n                             build_state_instr_spec {| scmd := i :: c; rmap := r; mmap := m; ms := ms |} v d s' ->\n                             build_c_leakage_spec s' vs ls ->\n                             build_c_leakage_spec {| scmd := i :: c; rmap := r; mmap := m; ms := ms |} (v :: vs) \n                             ((build_i_leakage_spec {| scmd := i :: c; rmap := r; mmap := m; ms := ms |}  v) :: ls)\n| build_leakage_empty_c_seq_vs : forall r m ms vs, \n                                 build_c_leakage_spec {| scmd := [::]; rmap := r; mmap := m; ms := ms |} vs [::]\n| build_leakage_seq_c_empty_vs : forall i c r m ms, \n                                 build_c_leakage_spec {| scmd := i :: c; rmap := r; mmap := m; ms := ms |} [::] [::].*)\n\nInductive build_c_leakage_spec : state -> seq (seq (option value)) -> seq directive -> seq (seq leakage) -> Prop :=\n| build_leakage_empty_c_vs : forall r m ms, \n                             build_c_leakage_spec {| scmd := [::]; rmap := r; mmap := m; ms := ms |} [::] [::] [::] \n| build_leakage_seq_c_vs   : forall i c r m ms d ds v vs s' l ls,\n                             build_i_leakage_spec {| scmd := i :: c; rmap := r; mmap := m; ms := ms |}  v = l ->\n                             build_state_instr_spec {| scmd := i :: c; rmap := r; mmap := m; ms := ms |} v d s' ->\n                             build_c_leakage_spec s' vs ds ls ->\n                             build_c_leakage_spec {| scmd := i :: c; rmap := r; mmap := m; ms := ms |} (v :: vs) (d :: ds)\n                             (l :: ls)\n| build_leakage_empty_c_seq_vs : forall r m ms vs, \n                                 build_c_leakage_spec {| scmd := [::]; rmap := r; mmap := m; ms := ms |} vs [::] [::]\n| build_leakage_seq_c_empty_vs : forall i c r m ms, \n                                 build_c_leakage_spec {| scmd := i :: c; rmap := r; mmap := m; ms := ms |} [::] [::] [::].\n\nLemma declassify_mem_to_leakage_spec : forall VGamma AGamma c,\ntype_cmd VGamma AGamma c ->\n(forall s1 s2 ov, \n   c = s1.(scmd) ->\n   state_equiv_spec s1 s2 VGamma AGamma ->\n   build_i_leakage_spec s1 ov = build_i_leakage_spec s2 ov).\nProof.\nmove=> VGamma AGamma c hty.\nmove=> [] c1 r1 m1 ms1 [] c2 r2 m2 ms2 ov /= hc /= hequiv /=; subst.\nmove: hequiv=> [] /= hc hms hr hm; subst. rewrite /= in hty.\nelim: hty; last first. + by auto.\nmove=> i c htyi htyc hrec. move: r1 m1 r2 m2 hr hm hrec.\ninduction htyi.\n(* empty *)\n+ by move=> r1 m1 r2 m2 hr hm hrec /=.\n(* x := e *)\n+ by move=> r1 m1 r2 m2 hr hm hrec /=.\n(* x := a[e] *)\n+ move=> r1 m1 r2 m2 hr hm hrec /=. case: a H0=> //=.\n  move=> x' e htya. inversion htya; subst.\n  have hpub : Public = Public. + by auto.\n  rewrite /build_i_leakage_spec /=.\n  have hequiv : state_equiv_spec {| scmd := Iload x d (AA x' e) :: c; rmap := r1; mmap := m1; ms := ms2 |} \n                {| scmd := Iload x d (AA x' e) :: c; rmap := r2; mmap := m2; ms := ms2 |} VGamma AGamma.\n  + by auto.\n  have hms : sub_vlevel Public (public_ms (ms\n              {| scmd := Iload x d (AA x' e) :: c; rmap := r1; mmap := m1; ms := ms2 |})).\n  + by auto. \n  by have -> := expr_equiv_val hequiv H5 hms. \n(* a[e] := e *)\n+ move=> r1 m1 r2 m2 hrec hm hr. case: a H0=> //=.\n  move=> x' ei htya. inversion htya; subst.\n  have hpub : Public = Public. + by auto.\n  rewrite /build_i_leakage_spec /=.\n  have hequiv : state_equiv_spec {| scmd := Istore (AA x' ei) d e :: c; rmap := r1; mmap := m1; ms := ms2 |} \n                {| scmd := Istore (AA x' ei) d e :: c; rmap := r2; mmap := m2; ms := ms2 |} VGamma AGamma.\n  + by auto.\n  have hms : sub_vlevel Public (public_ms (ms\n              {| scmd := Istore (AA x' ei) d e :: c; rmap := r1; mmap := m1; ms := ms2 |})).\n  + by auto.\n  by have -> := expr_equiv_val hequiv H5 hms. \n(* if e i i' *)\n+ move=> r1 m1 r2 m2 hr hm hrec /=. case: b H=> //= b' e e' hty.\n  inversion hty; subst. apply union_public_eq in H5.\n  case H5=> h5 h6; subst. case: H5=> hpub _.\n  rewrite /build_i_leakage_spec /=.\n  have hequiv : state_equiv_spec {| scmd := Iif (Ebool b' e e') i i' :: c; rmap := r1; mmap := m1; ms := ms2 |} \n                {| scmd := Iif (Ebool b' e e') i i' :: c; rmap := r2; mmap := m2; ms := ms2 |} VGamma AGamma.\n  + by auto.\n  have hms : sub_vlevel Public (public_ms (ms\n              {| scmd := Iif (Ebool b' e e') i i' :: c; rmap := r1; mmap := m1; ms := ms2 |})).\n  + by auto.\n  have -> := expr_equiv_val hequiv H3 hms. by have -> := expr_equiv_val hequiv H6 hms.\n(* protect *)\nmove=> r1 m1 r2 m2 hr hm hrec /=.\nby rewrite /build_i_leakage_spec /=.\nQed.\n\nLemma declassify_to_leakage_i_spec :\nforall s1 s1' d l c, \n c = s1.(scmd) -> \n sem_instr_spec s1 d l s1' -> \n build_i_leakage_spec s1 (extract_declassify_leakages_spec l) = l.\nProof.\nmove=> s1 s1' d l c. case: s1=> c1 r1 m1 ms /= hc; subst.\ncase: c1=> //=.\n+ move=> hsem. by inversion hsem; subst; (try discriminate).\nmove=> [].\n+ move=> c /=.\n(* empty *)\n+ move=> hsem. inversion hsem; subst; (try discriminate). \n  by rewrite /build_i_leakage_spec /extract_declassify_leakages_spec /=.\n(* assgn *)\n+ move=> x d' e c hsem. inversion hsem; subst; (try discriminate).\n  case: H=> h1 h2 h3 h4; subst.\n  rewrite /build_i_leakage_spec /=. by case: d0 hsem=> hsem /=.\n(* load *)\n+ move=> x d' a c hsem. inversion hsem; subst; (try discriminate).\n  case: H=> h1 h2 h3 h4; subst.\n  rewrite /build_i_leakage_spec /=. by case: d0 hsem=> hsem /=.\n(* store *)\n+ move=> x d' a c hsem. inversion hsem; subst; (try discriminate).\n  case: H=> h1 h2 h3 h4; subst.\n  rewrite /build_i_leakage_spec /=. by case: d0 hsem=> hsem /=.\n(* cond *)\n+ move=> b c c1' c2' hsem. inversion hsem; subst; (try discriminate).\n  case: H=> h1 h2 h3 h4; subst. by rewrite /build_i_leakage_spec /=. \n(* protect *)\nmove=> x y c hsem. inversion hsem; subst; (try discriminate).\ncase: H=> h1 h2 h3; subst. by rewrite /build_i_leakage_spec /=.\nQed.\n\nLemma build_empty_c_leakage : forall r1 m1 ms1 ov,\nbuild_c_leakage_spec {| scmd := [::]; rmap := r1; mmap := m1; ms := ms1 |} ov [::] [::].\nProof.\nmove=> r1 m1 ms1 ov /=. case: ov=> //=.\n+ by constructor.\nmove=> v vs /=. by constructor.\nQed.\n\nLemma build_empty_dvalue_leakage : forall s1,\nbuild_c_leakage_spec s1 [::] [::] [::].\nProof.\nmove=> s1. case: s1=> //=.\nmove=> c r m ms /=. case: c=> //=.\n+ by constructor.\nmove=> v vs /=. by constructor.\nQed.\n\nLemma step_declassify_state_equiv_spec : forall VGamma AGamma c s1 s2 d ov s1' s2',\ntype_cmd VGamma AGamma c ->\ns1.(scmd) = c ->\nstate_equiv_spec s1 s2 VGamma AGamma ->\nbuild_state_instr_spec s1 ov d s1' ->\nbuild_state_instr_spec s2 ov d s2' ->\nstate_equiv_spec s1' s2' VGamma AGamma.\nProof.\nmove=> VGamma AGamma c [] st1 r1 m1 ms1 [] st2 r2 m2 ms2 dir ov s1' s2' /= hty hc hequiv.\nhave hequiv' := hequiv.\nmove: hequiv=> [] /= hst hms hr hm. \nmove: r1 m1 ms1 r2 m2 ms2 dir ov s1' s2' hms hr hm hequiv'; subst.\ninduction hty; subst.\n+ induction H; rewrite /=.\n  (* Iempty *)\n  + move=> r1 m1 ms1 r2 m2 ms2 dir ov s1' s2' hms hr hm hequiv' hb1 hb2.\n    inversion hb1; (try discriminate); subst.\n    inversion hb2; (try discriminate); subst.\n    by apply st_equiv_spec.\n(* x := e *)\n+ move=> r1 m1 ms1 r2 m2 ms2 dir ov s1 s2' hms hr hm hequiv' hb1 hb2 /=.\n  inversion hb1; (try discriminate); subst.\n  inversion hb2; (try discriminate); subst.\n  apply st_equiv_spec. \n  + by auto.\n  + by auto.\n  + case: d H1 IHhty hequiv' hb1 hb2 => //=.\n    + case: T H=> //=.\n      (* x is secret *) \n      + move=> hx _ IHhty hequiv' hb1 hb2 x' hx' /=.\n        rewrite /update_rmap /update_map. case: ifP=> /=.\n        + by move=> hxeq.\n        move=> hxneq. by move: (hr x' hx').\n      (* x is publicload *)\n      move=> hx _ IHhty hequiv' hb1 hb2 x' hx' /=.\n      rewrite /update_rmap /update_map /=. case: ifP=> //=.\n      move=> hneq. by move: (hr x' hx').\n    (* d is false *)\n    move=> H1 IHhty hequiv' hb1 hb2 x' hx' /=. \n    rewrite /update_rmap /update_map. case: ifP=> //=.\n    + move=> hxeq. apply eqb_eq in hxeq; subst.\n      rewrite H in hx'. case: hx'=> hx''; subst.\n      apply sub_public_always_public in H1; subst. have hpub : Public = Public. + by auto.\n      by have /= := expr_equiv_val_public {| scmd := Iassgn x' false e :: c; rmap := r1; mmap := m1; ms := ms2 |} \n              {| scmd := Iassgn x' false e :: c; rmap := r2; mmap := m2; ms := ms2 |} hr H0 hpub.\n    move=> hxneq. by move: (hr x' hx').\n  (* no speculation *)\n  move=> /= hms'. case: d H1 IHhty hequiv' hb1 hb2 => //=.\n  + case: T H=> //=.\n    (* x is secret *)\n    + move=> hx _ IHhty hequiv' hb1 hb2 /=. split=> //=.\n      + rewrite /update_rmap /update_map /=. move=> x' hx'.\n        case: ifP=> //=. move=> hneq. move: (hm hms')=> [] hr' hm'.\n        by move: (hr' x' hx').\n      move=> a ha. move: (hm hms')=> [] hr' hm'. by move: (hm' a ha).\n    (* x is publicload *)\n    + move=> hx _ IHhty hequiv' hb1 hb2 /=. split=> //=.\n      + move=> x' hx'. rewrite /update_rmap /update_map. case: ifP=> //=.\n        + move=> hneq. move: (hm hms')=> [] hr' hm'.\n        by move: (hr' x' hx').\n      move=> a ha. move: (hm hms')=> [] hr' hm'. by move: (hm' a ha). \n  move=> H1 IHhty hequiv'. split=> //=.\n  + move=> x' hx'. rewrite /update_rmap /update_map. case: ifP=> //=.\n    + move=> hxeq. apply eqb_eq in hxeq; subst. rewrite H in hx'.\n      case: hx'=> [] ht; subst. apply sub_publicload_public in H1; subst.\n      case: H1.\n      + move=> H1; subst. have hpub : Public = Public. + by auto.\n        by have /= := expr_equiv_val_public {| scmd := Iassgn x' false e :: c; rmap := r1; mmap := m1; ms := ms2 |} \n              {| scmd := Iassgn x' false e :: c; rmap := r2; mmap := m2; ms := ms2 |} hr H0 hpub.\n      have hsub : sub_vlevel PublicLoad\n     (public_ms (ms {| scmd := Iassgn x' false e :: c; rmap := r1; mmap := m1; ms := ms2 |})) .\n      + rewrite /public_ms. by case: ifP=> //=.\n      move=> H1; subst. by have := expr_equiv_val hequiv' H0 hsub.\n     move=> hxneq. move: (hm hms')=> [] hr' hm'. by move: (hr' x' hx').\n  move=> a ha. move: (hm hms')=> [] hr' hm'. by move: (hm' a ha).\n(* x := a[e] *)\n+ move=> r1 m1 ms1 r2 m2 ms2 dir ov s1' s2' hms hr hm hequiv' hb1 hb2 /=. \n  case: a H0 IHhty hequiv' hb1 hb2=> //=.\n  move=> x' ei hta IHhty hequiv' hb1 hb2 /=.\n  inversion hb1; (try discriminate); subst.\n  inversion hb2; (try discriminate); subst.\n  apply st_equiv_spec.\n  + by auto.\n  + by auto.\n  + move=> x'' hr' /=. inversion hta; (try discriminate); subst.\n    case: d H1 IHhty hequiv' hb1 hb2 H11 => //=.\n    + case: T H=> //=. \n      + move=> hx _ IHhty hequiv' /=. \n        rewrite /update_rmap /update_map /=. \n        case: ifP=> //=. move=> hneq. by move: (hr x'' hr').\n      move=> hx _ IHhty hequiv' hb1 hb2 hei. \n      rewrite /update_rmap /update_map /=. case: ifP=> //=.\n      move=> hneq. by move: (hr x'' hr').\n    move=> H1 IHhty hequiv'. \n    rewrite /update_rmap /update_map. case: ifP=> //=.\n    + move=> hxeq. apply eqb_eq in hxeq; subst. rewrite H in hr'. case: hr'=> h1; subst.\n      apply  sub_public_always_public in H1. by case: T' hta H3 H1=> //=.\n    move=> hneq. by move: (hr x'' hr').\n  move=> /= hms1. case: d H1 IHhty hequiv' hb1 hb2 H11 => //. \n  + move=> H1 IHhty hequiv' /=. split=> //=.\n    + move=> x'' hx''. rewrite /update_rmap /update_map /=. case: ifP=> //=.\n      move=> hneq. move: (hm hms1)=> [] hr' hm'. by move: (hr' x'' hx'').\n    move=> a ha. move: (hm hms1)=> [] hr' hm'. by move: (hm' a ha).\n  move=> H1 IHhty hequiv' /=. split=> //=.\n  + move=> x'' hx''. rewrite /update_rmap /update_map /=. case: ifP=> //=.\n    + move=> heq. move: (hm hms1)=> [] hr' hm'. apply eqb_eq in heq; subst.\n      rewrite H in hx''. case: hx''=> h1; subst. inversion hta; (try discriminate); subst.\n      rewrite H11 /=.\n      apply sub_publicload_public in H1; subst. case: T' hta H3 H1=> //=.\n      + by move=> haty hx'ty [] //=.\n      move=> haty hx' [] //= _. move: (hm hms1)=> [] hr1 hm1. by move: (hm1 x' hx')=> ->.\n    move=> hneq. move: (hm hms1)=> [] hr' hm'. by move: (hr' x'' hx'').\n  move=> a ha. move: (hm hms1)=> [] hr' hm'. by move: (hm' a ha).\n(* a[e] := e *)\n+ move=> r1 m1 ms1 r2 m2 ms2 dir ov s1' s2' hms hr hm hequiv' hb1 hb2 /=.\n  case: a H0 IHhty hequiv' hb1 hb2=> //=.\n  move=> x' ei hta IHhty hequiv' hb1 hb2 /=.\n  inversion hb1; (try discriminate); subst.\n  inversion hb2; (try discriminate); subst.\n  apply st_equiv_spec.\n  + by auto.\n  + by auto.\n  + move=> x'' hr' /=. inversion hta; (try discriminate); subst.\n    case: d H1 IHhty hequiv' hb1 hb2 H11=> //=.\n    + case: T H=> //=. \n      + move=> hx _ IHhty hequiv' /=. by move: (hr x'' hr').\n        move=> H. case: T' hta H3=> //= hta H3 _ IHhty hequiv'. by move: (hr x'' hr').\n      by move: (hr x'' hr').\n    move=> H. case: T' hta H3=> //= hta H3 _ IHhty hequiv'. by move: (hr x'' hr').\n    by move: (hr x'' hr').\n    move=> H1 IHhty hequiv'. by move: (hr x'' hr').\n  move=> /= hms1. split=> //=.\n  + move=> x'' hx''. move: (hm hms1)=> [] hr' hm'. by move: (hr' x'' hx'').\n  move=> a ha /=. case: d H1 IHhty hequiv' hb1 hb2 H11=> //=.\n  + case: T' hta=> //= hta _ IHhty hequiv' /=.\n    inversion hta; (try discriminate); subst.\n    rewrite /update_mem /update_map /=. case: ifP=> //=.\n    + move=> heq. apply eqb_eq in heq; subst.\n      rewrite ha in H2. by case: H2.\n    move=> hneq. move: (hm hms1)=> [] hr' hm'. by move: (hm' a ha).\n  move=> hb1 hb2 heeq. rewrite /update_mem /update_map. case: ifP=> //=.\n  + move=> heq. apply eqb_eq in heq; subst.\n    move: (hm hms1)=> [] hr1 hm1. by move: (hm1 a ha)=> ->.\n  move=> hneq. move: (hm hms1)=> [] hr1 hm1. by move: (hm1 a ha)=> ->.\n  move=> H1 Ihhty hequiv' /=. move: (hm hms1)=> [] hr' hm'.\n  rewrite /update_mem /update_map /=. case: ifP=> //=.\n  + move=> heq. apply eqb_eq in heq; subst.\n    move: (hm' a ha)=> ->. inversion hta; (try discriminate); subst.\n    rewrite ha in H3. case: H3=> h3; subst.\n    have hpub : Public = Public. + by auto.\n    have -> := expr_equiv_val_public {| scmd := Istore (AA a ei) false e :: c; rmap := r1; mmap := m1; ms := ms2 |}\n          {| scmd := Istore (AA a ei) false e :: c; rmap := r2; mmap := m2; ms := ms2 |} hr H5 hpub.\n    case: T H1 H=> //= _ H1. \n    by have -> := expr_equiv_val_public {| scmd := Istore (AA a ei) false e :: c; rmap := r1; mmap := m1; ms := ms2 |}\n          {| scmd := Istore (AA a ei) false e :: c; rmap := r2; mmap := m2; ms := ms2 |} hr H1 hpub.\n  move=> hb1 hb2 heeq. move: (hm hms1)=> [] hr1 hm1. move: (hm1 a ha)=> <-. \n  have hsub : (sub_vlevel PublicLoad\n     (public_ms\n        (ms {| scmd := Istore (AA a ei) false e :: c; rmap := r1; mmap := m1; ms := ms2 |}))). + rewrite /public_ms /=. by case: ifP=> //=.\n  by have -> := expr_equiv_val hequiv' H1 hsub.\n by move: (hm' a ha).\n(* If b i i' *)\n+ move=> r1 m1 ms1 r2 m2 ms2 dir ov s1' s2' hms hr hm hequiv' hb1 hb2 /=. \n  case: b H0 H IHhty hequiv' hb1 hb2 => //=.\n  move=> bop e e' hity hbty IHhty hequiv' hb1 hb2 /=. \n  inversion hb1; (try discriminate); subst.\n  inversion hb2; (try discriminate); subst.\n  inversion hbty; (try discriminate); subst.\n  apply union_public_eq in H4. case: H4=> h4 h5; subst.\n  apply st_equiv_spec. + by auto. \n  + rewrite /=. have hpub : Public = Public. + by auto.\n    have -> := expr_equiv_val_public {| scmd := Iif (Ebool bop e e') i i' :: c; rmap := r1; mmap := m1; ms := ms2 |}\n            {| scmd := Iif (Ebool bop e e') i i' :: c; rmap := r2; mmap := m2; ms := ms2 |} hr H2 hpub.\n    by have -> := expr_equiv_val_public {| scmd := Iif (Ebool bop e e') i i' :: c; rmap := r1; mmap := m1; ms := ms2 |}\n            {| scmd := Iif (Ebool bop e e') i i' :: c; rmap := r2; mmap := m2; ms := ms2 |} hr H5 hpub.\n  + move=> x hx /=. by move: (hr x hx).\n  + move=> /= hms'. split=> //=.\n    + move=> x hx. have hpub : Public = Public. + by auto.\n    have he := expr_equiv_val_public {| scmd := Iif (Ebool bop e e') i i' :: c; rmap := r1; mmap := m1; ms := ms2 |}\n            {| scmd := Iif (Ebool bop e e') i i' :: c; rmap := r2; mmap := m2; ms := ms2 |} hr H2 hpub.\n    have he' := expr_equiv_val_public {| scmd := Iif (Ebool bop e e') i i' :: c; rmap := r1; mmap := m1; ms := ms2 |}\n            {| scmd := Iif (Ebool bop e e') i i' :: c; rmap := r2; mmap := m2; ms := ms2 |} hr H5 hpub.\n    rewrite he he' /= in hms'. move: hms'. case: ifP=> //= heval hms'.\n    move: (hm hms')=> [] hr' hm'. by move: (hr' x hx).\n  move=> a ha.  have hpub : Public = Public. + by auto.\n  have he := expr_equiv_val_public {| scmd := Iif (Ebool bop e e') i i' :: c; rmap := r1; mmap := m1; ms := ms2 |}\n            {| scmd := Iif (Ebool bop e e') i i' :: c; rmap := r2; mmap := m2; ms := ms2 |} hr H2 hpub.\n  have he' := expr_equiv_val_public {| scmd := Iif (Ebool bop e e') i i' :: c; rmap := r1; mmap := m1; ms := ms2 |}\n            {| scmd := Iif (Ebool bop e e') i i' :: c; rmap := r2; mmap := m2; ms := ms2 |} hr H5 hpub.\n  rewrite he he' /= in hms'. move: hms'. case: ifP=> //= heval hms'. move: (hm hms')=> [] hr' hm'.\n  by move: (hm' a ha).\n(* Protect x y *)\n+ move=> r1 m1 ms1 r2 m2 ms2 ov dir s1' s2' hms hr hm hequiv' hb1 hb2 /=.\n  inversion hb1; (try discriminate); subst.\n  inversion hb2; (try discriminate); subst.\n  apply st_equiv_spec.\n  + by auto.\n  + by auto.\n  + move=> x' hx' /=. case: ms2 hm hequiv' hb1 hb2=> //=.\n    + move=> hms hm hequiv'; subst.\n      rewrite /update_rmap /update_map. case: ifP=> //=.\n      move=> hneq. by move: (hr x' hx').\n    move=> hms hm hequiv'; subst. rewrite /update_rmap /update_map /=.\n    case: ifP=> //=.\n    + move=> heq. apply eqb_eq in heq; subst. apply sub_publicload_public in H1; subst.\n      case: H1=> //=.\n      + move=> H1; subst. by move: (hr y H0).\n      move=> H1; subst. have ht : ~false. + by auto.\n      move: (hms ht)=> [] hr1 hm1. by move: (hr1 y H0).\n    move=> hneq. by move: (hr x' hx').\n  move=> /= hms1. split=> //=.\n  + move=> x' hx'. case: ifP=> //=.\n    + move=> hms1'; subst. move: (hm hms1)=> [] hr' hm'.\n      rewrite /update_rmap /update_map. case: ifP=> //=.\n      + move=> heq. apply eqb_eq in heq; subst. apply sub_publicload_public in H1; subst.\n        case: H1=> //=.\n        + move=> H1; subst. by move: (hr y H0).\n        move=> H1; subst. by move: (hr' y H0).\n      move=> hneq. by move: (hr' x' hx').\n    move=> a ha. move: (hm hms1)=> [] hr' hm'. by move: (hm' a ha).\nmove=> r1 m1 ms1 r2 m2 ms2 dir ov /= s1' s2' hms hr hm hequiv hb1 hb2 /=; subst. \nby inversion hb1; (try discriminate); subst. \nQed.\n\nLemma st_show_spec : forall s,\n{| scmd := scmd s; rmap := rmap s; mmap := mmap s; ms := ms s |} = s. \nProof.\nmove=> s. by case: s.\nQed.\n\nLemma step_to_build_state_spec : forall s d l s',\nsem_instr_spec s d l s' ->\nbuild_state_instr_spec s (extract_declassify_leakages_spec l) d s'.\nProof.\nmove=> [] c r1 m1 ms1 d l s' hstep.\ncase: c hstep=> //=.\n+move=> hstep. by inversion hstep; (try discriminate); subst.\nmove=> i c hstep. case: i hstep=> //=.\n(* Iempty *)\n+ move=> hstep. inversion hstep; (try discriminate); subst; rewrite /=.\n  inversion H; (try discriminate); subst. by constructor.\n(* x := e *)\n+ move=> x d' e hstep. case: d' hstep=> //=.\n  + move=> hstep. inversion hstep; (try discriminate); subst.\n    case: d0 hstep H=> //= hstep [] h1 h2 h3; subst. by constructor.\n  move=> hstep. inversion hstep; (try discriminate); subst; rewrite /=.\n  case: d0 hstep H=> //= hstep [] h1 h2 h3; subst. by constructor.\n(* x := a[e] *)\n+ move=> x d' a hstep. case: d' hstep=> //=.\n  + move=> hstep. inversion hstep; (try discriminate); subst.\n    case: d0 hstep H=> //= hstep [] h1 h2 h3; subst. by constructor.\n  move=> hstep. inversion hstep; (try discriminate); subst; rewrite /=.\n  case: d0 hstep H=> //= hstep [] h1 h2 h3; subst. by constructor.\n(* a[e] := e *)\n+ move=> x d' e hstep. case: d' hstep=> //=.\n  + move=> hstep. inversion hstep; (try discriminate); subst.\n    case: d0 hstep H=> //= hstep [] h1 h2 h3; subst. by constructor.\n  move=> hstep. inversion hstep; (try discriminate); subst; rewrite /=.\n  case: d0 hstep H=> //= hstep [] h1 h2 h3; subst. by constructor.\n(* if b i i' *)\n+ move=> b i i' hstep. case: b hstep=> //= bop e e' hstep.\n  inversion hstep; (try discriminate); subst; rewrite /=. \n  inversion H; (try discriminate); subst.\n  by apply build_next_if.\n(* protect x y *)\nmove=> x y hstep /=. inversion hstep; (try discriminate); subst; rewrite /=.\ninversion H; (try discriminate); subst. by constructor.\nQed.\n\nLemma preservation_without_semantic_spec : forall VGamma AGamma s ov d s',\ntype_cmd VGamma AGamma s.(scmd) ->\nbuild_state_instr_spec s ov d s' -> \ntype_cmd VGamma AGamma s'.(scmd).\nProof.\nmove=> VGamma AGamma [] c r m ms ov d s' /= hty hnext.\ncase: c hty hnext=> //=.\n+ move=> hty hnext. by inversion hnext; (try discriminate); subst.\nmove=> i c hi hnext. \ncase:i hi hnext=> //=.\n+ move=> hi hnext. inversion hnext; (try discriminate); subst; rewrite /=.\n  by inversion hi; (try discriminate); subst.\n+ move=> x d' e hi hnext. inversion hnext; (try discriminate); subst; rewrite /=.\n  by inversion hi; (try discriminate); subst.\n+ move=> x d' a hi hnext. inversion hnext; (try discriminate); subst; rewrite /=.\n  by inversion hi; (try discriminate); subst.\n+ move=> a d' e hi hnext. inversion hnext; (try discriminate); subst; rewrite /=.\n  by inversion hi; (try discriminate); subst.\n+ move=> b i i' hi hnext. inversion hnext; (try discriminate); subst; rewrite /=.\n  inversion hi; (try discriminate); subst. inversion H1; (try discriminate); subst.\n  apply type_concat=> //=. by case: ifP.\nmove=> x y hi hnext. inversion hnext; (try discriminate); subst; rewrite /=.\nby inversion hi; (try discriminate); subst.\nQed.\n\nLemma declassify_mem_to_leakages : forall VGamma AGamma c,\ntype_cmd VGamma AGamma c -> \n(forall s1 s2 ov ls1 ls2 ds, \n   c = s1.(scmd) ->\n   state_equiv_spec s1 s2 VGamma AGamma ->\n   build_c_leakage_spec s1 ov ds ls1 ->\n   build_c_leakage_spec s2 ov ds ls2 ->\n   ls1 = ls2).\nProof.\nmove=> VGamma AGamma c hty.\nmove=> [] c1 r1 m1 ms1 [] c2 r2 m2 ms2 ov ls1 ls2 ds hc hequiv /=; subst. \nmove: hequiv=> [] /= hst /= hms hr hm; subst. rewrite /= in hty.\nmove: c2 r1 m1 r2 m2 ls1 ls2 ds ms2 hm hr hty.\ninduction ov.\n(* ov = [::] *)\n+ move=> c2 r1 m1 r2 m2 ms2 hm hr hty.\n  case: c2 hm hr hty=> //=.\n  + move=> ls1 ls2 ds hm hr hty h1 h2.\n    inversion h1; (try discriminate); subst. + by inversion h2; (try discriminate); subst.\n    + by inversion h2; (try discriminate); subst.\n  move=> i c ls1 ls2 ds hm hr hty h1 h2. inversion h1; (try discriminate); subst. \n  by inversion h2; (try discriminate); subst.\nmove=> c2 r1 m1 r2 m2 ls1 ls2 ds hm hr hty.\ncase: c2 hm hr hty=> /=.\n(* empty seq of instructions *)\n+ move=> hms hm hr hty h1 h2. inversion h1; (try discriminate); subst. by inversion h2; (try discriminate); subst.\n(* i :: c *)\nmove=> i c ms hm hr /= hty h1 h2; rewrite /=. have h1' := h1. have h2' := h2.\ninversion h1; (try discriminate); subst. inversion h2; (try discriminate); subst.\nhave heq : scmd {| scmd := i :: c; rmap := r1; mmap := m1; ms := ms |} = i :: c. + by auto.\nhave heq' : i :: c = scmd {| scmd := i :: c; rmap := r1; mmap := m1; ms := ms |}. + by auto.\nhave hequiv : state_equiv_spec {| scmd := i :: c; rmap := r1; mmap := m1; ms := ms |}\n              {| scmd := i :: c; rmap := r2; mmap := m2; ms := ms |} VGamma AGamma.\n+ apply st_equiv_spec; by auto.\nhave hsteq := step_declassify_state_equiv_spec.\nmove: (hsteq VGamma AGamma (i::c) {| scmd := i :: c; rmap := r1; mmap := m1; ms := ms |}\n{| scmd := i :: c; rmap := r2; mmap := m2; ms := ms |} d a s' s'0 hty heq hequiv H9 H12)=> hequiv'.\nmove: hequiv'=> [] hst hms hr' hm'. rewrite -heq in hty.\nhave hty' := preservation_without_semantic_spec hty H9. \ncase: s' H9 H10 hm' hst hms hr' hty'=> s1' r1' m1' ms1' H9 /= H10 /= hm' hst hms /= hr' hty'; subst. \ncase: s'0 H9 H10 H12 H13 hm' hr' hty'=> s2' r2' m2' ms2' H9 H10 H12 H13 /= hm' /= hr' hty'; subst. rewrite /= in H9.\nmove: (IHov s2' r1' m1' r2' m2' ls ls0 ds0 ms2' hm' hr' hty' H10 H13)=> ->. \nby have -> := declassify_mem_to_leakage_spec hty a heq' hequiv.\nQed.\n\nLemma declassify_to_leakage_c : forall VGamma AGamma c,\ntype_cmd VGamma AGamma c ->\n(forall s1 s1' n d l, \n c = s1.(scmd) ->\n multi_step_spec s1 d l n s1' -> \n build_c_leakage_spec s1 (extract_declassify_leakagess_spec l) d l).\nProof.\nmove=> VGamma AGamma c /= hty.\nmove=> [] c1 r1 m1 ms1 s1' n d l hc hmulti; subst. \nmove: c1 r1 m1 ms1 s1' d l hmulti hty.\ninduction n.\n(* n = 0 *)\n+ move=> c1 r1 m1 ms1 s1' d l hmulti hty /=.\n  (* 0 step means s1 = s1' and no leakage [::] *)\n  inversion hmulti; (try discriminate); subst; rewrite /=.\n  + case: c1 hmulti hty. + move=> hmulti hty. by constructor.\n  move=> i c hmulti hty. by constructor.\n  by case: (n) H=> //=.\n(* n != 0 *)\nmove=> c1 r1 m1 ms1 s1' d l hmulti hty.\nrewrite -addn1 in hmulti. \ninversion hmulti; (try discriminate); subst.\n(* empty leakage *)\n+ by case: n H3 IHn hmulti=> //=.\n(* non-empty leakage *)\ncase: c1 hty hmulti H0=> //=.\n(* empty seq of instructions *)\n+ move=> hty hmulti hsem.\n  inversion hmulti; (try discriminate); subst.\n  by inversion H8; (try discriminate); subst.\n(* i :: c *)\nmove=> i c hty hmulti H0 /=.\ninversion hmulti; (try discriminate); subst.\napply PeanoNat.Nat.add_cancel_r in H; rewrite H in H4.\napply PeanoNat.Nat.add_cancel_r in H8 ; subst.\nhave heq : i :: c = {| scmd := i :: c; rmap := r1; mmap := m1; ms := ms1 |}.(scmd). + by auto.\nhave heq' : {| scmd := i :: c; rmap := r1; mmap := m1; ms := ms1 |}.(scmd) = i :: c. + by auto.\nhave hnext : build_state_instr_spec {| scmd := i :: c; rmap := r1; mmap := m1; ms := ms1 |} \n                   (extract_declassify_leakages_spec l0) d0 s'0.\n+ by have := step_to_build_state_spec H9. \nhave hi := declassify_to_leakage_i_spec heq H9.\nrewrite heq in hty.\nhave hty' := preservation_without_semantic_spec hty hnext.\napply build_leakage_seq_c_vs with s'0.\n+ by apply hi.\n+ by apply hnext.\ncase: s'0 H9 H10 hnext hty'=> //= s2 r2 m2 ms H9 H10 hnext hty'.\nby move: (IHn s2 r2 m2 ms s1' d' l' H10 hty').\nQed.\n\nLemma type_declassify_ct_to_ct_spec : forall VGamma AGamma s1 s2,\ntype_cmd VGamma AGamma s1.(scmd) /\\ constant_time_declassify_spec VGamma AGamma s1 s2 ->\nconstant_time_spec VGamma AGamma s1 s2.\nProof.\nmove=> VGamma AGamma s1 s2 hty. rewrite /constant_time_spec /=.\ncase: hty=> [] hty hdeclassify. rewrite /constant_time_declassify_spec in hdeclassify.\nmove=> s1' s2' d l1 l2 n hequiv hmulti hmulti'.\nmove: (hdeclassify s1' s2' d l1 l2 n hequiv hmulti hmulti')=> [] hdeq hsafe {hdeclassify}.\nsplit; last by split=> //= hst; apply safe_lang.\nmove: s1 s2 d l1 l2 hmulti hmulti' hequiv hty hdeq.\ninduction n.\n(* n = 0 *)\n+ move=> s1 s2 d l1 l2 hmulti hmulti' hequiv hty hdeq.\n  inversion hmulti; (try discriminate); subst.\n  inversion hmulti'; (try discriminate); subst; auto.\n  by case:(n) H.\nmove=> s1 s2 d l1 l2 hmulti hmulti' hequiv hty hdeq. \ninversion hmulti; (try discriminate); subst.\ninversion hmulti'; (try discriminate); subst; auto.\nhave hd:= declassify_to_leakage_i_spec. have heq : forall s, scmd s = scmd s. + by auto.\nmove: (hd s1 s' d0 l (scmd s1) (heq s1) H0)=> <- /=.\nhave hequiv' := hequiv.\ncase: hequiv=> [] hst hms hr hm. rewrite hst in hty.\nmove: (hd s2 s'0 d0 l0 (scmd s2) (heq s2) H7)=> <- /=.\ncase: hdeq=> hd1 hds1. rewrite hd1.\nrewrite addn1 in H5. case: H5=> h1; subst.\nrewrite addn1 in H. case: H=> h; subst.\nhave hequiv'' := step_declassify_state_equiv_spec hty hst hequiv'.\nhave hs1eq := step_to_build_state_spec H0. rewrite hd1 in hs1eq.\nhave hs2eq := step_to_build_state_spec H7. \nrewrite -hst in hty.\nhave hty' := preservation hty H0.\nmove: (hequiv'' d0 (extract_declassify_leakages_spec l0) s' s'0 hs1eq hs2eq)=> {hequiv''} hequiv''. \nmove: (IHn s' s'0 d' l' l'0 H4 H9 hequiv'' hty' hds1)=> ->.\nby have -> := declassify_mem_to_leakage_spec hty (extract_declassify_leakages_spec l0) (heq s1) hequiv'.\nQed.\n\n\n\n\n", "meta": {"author": "swarnpriya", "repo": "simple_lang_sslh", "sha": "6d7172d1d61fe579d9045a9158d7aa1d46bbc1f8", "save_path": "github-repos/coq/swarnpriya-simple_lang_sslh", "path": "github-repos/coq/swarnpriya-simple_lang_sslh/simple_lang_sslh-6d7172d1d61fe579d9045a9158d7aa1d46bbc1f8/proofs_spec_declassify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376236, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.21162564196765588}}
{"text": "Require Import Util IL RenamedApart LabelsDefined OptionR.\nRequire Import Annotation Exp SetOperations Liveness.Liveness Restrict.\n\nSet Implicit Arguments.\n\nLemma plus_minus_eq n m\n  : n + m - n = m.\nProof.\n  omega.\nQed.\n\nLtac inv_get_step_some_minus :=\n  match goal with\n  | [ H : get (?f ⊝ (?g1 ⊝ ?A) \\\\ (?g2 ⊝ ?B) ++ ?C) ?k _,\n          H' : get ?A ?k _ |- _ ] =>\n    eapply get_app_lt_1 in H; [| eauto 20 with len]\n  | [ H : get (?f ⊝ (?g1 ⊝ ?A) \\\\ (?g2 ⊝ ?B) ++ ?C) ?k _,\n          H' : get ?B ?k _ |- _ ] =>\n    eapply get_app_lt_1 in H; [| eauto 20 with len]\n  | [ H : get (?f ⊝ (?g1 ⊝ ?A) \\\\ (?g2 ⊝ ?B) ++ ?C) (❬?B❭ + ?n) _ |- _ ] =>\n    let LENEQ := fresh \"LenEq\" in\n    assert (LENEQ:❬f ⊝ (g1 ⊝ A) \\\\ (g2 ⊝ B)❭ = ❬B❭) by eauto with len;\n    rewrite get_app_ge in H;\n    [ rewrite LENEQ in H; rewrite plus_minus_eq in H\n    | rewrite LENEQ; omega]\n  | [ H : get (?f ⊝ (?g1 ⊝ ?A) \\\\ (?g2 ⊝ ?B) ++ ?C) (❬?A❭ + ?n) _ |- _ ] =>\n    let LENEQ := fresh \"LenEq\" in\n    assert (LENEQ:❬f ⊝ (g1 ⊝ A) \\\\ (g2 ⊝ B)❭ = ❬A❭) by eauto with len;\n    rewrite get_app_ge in H;\n    [ rewrite LENEQ in H; rewrite plus_minus_eq in H\n    | rewrite LENEQ; omega]\n  end.\n\nSmpl Add inv_get_step_some_minus : inv_get.\n\n(** * Definition of Coherence: [srd] *)\n\nInductive srd : list (option (set var)) -> stmt -> ann (set var) -> Prop :=\n| srdExp DL x e s lv al\n  : srd (restr (getAnn al \\ singleton x) ⊝ DL) s al\n    -> srd DL (stmtLet x e s) (ann1 lv al)\n| srdIf DL e s t lv als alt\n  : srd DL s als\n    -> srd DL t alt\n    -> srd DL (stmtIf e s t) (ann2 lv als alt)\n| srdRet e DL lv\n  : srd DL (stmtReturn e) (ann0 lv)\n| srdGoto DL lv G' f Y\n  : get DL (counted f) (Some G')\n    -> srd DL (stmtApp f Y) (ann0 lv)\n| srdLet DL F t lv als alt\n  : length F = length als\n    -> (forall n Zs a, get F n Zs -> get als n a ->\n                 srd (restr (getAnn a \\ of_list (fst Zs)) ⊝\n                            (Some ⊝ (getAnn ⊝ als) \\\\ (fst ⊝ F) ++ DL)) (snd Zs) a)\n    -> srd (Some ⊝ (getAnn ⊝ als) \\\\ (fst ⊝ F) ++ DL) t alt\n    -> srd DL (stmtFun F t) (annF lv als alt).\n\n\n(** ** Some monotonicity properties *)\n\nLemma srd_monotone (DL DL' : list (option (set var))) s a\n : srd DL s a\n   -> PIR2 (fstNoneOrR Equal) DL DL'\n   -> srd DL' s a.\nProof.\n  intros. general induction H; eauto using srd.\n  - econstructor.\n    eapply IHsrd; eauto. eapply restrict_subset; eauto.\n  - destruct (PIR2_nth H0 H); eauto; dcr. inv H3.\n    econstructor; eauto.\n  - econstructor; eauto.\n    + intros. eapply H1; eauto.\n      repeat rewrite List.map_app.\n      eapply PIR2_app; eauto.\n      eapply restrict_subset; eauto.\n    + eapply IHsrd. eapply PIR2_app; eauto.\nQed.\n\nLemma srd_monotone2 (DL DL' : list (option (set var))) s a\n : srd DL s a\n   -> PIR2 (fstNoneOrR (flip Subset)) DL DL'\n   -> srd DL' s a.\nProof.\n  intros. general induction H; eauto using srd.\n  - econstructor.\n    eapply IHsrd; eauto. eapply restrict_subset2; eauto.\n  - destruct (PIR2_nth H0 H); eauto; dcr. inv H3.\n    econstructor; eauto.\n  - econstructor; eauto.\n    + intros. eapply H1; eauto.\n      repeat rewrite List.map_app.\n      eapply PIR2_app; eauto.\n      eapply restrict_subset2; eauto.\n    + eapply IHsrd. eapply PIR2_app; eauto.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Coherence/Coherence.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.21162563907245743}}
{"text": "Set Primitive Projections.\n\nAxiom I : Set.\nAxiom O : I -> SProp.\nDefinition ℙ := forall i : I, O i.\n\nInductive seq {A : Type} (x : A) : A -> SProp := srefl : @seq A x x.\n\nAxiom uip : forall A (x y : A), seq x y -> x = y.\nAxiom uip₀ : forall A (x y : A) (p q : x = y), p = q.\n\nAxiom sfunext : forall (A : SProp) (B : A -> Type) (f g : forall x, B x),\n  (forall x, f x = g x) -> f = g.\nAxiom funext : forall A (B : A -> Type) (f g : forall x, B x),\n  (forall x, f x = g x) -> f = g.\nAxiom pi : forall (A : Prop) (p q : A), p = q.\n\nRecord isSheaf (A : Type) := {\n  shf_elt : forall i : I, (O i -> A) -> A;\n  shf_spc : forall i (x : A), x = shf_elt i (fun _ => x);\n}.\n\nArguments shf_elt {_}.\nArguments shf_spc {_}.\n\nModule Import Sh.\n\nPrivate Inductive Shf (A : Type) :=\n| ret : A -> Shf A\n| ask : forall i, (O i -> Shf A) -> Shf A.\n\nArguments ret {_}.\nArguments ask {_}.\n\nAxiom eqn : forall {A} (i : I) (x : Shf A), ask i (fun _ => x) = x.\n\nFixpoint Shf_rect (A : Type) (P : Shf A -> Type)\n  (ur : forall (x : A), P (ret x))\n  (ua : forall (i : I) (k : O i -> Shf A),\n    (forall o : O i, P (k o)) -> P (ask i k))\n  (ue : forall (i : I) (x : Shf A) (px : P x),\n    match eqn i x in _ = e return P e with eq_refl => ua i (fun _ => x) (fun _ => px) end = px)\n  (x : Shf A) {struct x} :\n  P x :=\nmatch x with\n| ret x => ur x\n| ask i k => ua i k (fun o => Shf_rect A P ur ua ue (k o))\nend.\n\nFixpoint Shf_sind (A : Type) (P : Shf A -> SProp)\n  (ur : forall (x : A), P (ret x))\n  (ua : forall (i : I) (k : O i -> Shf A),\n    (forall o : O i, P (k o)) -> P (ask i k))\n  (x : Shf A) {struct x} :\n  P x :=\nmatch x with\n| ret x => ur x\n| ask i k => ua i k (fun o => Shf_sind A P ur ua (k o))\nend.\n\nEnd Sh.\n\nInductive Shε {A} : (ℙ -> A) -> SProp :=\n| retε : forall x : A, Shε (fun _ => x)\n| askε : forall (i : I) (k : O i -> ℙ -> A),\n  (forall o, Shε (k o)) -> Shε (fun α => k (α i) α)\n.\n\nDefinition eval {A} (x : Shf A) (α : ℙ) : A.\nProof.\nunshelve refine (\nShf_rect A (fun _ => A) (fun x => x) (fun i k r => r (α i)) _ x\n).\n{ clear; intros; destruct eqn; reflexivity. }\nDefined.\n\nLemma evalε : forall A (x : Shf A), Shε (eval x).\nProof.\nintros A x.\nsimple refine (\nShf_sind A (fun x => Shε (eval x)) _ _ x\n); clear x; simpl.\n+ intros x.\n  apply (retε x).\n+ intros i k kε.\n  apply (askε i (fun o => eval (ask i k))).\n  apply kε.\nQed.\n\nLemma eval_retract : forall A (x : Shf A) (α : ℙ),\n  ret (eval x α) = x.\nProof.\nintros A x α.\napply uip.\nrefine (\nShf_sind A (fun x => seq (ret (eval x α)) x) _ _ x\n); clear x; simpl.\n+ reflexivity.\n+ intros i k r.\n  change (eval (ask i k) α) with (eval (k (α i)) α).\n  change k with (fun _ : O i => k (α i)) at 2.\n  rewrite eqn.\n  apply r.\nQed.\n\nSection Permut.\n\nVariable A : Type.\nVariable i j : I.\nVariable k : O i -> O j -> Shf A.\n\nLemma permut_equiv :\n  ask i (fun o => ask j (fun q => k o q)) = ask j (fun q => ask i (fun o => k o q)).\nProof.\nmatch goal with [ |- ?p = ?q ] => rewrite <- (eqn i q) end.\nf_equal; apply sfunext; intros o.\nf_equal; apply sfunext; intros q.\nchange (fun o' => k o' q) with (fun _ : O i => k o q).\nrewrite eqn; reflexivity.\nQed.\n\nEnd Permut.\n\nInductive inhabited (A : Type) : SProp := inhabits : A -> inhabited A.\n\nDefinition unique_choice :=\n  forall (A : Type) (hA : forall x y : A, x = y), inhabited A -> A.\n\nDefinition choice := forall (A : Type), inhabited A -> A.\n\nSection WithChoice.\n\nVariable AC : choice.\n\nDefinition sreify {A : Type} (x : ℙ -> A) (xε : Shε x) :\n  inhabited {x₀ : Shf A | eval x₀ = x }.\nProof.\ninduction xε.\n+ constructor.\n  exists (ret x); reflexivity.\n+ constructor.\n  unshelve eexists.\n  - refine (ask i (fun o => _)).\n    specialize (H o).\n    apply AC in H.\n    destruct H as [x₀ Hx].\n    exact x₀.\n  - simpl.\n    apply sfunext; intros α.\n    match goal with [ |- context [ask i ?k ] ] =>\n      change k with (fun _ : O i => k (α i))\n    end; simpl.\n    rewrite eqn.\n    destruct AC.\n    rewrite e; reflexivity.\nDefined.\n\nDefinition reify {A : Type} (x : ℙ -> A) (xε : Shε x) :=\n  proj1_sig (AC _ (@sreify A x xε)).\n\nLemma eval_reify : forall (A : Type) (x : ℙ -> A) (xε : Shε x),\n  eval (reify x xε) = x.\nProof.\nintros A x xε.\nunfold reify.\ndestruct AC as [y hy]; simpl; assumption.\nQed.\n\nLemma reify_eval : forall (A : Type) (x : Shf A),\n  reify (eval x) (evalε _ x) = x.\nProof.\nintros A x.\napply uip.\nsimple refine (\nShf_sind A (fun x => seq (reify (eval x) (evalε A x)) x) _ _ x\n); clear x; simpl.\n+ intros x.\n  unfold reify.\n  destruct AC as [y hy]; simpl in *.\n  \nAbort.\n\nEnd WithChoice.\n\nLemma unique_eval_ret : forall A (p : Shf A) (x : A),\n  eval p = (fun _ : ℙ => x) -> p = ret x.\nProof.\nintros A p x e.\napply uip.\nrevert x e.\nrefine (Shf_sind A (fun p => forall x, eval p = (fun _ => x) -> seq p (ret x)) _ _ p); clear p.\n+ intros x₀ x e.\n  unfold eval in e.\n  cbn in *.\nAdmitted.\n\nLemma unique_eval_inv : forall A (x : ℙ -> A) (xε : Shε x)\n  (p q : {x₀ : Shf A | eval x₀ = x }), p = q.\nProof.\nintros A x xε [p hp] [q hq].\ncut (p = q).\n+ intros e; revert hq; destruct e; intros hq.\n  assert (e : hp = hq) by apply uip₀.\n  destruct e; reflexivity.\n+ apply uip.\n  revert p x xε hp q hq.\n  refine (Shf_sind A _ _ _).\n  - intros x₀ x xε hp q hq.\n    compute in hp.\n    revert q x₀ x xε hp hq.\n    refine (Shf_sind A _ _ _).\n    * intros x₁ x₂ x xε hp hq.\n      compute in hq.\n      revert x₁ x₂ hp hq.\n      induction xε; intros x₁ x₂ hp hq.\n      \n\nAdmitted.\n\nDefinition sreify {A : Type} {U : unique_choice} (x : ℙ -> A) (xε : Shε x) :\n  inhabited {x₀ : Shf A | eval x₀ = x }.\nProof.\ninduction xε.\n+ constructor.\n  exists (ret x); reflexivity.\n+ constructor.\n  unshelve eexists.\n  - refine (ask i (fun o => _)).\n    specialize (H o).\n    apply U in H; [|intros; apply unique_eval_inv, s].\n    destruct H as [x₀ Hx].\n    exact x₀.\n  - simpl.\n    apply sfunext; intros α.\n    match goal with [ |- context [ask i ?k ] ] =>\n      change k with (fun _ : O i => k (α i))\n    end; simpl.\n    rewrite eqn.\n    destruct U.\n    rewrite e; reflexivity.\nQed.\n", "meta": {"author": "ppedrot", "repo": "vitef", "sha": "695b0ac92de8911872d60834f6dcee5034fa88dc", "save_path": "github-repos/coq/ppedrot-vitef", "path": "github-repos/coq/ppedrot-vitef/vitef-695b0ac92de8911872d60834f6dcee5034fa88dc/sheaves/strict.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.21162563792720684}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Import approx_star0.\n\n\nLemma extensional_cantest {p} : forall a, extensional_op (@NCan p (NCanTest a)).\nProof.\n  introv Hpra Hprt Hprt' Hcv Has Hi.\n  applydup @compute_decompose_aux in Hcv; auto; exrepnd.\n\n  repndors; exrepnd; [|allsimpl; subst; repnd; complete ginv].\n\n  assert (m <= S k) as XX by omega.\n  repnud Hcv.\n  eapply reduces_atmost_split in XX; eauto.\n  remember (S k - m) as skm.\n  destruct skm; [omega|].\n  assert (skm <= k) by (subst; omega).\n  apply reduces_atmost_S in XX; exrepnd.\n  applydup @reduces_atmost_preserves_program in Hcv4; auto.\n  allapply @isprogram_cantest_implies; exrepnd; subst; cpx.\n\n  unfold lblift_sub in Has; simpl in Has; repnd; GC.\n  repeat(approxrelbtd); show_hyps.\n  allapply @approx_star_bterm_nobnd2.\n\n  apply no_change_after_val_like with (k2:=k) in Hcv3; auto; [].\n  make_red_val_like Hcv3 h1.\n  apply (Hi _ _ a2) in h1; auto; prove_isprogram;[].\n\n  extensional_ind XX0 k hh.\n\n  dorn Hcv0.\n\n  - apply iscan_implies in Hcv0; repndors; exrepnd; subst;\n    csunf XX1; allsimpl; ginv.\n\n    { apply (Hi _ _ (if canonical_form_test_for a c1 then b0 else c0)) in hh;\n        auto; prove_isprogram;\n        try (complete (destruct (canonical_form_test_for a c1); auto));\n        eauto 2 with slow.\n      apply howe_lemma2 in h1; exrepnd; auto; prove_isprogram.\n\n      apply @approx_star_open_trans with (b := if canonical_form_test_for a c1 then b0 else c0); auto.\n      apply approx_implies_approx_open.\n      apply @approx_trans with (b := oterm (NCan (NCanTest a)) [nobnd (oterm (Can c1) lbt'),nobnd b0,nobnd c0]).\n      apply reduces_to_implies_approx_eauto; prove_isprogram.\n      apply reduces_to_if_step; reflexivity.\n      apply reduces_to_implies_approx_eauto; prove_isprogram.\n      apply reduces_to_prinarg; auto; destruct h0; auto.\n    }\n\n    { apply howe_lemma2_seq in h1; exrepnd; auto.\n      apply (Hi _ _ c0) in hh; auto.\n      eapply approx_star_open_trans;[exact hh|clear hh].\n      apply approx_implies_approx_open.\n      apply reduces_to_implies_approx_eauto; prove_isprogram.\n      eapply reduces_to_trans;[apply reduces_to_prinarg;eauto|].\n      apply reduces_to_if_step.\n      csunf; simpl; auto.\n    }\n\n  - apply isexc_implies in Hcv0; auto; exrepnd; subst.\n    csunf XX1; allsimpl; ginv.\n    apply reduces_atmost_exc in XX0; subst.\n    apply howe_lemma2_exc in h1; exrepnd; auto; prove_isprogram.\n\n    apply @approx_star_open_trans with (b := mk_exception a' e').\n    apply approx_star_exception; auto.\n    apply approx_implies_approx_open.\n    apply computes_to_exception_implies_approx; auto; prove_isprogram.\n    allrw @computes_to_exception_as_reduces_to.\n    apply @reduces_to_trans with (b := oterm (NCan (NCanTest a)) [nobnd (mk_exception a' e'),nobnd b0,nobnd c0]).\n    apply reduces_to_prinarg; auto.\n    apply reduces_to_if_step; reflexivity.\nQed.\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"../util/\" \"../terms/\" \"../computation/\")\n*** End:\n*)\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/cequiv/extensional_cantest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.21162563617725869}}
{"text": "From Perennial.program_proof.mvcc Require Import\n     txn_prelude\n     txnmgr_repr tuple_repr index_proof wrbuf_repr.\n\nSection repr.\nContext `{!heapGS Σ, !mvcc_ghostG Σ}.\n\nDefinition own_txn_impl (txn : loc) (wrbuf : loc) (ts : nat) γ : iProp Σ :=\n  ∃ (tid sid : u64) (idx txnmgr : loc) (p : proph_id),\n    \"Htid\" ∷ txn ↦[Txn :: \"tid\"] #tid ∗\n    (* This ensures we do not lose the info that [tid] does not overflow. *)\n    \"%Etid\" ∷ ⌜int.nat tid = ts⌝ ∗\n    \"Hsid\" ∷ txn ↦[Txn :: \"sid\"] #sid ∗\n    \"%HsidB\" ∷ ⌜(int.Z sid) < N_TXN_SITES⌝ ∗\n    \"Hwrbuf\"    ∷ txn ↦[Txn :: \"wrbuf\"] #wrbuf ∗\n    \"#Hidx\" ∷ readonly (txn ↦[Txn :: \"idx\"] #idx) ∗\n    \"#HidxRI\" ∷ is_index idx γ ∗\n    \"#Htxnmgr\" ∷ readonly (txn ↦[Txn :: \"txnMgr\"] #txnmgr) ∗\n    \"#HtxnmgrRI\" ∷ is_txnmgr txnmgr γ ∗\n    \"Hactive\" ∷ active_tid γ tid sid ∗\n    \"#Hp\" ∷ readonly (txnmgr ↦[TxnMgr :: \"p\"] #p) ∗\n    \"#Hinv\" ∷ mvcc_inv_sst γ p ∗\n    \"_\" ∷ True.\n\n(* TODO: Unify [own_txn] and [own_txn_ready]. *)\nDefinition own_txn (txn : loc) (ts : nat) (view : dbmap) γ τ : iProp Σ :=\n  ∃ (wrbuf : loc) (mods : dbmap),\n    \"Himpl\"     ∷ own_txn_impl txn wrbuf ts γ ∗\n    \"#Hltuples\" ∷ ([∗ map] k ↦ v ∈ view, ltuple_ptsto γ k v ts) ∗\n    \"Htxnmap\"   ∷ txnmap_auth τ (mods ∪ view) ∗\n    \"%Hmodsdom\" ∷ ⌜dom mods ⊆ dom view⌝ ∗\n    \"HwrbufRP\"  ∷ own_wrbuf_xtpls wrbuf mods.\n\nDefinition own_txn_ready (txn : loc) (ts : nat) (view : dbmap) γ τ : iProp Σ :=\n  ∃ (wrbuf : loc) (mods : dbmap) (tpls : gmap u64 loc),\n    \"Himpl\"     ∷ own_txn_impl txn wrbuf ts γ ∗\n    \"#Hltuples\" ∷ ([∗ map] k ↦ v ∈ view, ltuple_ptsto γ k v ts) ∗\n    \"Htxnmap\"   ∷ txnmap_auth τ (mods ∪ view) ∗\n    \"%Hmodsdom\" ∷ ⌜dom mods ⊆ dom view⌝ ∗\n    \"HwrbufRP\"  ∷ own_wrbuf wrbuf mods tpls ∗\n    \"Htuples\"   ∷ own_tuples_locked ts tpls γ.\n\n(* TODO: Unify [own_txn_impl] and [own_txn_uninit]. *)\nDefinition own_txn_uninit (txn : loc) γ : iProp Σ := \n  ∃ (tid sid : u64) (wrbuf : loc) (idx txnmgr : loc) (p : proph_id) (mods : dbmap),\n    \"Htid\" ∷ txn ↦[Txn :: \"tid\"] #tid ∗\n    \"Hsid\" ∷ txn ↦[Txn :: \"sid\"] #sid ∗\n    \"%HsidB\" ∷ ⌜(int.Z sid) < N_TXN_SITES⌝ ∗\n    \"Hwrbuf\" ∷ txn ↦[Txn :: \"wrbuf\"] #wrbuf ∗\n    \"HwrbufRP\" ∷ own_wrbuf_xtpls wrbuf mods ∗\n    \"#Hidx\" ∷ readonly (txn ↦[Txn :: \"idx\"] #idx) ∗\n    \"#HidxRI\" ∷ is_index idx γ ∗\n    \"#Htxnmgr\" ∷ readonly (txn ↦[Txn :: \"txnMgr\"] #txnmgr) ∗\n    \"#HtxnmgrRI\" ∷ is_txnmgr txnmgr γ ∗\n    \"#Hp\" ∷ readonly (txnmgr ↦[TxnMgr :: \"p\"] #p) ∗\n    \"#Hinv\" ∷ mvcc_inv_sst γ p ∗\n    \"_\" ∷ True.\n\nEnd repr.\n\n#[global]\nHint Extern 1 (environments.envs_entails _ (own_txn_impl _ _ _ _)) => unfold own_txn_impl : core.\n#[global]\nHint Extern 1 (environments.envs_entails _ (own_txn _ _ _ _ _)) => unfold own_txn : core.\n#[global]\nHint Extern 1 (environments.envs_entails _ (own_txn_ready _ _ _ _ _)) => unfold own_txn_ready : core.\n#[global]\nHint Extern 1 (environments.envs_entails _ (own_txn_uninit _ _)) => unfold own_txn_uninit : core.\n\nSection lemma.\nContext `{!heapGS Σ, !mvcc_ghostG Σ}.\n\nLemma own_txn_txnmap_ptsto_dom {txn ts view k v γ τ} :\n  own_txn txn ts view γ τ -∗\n  txnmap_ptsto τ k v -∗\n  ⌜k ∈ dom view⌝.\nProof.\n  iIntros \"Htxn Hptsto\".\n  iNamed \"Htxn\".\n  iDestruct (txnmap_lookup with \"Htxnmap Hptsto\") as \"%Hlookup\".\n  iPureIntro.\n  apply elem_of_dom_2 in Hlookup. set_solver.\nQed.\n\nLemma own_txn_impl_tid txn wrbuf ts γ :\n  own_txn_impl txn wrbuf ts γ -∗\n  ∃ (tid : u64), ⌜int.nat tid = ts⌝.\nProof. iIntros \"Htxn\". iNamed \"Htxn\". eauto. Qed.\n\nEnd lemma.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/mvcc/txn_repr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.21162064555047294}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Import approx_star0.\nRequire Import approx_star_abs.\n\n\nLemma nuprl_extensional_abs {p} :\n  forall x : opabs, @extensional_op p (Abs x).\nProof.\n  introv Hpra Hprt Hprt' Hcv Has Hi.\n  allfold (approx_starbts lib).\n  apply computes_to_val_like_in_max_k_steps_S in Hcv; exrepnd.\n  csunf Hcv1; allsimpl.\n  apply compute_step_lib_success in Hcv1; exrepnd; subst.\n  dup Hcv2 as fe1.\n  pose proof (approx_starbts_numvars lib (Abs x) lbt lbt' Has) as eqnum.\n  apply @found_entry_change_bs with (bs2 := lbt') in Hcv2; auto.\n  rename Hcv2 into fe2.\n\n  unfold extensional_op_ind in Hi.\n\n  apply Hi with (v := mk_instance vars lbt' rhs) in Hcv0; auto;\n  [ | complete (eapply isprogram_subst_lib; eauto;\n                apply isprogram_ot_iff in Hprt; repnd; auto)\n    | complete (eapply isprogram_subst_lib; eauto;\n                apply isprogram_ot_iff in Hprt'; repnd; auto)\n    | ]; clear Hi.\n\n  - apply @approx_star_open_trans with (b := mk_instance vars lbt' rhs); auto.\n    apply approx_implies_approx_open.\n    apply reduces_to_implies_approx_eauto; prove_isprogram.\n    apply reduces_to_if_step; simpl.\n    eapply compute_step_lib_success_change_bs; eauto.\n\n  - unfold correct_abs in correct;repnd.\n    eapply mk_instance_approx_star_congr; eauto; try (complete (intro xxx; ginv)).\n\n    + apply found_entry_implies_matching_entry in fe1.\n      unfold matching_entry in fe1; sp.\n\n    + apply found_entry_implies_matching_entry in fe2.\n      unfold matching_entry in fe2; sp.\nQed.\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"../util/\" \"../terms/\" \"../computation/\")\n*** End:\n*)\n\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/cequiv/extensional_abs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.21162064555047294}}
{"text": "Import EqNotations.\nFrom Perennial.Helpers Require Import Map.\nFrom Perennial.algebra Require Import auth_map liftable log_heap async.\nFrom Perennial.base_logic Require Import lib.mono_nat lib.ghost_map.\n\nFrom Goose.github_com.mit_pdos.go_journal Require Import jrnl.\nFrom Perennial.program_logic Require Export ncinv.\nFrom Perennial.program_proof Require Import buf.buf_proof addr.addr_proof obj.obj_proof.\nFrom Perennial.program_proof Require jrnl.jrnl_proof.\nFrom Perennial.program_proof Require Import disk_prelude.\nFrom Perennial.goose_lang.lib Require Import slice.typed_slice.\nFrom Perennial.goose_lang.ffi Require Import disk_prelude.\n\n(** * A more separation logic-friendly spec for jrnl\n\nOverview of resources used here:\n\ndurable_mapsto_own - durable, exclusive\ndurable_mapsto - durable but missing modify_token\njrnl_maps_to - ephemeral\n\nis_crash_lock (durable_mapsto_own) (durable_mapsto)\non crash: exchange durable_mapsto for durable_mapsto_own\n\nlift: move durable_mapsto_own into transaction and get jrnl_maps_to and durable_mapsto is added to is_jrnl\n\nis_jrnl P = is_jrnl_mem * is_jrnl_durable P\n\nreads and writes need jrnl_maps_to and is_jrnl_mem\n\nis_jrnl_durable P -* P (P is going to be durable_mapsto) (use this to frame out crash condition)\n\nexchange own_last_frag γ for own_last_frag γ' ∗ modify_token γ' (in sep_jrnl layer)\nexchange ephemeral_txn_val γ for ephemeral_txn_val γ' if the transaction id was preserved\n *)\n\n(* mspec is a shorthand for referring to the old \"map-based\" spec, since we will\nwant to use similar names in this spec *)\nModule mspec := jrnl.jrnl_proof.\n\nNotation versioned_object := ({K & (bufDataT K * bufDataT K)%type}).\n\nDefinition objKind (obj: object): bufDataKind := projT1 obj.\nDefinition objData (obj: object): bufDataT (objKind obj) := projT2 obj.\n\nClass jrnlG Σ :=\n  { jrnl_buffer_inG :> mapG Σ addr object;\n    jrnl_mspec_jrnlG :> mspec.jrnlG Σ;\n    jrnl_asyncG :> asyncG Σ addr object;\n  }.\n\nDefinition jrnlΣ : gFunctors :=\n  #[ mapΣ addr object; mspec.jrnlΣ; asyncΣ addr object ].\n\n#[global]\nInstance subG_jrnlΣ Σ : subG jrnlΣ Σ → jrnlG Σ.\nProof. solve_inG. Qed.\n\nRecord jrnl_names :=\n  { jrnl_txn_names : txn_names;\n    jrnl_async_name : async_gname;\n  }.\n\nSection goose_lang.\n  Context `{!jrnlG Σ}.\n  Context `{!heapGS Σ}.\n\n  Context (N:namespace).\n\n  Implicit Types (l: loc) (γ: jrnl_names) (γtxn: gname).\n  Implicit Types (obj: object).\n\n  Definition txn_durable γ txn_id :=\n    (* oof, this leaks all the abstractions *)\n    mono_nat_lb_own γ.(jrnl_txn_names).(txn_walnames).(heapspec.wal_heap_durable_lb) txn_id.\n\n\n  Definition txn_system_inv γ: iProp Σ :=\n    ∃ (σs: async (gmap addr object)),\n      \"H◯async\" ∷ ghost_var γ.(jrnl_txn_names).(txn_crashstates) (3/4) σs ∗\n      \"H●latest\" ∷ async_ctx γ.(jrnl_async_name) 1 σs\n  .\n\n  (* modify_token is an obligation from the jrnl_proof, which is how the txn\n  invariant keeps track of exclusive ownership over an address. This proof has a\n  more sophisticated notion of owning an address coming from the logical setup\n  in [async.v], but we still have to track this token to be able to lift\n  addresses into a transaction. *)\n  Definition modify_token γ (a: addr) : iProp Σ :=\n    ∃ obj, obj.invariant.mapsto_txn γ.(jrnl_txn_names) a obj.\n\n  Global Instance modify_token_conflicting γ T :\n    Conflicting (λ (l : addr) (_ : T), modify_token γ l).\n  Proof.\n    iIntros (a0 v0 a1 v1) \"H0 H1\".\n    iDestruct \"H0\" as (o0) \"H0\".\n    iDestruct \"H1\" as (o1) \"H1\".\n    iApply (mspec.mapsto_txn_conflicting with \"H0 H1\").\n  Qed.\n\n  (* The basic statement of what is in the logical, committed disk of the\n  transaction system.\n\n  Has three components: the value starting from some txn i, a token giving\n  exclusive ownership over transactions ≥ i, and a persistent witness that i is\n  durable (so we don't crash to before this fact is relevant). The first two are\n  grouped into [ephemeral_val_from]. *)\n  Definition durable_mapsto γ (a: addr) obj: iProp Σ :=\n    ∃ i, ephemeral_val_from γ.(jrnl_async_name) i a obj ∗\n         txn_durable γ i.\n\n  Global Instance durable_mapsto_conflicting γ :\n    Conflicting (λ a v, durable_mapsto γ a v).\n  Proof.\n    iIntros (a0 v0 a1 v1) \"H0 H1\".\n    iDestruct \"H0\" as (o0) \"[H0 _]\".\n    iDestruct \"H1\" as (o1) \"[H1 _]\".\n    destruct (decide (a0 = a1)); try done; subst.\n    iDestruct (ephemeral_val_from_conflict with \"H0 H1\") as \"H\". done.\n  Qed.\n\n  Definition durable_mapsto_own γ a obj: iProp Σ :=\n    modify_token γ a ∗ durable_mapsto γ a obj.\n\n  Global Instance durable_mapsto_own_discretizable γ a obj: Discretizable (durable_mapsto_own γ a obj).\n  Proof. apply _. Qed.\n\n  Definition crash_point γ logm crash_txn : iProp Σ :=\n    async_ctx γ.(jrnl_async_name) 1 logm ∗\n    ⌜(length (possible logm) >= crash_txn + 1)%nat⌝.\n\n  Definition txn_durable_exchanger γ txn_id :=\n    heapspec.heapspec_durable_exchanger γ.(jrnl_txn_names).(txn_walnames) txn_id.\n\n  Lemma txn_durable_exchanger_use γ n lb :\n    txn_durable_exchanger γ n -∗\n    txn_durable γ lb -∗\n    ⌜ (lb ≤ n)%nat ⌝.\n  Proof. iIntros. iApply (heapspec.heapspec_durable_exchanger_use with \"[$] [$]\"). Qed.\n\n  Definition token_exchanger (a:addr) crash_txn γ γ' : iProp Σ :=\n    (∃ i, async.own_last_frag γ.(jrnl_async_name) a i) ∨\n    (async.own_last_frag γ'.(jrnl_async_name) a crash_txn ∗ modify_token γ' a).\n\n  Definition ephemeral_txn_val_exchanger (a:addr) crash_txn γ γ' : iProp Σ :=\n    ∃ v, ephemeral_txn_val γ.(jrnl_async_name) crash_txn a v ∗\n         ephemeral_txn_val γ'.(jrnl_async_name) crash_txn a v.\n\n  Definition addr_exchangers {A} txn γ γ' (m : gmap addr A) : iProp Σ :=\n    ([∗ map] a↦_ ∈ m,\n        token_exchanger a txn γ γ' ∗\n        ephemeral_txn_val_exchanger a txn γ γ')%I.\n\n  Definition sep_txn_exchanger γ γ' : iProp Σ :=\n    ∃ logm crash_txn,\n       \"Hcrash_point\" ∷ crash_point γ logm crash_txn ∗\n       \"Hdurable_exchanger\" ∷ txn_durable_exchanger γ crash_txn ∗\n       \"#Hcrash_txn_durable\" ∷ txn_durable γ' crash_txn ∗\n       \"Hexchanger\" ∷ addr_exchangers crash_txn γ γ' (latest logm)\n  .\n\n  (* TODO: note that we don't promise γ'.(jrnl_txn_names).(txn_kinds) =\n  γ.(jrnl_txn_names).(txn_kinds), even though txn_cfupd_res has this fact *)\n  Definition txn_cinv γ γ' : iProp Σ :=\n    (□ |C={⊤}=> inv N (sep_txn_exchanger γ γ')) ∗\n    ⌜γ.(jrnl_txn_names).(txn_kinds) = γ'.(jrnl_txn_names).(txn_kinds)⌝.\n\n  (* this is for the entire txn manager, and relates it to some ghost state *)\n\n  Definition is_txn_system γ : iProp Σ :=\n    \"Htxn_inv\" ∷ ncinv N (txn_system_inv γ) ∗\n    \"His_txn\" ∷ ncinv invN (is_txn_always γ.(jrnl_txn_names)).\n\n  Definition is_txn_system_full γ γ' : iProp Σ :=\n    \"His_txn_system\" ∷ is_txn_system γ ∗\n    \"Htxn_cinv\" ∷ txn_cinv γ γ'.\n\n  (*\n  Lemma init_txn_system {E} l_txn γUnified dinit σs :\n    is_txn l_txn γUnified dinit ∗ ghost_var γUnified.(txn_crashstates) (3/4) σs ={E}=∗\n    ∃ γ, ⌜γ.(jrnl_txn_names) = γUnified⌝ ∗\n         is_txn_system γ.\n  Proof.\n    iIntros \"[#Htxn Hasync]\".\n    iMod (async_ctx_init σs) as (γasync) \"H●async\".\n    set (γ:={|jrnl_txn_names := γUnified; jrnl_async_name := γasync; |}).\n    iExists γ.\n    iMod (ncinv_alloc N E (txn_system_inv γ) with \"[-]\") as \"($&Hcfupd)\".\n    { iNext.\n      iExists _; iFrame. }\n    iModIntro.\n    simpl.\n    iSplit; first by auto.\n    iNamed \"Htxn\"; iFrame \"#\".\n  Qed.\n   *)\n\n\n  Definition is_jrnl_mem l γ dinit γtxn γdurable : iProp Σ :=\n    ∃ (mT: gmap addr versioned_object) anydirty,\n      \"#Htxn_system\" ∷ is_txn_system γ ∗\n      \"Hjrnl\" ∷ mspec.is_jrnl l mT γ.(jrnl_txn_names) dinit anydirty ∗\n      \"Htxn_ctx\" ∷ map_ctx γtxn 1 (mspec.modified <$> mT) ∗\n      \"%Hanydirty\" ∷ ⌜anydirty=false →\n                      mspec.modified <$> mT = mspec.committed <$> mT⌝ ∗\n      \"Hdurable\" ∷ map_ctx γdurable (1/2) (mspec.committed <$> mT)\n  .\n\n  (* To make work with 2PL:\n     Consider is_jrnl_mem' that has Hdurable removed and adds mT as an explicit parameter.\n     Right before commit, we\n     convert is_jrnl_mem' .. .. mT ∗ ([∗ map] a ↦ o ∈ mT durable_mapsto a o) into an is_jrnl. *)\n\n  (* Alternative is define is_jrnl_durable' mT which is just Hdurable and then prove that\n     from is_jrnl_mem ∗ ([∗ map] a ↦ o ∈ mT, durable_mapsto a o) ∗ is_jrnl_durable' mT\n     can be converted into an is_jrnl\n\n    This seems better.\n  *)\n\n  Definition is_jrnl_durable γ γdurable (P0 : (_ -> _ -> iProp Σ) -> iProp Σ) : iProp Σ :=\n    ∃ committed_mT,\n      \"Hdurable_frag\" ∷ map_ctx γdurable (1/2) committed_mT ∗\n      \"Hold_vals\" ∷ ([∗ map] a↦v ∈ committed_mT,\n                     durable_mapsto γ a v) ∗\n      \"#HrestoreP0\" ∷ □ (∀ mapsto,\n                         ([∗ map] a↦v ∈ committed_mT,\n                          mapsto a v) -∗\n                         P0 mapsto)\n  .\n\n  Definition is_jrnl l γ dinit γtxn P0 : iProp Σ :=\n    ∃ γdurable,\n      \"Hjrnl_mem\" ∷ is_jrnl_mem l γ dinit γtxn γdurable ∗\n      \"Hjrnl_durable\" ∷ is_jrnl_durable γ γdurable P0.\n\n  Global Instance: Params (@is_jrnl) 4 := {}.\n\n  Global Instance is_jrnl_durable_proper γ γdurable :\n    Proper (pointwise_relation _ (⊣⊢) ==> (⊣⊢)) (is_jrnl_durable γ γdurable).\n  Proof.\n    intros P1 P2 Hequiv.\n    rewrite /is_jrnl_durable.\n    setoid_rewrite Hequiv.\n    reflexivity.\n  Qed.\n\n  Global Instance is_jrnl_durable_mono γ γdurable :\n    Proper (pointwise_relation _ (⊢) ==> (⊢)) (is_jrnl_durable γ γdurable).\n  Proof.\n    intros P1 P2 Hequiv.\n    rewrite /is_jrnl_durable.\n    setoid_rewrite Hequiv.\n    reflexivity.\n  Qed.\n\n  Theorem is_jrnl_durable_wand γ γdurable P1 P2 :\n    is_jrnl_durable γ γdurable P1 -∗\n    □(∀ mapsto, P1 mapsto -∗ P2 mapsto) -∗\n    is_jrnl_durable γ γdurable P2.\n  Proof.\n    iIntros \"Htxn #Hwand\".\n    iNamed \"Htxn\".\n    iExists _; iFrame \"∗#%\".\n    iIntros (mapsto) \"!> Hm\".\n    iApply \"Hwand\". iApply \"HrestoreP0\". iFrame.\n  Qed.\n\n  Global Instance is_jrnl_proper l γ dinit γtxn :\n    Proper (pointwise_relation _ (⊣⊢) ==> (⊣⊢)) (is_jrnl l γ dinit γtxn).\n  Proof.\n    intros P1 P2 Hequiv.\n    rewrite /is_jrnl.\n    setoid_rewrite Hequiv.\n    done.\n  Qed.\n\n  Global Instance is_jrnl_mono l γ dinit γtxn :\n    Proper (pointwise_relation _ (⊢) ==> (⊢)) (is_jrnl l γ dinit γtxn).\n  Proof.\n    intros P1 P2 Hequiv.\n    rewrite /is_jrnl.\n    setoid_rewrite Hequiv.\n    done.\n  Qed.\n\n  Theorem is_jrnl_wand l γ dinit γtxn P1 P2 :\n    is_jrnl l γ dinit γtxn P1 -∗\n    □(∀ mapsto, P1 mapsto -∗ P2 mapsto) -∗\n    is_jrnl l γ dinit γtxn P2.\n  Proof.\n    iIntros \"Htxn #Hwand\".\n    iNamed \"Htxn\".\n    iDestruct (is_jrnl_durable_wand with \"Hjrnl_durable Hwand\") as \"Hjrnl_durable\".\n    iExists _; iFrame.\n  Qed.\n\n  Theorem is_jrnl_durable_to_old_pred γ γdurable P0 :\n    is_jrnl_durable γ γdurable P0 -∗ P0 (durable_mapsto γ).\n  Proof.\n    iNamed 1.\n    iApply \"HrestoreP0\". iFrame.\n  Qed.\n\n  Theorem is_jrnl_to_old_pred' l γ dinit γtxn γdurable committed_mT :\n    \"Hjrnl_mem\" ∷ is_jrnl_mem l γ dinit γtxn γdurable -∗\n    \"Hdurable_frag\" ∷ map_ctx γdurable (1/2) committed_mT -∗\n    \"Hold_vals\" ∷ ([∗ map] a↦v ∈ committed_mT, durable_mapsto γ a v) -∗\n    \"Hold_vals\" ∷ ([∗ map] a↦v ∈ committed_mT, durable_mapsto_own γ a v).\n  Proof.\n    iIntros \"???\".\n    iNamed.\n    iNamed \"Hjrnl_mem\".\n    iDestruct (map_ctx_agree with \"Hdurable_frag Hdurable\") as %->.\n    iApply big_sepM_sep. iFrame.\n    iDestruct (mspec.is_jrnl_to_committed_mapsto_txn with \"Hjrnl\") as \"Hmod\".\n    iApply (big_sepM_mono with \"Hmod\").\n    iIntros (k x Hkx) \"H\".\n    iExists _; iFrame.\n  Qed.\n\n  Theorem is_jrnl_to_old_pred l γ dinit γtxn P0 :\n    is_jrnl l γ dinit γtxn P0 -∗ P0 (durable_mapsto_own γ).\n  Proof.\n    iNamed 1.\n    iNamed \"Hjrnl_durable\".\n    iApply \"HrestoreP0\".\n    iApply (\n      is_jrnl_to_old_pred' with \"Hjrnl_mem Hdurable_frag Hold_vals\"\n    ).\n  Qed.\n\n  Definition jrnl_maps_to γtxn (a: addr) obj : iProp Σ :=\n     ptsto_mut γtxn a 1 obj.\n\n  (* TODO: prove this instance for ptsto_mut 1 *)\n  Global Instance jrnl_maps_to_conflicting γtxn :\n    Conflicting (jrnl_maps_to γtxn).\n  Proof.\n    rewrite /jrnl_maps_to.\n    iIntros (????) \"Ha1 Ha2\".\n    destruct (decide (a0 = a1)); subst; auto.\n    iDestruct (ptsto_conflict with \"Ha1 Ha2\") as %[].\n  Qed.\n\n  Definition object_to_versioned (obj: object): versioned_object :=\n    existT (objKind obj) (objData obj, objData obj).\n\n  Lemma committed_to_versioned obj :\n    mspec.committed (object_to_versioned obj) = obj.\n  Proof. destruct obj; reflexivity. Qed.\n\n  Lemma modified_to_versioned obj :\n    mspec.modified (object_to_versioned obj) = obj.\n  Proof. destruct obj; reflexivity. Qed.\n\n  Lemma durable_mapsto_mapsto_txn_agree' E γ a obj1 obj2 k q :\n    ↑N ⊆ E →\n    ↑invN ⊆ E →\n    N ## invN →\n    is_txn_system γ -∗\n    durable_mapsto γ a obj1 -∗\n    mapsto_txn γ.(jrnl_txn_names) a obj2 -∗\n    NC q -∗\n    |k={E}=> (⌜obj1 = obj2⌝ ∗ durable_mapsto γ a obj1 ∗ mapsto_txn γ.(jrnl_txn_names) a obj2) ∗ NC q.\n  Proof.\n    iIntros (???) \"#Hinv Ha_i Ha HNC\".\n    iNamed \"Hinv\".\n    iMod (ncinv_acc_k with \"His_txn [$]\") as \"(>Hinner1&HNC&Hclose1)\"; first by auto.\n    iMod (ncinv_acc_k with \"Htxn_inv [$]\") as \"(>Hinner2&HNC&Hclose2)\"; first by set_solver.\n    iAssert (⌜obj1 = obj2⌝)%I as %?; last first.\n    { iMod (\"Hclose2\" with \"[$] [$]\") as \"HNC\".\n      iMod (\"Hclose1\" with \"[$] [$]\") as \"HNC\".\n      iFrame. auto. }\n    iNamed \"Hinner1\".\n    iClear \"Hheapmatch Hcrashheapsmatch Hmetactx\".\n    iNamed \"Hinner2\".\n    iDestruct (ghost_var_agree with \"Hcrashstates [$]\") as %->.\n    iDestruct (mapsto_txn_cur with \"Ha\") as \"[Ha _]\".\n    iDestruct \"Ha_i\" as (i) \"[Ha_i _]\".\n    iDestruct (ephemeral_val_from_agree_latest with \"H●latest Ha_i\") as %Hlookup_obj.\n    iDestruct (ghost_map_lookup with \"Hlogheapctx [$]\") as %Hlookup_obj0.\n    iPureIntro.\n    congruence.\n  Qed.\n\n  Lemma durable_mapsto_mapsto_txn_agree E γ a obj1 obj2 :\n    ↑N ⊆ E →\n    ↑invN ⊆ E →\n    N ## invN →\n    is_txn_system γ -∗\n    durable_mapsto γ a obj1 -∗\n    mapsto_txn γ.(jrnl_txn_names) a obj2 -∗\n    |NC={E}=> ⌜obj1 = obj2⌝ ∗ durable_mapsto γ a obj1 ∗ mapsto_txn γ.(jrnl_txn_names) a obj2.\n  Proof.\n    iIntros (???) \"#Hinv Ha_i Ha\".\n    rewrite ncfupd_eq /ncfupd_def.\n    iIntros. iApply (fupd_level_fupd _ _ _ O).\n    iMod (durable_mapsto_mapsto_txn_agree' with \"[$] [$] [$] [$]\"); auto.\n  Qed.\n\n  Theorem is_jrnl_durable_not_in_map γ a obj γdurable P0 committed_mT :\n    durable_mapsto γ a obj -∗\n    is_jrnl_durable γ γdurable P0 -∗\n    map_ctx γdurable (1 / 2) committed_mT -∗\n    ⌜committed_mT !! a = None⌝.\n  Proof.\n    iIntros \"Ha Hdur Hctx\".\n    destruct (committed_mT !! a) eqn:He; try eauto.\n    iNamed \"Hdur\".\n    iDestruct (map_ctx_agree with \"Hctx Hdurable_frag\") as %->.\n    iDestruct (big_sepM_lookup with \"Hold_vals\") as \"Ha2\"; eauto.\n    iDestruct \"Ha\" as (i) \"[Ha _]\".\n    iDestruct \"Ha2\" as (i2) \"[Ha2 _]\".\n    iDestruct (ephemeral_val_from_conflict with \"Ha Ha2\") as \"H\".\n    done.\n  Qed.\n\n  Theorem lift_into_txn' E l γ dinit γtxn γdurable committed_mT a obj :\n    ↑N ⊆ E →\n    ↑invN ⊆ E →\n    N ## invN →\n    \"Hjrnl_mem\" ∷ is_jrnl_mem l γ dinit γtxn γdurable -∗\n    \"Hdurable_frag\" ∷ map_ctx γdurable (1/2) committed_mT -∗\n    \"Hdurable_maps_to\" ∷ durable_mapsto_own γ a obj -∗\n    |NC={E}=>\n    \"Hjrnl_maps_to\" ∷ jrnl_maps_to γtxn a obj ∗\n    \"Hjrnl_mem\" ∷ is_jrnl_mem l γ dinit γtxn γdurable ∗\n    \"Hdurable_frag\" ∷ map_ctx γdurable (1/2) (<[a:=obj]>committed_mT) ∗\n    \"Hdurable_maps_to\" ∷ durable_mapsto γ a obj ∗\n    \"%Hnew\" ∷ ⌜committed_mT !! a = None⌝.\n  Proof.\n    iIntros (HN HinvN HNdisj) \"? ? [Ha Ha_i]\".\n    iNamed.\n    iNamed \"Hjrnl_mem\".\n\n    iDestruct \"Ha\" as (obj0) \"Ha\".\n\n    iMod (durable_mapsto_mapsto_txn_agree with \"[$] Ha_i Ha\") as \"(%Heq & Ha_i & Ha)\";\n      [ solve_ndisj.. | subst obj0 ].\n\n    iDestruct (mspec.is_jrnl_not_in_map with \"Hjrnl Ha\") as %Hnotin.\n    assert ((mspec.modified <$> mT) !! a = None).\n    { rewrite lookup_fmap Hnotin //. }\n    assert ((mspec.committed <$> mT) !! a = None).\n    { rewrite lookup_fmap Hnotin //. }\n    iMod (mspec.Op_lift_one _ _ _ _ _ _ E with \"[$Ha $Hjrnl]\") as \"Hjrnl\"; auto.\n    iMod (map_alloc a obj with \"Htxn_ctx\") as \"[Htxn_ctx Ha]\"; eauto.\n\n    iDestruct (map_ctx_agree with \"Hdurable Hdurable_frag\") as %<-.\n    iCombine \"Hdurable Hdurable_frag\" as \"Hdurable\".\n    iMod (map_alloc a obj with \"Hdurable\") as \"[Hdurable _]\"; eauto.\n    iDestruct \"Hdurable\" as \"[Hdurable Hdurable_frag]\".\n\n    iModIntro.\n    iFrame \"Ha\".\n    iSplitR \"Hdurable_frag Ha_i\".\n    {\n      iExists (<[a:=object_to_versioned obj]> mT), anydirty.\n      iFrame \"Htxn_system\".\n      rewrite !fmap_insert committed_to_versioned modified_to_versioned.\n      iFrame.\n      iPureIntro. destruct anydirty; intuition congruence.\n    }\n    iFrame \"Hdurable_frag\".\n    iFrame \"∗ %\".\n  Qed.\n\n  Theorem lift_into_txn E l γ dinit γtxn P0 a obj :\n    ↑N ⊆ E →\n    ↑invN ⊆ E →\n    N ## invN →\n    is_jrnl l γ dinit γtxn P0 -∗\n    durable_mapsto_own γ a obj\n    -∗ |NC={E}=>\n    jrnl_maps_to γtxn a obj ∗\n    is_jrnl l γ dinit γtxn (λ mapsto, mapsto a obj ∗ P0 mapsto).\n  Proof.\n    iIntros (HN HinvN HNdisj) \"Hctx Hnew\".\n    iNamed \"Hctx\".\n    iNamed \"Hjrnl_durable\".\n    iDestruct (\n      lift_into_txn' _ _ _ _ _ _ _ _ _ HN HinvN HNdisj\n      with \"Hjrnl_mem Hdurable_frag Hnew\"\n    ) as \"> (?&?&?&?&?)\".\n    iNamed.\n    iFrame \"Hjrnl_maps_to\".\n    iExists _.\n    iFrame.\n    iExists _.\n    iFrame.\n\n    iModIntro.\n    iSplit.\n    {\n      iApply big_sepM_insert; first by assumption.\n      iFrame.\n    }\n    iModIntro.\n    iIntros (mapsto) \"H\".\n    iDestruct (big_sepM_insert with \"H\") as \"[Ha H]\"; eauto. iFrame.\n    iApply \"HrestoreP0\"; iFrame.\n  Qed.\n\n  Theorem lift_map_into_txn' E l γ dinit γtxn γdurable committed_mT m :\n    ↑invN ⊆ E →\n    ↑N ⊆ E →\n    N ## invN →\n    \"Hjrnl_mem\" ∷ is_jrnl_mem l γ dinit γtxn γdurable -∗\n    \"Hdurable_frag\" ∷ map_ctx γdurable (1/2) committed_mT -∗\n    \"Hm\" ∷ ([∗ map] a↦v ∈ m, durable_mapsto_own γ a v)\n    -∗ |NC={E}=>\n    \"Hjrnl_maps_to\" ∷ ([∗ map] a↦v ∈ m, jrnl_maps_to γtxn a v) ∗\n    \"Hjrnl_mem\" ∷ is_jrnl_mem l γ dinit γtxn γdurable ∗\n    \"Hdurable_frag\" ∷ map_ctx γdurable (1/2) (m ∪ committed_mT) ∗\n    \"Hdurable_mapstos\" ∷ ([∗ map] a↦v ∈ m, durable_mapsto γ a v) ∗\n    \"%Hall_new\" ∷ ⌜m ##ₘ committed_mT⌝.\n  Proof.\n    iIntros (???) \"???\".\n    iNamed.\n    iInduction m as [|a v m] \"IH\" using map_ind forall (committed_mT).\n    - setoid_rewrite big_sepM_empty.\n      rewrite !left_id.\n      iModIntro.\n      iFrame.\n      iPureIntro.\n      apply map_disjoint_empty_l.\n    - rewrite !big_sepM_insert //.\n      iDestruct \"Hm\" as \"[[Ha_mod Ha_dur] Hm]\".\n      iAssert (durable_mapsto_own γ a v) with \"[Ha_mod Ha_dur]\" as \"Ha\".\n      { iFrame. }\n      iMod (lift_into_txn' with \"Hjrnl_mem Hdurable_frag Ha\")\n        as \"(?&?&?&?&?)\"; [ solve_ndisj .. | ].\n      iNamed.\n      iMod (\"IH\" with \"Hjrnl_mem Hdurable_frag Hm\") as \"(?&?&?&?&?)\".\n      iNamed.\n      iModIntro.\n      rewrite -insert_union_r.\n      2: assumption.\n      rewrite insert_union_l.\n      iFrame.\n      iPureIntro.\n      apply map_disjoint_insert_r in Hall_new.\n      apply map_disjoint_insert_l_2; intuition.\n  Qed.\n\n  Theorem lift_map_into_txn E l γ dinit γtxn P0 m :\n    ↑invN ⊆ E →\n    ↑N ⊆ E →\n    N ## invN →\n    is_jrnl l γ dinit γtxn P0 -∗\n    ([∗ map] a↦v ∈ m, durable_mapsto_own γ a v)\n    -∗ |NC={E}=>\n    ([∗ map] a↦v ∈ m, jrnl_maps_to γtxn a v) ∗\n    is_jrnl l γ dinit γtxn (λ mapsto,\n      ([∗ map] a↦v ∈ m, mapsto a v) ∗ P0 mapsto\n    ).\n  Proof.\n    iIntros (???) \"Hctx Hm\".\n    iNamed \"Hctx\".\n    iNamed \"Hjrnl_durable\".\n    iMod (lift_map_into_txn' with \"Hjrnl_mem Hdurable_frag Hm\")\n      as \"(?&?&?&?&?)\"; [ solve_ndisj.. | ].\n    iNamed.\n    iModIntro.\n    iFrame \"Hjrnl_maps_to\".\n    iExists _.\n    iFrame \"Hjrnl_mem\".\n    iExists _.\n    iFrame \"Hdurable_frag\".\n    iSplit.\n    {\n      iApply big_sepM_union; first by assumption.\n      iFrame.\n    }\n\n    iModIntro.\n    iIntros (?) \"Hmapsto\".\n    iDestruct (big_sepM_union with \"Hmapsto\") as \"[Hnew Hold]\".\n    1: assumption.\n    iFrame.\n    iApply \"HrestoreP0\".\n    iFrame.\n  Qed.\n\n  Lemma conflicting_exists {PROP:bi} (A L V : Type) (P : A → L → V → PROP) :\n    (∀ x1 x2, ConflictsWith (P x1) (P x2)) →\n    Conflicting (λ a v, ∃ x, P x a v)%I.\n  Proof.\n    intros.\n    hnf; intros a1 v1 a2 v2.\n    iIntros \"H1 H2\".\n    iDestruct \"H1\" as (?) \"H1\".\n    iDestruct \"H2\" as (?) \"H2\".\n    iApply (H with \"H1 H2\").\n  Qed.\n\n  Theorem lift_liftable_into_txn E `{!Liftable P}\n          l γ dinit γtxn P0 :\n    ↑invN ⊆ E →\n    ↑N ⊆ E →\n    N ## invN →\n    is_jrnl l γ dinit γtxn P0 -∗\n    P (λ a v, durable_mapsto_own γ a v)\n    -∗ |NC={E}=>\n    P (jrnl_maps_to γtxn) ∗\n    is_jrnl l γ dinit γtxn\n      (λ mapsto,\n       P mapsto ∗ P0 mapsto).\n  Proof.\n    iIntros (???) \"Hctx HP\".\n    iDestruct (liftable_restore_elim with \"HP\") as (m) \"[Hm #HP]\".\n    iMod (lift_map_into_txn with \"Hctx Hm\") as \"[Hm Hctx]\";\n      [ solve_ndisj .. | ].\n    iModIntro.\n    iFrame.\n    iSplitR \"Hctx\".\n    - iApply \"HP\"; iFrame.\n    - iApply (is_jrnl_wand with \"Hctx\").\n      iIntros (mapsto) \"!> [Hm $]\".\n      iApply \"HP\"; auto.\n  Qed.\n\n  Lemma exchange_big_sepM_addrs γ γ' (m0 m1 : gmap addr object) crash_txn :\n    dom m0 ⊆ dom m1 →\n    txn_durable γ' crash_txn -∗\n    addr_exchangers crash_txn γ γ' m1 -∗\n    ([∗ map] k0↦x ∈ m0, ephemeral_txn_val γ.(jrnl_async_name) crash_txn k0 x ∗\n                        (∃ i v, ephemeral_val_from γ.(jrnl_async_name) i k0 v)) -∗\n    addr_exchangers crash_txn γ γ' m1 ∗\n    [∗ map] k0↦x ∈ m0, durable_mapsto_own γ' k0 x.\n  Proof.\n    iIntros (Hdom) \"#Hdur H1 H2\".\n    rewrite /addr_exchangers.\n    iCombine \"Hdur H1\" as \"H1\".\n    iDestruct (big_sepM_mono_with_inv with \"H1 H2\") as \"((_&$)&H)\"; last iApply \"H\".\n    iIntros (k o Hlookup) \"((#Hdur&Hm)&Hephem)\".\n    assert (is_Some (m1 !! k)) as (v&?).\n    { apply elem_of_dom, Hdom, elem_of_dom. eauto. }\n    iDestruct (big_sepM_lookup_acc with \"Hm\") as \"(H&Hm)\"; first eassumption.\n    iDestruct \"Hephem\" as \"(#Hval0&Hephem)\".\n    iDestruct \"Hephem\" as (??) \"(_&Htok0)\".\n    iDestruct \"H\" as \"(Htok&#Hval)\".\n    iDestruct \"Hval\" as (?) \"(Hval1&Hval2)\".\n    iDestruct (ephemeral_txn_val_agree with \"Hval0 Hval1\") as %Heq. subst.\n    iDestruct \"Htok\" as \"[Hl|(Hr1&Hr2)]\".\n    { iExFalso. iDestruct \"Hl\" as (?) \"H\".\n      iApply (own_last_frag_conflict with \"[$] [$]\"). }\n    iSpecialize (\"Hm\" with \"[Htok0]\").\n    { iSplitL \"Htok0\".\n      - iLeft. eauto.\n      - iExists _. iFrame \"#\". }\n    iFrame \"# ∗\". iExists _. iFrame \"# ∗\".\n  Qed.\n\n  Lemma exchange_durable_mapsto γ γ' m :\n    (\"#Htxn_cinv\" ∷ txn_cinv γ γ' ∗\n     \"Hm\" ∷ [∗ map] a↦v ∈ m, durable_mapsto γ a v) -∗\n    |C={⊤}=> ([∗ map] a↦v ∈ m, durable_mapsto_own γ' a v).\n  Proof.\n    iNamed 1.\n    iDestruct \"Htxn_cinv\" as \"[#Hinv %kinds]\".\n    iMod (\"Hinv\").\n    iIntros \"HC\".\n    iInv (\"Hinv\") as \">H\" \"Hclo\".\n    iNamed \"H\".\n    iDestruct \"Hcrash_point\" as \"(Hasync&%Heq)\".\n    iAssert (⌜dom m ⊆ dom logm.(latest)⌝)%I with \"[Hm Hasync]\" as \"%Hdom2\".\n    {\n      iInduction m as [| i x m] \"IH\" using map_ind.\n      { iPureIntro; set_solver. }\n      rewrite big_sepM_insert //.\n      iDestruct \"Hm\" as \"(Hval1&Hval)\".\n      iDestruct (\"IH\" with \"[$] [$]\") as %Hdom.\n      iDestruct \"Hval1\" as (?) \"((?&?)&?)\".\n      iDestruct (ephemeral_val_from_agree_latest with \"[$] [$]\") as %Hlookup.\n      iPureIntro. rewrite dom_insert.\n      assert (i ∈ dom (logm.(latest))).\n      { apply elem_of_dom. eauto. }\n      set_solver.\n    }\n\n    iAssert ((txn_durable_exchanger γ crash_txn ∗ async_ctx γ.(jrnl_async_name) 1 logm) ∗\n              ([∗ map] k0↦x ∈ m, ephemeral_txn_val γ.(jrnl_async_name) crash_txn k0 x\n                  ∗ (∃ (i : nat) (v : object), ephemeral_val_from γ.(jrnl_async_name) i k0 v)))%I\n            with \"[Hasync Hdurable_exchanger Hm]\" as \"[[Hdurable_exchanger Hasync] Hm]\".\n    {\n      iCombine \"Hdurable_exchanger Hasync\" as \"H\".\n      iDestruct (big_sepM_mono_with_inv with \"H Hm\") as \"($&H)\"; last iApply \"H\".\n      iIntros (? ? Hlookup) \"((Hdurable_exchanger&Hasync)&Hm)\".\n      iDestruct \"Hm\" as (?) \"(?&?)\".\n      iDestruct (txn_durable_exchanger_use with \"[$] [$]\") as %Hlb.\n      iDestruct (ephemeral_val_from_val with \"Hasync [$]\") as \"#$\".\n      { lia. }\n      { lia. }\n      iFrame. iExists _, _; eauto.\n    }\n    iDestruct (exchange_big_sepM_addrs with \"[$] [$] Hm\") as \"(Hexchanger&Hval)\".\n    { eauto. }\n    iMod (\"Hclo\" with \"[Hexchanger Hdurable_exchanger Hasync]\").\n    { iNext. iExists _, _. iFrame \"# ∗\". eauto. }\n    iModIntro. eauto.\n  Qed.\n\n  Lemma exchange_durable_mapsto1 γ γ' a v :\n    (\"#Htxn_cinv\" ∷ txn_cinv γ γ' ∗\n     \"Hm\" ∷ durable_mapsto γ a v) -∗\n    |C={⊤}=> durable_mapsto_own γ' a v.\n  Proof.\n    iIntros \"H\".\n    iMod (exchange_durable_mapsto γ γ' {[ a := v ]} with \"[-]\").\n    { iNamed \"H\". iFrame \"Htxn_cinv\". rewrite big_sepM_singleton. eauto. }\n    iModIntro. rewrite big_sepM_singleton. eauto.\n  Qed.\n\n  Lemma exchange_mapsto_commit γ γ' m0 m txn_id :\n    dom m0 ⊆ dom m →\n    (\"#Htxn_cinv\" ∷ txn_cinv γ γ' ∗\n    \"Hold_vals\" ∷ ([∗ map] k↦x ∈ m0,\n          ∃ i : nat, txn_durable γ i ∗\n                     ephemeral_txn_val_range γ.(jrnl_async_name) i txn_id k x) ∗\n    \"Hval\" ∷ [∗ map] k↦x ∈ m, ephemeral_val_from γ.(jrnl_async_name) txn_id k x) -∗\n    |C={⊤}=> ([∗ map] a↦v ∈ m0, durable_mapsto_own γ' a v) ∨\n                  ([∗ map] a↦v ∈ m, durable_mapsto_own γ' a v).\n  Proof.\n    iIntros (Hdom1) \"H\". iNamed \"H\".\n    iDestruct \"Htxn_cinv\" as \"[#Hinv %kinds]\".\n    iMod (\"Hinv\").\n    iIntros \"HC\".\n    iInv (\"Hinv\") as \">H\" \"Hclo\".\n    iNamed \"H\".\n    iDestruct \"Hcrash_point\" as \"(Hasync&%Heq)\".\n    iAssert (⌜dom m ⊆ dom logm.(latest)⌝)%I with \"[Hval Hasync]\" as \"%Hdom2\".\n    {\n      clear Hdom1.\n      iInduction m as [| i x m] \"IH\" using map_ind.\n      { iPureIntro; set_solver. }\n      rewrite big_sepM_insert //.\n      iDestruct \"Hval\" as \"(Hval1&Hval)\".\n      iDestruct (\"IH\" with \"[$] [$]\") as %Hdom.\n      iDestruct (ephemeral_val_from_agree_latest with \"[$] [$]\") as %Hlookup.\n      iPureIntro. rewrite dom_insert.\n      assert (i ∈ dom (logm.(latest))).\n      { apply elem_of_dom. eauto. }\n      set_solver.\n    }\n\n    destruct (decide (crash_txn < txn_id)).\n    - (* We roll back, txn_id is not durable *)\n      iAssert (txn_durable_exchanger γ crash_txn ∗\n               ([∗ map] k0↦x ∈ m0, ephemeral_txn_val γ.(jrnl_async_name) crash_txn k0 x))%I\n        with \"[Hold_vals Hdurable_exchanger]\" as \"(Hdurable_exchanger&#Hold)\".\n      {\n        iDestruct (big_sepM_mono_with_inv with \"Hdurable_exchanger Hold_vals\") as \"($&H)\"; last iApply \"H\".\n        iIntros (?? Hlookup) \"(Hdurable_exchanger&H)\".\n        iDestruct \"H\" as (i) \"(Hdurable&Hrange)\".\n        iDestruct (txn_durable_exchanger_use with \"[$] [$]\") as %Hlb.\n        iFrame. iApply (ephemeral_txn_val_range_acc with \"[$]\").\n        lia.\n      }\n      iAssert ([∗ map] k0↦_ ∈ m, ∃ txn_id x, ephemeral_val_from γ.(jrnl_async_name) txn_id k0 x)%I\n       with \"[Hval]\" as \"Hval\".\n      { iApply (big_sepM_mono with \"Hval\"); eauto. }\n      iDestruct (big_sepM_dom with \"Hval\") as \"Hval\".\n      iDestruct (big_sepS_subseteq with \"Hval\") as \"Hval\"; eauto.\n      iDestruct (big_sepM_dom with \"Hval\") as \"Hval\".\n      iCombine \"Hold Hval\" as \"Hval\".\n      iEval (rewrite -big_sepM_sep) in \"Hval\".\n      iDestruct (exchange_big_sepM_addrs with \"[$] [$] Hval\") as \"(Hexchanger&Hval)\".\n      { etransitivity; last eassumption; eauto. }\n      iMod (\"Hclo\" with \"[Hexchanger Hdurable_exchanger Hasync]\").\n      { iNext. iExists _, _. iFrame \"# ∗\". eauto. }\n      iModIntro. eauto.\n    - (* We go forward, txn_id is durable *)\n      iAssert (async_ctx γ.(jrnl_async_name) 1 logm ∗\n                ([∗ map] k0↦x ∈ m, ephemeral_txn_val γ.(jrnl_async_name) crash_txn k0 x\n                    ∗ (∃ (i : nat) (v : object), ephemeral_val_from γ.(jrnl_async_name) i k0 v)))%I\n              with \"[Hasync Hval]\" as \"[Hasync Hval]\".\n      {iDestruct (big_sepM_mono_with_inv with \"Hasync Hval\") as \"($&H)\"; last iApply \"H\".\n       iIntros (? ? Hlookup) \"(Hasync&Hval)\".\n       iDestruct (ephemeral_val_from_val with \"Hasync Hval\") as \"#$\".\n       { lia. }\n       { lia. }\n       iFrame. iExists _, _; eauto.\n      }\n      iDestruct (exchange_big_sepM_addrs with \"[$] [$] Hval\") as \"(Hexchanger&Hval)\".\n      { eauto. }\n      iMod (\"Hclo\" with \"[Hexchanger Hdurable_exchanger Hasync]\").\n      { iNext. iExists _, _. iFrame \"# ∗\". eauto. }\n      iModIntro. eauto.\n  Qed.\n\nEnd goose_lang.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/jrnl/sep_jrnl_invariant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.21162063612758433}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import AbsAccessor.Spec.\nRequire Import RealmTimerHandler.Specs.handle_vtimer_sysreg_write.\nRequire Import RealmTimerHandler.LowSpecs.handle_vtimer_sysreg_write.\nRequire Import RealmTimerHandler.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       ESR_EL2_SYSREG_ISS_RT_spec\n       get_rec_regs_spec\n       sysreg_write_spec\n       set_rec_vtimer_masked_spec\n       sysreg_read_spec\n       get_rec_vtimer_masked_spec\n       get_rec_vtimer_spec\n       timer_condition_met_spec\n       set_rec_vtimer_asserted_spec\n       get_rec_sysregs_spec\n       set_rec_sysregs_spec\n    .\n\n  Lemma handle_vtimer_sysreg_write_spec_exists:\n    forall habd habd'  labd rec esr\n           (Hspec: handle_vtimer_sysreg_write_spec rec esr habd = Some habd')\n            (Hrel: relate_RData habd labd),\n    exists labd', handle_vtimer_sysreg_write_spec0 rec esr labd = Some labd' /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque ptr_eq.\n    intros. destruct Hrel. destruct rec.\n    unfold handle_vtimer_sysreg_write_spec, handle_vtimer_sysreg_write_spec0 in *.\n    repeat autounfold in *. simpl in *; unfold ref_accessible in *. simpl in *.\n    hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec;\n      repeat destruct_con; simpl in *; srewrite;\n        repeat (repeat grewrite; simpl; repeat simpl_update_reg; simpl; try rewrite ZMap.gss; simpl;\n                repeat (extract_if; [bool_rel_all; apply andb_true_iff; split; bool_rel;\n                                     match goal with\n                                     | [|- Z.lor ?a ?b <= ?x] => apply or_le_64; somega\n                                     | _ => somega\n                                     end | idtac]; grewrite; simpl));\n        try solve[eexists; split;\n                  [reflexivity|\n                   constructor; simpl;\n                   repeat (repeat simpl_field; repeat swap_fields; repeat rewrite ZMap.set2; simpl);\n                   reflexivity]].\n  Qed.\n\nEnd Refine.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RealmTimerHandler/RefProof/handle_vtimer_sysreg_write.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2116183864671024}}
{"text": "Require Import Coq.Classes.Morphisms.\nRequire Import Coq.Relations.Relations.\nRequire Import ExtLib.Core.RelDec.\nRequire Import ExtLib.Structures.Monad.\nRequire Import ExtLib.Structures.Traversable.\nRequire Import ExtLib.Data.Option.\nRequire Import ExtLib.Data.Prop.\nRequire Import ExtLib.Data.Pair.\nRequire Import ExtLib.Data.List.\nRequire Import ExtLib.Data.HList.\nRequire Import ExtLib.Data.Monads.OptionMonad.\nRequire Import ExtLib.Tactics.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.SubstI.\nRequire Import MirrorCore.ExprDAs.\nRequire Import MirrorCore.RTac.Core.\n\nRequire Import MirrorCore.Util.Quant.\nRequire Import MirrorCore.Util.Forwardy.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection parameterized.\n  Variable typ : Set.\n  Variable expr : Set.\n\n  Context {RType_typ : RType typ}.\n  Context {RTypeOk_typ : RTypeOk}.\n  Context {Typ0_Prop : Typ0 _ Prop}.\n  Context {Expr_expr : Expr typ expr}.\n  Context {ExprOk_expr : ExprOk Expr_expr}.\n\n(*\n  (** TODO(gmalecha): These should go somewhere more useful *)\n  Fixpoint forgets (from : nat) (ts : list typ) (s : subst)\n  : list (option expr) :=\n    match ts with\n      | nil => nil\n      | t :: ts =>\n        let rr := forgets (S from) ts s in\n        let ne := subst_lookup from s in\n        ne :: rr\n    end.\n\n  Fixpoint remembers (from : nat) (tes : list (typ * option expr)) (s : subst)\n  : option subst :=\n    match tes with\n      | nil => Some s\n      | (_,None) :: tes' => remembers (S from) tes' s\n      | (_,Some e) :: tes' =>\n        (* This should not be necessary but to eliminate it, we must have a\n         * syntactic soundness condition for [set] *)\n        match subst_lookup from s with\n          | None =>\n            match subst_set from e s with\n              | None => None\n              | Some s' => remembers (S from) tes' s'\n            end\n          | Some _ => None\n        end\n    end.\n*)\n\n\n  Definition rtacK_spec ctx (s : ctx_subst ctx) (g : Goal _ _)\n             (r : Result ctx) : Prop :=\n    match r with\n      | Fail => True\n      | Solved s' =>\n        WellFormed_Goal (getUVars ctx) (getVars ctx) g ->\n        WellFormed_ctx_subst s ->\n        WellFormed_ctx_subst s' /\\\n        match pctxD s\n            , goalD _ _ g\n            , pctxD s'\n        with\n          | None , _ , _\n          | Some _ , None , _ => True\n          | Some _ , Some _ , None => False\n          | Some cD , Some gD , Some cD' =>\n            SubstMorphism s s' /\\\n            forall us vs, cD' gD us vs\n        end\n      | More_ s' g' =>\n        WellFormed_Goal (getUVars ctx) (getVars ctx) g ->\n        WellFormed_ctx_subst s ->\n        WellFormed_ctx_subst s' /\\\n        WellFormed_Goal (getUVars ctx) (getVars ctx) g' /\\\n        match pctxD s\n            , goalD _ _ g\n            , pctxD s'\n            , goalD _ _ g'\n        with\n          | None , _ , _ , _\n          | Some _ , None , _ , _ => True\n          | Some _ , Some _ , None , _\n          | Some _ , Some _ , Some _ , None => False\n          | Some cD , Some gD , Some cD' , Some gD' =>\n            SubstMorphism s s' /\\\n            forall us vs,\n              cD' (fun us vs => gD' us vs -> gD us vs) us vs\n        end\n    end.\n\n  Definition rtacK_spec_wf ctx (s : ctx_subst ctx) (g : Goal _ _)\n             (r : Result ctx) : Prop :=\n    match r with\n      | Fail => True\n      | Solved s' =>\n        WellFormed_Goal (getUVars ctx) (getVars ctx) g ->\n        WellFormed_ctx_subst s ->\n        WellFormed_ctx_subst s'\n      | More_ s' g' =>\n        WellFormed_Goal (getUVars ctx) (getVars ctx) g ->\n        WellFormed_ctx_subst s ->\n        WellFormed_ctx_subst (c:=ctx) s' /\\\n        WellFormed_Goal (getUVars ctx) (getVars ctx) g'\n    end.\n\n  Theorem rtacK_spec_rtacK_spec_wf : forall ctx s g r,\n      @rtacK_spec ctx s g r ->\n      @rtacK_spec_wf ctx s g r.\n  Proof.\n    unfold rtacK_spec, rtacK_spec_wf; destruct r; tauto.\n  Qed.\n\n  Theorem Proper_rtacK_spec ctx s\n  : Proper (EqGoal (getUVars ctx) (getVars ctx) ==>\n            @EqResult _ _ _ _ _ ctx ==> iff)\n           (@rtacK_spec ctx s).\n  Proof.\n    red. red. red.\n    unfold rtacK_spec.\n    inversion 2.\n    { destruct x0; destruct y0; simpl in *; try congruence.\n      reflexivity. }\n    { destruct x0; destruct y0; simpl in *;\n      try solve [ reflexivity | congruence ]; inv_all; subst; inv_all;\n      repeat match goal with\n               | H : ?X , H' : ?X |- _ => clear H'\n               | H : EqGoal _ _ _ _ |- _ => destruct H\n               | |- (_ -> _) <-> (_ -> _) =>\n                 eapply impl_iff; [ solve [ eauto | reflexivity ] | ]; intros\n               | |- (_ /\\ _) <-> (_ /\\ _) =>\n                 eapply and_iff; [ solve [ eauto | reflexivity ] | ]; intros\n               | H : Roption _ _ _ |- _ => inversion H; clear H\n               | |- context [ match ?X with _ => _ end ] =>\n                 consider X; intros; try reflexivity; [ ]\n               | |- context [ match ?X with _ => _ end ] =>\n                 consider X; intros; reflexivity\n               | |- (forall x, _) <-> (forall y, _) =>\n                 eapply forall_iff; intro\n               | |- _ =>\n                 eapply left_side; [ match goal with\n                                       | H : _ <-> _ |- _ => apply H; constructor\n                                     end | ]\n               | |- _ =>\n                 eapply right_side; [ match goal with\n                                       | H : _ <-> _ |- _ => apply H; constructor\n                                     end | ]\n               | |- ?X _ _ _ <-> ?X _ _ _ =>\n                 (eapply Fmap_pctxD_iff; try reflexivity; eauto);\n                   [  ]\n             end.\n      { do 5 red; intros; equivs.\n        apply impl_iff; [ eapply H10; try reflexivity; eauto | intro ].\n        apply H12; reflexivity. }\n      { subst. do 5 red; intros; equivs.\n        do 5 red in H9.\n        rewrite H9; try reflexivity.\n        rewrite impl_True_iff.\n        eapply H11; reflexivity. }\n      { subst. do 5 red in H9.\n        do 5 red; intros; equivs.\n        rewrite <- H9; try reflexivity.\n        rewrite impl_True_iff.\n        eapply H11; reflexivity. }\n      { eapply Fmap_pctxD_iff; try reflexivity; eauto. } }\n  Qed.\n\n  (** Treat this as opaque! **)\n  Definition rtacK : Type :=\n    forall c : Ctx typ expr, ctx_subst c -> Goal typ expr -> Result c.\n\n  Definition rtacK_sound (tac : rtacK)\n  : Prop :=\n    forall ctx s g result,\n      tac ctx s g = result ->\n      @rtacK_spec ctx s g result.\n\n  Definition WellFormed_rtacK (tac : rtacK)\n  : Prop :=\n    forall ctx s g result,\n      tac ctx s g = result ->\n      @rtacK_spec_wf ctx s g result.\n\n  Theorem rtacK_sound_WellFormed_rtacK : forall tac,\n      rtacK_sound tac -> WellFormed_rtacK tac.\n  Proof.\n    intros. red. intros.\n    eapply rtacK_spec_rtacK_spec_wf. eauto.\n  Qed.\n\nEnd parameterized.\n\nDelimit Scope rtacK_scope with rtacK.\n\nArguments rtacK_sound {typ expr _ _ _} tac%rtacK : rename.\nArguments WellFormed_rtacK {typ expr _ _} tac%rtacK : rename.\n\nDelimit Scope or_rtacK_scope with or_rtacK.\n\nNotation \" [ ] \" := (@nil (rtacK _ _)) : or_rtacK_scope.\nNotation \" [  x ] \" := (@cons (rtacK _ _) x%rtacK (@nil (rtacK _ _))) : or_rtacK_scope.\nNotation \" [  x  | ..  | y  ] \" := (@cons (rtacK _ _) x%rtacK .. (@cons (rtacK _ _) y%rtacK (@nil (rtacK _ _))) ..) : or_rtacK_scope.\n\nExport MirrorCore.ExprI.\nExport MirrorCore.SubstI.\nExport MirrorCore.ExprDAs.\nExport MirrorCore.RTac.Core.\n", "meta": {"author": "gmalecha", "repo": "mirror-core", "sha": "b962fbca15b0b5a4653f66d29d7115bb04ebd4f3", "save_path": "github-repos/coq/gmalecha-mirror-core", "path": "github-repos/coq/gmalecha-mirror-core/mirror-core-b962fbca15b0b5a4653f66d29d7115bb04ebd4f3/theories/RTac/CoreK.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21161838646710235}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The L2C verified compiler                              *)\n(*                                                                     *)\n(*            L2C Group, Tsinghua University                           *)\n(*                                                                     *)\n(*  Copyright Tsinghua University.  All rights reserved.  This file is *)\n(*  distributed under the terms of the GNU General Public License as   *)\n(*  published by the Free Software Foundation, either version 2 of the *)\n(*  License, or (at your option) any later version.  This file is also *)\n(*  distributed under the terms of the INRIA Non-Commercial License    *)\n(*  Agreement.                                                         *)\n(*                                                                     *)\n(* *********************************************************************)\n\nRequire Import Coqlib.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import AST.\nRequire Import Lop.\nRequire Import Lustre.\n\n(** * Global Declares *)\n\n(** * Types *)   \n\n(** Types include short (signed 16 bits), ushort (unsigned 16 bits),int(signed 32 bits),\n  uint(unsigned 32 bits), float (32 bits), real (64 bits), bool(true or false), char, \n  array, struct and enum. *) \n \n(** The syntax of type expressions.  Some points to note:\n- struct type, e.g type s1 = { n : int, m : real } is expressed by syntax as below:\n       Tstruct \"s1\" (Fcons \"n\" (Tint)\n                    (Fcons \"m\" (Treal)\n                    Fnil))\n- no recursive type, e.g type s = { m : s } is not allowed, although it canbe expressed by syntax. \n*)\n \nInductive typeL : Type :=\n  | Tshort : typeL                          (**r integer types, signed 16 bits *)\n  | Tushort : typeL                         (**r integer types, unsigned 16 bits  *)\n  | Tint : typeL                            (**r integer types, signed 32 bits *)\n  | Tuint : typeL                           (**r integer types, unsigned 32 bits *)\n  | Tfloat : typeL                          (**r floating-point types, 32 bits *)\n  | Treal : typeL                           (**r floating-point types, 64 bits *)\n  | Tbool : typeL                           (**r bool types *)\n  | Tchar : typeL                           (**r char types *)\n  | Tarray : ident -> typeL -> Z -> typeL   (**r array types: array_type_id(ty^len) *)\n  | Tstruct : ident -> fieldlistL -> typeL  (**r struct types: struct_type_id {label1_id: type1; ...} *)\n  | Tenum : list ident -> typeL    (**r enum types: enum_type_id {value1_id, ...} *)         \n\nwith fieldlistL : Type :=\n  | Fnil : fieldlistL\n  | Fcons : ident -> typeL -> fieldlistL -> fieldlistL.\n\nLemma type_eqL: forall (ty1 ty2: typeL), {ty1=ty2} + {ty1<>ty2}\nwith fieldlist_eqL: forall (fld1 fld2: fieldlistL), {fld1=fld2} + {fld1<>fld2}.\nProof.\n  repeat (decide equality).\n  generalize ident_eq zeq. intros E1 E2. \n  decide equality.\nDefined.\n\nOpaque type_eqL fieldlist_eqL.\n\n(** const_block \n     Const block consisting of all character constants *)\n\nInductive constL : Type := \n  | ShortConstL: int -> constL\n  | UshortConstL: int -> constL\n  | IntConstL: int -> constL\n  | UintConstL: int -> constL\n  | CharConstL: int -> constL\n  | FloatConstL: float32 -> constL\n  | RealConstL: float -> constL\n  | BoolConstL: bool -> constL\n  | ConstructConstL : const_listL -> constL     (**r E.g struct {label1 : 1, label2 : 2}, or array [1, 2] *) \n  | ID : ident -> constL               (**r to define other constant by character constant *)     \n\nwith const_listL : Type :=\n  | ConstNilL : const_listL\n  | ConstConL : constL -> const_listL -> const_listL.\n\n(** * Expressions *)\n\nDefinition vars := list (ident * typeL * clock).\n\nInductive suboperator : Type := \n  | Nodehandler : ident -> bool -> list typeL -> suboperator\n  | PrefixL_unary : unary_operationL -> suboperator\n  | PrefixL_binary : binary_operationL -> suboperator. \n\nInductive exprT : Type := \n  | EconstT : const -> typeL -> exprT\n  | EvarT : ident -> typeL -> clock -> exprT\n  | ListExprT : expr_listT -> exprT                                           (**r list expression *)\n  | ApplyExprT : operatorT -> expr_listT ->  exprT \t              (**r operator application *)\n  | EconstructT : struct_listT -> exprT                                      (**r construct a struct, e.g {label1 : 3, label2 : false} *)\n  | EarrayaccT : exprT -> int -> exprT                                     (**r expr[i], access to (i+1)th member of an array \"expr\" *)\n  | EarraydefT :  exprT -> int -> exprT                               (**r expr ^ i, an array of size \"i\" with every element \"expr\" *)\n  | EarraydiffT : expr_listT ->  exprT                                      (**r [list expression], build an array with elements \"list expression\", e.g [1,2]*)\n  | EarrayprojT: exprT -> expr_listT -> exprT ->  exprT                     (**r dynamic projection, e.g (2^3^4.[7] default 100^3), value is 100^3 *) \n  | EarraysliceT : exprT -> int -> int -> exprT                            (**r a [i..j] is the sliced array [a_i, a_i+1, ... , a_j]*) \n  | EmixT : exprT -> label_index_listT -> exprT -> exprT                   (**r construct a new array or struct, e.g {label1:2^3} with label1.[0] = 7, value is {label1:[7,2]} *)\n  | EunopT : unary_operationL -> exprT -> exprT                            (**r unary operation *)\n  | EbinopT : binary_operationL -> exprT -> exprT -> exprT                 (**r binary operation *)\n  | EfieldT : exprT -> ident -> exprT                                      (**r access to a member of a struct *)\n  | EpreT : exprT -> exprT                              (**r pre : shift flows on the last instant backward, producing an undefined value at first instant*)\n  | EfbyT : expr_listT -> int -> expr_listT -> exprT  (**r fby : fby(b; n; a) = a -> pre fby(b; n-1; a) *) \n  | EarrowT : exprT -> exprT -> exprT                                         (**r -> : fix the inital value of flows*)\n  | EwhenT : exprT -> clock -> exprT                                          (**r x when h: if h=false, then no value; otherwise x *)\n  | EcurrentT: exprT ->  exprT   \n  | EmergeT: ident -> pattern_listT -> exprT   \n  | EifT : exprT -> exprT -> exprT -> exprT                                   (**r conditional*)\n  | EcaseT : exprT -> pattern_listT -> exprT                                  (**r case *)\n  | EboolredT: int -> int -> exprT -> exprT\n  | EdieseT: exprT -> exprT  (**r #(a1, ..., an) -> boolred(0,1,n)[a1, ..., an] *)\n  | EnorT: exprT ->  exprT  (**r nor(a1, ..., an) boolred(0,0,n)[a1, ..., an] *)\n\nwith expr_listT : Type :=\n  | Enil: expr_listT\n  | Econs: exprT -> expr_listT -> expr_listT\n\nwith struct_listT: Type :=\n  | EstructNil: struct_listT\n  | EstructCons: ident -> exprT -> struct_listT -> struct_listT\n\nwith label_index_listT: Type :=\n  | Lnil: label_index_listT\n  | LconsLabelT: ident -> label_index_listT -> label_index_listT\n  | LconsIndexT: exprT -> label_index_listT -> label_index_listT\n\nwith pattern_listT : Type :=\n  | PatternNilT : pattern_listT\n  | PatternConT : patn -> exprT -> pattern_listT -> pattern_listT\n\nwith operatorT : Type :=  \n  | SuboperatorT : suboperator -> operatorT\n  | IteratorT : iterator_operation -> suboperator -> int -> operatorT.\n\n(** * Equation *)\n\nInductive equationT : Type :=\n  | EquationT: vars -> exprT -> equationT.\n\n(** * Node *)\n\n(** Node : kind -> ID -> parameters -> returns -> locals -> body *)\n\nRecord nodeT : Type :=\n  | NodeT : bool -> ident -> vars -> vars -> vars -> list equationT -> nodeT.    \n\n(** * Program *)\n\nInductive programT : Type := mkprogramT{\n  type_blockT : list (ident*typeL);\n  const_blockT : list (ident*typeL*constL);\n  node_blockT : list nodeT;\n  node_mainT : ident\n}.\n\n", "meta": {"author": "linusboyle", "repo": "L2CDisplay", "sha": "4eb5b4dbb01da56534c0b0a1560dec8c715a68a4", "save_path": "github-repos/coq/linusboyle-L2CDisplay", "path": "github-repos/coq/linusboyle-L2CDisplay/L2CDisplay-4eb5b4dbb01da56534c0b0a1560dec8c715a68a4/src/LustreW.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.211618380406614}}
{"text": "From iris.program_logic Require Export language ectx_language ectxi_language.\nFrom iris.algebra Require Export ofe.\nFrom stdpp Require Export strings.\nFrom stdpp Require Import gmap.\nSet Default Proof Using \"Type\".\n\n(** heap_lang.  A fairly simple language used for common Iris examples.\n\n- This is a right-to-left evaluated language, like CakeML and OCaml.  The reason\n  for this is that it makes curried functions usable: Given a WP for [f a b], we\n  know that any effects [f] might have to not matter until after *both* [a] and\n  [b] are evaluated.  With left-to-right evaluation, that triple is basically\n  useless unless the user let-expands [b].\n\n- Iris-time specific: We added support for bounded integers, with a signed\n  semantics. Overflows have undefined semantics.\n\n*)\n\nDelimit Scope expr_scope with E.\nDelimit Scope val_scope with V.\n\n(* FIXME : we would like to parameterize the whole language with\n   respect to a typeclass containing the following, but then coercions\n   for LitInt, LitBool, Var and BNamed stop working because we break\n   the uniform inheritance condition. *)\nParameter word_size : nat.\nAxiom word_size_gt_1 : word_size > 1.\n\nDefinition max_mach_int : Z := 1 ≪ (word_size-1).\nDefinition min_mach_int : Z := - max_mach_int.\nDefinition mod_mach_int : Z := 2 * max_mach_int.\nDefinition mach_int_bounded (n : Z) := (min_mach_int ≤ n < max_mach_int)%Z.\n\nLemma max_mach_int_1_lt : (1 < max_mach_int)%Z.\nProof.\n  pose proof word_size_gt_1. rewrite /max_mach_int Z.shiftl_1_l.\n  apply (Z.pow_lt_mono_r 2 0 _); lia.\nQed.\n\nDefinition mach_int :=\n  {n : Z | bool_decide (mach_int_bounded n) }%Z.\n\nDefinition to_mach_int (n : Z) : option mach_int :=\n  match decide (bool_decide (mach_int_bounded n)) with\n  | left H => Some (n ↾ H)\n  | right _ => None\n  end.\n\nProgram Definition mach_int_0 : mach_int := 0 ↾ _.\nNext Obligation.\n  pose proof max_mach_int_1_lt. apply bool_decide_pack.\n  split; unfold min_mach_int; lia.\nQed.\n\nProgram Definition mach_int_1 : mach_int := 1 ↾ _.\nNext Obligation.\n  pose proof max_mach_int_1_lt. apply bool_decide_pack.\n  split; unfold min_mach_int; lia.\nQed.\n\nInstance mach_int_dec_eq :\n  EqDecision mach_int.\nProof. apply sig_eq_dec; by apply _. Qed.\n\nModule heap_lang.\nOpen Scope Z_scope.\n\n(** Expressions and vals. *)\nDefinition loc := positive. (* Really, any countable type. *)\n\nInductive base_lit : Set :=\n  | LitInt (n : Z) | LitBool (b : bool) | LitUnit | LitLoc (l : loc)\n  | LitMachInt (n : mach_int).\nInductive un_op : Set :=\n  | NegOp | MinusUnOp.\nInductive bin_op : Set :=\n  | PlusOp | MinusOp | MultOp | QuotOp | RemOp (* Arithmetic *)\n  | AndOp | OrOp | XorOp (* Bitwise *)\n  | ShiftLOp | ShiftROp (* Shifts *)\n  | LeOp | LtOp | EqOp. (* Relations *)\n\nInductive binder := BAnon | BNamed : string → binder.\nDeclare Scope binder_scope.\nDelimit Scope binder_scope with bind.\nBind Scope binder_scope with binder.\nDefinition cons_binder (mx : binder) (X : list string) : list string :=\n  match mx with BAnon => X | BNamed x => x :: X end.\nInfix \":b:\" := cons_binder (at level 60, right associativity).\nInstance binder_eq_dec_eq : EqDecision binder.\nProof. solve_decision. Defined.\n\nInstance set_unfold_cons_binder x mx X P :\n  SetUnfold (x ∈ X) P → SetUnfold (x ∈ mx :b: X) (BNamed x = mx ∨ P).\nProof.\n  constructor. rewrite -(set_unfold (x ∈ X) P).\n  destruct mx; rewrite /= ?elem_of_cons; naive_solver.\nQed.\n\nInductive expr :=\n  (* Values *)\n  | Val (v : val)\n  (* Base lambda calculus *)\n  | Var (x : string)\n  | Rec (f x : binder) (e : expr)\n  | App (e1 e2 : expr)\n  (* Base types and their operations *)\n  | UnOp (op : un_op) (e : expr)\n  | BinOp (op : bin_op) (e1 e2 : expr)\n  | If (e0 e1 e2 : expr)\n  (* Products *)\n  | Pair (e1 e2 : expr)\n  | Fst (e : expr)\n  | Snd (e : expr)\n  (* Sums *)\n  | InjL (e : expr)\n  | InjR (e : expr)\n  | Case (e0 : expr) (e1 : expr) (e2 : expr)\n  (* Concurrency *)\n  | Fork (e : expr)\n  (* Heap *)\n  | Alloc (e : expr)\n  | Load (e : expr)\n  | Store (e1 : expr) (e2 : expr)\n  | CAS (e0 : expr) (e1 : expr) (e2 : expr)\n  | FAA (e1 : expr) (e2 : expr)\nwith val :=\n  | LitV (l : base_lit)\n  | RecV (f x : binder) (e : expr)\n  | PairV (v1 v2 : val)\n  | InjLV (v : val)\n  | InjRV (v : val).\n\nBind Scope expr_scope with expr.\nBind Scope val_scope with val.\n\nNotation of_val := Val (only parsing).\n\nDefinition to_val (e : expr) : option val :=\n  match e with\n  | Val v => Some v\n  | _ => None\n  end.\n\n(** We assume the following encoding of values to 64-bit words: The least 3\nsignificant bits of every word are a \"tag\", and we have 61 bits of payload,\nwhich is enough if all pointers are 8-byte-aligned (common on 64bit\narchitectures). The tags have the following meaning:\n\n0: Payload is the data for a LitV (LitInt _).\n1: Payload is the data for a InjLV (LitV (LitInt _)).\n2: Payload is the data for a InjRV (LitV (LitInt _)).\n3: Payload is the data for a LitV (LitLoc _).\n4: Payload is the data for a InjLV (LitV (LitLoc _)).\n4: Payload is the data for a InjRV (LitV (LitLoc _)).\n6: Payload is one of the following finitely many values, which 61 bits are more\n   than enough to encode:\n   LitV LitUnit, InjLV (LitV LitUnit), InjRV (LitV LitUnit),\n   LitV (LitBool _), InjLV (LitV (LitBool _)), InjRV (LitV (LitBool _)).\n7: Value is boxed, i.e., payload is a pointer to some read-only memory area on\n   the heap which stores whether this is a RecV, PairV, InjLV or InjRV and the\n   relevant data for those cases. However, the boxed representation is never\n   used if any of the above representations could be used.\n\nIgnoring (as usual) the fact that we have to fit the infinite Z/loc into 61\nbits, this means every value is machine-word-sized and can hence be atomically\nread and written.  Also notice that the sets of boxed and unboxed values are\ndisjoint. *)\nDefinition val_is_unboxed (v : val) : Prop :=\n  match v with\n  | LitV _ => True\n  | InjLV (LitV _) => True\n  | InjRV (LitV _) => True\n  | _ => False\n  end.\n\n(** The state: heaps of vals. *)\nDefinition state : Type := gmap loc val.\n\n(** Equality and other typeclass stuff *)\nLemma to_of_val v : to_val (of_val v) = Some v.\nProof. by destruct v. Qed.\n\nLemma of_to_val e v : to_val e = Some v → of_val v = e.\nProof. destruct e=>//=. by intros [= <-]. Qed.\n\nGlobal Instance of_val_inj : Inj (=) (=) of_val.\nProof. intros ??. congruence. Qed.\n\nGlobal Instance base_lit_eq_dec : EqDecision base_lit.\nProof. solve_decision. Defined.\nGlobal Instance un_op_eq_dec : EqDecision un_op.\nProof. solve_decision. Defined.\nGlobal Instance bin_op_eq_dec : EqDecision bin_op.\nProof. solve_decision. Defined.\nGlobal Instance expr_eq_dec : EqDecision expr.\nProof.\n  refine (\n   fix go (e1 e2 : expr) {struct e1} : Decision (e1 = e2) :=\n     match e1, e2 with\n     | Val v, Val v' => cast_if (decide (v = v'))\n     | Var x, Var x' => cast_if (decide (x = x'))\n     | Rec f x e, Rec f' x' e' =>\n        cast_if_and3 (decide (f = f')) (decide (x = x')) (decide (e = e'))\n     | App e1 e2, App e1' e2' => cast_if_and (decide (e1 = e1')) (decide (e2 = e2'))\n     | UnOp o e, UnOp o' e' => cast_if_and (decide (o = o')) (decide (e = e'))\n     | BinOp o e1 e2, BinOp o' e1' e2' =>\n        cast_if_and3 (decide (o = o')) (decide (e1 = e1')) (decide (e2 = e2'))\n     | If e0 e1 e2, If e0' e1' e2' =>\n        cast_if_and3 (decide (e0 = e0')) (decide (e1 = e1')) (decide (e2 = e2'))\n     | Pair e1 e2, Pair e1' e2' =>\n        cast_if_and (decide (e1 = e1')) (decide (e2 = e2'))\n     | Fst e, Fst e' => cast_if (decide (e = e'))\n     | Snd e, Snd e' => cast_if (decide (e = e'))\n     | InjL e, InjL e' => cast_if (decide (e = e'))\n     | InjR e, InjR e' => cast_if (decide (e = e'))\n     | Case e0 e1 e2, Case e0' e1' e2' =>\n        cast_if_and3 (decide (e0 = e0')) (decide (e1 = e1')) (decide (e2 = e2'))\n     | Fork e, Fork e' => cast_if (decide (e = e'))\n     | Alloc e, Alloc e' => cast_if (decide (e = e'))\n     | Load e, Load e' => cast_if (decide (e = e'))\n     | Store e1 e2, Store e1' e2' =>\n        cast_if_and (decide (e1 = e1')) (decide (e2 = e2'))\n     | CAS e0 e1 e2, CAS e0' e1' e2' =>\n        cast_if_and3 (decide (e0 = e0')) (decide (e1 = e1')) (decide (e2 = e2'))\n     | FAA e1 e2, FAA e1' e2' =>\n        cast_if_and (decide (e1 = e1')) (decide (e2 = e2'))\n     | _, _ => right _\n     end\n   with gov (v1 v2 : val) {struct v1} : Decision (v1 = v2) :=\n     match v1, v2 with\n     | LitV l, LitV l' => cast_if (decide (l = l'))\n     | RecV f x e, RecV f' x' e' =>\n        cast_if_and3 (decide (f = f')) (decide (x = x')) (decide (e = e'))\n     | PairV e1 e2, PairV e1' e2' =>\n        cast_if_and (decide (e1 = e1')) (decide (e2 = e2'))\n     | InjLV e, InjLV e' => cast_if (decide (e = e'))\n     | InjRV e, InjRV e' => cast_if (decide (e = e'))\n     | _, _ => right _\n     end\n   for go); try (clear go gov; abstract intuition congruence).\nDefined.\nGlobal Instance val_eq_dec : EqDecision val.\nProof. solve_decision. Defined.\n\nGlobal Instance base_lit_countable : Countable base_lit.\nProof.\n refine (inj_countable' (λ l, match l with\n  | LitInt n => inl (inl (true, n)) | LitBool b => inl (inr b)\n  | LitUnit => inr (inl ()) | LitLoc l => inr (inr l)\n  | LitMachInt n => inl (inl (false, `n))\n  end) (λ l, match l with\n  | inl (inl (true, n)) => LitInt n | inl (inr b) => LitBool b\n  | inr (inl ()) => LitUnit | inr (inr l) => LitLoc l\n  | inl (inl (false, n)) =>\n    match decide _ with\n    | left H => LitMachInt (n ↾ H)\n    | right H => LitUnit        (* Dummy *)\n    end\n  end) _); intros []; try done.\n (* Machine integers. *)\n case_match; [by rewrite exists_proj1_pi|by destruct n].\nQed.\nGlobal Instance un_op_finite : Countable un_op.\nProof.\n refine (inj_countable' (λ op, match op with NegOp => 0 | MinusUnOp => 1 end)\n  (λ n, match n with 0 => NegOp | _ => MinusUnOp end) _); by intros [].\nQed.\nGlobal Instance bin_op_countable : Countable bin_op.\nProof.\n refine (inj_countable' (λ op, match op with\n  | PlusOp => 0 | MinusOp => 1 | MultOp => 2 | QuotOp => 3 | RemOp => 4\n  | AndOp => 5 | OrOp => 6 | XorOp => 7 | ShiftLOp => 8 | ShiftROp => 9\n  | LeOp => 10 | LtOp => 11 | EqOp => 12\n  end) (λ n, match n with\n  | 0 => PlusOp | 1 => MinusOp | 2 => MultOp | 3 => QuotOp | 4 => RemOp\n  | 5 => AndOp | 6 => OrOp | 7 => XorOp | 8 => ShiftLOp | 9 => ShiftROp\n  | 10 => LeOp | 11 => LtOp | _ => EqOp\n  end) _); by intros [].\nQed.\nGlobal Instance binder_countable : Countable binder.\nProof.\n refine (inj_countable' (λ b, match b with BNamed s => Some s | BAnon => None end)\n  (λ b, match b with Some s => BNamed s | None => BAnon end) _); by intros [].\nQed.\nGlobal Instance expr_countable : Countable expr.\nProof.\n set (enc :=\n   fix go e :=\n     match e with\n     | Val v => GenNode 0 [gov v]\n     | Var x => GenLeaf (inl (inl x))\n     | Rec f x e => GenNode 1 [GenLeaf (inl (inr f)); GenLeaf (inl (inr x)); go e]\n     | App e1 e2 => GenNode 2 [go e1; go e2]\n     | UnOp op e => GenNode 3 [GenLeaf (inr (inr (inl op))); go e]\n     | BinOp op e1 e2 => GenNode 4 [GenLeaf (inr (inr (inr op))); go e1; go e2]\n     | If e0 e1 e2 => GenNode 5 [go e0; go e1; go e2]\n     | Pair e1 e2 => GenNode 6 [go e1; go e2]\n     | Fst e => GenNode 7 [go e]\n     | Snd e => GenNode 8 [go e]\n     | InjL e => GenNode 9 [go e]\n     | InjR e => GenNode 10 [go e]\n     | Case e0 e1 e2 => GenNode 11 [go e0; go e1; go e2]\n     | Fork e => GenNode 12 [go e]\n     | Alloc e => GenNode 13 [go e]\n     | Load e => GenNode 14 [go e]\n     | Store e1 e2 => GenNode 15 [go e1; go e2]\n     | CAS e0 e1 e2 => GenNode 16 [go e0; go e1; go e2]\n     | FAA e1 e2 => GenNode 17 [go e1; go e2]\n     end\n   with gov v :=\n     match v with\n     | LitV l => GenLeaf (inr (inl l))\n     | RecV f x e =>\n        GenNode 0 [GenLeaf (inl (inr f)); GenLeaf (inl (inr x)); go e]\n     | PairV v1 v2 => GenNode 1 [gov v1; gov v2]\n     | InjLV v => GenNode 2 [gov v]\n     | InjRV v => GenNode 3 [gov v]\n     end\n   for go).\n set (dec :=\n   fix go e :=\n     match e with\n     | GenNode 0 [v] => Val (gov v)\n     | GenLeaf (inl (inl x)) => Var x\n     | GenNode 1 [GenLeaf (inl (inr f)); GenLeaf (inl (inr x)); e] => Rec f x (go e)\n     | GenNode 2 [e1; e2] => App (go e1) (go e2)\n     | GenNode 3 [GenLeaf (inr (inr (inl op))); e] => UnOp op (go e)\n     | GenNode 4 [GenLeaf (inr (inr (inr op))); e1; e2] => BinOp op (go e1) (go e2)\n     | GenNode 5 [e0; e1; e2] => If (go e0) (go e1) (go e2)\n     | GenNode 6 [e1; e2] => Pair (go e1) (go e2)\n     | GenNode 7 [e] => Fst (go e)\n     | GenNode 8 [e] => Snd (go e)\n     | GenNode 9 [e] => InjL (go e)\n     | GenNode 10 [e] => InjR (go e)\n     | GenNode 11 [e0; e1; e2] => Case (go e0) (go e1) (go e2)\n     | GenNode 12 [e] => Fork (go e)\n     | GenNode 13 [e] => Alloc (go e)\n     | GenNode 14 [e] => Load (go e)\n     | GenNode 15 [e1; e2] => Store (go e1) (go e2)\n     | GenNode 16 [e0; e1; e2] => CAS (go e0) (go e1) (go e2)\n     | GenNode 17 [e1; e2] => FAA (go e1) (go e2)\n     | _ => Val $ LitV LitUnit (* dummy *)\n     end\n   with gov v :=\n     match v with\n     | GenLeaf (inr (inl l)) => LitV l\n     | GenNode 0 [GenLeaf (inl (inr f)); GenLeaf (inl (inr x)); e] => RecV f x (go e)\n     | GenNode 1 [v1; v2] => PairV (gov v1) (gov v2)\n     | GenNode 2 [v] => InjLV (gov v)\n     | GenNode 3 [v] => InjRV (gov v)\n     | _ => LitV LitUnit (* dummy *)\n     end\n   for go).\n refine (inj_countable' enc dec _).\n refine (fix go (e : expr) {struct e} := _ with gov (v : val) {struct v} := _ for go).\n - destruct e as [v| | | | | | | | | | | | | | | | | |]; simpl; f_equal;\n     [exact (gov v)|done..].\n - destruct v; by f_equal.\nQed.\nGlobal Instance val_countable : Countable val.\nProof. refine (inj_countable of_val to_val _); auto using to_of_val. Qed.\n\nGlobal Instance val_inhabited : Inhabited val := populate (LitV LitUnit).\nGlobal Instance expr_inhabited : Inhabited expr := populate (Val inhabitant).\n\nCanonical Structure valC := leibnizO val.\nCanonical Structure exprC := leibnizO expr.\n\n(** Evaluation contexts *)\nInductive ectx_item :=\n  | AppLCtx (v2 : val)\n  | AppRCtx (e1 : expr)\n  | UnOpCtx (op : un_op)\n  | BinOpLCtx (op : bin_op) (v2 : val)\n  | BinOpRCtx (op : bin_op) (e1 : expr)\n  | IfCtx (e1 e2 : expr)\n  | PairLCtx (v2 : val)\n  | PairRCtx (e1 : expr)\n  | FstCtx\n  | SndCtx\n  | InjLCtx\n  | InjRCtx\n  | CaseCtx (e1 : expr) (e2 : expr)\n  | AllocCtx\n  | LoadCtx\n  | StoreLCtx (v2 : val)\n  | StoreRCtx (e1 : expr)\n  | CasLCtx (v1 : val) (v2 : val)\n  | CasMCtx (e0 : expr) (v2 : val)\n  | CasRCtx (e0 : expr) (e1 : expr)\n  | FaaLCtx (v2 : val)\n  | FaaRCtx (e1 : expr).\n\nDefinition fill_item (Ki : ectx_item) (e : expr) : expr :=\n  match Ki with\n  | AppLCtx v2 => App e (Val v2)\n  | AppRCtx e1 => App e1 e\n  | UnOpCtx op => UnOp op e\n  | BinOpLCtx op v2 => BinOp op e (Val v2)\n  | BinOpRCtx op e1 => BinOp op e1 e\n  | IfCtx e1 e2 => If e e1 e2\n  | PairLCtx v2 => Pair e (Val v2)\n  | PairRCtx e1 => Pair e1 e\n  | FstCtx => Fst e\n  | SndCtx => Snd e\n  | InjLCtx => InjL e\n  | InjRCtx => InjR e\n  | CaseCtx e1 e2 => Case e e1 e2\n  | AllocCtx => Alloc e\n  | LoadCtx => Load e\n  | StoreLCtx v2 => Store e (Val v2)\n  | StoreRCtx e1 => Store e1 e\n  | CasLCtx v1 v2 => CAS e (Val v1) (Val v2)\n  | CasMCtx e0 v2 => CAS e0 e (Val v2)\n  | CasRCtx e0 e1 => CAS e0 e1 e\n  | FaaLCtx v2 => FAA e (Val v2)\n  | FaaRCtx e1 => FAA e1 e\n  end.\n\n(** Substitution *)\nFixpoint subst (x : string) (v : val) (e : expr)  : expr :=\n  match e with\n  | Val _ => e\n  | Var y => if decide (x = y) then Val v else Var y\n  | Rec f y e =>\n     Rec f y $ if decide (BNamed x ≠ f ∧ BNamed x ≠ y) then subst x v e else e\n  | App e1 e2 => App (subst x v e1) (subst x v e2)\n  | UnOp op e => UnOp op (subst x v e)\n  | BinOp op e1 e2 => BinOp op (subst x v e1) (subst x v e2)\n  | If e0 e1 e2 => If (subst x v e0) (subst x v e1) (subst x v e2)\n  | Pair e1 e2 => Pair (subst x v e1) (subst x v e2)\n  | Fst e => Fst (subst x v e)\n  | Snd e => Snd (subst x v e)\n  | InjL e => InjL (subst x v e)\n  | InjR e => InjR (subst x v e)\n  | Case e0 e1 e2 => Case (subst x v e0) (subst x v e1) (subst x v e2)\n  | Fork e => Fork (subst x v e)\n  | Alloc e => Alloc (subst x v e)\n  | Load e => Load (subst x v e)\n  | Store e1 e2 => Store (subst x v e1) (subst x v e2)\n  | CAS e0 e1 e2 => CAS (subst x v e0) (subst x v e1) (subst x v e2)\n  | FAA e1 e2 => FAA (subst x v e1) (subst x v e2)\n  end.\n\nDefinition subst' (mx : binder) (v : val) : expr → expr :=\n  match mx with BNamed x => subst x v | BAnon => id end.\n\n(** The stepping relation *)\nDefinition un_op_eval (op : un_op) (v : val) : option val :=\n  match op, v with\n  | NegOp, LitV (LitBool b) => Some $ LitV $ LitBool (negb b)\n  | NegOp, LitV (LitInt n) => Some $ LitV $ LitInt (Z.lnot n)\n  | MinusUnOp, LitV (LitInt n) => Some $ LitV $ LitInt (- n)\n  | NegOp, LitV (LitMachInt n) =>\n    LitV <$> (LitMachInt <$> to_mach_int (Z.lnot (`n)))\n  | MinusUnOp, LitV (LitMachInt n) =>\n    LitV <$> (LitMachInt <$> to_mach_int (- (`n)))\n  | _, _ => None\n  end.\n\nDefinition bin_op_eval_int (op : bin_op) (n1 n2 : Z) : base_lit :=\n  match op with\n  | PlusOp => LitInt (n1 + n2)\n  | MinusOp => LitInt (n1 - n2)\n  | MultOp => LitInt (n1 * n2)\n  | QuotOp => LitInt (n1 `quot` n2)\n  | RemOp => LitInt (n1 `rem` n2)\n  | AndOp => LitInt (Z.land n1 n2)\n  | OrOp => LitInt (Z.lor n1 n2)\n  | XorOp => LitInt (Z.lxor n1 n2)\n  | ShiftLOp => LitInt (n1 ≪ n2)\n  | ShiftROp => LitInt (n1 ≫ n2)\n  | LeOp => LitBool (bool_decide (n1 ≤ n2))\n  | LtOp => LitBool (bool_decide (n1 < n2))\n  | EqOp => LitBool (bool_decide (n1 = n2))\n  end.\n\nDefinition bin_op_eval_mach_int (op : bin_op) (n1 n2 : mach_int) : option base_lit :=\n  match op with\n  | PlusOp =>  LitMachInt <$> to_mach_int (`n1 + `n2)\n  | MinusOp => LitMachInt <$> to_mach_int (`n1 - `n2)\n  | MultOp => LitMachInt <$> to_mach_int (`n1 * `n2)\n  | QuotOp => LitMachInt <$> to_mach_int (`n1 `quot` `n2)\n  | RemOp => LitMachInt <$> to_mach_int (`n1 `rem` `n2)\n  | AndOp => LitMachInt <$> to_mach_int (Z.land (`n1) (`n2))\n  | OrOp => LitMachInt <$> to_mach_int (Z.lor (`n1) (`n2))\n  | XorOp => LitMachInt <$> to_mach_int (Z.lxor (`n1) (`n2))\n  | ShiftLOp => LitMachInt <$> to_mach_int (`n1 ≪ `n2)\n  | ShiftROp => LitMachInt <$> to_mach_int (`n1 ≫ `n2)\n  | LeOp => Some $ LitBool (bool_decide (`n1 ≤ `n2))\n  | LtOp => Some $ LitBool (bool_decide (`n1 < `n2))\n  | EqOp => Some $ LitBool (bool_decide (`n1 = `n2))\n  end.\n\nDefinition bin_op_eval_bool (op : bin_op) (b1 b2 : bool) : option base_lit :=\n  match op with\n  | PlusOp | MinusOp | MultOp | QuotOp | RemOp => None (* Arithmetic *)\n  | AndOp => Some (LitBool (b1 && b2))\n  | OrOp => Some (LitBool (b1 || b2))\n  | XorOp => Some (LitBool (xorb b1 b2))\n  | ShiftLOp | ShiftROp => None (* Shifts *)\n  | LeOp | LtOp => None (* InEquality *)\n  | EqOp => Some (LitBool (bool_decide (b1 = b2)))\n  end.\n\nDefinition bin_op_eval (op : bin_op) (v1 v2 : val) : option val :=\n  if decide (op = EqOp) then Some $ LitV $ LitBool $ bool_decide (v1 = v2) else\n  match v1, v2 with\n  | LitV (LitInt n1), LitV (LitInt n2) => Some $ LitV $ bin_op_eval_int op n1 n2\n  | LitV (LitMachInt n1), LitV (LitMachInt n2) => LitV <$> bin_op_eval_mach_int op n1 n2\n  | LitV (LitBool b1), LitV (LitBool b2) => LitV <$> bin_op_eval_bool op b1 b2\n  | _, _ => None\n  end.\n\n(** CAS just compares the word-sized representation of the two values, it cannot\nlook into boxed data.  This works out fine if at least one of the to-be-compared\nvalues is unboxed (exploiting the fact that an unboxed and a boxed value can\nnever be equal because these are disjoint sets).  *)\nDefinition vals_cas_compare_safe (vl v1 : val) : Prop :=\n  val_is_unboxed vl ∨ val_is_unboxed v1.\nArguments vals_cas_compare_safe !_ !_ /.\n\nInductive head_step : expr → state → list Empty_set → expr → state → list (expr) → Prop :=\n  | RecS f x e σ :\n     head_step (Rec f x e) σ [] (Val $ RecV f x e) σ []\n  | PairS v1 v2 σ :\n     head_step (Pair (Val v1) (Val v2)) σ [] (Val $ PairV v1 v2) σ []\n  | InjLS v σ :\n     head_step (InjL $ Val v) σ [] (Val $ InjLV v) σ []\n  | InjRS v σ :\n     head_step (InjR $ Val v) σ [] (Val $ InjRV v) σ []\n  | BetaS f x e1 v2 e' σ :\n     e' = subst' x v2 (subst' f (RecV f x e1) e1) →\n     head_step (App (Val $ RecV f x e1) (Val v2)) σ [] e' σ []\n  | UnOpS op v v' σ :\n     un_op_eval op v = Some v' →\n     head_step (UnOp op (Val v)) σ [] (Val v') σ []\n  | BinOpS op v1 v2 v' σ :\n     bin_op_eval op v1 v2 = Some v' →\n     head_step (BinOp op (Val v1) (Val v2)) σ [] (Val v') σ []\n  | IfTrueS e1 e2 σ :\n     head_step (If (Val $ LitV $ LitBool true) e1 e2) σ [] e1 σ []\n  | IfFalseS e1 e2 σ :\n     head_step (If (Val $ LitV $ LitBool false) e1 e2) σ [] e2 σ []\n  | FstS v1 v2 σ :\n     head_step (Fst (Val $ PairV v1 v2)) σ [] (Val v1) σ []\n  | SndS v1 v2 σ :\n     head_step (Snd (Val $ PairV v1 v2)) σ [] (Val v2) σ []\n  | CaseLS v e1 e2 σ :\n     head_step (Case (Val $ InjLV v) e1 e2) σ [] (App e1 (Val v)) σ []\n  | CaseRS v e1 e2 σ :\n     head_step (Case (Val $ InjRV v) e1 e2) σ [] (App e2 (Val v)) σ []\n  | ForkS e σ:\n     head_step (Fork e) σ [] (Val $ LitV LitUnit) σ [e]\n  | AllocS v σ l :\n     σ !! l = None →\n     head_step (Alloc $ Val v) σ []\n               (Val $ LitV $ LitLoc l) (<[l:=v]> σ)\n               []\n  | LoadS l v σ :\n     σ !! l = Some v →\n     head_step (Load (Val $ LitV $ LitLoc l)) σ [] (Val v) σ []\n  | StoreS l v σ :\n     is_Some (σ !! l) →\n     head_step (Store (Val $ LitV $ LitLoc l) (Val v)) σ []\n               (Val $ LitV LitUnit) (<[l:=v]> σ)\n               []\n  | CasFailS l v1 v2 vl σ :\n     σ !! l = Some vl → vl ≠ v1 →\n     vals_cas_compare_safe vl v1 →\n     head_step (CAS (Val $ LitV $ LitLoc l) (Val v1) (Val v2)) σ []\n               (Val $ LitV $ LitBool false) σ []\n  | CasSucS l v1 v2 σ :\n     σ !! l = Some v1 →\n     vals_cas_compare_safe v1 v1 →\n     head_step (CAS (Val $ LitV $ LitLoc l) (Val v1) (Val v2)) σ []\n               (Val $ LitV $ LitBool true) (<[l:=v2]> σ)\n               []\n  | FaaS l i1 i2 σ :\n     σ !! l = Some (LitV (LitInt i1)) →\n     head_step (FAA (Val $ LitV $ LitLoc l) (Val $ LitV $ LitInt i2)) σ []\n               (Val $ LitV $ LitInt i1) (<[l:=LitV (LitInt (i1 + i2))]> σ)\n               [].\n\n(** Basic properties about the language *)\nGlobal Instance fill_item_inj Ki : Inj (=) (=) (fill_item Ki).\nProof. destruct Ki; intros ???; simplify_eq/=; auto with f_equal. Qed.\n\nLemma fill_item_val Ki e :\n  is_Some (to_val (fill_item Ki e)) → is_Some (to_val e).\nProof. intros [v ?]. destruct Ki; simplify_option_eq; eauto. Qed.\n\nLemma val_head_stuck e1 σ1 κ e2 σ2 efs : head_step e1 σ1 κ e2 σ2 efs → to_val e1 = None.\nProof. destruct 1; naive_solver. Qed.\n\nLemma head_ctx_step_val Ki e σ1 κ e2 σ2 efs :\n  head_step (fill_item Ki e) σ1 κ e2 σ2 efs → is_Some (to_val e).\nProof. destruct Ki; inversion_clear 1; simplify_option_eq; by eauto. Qed.\n\nLemma fill_item_no_val_inj Ki1 Ki2 e1 e2 :\n  to_val e1 = None → to_val e2 = None →\n  fill_item Ki1 e1 = fill_item Ki2 e2 → Ki1 = Ki2.\nProof. destruct Ki1, Ki2; intros; by simplify_eq. Qed.\n\nLemma alloc_fresh v σ :\n  let l := fresh (dom (gset loc) σ) in\n  head_step (Alloc $ Val v) σ [] (Val $ LitV $ LitLoc l) (<[l:=v]> σ) [].\nProof. by intros; apply AllocS, (not_elem_of_dom (D:=gset loc)), is_fresh. Qed.\n\nLemma heap_lang_mixin : EctxiLanguageMixin of_val to_val fill_item head_step.\nProof.\n  split; apply _ || eauto using to_of_val, of_to_val, val_head_stuck,\n    fill_item_val, fill_item_no_val_inj, head_ctx_step_val.\nQed.\nEnd heap_lang.\n\n(** Language *)\nCanonical Structure heap_ectxi_lang := EctxiLanguage heap_lang.heap_lang_mixin.\nCanonical Structure heap_ectx_lang := EctxLanguageOfEctxi heap_ectxi_lang.\nCanonical Structure heap_lang := LanguageOfEctx heap_ectx_lang.\n\n(* Prefer heap_lang names over ectx_language names. *)\nExport heap_lang.\n\n(** Define some derived forms. *)\nNotation Lam x e := (Rec BAnon x e) (only parsing).\nNotation Let x e1 e2 := (App (Lam x e2) e1) (only parsing).\nNotation Seq e1 e2 := (Let BAnon e1 e2) (only parsing).\nNotation LamV x e := (RecV BAnon x e) (only parsing).\nNotation LetCtx x e2 := (AppRCtx (LamV x e2)) (only parsing).\nNotation SeqCtx e2 := (LetCtx BAnon e2) (only parsing).\nNotation Match e0 x1 e1 x2 e2 := (Case e0 (Lam x1 e1) (Lam x2 e2)) (only parsing).\n\n(* Skip should be atomic, we sometimes open invariants around\n   it. Hence, we need to explicitly use LamV instead of e.g., Seq. *)\nNotation Skip := (App (Val $ LamV BAnon (Val $ LitV LitUnit)) (Val $ LitV LitUnit)).\n", "meta": {"author": "Ricagraca", "repo": "i-splay-tree", "sha": "263215b780f52dd0168143def37be537bb07e0ea", "save_path": "github-repos/coq/Ricagraca-i-splay-tree", "path": "github-repos/coq/Ricagraca-i-splay-tree/i-splay-tree-263215b780f52dd0168143def37be537bb07e0ea/theories/heap_lang/lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.21146297412860118}}
{"text": "(* This file is part of the LLIR Semantics project. *)\n(* Licensing information is available in the LICENSE file. *)\n(* (C) 2020 Nandor Licker. All rights reserved. *)\n\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\n\nRequire Import LLIR.Maps.\nRequire Export LLIR.Values.\nRequire Export LLIR.Types.\n\nImport ListNotations.\n\n\n\nRecord object := mkobject\n  { obj_sizre : positive\n  ; obj_align: positive\n  }.\n\nInductive unop : Type :=\n  | LLSext\n  | LLZext\n  | LLFext\n  | LLXext\n  | LLTrunc\n  | LLNeg\n  | LLBitcast\n  .\n\nInductive binop : Type :=\n  | LLAdd\n  | LLSub\n  | LLMul\n  | LLUDiv\n  | LLSDiv\n  | LLURem\n  | LLSRem\n  | LLCmp\n  | LLSll\n  | LLSra\n  | LLSrl\n  | LLXor\n  | LLAnd\n  | LLOr\n  | LLRotl\n  | LLUAddO\n  | LLUMulO\n  .\n\nInductive inst : Type :=\n  | LLLd (dst: (ty * reg)) (next: node) (addr: reg)\n  | LLArg (dst: (ty * reg)) (next: node) (index: nat)\n  | LLInt (dst: reg) (next: node) (value: INT.t)\n  | LLSelect (dst: (ty * reg)) (next: node) (cond: reg) (vt: reg) (vf: reg)\n  | LLFrame (dst: reg) (next: node) (object: positive) (offset: nat)\n  | LLGlobal (dst: reg) (next: node) (segment: positive) (object: positive) (offset: nat)\n  | LLFunc (dst: reg) (next: node) (func: name)\n  | LLUndef (dst: (ty * reg)) (next: node)\n  | LLUnop (dst: (ty * reg)) (next: node) (op: unop) (arg: reg)\n  | LLBinop (dst: (ty * reg)) (next: node) (op: binop) (lhs: reg) (rhs: reg)\n  | LLMov (dst: (ty * reg)) (next: node) (src: reg)\n  | LLSyscall (dst: reg) (next: node) (sno: reg) (args: list reg)\n  | LLCall (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg)\n  | LLInvoke (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg) (exn: node)\n  | LLTCall (callee: reg) (args: list reg)\n  | LLTInvoke (callee: reg) (args: list reg) (exn: node)\n  | LLSt (next: node) (addr: reg) (value: reg)\n  | LLRet (value: option reg)\n  | LLJcc (cond: reg) (bt: node) (bf: node)\n  | LLJmp (target: node)\n  | LLTrap\n  .\n\nInductive phi : Type :=\n  | LLPhi (dst: (ty * reg)) (ins: list (node * reg))\n  .\n\nDefinition inst_map := PTrie.t inst.\nDefinition phi_map := PTrie.t (list phi).\n\nRecord func : Type := mkfunc\n  { fn_stack: PTrie.t object\n  ; fn_insts: inst_map\n  ; fn_phis: phi_map\n  ; fn_entry: node\n  }.\n\n\nDefinition prog : Type := PTrie.t func.\n\n\nInductive InstDefs: inst -> reg -> Prop :=\n  | defs_ld:\n    forall (t: ty) (dst: reg) (next: node) (addr: reg),\n      InstDefs (LLLd (t, dst) next addr) dst\n  | defs_arg:\n    forall (t: ty) (dst: reg) (next: node) (index: nat),\n      InstDefs (LLArg (t, dst) next index) dst\n  | defs_int:\n    forall (dst: reg) (next: node) (value: INT.t),\n      InstDefs (LLInt dst next value) dst\n  | defs_mov:\n    forall (t: ty) (dst: reg) (next: node) (src: reg),\n      InstDefs (LLMov (t, dst) next src) dst\n  | defs_select:\n    forall (t: ty) (dst: reg) (next: node) (cond: reg) (vt: reg) (vf: reg),\n      InstDefs (LLSelect (t, dst) next cond vt vf) dst\n  | defs_frame:\n    forall (dst: reg) (next: node) (object: positive) (offset: nat),\n      InstDefs (LLFrame dst next object offset) dst\n  | defs_global:\n    forall (dst: reg) (next: node) (segment: positive) (object: positive) (offset: nat),\n      InstDefs (LLGlobal dst next segment object offset) dst\n  | defs_func:\n    forall (dst: reg) (next: node) (id: name),\n      InstDefs (LLFunc dst next id) dst\n  | defs_undef:\n    forall (t: ty) (dst: reg) (next: node),\n      InstDefs (LLUndef (t, dst) next) dst\n  | defs_unop:\n    forall (t: ty) (dst: reg) (next: node) (op: unop) (arg: reg),\n      InstDefs (LLUnop (t, dst) next op arg) dst\n  | defs_binop:\n    forall (t: ty) (dst: reg) (next: node) (op: binop) (lhs: reg) (rhs: reg),\n      InstDefs (LLBinop (t, dst) next op lhs rhs) dst\n  | defs_syscall:\n    forall (dst: reg) (next: node) (sno: reg) (args: list reg),\n      InstDefs (LLSyscall dst next sno args) dst\n  | defs_call:\n    forall (t: ty) (dst: reg) (next: node) (callee: reg) (args: list reg),\n      InstDefs (LLCall (Some (t, dst)) next callee args) dst\n  | defs_invoke:\n    forall (t: ty) (dst: reg) (next: node) (callee: reg) (args: list reg) (exn: node),\n      InstDefs (LLInvoke (Some (t, dst)) next callee args exn) dst\n  .\n\n(* Returns the register defined by an instruction and its type. *)\nDefinition get_inst_ty_def (i: inst): option (ty * reg) :=\n  match i with\n  | LLSyscall dst _ _ _ => Some (sys_ret_ty, dst)\n  | LLCall dst _ _ _ => dst\n  | LLTCall _ _ => None\n  | LLInvoke dst _ _ _ _ => dst\n  | LLTInvoke _ _ _ => None\n\n  | LLArg dst _ _ => Some dst\n  | LLInt dst _ v =>\n    let t := match v with\n      | INT.Int8 _ => I8\n      | INT.Int16 _ => I16\n      | INT.Int32 _ => I32\n      | INT.Int64 _ => I64\n      end\n    in Some (TInt t, dst)\n  | LLMov dst _ _ => Some dst\n\n  | LLFrame dst _ _ _ => Some (ptr_ty, dst)\n  | LLGlobal dst _ _ _ _ => Some (ptr_ty, dst)\n  | LLFunc dst _ _ => Some (ptr_ty, dst)\n\n  | LLLd dst _ _ => Some dst\n  | LLUndef dst _ => Some dst\n  | LLUnop dst _ _ _ => Some dst\n  | LLBinop dst _ _ _ _ => Some dst\n  | LLSelect dst _ _ _ _ => Some dst\n\n  | LLSt _ _ _ => None\n  | LLRet _ => None\n  | LLJcc _ _ _ => None\n  | LLJmp _ => None\n  | LLTrap => None\n  end.\n\nDefinition get_inst_def (i: inst): option reg :=\n  option_map snd (get_inst_ty_def i).\n\nLemma get_inst_def_defs:\n  forall (i: inst) (r: reg),\n    get_inst_def i = Some r <-> InstDefs i r.\nProof.\n  intros i r; split; intros H.\n  {\n    destruct i;\n      try match goal with\n      | [ dst: option (ty * reg) |- _ ] => destruct dst\n      end;\n      try match goal with\n      | [ dst: ty * reg |- _ ] => destruct dst\n      end;\n      inversion H as [Hr];\n      try constructor.\n  }\n  {\n    inversion H; simpl; reflexivity.\n  }\nQed.\n\nInductive PhiDefs: phi -> reg -> Prop :=\n  | defs_phi:\n    forall (t: ty) (dst: reg) (ins: list (node * reg)),\n      PhiDefs (LLPhi (t, dst) ins) dst\n  .\n\nInductive InstUses: inst -> reg -> Prop :=\n  | uses_ld:\n    forall (dst: (ty * reg)) (next: node) (addr: reg),\n      InstUses (LLLd dst next addr) addr\n  | uses_mov:\n    forall (dst: (ty * reg)) (next: node) (src: reg),\n      InstUses (LLMov dst next src) src\n  | uses_select_cond:\n    forall (dst: (ty * reg)) (next: node) (cond: reg) (vt: reg) (vf: reg),\n      InstUses (LLSelect dst next cond vt vf) cond\n  | uses_select_true:\n    forall (dst: (ty * reg)) (next: node) (cond: reg) (vt: reg) (vf: reg),\n      InstUses (LLSelect dst next cond vt vf) vt\n  | uses_select_false:\n    forall (dst: (ty * reg)) (next: node) (cond: reg) (vt: reg) (vf: reg),\n      InstUses (LLSelect dst next cond vt vf) vf\n  | uses_unop:\n    forall (dst: (ty * reg)) (next: node) (op: unop) (arg: reg),\n      InstUses (LLUnop dst next op arg) arg\n  | uses_binop_lhs:\n    forall (dst: (ty * reg)) (next: node) (op: binop) (lhs: reg) (rhs: reg),\n      InstUses (LLBinop dst next op lhs rhs) lhs\n  | uses_binop_rhs:\n    forall (dst: (ty * reg)) (next: node) (op: binop) (lhs: reg) (rhs: reg),\n      InstUses (LLBinop dst next op lhs rhs) rhs\n  | uses_syscall_sno:\n    forall (dst: reg) (next: node) (sno: reg) (args: list reg),\n      InstUses (LLSyscall dst next sno args) sno\n  | uses_syscall_arg:\n    forall (dst: reg) (next: node) (sno: reg) (arg: reg) (args: list reg)\n      (ARG: In arg args),\n      InstUses (LLSyscall dst next sno args) arg\n  | uses_call_callee:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg),\n      InstUses (LLCall dst next callee args) callee\n  | uses_call_arg:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (arg: reg) (args: list reg)\n      (ARG: In arg args),\n      InstUses (LLCall dst next callee args) arg\n  | uses_invoke_callee:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg) (exn: node),\n      InstUses (LLInvoke dst next callee args exn) callee\n  | uses_invoke_arg:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (arg: reg) (args: list reg) (exn: node)\n      (ARG: In arg args),\n      InstUses (LLInvoke dst next callee args exn) arg\n  | uses_tcall_callee:\n    forall (callee: reg) (args: list reg),\n      InstUses (LLTCall callee args) callee\n  | uses_tcall_arg:\n    forall (callee: reg) (arg: reg) (args: list reg)\n      (ARG: In arg args),\n      InstUses (LLTCall callee args) arg\n  | uses_tinvoke_callee:\n    forall (callee: reg) (args: list reg) (exn: node),\n      InstUses (LLTInvoke callee args exn) callee\n  | uses_tinvoke_arg:\n    forall (callee: reg) (arg: reg) (args: list reg) (exn: node)\n      (ARG: In arg args),\n      InstUses (LLTInvoke callee args exn) arg\n  | uses_st_addr:\n    forall (next: node) (addr: reg) (val: reg),\n      InstUses (LLSt next addr val) addr\n  | uses_st_val:\n    forall (next: node) (addr: reg) (val: reg),\n      InstUses (LLSt next addr val) val\n  | uses_ret:\n    forall (value: reg),\n      InstUses (LLRet (Some value)) value\n  | uses_jcc:\n    forall (cond: reg) (bt: node) (bf: node),\n      InstUses (LLJcc cond bt bf) cond\n  .\n\n(* Returns the list of registers used by an instruction. *)\nDefinition get_inst_uses (i: inst): list reg :=\n  match i with\n  | LLLd _ _ addr => [addr]\n  | LLArg _ _ _ => []\n  | LLInt _ _ _ => []\n  | LLSelect _ _ cond vt vf => [cond; vt; vf]\n  | LLFrame _ _ _ _ => []\n  | LLGlobal _ _ _ _ _ => []\n  | LLFunc _ _ _ => []\n  | LLUndef _ _ => []\n  | LLUnop _ _ _ arg => [arg]\n  | LLBinop _ _ _ lhs rhs => [lhs; rhs]\n  | LLMov _ _ src => [src]\n  | LLSyscall _ _ sno args => sno :: args\n  | LLCall _ _ callee args => callee :: args\n  | LLInvoke _ _ callee args _ => callee :: args\n  | LLTCall callee args => callee :: args\n  | LLTInvoke callee args _ => callee :: args\n  | LLSt _ addr value => [addr; value]\n  | LLRet value =>\n    match value with\n    | None => []\n    | Some reg => [reg]\n    end\n  | LLJcc cond _ _ => [cond]\n  | LLJmp _ => []\n  | LLTrap => []\n  end.\n\nLemma get_inst_uses_uses:\n  forall (i: inst) (r: reg),\n    In r (get_inst_uses i) <-> InstUses i r.\nProof.\n  intros i r; split; intros H.\n  {\n    destruct i; simpl in H;\n      repeat match goal with\n      | [ H: False |- _ ] => inversion H\n      | [ H: _ \\/ _ |- _ ] => destruct H\n      end; \n      subst; try constructor; auto;\n      destruct value; inversion H; subst; try constructor; inversion H0.\n  }\n  {\n    inversion H; subst; simpl; auto.\n  }\nQed.\n\nInductive PhiUses: phi -> node -> reg -> Prop :=\n  | phi_uses:\n    forall (dst: (ty * reg)) (ins: list (node * reg)) (n: node) (r: reg)\n      (ARG: In (n, r) ins),\n      PhiUses (LLPhi dst ins) n r\n  .\n\nDefinition PhiBlockUses (phis: list phi) (n: node) (r: reg): Prop :=\n  Exists (fun phi => PhiUses phi n r) phis.\n\nInductive Succeeds: inst -> node -> Prop :=\n  | succ_arg:\n    forall (dst: (ty * reg)) (next: node) (index: nat),\n      Succeeds (LLArg dst next index) next\n  | succ_int:\n    forall (dst: reg) (next: node) (value: INT.t),\n      Succeeds (LLInt dst next value) next\n  | succ_frame:\n    forall (dst: reg) (next: node) (object: positive) (offset: nat),\n      Succeeds (LLFrame dst next object offset) next\n  | succ_global:\n    forall (dst: reg) (next: node) (segment: positive) (object: positive) (offset: nat),\n      Succeeds (LLGlobal dst next segment object offset) next\n  | succ_func:\n    forall (dst: reg) (next: node) (id: name),\n      Succeeds (LLFunc dst next id) next\n  | succ_undef:\n    forall (dst: (ty * reg)) (next: node),\n      Succeeds (LLUndef dst next) next\n  | succ_ld:\n    forall (dst: (ty * reg)) (next: node) (addr: reg),\n      Succeeds (LLLd dst next addr) next\n  | succ_mov:\n    forall (dst: (ty * reg)) (next: node) (src: reg),\n      Succeeds (LLMov dst next src) next\n  | succ_select:\n    forall (dst: (ty * reg)) (next: node) (cond: reg) (vt: reg) (vf: reg),\n      Succeeds (LLSelect dst next cond vt vf) next\n  | succ_unop:\n    forall (dst: (ty * reg)) (next: node) (op: unop) (arg: reg),\n      Succeeds (LLUnop dst next op arg) next\n  | succ_binop:\n    forall (dst: (ty * reg)) (next: node) (op: binop) (lhs: reg) (rhs: reg),\n      Succeeds (LLBinop dst next op lhs rhs) next\n  | succ_syscall:\n    forall (dst: reg) (next: node) (sno: reg) (args: list reg),\n      Succeeds (LLSyscall dst next sno args) next\n  | succ_call:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg),\n      Succeeds (LLCall dst next callee args) next\n  | succ_invoke_next:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg) (exn: node),\n      Succeeds (LLInvoke dst next callee args exn) next\n  | succ_invoke_exn:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg) (exn: node),\n      Succeeds (LLInvoke dst next callee args exn) exn\n  | succ_tinvoke:\n    forall (callee: reg) (args: list reg) (exn: node),\n      Succeeds (LLTInvoke callee args exn) exn\n  | succ_st:\n    forall (next: node) (addr: reg) (val: reg),\n      Succeeds (LLSt next addr val) next\n  | succ_jcc_true:\n    forall (cond: reg) (bt: node) (bf: node),\n      Succeeds (LLJcc cond bt bf) bt\n  | succ_jcc_false:\n    forall (cond: reg) (bt: node) (bf: node),\n      Succeeds (LLJcc cond bt bf) bf\n  | succ_jmp:\n    forall (target: node),\n      Succeeds (LLJmp target) target\n  .\n\nDefinition is_terminator (i: inst): bool :=\n  match i with\n  | LLLd _ _ _ => false\n  | LLArg _ _ _ => false\n  | LLInt _ _ _ => false\n  | LLMov _ _ _ => false\n  | LLFrame _ _ _ _ => false\n  | LLFunc _ _ _ => false\n  | LLGlobal _ _ _ _ _ => false\n  | LLUndef _ _ => false\n  | LLUnop _ _ _ _ => false\n  | LLBinop _ _ _ _ _ => false\n  | LLSelect _ _ _ _ _ => false\n  | LLSyscall _ _ _ _ => true\n  | LLCall _ _ _ _ => true\n  | LLInvoke _ _ _ _ _ => true\n  | LLTCall _ _ => true\n  | LLTInvoke _ _ _ => true\n  | LLSt next _ _ => false\n  | LLRet _ => true\n  | LLJcc _ _ _ => true\n  | LLJmp _ => true\n  | LLTrap => true\n  end.\n\nDefinition has_effect (i: inst): bool :=\n  match i with\n  | LLLd _ _ _ => false\n  | LLArg _ _ _ => false\n  | LLInt _ _ _ => false\n  | LLMov _ _ _ => false\n  | LLFrame _ _ _ _ => false\n  | LLFunc _ _ _ => false\n  | LLGlobal _ _ _ _ _ => false\n  | LLUndef _ _ => false\n  | LLUnop _ _ _ _ => false\n  | LLBinop _ _ _ _ _ => false\n  | LLSelect _ _ _ _ _ => false\n  | LLSyscall _ _ _ _ => true\n  | LLCall _ _ _ _ => true\n  | LLInvoke _ _ _ _ _ => true\n  | LLTCall _ _ => true\n  | LLTInvoke _ _ _ => true\n  | LLSt next _ _ => true\n  | LLRet _ => false\n  | LLJcc _ _ _ => false\n  | LLJmp _ => false\n  | LLTrap => true\n  end.\n\nInductive Terminator: inst -> Prop :=\n  | term_ret:\n    forall (ret: option reg),\n      Terminator (LLRet ret)\n  | term_jcc:\n    forall (cond: reg) (bt: node) (bf: node),\n      Terminator (LLJcc cond bt bf)\n  | term_jmp:\n    forall (target: node),\n      Terminator (LLJmp target)\n  | term_trap:\n    Terminator LLTrap\n  | term_syscall:\n    forall (dst: reg) (next: node) (sno: reg) (args: list reg),\n      Terminator (LLSyscall dst next sno args)\n  | term_call:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg),\n      Terminator (LLCall dst next callee args)\n  | term_tcall:\n    forall (callee: reg) (args: list reg),\n      Terminator (LLTCall callee args)\n  | term_tinvoke:\n    forall (callee: reg) (args: list reg) (exn: node),\n      Terminator (LLTInvoke callee args exn)\n  | term_invoke:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg) (exn: node),\n      Terminator (LLInvoke dst next callee args exn)\n  .\n\nInductive Callee: inst -> reg -> Prop :=\n  | callee_call:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg),\n      Callee (LLCall dst next callee args) callee\n  | callee_invoke:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg) (exn: node),\n      Callee (LLInvoke dst next callee args exn) callee\n  | callee_tcall:\n    forall (callee: reg) (args: list reg),\n      Callee (LLTCall callee args) callee\n  | callee_tinvoke:\n    forall (callee: reg) (args: list reg) (exn: node),\n      Callee (LLTInvoke callee args exn) callee\n  .\n\nInductive VoidCallSite: inst -> Prop :=\n  | void_site_call:\n    forall (next: node) (callee: reg) (args: list reg),\n      VoidCallSite (LLCall None next callee args)\n  | void_site_invoke:\n    forall (next: node) (callee: reg) (args: list reg) (exn: node),\n      VoidCallSite (LLInvoke None next callee args exn)\n  .\n\nInductive CallSite: inst -> ty -> reg -> Prop :=\n  | call_site_call:\n    forall (t: ty) (dst: reg) (next: node) (callee: reg) (args: list reg),\n      CallSite (LLCall (Some (t, dst)) next callee args) t dst\n  | call_site_invoke:\n    forall (t: ty) (dst: reg) (next: node) (callee: reg) (args: list reg) (exn: node),\n      CallSite (LLInvoke (Some (t, dst)) next callee args exn) t dst\n  .\n\nInductive ReturnAddress: inst -> node -> Prop :=\n  | ret_addr_call:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg),\n      ReturnAddress (LLCall dst next callee args) next\n  | ret_addr_invoke:\n    forall (dst: option (ty * reg)) (next: node) (callee: reg) (args: list reg) (exn: node),\n      ReturnAddress (LLInvoke dst next callee args exn) next\n  .\n\nLemma is_terminator_terminator:\n  forall (i: inst),\n    is_terminator i = true <-> Terminator i.\nProof.\n  intros i. split; intros H; destruct i; try inversion H; constructor.\nQed.\n\nDefinition is_exit (i: inst): bool :=\n  match i with\n  | LLLd _ _ _ => false\n  | LLArg _ _ _ => false\n  | LLInt _ _ _ => false\n  | LLMov _ _ _ => false\n  | LLFrame _ _ _ _ => false\n  | LLFunc _ _ _ => false\n  | LLGlobal _ _ _ _ _ => false\n  | LLUndef _ _ => false\n  | LLUnop _ _ _ _ => false\n  | LLBinop _ _ _ _ _ => false\n  | LLSelect _ _ _ _ _ => false\n  | LLSyscall _ _ _ _ => false\n  | LLCall _ _ _ _ => false\n  | LLInvoke _ _ _ _ _ => false\n  | LLTCall _ _ => true\n  | LLTInvoke _ _ _ => false\n  | LLSt next _ _ => false\n  | LLRet _ => true\n  | LLJcc _ _ _ => false\n  | LLJmp _ => false\n  | LLTrap => true\n  end.\n\nInductive Exit: inst -> Prop :=\n  | exit_ret:\n    forall (ret: option reg),\n      Exit (LLRet ret)\n  | exit_trap:\n    Exit LLTrap\n  | exit_tcall:\n    forall (callee: reg) (args: list reg),\n      Exit (LLTCall callee args)\n  .\n\nLemma is_exit_exit:\n  forall (i: inst),\n    is_exit i = true <-> Exit i.\nProof.\n  intros i.\n  split; intros H.\n  + destruct i; simpl in H; inversion H; constructor.\n  + inversion H; simpl; reflexivity.\nQed.\n\nDefinition get_successors (i: inst) :=\n  match i with\n  | LLLd _ next _ => [next]\n  | LLArg _ next _ => [next]\n  | LLInt _ next _ => [next]\n  | LLMov _ next _ => [next]\n  | LLFrame _ next _ _ => [next]\n  | LLFunc _ next _ => [next]\n  | LLGlobal _ next _ _ _ => [next]\n  | LLUndef _ next => [next]\n  | LLUnop _ next _ _ => [next]\n  | LLBinop _ next _ _ _ => [next]\n  | LLSelect _ next _ _ _ => [next]\n  | LLSyscall _ next _ _ => [next]\n  | LLCall _ next _ _ => [next]\n  | LLInvoke _ next _ _ exn => [next; exn]\n  | LLTCall _ _ => []\n  | LLTInvoke _ _ exn => [exn]\n  | LLSt next _ _ => [next]\n  | LLRet _ => []\n  | LLJcc _ bt bf => [bt;bf]\n  | LLJmp target => [target]\n  | LLTrap => []\n  end.\n\nLemma get_successors_correct:\n  forall (i: inst) (succ: node),\n    In succ (get_successors i) <-> Succeeds i succ.\nProof.\n  split; intros H.\n  {\n    unfold get_successors in H.\n    destruct i; repeat destruct H as [H|H];\n    subst; try inversion H; constructor.\n  }\n  {\n    inversion H; simpl; auto.\n  }\nQed.\n\nSection FUNCTION.\n  Variable f: func.\n\n  Inductive SuccOf: node -> node -> Prop :=\n    | succ_of:\n        forall (n: node) (m: node) (i: inst)\n          (HN: Some i = f.(fn_insts) ! n)\n          (HM: None <> f.(fn_insts) ! m)\n          (SUCC: Succeeds i m),\n          SuccOf n m.\n\n  Lemma SuccOf_succ_dec:\n    forall (n: node),\n      {exists m, SuccOf n m} + {~exists m, SuccOf n m}.\n  Proof.\n    intros n.\n    destruct (f.(fn_insts) ! n) as [inst|] eqn:Einst.\n    {\n      remember (get_successors inst) as succs eqn:Esuccs.\n      destruct inst; simpl in Esuccs;\n        try match goal with\n        | [ Esuccs: succs = [?succ]\n          , Einst: (fn_insts f) ! n = Some ?inst \n          |- _ ] =>\n            destruct (fn_insts f) ! succ as [inst'|] eqn:Esucc;\n              [ left; exists succ; apply succ_of with inst;\n                [ auto\n                | intros contra; rewrite Esucc in contra; inversion contra\n                | constructor\n                ]\n              | right; intros contra; destruct contra as [next' Hnext]; \n                inversion Hnext; subst;\n                rewrite Einst in HN; inversion HN; subst i;\n                apply get_successors_correct in SUCC; simpl in SUCC; \n                destruct SUCC; auto;\n                subst next';\n                rewrite Esucc in HM;\n                contradiction\n              ]\n        | [ Esuccs: succs = [] |- _ ] =>\n          right; intros contra; destruct contra as [next' Hnext];\n          inversion Hnext; subst;\n          rewrite Einst in HN; inversion HN; subst i;\n          apply get_successors_correct in SUCC; simpl in SUCC;\n          contradiction\n        | [ Esuccs: succs = [?succ0; ?succ1]\n          , Einst: (fn_insts f) ! n = Some ?inst\n          |- _ ] =>\n            destruct (fn_insts f) ! succ0 as [inst0|] eqn:Einst0;\n              [ left; exists succ0; apply succ_of with inst;\n                [ auto\n                | intros contra; rewrite Einst0 in contra; inversion contra\n                | constructor\n                ]\n              | destruct (fn_insts f) ! succ1 as [inst1|] eqn:Einst1;\n                [ left; exists succ1; apply succ_of with inst;\n                  [ auto\n                  | intros contra; rewrite Einst1 in contra; inversion contra\n                  | constructor\n                  ]\n                | right; intros contra; destruct contra as [next' Hnext];\n                  inversion Hnext; subst;\n                  rewrite Einst in HN; inversion HN; subst i;\n                  apply get_successors_correct in SUCC; simpl in SUCC;\n                  repeat destruct SUCC as [SUCC|SUCC]; subst;\n                  try rewrite Einst0 in HM;\n                  try rewrite Einst1 in HM;\n                  contradiction\n                ]\n            ]\n        end.\n    }\n    {\n      right.\n      intros contra; destruct contra as [m contra]; inversion contra.\n      rewrite Einst in HN; inversion HN.\n    }\n  Qed.\n\n  Definition get_predecessors (n: node) :=\n    match f.(fn_insts) ! n with\n    | None => []\n    | Some _ =>\n      PTrie.keys\n        (PTrie.filter (fun k v =>\n          let succs := get_successors v in\n          List.existsb (fun succ => Pos.eqb succ n) succs\n        ) f.(fn_insts))\n    end.\n\n  Lemma get_predecessors_correct:\n    forall (n: node) (pred: node),\n      In pred (get_predecessors n) <-> SuccOf pred n.\n  Proof.\n    intros n pred; split.\n    {\n      intros Hin.\n      unfold get_predecessors in Hin.\n      destruct ((fn_insts f) ! n) eqn:Einst.\n      {\n        apply PTrie.keys_inversion in Hin.\n        destruct Hin as [k Hin].\n        apply PTrie.map_opt_inversion in Hin.\n        destruct Hin as [inst [Hinst Hpred]].\n        apply succ_of with (i := inst); auto.\n        { intros contra. rewrite Einst in contra. inversion contra. }\n        {\n          unfold get_successors in Hpred. unfold existsb in Hpred.\n          destruct inst; simpl;\n            repeat match goal with\n            | [ H: context [ Pos.eqb ?v n ] |- _ ] =>\n              destruct (Pos.eqb v n) eqn:E;\n              simpl in H;\n              [apply Pos.eqb_eq in E; subst; constructor|clear E]\n            | [ H: Some ?v = None |- _ ] =>\n              inversion H\n            end.\n        }\n      }\n      {\n        inversion Hin.\n      }\n    }\n    {\n      intros Hsucc.\n      inversion Hsucc.\n      destruct ((fn_insts f) ! n) as [inst'|] eqn:En; try contradiction.\n      unfold get_predecessors.\n      rewrite En. subst. clear HM.\n      apply PTrie.keys_correct with (v := i).\n      apply PTrie.filter_correct; auto.\n      apply List.existsb_exists. exists n.\n      split; [|apply Pos.eqb_eq; reflexivity].\n      destruct i; inversion SUCC; simpl; auto.\n    }\n  Qed.\n\n  Lemma SuccOf_pred_dec:\n    forall (m: node),\n      {exists n, SuccOf n m} + {~exists n, SuccOf n m}.\n  Proof.\n    intros m.\n    destruct ((fn_insts f) ! m) as [inst_m|] eqn:Einst_m.\n    {\n      remember (get_predecessors m) as preds eqn:Epreds.\n      destruct preds.\n      {\n        right; intros contra; destruct contra as [n Hsucc].\n        apply get_predecessors_correct in Hsucc.\n        rewrite <- Epreds in Hsucc.\n        inversion Hsucc.\n      }\n      {\n        left; exists k. \n        apply get_predecessors_correct.\n        rewrite <- Epreds.\n        left; auto.\n      }\n    }\n    {\n      right; intros contra; destruct contra as [n Hsucc]; inversion Hsucc;\n      rewrite Einst_m in HM; contradiction.\n    }\n  Qed.\n\n  Inductive InstDefinedAt: node -> reg -> Prop :=\n    | inst_defined_at:\n      forall (n: node) (r: reg) (i: inst)\n        (INST: Some i = f.(fn_insts) ! n)\n        (DEFS: InstDefs i r),\n        InstDefinedAt n r\n    .\n\n  Inductive PhiDefinedAt: node -> reg -> Prop :=\n    | phi_defined_at:\n      forall (n: node) (r: reg) (phis: list phi)\n        (PHIS: Some phis = f.(fn_phis) ! n)\n        (DEFS: Exists (fun phi => PhiDefs phi r) phis),\n        PhiDefinedAt n r\n    .\n\n  Inductive DefinedAt: node -> reg -> Prop :=\n    | defined_at_inst:\n      forall (n: node) (r: reg) (DEF: InstDefinedAt n r),\n        DefinedAt n r\n    | defined_at_phi:\n      forall (n: node) (r: reg) (DEF: PhiDefinedAt n r),\n        DefinedAt n r\n    .\n\n  Lemma inst_defined_at_dec:\n    forall (n: node) (r: reg),\n      {InstDefinedAt n r} + {~InstDefinedAt n r}.\n  Proof.\n    intros n r.\n    destruct ((fn_insts f) ! n) as [inst|] eqn:Einst.\n    {\n      destruct (get_inst_def inst) as [dst|] eqn:Edst.\n      {\n        destruct (Pos.eq_dec dst r) as [Eq|Ne].\n        {\n          subst r. left. apply inst_defined_at with (i := inst); auto.\n          apply get_inst_def_defs; auto.\n        }\n        {\n          right; intros contra; inversion contra.\n          rewrite Einst in INST; inversion INST; subst i.\n          apply get_inst_def_defs in DEFS.\n          rewrite Edst in DEFS; inversion DEFS.\n          contradiction.\n        }\n      }\n      {\n        right; intros contra; inversion contra.\n        apply get_inst_def_defs in DEFS.\n        rewrite Einst in INST; inversion INST; subst i.\n        rewrite Edst in DEFS; inversion DEFS.\n      }\n    }\n    {\n      right; intros contra; inversion contra.\n      rewrite Einst in INST; inversion INST.\n    }\n  Qed.\n\n  Lemma phi_defs_dec:\n    forall (p: phi) (r: reg),\n      {PhiDefs p r} + {~PhiDefs p r}.\n  Proof.\n    intros p r. destruct p; destruct dst.\n    destruct (Pos.eq_dec p r); subst.\n    - left; constructor.\n    - right; intros contra; inversion contra; contradiction.\n  Qed.\n\n  Lemma phi_defined_at_dec:\n    forall (n: node) (r: reg),\n      {PhiDefinedAt n r} + {~PhiDefinedAt n r}.\n  Proof.\n    intros n r.\n    destruct ((fn_phis f) ! n) as [phis|] eqn:Ephis.\n    {\n      destruct (Exists_dec (fun phi => PhiDefs phi r) phis).\n      {\n        intros phi.\n        generalize (phi_defs_dec phi r); intros Hdec; destruct Hdec; auto.\n      }\n      {\n        left. apply phi_defined_at with phis; auto.\n      }\n      {\n        right; intros contra; inversion contra.\n        rewrite Ephis in PHIS; inversion PHIS; subst.\n        contradiction.\n      }\n    }\n    {\n      right; intros contra; inversion contra.\n      rewrite Ephis in PHIS; inversion PHIS.\n    }\n  Qed.\n\n  Lemma defined_at_dec:\n    forall (n: node) (r: reg),\n      {DefinedAt n r} + {~DefinedAt n r}.\n  Proof.\n    intros n r.\n    destruct (inst_defined_at_dec n r).\n    - left; apply defined_at_inst; auto.\n    - destruct (phi_defined_at_dec n r).\n      + left; apply defined_at_phi; auto.\n      + right; intros contra; inversion contra; contradiction.\n  Qed.\n\n  Inductive InstUsedAt: node -> reg -> Prop :=\n    | inst_used_at:\n      forall (n: node) (r: reg) (i: inst)\n        (INST: Some i = f.(fn_insts) ! n)\n        (USES: InstUses i r),\n        InstUsedAt n r.\n\n  Inductive PhiUsedAt: node -> reg -> Prop :=\n    | phi_used_at:\n      forall (n: node) (r: reg) (block: node) (phis: list phi)\n        (SUCC: SuccOf n block)\n        (PHIS: Some phis = f.(fn_phis) ! block)\n        (USES: PhiBlockUses phis n r),\n        PhiUsedAt n r\n    .\n\n  Inductive UsedAt: node -> reg -> Prop :=\n    | used_at_inst:\n      forall (n: node) (r: reg) (USE: InstUsedAt n r),\n        UsedAt n r\n    | used_at_phi:\n      forall (n: node) (r: reg) (USE: PhiUsedAt n r),\n        UsedAt n r\n    .\n\n  Lemma inst_used_at_dec:\n    forall (n: node) (r: reg),\n      {InstUsedAt n r} + {~InstUsedAt n r}.\n  Proof.\n    intros n r.\n    destruct ((fn_insts f) ! n) as [inst|] eqn:Einst.\n    {\n      destruct (in_dec Pos.eq_dec r (get_inst_uses inst)) as [In|NotIn].\n      {\n        left; apply inst_used_at with inst; auto.\n        apply get_inst_uses_uses; auto.\n      }\n      {\n        right; intros contra; inversion contra; subst.\n        apply get_inst_uses_uses in USES.\n        rewrite Einst in INST; inversion INST; subst.\n        contradiction.\n      }\n    }\n    {\n      right; intros contra; inversion contra; subst;\n      rewrite Einst in INST; inversion INST.\n    }\n  Qed.\n\n  Lemma phi_in_dec:\n    forall (a: (node * reg)) (b: (node * reg)),\n      {a = b} + {a <> b}.\n  Proof.\n    destruct a as [an ar]; destruct b as [bn br].\n    destruct (Pos.eq_dec an bn);\n    destruct (Pos.eq_dec ar br);\n    subst; \n    try (left; reflexivity);\n    right; intros contra; inversion contra; subst; contradiction.\n  Qed.\n\n  Lemma phi_uses_dec:\n    forall (p: phi) (n: node) (r: reg),\n      {PhiUses p n r} + {~PhiUses p n r}.\n  Proof.\n    destruct p; intros n r.\n    destruct (in_dec phi_in_dec (n, r) ins) as [Ein|Enot_in].\n    {\n      left; constructor; auto.\n    }\n    {\n      right; intros contra; inversion contra; subst; contradiction.\n    }\n  Qed.\n\n  Lemma phi_block_uses_dec:\n    forall (phis: list phi) (n: node) (r: reg),\n      {PhiBlockUses phis n r} + {~PhiBlockUses phis n r}.\n  Proof.\n    induction phis; intros n r.\n    { right; intros contra; inversion contra. }\n    {\n      destruct (IHphis n r) as [Ein|Enot_in].\n      {\n        left; apply Exists_exists.\n        apply Exists_exists in Ein; inversion Ein; destruct H.\n        exists x; split; auto; right; auto.\n      }\n      {\n        destruct (phi_uses_dec a n r) as [Epin|Enot_pin].\n        {\n          left; apply Exists_exists; exists a; split; auto.\n          left; reflexivity.\n        }\n        {\n          right; intros contra.\n          inversion contra; try contradiction.\n        }\n      }\n    }\n  Qed.\n\n  Lemma phi_used_at_dec:\n    forall (n: node) (r:reg),\n      {PhiUsedAt n r} + {~PhiUsedAt n r}.\n  Proof.\n    intros n r.\n    destruct ((fn_insts f) ! n) as [inst_n|] eqn:Esome_inst_n.\n    {\n      remember (get_successors inst_n) as succ_n eqn:Esucc_n.\n      destruct inst_n eqn:Einst_n; simpl in Esucc_n;\n        try match goal with\n        | [ Esucc_n: succ_n = [?next] |- _ ] =>\n          destruct ((fn_phis f) ! next) as [phis_next|] eqn:Ephis_next;\n          [ destruct ((fn_insts f) ! next) as [inst_next|] eqn:Einst_next;\n            [ destruct (phi_block_uses_dec phis_next n r) as [Euse|Eno_use];\n              [ left; apply phi_used_at with next phis_next; auto;\n                apply succ_of with inst_n; subst; auto; try constructor;\n                intros contra; rewrite Einst_next in contra; inversion contra\n              | right; intros contra; inversion contra;\n                inversion SUCC; apply get_successors_correct in SUCC0;\n                rewrite Esome_inst_n in HN; inversion HN; clear HN; subst;\n                simpl in SUCC0;\n                repeat destruct SUCC0 as [SUCC0|SUCC0]; subst; try contradiction;\n                rewrite Ephis_next in PHIS; inversion PHIS; subst;\n                contradiction\n              ]\n            | right; intros contra; inversion contra; inversion SUCC;\n              rewrite Esome_inst_n in HN; inversion HN; clear HN; subst;\n              apply get_successors_correct in SUCC0; simpl in SUCC0;\n              repeat destruct SUCC0 as [SUCC0|SUCC0]; subst; try contradiction;\n              rewrite Einst_next in HM; contradiction\n            ]\n          | right; intros contra; inversion contra; inversion SUCC; subst;\n            rewrite Esome_inst_n in HN; inversion HN; subst;\n            apply get_successors_correct in SUCC0; simpl in SUCC0;\n            repeat destruct SUCC0 as [SUCC0|SUCC0]; subst; try contradiction;\n            rewrite Ephis_next in PHIS; inversion PHIS\n          ]\n        | [ Esucc_n: succ_n = [] |- _ ] =>\n          right; intros contra; inversion contra; inversion SUCC; subst;\n          rewrite Esome_inst_n in HN; inversion HN; subst;\n          apply get_successors_correct in SUCC0; subst; simpl in SUCC0;\n          contradiction\n        | [ Esucc_n: succ_n = [?s0; ?s1] |- _ ] =>\n          destruct ((fn_phis f) ! s0) as [phis_s0|] eqn:Ephis_s0;\n          destruct ((fn_phis f) ! s1) as [phis_s1|] eqn:Ephis_s1;\n          destruct ((fn_insts f) ! s0) as [inst_s0|] eqn:Einst_s0;\n          destruct ((fn_insts f) ! s1) as [inst_s1|] eqn:Einst_s1;\n          try destruct (phi_block_uses_dec phis_s0 n r) as [Euse_s0|Eno_use_s0];\n          try destruct (phi_block_uses_dec phis_s1 n r) as [Euse_s1|Eno_use_s1];\n          try match goal with\n          | [ Hphi: (fn_phis f) ! ?s0 = Some ?phis\n            , Hinst: (fn_insts f) ! ?s0 = Some _\n            , Hblock_use: PhiBlockUses ?phis n r \n            |- _ \n            ] =>\n            left;\n            apply phi_used_at with s0 phis; auto;\n            apply succ_of with inst_n;\n              [ subst; auto\n              | intros contra; rewrite Hinst in contra; inversion contra\n              | subst inst_n; constructor\n              ]\n          end;\n          right; intros contra; inversion contra; inversion SUCC;\n          rewrite Esome_inst_n in HN; inversion HN; clear HN; subst;\n          inversion SUCC0; subst;\n          match goal with\n          | [ Hinst: (fn_insts f) ! ?n = None, Hnone: None <> (fn_insts f) ! ?n |- _ ] =>\n            rewrite Hinst in Hnone; contradiction\n          | [ Hphi0: (fn_phis f) ! ?n = _, Hphi1: _ = (fn_phis f) ! ?n |- _ ] =>\n            rewrite Hphi0 in Hphi1; inversion Hphi1; clear Hphi1; subst; contradiction\n          end\n        end.\n    }\n    {\n      right; intros contra; inversion contra; inversion SUCC;\n      rewrite Esome_inst_n in HN; inversion HN.\n    }\n  Qed.\n\n  Inductive TermAt: node -> Prop :=\n    | term_at:\n      forall (i: inst) (n: node)\n        (INST: Some i = f.(fn_insts) ! n)\n        (TERM: Terminator i),\n        TermAt n.\n\n  Lemma non_terminal_unique_successor:\n    forall (n: node) (s: node) (s': node),\n      ~TermAt n ->\n       SuccOf n s ->\n       SuccOf n s' ->\n       s = s'.\n  Proof.\n    intros n s s' Hterm Hsucc Hsucc'.\n    destruct ((fn_insts f) ! n) as [i|] eqn:Einst.\n    {\n      destruct i eqn:Ei;\n        try (\n          assert (TermAt n);\n          [apply term_at with i; subst; auto; constructor|];\n          contradiction\n        );\n        inversion Hsucc; inversion Hsucc';\n        rewrite Einst in HN; inversion HN; subst i0; clear HN; inversion SUCC;\n        rewrite Einst in HN0; inversion HN0; subst i1; clear HN0; inversion SUCC0;\n        subst; reflexivity.\n    }\n    {\n      inversion Hsucc; rewrite Einst in HN; inversion HN.\n    }\n  Qed.\n\n  Inductive ExitAt: node -> Prop :=\n    | exit_at:\n      forall (i: inst) (n: node)\n        (INST: Some i = f.(fn_insts) ! n)\n        (EXIT: Exit i),\n        ExitAt n.\n\n  Theorem exit_no_succ:\n    forall (n: node),\n      ExitAt n -> ~exists (m: node), SuccOf n m.\n  Proof.\n    intros n Hexit contra; destruct contra as [m Hsucc].\n    inversion Hexit.\n    inversion Hsucc.\n    rewrite <- INST in HN; inversion HN; subst.\n    inversion EXIT; subst; inversion SUCC; subst.\n  Qed.\nEnd FUNCTION.\n\n", "meta": {"author": "nandor", "repo": "llir-semantics", "sha": "0edb7dfdbea45d2dc5416522341dbd2c75abc20c", "save_path": "github-repos/coq/nandor-llir-semantics", "path": "github-repos/coq/nandor-llir-semantics/llir-semantics-0edb7dfdbea45d2dc5416522341dbd2c75abc20c/LLIR.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21146296831786504}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\n\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import msl.Axioms.\n\nRequire Import sepcomp.mem_lemmas.\nRequire Import sepcomp.semantics.\nRequire Import sepcomp.semantics_lemmas.\nRequire Import sepcomp.effect_semantics.\nRequire Import sepcomp.structured_injections.\nRequire Import sepcomp.reach.\nRequire Import sepcomp.effect_simulations.\n\nSection Eff_INJ_SIMU_DIAGRAMS.\n  Context {F1 V1 C1 F2 V2 C2:Type}\n          {Sem1 : @EffectSem (Genv.t F1 V1) C1}\n          {Sem2 : @EffectSem (Genv.t F2 V2) C2}\n\n          {ge1: Genv.t F1 V1}\n          {ge2: Genv.t F2 V2}.\n\n  Let core_data := C1.\n\n  Variable match_states: core_data -> SM_Injection -> C1 -> mem -> C2 -> mem -> Prop.\n\n   Hypothesis genvs_dom_eq: genvs_domain_eq ge1 ge2.\n\n   Hypothesis match_sm_wd: forall d mu c1 m1 c2 m2,\n          match_states d mu c1 m1 c2 m2 ->\n          SM_wd mu.\n\n    Hypothesis match_visible: forall d mu c1 m1 c2 m2,\n          match_states d mu c1 m1 c2 m2 ->\n          REACH_closed m1 (vis mu).\n\n    Hypothesis match_restrict: forall d mu c1 m1 c2 m2 X,\n          match_states d mu c1 m1 c2 m2 ->\n          (forall b, vis mu b = true -> X b = true) ->\n          REACH_closed m1 X ->\n          match_states d (restrict_sm mu X) c1 m1 c2 m2.\n\n   Hypothesis match_validblocks: forall d mu c1 m1 c2 m2,\n          match_states d mu c1 m1 c2 m2 ->\n          sm_valid mu m1 m2.\n\n    Hypothesis match_genv: forall d mu c1 m1 c2 m2 (MC:match_states d mu c1 m1 c2 m2),\n          meminj_preserves_globals ge1 (extern_of mu) /\\\n          (forall b, isGlobalBlock ge1 b = true -> frgnBlocksSrc mu b = true).\n\n   Hypothesis inj_initial_cores: forall v vals1 c1 m1 j vals2 m2 DomS DomT,\n          initial_core Sem1 ge1 v vals1 = Some c1 ->\n          Mem.inject j m1 m2 ->\n          Forall2 (val_inject j) vals1 vals2 ->\n          meminj_preserves_globals ge1 j ->\n\n        (*the next two conditions are required to guarantee intialSM_wd*)\n         (forall b1 b2 d, j b1 = Some (b2, d) ->\n                          DomS b1 = true /\\ DomT b2 = true) ->\n         (forall b, REACH m2 (fun b' => isGlobalBlock ge2 b' || getBlocks vals2 b') b = true -> DomT b = true) ->\n\n        (*the next two conditions ensure the initialSM satisfies sm_valid*)\n         (forall b, DomS b = true -> Mem.valid_block m1 b) ->\n         (forall b, DomT b = true -> Mem.valid_block m2 b) ->\n\n       exists c2,\n            initial_core Sem2 ge2 v vals2 = Some c2 /\\\n            match_states c1 (initial_SM DomS\n                                       DomT\n                                       (REACH m1 (fun b => isGlobalBlock ge1 b || getBlocks vals1 b))\n                                       (REACH m2 (fun b => isGlobalBlock ge2 b || getBlocks vals2 b)) j)\n                           c1 m1 c2 m2.\n\n  Hypothesis inj_halted : forall cd mu c1 m1 c2 m2 v1,\n      match_states cd mu c1 m1 c2 m2 ->\n      halted Sem1 c1 = Some v1 ->\n\n      exists v2,\n             Mem.inject (as_inj mu) m1 m2 /\\\n             val_inject (restrict (as_inj mu) (vis mu)) v1 v2 /\\\n             halted Sem2 c2 = Some v2.\n\n  Hypothesis inj_at_external :\n      forall mu c1 m1 c2 m2 e vals1,\n        match_states c1 mu c1 m1 c2 m2 ->\n        at_external Sem1 c1 = Some (e,vals1) ->\n        Mem.inject (as_inj mu) m1 m2 /\\\n          exists vals2,\n            Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2 /\\\n            at_external Sem2 c2 = Some (e,vals2)\n    /\\ forall\n       (pubSrc' pubTgt' : block -> bool)\n       (pubSrcHyp : pubSrc' =\n                  (fun b : block =>\n                  locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b))\n       (pubTgtHyp: pubTgt' =\n                  (fun b : block =>\n                  locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b))\n       nu (Hnu: nu = (replace_locals mu pubSrc' pubTgt')),\n       match_states c1 nu c1 m1 c2 m2\n       /\\ Mem.inject (shared_of nu) m1 m2.\n\nSection EFF_INJ_SIMULATION_STAR_WF.\nVariable order: C1 -> C1 -> Prop.\nHypothesis order_wf: well_founded order.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            ((effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n              (effstep_star Sem2 ge2 U2 st2 m2 st2' m2' /\\\n               order st1' st1)) /\\\n\n             forall\n               (UHyp: forall b z, U1 b z = true -> vis mu b = true)\n               b ofs (Ub: U2 b ofs = true),\n             visTgt mu b = true /\\\n                (locBlocksTgt mu b = false ->\n                 exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                 U1 b1 (ofs-delta1) = true /\\\n                 Mem.perm m1 b1 (ofs-delta1) Max Nonempty)).\n\nLemma  inj_simulation_star_wf:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply SM_simulation.Build_SM_simulation_inject with\n    (core_ord := order)\n    (match_state := fun d j c1 m1 c2 m2 => d = c1 /\\ match_states d j c1 m1 c2 m2).\n  apply order_wf.\nclear - match_sm_wd. intros. destruct H; subst. eauto.\nassumption.\nclear - match_genv. intros. destruct MC; subst. eauto.\nclear - match_visible. intros. destruct H; subst. eauto.\nclear - match_restrict. intros. destruct H; subst. eauto.\nclear - match_validblocks. intros.\n    destruct H; subst. eauto.\nclear - inj_initial_cores. intros.\n    destruct (inj_initial_cores _ _ _ _ _ _ _ _ _ H\n         H0 H1 H2 H3 H4 H5 H6)\n    as [c2 [INI MS]].\n  exists c1, c2. intuition.\nclear - inj_effcore_diagram.\n  intros. destruct H0; subst.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H1) as\n    [c2' [m2' [mu' [INC [SEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists st1'. exists mu'.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  split. split; trivial.\n  exists U2. split; assumption.\nclear - inj_halted. intros. destruct H; subst.\n  destruct (inj_halted _ _ _ _ _ _ _ H1 H0) as [v2 [INJ [VAL HH]]].\n  exists v2; intuition.\nclear - inj_at_external. intros. destruct H; subst.\n  destruct (inj_at_external _ _ _ _ _ _ _ H1 H0)\n    as [INJ [vals2 [VALS [AtExt2 SH]]]].\n  split. trivial. exists vals2. split; trivial. split; trivial.\n    intros. split. split. trivial. eapply SH; eassumption. eapply SH; eassumption.\nclear - inj_after_external. intros.\n  destruct MatchMu as [ZZ matchMu]. subst cd.\n  destruct (inj_after_external _ _ _ _ _ _ _ _ _\n      MemInjMu matchMu AtExtSrc AtExtTgt ValInjMu _\n      pubSrcHyp _ pubTgtHyp _ NuHyp _ _ _ _ _ INC SEP\n      WDnu' SMvalNu' MemInjNu' RValInjNu' FwdSrc FwdTgt\n      _ frgnSrcHyp _ frgnTgtHyp _ Mu'Hyp\n      UnchPrivSrc UnchLOOR)\n    as [st1' [st2' [AftExt1 [AftExt2 MS']]]].\n  exists st1', st1', st2'. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR_WF.\n\nSection EFF_INJ_SIMULATION_STAR_WF_TYPED.\nVariable order: C1 -> C1 -> Prop.\nHypothesis order_wf: well_founded order.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            ((effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n              (effstep_star Sem2 ge2 U2 st2 m2 st2' m2' /\\\n               order st1' st1)) /\\\n\n           forall\n             (UHyp: forall b z, U1 b z = true -> vis mu b = true)\n             b ofs(Ub: U2 b ofs = true),\n             visTgt mu b = true /\\\n             (locBlocksTgt mu b = false ->\n                exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                U1 b1 (ofs-delta1) = true /\\\n                Mem.perm m1 b1 (ofs-delta1) Max Nonempty)).\n\nLemma  inj_simulation_star_wf_typed:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply SM_simulation.Build_SM_simulation_inject with\n    (core_ord := order)\n    (match_state := fun d j c1 m1 c2 m2 => d = c1 /\\ match_states d j c1 m1 c2 m2).\n  apply order_wf.\nclear - match_sm_wd. intros. destruct H; subst. eauto.\nassumption.\nclear - match_genv. intros. destruct MC; subst. eauto.\nclear - match_visible. intros. destruct H; subst. eauto.\nclear - match_restrict. intros. destruct H; subst. eauto.\nclear - match_validblocks. intros.\n    destruct H; subst. eauto.\nclear - inj_initial_cores. intros.\n    destruct (inj_initial_cores _ _ _ _ _ _ _ _ _ H H0 H1 H2 H3 H4 H5 H6)\n    as [c2 [INI MS]].\n  exists c1, c2. intuition.\nclear - inj_effcore_diagram.\n  intros. destruct H0; subst.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H1) as\n    [c2' [m2' [mu' [INC [SEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists st1'. exists mu'.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  split. split; trivial.\n  exists U2. split; assumption.\nclear - inj_halted. intros. destruct H; subst.\n  destruct (inj_halted _ _ _ _ _ _ _ H1 H0) as [v2 [INJ [VAL HH]]].\n  exists v2; intuition.\nclear - inj_at_external. intros. destruct H; subst.\n  destruct (inj_at_external _ _ _ _ _ _ _ H1 H0)\n    as [INJ [vals2 [VALS [AtExt2 SH]]]].\n  split. trivial. exists vals2. split; trivial. split; trivial.\n    intros. split. split. trivial. eapply SH; eassumption. eapply SH; eassumption.\nclear - inj_after_external. intros.\n  destruct MatchMu as [ZZ matchMu]. subst cd.\n  destruct (inj_after_external _ _ _ _ _ _ _ _ _\n      MemInjMu matchMu AtExtSrc AtExtTgt ValInjMu _\n      pubSrcHyp _ pubTgtHyp _ NuHyp _ _ _ _ _ HasTy1 HasTy2 INC SEP\n      WDnu' SMvalNu' MemInjNu' RValInjNu' FwdSrc FwdTgt\n      _ frgnSrcHyp _ frgnTgtHyp _ Mu'Hyp\n      UnchPrivSrc UnchLOOR)\n    as [st1' [st2' [AftExt1 [AftExt2 MS']]]].\n  exists st1', st1', st2'. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR_WF_TYPED.\n\nSection EFF_INJ_SIMULATION_STAR.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\\n             forall\n               (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n               b ofs(Ub: U2 b ofs = true),\n             visTgt mu b = true /\\\n             (locBlocksTgt mu b = false ->\n                 exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                 U1 b1 (ofs-delta1) = true /\\\n                 Mem.perm m1 b1 (ofs-delta1) Max Nonempty).\n\nLemma inj_simulation_star:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply inj_simulation_star_wf.\n  apply  (well_founded_ltof _ measure).\n  apply inj_after_external.\n  clear - inj_effcore_diagram. intros.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H0)\n    as [c2' [m2' [mu' [INC [SEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists mu'.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  exists U2. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR.\n\nSection EFF_INJ_SIMULATION_STAR_TYPED.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\\n             forall\n               (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n               b ofs(Ub: U2 b ofs = true),\n              visTgt mu b = true /\\\n                (locBlocksTgt mu b = false ->\n                 exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                     U1 b1 (ofs-delta1) = true /\\\n                     Mem.perm m1 b1 (ofs-delta1) Max Nonempty).\n\nLemma inj_simulation_star_typed:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply inj_simulation_star_wf_typed.\n  apply  (well_founded_ltof _ measure).\n  intros. eapply inj_after_external with (mu := mu); eauto.\n  clear - inj_effcore_diagram. intros.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H0)\n    as [c2' [m2' [mu' [INC [SEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists mu'.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  exists U2. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR_TYPED.\n\nSection EFF_INJ_SIMULATION_PLUS.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\ forall\n                 (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n                 b ofs (Ub: U2 b ofs = true),\n                 visTgt mu b = true /\\\n                 (locBlocksTgt mu b = false ->\n                     exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                     U1 b1 (ofs-delta1) = true /\\\n                     Mem.perm m1 b1 (ofs-delta1) Max Nonempty).\n\nLemma inj_simulation_plus:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  apply inj_simulation_star with (measure:=measure); auto.\nQed.\n\nEnd EFF_INJ_SIMULATION_PLUS.\n\nSection EFF_INJ_SIMULATION_PLUS_TYPED.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\ forall\n                 (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n                  b ofs (Ub: U2 b ofs = true),\n                visTgt mu b = true /\\\n                (locBlocksTgt mu b = false ->\n                    exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                    U1 b1 (ofs-delta1) = true /\\\n                    Mem.perm m1 b1 (ofs-delta1) Max Nonempty).\n\nLemma inj_simulation_plus_typed:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  apply inj_simulation_star_typed with (measure:=measure); auto.\nQed.\n\nEnd EFF_INJ_SIMULATION_PLUS_TYPED.\n\nEnd Eff_INJ_SIMU_DIAGRAMS.\n\nDefinition compose_sm (mu1 mu2 : SM_Injection) : SM_Injection :=\n Build_SM_Injection\n   (locBlocksSrc mu1) (locBlocksTgt mu2)\n   (pubBlocksSrc mu1) (pubBlocksTgt mu2)\n   (compose_meminj (local_of mu1) (local_of mu2))\n   (extBlocksSrc mu1) (extBlocksTgt mu2)\n   (frgnBlocksSrc mu1) (frgnBlocksTgt mu2)\n   (compose_meminj (extern_of mu1) (extern_of mu2)).\n\nLemma compose_sm_valid: forall mu1 mu2 m1 m2 m2' m3\n          (SMV1: sm_valid mu1 m1 m2) (SMV2: sm_valid mu2 m2' m3),\n       sm_valid (compose_sm mu1 mu2) m1 m3.\nProof.  split. apply SMV1. apply SMV2. Qed.\n\nLemma compose_sm_pub: forall mu12 mu23\n         (HypPub: forall b, pubBlocksTgt mu12 b = true ->\n                            pubBlocksSrc mu23 b = true)\n         (WD1:SM_wd mu12),\n      pub_of (compose_sm mu12 mu23) =\n      compose_meminj (pub_of mu12) (pub_of mu23).\nProof. intros. unfold compose_sm, pub_of.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (pSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    destruct (pubSrc _ WD1 _ Heqd) as [b2 [d1 [LOC1 Tgt1]]]; simpl in *.\n    rewrite Heqd in LOC1. apply HypPub in Tgt1.\n    unfold compose_meminj. rewrite Heqd. rewrite LOC1. rewrite Tgt1.\n    trivial.\n  unfold compose_meminj.\n    rewrite Heqd. trivial.\nQed.\n\nLemma compose_sm_DomSrc: forall mu12 mu23,\n  DomSrc (compose_sm mu12 mu23) = DomSrc mu12.\nProof. intros. unfold compose_sm, DomSrc; simpl. trivial. Qed.\n\nLemma compose_sm_DomTgt: forall mu12 mu23,\n  DomTgt (compose_sm mu12 mu23) = DomTgt mu23.\nProof. intros. unfold compose_sm, DomTgt; simpl. trivial. Qed.\n\nLemma compose_sm_foreign: forall mu12 mu23\n         (HypFrg: forall b, frgnBlocksTgt mu12 b = true ->\n                            frgnBlocksSrc mu23 b = true)\n         (WD1:SM_wd mu12),\n      foreign_of (compose_sm mu12 mu23) =\n      compose_meminj (foreign_of mu12) (foreign_of mu23).\nProof. intros. unfold compose_sm, foreign_of.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (fSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    destruct (frgnSrc _ WD1 _ Heqd) as [b2 [d1 [EXT1 Tgt1]]]; simpl in *.\n    rewrite Heqd in EXT1. apply HypFrg in Tgt1.\n    unfold compose_meminj. rewrite Heqd. rewrite EXT1. rewrite Tgt1.\n    trivial.\n  unfold compose_meminj.\n    rewrite Heqd. trivial.\nQed.\n\nLemma compose_sm_priv: forall mu12 mu23,\n   priv_of (compose_sm mu12 mu23) =\n   compose_meminj (priv_of mu12) (local_of mu23).\nProof. intros. unfold priv_of, compose_sm.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (pSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    unfold compose_meminj. rewrite Heqd. trivial.\n  unfold compose_meminj.\n    rewrite Heqd. trivial.\nQed.\n\nLemma compose_sm_unknown: forall mu12 mu23,\n   unknown_of (compose_sm mu12 mu23) =\n   compose_meminj (unknown_of mu12) (extern_of mu23).\nProof. intros. unfold unknown_of, compose_sm.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (locBSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    unfold compose_meminj. rewrite Heqd. trivial.\n  remember (fSrc1 b) as q; destruct q; apply eq_sym in Heqq.\n    unfold compose_meminj. rewrite Heqd. rewrite Heqq. trivial.\n  unfold compose_meminj.\n    rewrite Heqd. rewrite Heqq. trivial.\nQed.\n\nLemma compose_sm_local: forall mu12 mu23,\n   local_of (compose_sm mu12 mu23) =\n   compose_meminj (local_of mu12) (local_of mu23).\nProof. intros. reflexivity. Qed.\n\nLemma compose_sm_extern: forall mu12 mu23,\n   extern_of (compose_sm mu12 mu23) =\n   compose_meminj (extern_of mu12) (extern_of mu23).\nProof. intros. reflexivity. Qed.\n\nLemma compose_sm_shared: forall mu12 mu23\n         (HypPub: forall b, pubBlocksTgt mu12 b = true ->\n                            pubBlocksSrc mu23 b = true)\n         (HypFrg: forall b, frgnBlocksTgt mu12 b = true ->\n                            frgnBlocksSrc mu23 b = true)\n         (WD1:SM_wd mu12) (WD2:SM_wd mu23),\n      shared_of (compose_sm mu12 mu23) =\n      compose_meminj (shared_of mu12) (shared_of mu23).\nProof. intros. unfold shared_of.\n  rewrite compose_sm_pub; trivial.\n  rewrite compose_sm_foreign; trivial.\n  unfold join, compose_meminj. extensionality b.\n  remember (foreign_of mu12 b) as f; destruct f; apply eq_sym in Heqf.\n    destruct p as [b2 d1].\n    destruct (foreign_DomRng _ WD1 _ _ _ Heqf) as [A [B [C [D [E [F [G H]]]]]]].\n    apply HypFrg in F.\n    destruct (frgnSrc _ WD2 _ F) as [b3 [d2 [FRG2 TGT2]]].\n    rewrite FRG2. trivial.\n  remember (pub_of mu12 b) as d; destruct d; apply eq_sym in Heqd; trivial.\n    destruct p as [b2 d1].\n    destruct (pub_locBlocks _ WD1 _ _ _ Heqd) as [A [B [C [D [E [F [G H]]]]]]].\n    apply HypPub in B.\n    destruct (pubSrc _ WD2 _ B) as [b3 [d2 [PUB2 TGT2]]].\n    rewrite PUB2.\n    apply (pubBlocksLocalSrc _ WD2) in B.\n    apply (locBlocksSrc_frgnBlocksSrc _ WD2) in B.\n    unfold foreign_of. destruct mu23. simpl in *. rewrite B. trivial.\nQed.\n\nLemma compose_sm_wd: forall mu1 mu2 (WD1: SM_wd mu1) (WD2:SM_wd mu2)\n         (HypPub: forall b, pubBlocksTgt mu1 b = true ->\n                            pubBlocksSrc mu2 b = true)\n         (HypFrg: forall b, frgnBlocksTgt mu1 b = true ->\n                            frgnBlocksSrc mu2 b = true),\n      SM_wd (compose_sm mu1 mu2).\nProof. intros.\n  destruct mu1 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu2 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\nsplit; simpl in *.\napply WD1.\napply WD2.\n(*local_DomRng*)\n  intros b1 b3 d H.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n    as [b2 [d1 [d2 [PUB1 [PUB2 X]]]]]; subst; clear H.\n  split. eapply WD1. apply PUB1.\n         eapply WD2. apply PUB2.\n(*extern_DomRng*)\n  intros b1 b3 d H.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n    as [b2 [d1 [d2 [EXT1 [EXT2 X]]]]]; subst; clear H.\n  split. eapply WD1. apply EXT1.\n         eapply WD2. apply EXT2.\n(*pubSrc*)\n  intros.\n  destruct (pubSrc _ WD1 _ H) as [b2 [d1 [Loc1 Tgt1]]]. simpl in *.\n  apply HypPub in Tgt1.\n  destruct (pubSrc _ WD2 _ Tgt1) as [b3 [d2 [Loc2 Tgt2]]]. simpl in *.\n  unfold compose_meminj. exists b3, (d1+d2).\n  rewrite H in *. rewrite Tgt1 in *. rewrite Loc1. rewrite Loc2. auto.\n(*frgnSrc*)\n  intros.\n  destruct (frgnSrc _ WD1 _ H) as [b2 [d1 [Ext1 Tgt1]]]. simpl in *.\n  apply HypFrg in Tgt1.\n  destruct (frgnSrc _ WD2 _ Tgt1) as [b3 [d2 [Ext2 Tgt2]]]. simpl in *.\n  unfold compose_meminj. exists b3, (d1+d2).\n  rewrite H in *. rewrite Tgt1 in *. rewrite Ext1. rewrite Ext2. auto.\n(*locBlocksDomTgt*)\n  apply WD2.\n(*frgnBlocksDomTgt*)\n  apply WD2.\nQed.\n\nLemma compose_sm_as_inj: forall mu12 mu23 (WD1: SM_wd mu12) (WD2: SM_wd mu23)\n   (SrcTgtLoc: locBlocksTgt mu12 = locBlocksSrc mu23)\n   (SrcTgtExt: extBlocksTgt mu12 = extBlocksSrc mu23),\n   as_inj (compose_sm mu12 mu23) =\n   compose_meminj (as_inj mu12) (as_inj mu23).\nProof. intros.\n  unfold as_inj.\n  rewrite compose_sm_extern.\n  rewrite compose_sm_local.\n  unfold join, compose_meminj. extensionality b.\n  remember (extern_of mu12 b) as f; destruct f; apply eq_sym in Heqf.\n    destruct p as [b2 d1].\n    remember (extern_of mu23 b2) as d; destruct d; apply eq_sym in Heqd.\n      destruct p as [b3 d2]. trivial.\n    destruct (disjoint_extern_local _ WD1 b).\n       rewrite H in Heqf. discriminate.\n    rewrite H.\n    destruct (extern_DomRng _ WD1 _ _ _ Heqf) as [A B].\n    rewrite SrcTgtExt in B.\n    remember (local_of mu23 b2) as q; destruct q; trivial; apply eq_sym in Heqq.\n    destruct p as [b3 d2].\n    destruct (local_DomRng _ WD2 _ _ _ Heqq) as [AA BB].\n    destruct (disjoint_extern_local_Src _ WD2 b2); congruence.\n  remember (local_of mu12 b) as q; destruct q; trivial; apply eq_sym in Heqq.\n    destruct p as [b2 d1].\n    destruct (local_DomRng _ WD1 _ _ _ Heqq) as [AA BB].\n    remember (extern_of mu23 b2) as d; destruct d; trivial; apply eq_sym in Heqd.\n      destruct p as [b3 d2].\n      destruct (extern_DomRng _ WD2 _ _ _ Heqd) as [A B].\n      rewrite SrcTgtLoc in BB.\n      destruct (disjoint_extern_local_Src _ WD2 b2); congruence.\nQed.\n\nLemma compose_sm_intern_incr:\n      forall mu12 mu12' mu23 mu23'\n            (inc12: intern_incr mu12 mu12')\n            (inc23: intern_incr mu23 mu23'),\n      intern_incr (compose_sm mu12 mu23) (compose_sm mu12' mu23').\nProof. intros.\nsplit; simpl in *.\n    eapply compose_meminj_inject_incr.\n        apply inc12.\n        apply intern_incr_local; eassumption.\nsplit. rewrite (intern_incr_extern _ _ inc12).\n       rewrite (intern_incr_extern _ _ inc23).\n       trivial.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\napply inc23.\nQed.\n\nLemma compose_sm_extern_incr:\n      forall mu12 mu12' mu23 mu23'\n            (inc12: extern_incr mu12 mu12')\n            (inc23: extern_incr mu23 mu23')\n  (FRG': forall b1 b2 d1, foreign_of mu12' b1 = Some(b2,d1) ->\n         exists b3 d2, foreign_of mu23' b2 = Some(b3,d2))\n  (WD12': SM_wd mu12') (WD23': SM_wd mu23'),\n  extern_incr (compose_sm mu12 mu23) (compose_sm mu12' mu23').\nProof. intros.\nsplit; intros.\n  rewrite compose_sm_extern.\n  rewrite compose_sm_extern.\n  eapply compose_meminj_inject_incr.\n    apply inc12.\n    apply extern_incr_extern; eassumption.\nsplit; simpl.\n  rewrite (extern_incr_local _ _ inc12).\n  rewrite (extern_incr_local _ _ inc23).\n  trivial.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\napply inc23.\nQed.\n\nLemma extern_incr_inject_incr:\n      forall nu12 nu23 nu' (WDnu' : SM_wd nu')\n          (EXT: extern_incr (compose_sm nu12 nu23) nu')\n          (GlueInvNu: SM_wd nu12 /\\ SM_wd nu23 /\\\n                      locBlocksTgt nu12 = locBlocksSrc nu23 /\\\n                      extBlocksTgt nu12 = extBlocksSrc nu23 /\\\n                      (forall b, pubBlocksTgt nu12 b = true ->\n                                 pubBlocksSrc nu23 b = true) /\\\n                      (forall b, frgnBlocksTgt nu12 b = true ->\n                                 frgnBlocksSrc nu23 b = true)),\n      inject_incr (compose_meminj (as_inj nu12) (as_inj nu23)) (as_inj nu').\nProof. intros.\n  intros b; intros.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n    as [b2 [d1 [d2 [Nu12 [Nu23 D]]]]]; subst; clear H.\n  unfold extern_incr in EXT. simpl in EXT.\n  destruct EXT as [EXT [LOC [extBSrc12 [extBTgt23 [locBSrc12 [locBTgt23 [pubBSrc12 [pubBTgt23 [frgnBSrc12 frgnBTgt23]]]]]]]]].\n  destruct (joinD_Some _ _ _ _ _ Nu12); clear Nu12.\n  (*extern12*)\n     destruct (joinD_Some _ _ _ _ _ Nu23); clear Nu23.\n     (*extern12*)\n        apply join_incr_left. apply EXT.\n        unfold compose_meminj. rewrite H. rewrite H0. trivial.\n     (*local*)\n        destruct H0.\n        destruct GlueInvNu as [GLa [GLb [GLc [GLd [GLe GLf]]]]].\n        destruct (extern_DomRng' _ GLa _ _ _ H) as [? [? [? [? [? [? [? ?]]]]]]].\n        destruct (local_locBlocks _ GLb _ _ _ H1) as [? [? [? [? [? [? [? ?]]]]]]].\n        rewrite GLd in *. congruence.\n  (*local*)\n     destruct H.\n     destruct (joinD_Some _ _ _ _ _ Nu23); clear Nu23.\n     (*extern12*)\n        destruct GlueInvNu as [GLa [GLb [GLc [GLd [GLe GLf]]]]].\n        destruct (extern_DomRng' _ GLb _ _ _ H1) as [? [? [? [? [? ?]]]]].\n        destruct (local_locBlocks _ GLa _ _ _ H0) as [? [? [? [? [? ?]]]]].\n        rewrite GLd in *. congruence.\n     (*local*)\n        destruct H1.\n        apply join_incr_right. eapply disjoint_extern_local. apply WDnu'.\n        rewrite <- LOC. unfold compose_meminj.\n        rewrite H0, H2. trivial.\nQed.\n\nLemma compose_sm_as_injD: forall mu1 mu2 b1 b3 d\n      (I: as_inj (compose_sm mu1 mu2) b1 = Some (b3, d))\n      (WD1: SM_wd mu1) (WD2: SM_wd mu2),\n      exists b2 d1 d2, as_inj mu1 b1 = Some(b2,d1) /\\\n                       as_inj mu2 b2 = Some(b3,d2) /\\\n                       d=d1+d2.\nProof. intros.\ndestruct (joinD_Some _ _ _ _ _ I); clear I.\n(*extern*)\n  rewrite compose_sm_extern in H.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n      as [b2 [d1 [d2 [EXT1 [EXT2 D]]]]]; clear H.\n  exists b2, d1, d2.\n  split. apply join_incr_left. assumption.\n  split. apply join_incr_left. assumption.\n         assumption.\n(*local*)\n  destruct H.\n  rewrite compose_sm_extern in H.\n  rewrite compose_sm_local in H0.\n  destruct (compose_meminjD_Some _ _ _ _ _ H0)\n      as [b2 [d1 [d2 [LOC1 [LOC2 D]]]]]; clear H0.\n  exists b2, d1, d2.\n  split. apply join_incr_right.\n           apply disjoint_extern_local; assumption.\n           assumption.\n  split. apply join_incr_right.\n           apply disjoint_extern_local; assumption.\n           assumption.\n         assumption.\nQed.\n\nLemma compose_sm_intern_separated:\n      forall mu12 mu12' mu23 mu23' m1 m2 m3\n        (inc12: intern_incr mu12 mu12')\n        (inc23: intern_incr mu23 mu23')\n        (InjSep12 : sm_inject_separated mu12 mu12' m1 m2)\n        (InjSep23 : sm_inject_separated mu23 mu23' m2 m3)\n        (WD12: SM_wd mu12) (WD12': SM_wd mu12') (WD23: SM_wd mu23) (WD23': SM_wd mu23')\n        (BlocksLoc: locBlocksTgt mu12 = locBlocksSrc mu23)\n        (BlocksExt: extBlocksTgt mu12 = extBlocksSrc mu23),\n      sm_inject_separated (compose_sm mu12 mu23)\n                          (compose_sm mu12' mu23') m1 m3.\nProof. intros.\ndestruct InjSep12 as [AsInj12 [DomTgt12 Sep12]].\ndestruct InjSep23 as [AsInj23 [DomTgt23 Sep23]].\nsplit.\n  intros b1 b3 d; intros.\n  simpl.\n  destruct (compose_sm_as_injD _ _ _ _ _ H0)\n     as [b2 [d1 [d2 [AI12' [AI23' X]]]]]; subst; trivial; clear H0.\n  rewrite compose_sm_DomSrc, compose_sm_DomTgt.\n  assert (DomSrc (compose_sm mu12' mu23') b1 = true /\\\n          DomTgt (compose_sm mu12' mu23') b3 = true).\n    rewrite compose_sm_DomSrc, compose_sm_DomTgt.\n    split. eapply as_inj_DomRng; eassumption.\n           eapply as_inj_DomRng; eassumption.\n  destruct H0 as [DOM1 TGT3]; simpl in *.\n  assert (TGT2: DomTgt mu12' b2 = true).\n    eapply as_inj_DomRng. eassumption. eapply WD12'.\n  assert (DOMB2: DomSrc mu23' b2 = true).\n    eapply as_inj_DomRng. eassumption. eapply WD23'.\n  rewrite compose_sm_DomSrc, compose_sm_DomTgt in *.\n  remember (as_inj mu12 b1) as q.\n  destruct q; apply eq_sym in Heqq.\n    destruct p.\n    specialize (intern_incr_as_inj _ _ inc12 WD12' _ _ _ Heqq); intros.\n    rewrite AI12' in H0. apply eq_sym in H0. inv H0.\n    destruct (joinD_Some _ _ _ _ _ Heqq); clear Heqq.\n    (*extern12Some*)\n       assert (extern_of mu12' b1 = Some (b2, d1)).\n          rewrite <- (intern_incr_extern _ _ inc12). assumption.\n       destruct (joinD_None _ _ _ H); clear H.\n       clear AI12'.\n       destruct (joinD_Some _ _ _ _ _ AI23'); clear AI23'.\n       (*extern23'Some*)\n         assert (extern_of mu23 b2 = Some (b3, d2)).\n           rewrite (intern_incr_extern _ _ inc23). assumption.\n         rewrite compose_sm_extern in H2.\n         unfold compose_meminj in H2.\n         rewrite H0 in H2. rewrite H4 in H2. inv H2.\n       (*extern23'None*)\n         destruct H.\n         rewrite compose_sm_extern in H2.\n         destruct (compose_meminjD_None _ _ _ H2); clear H2.\n            rewrite H5 in H0. discriminate.\n         destruct H5 as [bb2 [dd1 [EXT12 EXT23]]].\n         rewrite EXT12 in H0. inv H0.\n         rewrite compose_sm_local in H3.\n         remember (local_of mu23 b2) as qq.\n         destruct qq; apply eq_sym in Heqqq.\n            destruct p.\n            specialize (intern_incr_local _ _ inc23); intros.\n            specialize (H0 _ _ _ Heqqq). rewrite H0 in H4. inv H4.\n            destruct (extern_DomRng _ WD12 _ _ _ EXT12) as [A B].\n            destruct (local_DomRng _ WD23 _ _ _ Heqqq) as [AA BB].\n            rewrite BlocksExt in B.\n            destruct (disjoint_extern_local_Src _ WD23 b2); congruence.\n         destruct (AsInj23 b2 b3 d2).\n            apply joinI_None. assumption. assumption.\n            apply join_incr_right.\n              apply disjoint_extern_local. assumption.\n              assumption.\n         destruct (extern_DomRng _ WD12 _ _ _ EXT12) as [XX YY].\n           rewrite BlocksExt in YY. unfold DomSrc in H0.\n           rewrite YY in H0. rewrite orb_comm in H0. discriminate.\n    (*extern12None*)\n       destruct H0.\n       assert (extern_of mu12' b1 = None).\n          rewrite <- (intern_incr_extern _ _ inc12). assumption.\n       assert (local_of mu12' b1 = Some (b2, d1)).\n          eapply (intern_incr_local _ _ inc12). assumption.\n       destruct (joinD_None _ _ _ H); clear H.\n       clear AI12'.\n       destruct (joinD_Some _ _ _ _ _ AI23'); clear AI23'.\n       (*extern23'Some*)\n         destruct (local_DomRng _ WD12' _ _ _ H3) as [AA BB].\n         destruct (extern_DomRng _ WD23' _ _ _ H) as [A B].\n         destruct (local_DomRng _ WD12 _ _ _ H1) as [AAA BBB].\n         rewrite BlocksLoc in BBB.\n         assert (locBlocksSrc mu23' b2 = true). apply inc23. assumption.\n         destruct (disjoint_extern_local_Src _ WD23' b2); congruence.\n       (*extern23'None*)\n         destruct H.\n         assert (extern_of mu23 b2 = None).\n           rewrite (intern_incr_extern _ _ inc23). assumption.\n         rewrite compose_sm_local in H5.\n         unfold compose_meminj in H5. rewrite H1 in H5.\n         remember (local_of mu23 b2).\n         destruct o. destruct p. inv H5. clear H5. apply eq_sym in Heqo.\n         clear H4.\n         destruct (local_DomRng _ WD12 _ _ _ H1) as [AA BB].\n         assert (DomSrc mu23 b2 = false /\\ DomTgt mu23 b3 = false).\n            eapply AsInj23.\n              apply joinI_None; assumption.\n              apply join_incr_right; try eassumption.\n                apply disjoint_extern_local; eassumption.\n         destruct H4.\n         destruct (local_locBlocks _ WD12 _ _ _ H1)\n           as [AAA [BBB [CCC [DDD [EEE FFF]]]]].\n         rewrite BlocksLoc in BBB. unfold DomSrc in H4.\n             rewrite BBB in H4. discriminate.\n   (*as_inj mu12 b1 = None*)\n     destruct (AsInj12 _ _ _ Heqq AI12'). split; trivial. clear H.\n     remember (as_inj mu23 b2) as d.\n     destruct d; apply eq_sym in Heqd.\n       destruct p.\n       specialize (intern_incr_as_inj _ _ inc23 WD23' _ _ _ Heqd).\n       intros ZZ; rewrite AI23' in ZZ. apply eq_sym in ZZ; inv ZZ.\n       destruct (as_inj_DomRng _ _ _ _ Heqd WD23).\n       unfold DomSrc in H. unfold DomTgt in H1.\n       rewrite BlocksLoc, BlocksExt in H1. rewrite H1 in H; discriminate.\n     eapply AsInj23. eassumption. eassumption.\nsimpl.\n  split. apply DomTgt12. apply Sep23.\nQed.\n\nLemma vis_compose_sm: forall mu nu, vis (compose_sm mu nu) = vis mu.\nProof. intros. unfold vis. destruct mu; simpl. reflexivity. Qed.\n\nLemma restrict_compose: forall j k X,\n  restrict (compose_meminj j k) X = compose_meminj (restrict j X) k.\nProof. intros.\n  extensionality b.\n  unfold compose_meminj, restrict.\n  remember (X b) as d.\n  destruct d; trivial.\nQed.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/sepcomp/effect_simulations_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.211462968317865}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*                       mCertiKOS C Source Code                       *)\n(*                                                                     *)\n(*                        Xiongnan (Newman) Wu                         *)\n(*                                                                     *)\n(*                          Yale University                            *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Cop.\nRequire Import Clight.\nRequire Import CDataTypes.\nRequire Import Ctypes.\n\n\n\n(** \n<<\n      #define NUM_PROC 64\n\n      extern void set_cr3 (char ** );\n\n      extern char * PTPool_LOC[NUM_PROC][1024];\n\n      void set_pt(unsigned int index)\n      {\n          set_cr3(PTPool_LOC[index]);\n      }\n>>\n *)\n\nLet tsetpt_index: ident := 1 % positive.\n\nDefinition set_pt_body : statement := \n  (Scall None\n  (Evar set_cr3 (Tfunction (Tcons (tptr tvoid) Tnil) tvoid cc_default))\n  ((Ederef\n     (Ebinop Oadd (Evar PTPool_LOC (tarray (tarray (tptr tchar) 1024) 64))\n       (Etempvar tsetpt_index tint) (tptr (tarray (tptr tchar) 1024)))\n     (tarray (tptr tchar) 1024)) :: nil))\n.\n\nDefinition f_set_pt := {|\n                        fn_return := Tvoid;\n                        fn_callconv := cc_default;\n                        fn_vars := nil;\n                        fn_params := ((tsetpt_index, tint) :: nil);\n                        fn_temps := nil;\n                        fn_body := set_pt_body\n                      |}.\n\n\n\n(**\n<<\n      #define NUM_PROC 64\n\n      extern char * PTPool_LOC[NUM_PROC][1024];\n\n      unsigned int get_PDE(unsigned int proc_index, unsigned int pde_index)\n      {\n          unsigned int pde;\n          pde = (unsigned int)PTPool_LOC[proc_index][pde_index] / 4096;\n          return pde;\n      }\n>>\n *)\n\nLet tproc_index: ident := 1 % positive.\nLet tpde_index: ident := 2 % positive.\nLet tpde: ident := 3 % positive.\n\n\nDefinition get_PDE_body : statement := \n  (Ssequence\n     (Sset tpde\n           (Ebinop Odiv\n                   (Ecast\n                      (Ederef\n                         (Ebinop Oadd\n                                 (Ederef\n                                    (Ebinop Oadd\n                                            (Evar PTPool_LOC (tarray (tarray (tptr tchar) 1024) 64))\n                                            (Etempvar tproc_index tint)\n                                            (tptr (tarray (tptr tchar) 1024)))\n                                    (tarray (tptr tchar) 1024)) (Etempvar tpde_index tint)\n                                 (tptr (tptr tchar))) (tptr tchar)) tint)\n                   (Econst_int (Int.repr 4096) tint) tint))\n     (Sreturn (Some (Etempvar tpde tint))))\n.\n\nDefinition f_get_PDE := {|\n                         fn_return := tint;\n                         fn_callconv := cc_default;\n                         fn_params := ((tproc_index, tint) :: (tpde_index, tint) :: nil);\n                         fn_vars := nil;\n                         fn_temps := ((tpde, tint) :: nil);\n                         fn_body := get_PDE_body\n                       |}.\n\n\n\n(** \n<<\n     #define NUM_PROC 64\n     #define PT_PERM_PTU 7\n\n     extern char * PTPool_LOC[NUM_PROC][1024];\n     extern unsigned int IDPMap_LOC[1024][1024];\n\n     void set_PDE(unsigned int proc_index, unsigned int pde_index)\n     {\n         PTPool_LOC[proc_index][pde_index] = ((char * )(IDPMap_LOC[pde_index])) + PT_PERM_PTU;\n     }\n>>\n *)\n\nDefinition set_pde_body: statement :=\n  (Sassign\n  (Ederef\n    (Ebinop Oadd\n      (Ederef\n        (Ebinop Oadd\n          (Evar PTPool_LOC (tarray (tarray (tptr tchar) 1024) 64))\n          (Etempvar tproc_index tint) (tptr (tarray (tptr tchar) 1024)))\n        (tarray (tptr tchar) 1024)) (Etempvar tpde_index tint)\n      (tptr (tptr tchar))) (tptr tchar))\n  (Ebinop Oadd\n    (Ecast\n      (Ederef\n        (Ebinop Oadd (Evar IDPMap_LOC (tarray (tarray tint 1024) 1024))\n          (Etempvar tpde_index tint) (tptr (tarray tint 1024)))\n        (tarray tint 1024)) (tptr tchar)) (Econst_int (Int.repr 7) tint)\n    (tptr tchar))).\n\nDefinition f_set_pde := {|\n                         fn_return := Tvoid;\n                         fn_callconv := cc_default;\n                         fn_vars := nil;\n                         fn_params := ((tproc_index, tint) :: (tpde_index, tint) :: nil);\n                         fn_temps := nil;\n                         fn_body := set_pde_body\n                       |}.\n\n\n(** \n<<\n     #define NUM_PROC 64\n     #define PT_PERM_UP 0\n\n     extern char * PTPool_LOC[NUM_PROC][1024];\n\n     void rmv_PDE(unsigned int proc_index, unsigned int pde_index)\n     {\n         PTPool_LOC[proc_index][pde_index] = (char * )PT_PERM_UP;\n     }\n>>\n *)\n\nDefinition rmv_pde_body: statement :=\n  (Sassign\n  (Ederef\n    (Ebinop Oadd\n      (Ederef\n        (Ebinop Oadd\n          (Evar PTPool_LOC (tarray (tarray (tptr tchar) 1024) 64))\n          (Etempvar tproc_index tint) (tptr (tarray (tptr tchar) 1024)))\n        (tarray (tptr tchar) 1024)) (Etempvar tpde_index tint)\n      (tptr (tptr tchar))) (tptr tchar))\n  (Ecast (Econst_int (Int.repr 0) tint) (tptr tchar))).\n\nDefinition f_rmv_pde := {|\n                         fn_return := Tvoid;\n                         fn_callconv := cc_default;\n                         fn_vars := nil;\n                         fn_params := ((tproc_index, tint) :: (tpde_index, tint) :: nil);\n                         fn_temps := nil;\n                         fn_body := rmv_pde_body\n                       |}.\n\n\n\n(** \n<<\n     #define NUM_PROC 64\n     #define PT_PERM_PTU 7\n\n     extern char * PTPool_LOC[NUM_PROC][1024];\n\n     void set_PDEU(unsigned int proc_index, unsigned int pde_index, unsigned int pi)\n     {\n         PTPool_LOC[proc_index][pde_index] = (char * )(pi * 4096 + PT_PERM_PTU);\n     }\n>>\n *)\n\nLet tpi: ident := 4 % positive.\n\nDefinition set_pdeu_body: statement :=\n  (Sassign\n  (Ederef\n    (Ebinop Oadd\n      (Ederef\n        (Ebinop Oadd\n          (Evar PTPool_LOC (tarray (tarray (tptr tchar) 1024) 64))\n          (Etempvar tproc_index tint) (tptr (tarray (tptr tchar) 1024)))\n        (tarray (tptr tchar) 1024)) (Etempvar tpde_index tint)\n      (tptr (tptr tchar))) (tptr tchar))\n  (Ecast\n    (Ebinop Oadd\n      (Ebinop Omul (Etempvar tpi tint) (Econst_int (Int.repr 4096) tint)\n        tint) (Econst_int (Int.repr 7) tint) tint) (tptr tchar))).\n\nDefinition f_set_pdeu := {|\n                         fn_return := Tvoid;\n                         fn_callconv := cc_default;\n                         fn_vars := nil;\n                         fn_params := ((tproc_index, tint) :: (tpde_index, tint) :: (tpi, tint) :: nil);\n                         fn_temps := nil;\n                         fn_body := set_pdeu_body\n                       |}.\n\n\n\n(** \n<<\n     #define NUM_PROC 64\n     #define PT_PERM_PTU 7\n\n     extern char * PTPool_LOC[NUM_PROC][1024];\n     extern unsigned int fload(unsigned int);\n\n     unsigned int get_PTE(unsigned int proc_index, unsigned int pde_index, unsigned int vadr)\n     {\n         unsigned int pte;\n         unsigned int offset;\n         offset = ((unsigned int)PTPool_LOC[proc_index][pde_index] - PT_PERM_PTU) / 4096;\n         pte = fload(offset * 1024 + vadr);\n         return pte;\n     }\n>>\n *)\n\nLet tpte: ident := 5 % positive.\nLet toffset: ident := 6 % positive.\nLet tvadr: ident := 7 % positive.\n\nDefinition get_pte_body: statement :=\n  (Ssequence\n  (Sset toffset\n    (Ebinop Odiv\n      (Ebinop Osub\n        (Ecast\n          (Ederef\n            (Ebinop Oadd\n              (Ederef\n                (Ebinop Oadd\n                  (Evar PTPool_LOC (tarray (tarray (tptr tchar) 1024) 64))\n                  (Etempvar tproc_index tint)\n                  (tptr (tarray (tptr tchar) 1024)))\n                (tarray (tptr tchar) 1024)) (Etempvar tpde_index tint)\n              (tptr (tptr tchar))) (tptr tchar)) tint)\n        (Econst_int (Int.repr 7) tint) tint)\n      (Econst_int (Int.repr 4096) tint) tint))\n  (Ssequence\n    (Ssequence\n      (Scall (Some 13%positive)\n        (Evar fload (Tfunction (Tcons tint Tnil) tint cc_default))\n        ((Ebinop Oadd\n           (Ebinop Omul (Etempvar toffset tint)\n             (Econst_int (Int.repr 1024) tint) tint) (Etempvar tvadr tint)\n           tint) :: nil))\n      (Sset tpte (Etempvar 13%positive tint)))\n      (Sreturn (Some (Etempvar tpte tint))))).\n\nDefinition f_get_pte := {|\n                         fn_return := tint;\n                         fn_callconv := cc_default;\n                         fn_vars := nil;\n                         fn_params := ((tproc_index, tint) :: (tpde_index, tint) :: (tvadr, tint) :: nil);\n                         fn_temps := (toffset, tint) :: (tpte, tint) :: (13%positive, tint) :: nil;\n                         fn_body := get_pte_body\n                       |}.\n\n\n\n(** \n<<\n     #define NUM_PROC 64\n     #define PT_PERM_PTU 7\n\n     extern char * PTPool_LOC[NUM_PROC][1024];\n     extern void fstore(unsigned int, unsigned int);\n\n     void set_PTE(unsigned int proc_index, unsigned int pde_index, unsigned int vadr, unsigned int padr, unsigned int perm)\n     {\n         unsigned int offset;\n         offset = ((unsigned int)PTPool_LOC[proc_index][pde_index] - PT_PERM_PTU) / 4096;\n         fstore(offset * 1024 + vadr, padr * 4096 + perm);\n     }\n>>\n *)\n\nLet tpadr: ident := 8 % positive.\nLet tperm: ident := 9 % positive.\n\nDefinition set_pte_body: statement :=\n  (Ssequence\n  (Sset toffset\n    (Ebinop Odiv\n      (Ebinop Osub\n        (Ecast\n          (Ederef\n            (Ebinop Oadd\n              (Ederef\n                (Ebinop Oadd\n                  (Evar PTPool_LOC (tarray (tarray (tptr tchar) 1024) 64))\n                  (Etempvar tproc_index tint)\n                  (tptr (tarray (tptr tchar) 1024)))\n                (tarray (tptr tchar) 1024)) (Etempvar tpde_index tint)\n              (tptr (tptr tchar))) (tptr tchar)) tint)\n        (Econst_int (Int.repr 7) tint) tint)\n      (Econst_int (Int.repr 4096) tint) tint))\n  (Scall None\n    (Evar fstore (Tfunction (Tcons tint (Tcons tint Tnil)) tvoid cc_default))\n    ((Ebinop Oadd\n       (Ebinop Omul (Etempvar toffset tint)\n         (Econst_int (Int.repr 1024) tint) tint) (Etempvar tvadr tint)\n       tint) ::\n     (Ebinop Oadd\n       (Ebinop Omul (Etempvar tpadr tint) (Econst_int (Int.repr 4096) tint)\n         tint) (Etempvar tperm tint) tint) :: nil))).\n\nDefinition f_set_pte := {|\n                         fn_return := Tvoid;\n                         fn_callconv := cc_default;\n                         fn_vars := nil;\n                         fn_params := ((tproc_index, tint) :: (tpde_index, tint) :: (tvadr, tint) :: (tpadr, tint) :: (tperm, tint) :: nil);\n                         fn_temps := (toffset, tint) :: nil;\n                         fn_body := set_pte_body\n                       |}.\n\n\n(** \n<<\n     #define NUM_PROC 64\n     #define PT_PERM_PTU 7\n\n     extern char * PTPool_LOC[NUM_PROC][1024];\n     extern void fstore(unsigned int, unsigned int);\n\n     void rmv_PTE(unsigned int proc_index, unsigned int pde_index, unsigned int vadr)\n     {\n         unsigned int offset;\n         offset = ((unsigned int)PTPool_LOC[proc_index][pde_index] - PT_PERM_PTU) / 4096;\n         fstore(offset * 1024 + vadr, 0);\n     }\n>>\n *)\n\nDefinition rmv_pte_body: statement :=\n  (Ssequence\n  (Sset toffset\n    (Ebinop Odiv\n      (Ebinop Osub\n        (Ecast\n          (Ederef\n            (Ebinop Oadd\n              (Ederef\n                (Ebinop Oadd\n                  (Evar PTPool_LOC (tarray (tarray (tptr tchar) 1024) 64))\n                  (Etempvar tproc_index tint)\n                  (tptr (tarray (tptr tchar) 1024)))\n                (tarray (tptr tchar) 1024)) (Etempvar tpde_index tint)\n              (tptr (tptr tchar))) (tptr tchar)) tint)\n        (Econst_int (Int.repr 7) tint) tint)\n      (Econst_int (Int.repr 4096) tint) tint))\n  (Scall None\n    (Evar fstore (Tfunction (Tcons tint (Tcons tint Tnil)) tvoid cc_default))\n    ((Ebinop Oadd\n       (Ebinop Omul (Etempvar toffset tint)\n         (Econst_int (Int.repr 1024) tint) tint) (Etempvar tvadr tint)\n       tint) :: (Econst_int (Int.repr 0) tint) :: nil))).\n\nDefinition f_rmv_pte := {|\n                         fn_return := Tvoid;\n                         fn_callconv := cc_default;\n                         fn_vars := nil;\n                         fn_params := ((tproc_index, tint) :: (tpde_index, tint) :: (tvadr, tint) :: nil);\n                         fn_temps := (toffset, tint) :: nil;\n                         fn_body := rmv_pte_body\n                       |}.\n\n\n(** \n<<\n     extern unsigned int IDPMap_LOC[1024][1024];\n\n     void set_IDPTE(unsigned int pde_index, unsigned int vadr, unsigned int perm)\n     {\n         IDPMap_LOC[pde_index][vadr] = (pde_index * 1024 + vadr) * 4096 + perm;\n     }\n>>\n *)\n\nDefinition set_idpte_body: statement :=\n  (Sassign\n  (Ederef\n    (Ebinop Oadd\n      (Ederef\n        (Ebinop Oadd (Evar IDPMap_LOC (tarray (tarray tint 1024) 1024))\n          (Etempvar tpde_index tint) (tptr (tarray tint 1024)))\n        (tarray tint 1024)) (Etempvar tvadr tint) (tptr tint)) tint)\n  (Ebinop Oadd\n    (Ebinop Omul\n      (Ebinop Oadd\n        (Ebinop Omul (Etempvar tpde_index tint)\n          (Econst_int (Int.repr 1024) tint) tint) (Etempvar tvadr tint)\n        tint) (Econst_int (Int.repr 4096) tint) tint)\n    (Etempvar tperm tint) tint)).\n\nDefinition f_set_idpte := {|\n                         fn_return := Tvoid;\n                         fn_callconv := cc_default;\n                         fn_vars := nil;\n                         fn_params := ((tpde_index, tint) :: (tvadr, tint) :: (tperm, tint) :: nil);\n                         fn_temps := nil;\n                         fn_body := set_idpte_body\n                       |}.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/mm/MContainerCSource.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21146296250712882}}
{"text": "(*\n  This module defines the functional unit entries for floating\n  point arithmetic.\n\n  TODO: WARNING: check that the instructions set exceptions on invalid rounding modes.\n*)\nRequire Import Kami.AllNotations.\nRequire Import FpuKami.Definitions.\nRequire Import FpuKami.MulAdd.\nRequire Import FpuKami.Compare.\nRequire Import FpuKami.NFToIN.\nRequire Import FpuKami.INToNF.\nRequire Import FpuKami.Classify.\nRequire Import FpuKami.ModDivSqrt.\nRequire Import ProcKami.FU.\nRequire Import ProcKami.RiscvIsaSpec.Insts.Fpu.FpuFuncs.\nRequire Import List.\nImport ListNotations.\n\nSection Fpu.\n  Context `{procParams: ProcParams}.\n  Context `{fpuParams : FpuParams}.\n\n  Section ty.\n    Variable ty : Kind -> Type.\n\n    Open Scope kami_expr.\n\n    Definition csr_invalid_mask : FflagsValue @# ty := Const ty ('b(\"10000\")).\n\n    Definition cmp_cond_width := 2.\n\n    Definition cmp_cond_kind : Kind := Bit cmp_cond_width.\n\n    Definition cmp_cond_not_used : cmp_cond_kind @# ty := $0.\n    Definition cmp_cond_eq : cmp_cond_kind @# ty := $1.\n    Definition cmp_cond_lt : cmp_cond_kind @# ty := $2.\n    Definition cmp_cond_gt : cmp_cond_kind @# ty := $3.\n\n    Definition cmp_cond_get (cond : cmp_cond_kind @# ty) (result : Compare_Output @# ty)\n      := ITE (cond == cmp_cond_not_used)\n             ($$false)\n             (ITE (cond == cmp_cond_eq)\n                  (result @% \"eq\")\n                  (ITE (cond == cmp_cond_lt)\n                       (result @% \"lt\")\n                       (result @% \"gt\"))). \n\n    Close Scope kami_expr.\n\n    Definition FCmpInputType\n      :  Kind\n      := STRUCT_TYPE {\n             \"fflags\" :: FflagsValue;\n             \"signal\" :: Bool;\n             \"cond0\"  :: cmp_cond_kind;\n             \"cond1\"  :: cmp_cond_kind;\n             \"arg1\"   :: NF expWidthMinus2 sigWidthMinus2;\n             \"arg2\"   :: NF expWidthMinus2 sigWidthMinus2\n           }.\n\n    Definition FCmpOutputType\n      :  Kind\n      := STRUCT_TYPE {\n             \"fflags\" :: Maybe FflagsValue;\n             \"result\" :: Bit fpu_len\n           }.\n\n    Open Scope kami_expr.\n\n    Definition FCmpInput\n        (signal : Bool @# ty)\n        (cond0 : cmp_cond_kind @# ty)\n        (cond1 : cmp_cond_kind @# ty)\n        (_ : ContextCfgPkt @# ty)\n        (context_pkt_expr : ExecContextPkt ## ty)\n      :  FCmpInputType ## ty\n      := LETE context_pkt\n           <- context_pkt_expr;\n         RetE\n           (STRUCT {\n              \"fflags\" ::= #context_pkt @% \"fflags\";\n              \"signal\" ::= signal;\n              \"cond0\"  ::= cond0;\n              \"cond1\"  ::= cond1;\n              \"arg1\"   ::= bitToNF (fp_get_float Flen (#context_pkt @% \"reg1\"));\n              \"arg2\"   ::= bitToNF (fp_get_float Flen (#context_pkt @% \"reg2\"))\n            } : FCmpInputType @# ty).\n\n    Definition FCmpOutput\n      (resultExpr : FCmpOutputType ## ty)\n      :  PktWithException ExecUpdPkt ## ty\n      := LETE result <- resultExpr;\n         LETC val1 <- (STRUCT {\n                               \"tag\"  ::= $$(natToWord RoutingTagSz IntRegTag);\n                               \"data\" ::= SignExtendTruncLsb Rlen (#result @% \"result\")\n                         } : RoutedReg @# ty);\n         LETC val2 <- (STRUCT {\n                                  \"tag\"  ::= $$(natToWord RoutingTagSz FflagsTag);\n                                  \"data\" ::= ZeroExtendTruncLsb Rlen (#result @% \"fflags\" @% \"data\")\n                         } : RoutedReg @# ty);\n         LETC fstVal\n           :  ExecUpdPkt\n           <- (noUpdPkt ty)\n                @%[\"val1\" <- (Valid #val1)]\n                @%[\"val2\"\n                    <- IF #result @% \"fflags\" @% \"valid\"\n                         then Valid #val2\n                         else Invalid : Maybe RoutedReg @# ty];\n         RetE\n           (STRUCT {\n              \"fst\" ::= #fstVal;\n              \"snd\" ::= @Invalid ty _\n            } : PktWithException ExecUpdPkt @# ty).\n\n    Close Scope kami_expr.\n\n  End ty.\n\n  Open Scope kami_expr.\n\n  Definition FCmp\n    :  FUEntry\n    := {|\n         fuName := append \"fcmp\" fpu_suffix;\n         fuFunc\n           := fun ty (sem_in_pkt_expr : FCmpInputType ## ty)\n                => LETE sem_in_pkt\n                     :  FCmpInputType\n                     <- sem_in_pkt_expr;\n                   LETE cmp_result\n                     :  Compare_Output\n                     <- Compare_expr (#sem_in_pkt @% \"arg1\") (#sem_in_pkt @% \"arg2\");\n                   LETC fflags\n                     :  FflagsValue\n                     <- ((#sem_in_pkt @% \"fflags\") .|\n                         (ZeroExtendTruncLsb FflagsWidth (csr_invalid_mask ty)));\n                   LETC result\n                     :  FCmpOutputType\n                     <- STRUCT {\n                          \"fflags\"\n                            ::= ITE\n                                  ((* signaling comparisons *)\n                                   ((#sem_in_pkt @% \"signal\") &&\n                                    ((#sem_in_pkt @% \"arg1\" @% \"isNaN\") ||\n                                     (#sem_in_pkt @% \"arg2\" @% \"isNaN\"))) ||\n                                    (* quiet comparisons *)\n                                   ((!(#sem_in_pkt @% \"signal\")) &&\n                                    ((isSigNaNRawFloat (#sem_in_pkt @% \"arg1\")) ||\n                                     (isSigNaNRawFloat (#sem_in_pkt @% \"arg2\")))))\n                                  (Valid #fflags)\n                                  (@Invalid ty FflagsValue);\n                          \"result\"\n                          ::= ITE ((#sem_in_pkt @% \"arg1\" @% \"isNaN\") ||\n                                   (#sem_in_pkt @% \"arg2\" @% \"isNaN\"))\n                                ($0 : Bit fpu_len @# ty)\n                                (ITE\n                                  (cmp_cond_get (#sem_in_pkt @% \"cond0\") #cmp_result ||\n                                   cmp_cond_get (#sem_in_pkt @% \"cond1\") #cmp_result)\n                                  $1 $0)\n                     } : FCmpOutputType @# ty;\n                   RetE #result;\n         fuInsts\n           := [\n                {|\n                  instName   := append \"feq\" fpu_suffix;\n                  xlens      := xlens_all;\n                  extensions := fpu_exts;\n                  ext_ctxt_off := [\"fs\"];\n                  uniqId\n                    := [\n                         fieldVal fmtField fpu_format_field;\n                         fieldVal instSizeField ('b\"11\");\n                         fieldVal opcodeField   ('b\"10100\");\n                         fieldVal funct3Field   ('b\"010\");\n                         fieldVal rs3Field      ('b\"10100\")\n                       ];\n                  inputXform  := fun ty => FCmpInput (ty := ty) ($$false) (cmp_cond_eq ty) (cmp_cond_not_used ty);\n                  outputXform := FCmpOutput;\n                  optMemParams := None;\n                  instHints   := falseHints<|hasFrs1 := true|><|hasFrs2 := true|><|hasRd := true|> \n                |};\n                {|\n                  instName   := append \"flt\" fpu_suffix;\n                  xlens      := xlens_all;\n                  extensions := fpu_exts;\n                  ext_ctxt_off := [\"fs\"];\n                  uniqId\n                    := [\n                         fieldVal fmtField fpu_format_field;\n                         fieldVal instSizeField ('b\"11\");\n                         fieldVal opcodeField   ('b\"10100\");\n                         fieldVal funct3Field   ('b\"001\");\n                         fieldVal rs3Field      ('b\"10100\")\n                       ];\n                  inputXform  := fun ty => FCmpInput (ty := ty) ($$true) (cmp_cond_lt ty) (cmp_cond_not_used ty);\n                  outputXform := FCmpOutput;\n                  optMemParams := None;\n                  instHints   := falseHints<|hasFrs1 := true|><|hasFrs2 := true|><|hasRd := true|> \n                |};\n                {|\n                  instName   := append \"fle\" fpu_suffix;\n                  xlens      := xlens_all;\n                  extensions := fpu_exts;\n                  ext_ctxt_off := [\"fs\"];\n                  uniqId\n                    := [\n                         fieldVal fmtField fpu_format_field;\n                         fieldVal instSizeField ('b\"11\");\n                         fieldVal opcodeField   ('b\"10100\");\n                         fieldVal funct3Field   ('b\"000\");\n                         fieldVal rs3Field      ('b\"10100\")\n                       ];\n                  inputXform  := fun ty => FCmpInput (ty := ty) ($$true) (cmp_cond_lt ty) (cmp_cond_eq ty);\n                  outputXform := FCmpOutput;\n                  optMemParams := None;\n                  instHints   := falseHints<|hasFrs1 := true|><|hasFrs2 := true|><|hasRd := true|> \n                |}\n              ]\n       |}.\n\n  Close Scope kami_expr.\n\nEnd Fpu.\n", "meta": {"author": "sifive", "repo": "ProcKami", "sha": "7094363c5587d50653b918c323e043105fd172d6", "save_path": "github-repos/coq/sifive-ProcKami", "path": "github-repos/coq/sifive-ProcKami/ProcKami-7094363c5587d50653b918c323e043105fd172d6/RiscvIsaSpec/Insts/Fpu/FCmp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.21146296250712882}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp\nRequire Import path.\nRequire Import Eqdep.\nFrom fcsl\nRequire Import pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL\nRequire Import Freshness State EqTypeX Protocols Worlds NetworkSem Rely.\nFrom DiSeL\nRequire Import NewStatePredicates.\nFrom DiSeL\nRequire Import SeqLib.\nFrom DiSeL\nRequire Import Actions Injection Process Always HoareTriples InferenceRules.\nFrom DiSeL\nRequire Import TwoPhaseProtocol TwoPhaseCoordinator TwoPhaseParticipant.\nFrom DiSeL\nRequire TwoPhaseInductiveProof.\nFrom DiSeL\nRequire Import QueryProtocol QueryHooked.\n\nSection QueryPlusTPC.\n\n(* Querying on behalf of the coordinator (it's easier this way, thanks *)\n(* to cn_agreement lemma). In order to query on behald of the *)\n(* participan, a different invariant-based fact should be proven. *)\n\n(****************************************************************)\n(*************         Basic definitions       ******************)\n(****************************************************************)\n\nVariables (lc lq : Label).\nVariables (cn : nid) (pts : seq nid).\nHypothesis Lab_neq: lq != lc.\nHypothesis Hnin : cn \\notin pts.\nHypothesis Puniq : uniq pts.\nHypothesis PtsNonEmpty : pts != [::].\n\n(* Core protocol *)\nDefinition pc : protocol := TwoPhaseInductiveProof.tpc_with_inv lc [::] Hnin.\nDefinition Data : Type := (nat * Log).\nDefinition qnodes := cn :: pts.\n\n(* Serialization of logs *)\nVariable serialize : Data -> seq nat.\nVariable deserialize : seq nat -> Data.\nHypothesis ds_inverse : left_inverse serialize deserialize.\n\n(* This one is in the init state *)\nDefinition local_indicator (d : Data) :=\n  [Pred h | h = st :-> (d.1, CInit) \\+ log :-> d.2].\n\n(* Data is just a log *)\nDefinition core_state_to_data n h (d : Data)  :=\n  if n == cn\n  then h = st :-> (d.1, CInit) \\+ log :-> d.2\n  else h = st :-> (d.1, PInit) \\+ log :-> d.2.                       \n\nLemma core_state_to_data_inj n h d d' :\n  core_state_to_data n h d -> core_state_to_data n h d' -> d = d'.\nProof.\nrewrite/core_state_to_data.\ncase:ifP=>_ E; rewrite E ![_ \\+ log :-> _]joinC=>{E}E.\n- have V: valid (log :-> d.2 \\+ st :-> (d.1, CInit)).\n  - by case: validUn=>//k; rewrite !domPt !inE/==>/eqP<-. \n  case: (hcancelV V E)=>E2=>{V E}V E. \n  case: (hcancelPtV V E)=>E1.\n  by rewrite [d]surjective_pairing [d']surjective_pairing E1 E2.\nhave V: valid (log :-> d.2 \\+ st :-> (d.1, PInit)).\n- by case: validUn=>//k; rewrite !domPt !inE/==>/eqP<-. \ncase: (hcancelV V E)=>E2=>{V E}V E. \ncase: (hcancelPtV V E)=>E1.\nby rewrite [d]surjective_pairing [d']surjective_pairing E1 E2.\nQed.\n\nLemma cn_in_qnodes : cn \\in qnodes.\nProof. by rewrite inE eqxx. Qed.\n\nNotation getLc s n := (getLocal n (getStatelet s lc)).\nNotation cn_agree := TwoPhaseInductiveInv.cn_log_agreement.\n\n(****************************************************************)\n(*************   Necessary properties of TPC   ******************)\n(****************************************************************)\n\nLemma core_state_stable_step z s d s' n :\n  cn != z -> network_step (mkWorld pc) z s s' ->\n  n \\in qnodes ->\n  local_indicator d (getLc s cn) ->\n  core_state_to_data n (getLc s n) d  -> \n  core_state_to_data n (getLc s' n) d.\nProof.\nmove=>N S Qn L H0; case: (step_coh S)=>C1 C2.\nhave R: network_rely (plab pc \\\\-> pc, Unit) cn s s' by exists 1, z, s'. \nrewrite -(rely_loc' _ R) in L.\ncase: C2=>V1 V2 _ D /(_ lc)/=; rewrite prEq=>/=[[C2] Inv].\ncase/orP: Qn=>[|P]; first by move/eqP=>Z; subst n; rewrite /core_state_to_data eqxx.  \nmove: (@cn_agree lc cn pts [::] Hnin (getStatelet s' lc) d.1 d.2 n C2 L Inv P)=>H. \nrewrite /core_state_to_data; case:ifP=>//; by move=>/eqP Z; subst n. \nQed.\n\n(***************  Intermediate definitions **********************)\n\n(* Composite world *)\nDefinition W := QueryHooked.W lq pc Data qnodes serialize core_state_to_data.\n\nNotation loc_qry s := (getLocal cn (getStatelet s lq)).\nNotation loc_tpc' s n := (getLocal n (getStatelet s lc)).\nNotation loc_tpc s := (loc_tpc' s cn).\nNotation qry_init := (query_init_state lq Data qnodes serialize cn).\n\nLemma loc_imp_core s d n :\n  Coh W s -> n \\in qnodes -> local_indicator d (loc_tpc s) ->\n  core_state_to_data n (loc_tpc' s n) d.\nProof.\nmove=>C Nq E.\ncase/orP: Nq=>[|P]; first by move/eqP=>z; subst n; rewrite /core_state_to_data eqxx. \ncase: (C)=>_ _ _ _/(_ lc); rewrite prEqC//=; case=> C2 Inv.\nmove: (@cn_agree lc cn pts [::] Hnin (getStatelet s lc) d.1 d.2 n C2 E Inv P)=>->.\nrewrite /core_state_to_data; case:ifP=>//.\nmove=>/eqP Z; subst n; move/negbTE: Hnin=>Z.\nsuff X: cn \\in pts by rewrite X in Z.\ndone.\nQed.\n\nLemma find_empty l i : l \\notin dom i -> getStatelet i l = empty_dstatelet.\nProof. by rewrite /getStatelet; case: dom_find=>//->. Qed.\n       \n\nDefinition cn_request_log :=\n  request_data_program _ pc _ _ _ _ ds_inverse _ core_state_to_data_inj Lab_neq _ cn_in_qnodes\n                       local_indicator core_state_stable_step (0, [::]).\n\n(* Coordinator loop *)\nDefinition coordinator ds :=\n  with_inv (TwoPhaseInductiveProof.ii _ _ _)\n           (coordinator_loop_zero lc cn pts [::] Hnin Puniq PtsNonEmpty ds).\n\n  \n(****************************************************************)\n(*************   Overall program combining the two  *************)\n(****************************************************************)\n\n(* The following program first initiates a series  of TPC rounds as a *)\n(* coordinator, and then, on behalf of the coordinator queries a *)\n(* particular pariticipant via the side protocol for querying. The *)\n(* goal is to show that the resul obtained from querying is coherent *)\n(* with respect to coordinator's state. *)\n\nProgram Definition coordinate_and_query (ds : seq data) to :\n  {rr : seq (nid * nat) * seq (nid * nat)}, DHT [cn, W]\n  (fun i =>\n      let: (reqs, resp) := rr in \n     [/\\ loc_tpc i = st :-> (0, CInit) \\+ log :-> ([::] : seq (bool * data)),\n        to \\in qnodes,\n        loc_qry i = qst :-> (reqs, resp) &\n        qry_init to i],\n   fun (res : Data) m =>\n     let: (reqs, resp) := rr in\n     exists (chs : seq bool),\n       let: d := (size ds, seq.zip chs ds) in\n       [/\\ loc_tpc m = st :-> (d.1, CInit) \\+ log :-> d.2,\n        loc_qry m = qst :-> (reqs, resp),\n        qry_init to m &\n        res = d]) \n  := Do _ (\n      iinject (coordinator ds);;    \n      cn_request_log to).\n\nNext Obligation.\nby exact : (query_hookz lq pc Data qnodes serialize core_state_to_data).\nDefined.\n\nNext Obligation.\nexact: (injW lq pc Data qnodes serialize core_state_to_data Lab_neq).\nDefined.\n\nNext Obligation.\napply:ghC=>i0[rq rs][P1 P2 P3 P4]C0; apply: step.\n(*Preparing to split the state. *)\nmove: (C0)=>CD0; rewrite /W eqW in CD0; move: (coh_hooks CD0)=>{CD0}CD0.\ncase: (coh_split CD0); try apply: hook_complete0.\nmove=>i1[j1][C1 D1 Z].\nsubst i0; apply: inject_rule=>//.\nhave E : loc_tpc (i1 \\+ j1) = loc_tpc i1 by rewrite (locProjL CD0 _ C1)// domPt inE andbC eqxx.\nrewrite E{E} in P1.\napply: with_inv_rule'. \napply: call_rule=>//_ i2 [chs]L2 C2 Inv j2 CD2/= R.\n(* Massaging the complementary state *)\nhave E : loc_qry (i1 \\+ j1) = loc_qry j1 by rewrite (locProjR CD0 _ D1)// domPt inE andbC eqxx.\nrewrite E {E} -(rely_loc' _ R) in P3.\ncase: (rely_coh R)=>_ D2.\nrewrite /W eqW in CD2; move: (coh_hooks CD2)=>{CD2}CD2.\nrewrite /mkWorld/= in C2.\nhave C2': i2 \\In Coh (plab pc \\\\-> pc, Unit).\n- split=>//=.\n  + by rewrite /valid/= valid_unit validPt.\n  + by apply: (cohS C2).\n  + by apply: hook_complete0.  \n  + by move=>z; rewrite -(cohD C2) !domPt.\n  move=>l; case B: (lc == l).\n  + move/eqP:B=>B; subst l; rewrite /getProtocol findPt; split=>//.\n    by move: (coh_coh lc C2); rewrite /getProtocol findPt.\n  have X: l \\notin dom i2 by rewrite -(cohD C2) domPt inE; move/negbT: B.\n  rewrite /getProtocol/= (find_empty _ _ X).\n  have Y: l \\notin dom (lc \\\\-> pc) by rewrite domPt inE; move/negbT: B.\n  by case: dom_find Y=>//->_. \nhave D2': j2 \\In Coh (lq \\\\-> pq lq Data qnodes serialize, Unit)\n    by apply: (cohUnKR CD2 _); try apply: hook_complete0.\n\nrewrite -(locProjL CD2 _ C2') in L2; last by rewrite domPt inE eqxx.\nrewrite -(locProjR CD2 _ D2') in P3; last by rewrite domPt inE eqxx.\nclear C2 D2.\n\n(* So what's important is for the precondition ofattachment to be *)\n(* independent of the core protocol. *)  \nrewrite injWQ in R.\nrewrite /query_init_state/= in P4.\nrewrite (locProjR CD0 _ D1) in P4; last by rewrite domPt inE eqxx.\nhave Q4: qry_init to j2.\n- by apply: (query_init_rely' lq Data qnodes serialize cn to _ _ P4 R).\nclear P4.\nrewrite /query_init_state/= -(locProjR CD2 _ D2') in Q4;\n  last by rewrite domPt inE eqxx.\n\n(* Now ready to use the spec for querying. *)\napply (gh_ex (g:=(rq, rs, (size ds, seq.zip chs ds)))).\napply: call_rule=>//=; last by move=>d m[->->T1 T2->]_; eexists _. \nmove=>CD2'; split=>//.\ncase/orP: P2=>[|P]; first by move/eqP=>Z; subst to; rewrite /core_state_to_data eqxx.  \nrewrite !(locProjL CD2 _ C2') in L2 *;\n  last by rewrite domPt inE eqxx.\nmove: (coh_coh lc C2'); rewrite prEq; case=>C3 _.\nrewrite /core_state_to_data; case:ifP=>//[|_]; first by move=>/eqP Z; subst to. \nby apply: (@cn_agree lc cn pts [::] Hnin _ _ _ to C3 _ Inv).\nQed.\n\nEnd QueryPlusTPC.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/disel/Examples/Querying/QueryPlusTPC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.21138740465834785}}
{"text": "From Perennial.program_proof Require Import grove_prelude.\nFrom Goose.github_com.mit_pdos.gokv Require Import pb.\nFrom Perennial.program_proof.pb Require Export replica_ghost_defns.\nFrom Perennial.Helpers Require Import ListSolver.\n\n#[global]\nHint Unfold log_po : list.\n\nSection replica_ghost_proof.\n\nContext `{!heapGS Σ}.\nContext `{!urpcregG Σ}.\nContext `{!pb_ghostG Σ}.\nImplicit Type γ:pb_names.\n\n(* accept a new log *)\nLemma append_new_ghost {rid} γ r (newCn:u64) newLog :\n  int.Z r.(cn) ≤ int.Z newCn →\n  int.Z r.(cn) < int.Z newCn ∨ length r.(opLog) ≤ length newLog →\n  \"Hown\" ∷ own_Replica_ghost rid γ r ∗\n  \"#HnewProp\" ∷ proposal_lb_fancy γ newCn newLog\n  ={⊤}=∗\n  own_Replica_ghost rid γ (mkReplica newLog newCn) ∗\n  accepted_lb γ newCn rid newLog.\nProof.\n  intros Hfresh Hnew.\n  iNamed 1.\n  iNamed \"Hown\".\n  assert (int.Z r.(cn) < int.Z newCn ∨ int.Z r.(cn) = int.Z newCn) as [HnewCn|HoldCn] by word.\n  { (* brand new cn *)\n    iDestruct (big_sepS_elem_of_acc_impl newCn with \"HacceptedUnused\") as \"[HH HacceptedUnused]\".\n    { set_solver. }\n    iClear \"Haccepted\".\n    iDestruct \"HH\" as \"[%Hbad|Haccepted]\".\n    { exfalso. word. }\n    iMod (accepted_update newLog with \"Haccepted\") as \"Haccepted\".\n    { list_solver. }\n    iDestruct (accepted_witness with \"Haccepted\") as \"#$\".\n    iFrame \"Haccepted HnewProp\".\n    iApply \"HacceptedUnused\".\n    { (* prove impl: we have accepted_ptstos past newCn, since newCn > r.(cn) *)\n      iModIntro.\n      iIntros (???) \"[%Hineq|$]\".\n      iLeft.\n      iPureIntro.\n      simpl.\n      word.\n    }\n    { (* Prove that we don't need the element we accessed *)\n      simpl.\n      by iLeft.\n    }\n  }\n  { (* same cn, but bigger log *)\n    assert (r.(cn) = newCn) as HsameCn.\n    { word. }\n    rewrite HsameCn.\n    iDestruct (proposal_lb_fancy_comparable with \"Hproposal_lb HnewProp\") as %[Hcomp|Hcomp].\n    { (* new log bigger *)\n      iMod (accepted_update newLog with \"Haccepted\") as \"Haccepted\".\n      { done. }\n      iDestruct (accepted_witness with \"Haccepted\") as \"#$\".\n      by iFrame \"∗ HnewProp\".\n    }\n    { (* new log the same as before *)\n      destruct Hnew as [Hbad|HnewLog].\n      { exfalso; word. }\n      assert (newLog = r.(opLog)) as ->.\n      { list_solver. }\n      iDestruct (accepted_witness with \"Haccepted\") as \"#$\".\n      by iFrame \"∗#\".\n    }\n  }\nQed.\n\n(*\n  If we increase a replica's cn, want to know that we can keep its commitIdx\n  unchanged. This is true because the proposal for cn' will need to have all of\n  the committed entries from all previous cn's.\n *)\nLemma maintain_committer_ghost γ r c newCn newLog :\n  int.Z r.(cn) ≤ int.Z newCn →\n  int.Z r.(cn) < int.Z newCn ∨ length r.(opLog) ≤ length newLog →\n  \"#HoldProp\" ∷ proposal_lb_fancy γ r.(cn) r.(opLog) ∗\n  \"#HnewProp\" ∷ proposal_lb_fancy γ newCn newLog ∗\n  \"#Hownc\" ∷ own_Committer_ghost γ r c\n  ={⊤}=∗\n  own_Committer_ghost γ (mkReplica newLog newCn) c.\nProof.\n  intros HnotStale Hnew.\n  iNamed 1.\n  iNamed \"Hownc\".\n  assert (int.Z r.(cn) = int.Z newCn ∨ int.Z r.(cn) < int.Z newCn) as [Hcase|Hcase] by word.\n  { (* case: newCn == oldCn *)\n    destruct Hnew as [Hbad|HlongerLog]; first word.\n    unfold own_Committer_ghost.\n    simpl.\n    iSplitR \"\"; last first.\n    { iPureIntro. word. }\n    replace (newCn) with (r.(cn)) by word.\n    iDestruct (proposal_lb_fancy_comparable with \"HoldProp HnewProp\") as %Hcomp.\n    iApply (commit_lb_by_monotonic with \"Hcommit_lb\").\n    { done. }\n    destruct Hcomp as [Hlog|Hlog].\n    * list_solver.\n    * list_solver.\n  }\n  { (* case: newCn > oldCn *)\n    iDestruct (oldConfMax_commit_lb_by with \"HnewProp Hcommit_lb\") as %HlogPrefix.\n    { done. }\n    unfold own_Committer_ghost.\n    simpl.\n    iModIntro.\n    iSplitL \"\".\n    {\n      iApply (commit_lb_by_monotonic with \"Hcommit_lb\").\n      { done. }\n      (* B[:n] ⪯ A -∗ A[:n] ⪯ B[:n] *)\n      list_solver.\n    }\n    {\n      iPureIntro.\n      (* A[:n] ⪯ B -∗ n ≤ length B *)\n      list_solver.\n    }\n  }\nQed.\n\n(* Same CN as before, and an old log; just get a witness that we already accepted *)\nLemma append_dup_ghost {rid} γ r (newCn:u64) newLog :\n  int.Z r.(cn) = int.Z newCn ∧ length newLog ≤ length r.(opLog) →\n  \"Hown\" ∷ own_Replica_ghost rid γ r ∗\n  \"#HnewProp\" ∷ proposal_lb_fancy γ newCn newLog\n  ={⊤}=∗\n  own_Replica_ghost rid γ r ∗\n  accepted_lb γ newCn rid newLog.\nProof.\n  intros [Hre HstaleLog].\n  assert (r.(cn) = newCn) as <- by word.\n  iNamed 1.\n  iNamed \"Hown\".\n  iDestruct (accepted_witness with \"Haccepted\") as \"#Hacc1\".\n  (* NOTE: idea: introduce a \"comparable\" predicate, and have some lemmas about that *)\n  iDestruct (proposal_lb_fancy_comparable with \"Hproposal_lb HnewProp\") as %[Hcomp|Hcomp].\n  { (* log must be equal *)\n    replace (newLog) with (r.(opLog)); last first.\n    { (* TODO: list_solver candidate *) admit. } (* len A ≤ len B ∧ B ⪯ A → B = A *)\n    iDestruct (accepted_lb_monotonic with \"Hacc1\") as \"$\".\n    { done. }\n    by iFrame \"∗#\".\n  }\n  {\n    iDestruct (accepted_lb_monotonic with \"Hacc1\") as \"$\".\n    { done. }\n    by iFrame \"∗#\".\n  }\nAdmitted.\n\n(* Increase commitIdx by getting a commit_lb_by witness from primary *)\nLemma commit_idx_update {rid} γ r log newCommitIdx :\n  int.Z newCommitIdx ≤ length log →\n  \"Hown\" ∷ own_Replica_ghost rid γ r ∗\n  \"#Hacc\" ∷ accepted_lb γ r.(cn) rid log ∗\n  \"#Hcommit_lb\" ∷ commit_lb_by γ r.(cn) (take (int.nat newCommitIdx) log)\n  -∗\n  own_Replica_ghost rid γ r ∗\n  own_Committer_ghost γ r (mkCommitterExtra newCommitIdx).\nProof.\n  (* argument: log ⪯ r.(log); (take n log) == (take n r.(log)); *)\n  intros HcommitIdx.\n  iNamed 1.\n  iNamed \"Hown\".\n  iDestruct (accepted_lb_le with \"Haccepted Hacc\") as \"%HlogLe\".\n  replace (take (int.nat newCommitIdx) log)\n          with (take (int.nat newCommitIdx) r.(opLog)); last first.\n  {\n    assert (int.nat newCommitIdx <= length log) by word.\n    set (a:=int.nat newCommitIdx) in *.\n    admit. (* TODO: list_solver candidate *)\n  }\n  iFrame \"∗#\".\n  iPureIntro.\n  simpl.\n  list_solver.\nAdmitted.\n\nLemma primary_matchidx_lookup {rid} conf (i:u64) γ r p :\n  conf !! int.nat i = Some rid →\n  \"#Hconf\" ∷ config_ptsto γ r.(cn) conf ∗\n  \"HprimaryG\" ∷ own_Primary_ghost γ r p\n  -∗\n  ⌜∃ (x:u64), p.(matchIdx) !! int.nat i = Some x⌝.\nProof.\n  intros HconfLookup.\n  iNamed 1.\n  iNamed \"HprimaryG\".\n  iDestruct (config_ptsto_agree with \"Hconf HconfPtsto\") as %->.\n  iDestruct (big_sepL2_lookup_1_some with \"HmatchIdxAccepted\") as \"$\".\n  done.\nQed.\n\nLemma primary_update_matchidx {rid} (i oldIdx:u64) γ r p newLog (newLogLen:u64) :\n  p.(matchIdx) !! int.nat i = Some oldIdx →\n  p.(conf) !! int.nat i = Some rid →\n  length newLog = int.nat newLogLen →\n  \"HprimaryG\" ∷ own_Primary_ghost γ r p ∗\n  \"#Hacc_lb\" ∷ accepted_lb γ r.(cn) rid newLog ∗\n  \"#Hprop_lb\" ∷ proposal_lb γ r.(cn) newLog\n  -∗\n  own_Primary_ghost γ r (mkPrimaryExtra\n                           p.(conf)\n                           (<[int.nat i:=newLogLen]> p.(matchIdx)) ).\nProof.\n  intros HmatchIdxLookup HconfLookup Hlen.\n  iNamed 1.\n  iNamed \"HprimaryG\".\n  iDestruct (proposal_lb_le with \"HprimaryOwnsProposal Hprop_lb\") as %HlogLe.\n  unfold own_Primary_ghost.\n  iFrame \"∗#\".\n  iDestruct (big_sepL2_insert_acc with \"HmatchIdxAccepted\") as \"[_ HH]\".\n  { done. }\n  { done. }\n  iSpecialize (\"HH\" $! rid).\n  replace (<[int.nat i:=rid]> p.(conf)) with (p.(conf)); last first.\n  { by rewrite list_insert_id. }\n  iApply \"HH\".\n  replace (take (int.nat newLogLen) r.(opLog)) with (newLog); last first.\n  {\n    admit. (* TODO: list_solver. candidate *)\n  }\n  iFrame \"#\".\nAdmitted.\n\nLemma primary_commit m γ r (p:PrimaryExtra) :\n  m ∈ p.(matchIdx) →\n  (∀ n, n ∈ p.(matchIdx) → int.Z m ≤ int.Z n) →\n  int.Z m ≤ length r.(opLog) →\n  pb_inv γ -∗\n  proposal_lb_fancy γ r.(cn) r.(opLog) -∗\n  own_Primary_ghost γ r p\n  ={⊤}=∗\n  own_Primary_ghost γ r p ∗\n  own_Committer_ghost γ r (mkCommitterExtra m).\nProof.\n  intros Hm Hmin HmLog.\n  iIntros \"#HpbInv #Hprop_lb\".\n  iNamed 1.\n  iFrame \"∗#\".\n  unfold own_Committer_ghost.\n  simpl.\n  iSplitR \"\"; last done.\n  iMod (do_commit with \"HpbInv [] []\") as \"$\".\n  { (* TODO: Use accepted_by_fancy. *) admit. }\n  { unfold accepted_by.\n    iExists _; iFrame \"HconfPtsto\".\n    iIntros (rid Hrid).\n    assert (exists i, p.(conf) !! i = Some rid) as [i HconfLookup].\n    { by apply elem_of_list_lookup_1. }\n    iDestruct (big_sepL2_lookup_1_some with \"HmatchIdxAccepted\") as %[n HmatchIdxLookup].\n    { done. }\n    iDestruct (big_sepL2_lookup_acc with \"HmatchIdxAccepted\") as \"[Hacc _]\".\n    { done. }\n    { done. }\n    assert (int.Z m <= int.Z n).\n    {\n      apply Hmin.\n      by eapply elem_of_list_lookup_2.\n    }\n    iApply (accepted_lb_monotonic with \"Hacc\").\n    list_solver.\n  }\n  done.\nAdmitted.\n\nEnd replica_ghost_proof.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/pb/replica_ghost_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.2113749957672558}}
{"text": "Require Import Platform.AutoSep Platform.Malloc Platform.Bootstrap Platform.Cito.examples.CountUnique.\n\n\nModule Type S.\n  Variable heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"top\"!\"top\" @ [topS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Call \"top\"!\"top\"()\n        [PREonly[_] [| False |] ]\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Require Platform.Cito.examples.ExampleImpl.\n\n  Definition m0 := link ExampleImpl.m boot.\n  Definition m1 := link all m0.\n\n  Lemma ok0 : moduleOk m0.\n    link ExampleImpl.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link all_ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n\n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, ($ (size * 4) <= w)%word -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Cito/examples/CountUniqueDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2113749901540599}}
{"text": "Require Import ConcurExec.\nRequire Import Spec.Equiv.Execution.\nRequire Import Spec.Equiv.\nRequire Import ProcMatch.\nRequire Import Equiv ProcMatch.\nRequire Import ProofAutomation.\nRequire Import FunctionalExtensionality.\nRequire Import Omega.\nRequire Import List.\nRequire Import Compile.\n\nImport ListNotations.\n\nGlobal Set Implicit Arguments.\nGlobal Generalizable All Variables.\n\n\nSection Compiler.\n\n  Variable OpLo : Type -> Type.\n  Variable OpHi : Type -> Type.\n\n  Variable compile_op : forall T, OpHi T -> ((option T -> OpLo T) * (T -> bool) * option T).\n\n  Definition compile :=\n    Compile.compile (fun T op =>\n      let '(body, cond, iv) := compile_op op in\n      Until cond (fun x => Call (body x)) iv).\n\n  Inductive compile_ok : forall T (p1 : proc OpLo T) (p2 : proc OpHi T), Prop :=\n  | CompileOp : forall `(op : OpHi T) body cond iv v,\n    compile_op op = (body, cond, iv) ->\n    compile_ok (Until cond (fun x => Call (body x)) v) (Call op)\n  | CompileOp1 : forall `(op : OpHi T) body cond iv v,\n    compile_op op = (body, cond, iv) ->\n    compile_ok (until1 cond (fun x => Call (body x)) v) (Call op)\n  | CompileRet : forall `(x : T),\n    compile_ok (Ret x) (Ret x)\n  | CompileExtraRet : forall `(x : T) `(p1 : T -> proc OpLo TF) p2,\n    compile_ok (p1 x) (p2 x) ->\n    compile_ok (Bind (Ret x) p1) (p2 x)\n  | CompileBind : forall `(p1a : proc OpLo T1) (p2a : proc OpHi T1)\n                         `(p1b : T1 -> proc _ T2) (p2b : T1 -> proc _ T2),\n    compile_ok p1a p2a ->\n    (forall x, compile_ok (p1b x) (p2b x)) ->\n    compile_ok (Bind p1a p1b) (Bind p2a p2b)\n  | CompileUntil : forall `(p1 : option T -> proc OpLo T) (p2 : option T -> proc OpHi T) (c : T -> bool) v,\n    (forall v', compile_ok (p1 v') (p2 v')) ->\n    compile_ok (Until c p1 v) (Until c p2 v)\n  | CompileSpawn : forall T (p1: proc OpLo T) (p2: proc OpHi T),\n      compile_ok p1 p2 ->\n      compile_ok (Spawn p1) (Spawn p2)\n  .\n\n  Hint Constructors compile_ok.\n\n  Theorem compile_ok_compile :\n    forall `(p : proc _ T),\n      no_atomics p ->\n      compile_ok (compile p) p.\n  Proof.\n    induction p; simpl; intros; eauto.\n    - destruct (compile_op op) as [x iv] eqn:He1.\n      destruct x as [body cond] eqn:He2.\n      eauto.\n    - invert H0; eauto.\n    - invert H0; eauto.\n    - invert H.\n    - invert H; eauto.\n  Qed.\n\n  Theorem compile_no_atomics :\n    forall `(p : proc _ T),\n      no_atomics p ->\n      no_atomics (compile p).\n  Proof.\n    intros.\n    eapply Compile.compile_no_atomics; eauto.\n    intros.\n    destruct (compile_op op); destruct p0; eauto.\n  Qed.\n\n  Definition compile_ts ts :=\n    thread_map compile ts.\n\n  Hint Resolve compile_ok_compile.\n\n  Theorem compile_ts_ok :\n    forall ts,\n      no_atomics_ts ts ->\n      proc_match compile_ok (compile_ts ts) ts.\n  Proof.\n    intros.\n    apply proc_match_sym.\n    unfold proc_match; intros.\n    unfold compile_ts.\n    destruct_with_eqn (ts tid).\n    rewrite thread_map_get_match.\n    destruct_with_eqn (ts tid); try congruence.\n    invert Heqm; eauto.\n    rewrite thread_map_get_match.\n    simpl_match; auto.\n  Qed.\n\n  Hint Resolve compile_no_atomics.\n\n  Theorem compile_ts_no_atomics :\n    forall ts,\n      no_atomics_ts ts ->\n      no_atomics_ts (compile_ts ts).\n  Proof.\n    unfold no_atomics_ts, compile_ts; intros.\n    eapply map_thread_Forall; eauto.\n  Qed.\n\n  Variable State : Type.\n  Variable lo_step : OpSemantics OpLo State.\n  Variable hi_step : OpSemantics OpHi State.\n\n  Definition noop_or_success :=\n    forall T (opM : OpHi T) opL cond iv tid s r s',\n      (opL, cond, iv) = compile_op opM ->\n      forall v evs,\n        lo_step (opL v) tid s r s' evs ->\n          cond r = false /\\ s = s' /\\ evs = nil \\/\n          cond r = true /\\ hi_step opM tid s r s' evs.\n\n  Variable is_noop_or_success : noop_or_success.\n\n  Hint Constructors exec_tid.\n\n  Lemma compile_ok_exec_tid : forall T (p1 : proc _ T) p2,\n    compile_ok p1 p2 ->\n    forall tid s s' result spawned evs,\n      exec_tid lo_step tid s p1 s' result spawned evs ->\n      (exists p1',\n        s' = s /\\\n        result = inr p1' /\\\n        compile_ok p1' p2 /\\\n        spawned = NoProc /\\\n        evs = nil) \\/\n      (exists spawned' result',\n        exec_tid hi_step tid s p2 s' result' spawned' evs /\\\n        proc_optR compile_ok spawned spawned' /\\\n        match result with\n        | inl v => match result' with\n          | inl v' => v = v'\n          | inr _ => False\n          end\n        | inr p' => match result' with\n          | inl v' => p' = Ret v'\n          | inr p'' => compile_ok p' p''\n          end\n        end).\n  Proof.\n    induction 1; intros.\n    - left.\n      exec_tid_inv.\n      eexists; intuition idtac.\n      eauto.\n    - repeat exec_tid_inv.\n      eapply is_noop_or_success in H6; eauto.\n      intuition idtac; subst.\n      + left.\n        descend; intuition eauto.\n        simpl_match; eauto.\n      + right.\n        descend; intuition eauto.\n        simpl_match; eauto.\n    - right.\n      exec_tid_inv.\n      descend; intuition eauto.\n    - left.\n      repeat exec_tid_inv.\n      eexists; intuition idtac.\n    - exec_tid_inv.\n      edestruct IHcompile_ok; eauto; intuition idtac.\n      + repeat deex; subst.\n        left.\n        eexists; intuition eauto.\n      + repeat deex; subst.\n        right.\n        descend; intuition eauto.\n        destruct matches; propositional; eauto.\n    - right.\n      exec_tid_inv.\n      descend; intuition eauto.\n      constructor; eauto; intros.\n      destruct (c x); eauto.\n    - right.\n      exec_tid_inv.\n      descend; intuition eauto.\n  Qed.\n\n  Theorem compile_traces_match_ts :\n    forall ts1 ts2,\n      proc_match compile_ok ts1 ts2 ->\n      traces_match_ts lo_step hi_step ts1 ts2.\n  Proof.\n    unfold traces_match_ts; intros.\n    generalize dependent ts2.\n    induction H0; eauto; intros.\n\n    eapply proc_match_pick with (tid := tid) in H3 as H2'.\n    intuition idtac; try congruence.\n    repeat deex.\n    rewrite H in H4; invert H4.\n\n    eapply compile_ok_exec_tid in H1; eauto.\n    (intuition eauto); propositional.\n\n    - simpl.\n      rewrite thread_upd_same_eq with (tid:=tid') in * by auto.\n      eapply IHexec.\n      erewrite <- thread_upd_same_eq with (ts := ts2) (tid := tid) by eassumption.\n      apply proc_match_upd; eauto.\n    - assert (ts2 tid' = NoProc) by eauto using proc_match_none.\n      destruct result.\n      + epose_proof IHexec.\n        eapply proc_match_del; eauto.\n        apply proc_match_upd_opt; eauto.\n        ExecPrefix tid tid'.\n        destruct result'; propositional; eauto.\n\n      + destruct result'; propositional.\n        * epose_proof IHexec.\n            eapply proc_match_upd; eauto.\n            apply proc_match_upd_opt; eauto.\n\n          rewrite exec_equiv_ret_None in H8.\n\n          abstract_tr.\n          ExecPrefix tid tid'.\n          reflexivity.\n\n        * epose_proof IHexec.\n            eapply proc_match_upd; eauto.\n            apply proc_match_upd_opt; eauto.\n          ExecPrefix tid tid'.\n  Qed.\n\nEnd Compiler.\n\nArguments compile_ts {OpLo OpHi}.\n", "meta": {"author": "mit-pdos", "repo": "cspec", "sha": "074e11f5c7758fd0f5624f0466dd23244f9112c4", "save_path": "github-repos/coq/mit-pdos-cspec", "path": "github-repos/coq/mit-pdos-cspec/cspec-074e11f5c7758fd0f5624f0466dd23244f9112c4/src/Spec/CompileLoop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.21123510340130422}}
{"text": "(* Copyright (c) 2012-2015, Robbert Krebbers. *)\n(* This file is distributed under the terms of the BSD license. *)\nRequire Export tactics smallstep executable.\n\nSection soundness.\nContext `{EnvSpec K}.\n\nLemma assign_exec_correct Γ m a v ass va' v' :\n  assign_exec Γ m a v ass = Some (va',v') ↔ assign_sem Γ m a v ass va' v'.\nProof.\n  split; [|by destruct 1; simplify_option_eq].\n  intros. destruct ass; simplify_option_eq; econstructor; eauto.\nQed.\nLemma ctx_lookup_correct (k : ctx K) i : ctx_lookup i k = locals k !! i.\nProof.\n  revert i.\n  induction k as [|[]]; intros [|x]; f_equal'; rewrite ?list_lookup_fmap; auto.\nQed.\nLemma ehexec_sound Γ k m1 m2 e1 e2 :\n  (e2,m2) ∈ ehexec Γ k e1 m1 → Γ\\ locals k ⊢ₕ e1, m1 ⇒ e2, m2.\nProof.\n  intros. destruct e1;\n    repeat match goal with\n    | H : assign_exec _ _ _ _ _ = Some _ |- _ =>\n      apply assign_exec_correct in H\n    | _ => progress decompose_elem_of\n    | H : ctx_lookup _ _ = _ |- _ => rewrite ctx_lookup_correct in H\n    | _ => progress simplify_equality'\n    | _ => case_match\n    end; do_ehstep.\nQed.\nLemma ehexec_weak_complete Γ k e1 m1 e2 m2 :\n  ehexec Γ k e1 m1 ≡ ∅ → \n  ¬Γ\\ locals k ⊢ₕ e1, m1 ⇒ e2, m2.\nProof.\n  destruct 2; \n    repeat match goal with\n    | H : assign_sem _ _ _ _ _ _ _ |- _ =>\n      apply assign_exec_correct in H\n    | H : is_Some _ |- _ => destruct H as [??]\n    | _ => progress decompose_empty\n    | H : locals _ !! _ = Some _ |- _ => rewrite <-ctx_lookup_correct in H\n    | H : option_to_set ?o ≫= _ ≡ _, Ho : ?o = Some _ |- _ =>\n       rewrite Ho in H; csimpl in H; rewrite set_bind_singleton in H\n    | _ => progress simplify_option_eq\n    | _ => case_match\n    | H : mguard (_) (_) ≡ ∅ |- _ => apply guard_empty in H\n    | H : _ ∨ _ |- _ => destruct H\n    end; eauto.\nQed.\nLemma ehstep_dec Γ ρ e1 m1 :\n  (∃ e2 m2, Γ\\ ρ ⊢ₕ e1, m1 ⇒ e2, m2) ∨ ∀ e2 m2, ¬Γ\\ ρ ⊢ₕ e1, m1 ⇒ e2, m2.\nProof.\n  set (k:=(λ oτ, CLocal (oτ.1) (oτ.2)) <$> ρ).\n  replace ρ with (locals k) by (induction ρ as [|[]]; f_equal'; auto).\n  destruct (set_choose_or_empty (ehexec Γ k e1 m1)) as [[[e2 m2]?]|];\n    eauto using ehexec_sound, ehexec_weak_complete.\nQed.\nLemma cexec_sound Γ δ S1 S2 : Γ\\ δ ⊢ₛ S1 ⇒ₑ S2 → Γ\\ δ ⊢ₛ S1 ⇒ S2.\nProof.\n  intros. assert (\n    ∀ (k : ctx K) e m,\n      ehexec Γ k e m ≡ ∅ → \n      maybe_ECall_redex e = None →\n      is_redex e → \n      ¬Γ\\ locals k ⊢ₕ safe e, m\n  ).\n  { intros k e m He. rewrite eq_None_not_Some.\n    intros Hmaybe Hred Hsafe; apply Hmaybe; destruct Hsafe.\n    * eexists; apply maybe_ECall_redex_Some; eauto.\n    * edestruct ehexec_weak_complete; eauto. }\n  destruct S1;\n    repeat match goal with\n    | H : _ ∈ ehexec _ _ _ _ |- _ => apply ehexec_sound in H\n    | H : _ ∈ expr_redexes _ |- _ =>\n      apply expr_redexes_correct in H; destruct H\n    | H : maybe VBase ?vb = _ |- _ => is_var vb; destruct vb\n    | H : maybe_ECall_redex _ = Some _ |- _ =>\n      apply maybe_ECall_redex_Some in H; destruct H\n    | _ => progress decompose_elem_of\n    | _ => case_decide\n    | _ => case_match\n    | _ => progress simplify_equality'\n    | H : maybe2 _ ?e = Some _ |- _ => is_var e; destruct e\n    end; do_cstep.\nQed.\nLemma cexecs_sound Γ δ S1 S2 : Γ\\ δ ⊢ₛ S1 ⇒ₑ* S2 → Γ\\ δ ⊢ₛ S1 ⇒* S2.\nProof. induction 1; econstructor; eauto using cexec_sound. Qed.\nLemma cexec_ex_loop Γ δ S :\n  ex_loop (λ S1 S2, Γ\\ δ ⊢ₛ S1 ⇒ₑ S2) S → ex_loop (cstep Γ δ) S.\nProof.\n  revert S; cofix COH; intros S; destruct 1 as [S1 S2 p].\n  econstructor; eauto using cexec_sound.\nQed.\nEnd soundness.\n", "meta": {"author": "robbertkrebbers", "repo": "ch2o", "sha": "1afb3f615db053b741341e9bfd1d5c65bddea641", "save_path": "github-repos/coq/robbertkrebbers-ch2o", "path": "github-repos/coq/robbertkrebbers-ch2o/ch2o-1afb3f615db053b741341e9bfd1d5c65bddea641/core_c/executable_sound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2112351034013042}}
{"text": "Require Import RelationClasses.\nRequire Import List.\n\nRequire Import sflib.\nFrom Paco Require Import paco.\n\nRequire Import Basic.\nRequire Import Axioms.\nRequire Import Loc.\nRequire Import LibTactics.\nRequire Import Integers.\nRequire Import Language.\nRequire Import ZArith.\nRequire Import Maps.\nRequire Import FSets.\nRequire Import FSetInterface.\nRequire Import Lattice.\nRequire Import Event.\nRequire Import Syntax.\nRequire Import Semantics.\n\nRequire Import Kildall.\nRequire Import LiveAnalysis.\nRequire Import CorrectOpt.\nRequire Import DCE.\n\nRequire Import Language.\nRequire Import Time.\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import MsgMapping.\nRequire Import DelaySet.\nRequire Import LocalSim.\n\n(** * Invariant in dead code elimination  *)\nDefinition I_dce (lo: Ordering.LocOrdMap) (inj: Mapping) (S: Rss) :=\n  match S with\n  | Build_Rss sc_tgt mem_tgt sc_src mem_src =>\n    (* injection timemaps for SC fence *)\n    (<<INJ_SC: TMapInj inj sc_tgt sc_src>> /\\\n    (* memory injection *)\n    <<INJ_MEM: MsgInj inj mem_tgt mem_src>> /\\\n    (* timestamps reservation *)\n    <<TS_RSV: forall loc val from' to' R' to,\n        Memory.get loc to' mem_src = Some (from', Message.concrete val R') ->\n        inj loc to = Some to' ->\n        Time.lt Time.bot to ->\n        lo loc = Ordering.nonatomic ->\n        exists to_r, Time.lt to_r from' /\\\n                (forall ts, Interval.mem (to_r, from') ts -> ~Cover.covered loc ts mem_src)>> /\\\n    (* no atomic location has no reservation *)\n    <<NO_RSVs: forall loc to from,\n            Memory.get loc to mem_src = Some (from, Message.reserve) -> lo loc = Ordering.atomic>> /\\           \n    (* identity atomic *)                                                                                            \n    <<ID_ATOMIC: forall loc to to', lo loc = Ordering.atomic -> inj loc to = Some to' -> to = to'>> /\\\n    (* closed src memory *)\n    <<CLOSED_SRC_MEM: Memory.closed mem_src>>\n    )\n  end. \n\n(** * Match state *)\n(* timestamp match *)\nDefinition TM (inj: Mapping) (loc: Loc.t) (tm_tgt: TimeMap.t)\n           (tm_src: TimeMap.t) (mem_src: Memory.t) :=\n  (forall to to', inj loc to = Some to' -> Time.lt (tm_tgt loc) to -> Time.lt (tm_src loc) to') /\\\n  (exists to', inj loc (tm_tgt loc) = Some to' /\\ Time.le to' (tm_src loc) /\\\n          (forall ts, Interval.mem (to', tm_src loc) ts -> concrete_covered loc ts mem_src)).\n\n(* view match *) \nInductive InvView_dce: Mapping -> Ordering.LocOrdMap -> TView.t -> TView.t -> Memory.t -> Prop :=\n| InvView_dce_intro\n    inj lo tview_tgt tview_src mem_src\n    (* For current view *)\n    (ATM_LOC_CUR_PLN: \n       forall loc, lo loc = Ordering.atomic ->\n              inj loc ((View.pln (TView.cur tview_tgt)) loc) = Some ((View.pln (TView.cur tview_src)) loc))\n    (ATM_LOC_CUR_RLX: \n       forall loc, lo loc = Ordering.atomic ->\n              inj loc ((View.rlx (TView.cur tview_tgt)) loc) = Some ((View.rlx (TView.cur tview_src)) loc))\n    (NA_LOC_CUR_RLX: \n       forall loc, lo loc = Ordering.nonatomic ->\n              TM inj loc (View.rlx (TView.cur tview_tgt)) (View.rlx (TView.cur tview_src)) mem_src)\n    (* For acquire view *)\n    (ATM_LOC_ACQ_PLN: \n       forall loc, lo loc = Ordering.atomic ->\n              inj loc ((View.pln (TView.acq tview_tgt)) loc) = Some ((View.pln (TView.acq tview_src)) loc))\n    (ATM_LOC_ACQ_RLX: \n       forall loc, lo loc = Ordering.atomic ->\n              inj loc ((View.rlx (TView.acq tview_tgt)) loc) = Some ((View.rlx (TView.acq tview_src)) loc))\n    (NA_LOC_CUR_RLX: \n       forall loc, lo loc = Ordering.nonatomic ->\n              TM inj loc (View.rlx (TView.acq tview_tgt)) (View.rlx (TView.acq tview_src)) mem_src)\n    (* For release view *)\n    (ATM_LOC_REL: \n       forall loc, lo loc = Ordering.atomic ->\n              ViewInj inj ((TView.rel tview_tgt) loc) ((TView.rel tview_src) loc)):\n    InvView_dce inj lo tview_tgt tview_src mem_src.\n\nDefinition cur_acq (lo: Ordering.LocOrdMap) (inj: Mapping)\n           (cur_tgt acq_tgt: View.t) (cur_src acq_src: View.t) :=\n  forall loc \n    (NA_LOC: lo loc = Ordering.nonatomic),\n    <<LT: Time.lt ((View.rlx cur_tgt) loc) ((View.rlx acq_tgt) loc) /\\\n          inj loc ((View.rlx acq_tgt) loc) = Some ((View.rlx acq_src) loc)>> \\/\n    <<EQ: ((View.rlx cur_tgt) loc) = ((View.rlx acq_tgt) loc) /\\\n          ((View.rlx cur_src) loc) = ((View.rlx acq_src) loc)>>.\n\nDefinition cur_acq_pln (lo: Ordering.LocOrdMap) (inj: Mapping)\n           (cur_tgt acq_tgt: View.t) (cur_src acq_src: View.t) :=\n  forall loc \n    (NA_LOC: lo loc = Ordering.nonatomic),\n    <<LT: Time.lt ((View.rlx cur_tgt) loc) ((View.pln acq_tgt) loc) /\\\n          inj loc ((View.pln acq_tgt) loc) = Some ((View.pln acq_src) loc)>> \\/\n    <<EQ: Time.le ((View.pln acq_tgt) loc) ((View.rlx cur_tgt) loc) /\\\n          Time.le ((View.pln acq_src) loc) ((View.rlx cur_src) loc)>>.\n    \n(* semantics for abstract interpretation *)\nDefinition sem_live_reg (R_tgt R_src: RegFile.t) (nr: nreg): Prop :=\n  forall r, NREG.get r nr = true -> RegFun.find r R_tgt = RegFun.find r R_src.\n\nDefinition sem_live_loc (inj: Mapping) (tview_tgt tview_src: TView.t) (nm: nmem): Prop :=\n  forall loc, negb (is_dead_loc loc nm) ->\n         (\n           (inj loc ((View.pln (TView.cur tview_tgt)) loc) = Some ((View.pln (TView.cur tview_src)) loc)) /\\\n           (inj loc ((View.pln (TView.acq tview_tgt)) loc) = Some ((View.pln (TView.acq tview_src)) loc)) /\\\n           (inj loc ((View.rlx (TView.cur tview_tgt)) loc) = Some ((View.rlx (TView.cur tview_src)) loc)) /\\\n           (inj loc ((View.rlx (TView.acq tview_tgt)) loc) = Some ((View.rlx (TView.acq tview_src)) loc))\n         ). \n\nDefinition ai_interp (inj: Mapping)\n           (R_tgt: RegFile.t) (tview_tgt: TView.t)\n           (R_src: RegFile.t) (tview_src: TView.t)\n           (ai: LvDS.L.t): Prop :=\n  match ai with\n  | (nr, nm) => sem_live_reg R_tgt R_src nr /\\ sem_live_loc inj tview_tgt tview_src nm\n  end.\n\n(* promise relation *)\nDefinition promises_relation (inj: Mapping) (lo: Ordering.LocOrdMap) (prm_tgt prm_src: Memory.t) :=\n  @rel_promises nat inj dset_init prm_tgt prm_src /\\\n  (forall loc from to,\n      lo loc = Ordering.atomic -> \n      (Memory.get loc to prm_tgt = Some (from, Message.reserve) <->\n       Memory.get loc to prm_src = Some (from, Message.reserve))).\n\n(* match state for current stack frame *)\nInductive match_state_cur_stkframe:\n  Mapping -> Ordering.LocOrdMap ->\n  (RegFile.t * BBlock.t * CodeHeap * TView.t) ->\n  (RegFile.t * BBlock.t * CodeHeap * TView.t) -> Prop :=\n| match_state_cur_stkframe_intro\n    inj lo R_tgt BB_tgt C_tgt tview_tgt R_src BB_src C_src tview_src\n    afunc ai_tail ai ai_pblk fid\n    (* function analysis *)\n    (FUNC_ANALYSIS: LvDS.analyze_func_backward (C_src, fid) succ transf_blk = Some afunc)\n    (* transformation code heap *)\n    (FUNC_TRANS: transform_cdhp C_src afunc = C_tgt)\n    (* analysis for the current source block *)\n    (AI_FOR_CBLK: transf_blk ai_tail BB_src = LvDS.AI.Cons ai ai_pblk)\n    (* current source and target blocks transformation *)\n    (TRANS_PBLK: transform_blk' ai_pblk BB_src = BB_tgt)\n    (* current ai interpretation *)\n    (AI_INTERP: ai_interp inj R_tgt tview_tgt R_src tview_src ai)\n    (* link *)\n    (LINK: forall s BB_src',\n        In s (succ BB_src) -> C_src ! s = Some BB_src' ->\n        LvDS.L.ge ai_tail (LvDS.AI.getFirst (transf_blk (LvDS.AI.getLast (afunc !! s)) BB_src'))):\n    match_state_cur_stkframe inj lo\n                             (R_tgt, BB_tgt, C_tgt, tview_tgt)\n                             (R_src, BB_src, C_src, tview_src).\n\n(* match state for stack frames *) \nInductive match_state_stkframes:\n  Ordering.LocOrdMap ->\n  Continuation.t -> Continuation.t -> Prop :=\n| match_state_stkframes_done\n    lo:\n    match_state_stkframes lo Continuation.done Continuation.done\n| match_state_stkframes_cont\n    lo\n    R_tgt BB_tgt C_tgt cont_tgt \n    R_src BB_src C_src cont_src\n    (CUR_MATCH:  \n       forall tview_tgt tview_src inj', \n         sem_live_loc inj' tview_tgt tview_src (NMem LocSet.empty) ->\n         match_state_cur_stkframe inj' lo\n                                  (R_tgt, BB_tgt, C_tgt, tview_tgt)\n                                  (R_src, BB_src, C_src, tview_src)\n    )\n    (CONT_MATCH: match_state_stkframes lo cont_tgt cont_src):\n    match_state_stkframes lo\n                          (Continuation.stack R_tgt BB_tgt C_tgt cont_tgt)\n                          (Continuation.stack R_src BB_src C_src cont_src).\n\nLemma match_state_call_stack\n      inj lo fid ai_tail ai_pblk nr afunc\n      R_tgt BB_tgt C_tgt tview_tgt\n      R_src BB_src C_src tview_src\n      (FUNC_ANALYSIS: LvDS.analyze_func_backward (C_src, fid) succ transf_blk = Some afunc)\n      (FUNC_TRANS: transform_cdhp C_src afunc = C_tgt)\n      (AI_FOR_CBLK: transf_blk ai_tail BB_src = LvDS.AI.Cons (nr, NMem LocSet.empty) ai_pblk)\n      (TRANS_PBLK: transform_blk' ai_pblk BB_src = BB_tgt)\n      (LV_REG: sem_live_reg R_tgt R_src nr)\n      (LV_LOC: sem_live_loc inj tview_tgt tview_src (NMem LocSet.empty))\n      (LINK: forall s BB_src',\n          In s (succ BB_src) -> C_src ! s = Some BB_src' ->\n          LvDS.L.ge ai_tail (LvDS.AI.getFirst (transf_blk (LvDS.AI.getLast (afunc !! s)) BB_src'))):\n  match_state_cur_stkframe inj lo\n                           (R_tgt, BB_tgt, C_tgt, tview_tgt)\n                           (R_src, BB_src, C_src, tview_src).\nProof.\n  econs; eauto.\n  unfold ai_interp.\n  split; eauto.\nQed.\n\n(* match state for the thread-local state *)\nInductive match_state_tlocal:\n  Mapping -> Ordering.LocOrdMap ->\n  (State.t * TView.t * Memory.t) -> (State.t * TView.t * Memory.t) -> Prop :=\n| match_state_tlocal_intro\n    inj lo\n    R_tgt BB_tgt C_tgt cont_tgt Prog_tgt tview_tgt prm_tgt\n    R_src BB_src C_src cont_src Prog_src tview_src prm_src\n    (PROG_TRANS: transform_prog Prog_src = Some Prog_tgt)\n    (CUR_STK_FRAME: match_state_cur_stkframe inj lo\n                                             (R_tgt, BB_tgt, C_tgt, tview_tgt)\n                                             (R_src, BB_src, C_src, tview_src))\n    (STK_FRAMES: match_state_stkframes lo cont_tgt cont_src):\n    match_state_tlocal inj lo\n                       (State.mk R_tgt BB_tgt C_tgt cont_tgt Prog_tgt, tview_tgt, prm_tgt)\n                       (State.mk R_src BB_src C_src cont_src Prog_src, tview_src, prm_src).\n\n(* match state for thread state *)\nInductive match_state_dce:\n  Mapping -> Ordering.LocOrdMap -> bool ->\n  Thread.t rtl_lang -> Thread.t rtl_lang -> Prop :=\n| match_state_dce_intro\n    inj inj' lo b\n    state_tgt tview_tgt prm_tgt sc_tgt mem_tgt\n    state_src tview_src prm_src sc_src mem_src\n    (INV: I_dce lo inj' (Build_Rss sc_tgt mem_tgt sc_src mem_src))\n    (ATOM_MEM_EQ: Mem_at_eq lo mem_tgt mem_src)\n    (MATCH_THRD_LOCAL: \n       match_state_tlocal inj' lo (state_tgt, tview_tgt, prm_tgt) (state_src, tview_src, prm_src))\n    (VIEW_MATCH: InvView_dce inj' lo tview_tgt tview_src mem_src)\n    (CUR_ACQ: cur_acq lo inj' (TView.cur tview_tgt) (TView.acq tview_tgt)\n                      (TView.cur tview_src) (TView.acq tview_src))\n    (CUR_ACQ_PLN: cur_acq_pln lo inj' (TView.cur tview_tgt) (TView.acq tview_tgt)\n                              (TView.cur tview_src) (TView.acq tview_src))\n    (* promise injection *)\n    (PROM_INJ: promises_relation inj lo prm_tgt prm_src)\n    (ATM_BIT: (b = false /\\ (forall loc t t', inj loc t = Some t' -> inj' loc t = Some t')) \\/\n              (b = true /\\ inj = inj'))\n    (* wf local, closed sc, closed memory *)\n    (LOCAL_WF_TGT: Local.wf (Local.mk tview_tgt prm_tgt) mem_tgt)\n    (CLOSED_SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n    (MEM_CLOSED_TGT: Memory.closed mem_tgt)\n    (LOCAL_WF_SRC: Local.wf (Local.mk tview_src prm_src) mem_src)\n    (CLOSED_SC_SRC: Memory.closed_timemap sc_src mem_src):\n    (*(MEM_CLOSED_SRC: Memory.closed mem_src):*)\n  match_state_dce inj lo b\n                  (Thread.mk rtl_lang state_tgt (Local.mk tview_tgt prm_tgt) sc_tgt mem_tgt)\n                  (Thread.mk rtl_lang state_src (Local.mk tview_src prm_src) sc_src mem_src).\n\nLemma promise_consistent_prsv\n      inj lo\n      tview_tgt prm_tgt tview_src prm_src mem_src\n      (VIEW_MATCH: InvView_dce inj lo tview_tgt tview_src mem_src)\n      (PROM_REL: promises_relation inj lo prm_tgt prm_src)\n      (PROM_CONS: Local.promise_consistent (Local.mk tview_tgt prm_tgt))\n      (MON_INJ: monotonic_inj inj):\n  Local.promise_consistent (Local.mk tview_src prm_src).\nProof.\n  unfold Local.promise_consistent in *; ii; ss.\n  unfold promises_relation in PROM_REL. des. clear PROM_REL0.\n  inv PROM_REL.\n  exploit COMPLETE; eauto. ii; des.\n  rewrite dset_gempty in x0. ss.\n  exploit PROM_CONS; eauto. ii.\n  clear - VIEW_MATCH x x0 x1 MON_INJ.\n  inv VIEW_MATCH.\n  destruct (lo loc) eqn:Heqe.\n  exploit ATM_LOC_CUR_RLX; eauto.\n  exploit NA_LOC_CUR_RLX; eauto.\n  introv TM_H. inv TM_H; ss. eauto.\nQed.\n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/rtl/optimizer/DCEProofMState.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.31742625267332647, "lm_q1q2_score": 0.21121878015226553}}
{"text": "Require Import Setoid PArith.\nFrom hahn Require Import Hahn.\nRequire Import PromisingLib.\nFrom Promising2 Require Import TView View Time Event Cell Thread Memory Configuration Local.\n\nFrom imm Require Import Events.\nFrom imm Require Import Execution.\nFrom imm Require Import Execution_eco.\nFrom imm Require Import imm_s_hb.\nFrom imm Require Import imm_s.\nFrom imm Require Import imm_bob imm_s_ppo.\nFrom imm Require Import CombRelations.\nFrom imm Require Import CombRelationsMore.\nFrom imm Require Import AuxDef.\n\nFrom imm Require Import TraversalConfig.\nFrom imm Require Import ViewRelHelpers.\nRequire Import SimulationRel.\nRequire Import SimState.\nRequire Import MemoryAux.\nRequire Import MaxValue.\nRequire Import ViewRel.\nRequire Import Event_imm_promise.\nRequire Import ExtTraversalConfig.\nRequire Import ExtTraversal.\nRequire Import ExtTraversalProperties.\nRequire Import FtoCoherent.\nRequire Import SimulationRelProperties.\nRequire Import IntervalHelper.\nRequire Import ExistsIssueInterval.\n\nSet Implicit Arguments.\n\nSection IssueStepHelper.\n\nVariable G : execution.\nVariable WF : Wf G.\nVariable sc : relation actid.\n\nNotation \"'acts'\" := G.(acts).\nNotation \"'co'\" := G.(co).\nNotation \"'sw'\" := G.(sw).\nNotation \"'hb'\" := G.(hb).\nNotation \"'sb'\" := G.(sb).\nNotation \"'rf'\" := G.(rf).\nNotation \"'rfi'\" := G.(rfi).\nNotation \"'rfe'\" := G.(rfe).\nNotation \"'rmw'\" := G.(rmw).\nNotation \"'lab'\" := G.(lab).\nNotation \"'msg_rel'\" := (msg_rel G sc).\nNotation \"'urr'\" := (urr G sc).\nNotation \"'release'\" := G.(release).\n\nNotation \"'E'\" := G.(acts_set).\nNotation \"'R'\" := (fun a => is_true (is_r lab a)).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\nNotation \"'Loc_' l\" := (fun x => loc lab x = Some l) (at level 1).\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'W_'\" := (fun l => W ∩₁ Loc_ l).\n(* Notation \"'RW'\" := (fun x => R x \\/ W x). *)\nNotation \"'FR'\" := (fun x => F x \\/ R x).\nNotation \"'FW'\" := (fun x => F x \\/ W x).\n\nNotation \"'W_ex'\" := (W_ex G).\nNotation \"'W_ex_acq'\" := (W_ex ∩₁ (fun a => is_true (is_xacq lab a))).\n\nNotation \"'Pln'\" := (fun a => is_true (is_only_pln lab a)).\nNotation \"'Rlx'\" := (is_rlx lab).\nNotation \"'Rel'\" := (is_rel lab).\nNotation \"'Acq'\" := (is_acq lab).\nNotation \"'Acqrel'\" := (is_acqrel lab).\nNotation \"'Sc'\" := (fun a => is_true (is_sc lab a)).\n\nVariable IMMCON : imm_consistent G sc.\n\nVariable T : trav_config.\nVariable S : actid -> Prop.\nVariable ETCCOH : etc_coherent G sc (mkETC T S).\n\nVariable RELCOV : W ∩₁ Rel ∩₁ issued T ⊆₁ covered T.\n\nVariable f_to f_from : actid -> Time.t.\nVariable FCOH : f_to_coherent G S f_to f_from.\n\nVariable PC : Configuration.t.\nHypothesis THREAD : forall e (ACT : E e) (NINIT : ~ is_init e),\n    exists langst, IdentMap.find (tid e) PC.(Configuration.threads) = Some langst.\n\nVariable smode : sim_mode.\nHypothesis SC_REQ :\n  smode = sim_normal -> \n  forall (l : Loc.t),\n    max_value f_to (S_tm G l (covered T)) (LocFun.find l PC.(Configuration.sc)).\n\nVariable thread : thread_id.\nVariable local : Local.t.\nHypothesis SIM_PROM     : sim_prom     G sc T   f_to f_from thread local.(Local.promises).\nHypothesis SIM_RES_PROM : sim_res_prom G    T S f_to f_from thread local.(Local.promises).\n\nHypothesis CLOSED_SC : Memory.closed_timemap PC.(Configuration.sc) PC.(Configuration.memory).\n\nHypothesis PROM_DISJOINT :\n  forall thread' langst' local'\n         (TNEQ : thread <> thread')\n         (TID' : IdentMap.find thread' PC.(Configuration.threads) =\n                 Some (langst', local')),\n  forall loc to,\n    Memory.get loc to local .(Local.promises) = None \\/\n    Memory.get loc to local'.(Local.promises) = None.\n\nHypothesis PROM_IN_MEM :\n  forall thread' langst local\n         (TID : IdentMap.find thread' PC.(Configuration.threads) =\n                Some (langst, local)),\n    Memory.le local.(Local.promises) PC.(Configuration.memory).\n\nHypothesis INHAB      : Memory.inhabited (Configuration.memory PC).\nHypothesis CLOSED_MEM : Memory.closed (Configuration.memory PC).\nHypothesis PLN_RLX_EQ : pln_rlx_eq local.(Local.tview).\nHypothesis MEM_CLOSE : memory_close local.(Local.tview) PC.(Configuration.memory).\n\nHypothesis RESERVED_TIME:\n  reserved_time G T S f_to f_from smode PC.(Configuration.memory).\n\nHypothesis SIM_RES_MEM :\n  sim_res_mem G T S f_to f_from thread local (Configuration.memory PC).\n\nHypothesis SIM_MEM : sim_mem G sc T f_to f_from thread local PC.(Configuration.memory).\nHypothesis SIM_TVIEW : sim_tview G sc (covered T) f_to local.(Local.tview) thread.\n\nLemma issue_step_helper_no_next w valw locw ordw langst\n      (TID : IdentMap.find (tid w) PC.(Configuration.threads) = Some (langst, local))\n      (NWEX : ~ W_ex w)\n      (NISSB : ~ issued T w)\n      (ISSUABLE : issuable G sc T w)\n      (NONEXT : dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) ⊆₁ ∅)\n      (LOC : loc lab w = Some locw)\n      (VAL : val lab w = Some valw)\n      (ORD : mod lab w = ordw)\n      (WTID : thread = tid w) :\n  let promises := local.(Local.promises) in\n  let memory   := PC.(Configuration.memory) in\n  let sc_view  := PC.(Configuration.sc) in\n  let covered' := if Rel w then covered T ∪₁ eq w else covered T in\n  let T'       := mkTC covered' (issued T ∪₁ eq w) in\n  let S'       := S ∪₁ eq w ∪₁ dom_sb_S_rfrmw G (mkETC T S) rfi (eq w) in\n  exists p_rel,\n    rfrmw_prev_rel G sc T f_to f_from PC.(Configuration.memory) w locw p_rel /\\\n    (⟪ FOR_ISSUE :\n         exists f_to' f_from',\n           let rel'' :=\n               if is_rel lab w\n               then (TView.cur (Local.tview local))\n               else (TView.rel (Local.tview local) locw)\n           in\n           let rel' := (View.join (View.join rel'' p_rel.(View.unwrap))\n                                  (View.singleton_ur locw (f_to' w))) in\n           ⟪ RELWFEQ : View.pln rel' = View.rlx rel' ⟫ /\\\n           ⟪ REL_VIEW_LT : Time.lt (View.rlx rel'' locw) (f_to' w) ⟫ /\\\n           ⟪ REL_VIEW_LE : Time.le (View.rlx rel'  locw) (f_to' w) ⟫ /\\\n\n           ⟪ REQ_TO : forall e (SE : S e) (NEQ : e <> w), f_to' e = f_to e ⟫ /\\\n           ⟪ REQ_FROM : forall e (SE : S e) (NEQ : e <> w), f_from' e = f_from e ⟫ /\\\n           ⟪ ISSEQ_TO   : forall e (ISS: issued T e), f_to' e = f_to e ⟫ /\\\n           ⟪ ISSEQ_FROM : forall e (ISS: issued T e), f_from' e = f_from e ⟫ /\\\n           ⟪ FTOWNBOT : f_to' w <> Time.bot ⟫ /\\\n\n           exists promises_add memory',\n             ⟪ PADD :\n                 Memory.add local.(Local.promises) locw (f_from' w) (f_to' w)\n                            (Message.full valw (Some rel')) promises_add ⟫ /\\\n             ⟪ MADD :\n                 Memory.add memory locw (f_from' w) (f_to' w)\n                            (Message.full valw (Some rel')) memory' ⟫ /\\\n\n             ⟪ INHAB : Memory.inhabited memory' ⟫ /\\\n             ⟪ RELMCLOS : Memory.closed_timemap (View.rlx rel') memory' ⟫ /\\\n             ⟪ RELVCLOS : Memory.closed_view rel' memory' ⟫ /\\\n\n             ⟪ FCOH : f_to_coherent G S' f_to' f_from' ⟫ /\\\n\n             ⟪ HELPER :\n                 sim_mem_helper\n                   G sc f_to' w (f_from' w) valw\n                   (View.join (View.join (if is_rel lab w\n                                          then (TView.cur (Local.tview local))\n                                          else (TView.rel (Local.tview local) locw))\n                                         p_rel.(View.unwrap))\n                              (View.singleton_ur locw (f_to' w))) ⟫ /\\\n\n             ⟪ RESERVED_TIME :\n                 reserved_time G T' S' f_to' f_from' smode memory' ⟫ /\\\n\n             ⟪ MEM_PROMISE :\n                 Memory.promise (Local.promises local) memory locw (f_from' w) (f_to' w)\n                                (Message.full valw (Some rel'))\n                                promises_add memory' Memory.op_kind_add ⟫ /\\\n\n             exists promises',\n               ⟪ PEQ :\n                   if Rel w\n                   then Memory.remove promises_add locw (f_from' w) (f_to' w)\n                                      (Message.full valw (Some rel')) promises'\n                   else promises' = promises_add ⟫ /\\\n\n               ⟪ NEW_PROM_IN_MEM : Memory.le promises' memory' ⟫ /\\\n\n               let tview' := if is_rel lab w\n                             then TView.write_tview\n                                    (Local.tview local) sc_view locw\n                                    (f_to' w) (Event_imm_promise.wmod ordw)\n                             else (Local.tview local) in\n               let local' := Local.mk tview' promises' in\n               let threads' :=\n                   IdentMap.add (tid w)\n                                (langst, local')\n                                (Configuration.threads PC) in\n\n               ⟪ THREAD : forall e (ACT : E e) (NINIT : ~ is_init e),\n                   exists langst, IdentMap.find (tid e) threads' = Some langst ⟫ /\\\n\n               ⟪ SC_REQ : smode = sim_normal -> \n                          forall (l : Loc.t),\n                            max_value\n                              f_to' (S_tm G l covered') (LocFun.find l sc_view) ⟫ /\\\n               ⟪ CLOSED_SC : Memory.closed_timemap sc_view memory' ⟫ /\\\n\n               ⟪ PROM_IN_MEM :\n                   forall thread' langst local\n                          (TID : IdentMap.find thread' threads' = Some (langst, local)),\n                     Memory.le (Local.promises local) memory' ⟫ /\\\n\n               ⟪ SIM_PROM     : sim_prom G sc T' f_to' f_from' (tid w) promises'  ⟫ /\\\n               ⟪ SIM_RES_PROM : sim_res_prom G T' S' f_to' f_from' (tid w) promises'  ⟫ /\\\n\n               ⟪ PROM_DISJOINT :\n                   forall thread' langst' local'\n                          (TNEQ : tid w <> thread')\n                          (TID' : IdentMap.find thread' threads' =\n                                  Some (langst', local')),\n                   forall loc to,\n                     Memory.get loc to promises' = None \\/\n                     Memory.get loc to (Local.promises local') = None ⟫ /\\\n\n               ⟪ SIM_MEM     : sim_mem G sc T' f_to' f_from' (tid w) local' memory' ⟫ /\\\n               ⟪ SIM_RES_MEM : sim_res_mem G T' S' f_to' f_from' (tid w) local' memory' ⟫ /\\\n               ⟪ NOWLOC : Rel w -> Memory.nonsynch_loc locw (Local.promises local') ⟫\n     ⟫ \\/\n     ⟪ FOR_SPLIT :\n         ⟪ SMODE : smode = sim_certification ⟫ /\\\n         exists ws wsv wsrel f_to' f_from',\n           let rel'' :=\n               if is_rel lab w\n               then (TView.cur (Local.tview local))\n               else (TView.rel (Local.tview local) locw)\n           in\n           let rel' := (View.join (View.join rel'' p_rel.(View.unwrap))\n                                  (View.singleton_ur locw (f_to' w))) in\n           let wsmsg := Message.full wsv wsrel in\n           ⟪ NREL    : ~ Rel w ⟫ /\\\n           ⟪ EWS     : E ws ⟫ /\\\n           ⟪ WSS     : S ws ⟫ /\\\n           ⟪ WSISS  : issued T ws ⟫ /\\\n           ⟪ NWEXWS : ~ W_ex ws ⟫ /\\\n           ⟪ WSNCOV  : ~ covered T ws ⟫ /\\\n           ⟪ WSNINIT : ~ is_init ws ⟫ /\\\n           ⟪ WSTID   : tid ws = tid w ⟫ /\\\n           ⟪ WSVAL   : val lab ws = Some wsv ⟫ /\\\n           ⟪ WSSMSG : sim_msg G sc f_to ws (View.unwrap wsrel) ⟫ /\\ \n\n           ⟪ SBWW : sb w ws ⟫ /\\\n           ⟪ SAME_LOC : Loc_ locw ws ⟫ /\\\n           ⟪ COWW : co w ws ⟫ /\\\n\n           ⟪ FEQ1 : f_to' w = f_from' ws ⟫ /\\\n           ⟪ FEQ2 : f_from' w = f_from ws ⟫ /\\\n\n           ⟪ WSPROM : Memory.get locw (f_to ws) (Local.promises local) =\n                      Some (f_from ws, wsmsg)⟫ /\\\n           ⟪ WSMEM : Memory.get locw (f_to ws) memory =\n                     Some (f_from ws, wsmsg)⟫ /\\\n\n           ⟪ RELWFEQ : View.pln rel' = View.rlx rel' ⟫ /\\\n           ⟪ REL_VIEW_LT : Time.lt (View.rlx rel'' locw) (f_to' w) ⟫ /\\\n           ⟪ REL_VIEW_LE : Time.le (View.rlx rel'  locw) (f_to' w) ⟫ /\\\n           ⟪ FCOH : f_to_coherent G S' f_to' f_from' ⟫ /\\\n\n           ⟪ REQ_TO : forall e (SE : S e) (NEQ : e <> w), f_to' e = f_to e ⟫ /\\\n           ⟪ ISSEQ_TO   : forall e (ISS: issued T e), f_to' e = f_to e ⟫ /\\\n           ⟪ FTOWNBOT : f_to' w <> Time.bot ⟫ /\\\n\n           exists promises_add memory',\n             ⟪ PADD :\n                 Memory.split (Local.promises local)\n                              locw (f_from' w) (f_to' w) (f_to' ws)\n                              (Message.full valw (Some rel'))\n                              wsmsg\n                              promises_add ⟫ /\\\n             ⟪ MADD :\n                 Memory.split memory locw (f_from' w) (f_to' w) (f_to' ws)\n                              (Message.full valw (Some rel'))\n                              wsmsg\n                              memory' ⟫ /\\\n\n             ⟪ INHAB : Memory.inhabited memory' ⟫ /\\\n             ⟪ RELMCLOS : Memory.closed_timemap (View.rlx rel') memory' ⟫ /\\\n             ⟪ RELVCLOS : Memory.closed_view rel' memory' ⟫ /\\\n\n\n             ⟪ HELPER :\n                 sim_mem_helper\n                   G sc f_to' w (f_from' w) valw\n                   (View.join (View.join (if is_rel lab w\n                                          then (TView.cur (Local.tview local))\n                                          else (TView.rel (Local.tview local) locw))\n                                         p_rel.(View.unwrap))\n                              (View.singleton_ur locw (f_to' w))) ⟫ /\\\n\n             ⟪ RESERVED_TIME :\n                 reserved_time G T' S' f_to' f_from' smode memory' ⟫ /\\\n\n             exists promises',\n               ⟪ PEQ :\n                   if Rel w\n                   then Memory.remove promises_add locw (f_from' w) (f_to' w)\n                                      (Message.full valw (Some rel')) promises'\n                   else promises' = promises_add ⟫ /\\\n\n               ⟪ NEW_PROM_IN_MEM : Memory.le promises' memory' ⟫ /\\\n\n               let tview' := if is_rel lab w\n                             then TView.write_tview\n                                    (Local.tview local) sc_view locw\n                                    (f_to' w) (Event_imm_promise.wmod ordw)\n                             else (Local.tview local) in\n               let local' := Local.mk tview' promises' in\n               let threads' :=\n                   IdentMap.add (tid w)\n                                (langst, local')\n                                (Configuration.threads PC) in\n\n               ⟪ THREAD : forall e (ACT : E e) (NINIT : ~ is_init e),\n                   exists langst, IdentMap.find (tid e) threads' = Some langst ⟫ /\\\n\n               ⟪ SC_REQ : smode = sim_normal -> \n                          forall (l : Loc.t),\n                            max_value\n                              f_to' (S_tm G l covered') (LocFun.find l sc_view) ⟫ /\\\n               ⟪ CLOSED_SC : Memory.closed_timemap sc_view memory' ⟫ /\\\n\n               ⟪ MEM_PROMISE :\n                   ~ Rel w ->\n                   Memory.promise (Local.promises local) memory locw (f_from' w) (f_to' w)\n                                  (Message.full valw (Some rel'))\n                                  promises' memory'\n                                  (Memory.op_kind_split (f_to' ws) wsmsg) ⟫ /\\\n\n               ⟪ PROM_IN_MEM :\n                   forall thread' langst local\n                          (TID : IdentMap.find thread' threads' = Some (langst, local)),\n                     Memory.le (Local.promises local) memory' ⟫ /\\\n\n               ⟪ SIM_PROM     : sim_prom G sc T' f_to' f_from' (tid w) promises'  ⟫ /\\\n               ⟪ SIM_RES_PROM : sim_res_prom G T' S' f_to' f_from' (tid w) promises'  ⟫ /\\\n\n               ⟪ PROM_DISJOINT :\n                   forall thread' langst' local'\n                          (TNEQ : tid w <> thread')\n                          (TID' : IdentMap.find thread' threads' =\n                                  Some (langst', local')),\n                   forall loc to,\n                     Memory.get loc to promises' = None \\/\n                     Memory.get loc to (Local.promises local') = None ⟫ /\\\n\n               ⟪ SIM_MEM     : sim_mem G sc T' f_to' f_from' (tid w) local' memory' ⟫ /\\\n               ⟪ SIM_RES_MEM : sim_res_mem G T' S' f_to' f_from' (tid w) local' memory' ⟫ /\\\n               ⟪ NOWLOC : Rel w -> Memory.nonsynch_loc locw (Local.promises local') ⟫ ⟫).\nProof using All.\n  assert (tc_coherent G sc T) as TCCOH by apply ETCCOH.\n  assert (complete G) as COMPL by apply IMMCON.\n  assert (sc_per_loc G) as SPL by (apply coherence_sc_per_loc; apply IMMCON).\n \n  assert (NSW : ~ S w).\n  { intros HH. apply NWEX. apply ETCCOH. by split. }\n\n  assert (S ⊆₁ E ∩₁ W) as SEW.\n  { apply set_subset_inter_r. split; [by apply ETCCOH|].\n    apply (reservedW WF ETCCOH). }\n  assert (E w /\\ W w) as [EW WW] by (by apply ISSUABLE).\n  assert (~ covered T w) as NCOVB.\n  { intros AA. apply NISSB. eapply w_covered_issued; eauto. by split. }\n  assert (~ is_init w) as WNINIT.\n  { intros HH. apply NCOVB. eapply init_covered; eauto. by split. }\n\n  subst.\n  edestruct exists_time_interval_for_issue_no_next as [p_rel [PREL [SEW' [HH|HH]]]]; eauto.\n  2: { red in HH. desc. exists p_rel. splits; eauto.\n       right. splits; eauto.\n       set (wsmsg := Message.full wsv wsrel).\n       exists ws, wsv, wsrel. exists f_to', f_from'. \n       splits; eauto.\n       exists promises', memory'. splits; eauto.\n\n       assert (ws <> w) as WSNEQ by (by intros HH; subst).\n       assert (sim_msg G sc f_to' ws (View.unwrap wsrel)) as WSMSG'.\n       { eapply sim_msg_f_issued; eauto. }\n\n       set (rel'' :=\n              if is_rel lab w\n              then (TView.cur (Local.tview local))\n              else (TView.rel (Local.tview local) locw)).\n       set (rel' := (View.join (View.join rel'' p_rel.(View.unwrap))\n                               (View.singleton_ur locw (f_to' w)))).\n\n       assert (exists promises'',\n                  ⟪ PEQ :\n                      if Rel w\n                      then Memory.remove promises' locw (f_from' w) (f_to' w)\n                                         (Message.full valw (Some rel')) promises''\n                      else promises'' = promises' ⟫).\n       { destruct (is_rel lab w) eqn:REL; eauto.\n         edestruct Memory.remove_exists as [promises''].\n         2: { exists promises''. eauto. }\n         erewrite Memory.split_o; eauto. rewrite loc_ts_eq_dec_eq; auto. }\n       desc.\n       exists promises''. simpls.\n       \n       assert (Memory.le promises' memory') as PP.\n       { eapply memory_le_split2; eauto. }\n\n       assert (forall tmap (MCLOS : Memory.closed_timemap tmap PC.(Configuration.memory)),\n                  Memory.closed_timemap tmap memory') as MADDCLOS.\n       { ins. eapply Memory.split_closed_timemap; eauto. }\n       \n       assert (Memory.le promises'' promises') as LEPADD.\n       { destruct (Rel w) eqn:RELB; subst; [|reflexivity].\n         eapply memory_remove_le; eauto. }\n\n       assert (Memory.le promises'' memory') as NEW_PROM_IN_MEM.\n       { etransitivity; eauto. }\n\n       assert (forall l to from msg\n                      (NEQ  : l <> locw \\/ to <> f_to' w)\n                      (NEQ' : l <> locw \\/ to <> f_to' ws),\n                  Memory.get l to memory' = Some (from, msg) <->\n                  Memory.get l to PC.(Configuration.memory) = Some (from, msg))\n         as NOTNEWM.\n       { ins. erewrite Memory.split_o; eauto. rewrite !loc_ts_eq_dec_neq; auto. }\n\n       assert (forall l to from msg\n                      (NEQ  : l <> locw \\/ to <> f_to' w)\n                      (NEQ' : l <> locw \\/ to <> f_to' ws),\n                  Memory.get l to promises' = Some (from, msg) <->\n                  Memory.get l to local.(Local.promises) = Some (from, msg))\n         as NOTNEWA.\n       { ins. erewrite Memory.split_o; eauto. rewrite !loc_ts_eq_dec_neq; auto. }\n\n       assert (forall l to from msg\n                      (NEQ  : l <> locw \\/ to <> f_to' w)\n                      (NEQ' : l <> locw \\/ to <> f_to' ws),\n                  Memory.get l to promises'' = Some (from, msg) <->\n                  Memory.get l to local.(Local.promises) = Some (from, msg))\n         as NOTNEWP.\n       { ins. arewrite (promises'' = promises') by desf. by apply NOTNEWA. }\n\n       assert (~ Rel w ->\n               Memory.get locw (f_to' w) promises'' =\n               Some (f_from' w, Message.full valw (Some rel')))\n         as INP''.\n       { ins. destruct (Rel w); subst; [by desf|].\n         erewrite Memory.split_o; eauto. by rewrite loc_ts_eq_dec_eq. }\n\n       assert (f_to' ws <> f_to' w) as WWSFTONEQ.\n       { intros HH. eapply f_to_eq in HH; eauto.\n         { red. by rewrite LOC. }\n         all: basic_solver. }\n\n       assert (Memory.get locw (f_to' ws) promises' =\n               Some (f_from' ws, Message.full wsv wsrel)) as WSMSGGET'.\n       { erewrite Memory.split_o; eauto. rewrite loc_ts_eq_dec_neq; eauto.\n         rewrite loc_ts_eq_dec_eq. by rewrite FEQ1. }\n\n       assert (Memory.get locw (f_to' ws) promises'' =\n               Some (f_from' ws, Message.full wsv wsrel)) as WSMSGGET'' by desf.\n\n       splits; eauto.\n       { ins.\n         destruct (Ident.eq_dec (tid e) (tid w)) as [EQ|NEQ].\n         { rewrite EQ. rewrite IdentMap.gss.\n           eexists. eauto. }\n         rewrite IdentMap.gso; auto. }\n       { intros QQ l.\n         assert (max_value f_to' (S_tm G l (covered T)) (LocFun.find l (Configuration.sc PC))) as BB.\n         { eapply sc_view_f_issued; eauto. }\n         destruct (Rel w); auto.\n         eapply max_value_same_set.\n         { apply BB. }\n         eapply s_tm_n_f_steps.\n         { apply TCCOH. }\n         { clear. basic_solver. }\n         intros a [HB|HB] HH AA.\n         { eauto. }\n         subst. clear -WW AA. type_solver. }\n       { intros HH. arewrite (promises'' = promises') by desf. }\n       { ins.\n         destruct (Ident.eq_dec thread' (tid w)) as [EQ|NEQ].\n         { subst. rewrite IdentMap.gss in TID0.\n           inv TID0; simpls; clear TID0. }\n         red; ins; rewrite IdentMap.gso in TID0; auto.\n         erewrite Memory.split_o; eauto.\n         destruct (loc_ts_eq_dec (loc, to) (locw, f_to' w)) as [[A B]|LL].\n         { simpls; rewrite A in *; rewrite B in *; subst.\n           exfalso. erewrite NINTER in LHS; eauto. inv LHS. }\n         rewrite (loc_ts_eq_dec_neq LL).\n         set (AA:=LHS).\n         eapply PROM_IN_MEM in AA; eauto.\n         destruct (loc_ts_eq_dec (loc, to) (locw, f_to' ws)) as [[A B]|LL'].\n         2: by rewrite (loc_ts_eq_dec_neq LL').\n         simpls; subst.\n         rewrite (loc_ts_eq_dec_eq locw (f_to' ws)).\n         rewrite REQ_TO in LHS; auto.\n         rewrite REQ_TO in AA; auto.\n         rewrite WSMEM in AA. inv AA.\n         exfalso.\n         edestruct PROM_DISJOINT with (local':=local0) as [BB|BB]; eauto.\n         2: { rewrite BB in LHS. inv LHS. }\n         rewrite WSPROM in BB. inv BB. }\n       { simpls. red. ins.\n         destruct (loc_ts_eq_dec (l, to) (locw, f_to' w)) as [[A' B']|LL].\n         { simpls; rewrite A' in *; rewrite B' in *.\n           destruct (Rel w) eqn:RELB; subst.\n           { erewrite Memory.remove_o in PROM; eauto.\n             rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in PROM. inv PROM. }\n           erewrite Memory.split_o in PROM; eauto.\n           rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in PROM.\n           inv PROM. exists w. splits; eauto. by right. }\n         simpls.\n         assert (PROM' :\n                   Memory.get l to promises' = Some (from, Message.full v rel)).\n         { destruct (Rel w) eqn:RELB; subst; auto. }\n         erewrite Memory.split_o in PROM'; eauto.\n         rewrite (loc_ts_eq_dec_neq LL) in PROM'.\n         destruct (loc_ts_eq_dec (l, to) (locw, f_to' ws)) as [[A' B']|LL'].\n         { simpls; rewrite A' in *; rewrite B' in *.\n           rewrite (loc_ts_eq_dec_eq locw (f_to' ws)) in PROM'.\n           inv PROM'. exists ws. splits; eauto.\n           { basic_solver. }\n           { intros HH. desf. }\n           red. splits; eauto.\n           left. eapply f_to_co_mon; eauto.\n           all: basic_solver. }\n         simpls. rewrite (loc_ts_eq_dec_neq LL') in PROM'.\n         edestruct SIM_PROM as [b H]; eauto; desc.\n         exists b; splits; auto.\n         { by left. }\n         { assert (W b) as WB by (eapply issuedW; eauto).\n           destruct (Rel w) eqn:RELB; auto. }\n         { rewrite ISSEQ_FROM; auto. intros HH. subst.\n           assert (Some l = Some locw) as BB.\n           { rewrite <- LOC0. by rewrite <- SAME_LOC. }\n           inv BB. destruct LL' as [|LL']; [done|].\n           rewrite ISSEQ_TO in LL'; auto. }\n         { by rewrite ISSEQ_TO. }\n         eapply sim_mem_helper_f_issued with (f_to:=f_to); eauto. }\n       { simpls. red. ins.\n         destruct (loc_ts_eq_dec (l, to) (locw, f_to' w)) as [[A' B']|LL].\n         { simpls; rewrite A' in *; rewrite B' in *.\n           destruct (Rel w) eqn:RELB; subst.\n           { erewrite Memory.remove_o in RES; eauto.\n             rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in RES. inv RES. }\n           erewrite Memory.split_o in RES; eauto.\n           rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in RES. inv RES. }\n         simpls.\n         assert (PROM' :\n                   Memory.get l to promises' = Some (from, Message.reserve)).\n         { destruct (Rel w) eqn:RELB; subst; auto. }\n         erewrite Memory.split_o in PROM'; eauto.\n         rewrite (loc_ts_eq_dec_neq LL) in PROM'.\n         destruct (loc_ts_eq_dec (l, to) (locw, f_to' ws)) as [[A' B']|LL'].\n         { simpls; rewrite A' in *; rewrite B' in *.\n           rewrite (loc_ts_eq_dec_eq locw (f_to' ws)) in PROM'.\n           inv PROM'. }\n         simpls. rewrite (loc_ts_eq_dec_neq LL') in PROM'.\n         edestruct SIM_RES_PROM as [b H]; eauto; desc.\n         exists b. splits; auto.\n         { generalize RES0. clear. basic_solver. }\n         { intros [A|A]; desf. }\n         { rewrite REQ_FROM; auto. intros HH; subst.\n           assert (Some l = Some locw) as BB.\n           { rewrite <- LOC0. by rewrite <- SAME_LOC. }\n           inv BB. }\n         rewrite REQ_TO; auto. by intros HH; subst. }\n       { ins.\n         rewrite IdentMap.gso in TID'; auto.\n         destruct (loc_ts_eq_dec (loc, to) (locw, (f_to' w))) as [EQ|NEQ]; simpls.\n         { desc. subst. right.\n           destruct (Memory.get locw (f_to' w) (Local.promises local')) eqn: HH; auto.\n           exfalso.\n           erewrite NINTER in HH; eauto. inv HH. }\n         edestruct (PROM_DISJOINT TNEQ TID') as [HH|HH]; eauto.\n         left.\n         enough (Memory.get loc to promises' = None).\n         { destruct (Rel w) eqn:RELB; subst; auto.\n           erewrite Memory.remove_o; eauto. by rewrite (loc_ts_eq_dec_neq NEQ). }\n         erewrite Memory.split_o; eauto.\n         rewrite (loc_ts_eq_dec_neq NEQ).\n         destruct (loc_ts_eq_dec (loc, to) (locw, (f_to' ws))) as [[A' B']|NEQ'].\n         2: by rewrite (loc_ts_eq_dec_neq NEQ').\n         simpls; rewrite A' in *; rewrite B' in *.\n         exfalso. rewrite REQ_TO in HH; auto.\n         rewrite HH in WSPROM. inv WSPROM. }\n       { red. ins.\n         destruct ISSB as [ISSB|]; subst.\n         { edestruct SIM_MEM as [rel_opt HH]; eauto. simpls. desc.\n           exists rel_opt. unnw.\n           destruct (loc_ts_eq_dec (l, f_to' b) (locw, (f_to' w))) as [EQ|NEQ]; simpls; desc; subst.\n           { exfalso.\n             assert (b = w); [|by desf].\n             eapply f_to_eq; try apply FCOH0; eauto.\n             { red. by rewrite LOC. }\n             { do 2 left. by apply ETCCOH.(etc_I_in_S). }\n             clear. basic_solver. }\n           destruct (loc_ts_eq_dec (l, f_to' b) (locw, (f_to' ws))) as [EQ|NEQ']; simpls; desc; subst.\n           { assert (b = ws); subst.\n             { eapply f_to_eq; try apply FCOH0; eauto.\n               { red. by rewrite SAME_LOC. }\n               { do 2 left. by apply ETCCOH.(etc_I_in_S). }\n               basic_solver. }\n             rewrite INMEM in WSMEM. inv WSMEM.\n             splits; eauto.\n             { red. splits; eauto. left. apply FCOH0; auto.\n               basic_solver. }\n             ins. destruct HH1 as [HH1 HH2]; auto.\n             split; auto.\n             desc. exists p_rel0. split.\n             { rewrite ISSEQ_TO with (e:=ws); auto. desf. }\n             destruct HH0 as [AA|]; desc; [left; split; auto|right].\n             { intros HH. apply NWEXWS. red. generalize HH. clear. basic_solver. }\n             exfalso. apply NWEXWS. red. generalize H2. clear. basic_solver. }\n\n           assert (b <> ws) as NWSNEQ.\n           { intros SUBST; subst.\n             destruct NEQ' as [AA|]; eauto. rewrite LOC0 in SAME_LOC. inv SAME_LOC. }\n           erewrite Memory.split_o with (mem2:=memory'); eauto.\n           rewrite !loc_ts_eq_dec_neq; auto.\n           splits; eauto.\n           { rewrite ISSEQ_TO; auto. rewrite ISSEQ_FROM; auto. }\n           { rewrite ISSEQ_FROM; auto. eapply sim_mem_helper_f_issued; eauto. }\n           intros AA BB.\n           assert (~ covered T b) as NCOVBB.\n           { intros HH. apply BB. generalize HH. clear. basic_solver. }\n           specialize (HH1 AA NCOVBB).\n           desc. splits; auto.\n           { apply NOTNEWP; auto.\n             rewrite ISSEQ_TO; auto. rewrite ISSEQ_FROM; auto. }\n           eexists. splits; eauto.\n           2: { destruct HH2 as [[CC DD]|CC]; [left|right].\n                { split; eauto. intros [y HH]. destruct_seq_l HH as OO.\n                  destruct OO as [OO|]; subst.\n                  { apply CC. exists y. apply seq_eqv_l. by split. }\n                  apply NISSB. eapply rfrmw_I_in_I; eauto. exists b.\n                  apply seqA. apply seq_eqv_r. by split. }\n                desc. exists p. splits; auto.\n                { by left. }\n                assert (loc lab p = Some l) as PLOC.\n                { rewrite <- LOC0. by apply wf_rfrmwl. }\n                eexists. splits; eauto.\n                assert (l <> locw \\/ f_to' p <> f_to' w) as NEQ''.\n                { destruct (classic (l = locw)); subst; [right|left]; auto.\n                  intros HH. eapply f_to_eq in HH; eauto; subst; auto.\n                  { red. by rewrite PLOC. }\n                  { do 2 left. by apply ETCCOH.(etc_I_in_S). }\n                  clear. basic_solver. }\n                destruct (classic (p = ws)) as [|NEQPWS]; subst.\n                2: { apply NOTNEWM; auto.\n                     2: by rewrite ISSEQ_TO; auto; rewrite ISSEQ_FROM.\n                     destruct (classic (l = locw)) as [|LNEQ]; subst; auto.\n                     right. intros HH. eapply f_to_eq in HH; eauto.\n                     { red. by rewrite PLOC. }\n                     all: by do 2 left; apply ETCCOH.(etc_I_in_S). }\n                rewrite PLOC in SAME_LOC. inv SAME_LOC.\n                erewrite Memory.split_o; eauto.\n                rewrite loc_ts_eq_dec_neq; auto.\n                rewrite loc_ts_eq_dec_eq; auto. by rewrite FEQ1. }\n           destruct (Rel w) eqn:RELW; eauto.\n           { by desf. }\n             by rewrite ISSEQ_TO. }\n\n         assert (Some l = Some locw) as QQ.\n         { by rewrite <- LOC0. }\n         inv QQ.\n         eexists. splits; eauto.\n         intros _ NT.\n         destruct (Rel b); desf.\n         splits.\n         { erewrite Memory.split_o; eauto. rewrite loc_ts_eq_dec_eq; eauto. }\n         exists p_rel. splits; eauto. left.\n         cdes PREL. destruct PREL1; desc.\n         2: { exfalso. apply NWEX. red. generalize INRMW. clear. basic_solver. }\n         split; auto.\n         intros [a HH].\n         apply seq_eqv_l in HH. destruct HH as [[HH|] RFRMW]; subst; eauto.\n         { apply NINRMW. generalize HH RFRMW. clear. basic_solver 10. }\n         eapply wf_rfrmw_irr; eauto. }\n       { red. ins.\n         assert (b <> w /\\ ~ issued T b) as [BNEQ NISSBB].\n         { generalize NISSB0. clear. basic_solver. }\n         assert (b <> ws) as BNEQ'.\n         { intros HH; subst. eauto. }\n         destruct RESB as [[SB|]|HH]; subst.\n         3: { exfalso. eapply NONEXT; eauto. }\n         2: by desf.\n         unnw.\n         erewrite Memory.split_o with (mem2:=memory'); eauto.\n         destruct (loc_ts_eq_dec (l, f_to' b) (locw, (f_to' w))) as [PEQ'|PNEQ];\n           simpls; desc; subst.\n         { exfalso. apply BNEQ.\n           eapply f_to_eq with (f_to:=f_to'); eauto. red.\n           { by rewrite LOC. }\n           { by do 2 left. }\n           clear. basic_solver. }\n         rewrite (loc_ts_eq_dec_neq PNEQ).\n         destruct (loc_ts_eq_dec (l, f_to' b) (locw, (f_to' ws))) as [PEQ''|PNEQ'];\n           simpls; desc; subst.\n         { exfalso. apply BNEQ'.\n           eapply f_to_eq with (f_to:=f_to'); eauto. red.\n           { by rewrite LOC0. }\n           all: by do 2 left. }\n         rewrite (loc_ts_eq_dec_neq PNEQ').\n         edestruct SIM_RES_MEM with (b:=b); eauto; unnw.\n         rewrite REQ_TO; auto. rewrite REQ_FROM; auto.\n         splits; ins.\n         apply NOTNEWP; auto.\n         all: rewrite <- REQ_TO; auto. }\n       intros WREL. exfalso. desf. }\n  red in HH. desc. exists p_rel. splits; eauto.\n  left. exists f_to', f_from'. splits; eauto.\n  exists promises', memory'. splits; eauto.\n\n  set (rel'' :=\n        if is_rel lab w\n        then (TView.cur (Local.tview local))\n        else (TView.rel (Local.tview local) locw)).\n  set (rel' := (View.join (View.join rel'' p_rel.(View.unwrap))\n                          (View.singleton_ur locw (f_to' w)))).\n\n  assert (exists promises'',\n             ⟪ PEQ :\n                 if Rel w\n                 then Memory.remove promises' locw (f_from' w) (f_to' w)\n                                    (Message.full valw (Some rel')) promises''\n                 else promises'' = promises' ⟫).\n  { destruct (is_rel lab w) eqn:REL; eauto.\n    edestruct Memory.remove_exists as [promises''].\n    2: { exists promises''. eauto. }\n    erewrite Memory.add_o; eauto. rewrite loc_ts_eq_dec_eq; auto. }\n  desc.\n  exists promises''. simpls.\n  \n  assert (Memory.le promises' memory') as PP.\n  { eapply memory_le_add2; eauto. }\n\n  assert (forall thread' langst' local' (TNEQ : tid w <> thread')\n                 (TID' : IdentMap.find thread' (Configuration.threads PC) =\n                         Some (langst', local')),\n             Memory.get locw (f_to' w) (Local.promises local') = None) as NINTER.\n  (* TODO: Move to IssueInterval.v? *)\n  { ins.\n    destruct (Memory.get locw (f_to' w) (Local.promises local')) eqn:HH; auto.\n    exfalso. destruct p as [from]. \n    eapply PROM_IN_MEM in HH; eauto.\n    set (AA := HH). apply Memory.get_ts in AA.\n    destruct AA as [|AA]; desc; eauto.\n    apply DISJOINT in HH.\n    apply HH with (x:=f_to' w); constructor; simpls; try reflexivity.\n    apply FCOH0; auto. clear. basic_solver. }\n\n  assert (forall tmap (MCLOS : Memory.closed_timemap tmap PC.(Configuration.memory)),\n             Memory.closed_timemap tmap memory') as MADDCLOS.\n  { ins. eapply Memory.add_closed_timemap; eauto. }\n  \n  assert (Memory.le promises'' promises') as LEPADD.\n  { destruct (Rel w) eqn:RELB; subst; [|reflexivity].\n    eapply memory_remove_le; eauto. }\n\n  assert (Memory.le promises'' memory') as NEW_PROM_IN_MEM.\n  { etransitivity; eauto. }\n\n  (* assert (forall l to from msg  *)\n  (*                (NEQ : l <> locw \\/ to <> f_to w), *)\n  (*            Memory.get l to promises_cancel = Some (from, msg) <-> *)\n  (*            Memory.get l to local.(Local.promises) = Some (from, msg)) *)\n  (*   as NOTNEWC. *)\n  (* { ins. erewrite Memory.remove_o; eauto. *)\n  (*   rewrite loc_ts_eq_dec_neq; auto. } *)\n\n  assert (forall l to from msg\n                 (NEQ : l <> locw \\/ to <> f_to' w),\n             Memory.get l to memory' = Some (from, msg) <->\n             Memory.get l to PC.(Configuration.memory) = Some (from, msg))\n    as NOTNEWM.\n  { ins. erewrite Memory.add_o; eauto.\n    rewrite loc_ts_eq_dec_neq; auto. }\n\n  assert (forall l to from msg\n                 (NEQ : l <> locw \\/ to <> f_to' w),\n             Memory.get l to promises' = Some (from, msg) <->\n             Memory.get l to local.(Local.promises) = Some (from, msg))\n    as NOTNEWA.\n  { ins. erewrite Memory.add_o; eauto.\n    rewrite loc_ts_eq_dec_neq; auto. }\n\n  assert (forall l to from msg\n                 (NEQ : l <> locw \\/ to <> f_to' w),\n             Memory.get l to promises'' = Some (from, msg) <->\n             Memory.get l to local.(Local.promises) = Some (from, msg))\n    as NOTNEWP.\n  { ins. destruct (Rel w); subst; auto.\n    erewrite Memory.remove_o; eauto. rewrite loc_ts_eq_dec_neq; auto. }\n\n  assert (~ Rel w ->\n          Memory.get locw (f_to' w) promises'' =\n          Some (f_from' w, Message.full valw (Some rel')))\n    as INP''.\n  { ins. destruct (Rel w); subst; [by desf|].\n    erewrite Memory.add_o; eauto. by rewrite loc_ts_eq_dec_eq. }\n\n  splits; eauto.\n  { ins.\n    destruct (Ident.eq_dec (tid e) (tid w)) as [EQ|NEQ].\n    { rewrite EQ. rewrite IdentMap.gss.\n      eexists. eauto. }\n    rewrite IdentMap.gso; auto. }\n  { intros QQ l.\n    assert (max_value f_to' (S_tm G l (covered T)) (LocFun.find l (Configuration.sc PC))) as BB.\n    { eapply sc_view_f_issued; eauto. }\n    destruct (Rel w); auto.\n    eapply max_value_same_set.\n    { apply BB. }\n    eapply s_tm_n_f_steps.\n    { apply TCCOH. }\n    { clear. basic_solver. }\n    intros a [HB|HB] HH AA.\n    { eauto. }\n    subst. clear -WW AA. type_solver. }\n  { ins.\n    destruct (Ident.eq_dec thread' (tid w)) as [EQ|NEQ].\n    { subst. rewrite IdentMap.gss in TID0.\n      inv TID0; simpls; clear TID0. }\n    red; ins; rewrite IdentMap.gso in TID0; auto.\n    erewrite Memory.add_o; eauto.\n    destruct (loc_ts_eq_dec (loc, to) (locw, f_to' w)) as [[A B]|LL].\n    { simpls; rewrite A in *; rewrite B in *; subst.\n      exfalso. erewrite NINTER in LHS; eauto. inv LHS. }\n    rewrite (loc_ts_eq_dec_neq LL).\n    eapply PROM_IN_MEM in LHS; eauto. }\n  { simpls. red. ins.\n    destruct (loc_ts_eq_dec (l, to) (locw, f_to' w)) as [[A' B']|LL].\n    { simpls; rewrite A' in *; rewrite B' in *.\n      destruct (Rel w) eqn:RELB; subst.\n      { erewrite Memory.remove_o in PROM; eauto.\n        rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in PROM. inv PROM. }\n      erewrite Memory.add_o in PROM; eauto.\n      rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in PROM.\n      inv PROM. exists w. splits; eauto. by right. }\n    eapply NOTNEWP in PROM; eauto.\n    edestruct SIM_PROM as [b H]; eauto; desc.\n    exists b; splits; auto.\n    { by left. }\n    { assert (W b) as WB by (eapply issuedW; eauto).\n      destruct (Rel w) eqn:RELB; auto.\n      intros [HH|HH]; desf. }\n    { by rewrite ISSEQ_FROM. }\n    { by rewrite ISSEQ_TO. }\n    eapply sim_mem_helper_f_issued with (f_to:=f_to); eauto. }\n  { simpls. red. ins.\n    destruct (loc_ts_eq_dec (l, to) (locw, f_to' w)) as [[A' B']|LL].\n    { simpls; rewrite A' in *; rewrite B' in *.\n      destruct (Rel w) eqn:RELB; subst.\n      { erewrite Memory.remove_o in RES; eauto.\n        rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in RES. inv RES. }\n      erewrite Memory.add_o in RES; eauto.\n      rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in RES. inv RES. }\n    apply NOTNEWP in RES; auto.\n    edestruct SIM_RES_PROM as [b H]; eauto; desc.\n    exists b. splits; auto.\n    { generalize RES0. basic_solver. }\n    { intros [A|A]; desf. }\n    { rewrite REQ_FROM; auto. by intros HH; subst. }\n      rewrite REQ_TO; auto. by intros HH; subst. }\n  { ins.\n    rewrite IdentMap.gso in TID'; auto.\n    destruct (loc_ts_eq_dec (loc, to) (locw, (f_to' w))) as [EQ|NEQ]; simpls.\n    { desc. subst. right.\n      destruct (Memory.get locw (f_to' w) (Local.promises local')) eqn: HH; auto.\n      exfalso.\n      erewrite NINTER in HH; eauto. inv HH. }\n    edestruct (PROM_DISJOINT TNEQ TID') as [HH|HH]; eauto.\n    left.\n    destruct (Memory.get loc to promises'') eqn:BB; auto.\n    destruct p. eapply NOTNEWP in BB; eauto. desf. }\n  { red. ins.\n    destruct ISSB as [ISSB|]; subst.\n    { edestruct SIM_MEM as [rel_opt HH]; eauto. simpls. desc.\n      exists rel_opt. unnw.\n      destruct (loc_ts_eq_dec (l, f_to' b) (locw, (f_to' w))) as [EQ|NEQ]; simpls; desc; subst.\n      { exfalso.\n        assert (b = w); [|by desf].\n        eapply f_to_eq; try apply FCOH0; eauto.\n        { red. by rewrite LOC. }\n        { do 2 left. by apply ETCCOH.(etc_I_in_S). }\n        clear. basic_solver. }\n      erewrite Memory.add_o with (mem2:=memory'); eauto.\n      rewrite !loc_ts_eq_dec_neq; auto.\n      splits; eauto.\n      { rewrite ISSEQ_TO; auto. rewrite ISSEQ_FROM; auto. }\n      { rewrite ISSEQ_FROM; auto. eapply sim_mem_helper_f_issued; eauto. }\n      intros AA BB.\n      assert (~ covered T b) as NCOVBB.\n      { intros HH. apply BB. generalize HH. clear. basic_solver. }\n      specialize (HH1 AA NCOVBB).\n      desc. splits; auto.\n      { apply NOTNEWP; auto.\n        rewrite ISSEQ_TO; auto. rewrite ISSEQ_FROM; auto. }\n      eexists. splits; eauto.\n      2: { destruct HH2 as [[CC DD]|CC]; [left|right].\n           { split; eauto. intros [y HH]. destruct_seq_l HH as OO.\n             destruct OO as [OO|]; subst.\n             { apply CC. exists y. apply seq_eqv_l. by split. }\n             apply NISSB. eapply rfrmw_I_in_I; eauto. exists b.\n             apply seqA. apply seq_eqv_r. by split. }\n           desc. exists p. splits; auto.\n           { by left. }\n           eexists. splits; eauto.\n           rewrite ISSEQ_TO; auto. rewrite ISSEQ_FROM; auto.\n           apply NOTNEWM; auto.\n           destruct (classic (l = locw)) as [|LNEQ]; subst; auto.\n           right. intros HH.\n           rewrite <- ISSEQ_TO in HH; auto.\n           eapply f_to_eq in HH; eauto; subst; auto.\n           { red. rewrite LOC. rewrite <- LOC0. by apply WF.(wf_rfrmwl). }\n           { do 2 left. by apply ETCCOH.(etc_I_in_S). }\n           clear. basic_solver. }\n      destruct (Rel w) eqn:RELW; auto.\n      2: by rewrite ISSEQ_TO.\n      assert (wmod (mod lab w) = Ordering.acqrel) as MM.\n      { clear -RELW. mode_solver. }\n      rewrite MM.\n      unfold TView.rel, TView.write_tview. \n      arewrite (Ordering.le Ordering.acqrel Ordering.acqrel = true) by reflexivity.\n      destruct (classic (l = locw)) as [|LNEQ]; subst.\n      2: { unfold LocFun.add. rewrite Loc.eq_dec_neq; auto. by rewrite ISSEQ_TO. }\n      exfalso.\n      assert (E b) as EB by (eapply issuedE; eauto).\n      assert (W b) as WB by (eapply issuedW; eauto).\n      assert ((⦗E⦘ ⨾ same_tid ⨾ ⦗E⦘) w b) as ST.\n      { apply seq_eqv_lr. by splits. }\n      apply tid_sb in ST. destruct ST as [[[|ST]|ST]|[AI BI]]; subst; auto.\n      2: { apply NCOVBB. apply ISSUABLE. exists w. apply seq_eqv_r. split; auto.\n           apply sb_to_w_rel_in_fwbob. apply seq_eqv_r. split; auto. by split. }\n      assert (issuable G sc T b) as IB by (eapply issued_in_issuable; eauto).\n      apply NCOVB. apply IB. exists b. apply seq_eqv_r. split; auto.\n      apply sb_from_w_rel_in_fwbob; auto. apply seq_eqv_lr. splits; auto.\n      all: split; auto. red. by rewrite LOC. }\n    assert (Some l = Some locw) as QQ.\n    { by rewrite <- LOC0. }\n    inv QQ.\n    eexists. splits; eauto.\n    { erewrite Memory.add_o; eauto. rewrite loc_ts_eq_dec_eq; eauto. }\n    { apply HELPER. }\n    { apply RELWFEQ. }\n    { apply RELMCLOS. }\n    intros _ NT.\n    destruct (Rel b); desf.\n    { exfalso. apply NT. by right. }\n    splits.\n    { erewrite Memory.add_o; eauto. rewrite loc_ts_eq_dec_eq; eauto. }\n    exists p_rel. splits; eauto. left.\n    cdes PREL. destruct PREL1; desc.\n    2: { exfalso. apply NWEX. red. generalize INRMW. clear. basic_solver. }\n    split; auto.\n    intros [a HH].\n    apply seq_eqv_l in HH. destruct HH as [[HH|] RFRMW]; subst; eauto.\n    { apply NINRMW. generalize HH RFRMW. clear. basic_solver 10. }\n    eapply wf_rfrmw_irr; eauto. }\n  { red. ins.\n    assert (b <> w /\\ ~ issued T b) as [BNEQ NISSBB].\n    { generalize NISSB0. clear. basic_solver. }\n    destruct RESB as [[SB|]|HH]; subst.\n    3: { exfalso. eapply NONEXT; eauto. }\n    2: by desf.\n    unnw.\n    erewrite Memory.add_o with (mem2:=memory'); eauto.\n    destruct (loc_ts_eq_dec (l, f_to' b) (locw, (f_to' w))) as [PEQ'|PNEQ];\n      simpls; desc; subst.\n    { exfalso. apply BNEQ.\n      eapply f_to_eq with (f_to:=f_to'); eauto. red.\n      { by rewrite LOC. }\n      { by do 2 left. }\n      clear. basic_solver. }\n    edestruct SIM_RES_MEM with (b:=b); eauto; unnw.\n    rewrite !(loc_ts_eq_dec_neq PNEQ); auto.\n    rewrite REQ_TO; auto. rewrite REQ_FROM; auto.\n    splits; ins.\n    apply NOTNEWP; auto. rewrite <- REQ_TO; auto. }\n  intros WREL. red. ins. destruct msg; auto.\n  rewrite WREL in PEQ.\n  exfalso. \n  erewrite Memory.remove_o in GET; eauto.\n  destruct (loc_ts_eq_dec (locw, t) (locw, f_to' w)) as [AA|NEQ]; simpls.\n  { desc; subst. rewrite (loc_ts_eq_dec_eq locw (f_to' w)) in GET.\n    inv GET. }\n  rewrite (loc_ts_eq_dec_neq NEQ) in GET.\n  erewrite Memory.add_o in GET; eauto.\n  rewrite (loc_ts_eq_dec_neq NEQ) in GET.\n  eapply SIM_PROM in GET. desc; subst.\n  assert (E b) as EB.\n  { eapply issuedE; eauto. }\n  assert (W b) as WB.\n  { eapply issuedW; eauto. }\n  assert ((⦗E⦘ ⨾ same_tid ⨾ ⦗E⦘) b w) as HH.\n  { apply seq_eqv_lr. splits; auto. }\n  apply tid_sb in HH. destruct HH as [[[HH|HH]|HH]|[AA BB]]; subst; auto.\n  2: { apply NCOVB. eapply dom_W_Rel_sb_loc_I_in_C; eauto.\n       exists b. apply seq_eqv_l. split; [by split|].\n       apply seqA.\n       do 2 (apply seq_eqv_r; split; auto).\n       split; auto. red. rewrite LOC. auto. }\n  apply NCOV. apply ISSUABLE. exists w. apply seq_eqv_r. split; auto.\n  apply sb_to_w_rel_in_fwbob. apply seq_eqv_r. \n  do 2 (split; auto).\nQed.\n\nEnd IssueStepHelper.\n", "meta": {"author": "weakmemory", "repo": "promising2ToImm", "sha": "8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c", "save_path": "github-repos/coq/weakmemory-promising2ToImm", "path": "github-repos/coq/weakmemory-promising2ToImm/promising2ToImm-8f462969e0cfaa0bb71d43b4cdae0f030d06ef9c/src/reserve_steps/IssueStepHelper.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.3276682942552091, "lm_q1q2_score": 0.2110921417587692}}
{"text": "(** * Implementation of Section 4.4 *)\nRequire Import RL.Utilities.Rpos.\nRequire Import RL.Utilities.riesz_logic_List_more.\nRequire Import RL.hmr.term.\nRequire Import RL.hmr.hseq.\nRequire Import RL.hmr.hmr.\nRequire Import RL.hmr.semantic.\nRequire Import RL.hmr.interpretation.\nRequire Import RL.hmr.tech_lemmas.\nRequire Import RL.hmr.lambda_prop_tools.\nRequire Import RL.hmr.soundness.\nRequire Import RL.hmr.tactics.\n\nRequire Import Lra.\nRequire Import Lia.\n\nRequire Import RL.OLlibs.List_more.\nRequire Import RL.OLlibs.List_Type.\nRequire Import RL.OLlibs.Permutation_Type_more.\nRequire Import RL.OLlibs.Permutation_Type_solve.\n\nLocal Open Scope R_scope.\n\n(** ** First formulation : A = B implies |- 1.A,1.-B and |- 1.B, 1.-A are derivable *)\n(** Proof of Lemma 4.20 *)\nLemma completeness_1 : forall A B r, A === B -> HMR_M_can (((r, -S B) :: (r, A) :: nil) :: nil)\nwith completeness_2 : forall A B r, A === B -> HMR_M_can (((r, -S A) :: (r, B) :: nil) :: nil).\nProof with try assumption; try reflexivity.\n  - intros A B r Heq; destruct Heq.\n    + change ((r, -S t) :: (r, t) :: nil) with ((vec (r :: nil) (-S t)) ++ (vec (r :: nil) t) ++ nil).\n      apply hmrr_ID_gen...\n      apply hmrr_INIT.\n    + apply hmrr_can with t2 (r :: nil) (r :: nil)...\n      apply hmrr_ex_seq with (((r, -S t2) :: (r, t1) :: nil) ++ ((r, -S t3) :: (r, t2) :: nil)); [ Permutation_Type_solve | ].\n      apply hmrr_M; try reflexivity; [ apply (completeness_1 _ _ _ Heq1) | apply (completeness_1 _ _ _ Heq2)].\n    + revert r; induction c; (try rename r into r0); intros r.\n      * apply completeness_1.\n        apply Heq.\n      * eapply hmrr_ex_seq ; [ apply Permutation_Type_swap | ].\n        apply completeness_2.\n        simpl; rewrite minus_minus; apply Heq.\n      * simpl; change ((r, -S t) :: (r, t) :: nil) with ((vec (r :: nil) (-S t)) ++ (vec (r :: nil) t) ++ nil).\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * simpl.\n        change ((r, MRS_covar v) :: (r, MRS_var v) :: nil) with ((vec (r :: nil) (MRS_covar v)) ++ (vec (r :: nil) (MRS_var v)) ++ nil).\n        apply hmrr_ID...\n        apply hmrr_INIT.\n      * simpl.\n        apply hmrr_ex_seq with ((vec (r :: nil) (MRS_covar v)) ++ (vec (r :: nil) (MRS_var v)) ++ nil) ; [Permutation_Type_solve | ].\n        apply hmrr_ID...\n        apply hmrr_INIT.\n      * simpl.\n        change ((r, MRS_zero) :: (r, MRS_zero) :: nil) with ((vec (r:: r:: nil) MRS_zero) ++ nil).\n        apply hmrr_Z.\n        apply hmrr_INIT.\n      * unfold evalContext; fold evalContext.\n        unfold MRS_minus; fold MRS_minus.\n        apply hmrr_ex_seq with ((vec (r :: nil) (evalContext c1 t1 /\\S evalContext c2 t1)) ++ (vec (r :: nil) (-S evalContext c1 t2 \\/S -S evalContext c2 t2)) ++ nil) ; [ Permutation_Type_solve | ].\n        apply hmrr_min.\n        -- apply hmrr_ex_seq with  ((vec (r :: nil) (-S evalContext c1 t2 \\/S -S evalContext c2 t2)) ++ (vec (r :: nil) (evalContext c1 t1)) ++ nil); [ Permutation_Type_solve | ].\n           apply hmrr_max.\n           apply hmrr_W.\n           apply IHc1.\n        -- apply hmrr_ex_seq with  ((vec (r :: nil) (-S evalContext c1 t2 \\/S -S evalContext c2 t2)) ++ (vec (r :: nil) (evalContext c2 t1)) ++ nil); [ Permutation_Type_solve | ].\n           apply hmrr_max.\n           eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n           apply hmrr_W.\n           eapply hmrr_ex_seq ; [ | apply IHc2].\n           Permutation_Type_solve.\n      * unfold evalContext; fold evalContext.\n        unfold MRS_minus; fold MRS_minus.\n        change ((r, -S evalContext c1 t2 /\\S -S evalContext c2 t2)\n                  :: (r, evalContext c1 t1 \\/S evalContext c2 t1) :: nil) with\n            ((vec (r ::nil) (-S evalContext c1 t2 /\\S -S evalContext c2 t2)) ++ (vec (r ::nil) (evalContext c1 t1 \\/S evalContext c2 t1)) ++ nil).\n        apply hmrr_min.\n        -- apply hmrr_ex_seq with  ((vec (r :: nil) (evalContext c1 t1 \\/S evalContext c2 t1)) ++ (vec (r :: nil) (-S evalContext c1 t2)) ++ nil); [ Permutation_Type_solve | ].\n           apply hmrr_max.\n           apply hmrr_W.\n           eapply hmrr_ex_seq ; [ | apply IHc1].\n           Permutation_Type_solve.\n        -- apply hmrr_ex_seq with  ((vec (r :: nil) (evalContext c1 t1 \\/S evalContext c2 t1)) ++ (vec (r :: nil) (-S evalContext c2 t2)) ++ nil); [ Permutation_Type_solve | ].\n           apply hmrr_max.\n           eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n           apply hmrr_W.\n           eapply hmrr_ex_seq ; [ | apply IHc2].\n           Permutation_Type_solve.\n      * unfold evalContext; fold evalContext; unfold MRS_minus; fold MRS_minus.\n        change ((r, (-S evalContext c1 t2) -S (evalContext c2 t2))\n                  :: (r, evalContext c1 t1 +S evalContext c2 t1) :: nil)\n          with ((vec (r :: nil) ((-S evalContext c1 t2) -S (evalContext c2 t2))) ++ (vec (r :: nil) (evalContext c1 t1 +S evalContext c2 t1)) ++ nil).\n        apply hmrr_plus.\n        apply hmrr_ex_seq with (vec (r :: nil) (evalContext c1 t1 +S evalContext c2 t1) ++\n                               vec (r :: nil) (-S evalContext c1 t2) ++\n                               vec (r :: nil) (-S evalContext c2 t2) ++ nil) ; [ Permutation_Type_solve | ].\n        apply hmrr_plus.\n        apply hmrr_ex_seq with (((r, -S evalContext c1 t2) :: (r, evalContext c1 t1) :: nil) ++ ((r, -S evalContext c2 t2) :: (r, evalContext c2 t1) :: nil)) ; [ Permutation_Type_solve | ].\n        apply hmrr_M; try reflexivity; [ apply IHc1 | apply IHc2].\n      * unfold evalContext; fold evalContext; unfold MRS_minus; fold MRS_minus.\n        change ((r, r0 *S (-S evalContext c t2)) :: (r, r0 *S evalContext c t1) :: nil) with ((vec (r :: nil) (r0 *S (-S evalContext c t2))) ++ (vec (r :: nil) (r0 *S evalContext c t1)) ++ nil).\n        apply hmrr_mul.\n        apply hmrr_ex_seq with (vec (r :: nil) (r0 *S evalContext c t1) ++ vec (mul_vec r0 (r :: nil)) (-S evalContext c t2) ++  nil) ; [ Permutation_Type_solve | ].\n        apply hmrr_mul.\n        simpl.\n        eapply hmrr_ex_seq; [ | apply IHc].\n        Permutation_Type_solve.\n      * simpl.\n        change ((r, MRS_coone) :: (r, MRS_one) :: nil) with (vec (r :: nil) MRS_coone ++ vec (r :: nil) MRS_one ++ nil).\n        apply hmrr_one; [ | apply hmrr_INIT].\n        simpl; nra.\n      * eapply hmrr_ex_seq;  [ apply Permutation_Type_swap | ].\n        simpl.\n        change ((r, MRS_coone) :: (r, MRS_one) :: nil) with (vec (r :: nil) MRS_coone ++ vec (r :: nil) MRS_one ++ nil).\n        apply hmrr_one; [ | apply hmrr_INIT].\n        simpl; nra.\n      * simpl in *.\n        change ((r, <S> (-S evalContext c t2)) :: (r, <S> evalContext c t1) :: nil) with (seq_diamond ((r , (-S evalContext c t2)) :: (r , evalContext c t1) :: nil)).\n        apply hmrr_diamond_no_one.\n        apply IHc.\n    + apply (completeness_2 _ _ _ Heq).\n    + replace (((r, -S subs t2 n t) :: (r, subs t1 n t) :: nil) :: nil) with (subs_hseq (((r, -S t2) :: (r, t1) :: nil) :: nil) n t) by now rewrite <-eq_subs_minus.\n      apply subs_proof.\n      apply completeness_1; apply Heq.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can. do_HMR_logical.\n      apply hmrr_ex_seq with ((vec (r :: nil) (-S t1)) ++ (vec (r :: nil) (t1)) ++ (vec (r :: nil) (-S t2)) ++ (vec (r :: nil) (t2)) ++ (vec (r :: nil) (-S t3)) ++ (vec (r :: nil) (t3)) ++ nil); [ Permutation_Type_solve | ].\n      do 3 (apply hmrr_ID_gen; try reflexivity).\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with ((vec (r :: nil) (-S t1)) ++ (vec (r :: nil) (t1)) ++ (vec (r :: nil) (-S t2)) ++ (vec (r :: nil) (t2)) ++ nil); [ Permutation_Type_solve | ].\n      do 2 (apply hmrr_ID_gen; try reflexivity).\n      apply hmrr_INIT.\n    + unfold HMR_M_can; do_HMR_logical.\n      pattern t at 1; rewrite <- minus_minus.\n      apply hmrr_ID_gen...\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      pattern t at 1; rewrite <-(minus_minus t).\n      rewrite<- ? app_assoc; apply hmrr_ID_gen...\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      unfold mul_vec.\n      apply hmrr_ex_seq with ((vec ((time_pos (minus_pos Hlt) r) ::(time_pos b r) :: nil) (-S t)) ++ (vec ((time_pos a r) :: nil) t) ++ nil); [ Permutation_Type_solve | ].\n      apply hmrr_ID_gen ; [ | apply hmrr_INIT ].\n      simpl; destruct a; destruct b; destruct r; unfold minus_pos.\n      simpl; nra.\n    + pattern t at 2; rewrite <- minus_minus.\n      apply hmrr_ex_seq with ((vec (r :: nil) (One *S (-S (-S t)))) ++ (vec (r :: nil) (-S t)) ++ nil); [ Permutation_Type_solve | ].\n      apply hmrr_mul.\n      apply hmrr_ID_gen; [ destruct r; simpl; nra | apply hmrr_INIT].\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      pattern t at 1; rewrite <- minus_minus.\n      apply hmrr_ID_gen ; [ | apply hmrr_INIT].\n      destruct r; destruct x; destruct y; simpl.\n      nra.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with ((vec (mul_vec x (r :: nil)) (-S t1)) ++ (vec (mul_vec x (r :: nil)) ( t1)) ++ (vec (mul_vec x (r :: nil)) (-S t2))++ (vec (mul_vec x (r :: nil)) (t2)) ++ nil) ; [ Permutation_Type_solve | ].\n      do 2 (apply hmrr_ID_gen; try reflexivity).\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      unfold mul_vec.\n      apply hmrr_ex_seq with ((vec ((time_pos x r) :: (time_pos y r) :: nil) (-S t)) ++ (vec (time_pos (plus_pos x y) r :: nil) t) ++ nil) ; [ Permutation_Type_solve | ].\n      apply hmrr_ID_gen; [ | apply hmrr_INIT].\n      destruct r; destruct x; destruct y; unfold plus_pos; simpl; nra.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ID_gen ; [ | apply hmrr_INIT].\n      simpl; nra.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W; apply hmrr_W.\n        pattern t1 at 1; rewrite <- (minus_minus).\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        pattern t2 at 1; rewrite <- (minus_minus).\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | apply hmrr_W ; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | apply hmrr_W]].\n        pattern t3 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        pattern t2 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        pattern t1 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W.\n        pattern t1 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        pattern t1 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * pattern t1 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        pattern t1 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W.\n        rewrite <- app_assoc.\n        apply hmrr_ID_gen...\n        pattern t3 at 1; rewrite<- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        rewrite <-app_assoc; apply hmrr_ID_gen...\n        pattern t3 at 1; rewrite<- minus_minus; apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        rewrite <-app_assoc; apply hmrr_ID_gen...\n        pattern t3 at 1; rewrite<- minus_minus; apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_INIT.\n      * simpl.\n        eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n        apply hmrr_W.\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      change (vec (r :: nil) (<S> (-S t1)) ++ vec (r :: nil) (<S> (-S t2)) ++ vec (r :: nil) (<S> (t1 +S t2)) ++ nil)\n        with\n          (seq_diamond (vec (r :: nil) (-S t1) ++ vec (r :: nil) (-S t2) ++ vec (r :: nil) (t1 +S t2) ++ nil)).\n      apply hmrr_diamond_no_one.\n      do_HMR_logical.\n      apply hmrr_ex_seq with (vec (r :: nil) (-S t2) ++ vec (r :: nil) t2 ++ vec (r :: nil) (-S t1) ++ vec (r :: nil) t1 ++ nil); [ Permutation_Type_solve | ].\n      apply hmrr_ID_gen; try reflexivity.\n      apply hmrr_ID_gen; try reflexivity.\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      change (vec (mul_vec r0 (r :: nil)) (<S> (-S t)) ++ vec (r :: nil) (<S> (r0 *S t)) ++ nil)\n        with\n          (seq_diamond (vec (mul_vec r0 (r :: nil)) (-S t) ++ vec (r :: nil) (r0 *S t) ++ nil)).\n      apply hmrr_diamond_no_one.\n      do_HMR_logical.\n      pattern t at 1.\n      rewrite <- minus_minus.\n      apply hmrr_ID_gen; try reflexivity.\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * change (<S> MRS_one) with (-S (<S> MRS_coone)).\n        apply hmrr_ID_gen; try reflexivity.\n        apply hmrr_INIT.\n      * rewrite app_nil_r.\n        change (vec (r :: nil) MRS_one ++ vec (r :: nil) (<S> MRS_coone))\n          with\n            (vec nil MRS_coone ++ vec (r :: nil) MRS_one ++ seq_diamond (vec (r :: nil) (MRS_coone))).\n        apply hmrr_diamond.\n        { destruct r as [r Hr]; simpl; apply R_blt_lt in Hr; nra. }\n        change MRS_one with (-S MRS_coone).\n        rewrite app_nil_l; rewrite <- (app_nil_r (vec (r :: nil) MRS_coone)).\n        apply hmrr_ID_gen; try reflexivity.\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical ; try apply hmrr_INIT.\n      change (vec (r :: nil) (<S> pos t) ++ nil) with (seq_diamond (vec (r :: nil) (pos t) ++ nil)).\n      apply hmrr_diamond_no_one.\n      do_HMR_logical; simpl.\n      eapply hmrr_ex_hseq;  [ apply Permutation_Type_swap | ].\n      apply hmrr_W.\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical ; try apply hmrr_INIT.\n      change (vec (r :: nil) MRS_one ++ nil)\n        with (vec nil MRS_coone ++ vec (r :: nil) MRS_one ++ nil).\n      apply hmrr_one; try apply hmrr_INIT.\n      destruct r as [r Hr]; simpl.\n      apply R_blt_lt in Hr; nra.\n  - intros A B r Heq; destruct Heq.\n    + unfold HMR_M_can; HMR_to_vec.\n      apply hmrr_ID_gen...\n      apply hmrr_INIT.\n    + apply hmrr_can with t2 (r :: nil) (r :: nil)...\n      apply hmrr_ex_seq with (((r, -S t1) :: (r, t2) :: nil) ++ ((r, -S t2) :: (r, t3) :: nil)); [ Permutation_Type_solve | ].\n      apply hmrr_M; try reflexivity; [ apply (completeness_2 _ _ _ Heq1) | apply (completeness_2 _ _ _ Heq2)].\n    + revert r;induction c; try (rename r into r0); intros r.\n      * apply completeness_2.\n        apply Heq.\n      * eapply hmrr_ex_seq ; [ apply Permutation_Type_swap | ].\n        apply completeness_1.\n        simpl; rewrite minus_minus; apply Heq.\n      * unfold HMR_M_can; simpl; HMR_to_vec.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * simpl; unfold HMR_M_can; HMR_to_vec.\n        apply hmrr_ID...\n        apply hmrr_INIT.\n      * simpl.\n        apply hmrr_ex_seq with ((vec (r :: nil) (MRS_covar v)) ++ (vec (r :: nil) (MRS_var v)) ++ nil) ; [Permutation_Type_solve | ].\n        apply hmrr_ID...\n        apply hmrr_INIT.\n      * simpl.\n        unfold HMR_M_can; do_HMR_logical.\n        apply hmrr_INIT.\n      * unfold evalContext; fold evalContext.\n        unfold MRS_minus; fold MRS_minus.\n        unfold HMR_M_can; do_HMR_logical.\n        -- apply hmrr_W.\n           apply IHc1.\n        -- eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W; apply IHc2.\n      * unfold evalContext; fold evalContext.\n        unfold MRS_minus; fold MRS_minus.\n        unfold HMR_M_can; do_HMR_logical.\n        -- apply hmrr_W.\n           simpl; eapply hmrr_ex_seq ; [ apply Permutation_Type_swap | ].\n           apply IHc1.\n        -- eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n           eapply hmrr_ex_seq ; [ apply Permutation_Type_swap | ].\n           apply IHc2.\n      * simpl. unfold HMR_M_can; do_HMR_logical.\n        apply hmrr_ex_seq with (((r, -S evalContext c1 t1) :: (r, evalContext c1 t2) :: nil) ++ ((r, -S evalContext c2 t1) :: (r, evalContext c2 t2) :: nil)) ; [ Permutation_Type_solve | ].\n        apply hmrr_M; try reflexivity; [apply IHc1 | apply IHc2].\n      * simpl; unfold HMR_M_can; do_HMR_logical.\n        apply IHc.\n      * simpl.\n        change ((r, MRS_coone) :: (r, MRS_one) :: nil) with (vec (r :: nil) MRS_coone ++ vec (r :: nil) MRS_one ++ nil).\n        apply hmrr_one; [ | apply hmrr_INIT].\n        simpl; nra.\n      * eapply hmrr_ex_seq;  [ apply Permutation_Type_swap | ].\n        simpl.\n        change ((r, MRS_coone) :: (r, MRS_one) :: nil) with (vec (r :: nil) MRS_coone ++ vec (r :: nil) MRS_one ++ nil).\n        apply hmrr_one; [ | apply hmrr_INIT].\n        simpl; nra.\n      * simpl in *.\n        change ((r, <S> (-S evalContext c t1)) :: (r, <S> evalContext c t2) :: nil) with (seq_diamond ((r , (-S evalContext c t1)) :: (r , evalContext c t2) :: nil)).\n        apply hmrr_diamond_no_one.\n        apply IHc.\n    + apply (completeness_1 _ _ _ Heq).\n    + replace (((r, -S subs t1 n t) :: (r, subs t2 n t) :: nil) :: nil) with (subs_hseq (((r, -S t1) :: (r, t2) :: nil) :: nil) n t) by now rewrite <-eq_subs_minus.\n      apply subs_proof.\n      apply completeness_2; apply Heq.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with ((vec (r :: nil) (-S t1)) ++ (vec (r :: nil) (t1)) ++ (vec (r :: nil) (-S t2)) ++ (vec (r :: nil) (t2)) ++ (vec (r :: nil) (-S t3)) ++ (vec (r :: nil) (t3)) ++ nil); [ Permutation_Type_solve | ].\n      do 3 (apply hmrr_ID_gen; try reflexivity).\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with ((vec (r :: nil) (-S t1)) ++ (vec (r :: nil) (t1)) ++ (vec (r :: nil) (-S t2)) ++ (vec (r :: nil) (t2)) ++ nil); [ Permutation_Type_solve | ].\n      do 2 (apply hmrr_ID_gen; try reflexivity).\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ID_gen...\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      rewrite minus_minus.\n      rewrite<- ? app_assoc; apply hmrr_ID_gen...\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      unfold mul_vec.\n      rewrite minus_minus.\n      apply hmrr_ex_seq with ((vec (time_pos a r :: nil) (-S t)) ++ (vec (time_pos (minus_pos Hlt) r :: time_pos b r :: nil) t) ++ nil); [ Permutation_Type_solve | ].\n      apply hmrr_ID_gen ; [ | apply hmrr_INIT ].\n      destruct r; destruct a; destruct b; unfold minus_pos.\n      simpl; nra.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ID_gen; [ | apply hmrr_INIT].\n      destruct r; simpl; nra.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ID_gen ; [ | apply hmrr_INIT].\n      destruct r; destruct x; destruct y; simpl.\n      nra.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with ((vec (mul_vec x (r :: nil)) (-S t1)) ++ (vec (mul_vec x (r :: nil)) ( t1)) ++ (vec (mul_vec x (r :: nil)) (-S t2))++ (vec (mul_vec x (r :: nil)) (t2)) ++ nil) ; [ Permutation_Type_solve | ].\n      do 2 (apply hmrr_ID_gen; try reflexivity).\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      unfold mul_vec.\n      apply hmrr_ex_seq with ((vec (time_pos (plus_pos x y) r :: nil) (-S t)) ++ (vec (time_pos x r :: time_pos y r :: nil) t) ++ nil) ; [ Permutation_Type_solve | ].\n      apply hmrr_ID_gen; [ | apply hmrr_INIT].\n      destruct r; destruct x; destruct y; unfold plus_pos; simpl; nra.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ID_gen ; [ | apply hmrr_INIT].\n      simpl; nra.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        pattern t1 at 1; rewrite <- (minus_minus).\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | apply hmrr_W ; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | apply hmrr_W]].\n        pattern t2 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W; apply hmrr_W.\n        pattern t3 at 1; rewrite <- (minus_minus).\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        pattern t1 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        pattern t2 at 1; rewrite <- minus_minus.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W; eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      * apply hmrr_W; apply hmrr_W.\n        apply hmrr_ex_seq with ((vec (r :: nil) (-S t1)) ++ (vec (r :: nil) t1) ++ (vec (r :: nil) (-S t3)) ++ (vec (r :: nil) t3) ++ nil); [ Permutation_Type_solve | ].\n        apply hmrr_ID_gen...\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n      * apply hmrr_W.\n        eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ]; apply hmrr_W.\n        apply hmrr_ex_seq with ((vec (r :: nil) (-S t2)) ++ (vec (r :: nil) t2) ++ (vec (r :: nil) (-S t3)) ++ (vec (r :: nil) t3) ++ nil); [ Permutation_Type_solve | ].\n        apply hmrr_ID_gen...\n        apply hmrr_ID_gen...\n        apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      simpl.\n      eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n      apply hmrr_W.\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with (seq_diamond (vec (r :: nil) ((-S t1) -S t2) ++ vec (r :: nil) t1 ++ vec (r :: nil) t2 ++ nil)) ; [ Permutation_Type_solve | ].\n      apply hmrr_diamond_no_one.\n      apply hmrr_plus.\n      apply hmrr_ex_seq with (vec (r :: nil) (-S t2) ++ vec (r :: nil) t2 ++ vec (r :: nil) (-S t1) ++ vec (r :: nil) t1 ++ nil) ; [ Permutation_Type_solve | ].\n      apply hmrr_ID_gen; try reflexivity.\n      apply hmrr_ID_gen; try reflexivity.\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_ex_seq with (seq_diamond (vec (r :: nil) (r0 *S (-S t)) ++ vec (mul_vec r0 (r :: nil)) t ++ nil)); [Permutation_Type_solve | ].\n      apply hmrr_diamond_no_one; apply hmrr_mul.\n      apply hmrr_ID_gen; try reflexivity.\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      apply hmrr_W.\n      change (vec (r :: nil) (<S> MRS_coone) ++ vec (r :: nil) (<S> MRS_one) ++ nil)\n        with (seq_diamond (vec (r :: nil) MRS_coone ++ vec (r :: nil) MRS_one ++ nil)).\n      apply hmrr_diamond_no_one.\n      apply hmrr_one; simpl; try nra.\n      apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      simpl.\n      eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ].\n      apply hmrr_W; apply hmrr_INIT.\n    + unfold MRS_minus; fold MRS_minus.\n      unfold HMR_M_can; do_HMR_logical.\n      simpl.\n      eapply hmrr_ex_hseq; [ apply Permutation_Type_swap | ].\n      apply hmrr_W.\n      apply hmrr_INIT.\nQed.\n\n(** ** Second formulation *)\n(** We use the can rule and the M rule to go from a proof |- 1.G to a proof of G *)\nLemma HMR_sem_seq P : forall G T D,\n    HMR P (((One, sem_seq T) :: D) :: G) ->\n    HMR (hmr_frag_add_CAN (hmr_frag_add_M P)) ((T ++ D) :: G).\nProof.\n  intros G T; revert P G; induction T; intros P G D pi.\n  - simpl in *.\n    apply hmrr_Z_can_inv with (One :: nil).\n    apply HMR_le_frag with P; [ | apply pi].\n    apply add_M_le_frag.\n  - destruct a as (a , A).\n    simpl in *.\n    apply hmrr_ex_seq with (T ++ (a , A) :: D); [ Permutation_Type_solve | ].\n    apply (IHT (hmr_frag_add_CAN (hmr_frag_add_M (hmr_frag_add_CAN (hmr_frag_add_M P))))).\n    replace a with (time_pos a One) by (destruct a; unfold One; apply Rpos_eq; simpl; nra).\n    apply hmrr_ex_seq with ((vec (mul_vec a (One :: nil)) A) ++ (vec (One :: nil) (sem_seq T)) ++ D) ; [ Permutation_Type_solve | ].\n    apply hmrr_mul_can_inv.\n    apply hmrr_plus_can_inv.\n    apply pi.\nQed.\n\nLemma HMR_sem_hseq P : forall G H,\n    H <> nil ->\n    HMR P (((One, sem_hseq H) :: nil) :: G) ->\n    HMR (hmr_frag_add_CAN (hmr_frag_add_M P)) (H ++ G).\nProof with try assumption; try reflexivity.\n  intros G H Hnnil; revert P G.\n  induction H; [ now auto | ].\n  rename a into T.\n  intros P G pi.\n  destruct H as [ | T2 H ].\n  - simpl in *.\n    replace T with (T ++ nil) by now rewrite app_nil_r.\n    apply HMR_sem_seq...\n  - unfold sem_hseq in pi; fold (sem_hseq (T2 :: H)) in pi.\n    change ((One, sem_seq T \\/S sem_hseq (T2 :: H)) :: nil) with ((vec (One :: nil) (sem_seq T \\/S sem_hseq (T2 :: H))) ++ nil) in pi.\n    apply hmrr_max_can_inv in pi.\n    apply hmrr_ex_hseq with ((T2 :: H) ++ (T :: G)); [ Permutation_Type_solve | ].\n    apply HMR_le_frag with (hmr_frag_add_CAN (hmr_frag_add_M (hmr_frag_add_CAN (hmr_frag_add_M (hmr_frag_add_CAN (hmr_frag_add_M P)))))).\n    { destruct P; repeat split; Bool.destr_bool. }\n    refine (IHlist _ (hmr_frag_add_CAN (hmr_frag_add_M (hmr_frag_add_CAN (hmr_frag_add_M P)))) (T :: G) _) ; [ now auto | ].\n    apply hmrr_ex_hseq with (T :: ((One , sem_hseq (T2 :: H)) :: nil) :: G) ; [ Permutation_Type_solve | ].\n    replace T with (T ++ nil) by now rewrite app_nil_r.\n    apply HMR_sem_seq.\n    eapply hmrr_ex_hseq ; [ apply Permutation_Type_swap | ].\n    apply pi.\nQed.\n\n(** Proof of the completeness of the system of HMR - hmr_complete return a T free proof of G *)\nLemma hmr_complete : forall G,\n    G <> nil ->\n    MRS_zero <== sem_hseq G ->\n    HMR_M_can G.\nProof with try assumption.\n  intros G Hnnil Hleq.\n  assert (pi := completeness_1 _ _ One Hleq).\n  replace G with (G ++ nil) by now rewrite app_nil_r.\n  apply (@HMR_sem_hseq hmr_frag_M_can)...\n  change ((One , sem_hseq G) :: nil) with ((vec (One :: nil) (sem_hseq G)) ++ nil).\n  apply (@hmrr_min_can_inv_r hmr_frag_M_can) with MRS_zero.\n  apply (@hmrr_Z_can_inv hmr_frag_M_can) with (One :: nil)...\nQed.\n", "meta": {"author": "clucas26e4", "repo": "ramics_archimedean", "sha": "27074ea90fcb3c1b7e857b8f789f223a10f3c4dd", "save_path": "github-repos/coq/clucas26e4-ramics_archimedean", "path": "github-repos/coq/clucas26e4-ramics_archimedean/ramics_archimedean-27074ea90fcb3c1b7e857b8f789f223a10f3c4dd/hmr/completeness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.21099511697152246}}
{"text": "Require Import Relations.\nRequire Import EqNat.\nRequire Import ZArith.\nRequire Import List.\nRequire Import Utils.\nRequire Import Instr.\nRequire Import Concrete ConcreteMachine.\n\nSet Implicit Arguments.\nLocal Open Scope Z_scope.\n\n(** The concrete machine is deterministic. *)\n\nSection Determinism.\n\nLemma cache_hit_read_determ: forall c rl1 rpcl1 rl2 rpcl2,\n  cache_hit_read c rl1 rpcl1 ->\n  cache_hit_read c rl2 rpcl2 ->\n  rl1 = rl2 /\\ rpcl1 = rpcl2.\nProof.\n  intros. inv H. inv TAG_Res. inv TAG_ResPC.\n  inv H0. inv TAG_Res. inv TAG_ResPC.\n  allinv'. allinv'. intuition.\nQed.\n\nLemma cmach_determ:\n  forall s e s' e' s'',\n    cstep s e s' ->\n    cstep s e' s'' ->\n    s' = s'' /\\ e = e'.\nProof.\n  induction 1; intros;\n  match goal with\n      | [HH: cstep _ _ _ |- _ ] => inv HH; try congruence; auto\n  end;\n  try (match goal with\n    | [H1 : cache_hit_read ?c ?rl _,\n       H2 : cache_hit_read ?c ?rl0 _ |- _ ] =>\n  (exploit (@cache_hit_read_determ c rl); eauto; intros [Heq Heq'])\n  end);\n  (allinv'; split ; try reflexivity).\n\n  - (* Store user *)\n    allinv'. split ; reflexivity.\n\n  - (* Call user *)\n    subst.\n    exploit app_same_length_eq; eauto. intro Heq ; inv Heq.\n    exploit app_same_length_eq_rest ; eauto. intro Heq ; inv Heq.\n    split; reflexivity.\n\n  - (* Call kernel *)\n    subst.\n    exploit app_same_length_eq; eauto. intro Heq ; inv Heq.\n    exploit app_same_length_eq_rest ; eauto. intro Heq ; inv Heq.\n    split ; reflexivity.\n\n  - (* Ret Ret user *)\n    exploit @c_pop_to_return_spec; eauto.\n    intros [dstk [stk [a [b [p [Hs Hdstk]]]]]]. inv Hs.\n\n    exploit @c_pop_to_return_spec2; eauto.  move_to_top POP0.\n    exploit @c_pop_to_return_spec2; eauto. intros.\n    inv H. inv H0.\n\n    exploit @c_pop_to_return_spec3; eauto. clear POP.\n    exploit @c_pop_to_return_spec3; eauto.\n    intros.  inv H.\n    split ; reflexivity.\n\n  - (* Ret user *)\n    exploit @c_pop_to_return_spec; eauto.\n    intros [dstk [stk [a [b [p [Hs Hdstk]]]]]]. inv Hs.\n\n    exploit @c_pop_to_return_spec2; eauto.  move_to_top POP0.\n    exploit @c_pop_to_return_spec2; eauto. intros.\n    inv H. inv H0. congruence.\n\n  - (* Ret kernel / user - sym *)\n    exploit @c_pop_to_return_spec; eauto.\n    intros [dstk [stk [a [b [p [Hs Hdstk]]]]]]. inv Hs.\n\n    exploit @c_pop_to_return_spec2; eauto.  move_to_top POP0.\n    exploit @c_pop_to_return_spec2; eauto. intros.\n    inv H. inv H0. congruence.\n\n  - (* Ret kernel *)\n    exploit @c_pop_to_return_spec; eauto.\n    intros [dstk [stk [a [b [p [Hs Hdstk]]]]]]. inv Hs.\n\n    exploit @c_pop_to_return_spec2; eauto.  move_to_top POP0.\n    exploit @c_pop_to_return_spec2; eauto. intros.\n    inv H. inv H0.\n    split ; reflexivity.\n\n  - (* Ret Ret *)\n    exploit @c_pop_to_return_spec; eauto.\n    intros [dstk [stk [a [b [p [Hs Hdstk]]]]]]. inv Hs.\n\n    exploit @c_pop_to_return_spec2; eauto.  move_to_top H12.\n    exploit @c_pop_to_return_spec2; eauto. intros.\n    inv H1. inv H2.\n\n    exploit @c_pop_to_return_spec3; eauto. clear H0.\n    exploit @c_pop_to_return_spec3; eauto.\n    intros.  inv H1.\n    split ; reflexivity.\n\n  - (* VRet user *)\n    exploit @c_pop_to_return_spec; eauto.\n    intros [dstk [stk [a [b [p [Hs Hdstk]]]]]]. inv Hs.\n\n    exploit @c_pop_to_return_spec2; eauto. intros. move_to_top POP0.\n    exploit @c_pop_to_return_spec2; eauto. intros.\n\n    exploit @c_pop_to_return_spec3; eauto. intros.\n    generalize POP0 ; clear POP0 ; intros POP0.\n    exploit @c_pop_to_return_spec3; eauto. intros.\n    inv H1.  inv H. inv H0.\n    split ; reflexivity.\n\n  - (* Ret kernel / user *)\n    exploit @c_pop_to_return_spec; eauto.\n    intros [dstk [stk [a [b [p [Hs Hdstk]]]]]]. inv Hs.\n\n    exploit @c_pop_to_return_spec2; eauto.  move_to_top POP0.\n    exploit @c_pop_to_return_spec2; eauto. intros.\n    inv H. inv H0.\n    congruence.\n\n  - (* Ret kernel / user - sym *)\n    exploit @c_pop_to_return_spec; eauto.\n    intros [dstk [stk [a [b [p [Hs Hdstk]]]]]]. inv Hs.\n\n    exploit @c_pop_to_return_spec2; eauto.  move_to_top POP0.\n    exploit @c_pop_to_return_spec2; eauto. intros.\n    inv H. inv H0.\n    congruence.\n\n  - (* VRet priv *)\n    exploit @c_pop_to_return_spec; eauto.\n    intros [dstk [stk [a [b [p [Hs Hdstk]]]]]]. inv Hs.\n\n    exploit @c_pop_to_return_spec2; eauto.  move_to_top POP0.\n    exploit @c_pop_to_return_spec2; eauto. intros.\n    inv H. inv H0.\n\n    exploit @c_pop_to_return_spec3; eauto.\n\n  - (* VRet true *)\n    exploit @c_pop_to_return_spec; eauto.\n    intros [dstk [stk [a [b [p [Hs Hdstk]]]]]]. inv Hs.\n\n    exploit @c_pop_to_return_spec2; eauto. intros. move_to_top H14.\n    exploit @c_pop_to_return_spec2; eauto. intros.\n    inv H1. inv H2.\n\n    exploit @c_pop_to_return_spec3; eauto. clear H0.\n    exploit @c_pop_to_return_spec3; eauto. intros.\n    inv H1.\n    split ; reflexivity.\nQed.\n\nEnd Determinism.\n", "meta": {"author": "micro-policies", "repo": "verified-ifc", "sha": "1ce5075b3a5580679feddb718d274d89fc7dd77f", "save_path": "github-repos/coq/micro-policies-verified-ifc", "path": "github-repos/coq/micro-policies-verified-ifc/verified-ifc-1ce5075b3a5580679feddb718d274d89fc7dd77f/basic_machines/Determinism.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.611381973294151, "lm_q2_score": 0.3451052574867685, "lm_q1q2_score": 0.21099113331644662}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\nFrom Coq Require Import Ensembles Logic.Classical_Prop.\nFrom Coq Require Import Arith.Wf_nat Relations.Relation_Operators Wellfounded.Wellfounded.\nFrom Coq Require Import Logic.FunctionalExtensionality.\nFrom Coq.micromega Require Import Lia.\n\nFrom Equations Require Import Equations.\n\nFrom stdpp Require Import base option.\n\nFrom MatchingLogic Require Import\n     Syntax\n     Semantics\n     DerivedOperators_Syntax\n     ProofSystem\n     ProofMode.MLPM\n     Utils.extralibrary\n.\n\n\nImport MatchingLogic.Syntax.Notations MatchingLogic.DerivedOperators_Syntax.Notations.\n\n\nGlobal Set Transparent Obligations.\nDerive NoConfusion for Pattern.\nDerive Subterm for Pattern.\n\n\nOpen Scope ml_scope.\n\nEquations match_not {Σ : Signature} (p : Pattern)\n  : ({ p' : Pattern & p = patt_not p'}) + (forall p', p <> patt_not p')\n  :=\n  match_not (p' ---> ⊥) := inl _ ;\n  match_not _ := inr _ .\nSolve Obligations with Tactics.program_simplify; CoreTactics.equations_simpl.\nNext Obligation.\n  intros. eapply existT. reflexivity.\nDefined.\n\nLemma match_not_patt_not  {Σ : Signature} p: is_inl (match_not (patt_not p)).\nProof.\n  funelim (match_not _). simpl. reflexivity.\nQed.\n\nEquations match_or {Σ : Signature} (p : Pattern)\n  : ({ p1 : Pattern & {p2 : Pattern & p = patt_or p1 p2} } ) + (forall p1 p2, p <> patt_or p1 p2)\n  :=\n  match_or (p1 ---> p2) with match_not p1 => {\n    | inl (existT p1' e) => inl _\n    | inr _ => inr _\n    } ;      \n  match_or _ := inr _.\nSolve Obligations with Tactics.program_simplify; CoreTactics.equations_simpl.\nNext Obligation.\n  intros. inversion e. subst. eapply existT. eapply existT. reflexivity.\nDefined.\nNext Obligation.\n  intros.\n  unfold patt_or.\n  assert (p1 <> patt_not p0). auto.\n  congruence.\nDefined.\n\nLemma match_or_patt_or  {Σ : Signature} p1 p2: is_inl (match_or (patt_or p1 p2)).\nProof. reflexivity. Qed.\n\nEquations?  match_and {Σ : Signature} (p : Pattern)\n  : ({ p1 : Pattern & {p2 : Pattern & p = patt_and p1 p2} } ) + (forall p1 p2, p <> patt_and p1 p2)\n  :=\n  match_and p with match_not p => {\n    | inr _ := inr _ ;\n    | inl (existT p' e') with match_or p' => {\n      | inr _ := inr _ ;\n      | inl (existT p1 (existT p2 e12)) with match_not p1 => {\n        | inr _ := inr _ ;\n        | inl (existT np1 enp1) with match_not p2 => {\n          | inr _ := inr _ ;\n          | inl (existT np2 enp2) := inl _\n          }\n        }\n      }\n    }.\nProof.\n  - subst. eapply existT. eapply existT. reflexivity.\n  - subst. intros. unfold not. intros Hcontra. inversion Hcontra.\n    subst. specialize (n p0). contradiction.\n  - subst. intros. unfold not. intros Hcontra. inversion Hcontra.\n    subst. specialize (n p0). contradiction.\n  - subst. intros. unfold not. intros Hcontra. inversion Hcontra.\n    subst. specialize (n (patt_not p1) (patt_not p2)). contradiction.\n  - intros. unfold not. intros Hcontra. subst.\n    specialize (n ((patt_or (patt_not p1) (patt_not p2)))). contradiction.\nDefined.\n\nLemma match_and_patt_and  {Σ : Signature} p1 p2: is_inl (match_and (patt_and p1 p2)).\nProof. reflexivity. Qed.\n\nLemma match_and_patt_or  {Σ : Signature} p1 p2: is_inl (match_and (patt_or p1 p2)) = false.\nProof.\n  funelim (match_and _); rewrite -Heqcall; simpl; try reflexivity.\n  subst. try inversion e'.\nQed.\n\nEquations match_imp {Σ : Signature} (p : Pattern)\n  : ({ p1 : Pattern & {p2 : Pattern & p = patt_imp p1 p2} } ) + (forall p1 p2, p <> patt_imp p1 p2)\n  :=\n  match_imp (p1 ---> p2) := inl _ ;\n  match_imp _ := inr _.\nSolve Obligations with Tactics.program_simplify; CoreTactics.equations_simpl.\nNext Obligation.\n  intros. eapply existT. eapply existT. reflexivity.\nDefined.\n\nLemma match_imp_patt_imp {Σ : Signature} p1 p2: is_inl (match_imp (patt_imp p1 p2)).\nProof. reflexivity. Qed.\n\nEquations match_bott {Σ : Signature} (p : Pattern)\n  : (p = patt_bott) + (p <> patt_bott)\n  :=\n  match_bott patt_bott := inl _ ;\n  match_bott _ := inr _.\nSolve Obligations with Tactics.program_simplify; CoreTactics.equations_simpl.\nNext Obligation. reflexivity. Defined.\n\n\nEquations match_a_impl_b_impl_c {Σ : Signature} (p : Pattern) :\n  ({a : Pattern & {b : Pattern & {c : Pattern & p = patt_imp a (patt_imp b c)} } })\n  + (forall (a b c : Pattern), p <> patt_imp a (patt_imp b c)) :=\n  match_a_impl_b_impl_c (p1 ---> (p2 ---> p3)) := inl _ ;\n  match_a_impl_b_impl_c _ := inr _ .\nSolve Obligations with Tactics.program_simplify; CoreTactics.equations_simpl.\nNext Obligation.\n  intros Σ p1 p2 p3.\n  do 3 eapply existT.\n  reflexivity.\nDefined.\n\n", "meta": {"author": "harp-project", "repo": "AML-Formalization", "sha": "ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d", "save_path": "github-repos/coq/harp-project-AML-Formalization", "path": "github-repos/coq/harp-project-AML-Formalization/AML-Formalization-ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d/prover/theories/Matchers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2109839562057856}}
{"text": "Require Import Io.All.\nRequire Choose.\nRequire Import Semantics.\n\nFixpoint to_choose {E A} (x : C.t E A) : Choose.t E A :=\n  match x with\n  | C.Ret _ v => Choose.Ret v\n  | C.Call c => Choose.Call c Choose.Ret\n  | C.Let _ _ x f => Choose.bind (to_choose x) (fun x => to_choose (f x))\n  | C.Choose _ x1 x2 => Choose.Choose (to_choose x1) (to_choose x2)\n  | C.Join _ _ x y => Choose.join (to_choose x) (to_choose y)\n  end.\n\nModule Path.\n  Module Last.\n    Fixpoint to_choose (p : C.Last.Path.t) : Choose.Path.t :=\n      match p with\n      | C.Last.Path.Ret => Choose.Path.Done\n      | C.Last.Path.Let p_x p_f =>\n        Choose.Path.bind (to_choose p_x) (to_choose p_f)\n      | C.Last.Path.ChooseLeft p_x1 =>\n        Choose.Path.ChooseLeft (to_choose p_x1)\n      | C.Last.Path.ChooseRight p_x2 =>\n        Choose.Path.ChooseRight (to_choose p_x2)\n      | C.Last.Path.Join p_x p_y =>\n        Choose.Path.ChooseLeft\n          (Choose.Path.bind (to_choose p_x) (to_choose p_y))\n      end.\n  End Last.\n\n  Fixpoint to_choose (p : C.Path.t) : Choose.Path.t :=\n    match p with\n    | C.Path.Call => Choose.Path.Done\n    | C.Path.Let p_x => to_choose p_x\n    | C.Path.LetDone p_x p_f =>\n      Choose.Path.bind (Last.to_choose p_x) (to_choose p_f)\n    | C.Path.ChooseLeft p_x1 => Choose.Path.ChooseLeft (to_choose p_x1)\n    | C.Path.ChooseRight p_x2 => Choose.Path.ChooseRight (to_choose p_x2)\n    | C.Path.JoinLeft p_x => Choose.Path.ChooseLeft (to_choose p_x)\n    | C.Path.JoinLeftDone p_x p_y =>\n      Choose.Path.ChooseLeft (Choose.Path.bind\n        (Last.to_choose p_x) (to_choose p_y))\n    | C.Path.JoinRight p_y => Choose.Path.ChooseRight (to_choose p_y)\n    | C.Path.JoinRightDone p_x p_y =>\n      Choose.Path.ChooseRight (Choose.Path.bind\n        (to_choose p_x) (Last.to_choose p_y))\n    end.\n\n  Fixpoint to_c {E A} (x : C.t E A) (p : Choose.Path.t)\n    : (C.Last.Path.t * A * Choose.Path.t) + C.Path.t :=\n    match x with\n    | C.Ret _ v => inl (C.Last.Path.Ret, v, p)\n    | C.Call _ => inr C.Path.Call\n    | C.Let _ _ x f =>\n      match to_c x p with\n      | inl (p_x, v_x, p) =>\n        match to_c (f v_x) p with\n        | inl (p_f, v_y, p) => inl (C.Last.Path.Let p_x p_f, v_y, p)\n        | inr p_y => inr (C.Path.LetDone p_x p_y)\n        end\n      | inr p_x => inr (C.Path.Let p_x)\n      end\n    | C.Choose _ x1 x2 =>\n      match p with\n      | Choose.Path.Done => inr C.Path.Call\n      | Choose.Path.ChooseLeft p =>\n        match to_c x1 p with\n        | inl (p_x1, v_x1, p) => inl (C.Last.Path.ChooseLeft p_x1, v_x1, p)\n        | inr p_x1 => inr (C.Path.ChooseLeft p_x1)\n        end\n      | Choose.Path.ChooseRight p =>\n        match to_c x2 p with\n        | inl (p_x2, v_x2, p) => inl (C.Last.Path.ChooseRight p_x2, v_x2, p)\n        | inr p_x2 => inr (C.Path.ChooseRight p_x2)\n        end\n      end\n    | C.Join _ _ x y =>\n      match p with\n      | Choose.Path.Done => inr C.Path.Call\n      | Choose.Path.ChooseLeft p =>\n        match to_c x p with\n        | inl (p_x, v_x, p) =>\n          match to_c y p with\n          | inl (p_y, v_y, p) => inl (C.Last.Path.Join p_x p_y, (v_x, v_y), p)\n          | inr p_y => inr (C.Path.JoinLeftDone p_x p_y)\n          end\n        | inr p_x => inr (C.Path.JoinLeft p_x)\n        end\n      | Choose.Path.ChooseRight p =>\n        match to_c y p with\n        | inl (p_y, v_y, p) =>\n          match to_c x p with\n          | inl (p_x, v_x, p) => inl (C.Last.Path.Join p_x p_y, (v_x, v_y), p)\n          | inr p_x => inr (C.Path.JoinRightDone p_x p_y)\n          end\n        | inr p_y => inr (C.Path.JoinRight p_y)\n        end\n      end\n    end.\nEnd Path.\n", "meta": {"author": "coq-io", "repo": "checker", "sha": "fe61e3605a65f7be297fd02eb59a12a83f0aa92f", "save_path": "github-repos/coq/coq-io-checker", "path": "github-repos/coq/coq-io-checker/checker-fe61e3605a65f7be297fd02eb59a12a83f0aa92f/src/Compile.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2109839562057856}}
{"text": "(* Standard library imports *)\nRequire Import Coq.Strings.String.\nRequire Import Coq.Strings.Ascii.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.Arith.PeanoNat.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Program.Equality.\nImport ListNotations.\n(* Project related imports *)\nRequire Import GenericLemmas.\nRequire Import OptionMonad.\nRequire Import Names.\nRequire Import AST.\nRequire Import UtilsProgram.\nRequire Import UtilsSkeleton.\nRequire Import Skeleton.\nRequire Import Typechecker.\nRequire Import Unique.\n\n(**************************************************************************************************)\n(** * Constructorization Part I:                                                                 *)\n(**                                                                                               *)\n(** In the first part of the algorithm we compute a new program skeleton.                         *)\n(**************************************************************************************************)\n\nDefinition DestrFunSignature : Type := list TypeName * TypeName.\n\nDefinition Constructor : Type := ScopedName * list TypeName.\n\nDefinition computeNewDatatype (p : program) (n : TypeName) : list Constructor :=\n  (map (fun x => (global (fst x), snd x))\n       (filter (fun x => eq_TypeName (fst (fst x)) n) (skeleton_gfun_sigs_g (program_skeleton p)))) ++\n  (map (fun x => (local (fst x), snd x))\n       (filter (fun x => eq_TypeName (fst (fst x)) n) (skeleton_gfun_sigs_l (program_skeleton p)))).\n\n(**************************************************************************************************)\n(** ** Proof of dts_ctors_in_dts (dt well-formedness #1)                                          *)\n(**************************************************************************************************)\n\nLemma new_dts_ctors_in_dts_g : forall (p : program) (n : TypeName),\n    dts_ctors_in_dts (n :: skeleton_dts (program_skeleton p))\n      (map (fun x => (global (fst x), snd x))\n       (filter (fun x => eq_TypeName (fst (fst x)) n) (skeleton_gfun_sigs_g (program_skeleton p)))).\nProof.\nintros p n. unfold dts_ctors_in_dts.\nassert (H : Forall (fun ctor => fst (unscope (fst ctor)) = n)\n  (map (fun x => (global (fst x), snd x))\n       (filter (fun x => eq_TypeName (fst (fst x)) n) (skeleton_gfun_sigs_g (program_skeleton p))))).\n- induction (skeleton_gfun_sigs_g (program_skeleton p)).\n  + simpl. apply Forall_nil.\n  + simpl. destruct a as [[a0 a1] a2]; simpl in *. destruct (eq_TypeName a0 n) eqn:E.\n    * simpl. apply Forall_cons. simpl. name_eq_tac. apply IHg.\n    * apply IHg.\n- induction (map (fun x => (global (fst x), snd x))\n       (filter (fun x => eq_TypeName (fst (fst x)) n) (skeleton_gfun_sigs_g (program_skeleton p))));\n    inversion H; subst.\n  + apply Forall_nil.\n  + apply Forall_cons.\n    * simpl. left. reflexivity.\n    * apply IHl. assumption.\nQed.\n\nLemma new_dts_ctors_in_dts_l : forall (p : program) (n : TypeName),\n    dts_ctors_in_dts (n :: skeleton_dts (program_skeleton p))\n      (map (fun x => (local (fst x), snd x))\n       (filter (fun x => eq_TypeName (fst (fst x)) n) (skeleton_gfun_sigs_l (program_skeleton p)))).\nintros p n. unfold dts_ctors_in_dts.\nassert (H : Forall (fun ctor => fst (unscope (fst ctor)) = n)\n  (map (fun x => (local (fst x), snd x))\n       (filter (fun x => eq_TypeName (fst (fst x)) n) (skeleton_gfun_sigs_l (program_skeleton p))))).\n- induction (skeleton_gfun_sigs_l (program_skeleton p)).\n  + simpl. apply Forall_nil.\n  + simpl. destruct a as [[a0 a1] a2]; simpl in *. destruct (eq_TypeName a0 n) eqn:E.\n    * simpl. apply Forall_cons. simpl. name_eq_tac. apply IHg.\n    * apply IHg.\n- induction (map (fun x => (local (fst x), snd x))\n       (filter (fun x => eq_TypeName (fst (fst x)) n) (skeleton_gfun_sigs_l (program_skeleton p))));\n    inversion H; subst.\n  + apply Forall_nil.\n  + apply Forall_cons.\n    * simpl. left. reflexivity.\n    * apply IHl. assumption.\nQed.\n\nLemma new_dts_ctors_in_dts : forall (p : program) (n : TypeName),\n    dts_ctors_in_dts (n :: skeleton_dts (program_skeleton p)) ((computeNewDatatype p n) ++ (skeleton_ctors (program_skeleton p))).\nProof.\nintros p n. unfold dts_ctors_in_dts. unfold computeNewDatatype.\nrepeat apply Forall_app.\n- apply new_dts_ctors_in_dts_g.\n- apply new_dts_ctors_in_dts_l.\n- destruct p. simpl. clear - program_skeleton. destruct program_skeleton. simpl.\n  clear - skeleton_dts_ctors_in_dts. unfold dts_ctors_in_dts in skeleton_dts_ctors_in_dts.\n  induction skeleton_ctors.\n  + apply Forall_nil.\n  + apply Forall_cons.\n    * right. inversion skeleton_dts_ctors_in_dts; subst. assumption.\n    * apply IHskeleton_ctors. inversion skeleton_dts_ctors_in_dts; subst. assumption.\nQed.\n\n(**************************************************************************************************)\n(** ** Proof of dts_ctor_names_unique (dt well-formedness #1)                                     *)\n(**************************************************************************************************)\n\nLemma disjoint_app_unique : forall {A} (l1 l2 : list A),\n  (forall a, ~(In a l1 /\\ In a l2)) ->\n  unique l1 ->\n  unique l2 ->\n  unique (l1 ++ l2).\nProof with try apply in_eq; try apply in_cons; auto.\nintros. induction l1... rewrite <- app_comm_cons. apply Unique_cons.\n- unfold not. intros. unfold not in H. inversion H0; subst. apply in_app_or in H2. destruct H2...\n  apply H with (a0:=a). split...\n- inversion H0; subst. apply IHl1... intros. unfold not. intros. unfold not in H. destruct H2. apply H with (a0:=a0). split...\nQed.\n\nLemma new_dts_ctor_names_unique : forall (p : program)(n : TypeName),\n    dts_ctor_names_unique ((computeNewDatatype p n) ++ skeleton_ctors (program_skeleton p)).\nProof with auto.\nintros p n. unfold dts_ctor_names_unique.\nunfold computeNewDatatype. repeat (rewrite map_app). repeat (rewrite map_map). simpl.\npose proof (skeleton_dts_cdts_disjoint (program_skeleton p)) as Disj.\npose proof (skeleton_dts_ctors_in_dts (program_skeleton p)) as ctorInDts.\npose proof (skeleton_cdts_dtors_in_cdts (program_skeleton p)) as dtorInCdts.\npose proof (skeleton_gfun_sigs_in_cdts_g (program_skeleton p)) as InCdt_g.\npose proof (skeleton_gfun_sigs_in_cdts_l (program_skeleton p)) as InCdt_l.\napply disjoint_app_unique.\n- intros. unfold not. intros. unfold dts_cdts_disjoint in Disj.\n  unfold not in Disj. destruct H. apply in_app_or in H. destruct H.\n  + unfold gfun_sigs_in_cdts in InCdt_g.\n    rewrite Forall_forall in InCdt_g.\n    rewrite in_map_iff in H. destruct H as [x [H xIn]].\n    rewrite filter_In in xIn. destruct xIn.\n    eapply Disj. rewrite and_comm. split.\n    * apply InCdt_g. eauto.\n    * unfold dts_ctors_in_dts in ctorInDts. rewrite Forall_forall in ctorInDts.\n      apply (f_equal unscope) in H. simpl in H. unfold QName in *. rewrite H.\n      rewrite in_map_iff in H0. destruct H0. destruct H0. destruct x0. simpl in *; subst.\n      change a with (fst (a,l)). apply ctorInDts...\n  + unfold gfun_sigs_in_cdts in InCdt_l.\n    rewrite Forall_forall in InCdt_l.\n    rewrite in_map_iff in H. destruct H as [x [H xIn]].\n    rewrite filter_In in xIn. destruct xIn.\n    eapply Disj. rewrite and_comm. split.\n    * apply InCdt_l. eauto.\n    * unfold dts_ctors_in_dts in ctorInDts. rewrite Forall_forall in ctorInDts.\n      apply (f_equal unscope) in H. simpl in H. unfold QName in *. rewrite H.\n      rewrite in_map_iff in H0. destruct H0. destruct H0. destruct x0. simpl in *; subst.\n      change a with (fst (a,l)). apply ctorInDts...\n- apply disjoint_app_unique.\n  + intros. unfold not. intros. destruct H.\n    rewrite in_map_iff in H. rewrite in_map_iff in H0.\n    destruct H as [x [H xIn]]. destruct H0 as [x0 [H0 x0In]].\n    rewrite <- H0 in H. discriminate.\n  + pose proof (skeleton_gfun_sigs_names_unique_g (program_skeleton p)) as H.\n    unfold gfun_sigs_names_unique in H. rewrite <- map_map.\n    assert (forall l, unique l -> unique (map global l)) as H0.\n    { intros. induction l; try apply Unique_nil. simpl. inversion H0; subst.\n      apply Unique_cons... unfold not. intros. unfold not in H3. apply H3.\n      rewrite in_map_iff in H1. do 2 (destruct H1). inversion H1; subst... }\n    apply H0.\n    rewrite filter_map with\n      (g:=fun x : TypeName * Name => eq_TypeName (fst x) n) (f:=fst).\n    apply filter_unique...\n  + pose proof (skeleton_gfun_sigs_names_unique_l (program_skeleton p)) as H.\n    unfold gfun_sigs_names_unique in H. rewrite <- map_map.\n    assert (forall l, unique l -> unique (map local l)) as H0.\n    { intros. induction l; try apply Unique_nil. simpl. inversion H0; subst.\n      apply Unique_cons... unfold not. intros. unfold not in H3. apply H3.\n      rewrite in_map_iff in H1. do 2 (destruct H1). inversion H1; subst... }\n    apply H0.\n    rewrite filter_map with\n      (g:=fun x : TypeName * Name => eq_TypeName (fst x) n) (f:=fst).\n    apply filter_unique...\n- apply (skeleton_dts_ctor_names_unique (program_skeleton p)).\nQed.\n\n\n(**************************************************************************************************)\n(** ** Proof of cdts_dtors_in_cdts (cdt well-formedness #1)                                       *)\n(**************************************************************************************************)\n\nDefinition new_cdts (p : program) (n : TypeName) : list TypeName :=\n      (filter (fun n' : TypeName => negb (eq_TypeName n n')) (skeleton_cdts (program_skeleton p))).\n\nDefinition new_dtors (p : program) (n : TypeName) :=\n  filter (fun x => match x with (n',_,_) => negb (eq_TypeName n (fst (unscope n'))) end) (skeleton_dtors (program_skeleton p)).\n\nLemma new_cdts_dtors_in_cdts : forall (p : program) (n : TypeName),\n  cdts_dtors_in_cdts (new_cdts p n) (new_dtors p n).\nProof.\nintros p n. unfold new_dtors. unfold new_cdts. destruct p. simpl. clear - program_skeleton.\ndestruct program_skeleton. simpl. clear - skeleton_cdts_dtors_in_cdts.\nunfold cdts_dtors_in_cdts in *.\ninduction skeleton_dtors.\n- simpl. apply Forall_nil.\n- simpl. destruct a as [[a0 a1] a2]. simpl in *.\n  destruct (eq_TypeName n (fst (unscope a0))) eqn:E.\n  + simpl. apply IHskeleton_dtors. inversion skeleton_cdts_dtors_in_cdts; subst. apply H2.\n  + simpl. apply Forall_cons.\n    * simpl. inversion skeleton_cdts_dtors_in_cdts; subst. simpl in *. remember (fst (unscope a0)) as X.\n      clear - H1 E. induction skeleton_cdts; try inversion H1.\n      simpl. simpl in H1. destruct H1.\n      -- subst. rewrite E. simpl. left. reflexivity.\n      -- destruct (eq_TypeName n a) eqn:E'.\n         ++ name_eq_tac. simpl. apply IHskeleton_cdts. assumption.\n         ++ simpl. right. apply IHskeleton_cdts. assumption.\n      -- simpl. destruct (eq_TypeName n a) eqn:E2.\n         ++ simpl. apply IHskeleton_cdts. assumption.\n         ++ simpl. right. apply IHskeleton_cdts. assumption.\n    * apply IHskeleton_dtors. inversion skeleton_cdts_dtors_in_cdts; subst. assumption.\nQed.\n\n(**************************************************************************************************)\n(** ** Proof of cdts_dtor_names_unique (cdt well-formedness #2)                                   *)\n(**************************************************************************************************)\n\nFact filter_ext : forall {A} (l : list A) f g,\n  (forall a, f a = g a) ->\n  filter f l = filter g l.\nProof with auto. intros. induction l... simpl. rewrite H. rewrite IHl... Qed.\n\nLemma new_cdts_dtor_names_unique : forall (p : program)(n : TypeName),\n  cdts_dtor_names_unique (new_dtors p n).\nProof.\nintros p n. unfold new_dtors. destruct p. simpl. clear - program_skeleton.\ndestruct program_skeleton. simpl. clear - skeleton_cdts_dtor_names_unique.\nunfold cdts_dtor_names_unique in *.\nrewrite filter_ext with (g:=fun x => negb (eq_TypeName n (fst (unscope (fst (fst x)))))).\n2: { intros. destruct a. destruct p. auto. }\nrewrite filter_map with\n  (g:=fun x : ScopedName => negb (eq_TypeName n (fst (unscope x))))\n  (f:=fun x => fst (fst x)). apply filter_unique. auto.\nQed.\n\n(**************************************************************************************************)\n(** ** Proof of dts_cdts_disjoint                                                                     *)\n(**************************************************************************************************)\n\nLemma new_d_cd_disj : forall (p : program) (n : TypeName),\n    dts_cdts_disjoint (n :: skeleton_dts (program_skeleton p)) (new_cdts p n).\nProof.\nintros p n. unfold dts_cdts_disjoint. intros t H. unfold new_cdts in H.\ndestruct p; simpl in *. clear - H program_skeleton.\ndestruct program_skeleton; simpl in *. clear - H skeleton_dts_cdts_disjoint.\nunfold dts_cdts_disjoint in skeleton_dts_cdts_disjoint.\ndestruct H. destruct H.\n- subst. clear - H0. induction skeleton_cdts.\n  + simpl in H0. assumption.\n  + simpl in H0. destruct (eq_TypeName t a) eqn:E.\n    * simpl in *. apply IHskeleton_cdts. assumption.\n    * simpl in *. destruct H0.\n      -- subst. name_refl_tac. inversion E.\n      -- apply IHskeleton_cdts. assumption.\n- specialize (skeleton_dts_cdts_disjoint t). apply skeleton_dts_cdts_disjoint. split.\n   + assumption.\n   + clear - H0. induction skeleton_cdts.\n    * inversion H0.\n    * simpl in *. destruct (eq_TypeName n a) eqn:E.\n      -- simpl in *. name_eq_tac. right. apply IHskeleton_cdts. assumption.\n      -- simpl in *. destruct H0.\n         ++ left. assumption.\n         ++ right. apply IHskeleton_cdts. assumption.\nQed.\n\n(**************************************************************************************************)\n(** ** Proof of cfun_sigs_in_dts (cfuns well-formedness #1)                                       *)\n(**************************************************************************************************)\n\nDefinition cfunsigs_mapfun (x : ScopedName * list TypeName * TypeName) :=\n  match x with (x1,x2,x3) => (unscope x1, x2, x3) end.\n\nDefinition cfunsigs_filterfun_g (n : TypeName) (x : ScopedName * list TypeName * TypeName) :=\n  match x with\n  |(global n',_,_) => eq_TypeName n (fst n')\n  | _ => false\n  end.\n\nDefinition new_cfunsigs_g p n :=\n  List.map cfunsigs_mapfun (filter (cfunsigs_filterfun_g n) (skeleton_dtors (program_skeleton p)))\n           ++ (skeleton_cfun_sigs_g (program_skeleton p)).\n\nLemma new_cfun_sigs_in_dts_g : forall (p : program) (n : TypeName),\n    cfun_sigs_in_dts\n      (n :: skeleton_dts (program_skeleton p))\n      (new_cfunsigs_g p n).\nProof.\n  intros p n. pose proof (skeleton_cfun_sigs_in_dts_g (program_skeleton p)).\n  unfold cfun_sigs_in_dts in *. unfold new_cfunsigs_g. apply Forall_app.\n  - (* Show the newly generated cfunsigs are in (n :: dts) *)\n    clear H. induction (skeleton_dtors (program_skeleton p)).\n    + simpl. apply Forall_nil.\n    + simpl. destruct a as [[a0 a1] a2]. simpl in *. destruct a0.\n      * apply IHd.\n      * destruct (eq_TypeName n (fst q)) eqn:E.\n        ** simpl. apply Forall_cons.\n           *** left. simpl. name_eq_tac.\n           *** apply IHd.\n        ** apply IHd.\n  - (* Show the old cfunsigs are in dts *)\n    induction (skeleton_cfun_sigs_g (program_skeleton p)).\n    + apply Forall_nil.\n    + apply Forall_cons.\n      * apply in_cons. inversion H; assumption.\n      * apply IHc. inversion H; subst. assumption.\nQed.\n\nDefinition cfunsigs_filterfun_l (n : TypeName) (x : ScopedName * list TypeName * TypeName) :=\n  match x with\n  |(local n',_,_) => eq_TypeName n (fst n')\n  | _ => false\n  end.\n\nDefinition new_cfunsigs_l p n :=\n  List.map cfunsigs_mapfun (filter (cfunsigs_filterfun_l n) (skeleton_dtors (program_skeleton p)))\n           ++ (skeleton_cfun_sigs_l (program_skeleton p)).\n\nLemma new_cfun_sigs_in_dts_l : forall (p : program) (n : TypeName),\n    cfun_sigs_in_dts\n      (n :: skeleton_dts (program_skeleton p))\n      (new_cfunsigs_l p n).\nProof.\n  intros p n. pose proof (skeleton_cfun_sigs_in_dts_l (program_skeleton p)).\n  unfold cfun_sigs_in_dts in *. unfold new_cfunsigs_l. apply Forall_app.\n  - (* Show the newly generated cfunsigs are in (n :: dts) *)\n    clear H. induction (skeleton_dtors (program_skeleton p)).\n    + simpl. apply Forall_nil.\n    + simpl. destruct a as [[a0 a1] a2]. simpl in *. destruct a0.\n      * destruct (eq_TypeName n (fst q)) eqn:E.\n        ** simpl. apply Forall_cons.\n           *** left. simpl. name_eq_tac.\n           *** apply IHd.\n        ** apply IHd.\n      * apply IHd.\n  - (* Show the old cfunsigs are in dts *)\n    induction (skeleton_cfun_sigs_l (program_skeleton p)).\n    + apply Forall_nil.\n    + apply Forall_cons.\n      * apply in_cons. inversion H; assumption.\n      * apply IHc. inversion H; subst. assumption.\nQed.\n\n\n(**************************************************************************************************)\n(** ** Proof of cfun_sigs_names_unique (cfuns well-formedness #2)                                 *)\n(**************************************************************************************************)\n\nLemma new_cfun_sigs_names_unique_g : forall (p : program) (n : TypeName),\n    cfun_sigs_names_unique (new_cfunsigs_g p n).\nProof.\nintros p n. unfold cfun_sigs_names_unique. unfold new_cfunsigs_g.\npose proof (skeleton_cfun_sigs_names_unique_g (program_skeleton p)).\nunfold cfun_sigs_names_unique in H. unfold cfunsigs_mapfun.\npose proof (skeleton_dts_cdts_disjoint (program_skeleton p)) as Disj.\npose proof (skeleton_cdts_dtors_in_cdts (program_skeleton p)) as dtorInCdts.\npose proof (skeleton_cfun_sigs_in_dts_g (program_skeleton p)) as InDt_g.\nrewrite map_app.\napply disjoint_app_unique.\n- intros. unfold not. intros. destruct H0.\n  unfold cdts_dtors_in_cdts in dtorInCdts. rewrite Forall_forall in dtorInCdts.\n  rewrite map_map in H0. rewrite in_map_iff in H0. do 2 (destruct H0).\n  rewrite filter_In in H2. destruct H2. pose proof (dtorInCdts _ H2).\n\n  unfold cfun_sigs_in_dts in InDt_g. rewrite Forall_forall in InDt_g.\n  rewrite in_map_iff in H1. do 2 (destruct H1). pose proof (InDt_g _ H5).\n  destruct x. destruct p0. subst. simpl in *. unfold QName in *. rewrite H1 in H6.\n\n  unfold dts_cdts_disjoint in Disj. unfold not in Disj. eapply Disj. split; eauto.\n- pose proof (skeleton_cdts_dtor_names_unique (program_skeleton p)).\n  unfold cdts_dtor_names_unique in H0.\n  unfold cfunsigs_filterfun_g. clear - H0.\n  generalize dependent (skeleton_dtors (program_skeleton p)). induction d; intros.\n  + simpl. apply Unique_nil.\n  + simpl. destruct a. destruct p0. destruct s.\n    * apply IHd. inversion H0; subst. auto.\n    * case (eq_TypeName n (fst q)).\n      -- simpl. apply Unique_cons.\n         ++ inversion H0; subst. unfold not in *. intros. apply H2. clear - H.\n            rewrite map_map in H. rewrite in_map_iff in H. do 2 (destruct H).\n            rewrite filter_In in H0. destruct H0. destruct x. destruct p. rewrite <- H.\n            simpl in *. rewrite in_map_iff. exists (s,l,t). simpl. split; auto.\n            destruct s; try discriminate. auto.\n         ++ inversion H0; subst. auto.\n      -- inversion H0; subst. auto.\n- apply (skeleton_cfun_sigs_names_unique_g (program_skeleton p)).\nQed.\n\nLemma new_cfun_sigs_names_unique_l : forall (p : program) (n : TypeName),\n    cfun_sigs_names_unique (new_cfunsigs_l p n).\nProof.\nintros p n. unfold cfun_sigs_names_unique. unfold new_cfunsigs_l.\npose proof (skeleton_cfun_sigs_names_unique_l (program_skeleton p)).\nunfold cfun_sigs_names_unique in H. unfold cfunsigs_mapfun.\npose proof (skeleton_dts_cdts_disjoint (program_skeleton p)) as Disj.\npose proof (skeleton_cdts_dtors_in_cdts (program_skeleton p)) as dtorInCdts.\npose proof (skeleton_cfun_sigs_in_dts_l (program_skeleton p)) as InDt_l.\nrewrite map_app.\napply disjoint_app_unique.\n- intros. unfold not. intros. destruct H0.\n  unfold cdts_dtors_in_cdts in dtorInCdts. rewrite Forall_forall in dtorInCdts.\n  rewrite map_map in H0. rewrite in_map_iff in H0. do 2 (destruct H0).\n  rewrite filter_In in H2. destruct H2. pose proof (dtorInCdts _ H2).\n\n  unfold cfun_sigs_in_dts in InDt_l. rewrite Forall_forall in InDt_l.\n  rewrite in_map_iff in H1. do 2 (destruct H1). pose proof (InDt_l _ H5).\n  destruct x. destruct p0. subst. simpl in *. unfold QName in *. rewrite H1 in H6.\n\n  unfold dts_cdts_disjoint in Disj. unfold not in Disj. eapply Disj. split; eauto.\n- pose proof (skeleton_cdts_dtor_names_unique (program_skeleton p)).\n  unfold cdts_dtor_names_unique in H0.\n  unfold cfunsigs_filterfun_l. clear - H0.\n  generalize dependent (skeleton_dtors (program_skeleton p)). induction d; intros.\n  + simpl. apply Unique_nil.\n  + simpl. destruct a. destruct p0. destruct s.\n    * case (eq_TypeName n (fst q)).\n      -- simpl. apply Unique_cons.\n         ++ inversion H0; subst. unfold not in *. intros. apply H2. clear - H.\n            rewrite map_map in H. rewrite in_map_iff in H. do 2 (destruct H).\n            rewrite filter_In in H0. destruct H0. destruct x. destruct p. rewrite <- H.\n            simpl in *. rewrite in_map_iff. exists (s,l,t). simpl. split; auto.\n            destruct s; try discriminate. auto.\n         ++ inversion H0; subst. auto.\n      -- inversion H0; subst. auto.\n    * apply IHd. inversion H0; subst. auto.\n- apply (skeleton_cfun_sigs_names_unique_l (program_skeleton p)).\nQed.\n\n(**************************************************************************************************)\n(** ** Proof of gfun_sigs_in_dts (gfuns well-formedness #1)                                       *)\n(**************************************************************************************************)\n\nDefinition new_gfunsigs_g p n :=\n  filter (fun x => match x with (n',_) => negb (eq_TypeName n (fst n')) end) (skeleton_gfun_sigs_g (program_skeleton p)).\n\nLemma new_gfun_sigs_in_cdts_g : forall (p : program) (n : TypeName),\n  gfun_sigs_in_cdts (new_cdts p n) (new_gfunsigs_g p n).\nProof.\n  intros p n. unfold gfun_sigs_in_cdts. unfold new_cdts.\n  unfold new_gfunsigs_g. destruct p; simpl. clear - program_skeleton.\n  destruct program_skeleton; simpl. clear - skeleton_gfun_sigs_in_cdts_g.\n  unfold gfun_sigs_in_cdts in skeleton_gfun_sigs_in_cdts_g.\n  induction skeleton_gfun_sigs_g.\n  -simpl. apply Forall_nil.\n  -simpl. destruct a as [a0 a1]. simpl. destruct (eq_TypeName n (fst a0)) eqn:E.\n   +simpl. apply IHskeleton_gfun_sigs_g. inversion skeleton_gfun_sigs_in_cdts_g; subst. assumption.\n   +simpl. apply Forall_cons.\n    *simpl. inversion skeleton_gfun_sigs_in_cdts_g; subst. clear - E H1. simpl in H1. induction skeleton_cdts.\n     **inversion H1.\n     **simpl. destruct (eq_TypeName n a) eqn:E'.\n       ***simpl. apply IHskeleton_cdts. simpl in H1. destruct H1.\n          ****subst. rewrite E in E'. inversion E'.\n          ****assumption.\n       ***simpl. simpl in H1. destruct H1.\n          ****subst. left. reflexivity.\n          ****right. apply IHskeleton_cdts. assumption.\n    *apply IHskeleton_gfun_sigs_g. inversion skeleton_gfun_sigs_in_cdts_g; subst. assumption.\nQed.\n\nDefinition new_gfunsigs_l p n :=\n  filter (fun x => match x with (n',_) => negb (eq_TypeName n (fst n')) end) (skeleton_gfun_sigs_l (program_skeleton p)).\n\nLemma new_gfun_sigs_in_cdts_l : forall (p : program) (n : TypeName),\n  gfun_sigs_in_cdts (new_cdts p n) (new_gfunsigs_l p n).\nProof.\n  intros p n. unfold gfun_sigs_in_cdts. unfold new_cdts.\n  unfold new_gfunsigs_l. destruct p; simpl. clear - program_skeleton.\n  destruct program_skeleton; simpl. clear - skeleton_gfun_sigs_in_cdts_l.\n  unfold gfun_sigs_in_cdts in skeleton_gfun_sigs_in_cdts_l.\n  induction skeleton_gfun_sigs_l.\n  -simpl. apply Forall_nil.\n  -simpl. destruct a as [a0 a1]. simpl. destruct (eq_TypeName n (fst a0)) eqn:E.\n   +simpl. apply IHskeleton_gfun_sigs_l. inversion skeleton_gfun_sigs_in_cdts_l; subst. assumption.\n   +simpl. apply Forall_cons.\n    *simpl. inversion skeleton_gfun_sigs_in_cdts_l; subst. clear - E H1. simpl in H1. induction skeleton_cdts.\n     **inversion H1.\n     **simpl. destruct (eq_TypeName n a) eqn:E'.\n       ***simpl. apply IHskeleton_cdts. simpl in H1. destruct H1.\n          ****subst. rewrite E in E'. inversion E'.\n          ****assumption.\n       ***simpl. simpl in H1. destruct H1.\n          ****subst. left. reflexivity.\n          ****right. apply IHskeleton_cdts. assumption.\n    *apply IHskeleton_gfun_sigs_l. inversion skeleton_gfun_sigs_in_cdts_l; subst. assumption.\nQed.\n\n(**************************************************************************************************)\n(** ** Proof of gfun_sigs_names_unique (gfuns well-formedness #2)                                 *)\n(**************************************************************************************************)\n\nLemma new_gfun_sigs_names_unique_g : forall (p : program) (n : TypeName),\n  gfun_sigs_names_unique (new_gfunsigs_g p n).\nProof.\nintros p n. unfold gfun_sigs_names_unique. unfold new_gfunsigs_g.\npose proof (skeleton_gfun_sigs_names_unique_g (program_skeleton p)).\nunfold gfun_sigs_names_unique in H.\nassert (forall l, filter (fun x : TypeName * Name * list TypeName => let (n', _) := x in negb (eq_TypeName n (fst n'))) l\n = filter (fun x : TypeName * Name * list TypeName => negb (eq_TypeName n (fst (fst x)))) l).\n{ clear. intros. induction l; auto. simpl. destruct a. simpl. rewrite IHl. auto. }\nrewrite H0.\nrewrite filter_map with\n  (g:=fun x : TypeName * Name => negb (eq_TypeName n (fst x)))\n  (f:=fst). apply filter_unique. auto.\nQed.\n\nLemma new_gfun_sigs_names_unique_l : forall (p : program) (n : TypeName),\n  gfun_sigs_names_unique (new_gfunsigs_l p n).\nProof.\nintros p n. unfold gfun_sigs_names_unique. unfold new_gfunsigs_l.\npose proof (skeleton_gfun_sigs_names_unique_l (program_skeleton p)).\nunfold gfun_sigs_names_unique in H.\nassert (forall l, filter (fun x : TypeName * Name * list TypeName => let (n', _) := x in negb (eq_TypeName n (fst n'))) l\n = filter (fun x : TypeName * Name * list TypeName => negb (eq_TypeName n (fst (fst x)))) l).\n{ clear. intros. induction l; auto. simpl. destruct a. simpl. rewrite IHl. auto. }\nrewrite H0.\nrewrite filter_map with\n  (g:=fun x : TypeName * Name => negb (eq_TypeName n (fst x)))\n  (f:=fst). apply filter_unique. auto.\nQed.\n\n(**************************************************************************************************)\n(** * Constructorize to Skeleton.                                                                *)\n(**************************************************************************************************)\n\nDefinition constructorize_to_skeleton (p : program) (n : TypeName) : skeleton :=\n  let newDatatype := (computeNewDatatype p n) in\n  {|\n    skeleton_dts := n :: skeleton_dts (program_skeleton p);\n    skeleton_ctors := newDatatype ++ (skeleton_ctors (program_skeleton p));\n    skeleton_dts_ctors_in_dts := new_dts_ctors_in_dts p n;\n    skeleton_dts_ctor_names_unique := new_dts_ctor_names_unique p n;\n    skeleton_cdts := new_cdts p n;\n    skeleton_dtors := new_dtors p n;\n    skeleton_cdts_dtors_in_cdts := new_cdts_dtors_in_cdts p n;\n    skeleton_cdts_dtor_names_unique := new_cdts_dtor_names_unique p n;\n    skeleton_dts_cdts_disjoint := new_d_cd_disj p n;\n    skeleton_fun_sigs := skeleton_fun_sigs (program_skeleton p);\n    skeleton_fun_sigs_names_unique := skeleton_fun_sigs_names_unique (program_skeleton p);\n    skeleton_cfun_sigs_g := new_cfunsigs_g p n;\n    skeleton_cfun_sigs_in_dts_g := new_cfun_sigs_in_dts_g p n;\n    skeleton_cfun_sigs_names_unique_g := new_cfun_sigs_names_unique_g p n;\n    skeleton_cfun_sigs_l := new_cfunsigs_l p n;\n    skeleton_cfun_sigs_in_dts_l := new_cfun_sigs_in_dts_l p n;\n    skeleton_cfun_sigs_names_unique_l := new_cfun_sigs_names_unique_l p n;\n    skeleton_gfun_sigs_g := new_gfunsigs_g p n;\n    skeleton_gfun_sigs_in_cdts_g := new_gfun_sigs_in_cdts_g p n;\n    skeleton_gfun_sigs_names_unique_g := new_gfun_sigs_names_unique_g p n;\n    skeleton_gfun_sigs_l := new_gfunsigs_l p n;\n    skeleton_gfun_sigs_in_cdts_l := new_gfun_sigs_in_cdts_l p n;\n    skeleton_gfun_sigs_names_unique_l := new_gfun_sigs_names_unique_l p n\n  |}.\n", "meta": {"author": "ps-tuebingen", "repo": "decomposition-diversity", "sha": "28ab18c34f0a192c9b3d58caa709dee3e9129068", "save_path": "github-repos/coq/ps-tuebingen-decomposition-diversity", "path": "github-repos/coq/ps-tuebingen-decomposition-diversity/decomposition-diversity-28ab18c34f0a192c9b3d58caa709dee3e9129068/Formalization/CtorizeI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2109839562057856}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness of instruction selection for integer division *)\n\nRequire Import String.\nRequire Import Coqlib Maps.\nRequire Import AST Errors Integers Floats.\nRequire Import Values Memory Globalenvs Events Cminor Op CminorSel.\nRequire Import SelectOp SelectOpproof SplitLong.\n\nLocal Open Scope cminorsel_scope.\nLocal Open Scope string_scope.\n\n(** * Axiomatization of the helper functions *)\n\nDefinition external_implements (name: string) (sg: signature) (vargs: list val) (vres: val) : Prop :=\n  forall F V (ge: Genv.t F V) m,\n  external_call (EF_runtime name sg) ge vargs m E0 vres m.\n\nDefinition builtin_implements (name: string) (sg: signature) (vargs: list val) (vres: val) : Prop :=\n  forall F V (ge: Genv.t F V) m,\n  external_call (EF_builtin name sg) ge vargs m E0 vres m.\n\nAxiom i64_helpers_correct :\n    (forall x z, Val.longoffloat x = Some z -> external_implements \"__compcert_i64_dtos\" sig_f_l (x::nil) z)\n /\\ (forall x z, Val.longuoffloat x = Some z -> external_implements \"__compcert_i64_dtou\" sig_f_l (x::nil) z)\n /\\ (forall x z, Val.floatoflong x = Some z -> external_implements \"__compcert_i64_stod\" sig_l_f (x::nil) z)\n /\\ (forall x z, Val.floatoflongu x = Some z -> external_implements \"__compcert_i64_utod\" sig_l_f (x::nil) z)\n /\\ (forall x z, Val.singleoflong x = Some z -> external_implements \"__compcert_i64_stof\" sig_l_s (x::nil) z)\n /\\ (forall x z, Val.singleoflongu x = Some z -> external_implements \"__compcert_i64_utof\" sig_l_s (x::nil) z)\n /\\ (forall x, builtin_implements \"__builtin_negl\" sig_l_l (x::nil) (Val.negl x))\n /\\ (forall x y, builtin_implements \"__builtin_addl\" sig_ll_l (x::y::nil) (Val.addl x y))\n /\\ (forall x y, builtin_implements \"__builtin_subl\" sig_ll_l (x::y::nil) (Val.subl x y))\n /\\ (forall x y, builtin_implements \"__builtin_mull\" sig_ii_l (x::y::nil) (Val.mull' x y))\n /\\ (forall x y z, Val.divls x y = Some z -> external_implements \"__compcert_i64_sdiv\" sig_ll_l (x::y::nil) z)\n /\\ (forall x y z, Val.divlu x y = Some z -> external_implements \"__compcert_i64_udiv\" sig_ll_l (x::y::nil) z)\n /\\ (forall x y z, Val.modls x y = Some z -> external_implements \"__compcert_i64_smod\" sig_ll_l (x::y::nil) z)\n /\\ (forall x y z, Val.modlu x y = Some z -> external_implements \"__compcert_i64_umod\" sig_ll_l (x::y::nil) z)\n /\\ (forall x y, external_implements \"__compcert_i64_shl\" sig_li_l (x::y::nil) (Val.shll x y))\n /\\ (forall x y, external_implements \"__compcert_i64_shr\" sig_li_l (x::y::nil) (Val.shrlu x y))\n /\\ (forall x y, external_implements \"__compcert_i64_sar\" sig_li_l (x::y::nil) (Val.shrl x y))\n /\\ (forall x y, external_implements \"__compcert_i64_umulh\" sig_ll_l (x::y::nil) (Val.mullhu x y))\n /\\ (forall x y, external_implements \"__compcert_i64_smulh\" sig_ll_l (x::y::nil) (Val.mullhs x y)).\n\nDefinition helper_declared {F V: Type} (p: AST.program (AST.fundef F) V) (id: ident) (name: string) (sg: signature) : Prop :=\n  (prog_defmap p)!id = Some (Gfun (External (EF_runtime name sg))).\n\nDefinition helper_functions_declared {F V: Type} (p: AST.program (AST.fundef F) V) (hf: helper_functions) : Prop :=\n     helper_declared p i64_dtos \"__compcert_i64_dtos\" sig_f_l\n  /\\ helper_declared p i64_dtou \"__compcert_i64_dtou\" sig_f_l\n  /\\ helper_declared p i64_stod \"__compcert_i64_stod\" sig_l_f\n  /\\ helper_declared p i64_utod \"__compcert_i64_utod\" sig_l_f\n  /\\ helper_declared p i64_stof \"__compcert_i64_stof\" sig_l_s\n  /\\ helper_declared p i64_utof \"__compcert_i64_utof\" sig_l_s\n  /\\ helper_declared p i64_sdiv \"__compcert_i64_sdiv\" sig_ll_l\n  /\\ helper_declared p i64_udiv \"__compcert_i64_udiv\" sig_ll_l\n  /\\ helper_declared p i64_smod \"__compcert_i64_smod\" sig_ll_l\n  /\\ helper_declared p i64_umod \"__compcert_i64_umod\" sig_ll_l\n  /\\ helper_declared p i64_shl \"__compcert_i64_shl\" sig_li_l\n  /\\ helper_declared p i64_shr \"__compcert_i64_shr\" sig_li_l\n  /\\ helper_declared p i64_sar \"__compcert_i64_sar\" sig_li_l\n  /\\ helper_declared p i64_umulh \"__compcert_i64_umulh\" sig_ll_l\n  /\\ helper_declared p i64_smulh \"__compcert_i64_smulh\" sig_ll_l.\n\n(** * Correctness of the instruction selection functions for 64-bit operators *)\n\nSection CMCONSTR.\n\nVariable prog: program.\nVariable hf: helper_functions.\nHypothesis HELPERS: helper_functions_declared prog hf.\nLet ge := Genv.globalenv prog.\nVariable sp: val.\nVariable e: env.\nVariable m: mem.\n\nLtac UseHelper := decompose [Logic.and] i64_helpers_correct; eauto.\nLtac DeclHelper := red in HELPERS; decompose [Logic.and] HELPERS; eauto.\n\nLemma eval_helper:\n  forall le id name sg args vargs vres,\n  eval_exprlist ge sp e m le args vargs ->\n  helper_declared prog id name sg  ->\n  external_implements name sg vargs vres ->\n  eval_expr ge sp e m le (Eexternal id sg args) vres.\nProof.\n  intros.\n  red in H0. apply Genv.find_def_symbol in H0. destruct H0 as (b & P & Q).\n  rewrite <- Genv.find_funct_ptr_iff in Q.\n  econstructor; eauto.\nQed.\n\nCorollary eval_helper_1:\n  forall le id name sg arg1 varg1 vres,\n  eval_expr ge sp e m le arg1 varg1 ->\n  helper_declared prog id name sg  ->\n  external_implements name sg (varg1::nil) vres ->\n  eval_expr ge sp e m le (Eexternal id sg (arg1 ::: Enil)) vres.\nProof.\n  intros. eapply eval_helper; eauto. constructor; auto. constructor.\nQed.\n\nCorollary eval_helper_2:\n  forall le id name sg arg1 arg2 varg1 varg2 vres,\n  eval_expr ge sp e m le arg1 varg1 ->\n  eval_expr ge sp e m le arg2 varg2 ->\n  helper_declared prog id name sg  ->\n  external_implements name sg (varg1::varg2::nil) vres ->\n  eval_expr ge sp e m le (Eexternal id sg (arg1 ::: arg2 ::: Enil)) vres.\nProof.\n  intros. eapply eval_helper; eauto. constructor; auto. constructor; auto. constructor.\nQed.\n\nRemark eval_builtin_1:\n  forall le id sg arg1 varg1 vres,\n  eval_expr ge sp e m le arg1 varg1 ->\n  builtin_implements id sg (varg1::nil) vres ->\n  eval_expr ge sp e m le (Ebuiltin (EF_builtin id sg) (arg1 ::: Enil)) vres.\nProof.\n  intros. econstructor. econstructor. eauto. constructor. apply H0.\nQed.\n\nRemark eval_builtin_2:\n  forall le id sg arg1 arg2 varg1 varg2 vres,\n  eval_expr ge sp e m le arg1 varg1 ->\n  eval_expr ge sp e m le arg2 varg2 ->\n  builtin_implements id sg (varg1::varg2::nil) vres ->\n  eval_expr ge sp e m le (Ebuiltin (EF_builtin id sg) (arg1 ::: arg2 ::: Enil)) vres.\nProof.\n  intros. econstructor. constructor; eauto. constructor; eauto. constructor. apply H1.\nQed.\n\nDefinition unary_constructor_sound (cstr: expr -> expr) (sem: val -> val) : Prop :=\n  forall le a x,\n  eval_expr ge sp e m le a x ->\n  exists v, eval_expr ge sp e m le (cstr a) v /\\ Val.lessdef (sem x) v.\n\nDefinition binary_constructor_sound (cstr: expr -> expr -> expr) (sem: val -> val -> val) : Prop :=\n  forall le a x b y,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  exists v, eval_expr ge sp e m le (cstr a b) v /\\ Val.lessdef (sem x y) v.\n\nLtac EvalOp :=\n  eauto;\n  match goal with\n  | [ |- eval_exprlist _ _ _ _ _ Enil _ ] => constructor\n  | [ |- eval_exprlist _ _ _ _ _ (_:::_) _ ] => econstructor; EvalOp\n  | [ |- eval_expr _ _ _ _ _ (Eletvar _) _ ] => constructor; simpl; eauto\n  | [ |- eval_expr _ _ _ _ _ (Elet _ _) _ ] => econstructor; EvalOp\n  | [ |- eval_expr _ _ _ _ _ (lift _) _ ] => apply eval_lift; EvalOp\n  | [ |- eval_expr _ _ _ _ _ _ _ ] => eapply eval_Eop; [EvalOp | simpl; eauto]\n  | _ => idtac\n  end.\n\nLemma eval_splitlong:\n  forall le a f v sem,\n  (forall le a b x y,\n   eval_expr ge sp e m le a x ->\n   eval_expr ge sp e m le b y ->\n   exists v, eval_expr ge sp e m le (f a b) v /\\\n             (forall p q, x = Vint p -> y = Vint q -> v = sem (Vlong (Int64.ofwords p q)))) ->\n  match v with Vlong _ => True | _ => sem v = Vundef end ->\n  eval_expr ge sp e m le a v ->\n  exists v', eval_expr ge sp e m le (splitlong a f) v' /\\ Val.lessdef (sem v) v'.\nProof.\n  intros until sem; intros EXEC UNDEF.\n  unfold splitlong. case (splitlong_match a); intros.\n- InvEval; subst.\n  exploit EXEC. eexact H2. eexact H3. intros [v' [A B]].\n  exists v'; split. auto.\n  destruct v1; simpl in *; try (rewrite UNDEF; auto).\n  destruct v0; simpl in *; try (rewrite UNDEF; auto).\n  erewrite B; eauto.\n- exploit (EXEC (v :: le) (Eop Ohighlong (Eletvar 0 ::: Enil)) (Eop Olowlong (Eletvar 0 ::: Enil))).\n  EvalOp. EvalOp.\n  intros [v' [A B]].\n  exists v'; split. econstructor; eauto.\n  destruct v; try (rewrite UNDEF; auto). erewrite B; simpl; eauto. rewrite Int64.ofwords_recompose. auto.\nQed.\n\nLemma eval_splitlong_strict:\n  forall le a f va v,\n  eval_expr ge sp e m le a (Vlong va) ->\n  (forall le a1 a2,\n     eval_expr ge sp e m le a1 (Vint (Int64.hiword va)) ->\n     eval_expr ge sp e m le a2 (Vint (Int64.loword va)) ->\n     eval_expr ge sp e m le (f a1 a2) v) ->\n  eval_expr ge sp e m le (splitlong a f) v.\nProof.\n  intros until v.\n  unfold splitlong. case (splitlong_match a); intros.\n- InvEval. destruct v1; simpl in H; try discriminate. destruct v0; inv H.\n  apply H0. rewrite Int64.hi_ofwords; auto. rewrite Int64.lo_ofwords; auto.\n- EvalOp. apply H0; EvalOp.\nQed.\n\nLemma eval_splitlong2:\n  forall le a b f va vb sem,\n  (forall le a1 a2 b1 b2 x1 x2 y1 y2,\n   eval_expr ge sp e m le a1 x1 ->\n   eval_expr ge sp e m le a2 x2 ->\n   eval_expr ge sp e m le b1 y1 ->\n   eval_expr ge sp e m le b2 y2 ->\n   exists v,\n     eval_expr ge sp e m le (f a1 a2 b1 b2) v /\\\n     (forall p1 p2 q1 q2,\n       x1 = Vint p1 -> x2 = Vint p2 -> y1 = Vint q1 -> y2 = Vint q2 ->\n       v = sem (Vlong (Int64.ofwords p1 p2)) (Vlong (Int64.ofwords q1 q2)))) ->\n  match va, vb with Vlong _, Vlong _ => True | _, _ => sem va vb = Vundef end ->\n  eval_expr ge sp e m le a va ->\n  eval_expr ge sp e m le b vb ->\n  exists v, eval_expr ge sp e m le (splitlong2 a b f) v /\\ Val.lessdef (sem va vb) v.\nProof.\n  intros until sem; intros EXEC UNDEF.\n  unfold splitlong2. case (splitlong2_match a b); intros.\n- InvEval; subst.\n  exploit (EXEC le h1 l1 h2 l2); eauto. intros [v [A B]].\n  exists v; split; auto.\n  destruct v1; simpl in *; try (rewrite UNDEF; auto).\n  destruct v0; try (rewrite UNDEF; auto).\n  destruct v2; simpl in *; try (rewrite UNDEF; auto).\n  destruct v3; try (rewrite UNDEF; auto).\n  erewrite B; eauto.\n- InvEval; subst.\n  exploit (EXEC (vb :: le) (lift h1) (lift l1)\n                (Eop Ohighlong (Eletvar 0 ::: Enil)) (Eop Olowlong (Eletvar 0 ::: Enil))).\n  EvalOp. EvalOp. EvalOp. EvalOp.\n  intros [v [A B]].\n  exists v; split.\n  econstructor; eauto.\n  destruct v1; simpl in *; try (rewrite UNDEF; auto).\n  destruct v0; try (rewrite UNDEF; auto).\n  destruct vb; try (rewrite UNDEF; auto).\n  erewrite B; simpl; eauto. rewrite Int64.ofwords_recompose. auto.\n- InvEval; subst.\n  exploit (EXEC (va :: le)\n                (Eop Ohighlong (Eletvar 0 ::: Enil)) (Eop Olowlong (Eletvar 0 ::: Enil))\n                (lift h2) (lift l2)).\n  EvalOp. EvalOp. EvalOp. EvalOp.\n  intros [v [A B]].\n  exists v; split.\n  econstructor; eauto.\n  destruct va; try (rewrite UNDEF; auto).\n  destruct v1; simpl in *; try (rewrite UNDEF; auto).\n  destruct v0; try (rewrite UNDEF; auto).\n  erewrite B; simpl; eauto. rewrite Int64.ofwords_recompose. auto.\n- exploit (EXEC (vb :: va :: le)\n                (Eop Ohighlong (Eletvar 1 ::: Enil)) (Eop Olowlong (Eletvar 1 ::: Enil))\n                (Eop Ohighlong (Eletvar 0 ::: Enil)) (Eop Olowlong (Eletvar 0 ::: Enil))).\n  EvalOp. EvalOp. EvalOp. EvalOp.\n  intros [v [A B]].\n  exists v; split. EvalOp.\n  destruct va; try (rewrite UNDEF; auto); destruct vb; try (rewrite UNDEF; auto).\n  erewrite B; simpl; eauto. rewrite ! Int64.ofwords_recompose; auto.\nQed.\n\nLemma eval_splitlong2_strict:\n  forall le a b f va vb v,\n  eval_expr ge sp e m le a (Vlong va) ->\n  eval_expr ge sp e m le b (Vlong vb) ->\n  (forall le a1 a2 b1 b2,\n     eval_expr ge sp e m le a1 (Vint (Int64.hiword va)) ->\n     eval_expr ge sp e m le a2 (Vint (Int64.loword va)) ->\n     eval_expr ge sp e m le b1 (Vint (Int64.hiword vb)) ->\n     eval_expr ge sp e m le b2 (Vint (Int64.loword vb)) ->\n     eval_expr ge sp e m le (f a1 a2 b1 b2) v) ->\n  eval_expr ge sp e m le (splitlong2 a b f) v.\nProof.\n  assert (INV: forall v1 v2 n,\n    Val.longofwords v1 v2 = Vlong n -> v1 = Vint(Int64.hiword n) /\\ v2 = Vint(Int64.loword n)).\n  {\n    intros. destruct v1; simpl in H; try discriminate. destruct v2; inv H.\n    rewrite Int64.hi_ofwords; rewrite Int64.lo_ofwords; auto.\n  }\n  intros until v.\n  unfold splitlong2. case (splitlong2_match a b); intros.\n- InvEval. exploit INV. eexact H. intros [EQ1 EQ2]. exploit INV. eexact H0. intros [EQ3 EQ4].\n  subst. auto.\n- InvEval. exploit INV; eauto. intros [EQ1 EQ2]. subst.\n  econstructor. eauto. apply H1; EvalOp.\n- InvEval. exploit INV; eauto. intros [EQ1 EQ2]. subst.\n  econstructor. eauto. apply H1; EvalOp.\n- EvalOp. apply H1; EvalOp.\nQed.\n\nLemma is_longconst_sound:\n  forall le a x n,\n  is_longconst a = Some n ->\n  eval_expr ge sp e m le a x ->\n  x = Vlong n.\nProof.\n  unfold is_longconst; intros until n; intros LC.\n  destruct (is_longconst_match a); intros.\n  inv LC. InvEval. simpl in H5. inv H5. auto.\n  discriminate.\nQed.\n\nLemma is_longconst_zero_sound:\n  forall le a x,\n  is_longconst_zero a = true ->\n  eval_expr ge sp e m le a x ->\n  x = Vlong Int64.zero.\nProof.\n  unfold is_longconst_zero; intros.\n  destruct (is_longconst a) as [n|] eqn:E; try discriminate.\n  revert H. predSpec Int64.eq Int64.eq_spec n Int64.zero.\n  intros. subst. eapply is_longconst_sound; eauto.\n  congruence.\nQed.\n\nLemma eval_lowlong: unary_constructor_sound lowlong Val.loword.\nProof.\n  unfold lowlong; red. intros until x. destruct (lowlong_match a); intros.\n  InvEval; subst. exists v0; split; auto.\n  destruct v1; simpl; auto. destruct v0; simpl; auto.\n  rewrite Int64.lo_ofwords. auto.\n  exists (Val.loword x); split; auto. EvalOp.\nQed.\n\nLemma eval_highlong: unary_constructor_sound highlong Val.hiword.\nProof.\n  unfold highlong; red. intros until x. destruct (highlong_match a); intros.\n  InvEval; subst. exists v1; split; auto.\n  destruct v1; simpl; auto. destruct v0; simpl; auto.\n  rewrite Int64.hi_ofwords. auto.\n  exists (Val.hiword x); split; auto. EvalOp.\nQed.\n\nLemma eval_longconst:\n  forall le n, eval_expr ge sp e m le (longconst n) (Vlong n).\nProof.\n  intros. EvalOp. rewrite Int64.ofwords_recompose; auto.\nQed.\n\nTheorem eval_intoflong: unary_constructor_sound intoflong Val.loword.\nProof eval_lowlong.\n\nTheorem eval_longofintu: unary_constructor_sound longofintu Val.longofintu.\nProof.\n  red; intros. unfold longofintu. econstructor; split. EvalOp.\n  unfold Val.longofintu. destruct x; auto.\n  replace (Int64.repr (Int.unsigned i)) with (Int64.ofwords Int.zero i); auto.\n  apply Int64.same_bits_eq; intros.\n  rewrite Int64.testbit_repr by auto.\n  rewrite Int64.bits_ofwords by auto.\n  fold (Int.testbit i i0).\n  destruct (zlt i0 Int.zwordsize).\n  auto.\n  rewrite Int.bits_zero. rewrite Int.bits_above by omega. auto.\nQed.\n\nTheorem eval_longofint: unary_constructor_sound longofint Val.longofint.\nProof.\n  red; intros. unfold longofint. destruct (longofint_match a).\n- InvEval. econstructor; split. apply eval_longconst. auto.\n- exploit (eval_shrimm ge sp e m (Int.repr 31) (x :: le) (Eletvar 0)). EvalOp.\n  intros [v1 [A B]].\n  econstructor; split. EvalOp.\n  destruct x; simpl; auto.\n  simpl in B. inv B. simpl.\n  replace (Int64.repr (Int.signed i))\n     with (Int64.ofwords (Int.shr i (Int.repr 31)) i); auto.\n  apply Int64.same_bits_eq; intros.\n  rewrite Int64.testbit_repr by auto.\n  rewrite Int64.bits_ofwords by auto.\n  rewrite Int.bits_signed by omega.\n  destruct (zlt i0 Int.zwordsize).\n  auto.\n  assert (Int64.zwordsize = 2 * Int.zwordsize) by reflexivity.\n  rewrite Int.bits_shr by omega.\n  change (Int.unsigned (Int.repr 31)) with (Int.zwordsize - 1).\n  f_equal. destruct (zlt (i0 - Int.zwordsize + (Int.zwordsize - 1)) Int.zwordsize); omega.\nQed.\n\nTheorem eval_negl: unary_constructor_sound negl Val.negl.\nProof.\n  unfold negl; red; intros. destruct (is_longconst a) eqn:E.\n  econstructor; split. apply eval_longconst.\n  exploit is_longconst_sound; eauto. intros EQ; subst x. simpl. auto.\n  econstructor; split. eapply eval_builtin_1; eauto. UseHelper. auto.\nQed.\n\nTheorem eval_notl: unary_constructor_sound notl Val.notl.\nProof.\n  red; intros. unfold notl. apply eval_splitlong; auto.\n  intros.\n  exploit eval_notint. eexact H0. intros [va [A B]].\n  exploit eval_notint. eexact H1. intros [vb [C D]].\n  exists (Val.longofwords va vb); split. EvalOp.\n  intros; subst. simpl in *. inv B; inv D.\n  simpl. unfold Int.not. rewrite <- Int64.decompose_xor. auto.\n  destruct x; auto.\nQed.\n\nTheorem eval_longoffloat:\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  Val.longoffloat x = Some y ->\n  exists v, eval_expr ge sp e m le (longoffloat a) v /\\ Val.lessdef y v.\nProof.\n  intros; unfold longoffloat. econstructor; split.\n  eapply eval_helper_1; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_longuoffloat:\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  Val.longuoffloat x = Some y ->\n  exists v, eval_expr ge sp e m le (longuoffloat a) v /\\ Val.lessdef y v.\nProof.\n  intros; unfold longuoffloat. econstructor; split.\n  eapply eval_helper_1; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_floatoflong:\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  Val.floatoflong x = Some y ->\n  exists v, eval_expr ge sp e m le (floatoflong a) v /\\ Val.lessdef y v.\nProof.\n  intros; unfold floatoflong. econstructor; split.\n  eapply eval_helper_1; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_floatoflongu:\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  Val.floatoflongu x = Some y ->\n  exists v, eval_expr ge sp e m le (floatoflongu a) v /\\ Val.lessdef y v.\nProof.\n  intros; unfold floatoflongu. econstructor; split.\n  eapply eval_helper_1; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_longofsingle:\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  Val.longofsingle x = Some y ->\n  exists v, eval_expr ge sp e m le (longofsingle a) v /\\ Val.lessdef y v.\nProof.\n  intros; unfold longofsingle.\n  destruct x; simpl in H0; inv H0. destruct (Float32.to_long f) as [n|] eqn:EQ; simpl in H2; inv H2.\n  exploit eval_floatofsingle; eauto. intros (v & A & B). simpl in B. inv B.\n  apply Float32.to_long_double in EQ.\n  eapply eval_longoffloat; eauto. simpl.\n  change (Float.of_single f) with (Float32.to_double f); rewrite EQ; auto.\nQed.\n\nTheorem eval_longuofsingle:\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  Val.longuofsingle x = Some y ->\n  exists v, eval_expr ge sp e m le (longuofsingle a) v /\\ Val.lessdef y v.\nProof.\n  intros; unfold longuofsingle.\n  destruct x; simpl in H0; inv H0. destruct (Float32.to_longu f) as [n|] eqn:EQ; simpl in H2; inv H2.\n  exploit eval_floatofsingle; eauto. intros (v & A & B). simpl in B. inv B.\n  apply Float32.to_longu_double in EQ.\n  eapply eval_longuoffloat; eauto. simpl.\n  change (Float.of_single f) with (Float32.to_double f); rewrite EQ; auto.\nQed.\n\nTheorem eval_singleoflong:\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  Val.singleoflong x = Some y ->\n  exists v, eval_expr ge sp e m le (singleoflong a) v /\\ Val.lessdef y v.\nProof.\n  intros; unfold singleoflong. econstructor; split.\n  eapply eval_helper_1; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_singleoflongu:\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  Val.singleoflongu x = Some y ->\n  exists v, eval_expr ge sp e m le (singleoflongu a) v /\\ Val.lessdef y v.\nProof.\n  intros; unfold singleoflongu. econstructor; split.\n  eapply eval_helper_1; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_andl: binary_constructor_sound andl Val.andl.\nProof.\n  red; intros. unfold andl. apply eval_splitlong2; auto.\n  intros.\n  exploit eval_and. eexact H1. eexact H3. intros [va [A B]].\n  exploit eval_and. eexact H2. eexact H4. intros [vb [C D]].\n  exists (Val.longofwords va vb); split. EvalOp.\n  intros; subst. simpl in B; inv B. simpl in D; inv D.\n  simpl. f_equal. rewrite Int64.decompose_and. auto.\n  destruct x; auto. destruct y; auto.\nQed.\n\nTheorem eval_orl: binary_constructor_sound orl Val.orl.\nProof.\n  red; intros. unfold orl. apply eval_splitlong2; auto.\n  intros.\n  exploit eval_or. eexact H1. eexact H3. intros [va [A B]].\n  exploit eval_or. eexact H2. eexact H4. intros [vb [C D]].\n  exists (Val.longofwords va vb); split. EvalOp.\n  intros; subst. simpl in B; inv B. simpl in D; inv D.\n  simpl. f_equal. rewrite Int64.decompose_or. auto.\n  destruct x; auto. destruct y; auto.\nQed.\n\nTheorem eval_xorl: binary_constructor_sound xorl Val.xorl.\nProof.\n  red; intros. unfold xorl. apply eval_splitlong2; auto.\n  intros.\n  exploit eval_xor. eexact H1. eexact H3. intros [va [A B]].\n  exploit eval_xor. eexact H2. eexact H4. intros [vb [C D]].\n  exists (Val.longofwords va vb); split. EvalOp.\n  intros; subst. simpl in B; inv B. simpl in D; inv D.\n  simpl. f_equal. rewrite Int64.decompose_xor. auto.\n  destruct x; auto. destruct y; auto.\nQed.\n\nLemma is_intconst_sound:\n  forall le a x n,\n  is_intconst a = Some n ->\n  eval_expr ge sp e m le a x ->\n  x = Vint n.\nProof.\n  unfold is_intconst; intros until n; intros LC.\n  destruct a; try discriminate. destruct o; try discriminate. destruct e0; try discriminate.\n  inv LC. intros. InvEval. auto.\nQed.\n\nRemark eval_shift_imm:\n  forall (P: expr -> Prop) n a0 a1 a2 a3,\n  (n = Int.zero -> P a0) ->\n  (0 <= Int.unsigned n < Int.zwordsize ->\n   Int.ltu n Int.iwordsize = true ->\n   Int.ltu (Int.sub Int.iwordsize n) Int.iwordsize = true ->\n   Int.ltu n Int64.iwordsize' = true ->\n   P a1) ->\n  (Int.zwordsize <= Int.unsigned n < Int64.zwordsize ->\n   Int.ltu (Int.sub n Int.iwordsize) Int.iwordsize = true ->\n   P a2) ->\n  P a3 ->\n  P (if Int.eq n Int.zero then a0\n     else if Int.ltu n Int.iwordsize then a1\n     else if Int.ltu n Int64.iwordsize' then a2\n     else a3).\nProof.\n  intros until a3; intros A0 A1 A2 A3.\n  predSpec Int.eq Int.eq_spec n Int.zero.\n  apply A0; auto.\n  assert (NZ: Int.unsigned n <> 0).\n  { red; intros. elim H. rewrite <- (Int.repr_unsigned n). rewrite H0. auto. }\n  destruct (Int.ltu n Int.iwordsize) eqn:LT.\n  exploit Int.ltu_iwordsize_inv; eauto. intros RANGE.\n  assert (0 <= Int.zwordsize - Int.unsigned n < Int.zwordsize) by omega.\n  apply A1. auto. auto.\n  unfold Int.ltu, Int.sub. rewrite Int.unsigned_repr_wordsize.\n  rewrite Int.unsigned_repr. rewrite zlt_true; auto. omega.\n  generalize Int.wordsize_max_unsigned; omega.\n  unfold Int.ltu. rewrite zlt_true; auto.\n  change (Int.unsigned Int64.iwordsize') with 64.\n  change Int.zwordsize with 32 in RANGE. omega.\n  destruct (Int.ltu n Int64.iwordsize') eqn:LT'.\n  exploit Int.ltu_inv; eauto.\n  change (Int.unsigned Int64.iwordsize') with (Int.zwordsize * 2).\n  intros RANGE.\n  assert (Int.zwordsize <= Int.unsigned n).\n    unfold Int.ltu in LT. rewrite Int.unsigned_repr_wordsize in LT.\n    destruct (zlt (Int.unsigned n) Int.zwordsize). discriminate. omega.\n  apply A2. tauto. unfold Int.ltu, Int.sub. rewrite Int.unsigned_repr_wordsize.\n  rewrite Int.unsigned_repr. rewrite zlt_true; auto. omega.\n  generalize Int.wordsize_max_unsigned; omega.\n  auto.\nQed.\n\nLemma eval_shllimm:\n  forall n,\n  unary_constructor_sound (fun e => shllimm e n) (fun v => Val.shll v (Vint n)).\nProof.\n  unfold shllimm; red; intros.\n  apply eval_shift_imm; intros.\n  + (* n = 0 *)\n    subst n. exists x; split; auto. destruct x; simpl; auto.\n    change (Int64.shl' i Int.zero) with (Int64.shl i Int64.zero).\n    rewrite Int64.shl_zero. auto.\n  + (* 0 < n < 32 *)\n    apply eval_splitlong with (sem := fun x => Val.shll x (Vint n)); auto.\n    intros.\n    exploit eval_shlimm. eexact H4. instantiate (1 := n). intros [v1 [A1 B1]].\n    exploit eval_shlimm. eexact H5. instantiate (1 := n). intros [v2 [A2 B2]].\n    exploit eval_shruimm. eexact H5. instantiate (1 := Int.sub Int.iwordsize n). intros [v3 [A3 B3]].\n    exploit eval_or. eexact A1. eexact A3. intros [v4 [A4 B4]].\n    econstructor; split. EvalOp.\n    intros. subst. simpl in *. rewrite H1 in *. rewrite H2 in *. rewrite H3.\n    inv B1; inv B2; inv B3. simpl in B4. inv B4.\n    simpl. rewrite Int64.decompose_shl_1; auto.\n    destruct x; auto.\n  + (* 32 <= n < 64 *)\n    exploit eval_lowlong. eexact H. intros [v1 [A1 B1]].\n    exploit eval_shlimm. eexact A1. instantiate (1 := Int.sub n Int.iwordsize). intros [v2 [A2 B2]].\n    econstructor; split. EvalOp.\n    destruct x; simpl; auto.\n    destruct (Int.ltu n Int64.iwordsize'); auto.\n    simpl in B1; inv B1. simpl in B2. rewrite H1 in B2. inv B2.\n    simpl. erewrite <- Int64.decompose_shl_2. instantiate (1 := Int64.hiword i).\n    rewrite Int64.ofwords_recompose. auto. auto.\n  + (* n >= 64 *)\n    econstructor; split. eapply eval_helper_2; eauto. EvalOp. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_shll: binary_constructor_sound shll Val.shll.\nProof.\n  unfold shll; red; intros.\n  destruct (is_intconst b) as [n|] eqn:IC.\n- (* Immediate *)\n  exploit is_intconst_sound; eauto. intros EQ; subst y; clear H0.\n  eapply eval_shllimm; eauto.\n- (* General case *)\n  econstructor; split. eapply eval_helper_2; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nLemma eval_shrluimm:\n  forall n,\n  unary_constructor_sound (fun e => shrluimm e n) (fun v => Val.shrlu v (Vint n)).\nProof.\n  unfold shrluimm; red; intros. apply eval_shift_imm; intros.\n  + (* n = 0 *)\n    subst n. exists x; split; auto. destruct x; simpl; auto.\n    change (Int64.shru' i Int.zero) with (Int64.shru i Int64.zero).\n    rewrite Int64.shru_zero. auto.\n  + (* 0 < n < 32 *)\n    apply eval_splitlong with (sem := fun x => Val.shrlu x (Vint n)); auto.\n    intros.\n    exploit eval_shruimm. eexact H5. instantiate (1 := n). intros [v1 [A1 B1]].\n    exploit eval_shruimm. eexact H4. instantiate (1 := n). intros [v2 [A2 B2]].\n    exploit eval_shlimm. eexact H4. instantiate (1 := Int.sub Int.iwordsize n). intros [v3 [A3 B3]].\n    exploit eval_or. eexact A1. eexact A3. intros [v4 [A4 B4]].\n    econstructor; split. EvalOp.\n    intros. subst. simpl in *. rewrite H1 in *. rewrite H2 in *. rewrite H3.\n    inv B1; inv B2; inv B3. simpl in B4. inv B4.\n    simpl. rewrite Int64.decompose_shru_1; auto.\n    destruct x; auto.\n  + (* 32 <= n < 64 *)\n    exploit eval_highlong. eexact H. intros [v1 [A1 B1]].\n    exploit eval_shruimm. eexact A1. instantiate (1 := Int.sub n Int.iwordsize). intros [v2 [A2 B2]].\n    econstructor; split. EvalOp.\n    destruct x; simpl; auto.\n    destruct (Int.ltu n Int64.iwordsize'); auto.\n    simpl in B1; inv B1. simpl in B2. rewrite H1 in B2. inv B2.\n    simpl. erewrite <- Int64.decompose_shru_2. instantiate (1 := Int64.loword i).\n    rewrite Int64.ofwords_recompose. auto. auto.\n  + (* n >= 64 *)\n    econstructor; split. eapply eval_helper_2; eauto. EvalOp. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_shrlu: binary_constructor_sound shrlu Val.shrlu.\nProof.\n  unfold shrlu; red; intros.\n  destruct (is_intconst b) as [n|] eqn:IC.\n- (* Immediate *)\n  exploit is_intconst_sound; eauto. intros EQ; subst y; clear H0.\n  eapply eval_shrluimm; eauto.\n- (* General case *)\n  econstructor; split. eapply eval_helper_2; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nLemma eval_shrlimm:\n  forall n,\n  unary_constructor_sound (fun e => shrlimm e n) (fun v => Val.shrl v (Vint n)).\nProof.\n  unfold shrlimm; red; intros. apply eval_shift_imm; intros.\n  + (* n = 0 *)\n    subst n. exists x; split; auto. destruct x; simpl; auto.\n    change (Int64.shr' i Int.zero) with (Int64.shr i Int64.zero).\n    rewrite Int64.shr_zero. auto.\n  + (* 0 < n < 32 *)\n    apply eval_splitlong with (sem := fun x => Val.shrl x (Vint n)); auto.\n    intros.\n    exploit eval_shruimm. eexact H5. instantiate (1 := n). intros [v1 [A1 B1]].\n    exploit eval_shrimm. eexact H4. instantiate (1 := n). intros [v2 [A2 B2]].\n    exploit eval_shlimm. eexact H4. instantiate (1 := Int.sub Int.iwordsize n). intros [v3 [A3 B3]].\n    exploit eval_or. eexact A1. eexact A3. intros [v4 [A4 B4]].\n    econstructor; split. EvalOp.\n    intros. subst. simpl in *. rewrite H1 in *. rewrite H2 in *. rewrite H3.\n    inv B1; inv B2; inv B3. simpl in B4. inv B4.\n    simpl. rewrite Int64.decompose_shr_1; auto.\n    destruct x; auto.\n  + (* 32 <= n < 64 *)\n    exploit eval_highlong. eexact H. intros [v1 [A1 B1]].\n    assert (eval_expr ge sp e m (v1 :: le) (Eletvar 0) v1) by EvalOp.\n    exploit eval_shrimm. eexact H2. instantiate (1 := Int.sub n Int.iwordsize). intros [v2 [A2 B2]].\n    exploit eval_shrimm. eexact H2. instantiate (1 := Int.repr 31). intros [v3 [A3 B3]].\n    econstructor; split. EvalOp.\n    destruct x; simpl; auto.\n    destruct (Int.ltu n Int64.iwordsize'); auto.\n    simpl in B1; inv B1. simpl in B2. rewrite H1 in B2. inv B2.\n    simpl in B3. inv B3.\n    change (Int.ltu (Int.repr 31) Int.iwordsize) with true. simpl.\n    erewrite <- Int64.decompose_shr_2. instantiate (1 := Int64.loword i).\n    rewrite Int64.ofwords_recompose. auto. auto.\n  + (* n >= 64 *)\n    econstructor; split. eapply eval_helper_2; eauto. EvalOp. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_shrl: binary_constructor_sound shrl Val.shrl.\nProof.\n  unfold shrl; red; intros.\n  destruct (is_intconst b) as [n|] eqn:IC.\n- (* Immediate *)\n  exploit is_intconst_sound; eauto. intros EQ; subst y; clear H0.\n  eapply eval_shrlimm; eauto.\n- (* General case *)\n  econstructor; split. eapply eval_helper_2; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_addl: Archi.ptr64 = false -> binary_constructor_sound addl Val.addl.\nProof.\n  unfold addl; red; intros.\n  set (default := Ebuiltin (EF_builtin \"__builtin_addl\" sig_ll_l) (a ::: b ::: Enil)).\n  assert (DEFAULT:\n    exists v, eval_expr ge sp e m le default v /\\ Val.lessdef (Val.addl x y) v).\n  {\n    econstructor; split. eapply eval_builtin_2; eauto. UseHelper. auto.\n  }\n  destruct (is_longconst a) as [p|] eqn:LC1;\n  destruct (is_longconst b) as [q|] eqn:LC2.\n- exploit (is_longconst_sound le a); eauto. intros EQ; subst x.\n  exploit (is_longconst_sound le b); eauto. intros EQ; subst y.\n  econstructor; split. apply eval_longconst. simpl; auto.\n- predSpec Int64.eq Int64.eq_spec p Int64.zero; auto.\n  subst p. exploit (is_longconst_sound le a); eauto. intros EQ; subst x.\n  exists y; split; auto. unfold Val.addl; rewrite H; destruct y; auto. rewrite Int64.add_zero_l; auto.\n- predSpec Int64.eq Int64.eq_spec q Int64.zero; auto.\n  subst q. exploit (is_longconst_sound le b); eauto. intros EQ; subst y.\n  exists x; split; auto. unfold Val.addl; rewrite H; destruct x; simpl; auto. rewrite Int64.add_zero; auto.\n- auto.\nQed.\n\nTheorem eval_subl: Archi.ptr64 = false -> binary_constructor_sound subl Val.subl.\nProof.\n  unfold subl; red; intros.\n  set (default := Ebuiltin (EF_builtin \"__builtin_subl\" sig_ll_l) (a ::: b ::: Enil)).\n  assert (DEFAULT:\n    exists v, eval_expr ge sp e m le default v /\\ Val.lessdef (Val.subl x y) v).\n  {\n    econstructor; split. eapply eval_builtin_2; eauto. UseHelper. auto.\n  }\n  destruct (is_longconst a) as [p|] eqn:LC1;\n  destruct (is_longconst b) as [q|] eqn:LC2.\n- exploit (is_longconst_sound le a); eauto. intros EQ; subst x.\n  exploit (is_longconst_sound le b); eauto. intros EQ; subst y.\n  econstructor; split. apply eval_longconst. simpl; auto.\n- predSpec Int64.eq Int64.eq_spec p Int64.zero; auto.\n  replace (Val.subl x y) with (Val.negl y). eapply eval_negl; eauto.\n  subst p. exploit (is_longconst_sound le a); eauto. intros EQ; subst x.\n  destruct y; simpl; auto.\n- predSpec Int64.eq Int64.eq_spec q Int64.zero; auto.\n  subst q. exploit (is_longconst_sound le b); eauto. intros EQ; subst y.\n  exists x; split; auto. unfold Val.subl; rewrite H; destruct x; simpl; auto. rewrite Int64.sub_zero_l; auto.\n- auto.\nQed.\n\nLemma eval_mull_base: binary_constructor_sound mull_base Val.mull.\nProof.\n  unfold mull_base; red; intros. apply eval_splitlong2; auto.\n- intros.\n  set (p := Val.mull' x2 y2). set (le1 := p :: le0).\n  assert (E1: eval_expr ge sp e m le1 (Eop Olowlong (Eletvar O ::: Enil)) (Val.loword p)) by EvalOp.\n  assert (E2: eval_expr ge sp e m le1 (Eop Ohighlong (Eletvar O ::: Enil)) (Val.hiword p)) by EvalOp.\n  exploit eval_mul. apply eval_lift. eexact H2. apply eval_lift. eexact H3.\n  instantiate (1 := p). fold le1. intros [v3 [E3 L3]].\n  exploit eval_mul. apply eval_lift. eexact H1. apply eval_lift. eexact H4.\n  instantiate (1 := p). fold le1. intros [v4 [E4 L4]].\n  exploit eval_add. eexact E2. eexact E3. intros [v5 [E5 L5]].\n  exploit eval_add. eexact E5. eexact E4. intros [v6 [E6 L6]].\n  exists (Val.longofwords v6 (Val.loword p)); split.\n  EvalOp. eapply eval_builtin_2; eauto. UseHelper.\n  intros. unfold le1, p in *; subst; simpl in *.\n  inv L3. inv L4. inv L5. simpl in L6. inv L6.\n  simpl. f_equal. symmetry. apply Int64.decompose_mul.\n- destruct x; auto; destruct y; auto.\nQed.\n\nLemma eval_mullimm:\n  forall n, unary_constructor_sound (mullimm n) (fun v => Val.mull v (Vlong n)).\nProof.\n  unfold mullimm; red; intros.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero.\n  subst n. econstructor; split. apply eval_longconst.\n  destruct x; simpl; auto. rewrite Int64.mul_zero. auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.one.\n  subst n. exists x; split; auto.\n  destruct x; simpl; auto. rewrite Int64.mul_one. auto.\n  destruct (Int64.is_power2' n) as [l|] eqn:P2.\n  exploit eval_shllimm. eauto. instantiate (1 := l). intros [v [A B]].\n  exists v; split; auto.\n  destruct x; simpl; auto.\n  erewrite Int64.mul_pow2' by eauto.\n  simpl in B. erewrite Int64.is_power2'_range in B by eauto.\n  exact B.\n  apply eval_mull_base; auto. apply eval_longconst.\nQed.\n\nTheorem eval_mull: binary_constructor_sound mull Val.mull.\nProof.\n  unfold mull; red; intros.\n  destruct (is_longconst a) as [p|] eqn:LC1;\n  destruct (is_longconst b) as [q|] eqn:LC2.\n- exploit (is_longconst_sound le a); eauto. intros EQ; subst x.\n  exploit (is_longconst_sound le b); eauto. intros EQ; subst y.\n  econstructor; split. apply eval_longconst. simpl; auto.\n- exploit (is_longconst_sound le a); eauto. intros EQ; subst x.\n  replace (Val.mull (Vlong p) y) with (Val.mull y (Vlong p)) in *.\n  eapply eval_mullimm; eauto.\n  destruct y; simpl; auto. rewrite Int64.mul_commut; auto.\n- exploit (is_longconst_sound le b); eauto. intros EQ; subst y.\n  eapply eval_mullimm; eauto.\n- apply eval_mull_base; auto.\nQed.\n\nTheorem eval_mullhu:\n  forall n, unary_constructor_sound (fun a => mullhu a n) (fun v => Val.mullhu v (Vlong n)).\nProof.\n  unfold mullhu; intros; red; intros. econstructor; split; eauto.\n  eapply eval_helper_2; eauto. apply eval_longconst. DeclHelper; eauto. UseHelper.\nQed.\n\nTheorem eval_mullhs:\n  forall n, unary_constructor_sound (fun a => mullhs a n) (fun v => Val.mullhs v (Vlong n)).\nProof.\n  unfold mullhs; intros; red; intros. econstructor; split; eauto.\n  eapply eval_helper_2; eauto. apply eval_longconst. DeclHelper; eauto. UseHelper.\nQed.\n\nTheorem eval_shrxlimm:\n  forall le a n x z,\n  Archi.ptr64 = false ->\n  eval_expr ge sp e m le a x ->\n  Val.shrxl x (Vint n) = Some z ->\n  exists v, eval_expr ge sp e m le (shrxlimm a n) v /\\ Val.lessdef z v.\nProof.\n  intros.\n  apply Val.shrxl_shrl_2 in H1. unfold shrxlimm.\n  destruct (Int.eq n Int.zero).\n- subst z; exists x; auto.\n- set (le' := x :: le).\n  edestruct (eval_shrlimm (Int.repr 63) le' (Eletvar O)) as (v1 & A1 & B1).\n  constructor. reflexivity.\n  edestruct (eval_shrluimm (Int.sub (Int.repr 64) n) le') as (v2 & A2 & B2).\n  eexact A1.\n  edestruct (eval_addl H le' (Eletvar 0)) as (v3 & A3 & B3).\n  constructor. reflexivity. eexact A2.\n  edestruct (eval_shrlimm n le') as (v4 & A4 & B4). eexact A3.\n  exists v4; split.\n  econstructor; eauto.\n  assert (X: forall v1 v2 n, Val.lessdef v1 v2 -> Val.lessdef (Val.shrl v1 (Vint n)) (Val.shrl v2 (Vint n))).\n  { intros. inv H2; auto. }\n  assert (Y: forall v1 v2 n, Val.lessdef v1 v2 -> Val.lessdef (Val.shrlu v1 (Vint n)) (Val.shrlu v2 (Vint n))).\n  { intros. inv H2; auto. }\n  subst z. eapply Val.lessdef_trans; [|eexact B4]. apply X.\n  eapply Val.lessdef_trans; [|eexact B3]. apply Val.addl_lessdef; auto.\n  eapply Val.lessdef_trans; [|eexact B2]. apply Y.\n  auto.\nQed.\n\nTheorem eval_divlu_base:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.divlu x y = Some z ->\n  exists v, eval_expr ge sp e m le (divlu_base a b) v /\\ Val.lessdef z v.\nProof.\n  intros; unfold divlu_base.\n  econstructor; split. eapply eval_helper_2; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_modlu_base:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.modlu x y = Some z ->\n  exists v, eval_expr ge sp e m le (modlu_base a b) v /\\ Val.lessdef z v.\nProof.\n  intros; unfold modlu_base.\n  econstructor; split. eapply eval_helper_2; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_divls_base:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.divls x y = Some z ->\n  exists v, eval_expr ge sp e m le (divls_base a b) v /\\ Val.lessdef z v.\nProof.\n  intros; unfold divls_base.\n  econstructor; split. eapply eval_helper_2; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nTheorem eval_modls_base:\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.modls x y = Some z ->\n  exists v, eval_expr ge sp e m le (modls_base a b) v /\\ Val.lessdef z v.\nProof.\n  intros; unfold modls_base.\n  econstructor; split. eapply eval_helper_2; eauto. DeclHelper. UseHelper. auto.\nQed.\n\nRemark decompose_cmpl_eq_zero:\n  forall h l,\n  Int64.eq (Int64.ofwords h l) Int64.zero = Int.eq (Int.or h l) Int.zero.\nProof.\n  intros.\n  assert (Int64.zwordsize = Int.zwordsize * 2) by reflexivity.\n  predSpec Int64.eq Int64.eq_spec (Int64.ofwords h l) Int64.zero.\n  replace (Int.or h l) with Int.zero. rewrite Int.eq_true. auto.\n  apply Int.same_bits_eq; intros.\n  rewrite Int.bits_zero. rewrite Int.bits_or by auto.\n  symmetry. apply orb_false_intro.\n  transitivity (Int64.testbit (Int64.ofwords h l) (i + Int.zwordsize)).\n  rewrite Int64.bits_ofwords by omega. rewrite zlt_false by omega. f_equal; omega.\n  rewrite H0. apply Int64.bits_zero.\n  transitivity (Int64.testbit (Int64.ofwords h l) i).\n  rewrite Int64.bits_ofwords by omega. rewrite zlt_true by omega. auto.\n  rewrite H0. apply Int64.bits_zero.\n  symmetry. apply Int.eq_false. red; intros; elim H0.\n  apply Int64.same_bits_eq; intros.\n  rewrite Int64.bits_zero. rewrite Int64.bits_ofwords by auto.\n  destruct (zlt i Int.zwordsize).\n  assert (Int.testbit (Int.or h l) i = false) by (rewrite H1; apply Int.bits_zero).\n  rewrite Int.bits_or in H3 by omega. exploit orb_false_elim; eauto. tauto.\n  assert (Int.testbit (Int.or h l) (i - Int.zwordsize) = false) by (rewrite H1; apply Int.bits_zero).\n  rewrite Int.bits_or in H3 by omega. exploit orb_false_elim; eauto. tauto.\nQed.\n\nLemma eval_cmpl_eq_zero:\n  forall le a x,\n  eval_expr ge sp e m le a (Vlong x) ->\n  eval_expr ge sp e m le (cmpl_eq_zero a) (Val.of_bool (Int64.eq x Int64.zero)).\nProof.\n  intros. unfold cmpl_eq_zero.\n  eapply eval_splitlong_strict; eauto. intros.\n  exploit eval_or. eexact H0. eexact H1. intros [v1 [A1 B1]]. simpl in B1; inv B1.\n  exploit eval_comp. eexact A1. instantiate (2 := Eop (Ointconst Int.zero) Enil). EvalOp.\n  instantiate (1 := Ceq). intros [v2 [A2 B2]].\n  unfold Val.cmp in B2; simpl in B2.\n  rewrite <- decompose_cmpl_eq_zero in B2.\n  rewrite Int64.ofwords_recompose in B2.\n  destruct (Int64.eq x Int64.zero); inv B2; auto.\nQed.\n\nLemma eval_cmpl_ne_zero:\n  forall le a x,\n  eval_expr ge sp e m le a (Vlong x) ->\n  eval_expr ge sp e m le (cmpl_ne_zero a) (Val.of_bool (negb (Int64.eq x Int64.zero))).\nProof.\n  intros. unfold cmpl_ne_zero.\n  eapply eval_splitlong_strict; eauto. intros.\n  exploit eval_or. eexact H0. eexact H1. intros [v1 [A1 B1]]. simpl in B1; inv B1.\n  exploit eval_comp. eexact A1. instantiate (2 := Eop (Ointconst Int.zero) Enil). EvalOp.\n  instantiate (1 := Cne). intros [v2 [A2 B2]].\n  unfold Val.cmp in B2; simpl in B2.\n  rewrite <- decompose_cmpl_eq_zero in B2.\n  rewrite Int64.ofwords_recompose in B2.\n  destruct (negb (Int64.eq x Int64.zero)); inv B2; auto.\nQed.\n\nLemma eval_cmplu_gen:\n  forall ch cl a b le x y,\n  eval_expr ge sp e m le a (Vlong x) ->\n  eval_expr ge sp e m le b (Vlong y) ->\n  eval_expr ge sp e m le (cmplu_gen ch cl a b)\n    (Val.of_bool (if Int.eq (Int64.hiword x) (Int64.hiword y)\n                  then Int.cmpu cl (Int64.loword x) (Int64.loword y)\n                  else Int.cmpu ch (Int64.hiword x) (Int64.hiword y))).\nProof.\n  intros. unfold cmplu_gen. eapply eval_splitlong2_strict; eauto. intros.\n  econstructor. econstructor. EvalOp. simpl. eauto.\n  destruct (Int.eq (Int64.hiword x) (Int64.hiword y)); EvalOp.\nQed.\n\nRemark int64_eq_xor:\n  forall p q, Int64.eq p q = Int64.eq (Int64.xor p q) Int64.zero.\nProof.\n  intros.\n  predSpec Int64.eq Int64.eq_spec p q.\n  subst q. rewrite Int64.xor_idem. rewrite Int64.eq_true. auto.\n  predSpec Int64.eq Int64.eq_spec (Int64.xor p q) Int64.zero.\n  elim H. apply Int64.xor_zero_equal; auto.\n  auto.\nQed.\n\nTheorem eval_cmplu:\n  forall c le a x b y v,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.cmplu (Mem.valid_pointer m) c x y = Some v ->\n  Archi.ptr64 = false ->\n  eval_expr ge sp e m le (cmplu c a b) v.\nProof.\n  intros. unfold Val.cmplu, Val.cmplu_bool in H1. rewrite H2 in H1. simpl in H1.\n  destruct x; simpl in H1; try discriminate H1; destruct y; inv H1.\n  rename i into x. rename i0 into y.\n  destruct c; simpl.\n- (* Ceq *)\n  exploit eval_xorl. eexact H. eexact H0. intros [v1 [A B]]. simpl in B. inv B.\n  rewrite int64_eq_xor. apply eval_cmpl_eq_zero; auto.\n- (* Cne *)\n  exploit eval_xorl. eexact H. eexact H0. intros [v1 [A B]]. simpl in B. inv B.\n  rewrite int64_eq_xor. apply eval_cmpl_ne_zero; auto.\n- (* Clt *)\n  exploit (eval_cmplu_gen Clt Clt). eexact H. eexact H0. simpl.\n  rewrite <- Int64.decompose_ltu. rewrite ! Int64.ofwords_recompose. auto.\n- (* Cle *)\n  exploit (eval_cmplu_gen Clt Cle). eexact H. eexact H0. intros.\n  rewrite <- (Int64.ofwords_recompose x). rewrite <- (Int64.ofwords_recompose y).\n  rewrite Int64.decompose_leu. auto.\n- (* Cgt *)\n  exploit (eval_cmplu_gen Cgt Cgt). eexact H. eexact H0. simpl.\n  rewrite Int.eq_sym. rewrite <- Int64.decompose_ltu. rewrite ! Int64.ofwords_recompose. auto.\n- (* Cge *)\n  exploit (eval_cmplu_gen Cgt Cge). eexact H. eexact H0. intros.\n  rewrite <- (Int64.ofwords_recompose x). rewrite <- (Int64.ofwords_recompose y).\n  rewrite Int64.decompose_leu. rewrite Int.eq_sym. auto.\nQed.\n\nLemma eval_cmpl_gen:\n  forall ch cl a b le x y,\n  eval_expr ge sp e m le a (Vlong x) ->\n  eval_expr ge sp e m le b (Vlong y) ->\n  eval_expr ge sp e m le (cmpl_gen ch cl a b)\n    (Val.of_bool (if Int.eq (Int64.hiword x) (Int64.hiword y)\n                  then Int.cmpu cl (Int64.loword x) (Int64.loword y)\n                  else Int.cmp ch (Int64.hiword x) (Int64.hiword y))).\nProof.\n  intros. unfold cmpl_gen. eapply eval_splitlong2_strict; eauto. intros.\n  econstructor. econstructor. EvalOp. simpl. eauto.\n  destruct (Int.eq (Int64.hiword x) (Int64.hiword y)); EvalOp.\nQed.\n\nRemark decompose_cmpl_lt_zero:\n  forall h l,\n  Int64.lt (Int64.ofwords h l) Int64.zero = Int.lt h Int.zero.\nProof.\n  intros.\n  generalize (Int64.shru_lt_zero (Int64.ofwords h l)).\n  change (Int64.shru (Int64.ofwords h l) (Int64.repr (Int64.zwordsize - 1)))\n    with (Int64.shru' (Int64.ofwords h l) (Int.repr 63)).\n  rewrite Int64.decompose_shru_2.\n  change (Int.sub (Int.repr 63) Int.iwordsize)\n    with (Int.repr (Int.zwordsize - 1)).\n  rewrite Int.shru_lt_zero.\n  destruct (Int64.lt (Int64.ofwords h l) Int64.zero); destruct (Int.lt h Int.zero); auto; intros.\n  elim Int64.one_not_zero. auto.\n  elim Int64.one_not_zero. auto.\n  vm_compute. intuition congruence.\nQed.\n\nTheorem eval_cmpl:\n  forall c le a x b y v,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.cmpl c x y = Some v ->\n  eval_expr ge sp e m le (cmpl c a b) v.\nProof.\n  intros. unfold Val.cmpl in H1.\n  destruct x; simpl in H1; try discriminate. destruct y; inv H1.\n  rename i into x. rename i0 into y.\n  destruct c; simpl.\n- (* Ceq *)\n  exploit eval_xorl. eexact H. eexact H0. intros [v1 [A B]]. simpl in B; inv B.\n  rewrite int64_eq_xor. apply eval_cmpl_eq_zero; auto.\n- (* Cne *)\n  exploit eval_xorl. eexact H. eexact H0. intros [v1 [A B]]. simpl in B; inv B.\n  rewrite int64_eq_xor. apply eval_cmpl_ne_zero; auto.\n- (* Clt *)\n  destruct (is_longconst_zero b) eqn:LC.\n+ exploit is_longconst_zero_sound; eauto. intros EQ; inv EQ; clear H0.\n  exploit eval_highlong. eexact H. intros [v1 [A1 B1]]. simpl in B1. inv B1.\n  exploit eval_comp. eexact A1.\n  instantiate (2 := Eop (Ointconst Int.zero) Enil). EvalOp.\n  instantiate (1 := Clt). intros [v2 [A2 B2]].\n  unfold Val.cmp in B2. simpl in B2.\n  rewrite <- (Int64.ofwords_recompose x). rewrite decompose_cmpl_lt_zero.\n  destruct (Int.lt (Int64.hiword x) Int.zero); inv B2; auto.\n+ exploit (eval_cmpl_gen Clt Clt). eexact H. eexact H0. simpl.\n  rewrite <- Int64.decompose_lt. rewrite ! Int64.ofwords_recompose. auto.\n- (* Cle *)\n  exploit (eval_cmpl_gen Clt Cle). eexact H. eexact H0. intros.\n  rewrite <- (Int64.ofwords_recompose x). rewrite <- (Int64.ofwords_recompose y).\n  rewrite Int64.decompose_le. auto.\n- (* Cgt *)\n  exploit (eval_cmpl_gen Cgt Cgt). eexact H. eexact H0. simpl.\n  rewrite Int.eq_sym. rewrite <- Int64.decompose_lt. rewrite ! Int64.ofwords_recompose. auto.\n- (* Cge *)\n  destruct (is_longconst_zero b) eqn:LC.\n+ exploit is_longconst_zero_sound; eauto. intros EQ; inv EQ; clear H0.\n  exploit eval_highlong. eexact H. intros [v1 [A1 B1]]. simpl in B1; inv B1.\n  exploit eval_comp. eexact A1.\n  instantiate (2 := Eop (Ointconst Int.zero) Enil). EvalOp.\n  instantiate (1 := Cge). intros [v2 [A2 B2]].\n  unfold Val.cmp in B2; simpl in B2.\n  rewrite <- (Int64.ofwords_recompose x). rewrite decompose_cmpl_lt_zero.\n  destruct (negb (Int.lt (Int64.hiword x) Int.zero)); inv B2; auto.\n+ exploit (eval_cmpl_gen Cgt Cge). eexact H. eexact H0. intros.\n  rewrite <- (Int64.ofwords_recompose x). rewrite <- (Int64.ofwords_recompose y).\n  rewrite Int64.decompose_le. rewrite Int.eq_sym. auto.\nQed.\n\nEnd CMCONSTR.\n\n", "meta": {"author": "scuellar", "repo": "NewCompCert", "sha": "ff3f7c830c7676f7847ca9391d2786da3236c9f6", "save_path": "github-repos/coq/scuellar-NewCompCert", "path": "github-repos/coq/scuellar-NewCompCert/NewCompCert-ff3f7c830c7676f7847ca9391d2786da3236c9f6/backend/SplitLongproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2109839562057856}}
{"text": "(* heap_lang with deterministic allocation *)\nFrom stdpp Require Import base gmap.\nFrom iris.proofmode Require Import base proofmode classes.\nFrom iris.heap_lang Require Import lang primitive_laws.\nFrom iris_ni.program_logic Require Import dwp heap_lang_lifting.\n\n(** A simple allocator only knows about the state.\n    In the future we can also make it aware of the threadpool.\n*)\nModule Type Allocator.\nParameter oracle : state -> Z -> loc.\nAxiom oracle_fresh : ∀ σ n (i : Z), (0 ≤ i)%Z → (i < n)%Z → (heap σ) !! (oracle σ n +ₗ i) = None.\nEnd Allocator.\n\nModule SimpleAllocator : Allocator.\n  Definition oracle σ (n : Z) := fresh_locs (dom (gset loc) σ.(heap)).\n  Lemma oracle_fresh : ∀ σ n (i : Z), (0 ≤ i)%Z → (i < n)%Z → (heap σ) !! (oracle σ n +ₗ i) = None.\n  Proof.\n    intros σ n i Hi Hn. eapply (not_elem_of_dom (D:=gset loc)).\n    by apply fresh_locs_fresh.\n  Qed.\nEnd SimpleAllocator.\n\nModule heap_lang_det (A : Allocator).\n\nInductive head_step : expr → state → list observation → expr → state → list expr → Prop :=\n  | RecS f x e σ :\n     head_step (Rec f x e) σ [] (Val $ RecV f x e) σ []\n  | PairS v1 v2 σ :\n     head_step (Pair (Val v1) (Val v2)) σ [] (Val $ PairV v1 v2) σ []\n  | InjLS v σ :\n     head_step (InjL $ Val v) σ [] (Val $ InjLV v) σ []\n  | InjRS v σ :\n     head_step (InjR $ Val v) σ [] (Val $ InjRV v) σ []\n  | BetaS f x e1 v2 e' σ :\n     e' = subst' x v2 (subst' f (RecV f x e1) e1) →\n     head_step (App (Val $ RecV f x e1) (Val v2)) σ [] e' σ []\n  | UnOpS op v v' σ :\n     un_op_eval op v = Some v' →\n     head_step (UnOp op (Val v)) σ [] (Val v') σ []\n  | BinOpS op v1 v2 v' σ :\n     bin_op_eval op v1 v2 = Some v' →\n     head_step (BinOp op (Val v1) (Val v2)) σ [] (Val v') σ []\n  | IfTrueS e1 e2 σ :\n     head_step (If (Val $ LitV $ LitBool true) e1 e2) σ [] e1 σ []\n  | IfFalseS e1 e2 σ :\n     head_step (If (Val $ LitV $ LitBool false) e1 e2) σ [] e2 σ []\n  | FstS v1 v2 σ :\n     head_step (Fst (Val $ PairV v1 v2)) σ [] (Val v1) σ []\n  | SndS v1 v2 σ :\n     head_step (Snd (Val $ PairV v1 v2)) σ [] (Val v2) σ []\n  | CaseLS v e1 e2 σ :\n     head_step (Case (Val $ InjLV v) e1 e2) σ [] (App e1 (Val v)) σ []\n  | CaseRS v e1 e2 σ :\n     head_step (Case (Val $ InjRV v) e1 e2) σ [] (App e2 (Val v)) σ []\n  | ForkS e σ:\n     head_step (Fork e) σ [] (Val $ LitV LitUnit) σ [e]\n  | AllocNS n v σ :\n      let l := A.oracle σ n in\n     (0 < n)%Z →\n     (∀ i, (0 ≤ i)%Z → (i < n)%Z → σ.(heap) !! (l +ₗ i) = None) →\n     head_step (AllocN (Val $ LitV $ LitInt n) (Val v)) σ\n               []\n               (Val $ LitV $ LitLoc l) (state_init_heap l n v σ)\n               []\n  | FreeS l v σ :\n     σ.(heap) !! l = Some $ Some v →\n     head_step (Free (Val $ LitV $ LitLoc l)) σ\n               []\n               (Val $ LitV LitUnit) (state_upd_heap <[l:=None]> σ)\n               []\n  | LoadS l v σ :\n     σ.(heap) !! l = Some $ Some v →\n     head_step (Load (Val $ LitV $ LitLoc l)) σ [] (of_val v) σ []\n  | StoreS l v0 v σ :\n     σ.(heap) !! l = Some $ Some v0 →\n     head_step (Store (Val $ LitV $ LitLoc l) (Val v)) σ\n               []\n               (Val $ LitV LitUnit) (state_upd_heap <[l:=Some v]> σ)\n               []\n  | XchgS l v1 v2 σ :\n     σ.(heap) !! l = Some $ Some v1 →\n     head_step (Xchg (Val $ LitV $ LitLoc l) (Val v2)) σ\n               []\n               (Val v1) (state_upd_heap <[l:=Some v2]> σ)\n               []\n  | CmpXchgS l v1 v2 vl σ b :\n     σ.(heap) !! l = Some $ Some vl →\n     (* Crucially, this compares the same way as [EqOp]! *)\n     vals_compare_safe vl v1 →\n     b = bool_decide (vl = v1) →\n     head_step (CmpXchg (Val $ LitV $ LitLoc l) (Val v1) (Val v2)) σ\n               []\n               (Val $ PairV vl (LitV $ LitBool b)) (if b then state_upd_heap <[l:=Some v2]> σ else σ)\n               []\n  | FaaS l i1 i2 σ :\n     σ.(heap) !! l = Some $ Some (LitV (LitInt i1)) →\n     head_step (FAA (Val $ LitV $ LitLoc l) (Val $ LitV $ LitInt i2)) σ\n               []\n               (Val $ LitV $ LitInt i1) (state_upd_heap <[l:=Some $ LitV (LitInt (i1 + i2))]>σ)\n               []\n  | NewProphS σ :\n     let p := fresh σ.(used_proph_id) in\n     head_step NewProph σ\n               []\n               (Val $ LitV $ LitProphecy p) (state_upd_used_proph_id ({[ p ]} ∪.) σ)\n               []\n  | ResolveS p v e σ w σ' κs ts :\n     head_step e σ κs (Val v) σ' ts →\n     head_step (Resolve e (Val $ LitV $ LitProphecy p) (Val w)) σ\n               (κs ++ [(p, (v, w))]) (Val v) σ' ts.\n\nLtac inv_head_step :=\n  repeat match goal with\n  | _ => progress simplify_map_eq/= (* simplify memory stuff *)\n  | H : to_val _ = Some _ |- _ => apply of_to_val in H\n  | H : head_step ?e _ _ _ _ _ |- _ =>\n     inversion H; subst; clear H\n  end.\n\nLocal Hint Extern 0 (head_reducible _ _) => eexists _, _, _, _; simpl : core.\nLocal Hint Extern 0 (head_reducible_no_obs _ _) => eexists _, _, _; simpl : core.\n\n(* [simpl apply] is too stupid, so we need extern hints here. *)\nLocal Hint Extern 1 (head_step _ _ _ _ _ _) => econstructor : core.\nLocal Hint Extern 0 (head_step (CmpXchg _ _ _) _ _ _ _ _) => eapply CmpXchgS : core.\nLocal Hint Extern 0 (head_step (AllocN _ _) _ _ _ _ _) => apply alloc_fresh : core.\nLocal Hint Extern 0 (head_step NewProph _ _ _ _ _) => apply new_proph_id_fresh : core.\nLocal Hint Resolve to_of_val : core.\n\n(** The op sem is actually deterministic. *)\nTheorem head_step_det e σ e'1 σ'1 obs1 efs1 e'2 σ'2 obs2 efs2 :\n  head_step e σ obs1 e'1 σ'1 efs1 →\n  head_step e σ obs2 e'2 σ'2 efs2 →\n  obs1 = obs2 ∧ e'1 = e'2 ∧ σ'1 = σ'2 ∧ efs1 = efs2.\nProof.\n  intros Hst1. revert obs2 e'2 σ'2 efs2.\n  induction Hst1; intros obs2 e'2 σ'2 efs2;\n    inversion 1; repeat simplify_map_eq/=; eauto.\n  specialize (IHHst1 κs0 (Val v0) σ'2 efs2).\n  assert (v = v0) as <-.\n  { enough (Val v = Val v0); first by simplify_eq/=.\n    by apply IHHst1. }\n  repeat split; try f_equiv; eauto; by apply IHHst1.\nQed.\n\n(** Basic properties *)\n#[local] Instance fill_item_inj Ki : Inj (=) (=) (fill_item Ki).\nProof. induction Ki; intros ???; simplify_eq/=; auto with f_equal. Qed.\n\nLemma fill_item_val Ki e :\n  is_Some (to_val (fill_item Ki e)) → is_Some (to_val e).\nProof. intros [v ?]. induction Ki; simplify_option_eq; eauto. Qed.\n\nLemma val_head_stuck e1 σ1 κ e2 σ2 efs : head_step e1 σ1 κ e2 σ2 efs → to_val e1 = None.\nProof. destruct 1; naive_solver. Qed.\n\nLemma head_ctx_step_val Ki e σ1 κ e2 σ2 efs :\n  head_step (fill_item Ki e) σ1 κ e2 σ2 efs → is_Some (to_val e).\nProof. revert κ e2. induction Ki; inversion_clear 1; simplify_option_eq; eauto. Qed.\n\nLemma fill_item_no_val_inj Ki1 Ki2 e1 e2 :\n  to_val e1 = None → to_val e2 = None →\n  fill_item Ki1 e1 = fill_item Ki2 e2 → Ki1 = Ki2.\nProof. revert Ki1. induction Ki2, Ki1; naive_solver eauto with f_equal. Qed.\n\n\nLemma heap_lang_det_mixin : EctxiLanguageMixin of_val to_val fill_item head_step.\nProof.\n  split; apply _ || eauto using to_of_val, of_to_val, val_head_stuck,\n    fill_item_val, fill_item_no_val_inj, head_ctx_step_val.\nQed.\n\nCanonical Structure heap_ectxi_lang_det := EctxiLanguage heap_lang_det_mixin.\nCanonical Structure heap_ectx_lang_det := EctxLanguageOfEctxi heap_ectxi_lang_det.\nCanonical Structure heap_lang_det := LanguageOfEctx heap_ectx_lang_det.\n\n\n(** Different relations between the deterministic and non-deterministic semantics *)\n\nLemma head_step_det_nondet e σ e' σ' κs efs :\n  head_step e σ κs e' σ' efs →\n  heap_lang.head_step e σ κs e' σ' efs.\nProof.\n  induction 1; try econstructor; eauto.\n  - unfold p. apply is_fresh.\nQed.\n\nLemma prim_step_det_nondet e σ e' σ' κs efs :\n  prim_step (Λ := heap_ectx_lang_det) e σ κs e' σ' efs →\n  prim_step (Λ := heap_ectx_lang) e σ κs e' σ' efs.\nProof.\n  inversion 1. subst. econstructor; try done. by apply head_step_det_nondet.\nQed.\n\nLemma head_step_nondet_det_val e v σ σ' κs efs e2 σ'2 κs2 efs2 :\n  heap_lang.head_step e σ κs (Val v) σ' efs →\n  head_step e σ κs2 e2 σ'2 efs2 →\n  is_Some (to_val e2).\nProof.\n  intros Hst_nondet Hst_det.\n  inversion Hst_nondet; inversion Hst_det; simplify_eq/=; eauto.\n  exists v. rewrite -H. eauto.\nQed.\n\nLemma head_reducible_nondet_det e σ :\n  head_reducible (Λ := heap_ectx_lang) e σ →\n  head_reducible (Λ := heap_ectx_lang_det) e σ.\nProof.\n  destruct 1 as (κs&e2&σ2&efs&H).\n  induction H; try by (do 4 eexists; econstructor; eauto).\n  - repeat econstructor; eauto=> i Hi Hn.\n    by apply A.oracle_fresh.\n  - destruct IHhead_step as (κs2&e2&σ2&efs2&Hst_det). simpl in *.\n    assert (is_Some (to_val e2)) as [v2 Hv2].\n    { by eapply head_step_nondet_det_val. }\n    repeat econstructor.\n    rewrite -(of_to_val _ _ Hv2) in Hst_det. done.\nQed.\n\nLemma reducible_det_nondet e σ :\n  reducible (Λ := heap_lang_det) e σ →\n  reducible (Λ := heap_lang) e σ.\nProof.\n  destruct 1 as (κs & e' & σ' & efs & H).\n  inversion H. simpl in *. subst e e'.\n  do 4 eexists. econstructor; try naive_solver.\n  by apply head_step_det_nondet.\nQed.\n\nLemma reducible_nondet_det e σ :\n  reducible (Λ := heap_lang) e σ →\n  reducible (Λ := heap_lang_det) e σ.\nProof.\n  destruct 1 as (κs & e' & σ' & efs & H).\n  inversion H. simpl in *. subst e e'.\n  apply (@head_prim_fill_reducible heap_ectxi_lang_det).\n  apply head_reducible_nondet_det.\n  by repeat eexists.\nQed.\n\nLemma head_step_nondet_det_obs e1 σ1 e2 σ2 efs e2' σ2' efs' κ :\n  heap_lang.head_step e1 σ1 [] e2 σ2 efs →\n  head_step e1 σ1 κ e2' σ2' efs' →\n  κ = [].\nProof.\n  intros Hst1 Hst2.\n  inversion Hst2; try by eauto.\n  simpl in * ; subst.\n  inversion Hst1. exfalso.\n  by eapply app_cons_not_nil.\nQed.\n\nLemma head_reducible_no_obs_nondet_det e σ :\n  head_reducible_no_obs (Λ := heap_ectx_lang) e σ →\n  head_reducible_no_obs (Λ := heap_ectx_lang_det) e σ.\nProof.\n  destruct 1 as (e'&σ'&efs&Hst).\n  assert (head_reducible (Λ := heap_ectx_lang_det) e σ) as Hred2.\n  { apply head_reducible_nondet_det. eauto. }\n  destruct Hred2 as (κ&e''&σ''&efs''&Hst2).\n  assert (κ = []) as ->.\n  { eapply head_step_nondet_det_obs; eauto. }\n  eauto.\nQed.\n\nLemma reducible_no_obs_nondet_det e σ :\n  reducible_no_obs (Λ := heap_lang) e σ →\n  reducible_no_obs (Λ := heap_lang_det) e σ.\nProof.\n  destruct 1 as (e' & σ' & efs & H).\n  inversion H. simpl in *. subst e e'.\n  apply (@head_prim_fill_reducible_no_obs heap_ectxi_lang_det).\n  apply head_reducible_no_obs_nondet_det.\n  by repeat eexists.\nQed.\n\nSection lifting.\n\n#[local] Instance heapG_irisG_det `{!heapGS Σ} : irisGS heap_lang_det Σ := {\n  iris_invGS := heapGS_invGS;\n  state_interp σ _ κs _ :=\n    (gen_heap_interp σ.(heap) ∗ proph_map_interp κs σ.(used_proph_id))%I;\n  fork_post _ := True%I;\n  num_laters_per_step := λ _, 0;\n  state_interp_mono _ _ _ _ := fupd_intro _ _;\n}.\n\n\nContext `{!heapGS Σ}.\nImplicit Types Φ Ψ : val → iProp Σ.\n\nLemma wp_simul e E Φ :\n  (wp (EXPR := language.expr heap_lang    ) (VAL := language.val heap_lang    ) NotStuck E e Φ) -∗\n  (wp (EXPR := language.expr heap_lang_det) (VAL := language.val heap_lang_det) NotStuck E e Φ).\nProof.\n  iLöb as \"IH\" forall (e E Φ).\n  rewrite !wp_unfold /wp_pre /=.\n  destruct (to_val e) as [v|]; first by eauto.\n  iIntros \"H\". iIntros (σ1 m κ κs n) \"[Hσ Hp]\".\n  iMod (\"H\" $! σ1 m κ κs n with \"[$Hσ $Hp]\") as \"[% H]\".\n  iModIntro. iSplitR.\n  { iPureIntro. by apply reducible_nondet_det. }\n  iIntros (e2 σ2 efs Hst_det).\n  iSpecialize (\"H\" $! e2 σ2 efs with \"[%]\").\n  { by apply prim_step_det_nondet. }\n  iMod \"H\" as \"H\". iModIntro. iNext.\n  iMod \"H\" as \"H\". iModIntro.\n  iMod \"H\" as \"($&HWP&Hefs)\". iModIntro.\n  iSplitL \"HWP\".\n  - by iApply \"IH\".\n  - iApply (big_sepL_impl with \"Hefs []\").\n    iModIntro. iIntros (???). iApply \"IH\".\nQed.\nEnd lifting.\n\nSection dwp_lifting.\n\n#[local] Instance heapDG_irisDG_det `{heapDG Σ} : irisDG heap_lang_det Σ := {\n  state_rel := (λ σ1 σ2 κs1 κs2,\n      @gen_heap_interp _ _ _ _ _ heapDG_gen_heapG1 σ1.(heap)\n    ∗ @proph_map_interp _ _ _ _ _ heapDG_proph_mapG1 κs1 σ1.(used_proph_id)\n    ∗ @gen_heap_interp _ _ _ _ _ heapDG_gen_heapG2 σ2.(heap)\n    ∗ @proph_map_interp _ _ _ _ _ heapDG_proph_mapG2 κs2 σ2.(used_proph_id))%I\n}.\n\nContext `{!heapDG Σ}.\n\nLemma dwp_simul e1 e2 E Φ :\n  (dwp (Λ := heap_lang) E e1 e2 Φ) -∗\n  (dwp (Λ := heap_lang_det) E e1 e2 Φ).\nProof.\n  iLöb as \"IH\" forall (e1 e2 E Φ).\n  rewrite !dwp_unfold /dwp_pre /=.\n  repeat case_match; [by eauto with iFrame..|].\n  iIntros \"H\". iIntros (σ1 σ2 κ1 κs1 κ2 κs2) \"(Hσ1 & Hp1 & Hσ2 & Hp2)\".\n  iMod (\"H\" with \"[$Hσ1 $Hp1 $Hσ2 $Hp2]\") as \"[% [% H]]\".\n  iModIntro. iSplitR.\n  { iPureIntro. by apply reducible_no_obs_nondet_det. }\n  iSplitR.\n  { iPureIntro. by apply reducible_no_obs_nondet_det. }\n  iIntros (e1' σ1' efs1 e2' σ2' efs2 Hst_det1 Hst_det2).\n  iSpecialize (\"H\" $! e1' σ1' efs1 e2' σ2' efs2 with \"[%] [%]\").\n  { by apply prim_step_det_nondet. }\n  { by apply prim_step_det_nondet. }\n  iMod \"H\" as \"H\". iModIntro.\n  iNext. iMod \"H\" as \"H\". iModIntro.\n  iDestruct \"H\" as \"($&HWP&Hefs)\".\n  iSplitL \"HWP\".\n  - by iApply \"IH\".\n  - iApply (big_sepL2_impl with \"Hefs []\").\n    iModIntro. iIntros (?????). iApply \"IH\".\nQed.\n\nEnd dwp_lifting.\n\n\nEnd heap_lang_det.\n\n", "meta": {"author": "co-dan", "repo": "SeLoC", "sha": "c6e3e77b61ed4800a201eec123ae5e4f277d2ea1", "save_path": "github-repos/coq/co-dan-SeLoC", "path": "github-repos/coq/co-dan-SeLoC/SeLoC-c6e3e77b61ed4800a201eec123ae5e4f277d2ea1/theories/heap_lang/lang_det.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21096646362586}}
{"text": "Set Implicit Arguments.\nSet Maximal Implicit Insertion.\nSet Contextual Implicit.\n\nFrom Coq Require Import\n     List\n     Psatz\n     Relation_Definitions\n     RelationClasses\n.\n\nRequire Import GHC.Base.\nRequire Import Fix.\nRequire Import Tactics.Tactics.\nRequire Import ClassesOfFunctors.FunctorPlus.\nRequire Import ClassesOfFunctors.DictDerive.\n\nRequire Import Adverb.Composable.Adverb.\nRequire Import Adverb.Composable.Purely.\nRequire Import Adverb.Composable.Statically.\nRequire Import Adverb.Composable.Dynamically.\n\nDefinition var := nat.\n\nDefinition val := nat.\n\n(** * Effect. *)\n\nVariant DataEff (K : Set -> Set) : Set -> Set :=\n| GetData : var -> DataEff K val.\n\nArguments GetData {_}.\n\nDefinition fmap1_DataEff {F G : Set -> Set} {A : Set}\n           (f : forall X, F X -> G X)\n           (a : DataEff F A) : DataEff G A :=\n  match a with\n  | GetData v => GetData v\n  end.\n\n#[global] Program Instance Functor1__DataEff : Functor1 DataEff :=\n  {| fmap1 := @fmap1_DataEff |}.\nNext Obligation.\n  destruct x; reflexivity.\nQed.\nNext Obligation.\n  destruct x; reflexivity.\nQed.\n\nSection SmartConstructor.\n\n  Variable F : (Set -> Set) -> Set -> Set.\n  Context `{Functor1 F}.\n  Context `{DataEff -≪ F}.\n\n  Definition getData (x : var) : Fix1 F val :=\n    @inF1 _ _ _ (inj1 (GetData x)).\n\nEnd SmartConstructor.\n\n(** * Adverbs used. *)\n\nDefinition LanAdverbs := PurelyAdv ⊕ StaticallyAdv ⊕ DynamicallyAdv ⊕ DataEff.\n\nDefinition Lan := Fix1 LanAdverbs.\n\n(** * The Update monad\n\n    As shown in Fig. 14a. *)\n\nDefinition Update (A : Set) : Set := ((var -> val) -> A * nat).\n\nOpen Scope nat_scope.\n\nDefinition retUpdate {A : Set} (a : A) : Update A := fun map => (a, 0).\n\nDefinition bindUpdate {A B : Set}\n           (m : Update A) (k : A -> Update B) : Update B :=\n  fun map =>\n    match m map with\n    | (i, n) =>\n      match (k i map) with\n      | (r, n') => (r, n + n')\n      end\n    end.\n\nDefinition parUpdate {A B C : Set}\n           (f : A -> B -> C) (a : Update A) (b : Update B) : Update C :=\n  fun map =>\n    match (a map, b map) with\n    | ((a, n1), (b, n2)) => (f a b, Nat.max n1 n2)\n    end.\n\n(* [getUpdate] is [get] in Fig. 14a. *)\nDefinition getUpdate (v : var) : Update val :=\n  fun map => (map v, 1).\n\nGoal forall {A B C : Set} (f : A -> B -> C) a b,\n    forall m, parUpdate f a b m = parUpdate (flip f) b a m.\nProof.\n  intros. unfold parUpdate.\n  remember (a m) as am. remember (b m) as bm.\n  destruct am; destruct bm. unfold flip.\n  f_equal. apply Nat.max_comm.\nQed.\n\nDefinition MonadDict__Update : Monad__Dict Update :=\n  (* [bindUpdate] is [bind] in Fig. 14a. *)\n  {| op_zgzg____ := fun _ _ m k => bindUpdate m (fun _ => k) ;\n     op_zgzgze____ := fun _ _ => bindUpdate ;\n  (* [retUpdate] is [ret] in Fig. 14a. *)\n     return___ := fun _ => retUpdate\n  |}.\n\nDefinition ApDict__Update : Applicative__Dict Update :=\n  (* [parUpdate] is [liftA2] in Fig. 14a. *)\n  {| liftA2__ := fun _ _ _ => parUpdate ;\n     op_zlztzg____ := fun _ _ => parUpdate id ;\n     op_ztzg____ := fun _ _ => parUpdate (fun _ => id) ;\n     pure__ := fun _ => retUpdate\n  |}.\n\n(** Give a name to [AdverbAlg], a technical way to tell apart\n    different adverb interpretations. *)\n\nDefinition costName : nat := 0.\n\n(** * Interpreting Composed Adverbs\n\n    Fig. 14b. We define the interpreter of our composed adverb [LanAdverbs] by\n    defining an interpretation for each individual adverb and then compose their\n    interpretation together (automatically composed via the [AdverbAlgSum]\n    instance shown earlier). *)\n\n#[global] Instance CostApp : AdverbAlg StaticallyAdv Update costName :=\n  {| adverbAlg := fun _ c =>\n                    match c with\n                    | LiftA2 f a b =>\n                      parUpdate f a b\n                    end\n  |}.\n\n#[global] Instance CostMonad : AdverbAlg DynamicallyAdv Update costName :=\n  {| adverbAlg := fun _ c =>\n                    match c with\n                    | Bind m k =>\n                      bindUpdate m k\n                    end\n  |}.\n\n#[global] Instance CostPure : AdverbAlg PurelyAdv Update costName :=\n  {| adverbAlg := fun _ c =>\n                    match c with\n                    | Pure a => retUpdate a\n                    end\n  |}.\n\n#[global] Instance CostData : AdverbAlg DataEff Update costName :=\n  {| adverbAlg := fun _ c =>\n                    match c in (DataEff _ N) return (Update N) with\n                    | GetData v => getUpdate v\n                    end\n  |}.\n\n(** The composed interpreter. *)\n\nDefinition costAlg : Alg1 LanAdverbs Update := adverbAlg (name := costName).\n\nDefinition cost {A : Set} : Lan A -> Update A := foldFix1 (@costAlg).\n\n(** * Examples. *)\n\nDefinition test1 : Lan bool := liftA2 (fun _ _ => true)\n                              (@getData _ _ _ 0)\n                              (@getData _ _ _ 1).\n\nDefinition test2 : Lan val := (@getData _ _ _ 0) >> (@getData _ _ _ 1).\n\nDefinition test3 : Lan bool := liftA2 (fun _ _ => true)\n                              (@test2)\n                              ((@test1) >> (@test2)).\n\n(** Uncomment the following to see results: *)\n\n(*\nCompute (cost (@test1)).\n\nCompute (cost (@test2)).\n\nCompute (cost (@test3)).\n*)\n\n(* cost (the second value in the product) of [test1] should be 1 *)\n(* cost (the second value in the product) of [test2] should be 2 *)\n(* cost (the second value in the product) of [test3] should be 3 *)\n", "meta": {"author": "lastland", "repo": "ProgramAdverbs", "sha": "1f8086d379d1fc0eb896539adae66cd9f7d8ec04", "save_path": "github-repos/coq/lastland-ProgramAdverbs", "path": "github-repos/coq/lastland-ProgramAdverbs/ProgramAdverbs-1f8086d379d1fc0eb896539adae66cd9f7d8ec04/Examples/Haxl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.21085589648774453}}
{"text": "(* ** Imports and settings *)\nFrom mathcomp Require Import all_ssreflect all_algebra.\nRequire Import oseq.\nRequire Export ZArith Setoid Morphisms.\nFrom mathcomp Require Import word_ssrZ.\nRequire Export strings word utils type ident var global sem_type sopn syscall.\nRequire Import xseq.\nImport Utf8 ZArith.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Unset Elimination Schemes.\n\n(* ** Operators\n * -------------------------------------------------------------------- *)\n(* *** Summary\n   Operators represent several constructs in the Ocaml compiler:\n   - const-op: compile-time expressions (constexpr in C++)\n   - list-op: argument and result lists\n   - arr-op: reading and writing arrays\n   - cpu-op: CPU instructions such as addition with carry\n*)\n\nVariant cmp_kind :=\n  | Cmp_int\n  | Cmp_w of signedness & wsize.\n\nVariant op_kind :=\n  | Op_int\n  | Op_w of wsize.\n\nVariant sop1 :=\n| Oword_of_int of wsize     (* int → word *)\n| Oint_of_word of wsize     (* word → unsigned int *)\n| Osignext of wsize & wsize (* Sign-extension: output-size, input-size *)\n| Ozeroext of wsize & wsize (* Zero-extension: output-size, input-size *)\n| Onot                      (* Boolean negation *)\n| Olnot of wsize            (* Bitwize not: 1s’ complement *)\n| Oneg  of op_kind          (* Arithmetic negation *)\n.\n\nVariant sop2 :=\n| Obeq                        (* const : sbool -> sbool -> sbool *)\n| Oand                        (* const : sbool -> sbool -> sbool *)\n| Oor                         (* const : sbool -> sbool -> sbool *)\n\n| Oadd  of op_kind\n| Omul  of op_kind\n| Osub  of op_kind\n| Odiv  of cmp_kind\n| Omod  of cmp_kind\n\n| Oland of wsize\n| Olor  of wsize\n| Olxor of wsize\n| Olsr  of wsize \n| Olsl  of op_kind\n| Oasr  of op_kind\n| Oror  of wsize\n| Orol  of wsize\n\n| Oeq   of op_kind\n| Oneq  of op_kind\n| Olt   of cmp_kind\n| Ole   of cmp_kind\n| Ogt   of cmp_kind\n| Oge   of cmp_kind\n\n(* vector operation *)\n| Ovadd of velem & wsize (* VPADD   *)\n| Ovsub of velem & wsize (* VPSUB   *)\n| Ovmul of velem & wsize (* VPMULLW *)\n| Ovlsr of velem & wsize\n| Ovlsl of velem & wsize\n| Ovasr of velem & wsize\n.\n\n(* N-ary operators *)\nVariant combine_flags :=\n| CF_LT    of signedness   (* Alias : signed => L  ; unsigned => B   *) \n| CF_LE    of signedness   (* Alias : signed => LE ; unsigned => BE  *)\n| CF_EQ                    (* Alias : E                              *)\n| CF_NEQ                   (* Alias : !E                             *)\n| CF_GE    of signedness   (* Alias : signed => !L ; unsigned => !B  *)\n| CF_GT    of signedness   (* Alias : signed => !LE; unsigned => !BE *)\n.\n\nVariant opN :=\n| Opack of wsize & pelem (* Pack words of size pelem into one word of wsize *)\n| Ocombine_flags of combine_flags\n.\n\nScheme Equality for sop1.\n(* Definition sop1_beq : sop1 -> sop1 -> bool *)\n\nLemma sop1_eq_axiom : Equality.axiom sop1_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_sop1_dec_bl.\n  by apply: internal_sop1_dec_lb.\nQed.\n\nDefinition sop1_eqMixin     := Equality.Mixin sop1_eq_axiom.\nCanonical  sop1_eqType      := Eval hnf in EqType sop1 sop1_eqMixin.\n\nScheme Equality for sop2.\n(* Definition sop2_beq : sop2 -> sop2 -> bool *)\n\nLemma sop2_eq_axiom : Equality.axiom sop2_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_sop2_dec_bl.\n  by apply: internal_sop2_dec_lb.\nQed.\n\nDefinition sop2_eqMixin     := Equality.Mixin sop2_eq_axiom.\nCanonical  sop2_eqType      := Eval hnf in EqType sop2 sop2_eqMixin.\n\nScheme Equality for opN.\n\nLemma opN_eq_axiom : Equality.axiom opN_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_opN_dec_bl.\n  by apply: internal_opN_dec_lb.\nQed.\n\nDefinition opN_eqMixin     := Equality.Mixin opN_eq_axiom.\nCanonical  opN_eqType      := Eval hnf in EqType opN opN_eqMixin.\n\n(* ----------------------------------------------------------------------------- *)\n\n(* Type of unany operators: input, output *)\nDefinition type_of_op1 (o: sop1) : stype * stype :=\n  match o with\n  | Oword_of_int sz => (sint, sword sz)\n  | Oint_of_word sz => (sword sz, sint)\n  | Osignext szo szi\n  | Ozeroext szo szi\n    => (sword szi, sword szo)\n  | Onot => (sbool, sbool)\n  | Olnot sz\n  | Oneg (Op_w sz)\n    => let t := sword sz in (t, t)\n  | Oneg Op_int => (sint, sint)\n  end.\n\n(* Type of binany operators: inputs, output *)\nDefinition type_of_op2 (o: sop2) : stype * stype * stype :=\n  match o with\n  | Obeq | Oand | Oor => (sbool, sbool, sbool)\n  | Oadd Op_int\n  | Omul Op_int\n  | Osub Op_int\n  | Odiv Cmp_int | Omod Cmp_int\n  | Olsl Op_int | Oasr Op_int\n    => (sint, sint, sint)\n  | Oadd (Op_w s)\n  | Omul (Op_w s)\n  | Osub (Op_w s)\n  | Odiv (Cmp_w _ s) | Omod (Cmp_w _ s)\n  | Oland s | Olor s | Olxor s | Ovadd _ s | Ovsub _ s | Ovmul _ s\n    => let t := sword s in (t, t, t)\n  | Olsr s | Olsl (Op_w s) | Oasr (Op_w s) | Oror s | Orol s\n  | Ovlsr _ s | Ovlsl _ s | Ovasr _ s\n    => let t := sword s in (t, sword8, t)\n  | Oeq Op_int | Oneq Op_int\n  | Olt Cmp_int | Ole Cmp_int\n  | Ogt Cmp_int | Oge Cmp_int\n    => (sint, sint, sbool)\n  | Oeq (Op_w s) | Oneq (Op_w s)\n  | Olt (Cmp_w _ s) | Ole (Cmp_w _ s)\n  | Ogt (Cmp_w _ s) | Oge (Cmp_w _ s)\n    => let t := sword s in (t, t, sbool)\n  end.\n\n(* Type of n-ary operators: inputs, output *)\n\nDefinition tin_combine_flags := [:: sbool; sbool; sbool; sbool].\n\nDefinition type_of_opN (op: opN) : seq stype * stype :=\n  match op with\n  | Opack ws p =>\n    let n := nat_of_wsize ws %/ nat_of_pelem p in\n    (nseq n sint, sword ws)\n  | Ocombine_flags c => (tin_combine_flags, sbool) \n  end.\n\n(* ** Expressions\n * -------------------------------------------------------------------- *)\n(* Used only by the ocaml compiler *)\n(** A “tag” is a non-empty type, extracted to plain OCaml [int] *)\nModule Type TAG.\n  Parameter t : Type.\n  Parameter witness : t.\nEnd TAG.\n\nModule VarInfo : TAG.\n  Definition t := positive.\n  Definition witness : t := 1%positive.\nEnd VarInfo.\n\nDefinition var_info := VarInfo.t.\nDefinition dummy_var_info : var_info := VarInfo.witness.\n\nRecord var_i := VarI {\n  v_var :> var;\n  v_info : var_info\n}.\n\nNotation vid ident :=\n  {|\n    v_var :=\n      {|\n        vtype := sword Uptr;\n        vname := ident%string;\n      |};\n    v_info := dummy_var_info;\n  |}.\n\nVariant v_scope := \n  | Slocal \n  | Sglob.\n\nScheme Equality for v_scope.\n\nLemma v_scope_eq_axiom : Equality.axiom v_scope_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_v_scope_dec_bl.\n  by apply: internal_v_scope_dec_lb.\nQed.\n\nDefinition v_scope_eqMixin     := Equality.Mixin v_scope_eq_axiom.\nCanonical  v_scope_eqType      := Eval hnf in EqType v_scope v_scope_eqMixin.\n\nRecord gvar := Gvar { gv : var_i; gs : v_scope }.\n\nDefinition mk_gvar x := {| gv := x; gs := Sglob  |}.\nDefinition mk_lvar x := {| gv := x; gs := Slocal |}.\n\nDefinition is_lvar (x:gvar) := x.(gs) == Slocal.\nDefinition is_glob (x:gvar) := x.(gs) == Sglob.\n\nInductive pexpr : Type :=\n| Pconst :> Z -> pexpr\n| Pbool  :> bool -> pexpr\n| Parr_init : positive → pexpr\n| Pvar   :> gvar -> pexpr\n| Pget   : arr_access -> wsize -> gvar -> pexpr -> pexpr\n| Psub   : arr_access -> wsize -> positive -> gvar -> pexpr -> pexpr \n| Pload  : wsize -> var_i -> pexpr -> pexpr\n| Papp1  : sop1 -> pexpr -> pexpr\n| Papp2  : sop2 -> pexpr -> pexpr -> pexpr\n| PappN of opN & seq pexpr\n| Pif    : stype -> pexpr -> pexpr -> pexpr -> pexpr.\n\nNotation pexprs := (seq pexpr).\n\nDefinition Plvar x := Pvar (mk_lvar x).\n\nDefinition enot e := Papp1 Onot e.\nDefinition eor e1 e2 := Papp2 Oor e1 e2.\nDefinition eand e1 e2 := Papp2 Oand e1 e2.\nDefinition eeq e1 e2 := Papp2 Obeq e1 e2.\nDefinition eneq e1 e2 := enot (eeq e1 e2).\n\n(* ** Left values\n * -------------------------------------------------------------------- *)\n\nVariant lval : Type :=\n| Lnone `(var_info) `(stype)\n| Lvar  `(var_i)\n| Lmem  `(wsize) `(var_i) `(pexpr)\n| Laset `(arr_access) `(wsize) `(var_i) `(pexpr)\n| Lasub `(arr_access) `(wsize) `(positive) `(var_i) `(pexpr).\n\nCoercion Lvar : var_i >-> lval.\n\nNotation lvals := (seq lval).\n\nDefinition get_pvar (e: pexpr) : exec var :=\n  if e is Pvar {| gv := x ; gs := Slocal |} then ok (v_var x) else type_error.\n\nDefinition get_lvar (x: lval) : exec var :=\n  if x is Lvar x then ok (v_var x) else type_error.\n\n(* ** Instructions\n * -------------------------------------------------------------------- *)\n\nVariant dir := UpTo | DownTo.\n\nScheme Equality for dir.\n\nLemma dir_eq_axiom : Equality.axiom dir_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_dir_dec_bl.\n  by apply: internal_dir_dec_lb.\nQed.\n\nDefinition dir_eqMixin     := Equality.Mixin dir_eq_axiom.\nCanonical  dir_eqType      := Eval hnf in EqType dir dir_eqMixin.\n\nDefinition range := (dir * pexpr * pexpr)%type.\n\nDefinition wrange d (n1 n2 : Z) :=\n  let n := Z.to_nat (n2 - n1) in\n  match d with\n  | UpTo   => [seq (Z.add n1 (Z.of_nat i)) | i <- iota 0 n]\n  | DownTo => [seq (Z.sub n2 (Z.of_nat i)) | i <- iota 0 n]\n  end.\n\nModule InstrInfo : TAG.\n  Definition t := positive.\n  Definition witness : t := 1%positive.\nEnd InstrInfo.\n\nDefinition instr_info := InstrInfo.t.\nDefinition dummy_instr_info : instr_info := InstrInfo.witness.\n\nVariant assgn_tag :=\n  | AT_none       (* assignment introduced by the developer that can be removed *)\n  | AT_keep       (* assignment that should be kept by the compiler *)\n  | AT_rename     (* equality constraint introduced by inline, used in reg-alloc\n                     and compiled to no-op *)\n  | AT_inline     (* assignment to be propagated and removed later : introduced\n                     by unrolling, inlining or lowering *)\n  | AT_phinode    (* renaming during SSA transformation *)\n  .\n\nScheme Equality for assgn_tag.\n\nLemma assgn_tag_eq_axiom : Equality.axiom assgn_tag_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_assgn_tag_dec_bl.\n  by apply: internal_assgn_tag_dec_lb.\nQed.\n\nDefinition assgn_tag_eqMixin     := Equality.Mixin assgn_tag_eq_axiom.\nCanonical  assgn_tag_eqType      := Eval hnf in EqType assgn_tag assgn_tag_eqMixin.\n\n(* -------------------------------------------------------------------- *)\n\nVariant inline_info :=\n  | InlineFun\n  | DoNotInline.\n\nScheme Equality for inline_info.\n\nLemma inline_info_eq_axiom : Equality.axiom inline_info_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_inline_info_dec_bl.\n  by apply: internal_inline_info_dec_lb.\nQed.\n\nDefinition inline_info_eqMixin     := Equality.Mixin inline_info_eq_axiom.\nCanonical  inline_info_eqType      := Eval hnf in EqType inline_info inline_info_eqMixin.\n\n(* -------------------------------------------------------------------- *)\n\nVariant align :=\n  | Align\n  | NoAlign.\n\nScheme Equality for align.\n\nLemma align_eq_axiom : Equality.axiom align_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_align_dec_bl.\n  by apply: internal_align_dec_lb.\nQed.\n\nDefinition align_eqMixin     := Equality.Mixin align_eq_axiom.\nCanonical  align_eqType      := Eval hnf in EqType align align_eqMixin.\n\n(* -------------------------------------------------------------------- *)\n\n(* ----------------------------------------------------------------------------- *)\n\nSection ASM_OP.\n\nContext `{asmop:asmOp}.\n\nInductive instr_r :=\n| Cassgn   : lval -> assgn_tag -> stype -> pexpr -> instr_r\n| Copn     : lvals -> assgn_tag -> sopn -> pexprs -> instr_r\n| Csyscall : lvals -> syscall_t -> pexprs -> instr_r \n| Cif      : pexpr -> seq instr -> seq instr  -> instr_r\n| Cfor     : var_i -> range -> seq instr -> instr_r\n| Cwhile   : align -> seq instr -> pexpr -> seq instr -> instr_r\n| Ccall    : inline_info -> lvals -> funname -> pexprs -> instr_r\n\nwith instr := MkI : instr_info -> instr_r ->  instr.\n\nEnd ASM_OP.\n\nNotation cmd := (seq instr).\n\nSection CMD_RECT.\n\n  Context `{asmop:asmOp}.\n\n  Variables (Pr:instr_r -> Type) (Pi:instr -> Type) (Pc : cmd -> Type).\n  Hypothesis Hmk  : forall i ii, Pr i -> Pi (MkI ii i).\n  Hypothesis Hnil : Pc [::].\n  Hypothesis Hcons: forall i c, Pi i -> Pc c -> Pc (i::c).\n  Hypothesis Hasgn: forall x tg ty e, Pr (Cassgn x tg ty e).\n  Hypothesis Hopn : forall xs t o es, Pr (Copn xs t o es).\n  Hypothesis Hsyscall : forall xs o es, Pr (Csyscall xs o es).\n  Hypothesis Hif  : forall e c1 c2, Pc c1 -> Pc c2 -> Pr (Cif e c1 c2).\n  Hypothesis Hfor : forall v dir lo hi c, Pc c -> Pr (Cfor v (dir,lo,hi) c).\n  Hypothesis Hwhile : forall a c e c', Pc c -> Pc c' -> Pr (Cwhile a c e c').\n  Hypothesis Hcall: forall i xs f es, Pr (Ccall i xs f es).\n\n  Section C.\n  Variable instr_rect : forall i, Pi i.\n\n  Fixpoint cmd_rect_aux (c:cmd) : Pc c :=\n    match c return Pc c with\n    | [::] => Hnil\n    | i::c => @Hcons i c (instr_rect i) (cmd_rect_aux c)\n    end.\n  End C.\n\n  Fixpoint instr_Rect (i:instr) : Pi i :=\n    match i return Pi i with\n    | MkI ii i => @Hmk i ii (instr_r_Rect i)\n    end\n  with instr_r_Rect (i:instr_r) : Pr i :=\n    match i return Pr i with\n    | Cassgn x tg ty e => Hasgn x tg ty e\n    | Copn xs t o es => Hopn xs t o es\n    | Csyscall xs o es => Hsyscall xs o es\n    | Cif e c1 c2  => @Hif e c1 c2 (cmd_rect_aux instr_Rect c1) (cmd_rect_aux instr_Rect c2)\n    | Cfor i (dir,lo,hi) c => @Hfor i dir lo hi c (cmd_rect_aux instr_Rect c)\n    | Cwhile a c e c'   => @Hwhile a c e c' (cmd_rect_aux instr_Rect c) (cmd_rect_aux instr_Rect c')\n    | Ccall ii xs f es => @Hcall ii xs f es\n    end.\n\n  Definition cmd_rect := cmd_rect_aux instr_Rect.\n\nEnd CMD_RECT.\n\nModule FunInfo : TAG.\n  Definition t := positive.\n  Definition witness : t := 1%positive.\nEnd FunInfo.\n\nSection ASM_OP.\n\nContext `{asmop:asmOp}.\n\n(* ** Functions\n * -------------------------------------------------------------------- *)\n\nDefinition fun_info := FunInfo.t.\n\nClass progT (eft:eqType) := {\n  extra_prog_t : Type;\n  extra_val_t  : Type;\n}.\n\nDefinition extra_fun_t {eft} {pT: progT eft} := eft.\n\nRecord _fundef (extra_fun_t: Type) := MkFun {\n  f_info   : fun_info;\n  f_tyin   : seq stype;\n  f_params : seq var_i;\n  f_body   : cmd;\n  f_tyout  : seq stype;\n  f_res    : seq var_i;\n  f_extra  : extra_fun_t;\n}.\n\nDefinition _fun_decl (extra_fun_t: Type) := (funname * _fundef extra_fun_t)%type.\n\nRecord _prog (extra_fun_t: Type) (extra_prog_t: Type):= {\n  p_funcs : seq (_fun_decl extra_fun_t);\n  p_globs : glob_decls;\n  p_extra : extra_prog_t;\n}.\n\nSection PROG.\n\nContext {eft} {pT:progT eft}.\n\nDefinition fundef := _fundef extra_fun_t.\n\nDefinition function_signature : Type :=\n  (seq stype * seq stype).\n\nDefinition signature_of_fundef (fd: fundef) : function_signature :=\n  (f_tyin fd, f_tyout fd).\n\nDefinition fun_decl := (funname * fundef)%type.\n\nDefinition prog := _prog extra_fun_t extra_prog_t.\n\nDefinition Build_prog p_funcs p_globs p_extra : prog := Build__prog p_funcs p_globs p_extra.\n\nEnd PROG.\n\nEnd ASM_OP.\n\nNotation fun_decls  := (seq fun_decl).\n\nSection ASM_OP.\n\nContext {pd: PointerData}.\nContext `{asmop:asmOp}.\n\n(* ** Programs before stack/memory allocation \n * -------------------------------------------------------------------- *)\n\nDefinition progUnit : progT [eqType of unit] :=\n  {| extra_val_t := unit;\n     extra_prog_t := unit;\n  |}.\n\nDefinition ufundef     := @fundef _ _ _ progUnit.\nDefinition ufun_decl   := @fun_decl _ _ _ progUnit.\nDefinition ufun_decls  := seq (@fun_decl _ _ _ progUnit).\nDefinition uprog       := @prog _ _ _ progUnit.\n\n(* For extraction *)\nDefinition _ufundef    := _fundef unit. \nDefinition _ufun_decl  := _fun_decl unit.\nDefinition _ufun_decls :=  seq (_fun_decl unit).\nDefinition _uprog      := _prog unit unit. \nDefinition to_uprog (p:_uprog) : uprog := p.\n\n(* ** Programs after stack/memory allocation \n * -------------------------------------------------------------------- *)\n\nVariant saved_stack :=\n| SavedStackNone\n| SavedStackReg of var\n| SavedStackStk of Z.\n\nDefinition saved_stack_beq (x y : saved_stack) :=\n  match x, y with\n  | SavedStackNone, SavedStackNone => true\n  | SavedStackReg v1, SavedStackReg v2 => v1 == v2\n  | SavedStackStk z1, SavedStackStk z2 => z1 == z2\n  | _, _ => false\n  end.\n\nLemma saved_stack_eq_axiom : Equality.axiom saved_stack_beq.\nProof.\n  move=> [ | v1 | z1] [ | v2 | z2] /=; try by constructor.\n  + by apply (iffP eqP); congruence.\n  by apply (iffP eqP); congruence.\nQed.\n\nDefinition saved_stack_eqMixin   := Equality.Mixin saved_stack_eq_axiom.\nCanonical  saved_stack_eqType    := Eval hnf in EqType saved_stack saved_stack_eqMixin.\n\nVariant return_address_location :=\n| RAnone\n| RAreg of var               (* The return address is pass by a register and \n                                keeped in this register during function call *)\n| RAstack of option var & Z. (* None means that the call instruction directly store ra on the stack \n                                Some r means that the call instruction directly store ra on r and \n                                the function should store r on the stack *)\n\nDefinition return_address_location_beq (r1 r2: return_address_location) : bool :=\n  match r1 with\n  | RAnone => if r2 is RAnone then true else false\n  | RAreg x1 => if r2 is RAreg x2 then x1 == x2 else false\n  | RAstack lr1 z1 => if r2 is RAstack lr2 z2 then (lr1 == lr2) && (z1 == z2) else false\n  end.\n\nLemma return_address_location_eq_axiom : Equality.axiom return_address_location_beq.\nProof.\n  case => [ | x1 | lr1 z1 ] [ | x2 | lr2 z2 ] /=; try by constructor.\n  + by apply (iffP eqP); congruence.\n  by apply (iffP andP) => [ []/eqP-> /eqP-> | []-> ->].\nQed.\n\nDefinition return_address_location_eqMixin := Equality.Mixin return_address_location_eq_axiom.\nCanonical  return_address_location_eqType  := Eval hnf in EqType return_address_location return_address_location_eqMixin.\n\nRecord stk_fun_extra := MkSFun {\n  sf_align          : wsize;\n  sf_stk_sz         : Z;\n  sf_stk_ioff       : Z;\n  sf_stk_extra_sz   : Z;\n  sf_stk_max        : Z;\n  sf_max_call_depth : Z;\n  sf_to_save        : seq (var * Z);\n  sf_save_stack     : saved_stack;\n  sf_return_address : return_address_location;\n}.\n\nDefinition sfe_beq (e1 e2: stk_fun_extra) : bool :=\n  (e1.(sf_align) == e2.(sf_align)) &&\n  (e1.(sf_stk_sz) == e2.(sf_stk_sz)) &&\n  (e1.(sf_stk_ioff) == e2.(sf_stk_ioff)) &&\n  (e1.(sf_stk_max) == e2.(sf_stk_max)) &&\n  (e1.(sf_max_call_depth) == e2.(sf_max_call_depth)) &&\n  (e1.(sf_stk_extra_sz) == e2.(sf_stk_extra_sz)) &&\n  (e1.(sf_to_save) == e2.(sf_to_save)) &&\n  (e1.(sf_save_stack) == e2.(sf_save_stack)) &&\n  (e1.(sf_return_address) == e2.(sf_return_address)).\n\nLemma sfe_eq_axiom : Equality.axiom sfe_beq.\nProof.\n  case => a b c d e f g h i [] a' b' c' d' e' f' g' h' i'; apply: (equivP andP) => /=; split.\n  + by case => /andP[] /andP[] /andP[] /andP[] /andP[] /andP[] /andP[] /eqP <- /eqP <- /eqP <- /eqP <- /eqP <- /eqP <- /eqP <- /eqP <- /eqP <-.\n  by case => <- <- <- <- <- <- <- <- <-; rewrite !eqxx.\nQed.\n\nDefinition sfe_eqMixin   := Equality.Mixin sfe_eq_axiom.\nCanonical  sfe_eqType    := Eval hnf in EqType stk_fun_extra sfe_eqMixin.\n\nRecord sprog_extra := {\n  sp_rsp   : Ident.ident;\n  sp_rip   : Ident.ident;\n  sp_globs : seq u8;\n}.\n\nDefinition progStack : progT [eqType of stk_fun_extra] := \n  {| extra_val_t := pointer;\n     extra_prog_t := sprog_extra  |}.\n\nDefinition sfundef     := @fundef _ _ _ progStack.\nDefinition sfun_decl   := @fun_decl _ _ _ progStack.\nDefinition sfun_decls  := seq (@fun_decl _ _ _ progStack).\nDefinition sprog       := @prog _ _ _ progStack.\n\n(* For extraction *)\n\nDefinition _sfundef    := _fundef stk_fun_extra.\nDefinition _sfun_decl  := _fun_decl stk_fun_extra. \nDefinition _sfun_decls := seq (_fun_decl stk_fun_extra).\nDefinition _sprog      := _prog stk_fun_extra sprog_extra.\nDefinition to_sprog (p:_sprog) : sprog := p.\n\n(* Update functions *)\nDefinition with_body eft (fd:_fundef eft) body := {|\n  f_info   := fd.(f_info);\n  f_tyin   := fd.(f_tyin);\n  f_params := fd.(f_params);\n  f_body   := body;\n  f_tyout  := fd.(f_tyout);\n  f_res    := fd.(f_res);\n  f_extra  := fd.(f_extra);\n|}.\n\nDefinition swith_extra {_: PointerData} (fd:ufundef) f_extra : sfundef := {|\n  f_info   := fd.(f_info);\n  f_tyin   := fd.(f_tyin);\n  f_params := fd.(f_params);\n  f_body   := fd.(f_body);\n  f_tyout  := fd.(f_tyout);\n  f_res    := fd.(f_res);\n  f_extra  := f_extra;\n|}.\n\nEnd ASM_OP.\n\nSection ASM_OP.\n\nContext `{asmop:asmOp}.\nContext {eft} {pT : progT eft}.\n\n(* ** Some smart constructors\n * -------------------------------------------------------------------------- *)\n\nDefinition is_const (e:pexpr) :=\n  match e with\n  | Pconst n => Some n\n  | _        => None\n  end.\n\nDefinition is_bool (e:pexpr) :=\n  match e with\n  | Pbool b => Some b\n  | _ => None\n  end.\n\nFixpoint cast_w ws (e: pexpr) : pexpr :=\n  match e with\n  | Papp2 (Oadd Op_int) e1 e2 =>\n      let: e1 := cast_w ws e1 in\n      let: e2 := cast_w ws e2 in\n      Papp2 (Oadd (Op_w ws)) e1 e2\n  | Papp2 (Osub Op_int) e1 e2 =>\n      let: e1 := cast_w ws e1 in\n      let: e2 := cast_w ws e2 in\n      Papp2 (Osub (Op_w ws)) e1 e2\n  | Papp2 (Omul Op_int) e1 e2 =>\n      let: e1 := cast_w ws e1 in\n      let: e2 := cast_w ws e2 in\n      Papp2 (Omul (Op_w ws)) e1 e2\n  | Papp1 (Oneg Op_int) e' =>\n      let: e' := cast_w ws e' in\n      Papp1 (Oneg (Op_w ws)) e'\n  | Papp1 (Oint_of_word ws') e' =>\n      if (ws ≤ ws')%CMP then e'\n      else Papp1 (Oword_of_int ws) e\n  | _ => Papp1 (Oword_of_int ws) e\n  end.\n\nSection WITH_POINTER_DATA.\nContext {pd: PointerData}.\n\nDefinition cast_ptr := cast_w Uptr.\n\nDefinition cast_const z := cast_ptr (Pconst z).\n\nEnd WITH_POINTER_DATA.\n\nDefinition eword_of_int (ws : wsize) (x : Z) : pexpr :=\n  Papp1 (Oword_of_int ws) (Pconst x).\n\nDefinition wconst (sz: wsize) (n: word sz) : pexpr :=\n  Papp1 (Oword_of_int sz) (Pconst (wunsigned n)).\n\nDefinition is_wconst (sz: wsize) (e: pexpr) : option (word sz) :=\n  match e with\n  | Papp1 (Oword_of_int sz') e =>\n    if (sz <= sz')%CMP then\n      is_const e >>= λ n, Some (zero_extend sz (wrepr sz' n))\n    else None\n  | _       => None\n  end%O.\n\nDefinition is_wconst_of_size sz (e: pexpr) : option Z :=\n  match e with\n  | Papp1 (Oword_of_int sz') (Pconst z) =>\n    if sz' == sz then Some z else None\n  | _ => None end.\n\n(* ** Compute written variables\n * -------------------------------------------------------------------- *)\n\nDefinition vrv_rec (s:Sv.t) (rv:lval) :=\n  match rv with\n  | Lnone _ _  => s\n  | Lvar  x    => Sv.add x s\n  | Lmem _ _ _  => s\n  | Laset _ _ x _  => Sv.add x s\n  | Lasub _ _ _ x _ => Sv.add x s\n  end.\n\nDefinition vrvs_rec s (rv:lvals) := foldl vrv_rec s rv.\n\nDefinition vrv := (vrv_rec Sv.empty).\nDefinition vrvs := (vrvs_rec Sv.empty).\n\nDefinition lv_write_mem (r:lval) : bool :=\n  if r is Lmem _ _ _ then true else false.\n\nFixpoint write_i_rec s (i:instr_r) :=\n  match i with\n  | Cassgn x _ _ _  => vrv_rec s x\n  | Copn xs _ _ _   => vrvs_rec s xs\n  | Csyscall xs _ _ => vrvs_rec s xs \n  | Cif   _ c1 c2   => foldl write_I_rec (foldl write_I_rec s c2) c1\n  | Cfor  x _ c     => foldl write_I_rec (Sv.add x s) c\n  | Cwhile _ c _ c' => foldl write_I_rec (foldl write_I_rec s c') c\n  | Ccall _ x _ _   => vrvs_rec s x\n  end\nwith write_I_rec s i :=\n  match i with\n  | MkI _ i => write_i_rec s i\n  end.\n\nDefinition write_i i := write_i_rec Sv.empty i.\n\nDefinition write_I i := write_I_rec Sv.empty i.\n\nDefinition write_c_rec s c := foldl write_I_rec s c.\n\nDefinition write_c c := write_c_rec Sv.empty c.\n\n(* ** Compute read variables\n * -------------------------------------------------------------------- *)\n\nDefinition read_gvar (x:gvar) := \n  if is_lvar x then Sv.singleton x.(gv)\n  else Sv.empty.\n\nFixpoint read_e_rec (s:Sv.t) (e:pexpr) : Sv.t :=\n  match e with\n  | Pconst _\n  | Pbool  _\n  | Parr_init _    => s\n  | Pvar   x       => Sv.union (read_gvar x) s\n  | Pget _ _ x e   => read_e_rec (Sv.union (read_gvar x) s) e\n  | Psub _ _ _ x e => read_e_rec (Sv.union (read_gvar x) s) e\n  | Pload _ x e    => read_e_rec (Sv.add x s) e\n  | Papp1  _ e     => read_e_rec s e\n  | Papp2  _ e1 e2 => read_e_rec (read_e_rec s e2) e1\n  | PappN _ es     => foldl read_e_rec s es\n  | Pif  _ t e1 e2 => read_e_rec (read_e_rec (read_e_rec s e2) e1) t\n  end.\n\nDefinition read_e := read_e_rec Sv.empty.\nDefinition read_es_rec := foldl read_e_rec.\nDefinition read_es := read_es_rec Sv.empty.\n\nDefinition read_rv_rec  (s:Sv.t) (r:lval) :=\n  match r with\n  | Lnone _ _     => s\n  | Lvar  _       => s\n  | Lmem _ x e    => read_e_rec (Sv.add x s) e\n  | Laset _ _ x e => read_e_rec (Sv.add x s) e\n  | Lasub _ _ _ x e => read_e_rec (Sv.add x s) e\n  end.\n\nDefinition read_rv := read_rv_rec Sv.empty.\nDefinition read_rvs_rec := foldl read_rv_rec.\nDefinition read_rvs := read_rvs_rec Sv.empty.\n\nFixpoint read_i_rec (s:Sv.t) (i:instr_r) : Sv.t :=\n  match i with\n  | Cassgn x _ _ e => read_rv_rec (read_e_rec s e) x\n  | Copn xs _ _ es => read_es_rec (read_rvs_rec s xs) es\n  | Csyscall xs _ es => read_es_rec (read_rvs_rec s xs) es\n  | Cif b c1 c2 =>\n    let s := foldl read_I_rec s c1 in\n    let s := foldl read_I_rec s c2 in\n    read_e_rec s b\n  | Cfor x (dir, e1, e2) c =>\n    let s := foldl read_I_rec s c in\n    read_e_rec (read_e_rec s e2) e1\n  | Cwhile a c e c' =>\n    let s := foldl read_I_rec s c in\n    let s := foldl read_I_rec s c' in\n    read_e_rec s e\n  | Ccall _ xs _ es => read_es_rec (read_rvs_rec s xs) es\n  end\nwith read_I_rec (s:Sv.t) (i:instr) : Sv.t :=\n  match i with\n  | MkI _ i => read_i_rec s i\n  end.\n\nDefinition read_c_rec := foldl read_I_rec.\n\nDefinition read_i := read_i_rec Sv.empty.\n\nDefinition read_I := read_I_rec Sv.empty.\n\nDefinition read_c := read_c_rec Sv.empty.\n\n(* ** Compute occurring variables (= read + write)\n * -------------------------------------------------------------------------- *)\n\nDefinition vars_I (i: instr) := Sv.union (read_I i) (write_I i).\n\nDefinition vars_c c := Sv.union (read_c c) (write_c c).\n\nDefinition vars_lval l := Sv.union (read_rv l) (vrv l).\n\nDefinition vars_lvals ls := Sv.union (read_rvs ls) (vrvs ls).\n\nFixpoint vars_l (l: seq var_i) :=\n  match l with\n  | [::] => Sv.empty\n  | h :: q => Sv.add h (vars_l q)\n  end.\n\nDefinition vars_fd (fd:fundef) :=\n  Sv.union (vars_l fd.(f_params)) (Sv.union (vars_l fd.(f_res)) (vars_c fd.(f_body))).\n\nDefinition vars_p (p: fun_decls) :=\n  foldr (fun f x => let '(fn, fd) := f in Sv.union x (vars_fd fd)) Sv.empty p.\n\nEnd ASM_OP.\n\n(* --------------------------------------------------------------------- *)\n(* Test the equality of two expressions modulo variable info             *)\n\nDefinition eq_gvar x x' := \n  (x.(gs) == x'.(gs)) && (v_var x.(gv) == v_var x'.(gv)).\n\nFixpoint eq_expr e e' :=\n  match e, e' with\n  | Pconst z      , Pconst z'         => z == z'\n  | Pbool  b      , Pbool  b'         => b == b'\n  | Parr_init n   , Parr_init n'      => n == n'\n  | Pvar   x      , Pvar   x'         => eq_gvar x x'\n  | Pget aa w x e , Pget aa' w' x' e' => (aa==aa') && (w == w') && (eq_gvar x x') && eq_expr e e'\n  | Psub aa w len x e , Psub aa' w' len' x' e' => (aa==aa') && (w == w') && (len == len') && (eq_gvar x x') && eq_expr e e'\n  | Pload w x e, Pload w' x' e' => (w == w') && (v_var x == v_var x') && eq_expr e e'\n  | Papp1  o e    , Papp1  o' e'      => (o == o') && eq_expr e e'\n  | Papp2  o e1 e2, Papp2  o' e1' e2' => (o == o') && eq_expr e1 e1' && eq_expr e2 e2'\n  | PappN o es, PappN o' es' => (o == o') && (all2 eq_expr es es')\n  | Pif t e e1 e2, Pif t' e' e1' e2' =>\n    (t == t') && eq_expr e e' && eq_expr e1 e1' && eq_expr e2 e2'\n  | _             , _                 => false\n  end.\n\n(* ------------------------------------------------------------------- *)\nDefinition to_lvals (l:seq var) : seq lval := \n  map (fun x => Lvar {|v_var := x; v_info := dummy_var_info |}) l.\n\n(* ------------------------------------------------------------------- *)\nDefinition is_false (e: pexpr) : bool :=\n  if e is Pbool false then true else false.\n\nDefinition is_zero sz (e: pexpr) : bool :=\n  if e is Papp1 (Oword_of_int sz') (Pconst Z0) then sz' == sz else false.\n\nNotation copn_args := (seq lval * sopn * seq pexpr)%type (only parsing).\n", "meta": {"author": "jasmin-lang", "repo": "jasmin", "sha": "3c783b662000c371ba924a953d444fd80b860d9f", "save_path": "github-repos/coq/jasmin-lang-jasmin", "path": "github-repos/coq/jasmin-lang-jasmin/jasmin-3c783b662000c371ba924a953d444fd80b860d9f/proofs/lang/expr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.21082728440158927}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Compile-time evaluation of initializers for global C variables. *)\n\nRequire Import Coqlib Maps Errors.\nRequire Import Integers Floats Values AST Memory Globalenvs.\nRequire Import Ctypes Cop Csyntax.\n\nOpen Scope error_monad_scope.\n\n(** * Evaluation of compile-time constant expressions *)\n\n(** To evaluate constant expressions at compile-time, we use the same [value]\n  type and the same [sem_*] functions that are used in CompCert C's semantics\n  (module [Csem]).  However, we interpret pointer values symbolically:\n  [Vptr id ofs] represents the address of global variable [id]\n  plus byte offset [ofs]. *)\n\n(** [constval a] evaluates the constant expression [a].\n\nIf [a] is a r-value, the returned value denotes:\n- [Vint n], [Vlong n], [Vfloat f], [Vsingle f]: the corresponding number\n- [Vptr id ofs]: address of global variable [id] plus byte offset [ofs]\n- [Vundef]: erroneous expression\n\nIf [a] is a l-value, the returned value denotes:\n- [Vptr id ofs]: global variable [id] plus byte offset [ofs]\n*)\n\nDefinition do_cast (v: val) (t1 t2: type) : res val :=\n  match sem_cast v t1 t2 Mem.empty with\n  | Some v' => OK v'\n  | None => Error(msg \"undefined cast\")\n  end.\n\nDefinition lookup_composite (ce: composite_env) (id: ident) : res composite :=\n  match ce!id with\n  | Some co => OK co\n  | None => Error (MSG \"Undefined struct or union \" :: CTX id :: nil)\n  end.\n\nFixpoint constval (ce: composite_env) (a: expr) : res val :=\n  match a with\n  | Eval v ty =>\n      match v with\n      | Vint _ | Vfloat _ | Vsingle _ | Vlong _ => OK v\n      | Vptr _ _ | Vundef => Error(msg \"illegal constant\")\n      end\n  | Evalof l ty =>\n      match access_mode ty with\n      | By_reference | By_copy => constval ce l\n      | _ => Error(msg \"dereferencing of an l-value\")\n      end\n  | Eaddrof l ty =>\n      constval ce l\n  | Eunop op r1 ty =>\n      do v1 <- constval ce r1;\n      match sem_unary_operation op v1 (typeof r1) Mem.empty with\n      | Some v => OK v\n      | None => Error(msg \"undefined unary operation\")\n      end\n  | Ebinop op r1 r2 ty =>\n      do v1 <- constval ce r1;\n      do v2 <- constval ce r2;\n      match sem_binary_operation ce op v1 (typeof r1) v2 (typeof r2) Mem.empty with\n      | Some v => OK v\n      | None => Error(msg \"undefined binary operation\")\n      end\n  | Ecast r ty =>\n      do v1 <- constval ce r; do_cast v1 (typeof r) ty\n  | Esizeof ty1 ty =>\n      OK (Vptrofs (Ptrofs.repr (sizeof ce ty1)))\n  | Ealignof ty1 ty =>\n      OK (Vptrofs (Ptrofs.repr (alignof ce ty1)))\n  | Eseqand r1 r2 ty =>\n      do v1 <- constval ce r1;\n      do v2 <- constval ce r2;\n      match bool_val v1 (typeof r1) Mem.empty with\n      | Some true => do_cast v2 (typeof r2) type_bool\n      | Some false => OK (Vint Int.zero)\n      | None => Error(msg \"undefined && operation\")\n      end\n  | Eseqor r1 r2 ty =>\n      do v1 <- constval ce r1;\n      do v2 <- constval ce r2;\n      match bool_val v1 (typeof r1) Mem.empty with\n      | Some false => do_cast v2 (typeof r2) type_bool\n      | Some true => OK (Vint Int.one)\n      | None => Error(msg \"undefined || operation\")\n      end\n  | Econdition r1 r2 r3 ty =>\n      do v1 <- constval ce r1;\n      do v2 <- constval ce r2;\n      do v3 <- constval ce r3;\n      match bool_val v1 (typeof r1) Mem.empty with\n      | Some true => do_cast v2 (typeof r2) ty\n      | Some false => do_cast v3 (typeof r3) ty\n      | None => Error(msg \"condition is undefined\")\n      end\n  | Ecomma r1 r2 ty =>\n      do v1 <- constval ce r1; constval ce r2\n  | Evar x ty =>\n      OK(Vptr x Ptrofs.zero)\n  | Ederef r ty =>\n      constval ce r\n  | Efield l f ty =>\n      do (delta, bf) <-\n        match typeof l with\n        | Tstruct id _ =>\n            do co <- lookup_composite ce id; field_offset ce f (co_members co)\n        | Tunion id _ =>\n            do co <- lookup_composite ce id; union_field_offset ce f (co_members co)\n        | _ =>\n            Error (msg \"ill-typed field access\")\n        end;\n      do v <- constval ce l;\n      match bf with\n      | Full =>\n          OK (if Archi.ptr64\n              then Val.addl v (Vlong (Int64.repr delta))\n              else Val.add v (Vint (Int.repr delta)))\n      | Bits _ _ _ _ =>\n          Error(msg \"taking the address of a bitfield\")\n      end\n  | Eparen r tycast ty =>\n      do v <- constval ce r; do_cast v (typeof r) tycast\n  | _ =>\n    Error(msg \"not a compile-time constant\")\n  end.\n\n(** [constval_cast ce a ty] evaluates [a] then converts its value to type [ty]. *)\n\nDefinition constval_cast (ce: composite_env) (a: expr) (ty: type): res val :=\n  do v <- constval ce a; do_cast v (typeof a) ty.\n\n(** * Building and recording initialization data *)\n\n(** The following [state] type is the output of the translation of\n    initializers.  It contains the list of initialization data\n    generated so far, the corresponding position in bytes, and the\n    total size expected for the final initialization data, in bytes. *)\n\nRecord state : Type := {\n  init: list init_data;      (**r reversed *)\n  curr: Z;                   (**r current position for head of [init] *)\n  total_size: Z              (**r total expected size *)\n}.\n\n(** A state [s] can also be viewed as a memory block.  The size of\n    the block is [s.(total_size)], it is initialized with zero bytes,\n    then filled with the initialization data [rev s.(init)] like\n    [Genv.store_init_data_list] does. *)\n\nDefinition initial_state (sz: Z) : state :=\n  {| init := nil; curr := 0; total_size := sz |}.\n\n(** We now define abstract \"store\" operations that operate\n    directly on the state, but whose behavior mimic those of\n    storing in the corresponding memory block.  To initialize\n    bitfields, we also need an abstract \"load\" operation.\n    The operations are optimized for stores that occur at increasing\n    positions, like those that take place during initialization. *)\n\n(** Initialization from bytes *)\n\nDefinition int_of_byte (b: byte) := Int.repr (Byte.unsigned b).\n\nDefinition Init_byte (b: byte) := Init_int8 (int_of_byte b).\n\n(** Add a list of bytes to a reversed initialization data list. *)\n\nFixpoint add_rev_bytes (l: list byte) (il: list init_data) :=\n  match l with\n  | nil => il\n  | b :: l => add_rev_bytes l (Init_byte b :: il)\n  end.\n\n(** Add [n] zero bytes to an initialization data list. *)\n\nDefinition add_zeros (n: Z) (il: list init_data) :=\n  Z.iter n (fun l => Init_int8 Int.zero :: l) il.\n\n(** Make sure the [depth] positions at the top of [il] are bytes,\n    that is, [Init_int8] items.  Other numerical items are split\n    into bytes.  [Init_addrof] items cannot be split and result in\n    an error. *)\n\nFixpoint normalize (il: list init_data) (depth: Z) : res (list init_data) :=\n  if zle depth 0 then OK il else\n    match il with\n    | nil =>\n        Error (msg \"normalize: empty list\")\n    | Init_int8 n :: il =>\n        do il' <- normalize il (depth - 1);\n        OK (Init_int8 n :: il')\n    | Init_int16 n :: il =>\n        do il' <- normalize il (depth - 2);\n        OK (add_rev_bytes (encode_int 2%nat (Int.unsigned n)) il')\n    | Init_int32 n :: il =>\n        do il' <- normalize il (depth - 4);\n        OK (add_rev_bytes (encode_int 4%nat (Int.unsigned n)) il')\n    | Init_int64 n :: il =>\n        do il' <- normalize il (depth - 8);\n        OK (add_rev_bytes (encode_int 8%nat (Int64.unsigned n)) il')\n    | Init_float32 f :: il =>\n        do il' <- normalize il (depth - 4);\n        OK (add_rev_bytes (encode_int 4%nat (Int.unsigned (Float32.to_bits f))) il')\n    | Init_float64 f :: il =>\n        do il' <- normalize il (depth - 8);\n        OK (add_rev_bytes (encode_int 8%nat (Int64.unsigned (Float.to_bits f))) il')\n    | Init_addrof _ _ :: il =>\n        Error (msg \"normalize: Init_addrof\")\n    | Init_space n :: il =>\n        let n := Z.max 0 n in\n        if zle n depth then\n          do il' <- normalize il (depth - n);\n          OK (add_zeros n il')\n        else\n          OK (add_zeros depth (Init_space (n - depth) :: il))\n    end.\n\n(** Split [il] into [depth] bytes and the initialization list that follows.\n    The bytes are returned reversed. *)\n\nFixpoint decompose_rec (accu: list byte) (il: list init_data) (depth: Z) : res (list byte * list init_data) :=\n  if zle depth 0 then OK (accu, il) else\n    match il with\n    | Init_int8 n :: il => decompose_rec (Byte.repr (Int.unsigned n) :: accu) il (depth - 1)\n    | _ => Error (msg \"decompose: wrong shape\")\n    end.\n\nDefinition decompose (il: list init_data) (depth: Z) : res (list byte * list init_data) :=\n  decompose_rec nil il depth.\n\n(** Decompose an initialization list in three parts:\n    [depth] bytes (reversed), [sz] bytes (reversed),\n    and the remainder of the initialization list. *)\n\nDefinition trisection (il: list init_data) (depth sz: Z) : res (list byte * list byte * list init_data) :=\n  do il0 <- normalize il (depth + sz);\n  do (bytes1, il1) <- decompose il0 depth;\n  do (bytes2, il2) <- decompose il1 sz;\n  OK (bytes1, bytes2, il2).\n\n(** Graphically: [rev il] is equal to\n<<\n                 <---sz---><--depth-->\n+----------------+---------+---------+\n|                |         |         |\n+----------------+---------+---------+\n    rev il2         bytes2    bytes1\n>>\n*)\n\n(** Add padding if necessary so that position [pos] is within the state. *)\n\nDefinition pad_to (s: state) (pos: Z) : state :=\n  if zle pos s.(curr)\n  then s\n  else {| init := Init_space (pos - s.(curr)) :: s.(init);\n          curr := pos;\n          total_size := s.(total_size) |}.\n\n(** Store the initialization data [i] at position [pos] in state [s]. *)\n\nDefinition store_data (s: state) (pos: Z) (i: init_data) : res state :=\n  let sz := init_data_size i in\n  assertion (zle 0 pos && zle (pos + sz) s.(total_size));\n  if zle s.(curr) pos then\n    OK {| init := i :: (if zlt s.(curr) pos\n                        then Init_space (pos - s.(curr)) :: s.(init)\n                        else s.(init));\n          curr := pos + sz;\n          total_size := s.(total_size) |}\n  else\n    let s' := pad_to s (pos + sz) in\n    do x3 <- trisection s'.(init) (s'.(curr) - (pos + sz)) sz;\n    let '(bytes1, _, il2) := x3 in\n    OK {| init := add_rev_bytes bytes1 (i :: il2);\n          curr := s'.(curr);\n          total_size := s'.(total_size) |}.\n\n(** Store the integer [n] of size [isz] at position [pos] in state [s]. *)\n\nDefinition init_data_for_carrier (isz: intsize) (n: int) :=\n  match isz with\n  | I8 | IBool => Init_int8 n\n  | I16 => Init_int16 n\n  | I32 => Init_int32 n\n  end.\n\nDefinition store_int (s: state) (pos: Z) (isz: intsize) (n: int) : res state :=\n  store_data s pos (init_data_for_carrier isz n).\n\n(** Load the integer of size [isz] at position [pos] in state [s]. *)\n\nDefinition load_int (s: state) (pos: Z) (isz: intsize) : res int :=\n  let chunk := chunk_for_carrier isz in\n  let sz := size_chunk chunk in\n  assertion (zle 0 pos && zle (pos + sz) s.(total_size));\n  let s' := pad_to s (pos + sz) in\n  do x3 <- trisection s'.(init) (s'.(curr) - (pos + sz)) sz;\n  let '(_, bytes2, _) := x3 in\n  OK (Int.repr (decode_int bytes2)).\n\n(** Extract the final initialization data from a state. *)\n\nDefinition init_data_list_of_state (s: state) : res (list init_data) :=\n  assertion (zle s.(curr) s.(total_size));\n  let s' := pad_to s s.(total_size) in\n  OK (List.rev' s'.(init)).\n\n(** * Translation of initializers *)\n\nInductive initializer :=\n  | Init_single (a: expr)\n  | Init_array (il: initializer_list)\n  | Init_struct (il: initializer_list)\n  | Init_union (f: ident) (i: initializer)\nwith initializer_list :=\n  | Init_nil\n  | Init_cons (i: initializer) (il: initializer_list).\n\nDefinition length_initializer_list (il: initializer_list) :=\n  let fix length (accu: Z) (il: initializer_list) : Z :=\n    match il with Init_nil => accu | Init_cons _ il => length (Z.succ accu) il end\n  in length 0 il.\n\n(** Translate an initializing expression [a] for a scalar variable\n  of type [ty].  Return the corresponding initialization datum. *)\n\nDefinition transl_init_single (ce: composite_env) (ty: type) (a: expr) : res init_data :=\n  do v <- constval_cast ce a ty;\n  match v, ty with\n  | Vint n, Tint (I8|IBool) sg _ => OK(Init_int8 n)\n  | Vint n, Tint I16 sg _ => OK(Init_int16 n)\n  | Vint n, Tint I32 sg _ => OK(Init_int32 n)\n  | Vint n, Tpointer _ _ => assertion (negb Archi.ptr64); OK(Init_int32 n)\n  | Vlong n, Tlong _ _ => OK(Init_int64 n)\n  | Vlong n, Tpointer _ _ => assertion (Archi.ptr64); OK(Init_int64 n)\n  | Vsingle f, Tfloat F32 _ => OK(Init_float32 f)\n  | Vfloat f, Tfloat F64 _ => OK(Init_float64 f)\n  | Vptr id ofs, Tint I32 sg _ => assertion (negb Archi.ptr64); OK(Init_addrof id ofs)\n  | Vptr id ofs, Tlong _ _ => assertion (Archi.ptr64); OK(Init_addrof id ofs)\n  | Vptr id ofs, Tpointer _ _ => OK(Init_addrof id ofs)\n  | Vundef, _ => Error(msg \"undefined operation in initializer\")\n  | _, _ => Error (msg \"type mismatch in initializer\")\n  end.\n\n(** Initialize a bitfield [Bits sz sg p w] with expression [a]. *)\n\nDefinition transl_init_bitfield (ce: composite_env) (s: state)\n                                (ty: type) (sz: intsize) (p w: Z)\n                                (i: initializer) (pos: Z) : res state :=\n  match i with\n  | Init_single a =>\n      do v <- constval_cast ce a ty;\n      match v with\n      | Vint n =>\n          do c <- load_int s pos sz;\n          let c' := Int.bitfield_insert (first_bit sz p w) w c n in\n          store_int s pos sz c'\n      | Vundef =>\n          Error (msg \"undefined operation in bitfield initializer\")\n      | _ =>\n          Error (msg \"type mismatch in bitfield initializer\")\n      end\n  | _ =>\n      Error (msg \"bitfield initialized by composite initializer\")\n  end.\n\n(** Padding bitfields and bitfields with zero width are not initialized. *)\n\nDefinition member_not_initialized (m: member) : bool :=\n  match m with\n  | Member_plain _ _ => false\n  | Member_bitfield _ _ _ _ w p => p || zle w 0\n  end.\n\n(** Translate an initializer [i] for a variable of type [ty]\n    and store the corresponding list of initialization data in state [s]\n    at position [pos].  Return the updated state. *)\n\nFixpoint transl_init_rec (ce: composite_env) (s: state)\n                         (ty: type) (i: initializer) (pos: Z)\n                         {struct i} : res state :=\n  match i, ty with\n  | Init_single a, _ =>\n      do d <- transl_init_single ce ty a; store_data s pos d\n  | Init_array il, Tarray tyelt nelt _ =>\n      assertion (zle (length_initializer_list il) (Z.max 0 nelt));\n      transl_init_array ce s tyelt il pos\n  | Init_struct il, Tstruct id _ =>\n      do co <- lookup_composite ce id;\n      match co_su co with\n      | Struct => transl_init_struct ce s (co_members co) il pos 0\n      | Union  => Error (MSG \"struct/union mismatch on \" :: CTX id :: nil)\n      end\n  | Init_union f i1, Tunion id _ =>\n      do co <- lookup_composite ce id;\n      match co_su co with\n      | Struct => Error (MSG \"union/struct mismatch on \" :: CTX id :: nil)\n      | Union =>  do ty1 <- field_type f (co_members co);\n                  do (delta, layout) <- union_field_offset ce f (co_members co);\n                  match layout with\n                  | Full =>\n                      transl_init_rec ce s ty1 i1 (pos + delta)\n                  | Bits sz sg p w =>\n                      transl_init_bitfield ce s ty1 sz p w i1 (pos + delta)\n                  end\n      end\n  | _, _ =>\n      Error (msg \"wrong type for compound initializer\")\n  end\n\nwith transl_init_array (ce: composite_env) (s: state)\n                       (tyelt: type) (il: initializer_list) (pos: Z)\n                       {struct il} : res state :=\n  match il with\n  | Init_nil =>\n      OK s\n  | Init_cons i1 il' =>\n      do s1 <- transl_init_rec ce s tyelt i1 pos;\n      transl_init_array ce s1 tyelt il' (pos + sizeof ce tyelt)\n  end\n\nwith transl_init_struct (ce: composite_env) (s: state)\n                        (ms: members) (il: initializer_list)\n                        (base: Z) (pos: Z)\n                        {struct il} : res state :=\n  match il with\n  | Init_nil =>\n      OK s\n  | Init_cons i1 il' =>\n      let fix init (ms: members) (pos: Z) {struct ms} : res state :=\n        match ms with\n        | nil =>\n            Error (msg \"too many elements in struct initializer\")\n        | m :: ms' =>\n            if member_not_initialized m then\n              init ms' (next_field ce pos m)\n            else\n              do (delta, layout) <- layout_field ce pos m;\n              do s1 <-\n                match layout with\n                | Full =>\n                    transl_init_rec ce s (type_member m) i1 (base + delta)\n                | Bits sz sg p w =>\n                    transl_init_bitfield ce s (type_member m) sz p w i1 (base + delta)\n                end;\n                transl_init_struct ce s1 ms' il' base (next_field ce pos m)\n         end in\n      init ms pos\n  end.\n\n(** The entry point. *)\n\nDefinition transl_init (ce: composite_env) (ty: type) (i: initializer)\n                       : res (list init_data) :=\n  let s0 := initial_state (sizeof ce ty) in\n  do s1 <- transl_init_rec ce s0 ty i 0;\n  init_data_list_of_state s1.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/cfrontend/Initializers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.21079114684943562}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import ssreflect ssrbool.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICCases PCUICLiftSubst PCUICUnivSubst\n     PCUICTyping PCUICCumulativity PCUICConfluence PCUICConversion\n     PCUICOnFreeVars PCUICClosedTyp PCUICWellScopedCumulativity.\n\nRequire Import Equations.Prop.DepElim.\n(* TODO: make wf arguments implicit *)\nSection Inversion.\n\n  Context {cf : checker_flags}.\n  Context (Σ : global_env_ext).\n  Context (wfΣ : wf Σ).\n\n  Ltac insum :=\n    match goal with\n    | |- ∑ x : _, _ =>\n      eexists\n    end.\n\n  Ltac intimes :=\n    match goal with\n    | |- _ × _ =>\n      split\n    end.\n\n  Ltac outsum :=\n    match goal with\n    | ih : ∑ x : _, _ |- _ =>\n      destruct ih as [? ?]\n    end.\n\n  Ltac outtimes :=\n    match goal with\n    | ih : _ × _ |- _ =>\n      destruct ih as [? ?]\n    end.\n\n  Lemma into_ws_cumul {Γ t T U s} :\n    Σ ;;; Γ |- t : T ->\n    Σ ;;; Γ |- U : tSort s ->\n    Σ ;;; Γ |- T <= U ->\n    Σ ;;; Γ ⊢ T ≤ U.\n  Proof using wfΣ.\n    intros. eapply into_ws_cumul_pb; tea.\n    - eapply typing_wf_local in X; eauto with fvs.\n    - eapply PCUICClosedTyp.type_closed in X.\n      eapply PCUICOnFreeVars.closedn_on_free_vars in X; tea.\n    - eapply PCUICClosedTyp.subject_closed in X0.\n      eapply PCUICOnFreeVars.closedn_on_free_vars in X0; tea.\n  Qed.\n\n  Lemma typing_closed_ctx Γ t T :\n    Σ ;;; Γ |- t : T ->\n    is_closed_context Γ.\n  Proof using wfΣ.\n    move/typing_wf_local; eauto with fvs.\n  Qed.\n  Hint Immediate typing_closed_ctx : fvs.\n\n  Lemma typing_ws_cumul_pb le Γ t T :\n    Σ ;;; Γ |- t : T ->\n    Σ ;;; Γ ⊢ T ≤[le] T.\n  Proof using wfΣ.\n    intros ht. apply into_ws_cumul_pb; auto. destruct le ; reflexivity.\n    eauto with fvs.\n    eapply PCUICClosedTyp.type_closed in ht.\n    now rewrite -is_open_term_closed.\n    eapply PCUICClosedTyp.type_closed in ht.\n    now rewrite -is_open_term_closed.\n  Qed.\n  Hint Immediate typing_closed_ctx : fvs.\n\n  Ltac invtac h :=\n    dependent induction h ; [\n      repeat insum ;\n      repeat intimes ;\n      [ try first [ eassumption | try reflexivity ] .. | try solve [eapply typing_ws_cumul_pb; econstructor; eauto] ]\n    | repeat outsum ;\n      repeat outtimes ;\n      repeat insum ;\n      repeat intimes ;\n      [ try first [ eassumption | reflexivity ] ..\n      | try etransitivity ; try eassumption;\n        try eauto with pcuic;\n        try solve [eapply into_ws_cumul; tea] ]\n    ].\n\n  Derive Signature for typing.\n\n  Import PCUICClosed PCUICOnFreeVars.\n\n  Lemma nth_error_closed_context {Γ n d} :\n    is_closed_context Γ ->\n    nth_error Γ n = Some d ->\n    is_open_term Γ (lift0 (S n) (decl_type d)).\n  Proof using Type.\n    intros isc hnth.\n    rewrite -on_free_vars_ctx_on_ctx_free_vars in isc.\n    rewrite <- (addnP0) in isc.\n    eapply nth_error_on_free_vars_ctx in isc; tea.\n    2:{ rewrite /shiftnP orb_false_r. eapply Nat.ltb_lt.\n        eapply nth_error_Some_length in hnth. lia. }\n    now move/andP: isc=> [] _ /on_free_vars_lift0 /=.\n  Qed.\n\n  Lemma inversion_Rel :\n    forall {Γ n T},\n      Σ ;;; Γ |- tRel n : T ->\n      ∑ decl,\n        wf_local Σ Γ ×\n        (nth_error Γ n = Some decl) ×\n        Σ ;;; Γ ⊢ lift0 (S n) (decl_type decl) ≤ T.\n  Proof using wfΣ.\n    intros Γ n T h. invtac h.\n  Qed.\n\n  Lemma inversion_Var :\n    forall {Γ i T},\n      Σ ;;; Γ |- tVar i : T -> False.\n  Proof using Type.\n    intros Γ i T h. dependent induction h. assumption.\n  Qed.\n\n  Lemma inversion_Evar :\n    forall {Γ n l T},\n      Σ ;;; Γ |- tEvar n l : T -> False.\n  Proof using Type.\n    intros Γ n l T h. dependent induction h. assumption.\n  Qed.\n\n  Lemma inversion_Sort :\n    forall {Γ s T},\n      Σ ;;; Γ |- tSort s : T ->\n      wf_local Σ Γ ×\n      wf_universe Σ s ×\n      Σ ;;; Γ ⊢ tSort (Universe.super s) ≤ T.\n  Proof using wfΣ.\n    intros Γ s T h. invtac h.\n  Qed.\n\n  Lemma inversion_Prod :\n    forall {Γ na A B T},\n      Σ ;;; Γ |- tProd na A B : T ->\n      ∑ s1 s2,\n        Σ ;;; Γ |- A : tSort s1 ×\n        Σ ;;; Γ ,, vass na A |- B : tSort s2 ×\n        Σ ;;; Γ ⊢ tSort (Universe.sort_of_product s1 s2) ≤ T.\n  Proof using wfΣ.\n    intros Γ na A B T h. invtac h.\n  Qed.\n\n  Lemma inversion_Prod_size :\n    forall {Γ na A B T},\n      forall H : Σ ;;; Γ |- tProd na A B : T,\n      ∑ s1 s2 (H1 : Σ ;;; Γ |- A : tSort s1) (H2 : Σ ;;; Γ ,, vass na A |- B : tSort s2),\n        typing_size H1 < typing_size H × typing_size H2 < typing_size H ×\n        Σ ;;; Γ ⊢ tSort (Universe.sort_of_product s1 s2) ≤ T.\n  Proof using wfΣ.\n    intros Γ na A B T h. unshelve invtac h; eauto.\n    all: unfold typing_size at 2; fold (typing_size h1); fold (typing_size h2); lia.\n  Qed.\n\n  Lemma inversion_Lambda :\n    forall {Γ na A t T},\n      Σ ;;; Γ |- tLambda na A t : T ->\n      ∑ s B,\n        Σ ;;; Γ |- A : tSort s ×\n        Σ ;;; Γ ,, vass na A |- t : B ×\n        Σ ;;; Γ ⊢ tProd na A B ≤ T.\n  Proof using wfΣ.\n    intros Γ na A t T h. invtac h.\n  Qed.\n\n  Lemma inversion_LetIn :\n    forall {Γ na b B t T},\n      Σ ;;; Γ |- tLetIn na b B t : T ->\n      ∑ s1 A,\n        Σ ;;; Γ |- B : tSort s1 ×\n        Σ ;;; Γ |- b : B ×\n        Σ ;;; Γ ,, vdef na b B |- t : A ×\n        Σ ;;; Γ ⊢ tLetIn na b B A ≤ T.\n  Proof using wfΣ.\n    intros Γ na b B t T h. invtac h.\n  Qed.\n\n  Lemma inversion_App :\n    forall {Γ u v T},\n      Σ ;;; Γ |- tApp u v : T ->\n      ∑ na A B,\n        Σ ;;; Γ |- u : tProd na A B ×\n        Σ ;;; Γ |- v : A ×\n        Σ ;;; Γ ⊢ B{ 0 := v } ≤ T.\n  Proof using wfΣ.\n    intros Γ u v T h. invtac h.\n  Qed.\n\n  Lemma inversion_App_size :\n  forall {Γ u v T}\n      (H : Σ ;;; Γ |- tApp u v : T),\n      ∑ na A B s  (H1 : Σ ;;; Γ |- u : tProd na A B) (H2 : Σ ;;; Γ |- v : A) (H3 : Σ ;;; Γ |- tProd na A B : tSort s),\n      typing_size H1 < typing_size H × typing_size H2 < typing_size H × typing_size H3 < typing_size H ×\n        Σ ;;; Γ ⊢ B{ 0 := v } ≤ T.\n  Proof using wfΣ.\n    intros Γ u v T h. unshelve invtac h.\n    4,5,6,10,11,12: eauto.\n    all: unfold typing_size at 2; fold (typing_size h1); fold (typing_size h2); try fold (typing_size h3); lia.\n  Qed.\n\n  Lemma inversion_Const :\n    forall {Γ c u T},\n      Σ ;;; Γ |- tConst c u : T ->\n      ∑ decl,\n        wf_local Σ Γ ×\n        declared_constant Σ c decl ×\n        (consistent_instance_ext Σ decl.(cst_universes) u) ×\n        Σ ;;; Γ ⊢ subst_instance u (cst_type decl) ≤ T.\n  Proof using wfΣ.\n    intros Γ c u T h. invtac h.\n  Qed.\n\n  Lemma inversion_Ind :\n    forall {Γ ind u T},\n      Σ ;;; Γ |- tInd ind u : T ->\n      ∑ mdecl idecl,\n        wf_local Σ Γ ×\n        declared_inductive Σ ind mdecl idecl ×\n        consistent_instance_ext Σ (ind_universes mdecl) u ×\n        Σ ;;; Γ ⊢ subst_instance u idecl.(ind_type) ≤ T.\n  Proof using wfΣ.\n    intros Γ ind u T h. invtac h.\n  Qed.\n\n  Lemma inversion_Construct :\n    forall {Γ ind i u T},\n      Σ ;;; Γ |- tConstruct ind i u : T ->\n      ∑ mdecl idecl cdecl,\n        wf_local Σ Γ ×\n        declared_constructor (fst Σ) (ind, i) mdecl idecl cdecl ×\n        consistent_instance_ext Σ (ind_universes mdecl) u ×\n        Σ;;; Γ ⊢ type_of_constructor mdecl cdecl (ind, i) u ≤ T.\n  Proof using wfΣ.\n    intros Γ ind i u T h. invtac h.\n  Qed.\n  Import PCUICEquality.\n  Variant case_inversion_data Γ ci p c brs mdecl idecl indices :=\n   | case_inv\n       (ps : Universe.t)\n       (eq_npars : mdecl.(ind_npars) = ci.(ci_npar))\n       (predctx := case_predicate_context ci.(ci_ind) mdecl idecl p)\n       (wf_pred : wf_predicate mdecl idecl p)\n       (cons : consistent_instance_ext Σ (ind_universes mdecl) p.(puinst))\n       (wf_pctx : wf_local Σ (Γ ,,, predctx))\n       (conv_pctx : eq_context_upto_names p.(pcontext) (ind_predicate_context ci.(ci_ind) mdecl idecl))\n       (pret_ty : Σ ;;; Γ ,,, predctx |- p.(preturn) : tSort ps)\n       (allowed_elim : is_allowed_elimination Σ idecl.(ind_kelim) ps)\n       (ind_inst : ctx_inst typing Σ Γ (p.(pparams) ++ indices)\n                            (List.rev (subst_instance p.(puinst)\n                                                      (ind_params mdecl ,,, ind_indices idecl))))\n       (scrut_ty : Σ ;;; Γ |- c : mkApps (tInd ci.(ci_ind) p.(puinst)) (p.(pparams) ++ indices))\n       (not_cofinite : isCoFinite mdecl.(ind_finite) = false)\n       (ptm := it_mkLambda_or_LetIn predctx p.(preturn))\n       (wf_brs : wf_branches idecl brs)\n       (brs_ty :\n          All2i (fun i cdecl br =>\n                   eq_context_upto_names br.(bcontext) (cstr_branch_context ci mdecl cdecl) ×\n                   let brctxty := case_branch_type ci.(ci_ind) mdecl idecl p br ptm i cdecl in\n                   (wf_local Σ (Γ ,,, brctxty.1) ×\n                   ((Σ ;;; Γ ,,, brctxty.1 |- br.(bbody) : brctxty.2) ×\n                    (Σ ;;; Γ ,,, brctxty.1 |- brctxty.2 : tSort ps))))\n                0 idecl.(ind_ctors) brs).\n\n  Lemma inversion_Case :\n    forall {Γ ci p c brs T},\n      Σ ;;; Γ |- tCase ci p c brs : T ->\n      ∑ mdecl idecl (isdecl : declared_inductive Σ.1 ci.(ci_ind) mdecl idecl) indices,\n        let predctx := case_predicate_context ci.(ci_ind) mdecl idecl p in\n        let ptm := it_mkLambda_or_LetIn predctx p.(preturn) in\n        case_inversion_data Γ ci p c brs mdecl idecl indices ×\n        Σ ;;; Γ ⊢ mkApps ptm (indices ++ [c]) ≤ T.\n  Proof using wfΣ.\n    intros Γ ci p c brs T h.\n    dependent induction h.\n    {  remember c0; remember c1. destruct c0, c1. repeat insum; repeat intimes; try eapply case_inv ;\n\t    [ try first [ eassumption | reflexivity ].. | try eapply typing_ws_cumul_pb; econstructor; eauto ]. }\n    repeat outsum; repeat outtimes; repeat insum; repeat intimes ; tea;\n      [ try first\n      [ eassumption | reflexivity ]..\n      | try etransitivity; try eassumption; eapply into_ws_cumul; tea; eauto with pcuic ].\n  Qed.\n\n  Lemma inversion_Proj :\n    forall {Γ p c T},\n      Σ ;;; Γ |- tProj p c : T ->\n      ∑ u mdecl idecl cdecl pdecl args,\n        declared_projection Σ p mdecl idecl cdecl pdecl ×\n        Σ ;;; Γ |- c : mkApps (tInd p.(proj_ind) u) args ×\n        #|args| = ind_npars mdecl ×\n        Σ ;;; Γ ⊢ (subst0 (c :: List.rev args)) pdecl.(proj_type)@[u] ≤ T.\n  Proof using wfΣ.\n    intros Γ p c T h. invtac h.\n  Qed.\n\n  Lemma inversion_Fix :\n    forall {Γ mfix n T},\n      Σ ;;; Γ |- tFix mfix n : T ->\n      ∑ decl,\n        let types := fix_context mfix in\n        fix_guard Σ Γ mfix ×\n        nth_error mfix n = Some decl ×\n        All (fun d => isType Σ Γ (dtype d)) mfix ×\n        All (fun d =>\n          Σ ;;; Γ ,,, types |- dbody d : (lift0 #|types|) (dtype d)) mfix ×\n        wf_fixpoint Σ mfix ×\n        Σ ;;; Γ ⊢ dtype decl ≤ T.\n  Proof using wfΣ.\n    intros Γ mfix n T h. invtac h.\n  Qed.\n\n  Lemma inversion_CoFix :\n    forall {Γ mfix idx T},\n      Σ ;;; Γ |- tCoFix mfix idx : T ->\n      ∑ decl,\n        cofix_guard Σ Γ mfix ×\n        let types := fix_context mfix in\n        nth_error mfix idx = Some decl ×\n        All (fun d => isType Σ Γ (dtype d)) mfix ×\n        All (fun d =>\n          Σ ;;; Γ ,,, types |- d.(dbody) : lift0 #|types| d.(dtype)\n        ) mfix ×\n        wf_cofixpoint Σ mfix ×\n        Σ ;;; Γ ⊢ decl.(dtype) ≤ T.\n  Proof using wfΣ.\n    intros Γ mfix idx T h. invtac h.\n  Qed.\n\n  Lemma inversion_Prim :\n    forall {Γ p T},\n    Σ ;;; Γ |- tPrim p : T ->\n    ∑ prim_ty cdecl,\n      [× wf_local Σ Γ,\n        primitive_constant Σ (prim_val_tag p) = Some prim_ty,\n        declared_constant Σ prim_ty cdecl,\n        primitive_invariants cdecl &\n        Σ ;;; Γ ⊢ tConst prim_ty [] ≤ T].\n  Proof.\n    intros Γ p T h. depind h.\n    - exists prim_ty, cdecl; split => //.\n      eapply ws_cumul_pb_refl; fvs.\n    - destruct IHh1 as [prim_ty [cdecl []]].\n      exists prim_ty, cdecl. split => //.\n      transitivity A; tea. eapply cumulSpec_cumulAlgo_curry; tea; fvs.\n  Qed.\n\n  Lemma inversion_it_mkLambda_or_LetIn :\n    forall {Γ Δ t T},\n      Σ ;;; Γ |- it_mkLambda_or_LetIn Δ t : T ->\n      ∑ A,\n        Σ ;;; Γ ,,, Δ |- t : A ×\n        Σ ;;; Γ ⊢ it_mkProd_or_LetIn Δ A ≤ T.\n  Proof using wfΣ.\n    intros Γ Δ t T h.\n    induction Δ as [| [na [b|] A] Δ ih ] in Γ, t, h |- *.\n    - eexists. split ; eauto. cbn.\n      eapply into_ws_cumul_pb; [reflexivity|..].\n      eauto with fvs.\n      eapply type_closed in h.\n      now eapply closedn_on_free_vars in h.\n      eapply type_closed in h.\n      now eapply closedn_on_free_vars in h.\n    - simpl. apply ih in h. cbn in h.\n      destruct h as [B [h c]].\n      apply inversion_LetIn in h as hh.\n      destruct hh as [s1 [A' [? [? [? ?]]]]].\n      exists A'. split ; eauto.\n      cbn. etransitivity; tea.\n      eapply ws_cumul_pb_it_mkProd_or_LetIn_codom.\n      assumption.\n    - simpl. apply ih in h. cbn in h.\n      destruct h as [B [h c]].\n      apply inversion_Lambda in h as hh.\n      pose proof hh as [s1 [B' [? [? ?]]]].\n      exists B'. split ; eauto.\n      cbn. etransitivity; tea.\n      eapply ws_cumul_pb_it_mkProd_or_LetIn_codom.\n      assumption.\n  Qed.\n\nEnd Inversion.\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/pcuic/theories/PCUICInversion.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.21079114130019794}}
{"text": "From Undecidability.L.Datatypes Require Import LNat Lists LVector.\nFrom Undecidability.L Require Import TM.TMEncoding.\n\nFrom Undecidability.TM Require Import Util.TM_facts.\n\n\nSet Default Proof Using \"Type\".\nSection fix_sig.\n  Variable sig : Type.\n  Context `{reg_sig : registered sig}.\n\n  Section reg_tapes.\n\n    Global Instance term_tape_move_left' : computableTime' (@tape_move_left' sig) (fun _ _ => (1, fun _ _ => (1,fun _ _ => (12,tt)))).\n    Proof.\n      extract. solverec.\n    Qed.\n\n    Global Instance term_tape_move_left : computableTime' (@tape_move_left sig) (fun _ _ => (23,tt)).\n    Proof.\n      extract. solverec.\n    Qed.\n\n    Global Instance term_tape_move_right' : computableTime' (@tape_move_right' sig) (fun _ _ => (1, fun _ _ => (1,fun _ _ => (12,tt)))).\n    Proof.\n      extract. solverec.\n    Qed.\n\n    Global Instance term_tape_move_right : computableTime' (@tape_move_right sig) (fun _ _ => (23,tt)).\n    Proof.\n      extract. solverec.\n    Qed.\n\n    Global Instance term_tape_move : computableTime' (@tape_move sig) (fun _ _ => (1,fun _ _ => (48,tt))).\n    Proof.\n      extract. solverec.\n    Qed.\n\n    Global Instance term_left : computableTime' (@left sig) (fun _ _ => (10,tt)).\n    Proof.\n      extract. solverec.\n    Qed.\n\n    Global Instance term_right : computableTime' (@right sig) (fun _ _ => (10,tt)).\n    Proof.\n      extract. solverec.\n    Qed.\n\n    Global Instance term_tape_write : computableTime' (@tape_write sig) ((fun _ _ => (1,fun _ _ => (28,tt)))).\n    Proof.\n      extract. solverec.\n    Qed.\n\n\n    \n    Global Instance term_tapeToList:  computableTime' (@tapeToList sig) (fun t _ => (sizeOfTape t*29 + 53,tt)).  \n    Proof.\n    extract. recRel_prettify2. all:repeat (simpl_list;cbn -[plus mult]). \n    all: unfold c__rev, c__app. all: try nia.\n    Qed.\n\n\n    Global Instance term_sizeOfTape: computableTime' (@sizeOfTape sig) (fun t _ => (sizeOfTape t*40 + 65,tt)).\n    Proof.\n      extract. unfold sizeOfTape. solverec. unfold c__length. solverec. \n    Qed.\n\n    Import Nat.\n\n    Global Instance term_sizeOfmTapes n:\n      computableTime' (@sizeOfmTapes sig n) (fun t _ => ((sizeOfmTapes t*105+101) * n + 56,tt)).\n    Proof.\n      set (f:= (fix sizeOfmTapes acc (ts : list (tape sig)) : nat :=\n                  match ts with\n                  | [] => acc\n                  | t :: ts0 => sizeOfmTapes (Init.Nat.max acc (sizeOfTape t)) ts0\n                  end)).\n      \n      assert (H' : extEq (fun v => f 0 (Vector.to_list v)) (@sizeOfmTapes sig n)).\n      { intros x. hnf. unfold sizeOfmTapes. generalize 0.\n        induction x using Vector.t_ind;intros acc. cbn. nia.        \n        cbn in *. rewrite <- IHx. unfold Vector.to_list. nia.\n      }\n      assert (computableTime' f (fun acc _ => (5, fun t _ => ((max acc (fold_right max 0 (map (sizeOfTape (sig:=sig))t))*105 + 101) * (length t) + 49,tt)))).\n      { unfold f. extract. solverec. unfold c__max1, max_time, c__max2. solverec. }\n\n      eapply computableTimeExt. exact H'.\n      extract. solverec. unfold sizeOfmTapes. rewrite vector_fold_left_to_list,fold_symmetric. 2,3:intros;nia.\n      rewrite vector_map_to_list,to_list_length.\n      set (List.fold_right _ _ _). nia. \n    Qed.\n\n    Global Instance term_current: computableTime' ((current (Σ:=sig))) (fun _ _ => (10,tt)).\n    Proof.\n      extract.\n      solverec.\n    Qed.\n\n    Global Instance term_current_chars n: computableTime' (current_chars (sig:=sig) (n:=n))  (fun _ _ => (n * 22 +16,tt)).\n    Proof.\n      extract.\n      solverec.\n      rewrite map_time_const,to_list_length. unfold c__map. lia.\n    Qed.\n\n    Global Instance term_doAct: computableTime' (doAct (sig:=sig)) (fun _ _ => (1,fun _ _ => (89,tt))).\n    Proof.\n      extract.\n      solverec.\n    Qed.\n\n\n  End reg_tapes.\nEnd fix_sig.\n\nFixpoint loopTime {X} `{registered X} f (fT: timeComplexity (X -> X)) (p: X -> bool) (pT : timeComplexity (X -> bool)) (a:X) k :=\n  fst (pT a tt) +\n  match k with\n    0 => 7\n  |  S k =>\n     fst (fT a tt) + 13 + loopTime f fT p pT (f a) k\n  end.\n\nGlobal\nInstance term_loop A `{registered A} :\n  computableTime' (@loop A)\n                 (fun f fT => (1,fun p pT => (1,fun a _ => (5,fun k _ =>(loopTime f fT p pT a k,tt))))).\nProof.\n  extract.\n  solverec.\nQed.\n", "meta": {"author": "uds-psl", "repo": "coq-synthetic-incompleteness", "sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53", "save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness", "path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/L/TM/TapeFuns.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21069055637134734}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.reverse_client.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\nDefinition t_struct_list := Tstruct _list noattr.\n\nFixpoint listrep (sigma: list int) (x: val) : mpred :=\n match sigma with\n | h::hs => \n    EX y:val, \n      data_at Tsh t_struct_list (Vint h,y) x  *  listrep hs y\n | nil => \n    !! (x = nullval) && emp\n end.\n\nArguments listrep sigma x : simpl never.\n\nLemma listrep_local_facts:\n  forall sigma p,\n   listrep sigma p |--\n   !! (is_pointer_or_null p /\\ (p=nullval <-> sigma=nil)).\nProof.\nintros.\nrevert p; induction sigma; \n  unfold listrep; fold listrep; intros. entailer!. intuition.\nIntros y. entailer!.\nsplit; intro. subst p. destruct H; contradiction. inv H2.\nQed.\n\nHint Resolve listrep_local_facts : saturate_local.\n\nLemma listrep_valid_pointer:\n  forall sigma p,\n   listrep sigma p |-- valid_pointer p.\nProof.\n destruct sigma; unfold listrep; fold listrep; intros; Intros; subst.\n auto with valid_pointer.\n Intros y.\n apply sepcon_valid_pointer1.\n apply data_at_valid_ptr; auto.\n simpl;  computable.\nQed.\n\nHint Resolve listrep_valid_pointer : valid_pointer.\n\nDefinition reverse_spec :=\n DECLARE _reverse\n  WITH sigma : list int, p: val\n  PRE  [ tptr t_struct_list ]\n     PROP ()\n     PARAMS (p)\n     SEP (listrep sigma p)\n  POST [ (tptr t_struct_list) ]\n    EX q:val,\n     PROP () RETURN (q)\n     SEP (listrep (rev sigma) q).\n\nDefinition last_foo_spec :=\n DECLARE _last_foo\n  WITH sigma : list int, p: val, sigma': list int, x: int\n  PRE  [ tptr t_struct_list ]\n     PROP (sigma = sigma' ++ x :: nil)\n     PARAMS (p)\n     SEP (listrep sigma p)\n  POST [ tuint ]\n     PROP () RETURN (Vint x)\n     SEP (TT).\n\nDefinition Gprog : funspecs :=\n         ltac:(with_library prog [ reverse_spec; last_foo_spec ]).\n\nLemma body_last_foo: semax_body Vprog Gprog\n                                    f_last_foo last_foo_spec.\nProof.\n  start_function.\n  subst sigma.\n  forward_call (sigma' ++ [x], p). (* p = reverse (p); *)\n  Intros p'.\n  rewrite rev_app_distr; simpl.\n  unfold listrep; fold listrep.\n  Intros q.\n  forward. (* res = p -> head; *)\n  forward. (* return res; *)\nQed.\n", "meta": {"author": "Ereboas", "repo": "PL-Final-Project", "sha": "442d296ce43a3728e7a8c2b373db2d331a4a4bbf", "save_path": "github-repos/coq/Ereboas-PL-Final-Project", "path": "github-repos/coq/Ereboas-PL-Final-Project/PL-Final-Project-442d296ce43a3728e7a8c2b373db2d331a4a4bbf/code/VST/progs/verif_reverse_client.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21069055637134734}}
{"text": "(* \n  Proof of correctness of the Clight code generation phase of CertiCoq \n\n  > Relates values to location in memory (syntactic)\n  > Relates expression to statements (syntactic)\n  > Relates Codegen values (header, payload) to Codegen values after GC (syntactic, up to non-function pointer location)\n  > Relates LambdaANF states to Codegen states according to execution semantics\n\n\n\nTODO: bundle the notation in LambdaANF_to_Clight and import it instead of redefining it \n\nDone: change LambdaANF_to_Clight's fn_vars into fn_temps\nDone: change LambdaANF_to_Clight's reserve into reserve', todo update proof with new order \nDone: update proof to 64 bits (parametric over Archi.ptr64) \n *)\n        \nRequire Import LambdaANF.cps LambdaANF.eval LambdaANF.cps_util LambdaANF.List_util LambdaANF.Ensembles_util LambdaANF.identifiers LambdaANF.tactics LambdaANF.shrink_cps_corresp. \n  \n\n\n(* Require Import RamifyCoq.CertiGC.GCGraph. *)\n\n\n\nRequire Import Coq.Arith.Arith Coq.NArith.BinNat ExtLib.Data.String ExtLib.Data.List Coq.micromega.Lia Coq.Program.Program Coq.micromega.Psatz Coq.Sets.Ensembles Coq.Logic.Decidable Coq.Lists.ListDec Coq.Relations.Relations.\n\nRequire Import compcert.common.AST\n        compcert.common.Errors\n        compcert.lib.Integers\n        compcert.cfrontend.Cop\n        compcert.cfrontend.Ctypes\n        compcert.cfrontend.Clight\n        compcert.common.Values\n        compcert.common.Globalenvs\n        compcert.common.Memory.\n\nRequire Import Codegen.tactics\n               Codegen.LambdaANF_to_Clight.\n\nRequire Import Libraries.maps_util.\n\n \n(* Space guarantied by the GC on return *)\nDefinition gc_size:Z := Z.shiftl 1%Z 16%Z.\n \nDefinition loc:Type := block * ptrofs.\n\n\nNotation intTy := (Tint I32 Signed\n                        {| attr_volatile := false; attr_alignas := None |}).\n\nNotation uintTy := (Tint I32 Unsigned\n                         {| attr_volatile := false; attr_alignas := None |}).\n\nNotation longTy := (Tlong Signed\n                        {| attr_volatile := false; attr_alignas := None |}).\n\nNotation ulongTy := (Tlong Unsigned\n                           {| attr_volatile := false; attr_alignas := None |}).\nNotation boolTy := (Tint IBool Unsigned noattr). \n\n\n (* 64-bit \n\nDefinition int_chunk := if Archi.ptr64 then Mint64 else Mint32.\nDefinition val := if Archi.ptr64 then ulongTy else uintTy. (* NOTE: in Clight, SIZEOF_PTR == SIZEOF_INT *) \nDefinition uval := if Archi.ptr64 then ulongTy else uintTy.\nDefinition sval := if Archi.ptr64 then longTy else intTy.\nDefinition val_typ := if Archi.ptr64 then  (AST.Tlong:typ) else (Tany32:typ).\nDefinition Init_int x := if Archi.ptr64 then (Init_int64 (Int64.repr x)) else (Init_int32 (Int.repr x)).\nDefinition make_vint z := if Archi.ptr64 then Vlong (Int64.repr z) else Vint (Int.repr z).\nDefinition make_cint z t := if Archi.ptr64 then Econst_long (Int64.repr z) t else (Econst_int (Int.repr z) t).\nTransparent val.\nTransparent uval.\nTransparent val_typ.\nTransparent Init_int.\nTransparent make_vint.\nTransparent make_cint.                                                                   \n  *)\n\n\n\n                \n\n\n\nDefinition int_size := (size_chunk int_chunk).\nDefinition max_args :=   1024%Z. (* limited by space in boxed header *)\n\nTheorem int_size_pos:\n  (0 <= size_chunk int_chunk)%Z.\nProof.\n  apply Z.lt_le_incl. apply Z.gt_lt.   apply size_chunk_pos. \nQed.\n\n\nDefinition uint_range : Z -> Prop := \n  fun i => (0 <= i <=   Ptrofs.max_unsigned)%Z. \nTransparent uint_range.\n\nTheorem uint_range_unsigned:\n  forall i,\n    uint_range (Ptrofs.unsigned i).\nProof.\n  apply Ptrofs.unsigned_range_2.\nQed.\n  \nLtac int_red := unfold int_size in *; simpl size_chunk in *.\n\nLtac chunk_red := unfold int_size in *; unfold int_chunk in *; destruct Archi.ptr64 eqn:Harchi; simpl size_chunk in *.\n\nLtac uomega := (unfold int_size; simpl size_chunk; omega).\n\nDefinition uint_range_l: list Z -> Prop :=\n  fun l => Forall uint_range l.\n\n\nTheorem ptrofs_mu_weak:\n  (Int.max_unsigned <= Ptrofs.max_unsigned)%Z.\nProof.\n  unfold Int.max_unsigned.\n  unfold Ptrofs.max_unsigned.\n\n  destruct (Archi.ptr64) eqn:Harchi. \n\n  rewrite Ptrofs.modulus_eq64 by auto. unfold Int.modulus. unfold Int64.modulus. simpl. omega.\n  rewrite Ptrofs.modulus_eq32 by auto. reflexivity.\nQed.\n\nTheorem ptrofs_ms:\n(Ptrofs.max_signed = if Archi.ptr64 then Int64.max_signed else Int.max_signed )%Z.\nProof.\n  unfold Int.max_signed.\n  unfold Ptrofs.max_signed.\n  unfold Ptrofs.half_modulus.\n  destruct (Archi.ptr64) eqn:Harchi.   \n  rewrite Ptrofs.modulus_eq64 by auto; reflexivity. \n  rewrite Ptrofs.modulus_eq32 by auto; reflexivity.\nQed.\n  \n\nTheorem ptrofs_mu:\n  (Ptrofs.max_unsigned = if Archi.ptr64 then Int64.max_unsigned else Int.max_unsigned )%Z.\nProof.\n  unfold Int.max_unsigned.\n  unfold Ptrofs.max_unsigned.\n\n  destruct (Archi.ptr64) eqn:Harchi.   \n  rewrite Ptrofs.modulus_eq64 by auto; reflexivity. \n  rewrite Ptrofs.modulus_eq32 by auto; reflexivity.\nQed.\n\nLtac uint_range_ptrofs :=\n  unfold uint_range_l; unfold uint_range; rewrite ptrofs_mu.\n\nLtac solve_uint_range:=\n  unfold Int64.max_unsigned in *; unfold Int64.modulus in *; unfold Int.max_unsigned in *; unfold Int.modulus in *;  simpl in *; (match goal with\n          | [H:uint_range _ |- _] => unfold uint_range in H; rewrite ptrofs_mu in H; solve_uint_range\n          | [H:uint_range_l _ |- _] => unfold uint_range_l in H;  solve_uint_range \n          | [H: Forall uint_range _ |- _] => inv H; solve_uint_range \n          | [|- uint_range _] => unfold uint_range; unfold Int.max_unsigned; unfold Int.modulus; simpl; try omega\n          | [|- uint_range (Ptrofs.unsigned _)] => apply uint_range_unsigned\n          | [|- uint_range (Int.unsigned _)] => apply uint_range_unsigned\n          | [|- uint_range_l _] => unfold uint_range_l; solve_uint_range\n          | [ |- Forall uint_range _] => constructor; solve_uint_range\n          | _ => auto\n          end).\n\n\n\nTheorem int_z_mul :\n  forall i y,\n    uint_range_l [i; y] -> \n  Ptrofs.mul (Ptrofs.repr i) (Ptrofs.repr y) = Ptrofs.repr (i * y)%Z.\nProof.\n  intros.\n  unfold Ptrofs.mul.\n  rewrite Ptrofs.unsigned_repr.\n  rewrite Ptrofs.unsigned_repr. reflexivity.\n  inv H. inv H3; auto.\n  inv H; auto.\nQed.\n\n  \nTheorem int_z_add:\n  forall i y,\n    uint_range_l [i; y] -> \n    Ptrofs.add (Ptrofs.repr i) (Ptrofs.repr y) = Ptrofs.repr (i + y)%Z.\nProof.\n  intros.\n  unfold Ptrofs.add.\n  rewrite Ptrofs.unsigned_repr.\n  rewrite Ptrofs.unsigned_repr.\n  reflexivity.\n  inv H. inv H3; auto.\n  inv H; auto.\nQed.  \n\n\nTheorem pointer_ofs_no_overflow:\nforall ofs z, \n  (0 <= z)%Z ->\n  (Ptrofs.unsigned ofs + int_size * z <= Ptrofs.max_unsigned )%Z ->\n                        \n                        Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr (int_size * z))) =\n        (Ptrofs.unsigned ofs + int_size * z)%Z.\nProof.\n  intros.\n  unfold int_size in *; simpl size_chunk in *.\n  assert (0 <=  Ptrofs.unsigned ofs)%Z by apply Ptrofs.unsigned_range_2.\n  unfold Ptrofs.add.\n  assert (0 <= size_chunk int_chunk)%Z by apply int_size_pos.\n  rewrite Ptrofs.unsigned_repr with (z := (_ * z)%Z).\n  rewrite Ptrofs.unsigned_repr. reflexivity.  \n\n  split; auto. apply Z.add_nonneg_nonneg; auto. apply Z.mul_nonneg_nonneg; auto.\n  split; auto. apply Z.mul_nonneg_nonneg; auto. \n  omega.\nQed.\n\n   \n (* TODO: move to identifiers *)\nInductive bound_var_val: LambdaANF.cps.val -> Ensemble var :=\n| Bound_Vconstr :\n    forall c vs v x, \n    bound_var_val v x ->\n    List.In v vs ->\n    bound_var_val (Vconstr c vs) x\n| Bound_Vfun:\n    forall fds rho x f,\n    bound_var_fundefs fds x ->\n    bound_var_val (Vfun rho fds f) x.\n\n  \nInductive occurs_free_val: LambdaANF.cps.val -> Ensemble var :=\n| OF_Vconstr :\n    forall c vs v x, \n    occurs_free_val v x ->\n    List.In v vs ->\n    occurs_free_val (Vconstr c vs) x\n| OF_Vfun:\n    forall fds rho x f,\n      occurs_free_fundefs fds x ->\n      M.get x rho = None ->\n      occurs_free_val (Vfun rho fds f) x.\n\n\nDefinition closed_val (v : LambdaANF.cps.val) : Prop :=\n  Same_set var (occurs_free_val v) (Empty_set var).\n\n\nTheorem closed_val_fun:\n  forall fl f t vs e, \n    closed_val (Vfun (M.empty cps.val) fl f) ->\n    find_def f fl = Some (t, vs, e) ->\n    (Included _ (occurs_free e) (Ensembles.Union _  (FromList vs) (name_in_fundefs fl)) ).\nProof.\n  intros. inv H. intro. intros.\n  assert (~  occurs_free_val (Vfun (M.empty cps.val) fl f) x). intro. apply H1 in H3. inv H3.\n  clear H1. clear H2.\n  assert (decidable (List.In x vs)). apply In_decidable. apply shrink_cps_correct.var_dec_eq.\n  assert (decidable (name_in_fundefs fl x)). unfold decidable. assert (Hd := Decidable_name_in_fundefs fl). inv Hd. specialize (Dec x). inv Dec; auto.\n  inv H1; inv H2; auto. exfalso. \n  apply H3. constructor. SearchAbout occurs_free_fundefs find_def.\n  eapply shrink_cps_correct.find_def_free_included. eauto. constructor. constructor. auto. auto. auto.\n  apply M.gempty.\nQed.\n  \n  \n\nInductive dsubval_v: LambdaANF.cps.val -> LambdaANF.cps.val -> Prop :=\n| dsubval_constr: forall v vs c,\n  List.In v vs ->\n  dsubval_v v (Vconstr c vs)\n| dsubval_fun : forall x fds rho f,\n  name_in_fundefs fds x ->\n    dsubval_v (Vfun rho fds x) (Vfun rho fds f)\n.\n\nDefinition subval_v := clos_trans _ dsubval_v.\nDefinition subval_or_eq := clos_refl_trans _ dsubval_v.\n\n\n  \nTheorem t_then_rt:\n  forall A R (v v':A),\n  clos_trans _ R v v'  ->\n  clos_refl_trans _ R v v'.\nProof.\n  intros. induction H.\n  apply rt_step. auto.\n  eapply rt_trans; eauto.\nQed.\n\n\nTheorem rt_then_t_or_eq:\n  forall A R (v v':A),\n    clos_refl_trans _ R v v' ->\n    v = v' \\/ clos_trans _ R v v'.\nProof.\n  intros. induction H.\n  right. apply t_step; auto.\n  left; auto.\n  inv IHclos_refl_trans1; inv IHclos_refl_trans2.\n  left; auto.\n  right; auto.\n  right; auto. right.\n  eapply t_trans; eauto.\nQed.\n\nTheorem dsubterm_case_cons:\n  forall v l e',\n    dsubterm_e e' (Ecase v l) -> \n  forall a, dsubterm_e e' (Ecase v (a:: l)).\nProof.\n  intros. inv H. econstructor.\n  right; eauto.\nQed.\n\n  \n\nTheorem subterm_case:\nforall v l e', \n  subterm_e e' (Ecase v l) -> \n  forall a, subterm_e e' (Ecase v (a:: l)).\nProof.  \n  intros. remember (Ecase v l) as y. revert dependent v. revert l. induction H.\n  - intros. subst. constructor.\n    eapply dsubterm_case_cons; eauto.\n  - intros. apply IHclos_trans2 in Heqy.\n    eapply t_trans. apply H. eauto.\nQed.\n\n\nTheorem subval_fun: forall v rho fl x,\n    name_in_fundefs fl x -> \n        subval_or_eq v (Vfun rho fl x) ->\n        exists l, v = Vfun rho fl l /\\ name_in_fundefs fl l.\nProof.\n  intros. apply rt_then_t_or_eq in H0.\n  inv H0.\n  exists x; auto.\n  remember (Vfun rho fl x) as y.\n  assert (exists x, y = Vfun rho fl x /\\ name_in_fundefs fl x ) by eauto.\n  clear H. clear Heqy. clear x. \n  induction H1.  destructAll. subst. inv H. eauto.\n  destructAll. \n  assert ( (exists x : var, Vfun rho fl x0 = Vfun rho fl x /\\ name_in_fundefs fl x)) by eauto.\n  apply IHclos_trans2 in H. apply IHclos_trans1 in H. auto.\nQed.  \n\nTheorem subval_or_eq_constr:\nforall v v' vs c,\n  subval_or_eq v v' ->\n  List.In v' vs ->\n  subval_or_eq v (Vconstr c vs).\nProof.\n  intros.\n  eapply rt_trans; eauto.\n  apply rt_step. constructor; auto.\nQed.\n\n\n \nTheorem subval_v_constr:\n  forall v vs t,\n  subval_v v (Vconstr t vs) ->\n  exists v',\n    subval_or_eq v v' /\\ List.In v' vs.\nProof.\n  intros.\n  remember (Vconstr t vs) as v'. revert t vs Heqv'.\n  induction H; intros; subst. \n  - inv H. exists x. split.\n    apply rt_refl. apply H2.\n  -  specialize (IHclos_trans2 t vs eq_refl).\n     destruct IHclos_trans2.\n     exists x0. destruct H1. split.\n     apply t_then_rt in H.\n     eapply rt_trans; eauto.\n     auto.\nQed.      \n       \nTheorem subval_or_eq_fun:\n  forall rho' fds f vs t,\n  subval_or_eq (Vfun rho' fds f) (Vconstr t vs) ->\n  exists v',\n    subval_or_eq (Vfun rho' fds f) v' /\\ List.In v' vs.\nProof.\n  intros.\n  apply rt_then_t_or_eq in H. destruct H.\n  inv H.\n  eapply subval_v_constr; eauto.\nQed.  \n\n\nTheorem bound_var_subval:\n  forall x v v',\n  bound_var_val v x ->\n  subval_or_eq v v' -> \n  bound_var_val v' x.\nProof.\n  intros. induction H0.\n  - inv H0. econstructor; eauto.\n    inv H. constructor. auto.\n  - auto.\n  - apply   IHclos_refl_trans2.\n    apply   IHclos_refl_trans1.\n    auto.\nQed.\n\n\n(* bound_var_val - name_in_fds *)\nInductive bound_subvar_val : cps.val -> Ensemble var :=\n    Bound_SVconstr : forall (c : ctor_tag) (vs : list cps.val) (v : cps.val) (x : var),\n                    bound_var_val (Vconstr c vs) x -> bound_subvar_val (Vconstr c vs) x\n  | Bound_SVfun : forall (fds : fundefs) (rho : cps.M.t cps.val) (x f : var),\n      bound_var_val (Vfun rho fds f) x -> ~name_in_fundefs fds x -> bound_subvar_val (Vfun rho fds f) x. \n\n\n \n(* deep version of bound_subvar_val, likely what is needed for functions_not_bound inv *)\nInductive bound_notfun_val: cps.val -> Ensemble var :=\n  Bound_FVconstr : forall (c : ctor_tag) (vs : list cps.val) \n                         (v : cps.val) (x : var),\n                    bound_notfun_val v x ->\n                    List.In v vs -> bound_notfun_val (Vconstr c vs) x\n| Bound_FVfun : forall (e:exp) (fds : fundefs) (rho : cps.M.t cps.val) ys (x f f' : var) t,\n    In _ (Ensembles.Union _ (FromList ys) (bound_var e)) x ->  find_def f' fds = Some (t, ys, e) ->  bound_notfun_val (Vfun rho fds f) x.\n\n\nTheorem find_dsubterm:\n  forall x t ys e fl,\nfind_def x fl = Some (t, ys, e) -> dsubterm_fds_e e fl.\nProof.\n  induction fl; intros.\n  - simpl in H. destruct (cps.M.elt_eq x v) eqn:Heq_xv. inv H. constructor.\n    constructor 2. eapply IHfl; eauto.\n  - inv H.\nQed.\n      \nTheorem bound_subvar_var: forall v x,\n  bound_subvar_val v x -> bound_var_val v x.\nProof.\n  intros. inv H; auto. \nQed.\n\nTheorem bound_notfun_var: forall v x,\n  bound_notfun_val v x -> bound_var_val v x.\nProof.\n  intros. induction H.\n  - econstructor; eauto. \n  -  constructor. induction fds. simpl in H0.\n     destruct  (cps.M.elt_eq f' v). inv H0. inv H. constructor; auto.     \n     constructor 3; auto.\n     constructor 2. auto.\n     inv H0.\nQed.        \n\n\nTheorem set_lists_In:\n  forall {A} x xs (v:A) vs rho rho' ,\n    List.In x xs ->\n    M.get x rho' = Some v ->\n    set_lists xs vs rho = Some rho' ->\n    List.In  v vs.\nProof.\n  induction xs; intros.\n  -   inv H.\n  - destruct vs. simpl in H1; inv H1. simpl in H1.\n    destruct (set_lists xs vs rho) eqn:Hsl; inv H1.\n    destruct (var_dec x a).     \n    + subst. \n      rewrite M.gss in H0. inv H0. constructor; reflexivity.      \n    + rewrite M.gso in H0 by auto.\n      constructor 2.\n      inv H. exfalso; apply n; reflexivity.\n      eapply IHxs; eauto.\nQed.\n\nLtac inList := repeat (try (left; reflexivity); right).\n\n\nLtac solve_nodup :=\n  let hxy := fresh \"Hxy\" in\n  intro hxy; subst; try (clear hxy); \nrepeat (match goal with\n        | [H: NoDup _ |- _] => let h2 := fresh \"Hnd\" in\n                               let h1 := fresh \"HinList\" in\n                               let x := fresh \"x\" in\n                               let l := fresh \"l\" in\n                               inversion H as [h1 | x l h1 h2];\n                               subst; clear H;\n                               try (solve [apply h1; inList])\n        end).\n\n(**** Representation relation for LambdaANF values, expressions and functions ****)\nSection RELATION.\n \n  (* same as LambdaANF_to_Clight *)\n  Variable (argsIdent : ident).\n  Variable (allocIdent : ident).\n  Variable (limitIdent : ident).\n  Variable (gcIdent : ident).\n  Variable (mainIdent : ident).\n  Variable (bodyIdent : ident).\n  Variable (threadInfIdent : ident).\n  Variable (tinfIdent : ident).\n  Variable (heapInfIdent : ident).\n  Variable (numArgsIdent : ident).  \n  Variable (isptrIdent: ident). (* ident for the isPtr external function *)\n  Variable (caseIdent:ident).\n  Variable (nParam:nat).\n\n  Definition protectedIdent: list ident := (argsIdent::allocIdent::limitIdent::gcIdent::mainIdent::bodyIdent::threadInfIdent::tinfIdent::heapInfIdent::numArgsIdent::numArgsIdent::isptrIdent::caseIdent::[]).\n\n  \n\n  Variable cenv:LambdaANF.cps.ctor_env.\n  Variable fenv:LambdaANF.cps.fun_env.\n  Variable finfo_env: LambdaANF_to_Clight.fun_info_env. (* map from a function name to its type info *)\n  Variable p:program.\n  \n  (* This should be a definition rather than a parameter, computed once and for all from cenv *)\n  Variable rep_env: M.t ctor_rep.\n \n  \n  Notation threadStructInf := (Tstruct threadInfIdent noattr).\n  Notation threadInf := (Tpointer threadStructInf noattr).\n\n  Notation funTy := (Tfunction (Tcons threadInf Tnil) Tvoid\n                            {|\n                              cc_vararg := false;\n                              cc_unproto := false;\n                              cc_structret := false |}).\n\nNotation pfunTy := (Tpointer funTy noattr).\n\nNotation gcTy := (Tfunction (Tcons (Tpointer (Tint I32 Unsigned noattr) noattr) (Tcons threadInf Tnil)) Tvoid\n                            {|\n                              cc_vararg := false;\n                              cc_unproto := false;\n                              cc_structret := false |}).\n\nNotation isptrTy := (Tfunction (Tcons (Tint I32 Unsigned noattr) Tnil) (Tint IBool Unsigned noattr)\n                               {|\n                                 cc_vararg := false;\n                                 cc_unproto := false;\n                                 cc_structret := false |}).\n\n\n\n\n\n\n\nNotation valPtr := (Tpointer val\n                            {| attr_volatile := false; attr_alignas := None |}).\n\nNotation boolTy := (Tint IBool Unsigned noattr).\n\nNotation \"'var' x\" := (Etempvar x val) (at level 20).\nNotation \"'ptrVar' x\" := (Etempvar x valPtr) (at level 20).\n\nNotation \"'bvar' x\" := (Etempvar x boolTy) (at level 20).\nNotation \"'funVar' x\" := (Evar x funTy) (at level 20).\n\n\nNotation allocPtr := (Etempvar allocIdent valPtr).\nNotation limitPtr := (Etempvar limitIdent valPtr).\nNotation args := (Etempvar argsIdent valPtr).\nNotation gc := (Evar gcIdent gcTy).\nNotation ptr := (Evar isptrIdent isptrTy).\n\n\n\n(* changed tinf to be tempvar and have type Tstruct rather than Tptr Tstruct *)\nNotation tinf := (Etempvar tinfIdent threadInf).\nNotation tinfd := (Ederef tinf threadStructInf).\n\nNotation heapInf := (Tstruct heapInfIdent noattr).\n\n\nNotation \" a '+'' b \" := (add a b) (at level 30).\n\n\nNotation \" a '-'' b \" := (sub a b) (at level 30).\n\n\nNotation \" a '='' b \" := (int_eq a b) (at level 35).\n\n\nNotation \"'!' a \" := (not a) (at level 40).\n\nNotation seq := Ssequence.\n\nNotation \" p ';' q \" := (seq p q)\n                         (at level 100, format \" p ';' '//' q \").\n\nNotation \" a '::=' b \" := (Sset a b) (at level 50).\nNotation \" a ':::=' b \" := (Sassign a b) (at level 50).\n\nNotation \"'*' p \" := (Ederef p val) (at level 40).\n\nNotation \"'&' p \" := (Eaddrof p valPtr) (at level 40).\n\n\n\nNotation c_int := c_int'.\n\nNotation \"'while(' a ')' '{' b '}'\" :=\n  (Swhile a b) (at level 60).\n\nNotation \"'call' f \" := (Scall None f (tinf :: nil)) (at level 35).\n\nNotation \"'[' t ']' e \" := (Ecast e t) (at level 34).\n\nNotation \"'Field(' t ',' n ')'\" :=\n  ( *(add ([valPtr] t) (c_int n%Z val))) (at level 36). (* what is the type of int being added? *)\n\nNotation \"'args[' n ']'\" :=\n  ( *(add args (c_int n%Z val))) (at level 36).\n\nDefinition int_shru z1 z2 := if Archi.ptr64 then (Vlong (Int64.shru (Int64.repr z1) (Int64.repr z2)))\n                                                  else (Vint (Int.shru (Int.repr z1) (Int.repr z2))).\n\nDefinition int_and z1 z2 := if Archi.ptr64 then\n                              (Vlong (Int64.and (Int64.repr z1) (Int64.repr z2))) else\n                              (Vint (Int.and (Int.repr z1) (Int.repr z2))).\n\nLtac archi_red :=\n  int_red;\n  unfold sizeof in *;\n  unfold int_chunk in *;\n  unfold val in *;\n  unfold uval in *;\n  unfold val_typ in *;\n  unfold Init_int in *;\n  unfold make_vint in *;\n  unfold make_cint in *;\n  unfold int_shru in *;\n  unfold int_and in *;\n  unfold c_int in *;\n  unfold uint_range in *;\n  try (rewrite ptrofs_mu in *);\n  (match goal with\n   | [ H : Archi.ptr64 = _ |- _] => try (rewrite H in *)\n   end).\n\n(* these ltac are agnostic on archi, useful for automation *)   \n   Ltac ptrofs_of_int :=\n     unfold Ptrofs.of_int64 in *;\n     unfold ptrofs_of_int in *;\n     unfold Ptrofs.of_intu in *;\n     unfold Ptrofs.of_int in *.\n\n   Ltac int_unsigned_repr :=\n     try (rewrite Int64.unsigned_repr in *);\n     try (rewrite Int.unsigned_repr in *).\n          \n   Ltac int_max_unsigned:=  \n     unfold Int64.max_unsigned in *;\n     unfold Int.max_unsigned in *.\n\n\n\n Inductive header_of_rep: ctor_rep -> Z -> Prop :=\n | header_enum: forall t, header_of_rep (enum t) (Z.of_N ((N.shiftl t 1) + 1))\n | header_boxed: forall t a, header_of_rep (boxed t a) (Z.of_N ((N.shiftl a 10) + t)).\n\n Function var_or_funvar_f' (n : nat) (x:positive):expr :=\n   match Genv.find_symbol (Genv.globalenv p) x with\n   | Some _ =>  makeVar threadInfIdent n x fenv finfo_env\n   | None => var x\n   end.\n \n Function var_or_funvar_f (x:positive):expr :=\n   match Genv.find_symbol (Genv.globalenv p) x with\n   | Some _ =>  makeVar threadInfIdent nParam x fenv finfo_env\n   | None => var x\n   end.\n \n (* The full the domain of map is exactly the symbols of globalenv *)\n  Definition find_symbol_domain {A} (map:M.t A):=\n   forall (x:positive), (exists V1, M.get x map = Some V1) <-> (exists b, Genv.find_symbol (Genv.globalenv p) x = Some b).\n\n Definition finfo_env_correct :=\n   forall (x:positive) i t, M.get x finfo_env = Some (i , t) -> (exists finfo, M.get t fenv = Some finfo).\n  \n(* CHANGE THIS *)                                    \nInductive repr_asgn_fun': list positive -> list N -> statement -> Prop :=\n| repr_asgn_nil: repr_asgn_fun' [] [] Sskip\n| repr_asgn_cons: forall y ys i inf s, repr_asgn_fun' ys inf s ->\n                 repr_asgn_fun' (y::ys) (i::inf) (s; args[ Z.of_N i ] :::= (var_or_funvar_f y)).\n\nInductive repr_asgn_fun: list positive -> list N -> statement -> Prop :=\n  |repr_asgn_wrap: forall ys inf s, repr_asgn_fun' ys inf s ->\n                   repr_asgn_fun ys inf (argsIdent ::= Efield tinfd argsIdent (Tarray val maxArgs noattr);s).\n\nInductive repr_call_vars' (par : nat) : nat -> list positive -> list expr -> Prop :=\n| repr_call_nil : repr_call_vars' par 0 [] []\n| repr_call_cons : forall n y ys es, repr_call_vars' par n ys es ->\n                                     repr_call_vars' par (S n) (y :: ys) (var_or_funvar_f' par y :: es).\n\n\nDefinition repr_call_vars : nat -> list positive -> list expr -> Prop := repr_call_vars' nParam.\n\n(* like fromN but for Z, should move to list_util and make a generic one *)\nFixpoint fromZ (z:Z) (m:nat): list Z :=\n  match m with\n  | 0 => nil\n  | S m' => z :: (fromZ (Z.succ z) m')\n  end.\n\nFixpoint fromInt (i:int) (m:nat): list int :=\n  match m with\n  | 0 => nil\n  | S m' => i :: (fromInt (Int.add i Int.one) m')\n  end.\n\n\nTheorem fromN_Some: forall x n z l ,\n nthN (fromN l z) n = Some x ->\n x = N.add l n.\nProof.  \n  induction n using N.peano_rect; intros; simpl in H.\n  - destruct z. simpl in H. inv H.\n    simpl in H. inv H. \n    rewrite N.add_0_r. reflexivity.\n  - destruct z. simpl in H. inv H.\n    simpl in H. (destruct (N.succ n) eqn:Sn). apply N.neq_succ_0 in Sn.  inv Sn.\n    assert (n = (N.sub (N.pos p0)  1)).\n    rewrite <- Sn. rewrite <- N.pred_sub.\n    symmetry. apply N.pred_succ.\n    rewrite <- H0 in H.\n    apply IHn in H. rewrite <- Sn.\n    rewrite N.add_succ_l in H.\n    rewrite N.add_succ_r. auto.\nQed. \n    \n\n\nDefinition Forall_in_mem_block {A} : (A -> (block *  int) -> Prop) -> list A -> (block * int) -> int -> Prop :=\n  fun P ls loc z =>\n    let (b, z0) := loc in\n    let ids := fromN 0%N  (length ls) in \n    Forall2 (fun a i => P a (b, Int.add z0 (Int.mul (Int.repr (Z.of_N i)) z))) ls ids.\n\n\nTheorem Forall_in_mem_block_nthN :\n  forall {A P vs b i z v n},\n     Forall_in_mem_block P vs  (b, i) z -> \n     @nthN A vs n = Some v ->\n     P v (b, Int.add i (Int.mul (Int.repr (Z.of_N n)) z)).\nProof.\n  intros. unfold Forall_in_mem_block in H.\n  assert (Hf2 := Forall2_nthN _ _ _ _ _ H H0).\n  destruct Hf2. destruct H1.\n  apply fromN_Some in H1. simpl in H1. subst; assumption.\nQed.  \n\nInductive Forall_statements_in_seq' {A}: (BinNums.Z  -> A -> statement -> Prop) ->  list A -> statement -> BinNums.Z -> Prop :=\n| Fsis_last: forall (R: (BinNums.Z  -> A -> statement -> Prop)) n v s, R n v s -> Forall_statements_in_seq' R [v] s n\n| Fsis_cons: forall R v vs s s' n, Forall_statements_in_seq' R vs s' (Z.succ n) ->\n                                   R n v s ->  Forall_statements_in_seq' R (v::vs) (s; s') n.\n\n\n\nInductive Forall_statements_in_seq_rev {A}: (BinNums.Z  -> A -> statement -> Prop) ->  list A -> statement -> nat -> Prop :=\n| Fsir_last: forall (R: (BinNums.Z  -> A -> statement -> Prop)) v s, R 0%Z v s -> Forall_statements_in_seq_rev R [v] s 0\n| Fsir_cons: forall R v vs s s' n, Forall_statements_in_seq_rev R vs s' n ->\n                                   R (Z.of_nat (S n)) v s ->  Forall_statements_in_seq_rev R (v::vs) (s; s') (S n).\n\n\n\n\n(* This is true for R, vs and S iff forall i, R i (nth vs) (nth s)\n   > list cannot be empty (o.w. no statement)\n   > nth on statement is taken as nth on a list of sequenced statement (;) *)\nDefinition Forall_statements_in_seq {A}: (BinNums.Z  -> A -> statement -> Prop) ->  list A -> statement -> Prop :=\n  fun P vs s =>  Forall_statements_in_seq' P vs s (0%Z).\n\n(* This should sync with makeVar *)\nInductive var_or_funvar : positive -> expr -> Prop :=\n| F_VoF : forall x b,\n    Genv.find_symbol (Genv.globalenv p) x = Some b ->\n                var_or_funvar x (makeVar threadInfIdent nParam x fenv finfo_env)\n| V_VoF : forall x,\n    Genv.find_symbol (Genv.globalenv p) x = None ->\n       var_or_funvar x (var x).\n\nTheorem var_or_funvar_of_f:\n  forall x e,\n  var_or_funvar x e <-> var_or_funvar_f x = e.\nProof.\n  unfold var_or_funvar_f; split; intro.\n  inv H;  rewrite H0; auto. \n  destruct ( Genv.find_symbol (Genv.globalenv p) x) eqn:Hx; subst; econstructor; eauto.\nQed.\n  \nFixpoint Vint_or_Vptr (v:Values.val): bool :=\n  match v with\n  | Vint _ => negb Archi.ptr64 \n  | Vlong _ => Archi.ptr64 \n  | Vptr _ _ => true\n  | _ => false\n  end.\n\nInductive get_var_or_funvar (lenv: temp_env): positive -> Values.val -> Prop :=\n|F_gVoF:\n   forall b x,\n     Genv.find_symbol (Genv.globalenv p) x = Some b ->\n   get_var_or_funvar lenv x (Vptr b (Ptrofs.repr 0%Z))\n| V_gVoF:\n    forall x v,\n      Genv.find_symbol (Genv.globalenv p) x = None -> \n      M.get x lenv = Some v ->\n      Vint_or_Vptr v = true -> \n      get_var_or_funvar lenv x v.\n \n(* goes through a lists of positive l and returns a lists of Values vs for which \n Forall2 (get_var_or_fun lenv) l vs *)\nFixpoint get_var_or_funvar_list (lenv:temp_env) (l:list positive): option (list (Values.val)) :=\n  match l with\n  | nil => Some nil\n  | x::ls =>\n    (match get_var_or_funvar_list lenv ls with\n     | Some vs =>\n       (match Genv.find_symbol (Genv.globalenv p) x with\n        | Some b => Some ((Vptr b Ptrofs.zero)::vs)\n        | None =>\n          (match (M.get x lenv) with\n           | Some v =>\n             (match v with\n              | Vint _ => if Archi.ptr64 then None else Some (v::vs)\n              | Vlong _ => if Archi.ptr64 then Some (v::vs) else None\n              | Vptr _ _ => Some (v::vs)\n              | _ => None\n              end)\n           | None => None\n           end)\n        end)\n     | None => None\n     end)\n  end.\n\n\nLemma get_var_or_funvar_list_correct1:\n  forall lenv l vs, \n  get_var_or_funvar_list lenv l = Some vs ->\n  Forall2 (get_var_or_funvar lenv) l vs.\nProof.\n  induction l; intros.\n  simpl in H. inv H. constructor.\n  simpl in H.\n  destruct (get_var_or_funvar_list lenv l)  eqn:gvl.\n  specialize (IHl l0 (eq_refl _)).\n  destruct (Genv.find_symbol (Genv.globalenv p) a) eqn:gfpa.\n  - inv H.\n    constructor; auto.\n    left; auto.\n  - destruct  (M.get a lenv) eqn:gal. \n    destruct v; inv H.\n    destruct (Archi.ptr64) eqn:Harch; constructor. right; auto. auto.\n    constructor; auto. auto.\n    constructor; auto. right;  auto.  inv H.\n  - inv H.\nQed.\n\nTheorem get_var_or_funvar_list_correct2:\n  forall lenv l vs, \n    Forall2 (get_var_or_funvar lenv) l vs    ->\n    get_var_or_funvar_list lenv l = Some vs. \nProof.\n  induction l; intros.\n  - inv H. reflexivity.\n  - inv H. apply IHl in H4. simpl. rewrite H4.    \n    inv H2.\n    rewrite H.\n    reflexivity.\n    rewrite H. rewrite H0. destruct y; inv H1; auto.\nQed.\n\nTheorem get_var_or_funvar_list_correct:\n  forall lenv l vs, \n  Forall2 (get_var_or_funvar lenv) l vs    <->\n    get_var_or_funvar_list lenv l = Some vs. \nProof.\n  split. apply get_var_or_funvar_list_correct2.\n  apply get_var_or_funvar_list_correct1.\nQed.\n\n(* can be strenghten to lenv maps that are equal over l *)\nTheorem get_var_or_funvar_list_set:\n  forall lenv x v l,\n    ~ List.In x l ->\n              get_var_or_funvar_list lenv l = get_var_or_funvar_list (M.set x v lenv) l.\nProof.\n  induction l; intros.\n  - reflexivity.\n  - simpl. rewrite M.gso. rewrite IHl. reflexivity.\n    intro. apply H. constructor 2. auto. intro; apply H.\n    constructor; auto.\nQed.\n \n\nTheorem Forall2_length':\n  forall A B (R:A -> B -> Prop) l l',\n  Forall2 R l l' ->\n  length l = length l'.\nProof.\n  induction l; intros. inv H. auto.\n  inv H. apply IHl in H4. simpl; auto.\nQed.  \n  \nTheorem get_var_or_funvar_list_same_length:\n  forall lenv l vs,\n  get_var_or_funvar_list lenv l = Some vs ->\n  length l = length vs.\nProof.\n  intros. \n  apply get_var_or_funvar_list_correct in H.\n  apply Forall2_length' in H.\n  auto.\nQed.\n\n\nDefinition map_get_r_l: forall t l, relation (M.t t) := \n  fun t l => fun sub sub' => forall v,\n               List.In v l ->\n               M.get v sub = M.get v sub'.\n\nTheorem get_var_or_funvar_proper:\n  forall lenv lenv' l x v,\n  get_var_or_funvar lenv x v ->\n  map_get_r_l _ l lenv lenv' ->\n  List.In x l -> \n  get_var_or_funvar lenv' x v.\nProof.\n  intros.\n  inv H. constructor; auto.\n  constructor 2; auto. erewrite <- H0; auto.\nQed.\n\nTheorem get_var_or_funvar_int_or_ptr:\n  forall lenv y v7,\n    get_var_or_funvar lenv y v7 ->\n    Vint_or_Vptr v7 = true.\nProof.\n  intros. inv H. auto.\n  auto.\nQed.\n\n\nTheorem get_var_or_funvar_list_proper:\n  forall lenv lenv' l vs, \n  get_var_or_funvar_list lenv l = Some vs ->\n  map_get_r_l _ l lenv lenv' ->\n  get_var_or_funvar_list lenv' l = Some vs.\nProof.\n  induction l; intros.\n  simpl. simpl in H. auto.\n  simpl in H.\n  destruct (get_var_or_funvar_list lenv l) eqn:Hgll.\n  assert ( Some l0 = Some l0) by reflexivity.\n  assert (map_get_r_l Values.val l lenv lenv'). intro; intros.\n  apply H0. constructor 2; auto.\n  specialize (IHl _ H1 H2).\n  simpl. rewrite IHl.\n  destruct  (Genv.find_symbol (Genv.globalenv p) a).\n  auto.\n  rewrite <- H0. auto.\n  constructor. auto.\n  inv H.\nQed. \n  \nInductive is_nth_projection_of_x : positive -> Z -> positive -> statement -> Prop :=\n  Make_nth_proj: forall x  n v e,\n                         var_or_funvar v  e ->\n                          is_nth_projection_of_x x n v (Field(var x, n) :::=  e).\n\n\n(* this version of mem_after_n_proj casts to match is_nth_projection *)\nInductive mem_after_n_proj_store_cast : block -> Z -> (list Values.val) -> Z -> mem -> mem ->  Prop :=\n| Mem_last_c:\n    forall m b ofs i v m',\n    Mem.store int_chunk m b  (Ptrofs.unsigned (Ptrofs.add (Ptrofs.repr ofs) (Ptrofs.repr (int_size*i)))) v = Some m' ->\n    mem_after_n_proj_store_cast b ofs [v] i m m'\n| Mem_next_c:\n    forall m b ofs i v m' m'' vs,\n      Mem.store int_chunk m b (Ptrofs.unsigned (Ptrofs.add (Ptrofs.repr ofs) (Ptrofs.repr (int_size*i)))) v = Some m' ->\n      mem_after_n_proj_store_cast b ofs vs (Z.succ i) m' m'' ->\n      mem_after_n_proj_store_cast b ofs (v::vs) i m m''. \n\n\nInductive mem_after_n_proj_store : block -> Z -> (list Values.val) -> Z -> mem -> mem ->  Prop :=\n| Mem_last:\n    forall m b ofs i v m',\n    Mem.store int_chunk m b  (ofs + (int_size*i)) v = Some m' ->\n    mem_after_n_proj_store b ofs [v] i m m'\n| Mem_next:\n    forall m b ofs i v m' m'' vs,\n      Mem.store int_chunk m b (ofs + (int_size*i)) v = Some m' ->\n      mem_after_n_proj_store b ofs vs (Z.succ i) m' m'' ->\n      mem_after_n_proj_store b ofs (v::vs) i m m''. \n\n(* represent work \"already done\" while consuming mem_after_n_proj *)\nInductive mem_after_n_proj_snoc :  block -> Z -> (list Values.val)  -> mem -> mem ->  Prop :=\n| Mem_nil_snoc: forall m b ofs, \n    mem_after_n_proj_snoc b ofs [] m m\n| Mem_cons_snoc: forall m b ofs m' m'' v vs,\n    mem_after_n_proj_snoc b ofs vs m m' ->\n    Mem.store int_chunk m' b (ofs + (int_size*(Z.of_nat (length vs)))) v = Some m'' ->\n    mem_after_n_proj_snoc b ofs (v::vs) m m''.\n\n\n\n\nTheorem  mem_after_n_proj_store_snoc:\n  forall b ofs vs1 m m1, \n  mem_after_n_proj_snoc b ofs vs1 m m1 ->\nforall vs2 m',\n  mem_after_n_proj_store b ofs vs2 (Z.of_nat (length vs1)) m1 m' ->\n  forall vs,\n    List.app (rev vs1) vs2 = vs -> \n    mem_after_n_proj_store b ofs vs 0 m m'.\nProof.\n  induction vs1; intros.\n  - simpl in H1; subst. simpl in H0. inv H. auto.\n  -   simpl in H1. inv H.\n      rewrite <- app_assoc. eapply IHvs1. apply H6. 2: reflexivity.\n      simpl.\n      simpl length in H0. rewrite Nat2Z.inj_succ in H0.\n      econstructor; eauto.\nQed.\n \nTheorem  mem_after_n_proj_store_snoc':\n  forall b ofs vs m m',\n    mem_after_n_proj_store b ofs vs 0 m m' ->\n    forall vs1 vs2,\n      vs2 <> nil ->\n      List.app (rev vs1) vs2 = vs ->\n      exists m1, \n  mem_after_n_proj_snoc b ofs vs1 m m1 /\\ \n  mem_after_n_proj_store b ofs vs2 (Z.of_nat (length vs1)) m1 m'.\nProof.\n  intros b ofs vs m m' Hmm'.\n  induction vs1; intros.\n  -  simpl in H0; subst. exists m. simpl. split.\n     constructor. auto.\n  - simpl in H0. rewrite <- app_assoc in H0. apply IHvs1 in H0. destruct H0. destruct H0.\n    simpl in H1.\n    inv H1. (* impossible, vs2 is not empty *)  exfalso; auto.\n    exists m'0. split. econstructor; eauto. simpl length. rewrite Nat2Z.inj_succ. auto. intro. inv H1.\nQed.    \n      \n    \n\n\n  (*\ntodo:\nTheorem mem_after_n_proj_store_snoc:\n  forall b ofs,\n  forall vs1 vs2, \n    List.app (rev vs1) vs2 = vs ->\n    forall vs m m' i,\n      mem_after_n_proj_store b ofs vs i m m' ->\n      exists m1,\n        mem_after_n_proj_snoc b ofs vs1 m m1  /\\\n        mem_after_n_proj_store b ofs vs2 (Z.of_nat (length (rev vs1))) m1 m'.\n*)\n    \n      \nTheorem mem_after_n_proj_wo_cast:\n  forall vs b ofs i m m', \n\n  (0 <= ofs)%Z -> (0 <= i)%Z ->\n   (uint_range (ofs+int_size*(i+(Z.of_nat (length vs)))))%Z ->\n      mem_after_n_proj_store_cast b ofs vs i m m' <-> mem_after_n_proj_store b ofs vs i m m'. \nProof.\n  induction vs; intros.\n  { (* impossible *) split; intro; inv H2. }\n  assert (ofs + int_size * i  = Ptrofs.unsigned (Ptrofs.add (Ptrofs.repr ofs) (Ptrofs.repr (int_size * i))))%Z.\n  assert (0 <=  int_size * (i + Z.of_nat (length (a::vs)))<= Ptrofs.max_unsigned)%Z.\n  unfold int_size in *. simpl size_chunk in *.\n  inv H1. assert (Hisp := int_size_pos).\n  split. apply Z.mul_nonneg_nonneg; auto.  omega. omega.\n  rewrite Ptrofs.add_unsigned.\n  unfold int_size in *.\n  simpl size_chunk in *.\n  inv H1.\n  rewrite Ptrofs.unsigned_repr with (z := ofs).\n  rewrite Ptrofs.unsigned_repr with (z := (_ * i)%Z).\n  rewrite Ptrofs.unsigned_repr.\n  reflexivity. split.\n  assert (Hisp := int_size_pos).\n  apply Z.add_nonneg_nonneg; auto. \n  apply Z.mul_nonneg_nonneg; auto.\n  chunk_red; omega.\n  chunk_red; omega.\n  omega.\n  simpl length in H1.\n  rewrite Nat2Z.inj_succ in H1.  \n  rewrite Z.add_succ_r in H1.\n  split; intro; inv H3.\n  - constructor. rewrite H2. auto.\n  - econstructor. rewrite H2. apply H8.\n    rewrite <- IHvs; auto. omega.\n    rewrite Z.add_succ_l.\n    apply H1.    \n  - constructor. rewrite <- H2. auto.\n  - econstructor. rewrite <- H2. apply H8.\n    rewrite IHvs; auto. omega.\n    rewrite Z.add_succ_l.\n    apply H1.\nQed. \n\n\n(* mem_after_n_proj_store_load *)\n\nTheorem mem_after_n_proj_store_load:\n  forall b ofs vs i m m', \n    mem_after_n_proj_store b ofs vs i m m' ->\n    forall ofs' b',\n      ( b' <> b \\/\n        (ofs' + int_size <= ofs + int_size * i)%Z \\/\n        (ofs + int_size * (1+(i+(Z.of_nat (length vs)))) <= ofs')%Z) ->\n      Mem.load int_chunk m' b' ofs' = Mem.load int_chunk m b' ofs'.\nProof.\n  induction vs; intros; inv H.\n  - eapply Mem.load_store_other.\n    apply H8.\n    unfold int_size in *.\n    rewrite <- Zred_factor3 in H0.\n    rewrite Z.add_assoc in H0.\n    simpl length in H0. simpl Z.of_nat in H0.\n    inv H0; auto.\n    inv H; auto.\n    right; right.\n    rewrite Z.add_comm with (n := i) in H0.\n    rewrite  <- Zred_factor3 in H0.\n    rewrite Z.add_assoc in H0.  simpl size_chunk in H0. assert (Hisp := int_size_pos). omega.\n  - eapply IHvs in H9.\n     symmetry.\n     erewrite <- Mem.load_store_other.  \n     symmetry. apply H9. apply H5.\n     { destruct H0; auto.\n       unfold int_size in *.\n       destruct H; auto.\n       right. right.\n       simpl length in H.\n       rewrite Nat2Z.inj_succ in H.\n       chunk_red ; omega. \n     }\n     {\n       assert (Hisp := int_size_pos). \n       unfold int_size in *.\n       simpl size_chunk in *.\n       simpl length in H0.\n       rewrite Nat2Z.inj_succ in H0.\n       destruct H0; auto.\n       destruct H. right. left. chunk_red; omega. \n       right. right. chunk_red; omega. \n     }\nQed.\n\n \n(* mem_after_n_proj_store on area in comp(L) leaves m unchanged on L (or any area unaffected by the proj stored *)\nTheorem mem_after_n_proj_store_unchanged:\n  forall L b ofs vs i m m',\n    mem_after_n_proj_store b ofs vs i m m' ->\n  (forall j, (ofs+int_size*i) <= j < ofs+int_size*(i + Z.of_nat (length vs)) ->  ~ L b j)%Z -> \n  Mem.unchanged_on L m m'.\nProof.\n  induction vs; intros; inv H.\n  - eapply Mem.store_unchanged_on; eauto.\n    intros.\n    apply H0.\n    unfold int_size in *.\n    simpl length. simpl Z.of_nat.    \n    chunk_red; omega.\n  - apply Mem.unchanged_on_trans with (m2 := m'0).\n    + eapply Mem.store_unchanged_on; eauto.\n      intros. apply H0.\n      simpl length.\n      rewrite Nat2Z.inj_succ.\n      chunk_red;\n      omega.\n    + eapply IHvs; eauto.\n      intros. apply H0.\n      simpl length.\n      rewrite Nat2Z.inj_succ.\n      chunk_red;\n      omega.\nQed.\n\nTheorem mem_after_n_proj_snoc_unchanged:\n  forall L b ofs vs  m m',\n    mem_after_n_proj_snoc b ofs vs m m' ->\n  (forall j, ofs <= j < ofs+int_size*(Z.of_nat (length vs)) ->  ~ L b j)%Z -> \n  Mem.unchanged_on L m m'.\nProof.\n  induction vs.\n  - intros. inv H. apply Mem.unchanged_on_refl.\n  - intros. inv H.\n    apply Mem.unchanged_on_trans with (m2 := m'0).\n    + apply IHvs in H5; auto.\n      simpl length in H0.\n      rewrite Nat2Z.inj_succ in H0.        intros. apply H0. chunk_red; omega.\n    + eapply Mem.store_unchanged_on; eauto.\n      intros.\n      simpl length in H0.\n      rewrite Nat2Z.inj_succ in H0. intros. apply H0. chunk_red;\n      omega. \nQed.\n\n\nDefinition prefix_ctx {A:Type} rho' rho :=\n  forall x v, M.get x rho' = Some v -> @M.get A x rho = Some v.\n\n\n\n(* keep around the fact that t is no bigger than 2^(int_size-1) [which we know by correct_crep] *)\n Definition repr_unboxed_Codegen: N -> Z -> Prop :=\n   fun t => fun h =>\n              (h = (Z.shiftl (Z.of_N t) 1) + 1)%Z /\\\n              (0 <= (Z.of_N t)  <  Ptrofs.half_modulus )%Z.\n\n Theorem repr_unboxed_eqm: forall h t,\n     repr_unboxed_Codegen t h -> \n   Ptrofs.eqm h (Z.of_N ((N.shiftl t 1) + 1)).\n Proof.\n   intros. inv H.\n   rewrite OrdersEx.Z_as_DT.shiftl_mul_pow2; try omega.\n   simpl.\n   rewrite N.shiftl_mul_pow2.\n   rewrite N2Z.inj_add.\n   rewrite N2Z.inj_mul.\n   simpl.\n   rewrite Z.pow_pos_fold.\n   rewrite Pos2Z.inj_pow.  apply Ptrofs.eqm_refl.\n Qed.   \n SearchAbout Int.max_signed.\n\n Theorem nat_shiftl_p1:\n   forall n z,\n     1 < z ->\n n  < (z / 2) ->\n n * 2 + 1 < z.\n Proof.\n   induction n; intros.\n   simpl. auto.\n   simpl.\n   destruct z. inv H0. destruct z.\n   - inv H0. \n   - rewrite <- Nat.div2_div in H0. simpl in H0. rewrite Nat.div2_div in H0. \n     apply lt_S_n in H0.\n     assert (Hz := NPeano.Nat.lt_decidable 1 z). inv Hz.\n     specialize (IHn _ H1 H0). omega.\n     destruct z.\n       (* case 0 *) inv H0. inv H.\n     destruct z.\n     (* case 1 *) inv H0. \n     exfalso. apply H1. omega.\n Qed.\n\n Theorem pos_nat_div2 : forall p,\n    p <> xH ->\n  Pos.to_nat (Pos.div2 p) = Nat.div2 (Pos.to_nat p).\n Proof.\n   intros. destruct p0.\n   - simpl Pos.div2.\n     rewrite Pos2Nat.inj_xI.\n     rewrite Nat.div2_succ_double. reflexivity.\n   - simpl Pos.div2.\n     rewrite Pos2Nat.inj_xO.\n     rewrite Div2.div2_double. reflexivity.\n   - exfalso. apply H; auto.\n Qed.\n \n Theorem Div2_Z_to_nat: forall n,\n     (0 <= n)%Z ->\n    Z.to_nat (Z.div2 n) = Nat.div2 (Z.to_nat n).\n Proof.\n   induction n; intros.\n   - reflexivity.\n   -  simpl. destruct p0.\n      rewrite Z2Nat.inj_pos. \n      rewrite pos_nat_div2. reflexivity.\n      intro. inv H0.\n      rewrite Z2Nat.inj_pos. \n      rewrite pos_nat_div2. reflexivity.\n      intro. inv H0.\n      reflexivity.      \n   - assert (Hp0 := Zlt_neg_0 p0). exfalso. omega.\n Qed.\n   \n   \n   \n Theorem repr_unboxed_header_range:\n   forall t h,\n     repr_unboxed_Codegen t h ->\n     (0 <= h <= Ptrofs.max_unsigned)%Z.\n Proof. \n   intros. inv H.   \n   unfold Ptrofs.max_unsigned.\n   unfold Ptrofs.half_modulus in *.\n   \n   unfold Ptrofs.modulus in *.\n   rewrite OrdersEx.Z_as_DT.shiftl_mul_pow2; try omega.\n   rewrite Z.pow_1_r.\n   split; try omega.\n\n   rewrite Z.sub_1_r.\n   rewrite <- ReflOmegaCore.Z_as_Int.le_lt_int.\n   destruct H1.\n   unfold Ptrofs.wordsize in *. unfold Wordsize_Ptrofs.wordsize in *. \n   assert (Hws:(0 <= Zpower.two_power_nat (if Archi.ptr64 then 64%nat else 32%nat))%Z).\n   {     \n     assert (Hws' := Coqlib.two_power_nat_pos (if Archi.ptr64 then 64%nat else 32%nat)). omega.\n   }\n   rewrite Z2Nat.inj_lt; try omega. rewrite Z2Nat.inj_lt in H0; try omega.\n   rewrite Z2Nat.inj_add in * by omega.\n   rewrite Z2Nat.inj_mul in * by omega.\n   rewrite <- Z.div2_div in H0.\n   rewrite Div2_Z_to_nat in H0.\n   rewrite Nat.div2_div in H0.\n   eapply nat_shiftl_p1.\n   chunk_red; simpl; rewrite <- Pos2Nat.inj_1;\n     apply nat_of_P_lt_Lt_compare_morphism; auto.\n   auto. auto.\n Qed.\n\n\n\n Theorem repr_unboxed_shiftr:\n   forall t h, \n   repr_unboxed_Codegen t h ->\n   Z.shiftr h 1 =  Z.of_N t.\n Proof.\n   intros.\n   inv H.\n   rewrite Ptrofs.Zshiftl_mul_two_p by omega.\n   unfold Z.shiftr. \n   simpl Z.shiftl.\n   unfold Zpower.two_power_pos. simpl.\n   rewrite Zdiv.Zdiv2_div. \n   replace (Z.of_N t * 2 + 1)%Z with (OrdersEx.Z_as_OT.b2z true + 2 * (Z.of_N t))%Z by (simpl OrdersEx.Z_as_OT.b2z; omega).\n   apply OrdersEx.Z_as_OT.add_b2z_double_div2.\nQed.\n \n\nDefinition boxed_header: N -> N -> Z -> Prop :=\n  fun t => fun a =>  fun h =>\n                       (h =  (Z.shiftl (Z.of_N a) 10) + (Z.of_N t))%Z /\\\n                       (0 <= Z.of_N t <  Zpower.two_power_pos 8)%Z /\\\n                       (0 <= Z.of_N a <  Zpower.two_power_nat (Ptrofs.wordsize - 10))%Z.\n\nTheorem repr_boxed_header_range:\n   forall t a h,\n     boxed_header t a h ->\n     (0 <= h <= Ptrofs.max_unsigned)%Z.\n Proof.\n   intros. inv H.\n   rewrite  OrdersEx.Z_as_DT.shiftl_mul_pow2.\n   destruct H1.\n   rewrite Zpower.two_power_pos_correct in *.\n   rewrite Zpower.two_power_nat_correct in *.\n   simpl in *.\n   unfold Z.pow_pos in *.\n   2: omega.\n   split. \n   - apply Z.add_nonneg_nonneg.\n     apply Z.mul_nonneg_nonneg. omega. simpl; omega.\n     omega.\n   - (* moving to pos then computing by archi *)\n     unfold Ptrofs.max_unsigned. unfold Ptrofs.modulus. \n     unfold Ptrofs.wordsize in *.\n     unfold Wordsize_Ptrofs.wordsize in *. \n     chunk_red; simpl in *. omega. omega.\nQed. \n \nTheorem div2_iter_pos:\n  forall p0 a, \n    (0 <= a -> 0 <= Pos.iter Z.div2 a p0)%Z.\nProof.\n  induction p0; intros.\n  - simpl.\n    rewrite OrdersEx.Z_as_OT.div2_nonneg.\n    apply IHp0. apply IHp0. auto.\n  - simpl. apply IHp0. apply IHp0.\n    auto.\n  - simpl; rewrite OrdersEx.Z_as_OT.div2_nonneg; auto.\nQed.\n\n\nTheorem mul2_iter_pos:\n  forall p0 a, \n    (0 <= a -> 0 <= Pos.iter (Z.mul 2) a p0)%Z.\nProof.\n  induction p0; intros.\n  - simpl. destruct (Pos.iter (Z.mul 2) (Pos.iter (Z.mul 2) a p0) p0) eqn:Hp.\n    * reflexivity.\n    * apply Pos2Z.is_nonneg.\n    * exfalso.\n      assert (0 <=  Pos.iter (Z.mul 2) (Pos.iter (Z.mul 2) a p0) p0)%Z.\n      apply IHp0. apply IHp0. auto.\n      rewrite Hp in H0.\n      assert (Hneg := Pos2Z.neg_is_neg p1).\n      omega.\n  - simpl. apply IHp0. apply IHp0. auto.\n  - simpl. destruct a; try omega.\n    apply Pos2Z.is_nonneg.\n    exfalso.\n    assert (Hneg := Pos2Z.neg_is_neg p0).\n    omega.\nQed.\n\n\nTheorem pos_iter_xI: forall A f (a:A) p,\n  Pos.iter f (a)%Z p~1 = f (Pos.iter f (Pos.iter f a p)%Z p).\nProof.\n  intros. simpl. reflexivity.\nQed.\n\nTheorem pos_iter_xH: forall A f (a:A),\n  Pos.iter f (a)%Z 1 = f a.\nProof.\n  intros. simpl. reflexivity.\nQed.\n \nTheorem pos_iter_xO: forall A f (a:A) p,\n  Pos.iter f (a)%Z p~0 = (Pos.iter f (Pos.iter f a p)%Z p).\nProof.\n  intros. simpl. reflexivity.\nQed.\n\nSearchAbout Z.div2 Z.add.\n\n\nTheorem div2_even_add:\n  forall a b,\n    (Z.odd a = false ->\n   Z.div2 (a + b) = Z.div2 a + Z.div2 b)%Z.\nProof.\n  intros.\n  repeat (rewrite Z.div2_div).\n  rewrite Z.div2_odd with (a := b).\n  rewrite Z.add_assoc.\n  rewrite Z.add_carry_div2.\n  rewrite <- Z.div2_odd with (a := b).\n  repeat (rewrite Z.bit0_odd).\n  rewrite H.\n  rewrite <- Z.bit0_odd.\n  rewrite Z.testbit_even_0.\n  replace  (Z.b2z (false && false || Z.odd b && (false || false))) with 0%Z.\n  rewrite Z.mul_comm.\n  rewrite Zdiv.Z_div_mult. \n  rewrite Z.add_0_r.\n  rewrite Z.div2_div. reflexivity.\n  omega.\n  destruct (Z.odd b); simpl; reflexivity.\nQed.\n\n\n\nTheorem shiftl_add_nonneg:\n  forall c a b,\n   ( 0 <= a ->\n    0 <= b ->\n     0 <= c ->\n    Z.shiftl (a + b) c = Z.shiftl a c + Z.shiftl b c)%Z.\nProof. \n  destruct c; intros.\n  reflexivity.\n  - simpl.\n    revert dependent a. revert dependent b.\n    clear H1. revert p0.\n    induction p0; intros. \n    + do 3 (rewrite pos_iter_xI).\n      rewrite <- Z.mul_add_distr_l.\n      rewrite <- IHp0.\n      rewrite <- IHp0.\n      reflexivity.\n      auto. auto.\n      apply mul2_iter_pos; auto.\n      apply mul2_iter_pos; auto.\n    + simpl. rewrite IHp0.\n      rewrite IHp0.\n      reflexivity.\n      apply mul2_iter_pos; auto.\n      apply mul2_iter_pos; auto.\n      auto. auto.\n    + do 3 (rewrite pos_iter_xH).\n      apply Z.mul_add_distr_l.\n  - simpl.\n    exfalso.\n    assert (Hneg := Pos2Z.neg_is_neg p0). omega.\nQed.\n\n\n\nTheorem iter_div_testbit_decompose:\n  (forall c a b,\n      (forall d, (0 <= d < (Z.pos c))%Z ->\n                 Z.testbit a d = false) ->\n      Pos.iter Z.div2 (a + b) c =\n      Pos.iter Z.div2 a c + Pos.iter Z.div2 b c)%Z.\nProof.\n  induction c; intros.\n  - do 3 (rewrite pos_iter_xI).\n    assert (Hrw := Z.shiftr_spec).\n    rewrite IHc.\n    rewrite IHc.\n    rewrite div2_even_add. reflexivity.\n    rewrite <- Z.bit0_odd. \n    assert (Hrw' := Hrw).\n    specialize (Hrw (Pos.iter Z.div2 a c) (Z.pos c)).\n    unfold Z.shiftr in Hrw. simpl in Hrw.\n    rewrite Hrw by omega.\n    specialize (Hrw' a (Z.pos c)). rewrite Hrw'.\n    simpl Z.add.\n    apply H. split.\n    apply Pos2Z.pos_is_nonneg.\n    rewrite Pos.add_diag.\n    rewrite Pos2Z.inj_xI.\n    rewrite Pos2Z.inj_xO. omega.\n    simpl.\n    apply Pos2Z.pos_is_nonneg.\n    specialize (Hrw a (Z.pos c)).\n    unfold Z.shiftr in Hrw. simpl in Hrw.\n    intros. \n    rewrite Hrw. apply H.\n    rewrite Pos2Z.inj_xI.\n    omega. omega.\n    intros. apply H.\n    rewrite Pos2Z.inj_xI. omega.\n  - rewrite pos_iter_xO.    \n    rewrite IHc.\n    rewrite pos_iter_xO.\n    rewrite pos_iter_xO.\n    2:{ intros. apply H.\n    rewrite Pos2Z.inj_xO.\n    assert (0 < Z.pos c)%Z by apply Pos2Z.is_pos.\n    omega. }\n    rewrite IHc. reflexivity.\n    intros.\n    assert (Hrw := Z.shiftr_spec).\n    specialize (Hrw a (Z.pos c)). unfold Z.shiftr in Hrw.\n    simpl in Hrw.  rewrite Hrw. \n    2:{ destruct H0. auto. }\n    apply H.\n    rewrite Pos2Z.inj_xO. omega.\n  - repeat (rewrite pos_iter_xH).\n    rewrite div2_even_add. reflexivity.\n    rewrite <- Z.bit0_odd.\n    apply H. omega.\nQed.\n\nCorollary shiftr_testbit_decompose:\n  (forall c a b,\n      (forall d, (0 <= d < (Z.pos c))%Z ->\n                 Z.testbit a d = false) ->\n      Z.shiftr (a + b) (Z.pos c) =\n      Z.shiftr a (Z.pos c) + Z.shiftr b (Z.pos c))%Z.\nProof.\n  intros. unfold Z.shiftr. simpl.\n  apply iter_div_testbit_decompose; auto.\nQed.\n\n \nTheorem shiftr_bounded_decompose:\n  forall a b c,\n  (0 <= a ->\n  0 < c ->\n  (0 <= b < Zpower.two_p c) ->\n  Z.shiftr ((Z.shiftl a c) + b) c = a)%Z.\nProof.\n  intros.\n  destruct c.\n  (* impossible cases *)\n  inv H0.\n  2:{ exfalso.\n  assert (Hneg:= Pos2Z.neg_is_neg p0). omega. }\n  rewrite shiftr_testbit_decompose.\n  rewrite Z.shiftr_shiftl_l.\n  rewrite Z.sub_diag. simpl.\n  \n  rewrite Int.Zshiftr_div_two_p.\n  rewrite Zdiv.Zdiv_small. omega.\n  auto.\n  omega.\n  omega.\n  intros.\n  apply Z.shiftl_spec_low. destruct H2. auto.\nQed.\n\nTheorem repr_boxed_a:\n   forall a t h, \n     boxed_header t a h ->\n   Z.shiftr h 10 =  Z.of_N a.\nProof.\n  intros.\n  inv H.\n  destructAll.\n  rewrite shiftr_bounded_decompose; auto.\n  omega. simpl.\n  split; auto.  \n  rewrite Zpower.two_power_pos_equiv in *.\n  simpl in *. unfold Z.pow_pos in *. simpl in *.\n  omega.\nQed.\n\nTheorem pos_testbit_impossible:\n  forall b, \n  ~ (forall d : N, (0 <= d)%N -> Pos.testbit b d = false).\nProof.\n  induction b; intro.\n  - apply IHb; intros.\n    assert ( 0 <= 0)%N by reflexivity.\n    apply H in H1. inv H1.\n  - apply IHb.\n    intros.    \n    simpl in H.    \n    assert (0 <= (N.pos (N.succ_pos d)))%N.\n    apply N.lt_le_incl.\n    unfold N.lt. reflexivity. \n    apply H in H1.\n    rewrite N.pos_pred_succ in H1.\n    auto.\n  - assert (0 <= 0)%N.\n    reflexivity.\n    apply H in H0. inv H0.    \nQed.\n\nTheorem pos_testbit_nat_impossible:\n  forall b,\n  ~(forall d : nat, 0 <= d -> Pos.testbit_nat b d = false).\nProof.\n  induction b; intro.\n  - apply IHb; intros.\n    assert ( 0 <= 0) by reflexivity.\n    apply H in H1. inv H1.\n  - apply IHb.\n    intros.    \n    simpl in H.    \n    assert (0 <= S d) by omega.\n    apply H in H1.\n    auto.\n  - assert (0 <= 0).\n    reflexivity.\n    apply H in H0. inv H0.    \nQed.\n\nTheorem N_lt_pos:  \n  forall p, (0 < N.pos p)%N.\nProof.\n  intro.\n  apply N2Z.inj_lt.\n  simpl.\n  apply Pos2Z.is_pos.\nQed.\n     \nTheorem pos_testbit_false_xI:\n  forall b, \n  (forall d : N, (1 <= d)%N -> Pos.testbit b~1 d = false) ->\n  (forall d : N, (0 <= d)%N -> Pos.testbit b d = false).\nProof.\n  intros.\n  assert (1 <= (N.pos (N.succ_pos d)))%N.\n  apply N2Z.inj_le.\n  apply Z.lt_pred_le.\n  simpl.\n  apply Pos2Z.is_pos.   \n  apply H in H1.\n  simpl in H1.\n  rewrite N.pos_pred_succ in H1.\n  auto.\nQed.  \n \nTheorem pos_testbit_false_xO:\n  forall b, \n  (forall d : N, (1 <= d)%N -> Pos.testbit b~0 d = false) ->\n  (forall d : N, (0 <= d)%N -> Pos.testbit b d = false).\nProof.\n  intros.\n  assert (1 <= (N.pos (N.succ_pos d)))%N.\n  apply N2Z.inj_le.\n  apply Z.lt_pred_le.\n  simpl.\n  apply Pos2Z.is_pos.   \n  apply H in H1.\n  simpl in H1.\n  rewrite N.pos_pred_succ in H1.\n  auto.\nQed.\n\n\n\nTheorem pland_split_nat:\n  forall c a b,\n  (forall d, d < c -> Pos.testbit_nat a d = false) -> \n  (forall d, c <= d -> Pos.testbit_nat b d = false) ->\n                Pos.land a b = 0%N.\nProof.\n  induction c; intros.\n  - apply pos_testbit_nat_impossible in H0.\n    inv H0.\n  - destruct a.\n    + (* impossible: a needs to be 0 on lower bits *)\n      assert (0 < S c) by omega.\n      apply H in H1.\n      inv H1.\n    + destruct b.\n      * simpl.\n        rewrite IHc; intros.\n        reflexivity.\n        simpl in H.\n        assert (S d < S c) by omega.\n        apply H in H2. auto.\n        assert (S c <= S d) by omega.\n        apply H0 in H2.\n        simpl in H2. auto.\n      * simpl.\n        rewrite IHc; intros.\n        reflexivity.\n        simpl in H.\n        assert (S d < S c) by omega.\n        apply H in H2. auto.\n        assert (S c <= S d) by omega.\n        apply H0 in H2.\n        simpl in H2. auto.\n      * reflexivity.\n    + (* impossible: a needs to be 0 on lower bits *)\n      assert (0 < S c) by omega.\n      apply H in H1.\n      inv H1.\nQed.\n\n\n\n\nTheorem repr_boxed_t:\n   forall a t h, \n     boxed_header t a h ->\n   Z.land h 255 =  Z.of_N t.\nProof.\n  intros. inv H.\n  apply Z.bits_inj.\n  unfold Z.eqf.\n  intro.\n  destruct H1.\n  rewrite Z.land_spec.\n  assert (Hcase_z:= Z.lt_ge_cases n 0%Z).\n  destruct Hcase_z as [Hnz | Hnz].\n  { (* testbit = false *)\n    destruct n. exfalso; omega.\n    exfalso. assert (0 < Z.pos p0)%Z by apply Pos2Z.pos_is_pos. omega.\n    reflexivity.\n  }    \n  \n  assert (Hcase := Z.lt_ge_cases n 8%Z).\n\n  destruct Hcase.\n  - replace 255%Z with (Z.pred (2^8))%Z.\n    rewrite <- Z.ones_equiv. \n    rewrite Z.ones_spec_low.\n    rewrite Bool.andb_true_r.\n    rewrite Z.add_nocarry_lxor.\n    rewrite Z.lxor_spec.\n    rewrite OrdersEx.Z_as_OT.shiftl_spec_low.\n    rewrite Bool.xorb_false_l.\n    reflexivity. omega.\n    (* multiple cases depending of if one is 0 or not *)\n    {\n      destruct (Z.shiftl (Z.of_N a) 10) eqn:Ha.\n      - reflexivity.\n      - destruct (Z.of_N t) eqn:Hb.\n        + reflexivity.\n        + simpl.\n          rewrite pland_split_nat with (c := 8). reflexivity.\n          * intros.\n            rewrite <- Ndigits.Ptestbit_Pbit.            \n            destruct d. simpl.\n            destruct (Z.of_N a). simpl in Ha.\n            assert (0 < Z.pos p0)%Z by apply Pos2Z.pos_is_pos. omega.\n            simpl in Ha. inv Ha. reflexivity.\n            inv Ha. \n            replace false with\n                (Z.testbit (Z.pos p0)  (Z.of_nat (S d))).\n            reflexivity.\n            rewrite <- Ha.\n            apply Z.shiftl_spec_low.\n            apply Nat2Z.inj_lt in H2.\n            simpl Z.of_nat in *. omega.\n          * intros.\n            rewrite Zpower.two_power_pos_nat in H.\n            rewrite <- Ndigits.Ptestbit_Pbit.            \n            destruct d. exfalso; omega.\n            replace false with\n                (Z.testbit (Z.pos p1)  (Z.of_nat (S d))). reflexivity.\n            eapply Int.Ztestbit_above.\n            apply H.\n            apply Nat2Z.inj_le in H2.\n            replace (Pos.to_nat 8) with 8.\n            omega. reflexivity.\n        + destruct t; inv Hb.\n      - exfalso.\n        destruct H0.\n        rewrite <- Z.shiftl_nonneg with (n := 10%Z) in H0.\n        rewrite Ha in H0.       \n        assert (Hnn := Zlt_neg_0 p0). omega.\n    }\n    \n    \n    omega.\n    simpl. reflexivity.\n  - (* always false *)\n    rewrite Bool.andb_false_intro2.\n    symmetry.\n    eapply Byte.Ztestbit_above with (n := 8).\n    rewrite Zpower.two_power_nat_correct. \n    rewrite Zpower.two_power_pos_correct in *.\n    unfold Z.pow_pos in H. simpl in *.\n    omega.\n    simpl. omega.\n    eapply Byte.Ztestbit_above with (n := 8).\n    rewrite Zpower.two_power_nat_correct. simpl. omega.\n    simpl. omega.\nQed.    \n  \n\n  \n  \n\nDefinition arity_of_header (h:Z): N :=\n  Z.to_N (Z.shiftr h 10).\n\nDefinition tag_of_header (h:Z): N :=\n    Z.to_N (Z.land h 255).\n\n\n\nInductive repr_asgn_constr: positive -> ctor_tag -> list positive -> statement -> Prop :=\n| Rconstr_ass_boxed: forall x (t:ctor_tag) vs s a n h,\n    (* boxed x *)   \n    M.get t rep_env = Some (boxed n a) ->\n    boxed_header n a h -> \n    Forall_statements_in_seq (is_nth_projection_of_x x) vs s -> \n    repr_asgn_constr x t vs (x ::= [val] (allocPtr +' (c_int Z.one val));\n                                     allocIdent ::= allocPtr +'\n                                           (c_int (Z.of_N (a + 1)) val); Field(var x, -1) :::= c_int h val;  s)\n| Rconstr_ass_enum: forall x t n h,\n    (* unboxed x *)\n    M.get t rep_env  = Some (enum n) ->\n    repr_unboxed_Codegen n h  ->\n    repr_asgn_constr x t nil (x ::= c_int h val).\n\n\nInductive repr_switch_LambdaANF_Codegen: positive -> labeled_statements -> labeled_statements -> statement -> Prop :=\n| Mk_switch: forall x ls ls',\n    repr_switch_LambdaANF_Codegen x ls ls'\n                      (isPtr isptrIdent caseIdent x;\n                         Sifthenelse\n                           (bvar caseIdent)\n                           (Sswitch (Ebinop Oand (Field(var x, -1)) (make_cint 255 val) val) ls)\n                           (\n                             Sswitch (Ebinop Oshr (var x) (make_cint 1 val) val)\n                                     ls')).\n\n(* relate a LambdaANF.exp -| ctor_env, fun_env to a series of statements in a clight program (passed as parameter) -- syntactic relation that shows the right instructions have been generated for functions body. There should not be function definitions (Efun), or primitive operations (they are not supported by our backend) in this \nTODO: maybe this should be related to a state instead? \n *)\n\n(* CHANGE THIS (relational version from translate body) *)\nInductive repr_expr_LambdaANF_Codegen: LambdaANF.cps.exp -> statement -> Prop :=\n| Rconstr_e:\n    forall x t vs  s s' e, \n    repr_asgn_constr x t vs s -> \n    repr_expr_LambdaANF_Codegen e  s' ->\n    repr_expr_LambdaANF_Codegen (Econstr x t vs e)  (s; s')    \n| Rproj_e: forall x t n v e  s,\n    repr_expr_LambdaANF_Codegen e  s ->\n    repr_expr_LambdaANF_Codegen (Eproj x t n v e)  (x ::= Field(var v, Z.of_N n) ; s)\n| R_app_e: forall f inf ainf ys ays bys pnum (t : fun_tag) s1 s2,\n    (* 1 - assign vs to the right args acording to fenv(f)*)\n    M.get t fenv = Some inf ->\n    ays = skipn nParam ys ->\n    bys = firstn nParam ys ->\n    ainf = skipn nParam (snd inf) ->\n    repr_asgn_fun ays ainf s1 ->\n    pnum = min (N.to_nat (fst inf)) nParam ->\n    repr_call_vars pnum bys s2 ->\n    (* 2 - call f *)\n    (* NOTE: added redundant limitIdent |-> limitPtr to avoid having to carry this info around, but could optimize it away *)\n    repr_expr_LambdaANF_Codegen (Eapp f t ys) (s1; Efield tinfd allocIdent valPtr :::= allocPtr ; Efield tinfd limitIdent valPtr  :::= limitPtr ;\n                                      (Scall None ([Tpointer (mkFunTy threadInfIdent pnum) noattr] (var_or_funvar_f f)) ((Etempvar tinfIdent threadInf) :: s2)))\n| R_halt_e: forall v e,\n    (* halt v <-> end with v in args[1] *)\n    var_or_funvar v e -> \n    repr_expr_LambdaANF_Codegen (Ehalt v)  (args[Z.of_nat 1 ] :::= e)\n| Rcase_e: forall v cl ls ls' s ,\n    (* 1 - branches matches the lists of two lists of labeled statements *)\n    repr_branches_LambdaANF_Codegen cl ls ls' -> \n    (* 2 - switch-header matches  *)\n    repr_switch_LambdaANF_Codegen v ls ls' s ->\n    repr_expr_LambdaANF_Codegen  (Ecase v cl)  s\n                     (* default case for last boxed and unboxed constructor \n                        OS: perhaps want to include a *)\nwith repr_branches_LambdaANF_Codegen: list (ctor_tag * exp) -> labeled_statements -> labeled_statements -> Prop :=\n     | Rempty_br : repr_branches_LambdaANF_Codegen nil LSnil LSnil\n     | Runboxed_default_br: forall t e cl ls n s,\n         repr_expr_LambdaANF_Codegen e s ->\n         M.get t rep_env  = Some (enum n) ->\n         repr_branches_LambdaANF_Codegen cl ls LSnil ->\n         repr_branches_LambdaANF_Codegen ((t, e) ::cl) ls (LScons None  (Ssequence s Sbreak)\n                                                      LSnil)\n     | Runboxed_br: forall cl ls lsa' lsb' lsc' t n tag e s, repr_branches_LambdaANF_Codegen cl ls (LScons lsa' lsb' lsc') ->\n                                                repr_expr_LambdaANF_Codegen e s ->\n                                                M.get t rep_env  = Some (enum n) ->\n                                                repr_unboxed_Codegen n tag ->\n                                                repr_branches_LambdaANF_Codegen ((t, e) ::cl) ls (LScons (Some (Z.shiftr tag 1)) (Ssequence s Sbreak) (LScons lsa' lsb' lsc'))\n     | Rboxed_default_br : forall cl  ls' t a n e s, repr_branches_LambdaANF_Codegen cl LSnil ls' ->\n                                           repr_expr_LambdaANF_Codegen e s ->\n                                           M.get t rep_env = Some (boxed n a) ->\n                                           repr_branches_LambdaANF_Codegen ((t, e)::cl) (LScons None  (Ssequence s Sbreak) LSnil) ls'\n     | Rboxed_br : forall cl lsa lsb lsc ls' t a n tag e s, repr_branches_LambdaANF_Codegen cl (LScons lsa lsb lsc) ls' ->\n                                           repr_expr_LambdaANF_Codegen e s ->\n                                           M.get t rep_env = Some (boxed n a) ->\n                                           boxed_header n a tag ->\n                                           repr_branches_LambdaANF_Codegen ((t, e)::cl) (LScons (Some (Z.land tag 255)) (Ssequence s Sbreak)  (LScons lsa lsb lsc)) ls'.\n\n                    \nTheorem repr_branches_LSnil_no_unboxed:\n  forall t e cl  ls,\n    findtag cl t = Some e ->\n    repr_branches_LambdaANF_Codegen cl ls LSnil  -> \n    ~ (exists arr, M.get t rep_env = Some (enum arr)).\nProof.\n  induction cl; intros.\n  - inv H.\n  - simpl in H. destruct a.\n    destruct (M.elt_eq c t).\n    + subst. inv H0; intro; destruct H0; rewrite H0 in H8; inv H8.\n    + inv H0. inv H4. inv H.\n      eapply IHcl; eauto.\nQed.\n\nTheorem repr_branches_LSnil_no_boxed:\n  forall t e cl  ls,\n    findtag cl t = Some e ->\n    repr_branches_LambdaANF_Codegen cl LSnil ls  -> \n    ~ (exists arr s, M.get t rep_env = Some (boxed arr s)).\nProof.\n  induction cl; intros.\n  - inv H.\n  - simpl in H. destruct a.\n    destruct (M.elt_eq c t).\n    + subst. inv H0; intro; destruct H0; destruct H0. rewrite H0 in H7; inv H7. rewrite H0 in H8; inv H8.\n    + inv H0. inv H8. inv H.\n      eapply IHcl; eauto.\nQed.\n\n\n      \nDefinition gc_vars := ((allocIdent, valPtr)::(limitIdent, valPtr)::(argsIdent, valPtr)::(caseIdent, boolTy) ::nil).\n\nDefinition gc_set := (allocIdent ::= Efield tinfd allocIdent valPtr ;\n                                                    limitIdent ::= Efield tinfd limitIdent valPtr ;\n                                                    argsIdent ::= Efield tinfd argsIdent (Tarray val maxArgs noattr)).\n\nDefinition gc_test (gcArrIdent:positive) (l:N) (vs : list positive) (ind : list N) (fenv : fun_env) (finfo_env : fun_info_env) := (reserve argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent nParam gcArrIdent\n                                                           (Z.of_N (l + 2)) vs ind fenv finfo_env).\n\nDefinition gc_test' (gcArrIdent:positive) (l:N) (vs : list positive) (ind : list N) (fenv : fun_env) (finfo_env : fun_info_env) := (reserve' argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent nParam gcArrIdent\n                                                           (Z.of_N (l + 2)) vs ind fenv finfo_env).\n\nInductive right_param_asgn: list positive -> list N -> statement -> Prop :=\n| asgn_nil: right_param_asgn nil nil Sskip\n| asgn_cons: forall x xs n ns s,  right_param_asgn xs ns s -> right_param_asgn (x::xs) (n::ns) ((x ::= args[Z.of_N n]);s).\n\n\n(* lenv' is lenv after binding xs->vs with NoDup xs *)\nDefinition lenv_param_asgn (lenv lenv':temp_env) (xs:list positive) (vs:list Values.val): Prop :=\n  forall i, (forall z, nthN xs z  = Some i ->  M.get i lenv' = nthN vs z)\n            /\\\n            (~ List.In i xs -> M.get i lenv' = M.get i lenv).\n\nInductive lenv_param_asgn_i: temp_env -> temp_env -> list positive -> list Values.val -> Prop :=\n| LPA_nil: forall lenv, lenv_param_asgn_i lenv lenv [] []    \n| LPA_cons: forall lenv lenv' ys vs y v,\n    lenv_param_asgn_i (M.set y v lenv) lenv' ys vs ->\n    lenv_param_asgn_i lenv lenv' (y::ys) (v::vs).\n\n\nTheorem lenv_param_asgn_i_length:\n  forall ys vs lenv lenv',\n    lenv_param_asgn_i lenv lenv' ys vs ->\n    length ys = length vs.\nProof.\n  induction ys; intros. inv H; reflexivity.\n  inv H. simpl. eapply IHys in H5. auto.\nQed.\n\n\nTheorem lenv_param_asgn_rel:\n  forall ys vs lenv lenv', \n    lenv_param_asgn_i lenv lenv' ys vs ->\n    NoDup ys ->\n    lenv_param_asgn lenv lenv' ys vs.\nProof.\n  induction ys; intros.\n  - inv H. constructor; intros. inv H. reflexivity.\n  - inv H. eapply IHys in H6. split; intros; specialize (H6 i); destruct H6.\n    + rewrite nthN_equation in *. destruct (var_dec a i).\n      * destruct z. subst.\n        rewrite H2. rewrite M.gss. reflexivity. inv H0; auto.\n        apply H1 in H. auto.\n      * destruct z. exfalso. inv H. apply n; auto.\n        apply H1 in H. auto.        \n    + rewrite M.gso in H2. apply H2.\n      intro. apply H. constructor 2. auto.\n      intro. apply H. constructor; auto.\n    + inv H0; auto.\nQed.\n\nTheorem e_lenv_param_asgn_i:\n  forall ys lenv vs,\n    length ys = length vs ->\n    NoDup ys ->\n    exists lenv',\n      lenv_param_asgn_i lenv lenv' ys vs.\nProof.\n  induction ys; intros.\n  - destruct vs; inv H. exists lenv. constructor. \n  - destruct vs; inv H. inv H0.\n    specialize (IHys  (M.set a v lenv)).\n    specialize (IHys _ H2 H4).\n    destruct IHys as [lenv' Hlenv'].\n    eexists; constructor; eauto. \nQed.\n\n\n\nTheorem e_lenv_param_asgn:\n  forall lenv ys vs,\n    length ys = length vs ->\n    NoDup ys ->\n    exists lenv',\n      lenv_param_asgn lenv lenv' ys vs.\nProof.\n  intros.\n  assert (Hi := e_lenv_param_asgn_i ys lenv vs H H0).\n  destruct Hi.\n  apply lenv_param_asgn_rel in H1; eauto.\nQed.\n\n\nTheorem get_list_nth_get' (B:Type):\n  forall  (vs : list B) rho v xs  N, \n  get_list xs rho = Some vs ->\n  nthN vs N = Some v ->\n  exists x, nthN xs N = Some x /\\ M.get x rho = Some v. \nProof.\n  induction vs; intros; destruct xs.\n  inv H0. inv H0.\n  simpl in H. inv H.\n  rewrite nthN_equation in H0.\n  destruct N.\n  - inv H0. simpl in H.\n    exists e. split. reflexivity.\n    destruct (M.get e rho).\n    destruct (get_list xs rho). inv H; auto.\n    inv H. inv H.\n  - simpl in H. destruct (M.get e rho).\n    destruct (get_list xs rho) eqn:Hxs. inv H.\n    specialize (IHvs _ _ _ _ Hxs H0).\n    rewrite nthN_equation. auto. inv H.\n    inv H.\nQed.   \n  \n\nTheorem in_rho_entry:\n  forall xs vs fl rho x v, \n  set_lists xs vs (def_funs fl fl (M.empty cps.val) (M.empty cps.val)) = Some rho ->\n  NoDup xs ->\n  M.get x rho = Some v ->\n  (exists n, nthN xs n = Some x /\\ nthN vs n = Some v) \\/\n  (exists t ys b, ~List.In x xs /\\  find_def x fl = Some (t, ys, b) /\\ v = Vfun (M.empty cps.val) fl x).\nProof.                               \n  intros.\n  assert (decidable (List.In x xs)). apply In_decidable. apply shrink_cps_correct.var_dec_eq. \n  inv H2.\n  - left. \n    assert (Hgl := get_list_set_lists _ _ _ _  H0 H ).\n    apply In_nthN in H3. destruct H3.\n    assert (Hgl' := get_list_nth_get _ _ _ _ _ Hgl H2).\n    destruct Hgl'.\n    destruct H3.\n    exists x0.\n    rewrite H4 in H1; inv H1.\n    split; auto.\n  - right.\n    erewrite <- set_lists_not_In in H1; eauto.\n    assert (decidable (name_in_fundefs fl x)). unfold decidable. assert (Hd := Decidable_name_in_fundefs fl). inv Hd. specialize (Dec x). inv Dec; auto.\n    inv H2.\n    + assert (H4' := H4).\n      eapply def_funs_eq in H4.\n      rewrite H1 in H4.\n      inv H4.\n      apply name_in_fundefs_find_def_is_Some in H4'.\n      destruct H4' as [ft [ys [e Hfd]]].\n      exists ft, ys, e; eauto.\n    +  erewrite def_funs_neq in H1; eauto.\n       rewrite M.gempty in H1; inv H1.\nQed.\n\n      \n\n\nInductive repr_val_LambdaANF_Codegen:  LambdaANF.cps.val -> mem -> Values.val -> Prop :=\n| Rint_v: forall  z r m,\n    repr_unboxed_Codegen (Z.to_N z) r ->\n    repr_val_LambdaANF_Codegen (LambdaANF.cps.Vint z) m (make_vint r)\n| Rconstr_unboxed_v:\n    forall t arr n m,\n      M.get t rep_env = Some (enum arr) ->\n      repr_unboxed_Codegen arr n ->\n      repr_val_LambdaANF_Codegen (LambdaANF.cps.Vconstr t nil) m  (make_vint n)\n| Rconstr_boxed_v: forall  t vs n a b i m h,\n    (* t is a boxed constructor, n ends with 0 and represents \n      a pointer to repr_val_ptr of (t, vs)  *)\n    M.get t rep_env = Some (boxed n a) ->\n    (* 1) well-formedness of the header block *)\n\n    Mem.load int_chunk m b (Ptrofs.unsigned (Ptrofs.sub i (Ptrofs.repr int_size))) = Some (make_vint h) ->\n    boxed_header n a h ->\n    (* 2) all the fields are also well-represented *)\n    repr_val_ptr_list_LambdaANF_Codegen vs m b i ->\n    repr_val_LambdaANF_Codegen (LambdaANF.cps.Vconstr t vs) m  (Vptr b i)\n| Rfunction_v: \n    forall vars avars fds f m b t t' vs pvs avs alocs e asgn body l locs finfo gccall,\n      let F := mkfunction (Tvoid)\n                          ((mkcallconv false false false)) (*({| cc_vararg := false; cc_unproto := false; cc_structret := false |})*)\n             ((tinfIdent, threadInf)::(map (fun x => (x , val)) pvs))\n             (nil)\n             (List.app avars gc_vars)\n             (Ssequence gccall (Ssequence (Ssequence gc_set asgn)\n                                          body)) in\n      find_def f fds = Some (t, vs, e) ->\n      M.get t fenv = Some (l, locs) ->\n      M.get f finfo_env = Some (finfo , t') -> (* TODO: check this *)\n      t = t' ->\n      Genv.find_symbol (Genv.globalenv p) f = Some b -> (* symbol f points to b in the globalenv *)\n      (* b points to an internal function in the heap [and i is 0] *)\n      gc_test' finfo l vs locs fenv finfo_env = Some gccall ->\n      Genv.find_funct (globalenv p) (Vptr b  Ptrofs.zero) = Some (Internal F) ->\n      (* F should have the shape that we expect for functions generated by our compiler, \n       > see translate_fundefs i.e.\n        - returns a Tvoid *)\n      (*\n       - calling convention?  \n        - only param is the threadinfo (tinfIdent of type threadInf) *)\n       (*\n        - all the vars match + the 3 gc vars *)       \n\n       (* - no temps *)\n       (*\n        - function header: threadInfo, gc check, load parameters,  then body equivalent to e (related according to repr_exp_LambdaANF_Codegen)\n        *)\n      Forall2 (fun x xt =>  xt = (x, val))  vs vars  ->\n      pvs = firstn nParam vs ->\n      avs = skipn nParam vs ->\n      alocs = skipn nParam locs ->\n      avars = skipn nParam vars ->\n      right_param_asgn avs alocs asgn ->\n      repr_expr_LambdaANF_Codegen e body ->\n      repr_val_LambdaANF_Codegen (cps.Vfun (M.empty cps.val) fds f) m (Vptr b Ptrofs.zero) \nwith repr_val_ptr_list_LambdaANF_Codegen: (list LambdaANF.cps.val) -> mem -> block -> ptrofs -> Prop := \n     | Rnil_l:\n         forall m b i,\n           repr_val_ptr_list_LambdaANF_Codegen nil m b i\n     | Rcons_l:\n         forall v vs m b i v7,\n           Mem.load int_chunk m b (Ptrofs.unsigned  i) = Some v7 ->\n           repr_val_LambdaANF_Codegen v m v7 -> \n           repr_val_ptr_list_LambdaANF_Codegen vs m b (Ptrofs.add i (Ptrofs.repr int_size)) ->\n           repr_val_ptr_list_LambdaANF_Codegen (v::vs) m b i.\n\n\n\nDefinition locProp := block -> Z -> Prop.\n\n\n(* m and m' are the _same_ over subheap L *)\n\nDefinition sub_locProp: locProp -> locProp -> Prop :=\n  fun L L' => forall b ofs, L b ofs -> L' b ofs.\n\n      \n\n(* CHANGE THIS *)\nInductive repr_val_L_LambdaANF_Codegen:  LambdaANF.cps.val -> mem -> locProp -> Values.val -> Prop :=\n| RSint_v: forall L z r m,\n    repr_unboxed_Codegen (Z.to_N z) r ->\n    repr_val_L_LambdaANF_Codegen (LambdaANF.cps.Vint z) m L (make_vint r)\n| RSconstr_unboxed_v:\n    forall t arr n m L,\n      M.get t rep_env = Some (enum arr) ->\n      repr_unboxed_Codegen arr n ->\n      repr_val_L_LambdaANF_Codegen (LambdaANF.cps.Vconstr t nil) m L (make_vint n)\n| RSconstr_boxed_v: forall (L:block -> Z -> Prop) t vs n a b i m h,\n    (* t is a boxed constructor, n ends with 0 and represents \n      a pointer to repr_val_ptr of (t, vs)  *)\n    M.get t rep_env = Some (boxed n a) ->\n    (forall j : Z, (Ptrofs.unsigned (Ptrofs.sub i (Ptrofs.repr int_size)) <= j <\n   Ptrofs.unsigned (Ptrofs.sub i (Ptrofs.repr int_size)) + size_chunk int_chunk)%Z  -> L b j%Z) ->\n    (* 1) well-formedness of the header block *)\n\n    Mem.load int_chunk m b (Ptrofs.unsigned (Ptrofs.sub i (Ptrofs.repr int_size))) = Some (make_vint h) -> \n    boxed_header n a h ->\n    (* 2) all the fields are also well-represented *)\n    repr_val_ptr_list_L_LambdaANF_Codegen vs m L b i ->\n    repr_val_L_LambdaANF_Codegen (LambdaANF.cps.Vconstr t vs) m L (Vptr b i)\n| RSfunction_v:             \n    forall (L:block -> Z -> Prop)  vars avars fds f m b t t' vs pvs avs e asgn body l locs alocs finfo gccall,\n      let F := mkfunction (Tvoid)\n                          ((mkcallconv false false false)) (*({| cc_vararg := false; cc_unproto := false; cc_structret := false |})*)\n             ((tinfIdent, threadInf)::(map (fun x => (x , val)) pvs))\n             (nil)\n             (List.app avars gc_vars)\n             (Ssequence gccall (Ssequence (Ssequence gc_set asgn)\n                                          body)) in\n      find_def f fds = Some (t, vs, e) ->\n      M.get t fenv = Some (l, locs) ->\n      M.get f finfo_env = Some (finfo , t') -> (* TODO: check this *)\n      t = t' ->\n      Genv.find_symbol (Genv.globalenv p) f = Some b -> (* symbol f points to b in the globalenv *)\n      (* b points to an internal function in the heap [and i is 0] *)\n      gc_test' finfo l vs locs fenv finfo_env = Some gccall ->\n      Genv.find_funct (globalenv p) (Vptr b  Ptrofs.zero) = Some (Internal F) ->\n      (* F should have the shape that we expect for functions generated by our compiler, \n       > see translate_fundefs i.e.\n        - returns a Tvoid *)\n      (*\n       - calling convention?  \n        - only param is the threadinfo (tinfIdent of type threadInf) *)\n       (*\n        - all the vars match + the 3 gc vars *)       \n\n       (* - no temps *)\n       (*\n        - function header: threadInfo, gc check, load parameters,  then body equivalent to e (related according to repr_exp_LambdaANF_Codegen)\n        *)\n      Forall2 (fun x xt =>  xt = (x, val))  vs vars  ->\n      pvs = firstn nParam vs ->\n      avs = skipn nParam vs ->\n      alocs = skipn nParam locs ->\n      avars = skipn nParam vars ->\n      right_param_asgn avs alocs asgn ->\n      repr_expr_LambdaANF_Codegen e body ->\n      repr_val_L_LambdaANF_Codegen (cps.Vfun (M.empty cps.val) fds f) m L (Vptr b Ptrofs.zero) \nwith repr_val_ptr_list_L_LambdaANF_Codegen: (list LambdaANF.cps.val) -> mem -> locProp -> block -> ptrofs -> Prop := \n     | RSnil_l:\n         forall m L b i,\n           repr_val_ptr_list_L_LambdaANF_Codegen nil m L b i\n     | RScons_l:\n         forall v vs m (L:block -> Z -> Prop) b i v7,\n           (forall j : Z, ((Ptrofs.unsigned i) <= j < (Ptrofs.unsigned i) + int_size)%Z -> L b j) ->\n           Mem.load int_chunk m b (Ptrofs.unsigned i) = Some v7 ->\n           repr_val_L_LambdaANF_Codegen v m L v7 -> \n           repr_val_ptr_list_L_LambdaANF_Codegen vs m L b (Ptrofs.add i (Ptrofs.repr int_size)) ->\n           repr_val_ptr_list_L_LambdaANF_Codegen (v::vs) m L b i.\n\nScheme repr_val_L_LambdaANF_Codegen_rec := Induction for repr_val_L_LambdaANF_Codegen Sort Prop\n  with repr_val_ptr_list_L_LambdaANF_Codegen_rec := Induction for repr_val_ptr_list_L_LambdaANF_Codegen Sort Prop.\n\n\n\nInductive  repr_val_ptr_list_L_LambdaANF_Codegen_Z: (list LambdaANF.cps.val) -> mem -> locProp -> block -> Z -> Prop := \n     | RSnil_l_Z:\n         forall m L b i,\n           repr_val_ptr_list_L_LambdaANF_Codegen_Z nil m L b i\n     | RScons_l_Z:\n         forall v vs m (L:block -> Z -> Prop) b i v7,\n           (forall j : Z, (i <= j < i + int_size)%Z -> L b j) ->\n           Mem.load int_chunk m b i = Some v7 ->\n           repr_val_L_LambdaANF_Codegen v m L v7 -> \n           repr_val_ptr_list_L_LambdaANF_Codegen_Z vs m L b (i+ int_size)%Z ->\n           repr_val_ptr_list_L_LambdaANF_Codegen_Z (v::vs) m L b i.\n\n\n\n\n \n\n(* \nTheorem repr_val_forall_L_fun:\n  forall L fds f m b,\n  repr_val_ptr_LambdaANF_Codegen (cps.Vfun (M.empty cps.val) fds f) m (b,Int.zero) <-> repr_val_L_LambdaANF_Codegen (cps.Vfun (M.empty cps.val) fds f) m L (Vptr b Int.zero).\nProof.\n  intros. split; intro H; inv H; econstructor; eauto.\nQed.   *)\n\nTheorem repr_val_ptr_list_Z:\n  forall m L b vs i,\n    uint_range ((Ptrofs.unsigned i) + (Z.of_nat (length vs)* int_size))%Z -> \n  repr_val_ptr_list_L_LambdaANF_Codegen vs m L b i <-> repr_val_ptr_list_L_LambdaANF_Codegen_Z vs m L b (Ptrofs.unsigned i).\nProof.\n  induction vs; intros.\n  - split; intro; constructor.\n  - assert  (Hi4 : (Ptrofs.unsigned i + int_size)%Z = (Ptrofs.unsigned (Ptrofs.add i (Ptrofs.repr int_size)))).\n    { \n      unfold int_size in *; simpl size_chunk in *.\n      rewrite Ptrofs.add_unsigned.\n      rewrite Ptrofs.unsigned_repr.\n      rewrite Ptrofs.unsigned_repr. reflexivity.\n      compute; destruct Archi.ptr64; split; intros Hlt; inv Hlt.\n\n      \n      rewrite Ptrofs.unsigned_repr.\n      simpl length in H.\n      rewrite Nat2Z.inj_succ in H.\n      rewrite Z.mul_succ_l in H.\n      assert (0 <= Z.of_nat (length vs))%Z.     \n      apply Zle_0_nat.\n      rewrite Z.add_assoc in H.\n      assert (0 <= Ptrofs.unsigned i)%Z by apply Ptrofs.unsigned_range.\n      inv H. split. apply OrdersEx.Z_as_OT.add_nonneg_nonneg. auto. \n      chunk_red; omega. chunk_red; omega. compute; destruct Archi.ptr64; split; intros Hlt; inv Hlt.\n      }\n    split; intro; inv H0.\n    + econstructor; eauto; unfold int_size in *; simpl size_chunk in *.\n      apply IHvs in H10.\n      rewrite Hi4.\n      auto.\n      rewrite <- Hi4.\n      \n      simpl length in H.\n      rewrite Nat2Z.inj_succ in H.\n     \n      assert (0 <= Ptrofs.unsigned i)%Z by apply Ptrofs.unsigned_range.\n      assert (0 <= Z.of_nat (length vs))%Z by       apply Zle_0_nat.\n      inv H.\n      rewrite Z.mul_succ_l in H7.\n      rewrite Z.add_assoc in H7.\n      split; chunk_red; omega.\n    + econstructor; eauto.\n      unfold int_size in *; simpl size_chunk in *.\n      apply IHvs.\n      rewrite <- Hi4. \n      simpl length in H.\n      rewrite Nat2Z.inj_succ in H.     \n      assert (0 <= Ptrofs.unsigned i)%Z by apply Ptrofs.unsigned_range.\n      assert (0 <= Z.of_nat (length vs))%Z by       apply Zle_0_nat.\n      inv H.\n      rewrite Z.mul_succ_l in H6.\n      rewrite Z.add_assoc in H6.\n      split; chunk_red; omega.\n      rewrite <- Hi4. auto.\nQed.      \n\n\n    \n  \n(* this is the sum of get_var_or_funvar and repr_val_L_LambdaANF_Codegen (-> and <-\\-) *)\nInductive repr_val_id_L_LambdaANF_Codegen: LambdaANF.cps.val -> mem -> locProp -> temp_env -> positive -> Prop := \n| RVid_F:\n   forall b f lenv fds L m,\n     Genv.find_symbol (Genv.globalenv p) f = Some b ->\n     repr_val_L_LambdaANF_Codegen (cps.Vfun (M.empty cps.val) fds f) m L (Vptr b (Ptrofs.zero)) ->\n     repr_val_id_L_LambdaANF_Codegen (cps.Vfun (M.empty cps.val) fds f) m L lenv f\n| RVid_V:\n    forall x m lenv L v6 v7,\n      Genv.find_symbol (Genv.globalenv p) x = None -> \n      M.get x lenv = Some v7 ->\n      repr_val_L_LambdaANF_Codegen v6 m L v7 ->\n      repr_val_id_L_LambdaANF_Codegen v6 m L lenv x.\n\n\nTheorem repr_val_id_L_LambdaANF_Codegen_vint_or_vptr:\n  forall v6 m L v7,\n  repr_val_L_LambdaANF_Codegen v6 m L v7 ->\n  Vint_or_Vptr v7 = true.\nProof.  \n  intros; inv H; auto. \nQed.\n\n\n(* If v is needed *)\nTheorem repr_val_id_L_LambdaANF_Codegen_ptr:\n  forall v6 m L lenv x,\n  repr_val_id_L_LambdaANF_Codegen v6 m L lenv x ->\n  exists v7, repr_val_L_LambdaANF_Codegen v6 m L v7 /\\\n            ((M.get x lenv = Some v7 /\\\n             Genv.find_symbol (Genv.globalenv p) x = None)\n             \\/\n             (exists b, v7 = Vptr b Ptrofs.zero /\\\n                        Genv.find_symbol (Genv.globalenv p) x = Some b)).\nProof.            \n  intros. inv H.\n  - exists (Vptr b (Ptrofs.zero)). split; auto.\n    right. exists b; auto.\n  - exists v7. split; auto. \nQed. \n\n\nTheorem get_var_or_funvar_eval:\n  forall lenv a v m, \n    find_symbol_domain finfo_env ->\n    finfo_env_correct ->\n    get_var_or_funvar lenv a v ->\n    eval_expr (globalenv p) empty_env lenv m (var_or_funvar_f   a) v.\nProof. \n  intros. specialize (H a). inv H. unfold var_or_funvar_f. inv H1.\n  - rewrite H. destruct (H3 (ex_intro _ b H)). \n    unfold makeVar. rewrite H1.\n    destruct x.\n    specialize (H0 _ _ f H1).\n    destruct H0. destruct x.\n    rewrite H0.\n    econstructor. constructor 2.\n    apply M.gempty. eauto.\n    constructor. auto.\n  - rewrite H. constructor. auto.\nQed.\n\nTheorem get_var_or_funvar_semcast:\n  forall v a m lenv,\n    find_symbol_domain finfo_env ->\n    finfo_env_correct ->\n    get_var_or_funvar lenv a v ->\n    sem_cast v (typeof (var_or_funvar_f a)) uval m = Some v.\nProof.\n  intros. unfold var_or_funvar_f. specialize (H a). inv H. inv H1.\n  - rewrite H. destruct (H3 (ex_intro _ b H)). \n    unfold makeVar. rewrite H1.\n    destruct x.\n    specialize (H0 _ _ f H1).\n    destruct H0. destruct x.\n    rewrite H0.\n    constructor. \n  - rewrite H. destruct v; inv H5; auto. \nQed.  \n\nTheorem repr_val_id_implies_var_or_funvar:\n  forall v6 m L lenv x,\n  repr_val_id_L_LambdaANF_Codegen v6 m L lenv x ->\n  exists v7, get_var_or_funvar lenv x v7 /\\\n             repr_val_L_LambdaANF_Codegen v6 m L v7.\nProof.\n  intros. inv H.\n  - exists (Vptr b Ptrofs.zero).\n    split. constructor; auto.\n    auto.\n  - exists v7.\n    split. constructor 2; auto. inv H2; auto.\n    auto.\nQed.\n\nTheorem repr_val_id_set:\n  forall v6 m L lenv x,\n    repr_val_id_L_LambdaANF_Codegen v6 m L lenv x ->\n    forall x0 v, \n    x <> x0 ->\n    repr_val_id_L_LambdaANF_Codegen v6 m L (M.set x0 v lenv) x.\nProof.\n  intros. inv H.\n  - econstructor; eauto.\n  - econstructor 2; eauto.\n    rewrite M.gso; auto.\nQed.\n                                \nScheme repr_val_ind' := Minimality for repr_val_L_LambdaANF_Codegen Sort Prop\n  with repr_val_list_ind' := Minimality for repr_val_ptr_list_L_LambdaANF_Codegen Sort Prop.\n (* Combined Scheme repr_val_L_LambdaANF_Codegen_mutind from repr_val_L_LambdaANF_Codegen_ind, repr_val_ptr_list_L_LambdaANF_Codegen_ind. *)\n \nTheorem nthN_pos_pred: \n  forall {A} (a:A) vs v6 p0,\n  nthN (a :: vs) (N.pos p0) = Some v6 ->\n  nthN vs (N.pred (N.pos p0)) = Some v6.\nProof.\n  intros. destruct p0; auto.\nQed.\n\nTheorem Z_mul_4:\n  forall p,\n   Z.pos p~0~0 = (4 * Z.pos p)%Z.\nProof.\n  intro.\n  replace ((xO (xO p0))) with (Zpower.shift 2%Z p0) by reflexivity.\n  rewrite Zpower.shift_equiv; auto. omega.\nQed.\n\n\nTheorem repr_val_ptr_list_L_Z_nth:\n  forall {m L  v6 vs n b i},\n repr_val_ptr_list_L_LambdaANF_Codegen_Z vs m L b i -> \n nthN vs n = Some v6 ->\n exists v7, Mem.load int_chunk m b (i + (Z.of_N n * int_size))  = Some v7 /\\\n repr_val_L_LambdaANF_Codegen v6 m L v7.\nProof.  \n  induction vs; intros. inv H0.\n  inv H. \n  destruct n. simpl in H0. inv H0.\n  exists v7.\n  simpl. rewrite Z.add_0_r. auto.\n  apply nthN_pos_pred in H0.\n  eapply IHvs in H0; eauto. destruct H0. exists x. inv H.\n  split; auto.\n  rewrite N2Z.inj_pred in H0. 2: apply N_lt_pos. rewrite Z.mul_pred_l in H0.  \n  replace (i +  int_size + (Z.of_N (N.pos p0) *  int_size -  int_size))%Z with (i + Z.of_N (N.pos p0) *  int_size)%Z in H0 by (chunk_red; omega).\n  auto.\nQed.\n\n\nTheorem repr_val_ptr_list_L_nth:\n  forall {m L  v6 vs n b i},\n repr_val_ptr_list_L_LambdaANF_Codegen vs m L b i -> \n nthN vs n = Some v6 ->\n exists v7, Mem.load int_chunk m b (Ptrofs.unsigned (Ptrofs.add i (Ptrofs.mul (Ptrofs.repr (Z.of_N n)) (Ptrofs.repr int_size))))  = Some v7 /\\\n repr_val_L_LambdaANF_Codegen v6 m L v7.\nProof.  \n  induction vs; intros. inversion H0.\n  destruct n.\n  - simpl. inv H0.\n    inv H.\n    rewrite Ptrofs.add_zero. \n    exists v7; auto.\n  - simpl.\n    inv H.\n    apply nthN_pos_pred in H0.\n    specialize (IHvs _ _ _ H10 H0).\n    destruct IHvs. destruct H.\n    exists x; split; auto.\n    replace (Ptrofs.unsigned\n           (Ptrofs.add (Ptrofs.add i (Ptrofs.repr int_size))\n              (Ptrofs.mul (Ptrofs.repr (Z.of_N (N.pred (N.pos p0))))\n                       (Ptrofs.repr int_size)))) with\n        (Ptrofs.unsigned\n           (Ptrofs.add i (Ptrofs.mul (Ptrofs.repr (Z.pos p0)) (Ptrofs.repr int_size)))) in H.\n    auto.\n    rewrite Ptrofs.add_assoc.\n    unfold Ptrofs.mul.\n    unfold Ptrofs.add.\n    erewrite  Ptrofs.eqm_samerepr.\n    reflexivity.\n    apply Ptrofs.eqm_add.\n    apply Ptrofs.eqm_refl.\n    eapply Ptrofs.eqm_trans.\n    apply Ptrofs.eqm_unsigned_repr_l.\n    2:{\n    apply Ptrofs.eqm_unsigned_repr_r.\n    apply Ptrofs.eqm_refl. }\n    rewrite Z.add_comm.\n    rewrite N2Z.inj_pred by (unfold N.lt; auto).\n    int_red.\n    rewrite N2Z.inj_pos.\n    eapply Ptrofs.eqm_trans.\n    apply Ptrofs.eqm_mult.\n    apply Ptrofs.eqm_unsigned_repr_l.\n    apply Ptrofs.eqm_refl.\n    apply Ptrofs.eqm_unsigned_repr_l.\n    apply Ptrofs.eqm_refl. \n    eapply Ptrofs.eqm_trans.\n    2:{\n    apply Ptrofs.eqm_add.\n    apply Ptrofs.eqm_unsigned_repr_r.\n    apply Ptrofs.eqm_mult.\n    apply Ptrofs.eqm_unsigned_repr_r.\n    apply Ptrofs.eqm_refl.\n    apply Ptrofs.eqm_unsigned_repr_r.\n    apply Ptrofs.eqm_refl.\n    apply Ptrofs.eqm_unsigned_repr_r.\n    apply Ptrofs.eqm_refl. }\n    rewrite Z.mul_pred_l.\n    apply Ptrofs.eqm_refl2. omega.\nQed.\n\n\n\nTheorem repr_val_L_unchanged:\n  forall v6 m L v7, \n  repr_val_L_LambdaANF_Codegen v6 m L v7 ->\n  forall m', Mem.unchanged_on L m m' ->\n  repr_val_L_LambdaANF_Codegen v6 m' L v7.\nProof.\n  apply (repr_val_ind' (fun v m L v7 => forall m', Mem.unchanged_on L m m' -> repr_val_L_LambdaANF_Codegen v m' L v7)\n                       (fun vs m L b i => forall m', Mem.unchanged_on L m m' -> repr_val_ptr_list_L_LambdaANF_Codegen vs m' L b i)); intros; try (now econstructor; eauto).\n  - specialize (H4 _ H5). \n    econstructor; eauto.\n    eapply Mem.load_unchanged_on; eauto.  \n  - econstructor; eauto.\n    eapply Mem.load_unchanged_on; eauto.\nQed.\n\nTheorem repr_val_id_L_unchanged:\n  forall v6 m lenv L x, \n  repr_val_id_L_LambdaANF_Codegen v6 m L lenv x ->\n  forall m', Mem.unchanged_on L m m' ->\n  repr_val_id_L_LambdaANF_Codegen v6 m' L lenv x.\nProof.\n    intros. inv H.\n  - econstructor; eauto. eapply repr_val_L_unchanged; eauto.\n  - econstructor 2; eauto.\n    eapply repr_val_L_unchanged; eauto.\nQed.\n\nTheorem repr_val_ptr_list_L_unchanged:\n  forall vs m L b i,\n    repr_val_ptr_list_L_LambdaANF_Codegen vs m L b i ->\nforall m', Mem.unchanged_on L m m' -> repr_val_ptr_list_L_LambdaANF_Codegen vs m' L b i.\nProof.\n  apply (repr_val_list_ind' (fun v m L v7 => forall m', Mem.unchanged_on L m m' -> repr_val_L_LambdaANF_Codegen v m' L v7)\n                       (fun vs m L b i => forall m', Mem.unchanged_on L m m' -> repr_val_ptr_list_L_LambdaANF_Codegen vs m' L b i)); intros; try (now econstructor; eauto).\n  - specialize (H4 _ H5). \n    econstructor; eauto.\n    eapply Mem.load_unchanged_on; eauto.  \n  - econstructor; eauto.\n    eapply Mem.load_unchanged_on; eauto.\nQed.\n\nCorollary repr_val_ptr_list_L_Z_unchanged:\n  forall vs m L b i,\n    repr_val_ptr_list_L_LambdaANF_Codegen_Z vs m L b i ->\nforall m', Mem.unchanged_on L m m' -> repr_val_ptr_list_L_LambdaANF_Codegen_Z vs m' L b i.\nProof.\n  induction vs; intros.\n  constructor.\n  inv H. econstructor; eauto.\n  eapply Mem.load_unchanged_on; eauto.  \n  eapply repr_val_L_unchanged; eauto.\nQed.\n\nTheorem repr_val_L_sub_locProp:\n    forall v6 m L v7, \n  repr_val_L_LambdaANF_Codegen v6 m L v7 ->\n  forall L', sub_locProp L L' -> \n  repr_val_L_LambdaANF_Codegen v6 m L' v7.\nProof.\n  apply (repr_val_ind' (fun v6 m L v7 => forall L', sub_locProp L L' -> \n                                                   repr_val_L_LambdaANF_Codegen v6 m L' v7)\n                       (fun vs m L b i => forall L', sub_locProp L L' ->  repr_val_ptr_list_L_LambdaANF_Codegen vs m L' b i)); intros; try (now econstructor; eauto).\nQed.\n\nTheorem repr_val_id_L_sub_locProp:\n  forall v6 m L x lenv, \n    repr_val_id_L_LambdaANF_Codegen v6 m L lenv x ->\n    forall L', sub_locProp L L' -> \n               repr_val_id_L_LambdaANF_Codegen v6 m L' lenv x.\nProof.\n  intros. inv H.\n  - econstructor; eauto. eapply repr_val_L_sub_locProp; eauto.\n  - econstructor 2; eauto.\n    eapply repr_val_L_sub_locProp; eauto.\nQed.\n\n    \nTheorem repr_val_ptr_list_L_sub_locProp:\n    forall vs m L b i,\n      repr_val_ptr_list_L_LambdaANF_Codegen vs m L b i ->\n      forall L', sub_locProp L L' ->\n                 repr_val_ptr_list_L_LambdaANF_Codegen vs m L' b i.\nProof.\n  apply (repr_val_list_ind' (fun v6 m L v7 => forall L', sub_locProp L L' -> \n                                                   repr_val_L_LambdaANF_Codegen v6 m L' v7)\n                       (fun vs m L b i => forall L', sub_locProp L L' ->  repr_val_ptr_list_L_LambdaANF_Codegen vs m L' b i)); intros; try (now econstructor; eauto).\nQed.\n\nCorollary repr_val_ptr_list_L_Z_sub_locProp:\n    forall vs m L b i,\n      repr_val_ptr_list_L_LambdaANF_Codegen_Z vs m L b i ->\n      forall L', sub_locProp L L' ->\n                 repr_val_ptr_list_L_LambdaANF_Codegen_Z vs m L' b i.\nProof.\n  induction vs; intros.\n  -  constructor.\n  - inv H. econstructor; eauto.\n    eapply repr_val_L_sub_locProp; eauto.\nQed.  \n\n\n\n    \n(* \nReturns True if the pointer Vptr q_b q_ofs is reachable by crawling v7 \nAssumes correct memory layout (i.e. repr_val_LambdaANF_Codegen v6 m v7)\n *)\nFixpoint reachable_val_Codegen (v6:LambdaANF.cps.val) (m:mem) (v7:Values.val) (q_b:block) (q_ofs:ptrofs): Prop :=\n  match v6, v7 with\n  | LambdaANF.cps.Vint z, Vint r => False\n  | LambdaANF.cps.Vconstr t vs, Vptr b i =>\n    (fst (List.fold_left (fun curr v =>\n                            let '(p, (p_b, p_ofs)) := curr in\n                            (match Val.cmpu_bool (Mem.valid_pointer m) Ceq (Vptr p_b p_ofs) (Vptr q_b q_ofs) with\n                             | Some true => (True, (p_b, (Ptrofs.add p_ofs (Ptrofs.repr (sizeof (M.empty composite) val)))))\n                             | _ => \n                               (match Mem.load int_chunk m p_b (Ptrofs.unsigned p_ofs) with\n                                | Some v7 => \n                                  (reachable_val_Codegen v m v7 q_b q_ofs, (p_b, (Ptrofs.add p_ofs (Ptrofs.repr (sizeof (M.empty composite) val)))))\n                                | _ => curr\n                                end)\n                             end))                        \n                        vs (False, (b,i))))\n  | (LambdaANF.cps.Vfun rho fds f), Vptr b i => False\n  | _, _ => False\n  end.\n\n\n                                                                        \n(*\nTheorem repr_val_load_result: forall v6 m v7,\n    repr_val_LambdaANF_Codegen v6 m (Val.load_result int_chunk v7)\n                   <->\n  repr_val_LambdaANF_Codegen v6 m v7.\nProof.\n  intros.\n  destruct v7; split; intro H; inv H; simpl in *; econstructor; eauto.\nQed.   *)\n\nTheorem repr_val_L_load_result: forall v6 m v7 L,\n    repr_val_L_LambdaANF_Codegen v6 m L (Val.load_result int_chunk v7)\n                   <->\n  repr_val_L_LambdaANF_Codegen v6 m L v7.\nProof.\n  intros.\n  unfold Val.load_result in *. unfold int_chunk in *.\n  destruct Archi.ptr64 eqn:Harch;\n  destruct v7; split; intro H; try (inv H; simpl in *; unfold make_vint; try (rewrite Harch); econstructor; eauto).\n  apply repr_val_id_L_LambdaANF_Codegen_vint_or_vptr in H. simpl in H. rewrite Harch in H. inv H.\nQed. \n\n\n\n\n\n(* the memory blocks in the sequence (b, i), (b, i+off) ... (b, i+((n-1)*off)) are pairwise related with the sequence (b', i'), (b', i'+off) ... (b', i'+(n-1*off))  *)\nInductive For_N_blocks (P:(block * ptrofs) -> (block * ptrofs) -> Prop) (loc:block * ptrofs) (loc':block * ptrofs) (off: ptrofs) :  nat -> Prop :=\n| FNb_O: For_N_blocks P loc loc' off 0\n| FNb_S: forall n,\n    P (fst loc, Ptrofs.add (snd loc) (Ptrofs.mul off (Ptrofs.repr (Z.of_nat n)))) (fst loc', Ptrofs.add (snd loc') (Ptrofs.mul off (Ptrofs.repr (Z.of_nat n)))) ->\n    For_N_blocks P  loc loc' off n -> \n    For_N_blocks P loc  loc' off (S n). \n\n\n(* Related (deep copy) vals that may have been moved by the GC, in such way that they can be used in place of the other in repr_val_ptr_LambdaANF_Codegen \n *)\nInductive related_boxed_Codegen: mem -> (block *  ptrofs) -> mem -> (block *  ptrofs) -> Prop :=\n| SV_constr_boxed :\n    forall m m' b i b' i' h h' n a,\n    (* same tag *)\n      Mem.load int_chunk m b (Ptrofs.unsigned (Ptrofs.sub i Ptrofs.one)) = Some (make_vint h) ->\n      boxed_header n a  h ->\n      Mem.load int_chunk m' b' (Ptrofs.unsigned (Ptrofs.sub i' Ptrofs.one)) = Some (make_vint h') ->\n      boxed_header n a  h' ->      \n      (* each of the a (arrity) fields are either same int shifted+1, same function or pointers (0-ended) related according to same_boxed *)\n      For_N_blocks (fun loc loc' => related_boxed_or_same_val_Codegen m loc m' loc') (b,i) (b', i') (Ptrofs.repr (sizeof (M.empty composite) val)) (N.to_nat a) -> \n      related_boxed_Codegen m (b,i) m' (b', i')\nwith related_boxed_or_same_val_Codegen: mem -> (block *  ptrofs) -> mem -> (block * ptrofs) -> Prop :=\n     | RBSI_fun :\n         (* same fun *)\n         forall m m' b i b' i' F,\n           b = b' /\\ i = i' ->\n           Genv.find_funct (globalenv p) (Vptr b i) = Some (Internal F) ->\n           related_boxed_or_same_val_Codegen m (b,i) m' (b', i')                                   \n     | RBSI_int :\n         (* same int/unboxed constructor *)\n         forall m b i n m' b' i' h,\n           Mem.load int_chunk m b (Ptrofs.unsigned i) = Some (make_vint h) ->\n           Mem.load int_chunk m' b' (Ptrofs.unsigned i') = Some (make_vint h) ->\n           repr_unboxed_Codegen n h ->\n           related_boxed_or_same_val_Codegen m (b,i) m' (b', i')\n     | RBSI_pointer:\n         forall m b i  m' b' i' b1 i1 b2 i2,\n         Mem.load int_chunk m b (Ptrofs.unsigned i) = Some (Vptr b1 i1) ->\n         Mem.load int_chunk m' b' (Ptrofs.unsigned i') = Some (Vptr b2 i2) ->\n         (* TODO: may be Vint h and h' that needs to be interpreted as pointers inside m *)\n         (* TODO: make sure that *)\n         related_boxed_Codegen m (b1, i1) m' (b2,i2) ->\n         related_boxed_or_same_val_Codegen m (b,i) m' (b', i').\n\n(* TODO: related or boxed which also checks that what is reachable is in L *)\n(* \nInductive val_tree: Type :=\n| u_c_leaf :  int -> val_tree\n| f_leaf : block -> int -> val_tree\n| b_c_node : \n    (* header *) int ->\n                 list val_tree -> val_tree.\n\nFixpoint eq_val_trees (v1:val_tree) (v2:val_tree): bool :=\n  match v1, v2 with\n  | u_c_leaf i1, u_c_leaf i2 => Int.eq i1 i2\n  | f_leaf b1 ofs1, f_leaf b2 ofs2 =>\n    andb (Pos.eqb b1 b2) (Int.eq ofs1 ofs2)\n  | b_c_node h1 l1, b_c_node h2 l2 =>\n    andb (Int.eq h1 h2) (utils.forallb2 eq_val_trees l1 l2)\n  | _ , _ => false\n  end.\n\n\n\n(* need either fuel or assumption that blocks are increasing when allocated [thus decreasing while traversing] \n   fuel bounds the depth of the tree\n*)\nFixpoint load_val_tree (m:mem) (v:Values.val) (fuel:nat) : option val_tree :=\n  match fuel with\n  | S fuel' => \n    (match v with\n     | (Vptr b' i') =>\n       if (Mem.valid_pointer m b' (Int.unsigned i')) then\n         (* this is a b_c, load the header and then the rest of the tree *)\n         (match Mem.load int_chunk m b' ((Int.unsigned i') - int_size) with\n          | Some (Vint h) =>\n            (* get arity from header *)\n            let n := arity_of_header (Int.unsigned h) in\n            (* \n            let fix load_val_tree_ptr (m:mem) (b:block) (ofs:Z) (i:nat): option (list val_tree) :=\n                (match i with\n                | 0 =>  Some nil\n                | S i' =>\n                  (match Mem.load int_chunk m b ofs with\n                   | Some v =>\n                     (match load_val_tree m v fuel, load_val_tree_ptr m b (ofs + int_size)%Z i' with\n                      | Some vt, Some lv => Some (vt::lv)\n                      | _, _ => None\n                      end)\n                   | None => None\n                   end)\n                 end) in\n            \n            (match load_val_tree_ptr m b' (Int.unsigned i') (N.to_nat n) with\n             | Some vl => Some (b_c_node h vl)\n             | None => None\n             end) *)\n            None\n          | _ => None\n          end) \n       else\n         (* this is a function [ outside of m ]*)\n         Some (f_leaf b' i')    \n     | (Vint h) => Some (u_c_leaf h)\n     | _ => None\n     end)\n  | 0 => None\n  end\n.\n\n \n\n  *)\n  \n\n\n\n(* this is false, missing the boxed case which is off-shifted \nTheorem repr_val_ptr_load :\n  forall v6 m b i,\n    repr_val_ptr_LambdaANF_Codegen v6 m (b, i) ->\n    (exists v7, Mem.load int_chunk m b (Int.unsigned i)  = Some v7 /\\ repr_val_LambdaANF_Codegen v6 m v7)\n             \\/ exists F, Genv.find_funct (globalenv p) (Vptr b i) = Some (Internal F). *)\n\n(* relational version of get_allocs *)\nInductive get_allocs_ind: exp -> list positive -> Prop :=\n| GEI_constr: forall x t vs e l, get_allocs_ind e l -> get_allocs_ind (Econstr x t vs e) (x::l)\n| GEI_case: forall x cs l, get_allocs_case_ind cs l -> get_allocs_ind (Ecase x cs) l\n| GEI_proj: forall x t n v e l, get_allocs_ind e l -> get_allocs_ind (Eproj x t n v e) (x::l)\n| GEI_app: forall x t vs, get_allocs_ind (Eapp x t vs) []\n| GEI_prim: forall x p vs e l, get_allocs_ind e l -> get_allocs_ind (Eprim x p vs e) (x::l)\n| GEI_halt: forall x, get_allocs_ind (Ehalt x) []\n| GEI_fun: forall fnd e l l', get_allocs_fundefs_ind fnd l ->\n                              get_allocs_ind e l' ->\n                              get_allocs_ind (Efun fnd e) (l ++ l')\nwith get_allocs_case_ind: list (ctor_tag * exp) -> list positive -> Prop :=\n   | GEI_nil: get_allocs_case_ind nil nil\n   | GEI_cons: forall z e cs l l',\n       get_allocs_ind e l ->\n       get_allocs_case_ind cs l' ->\n       get_allocs_case_ind (cons (z, e) cs) (l++l')\nwith get_allocs_fundefs_ind: fundefs -> list positive -> Prop :=\n   | GEI_Fnil: get_allocs_fundefs_ind Fnil nil\n   | GEI_Fcons:\n       forall f t vs e fnd l l',\n         get_allocs_ind e l ->\n         get_allocs_fundefs_ind fnd l' ->\n       get_allocs_fundefs_ind (Fcons f t vs e fnd)  (vs++l++l').\n\n\n\nTheorem get_allocs_correct:\n  (forall e,\n      get_allocs_ind e (get_allocs e))\n  /\\\n  (forall fds,\n      get_allocs_fundefs_ind fds (get_allocs_fundefs fds)).\nProof.\n  eapply exp_def_mutual_ind; intros; simpl; try  (constructor; auto; fail).\n  - constructor. constructor.\n  - constructor. constructor. auto.\n    clear H.  inv H0. simpl in H3. induction l.\n    + constructor.\n    + inv H3. constructor. auto. auto.\nQed.\n\n\n  \n(* TODO: write this to ensure that the GC nevers runs out of space in the middle of a function*)\nDefinition correct_alloc: exp -> Z -> Prop := fun e i => i =  Z.of_nat (max_allocs e ).\n\nTheorem e_correct_alloc:\n  forall e, exists i, correct_alloc e i.\nProof.\n  intros.\n  eexists. unfold correct_alloc. reflexivity.\nQed.\n\n\n\nTheorem max_allocs_boxed: forall v c e l,\n    l <> nil -> \n(max_allocs (Econstr v c l e) = 1 + (length l) + max_allocs e).\nProof.\n  intros; simpl. induction l.\n  exfalso; auto.\n  destruct l. omega.\n  simpl.\n  simpl in IHl.\n  rewrite <- IHl. omega.\n  intro. inv H0.\nQed.\n\n\n(* see make_fundef_info, this is w.r.t. some fenv, another prop should assert the fenv is correct w.r.t. all functions *)\n\nDefinition correct_fundef_info (m:mem) (f:positive) (t:fun_tag) (vs:list positive) e finfo :=\n  exists n l b fi_0,\n   (* the tag for f points to a record r *)\n    M.get t fenv =  Some (n, l) /\\\n    n = N.of_nat (length l) /\\\n    length l = length vs /\\\n    (* no duplicate could be weaken if shared *)\n    NoDup l /\\\n    Forall (fun i => 0 <= (Z.of_N i) < max_args)%Z l /\\\n    (* id points to an array in global memory *)\n    Genv.find_symbol (globalenv p) finfo = Some b /\\\n    \n    (* \n 12/17 -- now looking this up in mem directly\nGenv.find_var_info (globalenv p) b = Some finfo_init /\\ \n*)\n    \n    (* the record has the right information w.r.t. vs and r \n       fi[0] = alloc(e)\n       fi[1] = number of roots\n       |fi| = 2+fi[1] *)\n    Mem.loadv int_chunk m (Vptr b Ptrofs.zero) = Some (make_vint fi_0) /\\\n    \n             Mem.loadv int_chunk m (Vptr b (Ptrofs.repr int_size)) = Some (make_vint (Z.of_N n)) /\\\n\n    (* gvar_init finfo_init = ((Init_int32 fi_0)::(Init_int32 fi_1)::fi_rest) /\\ *)\n             correct_alloc e fi_0 /\\\n             (int_size * fi_0 <= gc_size)%Z /\\\n                                         \n    (forall (i:N), (i < n)%N ->\n                   exists li, Mem.loadv int_chunk m (Vptr b (Ptrofs.repr (int_size*(Z.of_N (2+i)%N)))) = Some (make_vint (Z.of_N li)) /\\\n                                (nthN l i) = Some li).\n(*\n 12/17: probably need something w.r.t permissions \n/\\\n\n    (forall (j:N), (j < n + 2)%N -> \n        Mem.perm int_chunk m (Vptr b (Int.repr (int_size * (Z.of_N j)))) Readable) *)\n\n\n              \n(*     Forall2 (fun a i => exists i', i = Init_int32 i' /\\ (Z.of_N a) = Int.unsigned i')  l fi_rest. *)\n \n(* P is true of every fundefs in a bundle *)\n(* TODO: move this to cps_util *)\nInductive Forall_fundefs: (LambdaANF.cps.var -> fun_tag -> list LambdaANF.cps.var -> exp -> Prop) -> fundefs -> Prop :=\n| Ff_cons : forall (P:(LambdaANF.cps.var -> fun_tag -> list LambdaANF.cps.var -> exp -> Prop)) f t vs e fds,\n         P f t vs e -> \n         Forall_fundefs P fds ->\n         Forall_fundefs P (Fcons f t vs e fds)         \n| Ff_nil: forall P, Forall_fundefs P Fnil.\n\n\nTheorem Forall_fundefs_In:\n  forall P f t vs e fds,\n  Forall_fundefs P fds ->\n  fun_in_fundefs fds (f,t,vs,e) ->\n  P f t vs e.\nProof.\n  induction fds; intros.\n  - inv H; inv H0; subst.\n    + inv H; auto.\n    +  apply IHfds; auto.\n  - inv H0.\nQed.\n(* END TODO move *)\n\n\n(* 1) finfo_env has the correct finfo\n   2) fenv is consistent with the info\n   3) global env holds a correct Codegen representation of the function *)\nDefinition correct_environments_for_function:\n  genv -> fun_env -> M.t positive -> mem -> fundefs ->  LambdaANF.cps.var ->\n  fun_tag -> list LambdaANF.cps.var -> exp ->  Prop\n  := fun ge fenv finfo_env m fds f t vs e =>\n       exists l locs finfo b, \n         (*1*)\n         M.get f finfo_env = Some finfo /\\\n         correct_fundef_info m f t vs e finfo  /\\\n         (*2*)\n         M.get t fenv = Some (l, locs) /\\\n         l = N.of_nat (length vs) /\\\n         (* may want to check that locs are distinct and same as in finfo? *)\n         (*3*)\n         Genv.find_symbol (globalenv p) f = Some b /\\\n         (* TODO: change this to repr_val_LambdaANF_Codegen *)\n         repr_val_LambdaANF_Codegen (cps.Vfun (M.empty cps.val) fds f) m (Vptr b Ptrofs.zero).\n\n\nDefinition correct_environments_for_functions: fundefs -> genv -> fun_env -> M.t positive -> mem ->  Prop := fun fds ge fenv finfo_env m =>\n                                                                                                            Forall_fundefs (correct_environments_for_function ge fenv finfo_env m fds) fds.\n\n\nDefinition is_protected_id  (id:positive)  : Prop :=\n  List.In id protectedIdent.\n\nDefinition is_protected_tinfo_id (id:positive) : Prop :=\n    id = allocIdent \\/ id = limitIdent \\/ id = argsIdent.\n\nTheorem is_protected_tinfo_weak:\n  forall x, is_protected_tinfo_id x ->\n            is_protected_id x.\nProof.\n  intros. repeat destruct H; subst; inList. \nQed.\n\n                                               \n(* Domain of find_symbol (globalenv p) is disjoint from bound_var e /\\ \\sum_rho (bound_var_val x \\setminus names_in_fundef x) *)\n(*  *)\nDefinition functions_not_bound (rho:LambdaANF.eval.env) (e:exp): Prop :=\n  (forall x,\n    bound_var e x ->\n    Genv.find_symbol (Genv.globalenv p) x = None)/\\\n  (forall x y v,\n      M.get y rho = Some v ->\n      bound_notfun_val v x ->\n      Genv.find_symbol (Genv.globalenv p) x = None).\n\n\n\nInductive unique_bindings_val: LambdaANF.cps.val -> Prop :=\n| UB_Vfun: forall rho fds f,\n    unique_bindings_fundefs fds ->\n    unique_bindings_val (Vfun rho fds f)\n| UB_Vconstr: forall c vs,\n    Forall unique_bindings_val vs ->\n    unique_bindings_val (Vconstr c vs)\n|UB_VInt: forall z,\n    unique_bindings_val (cps.Vint z)\n.\n\n      \n(* UB + disjoint bound and in env *)\nDefinition unique_bindings_env (rho:LambdaANF.eval.env) (e:exp) : Prop :=\n      unique_bindings e  /\\ \n      (forall x v,\n        M.get x rho = Some v ->\n    ~ bound_var e x /\\ unique_bindings_val v). \n\nTheorem unique_bindings_env_prefix:\n  forall e rho,\n    unique_bindings_env rho e ->\n    forall rho',\n  prefix_ctx rho' rho ->\n  unique_bindings_env rho' e.\nProof.\n  intros.\n  inv H.\n  split; auto.\nQed.  \n\n\n(* TODO: also need UB for the functions in rho\nTheorem unique_bindings_env_weaken :\n  unique_bindings_env rho e ->\n  rho' subseteq rho\nunique_bindings_env rho e *)\n\n  \nTheorem functions_not_bound_subterm:\n  forall rho e,\n    functions_not_bound rho e ->\n    forall e',\n    subterm_e e' e ->\n    functions_not_bound rho e'.\nProof.\n  intros. split. intro; intros. \n  apply H.\n  eapply bound_var_subterm_e; eauto.\n  apply H.\nQed.  \n\nTheorem functions_not_bound_set:\n    forall rho e y v,\n      functions_not_bound rho e ->\n      (forall x, bound_notfun_val v x -> Genv.find_symbol (globalenv p) x = None) ->\n      functions_not_bound (M.set y v rho) e.\nProof.\n  intros. split. apply H.\n  intros. destruct (var_dec y0 y).\n  - subst. rewrite M.gss in H1. inv H1. destruct H. apply H0. auto. \n  - rewrite M.gso in H1 by auto. inv H. eapply H4; eauto.\nQed.\n    \nDefinition protected_id_not_bound  (rho:LambdaANF.eval.env) (e:exp) : Prop :=\n  (forall x y v, M.get x rho = Some v ->\n                 is_protected_id  y ->\n                 ~ (x = y \\/ bound_var_val v y) )/\\\n  (forall y, is_protected_id  y ->\n             ~ bound_var e y).\n\n\nTheorem protected_id_not_bound_prefix:\n  forall rho rho' e,\n    protected_id_not_bound rho e ->\n    prefix_ctx rho' rho ->\n    protected_id_not_bound rho' e.\nProof.\n  intros. inv H. split; intros.\n  - apply H0 in H.\n    apply H1; eauto.\n  - eapply H2; eauto.\nQed.\n\n \n    \nTheorem find_def_bound_in_bundle:\n  forall e y t xs f fds,\n  bound_var e y ->\n  find_def f fds = Some (t, xs, e) ->            \n  bound_var_fundefs fds y.\nProof.\n  induction fds; intros.\n  simpl in H0. destruct (cps.M.elt_eq f v). inv H0. constructor 3; auto.\n  constructor 2. apply IHfds; auto.\n  inv H0.\nQed.\n  \nTheorem protected_id_not_bound_closure:\n  forall rho e e' f' f fds rho' t xs,\n    protected_id_not_bound rho e ->\n    M.get f rho = Some (Vfun rho' fds f') ->\n    find_def f' fds = Some (t, xs, e') ->\n   protected_id_not_bound rho e'.\nProof.\n  intros.\n  inv H.\n  split. auto.\n  intros.\n  intro.\n  specialize (H2 _ _ _ H0 H).\n  apply H2. right.\n  constructor. \n  eapply find_def_bound_in_bundle; eauto.\nQed.\n\nTheorem protected_id_closure:\n  forall rho rho' f t0 ys fl f' t xs e' vs,\n    protected_id_not_bound rho (Eapp f t0 ys) ->\n    cps.M.get f rho = Some (Vfun (M.empty _) fl f') ->\n    get_list ys rho = Some vs ->\n    find_def f' fl = Some (t, xs, e') ->\n    set_lists xs vs (def_funs fl fl (M.empty _) (M.empty _)) = Some rho' -> \n    protected_id_not_bound rho' e'.\nProof.\n  intros.\n  assert (protected_id_not_bound rho e') by (eapply protected_id_not_bound_closure; eauto).\n  split. intros.\n  assert (decidable (List.In x xs)). apply In_decidable. apply shrink_cps_correct.var_dec_eq. \n  inv H7.\n  (* in vs *)\n  { inv H.\n    intro. inv H.\n    - specialize (H7 _ _ _ H0 H6). apply H7. right.\n      constructor. eapply shrink_cps_correct.name_boundvar_arg; eauto.\n    - assert (List.In v vs) by (eapply set_lists_In; eauto).\n      assert (Hgl := get_list_In_val _ _ _ _  H1 H). destruct Hgl.\n      destruct H11. specialize (H7 _ _ _ H12 H6). apply H7. auto.\n  }  \n  erewrite <- set_lists_not_In in H5.\n  2: eauto.\n  2: eauto.\n  assert (decidable (name_in_fundefs fl x)). unfold decidable. assert (Hd := Decidable_name_in_fundefs fl). inv Hd. specialize (Dec x). inv Dec; auto.\n      inv H7.\n        (*\n          2) in fl *)\n      rewrite def_funs_eq in H5. 2: eauto. inv H5.\n      inv H.\n      specialize (H5 _ _ _ H0 H6).\n      intro. inv H.\n\n      apply H5. right. constructor.\n      apply name_in_fundefs_bound_var_fundefs. auto.\n\n      apply H5. right. constructor. inv H10. auto.\n      \n      rewrite def_funs_neq in H5. 2: eauto.\n      rewrite M.gempty in H5. inv H5.\n        \n        apply H4.\nQed.\n\nInductive empty_cont: cont -> Prop :=\n| Kempty_stop: empty_cont Kstop\n| Kempty_switch: forall k, empty_cont k ->\n                           empty_cont (Kswitch k)\n| Kempty_sbreak: forall k, empty_cont k ->\n                           empty_cont (Kseq Sbreak k)\n| Kempty_sskip: forall k, empty_cont k ->\n                           empty_cont (Kseq Sskip k)\n.\nAbout int_size.\n                                      \nDefinition protected_non_reachable_val_Codegen v6 m v7 (lenv:temp_env) : Prop :=\n      exists alloc_b alloc_ofs limit_b limit_ofs args_b args_ofs,\n        M.get allocIdent lenv = Some (Vptr alloc_b alloc_ofs) /\\\n        ~reachable_val_Codegen v6 m v7 alloc_b alloc_ofs /\\\n        M.get limitIdent lenv = Some (Vptr limit_b limit_ofs) /\\\n        ~reachable_val_Codegen v6 m v7 limit_b limit_ofs /\\\n        M.get argsIdent lenv = Some (Vptr args_b args_ofs) /\\\n        (forall i,\n            Ptrofs.ltu i (Ptrofs.repr max_args) = true ->                   \n            ~reachable_val_Codegen v6 m v7 args_b (Ptrofs.add args_ofs (Ptrofs.mul (Ptrofs.repr int_size) i))).\n\n(* true if alloc, limit or args *)\nDefinition is_protected_loc lenv b ofs : Prop  :=\n  M.get allocIdent lenv = Some (Vptr b ofs)\n  \\/\n  M.get limitIdent lenv = Some (Vptr b ofs)\n  \\/\n  (exists args_ofs i, M.get argsIdent lenv = Some (Vptr b (Ptrofs.add args_ofs (Ptrofs.repr (int_size * i))))%Z /\\\n                      (0 <= i < max_args)%Z).\n\n\n(* L is the current allocated memory for user's datastructure\n   space between alloc_ofs and limit_ofs is not in L\n   anything in the args array is not in L\n   tinfo is not in L\n   anything pointed to by global env is not in L \n*)\n   \nDefinition protected_not_in_L (lenv:temp_env)  (L:block -> Z -> Prop): Prop :=\n  exists alloc_b alloc_ofs limit_ofs args_b args_ofs tinf_b tinf_ofs,\n    M.get allocIdent lenv = Some (Vptr alloc_b alloc_ofs) /\\\n    (forall j : Z, ((Ptrofs.unsigned alloc_ofs) <= j <\n                    Ptrofs.unsigned limit_ofs)%Z  ->\n                   ~ L alloc_b j) /\\\n    M.get limitIdent lenv = Some (Vptr alloc_b limit_ofs) /\\\n(*         (forall j : Z, ((Int.unsigned limit_ofs) <= j <\n                    Int.unsigned limit_ofs + size_chunk int_chunk)%Z  ->\n                   ~ L alloc_b_b j) *)\n    M.get argsIdent lenv = Some (Vptr args_b args_ofs) /\\\n          (forall z j: Z,\n              (0 <= z < max_args)%Z -> \n              ((Ptrofs.unsigned  (Ptrofs.add args_ofs (Ptrofs.repr (int_size * z))))\n               <= j <\n               (Ptrofs.unsigned (Ptrofs.add args_ofs (Ptrofs.repr (int_size * z)))) +  int_size)%Z ->\n\n              ~ L args_b j) /\\\n          (* tinfo_b is disjoint from L *)\n          M.get tinfIdent lenv = Some (Vptr tinf_b tinf_ofs) /\\\n          (forall i, ~ L tinf_b i) /\\\n          (* anything pointed out by the global env is disjoint from l *)\n          (forall x b,\n              Genv.find_symbol (globalenv p) x = Some b ->\n              b <> args_b /\\ b <> alloc_b   (* these are also covered by correct_tinfo, but convenient here *)\n            /\\  \n              forall i, ~ L b i) \n.\n\nTheorem protected_not_in_L_proper:\n  forall lenv lenv' L,\n    protected_not_in_L lenv L ->\n      map_get_r_l _ (cons argsIdent (cons limitIdent (cons allocIdent (cons tinfIdent nil)))) lenv lenv' ->\n      protected_not_in_L lenv' L.\nProof.\n  intros.\n  inv H. destructAll. rewrite H0 in *; inList.\n  do 7 eexists. repeat split; eauto.\n  eapply H7; eauto.\n  eapply H7; eauto.\n  eapply H7; eauto. \nQed.\n  \nTheorem protected_not_in_L_proper_weak:\n  forall lenv lenv' L ,\n  map_get_r _ lenv lenv' ->\n  protected_not_in_L lenv  L ->\n  protected_not_in_L lenv'  L.\nProof.\n  intros.\n  eapply protected_not_in_L_proper. eauto.\n  intro. intro. apply H.\nQed.\n \nTheorem protected_not_in_L_set:\n  forall lenv  L x v ,\n  protected_not_in_L lenv  L ->\n  ~ is_protected_tinfo_id x ->\n  x <> tinfIdent ->\n  protected_not_in_L (M.set x v lenv)  L.\nProof.\n  intros.\n  destruct H.\n  destructAll.\n  exists x0, x1, x2, x3, x4, x5, x6.\n  repeat split;auto.\n  - destruct (var_dec allocIdent x).\n    + exfalso; apply H0.\n      rewrite <- e.\n      unfold is_protected_id.\n      left; auto.\n    +  rewrite M.gso by auto. auto.\n  - destruct (var_dec limitIdent x).\n    + exfalso; apply H0.\n      rewrite <- e.\n      unfold is_protected_id.\n      right; auto.\n    +  rewrite M.gso by auto. auto.\n  - destruct (var_dec argsIdent x).\n    + exfalso; apply H0.\n      rewrite <- e.\n      unfold is_protected_id.\n      right; auto.\n    +  rewrite M.gso by auto. auto.\n  - rewrite M.gso; auto.\n  - eapply H8; eauto.\n  - eapply H8; eauto.\n  - eapply H8; eauto.\nQed.\n\nTheorem lenv_param_refl :\n  forall lenv lenv' vs, \n  lenv_param_asgn lenv lenv' [] vs\n  -> map_get_r _ lenv lenv'.\nProof.\n  intros.\n  intro.\n  specialize (H v).\n  destruct H.\n  symmetry.\n  apply H0.\n  intro.\n  inv H1.\nQed.\n \nTheorem lenv_param_asgn_not_in:\n  forall lenv lenv' b ofs x (L:positive -> Prop) xs vs7,\nM.get x lenv = Some (Vptr b ofs) ->\n  L x ->\n  (forall x6 : positive, List.In x6 xs -> ~ L x6) ->\n  lenv_param_asgn lenv lenv' xs vs7 ->\n  M.get x lenv' = Some (Vptr b ofs).\nProof.\n  intros.\n  specialize (H2 x).\n  destruct H2.\n  rewrite H3.\n  auto.\n  intro.\n  eapply H1; eauto.\nQed.\n\n\nTheorem lenv_param_asgn_map:\n  forall lenv lenv' xs vs7 l,\n  lenv_param_asgn lenv lenv' xs vs7 ->\n  Disjoint _ (FromList xs) (FromList l) ->\n  map_get_r_l _ l lenv lenv'.\nProof.  \n  intros.\n  intro.\n  intro.\n  specialize (H v); destruct H.\n  rewrite H2.\n  auto.\n  inv H0. specialize (H3 v).\n  intro.\n  apply H3.\n  auto.\nQed.\n\n  \n  Theorem protected_not_in_L_asgn:\n  forall L xs vs7 lenv lenv',\nprotected_not_in_L lenv  L ->\nlenv_param_asgn lenv lenv' xs vs7 ->\n(forall x, List.In x xs -> ~ (is_protected_tinfo_id x \\/ x = tinfIdent)) ->\nprotected_not_in_L lenv'  L.\n  Proof.\n    intros.\n    inv H; destructAll.\n    exists x, x0, x1, x2, x3, x4, x5.\n    \n    repeat split; auto; try (eapply lenv_param_asgn_not_in with (L :=  fun x => (is_protected_tinfo_id x \\/ x = tinfIdent)); eauto).\n    left; inList. left; inList.\n    left; inList. reflexivity.\n    eapply H8; eauto.\n    eapply H8; eauto.\n    eapply H8; eauto.\n  Qed.    \n\n  (* no longer needed without max_alloc *)\n      (* Mono + extra assumptions to avoid overflow \nTheorem protected_not_in_L_mono:\n  forall lenv alloc_b alloc_ofs z limit_ofs,\n    M.get allocIdent lenv = Some (Vptr alloc_b alloc_ofs) ->\n    M.get limitIdent lenv = Some (Vptr alloc_b limit_ofs) ->\n    ((Int.unsigned alloc_ofs) + int_size * z <=  Int.unsigned limit_ofs)%Z -> \n    forall L z', \n   protected_not_in_L lenv z L ->   \n  (0 <= z' <= z)%Z ->\n  protected_not_in_L lenv z' L.\nProof.\n  intros.\n  inv H2. destructAll.\n  rewrite H4 in H. inv H.\n  rewrite H6 in H0. inv H0.\n  exists alloc_b, alloc_ofs, limit_ofs.\n  do 4 (eexists). \n  repeat split; eauto.  \n  intros. apply H5.\n  unfold int_size in *; simpl size_chunk in *.\n  assert (Int.unsigned limit_ofs <= Int.max_unsigned)%Z by apply Int.unsigned_range_2 .\n  assert (0 <= Int.unsigned alloc_ofs)%Z by apply Int.unsigned_range_2 .\n  unfold Int.add in *.\n  rewrite Int.unsigned_repr with (z := (4 * z)%Z) by omega.\n  rewrite Int.unsigned_repr with (z := (4 * z')%Z) in H by omega.\n  rewrite Int.unsigned_repr by omega.\n  rewrite Int.unsigned_repr in H by omega. omega.\n  apply H11 in H; destructAll; auto.\n  apply H11 in H; destructAll; auto.\n  apply H11 in H; destructAll; auto.\nQed. *)\n \n   \nDefinition Vint_or_Vconstr (v:cps.val): Prop :=\n  (exists i, v = cps.Vint i) \\/ (exists c vs, v = cps.Vconstr c vs).\n\nDefinition correct_fundef_id_info (m:mem) (fds:fundefs) (f:positive) :=\n            exists finfo t t' vs e, (find_def f fds = Some (t, vs, e) /\\                          \n                                     M.get f finfo_env = Some (finfo , t') /\\\n                                     t = t' /\\\n                                     correct_fundef_info  m f t vs e finfo).\n\n(* relates a LambdaANF evaluation environment to a Clight memory up to the free variables in e *)\n(* If x is a free variable of e, then it might be in the generated code:\n   1) a function (may want to handle this separately as they won't get moved by the GC) in the global environment, evaluates to a location related to f by repr_val_ptr_LambdaANF_Codegen\n   2) a local variable in le related to (rho x) according to repr_val_LambdaANF_Codegen -- this happens when e.g. x := proj m, or after function initialization\n\nAll the values are in a space L which is disjoint form protected space\n\nNote that parameters are heap allocated, and at function entry \"free variables\" are held in args and related according to repr_val_ptr_LambdaANF_Codegen\n \nNow also makes sure none of the protected portion are reachable by the v7\n\nTODO: second section needs that for any such f s.t. find_def f fl = Some (t, vs4, e),  e is closed by  var (FromList vsm4 :|: name_in_fundefs fl)\n may want something about functions in rho, i.e. that they don't need to be free to be repr_val_id, since they are the only thing that may appear free in other functions body (and not bound in the opening \nmay need rho' also has the Vfun \n *) \n\n    Definition rel_mem_LambdaANF_Codegen: exp -> LambdaANF.eval.env -> mem -> temp_env -> Prop :=\n      fun e rho m le =>\n        exists L, protected_not_in_L le L /\\\n        (forall x,          \n        (occurs_free e x ->\n                  exists v6, M.get x rho = Some v6 /\\\n                             repr_val_id_L_LambdaANF_Codegen v6 m L le x)\n        /\\\n        (forall rho' fds f v,\n            M.get x rho = Some v ->\n            subval_or_eq (Vfun rho' fds f) v ->\n            repr_val_id_L_LambdaANF_Codegen (Vfun rho' fds f) m L le f /\\\n            closed_val (Vfun rho' fds f) /\\\n            correct_fundef_id_info m fds f)).\n(* \n    Theorem rel_mem_LambdaANF_Codegen_set_vconstr:\n      rel_mem_LambdaANF_Codegen e rho m lenv ->\n      rel_mem_LambdaANF_Codegen e rho m (M.set x (Vconstr c vs)) *)\n\n    (* this is wrong, the block after limit may be in L\n    Theorem protected_not_L:\n      forall e le b ofs L, \n      protected_not_in_L le (Z.of_nat (max_allocs e)) L ->\n      is_protected_loc le b (Int.repr ofs) -> forall i : Z, (ofs <= i < ofs + size_chunk int_chunk)%Z -> ~ L b i. *)\n\nDefinition unchanged_globals: mem -> mem -> Prop :=\n  fun m m' =>\n    forall x b,\n      Genv.find_symbol (globalenv p) x = Some b ->\n      forall i chunk, Mem.loadv chunk m (Vptr b i) =  Mem.loadv chunk m' (Vptr b i).\n\nTheorem unchanged_globals_trans:\n  forall m1 m2 m3,\n    unchanged_globals m1 m2 ->\n    unchanged_globals m2 m3 ->\n    unchanged_globals m1 m3.\nProof.\n  intros.\n  intro; intros.\n  specialize (H _ _ H1 i chunk).\n  specialize (H0 _ _ H1 i chunk).\n  rewrite H; rewrite H0.\n  reflexivity.\nQed.\n\nTheorem correct_fundefs_unchanged_global:\n  forall m m' fds f, \n    correct_fundef_id_info m fds f ->\n    unchanged_globals m m' ->\n    correct_fundef_id_info m' fds f.\nProof.\n  intros.\n  destruct H as [finfo [t [t' [vs [e H]]]]].\n  exists finfo, t, t', vs, e.\n  destruct H. destruct H1. destruct H2.\n  split; auto.\n  split; auto.\n  split; auto.\n  destruct H3 as [n [l [b [fi_0 [fi_1 H3]]]]].\n  exists n, l, b, fi_0.\n  destructAll.\n  repeat split; auto.\n  specialize (H0 finfo b); rewrite <- H0; auto.\n  specialize (H0 finfo b); rewrite <- H0; auto.\n  intros.\n  apply H12 in H2.\n  destruct H2 as [li H2].\n  exists li.\n  destructAll.\n  split; auto.\n  specialize (H0 finfo b); rewrite <- H0; auto.\nQed.\n\n \nTheorem store_globals_unchanged:\n  forall b' i m m' a,\n     Mem.store int_chunk m b' i a = Some m' ->\n (forall (x : ident) (b : block),\n          Genv.find_symbol (globalenv p) x = Some b -> b <> b') ->\n  unchanged_globals m m'. \nProof.\n  intros. \n  intro; intros. apply H0 in H1.\n  symmetry.\n  eapply Mem.load_store_other. apply H.\n  auto.\nQed.\n\nTheorem mem_after_n_proj_store_globals_unchanged:\n  forall b' i vs z  m m',\n  mem_after_n_proj_store b' i vs z m m' ->\n (forall (x : ident) (b : block),\n          Genv.find_symbol (globalenv p) x = Some b -> b <> b') ->\n  unchanged_globals m m'. \nProof.\n  induction vs; intros. inv H.\n  inv H.\n  - eapply store_globals_unchanged; eauto.\n  - specialize (IHvs _ _ _ H9 H0).\n    eapply unchanged_globals_trans; eauto.\n    eapply store_globals_unchanged; eauto. \nQed.\n\n\nTheorem rel_mem_update_protected:\n  forall e rho m le args_b args_ofs i v m',\n    rel_mem_LambdaANF_Codegen e rho m le ->\n    M.get argsIdent le = Some (Vptr args_b args_ofs) ->\n    (0 <= Z.of_N i < max_args)%Z ->\n    Mem.store int_chunk m args_b (Ptrofs.unsigned (Ptrofs.add args_ofs  (Ptrofs.repr (int_size * Z.of_N i)))) v = Some m' ->\n    rel_mem_LambdaANF_Codegen e rho m' le. \nProof. \n  intros. destruct H as [L Hrel_mem].\n  destruct Hrel_mem as [Hprotect Hof_v].      \n  exists L.\n  split; auto.\n  intro.\n  specialize (Hof_v x).\n  destruct Hof_v as [Hof_v1 Hof_v2].\n  split.\n  * intros. apply Hof_v1 in H. \n    destructAll. exists x0. split; auto.\n    eapply repr_val_id_L_unchanged.\n    eauto.\n    eapply Mem.store_unchanged_on. eauto.\n    intros.\n    inv Hprotect. destructAll. rewrite H10 in H0. inv H0.\n    eapply H11. eauto. unfold int_size in *.\n    split; auto.\n    \n  * intros. \n    specialize (Hof_v2 _ _ _ _ H H3). \n    destruct Hof_v2 as [Hof_v2 [Hv2_closed Hv2_f]]. split.\n    eapply repr_val_id_L_unchanged.\n    eauto.\n    eapply Mem.store_unchanged_on. eauto.\n    intros.     inv Hprotect. destructAll. rewrite H10 in H0. inv H0.\n    eapply H11. eauto. unfold int_size in *.\n    split; auto.\n    auto.\n    split. auto.\n    eapply correct_fundefs_unchanged_global.\n    eauto.\n    intro finfo; intros. \n    inv Hprotect. destructAll.\n    symmetry. eapply Mem.load_store_other.\n    eauto. left.\n    rewrite H9 in H0; inv H0. eapply H13. eauto.\nQed.\n  \n Fixpoint mem_of_state (s:state) : mem :=\n  match s with\n  | State f s k e le m => m\n  | Callstate f vs k m => m\n  | Returnstate x k m =>  m\n  end.\n\n\n  \n(* [pure] step with no built-in, i.e. trace is always E0 *)\nDefinition traceless_step2:  genv -> state -> state -> Prop := fun ge s s' => step2 ge s nil s'. \n\nDefinition m_tstep2 (ge:genv):=  clos_trans state (traceless_step2 ge).\n\nHint Unfold Ptrofs.modulus Ptrofs.max_unsigned uint_range : core.\nHint Transparent Ptrofs.max_unsigned Ptrofs.modulus uint_range : core.\n \nInductive mem_after_n_proj_store_rev: block -> Z -> (list Values.val) -> mem -> mem -> Prop :=\n| Mem_last_ind: forall m b ofs v m', \n    Mem.store int_chunk m b ofs v = Some m' ->\n    mem_after_n_proj_store_rev b ofs [v] m m'\n| Mem_next_ind:\n    forall b ofs vs v m m' m'', \n    mem_after_n_proj_store_rev b (ofs + int_size) vs m m' ->\n    Mem.store int_chunk m' b ofs v = Some m'' ->\n    mem_after_n_proj_store_rev b ofs (v::vs) m m''.\n  \nTheorem set_commute:\n  forall A (vx vy:A) (x y:positive) rho, \n    x <> y -> \n    M.set x vx (M.set y vy rho) = M.set y vy  (M.set x vx rho). \nProof.\n  induction x; intros; simpl; destruct y; try solve [simpl; destruct rho; reflexivity].\n  - simpl.  destruct rho. rewrite IHx. reflexivity. intro. apply H. subst. auto.\n      rewrite IHx. reflexivity. intro; apply H; subst; auto.\n  - simpl. destruct rho. rewrite IHx. reflexivity. intro. apply H. subst; auto.\n    rewrite IHx. reflexivity. intro; apply H; subst; auto.\n  - exfalso. auto.\nQed.\n  \n\n\n\n\n\nTheorem mem_of_Forall_nth_projection_cast:\n  forall x lenv b ofs f, \n    find_symbol_domain finfo_env ->\n    finfo_env_correct ->\n    M.get x lenv = Some (Vptr b ofs) ->\n    forall l s i m k,\n      (0 <= i /\\ i + (Z.of_nat (List.length l)) <= Ptrofs.max_unsigned )%Z ->\n      (forall j, 0 <= j < i + Z.of_nat (List.length l) -> Mem.valid_access m int_chunk b (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr  (int_size * j)))) Writable)%Z ->\n      Forall_statements_in_seq'\n        (is_nth_projection_of_x x) l s i ->\n      forall vs, \n      Forall2 (get_var_or_funvar lenv) l vs ->\n      exists m', m_tstep2 (globalenv p) (State f s k empty_env lenv m)\n               (State f Sskip k empty_env lenv m') /\\ \n      mem_after_n_proj_store_cast b (Ptrofs.unsigned ofs) vs i m m'.\nProof with archi_red.\n  intros x lenv b ofs f Hsym HfinfoCorrect Hxlenv.\n  induction l; intros s i m k Hil_max; intros.\n  - (* empty -- impossible *)\n    inv H1. inv H0. \n  -   assert (length (a :: l) = length vs) by (eapply Forall2_length'; eauto). rewrite H2 in *. clear H2.\n      assert (Hi_range : uint_range i) by solve_uint_range.\n     inv H1.\n     assert (Hvas :  Mem.valid_access m int_chunk b\n                                      (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr (int_size * i))))\n                                      Writable).\n     apply H. simpl. split.\n     omega.\n     rewrite Zplus_0_r_reverse with (n := i) at 1.\n     apply Zplus_lt_compat_l.\n     apply Pos2Z.is_pos.\n     assert (Hvra := Mem.valid_access_store m int_chunk b  (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr (int_size* i)))) y Hvas).\n     destruct Hvra as [m2 Hsm2].        \n     inv H0.\n     + (* last statement *)\n       inv H6.\n       inv H8.\n       exists m2.\n       split.\n       2:{\n       constructor. rewrite Ptrofs.repr_unsigned. auto. }\n       inv H0.\n       * inv H4. \n         2:{ exfalso. rewrite H1 in H0. inv H0. }\n         \n         rewrite H1 in H0; inv H0.\n         constructor.\n          \n         destruct (Archi.ptr64) eqn:Harchi. \n         { \n           econstructor.\n         constructor. econstructor. econstructor.\n         econstructor. apply Hxlenv. constructor.\n         archi_red. constructor.\n         archi_red. constructor.\n         specialize (Hsym a). inv Hsym.\n         destruct (H2 (ex_intro _ b1 H1)). destruct x0.\n         unfold makeVar. rewrite H3.\n         specialize (HfinfoCorrect _ _ _ H3). inv HfinfoCorrect.\n         destruct x0. rewrite H4. \n         econstructor.  apply eval_Evar_global.  apply M.gempty.\n\n         apply H1. constructor. constructor.\n         specialize (Hsym a). inv Hsym.\n         destruct (H2 (ex_intro _ b1 H1)). destruct x0.\n         unfold makeVar. rewrite H3. \n         specialize (HfinfoCorrect _ _ _ H3). inv HfinfoCorrect.\n         destruct x0. rewrite H4.\n         constructor.\n         eapply assign_loc_value.\n\n         2:{ unfold Ptrofs.of_int64.\n         rewrite Int64.unsigned_repr in *.\n         rewrite int_z_mul. archi_red. apply Hsm2.\n         solve_uint_range. archi_red. unfold Int64.max_unsigned. simpl; omega. \n         archi_red. auto. }\n         archi_red. \n         constructor. }\n         {\n           econstructor.\n         constructor. econstructor. econstructor.\n         econstructor. apply Hxlenv. constructor.\n         archi_red. constructor.\n         archi_red. constructor.\n\n         specialize (Hsym a). inv Hsym.\n         destruct (H2 (ex_intro _ b1 H1)). destruct x0.\n         unfold makeVar. rewrite H3. \n         specialize (HfinfoCorrect _ _ _ H3). inv HfinfoCorrect.\n         destruct x0. rewrite H4.\n         econstructor. apply eval_Evar_global.  apply M.gempty.\n         apply H1. constructor. constructor. \n         specialize (Hsym a). inv Hsym.\n         destruct (H2 (ex_intro _ b1 H1)). destruct x0.\n         unfold makeVar. rewrite H3.  \n         specialize (HfinfoCorrect _ _ _ H3). inv HfinfoCorrect.\n         destruct x0. rewrite H4.\n         constructor.\n         eapply assign_loc_value.\n\n         \n         2:{ unfold ptrofs_of_int.  unfold Ptrofs.of_intu.\n         unfold Ptrofs.of_int.\n         rewrite Int.unsigned_repr in *.\n         rewrite int_z_mul. archi_red. apply Hsm2.\n         solve_uint_range. archi_red. solve_uint_range. omega. \n         archi_red. auto. }\n         archi_red. \n         constructor.\n         }\n       * inv H4. exfalso; rewrite H1 in H0; inv H0.         \n         constructor.\n         destruct (Archi.ptr64) eqn:Harchi... \n\n         {\n           eapply step_assign with (v2 := y) (v := y). \n           constructor. econstructor. econstructor.\n           econstructor. apply Hxlenv. constructor.\n           constructor. constructor. constructor. apply H2.\n           simpl. destruct y; inv H3; auto.\n           eapply assign_loc_value. 2:{  unfold Ptrofs.of_int64.\n           rewrite Int64.unsigned_repr in *.\n           rewrite int_z_mul. archi_red. eauto. solve_uint_range.\n           archi_red. unfold Int64.max_unsigned. simpl; omega.\n           archi_red. auto. auto. } \n           constructor. }\n         {\n           eapply step_assign with (v2 := y) (v := y). \n           constructor. econstructor. econstructor.\n           econstructor. apply Hxlenv. simpl. unfold sem_cast. simpl. rewrite Harchi. constructor.\n           constructor. constructor. constructor. apply H2.\n           simpl.  destruct y; inversion H3; auto. simpl in H3. rewrite H3 in Harchi; inv Harchi.\n           unfold sem_cast. simpl. rewrite Harchi. constructor.\n           eapply assign_loc_value.\n           2:{ unfold ptrofs_of_int. unfold Ptrofs.of_intu. unfold Ptrofs.of_int.\n           rewrite Int.unsigned_repr. \n           rewrite int_z_mul. eauto. solve_uint_range.\n           archi_red. solve_uint_range. omega.\n           archi_red. auto.\n           solve_uint_range. }\n           constructor. }\n         \n     +  (* IH *)\n       inv H9.\n       eapply IHl with (m := m2) in H5; eauto. destruct H5 as [m3 [H5a H5b]]. exists m3.       \n       split.\n       2:{ econstructor. rewrite Ptrofs.repr_unsigned. apply Hsm2. apply H5b. }\n\n       inv H0.\n       * inv H4.\n         2:{ exfalso; rewrite H1 in H0; inv H0. }\n         rewrite H1 in H0; inv H0.\n         eapply t_trans.\n         econstructor.  constructor.\n         (* branch here *)\n         destruct (Archi.ptr64) eqn:Harchi... \n         { \n         eapply t_trans. constructor. econstructor.\n         constructor. econstructor. econstructor. constructor. eauto. constructor.\n         constructor. constructor. \n         specialize (Hsym a). inv Hsym.\n         destruct (H2 (ex_intro _ b1 H1)). destruct x0.\n         unfold makeVar. rewrite H3. econstructor.   \n         specialize (HfinfoCorrect _ _ _ H3). inv HfinfoCorrect.\n         destruct x0. rewrite H4.  \n         apply eval_Evar_global. apply M.gempty. eauto.\n         specialize (HfinfoCorrect _ _ _ H3). inv HfinfoCorrect.\n         destruct x0. rewrite H4. \n         constructor. constructor.\n         specialize (Hsym a). inv Hsym.\n         destruct (H2 (ex_intro _ b1 H1)). destruct x0.\n         unfold makeVar. rewrite H3.\n         specialize (HfinfoCorrect _ _ _ H3). inv HfinfoCorrect.\n         destruct x0. rewrite H4. \n         constructor. eapply assign_loc_value. constructor.\n          unfold Ptrofs.of_int64.\n           rewrite Int64.unsigned_repr in *. \n           rewrite int_z_mul. eauto. solve_uint_range.\n           archi_red. unfold Int64.max_unsigned. simpl; omega.\n           archi_red. auto. auto. \n         eapply t_trans. constructor. constructor.\n         apply H5a. }\n         { \n         eapply t_trans. constructor. econstructor.\n         constructor. econstructor. econstructor. constructor. eauto. unfold sem_cast. simpl. archi_red. constructor.\n         constructor. constructor.\n         specialize (Hsym a). inv Hsym.\n         destruct (H2 (ex_intro _ b1 H1)). destruct x0.\n         unfold makeVar. rewrite H3.\n         specialize (HfinfoCorrect _ _ _ H3). inv HfinfoCorrect.\n         destruct x0. rewrite H4. \n         econstructor.          \n         apply eval_Evar_global.  apply M.gempty. eauto. constructor. constructor.\n         unfold sem_cast. simpl. archi_red. \n         specialize (Hsym a). inv Hsym.\n         destruct (H2 (ex_intro _ b1 H1)). destruct x0.\n         unfold makeVar. rewrite H3. specialize (HfinfoCorrect _ _ _ H3). inv HfinfoCorrect.\n         destruct x0. rewrite H4. constructor.  eapply assign_loc_value. constructor.\n         unfold ptrofs_of_int. unfold Ptrofs.of_intu. unfold Ptrofs.of_int.\n           rewrite Int.unsigned_repr in *. \n         rewrite int_z_mul. eauto. solve_uint_range.\n         archi_red. solve_uint_range. omega.\n         archi_red. solve_uint_range. omega. \n         eapply t_trans. constructor. constructor.\n         apply H5a. }\n         \n       * inv H4. exfalso; rewrite H1 in H0; inv H0.\n         (* branch here *)\n         destruct (Archi.ptr64) eqn:Harchi... \n{         eapply t_trans.\n         econstructor.  constructor.\n         eapply t_trans. constructor. eapply step_assign with (v2 := y) (v := y). \n         constructor. econstructor. econstructor. constructor. eauto. constructor.\n         constructor. constructor. econstructor. auto. simpl.\n         destruct y; inv H3; auto.\n         eapply assign_loc_value.\n         2:{ unfold Ptrofs.of_int64.\n           rewrite Int64.unsigned_repr in *.\n\n           rewrite int_z_mul. apply Hsm2. solve_uint_range.  archi_red; eauto.\n           unfold Int64.max_unsigned; simpl; omega. archi_red; auto. auto. }\n           constructor.\n         eapply t_trans. constructor. constructor.\n         apply H5a. }\n\n{         eapply t_trans.\n         econstructor.  constructor.\n         eapply t_trans. constructor. eapply step_assign with (v2 := y) (v := y). \n         constructor. econstructor. econstructor. constructor. eauto. unfold sem_cast.\n         simpl. archi_red. constructor. \n         constructor.\n         constructor. constructor.  auto. simpl.\n         destruct y; inversion H3; auto. simpl in H3. rewrite H3 in Harchi; inv Harchi.\n         unfold sem_cast. simpl. archi_red. constructor.\n         eapply assign_loc_value.\n         2:{ unfold ptrofs_of_int. unfold Ptrofs.of_intu. unfold Ptrofs.of_int.\n         rewrite Int.unsigned_repr. \n         rewrite int_z_mul. apply Hsm2. solve_uint_range.  archi_red. solve_uint_range.\n         omega. archi_red. auto. auto. }\n         constructor.\n         eapply t_trans. constructor. constructor.\n         apply H5a. } \n\n\n       * destruct Hil_max.\n         split. apply Z.lt_le_incl.  apply Zle_lt_succ. auto.\n         simpl in H2. rewrite Zpos_P_of_succ_nat in H2. rewrite Z.add_succ_comm. \n         assert (Hll' : length l = length l') by (eapply Forall2_length'; eauto).         \n         rewrite Hll' in *. auto.\n       * intros.\n         eapply Mem.store_valid_access_1. apply Hsm2.\n         apply H. simpl.\n         rewrite Zpos_P_of_succ_nat.\n         assert (Hll' : length l = length l') by (eapply Forall2_length'; eauto).         \n         rewrite Hll' in *. \n         omega.\nQed.         \n\n\n\n\n\n\n\nEnd RELATION.\n\n\n \n\nSection THEOREM.\n\n\nLtac archi_red :=\n  int_red;\n  unfold int_chunk in *;\n  unfold val in *;\n  unfold uval in *;\n  unfold val_typ in *;\n  unfold Init_int in *;\n  unfold make_vint in *;\n  unfold c_int' in *;\n  unfold uint_range in *;\n  try (rewrite ptrofs_mu in *);\n  (match goal with\n   | [ H : Archi.ptr64 = _ |- _] => try (rewrite H in *)\n   end).\n\n(* these ltac are agnostic on archi, useful for automation *)   \n   Ltac ptrofs_of_int :=\n     unfold Ptrofs.of_int64 in *;\n     unfold ptrofs_of_int in *;\n     unfold Ptrofs.of_intu in *;\n     unfold Ptrofs.of_int in *.\n\n   Ltac int_unsigned_repr :=\n     try (rewrite Int64.unsigned_repr in *);\n     try (rewrite Int.unsigned_repr in *).\n          \n   Ltac int_max_unsigned:=  \n     try (rewrite Int64.max_unsigned in *);\n     try (rewrite Int.max_unsigned in *).\n     \n\n\n  \nNotation vval := val. (* NOTE: in Clight, SIZEOF_PTR == SIZEOF_INT *)\nNotation uval := val.\n\nNotation valPtr := (Tpointer vval\n                            {| attr_volatile := false; attr_alignas := None |}).\n\n\n  (* same as LambdaANF_to_Clight *)\n  Variable (argsIdent : ident).\n  Variable (allocIdent : ident).\n  Variable (limitIdent : ident).\n  Variable (gcIdent : ident).\n  Variable (mainIdent : ident).\n  Variable (bodyIdent : ident).\n  Variable (threadInfIdent : ident).\n  Variable (tinfIdent : ident).\n  Variable (heapInfIdent : ident).\n  Variable (numArgsIdent : ident).  \n  Variable (isptrIdent: ident). (* ident for the isPtr external function *)\n  Variable (caseIdent:ident).\n  Variable (nParam:nat).\n\n  Definition protectedIdent_thm := protectedIdent argsIdent allocIdent limitIdent gcIdent mainIdent bodyIdent threadInfIdent tinfIdent heapInfIdent numArgsIdent isptrIdent caseIdent.\n  Variable (disjointIdent: NoDup protectedIdent_thm).\n  \n  Definition protectedNotTinfoIdent_thm: list ident := (gcIdent::mainIdent::bodyIdent::threadInfIdent::tinfIdent::heapInfIdent::numArgsIdent::numArgsIdent::isptrIdent::caseIdent::[]).\n\n  \n  Definition is_protected_id_thm := is_protected_id argsIdent allocIdent limitIdent gcIdent mainIdent bodyIdent threadInfIdent tinfIdent heapInfIdent numArgsIdent isptrIdent caseIdent. \n\n  Definition is_protected_tinfo_id_thm := is_protected_tinfo_id argsIdent allocIdent limitIdent.\n\n  Definition repr_val_id_L_LambdaANF_Codegen_thm := repr_val_id_L_LambdaANF_Codegen argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam.\n\n  Definition repr_val_LambdaANF_Codegen_thm := repr_val_LambdaANF_Codegen argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam. \n  \n\n\nTheorem is_protected_not_tinfo:\n  forall x, List.In x protectedNotTinfoIdent_thm ->\n            ~ is_protected_tinfo_id_thm x.\nProof.\n intros.  \n intro.\n assert (H_dj := disjointIdent).\n inv H_dj. inv H4. inv H6. \n inv H0.\n apply H5. right; auto.\n inv H1.\n apply H4; auto.\n apply H3. right; right; auto.\nQed.\n \n(*\n    Variable cenv:LambdaANF.cps.ctor_env.\n  Variable fenv:LambdaANF.cps.fun_env.\n  Variable finfo_env: M.t positive. (* map from a function name to its type info *)\n  Variable p:program.\n  \n  \n  (* This should be a definition rather than a parameter, computed once and for all from cenv *)\n  Variable rep_env: M.t ctor_rep.\n*)\n\n\n  (* TODO: move this to cps_util *)\n  Definition Forall_constructors_in_e (P: var -> ctor_tag -> list var -> Prop) (e:exp) := \n    forall x t  ys e',\n      subterm_or_eq (Econstr x t ys e') e -> P x t ys.\n      \n\n  Definition Forall_projections_in_e (P: var -> ctor_tag -> N -> var -> Prop) (e:exp) :=\n    forall x t n v e',\n      subterm_or_eq (Eproj x t n v e') e -> P x t n v.\n  \n  (* Note: the fundefs in P is the whole bundle, not the rest of the list *)\n  Definition Forall_functions_in_e (P: var -> fun_tag -> list var -> exp ->  fundefs -> Prop) (e:exp) :=\n    forall fds e' f t xs e'',  subterm_or_eq (Efun fds e') e ->\n                               fun_in_fundefs fds (f, t, xs, e'') ->\n                               P f t xs e'' fds.\n\n\n  Definition Forall_exp_in_caselist (P: exp -> Prop) (cl:list (ctor_tag * exp)) := \n    forall g e, List.In (g, e) cl -> P e.\n\n\n\n  \n  Theorem crt_incl_ct:\n          forall T P e e', \n          clos_trans T P e e' ->\n          clos_refl_trans T P e e'.\n  Proof.\n    intros. induction H. constructor; auto.\n    eapply rt_trans; eauto.\n  Qed.    \n    \n  Theorem Forall_constructors_subterm:\n    forall P e e' ,\n    Forall_constructors_in_e P e ->\n    subterm_e e' e ->\n    Forall_constructors_in_e P e'. \n  Proof.\n    intros. intro; intros.\n    eapply H.\n    assert (subterm_or_eq e' e).\n    apply crt_incl_ct.\n    apply H0.\n    eapply rt_trans; eauto.\n  Qed.\n \n   \n  (* END TODO move *)\n\n  (* all constructors in the exp exists in cenv and are applied to the right number of arguments \n    May want to have \"exists in cenv\" also true for constructors in rho *)\n  Definition correct_cenv_of_exp: LambdaANF.cps.ctor_env -> exp -> Prop :=\n    fun cenv e =>\n      Forall_constructors_in_e (fun x t ys =>\n                                  match (M.get t cenv) with\n                                  | Some (Build_ctor_ty_info _ _ _ a _) =>\n                                    N.of_nat (length ys) = a\n                                  | None => False\n                                  end) e.\n\n  Definition correct_cenv_of_caselist: LambdaANF.cps.ctor_env -> list (ctor_tag * exp) -> Prop :=\n    fun cenv cl =>\n      Forall_exp_in_caselist (correct_cenv_of_exp cenv) cl.\n\n\n  \n  Theorem correct_cenv_of_case:\n    forall cenv v l, \n      correct_cenv_of_exp cenv (Ecase v l) ->\n      correct_cenv_of_caselist cenv l.\n  Proof.\n    intros; intro; intros.\n    eapply Forall_constructors_subterm. apply H.\n    constructor. econstructor. eauto.\n  Qed.  \n\n  Theorem Forall_constructors_in_constr:\n  forall P x t ys e,\n  Forall_constructors_in_e P (Econstr x t ys e) ->\n  P x t ys.\n  Proof.\n    intros.\n    unfold Forall_constructors_in_e in *.\n    eapply H.\n    apply rt_refl.\n  Qed.\n\n\n  \n  Theorem nodup_test:\n    forall (x1 x2 x3 x4 x5: positive),\n  NoDup [x1; x2; x3; x4; x5] ->\n   x4 <> x2.\n  Proof.\n    intros.\n    intro; subst.\n    inversion H as [H1 | x l H1 H2]; subst.\n    try (solve [apply H1; inList]).\n    inversion H2 as [H3 | x l H3 H4]; subst.\n    try (solve [apply H3; inList]).\n  Qed.\n\n\n\nInductive correct_cenv_of_val: LambdaANF.cps.ctor_env -> (LambdaANF.cps.val) -> Prop :=\n| CCV_constr:forall cenv c vs inf,\n    Forall (correct_cenv_of_val cenv) vs ->\n    M.get c cenv = Some inf ->\n    N.of_nat (length vs) = ctor_arity inf ->\n    correct_cenv_of_val cenv (Vconstr c vs)\n| CCV_fun: forall cenv rho fds f,\n    Forall_fundefs (fun v t xs e => correct_cenv_of_exp cenv e) fds -> \n    correct_cenv_of_val cenv (Vfun rho fds f)\n| CCV_int: forall cenv z,\n    correct_cenv_of_val cenv (cps.Vint z).\n                          \n  \n\n(* everything in cenv is in ienv, AND there is a unique entry for it, AND its ord is not reused \n    Doesn't check that name of the i will be consistent (namei could be different from name') *)\n  Definition correct_ienv_of_cenv: LambdaANF.cps.ctor_env -> n_ind_env -> Prop :=\n    fun cenv ienv =>\n      forall x, forall i a ord name name', M.get x cenv = Some (Build_ctor_ty_info name name' i a ord) ->\n                                   exists  namei cl, M.get i ienv = Some (namei, cl) /\\ List.In (name, x, a, ord) cl /\\ ~ (exists ord' name' a', (name', a', ord') <> (name, a, ord) /\\ List.In (name', x, a', ord') cl) /\\ ~ (exists name' x' a', (name', x', a') <> (name, x, a) /\\ List.In (name', x', a', ord) cl).\n\n  (* all constructors found in ienv are in cenv *) \n  Definition domain_ienv_cenv:  LambdaANF.cps.ctor_env -> n_ind_env -> Prop :=\n    fun cenv ienv =>\n      forall i namei cl, M.get i ienv = Some (namei, cl)  ->\n                         forall name x a ord, List.In (name, x, a, ord) cl ->\n                                              exists namei', M.get x cenv = Some (Build_ctor_ty_info name namei' i a ord).              \n\n                                   \n\n(* stronger version of ienv_of_cenv that enforces uniqueness of name' for i and that nothing is in ienv and not in cenv *)\n    Definition correct_ienv_of_cenv_strong: LambdaANF.cps.ctor_env -> n_ind_env -> Prop :=\n    fun cenv ienv =>\n      forall x, forall i a ord name namei, M.get x cenv = Some (Build_ctor_ty_info name namei i a ord) ->\n                                   exists   cl, M.get i ienv = Some (namei, cl) /\\ List.In (name, x, a, ord) cl /\\ ~ (exists ord' name' a', (name', a', ord') <> (name, a, ord) /\\ List.In (name', x, a', ord') cl) /\\ ~ (exists name' x' a', (name', x', a') <> (name, x, a) /\\ List.In (name', x', a', ord) cl).\n \n  \n  \n\n  (* OS 04/24: added in bound on n includes in this *) \n  Inductive correct_crep (cenv:ctor_env): ctor_tag -> ctor_rep -> Prop :=\n  | rep_enum :\n      forall c name namei it  n,\n        M.get c cenv = Some (Build_ctor_ty_info name namei it 0%N n) ->\n        (* there should not be more than 2^(intsize - 1) unboxed constructors *)\n        (0 <= (Z.of_N n) <   Ptrofs.half_modulus)%Z ->\n      correct_crep cenv c (enum n)\n  | rep_boxed:\n      forall c name namei it a n,\n        M.get c cenv = Some (Build_ctor_ty_info name namei it (Npos a%N) n) ->\n        (* there should not be more than 2^8 - 1 boxed constructors *)\n        (0 <= (Z.of_N n) <  Zpower.two_p 8)%Z ->\n        (* arity shouldn't be higher than 2^54 - 1  *)\n        (0 <= Z.of_N (Npos a) <  Zpower.two_power_nat (Ptrofs.wordsize - 10))%Z -> \n      correct_crep cenv c (boxed n (Npos a)).\n\n  (* crep <-> make_ctor_rep cenv *)\n  Definition correct_crep_of_env: LambdaANF.cps.ctor_env -> M.t ctor_rep -> Prop :=\n    fun cenv crep_env =>\n      (forall c name namei it a n,\n        M.get c cenv = Some (Build_ctor_ty_info name namei it a n) ->\n        exists crep, M.get c crep_env = Some crep /\\\n                     correct_crep cenv c crep) /\\\n      (forall c crep, M.get c crep_env = Some crep ->\n                     correct_crep cenv c crep).\n\n\n  Definition correct_cenv_of_env: ctor_env -> cps.M.t cps.val -> Prop :=\n    fun cenv rho =>\n      forall x v,\n        M.get x rho = Some v ->\n        correct_cenv_of_val cenv v.\n   \n  Definition correct_envs: ctor_env -> n_ind_env -> M.t ctor_rep ->  cps.M.t cps.val ->  exp -> Prop :=\n    fun cenv ienv crep_env rho e =>\n      correct_ienv_of_cenv cenv ienv /\\\n      correct_cenv_of_env cenv rho /\\\n      correct_cenv_of_exp cenv e /\\\n      correct_crep_of_env cenv crep_env. \n   \n  Theorem correct_envs_subterm:\n    forall cenv ienv crep rho e,\n           correct_envs cenv ienv crep rho e ->\n    forall e', subterm_e e' e ->\n               correct_envs cenv ienv crep rho e'.\n  Proof.\n    intros.\n    inv H. inv H2. inv H3. split; auto.\n    split; auto. split; auto.\n    eapply Forall_constructors_subterm; eauto.\n  Qed.    \n\n \n  Theorem correct_envs_set:\n    forall cenv ienv crep rho x v e,\n    correct_envs cenv ienv crep rho e ->\n    correct_cenv_of_val cenv v ->\n    correct_envs cenv ienv crep (M.set x v rho) e. \n  Proof.\n    intros.\n    inv H. inv H2. inv H3.\n    split; auto. split; auto.\n    intro; intros. destruct (var_dec x0 x).\n    - subst.  rewrite M.gss in H3.\n      inv H3. auto.\n    - rewrite M.gso in H3 by auto.\n      eapply H; eauto.\n  Qed.\n \n  \n  (* \n   correct_tinfo alloc_id limit_id args_id alloc_max le m\n  > alloc and limit are respectively valid and weak-valid pointers in memory, alloc is at least max before limit_id\n  > args points to an array of size max_args in memory before alloc \n\nlimit might be on the edge of current memory so weak_valid, alloc and args are pointing in mem. the int is the max number of blocks allocated by the function \n\n   *)\n   \nDefinition correct_tinfo: program ->  Z -> temp_env ->  mem  -> Prop :=\n  fun p max_alloc lenv m  =>\n    exists alloc_b alloc_ofs limit_ofs args_b args_ofs tinf_b tinf_ofs,\n      M.get allocIdent lenv = Some (Vptr alloc_b alloc_ofs) /\\\n      (align_chunk int_chunk | Ptrofs.unsigned alloc_ofs)%Z /\\\n      (* everything between alloc_ofs and limit_fs is writable *)\n      Mem.range_perm m alloc_b (Ptrofs.unsigned alloc_ofs) (Ptrofs.unsigned limit_ofs) Cur Writable /\\\n      M.get limitIdent lenv = Some (Vptr alloc_b limit_ofs) /\\\n      (* alloc is at least max blocks from limit *)\n      (int_size*max_alloc <= (Ptrofs.unsigned limit_ofs -  Ptrofs.unsigned alloc_ofs) <= gc_size)%Z /\\\n      M.get argsIdent lenv = Some (Vptr args_b args_ofs) /\\\n      (* args is in a different block from alloc *) \n      args_b <> alloc_b /\\\n      (* the max_args int blocks after args are Writable *)\n      ((Ptrofs.unsigned args_ofs)+ int_size * max_args <= Ptrofs.max_unsigned)%Z  /\\\n      (forall i, 0 <= i < max_args ->  Mem.valid_access m int_chunk args_b (Ptrofs.unsigned (Ptrofs.add args_ofs (Ptrofs.mul (Ptrofs.repr int_size) (Ptrofs.repr i))))  Writable)%Z /\\\n      M.get tinfIdent lenv = Some (Vptr tinf_b tinf_ofs) /\\\n      tinf_b <> args_b /\\\n      tinf_b <> alloc_b /\\\n      (* valid access on four pointers in tinfo *)\n      (forall i, 0 <= i < 4 -> Mem.valid_access m int_chunk tinf_b (Ptrofs.unsigned (Ptrofs.add tinf_ofs (Ptrofs.repr (int_size*i)))) Writable)%Z\n      /\\  deref_loc (Tarray uval maxArgs noattr) m tinf_b (Ptrofs.add tinf_ofs (Ptrofs.repr (int_size*3))) (Vptr args_b args_ofs) /\\\n(* everything pointed to by globals is valid, and not alloc, tinf or args*)\n      (forall x b,\n          Genv.find_symbol (globalenv p) x = Some b ->\n          b <> args_b /\\ b <> alloc_b /\\ b <> tinf_b /\\ (exists chunk, Mem.valid_access m chunk b 0%Z Nonempty)).\n\n\nTheorem range_perm_to_valid_access:\n  forall alloc_b alloc_ofs limit_ofs size m,\n    Mem.range_perm m alloc_b alloc_ofs limit_ofs Cur Writable ->\n    forall ofs, \n      (align_chunk size | ofs)%Z ->\n      (alloc_ofs <= ofs)%Z ->\n      (ofs + size_chunk size <= limit_ofs)%Z ->\n      Mem.valid_access m size alloc_b ofs Writable.\n  Proof.\n    intros.\n    constructor; auto.\n    intro. intro.\n    eapply H.\n    omega.\n  Qed.      \n    \n\nTheorem correct_tinfo_mono:\n  forall p z lenv m,\n    correct_tinfo p z lenv m ->\n    forall z', \n      (0 <= z' <= z)%Z ->\n    correct_tinfo p z' lenv m. \nProof.\n  intros.\n  inv H; destructAll.\n  do 7 eexists.\n  repeat (split; eauto).\n  unfold int_size in *. chunk_red; omega.\nQed.  \n\n\nTheorem correct_tinfo_proper:\n  forall p z lenv m lenv',\n  correct_tinfo p z lenv m ->\n  map_get_r_l _ [argsIdent; limitIdent; allocIdent;  tinfIdent] lenv lenv' ->\n  correct_tinfo p z lenv' m.\nProof.  \n  intros.\n  inv H; destructAll.\n  exists x, x0, x1, x2, x3, x4, x5.\n  repeat (split; auto; try (rewrite <- H0; auto; inList)).\nQed.  \n\nTheorem correct_tinfo_not_protected:\n  forall p z lenv m,\n  correct_tinfo p z lenv m ->\n  forall x v, \n    ~ is_protected_tinfo_id_thm x ->\n    x <> tinfIdent ->\n  correct_tinfo p z (M.set x v lenv) m. \nProof.\n  intros.\n  destruct H as [alloc_b [alloc_ofs [limit_ofs [args_b [args_ofs [tinf_b [tinf_ofs H]]]]]]].\n  exists alloc_b, alloc_ofs, limit_ofs, args_b, args_ofs, tinf_b, tinf_ofs.\n  destructAll.\n  repeat (split; auto).\n  rewrite M.gso; auto. intro. apply H0. left; auto. \n  rewrite M.gso; auto. intro. apply H0. right; auto. \n  rewrite M.gso; auto. intro. apply H0. right; auto.\n  rewrite M.gso; auto. \nQed.\n\n  \nTheorem correct_tinfo_param_asgn:\n  forall p lenv m xs z vs7 lenv',\n  correct_tinfo p z lenv m ->\n  lenv_param_asgn lenv lenv' xs vs7 ->\n  (forall x, List.In x xs -> ~ (is_protected_tinfo_id_thm x \\/ x = tinfIdent)) ->\n  correct_tinfo p z lenv' m.\nProof. \n  intros.\n  destruct H.\n  destructAll.\n  exists x, x0, x1, x2, x3, x4, x5.\n  repeat (split; auto; try (eapply lenv_param_asgn_not_in with (L :=  fun x => (is_protected_tinfo_id_thm x \\/ x = tinfIdent)); eauto; try (left; inList); try (right; reflexivity))).\nQed.\n  \n\n\n\n\nTheorem mem_range_valid: forall m m', \n    (forall b ofs ofs'  p, Mem.range_perm m b ofs ofs' Cur p -> Mem.range_perm m' b ofs ofs' Cur p) <->\n    (forall b ofs chunk  p, Mem.valid_access m chunk b ofs p -> Mem.valid_access m' chunk b ofs p).\nProof.\n  split.\n  - intros.\n    inv H0.\n    apply H in H1.\n    constructor;  auto.\n  - intros.\n    intro.\n    intros.\n    specialize (H b ofs0  Mint8unsigned p).\n    apply H0 in H1.\n    assert ( Mem.valid_access m Mint8unsigned b ofs0 p).\n    constructor. simpl. intro. intro. assert (ofs0 = ofs1)%Z by omega. subst; auto.\n    simpl. apply Z.divide_1_l. apply H in H2. inv H2. simpl in H3.\n    eapply H3. omega.\nQed.\n\n\nTheorem correct_tinfo_valid_access:\n  forall  p z lenv m,\n    correct_tinfo p z lenv m ->\n    forall m',\n    (forall b ofs ofs'  p, Mem.range_perm m b ofs ofs' Cur p -> Mem.range_perm m' b ofs ofs' Cur p) ->\n    correct_tinfo p z lenv m'. \nProof.\n  intros.\n  unfold correct_tinfo in H. \n  destruct H as [alloc_b [alloc_ofs [limit_ofs [args_b [args_ofs [tinf_b [tinf_ofs [Hget_alloc [Hdiv_alloc [Hrange_alloc [Hget_limit [Hbound_limit [Hget_args [Hdj_args [Hbound_args [Hrange_args [Hget_tinf [Htinfne1 [Htinfne2 [Hinf_limit [Hloc_args  Hglobal ]]]]]]]]]]]]]]]]]]]]].\n  do 7 eexists.\n  \n  repeat (split; eauto).\n  eapply H0.\n  eapply Hrange_args.\n  auto.\n  \n  apply Hrange_args in H.\n  inv H. auto.\n  eapply H0.\n  apply Hinf_limit. auto.\n  apply Hinf_limit. auto.\n \n  inv Hloc_args. inv H. constructor; auto. inv H1.\n\n\n  \n  apply Hglobal in H. destructAll; auto.\n  apply Hglobal in H; destructAll; auto.\n  apply Hglobal in H; destructAll; auto.\n  erewrite mem_range_valid in H0.\n  apply Hglobal in H. destructAll.\n  exists x0. apply H0. auto.\nQed.\n\nCorollary correct_tinfo_after_store:\n  forall p z lenv m,\n    correct_tinfo p z lenv m ->\n    forall m' chunk b ofs v,\n      Mem.store chunk m b ofs v = Some m' ->\n    correct_tinfo p z lenv m'. \nProof. \n  intros. \n  eapply correct_tinfo_valid_access.\n  apply H.\n  eapply mem_range_valid. intros.\n  eapply Mem.store_valid_access_1 in H0; eauto. \nQed.    \n     \nCorollary valid_access_after_nstore:\n  forall  vs m m' i b' ofs',\n    forall chunk b ofs p, Mem.valid_access m chunk b ofs p ->\n                          mem_after_n_proj_store b' ofs' vs i m m' ->\n                         Mem.valid_access m' chunk b ofs p.\nProof.\n  induction vs; intros.\n  - inv H0.\n  - inv H0.\n    + eapply Mem.store_valid_access_1; eauto.\n    + eapply IHvs.   \n      2: apply H9.\n      eapply Mem.store_valid_access_1; eauto.\nQed.      \n      \n\nCorollary correct_tinfo_after_nstore:\n  forall p vs  z lenv m m' b ofs i,\n    correct_tinfo p z lenv m ->\n      mem_after_n_proj_store b ofs vs i m m' ->\n      correct_tinfo p z lenv m'. \nProof.\n  induction vs; intros.\n  - inv H0.\n  -   inv H0.\n      + eapply correct_tinfo_after_store; eauto. \n      + eapply IHvs. 2:{ apply H9. }\n        eapply correct_tinfo_after_store; eauto.\nQed.         \n\n\n\n        \nTheorem var_names_app:\n  forall l1 l2,\n    (var_names (l1 ++ l2)) = (var_names l1 ++ var_names l2).\nProof.\n  induction l1. reflexivity.\n  intros.\n  destruct a; simpl. rewrite IHl1. reflexivity.\nQed.\n\n \n  \n\n\n\nDefinition repr_expr_LambdaANF_Codegen_id := repr_expr_LambdaANF_Codegen argsIdent allocIdent limitIdent threadInfIdent tinfIdent\n     isptrIdent caseIdent nParam.\n\n\nDefinition rel_mem_LambdaANF_Codegen_id := rel_mem_LambdaANF_Codegen argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent\n   isptrIdent caseIdent nParam.\n \n\nDefinition repr_val_L_LambdaANF_Codegen_id := repr_val_L_LambdaANF_Codegen argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam. \n\nDefinition repr_val_id_L_LambdaANF_Codegen_id := repr_val_id_L_LambdaANF_Codegen\n    argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent isptrIdent\n     caseIdent nParam.\n \nDefinition protected_id_not_bound_id := protected_id_not_bound argsIdent allocIdent limitIdent gcIdent mainIdent bodyIdent threadInfIdent tinfIdent heapInfIdent numArgsIdent isptrIdent\n   caseIdent.\n\nDefinition protected_not_in_L_id := protected_not_in_L argsIdent allocIdent limitIdent tinfIdent.\n\nTheorem Z_non_neg_add:\n        forall n m p, \n        (n <= m -> 0 <= p -> n <= p + m)%Z.\nProof.   \n  intros.\n  etransitivity. eauto. omega.\nQed.\n  \n(* ident[n] contains either a Vint representing an enum or an integer OR a pointer to a function or the boxed representation of v *)\nInductive nth_arg_rel_LambdaANF_Codegen (fenv:fun_env) (finfo_env:fun_info_env) (p:program) (rep_env: M.t ctor_rep) : LambdaANF.eval.env -> positive -> temp_env -> mem -> Z -> Prop :=\n| is_in_and_rel:\n    forall lenv args_b args_ofs rho m n x LambdaANFv Codegenv L,\n       protected_not_in_L argsIdent allocIdent limitIdent tinfIdent p lenv  L -> \n      (* get the value rho(x)*)\n      M.get x rho = Some LambdaANFv -> \n      (* get Vargs pointer and load the value from it *)\n      M.get argsIdent lenv = Some (Vptr args_b args_ofs) ->\n      Mem.load int_chunk m args_b (Ptrofs.unsigned (Ptrofs.add args_ofs  (Ptrofs.mul\n                   (Ptrofs.repr (sizeof (M.empty composite) val))\n                   (Ptrofs.repr n)))) = Some Codegenv ->\n      (* relate both val *)\n      repr_val_L_LambdaANF_Codegen_id fenv finfo_env p rep_env LambdaANFv m L Codegenv ->\n          nth_arg_rel_LambdaANF_Codegen fenv finfo_env p rep_env rho x lenv m n.\n \n \nTheorem caseConsistent_findtag_In_cenv:\n  forall cenv t e l,\n    caseConsistent cenv l t ->\n    findtag l t = Some e ->\n    exists (a aty:BasicAst.name) (ty:ind_tag) (n:N) (i:N), M.get t cenv = Some (Build_ctor_ty_info a aty ty n i).\nProof.\n  destruct l; intros.\n  - inv H0.\n  - inv H. destruct info.\n    exists ctor_name, ctor_ind_name, ctor_ind_tag,ctor_arity,ctor_ordinal; auto.\nQed.\n \n\nInductive isPtr_sem: Events.extcall_sem :=\n| isPtr_true : forall genv m b ofs,\n    isPtr_sem genv ((Vptr b ofs)::nil) m nil (Vtrue) m\n| isPtr_false : forall genv m i, \n    isPtr_sem genv ((Vint i)::nil) m nil (Vfalse) m.\n  \n\nDefinition bind_n_after_ptr (n:Z) (x:block) (x0:Z) (L: block -> Z -> Prop): block -> Z -> Prop :=\n  fun b ofs =>\n                   match Pos.eqb b x with\n                   | true => (match Z.leb x0 ofs with\n                              | true => \n                                (match Z.ltb ofs (x0 + n)%Z with\n                                 | true => True\n                                 | false => L b ofs\n                                 end)\n                              | false => L b ofs\n                              end\n                             ) \n                   | false => L b ofs\n                   end.\n       \nTheorem bind_n_after_ptr_def:\n  forall n x x0 L b ofs,\n  bind_n_after_ptr n x x0 L b ofs\n  <->\n  (L b ofs \\/ (b = x /\\ x0 <= ofs < x0 + n))%Z.\nProof.\n  intros. unfold bind_n_after_ptr. \n  destruct (b =? x)%positive eqn:bxeq.\n  apply Peqb_true_eq in bxeq; subst.\n  destruct (x0 <=? ofs)%Z eqn:x0ofsle.\n  destruct (ofs <? x0 + n)%Z eqn:ofsx0lt.\n  split; auto.\n  intro. right; auto. split; auto.\n  split.\n  apply Zle_bool_imp_le in x0ofsle. auto.\n  apply Z.ltb_lt in ofsx0lt. auto.\n  split; auto. \n  intro. inv H; auto. destruct H0.\n  apply OrdersEx.Z_as_DT.ltb_nlt in ofsx0lt.\n  exfalso; omega.\n  split; auto. intros.\n  inv H; auto.\n  destruct H0.\n  apply Z.leb_nle in x0ofsle. exfalso; omega.\n  split; auto. intro.\n  inv H; auto.\n  destruct H0.\n  apply Pos.eqb_neq in bxeq. exfalso; auto.\nQed.\n\n\n \nInductive bind_n_after_ptr_rev: nat -> block -> Z ->  (block -> Z -> Prop) -> (block -> Z -> Prop) -> Prop :=\n| Bind_0_ind: forall b ofs L,  bind_n_after_ptr_rev 0 b ofs L L\n                                                    \n| Bind_S_ind : forall n b ofs L L',\n    bind_n_after_ptr_rev n b (ofs + int_size) L L' ->    \n    bind_n_after_ptr_rev (S n) b ofs L (fun b' z => L' b' z \\/ (b = b' /\\ ofs <= z < ofs + int_size)%Z).\n \n\n\n\n\n \nTheorem bind_n_after_ptr_exists':\nforall n b ofs L,\nexists L',\n  bind_n_after_ptr_rev n b ofs L L'.\nProof.\n  induction n; intros.\n  eexists. constructor.\n  specialize (IHn b (ofs+int_size)%Z L). inv IHn.\n  eexists.  constructor. eauto.\nQed.\n \n\nTheorem bind_n_after_ptr_from_rev:\nforall n b ofs L L', \n  bind_n_after_ptr_rev n b ofs L L' -> (forall b' z', (bind_n_after_ptr ((Z.of_nat n) * int_size) b ofs L) b' z' <-> L' b' z'). \nProof.\n  induction n; intros.\n  -  inv H. split.  intro. rewrite bind_n_after_ptr_def in H. inv H; auto. destruct H0.  simpl in H0.\n    exfalso.  omega.\n    rewrite bind_n_after_ptr_def. auto. \n  - inv H.\n    specialize (IHn _ _ _ _ H1).\n    split; intro.    \n    + rewrite bind_n_after_ptr_def in H.\n      inv H.\n      * left.\n        rewrite <- IHn.\n        rewrite bind_n_after_ptr_def. auto.\n      * (* either z is in the first portion OR it is in the rest of the binds *)\n        rewrite <- IHn.\n        rewrite bind_n_after_ptr_def.\n        destruct H0.\n        unfold int_size in *; simpl size_chunk in *.\n        rewrite Nat2Z.inj_succ in H0.\n        assert (0 <= Z.of_nat n)%Z by apply Zle_0_nat.        \n        assert (Hcase := Z.lt_ge_cases z' (ofs+int_size)%Z).\n        destruct Hcase.\n        right.  split; auto.  chunk_red; omega.\n        left. right. split; auto. chunk_red; omega.        \n    + inv H.\n      rewrite <- IHn in H0.\n      rewrite bind_n_after_ptr_def.\n      rewrite bind_n_after_ptr_def in H0.\n      rewrite Nat2Z.inj_succ.\n      rewrite Z.mul_succ_l. destruct H0. auto. right.\n      destruct H. split; auto. chunk_red; omega.\n      rewrite bind_n_after_ptr_def.\n      right.       unfold int_size in *; simpl size_chunk in *.\n      destruct H0. split. auto.\n      rewrite Nat2Z.inj_succ.\n      rewrite Z.mul_succ_l. chunk_red; omega.      \nQed.\n  \n\nTheorem bind_n_after_ptr_exists:\nforall n b ofs L,\nexists L',\n  bind_n_after_ptr_rev n b ofs L L' /\\ (forall b' z', (bind_n_after_ptr ((Z.of_nat n) * int_size) b ofs L) b' z' <-> L' b' z'). \nProof.\n  intros.\n  assert (H_L := bind_n_after_ptr_exists' n b ofs L).\n  destruct H_L.\n  exists x. split. auto.\n  eapply bind_n_after_ptr_from_rev. auto.\nQed.\n\n\nTheorem load_ptr_or_int:\n  forall y,\n    Vint_or_Vptr y = true ->\n    Val.load_result int_chunk y = y.\nProof.\n  intros. simpl. destruct y; inv H; auto.\nQed.\n\n\n \n \nTheorem mem_after_n_proj_rev_unchanged:\n  forall b  vs ofs m m',\n    mem_after_n_proj_store_rev b ofs vs m m' ->\n    forall L, \n  (forall j, ofs <= j < ofs+int_size*(Z.of_nat (length vs)) ->  ~ L b j)%Z -> \n  Mem.unchanged_on L m m'.\nProof.\n  induction vs; intros; inv H.\n  -  eapply Mem.store_unchanged_on. eauto.\n     simpl in H0.\n     simpl size_chunk. auto.\n  - eapply IHvs with (L := L) in H5.\n    + apply Mem.unchanged_on_trans with (m2 := m'0).\n      auto.\n      eapply Mem.store_unchanged_on; eauto.\n      intros. apply H0.\n      simpl length.\n      rewrite Nat2Z.inj_succ.\n      chunk_red;\n      omega.\n    + intros. apply H0.\n      simpl length.\n      rewrite Nat2Z.inj_succ.\n      chunk_red;\n      omega.\nQed.\n\n(* not true as state, m' are equivalent w.r.t. load, may not be equal. also \nneed a lemma that says you can commute store which don't affect each other                           \nTheorem mem_after_n_proj_eq_rev:\n  forall b vs ofs i m m',\n  mem_after_n_proj_store_rev b (ofs + (int_size * i)) vs m m' <->\n  mem_after_n_proj_store b ofs vs i m m'.\nProof.\n  induction vs.\n  - intros.\n    split; intro; inv H.\n  - intros.\n    split; intro; inv H.\n    + constructor. auto.\n    + rewrite <- Z.add_assoc in H4. rewrite <- Z.mul_succ_r in H4.\n      econstructor.\n      SearchAbout Mem.store. \n    + constructor. auto.\n    +    \n*)\nDefinition arg_val_LambdaANF_Codegen (fenv:fun_env) (finfo_env:fun_info_env) (p:program) (rep_env: M.t ctor_rep): LambdaANF.cps.val -> mem -> temp_env -> Prop :=\n  fun v m lenv =>\n    exists args_b args_ofs Codegenv L,\n(*       M.get tinfIdent lenv = Some (Vptr tinf_b tinf_ofs) /\\\n      deref_loc (Tarray uval maxArgs noattr) m tinf_b (Ptrofs.add tinf_ofs (Ptrofs.repr 12)) (Vptr args_b args_ofs) /\\ *)\n      M.get argsIdent lenv = Some (Vptr args_b args_ofs) /\\ \n                                  Mem.load int_chunk m args_b (Ptrofs.unsigned (Ptrofs.add args_ofs (Ptrofs.repr int_size))) = Some Codegenv /\\\n                                  repr_val_L_LambdaANF_Codegen_id fenv finfo_env p rep_env v m L Codegenv.\n\n\nDefinition same_args_ptr lenv lenv' :=\n  @M.get  Values.val argsIdent lenv = M.get argsIdent lenv'.\n\nDefinition same_tinf_ptr lenv lenv' :=\n  @M.get Values.val tinfIdent lenv =  M.get tinfIdent lenv'.\n\nDefinition mem_same_block (b:block) (m m':mem) : Prop :=\n  forall chunk ofs,\n    Mem.load chunk m b ofs = Mem.load chunk m' b ofs.\n\n\nTheorem max_allocs_case:\n  forall c e y cl, \n  List.In (c, e) cl ->\n  max_allocs e <= max_allocs (Ecase y cl).\nProof.\n  induction cl; intros.\n  inv H.\n  simpl. destruct a. inv H.\n  - inv H0.\n    apply Nat.le_max_l.\n  - apply IHcl in H0. simpl in H0.\n    etransitivity. apply H0.\n    apply Nat.le_max_r.\nQed.\n  \n  \nTheorem get_list_cons :\n  forall A rho v ys vs,\n    @get_list A ys rho = Some (v :: vs) ->\n  exists y ys', ys = y::ys' /\\\n                cps.M.get y rho = Some v /\\ \n                get_list ys' rho = Some vs. \nProof.\n  intros. destruct ys as [ | y ys'].\n  inv H. exists y, ys'.\n  split; auto.  simpl in H.\n  destruct  (cps.M.get y rho).\n  destruct (get_list ys' rho). inv H. auto.\n  inv H. inv H.\nQed.\n \n      \nTheorem exists_getvar_or_funvar_list:\n  forall lenv p rho L rep_env finfo_env argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam fenv\n         m xs vs,\n            ( forall x, List.In x xs ->\n                        exists v6 : cps.val,\n         M.get x rho = Some v6 /\\\n         repr_val_id_L_LambdaANF_Codegen argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam fenv finfo_env\n                             p rep_env v6 m L lenv x)\n            ->\n            get_list xs rho = Some vs  ->\n            exists vs7 : list Values.val, get_var_or_funvar_list p lenv xs = Some vs7.\nProof.  \n  induction xs; intros.\n  - exists nil. auto.\n  - simpl in H0.\n    destruct (cps.M.get a rho) eqn:Hgar.\n    destruct (get_list xs rho) eqn:Hgxsr.\n    inv H0.\n    specialize (IHxs l).\n    assert ((forall x : positive,\n          List.In x xs ->\n          exists v6 : cps.val,\n            M.get x rho = Some v6 /\\\n            repr_val_id_L_LambdaANF_Codegen argsIdent0 allocIdent0 limitIdent0 gcIdent0 threadInfIdent0 tinfIdent0 isptrIdent0 caseIdent0 nParam0\n                                fenv finfo_env p rep_env v6 m L lenv x)).\n    {\n      intros. apply H. constructor 2; auto.\n    }\n    apply IHxs in H0. destruct H0.\n    assert \n      (exists v6 : cps.val,\n        M.get a rho = Some v6 /\\\n        repr_val_id_L_LambdaANF_Codegen argsIdent0 allocIdent0 limitIdent0 gcIdent0 threadInfIdent0 tinfIdent0 isptrIdent0 caseIdent0 nParam0 fenv\n                            finfo_env p rep_env v6 m L lenv a).\n    apply H. constructor. reflexivity.\n    destruct H1. destruct H1.\n    rewrite H1 in Hgar. inv Hgar.\n    inv H2. eexists. simpl. rewrite H0. rewrite H3. reflexivity.\n    destruct Archi.ptr64 eqn:Harchi; eexists; simpl; rewrite H0; rewrite H3; rewrite H4; inv H5; archi_red; reflexivity. \n    reflexivity.\n    inv H0.\n    inv H0.\nQed.     \n\n \n  \nTheorem store_unchanged_on' :\n        forall m m'' m' L v b chunk ofs,\n          Mem.unchanged_on L m m'' ->\n          (forall i, ofs <= i < ofs + size_chunk chunk -> ~ L b i)%Z ->\n          Mem.store chunk m' b ofs v = Some m'' ->\n          Mem.unchanged_on L m m'.\nProof.\n  intros. inv H. constructor.\n  - apply Mem.nextblock_store in H1.\n    rewrite <- H1. auto.\n  - split; intros.\n    eapply Mem.perm_store_2.\n    apply H1. apply unchanged_on_perm; auto.\n    apply unchanged_on_perm; auto.\n    eapply Mem.perm_store_1; eauto.\n  - intros.\n    rewrite <- unchanged_on_contents; auto.        \n    symmetry.\n    erewrite Mem.store_mem_contents; eauto.\n    rewrite Maps.PMap.gsspec.\n    destruct (Coqlib.peq b0 b); auto. subst b0. apply Mem.setN_outside.\n  rewrite encode_val_length. rewrite <- size_chunk_conv.\n  destruct (Coqlib.zlt ofs0 ofs); auto.\n  destruct (Coqlib.zlt ofs0 (ofs + size_chunk chunk)); auto.\n  elim (H0 ofs0). chunk_red; omega. auto.\nQed.  \n \n\n    \n   \n\n\n    \n\nTheorem sem_shr_unboxed:\n  forall n,\n(*     sem_shr (Vint n) val (Vint (Int.repr 1)) val = Some (Vint (Int.repr (Z.shiftr (Int.unsigned n) 1))).*)\n\n    sem_shr (make_vint (Ptrofs.unsigned n)) val (make_vint 1) val = Some (make_vint (Z.shiftr (Ptrofs.unsigned n) 1)).\nProof.  \n  intros.\n  unfold sem_shr. unfold sem_shift. simpl.\n  assert (Hrange:= uint_range_unsigned n).\n  destruct Archi.ptr64 eqn:Harchi;\n    archi_red; unfold classify_shift; simpl.\n  {   (* unfold Int64.ltu. rewrite Coqlib.zlt_true. *)\n      rewrite Int64.shru_div_two_p.\n      rewrite Int64.Zshiftr_div_two_p by omega.\n      rewrite Int64.unsigned_repr by (archi_red; solve_uint_range; omega).\n      unfold Int64.iwordsize. unfold Int64.zwordsize. simpl.\n      unfold Int64.ltu.\n      rewrite Int64.unsigned_repr by (unfold Int64.max_unsigned; solve_uint_range; omega).\n      rewrite Int64.unsigned_repr by (unfold Int64.max_unsigned; solve_uint_range; omega).\n  unfold classify_shift. simpl. reflexivity.\n}\n{   \n  rewrite Int.shru_div_two_p.\n  rewrite Int.Zshiftr_div_two_p by omega.\n  rewrite Int.unsigned_repr by (archi_red; solve_uint_range; omega).\n  unfold Int.iwordsize. unfold Int.zwordsize. simpl.\n  unfold Int.ltu.\n  rewrite Int.unsigned_repr by (solve_uint_range; omega).\n  rewrite Int.unsigned_repr by (solve_uint_range; omega).\n  unfold classify_shift. simpl. reflexivity.\n}\nQed.\n\n\nTheorem sem_switch_and_255: forall h,\n     (0 <= h <= Ptrofs.max_unsigned)%Z -> \n  sem_switch_arg (int_and h 255) uval = Some (Z.land h 255).\nProof.\n  intros.\n  rewrite ptrofs_mu in H.\n  unfold sem_switch_arg. unfold int_and. \n  destruct Archi.ptr64 eqn:Harchi;\n    archi_red; unfold classify_shift; simpl.\n  { unfold Int64.and.\n    rewrite Int64.unsigned_repr with (z := h) by (archi_red; solve_uint_range; omega).\n    rewrite Int64.unsigned_repr with (z := 255%Z) by (archi_red; solve_uint_range; omega).\n    rewrite Int64.unsigned_repr. reflexivity.\n    replace 255%Z with (Z.ones 8) by reflexivity.\n    rewrite Z.land_ones. unfold Int64.max_unsigned in *; simpl in *.\n    assert ( (0 <= h mod Z.pow_pos 2 8 < Z.pow_pos 2 8)%Z).\n    apply Z.mod_bound_pos.  omega. compute. reflexivity.\n    destruct H0. split; auto.\n    eapply OrdersEx.Z_as_OT.lt_le_incl. \n    eapply OrdersEx.Z_as_DT.lt_le_trans.\n    eauto. compute. intro. inv H2.\n    omega.\n  }\n  { unfold Int.and.\n    rewrite Int.unsigned_repr with (z := h) by (archi_red; solve_uint_range; omega).\n    rewrite Int.unsigned_repr with (z := 255%Z) by (archi_red; solve_uint_range; omega).\n    rewrite Int.unsigned_repr. reflexivity.\n    replace 255%Z with (Z.ones 8) by reflexivity.\n    rewrite Z.land_ones. unfold Int.max_unsigned in *; simpl in *.\n    assert ( (0 <= h mod Z.pow_pos 2 8 < Z.pow_pos 2 8)%Z).\n    apply Z.mod_bound_pos.  omega. compute. reflexivity.\n    destruct H0. split; auto.\n    eapply OrdersEx.Z_as_OT.lt_le_incl. \n    eapply OrdersEx.Z_as_DT.lt_le_trans.\n    eauto. compute. intro. inv H2.\n    omega.\n  }\nQed.\n    \nTheorem sem_switch_arg_1: forall n,\n     (0 <= n <= Ptrofs.max_unsigned)%Z -> \n        sem_switch_arg (int_shru n 1) uval = Some (Z.shiftr n 1).\nProof.  \n  intros. rewrite ptrofs_mu in H.\n  unfold sem_switch_arg. unfold int_shru.\n   \n  destruct Archi.ptr64 eqn:Harchi;\n    archi_red; unfold classify_shift; simpl.\n  {   (* unfold Int64.ltu. rewrite Coqlib.zlt_true. *)\n    rewrite Int64.shru_div_two_p.\n    rewrite Int64.Zshiftr_div_two_p by omega.\n      rewrite Int64.unsigned_repr with (z := n) by (archi_red; solve_uint_range; omega).\n      rewrite Int64.unsigned_repr with (z := 1%Z) by (archi_red; solve_uint_range; omega).\n      rewrite Int64.unsigned_repr. reflexivity.\n      unfold Int64.max_unsigned; solve_uint_range.\n    unfold  Zpower.two_power_pos.  simpl.\n    inv H. split.\n    apply Z.div_pos; omega.\n    apply OrdersEx.Z_as_OT.div_le_upper_bound. omega. omega.\n}\n  {\n        rewrite Int.shru_div_two_p.\n    rewrite Int.Zshiftr_div_two_p by omega.\n      rewrite Int.unsigned_repr with (z := n) by (archi_red; solve_uint_range; omega).\n      rewrite Int.unsigned_repr with (z := 1%Z) by (archi_red; solve_uint_range; omega).\n      rewrite Int.unsigned_repr. reflexivity.\n      unfold Int.max_unsigned; solve_uint_range.\n    unfold  Zpower.two_power_pos.  simpl.\n    inv H. split.\n    apply Z.div_pos; omega.\n    apply OrdersEx.Z_as_OT.div_le_upper_bound. omega. omega.\n  }\nQed.\n\n\n(* Two constructors of the same inductive cannot have the same ordinal *)\nTheorem disjoint_ord:\n  forall {cenv ienv c c' namec namec' namei namei' i a a' ord ord'}, \n    correct_ienv_of_cenv cenv ienv ->        \n    M.get c cenv = Some (Build_ctor_ty_info namec namei i a ord) -> \n    M.get c' cenv = Some (Build_ctor_ty_info namec' namei' i a' ord') ->\n    (c <> c' <-> ord <> ord').\nProof.\n  intros.\n  apply H in H0. apply H in H1. destructAll.\n  rewrite H1 in H0. inv H0.\n  split; intro; intro; subst.\n  - (* c -> ord *)\n    apply H7. exists namec', c', a'.  split. intro. inv H8. apply H0; auto. auto.\n  - (* ord -> c *)\n    apply H6. exists ord', namec', a'. split. intro. inv H8. apply H0; auto. auto.\nQed.\n\n\n\nTheorem pos_iter_injective:\n  forall A f,\n         (forall a b, f a = f b -> a = b) ->\n         forall p (a b:A),\n  Pos.iter f a p = Pos.iter f b p ->\n  a = b.\nProof.\n  induction p; intros.\n  simpl in H0.\n  apply H in H0.\n  apply IHp in H0. apply IHp in H0. auto.\n  simpl in H0. apply IHp in H0. apply IHp; auto.\n  simpl in H0. apply H; auto.\nQed.  \n  \n  \nTheorem shiftl_injective:\n  forall c a b,\n    (0 <= c)%Z ->\n  Z.shiftl a c = Z.shiftl b c ->\n  a = b.\nProof.\n  induction c; intros.\n  simpl in *. auto.\n  simpl in H0.\n  apply pos_iter_injective in H0. auto.\n  intros. omega.\n  simpl in H0. exfalso.\n  assert (Z.neg p < 0)%Z by apply Pos2Z.neg_is_neg.\n  omega.\nQed.\n \nTheorem unzip_vars:\n  forall vs0 vars x, \n    Forall2 (fun (x0 : var) (xt : var * type) => xt = (x0, uval)) vs0 vars ->\n    List.In x (var_names vars) <->\n    List.In x vs0.\nProof.\n  induction vs0; intros.\n  inv H. split; intro H; inv H.\n  inv H. simpl.\n  apply IHvs0 with (x := x) in H4.\n  rewrite <- H4. reflexivity.\nQed.\n\n \n\nTheorem case_of_labeled_stm_unboxed:\n  forall rep_env arr t  n0 e p fenv finfo_env ienv cenv ,\n    correct_ienv_of_cenv cenv ienv ->\n    M.get t rep_env = Some (enum arr) ->\n    correct_crep_of_env cenv  rep_env ->\n    repr_unboxed_Codegen arr n0 ->\n    forall cl ls ls',\n      caseConsistent cenv cl t ->\n  findtag cl t = Some e ->\n  repr_branches_LambdaANF_Codegen argsIdent allocIdent limitIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam fenv finfo_env p rep_env cl ls ls' ->\n  exists s s', \n    seq_of_labeled_statement (select_switch (Z.shiftr n0 1) ls') = (Ssequence (Ssequence s Sbreak) s') /\\  repr_expr_LambdaANF_Codegen_id fenv finfo_env p rep_env e s.\nProof.\n  intros rep_env arr t  n0 e p fenv finfo_env ienv cenv Hienv H H0 H1.\n  induction cl;\n  intros ls ls' Hcc; intros.\n  (* impossible empty cl *)  inv H2.\n  simpl in H2. destruct a. destruct (M.elt_eq c t).\n  - (* is-case *)\n    inv H2. inv H3.\n    (* remove impossible boxed cases *)\n    3:{   rewrite H10 in H. inv H. }\n    3:{  rewrite H10 in H. inv H. }\n    + (* default *)\n      simpl. exists s, Sskip.\n      split. reflexivity.\n      auto.\n    + rewrite H10 in H. inv H.\n      exists s, (seq_of_labeled_statement ( (LScons lsa' lsb' lsc'))). split; auto.\n      simpl. unfold select_switch. simpl.\n      \n      assert (tag = n0).\n      inv H11; inv H1. auto.\n      subst.\n      rewrite Coqlib.zeq_true.\n      simpl. reflexivity.\n  - (*is not case -- IH *)\n    inv H3.\n    + (* impossible because rep_env is correct, t is in cl but cl -unboxed-> LSnil *)\n      exfalso.\n      assert (Hn_repr := repr_branches_LSnil_no_unboxed _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H2 H11). apply Hn_repr.\n      eauto.\n     + simpl. (* c <> t so arr <> n1 and the headers are different *)\n       unfold select_switch.\n       simpl select_switch_case. \n       rewrite Coqlib.zeq_false.\n       inv Hcc. \n       specialize (IHcl _ _ H14 H2 H7). apply IHcl.\n       inv H0. apply H4 in H11.\n       apply H4 in H. inv H. inv H11. \n       assert (it = it0). {\n         inv Hcc.  rewrite H5 in H13; rewrite H0 in H14; inv H13; inv H14. auto.\n       }\n       subst.\n       assert (n1 <> arr). {\n         assert (Hdj := disjoint_ord Hienv H0 H5).\n         apply Hdj. auto.\n       }      \n       inv Hcc. rewrite H5 in H14; inv H14. rewrite H0 in H15; inv H15.\n       intro. do 2 (erewrite repr_unboxed_shiftr in H6 by eauto). \n       apply H. apply N2Z.inj. apply H6.\n     + inv Hcc; eapply IHcl; eauto.       \n     + inv Hcc; eapply IHcl; eauto.\nQed.\n   \n(* \nDefinition z_and z1 z2 :=\n  if Archi.ptr64 then (Int64.unsigned (Int64.and (Int.repr z1) (Int64.repr z2))) else\n    (Int.unsigned (Int.and (Int.repr z1) (Int.repr z2))). *)\n  \nTheorem case_of_labeled_stm_boxed:\n  forall rep_env n arr t  h e p fenv finfo_env ienv cenv ,\n    correct_ienv_of_cenv cenv ienv ->\n     M.get t rep_env = Some (boxed n arr)  ->\n    correct_crep_of_env cenv rep_env ->\n    boxed_header n arr  h ->\n    forall cl ls ls',\n      caseConsistent cenv cl t ->\n  findtag cl t = Some e ->\n  repr_branches_LambdaANF_Codegen argsIdent allocIdent limitIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam fenv finfo_env p rep_env cl ls ls' ->\n  exists s s', \n                       (seq_of_labeled_statement (select_switch (Z.land  h 255) ls)) = (Ssequence (Ssequence s Sbreak) s') /\\  repr_expr_LambdaANF_Codegen_id fenv finfo_env p rep_env e s.\nProof. \n  intros rep_env n arr t  h e p fenv finfo_env ienv cenv  Hienv H H0 H1.\n  induction cl; intros ls ls' Hcc; intros.\n  (* impossible empty cl *) inv H2.\n  simpl in H2. destruct a. destruct (M.elt_eq c t).\n  - (* is case *)\n    inv H2. inv H3. rewrite H9 in H; inv H.\n    rewrite H10 in H; inv H.\n    + (* default *)\n      simpl. exists s, Sskip.\n      split; auto.\n    + rewrite H10 in H. inv H.\n      assert (tag = h). {\n        inv H1; inv H11. auto.\n      }\n      rewrite <- H in *. clear H. clear H11.\n      unfold select_switch. simpl. \n      rewrite Coqlib.zeq_true. simpl. \n      do 2 eexists.\n      split. reflexivity. auto.\n  - (* is-not-case -- IH *)    \n    inv H3.\n    + (* enum default *)\n      inv Hcc; eapply IHcl; eauto.       \n    + inv Hcc; eapply IHcl; eauto.            \n    + exfalso.\n      eapply repr_branches_LSnil_no_boxed; eauto.\n    + (* c <> t so arr <> n1 and the header are different *)\n      unfold select_switch.\n      simpl select_switch_case. \n      rewrite Coqlib.zeq_false.\n      inv Hcc. \n      specialize (IHcl _ _ H14 H2 H7). apply IHcl.\n      do 2 (erewrite  repr_boxed_t; eauto).\n\n\n      inv H0. apply H4 in H11.\n      apply H4 in H. inv H. inv H11.          \n      inv Hcc.\n \n      rewrite H6 in H11. inv H11. rewrite H5 in H16. inv H16.\n      simpl in H18. inv H18.\n      \n      assert (Hdj := disjoint_ord Hienv H5 H6).\n      apply Hdj in n0. intro. apply n0.\n      apply N2Z.inj. auto.\nQed.\n\n(* CHANGE HERE *)\n\nLemma skipn_suc1  {A} n (x : A) (l1 l2 : list A) : skipn n l1 = x :: l2 -> skipn (S n) l1 = l2.\nProof.\n  generalize n l2. induction l1; destruct n0; intros.\n  - simpl in H. rewrite H; reflexivity.\n  - inv H.\n  - inv H. reflexivity.\n  - apply (IHl1 n0 l0 H).\nQed.\n \nLemma skipn_suc2 {A} n (x y : A) (l1 l2 : list A) : skipn n (x :: l1) = y :: l2 -> skipn n l1 = l2.\nProof.\n  generalize x y n l2. induction l1; destruct n0; intros; inv H; try reflexivity.\n  - destruct n0; inv H1.\n  - apply (IHl1 _ _ _ _ H1).\nQed.  \n\nLemma skipn_cons {A} n (x y : A) (l1 l2 : list A) : skipn n (x :: l1) = (y :: l2) -> skipn n l1 = l2.\nProof.\n  induction l2 , l1; intros.\n  - destruct n; reflexivity. \n  - destruct n; inv H.\n    destruct n; intros.\n    + inv H1. reflexivity.\n    + inv H1. apply (skipn_suc1 n y l1 []). assumption.\n  - apply (skipn_suc1 n y [x] (a :: l2)). assumption.\n  - apply (skipn_suc2 _ x y). assumption.\nQed.   \n\nLemma skipn_cons_nil {A} n (x : A) (l : list A) : skipn n (x :: l) = [] -> skipn n l = [].\nProof.\n  generalize n x. induction l; intros.\n  - destruct n0; reflexivity. \n  - destruct n0.\n    + inv H.\n    + simpl in H. simpl.  apply (IHl n0 a). assumption.\nQed.\n\n(* place values lenv(ys) into the inf slots of the args array\n   something about allocPtr *)\nDefinition mem_of_asgn argsIdent p lenv (ys:list positive) (inf:list N) m :=\n  exists args_b args_ofs, M.get argsIdent lenv = Some (Vptr args_b args_ofs)  /\\ Forall2 (fun y i => exists v, Mem.loadv int_chunk m (Vptr args_b (Ptrofs.add args_ofs (Ptrofs.repr (int_size * (Z.of_N i))))) = Some v /\\ get_var_or_funvar p lenv y v) ys inf.\n\n(* same as above but with val list explicit *)\nInductive mem_of_asgn_v args_b args_ofs p lenv m: list positive -> list N -> list Values.val -> Prop :=\n| moa_cons: forall y i v ys inf vs, \n    mem_of_asgn_v args_b args_ofs p lenv m ys inf vs ->\n    Mem.loadv int_chunk m (Vptr args_b (Ptrofs.add args_ofs (Ptrofs.repr (int_size * (Z.of_N i))))) = Some v ->\n    get_var_or_funvar p lenv y v ->\n     mem_of_asgn_v args_b args_ofs p lenv m (y::ys) (i::inf) (v::vs)\n| moa_nil:\n    mem_of_asgn_v args_b args_ofs p lenv m [] [] [].\n \n(* same as above, but without lenv and ys \n   i.e. disregarding provenance *)\nInductive mem_after_asgn args_b args_ofs  m: list N -> list Values.val -> Prop :=\n  | maa_cons: forall  i v  inf vs, \n    mem_after_asgn args_b args_ofs  m inf vs ->\n    Mem.loadv int_chunk m (Vptr args_b (Ptrofs.add args_ofs (Ptrofs.repr (int_size * (Z.of_N i))))) = Some v ->\n     mem_after_asgn args_b args_ofs  m (i::inf) (v::vs)\n| maa_nil:\n    mem_after_asgn args_b args_ofs  m [] [].\n\n\n\nTheorem mem_of_asgn_nthN:\n  forall {args_b args_ofs p lenv m ys inf vs y v n},\n  mem_of_asgn_v args_b args_ofs p lenv m ys inf vs  ->\n  nthN ys n = Some y ->\n  nthN vs n = Some v ->\n  get_var_or_funvar p lenv y v.\nProof.\n  induction ys; intros.\n  inv H0.\n  destruct vs. inv H1.\n  inv H.\n  destruct n. inv H0; inv H1; auto.  \n  apply nthN_pos_pred in H0.\n  apply nthN_pos_pred in H1.\n  eapply IHys; eauto.\nQed.\n\nTheorem mem_of_asgn_after:\n  forall args_b args_ofs p m lenv inf ys vs,\n  mem_of_asgn_v args_b args_ofs p lenv m ys inf vs ->\n  mem_after_asgn args_b args_ofs m inf vs.\nProof.\n  induction inf; intros.\n  - inv H; constructor.\n  - inv H; constructor; eauto.\nQed.\n\nTheorem mem_after_asgn_length:\n  forall args_b args_ofs m  inf vs,\n  mem_after_asgn args_b args_ofs m inf vs ->\n  length inf = length vs. \nProof.\n  induction inf; intros.\n  inv H; auto.\n  inv H. simpl. erewrite IHinf; eauto.\nQed.\n\nTheorem mem_of_asgn_exists_v:\n  forall {argsIdent p lenv m args_b args_ofs ys inf},\n  mem_of_asgn argsIdent p lenv ys inf m ->\n  M.get argsIdent lenv = Some (Vptr args_b args_ofs) ->\n  exists vs,\n    mem_of_asgn_v args_b args_ofs p lenv m ys inf vs.\nProof.\n  intros. inv H. destruct H1. destruct H.\n  rewrite H in H0. inv H0. \n  clear H. revert dependent inf. induction ys; intros.\n  -  inv H1.\n     exists []. constructor.\n  - inv H1. specialize (IHys _ H4).\n    inv IHys. inv H2.\n    exists (x0::x). destruct H0. constructor; eauto.\nQed.\n\n\nTheorem mem_of_asgn_forall_v:\n  forall {argsIdent p lenv m args_b args_ofs ys inf vs},\n  mem_of_asgn_v args_b args_ofs p lenv m ys inf vs ->\n  M.get argsIdent lenv = Some (Vptr args_b args_ofs) ->\n  mem_of_asgn argsIdent p lenv ys inf m.\nProof.\n  induction ys; intros.\n  - inv H. eexists. eexists. split; eauto.\n  - inv H. specialize (IHys _ _ H3 H0).\n    exists args_b, args_ofs. split; auto. constructor.\n    exists v; eauto.\n    inv IHys. destructAll. rewrite H in H0. inv H0.\n    auto.\nQed.\n \n    \nTheorem mem_of_asgn_v_length:\n  forall {p lenv m args_b args_ofs ys inf vs},\n    mem_of_asgn_v args_b args_ofs p lenv m ys inf vs ->\n    length inf = length vs.\nProof.\n  induction ys; intros; inv H.\n  reflexivity.\n  simpl. erewrite IHys. reflexivity.\n  eauto.\nQed.\n\nTheorem mem_of_asgn_v_length13:\n  forall {p lenv m args_b args_ofs ys inf vs},\n    mem_of_asgn_v args_b args_ofs p lenv m ys inf vs ->\n    length ys = length vs.\nProof.\n  induction ys; intros; inv H.\n  reflexivity.\n  simpl. erewrite IHys. reflexivity.\n  eauto.\nQed.\n\n\n\n\nTheorem mem_of_asgn_v_disjoint:\n  forall a v lenv args_b args_ofs p ys vs inf m,\n    ~ List.In a ys ->\n    mem_of_asgn_v args_b args_ofs p lenv m ys inf vs ->\n    mem_of_asgn_v args_b args_ofs p (Maps.PTree.set a v lenv) m ys inf vs.\nProof.\n  induction ys; intros.\n  - inv H0. constructor.\n  - inv H0. constructor. apply IHys. intro; apply H. constructor 2; auto.\n    auto. auto. inv H7.\n    + constructor. auto.\n    + constructor 2; auto.\n      rewrite M.gso. auto. intro; apply H. subst.\n      constructor. auto.\nQed.\n\nTheorem mem_of_asgn_v_store:\n  forall args_b args_ofs p v chunk b ofs lenv m m' ys inf vs,\n  mem_of_asgn_v args_b args_ofs p lenv m ys inf vs ->\n  Mem.store chunk m b ofs v  = Some m' ->\n  b <> args_b ->\n  mem_of_asgn_v args_b args_ofs p lenv m' ys inf vs.\nProof.  \n  induction ys; intros.\n  - inv H.\n    constructor.\n  - inv H.\n    constructor; auto.\n    unfold Mem.loadv in *.\n    erewrite Mem.load_store_other; eauto.\nQed.    \n\nLtac solve_ptrofs_range:=\n  solve_uint_range; uint_range_ptrofs; chunk_red; archi_red; unfold Int64.max_unsigned; unfold Int.max_unsigned; simpl; try omega.  \n\n(* w/o destructing ptr64 *)\nLtac solve_ptrofs_range':=\n  solve_uint_range; uint_range_ptrofs; archi_red; unfold Int64.max_unsigned; unfold Int.max_unsigned; simpl; try omega.  \n\n\nDefinition mem_of_asgn_cons:\n  forall p y lenv ys inf m i max_alloc m' v args_ofs args_b,\n  mem_of_asgn argsIdent p lenv ys inf m ->\n  NoDup (i::inf) ->\n  Forall (fun i => 0 <= (Z.of_N i) < max_args)%Z (i::inf) ->\n  (0 <= Ptrofs.unsigned args_ofs + int_size * max_args  <= Ptrofs.max_unsigned )%Z ->\n  correct_tinfo p max_alloc lenv m ->\n  M.get argsIdent lenv = Some (Vptr args_b args_ofs) ->\n\n  get_var_or_funvar p lenv y v ->\n  \n  \n  Mem.storev int_chunk m (Vptr args_b (Ptrofs.add args_ofs (Ptrofs.repr (int_size * (Z.of_N i))))) v = Some m' ->\n  mem_of_asgn argsIdent p lenv (y::ys) (i::inf) m'.\nProof.\n   intros. \n  destruct H3 as [alloc_b [alloc_ofs [limit_ofs [args_b' [args_ofs' [tinf_b [tinf_ofs [Hget_alloc [Halign_alloc [Hrange_alloc [Hget_limit [Hbound_limit [Hget_args [Hdj_args [Hbound_args [Hrange_args [Htinf1 Htinf2]]]]]]]]]]]]]]]]].\n  rewrite Hget_args in H4. inv H4.\n  destruct H as [args_b' [args_ofs' [H3]]]. rewrite H3 in Hget_args.  inv Hget_args. \n  exists args_b, args_ofs.\n  split; auto.\n  constructor.\n  - exists v. split; auto.\n    simpl in *. erewrite Mem.load_store_same; eauto.\n    simpl.  destruct v; inv H5; inv H8; auto. \n  - eapply Forall2_monotonic_strong; eauto.\n    intros. cbv beta in *.\n    destruct H8. exists x.\n    destruct H8. split; auto.\n    unfold Mem.loadv in *. \n    erewrite Mem.load_store_other; eauto.\n    right.  inv H0.\n    assert (i <> x2).\n    intro. apply H12. subst; auto.\n    inv H1.\n    eapply Forall_forall in H15; eauto.\n    assert ( uint_range_l [int_size; Z.of_N i] ) by  (unfold max_args in *; solve_ptrofs_range).\n    assert ( uint_range_l [int_size; Z.of_N x2] ) by (unfold int_size in *; unfold max_args in *; solve_ptrofs_range).\n    assert (Hix2 := N.le_gt_cases x2 i).\n    inv Hix2. \n    + left.\n      assert (x2 < i)%N.\n      apply N.le_neq. split; auto.\n      clear H11.\n      rewrite Ptrofs.add_unsigned.\n      rewrite Ptrofs.add_unsigned.\n      repeat (rewrite Ptrofs.unsigned_repr_eq).\n      rewrite Zdiv.Zplus_mod_idemp_r.\n      rewrite Zdiv.Zplus_mod_idemp_r.\n\n      destruct H2.  apply Z.lt_le_pred in H11.   \n      rewrite Z.mod_small.\n      rewrite Z.mod_small.\n      assert (Z.of_N x2 + 1 <=  Z.of_N i)%Z.\n      apply Zlt_le_succ.        apply N2Z.inj_lt. auto.\n      rewrite <- Z.add_assoc. \n      replace (Z.add (Z.mul int_size (Z.of_N x2)) (size_chunk int_chunk)) with (int_size * (Z.of_N x2 + 1))%Z by (chunk_red; omega).\n\n\n      chunk_red; uomega. \n      split. apply OrdersEx.Z_as_OT.add_nonneg_nonneg. apply Ptrofs.unsigned_range. chunk_red; uomega.\n      eapply OrdersEx.Z_as_OT.le_lt_trans; eauto. chunk_red; uomega.\n      split. apply OrdersEx.Z_as_OT.add_nonneg_nonneg. apply Ptrofs.unsigned_range. chunk_red; uomega.\n      eapply OrdersEx.Z_as_OT.le_lt_trans; eauto. chunk_red; uomega.\n    + right.\n      rewrite Ptrofs.add_unsigned.\n       rewrite Ptrofs.add_unsigned.\n       repeat (rewrite Ptrofs.unsigned_repr_eq).\n       rewrite Zdiv.Zplus_mod_idemp_r.\n       rewrite Zdiv.Zplus_mod_idemp_r.\n\n       destruct H2.\n       unfold Ptrofs.max_unsigned in *. apply Z.lt_le_pred in H16.   \n       rewrite Z.mod_small.\n       rewrite Z.mod_small.\n       assert (Z.of_N i + 1 <=  Z.of_N x2)%Z.\n       apply Zlt_le_succ.        apply N2Z.inj_lt. auto.\n       replace (int_size*Z.of_N i + int_size)%Z with (int_size * (Z.of_N i + 1))%Z  by (chunk_red; uomega).\n       chunk_red; uomega.\n       split. apply OrdersEx.Z_as_OT.add_nonneg_nonneg. apply Ptrofs.unsigned_range. chunk_red; uomega.\n       eapply OrdersEx.Z_as_OT.le_lt_trans; eauto. chunk_red; uomega.\n       split. apply OrdersEx.Z_as_OT.add_nonneg_nonneg. apply Ptrofs.unsigned_range. chunk_red; uomega.\n       eapply OrdersEx.Z_as_OT.le_lt_trans; eauto. chunk_red; uomega.\nQed.\n\n(* What is needed at function entry to unmarshal the parameters *)\nTheorem repr_asgn_fun_entry: \n  forall args_b args_ofs argsIdent F p m k xs locs vs7 asgn lenv lenv',\n    M.get argsIdent lenv = Some (Vptr args_b args_ofs) ->\n    mem_after_asgn args_b args_ofs m (skipn nParam locs) (skipn nParam vs7) ->\n    right_param_asgn argsIdent (skipn nParam xs) (skipn nParam locs) asgn ->\n    lenv_param_asgn_i lenv lenv' (skipn nParam xs) (skipn nParam vs7) ->\n    NoDup xs ->\n    ~ List.In argsIdent xs ->\n    Forall (fun i : N => (0 <= Z.of_N i < max_args)%Z) locs -> \n    clos_refl_trans state (traceless_step2 (globalenv p))\n               (State F asgn k empty_env lenv m)\n               (State F Sskip k empty_env lenv' m).\nProof. Admitted. (*\n  induction xs; intros.\n  - (* base case *)\n    inv H1; inv H2; inv H0.\n    apply rt_refl.\n  - (* Inductive case *)\n    inv H1; inv H2; inv H3; inv H0.\n    inv H5.\n\n    eapply rt_trans. constructor. constructor.\n    (* BRANCH ptr64*)\n    chunk_red;  archi_red.\n    {\n    eapply rt_trans. constructor. constructor. econstructor. constructor. econstructor. constructor. eauto.\n    constructor. constructor.\n    ptrofs_of_int. int_unsigned_repr.\n    rewrite int_z_mul. econstructor. reflexivity. eauto.\n    unfold max_args in *.  solve_ptrofs_range'. unfold max_args in *.  solve_uint_range. omega. \n    eapply rt_trans. constructor. constructor.\n    eapply IHxs; eauto.  rewrite M.gso. auto. intro; apply H4; constructor; auto.\n    intro. apply H4. constructor 2; auto.    }\n    {\n    eapply rt_trans. constructor. constructor. econstructor. constructor. econstructor. constructor. eauto.\n    constructor. constructor.\n    ptrofs_of_int. rewrite Int.unsigned_repr.\n    rewrite int_z_mul. econstructor. reflexivity. eauto.\n    unfold max_args in *.  solve_ptrofs_range'. unfold max_args in *.  solve_uint_range. omega. \n    eapply rt_trans. constructor. constructor.\n\n    eapply IHxs; eauto.  rewrite M.gso. auto. intro; apply H4; constructor; auto.\n    intro. apply H4. constructor 2; auto. }\nQed. *)\n\n(* CHANGE THIS *)    \n(* after stepping through a repr_asgn_fun', argsIdent[i] contain valuees y_i *)\n(* rest of m is the same *)\n(* maybe also have that L stays the same between the two *)\n(* also wants NoDup on i *)\nTheorem repr_asgn_fun_mem:\n  forall fu lenv p rho e fenv max_alloc rep_env finfo_env,\n  forall ys inf s m,\n    find_symbol_domain p finfo_env ->\n    finfo_env_correct fenv finfo_env ->\n rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env e rho m lenv ->\n correct_tinfo p max_alloc lenv m ->\n Forall (fun x => exists v, get_var_or_funvar p lenv x v) ys ->\n Forall (fun i => 0 <= (Z.of_N i) < max_args)%Z inf ->\n NoDup inf ->\n repr_asgn_fun' argsIdent threadInfIdent nParam fenv finfo_env p ys inf s ->\n exists m', \n  (forall k, clos_refl_trans state (traceless_step2 (globalenv p))\n    (State fu s k empty_env lenv m)\n    (State fu Sskip k empty_env lenv m')) /\\ mem_of_asgn argsIdent p lenv ys inf m' /\\rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env e  rho m' lenv /\\ correct_tinfo p max_alloc lenv m'.\nProof. \n  intros fu lenv p rho e fenv max_alloc rep_env finfo_env.\n  induction ys; intros inf s m Hsym HfinfoCorrect Hrel_mem Htinfo Hfys Hfinf Hnodub Hasgn; inv Hasgn. \n  - (* ys = [] inf = [] *)\n    assert (Htinfo' := Htinfo).\n    destruct Htinfo as [alloc_b [alloc_ofs [limit_ofs [args_b [args_ofs [tinf_b [tinf_ofs [Hget_alloc [Halign_alloc [Hrange_alloc [Hget_limit [Hbound_limit [Hget_args [Hdj_args [Hbound_args [Hrange_args [Htinf1 Htinf2]]]]]]]]]]]]]]]]].\n    (* cam have empty asgn now *)\n    exists m.\n    repeat split; try assumption.\n    + intros. constructor 2.\n    + econstructor. eauto.\n\n  -  (* ys = a::ys0 inf = i::inf0 *)\n    (* repeat of the init case *)\n    assert (Hfinf' := Hfinf).\n    inv Hfys; inv Hfinf. destruct H1.\n    assert (Hnodub' := Hnodub). inv Hnodub. \n    specialize (IHys inf0 s0 m Hsym HfinfoCorrect Hrel_mem Htinfo H2 H5 H7 H3).\n    destruct IHys as [m' [Hclo_m' [Hmem_m' [Hrel_m' Htinfo_m']]]].\n    assert (Htinfo_m'c := Htinfo_m').\n    destruct Htinfo_m' as [alloc_b [alloc_ofs [limit_ofs [args_b [args_ofs [tinf_b [tinf_ofs [Hget_alloc [Halign_alloc [Hrange_alloc [Hget_limit [Hbound_limit [Hget_args [Hdj_args [Hbound_args [Hrange_args [Htinf1 Htinf2]]]]]]]]]]]]]]]]].\n    assert (Hm'_valid : Mem.valid_access m' int_chunk args_b (Ptrofs.unsigned\n                                                               (Ptrofs.add args_ofs\n                                                                        (Ptrofs.mul (Ptrofs.repr int_size) (Ptrofs.repr (Z.of_N i))))) Writable). \n    apply Hrange_args. auto.\n    assert (Hm' := Mem.valid_access_store _ _ _ _ x Hm'_valid).\n    destruct Hm' as [m2 Hm2].\n    exists m2.\n\n    (* apply mem_of_asgn_cons *)\n    assert (Hm2' := Hm2).\n    rewrite int_z_mul in Hm2'.\n    \n    assert (Hargs_bound :   (0 <= Ptrofs.unsigned args_ofs + int_size * max_args <= Ptrofs.max_unsigned)%Z). split.\n    apply OrdersEx.Z_as_OT.add_nonneg_nonneg. apply Ptrofs.unsigned_range. chunk_red; uomega.    \n    auto.  \n    assert (Hmem_of_asgn := mem_of_asgn_cons _ _ _ _ _ _ _ _ _ _ _ _ Hmem_m' Hnodub' Hfinf' Hargs_bound Htinfo_m'c Hget_args H Hm2').\n\n    split.\n    \n    (* step though cons and then asgn *)\n      intro.\n      eapply rt_trans.\n      constructor. constructor.\n      eapply rt_trans.\n      apply Hclo_m'.\n      (* branch ptr64 *)\n      chunk_red; archi_red.\n      {\n        eapply rt_trans. constructor. constructor.\n        constructor. econstructor. constructor. econstructor. constructor. eauto.\n        constructor. simpl. constructor.\n        eapply get_var_or_funvar_eval; eauto.\n        eapply get_var_or_funvar_semcast; eauto.\n        simpl. eapply assign_loc_value. constructor. auto.\n        ptrofs_of_int. int_unsigned_repr. auto.\n        unfold max_args in *.  solve_uint_range. omega. \n      }\n      {\n        eapply rt_trans. constructor. constructor.\n        constructor. econstructor. constructor. econstructor. constructor. eauto.\n        constructor. simpl. constructor.\n        eapply get_var_or_funvar_eval; eauto.\n        \n        eapply get_var_or_funvar_semcast in H; archi_red; eauto. \n        simpl. eapply assign_loc_value. constructor. \n        ptrofs_of_int. int_unsigned_repr. auto.\n        unfold max_args in *.  solve_uint_range. omega. \n      }\n    \n    split; auto. \n    split.\n    eapply rel_mem_update_protected with (m := m'); eauto. \n\n\n    eapply correct_tinfo_valid_access; eauto.\n    eapply mem_range_valid. intros. \n    eapply Mem.store_valid_access_1; eauto.\n    unfold max_args in *; solve_ptrofs_range.\nQed.\n\n \n\n\nDefinition program_isPtr_inv (p:program) :=\n  exists b_isPtr name sg, Genv.find_symbol (globalenv p) isptrIdent = Some b_isPtr /\\\n                          Genv.find_funct (globalenv p) (Vptr  b_isPtr Ptrofs.zero) = Some (External (EF_external name sg) (Tcons val Tnil)  (Tint IBool Unsigned noattr)   {| cc_vararg := false; cc_unproto := false; cc_structret := false |}) /\\\n                                  (forall m n, Events.external_functions_sem name sg (Genv.globalenv p) [make_vint n] m [] Vfalse m) /\\\n                                  (forall m b i, Events.external_functions_sem name sg (Genv.globalenv p) [Vptr b i] m [] Vtrue m).\n\n\n (*  deprecated version\nthe lenv should actually be post asgn \n\n e_lenv_param_asgn_i  vsm4 lenv_new' vs7 Hl_temp Hnd_vs0\nwhere lenv_new' = (M.set limitIdent (Vptr alloc_b limit_ofs) (M.set allocIdent (Vptr alloc_b alloc_ofs) lenv_new))\nDefinition program_gc_inv (p:program) :=\n  exists b_gcPtr name sg, Genv.find_symbol (globalenv p) gcIdent = Some b_gcPtr /\\\n                          Genv.find_funct (globalenv p) (Vptr  b_gcPtr Int.zero) = Some (External (EF_external name sg) (Tcons (Tpointer (Tint I32 Unsigned noattr) noattr) (Tcons (Tpointer (Tstruct threadInfIdent noattr) noattr) Tnil)) Tvoid\n                            {|\n                              cc_vararg := false;\n                              cc_unproto := false;\n                              cc_structret := false |}) /\\\n                          forall lenv m rho rep_env finfo_env finfo_b finfo_maxalloc fenv e tinf_b tinf_ofs args_b args_ofs,\n                            rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env e rho m lenv ->\n                            M.get tinfIdent lenv = Some (Vptr tinf_b tinf_ofs) ->\n                            Mem.loadv int_chunk m (Vptr finfo_b Int.zero) = Some (Vint finfo_maxalloc) ->\n                            deref_loc valPtr m tinf_b (Int.add tinf_ofs (Int.repr (3*int_size))) (Vptr args_b args_ofs) -> \n                          exists v m' alloc_b alloc_ofs limit_ofs,\n                            (Events.external_functions_sem name sg (Genv.globalenv p) [Vptr finfo_b Int.zero; Vptr tinf_b tinf_ofs] m [] v m') /\\\n                            (* get new alloc *)                            \n                            deref_loc valPtr m' tinf_b tinf_ofs (Vptr alloc_b alloc_ofs) /\\\n                             (* get new limit *)\n                            deref_loc valPtr m' tinf_b (Int.add tinf_ofs (Int.repr int_size)) (Vptr alloc_b limit_ofs)  /\\\n                            (* same args block and offset *)\n                            deref_loc valPtr m' tinf_b (Int.add tinf_ofs (Int.repr (3*int_size))) (Vptr args_b args_ofs)  /\\\n                            (* same thing in the args block *)\n                             mem_same_block args_b m m' /\\\n                             (forall lenv' : temp_env,\n                                 forall vsm4 vs7 vars, \n   lenv_param_asgn\n     (M.set argsIdent (Vptr args_b args_ofs)\n        (M.set limitIdent (Vptr alloc_b limit_ofs)\n           (M.set allocIdent (Vptr alloc_b alloc_ofs)\n                 (Maps.PTree.set tinfIdent (Vptr tinf_b tinf_ofs)\n                    (create_undef_temps\n                       vars)))))\n     lenv' vsm4 vs7 ->\n   rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env e rho m' lenv' /\\\n   correct_tinfo p (Int.unsigned finfo_maxalloc) lenv' m'). *)\n                                          \n(* deep version of mem_after_asgn  *)\n Inductive rel_mem_asgn {fenv finfo_env p rep_env} args_b args_ofs m L: list LambdaANF.cps.val -> list N -> list Values.val -> Prop :=\n  | rma_cons: forall  i v6 v7  vs6 inf vs7, \n    rel_mem_asgn args_b args_ofs  m L vs6 inf vs7 ->\n    Mem.loadv int_chunk m (Vptr args_b (Ptrofs.add args_ofs (Ptrofs.repr (int_size * (Z.of_N i))))) = Some v7 ->\n    repr_val_L_LambdaANF_Codegen_id fenv finfo_env p rep_env v6 m L v7 ->\n     rel_mem_asgn args_b args_ofs  m L (v6::vs6) (i::inf) (v7::vs7)\n| rma_nil:\n    rel_mem_asgn args_b args_ofs  m L [] [] []. \n \n Theorem rel_mem_asgn_length:\n   forall {fenv finfo_env p rep_env m L args_b args_ofs ys inf vs},\n     @rel_mem_asgn fenv finfo_env p rep_env args_b args_ofs m L ys inf vs ->\n    length ys = length vs.\n Proof.\n   induction ys; intros.\n   inv H; auto.\n   inv H. simpl. erewrite IHys. reflexivity.\n   eauto.\n Qed.\n\n \n Theorem rel_mem_asgn_nthN:\n  forall {L rep_env finfo_env fenv args_b args_ofs p  m vs6 inf vs7 v6 v7 n},\n  @rel_mem_asgn fenv finfo_env p rep_env args_b args_ofs  m L vs6 inf vs7 -> \n  nthN vs6 n = Some v6 ->\n  nthN vs7 n = Some v7 ->\n  repr_val_L_LambdaANF_Codegen_id fenv finfo_env p rep_env v6 m L v7.\nProof.\n  induction vs6; intros.\n  inv H0.\n  destruct vs7. inv H1.\n  inv H.\n  destruct n. inv H0; inv H1; auto.  \n  apply nthN_pos_pred in H0.\n  apply nthN_pos_pred in H1.\n  eapply IHvs6; eauto.\nQed.\n\n\n Theorem cons_get_list: forall {A y ys rho vs},\n   @get_list A (y::ys) rho = Some vs ->\n   exists v vs',\n     v::vs' = vs /\\ M.get y rho = Some v /\\ @get_list A ys rho = Some vs'.\n Proof.\n   intros. simpl in H. destruct (M.get y rho) eqn:Hgy; destruct (get_list ys rho) eqn:Hgys.\n   exists a, l. split. inv H; auto. split; reflexivity.\n   inv H. inv H. inv H.\n Qed.\n\n\n Theorem rel_mem_after_asgn: \n   forall fenv finfo_env p rep_env args_b args_ofs m L vs6 locs vs7,\n   @rel_mem_asgn fenv finfo_env p rep_env args_b args_ofs  m L vs6 locs vs7 ->\n     mem_after_asgn args_b args_ofs m locs vs7.\n Proof.\n   induction vs6; intros.\n   - inv H.\n     constructor.\n   - inv H.\n     constructor; eauto.\n Qed.\n \nTheorem rel_mem_of_asgn: forall fenv finfo_env  rep_env args_b args_ofs p lenv m rho L ys inf vs7 vs6,\n mem_of_asgn_v args_b args_ofs p lenv m ys inf vs7 ->\n get_list ys rho = Some vs6 ->\n (forall x, List.In x ys ->\n            exists v6, M.get x rho = Some v6 /\\\n                       repr_val_id_L_LambdaANF_Codegen_id fenv finfo_env p rep_env v6 m L lenv x) ->\n @rel_mem_asgn fenv finfo_env p rep_env args_b args_ofs m L vs6 inf vs7.\nProof.\n  induction ys; intros.\n  -   inv H0; inv H. constructor.\n  - apply cons_get_list in H0. destruct H0 as [v [vs' [Heqvs [Hgar Hgysr]]]]. subst.\n    inv H. constructor.\n    eapply IHys; eauto. intros. eapply H1. constructor 2; auto.\n    eauto.\n    assert (Hli: List.In a (a :: ys)) by (constructor; reflexivity).\n    apply H1 in Hli. destruct Hli. destruct H. inv H7; inv H0.\n    rewrite H2 in H5. inv H5. rewrite H in Hgar. inv Hgar. auto.\n    rewrite H2 in H5; inv H5. rewrite H2 in H7; inv H7.\n    rewrite H5 in H8; inv H8. rewrite H in Hgar. inv Hgar. auto.\nQed. \n\n(* invariant for GC, needs to be shown to be provable from GC proof *)\n(* OS: Changed returned vs7 into vs7' s.t. the pointers can have changed (but represent the same values in LambdaANF) *)\n Definition program_gc_inv (p:program) :=\n  exists b_gcPtr name sg, Genv.find_symbol (globalenv p) gcIdent = Some b_gcPtr /\\\n                          Genv.find_funct (globalenv p) (Vptr  b_gcPtr Ptrofs.zero) = Some (External (EF_external name sg) (Tcons (Tpointer val noattr) (Tcons (Tpointer (Tstruct threadInfIdent noattr) noattr) Tnil)) Tvoid\n                            {|\n                              cc_vararg := false;\n                              cc_unproto := false;\n                              cc_structret := false |}) /\\\n                          forall lenv m finfo_b finfo_env (p:program) rep_env finfo_maxalloc fenv tinf_b tinf_ofs args_b args_ofs L vs6 vs7 inf,\n                            @rel_mem_asgn fenv finfo_env p rep_env args_b args_ofs m L vs6 inf vs7 -> \n                            M.get tinfIdent lenv = Some (Vptr tinf_b tinf_ofs) ->\n                            Mem.loadv int_chunk m (Vptr finfo_b Ptrofs.zero) = Some (make_vint finfo_maxalloc) ->\n                            (int_size * finfo_maxalloc <= gc_size)%Z ->\n                            deref_loc (Tarray uval maxArgs noattr) m tinf_b (Ptrofs.add tinf_ofs (Ptrofs.repr (3*int_size))) (Vptr args_b args_ofs) -> \n                          exists v m' alloc_b alloc_ofs limit_ofs L' vs7',\n                            (Events.external_functions_sem name sg (Genv.globalenv p) [Vptr finfo_b Ptrofs.zero; Vptr tinf_b tinf_ofs] m [] v m') /\\\n                            (* get new alloc *)                            \n                            deref_loc valPtr m' tinf_b tinf_ofs (Vptr alloc_b alloc_ofs) /\\\n                             (* get new limit *)\n                            deref_loc valPtr m' tinf_b (Ptrofs.add tinf_ofs (Ptrofs.repr int_size)) (Vptr alloc_b limit_ofs)  /\\\n                            (* same args block and offset *)\n                            deref_loc (Tarray uval maxArgs noattr) m' tinf_b (Ptrofs.add tinf_ofs (Ptrofs.repr (3*int_size))) (Vptr args_b args_ofs)  /\\\n                            (* deep copied arguments *)\n                            @rel_mem_asgn fenv finfo_env p rep_env args_b args_ofs m' L' vs6 inf vs7' /\\\n                            Mem.unchanged_on (fun b z => and (~(L b z)) (and (~ (L' b z)) (b <> tinf_b))) m m' /\\\n                            (* SEP :- this is just L' disjoint from m \\ L + tinfo AND tinfo [args, alloc_b] is disjoint from global *) \n                            protected_not_in_L_id p  (M.set argsIdent (Vptr args_b args_ofs) (M.set limitIdent (Vptr alloc_b limit_ofs)\n               (M.set allocIdent (Vptr alloc_b alloc_ofs)\n                      (Maps.PTree.set tinfIdent (Vptr tinf_b tinf_ofs) (M.empty _))))) L' /\\\n                            (* Some SEP, some GC :- enough space in nursey, aligned pointers, enough space in args *)\n                            correct_tinfo p finfo_maxalloc (M.set argsIdent (Vptr args_b args_ofs)\n            (M.set limitIdent (Vptr alloc_b limit_ofs)\n               (M.set allocIdent (Vptr alloc_b alloc_ofs)\n                     (Maps.PTree.set tinfIdent (Vptr tinf_b tinf_ofs) (M.empty _)))))  m'.\n\n\n\n\n (* Working towards a clearer interface with the gc \n\n \nAbout meminj.\nAbout Mem.mem_inj.\n   sep1) inject f m m'\n       if not L or tinfo, then f = x -> Some (x, 0)\n\n   gc1) deep roots are copied to L' (in m')\n   sep2)\n       If y in L', then either in L or did not exists in m, i.e. there doesn't exists an x, f x = y\n\n   gc2) limit - alloc > tinfo.max_alloc\n\nas injection, this looks like:\n\n\n          \n\n  *)\n\n \n\n\n(* find the right co for threadInf *)\n\n \nDefinition program_threadinfo_inv (p:program) :=\n  exists co, \n    Maps.PTree.get threadInfIdent (genv_cenv (globalenv p))= Some co /\\\n    co_members co =  ((allocIdent, valPtr) ::\n                         (limitIdent, valPtr) :: (heapInfIdent, (Clightdefs.tptr (Tstruct heapInfIdent noattr))) ::\n                         (argsIdent, (Tarray val maxArgs noattr))::nil).\n\nTheorem allocIdent_delta:\n  forall p,\n      field_offset p allocIdent\n    [(allocIdent, valPtr); (limitIdent, valPtr); (heapInfIdent, Clightdefs.tptr (Tstruct heapInfIdent noattr));\n       (argsIdent, Tarray uval maxArgs noattr)] = OK (0)%Z.\nProof.\n   intro. chunk_red; archi_red; simpl; unfold field_offset; simpl;  \n  assert (Hnd := disjointIdent);\n  inv Hnd; rewrite Coqlib.peq_true;\n  reflexivity.\nQed.    \n\n\nTheorem limitIdent_delta:\n  forall p,\n      field_offset p limitIdent\n    [(allocIdent, valPtr); (limitIdent, valPtr); (heapInfIdent, Clightdefs.tptr (Tstruct heapInfIdent noattr));\n       (argsIdent, Tarray uval maxArgs noattr)] = OK (1*int_size)%Z.\nProof.\n   intro. chunk_red; archi_red; simpl; unfold field_offset; simpl;  \n  assert (Hnd := disjointIdent);\n  inv Hnd.\n  \n  rewrite Coqlib.peq_false.\n  rewrite Coqlib.peq_true.\n  reflexivity.\n  inv H2. \n  intro; subst; apply H3; inList.\n\n  rewrite Coqlib.peq_false.\n  rewrite Coqlib.peq_true.\n  archi_red. simpl. reflexivity.\n  inv H2.\n  intro; subst; apply H3; inList.\nQed.    \n\nTheorem argsIdent_delta:\n  forall p,\n  field_offset p argsIdent\n    [(allocIdent, valPtr); (limitIdent, valPtr);\n    (heapInfIdent, Clightdefs.tptr (Tstruct heapInfIdent noattr));\n    (argsIdent, Tarray uval maxArgs noattr)] = OK (3*int_size)%Z.\nProof.\n  intro. chunk_red; archi_red; simpl; unfold field_offset; simpl;  \n  assert (Hnd := disjointIdent);\n  inv Hnd.\n  \n  rewrite Coqlib.peq_false.\n  rewrite Coqlib.peq_false.\n  rewrite Coqlib.peq_false.\n  rewrite Coqlib.peq_true.\n  reflexivity.\n  intro; subst; apply H1; inList.\n  intro; subst; apply H1; inList.\n  intro; subst; apply H1; inList.\n\n  rewrite Coqlib.peq_false.\n  rewrite Coqlib.peq_false.\n  rewrite Coqlib.peq_false.\n  rewrite Coqlib.peq_true.\n  archi_red. simpl. reflexivity.\n  intro; subst; apply H1; inList.\n  intro; subst; apply H1; inList.\n  intro; subst; apply H1; inList.\nQed.    \n\n(* \nTheorem direct_assignConstructor:\n  forall cenv ienv map v c l,\n    assignConstructor allocIdent threadInfIdent cenv ienv map v c l =\n    assignConstructorS allocIdent threadInfIdent cenv ienv map v c l.\nProof.\n  intros. unfold assignConstructor.\n  unfold assignConstructorS.\n  destruct (makeTag cenv c) eqn:H_makeTag.\n  destruct (make_ctor_rep cenv c) eqn:H_make_ctor_rep.\n  simpl. destruct c0.\n  - (* true because enum n means l is empty, but need some assumptions on the size of l w.r.t. arity of the constructor *)\n    \n    admit.\n  - (* by construction*)\n    admit.\n\n\n  - simpl. induction (rev l). simpl. rewrite H_makeTag. rewrite H_make_ctor_rep. auto.\n  simpl. rewrite IHl0. auto.\n  -  simpl. induction (rev l). simpl. rewrite H_makeTag. auto. \n  simpl. rewrite IHl0. auto.  \nAdmitted.\n*)\n\n\n\nTheorem find_symbol_map:\n  forall p fenv m finfo_env id v, \n    find_symbol_domain p finfo_env ->\n    var_or_funvar id m fenv finfo_env p v (makeVar id m v fenv finfo_env).\nProof. \n  intros. specialize (H v). inv H. \n  destruct (cps.M.get v finfo_env) eqn:Hgvm.\n  - destruct (H0 (ex_intro _ p0 (eq_refl _))). econstructor. apply H.\n  - unfold makeVar. rewrite Hgvm. econstructor.\n    destruct (Genv.find_symbol (Genv.globalenv p) v) eqn:Hgpv; auto.\n    exfalso.\n    destruct (H1 (ex_intro _ b (eq_refl _))).\n    inv H.\nQed.\n \nTheorem find_symbol_map_f:\n    forall p fenv m finfo_env id v, \n    find_symbol_domain p finfo_env ->\n    var_or_funvar_f id m fenv finfo_env p v = makeVar id m v fenv finfo_env.\nProof. \n  intros. apply var_or_funvar_of_f.\n  apply find_symbol_map; auto.\nQed.\n\nTheorem asgnAppVars_correct:\n  forall p fenv finfo_env,\n    forall vs avs ind aind s,\n    find_symbol_domain p finfo_env ->\n      avs = skipn nParam vs ->\n      aind = skipn nParam ind ->\n      asgnAppVars' argsIdent threadInfIdent nParam vs ind fenv finfo_env = Some s ->\n      repr_asgn_fun' argsIdent threadInfIdent nParam fenv finfo_env p avs aind s.\nProof.\n  intros p fenv finfo_env vs avs. generalize vs. clear vs.\n  induction avs; intros vs ind aind s Hfinfo_env Hvs Hind Hasgn; unfold asgnAppVars' in Hasgn.\n  - destruct aind; rewrite <- Hvs in Hasgn; rewrite <- Hind in Hasgn;\n      destruct nParam; inv Hasgn; constructor.\n  - destruct aind; rewrite <- Hvs in Hasgn; rewrite <- Hind in Hasgn; [ destruct nParam; inv Hasgn | ].\n    destruct vs; [destruct nParam; inv Hvs | ].\n    destruct ind; [destruct nParam; inv Hind | ].\n    symmetry in Hvs.\n    set (Hvs' := skipn_cons nParam p0 a vs avs Hvs).\n    symmetry in Hvs'.\n    symmetry in Hind.\n    set (Hind' := skipn_cons nParam n0 n ind aind Hind).\n    symmetry in Hind'.\n    simpl in Hasgn.\n    destruct (asgnAppVars'' argsIdent threadInfIdent nParam avs aind fenv) eqn:Happ.\n    2: inv Hasgn.\n    specialize (IHavs _ _ _ s0 Hfinfo_env Hvs' Hind').\n    unfold asgnAppVars' in IHavs.\n    rewrite <- Hvs' in IHavs.\n    rewrite <- Hind' in IHavs.\n    apply IHavs in Happ.\n    inv Hasgn.\n    erewrite <- find_symbol_map_f; eauto.\n    exact (repr_asgn_cons _ _ _ _ _ _ _ _ _ _ s0 Happ).\nQed.    \n\nTheorem repr_call_vars_length1 : forall p fenv map n l1 l2, repr_call_vars threadInfIdent nParam fenv map p  n l1 l2 -> length l1 = n.\nProof.\n      induction n; intros l1 l2 Hr; destruct l1; inv Hr.\n      + reflexivity. \n      + simpl. apply f_equal.\n        eapply IHn. eauto.\nQed.   \n\n \nTheorem  mkCallVars_correct:\n  forall p fenv map n vs bvs es,\n    find_symbol_domain p map ->\n    bvs = firstn nParam vs -> \n    mkCallVars threadInfIdent nParam fenv map n bvs = Some es ->\n    repr_call_vars threadInfIdent nParam fenv map p n bvs es.\nProof.\n  Admitted. (*\n  intros p fenv map n. unfold repr_call_vars. \n  generalize nParam as m.\n  induction n; intros m vs bvs es Hsym bvsEq Hcall;\n    destruct bvs; try solve [unfold mkCallVars in Hcall; inv Hcall; try constructor; try inv bvsEq].\n  + simpl in Hcall.\n    match_case_hyp Hcall.\n    inv Hcall.\n    erewrite <- (find_symbol_map_f _ _ _ _ _ _ Hsym). \n    constructor.\n    eapply IHn; eauto.\n    constructor. destruct m; inv bvsEq. \n    destruct m. inv bvsEq.\n    rewrite (firstn_cons m p1 vs) in bvsEq.\n    eapply IHn; auto.\n    inbvsEq. destruct m; inv bvsEq.\n    destruct m. inv bvsEq. \n    rewrite (firstn_cons m p1 vs) in bvsEq.\n    inversion bvsEq. Print repr_call_vars.\n    admit.\n\n  Set Printing All. simpl.\n  generalize nParam as m.\n  induction m; induction n; intros vs bvs es Hsym bvsEq Hcall;\n    destruct bvs; try solve [unfold mkCallVars in Hcall; inv Hcall; try constructor].\n  - inv bvsEq.\n  - simpl in Hcall.\n    destruct (mkCallVars threadInfIdent (S m) fenv map n bvs) eqn:HcallEq; inv Hcall.\n    erewrite <- (find_symbol_map_f _ _ _ _ _ _ Hsym).\n    constructor.\n    Print repr_call_vars.\n  intro n.\n  \n\n    admit.\n(*\n    eapply IHn.\n    reflexivity.\n    assumption.\nQed. *)\nAdmitted. *)\n\n\nTheorem repr_make_case_switch:\n  forall x ls ls',\n  repr_switch_LambdaANF_Codegen isptrIdent caseIdent x ls ls' (make_case_switch isptrIdent caseIdent x ls ls').\nProof.\n  intros. unfold make_case_switch. constructor. \nQed.  \n\n\nDefinition makeCases argsIdent allocIdent limitIdent threadInfIdent tinfIdent isptrIdent caseIdent (p:program) fenv cenv ienv map :=\n (fix makeCases (l : list (ctor_tag * exp)) :\n            option (labeled_statements * labeled_statements) :=\n            match l with\n            | [] => Monad.ret (LSnil, LSnil)\n            | p :: l' =>\n                Monad.pbind\n                  (translate_body argsIdent allocIdent limitIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam (snd p) fenv cenv ienv map)\n                  (fun prog : statement =>\n                   Monad.pbind (makeCases l')\n                     (fun '(ls, ls') =>\n                      match make_ctor_rep cenv (fst p) with\n                      | Some (enum t) =>\n                        let tag := ((Z.shiftl (Z.of_N t) 1) + 1)%Z in\n                          match ls' with\n                          | LSnil =>\n                              Monad.ret (ls, LScons None  (Ssequence prog Sbreak) ls')\n                          | LScons _ _ _ =>\n                              Monad.ret\n                                (ls,\n                                LScons (Some (Z.shiftr tag 1))\n                                  (Ssequence prog Sbreak) ls')\n                          end\n                      | Some (boxed t a) =>\n                        let tag := ((Z.shiftl (Z.of_N a) 10) + (Z.of_N t))%Z in\n                          match ls with\n                          | LSnil =>\n                              Monad.ret (LScons None (Ssequence prog Sbreak) ls, ls')\n                          | LScons _ _ _ =>\n                              Monad.ret\n                                (LScons (Some (Z.land tag 255))\n                                   (Ssequence prog Sbreak) ls,\n                                ls')\n                          end\n                      | None => None\n                      end))\n            end).\n\nDefinition fmake_ctor_rep (p:positive) (c:ctor_ty_info) : ctor_rep :=\n  let '(Build_ctor_ty_info name _ it  a  n) := c in\n      match (a =? 0)%N with\n      | true =>\n        (enum n)\n      | false =>\n        (boxed n a)\n      end.\n\n\nDefinition compute_rep_env (cenv:ctor_env): M.t ctor_rep :=\n  M.map fmake_ctor_rep cenv.\n\n\n  \nTheorem crep_cenv_correct:\nforall cenv rep_env, \n  correct_crep_of_env cenv rep_env ->\n  forall c, \n    make_ctor_rep cenv c =  M.get c rep_env.\nProof.\n  intros. unfold make_ctor_rep.\n  destruct (cps.M.get c cenv) eqn:Hgc.\n  - destruct c0.\n    simpl.\n    destruct (ctor_arity =? 0)%N eqn:Hn0.    \n    + rewrite N.eqb_eq in Hn0. subst.\n      inv H. specialize (H0 _ _ _ _ _ _ Hgc). destruct H0. destruct H. inv H0; rewrite H2 in Hgc; inv Hgc. auto.\n    + rewrite N.eqb_neq in Hn0.\n      inv H. specialize (H0 _ _ _ _ _ _ Hgc). destruct H0. destruct H. inv H0; rewrite H2 in Hgc; inv Hgc.  exfalso; apply Hn0; auto.\n      auto. \n  -  simpl. symmetry.\n     inv H. destruct (M.get c rep_env) eqn:Hcr.\n     exfalso. apply H1 in Hcr. inv Hcr; rewrite H in Hgc; inv Hgc. auto.\nQed.\n \nTheorem nth_proj_assign': \n      forall p fenv finfo_env,\n        find_symbol_domain p finfo_env ->\n        forall v l a n,\n        Forall_statements_in_seq' (is_nth_projection_of_x threadInfIdent nParam fenv finfo_env p v) \n                                  (a :: l) (assignConstructorS' threadInfIdent nParam fenv finfo_env v n (a :: l)) (Z.of_nat n).\nProof.\n  induction l; intros.\n  - (* last *)\n    simpl. constructor.\n    constructor.\n    apply find_symbol_map; eauto.\n  - (* IH *)\n    specialize (IHl a (S n)).\n    remember (a::l) as l'. simpl.\n    rewrite Heql'.  constructor.\n    rewrite Nat2Z.inj_succ in IHl.\n    rewrite <- Heql'. rewrite Nat.add_1_r. auto.\n    constructor.\n    apply find_symbol_map; eauto.\nQed.\n\n\nTheorem nth_proj_assign:\n      forall p fenv finfo_env ,\n        find_symbol_domain p finfo_env ->\n        forall v l,\n          length l > 0 ->\n      Forall_statements_in_seq (is_nth_projection_of_x threadInfIdent nParam fenv finfo_env p v) l (assignConstructorS' threadInfIdent nParam fenv finfo_env v 0 l).\nProof.\n  induction l.\n  intros Hl. inv Hl.\n  intros. unfold Forall_statements_in_seq.\n  apply nth_proj_assign'. auto.\nQed.\n\nTheorem repr_asgn_constructorS:\n  forall p cenv ienv  rep_env fenv finfo_env v c l s name iname it n,\n      find_symbol_domain p finfo_env ->\n  correct_crep_of_env cenv  rep_env ->\n  M.get c cenv = Some  (Build_ctor_ty_info name iname it (N.of_nat (length l)) n) ->\n        assignConstructorS allocIdent threadInfIdent nParam cenv ienv fenv finfo_env v c l = Some s -> \nrepr_asgn_constr allocIdent threadInfIdent nParam fenv finfo_env p rep_env v c l s.\nProof.\n  intros p cenv ienv rep_env fenv map v c l s name iname it n Hsymbol; intros.\n  unfold assignConstructorS in *.\n    destruct (makeTag cenv c) eqn:H_makeTag.\n    destruct (make_ctor_rep cenv c) eqn:H_make_ctor_rep.\n    simpl in H1. destruct c0; inv H1.\n  - unfold make_ctor_rep in H_make_ctor_rep. rewrite H0 in H_make_ctor_rep. simpl in *.\n    destruct ((N.of_nat (length l) =? 0)%N ) eqn:Hll; inv H_make_ctor_rep.\n    rewrite OrdersEx.N_as_OT.eqb_eq in Hll.\n    destruct l; inv Hll.\n    unfold makeTag in *.\n    destruct (makeTagZ cenv c) eqn:H_makeTagZ; inv H_makeTag.\n    inv H. specialize (H1 _ _ _ _ _ _ H0). inv H1. inv H. inv H3; rewrite H0 in H; inv H. \n    econstructor. apply H1. \n    {split.  unfold makeTagZ in *.  unfold make_ctor_rep in *. rewrite H0 in H_makeTagZ. simpl in H_makeTagZ. inv H_makeTagZ.\n     reflexivity. \n     auto. }\n  - unfold make_ctor_rep in H_make_ctor_rep. rewrite H0 in H_make_ctor_rep. simpl in *.\n    destruct ((N.of_nat (length l) =? 0)%N ) eqn:Hll; inv H_make_ctor_rep.\n    unfold makeTag in H_makeTag. \n    destruct (makeTagZ cenv c) eqn:H_makeTagZ; inv H_makeTag.\n    inv H. specialize (H1 _ _ _ _ _ _ H0). destruct H1. destruct H.\n    rewrite OrdersEx.N_as_OT.eqb_neq in Hll.\n    inv H1; rewrite H3 in H0; inv H0. exfalso; auto.\n    econstructor. eauto.\n    { split. unfold makeTagZ in *. unfold make_ctor_rep in *.\n      rewrite H3 in H_makeTagZ. simpl Monad.pbind in H_makeTagZ.\n      inv H_makeTagZ; auto.\n      split; auto.  }\n    apply nth_proj_assign. auto.\n    destruct l. exfalso; auto. apply gt_Sn_O.     \n  - simpl in H1; inv H1.\n  - simpl in H1. inv H1.\nQed.\n\n\n\n\n\n\nTheorem make_crep_none:\n  forall c cenv,\n  make_ctor_rep cenv c = None ->\n  M.get c cenv = None.\nProof.\n  intros.\n  unfold make_ctor_rep in *.\n  destruct (cps.M.get c cenv); auto.\n  exfalso. destruct c0. inv H.\n  destruct (ctor_arity =? 0)%N; inv H1.\nQed.\n\nTheorem make_tagZ_none:\n  forall c cenv,\n  makeTagZ cenv c = None ->\n  M.get c cenv = None.\nProof.\n  intros.\n  unfold makeTagZ in *.\n  unfold make_ctor_rep in *.\n  destruct (cps.M.get c cenv). destruct c0. simpl in H.\n  destruct  (ctor_arity =? 0)%N; inv H. auto.\nQed.\n\n(* Main Theorem *)\nTheorem translate_body_correct:\n  forall fenv cenv ienv  p rep_env map,\n    find_symbol_domain p map ->\n    finfo_env_correct fenv map ->\n    correct_crep_of_env cenv rep_env ->\n    forall  e stm,\n      correct_cenv_of_exp cenv e ->\n    translate_body argsIdent allocIdent limitIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam e fenv cenv ienv map = Some stm ->\n    repr_expr_LambdaANF_Codegen_id fenv map p rep_env e stm.\nProof.\n  intros fenv cenv ienv  p rep_env map Hmap Hmapcorrect Hcrep.\n  induction e using exp_ind'; intros stm Hcenv; intros.\n  - (* Econstr *) \n    simpl in H.\n    destruct (assignConstructorS allocIdent threadInfIdent nParam cenv ienv fenv map v t l) eqn:H_eqAssign.\n    destruct (translate_body argsIdent allocIdent limitIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam e fenv cenv ienv map) eqn:H_eqTranslate; inv H.\n    2: inv H.\n    constructor.\n    2: eapply IHe; eauto.\n    clear IHe H_eqTranslate.\n    apply Forall_constructors_in_constr in Hcenv.\n    destruct (M.get t cenv) eqn:Hccenv. destruct c.\n    subst.\n    eapply repr_asgn_constructorS; eauto.\n    inv Hcenv.\n    eapply Forall_constructors_subterm. apply Hcenv. constructor. constructor.\n  -  (* Ecase nil *) simpl in H. inv H.\n                     econstructor. constructor. apply repr_make_case_switch. \n  - (* Ecase *)    \n    simpl in H.\n    destruct (translate_body argsIdent allocIdent limitIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam e fenv cenv ienv map) eqn:He.\n    destruct (translate_body argsIdent allocIdent limitIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam (Ecase v l) fenv cenv ienv map) eqn:Hl.\n    assert (correct_cenv_of_exp cenv (Ecase v l)).\n    { intro; intros. eapply Hcenv. apply rt_then_t_or_eq in H0. inv H0. inv H1. apply t_then_rt. apply subterm_case. eauto. } \n    specialize (IHe0 s0 H0). clear H0.  assert (Some s0 = Some s0) by reflexivity. specialize (IHe0 H0). clear H0.\n    simpl in Hl. \n    destruct (makeCases argsIdent allocIdent limitIdent threadInfIdent tinfIdent isptrIdent caseIdent p fenv cenv ienv map l) eqn:Hmc.\n    assert (Hmc' := Hmc); unfold makeCases in Hmc; simpl in Hmc; rewrite Hmc in H; rewrite Hmc in Hl; clear Hmc. \n    destruct p0. inv Hl.\n    + (* step case *)\n      {\n        assert ( correct_cenv_of_exp cenv e).\n        { intro; intros. eapply Hcenv.  eapply rt_trans. eauto. constructor. econstructor. constructor. reflexivity. }\n        specialize (IHe s H0 eq_refl). clear H0.\n        inv IHe0. (* l0 = ls, ls' = l1 *) unfold make_case_switch in H4. inv H4. \n        destruct ( make_ctor_rep cenv c ) eqn:Hctor_rep. 2: inv H.\n        destruct c0.\n        - (* case-enum *)\n          destruct l1.\n          + (* case-enum-last *)            \n            inv H. econstructor.\n            eapply Runboxed_default_br; eauto. erewrite <- crep_cenv_correct; eauto.\n            apply repr_make_case_switch. \n          + (* case-enum-step *)\n            inv H. econstructor.\n            eapply Runboxed_br; eauto. erewrite <- crep_cenv_correct; eauto.\n            2: apply repr_make_case_switch.\n            erewrite crep_cenv_correct in Hctor_rep; eauto. \n            inv Hcrep. apply H0 in Hctor_rep.  inv Hctor_rep. constructor; auto.            \n        - (* case-boxed *)\n          destruct l0.\n          + (* case-boxed-last *)\n            inv H. econstructor.\n            eapply Rboxed_default_br; eauto. erewrite <- crep_cenv_correct; eauto.\n            apply repr_make_case_switch.\n          + (* case-boxed-step *)\n            inv H. econstructor.\n            eapply Rboxed_br; eauto. erewrite <- crep_cenv_correct; eauto.\n            2: apply repr_make_case_switch.\n            erewrite crep_cenv_correct in Hctor_rep; eauto. \n            inv Hcrep. apply H0 in Hctor_rep.  inv Hctor_rep. constructor; auto.            \n\n      }\n    +   assert (Hmc' := Hmc); unfold makeCases in Hmc; simpl in Hmc; rewrite Hmc in H; rewrite Hmc in Hl; clear Hmc.  inv H.\n    +  (* should probably invvert destruction of makeCases and Hl to avoid this redundant case *) simpl in Hl. \n      destruct (makeCases argsIdent allocIdent limitIdent threadInfIdent tinfIdent isptrIdent caseIdent p fenv cenv ienv map l) eqn:Hmc.\n      assert (Hmc' := Hmc); unfold makeCases in Hmc; simpl in Hmc; rewrite Hmc in H; rewrite Hmc in Hl; clear Hmc.  destruct p0; inv Hl.\n      assert (Hmc' := Hmc); unfold makeCases in Hmc; simpl in Hmc; rewrite Hmc in H; rewrite Hmc in Hl; clear Hmc.  inv H. \n    +  inv H.\n  - (* Eproj *)\n      simpl in H.\n      destruct (translate_body argsIdent allocIdent limitIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam e fenv cenv ienv map) eqn:He.\n      2: inv H. \n      inv H. constructor.\n      eapply IHe.\n      eapply Forall_constructors_subterm. apply Hcenv. constructor. constructor.\n      reflexivity.\n  - (* Efun *)  \n    inv H. \n  - (* Eapp *)\n    unfold translate_body in H.\n    destruct (cps.M.get t fenv) eqn:Hffenv. 2:inv H. \n    destruct f as [n locs].\n    unfold var , cps.M.elt in l.\n    set (avs := skipn nParam l).\n    set (aind := skipn nParam locs).\n    set (bvs := firstn nParam l).\n    assert (vsEq : avs = skipn nParam l). reflexivity.\n    assert (indEq : aind = skipn nParam locs). reflexivity. \n    assert (bvsEq : bvs = firstn nParam l). reflexivity.\n    unfold asgnAppVars in H. unfold asgnAppVars' in H.\n    unfold mkCall in H.\n    simpl in H.\n    rewrite <- vsEq in H. rewrite <- indEq in H. rewrite <- bvsEq in H.  \n    destruct (asgnAppVars'' argsIdent threadInfIdent nParam avs aind fenv map) eqn:Happvar; inv H.\n    destruct (mkCallVars threadInfIdent nParam fenv map (Init.Nat.min (N.to_nat n) nParam) bvs) eqn:Hcallvar; inv H1.\n    erewrite <- find_symbol_map_f. 2: eauto.\n    econstructor; eauto.\n    constructor.\n    eapply asgnAppVars_correct; eauto.\n    eapply mkCallVars_correct; eauto.\n  - (* Eprim *)\n    inv H. \n  - (* Ehalt *)\n    simpl in H. inv H.\n\n    eapply R_halt_e.\n    apply find_symbol_map. auto.\nQed.\n\n\n\n(* PROOFs on correct environments *)\n\n(* ctor_ty_info is proper if a and ord are small enough to be represented *)\nInductive proper_ctor_ty_info: ctor_ty_info -> Prop :=\n| PC_enum: forall name iname it ord,\n    (0 <= (Z.of_N ord) <   Ptrofs.half_modulus)%Z ->\n    proper_ctor_ty_info (Build_ctor_ty_info name iname it 0%N ord)\n| PC_boxed: forall name iname it a ord,\n    (* there should not be more than 2^8 - 1 boxed constructors *)\n    (0 <= (Z.of_N ord) <  Zpower.two_p 8)%Z ->\n    (* arity shouldn't be higher than 2^54 - 1  *)\n    (0 <= Z.of_N (Npos a) <  Zpower.two_power_nat (Ptrofs.wordsize - 10))%Z ->\n    proper_ctor_ty_info (Build_ctor_ty_info name iname it (Npos a)%N ord).\n\n  \n \n(* cenv is proper if ctor_ty_info is proper, and that there is a unique (ty, ord) pair for each constructors  *)\nDefinition proper_cenv (cenv:ctor_env):=\n  forall c name iname it a ord,\n    M.get c cenv = Some (Build_ctor_ty_info name iname it a ord) ->\n    proper_ctor_ty_info (Build_ctor_ty_info name iname it a ord) /\\\n      ~ (exists c' name' iname' a', c <> c' /\\\n                    M.get c' cenv = Some (Build_ctor_ty_info name' iname' it a' ord)).\n\n(* Definition proper_nenv ? *)\n\n\n\nTheorem proper_cenv_set_none:\n  forall k v m,\n  proper_cenv (Maps.PTree.set k v m) ->\n  M.get k m = None ->\n  proper_cenv m.\nProof.\n  intros; intro; intros.\n  assert (c <> k). intro; subst. rewrite H1 in H0; inv H0.\n  split.\n  erewrite <- M.gso in H1. 2: eauto. apply H in H1. destruct H1; auto.\n  intro; destructAll.  \n  assert (x <> k). intro; subst. rewrite H4 in H0; inv H0.\n  erewrite <- M.gso in H1.\n  apply H in H1. destruct H1.\n  apply H6.\n  exists x, x0, x1, x2.\n  split; auto.\n  rewrite M.gso; auto.\n  auto. \nQed.\n\n\n\n\n\nTheorem compute_proper_rep_env: forall cenv,\nproper_cenv cenv -> \n  correct_crep_of_env cenv (compute_rep_env cenv).\nProof.\n  intros. split; intros.\n  - unfold compute_rep_env. rewrite M.gmap.\n    unfold fmake_ctor_rep. rewrite H0.\n    simpl.\n    specialize (H _ _ _ _ _ _ H0). destructAll.\n    destruct a.\n    + eexists; split; auto. rewrite N.eqb_refl.  inv H. econstructor; eauto.\n    + eexists; split; auto. assert (N.pos p <> 0%N). intro Hp; inv Hp. rewrite <- N.eqb_neq in H2.  rewrite H2. inv H. econstructor; eauto.\n  - unfold compute_rep_env in H0.    \n    rewrite M.gmap in H0.\n    unfold fmake_ctor_rep in H0.\n    destruct (M.get c cenv) eqn:Hccenv. 2: inv H0.\n    destruct c0. simpl in H0.\n    specialize (H _ _ _ _ _ _ Hccenv). destruct H.\n    destruct ctor_arity.\n    + rewrite N.eqb_refl in H0.  inv H0. inv H. econstructor; eauto.\n    + assert (N.pos p <> 0%N). intro Hp; inv Hp. rewrite <- N.eqb_neq in H2.  rewrite H2 in H0. inv H0. inv H. econstructor; eauto.\nQed.\n\n\n  Theorem compute_dc_ienv:\n  forall cenv, \n    (fun cenv ienv => proper_cenv cenv ->\n                      domain_ienv_cenv cenv ienv /\\\n                    correct_ienv_of_cenv cenv ienv) cenv (compute_ind_env cenv).\nProof.\n  intro cenv.\n  eapply Maps.PTree_Properties.fold_rec; intros.\n  - assert (proper_cenv m).\n    { intro; intros. rewrite H in H2. apply H1 in H2. destruct H2.\n      split; auto. intro; apply H3.  destructAll. rewrite H in H5.\n      exists x , x0 , x1 , x2. auto.\n    }\n    specialize (H0 H2). destruct H0. split.\n    intro; intros. eapply H0 in H5; eauto. rewrite H in H5. auto.    \n    intro; intros. rewrite <- H in H4. apply H3 in H4. auto. \n  - split; intro; intros; rewrite M.gempty in *; exfalso; inv H0. \n  - assert (proper_cenv  m) by (eapply proper_cenv_set_none; eauto).\n    specialize (H1 H3). destruct H1.\n    assert ( domain_ienv_cenv (Maps.PTree.set k v m) (update_ind_env a k v)).\n    {\n      intro; intros. destruct v. simpl in H5.\n      destruct ( cps.M.get ctor_ind_tag a) eqn:Hgi0a.\n      + destruct n.\n        destruct (var_dec i ctor_ind_tag).\n        * subst. rewrite M.gss in H5. inv H5. inv H6.\n          (* k = x *)\n          inv H5. eexists. apply M.gss.\n          (* k <> x *)\n          eapply H1 in H5; eauto. destruct H5. eexists.\n          rewrite M.gso. eauto. intro; subst. rewrite H5 in H. inv H.\n        * rewrite M.gso in H5 by auto.\n          eapply H1 in H6; eauto. destruct H6. eexists.\n          rewrite M.gso. eauto. intro; subst. rewrite H6 in H; inv H.\n      + destruct (var_dec i ctor_ind_tag).\n        * subst. rewrite M.gss in H5. inv H5. inv H6. inv H5. exists namei. apply M.gss. inv H5.\n        * rewrite M.gso in H5 by auto. apply H1 in H5. apply H5 in H6. destruct H6.\n          exists x0. rewrite M.gso. auto.  intro; subst. rewrite H in H6. inv H6.\n    } split; auto.\n    \n\n      \n    intro. intros.\n    assert (H6' := H6).\n    apply H2 in H6'. destruct H6' as [H6b H6'].\n    destruct (cps_util.var_dec x k).\n    + (* x = k  -> can update i and it still be proper *)\n      subst. rewrite M.gss in H6. inv H6.\n      simpl.  destruct (M.get i a) eqn:Hgia.\n      * (* i was already in a *)\n        destruct n. eexists. eexists. split.  apply M.gss.\n        split. constructor. reflexivity.\n        split; intro; intros; destructAll.\n        inv H7. inv H8. apply H6; auto.\n        eapply H1 in H8; eauto. inv H8. rewrite H7 in H; inv H.\n        inv H7. inv H8. apply H6; auto.\n        (* constructor shares the same ord, cannot be proper *)\n        eapply H1 in H8; eauto. inv H8.\n        destruct (var_dec x0 k); subst. rewrite H7 in H; inv H.\n        apply H6'. exists x0. eexists. eexists. eexists.\n        split; auto. rewrite M.gso by auto. eauto.\n      * (* k is the first cons of i *)\n        eexists. eexists. split. apply M.gss.\n        split. constructor. reflexivity.\n        split; intro; intros; destructAll.\n        inv H7; inv H8. apply H6; auto.\n        inv H7; inv H8. apply H6; auto.            \n    + (* x <> k *)\n      \n      assert (H6'' := H6).\n      rewrite M.gso in H6 by auto.\n      apply H4 in H6. destructAll.\n      {\n        unfold update_ind_env. destruct v. \n        destruct  (cps.M.get ctor_ind_tag a) eqn:Hi0a.\n        - destruct n0. \n          destruct (var_dec i ctor_ind_tag).\n          + subst.\n            rewrite Hi0a in H6. inv H6.\n            eexists. exists  ((ctor_name, k, ctor_arity, ctor_ordinal) :: x1).\n            split. rewrite M.gss; auto.\n            split. constructor 2. auto.\n            split. \n            * intro; intros.\n              destructAll.\n              inv H10.\n              inv H11. apply n; auto.\n              apply H8. eexists; eexists; eexists. split; eauto.\n            * intro; intros.\n              destructAll.\n              inv H10.\n              inv H11. apply H6'. eexists. eexists. eexists. eexists. split.\n              apply n. rewrite M.gss. reflexivity.\n              eapply H9.\n              eexists. eexists. eexists. split; eauto.                          \n          + exists x0, x1. rewrite M.gso; auto. \n        - exists x0, x1. rewrite M.gso. auto. intro; subst. rewrite H6 in Hi0a. inv Hi0a.\n      }\nQed.\n\n\n\n(* Note: can be proven directly *)\nCorollary compute_domain_ienv:\n  forall cenv, \n                    (fun cenv ienv => proper_cenv cenv -> \n                    domain_ienv_cenv cenv ienv) cenv (compute_ind_env cenv).\nProof.\n    assert ( forall cenv, \n           (fun cenv ienv => proper_cenv cenv ->\n                              domain_ienv_cenv cenv ienv /\\\n                    correct_ienv_of_cenv cenv ienv) cenv (compute_ind_env cenv)) by apply compute_dc_ienv. simpl; intros. simpl in H.  apply H in H0. destruct H0.\n  auto.\nQed.\n\n\nCorollary compute_correct_ienv:\n  forall cenv, \n                    (fun cenv ienv => proper_cenv cenv -> \n                    correct_ienv_of_cenv cenv ienv) cenv (compute_ind_env cenv).\nProof.\n  assert ( forall cenv, \n           (fun cenv ienv => proper_cenv cenv ->\n                              domain_ienv_cenv cenv ienv /\\\n                    correct_ienv_of_cenv cenv ienv) cenv (compute_ind_env cenv)) by apply compute_dc_ienv. simpl; intros. simpl in H.  apply H in H0. destruct H0.\n  auto.\nQed.\n\n\nDefinition correct_fenv_for_function (fenv:fun_env):=\n  fun f (t:fun_tag) (ys:list LambdaANF.cps.var) (e:exp) =>\n    exists n l, M.get f fenv = Some (n, l) /\\\n                n = N.of_nat (length l) /\\\n                length l = length ys /\\\n                    NoDup l /\\\n                    Forall (fun i => 0 <= (Z.of_N i) < max_args)%Z l. \n\nSearchAbout fun_tag. \n(* fun_tag are associated with an arity and a calling convention. \n   all functions and applications with this fun_tag have the right number of arguments *)\n\nDefinition correct_fenv (fenv:fun_env) (fds:fundefs):= Forall_fundefs (correct_fenv_for_function fenv) fds.\n\n(*\n(* unique tags of arity *)\nTheorem compute_correct_fenv:\n  forall fds  fenv,\n    \n    forall fenv', \n  compute_fun_env_fds fds fenv' = fenv ->\n  Forall_fundefs (correct_fenv_for_function fenv) fds.\nProof.\n  induction fds; intros.\n  -  simpl in H0.\n     inv H.\n     constructor.\n     +   admit.\n     + eapply IHfds. auto. reflexivity.     \n  - constructor.\nQed.  *)\n\n\n \n\n(* TODO: something that implies correct_fundef_info when ldefs are put in memory\nTheorem make_fundef_info_correct:\n  correct_fenv fenv fds ->\n  make_fundef_info fds fenv nenv = Some (ldefs * finfo_env * nenv') -> \n\n\n*)\n  \n        \n\n\n\n\nDefinition program_inv (p:program) := program_isPtr_inv p /\\ program_threadinfo_inv p /\\ program_gc_inv p.\n \n(* At the top level:\n  correct_envs >\n    > correct_ienv_of_cenv -> link ienv and crep\n    > correct_cenv_of_env -> this is just correct_cenv_of_exp for all functions, which is to say correct_cenv_of_exp on the full initial term \n    > correct_cenv_of_exp -> see above, correct_cenv_of_exp (fds e) so correct_cenv_of_exp e\n    > correct_crep_of_env -> correctness of crep\n  protected_id_not_bound -> disjoint bound_var and protected_id\n  unique_bindings_envs -> by unique_bindings on e\n  functions_not_bound -> by unique_bindings, all bound vars in e are disjoint from functions which were added to globalenv\n  rel_mem -> L can be empty since rho only has fun,\n             repr_val_id for all funs\n             closed_val for all funs \n             correct_fundefs_info for all funs\n  correct_alloc -> just computed\n  correct_tinfo ->  tinfo is initialized properly\n *)\n\nTheorem sizeof_uval:\n  forall p,\n  (sizeof p uval) = int_size.\nProof.\n  intro. unfold sizeof.\n  chunk_red; archi_red; auto.\nQed.\n\nTheorem sizeof_val:\n  forall p,\n  (sizeof p val) = int_size.\nProof.\n  intro. unfold sizeof.\n  chunk_red; archi_red; auto.\nQed.\n\n\nTheorem ptrofs_of_int64:\n  forall x, \n  Ptrofs.repr (Int64.unsigned (Int64.repr x)) = Ptrofs.repr x.\nProof.\n  intro.\n  symmetry.\n  eapply Ptrofs.eqm_samerepr. apply Int64.eqm_unsigned_repr.\nQed.\n\nTheorem ptrofs_of_int:\n  forall x,\n    Archi.ptr64 = false ->\n  Ptrofs.repr (Int.unsigned (Int.repr x)) = Ptrofs.repr x.\nProof.\n  intros.\n  symmetry.\n  eapply Ptrofs.eqm_samerepr.\n  apply Ptrofs.eqm32; auto.\n  apply Int.eqm_unsigned_repr.\nQed.\n\nTheorem sem_cast_vint:\n  forall n m, \n sem_cast (make_vint n) uval uval m = Some (make_vint n).\nProof.\n  intros. unfold sem_cast; chunk_red; simpl; archi_red; simpl; archi_red; auto.\nQed.\n\n\nTheorem sem_notbool_val:\n  forall n m,\n    sem_notbool\n          (Val.of_bool n) type_bool  m = Some (Val.of_bool (negb n)).\nProof.\n  intros; destruct n; simpl; reflexivity.\nQed.  \n\nTheorem eval_cint :\n  forall p env lenv m z, \n eval_expr (globalenv p) env lenv m\n    (make_cint z val) (make_vint z).\nProof.\n  intros.\n  chunk_red; archi_red.\n  constructor.\n  unfold make_cint. archi_red. constructor.\nQed.\n\nDefinition mk_gc_call_env' p (ys vs : list positive) (lenv_old lenv : temp_env) :\n  (Forall (fun x : positive => exists v : Values.val, get_var_or_funvar p lenv_old x v) ys) -> length ys = length vs -> temp_env.\nProof.\n  generalize vs. clear vs.\n  induction ys; intros vs Hval Hlen; destruct vs; [ | inv Hlen | inv Hlen | ].\n  - exact lenv. \n  - refine (M.set p0 _ (IHys vs _ _)).\n    destruct (Genv.find_symbol (Genv.globalenv p) a) eqn:geta1.\n    + exact (Vptr b (Ptrofs.repr 0)).\n    + destruct (M.get a lenv_old) eqn:geta2.\n      * exact v.\n      * abstract (\n            set (t := proj1 (Forall_forall _ _) Hval a (or_introl eq_refl));\n            simpl in t;\n            exfalso; inv t; inv H; [ rewrite geta1 in H0; inv H0\n                                   | rewrite geta2 in H1; inv H1]\n            ).\n    + abstract(apply Forall_forall; intros x Hin;\n               exact (proj1 (Forall_forall _ _) Hval x (or_intror Hin))).\n    + abstract (inv Hlen; auto).\nDefined.\n\n\nDefinition mk_gc_call_env p (ys vs : list positive) (lenv_old lenv : temp_env) :\n  (Forall (fun x : positive => exists v : Values.val, get_var_or_funvar p lenv_old x v) ys) -> length ys = length vs -> temp_env.\nProof.\n  generalize vs. clear vs.\n  induction ys; intros vs Hval Hlen; destruct vs; [ | inv Hlen | inv Hlen | ].\n  - exact lenv. \n  - refine (M.set p0 _ (IHys vs _ _)).\n    destruct (Genv.find_symbol (Genv.globalenv p) a).\n    + exact (Vptr b (Ptrofs.repr 0)).\n    + destruct (M.get a lenv_old).\n      * exact v.\n      * exact Vundef.\n    + abstract(apply Forall_forall; intros x Hin;\n               exact (proj1 (Forall_forall _ _) Hval x (or_intror Hin))).\n    + abstract (inv Hlen; auto).\nDefined.\n\nTheorem mk_gc_call_env_correct : forall p (ys vs : list positive) (lenv_old lenv : temp_env) Hys Hlen, NoDup vs ->\n    (Forall (fun x : positive => exists v : Values.val, get_var_or_funvar p (mk_gc_call_env p ys vs lenv_old lenv Hys Hlen) x v) vs).\nProof.\n  intros p ys. induction ys; intros vs lenv_old lenv Hys Hlen noDupvs; destruct vs; [ | inv Hlen | inv Hlen | ]; constructor.\n  - destruct Hys. inv Hlen. clear a.\n    destruct e as [v Hv]. exists v.\n    destruct Hv; simpl.\n    + constructor 2.\n      * admit.\n      * rewrite Maps.PTree.gss. rewrite e.\n        reflexivity.\n      * auto.\n    + constructor 2.\n      * admit.\n      * rewrite Maps.PTree.gss. rewrite e.\n        rewrite e0.\n        reflexivity.\n      * auto.\n  - admit.\n    Admitted.\n   (* apply IHys.\n        \n    destruct (Genv.find_symbol (Genv.globalenv p) x) eqn:geta1.\n    + exists (Vptr b (Ptrofs.repr 0)).\n      simpl. constructor 2.\n      * admit.\n      * rewrite Maps.PTree.gss.\n        rewrite geta1. reflexivity.\n      * \n        \n    + destruct (M.get a lenv_old) eqn:geta2.\n      * \n      * \n        rewrite geta1.\n        rewrite geta1.\n    unfold mk_gc_call_env. simpl.\n    \n    eexists. \n    simpl. \n    rewrite geta1. *)\n\nLtac unsigned_ptrofs_range :=\n  split; [apply Ptrofs.unsigned_range |  etransitivity;  [apply Ptrofs.unsigned_range_2 | rewrite ptrofs_mu; archi_red; reflexivity] ].\n\n\nTheorem type_of_mkFunTyList:\n  forall nParam vsm4, \n  (mkFunTyList\n     (Init.Nat.min (length vsm4)\n             nParam)) = (type_of_params (map (fun x : ident => (x, uval))\n                                              (firstn nParam vsm4))).\nProof.\n  induction nParam0; intros; simpl.\n  -  rewrite Nat.min_0_r.\n     reflexivity.\n  - destruct vsm4.\n    + (* empty list *)\n      reflexivity.\n    + simpl. erewrite IHnParam0. reflexivity.\nQed.\n\n(* Main Theorem *)\nTheorem repr_bs_LambdaANF_Codegen_related:\n  forall (p : program) (rep_env : M.t ctor_rep) (cenv : ctor_env)\n         (fenv : fun_env) (finfo_env : M.t (positive * fun_tag)) (ienv : n_ind_env),\n    program_inv p -> (* isPtr function is defined/correct /\\ thread info is correct /\\ gc invariant *)\n    find_symbol_domain p finfo_env -> (* finfo_env [LambdaANF] contains precisely the same things as global env [Clight] *)\n    finfo_env_correct fenv finfo_env -> (* everything in finfo_env is in the function environment *)\n    forall (rho : eval.env) (v : cps.val) (e : exp) (n : nat), (* rho is environment containing outer fundefs. e is body of LambdaANF program *)\n      bstep_e (M.empty _) cenv rho e v n ->  (* e n-steps to v *) (* for linking: environment won't be empty *)\n      correct_envs cenv ienv rep_env rho e -> (* inductive type/constructor environments are correct/pertain to e*)\n      protected_id_not_bound_id rho e ->\n      unique_bindings_env rho e ->\n      functions_not_bound p rho e -> (* function names in p/rho not bound in e *)\n      forall (stm : statement) (lenv : temp_env) (m : mem) (k : cont) (max_alloc : Z) (fu : function),\n        repr_expr_LambdaANF_Codegen_id fenv finfo_env p rep_env e stm -> (* translate_body e returns stm *)\n        rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env e rho m lenv ->\n        (* \" relates a LambdaANF evaluation environment [rho] to a Clight memory [m/lenv] up to the free variables in e \" *)\n        (* also says fundefs in e are correct in m *)\n        (* NOTE: this is only place pertaining to outside of the body, and can likely incorporate free variables here *)\n        correct_alloc e max_alloc ->  (* max_alloc correct *)\n        correct_tinfo p max_alloc lenv m -> (* thread_info correct *)\n        exists (m' : mem) (lenv' : temp_env),\n          m_tstep2 (globalenv p) (State fu stm k empty_env lenv m) (State fu Sskip k empty_env lenv' m') /\\\n          (* memory m/lenv becomes m'/lenv' after executing stm *)\n          same_args_ptr lenv lenv' /\\\n          arg_val_LambdaANF_Codegen fenv finfo_env p rep_env v m' lenv'. (* value v is related to memory m'/lenv' *)\nProof.\n  intros p rep_env cenv fenv finfo_env ienv Hpinv Hsym HfinfoCorrect rho v e n Hev.\n  induction Hev; intros Hc_env Hp_id Hrho_id Hf_id stm lenv m k max_alloc fu Hrepr_e Hrel_m Hc_alloc Hc_tinfo; inv Hrepr_e.\n  - (* Econstr *)\n\n    assert (Hx_not:  ~ is_protected_id_thm  x). {\n          intro. inv Hp_id. eapply H2; eauto.    \n    }\n\n    \n    (* get the tempenv and mem after assigning the constructor *)\n    assert (exists lenv' m', \n               ( clos_trans state (traceless_step2 (globalenv p))\n                                     (State fu s (Kseq s' k) empty_env lenv m)  \n                                     (State fu Sskip (Kseq s' k) empty_env lenv' m') )\n               /\\  rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env e (M.set x (Vconstr t vs) rho) m' lenv'\n               /\\ correct_tinfo p (Z.of_nat (max_allocs e)) lenv' m' /\\\n                   same_args_ptr lenv lenv').\n    {\n      inv H6.\n      - (* boxed *)\n\n        assert (Ha_l : a = N.of_nat (length ys) /\\ ys <> []). {          \n          assert (subterm_or_eq (Econstr x t ys e) (Econstr x t ys e)) by constructor 2.  \n          inv Hc_env. destruct H5 as [H5' H5]. destruct H5 as [H5 H6].\n          apply H5 in H3.   destruct (M.get t cenv) eqn:Hmc. destruct c0. inv H6.\n          apply H9 in H0. inv H0. rewrite H10 in Hmc. inv Hmc.\n          split; auto. destruct ys. inv H2. intro. inv H0. inv H3.\n        }\n\n        \n        (* 1 -> get the alloc info, steps through the assignment of the header *)\n        assert (Hc_tinfo' := Hc_tinfo).\n        unfold correct_tinfo in Hc_tinfo.\n        destruct Hc_tinfo as [alloc_b [alloc_ofs [limit_ofs [args_b [args_ofs [tinf_b [tinf_ofs [Hget_alloc [Halign_alloc [Hrange_alloc [Hget_limit [Hbound_limit [Hget_args [Hdj_args [Hbound_args [Hrange_args [Htinf1 [Htinf2 [Htinf3 [Hinf_limit [Htinf_deref Hglobals]]]]]]]]]]]]]]]]]]]]].\n\n        assert (~ is_protected_id_thm x).\n        { intro. inv Hp_id. eapply H5; eauto. }\n\n        assert (Hx_loc_eq : (Ptrofs.add (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr int_size) (Ptrofs.repr Z.one))) (Ptrofs.mul (Ptrofs.repr int_size) (Ptrofs.repr (-1)))) = alloc_ofs). { \n          rewrite Ptrofs.add_assoc.\n          rewrite Ptrofs.mul_mone.\n          rewrite Ptrofs.mul_one.\n          rewrite Ptrofs.add_neg_zero.\n          apply Ptrofs.add_zero.\n        }\n         \n        \n        assert ( {m2 : mem |  Mem.store int_chunk m alloc_b\n                                      (Ptrofs.unsigned alloc_ofs) (make_vint h) = Some m2}). {\n          apply Mem.valid_access_store.\n          split.\n          intro.\n          intro. apply Hrange_alloc.\n          unfold int_size in *.\n          simpl size_chunk in *.\n          inv H4.\n          split; auto.\n          eapply OrdersEx.Z_as_OT.lt_le_trans. eauto.          \n          inv Hbound_limit. \n          inv Hc_alloc. simpl max_allocs. destruct ys. exfalso; inv Ha_l; auto. simpl max_allocs in H4. \n          rewrite Nat2Z.inj_succ in H4. chunk_red; omega.\n          auto. \n        }\n        destruct X as [m2 Hm2]. \n   \n        assert (Hstep_m2 : clos_trans state (traceless_step2 (globalenv p))\n                            (State fu\n         (Ssequence\n            (Ssequence\n               (Ssequence\n                  (Sset x\n                     (Ecast\n                        (add (Etempvar allocIdent (Tpointer val {| attr_volatile := false; attr_alignas := None |}))\n                           (c_int' Z.one val)) val))\n                  (Sset allocIdent\n                     (add (Etempvar allocIdent (Tpointer val {| attr_volatile := false; attr_alignas := None |}))\n                        (c_int' (Z.of_N (a + 1)) val))))\n               (Sassign\n                  (Ederef\n                     (add (Ecast (Etempvar x val) (Tpointer val {| attr_volatile := false; attr_alignas := None |}))\n                          (c_int' (-1)%Z val)) val) (c_int' h val))) s0) (Kseq s' k) empty_env lenv m)\n                           (State fu s0 (Kseq s' k) empty_env\n       (Maps.PTree.set allocIdent\n          (Vptr alloc_b (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr (Z.of_N (a + 1))))))\n          (Maps.PTree.set x\n             (Vptr alloc_b (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr Z.one)))) lenv)) m2)).\n        {  \n          eapply t_trans. constructor. constructor.\n          eapply t_trans. constructor. constructor.\n          eapply t_trans. constructor. constructor.\n          chunk_red; archi_red.\n          (* branch ptr64 *)\n          \n          { \n            eapply t_trans. constructor. constructor. econstructor.\n            econstructor. constructor. eauto. constructor. constructor.\n            constructor.\n            eapply t_trans. constructor. constructor.\n\n            eapply t_trans. constructor. constructor.\n            econstructor. constructor. rewrite M.gso. \n            eauto. intro. apply H3. rewrite <- H4. inList. \n            constructor. constructor.\n            eapply t_trans. constructor. constructor.\n            eapply t_trans. constructor. econstructor. constructor. simpl. econstructor.\n            econstructor. constructor. rewrite M.gso. rewrite M.gss. reflexivity.\n            intro. apply H3. rewrite  H4. inList.\n            constructor. econstructor. constructor. constructor. constructor. simpl.\n            econstructor. econstructor.  simpl.  unfold Ptrofs.of_int64. rewrite ptrofs_of_int64. rewrite ptrofs_of_int64.  \n            rewrite Hx_loc_eq. eauto.\n            constructor. unfold Ptrofs.of_int64. do 2 (rewrite ptrofs_of_int64).\n            constructor.          \n          }\n          {\n            archi_red.\n            eapply t_trans. constructor. constructor. econstructor.\n            econstructor. constructor. eauto. constructor. constructor.\n            unfold sem_cast. simpl; archi_red.  constructor.\n\n            eapply t_trans. constructor. constructor.\n\n            eapply t_trans. constructor. constructor.\n            econstructor. constructor. rewrite M.gso. \n            eauto. intro. apply H3. rewrite <- H4. inList. \n            constructor. constructor.\n            eapply t_trans. constructor. constructor.\n            archi_red.\n            eapply t_trans. constructor. econstructor. constructor. simpl. econstructor.\n            econstructor. constructor. rewrite M.gso. rewrite M.gss. reflexivity.\n            intro. apply H3. rewrite  H4. inList.\n            unfold sem_cast; simpl; archi_red. constructor. \n            constructor. simpl.  unfold Ptrofs.of_intu. unfold Ptrofs.of_int. rewrite ptrofs_of_int.\n            unfold sval; archi_red. constructor. auto.\n            econstructor. constructor. simpl. econstructor. constructor.\n            unfold Ptrofs.of_intu. unfold Ptrofs.of_int. rewrite ptrofs_of_int.\n            rewrite Hx_loc_eq. eauto. auto.\n            constructor.\n            unfold Ptrofs.of_intu. unfold Ptrofs.of_int. rewrite ptrofs_of_int.\n            unfold Cop.ptrofs_of_int.             unfold Ptrofs.of_intu. unfold Ptrofs.of_int. rewrite ptrofs_of_int.\n            constructor.\n            auto. auto. \n          } }\n        \n        \n        (* 2 -> use mem_of_Forall_nth_projection to step through the assignment of vs *)\n        assert (Hstep_m3 := mem_of_Forall_nth_projection_cast).\n        specialize (Hstep_m3 threadInfIdent nParam fenv finfo_env p x\n                             (Maps.PTree.set allocIdent\n                                             (Vptr alloc_b\n                                                   (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr (Z.of_N (a + 1))))))\n                                             (Maps.PTree.set x\n                                                             (Vptr alloc_b (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr Z.one))))\n                                                             lenv))\n                             alloc_b\n                             (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr Z.one)))\n                             fu\n                   ).\n        assert (Htemp :  M.get x\n               (Maps.PTree.set allocIdent\n                  (Vptr alloc_b\n                     (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr (Z.of_N (a + 1))))))\n                  (Maps.PTree.set x\n                     (Vptr alloc_b (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr Z.one)))) lenv)) =\n             Some (Vptr alloc_b (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr Z.one))))).\n        rewrite M.gso. rewrite M.gss. reflexivity. intro; apply Hx_not. rewrite H4. inList.\n        specialize (Hstep_m3 Hsym HfinfoCorrect Htemp ys s0 0%Z m2 (Kseq s' k)). clear Htemp.\n        assert (Htemp : (0 <= 0)%Z /\\ (0 + Z.of_nat (length ys) <= Ptrofs.max_unsigned)%Z ).\n        {\n          split. omega.\n          assert (Ptrofs.unsigned limit_ofs <= Ptrofs.max_unsigned)%Z.\n          assert (Htemp := Ptrofs.unsigned_range_2 limit_ofs). omega.\n          assert (int_size * max_alloc <= gc_size)%Z by omega.\n          chunk_red; archi_red.\n         \n          inv Hc_alloc; destruct ys; inv H2.\n          simpl. unfold Int64.max_unsigned. simpl. omega.\n          simpl max_allocs in H5.\n          rewrite Nat2Z.inj_succ in H5. \n          rewrite Nat2Z.inj_add in H5.\n          simpl length.\n          etransitivity. etransitivity.\n          2:apply H5. omega.\n          unfold gc_size. simpl. unfold Int64.max_unsigned. simpl. omega.\n\n\n          inv Hc_alloc; destruct ys; inv H2.\n          simpl. unfold Int.max_unsigned. simpl. omega.\n          simpl max_allocs in H5.\n          rewrite Nat2Z.inj_succ in H5. \n          rewrite Nat2Z.inj_add in H5.\n          simpl length.\n          etransitivity. etransitivity.\n          2:apply H5. omega.\n          unfold gc_size. simpl. unfold Int.max_unsigned. simpl. omega.          \n          \n        }          \n\n        specialize (Hstep_m3 Htemp). clear Htemp.\n        assert (Htemp : (forall j : Z,\n              (0 <= j < 0 + Z.of_nat (length ys))%Z ->\n              Mem.valid_access m2 int_chunk alloc_b\n                (Ptrofs.unsigned\n                   (Ptrofs.add (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr Z.one)))\n                            (Ptrofs.repr (int_size * j)))) Writable)). {\n\n\n          intros.\n          \n          (* BACK specialize (Hrange_alloc (j+1)%Z). *)\n           \n          inv Hc_alloc.  destruct ys. inv H2.          \n          assert ((0 <= j + 1 <  Z.of_nat (max_allocs (Econstr x t (v0 :: ys) e)))%Z).\n          simpl. simpl in H4.\n          rewrite Zpos_P_of_succ_nat.\n          rewrite Nat2Z.inj_add.\n          rewrite Zpos_P_of_succ_nat in H4.\n          rewrite Nat2Z.inj_succ. omega.\n          replace ((Ptrofs.add (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr Z.one))) (Ptrofs.repr (int_size * j)))) with (Ptrofs.add alloc_ofs (Ptrofs.repr (int_size * (j + 1)))).\n\n          eapply Mem.store_valid_access_1; eauto.\n          replace (Ptrofs.unsigned (Ptrofs.add alloc_ofs (Ptrofs.repr (int_size * (j + 1))))) with\n                   (Ptrofs.unsigned alloc_ofs + int_size * (j+1))%Z.          \n          eapply range_perm_to_valid_access. \n          eapply Hrange_alloc.\n          eapply OrdersEx.Z_as_DT.divide_add_r.\n          auto.\n          unfold int_size. \n          eapply OrdersEx.Z_as_DT.divide_factor_l.\n          unfold int_size. chunk_red; omega. \n          inv Hbound_limit.\n          unfold int_size in *. chunk_red; omega.\n\n          symmetry.\n          apply  pointer_ofs_no_overflow.\n          omega.\n          destruct Hbound_limit.\n          unfold int_size in *. \n          assert (Ptrofs.unsigned limit_ofs <= Ptrofs.max_unsigned)%Z by apply Ptrofs.unsigned_range_2.\n          \n          chunk_red; omega.\n\n          rewrite Ptrofs.add_assoc.\n          replace (Ptrofs.add (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr Z.one))\n                           (Ptrofs.repr (int_size * j))) with (Ptrofs.repr (int_size * (j + 1))). reflexivity.\n          rewrite int_z_mul.\n          rewrite int_z_add.\n          rewrite Zred_factor4.\n          rewrite Z.add_comm. reflexivity.\n          constructor. solve_uint_range.\n          constructor. unfold uval. chunk_red; archi_red; simpl; omega.\n          rewrite ptrofs_mu. chunk_red; archi_red; simpl; solve_uint_range. omega. omega.\n          solve_uint_range.\n          \n          destruct Hbound_limit.\n\n          \n          assert (gc_size <= Int.max_unsigned)%Z. unfold gc_size; unfold Int.max_unsigned; simpl; omega.\n          split. chunk_red; omega. \n          etransitivity. 2: apply ptrofs_mu_weak.\n          assert ((int_size * j <= int_size * Z.pos (Pos.of_succ_nat (length ys))))%Z.\n          apply OrdersEx.Z_as_OT.mul_le_mono_pos_l. chunk_red; omega. omega.\n          etransitivity.\n          eauto.\n          etransitivity. 2: eauto. etransitivity. 2:eauto.\n          etransitivity. 2: eauto.\n          do 2 (rewrite Zpos_P_of_succ_nat).\n          rewrite Nat2Z.inj_add.\n          rewrite Nat2Z.inj_succ.\n          rewrite <- Z.add_succ_l.\n          assert (0 <= (Z.succ (Z.of_nat (max_allocs e))))%Z.\n          assert (0 <= (Z.of_nat (max_allocs e)))%Z.  omega. omega.\n          rewrite Z.mul_add_distr_l. \n          chunk_red; archi_red; omega. \n          \n          chunk_red; archi_red; solve_uint_range; rewrite ptrofs_mu; archi_red; solve_uint_range; unfold Z.one; omega.\n        }\n        specialize (Hstep_m3 Htemp H2). clear Htemp.\n        \n        (* first prove that allocIdent \\/ x is disjoint from ys s.t. can be ignore. then show that get_list works and that vs7 is the right thing  *)\n        assert (Htemp : exists vs : list Values.val,\n             Forall2\n               (get_var_or_funvar p\n                  (Maps.PTree.set allocIdent\n                     (Vptr alloc_b\n                        (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr (Z.of_N (a + 1))))))\n                     (Maps.PTree.set x\n                        (Vptr alloc_b (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr Z.one))))\n                        lenv))) ys vs).\n        {\n          assert (exists vs, get_var_or_funvar_list p lenv ys = Some vs).          \n          {\n            \n            inv Hrel_m.  destruct H4.\n            eapply exists_getvar_or_funvar_list.\n            2:{  eauto. }\n            intros.\n            apply H5. constructor. auto.\n          } \n          destruct H4 as [x0 Hgv_x0].\n          exists x0.\n          rewrite get_var_or_funvar_list_correct.\n          rewrite <- get_var_or_funvar_list_set.\n          rewrite <- get_var_or_funvar_list_set.\n          auto.\n\n          intro.\n          eassert (Hxrho := get_list_In _ _ _ _ H H4).\n          destruct Hxrho as [vv Hxrho].\n          eapply Hrho_id; eauto.\n          \n          \n          intro.\n          inv Hp_id.\n          \n          assert (Hgl := get_list_In _ _ _ _ H H4). destruct Hgl.          \n          specialize (H5 _ allocIdent _ H8). apply H5.\n          right. \n          left. auto. left; auto.          \n        } \n        destruct Htemp as [vs7 Hvs7].\n        specialize (Hstep_m3 vs7 Hvs7).\n        destruct Hstep_m3 as [m3 Hstep_m3].\n        assert (H_m2_m3 :  mem_after_n_proj_store alloc_b\n                                                       (Ptrofs.unsigned (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr Z.one)))) vs7 0 m2 m3). {\n          apply mem_after_n_proj_wo_cast.\n          destruct Hstep_m3; auto.\n          apply Ptrofs.unsigned_range. reflexivity.\n          inv Hc_alloc.\n          int_red. simpl max_allocs in Hbound_limit. destruct ys. destruct Ha_l. exfalso. auto.\n          rewrite Nat2Z.inj_succ in Hbound_limit.\n          rewrite Nat2Z.inj_add in Hbound_limit.\n\n          split.\n          apply Z.add_nonneg_nonneg.\n          apply Ptrofs.unsigned_range.\n          assert (0 <= Z.of_nat (length vs7))%Z by apply Zle_0_nat. chunk_red; omega.\n          apply Forall2_length' in Hvs7.\n          rewrite <- Hvs7 in *.\n          inv Hbound_limit.          \n          rewrite int_z_mul. \n          unfold Ptrofs.add.\n          rewrite Ptrofs.unsigned_repr with (z := (sizeof (globalenv p) uval * Z.one)%Z).\n          rewrite Ptrofs.unsigned_repr.\n\n          unfold Z.one.\n          rewrite Z.mul_succ_r in H4.\n          \n\n          \n          assert (Ptrofs.unsigned alloc_ofs + sizeof (globalenv p) uval * 1 +  size_chunk int_chunk * (0 + Z.of_nat (length (v0 :: ys))) <= Ptrofs.unsigned alloc_ofs + (Ptrofs.unsigned limit_ofs - Ptrofs.unsigned alloc_ofs))%Z. chunk_red; unfold sizeof; archi_red; omega. etransitivity. eauto.\n          rewrite Zplus_minus. apply Ptrofs.unsigned_range_2.\n          unfold Z.one.\n          rewrite Z.mul_succ_r in H4.\n          assert (0 <= Ptrofs.unsigned alloc_ofs)%Z by apply Ptrofs.unsigned_range_2. split. chunk_red; unfold sizeof; archi_red; omega.  \n          assert (Ptrofs.unsigned alloc_ofs +  sizeof (globalenv p) uval * 1 <= Ptrofs.unsigned alloc_ofs + ( Ptrofs.unsigned limit_ofs - Ptrofs.unsigned alloc_ofs))%Z by (chunk_red; unfold sizeof; archi_red; omega). \n          etransitivity. eauto.\n          rewrite Zplus_minus. apply Ptrofs.unsigned_range_2.\n\n          unfold Z.one; rewrite ptrofs_mu.  chunk_red; unfold sizeof; archi_red; solve_uint_range; omega.  \n          simpl sizeof. unfold Z.one. chunk_red; unfold sizeof; solve_uint_range; rewrite ptrofs_mu; archi_red; solve_uint_range; omega.  \n          destruct Hstep_m3.\n          auto.\n        }          \n        assert (H_ug1 :unchanged_globals p m m2). {\n          intro. \n          intros. symmetry.\n          eapply Mem.load_store_other.\n          eauto.\n          left.\n          inv Hrel_m. destructAll. inv H5. destructAll.\n          apply H19 in H4. destructAll. rewrite H5 in Hget_alloc; inv Hget_alloc. auto.\n        }\n        assert (H_ug2 : unchanged_globals p m2 m3). {\n          inv Hrel_m. destructAll. inv H4. \n          destructAll.\n          eapply mem_after_n_proj_store_globals_unchanged. eauto.\n          intros.\n          apply H18 in H19. rewrite H4 in Hget_alloc; inv Hget_alloc. destructAll; auto.\n        }\n        \n\n         \n        do 2 eexists.\n        split.\n        eapply t_trans.\n        \n        apply Hstep_m2.\n        apply Hstep_m3.\n        split.\n        { (* rel_mem after adding the new constructor *)\n          inversion Hrel_m as [L [Hrel_pL Hrel_mL]].\n          assert (Hbound_max:\n                    (Ptrofs.unsigned alloc_ofs + int_size * (Z.succ (Z.of_nat (max_allocs e)) + Z.of_N a) <= Ptrofs.unsigned limit_ofs)%Z). {\n            inv Hc_alloc. \n            simpl max_allocs in Hbound_limit.\n            destruct ys. exfalso.\n            destruct Ha_l. auto. \n            \n            rewrite Nat2Z.inj_succ in Hbound_limit.\n            rewrite Nat2Z.inj_add in Hbound_limit.\n            destruct Ha_l. \n            \n            replace (Z.of_N a) with (Z.of_nat (length (v0 :: ys))). \n            rewrite  Z.add_succ_l.\n            destruct Hbound_limit.\n            omega.\n            rewrite H4. rewrite nat_N_Z. reflexivity.            \n          }\n          assert (H_unchanged_m2_m3: Mem.unchanged_on L m2 m3). {                          \n            inv Hrel_pL.\n            destructAll.\n            rewrite H4 in Hget_alloc. inv Hget_alloc.\n\n            eapply mem_after_n_proj_store_unchanged.\n            eauto.            \n            intros. \n            apply H12.\n            simpl max_allocs in *.\n            apply Forall2_length' in Hvs7. \n            rewrite <- Hvs7 in *.\n            clear Hvs7.\n\n            destruct ys.\n            exfalso; auto.\n            rewrite Hget_limit in H13; inv H13.\n            \n            \n            simpl length in H8. unfold int_size in *; simpl size_chunk in *.\n            simpl sizeof in *.\n            simpl length in Hbound_max.\n            rewrite int_z_mul in H8.\n            rewrite pointer_ofs_no_overflow in H8.\n            inv Hc_alloc. simpl max_allocs in H10.\n            rewrite Nat2Z.inj_succ in *.\n            unfold int_size in *;  simpl size_chunk in *.\n            unfold Z.one in *. split. chunk_red; omega.\n            inv H8. \n            eapply OrdersEx.Z_as_OT.lt_le_trans; eauto.\n            rewrite Nat2Z.inj_add in H10.\n            rewrite Z.mul_succ_r in H10.\n            assert (0 <= Z.of_nat (max_allocs e))%Z by apply Zle_0_nat.\n            rewrite <- OrdersEx.Z_as_DT.le_add_le_sub_l in H10.\n            etransitivity. 2: apply H10.\n            rewrite Nat2Z.inj_succ.\n            \n            rewrite Z.add_0_l.\n            rewrite Z.mul_add_distr_l.            \n            repeat (rewrite Z.mul_succ_r).\n            repeat rewrite Z.add_assoc.\n            rewrite Z.add_comm with (m := (size_chunk int_chunk * Z.of_nat (max_allocs e))%Z).\n            repeat rewrite <- Z.add_assoc.\n            apply Z_non_neg_add.\n            assert (Ptrofs.unsigned alloc_ofs + (size_chunk int_chunk * 1 + ((size_chunk int_chunk) * Z.of_nat (length ys) + (size_chunk int_chunk))) <= (Ptrofs.unsigned alloc_ofs + ((size_chunk int_chunk) * Z.of_nat (length ys) + ((size_chunk int_chunk) + (size_chunk int_chunk)))))%Z. chunk_red; omega. etransitivity. eauto. reflexivity. chunk_red; omega.\n            unfold Z.one; omega.\n            inv Hc_alloc. simpl max_allocs in H10.\n            rewrite Nat2Z.inj_succ in H10. \n            rewrite <- Z.le_add_le_sub_l in H10.            \n            etransitivity.\n            etransitivity.\n            2: apply H10.\n            unfold Z.one. rewrite Nat2Z.inj_add.\n            rewrite Nat2Z.inj_succ. chunk_red; omega.\n            apply Ptrofs.unsigned_range_2.\n            \n            unfold Z.one.\n            solve_uint_range; rewrite ptrofs_mu; chunk_red; archi_red; solve_uint_range; omega.\n\n          } \n          assert (H_unchanged_m_m3:   Mem.unchanged_on L m m3). {\n             \n            inv Hrel_pL.\n            destructAll.\n            rewrite H4 in Hget_alloc. inv Hget_alloc.\n\n            eapply Mem.unchanged_on_trans.\n            eapply Mem.store_unchanged_on.\n \n            eauto.\n            intros.\n            apply H12.\n            inv H8.\n            split; auto.\n            rewrite H13 in Hget_limit; inv Hget_limit.\n            eapply OrdersEx.Z_as_OT.lt_le_trans. eauto.\n            rewrite <- Z.le_add_le_sub_l in H10.            \n            etransitivity; eauto.\n            apply Zplus_le_compat_l.\n            rewrite Z.mul_add_distr_l.  \n            rewrite Z.mul_succ_r. repeat rewrite  Z.add_assoc.\n            rewrite OrdersEx.Z_as_OT.add_shuffle0.\n            apply Z_non_neg_add.\n            reflexivity.\n            rewrite nat_N_Z.\n            chunk_red; omega.\n            auto. \n              }\n          \n          exists (bind_n_after_ptr (Z.of_N (a+1) * int_size) alloc_b (Ptrofs.unsigned alloc_ofs)  L).\n          split.\n          - (* protected okay since only took the space from Econstr to e *)\n            exists alloc_b, (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr (Z.of_N (a + 1))))),\n            limit_ofs, args_b, args_ofs, tinf_b, tinf_ofs.\n            assert (H_dj := disjointIdent).            \n            repeat split.  \n            + rewrite M.gss. reflexivity.\n            + intros.\n              inv Hrel_pL.\n              destructAll.\n              inv Hc_alloc.\n              destruct ys. exfalso; auto.\n              simpl max_allocs in *.\n              int_red. \n              rewrite Nat2Z.inj_succ in H12. \n              rewrite Nat2Z.inj_add in H12. \n              rewrite H5 in Hget_alloc. inv Hget_alloc.\n              rewrite H15 in Hget_limit. inv Hget_limit.\n              intro.\n              apply bind_n_after_ptr_def in H10.\n              rewrite Ptrofs.add_unsigned with (x := alloc_ofs) in * .\n              replace (Ptrofs.unsigned\n                         (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr (Z.of_N (N.of_nat (@length var (v0 :: ys)) + 1))))) with\n                  ((size_chunk int_chunk) * Z.of_nat (length (v0 :: ys)) + (size_chunk int_chunk))%Z in *.\n              unfold Ptrofs.add in H6.                     \n              replace  (Ptrofs.unsigned (Ptrofs.repr ((size_chunk int_chunk) * Z.of_nat (max_allocs e)))) with\n                  ((size_chunk int_chunk) * Z.of_nat (max_allocs e))%Z in *.                            \n              replace (Ptrofs.unsigned (Ptrofs.repr (Ptrofs.unsigned alloc_ofs + ((size_chunk int_chunk) * Z.of_nat (length (v0 :: ys)) + (size_chunk int_chunk))))) with\n                  (Ptrofs.unsigned alloc_ofs + ((size_chunk int_chunk) * Z.of_nat (length (v0 :: ys)) + (size_chunk int_chunk)))%Z in *.\n              inv H10.\n              * revert H21.\n                eapply H14.\n                split; auto.\n                etransitivity; eauto; chunk_red; omega.\n              * inv H21.\n                \n                rewrite N2Z.inj_add in H22.\n                rewrite nat_N_Z in H22.\n                simpl Z.of_N in *.\n                chunk_red; omega.\n                 \n              * assert (0 <= Ptrofs.unsigned alloc_ofs)%Z by apply Ptrofs.unsigned_range. \n                rewrite Ptrofs.unsigned_repr. reflexivity.\n                split. chunk_red; omega.\n                rewrite <- Z.le_add_le_sub_l in H12.    \n                etransitivity. etransitivity.\n                2: apply H12.\n                rewrite Z.mul_succ_r.\n                simpl length. \n                chunk_red; omega.\n                apply Ptrofs.unsigned_range_2.\n              * rewrite Ptrofs.unsigned_repr. reflexivity.\n                split. chunk_red; omega.\n                rewrite <- Z.le_add_le_sub_l in H12.    \n                etransitivity. etransitivity.\n                2: apply H12.\n                rewrite Nat2Z.inj_succ.\n                rewrite Z.mul_succ_r.\n                assert (0 <= Ptrofs.unsigned alloc_ofs)%Z by apply Ptrofs.unsigned_range.                \n                chunk_red; omega.\n                apply Ptrofs.unsigned_range_2.\n              * simpl sizeof.\n                unfold Ptrofs.mul.\n                rewrite Ptrofs.unsigned_repr with (z :=  (Z.of_N (N.of_nat (length (v0 :: ys)) + 1))).\n                rewrite Ptrofs.unsigned_repr with (z := (sizeof (prog_comp_env p) uval)).\n                rewrite Ptrofs.unsigned_repr. reflexivity.\n                split. apply Z.mul_nonneg_nonneg. unfold sizeof. chunk_red; archi_red; omega. \n                apply N2Z.is_nonneg.\n                rewrite <- Z.le_add_le_sub_l in H12.    \n                etransitivity. etransitivity. 2: apply H12.  simpl length.\n                assert (0 <= Ptrofs.unsigned alloc_ofs)%Z by apply Ptrofs.unsigned_range.\n                rewrite Z.mul_succ_r.\n                rewrite N2Z.inj_add.\n                rewrite nat_N_Z.\n                simpl Z.of_N.\n                rewrite Z.mul_add_distr_l.\n                rewrite Z.mul_add_distr_l. unfold sizeof. chunk_red; archi_red; omega.\n                apply Ptrofs.unsigned_range_2.\n                rewrite ptrofs_mu. \n                unfold sizeof; chunk_red; archi_red; solve_uint_range; omega. \n                rewrite N2Z.inj_add.\n                rewrite nat_N_Z.\n                simpl Z.of_N.\n                split.\n                apply Z_non_neg_add. omega. omega.\n                rewrite <- Z.le_add_le_sub_l in H12.    \n                etransitivity. etransitivity. 2: apply H12. \n                simpl length.\n                rewrite Z.mul_succ_r.\n                assert (0 <= Ptrofs.unsigned alloc_ofs)%Z by apply Ptrofs.unsigned_range.\n                chunk_red; omega.\n                apply Ptrofs.unsigned_range_2.\n            + rewrite M.gso. rewrite M.gso.\n              auto.\n              intro.\n              apply H3.\n              subst. rewrite <- H4. inList. \n              intro. inv H_dj. rewrite <- H4 in *.\n              inv H9.\n              apply H10. constructor; auto. \n            + rewrite M.gso. rewrite M.gso.\n              auto. intro.\n              apply H3. rewrite <- H4.  inList.\n              intro; inv H_dj. apply H8. left. auto.\n            + intros.\n              inv Hrel_pL.\n              destructAll. \n              rewrite H18 in Hget_args; inv Hget_args.\n              intro.\n              apply bind_n_after_ptr_def in H12. inv H12.\n              revert H23. apply H19 with (z := z); auto.\n              destruct H23.\n              apply Hdj_args.\n              auto.\n            + rewrite M.gso. rewrite M.gso.\n              eauto. intro. apply H3.  unfold is_protected_id_thm; subst; inList.\n              intro. inv H_dj. inversion H9. apply H10. inList.\n            + intros; inv Hrel_pL; destructAll.\n              rewrite H16 in Htinf1; inv Htinf1.\n(*              apply H15 in H4. destructAll.  *)\n              specialize (H17 i). intro.\n              (* either b i is in L OR b = alloc_b  -> FALSE *)\n              apply bind_n_after_ptr_def in H8.               inv H8.\n              apply H17; auto.\n              destruct H19. subst. rewrite H4 in Hget_alloc; inv Hget_alloc. apply Htinf3; reflexivity.\n            + intros; inv Hrel_pL; destructAll.\n              apply H19 in H4. rewrite H15 in Hget_args; inv Hget_args.\n              destructAll; auto.\n            + intros; inv Hrel_pL; destructAll.\n              apply H19 in H4. rewrite H5 in Hget_alloc; inv Hget_alloc.\n              destructAll; auto.\n            + intros; inv Hrel_pL; destructAll.\n              apply H19 in H4. destructAll.\n              intro. apply bind_n_after_ptr_def in H21.\n              inv H21.\n              eapply H20; eauto.\n              rewrite H5 in Hget_alloc; inv Hget_alloc.\n              inv H22. apply H9; auto. \n          - intros. destruct (var_dec x0 x).\n                 + (* x0 = x *)\n                   subst. split.\n                   2:{ \n                     intros. rewrite M.gss in H4. inv H4.\n                     apply subval_or_eq_fun in H5. destruct H5. destruct H4.\n                     assert (Hy0x0 := get_list_In_val _ _ _ _ H H5).\n                     destruct Hy0x0 as [y0 [Hy0In Hy0x0]].\n                     specialize (Hrel_mL y0). \n                     destruct Hrel_mL as [Hrem_mL Hrel_mL'].\n                     specialize (Hrel_mL' _ _ _ _ Hy0x0 H4).\n                     destruct Hrel_mL' as [Hrel_mL' [Hrel_closed Hrel_f]]. split.\n                     eapply repr_val_id_L_sub_locProp.\n                     eapply repr_val_id_L_unchanged.                     \n                     2: eauto.\n                     2:{ intro. intro. intro. apply bind_n_after_ptr_def. left; auto. }\n                     apply repr_val_id_set. apply repr_val_id_set.\n                     auto.\n                     (* unique binding env should take care of this one? ...also since function not bound, but Hrel_mL'...*)\n                     intro; subst. inv Hrho_id.\n                     inv Hf_id.\n                     assert (bound_var (Econstr x t ys e) x) by constructor.\n                     apply H9 in H11.\n                     inv Hrel_mL'. rewrite H19 in H11. inv H11. \n                     inv H14. rewrite H22 in H11. inv H11.\n\n                     (* since fds includes f *)\n                     intro. inv Hp_id. eapply H8.\n                     apply Hy0x0.\n                     right. left. reflexivity.\n                     right.\n                     eapply bound_var_subval; eauto.\n                     inv Hrel_mL'.\n                     inv H17.\n                     constructor.\n                     apply name_in_fundefs_bound_var_fundefs.\n                     eapply find_def_name_in_fundefs. eauto.\n                     inv H11. rewrite H19 in H6. inv H6. split. auto.\n                     \n                     eapply correct_fundefs_unchanged_global with (m := m2).\n                     eapply correct_fundefs_unchanged_global with (m := m).\n                     apply Hrel_f.\n                     auto.\n                     auto. }\n                     \n                   intros. eexists. split.\n                   rewrite M.gss. reflexivity.\n                   eapply RVid_V.\n                   apply Hf_id. constructor. (* x is not global *)\n                   rewrite M.gso. rewrite M.gss. reflexivity.\n                   intro. apply H3. subst. inList.\n                   eapply RSconstr_boxed_v.\n                   *  eauto.\n                   *  rewrite Ptrofs.sub_add_opp.                 \n                      rewrite Ptrofs.mul_one. \n                      rewrite Ptrofs.add_assoc.\n                      rewrite Ptrofs.add_neg_zero.\n                      rewrite Ptrofs.add_zero. intros.\n                      rewrite bind_n_after_ptr_def. right. split; auto.\n                      simpl size_chunk in *.\n                      rewrite N2Z.inj_add.\n                      simpl Z.of_N.\n                      rewrite Z.mul_add_distr_r.\n                      rewrite Z.add_assoc.\n                      simpl Z.mul.\n                      assert (0 <=  Z.of_N a)%Z by apply N2Z.is_nonneg. \n                      chunk_red; omega.\n                   * (* skip m3, (repr H) is what is stored for m2 *)\n                     rewrite Ptrofs.sub_add_opp.\n                     rewrite Ptrofs.mul_one. \n                     rewrite Ptrofs.add_assoc.\n                     rewrite Ptrofs.add_neg_zero.\n                     rewrite Ptrofs.add_zero.\n                     destruct Hstep_m3 as [Hstep_m3_s Hstep_m3_mem].\n                     apply Mem.load_store_same in Hm2. simpl in Hm2.\n                     erewrite mem_after_n_proj_store_load.\n                     apply Hm2.\n                     apply H_m2_m3.\n                     right. left.\n                     simpl.\n                     rewrite Ptrofs.mul_one.\n                     unfold Ptrofs.add.\n                     rewrite Ptrofs.unsigned_repr with (z := (sizeof (prog_comp_env p) uval)). \n                     rewrite Ptrofs.unsigned_repr.                     \n                     unfold sizeof; unfold int_size; chunk_red; archi_red; omega.\n                     split.\n                     apply Z_non_neg_add.\n                     unfold sizeof; chunk_red; archi_red; omega. apply Ptrofs.unsigned_range.\n                     destruct Hbound_limit.\n                     rewrite <- Z.le_add_le_sub_l in H5.    \n                     etransitivity. etransitivity.\n                     2: apply H5. \n                     inv Hc_alloc. simpl max_allocs.\n                     destruct ys.  inv Ha_l. exfalso; auto.\n                     rewrite Nat2Z.inj_succ.\n                     rewrite Z.mul_succ_r.\n                     int_red.\n                     assert (0 <=  Z.of_nat (max_allocs e + length (v0 :: ys))%nat)%Z by       apply Zle_0_nat.\n                     unfold sizeof; chunk_red; archi_red; omega.\n                     apply Ptrofs.unsigned_range_2.\n                     rewrite ptrofs_mu.\n                     unfold sizeof; chunk_red; archi_red; solve_uint_range; omega.\n                   * \n                     auto.\n\n                   * (* todo: theorem linking repr_val_ptr_list and mem_after_n_proj_store *)\n                     (* need to clear a few things here before inducting on vs *)\n                     { clear IHHev.\n                       assert (H_alloc4 :(Ptrofs.unsigned (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr Z.one)))\n                                          = (Ptrofs.unsigned alloc_ofs) + int_size)%Z).\n                       {\n                         \n                         rewrite Ptrofs.mul_one.\n                         rewrite Ptrofs.add_unsigned.\n                         rewrite Ptrofs.unsigned_repr with (z := (sizeof (globalenv p) uval)).\n                         rewrite Ptrofs.unsigned_repr. auto.\n                         inv Hc_alloc.\n                         split. apply OrdersEx.Z_as_OT.add_nonneg_nonneg. apply Ptrofs.unsigned_range.  unfold sizeof; chunk_red; archi_red; omega. \n                    inv Hbound_limit.\n                    rewrite <- Z.le_add_le_sub_l in H5.  \n                    etransitivity. etransitivity. 2: apply H5. unfold int_size in *. 2: eapply Ptrofs.unsigned_range_2. \n                    simpl max_allocs. destruct ys. exfalso. apply Ha_l. auto.\n                    rewrite Nat2Z.inj_succ.\n                    rewrite Z.mul_succ_r.\n                    rewrite Z.add_assoc. unfold int_size; simpl size_chunk.\n                    assert (0 <=  Ptrofs.unsigned alloc_ofs)%Z.\n                    apply Ptrofs.unsigned_range.\n                    assert (0 <= Z.of_nat (max_allocs e + length (v0 :: ys)))%Z by \n                    apply Zle_0_nat.\n                    unfold sizeof; chunk_red; archi_red; omega.\n                    rewrite ptrofs_mu.\n                    unfold sizeof; chunk_red; archi_red; solve_uint_range; omega. \n                  }                    \n                  \n\n\n                    \n                  rewrite repr_val_ptr_list_Z.\n                  2:{ \n                  rewrite H_alloc4. \n                    unfold int_size in *; simpl size_chunk in *.\n                    inv Hc_alloc.\n                    split. apply OrdersEx.Z_as_OT.add_nonneg_nonneg. apply OrdersEx.Z_as_OT.add_nonneg_nonneg.\n                    apply Ptrofs.unsigned_range. chunk_red; omega.  chunk_red; omega.\n                    inv Hbound_limit.\n                    rewrite <- Z.le_add_le_sub_l in H5. \n                    etransitivity. etransitivity. 2: apply H5. 2: apply Ptrofs.unsigned_range_2. \n                    simpl max_allocs.\n                    apply get_list_length_eq in H. \n                    destruct ys. exfalso. apply Ha_l. auto.\n                    rewrite Nat2Z.inj_succ.\n                    rewrite Nat2Z.inj_add.\n                    simpl length.\n                    simpl in H. rewrite <- H.                    \n                    rewrite Nat2Z.inj_succ.\n                    rewrite Nat2Z.inj_succ.\n                    assert (0 <=  Ptrofs.unsigned alloc_ofs)%Z by apply Ptrofs.unsigned_range.                    \n                    rewrite Z.mul_succ_r.\n                    rewrite Z.mul_add_distr_l.\n                    rewrite Z.mul_succ_r.\n                    rewrite Z.add_assoc.\n                    assert (0 <= (Z.of_nat (length ys)))%Z by                     apply Zle_0_nat.\n                    assert (0 <= (Z.of_nat (max_allocs e)))%Z by                     apply Zle_0_nat.\n                    rewrite Z.mul_succ_l.\n                    rewrite <- Z.add_assoc.\n                    rewrite <- Z.add_assoc.\n                    apply Zplus_le_compat_l.\n                    rewrite Z.add_comm.\n                    rewrite Z.add_assoc.\n                    rewrite Z.mul_comm.\n                    rewrite <- Z.add_0_l at 1.\n                    replace  (int_size * Z.of_nat (max_allocs e) + int_size * Z.of_nat (length ys) + int_size + int_size)%Z with  (int_size * Z.of_nat (max_allocs e) + ( int_size * Z.of_nat (length ys) + int_size + int_size))%Z by omega.\n                    \n                    rewrite Z.add_0_l; \n                    apply Z.add_le_mono; [ | omega];\n                    apply Z.add_le_mono; [ | omega];\n                    rewrite <- Z.add_0_l at 1;\n                    apply Z.add_le_mono_r; chunk_red; omega. }\n                    \n                    (* done *)\n\n                    \n                    rewrite H_alloc4.\n                    rewrite H_alloc4 in H_m2_m3.\n                  clear H_alloc4.\n\n                  \n\n\n                  \n\n                  \n                  \n                  (* creating an intermediate memory representing the work done so far, with equality that will be cleared before induction *)\n                  assert (H_mmid: exists m_mid vs1 vs2, mem_after_n_proj_snoc alloc_b (Ptrofs.unsigned alloc_ofs + int_size) vs1 m2 m_mid /\\\n                                                        (rev (vs1) ++ vs2 = vs7) /\\ vs7 = vs2 /\\ vs1 = [] /\\  m2 = m_mid). {\n                    \n                    exists m2, [], vs7. split. constructor.\n                    auto.\n                  }\n                  destruct H_mmid as [m_mid [vs1 [vs2 [H_m2_mmid [H_rev_vs7 [H_eq_vs7 [H_eq_vs1 H_eq_m2]]]]]]].\n                  rewrite H_eq_vs7 in H_m2_m3.\n                  rewrite H_eq_m2 in H_m2_m3.\n                  rewrite H_eq_vs7 in Hvs7.\n                  replace 0%Z with (Z.of_nat (length vs1)) in H_m2_m3 by (rewrite H_eq_vs1; auto).\n                  \n                  \n                  \n\n                  \n\n\n                  \n                  (* IH needs to walk on the total (a) size of ys *)\n                  assert (Hays: (Z.of_N a - Z.of_nat (length ys) = 0)%Z).\n                  destruct Ha_l; subst. rewrite nat_N_Z.\n                  omega.\n\n\n                  replace (Ptrofs.unsigned alloc_ofs + int_size)%Z with  (Ptrofs.unsigned alloc_ofs + int_size + int_size * Z.of_nat (length vs1))%Z by (rewrite H_eq_vs1; simpl; omega).\n                  \n                  assert (Hrel_pL' := Hrel_pL).\n(*   Not needed w/o maxalloc in pniL\n               assert (Hrel_pL' :  protected_not_in_L argsIdent allocIdent limitIdent tinfIdent p lenv (Z.succ (Z.of_nat (max_allocs e)) + Z.of_nat (length vs7) )%Z L). {                                        \n                    simpl in Hrel_pL. destruct ys. exfalso; destruct Ha_l. apply H6; auto.\n                    rewrite Nat2Z.inj_succ in Hrel_pL.\n                    rewrite Nat2Z.inj_add in Hrel_pL.\n                    replace (Z.of_nat (length vs7)) with (Z.of_nat (length (v0 :: ys))).\n                    rewrite  Z.add_succ_l. auto.\n                    rewrite H_eq_vs7.\n                    apply Forall2_length' in Hvs7. rewrite <- Hvs7; auto.\n                    \n                  } *)\n                  assert (forall y, List.In y ys -> \n                                    exists v6 : cps.val,\n              M.get y rho = Some v6 /\\\n              repr_val_id_L_LambdaANF_Codegen argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam fenv\n                                  finfo_env p rep_env v6 m L lenv y).  \n                  intros. apply Hrel_mL. constructor. auto.\n \n                  (* replacing bind_n_after_ptr to something easier to induct on *)\n                  assert (Hll' := bind_n_after_ptr_exists  (length vs2) alloc_b (Ptrofs.unsigned alloc_ofs + int_size + int_size * Z.of_nat (length vs1)) L). \n                  destruct Hll' as [L' [H_ll' H_eql']].\n                  eapply  repr_val_ptr_list_L_Z_sub_locProp with (L := L'); auto.\n                  2:{                   \n                  intro. intro. intro. apply bind_n_after_ptr_def.\n                  rewrite <- H_eql' in H6.\n                  apply bind_n_after_ptr_def in H6.\n                  inv H6. auto.\n                  destruct H8. right. split. auto.\n                  split. chunk_red; omega.\n                  rewrite N2Z.inj_add.\n                  replace (Z.of_N a) with (Z.of_nat (length ys)) by omega.\n                  replace (length ys) with (length vs2). int_red. simpl in H8. simpl Z.of_N. chunk_red; omega.\n                  apply Forall2_length' in Hvs7. auto. }\n\n                  (* current locprop, from L + 1 to L + 1 + length vs *)\n                  assert (H_ll'':= bind_n_after_ptr_exists' (length vs1) alloc_b  (Ptrofs.unsigned alloc_ofs + int_size) L).\n                  destruct H_ll'' as [L'' H_ll''].\n\n                  assert (H_not_in_L:\n                            (forall j:Z,\n                                (Ptrofs.unsigned alloc_ofs  <= j <\n                                 Ptrofs.unsigned alloc_ofs + int_size + int_size  * (Z.of_nat (length vs7)))%Z -> ~ L alloc_b j)).\n                  {\n                    inv Hrel_pL. destructAll. rewrite H6 in Hget_alloc. inv Hget_alloc.\n                    intros.\n                    apply H14.\n                    \n                    simpl max_allocs. destruct ys. exfalso; auto. rewrite H15 in Hget_limit. inv Hget_limit.\n                    destruct H10. split; auto.\n                    eapply OrdersEx.Z_as_OT.lt_le_trans.\n                    eauto.\n                    \n                    etransitivity.\n                    2: apply Hbound_max. rewrite H_eq_vs7.                    \n                    int_red.\n                    apply Forall2_length' in Hvs7. replace (@length var (@cons var v0 ys)) with (@length Values.val vs2).\n                    rewrite Z.mul_add_distr_l.\n                    rewrite Z.mul_succ_r.\n                    rewrite nat_N_Z. \n                    chunk_red; omega.\n                  }                  \n                  assert (H_u_mmid_m3: Mem.unchanged_on L'' m_mid m3). {                    \n                    eapply mem_after_n_proj_store_unchanged. eauto. \n                    intros; intro.\n                    eapply bind_n_after_ptr_from_rev in H_ll''. rewrite <- H_ll'' in H8.                    \n                    rewrite bind_n_after_ptr_def in H8.\n                    destruct H8.\n                    - (* L alloc_b j is protected *)\n                      revert H8. apply H_not_in_L. subst. simpl length in *. int_red. simpl Z.of_nat in *.  chunk_red; omega.\n                      \n                    - (* j is both in and after vs1 so impossible *)\n                      int_red. chunk_red; omega.\n                    }\n                   \n                  clear H_eql'.\n                   \n                  rewrite get_var_or_funvar_list_correct in Hvs7. rewrite <- get_var_or_funvar_list_set in Hvs7.\n                  rewrite <- get_var_or_funvar_list_set in Hvs7.\n                  2:{  intro.\n                  assert (Hxrho := get_list_In _ _ _ _ H H6).\n                  destruct Hxrho as [vv Hxrho].\n                  eapply Hrho_id; eauto. }\n                  2:{  intro.\n                  inv Hp_id.\n                  \n                  eapply get_list_In in H; eauto. \n                  destruct H. \n                  eapply H8. apply H.\n                  right. \n                  left. reflexivity.\n                  left. reflexivity. }\n                  rewrite <- get_var_or_funvar_list_correct in Hvs7. \n                    \n                  clear Hrel_mL.\n                  clear Hev.  clear Hc_env. revert H. clear Hp_id. clear Hf_id. revert H5.  clear Hrel_m. clear Hc_alloc.\n                  clear H2. \n                  clear H1.  clear H0.   clear Hstep_m2.  destruct Hstep_m3 as [Htemp Hm3]. clear Htemp.\n\n                  \n\n                   \n                  clear Hm3.\n                  revert H_m2_m3.\n                  revert H_m2_mmid.\n                  revert H_rev_vs7.\n\n                  \n                  revert H_ll'. revert L'.\n                  revert H_ll''. revert H_u_mmid_m3. revert L''.\n                  revert Hvs7.\n                  clear Hrel_pL.\n                  clear Hays.\n\n                  clear Hrho_id.\n                  clear Ha_l.\n                  revert ys.\n\n\n                  clear H_eq_vs7. clear H_eq_vs1. clear H_eq_m2.\n                  revert m_mid.\n                  revert vs1. revert vs2.\n                  \n                  induction vs. constructor.\n                   intros.\n                  apply get_list_cons in H. destruct H as [y [ys' [H_ys [Hyrho Hget_ys']]]].\n                  subst.\n                  inv Hvs7.\n\n                  assert (H_repr_a0: repr_val_L_LambdaANF_Codegen_id fenv finfo_env p rep_env a0 m3 L'  (Val.load_result int_chunk y0)). {\n                    assert (List.In y (y::ys')) by (constructor; auto). apply H5 in H. destructAll.\n                    rewrite H in Hyrho. inv Hyrho.  inv H1.\n                    inv H8. rewrite H9 in H1; inv H1.\n                    - (* fun *)\n                      eapply repr_val_L_sub_locProp.\n                      2:{  intro.  intros. eapply bind_n_after_ptr_from_rev in H_ll'. rewrite <- H_ll'.\n                      apply bind_n_after_ptr_def. left. apply H1. }\n                      eapply repr_val_L_unchanged; eauto.\n                    - (* constr *)\n                      rewrite load_ptr_or_int.\n                      rewrite H9 in H1.  inv H1.\n                      rewrite H9 in H1; inv H1.\n                    - \n                      eapply repr_val_L_sub_locProp.\n                      2:{ intro.  intros. eapply bind_n_after_ptr_from_rev in H_ll'. rewrite <- H_ll'.\n                      apply bind_n_after_ptr_def. left. apply H1. }\n                      eapply repr_val_L_unchanged; eauto.\n                      rewrite load_ptr_or_int by auto.\n                      inv H8. rewrite H1 in H9. inv H9.                      \n                      rewrite H10 in H12. inv H12. auto.\n                      \n                  }\n\n                  \n                   simpl length in H_ll'.\n                   inv H_ll'.  \n\n\n                   \n                   inv H_m2_m3.\n                  - (* vs2 = [a] last case *)\n                    inv H6. inv Hget_ys'. econstructor.\n                    + intros.\n                      right. split; auto.\n                    + int_red.\n                      eapply Mem.load_store_same. auto. apply H13.                      \n                    + auto.\n                    + constructor.\n                   - (* vs2 = a::vs2' IH *)\n                     \n                     assert (H_m2_m': mem_after_n_proj_snoc alloc_b (Ptrofs.unsigned alloc_ofs + int_size) (y0::vs1) m2 m') by (econstructor; eauto).\n                     assert (H_ll''_new:= bind_n_after_ptr_exists (length (y0::vs1)) alloc_b  (Ptrofs.unsigned alloc_ofs + int_size) L).\n                     destruct H_ll''_new as [L3 [H_ll3 H_ll3_def]].\n                     assert (H_unchanged_L3: Mem.unchanged_on L3 m' m3).\n                     {  eapply mem_after_n_proj_store_unchanged. apply H14.\n                       intros. intro. rewrite <- H_ll3_def in H2.\n                       rewrite bind_n_after_ptr_def in H2.\n                       destruct H2.\n                       * revert H2. apply H_not_in_L.\n                         int_red.\n                         rewrite app_length.\n                         rewrite rev_length.\n                         simpl length.\n                         rewrite Nat2Z.inj_add.\n                         rewrite Nat2Z.inj_succ. chunk_red; omega.                         \n                       * destruct H2. simpl length in H8.\n                         rewrite Nat2Z.inj_succ in H8. int_red. chunk_red; omega.\n                     }\n                     eapply IHvs in H_m2_m'; eauto.\n                     + econstructor.\n                       * intros. right. auto.\n                       * int_red. \n                         eapply Mem.load_unchanged_on.\n                         eauto.\n                         intros. rewrite <- H_ll3_def.\n                         rewrite bind_n_after_ptr_def. right. split; auto. simpl length.\n                         rewrite Nat2Z.inj_succ. int_red. chunk_red; omega.\n                         eapply Mem.load_store_same. apply H10. \n                       * (* this is from m3 unchanged m over L *)\n                         auto.\n                         \n                       *  eapply repr_val_ptr_list_L_Z_sub_locProp; auto. \n                          replace (Ptrofs.unsigned alloc_ofs + int_size + int_size * Z.of_nat (length vs1) + int_size)%Z\n                           with\n                             (Ptrofs.unsigned alloc_ofs + int_size + int_size * Z.of_nat (length (y0 :: vs1)))%Z.\n                         apply H_m2_m'. simpl length. rewrite Nat2Z.inj_succ.\n                         rewrite Z.mul_succ_r. int_red. omega. \n                         intro. intros. left. eauto. \n                     + simpl length. rewrite Nat2Z.inj_succ. rewrite Z.mul_succ_r. int_red. rewrite Z.add_assoc. eauto.\n                     + simpl. rewrite <- app_assoc. simpl. auto.\n                     + simpl length. rewrite Nat2Z.inj_succ. auto.\n                     + intros. apply H5. constructor 2. auto.\n                     }                     \n        (* \n\n get_list ys rho = Some vs ->\nForall2\n           (get_var_or_funvar p\n              (Maps.PTree.set allocIdent\n                 (Vptr alloc_b (Int.add alloc_ofs (Int.mul (Int.repr (sizeof (globalenv p) val)) (Int.repr (Z.of_N (a + 1))))))\n                 (Maps.PTree.set x\n                    (Vptr alloc_b (Int.add alloc_ofs (Int.mul (Int.repr (sizeof (globalenv p) val)) (Int.repr Z.one)))) lenv)))\n           ys vs7\n rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env (Econstr x t ys e) rho m lenv\n -> \n mem_after_n_proj_store_cast alloc_b\n               (Int.unsigned (Int.add alloc_ofs (Int.mul (Int.repr (sizeof (globalenv p) val)) (Int.repr Z.one)))) vs7 0 m2 m3\n ->\n  repr_val_ptr_list_L_LambdaANF_Codegen argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent isptrIdent caseIdent fenv finfo_env\n    p rep_env vs m3 (bind_n_after_ptr (Z.of_N (a + 1)) alloc_b (Int.unsigned alloc_ofs) L) alloc_b\n    (Int.add alloc_ofs (Int.mul (Int.repr (sizeof (globalenv p) val)) (Int.repr Z.one)))\n\n*)                                \n                 + (* x0 <> x*)\n                   {\n                     specialize (Hrel_mL x0).\n                     destruct Hrel_mL as [Hrel_mL Hrel_ml'].\n\n                     split.\n                     - intro.\n                       assert (occurs_free (Econstr x t ys e) x0).\n                       constructor 2; auto.\n                       specialize (Hrel_mL  H5).\n                       destruct Hrel_mL as [v6 [Hx0_v6 Hrepr_v6]].\n                       exists v6. split.\n                       rewrite M.gso; auto.\n                       apply repr_val_id_set.\n                       apply repr_val_id_set.\n                       eapply repr_val_id_L_sub_locProp with (L := L).\n                       eapply repr_val_id_L_unchanged. apply Hrepr_v6. auto.\n                       intro. intros.\n                       rewrite bind_n_after_ptr_def. auto.\n                       auto.\n                       inv Hp_id. \n                       intro. \n                       eapply H6. apply Hx0_v6.\n                       right. left. reflexivity. auto.\n                     -  intros. \n                        rewrite M.gso in H4 by auto. assert (H4' := H4).\n                        specialize (Hrel_ml' _ _ _ _ H4 H5). \n                        destruct Hrel_ml' as [Hrel_ml' [Hrel_closed Hrel_f]]. split.\n                        2: auto.\n                        apply repr_val_id_set.\n                        apply repr_val_id_set.\n                        eapply repr_val_id_L_sub_locProp with (L := L).\n                        eapply repr_val_id_L_unchanged. eauto.  auto.\n                        intro. intros.                        rewrite bind_n_after_ptr_def. auto.\n                        subst; auto.\n                        inv Hf_id.\n                        assert ( bound_var (Econstr x t ys e) x) by constructor. intro; subst.\n                        apply H6 in H9. inv Hrel_ml'.\n                        rewrite H17 in H9; inv H9.\n                        inv H12. rewrite H20 in H9. inv H9. \n                        intro. subst.\n                        \n                        inv Hp_id. eapply H6.  apply H4. right; left. reflexivity. right.\n                        eapply bound_var_subval; eauto.\n                        inv Hrel_ml'. inv H17. constructor.\n                        apply name_in_fundefs_bound_var_fundefs.\n                        eapply find_def_name_in_fundefs. eauto.\n                        inv H11. rewrite H19 in H9. inv H9. split. auto. \n                        eapply correct_fundefs_unchanged_global with (m := m2).\n                        eapply correct_fundefs_unchanged_global with (m := m).\n                        apply Hrel_f.\n                        auto.\n                        auto.\n                   }      }\n        { (* correct_tinfo after adding the constructor *)\n\n\n          assert (correct_tinfo p (Z.of_nat (max_allocs e))\n                                (Maps.PTree.set x (Vptr alloc_b (Ptrofs.add alloc_ofs (Ptrofs.mul (Ptrofs.repr (sizeof (globalenv p) val)) (Ptrofs.repr Z.one))))\n                                                lenv) m3).\n          \n          eapply correct_tinfo_not_protected.\n          eapply correct_tinfo_mono.                    \n          destruct Hstep_m3.          \n          eapply correct_tinfo_after_nstore.\n          \n          2: eauto.\n          \n          eapply correct_tinfo_after_store; eauto.\n          inv Hc_alloc.\n          simpl max_allocs. destruct ys. omega.\n          rewrite Nat2Z.inj_succ.\n          rewrite Nat2Z.inj_add.\n          omega.\n          intro; apply H3.\n          apply is_protected_tinfo_weak. auto.\n          {\n            inv Hp_id.\n            intro; subst; eapply H5.\n            2: constructor.\n            inList.\n          }\n          (* alloc is moved to an OK location *)\n          {\n\n            \n            \n            destruct H4 as [alloc_b' [alloc_ofs' [limit_ofs' [args_b' [args_ofs' [tinf_b' [tinf_ofs' [Hget_alloc' [Hdiv_alloc [Hrange_alloc' [Hget_limit' [Hbound_limit' [Hget_args' [Hdj_args' [Hbound_args' [Hrange_args' [Htinf1' [Htinf2' [Htinf3' [Hinf_limit' Htinf_deref']]]]]]]]]]]]]]]]]]]].\n            assert (alloc_b' = alloc_b /\\ alloc_ofs' = alloc_ofs).  rewrite M.gso in Hget_alloc'. rewrite Hget_alloc' in Hget_alloc. inv Hget_alloc. auto.             \n            intro.  apply H3. subst. rewrite <- H4. inList.\n            destruct H4; subst. \n            assert (args_b' = args_b /\\ args_ofs' = args_ofs).  rewrite M.gso in Hget_args'. rewrite Hget_args' in Hget_args. inv Hget_args. auto.            \n            intro.  apply H3. subst. rewrite <- H4; inList. \n            destruct H4; subst. \n            assert (limit_ofs = limit_ofs'). rewrite M.gso in Hget_limit'. rewrite Hget_limit' in Hget_limit. inv Hget_limit. auto.\n            intro.  apply H3. rewrite <- H4; inList.\n            subst.\n            assert (tinf_b' = tinf_b /\\ tinf_ofs' = tinf_ofs). rewrite M.gso in Htinf1'. rewrite Htinf1' in Htinf1; inv Htinf1; auto. intro. apply H3. subst. rewrite <- H4. inList. destruct H4; subst. split.\n            do 7 eexists. split.\n            rewrite M.gss. reflexivity.\n            split.\n            (* align *)\n            rewrite int_z_mul. \n            rewrite pointer_ofs_no_overflow.\n            apply Z.divide_add_r. auto.            \n            apply OrdersEx.Z_as_DT.divide_factor_l. apply N2Z.is_nonneg.\n            inv Hbound_limit.\n            rewrite <- Z.le_add_le_sub_l in H4.\n            etransitivity. etransitivity. 2: apply H4.\n            inv Hc_alloc. simpl max_allocs. destruct ys. inv Ha_l; exfalso; auto.\n            destruct Ha_l. rewrite H6. rewrite N2Z.inj_add. rewrite nat_N_Z.\n            rewrite Nat2Z.inj_succ.\n            rewrite Nat2Z.inj_add.  \n            unfold int_size. simpl size_chunk.  simpl Z.of_N. chunk_red; omega.\n            apply Ptrofs.unsigned_range_2. constructor.\n            constructor. unfold sizeof. chunk_red; archi_red; omega. rewrite ptrofs_mu. chunk_red; archi_red; solve_uint_range; omega.\n            constructor. \n            split.\n            apply N2Z.is_nonneg.\n            inv Hbound_limit.\n            rewrite <- Z.le_add_le_sub_l in H4.\n            etransitivity. etransitivity. 2: apply H4.\n            inv Hc_alloc. simpl max_allocs.\n             destruct ys. inv Ha_l; exfalso; auto.\n            destruct Ha_l. rewrite H6. rewrite N2Z.inj_add. rewrite nat_N_Z.\n            rewrite Nat2Z.inj_succ.\n            rewrite Nat2Z.inj_add. \n            unfold int_size. simpl size_chunk. simpl Z.of_N.\n            rewrite <- Z.add_succ_l.\n            assert (0 <=   Ptrofs.unsigned alloc_ofs)%Z by apply Ptrofs.unsigned_range_2.\n            chunk_red; omega.\n            apply Ptrofs.unsigned_range_2. constructor.\n\n\n            \n            split.\n            intro. intro. apply Hrange_alloc'. destruct H4. split; eauto.\n            etransitivity. 2: apply H4. rewrite int_z_mul. rewrite pointer_ofs_no_overflow.\n            int_red. rewrite Z.add_comm. apply Z_non_neg_add. reflexivity. apply Z.mul_nonneg_nonneg.\n            chunk_red; omega. apply N2Z.is_nonneg. apply N2Z.is_nonneg.\n            inv Hbound_limit.\n            rewrite <- Z.le_add_le_sub_l in H6.\n            etransitivity. etransitivity. 2: apply H6.\n            inv Hc_alloc. simpl max_allocs. destruct ys. inv Ha_l; exfalso; auto.\n            destruct Ha_l. rewrite H9. rewrite N2Z.inj_add. rewrite nat_N_Z.\n            rewrite Nat2Z.inj_succ.\n            rewrite Nat2Z.inj_add. \n            unfold int_size. simpl size_chunk. simpl Z.of_N. chunk_red; omega.\n            apply Ptrofs.unsigned_range_2. constructor.\n            unfold uint_range. unfold sizeof. rewrite ptrofs_mu. chunk_red; archi_red; solve_uint_range; omega. \n            constructor.\n            split.\n            apply N2Z.is_nonneg.\n            destruct Hbound_limit.\n            rewrite <- Z.le_add_le_sub_l in H6.\n            etransitivity. etransitivity. 2: apply H6.\n            inv Hc_alloc. simpl max_allocs.\n             destruct ys. inv Ha_l; exfalso; auto.\n            destruct Ha_l. rewrite H9. rewrite N2Z.inj_add. rewrite nat_N_Z.\n            rewrite Nat2Z.inj_succ.\n            rewrite Nat2Z.inj_add. \n            unfold int_size. simpl size_chunk. simpl Z.of_N.\n            rewrite <- Z.add_succ_l.\n            assert (0 <=   Ptrofs.unsigned alloc_ofs)%Z by apply Ptrofs.unsigned_range_2.\n            chunk_red; omega.\n            apply Ptrofs.unsigned_range_2. constructor.\n(* \n            \n            intros. inv Hc_alloc. \n            assert ( (0 <= i + (Z.of_N (a + 1)) < Z.of_nat (max_allocs (Econstr x t ys e))))%Z.\n            simpl max_allocs.   destruct ys. inv H2.\n            rewrite Nat2Z.inj_succ. \n            rewrite Nat2Z.inj_add.\n            destruct Ha_l. rewrite H5. simpl.  rewrite Pos2Z.inj_add.\n            rewrite Z.add_1_r.\n            rewrite Z.add_succ_r.\n            split.\n            apply Z.le_le_succ_r.\n            apply Z_non_neg_add.\n            apply Pos2Z.is_nonneg.\n            apply H4.\n            omega.\n            apply Hrange_alloc in H5.\n            rewrite Z.mul_add_distr_l in H5.\n            rewrite Z.add_comm in H5.\n            rewrite Int.add_assoc.\n            replace (Int.add (Int.mul (Int.repr (sizeof (globalenv p) val)) (Int.repr (Z.of_N (a + 1)))) (Int.repr (int_size * i)))  with (Int.repr (int_size * Z.of_N (a + 1) + int_size * i)).\n            eapply valid_access_after_nstore.\n            eapply Mem.store_valid_access_1.\n            eauto. apply H5.\n            destruct Hstep_m3; eauto.\n\n\n            assert (Halloc_ofs := Int.unsigned_range_2 alloc_ofs).\n            assert (Hlimit_ofs' := Int.unsigned_range_2 limit_ofs').\n            simpl max_allocs in Hbound_limit.\n            destruct ys. inv Ha_l. exfalso. apply H8; auto.\n            destruct Ha_l.\n            rewrite Nat2Z.inj_succ in Hbound_limit.\n            rewrite Nat2Z.inj_add in Hbound_limit.\n            rewrite <- nat_N_Z with (n := (length (v0 :: ys))) in Hbound_limit.\n            rewrite <- H6 in Hbound_limit.\n            rewrite N.add_1_r.\n            rewrite N2Z.inj_succ.\n            rewrite Zplus_succ_r_reverse in Hbound_limit.\n            rewrite Z.mul_add_distr_l in Hbound_limit.            \n            \n            rewrite int_z_mul.\n\n            rewrite int_z_add. reflexivity. \n            simpl sizeof. int_red.\n            constructor.\n            split.\n            assert (0 <= Z.of_N a)%Z by apply N2Z.is_nonneg. omega.\n            etransitivity. etransitivity. Focus 2. apply Hbound_limit.\n            assert (0 <= Int.unsigned alloc_ofs)%Z by apply Int.unsigned_range. omega.\n            apply Int.unsigned_range_2.\n            constructor. split. omega.\n            etransitivity. etransitivity. Focus 2. apply Hbound_limit.\n            assert (0 <= Int.unsigned alloc_ofs)%Z by apply Int.unsigned_range.\n            assert (0 <= Z.of_N a)%Z by apply N2Z.is_nonneg. omega.\n            apply Int.unsigned_range_2.\n            constructor.\n            simpl sizeof. constructor. solve_uint_range. constructor.\n\n            assert (0 <= Z.of_N a)%Z by apply N2Z.is_nonneg.\n            split. omega.\n            etransitivity. etransitivity. Focus 2. apply Hbound_limit.\n            assert (0 <= Int.unsigned alloc_ofs)%Z by apply Int.unsigned_range.\n            int_red.\n            omega.\n            apply Int.unsigned_range_2.\n            constructor. \n*) \n            split. rewrite M.gso.\n            subst.\n            eauto. intro.\n            assert (H_nodup := disjointIdent).\n            inv H_nodup. inversion H9.\n            apply H10. constructor. constructor.\n            split.\n            rewrite int_z_mul.\n            unfold Ptrofs.add.\n            destruct Ha_l. rewrite H4.\n            destruct ys. exfalso; apply H5; auto.\n            rewrite N2Z.inj_add.\n            rewrite nat_N_Z.\n            simpl Z.of_N.\n            simpl sizeof. rewrite Ptrofs.unsigned_repr with (z := (sizeof (prog_comp_env p) uval * (Z.of_nat (length (v0 :: ys)) + 1))%Z).\n            rewrite Ptrofs.unsigned_repr.\n            inv Hbound_limit.\n            inv Hc_alloc. simpl max_allocs in H6.\n            repeat (rewrite Nat2Z.inj_succ in H6).\n            rewrite Nat2Z.inj_add in H6. unfold int_size in *.\n            simpl size_chunk in *.\n            rewrite Nat2Z.inj_succ in H6.\n            split.\n            rewrite Z.sub_add_distr.\n            rewrite <- Z.le_add_le_sub_l.\n            etransitivity. 2: apply H6.\n            simpl length. rewrite Nat2Z.inj_succ.\n            chunk_red; unfold sizeof; archi_red; omega.\n            chunk_red; unfold sizeof; archi_red; omega.\n\n\n            split. apply Z_non_neg_add.\n            chunk_red; unfold sizeof; archi_red; omega.\n            apply Ptrofs.unsigned_range.\n            inv Hbound_limit. inv Hc_alloc.\n            rewrite <- Z.le_add_le_sub_l in H6.\n            etransitivity. etransitivity. 2: apply H6.\n            simpl max_allocs. simpl length. \n            rewrite Nat2Z.inj_succ.\n            rewrite Nat2Z.inj_succ.\n            rewrite Nat2Z.inj_add.                                                \n            rewrite Nat2Z.inj_succ. unfold int_size in *.\n            chunk_red; unfold sizeof; archi_red; omega.\n\n            apply Ptrofs.unsigned_range_2.\n            split.             chunk_red; unfold sizeof; archi_red; omega.\n            inv Hbound_limit. inv Hc_alloc. etransitivity.\n            etransitivity. 2: apply H8.\n            etransitivity. 2: apply H6.\n            unfold int_size.\n            simpl max_allocs. simpl length. \n            rewrite Nat2Z.inj_succ.\n            rewrite Nat2Z.inj_succ.\n            rewrite Nat2Z.inj_add.                                                \n            rewrite Nat2Z.inj_succ.\n            assert (0 <=  Ptrofs.unsigned alloc_ofs)%Z by apply Ptrofs.unsigned_range.\n            chunk_red; unfold sizeof; archi_red; omega.\n\n            unfold gc_size. rewrite ptrofs_mu. chunk_red; archi_red;  solve_uint_range; omega.\n            constructor.             chunk_red; unfold sizeof; archi_red; solve_uint_range; omega. \n            constructor.\n            split. apply N2Z.is_nonneg.\n            destruct Ha_l. rewrite H4.\n            destruct ys. exfalso; auto.\n            inv Hbound_limit.\n            rewrite <- Z.le_add_le_sub_l in H6. etransitivity.\n            etransitivity. 2: apply H6. 2: apply Ptrofs.unsigned_range_2.\n            inv Hc_alloc.  simpl max_allocs. simpl length. \n            rewrite Nat2Z.inj_succ.\n            rewrite Nat2Z.inj_add.\n            rewrite N2Z.inj_add.           \n            rewrite nat_N_Z.\n            unfold int_size. simpl size_chunk. simpl Z.of_N.         \n            assert (0 <=  Ptrofs.unsigned alloc_ofs)%Z by apply Ptrofs.unsigned_range.\n            simpl in H6. chunk_red; omega.\n\n            constructor.\n\n            \n            split. rewrite M.gso. eauto.\n            intro.\n            assert (H_nodup := disjointIdent). subst. \n            inversion H_nodup. subst. apply H8; inList.\n            split. auto. split. auto. split. auto.\n            split. rewrite M.gso. rewrite M.gso. eauto.\n            { inv Hp_id.\n              intro; subst.\n              eapply H5.\n              2: constructor.\n              inList.\n            }\n            intro.\n            assert (H_dj := disjointIdent); inv H_dj.\n            clear H4. inv H9. apply H6.\n            inList.\n            split. eauto. eauto.\n\n            (* same args_ptr *)\n            unfold same_args_ptr.\n            rewrite M.gso. rewrite M.gso. reflexivity.\n            intro. apply H3. unfold is_protected_id_thm. subst. inList.\n            assert (Hnd := disjointIdent).\n            inv Hnd. intro; apply H6; subst; inList.\n            \n        }} \n\n      - (* unboxed *)\n        eexists. eexists. split.\n        constructor. constructor. constructor.\n        split.\n        + (* mem *) \n          destruct Hrel_m as [L  [Hnot_in_L Hrepr_m]].\n          exists L. split.\n          eapply protected_not_in_L_set; eauto.\n          intro; apply Hx_not; apply is_protected_tinfo_weak; eauto.\n          intro. apply Hx_not. unfold is_protected_id_thm. subst; inList.\n          intros.  specialize (Hrepr_m x0).\n          destruct Hrepr_m as [Hrepr_m Hrepr_m'].\n          destruct (var_dec x0 x).\n          * subst.\n            split. \n              2:{ intros. rewrite M.gss in H2. inv H2.\n              apply subval_or_eq_fun in H3. destruct H3. destruct H2.\n              assert (Hy0x0 := get_list_In_val _ _ _ _ H H3).\n              destruct Hy0x0 as [y0 [Hy0 Hy0']].\n              inv Hy0. }\n            \n              \n            intro. \n            exists (Vconstr t vs). split.\n            rewrite M.gss. reflexivity.\n            econstructor 2.\n            apply Hf_id. constructor.\n            rewrite M.gss. reflexivity.\n            simpl in H. inv H.\n            econstructor; eauto.\n            \n          * \n            split. intro.\n            assert (occurs_free (Econstr x t [] e) x0).\n            constructor 2; auto.\n            specialize (Hrepr_m  H3).\n            destruct Hrepr_m as [v6 [Hx0v6 Hrepr_v6]].\n            exists v6.\n            split.\n            rewrite M.gso; auto.\n            apply repr_val_id_set; auto.\n            \n            intros. rewrite M.gso in H2 by auto.\n            eapply Hrepr_m' in H2; eauto.\n            destruct H2 as [H2 Hrepr_f].\n            split. 2: auto.\n            apply repr_val_id_set; auto.\n            intro; subst.\n            inv Hf_id.\n            assert ( bound_var (Econstr x t [] e) x) by constructor.\n            \n            apply H4 in H6.\n            inv H2.\n            rewrite H15 in H6; inv H6.\n            inv H10.\n            rewrite H17 in H6.\n            inv H6.\n        + split.\n          (* tinfo *)\n          apply correct_tinfo_not_protected.\n          eapply correct_tinfo_mono; eauto.\n          inv Hc_alloc. simpl. omega.\n          intro.\n          inv Hp_id.\n          eapply H4. apply is_protected_tinfo_weak. eauto. eauto.\n          { inv Hp_id.\n            intro; subst.\n            eapply H3.\n            2: constructor.\n            inList.\n          }\n\n          (* same args *)\n          unfold same_args_ptr. rewrite M.gso. reflexivity.\n          inv Hp_id. intro. apply Hx_not.\n          unfold is_protected_id_thm. subst; inList.\n          \n    }  destruct H0 as [lenv' [m' [Hstep [Hrel_m' [Htinfo_e Hsame_args]]]]].\n    \n    (* set up the with the recursive call *)\n    assert (Hc_env_e: correct_envs cenv ienv rep_env (cps.M.set x (Vconstr t vs) rho) e). {\n      eapply correct_envs_subterm.\n      eapply correct_envs_set. \n      eauto.\n      - inv Hc_env.\n        destructAll.\n        apply Forall_constructors_in_constr in H2. destruct (M.get t cenv) eqn:Mtcenv. 2: inv H2. destruct c0.\n        econstructor; eauto.   \n        2:{ simpl. simpl. subst. symmetry. exact (f_equal N.of_nat (get_list_length_eq _ _ _ H)). }\n        apply Forall_forall. intros.\n        assert (Hgiv := get_list_In_val _ _ _ _ H H4).\n        destruct Hgiv. destruct H5.\n        eapply H1. eauto.\n      -  constructor. constructor.\n    }\n    assert (Hp_id_e: protected_id_not_bound_id (cps.M.set x (Vconstr t vs) rho) e).\n    { split; intros.\n      - inv Hp_id.\n        destruct (var_dec x0 x).\n        + subst. intro. inv H4; subst.\n          eapply H3; eauto.                    \n          rewrite M.gss in H0. inv H0.\n          inv H5.\n          assert (Hgi_v := get_list_In_val _ _ _ _ H H10).\n          destructAll.           \n          eapply H2; eauto. \n        + rewrite M.gso in H0 by auto. eapply H2; auto. \n      - inv Hp_id.\n        intro. eapply H2; eauto.\n    }\n    assert (Hf_id_e:  functions_not_bound p (cps.M.set x (Vconstr t vs) rho) e). {\n      eapply functions_not_bound_subterm.\n      eapply functions_not_bound_set;\n        eauto.\n      - intros.\n\n        inv H0.\n        inv Hf_id.\n        assert (Hx0rho := get_list_In_val _ _ _ _ H H5).\n        destruct Hx0rho. destruct H2.  \n        eapply H1; eauto. \n      - constructor. constructor.\n    }\n    assert (H_rho_e:  unique_bindings_env (cps.M.set x (Vconstr t vs) rho) e ).\n    {  destruct Hrho_id as [Hub Hrho_id].\n      split.\n      inv Hub; auto.\n      intro. intros.\n      destruct (var_dec x0 x).\n      - subst. (* need unique binding *)        \n        inv Hub. auto.\n        rewrite M.gss in H0. inv H0.\n        split; auto. constructor.\n        apply Forall_forall. intros.         \n        assert (Hx0rho := get_list_In_val _ _ _ _ H H0). destruct Hx0rho as [xx0 [Hinys Hxx0rho]].\n        apply Hrho_id in Hxx0rho. destruct Hxx0rho. auto.\n      -  rewrite M.gso in H0 by auto.\n         apply Hrho_id in H0.\n         destruct H0. split; auto.\n    }\n    specialize (IHHev Hc_env_e Hp_id_e H_rho_e Hf_id_e).\n    assert (Hca_e : correct_alloc e (Z.of_nat (max_allocs e))).\n    unfold correct_alloc. reflexivity.\n    specialize (IHHev _ _ _ k _ fu H7 Hrel_m' Hca_e Htinfo_e).\n    destruct IHHev as [m'' [lenv'' [Hstep' [Hargs1 Hargs2]]]].\n    exists m'', lenv''.\n    split; auto.\n    eapply t_trans. eapply t_trans.\n    constructor. constructor. apply Hstep.\n    eapply t_trans. constructor. constructor.\n    auto.\n    split; auto.    \n    unfold same_args_ptr in *. etransitivity; eauto.\n\n\n  - (* Eproj *)\n     \n    (* > representation in memory of the Vconstr *)\n    assert (Hy : occurs_free (Eproj x t n y e) y) by constructor.\n    destruct (Hrel_m) as [L [HL_pro Hmem]].\n    apply Hmem in Hy. destruct Hy as [v6 [Hyv6 Hrepr_v6]].    \n    rewrite Hyv6 in H. inv H.     \n    inversion Hrepr_v6; subst.\n    \n    rename H1 into Hyv7.\n    inv H2.\n    (* impossible that v7 is an enum, if taking proj, then vs is not empty so c is boxed *) \n    { exfalso.  \n      inv H0.\n    }\n    (* get the value on the nth of vs in memory *)\n    \n    assert (Hvn := repr_val_ptr_list_L_nth argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent isptrIdent caseIdent nParam _ _ _ _ H12  H0).\n \n    (* done setting up, taking the proj step *)\n    destruct Hvn as [v7' [Hv7'_l Hv7'_rep]]. \n    assert (m_tstep2 (globalenv p)\n      (State fu\n         (Ssequence\n            (Sset x\n               (Ederef\n                  (add\n                     (Ecast (Etempvar y val)\n                        (Tpointer val\n                           {|\n                           attr_volatile := false;\n                           attr_alignas := None |}))\n                     (c_int' (Z.of_N n) val)) val)) s) k empty_env\n         lenv m)\n      (State fu s k empty_env (Maps.PTree.set x v7' lenv) m)).\n    {\n      eapply t_trans.\n      constructor. constructor.\n      eapply t_trans.\n      constructor. constructor. eapply eval_Elvalue. apply eval_Ederef.\n      econstructor. econstructor. constructor.\n      eauto. reflexivity. constructor.\n      simpl. unfold sem_add. simpl. reflexivity.\n      eapply deref_loc_value. constructor. simpl.\n      rewrite Ptrofs.mul_commut. unfold Ptrofs.of_int64.\n      rewrite ptrofs_of_int64.\n      rewrite sizeof_uval.\n      apply Hv7'_l.\n      constructor. constructor.\n    }\n\n    simpl in Hc_alloc.\n    assert (Hc_env_e: correct_envs cenv ienv rep_env (cps.M.set x v rho) e). {\n      eapply correct_envs_subterm.\n      eapply correct_envs_set.\n      eauto.\n      - inv Hc_env. destructAll.\n        apply nthN_In in H0.\n        apply H3 in Hyv6. inv Hyv6.        \n        rewrite Forall_forall in H14.\n        apply H14; auto.\n      - constructor. constructor.\n    }\n    specialize (IHHev Hc_env_e).\n    assert (Hp_id_e: protected_id_not_bound_id (cps.M.set x v rho) e).\n    { split; intros.\n      - inv Hp_id.\n        destruct (var_dec x0 x).\n        + subst. intro. inv H11; subst.\n          eapply H10. apply H3. constructor.\n          rewrite M.gss in H2. inv H2.\n          eapply H9. apply Hyv6. apply H3.\n          right. econstructor.\n          apply H13. eapply nthN_In; eauto.\n        + rewrite M.gso in H2 by auto. eapply H9. apply H2. auto.\n      - inv Hp_id.\n        intro. eapply H9. apply H2.\n        constructor; auto.\n    }\n    specialize (IHHev Hp_id_e).\n    assert (Hf_id_e: functions_not_bound p (cps.M.set x v rho) e). {\n      eapply functions_not_bound_subterm.\n      eapply functions_not_bound_set; eauto.\n      - intros.\n        inv Hf_id. eapply H9. apply Hyv6.\n        econstructor. apply H2.\n        eapply nthN_In; eauto.\n      - constructor. constructor.\n    }\n      \n    assert (Hrho_id_e: unique_bindings_env (cps.M.set x v rho) e). {\n      destruct Hrho_id as [Hub Hrho_id].\n      split.\n      inv Hub; auto. \n      intros. destruct (var_dec x0 x).\n      - subst. rewrite M.gss in H2. inv H2. inv Hub; auto.\n        split; auto.\n        apply Hrho_id in Hyv6.\n        destruct Hyv6. inv H3. rewrite Forall_forall in H11.\n        apply H11; auto. eapply nthN_In. eauto.\n      - rewrite M.gso in H2 by auto. apply Hrho_id in H2.\n        destruct H2. split; auto.\n    }\n    specialize (IHHev Hrho_id_e Hf_id_e _ (Maps.PTree.set x v7' lenv) m k max_alloc fu H7).    \n    assert (Hx_not:  ~ is_protected_id_thm x). {\n      intro. inv Hp_id. eapply H9; eauto.    \n    }\n    assert (rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env e (cps.M.set x v rho) m (Maps.PTree.set x v7' lenv)).\n    { exists L.\n      \n      split.\n      -  eapply protected_not_in_L_set; eauto.\n         intro; apply Hx_not; apply is_protected_tinfo_weak; auto.\n         intro; apply Hx_not. subst. unfold is_protected_id_thm; inList.\n      - intros.\n        destruct (var_dec x0 x).\n        + subst.\n          split; intros.\n          * exists v. split.\n            rewrite M.gss; auto.\n            specialize (Hmem x). destruct Hmem as [Hmem Hmem'].\n            econstructor 2. \n            (* x is bound in Eproj x t n y e so cannot be a function name  *)\n            apply Hf_id. constructor.\n            rewrite M.gss. reflexivity.\n            apply Hv7'_rep.\n          * rewrite M.gss in H2. inv H2.\n            apply nthN_In in H0.\n            specialize (Hmem y). destruct Hmem as [Hmem Hmem'].\n            specialize (Hmem' _ _ _ _ Hyv6 (subval_or_eq_constr _ _ _ _ H3 H0)). \n            destruct Hmem' as [Hmem' Hmem_f]. split. 2: auto.\n            apply repr_val_id_set. auto.\n            intro. subst.\n            inv Hf_id.\n            assert ( bound_var (Eproj x t n y e) x) by constructor.\n            apply H2 in H10.\n            inv Hmem'.\n            rewrite H10 in H19. inv H19.\n            inv H14. rewrite H10 in H22. inv H22.\n        + rewrite M.gso by auto.\n          specialize (Hmem x0). destruct Hmem as [Hmem Hmem'].\n          split. intros.\n          assert ( occurs_free (Eproj x t n y e) x0). constructor; auto.\n\n          specialize (Hmem  H3). destructAll.\n          exists x1; split; auto.\n          inv H10.\n          * econstructor; eauto.\n          * econstructor 2; eauto.\n            rewrite M.gso; auto.\n          * intros. specialize (Hmem' _ _ _ _ H2 H3).\n            destruct Hmem' as [Hmem' Hmem_f].\n            split. 2: auto.\n            apply repr_val_id_set. auto.\n            inv Hmem'. intro.  inv Hf_id. specialize (H10 x).\n            assert ( bound_var (Eproj x t n y e) x) by constructor. apply H10 in H9. \n            rewrite H9 in H17. inv H17.\n            inv H11.\n            rewrite H20 in H9. inv H9.            \n    } \n    assert ( correct_alloc e max_alloc). inv Hc_alloc.\n    simpl. constructor.\n    assert ( correct_tinfo p max_alloc\n            (Maps.PTree.set x v7' lenv) m ).\n    apply correct_tinfo_not_protected; auto.\n    intro; apply Hx_not; apply is_protected_tinfo_weak; auto.\n    {\n      inv Hp_id.\n      intro. eapply H10.\n      2:{ subst. constructor. }\n      inList.\n    }\n    specialize (IHHev H2 H3 H9).\n    destruct IHHev as [m' [lenv' [Hstep [Hargs1 Hargs2]]]].\n    exists m', lenv'.\n    split; auto.\n    eapply t_trans; eauto.\n    split; auto.\n    unfold same_args_ptr in *.\n    rewrite <- Hargs1.\n    rewrite M.gso. auto.\n    inv Hp_id. intro. apply Hx_not. unfold is_protected_id_thm. subst; inList.\n  - (* Ecase *)     \n    \n    (* get the representation of y *)\n    assert (Hrel_m' := Hrel_m).\n    destruct Hrel_m' as [L [Hmem_p Hmem_rel]].\n    assert (occurs_free (Ecase y cl) y) by constructor.\n    apply Hmem_rel in H2. destruct H2 as [y6 [Hy6 Hrepr_id_y6]].\n    rewrite Hy6 in H. inv H.\n\n    assert (Htcenv := caseConsistent_findtag_In_cenv _ _ _ _ H0 H1).\n    destruct Htcenv as [a [ty [n [i Htcenv]]]].\n    (** Hrepr_id_y6 must be RVid_V *)\n    inv Hrepr_id_y6.\n    rename H into Hglob_y. rename H2 into Hlenv_y. rename H3 into Hrepr_y.\n\n\n    (* step through the assignment and the isptr check *)\n    inv H6.\n    destruct Hpinv as [Hptr_inv Htinf_inv].\n    clear Htinf_inv.\n    destruct Hptr_inv as [b_isPtr [isPtr_name [isPtr_sg [H_isPtr [H_isPtr_ff [H_isPtr_int H_isPtr_ptr]]]]]].\n\n    assert (Hstep_case:\n        exists vbool s s', \n          m_tstep2 (globalenv p)                   \n         (State fu\n         (Ssequence (isPtr isptrIdent caseIdent y)\n            (Sifthenelse (Etempvar caseIdent boolTy)\n               (Sswitch\n                  (Ebinop Oand\n                     (Ederef\n                        (add\n                           (Ecast (Etempvar y val)\n                              (Tpointer val\n                                 {| attr_volatile := false; attr_alignas := None |}))\n                           (c_int' (-1) val)) val) (make_cint 255 val)\n                     val) ls)\n               (Sswitch\n                  (Ebinop Oshr (Etempvar y val) (make_cint 1 val) val) ls')))\n         k empty_env lenv m)\n         (State fu s (Kseq Sbreak (Kseq s' (Kswitch k))) empty_env\n                (Maps.PTree.set caseIdent vbool lenv) m) /\\\n         repr_expr_LambdaANF_Codegen_id fenv finfo_env p rep_env e s).\n    {\n      inv Hrepr_y.\n      - (* unboxed *)\n        exists (Vfalse).\n        assert (exists s s', seq_of_labeled_statement (select_switch (Z.shiftr n0 1) ls') = (Ssequence (Ssequence s Sbreak) s') /\\  repr_expr_LambdaANF_Codegen_id fenv finfo_env p rep_env e s).\n        eapply case_of_labeled_stm_unboxed; eauto; inv Hc_env; destruct H2; destruct H5; eauto.\n        destruct H as [s [s' [Hseq Hrepr_es]]].\n        exists s, s'.\n        split; auto.\n\n        \n        eapply t_trans. constructor.\n        constructor. eapply t_trans.\n        constructor. unfold isPtr.\n\n\n        econstructor.\n        simpl. constructor. \n        econstructor.  apply eval_Evar_global. apply Maps.PTree.gempty. (* assumption 1 *) eauto. \n        constructor. constructor. econstructor. econstructor. constructor. apply Hlenv_y. apply sem_cast_vint. apply sem_cast_vint.         constructor. eauto.\n        reflexivity. \n        eapply t_trans. constructor.\n        \n        eapply step_external_function. apply H_isPtr_int.\n        \n        (* return *)\n        eapply t_trans. constructor. constructor. eapply t_trans. constructor. constructor.\n        eapply t_trans. constructor. econstructor. constructor. unfold set_opttemp. rewrite M.gss. reflexivity. simpl.  constructor. \n        rewrite Int.eq_true. simpl. \n\n         (* switch to the right case *)\n        eapply t_trans. constructor. econstructor. simpl. econstructor. constructor.\n        rewrite M.gso. apply Hlenv_y. (* caseIdent is protected *)\n        {\n          destruct Hp_id as [Hp_1 Hp_2].\n          intro; eapply Hp_1; eauto.\n          inList.\n        }\n        apply eval_cint.\n        simpl.\n        assert (  sem_binary_operation (globalenv p) Oshr (make_vint n0) (typeof (Etempvar y uval))\n                                       (make_vint 1) (typeof (make_cint 1 uval)) m = (Some (int_shru n0 1))).  unfold int_shru. unfold make_cint. chunk_red; archi_red. constructor. constructor. apply H.\n        apply sem_switch_arg_1. \n        eapply repr_unboxed_header_range; eauto.  \n        \n         rewrite Hseq. eapply t_trans.\n        constructor. constructor.\n        constructor. constructor.\n      - exists Vtrue.\n\n        assert ( exists s s', \n                   (seq_of_labeled_statement (select_switch (Z.land h 255) ls)) = (Ssequence (Ssequence s Sbreak) s') /\\  repr_expr_LambdaANF_Codegen_id fenv finfo_env p rep_env e s).\n        inv Hc_env. inv H2. destruct H9. \n         eapply case_of_labeled_stm_boxed; eauto. \n        destruct H as [s [s' [H_seq H_repr_es]]].\n        exists s, s'.\n        split; auto.\n        eapply t_trans. constructor.\n        constructor. eapply t_trans.\n        constructor. unfold isPtr. \n        econstructor.\n        simpl. constructor. \n        econstructor.  apply eval_Evar_global. apply Maps.PTree.gempty. (* assumption 1 *) eauto. \n        constructor. constructor. econstructor. econstructor. constructor. apply Hlenv_y. simpl. constructor. simpl. constructor. \n        constructor. (* assumption 2 *) eauto. reflexivity.\n        eapply t_trans. constructor.\n        \n        eapply step_external_function.\n        apply H_isPtr_ptr.\n\n        (* return *)\n        eapply t_trans. constructor. constructor. eapply t_trans. constructor. constructor.\n\n        (* if-then-else *)\n        eapply t_trans. constructor. econstructor. constructor. unfold set_opttemp. rewrite M.gss. reflexivity. simpl. constructor.\n        simpl. rewrite Int.eq_false. simpl.\n\n      (* switch to the right case *)\n      eapply t_trans. constructor. econstructor. simpl. econstructor. econstructor. constructor.\n      econstructor. econstructor. constructor. \n      rewrite M.gso. apply Hlenv_y.\n      (* caseIdent is protected *)\n      {                \n        destruct Hp_id as [Hp_id1 Hp_id2].\n        intro; eapply Hp_id1; eauto.\n        inList.\n      }\n      constructor. constructor.  constructor. eapply  deref_loc_value. simpl. reflexivity.\n      simpl. rewrite Ptrofs.sub_add_opp in H6.\n      unfold Ptrofs.of_int64. rewrite ptrofs_of_int64. \n      rewrite Ptrofs.mul_mone. rewrite sizeof_val. eauto.\n      apply eval_cint.\n      simpl.\n      assert (  sem_and (make_vint h) uval (make_vint 255) (typeof (make_cint 255 uval)) m = Some (int_and h 255)). {\n        unfold sem_and. unfold int_and. chunk_red; archi_red; auto. \n      }\n      apply H. simpl.\n      apply sem_switch_and_255.\n      eapply repr_boxed_header_range; eauto. \n      rewrite H_seq.\n      eapply t_trans.\n      constructor.  constructor.\n      constructor. constructor.\n      intro. inv H.        \n    }\n    destruct Hstep_case as [vbool [s [s' [Hstep_case H_repr_es]]]].\n\n    (* building up the IHHev to use after Hstep_case *)\n    assert (H_cenv_e: correct_envs cenv ienv rep_env rho e).\n    {\n      eapply correct_envs_subterm; eauto.\n      constructor. eapply dsubterm_case.\n      apply findtag_In. eauto.\n    }\n    assert (Hp_id_e: protected_id_not_bound_id rho e).\n    {\n      inv Hp_id. \n      split; intros.\n      apply H; eauto.\n      intro.\n      eapply H2. apply H3.\n      econstructor. apply H5.\n      apply findtag_In. eauto.\n    }\n    assert (H_rho_id_e:  unique_bindings_env rho e).\n    { inv Hrho_id.\n      split.\n      - assert (Hcase := shrink_cps_correct.ub_case_inl).\n        specialize (Hcase ctx.Hole_c). simpl in Hcase.\n        eapply Hcase; eauto.\n      - intros. apply H2 in H3.\n        destruct H3; split; auto.\n        intro.\n        apply H3.        \n        eapply Bound_Ecase; eauto.\n        eapply findtag_In; eauto.\n    }\n    assert (Hf_id_e: functions_not_bound p rho e).\n    {\n      eapply functions_not_bound_subterm.\n      eauto.\n      econstructor.\n      econstructor. apply findtag_In; eauto.\n    }\n    assert (Hca_e : correct_alloc e (Z.of_nat (max_allocs e))).\n    unfold correct_alloc. reflexivity.\n    assert (Hmem_e : rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env e rho m  (Maps.PTree.set caseIdent vbool lenv)).\n    {\n      inv Hc_tinfo; destructAll. \n      exists L.\n      split.      \n      -  eapply protected_not_in_L_set.\n         auto.\n        apply is_protected_not_tinfo. inList.\n        intro.   assert (Hnd := disjointIdent). inv Hnd. \n        replace [allocIdent; limitIdent; gcIdent; mainIdent; bodyIdent;\n          threadInfIdent; tinfIdent; heapInfIdent; numArgsIdent;\n          numArgsIdent; isptrIdent; tinfIdent] with ([allocIdent; limitIdent; gcIdent; mainIdent; bodyIdent;\n          threadInfIdent]++[tinfIdent; heapInfIdent; numArgsIdent;\n          numArgsIdent; isptrIdent; tinfIdent]) in * by reflexivity. apply NoDup_cons_r in H23. inversion H23. apply H24; inList. \n      - intros. \n        specialize (Hmem_rel x7). destruct Hmem_rel as [Hmem_rel Hmem_rel'].\n        split; intros.\n        \n        assert (occurs_free (Ecase y cl) x7).\n        eapply occurs_free_Ecase_Included.\n        apply findtag_In. eauto. auto. \n        \n        apply Hmem_rel in H20.\n        destruct H20 as [v6 [Hx4v6 Hrepr_v6]].\n        exists v6. split; auto.\n        apply repr_val_id_set. auto.\n        inv Hp_id_e.\n        eapply H20 in Hx4v6.\n        intro. apply Hx4v6. left. apply H22.\n        inList.\n\n        specialize (Hmem_rel' _ _ _ _ H19 H20).\n        destruct Hmem_rel' as [Hmem_rel' Hmem_f].\n        split. 2: auto.\n        apply repr_val_id_set. auto.\n        intro. inv Hp_id. eapply H22. apply H19. 2:{ right.\n        eapply bound_var_subval; eauto.\n        inv Hmem_rel'.\n        inv H31.\n        constructor.\n        apply name_in_fundefs_bound_var_fundefs.\n        eapply find_def_name_in_fundefs. eauto.\n        inv H25. rewrite H33 in H21. inv H21. }\n        inList.\n        \n    }\n    assert (H_tinfo_e: correct_tinfo p  (Z.of_nat (max_allocs e))\n                           (Maps.PTree.set caseIdent vbool lenv) m ).\n    {\n      apply correct_tinfo_not_protected.\n      eapply correct_tinfo_mono; eauto.\n      split. omega.\n      inv Hc_alloc.\n      apply inj_le.\n      eapply max_allocs_case.\n      apply findtag_In. eauto.\n      intro.  \n      assert (Hdj:=disjointIdent).\n      inv Hdj.\n      inv H. clear H2.\n      inv H6. apply H3; inList.      \n      destruct H2; subst.\n      clear H. inv H6. inv H7. apply H6; inList.\n      clear H.\n      apply H5; inList.\n      assert (Hdj:=disjointIdent).\n      inv Hdj.\n      intro. inv H5. clear H.  inv H8.\n      inv H6. inv H9. inv H10. inv H11. inv H12. apply H11.\n      inList.\n    }\n\n    specialize (IHHev H_cenv_e Hp_id_e H_rho_id_e Hf_id_e _ _ _ (Kseq Sbreak (Kseq s' (Kswitch k))) _ fu H_repr_es Hmem_e Hca_e H_tinfo_e).\n\n    destruct IHHev as [m' [lenv' [Hstep_end [Hargs1 Hargs2]]]].\n    exists m', lenv'.\n    split; auto.\n\n    (* step to e, then IH *)\n    eapply t_trans.\n    apply Hstep_case.\n    eapply t_trans.\n    apply Hstep_end.\n\n    (* break back to k *)\n    eapply t_trans.\n    constructor. constructor.\n    eapply t_trans.\n    constructor. constructor.\n    constructor.\n    constructor. auto.\n    split; auto.\n    unfold same_args_ptr in *. rewrite <- Hargs1.\n    rewrite M.gso; auto.\n    assert (H_dj := disjointIdent). inv H_dj.\n    intro; apply H3; subst; inList.     \n  - (* Eapp  *)  (* CHANGE THIS *)  \n\n    (* need assumption that unique_binding_env -> done! and functions_not_bound is preserved by all closures (rho', e) in rho - DONE *)\n    (* Show protected_id_not_bound_id is preserved by prefixes - done *)\n    (* also need to should that correct_cenv_of_exp is respected for all constructors found DONE! *)\n    (* > new max_alloc is correct_alloc for e *)\n    (* > tinfo is updated to reflect the max_alloc of e *)\n    (* IH will be on Hev with rho'' |- e -> v. Need to show that rho' is a sufficient prefix of rho, and create a related mem *)\n\n\n    (* show that tinfo -> argsIdent is some pointer to the right thing, and then that\n  rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env e  rho (M.set argsIdent ( m) lenv *)  \n    destruct inf as [n ind].\n    unfold ctor_tag in t.\n    set (bys := firstn nParam ys).\n    set (ays := skipn nParam ys).\n    set (aind := skipn nParam ind).\n    set (bind := firstn nParam ind).\n    assert (bysEq : bys = firstn nParam ys) by reflexivity.\n    assert (aysEq : ays = skipn nParam ys) by reflexivity.\n    assert (aindEq : aind = skipn nParam ind) by reflexivity.\n    assert (bindEq : bind = firstn nParam ind) by reflexivity.\n   \n    inv H10.\n\n    assert (Hrepr : repr_asgn_fun' argsIdent threadInfIdent nParam fenv finfo_env p ays aind s) by apply H3.\n    clear H3.\n    \n    assert (Hcall : repr_call_vars threadInfIdent nParam fenv finfo_env p (Init.Nat.min (N.to_nat n) nParam) bys s2) by apply H13.\n    clear H13.\n    \n    destruct Hpinv as [Hpinv_ptr [Hpinv_tinfo Hpinv_gc]].\n    destruct Hpinv_tinfo as [co [Hget_tinfident Htinfident_members]].\n  \n    (* get more info about the function *) \n    assert (Hrel' := Hrel_m).\n    destruct Hrel' as [L [Hrel_p Hrel_m']].\n    specialize (Hrel_m' f).\n    destruct Hrel_m' as [Hrel_of Hrel_fun].\n    \n    assert (Hsubval : subval_or_eq (Vfun rho' fl f') (Vfun rho' fl f')) by apply rt_refl.\n      \n    specialize (Hrel_fun rho' fl f' _ H Hsubval).   \n    destruct Hrel_fun as [Hrepr_f [Hclosed_f Hfundef_f]]. \n    destruct Hfundef_f as [finfo [t' [t'' [vs' [e' [Hfind_def_f' [Hfinfo_env_f' [Hfundef_tag' Hfundef_f']]]]]]]].\n    rewrite Hfind_def_f' in H1. inversion H1. subst. clear H1. clear Hsubval.\n     \n    destruct Hfundef_f' as [n' [l' [b' [fi_0 [Hf_fenv [Hnl [Hlvs [Hl_nodub [Hinf1 [Hfind_symbol [Hload_fi0 [Hload_fi1 [Hcorrect_alloc [Hgc_size_fi0 Hforall_l_fi]]]]]]]]]]]]]].    \n    rewrite Hf_fenv in H6. inv H6.\n    rewrite Nnat.Nat2N.id in Hcall.\n\n    (* break apart the tinfo *)\n    assert (Hc_tinfo' := Hc_tinfo).  \n    destruct Hc_tinfo as [alloc_b [alloc_ofs [limit_ofs [args_b [args_ofs [tinf_b [tinf_ofs [Hget_alloc [Hdiv_alloc [Hrange_alloc [Hget_limit [Hbound_limit [Hget_args [Hdj_args [Hbound_args [Hrange_args [Hget_tinf [Htinfne1 [Htinfne2 [Hinfo_limit [Hloc_args Hglobals]]]]]]]]]]]]]]]]]]]]].\n    destruct Hbound_limit as [Hbound_limit Hbound_gc_size].\n    rewrite <- Z.le_add_le_sub_l in Hbound_limit. \n \n    remember (Kseq\n                (Sassign\n                   (Efield\n                      (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr))\n                      allocIdent valPtr) (Etempvar allocIdent valPtr))\n                (Kseq\n                   (Sassign\n                      (Efield\n                         (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr))\n                         limitIdent valPtr) (Etempvar limitIdent valPtr))\n                   (Kseq\n                      (Scall None (Ecast (var_or_funvar_f threadInfIdent nParam fenv finfo_env p f)\n                                         (Tpointer (mkFunTy threadInfIdent (Init.Nat.min (N.to_nat (fst (N.of_nat (length ind), ind))) nParam)) noattr))\n                             (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr) :: s2)) k))) as k'.\n\n    remember (Maps.PTree.set argsIdent (Vptr args_b args_ofs) lenv) as  lenv'.\n    assert (Hlenv' : (Maps.PTree.set argsIdent (Vptr args_b args_ofs) lenv) = lenv) by (apply  Maps.PTree.gsident; auto).\n    assert (Hrel_m' : rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env  (Eapp f t ys) rho m lenv'). {      \n      rewrite Heqlenv'. rewrite Hlenv'. auto.\n    }\n \n    assert (Hys: Forall (fun x => exists v, get_var_or_funvar p lenv x v) ys). {\n      apply Forall_forall. intros.      \n      assert (Hgl := get_list_In _ _ _ _ H0 H1).\n      destruct Hgl. destruct Hrel_m. destructAll. specialize (H5 x). destruct H5. \n      assert ( occurs_free (Eapp f t ys) x). constructor. auto.\n      specialize (H5 H7). inv H5. destruct H8. rewrite H5 in H3. inv H3. \n      inv H8. eexists. constructor. eauto.\n      eexists. constructor 2. eauto. eauto. inv H10; auto.       \n    } \n    assert (HInFirstn : forall {A} n x (l : list A) , List.In x (firstn n l) -> List.In x l). (* TODO : move out *)\n    {\n      intros A n x l Hl.\n      erewrite <- firstn_skipn.\n      eapply in_or_app. eauto.\n    }\n    assert (HInSkipn : forall {A} n x (l : list A) , List.In x (skipn n l) -> List.In x l). (* TODO : move out *)\n    {\n      induction n; intros. assumption.\n      induction l. inv H1.\n      simpl in H1.\n      specialize (IHn x l H1).\n      right. assumption.\n    }\n    assert (HFirstnLength : forall {A B} n (l1 : list A) (l2 : list B), length l1 = length l2 -> length (firstn n l1) = length (firstn n l2)). (* TODO : move out *)\n    {\n      intros A B n l1. generalize n. clear n. induction l1; intros n l2 Hlen; destruct l2; [ | inv Hlen | inv Hlen | ].\n      + destruct n; reflexivity.\n      + inv Hlen. destruct n. reflexivity.\n        simpl. apply f_equal.\n        auto.\n    }\n    assert (HSkipnLength : forall {A B} n (l1 : list A) (l2 : list B), length l1 = length l2 -> length (skipn n l1) = length (skipn n l2)). (* TODO : move out *)\n    {\n      intros A B n l1. generalize n. clear n. induction l1; intros n l2 Hlen; destruct l2; [ | inv Hlen | inv Hlen | ].\n      + destruct n; reflexivity.\n      + inv Hlen. destruct n.\n        * simpl. apply f_equal. auto.\n        * simpl. apply IHl1; auto.\n    }\n    assert (Hbys : Forall (fun x : positive => exists v : Values.val, get_var_or_funvar p lenv x v) bys).\n    {\n      apply Forall_forall. intros.\n      apply (proj1 (Forall_forall _ ys) Hys x).\n      rewrite bysEq in H1. eapply HInFirstn. eauto.\n    }\n    assert (Hays : Forall (fun x : positive => exists v : Values.val, get_var_or_funvar p lenv x v) ays).\n    {\n      apply Forall_forall. intros.\n      apply (proj1 (Forall_forall _ ys) Hys x).\n      rewrite aysEq in H1. eapply HInSkipn. eauto.\n    }\n    assert (Haind :  Forall (fun i : N => (0 <= Z.of_N i < max_args)%Z) aind).\n    {\n      apply Forall_forall. intros.\n      apply (proj1 (Forall_forall _ ind) Hinf1 x).\n      rewrite aindEq in H1. eapply HInSkipn. eauto.  \n    }\n    assert (Hbind :  Forall (fun i : N => (0 <= Z.of_N i < max_args)%Z) bind).\n    {\n      apply Forall_forall. intros.\n      apply (proj1 (Forall_forall _ ind) Hinf1 x).\n      rewrite bindEq in H1. eapply HInFirstn. eauto.  \n    }\n    assert (Haind_nodup : NoDup aind).\n    {\n      rewrite aindEq.\n      eapply NoDup_cons_r.\n      rewrite (firstn_skipn nParam ind).\n      assumption.\n    } \n    assert (Hbind_nodup : NoDup bind).\n    {\n      rewrite bindEq.\n      eapply NoDup_cons_l.\n      rewrite (firstn_skipn nParam ind).\n      assumption.\n    }\n    \n    assert (Hasgn_fun_mem :=  repr_asgn_fun_mem fu lenv p rho (Eapp f t ys) fenv max_alloc rep_env finfo_env ays aind s m Hsym HfinfoCorrect Hrel_m Hc_tinfo' Hays Haind Haind_nodup Hrepr). \n    destruct Hasgn_fun_mem as [m2 [Hasgn_fun_mem [Hmem_of_asgn Hrel_mem]]]. \n    specialize (Hasgn_fun_mem k').\n    (* lenv' := (Maps.PTree.set argsIdent (Vptr args_b args_ofs) lenv) *) \n    (* k := (Kseq\n          (Sassign\n             (Efield\n                (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr))\n                allocIdent valPtr) (Etempvar allocIdent valPtr))\n          (Kseq\n             (Scall None\n                (Ecast\n                   (Evar f\n                      (Tfunction (Tcons (Tpointer (Tstruct threadInfIdent noattr) noattr) Tnil) Tvoid\n                         {| cc_vararg := false; cc_unproto := false; cc_structret := false |}))\n                   (Tpointer\n                      (Tfunction (Tcons (Tpointer (Tstruct threadInfIdent noattr) noattr) Tnil) Tvoid\n                         {| cc_vararg := false; cc_unproto := false; cc_structret := false |}) noattr))\n                [Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)]) k)) *)\n \n\n    (* m3 saves the value of alloc_ofs into the tinfo *)\n     \n    assert (Hm3 : Mem.valid_access m2 int_chunk tinf_b (Ptrofs.unsigned tinf_ofs) Writable). {\n      destruct Hrel_mem. inv H3. destructAll. rewrite H12 in Hget_tinf; inv Hget_tinf. specialize (H15 0%Z). rewrite Ptrofs.add_zero in H15. eapply H15. omega.\n    }\n    eapply Mem.valid_access_store with (v := (Vptr alloc_b alloc_ofs)) in Hm3.\n    destruct Hm3 as [m3 Hm3].\n\n    (* m4 saves the value of limit_ofs into tinfo *)\n    assert (Hm4 : Mem.valid_access m3 int_chunk tinf_b (Ptrofs.unsigned (Ptrofs.add tinf_ofs (Ptrofs.repr int_size))) Writable). {\n      eapply Mem.store_valid_access_1.\n      eauto.\n      destruct Hrel_mem. inv H3. destructAll.\n      rewrite H12 in Hget_tinf; inv Hget_tinf.\n      specialize (H15 1%Z). simpl in H15. eapply H15. omega.\n    }\n    eapply Mem.valid_access_store with (v := (Vptr alloc_b limit_ofs)) in Hm4.\n    destruct Hm4 as [m4 Hm4].\n    destruct Hrel_mem as [Hrel_mem2 Hc_tinfo_m2].\n\n    assert (Hrel_mem3 :  rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env (Eapp f t ys) rho m3 lenv). {\n      inv Hrel_mem2.\n      exists x. \n      assert (Mem.unchanged_on x m2 m3). {\n        (* protected not in x *)\n        destruct H1. eapply Mem.store_unchanged_on; eauto.\n        intros.\n        inv H1. destructAll. rewrite H10 in Hget_tinf; inv Hget_tinf. apply H11.\n      }\n      destructAll.\n      split; auto. intro. specialize (H4 x0).\n      destruct H4.\n      split. intro. apply H4 in H6.\n      destructAll.\n      exists x1. split; auto.\n      apply repr_val_id_L_unchanged with (m := m2); eauto. \n      intros. specialize (H5 _ _ _ _ H6 H7).\n      destruct H5. destruct H8 as [Hclosed H8].\n      split; auto.\n      apply repr_val_id_L_unchanged with (m := m2); eauto.\n      (* tinf_b disjoint from global *)  split; auto.\n      eapply correct_fundefs_unchanged_global.\n      eauto.\n      eapply store_globals_unchanged.\n      eauto.\n      intros.\n      specialize (Hglobals _ _ H9). destructAll; auto.\n    }\n\n    assert (Hrel_mem4 :  rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env (Eapp f t ys) rho m4 lenv). {\n      inv Hrel_mem3.\n      exists x.\n      assert (Mem.unchanged_on x m3 m4). {\n        destruct H1. eapply Mem.store_unchanged_on; eauto.\n        intros.\n        inv H1. destructAll. rewrite H10 in Hget_tinf; inv Hget_tinf. apply H11.\n      }\n      destructAll.\n      split; auto. intro. specialize (H4 x0).\n      destruct H4. \n      split. intro. apply H4 in H6.\n      destructAll.\n      exists x1. split; auto.\n      apply repr_val_id_L_unchanged with (m := m3); eauto. \n      intros. specialize (H5 _ _ _ _ H6 H7).\n      destruct H5. destruct H8 as [Hclosed H8].\n      split; auto.\n      apply repr_val_id_L_unchanged with (m := m3); eauto.\n      (* tinf_b disjoint from global *) split; auto.\n      eapply correct_fundefs_unchanged_global.\n      eauto.\n      eapply store_globals_unchanged.\n      eauto.\n      intros.\n      specialize (Hglobals _ _ H9). destructAll; auto.      \n    }\n    \n    assert (Hc_tinfo_m4 :  correct_tinfo p max_alloc lenv m4). {\n      eapply correct_tinfo_after_store.\n      eapply correct_tinfo_after_store.\n      apply Hc_tinfo_m2.\n      eauto.\n      eauto.\n    } \n\n    assert (exists b,\n               (repr_val_LambdaANF_Codegen_thm fenv finfo_env p rep_env (cps.Vfun (M.empty cps.val) fl f') m4 (Vptr b Ptrofs.zero)) /\\\n(*               Genv.find_symbol (globalenv p) f' = Some b /\\ *)\n               eval_expr (globalenv p) empty_env lenv m4\n                         (Ecast (var_or_funvar_f threadInfIdent nParam fenv finfo_env p f)\n                                (Tpointer\n                                   (mkFunTy threadInfIdent (Init.Nat.min (length ind) nParam)) noattr)) (Vptr b Ptrofs.zero)). {\n      inv Hrel_mem4. destruct H1. specialize (H3 f). destruct H3.\n      assert ( occurs_free (Eapp f t ys) f) by constructor. \n      specialize (H3 H5).\n      destruct H3. destruct H3. rewrite H3 in H. inv H.\n      inv H6. \n      - exists b. split; auto. \n        inv H14; econstructor; eauto.\n        unfold var_or_funvar_f. rewrite H13. \n        specialize (Hsym f). inv Hsym.\n        destruct (H6 (ex_intro _ b H13)). destruct x0. \n        unfold makeVar. rewrite H7. \n        specialize (HfinfoCorrect _ _ _ H7). inv HfinfoCorrect.   \n        destruct x0. rewrite H8.\n        econstructor. econstructor.     \n        constructor 2. apply M.gempty. eauto. constructor. constructor.\n        auto.\n      - admit. (* inv H8. exists b. split. auto. \n        econstructor; eauto.\n        unfold var_or_funvar_f. rewrite H. econstructor. econstructor.\n        eauto. constructor.*)\n    }\n    destruct H1 as [bf' [Hfind_f' Heval_f']]. \n    inv Hfind_f'.\n\n    \n    rewrite  Hfind_def_f' in H5; inv H5.\n    rewrite Hf_fenv in H6; inv H6.\n    \n    (* clear old assumptions about m and get them about m4 instead *)\n    clear Hload_fi0 Hload_fi1.\n    assert (Hrel_mem4' := Hrel_mem4).\n    destruct Hrel_mem4' as [Lm4 [Hrel_pm4 Hrel_rho_m4]].\n    assert (Hrel_rho_m4f := Hrel_rho_m4 f). \n    destruct Hrel_rho_m4f as [_  Hrel_fun_m4].\n    assert (Hsubval : subval_or_eq (Vfun rho' fl f') (Vfun rho' fl f')) by apply rt_refl.\n     \n    specialize (Hrel_fun_m4 rho' fl f' _ H Hsubval). \n    destruct Hrel_fun_m4 as [Hrepr_f_m4 [Hclosed_f_m4 Hfundef_f_m4]].\n    clear Hsubval.\n    destruct Hfundef_f_m4 as [finfom4 [tm4 [tm4' [vsm4 [e4 [Hbd_f' [Hget_finfo [hfundef_tag' Hfundef_f']]]]]]]].\n    rewrite Hfind_def_f' in Hbd_f'; inv Hbd_f'.\n    \n    destruct Hfundef_f' as [nm4 [lm4 [bm4 [fi_0_m4  [_ [_ [_ [_ [_ [Hfind_symbol_m4 [Hload_fi0 [Hload_fi1 [Hcorrect_alloc_m4 [Hgc_size_fi0m4 _]]]]]]]]]]]]]].\n    rewrite  Hfinfo_env_f' in Hget_finfo. inv Hget_finfo.\n    \n    rewrite Hfind_symbol in Hfind_symbol_m4. inv Hfind_symbol_m4.\n\n    assert (repr_asgn_fun_length : forall ys ind s,\n               repr_asgn_fun' argsIdent threadInfIdent nParam fenv finfo_env p ys ind s -> length ys = length ind). (* TODO : Move out *)\n    {\n      intro ys0. induction ys0; intros ind s' Hr; destruct ind; [ | inv Hr | inv Hr | ].\n      - reflexivity. \n      - simpl. apply f_equal. inv Hr. apply (IHys0 _ _ H8).\n    }\n    assert (ays_aind_length : length ays = length aind).\n    { eapply repr_asgn_fun_length. apply Hrepr. }\n    assert (bys_bind_length : length bys = length bind).\n    { eapply repr_call_vars_length1. rewrite bindEq.\n      rewrite firstn_length. rewrite Nat.min_comm. apply Hcall. }\n    \n    set (bvsm4 := firstn nParam vsm4).\n    set (avsm4 := skipn nParam vsm4).\n    assert (bvsm4Eq : bvsm4 = firstn nParam vsm4) by reflexivity.\n    assert (avsm4Eq : avsm4 = skipn nParam vsm4) by reflexivity.\n\n    assert (bys_bvsm4_length : length bys = length bvsm4).\n    {\n      rewrite bvsm4Eq. Set Printing All.\n      simpl. unfold var , cps.M.elt.\n      rewrite <- (HFirstnLength _ _ nParam _ _ Hlvs).\n      rewrite <- bindEq.\n      Unset Printing All. simpl.\n      apply bys_bind_length.\n    }\n\n    (* lenv_new is just lenv from fentry *)\n\n    remember (create_undef_temps (skipn nParam vars ++ gc_vars argsIdent allocIdent limitIdent caseIdent)) as lenv_new''.\n    \n    set (lenv_new' := mk_gc_call_env p bys bvsm4 lenv lenv_new'' Hbys bys_bvsm4_length).\n    assert (lenv_newEq' : lenv_new' = mk_gc_call_env p bys bvsm4 lenv lenv_new'' Hbys bys_bvsm4_length) by reflexivity.\n \n    set (lenv_new := Maps.PTree.set tinfIdent (Vptr tinf_b tinf_ofs) lenv_new').\n    assert (lenv_newEq : lenv_new = Maps.PTree.set tinfIdent (Vptr tinf_b tinf_ofs) lenv_new') by reflexivity.    \n    (* show that after the branch, some memory m5 will be correct and contain enough space to execute the body *) \n    (* need to construct the memory and environment that exists after the (potential) gc call \n    > every function has a code_info which points to the total number of alloc \n\n     *)\n    assert (Hc_alloc' : exists max_alloc',  correct_alloc e4 max_alloc') by apply e_correct_alloc.\n    destruct Hc_alloc' as [max_alloc' Hc_alloc'].\n\n    assert (rho' = M.empty _). { inv Hrepr_f_m4. reflexivity. inv H4. reflexivity. } rewrite H1 in *. clear H1.\n\n\n   \n    assert (Hvs := mem_of_asgn_exists_v Hmem_of_asgn Hget_args).\n    destruct Hvs as [avs7 Hvs7].\n\n    \n    assert (Hnd_vs0: NoDup vsm4). {\n      destruct Hrho_id as [Hrho_id1 Hrho_id2].\n      apply Hrho_id2 in H.\n      destruct H as [_ Hub].\n      inv Hub.\n      eapply shrink_cps_correct.ub_find_def_nodup; eauto.\n    }\n    assert (Hnoprot_vs0:  (forall x : positive, List.In x vsm4 -> ~ (is_protected_tinfo_id argsIdent allocIdent limitIdent x \\/ x = tinfIdent))). {\n                intros.\n                inv Hp_id.\n                intro.\n                eapply H3 with (y := x) in H.\n                apply H.\n                right. constructor.\n                eapply shrink_cps_correct.name_boundvar_arg; eauto.\n                inv H5.\n                apply is_protected_tinfo_weak; auto.\n                inList. }              \n\n    assert (Hnoargs_vs0: ~ List.In argsIdent vsm4).\n    {\n      intro.\n      eapply Hnoprot_vs0.\n      eauto.\n      left; inList.\n      reflexivity.\n    }\n\n    assert (Hnotinf_vs0: ~ List.In tinfIdent vsm4).\n    {\n      intro.\n      eapply Hnoprot_vs0.\n      eauto.\n      right.\n      reflexivity.\n    }\n\n(* TODO: do something with bvs7, lenv, lenv_new, bys, and bvsm4 *)\n    \n(*\n    assert (Hl_temp: length vsm4 = length vs7). { \n\n      eapply mem_of_asgn_v_length in Hvs7.\n      rewrite <- Hvs7.\n      auto.\n    } \n    assert (Hvs7_m4 : mem_after_asgn args_b args_ofs m4 aind avs7). {\n      assert (Hdj := disjointIdent).  \n      eapply mem_of_asgn_after. Print mem_of_asgn_after.\n      apply aindEq. apply aysEq. apply avs7eq.\n      eapply mem_of_asgn_v_store.\n      eapply mem_of_asgn_v_store.\n      eauto. eauto.\n      solve_nodup.\n      eauto.\n      solve_nodup.        \n    } *)\n    (* MAIN CHANGE: This is stepping through the function call, stitch together function arguments.\n               Need to update memory state proof to account for the reading/writing with args around gc call *)\n\n    (* \n    set (bind := firstn nParam locs).\n    assert (bindEq : bind = firstn nParam locs) by reflexivity.\n    assert (Hgc : exists s ,\n               match asgnAppVars'' argsIdent threadInfIdent ays aind fenv with\n               | Some bef =>\n                 match asgnFunVars' argsIdent bys bind with\n                 | Some aft =>\n                   Some\n                     (Sifthenelse\n                        (not\n                           (Ebinop Ole\n                                   (Ederef\n                                      (Evar finfo0 (Tarray LambdaANF_to_Clight.uval (Z.of_N (N.of_nat (length locs) + 2)) noattr))\n                                      LambdaANF_to_Clight.uval)\n                                   (sub\n                                      (Efield\n                                         (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr))\n                                                 (Tstruct threadInfIdent noattr)) limitIdent valPtr)\n                                      (Efield\n                                         (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr))\n                                                 (Tstruct threadInfIdent noattr)) allocIdent valPtr)) type_bool))\n                        (Ssequence\n                           (Ssequence bef\n                                      (Scall None\n                                             (Evar gcIdent\n                                                   (Tfunction\n                                                      (Tcons (Tpointer uval noattr)\n                                                             (Tcons (Tpointer (Tstruct threadInfIdent noattr) noattr) Tnil)) Tvoid\n                                                      {| cc_vararg := false; cc_unproto := false; cc_structret := false |}))\n                                             [Evar finfo0 (Tarray LambdaANF_to_Clight.uval (Z.of_N (N.of_nat (length locs) + 2)) noattr);\n                                              Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)])) aft) Sskip)\n                 | None => None\n                 end\n               | None => None\n               end = Some s). {\n     *) \n\n(*   \n    set (bvsm4 := firstn nParam vsm4).\n    assert (bvsm4Eq : bvsm4 = firstn nParam vsm4) by reflexivity. \n    assert(firstnLengthEq : forall {A B} n (l1 : list A) (l2 : list B), length l1 = length l2 -> length (firstn n l1) = length (firstn n l2)).\n    {\n      intros A B n l1. generalize n. clear n. induction l1; destruct l2; intros Heq; inv Heq. \n      + destruct n; reflexivity.\n      + destruct n. auto.\n        simpl.\n        apply f_equal. apply IHl1. auto.\n    }\n    assert (bindLengthEq : length bind = length bvsm4).\n    { \n      rewrite bindEq. rewrite bvsm4Eq.\n      apply firstnLengthEq. assumption.\n    } \n    assert(lengthAsgnFun : forall l1 l2, length l1 = length l2 -> exists s, asgnFunVars' argsIdent l1 l2 = Some s).\n    {\n      induction l1; intros l2 lEq; destruct l2; inv lEq.\n      - eexists. reflexivity.\n      - apply IHl1 in H3. inv H3.\n        eexists. simpl.\n        rewrite H1. reflexivity.\n    }\n    assert (HgcAsgn : exists gcAsgn, asgnFunVars' argsIdent bvsm4 bind = Some gcAsgn).\n    {\n      apply lengthAsgnFun. auto.\n    }\n    destruct HgcAsgn as [gcAsgn gcAsgnEq].\n \n    Forall (fun x : positive => exists v : Values.val, get_var_or_funvar p lenv x v) bvsm4\n    assert (Hasgn_gc_fun_mem :=  repr_asgn_fun_mem fu lenv p rho (Eapp f t ys) fenv max_alloc rep_env finfo_env ays aind s0 m Hsym Hrel_m Hc_tinfo' Hays Haind Haind_nodup Hrepr). *)\n    assert (Hgcbef : exists bef, asgnAppVars'' argsIdent threadInfIdent nParam (firstn nParam vsm4) (firstn nParam locs) fenv finfo_env = Some bef).\n    {\n      unfold gc_test' in H9. unfold reserve' in H9.\n      remember (asgnAppVars'' argsIdent threadInfIdent nParam (firstn nParam vsm4) (firstn nParam locs) fenv finfo_env) as bef.\n      assert (match bef with\n              | Some bef =>\n                match asgnFunVars' argsIdent (firstn nParam vsm4) (firstn nParam locs) with\n                | Some aft =>\n                  Some\n                    (Sifthenelse\n                       (not\n                          (Ebinop Ole (Ederef (Evar finfo0 (Tarray LambdaANF_to_Clight.uval (Z.of_N (N.of_nat (length locs) + 2)) noattr)) LambdaANF_to_Clight.uval)\n                                  (sub (Efield (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr)) limitIdent valPtr)\n                                       (Efield (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr)) allocIdent valPtr))\n                                  type_bool))\n                       (Ssequence\n                          (Ssequence bef\n                                     (Scall None\n                                            (Evar gcIdent\n                                                  (Tfunction (Tcons (Tpointer uval noattr) (Tcons (Tpointer (Tstruct threadInfIdent noattr) noattr) Tnil)) Tvoid\n                                                             {| cc_vararg := false; cc_unproto := false; cc_structret := false |}))\n                                            [Evar finfo0 (Tarray LambdaANF_to_Clight.uval (Z.of_N (N.of_nat (length locs) + 2)) noattr);\n                                             Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)])) aft) Sskip)\n                | None => None\n                end\n              | None => None\n              end = Some gccall).\n      { rewrite Heqbef. assumption. } \n      destruct bef.\n      + exists s0. auto.\n      + inv H1.\n    }\n    assert (Hgcaft : exists aft, asgnFunVars' argsIdent (firstn nParam vsm4) (firstn nParam locs) = Some aft).\n    {\n      unfold gc_test' in H9. unfold reserve' in H9.\n      remember (asgnFunVars' argsIdent (firstn nParam vsm4) (firstn nParam locs)) as aft.\n      assert (match asgnAppVars'' argsIdent threadInfIdent nParam (firstn nParam vsm4) (firstn nParam locs) fenv finfo_env with\n              | Some bef =>\n                match aft with\n                | Some aft =>\n                  Some\n                    (Sifthenelse\n                       (not\n                          (Ebinop Ole (Ederef (Evar finfo0 (Tarray LambdaANF_to_Clight.uval (Z.of_N (N.of_nat (length locs) + 2)) noattr)) LambdaANF_to_Clight.uval)\n                                  (sub (Efield (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr)) limitIdent valPtr)\n                                       (Efield (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr)) allocIdent valPtr))\n                                  type_bool))\n                       (Ssequence\n                          (Ssequence bef\n                                     (Scall None\n                                            (Evar gcIdent\n                                                  (Tfunction (Tcons (Tpointer uval noattr) (Tcons (Tpointer (Tstruct threadInfIdent noattr) noattr) Tnil)) Tvoid\n                                                             {| cc_vararg := false; cc_unproto := false; cc_structret := false |}))\n                                            [Evar finfo0 (Tarray LambdaANF_to_Clight.uval (Z.of_N (N.of_nat (length locs) + 2)) noattr);\n                                             Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)])) aft) Sskip)\n                | None => None\n                end\n              | None => None\n              end = Some gccall). \n      { rewrite Heqaft. assumption. }\n      destruct aft.\n      + exists s0. auto.\n      + destruct (asgnAppVars'' argsIdent threadInfIdent nParam (firstn nParam vsm4) (firstn nParam locs) fenv); inv H1.\n    }\n    destruct Hgcbef as [bef Heqbef].\n    destruct Hgcaft as [aft Heqaft].\n    \n    assert (Hgc : gc_test' argsIdent allocIdent limitIdent gcIdent threadInfIdent tinfIdent nParam finfo0 (N.of_nat (length locs)) vsm4 locs fenv finfo_env =\n            Some\n              (Sifthenelse\n                 (not\n                    (Ebinop Ole (Ederef (Evar finfo0 (Tarray LambdaANF_to_Clight.uval (Z.of_N (N.of_nat (length locs) + 2)) noattr)) LambdaANF_to_Clight.uval)\n                            (sub (Efield (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr)) limitIdent valPtr)\n                                 (Efield (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr)) allocIdent valPtr)) type_bool))\n                 (Ssequence\n                    (Ssequence bef\n                               (Scall None\n                                      (Evar gcIdent\n                                            (Tfunction (Tcons (Tpointer uval noattr) (Tcons (Tpointer (Tstruct threadInfIdent noattr) noattr) Tnil)) Tvoid\n                                                       {| cc_vararg := false; cc_unproto := false; cc_structret := false |}))\n                                      [Evar finfo0 (Tarray LambdaANF_to_Clight.uval (Z.of_N (N.of_nat (length locs) + 2)) noattr); Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)])) aft)\n                 Sskip)).\n    { unfold gc_test'. unfold reserve'. Set Printing All. simpl.\n      unfold var , cps.M.elt in Heqbef.\n      unfold var , cps.M.elt in Heqaft.\n      rewrite Heqbef. rewrite Heqaft.\n      Unset Printing All. simpl.\n      reflexivity.\n    }\n    assert (Hgccalleq : gccall = (Sifthenelse\n                 (not\n                    (Ebinop Ole (Ederef (Evar finfo0 (Tarray LambdaANF_to_Clight.uval (Z.of_N (N.of_nat (length locs) + 2)) noattr)) LambdaANF_to_Clight.uval)\n                            (sub (Efield (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr)) limitIdent valPtr)\n                                 (Efield (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr)) allocIdent valPtr)) type_bool))\n                 (Ssequence\n                    (Ssequence bef\n                               (Scall None\n                                      (Evar gcIdent\n                                            (Tfunction (Tcons (Tpointer uval noattr) (Tcons (Tpointer (Tstruct threadInfIdent noattr) noattr) Tnil)) Tvoid\n                                                       {| cc_vararg := false; cc_unproto := false; cc_structret := false |}))\n                                      [Evar finfo0 (Tarray LambdaANF_to_Clight.uval (Z.of_N (N.of_nat (length locs) + 2)) noattr); Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)])) aft)\n                 Sskip)).\n    {\n      rewrite Hgc in H10. inv H10. reflexivity.\n    }\n\n    assert (rel_mem_gc : rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env (Ehalt 1%positive) rho m4 lenv_new).\n    {\n      admit.\n    }\n\n    assert (Hbvsm4_nodup : NoDup bvsm4).\n    {\n      rewrite bvsm4Eq.\n      eapply NoDup_cons_l.\n      rewrite (firstn_skipn nParam vsm4).\n      assumption.\n    } \n\n    assert (Havsm4_nodup : NoDup avsm4).\n    {\n      rewrite avsm4Eq.\n      eapply NoDup_cons_r.\n      rewrite (firstn_skipn nParam vsm4).\n      assumption.\n    } \n   \n    assert (Hvsm4 : Forall (fun x : positive => exists v : Values.val, get_var_or_funvar p lenv_new x v) bvsm4).\n    {\n      rewrite lenv_newEq.\n      apply Forall_forall. intros.\n      assert (Hcorrect := proj1 (Forall_forall _ _) (mk_gc_call_env_correct p bys bvsm4 lenv lenv_new'' Hbys bys_bvsm4_length Hbvsm4_nodup) x H1).\n      rewrite <- lenv_newEq' in Hcorrect.\n      destruct Hcorrect as [z Hz].\n      exists z.\n      eapply get_var_or_funvar_proper; eauto.\n      unfold map_get_r_l. intros.\n      symmetry. apply M.gso. intros veq. inv veq.\n      rewrite bvsm4Eq in H3. apply HInFirstn in H3.\n      apply Hnotinf_vs0. assumption.\n    }\n\n    assert (Hc_tinfo_m4_new : correct_tinfo p max_alloc lenv_new m4).\n    {\n      admit.\n    }\n\n    assert (Hrepr_gc : repr_asgn_fun' argsIdent threadInfIdent nParam fenv finfo_env p bvsm4 bind bef).\n    {\n      admit.\n    }\n\n    (*\n    NEED:\n      rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env (Ehalt 1%positive) rho m4 lenv\n      correct_tinfo p max_alloc lenv_new m4     \n      Forall (fun x : positive => exists v : Values.val, get_var_or_funvar p lenv x v) bvsm4\n      repr_asgn_fun' argsIdent threadInfIdent nParam fenv p bvsm4 bind bef\n     *) \n\n    assert (Hasgn_fun_mem_bgc := repr_asgn_fun_mem fu lenv_new p rho (Ehalt 1%positive) fenv max_alloc rep_env finfo_env bvsm4 bind bef m4 Hsym HfinfoCorrect rel_mem_gc Hc_tinfo_m4_new Hvsm4 Hbind Hbind_nodup Hrepr_gc). \n    destruct Hasgn_fun_mem_bgc as [mgc [Hasgn_fun_mem_bgc [Hmem_of_asgn_bgc Hrel_mem_bgc]]]. \n    \n    assert (Hm_agc : exists magc lenv_new_agc,\n               clos_trans state (traceless_step2 (globalenv p))\n                          (State F\n                                 (Ssequence bef\n                                            (Scall None\n                                                   (Evar gcIdent\n                                                         (Tfunction (Tcons (Tpointer uval noattr) (Tcons (Tpointer (Tstruct threadInfIdent noattr) noattr) Tnil)) Tvoid\n                                                                    {| cc_vararg := false; cc_unproto := false; cc_structret := false |}))\n                                                   [Evar finfo0 (Tarray LambdaANF_to_Clight.uval (Z.of_N (N.of_nat (length locs) + 2)) noattr);\n                                                    Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)]))\n                                 (Kseq (Ssequence aft Sskip) (Kseq  (Ssequence (Ssequence (gc_set argsIdent allocIdent limitIdent threadInfIdent tinfIdent) asgn) body)\n                                                                    (Kcall None fu empty_env lenv k)))\n                                       empty_env lenv_new m4)\n                                 (State F\n                                        Sskip\n                                        (Kseq (Ssequence aft Sskip) (Kseq  (Ssequence (Ssequence (gc_set argsIdent allocIdent limitIdent threadInfIdent tinfIdent) asgn) body)\n                                                                           (Kcall None fu empty_env lenv k)))\n                                              empty_env lenv_new_agc magc) /\\\n                           same_tinf_ptr lenv_new lenv_new_agc /\\\n                           exists alloc_b alloc_ofs limit_ofs, \n                             deref_loc (Tarray uval maxArgs noattr) magc tinf_b\n                                       (Ptrofs.add tinf_ofs (Ptrofs.repr (int_size * 3)))\n                                       (Vptr args_b args_ofs) /\\\n                             Mem.load int_chunk magc tinf_b\n                                      (Ptrofs.unsigned tinf_ofs) = Some (Val.load_result int_chunk (Vptr alloc_b alloc_ofs)) /\\\n                             Mem.load int_chunk magc tinf_b\n                                      (Ptrofs.unsigned (Ptrofs.add tinf_ofs (Ptrofs.repr int_size))) = Some (Val.load_result int_chunk (Vptr alloc_b limit_ofs))).\n    {\n      admit.\n    }\n\n    destruct Hm_agc as [macg [lenv_new_agc [Hmem_agc [Hptr_agc [alloc_b_agc [alloc_ofs_agc [limit_ofs_agc [Hderef_agc [Htinf_ofs_agc H_tinf_ofs_size_agc]]]]]]]]].\n      \n    assert (Hm5 : exists m5 lenv_new',\n               clos_trans state (traceless_step2 (globalenv p))\n                          (State F\n                                 gccall\n                                 (Kseq  (Ssequence (Ssequence (gc_set argsIdent allocIdent limitIdent threadInfIdent tinfIdent) asgn) body)\n                                        (Kcall None fu empty_env lenv k))\n                                 empty_env lenv_new m4)\n                          (State F\n                                 Sskip\n                                 (Kseq (Ssequence (Ssequence (gc_set argsIdent allocIdent limitIdent threadInfIdent tinfIdent) asgn) body)\n                                       (Kcall None fu empty_env lenv k))\n                                 empty_env lenv_new' m5) /\\\n               same_tinf_ptr lenv_new lenv_new' /\\\n               exists alloc_b alloc_ofs limit_ofs vs7', \n\n                 deref_loc (Tarray uval maxArgs noattr) m5 tinf_b\n                           (Ptrofs.add tinf_ofs (Ptrofs.repr (int_size * 3)))\n                           (Vptr args_b args_ofs) /\\\n                 Mem.load int_chunk m5 tinf_b\n                              (Ptrofs.unsigned tinf_ofs) = Some (Val.load_result int_chunk (Vptr alloc_b alloc_ofs)) /\\\n                   Mem.load int_chunk m5 tinf_b\n                            (Ptrofs.unsigned (Ptrofs.add tinf_ofs (Ptrofs.repr int_size))) = Some (Val.load_result int_chunk (Vptr alloc_b limit_ofs)) /\\\n                   mem_after_asgn args_b args_ofs m5 (skipn nParam locs) (skipn nParam vs7') /\\\n                (* lenv_new' then gets the tinf ptr, and then the param_asgn *) (* TODO: say something about lenv_new' and firstn nParam *)\n                   (forall lenv_new'', lenv_param_asgn (M.set argsIdent (Vptr args_b args_ofs) (M.set limitIdent (Vptr alloc_b limit_ofs) (M.set allocIdent (Vptr alloc_b alloc_ofs) lenv_new'))) lenv_new'' (skipn nParam vsm4) (skipn nParam vs7') -> \n                rel_mem_LambdaANF_Codegen_id fenv finfo_env p rep_env e4 rho'' m5 lenv_new'' /\\\n                correct_tinfo p max_alloc' lenv_new'' m5)).\n    { (*\n      unfold gc_test' in H9. unfold reserve' in H9. simpl in H9.\n      unfold gc_test'. \n      unfold reserve'.\n      remember  (LambdaANF_to_Clight.not\n               (Ebinop Ole\n                  (Ederef\n                     (Evar finfo0\n                        (Tarray uval (Z.of_N (N.of_nat (length locs) + 2)) noattr)) uval)\n                  (LambdaANF_to_Clight.sub\n                     (Efield\n                        (Ederef\n                           (Etempvar tinfIdent\n                              (Tpointer (Tstruct threadInfIdent noattr) noattr))\n                           (Tstruct threadInfIdent noattr)) limitIdent valPtr)\n                     (Efield\n                        (Ederef\n                           (Etempvar tinfIdent\n                              (Tpointer (Tstruct threadInfIdent noattr) noattr))\n                           (Tstruct threadInfIdent noattr)) allocIdent valPtr)) type_bool)) as gc_test.\n      \n      unfold LambdaANF_to_Clight.not in *.\n       *)  \n      rewrite Hgccalleq.   \n      eexists. eexists.   \n      repeat weak_split. \n      - remember  (not (Ebinop Ole (Ederef (Evar finfo0 (Tarray LambdaANF_to_Clight.uval (Z.of_N (N.of_nat (length locs) + 2)) noattr)) LambdaANF_to_Clight.uval)\n                               (sub (Efield (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr)) limitIdent valPtr)\n                                    (Efield (Ederef (Etempvar tinfIdent (Tpointer (Tstruct threadInfIdent noattr) noattr)) (Tstruct threadInfIdent noattr)) allocIdent valPtr)) type_bool)) as gc_test.\n        unfold LambdaANF_to_Clight.not in *.\n\n        assert (Hgc_test : exists v,  eval_expr (globalenv p) empty_env lenv_new m4 gc_test v /\\ exists b, bool_val v (typeof gc_test) m4 = Some b).\n        {\n          rewrite Heqgc_test.\n          assert (exists v, match\n                       Val.of_bool (negb (Ptrofs.ltu (Ptrofs.divs (Ptrofs.sub limit_ofs alloc_ofs) (Ptrofs.repr int_size)) (Ptrofs.repr fi_0_m4)))\n                     with\n                     | Vint n => Some (Val.of_bool (Int.eq n Int.zero))\n                     | _ => None\n                     end = Some v).  { \n            destruct (negb (Ptrofs.ltu (Ptrofs.divs (Ptrofs.sub limit_ofs alloc_ofs) (Ptrofs.repr int_size)) (Ptrofs.repr fi_0_m4))); eexists; reflexivity.\n          }\n          destruct H1 as [vb Hvb].\n          rewrite Hfinfo_env_f' in H7. inv H7.\n          assert (Hnd := disjointIdent).\n          eexists. split. \n          - econstructor. econstructor. econstructor. constructor. econstructor. constructor 2. apply M.gempty. eauto.\n            constructor. reflexivity. econstructor 1. constructor. eauto.\n            \n            econstructor. econstructor. econstructor. econstructor. constructor. constructor. apply M.gss. constructor 3. reflexivity.\n            reflexivity. eauto. rewrite  Htinfident_members. apply limitIdent_delta.  \n            econstructor 1. reflexivity.\n            eapply Mem.load_store_same. eauto.\n\n            econstructor. econstructor. econstructor. econstructor. constructor. apply M.gss. constructor 3. reflexivity. reflexivity. eauto.\n            rewrite Htinfident_members. apply allocIdent_delta. econstructor 1. reflexivity.\n            simpl. rewrite Ptrofs.add_zero. erewrite Mem.load_store_other.\n            eapply Mem.load_store_same. eauto. eauto.\n            right.\n            assert (Het := Ptrofs.unsigned_add_either tinf_ofs (Ptrofs.repr int_size)). destruct Het. rewrite H1. left. simpl. rewrite Ptrofs.unsigned_repr. reflexivity.\n            rewrite ptrofs_mu. chunk_red; archi_red; solve_uint_range; omega.\n\n            right. rewrite H1.  rewrite Ptrofs.unsigned_repr. fold int_size.\n            assert (int_size - Ptrofs.modulus + int_size < 0)%Z. 2: omega.\n            unfold Ptrofs.modulus; unfold Ptrofs.wordsize;  unfold Wordsize_Ptrofs.wordsize;\n              chunk_red; archi_red; simpl; omega. \n            rewrite ptrofs_mu; chunk_red; archi_red; solve_uint_range; omega.\n            \n            \n            simpl. unfold sem_sub. simpl. rewrite load_ptr_or_int. rewrite load_ptr_or_int. rewrite Coqlib.peq_true. reflexivity. reflexivity. reflexivity.\n            simpl.\n            assert (\n                sem_cmp Cle (make_vint fi_0_m4) uval\n                        (Vptrofs (Ptrofs.divs (Ptrofs.sub limit_ofs alloc_ofs) (Ptrofs.repr (sizeof (prog_comp_env p) uval))))\n                        (Tpointer LambdaANF_to_Clight.val {| attr_volatile := false; attr_alignas := None |}) m4 =\n                Some (Val.of_bool (negb (Ptrofs.ltu (Ptrofs.divs (Ptrofs.sub limit_ofs alloc_ofs) (Ptrofs.repr int_size)) (Ptrofs.repr fi_0_m4))))).\n            {\n              unfold sem_cmp. simpl. chunk_red; archi_red; simpl; unfold cmp_ptr; archi_red; unfold Val.cmplu_bool; unfold Vptrofs; archi_red; simpl. unfold Int64.ltu. unfold Ptrofs.to_int64. rewrite Int64.unsigned_repr.  rewrite Int64.unsigned_repr.\n              unfold Ptrofs.ltu. unfold Ptrofs.of_int64.  rewrite ptrofs_of_int64. reflexivity. unsigned_ptrofs_range.\n              unsigned_ptrofs_range.\n\n              unfold Int.ltu. unfold Ptrofs.to_int. rewrite Int.unsigned_repr. rewrite Int.unsigned_repr.\n              unfold Ptrofs.ltu. unfold Ptrofs.of_intu. unfold Ptrofs.of_int. rewrite ptrofs_of_int. reflexivity. auto.\n              unsigned_ptrofs_range.\n              unsigned_ptrofs_range.\n            } apply H1. \n            \n            simpl. unfold sem_notbool. unfold bool_val. simpl.\n            destruct (Val.of_bool (negb (Ptrofs.ltu (Ptrofs.divs (Ptrofs.sub limit_ofs alloc_ofs) (Ptrofs.repr int_size)) (Ptrofs.repr fi_0_m4))));\n              try (solve [inv Hvb]). simpl. rewrite Bool.negb_involutive. apply Hvb.\n            \n          - destruct (negb (Ptrofs.ltu (Ptrofs.divs (Ptrofs.sub limit_ofs alloc_ofs) (Ptrofs.repr int_size)) (Ptrofs.repr fi_0_m4))); eexists; inv Hvb; reflexivity.\n        }   \n         \n        destruct Hgc_test as [gc_test_v [Hgc_test_v [gc_test_b Hgc_test_b]]].\n        (* give the gc_test inequality with Z ops *)\n        (* Ederef evaluated to the old limit_ofs and alloc_ofs *)\n        assert (Hgc_case : (((Ptrofs.unsigned limit_ofs - Ptrofs.unsigned alloc_ofs) / int_size) <?  max_alloc' = gc_test_b)%Z).\n        {\n          \n          subst.        \n          simpl in Hgc_test_b.\n          unfold bool_val in Hgc_test_b. simpl in Hgc_test_b.\n \n          (* * get the value of gc_test_v *)\n          destruct gc_test_v; inv Hgc_test_b.  \n   \n          inv Hgc_test_v.  2: inv H1. \n          inv H6. 2: inv H1. \n          inv H14. \n          inv H1. inv H14. inv H1. rewrite M.gempty in H17; inv H17.\n          inv H15. 2: inv H1.\n\n          inv H22.  inv H21.\n \n\n          assert (H_dj := disjointIdent).\n          inv H1. 2: inv H26.\n          inv H24. rewrite <- H15 in *. clear H15.             \n          \n          inv H6. 2: inv H26. inv H24.\n          rewrite <- H6 in *; clear H6. \n          rewrite Hget_tinfident in H29; inv H29.\n          rewrite Hget_tinfident in H27; inv H27.\n          rewrite Htinfident_members in *. simpl in H28.\n          rewrite allocIdent_delta in H28. inv H28.  \n          rewrite limitIdent_delta in H30; inv H30.\n \n          inv H21. inv H1. inv H6. inv H1. inv H15. clear H15.\n          inv H22. inv H1. inv H6. inv H1. inv H15. clear H15.\n          inv H25. 2: inv H1. rewrite lenv_newEq in *.\n          rewrite M.gss in H17; inv H17.\n          \n          inv H24. 2: inv H1. rewrite M.gss in H17; inv H17.\n          inv H5; inv H1.\n          inv H14; inv H1.\n          \n          \n          unfold Mem.loadv in H5. \n          erewrite Mem.load_store_same in H5; eauto.\n          simpl in H5. inv H5. \n\n          unfold Mem.loadv in H6.\n          erewrite Mem.load_store_other in H6; eauto.\n          rewrite Ptrofs.add_zero in H6. \n          erewrite Mem.load_store_same in H6; eauto. inv H6.\n          2: { right. rewrite Ptrofs.add_zero. simpl.\n               assert (Het := Ptrofs.unsigned_add_either ofs2 (Ptrofs.repr int_size)). destruct Het.\n               rewrite H1. left. rewrite Ptrofs.unsigned_repr. unfold Mptr; chunk_red; archi_red; omega. rewrite ptrofs_mu; chunk_red; archi_red; solve_uint_range; omega. \n               right. rewrite H1. rewrite Ptrofs.unsigned_repr.\n               fold int_size.\n               assert (int_size - Ptrofs.modulus + int_size < 0)%Z. 2: omega.\n               unfold Ptrofs.modulus; unfold Ptrofs.wordsize;  unfold Wordsize_Ptrofs.wordsize;\n                 chunk_red; archi_red; simpl; omega. \n               rewrite ptrofs_mu; chunk_red; archi_red; solve_uint_range; omega.\n               }\n             \n\n             (* get the value of max_alloc in tinfo *)\n             rewrite Hfinfo_env_f' in H7; inv H7.\n               rewrite Hfind_symbol in H20 ; inv H20.\n               \n               inv H4. inv H1. 2: inv H5.\n               inv H3; inv H1.\n               unfold int_chunk in *.\n               assert\n                 (Some v0 =  Some (make_vint fi_0_m4) ).\n               chunk_red; archi_red; simpl in *; rewrite Hload_fi0 in H4; auto.\n               clear H4. inv H1. \n               \n               clear H5.\n\n               \n               assert (max_alloc' = fi_0_m4).\n               unfold correct_alloc in *; subst; auto. subst.\n\n               simpl in H16.\n               simpl in H23.  unfold sem_sub in H23; simpl in H23.\n               rewrite load_ptr_or_int in H23; [ | auto].\n               rewrite load_ptr_or_int in H23; [ | auto].\n               rewrite Coqlib.peq_true in H23.\n               assert ((Coqlib.proj_sumbool (Coqlib.zlt 0 (sizeof (prog_comp_env p) uval)) &&\n                                            Coqlib.proj_sumbool (Coqlib.zle (sizeof (prog_comp_env p) uval) Ptrofs.max_signed))%bool = true). { rewrite ptrofs_ms. unfold sizeof in *; chunk_red; archi_red; reflexivity. } \n                                                                                                                                              rewrite H1 in H23. inv H23. clear H1.\n               assert (\n                   sem_cmp Cle (make_vint fi_0_m4) LambdaANF_to_Clight.uval (Vptrofs (Ptrofs.divs (Ptrofs.sub limit_ofs alloc_ofs) (Ptrofs.repr (sizeof (prog_comp_env p) uval)))) valPtr m4 =\n                   Some (Val.of_bool (negb (Ptrofs.ltu (Ptrofs.divs (Ptrofs.sub limit_ofs alloc_ofs) (Ptrofs.repr int_size)) (Ptrofs.repr fi_0_m4))))).\n               {\n                 unfold sem_cmp. simpl. chunk_red; archi_red; simpl; unfold cmp_ptr; archi_red; unfold Val.cmplu_bool; unfold Vptrofs; archi_red; simpl. unfold Int64.ltu. unfold Ptrofs.to_int64. rewrite Int64.unsigned_repr.  rewrite Int64.unsigned_repr.\n                 unfold Ptrofs.ltu. unfold Ptrofs.of_int64.  rewrite ptrofs_of_int64. reflexivity. unsigned_ptrofs_range.\n                 unsigned_ptrofs_range.\n\n                 unfold Int.ltu. unfold Ptrofs.to_int. rewrite Int.unsigned_repr. rewrite Int.unsigned_repr.\n                 unfold Ptrofs.ltu. unfold Ptrofs.of_intu. unfold Ptrofs.of_int. rewrite ptrofs_of_int. reflexivity. auto.\n                 unsigned_ptrofs_range.\n                 unsigned_ptrofs_range.\n               }\n               Set Printing All. simpl. rewrite H16 in H1.\n               Unset Printing All. simpl. inv H1.\n                 \n               simpl in H8. rewrite sem_notbool_val in H8. \n               rewrite Bool.negb_involutive in H8. simpl in H8.\n               clear H16.\n               unfold Ptrofs.ltu in *. unfold Ptrofs.sub in *.\n               unfold Ptrofs.divs in *.\n               \n               rewrite Ptrofs.signed_repr with (z := int_size%Z) in H8.\n               rewrite Ptrofs.signed_repr in H8.\n               2:{ split.\n                   rewrite <- Z.le_add_le_sub_l. etransitivity. 2: eauto.\n                   unfold Ptrofs.min_signed.  \n                   inv Hc_alloc.    unfold Ptrofs.half_modulus. unfold Ptrofs.modulus. simpl. unfold Ptrofs.wordsize. unfold Wordsize_Ptrofs.wordsize. chunk_red; archi_red; simpl; omega. \n                   etransitivity; eauto. unfold gc_size; unfold Ptrofs.max_signed. unfold Ptrofs.half_modulus. unfold Ptrofs.modulus.  unfold Ptrofs.wordsize. unfold Wordsize_Ptrofs.wordsize. chunk_red; archi_red; simpl; omega. } \n                 2:unfold Ptrofs.min_signed; unfold Ptrofs.max_signed; unfold Ptrofs.half_modulus;  unfold Ptrofs.modulus;  unfold Ptrofs.wordsize; unfold Wordsize_Ptrofs.wordsize; chunk_red; archi_red; simpl; omega. \n                   rewrite Ptrofs.unsigned_repr in H8. \n                   rewrite Ptrofs.unsigned_repr in H8.\n                   rewrite  Zquot.Zquot_Zdiv_pos in H8.\n                   destruct  ((Ptrofs.unsigned limit_ofs - Ptrofs.unsigned alloc_ofs) / int_size <?  fi_0_m4)%Z eqn: Hcase.\n                   (* true *)\n                   apply Z.ltb_lt in Hcase.\n                   rewrite Coqlib.zlt_true in H8 by auto. simpl in H8. inv H8.\n                   reflexivity. \n                   (* false *)\n                   apply Z.ltb_ge in Hcase.\n                   apply Z.le_ge in Hcase.\n                   rewrite Coqlib.zlt_false in H8 by auto.\n                   inv H8. reflexivity.\n                   (* bounds *) \n                   apply Zle_minus_le_0. unfold int_size in *. etransitivity; eauto.\n                   inv Hc_alloc.\n                   simpl. chunk_red; omega. chunk_red; omega. \n                   (* Assumption that max_allocs is smaller than gc_size -- add this to correct_fundef_info *)\n                   assert (  (0 <= fi_0_m4)%Z) by (inv Hcorrect_alloc_m4; apply Zle_0_nat).\n                   split. auto.\n                   unfold gc_size in *. rewrite ptrofs_mu. simpl in Hgc_size_fi0m4. etransitivity. etransitivity. 2: apply Hgc_size_fi0m4. chunk_red; omega. chunk_red; archi_red; solve_uint_range; simpl; omega.\n\n                   split. apply Zquot.Z_quot_pos.\n                   apply Zle_minus_le_0. unfold int_size in *. etransitivity; eauto.\n                   inv Hc_alloc.\n                   simpl. chunk_red; omega. chunk_red; omega.\n                   apply Z.quot_le_upper_bound. chunk_red; omega.\n                   assert  (Ptrofs.max_unsigned <= int_size * Ptrofs.max_unsigned)%Z. assert (0 <= Ptrofs.max_unsigned)%Z. etransitivity. 2: apply ptrofs_mu_weak. unfold Int.max_unsigned; simpl; omega. chunk_red; omega.\n                   etransitivity; eauto.\n                   \n                   }\n\n        destruct gc_test_b.\n      (* two cases *)\n      (** 1) not enough space in the nursery for body, GC call *)\n                 \n      *   (* done - modify gc_inv to account for new lenv and additional restriction on args*)\n        rewrite Hfinfo_env_f' in H7. inv H7.\n        destruct Hpinv_gc as [b_gcPtr [name_gc [sg_gc [Hfind_gc_ptr [Hfind_gc_funct Hinv_gc]]]]].\n        \n        assert (@rel_mem_asgn fenv finfo_env p rep_env args_b args_ofs m4 Lm4 (skipn nParam vs) aind avs7). {\n          assert (Hdj := disjointIdent). \n          assert (Hmem_of_asgn_m4: mem_of_asgn_v args_b args_ofs p lenv m4 ays aind avs7). \n          eapply mem_of_asgn_v_store.\n          eapply mem_of_asgn_v_store.\n          eauto. eauto. solve_nodup.\n          eauto. solve_nodup.\n          eapply rel_mem_of_asgn; eauto. \n          intros. \n          assert (Hskipn_get_list : forall {A} n l1 (l2 : list A) rho,\n                                        get_list l1 rho = Some l2 -> get_list (skipn n l1) rho = Some (skipn n l2)). (* TODO : Move out *)\n          {\n            intros A. induction n; intros. auto.\n            destruct l1 , l2. \n            - reflexivity.\n            - inv H1.  \n            - simpl in H1.\n              repeat match_case in H1.\n            - simpl in H1.\n              repeat match_case in H1.\n              simpl. apply IHn; auto.\n              inv H1. assumption.\n          }\n          rewrite aysEq.\n          apply Hskipn_get_list. eauto. intros.\n          assert (occurs_free (Eapp f tm4' ys) x). constructor. eauto. \n          specialize (Hrel_rho_m4 x). destruct Hrel_rho_m4 as [Hrel_mg1 Hrel_mg2].\n          specialize (Hrel_mg1 H3).\n          destruct Hrel_mg1 as [v6 [Hgv6 Hv6_repr]].\n          exists v6. split; auto. \n        }          \n         \n        assert ( deref_loc (Tarray uval maxArgs noattr) m4 tinf_b (Ptrofs.add tinf_ofs (Ptrofs.repr (3 * int_size)))\n                           (Vptr args_b args_ofs)). {\n          destruct Hc_tinfo_m4. \n          destructAll.\n          rewrite H14 in  Hget_args; inv Hget_args.\n          rewrite H20 in  Hget_tinf; inv Hget_tinf.\n          eauto.\n        }   \n        \n        specialize (Hinv_gc _ _ _ _ _ _ _  _ _   _ _ _ _ _ _ _ H1 Hget_tinf  Hload_fi0  Hgc_size_fi0m4 H3).\n        \n        destruct Hinv_gc as [gc_vret [m5 [alloc_b' [alloc_ofs' [limit_ofs' [L' [vs7' [Hinv_gc [Hderef_alloc' [Hderef_limit' [Hderef_args' [Hrel_mem_asgn' [Hrel_mem_unchanged' [Hprotected_L' Hcorrect_tinfo']]]]]]]]]]]]]]. (* I'M HERE *)\n        eexists. eexists. split.\n        eapply t_trans.\n        constructor. econstructor. eauto. eauto. \n        simpl. \n        \n\n        \n        (* true branch -> call to gc *)\n        eapply t_trans.\n        constructor. econstructor. reflexivity. eauto.\n        econstructor. \n        apply eval_Evar_global. apply M.gempty. eauto.\n        simpl. constructor. simpl. constructor.         \n        econstructor. econstructor. constructor 2.\n        apply M.gempty.  eauto. \n        constructor. reflexivity. simpl. reflexivity.\n        econstructor. constructor.\n        assert (Hdj:=disjointIdent).\n        rewrite M.gss. reflexivity.\n        reflexivity. constructor.\n        eauto. simpl. reflexivity.\n\n        eapply t_trans. \n        constructor.\n        eapply step_external_function.\n        eauto.\n\n        constructor. constructor.\n\n        split. simpl. reflexivity.\n        exists alloc_b', alloc_ofs', limit_ofs', vs7'.\n        split. auto. split.          \n        inv Hderef_alloc' ; try (inv H6). inv H5. auto.\n        split. inv Hderef_limit'; try (inv H6). inv H5; auto.\n\n        split.\n        eapply rel_mem_after_asgn; eauto.\n        intros.\n        assert (map_get_r_l Values.val [argsIdent; limitIdent; allocIdent; tinfIdent]\n                            (M.set argsIdent (Vptr args_b args_ofs)\n                                   (M.set limitIdent (Vptr alloc_b' limit_ofs')\n                                          (M.set allocIdent (Vptr alloc_b' alloc_ofs')\n                                                 (Maps.PTree.set tinfIdent (Vptr tinf_b tinf_ofs) (M.empty Values.val))))) lenv_new''). {\n          assert (H_nodup := disjointIdent).\n          eapply lenv_param_asgn_map with (l := [argsIdent; limitIdent; allocIdent; tinfIdent]) in H5.\n          \n          intro. intro. rewrite <- H5.\n          2: auto.\n          inv H6. rewrite M.gss. rewrite M.gss. reflexivity.\n          inv H7. clear H6. rewrite M.gso. rewrite M.gss. rewrite M.gso. rewrite M.gss.\n          reflexivity. \n          solve_nodup. solve_nodup.\n          inv H6. clear H7. rewrite M.gso by solve_nodup. rewrite M.gso by solve_nodup. rewrite M.gss.\n          rewrite M.gso by solve_nodup. rewrite M.gso by solve_nodup. rewrite M.gss. reflexivity.\n          inv H7. clear H6.\n          rewrite M.gso by solve_nodup. rewrite M.gso by solve_nodup. rewrite M.gso by solve_nodup. rewrite M.gss.\n          rewrite M.gso by solve_nodup. rewrite M.gso by solve_nodup. rewrite M.gso by solve_nodup. simpl. rewrite M.gss. reflexivity.\n          inv H6.\n          split. intro. intro. destruct H6. apply Hnoprot_vs0 in H6. apply H6. inv H7. left. constructor 2. auto.\n          inv H8. left. constructor 2. auto. inv H7. left. constructor. auto. inv H8. auto. inv H7.            \n        }\n        split.\n      * (* rel_mem m5 *)\n        exists L'.\n\n        assert (Hug_m45: unchanged_globals p m4 m5). {\n          intro.\n          intros. symmetry.\n          eapply Mem.load_unchanged_on_1.\n          eauto. destruct Hc_tinfo_m4. destructAll. apply H27 in H7. destructAll.\n          eapply Mem.valid_access_valid_block. eauto. (* any block in globalenv is valid, and that GC preserve those blocks *)\n          intros. simpl. split.\n          inv Hrel_pm4. destructAll.\n          rewrite  Hget_args in H18; inv H18.\n          rewrite Hget_alloc in H12; inv H12. eapply H22.\n          apply H7.\n          inv  Hprotected_L'. destructAll.\n          rewrite M.gss in H18. inv H18.\n          assert (Hnd := disjointIdent).\n          rewrite M.gso in H20 by solve_nodup.\n          rewrite M.gso in H20 by solve_nodup.\n          rewrite M.gso in H20 by solve_nodup.\n          rewrite M.gss in H20. inv H20.\n          split.\n          eapply H22. eauto.\n          inv Hc_tinfo'. destructAll.\n          apply H35 in H7. destructAll. rewrite H30 in Hget_tinf. inv Hget_tinf. eauto.\n        }\n\n\n        split.          \n        eapply protected_not_in_L_proper; eauto. split.\n        { (* rel_mem of *)\n          intros.\n          (* e4 is closed under  (name_in_fundefs fl + vsm4) so x is in rho'' *)\n          assert (Hx_in: (In _ (Ensembles.Union _  (FromList vsm4) (name_in_fundefs fl)) x)). {\n            eapply closed_val_fun; eauto.\n          }\n          assert (Hx_vsm4: decidable (List.In x vsm4)). apply In_decidable. apply shrink_cps_correct.var_dec_eq.  \n          inv Hx_vsm4. \n          + (* x in vsm4 *)\n            assert (Hx_rho'' := get_set_lists_In_xs _ _ _ _ _ H8 H2). destruct Hx_rho''. exists x0. split; auto.\n            assert (Hx_in_rho := in_rho_entry _ _ _ _ _ _ H2  Hnd_vs0  H12). destruct Hx_in_rho.\n            2: exfalso; destructAll; auto.\n            destruct H15. destruct H15. \n            assert (H_x0_vs := nthN_In _ _ _ H16). \n            specialize ( H5 x). destruct H5. specialize (H5 _ H15).\n            \n            assert (Hx_rho_x_val := get_list_nth_get' _ _ _ _ _ _ H0 H16). destruct Hx_rho_x_val as [y4 [Hy4_ys Hy4_rho]].\n            \n            specialize (Hrel_rho_m4 y4). destruct (Hrel_rho_m4). \n            assert (occurs_free (Eapp f tm4 ys) y4). constructor. apply nthN_In in Hy4_ys; auto. apply H18 in H20.\n            destruct H20. destruct H20. rewrite Hy4_rho in H20. inv H20.\n            assert (Genv.find_symbol (Genv.globalenv p) x = None). {\n              inv Hf_id. eapply H22. apply H.\n              eapply  Bound_FVfun. left. eauto. eauto.\n            }\n            assert (exists v7, nthN vs7' x1 = Some v7). \n            eapply nthN_length. eapply OrdersEx.Nat_as_OT.eq_le_incl. eapply rel_mem_asgn_length; eauto. \n            eauto. destruct H22 as [v7 Hv7_vs7].\n            econstructor. eauto. erewrite Hv7_vs7 in H5. apply H5.\n            assert (Hx2v7 := rel_mem_asgn_nthN   Hrel_mem_asgn' H16 Hv7_vs7). auto.\n          + (* x in fl *)\n            inv Hx_in. exfalso; auto.\n            eapply set_lists_not_In in H2. 2: eauto.\n            rewrite def_funs_eq in H2; auto. eexists. split; eauto.\n            assert (subval_or_eq  (Vfun (M.empty cps.val) fl x) (Vfun (M.empty cps.val) fl f')). constructor. eapply dsubval_fun.  auto. destruct (Hrel_rho_m4 f). specialize (H17 _ _ _ _  H H15). destruct H17. inv H17.\n\n            econstructor. apply H21. inv H26.\n            econstructor; eauto. \n            (* impossible, functions not bound *)\n            inv H21. rewrite H26 in H19. inv H19.              \n        }\n        { (* rel_mem fun *)\n          intros.\n\n\n          \n          assert (Hin := in_rho_entry _ _ _ _ _ _ H2 Hnd_vs0 H7).\n          \n          destruct Hin.\n          + (* x is from vs0 *)\n            destruct H12.\n            destruct H12.\n            apply nthN_In in H15.\n            apply (get_list_In_val _ _ _  _ H0) in H15.\n            destruct H15. destruct H15.\n\n            \n            specialize (Hrel_rho_m4 x1). \n            destruct Hrel_rho_m4.                     \n            specialize (H18 _ _ _ _ H16 H8).\n            destruct H18 as [Hrel_m421 Hrel_m422].\n            split.\n          - inv Hrel_m421.\n            inv H26. econstructor; eauto.\n            econstructor; eauto.\n            (* imposible since function not bound *)\n            inv H20. rewrite H27 in H18. inv H18.\n          - destruct  Hrel_m422.  split. auto. eapply correct_fundefs_unchanged_global; eauto.\n\n            + (* x is from fl *) \n              destructAll.\n              specialize (Hrel_rho_m4 f). destruct Hrel_rho_m4 as [Hrel_m41 Hrel_m42].\n              assert (    exists l,  (Vfun rho'0 fds f0) = Vfun  (M.empty cps.val) fl l /\\ name_in_fundefs fl l).\n              eapply subval_fun.                     eapply find_def_name_in_fundefs; eauto. auto. destruct H16. destruct H16. inv H16.\n              assert (subval_or_eq (Vfun (M.empty cps.val) fl x3) (Vfun (M.empty cps.val) fl f')). \n              constructor. constructor. auto.                                       \n              specialize (Hrel_m42 _ _ _ _ H H16). destruct Hrel_m42 as [Hrel_m421 [Hrel_closed_m42 Hrel_m422]].\n              \n              split.\n          - inv Hrel_m421.\n            inv H25. econstructor; eauto.\n            econstructor; eauto.\n            (* imposible since function not bound *)\n            inv H20. rewrite H26 in H18. inv H18.\n          - split; auto. eapply correct_fundefs_unchanged_global; eauto.                               \n        }\n        \n      *             (* correct_tinfo m5 *)            \n        assert ( max_alloc' = fi_0_m4).\n        inv Hc_alloc'; inv Hcorrect_alloc_m4.\n        reflexivity. \n        eapply correct_tinfo_proper. rewrite H7. eauto.\n        eauto.\n\n\n\n\n           \n      (** 2) enough space in the nursery, so m5 = bindings + m4 *)\n      - \n        assert (Hlenv_asgn := e_lenv_param_asgn_i  vsm4 lenv_new vs7 Hl_temp Hnd_vs0).\n        clear Hl_temp.\n        destruct Hlenv_asgn as [lenv_new' Hlenv_new']. \n        exists m4, lenv_new.\n        split.\n        evar (e:statement). replace Sskip with e at 2.\n        eapply t_step.  eapply step_ifthenelse. unfold  LambdaANF_to_Clight.uval in *; unfold  LambdaANF_to_Clight.val in *; unfold val in *; unfold uval in *. rewrite <-   Heqgc_test. \n        eauto.\n        unfold  LambdaANF_to_Clight.uval in *; unfold  LambdaANF_to_Clight.val in *; unfold val in *; unfold uval in *. rewrite <-   Heqgc_test.  \n        eauto. reflexivity.\n        split. \n        reflexivity. exists alloc_b, alloc_ofs, limit_ofs, vs7.\n        split. inv Hc_tinfo_m4. destructAll. rewrite H12 in Hget_args; inv Hget_args. rewrite H18 in Hget_tinf; inv Hget_tinf. unfold int_chunk. simpl.  auto.\n        split.\n        erewrite Mem.load_store_other.\n        eapply Mem.load_store_same. eauto.  eauto.\n        right.\n        assert (Het := Ptrofs.unsigned_add_either tinf_ofs (Ptrofs.repr int_size)). destruct Het.\n        rewrite H1. left.  rewrite Ptrofs.unsigned_repr. unfold Mptr; chunk_red; archi_red; omega. rewrite ptrofs_mu; chunk_red; archi_red; solve_uint_range; omega.  \n        right. rewrite H1. rewrite Ptrofs.unsigned_repr.\n            fold int_size.\n            assert (int_size - Ptrofs.modulus + int_size < 0)%Z. 2: omega.\n            unfold Ptrofs.modulus; unfold Ptrofs.wordsize;  unfold Wordsize_Ptrofs.wordsize;\n        chunk_red; archi_red; simpl; omega. \n            rewrite ptrofs_mu; chunk_red; archi_red; solve_uint_range; omega. \n        split.  \n        eapply Mem.load_store_same. eauto. split; auto.\n        intros. \n        split. \n        + (* destruct Hrel_mem4 as [Lm4' [Hp_Lm4' Hrel_mem4]]. *)\n           exists Lm4.\n            split.\n            * apply lenv_param_asgn_rel in Hlenv_new'; auto. \n              eapply protected_not_in_L_asgn. 2: eauto.\n              inv Hrel_pm4.\n              destructAll.\n              rewrite H4 in Hget_alloc; inv Hget_alloc.\n              rewrite H6 in Hget_limit; inv Hget_limit.\n              rewrite H15 in Hget_tinf; inv Hget_tinf.\n              rewrite H7 in Hget_args; inv Hget_args.\n              assert (Hdj := disjointIdent). \n              do 7 eexists. repeat (split; eauto).\n              rewrite M.gso. rewrite M.gso. rewrite M.gss. reflexivity. \n              solve_nodup.  solve_nodup.\n              rewrite M.gso. rewrite M.gss. reflexivity.\n              solve_nodup.\n              rewrite M.gss. reflexivity.\n              rewrite M.gso. rewrite M.gso. rewrite M.gso. rewrite M.gss.\n              reflexivity. solve_nodup. solve_nodup. solve_nodup.\n              auto.\n            * intro.\n              \n              {\n                split.\n                - (* need closed term at top level, s.t. x has to come from fl or xs *)\n                  intro.\n                  assert (Hx_in: (In _ (Ensembles.Union _  (FromList vsm4) (name_in_fundefs fl)) x)). {\n                    eapply closed_val_fun; eauto.\n                  }\n                  assert (Hx_vsm4: decidable (List.In x vsm4)). apply In_decidable. apply shrink_cps_correct.var_dec_eq.  \n                  inv Hx_vsm4. \n                  + (* x in vsm4 *)\n                    assert (Hx_rho'' := get_set_lists_In_xs _ _ _ _ _ H5 H2). destruct Hx_rho''. exists x0. split; auto.\n                    assert (Hx_in_rho := in_rho_entry _ _ _ _ _ _ H2  Hnd_vs0  H6). destruct Hx_in_rho.\n                    2: exfalso; destructAll; auto.\n                    destruct H7. destruct H7.\n                    assert (H_x0_vs := nthN_In _ _ _ H12).\n                    specialize (H1 x). destruct H1. specialize (H1 _ H7).                    \n                    assert (Hx_rho_x_val := get_list_nth_get' _ _ _ _ _ _ H0 H12). destruct Hx_rho_x_val as [y4 [Hy4_ys Hy4_rho]].\n                    \n                    specialize (Hrel_rho_m4 y4). destruct (Hrel_rho_m4). \n                    assert (occurs_free (Eapp f tm4 ys) y4). constructor. apply nthN_In in Hy4_ys; auto. apply H16 in H18.\n                    destruct H18. destruct H18. rewrite Hy4_rho in H18. inv H18.\n                    assert (Genv.find_symbol (Genv.globalenv p) x = None). {\n                      inv Hf_id. eapply H20. apply H.\n                      eapply  Bound_FVfun. left. apply H5. eauto. \n                    }\n                    assert (exists v7, nthN vs7 x1 = Some v7).\n                    eapply nthN_length. eapply OrdersEx.Nat_as_OT.eq_le_incl. eapply lenv_param_asgn_i_length. eauto.\n                    eauto. destruct H20 as [v7 Hv7_vs7].\n                    econstructor. eauto. erewrite Hv7_vs7 in H1. apply H1.\n                    assert (Hy4v7 := mem_of_asgn_nthN  Hvs7 Hy4_ys Hv7_vs7).\n                    inv Hy4v7.\n                    * inv H19. rewrite H20 in H21. inv H21. eauto. rewrite H20 in H21. inv H21.\n                    * inv H19. rewrite H23 in H20. inv H20. rewrite H21 in H24. inv H24. auto.\n                  + (* x in fl *)\n                    inv Hx_in. exfalso; auto.\n                    eapply set_lists_not_In in H2. 2: eauto.\n                    rewrite def_funs_eq in H2; auto. eexists. split; eauto.\n                    assert (subval_or_eq  (Vfun (M.empty cps.val) fl x) (Vfun (M.empty cps.val) fl f')). constructor. eapply dsubval_fun.  auto. destruct (Hrel_rho_m4 f). specialize (H15 _ _ _ _  H H7). destruct H15. inv H15. econstructor; eauto.\n                    (* impossible, functions not bound *)\n                    inv H19. rewrite H24 in H17. inv H17.\n                -  intros.\n                  assert (Hin := in_rho_entry _ _ _ _ _ _ H2 Hnd_vs0 H4).\n                  destruct Hin.\n                  + (* x is from vs0 *)\n                    destruct H6.\n                    destruct H6. \n                    apply nthN_In in H7.\n                    apply (get_list_In_val _ _ _  _ H0) in H7.\n                    destruct H7. destruct H7. \n                    specialize (Hrel_rho_m4 x1).\n                    destruct Hrel_rho_m4.                    \n                    specialize (H16 _ _ _ _ H12 H5). \n                    destruct H16.\n                    split; auto.\n                    inv H16. econstructor; eauto.\n                    \n                    (* impossible *)\n                    inv H20. destructAll. rewrite H26 in H18; inv H18.       \n                  + (* x is from fl *)\n                    destructAll.\n                    specialize (Hrel_rho_m4 f). destruct Hrel_rho_m4 as [Hrel_m41 Hrel_m42].\n                    assert (    exists l,  (Vfun rho'0 fds f0) = Vfun  (M.empty cps.val) fl l /\\ name_in_fundefs fl l).\n                    eapply subval_fun.                     eapply find_def_name_in_fundefs; eauto. auto. destruct H12. destruct H12. inv H12.\n                    assert (subval_or_eq (Vfun (M.empty cps.val) fl x3) (Vfun (M.empty cps.val) fl f')). \n                    constructor. constructor. auto.                                       \n                    specialize (Hrel_m42 _ _ _ _ H H12). destruct Hrel_m42 as [Hrel_m421 Hrel_m422]. split; auto.\n                    inv Hrel_m421; subst. econstructor; eauto.\n                    (* imposible since function not bound *)\n                    inv H18. rewrite H24 in H16. inv H16.\n              }\n        + eapply correct_tinfo_param_asgn; eauto.\n(*          2: eapply lenv_param_asgn_rel in Hlenv_new'; eauto. *)\n          eapply correct_tinfo_proper with (lenv := lenv).\n          2 : {\n            intro; intros.\n            destruct (var_dec v0 argsIdent).\n            subst. rewrite M.gss; auto.\n            inv H4. exfalso; auto.\n            rewrite M.gso by auto.\n            destruct (var_dec v0 limitIdent).\n            subst. rewrite M.gss; auto.\n            rewrite M.gso by auto.\n            inv H5. exfalso; auto.\n            destruct (var_dec v0 allocIdent).\n            subst; rewrite M.gss; auto.\n            inv H4. exfalso; auto.\n            rewrite M.gso by auto.\n            inv H5. rewrite M.gss; auto.\n            inv H4. }\n            destruct Hc_tinfo_m4; destructAll.\n            rewrite H4 in Hget_alloc; inv Hget_alloc.\n            rewrite H15 in Hget_args; inv Hget_args.\n            rewrite H7 in Hget_limit; inv Hget_limit.\n            rewrite H19 in Hget_tinf; inv Hget_tinf.\n            exists alloc_b, alloc_ofs, limit_ofs, args_b, args_ofs, tinf_b, tinf_ofs.\n            repeat (split; auto).\n            apply Z.ltb_ge in Hgc_case. \n            eapply OrdersEx.Z_as_OT.mul_le_mono_nonneg_l with (p := int_size%Z) in Hgc_case.\n\n            assert ( int_size * ((Ptrofs.unsigned limit_ofs - Ptrofs.unsigned alloc_ofs) / int_size)<= ((Ptrofs.unsigned limit_ofs - Ptrofs.unsigned alloc_ofs)))%Z by (apply Z.mul_div_le; chunk_red; archi_red; omega).\n            omega.\n            chunk_red; archi_red; omega.\n                       *)       \n            } (*END OF Hm5*)\n              \n              destruct Hm5 as [m5 [lenv_new'' [Hm5 [Hm5_lenv [alloc_b_m5 [alloc_ofs_m5 [limit_ofs_m5 [vs7_m5 [deref_args_m5 [load_alloc_m5 [load_limit_m5 [Hvs7_m5 Hm5_all_rel]]]]]]]]]]]].\n            \n    assert (Hl_temp': length avsm4 = length (skipn nParam vs7_m5)). {\n      SearchAbout mem_after_asgn length.\n      apply mem_after_asgn_length in Hvs7_m5.\n      eapply HSkipnLength in Hlvs.\n      rewrite avsm4Eq.\n      rewrite <- Hlvs. auto.\n    }\n\n    assert (Help := e_lenv_param_asgn_i _ (M.set argsIdent (Vptr args_b args_ofs)\n                                                 (M.set limitIdent (Vptr alloc_b_m5 limit_ofs_m5)\n                                                        (M.set allocIdent (Vptr alloc_b_m5 alloc_ofs_m5) lenv_new'')))  _ Hl_temp' Havsm4_nodup).\n    destruct Help as [lenv_new''' Hlenv_new'''_asgn_i].\n    assert (Hlenv_new'''_asgn := lenv_param_asgn_rel _ _ _ _ Hlenv_new'''_asgn_i Havsm4_nodup). \n    specialize (Hm5_all_rel lenv_new''' Hlenv_new'''_asgn).\n    destruct Hm5_all_rel as [Hm5_relmem Hm5_tinfo].\n    \n    \n    assert (Hc_env' : correct_envs cenv ienv rep_env rho'' e4). { \n      inv Hc_env. destructAll.\n      split.\n      (* ienv_of_cenv *)\n      auto. split. \n      (* cenv of env  ccenv rho'' *)\n      { intro; intros. \n        assert (decidable (List.In x vsm4)). apply In_decidable. apply shrink_cps_correct.var_dec_eq.\n        inv H14. \n        (* 1) in vs  *) \n        assert (List.In v0 vs) by (eapply set_lists_In; eauto).\n        \n        assert (Hgl := get_list_In_val _ _ _ _  H0 H14). \n        destruct Hgl. destruct H16. \n        apply H3 in H17. auto.\n        \n        erewrite <- set_lists_not_In in H13.\n        2: eauto.\n        2: eauto.\n\n        assert (decidable (name_in_fundefs fl x)).\n        {\n          unfold decidable. assert (Hd := Decidable_name_in_fundefs fl). inv Hd. specialize (Dec x). inv Dec; auto.\n        } \n        inv H14.\n        (*\n          2) in fl *)\n        rewrite def_funs_eq in H13. 2: eauto.\n        inv H13.\n        apply H3 in H. inv H.\n        constructor. auto. \n        \n        (*\n          3* ) in rho' (EMPTY!!!)\n         *)\n        rewrite def_funs_neq in H13. 2: eauto.\n        rewrite M.gempty in H13. inv H13.\n      }       \n      \n      split.\n      (* cenv_of_exp cenv e0 -- can get this from correct_cenv_of_val (CCV_fun) *)\n      apply H3 in H. inv H.\n      eapply Forall_fundefs_In in H15. apply H15.\n      eapply find_def_correct. eauto.\n\n      (* crep_of_env *)\n      auto.\n\n    }\n    assert (Hrel_p'': protected_id_not_bound_id rho'' e4 ) by (eapply protected_id_closure; eauto).\n\n    assert (Hrho''_id : unique_bindings_env rho'' e4). {\n      destruct Hrho_id. \n      split.\n      apply H3 in H.\n      \n      destruct H as [Hbv Hubv].\n      inv Hubv.\n      eapply shrink_cps_correct.ub_in_fundefs; eauto.\n\n\n      intros.   assert (decidable (List.In x vsm4)). apply In_decidable. apply shrink_cps_correct.var_dec_eq.\n      destruct H5. \n      (* in vs0 *)\n      apply H3 in H.\n      destruct H as [Hbv Hubv].\n      inv Hubv.\n      assert (List.In v0 vs) by (eapply set_lists_In; eauto).       \n      assert (Hgl := get_list_In_val _ _ _ _  H0 H). destruct Hgl. destruct H8.\n      \n      split. intro.  \n       \n      assert (Hdj:=shrink_cps_correct.Disjoint_bindings_find_def _ _ _ _ _ H6 Hfind_def_f'). \n      inv Hdj. specialize (H15 x). apply H15. split; auto.\n\n      apply H3 in H13. destruct H13; auto. \n\n      \n      (* in fl *)\n      erewrite <- set_lists_not_In in H4. 2: eauto. 2:eauto.\n      \n      assert (decidable (name_in_fundefs fl x)). unfold decidable. assert (Hd := Decidable_name_in_fundefs fl). inv Hd. specialize (Dec x). inv Dec; auto.\n      inv H6.\n      apply H3 in H.\n      destruct H as [Hbv Hubv].\n      inv Hubv. \n      erewrite def_funs_eq in H4. 2: eauto.\n      inv H4.\n      split.\n      assert  (Hdj := shrink_cps_correct.Disjoint_bindings_fundefs _ _ _ _ _ H6 Hfind_def_f').\n      inv Hdj. intro. specialize (H x). apply H. split; auto.\n      \n      constructor; auto.\n      \n      rewrite def_funs_neq in H4; eauto.\n      rewrite M.gempty in H4. inv H4. \n    }\n        assert (Hf_id': functions_not_bound p rho'' e4 ). {\n      destruct Hf_id as [Hf_id1 Hf_id2].\n      split.\n\n      -  intros. eapply Hf_id2 in H. eauto. \n        econstructor. right. apply H1. eauto.\n      - intros.\n        assert (decidable (List.In y vsm4)). apply In_decidable. apply shrink_cps_correct.var_dec_eq. \n        inv H4.\n        (* in vsm4 *)\n        assert (List.In v0 vs) by (eapply set_lists_In; eauto).       \n        assert (Hgl := get_list_In_val _ _ _ _  H0 H4). destruct Hgl. destruct H6.\n        eapply Hf_id2 in H8; eauto. \n\n\n        (* in fl *)\n        erewrite <- set_lists_not_In in H1. 2: eauto. 2: eauto.\n        assert (decidable (name_in_fundefs fl y)). unfold decidable. assert (Hd := Decidable_name_in_fundefs fl). inv Hd. specialize (Dec y). inv Dec; auto.\n        inv H4. \n\n        erewrite def_funs_eq in H1. 2: eauto. inv H1.\n        eapply Hf_id2 in H; eauto. inv H3. econstructor; eauto. \n        \n        rewrite def_funs_neq in H1; eauto.\n        rewrite M.gempty in H1. inv H1.         \n\n    }\n    specialize (IHHev Hc_env' Hrel_p'' Hrho''_id Hf_id' _ _ _ (Kcall None fu empty_env lenv k) _ F H19 Hm5_relmem Hc_alloc' Hm5_tinfo).\n    destruct IHHev as [m6 [lenv6 [Hstep_m6 Hargs_m6]]].\n    \n    \n    exists m6, lenv.\n\n    split.\n   \n    (* step through s*)  \n    eapply t_trans.\n    constructor. constructor.\n\n    eapply t_trans.\n    constructor. constructor.\n\n    eapply t_trans.\n    constructor. constructor.\n\n    eapply t_trans.\n    econstructor. constructor.\n\n    eapply t_trans.\n    econstructor. constructor. \n     \n    econstructor. econstructor. econstructor.  constructor.\n    constructor. \n    (* tinfIdent is in lenv *) eauto.\n    constructor 3. simpl. reflexivity. simpl. reflexivity.\n    eauto.\n    rewrite Htinfident_members. apply argsIdent_delta. \n    simpl. eauto.  \n     \n    eapply t_trans.\n    constructor.\n    constructor.\n \n    eapply clos_rt_t.\n    Set Printing All. simpl.\n    rewrite Hlenv'.\n    Unset Printing All. simpl.\n    eauto.\n\n    (* done marshalling elements *) \n    eapply t_trans.\n    constructor.\n    constructor.\n\n    eapply t_trans.\n    constructor. econstructor. econstructor. econstructor.\n    constructor. constructor. eauto.\n    constructor 3. reflexivity. reflexivity. eauto.\n    rewrite Htinfident_members. apply allocIdent_delta. constructor. eauto. simpl. reflexivity.\n    econstructor. reflexivity.\n    unfold Mem.storev. rewrite Ptrofs.add_zero. apply Hm3.\n\n\n    eapply t_trans.\n    constructor. constructor.\n\n\n\n    (* step to m4 now *)\n    eapply t_trans.\n    constructor. econstructor. econstructor. econstructor.\n    constructor. constructor. eauto.\n    constructor 3. reflexivity. reflexivity. eauto.\n    rewrite Htinfident_members. apply limitIdent_delta. \n\n    constructor. eauto. reflexivity. econstructor. reflexivity.\n    unfold Mem.storev. apply Hm4.\n\n\n    eapply t_trans.\n    constructor. econstructor. \n    \n     \n    (* CALL TIME! *)\n\n    eapply t_trans. \n    constructor. econstructor.\n    reflexivity.   \n    simpl. rewrite Nnat.Nat2N.id.\n    eapply Heval_f'.\n    econstructor. econstructor.\n    eauto. constructor.\n    (* OSTODO: need a hyp:\n   eval_exprlist (globalenv p) empty_env lenv m4 s2\n    (mkFunTyList\n       (Init.Nat.min\n          (N.to_nat (fst (N.of_nat (length locs), locs))) nParam))\n    ?Goal12 for some ?Goal12 equivalent to values in bys *)\n    simpl. rewrite Nnat.Nat2N.id.\n    admit.\n    (* -- find_funct f'*)\n    eauto.\n    (* -- type_of_fundef F*)\n    simpl. unfold type_of_function. rewrite Nnat.Nat2N.id.\n    rewrite Hlvs. unfold fn_params. simpl.\n    rewrite type_of_mkFunTyList. reflexivity.\n\n    \n\n    (* - step through the Callstate *)\n    (* OSTODO: HOSTEMP1 shows that you can skip the mk_gv_call when looking up a protected ident [whenever used to rewrite Heqlenv_new *)\n    assert (HOSTEMP1: M.get tinfIdent lenv_new = Some (Vptr tinf_b tinf_ofs)) by admit.\n    eapply t_trans. \n    constructor.\n    (* I'M HERE : TODO: update the le in step_internal_function to include the argument vector computed earlier [in the eval_exprlist] *) \n\n    eapply  step_internal_function with (le := lenv_new).\n(*    (Maps.PTree.set tinfIdent (Vptr tinf_b tinf_ofs)\n       (create_undef_temps ((skipn nParam vars) ++ gc_vars argsIdent allocIdent limitIdent caseIdent)))). *)\n    constructor. \n    simpl. constructor.\n    (* OSTODO: need to show that tinfo and all params are disjoint (from unique_bindigns and protected_not_bound) *)\n    (*    simpl. constructor. intro Hfalse; inv Hfalse. constructor. *)\n    admit.\n    (* OSTODO: need to show that first n param are disjoint from last arity-n *)\n    (*simpl. intro; intros. inv H1. rewrite <- H5 in *. clear H5. *)\n    admit.\n\n\n    (* --  alloc_variables (globalenv p) empty_env m4 \n    (fn_vars F) ?Goal12 ?Goal13 *) \n    admit.\n    \n    (* -- bind_parameter_temps*)\n    unfold lenv_new; rewrite Heqlenv_new'. \n    admit.\n    (* \n    rewrite var_names_app in H4.\n    rewrite Coqlib.in_app in H4. destruct H4.\n    intro. rewrite <- H4 in *; clear H4.\n    assert (List.In tinfIdent vsm4).\n    eapply unzip_vars; eauto.\n    inv Hp_id.\n    assert ( is_protected_id argsIdent allocIdent limitIdent gcIdent mainIdent bodyIdent threadInfIdent\n         tinfIdent heapInfIdent numArgsIdent isptrIdent caseIdent tinfIdent) by inList.\n    specialize (H5 _ _ _ H H7).\n    apply H5. right.\n    constructor.\n    eapply shrink_cps_correct.name_boundvar_arg.\n    apply H4. eauto.\n    simpl in H1. intro. rewrite <- H4 in *. clear H4.\n    assert (H_dj := disjointIdent). inv H_dj. inv H7. inv H15.\n    inv H16. inv H17. inv H18. inv H19. inv H20. inv H1. apply H12; inList. inv H4. apply H7; inList. inv H1. apply H6; inList.\n    inv H4. apply H19; inList. auto.   \n    inv H5.\n    constructor. reflexivity.\n     *)\n\n \n    eapply t_trans.\n    constructor. constructor.\n\n    (* go through gc_test' to m5 *)\n    eapply t_trans.\n    apply Hm5.\n\n\n    eapply t_trans.\n    constructor. constructor.\n    eapply t_trans.\n    constructor. constructor.\n    eapply t_trans.\n    constructor. constructor.\n\n    (* step through gc_set *)\n    unfold gc_set.\n\n\n    (* step through reestablishing locals for tinfo's field *)\n    eapply t_trans.\n    constructor. constructor.\n    \n    eapply t_trans.\n    constructor. constructor.\n    (* * allocs *)\n    eapply t_trans.\n    constructor. constructor.\n    \n    econstructor. econstructor. econstructor.\n    constructor. constructor. rewrite <- Hm5_lenv. \n    eauto.\n(*    unfold lenv_new; rewrite Heqlenv_new'. rewrite M.gss. reflexivity.     *)\n    constructor 3. reflexivity.\n    reflexivity.\n    eauto. rewrite Htinfident_members.  apply allocIdent_delta.  eapply deref_loc_value. constructor.\n    unfold Mem.loadv.   rewrite Ptrofs.add_zero. eauto.\n     \n    \n    eapply t_trans.\n    constructor. constructor.\n\n    (* * limit *)\n    eapply t_trans.\n    constructor. constructor.\n    econstructor. econstructor. econstructor.\n    constructor. constructor.\n    rewrite M.gso. rewrite <- Hm5_lenv. eauto.  (* rewrite Heqlenv_new. rewrite M.gss. reflexivity. *)\n    \n    assert (H_dj := disjointIdent).\n    solve_nodup.\n    constructor 3. reflexivity.\n    reflexivity.\n    eauto. rewrite Htinfident_members. apply limitIdent_delta. \n    eapply deref_loc_value. constructor.\n    eauto.\n\n \n    \n    eapply t_trans.\n    constructor. constructor.\n\n    (* * args *)\n    \n    eapply t_trans.\n    constructor. constructor.\n    econstructor. econstructor. econstructor.\n    constructor. constructor. rewrite M.gso. rewrite M.gso. rewrite <- Hm5_lenv.\n    eauto.  (* rewrite Heqlenv_new. rewrite M.gss. reflexivity. *)\n    assert (H_dj := disjointIdent).  solve_nodup. \n    assert (H_dj := disjointIdent).  solve_nodup. \n    constructor 3. reflexivity. reflexivity.\n    eauto. rewrite Htinfident_members. apply argsIdent_delta.\n    simpl. eauto.\n\n\n    \n    eapply t_trans.\n    constructor. constructor.\n\n    (* asgn! *)\n    \n    eapply clos_rt_t.\n     \n    eapply repr_asgn_fun_entry; eauto.\n    rewrite M.gss. reflexivity. eauto.\n\n\n\n    eapply t_trans. constructor. constructor.\n\n    eapply t_trans.\n    apply Hstep_m6.\n    \n\n    eapply t_trans.\n    constructor. \n    constructor. constructor. compute. reflexivity.\n    constructor. constructor.\n\n\n    (* lenv6 and lenv are equivalent here since argsIdent stays the same *)\n    split.\n    reflexivity.\n    destruct Hargs_m6 as [Hargs_m61 Hargs_m62].\n    inv Hargs_m62. destructAll.\n    inv Hc_tinfo'.\n    exists x, x0, x1, x2. split; auto. rewrite <- Hargs_m61 in H1.\n\n    assert (M.get argsIdent (M.set argsIdent (Vptr args_b args_ofs)\n                          (M.set limitIdent (Vptr alloc_b_m5 limit_ofs_m5)\n                                 (M.set allocIdent (Vptr alloc_b_m5 alloc_ofs_m5) lenv_new'')))= M.get argsIdent lenv_new''').\n    eapply lenv_param_asgn_map with (l := [argsIdent]). eauto.\n    split. intro; intro.\n    inv H13. inv H15. eapply Hnoprot_vs0. eauto.\n\n    left. right. auto. inv H13. constructor; auto. rewrite <- H13 in H1.\n    rewrite M.gss in H1. inv H1. auto. \n  - (* Ehalt *)\n\n    (* find out what v looks like in memory *)\n    assert (Hof: occurs_free (Ehalt x) x) by constructor.\n    destruct (Hrel_m) as [L [HL_pro Hmem]].\n    apply Hmem in Hof. destruct Hof as [v6 [Hxrho Hrel_v6]].\n    clear Hmem.\n\n    (* show that we have write access to args[1] *)\n    unfold correct_tinfo in Hc_tinfo.\n    destruct Hc_tinfo as [alloc_b [alloc_ofs [limit_ofs [args_b [args_ofs [tinf_b [tinf_ofs [Hget_alloc [Hdiv_alloc [Hrange_alloc [Hget_limit [Hbound_limit [Hget_args [Hdj_args [Hbound_args [Hrange_args [Htinf1 [Htinf2 [Htinf3 [Htinf4 Hglobals]]]]]]]]]]]]]]]]]]]]. \n    assert (Htemp : (0 <= 1 < max_args)%Z) by (unfold max_args; omega).\n\n    assert (Hvalid_args1:= Hrange_args _ Htemp).\n    clear Htemp.\n\n    inv Hrel_v6.\n     \n    + (* halt on a function *)\n      inv H1. rewrite H0 in H3. inv H3. \n      \n      assert (Hvv  :=  Mem.valid_access_store _ _ _ _ (Vptr b0 Ptrofs.zero) Hvalid_args1).\n      destruct Hvv as [m2 Hm2].\n      \n      assert (Hm2_u : Mem.unchanged_on L m m2). {\n        inv HL_pro.\n        destructAll.\n        eapply Mem.store_unchanged_on; eauto; intros. \n        rewrite Hget_args in H9; inv H9.\n        apply H10 with (z := 1%Z).\n        unfold max_args; omega.\n        rewrite Ptrofs.mul_one in *.\n        simpl. unfold int_size in *; eauto.\n      }\n      exists m2, lenv.\n       \n      split.\n      \n      * \n        apply t_step.\n        eapply step_assign with (v := (Vptr b0 Ptrofs.zero)) (m' := m2).  \n        { \n          constructor.\n          econstructor. constructor; eauto.\n          constructor. simpl. unfold sem_add. simpl. reflexivity.       \n        }\n        assert (Hvorfv : get_var_or_funvar p lenv x (Vptr b0 (Ptrofs.repr 0))).\n        {\n          constructor. auto.\n        }\n        assert (HvorfvEval := get_var_or_funvar_eval threadInfIdent nParam fenv finfo_env p lenv x (Vptr b0 (Ptrofs.repr 0)) m Hsym HfinfoCorrect Hvorfv).\n        assert (HvorfvEq : var_or_funvar_f threadInfIdent nParam fenv finfo_env p x = makeVar threadInfIdent nParam x fenv finfo_env).\n        {\n          unfold var_or_funvar_f. rewrite H0. reflexivity.\n        }\n        rewrite <- HvorfvEq.\n        eassumption.   \n        assert (Hvorfv : get_var_or_funvar p lenv x (Vptr b0 (Ptrofs.repr 0))).\n        {\n          constructor. auto.\n        }\n        assert (HvorfvEq : var_or_funvar_f threadInfIdent nParam fenv finfo_env p x = makeVar threadInfIdent nParam x fenv finfo_env).\n        {\n          unfold var_or_funvar_f. rewrite H0. reflexivity.\n        }\n        rewrite <- HvorfvEq.\n        eapply get_var_or_funvar_semcast; eauto.\n        econstructor. simpl. reflexivity. apply Hm2.\n      * unfold arg_val_LambdaANF_Codegen. split. reflexivity.\n        exists args_b, args_ofs, (Vptr b0 Ptrofs.zero), L.\n        split; auto. rewrite Ptrofs.mul_one in Hm2. split.\n        eapply Mem.load_store_same in Hm2.\n        simpl in Hm2. auto.\n        rewrite Hxrho in H; inv H.\n        eapply repr_val_L_unchanged; eauto.\n      * rewrite H0 in H3; inv H3.                        \n    + (* halt on constr or vint *)\n      inv H1. rewrite H4 in H0; inv H0.\n      clear H4.\n      assert (Hvv  :=  Mem.valid_access_store _ _ _ _ v7 Hvalid_args1).\n      destruct Hvv as [m2 Hm2].      \n      assert (Hm2_u : Mem.unchanged_on L m m2). {\n        inv HL_pro.\n        destructAll.\n        eapply Mem.store_unchanged_on; eauto; intros.\n        rewrite Hget_args in H10; inv H10.\n        apply H11 with (z := 1%Z).\n        unfold max_args; omega.\n        rewrite Ptrofs.mul_one in *.\n        simpl. unfold int_size in *; eauto.\n      }\n      exists m2, lenv.\n      split.\n      * apply t_step. eapply step_assign with (v := v7) (m' := m2).  \n        { \n          constructor.\n          econstructor. constructor; eauto.\n          constructor. simpl. unfold sem_add. simpl. reflexivity.      \n        } \n        econstructor. eauto.  simpl. \n        unfold sem_cast. simpl. inv H3; reflexivity.\n        econstructor. constructor.\n        simpl. apply Hm2.\n      * unfold arg_val_LambdaANF_Codegen. split. reflexivity.\n        exists args_b, args_ofs, v7, L.\n        split; auto. split.\n        rewrite Ptrofs.mul_one in Hm2.\n        eapply Mem.load_store_same in Hm2. simpl in Hm2. destruct v7; inv H3; auto. \n        rewrite H in Hxrho. inv Hxrho. \n        eapply repr_val_L_unchanged; eauto.\nAdmitted.\n\n\n\n(* Top level theorem on the LambdaANF_to_Clight translation \nTheorem top_repr_LambdaANF_Codegen_are_related:\n   forall fds e,\nwell_formed (Efun fds e) ->\nproper_cenv cenv ->\nproper_cenv_of_exp cenv e ->\ncompile e cenv nenv = ...\n\n *)\n  \n", "meta": {"author": "CertiCoq", "repo": "certicoq", "sha": "2405e1012e9c0a58e49002d9779bb65527d6c323", "save_path": "github-repos/coq/CertiCoq-certicoq", "path": "github-repos/coq/CertiCoq-certicoq/certicoq-2405e1012e9c0a58e49002d9779bb65527d6c323/theories/Codegen/LambdaANF_to_Clight_correct.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21069055637134734}}
{"text": "Set Implicit Arguments.\nSet Maximal Implicit Insertion.\nSet Contextual Implicit.\nSet Universe Polymorphism.\n\nFrom Coq Require Import\n     Relation_Definitions\n     RelationClasses\n.\n\nRequire Import Fix.\nRequire Import GHC.Base.\nRequire Import Adverb.Adverb.\nRequire Import ClassesOfFunctors.DictDerive.\nRequire Import ClassesOfFunctors.Laws.\nRequire Import ClassesOfFunctors.Selective.\n\nOpen Scope adverb_scope.\n\n\n(* begin conditionally_adv *)\n(* Conditionally *)\nInductive ReifiedSelective (E : Type -> Type) (R : Type) : Type :=\n| EmbedS (e : E R)\n| PureS (r : R)\n| SelectBy {X Y : Type} (f : X -> ((Y -> R) + R))\n           (a : ReifiedSelective E X) (b : ReifiedSelective E Y).\n(* end conditionally_adv *)\n\nDefinition selectByCA {E A B C} :\n  (A -> ((B -> C) + C)) -> ReifiedSelective E A -> ReifiedSelective E B -> ReifiedSelective E C :=\n  SelectBy.\n\nDefinition selectCA {E A B} (a : ReifiedSelective E (A + B)) (b : ReifiedSelective E (A -> B)) : ReifiedSelective E B :=\n  selectByCA (fun x => match x with\n                  | inl x => inl (fun y => y x)\n                  | inr x => inr x\n                  end) a b.\n\nDefinition pureCA {E A} : A -> ReifiedSelective E A := PureS.\n\nDefinition fmap__CA {E A B}\n           (f : A -> B) (a : ReifiedSelective E A) : ReifiedSelective E B :=\n  selectByCA inl (pureCA f) a.\n\nDefinition ap__CA {E A B} (f : ReifiedSelective E (A -> B))\n           (a : ReifiedSelective E A) : ReifiedSelective E B :=\n  selectCA (fmap__CA inl f) (fmap__CA (fun a f => f a) a).\n\nDefinition liftA2__CA {E A B C} (f : A -> B -> C)\n           (a : ReifiedSelective E A) (b : ReifiedSelective E B) : ReifiedSelective E C :=\n  ap__CA (ap__CA (pureCA f) a) b.\n\nGlobal Instance Functor__CA {E : Type -> Type} : Functor (ReifiedSelective E) :=\n  fun r k => k {| fmap__      := fun {a} {b} => fmap__CA ;\n              op_zlzd____ := fun {a} {b} => fmap__CA ∘ const |}.\n\nGlobal Program Instance Applicative__ReifiedSelective {E : Type -> Type} :\n  Applicative (ReifiedSelective E) :=\n  fun r k => k {| liftA2__ := fun {a b c} => liftA2__CA ;\n               op_zlztzg____ := fun {a b} => ap__CA ;\n               op_ztzg____ := fun {a b} fa => liftA2__CA id ((fmap__CA ∘ const) id fa) ;\n               pure__ := fun {a} => pureCA |}.\n\nGlobal Program Instance Selective__ReifiedSelective {E : Type -> Type} :\n  Selective (ReifiedSelective E) :=\n  fun r k => k {| select__ := fun _ _ => selectCA |}.\n\nDefinition fmapSum {A B C} (f : A -> B) (a : sum C A) : sum C B :=\n  match a with\n  | inl c => inl c\n  | inr a => inr (f a)\n  end.\n\nDefinition branch {E A B C} (b : ReifiedSelective E (A + B))\n           (l : ReifiedSelective E (A -> C))\n           (r : ReifiedSelective E (B -> C)) : ReifiedSelective E C :=\n  selectCA (selectCA (fmap (fmapSum inl) b) (fmap (fun f a => inr (f a)) l)) r.\n\nDefinition ifS {E A} (b : ReifiedSelective E bool)\n           (t e : ReifiedSelective E A) : ReifiedSelective E A :=\n  branch (fmap (fun b : bool => if b then inl tt else inr tt) b)\n         (fmap (fun a _ => a) t) (fmap (fun a _ => a) e).\n\nDefinition pand {E} (x y : ReifiedSelective E bool) : ReifiedSelective E bool :=\n  ifS x y (pureCA false).\n\nDefinition interpS\n  {E I : Type -> Type} `{Monad I}\n  {EqI : forall (A : Type), relation (I A)} {A : Type}\n  (interpE : forall A, E A -> I A) :=\n  let fix go {A : Type} (t : ReifiedSelective E A) : I A :=\n    match t with\n    | EmbedS e => interpE _ e\n    | PureS a => return_ a\n    | SelectBy f a b =>  go a >>= (fun x =>\n                                    match f x with\n                                    | inl y => fmap y (go b)\n                                    | inr r => return_ r\n                                    end)\n    end\n  in @go A.\n\n(** * The adverb simulation. *)\nGlobal Instance ReifiedSelectiveSim :\n  ReifiedSelective ⊧ Monad__Dict UNDER IdT :=\n  {| interp := fun _ I D =>\n                 @interpS _ _\n                   (monaddict_functor I D)\n                   (monaddict_applicative I D)\n                   (monaddict_monad I D)\n  |}.\n\nReserved Notation \"a ≅ b\" (at level 42).\n\nDeclare Scope conditionally_scope.\n\nInductive ConditionallyBisim {E : Type -> Type}\n  : forall {A : Type}, relation (ReifiedSelective E A) :=\n| conditionally_congruence :\n  forall {A B} (a1 a2 : ReifiedSelective E (A + B))\n    (b1 b2 : ReifiedSelective E (A -> B)),\n    a1 ≅ a2 ->\n    b1 ≅ b2 ->\n    select a1 b1 ≅ select a2 b2\n| conditionally_id : forall {A} (a : ReifiedSelective E (A + A)),\n    select a (pure id) ≅ fmap (fun x => match x with\n                                     | inl x => x\n                                     | inr x => x\n                                     end) a\n| conditioanlly_distr : forall {A B} (x : A + B)\n                          (y z : ReifiedSelective E (A -> B)),\n    select (pure x) (y *> z) ≅ (select (pure x) y *> select (pure x) z)\n| conditionally_assoc : forall {A B C}\n                          (x : ReifiedSelective E (A + B))\n                          (y : ReifiedSelective E (C + (A -> B)))\n                          (z : ReifiedSelective E (C -> A -> B))\n                          (f : (A + B) -> ((A + A) + (C * A + B)))\n                          g (h : (C -> A -> B) -> (C * A) -> B),\n    (forall x, f x = match x with\n                | inl x => inl (inr x)\n                | inr x => inr (inr x)\n                end) ->\n    (forall (y : C + (A -> B)) (a : A + A),\n        g y a = let i a :=\n                  match y with\n                  | inl c => inl (c, a)\n                  | inr k => inr (k a)\n                  end in\n                match a with\n                | inl a => i a\n                | inr a => i a\n                end) ->\n    (forall f p, h f p = f (fst p) (snd p)) ->\n      select x (select y z) ≅ select (select (fmap f x) (fmap g y)) (fmap h z)\n| conditionally_force : forall {A B} (a : ReifiedSelective E B) (b : ReifiedSelective E (A -> B)),\n    select (fmap inr a) b ≅ a\n| conditionally_refl : forall A (a : ReifiedSelective E A), a ≅ a\n| conditionally_sym : forall A (a b : ReifiedSelective E A), a ≅ b -> b ≅ a\n| conditionally_trans : forall A (a b c : ReifiedSelective E A), a ≅ b -> b ≅ c -> a ≅ c\nwhere \"a ≅ b\" := (ConditionallyBisim a b) : conditionally_scope.\n\nGlobal Program Instance ReifiedConditionally__Adverb : Adverb ReifiedSelective :=\n  {| Bisim := fun _ _ => ConditionallyBisim ;\n     Refines := fun _ _ => ConditionallyBisim\n  |}.\nNext Obligation.\n  constructor.\n  - intros a. constructor.\n  - intros a b. constructor. assumption.\n  - intros a b c ? ?. econstructor; eassumption.\nQed.\nNext Obligation.\n  constructor.\n  - intros a. constructor.\n  - intros a b c ? ?. econstructor; eassumption.\nQed.\n\nTheorem soundness_of_conditionally :\n  forall {E I : Type -> Type} {A : Type}\n    {EqI : forall (A : Type), relation (I A) } `{forall A, Equivalence (EqI A) }\n    {D : Monad__Dict I}\n    {_ : @MonadLaws I EqI (monaddict_functor _ D) (monaddict_applicative _ D)\n           (monaddict_monad _ D)}\n    {_ : @MonadCongruenceLaws I EqI (monaddict_functor _ D)\n           (monaddict_applicative _ D) (monaddict_monad _ D)}\n    (interpE : forall A, E A -> I A) (x y : ReifiedSelective E A),\n    (* The theorem states that [Bisim] is an under-approximation of\n       [EqI]. *)\n    Bisim (Adverb:=ReifiedConditionally__Adverb) x y ->\n    EqI _ (interp (C0:=D)(EqI:=EqI)(AdverbSim:=ReifiedSelectiveSim) interpE x)\n      (interp (C0:=D)(EqI:=EqI)(AdverbSim:=ReifiedSelectiveSim) interpE y).\nProof.\n  intros until y. intro Hbisim. induction Hbisim.\n  - unfold interp. cbn.\n    apply bind_cong.\n    + apply H1.\n    + apply IHHbisim1.\n    + intros. destruct a.\n      * unfold monaddict_fmap.\n        pose proof bind_cong. unfold \">>=\" in H2.\n        specialize (H2 I EqI _ _ _ H1 (A -> B) B).\n        unfold monaddict_monad in H2. apply H2.\n        -- rewrite <- IHHbisim2. reflexivity.\n        -- reflexivity.\n      * reflexivity.\n  - unfold interp. cbn.\n    rewrite monad_left_id; [|assumption].\n    unfold monaddict_fmap.\n    pose proof bind_cong. unfold \">>=\" in H2.\n    specialize (H2 I EqI _ _ _ H1 (A + A) A).\n    unfold monaddict_monad in H2. apply H2.\n    + reflexivity.\n    + intros. destruct a0.\n      * pose proof monad_left_id. unfold \">>=\" in H3.\n        specialize (H3 I EqI _ _ _ H0 (A -> A) A).\n        unfold monaddict_monad in H3. rewrite H3.\n        reflexivity.\n      * reflexivity.\n  - unfold interp. cbn.\n    rewrite !monad_left_id.\n    pose proof monad_assoc as assoc. unfold \">>=\" in assoc.\n    specialize (assoc I EqI _ _ _ H0).\n    unfold monaddict_monad in assoc.\n    pose proof monad_left_id as left_id. unfold \">>=\" in left_id.\n    specialize (left_id I EqI _ _ _ H0).\n    unfold monaddict_monad in left_id.\n    pose proof left_id as left_id'.\n    unfold return_ in left_id'.\n    destruct x.\n    + unfold monaddict_fmap. unfold \">>=\", monaddict_monad.\n      rewrite !assoc.\n      pose proof (assoc ((B -> B) -> (B -> B) + B) ((B -> B) + B) B) as Ht;\n        rewrite !Ht; clear Ht.\n      rewrite !left_id.\n      pose proof (left_id ((B -> B) -> (B -> B) + B) B) as Ht; rewrite !Ht; clear Ht.\n      rewrite !assoc, !left_id.\n      pose proof (left_id (((B -> B) -> B -> B) -> ((B -> B) -> B -> B) + (B -> B)) B) as Ht;\n        rewrite !Ht; clear Ht.\n      rewrite !assoc, !left_id.\n      pose proof (left_id ((B -> B) -> B -> B) B) as Ht; rewrite !Ht; clear Ht.\n      unfold \"∘\". rewrite !left_id'.\n      rewrite !assoc, !left_id.\n      pose proof (left_id ((B -> B) -> ((B -> B) -> B -> B) -> B -> B) B) as Ht.\n      rewrite !Ht; clear Ht.\n      rewrite !assoc, !left_id.\n      pose proof (left_id (B -> B -> B) B) as Ht; rewrite !Ht; clear Ht.\n      rewrite !assoc.\n      pose proof (left_id (A + B) B) as Ht; rewrite !Ht; clear Ht.\n      rewrite !assoc.\n      pose proof bind_cong as cong. unfold \">>=\" in cong.\n      specialize (cong I EqI _ _ _ H1).\n      unfold monaddict_monad in cong. apply cong; [reflexivity|]. intros.\n      rewrite !left_id'. repeat rewrite !assoc, !left_id.\n      rewrite !assoc. apply cong; [reflexivity|]. intros.\n      rewrite !left_id'. reflexivity.\n    + unfold monaddict_fmap. unfold \">>=\", monaddict_monad.\n      repeat rewrite !assoc, !left_id. unfold \"∘\".\n      rewrite !left_id'. repeat rewrite !assoc, !left_id.\n      rewrite !left_id'. repeat rewrite !assoc, !left_id.\n      rewrite !left_id'. reflexivity.\n    + assumption.\n  - unfold interp. cbn. unfold monaddict_fmap. unfold \">>=\", monaddict_monad.\n    pose proof monad_assoc as assoc. unfold \">>=\" in assoc.\n    specialize (assoc I EqI _ _ _ H0).\n    unfold monaddict_monad in assoc.\n    pose proof monad_left_id as left_id. unfold \">>=\" in left_id.\n    specialize (left_id I EqI _ _ _ H0).\n    unfold monaddict_monad in left_id.\n    pose proof left_id as left_id'.\n    unfold return_ in left_id'.\n    repeat rewrite !assoc, !left_id. rewrite !assoc.\n    pose proof monad_right_id as right_id.\n    specialize (right_id I EqI _ _ _ H0).\n    pose proof bind_cong as cong. unfold \">>=\" in cong.\n    specialize (cong I EqI _ _ _ H1).\n    unfold monaddict_monad in cong. apply cong; [reflexivity|]. intros [].\n    + unfold \"∘\". rewrite !assoc, !left_id'. simpl.\n      rewrite H2. repeat rewrite !assoc, !left_id.\n      rewrite !assoc. apply cong; [reflexivity|]. intros.\n      destruct a0.\n      * rewrite !assoc, !left_id'. rewrite H3. simpl.\n        repeat rewrite !assoc, !left_id. rewrite !assoc.\n        apply cong; [reflexivity|]. intros.\n        rewrite !left_id'. rewrite H4. cbn. reflexivity.\n      * rewrite !left_id, !left_id'. rewrite H3. simpl.\n        reflexivity.\n    + unfold \"∘\". rewrite !left_id'.\n      rewrite H2. rewrite !left_id. reflexivity.\n  - unfold interp. cbn. unfold monaddict_fmap. unfold \">>=\", monaddict_monad.\n    pose proof monad_assoc as assoc. unfold \">>=\" in assoc.\n    specialize (assoc I EqI _ _ _ H0).\n    unfold monaddict_monad in assoc.\n    pose proof monad_left_id as left_id. unfold \">>=\" in left_id.\n    specialize (left_id I EqI _ _ _ H0).\n    unfold monaddict_monad in left_id.\n    pose proof left_id as left_id'.\n    unfold return_ in left_id'.\n    repeat rewrite !assoc, !left_id. rewrite !assoc.\n    pose proof monad_right_id as right_id.\n    specialize (right_id I EqI _ _ _ H0).\n    pose proof (right_id _ (@interpS E I (monaddict_functor I D)\n                              (monaddict_applicative I D)\n                              (fun (r : Type) (k : Monad__Dict I -> r) => k D) EqI B interpE a)).\n    etransitivity; [|apply H2].\n    pose proof bind_cong as cong. unfold \">>=\" in cong.\n    specialize (cong I EqI _ _ _ H1).\n    unfold monaddict_monad in cong.\n    unfold \">>=\". unfold monaddict_monad.\n    apply cong; [reflexivity|]. intros.\n    unfold \"∘\". rewrite left_id'. reflexivity.\n  - unfold interp. cbn. reflexivity.\n  - unfold interp. cbn. symmetry. assumption.\n  - unfold interp. cbn. etransitivity; eassumption.\nQed.\n", "meta": {"author": "lastland", "repo": "ProgramAdverbs", "sha": "1f8086d379d1fc0eb896539adae66cd9f7d8ec04", "save_path": "github-repos/coq/lastland-ProgramAdverbs", "path": "github-repos/coq/lastland-ProgramAdverbs/ProgramAdverbs-1f8086d379d1fc0eb896539adae66cd9f7d8ec04/Adverb/Conditionally.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21044614886605953}}
{"text": "(* Hendra : DEX big step semantics, looking into BigStepLoad.v as reference *)\n\n  Import DEX_Dom DEX_Prog.\n\n  Open Scope type_scope.\n  Definition DEX_InitCallState :=  DEX_Method * DEX_Registers.t.\n  Definition DEX_IntraNormalState := DEX_PC * ((*DEX_Heap.t **) DEX_Registers.t).\n(*  Definition IntraExceptionState := Heap.t * Location. *)\n  Definition DEX_ReturnState := (*DEX_Heap.t **) DEX_ReturnVal.\n\n\n  Inductive DEX_NormalStep (p:DEX_Program) : DEX_Method -> DEX_IntraNormalState -> DEX_IntraNormalState  -> Prop :=\n  | nop : forall (*h*) m pc pc' regs,\n\n    instructionAt m pc = Some DEX_Nop ->\n    next m pc = Some pc' ->\n\n    DEX_NormalStep p m (pc, regs(*h, regs*)) (pc', regs(*h, regs*))\n\n  | const : forall (*h*) m pc pc' regs regs' k rt v,\n\n    instructionAt m pc = Some (DEX_Const k rt v) ->\n    In rt (DEX_Registers.dom regs) ->\n    next m pc = Some pc' ->\n    (-2^31 <= v < 2^31)%Z ->\n    DEX_METHOD.valid_reg m rt ->\n    regs' = DEX_Registers.update regs rt (Num (I (Int.const v))) ->\n\n    DEX_NormalStep p m (pc, regs(*h, l*)) (pc', regs'(*h, l'*))\n  \n  | move_step_ok : forall (*h*) m pc pc' regs regs' k rt rs v,\n\n    instructionAt m pc = Some (DEX_Move k rt rs) ->\n    In rt (DEX_Registers.dom regs) ->\n    In rs (DEX_Registers.dom regs) ->\n    next m pc = Some pc' ->\n    Some v = DEX_Registers.get regs rs ->\n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m rs ->\n    regs' = DEX_Registers.update regs rt v ->\n\n    DEX_NormalStep p m (pc, regs(*h, l*)) (pc', regs'(*h, l'*))\n(* DEX Method  \n  | moveresult_step_ok : forall h m pc pc' l l' k rt v,\n\n    instructionAt m pc = Some (DEX_MoveResult k rt) ->\n    next m pc = Some pc' ->\n    Some v = DEX_Registers.get l DEX_Registers.ret ->\n    DEX_METHOD.valid_reg m rt ->\n    l' = DEX_Registers.update l rt v ->\n\n    DEX_NormalStep p m (pc, (h, l)) (pc', (h, l'))\n*)\n(* DEX Object\n (** <addlink>instanceof</addlink>: Determine if object is of given type *)\n  | instanceof_step_ok1 : forall h m pc pc' l loc rt r t l',\n\n    instructionAt m pc = Some (DEX_InstanceOf rt r t) ->\n    next m pc = Some pc' ->\n    Some (Ref loc) = DEX_Registers.get l r ->\n    assign_compatible p h (Ref loc) (DEX_ReferenceType t) ->\n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m r ->\n    l' = DEX_Registers.update l' rt (Num (I (Int.const 1))) ->\n\n    DEX_NormalStep p m (pc, (h, l)) (pc', (h, l'))\n (** <addlink>instanceof</addlink>: with object == null *)\n  | instanceof_step_ok2 : forall h m pc pc' l rt r t v l',\n\n    instructionAt m pc = Some (DEX_InstanceOf rt r t) ->\n    next m pc = Some pc' ->\n    Some v = DEX_Registers.get l r ->\n    isReference v ->\n    (~ assign_compatible p h v (DEX_ReferenceType t) \\/ v=Null) ->\n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m r ->\n    l' = DEX_Registers.update l' rt (Num (I (Int.const 0))) ->\n\n    DEX_NormalStep p m (pc, (h, l)) (pc', (h, l'))\n  \n  (** <addlink>arraylength</addlink>: Get length of array *)\n  | arraylength_step_ok : forall h m pc pc' l l' loc length tp a rt rs,\n\n    instructionAt m pc = Some (DEX_ArrayLength rt rs)->\n    next m pc = Some pc' ->\n    Some (Ref loc) = DEX_Registers.get l rs ->\n    DEX_Heap.typeof h loc = Some (DEX_Heap.LocationArray length tp a) ->\n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m rs ->\n    l' = DEX_Registers.update l rt (Num (I length)) ->\n    \n    DEX_NormalStep p m (pc, (h, l)) (pc', (h, l'))\n\n  (** <addlink>new</addlink>: Create new object *)\n  | new_step_ok : forall h m pc pc' l l' c loc h' rt,\n\n    instructionAt m pc = Some (DEX_New rt (DEX_ClassType c)) ->\n    next m pc = Some pc' ->\n    DEX_Heap.new h p (DEX_Heap.LocationObject c) = Some (pair loc h') ->\n    DEX_METHOD.valid_reg m rt ->\n    l' = DEX_Registers.update l rt (Ref loc) ->\n\n    DEX_NormalStep p m (pc, (h, l)) (pc', (h', l'))\n\n (** Create new array (<addlink>anewarray</addlink>, <addlink>newarray</addlink>) *)\n (** OutOfMemory is not considered in Bicolano *)\n  | newarray_step_ok : forall h m pc pc' l l' i t loc h_new rt rl,\n\n    instructionAt m pc = Some (DEX_NewArray rt rl t) ->\n    next m pc = Some pc' ->\n    DEX_Heap.new h p (DEX_Heap.LocationArray i t (m,pc)) = Some (pair loc h_new) ->\n    Some (Num (I i)) = DEX_Registers.get l rl ->\n    (0 <= Int.toZ i)%Z ->\n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m rl ->\n    l' = DEX_Registers.update l rt (Ref loc) ->\n\n    DEX_NormalStep p m (pc, (h, l)) (pc', (h_new, l'))\n*)\n\n  | goto_step_ok : forall (*h*) m pc regs o,\n\n    instructionAt m pc = Some (DEX_Goto o) ->\n\n    DEX_NormalStep p m (pc, regs(*h, l*)) ((DEX_OFFSET.jump pc o), regs(*h, l*))\n(*  \n  | packedswitch_step_ok1 : forall h m pc l v r firstKey size list_offset n o,\n    \n    instructionAt m pc = Some (DEX_PackedSwitch r firstKey size list_offset) ->\n    Some (Num (I v)) = DEX_Registers.get l r ->\n    (firstKey <= Int.toZ v < firstKey + (Z_of_nat size))%Z ->\n    length list_offset = size ->\n    Z_of_nat n = ((Int.toZ v) - firstKey)%Z ->\n    nth_error list_offset n = Some o ->\n    DEX_METHOD.valid_reg m r ->\n    \n    DEX_NormalStep p m (pc, (h, l)) ((DEX_OFFSET.jump pc o), (h, l))\n\n  | packedswitch_step_ok2 : forall h m pc pc' l v r firstKey size list_offset,\n    \n    instructionAt m pc = Some (DEX_PackedSwitch r firstKey size list_offset) ->\n    Some (Num (I v)) = DEX_Registers.get l r ->\n    length list_offset = size ->\n    (Int.toZ v < firstKey \\/ firstKey + (Z_of_nat size) <= Int.toZ v)%Z ->\n    next m pc = Some pc' ->\n    DEX_METHOD.valid_reg m r ->\n\n    DEX_NormalStep p m (pc, (h, l)) (pc', (h, l))\n  \n  | sparseswitch_step_ok1 : forall h m pc l v v' o r size listkey,\n    \n    instructionAt m pc = Some (DEX_SparseSwitch r size listkey) ->\n    length listkey = size ->\n    Some (Num (I v)) = DEX_Registers.get l r ->\n    List.In (pair v' o) listkey ->\n    v' = Int.toZ v ->\n    DEX_METHOD.valid_reg m r ->\n    \n    DEX_NormalStep p m (pc, (h, l)) ((DEX_OFFSET.jump pc o), (h, l))\n\n  | sparseswitch_step_ok2 : forall h m pc pc' l v r size listkey,\n\n    instructionAt m pc = Some (DEX_SparseSwitch r size listkey) ->\n    length listkey = size ->\n    Some (Num (I v)) = DEX_Registers.get l r ->\n    (forall v' o, List.In (pair v' o) listkey ->  v' <> Int.toZ v) ->\n    next m pc = Some pc' ->\n    DEX_METHOD.valid_reg m r ->\n\n    DEX_NormalStep p m (pc, (h, l)) (pc', (h, l))\n*)\n  | ifcmp_step_jump : forall (*h*) m pc regs va vb cmp ra rb o,\n\n    instructionAt m pc = Some (DEX_Ifcmp cmp ra rb o) ->\n    In ra (DEX_Registers.dom regs) ->\n    In rb (DEX_Registers.dom regs) ->\n    Some (Num (I va)) = DEX_Registers.get regs ra ->\n    Some (Num (I vb)) = DEX_Registers.get regs rb ->\n    SemCompInt cmp (Int.toZ va) (Int.toZ vb) ->\n    DEX_METHOD.valid_reg m ra ->\n    DEX_METHOD.valid_reg m rb ->\n    \n    DEX_NormalStep p m (pc, regs(*h, l*)) ((DEX_OFFSET.jump pc o), regs(*h, l*))\n\n  | ifcmp_step_continue : forall (*h*) m pc pc' regs va vb cmp ra rb o,\n    \n    instructionAt m pc = Some (DEX_Ifcmp cmp ra rb o) ->\n    In ra (DEX_Registers.dom regs) ->\n    In rb (DEX_Registers.dom regs) ->\n    Some (Num (I va)) = DEX_Registers.get regs ra ->\n    Some (Num (I vb)) = DEX_Registers.get regs rb ->\n    ~SemCompInt cmp (Int.toZ va) (Int.toZ vb) ->\n    next m pc = Some pc' ->\n    DEX_METHOD.valid_reg m ra ->\n    DEX_METHOD.valid_reg m rb ->\n\n    DEX_NormalStep p m (pc, regs(*h, l*)) (pc', regs(*h, l*))\n\n  | ifz_step_jump : forall (*h*) m pc regs v cmp r o,\n\n    instructionAt m pc = Some (DEX_Ifz cmp r o) ->\n    In r (DEX_Registers.dom regs) ->\n    Some (Num (I v)) = DEX_Registers.get regs r ->\n    SemCompInt cmp (Int.toZ v) (0) ->\n    DEX_METHOD.valid_reg m r ->\n    \n    DEX_NormalStep p m (pc, regs(*h, l*)) ((DEX_OFFSET.jump pc o), regs(*h, l*))\n\n  | ifz_step_continue : forall (*h*) m pc pc' regs v cmp r o,\n    \n    instructionAt m pc = Some (DEX_Ifz cmp r o) ->\n    In r (DEX_Registers.dom regs) ->\n    Some (Num (I v)) = DEX_Registers.get regs r ->\n    ~SemCompInt cmp (Int.toZ v) (0) ->\n    next m pc = Some pc' ->\n\n    DEX_NormalStep p m (pc, regs(*h, l*)) (pc', regs(*h, l*))\n\n(* DEX Object\n   (** Load value from array *)\n  | aget_step_ok : forall h m pc pc' l l' loc val i length t a k rt ra ri,\n\n    instructionAt m pc = Some (DEX_Aget k rt ra ri) ->\n    next m pc = Some pc' ->\n    Some (Ref loc) = DEX_Registers.get l ra ->\n    DEX_Heap.typeof h loc = Some (DEX_Heap.LocationArray length t a) ->\n    compat_ArrayKind_type k t ->\n    Some (Num (I i)) = DEX_Registers.get l ri ->\n    (0 <= Int.toZ i < Int.toZ length)%Z ->\n    DEX_Heap.get h (DEX_Heap.ArrayElement loc (Int.toZ i)) = Some val ->\n    compat_ArrayKind_value k val ->\n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m ra ->\n    DEX_METHOD.valid_reg m ri ->\n    l' = DEX_Registers.update l rt (conv_for_stack val) -> \n\n    DEX_NormalStep p m (pc, (h, l)) (pc', (h, l'))\n\n  (** Store into array *)\n  | aput_step_ok : forall h m pc pc' l loc val i length tp k a rs ra ri, \n\n    instructionAt m pc = Some (DEX_Aput k rs ra ri) ->\n    next m pc = Some pc' ->\n    Some (Ref loc) = DEX_Registers.get l ra ->\n    DEX_Heap.typeof h loc = Some (DEX_Heap.LocationArray length tp a) ->\n    Some val = DEX_Registers.get l rs ->\n    assign_compatible p h val tp ->\n    Some (Num (I i)) = DEX_Registers.get l ri ->\n    (0 <= Int.toZ i < Int.toZ length)%Z ->\n    compat_ArrayKind_type k tp ->\n    compat_ArrayKind_value k val ->\n    DEX_METHOD.valid_reg m rs ->\n    DEX_METHOD.valid_reg m ra ->\n    DEX_METHOD.valid_reg m ri ->\n\n    DEX_NormalStep p m (pc, (h, l))\n                   (pc',((DEX_Heap.update h (DEX_Heap.ArrayElement loc (Int.toZ i)) (conv_for_array val tp)), l))\n\n  (** <addlink>iget</addlink>: Fetch field from object *)\n  | iget_step_ok : forall h m pc pc' l l' loc f v cn k rt ro,\n\n    instructionAt m pc = Some (DEX_Iget k rt ro f) ->\n    next m pc = Some pc' ->\n    Some (Ref loc) = DEX_Registers.get l ro ->\n    DEX_Heap.typeof h loc = Some (DEX_Heap.LocationObject cn) -> \n    defined_field p cn f ->\n    DEX_Heap.get h (DEX_Heap.DynamicField loc f) = Some v ->    \n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m ro ->\n    l' = DEX_Registers.update l rt v ->\n\n    DEX_NormalStep p m (pc, (h, l)) (pc', (h, l'))\n  \n  (** <addlink>iput</addlink>: Set field in object *)\n  | iput_step_ok : forall h m pc pc' l f loc cn v k rs ro,\n\n    instructionAt m pc = Some (DEX_Iput k rs ro f) ->\n    next m pc = Some pc' ->\n    Some (Ref loc) = DEX_Registers.get l ro ->\n    DEX_Heap.typeof h loc = Some (DEX_Heap.LocationObject cn) -> \n    defined_field p cn f ->\n    Some v = DEX_Registers.get l rs ->\n    assign_compatible p h v (DEX_FIELDSIGNATURE.type (snd f)) ->\n    DEX_METHOD.valid_reg m rs ->\n    DEX_METHOD.valid_reg m ro ->\n\n    DEX_NormalStep p m (pc, (h, l))\n           (pc, ((DEX_Heap.update h (DEX_Heap.DynamicField loc f) v), l))\n*)\n\n  (** <addlink>ineg</addlink>: Negate [int] *)\n  | ineg_step : forall (*h*) m pc regs regs' pc' rt rs v,\n\n    instructionAt m pc = Some (DEX_Ineg rt rs) ->\n    In rt (DEX_Registers.dom regs) ->\n    In rs (DEX_Registers.dom regs) ->\n    next m pc = Some pc' ->\n    Some (Num (I v)) = DEX_Registers.get regs rs ->\n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m rs ->\n    regs' = DEX_Registers.update regs rt (Num (I (Int.neg v))) ->\n\n    DEX_NormalStep p m (pc, regs(*h, l*)) (pc', regs'(*h, l'*))\n\n  (** <addlink>ineg</addlink>: Not [int] (one's complement) *)\n  | inot_step : forall (*h*) m pc regs regs' pc' rt rs v,\n\n    instructionAt m pc = Some (DEX_Inot rt rs) ->\n    In rt (DEX_Registers.dom regs) ->\n    In rs (DEX_Registers.dom regs) ->\n    next m pc = Some pc' ->\n    Some (Num (I v)) = DEX_Registers.get regs rs ->\n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m rs ->\n    regs' = DEX_Registers.update regs rt (Num (I (Int.not v))) ->\n\n    DEX_NormalStep p m (pc, regs(*h, l*)) (pc', regs'(*h, l'*))\n\n  (** <addlink>i2b</addlink>: Convert [int] to [byte] *)\n  | i2b_step_ok : forall (*h*) m pc pc' regs regs' rt rs v,\n\n    instructionAt m pc = Some (DEX_I2b rt rs) ->\n    In rt (DEX_Registers.dom regs) ->\n    In rs (DEX_Registers.dom regs) ->\n    next m pc = Some pc' ->\n    Some (Num (I v)) = DEX_Registers.get regs rs ->\n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m rs ->\n    regs' = DEX_Registers.update regs rt (Num (I (b2i (i2b v)))) ->\n    \n    DEX_NormalStep p m (pc, regs(*h, l*)) (pc', regs'(*h, l'*))\n\n (** <addlink>i2s</addlink>: Convert [int] to [short] *)\n  | i2s_step_ok : forall (*h*) m pc pc' regs regs' rt rs v,\n\n    instructionAt m pc = Some (DEX_I2s rt rs) ->\n    In rt (DEX_Registers.dom regs) ->\n    In rs (DEX_Registers.dom regs) ->\n    next m pc = Some pc' ->\n    Some (Num (I v)) = DEX_Registers.get regs rs ->\n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m rs ->\n    regs' = DEX_Registers.update regs rt (Num (I (s2i (i2s v)))) ->\n\n    DEX_NormalStep p m (pc, regs(*h, l*)) (pc', regs'(*h, l'*))\n\n  | ibinop_step_ok : forall (*h*) m pc pc' regs regs' op rt ra rb va vb,\n\n    instructionAt m pc = Some (DEX_Ibinop op rt ra rb) ->\n    In rt (DEX_Registers.dom regs) ->\n    In ra (DEX_Registers.dom regs) ->\n    In rb (DEX_Registers.dom regs) ->\n    next m pc = Some pc' ->\n    (*(op = DivInt \\/ op = RemInt -> ~ Int.toZ i2 = 0) -> at this moment there is no exception*)\n    Some (Num (I va)) = DEX_Registers.get regs ra ->\n    Some (Num (I vb)) = DEX_Registers.get regs rb ->\n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m ra ->\n    DEX_METHOD.valid_reg m rb ->\n    regs' = DEX_Registers.update regs rt (Num (I (SemBinopInt op va vb))) ->\n\n    DEX_NormalStep p m (pc, regs(*h, l*)) (pc', regs'(*h, l'*))\n\n  | ibinopconst_step_ok : forall (*h*) m pc pc' regs regs' op rt r va v,\n\n    instructionAt m pc = Some (DEX_IbinopConst op rt r v) ->\n    In r (DEX_Registers.dom regs) ->\n    In rt (DEX_Registers.dom regs) ->\n    next m pc = Some pc' ->\n    (*(op = DivInt \\/ op = RemInt -> ~ Int.toZ i2 = 0) -> at this moment there is no exception*)\n    Some (Num (I va)) = DEX_Registers.get regs r ->\n    DEX_METHOD.valid_reg m rt ->\n    DEX_METHOD.valid_reg m r ->\n    regs' = DEX_Registers.update regs rt (Num (I (SemBinopInt op va (Int.const v)))) ->\n\n    DEX_NormalStep p m (pc, regs(*h, l*)) (pc', regs'(*h, l'*))\n.\n\n\n(*  Inductive JVMExceptionStep  (p:Program) : Method -> IntraNormalState -> ShortClassName -> Prop :=\n  | arraylength_NullPointerException : forall h m pc s l,\n\n    instructionAt m pc = Some Arraylength ->\n\n    JVMExceptionStep p m (pc,(h,(Null::s),l))  NullPointerException\n\n  | athrow_NullPointerException : forall h m pc s l,\n\n    instructionAt m pc = Some Athrow ->\n\n    JVMExceptionStep p m (pc,(h,(Null::s),l)) NullPointerException\n\n  | checkcast_ClassCastException : forall h m pc s l loc t,\n\n    instructionAt m pc = Some (Checkcast t) ->\n    ~ assign_compatible p h (Ref loc) (ReferenceType t) ->\n\n    JVMExceptionStep p m (pc,(h,(Ref loc::s),l)) ClassCastException\n\n  | getfield_NullPointerException : forall h m pc s l f ,\n\n    instructionAt m pc = Some (Getfield f) ->\n\n    JVMExceptionStep p m (pc,(h,(Null::s),l)) NullPointerException\n\n | ibinop_ArithmeticException : forall h m pc s l op i1 i2,\n\n    instructionAt m pc = Some (Ibinop op) ->\n    op = DivInt \\/ op = RemInt ->\n    Int.toZ i2 = 0%Z ->\n\n    JVMExceptionStep p m (pc,(h,(Num (I i2)::Num (I i1)::s),l)) ArithmeticException\n\n  | invokevirtual_NullPointerException : forall h m pc s l mid args,\n\n    instructionAt m pc = Some (Invokevirtual mid) ->\n    length args = length (METHODSIGNATURE.parameters (snd mid)) ->\n\n    JVMExceptionStep p m (pc,(h,(args++Null::s),l)) NullPointerException\n\n  | newarray_NegativeArraySizeException : forall h m pc s l t i,\n\n    instructionAt m pc = Some (Newarray t) ->\n    (~ 0 <= Int.toZ i)%Z ->\n\n    JVMExceptionStep p m (pc,(h,(Num (I i)::s),l)) NegativeArraySizeException\n\n  | putfield_NullPointerException : forall h m pc s l f v,\n\n    instructionAt m pc = Some (Putfield f) ->\n   \n    JVMExceptionStep p m (pc,(h,(v::Null::s),l)) NullPointerException\n\n  | vaload_NullPointerException : forall h m pc s l i k,\n\n    instructionAt m pc = Some (Vaload k) ->\n\n    JVMExceptionStep p m (pc,(h,((Num (I i))::Null::s),l)) NullPointerException\n\n  | vaload_ArrayIndexOutOfBoundsException : forall h m pc s l loc i length t k a,\n\n    instructionAt m pc = Some (Vaload k) ->\n    Heap.typeof h loc = Some (Heap.LocationArray length t a) ->\n    compat_ArrayKind_type k t ->\n    (~ 0 <= Int.toZ i < Int.toZ length)%Z ->\n\n    JVMExceptionStep p m (pc,(h,((Num (I i))::(Ref loc)::s),l)) ArrayIndexOutOfBoundsException\n\n  | vastore_NullPointerException : forall h m pc s l val i k,\n\n    instructionAt m pc = Some (Vastore k) ->\n    compat_ArrayKind_value k val ->\n\n    JVMExceptionStep p m (pc,(h,(val::(Num (I i))::Null::s),l)) NullPointerException\n\n  | vastore_ArrayIndexOutOfBoundsException : forall h m pc s l loc val i t length k a,\n\n    instructionAt m pc = Some (Vastore k) ->\n    Heap.typeof h loc = Some (Heap.LocationArray length t a) ->\n    (~ 0 <= Int.toZ i < Int.toZ length)%Z ->\n    compat_ArrayKind_type k t ->\n    compat_ArrayKind_value k val ->\n\n    JVMExceptionStep p m (pc,(h,(val::(Num (I i))::(Ref loc)::s),l)) ArrayIndexOutOfBoundsException\n\n  | vastore_ArrayStoreException : forall h m pc s l loc val i t k length a,\n\n    instructionAt m pc = Some (Vastore k) ->\n    Heap.typeof h loc = Some (Heap.LocationArray length t a) ->\n    ~ assign_compatible p h val t ->\n    (0 <= Int.toZ i < Int.toZ length)%Z ->\n    compat_ArrayKind_type k t ->\n    compat_ArrayKind_value k val ->\n\n    JVMExceptionStep p m (pc,(h,(val::(Num (I i))::(Ref loc)::s),l)) ArrayStoreException\n.\n\n  Inductive ExceptionStep (p:Program) : Method -> IntraNormalState -> IntraExceptionState -> Prop :=\n  | athrow : forall h m pc s l loc cn,\n\n    instructionAt m pc = Some Athrow ->\n    Heap.typeof h loc = Some (Heap.LocationObject cn) ->\n    subclass_name p cn javaLangThrowable ->\n    ExceptionStep p m (pc,(h,(Ref loc::s),l)) (h,loc)\n\n  | jvm_exception : forall h m pc s l h' loc (e:ShortClassName),\n\n    JVMExceptionStep p m (pc,(h,s,l)) e ->\n    Heap.new h p (Heap.LocationObject (javaLang,e)) = Some (loc,h') ->\n\n    ExceptionStep p m (pc,(h,s,l)) (h',loc).\n*)\n\n(* DEX Method\n  Inductive DEX_CallStep (p:DEX_Program) : DEX_Method -> DEX_IntraNormalState -> DEX_InitCallState -> Prop :=\n  | invokestatic : forall h m pc l mid M args bM n,\n\n    instructionAt m pc = Some (DEX_Invokestatic mid n args) ->\n    findMethod p mid = Some M ->\n    DEX_METHOD.isNative M = false ->\n    length args = length (DEX_METHODSIGNATURE.parameters (snd mid)) ->\n    DEX_METHOD.body M = Some bM ->\n    DEX_METHOD.isStatic M = true ->\n    \n    DEX_CallStep p m (pc,(h, l)) (M, (listreg2regs l (length args) args))\n\n  | invokevirtual : forall h m pc l mid M args loc bM n,\n\n    instructionAt m pc = Some (DEX_Invokevirtual mid n args) ->\n    (*lookup p cn mid (pair cl M) ->*)\n    findMethod p mid = Some M ->\n    DEX_Heap.typeof h loc = Some (DEX_Heap.LocationObject (fst mid)) ->\n    length args = length (DEX_METHODSIGNATURE.parameters (snd mid)) ->\n    DEX_METHOD.body M = Some bM ->\n    DEX_METHOD.isStatic M = false ->\n \n    DEX_CallStep p m (pc,(h, l)) (M,(listreg2regs l (length args) args))\n  .\n*)\n\n  Inductive DEX_ReturnStep (p:DEX_Program) : DEX_Method -> DEX_IntraNormalState -> DEX_ReturnState -> Prop :=\n  | void_return : forall (*h*) m pc regs,\n\n    instructionAt m pc = Some DEX_Return -> \n    DEX_METHODSIGNATURE.result (DEX_METHOD.signature m) = None ->\n\n    DEX_ReturnStep p m (pc, regs(*h, l*)) (Normal None)(*h, Normal None*)\n\n  | vreturn : forall (*h*) m pc regs val t k rs,\n    (* Implicit in the assumption is that the register has a value in it *)\n    instructionAt m pc = Some (DEX_VReturn k rs) ->\n    In rs (DEX_Registers.dom regs) ->\n    DEX_METHODSIGNATURE.result (DEX_METHOD.signature m) = Some t ->\n    assign_compatible p (*h*) val t ->\n    compat_ValKind_value k val ->\n    Some val = DEX_Registers.get regs rs ->\n\n    DEX_ReturnStep p m (pc, regs(*h, l*)) (Normal (Some val))(*h, Normal (Some val)*)\n.\n\n(* DEX Method\n  Inductive DEX_call_and_return : DEX_Method -> DEX_IntraNormalState -> DEX_InitCallState -> DEX_IntraNormalState -> DEX_ReturnState -> DEX_IntraNormalState -> Prop :=\n  | call_and_return_void : forall m pc h l m' l' bm' h'' pc',\n      next m pc = Some pc' -> \n      DEX_METHOD.body m' = Some bm' ->\n      DEX_call_and_return\n                 m\n                 (pc, (h,l))\n                 (m', l')\n                  (DEX_BYTECODEMETHOD.firstAddress bm',(h, l'))\n                 (h'', Normal None) \n                 (pc',(h'', l))\n  | call_and_return_value : forall m pc h l m' l' bm' h'' v pc' l'',\n      next m pc = Some pc' -> \n      DEX_METHOD.body m' = Some bm' ->\n      l'' = DEX_Registers.update l DEX_Registers.ret v ->\n      DEX_call_and_return\n                 m\n                 (pc, (h, l))\n                 (m', l')\n                 (DEX_BYTECODEMETHOD.firstAddress bm',(h, l'))\n                 (h'', Normal (Some v)) \n                 (pc',(h'', l'')).\n*)\n\n\n(*\n  Inductive call_and_return_exception : Method -> IntraNormalState -> InitCallState -> IntraNormalState -> ReturnState -> IntraExceptionState -> Prop :=\n  | call_and_return_exception_def : forall m pc h s l m' l' bm' h'' s' loc,\n      METHOD.body m' = Some bm' ->\n      call_and_return_exception\n                 m\n                 (pc,(h,s,l))\n                 (m',(s',l'))\n                 (BYTECODEMETHOD.firstAddress bm',(h,OperandStack.empty,l'))\n                 (h'',Exception loc) \n                 (h'',loc).\n*)\n  Inductive DEX_exec_intra (p:DEX_Program) (m:DEX_Method) : DEX_IntraNormalState -> DEX_IntraNormalState -> Prop :=\n  | exec_intra_normal : forall s1 s2,\n     DEX_NormalStep p m s1 s2 ->\n     DEX_exec_intra p m s1 s2\n  (*| exec_exception : forall pc1 h1 h2 loc2 s1 l1 pc',\n   ExceptionStep p m (pc1,(h1,s1,l1)) (h2,loc2) ->\n   CaughtException p m (pc1,h2,loc2) pc' ->\n   exec_intra p m (pc1,(h1,s1,l1)) (pc',(h2,Ref loc2::OperandStack.empty,l1))*)\n.\n\n  Inductive DEX_exec_return (p:DEX_Program) (m:DEX_Method) : DEX_IntraNormalState -> DEX_ReturnState -> Prop :=\n  | exec_return_normal : forall s (*h*) ov,\n     DEX_ReturnStep p m s (Normal ov)(*h,Normal ov*) ->\n     DEX_exec_return p m s (Normal ov)(*h,Normal ov*)\n(*  | exec_return_exception : forall pc1 h1 h2 loc2 s1 l1,\n     ExceptionStep p m (pc1,(h1,s1,l1)) (h2,loc2) ->\n     UnCaughtException  p m (pc1,h2,loc2) ->\n     exec_return p m (pc1,(h1,s1,l1)) (h2,Exception loc2)*)\n.\n\n(* DEX Method\n  Inductive DEX_exec_call (p:DEX_Program) (m:DEX_Method) :\n   DEX_IntraNormalState -> DEX_ReturnState -> DEX_Method  -> DEX_IntraNormalState -> DEX_IntraNormalState+DEX_ReturnState -> Prop :=\n | exec_call_normal : forall m2 pc1 pc1' h1 l1 l2 h2 bm2 ov l1',\n     DEX_CallStep p m (pc1,(h1, l1 )) (m2, l2) ->\n     DEX_METHOD.body m2 = Some bm2 ->\n     next m pc1 = Some pc1' ->\n     l1' = DEX_Registers.update l1 DEX_Registers.ret ov ->\n     DEX_exec_call p m\n        (pc1,(h1, l1))\n        (h2,Normal (Some ov))\n        m2\n        (DEX_BYTECODEMETHOD.firstAddress bm2, (h1, l2))\n        (inl _ (pc1',(h2, l1')))\n(*\n | exec_call_caught : forall m2 pc1 pc1' h1 s1 l1 os l2 h2 loc bm2,\n     CallStep p m (pc1,(h1,s1,l1 )) (m2,(os,l2)) ->\n     METHOD.body m2 = Some bm2 ->\n     CaughtException p m (pc1, h2, loc) pc1' ->\n     exec_call p m\n        (pc1,(h1,s1,l1))\n        (h2,Exception loc)\n        m2\n        (BYTECODEMETHOD.firstAddress bm2,(h1,OperandStack.empty,l2))\n        (inl _(pc1',(h2,Ref loc::nil,l1)))\n | exec_call_uncaught : forall m2 pc1 h1 s1 l1 os l2 h2 loc bm2,\n     CallStep p m (pc1,(h1,s1,l1 )) (m2,(os,l2)) ->\n     METHOD.body m2 = Some bm2 ->\n     UnCaughtException p m (pc1, h2, loc)  ->\n     exec_call p m\n       (pc1,(h1,s1,l1))\n       (h2,Exception loc)\n       m2\n       (BYTECODEMETHOD.firstAddress bm2,(h1,OperandStack.empty,l2))\n       (inr _ (h2,Exception loc))*).\n*)\n\n Inductive DEX_IntraStep (p:DEX_Program) : \n    DEX_Method -> DEX_IntraNormalState -> DEX_IntraNormalState + DEX_ReturnState -> Prop :=\n  | IntraStep_res :forall m s ret,\n     DEX_exec_return p m s ret ->\n     DEX_IntraStep p m s (inr _ ret)\n  | IntraStep_intra_step:forall m s1 s2,\n     DEX_exec_intra p m s1 s2 ->\n     DEX_IntraStep p m s1 (inl _ s2) \n(* DEX Method\n  | IntraStep_call :forall m m' s1 s' ret' r,\n     DEX_exec_call p m s1 ret' m' s' r ->\n     TransStep_l (DEX_IntraStep p m') s' (inr _ ret') ->\n     DEX_IntraStep p m s1 r*) .\n \n Definition DEX_IntraStepStar p m s r := TransStep_l (DEX_IntraStep p m) s r.\n\n Definition DEX_IntraStepStar_intra p m s s' := DEX_IntraStepStar p m s (inl _ s').\n\n Definition DEX_BigStep  p m s ret := DEX_IntraStepStar p m s (inr _ ret).\n\n Inductive DEX_ReachableStep (P:DEX_Program) : \n      (DEX_Method*DEX_IntraNormalState)->(DEX_Method*DEX_IntraNormalState) ->Prop :=\n   | ReachableIntra : forall M s s', \n       DEX_IntraStep P M s (inl _ s') ->\n       DEX_ReachableStep P (M,s) (M,s')\n(* DEX Method\n   | Reachable_invS : forall M pc h l M' l' bm',\n       DEX_CallStep P M (pc,(h, l)) (M', l') ->\n       DEX_METHOD.body M' = Some bm' ->\n       DEX_ReachableStep P (M, (pc,(h, l)))\n         (M', (DEX_BYTECODEMETHOD.firstAddress bm',(h, l')))*).\n\n Definition DEX_Reachable P M s s' := \n   exists M',  ClosReflTrans (DEX_ReachableStep P) (M,s) (M',s').\n", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/DEX_BigStepLoad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.21043926059305898}}
{"text": "Require Import CodeProofDeps.\nRequire Import Ident.\nRequire Import Constants.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import RunSMC.Layer.\nRequire Import TableAux.Code.table_maps_block.\n\nRequire Import TableAux.LowSpecs.table_maps_block.\n\nLocal Open Scope Z_scope.\n\nSection CodeProof.\n\n  Context `{real_params: RealParams}.\n  Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n  Context `{Hmwd: UseMemWithData memb}.\n\n  Let mem := mwd (cdata RData).\n\n  Context `{Hstencil: Stencil}.\n  Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n  Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n  Let L : compatlayer (cdata RData) :=\n    _pgte_read ↦ gensem pgte_read_spec\n      ⊕ _entry_to_phys ↦ gensem entry_to_phys_spec\n      ⊕ _addr_is_level_aligned ↦ gensem addr_is_level_aligned_spec\n  .\n\n  Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n  Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n  Section BodyProof.\n\n    Context `{Hwb: WritableBlockOps}.\n    Variable (sc: stencil).\n    Variables (ge: genv) (STENCIL_MATCHES: stencil_matches sc ge).\n\n    Variable b_pgte_read: block.\n    Hypothesis h_pgte_read_s : Genv.find_symbol ge _pgte_read = Some b_pgte_read.\n    Hypothesis h_pgte_read_p : Genv.find_funct_ptr ge b_pgte_read\n                               = Some (External (EF_external _pgte_read\n                                                (signature_of_type (Tcons Tptr (Tcons tulong Tnil)) tulong cc_default))\n                                      (Tcons Tptr (Tcons tulong Tnil)) tulong cc_default).\n    Local Opaque pgte_read_spec.\n\n    Variable b_entry_to_phys: block.\n    Hypothesis h_entry_to_phys_s : Genv.find_symbol ge _entry_to_phys = Some b_entry_to_phys.\n    Hypothesis h_entry_to_phys_p : Genv.find_funct_ptr ge b_entry_to_phys\n                                   = Some (External (EF_external _entry_to_phys\n                                                    (signature_of_type (Tcons tulong (Tcons tulong Tnil)) tulong cc_default))\n                                          (Tcons tulong (Tcons tulong Tnil)) tulong cc_default).\n    Local Opaque entry_to_phys_spec.\n\n    Variable b_addr_is_level_aligned: block.\n    Hypothesis h_addr_is_level_aligned_s : Genv.find_symbol ge _addr_is_level_aligned = Some b_addr_is_level_aligned.\n    Hypothesis h_addr_is_level_aligned_p : Genv.find_funct_ptr ge b_addr_is_level_aligned\n                                           = Some (External (EF_external _addr_is_level_aligned\n                                                            (signature_of_type (Tcons tulong (Tcons tulong Tnil)) tuint cc_default))\n                                                  (Tcons tulong (Tcons tulong Tnil)) tuint cc_default).\n    Local Opaque addr_is_level_aligned_spec.\n\n\n    Ltac solve_func64 val :=\n      try unfold Monad.bind; try unfold ret; simpl;\n      match goal with\n      | [|- match ?v with | Some _ => _ | None => None end = _] =>\n          replace v with (Some (VZ64 (Int64.unsigned (Int64.repr val))))\n      end.\n\n    Ltac solve_func val :=\n      try unfold Monad.bind; try unfold ret; simpl;\n      match goal with\n      | [|- match ?v with | Some _ => _ | None => None end = _] =>\n          replace v with (Some (Int.unsigned (Int.repr val)))\n      end.\n\n    Lemma table_maps_block_body_correct:\n      forall m d env le table_base table_offset level ipa_state res\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTtable: PTree.get _table le = Some (Vptr table_base (Int.repr table_offset)))\n             (HPTlevel: PTree.get _level le = Some (Vlong level))\n             (HPTipa_state: PTree.get _ipa_state le = Some (Vlong ipa_state))\n             (Hspec: table_maps_block_spec0 (table_base, table_offset) (VZ64 (Int64.unsigned level)) (VZ64 (Int64.unsigned ipa_state)) d = Some (Int.unsigned res)),\n           exists le', (exec_stmt ge env le ((m, d): mem) table_maps_block_body E0 le' (m, d) (Out_return (Some (Vint res, tuint)))).\n    Proof.\n      solve_code_proof Hspec table_maps_block_body.\n      - eexists. repeat big_vcgen.\n        solve_func64 z0. reflexivity.\n        symmetry. repeat sstep. assumption. somega.\n        solve_func64 z2. reflexivity.\n        symmetry. repeat sstep.\n        rewrite C8. reflexivity.\n        somega. somega. somega. somega.\n        solve_proof_low.\n        simpl. solve_proof_low.\n      - get_loop_body. clear_hyp.\n        set (Hloop := C11). simpl; solve_proof_low.\n        remember\n            (PTree.set _i (Vint (Int.repr 0))\n                (PTree.set _ret (Vint (Int.repr 1))\n                  (PTree.set _t'5 (Vint (Int.repr z3))\n                      (PTree.set _base_pa (Vlong (Int64.repr z2))\n                        (PTree.set _t'2 (Vlong (Int64.repr z2))\n                            (PTree.set _pgte (Vlong (Int64.repr z0))\n                              (PTree.set _t'1 (Vlong (Int64.repr z0)) le)))))))\n            as le_loop.\n        remember 512 as num.\n        set (P := fun le0 m0 => m0 = (m, d) /\\ le0 = le_loop).\n        set (Q := fun (le0: temp_env) m0 => m0 = (m, d) /\\ le0 ! _ret = Some (Vint res)).\n        set (Inv := fun le0 m0 n => exists i' ret',\n                        table_maps_block_loop0 (Z.to_nat (num - n)) 0 1 (table_base, table_offset) z2\n                                               (Int64.unsigned level) (Int64.unsigned ipa_state) d =\n                          Some (Int.unsigned i', Int.unsigned ret') /\\ Int.unsigned i' = num - n /\\\n                          m0 = (m, d) /\\ 0 <= n /\\ n <= num /\\ le0 ! _i = Some (Vint i') /\\\n                          le0 ! _table = Some (Vptr table_base (Int.repr table_offset)) /\\\n                          le0 ! _level = Some (Vlong level) /\\\n                          le0 ! _ipa_state = Some (Vlong ipa_state) /\\\n                          le0 ! _ret = Some (Vint ret') /\\\n                          le0 ! _base_pa = Some (Vlong (Int64.repr z2))).\n        assert(loop_succ: forall N, Z.of_nat N <= num -> exists i' ret',\n                    table_maps_block_loop0 (Z.to_nat (num - Z.of_nat N)) 0 1\n                                           (table_base, table_offset) z2\n                                           (Int64.unsigned level) (Int64.unsigned ipa_state) d =\n                      Some (Int.unsigned i', Int.unsigned ret')).\n        { add_int Hloop z4; try somega.\n          induction N. rewrite Z.sub_0_r. rewrite Hloop. intros. repeat eexists; reflexivity.\n          intros. erewrite loop_ind_sub1 in IHN; try omega.\n          rewrite Nat2Z.inj_succ, succ_plus_1 in H.\n          assert(Hcc: Z.of_nat N <= num) by omega.\n          apply IHN in Hcc. destruct Hcc as (? & ? & Hnext).\n          Local Opaque Z.of_nat. simpl in Hnext. clear Heqle_loop.\n          simpl_func Hnext; try add_int' z; try somega; try add_int' z1; try somega; repeat eexists. }\n        assert (T: LoopProofSimpleWhile.t (external_calls_ops := CompatExternalCalls.compatlayer_extcall_ops L) cond body ge (PTree.empty _) P Q).\n        { apply LoopProofSimpleWhile.make with (W:=Z) (lt:=fun z1 z2 => (0 <= z2 /\\ z1 < z2)) (I:=Inv).\n          - apply Zwf_well_founded.\n          - unfold P, Inv. intros ? ? CC. destruct CC as [CC1 CC2].\n            rewrite CC2 in *. exists num.\n            replace (num - num) with 0 by omega. simpl.\n            exists (Int.repr 0). exists (Int.repr 1).\n            rewrite Heqnum. rewrite Heqle_loop.\n            repeat eexists; first [reflexivity|assumption|solve_proof_low].\n          - intros ? ? ? I. unfold Inv in I.\n            destruct I as (? & ? & ? & ? & ? & ? & ? & ? & ? & ? & ? & ? & ?).\n            set (Hnow := H).\n            rewrite Heqbody, Heqcond in *.\n            destruct (n >? 0) eqn:Hn; bool_rel.\n            + eexists. eexists. split_and.\n              * solve_proof_low.\n              * solve_proof_low.\n              * intro CC. inversion CC.\n              * assert(Hlx: Z.of_nat (Z.to_nat (n-1)) <= num) by (rewrite Z2Nat.id; omega).\n                apply loop_succ in Hlx. rewrite Z2Nat.id in Hlx; try omega.\n                intro. destruct Hlx as (? & ? & Hnext). duplicate Hnext.\n                rewrite loop_nat_sub1 in Hnext; try somega.\n                simpl in Hnext. rewrite Hnow in Hnext.\n                autounfold in Hnext; repeat simpl_hyp Hnext;\n                  repeat destruct_con; bool_rel; contra; inversion Hnext.\n                rewrite H12, H13 in *; eexists; eexists; split.\n                repeat big_vcgen.\n                solve_func64 z1. reflexivity.\n                symmetry. repeat sstep. assumption. somega.\n                solve_proof_low. somega. somega. somega. somega. somega. somega.\n                somega. somega. simpl.\n                solve_proof_low. solve_proof_low.\n                solve_proof_low. somega.\n                exists (n-1); split. split; solve_proof_low.\n                solve_proof_low; unfold Inv; repeat eexists; first[eassumption|solve_proof_low].\n                rewrite <- (Int.repr_unsigned x2). rewrite <- H13.\n                rewrite Int.repr_unsigned. assumption.\n\n                rewrite H12, H13 in *; eexists; eexists; split.\n                repeat big_vcgen.\n                solve_func64 z1. reflexivity.\n                symmetry. repeat sstep. assumption. somega.\n                solve_proof_low. somega. somega. somega. somega. somega. somega.\n                somega. somega. simpl.\n                solve_proof_low. solve_proof_low.\n                solve_proof_low. somega.\n                exists (n-1); split. split; solve_proof_low.\n                solve_proof_low; unfold Inv; repeat eexists; first[eassumption|solve_proof_low].\n                rewrite H12. rewrite H13. rewrite D. sstep. reflexivity.\n                rewrite H12. sstep. omega.\n\n                rewrite H12, H13 in *; eexists; eexists; split.\n                repeat big_vcgen.\n                solve_func64 z1. reflexivity.\n                symmetry. repeat sstep. assumption. somega.\n                solve_proof_low. somega. somega. somega. somega. somega. somega.\n                somega. somega. somega. somega.  simpl.\n                solve_proof_low. solve_proof_low.\n                solve_proof_low. somega.\n                exists (n-1); split. split; solve_proof_low.\n                solve_proof_low; unfold Inv; repeat eexists; first[eassumption|solve_proof_low].\n                rewrite H12. rewrite H13. rewrite D. sstep. reflexivity.\n                rewrite H12. sstep. omega.\n            + eexists. eexists. split_and.\n              * solve_proof_low.\n              * solve_proof_low.\n              * intro. unfold Q.\n                assert (n=0) by omega. clear Heqle_loop. subst.\n                sstep. rewrite Hloop in Hnow. inv Hnow.\n                split_and; first[reflexivity|solve_proof_low].\n              * intro CC. inversion CC. }\n        assert (Pre: P le_loop (m, d)) by (split; reflexivity).\n        pose proof (LoopProofSimpleWhile.termination _ _ _ _ _ _ T _ (m, d) Pre) as LoopProof.\n        destruct LoopProof as (le' & m' & (exec & Post)).\n        unfold exec_stmt in exec. rewrite Heqle_loop in exec.\n        unfold Q in Post. destruct Post as (Post & Hle'). rewrite Post in exec.\n\n        eexists. repeat big_vcgen.\n        solve_func64 z0. reflexivity.\n        symmetry. repeat sstep. assumption. somega. somega.\n        solve_func64 z2. reflexivity.\n        symmetry. repeat sstep.\n        solve_func z3. reflexivity.\n        symmetry. sstep. assumption. somega. somega. somega. somega.\n        solve_proof_low. simpl.\n        solve_proof_low.\n      Qed.\n\n\n\n  End BodyProof.\n\nEnd CodeProof.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableAux/CodeProof/table_maps_block.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21039512241972638}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp\nRequire Import path.\nRequire Import Eqdep.\nRequire Import Relation_Operators.\nFrom fcsl\nRequire Import axioms pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL\nRequire Import Freshness State EqTypeX Protocols Worlds NetworkSem Rely.\nFrom DiSeL\nRequire Import Actions Injection Process Always HoareTriples InferenceRules.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nModule LockProtocol.\nSection LockProtocol.\n\nVariable server : nid.\nVariable clients : seq nid.\n\nHypothesis Hnin : server \\notin clients.\nHypothesis Huniq : uniq clients.\n\nLemma client_not_server n : n \\in clients -> (n == server) = false.\nProof.\n  move=>H.\n  case E: (n == server)=>//.\n  move/eqP in E. subst n.\n  move: (Hnin).\n  by rewrite H.\nQed.\n\nDefinition nodes := [:: server] ++ clients.\n\nLemma client_nodes n : n \\in clients -> n \\in nodes.\nProof.\n  by rewrite inE orbC/= =>->.\nQed.\n\nNotation epoch := nat (only parsing).\n\nRecord server_state :=\n  ServerState {\n      outstanding : seq nid;\n      current_epoch : epoch;\n      current_holder : option nid\n    }.\n\nInductive client_state :=\n| NotHeld\n| Held of epoch.\n\nDefinition acquire_tag := 0.\nDefinition grant_tag := 1.\nDefinition release_tag := 2.\n\nDefinition msg_from_server ms e :=\n  (tag ms == grant_tag) && (tms_cont ms == [:: e]).\n\nDefinition msg_from_client ms :=\n  ((tag ms == acquire_tag) || (tag ms == release_tag)) &&\n  (tms_cont ms == [::]).\n\nDefinition coh_msg pkt e :=\n  if from pkt == server\n  then to pkt \\in clients /\\ msg_from_server (content pkt) e\n  else if from pkt \\in clients\n  then to pkt == server /\\ msg_from_client (content pkt)\n  else False.\n\nDefinition st := ptr_nat 1.\n\nDefinition client_local_coh (cs : client_state) :=\n  [Pred h | h = st :-> cs].\n\nDefinition server_local_coh (ss : server_state) :=\n  [Pred h | h = st :-> ss].\n\nDefinition local_coh (n : nid) :=\n  [Pred h | valid h /\\\n   if n == server\n   then exists ss, server_local_coh ss h\n   else n \\in clients /\\\n        exists cs, client_local_coh cs h].\n\nDefinition soup_coh : Pred soup :=\n  [Pred s |\n    valid s /\\\n    forall m ms, find m s = Some ms -> active ms -> exists e, coh_msg ms e].\n\nLemma soup_coh_post_msg d m:\n    soup_coh (dsoup d) -> (exists e, coh_msg m e) -> soup_coh (post_msg (dsoup d) m).1.\nProof.\nmove=>[H1 H2][y]Cm; split=>[|i ms/=]; first by rewrite valid_fresh.\nrewrite findUnL; last by rewrite valid_fresh.\ncase: ifP=>E; first by move/H2.\nby move/findPt_inv=>[Z G]; subst i m; exists y.\nQed.\n\nDefinition state_coh d :=\n  forall n, n \\in nodes -> local_coh n (getLocal n d).\n\nDefinition lock_coh d :=\n  let: dl := dstate d in\n  let: ds := dsoup d in\n  [/\\ soup_coh ds\n   , dom dl =i nodes\n   , valid dl\n   & state_coh d].\n\nLemma l1 d: lock_coh d -> valid (dstate d).\nProof. by case. Qed.\n\nLemma l2 d: lock_coh d -> valid (dsoup d).\nProof. by case; case. Qed.\n\nLemma l3 d: lock_coh d -> dom (dstate d) =i nodes.\nProof. by case. Qed.\n\nDefinition LockCoh := CohPred (CohPredMixin l1 l2 l3).\n\nLemma consume_coh d m : LockCoh d -> soup_coh (consume_msg (dsoup d) m).\nProof.\nmove=>C; split=>[|m' msg]; first by apply: consume_valid; rewrite (cohVs C).\ncase X: (m == m');[move/eqP: X=><-{m'}|].\n- case/(find_mark (cohVs C))=>tms[E]->{msg}.\n  by case:(C); case=>_/(_ m tms E).\nrewrite eq_sym in X.\nrewrite (mark_other (cohVs C) X)=>E.\nby case:(C); case=>_; move/(_ m' msg E).\nQed.\n\nLemma coh_dom_upd this d s :\n  this \\in nodes -> LockCoh d -> dom (upd this s (dstate d)) =i nodes.\nProof.\nmove=>D C z; rewrite -(cohDom C) domU inE/=.\nby case: ifP=>///eqP->{z}; rewrite (cohDom C) D; apply: cohVl C.\nQed.\n\nDefinition server_send_step (ss : server_state) (to : nid) : server_state :=\n  if to \\in clients\n  then if outstanding ss is _ :: out'\n       then ServerState out' (S (current_epoch ss)) (Some to)\n       else ss\n  else ss.\n\nDefinition client_send_step (cs : client_state) : client_state :=\n  NotHeld. (* ! *)\n\n\n\nDefinition server_recv_step (ss : server_state) (from : nid)\n           (mtag : nat) (mbody : seq nat) : server_state :=\n  if mtag == acquire_tag\n  then\n    ServerState (rcons (outstanding ss) from) (current_epoch ss) (current_holder ss)\n  else (* mtag == release_tag *)\n    ServerState (outstanding ss) (current_epoch ss) None.\n\n\nDefinition client_recv_step (cs : client_state) (from : nid)\n           (mtag : nat) (mbody : seq nat) : client_state :=\n  if mbody is [:: e]\n  then Held e\n  else NotHeld.\n\nSection GetterLemmas.\n\nLemma getLocal_coh n d (C : LockCoh d):\n  n \\in nodes ->\n  valid (getLocal n d) /\\\n  if n == server\n  then exists (ss : server_state),\n      getLocal n d = st :-> ss\n  else (n \\in clients) /\\\n       exists (cs : client_state),\n           getLocal n d = st :-> cs.\nProof.\n  by case: C=>_ _ _ /(_ n)G; rewrite /local_coh/=.\nQed.\n\nLemma getLocal_server_st_tp d (C : LockCoh d) s:\n  find st (getLocal server d) = Some s ->\n  dyn_tp s = server_state.\nProof.\nhave pf: server \\in nodes by rewrite inE eqxx.\nmove: (getLocal_coh C pf); rewrite eqxx; move =>[V][s']Z; rewrite Z in V *.\nrewrite findPt /=.\nby case =><-.\nQed.\n\nLemma getLocal_client_st_tp n d (C : LockCoh d) (H : n \\in clients) s:\n  find st (getLocal n d) = Some s ->\n  dyn_tp s = client_state.\nProof.\nhave pf: n \\in nodes by rewrite inE/= orbC H.\nmove: (getLocal_coh C pf); rewrite H=>[[V]].\nrewrite client_not_server//.\nmove=>[_][cs] L. rewrite L in V *.\nrewrite findPt /=.\nby case=> <-.\nQed.\n\nDefinition getSt_server d (C : LockCoh d) : server_state :=\n  match find st (getLocal server d) as f return _ = f -> _ with\n    Some v => fun epf => icast (sym_eq (getLocal_server_st_tp C epf)) (dyn_val v)\n  | _ => fun epf => ServerState [::] 0 None\n  end (erefl _).\n\nLemma getSt_server_K d (C : LockCoh d) m :\n  getLocal server d = st :-> m -> getSt_server C = m.\nProof.\nmove=>E; rewrite /getSt_server/=.\nhave pf: server \\in nodes by rewrite inE eqxx.\nhave V: valid (getLocal server d) by case: (getLocal_coh C pf).\nmove: (getLocal_server_st_tp C); rewrite !E=>/= H.\nby apply: eqc.\nQed.\n\nProgram Definition getSt_client c d (C : LockCoh d) (pf : c \\in nodes) : client_state.\ncase X: (c \\in clients); last by exact: NotHeld.\nexact: (match find st (getLocal c d) as f return _ = f -> _ with\n    Some v => fun epf => icast (sym_eq (getLocal_client_st_tp C X epf)) (dyn_val v)\n  | _ => fun epf => NotHeld\n  end (erefl _)).\nDefined.\n\nLemma getSt_client_K c d (C : LockCoh d) (pf : c \\in nodes) m :\n  c \\in clients -> getLocal c d = st :-> m -> getSt_client C pf = m.\nProof.\nmove=>X E; rewrite /getSt_client/=.\nhave V: valid (getLocal c d) by case: (getLocal_coh C pf).\nmove: (getLocal_client_st_tp C); rewrite X !E=>/= H.\nby apply: eqc.\nQed.\n\nEnd GetterLemmas.\n\nSection ServerGenericSendTransitions.\n\nDefinition HServ this to := (this == server /\\ to \\in clients).\n\nVariable the_tag : nat.\n\nVariable prec : server_state -> nid -> seq nid -> Prop.\n\nHypothesis prec_safe :\n  forall this to s m,\n    HServ this to ->\n    prec s to m ->\n    coh_msg (Msg (TMsg the_tag m) this to true) (current_epoch s).\n\nNotation coh := LockCoh.\n\nDefinition server_send_safe (this n : nid)\n           (d : dstatelet) (msg : seq nat) :=\n  HServ this n /\\\n  exists (C : coh d), prec (getSt_server C) n msg.\n\nLemma server_send_safe_coh this to d m : server_send_safe this to d m -> coh d.\nProof. by case=>_[]. Qed.\n\nLemma server_send_this_in this to : HServ this to -> this \\in nodes.\nProof. by case=>/eqP->; rewrite inE eqxx. Qed.\n\nLemma server_send_to_in this to : HServ this to -> to \\in nodes.\nProof. by case=>_; rewrite /nodes inE/= orbC=>->. Qed.\n\nLemma server_send_safe_in this to d m : server_send_safe this to d m ->\n                                  this \\in nodes /\\ to \\in nodes.\nProof.\nby case=>[]=>G _; move/server_send_to_in: (G)->; case: G=>/eqP-> _; rewrite inE eqxx.\nQed.\n\n\nDefinition server_step (this to : nid) (d : dstatelet)\n           (msg : seq nat)\n           (pf : server_send_safe this to d msg) :=\n  let C := server_send_safe_coh pf in\n  let s := getSt_server C in\n  Some (st :-> server_send_step s to).\n\nLemma server_step_coh : s_step_coh_t coh the_tag server_step.\nProof.\nmove=>this to d msg pf h[]->{h}.\nhave C : (coh d) by case: pf=>?[].\nhave E: this = server by case: pf=>[][]/eqP.\nsplit=>/=.\n- apply: soup_coh_post_msg; first by case:(server_send_safe_coh pf).\n  case: (pf)=>H[C']P/=.\n  eexists.\n  by apply: (prec_safe _ P).\n- by apply: coh_dom_upd=>//; case: (server_send_safe_in pf).\n- by rewrite validU; apply: cohVl C.\nmove=>n Ni. rewrite /local_coh/=.\nrewrite /getLocal/=findU; case: ifP=>B; last by case: C=>_ _ _/(_ n Ni).\nmove/eqP: B=>Z; subst n this; rewrite eqxx (cohVl C)/=.\nsplit.\nby rewrite validPt.\nby eexists.\nQed.\n\nLemma server_step_def this to d msg :\n      server_send_safe this to d msg <->\n      exists b pf, @server_step this to d msg pf = Some b.\nProof.\nsplit=>[pf/=|]; last by case=>?[].\nset b := let C := server_send_safe_coh pf in\n         let s := getSt_server C in\n         st :-> (server_send_step s to).\nby exists b, pf.\nQed.\n\nDefinition server_send_trans :=\n  SendTrans server_send_safe_coh server_send_safe_in server_step_def server_step_coh.\n\nEnd ServerGenericSendTransitions.\n\nSection ServerSendTransitions.\n\nDefinition server_send_grant_prec (ss : server_state) to m :=\n  exists rest e,\n    ss = ServerState (to :: rest) e None /\\\n    m = [:: e].\n\nProgram Definition server_send_grant_trans : send_trans LockCoh :=\n  @server_send_trans grant_tag server_send_grant_prec _.\nNext Obligation.\ncase: H=>/eqP->H; rewrite /coh_msg eqxx; split=>//=.\ncase: H0=>[rest] [e] []-> ->/=. by rewrite /msg_from_server /= eqxx.\nQed.\n\nEnd ServerSendTransitions.\n\nSection ServerGenericReceiveTransitions.\n\nNotation coh := LockCoh.\n\nVariable the_tag : nat.\nVariable server_recv_wf : forall d, coh d -> nid -> nid -> TaggedMessage -> bool.\n\nDefinition rs_step : receive_step_t coh :=\n  fun this (from : nid) (m : seq nat) d (pf : coh d) (pt : this \\in nodes) =>\n    if (this == server)\n    then let s := getSt_server pf in\n         st :-> server_recv_step s from the_tag m\n    else getLocal this d.\n\nLemma rs_step_coh : r_step_coh_t server_recv_wf the_tag rs_step.\nProof.\nmove=>d from this m C pf tms D F Wf T/=.\nrewrite /rs_step; case X: (this == server); last first.\n- split=>/=; first by apply: consume_coh.\n  + by apply: coh_dom_upd.\n  + by rewrite validU; apply: cohVl C.\n  by move=>n Ni/=; case: (C)=>_ _ _/(_ n Ni)=>L; rewrite -(getLocalU)// (cohVl C).\nsplit=>/=; first by apply: consume_coh.\n- by apply: coh_dom_upd.\n- by rewrite validU; apply: cohVl C.\nmove=>n Ni/=; rewrite /local_coh/=.\nrewrite /getLocal/=findU; case: ifP=>B/=; last by case: (C)=>_ _ _/(_ n Ni).\nmove/eqP: B X=>Z/eqP X; subst n this; rewrite eqxx (cohVl C)/=.\nsplit; first by rewrite validPt.\nby eexists.\nQed.\n\nDefinition rs_recv_trans := ReceiveTrans rs_step_coh.\n\nEnd ServerGenericReceiveTransitions.\n\nSection ServerReceiveTransitions.\n\nDefinition s_matches_tag (ss : server_state) from t :=\n  (t == acquire_tag) ||\n  ((t == release_tag) && (current_holder ss == Some from)).\n\nDefinition server_msg_wf d (C : LockCoh d) (this from : nid) :=\n  [pred m : TaggedMessage | s_matches_tag (getSt_server C) from (tag m)].\n\nDefinition server_recv_acquire_trans := rs_recv_trans acquire_tag server_msg_wf.\n\nDefinition server_recv_release_trans := rs_recv_trans release_tag server_msg_wf.\n\nEnd ServerReceiveTransitions.\n\n\nSection ClientGenericSendTransitions.\n\nDefinition HClient this to := (this \\in clients /\\ to == server).\n\nVariable the_tag : nat.\n\nVariable prec : client_state -> nid -> seq nat -> Prop.\n\nHypothesis prec_safe :\n  forall this to s m,\n    HClient this to ->\n    prec s to m ->\n    msg_from_client (TMsg the_tag m).\n\nNotation coh := LockCoh.\n\nLemma client_send_this_in this to : HClient this to -> this \\in nodes.\nProof. case=>H _. by apply /client_nodes. Qed.\n\nDefinition client_send_safe (this n : nid)\n           (d : dstatelet) (msg : seq nat) :=\n  HClient this n /\\\n  exists (HC : HClient this n) (C : coh d), prec (getSt_client C (client_send_this_in HC)) n msg.\n\nLemma client_send_safe_coh this to d m : client_send_safe this to d m -> coh d.\nProof. by case => _[?][C]. Qed.\n\nLemma client_send_to_in this to : HClient this to -> to \\in nodes.\nProof. by case=>_ /eqP->; rewrite /nodes inE/= eqxx. Qed.\n\nLemma client_send_safe_in this to d m : client_send_safe this to d m ->\n                                  this \\in nodes /\\ to \\in nodes.\nProof.\ncase=>_[HC][C]_.\nsplit.\n- exact: (client_send_this_in HC).\nexact: (client_send_to_in HC).\nQed.\n\nDefinition client_step (this to : nid) (d : dstatelet)\n           (msg : seq nat)\n           (pf : client_send_safe this to d msg) :=\n  let C := client_send_safe_coh pf in\n  let s := getSt_client C (client_send_this_in (proj1 pf)) in\n  Some (st :-> client_send_step s).\n\nLemma client_step_coh : s_step_coh_t coh the_tag client_step.\nProof.\nmove=>this to d msg pf h[]->{h}.\nhave C : (coh d) by exact: (client_send_safe_coh pf).\nhave E: this \\in clients by case: pf=>_[][].\nsplit=>/=.\n- apply: soup_coh_post_msg; first by case:(client_send_safe_coh pf).\n  case: (pf)=>_[H][C']P/=.\n  exists 0.\n  rewrite/coh_msg/= client_not_server// E.\n  split; first by case: (H).\n  by apply: (prec_safe H P).\n- by apply: coh_dom_upd=>//; case: (client_send_safe_in pf).\n- by rewrite validU; apply: cohVl C.\nmove=>n Ni. rewrite /local_coh/=.\nrewrite /getLocal/=findU; case: ifP=>B; last by case: C=>_ _ _/(_ n Ni).\nmove/eqP: B=>Z; subst n.\nrewrite client_not_server// (cohVl C)/=.\nsplit.\n- by rewrite validPt.\nsplit=>//.\nby eexists.\nQed.\n\nLemma client_step_def this to d msg :\n      client_send_safe this to d msg <->\n      exists b pf, @client_step this to d msg pf = Some b.\nProof.\nsplit=>[pf/=|]; last by case=>?[].\nset b := let C := client_send_safe_coh pf in\n         let s := getSt_client C (client_send_this_in (proj1 pf)) in\n         st :-> (client_send_step s).\nby exists b, pf.\nQed.\n\nDefinition client_send_trans :=\n  SendTrans client_send_safe_coh client_send_safe_in client_step_def client_step_coh.\n\nEnd ClientGenericSendTransitions.\n\nSection ClientSendTransitions.\n\nDefinition client_send_acquire_prec (cs : client_state) (to : nid) (m : seq nat) :=\n  cs = NotHeld /\\\n  m = [::].\n\nProgram Definition client_send_acquire_trans : send_trans LockCoh :=\n  @client_send_trans acquire_tag client_send_acquire_prec _.\nNext Obligation.\napply/andP=>/=.\nsplit=>//.\nby case: H0=>_/eqP.\nQed.\n\nDefinition client_send_release_prec (cs : client_state) (to : nid) (m : seq nat) :=\n  (exists e, cs = Held e) /\\\n  m = [::].\n\nProgram Definition client_send_release_trans : send_trans LockCoh :=\n  @client_send_trans release_tag client_send_release_prec _.\nNext Obligation.\napply/andP=>/=.\nsplit=>//.\nby case: H0=>_/eqP.\nQed.\n\nEnd ClientSendTransitions.\n\nSection ClientGenericReceiveTransitions.\n\nNotation coh := LockCoh.\n\nVariable the_tag : nat.\nVariable client_recv_wf : forall d, coh d -> nid -> nid -> TaggedMessage -> bool.\n\nDefinition rc_step : receive_step_t coh :=\n  fun this (from : nid) (m : seq nat) d (pf : coh d) (pt : this \\in nodes) =>\n    if (this \\in clients)\n    then let s := getSt_client pf pt in\n         st :-> client_recv_step s from the_tag m\n    else getLocal this d.\n\nLemma rc_step_coh : r_step_coh_t client_recv_wf the_tag rc_step.\nProof.\nmove=>d from this m C pf tms D F Wf T/=.\nrewrite /rc_step; case X: (this \\in clients); last first.\n- split=>/=; first by apply: consume_coh.\n  + by apply: coh_dom_upd.\n  + by rewrite validU; apply: cohVl C.\n  have Y: forall z : nat_eqType, z \\in nodes -> local_coh z (getLocal z d)\n      by case: (C).\n  by move=>n Ni/=; move: (Y n Ni)=>L; rewrite -(getLocalU)// (cohVl C).\nsplit=>/=; first by apply: consume_coh.\n- by apply: coh_dom_upd.\n- by rewrite validU; apply: cohVl C.\nmove=>n Ni/=; rewrite /local_coh/=.\nrewrite /getLocal/=findU; case: ifP=>B/=; last by case: (C)=>_ _ _/(_ n Ni).\nmove/eqP: B X=>Z/eqP X/= ;rewrite !(cohVl C); subst n.\nsplit; first done.\nmove/eqP: X => X.\nrewrite client_not_server X//.\nsplit=>//.\nby eexists _.\nQed.\n\nDefinition rc_recv_trans := ReceiveTrans rc_step_coh.\n\nEnd ClientGenericReceiveTransitions.\n\nSection ClientReceiveTransitions.\n\nDefinition client_msg_wf d (_ : LockCoh d) (this from : nid) :=\n  [pred m : TaggedMessage | true].\n\nDefinition client_receive_grant_trans := rc_recv_trans grant_tag client_msg_wf.\n\nEnd ClientReceiveTransitions.\n\nSection Protocol.\n\nVariable l : Label.\n\n(* All send-transitions *)\nDefinition lock_sends :=\n  [::\n     server_send_grant_trans;\n     client_send_acquire_trans;\n     client_send_release_trans\n  ].\n\n(* All receive-transitions *)\nDefinition lock_receives :=\n  [::\n     server_recv_acquire_trans;\n     server_recv_release_trans;\n     client_receive_grant_trans\n  ].\n\nProgram Definition LockProtocol : protocol :=\n  @Protocol _ l _ lock_sends lock_receives _ _.\n\nEnd Protocol.\nEnd LockProtocol.\n\nModule Exports.\nSection Exports.\n\nDefinition LockProtocol := LockProtocol.\n\nEnd Exports.\nEnd Exports.\n\nEnd LockProtocol.\n\nExport LockProtocol.Exports.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/disel/Examples/LockResource/LockProtocol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21039512241972638}}
{"text": "Require Export ucos_include.\nRequire Import OSTimeDlyPure.\nRequire Import OSQAcceptPure.\nRequire Import oscore_common.\nRequire Import new_inv.\n\nLocal Open Scope int_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope code_scope.\n\n\nLtac simpljoin1 := simpljoin.\n\n(**** lzh-begin ****)\n\nLemma ecbmod_absmsgq:\n  forall a x y z b,\n    RLH_ECBData_P\n      (DMsgQ a x y z) b -> exists vl n wl, b = (absmsgq vl n, wl).\nProof.\n  intros.\n  unfold RLH_ECBData_P in H.\n  destruct b.\n  destruct e;tryfalse.\n  do 3 eexists;auto.\nQed.\n(**** lzh-end ****)\n\nLemma post_exwt_succ_pre:\n  forall v'36 v'13 v'12 v'32 v'15 v'24 v'35 v'0 v'8 v'9 v'11 x x0 x1 v'6 v'10 v'38 v'69 v'39 v'58 a b c v'62 v'7 vhold,\n    v'12 <> Int.zero ->\n    R_PrioTbl_P v'36 v'7 vhold ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    R_ECB_ETbl_P (v'32, Int.zero)\n                 (V$OS_EVENT_TYPE_Q\n                   :: Vint32 v'12\n                   :: Vint32 v'15 :: Vptr (v'24, Int.zero) :: v'35 :: v'0 :: nil,\n                  v'13) v'7 ->\n    RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    EcbMod.joinsig (v'32, Int.zero) (absmsgq x x0, x1) v'6 v'10 ->\n    Int.unsigned v'12 <= 255 ->\n    array_type_vallist_match Int8u v'13 ->\n    length v'13 = ∘OS_EVENT_TBL_SIZE ->\n    nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n    Int.unsigned v'38 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n    Int.unsigned v'69 <= 255 ->\n    nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 = Vptr (v'58, Int.zero)->\n    TcbJoin (v'58, Int.zero) (a,b,c) v'62 v'7 ->\n    x1<>nil /\\ GetHWait v'7 x1 (v'58,Int.zero) /\\ TcbMod.get v'7 (v'58,Int.zero) = Some (a,b,c).\nProof.\n  intros.\n  lets Hs : tcbjoin_get_a H16.\n  unfolds in H3.\n  unfolds in H1.\n  unfolds in H0.\n  unfolds in H2.\n  destruct H2.\n  destruct H17 as (H17&Htype).\n  unfolds in H2.\n  unfolds in H17.\n  lets Hg : EcbMod.join_joinsig_get H4 H5.\n  clear H4 H5.\n  clear H16.\n  assert ( Int.unsigned v'38 < 8) as Hx by omega.\n  assert (Int.unsigned v'39 < 8) as Hy by omega.\n  clear H10 H12.\n  lets Hrs : math_xy_prio_cons Hx Hy.\n  unfold nat_of_Z in H0.\n  destruct H0 as (Hpr1 & Hpr2).\n  assert ((v'58, Int.zero) <> vhold) as Hnvhold.\n  destruct Hpr2.\n  apply H0 in Hs.\n  destruct Hs;auto.\n  lets Hnth : nth_val'_imp_nth_val_vptr H15.\n  lets Hsd : Hpr1 Hrs Hnth.\n  destruct Hsd as (st & m & Hst).\n  intro; tryfalse.\n\n  unfold get in Hst; simpl in Hst.\n  rewrite Hs in Hst.\n  inverts Hst.\n  assert (Int.shru ((v'38<<ᵢ$ 3)+ᵢv'39) ($ 3)= v'38).\n  eapply math_shrl_3_eq; eauto.\n  eapply nat_8_range_conver; eauto.\n  assert ( (Z.to_nat (Int.unsigned v'38))  < length v'13)%nat.\n  rewrite H8.\n  simpl.\n  unfold Pos.to_nat; simpl.\n  clear - Hx.\n  mauto.\n  lets Has : array_int8u_nth_lt_len H7 H4.\n  destruct Has as (i & Hnthz & Hinsa).\n  rewrite H11 in Hnthz.\n  inverts Hnthz.\n  assert ((((v'38<<ᵢ$ 3)+ᵢv'39)&ᵢ$ 7) = v'39).\n  eapply math_8range_eqy; eauto.\n  eapply  nat_8_range_conver; eauto.\n  apply nth_val'_imp_nth_val_int in H11.\n  assert ( Vint32 v'12 = Vint32 v'12) by auto.\n  lets Hzs : H1 H11 H10.\n  eapply  nat_8_range_conver; eauto.\n  destruct Hzs.\n  lets Has : math_8_255_eq H6 H9 H.\n  assert (i <> $ 0).\n  assert ($ 1<<ᵢ$ Z.of_nat ∘(Int.unsigned v'38) = $ 1<<ᵢv'38).\n  clear -Hx.\n  mauto.\n  rewrite H18 in H16.\n  apply H16 in Has.\n  apply ltu_eq_false in Has.\n  pose (Int.eq_spec i ($0)).\n  rewrite Has in y.\n  auto.\n  assert (PrioWaitInQ (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39)) v'13).\n  unfolds.\n  rewrite Int.repr_unsigned in *.\n  exists ( ((v'38<<ᵢ$ 3)+ᵢv'39)&ᵢ$ 7 ).\n  exists (Int.shru ((v'38<<ᵢ$ 3)+ᵢv'39) ($ 3) ).\n  rewrite H0 in *.\n  exists i.\n  splits; eauto.\n  rewrite H5.\n  eapply math_8_255_eq; eauto.\n  destruct H2 as (H2&Hres).\n  lets Hes : H2 H19.\n  unfold V_OSEventType in Hes.\n  simpl nth_val in Hes.\n  assert (Some (V$OS_EVENT_TYPE_Q) = Some (V$OS_EVENT_TYPE_Q)) by auto.\n  apply Hes in H20.\n  clear Hes.\n  rename H20 into Hes.\n  destruct Hes as (td & nn &mm & Hge).\n  destruct Hpr2 as (Hpr2 & Hpr3).\n  unfolds in Hpr3.\n  assert (td = (v'58, Int.zero)  \\/ td <> (v'58, Int.zero) ) by tauto.\n  destruct H20.\n  Focus 2.\n  lets Hass : Hpr3 H20 Hge Hs.\n  rewrite Int.repr_unsigned in *.\n  tryfalse.\n  rewrite Int.repr_unsigned in *.\n  subst td.\n  unfold get in Hge; simpl in Hge.\n  rewrite Hs in Hge.\n  inverts Hge.\n  destruct H3 as (H3&Hres').\n  destruct H3 as (Heg1 & Heg2).\n  lets Hrgs : Heg2 Hs.\n  destruct Hrgs as (xz & y & qw & Hem & Hin).\n  unfold get in Hem; simpl in Hem.\n  rewrite Hg in Hem.\n  inverts Hem.\n  assert (qw = nil \\/ qw <> nil) by tauto.\n  destruct H3.\n  subst qw.\n  simpl in Hin; tryfalse.\n  splits; auto.\n  unfolds.\n  splits; auto.\n  do 3 eexists; splits; eauto.\n  intros.\n  assert (EcbMod.get v'11 (v'32, Int.zero) = Some (absmsgq xz y, qw) /\\ In t' qw) .\n  splits; auto.\n  lets Habs : Heg1 H22.\n  destruct Habs as (prio' & m' & n' & Hbs).\n  do 3 eexists; splits; eauto.\n  destruct H17 as (H17&Hres'').\n  lets Hpro : H17 Hbs.\n  destruct Hpro as (Hpro&Hss).\n  clear Hss.\n  unfolds in Hpro.\n  destruct Hpro as (xa & xb & zz & Hran & Hxx & Hyy & Hnths & Hzz).\n  subst xa xb.\n  rewrite Int.repr_unsigned in *.\n  lets Hat : math_highest_prio_select H13 H9 H11 Hnths  Hzz;\n    try eapply int_usigned_tcb_range; try omega;\n    eauto.\n  assert (Vint32 v'12 = Vint32 v'12) by auto.\n  lets Hzs : H1 Hnths H23.\n  eapply nat_8_range_conver; eauto.\n  try eapply int_usigned_tcb_range; eauto.  \n  destruct Hzs.\n  assert (zz = $ 0 \\/ zz <> $ 0) by tauto.\n  destruct H26.\n  subst zz.\n  rewrite Int.and_commut in Hzz.\n  rewrite Int.and_zero in Hzz.\n  unfold Int.one in *.\n  unfold Int.zero in *.\n  assert ($ 1<<ᵢ(prio'&ᵢ$ 7) <> $ 0 ).\n  eapply math_prop_neq_zero2; eauto.\n  tryfalse.\n  assert (Int.ltu ($ 0) zz = true).\n  clear - H26.\n  int auto.\n  assert (0<=Int.unsigned zz ).\n  int auto.\n  assert (Int.unsigned zz = 0).\n  omega.\n  rewrite <- H0 in H26.\n  rewrite Int.repr_unsigned in *.\n  tryfalse.\n  apply H25 in H27.\n  assert ($ Z.of_nat ∘(Int.unsigned (Int.shru prio' ($ 3))) = (Int.shru prio' ($ 3))).\n  clear -Hran.\n  mauto.\n  rewrite H28 in *.\n  auto.\n  lets Hasss : Hpr3 H20 Hs Hbs; eauto.\n  unfolds.\n  rewrite zlt_true; auto.\n  assert (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39) < Int.unsigned prio' \\/\n         Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39) = Int.unsigned prio').\n  omega.\n  destruct H23; auto; tryfalse.\n  false.\n  apply Hasss.\n  apply unsigned_inj; eauto.\nQed.\n\n\nLemma prio_set_rdy_in_tbl:\n  forall prio0 prio rtbl grp,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    prio_in_tbl prio0 rtbl ->\n    prio_in_tbl prio0\n                (update_nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl\n                                (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))).\nProof.\n  introv Fd1 Fd2 Fneq Fnth Fpit.\n  unfold prio_in_tbl in *.\n  introv Fx Fy Fnth'.\n  assert ( ∘(Int.unsigned (Int.shru prio ($ 3))) =  ∘(Int.unsigned (Int.shru prio0 ($ 3))) \\/\n           ∘(Int.unsigned (Int.shru prio ($ 3))) <>  ∘(Int.unsigned (Int.shru prio0 ($ 3)))) by tauto.\n  destruct H.\n  assert (nth_val ∘(Int.unsigned  (Int.shru prio ($ 3)))\n                  (update_nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl\n                                  (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))) = \n          Some (Vint32  (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))).\n  eapply update_nth.\n  eauto.\n  subst.\n  rewrite <- H in Fnth'.\n  rewrite H0 in Fnth'.\n  inverts Fnth'.\n  eapply or_and_combine; eauto.\n  eapply Fpit; trivial.\n  rewrite <- H; trivial.\n  unfolds in H.\n  eapply prio_bit_and_zero; eauto.\n  subst.\n\n  assert (nth_val ∘(Int.unsigned  (Int.shru prio0 ($ 3))) rtbl = Some (Vint32 z)).\n  eapply nth_upd_neq.\n  eapply neq_comm.\n  eapply H.\n  eapply Fnth'.\n  eapply Fpit; auto.\nQed.\n\n\nLemma prio_set_rdy_in_tbl_rev:\n  forall prio0 prio rtbl grp,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    prio_in_tbl prio0\n                (update_nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl\n                                (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))) ->\n    prio_in_tbl prio0 rtbl.\nProof.\n  introv Fd1 Fd2 Fneq Fnth Fpit.\n  unfold prio_in_tbl in *.\n  introv Fx Fy Fnth'.\n  assert ( ∘(Int.unsigned (Int.shru prio ($ 3))) =  ∘(Int.unsigned (Int.shru prio0 ($ 3))) \\/\n           ∘(Int.unsigned (Int.shru prio ($ 3))) <>  ∘(Int.unsigned (Int.shru prio0 ($ 3)))) by tauto.\n  destruct H.\n  assert (nth_val ∘(Int.unsigned  (Int.shru prio ($ 3)))\n                  (update_nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl\n                                  (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))) = \n          Some (Vint32  (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))).\n  eapply update_nth.\n  eauto.\n  subst.\n  rewrite <- H in Fnth'.\n  inverts Fnth'.\n  rewrite H in H0.\n  rewrite H in Fpit.\n  lets Hzz: Fpit H0; eauto.\n  rewrite -> Fnth in H2.\n  inverts H2.\n  eapply or_and_distrib; eauto.\n  eapply prio_bit_and_zero; eauto.\n  assert (nth_val ∘(Int.unsigned  (Int.shru prio0 ($ 3))) \n                  (update_nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl\n                                  (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))) = Some (Vint32 z)). \n  eapply nth_upd_neqrev; eauto.\n  rewrite Fy in Fnth'. trivial.\n  eapply Fpit; auto.\nQed.\n\nLemma prio_set_rdy_not_in_tbl:\n  forall prio0 prio rtbl grp,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    prio_not_in_tbl prio0 rtbl ->\n    prio_not_in_tbl prio0\n                    (update_nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl\n                                    (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))).\nProof.\n  introv Fd1 Fd2 Fneq Fnth Fpit.\n  unfold prio_not_in_tbl in *.\n  introv Fx Fy Fnth'.\n  assert ( ∘(Int.unsigned (Int.shru prio ($ 3))) =  ∘(Int.unsigned (Int.shru prio0 ($ 3))) \\/\n           ∘(Int.unsigned (Int.shru prio ($ 3))) <>  ∘(Int.unsigned (Int.shru prio0 ($ 3)))) by tauto.\n  destruct H.\n  assert (nth_val ∘(Int.unsigned  (Int.shru prio ($ 3)))\n                  (update_nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl\n                                  (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))) = \n          Some (Vint32  (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))).\n  eapply update_nth.\n  eauto.\n  subst.\n  rewrite <- H in Fnth'.\n  rewrite H0 in Fnth'.\n  inverts Fnth'.\n  eapply or_and_combine_zero; eauto.\n  eapply Fpit; trivial.\n  rewrite <- H; trivial.\n  unfolds in H.\n  eapply prio_bit_and_zero; eauto.\n  subst.\n  assert (nth_val ∘(Int.unsigned  (Int.shru prio0 ($ 3))) rtbl = Some (Vint32 z)).\n  eapply nth_upd_neq.\n  eapply neq_comm.\n  eapply H.\n  eapply Fnth'.\n  eapply Fpit; auto.\nQed.\n\n\nLemma prio_set_rdy_not_in_tbl_rev:\n  forall prio0 prio rtbl grp,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    prio_not_in_tbl prio0\n                    (update_nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl\n                                    (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))) ->\n    prio_not_in_tbl prio0 rtbl.\nProof.\n  introv Fd1 Fd2 Fneq Fnth Fpit.\n  unfold prio_in_tbl in *.\n  introv Fx Fy Fnth'.\n  assert ( ∘(Int.unsigned (Int.shru prio ($ 3))) =  ∘(Int.unsigned (Int.shru prio0 ($ 3))) \\/\n           ∘(Int.unsigned (Int.shru prio ($ 3))) <>  ∘(Int.unsigned (Int.shru prio0 ($ 3)))) by tauto.\n  destruct H.\n  assert (nth_val ∘(Int.unsigned  (Int.shru prio ($ 3)))\n                  (update_nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl\n                                  (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))) = \n          Some (Vint32  (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))).\n  eapply update_nth.\n  eauto.\n  subst.\n  rewrite <- H in Fnth'.\n  inverts Fnth'.\n  rewrite H in H0.\n  rewrite H in Fpit.\n  lets Hzz: Fpit H0; eauto.\n  rewrite -> Fnth in H2.\n  inverts H2.\n  eapply or_and_distrib_zero; eauto.\n  eapply prio_bit_and_zero; eauto.\n  \n  assert (nth_val ∘(Int.unsigned  (Int.shru prio0 ($ 3))) \n                  (update_nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl\n                                  (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7))))) = Some (Vint32 z)). \n  eapply nth_upd_neqrev; eauto.\n  rewrite Fy in Fnth'. trivial.\n  eapply Fpit; auto.\nQed.\n\n\n\nModule new_rtbl.\n  (* I want rtbl has more abstractions which make the operations on it more clean *)\n  Definition set_rdy p rtbl :=\n    update_nth_val ∘(Int.unsigned (Int.shru p ($ 3))) rtbl\n                   (val_inj (or (nth_val' (Z.to_nat (Int.unsigned (Int.shru p ($ 3)))) rtbl)\n                                (Vint32 ($ 1<<ᵢ(p&ᵢ$ 7))))).\n\n  Lemma trans_lemma_1:\n    forall p grp rtbl,\n      nth_val (Z.to_nat (Int.unsigned (Int.shru p ($ 3)))) rtbl = Some (Vint32 grp) ->\n      (val_inj\n         (or (nth_val' (Z.to_nat (Int.unsigned (Int.shru p ($ 3)))) rtbl)\n             (Vint32 ($ 1<<ᵢ(p&ᵢ$ 7))))) =\n      (Vint32 (Int.or grp ($ 1<<ᵢ(p&ᵢ$ 7)))).\n    Proof.\n      intros.\n      unfold val_inj.\n      eapply nth_val_nth_val'_some_eq in H.\n      rewrite H.\n      unfold or.\n      trivial.\n    Qed.\n\n  Lemma prio_set_rdy_in_tbl_lemma_1:\n    forall rtbl p,\n      0<= Int.unsigned p < 64 ->\n      array_type_vallist_match Int8u rtbl ->\n      length rtbl = ∘OS_RDY_TBL_SIZE ->\n      (exists v, nth_val (Z.to_nat (Int.unsigned (Int.shru p ($ 3)))) rtbl = Some (Vint32 v)). \n  Proof.\n    intros.\n    eapply array_type_match_get_value; eauto.\n    clear -H.\n    mauto.\n  Qed.\n\n  Lemma prio_set_rdy_in_tbl:\n    forall p0 p rtbl,\n      0 <= Int.unsigned p0 < 64 ->\n      0 <= Int.unsigned p < 64 ->\n      array_type_vallist_match Int8u rtbl ->\n      length rtbl = ∘OS_RDY_TBL_SIZE ->\n      p0 <> p ->\n      prio_in_tbl p0 rtbl ->\n      prio_in_tbl p0 (set_rdy p rtbl).\n  Proof.\n    intros.\n    unfold set_rdy.\n    assert (Fnth: \n              (exists v, nth_val (Z.to_nat (Int.unsigned (Int.shru p ($ 3)))) rtbl = Some (Vint32 v))). \n      eapply prio_set_rdy_in_tbl_lemma_1; eauto.\n    inversion Fnth.\n    lets Feq: trans_lemma_1 H5.\n    rewrite Feq.\n    eapply prio_set_rdy_in_tbl; eauto.\n  Qed.\n\n  Lemma prio_set_rdy_in_tbl_rev:\n    forall p0 p rtbl,\n      0 <= Int.unsigned p0 < 64 ->\n      0 <= Int.unsigned p < 64 ->\n      array_type_vallist_match Int8u rtbl ->\n      length rtbl = ∘OS_RDY_TBL_SIZE ->\n      p0 <> p ->\n      prio_in_tbl p0 (set_rdy p rtbl) ->\n      prio_in_tbl p0 rtbl.\n  Proof.\n    intros.\n    unfold set_rdy in *.\n    assert (Fnth: \n              (exists v, nth_val (Z.to_nat (Int.unsigned (Int.shru p ($ 3)))) rtbl = Some (Vint32 v))). \n      eapply prio_set_rdy_in_tbl_lemma_1; eauto.\n    inversion Fnth.\n    lets Feq: trans_lemma_1 H5.\n    rewrite Feq in H4.\n    eapply prio_set_rdy_in_tbl_rev; eauto.\n  Qed.\n\n  \n  Lemma prio_set_rdy_not_in_tbl:\n    forall p0 p rtbl,\n      0 <= Int.unsigned p0 < 64 ->\n      0 <= Int.unsigned p < 64 ->\n      array_type_vallist_match Int8u rtbl ->\n      length rtbl = ∘OS_RDY_TBL_SIZE ->\n      p0 <> p ->\n      prio_not_in_tbl p0 rtbl ->\n      prio_not_in_tbl p0 (set_rdy p rtbl).\n  Proof.\n    intros.\n    unfold set_rdy.\n    assert (Fnth: \n              (exists v, nth_val (Z.to_nat (Int.unsigned (Int.shru p ($ 3)))) rtbl = Some (Vint32 v))). \n      eapply prio_set_rdy_in_tbl_lemma_1; eauto.\n    inversion Fnth.\n    lets Feq: trans_lemma_1 H5.\n    rewrite Feq.\n    eapply prio_set_rdy_not_in_tbl; eauto.\n  Qed.\n\n\n  Lemma prio_set_rdy_not_in_tbl_rev:\n    forall p0 p rtbl,\n      0 <= Int.unsigned p0 < 64 ->\n      0 <= Int.unsigned p < 64 ->\n      array_type_vallist_match Int8u rtbl ->\n      length rtbl = ∘OS_RDY_TBL_SIZE ->\n      p0 <> p ->\n      prio_not_in_tbl p0 (set_rdy p rtbl) ->\n      prio_not_in_tbl p0 rtbl.\n  Proof.\n    intros.\n    unfold set_rdy in *.\n    assert (Fnth: \n              (exists v, nth_val (Z.to_nat (Int.unsigned (Int.shru p ($ 3)))) rtbl = Some (Vint32 v))). \n      eapply prio_set_rdy_in_tbl_lemma_1; eauto.\n    inversion Fnth.\n    lets Feq: trans_lemma_1 H5.\n    rewrite Feq in H4.\n    eapply prio_set_rdy_not_in_tbl_rev; eauto.\n  Qed.\nEnd new_rtbl.    \n\n\nLemma RdyTCBblk_rtbl_add:\n  forall prio0 prio rtbl grp vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RdyTCBblk vl rtbl prio0 ->\n    RdyTCBblk vl \n              (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                              (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n              prio0.\nProof.\n  introv Fp0 Fp Fneq Fnth.\n  unfold RdyTCBblk.\n  intuition; trivial.\n  eapply prio_set_rdy_in_tbl; eauto.\nQed.\n\nLemma RLH_RdyI_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RLH_RdyI_P vl rtbl (prio0, stat, msg) ->\n    RLH_RdyI_P vl \n               (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                               (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n               (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Frdy.\n  unfolds in Frdy.\n  unfolds.\n  introv Frdy_tcb.\n  eapply Frdy; eauto.\n  unfolds.\n  unfolds in Frdy_tcb.\n  simpljoin1;split; auto.\n  rewrite Fvp in H.\n  inversion H.\n  rewrite <- H6 in *.\n  eapply prio_set_rdy_in_tbl_rev; eauto.\nQed.  \n\nLemma RHL_RdyI_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RHL_RdyI_P vl rtbl (prio0, stat, msg) ->\n    RHL_RdyI_P vl \n               (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                               (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n               (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Frdy.\n  unfolds in Frdy.\n  unfolds.\n  intros.\n  inversion H.\n  rewrite <- H1 in *.\n  clear H1; subst.\n  splits.\n  eapply RdyTCBblk_rtbl_add; eauto.\n  eapply Frdy; eauto.\n  eapply Frdy; eauto.\n  eapply Frdy; eauto.\nQed.\n\nLemma WaitTCBblk_rtbl_add:\n  forall prio0 prio rtbl grp vl t,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    WaitTCBblk vl rtbl prio0 t->\n    WaitTCBblk vl \n               (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                               (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n               prio0 t.\nProof.\n  introv Fp0 Fp Fneq Fnth.\n  unfold WaitTCBblk.\n  intuition; trivial.\n  eapply prio_set_rdy_not_in_tbl; eauto.\nQed.\n\nLemma WaitTCBblk_rtbl_add_rev:\n  forall prio0 prio rtbl grp vl t,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    WaitTCBblk vl \n               (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                               (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n               prio0 t ->\n    WaitTCBblk vl rtbl prio0 t.\nProof.\n  introv Fp0 Fp Fneq Fnth.\n  unfold WaitTCBblk.\n  intuition; trivial.\n  eapply prio_set_rdy_not_in_tbl_rev; eauto.\nQed.\n\nLemma RLH_Wait_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RLH_Wait_P vl rtbl (prio0, stat, msg) ->\n    RLH_Wait_P vl \n               (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                               (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n               (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  introv Fwait_tcb Fst.\n  eapply Fwait; eauto.\n  unfolds.\n  unfolds in Fwait_tcb.\n  simpljoin1;splits; auto.\n  rewrite Fvp in H.\n  inversion H.\n  rewrite <- H7 in *.\n  eapply prio_set_rdy_not_in_tbl_rev; eauto.\nQed.  \n\n\nLemma RLH_WaitS_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RLH_WaitS_P vl rtbl (prio0, stat, msg) ->\n    RLH_WaitS_P vl \n                (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                                (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n                (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  introv Fwait_tcb Fst.\n  eapply Fwait; eauto.\n  unfolds.\n  unfolds in Fwait_tcb.\n  simpljoin1;splits; auto.\n  rewrite Fvp in H.\n  inversion H.\n  rewrite <- H7 in *.\n  eapply prio_set_rdy_not_in_tbl_rev; eauto.\nQed.  \n\nLemma RLH_WaitQ_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RLH_WaitQ_P vl rtbl (prio0, stat, msg) ->\n    RLH_WaitQ_P vl \n                (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                                (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n                (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  introv Fwait_tcb Fst.\n  eapply Fwait; eauto.\n  unfolds.\n  unfolds in Fwait_tcb.\n  simpljoin1; splits; auto.\n  rewrite Fvp in H.\n  inversion H.\n  rewrite <- H7 in *.\n  eapply prio_set_rdy_not_in_tbl_rev; eauto.\nQed.\n\n\n\nLemma RLH_WaitMB_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RLH_WaitMB_P vl rtbl (prio0, stat, msg) ->\n    RLH_WaitMB_P vl \n                (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                                (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n                (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  introv Fwait_tcb Fst.\n  eapply Fwait; eauto.\n  unfolds.\n  unfolds in Fwait_tcb.\n  simpljoin1;splits; auto.\n  rewrite Fvp in H.\n  inversion H.\n  rewrite <- H7 in *.\n  eapply prio_set_rdy_not_in_tbl_rev; eauto.\nQed.\n\n\nLemma RLH_WaitMS_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RLH_WaitMS_P vl rtbl (prio0, stat, msg) ->\n    RLH_WaitMS_P vl \n                (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                                (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n                (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  introv Fwait_tcb Fst.\n  eapply Fwait; eauto.\n  unfolds.\n  unfolds in Fwait_tcb.\n  simpljoin1; splits; auto.\n  rewrite Fvp in H.\n  inversion H.\n  rewrite <- H7 in *.\n  eapply prio_set_rdy_not_in_tbl_rev; eauto.\nQed.\n\n\nLemma RLH_Wait_all_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RLH_TCB_Status_Wait_P vl rtbl (prio0, stat, msg) ->\n    RLH_TCB_Status_Wait_P vl \n                          (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                                          (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n                          (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  intuition; trivial.\n  eapply RLH_Wait_P_rtbl_add; eauto.\n  eapply RLH_WaitS_P_rtbl_add; eauto.\n  eapply RLH_WaitQ_P_rtbl_add; eauto.\n  eapply RLH_WaitMB_P_rtbl_add; eauto.\n  eapply RLH_WaitMS_P_rtbl_add; eauto.\nQed.\n\nLemma RHL_Wait_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RHL_Wait_P vl rtbl (prio0, stat, msg) ->\n    RHL_Wait_P vl \n               (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                               (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n               (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  intros.\n  inversion H.\n  rewrite <- H1 in *.\n  clear H1; subst.\n  splits.\n  eapply WaitTCBblk_rtbl_add; eauto.\n  eapply Fwait; eauto.\n  eapply Fwait; eauto.\n  eapply Fwait; eauto.\nQed.\n  \n\nLemma RHL_WaitS_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RHL_WaitS_P vl rtbl (prio0, stat, msg) ->\n    RHL_WaitS_P vl \n                (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                                (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n                (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  intros.\n  inversion H.\n  rewrite <- H1 in *.\n  clear H1; subst.\n  splits.\n  eapply WaitTCBblk_rtbl_add; eauto.\n  eapply Fwait; eauto.\n  eapply Fwait; eauto.\n  eapply Fwait; eauto.\nQed.\n\nLemma RHL_WaitQ_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RHL_WaitQ_P vl rtbl (prio0, stat, msg) ->\n    RHL_WaitQ_P vl \n                (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                                (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n                (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  intros.\n  inversion H.\n  rewrite <- H1 in *.\n  clear H1; subst.\n  splits.\n  eapply WaitTCBblk_rtbl_add; eauto.\n  eapply Fwait; eauto.\n  eapply Fwait; eauto.\n  eapply Fwait; eauto.\nQed.\n\nLemma RHL_WaitMB_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RHL_WaitMB_P vl rtbl (prio0, stat, msg) ->\n    RHL_WaitMB_P vl \n                (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                                (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n                (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  intros.\n  inversion H.\n  rewrite <- H1 in *.\n  clear H1; subst.\n  splits.\n  eapply WaitTCBblk_rtbl_add; eauto.\n  eapply Fwait; eauto.\n  eapply Fwait; eauto.\n  eapply Fwait; eauto.\nQed.\n\nLemma RHL_WaitMS_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RHL_WaitMS_P vl rtbl (prio0, stat, msg) ->\n    RHL_WaitMS_P vl \n                (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                                (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n                (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  intros.\n  inversion H.\n  rewrite <- H1 in *.\n  clear H1; subst.\n  splits.\n  eapply WaitTCBblk_rtbl_add; eauto.\n  eapply Fwait; eauto.\n  eapply Fwait; eauto.\n  eapply Fwait; eauto.\nQed.\n\nLemma RHL_Wait_all_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    RHL_TCB_Status_Wait_P vl rtbl (prio0, stat, msg) ->\n    RHL_TCB_Status_Wait_P vl \n                          (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                                          (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n                          (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  intros.\n  intuition.\n  eapply RHL_Wait_P_rtbl_add; eauto.\n  eapply RHL_WaitS_P_rtbl_add; eauto.\n  eapply RHL_WaitQ_P_rtbl_add; eauto.\n  eapply RHL_WaitMB_P_rtbl_add; eauto.\n  eapply RHL_WaitMS_P_rtbl_add; eauto.\nQed.\n\nLemma R_TCB_Status_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    R_TCB_Status_P vl rtbl (prio0, stat, msg) ->\n    R_TCB_Status_P vl \n                   (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                                   (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n                   (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Fwait.\n  unfolds in Fwait.\n  unfolds.\n  intros.\n  intuition.\n  eapply RLH_RdyI_P_rtbl_add; eauto.\n  eapply RHL_RdyI_P_rtbl_add; eauto.\n  eapply RLH_Wait_all_rtbl_add; eauto.\n  eapply RHL_Wait_all_rtbl_add; eauto.\nQed.\n\nLemma TCBNode_P_rtbl_add:\n  forall prio0 prio rtbl grp stat msg vl,\n    0 <= Int.unsigned prio0 < 64 ->\n    0 <= Int.unsigned prio < 64 ->\n    prio0 <> prio ->\n    V_OSTCBPrio vl = Some (Vint32 prio0) ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    TCBNode_P vl rtbl (prio0, stat, msg) ->\n    TCBNode_P vl \n              (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                              (Vint32 (Int.or grp ($ 1<<ᵢ(prio&ᵢ$ 7)))))\n              (prio0, stat, msg).\nProof.\n  introv Fp0 Fp Fneq Fvp Fnth Ftcb.\n  unfolds in Ftcb.\n  unfolds.\n  intros.\n  intuition.\n  eapply R_TCB_Status_P_rtbl_add; eauto.\nQed.\n\nLemma TCBNode_P_prio:\n  forall vl rtbl p t m,\n    TCBNode_P vl rtbl (p, t, m) ->\n    0 <= Int.unsigned p < 64 /\\ V_OSTCBPrio vl = Some (Vint32 p).\nProof.\n  intros.\n  unfolds in H.\n  destruct H as (Hv1 & Hv2 & Hv3 & Hvs).\n  unfolds in Hv3.\n  fsimpl.\n  rewrite Hv2 in H.\n  inverts H.\n  split; try omega; auto.\nQed.\n\n          \n\nLemma TCBList_P_rtbl_add_simpl_version:\n  forall vl vptr rtbl tcbls prio grp,\n    0<= Int.unsigned prio < 64 ->\n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    (forall tid p s m , TcbMod.get tcbls tid  = Some (p,s,m) -> p <> prio\n    ) ->\n    TCBList_P vptr vl rtbl tcbls ->\n    TCBList_P vptr vl\n              (update_nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl\n                              (Vint32 (Int.or grp ($ 1<<ᵢ(prio &ᵢ$ 7))))) \n              tcbls.\nProof.\n  inductions vl.\n  intros; simpl in *; auto.\n  intros.\n  unfold TCBList_P in *; fold TCBList_P in *.\n  simpljoin1.\n  exists x x0 x1 x2.\n  splits; auto.\n  destruct x2; destruct p.\n  eapply TCBNode_P_rtbl_add; eauto.\n  eapply TCBNode_P_prio; eauto.\n  eapply H1; eauto.\n  unfolds in H4.\n  eapply TcbMod.join_sig_get; eauto.\n  eapply TCBNode_P_prio; eauto.\n  \n  eapply IHvl; eauto.\n  intros; eapply H1.\n  eapply tcbjoin_get_get; eauto.\nQed.\n\nLemma TCBList_P_rtbl_add_lemma_1a:\n  forall ma mb mab mc ma' ma'' p s m tid,\n    TcbMod.join ma mb mab ->\n    TcbMod.join mc ma' ma ->\n    TcbJoin tid (p, s, m) ma'' ma' ->\n    TcbMod.get mb tid = None.\nProof.\n  introv Fj1 Fj2 Fs1.\n  assert (Hl0: TcbMod.indom ma' tid).\n    eapply TcbMod.get_indom.\n    apply TcbMod.join_sig_get in Fs1.\n    eauto.\n  assert (Hl1: TcbMod.indom ma tid).\n    eapply TcbMod.indom_sub_indom; eauto.\n    TcbMod.solve_map.\n  assert (Hl2: TcbMod.disj ma mb).\n    TcbMod.solve_map.\n  assert (Hl3: ~ TcbMod.indom mb tid).\n    eapply TcbMod.disj_indom; eauto.\n    TcbMod.solve_map.\n  eapply TcbMod.nindom_get; trivial.\nQed.  \n\nLemma get_get_neq:\n  forall m tid v1 v2 tid',\n    TcbMod.get m tid = v1 ->\n    TcbMod.get m tid' = v2 ->\n    v1 <> v2 ->\n    tid <> tid'.\nProof.\n  introv Fg1 Fg2 Fneq.\n  assert (Fdes: tid = tid' \\/ tid <> tid').\n    tauto.\n  destruct Fdes eqn: Fdes'.\n  subst.\n  tryfalse.\n  trivial.\nQed.\n\nLemma TCBList_P_rtbl_add_lemma_1:\n  forall ma mb mab' mab mc ma' ma'' prio st msg tid,\n    TcbMod.join ma mb mab ->\n    TcbMod.join mc ma' ma ->\n    TcbJoin tid (prio, st, msg) ma'' ma' ->\n    TcbJoin tid (prio, st, msg) mab' mab ->\n    R_Prio_No_Dup mab ->\n    (forall tid' p s m,\n       TcbMod.get mb tid' = Some (p, s, m) -> p <> prio).\nProof.\n  introv Fj1 Fj2 Fs1 Fs2 Fnodup.\n  introv Fget.\n  assert (Hl1: TcbMod.get mab tid = Some (prio, st, msg)).\n  eapply TcbMod.join_sig_get.\n  unfolds in Fs2.\n  unfold join, sig in Fs2; simpl in Fs2; eauto.\n\n  assert (Hl2: TcbMod.get mb tid = None).\n    eapply TCBList_P_rtbl_add_lemma_1a; eauto.\n  assert (Hl3: tid <> tid').\n    eapply get_get_neq; eauto.\n    intro; tryfalse.\n  assert (Hl4: TcbMod.sub mb mab).\n    TcbMod.solve_map.\n  unfold R_Prio_No_Dup in Fnodup.\n  lets HF1': Fnodup Hl3.\n  unfold get in HF1'; simpl in HF1'.\n  lets HF1: HF1' Hl1.\n  lets Hl5: TcbMod.get_sub_get Fget Hl4. \n  eapply neq_comm.\n  eapply HF1; eauto.\n  auto.\nQed.\n\n\nLemma TCBList_P_rtbl_add_lemma_2a:\n  forall ertbl ptbl tcbl tcbl' tid px py prio  bitx st msg mab' mab vhold,\n     Int.unsigned py <= 7 ->\n     Int.unsigned px <= 7 ->\n    RL_RTbl_PrioTbl_P ertbl ptbl vhold->\n    nth_val' (Z.to_nat (Int.unsigned ((py<<ᵢ$ 3)+ᵢpx))) ptbl = Vptr tid ->\n    TcbJoin tid (prio, st, msg) tcbl' tcbl ->\n    R_PrioTbl_P ptbl mab vhold->\n    TcbJoin tid (prio, st, msg) mab' mab -> \n    nth_val' (Z.to_nat (Int.unsigned px)) OSMapVallist = Vint32 bitx ->\n    prio = ((py<<ᵢ$ 3)+ᵢpx) /\\ \n    0 <= Int.unsigned prio < 64 /\\ \n    px = prio &ᵢ$ 7 /\\\n    py = Int.shru prio ($ 3) /\\\n    bitx = $ 1<<ᵢpx. \nProof.\n  intros.\n  unfolds in H4.\n  apply tcbjoin_get_a in H5.\n  assert ( 0 <= Int.unsigned ((py<<ᵢ$ 3)+ᵢpx) < 64).\n  clear - H H0.\n  mauto.\n  apply nth_val'_imp_nth_val_vptr in H2.\n  destruct H4.\n  lets Ha : H4 H7 H2.\n  destruct Ha as (st0 & m & Hg).\n  apply H8 in H5.\n  destruct H5; auto.\n  unfold get in Hg; simpl in Hg.\n  rewrite H5 in Hg.\n  inverts Hg.\n  splits; eauto.\n  clear - H H0.\n  mauto.\n  clear - H H0.\n  mauto.\n  clear - H0 H6.\n  mautoext.\nQed.\n  \nLemma TCBList_P_rtbl_add_lemma_2:\n  forall prio px py bitx grp rtbl vl vptr tcbls,\n    0 <= Int.unsigned prio < 64 ->\n    py = Int.shru prio ($ 3) ->\n    px = prio &ᵢ$ 7 ->\n    bitx = $ 1<<ᵢpx  ->\n    Int.unsigned py <= 7 ->\n    Int.unsigned px <= 7 ->\n    \n    nth_val ∘(Int.unsigned (Int.shru prio ($ 3))) rtbl = Some (Vint32 grp) ->\n    TCBList_P vptr vl\n              (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) rtbl\n                              (Vint32 (Int.or grp ($ 1<<ᵢ(prio &ᵢ$ 7)))))\n              tcbls\n    ->\n    TCBList_P vptr vl\n              (update_nth_val (Z.to_nat (Int.unsigned py)) rtbl\n                              (val_inj\n                                 (or (nth_val' (Z.to_nat (Int.unsigned py)) rtbl) (Vint32 bitx))))\n              tcbls.\nProof.\n  intros.\n  remember (val_inj\n           (or (nth_val' (Z.to_nat (Int.unsigned py)) rtbl) (Vint32 bitx))) as Hv.\n  subst py.\n  apply nth_val_nth_val'_some_eq in H5.\n  unfold nat_of_Z in H5.\n  rewrite H5 in HeqHv.\n  unfold or in HeqHv.\n  simpl in HeqHv.\n  subst.\n  auto.\nQed.\n\nLemma nth_val'2nth_val:\n  forall n rtbl x,\n    nth_val' n rtbl = Vint32 x ->\n    nth_val n rtbl = Some (Vint32 x).\nProof.\n  intros.\n  inductions n;\n  simpl in *;  destruct rtbl; simpl in *;tryfalse; try subst; auto.\nQed.\n\nLemma TCBList_P_rtbl_add_lemma_main:\n  forall px py bitx ertbl (ma mb mab mc ma' ma'' mab':TcbMod.map) ptbl prio st msg tid vptr vl rtbl vhold,\n    Int.unsigned py <= 7 ->\n    Int.unsigned px <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned px)) OSMapVallist = Vint32 bitx ->\n    RL_RTbl_PrioTbl_P ertbl ptbl vhold->\n    nth_val' (Z.to_nat (Int.unsigned ((py<<ᵢ$ 3)+ᵢpx))) ptbl = Vptr tid ->\n    R_PrioTbl_P ptbl mab vhold->\n    array_type_vallist_match Int8u rtbl ->\n    length rtbl = ∘OS_RDY_TBL_SIZE ->\n    (* *)\n    TcbMod.join ma mb mab ->\n    TcbMod.join mc ma' ma ->\n    TcbJoin tid (prio, st, msg) ma'' ma' ->\n    TcbJoin tid (prio, st, msg) mab' mab ->\n    (* *)\n    TCBList_P vptr vl rtbl mb ->\n    TCBList_P vptr vl\n              (update_nth_val (Z.to_nat (Int.unsigned py)) rtbl\n                              (val_inj\n                                 (or (nth_val' (Z.to_nat (Int.unsigned py)) rtbl) (Vint32 bitx))))\n              mb.\nProof.\n  intros.\n  lets Hl0: H4.\n  unfold R_PrioTbl_P in Hl0; destructs Hl0.\n  assert (Hl1: (forall tid' p s m,\n                  TcbMod.get mb tid' = Some (p, s, m) -> p <> prio)).\n  eapply TCBList_P_rtbl_add_lemma_1; eauto.\n  assert (Hl2: prio = ((py<<ᵢ$ 3)+ᵢpx) /\\ \n               0 <= Int.unsigned prio < 64 /\\ \n               px = prio &ᵢ$ 7 /\\\n               py = Int.shru prio ($ 3) /\\\n               bitx = $ 1<<ᵢpx).\n  eapply TCBList_P_rtbl_add_lemma_2a; eauto.\n  destructs Hl2.\n  assert (Hl3: (exists v, nth_val (Z.to_nat (Int.unsigned py)) rtbl = Some (Vint32 v))).\n  eapply array_type_match_get_value; eauto.\n  clear -H.\n  int auto.\n  inversion Hl3.\n  rewrite -> H18 in H20; eauto.\n  eapply TCBList_P_rtbl_add_lemma_2; eauto.\n  eapply TCBList_P_rtbl_add_simpl_version; eauto.\nQed.\n\nLemma TCBList_P_rtbl_add:\n  forall v'47 v'36 v'38 v'39 v'40 v'13 v'44 v'43 v'7 v'8  v'45 v'58 v'59 v'49 v'62 v'37 prio st msg vhold,\n    Int.unsigned v'38 <= 7 ->\n    Int.unsigned v'39 <= 7 -> \n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    prio_in_tbl ((v'38<<ᵢ$ 3)+ᵢv'39) v'13 ->\n    RL_RTbl_PrioTbl_P v'13 v'36 vhold->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 = Vptr (v'58, Int.zero) ->\n    R_PrioTbl_P v'36 v'7 vhold->\n    array_type_vallist_match Int8u v'37 ->\n    length v'37 = ∘OS_RDY_TBL_SIZE ->\n    (* *)\n    TcbMod.join v'44 v'43 v'7 ->\n    TcbMod.join v'47 v'49 v'44 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg) v'59 v'49 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg) v'62 v'7 ->\n    (* *)\n    TCBList_P v'8 v'45 v'37 v'43 ->\n    TCBList_P v'8 v'45\n              (update_nth_val (Z.to_nat (Int.unsigned v'38)) v'37\n                              (val_inj\n                                 (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37) (Vint32 v'40))))\n              v'43.\nProof.\n  intros.\n  eapply TCBList_P_rtbl_add_lemma_main; eauto.\nQed.\n(*lzh-end ****)\n\n\n\n    \nLemma rl_tbl_grp_p_set_hold:\n  forall v'12 v'38 v'13 v'69 v'39 v'36 v'58 v'40 v'41,\n    v'12 <> Int.zero ->\n    Int.unsigned v'12 <= 255 ->\n    array_type_vallist_match Int8u v'13 ->\n    length v'13 = ∘OS_EVENT_TBL_SIZE ->\n    nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n    Int.unsigned v'38 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n    Int.unsigned v'69 <= 255 ->\n    nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 = Vptr (v'58, Int.zero)->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    Int.unsigned v'40 <= 128 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) OSMapVallist = Vint32 v'41 ->\n    Int.unsigned v'41 <= 128 ->\n    Int.eq (v'69&ᵢInt.not v'40) Int.zero = true ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    RL_Tbl_Grp_P\n      (update_nth_val (Z.to_nat (Int.unsigned v'38)) v'13\n                      (Vint32 (v'69&ᵢInt.not v'40))) (Vint32 (v'12&ᵢInt.not v'41)).\nProof.\n  intros.\n  unfold Int.zero in *.\n  pose (Int.eq_spec (v'69&ᵢInt.not v'40) ($ 0)) as Hps.\n  rewrite H14 in Hps.\n  unfolds in H15.\n  unfolds.\n  intros.\n  assert (n =  (Z.to_nat (Int.unsigned v'38)) \\/  n <>(Z.to_nat (Int.unsigned v'38))) as Hdisj.\n  tauto.\n  destruct Hdisj.\n  subst n.\n  apply nth_upd_eq in H17.\n  inverts H17.\n  assert (Int.unsigned v'38 < 8) as Ha by omega.\n  assert ($ Z.of_nat (Z.to_nat (Int.unsigned v'38)) = v'38).\n  clear - Ha.\n  mauto.\n  rewrite H17 in *.\n  inverts H18.\n  assert (   ($ 1<<ᵢv'38)&ᵢInt.not v'41 = $ 0).\n  clear - Ha H12.\n  mautoext.\n  splits.\n  split.\n  intros.\n  auto.\n  intros.\n  lets Hzs : math_8_255_eq H0 H3 H.\n  rewrite Int.and_commut.\n  rewrite <-Int.and_assoc.\n  assert ( v'12&ᵢ($ 1<<ᵢv'38) = ($ 1<<ᵢv'38)&ᵢv'12) .\n  rewrite Int.and_commut; auto.\n  rewrite H20 in Hzs.\n  rewrite Hzs.\n  auto.\n  splits.\n  rewrite Int.and_assoc.\n  intros.\n  assert (Int.not v'41&ᵢ($ 1<<ᵢv'38) = ($ 1<<ᵢv'38)&ᵢInt.not v'41).\n  apply Int.and_commut.\n  rewrite H20 in H19.\n  rewrite H18 in H19.\n  rewrite Int.and_zero in H19.\n  unfold Int.zero in H19.\n  false.\n  clear -Ha H19.\n  gen H19.\n  mauto.\n  intros.\n  rewrite Hps in H19.\n  false.\n  eapply nth_upd_neq in H17; eauto.\n  inverts H18.\n  assert (Vint32 v'12 = Vint32 v'12) by auto.\n  lets Hsa : H15 H16 H17 H18.\n  destruct Hsa.\n  lets Hasd : math_nth_8_neq_not  H12 H19; try omega; eauto.\n  split.\n  split;\n    intros.\n  apply H20.\n  rewrite Int.and_assoc in H22.\n  rewrite Hasd in H22.\n  auto.\n  intros.\n  apply H20 in H22.\n  assert (v'12&ᵢInt.not v'41 = Int.not v'41 &ᵢ v'12).\n  apply Int.and_commut.\n  rewrite H23.\n  rewrite Int.and_assoc.\n  rewrite H22.\n  rewrite Int.and_zero; auto.\n  split.\n  intros.\n  apply H21.\n  rewrite Int.and_assoc in H22.\n  rewrite Hasd in H22.\n  auto.\n  intros.\n  apply H21 in H22.\n  rewrite Int.and_assoc.\n  rewrite Hasd.\n  auto.\nQed.\n\nDefinition get_last_tcb_ptr (l: list vallist) (x : val) :=\n  match l with\n    | nil => Some x\n    |  _ => V_OSTCBNext (last l nil)\n  end.\n\nLemma get_last_tcb_ptr_prop:\n  forall l1 a x1 x z,\n    V_OSTCBNext a = Some x1 ->\n    get_last_tcb_ptr l1 x1 = Some x ->\n    get_last_tcb_ptr (a :: l1) z = Some x.\nProof.\n  inductions l1; intros; simpl in *; auto.\n  inverts H0.\n  auto.\nQed.\n\n\nLemma TCBList_P_Split:\n  forall l1 x l2 rtbl tcbls,\n    TCBList_P x (l1 ++ l2) rtbl tcbls ->\n    exists y tls1 tls2,\n      get_last_tcb_ptr l1 x  = Some y /\\\n      TcbMod.join tls1 tls2 tcbls /\\\n      TCBList_P x l1 rtbl tls1 /\\\n      TCBList_P y l2 rtbl tls2.\nProof.\n  inductions l1.\n  intros.\n  simpl in H.\n  exists x TcbMod.emp tcbls.\n  simpl.\n  splits; simpljoin1; auto.\n  apply TcbMod.join_emp; auto.\n  intros.\n  simpl in H.\n  simpljoin1.\n  lets Hx : IHl1 H3.\n  simpljoin1.\n  lets Has : get_last_tcb_ptr_prop (Vptr x0)  H0 H.\n  exists x.\n  lets Hab : tcbjoin_join_ex  H1 H4.\n  simpljoin1.\n  exists x6 x5.\n  splits; eauto.\n  simpl.\n  unfold TcbJoin in H7.\n  do 4 eexists; splits; eauto.\nQed.\n\n\nLemma get_last_tcb_ptr_prop':\n  forall l1 a x1 x z,\n    l1 <> nil ->\n    V_OSTCBNext a = Some x1 ->\n    get_last_tcb_ptr (a :: l1) z = Some x->\n    get_last_tcb_ptr l1 x1 = Some x.\nProof.\n  inductions l1; intros; simpl in *; auto; tryfalse.\nQed.\n\n\nLemma TCBList_P_Combine:\n  forall l1 x l2 rtbl y tls1 tls2 tcbls,\n    get_last_tcb_ptr l1 x  = Some y ->\n    TcbMod.join tls1 tls2 tcbls ->\n    TCBList_P x l1 rtbl tls1 ->\n    TCBList_P y l2 rtbl tls2 ->\n    TCBList_P x (l1 ++ l2) rtbl tcbls.\nProof.\n  inductions l1.\n  intros.\n  simpl in *.\n  inverts H.\n  subst.\n  apply TcbMod.join_meq in H0.\n  apply TcbMod.meq_eq in H0.\n  subst.\n  auto.\n  intros.\n  simpl.\n  simpl in H1.\n  simpljoin1.\n  assert (l1 = nil \\/ l1 <> nil) by tauto.\n  destruct H1.\n  subst.\n  assert ( get_last_tcb_ptr nil x1 = Some x1).\n  simpl; auto.\n  simpl in H6.\n  subst.\n  do 4 eexists; splits; eauto.\n  unfolds in H4.\n  apply TcbMod.join_comm in H4.\n  apply TcbMod.join_meq in H4.\n  apply TcbMod.meq_eq in H4.\n  subst.\n  auto.\n  lets Hbcd : get_last_tcb_ptr_prop' H1 H3 H.\n  lets Hds : tcbjoin_join_ex2 H4 H0.\n  destruct Hds as (z & Hxa & Hxb).\n  unfold TcbJoin in Hxb.\n  do 4 eexists;  splits; eauto.\nQed.\n\n\n\n\nLemma prio_in_tbl_orself :\n  forall prio v'37 vx,\n    prio_in_tbl prio\n                (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) v'37\n                                (Vint32 (Int.or vx ($ 1<<ᵢ(prio&ᵢ$ 7))))).\nProof.\n  intros.\n  unfolds.\n  intros.\n  subst.\n  apply nth_upd_eq in H1.\n  inverts H1.\n  rewrite Int.and_commut.\n  rewrite Int.or_commut.\n  rewrite Int.and_or_absorb.\n  auto.\nQed.\n\n\nLemma prio_notin_tbl_orself :\n  forall prio v'37 vx,\n    Int.unsigned prio < 64 ->\n    nth_val (Z.to_nat(Int.unsigned (Int.shru prio ($ 3)))) v'37 = Some (Vint32 vx) ->\n    ~ prio_not_in_tbl prio\n      (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) v'37\n                      (Vint32 (Int.or vx ($ 1<<ᵢ(prio&ᵢ$ 7))))).\nProof.\n  introv Hr Hx  Hf.\n  unfolds in Hf.\n  assert (nth_val ∘(Int.unsigned (Int.shru prio ($ 3)))\n                  (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) v'37\n                                  (Vint32 (Int.or vx ($ 1<<ᵢ(prio&ᵢ$ 7))))) = \n          Some (Vint32  (Int.or vx ($ 1<<ᵢ(prio&ᵢ$ 7))))).\n  eapply update_nth; eauto.\n  lets Hzds : Hf H; eauto.\n  rewrite Int.and_commut in Hzds.\n  rewrite Int.or_commut in Hzds.\n  rewrite Int.and_or_absorb in Hzds.\n  gen Hzds.\n  clear - Hr.\n  mauto.\nQed.\n   \n    \nLemma TCBList_P_post_msg:\n  forall v'42 v'48 v'47 v'60 v'50 v'37 v'59 v'49 v'44 v'63 v'64 v'65 v'51 v'52 v'53 v'54 v'55 v'56 x00 v'58 v'40 v'38 prio st msg v'7 v'62 v'43 v'36 v'39 v'13 vhold,\n    Int.unsigned v'38 <= 7 ->\n    Int.unsigned v'39 <= 7 -> \n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    prio_in_tbl ((v'38<<ᵢ$ 3)+ᵢv'39) v'13 ->\n    RL_RTbl_PrioTbl_P v'13 v'36 vhold->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 = Vptr (v'58, Int.zero) ->\n    R_PrioTbl_P v'36 v'7  vhold->\n    array_type_vallist_match Int8u v'37 ->\n    length v'37 = ∘OS_RDY_TBL_SIZE ->\n    (* *)\n    TcbMod.join v'44 v'43 v'7 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg) v'62 v'7 ->\n    get_last_tcb_ptr v'48 v'42 = Some (Vptr (v'58, Int.zero)) ->\n    TCBList_P v'42 v'48 v'37 v'47 ->\n    TCBList_P v'60 v'50 v'37 v'59 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg) v'59 v'49 ->\n    TcbMod.join v'47 v'49 v'44 ->\n    TCBNode_P\n      (v'60\n         :: v'63\n         :: v'64\n         :: v'65\n         :: Vint32 v'51\n         :: V$OS_STAT_Q\n         :: Vint32 v'52\n         :: Vint32 v'53\n         :: Vint32 v'54\n         :: Vint32 v'55 :: Vint32 v'56 :: nil) v'37\n      (prio, st, msg) ->\n    TCBList_P v'42\n              (v'48 ++\n                    (v'60\n                       :: v'63\n                       :: Vnull\n                       :: Vptr x00\n                       :: V$0\n                       :: Vint32 ($ OS_STAT_Q&ᵢInt.not ($ OS_STAT_Q))\n                       :: Vint32 v'52\n                       :: Vint32 v'53\n                       :: Vint32 v'54\n                       :: Vint32 v'55 :: Vint32 v'56 :: nil) :: v'50)\n              (update_nth_val (Z.to_nat (Int.unsigned v'38)) v'37\n                              (val_inj\n                                 (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37) (Vint32 v'40))))           \n              (TcbMod.set v'44 (v'58, Int.zero)\n                          (prio, rdy , Vptr x00)).\nProof.\n  intros.\n  unfolds in H5.\n  destruct H5 as (Ha1 & Ha2 & Ha3).\n  assert ( 0 <= Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39) < 64).\n  clear -H H0.\n  mauto.\n  unfold nat_of_Z in Ha1.\n  eapply nth_val'_imp_nth_val_vptr in H4.\n  lets Hps : Ha1 H5 H4.\n  \n  lets Hgs : tcbjoin_get_a H9.\n  assert ((v'58, Int.zero) <> vhold) as Hnvhold.\n  apply Ha2 in Hgs.\n  destruct Hgs;auto.\n  apply Hps in Hnvhold.\n  clear Hps.\n  simpljoin1.\n  unfold get in H16; simpl in H16.\n  rewrite H16 in Hgs.\n  inverts Hgs.\n  remember ((v'38<<ᵢ$ 3)) as px.\n  remember (v'39) as py.\n  clear Heqpy.\n  remember (px+ᵢpy) as prio.\n  remember ( (v'58, Int.zero)) as tid.\n  lets Hps : tcbjoin_set_ex (prio,st,msg) (prio,rdy,Vptr x00)  H14;eauto.\n  destruct Hps as (b&Htx & Hty).\n  remember (val_inj\n              (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37) (Vint32 v'40))) as Hv.\n  assert (0<= Z.to_nat (Int.unsigned v'38) <8)%nat.\n  clear -H.\n  mauto.\n  lets Hsx : n07_arr_len_ex H6 H7; eauto.\n  destruct Hsx as (vx & Hnth & Hi).\n  lets Hns :  nth_val_nth_val'_some_eq  Hnth.\n  rewrite Hns in HeqHv.\n  simpl in HeqHv.\n  subst Hv.\n  assert (v'38 = Int.shru prio ($ 3)).\n  subst.\n  clear - H H0.\n  mauto.\n  rewrite H19.\n  assert (v'40 = ($ 1<<ᵢ(prio &ᵢ$ 7))).  \n  rewrite Heqprio.\n  rewrite Heqpx.\n  assert ((((v'38<<ᵢ$ 3)+ᵢpy)&ᵢ$ 7) = py).\n  clear -H H0.\n  mauto.\n  rewrite H20.\n  clear -H0 H1.\n  mautoext.\n  rewrite H20.\n  eapply TCBList_P_Combine; eauto.\n  eapply TCBList_P_rtbl_add_simpl_version; eauto.\n  rewrite <-H19.\n  auto.\n  intros.\n  unfolds in Ha3.\n  lets Hsx : tcbjoin_join_get_neq H13 H14 H21.\n  destruct Hsx.\n  eapply Ha3; eauto.\n  lets Hacb  :  TcbMod.join_get_l H8 H23; eauto.\n  simpl.\n  unfold TcbJoin in Htx.\n  do 4 eexists; splits; eauto.\n  unfolds; simpl; eauto.\n  unfolds in H15.\n  unfolds.\n  fsimpl.\n  usimpl H15.\n  usimpl H22.\n  splits.\n  unfolds; simpl; auto.\n  unfolds; simpl; auto.\n  funfold H23.\n  unfolds.\n  do 6 eexists; splits; try solve [unfolds; simpl;auto].\n  omega.\n  splits; eauto.\n  eexists.\n  split.\n  unfolds;simpl; eauto.\n  auto.\n  unfolds.\n  splits.\n  unfolds.\n  intros.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  splits; try solve [unfolds; simpl;auto].\n  eexists; eauto.\n  unfolds.\n  intros.\n  inverts H15.\n  splits; try solve [unfolds; simpl;auto].\n  unfolds.\n  splits; try solve [unfolds; simpl;auto].\n  apply prio_in_tbl_orself ; auto.\n  unfolds.\n  splits.\n  unfolds.\n  intros.\n  usimpl H22.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  usimpl H25.\n  false.\n  rewrite H26 in H19.\n  rewrite H19 in Hnth.\n  rewrite H26 in H17.\n  rewrite H26 in H22.\n  lets Hfs :  prio_notin_tbl_orself  H17 Hnth.\n  tryfalse.\n\n  unfolds.\n  intros.\n  usimpl H22.\n  unfolds.\n  intros.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  usimpl H25.\n\n  unfolds.\n  intros.\n  usimpl H22.\n  unfolds.\n  intros.\n  unfolds in H15.\n  fsimpl.\n  usimpl H15.\n  usimpl H25.\n  \n  unfolds.\n  splits; try solve [\n                unfolds;\n                introv Hf; inverts Hf].\n  eapply TCBList_P_rtbl_add_simpl_version; eauto.\n  rewrite <-H19.\n  auto.\n  intros.\n  lets Hnas : tcbjoin_tid_neq H13 H21.\n  unfolds in Ha3.\n  eapply Ha3; eauto.\n  lets Haxc  : TcbMod.join_get_r H13 H21.\n  lets Haa : TcbMod.join_get_r H14 Haxc.\n  lets Ad :  TcbMod.join_get_l H8 Haa; eauto.\nQed.\n\n\nLemma rl_tbl_grp_p_set_hold':\n  forall v'12 v'38 v'37 v'57 v'69 v'39 v'36 v'13 v'58 v'40 v'41,\n    v'12 <> Int.zero ->\n    Int.unsigned v'12 <= 255 ->\n    array_type_vallist_match Int8u v'13 ->\n    length v'13 = ∘OS_EVENT_TBL_SIZE ->\n    array_type_vallist_match Int8u v'37 ->\n    length v'37 =  ∘OS_RDY_TBL_SIZE ->\n    nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n    Int.unsigned v'38 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n    Int.unsigned v'69 <= 255 ->\n    nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 = Vptr (v'58, Int.zero)->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    Int.unsigned v'40 <= 128 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) OSMapVallist = Vint32 v'41 ->\n    Int.unsigned v'41 <= 128 ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    RL_Tbl_Grp_P v'37 (Vint32 v'57) ->\n    RL_Tbl_Grp_P  (update_nth_val (Z.to_nat (Int.unsigned v'38)) v'37\n                                  (val_inj\n                                     (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37) (Vint32 v'40))))\n                  (Vint32 (Int.or v'57 v'41)).\nProof.\n  intros.\n  unfold Int.zero in *.\n  unfolds in H16.\n  unfolds in H17.\n  unfolds.\n  intros.\n  inverts H20.\n  assert (n =  (Z.to_nat (Int.unsigned v'38)) \\/  n <>(Z.to_nat (Int.unsigned v'38))) as Hdisj.\n  tauto.\n  destruct Hdisj.\n  subst n.\n  apply nth_upd_eq in H19.\n  unfolds in H19.\n  remember (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37) (Vint32 v'40)) as vo.\n  destruct vo; tryfalse.\n  subst v0.\n  assert ((Z.to_nat (Int.unsigned v'38)) < length v'37)%nat.\n  rewrite H4.\n  simpl.\n  clear -H6.\n  mauto.\n  lets Hrs : array_int8u_nth_lt_len H19 ; eauto.\n  destruct Hrs as (i & Hnth & Hr).\n  rewrite Hnth in Heqvo.\n  simpl in Heqvo.\n  inverts Heqvo.\n  assert (Int.unsigned v'38 < 8) as Ha by omega.\n  assert ($ Z.of_nat (Z.to_nat (Int.unsigned v'38)) = v'38).\n  clear - Ha.\n  mauto.\n  rewrite H20 in *.\n  clear H20.\n  split.\n  split.\n  intros.\n  rewrite Int.and_commut in H20.\n  rewrite  Int.and_or_distrib in H20.\n  apply int_or_zero_split in H20.\n  lets Hneq : math_nth_8_neq_zero  Ha H14.\n  destruct H20.\n  tryfalse.\n  intros.\n  apply int_or_zero_split in H20.\n  destruct H20. subst.\n  lets Hnz : math_nth_8_neq_zero' H12.\n  omega.\n  tryfalse.\n  splits.\n  assert (Int.unsigned v'40 <= Int.unsigned (Int.or i v'40)) .\n  rewrite Int.or_commut.\n  apply Int.or_le.\n  lets Hgs : math_nth_8_gt_zero  H10 H12.\n  assert (0 < Int.unsigned (Int.or i v'40)) by omega.\n  intros.\n  unfolds.\n  rewrite zlt_true; auto.\n  intros.\n  rewrite Int.and_commut.\n  rewrite Int.and_or_distrib.\n  lets Has :   math_nth_8_eq_shl Ha H14.\n  rewrite Has.\n  rewrite Int.or_commut.\n  rewrite Int.or_and_absorb.\n  auto.\n  apply nth_upd_neq in H19.\n  assert ( Vint32 v'57 = Vint32 v'57) by auto.\n  lets Hrs : H17 H18 H19 H21.\n  destruct Hrs.\n  splits.\n  split;intros.\n  apply H22.\n  rewrite Int.and_commut in H24.\n  rewrite Int.and_or_distrib in H24.\n  apply int_or_zero_split in H24.\n  destruct H24.\n  rewrite Int.and_commut; auto.\n  apply H22 in H24.\n  rewrite Int.and_commut.\n  rewrite Int.and_or_distrib .\n  rewrite Int.and_commut in H24.\n  rewrite H24.\n  rewrite Int.and_commut.\n  assert ($ 0 = Int.zero) by auto.\n  rewrite H25.\n  rewrite Int.or_commut.\n  rewrite Int.or_zero.\n  lets Hbc : math_nth_8_eq_zero H6 H14 H20; eauto.\n  intros.\n  split; intros.\n  apply H23.\n  lets Hbc : math_nth_8_eq_zero H6 H14 H20; eauto.\n  rewrite Int.and_commut in H24.\n  rewrite Int.and_or_distrib in H24.\n  rewrite Int.and_commut in Hbc.\n  rewrite Hbc in H24.\n  rewrite Int.or_zero in H24.\n  rewrite Int.and_commut.\n  auto.\n  apply H23 in H24.\n  lets Hbc : math_nth_8_eq_zero H6 H14 H20; eauto.\n  rewrite Int.and_commut .\n  rewrite Int.and_or_distrib.\n  rewrite Int.and_commut in Hbc.\n  rewrite Hbc .\n  rewrite Int.or_zero.\n  rewrite Int.and_commut.\n  auto.\n  auto.\nQed.\n\n\n\nLemma r_priotbl_p_set_hold:\n  forall v'7 prio st msg v'36 tid x y vhold,\n    R_PrioTbl_P v'36 v'7 vhold->\n    TcbMod.get v'7 tid = Some (prio, st, msg) ->\n    R_PrioTbl_P v'36\n                (TcbMod.set v'7 tid\n                            (prio, x, y)) vhold.\nProof.\n  intros.\n  unfolds in H.\n  unfolds.\n  splits.\n  intros.\n  destruct H.\n  lets Hs : H H1 H2.\n  simpljoin1.\n  assert (tcbid = tid \\/ tcbid <> tid) by tauto.\n  destruct H7.\n  subst.\n  unfold get; simpl.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; auto.\n  apply Hs in H3; auto.\n  unfold get in H3; simpl in H3.\n  rewrite H0 in H3.\n  simpljoin1.\n  inverts H3.\n  do 2 eexists; eauto.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  intros.\n  assert (tcbid = tid \\/ tcbid <> tid) by tauto.\n  destruct H2.\n  subst.\n  rewrite  TcbMod.set_sem in H1.\n  rewrite tidspec.eq_beq_true in H1.\n  inverts H1.\n  eapply H; eauto.\n  auto.\n   rewrite  TcbMod.set_sem in H1.\n  rewrite tidspec.neq_beq_false in H1; auto.\n  eapply H; eauto.\n  destruct H.\n  destruct H1.\n  eapply R_Prio_NoChange_Prio_hold; eauto.\nQed.   \n\nLemma rl_tbl_grp_p_set_hold''\n: forall (v'12 v'38 : int32) (v'13 : vallist) \n         (v'69 v'39 : int32) (v'36 : list val) (v'58 : block)\n         (v'40 v'41 : int32),\n    v'12 <> Int.zero ->\n    Int.unsigned v'12 <= 255 ->\n    array_type_vallist_match Int8u v'13 ->\n    length v'13 = ∘OS_EVENT_TBL_SIZE ->\n    nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n    Int.unsigned v'38 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n    Int.unsigned v'69 <= 255 ->\n    nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 =\n    Vptr (v'58, Int.zero) ->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    Int.unsigned v'40 <= 128 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) OSMapVallist = Vint32 v'41 ->\n    Int.unsigned v'41 <= 128 ->\n    Int.eq (v'69&ᵢInt.not v'40) Int.zero = false->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    RL_Tbl_Grp_P\n      (update_nth_val (Z.to_nat (Int.unsigned v'38)) v'13\n                      (Vint32 (v'69&ᵢInt.not v'40))) (Vint32 v'12).\nProof.\n  intros.\n  unfold Int.zero in *.\n  pose (Int.eq_spec (v'69&ᵢInt.not v'40) ($ 0)) as Hps.\n  rewrite H14 in Hps.\n  unfolds in H15.\n  unfolds.\n  intros.\n  assert (n =  (Z.to_nat (Int.unsigned v'38)) \\/  n <>(Z.to_nat (Int.unsigned v'38))) as Hdisj.\n  tauto.\n  destruct Hdisj.\n  subst n.\n  apply nth_upd_eq in H17.\n  inverts H17.\n  assert (Int.unsigned v'38 < 8) as Ha by omega.\n  assert ($ Z.of_nat (Z.to_nat (Int.unsigned v'38)) = v'38).\n  clear - Ha.\n  mauto.\n  rewrite H17 in *.\n  inverts H18.\n  splits.\n  splits.\n  intros.\n  lets Hsa : math_8_255_eq H0 H3 H.\n  rewrite Hsa in H18.\n  false.\n  gen H18.\n  clear - Ha.\n  mauto.\n  intros.\n  tryfalse.\n  split.\n  intros.\n  unfolds.\n  rewrite zlt_true; auto.\n  remember (v'69&ᵢInt.not v'40) as x.\n  clear - Hps.\n  assert (0<=Int.unsigned x) by (int auto).\n  assert (0 = Int.unsigned x \\/ 0 < Int.unsigned x) by omega.\n  destruct H0; auto.\n  false.\n  apply Hps.\n  rewrite H0.\n  int auto.\n  intros.\n  lets Hzs : math_8_255_eq H0 H3 H.\n  auto.\n  inverts H18.\n  eapply nth_upd_neq in H17;  eauto.\nQed.\n\n  \nLemma rl_rtbl_priotbl_p_hold:\n  forall v'36 v'12 v'13 v'38 v'69 v'39 v'58 v'40 v'41 v'57 v'37 vhold,\n    (v'58, Int.zero) <> vhold ->\n    RL_RTbl_PrioTbl_P v'37 v'36 vhold->\n    v'12 <> Int.zero ->\n    Int.unsigned v'12 <= 255 ->\n    array_type_vallist_match Int8u v'13 ->\n    length v'13 = ∘OS_EVENT_TBL_SIZE ->\n    array_type_vallist_match Int8u v'37 ->\n    length v'37 = ∘OS_EVENT_TBL_SIZE ->\n    nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n    Int.unsigned v'38 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n    Int.unsigned v'69 <= 255 ->\n    nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 = Vptr (v'58, Int.zero)->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    Int.unsigned v'40 <= 128 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) OSMapVallist = Vint32 v'41 ->\n    Int.unsigned v'41 <= 128 ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    RL_Tbl_Grp_P v'37 (Vint32 v'57) ->\n    Int.unsigned v'57 <= 255 ->\n    array_type_vallist_match Tint8 v'37 ->\n    length v'37 = nat_of_Z OS_RDY_TBL_SIZE ->\n    RL_RTbl_PrioTbl_P\n      (update_nth_val (Z.to_nat (Int.unsigned v'38)) v'37\n                      (val_inj\n                         (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37) (Vint32 v'40))))\n      v'36 vhold.\nProof.\n  introv Hnvhold.\n  intros.\n  unfold  RL_RTbl_PrioTbl_P  in *.\n  unfolds in H17.\n  unfolds in H18.\n  intros.\n  unfolds in H23.\n  assert (  p&ᵢ$ 7  = p&ᵢ$ 7 ) by auto.\n  assert (Int.shru p ($ 3) = Int.shru p ($ 3)) by auto.\n  assert ( ∘(Int.unsigned (Int.shru p ($ 3))) <> Z.to_nat (Int.unsigned v'38) \\/\n           ∘(Int.unsigned (Int.shru p ($ 3))) = (Z.to_nat (Int.unsigned v'38)))%nat.\n  tauto.\n\n  lets Hy : math_unmap_get_y H1 H6.\n  assert ( ∘(Int.unsigned (Int.shru p ($ 3))) <∘OS_EVENT_TBL_SIZE)%nat.\n  clear -H22.\n  mauto.\n  lets Ha : nthval'_has_value H4  H27; eauto.\n  destruct Ha as (x&Hnth & Htru).\n  lets Hnt : nth_val'_imp_nth_val_int Hnth.\n  destruct H26.\n  assert ( nth_val ∘(Int.unsigned (Int.shru p ($ 3)))\n                   (update_nth_val (Z.to_nat (Int.unsigned v'38)) v'37\n                                   (val_inj\n                                      (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37)\n                                          (Vint32 v'40)))) = Some (Vint32 x)).\n  eapply nth_upd_neqrev; eauto.\n  lets Hb : H23 H24 H25 H28 .\n  assert (Int.unsigned (Int.shru p ($ 3))<8). \n  clear - H22.\n  mauto.\n  remember (Int.shru p ($3)) as px. \n  assert ($ Z.of_nat ∘(Int.unsigned px) = px).\n  clear - H29.\n  mauto.\n  assert (prio_in_tbl p v'37 ).\n  unfolds.\n  intros.\n  subst.\n  rewrite H33 in Hnt.\n  inverts Hnt.\n  auto.\n  eapply H; eauto.\n  assert (  p&ᵢ$ 7 = v'39 \\/  p&ᵢ$ 7 <> v'39).\n  tauto.\n  destruct H28.\n  subst v'39.\n\n  lets Hzzp : int_usigned_tcb_range H22.\n  destruct Hzzp.\n  remember (Int.shru p ($3)) as px.\n  assert (px = v'38).\n  clear - Hy  H29 H26.\n  gen H26.\n  mauto.\n  subst v'38.\n  subst px.\n  assert ( (((Int.shru p ($ 3))<<ᵢ$ 3)+ᵢ(p&ᵢ$ 7)) = p).\n  clear -H22.\n  mauto.\n  rewrite H30 in H12.\n  apply nth_val'_imp_nth_val_vptr in H12.\n  eexists; eauto.\n  assert ( prio_in_tbl p v'37).\n  unfolds.\n  intros.\n  subst.\n  lets Hzzp : int_usigned_tcb_range H22.\n  destruct Hzzp.\n  remember (Int.shru p ($3)) as px.\n  remember (p&ᵢ$ 7) as py.\n  assert ( px = v'38).\n  clear -Hy H30 H26.\n  gen H26.\n  mauto.\n  subst v'38.\n  rewrite Hnt in H31.\n  inverts H31.\n  remember ((val_inj\n               (or (nth_val' (Z.to_nat (Int.unsigned px)) v'37)\n                   (Vint32 v'40)))) as v.\n  unfold val_inj in Heqv.\n  rewrite H26 in Hnth.\n  rewrite Hnth in Heqv.\n  unfold or in Heqv.\n  subst v.\n  assert ( nth_val ∘(Int.unsigned (px))\n                   (update_nth_val (Z.to_nat (Int.unsigned px)) v'37\n                                   (Vint32 (Int.or z v'40))) =Some (Vint32 (Int.or z v'40))).\n  rewrite <- H26.\n  eapply update_nth; eauto.\n  lets Hd : H23 H31; eauto.\n  rewrite Int.and_commut in Hd.\n  rewrite Int.and_or_distrib in Hd.\n  lets Hzzps :  math_nth_8_eq_zero'  H13 H29 H28; eauto; try omega.\n  rewrite Int.and_commut in Hzzps.\n  rewrite Hzzps in Hd.\n  rewrite Int.or_zero in Hd.\n  rewrite Int.and_commut in Hd.\n  auto.\n  eapply H; eauto.\nQed.\n\n(*modified by zhanghui*)\nLemma rl_rtbl_priotbl_p_hold1:\n  forall v'36 v'38 v'39 v'58 v'40 v'37 vhold,\n    RL_RTbl_PrioTbl_P v'37 v'36 vhold->\n    Int.unsigned v'38 <= 7 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 = Vptr (v'58, Int.zero)->\n    (v'58, Int.zero) <> vhold ->\n    array_type_vallist_match Tint8 v'37 ->\n    length v'37 = nat_of_Z OS_RDY_TBL_SIZE ->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    Int.unsigned v'40 <= 128 ->\n    RL_RTbl_PrioTbl_P\n      (update_nth_val (Z.to_nat (Int.unsigned v'38)) v'37\n                      (val_inj\n                         (or (nth_val' (Z.to_nat (Int.unsigned v'38)) v'37) (Vint32 v'40))))\n      v'36 vhold.\nProof.\n  intros.\n  unfold  RL_RTbl_PrioTbl_P  in *.\n  intros.\n  assert(0 <= Int.unsigned ((v'38<<ᵢ$ 3) +ᵢ v'39) < 64).\n  clear - H0 H1.\n  mauto.\n\n  assert(p <> ((v'38<<ᵢ$ 3) +ᵢ  v'39) \\/ p = (v'38<<ᵢ$ 3) +ᵢ  v'39).\n  tauto.\n  destruct H11.\n \n  lets Hx: new_rtbl.prio_set_rdy_in_tbl_rev H8 H10 H4 H5 H11.\n  unfold new_rtbl.set_rdy in Hx.\n  assert(((v'38<<ᵢ$ 3) +ᵢ  v'39) >>ᵢ $ 3 = v'38).\n  clear - H0 H1.\n  mauto.\n  rewrite H12 in Hx.\n  assert(((v'38<<ᵢ$ 3) +ᵢ  v'39)&ᵢ$ 7 = v'39).\n  clear - H0 H1.\n  mauto.\n  rewrite H13 in Hx.\n  assert(($ 1<<ᵢv'39) = v'40).\n  symmetry.\n  apply math_mapval_core_prop; auto.\n  mauto.\n  rewrite H14 in Hx.\n  eapply Hx in H9.\n  apply H; auto.\n\n  substs.\n  exists (v'58, Int.zero).\n  split; auto.\n  apply nth_val'_imp_nth_val_vptr; auto.\nQed.\n\n\nLemma prio_wt_inq_convert:\n  forall pri vx,\n    PrioWaitInQ pri vx <->\n    PrioWaitInQ (Int.unsigned ($ pri)) vx /\\ 0 <= pri < 64.\nProof.\n  split; intros.\n  unfolds in H.\n  simpljoin1.\n  split.\n  unfolds.\n  do 3 eexists;splits; eauto.\n  clear -H H4.\n  int auto.\n  rewrite Int.repr_unsigned.\n  eauto.\n  rewrite Int.repr_unsigned.\n  eauto.\n  auto.\n  auto.\n  destruct H.\n  unfolds in H.\n  simpljoin1.\n  unfolds.\n  do 3 eexists;splits;eauto.\n  clear H H6.\n  rewrite Int.repr_unsigned in *.\n  eauto.\n  rewrite Int.repr_unsigned in *.\n  eauto.\nQed.\n\n\n\n\nLemma prio_wt_inq_tid_neq:\n  forall prio'  v'13  v'69 prio,\n    nth_val' (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) v'13 = Vint32 v'69 ->\n    Int.unsigned prio < 64 ->\n    (PrioWaitInQ (Int.unsigned prio')\n                 (update_nth_val (Z.to_nat (Int.unsigned (Int.shru prio ($ 3)))) v'13\n                                 (Vint32 (v'69&ᵢInt.not ($ 1<<ᵢ (prio &ᵢ $7))))) <->\n     PrioWaitInQ  (Int.unsigned prio') v'13 /\\  prio' <> prio).\nProof.\n  intros.\n  splits.\n  intros.\n  unfolds in H1.\n  destruct H1 as (x & y & z & Hx & Hy & Hz & Hn & Heq).\n  subst.\n  rewrite Int.repr_unsigned in *.\n  \n  assert (Int.shru prio ($ 3) = Int.shru prio' ($ 3) \\/\n          Int.shru prio ($ 3) <> Int.shru prio' ($ 3)) by tauto.\n  destruct H1.\n  rewrite H1 in Hn.\n  lets Hzs : nth_upd_eq  Hn.\n  inverts Hzs.\n  assert (prio&ᵢ$ 7 = prio'&ᵢ$ 7 \\/ prio&ᵢ$ 7 <> prio'&ᵢ$ 7) by tauto.\n  destruct H2.\n  rewrite H2 in Heq.\n  rewrite Int.and_assoc in Heq.\n  assert (Int.not ($ 1<<ᵢ(prio'&ᵢ$ 7))&ᵢ(Int.one<<ᵢ(prio'&ᵢ$ 7)) = Int.zero).\n  rewrite Int.and_commut.\n  rewrite  Int.and_not_self; auto.\n  rewrite H3 in Heq.\n  rewrite Int.and_zero in Heq.\n  false.\n  gen Heq.\n  clear -Hx.\n  mauto.\n  splits.\n  unfolds.\n  do 3 eexists.\n  splits; eauto.\n  rewrite Int.repr_unsigned.\n  unfold nat_of_Z.\n  rewrite H1 in H.\n  apply nth_val'_imp_nth_val_int in H.\n  eauto.\n  rewrite Int.repr_unsigned.\n  rewrite Int.and_assoc in Heq.\n  \n  assert (Int.unsigned (prio'&ᵢ$ 7) < 8).\n  clear -Hx.\n  mauto.\n  assert (Int.unsigned (prio&ᵢ$ 7) < 8).\n  clear -H0.\n  mauto.\n  lets Hxa : int_not_shrl_and H4 H3 H2.\n  unfold Int.one in *.\n  rewrite Hxa in Heq.\n  auto.\n  introv Hf.\n  subst prio.\n  apply H2.\n  auto.\n  apply nth_upd_neq in Hn.\n  splits.\n  unfolds.\n  do 3 eexists.\n  splits; eauto.\n  rewrite Int.repr_unsigned.\n  apply nth_val'_imp_nth_val_int in H.\n  eauto.\n  rewrite Int.repr_unsigned.\n  eauto.\n  introv hf.\n  subst prio.\n  apply H1.\n  auto.\n  unfold nat_of_Z.\n  introv Hf.\n  apply H1.\n  rewrite Z2Nat.inj_iff in Hf.\n  apply unsigned_inj.\n  auto.\n  apply Int.unsigned_range.\n  apply Int.unsigned_range.\n  intros.\n  destruct H1 as (Hpro & Hneq).\n  unfolds in Hpro.\n  destruct Hpro as (px & py & pz & Hx& Hy& Hz &Hnt & Hez).\n  unfolds.\n  rewrite Int.repr_unsigned.\n  apply nth_val'_imp_nth_val_int in H.\n  assert (Int.shru prio ($ 3) = Int.shru prio' ($ 3) \\/\n          Int.shru prio ($ 3) <> Int.shru prio' ($ 3)) by tauto.\n  destruct H1.\n  unfold nat_of_Z in *.\n  do 3 eexists.\n  splits; eauto.\n  rewrite H1 in *.\n  eapply update_nth; eauto.\n  subst py px.\n  rewrite Int.repr_unsigned in *.\n  rewrite H1 in *.\n  rewrite H in Hnt.\n  inverts Hnt.\n  assert (pz &ᵢ Int.not ($ 1<<ᵢ(prio&ᵢ$ 7)) = Int.not ($ 1<<ᵢ(prio&ᵢ$ 7)) &ᵢ pz).\n  apply Int.and_commut.\n  rewrite H2.\n  rewrite Int.and_assoc.\n  rewrite Hez.\n  lets Hsd : int_usigned_tcb_range Hx.\n  destruct Hsd.\n  assert (0<=Int.unsigned prio < 64).\n  split; try omega.\n  clear -prio'.\n  int auto.\n  lets Hss : int_usigned_tcb_range H5.\n  destruct Hss.\n  apply  int_not_shrl_and ; try omega.\n  introv Hf.\n  apply Hneq.\n\n  rewrite math_prio_eq.\n  rewrite math_prio_eq at 1.\n  rewrite H1.\n  rewrite Hf.\n  auto.\n  omega.\n  omega.\n  do 3 eexists.\n  splits; eauto.\n  subst px py.\n  rewrite Int.repr_unsigned in *.\n  unfold nat_of_Z in *.\n  eapply nth_upd_neqrev; eauto.\n  introv Hf.\n  apply H1.\n  rewrite Z2Nat.inj_iff in Hf.\n  apply unsigned_inj.\n  auto.\n  apply Int.unsigned_range.\n  apply Int.unsigned_range.\n  subst px.\n  rewrite Int.repr_unsigned in *.\n  auto.\nQed.\n\n\nLemma wtset_notnil_msgls_nil:\n  forall x1 x0 x ,\n  x1 <> nil ->\n  RH_ECB_P (absmsgq x x0, x1) -> x = nil.\nProof.\n  intros.\n  unfolds in H0.\n  eapply H0; eauto.\nQed.\n\n\nLemma  rl_tbl_grp_neq_zero:\n  forall  v'12  px v'13 v'69,\n    Int.unsigned px < 8 ->\n    Int.unsigned v'12 <= 255 ->\n    v'12 <> $ 0 ->\n    nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32  px -> \n    nth_val' (Z.to_nat (Int.unsigned px)) v'13 = Vint32 v'69 ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    v'69 <> $ 0.\nProof.\n  introv Hran Hras Hneq Hnth Hth2 Hr.\n  unfolds in Hr.\n  assert (0 <=Z.to_nat (Int.unsigned px) < 8 )%nat.\n  clear - Hran.\n  mauto.\n  apply nth_val'_imp_nth_val_int in Hth2.\n  assert (Vint32 v'12 = Vint32 v'12) by auto.\n  lets Hsr : Hr H Hth2 H0.\n  simpljoin1.\n  lets Hneqz : math_8_255_eq Hras Hneq; eauto.\n  assert ($ Z.of_nat (Z.to_nat (Int.unsigned px)) = px).\n  clear -Hran.\n  mauto.\n  rewrite H0 in *.\n  rewrite Hneqz in *.\n  assert (v'69 = $ 0 \\/ v'69 <> $ 0) by tauto.\n  destruct H4; auto.\n  apply H1 in H4.\n  false.\n  gen H4.\n  clear - Hran.\n  mauto.\nQed.\n\n\nLemma ECBList_P_Set_Rdy_hold:\n  forall a tcbls tid prio  msg msg'  x y  b c eid nl,\n    TcbMod.get tcbls tid =  Some (prio, wait (os_stat_q eid) nl, msg) ->\n    EcbMod.get c eid = None ->\n    ECBList_P x y a b c tcbls ->\n    ECBList_P x y a b c (TcbMod.set tcbls tid (prio,rdy,msg')).\nProof.\n  inductions a; intros.\n  simpl in *; auto.\n  simpl in H1.\n  simpljoin1.\n  destruct b; tryfalse.\n  destruct a.\n  simpljoin1.\n  simpl.\n  eexists.\n  splits; eauto.\n  unfolds.\n  unfolds in H2.\n\n  splits.\n  \n  destructs H2.\n  unfolds in H2.\n  simpljoin1.\n  unfolds.\n  splits; unfolds;intros.\n\n  apply H2 in H11.\n  apply H11 in H12.\n  simpljoin1.\n  assert (tid = x3 \\/ tid <> x3) by tauto.\n  destruct H13.\n  subst tid.\n  unfold get in H12; simpl in H12.\n  rewrite H12 in H.\n  inverts H.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n  \n  \n  apply H8 in H11.\n  apply H11 in H12.\n  simpljoin1.\n  assert (tid = x3 \\/ tid <> x3) by tauto.\n  destruct H13.\n  subst tid.\n  unfold get in H12; simpl in H12.\n  rewrite H12 in H.\n  inverts H.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n\n  \n  apply H9 in H11.\n  apply H11 in H12.\n  simpljoin1.\n  assert (tid = x3 \\/ tid <> x3) by tauto.\n  destruct H13.\n  subst tid.\n  unfold get in H12; simpl in H12.\n  rewrite H12 in H.\n  inverts H.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n\n  \n  apply H10 in H11.\n  apply H11 in H12.\n  simpljoin1.\n  assert (tid = x3 \\/ tid <> x3) by tauto.\n  destruct H13.\n  subst tid.\n  unfold get in H12; simpl in H12.\n  rewrite H12 in H.\n  inverts H.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  exists x3 x4 x5.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; eauto.\n\n  \n  unfolds.\n  destructs H2;unfolds in H6;destructs H6.\n  splits;intros prio' mg ng x3 Hti;\n  assert (tid = x3\n          \\/ tid <> x3) by tauto.\n  destruct H11.\n  subst tid.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  rewrite H in Hti.\n  inverts Hti.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  rewrite tidspec.eq_beq_true in Hti; tryfalse; auto.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  eapply H6; eauto.\n\n  destruct H11.\n  subst tid.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  rewrite H in Hti.\n  inverts Hti.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  rewrite tidspec.eq_beq_true in Hti; tryfalse; auto.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  eapply H8; eauto.\n\n  destruct H11.\n  subst tid.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  rewrite H in Hti.\n  inverts Hti.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  rewrite tidspec.eq_beq_true in Hti; tryfalse; auto.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  eapply H9; eauto.\n\n  destruct H11.\n  subst tid.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  rewrite H in Hti.\n  inverts Hti.\n  apply ecbmod_joinsig_get in H3.\n  tryfalse.\n  rewrite tidspec.eq_beq_true in Hti; tryfalse; auto.\n  rewrite TcbMod.set_sem in Hti.\n  rewrite tidspec.neq_beq_false in Hti; auto.\n  eapply H10; eauto.\n\n  simpljoin1;auto.\n\n\n  do 3 eexists; splits; eauto.\n  eapply IHa; eauto.\n  eapply ecbmod_joinsig_get_none; eauto.\nQed.\n\n\n\nLemma ecblist_p_post_exwt_hold:\n  forall  v'36 v'12 v'13 v'38 v'69 v'39 v'58 v'40  v'32 v'15 v'24 v'35 v'16\n          v'18 v'19 v'20 v'34 v'21 v'22 v'23 v'25 v'26 v'27 x x0 x1 v'0 v'1\n          v'5 v'6 v'7 x00 v'11 v'31 v'30 v'29 v'10 v'9 prio v'62 st msg y vhold,\n    RL_RTbl_PrioTbl_P v'13 v'36 vhold->\n    v'12 <> Int.zero ->\n    Int.unsigned v'12 <= 255 ->\n    array_type_vallist_match Int8u v'13 ->\n    length v'13 = ∘OS_EVENT_TBL_SIZE ->\n    nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n    Int.unsigned v'38 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n    Int.unsigned v'69 <= 255 ->\n    nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 = Vptr (v'58, Int.zero)->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    Int.unsigned v'40 <= 128 ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    R_ECB_ETbl_P (v'32, Int.zero)\n                 (V$OS_EVENT_TYPE_Q\n                   :: Vint32 v'12\n                   :: Vint32 v'15 :: Vptr (v'24, Int.zero) :: v'35 :: v'0 :: nil,\n                  v'13) v'7 ->\n    RLH_ECBData_P\n      (DMsgQ (Vptr (v'24, Int.zero))\n             (v'16\n                :: v'18\n                :: v'19\n                :: v'20\n                :: v'34\n                :: Vint32 v'21\n                :: Vint32 v'22 :: Vptr (v'23, Int.zero) :: nil)\n             (v'26 :: v'25 :: nil) v'27) (absmsgq x x0, x1)->\n    ECBList_P v'0 Vnull v'1 v'5 v'6 v'7 ->\n    ECBList_P v'29 (Vptr (v'32, Int.zero)) v'30 v'31 v'9 v'7 ->\n    EcbMod.joinsig (v'32, Int.zero) (absmsgq x x0, x1) v'6 v'10 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg) v'62 v'7 ->\n    R_PrioTbl_P v'36 v'7 vhold ->\n    x1 <> nil ->\n    ECBList_P v'29 Vnull\n              (v'30 ++\n                    ((V$OS_EVENT_TYPE_Q\n                       :: Vint32 y\n                       :: Vint32 v'15 :: Vptr (v'24, Int.zero) :: v'35 :: v'0 :: nil,\n                      update_nth_val (Z.to_nat (Int.unsigned v'38)) v'13\n                                     (Vint32 (v'69&ᵢInt.not v'40))) :: nil) ++ v'1)\n              (v'31 ++\n                    (DMsgQ (Vptr (v'24, Int.zero))\n                           (v'16\n                              :: v'18\n                              :: v'19\n                              :: v'20\n                              :: v'34\n                              :: Vint32 v'21\n                              :: Vint32 v'22 :: Vptr (v'23, Int.zero) :: nil)\n                           (v'26 :: v'25 :: nil) v'27 :: nil) ++ v'5)\n              (EcbMod.set v'11 (v'32, Int.zero)\n                          (absmsgq nil x0, remove_tid (v'58, Int.zero) x1))\n              (TcbMod.set v'7 (v'58, Int.zero)\n                          (prio, rdy , Vptr x00))\n.\nProof.\n  intros.\n  unfolds in H21.\n  destruct H21 as (Ha1 & Ha2 & Ha3).\n  assert ( 0 <= Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39) < 64).\n  clear -H5 H9.\n  mauto.\n  unfold nat_of_Z in Ha1.\n  eapply nth_val'_imp_nth_val_vptr in H10.\n  lets Hps : Ha1 H21 H10.\n  apply tcbjoin_get_a in H20.\n  assert ((v'58, Int.zero) <> vhold) as Hnvhold.\n  apply Ha2 in H20.\n  destruct H20;auto.\n  destruct Hps as (sts & mg & Hget);auto.\n  unfold get in Hget; simpl in Hget.\n  rewrite Hget in H20.\n  inverts H20.\n  remember ((v'38<<ᵢ$ 3)) as px.\n  remember (v'39) as py.\n  clear Heqpy.\n  remember (px+ᵢpy) as prio.\n  remember ( (v'58, Int.zero)) as tid.\n  unfolds in H14.\n  destruct H14 as (Ha & Hb & Hc).\n  destruct Ha as (Ha&Ha'&Ha''&Ha''').\n  destruct Hb as (Hb&Hb'&Hb''&Hb''').\n  lets Hz : math_unmap_get_y H1 H4.\n  lets Heq1 :  math_mapval_core_prop H11; eauto.\n  omega.\n  subst v'40.\n  assert (v'38 = Int.shru prio ($3)).\n  subst.\n  clear -Hz H9.\n  mauto.\n  assert (py = prio &ᵢ $ 7).\n  subst prio. \n  rewrite Heqpx.\n  clear -Hz H9.\n  mauto.\n  rewrite H14 in H6.\n  assert (PrioWaitInQ (Int.unsigned prio) v'13) as Hcp.\n  unfolds.\n  do 3 eexists; splits; eauto.\n  rewrite Int.repr_unsigned.\n  eapply nth_val'_imp_nth_val_int; eauto.\n  rewrite Int.repr_unsigned.\n  rewrite <- H20.\n  unfold Int.one.\n  eapply math_8_255_eq; eauto.\n  \n  unfold Int.zero in H0.\n  rewrite <-H14 in *.\n  lets Hneq :  rl_tbl_grp_neq_zero H1 H0  H4 H6 H13.\n  omega.\n  auto.\n  lets Hecp : Ha Hcp.\n  unfold V_OSEventType in Hecp.\n  simpl nth_val in Hecp.\n  assert (Some (V$OS_EVENT_TYPE_Q) = Some (V$OS_EVENT_TYPE_Q)) by auto.\n  apply Hecp in H23.\n  clear Hecp.\n  rename H23 into Hecp.\n  destruct Hecp as (ct & nl & mg & Hcg).\n  assert (ct = tid) as Hed.\n  assert (ct = tid \\/ ct <> tid)  by tauto.\n  destruct H23; auto.\n  lets Heqs : Ha3 H23 Hcg Hget.\n  rewrite Int.repr_unsigned in Heqs.\n  tryfalse.\n  subst ct.\n  unfold get in Hcg; simpl in Hcg.\n  rewrite Hget in Hcg.\n  inversion Hcg.\n  subst mg st .\n  clear Hcg.\n  \n  lets Hsds : ecb_set_join_join  (absmsgq nil x0, remove_tid tid x1)  H18  H19.\n  destruct Hsds as ( vv & Hsj1 & Hsj2).\n  eapply msgqlist_p_compose.\n  instantiate (1:= (v'32, Int.zero)).\n  unfolds.\n  splits.\n  unfolds.\n  splits;unfolds.\n  \n  introv Hprs Hxx.\n  clear Hxx.\n  apply prio_wt_inq_convert in Hprs.\n  destruct Hprs as (Hprs1 & Hprs2).\n  rewrite H14 in Hprs1.\n  rewrite H20 in Hprs1.\n  lets Hrs : prio_wt_inq_tid_neq  H6 H21 .\n  destruct Hrs as (Hrs & _).\n  apply Hrs in Hprs1.\n  destruct Hprs1 as (Hpq & Hneq).\n  unfolds in Ha.\n  lets Hxs : Ha Hpq.\n  rewrite Int.repr_unsigned in Hxs.\n  destruct Hxs as (tid' & nn & mm & Htg).\n  unfolds;simpl;auto.\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  unfold get in Htg; simpl in Htg.\n  rewrite Hget in Htg.\n  inversion Htg.\n  tryfalse.\n  exists tid' nn mm.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false;eauto.\n\n  intros.\n  unfolds in H25;simpl in H25;tryfalse.\n  intros.\n  unfolds in H25;simpl in H25;tryfalse.\n  intros.\n  unfolds in H25;simpl in H25;tryfalse.\n \n\n\n  unfolds.\n  splits;\n  intros prio' mm nn tid'.\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  unfolds in Hb.\n  lets Hga : Hb Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H23 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n\n  lets Hrs : prio_wt_inq_tid_neq  H6 H21 .\n  destruct Hrs as (_ & Hrs).\n  apply Hrs in H25.\n  rewrite H20.\n  rewrite H14.\n  auto.\n\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  unfolds in Hb'.\n  lets Hga : Hb' Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H23 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n  unfolds in Hx;simpl in Hx;tryfalse.\n\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  unfolds in Hb''.\n  lets Hga : Hb'' Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H23 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n  unfolds in Hx;simpl in Hx;tryfalse.\n\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H23.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  unfolds in Hb'''.\n  lets Hga : Hb''' Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H23 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n  unfolds in Hx;simpl in Hx;tryfalse.\n\n  simpl fst in Hc;simpl;auto.\n  \n  instantiate (1:=v'9).\n  eapply ECBList_P_Set_Rdy_hold;eauto.\n  rewrite Int.repr_unsigned.  \n  eauto.\n  eapply joinsig_join_getnone; eauto.\n  instantiate (1:=v'6).\n  eapply ECBList_P_Set_Rdy_hold;eauto.\n  rewrite Int.repr_unsigned.  \n  eauto.\n  eapply  joinsig_get_none; eauto.\n  unfolds in H15.\n  simpljoin1.\n  unfolds in r.\n  apply r in H22.\n  subst x.\n  instantiate (1:=(absmsgq nil x0, remove_tid tid x1)).\n  splits; auto.\n  unfolds.\n  splits; intros; auto; tryfalse.\n  eapply Hsj1.\n  eapply Hsj2.\nQed.\n\nLemma ecblist_p_post_exwt_hold':\n  forall (v'36 : vallist) (v'12 : int32) (v'13 : vallist)\n         (v'38 v'69 v'39 : int32) (v'58 : block) (v'40 v'41 : int32)\n         (v'32 : block) (v'15 : int32) (v'24 : block)\n         (v'35 v'16 v'18 v'19 v'20 v'34 : val) (v'21 v'22 : int32)\n         (v'23 : block) (v'25 v'26 : val) (v'27 : vallist)\n         (x : list msg) (x0 : maxlen) (x1 : waitset) \n         (v'0 : val) (v'1 : list EventCtr) (v'5 : list EventData)\n         (v'6 : EcbMod.map) (v'7 : TcbMod.map) (x00 : addrval)\n         (v'11 : EcbMod.map) (v'31 : list EventData) \n         (v'30 : list EventCtr) (v'29 : val) (v'10 v'9 : EcbMod.map)\n         (prio : priority) v'62 st msg vhold,\n    RL_RTbl_PrioTbl_P v'13 v'36 vhold->\n    v'12 <> Int.zero ->\n    Int.unsigned v'12 <= 255 ->\n    array_type_vallist_match Int8u v'13 ->\n    length v'13 = ∘OS_EVENT_TBL_SIZE ->\n    nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n    Int.unsigned v'38 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n    Int.unsigned v'69 <= 255 ->\n    nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 = Vptr (v'58, Int.zero)->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    Int.unsigned v'40 <= 128 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) OSMapVallist = Vint32 v'41 ->\n    Int.unsigned v'41 <= 128 ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n    R_ECB_ETbl_P (v'32, Int.zero)\n                 (V$OS_EVENT_TYPE_Q\n                   :: Vint32 v'12\n                   :: Vint32 v'15 :: Vptr (v'24, Int.zero) :: v'35 :: v'0 :: nil,\n                  v'13) v'7 ->\n    RLH_ECBData_P\n      (DMsgQ (Vptr (v'24, Int.zero))\n             (v'16\n                :: v'18\n                :: v'19\n                :: v'20\n                :: v'34\n                :: Vint32 v'21\n                :: Vint32 v'22 :: Vptr (v'23, Int.zero) :: nil)\n             (v'26 :: v'25 :: nil) v'27) (absmsgq x x0, x1)->\n    ECBList_P v'0 Vnull v'1 v'5 v'6 v'7 ->\n    ECBList_P v'29 (Vptr (v'32, Int.zero)) v'30 v'31 v'9 v'7 ->\n    EcbMod.joinsig (v'32, Int.zero) (absmsgq x x0, x1) v'6 v'10 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg) v'62 v'7 ->\n    R_PrioTbl_P v'36 v'7 vhold->\n    x1 <> nil -> \n    ECBList_P v'29 Vnull\n              (v'30 ++\n                    ((V$OS_EVENT_TYPE_Q\n                       :: Vint32 v'12\n                       :: Vint32 v'15 :: Vptr (v'24, Int.zero) :: v'35 :: v'0 :: nil,\n                      update_nth_val (Z.to_nat (Int.unsigned v'38)) v'13\n                                     (Vint32 (v'69&ᵢInt.not v'40))) :: nil) ++ v'1)\n              (v'31 ++\n                    (DMsgQ (Vptr (v'24, Int.zero))\n                           (v'16\n                              :: v'18\n                              :: v'19\n                              :: v'20\n                              :: v'34\n                              :: Vint32 v'21\n                              :: Vint32 v'22 :: Vptr (v'23, Int.zero) :: nil)\n                           (v'26 :: v'25 :: nil) v'27 :: nil) ++ v'5)\n              (EcbMod.set v'11 (v'32, Int.zero)\n                          (absmsgq nil x0, remove_tid (v'58, Int.zero) x1))\n              (TcbMod.set v'7 (v'58, Int.zero)\n                          (prio, rdy , Vptr x00)).\n  Proof.\n    intros.\n    eapply ecblist_p_post_exwt_hold; eauto.\n  Qed.\n\n\nLemma rh_curtcb_set_nct:\n  forall v'8 v'7 x tid ,\n    RH_CurTCB v'8 v'7 ->\n    v'8 <> tid ->\n    RH_CurTCB v'8\n              (TcbMod.set v'7 tid\n                          x).\nProof.\n intros.\n unfolds in H.\n simpljoin1.\n unfolds.\n exists x0 x1 x2.\n rewrite TcbMod.set_sem.\n rewrite tidspec.neq_beq_false; eauto.\nQed.\n\nLemma tidneq_inwt_in:\n  forall  x1 tid tid0,\n    tid <> tid0 ->\n    (In tid0 (remove_tid tid x1) <->\n    In tid0 x1).\nProof.\n  inductions x1.\n  simpl.\n  intros; splits; auto.\n  intros.\n  simpl.\n  splits.\n  intros.\n  simpl in H0.\n  remember (beq_tid tid a) as Hb.\n  destruct Hb.\n  apply eq_sym in HeqHb.\n  apply tidspec.beq_true_eq in HeqHb.\n  subst.\n  right.\n  eapply IHx1; eauto.\n  simpl in H0.\n  destruct H0; auto.\n  right.\n  apply eq_sym in HeqHb.\n  apply tidspec.beq_false_neq in HeqHb.\n  eapply IHx1; eauto.\n  intros.\n  destruct H0.\n  subst.\n  rewrite tidspec.neq_beq_false; auto.\n  simpl.\n  left; auto.\n  remember (beq_tid tid a) as Hb.\n  destruct Hb.\n  apply eq_sym in HeqHb.\n  apply tidspec.beq_true_eq in HeqHb.\n  subst.\n  eapply IHx1; eauto.\n  simpl.\n  right.\n  eapply IHx1; eauto.\nQed.\n\n\nLemma  tid_in_rmwt_in :\n  forall x1 tid,\n    In tid (remove_tid tid x1) ->\n    In tid x1.\nProof.\n  inductions x1.\n  simpl.\n  intros; auto.\n  simpl.\n  intros.\n  remember (beq_tid tid a) as Hb.\n  destruct Hb.\n  apply eq_sym in HeqHb.\n  apply tidspec.beq_true_eq in HeqHb.\n  left; auto.\n  simpl in H.\n  destruct H.\n  left; auto.\n  right; apply IHx1; auto.\nQed.\n\n\n\nLemma in_wtset_rm_notin:\n  forall x1 tid,\n    In tid x1 ->\n    ~ In tid (remove_tid tid x1).\nProof.\n  inductions x1.\n  simpl.\n  intros; tryfalse.\n  simpl.\n  intros.\n  destruct H.\n  subst.\n  intro Hf.\n  rewrite tidspec.eq_beq_true in Hf; auto.\n  eapply IHx1; eauto.\n  apply tid_in_rmwt_in; auto.\n  apply IHx1 in H.\n  introv Hf.\n  apply H.\n  remember (beq_tid tid a) as Hb.\n  destruct Hb.\n  auto.\n  apply eq_sym in HeqHb.\n  simpl in Hf.\n  apply tidspec.beq_false_neq in HeqHb.\n  destruct Hf.\n  tryfalse.\n  auto.\nQed.\n\n\n\nLemma rh_tcblist_ecblist_p_post_exwt:\n  forall v'8 tid v'11 v'7 v'9 v'10 eid x x0 x1 v'6 prio  msg x00 xl,\n    RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    EcbMod.joinsig eid (absmsgq x x0, x1) v'6 v'10 ->\n    In tid x1 ->\n    TcbMod.get v'7 tid = Some (prio,  wait (os_stat_q eid) xl, msg) ->\n    RH_TCBList_ECBList_P\n      (EcbMod.set v'11 eid\n                  (absmsgq nil x0, remove_tid tid x1))\n      (TcbMod.set v'7 tid\n                  (prio, rdy , Vptr x00)) v'8.\nProof.\n  intros.\n  unfolds.\n  splits.\n  splits; intros.\n  destruct H4.\n  unfolds in H.\n  destruct H as (H&Hx).\n  destruct H.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H7.\n  subst.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  assert (EcbMod.get v'11 eid = Some (absmsgq x x0, x1)/\\ In tid0 x1 ).\n  splits; auto.\n  lets Hsa : H H7.\n  simpljoin1.\n  unfold get in H8; simpl in H8.\n  rewrite H3 in H8.\n  inverts H8.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H8.\n  subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n  apply  in_wtset_rm_notin in H9.\n  tryfalse.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert (EcbMod.get v'11 eid0 = Some (absmsgq x2 y, qwaitset) /\\ In tid0 qwaitset ).\n  splits; auto.\n  lets Hsc : H H13.\n  simpljoin1.\n  unfold get in H14; simpl in H14.\n  rewrite H3 in H14.\n  inverts H14.\n  tryfalse.\n  rewrite TcbMod.set_sem .\n  rewrite tidspec.neq_beq_false; auto.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H8.\n  subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n  lets Hbss :tidneq_inwt_in  x1 H7.\n  destruct Hbss as (Hbss & _).\n  lets Hbssc : Hbss H5.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  assert ( EcbMod.get v'11 eid0 = Some (absmsgq x y, x1) /\\ In tid0 x1 ).\n  splits; auto.\n  apply H in H4.\n  simpljoin1.\n  do 3 eexists; eauto.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert ( EcbMod.get v'11 eid0 = Some (absmsgq x2 y, qwaitset)/\\ In tid0 qwaitset ).\n  splits; auto.\n  apply H in H9.\n  simpljoin1.\n  do 3 eexists; eauto .\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H5.\n  subst.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  \n  unfolds in H.\n  destructs H.\n  destruct H.\n  apply H9 in H4.\n  simpljoin1.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H11.\n  subst.\n  unfold get in H4; simpl in H4.\n  rewrite H4 in Hget.\n  inverts Hget.\n  lets Hbss :tidneq_inwt_in  x1 H5.\n  destruct Hbss as (_ & Hbss).\n  lets Hbssc : Hbss H10.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.eq_beq_true; auto.\n  do 3 eexists; splits; eauto.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists; splits; eauto.\n\n\n  splits; intros.\n  destruct H4.\n  unfolds in H.\n  destruct H as (Hh&H&Hx).\n  destruct H.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H7;subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  tryfalse.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert (EcbMod.get v'11 eid0 = Some (abssem n, wls) /\\ In tid0 wls).\n  split;auto.\n  apply H in H8.\n  simpljoin1.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H11;subst.\n  unfold get in H8; simpl in H8.\n  rewrite H3 in H8;tryfalse.\n  do 3 eexists.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  eauto.\n\n  unfolds in H.\n  destruct H as (Hh&H&Hx).\n  destruct H.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H6;subst.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  apply H5 in H4.\n  simpljoin1.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H10;subst.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  unfold get in H4; simpl in H4.\n  rewrite H4 in Hget;tryfalse.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 2 eexists;split;eauto.\n\n  \n  splits; intros.\n  destruct H4.\n  unfolds in H.\n  destruct H as (Hh&Hhh&H&Hx).\n  destruct H.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H7;subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  tryfalse.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert (EcbMod.get v'11 eid0 = Some (absmbox n, wls) /\\ In tid0 wls).\n  split;auto.\n  apply H in H8.\n  simpljoin1.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H9;subst.\n  unfold get in H8; simpl in H8.\n  rewrite H3 in H8;tryfalse.\n  do 3 eexists.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  eauto.\n\n  unfolds in H.\n  destruct H as (Hh&Hhh&H&Hx).\n  destruct H.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H6;subst.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  apply H5 in H4.\n  simpljoin1.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H8;subst.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  unfold get in H4; simpl in H4.\n  rewrite H4 in Hget;tryfalse.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 2 eexists;split;eauto.\n\n   \n  splits; intros.\n  destruct H4.\n  unfolds in H.\n  destruct H as (Hh&Hhh&Hx&H).\n  destruct H.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H7;subst.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  tryfalse.\n  rewrite EcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  assert (EcbMod.get v'11 eid0 = Some (absmutexsem n1 n2, wls) /\\ In tid0 wls).\n  split;auto.\n  apply H in H8.\n  simpljoin1.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H10;subst.\n  unfold get in H8; simpl in H8.\n  rewrite H3 in H8;tryfalse.\n  do 3 eexists.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  eauto.\n\n  unfolds in H.\n  destruct H as (Hh&Hx&Hhh&H).\n  destruct H.\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H6;subst.\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.eq_beq_true in H4; auto.\n  inverts H4.\n\n  rewrite TcbMod.set_sem in H4.\n  rewrite tidspec.neq_beq_false in H4; auto.\n  apply H5 in H4.\n  simpljoin1.\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H9;subst.\n  apply ecbmod_joinsig_get in H1.\n  lets Hget : EcbMod.join_get_get_r H0 H1.\n  unfold get in H4; simpl in H4.\n  rewrite H4 in Hget;tryfalse.\n  rewrite EcbMod.set_sem.\n  rewrite tidspec.neq_beq_false; auto.\n  do 3 eexists;split;eauto.\n\n  unfolds in H.\n  destructs H.\n  clear H H4 H5.\n  elim H6; intros.\n  unfold RH_TCBList_ECBList_MUTEX_OWNER in *.\n  destruct H4 as (Hx&H4).\n  intros.\n\n  assert (eid = eid0 \\/ eid <> eid0) by tauto.\n  destruct H7; intros.\n  subst eid.\n  rewrite EcbMod.set_a_get_a in H5.\n  inversion H5.\n  apply CltEnvMod.beq_refl.\n  rewrite EcbMod.set_a_get_a' in H5.\n  2:apply tidspec.neq_beq_false; auto.\n\n  assert (tid = tid0 \\/ tid <> tid0) by tauto.\n  destruct H8.\n  subst.\n  rewrite TcbMod.set_a_get_a.\n  do 3 eexists;eauto.\n  apply CltEnvMod.beq_refl.\n  rewrite TcbMod.set_a_get_a'.\n  2:apply tidspec.neq_beq_false; auto.\n  eapply H4;eauto.\nQed.\n\n\nLemma qpost_ovf_prop:\n  forall i2 i1 x13 x12 x6 x7 x8 v'49 v'47 x14 x15 x x1 x2 v2,\n    true = Int.ltu i2 i1 ->\n    WellformedOSQ\n      (x13\n         :: x12\n         :: x6\n         :: x7\n         :: x8\n         :: Vint32 i2\n         :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil) -> \n    RLH_ECBData_P\n      (DMsgQ (Vptr (v'47, Int.zero))\n             (x13\n                :: x12\n                :: x6\n                :: x7\n                :: x8\n                :: Vint32 i2\n                :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil)\n             (x14 :: x15 :: nil) v2)  (absmsgq x x1, x2) ->\n    Z.ge (Z_of_nat (length x)) (Int.unsigned x1).\nProof.\n  introv Hlt Hwl Hr.\n  funfold Hwl.\n  funfold Hr.\n  funfold H0.\n  assert (  Z.of_nat (length x) = Int.unsigned x0) by auto.\n  rewrite H0.\n  unfold qend_right, arrayelem_addr_right in *.\n  simpljoin1.\n  unfold ptr_offset_right, ptr_minus in *.\n  destruct x3.\n  destruct x10.\n  destruct x5.\n  fsimpl.\n  funfold H.\n  funfold H1.\n  clear - Hlt.\n  int auto.\nQed.\n\nLemma qpost_ovf_prop':\n  forall i2 i1 x13 x12 x6 x7 x8 v'49 v'47 x14 x15 x x1 x2 v2,\n    true = Int.eq i1 i2 ->\n    WellformedOSQ\n      (x13\n         :: x12\n         :: x6\n         :: x7\n         :: x8\n         :: Vint32 i2\n         :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil) -> \n    RLH_ECBData_P\n      (DMsgQ (Vptr (v'47, Int.zero))\n             (x13\n                :: x12\n                :: x6\n                :: x7\n                :: x8\n                :: Vint32 i2\n                :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil)\n             (x14 :: x15 :: nil) v2)  (absmsgq x x1, x2) ->\n    Z.ge (Z_of_nat (length x)) (Int.unsigned x1).\nProof.\n  introv Hlt Hwl Hr.\n  funfold Hwl.\n  funfold Hr.\n  funfold H0.\n  assert (  Z.of_nat (length x) = Int.unsigned x0) by auto.\n  rewrite H0.\n  unfold qend_right, arrayelem_addr_right in *.\n  simpljoin1.\n  unfold ptr_offset_right, ptr_minus in *.\n  destruct x3.\n  destruct x10.\n  destruct x5.\n  fsimpl.\n  funfold H.\n  funfold H1.\n  clear - Hlt.\n  int auto.\nQed.\n\nLemma osq_same_blk_st_in':\n  forall (qptr qst qend qin qout qsz qen : val) (b : block) (i : int32),\n    WellformedOSQ\n      (qptr :: qst :: qend :: qin :: qout :: qsz :: qen :: Vptr (b, i) :: nil) ->\n    exists i', qin = Vptr (b, i').\nProof.\n  intros.\n  funfold H.\n  funfold H9.\n  funfold H8.\n  funfold H3.\n   unfolds in H10.\n  simpljoin1.\n  unfold ptr_minus in *.\n  unfold ptr_offset_right in *.\n  fsimpl.\n  simpl in H5.\n  inverts H5.\n  eexists; eauto.\nQed.\n\n\nLemma wellq_in_props:\n  forall (x12 x11 x5 x6 : val) (v'49 : block) (x i2 i1 : int32)\n         (v'47 : block) (x13 x14 : val) (v2 : list val) \n         (v'46 : absecb.B),\n    length v2 = ∘OS_MAX_Q_SIZE ->\n    RLH_ECBData_P\n      (DMsgQ (Vptr (v'47, Int.zero))\n             (x12\n                :: x11\n                :: x5\n                :: Vptr (v'49, x)\n                :: x6\n                :: Vint32 i2 :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil)\n             (x13 :: x14 :: nil) v2) v'46 ->\n    WellformedOSQ\n      (x12\n         :: x11\n         :: x5\n         :: Vptr (v'49, x)\n         :: x6\n         :: Vint32 i2 :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil) ->\n    Int.unsigned (Int.zero+ᵢ($ 4+ᵢInt.zero)) <= Int.unsigned x /\\\n    4 * ((Int.unsigned x - Int.unsigned (Int.zero+ᵢ($ 4+ᵢInt.zero))) / 4) =\n    Int.unsigned x - Int.unsigned (Int.zero+ᵢ($ 4+ᵢInt.zero)) /\\\n    (Int.unsigned x - Int.unsigned (Int.zero+ᵢ($ 4+ᵢInt.zero))) / 4 < 20 /\\\n    (Int.unsigned x - Int.unsigned (Int.zero+ᵢ($ 4+ᵢInt.zero))) / 4 <\n    Z.of_nat (length v2).\nProof.\n  introv Hlen Hrl  Hwf.  \n  assert (auxand (Int.unsigned (Int.zero+ᵢ($ 4+ᵢInt.zero)) <= Int.unsigned x)\n                 (4 * ((Int.unsigned x - Int.unsigned (Int.zero+ᵢ($ 4+ᵢInt.zero))) / 4) =\n                  Int.unsigned x - Int.unsigned (Int.zero+ᵢ($ 4+ᵢInt.zero)) /\\\n                  (Int.unsigned x - Int.unsigned (Int.zero+ᵢ($ 4+ᵢInt.zero))) / 4 < 20 /\\\n                  (Int.unsigned x - Int.unsigned (Int.zero+ᵢ($ 4+ᵢInt.zero))) / 4 <\n                  Z.of_nat (length v2)\n                 )).\n  funfold Hwf.\n  unfold arrayelem_addr_right, qend_right  in *.\n  unfold  ptr_offset_right, ptr_minus in *.\n  simpljoin1.\n  fsimpl.\n  simpl in H7.\n  subst i.\n  simpl in H13, H12,H10.\n  clear H5.\n  assert (Int.zero+ᵢ($ 4+ᵢInt.zero) = $4) as Heq.\n  clear -x.\n  mauto.\n  rewrite Heq in *.\n  clear Heq.\n  unfolds in Hrl.\n  destruct v'46. \n  destruct e; tryfalse.\n  splits.\n  clear - H.\n  int auto.\n  apply eq_sym.\n  eapply Z_div_exact_2; try omega.\n  eapply math_prop_int_modu; eauto.\n  eapply math_prop_ltu_20; eauto.\n  rewrite Hlen.\n  unfold OS_MAX_Q_SIZE.\n  simpl.\n  eapply math_prop_ltu_20; eauto.\n  auto.\nQed.\n\n\nLemma wellformedosq_size_add_1:\n  forall x13 x12 x6 v'49 x x8 i2 i1,\n    WellformedOSQ\n      (x13\n         :: x12\n         :: x6\n         :: Vptr (v'49, x)\n         :: x8\n         :: Vint32 i2\n         :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil) -> Int.unsigned (i2+ᵢ$ 1) <= Int16.max_unsigned.\nProof.\n  introv Hwl.\n  funfold Hwl.\n  unfold qend_right, arrayelem_addr_right in *.\n  simpljoin1.\n  unfold ptr_offset_right, ptr_minus in *.\n  destruct x1.\n  destruct x3.\n  destruct x5.\n  fsimpl.\n  clear - H11.\n  unfold OS_MAX_Q_SIZE in *.\n  unfold Int16.max_unsigned.\n  unfold Int16.modulus.\n  simpl.\n  int auto.\n  int auto.\nQed.\n\n\nLemma wellformedosq_ens_add_1:\n  forall x13 x12 x6 v'49 x x8 i2 i1 x10 x11 v'46 v2 v'36,\n    length v2 = ∘OS_MAX_Q_SIZE ->\n    RLH_ECBData_P\n         (DMsgQ (Vptr (v'36, Int.zero))\n                (x13\n                   :: x12\n                   :: x6\n                   :: Vptr (v'49, x)\n                   :: x8\n                   :: Vint32 i2\n                   :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil)\n            (x10 :: x11 :: nil) v2) v'46 ->\n    WellformedOSQ\n      (x13\n         :: x12\n         :: x6\n         :: Vptr (v'49, x)\n         :: x8\n         :: Vint32 i2\n         :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil) -> Int.unsigned (i1+ᵢ$ 1) <= Int16.max_unsigned.\nProof.\n  introv Ha Hlh Hwf.\n  funfold Hwf.\n  unfolds in Hlh.\n  destruct v'46.\n  destruct e;tryfalse.\n  simpljoin1.\n  unfold qend_right, arrayelem_addr_right in *.\n  simpljoin1.\n  unfold ptr_offset_right,  ptr_minus in *.\n  fsimpl.\n  funfold H.\n  simpl in H17, H16 , H15 , H5.\n  inverts H5.\n  assert ( (Int.zero+ᵢ($ 4+ᵢInt.zero))  = $4).\n  clear -x.\n  mauto.\n  rewrite H in *.\n  funfold H0.\n  funfold H1.\n  unfold distance in *.\n  simpl in H22, H24, H25.\n  rewrite Int.repr_unsigned in *.\n  clear H.\n  remember ( ((Int.unsigned (Int.divu (x-ᵢ$ 4) ($ 4))) )) as M.\n  remember ( Int.unsigned (Int.divu (i0-ᵢ$ 4) ($ 4))) as N.\n  assert (M = N \\/ M > N \\/ M < N).\n  clear -x.\n  omega.\n  destruct H as [Ha1 | [Ha2 | Ha3]].\n  apply H25 in Ha1.\n  destruct Ha1.\n  simpljoin1.\n  pose (Int.eq_spec x0 Int.zero) as Hps.\n  rewrite H in Hps.\n  subst.\n  clear -x.\n  mauto.\n  simpljoin1.\n  pose (Int.eq_spec x0 m) as Hps.\n  rewrite H in Hps.\n  subst x0.\n  clear - H11.\n  unfold OS_MAX_Q_SIZE in H11.\n  unfold  Int16.max_unsigned.\n  simpl.\n  mauto.\n  lets Hzs : H22 Ha2.\n  eapply vallist_seg_length_prop in Hzs.\n  rewrite Hzs in H5.\n  eapply math_MN_le_int16; eauto.\n  eapply math_MN_le_max; eauto.\n  rewrite Ha.\n  eapply math_MN_le_max; eauto.\n  lets Hasb : H24 Ha3.\n  remember (vallist_seg ∘N ∘(Int.unsigned m) v2) as l1.\n  eapply eq_sym in Heql1.\n  eapply vallist_seg_length_prop in Heql1.\n  remember (vallist_seg 0 ∘M v2) as l2.\n  eapply eq_sym in Heql2.\n  eapply vallist_seg_length_prop in Heql2.\n  assert (length (l1 ++ l2) = length l )%nat.\n  rewrite Hasb.\n  auto.\n  rewrite app_length in H.\n  rewrite Heql1 in H; rewrite Heql2 in H.\n  assert (length l < ∘(Int.unsigned m))%nat.\n  assert (∘M < ∘N)%nat.\n  unfold nat_of_Z.\n  eapply Z2Nat.inj_lt.\n  subst M.\n  apply Int.unsigned_range.\n  subst N.\n  apply Int.unsigned_range.\n  auto.\n  clear - H9 H12 H H0.\n  omega.\n  eapply math_le_int16; eauto.\n  clear -x.\n  omega.\n  rewrite Ha.\n  eapply math_MN_max_prop; eauto.\n  eapply math_MN_max_prop; eauto.\n  rewrite Ha.\n  eapply math_MN_max_prop; eauto.\nQed.\n\n\n\nLemma rlh_ecb_nowait_prop:\n  forall v'25 i i3 v'47 x4 v'42 v'40 v'35 v'34 x1 x2 x3 v'37,\n    RL_Tbl_Grp_P v'40 (Vint32 i)->\n    R_ECB_ETbl_P (v'25, Int.zero)\n                 (V$OS_EVENT_TYPE_Q\n                   :: Vint32 i\n                   :: Vint32 i3 :: Vptr (v'47, Int.zero) :: x4 :: v'42 :: nil,\n                  v'40) v'35 ->\n    EcbMod.get v'34 (v'25, Int.zero) = Some (absmsgq x1 x2, x3) ->\n    RH_TCBList_ECBList_P v'34 v'35 v'37 ->\n    Int.eq i ($ 0) = true ->\n    x3 = nil.\nProof.\n  introv Hrl Hre Hecb Hrh Heq.\n  pose (Int.eq_spec i ($0)) as Hps.\n  rewrite Heq in Hps.\n  subst i.\n  clear Heq.\n  simpljoin1.\n  unfolds in Hrh.\n  destruct Hrh as (Hrh&_).\n  unfolds in Hre.\n  destruct Hre as (Hre1 & Hre2 &_).\n  unfolds in Hre1.\n  destruct Hre1 as (Hre1 & _).\n  destruct Hre2 as (Hre2 & _).\n  unfolds in Hre1.\n  unfolds in Hre2.\n  assert (x3 = nil \\/ x3 <> nil) by tauto.\n  destruct H; auto.\n  destruct x3.\n  tryfalse.\n  unfolds in Hrh.\n  destruct Hrh as (Hrh &_).\n  assert (In t (t::x3)).\n  simpl.\n  left; auto.\n\n  assert ( EcbMod.get v'34 (v'25, Int.zero) = Some (absmsgq x1 x2, t :: x3)/\\ In t (t :: x3)).\n  split; auto.\n  apply Hrh in H1.\n  simpljoin1.\n  apply Hre2 in H1.\n  simpljoin1.\n\n  unfolds in H1.\n  simpljoin1.\n  unfolds in Hrl.\n  rewrite Int.repr_unsigned in H5.\n  assert (0<=∘(Int.unsigned (Int.shru x ($ 3)))<8)%nat.\n  clear - H7.\n  mauto.\n  assert (V$0 = V$0) by auto.\n  lets Habb : Hrl H3 H5 H4.\n  simpljoin1.\n  rewrite Int.and_commut in H8.\n  rewrite Int.and_zero in H8.\n  assert (x8 = $0).\n  apply H8; auto.\n  subst x8.\n  rewrite Int.and_commut in H6.\n  rewrite Int.and_zero in H6.\n  rewrite Int.repr_unsigned in H6.\n  assert ( $1<<ᵢ(x&ᵢ$ 7) <> $ 0).\n  eapply   math_prop_neq_zero2;omega.\n  unfold Int.zero in H6.\n  unfold Int.one in H6.\n  tryfalse.\nQed.\n\n\n\n\nLemma qpost_no_wait_prop':\n  forall i2 i1 x13 x12 x6 x7 x8 v'49 v'47 x14 x15 x x1 x2 v2,\n    Int.ltu i1 i2 = true ->\n    WellformedOSQ\n      (x13\n         :: x12\n         :: x6\n         :: x7\n         :: x8\n         :: Vint32 i2\n         :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil) -> \n    RLH_ECBData_P\n      (DMsgQ (Vptr (v'47, Int.zero))\n             (x13\n                :: x12\n                :: x6\n                :: x7\n                :: x8\n                :: Vint32 i2\n                :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil)\n             (x14 :: x15 :: nil) v2)  (absmsgq x x1, x2) ->\n    Z.of_nat (length x) < (Int.unsigned x1) .\nProof.\nintrov Hlt Hwl Hr.\n  funfold Hwl.\n  funfold Hr.\n  funfold H0.\n  assert (  Z.of_nat (length x) = Int.unsigned x0) by auto.\n  rewrite H0.\n  unfold qend_right, arrayelem_addr_right in *.\n  simpljoin1.\n  unfold ptr_offset_right, ptr_minus in *.\n  destruct x3.\n  destruct x10.\n  destruct x5.\n  fsimpl.\n  funfold H.\n  funfold H1.\n  clear - Hlt.\n  int auto.\nQed.\n\n\nLemma get_wellformedosq_in_setst:\n  forall i1 i2 x13 x12 x6 v'49 x x8,\n    Int.ltu i1 i2 = true ->\n    WellformedOSQ\n      (x13\n         :: x12\n         :: x6\n         :: Vptr (v'49, x)\n         :: x8\n         :: Vint32 i2\n         :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil) ->\n    val_inj\n      match x6 with\n        | Vundef => None\n        | Vnull => Some (Vint32 Int.zero)\n        | Vint32 _ => None\n        | Vptr (b2, ofs2) =>\n          if peq v'49 b2\n          then\n            if Int.eq (x+ᵢInt.mul ($ 1) ($ 4)) ofs2\n            then Some (Vint32 Int.one)\n            else Some (Vint32 Int.zero)\n          else Some (Vint32 Int.zero) \n      end <> Vint32 Int.zero ->\n    WellformedOSQ\n      (x13\n         :: x12\n         :: x6\n         :: x12\n         :: x8\n         :: Vint32 i2\n         :: Vint32 (i1+ᵢ$ 1) :: Vptr (v'49, Int.zero) :: nil).\nProof.\n  introv Hlt Hvl Hj.\n  funfold Hvl.\n  unfold qend_right, arrayelem_addr_right in *.\n  simpljoin1.\n  unfold ptr_offset_right, ptr_minus in *.\n  destruct x1.\n  destruct x3.\n  destruct x5.\n  fsimpl.\n  rewrite peq_true in Hj.\n  remember (Int.eq (x+ᵢInt.mul ($ 1) ($ 4)) i) as Hb.\n  destruct Hb; simpl in Hj; tryfalse.\n  apply eq_sym in HeqHb.\n  pose ( Int.eq_spec (x+ᵢInt.mul ($ 1) ($ 4)) i ) as Hpx. \n  rewrite HeqHb in Hpx.\n  subst i.\n  simpl in H7.\n  subst.\n  simpl in H5.\n  assert ( Int.zero+ᵢ($ 4+ᵢInt.zero) = $ 4) as Hx. \n  clear -x.\n  int auto.\n  int auto.\n  rewrite Hx in *.\n  assert (Int.mul ($ 1) ($ 4) = $ 4) as Hy.\n  clear -x.\n  int auto.\n  rewrite Hy in *.\n  simpl in *.\n  do 7 eexists; splits; try solve [unfolds; simpl; eauto].\n  splits; eauto.\n  unfolds.\n  splits; simpl; eauto.\n  rewrite Pos2Z.inj_eqb .\n  rewrite Z.eqb_refl.\n  splits; auto.\n  rewrite Pos2Z.inj_eqb .\n  rewrite Z.eqb_refl.\n  auto.\n  unfolds.\n  eexists.\n  unfold ptr_offset_right, ptr_minus in *.\n  rewrite Pos2Z.inj_eqb .\n  rewrite Z.eqb_refl.\n  splits; eauto.\n  simpl.\n  assert (Int.divu ($ 4-ᵢ$ 4) ($ 4) = $0).\n  clear -x.\n  mauto.\n  rewrite H1.\n  rewrite Int.unsigned_repr.\n  eapply Z2Nat.inj_lt;omega.\n  clear -x.\n  int auto.\n  unfolds.\n  unfold ptr_offset_right, ptr_minus in *.\n  rewrite Pos2Z.inj_eqb .\n  rewrite Z.eqb_refl.\n  eexists;  splits; eauto.\nQed.\n\n\nLemma msgqlist_p_compose'\n: forall (p : val) (qid : addrval) (mqls : EcbMod.map)\n         (qptrl1 qptrl2 : list EventCtr) (i i1 : int32) \n         (a : addrval) (x3 p' : val) (v'41 : vallist)\n         (msgqls1 msgqls2 : list EventData) (msgq : EventData)\n         (mqls1 mqls2 : EcbMod.map) (mq : absecb.B) \n         (mqls' : EcbMod.map) (tcbls : TcbMod.map),\n    R_ECB_ETbl_P qid\n                 (V$OS_EVENT_TYPE_Q\n                   :: Vint32 i :: Vint32 i1 :: Vptr a :: x3 :: p' :: nil, v'41) tcbls ->\n    ECBList_P p (Vptr qid) qptrl1 msgqls1 mqls1 tcbls ->\n    ECBList_P p' Vnull qptrl2 msgqls2 mqls2 tcbls ->\n    RLH_ECBData_P msgq mq ->\n    EcbMod.joinsig qid mq mqls2 mqls' ->\n    EcbMod.join mqls1 mqls' (EcbMod.set mqls qid mq) ->\n    ECBList_P p Vnull\n              (qptrl1 ++\n                      ((V$OS_EVENT_TYPE_Q\n                         :: Vint32 i :: Vint32 i1 :: Vptr a :: x3 :: p' :: nil, v'41)\n                         :: nil) ++ qptrl2) (msgqls1 ++ (msgq :: nil) ++ msgqls2) (EcbMod.set mqls qid mq)\n              tcbls.\nProof.\n  intros.\n  eapply msgqlist_p_compose;eauto.\nQed.\n\n\n\n\n\n\nLemma rlh_ecbdata_in_end:\n  forall i1 i2 x13 x12 v'49 x x8 v'47 x14 x15 v2 x1 x2 x0,\n    Int.ltu i1 i2 = true ->\n    length v2 = ∘OS_MAX_Q_SIZE ->\n    WellformedOSQ\n      (x13\n         :: x12\n         :: Vptr (v'49, (x+ᵢInt.mul ($ 1) ($ 4)) )\n         :: Vptr (v'49, x)\n         :: x8\n         :: Vint32 i2\n         :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil) ->\n    RLH_ECBData_P\n      (DMsgQ (Vptr (v'47, Int.zero))\n             (x13\n                :: x12\n                :: Vptr (v'49, (x+ᵢInt.mul ($ 1) ($ 4)) )\n                :: Vptr (v'49, x)\n                :: x8\n                :: Vint32 i2\n                :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil)\n             (x14 :: x15 :: nil) v2) (absmsgq x1 x2, nil) ->\n    RLH_ECBData_P\n      (DMsgQ (Vptr (v'47, Int.zero))\n             (x13\n                :: x12\n                :: Vptr (v'49, x+ᵢInt.mul ($ 1) ($ 4))\n                :: x12\n                :: x8\n                :: Vint32 i2\n                :: Vint32 (i1+ᵢ$ 1) :: Vptr (v'49, Int.zero) :: nil)\n             (x14 :: x15 :: nil)\n             (update_nth_val\n                (Z.to_nat\n                   ((Int.unsigned x - Int.unsigned (Int.zero+ᵢ($ 4+ᵢInt.zero))) /\n                                                                                4)) v2 (Vptr x0))) (absmsgq (x1 ++ (Vptr x0::nil)) x2, nil).\nProof.\n  introv Hi Hlen Hw Hr.\n  funfold Hw.\n  unfold qend_right, arrayelem_addr_right in *.\n  unfold ptr_offset_right,   ptr_minus  in *.\n  fsimpl.\n  simpl in H1.\n  subst i.\n  simpl in H5.\n  inverts H5.\n  assert (Int.mul ($ 1) ($ 4) = $ 4).\n  clear -b.\n  mauto.\n  rewrite H1 in *.\n  simpl in H13, H12, H10.\n  unfolds in Hr.\n  destruct Hr as (Hm1 & Hm2 & Hm3 & Hm4).\n  funfold Hm1.\n  funfold Hm2.\n  funfold Hm3.\n  unfold distance in *.\n  rewrite Int.repr_unsigned in *.\n  simpl in H18 , H20 ,  H21.\n  unfolds.\n  splits.\n  unfolds.\n  assert (Int.unsigned (Int.divu ($ 4-ᵢ$ 4) ($ 4)) = 0).\n  clear -x.\n  repeat progress (int auto);simpl;\n  try    rewrite Zdiv_0_l;omega.\n  assert ((Int.zero+ᵢ($ 4+ᵢInt.zero)) = $ 4).\n  clear -x.\n  mauto.\n  assert (Int.unsigned ($ 4) = 4).\n  clear -x.\n  int auto.\n  do 7 eexists; splits; try solve [unfolds; simpl; eauto].\n  rewrite H3 in *.\n  clear H3.\n  rewrite H5 in *.\n  rewrite H16 in *.\n  lets Heq : math_le_xyz  H11 H H12 H0 H15; eauto.\n  rewrite Int.repr_unsigned; auto.\n  rewrite H16 in *.\n  destruct Heq as (Hle & Hse & He).    \n  assert ( Int.unsigned (Int.divu (x-ᵢ$ 4) ($ 4)) >  Int.unsigned (Int.divu (i0-ᵢ$ 4) ($ 4)) \\/\n           Int.unsigned (Int.divu (x-ᵢ$ 4) ($ 4)) =  Int.unsigned (Int.divu (i0-ᵢ$ 4) ($ 4))) by omega.\n  destruct H3 as [Ha1 | Ha2].\n  lets Hres : H18 Ha1.\n  remember ( ∘(Int.unsigned (Int.divu (i0-ᵢ$ 4) ($ 4)))) as M.\n  remember (∘(Int.unsigned (Int.divu (x-ᵢ$ 4) ($ 4)))) as N.\n  rewrite  <- He.\n  splits.\n  splits.\n  intros.\n  assert (0<=Int.unsigned (Int.divu (i0-ᵢ$ 4) ($ 4))).\n  apply Int.unsigned_range.\n  omega.\n  intros.\n  rewrite <- Hse.\n  lets Heqs : math_le_max_q H11 H9 Hse.\n  destruct Heqs as (Hs1 & Hs2).\n  lets Has : vallist_seg_upd_prop (Vptr x0) Hres. \n  rewrite Hlen.\n  auto.\n  auto.\n  rewrite Has.\n  unfold vallist_seg.\n  simpl.\n  rewrite app_nil_r.\n  auto.\n  intros.\n  right.\n  lets Heqs : math_le_max_q H11 H9 Hse.\n  destruct Heqs as (Hs1 & Hs2).\n  lets Has : vallist_seg_upd_prop (Vptr x0) Hres. \n  rewrite Hlen.\n  auto.\n  auto.\n  rewrite <- Hse.\n  rewrite Has.\n  lets Hcs : math_len_le_and (Vptr x0) Hlen H11 H9 Hse.\n  destruct Hcs as (Hcs1 & Hcs2).\n  split.\n  lets Hsss : vallist_seg_length_prop Has.\n  auto.\n  auto.\n  rewrite <- H3 in *.\n  subst M.\n  rewrite app_length in Hsss.\n  simpl in Hsss.\n  eapply math_length_int_eq; eauto.\n  unfold vallist_seg.\n  simpl.\n  rewrite app_nil_r.\n  auto.\n  eapply isptr_list_tail_add;eauto.\n  lets Heqs : H21 Ha2.\n  rewrite <- He.\n  rewrite Ha2.\n  remember ( ∘(Int.unsigned (Int.divu (i0-ᵢ$ 4) ($ 4)))) as M.\n  splits.\n  splits.\n  assert (0<=Int.unsigned (Int.divu (i0-ᵢ$ 4) ($ 4))).\n  apply Int.unsigned_range.\n  intros.\n  clear - H3 H17.\n  omega.\n  intros.  \n  rewrite <- Hse.\n  rewrite Ha2.\n  rewrite <-HeqM.\n  destruct Heqs.\n  destruct H17.\n  subst x1.\n  simpl.\n  rewrite  vallist_seg_upd_SM.\n  unfold vallist_seg;simpl.\n  auto.\n  rewrite Hlen.\n  eapply math_max_le_q; eauto.\n  destruct H17.\n  eapply ltu_eq_false in Hi.\n  rewrite  Int.eq_sym in Hi.\n  rewrite Hi in H17.\n  inverts H17.\n  introv Hz.\n  rewrite <- Hz in *.\n  right. \n  rewrite <- Hse.\n  rewrite Ha2.\n  rewrite HeqM.\n  destruct Heqs.\n  destruct H3.\n  subst x1.\n  rewrite  vallist_seg_upd_SM.\n  unfold vallist_seg;simpl.\n  splits.\n  eapply math_length_int_eq; eauto.\n  simpl.\n  rewrite Ha2 in Hse.\n  simpl in Hse.\n  rewrite <- Hse.\n  auto.\n  auto.\n  rewrite Hlen.\n  simpl.\n  unfold Pos.to_nat;simpl; omega.\n  destruct H3 as (Hfs &_).\n  eapply ltu_eq_false in Hi.\n  rewrite Int.eq_sym in Hi.\n  rewrite Hi in Hfs.\n  inverts Hfs.\n  eapply isptr_list_tail_add;eauto.\n  unfolds.\n  eexists.\n  splits.\n  unfolds; simpl; eauto.\n  rewrite app_length.\n  simpl.\n  eapply  math_inc_eq_ltu; eauto.\n  unfolds.\n  eexists.\n  splits; auto.\n  unfolds; simpl; eauto.\n  rewrite Int.repr_unsigned; auto.\n  unfolds.\n  splits; auto.\n  intros.\n  tryfalse.\nQed.\n       \n\nLemma rh_tcbls_mqls_p_setmsg_hold:\n  forall (mqls : EcbMod.map) (tcbls : TcbMod.map) (ct : tid) \n         (a : tidspec.A) (v : msg) (vl : list msg) (qmax : maxlen) \n         (wl : waitset),\n    RH_TCBList_ECBList_P mqls tcbls ct ->\n    EcbMod.get mqls a = Some (absmsgq vl qmax, wl) ->\n    RH_TCBList_ECBList_P (EcbMod.set mqls a (absmsgq (vl++v::nil) qmax, wl)) tcbls ct.\nProof.\n  intros.\n  unfold RH_TCBList_ECBList_P in *; simpljoin1; splits.\n  clear H1 H2 H3.\n  unfold RH_TCBList_ECBList_Q_P in *; simpljoin1; splits.\n  clear H1; intros.\n  destruct (tidspec.beq a eid) eqn : eq1.\n  lets Hx: tidspec.beq_true_eq eq1; substs.\n  rewrite EcbMod.set_a_get_a in H1; auto.\n  destruct H1; inverts H1; eauto.\n  rewrite EcbMod.set_a_get_a' in H1; auto.\n  eapply H; eauto.\n  clear H; intros.\n  destruct (tidspec.beq a eid) eqn : eq1.\n  lets Hx: tidspec.beq_true_eq eq1; substs.\n  rewrite EcbMod.set_a_get_a; auto.\n  apply H1 in H; auto.\n  do 4 destruct H.\n  unfold get in H; simpl in H.\n  rewrite H in H0; inverts H0.\n  eauto.\n  rewrite EcbMod.set_a_get_a'; auto.\n  eapply H1; eauto.\n\n  clear H H2 H3.\n  unfold RH_TCBList_ECBList_SEM_P in *; simpljoin1; splits.\n  clear H1; intros.\n  destruct (tidspec.beq a eid) eqn : eq1.\n  lets Hx: tidspec.beq_true_eq eq1; substs.\n  rewrite EcbMod.set_a_get_a in H1; auto.\n  destruct H1; inverts H1; eauto.\n  rewrite EcbMod.set_a_get_a' in H1; auto.\n  eapply H; eauto.\n  clear H; intros.\n  destruct (tidspec.beq a eid) eqn : eq1.\n  lets Hx: tidspec.beq_true_eq eq1; substs.\n  rewrite EcbMod.set_a_get_a; auto.\n  apply H1 in H; auto.\n  do 3 destruct H.\n  unfold get in H; simpl in H.\n  rewrite H in H0; inverts H0.\n  eauto.\n  rewrite EcbMod.set_a_get_a'; auto.\n  eapply H1; eauto.\n  \n  clear H H1 H3.\n  unfold RH_TCBList_ECBList_MBOX_P in *; simpljoin1; splits.\n  clear H1; intros.\n  destruct (tidspec.beq a eid) eqn : eq1.\n  lets Hx: tidspec.beq_true_eq eq1; substs.\n  rewrite EcbMod.set_a_get_a in H1; auto.\n  destruct H1; inverts H1; eauto.\n  rewrite EcbMod.set_a_get_a' in H1; auto.\n  eapply H; eauto.\n  clear H; intros.\n  destruct (tidspec.beq a eid) eqn : eq1.\n  lets Hx: tidspec.beq_true_eq eq1; substs.\n  rewrite EcbMod.set_a_get_a; auto.\n  apply H1 in H; auto.\n  do 3 destruct H.\n  unfold get in H; simpl in H.\n  rewrite H in H0; inverts H0.\n  eauto.\n  rewrite EcbMod.set_a_get_a'; auto.\n  eapply H1; eauto.\n\n  clear H H1 H2.\n  unfold RH_TCBList_ECBList_MUTEX_P in *; simpljoin1; splits.\n  clear H1; intros.\n  destruct (tidspec.beq a eid) eqn : eq1.\n  lets Hx: tidspec.beq_true_eq eq1; substs.\n  rewrite EcbMod.set_a_get_a in H1; auto.\n  destruct H1; inverts H1; eauto.\n  rewrite EcbMod.set_a_get_a' in H1; auto.\n  eapply H; eauto.\n  clear H; intros.\n  destruct (tidspec.beq a eid) eqn : eq1.\n  lets Hx: tidspec.beq_true_eq eq1; substs.\n  rewrite EcbMod.set_a_get_a; auto.\n  apply H1 in H; auto.\n  do 4 destruct H.\n  unfold get in H; simpl in H.\n  rewrite H in H0; inverts H0.\n  eauto.\n  rewrite EcbMod.set_a_get_a'; auto.\n  eapply H1; eauto.\n\n \n  unfold RH_TCBList_ECBList_MUTEX_OWNER in *.\n  intros.\n\n  assert (eid = a \\/ eid <> a) by tauto.\n  destruct H4; intros.\n  subst eid.\n  rewrite EcbMod.set_a_get_a in H3.\n  inversion H3.\n  apply CltEnvMod.beq_refl.\n  rewrite EcbMod.set_a_get_a' in H3.\n  2:apply tidspec.neq_beq_false; auto.\n  eapply H2;eauto.\nQed.\n\n\n\nLemma get_wellformedosq_in_setst':\n  forall i1 i2 x13 x12 x6 v'49 x x8,\n    x6 <> Vptr (v'49,  (x+ᵢInt.mul ($ 1) ($ 4))) ->\n    WellformedOSQ\n      (x13\n         :: x12\n         :: x6\n         :: Vptr (v'49, x)\n         :: x8\n         :: Vint32 i2\n         :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil) ->\n    WellformedOSQ\n      (x13\n         :: x12\n         :: x6\n         :: Vptr (v'49, x+ᵢInt.mul ($ 1) ($ 4))\n         :: x8\n         :: Vint32 i2\n         :: Vint32 (i1+ᵢ$ 1) :: Vptr (v'49, Int.zero) :: nil).\nProof.\n  intros.\n  assert (Int.mul ($ 1) ($ 4) = $ 4) by mauto.\n  rewrite H1 in *.\n  funfold H0.\n  unfold qend_right, arrayelem_addr_right in *.\n  simpljoin1.\n  unfold ptr_offset_right, ptr_minus in *.\n  fsimpl.\n  simpl in *.\n  assert ( Int.zero+ᵢ($ 4+ᵢInt.zero) = $ 4).\n  clear -x.\n  mauto.\n  rewrite H3 in *.\n  inverts H7.\n  unfolds.\n  do 7 eexists; splits; try solve [unfolds; simpl; eauto].\n  rewrite H3 in *.\n  splits; eauto.\n  unfolds.\n  splits; simpl; auto.\n  rewrite Pos2Z.inj_eqb .\n  rewrite Z.eqb_refl.\n  splits; eauto.\n  rewrite Pos2Z.inj_eqb .\n  rewrite Z.eqb_refl.\n  auto.\n  unfolds.\n  unfold ptr_offset_right, ptr_minus in *.\n  eexists.\n  rewrite Pos2Z.inj_eqb .\n  rewrite Z.eqb_refl.\n  splits; eauto.\n  simpl.\n  eapply  math_ltu_false_false; eauto.\n  simpl.\n  eapply math_lt_mod_lt with i2 ;eauto.\n  intro Hf.\n  subst i2.\n  tryfalse.\n  unfolds.\n  unfold ptr_offset_right, ptr_minus in *.\n  eexists.\n  rewrite Pos2Z.inj_eqb .\n  rewrite Z.eqb_refl.\n  splits; eauto.\nQed.\n\n\nLemma rlh_ecbdata_in_noend:\n  forall i1 i2 x13 x12 v'49 x x8 v'47 x14 x15 v2 x1 x2 x0 x6,\n    x6 <> Vptr (v'49, x+ᵢInt.mul ($ 1) ($ 4)) ->\n    Int.ltu i1 i2 = true ->\n    length v2 = ∘OS_MAX_Q_SIZE ->\n    WellformedOSQ\n      (x13\n         :: x12\n         :: x6\n         :: Vptr (v'49, x)\n         :: x8\n         :: Vint32 i2\n         :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil) ->\n    RLH_ECBData_P\n      (DMsgQ (Vptr (v'47, Int.zero))\n             (x13\n                :: x12\n                :: x6\n                :: Vptr (v'49, x)\n                :: x8\n                :: Vint32 i2\n                :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil)\n             (x14 :: x15 :: nil) v2) (absmsgq x1 x2, nil) ->\n    RLH_ECBData_P\n      (DMsgQ (Vptr (v'47, Int.zero))\n             (x13\n                :: x12\n                :: x6\n                :: Vptr (v'49, x+ᵢInt.mul ($ 1) ($ 4))\n                :: x8\n                :: Vint32 i2\n                :: Vint32 (i1+ᵢ$ 1) :: Vptr (v'49, Int.zero) :: nil)\n             (x14 :: x15 :: nil)\n             (update_nth_val\n                (Z.to_nat\n                   ((Int.unsigned x - Int.unsigned (Int.zero+ᵢ($ 4+ᵢInt.zero))) /\n                                                                                4)) v2 (Vptr x0))) (absmsgq (x1++ (Vptr x0 :: nil)) x2, nil).\nProof.\n  introv Hneq Hi Hlen Hw Hr.\n  funfold Hw.\n  unfold qend_right, arrayelem_addr_right in *.\n  unfold ptr_offset_right,   ptr_minus  in *.\n  fsimpl.\n  simpl in H7,H13,H12, H10, H5.\n  inverts H5.\n  assert (Int.mul ($ 1) ($ 4) = $ 4).\n  clear -b.\n  mauto.\n  rewrite H5 in *.\n  assert (i2 <> x+ᵢ$ 4) as Hni.\n  introv Hf.\n  apply Hneq.\n  subst i2.\n  auto.\n  clear Hneq.\n  unfolds in Hr.\n  destruct Hr as (Hm1 & Hm2 & Hm3 & Hm4).\n  funfold Hm1.\n  funfold Hm2.\n  funfold Hm3.\n  unfold distance in *.\n  rewrite Int.repr_unsigned in *.\n  simpl in H19 , H21 ,  H22.\n  remember (Int.unsigned (Int.divu (x-ᵢ$ 4) ($ 4))) as M.\n  remember (Int.unsigned (Int.divu (i0-ᵢ$ 4) ($ 4))) as N.\n  assert (Int.unsigned ($ 4) = 4).\n  clear -x.\n  int auto.\n  rewrite H1 in *.\n  rewrite H7 in *.\n  unfolds.\n  splits.\n  unfolds.\n  do 7 eexists; splits; try solve [unfolds; simpl; eauto].\n  splits.\n  splits.\n  introv Hc1.\n  lets Heq :math_int_lt_eq_split H H0 HeqM HeqN  Hc1; eauto.\n  destruct Heq as (He1 & He2 & He3 & He4).\n  rewrite He3.\n  rewrite He1.\n  destruct He2 as [Hea1 | Hea2].\n  lets Hca1 : H19 Hea1.\n  lets Has : vallist_seg_upd_prop (Vptr x0) Hca1.\n  rewrite Hlen.\n  apply He4.\n  apply He4.\n  rewrite Has.\n  auto.\n  lets Hrs : H22 Hea2.\n  destruct Hrs as [Hrs1 | Hrs2].\n  destruct Hrs1 as (Heq1 & Heq2).\n  subst x1.\n  rewrite Hea2.\n  rewrite  vallist_seg_upd_SM.\n  simpl; auto.\n  rewrite Hlen.\n  rewrite <-Hea2.\n  destruct He4.\n  clear - H14.\n  omega.\n  destruct Hrs2 as (Hie & _).\n  eapply ltu_eq_false in Hi.\n  rewrite Int.eq_sym in Hi.\n  rewrite Hi in Hie.\n  tryfalse.\n  introv Hc2.\n  lets Heq :math_int_lt_eq_split' H H0 HeqM HeqN  Hc2; eauto.\n  destruct Heq as (He1 & He2 & He3 & He4).\n  rewrite He3.\n  rewrite He1.\n  lets Hres : H21 He2.\n  rewrite vallist_seg_upd_irr with (y:= (Vptr x0)) (M:=∘M)in Hres;auto.\n  remember ( vallist_seg 0 ∘M v2) as xy.\n  apply eq_sym in Heqxy.\n  lets Has : vallist_seg_upd_prop (Vptr x0) Heqxy.\n  rewrite Hlen.\n  clear - He4.\n  destruct He4.\n  omega.\n  clear -x.\n  omega.\n  rewrite Has.\n  rewrite app_assoc.\n  rewrite Hres.\n  auto.\n  apply He4.\n  rewrite Hlen.\n  apply He4.\n  introv Hc3.\n  lets Heq :math_int_lt_eq_split'' H H0 HeqM HeqN  Hc3; eauto.\n  right.\n  destruct Heq as (He1 & He2 & He3 & He4).\n  destruct He2 as (Hes & Hek).\n  rewrite He3.\n  rewrite He1.\n  lets Hrs : H21 Hek.\n  rewrite vallist_seg_upd_irr with (y:= (Vptr x0)) (M:=∘M)in Hrs;auto.\n  remember ( vallist_seg 0 ∘M v2) as xy.\n  apply eq_sym in Heqxy.\n  lets Has : vallist_seg_upd_prop (Vptr x0) Heqxy.\n  rewrite Hlen.\n  clear - He4.\n  simpljoin1.\n  omega.\n  clear -x.\n  omega.\n  rewrite Has.\n  rewrite app_assoc.\n  rewrite Hrs.\n  remember ( vallist_seg ∘N ∘(Int.unsigned x2) (update_nth_val ∘M v2 (Vptr x0))) as l1.\n  remember (vallist_seg 0 (S ∘M) (update_nth_val ∘M v2 (Vptr x0))) as l2.\n  apply eq_sym in Heql1.\n  apply eq_sym in Heql2.\n  lets Hl1 : vallist_seg_length_prop Heql1.\n  clear - H4.\n  omega.\n  rewrite update_nth_val_len_eq.\n  rewrite Hlen.\n  clear -He4.\n  simpljoin1.\n  omega.\n  lets Hl2 : vallist_seg_length_prop Heql2.\n  clear -x.\n  omega.\n  rewrite update_nth_val_len_eq.\n  rewrite Hlen.\n  clear -He4.\n  simpljoin1.\n  rewrite H0.\n  omega.\n  assert (length (l1 ++ xy) = length x1).\n  rewrite Hrs; auto.\n  assert (length l2 = length ( xy ++ Vptr x0 :: nil)) .\n  rewrite Has.\n  auto.\n  rewrite app_length in H14.\n  rewrite app_length in H17.\n  rewrite Hl1 in H14.\n  rewrite Hl2 in H17.\n  simpl in H17.\n  assert (length xy = ∘M)% nat.\n  clear - H17.\n  omega.\n  rewrite H18 in H14.\n  assert (length x1 =(∘(Int.unsigned x2)-1))%nat.\n  clear - H14 He4 H2 H4.\n  simpljoin1.\n  rewrite <- H0 in H14.\n  omega.\n  split; auto.\n  eapply math_int_eq_len; eauto.\n  clear - He4.\n  simpljoin1.\n  omega.\n  rewrite Hlen.\n  eapply He4.\n  eapply isptr_list_tail_add;eauto.\n  unfolds.\n  eexists.\n  splits.\n  unfolds; simpl; eauto.\n  rewrite app_length.\n  simpl.\n  eapply  math_inc_eq_ltu; eauto.\n  unfolds.\n  eexists.\n  splits; auto.\n  unfolds; simpl; eauto.\n  rewrite Int.repr_unsigned; auto.\n  unfolds.\n  splits; auto.\n  intros.\n  tryfalse.\nQed.\n\n\nLemma prio_in_rtbl_hold:\n  forall rtbl x y prio,\n    Int.unsigned prio < 64 ->\n    Int.unsigned x <= 7 ->\n    length rtbl = ∘OS_RDY_TBL_SIZE ->\n    array_type_vallist_match Int8u rtbl ->\n    prio_in_tbl prio rtbl ->\n    prio_in_tbl prio\n                (update_nth_val (Z.to_nat (Int.unsigned x)) rtbl\n                                (val_inj\n                                   (or (nth_val' (Z.to_nat (Int.unsigned x)) rtbl) (Vint32 y)))).\nProof.\n  introv Hr1 Hr2 Hlen Har Hpro.\n  unfolds.\n  intros.\n  subst.\n  unfolds in Hpro.\n  remember (val_inj\n               (or (nth_val' (Z.to_nat (Int.unsigned x)) rtbl) (Vint32 y))) as Hx.\n  assert ((Z.to_nat (Int.unsigned x)) < length rtbl)%nat.\n  rewrite Hlen.\n  clear - Hr2.\n  mauto.\n  lets Hsx : array_int8u_nth_lt_len Har H.\n  simpljoin1.\n  rewrite H0 in H1.\n  simpl in H1.\n  remember (Int.shru prio ($3)) as py.\n  assert (py = x \\/ py <> x) by tauto.\n  destruct H3.\n  subst x.\n  unfold nat_of_Z in H1.\n  apply nth_upd_eq in H1.\n  inverts H1.\n  apply nth_val'_imp_nth_val_int in H0.\n  lets Hsd : Hpro H0; eauto.\n  rewrite Int.and_commut.\n  rewrite Int.and_or_distrib.\n  rewrite Int.and_commut in Hsd.\n  rewrite Hsd.\n  rewrite Int.or_and_absorb.\n  auto.\n  apply nth_upd_neq in H1.\n  lets Hsd : Hpro H1; eauto.\n  introv Hf.\n  apply H3.\n  unfold nat_of_Z in Hf.\n  apply Z2Nat.inj_iff in Hf;  try apply Int.unsigned_range.\n  apply unsigned_inj ; auto.\nQed.\n\n\nLemma idle_in_rtbl_hold':\n  forall rtbl x y,\n    Int.unsigned x <= 7 ->\n    length rtbl = ∘OS_RDY_TBL_SIZE ->\n    array_type_vallist_match Int8u rtbl ->\n    prio_in_tbl ($ OS_IDLE_PRIO) rtbl ->\n    prio_in_tbl ($ OS_IDLE_PRIO)\n                (update_nth_val (Z.to_nat (Int.unsigned x)) rtbl\n                                (val_inj\n                                   (or (nth_val' (Z.to_nat (Int.unsigned x)) rtbl) (Vint32 y)))).\nProof.\n  intros.\n  eapply prio_in_rtbl_hold; eauto.\n  unfold OS_IDLE_PRIO.\n  unfold OS_LOWEST_PRIO.\n  clear-x.\n  int auto.\nQed.\n\n\n\n\n\n\nLemma get_tcb_stat:\n  forall p etbl ptbl tid tcbls abstcb tcbls' vl rtbl qid vle vhold,\n    0 <= Int.unsigned p < 64 ->\n    array_type_vallist_match Int8u etbl ->\n    length etbl = ∘OS_EVENT_TBL_SIZE ->\n    prio_in_tbl p etbl ->\n    nth_val' (Z.to_nat (Int.unsigned p)) ptbl = Vptr tid ->\n    R_PrioTbl_P ptbl tcbls vhold -> \n    TcbJoin tid abstcb tcbls' tcbls ->\n    TCBNode_P vl rtbl abstcb -> \n    R_ECB_ETbl_P qid\n                 (V$OS_EVENT_TYPE_Q\n                   ::vle,\n                  etbl) tcbls ->\n    V_OSTCBStat vl = Some (Vint32 (Int.repr OS_STAT_Q)).\nProof.\n  introv Hran Harr Hlen Hpri Hnth Hr Htj Htn Hre.\n  unfolds in Hre.\n  destruct Hre as (Hre1 & Hre2 & Hre3).\n  unfolds in Hre2.\n  destruct Hre1 as (Hre1& _).\n  unfolds in Hre1.\n  unfolds in Htn.\n  destruct abstcb.\n  destruct p0.\n  destruct Htn as (Hv1 & Hv2 &  Hrl & Hrc).\n  funfold Hrl.\n  rewrite H8 in H4.\n  inverts H4.\n  unfolds in Hrc.\n  destruct Hrc as (_&_&_&Hrc).\n  unfolds in Hrc.\n  destruct Hrc as (_&_&Hrc&_).\n  unfolds in Hrc.\n  unfolds in Hpri.\n  lets Hges : tcbjoin_get_a Htj.\n  unfolds in Hr.\n  destruct Hr.\n  apply nth_val'_imp_nth_val_vptr in Hnth.\n  lets Hs : H Hnth; eauto.\n  assert (tid <> vhold) as Hnvhold.\n  apply H4 in Hges;destruct Hges;auto.\n  destruct Hs as (st & mm & Hgs);auto.\n  unfold get in Hgs; simpl in Hgs.\n  rewrite Hges in Hgs.\n  inverts Hgs.\n  assert (PrioWaitInQ (Int.unsigned p) etbl).\n  unfolds.\n  rewrite Int.repr_unsigned.\n  remember (Int.shru p ($3)) as py.\n  remember ( p&ᵢ$ 7) as px.\n  lets Hrs : n07_arr_len_ex ∘(Int.unsigned py)  Harr Hlen.\n  subst py.\n  clear - H17.\n  mauto.\n  destruct Hrs as (vx & Hntht & Hin).\n  do 3 eexists; splits; eauto.\n  assert ( V_OSEventType (V$OS_EVENT_TYPE_Q :: vle) = Some (V$OS_EVENT_TYPE_Q)).\n  unfolds.\n  simpl; auto.\n  lets Hsd : Hre1 H15 H20.\n  simpljoin1.\n  rewrite Int.repr_unsigned in H21.\n  assert (x = tid \\/ x <> tid) by tauto.\n  destruct H23.\n  subst x.\n  unfold get in H21; simpl in H21.\n  rewrite Hges in H21.\n  inverts H21.\n  eapply Hrc; eauto.\n  unfolds in H22.\n  lets Hfs : H22 H23 H21 Hges.\n  tryfalse.\n Qed.\n\n\n\nLemma rh_tcblist_ecblist_p_post_exwt_aux:\n  forall (v'8 tid0 : tid) (v'11 : EcbMod.map) \n         (v'7 : TcbMod.map) (v'9 v'10 : EcbMod.map) \n         (eid : tidspec.A) (x : list msg) \n         (x0 : maxlen) (x1 : waitset) (v'6 : EcbMod.map) \n         (prio : priority) (msg0 : msg) \n         st,\n    RH_TCBList_ECBList_P v'11 v'7 v'8 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    EcbMod.joinsig eid (absmsgq x x0, x1) v'6 v'10 ->\n    In tid0 x1 ->\n    TcbMod.get v'7 tid0 = Some (prio, st, msg0) ->\n    exists xl, st =  wait (os_stat_q eid) xl.\nProof.\n  intros.\n  unfolds in H.\n  destruct H as (Hex & Hexa).\n  lets Hget : EcbMod.join_joinsig_get H0 H1.\n  assert (EcbMod.get v'11 eid = Some (absmsgq x x0, x1) /\\ In tid0 x1).\n  split; auto.\n  apply Hex in H.\n  simpljoin1.\n  unfold get in H; simpl in H.\n  rewrite H3 in H.\n  inverts H.\n  eauto.\nQed.\n  \n\nLemma statq_and_not_statq_eq_rdy:\n  Int.eq ($ OS_STAT_Q&ᵢInt.not ($ OS_STAT_Q)) ($ OS_STAT_RDY) = true.\nProof.\n  rewrite Int.and_not_self.\n  auto.\nQed.\n\nLemma isptr_zh :\n  forall x, isptr x ->\n            match x with\n              | Vundef => false\n              | Vnull => true\n              | Vint32 _ => false\n              | Vptr _ => true\n            end = true.\nProof.\n  intros.\n  unfolds in H; destruct H.\n  substs; auto.\n  destruct H; substs; auto.\nQed.\n\n\n(***lemmas***)\nLemma tcbdllseg_get_last_tcb_ptr :\n  forall vl head headprev tail tailnext P s,\n    s |= tcbdllseg head headprev tail tailnext vl ** P ->\n    get_last_tcb_ptr vl head = Some tailnext.\nProof.\n  induction vl; intros.\n  destruct_s s; simpl in H; simpljoin.\n  simpl; auto.\n\n  unfold tcbdllseg in H; unfold dllseg in H; fold dllseg in H.\n  sep normal in H; destruct H; sep split in H.\n  sep remember (1::nil)%nat in H.\n  destruct_s s.\n  unfold sat in H; fold sat in H.\n  Ltac simpl_state := simpl substmo in *; simpl getmem in *; simpl getabst in *.\n  simpl_state; simpljoin1.\n  unfold tcbdllseg in IHvl.\n  lets Hx: IHvl H8.\n  simpl.\n  destruct vl; auto.\n  simpl in Hx; inverts Hx; auto.\nQed.\n\nLemma tcbdllseg_combine_ptr_in_tcblist :\n  forall vl1 vl2 head1 headprev1 tail1 tailnext1 tail2 tailnext2 s P,\n    s |= tcbdllseg head1 headprev1 tail1 tailnext1 vl1 ** tcbdllseg tailnext1 tail1 tail2 tailnext2 vl2 ** P ->\n    vl2 <> nil ->\n    ptr_in_tcblist tailnext1 head1 (vl1 ++ vl2).\nProof.\n  inductions vl1; intros.\n  unfold tcbdllseg in H at 1.\n  simpl dllseg in H.\n  sep split in H; substs.\n  rewrite app_nil_l.\n\n  Lemma tcbdllseg_ptr_in_tcblist_head :\n    forall vl head headprev tail tailnext s P,\n      s |= tcbdllseg head headprev tail tailnext vl ** P ->\n      vl <> nil ->\n      ptr_in_tcblist head head vl.\n  Proof.\n    destruct vl; intros; tryfalse.\n    destruct_s s; unfold tcbdllseg in H; unfold dllseg in H; fold dllseg in H.\n    sep normal in H; destruct H; sep split in H.\n    simpl.\n    Lemma beq_addrval_true : forall a, beq_addrval a a = true.\n    Proof.\n      intro.\n      destruct a; simpl.\n      rewrite Int.eq_true.\n      rewrite beq_pos_Pos_eqb_eq.\n      rewrite Pos.eqb_refl.\n      simpl; auto.\n    Qed.\n\n    Lemma beq_val_true : forall v, beq_val v v = true.\n    Proof.\n      intro.\n      destruct v; simpl; auto.\n      rewrite Int.eq_true; auto.\n      rewrite beq_addrval_true; auto.\n    Qed.\n    rewrite beq_val_true.\n    auto.\n  Qed.\n\n  apply tcbdllseg_ptr_in_tcblist_head in H; auto.\n  unfold tcbdllseg in H at 1.\n  unfold dllseg in H; fold dllseg in H.\n  sep normal in H; destruct H; sep split in H.\n  sep remember (1::nil)%nat in H.\n  destruct_s s.\n  unfold sat in H; fold sat in H.\n  simpl_state; simpljoin1.\n  unfold tcbdllseg in IHvl1 at 1.\n  lets Hx: IHvl1 H9 H0.\n  rewrite <- app_comm_cons.\n  simpl.\n  destruct (beq_val tailnext1 head1); auto.\n  rewrite H1; auto.\nQed.\n\nLemma sep_disj_dist :\n  forall P Q R s,\n    s |= (P \\\\// Q) ** R ->\n    s |= (P ** R) \\\\// (Q ** R).\nProof.\n  intros.\n  destruct_s s.\n  simpl in H; simpljoin1.\n  destruct H3.\n  left.\n  simpl.\n  do 6 eexists; splits; eauto.\n  right.\n  simpl.\n  do 6 eexists; splits; eauto.\nQed.\n\nLemma tcbdllseg_split_hoare :\n  forall spec sd linv inv r ri tid tcbls rtbl vltcb P s q head tail,\n    ptr_in_tcbdllseg (Vptr tid) head vltcb ->\n    TCBList_P head vltcb rtbl tcbls ->\n    {|spec, sd, linv, inv, r, ri|} |- tid\n      {{\n          EX (l1 l2 : list vallist) tcb_cur (tail1 : val) (tcbls1 tcbls2 : TcbMod.map),\n          tcbdllseg head Vnull tail1 (Vptr tid) l1 **\n                    tcbdllseg (Vptr tid) tail1 tail Vnull (tcb_cur :: l2) **\n                    [|vltcb = l1 ++ (tcb_cur :: l2)|] **\n                    [|TcbMod.join tcbls1 tcbls2 tcbls|] **\n                    [|TCBList_P head l1 rtbl tcbls1|] **\n                    [|TCBList_P (Vptr tid) (tcb_cur :: l2) rtbl tcbls2|] ** P\n        }} s {{q}} ->\n    {|spec, sd, linv, inv, r, ri|} |- tid {{tcbdllseg head Vnull tail Vnull vltcb ** P }} s {{q}}.\nProof.\n  intros.\n  eapply backward_rule1.\n  eapply tcbdllseg_split'; eauto.\n  eapply backward_rule1.\n  instantiate(1:=(EX (l1 l2 : list vallist) (tcb_cur : vallist) \n                     (tail1 : val) (tcbls1 tcbls2 : TcbMod.map),\n                  tcbdllseg head Vnull tail1 (Vptr tid) l1 **\n                            tcbdllseg (Vptr tid) tail1 tail Vnull (tcb_cur :: l2) **\n                            [|vltcb = l1 ++ tcb_cur :: l2|] **\n                            [|TcbMod.join tcbls1 tcbls2 tcbls|] **\n                            [|TCBList_P head l1 rtbl tcbls1|] **\n                            [|TCBList_P (Vptr tid) (tcb_cur :: l2) rtbl tcbls2|] ** P)).\n  intros; clear H1.\n  destruct H2.\n  do 4 destruct H1.\n  destruct x0.\n  unfold tcbdllseg in H1 at 2.\n  simpl dllseg in H1.\n  sep split in H1; tryfalse.\n  sep auto; eauto.\n  auto.\nQed.\n\n\nLemma tcbdllseg_split_hoare' :\n  forall spec sd linv inv r ri tid P s q head tail vltcb1 vl vltcb2,\n    {|spec, sd, linv, inv, r, ri|} |- tid\n      {{EX tail1 tailnext1,\n          tcbdllseg head Vnull tail1 tailnext1 vltcb1 **\n          tcbdllseg tailnext1 tail1 tail Vnull (vl :: vltcb2) **\n          [|get_last_tcb_ptr vltcb1 head = Some tailnext1|] ** P\n        }} s {{q}} ->\n      {|spec, sd, linv, inv, r, ri|} |- tid\n        {{tcbdllseg head Vnull tail Vnull (vltcb1++vl::vltcb2) ** P }} s {{q}}.\nProof.\n  intros.\n  Lemma tcbdllseg_head_vptr :\n    forall vltcb1 vl vltcb2 head tail s,\n      s |= tcbdllseg head Vnull tail Vnull (vltcb1++vl::vltcb2) ->\n      exists a, head = Vptr a.\n  Proof.\n    intros.\n    destruct vltcb1.\n    rewrite app_nil_l in H.\n    unfold tcbdllseg in H.\n    unfold dllseg in H; fold dllseg in H.\n    sep normal in H.\n    destruct H.\n    sep split in H.\n    unfold node in H; sep normal in H; destruct H.\n    sep split in H.\n    simpljoin.\n    eauto.\n    rewrite <- app_comm_cons in H.\n    unfold tcbdllseg in H.\n    unfold dllseg in H; fold dllseg in H.\n    sep normal in H.\n    destruct H.\n    sep split in H.\n    unfold node in H; sep normal in H; destruct H.\n    sep split in H.\n    simpljoin.\n    eauto.\n  Qed.\n\n  eapply hoare_pure_gen with (p:=(exists a, head = Vptr a)).\n  intros.\n  eapply tcbdllseg_head_vptr in H0; auto.\n  pure intro.\n  eapply backward_rule1.\n  intros.\n  eapply ucos_common.tcbdllseg_split; eauto.\n  pure intro.\n  eapply backward_rule1\n  with (p:=(EX tail1 tailnext1 : val,\n        tcbdllseg (Vptr x) Vnull tail1 tailnext1 vltcb1 **\n        tcbdllseg tailnext1 tail1 tail Vnull (vl :: vltcb2) **\n        [|get_last_tcb_ptr vltcb1 (Vptr x) = Some tailnext1|] ** P)).\n  intros.\n  sep auto.\n  destruct H0; simpljoin.\n  unfolds.\n  destruct vltcb1; tryfalse.\n  unfolds; auto.\n  inverts H2.\n  simpl; auto.\n  auto.\nQed.\n\n\nLemma ecblist_p_post_exwt_hold1:\n  forall  v'36 v'12 v'13 v'38 v'69 v'39 v'58 v'40  v'32 v'15 v'24 v'35 v'16\n          v'18 v'19 v'20 v'34 v'21 v'22 v'23 v'25 v'26 v'27 x x0 x1 v'0 v'1\n          v'5 v'6 v'7 x00 v'11 v'31 v'30 v'29 v'10 v'9 prio v'62 st msg y vhold,\n    v'12 <> Int.zero ->\n    Int.unsigned v'12 <= 255 ->\n    array_type_vallist_match Int8u v'13 ->\n    length v'13 = ∘OS_EVENT_TBL_SIZE ->\n    nth_val' (Z.to_nat (Int.unsigned v'12)) OSUnMapVallist = Vint32 v'38 ->\n    Int.unsigned v'38 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned v'38)) v'13 = Vint32 v'69 ->\n    Int.unsigned v'69 <= 255 ->\n    nth_val' (Z.to_nat (Int.unsigned v'69)) OSUnMapVallist = Vint32 v'39 ->\n    Int.unsigned v'39 <= 7 ->\n    nth_val' (Z.to_nat (Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39))) v'36 = Vptr (v'58, Int.zero)->\n    nth_val' (Z.to_nat (Int.unsigned v'39)) OSMapVallist = Vint32 v'40 ->\n    Int.unsigned v'40 <= 128 ->\n    RL_Tbl_Grp_P v'13 (Vint32 v'12) ->\n(**)    \n    R_ECB_ETbl_P (v'32, Int.zero)\n                 (V$OS_EVENT_TYPE_Q\n                   :: Vint32 v'12\n                   :: Vint32 v'15 :: Vptr (v'24, Int.zero) :: v'35 :: v'0 :: nil,\n                  v'13) v'7 ->\n    RLH_ECBData_P\n      (DMsgQ (Vptr (v'24, Int.zero))\n             (v'16\n                :: v'18\n                :: v'19\n                :: v'20\n                :: v'34\n                :: Vint32 v'21\n                :: Vint32 v'22 :: Vptr (v'23, Int.zero) :: nil)\n             (v'26 :: v'25 :: nil) v'27) (absmsgq x x0, x1) ->\n    ECBList_P v'0 Vnull v'1 v'5 v'6 v'7 ->\n    ECBList_P v'29 (Vptr (v'32, Int.zero)) v'30 v'31 v'9 v'7 ->\n    EcbMod.joinsig (v'32, Int.zero) (absmsgq x x0, x1) v'6 v'10 ->\n    EcbMod.join v'9 v'10 v'11 ->\n    TcbJoin (v'58, Int.zero) (prio, st, msg) v'62 v'7 ->\n    R_PrioTbl_P v'36 v'7 vhold ->\n    x1 <> nil ->\n    ECBList_P v'29 Vnull\n              (v'30 ++\n                    ((V$OS_EVENT_TYPE_Q\n                       :: Vint32 y\n                       :: Vint32 v'15 :: Vptr (v'24, Int.zero) :: v'35 :: v'0 :: nil,\n                      update_nth_val (Z.to_nat (Int.unsigned v'38)) v'13\n                                     (Vint32 (v'69&ᵢInt.not v'40))) :: nil) ++ v'1)\n              (v'31 ++\n                    (DMsgQ (Vptr (v'24, Int.zero))\n                           (v'16\n                              :: v'18\n                              :: v'19\n                              :: v'20\n                              :: v'34\n                              :: Vint32 v'21\n                              :: Vint32 v'22 :: Vptr (v'23, Int.zero) :: nil)\n                           (v'26 :: v'25 :: nil) v'27 :: nil) ++ v'5)\n              (EcbMod.set v'11 (v'32, Int.zero)\n                          (absmsgq nil x0, remove_tid (v'58, Int.zero) x1))\n              (TcbMod.set v'7 (v'58, Int.zero)\n                          (prio, rdy , Vptr x00))\n.\nProof.\n  intros.\n  unfolds in H20.\n  destruct H20 as (Ha1 & Ha2 & Ha3).\n  assert ( 0 <= Int.unsigned ((v'38<<ᵢ$ 3)+ᵢv'39) < 64).\n  clear -H4 H8.\n  mauto.\n  unfold nat_of_Z in Ha1.\n  eapply nth_val'_imp_nth_val_vptr in H9.\n  lets Hps : Ha1 H20 H9.\n  apply tcbjoin_get_a in H19.\n  assert ((v'58, Int.zero) <> vhold) as Hnvhold.\n  apply Ha2 in H19.\n  destruct H19;auto.\n  destruct Hps as (sts & mg & Hget);auto.\n  unfold get in Hget; simpl in Hget.\n  rewrite Hget in H19.\n  inverts H19.\n  remember ((v'38<<ᵢ$ 3)) as px.\n  remember (v'39) as py.\n  clear Heqpy.\n  remember (px+ᵢpy) as prio.\n  remember ( (v'58, Int.zero)) as tid.\n  unfolds in H13.\n  destruct H13 as (Ha & Hb & Hc).\n  destruct Ha as (Ha&Ha'&Ha''&Ha''').\n  destruct Hb as (Hb&Hb'&Hb''&Hb''').\n  lets Hz : math_unmap_get_y H0 H3.\n  lets Heq1 :  math_mapval_core_prop H10; eauto.\n  omega.\n  subst v'40.\n  assert (v'38 = Int.shru prio ($3)).\n  subst.\n  clear -Hz H8.\n  mauto.\n  assert (py = prio &ᵢ $ 7).\n  subst prio. \n  rewrite Heqpx.\n  clear -Hz H8.\n  mauto.\n  rewrite H13 in H5.\n  assert (PrioWaitInQ (Int.unsigned prio) v'13) as Hcp.\n  unfolds.\n  do 3 eexists; splits; eauto.\n  rewrite Int.repr_unsigned.\n  eapply nth_val'_imp_nth_val_int; eauto.\n  rewrite Int.repr_unsigned.\n  rewrite <- H19.\n  unfold Int.one.\n  eapply math_8_255_eq; eauto.\n  \n  unfold Int.zero in H.\n  rewrite <-H13 in *.\n  lets Hneq :  rl_tbl_grp_neq_zero H0 H  H3 H5 H12.\n  omega.\n  auto.\n  lets Hecp : Ha Hcp.\n  unfold V_OSEventType in Hecp.\n  simpl nth_val in Hecp.\n  assert (Some (V$OS_EVENT_TYPE_Q) = Some (V$OS_EVENT_TYPE_Q)) by auto.\n  apply Hecp in H22.\n  clear Hecp.\n  rename H22 into Hecp.\n  destruct Hecp as (ct & nl & mg & Hcg).\n  assert (ct = tid) as Hed.\n  assert (ct = tid \\/ ct <> tid)  by tauto.\n  destruct H22; auto.\n  lets Heqs : Ha3 H22 Hcg Hget.\n  rewrite Int.repr_unsigned in Heqs.\n  tryfalse.\n  subst ct.\n  unfold get in Hcg; simpl in Hcg.\n  rewrite Hget in Hcg.\n  inversion Hcg.\n  subst mg st .\n  clear Hcg.\n  \n  lets Hsds : ecb_set_join_join  (absmsgq nil x0, remove_tid tid x1)  H17  H18.\n  destruct Hsds as ( vv & Hsj1 & Hsj2).\n  eapply msgqlist_p_compose.\n  instantiate (1:= (v'32, Int.zero)).\n  unfolds.\n  splits.\n  unfolds.\n  splits;unfolds.\n  \n  introv Hprs Hxx.\n  clear Hxx.\n  apply prio_wt_inq_convert in Hprs.\n  destruct Hprs as (Hprs1 & Hprs2).\n  rewrite H13 in Hprs1.\n  rewrite H19 in Hprs1.\n  lets Hrs : prio_wt_inq_tid_neq  H5 H20 .\n  destruct Hrs as (Hrs & _).\n  apply Hrs in Hprs1.\n  destruct Hprs1 as (Hpq & Hneq).\n  unfolds in Ha.\n  lets Hxs : Ha Hpq.\n  rewrite Int.repr_unsigned in Hxs.\n  destruct Hxs as (tid' & nn & mm & Htg).\n  unfolds;simpl;auto.\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H22.\n  subst tid'.\n  unfold get in Htg; simpl in Htg.\n  rewrite Hget in Htg.\n  inversion Htg.\n  tryfalse.\n  exists tid' nn mm.\n  rewrite TcbMod.set_sem.\n  rewrite tidspec.neq_beq_false;eauto.\n\n  intros.\n  unfolds in H24;simpl in H24;tryfalse.\n  intros.\n  unfolds in H24;simpl in H24;tryfalse.\n  intros.\n  unfolds in H24;simpl in H24;tryfalse.\n\n  unfolds.\n  splits;\n  intros prio' mm nn tid'.\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H22.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  unfolds in Hb.\n  lets Hga : Hb Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H22 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n\n  lets Hrs : prio_wt_inq_tid_neq  H5 H20 .\n  destruct Hrs as (_ & Hrs).\n  apply Hrs in H24.\n  rewrite H19.\n  rewrite H13.\n  auto.\n\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H22.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  unfolds in Hb'.\n  lets Hga : Hb' Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H22 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n  unfolds in Hx;simpl in Hx;tryfalse.\n\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H22.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  unfolds in Hb''.\n  lets Hga : Hb'' Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H22 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n  unfolds in Hx;simpl in Hx;tryfalse.\n\n  assert (tid = tid' \\/ tid <> tid') by tauto.\n  destruct H22.\n  subst tid'.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.eq_beq_true in Hgs; auto.\n  inverts Hgs.\n  introv Hgs.\n  rewrite TcbMod.set_sem in Hgs.\n  rewrite tidspec.neq_beq_false in Hgs; eauto.\n  unfolds in Hb'''.\n  lets Hga : Hb''' Hgs.\n  destruct Hga as (Hga & Hx).\n  unfolds in Ha3.\n  lets Hneqp: Ha3 H22 Hget Hgs.\n  assert ( PrioWaitInQ (Int.unsigned prio') v'13 /\\ prio' <> prio) .\n  splits; auto.\n  unfolds in Hx;simpl in Hx;tryfalse.\n\n  simpl fst in Hc;simpl;auto.\n  \n  instantiate (1:=v'9).\n  eapply ECBList_P_Set_Rdy_hold;eauto.\n  rewrite Int.repr_unsigned.  \n  eauto.\n  eapply joinsig_join_getnone; eauto.\n  instantiate (1:=v'6).\n  eapply ECBList_P_Set_Rdy_hold;eauto.\n  rewrite Int.repr_unsigned.  \n  eauto.\n  eapply  joinsig_get_none; eauto.\n  unfolds in H14.\n  simpljoin1.\n  unfolds in r.\n  apply r in H21.\n  subst x.\n  instantiate (1:=(absmsgq nil x0, remove_tid tid x1)).\n  splits; auto.\n  unfolds.\n  splits; intros; auto; tryfalse.\n  eapply Hsj1.\n  eapply Hsj2.\nQed.\n\nLemma qpost_ovf_prop1 :\n  forall (i2 i1 : int32) (x13 x12 x6 x7 x8 : val) \n         (v'49 v'47 : block) (x14 x15 : val) (x : list msg) \n         (x1 : maxlen) (x2 : waitset) (v2 : vallist),\n    (true = Int.ltu i2 i1 \\/ true = Int.eq i1 i2) ->\n    WellformedOSQ\n      (x13\n         :: x12\n         :: x6\n         :: x7\n         :: x8\n         :: Vint32 i2\n         :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil) ->\n    RLH_ECBData_P\n      (DMsgQ (Vptr (v'47, Int.zero))\n             (x13\n                :: x12\n                :: x6\n                :: x7\n                :: x8\n                :: Vint32 i2\n                :: Vint32 i1 :: Vptr (v'49, Int.zero) :: nil)\n             (x14 :: x15 :: nil) v2) (absmsgq x x1, x2) ->\n    Z.of_nat (length x) >= Int.unsigned x1.\nProof.\n  intros.\n  destruct H.\n  eapply qpost_ovf_prop; eauto.\n  eapply qpost_ovf_prop'; eauto.\nQed.\n\nFixpoint vptr_next (head:val) (vltcb:list vallist) :=\n  match vltcb with\n    | nil => True\n    | vl::vltcb' =>\n      exists a, head = Vptr a /\\\n                match V_OSTCBNext vl with\n                  | Some vn => vptr_next vn vltcb'\n                  | None => False\n                end\n  end.\n\n\nDefinition distinct_tcbdllseg_next_ptr_vnull (head : val) (l : list vallist) :=\n  distinct_tcbdllseg_next_ptr head l /\\ get_last_tcb_ptr l head = Some Vnull /\\\n  vptr_next head l.\n\nLemma tcbdllseg_vptr_next :\n  forall vltcb head headprev tail tailnext s P,\n    s |= tcbdllseg head headprev tail tailnext vltcb ** P ->\n    vptr_next head vltcb.\nProof.\n  inductions vltcb; intros.\n  simpl; auto.\n\n  unfold tcbdllseg in H.\n  unfold dllseg in H; fold dllseg in H.\n  sep normal in H; destruct H; sep split in H.\n  sep remember (1::nil)%nat in H.\n  destruct_s s.\n  unfold sat in H; fold sat in H.\n  simpl getmem in H; simpl getabst in H; simpl substmo in H.\n  simpljoin.\n  eapply IHvltcb in H8.\n  unfold vptr_next; fold vptr_next.\n  rewrite H0.\n  unfold node in H7; sep normal in H7.\n  destruct H7.\n  sep split in H.\n  simpljoin.\n  eauto.\nQed.\n\n  \nLemma tcbdllseg_distinct_tcbdllseg_next_ptr_vnull :\n  forall vltcb head headprev tail s P,\n    s |= tcbdllseg head headprev tail Vnull vltcb ** P ->\n    distinct_tcbdllseg_next_ptr_vnull head vltcb.\nProof.\n  intros.\n  unfolds.\n  split.\n  inductions vltcb; intros.\n  unfolds.\n  simpl.\n  unfold tcbdllseg in H.\n  unfold dllseg in H.\n  sep split in H.\n  substs.\n  auto.\n\n  unfold tcbdllseg in H.\n  unfold dllseg in H; fold dllseg in H.\n  sep normal in H.\n  destruct H.\n  sep split in H.\n  destruct_s s.\n  assert\n    (\n      (e, e0, m, i, (i0, i1, c), o, a0)\n        |= node head a OS_TCB_flag **\n        dllseg x head tail Vnull vltcb OS_TCB_flag V_OSTCBPrev V_OSTCBNext **\n        P\n    ) as H_bak by auto.\n  sep remember (1::nil)%nat in H.\n  simpl_sat H; simpljoin.\n  unfold tcbdllseg in IHvltcb.\n  lets Hx: IHvltcb H8.\n\n  unfold distinct_tcbdllseg_next_ptr; fold distinct_tcbdllseg_next_ptr.\n  rewrite H0.\n  destruct vltcb; auto.\n  split; auto.\n  eapply not_ptr_in_tcbdllseg1; eauto.\n  split.\n  eapply tcbdllseg_get_last_tcb_ptr; eauto.\n  eapply tcbdllseg_vptr_next; eauto.\nQed.\n\nLemma app_cons_not_nil :\n  forall {A} (vl1:list A) v vl2,\n  exists a vl', vl1++v::vl2 = a::vl'.\nProof.\n  inductions vl1; intros.\n  rewrite app_nil_l; eauto.\n  rewrite <- app_comm_cons.\n  pose proof IHvl1 v vl2.\n  simpljoin.\n  rewrite H.\n  exists a (x::x0).\n  auto.\nQed.\n\nLemma get_last_tcb_ptr_last :\n  forall vltcb vl head,\n    get_last_tcb_ptr (vltcb++vl::nil) head = Some Vnull ->\n    V_OSTCBNext vl = Some Vnull.\nProof.\n  inductions vltcb; intros.\n  rewrite app_nil_l in H.\n  simpl in H; auto.\n  rewrite <- app_comm_cons in H.\n  eapply IHvltcb with (head:=head).\n  unfold get_last_tcb_ptr in *.\n\n  pose proof app_cons_not_nil (A:=vallist) vltcb vl nil.\n  do 2 destruct H0.\n  rewrite H0.\n  rewrite H0 in H.\n  unfold last in *; auto.\nQed.\n\n\nLemma tcblist_get_split :\n  forall vltcb p head vl,\n    tcblist_get p head vltcb = Some vl ->\n    exists vltcb1 vltcb2, vltcb = vltcb1++vl::vltcb2.\nProof.\n  inductions vltcb; intros.\n  simpl in H; tryfalse.\n\n  unfold tcblist_get in H; fold tcblist_get in H.\n  destruct (beq_val p head) eqn : eq1.\n  inverts H.\n  exists (nil (A:=vallist)) vltcb.\n  rewrite app_nil_l; auto.\n\n  destruct(V_OSTCBNext a) eqn: eq2; tryfalse.\n\n  lets Hx: IHvltcb H; simpljoin.\n  rewrite app_comm_cons.\n  eauto.\nQed.\n\nLemma ptr_in_tcbdllseg1_true :\n  forall vltcb1 vltcb2 vl vl' head p,\n    V_OSTCBNext vl = Some p ->\n    vptr_next head (vltcb1 ++ vl :: vl' :: vltcb2) ->\n    ptr_in_tcbdllseg1 p head (vltcb1 ++ vl :: vl' :: vltcb2).\nProof.\n  inductions vltcb1; intros.\n  rewrite app_nil_l.\n  unfold ptr_in_tcbdllseg1; fold ptr_in_tcbdllseg1.\n  rewrite H.\n  rewrite beq_val_true.\n  destruct (beq_val p head); auto.\n\n  rewrite <- app_comm_cons in *. \n  unfold ptr_in_tcbdllseg1; fold ptr_in_tcbdllseg1.\n  unfold vptr_next in H0; fold vptr_next in H0; simpljoin.\n  destruct (beq_val p (Vptr x)); auto.\n  destruct (V_OSTCBNext a); tryfalse.\n  eapply IHvltcb1; eauto.\nQed.\n\nLemma distinct_tcbdllseg_next_ptr_vnull_dup_node_false :\n  forall vltcb1 vltcb2 head vl,\n    distinct_tcbdllseg_next_ptr_vnull head (vl :: vltcb1 ++ vl :: vltcb2) ->\n    False.\nProof.\n  intros.\n  destruct vltcb2.\n  unfolds in H; simpljoin.\n  rewrite app_comm_cons in H0.\n\n  apply get_last_tcb_ptr_last in H0.\n  unfold vptr_next in H1; fold vptr_next in H1.\n  simpljoin.\n  destruct (V_OSTCBNext vl) eqn : eq1; tryfalse.\n  inverts H0.\n  destruct vltcb1.\n  rewrite app_nil_l in H2.\n  unfold vptr_next in H2; simpljoin; tryfalse.\n  rewrite <- app_comm_cons in H2.\n  unfold vptr_next in H2; simpljoin; tryfalse.\n\n  unfolds in H; simpljoin.\n  unfold distinct_tcbdllseg_next_ptr in H; fold distinct_tcbdllseg_next_ptr in H.\n  pose proof app_cons_not_nil (A:=vallist) vltcb1 vl (v::vltcb2).\n  simpljoin.\n  rewrite H2 in H.\n  destruct (V_OSTCBNext vl) eqn : eq1; tryfalse.\n  simpljoin.\n  rewrite <- H2 in H3.\n\n  destruct vltcb1.\n  rewrite app_nil_l in H3.\n  unfold distinct_tcbdllseg_next_ptr in H3; fold distinct_tcbdllseg_next_ptr in H3.\n  rewrite eq1 in H3.\n  destruct H3.\n  unfold ptr_in_tcbdllseg1 in H3; fold ptr_in_tcbdllseg1 in H3.\n  rewrite beq_val_true in H3.\n  apply H3; auto.\n\n  rewrite <- app_comm_cons in H3.\n  unfold distinct_tcbdllseg_next_ptr in H3; fold distinct_tcbdllseg_next_ptr in H3.\n  pose proof app_cons_not_nil (A:=vallist) vltcb1 vl (v::vltcb2); simpljoin.\n  rewrite H4 in H3.\n  destruct (V_OSTCBNext v1) eqn : eq2; tryfalse.\n  destruct H3.\n  rewrite <- H4 in H3.\n  unfold vptr_next in H1; fold vptr_next in H1; simpljoin.\n  rewrite eq1 in H6.\n  rewrite <- app_comm_cons in H6.\n  unfold vptr_next in H6; fold vptr_next in H6; simpljoin.\n  destruct (V_OSTCBNext v1) eqn : eq3; tryfalse.\n  inverts eq2.\n\n  apply H3.\n  eapply ptr_in_tcbdllseg1_true; auto.\nQed.\n\nLemma tcblist_get_distinct_tcbdllseg_next_ptr_vnull_false :\n  forall vltcb head vl v p,\n    distinct_tcbdllseg_next_ptr_vnull head (vl :: vltcb) ->\n    V_OSTCBNext vl = Some v ->\n    tcblist_get p v vltcb = Some vl ->\n    False.\nProof.\n  intros.\n  eapply tcblist_get_split in H1; simpljoin.\n  eapply distinct_tcbdllseg_next_ptr_vnull_dup_node_false; eauto.\nQed.\n\nLemma distinct_tcbdllseg_next_ptr_vnull_tail :\n  forall vltcb vl head v,\n    distinct_tcbdllseg_next_ptr_vnull head (vl :: vltcb) ->\n    V_OSTCBNext vl = Some v ->\n    distinct_tcbdllseg_next_ptr_vnull v vltcb.\nProof.\n  inductions vltcb; intros.\n  unfold distinct_tcbdllseg_next_ptr_vnull in *; simpljoin.\n  split.\n  unfold distinct_tcbdllseg_next_ptr in *; auto.\n  split.\n  simpl in *.\n  rewrite H1 in H0; auto.\n  simpl; auto.\n\n  assert(distinct_tcbdllseg_next_ptr_vnull head (vl :: a :: vltcb)) as H_bak.\n  auto.\n  unfolds in H.\n  simpljoin.\n  unfold distinct_tcbdllseg_next_ptr in H; fold distinct_tcbdllseg_next_ptr in H.\n  rewrite H0 in H.\n  destruct H.\n  destruct vltcb.\n  unfolds.\n  simpl.\n  split; auto.\n  split.\n  simpl in H1; auto.\n  simpl in H2.\n  destruct H2.\n  destruct H2.\n  rewrite H0 in H4.\n  eauto.\n  destruct(V_OSTCBNext a) eqn : eq2; tryfalse.\n  assert(distinct_tcbdllseg_next_ptr_vnull head (a :: v0 :: vltcb)).\n  unfolds.\n  destruct H3.\n  splits; auto.\n  unfold distinct_tcbdllseg_next_ptr; fold distinct_tcbdllseg_next_ptr.\n  rewrite eq2.\n  split; auto.\n  intro.\n  apply H.\n  clear - eq2 H5.\n  unfold ptr_in_tcbdllseg1 in *; fold ptr_in_tcbdllseg1 in *.\n  destruct (beq_val head v) eqn : eq1; auto.\n  rewrite eq2.\n  auto.\n\n  unfold vptr_next in *; fold vptr_next in *.\n  rewrite  eq2 in *.\n  destruct H2.\n  destruct H2.\n  rewrite H0 in H5.\n  simpljoin.\n  destruct (V_OSTCBNext v0); tryfalse.\n  eauto.\n\n  eapply IHvltcb in H4; eauto.\n  unfold distinct_tcbdllseg_next_ptr_vnull in *.\n  simpljoin.\n  splits; auto.\n  unfold distinct_tcbdllseg_next_ptr; fold distinct_tcbdllseg_next_ptr.\n  rewrite eq2.\n  split; auto.\n\n  unfold vptr_next in H9; fold vptr_next in H9.\n  rewrite eq2 in H9; rewrite H0 in H9.\n  simpljoin.\n  unfold vptr_next; fold vptr_next.\n  rewrite eq2.\n  eexists.\n  splits; eauto.\nQed.\n\nLemma distinct_tcbdllseg_next_ptr_vnull_tcblist_get_get_last_tcb_ptr :\n  forall vltcb1 vltcb2 vl head tid p,\n    tcblist_get (Vptr tid) head (vltcb1++vl::vltcb2) = Some vl ->\n    get_last_tcb_ptr vltcb1 head = Some p ->\n    distinct_tcbdllseg_next_ptr_vnull head (vltcb1++vl::vltcb2) ->\n    p = (Vptr tid).\nProof.\n  induction vltcb1; intros.\n  simpl in H0; inverts H0.\n  rewrite app_nil_l in H.\n  unfold tcblist_get in H; fold tcblist_get in H.\n  destruct (beq_val (Vptr tid) p) eqn : eq1.\n  apply beq_val_true_eq in eq1; auto.\n  destruct(V_OSTCBNext vl) eqn : eq2; tryfalse.\n  rewrite app_nil_l in H1.\n  false.\n  eapply tcblist_get_distinct_tcbdllseg_next_ptr_vnull_false; eauto.\n\n  rewrite <- app_comm_cons in H.\n  unfold tcblist_get in H; fold tcblist_get in H.\n  destruct (beq_val (Vptr tid) head) eqn : eq1.\n  inverts H.\n  rewrite <- app_comm_cons in H1. \n\n  false.\n  eapply distinct_tcbdllseg_next_ptr_vnull_dup_node_false; eauto.\n  destruct (V_OSTCBNext a) eqn : eq2; tryfalse.\n  eapply IHvltcb1; eauto.\n  unfold get_last_tcb_ptr in *; fold get_last_tcb_ptr in *.\n  destruct vltcb1.\n  simpl in H0.\n  rewrite eq2 in H0; inverts H0; auto.\n  auto.\n  eapply distinct_tcbdllseg_next_ptr_vnull_tail; eauto.\nQed.\n\nLemma ptr_in_tcbdllseg1_preserv :\n  forall vltcb1 vl vl' vltcb2 head p,\n    ptr_in_tcbdllseg1 p head (vltcb1 ++ vl :: vltcb2) ->\n    same_prev_next vl vl' ->\n    ptr_in_tcbdllseg1 p head (vltcb1 ++ vl' :: vltcb2).\nProof.\n  inductions vltcb1; intros.\n  rewrite app_nil_l in *.\n  unfold ptr_in_tcbdllseg1 in *; fold ptr_in_tcbdllseg1 in *.\n  destruct (beq_val p head) eqn : eq1; auto.\n  unfolds in H0.\n  destruct (V_OSTCBNext vl); tryfalse.\n  destruct (V_OSTCBNext vl'); tryfalse.\n  simpljoin; auto.\n  rewrite <- app_comm_cons in *.\n  unfold ptr_in_tcbdllseg1 in *; fold ptr_in_tcbdllseg1 in *.\n  destruct (beq_val p head) eqn : eq1; auto.\n  destruct (V_OSTCBNext a); tryfalse.\n  eapply IHvltcb1; eauto.\nQed.\n\nLemma tcbls_rtbl_timetci_update_not_nil :\n  forall a a0 a' rtbl b c d rtbl' b' c',\n    tcbls_rtbl_timetci_update (a::a0) rtbl (Vint32 b) c d =\n    Some (a', rtbl', b', c') ->\n    a' <> nil.\nProof.\n  intros.\n  simpl in H.\n  xunfold H.\n  auto.\n  auto.\n  auto.\n  auto.\nQed.\n\nLemma distinct_tcbdllseg_next_ptr_preserve :\n  forall vltcb1 vltcb2 vl vl' head,\n    distinct_tcbdllseg_next_ptr_vnull head (vltcb1++vl::vltcb2) ->\n    same_prev_next vl vl' ->\n    distinct_tcbdllseg_next_ptr_vnull head (vltcb1++vl'::vltcb2).\nProof.\n  inductions vltcb1; intros.\n  rewrite app_nil_l in *.\n  unfold distinct_tcbdllseg_next_ptr_vnull in *; fold distinct_tcbdllseg_next_ptr_vnull in *.\n  destruct H.\n  destruct H1.\n  unfold distinct_tcbdllseg_next_ptr in *; fold distinct_tcbdllseg_next_ptr in *.\n  unfold get_last_tcb_ptr in *; fold get_last_tcb_ptr in *.\n  split.\n  destruct vltcb2; auto.\n  unfolds in H0.\n  destruct (V_OSTCBNext vl) eqn : eq1; tryfalse.\n  destruct (V_OSTCBNext vl'); tryfalse.\n  destruct H0; substs.\n  auto.\n  split.\n  destruct vltcb2.\n  simpl in *.\n  unfolds in H0.\n  rewrite H1 in H0.\n  destruct (V_OSTCBNext vl'); tryfalse.\n  destruct H0; substs; auto.\n  unfold last in *; fold last in *.\n  auto.\n  unfold vptr_next in *; fold vptr_next in *.\n  destruct H2.\n  exists x.\n  destruct H2.\n  split; auto.\n  unfolds in H0.\n  destruct (V_OSTCBNext vl); tryfalse.\n  destruct (V_OSTCBNext vl'); tryfalse.\n  destruct H0; substs; auto.\n\n  rewrite <- app_comm_cons in H.\n  rewrite <- app_comm_cons.\n  unfold distinct_tcbdllseg_next_ptr_vnull in *.\n  destruct H.\n  unfold distinct_tcbdllseg_next_ptr in *; fold distinct_tcbdllseg_next_ptr in *.\n  pose proof app_cons_not_nil vltcb1 vl vltcb2.\n  pose proof app_cons_not_nil vltcb1 vl' vltcb2.\n  simpljoin.\n  rewrite H3.\n  rewrite H2 in H.\n  destruct (V_OSTCBNext a) eqn: eq1; tryfalse.\n  rewrite H2 in H1.\n  unfold get_last_tcb_ptr in H1.\n  pose proof IHvltcb1 vltcb2 vl vl' v.\n  assert(\n      distinct_tcbdllseg_next_ptr v (vltcb1 ++ vl :: vltcb2) /\\\n      get_last_tcb_ptr (vltcb1 ++ vl :: vltcb2) v = Some Vnull /\\\n      vptr_next v (vltcb1 ++ vl :: vltcb2)\n    ).\n  rewrite H2.\n  destruct H.\n  split; auto.\n  split; auto.\n  rewrite H2 in H4. \n  unfold vptr_next in H4; fold vptr_next in H4.\n  destruct H4.\n  destruct H4.\n  destruct(V_OSTCBNext a); tryfalse.\n  unfold vptr_next; fold vptr_next.\n  inverts eq1.\n  destruct H7.\n  eauto.\n  \n  apply H5 in H6; auto; clear H5.\n  rewrite H3 in H6.\n  destruct H6.\n  destruct H6.\n  split.\n  split; auto.\n  rewrite <- H3 in *.\n  rewrite <- H2 in *.\n  destruct H.\n  clear - H H0.\n  intro.\n  apply H.\n\n  eapply ptr_in_tcbdllseg1_preserv; eauto.\n  eapply same_prev_next_sym; auto.\n  split; auto.\n  unfold vptr_next in *; fold vptr_next in *.\n  rewrite eq1.\n  destruct H4.\n  destruct H4.\n  exists x3.\n  split; auto.\nQed.\n\nLemma get_lasr_tcb_ptr_tick_hold:\n  forall a b c d a' b' c' rtbl rtbl' head x,\n    tcbls_rtbl_timetci_update a rtbl \n                              (Vint32 b) c d =\n    Some (a', rtbl',  b', c') ->\n    get_last_tcb_ptr a (Vptr head) = Some (Vptr x) ->\n    get_last_tcb_ptr a' (Vptr head) = Some (Vptr x).\nProof.\n  induction a;intros.\n  simpl in H.\n  inverts H.\n  simpl in H0;simpl;inverts H0;auto.\n\n  simpl in H.\n  xunfold H.\n\n  symmetry in Htick.\n  destruct a0.\n  simpl.\n  simpl in Htick; inverts Htick.\n  auto.\n  assert (get_last_tcb_ptr (v3 :: a0) (Vptr head) = Some (Vptr x)).\n  clear - H0.\n  simpl in *; auto.\n  lets Hx: IHa Htick H.\n  assert (exists h t, l = h::t).\n  eapply tcbls_rtbl_timetci_update_not_nil in Htick.\n  destruct l; tryfalse.\n  do 2 eexists; eauto.\n  simpljoin1.\n  simpl in Hx.\n  simpl; auto.\n\n  symmetry in Htick.\n  destruct a0.\n  simpl.\n  simpl in Htick; inverts Htick.\n  unfolds in H0; simpl in H0; inverts H0.\n  unfolds; simpl; auto.\n  assert (get_last_tcb_ptr (v1 :: a0) (Vptr head) = Some (Vptr x)).\n  clear - H0.\n  simpl in *; auto.\n  lets Hx: IHa Htick H.\n  assert (exists h t, l0 = h::t).\n  eapply tcbls_rtbl_timetci_update_not_nil in Htick.\n  destruct l0; tryfalse.\n  do 2 eexists; eauto.\n  simpljoin1.\n  simpl in Hx.\n  simpl; auto.\n\n  symmetry in Htick.\n  destruct a0.\n  simpl.\n  simpl in Htick; inverts Htick.\n  unfolds in H0; simpl in H0; inverts H0.\n  unfolds; simpl; auto.\n  assert (get_last_tcb_ptr (v1 :: a0) (Vptr head) = Some (Vptr x)).\n  clear - H0.\n  simpl in *; auto.\n  lets Hx: IHa Htick H.\n  assert (exists h t, l1 = h::t).\n  eapply tcbls_rtbl_timetci_update_not_nil in Htick.\n  destruct l1; tryfalse.\n  do 2 eexists; eauto.\n  simpljoin1.\n  simpl in Hx.\n  simpl; auto.\n\n  symmetry in Htick.\n  destruct a0.\n  simpl.\n  simpl in Htick; inverts Htick.\n  unfolds in H0; simpl in H0; inverts H0.\n  unfolds; simpl; auto.\n  assert (get_last_tcb_ptr (v3 :: a0) (Vptr head) = Some (Vptr x)).\n  clear - H0.\n  simpl in *; auto.\n  lets Hx: IHa Htick H.\n  assert (exists h t, l = h::t).\n  eapply tcbls_rtbl_timetci_update_not_nil in Htick.\n  destruct l; tryfalse.\n  do 2 eexists; eauto.\n  simpljoin1.\n  simpl in Hx.\n  simpl; auto.\nQed.\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/ucos_lib/OSQPostPure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.21039511654084503}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Typing rules and a type inference algorithm for RTL. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Op.\nRequire Import Registers.\nRequire Import Globalenvs.\nRequire Import Values.\nRequire Import Integers.\nRequire Import Events.\nRequire Import RTL.\nRequire Import Conventions.\n\n(** * The type system *)\n\n(** Like Cminor and all intermediate languages, RTL can be equipped with\n  a simple type system that statically guarantees that operations\n  and addressing modes are applied to the right number of arguments\n  and that the arguments are of the correct types.  The type algebra\n  is trivial, consisting of the two types [Tint] (for integers and pointers)\n  and [Tfloat] (for floats).  \n\n  Additionally, we impose that each pseudo-register has the same type\n  throughout the function.  This requirement helps with register allocation,\n  enabling each pseudo-register to be mapped to a single hardware register\n  or stack location of the correct type.\n\n  Finally, we also check that the successors of instructions\n  are valid, i.e. refer to non-empty nodes in the CFG.\n\n  The typing judgement for instructions is of the form [wt_instr f env\n  instr], where [f] is the current function (used to type-check\n  [Ireturn] instructions) and [env] is a typing environment\n  associating types to pseudo-registers.  Since pseudo-registers have\n  unique types throughout the function, the typing environment does\n  not change during type-checking of individual instructions.  One\n  point to note is that we have one polymorphic operator, [Omove],\n  which can work over both integers and floats.\n*)\n\nDefinition regenv := reg -> typ.\n\nSection WT_INSTR.\n\nVariable env: regenv.\nVariable funct: function.\n\nDefinition valid_successor (s: node) : Prop :=\n  exists i, funct.(fn_code)!s = Some i.\n\nInductive wt_instr : instruction -> Prop :=\n  | wt_Inop:\n      forall s,\n      valid_successor s ->\n      wt_instr (Inop s)\n  | wt_Iopmove:\n      forall r1 r s,\n      env r1 = env r ->\n      valid_successor s ->\n      wt_instr (Iop Omove (r1 :: nil) r s)\n  | wt_Iop:\n      forall op args res s,\n      op <> Omove ->\n      (List.map env args, env res) = type_of_operation op ->\n      valid_successor s ->\n      wt_instr (Iop op args res s)\n  | wt_Iload:\n      forall chunk addr args dst s,\n      List.map env args = type_of_addressing addr ->\n      env dst = type_of_chunk chunk ->\n      valid_successor s ->\n      wt_instr (Iload chunk addr args dst s)\n  | wt_Istore:\n      forall chunk addr args src s,\n      List.map env args = type_of_addressing addr ->\n      env src = type_of_chunk chunk ->\n      valid_successor s ->\n      wt_instr (Istore chunk addr args src s)\n  | wt_Icall:\n      forall sig ros args res s,\n      match ros with inl r => env r = Tint | inr s => True end ->\n      List.map env args = sig.(sig_args) ->\n      env res = proj_sig_res sig ->\n      valid_successor s ->\n      wt_instr (Icall sig ros args res s)\n  | wt_Itailcall:\n      forall sig ros args,\n      match ros with inl r => env r = Tint | inr s => True end ->\n      sig.(sig_res) = funct.(fn_sig).(sig_res) ->\n      List.map env args = sig.(sig_args) ->\n      tailcall_possible sig ->\n      wt_instr (Itailcall sig ros args)\n  | wt_Ibuiltin:\n      forall ef args res s,\n      List.map env args = (ef_sig ef).(sig_args) ->\n      env res = proj_sig_res (ef_sig ef) ->\n      arity_ok (ef_sig ef).(sig_args) = true \\/ ef_reloads ef = false ->\n      valid_successor s ->\n      wt_instr (Ibuiltin ef args res s)\n  | wt_Icond:\n      forall cond args s1 s2,\n      List.map env args = type_of_condition cond ->\n      valid_successor s1 ->\n      valid_successor s2 ->\n      wt_instr (Icond cond args s1 s2)\n  | wt_Ijumptable:\n      forall arg tbl,\n      env arg = Tint ->\n      (forall s, In s tbl -> valid_successor s) ->\n      list_length_z tbl * 4 <= Int.max_unsigned ->\n      wt_instr (Ijumptable arg tbl)\n  | wt_Ireturn: \n      forall optres,\n      option_map env optres = funct.(fn_sig).(sig_res) ->\n      wt_instr (Ireturn optres).\n\nEnd WT_INSTR.\n\n(** A function [f] is well-typed w.r.t. a typing environment [env],\n   written [wt_function env f], if all instructions are well-typed,\n   parameters agree in types with the function signature, and\n   parameters are pairwise distinct. *)\n\nRecord wt_function (f: function) (env: regenv): Prop :=\n  mk_wt_function {\n    wt_params:\n      List.map env f.(fn_params) = f.(fn_sig).(sig_args);\n    wt_norepet:\n      list_norepet f.(fn_params);\n    wt_instrs:\n      forall pc instr, \n      f.(fn_code)!pc = Some instr -> wt_instr env f instr;\n    wt_entrypoint:\n      valid_successor f f.(fn_entrypoint)\n}.\n\nInductive wt_fundef: fundef -> Prop :=\n  | wt_fundef_external: forall ef,\n      wt_fundef (External ef)\n  | wt_function_internal: forall f env,\n      wt_function f env ->\n      wt_fundef (Internal f).\n\nDefinition wt_program (p: program): Prop :=\n  forall i f, In (i, Gfun f) (prog_defs p) -> wt_fundef f.\n\n(** * Type inference *)\n\n(** There are several ways to ensure that RTL code is well-typed and\n  to obtain the typing environment (type assignment for pseudo-registers)\n  needed for register allocation.  One is to start with well-typed Cminor\n  code and show type preservation for RTL generation and RTL optimizations.\n  Another is to start with untyped RTL and run a type inference algorithm\n  that reconstructs the typing environment, determining the type of\n  each pseudo-register from its uses in the code.  We follow the second\n  approach.\n\n  We delegate the task of determining the type of each pseudo-register\n  to an external ``oracle'': a function written in Caml and not\n  proved correct.  We verify the returned type environment using\n  the following Coq code, which we will prove correct. *)\n\nParameter infer_type_environment:\n  function -> list (node * instruction) -> option regenv.\n\n(** ** Algorithm to check the correctness of a type environment *)\n\nSection TYPECHECKING.\n\nVariable funct: function.\nVariable env: regenv.\n\nDefinition check_reg (r: reg) (ty: typ): bool :=\n  if typ_eq (env r) ty then true else false.\n\nFixpoint check_regs (rl: list reg) (tyl: list typ) {struct rl}: bool :=\n  match rl, tyl with\n  | nil, nil => true\n  | r1::rs, ty::tys => check_reg r1 ty && check_regs rs tys\n  | _, _ => false\n  end.\n\nDefinition check_op (op: operation) (args: list reg) (res: reg): bool :=\n  let (targs, tres) := type_of_operation op in\n  check_regs args targs && check_reg res tres.\n\nDefinition check_successor (s: node) : bool :=\n  match funct.(fn_code)!s with None => false | Some i => true end.\n\nDefinition check_instr (i: instruction) : bool :=\n  match i with\n  | Inop s =>\n      check_successor s\n  | Iop Omove (arg::nil) res s =>\n      if typ_eq (env arg) (env res) \n      then check_successor s\n      else false\n  | Iop Omove args res s =>\n      false\n  | Iop op args res s =>\n      check_op op args res && check_successor s\n  | Iload chunk addr args dst s =>\n      check_regs args (type_of_addressing addr)\n      && check_reg dst (type_of_chunk chunk)\n      && check_successor s\n  | Istore chunk addr args src s =>\n      check_regs args (type_of_addressing addr)\n      && check_reg src (type_of_chunk chunk)\n      && check_successor s\n  | Icall sig ros args res s =>\n      match ros with inl r => check_reg r Tint | inr s => true end\n      && check_regs args sig.(sig_args)\n      && check_reg res (proj_sig_res sig)\n      && check_successor s\n  | Itailcall sig ros args =>\n      match ros with inl r => check_reg r Tint | inr s => true end\n      && check_regs args sig.(sig_args)\n      && opt_typ_eq sig.(sig_res) funct.(fn_sig).(sig_res)\n      && tailcall_is_possible sig\n  | Ibuiltin ef args res s =>\n      check_regs args (ef_sig ef).(sig_args)\n      && check_reg res (proj_sig_res (ef_sig ef))\n      && (if ef_reloads ef then arity_ok (ef_sig ef).(sig_args) else true)\n      && check_successor s\n  | Icond cond args s1 s2 =>\n      check_regs args (type_of_condition cond)\n      && check_successor s1\n      && check_successor s2\n  | Ijumptable arg tbl =>\n      check_reg arg Tint\n      && List.forallb check_successor tbl\n      && zle (list_length_z tbl * 4) Int.max_unsigned\n  | Ireturn optres =>\n      match optres, funct.(fn_sig).(sig_res) with\n      | None, None => true\n      | Some r, Some t => check_reg r t\n      | _, _ => false\n      end\n  end.\n\nDefinition check_params_norepet (params: list reg): bool :=\n  if list_norepet_dec Reg.eq params then true else false.\n\nFixpoint check_instrs (instrs: list (node * instruction)) : bool :=\n  match instrs with\n  | nil => true\n  | (pc, i) :: rem => check_instr i && check_instrs rem\n  end.\n\n(** ** Correctness of the type-checking algorithm *)\n\nLtac elimAndb :=\n  match goal with\n  | [ H: _ && _ = true |- _ ] =>\n      elim (andb_prop _ _ H); clear H; intros; elimAndb\n  | _ =>\n      idtac\n  end.\n\nLemma check_reg_correct:\n  forall r ty, check_reg r ty = true -> env r = ty.\nProof.\n  unfold check_reg; intros.\n  destruct (typ_eq (env r) ty). auto. discriminate.\nQed.\n\nLemma check_regs_correct:\n  forall rl tyl, check_regs rl tyl = true -> List.map env rl = tyl.\nProof.\n  induction rl; destruct tyl; simpl; intros.\n  auto. discriminate. discriminate.\n  elimAndb.\n  rewrite (check_reg_correct _ _ H). rewrite (IHrl tyl H0). auto.\nQed.\n\nLemma check_op_correct:\n  forall op args res,\n  check_op op args res = true ->\n  (List.map env args, env res) = type_of_operation op.\nProof.\n  unfold check_op; intros.\n  destruct (type_of_operation op) as [targs tres].\n  elimAndb. \n  rewrite (check_regs_correct _ _ H).\n  rewrite (check_reg_correct _ _ H0).\n  auto.\nQed.\n\nLemma check_successor_correct:\n  forall s,\n  check_successor s = true -> valid_successor funct s.\nProof.\n  intro; unfold check_successor, valid_successor.\n  destruct (fn_code funct)!s; intro.\n  exists i; auto.\n  discriminate.\nQed.\n\nLemma check_instr_correct:\n  forall i, check_instr i = true -> wt_instr env funct i.\nProof.\n  unfold check_instr; intros; destruct i; elimAndb.\n  (* nop *)\n  constructor. apply check_successor_correct; auto.\n  (* op *)\n  destruct o; elimAndb;\n  try (apply wt_Iop; [ congruence\n                     | apply check_op_correct; auto\n                     | apply check_successor_correct; auto ]).\n  destruct l; try discriminate. destruct l; try discriminate.\n  destruct (typ_eq (env r0) (env r)); try discriminate.\n  apply wt_Iopmove; auto. apply check_successor_correct; auto.\n  (* load *)\n  constructor. apply check_regs_correct; auto. apply check_reg_correct; auto.\n  apply check_successor_correct; auto.\n  (* store *)\n  constructor. apply check_regs_correct; auto. apply check_reg_correct; auto.\n  apply check_successor_correct; auto.\n  (* call *)\n  constructor.\n  destruct s0; auto. apply check_reg_correct; auto.\n  apply check_regs_correct; auto.\n  apply check_reg_correct; auto.\n  apply check_successor_correct; auto.\n  (* tailcall *)\n  constructor.\n  destruct s0; auto. apply check_reg_correct; auto.\n  eapply proj_sumbool_true; eauto.\n  apply check_regs_correct; auto.\n  apply tailcall_is_possible_correct; auto.\n  (* builtin *)\n  constructor.\n  apply check_regs_correct; auto.\n  apply check_reg_correct; auto.\n  auto.\n  destruct (ef_reloads e); auto. \n  apply check_successor_correct; auto.\n  (* cond *)\n  constructor. apply check_regs_correct; auto.\n  apply check_successor_correct; auto.\n  apply check_successor_correct; auto.\n  (* jumptable *)\n  constructor. apply check_reg_correct; auto.\n  rewrite List.forallb_forall in H1. intros. apply check_successor_correct; auto.\n  eapply proj_sumbool_true. eauto.  \n  (* return *)\n  constructor. \n  destruct o; simpl; destruct funct.(fn_sig).(sig_res); try discriminate.\n  rewrite (check_reg_correct _ _ H); auto.\n  auto.\nQed.\n\nLemma check_instrs_correct:\n  forall instrs,\n  check_instrs instrs = true ->\n  forall pc i, In (pc, i) instrs -> wt_instr env funct i.\nProof.\n  induction instrs; simpl; intros.\n  elim H0.\n  destruct a as [pc' i']. elimAndb. \n  elim H0; intro.\n  inversion H2; subst pc' i'. apply check_instr_correct; auto.\n  eauto.\nQed.\n\nEnd TYPECHECKING.\n\n(** ** The type inference function **)\n\nOpen Scope string_scope.\n\nDefinition type_function (f: function): res regenv :=\n  let instrs := PTree.elements f.(fn_code) in\n  match infer_type_environment f instrs with\n  | None => Error (msg \"RTL type inference error\")\n  | Some env =>\n      if check_regs env f.(fn_params) f.(fn_sig).(sig_args)\n      && check_params_norepet f.(fn_params)\n      && check_instrs f env instrs\n      && check_successor f f.(fn_entrypoint)\n      then OK env\n      else Error (msg \"RTL type checking error\")\n  end.\n\nLemma type_function_correct:\n  forall f env,\n  type_function f = OK env ->\n  wt_function f env.\nProof.\n  unfold type_function; intros until env.\n  set (instrs := PTree.elements f.(fn_code)).\n  case (infer_type_environment f instrs).\n  intro env'. \n  caseEq (check_regs env' f.(fn_params) f.(fn_sig).(sig_args)); intro; simpl; try congruence.\n  caseEq (check_params_norepet f.(fn_params)); intro; simpl; try congruence.\n  caseEq (check_instrs f env' instrs); intro; simpl; try congruence.\n  caseEq (check_successor f (fn_entrypoint f)); intro; simpl; try congruence.\n  intro EQ; inversion EQ; subst env'.\n  constructor. \n  apply check_regs_correct; auto.\n  unfold check_params_norepet in H0. \n  destruct (list_norepet_dec Reg.eq (fn_params f)). auto. discriminate.\n  intros. eapply check_instrs_correct. eauto. \n  unfold instrs. apply PTree.elements_correct. eauto.\n  apply check_successor_correct. auto.\n  congruence.\nQed.\n\n(** * Type preservation during evaluation *)\n\n(** The type system for RTL is not sound in that it does not guarantee\n  progress: well-typed instructions such as [Icall] can fail because\n  of run-time type tests (such as the equality between callee and caller's\n  signatures).  However, the type system guarantees a type preservation\n  property: if the execution does not fail because of a failed run-time\n  test, the result values and register states match the static\n  typing assumptions.  This preservation property will be useful\n  later for the proof of semantic equivalence between [Linear] and [Mach].\n  Even though we do not need it for [RTL], we show preservation for [RTL]\n  here, as a warm-up exercise and because some of the lemmas will be\n  useful later. *)\n\nDefinition wt_regset (env: regenv) (rs: regset) : Prop :=\n  forall r, Val.has_type (rs#r) (env r).\n\nLemma wt_regset_assign:\n  forall env rs v r,\n  wt_regset env rs ->\n  Val.has_type v (env r) ->\n  wt_regset env (rs#r <- v).\nProof.\n  intros; red; intros. \n  rewrite Regmap.gsspec.\n  case (peq r0 r); intro.\n  subst r0. assumption.\n  apply H.\nQed.\n\nLemma wt_regset_list:\n  forall env rs,\n  wt_regset env rs ->\n  forall rl, Val.has_type_list (rs##rl) (List.map env rl).\nProof.\n  induction rl; simpl.\n  auto.\n  split. apply H. apply IHrl.\nQed.  \n\nLemma wt_init_regs:\n  forall env rl args,\n  Val.has_type_list args (List.map env rl) ->\n  wt_regset env (init_regs args rl).\nProof.\n  induction rl; destruct args; simpl; intuition.\n  red; intros. rewrite Regmap.gi. simpl; auto. \n  apply wt_regset_assign; auto.\nQed.\n\nInductive wt_stackframes: list stackframe -> option typ -> Prop :=\n  | wt_stackframes_nil:\n      wt_stackframes nil (Some Tint)\n  | wt_stackframes_cons:\n      forall s res f sp pc rs env tyres,\n      wt_function f env ->\n      wt_regset env rs ->\n      env res = match tyres with None => Tint | Some t => t end ->\n      wt_stackframes s (sig_res (fn_sig f)) ->\n      wt_stackframes (Stackframe res f sp pc rs :: s) tyres.\n\nInductive wt_state: state -> Prop :=\n  | wt_state_intro:\n      forall s f sp pc rs m env\n        (WT_STK: wt_stackframes s (sig_res (fn_sig f)))\n        (WT_FN: wt_function f env)\n        (WT_RS: wt_regset env rs),\n      wt_state (State s f sp pc rs m)\n  | wt_state_call:\n      forall s f args m,\n      wt_stackframes s (sig_res (funsig f)) ->\n      wt_fundef f ->\n      Val.has_type_list args (sig_args (funsig f)) ->\n      wt_state (Callstate s f args m)\n  | wt_state_return:\n      forall s v m tyres,\n      wt_stackframes s tyres ->\n      Val.has_type v (match tyres with None => Tint | Some t => t end) ->\n      wt_state (Returnstate s v m).\n\nSection SUBJECT_REDUCTION.\n\nVariable p: program.\n\nHypothesis wt_p: wt_program p.\n\nLet ge := Genv.globalenv p.\n\nLemma subject_reduction:\n  forall st1 t st2, step ge st1 t st2 ->\n  forall (WT: wt_state st1), wt_state st2.\nProof.\n  induction 1; intros; inv WT;\n  try (generalize (wt_instrs _ _ WT_FN pc _ H);\n       intro WT_INSTR;\n       inv WT_INSTR).\n  (* Inop *)\n  econstructor; eauto.\n  (* Iop *)\n  econstructor; eauto.\n  apply wt_regset_assign. auto. \n  simpl in H0. inv H0. rewrite <- H3. apply WT_RS.\n  econstructor; eauto.\n  apply wt_regset_assign. auto.\n  replace (env res) with (snd (type_of_operation op)).\n  eapply type_of_operation_sound; eauto.\n  rewrite <- H6. reflexivity.\n  (* Iload *)\n  econstructor; eauto.\n  apply wt_regset_assign. auto. rewrite H8. \n  eapply type_of_chunk_correct; eauto.\n  (* Istore *)\n  econstructor; eauto.\n  (* Icall *)\n  assert (wt_fundef fd).\n    destruct ros; simpl in H0.\n    pattern fd. apply Genv.find_funct_prop with fundef unit p (rs#r).\n    exact wt_p. exact H0. \n    caseEq (Genv.find_symbol ge i); intros; rewrite H1 in H0.\n    pattern fd. apply Genv.find_funct_ptr_prop with fundef unit p b.\n    exact wt_p. exact H0.\n    discriminate.\n  econstructor; eauto.\n  econstructor; eauto.\n  rewrite <- H7. apply wt_regset_list. auto.\n  (* Itailcall *)\n  assert (wt_fundef fd).\n    destruct ros; simpl in H0.\n    pattern fd. apply Genv.find_funct_prop with fundef unit p (rs#r).\n    exact wt_p. exact H0. \n    caseEq (Genv.find_symbol ge i); intros; rewrite H1 in H0.\n    pattern fd. apply Genv.find_funct_ptr_prop with fundef unit p b.\n    exact wt_p. exact H0.\n    discriminate.\n  econstructor; eauto.\n  rewrite H6; auto.\n  rewrite <- H7. apply wt_regset_list. auto.\n  (* Ibuiltin *)\n  econstructor; eauto.\n  apply wt_regset_assign. auto. \n  rewrite H6. eapply external_call_well_typed; eauto. \n  (* Icond *)\n  econstructor; eauto.\n  (* Ijumptable *)\n  econstructor; eauto.\n  (* Ireturn *)\n  econstructor; eauto. \n  destruct or; simpl in *.\n  rewrite <- H2. apply WT_RS. exact I.\n  (* internal function *)\n  simpl in *. inv H5. inversion H1; subst.  \n  econstructor; eauto.\n  apply wt_init_regs; auto. rewrite wt_params0; auto.\n  (* external function *)\n  simpl in *. inv H5. \n  econstructor; eauto. \n  change (Val.has_type res (proj_sig_res (ef_sig ef))).\n  eapply external_call_well_typed; eauto.\n  (* return *)\n  inv H1. econstructor; eauto. \n  apply wt_regset_assign; auto. congruence. \nQed.\n\nEnd SUBJECT_REDUCTION.\n", "meta": {"author": "academic-archive", "repo": "pldi14-veristack", "sha": "9edcd8752ae2e1e6377bfb33589a377cc39c04ca", "save_path": "github-repos/coq/academic-archive-pldi14-veristack", "path": "github-repos/coq/academic-archive-pldi14-veristack/pldi14-veristack-9edcd8752ae2e1e6377bfb33589a377cc39c04ca/qcompcert/backend/RTLtyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21037225816046312}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import sha.sha.\nRequire Import sha.SHA256.\nRequire Import sha.spec_sha.\nRequire Import sha.sha_lemmas.\nRequire Import sha.bdo_lemmas.\nLocal Open Scope logic.\n\nLemma rearrange_aux:\n forall h f c k l,\n Int.add (Int.add (Int.add (Int.add h f) c) k) l =\nInt.add (Int.add (Int.add (Int.add l h) f) c) k.\nProof.\nintros.\nrewrite <- (Int.add_commut l).\nrepeat rewrite (Int.add_assoc h).\nrewrite <- (Int.add_assoc l).\nrepeat rewrite (Int.add_assoc (Int.add l h)).\nreflexivity.\nQed.\n\nLemma loop1_aux_lemma1:\n  forall i b,\n  (0 <= i < Zlength b) ->\n  Zlength b <= 16 ->\n  upd_Znth i\n          (map Vint (sublist 0 i b) ++ list_repeat (Z.to_nat (16 - i)) Vundef)\n          (Vint (Znth i b))\n  =  map Vint (sublist 0 (i+1) b) ++ list_repeat (Z.to_nat (16 - (i+1))) Vundef.\nProof.\nintros.\nunfold upd_Znth.\nautorewrite with sublist.\nrewrite (sublist_split 0 i (i+1)) by omega.\nrewrite map_app.\nrewrite app_ass.\nf_equal.\nrewrite (sublist_len_1 i) by omega.\nsimpl.\nautorewrite with sublist.\nf_equal. f_equal. f_equal. omega.\nQed.\n\nDefinition block_data_order_loop1 :=\n Ssequence\n (Sset _i (Econst_int (Int.repr 0) tint))\n   (nth 0 (loops (fn_body f_sha256_block_data_order)) Sskip).\n\nLemma sha256_block_data_order_loop1_proof:\n  forall (Espec : OracleKind) (sh: share)\n     (b: list int) ctx (data: val) (regs: list int) gv Xv\n     (Hregs: length regs = 8%nat)\n     (Hsh: readable_share sh),\n     Zlength b = LBLOCKz ->\n     semax (func_tycontext f_sha256_block_data_order Vprog Gtot nil)\n  (PROP  ()\n   LOCAL  (temp _a (Vint (nthi regs 0)); temp _b (Vint (nthi regs 1));\n                temp _c (Vint (nthi regs 2)); temp _d (Vint (nthi regs 3));\n                temp _e (Vint (nthi regs 4)); temp _f (Vint (nthi regs 5));\n                temp _g (Vint (nthi regs 6)); temp _h (Vint (nthi regs 7));\n                temp _data data; temp _ctx ctx; temp _in data;\n                gvars gv; lvar _X (tarray tuint LBLOCKz) Xv)\n   SEP  (data_at_ Tsh (tarray tuint 16) Xv;\n           data_block sh (intlist_to_bytelist b) data; K_vector gv))\n  block_data_order_loop1\n  (normal_ret_assert\n    (PROP ()\n     LOCAL(temp _ctx ctx; temp _i (Vint (Int.repr LBLOCKz));\n                temp _a (Vint (nthi (Round regs (nthi b) (LBLOCKz - 1)) 0));\n                temp _b (Vint (nthi (Round regs (nthi b) (LBLOCKz - 1)) 1));\n                temp _c (Vint (nthi (Round regs (nthi b) (LBLOCKz - 1)) 2));\n                temp _d (Vint (nthi (Round regs (nthi b) (LBLOCKz - 1)) 3));\n                temp _e (Vint (nthi (Round regs (nthi b) (LBLOCKz - 1)) 4));\n                temp _f (Vint (nthi (Round regs (nthi b) (LBLOCKz - 1)) 5));\n                temp _g (Vint (nthi (Round regs (nthi b) (LBLOCKz - 1)) 6));\n                temp _h (Vint (nthi (Round regs (nthi b) (LBLOCKz - 1)) 7));\n                gvars gv; lvar _X (tarray tuint LBLOCKz) Xv)\n     SEP (K_vector gv;\n            data_at Tsh (tarray tuint LBLOCKz) (map Vint b) Xv;\n            data_block sh (intlist_to_bytelist b) data))).\nProof.\nunfold block_data_order_loop1.\nintros.\nsimpl nth.\nabbreviate_semax.\nassert (LBE := LBLOCKz_eq).\nforward_for_simple_bound 16\n   (EX i:Z,\n    PROP ()\n    LOCAL  (temp _ctx ctx;\n                 temp _data  (offset_val (i*4) data);\n                 temp _a (Vint (nthi (Round regs (nthi b) (i - 1)) 0));\n                 temp _b (Vint (nthi (Round regs (nthi b) (i - 1)) 1));\n                 temp _c (Vint (nthi (Round regs (nthi b) (i - 1)) 2));\n                 temp _d (Vint (nthi (Round regs (nthi b) (i - 1)) 3));\n                 temp _e (Vint (nthi (Round regs (nthi b) (i - 1)) 4));\n                 temp _f (Vint (nthi (Round regs (nthi b) (i - 1)) 5));\n                 temp _g (Vint (nthi (Round regs (nthi b) (i - 1)) 6));\n                 temp _h (Vint (nthi (Round regs (nthi b) (i - 1)) 7));\n                 lvar _X (tarray tuint LBLOCKz) Xv;\n                 gvars gv)\n     SEP (K_vector gv;\n       data_at Tsh (tarray tuint LBLOCKz)\n           (map Vint (sublist 0 i b) ++ list_repeat (Z.to_nat (16-i)) Vundef)\n            Xv;\n       data_block sh (intlist_to_bytelist b) data)).\n* (* precondition of loop entails the loop invariant *)\n rewrite Round_equation. rewrite if_true by (compute; auto).\n entailer!. simpl; cancel.\n* (* loop body & loop condition preserves loop invariant *)\nassert_PROP (data_block sh (intlist_to_bytelist b) data =\n   array_at sh (tarray tuchar (Zlength b * 4)) [] 0 (i * 4)\n       (sublist 0 (i * 4) (map Vubyte (intlist_to_bytelist b)))\n       data *\n   data_at sh (tarray tuchar 4)\n        (map Vubyte (sublist (i * 4) ((i + 1) * 4) (intlist_to_bytelist b)))\n        (offset_val (i * 4) data) *\n   array_at sh (tarray tuchar (Zlength b * 4)) [] (i * 4 + 4)\n       (Zlength b * 4)\n       (sublist (4 + i * 4) (Zlength b * 4)\n          (map Vubyte (intlist_to_bytelist b))) data). {\n entailer!.\n unfold data_block.\n unfold data_at at 1.\n   erewrite field_at_Tarray\n   by (try reflexivity; auto; autorewrite with sublist; Omega1).\n   rewrite (split2_array_at _ _ _ 0 (i*4)) by (autorewrite with sublist; omega).\n   rewrite (split2_array_at _ _ _ (i*4) (i*4+4)) by (autorewrite with sublist; omega).\n   autorewrite with sublist.\n  rewrite <- !sepcon_assoc.\n  f_equal. f_equal.\n  rewrite Zlength_intlist_to_bytelist in H5.\n  rewrite array_at_data_at' by (auto with field_compatible; omega).\n  simpl.\n  autorewrite with sublist.\n  fold (tarray tuchar 4). f_equal.\n   rewrite <- sublist_map.\n  rewrite Z.add_comm, Z.mul_add_distr_r.\n  reflexivity.\n rewrite field_address0_offset by auto with field_compatible.\n  f_equal. f_equal. simpl. omega.\n }\nforward_call (* l = __builtin_read32_reversed(_data) *)\n      (offset_val (i*4) data, sh,\n         sublist (i*4) ((i+1)*4) (intlist_to_bytelist b)).\n entailer!.\n rewrite H1; cancel.\n autorewrite with sublist; omega.\ngather_SEP 3 0 4.\n match goal with |- context [SEPx (?A::_)] =>\n  replace A with (data_block sh (intlist_to_bytelist b) data)\n    by (rewrite H1,<- !sepcon_assoc; auto)\n end.\n clear H1.\nrewrite <- Znth_big_endian_integer by omega.\nforward. (* data := data + 4; *)\nrewrite LBE.\nforward. (* X[i]=l; *)\nsimpl.\nrewrite loop1_aux_lemma1 by Omega1.\n(* 1,506,948 1,110,852 *)\n(* 1,506,948 1,134,576 *)\nunfold K_vector.\nassert (i < Zlength K256)\n  by (change (Zlength K256) with 64; omega).\nforward.  (* Ki=K256[i]; *)\n(* 1,811,028 1,406,332 *)\nautorewrite with sublist.\nsubst POSTCONDITION; unfold abbreviate.\nreplace (i + 1 - 1)%Z with i by omega.\nrewrite (Round_equation _ _ i).\nrewrite if_false by omega.\nforget (nthi b) as M.\nreplace (M i) with (W M i)\n  by (rewrite W_equation; rewrite if_true by omega; auto).\nassert_PROP (isptr data) as H3 by entailer!.\nchange (data_at Tsh (tarray tuint  (Zlength K256)) (map Vint K256) (gv _K256)) with (K_vector gv).\nchange (tarray tuint LBLOCKz) with (tarray tuint 16).\nmatch goal with |- semax _ (PROPx _ (LOCALx _ (SEPx ?R))) _ _ =>\n  semax_frame [  ] R\nend.\nclear b H1 H.\nforget (nthi K256 i) as k.\nforget (W M i) as w.\nassert (length (Round regs M (i - 1)) = 8)%nat\n  by (apply length_Round; auto).\nforget (Round regs M (i - 1)) as regs'.\nchange 16%nat with LBLOCK.\ndestruct regs' as [ | a [ | b [ | c [ | d [ | e [ | f [ | g [ | h [ | ]]]]]]]]]; inv H.\nforward. (* T1 = l + h + Sigma1(e) + Ch(e,f,g) + Ki; *)\nrewrite <- Sigma_1_eq, <- Ch_eq, rearrange_aux.\nforward. (* T2 = Sigma0(a) + Maj(a,b,c); *)\n rewrite <- Sigma_0_eq, <- Maj_eq.\nunfold nthi; simpl nth.\ndo 8 forward.\nentailer!.\nunfold nthi; simpl nth.\nsplit3.\n+ f_equal. omega.\n+ f_equal.  f_equal.\n  rewrite rearrange_aux. rewrite rearrange_aux. auto.\n+ f_equal. f_equal.\n   rewrite (Int.add_commut (Int.add k _)).\n   do 5 rewrite Int.add_assoc.\n   f_equal. rewrite (Int.add_commut (Int.add k _)).\n   rewrite <- Int.add_assoc. auto.\n* (* loop invariant & not test implies postcondition *)\nautorewrite with sublist.\nentailer!.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/sha/verif_sha_bdo4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21037225816046312}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import MemoryFacts.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import MemoryReorder.\nRequire Import MemoryMerge.\nRequire Import FulfillStep.\nRequire Import PromiseConsistent.\n\nRequire Import ReorderTView.\n\nSet Implicit Arguments.\n\n\nLemma reorder_read_promise_diff\n      loc1 ts1 val1 released1 ord1\n      loc2 from2 to2 msg2 kind2\n      lc0 mem0\n      lc1\n      lc2 mem2\n      (DIFF: (loc1, ts1) <> (loc2, to2))\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.promise_step lc1 mem0 loc2 from2 to2 msg2 lc2 mem2 kind2):\n  exists lc1',\n    <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc1' mem2 kind2>> /\\\n    <<STEP2: Local.read_step lc1' mem2 loc1 ts1 val1 released1 ord1 lc2>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit MemoryFacts.promise_get1_diff; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma lower_closed_timemap_inv\n      tm\n      mem1 loc from to msg1 msg2 mem2\n      (CLOSED: Memory.closed_timemap tm mem2)\n      (LOWER: Memory.lower mem1 loc from to msg1 msg2 mem2):\n  Memory.closed_timemap tm mem1.\nProof.\n  ii. specialize (CLOSED loc0). des.\n  revert CLOSED. erewrite Memory.lower_o; eauto. condtac; ss; eauto.\n  des. subst. i. inv CLOSED.\n  exploit Memory.lower_get0; eauto. i. des. inv MSG_LE. eauto.\nQed.\n\nLemma lower_closed_view_inv\n      view\n      mem1 loc from to msg1 msg2 mem2\n      (CLOSED: Memory.closed_view view mem2)\n      (LOWER: Memory.lower mem1 loc from to msg1 msg2 mem2):\n  Memory.closed_view view mem1.\nProof.\n  inv CLOSED. econs; eauto using lower_closed_timemap_inv.\nQed.\n\nLemma lower_closed_message_inv\n      msg\n      mem1 loc from to msg1 msg2 mem2\n      (CLOSED: Memory.closed_message msg mem2)\n      (LOWER: Memory.lower mem1 loc from to msg1 msg2 mem2):\n  Memory.closed_message msg mem1.\nProof.\n  inv CLOSED; eauto.\n  econs. inv CLOSED0; eauto.\n  econs. eauto using lower_closed_view_inv.\nQed.\n\nLemma write_na_lower_closed_message_inv\n      msg\n      ts promises1 mem1 loc from to val promises2 mem2 msgs kinds kind\n      (CLOSED: Memory.closed_message msg mem2)\n      (KINDS: List.Forall Memory.op_kind_is_lower kinds)\n      (KIND: Memory.op_kind_is_lower kind)\n      (WRITE: Memory.write_na ts promises1 mem1 loc from to val promises2 mem2 msgs kinds kind):\n  Memory.closed_message msg mem1.\nProof.\n  induction WRITE.\n  - inv WRITE. inv PROMISE; ss.\n    eauto using lower_closed_message_inv.\n  - inv KINDS. exploit IHWRITE; eauto. i.\n    inv WRITE_EX. inv PROMISE; ss.\n    eauto using lower_closed_message_inv.\nQed.\n\nLemma reorder_memory_write_lower_promise\n      promises0 mem0 loc1 from1 to1 msg1 promises1 mem1 kind1\n      loc2 from2 to2 msg2 promises2 mem2 kind2\n      (LE: Memory.le promises0 mem0)\n      (KIND1: Memory.op_kind_is_lower kind1)\n      (WRITE: Memory.write promises0 mem0 loc1 from1 to1 msg1 promises1 mem1 kind1)\n      (PROMISE: Memory.promise promises1 mem1 loc2 from2 to2 msg2 promises2 mem2 kind2):\n  exists promises1' mem1',\n    (<<PROMISE: Memory.promise promises0 mem0 loc2 from2 to2 msg2 promises1' mem1' kind2>>) /\\\n    (<<WRITE: Memory.write promises1' mem1' loc1 from1 to1 msg1 promises2 mem2 kind1>>).\nProof.\n  inv WRITE.\n  destruct (classic ((loc1, to1) = (loc2, to2))).\n  { inv H.\n    exploit Memory.promise_get0; try exact PROMISE0.\n    { destruct kind1; ss. }\n    i. des.\n    exploit Memory.remove_get0; eauto. i. des. clear GET.\n    inv PROMISE.\n    - exploit Memory.add_get0; try exact MEM. i. des. congr.\n    - exploit Memory.split_get0; try exact MEM. i. des. congr.\n    - exploit Memory.lower_get0; try exact PROMISES. i. des. congr.\n    - exploit Memory.remove_get0; try exact PROMISES. i. des. congr.\n  }\n\n  hexploit Memory.promise_le; try apply LE; eauto. i. des.\n  exploit MemoryReorder.remove_promise; try exact REMOVE; eauto. i. des.\n  inv PROMISE0; ss. inv x0; ss.\n  { exploit MemoryReorder.lower_add; try exact PROMISES; eauto. i. des.\n    exploit MemoryReorder.lower_add; try exact MEM; eauto. i. des.\n    esplits; eauto. econs; eauto.\n    i. exploit Memory.lower_get1; try exact GET; eauto. i. des. eauto.\n  }\n  { exploit MemoryReorder.lower_split; try exact PROMISES; eauto. i. des.\n    exploit MemoryReorder.lower_split; try exact MEM; eauto. i. des.\n    unguard; des; try congr.\n    { inv FROM1. inv FROM0. inv PROMISE; ss.\n      exploit Memory.remove_get0; eauto. i. des.\n      exploit Memory.split_get0; try exact PROMISES1; eauto. i. des.\n      congr.\n    }\n    inv FROM3. inv FROM2.\n    esplits; eauto.\n  }\n  { exploit MemoryReorder.lower_lower; try exact PROMISES; eauto. i.\n    exploit MemoryReorder.lower_lower; try exact MEM; eauto. i.\n    des; subst; try congr.\n    esplits; eauto.\n  }\n  { exploit MemoryReorder.lower_remove; try exact PROMISES; eauto. i. des.\n    exploit MemoryReorder.lower_remove; try exact MEM; eauto. i. des.\n    esplits; eauto.\n  }\nQed.  \n\nLemma reorder_write_lower_promise\n      loc1 from1 to1 val1 releasedm1 released1 ord1 kind1\n      loc2 from2 to2 msg2 kind2\n      lc0 sc0 mem0\n      lc1 sc1 mem1\n      lc2 mem2\n      (WF0: Local.wf lc0 mem0)\n      (KIND1: Memory.op_kind_is_lower kind1)\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (STEP1: Local.write_step lc0 sc0 mem0 loc1 from1 to1 val1 releasedm1 released1 ord1 lc1 sc1 mem1 kind1)\n      (STEP2: Local.promise_step lc1 mem1 loc2 from2 to2 msg2 lc2 mem2 kind2):\n  exists lc1' mem1',\n    (<<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc1' mem1' kind2>>) /\\\n    (<<STEP2: Local.write_step lc1' sc0 mem1' loc1 from1 to1 val1 releasedm1 released1 ord1 lc2 sc1 mem2 kind1>>).\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit reorder_memory_write_lower_promise; try apply WF0; eauto. i. des.\n  esplits.\n  - econs; eauto.\n    inv WRITE0. inv PROMISE1; ss.\n    eapply lower_closed_message_inv; eauto.\n  - econs; eauto. destruct ord1; ss.\nQed.\n\nLemma reorder_memory_write_na_lower_promise\n      ts promises0 mem0 loc1 from1 to1 val1 promises1 mem1 msgs1 kinds1 kind1\n      loc2 from2 to2 msg2 promises2 mem2 kind2\n      (LE: Memory.le promises0 mem0)\n      (KINDS1: List.Forall Memory.op_kind_is_lower kinds1)\n      (KIND1: Memory.op_kind_is_lower kind1)\n      (WRITE: Memory.write_na ts promises0 mem0 loc1 from1 to1 val1 promises1 mem1 msgs1 kinds1 kind1)\n      (PROMISE: Memory.promise promises1 mem1 loc2 from2 to2 msg2 promises2 mem2 kind2):\n  exists promises1' mem1',\n    (<<PROMISE: Memory.promise promises0 mem0 loc2 from2 to2 msg2 promises1' mem1' kind2>>) /\\\n    (<<WRITE: Memory.write_na ts promises1' mem1' loc1 from1 to1 val1 promises2 mem2 msgs1 kinds1 kind1>>).\nProof.\n  induction WRITE.\n  { exploit reorder_memory_write_lower_promise; eauto. i. des.\n    esplits; eauto.\n  }\n  inv KINDS1.\n  hexploit Memory.write_le; eauto. i. des.\n  exploit IHWRITE; eauto. i. des.\n  exploit reorder_memory_write_lower_promise; try exact WRITE_EX; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_write_na_lower_promise\n      loc1 from1 to1 val1 ord1 msgs1 kinds1 kind1\n      loc2 from2 to2 msg2 kind2\n      lc0 sc0 mem0\n      lc1 sc1 mem1\n      lc2 mem2\n      (WF0: Local.wf lc0 mem0)\n      (KINDS1: List.Forall Memory.op_kind_is_lower kinds1)\n      (KIND1: Memory.op_kind_is_lower kind1)\n      (ORD1: Ordering.le ord1 Ordering.relaxed)\n      (STEP1: Local.write_na_step lc0 sc0 mem0 loc1 from1 to1 val1 ord1\n                                  lc1 sc1 mem1 msgs1 kinds1 kind1)\n      (STEP2: Local.promise_step lc1 mem1 loc2 from2 to2 msg2 lc2 mem2 kind2):\n  exists lc1' mem1',\n    (<<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc1' mem1' kind2>>) /\\\n    (<<STEP2: Local.write_na_step lc1' sc0 mem1' loc1 from1 to1 val1 ord1\n                                  lc2 sc1 mem2 msgs1 kinds1 kind1>>).\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit reorder_memory_write_na_lower_promise; try apply WF0; eauto. i. des.\n  esplits.\n  - econs; eauto.\n    eapply write_na_lower_closed_message_inv; eauto.\n  - econs; eauto.\nQed.\n\nLemma reorder_update_lower_promise_diff\n      lc0 sc0 mem0\n      loc1 ts1 val1 released1 ord1 lc1\n      from2 to2 val2 released2 ord2 lc2 sc2 mem2 kind2\n      loc3 from3 to3 msg3 lc3 mem3 kind3\n      (DIFF: (loc1, ts1) <> (loc3, to3))\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (KIND2: Memory.op_kind_is_lower kind2)\n      (ORD2: Ordering.le ord2 Ordering.relaxed)\n      (STEP1: Local.read_step lc0 mem0 loc1 ts1 val1 released1 ord1 lc1)\n      (STEP2: Local.write_step lc1 sc0 mem0 loc1 from2 to2 val2 released1 released2 ord2 lc2 sc2 mem2 kind2)\n      (STEP3: Local.promise_step lc2 mem2 loc3 from3 to3 msg3 lc3 mem3 kind3):\n  exists lc1' mem1' lc2',\n    (<<STEP1: Local.promise_step lc0 mem0 loc3 from3 to3 msg3 lc1' mem1' kind3>>) /\\\n    (<<STEP2: Local.read_step lc1' mem1' loc1 ts1 val1 released1 ord1 lc2'>>) /\\\n    (<<STEP3: Local.write_step lc2' sc0 mem1' loc1 from2 to2 val2 released1 released2 ord2 lc3 sc2 mem3 kind2>>).\nProof.\n  exploit Local.read_step_future; eauto. i. des.\n  exploit reorder_write_lower_promise; try exact STEP2; eauto. i. des.\n  exploit reorder_read_promise_diff; try exact STEP1; eauto. i. des.\n  esplits; eauto.\nQed.\n\nLemma reorder_fence_promise\n      ordr1 ordw1\n      loc2 from2 to2 msg2\n      lc0 sc0 mem0\n      lc1 sc1\n      lc2 mem2\n      kind\n      (ORDW1: Ordering.le ordw1 Ordering.relaxed)\n      (STEP1: Local.fence_step lc0 sc0 ordr1 ordw1 lc1 sc1)\n      (STEP2: Local.promise_step lc1 mem0 loc2 from2 to2 msg2 lc2 mem2 kind):\n  exists lc1',\n    <<STEP1: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc1' mem2 kind>> /\\\n    <<STEP2: Local.fence_step lc1' sc0 ordr1 ordw1 lc2 sc1>>.\nProof.\n  inv STEP1. inv STEP2. ss.\n  esplits.\n  - econs; eauto.\n  - econs; eauto.\n    + s. i. destruct ordw1; inv ORDW1; inv H.\n    + s. i. destruct ordw1; inv ORDW1; inv H.\nQed.\n\nLemma reorder_is_racy_promise\n      loc1 to1 ord1\n      loc2 from2 to2 msg2 kind2\n      lc0 mem0\n      lc2 mem2\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.is_racy lc0 mem0 loc1 to1 ord1)\n      (STEP2: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc2 mem2 kind2):\n  <<STEP: Local.is_racy lc2 mem2 loc1 to1 ord1>>.\nProof.\n  inv STEP1. inv STEP2.\n  exploit Memory.promise_future; try exact PROMISE; try apply WF0; eauto. i. des.\n  exploit Memory.future_get1; eauto. i. des.\n  econs; eauto; ss.\n  - destruct (Memory.get loc1 to1 promises2) as [[]|] eqn:X; ss.\n    revert X. inv PROMISE; ss.\n    + erewrite Memory.add_o; eauto. condtac; ss; try congr.\n      i. des. inv X.\n      exploit Memory.add_get0; try exact MEM. i. des. congr.\n    + erewrite Memory.split_o; eauto. repeat (condtac; ss); try congr.\n      * i. des. inv X.\n        exploit Memory.split_get0; try exact MEM. i. des. congr.\n      * guardH o. i. des. inv X.\n        exploit Memory.split_get0; try exact PROMISES. i. des. congr.\n    + erewrite Memory.lower_o; eauto. condtac; ss; try congr.\n      i. des. inv X.\n      exploit Memory.lower_get0; try exact PROMISES. i. des. congr.\n    + erewrite Memory.remove_o; eauto. condtac; ss; try congr.\n  - inv MSG_LE; ss.\n  - i. exploit MSG2; eauto. i. subst. inv MSG_LE. ss.\nQed.\n\nLemma reorder_racy_read_promise\n      loc1 to1 val1 ord1\n      loc2 from2 to2 msg2 kind2\n      lc0 mem0\n      lc2 mem2\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.racy_read_step lc0 mem0 loc1 to1 val1 ord1)\n      (STEP2: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc2 mem2 kind2):\n  <<STEP: Local.racy_read_step lc2 mem2 loc1 to1 val1 ord1>>.\nProof.\n  inv STEP1.\n  exploit reorder_is_racy_promise; eauto.\nQed.\n\nLemma reorder_racy_write_promise\n      loc1 to1 ord1\n      loc2 from2 to2 msg2 kind2\n      lc0 mem0\n      lc2 mem2\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.racy_write_step lc0 mem0 loc1 to1 ord1)\n      (STEP2: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc2 mem2 kind2)\n      (CONS: Local.promise_consistent lc2):\n  <<STEP: Local.racy_write_step lc2 mem2 loc1 to1 ord1>>.\nProof.\n  inv STEP1.\n  exploit reorder_is_racy_promise; eauto.\nQed.\n\nLemma reorder_racy_update_promise\n      loc1 to1 ord1\n      loc2 from2 to2 msg2 kind2\n      lc0 mem0\n      lc2 mem2\n      (WF0: Local.wf lc0 mem0)\n      (MEM0: Memory.closed mem0)\n      (STEP1: Local.racy_write_step lc0 mem0 loc1 to1 ord1)\n      (STEP2: Local.promise_step lc0 mem0 loc2 from2 to2 msg2 lc2 mem2 kind2)\n      (CONS: Local.promise_consistent lc2):\n  <<STEP: Local.racy_write_step lc2 mem2 loc1 to1 ord1>>.\nProof.\n  inv STEP1; eauto.\n  exploit reorder_is_racy_promise; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/prop/ReorderStepPromise.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21037225816046312}}
{"text": "From iris.proofmode Require Import coq_tactics reduction.\nFrom iris.proofmode Require Export tactics.\nFrom iris.program_logic Require Import atomic.\nFrom intensional.heap_lang Require Export tactics lifting.\nFrom intensional Require Import notation.\nImport uPred.\n\nLemma tac_wp_expr_eval `{!heapG Σ} Δ s E Φ e e' :\n  (∀ (e'':=e'), e = e'') →\n  envs_entails Δ (WP e' @ s; E {{ Φ }}) → envs_entails Δ (WP e @ s; E {{ Φ }}).\nProof. by intros ->. Qed.\nLemma tac_twp_expr_eval `{!heapG Σ} Δ s E Φ e e' :\n  (∀ (e'':=e'), e = e'') →\n  envs_entails Δ (WP e' @ s; E [{ Φ }]) → envs_entails Δ (WP e @ s; E [{ Φ }]).\nProof. by intros ->. Qed.\n\nTactic Notation \"wp_expr_eval\" tactic3(t) :=\n  iStartProof;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    eapply tac_wp_expr_eval;\n      [let x := fresh in intros x; t; unfold x; reflexivity|]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    eapply tac_twp_expr_eval;\n      [let x := fresh in intros x; t; unfold x; reflexivity|]\n  | _ => fail \"wp_expr_eval: not a 'wp'\"\n  end.\n\nLemma tac_wp_pure `{!heapG Σ} Δ Δ' s E K e1 e2 φ n Φ :\n  PureExec φ n e1 e2 →\n  φ →\n  MaybeIntoLaterNEnvs n Δ Δ' →\n  envs_entails Δ' (WP (fill K e2) @ s; E {{ Φ }}) →\n  envs_entails Δ (WP (fill K e1) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ??? HΔ'. rewrite into_laterN_env_sound /=.\n  rewrite HΔ' -lifting.wp_pure_step_later //.\nQed.\nLemma tac_twp_pure `{!heapG Σ} Δ s E K e1 e2 φ n Φ :\n  PureExec φ n e1 e2 →\n  φ →\n  envs_entails Δ (WP (fill K e2) @ s; E [{ Φ }]) →\n  envs_entails Δ (WP (fill K e1) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=> ?? ->. rewrite -total_lifting.twp_pure_step //.\nQed.\n\nLemma tac_wp_value `{!heapG Σ} Δ s E Φ v :\n  envs_entails Δ (Φ v) → envs_entails Δ (WP (Val v) @ s; E {{ Φ }}).\nProof. rewrite envs_entails_eq=> ->. by apply wp_value. Qed.\nLemma tac_twp_value `{!heapG Σ} Δ s E Φ v :\n  envs_entails Δ (Φ v) → envs_entails Δ (WP (Val v) @ s; E [{ Φ }]).\nProof. rewrite envs_entails_eq=> ->. by apply twp_value. Qed.\n\nLtac wp_expr_simpl := wp_expr_eval simpl.\n\nLtac wp_value_head :=\n  first [eapply tac_wp_value || eapply tac_twp_value].\n\nLtac wp_finish :=\n  wp_expr_simpl;      (* simplify occurences of subst/fill *)\n  try wp_value_head;  (* in case we have reached a value, get rid of the WP *)\n  pm_prettify.        (* prettify ▷s caused by [MaybeIntoLaterNEnvs] and\n                         λs caused by wp_value *)\n\nLtac solve_vals_compare_safe :=\n  (* The first branch is for when we have [vals_compare_safe] in the context.\n     The other two branches are for when either one of the branches reduces to\n     [True] or we have it in the context. *)\n  fast_done || (left; fast_done) || (right; fast_done).\n\n(** The argument [efoc] can be used to specify the construct that should be\nreduced. For example, you can write [wp_pure (EIf _ _ _)], which will search\nfor an [EIf _ _ _] in the expression, and reduce it.\n\nThe use of [open_constr] in this tactic is essential. It will convert all holes\n(i.e. [_]s) into evars, that later get unified when an occurences is found\n(see [unify e' efoc] in the code below). *)\nTactic Notation \"wp_pure\" open_constr(efoc) :=\n  iStartProof;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    let e := eval simpl in e in\n    reshape_expr e ltac:(fun K e' =>\n      unify e' efoc;\n      eapply (tac_wp_pure _ _ _ _ K e');\n      [iSolveTC                       (* PureExec *)\n      |try solve_vals_compare_safe    (* The pure condition for PureExec -- handles trivial goals, including [vals_compare_safe] *)\n      |iSolveTC                       (* IntoLaters *)\n      |wp_finish                      (* new goal *)\n      ])\n    || fail \"wp_pure: cannot find\" efoc \"in\" e \"or\" efoc \"is not a redex\"\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    let e := eval simpl in e in\n    reshape_expr e ltac:(fun K e' =>\n      unify e' efoc;\n      eapply (tac_twp_pure _ _ _ K e');\n      [iSolveTC                       (* PureExec *)\n      |try solve_vals_compare_safe    (* The pure condition for PureExec *)\n      |wp_finish                      (* new goal *)\n      ])\n    || fail \"wp_pure: cannot find\" efoc \"in\" e \"or\" efoc \"is not a redex\"\n  | _ => fail \"wp_pure: not a 'wp'\"\n  end.\n\n(* TODO: do this in one go, without [repeat]. *)\nLtac wp_pures :=\n  iStartProof;\n  repeat (wp_pure _; []). (* The `;[]` makes sure that no side-condition\n                             magically spawns. *)\n\n(** Unlike [wp_pures], the tactics [wp_rec] and [wp_lam] should also reduce\nlambdas/recs that are hidden behind a definition, i.e. they should use\n[AsRecV_recv] as a proper instance instead of a [Hint Extern].\n\nWe achieve this by putting [AsRecV_recv] in the current environment so that it\ncan be used as an instance by the typeclass resolution system. We then perform\nthe reduction, and finally we clear this new hypothesis. *)\nTactic Notation \"wp_rec\" :=\n  let H := fresh in\n  assert (H := AsRecV_recv);\n  wp_pure (App _ _);\n  clear H.\n\nTactic Notation \"wp_if\" := wp_pure (If _ _ _).\nTactic Notation \"wp_if_true\" := wp_pure (If (LitV (LitBool true)) _ _).\nTactic Notation \"wp_if_false\" := wp_pure (If (LitV (LitBool false)) _ _).\nTactic Notation \"wp_unop\" := wp_pure (UnOp _ _).\nTactic Notation \"wp_binop\" := wp_pure (BinOp _ _ _).\nTactic Notation \"wp_op\" := wp_unop || wp_binop.\nTactic Notation \"wp_lam\" := wp_rec.\nTactic Notation \"wp_let\" := wp_pure (Rec BAnon (BNamed _) _); wp_lam.\nTactic Notation \"wp_seq\" := wp_pure (Rec BAnon BAnon _); wp_lam.\nTactic Notation \"wp_proj\" := wp_pure (Fst _) || wp_pure (Snd _).\nTactic Notation \"wp_case\" := wp_pure (Case _ _ _).\nTactic Notation \"wp_match\" := wp_case; wp_pure (Rec _ _ _); wp_lam.\nTactic Notation \"wp_inj\" := wp_pure (InjL _) || wp_pure (InjR _).\nTactic Notation \"wp_pair\" := wp_pure (Pair _ _).\nTactic Notation \"wp_closure\" := wp_pure (Rec _ _ _).\n\nLemma tac_wp_bind `{!heapG Σ} K Δ s E Φ e f :\n  f = (λ e, fill K e) → (* as an eta expanded hypothesis so that we can `simpl` it *)\n  envs_entails Δ (WP e @ s; E {{ v, WP f (Val v) @ s; E {{ Φ }} }})%I →\n  envs_entails Δ (WP fill K e @ s; E {{ Φ }}).\nProof. rewrite envs_entails_eq=> -> ->. by apply: wp_bind. Qed.\nLemma tac_twp_bind `{!heapG Σ} K Δ s E Φ e f :\n  f = (λ e, fill K e) → (* as an eta expanded hypothesis so that we can `simpl` it *)\n  envs_entails Δ (WP e @ s; E [{ v, WP f (Val v) @ s; E [{ Φ }] }])%I →\n  envs_entails Δ (WP fill K e @ s; E [{ Φ }]).\nProof. rewrite envs_entails_eq=> -> ->. by apply: twp_bind. Qed.\n\nLtac wp_bind_core K :=\n  lazymatch eval hnf in K with\n  | [] => idtac\n  | _ => eapply (tac_wp_bind K); [simpl; reflexivity|reduction.pm_prettify]\n  end.\nLtac twp_bind_core K :=\n  lazymatch eval hnf in K with\n  | [] => idtac\n  | _ => eapply (tac_twp_bind K); [simpl; reflexivity|reduction.pm_prettify]\n  end.\n\nTactic Notation \"wp_bind\" open_constr(efoc) :=\n  iStartProof;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' => unify e' efoc; wp_bind_core K)\n    || fail \"wp_bind: cannot find\" efoc \"in\" e\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    reshape_expr e ltac:(fun K e' => unify e' efoc; twp_bind_core K)\n    || fail \"wp_bind: cannot find\" efoc \"in\" e\n  | _ => fail \"wp_bind: not a 'wp'\"\n  end.\n\n(** Heap tactics *)\nSection heap.\nContext `{!heapG Σ}.\nImplicit Types P Q : iProp Σ.\nImplicit Types Φ : val → iProp Σ.\nImplicit Types Δ : envs (uPredI (iResUR Σ)).\nImplicit Types v : val.\nImplicit Types z : Z.\n\nLemma tac_wp_alloc Δ Δ' s E j K v Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  (∀ l,\n    match envs_app false (Esnoc Enil j (l ↦ v)) Δ' with\n    | Some Δ'' =>\n       envs_entails Δ'' (WP fill K (Val $ LitV l) @ s; E {{ Φ }})\n    | None => False\n    end) →\n  envs_entails Δ (WP fill K (Alloc (Val v)) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ? HΔ.\n  rewrite -wp_bind. eapply wand_apply; first exact: wp_alloc.\n  rewrite left_id into_laterN_env_sound; apply later_mono, forall_intro=> l.\n  specialize (HΔ l).\n  destruct (envs_app _ _ _) as [Δ''|] eqn:HΔ'; [ | contradiction ].\n  rewrite envs_app_sound //; simpl.\n  apply wand_intro_l. by rewrite (sep_elim_l (l ↦ v)%I) right_id wand_elim_r.\nQed.\nLemma tac_twp_alloc Δ s E j K v Φ :\n  (∀ l,\n    match envs_app false (Esnoc Enil j (l ↦ v)) Δ with\n    | Some Δ' =>\n       envs_entails Δ' (WP fill K (Val $ LitV $ LitLoc l) @ s; E [{ Φ }])\n    | None => False\n    end) →\n  envs_entails Δ (WP fill K (Alloc (Val v)) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=> HΔ.\n  rewrite -twp_bind. eapply wand_apply; first exact: twp_alloc.\n  rewrite left_id. apply forall_intro=> l.\n  specialize (HΔ l).\n  destruct (envs_app _ _ _) as [Δ''|] eqn:HΔ'; [ | contradiction ].\n  rewrite envs_app_sound //; simpl.\n  apply wand_intro_l. by rewrite (sep_elim_l (l ↦ v)%I) right_id wand_elim_r.\nQed.\n\nLemma tac_wp_load Δ Δ' s E i K l q v Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦{q} v)%I →\n  envs_entails Δ' (WP fill K (Val v) @ s; E {{ Φ }}) →\n  envs_entails Δ (WP fill K (Load (LitV l)) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ???.\n  rewrite -wp_bind. eapply wand_apply; first exact: wp_load.\n  rewrite into_laterN_env_sound -later_sep envs_lookup_split //; simpl.\n  by apply later_mono, sep_mono_r, wand_mono.\nQed.\nLemma tac_twp_load Δ s E i K l q v Φ :\n  envs_lookup i Δ = Some (false, l ↦{q} v)%I →\n  envs_entails Δ (WP fill K (Val v) @ s; E [{ Φ }]) →\n  envs_entails Δ (WP fill K (Load (LitV l)) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=> ??.\n  rewrite -twp_bind. eapply wand_apply; first exact: twp_load.\n  rewrite envs_lookup_split //; simpl.\n  by apply sep_mono_r, wand_mono.\nQed.\n\nLemma tac_wp_store Δ Δ' s E i K l v v' Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦ v)%I →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ v')) Δ' with\n  | Some Δ'' => envs_entails Δ'' (WP fill K (Val $ LitV LitUnit) @ s; E {{ Φ }})\n  | None => False\n  end →\n  envs_entails Δ (WP fill K (Store (LitV l) (Val v')) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ???.\n  destruct (envs_simple_replace _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  rewrite -wp_bind. eapply wand_apply; first by eapply wp_store.\n  rewrite into_laterN_env_sound -later_sep envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply later_mono, sep_mono_r, wand_mono.\nQed.\nLemma tac_twp_store Δ s E i K l v v' Φ :\n  envs_lookup i Δ = Some (false, l ↦ v)%I →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ v')) Δ with\n  | Some Δ' => envs_entails Δ' (WP fill K (Val $ LitV LitUnit) @ s; E [{ Φ }])\n  | None => False\n  end →\n  envs_entails Δ (WP fill K (Store (LitV l) v') @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq. intros.\n  destruct (envs_simple_replace _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  rewrite -twp_bind. eapply wand_apply; first by eapply twp_store.\n  rewrite envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply sep_mono_r, wand_mono.\nQed.\n\nLemma tac_wp_cmpxchg Δ Δ' s E i K l v v1 v2 Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦ v)%I →\n  vals_compare_safe v v1 →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ v2)) Δ' with\n  | Some Δ'' =>\n     v = v1 →\n     envs_entails Δ'' (WP fill K (Val $ PairV v (LitV $ LitBool true)) @ s; E {{ Φ }})\n  | None => False\n  end →\n  (v ≠ v1 →\n   envs_entails Δ' (WP fill K (Val $ PairV v (LitV $ LitBool false)) @ s; E {{ Φ }})) →\n  envs_entails Δ (WP fill K (CmpXchg (LitV l) (Val v1) (Val v2)) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ??? Hsuc Hfail.\n  destruct (envs_simple_replace _ _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  destruct (decide (v = v1)) as [Heq|Hne].\n  - rewrite -wp_bind. eapply wand_apply.\n    { eapply wp_cmpxchg_suc; eauto. }\n    rewrite into_laterN_env_sound -later_sep /= {1}envs_simple_replace_sound //; simpl.\n    apply later_mono, sep_mono_r. rewrite right_id. apply wand_mono; auto.\n  - rewrite -wp_bind. eapply wand_apply.\n    { eapply wp_cmpxchg_fail; eauto. }\n    rewrite into_laterN_env_sound -later_sep /= {1}envs_lookup_split //; simpl.\n    apply later_mono, sep_mono_r. apply wand_mono; auto.\nQed.\nLemma tac_twp_cmpxchg Δ s E i K l v v1 v2 Φ :\n  envs_lookup i Δ = Some (false, l ↦ v)%I →\n  vals_compare_safe v v1 →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ v2)) Δ with\n  | Some Δ' =>\n     v = v1 →\n     envs_entails Δ' (WP fill K (Val $ PairV v (LitV $ LitBool true)) @ s; E [{ Φ }])\n  | None => False\n  end →\n  (v ≠ v1 →\n   envs_entails Δ (WP fill K (Val $ PairV v (LitV $ LitBool false)) @ s; E [{ Φ }])) →\n  envs_entails Δ (WP fill K (CmpXchg (LitV l) v1 v2) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=> ?? Hsuc Hfail.\n  destruct (envs_simple_replace _ _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  destruct (decide (v = v1)) as [Heq|Hne].\n  - rewrite -twp_bind. eapply wand_apply.\n    { eapply twp_cmpxchg_suc; eauto. }\n    rewrite /= {1}envs_simple_replace_sound //; simpl.\n    apply sep_mono_r. rewrite right_id. apply wand_mono; auto.\n  - rewrite -twp_bind. eapply wand_apply.\n    { eapply twp_cmpxchg_fail; eauto. }\n    rewrite /= {1}envs_lookup_split //; simpl.\n    apply sep_mono_r. apply wand_mono; auto.\nQed.\n\nLemma tac_wp_cmpxchg_fail Δ Δ' s E i K l q v v1 v2 Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦{q} v)%I →\n  v ≠ v1 → vals_compare_safe v v1 →\n  envs_entails Δ' (WP fill K (Val $ PairV v (LitV $ LitBool false)) @ s; E {{ Φ }}) →\n  envs_entails Δ (WP fill K (CmpXchg (LitV l) v1 v2) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ?????.\n  rewrite -wp_bind. eapply wand_apply; first exact: wp_cmpxchg_fail.\n  rewrite into_laterN_env_sound -later_sep envs_lookup_split //; simpl.\n  by apply later_mono, sep_mono_r, wand_mono.\nQed.\nLemma tac_twp_cmpxchg_fail Δ s E i K l q v v1 v2 Φ :\n  envs_lookup i Δ = Some (false, l ↦{q} v)%I →\n  v ≠ v1 → vals_compare_safe v v1 →\n  envs_entails Δ (WP fill K (Val $ PairV v (LitV $ LitBool false)) @ s; E [{ Φ }]) →\n  envs_entails Δ (WP fill K (CmpXchg (LitV l) v1 v2) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq. intros. rewrite -twp_bind.\n  eapply wand_apply; first exact: twp_cmpxchg_fail.\n  rewrite envs_lookup_split //=. by do 2 f_equiv.\nQed.\n\nLemma tac_wp_cmpxchg_suc Δ Δ' s E i K l v v1 v2 Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦ v)%I →\n  v = v1 → vals_compare_safe v v1 →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ v2)) Δ' with\n  | Some Δ'' =>\n     envs_entails Δ'' (WP fill K (Val $ PairV v (LitV $ LitBool true)) @ s; E {{ Φ }})\n  | None => False\n  end →\n  envs_entails Δ (WP fill K (CmpXchg (LitV l) v1 v2) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ?????; subst.\n  destruct (envs_simple_replace _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  rewrite -wp_bind. eapply wand_apply.\n  { eapply wp_cmpxchg_suc; eauto. }\n  rewrite into_laterN_env_sound -later_sep envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply later_mono, sep_mono_r, wand_mono.\nQed.\nLemma tac_twp_cmpxchg_suc Δ s E i K l v v1 v2 Φ :\n  envs_lookup i Δ = Some (false, l ↦ v)%I →\n  v = v1 → vals_compare_safe v v1 →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ v2)) Δ with\n  | Some Δ' =>\n     envs_entails Δ' (WP fill K (Val $ PairV v (LitV $ LitBool true)) @ s; E [{ Φ }])\n  | None => False\n  end →\n  envs_entails Δ (WP fill K (CmpXchg (LitV l) v1 v2) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=>????; subst.\n  destruct (envs_simple_replace _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  rewrite -twp_bind. eapply wand_apply.\n  { eapply twp_cmpxchg_suc; eauto. }\n  rewrite envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply sep_mono_r, wand_mono.\nQed.\n\nLemma tac_wp_faa Δ Δ' s E i K l z1 z2 Φ :\n  MaybeIntoLaterNEnvs 1 Δ Δ' →\n  envs_lookup i Δ' = Some (false, l ↦ LitV z1)%I →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ LitV (LitInt (z1 + z2)))) Δ' with\n  | Some Δ'' => envs_entails Δ'' (WP fill K (Val $ LitV z1) @ s; E {{ Φ }})\n  | None => False\n  end →\n  envs_entails Δ (WP fill K (FAA (LitV l) (LitV z2)) @ s; E {{ Φ }}).\nProof.\n  rewrite envs_entails_eq=> ???.\n  destruct (envs_simple_replace _ _ _) as [Δ''|] eqn:HΔ''; [ | contradiction ].\n  rewrite -wp_bind. eapply wand_apply; first exact: (wp_faa _ _ _ z1 z2).\n  rewrite into_laterN_env_sound -later_sep envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply later_mono, sep_mono_r, wand_mono.\nQed.\nLemma tac_twp_faa Δ s E i K l z1 z2 Φ :\n  envs_lookup i Δ = Some (false, l ↦ LitV z1)%I →\n  match envs_simple_replace i false (Esnoc Enil i (l ↦ LitV (LitInt (z1 + z2)))) Δ with\n  | Some Δ' => envs_entails Δ' (WP fill K (Val $ LitV z1) @ s; E [{ Φ }])\n  | None => False\n  end →\n  envs_entails Δ (WP fill K (FAA (LitV l) (LitV z2)) @ s; E [{ Φ }]).\nProof.\n  rewrite envs_entails_eq=> ??.\n  destruct (envs_simple_replace _ _ _) as [Δ'|] eqn:HΔ'; [ | contradiction ].\n  rewrite -twp_bind. eapply wand_apply; first exact: (twp_faa _ _ _ z1 z2).\n  rewrite envs_simple_replace_sound //; simpl.\n  rewrite right_id. by apply sep_mono_r, wand_mono.\nQed.\nEnd heap.\n\n(** Evaluate [lem] to a hypothesis [H] that can be applied, and then run\n[wp_bind K; tac H] for every possible evaluation context.  [tac] can do\n[iApplyHyp H] to actually apply the hypothesis.  TC resolution of [lem] premises\nhappens *after* [tac H] got executed. *)\nTactic Notation \"wp_apply_core\" open_constr(lem) tactic3(tac) :=\n  wp_pures;\n  iPoseProofCore lem as false (fun H =>\n    lazymatch goal with\n    | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n      reshape_expr e ltac:(fun K e' =>\n        wp_bind_core K; tac H) ||\n      lazymatch iTypeOf H with\n      | Some (_,?P) => fail \"wp_apply: cannot apply\" P\n      end\n    | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n      reshape_expr e ltac:(fun K e' =>\n        twp_bind_core K; tac H) ||\n      lazymatch iTypeOf H with\n      | Some (_,?P) => fail \"wp_apply: cannot apply\" P\n      end\n    | _ => fail \"wp_apply: not a 'wp'\"\n    end).\nTactic Notation \"wp_apply\" open_constr(lem) :=\n  wp_apply_core lem (fun H => iApplyHyp H; try iNext; try wp_expr_simpl).\n(** Tactic tailored for atomic triples: the first, simple one just runs\n[iAuIntro] on the goal, as atomic triples always have an atomic update as their\npremise.  The second one additionaly does some framing: it gets rid of [Hs] from\nthe context, which is intended to be the non-laterable assertions that iAuIntro\nwould choke on.  You get them all back in the continuation of the atomic\noperation. *)\nTactic Notation \"awp_apply\" open_constr(lem) :=\n  wp_apply_core lem (fun H => iApplyHyp H);\n  last iAuIntro.\nTactic Notation \"awp_apply\" open_constr(lem) \"without\" constr(Hs) :=\n  wp_apply_core lem (fun H => iApply wp_frame_wand_l; iSplitL Hs; [iAccu|iApplyHyp H]);\n  last iAuIntro.\n\nTactic Notation \"wp_alloc\" ident(l) \"as\" constr(H) :=\n  let Htmp := iFresh in\n  let finish _ :=\n    first [intros l | fail 1 \"wp_alloc:\" l \"not fresh\"];\n    pm_reduce;\n    lazymatch goal with\n    | |- False => fail 1 \"wp_alloc:\" H \"not fresh\"\n    | _ => iDestructHyp Htmp as H; wp_finish\n    end in\n  wp_pures;\n  (** The code first tries to use allocation lemma for a single reference,\n     ie, [tac_wp_alloc] (respectively, [tac_twp_alloc]).\n     If that fails, it tries to use the lemma [tac_wp_allocN]\n     (respectively, [tac_twp_allocN]) for allocating an array.\n     Notice that we could have used the array allocation lemma also for single\n     references. However, that would produce the resource l ↦∗ [v] instead of\n     l ↦ v for single references. These are logically equivalent assertions\n     but are not equal. *)\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    let process_single _ :=\n        first\n          [reshape_expr e ltac:(fun K e' => eapply (tac_wp_alloc _ _ _ _ Htmp K))\n          |fail 1 \"wp_alloc: cannot find 'Alloc' in\" e];\n        [iSolveTC\n        |finish ()]\n    in (process_single ())\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    let process_single _ :=\n        first\n          [reshape_expr e ltac:(fun K e' => eapply (tac_twp_alloc _ _ _ Htmp K))\n          |fail 1 \"wp_alloc: cannot find 'Alloc' in\" e];\n        finish ()\n    in (process_single ())\n  | _ => fail \"wp_alloc: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_alloc\" ident(l) :=\n  wp_alloc l as \"?\".\n\nTactic Notation \"wp_load\" :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_load: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_load _ _ _ _ _ K))\n      |fail 1 \"wp_load: cannot find 'Load' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |wp_finish]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_load _ _ _ _ K))\n      |fail 1 \"wp_load: cannot find 'Load' in\" e];\n    [solve_mapsto ()\n    |wp_finish]\n  | _ => fail \"wp_load: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_store\" :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_store: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_store _ _ _ _ _ K))\n      |fail 1 \"wp_store: cannot find 'Store' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |pm_reduce; first [wp_seq|wp_finish]]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_store _ _ _ _ K))\n      |fail 1 \"wp_store: cannot find 'Store' in\" e];\n    [solve_mapsto ()\n    |pm_reduce; first [wp_seq|wp_finish]]\n  | _ => fail \"wp_store: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_cmpxchg\" \"as\" simple_intropattern(H1) \"|\" simple_intropattern(H2) :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_cmpxchg: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_cmpxchg _ _ _ _ _ K))\n      |fail 1 \"wp_cmpxchg: cannot find 'CmpXchg' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |try solve_vals_compare_safe\n    |pm_reduce; intros H1; wp_finish\n    |intros H2; wp_finish]\n  | |- envs_entails _ (twp ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_cmpxchg _ _ _ _ K))\n      |fail 1 \"wp_cmpxchg: cannot find 'CmpXchg' in\" e];\n    [solve_mapsto ()\n    |try solve_vals_compare_safe\n    |pm_reduce; intros H1; wp_finish\n    |intros H2; wp_finish]\n  | _ => fail \"wp_cmpxchg: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_cmpxchg_fail\" :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_cmpxchg_fail: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_cmpxchg_fail _ _ _ _ _ K))\n      |fail 1 \"wp_cmpxchg_fail: cannot find 'CmpXchg' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |try (simpl; congruence) (* value inequality *)\n    |try solve_vals_compare_safe\n    |wp_finish]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_cmpxchg_fail _ _ _ _ K))\n      |fail 1 \"wp_cmpxchg_fail: cannot find 'CmpXchg' in\" e];\n    [solve_mapsto ()\n    |try (simpl; congruence) (* value inequality *)\n    |try solve_vals_compare_safe\n    |wp_finish]\n  | _ => fail \"wp_cmpxchg_fail: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_cmpxchg_suc\" :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_cmpxchg_suc: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_cmpxchg_suc _ _ _ _ _ K))\n      |fail 1 \"wp_cmpxchg_suc: cannot find 'CmpXchg' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |try (simpl; congruence) (* value equality *)\n    |try solve_vals_compare_safe\n    |pm_reduce; wp_finish]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_cmpxchg_suc _ _ _ _ K))\n      |fail 1 \"wp_cmpxchg_suc: cannot find 'CmpXchg' in\" e];\n    [solve_mapsto ()\n    |try (simpl; congruence) (* value equality *)\n    |try solve_vals_compare_safe\n    |pm_reduce; wp_finish]\n  | _ => fail \"wp_cmpxchg_suc: not a 'wp'\"\n  end.\n\nTactic Notation \"wp_faa\" :=\n  let solve_mapsto _ :=\n    let l := match goal with |- _ = Some (_, (?l ↦{_} _)%I) => l end in\n    iAssumptionCore || fail \"wp_faa: cannot find\" l \"↦ ?\" in\n  wp_pures;\n  lazymatch goal with\n  | |- envs_entails _ (wp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_wp_faa _ _ _ _ _ K))\n      |fail 1 \"wp_faa: cannot find 'FAA' in\" e];\n    [iSolveTC\n    |solve_mapsto ()\n    |pm_reduce; wp_finish]\n  | |- envs_entails _ (twp ?s ?E ?e ?Q) =>\n    first\n      [reshape_expr e ltac:(fun K e' => eapply (tac_twp_faa _ _ _ _ K))\n      |fail 1 \"wp_faa: cannot find 'FAA' in\" e];\n    [solve_mapsto ()\n    |pm_reduce; wp_finish]\n  | _ => fail \"wp_faa: not a 'wp'\"\n  end.\n", "meta": {"author": "logsem", "repo": "free-theorems-sl", "sha": "0a34d49adbce012d406ca4457941d7c966f384f3", "save_path": "github-repos/coq/logsem-free-theorems-sl", "path": "github-repos/coq/logsem-free-theorems-sl/free-theorems-sl-0a34d49adbce012d406ca4457941d7c966f384f3/theories/heap_lang/proofmode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21037225816046312}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import hmacdrbg.HMAC_DRBG_algorithms.\nRequire Import hmacdrbg.HMAC_DRBG_common_lemmas.\nRequire Import hmacdrbg.spec_hmac_drbg.\n\nLemma ReseedRes: forall X r v, @return_value_relate_result X r (Vint v) -> Int.eq v (Int.repr (-20864)) = false.\nProof. intros.\n  unfold return_value_relate_result in H.\n  destruct r. inversion H; reflexivity.\n  destruct e; inversion H; try reflexivity.\n  apply Int.eq_false. eapply ENT_GenErrAx.\nQed.\n\nLemma hmac_interp_empty d r: hmac_interp d r |-- md_empty r.\nProof.\ndestruct d; simpl. auto.\neapply derives_trans. apply md_relate_full. apply md_full_empty.\napply md_full_empty.\nQed.\n\nLemma instantiate256_reseed d s pr_flag rc ri (ZLc'256F : (Zlength d >? 256) = false):\n      instantiate_function_256 s pr_flag  d =\n      mbedtls_HMAC256_DRBG_reseed_function s (HMAC256DRBGabs initial_key initial_value rc 48 pr_flag ri) d.\nProof. intros.\n  unfold instantiate_function_256; simpl.\n  rewrite ZLc'256F, andb_negb_r.\n  assert (MaxString': Zlength d >? max_personalization_string_length = false).\n  { apply Zgt_is_gt_bool_f. apply Zgt_is_gt_bool_f in ZLc'256F.\n    unfold max_personalization_string_length. omega. }\n  rewrite MaxString' in *; trivial.\nQed.", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/hmacdrbg/verif_hmac_drbg_seed_common.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.21030462406161338}}
{"text": "Require Import ch2o.prelude.base.\nRequire Import ch2o.prelude.option.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Program.Equality.\nRequire Import Coq.Strings.String.\n\nRequire Import common.\nRequire Import Ast.\nRequire Import Store.\nRequire Import Entities.\n\nOpen Scope string_scope.\n\nSection step.\nContext (P: program).\n\nInductive step : heap * list frame * expr -> heap * list frame * expr -> Prop :=\n| step_hole : forall χ χ' φ φ' σ e e' ectx,\n    step (χ, φ::σ, e) (χ', φ'::σ, e') ->\n    step (χ, φ::σ, fill_hole ectx e) (χ', φ'::σ, fill_hole ectx e')\n\n| step_seq : forall χ σ t e,\n    step (χ, σ, expr_seq (expr_temp t) e)\n         (χ, σ, e)\n\n| step_recover : forall χ σ t,\n    step (χ, σ, expr_recover (expr_temp t))\n         (χ, σ, (expr_temp t))\n\n| step_local : forall χ φ σ t φ' x,\n    not (t ∈ φ) ->\n    φ' = <[t := φ !!! x]> φ ->\n    step (χ, φ::σ, expr_local x)\n         (χ, φ'::σ, expr_temp t)\n\n| step_asn_local : forall χ φ φ' σ t t' x,\n    not (t' ∈ φ) ->\n    φ' = <[t' := φ !!! x]>(<[x := φ !!! t]>φ) ->\n    step (χ, φ::σ, expr_assign_local x (expr_temp t))\n         (χ, φ'::σ, expr_temp t')\n\n| step_field : forall χ φ φ' σ t t' f ω,\n    not (t' ∈ φ) ->\n    v_addr ω = φ !!! t ->\n    φ' = <[t' := χ !!! (ω, f)]> φ ->\n    step (χ, φ::σ, expr_field (expr_temp t) f)\n         (χ, φ'::σ, expr_temp t')\n\n| step_asn_field : forall χ χ' φ φ' σ t t' t'' f ω,\n    not (t'' ∈ φ) ->\n    v_addr ω = φ !!! t ->\n    φ' = <[t'' := χ !!! (ω, f)]>φ ->\n    χ' = <[(ω, f) := φ !!! t']>χ ->\n\n    step (χ, φ::σ, expr_assign_field (expr_temp t) f (expr_temp t'))\n           (χ', φ'::σ, expr_temp t'')\n\n| step_sync : forall χ φ φ' φ'' σ ectx t m e xs ts ω,\n    v_addr ω = φ !!! t ->\n    Some (xs, e) = (obj <- χ !! ω; lookup_Mr P obj.(name) m) ->\n\n    φ'' = {|\n      method := m;\n      locals := <[* xs := map (φ !!!) ts ]>(<[\"this\" := v_addr ω]>empty);\n      hole := expr_hole_id\n    |} ->\n\n    φ' = {|\n      method := φ.(method);\n      locals := φ.(locals);\n      hole := ectx\n    |} ->\n\n    step (χ, φ :: σ, fill_hole ectx (expr_call (expr_temp t) m (list_expr_temps ts)))\n         (χ, φ'' :: φ' :: σ, e)\n\n| step_ctor : forall χ χ' ω φ φ' φ'' σ ectx kt k e fs xs ts,\n    not (ω ∈ heap_dom χ) ->\n    Some fs = lookup_Fs P kt ->\n    Some (xs, e) = lookup_Mr P kt k ->\n\n    χ' = <[ω := {| name := kt; fields := <[* fs := v_null ]>empty |}]>χ ->\n\n    φ'' = {|\n      method := k;\n      locals := <[* xs := map (φ !!!) ts ]>(<[\"this\" := v_addr ω]>empty);\n      hole := expr_hole_id\n    |} ->\n\n    φ' = {|\n      method := φ.(method);\n      locals := φ.(locals);\n      hole := ectx\n    |} ->\n\n    step (χ, φ :: σ, fill_hole ectx (expr_ctor kt k (list_expr_temps ts)))\n         (χ', φ'' :: φ' :: σ, e)\n\n| step_return : forall χ φ φ' φ'' t t' σ,\n    not (t' ∈ φ) ->\n    φ'' = {|\n        method := φ.(method);\n        locals := <[t' := φ' !!! t]>φ.(locals);\n        hole := expr_hole_id;\n    |} ->\n    step (χ, φ' :: φ :: σ, expr_temp t)\n         (χ, φ'' :: σ, fill_hole φ.(hole) (expr_temp t'))\n\n| step_null : forall χ φ φ' σ t,\n    not (t ∈ φ) ->\n    φ' = <[t := v_null]>φ ->\n    step (χ, φ::σ, expr_null)\n         (χ, φ'::σ, expr_temp t)\n\n| step_field_null : forall χ φ σ t f,\n    v_null = φ !!! t ->\n\n    step (χ, φ::σ, expr_field (expr_temp t) f)\n         (χ, φ::σ, expr_temp t)\n\n| step_asn_field_null : forall χ φ σ t t' f,\n    v_null = φ !!! t ->\n\n    step (χ, φ::σ, expr_assign_field (expr_temp t) f (expr_temp t'))\n         (χ, φ::σ, expr_temp t)\n\n| step_call_null : forall χ φ σ t n ts,\n    v_null = φ !!! t ->\n\n    step (χ, φ::σ, expr_call (expr_temp t) n (list_expr_temps ts))\n         (χ, φ::σ, expr_temp t)\n.\n\nEnd step.\n", "meta": {"author": "plietar", "repo": "formal-pony", "sha": "fd48593f1deea4a98b45508ad808d6b8a252ebbd", "save_path": "github-repos/coq/plietar-formal-pony", "path": "github-repos/coq/plietar-formal-pony/formal-pony-fd48593f1deea4a98b45508ad808d6b8a252ebbd/src/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2103046161217321}}
{"text": "(*\n * Copyright (c) 2017-present,\n * Programming Research Laboratory (ROPAS), Seoul National University, Korea\n * This software is distributed under the term of the BSD-3 clause license.\n *)\n(** * Concrete Domain *)\n\nSet Implicit Arguments.\n\nRequire Import ZArith OrderedTypeEx.\nRequire Import Monad vgtac VocabA Syn DFSetAVL DFMapAVL InterCfg DLat\n        DUnit DNat DZ DStr DList DSum DMap DProd DPow Global.\nRequire DMem.\nRequire Import SemCommon.\n\nLocal Open Scope type.\n\nModule Step <: KEY := Nat.\n\n(** CallId is a step number on the call node, which is used to\ndistinguish function calls in concrete semantics. *)\n\nModule CallId <: KEY := Step.\n\nModule Proc <: KEY := DStr.\nModule GVar <: KEY := DStr.\nModule LVar <: KEY := ProdKey3 CallId Proc DStr.\nModule Var <: KEY := SumKey2 GVar LVar.\n\nModule ExtAllocsite <: KEY := SumKey2 Unit Proc.\nModule Allocsite <: KEY := SumKey2 InterNode ExtAllocsite.\nModule OSS <: KEY := ProdKey3 DZ DZ DZ.\nModule Region <: KEY := ProdKey3 Step Allocsite OSS.\nModule VarRegion <: KEY := SumKey2 Var Region.\n\nModule Field <: KEY := DStr.\nModule Fields <: KEY := ListKey Field.\n\nModule Loc <: KEY := ProdKey2 VarRegion Fields.\n\nDefinition val_t := Z.t + Loc.t + Proc.t.\n\n(** Auxiliary alias functions for value *)\n\nDefinition val_of_z (z : Z) : val_t := inl (inl z).\nDefinition val_of_loc (l : Loc.t) : val_t := inl (inr l).\nDefinition val_of_proc (p : Proc.t) : val_t := inr p.\n\nDefinition loc_of_gvar (x : vid_t) (fs : Fields.t) : Loc.t :=\n  (VarRegion.Inl (Var.Inl x), fs).\nDefinition loc_of_lvar (cid : CallId.t) (p : Proc.t) (x : vid_t) (fs : Fields.t)\n: Loc.t :=\n  (VarRegion.Inl (Var.Inr (cid, p, x)), fs).\nDefinition loc_of_alloc (step : Step.t) (alloc : Allocsite.t) (oss : OSS.t)\n  (fs : Fields.t) : Loc.t :=\n  (VarRegion.Inr (step, alloc, oss), fs).\n\n\nModule M := FMapAVL'.Make Loc.\nDefinition mem_t := M.t val_t.\n\n(** Stack is a list of call stack information, which is a product of\ncallee, (optional) return location, and caller's CallId for\nrestorations of CallId on return statements.  *)\n\nDefinition stack1 : Type := Proc.t * option Loc.t * CallId.t.\n\nDefinition stack_t : Type := list stack1.\n\nDefinition callee_t := option Proc.t.\n\n(** intra_node_state_t represents CallId (call node's step numbers to\ndistinguish local variables), an optional and temporary callee name\nafter call statements, memory, and stack. *)\n\nDefinition intra_node_state_t := CallId.t * callee_t * mem_t * stack_t.\n\nDefinition call_nodes_t := list InterNode.t.\n\nDefinition inter_node_state_t :=\n  InterNode.t * Step.t * call_nodes_t * intra_node_state_t.\n\nDefinition state_t := mem_pos * inter_node_state_t.\n\nInductive not_appear_stack f : stack_t -> Prop :=\n| not_appear_nil : not_appear_stack f nil\n| not_appear_cons :\n    forall s (Hs : not_appear_stack f s) f' (Hf' : ~ Proc.eq f f') opt_loc cid,\n      not_appear_stack f ((f', opt_loc, cid) :: s).\n\nInductive appear_once_stack f : stack_t -> Prop :=\n| appear_once_nil :\n    forall s (Hs : not_appear_stack f s) f' (Hf' : Proc.eq f f') opt_loc cid,\n      appear_once_stack f ((f', opt_loc, cid) :: s)\n| appear_once_cons :\n    forall s (Hs : appear_once_stack f s) f' (Hf' : ~ Proc.eq f f') opt_loc cid,\n      appear_once_stack f ((f', opt_loc, cid) :: s).\n\nDefinition wf_non_rec_stack g :=\n  forall f stk (Hf : Global.G.is_rec f g = false), appear_once_stack f stk.\n\nLocal Close Scope type.\n", "meta": {"author": "ropas", "repo": "zooberry", "sha": "17b1cb1a44c2a796d6b7d85c2026b142685d291b", "save_path": "github-repos/coq/ropas-zooberry", "path": "github-repos/coq/ropas-zooberry/zooberry-17b1cb1a44c2a796d6b7d85c2026b142685d291b/spec/Proof/DomCon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.2103046121517915}}
{"text": "(* This file is an automatic translation, the licence of the source can be found here: *)\n(* https://github.com/herd/herdtools7/blob/master/LICENSE.txt *)\n(* Translation of model Model *)\nFrom Coq Require Import Relations Ensembles String.\nFrom RelationAlgebra Require Import lattice prop monoid rel kat.\nFrom Catincoq.lib Require Import Cat proprel.\nSection Model.\nVariable c : candidate.\nDefinition events := events c.\nDefinition R := R c.\nDefinition W := W c.\nDefinition IW := IW c.\nDefinition FW := FW c.\nDefinition B := B c.\nDefinition RMW := RMW c.\nDefinition F := F c.\nDefinition rf := rf c.\nDefinition po := po c.\nDefinition int := int c.\nDefinition ext := ext c.\nDefinition loc := loc c.\nDefinition addr := addr c.\nDefinition data := data c.\nDefinition ctrl := ctrl c.\nDefinition amo := amo c.\nDefinition rmw := rmw c.\nDefinition unknown_set := unknown_set c.\nDefinition unknown_relation := unknown_relation c.\nDefinition M := R ⊔ W.\nDefinition emptyset : set events := empty.\nDefinition classes_loc : set events -> Ensemble (Ensemble events) := partition loc.\nDefinition X := unknown_set \"X\".\nDefinition tag2events := unknown_relation \"tag2events\".\nDefinition emptyset_0 : set events := domain 0.\nDefinition partition := classes_loc.\nDefinition tag2instrs := tag2events.\nDefinition po_loc := po ⊓ loc.\nDefinition rfe := rf ⊓ ext.\nDefinition rfi := rf ⊓ int.\nDefinition co0 := loc ⊓ ([IW] ⋅ top ⋅ [(W ⊓ !IW)] ⊔ [(W ⊓ !FW)] ⋅ top ⋅ [FW]).\nDefinition toid (s : set events) : relation events := [s].\nDefinition fencerel (B : set events) := (po ⊓ [top] ⋅ top ⋅ [B]) ⋅ po.\nDefinition ctrlcfence (CFENCE : set events) := (ctrl ⊓ [top] ⋅ top ⋅ [CFENCE]) ⋅ po.\nDefinition imply (A : relation events) (B : relation events) := !A ⊔ B.\nDefinition nodetour (R1 : relation events) (R2 : relation events) (R3 : relation events) := R1 ⊓ !(R2 ⋅ R3).\nDefinition singlestep (R : relation events) := nodetour R R R.\n(* Definition of map already included in the prelude *)\nDefinition LKW := (*failed: try LKW with emptyset_0*) emptyset_0.\nDefinition A := ((*successful: try X with emptyset_0*) X) ⊔ ((*failed: try A with emptyset_0*) emptyset_0).\nDefinition P := M ⊓ !A.\nDefinition WW r := r ⊓ [W] ⋅ top ⋅ [W].\nDefinition WR r := r ⊓ [W] ⋅ top ⋅ [R].\nDefinition RW r := r ⊓ [R] ⋅ top ⋅ [W].\nDefinition RR r := r ⊓ [R] ⋅ top ⋅ [R].\nDefinition RM r := r ⊓ [R] ⋅ top ⋅ [M].\nDefinition MR r := r ⊓ [M] ⋅ top ⋅ [R].\nDefinition WM r := r ⊓ [W] ⋅ top ⋅ [M].\nDefinition MW r := r ⊓ [M] ⋅ top ⋅ [W].\nDefinition MM r := r ⊓ [M] ⋅ top ⋅ [M].\nDefinition AA r := r ⊓ [A] ⋅ top ⋅ [A].\nDefinition AP r := r ⊓ [A] ⋅ top ⋅ [P].\nDefinition PA r := r ⊓ [P] ⋅ top ⋅ [A].\nDefinition PP r := r ⊓ [P] ⋅ top ⋅ [P].\nDefinition AM r := r ⊓ [A] ⋅ top ⋅ [M].\nDefinition MA r := r ⊓ [M] ⋅ top ⋅ [A].\nDefinition noid r : relation events := r ⊓ !id.\nDefinition atom := [A].\nDefinition obsco := WW po_loc ⊔ (rf ⋅ RW po_loc ⊔ (noid (WR po_loc ⋅ rf°) ⊔ noid (rf ⋅ (RR po_loc ⋅ rf°)))).\nDefinition cobase := obsco ⊔ co0.\nDefinition uniproc := acyclic cobase.\nDefinition co := cobase^+.\nDefinition fr := noid (rf° ⋅ co).\nDefinition coi := co ⊓ int.\nDefinition fri := fr ⊓ int.\nDefinition coe := co ⊓ !coi.\nDefinition fre := fr ⊓ !fri.\nDefinition dd := addr ⊔ data.\nDefinition rdw := po_loc ⊓ fre ⋅ rfe.\nDefinition detour := po_loc ⊓ coe ⋅ rfe.\nDefinition addrpo := addr ⋅ po.\nDefinition dmb_st : relation events := (*failed: try fencerel DMB.ST with 0*) 0.\nDefinition dsb_st : relation events := (*failed: try fencerel DSB.ST with 0*) 0.\nDefinition dmb : relation events := (*failed: try fencerel DMB with 0*) 0.\nDefinition dsb : relation events := (*failed: try fencerel DSB with 0*) 0.\nDefinition isb : relation events := (*failed: try fencerel ISB with 0*) 0.\nDefinition ctrlisb : relation events := (*failed: try ctrlcfence ISB with 0*) 0.\nDefinition sync : relation events := (*failed: try fencerel SYNC with 0*) 0.\nDefinition lwsync : relation events := (*failed: try fencerel LWSYNC with 0*) 0.\nDefinition eieio : relation events := (*failed: try fencerel EIEIO with 0*) 0.\nDefinition isync : relation events := (*failed: try fencerel ISYNC with 0*) 0.\nDefinition ctrlisync : relation events := (*failed: try ctrlcfence ISYNC with 0*) 0.\nDefinition ci0 := ctrlisync ⊔ (ctrlisb ⊔ detour).\nDefinition ii0 := dd ⊔ (rfi ⊔ rdw).\nDefinition cc0 := dd ⊔ (po_loc ⊔ (ctrl ⊔ addrpo)).\nDefinition ic0 : relation events := 0.\nInductive ci : relation _ := ci_c : incl (ci0 ⊔ (ci ⋅ ii ⊔ cc ⋅ ci)) ci\n     with ii : relation _ := ii_c : incl (ii0 ⊔ (ci ⊔ (ic ⋅ ci ⊔ ii ⋅ ii))) ii\n     with cc : relation _ := cc_c : incl (cc0 ⊔ (ci ⊔ (ci ⋅ ic ⊔ cc ⋅ cc))) cc\n     with ic : relation _ := ic_c : incl (ic0 ⊔ (ii ⊔ (cc ⊔ (ic ⋅ cc ⊔ ii ⋅ ic)))) ic.\nSection scheme.\nVariables ci' ii' cc' ic' : relation events.\nVariable Hci' : incl (ci0 ⊔ (ci' ⋅ ii' ⊔ cc' ⋅ ci')) ci'.\nVariable Hii' : incl (ii0 ⊔ (ci' ⊔ (ic' ⋅ ci' ⊔ ii' ⋅ ii'))) ii'.\nVariable Hcc' : incl (cc0 ⊔ (ci' ⊔ (ci' ⋅ ic' ⊔ cc' ⋅ cc'))) cc'.\nVariable Hic' : incl (ic0 ⊔ (ii' ⊔ (cc' ⊔ (ic' ⋅ cc' ⊔ ii' ⋅ ic')))) ic'.\n\n  Fixpoint ci_ind' x y (r : ci x y) : ci' x y\n      with ii_ind' x y (r : ii x y) : ii' x y\n      with cc_ind' x y (r : cc x y) : cc' x y\n      with ic_ind' x y (r : ic x y) : ic' x y.\n  Proof.\n    destruct r as [x y r]; apply Hci'.\n    destruct r as [r | r]; [ left | right ].\n     exact r.\n     destruct r as [r | r]; [ left | right ].\n      destruct r as [x_y r1 r2]; exists x_y.\n       apply ci_ind'; exact r1.\n       apply ii_ind'; exact r2.\n      destruct r as [x_y r1 r2]; exists x_y.\n       apply cc_ind'; exact r1.\n       apply ci_ind'; exact r2.\n    destruct r as [x y r]; apply Hii'.\n    destruct r as [r | r]; [ left | right ].\n     exact r.\n     destruct r as [r | r]; [ left | right ].\n      apply ci_ind'; exact r.\n      destruct r as [r | r]; [ left | right ].\n       destruct r as [x_y r1 r2]; exists x_y.\n        apply ic_ind'; exact r1.\n        apply ci_ind'; exact r2.\n       destruct r as [x_y r1 r2]; exists x_y.\n        apply ii_ind'; exact r1.\n        apply ii_ind'; exact r2.\n    destruct r as [x y r]; apply Hcc'.\n    destruct r as [r | r]; [ left | right ].\n     exact r.\n     destruct r as [r | r]; [ left | right ].\n      apply ci_ind'; exact r.\n      destruct r as [r | r]; [ left | right ].\n       destruct r as [x_y r1 r2]; exists x_y.\n        apply ci_ind'; exact r1.\n        apply ic_ind'; exact r2.\n       destruct r as [x_y r1 r2]; exists x_y.\n        apply cc_ind'; exact r1.\n        apply cc_ind'; exact r2.\n    destruct r as [x y r]; apply Hic'.\n    destruct r as [r | r]; [ left | right ].\n     exact r.\n     destruct r as [r | r]; [ left | right ].\n      apply ii_ind'; exact r.\n      destruct r as [r | r]; [ left | right ].\n       apply cc_ind'; exact r.\n       destruct r as [r | r]; [ left | right ].\n        destruct r as [x_y r1 r2]; exists x_y.\n         apply ic_ind'; exact r1.\n         apply cc_ind'; exact r2.\n        destruct r as [x_y r1 r2]; exists x_y.\n         apply ii_ind'; exact r1.\n         apply ic_ind'; exact r2.\n  Qed.\nEnd scheme.\nDefinition ppo := let ppoR := ii ⊓ [R] ⋅ top ⋅ [R] in let ppoW := ic ⊓ [R] ⋅ top ⋅ [W] in ppoR ⊔ ppoW.\nDefinition lwsync_0 := RM lwsync ⊔ WW lwsync.\nDefinition eieio_0 := WW eieio.\nDefinition dmb_st_0 := WW dmb_st.\nDefinition dsb_st_0 := WW dsb_st.\nDefinition strong := sync ⊔ (dmb ⊔ (dsb ⊔ (dmb_st_0 ⊔ dsb_st_0))).\nDefinition light := lwsync_0 ⊔ eieio_0.\nDefinition fence := strong ⊔ light.\nDefinition hb := ppo ⊔ (fence ⊔ rfe).\nDefinition thinair := acyclic hb.\nDefinition hbstar := hb^*.\nDefinition propbase := (fence ⊔ rfe ⋅ fence) ⋅ hbstar.\nDefinition chapo := rfe ⊔ (fre ⊔ (coe ⊔ (fre ⋅ rfe ⊔ coe ⋅ rfe))).\nDefinition prop := propbase ⊓ [W] ⋅ top ⋅ [W] ⊔ (chapo ⊔ 1) ⋅ (propbase^* ⋅ (strong ⋅ hbstar)).\nDefinition propagation := acyclic (co ⊔ prop).\nDefinition observation := irreflexive (fre ⋅ (prop ⋅ hbstar)).\nDefinition xx := po ⊓ [X] ⋅ top ⋅ [X].\nDefinition scXX := acyclic (co ⊔ xx).\nDefinition witness_conditions := True.\nDefinition model_conditions := uniproc /\\ (thinair /\\ (propagation /\\ (observation /\\ scXX))).\nEnd Model.\n\nHint Unfold events R W IW FW B RMW F rf po int ext loc addr data ctrl amo rmw unknown_set unknown_relation M emptyset classes_loc X tag2events emptyset_0 partition tag2instrs po_loc rfe rfi co0 toid fencerel ctrlcfence imply nodetour singlestep LKW A P WW WR RW RR RM MR WM MW MM AA AP PA PP AM MA noid atom obsco cobase uniproc co fr coi fri coe fre dd rdw detour addrpo dmb_st dsb_st dmb dsb isb ctrlisb sync lwsync eieio isync ctrlisync ci0 ii0 cc0 ic0 ppo lwsync_0 eieio_0 dmb_st_0 dsb_st_0 strong light fence hb thinair hbstar propbase chapo prop propagation observation xx scXX witness_conditions model_conditions : cat.\n\nDefinition valid (c : candidate) := model_conditions c.\n\n(* End of translation of model Model *)\n", "meta": {"author": "jmadiot", "repo": "cats", "sha": "d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95", "save_path": "github-repos/coq/jmadiot-cats", "path": "github-repos/coq/jmadiot-cats/cats-d3d6cae610dbd41c8a00d8cbdc0374cb02d6de95/models/herdcat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.21026438934116845}}
{"text": "Require Import List Ascii.\nRequire Import Ynot.\nRequire Import IO Net FS.\nRequire Import RSep.\n\nOpen Local Scope hprop_scope.\nOpen Local Scope stsepi_scope.\nOpen Local Scope char_scope.\n\nSet Implicit Arguments.\n\nInductive trace (local remote : Net.SockAddr)\n  (fd : File (BoundSocketModel local remote) (R :: W :: nil)) : IO.Trace -> Prop :=\n| NilCorrect : trace fd nil\n| ConsCorrect : forall request reply past, trace fd past -> secure fd ->\n  trace fd  \n      (WroteString stdout reply ++ ReadLine fd reply ++ \n        Flush fd :: WroteString fd request ++ ReadLine FS.stdin request ++ past).\n\nLemma proj_inv : forall (T1 T2 : Type) (a b : T1) (c d : T2),\n  (a,c) = (b,d) -> a = b /\\ c = d.\n  intros; inversion H; auto.\nQed.\n\nDefinition iter_post (local remote : Net.SockAddr) (req rep : list ascii)\n  (fd : File (BoundSocketModel local remote) (R :: W :: nil)) (tr : Trace) :=\n  WroteString stdout rep ++ ReadLine fd rep ++ Flush fd :: WroteString fd req ++ ReadLine stdin req ++ tr.\n\nDefinition iter : forall (local remote : Net.SockAddr)\n  (fd : File (BoundSocketModel local remote) (R :: W :: nil)) (tr : [Trace]),\n  STsep (tr ~~ IO.traced tr * [secure fd] * handle FS.stdin * handle FS.stdout * handle fd)\n        (fun tr':[Trace] => tr ~~ tr' ~~ Exists req :@ list ascii, Exists rep :@ list ascii,\n          [tr' = WroteString stdout rep ++ ReadLine fd rep ++ Flush fd :: WroteString fd req ++ ReadLine stdin req] *\n          traced (iter_post req rep fd tr) * [secure fd] * handle FS.stdin * handle FS.stdout * handle fd).\n  refine (fun local remote fd tr =>\n    ln <- readline FS.stdin FS.ro_readable tr <@> _ ;\n    writeline fd ln rw_writeable (tr ~~~ ReadLine stdin ln ++ tr) <@> _ ;;\n    flush fd (tr ~~~ WroteString fd ln ++ ReadLine stdin ln ++ tr) rw_writeable <@> _;;\n    reply <- readline fd rw_readable (tr ~~~ Flush fd :: WroteString fd ln ++ ReadLine stdin ln ++ tr) <@> _ ;\n    writeline FS.stdout reply FS.wo_writeable (tr ~~~ ReadLine fd reply ++ Flush fd :: WroteString fd ln ++ ReadLine stdin ln ++ tr) <@> _;;\n    {{Return (tr ~~~ WroteString FS.stdout reply ++ ReadLine fd reply ++ Flush fd :: WroteString fd ln ++ ReadLine stdin ln)}});\n  rsep fail auto; sep fail auto.\nQed.\n\nTheorem list_no_cycle' : forall (T : Type) (l1 l2 : list T),\n  l2 <> nil -> l2 ++ l1 <> l1.\n  intros; pose (@list_no_cycle T l1 l2); unfold not in *; auto.\nQed.\n\nLemma list_fix : forall T (x y z : list T) a,\n  (a :: x ++ y) ++ z = a :: x ++ y ++ z.\n  intros. simpl. rewrite app_ass. auto.\nQed.\n\nDefinition client : forall (local remote : Net.SockAddr) (tr : [Trace]),\n  STsep (tr ~~ IO.traced nil * handle FS.stdin * handle FS.stdout)\n        (fun _:unit => tr ~~ Exists v :@ Trace, IO.traced v * handle FS.stdin * handle FS.stdout).\n  refine (fun local remote tr =>\n    skt <- SSL.bindSocket local remote <@> _ ;\n\n    xxx <- IO.forever \n             (fun t:Trace => [trace skt t] * handle skt * [secure skt] * handle FS.stdin * handle FS.stdout)\n             (fun t:[Trace] => \n               {{ iter skt t <@> _ }})\n             [nil] ;\n    close skt;;\n    {{Return tt}}); try unfold iter_post.\n  solve [ rsep fail auto ].\n  solve [ rsep fail auto ].\n  solve [ intros; inhabiter; unpack_conc; canceler; sep fail auto ]. (** rsep doesn't have good enough support for re-packing **)\n  sep fail auto. repeat rewrite app_ass.  rewrite list_fix. sep fail ltac:(econstructor; auto). \n  solve [ rsep fail ltac:(auto; econstructor) ].\n  solve [ rsep fail auto ].\n  solve [ destruct xxx ].\n  solve [ rsep fail auto ].\n  solve [ rsep fail auto ].\n  solve [ destruct xxx ].\nQed.", "meta": {"author": "Ptival", "repo": "ynot", "sha": "cd6f28816c41bbef7464b644edeba099d397a01e", "save_path": "github-repos/coq/Ptival-ynot", "path": "github-repos/coq/Ptival-ynot/ynot-cd6f28816c41bbef7464b644edeba099d397a01e/examples/servers/SslClient.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.21018421121865188}}
{"text": "(** * Initialization *)\n\n(** Evalution of concurrent statements during the initialization phase\n    of the simulation.\n\n    The initialization phase is composed of the evaluation of the\n    first part of reset blocks followed by a stabilization phase. *)\n\nRequire Import common.GlobalTypes.\nRequire Import common.NatSet.\n\nRequire Import hvhdl.Environment.\nRequire Import hvhdl.AbstractSyntax.\nRequire Import hvhdl.SSEvaluation.\nRequire Import hvhdl.PortMapEvaluation.\nRequire Import hvhdl.Stabilization.\nRequire Import hvhdl.SemanticalDomains.\nRequire Import hvhdl.Petri.\nRequire Import hvhdl.HVhdlTypes.\nRequire Import hvhdl.CSEvaluation.\n\nInclude HVhdlCsNotations.\n\n(** Relational definition of the initialization phase. *)\n\nInductive Init (D__s : IdMap design) (Δ : ElDesign) (σ : DState) (cstmt : cs) (σ0 : DState) : Prop :=\n| Init_ :\n    forall σ',\n\n      (* * Premises * *)\n\n      (* Executes the first part of reset blocks.  *)\n      VConc D__s Δ σ init cstmt σ' ->\n\n      (* Stabilization phase.  *)\n      Stabilize D__s Δ σ' cstmt σ0 ->\n      \n      (* * Conclusion * *)\n      Init D__s Δ σ cstmt σ0.\n\n#[export] Hint Constructors Init : hvhdl.\n", "meta": {"author": "viampietro", "repo": "ver-hilecop", "sha": "cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4", "save_path": "github-repos/coq/viampietro-ver-hilecop", "path": "github-repos/coq/viampietro-ver-hilecop/ver-hilecop-cb539e9bf4e73f70d8e039fd56ddcfccd1e660d4/hvhdl/Initialization.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.21018420729662413}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import XOmega.\n\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import Conventions.\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\n\nRequire Import AbstractDataType.\nRequire Import Soundness.\nRequire Import TSysCall.\nRequire Import I64Layer.\nRequire Import LoadStoreSem2.\n\nRequire Import SecurityCommon.\nRequire Import ProofIrrelevance.\nRequire Import MakeProgram.\n\nRequire Import SecurityInv1.\nRequire Import SecurityInv2.\n\n(* This file combines the invariants established in SecurityInv1.v and SecurityInv2.v.\n   It defines two invariants secure_inv and secure_inv' which will be assumed by the\n   main security lemmas. We prove that both of these invariants are preserved by each\n   step of tsyscall, but only the first one holds on the initial state. See below\n   for further discussion, as well as Section 3 of the paper. *)\n\nSection WITHMEM.\n\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Local Instance : ExternalCallsOps (mwd (cdata RData)) := \n    CompatExternalCalls.compatlayer_extcall_ops tsyscall_layer.\n  Local Instance : LayerConfigurationOps := compatlayer_configuration_ops tsyscall_layer.\n\n  Section WITHIMPL.\n    \n    Context `{make_program_ops: !MakeProgramOps function Ctypes.type fundef unit}.\n    Context `{make_program_prf: !MakeProgram function Ctypes.type fundef unit}.\n\n    Variables (s : stencil) (M : module) (ge : genv) (b : block).\n    Hypothesis (Hmake : make_globalenv s M tsyscall_layer = OK ge).\n    Hypothesis (Hpsu : Genv.find_symbol ge proc_start_user = Some b).\n\n    Section SECURE_INV.\n\n      (* secure_inv and secure_inv', the two invariants defined in this file. Note\n         that all fields of these invariants come from either SecurityInv1.v or\n         SecurityInv2.v. *)\n\n      Record secure_inv id d :=\n        {\n          sec_high_inv: high_level_invariant d;\n          sec_ihost_inv: ihost d = true;\n          sec_RA_startuser_inv: RA_startuser b d;\n          sec_single_mapped_inv: single_mapped (LAT d) (nps d) id;\n          sec_unshared_inv: unshared (LAT d) (nps d) id\n        }.\n\n      (* secure_inv' is the part of the invariant that does not hold on the initial\n         state. Our security theorem only applies to configurations of mCertiKOS that \n         set things up to make this invariant hold. At some point, it might be nice to\n         to design a particular family of configurations and prove that all members\n         of this family correctly establish the invariant.\n\n         Note that the assumption here is only that the mCertiKOS configuration\n         spawns the observer process (if the observer process were never spawned, then\n         it would be meaningless to reason about its security), and that the initial\n         kernel process 0 eventually switches to a different user mode process \n         without placing itself on the ready queue (meaning that process 0 will never\n         be scheduled again).\n\n         Paper Reference: Section 3 *)\n      Record secure_inv' id rs d :=\n        {\n          sec_used: cused (ZMap.get id (AC d)) = true;\n          sec_usermode: usermode b rs d\n        }.\n\n      (* proof that secure_inv holds on the initial state *)\n\n      Lemma secure_inv_init : \n        forall id, secure_inv id init_adt.\n      Proof.\n        intro id; constructor.\n        - apply empty_data_high_level_invariant.\n        - auto.\n        - intros ? ? Hcon; simpl in Hcon; zmap_simpl; inv Hcon.\n        - intros ? ? ? ? ? Hcon; simpl in Hcon; zmap_simpl; inv Hcon.\n        - simpl; intros ? ? Hcon; inv Hcon.\n          zmap_simpl; inv H0.\n      Qed.\n\n      (* proofs that the two invariants are preserved by each step *)\n\n      Lemma secure_inv_preserved :\n        forall id rs rs' (m m' : mem) (d d' : cdata RData) t,\n          LAsm.step ge (State rs (m,d)) t (State rs' (m',d')) -> \n          secure_inv id d -> secure_inv id d'.\n      Proof.\n        intros id rs rs' m m' d d' t Hstep Hinv.\n        destruct Hinv; constructor.\n        - eapply step_inv1; eauto.\n        - eapply ihost_inv; eauto.\n        - eapply RA_startuser_inv; eauto.\n        - eapply step_inv1; eauto. \n        - eapply step_inv1; eauto. \n      Qed.\n\n      Lemma secure_inv'_preserved :\n        forall id rs rs' (m m' : mem) (d d' : cdata RData) t,\n          LAsm.step ge (State rs (m,d)) t (State rs' (m',d')) -> \n          secure_inv id d -> secure_inv' id rs d -> secure_inv' id rs' d'.\n      Proof.\n        intros id rs rs' m m' d d' t Hstep Hinv Hinv'.\n        destruct Hinv; destruct Hinv'; constructor.\n        - eapply step_inv1; eauto. \n        - eapply usermode_inv; eauto.\n      Qed.\n\n    End SECURE_INV.\n\n  End WITHIMPL.\n\nEnd WITHMEM.", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/security/SecurityInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.37387580881868493, "lm_q1q2_score": 0.21018419945256864}}
{"text": "(** introduces monoidal actions in a bicategorical setting\n\n    This lifts to bicategories the view on actions as put forward in G. Janelidze and G.M. Kelly: A Note on Actions of a Monoidal Category, Theory and Applications of Categories, Vol. 9, 2001, No. 4, pp 61-91.\n    The strength notion for the morphisms between actions is taken from\n    B. Ahrens, R. Matthes and A. Mörtberg: Implementing a category-theoretic framework for typed abstract syntax, Proceedings CPP'22.\n\nAuthors: Ralph Matthes and Kobe Wullaert 2022\n *)\n\n\nRequire Import UniMath.Foundations.PartD.\nRequire Import UniMath.MoreFoundations.All.\n\nRequire Import UniMath.CategoryTheory.Core.Categories.\nRequire Import UniMath.CategoryTheory.Core.Functors.\nRequire Import UniMath.CategoryTheory.Core.Isos.\nRequire Import UniMath.CategoryTheory.Core.NaturalTransformations.\n\nRequire Import UniMath.CategoryTheory.DisplayedCats.Core.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Total.\nRequire Import UniMath.CategoryTheory.DisplayedCats.Constructions.\n\nRequire Import UniMath.CategoryTheory.Monoidal.Categories.\nRequire Import UniMath.CategoryTheory.Monoidal.WhiskeredBifunctors.\nRequire Import UniMath.CategoryTheory.Monoidal.Functors.\nRequire Import UniMath.CategoryTheory.Monoidal.Displayed.WhiskeredDisplayedBifunctors.\nRequire Import UniMath.CategoryTheory.Monoidal.Displayed.Monoidal.\nRequire Import UniMath.CategoryTheory.Monoidal.Displayed.TotalMonoidal.\nRequire Import UniMath.CategoryTheory.Monoidal.Displayed.MonoidalSections.\nRequire Import UniMath.Bicategories.MonoidalCategories.EndofunctorsWhiskeredMonoidal.\n\nRequire Import UniMath.Bicategories.MonoidalCategories.WhiskeredMonoidalFromBicategory.\nRequire Import UniMath.Bicategories.MonoidalCategories.ActionBasedStrongFunctorsWhiskeredMonoidal.\n\nRequire Import UniMath.Bicategories.Core.Bicat.\nRequire Import UniMath.Bicategories.Core.BicategoryLaws.\nRequire Import UniMath.Bicategories.Core.Unitors.\nRequire Import UniMath.Bicategories.DisplayedBicats.DispBicat.\nRequire Import UniMath.Bicategories.Core.Invertible_2cells.\n\nImport Bicat.Notations.\nImport BifunctorNotations.\nImport DisplayedBifunctorNotations.\n\nLocal Open Scope cat.\nSection FixMoncatAndBicat.\n\n  Context {V : category}.\n  Context (Mon_V : monoidal V).\n\n  Notation \"X ⊗ Y\" := (X ⊗_{ Mon_V } Y).\n\n  Context (B : bicat).\n\n  Definition disp_actionbicat_disp_mor {a0 a0' : B}\n  {FA : V ⟶ category_from_bicat_and_ob a0}\n  (FAm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a0) FA)\n  {FA' : V ⟶ category_from_bicat_and_ob a0'}\n  (FA'm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a0') FA')\n  (G : B ⟦ a0, a0' ⟧): UU :=\n    ∑ δ : parameterized_distributivity_bicat_nat G,\n                param_distr_bicat_triangle_eq Mon_V FAm FA'm G δ ×\n                  param_distr_bicat_pentagon_eq Mon_V FAm FA'm G δ.\n\n  Lemma disp_actionbicat_disp_mor_eq {a0 a0' : B}\n  {FA : V ⟶ category_from_bicat_and_ob a0}\n  {FAm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a0) FA}\n  {FA' : V ⟶ category_from_bicat_and_ob a0'}\n  {FA'm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a0') FA'}\n  {G : B ⟦ a0, a0' ⟧}\n  (pm1 pm2: disp_actionbicat_disp_mor FAm FA'm G):\n    pr1 pm1 = pr1 pm2 -> pm1 = pm2.\n  Proof.\n    intro Hyp.\n    apply subtypePath.\n    - intro δ. apply isapropdirprod.\n      + apply isaprop_param_distr_bicat_triangle_eq.\n      + apply isaprop_param_distr_bicat_pentagon_eq.\n    - exact Hyp.\n  Qed.\n\n  Definition disp_actionbicat_disp_ob_mor : disp_cat_ob_mor B.\n  Proof.\n    use tpair.\n    - intro a0.\n      exact (∑ FA: functor V (category_from_bicat_and_ob a0),\n                fmonoidal Mon_V (monoidal_from_bicat_and_ob a0) FA).\n    - intros a0 a0' [FA FAm] [FA' FA'm] G.\n      exact (disp_actionbicat_disp_mor FAm FA'm G).\n  Defined.\n\n  Definition disp_actionbicat_disp_id_nat_trans\n  {a : B}\n  {FA : V ⟶ category_from_bicat_and_ob a}\n  (FAm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a) FA):\n    H(V:=V)(FA':=FA) (id₁ a) ⟹ H'(FA:=FA) (id₁ a).\n  Proof.\n    use make_nat_trans.\n    * intro v. cbn. exact (lunitor _ • rinvunitor _).\n    * abstract ( intros v w f;\n                 cbn;\n                 rewrite vassocr;\n                 rewrite vcomp_lunitor;\n                 do 2 rewrite vassocl;\n                 apply maponpaths;\n                 apply pathsinv0, (rhs_right_inv_cell _ _ _ (is_invertible_2cell_runitor _));\n                 rewrite vassocl;\n                 rewrite vcomp_runitor;\n                 rewrite vassocr;\n                 rewrite rinvunitor_runitor;\n                 apply id2_left ).\n  Defined.\n\n  Lemma disp_actionbicat_disp_id_triangle {a : B}\n  {FA : V ⟶ category_from_bicat_and_ob a}\n  (FAm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a) FA):\n    param_distr_bicat_triangle_eq Mon_V FAm FAm (id₁ a) (disp_actionbicat_disp_id_nat_trans FAm).\n  Proof.\n    red; cbn.\n    rewrite vassocr.\n    rewrite vcomp_lunitor.\n    do 2 rewrite vassocl.\n    rewrite lunitor_id_is_left_unit_id.\n    apply maponpaths.\n    apply pathsinv0, (rhs_right_inv_cell _ _ _ (is_invertible_2cell_runitor _)).\n    rewrite vassocl.\n    apply pathsinv0, (rhs_left_inv_cell _ _ _ (is_invertible_2cell_lunitor _)).\n    rewrite vcomp_runitor.\n    rewrite lunitor_id_is_left_unit_id.\n    apply idpath.\n  Qed.\n\n  Lemma disp_actionbicat_disp_id_pentagon {a : B}\n    {FA : V ⟶ category_from_bicat_and_ob a}\n    (FAm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a) FA):\n    param_distr_bicat_pentagon_eq Mon_V FAm FAm (id₁ a) (disp_actionbicat_disp_id_nat_trans FAm).\n  Proof.\n    red; cbn.\n    intros v w.\n    unfold param_distr_bicat_pentagon_eq_body, param_distr_bicat_pentagon_eq_body_RHS.\n    cbn.\n    etrans.\n    { rewrite vassocl. apply maponpaths. rewrite vassocr. apply maponpaths_2.\n      apply vcomp_lunitor. }\n    etrans.\n    { repeat rewrite vassocr. apply idpath. }\n    apply pathsinv0, (rhs_right_inv_cell _ _ _ (is_invertible_2cell_runitor _)).\n    etrans.\n    { rewrite !vassocl. (* instead of repeat rewrite vassocl - hint by Niels van der Weide *) apply idpath. }\n    rewrite vcomp_runitor.\n    repeat rewrite vassocr. apply maponpaths_2.\n    (* now pure bicategorical reasoning *)\n    rewrite <- rwhisker_vcomp.\n    rewrite <- lwhisker_vcomp.\n    rewrite <- runitor_triangle.\n    rewrite <- lunitor_triangle.\n    etrans.\n    2: { rewrite vassocr.\n         rewrite rassociator_lassociator.\n         apply pathsinv0, id2_left. }\n    etrans.\n    { repeat rewrite vassocr. apply maponpaths_2.\n      repeat rewrite vassocl. rewrite lassociator_rassociator.\n      rewrite id2_right. apply idpath. }\n    repeat rewrite vassocl.\n    etrans.\n    { do 4 apply maponpaths.\n      rewrite lwhisker_vcomp.\n      rewrite rinvunitor_runitor.\n      apply lwhisker_id2. }\n    rewrite id2_right.\n    etrans.\n    2: { apply id2_right. }\n    apply maponpaths.\n    rewrite lunitor_lwhisker.\n    rewrite rwhisker_vcomp.\n    rewrite rinvunitor_runitor.\n    apply id2_rwhisker.\n  Qed.\n\n  Definition disp_actionbicat_disp_comp_nat_trans_data {a0 a1 a2 : B}\n      {g1 : B ⟦ a0, a1 ⟧}\n      {g2 : B ⟦ a1, a2 ⟧}\n      {FA : V ⟶ category_from_bicat_and_ob a0}\n      {FAm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a0) FA}\n      {FA' : V ⟶ category_from_bicat_and_ob a1}\n      {FA'm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a1) FA'}\n      {FA'' : V ⟶ category_from_bicat_and_ob a2}\n      {FA''m : fmonoidal Mon_V (monoidal_from_bicat_and_ob a2) FA''}\n      (Hyp1 : disp_actionbicat_disp_mor FAm FA'm g1)\n      (Hyp2 : disp_actionbicat_disp_mor FA'm FA''m g2):\n    nat_trans_data (H(V:=V)(FA':=FA'') (g1 · g2)) (H'(FA:=FA) (g1 · g2)).\n  Proof.\n    intro v. cbn.\n    exact (rassociator g1 g2 (FA'' v)\n             • ((g1 ◃ (pr1 Hyp2 v))\n             • ((lassociator g1 (FA' v) g2\n             • ((pr1 Hyp1 v) ▹ g2) : g1 · H' g2 v ==> FA v · g1 · g2)\n             • rassociator (FA v) g1 g2))).\n    (* refine (vcomp2 _ _).\n       { apply rassociator. }\n       refine (vcomp2 _ _).\n       { apply lwhisker.\n       apply Hyp2. }\n       refine (vcomp2 _ _).\n       2: { apply rassociator. }\n       cbn.\n       refine (vcomp2 _ _).\n       { apply lassociator. }\n       apply rwhisker.\n       apply Hyp1. *)\n  Defined.\n\n  Lemma disp_actionbicat_disp_comp_is_nat_trans {a0 a1 a2 : B}\n    {g1 : B ⟦ a0, a1 ⟧}\n    {g2 : B ⟦ a1, a2 ⟧}\n    {FA : V ⟶ category_from_bicat_and_ob a0}\n    {FAm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a0) FA}\n    {FA' : V ⟶ category_from_bicat_and_ob a1}\n    {FA'm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a1) FA'}\n    {FA'' : V ⟶ category_from_bicat_and_ob a2}\n    {FA''m : fmonoidal Mon_V (monoidal_from_bicat_and_ob a2) FA''}\n    (Hyp1 : disp_actionbicat_disp_mor FAm FA'm g1)\n    (Hyp2 : disp_actionbicat_disp_mor FA'm FA''m g2):\n    is_nat_trans _ _ (disp_actionbicat_disp_comp_nat_trans_data Hyp1 Hyp2).\n  Proof.\n    intros v w f. unfold disp_actionbicat_disp_comp_nat_trans_data.\n    cbn; rewrite vassocr.\n\n    rewrite (! lwhisker_lwhisker_rassociator _ _ _ _ _ _ _ _ _).\n    rewrite vassocr.\n    etrans. {\n      apply maponpaths_2.\n      rewrite vassocl.\n      apply maponpaths.\n      exact (lwhisker_vcomp g1  (g2 ◃ # FA'' f) (pr1 Hyp2 w)).\n    }\n\n    etrans.\n    2: {\n      rewrite !vassocr.\n      rewrite vassocl.\n      apply maponpaths.\n      apply rwhisker_rwhisker_alt.\n    }\n\n    rewrite !vassocl.\n    apply maponpaths.\n    rewrite !vassocr.\n    apply maponpaths_2.\n    etrans. {\n      apply maponpaths_2.\n      apply maponpaths_2.\n      apply maponpaths.\n      exact (pr21 Hyp2 v w f).\n    }\n    etrans.\n    2: {\n      rewrite vassocl.\n      apply maponpaths.\n      rewrite rwhisker_vcomp.\n      apply maponpaths.\n      exact (pr21 Hyp1 v w f).\n    }\n\n    cbn.\n    rewrite (! lwhisker_vcomp _ _ _).\n\n    do 3 rewrite vassocl.\n    apply maponpaths.\n    rewrite vassocr.\n    etrans.\n    2: {\n      rewrite (! rwhisker_vcomp _ _ _).\n      rewrite vassocr.\n      apply idpath.\n    }\n    apply maponpaths_2.\n    apply rwhisker_lwhisker.\n  Qed.\n\n  Definition disp_actionbicat_disp_comp_nat_trans {a0 a1 a2 : B}\n    {g1 : B ⟦ a0, a1 ⟧}\n    {g2 : B ⟦ a1, a2 ⟧}\n    {FA : V ⟶ category_from_bicat_and_ob a0}\n    {FAm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a0) FA}\n    {FA' : V ⟶ category_from_bicat_and_ob a1}\n    {FA'm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a1) FA'}\n    {FA'' : V ⟶ category_from_bicat_and_ob a2}\n    {FA''m : fmonoidal Mon_V (monoidal_from_bicat_and_ob a2) FA''}\n    (Hyp1 : disp_actionbicat_disp_mor FAm FA'm g1)\n    (Hyp2 : disp_actionbicat_disp_mor FA'm FA''m g2):\n    parameterized_distributivity_bicat_nat(V:=V)(FA:=FA)(FA':=FA'') (g1 · g2) :=\n    _,, disp_actionbicat_disp_comp_is_nat_trans Hyp1 Hyp2.\n\n  Lemma disp_actionbicat_disp_comp_triangle {a0 a1 a2 : B}\n    {g1 : B ⟦ a0, a1 ⟧}\n    {g2 : B ⟦ a1, a2 ⟧}\n    {FA : V ⟶ category_from_bicat_and_ob a0}\n    {FAm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a0) FA}\n    {FA' : V ⟶ category_from_bicat_and_ob a1}\n    {FA'm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a1) FA'}\n    {FA'' : V ⟶ category_from_bicat_and_ob a2}\n    {FA''m : fmonoidal Mon_V (monoidal_from_bicat_and_ob a2) FA''}\n    (Hyp1 : disp_actionbicat_disp_mor FAm FA'm g1)\n    (Hyp2 : disp_actionbicat_disp_mor FA'm FA''m g2):\n    param_distr_bicat_triangle_eq Mon_V FAm FA''m (g1 · g2) (disp_actionbicat_disp_comp_nat_trans Hyp1 Hyp2).\n  Proof.\n    red; cbn.\n    unfold disp_actionbicat_disp_comp_nat_trans_data.\n    assert (aux1 := pr12 Hyp1).\n    assert (aux2 := pr12 Hyp2).\n    apply param_distr_bicat_triangle_eq_variant0_follows in aux1.\n    apply param_distr_bicat_triangle_eq_variant0_follows in aux2.\n    red in aux1, aux2; cbn in aux1, aux2.\n    rewrite aux1, aux2.\n    clear Hyp1 Hyp2 aux1 aux2.\n    unfold param_distr_bicat_triangle_eq_variant0_RHS.\n    repeat rewrite <- lwhisker_vcomp.\n    repeat rewrite <- rwhisker_vcomp.\n    etrans.\n    { repeat rewrite lassocr.\n      apply maponpaths.\n      repeat rewrite vassocr.\n      rewrite lwhisker_lwhisker_rassociator.\n      apply idpath. }\n    etrans.\n    { repeat rewrite vassocr.\n      do 10 apply maponpaths_2.\n      rewrite lwhisker_vcomp.\n      apply maponpaths.\n      apply (z_iso_inv_after_z_iso (_,,fmonoidal_preservesunitstrongly FA''m)). }\n    cbn.\n    rewrite lwhisker_id2.\n    rewrite id2_left.\n    etrans.\n    { repeat rewrite vassocl.\n      do 3 apply maponpaths.\n      repeat rewrite vassocr.\n      do 5 apply maponpaths_2.\n      apply rwhisker_lwhisker. }\n    etrans.\n    { repeat rewrite vassocr.\n      do 4 apply maponpaths_2.\n      repeat rewrite vassocl.\n      do 4 apply maponpaths.\n      rewrite rwhisker_vcomp.\n      rewrite lwhisker_vcomp.\n      do 2 apply maponpaths.\n      apply (z_iso_inv_after_z_iso (_,,fmonoidal_preservesunitstrongly FA'm)). }\n    cbn.\n    rewrite lwhisker_id2.\n    rewrite id2_rwhisker.\n    rewrite id2_right.\n    etrans.\n    { repeat rewrite vassocl.\n      rewrite rwhisker_rwhisker_alt.\n      apply idpath. }\n    repeat rewrite vassocr.\n    apply maponpaths_2.\n    (* now pure bicategorical reasoning *)\n    rewrite <- runitor_triangle.\n    apply (rhs_right_inv_cell _ _ _ (is_invertible_2cell_lunitor _)).\n    rewrite <- lunitor_triangle.\n    repeat rewrite vassocr.\n    etrans.\n    { apply maponpaths_2.\n      repeat rewrite vassocl.\n      rewrite rassociator_lassociator.\n      rewrite id2_right.\n      apply idpath. }\n    etrans.\n    { repeat rewrite vassocl.\n      rewrite rwhisker_vcomp.\n      rewrite linvunitor_lunitor.\n      rewrite id2_rwhisker.\n      rewrite id2_right.\n      apply idpath. }\n    etrans.\n    2: { apply id2_right. }\n    repeat rewrite vassocl.\n    do 2 apply maponpaths.\n    rewrite runitor_rwhisker.\n    rewrite lwhisker_vcomp.\n    rewrite linvunitor_lunitor.\n    apply lwhisker_id2.\n  Qed.\n\n  Lemma disp_actionbicat_disp_comp_pentagon {a0 a1 a2 : B}\n    {g1 : B ⟦ a0, a1 ⟧}\n    {g2 : B ⟦ a1, a2 ⟧}\n    {FA : V ⟶ category_from_bicat_and_ob a0}\n    {FAm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a0) FA}\n    {FA' : V ⟶ category_from_bicat_and_ob a1}\n    {FA'm : fmonoidal Mon_V (monoidal_from_bicat_and_ob a1) FA'}\n    {FA'' : V ⟶ category_from_bicat_and_ob a2}\n    {FA''m : fmonoidal Mon_V (monoidal_from_bicat_and_ob a2) FA''}\n    (Hyp1 : disp_actionbicat_disp_mor FAm FA'm g1)\n    (Hyp2 : disp_actionbicat_disp_mor FA'm FA''m g2):\n    param_distr_bicat_pentagon_eq Mon_V FAm FA''m (g1 · g2) (disp_actionbicat_disp_comp_nat_trans Hyp1 Hyp2).\n  Proof.\n    intros v w.\n    red; cbn.\n    unfold param_distr_bicat_pentagon_eq_body_RHS,\n      disp_actionbicat_disp_comp_nat_trans, disp_actionbicat_disp_comp_nat_trans_data.\n    set (aux1 := pr22 Hyp1 v w).\n    set (aux2 := pr22 Hyp2 v w).\n    apply param_distr_bicat_pentagon_eq_body_variant_follows in aux1.\n    apply param_distr_bicat_pentagon_eq_body_variant_follows in aux2.\n    red in aux1, aux2; cbn in aux1, aux2.\n    rewrite aux1, aux2.\n    clear aux1 aux2.\n    unfold param_distr_bicat_pentagon_eq_body_variant_RHS, param_distr_bicat_pentagon_eq_body_RHS.\n    induction Hyp1 as [δ1 [trieq1 pentaeq1]].\n    induction Hyp2 as [δ2 [trieq2 pentaeq2]].\n    cbn.\n    clear trieq1 trieq2 pentaeq1 pentaeq2.\n    repeat rewrite rwhisker_vcomp.\n    repeat rewrite <- lwhisker_vcomp.\n    etrans.\n    { repeat rewrite vassocl.\n      apply maponpaths.\n      repeat rewrite vassocr.\n      do 10 apply maponpaths_2.\n      apply pathsinv0, lwhisker_lwhisker_rassociator. }\n    etrans.\n    { repeat rewrite vassocl.\n      do 2 apply maponpaths.\n      repeat rewrite vassocr.\n      do 9 apply maponpaths_2.\n      etrans.\n      { rewrite lwhisker_vcomp.\n        apply maponpaths.\n        rewrite lwhisker_vcomp.\n        apply maponpaths.\n        apply (pr2 (fmonoidal_preservestensorstrongly FA''m v w)). }\n      cbn.\n      rewrite lwhisker_id2.\n      apply lwhisker_id2.\n    }\n    rewrite id2_left.\n    etrans.\n    { repeat rewrite vassocr.\n      apply idpath. }\n    apply pathsinv0.\n    apply (vcomp_move_L_Vp _ _ _ (is_invertible_2cell_lassociator _ _ _)).\n    etrans.\n    { repeat rewrite vassocl.\n      do 8 apply maponpaths.\n      apply pathsinv0, rwhisker_rwhisker. }\n    repeat rewrite <- rwhisker_vcomp.\n    repeat rewrite vassocr.\n    apply maponpaths_2.\n    etrans.\n    2: { do 5 apply maponpaths_2.\n         repeat rewrite vassocl.\n         do 7 apply maponpaths.\n         etrans.\n         2: { rewrite vassocr.\n              apply maponpaths_2.\n              apply pathsinv0, rwhisker_lwhisker. }\n         rewrite vassocl.\n         apply maponpaths.\n         rewrite rwhisker_vcomp.\n         apply maponpaths.\n         rewrite lwhisker_vcomp.\n         apply maponpaths.\n         apply pathsinv0, (pr2 (fmonoidal_preservestensorstrongly FA'm v w)). }\n    cbn.\n    rewrite lwhisker_id2.\n    rewrite id2_rwhisker.\n    rewrite id2_right.\n    (* the equation is now free from the preservation of the tensor by the given strong monoidal functors;\n       both sides of the equation are chains of 13 two-cells *)\n    etrans.\n    2: { repeat rewrite vassocl.\n         do 6 apply maponpaths.\n         repeat rewrite vassocr.\n         do 4 apply maponpaths_2.\n         apply pathsinv0, lassociator_lassociator. }\n    etrans.\n    { repeat rewrite vassocl.\n      do 4 apply maponpaths.\n      repeat rewrite vassocr.\n      do 6 apply maponpaths_2.\n      apply rassociator_rassociator. }\n    (* both sides of the equation are chains of 12 two-cells *)\n    etrans.\n    2: { repeat rewrite vassocr.\n         do 10 apply maponpaths_2.\n         apply rassociator_rassociator. }\n    repeat rewrite vassocl.\n    apply maponpaths.\n    etrans.\n    2: { repeat rewrite vassocr.\n         do 8 apply maponpaths_2.\n         etrans.\n         2: { apply maponpaths_2.\n              rewrite vassocl.\n              etrans.\n              2: { apply maponpaths.\n                   rewrite lwhisker_vcomp.\n                   apply maponpaths.\n                   apply pathsinv0, rassociator_lassociator. }\n              rewrite lwhisker_id2.\n              apply pathsinv0, id2_right. }\n         apply pathsinv0, rwhisker_lwhisker_rassociator.\n    }\n    repeat rewrite vassocl.\n    apply maponpaths.\n    (* two occurrences of [δ2] vanished *)\n    etrans.\n    { apply maponpaths.\n      repeat rewrite vassocr.\n      do 5 apply maponpaths_2.\n      rewrite rwhisker_rwhisker_alt.\n        rewrite vassocl.\n        rewrite lwhisker_lwhisker_rassociator.\n        rewrite vassocl.\n        apply maponpaths.\n        rewrite vassocr.\n        apply maponpaths_2.\n        apply vcomp_whisker. }\n    etrans.\n    2: { do 2 apply maponpaths.\n         repeat rewrite vassocr.\n         do 3 apply maponpaths_2.\n         rewrite lwhisker_lwhisker.\n         rewrite vassocl.\n         rewrite rwhisker_rwhisker.\n         apply idpath.\n    }\n    assert (Haux: (lassociator g1 (FA' v) g2 ▹ FA'' w) • rassociator (g1 · FA' v) g2 (FA'' w) =\n                    rassociator g1 (FA' v · g2) (FA'' w) • (g1 ◃ rassociator (FA' v) g2 (FA'' w)) • lassociator g1 (FA' v) (g2 · FA'' w)).\n    { etrans.\n      2: { rewrite vassocl.\n           apply inverse_pentagon_2. }\n      apply maponpaths_2.\n      apply pathsinv0, hcomp_identity_right. }\n    etrans.\n    { repeat rewrite vassocr.\n      do 8 apply maponpaths_2.\n      apply Haux. }\n    clear Haux.\n    repeat rewrite vassocl.\n    do 5 apply maponpaths.\n    (* two occurrences of [δ1] and [δ2] vanished\n       ten two-cells remain, one occurrence of [δ1] on both sides *)\n    assert (Haux2: rassociator (FA v) g1 (FA' w · g2) • (FA v ◃ lassociator g1 (FA' w) g2) =\n                     lassociator (FA v · g1) (FA' w) g2 • ((rassociator (FA v) g1 (FA' w) ▹ g2) • rassociator (FA v) (g1 · FA' w) g2)).\n    { rewrite <- hcomp_identity_right.\n      etrans.\n      2: { apply inverse_pentagon_4. }\n      rewrite hcomp_identity_left.\n      apply idpath.\n    }\n    etrans.\n    { repeat rewrite vassocr.\n      do 4 apply maponpaths_2.\n      exact Haux2. }\n    clear Haux2.\n    repeat rewrite vassocl.\n    do 2 apply maponpaths.\n    etrans.\n    { repeat rewrite vassocr.\n      do 3 apply maponpaths_2.\n      apply rwhisker_lwhisker_rassociator. }\n    repeat rewrite vassocl.\n    apply maponpaths.\n    (* no more [δ1] nor [δ2] *)\n    etrans.\n    { repeat rewrite vassocr.\n      apply maponpaths_2.\n      rewrite vassocl.\n      apply pathsinv0, inverse_pentagon_2. }\n    rewrite vassocl.\n    rewrite rassociator_lassociator.\n    rewrite hcomp_identity_right.\n    apply id2_right.\n  Qed.\n\n  Definition disp_actionbicat_disp_id_comp : disp_cat_id_comp B disp_actionbicat_disp_ob_mor.\n  Proof.\n    split.\n    - intros a [FA FAm].\n      use tpair.\n      + exact (disp_actionbicat_disp_id_nat_trans FAm).\n      + split; [apply disp_actionbicat_disp_id_triangle | apply disp_actionbicat_disp_id_pentagon]; assumption.\n    - intros a0 a1 a2 g1 g2 [FA FAm] [FA' FA'm] [FA'' FA''m] Hyp1 Hyp2. cbn in Hyp1, Hyp2.\n      exists (disp_actionbicat_disp_comp_nat_trans Hyp1 Hyp2).\n      + split; [apply disp_actionbicat_disp_comp_triangle | apply disp_actionbicat_disp_comp_pentagon]; assumption.\n  Defined.\n\n  Definition disp_actionbicat_disp_catdata : disp_cat_data B\n    := (disp_actionbicat_disp_ob_mor,,disp_actionbicat_disp_id_comp).\n\n  Definition bidisp_actionbicat_disp_2cell_eq_body\n    {a a' : B}\n    {f1 f2 : B ⟦ a, a' ⟧}\n    (η : f1 ==> f2)\n    (FA : V ⟶ category_from_bicat_and_ob a)\n    (FA' : V ⟶ category_from_bicat_and_ob a')\n    (δ1 : parameterized_distributivity_bicat_nat f1)\n    (δ2 : parameterized_distributivity_bicat_nat f2)\n    (v : V): UU\n    := δ1 v • (FA v ◃ η) = (η ▹ FA' v) • δ2 v.\n\n  Lemma isaprop_bidisp_actionbicat_disp_2cell_eq_body\n    {a a' : B}\n    {f1 f2 : B ⟦ a, a' ⟧}\n    (η : f1 ==> f2)\n    (FA : V ⟶ category_from_bicat_and_ob a)\n    (FA' : V ⟶ category_from_bicat_and_ob a')\n    (δ1 : parameterized_distributivity_bicat_nat f1)\n    (δ2 : parameterized_distributivity_bicat_nat f2)\n    (v : V): isaprop (bidisp_actionbicat_disp_2cell_eq_body η FA FA' δ1 δ2 v).\n  Proof.\n    apply B.\n  Qed.\n\n  Definition bidisp_actionbicat_disp_2cell_struct : disp_2cell_struct disp_actionbicat_disp_ob_mor.\n  Proof.\n    intros a a' f1 f2 η [FA FAm] [FA' FA'm] [δ1 [tria1 penta1]] [δ2 [tria2 penta2]].\n    exact (∏ v: V, bidisp_actionbicat_disp_2cell_eq_body η FA FA' δ1 δ2 v).\n  Defined.\n\n  Lemma isaprop_bidisp_actionbicat_disp_2cell_struct\n    {a a' : B}\n    {f1 f2 : B ⟦ a, a' ⟧}\n    (η : f1 ==> f2)\n    {M : disp_actionbicat_disp_catdata a}\n    {M' : disp_actionbicat_disp_catdata a'}\n    (FM1 : M -->[ f1] M')\n    (FM2 : M -->[ f2] M'):\n    isaprop (bidisp_actionbicat_disp_2cell_struct a a' f1 f2 η M M' FM1 FM2).\n  Proof.\n    apply impred.\n    intro v.\n    apply isaprop_bidisp_actionbicat_disp_2cell_eq_body.\n  Qed.\n\n  Definition bidisp_actionbicat_disp_prebicat_1_id_comp_cells\n    :  disp_prebicat_1_id_comp_cells B\n    := (disp_actionbicat_disp_catdata,, bidisp_actionbicat_disp_2cell_struct).\n\n  Ltac aux_bidisp_actionbicat_disp_prebicat_ops :=\n      intros; red; cbn;\n      unfold bidisp_actionbicat_disp_2cell_struct, bidisp_actionbicat_disp_2cell_eq_body;\n      intro v;\n      unfold disp_actionbicat_disp_comp_nat_trans, disp_actionbicat_disp_comp_nat_trans_data;\n      cbn; show_id_type.\n\n  Definition actionbicat_ax2 : UU :=\n  (∏ (a b c d : B) (f : B ⟦ a, b ⟧) (g : B ⟦ b, c ⟧) (h : B ⟦ c, d ⟧)\n  (w : bidisp_actionbicat_disp_prebicat_1_id_comp_cells a)\n  (x : bidisp_actionbicat_disp_prebicat_1_id_comp_cells b)\n  (y : bidisp_actionbicat_disp_prebicat_1_id_comp_cells c)\n  (z : bidisp_actionbicat_disp_prebicat_1_id_comp_cells d) (ff : w -->[ f] x)\n  (gg : x -->[ g] y) (hh : y -->[ h] z),\n  disp_2cells (rassociator f g h) (ff ;; gg ;; hh) (ff ;; (gg ;; hh)))\n × (∏ (a b c d : B) (f : B ⟦ a, b ⟧) (g : B ⟦ b, c ⟧) (h : B ⟦ c, d ⟧)\n    (w : bidisp_actionbicat_disp_prebicat_1_id_comp_cells a)\n    (x : bidisp_actionbicat_disp_prebicat_1_id_comp_cells b)\n    (y : bidisp_actionbicat_disp_prebicat_1_id_comp_cells c)\n    (z : bidisp_actionbicat_disp_prebicat_1_id_comp_cells d) (ff : w -->[ f] x)\n    (gg : x -->[ g] y) (hh : y -->[ h] z),\n    disp_2cells (lassociator f g h) (ff ;; (gg ;; hh)) (ff ;; gg ;; hh))\n   × (∏ (a b : B) (f g h : B ⟦ a, b ⟧) (r : f ==> g) (s : g ==> h)\n      (x : bidisp_actionbicat_disp_prebicat_1_id_comp_cells a)\n      (y : bidisp_actionbicat_disp_prebicat_1_id_comp_cells b) (ff : x -->[ f] y)\n      (gg : x -->[ g] y) (hh : x -->[ h] y),\n      disp_2cells r ff gg → disp_2cells s gg hh → disp_2cells (r • s) ff hh)\n     × (∏ (a b c : B) (f : B ⟦ a, b ⟧) (g1 g2 : B ⟦ b, c ⟧) (r : g1 ==> g2)\n        (x : bidisp_actionbicat_disp_prebicat_1_id_comp_cells a)\n        (y : bidisp_actionbicat_disp_prebicat_1_id_comp_cells b)\n        (z : bidisp_actionbicat_disp_prebicat_1_id_comp_cells c) (ff : x -->[ f] y)\n        (gg1 : y -->[ g1] z) (gg2 : y -->[ g2] z),\n        disp_2cells r gg1 gg2 → disp_2cells (f ◃ r) (ff ;; gg1) (ff ;; gg2))\n       × (∏ (a b c : B) (f1 f2 : B ⟦ a, b ⟧) (g : B ⟦ b, c ⟧) (r : f1 ==> f2)\n          (x : bidisp_actionbicat_disp_prebicat_1_id_comp_cells a)\n          (y : bidisp_actionbicat_disp_prebicat_1_id_comp_cells b)\n          (z : bidisp_actionbicat_disp_prebicat_1_id_comp_cells c) (ff1 : x -->[ f1] y)\n          (ff2 : x -->[ f2] y) (gg : y -->[ g] z),\n         disp_2cells r ff1 ff2 → disp_2cells (r ▹ g) (ff1 ;; gg) (ff2 ;; gg)).\n\n  Context (ax2 : actionbicat_ax2).\n\n  Lemma bidisp_actionbicat_disp_prebicat_ops :\n    disp_prebicat_ops bidisp_actionbicat_disp_prebicat_1_id_comp_cells.\n  Proof.\n    split; [| split; [| split ; [| split ; [| split]]]].\n    (*repeat split; intros; red ; cbn;\n      unfold bidisp_actionbicat_disp_2cell_struct, bidisp_actionbicat_disp_2cell_eq_body;\n      intro v;\n      unfold disp_actionbicat_disp_comp_nat_trans, disp_actionbicat_disp_comp_nat_trans_data;\n      cbn; show_id_type. *)\n    - aux_bidisp_actionbicat_disp_prebicat_ops. rewrite lwhisker_id2. rewrite id2_right.\n      rewrite id2_rwhisker. apply pathsinv0, id2_left.\n    - aux_bidisp_actionbicat_disp_prebicat_ops. rewrite <- rwhisker_vcomp.\n      etrans.\n      { repeat rewrite vassocl. do 5 apply maponpaths.\n        apply lunitor_lwhisker. }\n      rewrite rwhisker_vcomp.\n      rewrite rinvunitor_runitor.\n      rewrite id2_rwhisker.\n      rewrite id2_right.\n      rewrite lunitor_triangle.\n      rewrite vcomp_lunitor.\n      rewrite vassocr.\n      apply maponpaths_2.\n      apply (lhs_left_invert_cell _ _ _ (is_invertible_2cell_rassociator _ _ _)).\n      cbn.\n      apply pathsinv0, lunitor_triangle.\n    - aux_bidisp_actionbicat_disp_prebicat_ops. rewrite <- lwhisker_vcomp.\n      etrans.\n      {\n        repeat rewrite vassocl.\n        do 5 apply maponpaths.\n        apply runitor_triangle.\n      }\n\n      etrans. {\n        do 2 apply maponpaths.\n        rewrite vassocr.\n        apply maponpaths_2.\n        apply rinvunitor_triangle.\n      }\n      rewrite vcomp_runitor.\n      etrans. {\n        do 2 apply maponpaths.\n        rewrite vassocr.\n        rewrite rinvunitor_runitor.\n        apply id2_left.\n      }\n      rewrite vassocr.\n      apply maponpaths_2.\n      apply lunitor_lwhisker.\n    - aux_bidisp_actionbicat_disp_prebicat_ops. etrans.\n      2: {\n        do 3 apply maponpaths.\n        apply maponpaths_2.\n        rewrite <- rwhisker_vcomp.\n        rewrite vassocr.\n        apply maponpaths_2.\n        apply (! lunitor_triangle _ _ _ _ _ _).\n      }\n      etrans.\n      2: {\n        do 2 apply maponpaths.\n        rewrite vassocr.\n        apply maponpaths_2.\n        rewrite vassocr.\n        apply maponpaths_2.\n        apply (! vcomp_lunitor _ _ _).\n      }\n\n      rewrite vassocr.\n      rewrite <- linvunitor_assoc.\n      rewrite !vassocr.\n      rewrite linvunitor_lunitor.\n      rewrite id2_left.\n      rewrite vassocl.\n      apply maponpaths.\n      rewrite (! hcomp_identity_right _ _ _ _).\n      rewrite (! hcomp_identity_left _ _ _ _).\n      apply triangle_r_inv.\n    - aux_bidisp_actionbicat_disp_prebicat_ops. rewrite <- lwhisker_vcomp.\n      etrans.\n      2: {\n        apply maponpaths.\n        rewrite vassocr.\n        apply maponpaths_2.\n        rewrite vassocr.\n        apply maponpaths_2.\n        apply (! lunitor_lwhisker _ _).\n      }\n      (* Search (lassociator _ _ (id₁ _)). *)\n      etrans.\n      2: {\n        apply maponpaths.\n        rewrite vassocl.\n        apply maponpaths.\n        rewrite vassocr.\n        apply maponpaths_2.\n        rewrite vassocr.\n        apply maponpaths_2.\n        apply (! rinvunitor_triangle  _ _ _ _ _ _).\n      }\n      rewrite vassocr.\n      rewrite rwhisker_vcomp.\n      rewrite rinvunitor_runitor.\n      rewrite id2_rwhisker.\n      rewrite id2_left.\n      rewrite left_unit_inv_assoc.\n      rewrite vassocr.\n      apply maponpaths_2.\n      rewrite rinvunitor_natural.\n      apply maponpaths.\n      apply hcomp_identity_right.\n    - exact ax2.\n\n  (* probably not useful for 10th goal after splitting:\n      induction x as [FA FAm].\n      induction y as [FA' FA'm].\n      induction f' as [δ [tria penta]].\n      cbn.\n      red in tria, penta. unfold param_distr_bicat_pentagon_eq_body in penta.\n      (* assert (δnat := pr2 δ). red in δnat.\n      unfold H, H' in δnat. cbn in δnat.\n      rewrite hcomp_identity_left in δnat; rewrite hcomp_identity_right in δnat. *)\n       *)\n\n  Qed.\n\n  Definition bidisp_actionbicat_disp_prebicat_data : disp_prebicat_data B\n    := (bidisp_actionbicat_disp_prebicat_1_id_comp_cells,, bidisp_actionbicat_disp_prebicat_ops).\n\n  Definition bidisp_actionbicat_disp_prebicat_laws : disp_prebicat_laws bidisp_actionbicat_disp_prebicat_data.\n  Proof.\n    repeat split; intro; intros; apply isaprop_bidisp_actionbicat_disp_2cell_struct.\n  Qed.\n\n  Definition bidisp_actionbicat_disp_prebicat : disp_prebicat B\n    := (bidisp_actionbicat_disp_prebicat_data,,bidisp_actionbicat_disp_prebicat_laws).\n\n  Definition bidisp_actionbicat_disp_bicat : disp_bicat B.\n  Proof.\n    refine (bidisp_actionbicat_disp_prebicat,, _).\n    intros a a' f1 f2 η M M' FM1 FM2.\n    apply isasetaprop.\n    apply isaprop_bidisp_actionbicat_disp_2cell_struct.\n  Defined.\n\n  Lemma actionbicat_disp_2cells_isaprop : disp_2cells_isaprop bidisp_actionbicat_disp_bicat.\n  Proof.\n    red.\n    intros.\n    apply isaprop_bidisp_actionbicat_disp_2cell_struct.\n  Qed.\n\n  Definition bicatactionbicat : bicat := total_bicat bidisp_actionbicat_disp_bicat.\n\n  Lemma actionbicat_disp_locally_groupoid : disp_locally_groupoid bidisp_actionbicat_disp_bicat.\n  Proof.\n    red. intros a a' f1 f2 ηinvertible [FA FAm] [FA' FA'm] [δ1 [tria1 penta1]] [δ2 [tria2 penta2]] is2cell.\n    use tpair.\n    - red. cbn. red. intro v. red.\n      transparent assert (invertible1 : (invertible_2cell (FA v · f2) (FA v · f1))).\n      { use make_invertible_2cell.\n        - exact (FA v ◃ ηinvertible ^-1).\n        - is_iso. }\n      transparent assert (invertible2 : (invertible_2cell (f2 · FA' v) (f1 · FA' v))).\n      { use make_invertible_2cell.\n        - exact (ηinvertible ^-1 ▹ FA' v).\n        - is_iso. }\n      apply (lhs_right_invert_cell _ _ _ invertible1).\n      rewrite vassocl.\n      apply pathsinv0, (lhs_left_invert_cell _ _ _ invertible2).\n      exact (is2cell v).\n    - split; apply isaprop_bidisp_actionbicat_disp_2cell_struct.\n  Qed.\n\nEnd FixMoncatAndBicat.\n", "meta": {"author": "UniMath", "repo": "UniMath", "sha": "7de5cc98a7f6718af63a429ea88d80411eca2977", "save_path": "github-repos/coq/UniMath-UniMath", "path": "github-repos/coq/UniMath-UniMath/UniMath-7de5cc98a7f6718af63a429ea88d80411eca2977/UniMath/Bicategories/MonoidalCategories/BicatOfActionsInBicat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.31742625913050115, "lm_q1q2_score": 0.21011170654792072}}
{"text": "From stdpp Require Import numbers list.\n\n(* models the less than operator *)\nStructure Comparator (A : Type) := {\n  compare : A -> A -> bool;\n  transitive : forall a b c, compare a b -> compare b c -> compare a c;\n  irreflexive : forall a, ~compare a a;\n  asymmetry : forall a b, compare a b -> ~compare b a;\n  connected : forall a b, a <> b -> compare a b \\/ compare b a;\n  equalityExcludedMiddle : forall a b : A, a = b \\/ a <> b; (* not true generally *)\n}.\n\nLemma negativelyTransitive {A : Type} (comparator : Comparator A) : forall a b c, ~(compare _ comparator a b) -> ~(compare _ comparator b c) -> ~(compare _ comparator a c).\nProof.\n  intros a b c h1 h2 h3.\n  pose proof transitive _ comparator a c b h3 as h.\n  epose proof connected _ comparator b c _ as h4.\n  destruct h4; tauto.\n  Unshelve.\n  intro h4. rewrite h4 in h1. tauto.\nQed.\n\nLemma lessThanOrEqual {A : Type} (comparator : Comparator A) : forall a b, ~(compare _ comparator a b) <-> a = b \\/ compare _ comparator b a.\nProof.\n  intros.\n  pose proof connected _ comparator a b.\n  split; intros; pose proof equalityExcludedMiddle _ comparator a b as hSplit; pose proof asymmetry _ comparator a b; pose proof irreflexive _ comparator a; pose proof irreflexive _ comparator b; destruct hSplit as [hSplit | hSplit]; try rewrite hSplit; tauto.\nQed.\n", "meta": {"author": "huynhtrankhanh", "repo": "CoqCP", "sha": "a03cd02d9ffb3619da286e680d33a5f0d29fabee", "save_path": "github-repos/coq/huynhtrankhanh-CoqCP", "path": "github-repos/coq/huynhtrankhanh-CoqCP/CoqCP-a03cd02d9ffb3619da286e680d33a5f0d29fabee/theories/Comparator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.21006480887585371}}
{"text": "From compcert Require Export Clightdefs.\nRequire Export VST.veric.base.\nRequire Export VST.veric.SeparationLogic.\nRequire Export VST.msl.Extensionality.\nRequire Export compcert.lib.Coqlib.\nRequire Export VST.msl.Coqlib2 VST.veric.coqlib4 VST.floyd.coqlib3.\nRequire Export VST.floyd.functional_base.\nImport LiftNotation.\n\nLemma is_int_dec i s v: {is_int i s v} + {~ is_int i s v}.\nProof. destruct v; simpl; try solve [right; intros N; trivial].\ndestruct i.\n+ destruct s.\n    * destruct (zle Byte.min_signed (Int.signed i0)); [| right; omega].\n      destruct (zle (Int.signed i0) Byte.max_signed). left; omega. right; omega.\n    * destruct (zle (Int.unsigned i0) Byte.max_unsigned). left; omega. right; omega.\n+ destruct s.\n    * destruct (zle (-32768) (Int.signed i0)); [| right; omega].\n      destruct (zle (Int.signed i0) 32767). left; omega. right; omega.\n    * destruct (zle (Int.unsigned i0) 65535). left; omega. right; omega.\n+ left; trivial.\n+ destruct (Int.eq_dec i0 Int.zero); subst. left; left; trivial.\n    destruct (Int.eq_dec i0 Int.one); subst. left; right; trivial.\n    right. intros N; destruct N; contradiction.\nDefined.\n\nLemma tc_val_dec t v: {tc_val t v} + {~ tc_val t v}.\nProof. destruct t; simpl.\n+ right; intros N; trivial.\n+ apply is_int_dec.\n+ apply is_long_dec.\n+ destruct f. apply is_single_dec. apply is_float_dec.\n+ destruct ((eqb_type t Tvoid &&\n    eqb_attr a\n      {| attr_volatile := false; attr_alignas := Some log2_sizeof_pointer |})%bool).\n  apply is_pointer_or_integer_dec.\n  apply is_pointer_or_null_dec.\n+ apply is_pointer_or_null_dec.\n+ apply is_pointer_or_null_dec.\n+ apply isptr_dec.\n+ apply isptr_dec.\nDefined.\n\nLemma sem_add_pi_ptr:\n   forall {cs: compspecs}  t p i si,\n    isptr p ->\n    match si with\n    | Signed => Int.min_signed <= i <= Int.max_signed\n    | Unsigned => 0 <= i <= Int.max_unsigned\n    end ->\n    Cop.sem_add_ptr_int cenv_cs t si p (Vint (Int.repr i)) = Some (offset_val (sizeof t * i) p).\nProof.\n  intros. destruct p; try contradiction.\n  unfold offset_val, Cop.sem_add_ptr_int.\n  unfold Cop.ptrofs_of_int, Ptrofs.of_ints, Ptrofs.of_intu, Ptrofs.of_int.\n  f_equal. f_equal. f_equal.\n  destruct si; rewrite <- ptrofs_mul_repr;  f_equal.\n  rewrite Int.signed_repr by omega; auto.\n  rewrite Int.unsigned_repr by omega; auto.\nQed.\nHint Rewrite @sem_add_pi_ptr using (solve [auto with norm]) : norm.\n\nLemma sem_cast_i2i_correct_range: forall sz s v,\n  is_int sz s v -> sem_cast_i2i sz s v = Some v.\nProof.\n  intros.\n  destruct sz, s, v; try solve [inversion H]; simpl;\n  f_equal; f_equal; try apply sign_ext_inrange; try apply zero_ext_inrange; eauto.\n  + simpl in H; destruct H; subst; reflexivity.\n  + simpl in H; destruct H; subst; reflexivity.\nQed.\nHint Rewrite sem_cast_i2i_correct_range using (solve [auto with norm]) : norm.\n\nLemma sem_cast_neutral_ptr:\n  forall p, isptr p -> sem_cast_pointer p = Some p.\nProof. intros. destruct p; try contradiction; reflexivity. Qed.\nHint Rewrite sem_cast_neutral_ptr using (solve [auto with norm]): norm.\n\nLemma sem_cast_neutral_Vint: forall v,\n  sem_cast_pointer (Vint v) = Some (Vint v).\nProof.\n  intros. reflexivity.\nQed.\nHint Rewrite sem_cast_neutral_Vint : norm.\n\nDefinition isVint v := match v with Vint _ => True | _ => False end.\n\nLemma is_int_is_Vint: forall i s v, is_int i s v -> isVint v.\nProof. intros.\n destruct i,s,v; simpl; intros; auto.\nQed.\n\nLemma is_int_I32_Vint: forall s v, is_int I32 s (Vint v).\nProof.\nintros.\nhnf. auto.\nQed.\nHint Resolve is_int_I32_Vint.\n\nLemma sem_cast_neutral_int: forall v,\n  isVint v ->\n  sem_cast_pointer v = Some v.\nProof.\ndestruct v; simpl; intros; try contradiction; auto.\nQed.\n\nHint Rewrite sem_cast_neutral_int using\n  (auto;\n   match goal with H: is_int ?i ?s ?v |- isVint ?v => apply (is_int_is_Vint i s v H) end) : norm.\n\nLemma sizeof_tuchar: forall {cs: compspecs}, sizeof tuchar = 1%Z.\nProof. reflexivity. Qed.\nHint Rewrite @sizeof_tuchar: norm.\n\nHint Rewrite Z.mul_1_l Z.mul_1_r Z.add_0_l Z.add_0_r Z.sub_0_r : norm.\n\nHint Rewrite eval_id_same : norm.\nHint Rewrite eval_id_other using solve [clear; intro Hx; inversion Hx] : norm.\nHint Rewrite Int.sub_idem Int.sub_zero_l  Int.add_neg_zero : norm.\nHint Rewrite Ptrofs.sub_idem Ptrofs.sub_zero_l  Ptrofs.add_neg_zero : norm.\n\nLemma eval_expr_Etempvar:\n  forall {cs: compspecs}  i t, eval_expr (Etempvar i t) = eval_id i.\nProof. reflexivity.\nQed.\nHint Rewrite @eval_expr_Etempvar : eval.\n\nLemma eval_expr_binop: forall {cs: compspecs}  op a1 a2 t, eval_expr (Ebinop op a1 a2 t) =\n          `(eval_binop op (typeof a1) (typeof a2)) (eval_expr a1) (eval_expr a2).\nProof. reflexivity. Qed.\nHint Rewrite @eval_expr_binop : eval.\n\nLemma eval_expr_unop: forall {cs: compspecs} op a1 t, eval_expr (Eunop op a1 t) =\n          lift1 (eval_unop op (typeof a1)) (eval_expr a1).\nProof. reflexivity. Qed.\nHint Rewrite @eval_expr_unop : eval.\n\nHint Resolve  eval_expr_Etempvar.\n\nLemma eval_expr_Etempvar' : forall {cs: compspecs}  i t, eval_id i = eval_expr (Etempvar i t).\nProof. intros. symmetry; auto.\nQed.\nHint Resolve  @eval_expr_Etempvar'.\n\nHint Rewrite Int.add_zero  Int.add_zero_l Int.sub_zero_l : norm.\nHint Rewrite Ptrofs.add_zero  Ptrofs.add_zero_l Ptrofs.sub_zero_l : norm.\n\nLemma eval_var_env_set:\n  forall i t j v (rho: environ), eval_var i t (env_set rho j v) = eval_var i t rho.\nProof. reflexivity. Qed.\nHint Rewrite eval_var_env_set : norm.\n\nLemma eval_expropt_Some: forall {cs: compspecs}  e, eval_expropt (Some e) = `Some (eval_expr e).\nProof. reflexivity. Qed.\nLemma eval_expropt_None: forall  {cs: compspecs} , eval_expropt None = `None.\nProof. reflexivity. Qed.\nHint Rewrite @eval_expropt_Some @eval_expropt_None : eval.\n\nLemma deref_noload_tarray:\n  forall ty n, deref_noload (tarray ty n) = (fun v => v).\nProof.\n intros. extensionality v. reflexivity.\nQed.\nHint Rewrite deref_noload_tarray : norm.\n\nLemma deref_noload_Tarray:\n  forall ty n a, deref_noload (Tarray ty n a) = (fun v => v).\nProof.\n intros. extensionality v. reflexivity.\nQed.\nHint Rewrite deref_noload_Tarray : norm.\n\nLemma flip_lifted_eq:\n  forall (v1: environ -> val) (v2: val),\n    `eq v1 `(v2) = `(eq v2) v1.\nProof.\nintros. unfold_lift. extensionality rho. apply prop_ext; split; intro; auto.\nQed.\nHint Rewrite flip_lifted_eq : norm.\n\nLemma isptr_is_pointer_or_null:\n  forall v, isptr v -> is_pointer_or_null v.\nProof. intros. destruct v; inv H; simpl; auto.\nQed.\nHint Resolve isptr_is_pointer_or_null.\n\nDefinition add_ptr_int  {cs: compspecs}  (ty: type) (v: val) (i: Z) : val :=\n           eval_binop Cop.Oadd (tptr ty) tint v (Vint (Int.repr i)).\n\nLemma add_ptr_int_offset:\n  forall  {cs: compspecs}  t v n,\n  repable_signed (sizeof t) ->\n  repable_signed n ->\n  add_ptr_int t v n = offset_val (sizeof t * n) v.\nAbort. (* broken in CompCert 2.7 *)\n\nLemma typed_false_cmp:\n  forall op i j ,\n   typed_false tint (force_val (sem_cmp op tint tint (Vint i) (Vint j))) ->\n   Int.cmp (negate_comparison op) i j = true.\nProof.\nintros.\nunfold sem_cmp in H.\nunfold Cop.classify_cmp in H. simpl in H.\nrewrite Int.negate_cmp.\nunfold both_int, force_val, typed_false, strict_bool_val, sem_cast, classify_cast, tint in H.\ndestruct Archi.ptr64 eqn:Hp; simpl in H.\ndestruct (Int.cmp op i j); inv H; auto.\ndestruct (Int.cmp op i j); inv H; auto.\nQed.\n\nLemma typed_true_cmp:\n  forall op i j,\n   typed_true tint (force_val (sem_cmp op tint tint (Vint i) (Vint j))) ->\n   Int.cmp op i j = true.\nProof.\nintros.\nunfold sem_cmp in H.\nunfold Cop.classify_cmp in H. simpl in H.\nunfold both_int, force_val, typed_false, strict_bool_val, sem_cast, classify_cast, tint in H.\ndestruct Archi.ptr64 eqn:Hp; simpl in H.\ndestruct (Int.cmp op i j); inv H; auto.\ndestruct (Int.cmp op i j); inv H; auto.\nQed.\n\nDefinition Zcmp (op: comparison) : Z -> Z -> Prop :=\n match op with\n | Ceq => eq\n | Cne => (fun i j => i<>j)\n | Clt => Z.lt\n | Cle => Z.le\n | Cgt => Z.gt\n | Cge => Z.ge\n end.\n\nLemma int_cmp_repr:\n forall op i j, repable_signed i -> repable_signed j ->\n   Int.cmp op (Int.repr i) (Int.repr j) = true ->\n   Zcmp op i j.\nProof.\nintros.\nunfold Int.cmp, Int.eq, Int.lt in H1.\nreplace (if zeq (Int.unsigned (Int.repr i)) (Int.unsigned (Int.repr j))\n             then true else false)\n with (if zeq i j then true else false) in H1.\n2:{\ndestruct (zeq i j); destruct (zeq (Int.unsigned (Int.repr i)) (Int.unsigned (Int.repr j)));\n auto.\nsubst. contradiction n; auto.\nclear - H H0 e n.\napply Int.signed_repr in H. rewrite Int.signed_repr_eq in H.\napply Int.signed_repr in H0; rewrite Int.signed_repr_eq in H0.\ncontradiction n; clear n.\nrepeat rewrite Int.unsigned_repr_eq in e.\n match type of H with\n           | context [if ?a then _ else _] => destruct a\n           end;\n match type of H0 with\n           | context [if ?a then _ else _] => destruct a\n           end; omega.\n}\nunfold Zcmp.\nrewrite (Int.signed_repr _ H) in H1; rewrite (Int.signed_repr _ H0) in H1.\nrepeat match type of H1 with\n           | context [if ?a then _ else _] => destruct a\n           end; try omegaContradiction;\n destruct op; auto; simpl in *; try discriminate; omega.\nQed.\n\nLemma typed_false_cmp_repr:\n  forall op i j,\n   repable_signed i -> repable_signed j ->\n   typed_false tint (force_val (sem_cmp op tint tint\n                              (Vint (Int.repr i))\n                              (Vint (Int.repr j)) )) ->\n   Zcmp (negate_comparison op) i j.\nProof.\n intros.\n apply typed_false_cmp in H1.\n apply int_cmp_repr; auto.\nQed.\n\nLemma typed_true_cmp_repr:\n  forall op i j,\n   repable_signed i -> repable_signed j ->\n   typed_true tint (force_val (sem_cmp op tint tint\n                              (Vint (Int.repr i))\n                              (Vint (Int.repr j)) )) ->\n   Zcmp op i j.\nProof.\n intros.\n apply typed_true_cmp in H1.\n apply int_cmp_repr; auto.\nQed.\n\nLtac intcompare H :=\n (apply typed_false_cmp_repr in H || apply typed_true_cmp_repr in H);\n   [ simpl in H | auto; unfold repable_signed, Int.min_signed, Int.max_signed in *; omega .. ].\n\n\nLemma isptr_deref_noload:\n forall t p, access_mode t = By_reference -> isptr (deref_noload t p) = isptr p.\nProof.\nintros.\nunfold deref_noload. rewrite H. reflexivity.\nQed.\nHint Rewrite isptr_deref_noload using reflexivity : norm.\n\nDefinition headptr (v: val): Prop :=\n  exists b,  v = Vptr b Ptrofs.zero.\n\nLemma headptr_isptr: forall v,\n  headptr v -> isptr v.\nProof.\n  intros.\n  destruct H as [b ?].\n  subst.\n  hnf; auto.\nQed.\nHint Resolve headptr_isptr.\n\nLemma headptr_offset_zero: forall v,\n  headptr (offset_val 0 v) <->\n  headptr v.\nProof.\n  split; intros.\n  + destruct H as [b ?]; subst.\n    destruct v; try solve [inv H].\n    simpl in H.\n    remember (Ptrofs.add i (Ptrofs.repr 0)).\n    inversion H; subst.\n    rewrite Ptrofs.add_zero in H2; subst.\n    hnf; eauto.\n  + destruct H as [b ?]; subst.\n    exists b.\n    reflexivity.\nQed.\n\n(* Equality proofs for all constants from the Compcert Int, Int64, Ptrofs modules: *)\n\nLemma typed_false_ptr:\n  forall {t a v},  typed_false (Tpointer t a) v -> v=nullval.\nProof.\nunfold typed_false, strict_bool_val, nullval; simpl; intros.\ndestruct Archi.ptr64 eqn:Hp;\ndestruct v; try discriminate; f_equal.\nfirst [pose proof (Int64.eq_spec i Int64.zero); \n          destruct (Int64.eq i Int64.zero)\n       | pose proof (Int.eq_spec i Int.zero); \n         destruct (Int.eq i Int.zero)]; \n      subst; auto; discriminate.\nQed.\n\nLemma typed_true_ptr:\n  forall {t a v},  typed_true (Tpointer t a) v -> isptr v.\nProof.\nunfold typed_true, strict_bool_val; simpl; intros.\ndestruct v; try discriminate; simpl; auto;\ndestruct Archi.ptr64; try discriminate;\n revert H; simple_if_tac; intros; discriminate.\nQed.\n\nLemma int_cmp_repr':\n forall op i j, repable_signed i -> repable_signed j ->\n   Int.cmp op (Int.repr i) (Int.repr j) = false ->\n   Zcmp (negate_comparison op) i j.\nProof.\nintros.\napply int_cmp_repr; auto.\nrewrite Int.negate_cmp.\nrewrite H1; reflexivity.\nQed.\n\nLemma typed_false_of_bool:\n forall x, typed_false tint (Val.of_bool x) -> (x=false).\nProof.\nunfold typed_false; simpl.\nunfold strict_bool_val, Val.of_bool; simpl.\ndestruct x; simpl; intros; [inversion H | auto].\nQed.\n\nLemma typed_true_of_bool:\n forall x, typed_true tint (Val.of_bool x) -> (x=true).\nProof.\nunfold typed_true; simpl.\nunfold strict_bool_val, Val.of_bool; simpl.\ndestruct x; simpl; intros; [auto | inversion H].\nQed.\n\nLemma typed_false_tint:\n Archi.ptr64=false -> \n forall v, typed_false tint v -> v=nullval.\nProof.\nintros.\n hnf in H0. destruct v; inv H0.\n destruct (Int.eq i Int.zero) eqn:?; inv H2.\n apply int_eq_e in Heqb. subst.\n inv H; reflexivity.\nQed.\n\nLemma typed_false_tlong:\n Archi.ptr64=true -> \n forall v, typed_false tlong v -> v=nullval.\nProof.\nintros. unfold nullval. rewrite H.\n hnf in H0. destruct v; inv H0.\npose proof (Int64.eq_spec i Int64.zero).\n destruct (Int64.eq i Int64.zero); inv H2.\nreflexivity.\nQed.\n\nLemma typed_true_e:\n forall t v, typed_true t v -> v<>nullval.\nProof.\nintros.\n intro Hx. subst.\n hnf in H. unfold nullval, strict_bool_val in H.\n destruct Archi.ptr64, t; discriminate.\nQed.\n\nLemma typed_false_tint_Vint:\n  forall v, typed_false tint (Vint v) -> v = Int.zero.\nProof.\nintros.\nunfold typed_false, strict_bool_val in H. simpl in H.\npose proof (Int.eq_spec v Int.zero).\ndestruct (Int.eq v Int.zero); auto. inv H.\nQed.\n\nLemma typed_true_tint_Vint:\n  forall v, typed_true tint (Vint v) -> v <> Int.zero.\nProof.\nintros.\nunfold typed_true, strict_bool_val in H. simpl in H.\npose proof (Int.eq_spec v Int.zero).\ndestruct (Int.eq v Int.zero); auto. inv H.\nQed.\n\nLemma typed_true_tlong_Vlong:\n  forall v, typed_true tlong (Vlong v) -> v <> Int64.zero.\nProof.\nintros.\nunfold typed_true, strict_bool_val in H. simpl in H.\npose proof (Int64.eq_spec v Int64.zero).\ndestruct (Int64.eq v Int64.zero); auto. inv H.\nQed.\n\nLtac intro_redundant_prop :=\n  (* do it in this complicated way because the proof will come out smaller *)\nmatch goal with |- ?P -> _ =>\n  ((assert P by immediate; fail 1) || fail 1) || intros _\nend.\n\nLtac fancy_intro aggressive :=\n match goal with\n | |- ?P -> _ => match type of P with Prop => idtac end\n | |- ~ _ => idtac\n end;\n let H := fresh in\n intro H;\n try simple apply ptr_eq_e in H;\n try simple apply Vint_inj in H;\n try match type of H with\n | tc_val _ _ => unfold tc_val in H; try change (eqb_type _ _) with false in H; cbv iota in H\n end;\n match type of H with\n | ?P => clear H; \n              match goal with H': P |- _ => idtac end (* work around bug number 6998 in Coq *)\n             + (((assert (H:P) by (clear; immediate); fail 1) || fail 1) || idtac)\n                (* do it in this complicated way because the proof will come out smaller *)\n | ?x = ?y => constr_eq aggressive true;\n                     first [subst x | subst y\n                             | is_var x; rewrite H\n                             | is_var y; rewrite <- H\n                             | idtac]\n | headptr (_ ?x) => let Hx1 := fresh \"HP\" x in\n                     let Hx2 := fresh \"P\" x in\n                       rename H into Hx1;\n                       pose proof headptr_isptr _ Hx1 as Hx2\n | headptr ?x => let Hx1 := fresh \"HP\" x in\n                 let Hx2 := fresh \"P\" x in\n                   rename H into Hx1;\n                   pose proof headptr_isptr _ Hx1 as Hx2\n | isptr ?x => let Hx := fresh \"P\" x in rename H into Hx\n | is_pointer_or_null ?x => let Hx := fresh \"PN\" x in rename H into Hx\n | typed_false _ _ =>\n        first [simple apply typed_false_of_bool in H\n               | apply typed_false_tint_Vint in H\n               | apply (typed_false_tint (eq_refl _)) in H\n               | apply (typed_false_tlong (eq_refl _)) in H\n               | apply typed_false_ptr in H\n               | idtac ]\n | typed_true _ _ =>\n        first [simple apply typed_true_of_bool in H\n               | apply typed_true_tint_Vint in H\n               | apply typed_true_tlong_Vlong in H\n(*  This one is not portable 32/64 bits \n                | apply (typed_true_e tint) in H\n*)\n               | apply typed_true_ptr in H\n               | idtac ]\n (* | locald_denote _ _ => hnf in H *)\n | _ => try solve [discriminate H]\n end.\n\nLtac fancy_intros aggressive :=\n repeat match goal with\n  | |- (_ <= _ < _) -> _ => fancy_intro aggressive\n  | |- (_ < _ <= _) -> _ => fancy_intro aggressive\n  | |- (_ <= _ <= _) -> _ => fancy_intro aggressive\n  | |- (_ < _ < _) -> _ => fancy_intro aggressive\n  | |- (?A /\\ ?B) -> ?C => apply (@and_ind A B C) (* For some reason \"apply and_ind\" doesn't work the same *)\n  | |- _ -> _ => fancy_intro aggressive\n  end.\n\nLtac fold_types :=\n fold noattr tuint tint tschar tuchar;\n repeat match goal with\n | |- context [Tpointer ?t noattr] =>\n      change (Tpointer t noattr) with (tptr t)\n | |- context [Tarray ?t ?n noattr] =>\n      change (Tarray t n noattr) with (tarray t n)\n end.\n\nLtac fold_types1 :=\n  match goal with |- _ -> ?A =>\n  let a := fresh \"H\" in set (a:=A); fold_types; subst a\n  end.\n\nLemma is_int_Vbyte: forall c, is_int I8 Signed (Vbyte c).\nProof.\nintros. simpl. normalize. rewrite Int.signed_repr by rep_omega. rep_omega.\nQed.\nHint Resolve is_int_Vbyte.\n\n", "meta": {"author": "anshumanmohan", "repo": "RamifyCoq_VST", "sha": "0517a39b069f79f50a45321db6ca81c48397b73d", "save_path": "github-repos/coq/anshumanmohan-RamifyCoq_VST", "path": "github-repos/coq/anshumanmohan-RamifyCoq_VST/RamifyCoq_VST-0517a39b069f79f50a45321db6ca81c48397b73d/VST/floyd/val_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.21003910942680032}}
{"text": "Require Import syntax.\nRequire Import partial.\nRequire Import namesAndTypes.\n\nImport ConcreteEverything.\n\nSection MethodsAndFields.\n  Variable P : Program.\n\n  Require Import Coq.Lists.List.\n  \n(* Module MethodsAndFields (ct: ClassTable). *)\n\n  (* Parameter CT : list ClassDecl. *)\n  (* Maybe change to method name? *)\n\n  Definition method : class -> MethodName_type -> MethDecl -> Prop :=\n    fun _ _ _ => classDecls P = nil.\n\n  Definition mtype C m md \n             (witn: method C m md) :=\n    retType md.\n\n  Definition mbody C m md\n             (witn: method C m md) :=\n    methodBody md.\n\n  Definition mparam C m md\n             (witn: method C m md) :=\n    argName md.\n\n  Definition class_name_methods : class -> list MethDecl :=\n    fun _ => match classDecls P with\n               | nil => nil\n               | _ => nil\n             end.\n\n  Definition fld : class -> FieldName_type -> Prop :=\n    fun _ _ => classDecls P = nil.\n  \n  Definition ftype : forall C f,\n                       fld C f -> class :=\n    fun C _ _ => C.\n  (*   destruct (ant.fn.constructFresh nil). *)\n  (*   auto. *)\n  (* Defined. *)\n\n  Definition fields : class -> list FieldName_type -> Prop.\n  Admitted.\n\n  Definition fieldsList : class -> list FieldName_type.\n  Admitted.\n  Theorem fieldsListIsFields :\n    forall C,\n      fields C (fieldsList C).\n  Admitted.\n\n  Theorem fld_in_flds C f fields_lst:\n    fld C f -> \n    fields C fields_lst ->\n    In f fields_lst.\n  Admitted.\n\n  Definition subclass : class -> class -> Prop :=\n    fun _ _ => classDecls P = nil.\n\n  Theorem method_subclass C D m md :\n    method D m md ->\n    subclass C D ->\n    method C m md.\n    admit.\n  Admitted.\n\n  Theorem subclass_refl C :\n    subclass C C.\n    admit.\n  Admitted.\n    \n  Theorem subclass_trans C D E:\n    subclass C D -> subclass D E -> subclass C E.\n    admit.\n  Admitted.\n\n  Theorem field_subclass C D f :\n    fld D f ->\n    subclass C D ->\n    fld C f.\n    admit.\n  Admitted.\n    \n  Theorem ftype_subclass C D f (f_witn: fld D f)\n          (sub_witn: subclass C D):\n    ftype D f f_witn = ftype C f (field_subclass C D f f_witn sub_witn).\n    admit.\n  Admitted.\n\n  Theorem unique_ftype C f (f_witn1 f_witn2: fld C f) :\n    ftype C f f_witn1 = ftype C f f_witn2.\n    admit.\n  Admitted.\n    \n  Inductive subtype : typecheck_type -> typecheck_type -> Type :=\n  | classSub : forall C D, subclass C D -> subtype (typt_class C) (typt_class D)\n  | boxSub : forall C D, subclass C D -> subtype (typt_box C) (typt_box D)\n  | allSub : forall sigma, subtype sigma typt_all.\n\n  Lemma subtype_and_subclass_lemma C' C :\n    subtype (typt_class C') (typt_class C) ->\n    subclass C' C.\n    intro X.\n  Admitted.\n\n  Print subtype_and_subclass_lemma.\n\n  Definition ocap : class -> Prop.\n  Admitted.\n\n  Theorem ocap_dec : forall C, ocap C \\/ ~ (ocap C).\n  Admitted.\n\n  Fixpoint lookup_l (c: class) (l: list ClassDecl) : option ClassDecl :=\n    match l with\n      | nil => None\n      | cd :: cds => if class_eq_dec c (cls cd)\n                     then (Some cd)\n                     else (lookup_l c cds)\n    end.\n\n  Definition lookup (c: class) : option ClassDecl :=\n    lookup_l c (classDecls P).\n\nEnd MethodsAndFields.\n\n", "meta": {"author": "aleloi", "repo": "lacasa-mechanized", "sha": "24dfa243f6b640d17211e732121857a4c9c14771", "save_path": "github-repos/coq/aleloi-lacasa-mechanized", "path": "github-repos/coq/aleloi-lacasa-mechanized/lacasa-mechanized-24dfa243f6b640d17211e732121857a4c9c14771/classTable.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.210029213402852}}
{"text": "From mathcomp Require Import all_ssreflect zify.\nFrom CoTypes Require Export coProj.\nRequire Import Paco.paco.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLet eqs := (coLocal.eqs, coGlobal.eqs). \n\n\n\nRequire Import Program. \nFrom Equations Require Import Equations. \n\n\n\n\nVariant part_ofF (p : ptcp) (R : gType -> Prop)  : gType -> Prop :=\n| po2_msg a u g0 : comp_dir p a -> part_ofF p R (GMsg a u g0)\n| po2_msg2 a u g0 : R g0 -> part_ofF p R (GMsg a u g0)\n| po2_branch a gs : comp_dir p a -> part_ofF p R (GBranch a gs)\n| po2_branch2 a g gs : In g gs -> R g ->  part_ofF p R (GBranch a gs).\nHint Constructors part_ofF. \n\nNotation part_ofFU := (fun p => ApplyF1 full_unf \\o part_ofF p).\n\n\nInductive part_of2 (p : ptcp) : gType -> Prop := \n| part_of2C g : part_ofFU p (part_of2 p) g -> part_of2 p g.\nHint Constructors part_of2.\n\nLemma part_of2_ind2\n     : forall (p : ptcp) (P : gType -> Prop),\n       (forall (a : action) (u : value) (g0 g' : gType), comp_dir p a -> full_unf g' = (GMsg a u g0) -> P g') ->\n       (forall (a : action) (u : value) (g0 g' : gType), ~ comp_dir p a -> part_of2 p g0 -> P g0 -> full_unf g' = (GMsg a u g0) -> P g') ->\n       (forall (a : action) (g' : gType)  (gs : seq gType), comp_dir p a -> full_unf g' = GBranch a gs -> P g') ->\n       (forall (a : action) (g g' : gType) (gs : seq gType),  ~ comp_dir p a -> In g gs -> part_of2 p g -> P g -> full_unf g' = GBranch a gs -> P g') ->\n       forall g : gType, part_of2 p g -> P g.\nProof.\nintros.  move : g H3. fix IH 2. intros. destruct H3. inv H3.  \ninv H4. \napply/H. eauto. eauto. \ndestruct (comp_dir p a) eqn:Heqn. \napply/H. 2 : eauto. comp_disc. \napply/H0. 4 : eauto. comp_disc. done. auto. \napply/H1. 2 : eauto. done. \ndestruct (comp_dir p a) eqn:Heqn. \napply/H1. 2 : eauto. comp_disc. \napply/H2. 5 : eauto. comp_disc. eauto. eauto. apply/IH. auto. \nQed.\n\n\nLemma part_of2_unf : forall p e, part_of2 p e -> part_of2 p (full_unf e). \nProof. intros. inv H. inv H0. con. con. rewrite full_unf_idemp //=. \nQed.\n\nLemma part_of2_unf2 : forall p e, part_of2 p (full_unf e) -> part_of2 p e. \nProof. intros. inv H. inv H0. con. con. rewrite full_unf_idemp in H1=>//=. \nQed.\n\nLemma part_of2_iff : forall p g, part_of2 p g <-> part_of2 p (full_unf  g). \nProof. intros. split. apply/part_of2_unf. apply/part_of2_unf2. \nQed.\n\nLemma not_part2_msg : forall p a v g, ~ part_of2 p (GMsg a v g) -> ~ part_of2 p g.\nProof.  \nintros. intro.  apply/H. con.  con. constructor 2. done. \nQed.\n\nLemma not_part2_msg2 : forall p a v g, ~ part_of2 p (GMsg a v g) -> ~ comp_dir p a.\nProof.  \nintros. intro.  apply/H. con. con. con. eauto. \nQed.\n\nLemma not_part2_branch : forall p a g (gs : seq gType), ~ part_of2 p (GBranch a gs) -> In g gs -> ~ part_of2 p g.\nProof.  \nintros. intro.  apply/H. con. con. rewrite /full_unf /=. eauto. \nQed.\n\nLemma not_part2_branch2 : forall p a (gs : seq gType), ~ part_of2 p (GBranch a gs) -> ~ comp_dir p a.  \nProof.  \nintros. intro.  apply/H. con. con. con. eauto. \nQed.\n\nHint Resolve not_part2_msg not_part2_msg2  not_part2_branch  not_part2_branch2. \n\n\n\n\n\n\nVariant part_of_allF (p : ptcp) (R : gType -> Prop)  : gType -> Prop :=\n| poa2_msg a u g0 : comp_dir p a -> part_of_allF p R (GMsg a u g0)\n| poa2_msg2 a u g0 : R g0 -> part_of_allF p R (GMsg a u g0)\n| poa2_branch a gs : comp_dir p a -> part_of_allF p R (GBranch a gs)\n| poa2_branch2 a gs : (forall g, In g gs -> R g) ->  part_of_allF p R (GBranch a gs).\nHint Constructors part_of_allF. \n\nNotation part_of_allFU := (fun p => ApplyF1 full_unf \\o part_of_allF p).\n\n\nInductive part_of_all2 (p : ptcp) : gType -> Prop := \n| part_of_allC g : part_of_allFU p (part_of_all2 p) g -> part_of_all2 p g.\nHint Constructors part_of_all2.\n\nLemma part_of_all2_ind2\n     : forall (p : ptcp) (P : gType -> Prop),\n       (forall (a : action) (u : value) (g0 g' : gType), comp_dir p a -> full_unf g' = (GMsg a u g0) -> P g') ->\n       (forall (a : action) (u : value) (g0 g' : gType), ~ comp_dir p a -> part_of_all2 p g0 -> P g0 -> full_unf g' = (GMsg a u g0) -> P g') ->\n       (forall (a : action) (g' : gType)  (gs : seq gType), comp_dir p a -> full_unf g' = GBranch a gs -> P g') ->\n       (forall (a : action) (g' : gType) (gs : seq gType),  ~ comp_dir p a -> (forall g, In g gs -> part_of_all2 p g) -> (forall g, In g gs -> part_of_all2 p g -> P g) -> full_unf g' = GBranch a gs -> P g') ->\n       forall g : gType, part_of_all2 p g -> P g.\nProof.\nintros.  move : g H3. fix IH 2. intros. destruct H3. inv H3.  \ninv H4. \napply/H. eauto. eauto. \ndestruct (comp_dir p a) eqn:Heqn. \napply/H. 2 : eauto. comp_disc. \napply/H0. 4 : eauto. comp_disc. done. auto. \napply/H1. 2 : eauto. done. \ndestruct (comp_dir p a) eqn:Heqn. \napply/H1. 2 : eauto. comp_disc. \napply/H2. 4 : eauto. comp_disc. clear H5. Guarded.\nintros.  apply/H6. apply H5. intros. apply IH. apply H6. apply H7. \nQed.\n\n\nLemma part_of_all2_unf : forall p e, part_of_all2 p e -> part_of_all2 p (full_unf e). \nProof. intros. inv H. inv H0. con. con. rewrite full_unf_idemp //=. \nQed.\n\nLemma part_of_all2_unf2 : forall p e, part_of_all2 p (full_unf e) -> part_of_all2 p e. \nProof. intros. inv H. inv H0. con. con. rewrite full_unf_idemp in H1=>//=. \nQed.\n\nLemma part_of_all2_iff : forall p g, part_of_all2 p g <-> part_of_all2 p (full_unf  g). \nProof. intros. split. apply/part_of_all2_unf. apply/part_of_all2_unf2. \nQed.\n\n\nLemma not_part_all2_msg : forall p a v g, ~ part_of_all2 p (GMsg a v g) -> ~ part_of_all2 p g.\nProof.  \nintros. intro.  apply/H. con.  con. constructor 2. done. \nQed.\n\nLemma not_part_all2_msg2 : forall p a v g, ~ part_of_all2 p (GMsg a v g) -> ~ comp_dir p a.\nProof.  \nintros. intro.  apply/H. con. con. con. eauto. \nQed.\n\n\nLemma not_part_all2_branch2 : forall p a (gs : seq gType), ~ part_of_all2 p (GBranch a gs) -> ~ comp_dir p a.  \nProof.  \nintros. intro.  apply/H. con. con. con. eauto. \nQed.\n\nHint Resolve not_part_all2_msg not_part_all2_msg2    not_part_all2_branch2. \n\n(*Using (forall x , In x .... generates a stronger induction principle*)\n\nInductive project_gen (p : ptcp) (R : gType ->  lType -> Prop) : gType -> lType -> Prop :=\n | project_msg_s g0 a e0 u d : comp_dir p a = Some d ->\n                                  R g0 e0 -> project_gen p R (GMsg a u g0) (EMsg d (action_ch a) u e0) (*Assumption does not have to build something*)\n | project_msg_n g0 a e0 u : comp_dir p a = None ->\n                                 R g0 e0 -> part_of_all2 p g0 ->  project_gen p R (GMsg a u g0) e0(*assumption has to build something*)\n | project_gen_branch_f (gs : seq gType) (es : seq lType) a d :  comp_dir p a = Some d -> size gs = size es ->\n                                        (forall p, In p (zip gs es) ->  R p.1 p.2 ) -> project_gen p R (GBranch a gs) (EBranch d (action_ch a) es)\n | project_gen_branch_o g (gs : seq gType)  a e : comp_dir p a = None -> In g gs ->  (*We need list to be non -empty otherweise it projects to anything*)\n                                    (forall g', In g' gs ->  part_of_all2 p g' /\\  R g' e) ->  project_gen p R (GBranch a gs) e\n | project_gen_end g : ~ part_of2 p g -> gInvPred g -> project_gen p R g EEnd. (*Need to preserve that all projectable g's satisfy gInvPred g*)\nHint Constructors project_gen. \n\nNotation UnfProj := (ApplyF full_unf full_eunf).\n\nDefinition Project g p e := paco2 (UnfProj \\o (project_gen p)) bot2 g e. \n\nLemma project_gen_mon p: monotone2 (project_gen p). \nProof.\nmove => x0 x1. intros. induction IN;try done.\ncon;eauto. con;eauto. con;eauto. econstructor;eauto.  \nintros. ssa. move/H1 : H2.  ssa. apply/LE. move/H1 : H2. ssa. con. \ndone. done. \nQed.\n\n\nHint Resolve project_gen_mon : paco. \n\n\n\n\n\nLemma part_of2_or_end : forall p g e r, paco2 (UnfProj \\o project_gen p) r g e -> part_of_all2 p g \\/ full_eunf e = EEnd. \nProof. \nintros. punfold H. inv H;eauto.  rewrite part_of_all2_iff. \ninv H0. \nleft. con.  con. con. comp_disc. \nleft. con. con. constructor 2. done. \nleft. repeat con.  comp_disc. \nleft. con. con. econstructor 4. \nintros. move/H4 : H5. ssa. \nauto. \nQed.\n\n\n\nLemma ICpart_of1 : forall p g gc, part_of2 p g -> gUnravel2 g gc -> part_of p gc.\nProof. \nintros. \nelim/part_of2_ind2 : H gc H0;intros. \npunfold H1. inv H1. rewrite H0 in H2. inv H2. eauto. \npunfold H3. inv H3. rewrite H2 in H4. inv H4. pclearbot. eauto. \npunfold H1. inv H1. rewrite H0 in H2. inv H2. eauto. \npunfold H4. inv H4. rewrite H3 in H5. inv H5. Check In_zip. \nmove : (@In_zip _ _ g0 gs ecs H0 H8)=>[]. ssa. \neconstructor 4. eauto. forallApp H10 H7. case=>//=.  eauto. \nQed.\n\nLemma ICpart_of2 : forall p gc g, part_of p gc -> gUnravel2 g gc -> part_of2 p g.\nProof. \nintros. \nelim/part_of_ind2 : H g H0;intros. \npunfold H0. inv H0. con. con. inv H1. eauto. \npunfold H2. inv H2. inv H3. pclearbot. con. con. \nrewrite -H4. constructor 2. eauto. \npunfold H0. inv H0. con. con. inv H1. eauto. \npunfold H3. inv H3. con. con. inv H4. injt. Check In_zip2. \nmove : (@In_zip2 _ _ g es gs H0 H8)=>[]. ssa. \nforallApp H9 H7. case=>[] //=.  eauto. \nQed.\n\nLemma ICpart_of_iff : forall p g gc,  gUnravel2 g gc  ->  part_of2 p g <-> part_of p gc.\nProof. intros. split;intros. apply/ICpart_of1. eauto. eauto. \napply/ICpart_of2. eauto. eauto. \nQed.\n\nLemma ICpart_of_all1 : forall p g gc, part_of_all2 p g -> gUnravel2 g gc -> part_of_all p gc.\nProof. \nintros. \nelim/part_of_all2_ind2 : H gc H0;intros. \npunfold H1. inv H1. rewrite H0 in H2. inv H2. eauto. \npunfold H3. inv H3. rewrite H2 in H4. inv H4. pclearbot. eauto. \npunfold H1. inv H1. rewrite H0 in H2. inv H2. eauto.\npunfold H3. inv H3. rewrite H2 in H4. inv H4. \neconstructor 4. intros.\nmove : (@In_zip2 _ _ g0 gs ecs H5 H7)=>[]. ssa. \n\n apply/H1. eauto. apply/H0. done. forallApp H9 H8. case=>[] //=. \nQed.\n\n\nLemma ICpart_of_all2 : forall p gc g, part_of_all p gc -> gUnravel2 g gc -> part_of_all2 p g.\nProof. \nintros. \nelim/part_of_all_ind : H g H0;intros. \npunfold H0. inv H0. con. con. inv H1. eauto. \npunfold H1. inv H1. inv H2. pclearbot. con. con. rewrite -H3. \nconstructor 2. eauto. \npunfold H0. inv H0. inv H1. con. con. rewrite -H2. econstructor. done. \npunfold H1. inv H1. con. con. inv H2. injt. econstructor 4. \nintros.\nmove: (@In_zip _ _ g0 es gs H4 H6)=>[].  ssa. apply/H0.  eauto. \nforallApp H7 H8. case=>[] //=. \nQed.\n\nLemma ICpart_of_all2_iff : forall p g gc,  gUnravel2 g gc  ->  part_of_all2 p g <-> part_of_all p gc.\nProof. intros. split;intros. apply/ICpart_of_all1. eauto. done. \napply/ICpart_of_all2. eauto. done. \nQed.\n\nLemma unravel_finite : forall g gc, g << (UnfgUnravel \\o gUnravel2_gen) >> gc -> Finite gc. \nProof. \npcofix CIH. intros. \npunfold H0. inv H0. pfold. inv H;pclearbot.  con. eauto. \ncon. apply/ForallP=> x xIn. right. Check In_zip2. \nmove : (@In_zip2 _ _ x es ecs xIn H2)=>[]. ssa. forallApp H3 H5.  case=>[] //=. \neauto. con. \nQed.\n\n\n\n\nLemma gInvPred_msg : forall a u g0, gInvPred (GMsg a u g0) -> gInvPred g0. \nProof. \nintros. punfold H. inv H. inv H0. pclearbot. done. \nQed.\n\nLemma gInvPred_branch : forall a g gs, gInvPred (GBranch a gs) -> In g gs ->  gInvPred g. \nProof. \nintros. punfold H. inv H. inv H1. forallApp H3 H0. case=>[] //=. \nQed.\n\nHint Resolve gInvPred_msg gInvPred_branch. \n\n\n\nLemma Project_not_part : forall g p, Project g p EEnd  ->  ~  part_of2 p g. \nProof. intros. intro. \nelim/part_of2_ind2 : H0 H;intros. punfold H1. inv H1.  rewrite H0 in H2. inv H2;try comp_disc. \napply/H3. con. con. con. done. \npunfold H3. inv H3. rewrite H2 in H4. inv H4;pclearbot;try comp_disc. \napply/H1. pfold. con. con. rewrite -part_of2_iff. eauto. \nrewrite -gInvPred_unf_iff. eauto. \npunfold H1. inv H1. rewrite H0 in H2. inv H2. comp_disc. \napply/H3. con. con. con. done. \npunfold H4. inv H4. rewrite H3 in H5. inv H5;try comp_disc;pclearbot. \nmove/H11 : H0. ssa. pclearbot. move : H6.  cbn. move/H2. done. \napply/H2. pfold. con. con. rewrite -part_of2_iff. eauto. \nrewrite -gInvPred_unf_iff. eauto. \nQed.\n\nLemma ICProject : forall p g e gc ec, Project g p e -> gUnravel2 g gc -> lUnravel2 e ec -> CProject gc p ec. \nProof. \nmove => p. pcofix CIH. intros. apply part_of2_or_end in H0 as Hor. \ndestruct Hor. \npunfold H0. inv H0;clear H0. \npunfold H1. inv H1;clear H1.  \npunfold H2. inv H2;clear H2.  \nelim/part_of_all2_ind2 : H H3 gc ec H0 H1;intros. \n- rewrite H0 in H3,H1,H2. inv H1;clear H1;pclearbot. \n  inv H3;try comp_disc;pclearbot;eauto. \n  rewrite -H7 in H2. inv H2;pclearbot. pfold. eauto. \n  rewrite -H1 in H2. inv H2. pfold. apply/cproject_gen_end. \n  rewrite -ICpart_of_iff;eauto. pfold. con. con. eauto.\n  pfold.  con. left. apply/unravel_finite. eauto. \n- rewrite H2 in H3,H4. inv H3; try comp_disc;pclearbot. \n  inv H4;clear H4;pclearbot. pfold. con=>//=. left. apply/H1.  \n  punfold H11. inv H11. rewrite full_eunf_idemp //= in H4. \n  punfold H13. inv H13. done. done.  apply/ICpart_of_all2_iff;eauto. \n  rewrite -H6 in H5. inv H5. pfold. apply cproject_gen_end. \n  rewrite -ICpart_of_iff;eauto. pfold. con. done. \n  apply/unravel_finite. pfold. con. eauto. instantiate (1 := GMsg a u g0). done. \n- rewrite H0 in H1,H2,H3. inv H1. inv H3;pclearbot; try comp_disc. \n  rewrite -H7 in H2. inv H2. pfold. con=>//=. lia. \n  suff : Forall (fun p0 =>  upaco2 (cproject_gen p) r p0.1 p0.2) (zip ecs ecs0). \n  move/ForallP. done. \n  clear H1 H3 H2 H7 H0. \n  have : Forall (fun p0 =>  upaco2 (UnfProj \\o project_gen p) bot2 p0.1 p0.2) (zip gs es). \n  apply/ForallP. eauto. clear H11.\n  elim : gs ecs es ecs0 H6 H10 H14 H8 H15. \n  case=>//=. case=> //=. case=>//=. \n  move => a0 l IH. case=>//=. move => a1 l0.  case=>//=. \n  move => a2 l1. case=>//=. move => a3 l2. move=> [] Heq [] Heq0 [] Heq1. \n  intros. inv H8. inv H15. inv x. pclearbot. simpl in *. con;eauto. \n  rewrite -H4 in H2. inv H2. pfold. apply/cproject_gen_end. \n  rewrite -ICpart_of_iff;eauto. pfold. con. eauto. \n  apply/unravel_finite. pfold. con. instantiate (1 := GBranch a gs). done. \n- rewrite H2 in H3,H4. inv H4;clear H4.\n  inv H3;try comp_disc;try done. \n  pfold.\n  move : (@In_zip _ _ g0 gs ecs H9 H8)=>[]. ssa. \n  econstructor=>//=. eauto. clear H9 H4 H6.  \n  apply/ForallP. clear H7. \nhave : forall g : gType,\n       In g gs ->\n       forall (gc : gcType) (ec : lcType),\n       gUnravel2_gen (upaco2 (UnfgUnravel \\o gUnravel2_gen) bot2) (full_unf g) gc ->\n       lUnravel2_gen (upaco2 (UnflUnravel \\o lUnravel2_gen) bot2) (full_eunf e) ec -> gc <<( r) (cproject_gen p) >> ec.\n  intros. apply/H1;eauto. move/H12 : H4. ssa. pclearbot. punfold H9. inv H9. \n  rewrite full_eunf_idemp in H11. done. clear H1. clear H12. \n  move/ForallP. clear H2 H3.  move/ForallP : H0.  \n  elim : gs ecs H8 H10. \n  case=>//=. move=> a0 l IH. case=>//=. move=> a1 l0 [] Heq Hfor Hfor2 Hfor3. inv Hfor. inv Hfor2. inv Hfor3. pclearbot. simpl in *. con;eauto.  ssa. apply/ICpart_of_all2_iff;eauto. left. apply/H7;eauto. \n  punfold H2. inv H2. done. \n  \n  rewrite -H4 in H5. inv H5. pfold. apply/cproject_gen_end. \n  rewrite -ICpart_of_iff;eauto. pfold. con. con=>//=. \n  apply/unravel_finite. pfold. con. instantiate (1 := GBranch a gs). con=>//=. \n- punfold H0. inv H0. punfold H2.  inv H2. rewrite H in H3,H4.  inv H4.\n  pfold. con. \n  inv H0. \n  have : Project g p EEnd. pfold. con. simpl.  cbn. rewrite -H. done. \n  intros. rewrite -ICpart_of_iff;eauto. apply/Project_not_part. done. \n  apply/unravel_finite. eauto. \nQed.\n\nLemma Project_unfg : forall g p e r, paco2  (UnfProj \\o project_gen p) r (full_unf g) e -> paco2  (UnfProj \\o project_gen p) r  g e. \nProof. \nintros. punfold H. inv H. pfold. con. rewrite full_unf_idemp in H0. done. \nQed.\n\nLemma Project_eunf : forall g p e r, paco2  (UnfProj \\o project_gen p) r g (full_eunf e) -> paco2  (UnfProj \\o project_gen p) r  g e. \nProof. \nintros. punfold H. inv H. pfold. con. rewrite full_eunf_idemp in H0. done. \nQed.\n\nLemma Project_eunf2 : forall g p e r, paco2  (UnfProj \\o project_gen p) r g e -> paco2  (UnfProj \\o project_gen p) r  g (full_eunf e). \nProof. \nintros. punfold H. inv H. pfold. con. rewrite full_eunf_idemp //=.  \nQed.\n\nLemma gUnravel2_Rol : forall g gc, gUnravel2 g gc -> gInvPred g. \nProof. \npcofix CIH. intros. punfold H0. inv H0. pfold. con. inv H;pclearbot.\ncon. eauto. con;eauto. apply/ForallP=> x xIn. eauto. right.\nmove : (@In_zip _ _ x es ecs xIn H2)=>[]. ssa. \nforallApp H3 H5. case=>[] //=. ssa. eauto. \ncon. \nQed.\n\nLemma gUnravel2_iff : forall e ec r,  e <<( r) (UnfgUnravel \\o gUnravel2_gen) >> ec <-> (full_unf e) <<( r) (UnfgUnravel \\o gUnravel2_gen) >> ec.\nProof. intros. split;intros. punfold H. inv H. pfold. con. rewrite full_unf_idemp. done. \npunfold H. inv H. pfold. con. rewrite full_unf_idemp in H0. done. \nQed.\n\nLemma lUnravel2_iff : forall e ec r,  e <<( r) (UnflUnravel \\o lUnravel2_gen) >> ec <-> (full_eunf e) <<( r) (UnflUnravel \\o lUnravel2_gen) >> ec.\nProof. intros. split;intros. punfold H. inv H. pfold. con. rewrite full_eunf_idemp. done. \npunfold H. inv H. pfold. con. rewrite full_eunf_idemp in H0. done. \nQed.\n\n\nLtac pc := pclearbot.\n\nLemma In_zip_and : forall (A B : Type) (a : A) (b : B) l0 l1, In (a,b) (zip l0 l1) -> In a l0 /\\ In b l1. \nProof. \nmove => A B a b. elim. case=>//=. \nmove => a0 l IH. case=>//=. \nintros. destruct H. inv H. auto. move/IH : H. ssa. \nQed.\n\nLemma CIProject : forall p g e gc ec, CProject gc p ec -> gUnravel2 g gc -> lUnravel2 e ec -> Project g p e. \nProof. \nmove => p. pcofix CIH. intros. apply part_of_or_end in H0 as H0'. destruct H0'. \nelim/part_of_all_ind2 : H ec g e H0 H1 H2;intros. \n- punfold H1. inv H1;clear H1. \n  punfold H0. inv H0;pclearbot;try comp_disc.  punfold H2. inv H2. inv H1;pclearbot.\n  inv H3. pfold. con. rewrite -H5 -H4. con=>//=. right. pclearbot. eauto.    \n  punfold H2. inv H2. apply/Project_eunf. inv H5. pfold. con. con. \n  rewrite ICpart_of_iff;eauto. pfold. con. rewrite full_unf_idemp. done. \n  rewrite -gInvPred_unf_iff. apply/gUnravel2_Rol. pfold.  con. eauto. \n- punfold H3. inv H3. apply/Project_unfg. inv H5;pc.\n  punfold H2. inv H2;try comp_disc;pc. \n  pfold. con. con=>//=. left. apply/H1;eauto. rewrite -lUnravel2_iff.   eauto. \n  apply/ICpart_of_all2_iff;eauto.  \n  punfold H4. inv H4. apply/Project_eunf. inv H10.\n  pfold. con. apply/project_gen_end. rewrite ICpart_of_iff;eauto.\n  rewrite /full_unf /=.  eauto. \n  pfold. con. con. left. done. cbn. apply/gUnravel2_Rol. pfold. con. con. eauto. \n- punfold H1. inv H1. apply/Project_unfg. inv H3. \n  punfold H0. inv H0;try comp_disc;pclearbot. injt. punfold H2. inv H2.\n  apply/Project_eunf. inv H5. injt. pfold. con. con=>//=. lia. \n  apply/ForallP. move/ForallP : H12. clear H6 H2 H0 H5 H1 H3 H4. \n  elim : es ecs es0 es1 H7 H10 H14 H8 H16. \n  case=>//=. case=>//=. case=>//=. move => a0 l IH. case=>//=.\n  move => a1 l0 [] //=.  move => a2 l1 [] //=. \n  move => a3 l2 [] Heq [] Heq0 [] Heq1. intros. inv H8. inv H16. inv H12. pclearbot. \n  simpl in *. con;eauto. \n  punfold H2. inv H2. apply/Project_eunf. inv H9. pfold. con. apply/project_gen_end. \n  rewrite ICpart_of_iff;eauto. rewrite -gUnravel2_iff. pfold.  con. con. lia. done. \n  rewrite -gInvPred_unf_iff. apply/gUnravel2_Rol. pfold. con. con. 2 : eauto. eauto.\n- punfold H3. inv H3.  apply/Project_unfg. inv H5. injt. \n  punfold H2. inv H2;pclearbot;try comp_disc. injt. \n   have :  forall g : gcType,\n       In g gs ->\n       forall (ec : lcType) (g0 : gType) (e : lType),\n       CProject g p ec -> gUnravel2 g0 g -> lUnravel2 e ec -> g0 <<( r) (UnfProj \\o project_gen p) >> e. \n  intros. apply/H1;eauto. clear H1 => H1. \n  move : (@In_zip2 _ _ g0 es gs H12 H9)=>[]. ssa. \n  pfold. con. econstructor=>//=. eauto.\n  ssa. move : (@In_zip _ _ g' es gs H13 H9)=>[].  ssa. \n  apply/ICpart_of_all2_iff;eauto.  forallApp H10 H16. case=>[]//=. \n  left. apply/Project_eunf2. (*apply In_zip_and in H8. ssa. *)\n  move : (@In_zip _ _ g' es gs H13 H9)=>[].  ssa. \n  apply/H1. apply/H15.  all : eauto. \n  move/H14 : H15. ssa. pclearbot. done. \n  forallApp H10 H16. case=>[] //=. punfold H4. inv H4. \n  apply/Project_eunf. inv H11. pfold. con. apply/project_gen_end. \n  cbn. rewrite ICpart_of_iff;eauto. pfold. con. con=>//=. \n  cbn. apply/gUnravel2_Rol. pfold. con. con. 2 : eauto. lia. \n- subst. pfold. con. punfold H2. inv H2. inv H. con. \n  rewrite ICpart_of_iff. apply/CProject_not_part. eauto. \n  rewrite -gUnravel2_iff //=. \n  apply/gUnravel2_Rol. rewrite -gUnravel2_iff. eauto. \nQed.\n\n\nLet rwd := (etocoind'_eq, etocoind_eq, gtocoind'_eq, gtocoind_eq). \nLtac seq := rewrite ?eqs -?rwd.\nLtac seq_in H := rewrite ?eqs -?rwd in H.\n\n\n\nLemma Project_gtree : forall p g e, Project g p e -> gUnravel2 g (gtocoind g). \nProof. \nmove => p. pcofix CIH. intros. punfold H0. inv H0. rewrite gtocoind_full_unf. apply/gUnravel2_iff.  inv H;seq.  \npfold. con. con. pclearbot.  eauto. \npfold. con. \ncon. pclearbot.  eauto. \npfold. con. con. rewrite size_map=>//=.\nmove/ForallP : H5. clear H2 H1. elim : gs es H4. case=>//=. \nmove => a0 l IH. case=>//=. move => a1 l0 [] Heq. intros. inv H5. pclearbot. simpl in *. \ncon;eauto. \npfold. con. con. rewrite size_map //=. \nmove/ForallP : H4. clear H2 H1 H3. elim : gs. \nsimpl. done. move => a0 l IH HH. inv HH. ssa.  pclearbot. con;eauto.\nrewrite -gtocoind_full_unf.  rewrite -gUnravel2_iff.\napply/paco2_mon.\napply/gInvPred_iff. rewrite gInvPred_unf_iff. done. done. \nQed. \n\n\n\nLemma Project_etree : forall p g e, Project g p e -> lUnravel2 e (etocoind e). \nProof. \nmove => p. pcofix CIH. intros. apply part_of2_or_end in H0 as H0'. \ndestruct H0'. \nelim/part_of_all2_ind2 : H e H0;intros. \npunfold H1. inv H1. rewrite H0 in H2. rewrite etocoind_full_eunf.  apply/lUnravel2_iff. inv H2;pclearbot;try comp_disc. \npfold. seq.  con. con. eauto. pfold. con. seq. con. \napply/H1. punfold H3. inv H3. rewrite H2 in H4. inv H4;pclearbot ;try comp_disc. \napply/Project_eunf. done. pfold. con. rewrite -H5. con. rewrite -part_of2_iff. eauto. \nrewrite -gInvPred_unf_iff.  eauto. \npunfold H1. inv H1. rewrite H0 in H2. rewrite etocoind_full_eunf.  apply/lUnravel2_iff. inv H2;pclearbot;try comp_disc. \npfold. seq.  con. con. rewrite size_map //=. \nmove/ForallP : H8. clear H5 H0 H2. elim : gs es H7. case=>//=. \nmove => a0 l IH. case=>//=. move => a1 l0 [] Heq. intros. inv H8. pclearbot. simpl in *. \ncon;eauto. \nseq. pfold. con. con. \npunfold H3. inv H3. rewrite H2 in H4. rewrite etocoind_full_eunf. apply/lUnravel2_iff. inv H4;pclearbot;try comp_disc. \nrewrite -lUnravel2_iff. rewrite -etocoind_full_eunf. apply/H1. eauto. eauto. \nmove/H10 : H8. ssa. pclearbot. apply/Project_eunf. done. \nseq. pfold. con. con. \nrewrite etocoind_full_eunf. apply/lUnravel2_iff. rewrite H. seq. pfold. con. con. \nQed.\n\n\nLemma ICProject_iff : forall g p e, Project g p e <-> exists gc ec, gUnravel2 g gc /\\ lUnravel2 e ec /\\ CProject gc p ec. \nProof. \nintros. split. intros. exists (gtocoind g). exists (etocoind e). ssa. \napply/Project_gtree;eauto.  \napply/Project_etree;eauto.  \napply/ICProject;eauto. apply/Project_gtree;eauto. apply/Project_etree;eauto.  \ncase=> x []. intros. ssa. apply/CIProject;eauto. \nQed.\n\n", "meta": {"author": "Tirore96", "repo": "projection", "sha": "7bf35d942fa572c9d77f96651f889d9c736b68af", "save_path": "github-repos/coq/Tirore96-projection", "path": "github-repos/coq/Tirore96-projection/projection-7bf35d942fa572c9d77f96651f889d9c736b68af/theories/Projection/intermediateProj.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.210029213402852}}
{"text": "From hahn Require Import Hahn.\nFrom imm Require Import\n     AuxDef\n     Events Execution TraversalConfig TraversalConfigAlt\n     SimTraversal SimTraversalProperties\n     imm_common imm_s imm_s_hb CertExecution1\n     CombRelations Execution_eco.\nRequire Import AuxRel.\nRequire Import AuxDef.\nRequire Import ImmProperties.\n\nSection CertRf.\nVariable G  : execution.\nVariable sc : relation actid.\nVariable TC : trav_config.\n\nNotation \"'C'\"  := (covered TC).\nNotation \"'I'\"  := (issued TC).\n\nNotation \"'E'\"  := G.(acts_set).\nNotation \"'lab'\" := (G.(lab)).\nNotation \"'rmw'\" := G.(rmw).\n\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'NTid_' t\" := (fun x => tid x <> t) (at level 1).\n\nNotation \"'R'\" := (fun a => is_true (is_r lab a)).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\n\nNotation \"'Acq'\" := (fun a => is_true (is_acq lab a)).\nNotation \"'Rel'\" := (fun a => is_true (is_rel lab a)).\nNotation \"'Sc'\" := (fun a => is_true (is_sc lab a)).\nNotation \"'Acq/Rel'\" := (fun a => is_true (is_ra lab a)).\n\nNotation \"'sb'\"  := (G.(sb)).\nNotation \"'ppo'\" := (G.(ppo)).\nNotation \"'sw'\"  := (G.(imm_s_hb.sw)).\nNotation \"'hb'\"  := (G.(imm_s_hb.hb)).\nNotation \"'rf'\"  := (G.(rf)).\nNotation \"'rfi'\" := (G.(rfi)).\nNotation \"'rfe'\" := (G.(rfe)).\nNotation \"'co'\"  := (G.(co)).\nNotation \"'loc'\" := (loc lab).\n\nNotation \"'Loc_' l\" := (fun x => loc x = Some l) (at level 1).\nNotation \"'W_' l\" := (W ∩₁ Loc_ l) (at level 1).\nNotation \"'R_' l\" := (R ∩₁ Loc_ l) (at level 1).\n\nNotation \"'furr'\" := (furr G sc).\n\nDefinition CsbI := (C ∪₁ dom_rel (sb^? ⨾ ⦗ I ⦘)).\n\nDefinition D :=\n  C ∪₁ I ∪₁\n  dom_rel (rfi^? ⨾ ppo ⨾ ⦗ I ⦘) ∪₁\n  codom_rel (⦗I⦘ ⨾ rfi) ∪₁\n  codom_rel (rfe ⨾ ⦗ R ∩₁ Acq ⦘).\n\nDefinition vf :=\n  ⦗ W ⦘ ⨾ (rf ⨾ ⦗ C ⦘)^? ⨾ hb^? ⨾ sc^? ⨾ hb^? ⨾ ⦗ E ⦘ ∪\n  rf ⨾ ⦗ D ⦘ ⨾ sb^?.\n\nDefinition cert_rf :=\n  vf ∩ same_loc lab ⨾ ⦗ CsbI ∩₁ R ⦘ \\ co ⨾ vf.\n\nDefinition cert_rfi := cert_rf ∩ sb.\nDefinition cert_rfe := cert_rf \\  sb.\n\nSection Properties.\nVariable WF  : Wf G.\nVariable COH : imm_consistent G sc.\nVariable TCCOH : tc_coherent G sc TC.\nVariable RELCOH : W ∩₁ Rel ∩₁ I ⊆₁ C.\n\n(******************************************************************************)\n(** ** CsbI propeties *)\n(******************************************************************************)\n\nLemma CsbI_in_E : CsbI ⊆₁ E.\nProof.\n  unfold CsbI.\n  rewrite coveredE, issuedE; try edone.\n  rewrite (dom_l (@wf_sbE G)).\n  basic_solver.\nQed.\n\nLemma CsbI_sb_prcl :\n  dom_rel (sb ⨾ ⦗ CsbI ⦘) ⊆₁ CsbI.\nProof.\n  unfold CsbI.\n  rewrite id_union.\n  rewrite seq_union_r.\n  rewrite dom_union.\n  apply set_union_Proper.\n  { eapply dom_sb_covered; eauto. }\n  rewrite !seq_eqv_r.\n  unfolder; ins; desf; splits; auto.\n  { do 2 eexists; splits; eauto. }\n  do 2 eexists; splits.\n  2-3: eauto.\n  right. eapply sb_trans; eauto.\nQed.\n\nLemma CsbI_rmw_fwcl (RMWCOV : forall r w, rmw r w -> C r <-> C w) :\n  ⦗CsbI⦘ ⨾ rmw ≡ ⦗CsbI⦘ ⨾ rmw ⨾ ⦗CsbI⦘.\nProof.\n  split; [|basic_solver].\n  unfold CsbI.\n  rewrite !id_union.\n  rewrite !seq_union_l, !seq_union_r.\n  unionL.\n  { repeat unionR left.\n    unfolder. ins. splits; desf.\n    match goal with\n    | H : rmw ?x ?y |- _ => eapply RMWCOV in H\n    end.\n    intuition. }\n  unionR right -> right.\n  rewrite WF.(wf_rmwD) at 1.\n  unfolder. ins. splits; desf.\n  1,3: exfalso;\n    match goal with\n    | H : I ?y |- _ => rename H into AA\n    end;\n    eapply issuedW in AA; eauto;\n      type_solver.\n  all: do 2 eexists.\n  { splits; eauto. }\n  splits; [| |by eauto].\n  2: done.\n  destruct (classic (y = y0)) as [|NEQ]; eauto.\n  right.\n  match goal with\n  | H : rmw ?x ?y |- _ => rename H into RMW\n  end.\n  apply WF.(rmw_from_non_init) in RMW.\n  destruct_seq_l RMW as AA.\n  edestruct sb_semi_total_l with (x:=x); eauto.\n  { by apply rmw_in_sb. }\n  exfalso.\n  eapply wf_rmwi; eauto.\nQed.\n\nLemma CsbI_hb_prcl :\n  dom_rel (hb ⨾ ⦗ CsbI ⦘) ⊆₁ CsbI.\nProof.\n  unfold CsbI.\n  rewrite <- seq_eqvK.\n  sin_rewrite hb_in_Chb_sb; eauto.\n  rewrite seq_union_l, dom_union.\n  unionL; [|apply CsbI_sb_prcl].\n  rewrite !seqA, !dom_seq.\n  basic_solver.\nQed.\n\nLemma sc_hb_CsbI_in_C :\n  dom_rel (sc ⨾ hb ⨾ ⦗CsbI⦘) ⊆₁ C.\nProof.\n  arewrite (hb ⨾ ⦗CsbI⦘ ⊆ ⦗CsbI⦘ ⨾ hb).\n  { generalize CsbI_hb_prcl. basic_solver. }\n  unfold CsbI.\n  rewrite <- seqA.\n  erewrite scCsbI_C; eauto.\n  basic_solver.\nQed.\n\nLemma hb_sc_hb_CsbI_alt :\n  hb^? ⨾ sc^? ⨾ hb^? ⨾ ⦗CsbI⦘ ⊆\n    (⦗C⦘ ⨾ hb^? ⨾ sc^? ⨾ hb^? ∪ sb)^?.\nProof.\n  rewrite crE\n    with (r := hb) at 1 2.\n  rewrite crE\n    with (r := sc) at 1.\n  relsf.\n  arewrite (hb ⨾ hb ⊆ hb).\n  rewrite !unionA.\n  apply union_mori.\n  { basic_solver. }\n  unionL.\n\n  1,4,5 : unfold CsbI;\n          rewrite hb_in_Chb_sb;\n          eauto; basic_solver 10.\n\n  { unfold CsbI.\n    erewrite scCsbI_C; eauto.\n    basic_solver 10. }\n\n  { erewrite dom_rel_helper.\n    2 : eapply sc_hb_CsbI_in_C; eauto.\n    basic_solver 10. }\n\n  { unfold CsbI.\n    erewrite scCsbI_C; eauto.\n    sin_rewrite hb_covered; eauto.\n    basic_solver 10. }\n\n  erewrite dom_rel_helper\n    with (r := hb ⨾ ⦗CsbI⦘).\n  2 : eapply CsbI_hb_prcl; eauto.\n  arewrite\n    (sc ⨾ ⦗CsbI⦘ ⊆ ⦗C⦘ ⨾ sc).\n  { unfold CsbI at 1.\n    erewrite scCsbI_C; eauto; done. }\n  sin_rewrite hb_covered; eauto.\n  basic_solver 10.\nQed.\n\n(******************************************************************************)\n(** ** D propeties *)\n(******************************************************************************)\n\nLemma D_in_E : D ⊆₁ E.\nProof.\n  unfold D.\n  rewrite (wf_ppoE WF), (wf_rfiE WF), (wf_rfeE WF), (coveredE TCCOH).\n  rewrite (issuedE TCCOH) at 1.\n  basic_solver 21.\nQed.\n\nLemma D_R : D ∩₁ R ≡₁ C ∩₁ R ∪₁\n  dom_rel (ppo ⨾ ⦗ I ⦘) ∪₁\n  codom_rel (⦗I⦘ ⨾ rfi) ∪₁\n  codom_rel (rfe ⨾ ⦗ R ∩₁ Acq ⦘).\nProof.\n  unfold D.\n  rewrite !set_inter_union_l.\n  rewrite crE. relsf.\n  arewrite\n    (I ∩₁ R ≡₁ ∅).\n  { split; [|done].\n    rewrite issuedW; eauto.\n    type_solver. }\n  arewrite\n    (dom_rel (rfi ⨾ ppo ⨾ ⦗I⦘) ∩₁ R ≡₁ ∅).\n  { rewrite wf_rfiD; auto. type_solver. }\n  rewrite wf_rfiD, wf_rfeD, wf_ppoD; auto.\n  basic_solver 20.\nQed.\n\nLemma C_in_D : C ⊆₁ D.\nProof. unfold D. by repeat left. Qed.\n\nLemma I_in_D : I ⊆₁ D.\nProof. unfold D. do 3 left. by right. Qed.\n\nLemma CI_in_D : C ∪₁ I ⊆₁ D.\nProof. unfold D. by do 3 left. Qed.\n\nLemma rfi_D_in_D :\n  dom_rel (rfi ⨾ ⦗ D ⦘) ⊆₁ D.\nProof.\n  intros w [r RFI]. destruct_seq_r RFI as DR.\n  apply wf_rfiD in RFI; auto. destruct_seq RFI as [WW RR].\n  apply wf_rfiE in RFI; auto. destruct_seq RFI as [EW ER].\n  red in DR. unfold set_union in DR. desf.\n  { apply C_in_D. eapply dom_sb_covered; eauto.\n    eexists. apply seq_eqv_r. split; eauto. apply RFI. }\n  { eapply issuedW in DR; eauto. type_solver. }\n  { red. do 2 left. right.\n    destruct DR as [z [v [[EE|EE] DR]]].\n    { desf. generalize RFI DR. basic_solver 10. }\n    apply wf_rfiD in EE; auto. destruct_seq EE as [WR RV].\n    clear -RR WR. type_solver. }\n  { apply I_in_D. destruct DR as [v DR].\n    destruct_seq_l DR as IV.\n    assert (v = w); desf.\n    eapply wf_rff; eauto.\n    { apply DR. }\n    apply RFI. }\n  destruct DR as [v DR].\n  destruct_seq_r DR as IV.\n  assert (v = w); desf.\n  { eapply wf_rff; eauto.\n    { apply DR. }\n    apply RFI. }\n  unfold Execution.rfi, Execution.rfe in *.\n  generalize RFI DR. basic_solver.\nQed.\n\nLemma rfe_D_CsbI_in_D :\n  dom_rel (rfe ⨾ ⦗ D ∩₁ CsbI ⦘) ⊆₁ D.\nProof.\n  intros w [r RFE]. destruct_seq_r RFE as DR.\n  apply wf_rfeD in RFE; auto. destruct_seq RFE as [WW RR].\n  apply wf_rfeE in RFE; auto. destruct_seq RFE as [EW ER].\n  destruct DR as [DR CsbIr].\n  assert (C r -> D w) as UU.\n  { intros HH. apply I_in_D. eapply dom_rf_covered; eauto.\n    eexists. apply seq_eqv_r. split; eauto. apply RFE. }\n  destruct CsbIr as [EE0|EE0].\n  { intuition. }\n\n  red in DR. unfold set_union in DR. desf.\n  { intuition. }\n  { eapply issuedW in DR; eauto. type_solver. }\n  { red. apply I_in_D.\n    destruct DR as [z [v [[EE|EE] DR]]].\n    2: { apply wf_rfiD in EE; auto. destruct_seq EE as [WR RV].\n         clear -RR WR. type_solver. }\n    desf. eapply dom_rfe_ppo_issued; eauto.\n    do 2 eexists. eauto. }\n  { exfalso. destruct DR as [v DR].\n    destruct_seq_l DR as IV.\n    assert (v = w); desf.\n    eapply wf_rff; eauto.\n    { apply DR. }\n    { apply RFE. }\n    apply RFE. apply DR. }\n  destruct EE0 as [t EE0]. destruct_seq_r EE0 as IT.\n  destruct EE0 as [|EE0]; subst.\n  { eapply issuedW in IT; eauto. type_solver. }\n  apply I_in_D.\n  eapply dom_rfe_acq_sb_issued; eauto.\n  destruct DR as [v DR].\n  destruct_seq_r DR as IV.\n  assert (v = w); desf.\n  { eapply wf_rff; eauto.\n    { apply DR. }\n    apply RFE. }\n  generalize DR IV IT EE0. basic_solver 10.\nQed.\n\nLemma rf_D_CsbI_in_D :\n  dom_rel (rf ⨾ ⦗ D ∩₁ CsbI ⦘) ⊆₁ D.\nProof.\n  intros w [r RF]. destruct_seq_r RF as DR.\n  apply rfi_union_rfe in RF. destruct RF as [RF|RF].\n  { apply rfi_D_in_D; auto. eexists.\n    apply seq_eqv_r; split; eauto. apply DR. }\n  apply rfe_D_CsbI_in_D; auto. eexists.\n  apply seq_eqv_r; split; eauto.\nQed.\n\n(******************************************************************************)\n(** ** vf propeties *)\n(******************************************************************************)\n\nLemma vfE : vf ≡ ⦗ E ⦘ ⨾ vf ⨾ ⦗ E ⦘.\nProof.\n  apply dom_helper_3.\n  unfold vf.\n  rewrite WF.(wf_rfE).\n  rewrite (dom_l WF.(wf_hbE)).\n  cdes COH.\n  rewrite (dom_l (wf_scE Wf_sc)).\n  rewrite (dom_r (@wf_sbE G)).\n  basic_solver.\nQed.\n\nLemma vf_dom : vf ≡ ⦗ W ⦘ ⨾ vf.\nProof.\n  split; [|basic_solver].\n  unfold vf.\n  rewrite (dom_l WF.(wf_rfD)) at 2.\n  rewrite !seqA. rewrite seq_union_r.\n    by seq_rewrite seq_eqvK.\nQed.\n\nLemma vf_alt :\n  vf ≡ ⦗ W ⦘ ⨾ (rf ⨾ ⦗ C ⦘)^? ⨾ hb^? ⨾ sc^? ⨾ hb^? ⨾ ⦗ E ⦘ ∪\n        rf ⨾ ⦗ C ⦘ ⨾ sb^? ∪\n        rf ⨾ ⦗ dom_rel (ppo ⨾ ⦗ I ⦘) ⦘ ⨾ sb^? ∪\n        ⦗I⦘ ⨾ rfi ⨾ sb^? ∪\n        rfe ⨾ ⦗ Acq ⦘ ⨾ sb^?.\nProof.\n  unfold vf.\n  rewrite !unionA.\n  apply union_more; try done.\n  rewrite <- !seqA, <- !unionA.\n  rewrite <- !seq_union_l.\n  apply seq_more; try done.\n  arewrite (rf ⨾ ⦗D⦘ ≡ rf ⨾ ⦗D ∩₁ R⦘).\n  { rewrite wf_rfD; auto. basic_solver. }\n  rewrite D_R.\n  rewrite !id_union, !seq_union_r.\n  repeat apply union_more; try done.\n  { rewrite wf_rfD; auto. basic_solver. }\n  { rewrite seq_eqv_l, seq_eqv_r.\n    unfolder; splits.\n    { intros x y [RF [z [Iz RFI]]].\n      arewrite (x = z); auto.\n      eapply wf_rff; eauto.\n      apply RFI. }\n    intros x y [Ix RFI].\n    split; [apply RFI|].\n    exists x; splits; auto. }\n  rewrite seq_eqv_r\n    with (dom := R ∩₁ Acq).\n  rewrite seq_eqv_r\n    with (dom := Acq).\n  rewrite seq_eqv_r.\n  unfolder; splits.\n  { intros x y [RF [z [RFE [Ry ACQy]]]].\n    arewrite (x = z); auto.\n    eapply wf_rff; eauto.\n    apply RFE. }\n  intros x y [RFE ACQy].\n  split; [apply RFE|].\n  exists x; splits; auto.\n  apply wf_rfeD in RFE; auto.\n  generalize RFE. basic_solver.\nQed.\n\nLemma vf_in_furr : vf ⊆ furr.\nProof.\n  cdes COH.\n  unfold vf.\n  arewrite_id ⦗D⦘. arewrite_id ⦗E⦘. arewrite_id ⦗C⦘.\n  rewrite !seq_id_r, !seq_id_l.\n  rewrite furr_alt; auto.\n  unionL; [done|].\n  rewrite (dom_l WF.(wf_rfD)) at 1.\n  rewrite sb_in_hb.\n  basic_solver 20.\nQed.\n\nLemma sb_in_vf : ⦗ W ⦘ ⨾ sb ⊆ vf.\nProof.\n  unfold vf.\n  rewrite wf_sbE.\n  rewrite sb_in_hb at 1.\n  basic_solver 20.\nQed.\n\nLemma vf_sb_in_vf : vf ⨾ sb ⊆ vf.\nProof.\n  unfold vf.\n  rewrite seq_union_l, !seqA.\n  apply union_mori.\n  { do 4 (apply seq_mori; [done|]).\n    rewrite wf_sbE.\n    rewrite sb_in_hb.\n    generalize hb_trans.\n    basic_solver. }\n  do 2 (apply seq_mori; [done|]).\n  generalize sb_trans.\n  basic_solver.\nQed.\n\n(******************************************************************************)\n(** ** cert_rf propeties *)\n(******************************************************************************)\n\nLemma cert_rfE : cert_rf ≡ ⦗E⦘ ⨾ cert_rf ⨾ ⦗E⦘.\nProof.\n  cdes COH.\n  apply dom_helper_3.\n  unfold cert_rf.\n  rewrite vfE.\n  basic_solver.\nQed.\n\nLemma cert_rfD : cert_rf ≡ ⦗W⦘ ⨾ cert_rf ⨾ ⦗R⦘.\nProof.\n  apply dom_helper_3.\n  unfold cert_rf.\n  rewrite inclusion_minus_rel.\n  rewrite inter_inclusion.\n  rewrite vf_dom.\n  basic_solver.\nQed.\n\nLemma cert_rf_codom : cert_rf ≡ cert_rf ⨾ ⦗CsbI⦘.\nProof. unfold cert_rf. basic_solver. Qed.\n\n(* Lemma cert_rf_codomt : cert_rf ≡ cert_rf ⨾ ⦗Tid_ thread⦘. *)\n(* Proof. *)\n(*   split; [|basic_solver]. *)\n(*   rewrite cert_rf_codomE0 at 1. *)\n(*   unfold E0. basic_solver. *)\n(* Qed. *)\n\nLemma cert_rfl : cert_rf ⊆ same_loc lab.\nProof. unfold cert_rf. basic_solver. Qed.\n\nLemma cert_rff : functional cert_rf⁻¹.\nProof.\n  rewrite cert_rfD, cert_rfE.\n  red. intros x y z AA BB.\n  assert (exists l, loc y = Some l) as HH.\n  { generalize (is_w_loc lab). unfolder in *.\n    basic_solver 12. }\n  desc.\n\n  assert (loc z = Some l) as GG.\n  { hahn_rewrite cert_rfl in AA.\n    hahn_rewrite cert_rfl in BB.\n    unfold same_loc in *.\n    unfolder in *.\n    desf. congruence. }\n\n  unfolder in *.\n  destruct (classic (y=z)) as [|X]; eauto; desf.\n  exfalso.\n  eapply wf_co_total in X; try basic_solver 22.\n  2: { unfolder. splits; eauto. congruence. }\n  unfold cert_rf in *. desf; unfolder in *; basic_solver 40.\nQed.\n\nLemma cert_rf_complete : forall b (IN: (CsbI ∩₁ R) b), exists a, cert_rf a b.\nProof.\n  ins; unfolder in *; desc.\n  assert (exists l, loc b = Some l); desc.\n  { by generalize (is_r_loc lab); unfolder in *; basic_solver 12. }\n\n  assert (E b) as UU.\n  { by apply CsbI_in_E. }\n\n  assert (E (InitEvent l)).\n  { by apply WF; eauto. }\n  assert (lab (InitEvent l) = Astore Xpln Opln l 0).\n  { by apply WF. }\n  assert (loc (InitEvent l) = Some l).\n  { by unfold Events.loc; rewrite (wf_init_lab WF). }\n  assert (W_ l (InitEvent l)).\n  { by unfolder; unfold is_w, Events.loc; desf; eauto. }\n  assert (sb (InitEvent l) b).\n  { by apply init_ninit_sb; eauto; eapply read_or_fence_is_not_init; eauto. }\n  assert (vf (InitEvent l) b).\n  { left. red.\n    exists (InitEvent l); splits.\n    { red. splits; desf; by apply WF.(init_w). }\n    unfold eqv_rel; eauto.\n    hahn_rewrite <- sb_in_hb.\n    basic_solver 21. }\n\n  forward (eapply last_exists with (s:=co ⨾ ⦗fun x => vf x b⦘)\n                                   (dom:= filterP (W_ l) G.(acts)) (a:=(InitEvent l))).\n  { eapply acyclic_mon.\n    apply trans_irr_acyclic; [apply co_irr| apply co_trans]; eauto.\n    basic_solver. }\n  { ins.\n    assert (A: (co ⨾ ⦗fun x : actid => vf x b⦘)^? (InitEvent l) c).\n    { apply rt_of_trans; try done.\n      apply transitiveI.\n      arewrite_id ⦗fun x : actid => vf x b⦘ at 1.\n      rewrite seq_id_l.\n      arewrite (co ⨾ co ⊆ co); [|done].\n      apply transitiveI.\n      eapply co_trans; eauto. }\n    unfolder in A; desf.\n    { by apply in_filterP_iff; split; auto. }\n    apply in_filterP_iff.\n    hahn_rewrite WF.(wf_coE) in A.\n    hahn_rewrite WF.(wf_coD) in A.\n    hahn_rewrite WF.(wf_col) in A.\n    unfold same_loc in *; unfolder in *; desf; splits; eauto; congruence. }\n  ins; desc.\n  assert (A: (co ⨾ ⦗fun x : actid => vf x b⦘)^? (InitEvent l) b0).\n  { apply rt_of_trans; [|by subst].\n    apply transitiveI.\n    arewrite_id ⦗fun x : actid => vf x b⦘ at 1.\n    rewrite seq_id_l.\n    arewrite (co ⨾ co ⊆ co); [|done].\n    apply transitiveI.\n    eapply co_trans; eauto. }\n  assert (loc b0 = Some l).\n  { unfolder in A; desf.\n    hahn_rewrite WF.(wf_col) in A.\n    unfold same_loc in *; desf; unfolder in *; congruence. }\n  exists b0; red; split.\n  { unfold urr, same_loc.\n    unfolder in A; desf; unfolder; ins; desf; splits; try basic_solver 21; congruence. }\n  unfold max_elt in *.\n  unfolder in *; ins; desf; intro; desf; basic_solver 11.\nQed.\n\n(* Lemma cert_rf_mod: E0 ∩₁ R ≡₁ codom_rel cert_rf. *)\n(* Proof. *)\n(*   split. *)\n(*   { intros x HH. *)\n(*     apply cert_rf_complete in HH. *)\n(*     desc. eexists. eauto. } *)\n(*   rewrite (dom_r cert_rfD). *)\n(*   rewrite cert_rf_codomE0. *)\n(*   rewrite !codom_eqv1. *)\n(*   basic_solver 10. *)\n(* Qed. *)\n\nLemma cert_rf_in_vf : cert_rf ⊆ vf.\nProof. unfold cert_rf. basic_solver. Qed.\n\nLemma cert_rf_in_furr : cert_rf ⊆ furr.\nProof. rewrite cert_rf_in_vf. apply vf_in_furr. Qed.\n\nLemma cert_rf_hb_sc_hb_irr: irreflexive (cert_rf ⨾ hb ⨾ (sc ⨾ hb)^?).\nProof.\n  rewrite cert_rf_in_furr.\n  apply furr_hb_sc_hb_irr; auto.\n  all: apply COH.\nQed.\n\nLemma cert_rf_hb_irr: irreflexive (cert_rf ⨾ hb).\nProof. generalize cert_rf_hb_sc_hb_irr. basic_solver 10. Qed.\n\nLemma cert_rf_tid_in_sb thread (NINITT : thread <> tid_init) :\n  ⦗ Tid_ thread ⦘ ⨾ cert_rf ⨾ ⦗ Tid_ thread ⦘ ⊆ sb.\nProof.\n  intros x y CertRF.\n  destruct_seq CertRF as [TIDx TIDy].\n  apply cert_rfE in CertRF; auto. destruct_seq CertRF as [EX EY].\n  apply cert_rfD in CertRF. destruct_seq CertRF as [WX RY].\n  edestruct same_thread\n    with (x:=x) (y:=y) as [[|SB]|SB]; eauto.\n  { intros INITx.\n    assert (is_w lab y)\n      as INITy; [|type_solver].\n    apply init_w; auto.\n    unfold tid, is_init in *.\n    destruct x, y; auto; congruence. }\n  { congruence. }\n  { type_solver. }\n  exfalso. eapply cert_rf_hb_sc_hb_irr; eauto.\n  eexists. splits; eauto.\n  eexists. splits.\n  { eapply imm_s_hb.sb_in_hb; eauto. }\n    by left.\nQed.\n\nLemma rf_D_in_vf : rf ⨾ ⦗D⦘ ⊆ vf.\nProof.\n  rewrite (dom_l WF.(wf_rfD)).\n  arewrite (D ⊆₁ D ∩₁ E).\n  { generalize D_in_E. basic_solver. }\n  unfold vf. basic_solver 20.\nQed.\n\nLemma rf_vf_in_cert_rf : (rf ⨾ ⦗CsbI⦘) ∩ vf ⊆ cert_rf.\nProof.\n  unfold cert_rf.\n  rewrite minus_inter_compl.\n  apply inclusion_inter_r.\n  { rewrite (dom_r WF.(wf_rfD)).\n    rewrite WF.(wf_rfl). basic_solver. }\n  rewrite vf_in_furr.\n  unfolder. ins. desf.\n  intros HH. desf.\n  eapply eco_furr_irr; eauto.\n  all: try apply COH.\n  eexists. split; eauto.\n  apply fr_in_eco. eexists. split; eauto.\nQed.\n\nLemma rf_D_in_cert_rf : rf ⨾ ⦗ D ∩₁ CsbI ⦘ ⊆ cert_rf.\nProof.\n  rewrite <- rf_vf_in_cert_rf.\n  apply inclusion_inter_r.\n  { basic_solver 10. }\n  rewrite <- rf_D_in_vf. basic_solver.\nQed.\n\nLemma rf_C_in_cert_rf : rf ⨾ ⦗ C ⦘ ⊆ cert_rf.\nProof.\n  rewrite <- rf_D_in_cert_rf.\n  unfold D, CsbI.\n  rewrite !set_inter_union_l,\n          !id_union, !seq_union_r.\n  basic_solver 10.\nQed.\n\nLemma rfi_in_cert_rf : rfi ⨾ ⦗ CsbI ⦘ ⊆ cert_rf.\nProof.\n  unfold cert_rf. rewrite minus_inter_compl.\n  apply inclusion_inter_r.\n  { rewrite (dom_r WF.(wf_rfiD)).\n    unfold Execution.rfi.\n    rewrite <- seq_eqv_inter_lr\n      with (r := vf).\n    apply inclusion_inter_r.\n    2: { rewrite WF.(wf_rfl). basic_solver. }\n    unfold vf.\n    rewrite seq_union_l.\n    unionR left.\n    rewrite (dom_l WF.(wf_rfD)), (dom_r WF.(wf_rfE)).\n    rewrite sb_in_hb. basic_solver 30. }\n  unfold Execution.rfi.\n  rewrite vf_in_furr.\n  unfolder. ins. desf.\n  intros HH. desf.\n  eapply eco_furr_irr; eauto.\n  all: try apply COH.\n  eexists. split; eauto.\n  apply fr_in_eco. eexists. split; eauto.\nQed.\n\n(* Lemma cert_rfi_union_cert_rfe : cert_rf ≡ cert_rfi ∪ cert_rfe. *)\n(* Proof. *)\n(*   unfold cert_rfi, cert_rfe. *)\n(*   rewrite <- seq_union_l. *)\n(*   rewrite <- id_union. *)\n(*   arewrite (Tid_ thread ∪₁ NTid_ thread ≡₁ ⊤₁). *)\n(*   { split; [basic_solver|]. *)\n(*     unfolder. ins. apply classic. } *)\n(*   rewrite seq_id_l. by rewrite cert_rf_codomt at 1. *)\n(* Qed. *)\n\nLemma cert_rf_D_in_rf : cert_rf ⨾ ⦗ D ⦘ ⊆ rf.\nProof.\n  rewrite cert_rf_codom, !seqA, <- id_inter.\n  arewrite (cert_rf ⊆ cert_rf ⨾ ⦗ E ∩₁ R ⦘).\n  { rewrite (dom_r cert_rfD), (dom_r cert_rfE) at 1.\n    basic_solver. }\n  cdes COH. red in Comp. rewrite Comp.\n  unfolder. ins. desf.\n  assert (x0 = x); try subst x0; desf.\n  eapply cert_rff; eauto.\n  apply rf_D_in_cert_rf.\n  apply seq_eqv_r.\n  do 3 (split; auto).\nQed.\n\nLemma cert_rf_C_in_rf : cert_rf ⨾ ⦗ C ⦘ ⊆ rf.\nProof.\n  arewrite (C ⊆₁ D).\n  { unfold D, CsbI. basic_solver 10. }\n  apply cert_rf_D_in_rf.\nQed.\n\nLemma cert_rf_D_eq_rf_D : cert_rf ⨾ ⦗ D ∩₁ CsbI ⦘ ≡ rf ⨾ ⦗ D ∩₁ CsbI ⦘.\nProof. generalize cert_rf_D_in_rf, rf_D_in_cert_rf. basic_solver 10. Qed.\n\nLemma cert_rf_Acq_in_rf : cert_rf ⨾ ⦗ Acq ⦘ ⊆ rf.\nProof.\n  arewrite (cert_rf ⊆ cert_rf ⨾ ⦗ E ∩₁ R ⦘).\n  { rewrite (dom_r cert_rfD), (dom_r cert_rfE) at 1.\n    basic_solver. }\n  cdes COH. red in Comp. rewrite Comp.\n  rewrite rfi_union_rfe at 1.\n  rewrite codom_union, id_union, !seq_union_l, !seq_union_r.\n  unfold Execution.rfi.\n  rewrite <- !id_inter.\n  arewrite (codom_rel rfe ∩₁ Acq ⊆₁ D).\n  { unfold D.\n    rewrite WF.(wf_rfeD).\n    basic_solver 10. }\n  unionL.\n  2: by apply cert_rf_D_in_rf.\n  rewrite cert_rf_codom.\n  unfolder. ins. desf.\n  assert (x0 = x); desf.\n  eapply cert_rff; eauto.\n  apply rfi_in_cert_rf.\n  apply seq_eqv_r.\n  basic_solver.\nQed.\n\nLemma cert_rf_sb_F_Acq_in_rf :\n  cert_rf ⨾ sb ⨾ ⦗F⦘ ⨾ ⦗ Acq ⦘ ⨾ ⦗CsbI⦘ ⊆ rf ⨾ sb.\nProof.\n  arewrite (sb ⨾ ⦗F⦘ ⨾ ⦗Acq⦘ ⨾ ⦗CsbI⦘ ⊆ ⦗C⦘ ⨾ sb).\n  2 : by sin_rewrite cert_rf_C_in_rf.\n  rewrite <- !id_inter, seq_eqv_r, seq_eqv_l.\n  intros x y [SB [Fy [ACQy E0y]]].\n  splits; auto.\n  eapply dom_sb_covered; eauto.\n  exists y. apply seq_eqv_r.\n  splits; auto.\n  destruct E0y as [Cy | SBIy]; auto.\n  destruct SBIy as [z HH].\n  apply seq_eqv_r in HH.\n  destruct HH as [[EQz | SB'] Iy].\n  { subst. eapply issuedW in Iy; eauto. type_solver. }\n  eapply dom_F_sb_issued; eauto.\n  unfold is_ra.\n  basic_solver 20.\nQed.\n\nLemma cert_rf_F_Acq_in_rf :\n  cert_rf ⨾ (sb ⨾ ⦗F⦘)^? ⨾ ⦗ Acq ⦘ ⨾ ⦗ CsbI ⦘ ⊆ rf ⨾ sb^?.\nProof.\n  rewrite !crE, !seq_union_l, !seq_union_r, !seq_id_l, !seq_id_r, !seqA.\n  apply union_mori.\n  { sin_rewrite cert_rf_Acq_in_rf. basic_solver. }\n  apply cert_rf_sb_F_Acq_in_rf.\nQed.\n\nLemma nI_rf_D_CsbI_in_sb :\n  ⦗set_compl I⦘ ⨾ rf ⨾ ⦗D⦘ ⨾ ⦗CsbI⦘ ⊆ sb.\nProof.\n  unfold D.\n  relsf.\n  rewrite !id_union.\n  rewrite !seq_union_l, !seq_union_r.\n  unionL.\n  { seq_rewrite rf_covered; eauto. basic_solver. }\n  { rewrite issuedW at 2; eauto.\n    rewrite (dom_r WF.(wf_rfD)).\n    type_solver. }\n  { rewrite rfi_union_rfe.\n    rewrite !seq_union_l, !seq_union_r.\n    unionL.\n    { generalize (@sb_trans G). unfold Execution.rfi. basic_solver. }\n    arewrite (\n      rfe ⨾ ⦗dom_rel (rfi^? ⨾ ppo ⨾ ⦗I⦘)⦘ ⊆ rfe ⨾ ⦗dom_rel (ppo ⨾ ⦗I⦘)⦘\n    ).\n    { rewrite crE. relsf.\n      rewrite id_union, !seq_union_r.\n      unionL; [done|].\n      rewrite (dom_l WF.(wf_rfiD)),\n              (dom_r WF.(wf_rfeD)).\n      rewrite !seqA, dom_eqv1.\n      type_solver. }\n    arewrite (\n      rfe ⨾ ⦗dom_rel (ppo ⨾ ⦗I⦘)⦘ ⊆ ⦗I⦘ ⨾ rfe ⨾ ⦗dom_rel (ppo ⨾ ⦗I⦘)⦘\n    ).\n    { generalize (dom_rfe_ppo_issued WF TCCOH). basic_solver 20. }\n    basic_solver. }\n  { arewrite (rf ⨾ ⦗codom_rel (⦗I⦘ ⨾ rfi)⦘ ⊆ sb).\n    2: { generalize (@sb_trans G). basic_solver. }\n    unfolder; ins; desf.\n    match goal with H : rfi _ _ |- _ => destruct H as [AA BB] end.\n    eapply wf_rff in H; eauto.\n    apply H in AA. by rewrite AA. }\n  unfold CsbI.\n  rewrite !id_union. rewrite !seq_union_r.\n  unionL.\n  { rewrite seq_eqvC. seq_rewrite rf_covered; eauto. basic_solver. }\n  rewrite rfi_union_rfe. rewrite !seq_union_l, !seq_union_r.\n  unionL.\n  { unfold Execution.rfi. basic_solver. }\n  assert (∅₂ ⊆ sb) as UU by done.\n  etransitivity; eauto.\n  unfolder; ins; desf.\n  { match goal with H : I _ |- _ => eapply issuedW in H; eauto end.\n    type_solver. }\n  match goal with H : ~ I _ |- _ => apply H end.\n  eapply dom_rfe_acq_sb_issued; eauto.\n  eexists. eexists. split; eauto.\n  apply seq_eqv_l. split; [split|]; auto.\n  apply seq_eqv_r. split; eauto.\nQed.\n\nLemma non_I_cert_rf: ⦗set_compl I⦘ ⨾ cert_rf ⊆ sb.\nProof.\n  cdes COH.\n  rewrite (dom_r (cert_rfD)).\n  rewrite cert_rf_codom.\n  rewrite cert_rf_in_vf.\n  unfold vf.\n  arewrite_id (⦗E⦘).\n  relsf. rewrite !seqA. unionL.\n\n  { rewrite !crE.\n    repeat (rewrite seq_union_l, seq_id_l).\n    rewrite !seq_union_r.\n    unionL.\n    all: try (\n      try rewrite (dom_r WF.(wf_rfD));\n      try rewrite Wf_sc.(wf_scD);\n      by type_solver\n    ).\n    5-9:\n      erewrite rf_covered; eauto;\n      basic_solver.\n    all: arewrite_id (⦗R⦘); seq_rewrite seq_id_r.\n    3 : sin_rewrite rewrite_trans; [|by apply hb_trans].\n    1-3: unfold CsbI; sin_rewrite hb_in_Chb_sb; eauto.\n    1-3: rewrite !seq_union_r; seq_rewrite <- !id_inter.\n    1-3: rewrite set_interA; erewrite w_covered_issued; eauto.\n    1-3: basic_solver.\n    arewrite (sc ⨾ hb ⨾ ⦗CsbI⦘ ⊆ ⦗C⦘ ⨾ sc ⨾ hb).\n    { generalize sc_hb_CsbI_in_C. basic_solver 10. }\n    sin_rewrite hb_covered; eauto.\n    rewrite !seqA. seq_rewrite <- !id_inter.\n    rewrite set_interA; erewrite w_covered_issued; eauto.\n    basic_solver. }\n\n  arewrite_id (⦗R⦘); seq_rewrite seq_id_r.\n  arewrite (sb^? ⨾ ⦗CsbI⦘ ⊆ ⦗CsbI⦘ ⨾ sb^?).\n  { rewrite crE. relsf.\n    apply union_mori; try done.\n    generalize CsbI_sb_prcl. basic_solver. }\n  sin_rewrite nI_rf_D_CsbI_in_sb.\n  generalize sb_trans. basic_solver.\nQed.\n\nLemma cert_rf_iss_sb :\n  cert_rf ⊆ ⦗ I ⦘ ⨾ cert_rf ∪ sb ∩ same_tid.\nProof.\n  rewrite <- seq_id_l\n    with (r := cert_rf) at 1.\n  rewrite <- set_compl_union_id\n    with (s := I).\n  rewrite id_union, seq_union_l.\n  apply union_mori; try done.\n  rewrite seq_eqv_l.\n  intros x y [nI CertRF].\n  assert (sb x y) as SB.\n  { apply non_I_cert_rf. basic_solver. }\n  split; auto.\n  apply sb_tid_init in SB.\n  destruct SB as [TID | INITx]; auto.\n  exfalso. apply nI.\n  eapply init_issued; eauto.\n  split; auto.\n  apply cert_rfE in CertRF.\n  by destruct_seq CertRF as [AA BB].\nQed.\n\nLemma cert_rf_ntid_iss_sb thread (NINITT : thread <> tid_init) :\n  cert_rf ⨾ ⦗ Tid_ thread ⦘ ⊆\n    ⦗ NTid_ thread ∩₁ I ⦘ ⨾ cert_rf ∪ sb ∩ same_tid.\nProof.\n  rewrite <- seq_id_l\n    with (r := cert_rf) at 1.\n  rewrite <- tid_set_dec with (thread := thread).\n  rewrite set_unionC, id_union, !seq_union_l, !seqA.\n  apply union_mori.\n  { rewrite cert_rf_iss_sb at 1.\n    unfold same_tid.\n    basic_solver 10. }\n  apply inclusion_inter_r.\n  { apply cert_rf_tid_in_sb; auto. }\n  unfold same_tid.\n  basic_solver.\nQed.\n\nLemma dom_cert_rfe :\n  dom_rel cert_rfe ⊆₁ I.\nProof.\n  unfold cert_rfe.\n  rewrite cert_rf_iss_sb.\n  basic_solver.\nQed.\n\nEnd Properties.\n\nEnd CertRf.\n\nSection CertRfLemmas.\nVariable G  : execution.\nVariable sc : relation actid.\nVariable WF  : Wf G.\nVariable COH : imm_consistent G sc.\n\nNotation \"'E'\"  := G.(acts_set).\nNotation \"'lab'\" := (G.(lab)).\nNotation \"'rmw'\" := G.(rmw).\n\nNotation \"'Tid_' t\" := (fun x => tid x = t) (at level 1).\nNotation \"'NTid_' t\" := (fun x => tid x <> t) (at level 1).\n\nNotation \"'R'\" := (fun a => is_true (is_r lab a)).\nNotation \"'W'\" := (fun a => is_true (is_w lab a)).\nNotation \"'F'\" := (fun a => is_true (is_f lab a)).\n\nNotation \"'Acq'\" := (fun a => is_true (is_acq lab a)).\nNotation \"'Rel'\" := (fun a => is_true (is_rel lab a)).\nNotation \"'Sc'\" := (fun a => is_true (is_sc lab a)).\nNotation \"'Acq/Rel'\" := (fun a => is_true (is_ra lab a)).\n\nNotation \"'sb'\"  := (G.(sb)).\nNotation \"'ppo'\" := (G.(ppo)).\nNotation \"'sw'\"  := (G.(imm_s_hb.sw)).\nNotation \"'hb'\"  := (G.(imm_s_hb.hb)).\nNotation \"'rf'\"  := (G.(rf)).\nNotation \"'rfi'\" := (G.(rfi)).\nNotation \"'rfe'\" := (G.(rfe)).\nNotation \"'co'\"  := (G.(co)).\nNotation \"'loc'\" := (loc lab).\n\nNotation \"'Loc_' l\" := (fun x => loc x = Some l) (at level 1).\nNotation \"'W_' l\" := (W ∩₁ Loc_ l) (at level 1).\nNotation \"'R_' l\" := (R ∩₁ Loc_ l) (at level 1).\n\nNotation \"'furr'\" := (furr G sc).\n\nLemma sim_trav_step_CsbI_mon TC TC'\n      (TCOH : tc_coherent G sc TC)\n      (TRAV_STEP : sim_trav_step G sc TC TC') :\n  CsbI G TC ⊆₁ CsbI G TC'.\nProof.\n  unfold CsbI.\n  rewrite sim_trav_step_covered_le; eauto.\n  rewrite sim_trav_step_issued_le; eauto.\nQed.\n\nLemma sim_trav_step_D_mon TC TC'\n      (TCOH : tc_coherent G sc TC)\n      (TRAV_STEP : sim_trav_step G sc TC TC') :\n  D G TC ⊆₁ D G TC'.\nProof.\n  unfold D.\n  rewrite sim_trav_step_covered_le; eauto.\n  rewrite sim_trav_step_issued_le; eauto.\nQed.\n\nLemma sim_trav_step_vf_mon TC TC'\n      (TCOH : tc_coherent G sc TC)\n      (TRAV_STEP : sim_trav_step G sc TC TC') :\n  vf G sc TC ⊆ vf G sc TC'.\nProof.\n  unfold vf.\n  rewrite sim_trav_step_covered_le; eauto.\n  rewrite sim_trav_step_D_mon; eauto.\n  done.\nQed.\n\nLemma sim_trav_step_cert_rf_co TC TC'\n      (TCOH : tc_coherent G sc TC)\n      (TRAV_STEP : sim_trav_step G sc TC TC') :\n  cert_rf G sc TC ⨾ (cert_rf G sc TC')⁻¹ ⊆ co^?.\nProof.\n  intros x y [z [CertRF CertRF']].\n  red in CertRF'.\n  destruct (classic (x = y))\n    as [EQ|nEQ].\n  { basic_solver. }\n  edestruct wf_co_total\n    as [CO|CO]; eauto.\n  { unfolder. splits.\n    { apply cert_rfE in CertRF; auto.\n      generalize CertRF. basic_solver. }\n    { apply cert_rfD in CertRF; auto.\n      generalize CertRF. basic_solver. }\n    edone. }\n  { unfolder. splits.\n    { apply cert_rfE in CertRF'; auto.\n      generalize CertRF'. basic_solver. }\n    { apply cert_rfD in CertRF'; auto.\n      generalize CertRF'. basic_solver. }\n    symmetry.\n    apply cert_rfl in CertRF.\n    apply cert_rfl in CertRF'.\n    congruence. }\n  exfalso.\n  unfold cert_rf in *.\n  apply CertRF'.\n  exists x; splits; auto.\n  eapply sim_trav_step_vf_mon; eauto.\n  generalize CertRF. basic_solver.\nQed.\n\nLemma isim_trav_step_vf_ntid thread TC TC'\n      (NINITT : thread <> tid_init)\n      (TCOH : tc_coherent G sc TC)\n      (RELCOH : W ∩₁ Rel ∩₁ (issued TC) ⊆₁ covered TC)\n      (ITRAV_STEP : isim_trav_step G sc thread TC TC') :\n  vf G sc TC' ⨾ ⦗CsbI G TC ∩₁ NTid_ thread⦘ ⊆ vf G sc TC.\nProof.\n  assert (sim_trav_step G sc TC TC')\n    as TRAV_STEP.\n  { eexists; edone. }\n  assert (tc_coherent G sc TC')\n    as TCCOH'.\n  { eapply sim_trav_step_coherence; eauto. }\n  assert (W ∩₁ Rel ∩₁ issued TC' ⊆₁ covered TC')\n    as RELCOH'.\n  { eapply sim_trav_step_rel_covered; eauto. }\n  rewrite !vf_alt; eauto.\n  rewrite !seq_union_l.\n\n  rewrite !seqA.\n  arewrite\n    (sb^? ⨾ ⦗CsbI G TC ∩₁ NTid_ thread⦘ ⊆ ⦗CsbI G TC ∩₁ NTid_ thread⦘ ⨾ sb^?).\n  { rewrite !crE. relsf.\n    apply union_mori; try done.\n    rewrite seq_eqv_l, seq_eqv_r.\n    intros x y [SB [CsbIy nTIDy]].\n    unfolder; splits; auto.\n    { eapply CsbI_sb_prcl; eauto. basic_solver 10. }\n    intros TIDx.\n    apply sb_tid_init in SB.\n    destruct SB as [EQtid | INITx].\n    { congruence. }\n    apply is_init_tid in INITx.\n    congruence. }\n\n  repeat apply union_mori.\n\n  { rewrite crE\n      with (r := rf ⨾ ⦗covered TC'⦘).\n    relsf. unionL.\n    { basic_solver 20. }\n    rewrite !seqA.\n    arewrite\n      (⦗E⦘ ⨾ ⦗CsbI G TC ∩₁ NTid_ thread⦘ ⊆\n       ⦗CsbI G TC⦘ ⨾ ⦗NTid_ thread⦘ ⨾ ⦗E⦘).\n    { basic_solver. }\n    arewrite\n      (hb^? ⨾ sc^? ⨾ hb^? ⨾ ⦗CsbI G TC⦘ ⊆\n       (⦗covered TC⦘ ⨾ hb^? ⨾ sc^? ⨾ hb^? ∪ sb)^?).\n    { eapply hb_sc_hb_CsbI_alt; auto. }\n    rewrite crE. relsf. unionL.\n    { erewrite isim_trav_step_new_covered_tid;\n        eauto.\n      basic_solver 20. }\n    { basic_solver 20. }\n    arewrite\n      (sb ⨾ ⦗NTid_ thread⦘ ⊆ ⦗NTid_ thread⦘ ⨾ sb).\n    { rewrite seq_eqv_r, seq_eqv_l.\n      intros x y [SB nTIDy].\n      split; auto.\n      apply sb_tid_init in SB.\n      destruct SB as [EQtid | INITx].\n      { congruence. }\n      apply is_init_tid in INITx.\n      congruence. }\n    erewrite isim_trav_step_new_covered_tid;\n      eauto.\n    rewrite sb_in_hb.\n    basic_solver 20. }\n\n  { erewrite isim_trav_step_new_covered_tid;\n      eauto.\n    basic_solver 10. }\n\n  { seq_rewrite !seq_eqv_r.\n    intros x y [z [HH SB']].\n    destruct HH as [HH [CsbIz nTIDz]].\n    destruct HH as [RF [z' [PPO Iy']]].\n    do 2 (eexists; splits; eauto).\n    eapply isim_trav_step_new_issued_tid in Iy'; eauto.\n    destruct Iy' as [[Iy _] | [Iy' TIDy]]; auto.\n    assert (SB := PPO).\n    apply ppo_in_sb in SB; auto.\n    apply sb_tid_init in SB.\n    destruct SB as [EQtid | INITx].\n    { congruence. }\n    eapply init_w in INITx; eauto.\n    apply wf_ppoD in PPO.\n    exfalso.\n    generalize PPO.\n    type_solver. }\n\n  { arewrite\n      (rfi ⨾ ⦗CsbI G TC ∩₁ NTid_ thread⦘ ⊆ ⦗CsbI G TC ∩₁ NTid_ thread⦘ ⨾ rfi).\n    { rewrite seq_eqv_l, seq_eqv_r.\n      intros x y [RFI [CsbIy nTIDy]].\n      assert (sb x y) as SB.\n      { apply RFI. }\n      unfolder; splits; auto.\n      { eapply CsbI_sb_prcl; eauto. basic_solver 10. }\n      intros TIDx.\n      apply sb_tid_init in SB.\n      destruct SB as [EQtid | INITx].\n      { congruence. }\n      apply is_init_tid in INITx.\n      congruence. }\n    erewrite isim_trav_step_new_issued_tid;\n      eauto.\n    basic_solver 10. }\n\n  basic_solver 10.\n\nQed.\n\nLemma isim_trav_step_cert_rf_ntid thread TC TC'\n      (NINITT : thread <> tid_init)\n      (TCOH : tc_coherent G sc TC)\n      (RELCOH : W ∩₁ Rel ∩₁ (issued TC) ⊆₁ covered TC)\n      (ITRAV_STEP : isim_trav_step G sc thread TC TC') :\n  cert_rf G sc TC ⨾ ⦗NTid_ thread⦘ ⊆ cert_rf G sc TC'.\nProof.\n  assert (sim_trav_step G sc TC TC')\n    as TRAV_STEP.\n  { eexists; edone. }\n  unfold cert_rf.\n  rewrite !seq_eqv_r\n    with (dom := CsbI G TC ∩₁ R).\n  rewrite !seq_eqv_r.\n  intros x y [CertRF nTIDy].\n  destruct CertRF as [VF nCOVF].\n  destruct VF as [[VF EQloc] [CsbIy Ry]].\n  unfolder; splits; auto.\n  { eapply sim_trav_step_vf_mon; eauto. }\n  { eapply sim_trav_step_CsbI_mon; eauto. }\n  intros [z [CO VF']].\n  apply nCOVF.\n  exists z; splits; auto.\n  eapply isim_trav_step_vf_ntid; eauto.\n  basic_solver.\nQed.\n\nEnd CertRfLemmas.\n", "meta": {"author": "weakmemory", "repo": "weakestmoToImm", "sha": "7061b6279887aa5777f13b5c5ed6a10fae6740a5", "save_path": "github-repos/coq/weakmemory-weakestmoToImm", "path": "github-repos/coq/weakmemory-weakestmoToImm/weakestmoToImm-7061b6279887aa5777f13b5c5ed6a10fae6740a5/src/compilation/CertRf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21002921340285197}}
{"text": "From Coq Require Import FSets.FMapPositive.\nFrom Velus Require Import Common.\nFrom Velus Require Import Operators.\nFrom Velus Require Import Clocks.\nFrom Velus Require Import CoreExpr.CESyntax.\n\nFrom Coq Require Import List.\nFrom Coq Require Import Morphisms.\nFrom Coq Require Import Permutation.\n\n(** * Well clocked expressions *)\n\nModule Type CECLOCKING\n       (Import Ids  : IDS)\n       (Import Op   : OPERATORS)\n       (Import Syn  : CESYNTAX Op).\n\n  Inductive SameVar : option ident -> exp -> Prop :=\n  | SVNone: forall e,\n      SameVar None e\n  | SVSome: forall x ty,\n      SameVar (Some x) (Evar x ty).\n\n  Section WellClocked.\n\n    Variable vars : list (ident * clock).\n\n    Inductive wc_exp : exp -> clock -> Prop :=\n    | Cconst:\n        forall c,\n          wc_exp (Econst c) Cbase\n    | Cvar:\n        forall x ck ty,\n          In (x, ck) vars ->\n          wc_exp (Evar x ty) ck\n    | Cwhen:\n        forall e x b ck,\n          wc_exp e ck ->\n          In (x, ck) vars ->\n          wc_exp (Ewhen e x b) (Con ck x b)\n    | Cunop:\n        forall op e ck ty,\n          wc_exp e ck ->\n          wc_exp (Eunop op e ty) ck\n    | Cbinop:\n        forall op e1 e2 ck ty,\n          wc_exp e1 ck ->\n          wc_exp e2 ck ->\n          wc_exp (Ebinop op e1 e2 ty) ck.\n\n    Inductive wc_cexp : cexp -> clock -> Prop :=\n    | Cmerge:\n        forall x t f ck,\n          In (x, ck) vars ->\n          wc_cexp t (Con ck x true) ->\n          wc_cexp f (Con ck x false) ->\n          wc_cexp (Emerge x t f) ck\n    | Cite:\n        forall b t f ck,\n          wc_exp b ck ->\n          wc_cexp t ck ->\n          wc_cexp f ck ->\n          wc_cexp (Eite b t f) ck\n    | Cexp:\n        forall e ck,\n          wc_exp e ck ->\n          wc_cexp (Eexp e) ck.\n\n  End WellClocked.\n\n  (** ** Basic properties of clocking *)\n\n  Lemma wc_clock_exp:\n    forall vars le ck,\n      wc_env vars ->\n      wc_exp vars le ck ->\n      wc_clock vars ck.\n  Proof.\n    induction le as [| |le IH | |] (* using exp_ind2 *).\n    - inversion_clear 2; now constructor.\n    - intros ck Hwc; inversion_clear 1 as [|? ? ? Hcv| | |].\n      apply wc_env_var with (1:=Hwc) (2:=Hcv).\n    - intros ck Hwc.\n      inversion_clear 1 as [| |? ? ? ck' Hle Hcv | |].\n      constructor; [now apply IH with (1:=Hwc) (2:=Hle)|assumption].\n    - intros ck Hwc; inversion_clear 1; auto.\n    - intros ck Hwc; inversion_clear 1; auto.\n  Qed.\n\n  Lemma wc_clock_cexp:\n    forall vars ce ck,\n      wc_env vars ->\n      wc_cexp vars ce ck ->\n      wc_clock vars ck.\n  Proof.\n    induction ce as [i ce1 IH1 ce2 IH2| |].\n    - intros ck Hwc.\n      inversion_clear 1 as [? ? ? ? Hcv Hct Hcf| |].\n      apply IH1 with (1:=Hwc) in Hct.\n      inversion_clear Hct; assumption.\n    - intros ck Hwc; inversion_clear 1 as [|? ? ? ? Hl H1 H2|].\n      now apply IHce1.\n    - intros ck Hwc; inversion_clear 1 as [| |? ? Hck].\n      apply wc_clock_exp with (1:=Hwc) (2:=Hck).\n  Qed.\n\n  Hint Constructors wc_clock wc_exp wc_cexp : nlclocking.\n  Hint Resolve Forall_nil : nlclocking.\n\n  Instance wc_exp_Proper:\n    Proper (@Permutation (ident * clock) ==> @eq exp ==> @eq clock ==> iff)\n           wc_exp.\n  Proof.\n    intros env' env Henv e' e He ck' ck Hck.\n    rewrite He, Hck; clear He Hck e' ck'.\n    revert ck.\n    induction e;\n      split; auto with nlclocking;\n        inversion_clear 1;\n        (rewrite Henv in * || rewrite <-Henv in * || idtac);\n        try edestruct IHe;\n        try edestruct IHe1, IHe2;\n        auto with nlclocking.\n  Qed.\n\n  Instance wc_cexp_Proper:\n    Proper (@Permutation (ident * clock) ==> @eq cexp ==> @eq clock ==> iff)\n           wc_cexp.\n  Proof.\n    intros env' env Henv e' e He ck' ck Hck.\n    rewrite He, Hck; clear He Hck e' ck'.\n    revert ck.\n    induction e;\n      split; inversion_clear 1;\n        (rewrite Henv in * || rewrite <-Henv in *);\n         constructor; auto;\n         now (rewrite <-IHe1 || rewrite IHe1\n              || rewrite <-IHe2 || rewrite IHe2).\n  Qed.\n\nEnd CECLOCKING.\n\nModule CEClockingFun\n       (Import Ids  : IDS)\n       (Import Op   : OPERATORS)\n       (Import Syn  : CESYNTAX Op)\n  <: CECLOCKING Ids Op Syn.\n  Include CECLOCKING Ids Op Syn.\nEnd CEClockingFun.\n", "meta": {"author": "INRIA", "repo": "velus", "sha": "116a88bc71f3608ff43ed967895743e8b9a340e0", "save_path": "github-repos/coq/INRIA-velus", "path": "github-repos/coq/INRIA-velus/velus-116a88bc71f3608ff43ed967895743e8b9a340e0/src/CoreExpr/CEClocking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.21002921340285194}}
{"text": "Require Import CSet Le Arith.Compare_dec.\n\nRequire Import Plus Util Map CMap Status Take Subset1 ListMax.\nRequire Import Val Var Envs IL Annotation Liveness.Liveness MoreList SetOperations.\nRequire Import AnnotationLattice AnnP.\nRequire Import Coherence Coherence.Allocation RenamedApart AllocationAlgo.\nRequire Import RenamedApart_Liveness LabelsDefined Restrict InfiniteSubset InfinitePartition MapSep.\nRequire Import RenameApart_Partition Filter AllocationAlgoSep StableFresh.\n\nSet Implicit Arguments.\n\nRequire Import AllocationAlgoCorrect AnnP BoundedIn VarP SmallestK.\n\nLemma mapAnn_renamedApart al ans s (ϱ ϱ': var -> var)\n      (P1:Proper (_eq ==> _eq) ϱ) (P2:Proper (_eq ==> _eq) ϱ')\n      (AR:ann_R Subset1 al ans)\n      (RA:renamedApart s ans)\n      (AGR:agree_on _eq (fst (getAnn ans) ∪ snd (getAnn ans)) ϱ ϱ')\n:  ann_R SetInterface.Equal (mapAnn (lookup_set ϱ) al)\n         (mapAnn (lookup_set ϱ') al).\nProof.\n  general induction RA; invt @ann_R; pe_rewrite; simpl in *; set_simpl.\n  - econstructor; eauto.\n    + eapply lookup_set_agree; eauto.\n      simpl. eapply agree_on_incl; eauto. eauto with cset.\n    + eapply IHRA; eauto using agree_on_incl with cset.\n  - econstructor; eauto.\n    + eapply lookup_set_agree; eauto.\n      simpl. eapply agree_on_incl; eauto. eauto with cset.\n    + eauto using agree_on_incl with cset.\n    + eauto using agree_on_incl with cset.\n  - econstructor; eauto.\n    + eapply lookup_set_agree; eauto.\n      simpl. eapply agree_on_incl; eauto.\n  - econstructor; eauto.\n    + eapply lookup_set_agree; eauto.\n      simpl. eapply agree_on_incl; eauto.\n  - econstructor; eauto.\n    + eapply lookup_set_agree; eauto.\n      simpl. eapply agree_on_incl; eauto. rewrite <- H9. clear; cset_tac.\n    + eauto with len.\n    + intros; inv_get.\n      eapply H1; eauto.\n      simpl. eapply agree_on_incl; eauto.\n      eapply ans_incl_D_union; eauto.\n    + eapply IHRA; eauto.\n      simpl. eapply agree_on_incl; eauto.\n      clear; cset_tac.\nQed.\n\nLemma regAssign_assignment_small k p o (ϱ:Map [var,var]) ZL Lv s alv ϱ' ra\n      (LS:live_sound Functional ZL Lv s alv)\n      (inj:injective_on (getAnn alv) (findt ϱ default_var))\n      (SEP:sep var p (getAnn alv) (findt ϱ default_var))\n      (RA:renamedApart s ra)\n      (INCL:ann_R Subset1 alv ra)\n      (allocOK:regAssign p o s alv ϱ = Success ϱ')\n      (BND:ann_P (part_size_bounded (part_1 p) k) alv)\n      (up:For_all (part_vars_bounded (part_1 p) k) (lookup_set (findt ϱ default_var) (getAnn alv)))\n  : ann_P (For_all (part_vars_bounded (part_1 p) k)) (mapAnn (lookup_set (findt ϱ' default_var)) alv).\nProof.\n  general induction LS; invt ann_P; invt renamedApart; invt @ann_R; simpl in *.\n  - econstructor; eauto.\n    + exploit regAssign_renamedApart_agree; eauto using live_sound.\n      pe_rewrite.\n      rewrite <- map_update_update_agree in H2.\n      eapply agree_on_update_inv in H2.\n      rewrite <- lookup_set_agree; swap 1 4.\n      simpl. eapply agree_on_incl; eauto. revert H10 H7; clear; cset_tac.\n      eauto. eauto. eauto.\n    + eapply IHLS; eauto.\n      * eapply injective_on_agree; [|eapply map_update_update_agree].\n        eapply injective_on_update_fresh; eauto using injective_on_incl.\n        eapply least_fresh_part_fresh.\n      * rewrite <- map_update_update_agree.\n        eapply sep_update_part.\n        eauto using sep_incl.\n      * hnf; intros.\n        rewrite <- lookup_set_agree in H2; swap 1 4.\n        eapply map_update_update_agree. eauto. eauto.\n        assert (EQal:getAnn al [=] getAnn al \\ singleton x ∪ singleton x). {\n          revert H1. clear.\n          cset_tac.\n        }\n        eapply lookup_set_morphism_eq in H2; [|rewrite EQal; reflexivity].\n        rewrite lookup_set_union in H2. eapply union_iff in H2; destruct H2.\n        -- rewrite lookup_set_agree in H2; swap 1 4.\n           eapply agree_on_update_dead. clear. cset_tac. reflexivity. eauto. eauto.\n           eapply up. rewrite <- H0. eauto.\n        -- rewrite lookup_set_singleton' in H2; eauto. eapply In_single in H2.\n           invc H2. lud; [|isabsurd].\n           hnf; intros. eapply ann_P_get in H5.\n           eapply least_fresh_part_small1. eauto.\n           rewrite <- sep_filter_map_comm.\n           rewrite <- H5. rewrite cardinal_map.\n           eapply subset_cardinal_lt with (x0 := x).\n           rewrite filter_difference. eauto with cset. eauto.\n           eapply zfilter_3; eauto.\n           eapply least_fresh_part_p1 in H2. eauto.\n           rewrite filter_incl. clear. cset_tac.\n           eauto. eauto. eauto. eapply sep_incl; eauto.\n        -- eauto.\n  - monadS_inv allocOK.\n    exploit regAssign_renamedApart_agree; eauto using live_sound. pe_rewrite.\n    exploit regAssign_renamedApart_agree; try eapply EQ; eauto using live_sound. pe_rewrite.\n    exploit regAssign_renamedApart_agree'; eauto. pe_rewrite.\n    econstructor; eauto.\n    + rewrite <- lookup_set_agree; eauto.\n      simpl.\n      etransitivity; eauto using agree_on_incl.\n    + exploit IHLS1; eauto.\n      * eauto using injective_on_incl; eauto.\n      * rewrite H0. eauto.\n      * eapply ann_P_morph with (R:=SetInterface.Equal); eauto.\n        intros. rewrite <- H17. eauto.\n        eapply mapAnn_renamedApart; eauto.\n        eapply agree_on_incl; eauto.\n        pe_rewrite. rewrite <- disj_eq_minus; try reflexivity.\n        eapply disj_union_left. symmetry. eapply renamedApart_disj in H12. pe_rewrite. eauto.\n        symmetry; eauto.\n    + exploit IHLS2; try eapply EQ0; eauto.\n      * eapply injective_on_agree; swap 1 2.\n        simpl.\n        eapply agree_on_incl. eapply H3. etransitivity; eauto.\n        eauto using injective_on_incl; eauto.\n      * rewrite H1. eapply sep_agree. eauto using agree_on_incl.\n        eauto.\n      * rewrite <- lookup_set_agree; swap 1 4.\n        simpl. eapply agree_on_incl; eauto. etransitivity; eauto.\n        eauto. eauto. rewrite H1. eauto.\n  - econstructor.\n    eauto.\n  - econstructor; eauto.\n  - monadS_inv allocOK.\n    exploit regAssign_renamedApart_agree; eauto using live_sound. pe_rewrite.\n    exploit regAssign_renamedApart_agreeF'; eauto using live_sound.\n    intros. eapply regAssign_renamedApart_agree'; eauto using live_sound.\n    reflexivity.\n    econstructor; eauto.\n    + rewrite <- lookup_set_agree; eauto.\n      simpl.\n      etransitivity; eauto using agree_on_incl.\n      eapply agree_on_incl; eauto.\n      rewrite <- disj_eq_minus; try reflexivity.\n      rewrite H19.  eapply disj_D_defVars; eauto.\n    + intros. inv_get.\n      edestruct regAssignF_get; eauto.\n      * intros. exploit disj_D_defVars; eauto.\n        eapply renamedApart_disj in H13. pe_rewrite.\n        eapply defVars_disj_D; eauto. eapply disj_union_right; eauto.\n      * dcr. instantiate (1:=fst (getAnn x1) ∪ snd (getAnn x1)) in H27.\n        rewrite <- disj_eq_minus in H27; try reflexivity; swap 1 2.\n        {\n          edestruct H11; dcr; eauto.\n          rewrite H20. setoid_rewrite union_comm at 2. rewrite union_assoc.\n          eapply disj_union_left; symmetry.\n          eapply disj_D_defVars_take; eauto.\n          exploit defVars_take_disj; eauto.\n        }\n        rewrite <- map_update_list_update_agree' in H27; eauto with len.\n        assert (INCLx0:getAnn x0 ⊆ fst (getAnn x1) ∪ snd (getAnn x1)). {\n          exploit H22; eauto.\n          eapply ann_R_get in H20. rewrite H20. eauto with cset.\n        }\n        assert (DECOMP:getAnn x0 [=] getAnn x0 \\ of_list (fst x2) ∪ of_list (fst x2)). {\n          edestruct H2; eauto; dcr.\n          revert H20; clear; cset_tac.\n        }\n        assert (Inclx2:getAnn x0 \\ of_list (fst x2) ⊆ lv). {\n          edestruct H2; eauto; dcr.\n        }\n        exploit H1; eauto.\n        -- eapply injective_on_agree; simpl; eauto using agree_on_incl.\n           rewrite DECOMP at 1.\n           eapply injective_on_fresh_list. eauto.\n           eapply injective_on_incl; eauto. eauto with len.\n           eapply fresh_list_stable_spec.\n           eapply fresh_list_stable_nodup.\n        -- eapply sep_agree; eauto.\n           eapply agree_on_incl; eauto.\n           rewrite DECOMP at 1.\n           eapply sep_update_list; eauto.\n           edestruct H2; eauto.\n           eapply sep_incl; eauto.\n           rewrite <- Inclx2. clear. cset_tac.\n        -- rewrite <- lookup_set_agree; swap 1 4; eauto using agree_on_incl.\n           rewrite DECOMP at 2.\n           rewrite lookup_set_union; eauto.\n           rewrite lookup_set_update_disj; eauto; swap 1 2.\n           clear. cset_tac.\n           rewrite For_all_union; split.\n           ++ rewrite Inclx2. eauto.\n           ++ edestruct H2; eauto; dcr.\n             rewrite update_with_list_lookup_list; eauto with len.\n             eapply fresh_list_stable_small; eauto.\n             exploit H8 as BNDk; eauto. eapply ann_P_get in BNDk.\n             hnf in BNDk.\n             rewrite DECOMP in BNDk.\n             rewrite filter_union in BNDk; eauto.\n             rewrite union_cardinal in BNDk; eauto; swap 1 2.\n             rewrite !filter_incl; eauto.\n             rewrite <- cardinal_map with (f:=findt ϱ default_var) in BNDk; eauto.\n             rewrite <- sep_filter_map_comm; eauto.\n        -- eapply ann_P_morph with (R:=SetInterface.Equal); eauto.\n           intros. rewrite <- H26. eauto.\n           eapply mapAnn_renamedApart; eauto.\n           eapply regAssign_renamedApart_agreeF' with (ans:=drop (S n ) ans) in H24;\n             eauto; try reflexivity; intros; inv_get; eauto with len.\n           ++ etransitivity. eapply agree_on_incl; eauto.\n             rewrite <- disj_eq_minus; swap 1 3.\n             eapply disj_fst_snd_ra; eauto. reflexivity. reflexivity.\n             eapply agree_on_incl.\n             eapply regAssign_renamedApart_agree'; try eapply EQ0; eauto.\n             pe_rewrite.\n             rewrite <- disj_eq_minus; swap 1 3; try reflexivity.\n             eapply disj_fst_snd_Dt; eauto.\n           ++ eapply regAssign_renamedApart_agree' in H30; eauto.\n    + exploit IHLS; try eapply EQ0; eauto.\n      * eapply injective_on_agree; swap 1 2.\n        change _eq with (@eq var).\n        eapply agree_on_incl. eapply H5. etransitivity; eauto.\n        rewrite <- disj_eq_minus; try reflexivity.\n        rewrite H19.  eapply disj_D_defVars; eauto.\n        eauto using injective_on_incl; eauto.\n      * eapply sep_incl; eauto.\n        etransitivity; eauto.\n        rewrite <- disj_eq_minus; try reflexivity.\n        rewrite H19.  eapply disj_D_defVars; eauto.\n      * rewrite <- lookup_set_agree; swap 1 4.\n        eapply agree_on_incl; eauto.\n        etransitivity; eauto.\n        rewrite <- disj_eq_minus; try reflexivity.\n        rewrite H19.  eapply disj_D_defVars; eauto. eauto. eauto.\n        rewrite H3. eauto.\nQed.\n\nLemma regAssign_assignment_small_I k p o (ϱ:Map [var,var]) ZL Lv s alv ϱ' ra\n      (LS:live_sound Imperative ZL Lv s alv)\n      (inj:injective_on (getAnn alv) (findt ϱ default_var))\n      (SEP:sep var p (getAnn alv) (findt ϱ default_var))\n      (RA:renamedApart s ra)\n      (INCL:ann_R Subset1 alv ra)\n      (allocOK:regAssign p o s alv ϱ = Success ϱ')\n      (BND:ann_P (part_size_bounded (part_1 p) k) alv)\n      (up:For_all (part_vars_bounded (part_1 p) k) (lookup_set (findt ϱ default_var) (getAnn alv)))\n      (BOUND:bounded (Some ⊝ Lv \\\\ ZL) (fst (getAnn ra)))\n      (NUC:noUnreachableCode (isCalled true) s)\n  : ann_P (For_all (part_vars_bounded (part_1 p) k)) (mapAnn (lookup_set (findt ϱ' default_var)) alv).\nProof.\n  intros.\n  eapply renamedApart_live_imperative_is_functional in LS; eauto using bounded_disjoint, renamedApart_disj, meet1_Subset1, live_sound_annotation, renamedApart_annotation.\n  eapply live_sound_overapproximation_F in LS.\n  exploit regAssign_assignment_small; eauto using locally_inj_subset, meet1_Subset, live_sound_annotation, renamedApart_annotation.\nQed.\n\nLemma ann_P_live_var_P i ZL Lv p k s lv\n  : ann_P (For_all (part_vars_bounded p k)) lv\n    -> live_sound i ZL Lv s lv\n    -> var_P (part_vars_bounded p k) s.\nProof.\n  intros ANN LS.\n  general induction LS; invt ann_P; eauto using var_P, ann_P_get.\n  - econstructor; eauto.\n    + eapply ann_P_get in H5. eauto.\n    + rewrite Exp.freeVars_live; eauto.\n  - econstructor; eauto.\n    rewrite Ops.freeVars_live; eauto.\n  - econstructor; eauto.\n    rewrite Ops.freeVars_live_list; eauto.\n  - econstructor; eauto.\n    rewrite Ops.freeVars_live; eauto.\n  - econstructor; intros; inv_get; eauto.\n    edestruct H2; dcr; eauto.\n    exploit H8; eauto. eapply ann_P_get in H10.\n    rewrite H6; eauto.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Coherence/AllocationAlgoBound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6757645879592642, "lm_q2_score": 0.3106943959796865, "lm_q1q2_score": 0.20995627048046533}}
{"text": "(* PREAMBLE *)\n\nFrom compcert.cfrontend     Require Csyntax.\nFrom trancert.properties    Require State Env.\nFrom trancert.lib           Require All.\n\nImport Csem properties.State properties.Env List Memory.Mem BinNums Coqlib lib.All Maps PTree ZArith.\n\nOpen Scope positive.\n\nSection Norepet.\n  Let alloc_variables_blocks_norepet_aux:\n    forall (ge : genv) ls e1  m1 e2 m2,\n      list_norepet (List.map fst ls) ->\n      (forall i b, get i e1 = Some b -> ~ In i (List.map fst ls)) ->\n      list_norepet (List.map (fst ∘ fst) (blocks_of_env ge e1)) ->\n      (forall b x t, get x e1 = Some (b,t) -> b < nextblock m1) ->\n      alloc_variables ge e1 m1 ls e2 m2 ->\n      list_norepet (List.map (fst ∘ fst) (blocks_of_env ge e2))\n  .\n  Proof.\n    unfold blocks_of_env,block_of_binding.\n    move => ge ls e1 m1 e2 m2.\n    move => Hnorepet Hcond1 Hcond2 Hmem Halloc.\n    rewrite List.map_map in Hcond2; rewrite List.map_map.\n    rewrite <-(map_ext (fun x : AST.ident * (Values.block * Ctypes.type) => fst (snd x))) in *; try by intros (? & (? & ?)).\n    generalize dependent e1.\n    generalize dependent e2.\n    generalize dependent m1.\n    generalize dependent m2.\n    generalize dependent ge.\n    induction ls; simpl in *; intros; inv Halloc; auto.\n    exploit alloc_result; eauto. intro; subst.\n    exploit nextblock_alloc; eauto. intro Hnext.\n    inv Hnorepet.\n    eapply IHls in H6; eauto; clear IHls.\n    - intros i b H. destruct (peq i id); first by subst.\n      rewrite gso in H; auto.\n      apply Hcond1 in H.\n      simpl in *.\n      contradict H. auto.\n    - intros b x t0 H.\n      rewrite Hnext.\n      rewrite gsspec in H.\n      destruct (peq _ _).\n      + inv H. apply Pos.lt_succ_diag_r.\n      + apply Hmem in H. eapply Pos.lt_trans; eauto.\n        apply Pos.lt_succ_diag_r.\n    - rewrite map_elem .\n      rewrite map_elem in Hcond2.\n      apply elements_list_norepet.\n      pose proof list_norepet_elements _ Hcond2 as H''.\n      move => x y v Hget1 Hget2.\n      rewrite gmap gsspec in Hget1.\n      rewrite gmap gsspec in Hget2.\n      destruct (peq x _), (peq y _); subst; auto; simpl in *; try autoinj.\n      exfalso.\n      + destruct (e1 ! y) eqn: Hget; try discriminate.\n        destruct p.\n        eapply Hmem in Hget.\n        simpl in *. autoinj. by apply Pos.lt_irrefl in Hget.\n      + destruct (e1 ! x) eqn: Hget; try discriminate.\n        destruct p.\n        eapply Hmem in Hget.\n        simpl in *. autoinj. by apply Pos.lt_irrefl in Hget.\n      + eapply H''; rewrite gmap; by eauto.\n  Qed.\n\n  Theorem alloc_variables_blocks_norepet:\n    forall (ge:genv) ls m1 e2 m2,\n      list_norepet (List.map fst ls) ->\n      alloc_variables ge empty_env m1 ls e2 m2 ->\n      list_norepet (List.map (fst ∘ fst) (blocks_of_env ge e2)).\n  Proof.\n    intros ge ls m1 e2 m2 H H0.\n    eapply alloc_variables_blocks_norepet_aux; eauto.\n    - intros. rewrite gempty in H1. discriminate.\n    - constructor.\n    - intros. rewrite gempty in H1. discriminate.\n  Qed.\n\nEnd Norepet.\n\n(** Local variables are allocated in valid blocks. *)\nTheorem alloc_variables_inside:\n  forall e1 m1 vars e2 m2 ge,\n    alloc_variables ge e1 m1 vars e2 m2 ->\n    env_inside m1 e1 -> env_inside m2 e2.\nProof.\n  unfold env_inside, valid_block.\n  intros e1 m1 vars e2 m2 ge H.\n  induction H; eauto.\n  intros Hpre id0 b t0 Hget.\n  eapply IHalloc_variables.\n  - move => ? ? ?. move: gsspec -> .\n    exploit alloc_result; eauto 1 => ->.\n    erewrite (nextblock_alloc m _ _ m1); last by eassumption.\n    destruct (peq _ _).\n    + intros; autoinj.\n      rewrite Pplus_one_succ_r. by apply Pos.lt_add_r.\n    + intros.\n      eapply (Pos.lt_trans _ (nextblock m)).\n      eapply Hpre; eauto.\n      rewrite Pplus_one_succ_r. apply Pos.lt_add_r.\n  - eassumption.\nQed.\n\n(** Allocating new variables in an existing local environment preserves its\ncontents. *)\n\nTheorem alloc_variables_preserves:\n  forall id ge e1 m1 vs e2 m2,\n    (forall ty, ~ In (id, ty) vs) ->\n    alloc_variables ge e1 m1 vs e2 m2 -> \n    get id e2 = get id e1.\nProof.\n  intros until m2.\n  induction 2 =>//=.\n  simpl in *.\n  rewrite gso in IHalloc_variables.\n  - by contradict H; subst; eauto.\n  - eapply IHalloc_variables.\n    intros ty0 H''. eapply (H ty0). by right.\nQed.\n\n\n(** Allocating a list of variables [ls] produces an environment that contains\nthe variables from [ls]. *)\n\nTheorem alloc_variables_get :\n  forall (ge: genv) e1 m1 (ls : list (AST.ident * Ctypes.type))  e2 m2 ty id,\n    list_norepet (List.map fst ls) ->\n    e1 ! id = None ->\n    alloc_variables ge e1 m1 ls e2 m2 ->\n    In (id, ty) ls ->\n    exists b, e2 ! id = Some (b,ty).\nProof.\n  move=>ge e1 m1 ls. move: ls ge e1 m1.\n  elim; first by inversion 2.\n  intros a l IH ge e1 m1 e2 m2 ty id Hnorepet Hget Halloc.\n  inv Halloc.\n  inv Hnorepet.\n  move => [Hin|Hin].\n  - inv Hin.\n    erewrite alloc_variables_preserves; eauto.\n    + by rewrite gss; eauto.\n    + move => ty0. contradict H1.\n      replace id with (fst (id, ty0)); by [eapply (in_map fst)|done].\n  - eapply IH in H6; eauto.\n    destruct (peq id id0).\n    + subst. contradiction H1.\n      replace id0 with (fst (id0, ty)); by [eapply (in_map fst)|done].\n    + by rewrite gso.\nQed.\n\n(** Allocating new variables in an existing local environment preserves its contents. *)\nTheorem alloc_variables_set_commute:\n  forall ge ls e1 m1  e2 m2 i b ty,\n    (forall t, ~In (i, t) ls) ->\n    alloc_variables ge e1 m1 ls e2 m2 ->\n    alloc_variables ge (set i (b,ty) e1) m1 ls (set i (b,ty) e2) m2.\nProof.\n  induction ls.\n  - by inversion 2; constructor.\n  - intros until ty.\n    inversion 2; subst. \n    econstructor; eauto 1.\n    have Hi: (i <> id) by (contradict H; subst; simpl; by eauto).\n    rewrite set_set_commute; auto.\n    eapply IHls; eauto.\n    intros t0 Hin.\n    eapply H; simpl; eauto.\nQed.\n\n\n(** If the environment contained no variable [i] and neither did the list [ls]\n    then allocating [ls] will preserve the absence of [i]. *)\n\nTheorem alloc_variables_none_preserves:\n  forall i ls e1 e2 ge m1 m2,\n    get i e1 = None ->\n    alloc_variables ge e1 m1 ls e2 m2 ->\n    (forall ty, ~In (i, ty) ls) ->\n    get i e2 = None.\nProof.\n  induction ls; inversion 2; subst =>//=.\n  intros.\n  inv H0.\n  eapply IHls; try eapply H8.\n  - rewrite gsspec.\n    destruct (peq _ _) =>//=.\n    + by subst; contradiction (H1 ty); auto.\n  - intros ty0 Hnotin.\n      by contradiction (H1 ty0); auto.\nQed.\n\n(** After allocation of a list of unique variables the resulting environment\nwill contain them. *)\n\nTheorem alloc_variables_spec:\n  forall hs id ty ts e1 m1 e2 m2 ge,\n    list_norepet (Csyntax.var_names (hs ++ (id,ty) :: ts)) ->\n    alloc_variables ge e1 m1 (hs ++ (id,ty) :: ts) e2 m2 ->\n    exists b, get id e2 = Some (b, ty).\nProof.\n  elim.\n  - move => id ty ts e1 m1 e2 m2 ge.\n    do 2 inversion 1. subst.\n    simpl in *.\n    inv H.\n    erewrite alloc_variables_preserves; eauto.\n    + by rewrite gss; eauto.\n    + move => ty0.\n      contradict H5.\n        by apply (in_map fst) in H5.\n  - move => a l H id ty ts e1 m1 e2 m2 ge.\n    do 2 inversion 1. subst.\n      by eapply H in H13.\nQed.\n\n(** Any other freeable environment will reman freeable after allocating local\nvariables. *)\n\nTheorem alloc_variables_freeable_any:\n  forall ge e e1 m1 ls e2 m2,\n    alloc_variables ge e1 m1 ls e2 m2 ->\n    env_freeable ge m1 e  ->\n    env_freeable ge m2 e .\nProof.\n  intros ge e e1 m1 ls e2 m2.\n  induction 1 => //= => Hfreeable.\n  eapply IHalloc_variables.\n  intros i b t0 H2 delta Hdelta.\n  eapply perm_alloc_1; eauto.\n  eapply Hfreeable; eauto.\nQed.\n\n(** Allocating variables produces a memory where variables can be freed (and preserves this property). *)\n\nTheorem alloc_variables_freeable_after:\n  forall ge e1 m1 ls e2 m2,\n    alloc_variables ge e1 m1 ls e2 m2 ->\n    env_freeable ge m1 e1  ->\n    env_freeable ge m2 e2 .\nProof.\n  move => ge e1 m1 ls e2 m2.\n  induction 1 =>//.\n  move => Hfreeable H1.\n  eapply IHalloc_variables.\n  intros i b t0 Hget delta Hdelta.\n  rewrite gsspec in Hget.\n  destruct (peq _ _).\n  - autoinj. eapply perm_alloc_2; eauto.\n  - eapply perm_alloc_1; eauto.\n      by eapply Hfreeable; eauto.\nQed.\n\n(** The maximal block index is not decreasing when variables are being\nallocated. *)\n\nTheorem alloc_variables_nextblock_le:\n  forall (ge:Csem.genv) ls e1 m1 e2 m2,\n    alloc_variables ge e1 m1 ls e2 m2 ->\n    Ple (nextblock m1) (nextblock m2) .\nProof.\n  induction ls.\n    by inversion 1; apply Ple_refl.\n    inversion 1; subst.\n    eapply IHls in H7.\n    exploit alloc_result; eauto.\n    exploit nextblock_alloc; eauto.\n    intros; subst.\n    rewrite H0 in H7.\n    eapply Ple_trans; eauto.\n    eapply Ple_succ.\nQed.\n\n\n(** Variables allocated in [m1] are placed after the last block of [m1]. *)\nTheorem alloc_variables_block_range:\n  forall (ge:Csem.genv) ls e1 m1 e2 m2 i b t,\n    alloc_variables ge e1 m1 ls e2 m2 ->\n    get i e2 = Some (b,t) ->\n    get i e1 = Some (b,t) \\/ b >= nextblock m1.\nProof.\n  induction ls; inversion 1; subst; first by auto.\n  intro Hget.\n  exploit alloc_result; eauto.\n  exploit nextblock_alloc; eauto.\n  intros. subst.\n  eapply IHls in H7; eauto.\n  rewrite gsspec in H7.\n  rewrite H0 in H7.\n  destruct H7.\n  - destruct (peq _ _); auto; autoinj.\n      by right; apply Pos.le_ge; apply Ple_refl.\n  - right.\n    apply Pos.le_ge.\n    eapply Ple_trans; eauto.\n    apply Ple_succ.\n      by apply Pos.ge_le.\nQed.\n\n\nLemma alloc_variables_nextblocks_len:\n  forall ls (ge:genv) e1 m1 e2 m2,\n    alloc_variables ge e1 m1 ls e2 m2 ->\n    ls <> [] ->\n    nextblock m2 = nextblock m1 + Pos.of_nat (length ls).\nProof.\n  case. congruence.\n  move => a ls. move: ls a. elim.\n  - move => a ge e1 m1 e2 m2 H _. inv H. inv H7.\n    exploit nextblock_alloc; eauto. simpl.\n      by move => -> ; apply Pplus_one_succ_r.\n  -\n    move => [x y] l H a0 ge e1 m1 e2 m2 H0 _. inv H0.\n    eapply H in H8; last by discriminate.\n    exploit nextblock_alloc; eauto. simpl.\n    rewrite H8 => ->.\n    simpl.\n    rewrite ! Pplus_one_succ_r.\n    rewrite - Pos.add_assoc.\n    apply Pos.add_cancel_l.\n    apply Pos.add_comm.\nQed.\n\n\nTheorem alloc_variables_app:\n  forall xs ge e1 m1 ys e2 m2,\n    Csem.alloc_variables ge e1 m1 (xs ++ ys) e2 m2 ->\n    exists e' m',\n      Csem.alloc_variables ge e1 m1 xs e' m' /\\ Csem.alloc_variables ge e' m' ys e2 m2 .\nProof.\n  induction xs.\n  {\n    intros.\n    simpl in *.\n    exists e1. exists m1.\n    split; auto.\n    constructor.\n  }\n  {\n    intros.\n    simpl in *.\n    inv H.\n    eapply IHxs in H7.\n    destruct H7 as (e' & m' & Halloc & Hvars).\n    eexists.\n    eexists.\n    split; eauto.\n    econstructor; eassumption.\n  }\nQed.\n\n\n(** CompCert does not expose the internals of memory interface operations and it\nalso does not define enough properties to reason about allocations on the low\nlevel. These two lemmas provide information about how the allocated memory is\nconstructed. *)\n\nTheorem alloc_mem_contents:\n  forall m m' lo hi nb ,\n    alloc m lo hi = (m', nb) ->\n    mem_contents m' = Maps.PMap.set (nextblock m) (Maps.ZMap.init Memdata.Undef) (mem_contents m).\nProof.\n  intros m m' lo hi nb H.\n  change alloc with ( \nfun (m : Memory.mem) (lo hi : Z) =>\n({|\n mem_contents := Maps.PMap.set (nextblock m) (Maps.ZMap.init Memdata.Undef) (mem_contents m);\n mem_access := Maps.PMap.set (nextblock m)\n                 (fun (ofs : Z) (_ : perm_kind) =>\n                  if zle lo ofs && zlt ofs hi is true then Some Freeable else None) \n                 (mem_access m);\n nextblock := Pos.succ (nextblock m);\n access_max := (fun (m0 : Memory.mem) (lo0 hi0 : Z) (b : positive) (ofs : Z) =>\n                Memory.Mem.alloc_obligation_1 m0 lo0 hi0 b ofs) m lo hi;\n nextblock_noaccess := (fun (m0 : Memory.mem) (lo0 hi0 : Z) (b : positive) \n                          (ofs : Z) (k : perm_kind) (H : ~ Plt b (Pos.succ (nextblock m0))) =>\n                        Memory.Mem.alloc_obligation_2 m0 lo0 hi0 b ofs k H) m lo hi;\n contents_default := (fun (m0 : Memory.mem) (_ _ : Z) (b : positive) =>\n                        Memory.Mem.alloc_obligation_3 m0 b) m lo hi |}, nextblock m)).\n\n  simpl in *.\n  inv H.\n  reflexivity.\nQed.\n\nTheorem alloc_mem_access:\nforall m m' lo hi nb',\n  alloc m lo hi = (m', nb') ->\n  mem_access m' = Maps.PMap.set (nextblock m)\n                           (fun (ofs : Z) (_ : Memtype.perm_kind) =>\n                              if zle lo ofs && zlt ofs hi is true then Some Memtype.Freeable else None) \n                           (mem_access m).\nProof.\n  intros m m' lo hi nb' H.\n  change alloc with ( \nfun (m : Memory.mem) (lo hi : Z) =>\n({|\n mem_contents := Maps.PMap.set (nextblock m) (Maps.ZMap.init Memdata.Undef) (mem_contents m);\n mem_access := Maps.PMap.set (nextblock m)\n                 (fun (ofs : Z) (_ : perm_kind) =>\n                  if zle lo ofs && zlt ofs hi is true then Some Freeable else None) \n                 (mem_access m);\n nextblock := Pos.succ (nextblock m);\n access_max := (fun (m0 : Memory.mem) (lo0 hi0 : Z) (b : positive) (ofs : Z) =>\n                Memory.Mem.alloc_obligation_1 m0 lo0 hi0 b ofs) m lo hi;\n nextblock_noaccess := (fun (m0 : Memory.mem) (lo0 hi0 : Z) (b : positive) \n                          (ofs : Z) (k : perm_kind) (H : ~ Plt b (Pos.succ (nextblock m0))) =>\n                        Memory.Mem.alloc_obligation_2 m0 lo0 hi0 b ofs k H) m lo hi;\n contents_default := (fun (m0 : Memory.mem) (_ _ : Z) (b : positive) =>\n                        Memory.Mem.alloc_obligation_3 m0 b) m lo hi |}, nextblock m)).\n  simpl in *.\n  destruct m'.\n  simpl in *.\n  inv H.\n  auto.\nQed.\n\n", "meta": {"author": "sayon", "repo": "trancert", "sha": "eb5c94c75067782158522f61bdd7cc902bf74185", "save_path": "github-repos/coq/sayon-trancert", "path": "github-repos/coq/sayon-trancert/trancert-eb5c94c75067782158522f61bdd7cc902bf74185/properties/memory/Alloc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.20993882131476546}}
{"text": "Set Implicit Arguments.\n\nRequire Import Platform.Cito.LayoutHintsUtil Platform.Cito.ADT.\nRequire Import Platform.Cito.RepInv Platform.Cito.WordMap.\n\nModule Make (Import E : ADT) (Import M : RepInv E).\n\n  Require Import Platform.Cito.Inv.\n  Module Import InvMake := Inv.Make E.\n  Module Import InvMake2 := InvMake.Make M.\n  Import SemanticsMake.\n  Require Import Platform.Cito.SemanticsFacts5.\n  Require Import Platform.Cito.SemanticsUtil.\n\n  Section TopSection.\n\n    Definition heap_to_split h (_ : list (W * ArgIn)) := is_heap h.\n\n    Lemma split_heap' : forall pairs h, good_inputs h pairs -> heap_to_split h pairs ===> let h1 := make_heap pairs in is_heap h1 * is_heap (heap_diff h h1).\n      unfold heap_to_split; induction pairs; simpl; intros.\n\n      unfold heap_diff, heap_empty.\n      eapply Himp_trans; [ | apply Himp_star_Emp' ].\n      unfold is_heap, heap_elements.\n      apply starL_permute.\n\n      apply NoDupA_NoDup.\n      apply WordMap.elements_3w.\n\n      apply NoDupA_NoDup.\n      apply WordMap.elements_3w.\n\n      intuition.\n      apply In_InA' in H0.\n      apply InA_In.\n      apply WordMap.elements_1.\n      apply WordMap.elements_2 in H0.\n      Require Import Platform.Cito.WordMapFacts.\n      apply diff_mapsto_iff.\n      intuition.\n      destruct H1.\n      eapply WordMap.empty_1; eauto.\n      apply In_InA' in H0.\n      apply WordMap.elements_2 in H0.\n      apply diff_mapsto_iff in H0.\n      intuition.\n      apply InA_In.\n      apply WordMap.elements_1; auto.\n\n      unfold is_heap, heap_elements.\n      destruct H.\n      inversion_clear H.\n      hnf in H1.\n      hnf in H0.\n      case_eq (snd a); intros.\n      rewrite H in *; subst.\n      unfold make_heap; simpl.\n      unfold store_pair at 2 4.\n      unfold ArgIn, SemanticsMake.ArgIn.\n      unfold WordMap.key in H.\n      rewrite H.\n      apply IHpairs.\n      split; auto.\n      hnf.\n      simpl in H0.\n      unfold ArgIn, SemanticsMake.ArgIn in H0.\n      rewrite H in H0.\n      auto.\n\n      rewrite H in H1.\n      generalize H1; intro Ho.\n      apply WordMap.find_2 in Ho.\n      apply WordMap.elements_1 in Ho.\n      apply InA_In in Ho.\n      eapply starL_out in Ho.\n      destruct Ho; intuition.\n      eapply Himp_trans; [ apply H4 | ].\n      clear H4; simpl.\n      2: apply NoDupA_NoDup; apply WordMap.elements_3w.\n      assert (In (fst a, a0) (WordMap.elements (elt:=elt) (make_heap (a :: pairs)))).\n      unfold make_heap; simpl.\n\n      apply InA_In.\n      apply elements_mapsto_iff.\n      simpl in H0.\n      unfold is_adt in H0.\n      unfold WordMap.key, SemanticsMake.ArgIn in *.\n      rewrite H in *; simpl in *.\n      inversion_clear H0.\n      apply preserve_store; auto.\n      apply Forall_forall; intros.\n      case_eq (snd x0); intuition idtac.\n      unfold store_pair in H8.\n      unfold WordMap.key, ArgIn, SemanticsMake.ArgIn in *.\n      rewrite H in H8.\n      unfold heap_upd in H8.\n      eapply add_in_iff in H8; intuition idtac.\n      2: destruct H9; eapply WordMap.empty_1; eauto.\n      destruct a; simpl in *; subst.\n      destruct x0; simpl in *; subst.\n\n      eauto using keep_key.\n      unfold store_pair.\n      unfold WordMap.key, ArgIn, SemanticsMake.ArgIn in *.\n      rewrite H.\n      unfold heap_upd.\n      apply WordMap.add_1; auto.\n\n      simpl in *.\n      destruct a; simpl in *; subst; simpl in *.\n      rename w into k.\n      inversion_clear H0.\n      eapply Himp_trans; [ | apply Himp_star_frame; [ apply starL_permute | apply Himp_refl ] ].\n      instantiate (1 := (k, a0) :: heap_elements (make_heap pairs)).\n      Focus 2.\n      constructor.\n      intro.\n      unfold heap_elements, make_heap in H0.\n      apply In_InA' in H0.\n      apply WordMap.elements_2 in H0.\n\n      apply store_keys in H0; intuition idtac.\n      apply H.\n      change k with (fst (k, AxSpec.ADT a0)).\n      apply in_map; apply filter_In; tauto.\n      eapply WordMap.empty_1; eauto.\n      apply NoDupA_NoDup; apply WordMap.elements_3w.\n      2: apply NoDupA_NoDup; apply WordMap.elements_3w.\n      Focus 2.\n      simpl.\n      split.\n      destruct 1; subst.\n      auto.\n      unfold heap_elements in H0.\n\n      apply InA_In.\n      destruct x0.\n      apply WordMap.elements_1.\n      unfold make_heap; simpl.\n      apply store_keys'; auto.\n      apply In_InA' in H0.\n      apply WordMap.elements_2 in H0.\n      apply store_keys in H0; intuition idtac.\n      exfalso; eapply WordMap.empty_1; eauto.\n\n      intro.\n      apply In_InA' in H0.\n      destruct x0.\n      apply WordMap.elements_2 in H0.\n      unfold make_heap in H0; simpl in H0.\n      apply store_keys in H0.\n      intuition idtac.\n      right.\n      apply InA_In.\n      apply WordMap.elements_1.\n      apply store_keys'; auto.\n      unfold store_pair in H7; simpl in H7.\n      apply add_mapsto_iff in H7; intuition subst.\n      auto.\n      exfalso; eapply WordMap.empty_1; eauto.\n\n      simpl.\n      eapply Himp_trans; [ | apply Himp_star_assoc' ].\n      apply Himp_star_frame; try apply Himp_refl.\n      eapply Himp_trans; [ apply starL_permute | ].\n      auto.\n      instantiate (1 := WordMap.elements (WordMap.remove k h)).\n      apply NoDupA_NoDup; apply WordMap.elements_3w.\n      split; intro.\n      apply InA_In.\n      destruct x0.\n      apply WordMap.elements_1.\n      apply remove_mapsto_iff.\n      apply H6 in H0.\n      destruct H0; split; auto.\n      2: apply WordMap.elements_2; apply In_InA'; auto.\n      apply In_InA' in H7; apply WordMap.elements_2 in H7.\n      apply WordMap.find_1 in H7.\n      congruence.\n      apply In_InA' in H0.\n      destruct x0; apply WordMap.elements_2 in H0.\n      apply remove_mapsto_iff in H0.\n      apply H6; intuition (try congruence).\n      apply InA_In; apply WordMap.elements_1; auto.\n\n      eapply Himp_trans; [ apply IHpairs | ]; clear IHpairs.\n      split; auto.\n      apply Forall_forall; intros.\n      eapply Forall_forall in H2; [ | apply H0 ].\n      hnf in H2; hnf.\n      destruct x0; simpl in *.\n      rename w into k0.\n      destruct v; auto.\n      apply WordMap.find_1.\n      apply remove_mapsto_iff.\n      apply WordMap.find_2 in H2.\n      intuition subst.\n      apply H.\n      change k0 with (fst (k0, AxSpec.ADT a)).\n      apply in_map.\n      apply filter_In; auto.\n\n      apply Himp_star_frame; try apply Himp_refl.\n      apply starL_permute; try (apply NoDupA_NoDup; apply WordMap.elements_3w); intros.\n      intuition; apply InA_In; apply WordMap.elements_1;\n        apply In_InA' in H0; apply WordMap.elements_2 in H0;\n          apply diff_mapsto_iff; apply diff_mapsto_iff in H0; intuition idtac.\n      apply remove_mapsto_iff in H7; tauto.\n      apply remove_mapsto_iff in H7; intuition subst.\n      destruct H0.\n      eapply store_keys in H0; intuition idtac.\n      simpl in *; intuition (try congruence).\n      apply H8.\n      eexists.\n      eapply store_keys'; eauto.\n      exfalso; eapply WordMap.empty_1; eauto.\n      apply remove_mapsto_iff; intuition subst.\n      apply H8.\n      eexists; eapply store_keys'; eauto.\n      simpl; eauto.\n      auto.\n      constructor; auto.\n      apply H8.\n      destruct H0.\n      eapply store_keys in H0; intuition idtac.\n      eexists.\n      eapply store_keys'.\n      simpl; eauto.\n      constructor; auto.\n      exfalso; eapply WordMap.empty_1; eauto.\n    Qed.\n\n    Lemma split_heap : forall h pairs, good_inputs h pairs -> heap_to_split h pairs ===> let h1 := make_heap pairs in is_heap h1 * is_heap (heap_diff h h1).\n      eauto using split_heap'.\n    Qed.\n\n    Definition hints_split_heap : TacPackage.\n      prepare split_heap tt.\n    Defined.\n\n  End TopSection.\n\nEnd Make.", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Cito/LayoutHints2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984137988773, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2099388154972992}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*              Tactics                                                *)\n(*                                                                     *)\n(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)\n(*                                                                     *)\n(*          Yale Flint Group                                           *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file provide the tactic for refinement proof between layers*)\n\nRequire Import Coqlib.\nRequire Import Integers.\n\nDefinition Z64ofwords (i1 i2: Z) :=\n  (Z.lor (Z.shiftl i1 32) i2).\n\nDefinition Z64_lo_int (i: Z) : int :=\n  Int.repr i.\n\nDefinition Z64_hi_int (i: Z) : int :=\n  Int.repr (Z.shiftr i 32).\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/layerlib/Z64Lemma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20990230106678573}}
{"text": "Require Import FunctionalExtensionality.\nRequire Import Arith.\nRequire Import Omega.\nRequire Import List.\nRequire Import Pred.\nRequire Import Mem.\nRequire Import AsyncDisk.\nRequire Import DiskSet.\nRequire Import Array.\nRequire Import ListUtils.\nRequire Import LogReplay.\nRequire Import GenSepN.\nRequire Import ListPred.\n\nImport ListNotations.\n\nDefinition syncedmem := @Mem.mem _ addr_eq_dec bool.\n\nDefinition sm_vs_valid (sm : @Mem.mem _ addr_eq_dec _) vs :=\n  forall a, a < length vs -> sm a <> None /\\ (sm a = Some true -> vs_synced a vs).\n\nDefinition sm_ds_valid (sm : @Mem.mem _ addr_eq_dec _) ds :=\n  Forall (sm_vs_valid sm) (fst ds :: snd ds).\n\nLemma sm_ds_valid_pushd_iff: forall sm ds d,\n  sm_ds_valid sm ds /\\ sm_vs_valid sm d <-> sm_ds_valid sm (pushd d ds).\nProof.\n  unfold pushd, sm_ds_valid, ds_synced.\n  split; intuition; cbn in *.\n  all: repeat apply Forall_cons.\n  all: try solve [eapply Forall_inv; eauto | eapply Forall_cons2; eauto].\n  repeat (eapply Forall_cons2; eauto).\n  eapply Forall_inv.\n  eapply Forall_cons2; eauto.\nQed.\n\nLemma sm_ds_valid_pushd: forall sm ds d,\n  sm_vs_valid sm d ->\n  sm_ds_valid sm ds -> sm_ds_valid sm (pushd d ds).\nProof.\n  intros.\n  apply sm_ds_valid_pushd_iff.\n  auto.\nQed.\n\nLemma sm_ds_valid_pushd_r: forall sm ds d,\n  sm_ds_valid sm (pushd d ds) ->\n  sm_ds_valid sm ds.\nProof.\n  intros.\n  rewrite <- sm_ds_valid_pushd_iff in H.\n  intuition.\nQed.\n\nLemma sm_ds_valid_pushd_l: forall sm ds d,\n  sm_ds_valid sm (pushd d ds) ->\n  sm_vs_valid sm d.\nProof.\n  intros.\n  rewrite <- sm_ds_valid_pushd_iff in H.\n  intuition.\nQed.\n\nLemma vs_synced_updN_synced: forall a d i v,\n  vs_synced a d ->\n  vs_synced a (updN d i (v, nil)).\nProof.\n  unfold vs_synced, vssync.\n  intros.\n  destruct (lt_dec i (length d)).\n  destruct (addr_eq_dec i a); subst.\n  rewrite selN_updN_eq; auto.\n  rewrite selN_updN_ne; auto.\n  rewrite updN_oob by omega; auto.\nQed.\n\nLemma sm_vs_valid_upd_unsynced: forall sm d a v,\n  sm_vs_valid sm d ->\n  sm_vs_valid (Mem.upd sm a false) (updN d a v).\nProof.\n  unfold sm_vs_valid, Mem.upd, vsupd.\n  intros.\n  rewrite length_updN in *.\n  intuition.\n  destruct addr_eq_dec; subst.\n  congruence.\n  eapply H; eauto.\n  destruct addr_eq_dec.\n  congruence.\n  unfold vs_synced.\n  rewrite selN_updN_ne; auto.\n  eapply H; eauto.\nQed.\n\nLemma sm_vs_valid_upd_synced: forall sm i d v,\n  sm_vs_valid sm d ->\n  sm_vs_valid (Mem.upd sm i true) (updN d i (v, nil)).\nProof.\n  unfold sm_vs_valid, Mem.upd; cbn.\n  intros.\n  rewrite length_updN in *.\n  intuition.\n  destruct addr_eq_dec; subst.\n  congruence.\n  eapply H; eauto.\n  destruct addr_eq_dec; subst.\n  unfold vs_synced.\n  rewrite selN_updN_eq; auto.\n  apply vs_synced_updN_synced.\n  eapply H; eauto.\nQed.\n\nLemma sm_vs_valid_same_upd_synced: forall sm i d v,\n  sm_vs_valid sm d ->\n  sm_vs_valid sm (updN d i (v, nil)).\nProof.\n  unfold sm_vs_valid, Mem.upd; cbn.\n  intros.\n  rewrite length_updN in *.\n  intuition.\n  - eapply H; eauto.\n  - destruct (addr_eq_dec a i); subst.\n    + unfold vs_synced.\n      rewrite selN_updN_eq; auto.\n    + apply vs_synced_updN_synced.\n      eapply H; eauto.\nQed.\n\nLemma sm_vs_valid_vssync': forall sm vs a,\n  sm_vs_valid sm vs -> sm_vs_valid sm (vssync vs a).\nProof.\n  unfold sm_vs_valid, vssync; intros.\n  rewrite length_updN in *.\n  intuition.\n  eapply H; eauto.\n  eapply H in H1; auto.\n  eapply vs_synced_updN_synced.\n  auto.\nQed.\n\nLemma sm_vs_valid_vs_synced: forall sm vs a,\n  sm_vs_valid sm vs -> sm a = Some true ->\n  vs_synced a vs.\nProof.\n  unfold vs_synced, sm_vs_valid.\n  intros.\n  destruct (lt_dec a (length vs)) as [Hl|Hl].\n  apply H in Hl; intuition.\n  rewrite selN_oob by omega.\n  auto.\nQed.\n\n\nLemma sm_ds_valid_dsupd: forall sm ds a v,\n  a < length (ds!!) ->\n  sm_ds_valid sm ds ->\n  sm_ds_valid (Mem.upd sm a false) (dsupd ds a v).\nProof.\n  unfold sm_ds_valid.\n  intros.\n  constructor.\n  rewrite dsupd_fst.\n  eapply sm_vs_valid_upd_unsynced.\n  eapply Forall_inv; eauto.\n  unfold dsupd; cbn.\n  rewrite <- Forall_map.\n  rewrite Forall_forall in *.\n  intros.\n  cbn in *.\n  eapply sm_vs_valid_upd_unsynced; auto.\nQed.\n\nLemma sm_ds_valid_latest: forall sm ds,\n  sm_ds_valid sm ds ->\n  sm_vs_valid sm ds!!.\nProof.\n  unfold latest, sm_ds_valid; cbn.\n  intros.\n  inversion H; subst.\n  destruct (snd ds) eqn:?; cbn; eauto.\n  eapply Forall_inv; eauto.\nQed.\n\nLemma sm_ds_valid_synced: forall sm d,\n  sm_vs_valid sm d ->\n  sm_ds_valid sm (d, nil).\nProof.\n  unfold sm_ds_valid.\n  cbn; intros.\n  repeat (constructor; auto).\nQed.\n\nLemma sm_ds_valid_dssync: forall sm ds a,\n  sm_ds_valid sm ds ->\n  sm_ds_valid (Mem.upd sm a true) (dssync ds a).\nProof.\n  unfold sm_ds_valid.\n  intros.\n  constructor.\n  setoid_rewrite d_map_fst.\n  unfold vssync.\n  destruct (selN) eqn:?; cbn.\n  apply sm_vs_valid_upd_synced.\n  eapply Forall_inv; eauto.\n  unfold dssync; cbn.\n  rewrite <- Forall_map.\n  inversion H; subst.\n  rewrite Forall_forall in *.\n  intros.\n  eapply sm_vs_valid_upd_synced; auto.\nQed.\n\nLemma sm_ds_valid_dssync': forall sm ds a,\n  sm_ds_valid sm ds -> sm_ds_valid sm (dssync ds a).\nProof.\n  unfold sm_ds_valid; cbn; intros.\n  inversion H; subst; constructor.\n  eapply sm_vs_valid_vssync'; auto.\n  rewrite <- Forall_map.\n  rewrite Forall_forall in *.\n  intros x; specialize (H x); intuition.\n  eapply sm_vs_valid_vssync'; auto.\nQed.\n\nLemma sm_ds_valid_dssync_vecs': forall sm ds al,\n  sm_ds_valid sm ds -> sm_ds_valid sm (dssync_vecs ds al).\nProof.\n  induction al; cbn; intros.\n  rewrite dssync_vecs_nop by constructor.\n  auto.\n  rewrite dssync_vecs_cons.\n  rewrite dssync_vecs_dssync_comm.\n  eapply sm_ds_valid_dssync'; auto.\nQed.\n\nLemma sm_ds_valid_ds_synced: forall sm ds a,\n  sm_ds_valid sm ds -> sm a = Some true ->\n  ds_synced a ds.\nProof.\n  unfold ds_synced, sm_ds_valid.\n  intros.\n  rewrite Forall_forall in *.\n  intros x; specialize (H x); intuition.\n  eapply sm_vs_valid_vs_synced; eauto.\nQed.\n\n\nLemma sm_ds_valid_pushd_latest: forall sm ds,\n  sm_ds_valid sm ds ->\n  sm_ds_valid sm (pushd ds!! ds).\nProof.\n  intros.\n  auto using sm_ds_valid_pushd, sm_ds_valid_latest.\nQed.\n\nLemma sm_ds_valid_d_in: forall sm ds d,\n  sm_ds_valid sm ds ->\n  d_in d ds ->\n  sm_vs_valid sm d.\nProof.\n  unfold d_in, sm_ds_valid.\n  intros.\n  inversion H; clear H; rewrite Forall_forall in *; subst.\n  intuition; subst.\n  auto.\nQed.\n\nLemma sm_ds_valid_nthd: forall n sm ds,\n  sm_ds_valid sm ds ->\n  sm_vs_valid sm (nthd n ds).\nProof.\n  intros.\n  eapply sm_ds_valid_d_in; eauto.\n  eapply nthd_in_ds.\nQed.\n\nLemma sm_vs_valid_all_synced: forall sm d d',\n  sm_vs_valid sm d ->\n  length d = length d' ->\n  Forall (fun v => snd v = []) d' ->\n  sm_vs_valid sm d'.\nProof.\n  unfold sm_vs_valid.\n  intros.\n  rewrite Forall_forall in *.\n  rewrite H0 in *.\n  intuition.\n  eapply H; eauto.\n  unfold vs_synced.\n  eauto using in_selN.\nQed.\n\nDefinition sm_disk_exact (d : diskstate) :=\n  list2nmem (map (fun v => match (snd v) with [] => true | _ => false end) d).\n\nLemma sm_vs_valid_disk_exact: forall d,\n  sm_vs_valid (sm_disk_exact d) d.\nProof.\n  unfold sm_vs_valid, sm_disk_exact, list2nmem.\n  intros.\n  rewrite map_map.\n  erewrite selN_map by auto.\n  intuition.\n  congruence.\n  unfold vs_synced.\n  inversion H0.\n  destruct selN as [? l] eqn:H'.\n  rewrite H' in *.\n  destruct l; cbn in *; congruence.\nQed.\n\nDefinition sm_unsynced : syncedmem := fun _ => Some false.\nDefinition sm_synced : syncedmem := fun _ => Some true.\nDefinition sm_sync_all (sm : syncedmem) : syncedmem := fun a =>\n  match sm a with\n  | None => None\n  | Some _ => Some true\n  end.\n\nDefinition sm_sync_invariant (p : pred) : Prop := forall sm, p sm -> p (sm_sync_all sm).\n\nLemma sm_vs_valid_sm_unsynced: forall d,\n  sm_vs_valid sm_unsynced d.\nProof.\n  unfold sm_vs_valid; firstorder. discriminate.\n  unfold sm_unsynced in *. congruence.\nQed.\nLocal Hint Resolve sm_vs_valid_sm_unsynced.\n\nLemma sm_ds_valid_sm_unsynced: forall ds,\n  sm_ds_valid sm_unsynced ds.\nProof.\n  unfold sm_ds_valid; intros.\n  induction (fst ds :: snd ds); constructor; auto.\nQed.\n\nDefinition sm_set_vecs (b : bool) (sm : syncedmem) (a : list addr) :=\n  fold_left (fun sm a => @Mem.upd _ _ addr_eq_dec sm a b) a sm.\n\nDefinition sm_upd_vecs sm (a : list (_ * valu)) := sm_set_vecs false sm (map fst a).\nDefinition sm_sync_vecs := sm_set_vecs true.\n\nLemma sm_set_vecs_cons: forall a sm x b,\n  sm_set_vecs b sm (x :: a) = Mem.upd (sm_set_vecs b sm a) x b.\nProof.\n  unfold sm_set_vecs.\n  induction a; cbn; intros.\n  auto.\n  rewrite <- IHa.\n  cbn.\n  destruct (Nat.eq_dec a x).\n  congruence.\n  rewrite Mem.upd_comm; auto.\nQed.\n\nLemma sm_set_vecs_cons_inside: forall a sm x b,\n  sm_set_vecs b sm (x :: a) = sm_set_vecs b (Mem.upd sm x b) a.\nProof.\n  unfold sm_set_vecs.\n  induction a; cbn; intros.\n  auto.\n  rewrite <- IHa.\n  cbn.\n  destruct (Nat.eq_dec a x).\n  congruence.\n  rewrite Mem.upd_comm; auto.\nQed.\n\nLemma sm_upd_vecs_cons: forall a sm x,\n  sm_upd_vecs sm (x :: a) = Mem.upd (sm_upd_vecs sm a) (fst x) false.\nProof.\n  eauto using sm_set_vecs_cons.\nQed.\n\nLemma sm_sync_vecs_cons: forall a sm x,\n  sm_sync_vecs sm (x :: a) = Mem.upd (sm_sync_vecs sm a) x true.\nProof.\n  eauto using sm_set_vecs_cons.\nQed.\n\nLemma sm_upd_vecs_cons_inside: forall a sm x,\n  sm_upd_vecs sm (x :: a) = sm_upd_vecs (Mem.upd sm (fst x) false) a.\nProof.\n  eauto using sm_set_vecs_cons_inside.\nQed.\n\nLemma sm_sync_vecs_cons_inside: forall a sm x,\n  sm_sync_vecs sm (x :: a) = sm_sync_vecs (Mem.upd sm x true) a.\nProof.\n  eauto using sm_set_vecs_cons_inside.\nQed.\n\nLemma sm_vs_valid_vsupd_vecs: forall a sm v,\n  sm_vs_valid sm v ->\n  sm_vs_valid (sm_upd_vecs sm a) (vsupd_vecs v a).\nProof.\n  induction a; intros.\n  auto.\n  destruct a.\n  rewrite vsupd_vecs_cons, sm_upd_vecs_cons_inside.\n  cbn.\n  eapply IHa.\n  eapply sm_vs_valid_upd_unsynced.\n  auto.\nQed.\n\nLemma sm_vs_valid_vssync_vecs: forall a sm v,\n  sm_vs_valid sm v ->\n  sm_vs_valid (sm_sync_vecs sm a) (vssync_vecs v a).\nProof.\n  induction a; intros.\n  auto.\n  rewrite vssync_vecs_cons, sm_sync_vecs_cons_inside.\n  eapply IHa.\n  eapply sm_vs_valid_upd_synced.\n  auto.\nQed.\n\nLemma sm_vs_valid_ds_valid: forall sm ds,\n  Forall (sm_vs_valid sm) (fst ds :: snd ds) ->\n  sm_ds_valid sm ds.\nProof.\n  intros.\n  unfold sm_ds_valid; auto.\nQed.\n\nLemma sm_ds_valid_dsupd_vecs: forall a sm ds,\n  sm_ds_valid sm ds ->\n  sm_ds_valid (sm_upd_vecs sm a) (dsupd_vecs ds a).\nProof.\n  intros.\n  apply sm_vs_valid_ds_valid.\n  rewrite Forall_forall; intros.\n  unfold dsupd_vecs, d_map in *.\n  cbn in *.\n  intuition subst.\n  eapply sm_vs_valid_vsupd_vecs.\n  inversion H; auto.\n  rewrite in_map_iff in *.\n  deex.\n  eapply sm_vs_valid_vsupd_vecs.\n  inversion H; subst.\n  rewrite Forall_forall in *.\n  auto.\nQed.\n\nLemma sm_ds_valid_dssync_vecs: forall a sm ds,\n  sm_ds_valid sm ds ->\n  sm_ds_valid (sm_sync_vecs sm a) (dssync_vecs ds a).\nProof.\n  intros.\n  apply sm_vs_valid_ds_valid.\n  rewrite Forall_forall; intros.\n  unfold dssync_vecs, d_map in *.\n  cbn in *.\n  intuition subst.\n  eapply sm_vs_valid_vssync_vecs.\n  inversion H; auto.\n  rewrite in_map_iff in *.\n  deex.\n  eapply sm_vs_valid_vssync_vecs.\n  inversion H; subst.\n  rewrite Forall_forall in *.\n  auto.\nQed.\n\nLemma sm_sync_all_mem_union: forall AEQ m1 m2,\n  @mem_union _ AEQ _ (sm_sync_all m1) (sm_sync_all m2) = sm_sync_all (mem_union m1 m2).\nProof.\n  unfold mem_union, sm_sync_all.\n  intros.\n  apply functional_extensionality.\n  intros.\n  destruct m1, m2; auto.\nQed.\n\nLemma sm_sync_all_mem_disjoint: forall m1 m2 AEQ,\n  mem_disjoint m1 m2 -> @mem_disjoint _ AEQ _ (sm_sync_all m1) (sm_sync_all m2).\nProof.\n  unfold mem_disjoint, sm_sync_all.\n  intuition repeat deex.\n  destruct m1 eqn:?, m2 eqn:?; try congruence.\n  apply H; eauto.\nQed.\n\nLemma sm_sync_invariant_sep_star: forall (p q : pred),\n  sm_sync_invariant p -> sm_sync_invariant q ->\n  sm_sync_invariant (p * q).\nProof.\n  unfold_sep_star.\n  unfold sm_sync_invariant.\n  intuition repeat deex.\n  repeat eexists.\n  rewrite sm_sync_all_mem_union; eauto.\n  eauto using sm_sync_all_mem_disjoint.\n  all: auto.\nQed.\n\nLemma sm_sync_all_sep_star_swap: forall AEQ (p p' q q' : @pred _ AEQ _) sm,\n  (p * q)%pred sm ->\n  (forall m, p m -> p' (sm_sync_all m)) ->\n  (forall m, q m -> q' (sm_sync_all m)) ->\n  (p' * q')%pred (sm_sync_all sm).\nProof.\n  unfold_sep_star.\n  intuition repeat deex.\n  repeat eexists.\n  rewrite sm_sync_all_mem_union.\n  reflexivity.\n  apply sm_sync_all_mem_disjoint; auto.\n  all: auto.\nQed.\n\nLemma sm_sync_all_sep_star_swap_l: forall (p p' q : pred) sm,\n  (p * q)%pred sm ->\n  (forall m, p m -> p' (sm_sync_all m)) ->\n  sm_sync_invariant q ->\n  (p' * q)%pred (sm_sync_all sm).\nProof.\n  eauto using sm_sync_all_sep_star_swap.\nQed.\n\nLemma sm_sync_all_sep_star_swap_r: forall (p q q' : pred) sm,\n  (p * q)%pred sm ->\n  (forall m, q m -> q' (sm_sync_all m)) ->\n  sm_sync_invariant p ->\n  (p * q')%pred (sm_sync_all sm).\nProof.\n  eauto using sm_sync_all_sep_star_swap.\nQed.\n\nLemma sm_sync_invariant_lift_empty: forall P,\n  sm_sync_invariant (lift_empty P).\nProof.\n  unfold sm_sync_invariant, sm_sync_all, lift_empty.\n  intuition.\n  rewrite H1; auto.\nQed.\n\nLemma sm_sync_all_ptsto: forall AEQ a b (m : syncedmem),\n  (@ptsto _ AEQ _ a b)%pred m ->\n  (@ptsto _ AEQ _ a true)%pred (sm_sync_all m).\nProof.\n  unfold ptsto, sm_sync_all.\n  intuition.\n  rewrite H0; auto.\n  rewrite H1; auto.\nQed.\n\nLemma sm_sync_invariant_exis_ptsto: forall a,\n  sm_sync_invariant (a |->?)%pred.\nProof.\n  unfold sm_sync_invariant, sm_sync_all, ptsto.\n  intros.\n  destruct H as [x ?].\n  intuition.\n  exists true.\n  destruct sm; try congruence.\n  intuition.\n  rewrite H1; auto.\nQed.\n\nLemma sm_sync_invariant_emp:\n  sm_sync_invariant emp.\nProof.\n  unfold sm_sync_invariant, sm_sync_all, emp.\n  intuition.\n  rewrite H.\n  auto.\nQed.\n\nLemma sm_sync_invariant_listpred: forall T prd (l : list T),\n  (forall x, In x l -> sm_sync_invariant (prd x)) ->\n  sm_sync_invariant (listpred prd l).\nProof.\n  induction l; cbn; intros.\n  apply sm_sync_invariant_emp.\n  apply sm_sync_invariant_sep_star; auto.\nQed.\n\nLemma sm_sync_all_listpred_swap: forall T AEQ (prd prd' : T -> @pred _ AEQ _) (l : list T) sm,\n  (forall sm x, In x l -> prd x sm -> prd' x (sm_sync_all sm)) ->\n  listpred prd l sm ->\n  listpred prd' l (sm_sync_all sm).\nProof.\n  induction l; cbn; intros.\n  apply sm_sync_invariant_emp; auto.\n  eapply sm_sync_all_sep_star_swap; eauto.\nQed.\n\nLemma sm_sync_all_arrayN_swap: forall T AEQ (prd prd' : nat -> T -> @pred _ AEQ _) d (l : list T) i sm,\n  (forall sm  i' x, i' < length l -> selN l i' d = x -> prd (i + i') x sm -> prd' (i + i') x (sm_sync_all sm)) ->\n  arrayN prd i l sm ->\n  arrayN prd' i l (sm_sync_all sm).\nProof.\n  induction l; cbn; intros.\n  apply sm_sync_invariant_emp; auto.\n  eapply sm_sync_all_sep_star_swap; eauto.\n  intros.\n  specialize (H m 0).\n  rewrite Nat.add_0_r in *.\n  apply H; auto.\n  omega.\n  intros.\n  eapply IHl; auto.\n  intros.\n  rewrite plus_Snm_nSm in *.\n  apply H; auto.\n  omega.\nQed.\n\nLemma sm_sync_invariant_piff: forall (p q : pred),\n  piff p q -> sm_sync_invariant p <-> sm_sync_invariant q.\nProof.\n  unfold sm_sync_invariant.\n  intros.\n  intuition.\n  all : do 3 match goal with H: _ |- _ => apply H end; auto.\nQed.\n\nHint Resolve sm_sync_invariant_sep_star.\nHint Resolve sm_sync_invariant_exis_ptsto.\nHint Resolve sm_sync_invariant_emp.\nHint Resolve sm_sync_invariant_lift_empty.\nHint Resolve sm_sync_invariant_listpred.\n\nHint Resolve sm_sync_all_ptsto.\n\nDefinition mem_except_mem {AT AEQ V} (m ex : @Mem.mem AT AEQ V) : @Mem.mem AT AEQ V := fun a =>\n  match ex a with\n  | Some _ => None\n  | None => m a\n  end.\n\nLemma mem_except_mem_disjoint: forall AT AEQ V (m ex : @Mem.mem AT AEQ V),\n  mem_disjoint (mem_except_mem m ex) ex.\nProof.\n  unfold mem_disjoint, mem_except_mem.\n  intuition repeat deex.\n  destruct ex; congruence.\nQed.\n\nLemma mem_except_mem_union: forall AT AEQ V (m ex : @Mem.mem AT AEQ V),\n  mem_union (mem_except_mem m ex) ex = (mem_union ex m).\nProof.\n  intros.\n  unfold mem_union, mem_except_mem.\n  eapply functional_extensionality.\n  intros.\n  destruct ex; auto.\n  destruct m; auto.\nQed.\n\nLemma sm_sync_all_mem_union_sm_synced: forall m m1 m2,\n  sm_sync_all m = mem_union m1 m2 ->\n  mem_disjoint m1 m2 ->\n  sm_synced = mem_union m2 sm_synced.\nProof.\n  unfold sm_sync_all, mem_union, sm_synced.\n  intros.\n  eapply functional_extensionality.\n  intros a.\n  eapply equal_f in H.\n  instantiate (1 := a) in H.\n  destruct m eqn:?, m1 eqn:?; inversion H; subst.\n  destruct m2 eqn:?; auto.\n  match goal with Hm: mem_disjoint _ _ |- _ =>\n    exfalso; apply Hm end.\n  all: eauto.\nQed.\n\nLemma sm_synced_sep_star_l: forall AEQ (p q : @pred _ AEQ _) m,\n  (p * q)%pred (sm_sync_all m) ->\n  (any * q)%pred sm_synced.\nProof.\n  unfold_sep_star.\n  intuition repeat deex.\n  repeat eexists.\n  3: eassumption.\n  2: apply mem_except_mem_disjoint.\n  rewrite mem_except_mem_union.\n  eapply sm_sync_all_mem_union_sm_synced; eauto.\nQed.\n\nLemma sm_synced_sep_star_r: forall AEQ (p q : @pred _ AEQ _) m,\n  (p * q)%pred (sm_sync_all m) ->\n  (p * any)%pred sm_synced.\nProof.\n  intros.\n  apply sep_star_comm.\n  apply sep_star_comm in H.\n  eauto using sm_synced_sep_star_l.\nQed.\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/SyncedMem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20990230106678573}}
{"text": "(* \n This is the definition of formal syntax for Dan Grossman's Thesis, \n  \"SAFE PROGRAMMING AT THE C LEVEL OF ABSTRACTION\". \n\n  Substitutions \n\n*)\n\nSet Implicit Arguments.\nRequire Export Cyclone_Formal_Syntax Cyclone_Static_Semantics_Kinding_And_Context_Well_Formedness.\nRequire Export Cyclone_Static_Semantics_Typing_Heap_Objects.\nRequire Export Cyclone_Classes Cyclone_Inductions Cyclone_LN_Tactics Cyclone_LN_Extra_Lemmas_And_Automation.\nRequire Export Cyclone_Context_Weakening_Proof.\nRequire Export Cyclone_LN_Types_Lemmas.\nRequire Export Cyclone_Get_Lemmas.\nRequire Export Cyclone_Admit_Environment.\nClose Scope list_scope.\nImport LibEnvNotations.\nImport LVPE.LibVarPathEnvNotations.\n\nLemma A_6_Subsititution_1:\n  forall d d' t k,\n      ok (d & d') ->\n      K (d & d') t k ->\n      forall alpha t' k',\n        ok (d & alpha ~ k & d') ->\n        K (d & alpha ~ k & d') t' k' ->\n        K (d & d')  (T.subst t alpha t') k'.\nProof.\n  introv okdd' Kd okdakd' Kdakd'.\n  gen_eq G: (d & alpha ~ k & d'). gen d'.\n  induction Kdakd'; intros; subst; auto.\n  simpl.\n  case_var.\n  apply get_middle_eq_inv in H; subst; auto.\n  apply get_subst in H; subst; auto.\n\n  simpl.\n  case_var.\n  apply K_ptype.\n  (* yes k is A! *) \n  admit.\n  apply K_star_A.\n  admit.\n\n  simpl.\n  apply_fresh K_utype.\n  intros.\n  assert(NI: y \\notin L). admit.\n  assert(OKB: ok (d & alpha ~ k & d' & y ~ k0)). admit.\n  specialize (H y NI OKB).\n  specialize (H0 y NI OKB OKB (d' & y ~ k0)).\n(*\n  rewrite <- ok_commutes in H0.\n  rewrite <- K_context_commutes in H0.\n  rewrite <- K_context_commutes in H0.\n  assert(KW: K (d & d' & y ~ k0) t k). admit. (* k weakening *)\n  assert(CC: d & alpha ~ k & d' & y ~ k0 = d & alpha ~ k & (d' & y ~ k0)). admit.\n  (* contexts commute, meta theorem I must accept. *)\n  specialize (H0 H1 KW CC).\n  rewrite* <- TP.subst_open_var.\n\n  apply K__lc with (d:= (d&d')) (k:=k); auto.\n  admit.\n\n  apply K_B_A.\n  apply* IHKdakd'.\n*)\nAdmitted.\n\nLemma A_6_Subsititution_2:\n  forall d d' t k,\n      ok (d & d') ->\n      AK (d & d') t k ->\n      forall alpha t' k',\n        ok (d & alpha ~ k & d') ->\n        AK (d & alpha ~ k & d') t' k' ->\n        AK (d & d') (T.subst t alpha t') k'.\nProof.\n  introv okdd' AKd okdakd' AKdakd'.\n  inversions* AKdakd'.\n  inversions* AKd.\n  constructor.\n  apply A_6_Subsititution_1 with (k:=k); auto.\n  constructor.\n  apply A_6_Subsititution_1 with (k:=A); auto.\n  (* bug ? A/B *)\n  admit.\n  simpl.\n  case_var*.\n  apply get_middle_eq_inv in H; subst*.\n  apply AK_A.\n  admit. (* get strengthening. *)\nAdmitted.\n\nLemma A_6_Subsititution_3:\n  forall d d' t,\n      ok (d & d') ->\n      ASGN (d & d') t ->\n      forall alpha t' k,\n        ok (d & alpha ~ k & d') ->\n        ASGN (d & alpha ~ k & d') t' ->\n        ASGN (d & d') (T.subst t alpha t').\nProof.\n  introv okdd' ASGNdd' OKdakd' ASGNdakd'.\n  gen_eq G: (d & alpha ~ k & d'). gen d'.\n  induction ASGNdakd'; intros; subst; auto; simpl; try solve[constructor; auto];\n    try solve[case_var*;\n              apply ASGN_B;\n              apply get_subst in H; subst; auto].\n\n  apply_fresh ASGN_utype.\n  assert(NI: y \\notin L). auto.\n  specialize (H y NI).\n  assert(OKB: ok (d & alpha ~ k & d' & y ~ k0)). admit.\n  assert(OKL : ok (d & d' & y ~ k0)); auto.\n  specialize (H0 y NI OKB (d' & y ~ k0)).\n(*\n  rewrite <- ok_commutes in H0.\n  assert(ASGNB: ASGN (d & (d' & y ~ k0)) t). admit. (* asgn commutes, commits *)\n  assert(H1: d & alpha ~ k & d' & y ~ k0 = d & alpha ~ k & (d' & y ~ k0)). admit.\n  specialize (H0 OKL ASGNB H1).\n  rewrite <- TP.subst_open_var.\n*)\nAdmitted.", "meta": {"author": "briangmilnes", "repo": "CycloneCoqSemantics", "sha": "190c0fc57d5aebfde244efb06a119f108de7a150", "save_path": "github-repos/coq/briangmilnes-CycloneCoqSemantics", "path": "github-repos/coq/briangmilnes-CycloneCoqSemantics/CycloneCoqSemantics-190c0fc57d5aebfde244efb06a119f108de7a150/4.5/Cyclone_Substitutions_Proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2099023010667857}}
{"text": "Require Import Bool.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Global.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import OrdStep.\nRequire Import Writes.\n\nSet Implicit Arguments.\n\n\nModule WThread.\n  Section WThread.\n    Variable lang: language.\n    Variable L: Loc.t -> bool.\n    Variable ordcr: Ordering.t.\n    Variable ordcw: Ordering.t.\n\n    Variant step rels1: forall (rels2: Writes.t) (e: ThreadEvent.t) (e1 e2: Thread.t lang), Prop :=\n    | step_intro\n        e e1 e2\n        (STEP: @OrdThread.step lang L ordcr ordcw e e1 e2):\n        step rels1 (Writes.append L e rels1) e e1 e2\n    .\n\n    (* Inducitve steps rels1: forall (rels2: Writes.t) (e1 e2: Thread.t lang), Prop := *)\n    (* | steps_refl *)\n    (*     e: *)\n    (*     steps rels1 rels1 e e *)\n    (* | steps_step *)\n    (*     rels2 rels3 e e1 e2 e3 *)\n    (*     (STEP: step rels1 rels2 e e1 e2) *)\n    (*     (STEPS: steps rels2 rels3 e2 e3): *)\n    (*     steps rels1 rels3 e1 e3 *)\n    (* . *)\n    (* Hint Constructors steps: core. *)\n\n    (* Inductive tau_steps rels1: forall (rels2: Writes.t) (e1 e2: Thread.t lang), Prop := *)\n    (* | tau_steps_refl *)\n    (*     e: *)\n    (*     tau_steps rels1 rels1 e e *)\n    (* | tau_steps_step *)\n    (*     rels2 rels3 e e1 e2 e3 *)\n    (*     (STEP: step rels1 rels2 e e1 e2) *)\n    (*     (SILENT: ThreadEvent.get_machine_event e = MachineEvent.silent) *)\n    (*     (STEPS: tau_steps rels2 rels3 e2 e3): *)\n    (*     tau_steps rels1 rels3 e1 e3 *)\n    (* . *)\n    (* Hint Constructors tau_steps: core. *)\n\n    Variant opt_step rels1: forall (rels2: Writes.t) (e: ThreadEvent.t) (e1 e2: Thread.t lang), Prop :=\n    | step_none\n        e:\n        opt_step rels1 rels1 ThreadEvent.silent e e\n    | step_some\n        rels2 e e1 e2\n        (STEP: step rels1 rels2 e e1 e2):\n        opt_step rels1 rels2 e e1 e2\n    .\n    Hint Constructors opt_step: core.\n\n\n    Lemma step_ord_step\n          rels1 rels2 e e1 e2\n          (STEP: step rels1 rels2 e e1 e2):\n      OrdThread.step L ordcr ordcw e e1 e2.\n    Proof.\n      inv STEP. eauto.\n    Qed.\n\n    Lemma opt_step_ord_opt_step\n          rels1 rels2 e e1 e2\n          (STEP: opt_step rels1 rels2 e e1 e2):\n      OrdThread.opt_step L ordcr ordcw e e1 e2.\n    Proof.\n      inv STEP; [econs 1|].\n      exploit step_ord_step; eauto. i. des.\n      econs 2. eauto.\n    Qed.\n\n    (* Lemma steps_ord_steps *)\n    (*       rels1 rels2 e1 e2 *)\n    (*       (STEPS: steps rels1 rels2 e1 e2): *)\n    (*   rtc (OrdThread.all_step L ordcr ordcw) e1 e2. *)\n    (* Proof. *)\n    (*   induction STEPS; eauto. *)\n    (*   exploit step_ord_step; eauto. i. des. *)\n    (*   econs 2; eauto. econs. econs. eauto. *)\n    (* Qed. *)\n\n    (* Lemma tau_steps_ord_tau_steps *)\n    (*       rels1 rels2 e1 e2 *)\n    (*       (STEPS: tau_steps rels1 rels2 e1 e2): *)\n    (*   rtc (@OrdThread.tau_step lang L ordcr ordcw) e1 e2. *)\n    (* Proof. *)\n    (*   induction STEPS; eauto. *)\n    (*   inv STEP; ss. *)\n    (*   econs 2; eauto. econs; eauto. econs. eauto. *)\n    (* Qed. *)\n\n    (* Lemma ord_tau_steps_tau_steps *)\n    (*       e1 e2 *)\n    (*       (STEPS: rtc (@OrdThread.tau_step lang L ordcr ordcw) e1 e2): *)\n    (*   forall rels1, exists rels2, *)\n    (*       tau_steps rels1 rels2 e1 e2. *)\n    (* Proof. *)\n    (*   induction STEPS; eauto. inv H. inv TSTEP. i. *)\n    (*   specialize (IHSTEPS (Writes.append L e rels1)). des. *)\n    (*   esplits. econs 2; eauto. econs; eauto. *)\n    (* Qed. *)\n\n    (* Lemma tau_steps_steps *)\n    (*       rels1 rels2 e1 e2 *)\n    (*       (STEPS: tau_steps rels1 rels2 e1 e2): *)\n    (*   steps rels1 rels2 e1 e2. *)\n    (* Proof. *)\n    (*   induction STEPS; eauto. *)\n    (* Qed. *)\n\n    (* Lemma reserve_steps_tau_steps *)\n    (*       rels e1 e2 *)\n    (*       (STEPS: rtc (@Thread.reserve_step _) e1 e2): *)\n    (*   tau_steps rels rels e1 e2. *)\n    (* Proof. *)\n    (*   induction STEPS; eauto. *)\n    (*   inv H. inv STEP; [|inv STEP0; inv LOCAL]. *)\n    (*   econs 2; eauto. *)\n    (*   - replace rels with *)\n    (*         (Writes.append *)\n    (*            L (ThreadEvent.promise loc from to Message.reserve Memory.op_kind_add) rels) *)\n    (*         at 2 by ss. *)\n    (*     econs. econs 1; eauto. *)\n    (*     ii. inv PROMISE. ss. *)\n    (*   - ss. *)\n    (* Qed. *)\n\n    (* Lemma cancel_steps_tau_steps *)\n    (*       rels e1 e2 *)\n    (*       (STEPS: rtc (@Thread.cancel_step _) e1 e2): *)\n    (*   tau_steps rels rels e1 e2. *)\n    (* Proof. *)\n    (*   induction STEPS; eauto. *)\n    (*   inv H. inv STEP; [|inv STEP0; inv LOCAL]. *)\n    (*   econs 2; eauto. *)\n    (*   - replace rels with *)\n    (*         (Writes.append *)\n    (*            L (ThreadEvent.promise loc from to Message.reserve Memory.op_kind_cancel) rels) *)\n    (*         at 2 by ss. *)\n    (*     econs. econs 1; eauto. *)\n    (*     ii. inv PROMISE; ss. *)\n    (*   - ss. *)\n    (* Qed. *)\n\n    (* Lemma tau_steps_rtc_tau_step *)\n    (*       rels1 rels2 e1 e2 *)\n    (*       (STEPS: tau_steps rels1 rels2 e1 e2): *)\n    (*   rtc (@OrdThread.tau_step lang L ordcr ordcw) e1 e2. *)\n    (* Proof. *)\n    (*   induction STEPS; eauto. *)\n    (*   econs 2; eauto. inv STEP; ss. *)\n    (*   econs; eauto. econs. eauto. *)\n    (* Qed. *)\n\n    (* Lemma opt_step_steps *)\n    (*       rels1 rels2 e e1 e2 *)\n    (*       (STEP: opt_step rels1 rels2 e e1 e2): *)\n    (*   steps rels1 rels2 e1 e2. *)\n    (* Proof. *)\n    (*   inv STEP; eauto. *)\n    (* Qed. *)\n\n    (* Lemma steps_trans *)\n    (*       rels1 rels2 rels3 e1 e2 e3 *)\n    (*       (STEPS1: steps rels1 rels2 e1 e2) *)\n    (*       (STEPS2: steps rels2 rels3 e2 e3): *)\n    (*   steps rels1 rels3 e1 e3. *)\n    (* Proof. *)\n    (*   revert rels3 e3 STEPS2. *)\n    (*   induction STEPS1; i; eauto. *)\n    (* Qed. *)\n\n    (* Lemma tau_steps_trans *)\n    (*       rels1 rels2 rels3 e1 e2 e3 *)\n    (*       (STEPS1: tau_steps rels1 rels2 e1 e2) *)\n    (*       (STEPS2: tau_steps rels2 rels3 e2 e3): *)\n    (*   tau_steps rels1 rels3 e1 e3. *)\n    (* Proof. *)\n    (*   revert rels3 e3 STEPS2. *)\n    (*   induction STEPS1; i; eauto. *)\n    (* Qed. *)\n\n    Lemma step_future\n          rels1 rels2 e e1 e2\n          (STEP: step rels1 rels2 e e1 e2)\n          (LC_WF1: Local.wf (Thread.local e1) (Thread.global e1))\n          (GL_WF1: Global.wf (Thread.global e1)):\n      <<LC_WF2: Local.wf (Thread.local e2) (Thread.global e2)>> /\\\n      <<GL_WF2: Global.wf (Thread.global e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<GL_FUTURE: Global.future (Thread.global e1) (Thread.global e2)>>.\n    Proof.\n      inv STEP; eauto using OrdThread.step_future.\n    Qed.\n\n    Lemma opt_step_future\n          rels1 rels2 e e1 e2\n          (STEP: opt_step rels1 rels2 e e1 e2)\n          (LC_WF1: Local.wf (Thread.local e1) (Thread.global e1))\n          (GL_WF1: Global.wf (Thread.global e1)):\n      <<LC_WF2: Local.wf (Thread.local e2) (Thread.global e2)>> /\\\n      <<GL_WF2: Global.wf (Thread.global e2)>> /\\\n      <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\\n      <<GL_FUTURE: Global.future (Thread.global e1) (Thread.global e2)>>.\n    Proof.\n      inv STEP.\n      - esplits; eauto; refl.\n      - inv STEP0; eauto using OrdThread.step_future.\n    Qed.\n\n    (* Lemma steps_future *)\n    (*       rels1 rels2 e1 e2 *)\n    (*       (STEPS: steps rels1 rels2 e1 e2) *)\n    (*       (WF1: Local.wf (Thread.local e1) (Thread.memory e1)) *)\n    (*       (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1)) *)\n    (*       (CLOSED1: Memory.closed (Thread.memory e1)): *)\n    (*   <<WF2: Local.wf (Thread.local e2) (Thread.memory e2)>> /\\ *)\n    (*   <<SC2: Memory.closed_timemap (Thread.sc e2) (Thread.memory e2)>> /\\ *)\n    (*   <<CLOSED2: Memory.closed (Thread.memory e2)>> /\\ *)\n    (*   <<TVIEW_FUTURE: TView.le (Local.tview (Thread.local e1)) (Local.tview (Thread.local e2))>> /\\ *)\n    (*   <<SC_FUTURE: TimeMap.le (Thread.sc e1) (Thread.sc e2)>> /\\ *)\n    (*   <<MEM_FUTURE: Memory.future (Thread.memory e1) (Thread.memory e2)>>. *)\n    (* Proof. *)\n    (*   revert WF1 SC1 CLOSED1. induction STEPS; i. *)\n    (*   - splits; ss; refl. *)\n    (*   - exploit step_future; eauto. i. des. *)\n    (*     exploit IHSTEPS; eauto. i. des. *)\n    (*     splits; ss; etrans; eauto. *)\n    (* Qed. *)\n\n    Lemma step_disjoint\n          rels1 rels2 e e1 e2 lc\n          (STEP: step rels1 rels2 e e1 e2)\n          (LC_WF1: Local.wf (Thread.local e1) (Thread.global e1))\n          (GL_WF1: Global.wf (Thread.global e1))\n          (DISJOINT1: Local.disjoint (Thread.local e1) lc)\n          (LC_WF: Local.wf lc (Thread.global e1)):\n      <<DISJOINT2: Local.disjoint (Thread.local e2) lc>> /\\\n      <<LC_WF: Local.wf lc (Thread.global e2)>>.\n    Proof.\n      inv STEP; eauto using OrdThread.step_disjoint.\n    Qed.\n\n    Lemma opt_step_disjoint\n          rels1 rels2 e e1 e2 lc\n          (STEP: opt_step rels1 rels2 e e1 e2)\n          (LC_WF1: Local.wf (Thread.local e1) (Thread.global e1))\n          (GL_WF1: Global.wf (Thread.global e1))\n          (DISJOINT1: Local.disjoint (Thread.local e1) lc)\n          (LC_WF: Local.wf lc (Thread.global e1)):\n      <<DISJOINT2: Local.disjoint (Thread.local e2) lc>> /\\\n      <<LC_WF: Local.wf lc (Thread.global e2)>>.\n    Proof.\n      inv STEP; eauto.\n      inv STEP0; eauto using OrdThread.step_disjoint.\n    Qed.\n\n\n    (* Writes.wf *)\n\n    Lemma step_writes_wf\n          rels1 rels2 e e1 e2\n          (ORDCW: Ordering.le Ordering.plain ordcw)\n          (RELS1: Writes.wf L rels1 (Global.memory (Thread.global e1)))\n          (STEP: step rels1 rels2 e e1 e2):\n      Writes.wf L rels2 (Global.memory (Thread.global e2)).\n    Proof.\n      inv STEP. eapply Writes.step_wf; eauto.\n    Qed.\n\n    (* Lemma steps_writes_wf *)\n    (*       rels1 rels2 e1 e2 *)\n    (*       (ORDCW: Ordering.le Ordering.plain ordcw) *)\n    (*       (RELS1: Writes.wf L rels1 (Thread.memory e1)) *)\n    (*       (STEPS: steps rels1 rels2 e1 e2): *)\n    (*   Writes.wf L rels2 (Thread.memory e2). *)\n    (* Proof. *)\n    (*   induction STEPS; eauto. *)\n    (*   apply IHSTEPS. eapply step_writes_wf; eauto. *)\n    (* Qed. *)\n\n    (* Lemma step_rels_disjoint *)\n    (*       rels1 rels2 e e1 e2 promises *)\n    (*       (RELS1: Writes.wf L rels1 (Local.promises (Thread.local e1)) (Thread.memory e1)) *)\n    (*       (STEP: step rels1 rels2 e e1 e2) *)\n    (*       (DISJOINT: Memory.disjoint (Local.promises (Thread.local e1)) promises) *)\n    (*       (LE: Memory.le promises (Thread.memory e1)) *)\n    (*       (RELS: Writes.wf L rels1 promises (Thread.memory e1)): *)\n    (*   Writes.wf L rels2 promises (Thread.memory e2). *)\n    (* Proof. *)\n    (*   inv STEP. eauto using Writes.step_disjoint. *)\n    (* Qed. *)\n\n    (* Lemma steps_rels_disjoint *)\n    (*       rels1 rels2 e1 e2 lc *)\n    (*       (RELS1: Writes.wf L rels1 (Local.promises (Thread.local e1)) (Thread.memory e1)) *)\n    (*       (STEPS: steps rels1 rels2 e1 e2) *)\n    (*       (WF1: Local.wf (Thread.local e1) (Thread.memory e1)) *)\n    (*       (SC1: Memory.closed_timemap (Thread.sc e1) (Thread.memory e1)) *)\n    (*       (CLOSED1: Memory.closed (Thread.memory e1)) *)\n    (*       (DISJOINT: Local.disjoint (Thread.local e1) lc) *)\n    (*       (WF: Local.wf lc (Thread.memory e1)) *)\n    (*       (RELS: Writes.wf L rels1 (Local.promises lc) (Thread.memory e1)): *)\n    (*   Writes.wf L rels2 (Local.promises lc) (Thread.memory e2). *)\n    (* Proof. *)\n    (*   induction STEPS; ss. *)\n    (*   hexploit step_rels_disjoint; eauto; try apply DISJOINT; try apply WF. i. *)\n    (*   hexploit step_writes_wf; eauto. i. *)\n    (*   inv STEP. *)\n    (*   exploit OrdThread.step_future; eauto. i. des. *)\n    (*   exploit OrdThread.step_disjoint; eauto. i. des. *)\n    (*   eapply IHSTEPS; eauto. *)\n    (* Qed. *)\n\n    Lemma step_rels_incl\n          rels1 rels2 e e1 e2\n          (STEP: step rels1 rels2 e e1 e2):\n      rels2 = rels1 \\/ exists a, rels2 = a :: rels1.\n    Proof.\n      inv STEP. unfold Writes.append. des_ifs; eauto.\n    Qed.\n  End WThread.\nEnd WThread.\n\n\nModule WConfiguration.\n  Section WConfiguration.\n    Variable L: Loc.t -> bool.\n    Variable ordcr ordcw: Ordering.t.\n\n    Variant step:\n      forall (e: ThreadEvent.t) (tid: Ident.t) (rels1 rels2: Writes.t) (c1 c2: Configuration.t), Prop :=\n    | step_intro\n        rels1 rels2\n        e tid c1 lang st1 lc1 st2 lc2 gl2\n        (TID: IdentMap.find tid (Configuration.threads c1) = Some (existT _ lang st1, lc1))\n        (STEP: WThread.step L ordcr ordcw rels1 rels2 e\n                            (Thread.mk _ st1 lc1 (Configuration.global c1))\n                            (Thread.mk _ st2 lc2 gl2)):\n        step e tid rels1 rels2\n             c1 (Configuration.mk (IdentMap.add tid (existT _ _ st2, lc2) (Configuration.threads c1)) gl2)\n    .\n\n    Inductive steps rels1: forall (rels2: Writes.t) (c1 c2: Configuration.t), Prop :=\n    | steps_refl\n        c:\n        steps rels1 rels1 c c\n    | steps_step\n        rels2 rels3 e tid c1 c2 c3\n        (STEP: step e tid rels1 rels2 c1 c2)\n        (STEPS: steps rels2 rels3 c2 c3):\n        steps rels1 rels3 c1 c3\n    .\n    Hint Constructors steps: core.\n\n    Lemma steps_trans\n          rels1 rels2 rels3 c1 c2 c3\n          (STEPS1: steps rels1 rels2 c1 c2)\n          (STEPS2: steps rels2 rels3 c2 c3):\n      steps rels1 rels3 c1 c3.\n    Proof.\n      revert c3 STEPS2. induction STEPS1; i; eauto.\n    Qed.\n\n    Lemma step_ord_step\n          e tid rels1 rels2 c1 c2\n          (STEP: step e tid rels1 rels2 c1 c2):\n      OrdConfiguration.estep L ordcr ordcw e tid c1 c2.\n    Proof.\n      inv STEP. econs; eauto. inv STEP0. ss.\n    Qed.\n\n    Lemma steps_ord_steps\n          rels1 rels2 c1 c2\n          (STEPS: steps rels1 rels2 c1 c2):\n      rtc (@OrdConfiguration.all_step L ordcr ordcw) c1 c2.\n    Proof.\n      induction STEPS; eauto.\n      exploit step_ord_step; eauto. i. econs 2; eauto.\n      econs. eauto.\n    Qed.\n\n    Lemma step_future\n          e tid rels1 rels2 c1 c2\n          (WF1: Configuration.wf c1)\n          (STEP: step e tid rels1 rels2 c1 c2):\n      <<WF2: Configuration.wf c2>> /\\\n      <<GL_FUTURE: Global.future (Configuration.global c1) (Configuration.global c2)>>.\n    Proof.\n      apply step_ord_step in STEP.\n      eapply OrdConfiguration.estep_future; eauto.\n    Qed.\n\n    Lemma steps_future\n          rels1 rels2 c1 c2\n          (WF1: Configuration.wf c1)\n          (STEPS: steps rels1 rels2 c1 c2):\n      <<WF2: Configuration.wf c2>> /\\\n      <<GL_FUTURE: Global.future (Configuration.global c1) (Configuration.global c2)>>.\n    Proof.\n      induction STEPS; ss.\n      - split; ss. econs; refl.\n      - exploit step_future; eauto. i. des.\n        exploit IHSTEPS; eauto. i. des.\n        splits; ss; etrans; eauto.\n    Qed.\n\n    Lemma step_rels\n          e tid rels1 rels2 c1 c2\n          (STEP: WConfiguration.step e tid rels1 rels2 c1 c2):\n      rels2 = Writes.append L e rels1.\n    Proof.\n      unfold Writes.append.\n      inv STEP. inv STEP0; ss.\n    Qed.\n\n    Lemma step_rels_incl\n          e tid rels1 rels2 c1 c2\n          (STEP: step e tid rels1 rels2 c1 c2):\n      rels2 = rels1 \\/ exists a, rels2 = a :: rels1.\n    Proof.\n      inv STEP. inv STEP0; eauto. inv STEP.\n      unfold Writes.append. des_ifs; eauto.\n    Qed.\n\n    Lemma steps_rels_incl\n          rels1 rels2 c1 c2\n          (STEPS: steps rels1 rels2 c1 c2):\n      exists rels, rels2 = rels ++ rels1.\n    Proof.\n      induction STEPS.\n      - exists []. ss.\n      - des. exploit step_rels_incl; eauto. i. des; subst.\n        + exists rels. ss.\n        + exists (rels ++ [a]). rewrite <- List.app_assoc. ss.\n    Qed.\n  End WConfiguration.\nEnd WConfiguration.\n\n\nModule RARaceW.\n  Section RARaceW.\n    Variable L: Loc.t -> bool.\n    Variable ordcr ordcw: Ordering.t.\n\n    Definition wr_race (rels: Writes.t) (tview: TView.t) (loc: Loc.t) (ord: Ordering.t): Prop :=\n      exists to ordw,\n        (<<LOC: L loc>>) /\\\n        (<<HIGHER: Time.lt ((View.rlx (TView.cur tview)) loc) to>>) /\\\n        (<<IN: List.In (loc, to, ordw) rels>>) /\\\n        ((<<ORDW: Ordering.le ordw Ordering.strong_relaxed>>) \\/\n         (<<ORDR: Ordering.le ord Ordering.strong_relaxed>>)).\n\n    Definition ww_race (rels: Writes.t) (tview: TView.t) (loc: Loc.t) (ord: Ordering.t): Prop :=\n      exists to ordw,\n        (<<LOC: L loc>>) /\\\n        (<<HIGHER: Time.lt ((View.rlx (TView.cur tview)) loc) to>>) /\\\n        (<<IN: List.In (loc, to, ordw) rels>>) /\\\n        ((<<ORDW1: Ordering.le ordw Ordering.na>>) \\/\n         (<<ORDW2: Ordering.le ord Ordering.na>>)).\n\n    Definition ra_race (rels: Writes.t) (tview: TView.t) (e: ProgramEvent.t): Prop :=\n      (exists loc val ord,\n          (<<READ: ProgramEvent.is_reading e = Some (loc, val, ord)>>) /\\\n          (<<WRRACE: wr_race rels tview loc ord>>)) \\/\n      (exists loc val ord,\n          (<<WRITE: ProgramEvent.is_writing e = Some (loc, val, ord)>>) /\\\n          (<<WWRACE: ww_race rels tview loc ord>>)).\n\n    Definition ra_race_steps (rels: Writes.t) (c: Configuration.t): Prop :=\n      exists tid rels2 c2 lang st2 lc2 e st3,\n        (<<STEPS: WConfiguration.steps L ordcr ordcw rels rels2 c c2>>) /\\\n        (<<TID: IdentMap.find tid (Configuration.threads c2) = Some (existT _ lang st2, lc2)>>) /\\\n        (<<THREAD_STEP: lang.(Language.step) e st2 st3>>) /\\\n        (<<RARACE: ra_race rels2 (Local.tview lc2) e>>).\n\n    Definition racefree (rels: Writes.t) (c: Configuration.t): Prop :=\n      forall tid rels2 c2 lang st2 lc2 e st3\n        (STEPS: WConfiguration.steps L ordcr ordcw rels rels2 c c2)\n        (TID: IdentMap.find tid (Configuration.threads c2) = Some (existT _ lang st2, lc2))\n        (THREAD_STEP: lang.(Language.step) e st2 st3)\n        (RARACE: ra_race rels2 (Local.tview lc2) e),\n        False.\n\n    Definition racefree_syn (syn: Threads.syntax): Prop :=\n      racefree [] (Configuration.init syn).\n\n    Lemma step_racefree\n          e tid rels1 rels2 c1 c2\n          (RACEFREE: racefree rels1 c1)\n          (STEP: WConfiguration.step L ordcr ordcw e tid rels1 rels2 c1 c2):\n      racefree rels2 c2.\n    Proof.\n      ii. eapply RACEFREE; eauto. econs 2; eauto.\n    Qed.\n  End RARaceW.\nEnd RARaceW.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/ldrfra/WStep.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.33111973962899144, "lm_q1q2_score": 0.2097346415873373}}
{"text": "Require Import Crypto.Compilers.Named.PositiveContext.\nRequire Import Crypto.Compilers.Named.PositiveContext.DefaultsProperties.\nRequire Import Crypto.Compilers.Named.ContextDefinitions.\nRequire Import Crypto.Compilers.Named.InterpretToPHOASInterp.\nRequire Import Crypto.Compilers.Named.CompileWf.\nRequire Import Crypto.Compilers.Named.CompileInterp.\nRequire Import Crypto.Compilers.Named.WfFromUnit.\nRequire Import Crypto.Compilers.Named.DeadCodeEliminationInterp.\nRequire Import Crypto.Compilers.Named.WfInterp.\nRequire Import Crypto.Compilers.Syntax.\nRequire Import Crypto.Compilers.Wf.\nRequire Import Crypto.Compilers.Z.Syntax.\nRequire Import Crypto.Compilers.Z.RewriteAddToAdc.\nRequire Import Crypto.Compilers.Z.Named.RewriteAddToAdcInterp.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Decidable.\nRequire Import Crypto.Util.Bool.\n\nSection language.\n  Local Notation PContext var := (PositiveContext _ var _ internal_base_type_dec_bl).\n\n  Lemma InterpRewriteAdc\n        {t} (e : Expr t) (Hwf : Wf e)\n  : forall x, Compilers.Syntax.Interp interp_op (RewriteAdc e) x = Compilers.Syntax.Interp interp_op e x.\n  Proof.\n    intro x; unfold RewriteAdc, option_map; break_innermost_match; try reflexivity;\n      match goal with |- ?x = ?y => cut (Some x = Some y); [ congruence | ] end;\n      (etransitivity; [ symmetry; eapply @Interp_InterpToPHOAS with (t:=Arrow _ _) | ]);\n      repeat\n        repeat\n        first [ lazymatch goal with\n                | [ H : DeadCodeElimination.EliminateDeadCode _ _ = Some ?e |- Syntax.Named.Interp ?e _ = Some _ ]\n                  => let lhs := match goal with |- ?lhs = _ => lhs end in\n                     let v := fresh in\n                     (destruct lhs as [v|] eqn:?);\n                     [ apply f_equal; eapply @InterpEliminateDeadCode with (Name_beq:=BinPos.Pos.eqb);\n                       [ .. | eassumption | try eassumption | try eassumption ]; clear H | ]\n                | [ |- Syntax.Named.Interp (RewriteAddToAdc.rewrite_expr _ ?e) _ = Some _ ]\n                  => let lhs := match goal with |- ?lhs = _ => lhs end in\n                     let H := fresh in\n                     destruct lhs eqn:H; [ apply (f_equal (@Some _)); eapply @Interp_rewrite_expr in H | ]\n                | [ H : Compile.compile (?e _) _ = Some ?e'', H' : Syntax.Named.Interp ?e'' ?x = Some ?v' |- ?v' = Compilers.Syntax.Interp ?interp_op' ?e ?x ]\n                  => eapply @Interp_compile with (v:=x) (interp_op:=interp_op') in H\n                end\n              | intros; exact (@PositiveContextOk _ _ base_type_beq internal_base_type_dec_bl internal_base_type_dec_lb)\n              | progress split_andb\n              | congruence\n              | tauto\n              | solve [ auto | eapply @BinPos.Pos.eqb_eq; auto ]\n              | eapply @Wf_from_unit\n              | eapply @dec_rel_of_bool_dec_rel\n              | eapply @internal_base_type_dec_lb\n              | eapply @internal_base_type_dec_bl\n              | eapply @InterpEliminateDeadCode; [ .. | eassumption | eassumption | ]\n              | apply name_list_unique_DefaultNamesFor\n              | progress intros\n              | rewrite !@lookupb_empty\n              | eapply @wf_from_unit with (uContext:=PContext _); [ .. | eassumption ]\n              | match goal with\n                | [ H : Syntax.Named.Interp ?e ?x = Some ?a, H' : Syntax.Named.Interp ?e ?x = Some ?b |- _ ]\n                  => assert (a = b) by congruence; (subst a || subst b)\n                end\n              | lazymatch goal with\n                | [ |- Some _ = Some _ ] => fail\n                | [ |- None = Some _ ] => exfalso; eapply @wf_interp_not_None; [ .. | unfold Syntax.Named.Interp in *; eassumption ]\n                | [ |- ?x = Some _ ] => destruct x eqn:?; [ apply f_equal | ]\n                end ].\n  Qed.\nEnd language.\n\nHint Rewrite @InterpRewriteAdc using solve_wf_side_condition : reflective_interp.\n", "meta": {"author": "anonymous-code-submission-01", "repo": "sp2019-54-code", "sha": "8867f5bed0821415ec99f593b1d61f715ed4f789", "save_path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code", "path": "github-repos/coq/anonymous-code-submission-01-sp2019-54-code/sp2019-54-code-8867f5bed0821415ec99f593b1d61f715ed4f789/src/Compilers/Z/RewriteAddToAdcInterp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.20966158534864873}}
{"text": "From iris Require Import program_logic.weakestpre.\nFrom iris Require Import base_logic.lib.invariants.\nFrom st.STLCmuST Require Import types typing.\nFrom st.STLCmuVS Require Import lang wkpre generic.lift tactics.\nFrom st.backtranslations.st_sem.well_defined.logrel Require Import definition.\nFrom iris.proofmode Require Import tactics.\nFrom st.backtranslations.st_sem Require Import ghost heap_emul.base heap_emul.spec expressions.\nFrom st.prelude Require Import big_op_three.\nFrom st Require Import resources.\n\nSection compat_lemmas_easy.\n\n  Context `{Σ : !gFunctors} `{semΣ_inst : !semΣ Σ}.\n\n  Lemma compat_Var (Γ : list type) (x : var) (τ : type) :\n    Γ !! x = Some τ → open_exprel_typed Γ (%x)%Eₙₒ (%x)%Eₙₒ τ.\n  Proof.\n    intros H. iIntros (Δ vs vs') \"Hvsvs\".\n    iDestruct (big_sepL3_length _ _ _ _ with \"Hvsvs\") as \"[%eq %eq']\".\n    destruct (Var_subst_list_closed_n_length vs x) as [v [eqv ->]]. apply ids_lt_Closed_n. rewrite -eq. by eapply lookup_lt_Some.\n    destruct (Var_subst_list_closed_n_length vs' x) as [v' [eqv' ->]]. apply ids_lt_Closed_n. rewrite -eq' -eq. by eapply lookup_lt_Some.\n    rewrite /exprel_typed /=. iApply lift_val.\n    iApply ((big_sepL3_lookup _ _ _ _ x _ _ _ H eqv eqv') with \"Hvsvs\").\n  Qed.\n\n  Lemma lift_bind (Kᵢ Kₛ : list ectx_item) (Φ Ψ : valO -n> valO -n> iPropO Σ) (eᵢ eₛ : expr) :\n    ⊢ lift MaybeStuck Φ eᵢ eₛ -∗ (∀ vᵢ vₛ, Φ vᵢ vₛ -∗ lift MaybeStuck Ψ (fill Kᵢ (of_val vᵢ)) (fill Kₛ (of_val vₛ))) -∗ lift MaybeStuck Ψ (fill Kᵢ eᵢ) (fill Kₛ eₛ).\n  Proof. iIntros \"H H2\". iApply lift.lift_bind. iFrame. Qed.\n\n  Lemma compat_Unit (Γ : list type) :\n    open_exprel_typed Γ ()%Eₙₒ ()%Eₙₒ TUnit.\n  Proof.\n    iIntros (Δ vs vs') \"Hvsvs\". asimpl.\n    change ()%Eₙₒ with (of_val ()%Vₙₒ). iApply lift_val.\n    by rewrite valrel_typed_TUnit_unfold.\n  Qed.\n\n  Lemma compat_Bool (Γ : list type) (b : bool) :\n    open_exprel_typed Γ b b TBool.\n  Proof.\n    iIntros (Δ vs vs') \"Hvsvs\". asimpl.\n    change (Lit b)%Eₙₒ with (of_val b). iApply lift_val.\n    rewrite valrel_typed_TBool_unfold. by iExists _.\n  Qed.\n\n  Lemma compat_Int (Γ : list type) (z : Z) :\n    open_exprel_typed Γ z z TInt.\n  Proof.\n    iIntros (Δ vs vs') \"Hvsvs\". asimpl.\n    change (Lit z)%Eₙₒ with (of_val z). iApply lift_val.\n    rewrite valrel_typed_TInt_unfold. by iExists _.\n  Qed.\n\n  Lemma compat_BinOp (Γ : list type) (op : bin_op) (e1 e1' e2 e2' : expr) :\n      open_exprel_typed Γ e1 e1' TInt → open_exprel_typed Γ e2 e2' TInt →\n      open_exprel_typed Γ (BinOp op e1 e2) (BinOp op e1' e2') (binop_res_type op).\n  Proof.\n    intros IHe1 IHe2.\n    iIntros (Δ vs vs') \"#Hvsvs\". simpl.\n    iApply (lift_bind [BinOpLCtx op _] [BinOpLCtx op _]). by iApply IHe1. iIntros (v1 v1') \"#Hv1\".\n    iApply (lift_bind [BinOpRCtx op _] [BinOpRCtx op _]). by iApply IHe2. iIntros (v2 v2') \"#Hv2\".\n    rewrite !valrel_typed_TInt_unfold. iDestruct \"Hv1\" as (z1) \"[-> ->]\". iDestruct \"Hv2\" as (z2) \"[-> ->]\".\n    iApply lift_step. simpl. auto_STLCmuVS_step.\n    iApply lift_step_later. auto_STLCmuVS_step. iNext. simpl.\n    iApply lift_val.\n    destruct op; simpl; (rewrite valrel_typed_TInt_unfold || rewrite valrel_typed_TBool_unfold); by iExists _.\n  Qed.\n\n  Lemma compat_Seq (Γ : list type) (e1 e1' e2 e2' : expr) (τ : type) :\n      open_exprel_typed Γ e1 e1' TUnit → open_exprel_typed Γ e2 e2' τ →\n      open_exprel_typed Γ (Seq e1 e2) (Seq e1' e2') τ.\n  Proof.\n    intros IHe1 IHe2.\n    iIntros (Δ vs vs') \"#Hvsvs\".\n    iApply (lift_bind [SeqCtx _] [SeqCtx _]). by iApply IHe1. iIntros (v1 v1') \"#Hv1\".\n    rewrite !valrel_typed_TUnit_unfold. iDestruct \"Hv1\" as \"[-> ->]\".\n    iApply lift_step. auto_STLCmuVS_step.\n    iApply lift_step_later. auto_STLCmuVS_step. iNext. simpl.\n    by iApply IHe2.\n  Qed.\n\n  Lemma compat_Pair (Γ : list type) (e1 e1' e2 e2' : expr) (τ1 τ2 : type) :\n      open_exprel_typed Γ e1 e1' τ1 → open_exprel_typed Γ e2 e2' τ2 →\n      open_exprel_typed Γ (e1, e2)%Eₙₒ (e1', e2')%Eₙₒ (τ1 × τ2)%Tₛₜ.\n  Proof.\n    intros IHe1 IHe2.\n    iIntros (Δ vs vs') \"#Hvsvs\".\n    iApply (lift_bind [PairLCtx _] [PairLCtx _]). by iApply IHe1. iIntros (v1 v1') \"#Hv1\".\n    iApply (lift_bind [PairRCtx _] [PairRCtx _]). by iApply IHe2. iIntros (v2 v2') \"#Hv2\".\n    simpl. change (of_val ?v1, of_val ?v2)%Eₙₒ with (of_val (PairV v1 v2)). iApply lift_val.\n    rewrite valrel_typed_TProd_unfold. repeat iExists _; eauto.\n  Qed.\n\n  Lemma compat_Fst (Γ : list type) (e e' : expr) (τ1 τ2 : type) :\n      open_exprel_typed Γ e e' (τ1 × τ2)%Tₛₜ → open_exprel_typed Γ (Fst e) (Fst e') τ1.\n  Proof.\n    intros IHe.\n    iIntros (Δ vs vs') \"#Hvsvs\".\n    iApply (lift_bind [FstCtx] [FstCtx]). by iApply IHe. iIntros (v v') \"#Hv\".\n    rewrite !valrel_typed_TProd_unfold. iDestruct \"Hv\" as (v1 v2 v1' v2') \"(-> & -> & H1 & H2)\".\n    iApply lift_step. auto_STLCmuVS_step.\n    iApply lift_step_later. auto_STLCmuVS_step. iNext. simplify_custom. by iApply lift_val.\n  Qed.\n\n  Lemma compat_Snd (Γ : list type) (e e' : expr) (τ1 τ2 : type) :\n      open_exprel_typed Γ e e' (τ1 × τ2)%Tₛₜ → open_exprel_typed Γ (Snd e) (Snd e') τ2.\n  Proof.\n    intros IHe.\n    iIntros (Δ vs vs') \"#Hvsvs\".\n    iApply (lift_bind [SndCtx] [SndCtx]). by iApply IHe. iIntros (v v') \"#Hv\".\n    rewrite !valrel_typed_TProd_unfold. iDestruct \"Hv\" as (v1 v2 v1' v2') \"(-> & -> & H1 & H2)\".\n    iApply lift_step. auto_STLCmuVS_step.\n    iApply lift_step_later. auto_STLCmuVS_step. iNext. simplify_custom. by iApply lift_val.\n  Qed.\n\n  Lemma compat_InjL (Γ : list type) (e e' : expr) (τ1 τ2 : type) :\n    open_exprel_typed Γ e e' τ1 → open_exprel_typed Γ (InjL e) (InjL e') (τ1 + τ2)%Tₛₜ.\n  Proof.\n    intros IHe.\n    iIntros (Δ vs vs') \"#Hvsvs\".\n    iApply (lift_bind [InjLCtx] [InjLCtx]). by iApply IHe. iIntros (v1 v1') \"#Hv1\".\n    simpl. change (InjL (of_val ?v))%Eₙₒ with (of_val (InjLV v)). iApply lift_val.\n    rewrite valrel_typed_TSum_unfold. repeat iExists _; eauto.\n  Qed.\n\n  Lemma compat_InjR (Γ : list type) (e e' : expr) (τ1 τ2 : type) :\n    open_exprel_typed Γ e e' τ2 → open_exprel_typed Γ (InjR e) (InjR e') (τ1 + τ2)%Tₛₜ.\n  Proof.\n    intros IHe.\n    iIntros (Δ vs vs') \"#Hvsvs\".\n    iApply (lift_bind [InjRCtx] [InjRCtx]). by iApply IHe. iIntros (v2 v2') \"#Hv2\".\n    simpl. change (InjR (of_val ?v))%Eₙₒ with (of_val (InjRV v)). iApply lift_val.\n    rewrite valrel_typed_TSum_unfold. repeat iExists _; eauto.\n  Qed.\n\n  Lemma compat_Case (Γ : list type) (e0 e0' e1 e1' e2 e2' : expr) (τ1 τ2 τ3 : type) :\n      open_exprel_typed Γ e0 e0' (τ1 + τ2)%Tₛₜ\n      → open_exprel_typed (τ1 :: Γ) e1 e1' τ3\n      → open_exprel_typed (τ2 :: Γ) e2 e2' τ3 → open_exprel_typed Γ (Case e0 e1 e2) (Case e0' e1' e2') τ3.\n  Proof.\n    intros IHe0 IHe1 IHe2.\n    iIntros (Δ vs vs') \"#Hvsvs\".\n    iApply (lift_bind [CaseCtx _ _] [CaseCtx _ _]). by iApply IHe0. iIntros (v v') \"#Hv\".\n    rewrite !valrel_typed_TSum_unfold. iDestruct \"Hv\" as (vi vi') \"[(-> & -> & H) | (-> & -> & H)]\".\n    - iApply lift_step. auto_STLCmuVS_step. iApply lift_step_later. auto_STLCmuVS_step. iNext. simplify_custom.\n      rewrite !subst_list_val_cons. iApply IHe1. simpl. auto.\n    - iApply lift_step. auto_STLCmuVS_step. iApply lift_step_later. auto_STLCmuVS_step. iNext. simplify_custom.\n      rewrite !subst_list_val_cons. iApply IHe2. simpl. auto.\n  Qed.\n\n  Lemma compat_If (Γ : list type) (e0 e0' e1 e1' e2 e2' : expr) (τ : type) :\n    open_exprel_typed Γ e0 e0' TBool → open_exprel_typed Γ e1 e1' τ → open_exprel_typed Γ e2 e2' τ →\n    open_exprel_typed Γ (If e0 e1 e2) (If e0' e1' e2') τ.\n  Proof.\n    intros IHe0 IHe1 IHe2.\n    iIntros (Δ vs vs') \"#Hvsvs\".\n    iApply (lift_bind [IfCtx _ _] [IfCtx _ _]). by iApply IHe0. iIntros (v v') \"#Hv\".\n    rewrite !valrel_typed_TBool_unfold. iDestruct \"Hv\" as (b) \"[-> ->]\".\n    destruct b; (iApply lift_step; first by auto_STLCmuVS_step); (iApply lift_step_later; first by auto_STLCmuVS_step); iNext; simpl;\n      [by iApply IHe1 | by iApply IHe2].\n  Qed.\n\n  Lemma compat_LetIn (Γ : list type) (e1 e1' e2 e2' : expr) (τ1 τ2 : type) :\n      open_exprel_typed Γ e1 e1' τ1 → open_exprel_typed (τ1 :: Γ) e2 e2' τ2 →\n      open_exprel_typed Γ (LetIn e1 e2) (LetIn e1' e2') τ2.\n  Proof.\n    intros IHe1 IHe2.\n    iIntros (Δ vs vs') \"#Hvsvs\".\n    iApply (lift_bind [LetInCtx _] [LetInCtx _]). by iApply IHe1. iIntros (v1 v1') \"#Hv1\".\n    iApply lift_step; first by auto_STLCmuVS_step. iApply lift_step_later; first by auto_STLCmuVS_step. iNext. simplify_custom.\n    rewrite !subst_list_val_cons. iApply IHe2. simpl. auto.\n  Qed.\n\n  Lemma compat_Lam (Γ : list type) (e e' : expr) (τ1 τ2 : type) :\n    open_exprel_typed (τ1 :: Γ) e e' τ2 →\n    open_exprel_typed Γ (Lam e) (Lam e') (τ1 ⟶ τ2)%Tₛₜ.\n  Proof.\n    intros IHe.\n    iIntros (Δ vs vs') \"#Hvsvs\". simpl.\n    change (Lam ?e) with (of_val (LamV e)). iApply lift_val.\n    rewrite valrel_typed_TArrow_unfold. iModIntro. iIntros (w w') \"Hww\".\n    iApply lift_step; first by auto_STLCmuVS_step. iApply lift_step_later; first by auto_STLCmuVS_step. iNext. simplify_custom.\n    rewrite !subst_list_val_cons. iApply IHe. simpl. auto.\n  Qed.\n\n  Lemma compat_App (Γ : list type) (e1 e1' e2 e2' : expr) (τ1 τ2 : type) :\n      open_exprel_typed Γ e1 e1' (τ1 ⟶ τ2)%Tₛₜ → open_exprel_typed Γ e2 e2' τ1 →\n      open_exprel_typed Γ (e1 e2) (e1' e2') τ2.\n  Proof.\n    intros IHe1 IHe2.\n    iIntros (Δ vs vs') \"#Hvsvs\".\n    iApply (lift_bind [AppLCtx _] [AppLCtx _]). by iApply IHe1. iIntros (v1 v1') \"#Hv1\".\n    iApply (lift_bind [AppRCtx _] [AppRCtx _]). by iApply IHe2. iIntros (v2 v2') \"#Hv2\".\n    rewrite /= valrel_typed_TArrow_unfold. by iApply \"Hv1\".\n  Qed.\n\n  Lemma compat_Fold (Γ : list type) (e e' : expr) (τ : {bind type}) :\n      open_exprel_typed Γ e e' τ.[TRec τ/] → open_exprel_typed Γ (Fold e) (Fold e') (TRec τ).\n  Proof.\n    intros IHe.\n    iIntros (Δ vs vs') \"#Hvsvs\". simpl.\n    iApply (lift_bind [FoldCtx] [FoldCtx]). by iApply IHe. iLöb as \"IHlob\". iIntros (v v') \"#Hv\".\n    simpl. change (Fold (of_val ?v)) with (of_val (FoldV v)). iApply lift_val.\n    rewrite valrel_typed_TRec_unfold. repeat iExists _; eauto.\n  Qed.\n\n  Lemma compat_Unfold (Γ : list type) (e e' : expr) (τ : {bind type}) :\n    open_exprel_typed Γ e e' (TRec τ) → open_exprel_typed Γ (Unfold e) (Unfold e') τ.[TRec τ/].\n  Proof.\n    intros IHe.\n    iIntros (Δ vs vs') \"#Hvsvs\". simpl.\n    iApply (lift_bind [UnfoldCtx] [UnfoldCtx]). by iApply IHe. iIntros (v v') \"#Hv\".\n    rewrite valrel_typed_TRec_unfold. iDestruct \"Hv\" as (w w') \"(-> & -> & Hw)\".\n    iApply lift_step; first by auto_STLCmuVS_step. iApply lift_step_later; first by auto_STLCmuVS_step. iNext. simplify_custom.\n    by iApply lift_val.\n  Qed.\n\nEnd compat_lemmas_easy.\n", "meta": {"author": "scaup", "repo": "sem_backs_st", "sha": "e14aa7f421de94df5c1369d2b4b44d8644243cec", "save_path": "github-repos/coq/scaup-sem_backs_st", "path": "github-repos/coq/scaup-sem_backs_st/sem_backs_st-e14aa7f421de94df5c1369d2b4b44d8644243cec/theories/backtranslations/st_sem/well_defined/logrel/compat_lemmas_easy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953797290153, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.20961303917149016}}
{"text": "From SFS Require Import cps cps_util set_util identifiers ctx Ensembles_util\n     List_util functions tactics map_util.\n\nFrom SFS Require Import heap heap_impl heap_defs heap_equiv space_sem\n     cc_log_rel closure_conversion closure_conversion_util bounds\n     invariants GC closure_conversion_correct.\n\nFrom Coq Require Import ZArith.Znumtheory Relations.Relations Arith.Wf_nat\n                        Lists.List MSets.MSets MSets.MSetRBT Numbers.BinNums NArith.Ndist\n                        NArith.BinNat PArith.BinPos Sets.Ensembles Omega Permutation.\n\nImport ListNotations.\n\nOpen Scope ctx_scope.\nOpen Scope fun_scope.\nClose Scope Z_scope.\n\nModule Top.\n\n  Module CC := ClosureConversionCorrect MHeap.\n  \n  Import MHeap CC.Inv.Size.Util.C.LR.Sem.GC.Equiv\n         CC.Inv.Size.Util.C.LR.Sem.GC.Equiv.Defs\n         CC.Inv.Size.Util.C.LR.Sem.GC CC.Inv.Size.Util.C.LR.Sem\n         CC.Inv.Size.Util.C.LR CC.Inv.Size.Util.C CC.Inv.Size.Util\n         CC.Inv.Size CC.Inv CC.\n\n  Definition ct := CC.Inv.Size.Util.clo_tag. \n\n  Definition install_env Γ :=\n    let (lenv, H1) := alloc (Constr ct []) emp in\n    (M.set Γ (Loc lenv) (M.empty _), H1).\n\n  Lemma key_set_empty A :\n    key_set (M.empty A) <--> Empty_set _.\n  Proof. \n    split; eauto with Ensembles_DB.\n    intros x k. unfold In, key_set in *.\n    rewrite M.gempty in k. contradiction.\n  Qed.\n\n  Lemma closure_conversion_correct_lr_closed (k : nat) (e1 e2 : exp) (C : exp_ctx) (Γ : var) K rho2 H2 :\n    (rho2, H2) = install_env Γ ->\n    ~ Γ \\in bound_var e1 ->\n    unique_bindings e1 ->\n    has_true_mut e1 ->\n    \n    Closure_conversion ct (Empty_set _) (Empty_set _) id ct Γ [] e1 e2 C ->\n    \n    (forall j, (e1, M.empty _, emp) ⪯ ^ (k ; j ;\n                              Pre (Empty_set _) 0 K; PreG;\n                              Post 0 0 K; PostG)\n          (C |[ e2 ]|, rho2, H2)).\n  Proof with (now eauto with Ensembles_DB).\n    unfold install_env.\n    destruct (alloc (Constr ct []) emp) as [lenv Η2] eqn:Ha. \n    intros Ha' Hnin Hun Htm Hcc. inv Ha'. \n    intros j.\n    eapply Closure_conversion_correct in Hcc.\n    eapply cc_approx_exp_rel_mon_pre.\n    - eassumption.\n    - intros [[H1 rho1] e1'] [[H2 rho2] e2'] Hpre.\n      eapply PreSubsetCompat with (Funs := Empty_set var).\n      eassumption. rewrite Intersection_Empty_set_abs_l...\n    - intros j1. eapply cc_approx_env_Empty_set.\n    - intros j2. split.\n      + rewrite env_locs_set_In, <- env_locs_Empty; [| reflexivity ].\n        rewrite !Union_Empty_set_neut_r.\n        rewrite reach_unfold.\n        simpl. rewrite post_Singleton; [| eapply gas; eassumption ].  \n        simpl. rewrite reach'_Empty_set.\n        rewrite !Union_Empty_set_neut_r.\n        intros x b Hi Hget; inv Hi. eapply gas in Ha.\n        subst_exp...\n      + split.\n        * unfold FV.\n          rewrite key_set_empty.\n          rewrite FromList_nil, !Setminus_Empty_set_neut_r. \n          rewrite !Union_Empty_set_neut_r at 1.\n          rewrite Setminus_Empty_set_neut_r, !Union_Empty_set_neut_r.\n          reflexivity.\n        * do 2 eexists. split; [| split ].\n          rewrite M.gss. reflexivity. \n          eapply gas. eassumption.\n          now constructor. \n    - intros j1 x _ Hin. inv Hin.\n    - unfold FV.\n      rewrite FromList_nil, !Setminus_Empty_set_neut_r, !image_Empty_set, !Union_Empty_set_neut_r at 1.\n      rewrite Setminus_Empty_set_neut_r, !Union_Empty_set_neut_r.\n      eapply Disjoint_Singleton_l. eassumption.\n    - unfold FV.\n      rewrite FromList_nil, !Setminus_Empty_set_neut_r. \n      rewrite !Union_Empty_set_neut_r at 1.\n      rewrite Setminus_Empty_set_neut_r, !Union_Empty_set_neut_r.\n      intros x Hin. inv Hin.\n    - eassumption.\n    - eassumption.\n    - unfold FV.\n      rewrite FromList_nil, !Setminus_Empty_set_neut_r. \n      rewrite !Union_Empty_set_neut_r at 1.\n      rewrite Setminus_Empty_set_neut_r, !Union_Empty_set_neut_r.\n      now eauto with Ensembles_DB.\n\n      Grab Existential Variables.\n      tci. tci. exact id.\n  Qed.\n\n\n  Lemma key_set_get {A} rho1 x (v : A) :\n    M.get x rho1 = Some v ->\n    x \\in key_set rho1. \n  Proof.\n    intros. unfold key_set, In. rewrite H. eauto.\n  Qed. \n\n  Lemma key_set_getlist {A} rho1 xs (vs : list A) :\n    getlist xs rho1 = Some vs ->\n    FromList xs \\subset key_set rho1. \n  Proof with (now eauto with Ensembles_DB).\n    revert rho1 vs. induction xs; intros rho1 vs1 Hget; inv Hget.\n    - normalize_sets...\n    - normalize_sets.\n      destruct (M.get a rho1) eqn:Hgeta; try congruence. \n      destruct (getlist xs rho1) eqn:Hgetl; try congruence. \n      inv H0.\n      eapply Union_Included.\n      + eapply Singleton_Included. eapply key_set_get.\n        eassumption.\n      + eauto.\n  Qed. \n      \n      \n  (** ** Top-level theorem *) \n  Lemma closure_conversion_correct_top\n        (k : nat) (j : nat) (e1 e2 : exp) (C : exp_ctx) (Γ : var) (* dummy varaiable for environment *)\n        r1 c1 m1 :\n    \n    (* The source program has unique binders *)\n    unique_bindings e1 ->\n    (* Requirement for mutual rec function blocks *)\n    has_true_mut e1 ->\n    (* dummy var is fresh *)\n    ~ Γ \\in bound_var e1 ->\n            \n    (* C[e2] is the closure converted program *)\n    Closure_conversion ct (Empty_set _) (Empty_set _) id ct Γ [] e1 e2 C ->\n    \n    (* the source evaluates *)\n    big_step emp (M.empty _) e1 r1 c1 m1 ->\n\n    (* and it is not a stuck program -- because currently we don't assume that r1 is a value (it can be out-of-time-exception) *)\n    not_stuck emp (M.empty _) e1 ->\n    \n    exists (r2 : ans) (c2 m2 : nat) (b : Inj),\n      (* the target evaluates *)\n      big_step_GC_cc emp (M.empty _) (C |[ e2 ]|) r2 c2 m2 /\\\n      (* time bounds *)\n      c1 <= c2 <= Ktime * c1 /\\\n      (* space bounds *)\n      m2 <= m1 + (cost_space_exp e1) + 1 /\\\n      (* the results are related *)\n      r1 ≺ ^ (k ; j ; PreG ; PostG ; b ) r2.  \n  Proof with (now eauto with Ensembles_DB).\n    unfold install_env.\n    destruct (alloc (Constr ct []) emp) as [lenv H2'] eqn:Ha.\n    intros Hun Htm Hnin Hcc Hbs Hns. \n    assert (Heq : (e1, M.empty _, emp) ⪯ ^ (k + c1 ; j ;\n                                            Pre (Empty_set _) 0 1; PreG;\n                                            Post 0 0 1; PostG)\n                                             (C |[ e2 ]|, (M.set Γ (Loc lenv) (M.empty value)), H2')).\n    { eapply closure_conversion_correct_lr_closed; try eassumption.\n      unfold install_env. rewrite Ha. reflexivity. }\n    \n    edestruct Heq with (rho2' := M.empty value) (H2'0 := @emp block) (b2 := @id var)\n      as (r2 & c2 & m2 & b & Hbs2 & Hin & Hres); [ | | | | | | eassumption | | ].\n    - reflexivity.\n    - clear; now firstorder.\n    - eapply Closure_conversion_toplevel_closed_cc in Hcc. unfold closed_exp in *.\n      rewrite Hcc. split; intros x v Hin; inv Hin.\n    - clear; now firstorder.\n    - unfold Pre. unfold size_heap.\n      rewrite !plus_O_n at 1.\n      rewrite PS_cardinal_empty.\n      simpl. rewrite <- plus_n_O.\n      rewrite HL.size_with_measure_emp. omega.\n      eapply PS_cardinal_empty_l. \n      rewrite <- mset_eq. reflexivity. \n    - eapply le_plus_r.\n    - eassumption.\n    - unfold Post in Hin. destruct Hin as [[Ht1 Ht2] Hm]. do 4 eexists. split. eassumption.\n      split; [| split ].\n      + omega.\n      + rewrite !plus_O_n in *. eapply le_trans. eassumption.\n        eapply Nat.max_lub. omega.\n        unfold cost_space_heap, cost_heap in *.\n        rewrite HL.max_with_measure_emp in *. \n        rewrite Nat_as_OT.max_0_r. omega.\n      + rewrite cc_approx_val_eq in Hres.\n        eapply cc_approx_val_monotonic. eassumption. omega.\n  Qed. \n\n  Lemma closure_conversion_correct_top_div\n        (k : nat) (j : nat) (e1 e2 : exp) (C : exp_ctx) (Γ : var) (* dummy varaiable for environment *)\n        m1 :\n    \n     (* The source program has unique binders *)\n     unique_bindings e1 ->\n     has_true_mut e1 ->\n     ~ Γ \\in bound_var e1 ->\n     \n     (* C[e2] is the closure converted program *)\n     Closure_conversion ct (Empty_set _) (Empty_set _) id ct Γ [] e1 e2 C ->\n            \n     (* the source diverges *)\n     div_src emp (M.empty _) e1 m1 ->\n    \n    exists (m2 : natinf),\n      (* the target diverges *)\n      div_trg emp (M.empty _) (C |[ e2 ]|) m2 /\\\n      match m1, m2 with\n      | ni m1, ni m2 => m2 <= m1 + (cost_space_exp e1) + 1\n      | ni _, inf => False                                                          \n      | inf, _ => True\n      end.\n  Proof with (now eauto with Ensembles_DB).\n    destruct (alloc (Constr ct []) emp) as [lenv H2'] eqn:Ha. \n    intros Hun Htm Hnin Hcc Hdiv. \n\n    assert (Hns: not_stuck emp (M.empty _)  e1).\n    { intros j'. eexists OOT. edestruct (Hdiv j') as [m' [Hbs Hleq]].\n      eexists. eassumption. }\n\n    eexists (match m1 with\n             | infty => infty\n             | ni m0 => ni (m0 + cost_space_exp e1 + 1)\n             end).\n\n    split; [| now  destruct m1; eauto ]. \n    \n    intros i. destruct (Hdiv i) as [m1' [Hbs Hleq]].  \n    assert (Heq : (e1, M.empty _, emp) ⪯ ^ (i ; j ;\n                                              Pre (Empty_set _) 0 1; PreG;\n                                              Post 0 0 1; PostG)\n                                               (C |[ e2 ]|, (M.set Γ (Loc lenv) (M.empty value)), H2')).\n      { eapply closure_conversion_correct_lr_closed; try eassumption.\n        unfold install_env. rewrite Ha. reflexivity. }\n      \n      edestruct Heq with (rho2' := M.empty value) (H2'0 := @emp block) (b2 := @id var)\n      as (r2 & c2 & m2 & b & Hbs2 & Hin & Hres); [ | | | | | | eassumption | | ].\n    - reflexivity.\n    - clear; now firstorder.\n    - eapply Closure_conversion_toplevel_closed_cc in Hcc. unfold closed_exp in *.\n      rewrite Hcc. split; intros x v Hin; inv Hin.\n    - clear; now firstorder.\n    - unfold Pre. unfold size_heap.\n      rewrite !plus_O_n at 1.\n      rewrite PS_cardinal_empty.\n      simpl. rewrite HL.size_with_measure_emp. omega.\n      eapply PS_cardinal_empty_l. \n      rewrite <- mset_eq. reflexivity. \n    - reflexivity.\n    - eassumption.\n    - rewrite cc_approx_val_eq in Hres. simpl in Hres.\n      destruct r2; try contradiction.\n      \n      assert (Hmon : exists m2', m2' <= m2 /\\ big_step_GC_cc emp (M.empty _) (C |[ e2 ]|) OOT i m2' ).\n      { eapply big_step_GC_cc_OOT_mon. eassumption.\n        unfold Post in *. omega. }\n      edestruct Hmon as [m2' [Hm1 Hm2]]. eexists. split. eassumption.\n      destruct m1; eauto. now constructor.\n      destruct Hin as [_ Hmem]. eapply le_ni_le. eapply le_trans. eassumption.\n      eapply le_trans. eassumption. simpl.\n      eapply Nat_as_DT.max_lub. omega.\n      unfold cost_space_heap, cost_heap in *.\n      rewrite HL.max_with_measure_emp in *. \n      rewrite Nat_as_OT.max_0_r.\n      eapply ni_le_le in Hleq. omega.\n  Qed. \n\nEnd Top.\n\nPrint Assumptions Top.closure_conversion_correct_top.\n\nPrint Assumptions Top.closure_conversion_correct_top_div.\n", "meta": {"author": "zoep", "repo": "safe-for-space", "sha": "0e0d0cf2ee2a2f8ee90aa5c6c5e1ff6052eed9a5", "save_path": "github-repos/coq/zoep-safe-for-space", "path": "github-repos/coq/zoep-safe-for-space/safe-for-space-0e0d0cf2ee2a2f8ee90aa5c6c5e1ff6052eed9a5/toplevel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.20961302593374945}}
{"text": "From mathcomp\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun.\nFrom fcsl\nRequire Import prelude pred pcm unionmap heap.\nFrom HTT\nRequire Import stmod stsep stlog stlogR.\nFrom SSL\nRequire Import core.\nFrom Hammer Require Import Hammer.\n(* Configure Hammer *)\nSet Hammer ATPLimit 60.\nUnset Hammer Eprover.\nUnset Hammer Vampire.\nAdd Search Blacklist \"fcsl.\".\nAdd Search Blacklist \"HTT.\".\nAdd Search Blacklist \"Coq.ssr.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.bigop\".\nAdd Search Blacklist \"mathcomp.ssreflect.choice\".\nAdd Search Blacklist \"mathcomp.ssreflect.div\".\nAdd Search Blacklist \"mathcomp.ssreflect.finfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.fintype\".\nAdd Search Blacklist \"mathcomp.ssreflect.path\".\nAdd Search Blacklist \"mathcomp.ssreflect.tuple\".\n\n\nRequire Import common.\n\nLemma pure1 : (1) = (1). intros; hammer. Qed.\nHint Resolve pure1: ssl_pure.\nLemma pure2 (k1 : nat) : (k1) <= (7) -> (0) <= (k1) -> ((if (0) <= (k1) then k1 else 0)) = ((if (0) <= (k1) then k1 else 0)). intros; hammer. Qed.\nHint Resolve pure2: ssl_pure.\nLemma pure3 (k1 : nat) : (k1) <= (7) -> (0) <= (k1) -> ((if (k1) <= (7) then k1 else 7)) = ((if (k1) <= (7) then k1 else 7)). intros; hammer. Qed.\nHint Resolve pure3: ssl_pure.\nLemma pure4 (a : nat) : (a) < ((a) + (3)).\n  (* intros; hammer. *)\n  scongruence use: addSnnS, leq_addr.\nQed.\nHint Resolve pure4: ssl_pure.\nLemma pure5 (a : nat) : (a) < ((a) + (3)).\n  (* intros; hammer. *)\n  scongruence use: addSnnS, leq_addr.\nQed.\nHint Resolve pure5: ssl_pure.\nLemma pure6 (sz1x : nat) (sz2x : nat) : (0) <= (sz1x) -> (0) <= (sz2x) -> (0) <= (((1) + (sz1x)) + (sz2x)) -> (0) <= ((sz1x) + (1)). intros; hammer. Qed.\nHint Resolve pure6: ssl_pure.\nLemma pure7 (sz1x : nat) (sz2x : nat) : (0) <= (((1) + (sz1x)) + (sz2x)) -> (0) <= (sz1x) -> (0) <= (sz2x) -> ((((1) + (sz1x)) + (sz2x)) + (1)) = (((1) + ((sz1x) + (1))) + (sz2x)). intros; hammer. Qed.\nHint Resolve pure7: ssl_pure.\nLemma pure8 (k1 : nat) (lo2x : nat) (vx1 : nat) (hi1x : nat) (hi2x : nat) : (k1) <= (vx1) -> (vx1) <= (lo2x) -> (vx1) <= (7) -> (k1) <= (7) -> (hi1x) <= (vx1) -> (0) <= (vx1) -> (0) <= (k1) -> ((if ((if (hi2x) <= (vx1) then vx1 else hi2x)) <= (k1) then k1 else (if (hi2x) <= (vx1) then vx1 else hi2x))) = ((if (hi2x) <= (vx1) then vx1 else hi2x)).\n  (* intros; hammer. *)\n  intros.\n  destruct (hi2x <= vx1) eqn:H6;\n  sauto.\nQed.\nHint Resolve pure8: ssl_pure.\nLemma pure9 (k1 : nat) (lo2x : nat) (vx1 : nat) (hi1x : nat) (lo1x : nat) : (k1) <= (vx1) -> (vx1) <= (lo2x) -> (vx1) <= (7) -> (k1) <= (7) -> (hi1x) <= (vx1) -> (0) <= (vx1) -> (0) <= (k1) -> ((if (k1) <= ((if (vx1) <= (lo1x) then vx1 else lo1x)) then k1 else (if (vx1) <= (lo1x) then vx1 else lo1x))) = ((if (vx1) <= ((if (k1) <= (lo1x) then k1 else lo1x)) then vx1 else (if (k1) <= (lo1x) then k1 else lo1x))).\n  (* intros; hammer. *)\n  intros.\n  destruct (vx1 <= lo1x) eqn:H6;\n  destruct (k1 <= lo1x) eqn:H7;\n  sauto.\nQed.\nHint Resolve pure9: ssl_pure.\nLemma pure10 (hi1x : nat) (k1 : nat) (vx1 : nat) (lo2x : nat) : (k1) <= (vx1) -> (vx1) <= (lo2x) -> (vx1) <= (7) -> (k1) <= (7) -> (hi1x) <= (vx1) -> (0) <= (vx1) -> (0) <= (k1) -> ((if (hi1x) <= (k1) then k1 else hi1x)) <= (vx1). intros; hammer. Qed.\nHint Resolve pure10: ssl_pure.\nLemma pure11 (sz2x : nat) (sz1x : nat) : (0) <= (((1) + (sz1x)) + (sz2x)) -> (0) <= (sz1x) -> (0) <= (sz2x) -> (0) <= ((sz2x) + (1)). intros; hammer. Qed.\nHint Resolve pure11: ssl_pure.\nLemma pure12 (sz1x : nat) (sz2x : nat) : (0) <= (((1) + (sz1x)) + (sz2x)) -> (0) <= (sz1x) -> (0) <= (sz2x) -> ((((1) + (sz1x)) + (sz2x)) + (1)) = (((1) + (sz1x)) + ((sz2x) + (1))). intros; hammer. Qed.\nHint Resolve pure12: ssl_pure.\nLemma pure13 (k1 : nat) (lo2x : nat) (vx1 : nat) (hi1x : nat) (lo1x : nat) : (vx1) <= (lo2x) -> (vx1) <= (7) -> ~~ ((k1) <= (vx1)) -> (k1) <= (7) -> (hi1x) <= (vx1) -> (0) <= (vx1) -> (0) <= (k1) -> ((if (k1) <= ((if (vx1) <= (lo1x) then vx1 else lo1x)) then k1 else (if (vx1) <= (lo1x) then vx1 else lo1x))) = ((if (vx1) <= (lo1x) then vx1 else lo1x)).\n  (* intros; hammer. *)\n  intros.\n  destruct (vx1 <= lo1x) eqn:H6;\n  sauto.\nQed.\nHint Resolve pure13: ssl_pure.\nLemma pure14 (k1 : nat) (lo2x : nat) (vx1 : nat) (hi1x : nat) (hi2x : nat) : (vx1) <= (lo2x) -> (vx1) <= (7) -> ~~ ((k1) <= (vx1)) -> (k1) <= (7) -> (hi1x) <= (vx1) -> (0) <= (vx1) -> (0) <= (k1) -> ((if ((if (hi2x) <= (vx1) then vx1 else hi2x)) <= (k1) then k1 else (if (hi2x) <= (vx1) then vx1 else hi2x))) = ((if ((if (hi2x) <= (k1) then k1 else hi2x)) <= (vx1) then vx1 else (if (hi2x) <= (k1) then k1 else hi2x))).\n  (* intros; hammer. *)\n  intros.\n  destruct (hi2x <= vx1) eqn:H6;\n  destruct (hi2x <= k1) eqn:H7;\n  sauto.\nQed.\nHint Resolve pure14: ssl_pure.\nLemma pure15 (vx1 : nat) (k1 : nat) (lo2x : nat) (hi1x : nat) : (vx1) <= (lo2x) -> (vx1) <= (7) -> ~~ ((k1) <= (vx1)) -> (k1) <= (7) -> (hi1x) <= (vx1) -> (0) <= (vx1) -> (0) <= (k1) -> (vx1) <= ((if (k1) <= (lo2x) then k1 else lo2x)).\n  (* intros; hammer. *)\n  intros.\n  rewrite -ltnNge in H1.\n  sauto.\nQed.\nHint Resolve pure15: ssl_pure.\n\nDefinition bst_insert_type :=\n  forall (vprogs : ptr * ptr),\n  {(vghosts : nat * nat * nat * nat)},\n  STsep (\n    fun h =>\n      let: (x, retv) := vprogs in\n      let: (k, n, lo, hi) := vghosts in\n      exists h_bst_xnlohi_a,\n      (0) <= (k) /\\ (0) <= (n) /\\ (k) <= (7) /\\ h = retv :-> (k) \\+ h_bst_xnlohi_a /\\ bst x n lo hi h_bst_xnlohi_a,\n    [vfun (_: unit) h =>\n      let: (x, retv) := vprogs in\n      let: (k, n, lo, hi) := vghosts in\n      exists hi1 lo1 n1 y,\n      exists h_bst_yn1lo1hi1_b,\n      (hi1) == ((if (hi) <= (k) then k else hi)) /\\ (lo1) == ((if (k) <= (lo) then k else lo)) /\\ (n1) == ((n) + (1)) /\\ h = retv :-> (y) \\+ h_bst_yn1lo1hi1_b /\\ bst y n1 lo1 hi1 h_bst_yn1lo1hi1_b\n    ]).\n\nProgram Definition bst_insert : bst_insert_type :=\n  Fix (fun (bst_insert : bst_insert_type) vprogs =>\n    let: (x, retv) := vprogs in\n    Do (\n      k1 <-- @read nat retv;\n      if (x) == (null)\n      then\n        y1 <-- allocb null 3;\n        retv ::= y1;;\n        (y1 .+ 1) ::= null;;\n        (y1 .+ 2) ::= null;;\n        y1 ::= k1;;\n        ret tt\n      else\n        vx1 <-- @read nat x;\n        lx1 <-- @read ptr (x .+ 1);\n        rx1 <-- @read ptr (x .+ 2);\n        if (k1) <= (vx1)\n        then\n          bst_insert (lx1, retv);;\n          y11 <-- @read ptr retv;\n          retv ::= x;;\n          (x .+ 1) ::= y11;;\n          ret tt\n        else\n          bst_insert (rx1, retv);;\n          y11 <-- @read ptr retv;\n          retv ::= x;;\n          (x .+ 2) ::= y11;;\n          ret tt\n    )).\nObligation Tactic := intro; move=>[x retv]; ssl_program_simpl.\nNext Obligation.\nssl_ghostelim_pre.\nmove=>[[[k n] lo] hi].\nex_elim h_bst_xnlohi_a.\nmove=>[phi_self0] [phi_self1] [phi_self2].\nmove=>[sigma_self].\nsubst h_self.\nmove=>H_bst_xnlohi_a.\nssl_ghostelim_post.\ntry rename h_bst_yn1lo1hi1_b into h_bst_yn1lo1hi1_a.\ntry rename H_bst_yn1lo1hi1_b into H_bst_yn1lo1hi1_a.\ntry rename h_bst_yn1lo1hi1_a into h_bst_yn1lo1hikkhi_a.\ntry rename H_bst_yn1lo1hi1_a into H_bst_yn1lo1hikkhi_a.\ntry rename h_bst_yn1lo1hikkhi_a into h_bst_yn1kloklohikkhi_a.\ntry rename H_bst_yn1lo1hikkhi_a into H_bst_yn1kloklohikkhi_a.\ntry rename h_bst_yn1kloklohikkhi_a into h_bst_ynkloklohikkhi_a.\ntry rename H_bst_yn1kloklohikkhi_a into H_bst_ynkloklohikkhi_a.\nssl_read retv.\ntry rename k into k1.\ntry rename h_bst_ynkloklohikkhi_a into h_bst_ynk1lok1lohik1k1hi_a.\ntry rename H_bst_ynkloklohikkhi_a into H_bst_ynk1lok1lohik1k1hi_a.\nssl_open ((x) == (null)) H_bst_xnlohi_a.\nmove=>[phi_bst_xnlohi_a0] [phi_bst_xnlohi_a1] [phi_bst_xnlohi_a2].\nmove=>[sigma_bst_xnlohi_a].\nsubst h_bst_xnlohi_a.\ntry rename h_bst_xnlohi_a into h_bst_xnlo_a.\ntry rename H_bst_xnlohi_a into H_bst_xnlo_a.\ntry rename h_bst_ynk1lok1lohik1k1hi_a into h_bst_ynk1lok1lok1k1_a.\ntry rename H_bst_ynk1lok1lohik1k1hi_a into H_bst_ynk1lok1lok1k1_a.\ntry rename h_bst_ynk1lok1lok1k1_a into h_bst_ynk1k1k1k1_a.\ntry rename H_bst_ynk1lok1lok1k1_a into H_bst_ynk1k1k1k1_a.\ntry rename h_bst_xnlo_a into h_bst_xn_a.\ntry rename H_bst_xnlo_a into H_bst_xn_a.\ntry rename h_bst_ynk1k1k1k1_a into h_bst_yk1k1k1k1_a.\ntry rename H_bst_ynk1k1k1k1_a into H_bst_yk1k1k1k1_a.\ntry rename h_bst_xn_a into h_bst_x_a.\ntry rename H_bst_xn_a into H_bst_x_a.\ntry rename h_bst_lysz1ylo11yhi11y_0y into h_bst_lysz1ylo11y_0y.\ntry rename H_bst_lysz1ylo11yhi11y_0y into H_bst_lysz1ylo11y_0y.\ntry rename h_bst_lysz1ylo11y_0y into h_bst_lysz1y_0y.\ntry rename H_bst_lysz1ylo11y_0y into H_bst_lysz1y_0y.\ntry rename h_bst_lysz1y_0y into h_bst_sz1y_0y.\ntry rename H_bst_lysz1y_0y into H_bst_sz1y_0y.\ntry rename h_bst_sz1y_0y into h_bst__0y.\ntry rename H_bst_sz1y_0y into H_bst__0y.\ntry rename h_bst_rysz2ylo2yhi2y_1y into h_bst_rysz2ylo2y_1y.\ntry rename H_bst_rysz2ylo2yhi2y_1y into H_bst_rysz2ylo2y_1y.\ntry rename h_bst_rysz2ylo2y_1y into h_bst_rysz2y_1y.\ntry rename H_bst_rysz2ylo2y_1y into H_bst_rysz2y_1y.\ntry rename h_bst_rysz2y_1y into h_bst_sz2y_1y.\ntry rename H_bst_rysz2y_1y into H_bst_sz2y_1y.\ntry rename h_bst_sz2y_1y into h_bst__1y.\ntry rename H_bst_sz2y_1y into H_bst__1y.\nssl_alloc y1.\ntry rename y into y1.\ntry rename h_bst_yk1k1k1k1_a into h_bst_y1k1k1k1k1_a.\ntry rename H_bst_yk1k1k1k1_a into H_bst_y1k1k1k1k1_a.\nssl_write retv.\nssl_write_post retv.\nssl_write (y1 .+ 1).\nssl_write_post (y1 .+ 1).\nssl_write (y1 .+ 2).\nssl_write_post (y1 .+ 2).\nssl_write y1.\nssl_write_post y1.\ntry rename h_bst__0y into h_bst__a.\ntry rename H_bst__0y into H_bst__a.\ntry rename h_bst__1y into h_bst__a.\ntry rename H_bst__1y into H_bst__a.\nssl_emp;\nexists ((if (0) <= (k1) then k1 else 0)), ((if (k1) <= (7) then k1 else 7)), ((0) + (1)), (y1);\nexists (y1 :-> (k1) \\+ y1 .+ 1 :-> (null) \\+ y1 .+ 2 :-> (null));\nsslauto.\nssl_close 2;\nexists (0), (0), (k1), (0), (0), (7), (7), (null), (null), (empty), (empty);\nsslauto.\nssl_close 1;\nsslauto.\nssl_close 1;\nsslauto.\nex_elim sz1x sz2x vx hi2x hi1x.\nex_elim lo1x lo2x lx rx.\nex_elim h_bst_lxsz1xlo1xhi1x_0x h_bst_rxsz2xlo2xhi2x_1x.\nmove=>[phi_bst_xnlohi_a0] [phi_bst_xnlohi_a1] [phi_bst_xnlohi_a2] [phi_bst_xnlohi_a3] [phi_bst_xnlohi_a4] [phi_bst_xnlohi_a5] [phi_bst_xnlohi_a6] [phi_bst_xnlohi_a7] [phi_bst_xnlohi_a8].\nmove=>[sigma_bst_xnlohi_a].\nsubst h_bst_xnlohi_a.\nmove=>[H_bst_lxsz1xlo1xhi1x_0x H_bst_rxsz2xlo2xhi2x_1x].\ntry rename h_bst_xnlohi_a into h_bst_xnlohi2xvxvxhi2x_a.\ntry rename H_bst_xnlohi_a into H_bst_xnlohi2xvxvxhi2x_a.\ntry rename h_bst_ynk1lok1lohik1k1hi_a into h_bst_ynk1lok1lohi2xvxvxhi2xk1k1hi2xvxvxhi2x_a.\ntry rename H_bst_ynk1lok1lohik1k1hi_a into H_bst_ynk1lok1lohi2xvxvxhi2xk1k1hi2xvxvxhi2x_a.\ntry rename h_bst_ynk1lok1lohi2xvxvxhi2xk1k1hi2xvxvxhi2x_a into h_bst_ynk1vxlo1xvxlo1xk1vxlo1xvxlo1xhi2xvxvxhi2xk1k1hi2xvxvxhi2x_a.\ntry rename H_bst_ynk1lok1lohi2xvxvxhi2xk1k1hi2xvxvxhi2x_a into H_bst_ynk1vxlo1xvxlo1xk1vxlo1xvxlo1xhi2xvxvxhi2xk1k1hi2xvxvxhi2x_a.\ntry rename h_bst_xnlohi2xvxvxhi2x_a into h_bst_xnvxlo1xvxlo1xhi2xvxvxhi2x_a.\ntry rename H_bst_xnlohi2xvxvxhi2x_a into H_bst_xnvxlo1xvxlo1xhi2xvxvxhi2x_a.\ntry rename h_bst_xnvxlo1xvxlo1xhi2xvxvxhi2x_a into h_bst_xsz1xsz2xvxlo1xvxlo1xhi2xvxvxhi2x_a.\ntry rename H_bst_xnvxlo1xvxlo1xhi2xvxvxhi2x_a into H_bst_xsz1xsz2xvxlo1xvxlo1xhi2xvxvxhi2x_a.\ntry rename h_bst_ynk1vxlo1xvxlo1xk1vxlo1xvxlo1xhi2xvxvxhi2xk1k1hi2xvxvxhi2x_a into h_bst_ysz1xsz2xk1vxlo1xvxlo1xk1vxlo1xvxlo1xhi2xvxvxhi2xk1k1hi2xvxvxhi2x_a.\ntry rename H_bst_ynk1vxlo1xvxlo1xk1vxlo1xvxlo1xhi2xvxvxhi2xk1k1hi2xvxvxhi2x_a into H_bst_ysz1xsz2xk1vxlo1xvxlo1xk1vxlo1xvxlo1xhi2xvxvxhi2xk1k1hi2xvxvxhi2x_a.\nssl_read x.\ntry rename vx into vx1.\ntry rename h_bst_xsz1xsz2xvxlo1xvxlo1xhi2xvxvxhi2x_a into h_bst_xsz1xsz2xvx1lo1xvx1lo1xhi2xvx1vx1hi2x_a.\ntry rename H_bst_xsz1xsz2xvxlo1xvxlo1xhi2xvxvxhi2x_a into H_bst_xsz1xsz2xvx1lo1xvx1lo1xhi2xvx1vx1hi2x_a.\ntry rename h_bst_ysz1xsz2xk1vxlo1xvxlo1xk1vxlo1xvxlo1xhi2xvxvxhi2xk1k1hi2xvxvxhi2x_a into h_bst_ysz1xsz2xk1vx1lo1xvx1lo1xk1vx1lo1xvx1lo1xhi2xvx1vx1hi2xk1k1hi2xvx1vx1hi2x_a.\ntry rename H_bst_ysz1xsz2xk1vxlo1xvxlo1xk1vxlo1xvxlo1xhi2xvxvxhi2xk1k1hi2xvxvxhi2x_a into H_bst_ysz1xsz2xk1vx1lo1xvx1lo1xk1vx1lo1xvx1lo1xhi2xvx1vx1hi2xk1k1hi2xvx1vx1hi2x_a.\nssl_read (x .+ 1).\ntry rename lx into lx1.\ntry rename h_bst_lxsz1xlo1xhi1x_0x into h_bst_lx1sz1xlo1xhi1x_0x.\ntry rename H_bst_lxsz1xlo1xhi1x_0x into H_bst_lx1sz1xlo1xhi1x_0x.\nssl_read (x .+ 2).\ntry rename rx into rx1.\ntry rename h_bst_rxsz2xlo2xhi2x_1x into h_bst_rx1sz2xlo2xhi2x_1x.\ntry rename H_bst_rxsz2xlo2xhi2x_1x into H_bst_rx1sz2xlo2xhi2x_1x.\nssl_branch ((k1) <= (vx1)).\ntry rename h_bst_x1n2lo2hi2_a1 into h_bst_lx1sz1xlo1xhi1x_0x.\ntry rename H_bst_x1n2lo2hi2_a1 into H_bst_lx1sz1xlo1xhi1x_0x.\nssl_call_pre (retv :-> (k1) \\+ h_bst_lx1sz1xlo1xhi1x_0x).\nssl_call (k1, sz1x, lo1x, hi1x).\nexists (h_bst_lx1sz1xlo1xhi1x_0x);\nsslauto.\nssl_frame_unfold.\nmove=>h_call0.\nex_elim hi11 lo11 n11 y1.\nex_elim h_bst_y1n11lo11hi11_b1.\nmove=>[phi_call00] [phi_call01] [phi_call02].\nmove=>[sigma_call0].\nsubst h_call0.\nmove=>H_bst_y1n11lo11hi11_b1.\nstore_valid.\ntry rename h_bst_y1n11lo11hi11_b1 into h_bst_y1n11lo11hi11_0x.\ntry rename H_bst_y1n11lo11hi11_b1 into H_bst_y1n11lo11hi11_0x.\ntry rename h_bst_y1n11lo11hi11_0x into h_bst_y1n11lo11hi1xk1k1hi1x_0x.\ntry rename H_bst_y1n11lo11hi11_0x into H_bst_y1n11lo11hi1xk1k1hi1x_0x.\ntry rename h_bst_y1n11lo11hi1xk1k1hi1x_0x into h_bst_y1n11k1lo1xk1lo1xhi1xk1k1hi1x_0x.\ntry rename H_bst_y1n11lo11hi1xk1k1hi1x_0x into H_bst_y1n11k1lo1xk1lo1xhi1xk1k1hi1x_0x.\ntry rename h_bst_y1n11k1lo1xk1lo1xhi1xk1k1hi1x_0x into h_bst_y1sz1xk1lo1xk1lo1xhi1xk1k1hi1x_0x.\ntry rename H_bst_y1n11k1lo1xk1lo1xhi1xk1k1hi1x_0x into H_bst_y1sz1xk1lo1xk1lo1xhi1xk1k1hi1x_0x.\nssl_read retv.\ntry rename y1 into y11.\ntry rename h_bst_y1sz1xk1lo1xk1lo1xhi1xk1k1hi1x_0x into h_bst_y11sz1xk1lo1xk1lo1xhi1xk1k1hi1x_0x.\ntry rename H_bst_y1sz1xk1lo1xk1lo1xhi1xk1k1hi1x_0x into H_bst_y11sz1xk1lo1xk1lo1xhi1xk1k1hi1x_0x.\ntry rename h_bst_lysz1ylo12yhi12y_0y into h_bst_y11sz1xk1lo1xk1lo1xhi1xk1k1hi1x_0x.\ntry rename H_bst_lysz1ylo12yhi12y_0y into H_bst_y11sz1xk1lo1xk1lo1xhi1xk1k1hi1x_0x.\ntry rename h_bst_rysz2ylo21yhi21y_1y into h_bst_rx1sz2xlo2xhi2x_1x.\ntry rename H_bst_rysz2ylo21yhi21y_1y into H_bst_rx1sz2xlo2xhi2x_1x.\ntry rename h_bst_ysz1xsz2xk1vx1lo1xvx1lo1xk1vx1lo1xvx1lo1xhi2xvx1vx1hi2xk1k1hi2xvx1vx1hi2x_a into h_bst_xsz1xsz2xk1vx1lo1xvx1lo1xk1vx1lo1xvx1lo1xhi2xvx1vx1hi2xk1k1hi2xvx1vx1hi2x_a.\ntry rename H_bst_ysz1xsz2xk1vx1lo1xvx1lo1xk1vx1lo1xvx1lo1xhi2xvx1vx1hi2xk1k1hi2xvx1vx1hi2x_a into H_bst_xsz1xsz2xk1vx1lo1xvx1lo1xk1vx1lo1xvx1lo1xhi2xvx1vx1hi2xk1k1hi2xvx1vx1hi2x_a.\nssl_write retv.\nssl_write_post retv.\nssl_write (x .+ 1).\nssl_write_post (x .+ 1).\nssl_emp;\nexists ((if ((if (hi2x) <= (vx1) then vx1 else hi2x)) <= (k1) then k1 else (if (hi2x) <= (vx1) then vx1 else hi2x))), ((if (k1) <= ((if (vx1) <= (lo1x) then vx1 else lo1x)) then k1 else (if (vx1) <= (lo1x) then vx1 else lo1x))), ((((1) + (sz1x)) + (sz2x)) + (1)), (x);\nexists (x :-> (vx1) \\+ x .+ 1 :-> (y11) \\+ x .+ 2 :-> (rx1) \\+ h_bst_y11sz1xk1lo1xk1lo1xhi1xk1k1hi1x_0x \\+ h_bst_rx1sz2xlo2xhi2x_1x);\nsslauto.\nssl_close 2;\nexists ((sz1x) + (1)), (sz2x), (vx1), (hi2x), ((if (hi1x) <= (k1) then k1 else hi1x)), ((if (k1) <= (lo1x) then k1 else lo1x)), (lo2x), (y11), (rx1), (h_bst_y11sz1xk1lo1xk1lo1xhi1xk1k1hi1x_0x), (h_bst_rx1sz2xlo2xhi2x_1x);\nsslauto.\nssl_frame_unfold.\nssl_frame_unfold.\ntry rename h_bst_x1n2lo2hi2_a1 into h_bst_rx1sz2xlo2xhi2x_1x.\ntry rename H_bst_x1n2lo2hi2_a1 into H_bst_rx1sz2xlo2xhi2x_1x.\nssl_call_pre (retv :-> (k1) \\+ h_bst_rx1sz2xlo2xhi2x_1x).\nssl_call (k1, sz2x, lo2x, hi2x).\nexists (h_bst_rx1sz2xlo2xhi2x_1x);\nsslauto.\nssl_frame_unfold.\nmove=>h_call0.\nex_elim hi11 lo11 n11 y1.\nex_elim h_bst_y1n11lo11hi11_b1.\nmove=>[phi_call00] [phi_call01] [phi_call02].\nmove=>[sigma_call0].\nsubst h_call0.\nmove=>H_bst_y1n11lo11hi11_b1.\nstore_valid.\ntry rename h_bst_y1n11lo11hi11_b1 into h_bst_y1n11lo11hi11_1x.\ntry rename H_bst_y1n11lo11hi11_b1 into H_bst_y1n11lo11hi11_1x.\ntry rename h_bst_y1n11lo11hi11_1x into h_bst_y1n11lo11hi2xk1k1hi2x_1x.\ntry rename H_bst_y1n11lo11hi11_1x into H_bst_y1n11lo11hi2xk1k1hi2x_1x.\ntry rename h_bst_y1n11lo11hi2xk1k1hi2x_1x into h_bst_y1n11k1lo2xk1lo2xhi2xk1k1hi2x_1x.\ntry rename H_bst_y1n11lo11hi2xk1k1hi2x_1x into H_bst_y1n11k1lo2xk1lo2xhi2xk1k1hi2x_1x.\ntry rename h_bst_y1n11k1lo2xk1lo2xhi2xk1k1hi2x_1x into h_bst_y1sz2xk1lo2xk1lo2xhi2xk1k1hi2x_1x.\ntry rename H_bst_y1n11k1lo2xk1lo2xhi2xk1k1hi2x_1x into H_bst_y1sz2xk1lo2xk1lo2xhi2xk1k1hi2x_1x.\nssl_read retv.\ntry rename y1 into y11.\ntry rename h_bst_y1sz2xk1lo2xk1lo2xhi2xk1k1hi2x_1x into h_bst_y11sz2xk1lo2xk1lo2xhi2xk1k1hi2x_1x.\ntry rename H_bst_y1sz2xk1lo2xk1lo2xhi2xk1k1hi2x_1x into H_bst_y11sz2xk1lo2xk1lo2xhi2xk1k1hi2x_1x.\ntry rename h_bst_lysz1ylo12yhi12y_0y into h_bst_lx1sz1xlo1xhi1x_0x.\ntry rename H_bst_lysz1ylo12yhi12y_0y into H_bst_lx1sz1xlo1xhi1x_0x.\ntry rename h_bst_rysz2ylo21yhi21y_1y into h_bst_y11sz2xk1lo2xk1lo2xhi2xk1k1hi2x_1x.\ntry rename H_bst_rysz2ylo21yhi21y_1y into H_bst_y11sz2xk1lo2xk1lo2xhi2xk1k1hi2x_1x.\ntry rename h_bst_ysz1xsz2xk1vx1lo1xvx1lo1xk1vx1lo1xvx1lo1xhi2xvx1vx1hi2xk1k1hi2xvx1vx1hi2x_a into h_bst_xsz1xsz2xk1vx1lo1xvx1lo1xk1vx1lo1xvx1lo1xhi2xvx1vx1hi2xk1k1hi2xvx1vx1hi2x_a.\ntry rename H_bst_ysz1xsz2xk1vx1lo1xvx1lo1xk1vx1lo1xvx1lo1xhi2xvx1vx1hi2xk1k1hi2xvx1vx1hi2x_a into H_bst_xsz1xsz2xk1vx1lo1xvx1lo1xk1vx1lo1xvx1lo1xhi2xvx1vx1hi2xk1k1hi2xvx1vx1hi2x_a.\nssl_write retv.\nssl_write_post retv.\nssl_write (x .+ 2).\nssl_write_post (x .+ 2).\nssl_emp;\nexists ((if ((if (hi2x) <= (vx1) then vx1 else hi2x)) <= (k1) then k1 else (if (hi2x) <= (vx1) then vx1 else hi2x))), ((if (k1) <= ((if (vx1) <= (lo1x) then vx1 else lo1x)) then k1 else (if (vx1) <= (lo1x) then vx1 else lo1x))), ((((1) + (sz1x)) + (sz2x)) + (1)), (x);\nexists (x :-> (vx1) \\+ x .+ 1 :-> (lx1) \\+ x .+ 2 :-> (y11) \\+ h_bst_lx1sz1xlo1xhi1x_0x \\+ h_bst_y11sz2xk1lo2xk1lo2xhi2xk1k1hi2x_1x);\nsslauto.\nssl_close 2;\nexists (sz1x), ((sz2x) + (1)), (vx1), ((if (hi2x) <= (k1) then k1 else hi2x)), (hi1x), (lo1x), ((if (k1) <= (lo2x) then k1 else lo2x)), (lx1), (y11), (h_bst_lx1sz1xlo1xhi1x_0x), (h_bst_y11sz2xk1lo2xk1lo2xhi2xk1k1hi2x_1x);\nsslauto.\nssl_frame_unfold.\nssl_frame_unfold.\nQed.\n", "meta": {"author": "TyGuS", "repo": "ssl-htt", "sha": "3ee4aad8e6d336dc2520eb2c62f90c8f98d9113d", "save_path": "github-repos/coq/TyGuS-ssl-htt", "path": "github-repos/coq/TyGuS-ssl-htt/ssl-htt-3ee4aad8e6d336dc2520eb2c62f90c8f98d9113d/benchmarks/advanced/bst/bst_insert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.20955444769611337}}
{"text": "Require Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Coq.Classes.RelationPairs.\nRequire Import Coq.Relations.Relations.\nRequire Import Crypto.Util.ZRange.\nRequire Import Crypto.Util.Sum.\nRequire Import Crypto.Util.LetIn.\nRequire Import Crypto.Util.Prod.\nRequire Import Crypto.Util.Sigma.\nRequire Import Crypto.Util.Option.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.ListUtil.Forall.\nRequire Import Crypto.Util.NatUtil.\nRequire Import Crypto.Util.Bool.Reflect.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.Tactics.BreakMatch.\nRequire Import Crypto.Util.Tactics.DestructHead.\nRequire Import Crypto.Util.Tactics.SplitInContext.\nRequire Import Crypto.Util.Tactics.UniquePose.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Crypto.Util.Tactics.SpecializeAllWays.\nRequire Import Rewriter.Language.Language.\nRequire Import Rewriter.Language.Inversion.\nRequire Import Crypto.Language.InversionExtra.\nRequire Import Rewriter.Language.Wf.\nRequire Import Rewriter.Language.UnderLetsProofs.\nRequire Import Crypto.AbstractInterpretation.AbstractInterpretation.\nImport Coq.Lists.List.\n\nImport EqNotations.\nModule Compilers.\n  Import Language.Compilers.\n  Import UnderLets.Compilers.\n  Import AbstractInterpretation.Compilers.\n  Import Language.Inversion.Compilers.\n  Import Language.InversionExtra.Compilers.\n  Import Language.Wf.Compilers.\n  Import UnderLetsProofs.Compilers.\n  Import invert_expr.\n\n  Module Import partial.\n    Import AbstractInterpretation.Compilers.partial.\n    Import UnderLets.Compilers.UnderLets.\n    Section with_type.\n      Context {base_type : Type}.\n      Local Notation type := (type base_type).\n      Let type_base (x : base_type) : type := type.base x.\n      Local Coercion type_base : base_type >-> type.\n      Context {ident : type -> Type}.\n      Local Notation expr := (@expr base_type ident).\n      Local Notation Expr := (@expr.Expr base_type ident).\n      Local Notation UnderLets := (@UnderLets base_type ident).\n      Context (abstract_domain' : base_type -> Type)\n              (bottom' : forall A, abstract_domain' A)\n              (abstract_interp_ident : forall t, ident t -> type.interp abstract_domain' t)\n              (abstract_domain'_R : forall t, abstract_domain' t -> abstract_domain' t -> Prop)\n              {abstract_interp_ident_Proper : forall t, Proper (eq ==> abstract_domain'_R t) (abstract_interp_ident t)}\n              {bottom'_Proper : forall t, Proper (abstract_domain'_R t) (bottom' t)}.\n      Local Notation value var := (@value base_type ident var abstract_domain').\n      Local Notation abstract_domain := (@abstract_domain base_type abstract_domain').\n      Local Notation bottom := (@bottom base_type abstract_domain' (@bottom')).\n      Local Notation bottom_for_each_lhs_of_arrow := (@bottom_for_each_lhs_of_arrow base_type abstract_domain' (@bottom')).\n\n      Section with_var2.\n        Context {var1 var2 : type -> Type}.\n        Local Notation UnderLets1 := (@UnderLets.UnderLets base_type ident var1).\n        Local Notation UnderLets2 := (@UnderLets.UnderLets base_type ident var2).\n        Local Notation expr1 := (@expr.expr base_type ident var1).\n        Local Notation expr2 := (@expr.expr base_type ident var2).\n        Local Notation value1 := (@value var1).\n        Local Notation value2 := (@value var2).\n        Local Notation value_with_lets1 := (@value_with_lets base_type ident var1 abstract_domain').\n        Local Notation value_with_lets2 := (@value_with_lets base_type ident var2 abstract_domain').\n        Local Notation state_of_value1 := (@state_of_value base_type ident var1 abstract_domain' bottom').\n        Local Notation state_of_value2 := (@state_of_value base_type ident var2 abstract_domain' bottom').\n        Context (annotate1 : forall (is_let_bound : bool) t, abstract_domain' t -> @expr1 t -> UnderLets1 (@expr1 t))\n                (annotate2 : forall (is_let_bound : bool) t, abstract_domain' t -> @expr2 t -> UnderLets2 (@expr2 t))\n                (annotate_Proper\n                 : forall is_let_bound t G\n                     v1 v2 (Hv : abstract_domain'_R t v1 v2)\n                     e1 e2 (He : expr.wf G e1 e2),\n                    UnderLets.wf (fun G' => expr.wf G') G (annotate1 is_let_bound t v1 e1) (annotate2 is_let_bound t v2 e2))\n                (interp_ident1 : bool -> forall t, ident t -> value_with_lets1 t)\n                (interp_ident2 : bool -> forall t, ident t -> value_with_lets2 t)\n                (skip_annotations_under : forall t, ident t -> bool).\n        Local Notation reify1 := (@reify base_type ident var1 abstract_domain' annotate1 bottom').\n        Local Notation reify2 := (@reify base_type ident var2 abstract_domain' annotate2 bottom').\n        Local Notation reflect1 := (@reflect base_type ident var1 abstract_domain' annotate1 bottom').\n        Local Notation reflect2 := (@reflect base_type ident var2 abstract_domain' annotate2 bottom').\n        Local Notation bottomify1 := (@bottomify base_type ident var1 abstract_domain' bottom').\n        Local Notation bottomify2 := (@bottomify base_type ident var2 abstract_domain' bottom').\n        Local Notation interp1 := (@interp base_type ident var1 abstract_domain' annotate1 bottom' skip_annotations_under interp_ident1).\n        Local Notation interp2 := (@interp base_type ident var2 abstract_domain' annotate2 bottom' skip_annotations_under interp_ident2).\n        Local Notation eval_with_bound'1 := (@eval_with_bound' base_type ident var1 abstract_domain' annotate1 bottom' skip_annotations_under interp_ident1).\n        Local Notation eval_with_bound'2 := (@eval_with_bound' base_type ident var2 abstract_domain' annotate2 bottom' skip_annotations_under interp_ident2).\n        Local Notation eval'1 := (@eval' base_type ident var1 abstract_domain' annotate1 bottom' skip_annotations_under interp_ident1).\n        Local Notation eval'2 := (@eval' base_type ident var2 abstract_domain' annotate2 bottom' skip_annotations_under interp_ident2).\n        Local Notation eta_expand_with_bound'1 := (@eta_expand_with_bound' base_type ident var1 abstract_domain' annotate1 bottom').\n        Local Notation eta_expand_with_bound'2 := (@eta_expand_with_bound' base_type ident var2 abstract_domain' annotate2 bottom').\n\n        Definition abstract_domain_R {t} : relation (abstract_domain t)\n          := type.related abstract_domain'_R.\n\n        (** This one is tricky.  Because we need to be stable under\n            weakening and reordering of the context, we permit any\n            context for well-formedness of the input in the arrow\n            case, and simply tack on that context at the beginning of\n            the output.  This is sort-of wasteful on the output\n            context, but it's sufficient to prove\n            [wf_value_Proper_list] below, which is what we really\n            need. *)\n        Fixpoint wf_value G {t} : value1 t -> value2 t -> Prop\n          := match t return value1 t -> value2 t -> Prop with\n             | type.base t\n               => fun v1 v2\n                 => abstract_domain_R (fst v1) (fst v2)\n                    /\\ expr.wf G (snd v1) (snd v2)\n             | type.arrow s d\n               => fun v1 v2\n                 => forall seg G' sv1 sv2,\n                     G' = (seg ++ G)%list\n                     -> @wf_value seg s sv1 sv2\n                     -> UnderLets.wf\n                         (fun G' => @wf_value G' d) G'\n                         (v1 sv1) (v2 sv2)\n             end.\n\n        Definition wf_value_with_lets G {t} : value_with_lets1 t -> value_with_lets2 t -> Prop\n          := UnderLets.wf (fun G' => wf_value G') G.\n\n        Context (interp_ident_Proper\n                 : forall G t idc1 idc2 (Hidc : idc1 = idc2) annotate_with_state,\n                    wf_value_with_lets G (interp_ident1 annotate_with_state t idc1) (interp_ident2 annotate_with_state t idc2)).\n\n        Global Instance bottom_Proper {t} : Proper abstract_domain_R (@bottom t) | 10.\n        Proof using bottom'_Proper.\n          clear -bottom'_Proper type_base.\n          cbv [Proper] in *; induction t; cbn; cbv [respectful]; eauto.\n        Qed.\n\n        Global Instance bottom_for_each_lhs_of_arrow_Proper {t}\n          : Proper (type.and_for_each_lhs_of_arrow (@abstract_domain_R)) (@bottom_for_each_lhs_of_arrow t) | 10.\n        Proof using bottom'_Proper.\n          clear -bottom'_Proper type_base.\n          pose proof (@bottom_Proper).\n          cbv [Proper] in *; induction t; cbn; cbv [respectful]; eauto.\n        Qed.\n\n        Lemma state_of_value_Proper G {t} v1 v2 (Hv : @wf_value G t v1 v2)\n          : abstract_domain_R (state_of_value1 v1) (state_of_value2 v2).\n        Proof using bottom'_Proper.\n          clear -Hv type_base bottom'_Proper.\n          destruct t; [ destruct v1, v2, Hv | ]; cbn in *; cbv [respectful]; eauto; intros; apply bottom_Proper.\n        Qed.\n\n        Local Hint Resolve (fun A (P : list A -> Prop) => ex_intro P nil) (fun A (x : A) (P : list A -> Prop) => ex_intro P (cons x nil)) : core.\n        Local Hint Constructors expr.wf ex : core.\n        Local Hint Unfold List.In : core.\n\n        Lemma wf_value_Proper_list G1 G2\n              (HG1G2 : forall t v1 v2, List.In (existT _ t (v1, v2)) G1 -> List.In (existT _ t (v1, v2)) G2)\n              t e1 e2\n              (Hwf : @wf_value G1 t e1 e2)\n          : @wf_value G2 t e1 e2.\n        Proof using Type.\n          clear -type_base HG1G2 Hwf.\n          revert dependent G1; revert dependent G2; induction t; intros;\n            repeat first [ progress cbn in *\n                         | progress intros\n                         | solve [ eauto ]\n                         | progress subst\n                         | progress destruct_head'_and\n                         | progress destruct_head'_or\n                         | apply conj\n                         | rewrite List.in_app_iff in *\n                         | match goal with H : _ |- _ => apply H; clear H end\n                         | wf_unsafe_t_step\n                         | eapply UnderLets.wf_Proper_list; [ | | solve [ eauto ] ] ].\n        Qed.\n\n        Fixpoint wf_reify (annotate_with_state : bool) (is_let_bound : bool) G {t}\n          : forall v1 v2 (Hv : @wf_value G t v1 v2)\n              s1 s2 (Hs : type.and_for_each_lhs_of_arrow (@abstract_domain_R) s1 s2),\n            UnderLets.wf (fun G' => expr.wf G') G (@reify1 annotate_with_state is_let_bound t v1 s1) (@reify2 annotate_with_state is_let_bound t v2 s2)\n        with wf_reflect (annotate_with_state : bool) G {t}\n             : forall e1 e2 (He : expr.wf G e1 e2)\n                 s1 s2 (Hs : abstract_domain_R s1 s2),\n            @wf_value G t (@reflect1 annotate_with_state t e1 s1) (@reflect2 annotate_with_state t e2 s2).\n        Proof using annotate_Proper bottom'_Proper.\n          all: clear -wf_reflect wf_reify annotate_Proper type_base bottom'_Proper.\n          all: pose proof (@bottom_for_each_lhs_of_arrow_Proper); cbv [Proper abstract_domain_R] in *.\n          all: destruct t as [t|s d];\n            [ clear wf_reify wf_reflect\n            | pose proof (fun G => wf_reflect annotate_with_state G s) as wf_reflect_s;\n              pose proof (fun G => wf_reflect annotate_with_state G d) as wf_reflect_d;\n              pose proof (fun G => wf_reify annotate_with_state false G s) as wf_reify_s;\n              pose proof (fun G => wf_reify annotate_with_state false G d) as wf_reify_d;\n              pose proof (@bottom_Proper s);\n              clear wf_reify wf_reflect ].\n          all: cbn [reify reflect] in *.\n          all: fold (@reify2) (@reflect2) (@reify1) (@reflect1).\n          all: cbn in *.\n          all: repeat first [ progress cbn [fst snd] in *\n                            | progress cbv [respectful] in *\n                            | progress intros\n                            | progress subst\n                            | progress destruct_head'_and\n                            | progress destruct_head'_ex\n                            | solve [ eauto | wf_t ]\n                            | apply annotate_Proper\n                            | apply UnderLets.wf_to_expr\n                            | break_innermost_match_step\n                            | match goal with\n                              | [ |- UnderLets.wf _ _ _ _ ] => constructor\n                              | [ |- expr.wf _ _ _ ] => constructor\n                              | [ He : forall seg G' sv1 sv2, G' = (seg ++ ?G)%list -> _ |- UnderLets.wf _ (?v :: ?G) (UnderLets.splice _ _) (UnderLets.splice _ _) ]\n                                => eapply UnderLets.wf_splice; [ apply (He (cons v nil)) | ]\n                              | [ |- UnderLets.wf _ _ (UnderLets.splice (reify1 _ _ _ _) _) (UnderLets.splice (reify2 _ _ _ _) _) ]\n                                => eapply UnderLets.wf_splice; [ apply wf_reify_s || apply wf_reify_d | ]\n                              | [ |- wf_value _ (reflect1 _ _ _) (reflect2 _ _ _) ] => apply wf_reflect_s || apply wf_reflect_d\n                              | [ H : wf_value _ ?x ?y |- wf_value _ ?x ?y ]\n                                => eapply wf_value_Proper_list; [ | eassumption ]\n                              | [ H : forall x y, ?R x y -> ?R' (?f x) (?g y) |- ?R' (?f _) (?g _) ]\n                                => apply H\n                              | [ |- ?R (state_of_value1 _) (state_of_value2 _) ] => eapply state_of_value_Proper\n                              end ].\n        Qed.\n\n        Lemma wf_bottomify {t} G v1 v2\n              (Hwf : @wf_value G t v1 v2)\n          : wf_value_with_lets G (bottomify1 v1) (bottomify2 v2).\n        Proof using bottom'_Proper.\n          cbv [wf_value_with_lets] in *.\n          revert dependent G; induction t as [|s IHs d IHd]; intros;\n            cbn [bottomify wf_value]; fold (@value1) (@value2) in *; break_innermost_match;\n              constructor.\n          all: repeat first [ progress cbn [fst snd wf_value] in *\n                            | progress destruct_head'_and\n                            | assumption\n                            | apply bottom'_Proper\n                            | apply conj\n                            | progress intros\n                            | progress subst\n                            | solve [ eapply UnderLets.wf_splice; eauto ] ].\n        Qed.\n\n        Local Ltac wf_interp_t :=\n          repeat first [ progress cbv [wf_value_with_lets abstract_domain_R respectful] in *\n                       | progress cbn [wf_value fst snd partial.bottom type.related eq_rect List.In] in *\n                       | wf_safe_t_step\n                       | exact I\n                       | apply wf_reify\n                       | apply bottom_Proper\n                       | progress destruct_head'_ex\n                       | progress destruct_head'_or\n                       | eapply UnderLets.wf_splice\n                       | match goal with\n                         | [ |- UnderLets.wf _ _ (bottomify1 _) (bottomify2 _) ] => apply wf_bottomify\n                         | [ |- UnderLets.wf _ _ _ _ ] => constructor\n                         | [ |- and _ _ ] => apply conj\n                         end\n                       | eapply wf_value_Proper_list; [ | solve [ eauto ] ]\n                       | eapply UnderLets.wf_Proper_list; [ | | solve [ eauto ] ]\n                       | match goal with\n                         | [ H : _ |- _ ] => eapply H; clear H; solve [ wf_interp_t ]\n                         end\n                       | break_innermost_match_step ].\n\n        Local Notation skip_annotations_for_App := (@skip_annotations_for_App base_type ident skip_annotations_under).\n\n        Lemma wf_skip_annotations_for_App {var1' var2' G t e1 e2} (Hwf : expr.wf G (t:=t) e1 e2)\n          : @skip_annotations_for_App var1' t e1 = @skip_annotations_for_App var2' t e2.\n        Proof using Type.\n          cbv [skip_annotations_for_App]; break_innermost_match;\n            expr.invert_subst;\n            repeat first [ progress cbn [projT1 projT2 fst snd eq_rect invert_App_curried invert_Ident Option.bind] in *\n                         | reflexivity\n                         | exfalso; assumption\n                         | progress inversion_option\n                         | progress destruct_head'_sig\n                         | progress destruct_head'_and\n                         | progress expr.inversion_wf_constr\n                         | progress subst\n                         | match goal with\n                           | [ H : expr.wf _ (App_curried _ _) _ |- _ ]\n                             => apply expr.invert_wf_App_curried_or_eq_base in H;\n                                [ | clear H .. ]\n                           | [ |- _ \\/ _ ] => right; split; intros; congruence\n                           | [ Hwf : expr.wf _ (App_curried _ _) ?e, H' : invert_AppIdent_curried _ = None |- _ ]\n                             => apply expr.wf_invert_AppIdent_curried in Hwf; rewrite H' in Hwf; cbv [invert_AppIdent_curried Option.option_eq] in Hwf\n                           | [ Hwf : expr.wf _ ?e (App_curried _ _), H' : invert_AppIdent_curried _ = None |- _ ]\n                             => apply expr.wf_invert_AppIdent_curried in Hwf; rewrite H' in Hwf; cbv [Option.option_eq invert_AppIdent_curried] in Hwf\n                           | [ H : context[invert_App_curried (App_curried _ _)] |- _ ]\n                             => rewrite expr.invert_App_curried_App_curried in Hwf\n                           end ].\n        Qed.\n\n        Lemma wf_interp (annotate_with_state : bool) G G' {t} (e1 : @expr (@value_with_lets1) t) (e2 : @expr (@value_with_lets2) t)\n              (Hwf : expr.wf G e1 e2)\n              (HGG' : forall t v1 v2, List.In (existT _ t (v1, v2)) G -> wf_value_with_lets G' v1 v2)\n          : wf_value_with_lets G' (interp1 annotate_with_state e1) (interp2 annotate_with_state e2).\n        Proof using annotate_Proper bottom'_Proper interp_ident_Proper.\n          revert dependent G'; revert annotate_with_state; induction Hwf; intros; cbn [interp];\n            try solve [ apply interp_ident_Proper; auto\n                      | eauto ];\n            match goal with\n            | [ G' : list _ |- context[skip_annotations_for_App ?e1v] ]\n              => match goal with\n                 | [ |- context[skip_annotations_for_App ?e2v] ]\n                   => epose proof (wf_skip_annotations_for_App (e1:=e1v) (e2:=e2v) (G:=G') ltac:(solve [ wf_t ]));\n                        generalize dependent (skip_annotations_for_App e1v);\n                        generalize dependent (skip_annotations_for_App e2v); intros;\n                          subst\n                 end\n            end;\n            wf_interp_t.\n        Qed.\n\n        Lemma wf_eval_with_bound' (annotate_with_state : bool) G G' {t} e1 e2 (He : expr.wf G e1 e2) st1 st2 (Hst : type.and_for_each_lhs_of_arrow (@abstract_domain_R) st1 st2)\n              (HGG' : forall t v1 v2, List.In (existT _ t (v1, v2)) G -> wf_value_with_lets G' v1 v2)\n          : expr.wf G' (@eval_with_bound'1 annotate_with_state t e1 st1) (@eval_with_bound'2 annotate_with_state t e2 st2).\n        Proof using annotate_Proper bottom'_Proper interp_ident_Proper.\n          eapply UnderLets.wf_to_expr, UnderLets.wf_splice.\n          { eapply wf_interp; solve [ eauto ]. }\n          { intros; destruct_head'_ex; subst; eapply wf_reify; eauto. }\n        Qed.\n\n        Lemma wf_eval' G G' {t} e1 e2 (He : expr.wf G e1 e2)\n              (HGG' : forall t v1 v2, List.In (existT _ t (v1, v2)) G -> wf_value_with_lets G' v1 v2)\n          : expr.wf G' (@eval'1 t e1) (@eval'2 t e2).\n        Proof using annotate_Proper bottom'_Proper interp_ident_Proper.\n          eapply wf_eval_with_bound'; eauto; apply bottom_for_each_lhs_of_arrow_Proper.\n        Qed.\n\n        Lemma wf_eta_expand_with_bound' G {t} e1 e2 (He : expr.wf G e1 e2) st1 st2 (Hst : type.and_for_each_lhs_of_arrow (@abstract_domain_R) st1 st2)\n          : expr.wf G (@eta_expand_with_bound'1 t e1 st1) (@eta_expand_with_bound'2 t e2 st2).\n        Proof using annotate_Proper bottom'_Proper.\n          eapply UnderLets.wf_to_expr, wf_reify; [ eapply wf_reflect | ]; eauto; apply bottom_Proper.\n        Qed.\n      End with_var2.\n    End with_type.\n\n    Module ident.\n      Import API.\n      Local Notation UnderLets := (@UnderLets base.type ident).\n      Section with_type.\n        Context (abstract_domain' : base.type -> Type).\n        Local Notation abstract_domain := (@abstract_domain base.type abstract_domain').\n        Context (bottom' : forall A, abstract_domain' A)\n                (abstract_interp_ident : forall t, ident t -> type.interp abstract_domain' t)\n                (extract_list_state : forall A, abstract_domain' (base.type.list A) -> option (list (abstract_domain' A)))\n                (extract_option_state : forall A, abstract_domain' (base.type.option A) -> option (option (abstract_domain' A))).\n        Context (abstract_domain'_R : forall t, abstract_domain' t -> abstract_domain' t -> Prop).\n        Local Notation abstract_domain_R := (@abstract_domain_R base.type abstract_domain' abstract_domain'_R).\n        Context {abstract_interp_ident_Proper : forall t, Proper (eq ==> @abstract_domain_R t) (abstract_interp_ident t)}\n                {bottom'_Proper : forall t, Proper (abstract_domain'_R t) (bottom' t)}\n                (extract_list_state_length : forall t v1 v2, abstract_domain'_R _ v1 v2 -> option_map (@length _) (extract_list_state t v1) = option_map (@length _) (extract_list_state t v2))\n                (extract_list_state_rel : forall t v1 v2, abstract_domain'_R _ v1 v2 -> forall l1 l2, extract_list_state t v1 = Some l1 -> extract_list_state t v2 = Some l2 -> List.Forall2 (@abstract_domain'_R t) l1 l2)\n                (extract_option_state_rel : forall t v1 v2, abstract_domain'_R _ v1 v2 -> option_eq (option_eq (abstract_domain'_R _)) (extract_option_state t v1) (extract_option_state t v2)).\n\n        Local Instance abstract_interp_ident_Proper_arrow s d\n          : Proper (eq ==> abstract_domain'_R s ==> abstract_domain'_R d) (abstract_interp_ident (type.arrow s d))\n          := abstract_interp_ident_Proper (type.arrow s d).\n\n        Local Ltac handle_Forall2_step :=\n          first [ match goal with\n                  | [ |- List.Forall2 _ ?x ?x ] => rewrite Forall2_Forall; cbv [Proper]\n                  | [ |- List.Forall2 _ (List.map _ _) (List.map _ _) ] => rewrite Forall2_map_map_iff\n                  | [ |- List.Forall2 _ (List.combine _ _) (List.combine _ _) ]\n                    => eapply Forall2_combine; [ intros | eassumption | eassumption ]\n                  | [ |- List.Forall2 _ (List.combine ?x _) (List.combine ?x _) ]\n                    => eapply Forall2_combine;\n                       [ intros\n                       | instantiate (1:=fun a b => a = b /\\ List.In a x);\n                         rewrite Forall2_Forall, Forall_forall; cbv [Proper]; auto\n                       | eassumption ]\n                  | [ H : expr.wf _ ?d1 ?d2, H' : List.Forall2 (expr.wf _) ?xs ?ys\n                      |- expr.wf ?G (nth_default ?d1 ?xs ?n) (nth_default ?d2 ?ys ?n) ]\n                    => cut (List.Forall2 (expr.wf G) xs ys /\\ expr.wf G d1 d2);\n                       [ rewrite Forall2_forall_iff'';\n                         let H := fresh in intros [? H]; apply H\n                       | ]\n                  end ].\n\n\n        Section with_var2.\n          Context {var1 var2 : type -> Type}.\n          Local Notation wf_value_with_lets := (@wf_value_with_lets base.type ident abstract_domain' abstract_domain'_R var1 var2).\n          Local Notation wf_value := (@wf_value base.type ident abstract_domain' abstract_domain'_R var1 var2).\n          Context (annotate_expr1 : forall t, abstract_domain' t -> option (@expr var1 (t -> t)))\n                  (annotate_expr2 : forall t, abstract_domain' t -> option (@expr var2 (t -> t)))\n                  (is_annotated_for1 : forall t t', @expr var1 t -> abstract_domain' t' -> bool)\n                  (is_annotated_for2 : forall t t', @expr var2 t -> abstract_domain' t' -> bool)\n                  (strip_annotation1 : forall t, ident t -> option (value _ t))\n                  (strip_annotation2 : forall t, ident t -> option (value _ t))\n                  (annotation_to_cast1 : forall s d, @expr var1 (s -> d) -> option (@expr var1 s -> @expr var1 d))\n                  (annotation_to_cast2 : forall s d, @expr var2 (s -> d) -> option (@expr var2 s -> @expr var2 d))\n                  (skip_annotations_under : forall t, ident t -> bool)\n                  {wf_annotation_to_cast\n                   : forall s d G e1 e2,\n                      expr.wf G e1 e2\n                      -> option_eq (fun f g => forall e1 e2, expr.wf G e1 e2 -> expr.wf G (f e1) (g e2))\n                                   (annotation_to_cast1 s d e1)\n                                   (annotation_to_cast2 s d e2)}\n                  {annotate_expr_Proper : forall t s1 s2,\n                      abstract_domain'_R t s1 s2\n                      -> option_eq (expr.wf nil) (annotate_expr1 t s1) (annotate_expr2 t s2)}\n                  {is_annotated_for_Proper : forall G t t' e1 e2,\n                      expr.wf G e1 e2\n                      -> ((abstract_domain'_R _ ==> eq)%signature)\n                           (@is_annotated_for1 t t' e1)\n                           (@is_annotated_for2 t t' e2)}\n                  {wf_strip_annotation\n                   : forall G t idc,\n                      option_eq (wf_value G)\n                                (@strip_annotation1 t idc)\n                                (@strip_annotation2 t idc)}.\n\n          Local Notation update_annotation1 := (@ident.update_annotation var1 abstract_domain' annotate_expr1 is_annotated_for1).\n          Local Notation update_annotation2 := (@ident.update_annotation var2 abstract_domain' annotate_expr2 is_annotated_for2).\n          Local Notation annotate1 := (@ident.annotate var1 abstract_domain' annotate_expr1 abstract_interp_ident extract_list_state extract_option_state is_annotated_for1).\n          Local Notation annotate2 := (@ident.annotate var2 abstract_domain' annotate_expr2 abstract_interp_ident extract_list_state extract_option_state is_annotated_for2).\n          Local Notation annotate_base1 := (@ident.annotate_base var1 abstract_domain' annotate_expr1 is_annotated_for1).\n          Local Notation annotate_base2 := (@ident.annotate_base var2 abstract_domain' annotate_expr2 is_annotated_for2).\n          Local Notation annotate_with_expr1 := (@ident.annotate_with_expr var1 abstract_domain' annotate_expr1 is_annotated_for1).\n          Local Notation annotate_with_expr2 := (@ident.annotate_with_expr var2 abstract_domain' annotate_expr2 is_annotated_for2).\n          Local Notation interp_ident1 := (@ident.interp_ident var1 abstract_domain' annotate_expr1 bottom' abstract_interp_ident extract_list_state extract_option_state is_annotated_for1 strip_annotation1).\n          Local Notation interp_ident2 := (@ident.interp_ident var2 abstract_domain' annotate_expr2 bottom' abstract_interp_ident extract_list_state extract_option_state is_annotated_for2 strip_annotation2).\n          Local Notation reflect1 := (@reflect base.type ident var1 abstract_domain' annotate1 bottom').\n          Local Notation reflect2 := (@reflect base.type ident var2 abstract_domain' annotate2 bottom').\n\n          Lemma wf_update_annotation G {t} st1 st2 (Hst : abstract_domain'_R t st1 st2) e1 e2 (He : expr.wf G e1 e2)\n            : expr.wf G (@update_annotation1 t st1 e1) (@update_annotation2 t st2 e2).\n          Proof using abstract_interp_ident_Proper annotate_expr_Proper is_annotated_for_Proper.\n            cbv [ident.update_annotation];\n              repeat first [ progress subst\n                           | progress expr.invert_subst\n                           | progress cbn [fst snd projT1 projT2 eq_rect] in *\n                           | progress cbn [invert_AppIdent Option.bind invert_App invert_Ident] in *\n                           | progress destruct_head'_sig\n                           | progress destruct_head'_sigT\n                           | progress destruct_head'_and\n                           | progress destruct_head'_prod\n                           | progress destruct_head' False\n                           | progress inversion_option\n                           | progress expr.inversion_wf_constr\n                           | progress expr.inversion_wf_one_constr\n                           | break_innermost_match_hyps_step\n                           | expr.invert_match_step\n                           | progress expr.inversion_expr\n                           | progress rewrite_type_transport_correct\n                           | progress type_beq_to_eq\n                           | progress type.inversion_type\n                           | progress base.type.inversion_type\n                           | discriminate\n                           | match goal with\n                             | [ H : abstract_domain'_R _ ?x _ |- _ ] => rewrite !H\n                             | [ H : abstract_domain'_R _ ?x _, H' : context[?x] |- _ ] => rewrite !H in H'\n                             end\n                           | progress wf_safe_t\n                           | break_innermost_match_step\n                           | solve [ wf_t ]\n                           | match goal with\n                             | [ H : abstract_domain'_R _ ?x ?y, H1 : annotate_expr1 _ ?x = _, H2 : annotate_expr2 _ ?y = _ |- _ ]\n                               => let H' := fresh in\n                                  pose proof (annotate_expr_Proper _ _ _ H) as H';\n                                  rewrite H1, H2 in H'; clear H1 H2; cbv [option_eq] in H'\n                             | [ H1 : is_annotated_for1 _ _ ?e1 ?s1 = _,\n                                      H2 : is_annotated_for2 _ _ ?e2 ?s2 = _ ,\n                                           Hwf : expr.wf _ ?e1 ?e2,\n                                                 Hrel : abstract_domain'_R _ ?s1 ?s2 |- _ ]\n                               => let H' := fresh in\n                                  pose proof (is_annotated_for_Proper _ _ _ _ _ Hwf _ _ Hrel) as H';\n                                  rewrite H1, H2 in H'; clear H1 H2\n                             end ].\n          Qed.\n\n          Lemma wf_annotate_with_expr\n                is_let_bound t G\n                v1 v2 (Hv : abstract_domain'_R t v1 v2)\n                e1 e2 (He : expr.wf G e1 e2)\n            : UnderLets.wf (fun G' => expr.wf G') G (@annotate_with_expr1 is_let_bound t v1 e1) (@annotate_with_expr2 is_let_bound t v2 e2).\n          Proof using abstract_interp_ident_Proper annotate_expr_Proper is_annotated_for_Proper.\n            cbv [ident.annotate_with_expr]; break_innermost_match; repeat constructor; apply wf_update_annotation; assumption.\n          Qed.\n\n          Lemma wf_annotate_base\n                is_let_bound (t : base.type.base) G\n                v1 v2 (Hv : abstract_domain'_R t v1 v2)\n                e1 e2 (He : expr.wf G e1 e2)\n            : UnderLets.wf (fun G' => expr.wf G') G (@annotate_base1 is_let_bound t v1 e1) (@annotate_base2 is_let_bound t v2 e2).\n          Proof using abstract_interp_ident_Proper annotate_expr_Proper is_annotated_for_Proper.\n            cbv [ident.annotate_base];\n              repeat first [ apply wf_annotate_with_expr\n                           | break_innermost_match_step\n                           | progress subst\n                           | progress cbv [type_base ident.smart_Literal] in *\n                           | progress cbn [invert_Literal] in *\n                           | discriminate\n                           | progress destruct_head' False\n                           | progress expr.invert_subst\n                           | progress expr.inversion_wf\n                           | wf_safe_t_step\n                           | break_innermost_match_hyps_step\n                           | match goal with\n                             | [ H : _ = _ :> ident _ |- _ ] => inversion H; clear H\n                             | [ |- UnderLets.wf _ _ _ _ ] => constructor\n                             | [ H : abstract_domain'_R _ _ _ |- _ ] => rewrite !H\n                             end\n                           | progress expr.invert_match_step\n                           | progress expr.inversion_expr ].\n          Qed.\n\n          Local Opaque ident.ident_Some ident.ident_None.\n          Lemma wf_annotate\n                is_let_bound t G\n                v1 v2 (Hv : abstract_domain'_R t v1 v2)\n                e1 e2 (He : expr.wf G e1 e2)\n            : UnderLets.wf (fun G' => expr.wf G') G (@annotate1 is_let_bound t v1 e1) (@annotate2 is_let_bound t v2 e2).\n          Proof using abstract_interp_ident_Proper annotate_expr_Proper extract_list_state_length extract_list_state_rel extract_option_state_rel is_annotated_for_Proper.\n            revert dependent G; induction t; intros;\n              cbn [ident.annotate]; try apply wf_annotate_base; trivial.\n            all: try solve [ repeat first [ lazymatch goal with\n                                | [ H : expr.wf _ ?e1 ?e2, H' : reflect_list ?e1 = Some _, H'' : reflect_list ?e2 = None |- _ ]\n                                  => apply expr.wf_reflect_list in H; rewrite H', H'' in H; exfalso; clear -H; intuition congruence\n                                | [ H : expr.wf _ ?e1 ?e2, H' : reflect_list ?e2 = Some _, H'' : reflect_list ?e1 = None |- _ ]\n                                  => apply expr.wf_reflect_list in H; rewrite H', H'' in H; exfalso; clear -H; intuition congruence\n                                | [ H : expr.wf _ (reify_list _) (reify_list _) |- _ ] => apply expr.wf_reify_list in H\n                                | [ |- expr.wf _ (reify_list _) (reify_list _) ] => apply expr.wf_reify_list\n                                | [ |- UnderLets.wf _ _ (UnderLets.splice_list _ _) (UnderLets.splice_list _ _) ]\n                                  => eapply @UnderLets.wf_splice_list_no_order with (P:=fun G => expr.wf G); autorewrite with distr_length\n                                | [ H : expr.wf _ (reify_list _) ?e, H' : reflect_list ?e = None |- _ ]\n                                  => apply expr.wf_reflect_list in H; rewrite H', expr.reflect_reify_list in H; exfalso; clear -H; intuition congruence\n                                | [ H : expr.wf _ ?e (reify_list _), H' : reflect_list ?e = None |- _ ]\n                                  => apply expr.wf_reflect_list in H; rewrite H', expr.reflect_reify_list in H; exfalso; clear -H; intuition congruence\n                                | [ H : extract_list_state ?t ?v1 = ?x1, H' : extract_list_state ?t ?v2 = ?x2, Hv : abstract_domain'_R _ ?v1 ?v2 |- _ ]\n                                  => let Hl := fresh in\n                                     let Hl' := fresh in\n                                     pose proof (extract_list_state_length _ v1 v2 Hv) as Hl;\n                                     pose proof (extract_list_state_rel _ v1 v2 Hv) as Hl';\n                                     rewrite H, H' in Hl, Hl'; cbv [option_eq option_map] in Hl, Hl'; clear H H'\n                                | [ H : abstract_domain'_R _ ?v1 ?v2, H1 : extract_option_state _ ?v1 = _, H2 : extract_option_state _ ?v2 = _ |- _ ]\n                                  => let H' := fresh in\n                                     pose proof H as H';\n                                     apply extract_option_state_rel in H';\n                                     rewrite H1, H2 in H';\n                                     cbv [option_eq] in H';\n                                     clear H1 H2\n                                | [ H : ?x = ?x |- _ ] => clear H\n                                | [ H : length ?l1 = length ?l2, H' : context[length ?l1] |- _ ] => rewrite H in H'\n                                | [ H : context[invert_pair ?e] |- _ ]\n                                  => let lem := lazymatch e with\n                                                | (?x, ?y)%expr => constr:(expr.invert_pair_ident_pair(v1:=x) (v2:=y) : invert_pair e = _)\n                                                end in\n                                     rewrite lem in H\n                                end\n                              | apply wf_annotate_with_expr\n                              | apply DefaultValue.expr.base.wf_default\n                              | apply DefaultValue.expr.wf_default\n                              | progress expr.invert_subst\n                              | progress cbn [ident.annotate ident.smart_Literal invert_Literal invert_pair invert_AppIdent2 invert_App2 fst snd projT2 projT1 eq_rect Option.bind] in *\n                              | progress destruct_head' False\n                              | progress inversion_option\n                              | progress destruct_head'_ex\n                              | discriminate\n                              | wf_safe_t_step\n                              | progress expr.inversion_wf_constr\n                              | progress expr.inversion_expr\n                              | progress type_beq_to_eq\n                              | progress type.inversion_type\n                              | progress base.type.inversion_type\n                              | match goal with\n                                | [ |- expr.wf _ (update_annotation1 _ _) (update_annotation2 _ _) ] => apply wf_update_annotation\n                                | [ H : _ = _ :> ident _ |- _ ] => inversion H; clear H\n                                | [ |- UnderLets.wf _ _ _ _ ] => constructor\n                                | [ H : abstract_domain'_R _ ?x _ |- _ ] => rewrite !H\n                                | [ |- UnderLets.wf _ _ (UnderLets.splice _ _) (UnderLets.splice _ _) ] => eapply UnderLets.wf_splice\n                                | [ H : List.nth_error (List.map _ _) _ = Some _ |- _ ] => apply nth_error_map_ex in H\n                                | [ H : context[List.nth_error (List.combine _ _) _] |- _ ] => rewrite nth_error_combine in H\n                                | [ |- context[List.nth_error (List.combine _ _) _] ] => rewrite nth_error_combine\n                                | [ H : forall x y, Some _ = Some _ -> Some _ = Some _ -> _ |- _ ]\n                                  => specialize (H _ _ eq_refl eq_refl)\n                                | [ H : forall v1 v2, List.In (v1, v2) (List.combine ?l1 ?l2) -> ?R v1 v2, H' : List.nth_error ?l1 ?n = Some ?a1, H'' : List.nth_error ?l2 ?n = Some ?a2\n                                                                                                                                                  |- ?R ?a1 ?a2 ]\n                                  => apply H\n                                | [ H : List.nth_error ?l ?n' = Some ?v |- List.In (?v, _) (List.combine ?l _) ] => apply nth_error_In with (n:=n')\n                                | [ H : length ?x = length ?y |- context[length ?x] ] => rewrite H\n                                end\n                              | handle_Forall2_step\n                              | break_innermost_match_step\n                              | break_innermost_match_hyps_step\n                              | progress expr.invert_match\n                              | progress expr.inversion_wf_one_constr\n                              | match goal with\n                                | [ H : context[UnderLets.wf _ _ (annotate1 _ _ _) (annotate2 _ _ _)]\n                                    |- UnderLets.wf _ _ (annotate1 _ _ _) (annotate2 _ _ _) ] => eapply H\n                                end\n                              | apply abstract_interp_ident_Proper_arrow\n                              | progress rewrite_type_transport_correct\n                              | apply conj\n                              | congruence\n                              | progress destruct_head' option\n                              | progress cbn [Option.combine option_map UnderLets.splice_option reify_option option_rect] in *\n                              | progress cbn [type.decode f_equal eq_rect fst snd] in *\n                              | solve [ wf_t ] ] ].\n          Qed.\n          Local Ltac type_of_value v :=\n            lazymatch v with\n            | (abstract_domain ?t * _)%type => t\n            | (?a -> UnderLets _ ?b)\n              => let a' := type_of_value a in\n                let b' := type_of_value b in\n                constr:(type.arrow a' b')\n            end.\n          Local Opaque ident.ident_Literal.\n          Lemma wf_interp_ident_nth_default (annotate_with_state : bool) G T\n            : wf_value_with_lets G (@interp_ident1 annotate_with_state _ (@ident.List_nth_default T)) (@interp_ident2 annotate_with_state _ (@ident.List_nth_default T)).\n          Proof using abstract_interp_ident_Proper annotate_expr_Proper extract_list_state_length extract_list_state_rel extract_option_state_rel is_annotated_for_Proper.\n            cbv [wf_value_with_lets wf_value ident.interp_ident]; constructor; cbn -[abstract_domain_R abstract_domain].\n            { intros; subst.\n              destruct_head'_prod; destruct_head'_and; cbn [fst snd] in *.\n              repeat first [ progress subst\n                           | lazymatch goal with\n                             | [ H : expr.wf _ ?e1 ?e2, H' : reflect_list ?e1 = Some _, H'' : reflect_list ?e2 = None |- _ ]\n                               => apply expr.wf_reflect_list in H; rewrite H', H'' in H; exfalso; clear -H; intuition congruence\n                             | [ H : expr.wf _ ?e1 ?e2, H' : reflect_list ?e2 = Some _, H'' : reflect_list ?e1 = None |- _ ]\n                               => apply expr.wf_reflect_list in H; rewrite H', H'' in H; exfalso; clear -H; intuition congruence\n                             | [ H : expr.wf _ (reify_list _) (reify_list _) |- _ ] => apply expr.wf_reify_list in H\n                             | [ |- expr.wf _ (reify_list _) (reify_list _) ] => apply expr.wf_reify_list\n                             | [ |- UnderLets.wf _ _ (UnderLets.splice_list _ _) (UnderLets.splice_list _ _) ]\n                               => eapply @UnderLets.wf_splice_list_no_order with (P:=fun G => expr.wf G); autorewrite with distr_length\n                             | [ H : expr.wf _ (reify_list _) ?e, H' : reflect_list ?e = None |- _ ]\n                               => apply expr.wf_reflect_list in H; rewrite H', expr.reflect_reify_list in H; exfalso; clear -H; intuition congruence\n                             | [ H : expr.wf _ ?e (reify_list _), H' : reflect_list ?e = None |- _ ]\n                               => apply expr.wf_reflect_list in H; rewrite H', expr.reflect_reify_list in H; exfalso; clear -H; intuition congruence\n                             | [ H : extract_list_state ?t ?v1 = ?x1, H' : extract_list_state ?t ?v2 = ?x2, Hv : abstract_domain_R ?v1 ?v2 |- _ ]\n                               => let Hl := fresh in\n                                  let Hl' := fresh in\n                                  pose proof (extract_list_state_length _ v1 v2 Hv) as Hl;\n                                  pose proof (extract_list_state_rel _ v1 v2 Hv) as Hl';\n                                  rewrite H, H' in Hl, Hl'; cbv [option_eq option_map] in Hl, Hl'; clear H H'\n                             | [ H : ?x = ?x |- _ ] => clear H\n                             | [ H : length ?l1 = length ?l2, H' : context[length ?l1] |- _ ] => rewrite H in H'\n                             end\n                           | match goal with\n                             | [ |- UnderLets.wf ?Q ?G (UnderLets.splice ?x1 ?e1) (UnderLets.splice ?x2 ?e2) ]\n                               => simple refine (@UnderLets.wf_splice _ _ _ _ _ _ _ _ _ Q G x1 x2 _ e1 e2 _);\n                                 [ let G := fresh \"G\" in\n                                   intro G;\n                                   lazymatch goal with\n                                   | [ |- expr _ -> _ -> _ ]\n                                     => refine (expr.wf G)\n                                   | [ |- ?T -> _ -> _ ]\n                                     => let t := type_of_value T in\n                                       refine (@wf_value G t)\n                                   end\n                                 | | ]\n                             | [ |- UnderLets.wf ?Q ?G (UnderLets.Base _) (UnderLets.Base _) ]\n                               => constructor\n                             | [ H : ident.ident_Literal _ = ident.ident_Literal _ |- _ ]\n                               => apply (f_equal (fun idc => invert_Literal (var:=var1) (#idc))) in H; rewrite !expr.invert_Literal_ident_Literal in H\n                             | [ H : _ = _ :> ident _ |- _ ] => inversion H; clear H\n                             | [ H : List.nth_error _ _ = None |- _ ] => apply List.nth_error_None in H\n                             | [ H : List.nth_error _ _ = Some _ |- _ ]\n                               => unique pose proof (@ListUtil.nth_error_value_length _ _ _ _ H);\n                                  unique pose proof (@ListUtil.nth_error_value_In _ _ _ _ H)\n                             | [ H : context[List.In _ (List.map _ _)] |- _ ] => rewrite List.in_map_iff in H\n                             | [ H : (?x <= ?y)%nat, H' : (?y < ?x)%nat |- _ ] => exfalso; clear -H H'; lia\n                             | [ H : (?x <= ?y)%nat, H' : (?y < ?x')%nat, H'' : ?x' = ?x |- _ ] => exfalso; clear -H H' H''; lia\n                             | [ H : length ?x = length ?y |- context[length ?x] ] => rewrite H\n                             | [ H : List.nth_error (List.map _ _) _ = Some _ |- _ ] => apply nth_error_map_ex in H\n                             | [ H : context[List.nth_error (List.combine _ _) _] |- _ ] => rewrite nth_error_combine in H\n                             | [ |- context[List.nth_error (List.combine _ _) _] ] => rewrite nth_error_combine\n                             | [ H : forall x y, Some _ = Some _ -> Some _ = Some _ -> _ |- _ ]\n                               => specialize (H _ _ eq_refl eq_refl)\n                             | [ H : forall v1 v2, List.In (v1, v2) (List.combine ?l1 ?l2) -> ?R v1 v2, H' : List.nth_error ?l1 ?n' = Some ?a1, H'' : List.nth_error ?l2 ?n' = Some ?a2\n                                                                                                                                                |- _ ]\n                               => unique pose proof (H a1 a2 ltac:(apply nth_error_In with (n:=n'); rewrite nth_error_combine, H', H''; reflexivity))\n                             | [ H : List.nth_error ?l ?n' = Some ?v |- List.In (?v, _) (List.combine ?l _) ] => apply nth_error_In with (n:=n')\n                             | [ H : context[length ?ls] |- _ ] => tryif is_var ls then fail else (progress autorewrite with distr_length in H)\n                             | [ H : context[List.nth_error (List.seq _ _) _] |- _ ] => rewrite nth_error_seq in H\n                             end\n                           | progress inversion_option\n                           | progress intros\n                           | progress cbn [fst snd value] in *\n                           | progress destruct_head'_prod\n                           | progress destruct_head'_ex\n                           | progress destruct_head'_and\n                           | progress destruct_head' False\n                           | progress specialize_by_assumption\n                           | apply conj\n                           | progress expr.invert_subst\n                           | progress expr.inversion_wf_constr\n                           | progress expr.inversion_expr\n                           | handle_Forall2_step\n                           | wf_safe_t_step\n                           | progress destruct_head' (@partial.wf_value)\n                           | solve [ eapply wf_annotate; wf_t; try apply DefaultValue.expr.base.wf_default\n                                   | eapply wf_annotate_base; wf_t\n                                   | eapply (abstract_interp_ident_Proper _ (@ident.List_nth_default T) _ eq_refl); assumption\n                                   | eapply wf_update_annotation; wf_t\n                                   | wf_t\n                                   | match goal with\n                                     | [ H : context[UnderLets.wf _ _ _ _] |- UnderLets.wf _ _ _ _ ] => eapply H; solve [ repeat esplit; eauto ]\n                                     end\n                                   | eauto using List.nth_error_In\n                                   | eapply expr.wf_Proper_list; [ | eassumption ]; wf_safe_t; eauto 10 ]\n                           | break_innermost_match_step\n                           | match goal with\n                             | [ H : context[List.In] |- expr.wf _ ?x ?y ]\n                               => specialize (H x y); rewrite !List.nth_default_eq, <- List.combine_nth, <- !List.nth_default_eq in H; cbv [List.nth_default] in H |- *\n                             | [ H : List.In _ _ -> ?P |- ?P ] => apply H\n                             end\n                           | break_innermost_match_hyps_step\n                           | congruence\n                           | rewrite List.combine_length in *\n                           | rewrite NPeano.Nat.min_r in * by lia\n                           | rewrite NPeano.Nat.min_l in * by lia\n                           | progress expr.inversion_wf_one_constr\n                           | progress expr.invert_match\n                           | match goal with\n                             | [ |- wf_value _ _ _ ] => progress hnf\n                             end ]. }\n          Qed.\n\n          Lemma wf_interp_ident_not_nth_default_nostrip (annotate_with_state : bool) G {t} (idc : ident t)\n            : wf_value_with_lets G (Base (reflect1 annotate_with_state (###idc)%expr (abstract_interp_ident _ idc))) (Base (reflect2 annotate_with_state (###idc)%expr (abstract_interp_ident _ idc))).\n          Proof using abstract_interp_ident_Proper annotate_expr_Proper bottom'_Proper extract_list_state_length extract_list_state_rel extract_option_state_rel is_annotated_for_Proper.\n            constructor; eapply wf_reflect;\n              solve [ apply bottom'_Proper\n                    | apply wf_annotate\n                    | repeat constructor\n                    | apply abstract_interp_ident_Proper; reflexivity ].\n          Qed.\n\n          Lemma wf_interp_ident_not_nth_default (annotate_with_state : bool) G {t} (idc : ident t)\n            : (wf_value_with_lets G)\n                (Base match strip_annotation1 _ idc with\n                      | Some v => v\n                      | None => reflect1 annotate_with_state (###idc)%expr (abstract_interp_ident _ idc)\n                      end)\n                (Base match strip_annotation2 _ idc with\n                      | Some v => v\n                      | None => reflect2 annotate_with_state (###idc)%expr (abstract_interp_ident _ idc)\n                      end).\n          Proof using abstract_interp_ident_Proper annotate_expr_Proper bottom'_Proper extract_list_state_length extract_list_state_rel extract_option_state_rel is_annotated_for_Proper wf_strip_annotation.\n            pose proof (wf_strip_annotation G _ idc).\n            break_innermost_match; cbn [option_eq] in *;\n              solve [ exfalso; assumption\n                    | congruence\n                    | apply wf_interp_ident_not_nth_default_nostrip\n                    | constructor; assumption ].\n          Qed.\n\n          Lemma wf_interp_ident G {t} idc1 idc2 (Hidc : idc1 = idc2) (annotate_with_state : bool)\n            : wf_value_with_lets G (@interp_ident1 annotate_with_state t idc1) (@interp_ident2 annotate_with_state t idc2).\n          Proof using abstract_interp_ident_Proper annotate_expr_Proper bottom'_Proper extract_list_state_length extract_list_state_rel extract_option_state_rel is_annotated_for_Proper wf_strip_annotation.\n            cbv [wf_value_with_lets ident.interp_ident]; subst idc2; destruct idc1;\n              first [ apply wf_interp_ident_nth_default\n                    | apply wf_interp_ident_not_nth_default ].\n          Qed.\n\n          Local Notation strip_all_annotations'1 := (@partial.ident.strip_all_annotations' var1 annotation_to_cast1 skip_annotations_under).\n          Local Notation strip_all_annotations'2 := (@partial.ident.strip_all_annotations' var2 annotation_to_cast2 skip_annotations_under).\n          Local Notation strip_all_annotations1 := (@partial.ident.strip_all_annotations var1 annotation_to_cast1 skip_annotations_under).\n          Local Notation strip_all_annotations2 := (@partial.ident.strip_all_annotations var2 annotation_to_cast2 skip_annotations_under).\n          Lemma wf_strip_all_annotations' G t e1 e2 (Hwf : expr.wf G e1 e2)\n            : forall should_strip, expr.wf G (@strip_all_annotations'1 should_strip t e1) (@strip_all_annotations'2 should_strip t e2).\n          Proof using wf_annotation_to_cast.\n            induction Hwf; cbn [partial.ident.strip_all_annotations'];\n              repeat first [ progress cbn [projT1 projT2 fst snd] in *\n                           | progress type.inversion_type\n                           | progress wf_safe_t\n                           | progress break_innermost_match\n                           | progress expr.invert_subst\n                           | discriminate\n                           | solve [ exfalso; eauto\n                                   | eassert (Some _ = None) by eauto; congruence ]\n                           | match goal with\n                             | [ H1 : annotation_to_cast1 ?s ?d ?e1 = _, H2 : annotation_to_cast2 ?s ?d ?e2 = _ |- _ ]\n                               => let H := fresh in\n                                  pose proof (fun G => wf_annotation_to_cast s d G e1 e2) as H;\n                                  rewrite H1, H2 in H; cbv [option_eq] in H;\n                                  clear H1 H2\n                             end ].\n          Qed.\n\n          Lemma wf_strip_all_annotations G t e1 e2 (Hwf : expr.wf G e1 e2)\n            : expr.wf G (@strip_all_annotations1 t e1) (@strip_all_annotations2 t e2).\n          Proof using wf_annotation_to_cast. now apply wf_strip_all_annotations'. Qed.\n\n          Local Notation eval_with_bound1 := (@partial.ident.eval_with_bound var1 abstract_domain' annotate_expr1 bottom' abstract_interp_ident extract_list_state extract_option_state is_annotated_for1 strip_annotation1 skip_annotations_under).\n          Local Notation eval_with_bound2 := (@partial.ident.eval_with_bound var2 abstract_domain' annotate_expr2 bottom' abstract_interp_ident extract_list_state extract_option_state is_annotated_for2 strip_annotation2 skip_annotations_under).\n          Lemma wf_eval_with_bound (annotate_with_state : bool) {t} G G' e1 e2 (Hwf : expr.wf G e1 e2) st1 st2 (Hst : type.and_for_each_lhs_of_arrow (@abstract_domain_R) st1 st2)\n                (HGG' : forall t v1 v2, List.In (existT _ t (v1, v2)) G -> wf_value_with_lets G' v1 v2)\n            : expr.wf G' (@eval_with_bound1 annotate_with_state t e1 st1) (@eval_with_bound2 annotate_with_state t e2 st2).\n          Proof using abstract_interp_ident_Proper annotate_expr_Proper bottom'_Proper extract_list_state_length extract_list_state_rel extract_option_state_rel is_annotated_for_Proper wf_strip_annotation.\n            eapply wf_eval_with_bound';\n              solve [ eassumption\n                    | eapply wf_annotate\n                    | eapply wf_interp_ident ].\n          Qed.\n\n          Local Notation eval1 := (@partial.ident.eval var1 abstract_domain' annotate_expr1 bottom' abstract_interp_ident extract_list_state extract_option_state is_annotated_for1 strip_annotation1).\n          Local Notation eval2 := (@partial.ident.eval var2 abstract_domain' annotate_expr2 bottom' abstract_interp_ident extract_list_state extract_option_state is_annotated_for2 strip_annotation2).\n          Lemma wf_eval {t} G G' e1 e2 (Hwf : expr.wf G e1 e2)\n                (HGG' : forall t v1 v2, List.In (existT _ t (v1, v2)) G -> wf_value_with_lets G' v1 v2)\n            : expr.wf G' (@eval1 t e1) (@eval2 t e2).\n          Proof using abstract_interp_ident_Proper annotate_expr_Proper bottom'_Proper extract_list_state_length extract_list_state_rel extract_option_state_rel is_annotated_for_Proper wf_strip_annotation.\n            eapply wf_eval';\n              solve [ eassumption\n                    | eapply wf_annotate\n                    | eapply wf_interp_ident ].\n          Qed.\n\n          Local Notation eta_expand_with_bound1 := (@partial.ident.eta_expand_with_bound var1 abstract_domain' annotate_expr1 bottom' abstract_interp_ident extract_list_state extract_option_state is_annotated_for1).\n          Local Notation eta_expand_with_bound2 := (@partial.ident.eta_expand_with_bound var2 abstract_domain' annotate_expr2 bottom' abstract_interp_ident extract_list_state extract_option_state is_annotated_for2).\n          Lemma wf_eta_expand_with_bound {t} G e1 e2 (Hwf : expr.wf G e1 e2) st1 st2 (Hst : type.and_for_each_lhs_of_arrow (@abstract_domain_R) st1 st2)\n            : expr.wf G (@eta_expand_with_bound1 t e1 st1) (@eta_expand_with_bound2 t e2 st2).\n          Proof using abstract_interp_ident_Proper annotate_expr_Proper bottom'_Proper extract_list_state_length extract_list_state_rel extract_option_state_rel is_annotated_for_Proper.\n            eapply wf_eta_expand_with_bound';\n              solve [ eassumption\n                    | eapply wf_annotate\n                    | eapply wf_interp_ident ].\n          Qed.\n        End with_var2.\n      End with_type.\n    End ident.\n\n    Section specialized.\n      Import API.\n      Local Notation abstract_domain' := ZRange.type.base.option.interp (only parsing).\n      Local Notation abstract_domain := (@partial.abstract_domain base.type abstract_domain').\n      Local Notation abstract_domain'_R t := (@eq (abstract_domain' t)) (only parsing).\n      Local Notation abstract_domain_R := (@abstract_domain_R base.type abstract_domain' (fun t => abstract_domain'_R t)).\n      Local Notation wf_value := (@wf_value base.type ident abstract_domain' (fun t => abstract_domain'_R t)).\n\n      Lemma annotate_expr_Proper {relax_zrange var1 var2} {t} s1 s2\n        : abstract_domain'_R t s1 s2\n          -> option_eq (expr.wf nil)\n                       (@annotate_expr relax_zrange var1 t s1)\n                       (@annotate_expr relax_zrange var2 t s2).\n      Proof using Type.\n        intros ?; subst s2.\n        cbv [annotate_expr Crypto.Util.Option.bind option_eq]; break_innermost_match;\n          repeat constructor.\n      Qed.\n\n      Global Instance bottom'_Proper {t} : Proper (abstract_domain'_R t) (bottom' t).\n      Proof using Type. reflexivity. Qed.\n\n      Global Instance abstract_interp_ident_Proper {opts : AbstractInterpretation.Options} {assume_cast_truncates : bool} {t}\n        : Proper (eq ==> @abstract_domain_R t) (abstract_interp_ident assume_cast_truncates t).\n      Proof using Type.\n        cbv [abstract_interp_ident abstract_domain_R type.related respectful type.interp]; intros idc idc' ?; subst idc'; destruct idc;\n          repeat first [ reflexivity\n                       | progress subst\n                       | progress cbn [ZRange.type.base.option.interp ZRange.type.base.interp base.interp base.base_interp Crypto.Util.Option.bind] in *\n                       | progress cbv [Crypto.Util.Option.bind]\n                       | intro\n                       | progress destruct_head'_prod\n                       | progress destruct_head'_bool\n                       | progress destruct_head' option\n                       | progress inversion_option\n                       | discriminate\n                       | solve [ eauto ]\n                       | apply NatUtil.nat_rect_Proper_nondep\n                       | apply ListUtil.list_rect_Proper\n                       | apply ListUtil.list_rect_arrow_Proper\n                       | apply ListUtil.list_case_Proper\n                       | apply ListUtil.pointwise_map\n                       | apply ListUtil.fold_right_Proper\n                       | apply ListUtil.update_nth_Proper\n                       | apply (@nat_rect_Proper_nondep_gen (_ -> _) (eq ==> eq)%signature)\n                       | cbn; apply (f_equal (@Some _))\n                       | progress cbn [ZRange.ident.option.interp]\n                       | progress cbv [zrange_rect]\n                       | apply (f_equal2 pair)\n                       | break_innermost_match_step\n                       | match goal with\n                         | [ H : _ |- _ ] => erewrite H by (eauto; (eassumption || reflexivity))\n                         | [ H : forall x y, x = y -> _ |- _ ] => specialize (fun x => H x x eq_refl)\n                         | [ H : forall x, ?f x = ?g x, H1 : ?f ?y = _, H2 : ?g ?y = _ |- _ ]\n                           => specialize (H y); rewrite H1, H2 in H\n                         end ].\n      Qed.\n\n      Global Instance extract_list_state_Proper {t}\n        : Proper (abstract_domain'_R _ ==> option_eq (SetoidList.eqlistA (@abstract_domain'_R t)))\n                 (extract_list_state t).\n      Proof using Type.\n        intros st st' ?; subst st'; cbv [option_eq extract_list_state]; break_innermost_match; reflexivity.\n      Qed.\n\n      Local Notation tZ := (base.type.type_base base.type.Z).\n      Local Notation cstZ r\n        := (expr.App\n              (d:=type.arrow (type.base tZ) (type.base tZ))\n              (expr.Ident ident.Z_cast)\n              (expr.Ident (@ident.Literal base.type.zrange r%zrange))).\n      Local Notation cstZZ r1 r2\n        := (expr.App\n              (d:=type.arrow (type.base (tZ * tZ)) (type.base (tZ * tZ)))\n              (expr.Ident ident.Z_cast2)\n              (#(@ident.Literal base.type.zrange r1%zrange), #(@ident.Literal base.type.zrange r2%zrange))%expr_pat).\n\n      Lemma wf_always_strip_annotation {opts : AbstractInterpretation.Options} (assume_cast_truncates : bool) {var1 var2} G {t} idc\n        : option_eq (wf_value G)\n                    (always_strip_annotation assume_cast_truncates (var:=var1) t idc)\n                    (always_strip_annotation assume_cast_truncates (var:=var2) t idc).\n      Proof using Type.\n        cbv [always_strip_annotation]; break_innermost_match; try reflexivity;\n          cbn [option_eq wf_value].\n        all: repeat first [ progress intros\n                          | assumption\n                          | progress subst\n                          | exfalso; congruence\n                          | progress cbn [fst snd] in *\n                          | progress break_innermost_match\n                          | progress destruct_head'_and\n                          | match goal with\n                            | [ |- UnderLets.wf _ _ (Base _) (Base _) ] => constructor\n                            | [ |- _ /\\ _ ] => split\n                            end\n                          | solve [ wf_t ]\n                          | progress cbn [abstract_domain_R type.related] in * ].\n      Qed.\n\n      Lemma wf_strip_annotation {opts : AbstractInterpretation.Options} (assume_cast_truncates : bool) (strip_annotations : bool) {var1 var2} G {t} idc\n        : option_eq (wf_value G)\n                    (strip_annotation assume_cast_truncates strip_annotations (var:=var1) t idc)\n                    (strip_annotation assume_cast_truncates strip_annotations (var:=var2) t idc).\n      Proof using Type.\n        cbv [strip_annotation]; break_innermost_match; now try apply wf_always_strip_annotation.\n      Qed.\n\n      Local Arguments base.try_make_transport_cps / _ _ _.\n      Local Arguments type.try_make_transport_cps / _ _ _ _ _.\n      Lemma is_annotated_for_spec {relax_zrange var} t t' e st\n        : @is_annotated_for relax_zrange var t t' e st = true\n          <-> ((exists (pf : t' = tZ) r,\n                   (annotation_of_state relax_zrange (rew pf in st) = Some r)\n                   /\\ existT (@expr var) t e = existT (@expr var) _ (cstZ r))\n               \\/ (exists (pf : t' = (tZ * tZ)%etype) r1 r2,\n                      ((fun '(r1, r2) => (annotation_of_state relax_zrange r1, annotation_of_state relax_zrange r2))\n                         (rew pf in st) = (Some r1, Some r2))\n                      /\\ existT (@expr var) t e = existT (@expr var) _ (cstZZ r1 r2))).\n      Proof using Type.\n        split.\n        { cbv [is_annotated_for]; break_innermost_match; try discriminate.\n          all: rewrite ?Bool.andb_true_iff.\n          all: intro; destruct_head'_and; reflect_beq_to_eq (option_beq zrange_beq).\n          all: constructor; exists eq_refl; cbn [eq_rect].\n          all: repeat esplit; try apply (f_equal2 (@pair _ _)); try (symmetry; eassumption).\n          all: multimatch goal with\n               | [ H : invert_Z_cast _ = Some _ |- _ ]\n                 => apply expr.invert_Z_cast_Some in H\n               | [ H : invert_Z_cast2 _ = Some _ |- _ ]\n                 => apply expr.invert_Z_cast2_Some in H\n               end;\n            solve [ repeat first [ progress inversion_sigma\n                                 | progress subst\n                                 | progress cbn [eq_rect] in *\n                                 | reflexivity ] ]. }\n        { repeat first [ progress intros\n                       | progress subst\n                       | progress cbn [eq_rect fst snd] in *\n                       | progress inversion_option\n                       | progress inversion_sigma\n                       | progress inversion_prod\n                       | progress destruct_head'_ex\n                       | progress destruct_head'_and\n                       | progress destruct_head'_or\n                       | progress cbn\n                       | break_innermost_match_step\n                       | rewrite Bool.andb_true_iff\n                       | apply conj\n                       | apply zrange_lb\n                       | reflexivity ]. }\n      Qed.\n\n      Lemma is_annotated_for_Proper {relax_zrange var1 var2} G t t' e1 e2\n        : expr.wf G e1 e2\n          -> ((abstract_domain'_R _ ==> eq)%signature)\n               (@is_annotated_for relax_zrange var1 t t' e1)\n               (@is_annotated_for relax_zrange var2 t t' e2).\n      Proof using Type.\n        repeat intro; subst;\n          match goal with |- ?x = ?y => destruct x eqn:?, y eqn:? end.\n        all: repeat first [ match goal with\n                            | [ H : is_annotated_for _ _ _ _ _ = true |- _ ]\n                              => rewrite is_annotated_for_spec in H\n                            | [ H : ?x <> ?x |- _ ] => congruence\n                            end\n                          | reflexivity\n                          | exfalso; assumption\n                          | progress cbn [eq_rect fst snd projT1 projT2 andb] in *\n                          | progress subst\n                          | progress inversion_prod\n                          | progress destruct_head'_ex\n                          | progress destruct_head'_sig\n                          | progress destruct_head'_sigT\n                          | progress destruct_head'_prod\n                          | progress destruct_head'_and\n                          | progress reflect_beq_to_eq zrange_beq\n                          | progress inversion_sigma\n                          | progress inversion_option\n                          | progress destruct_head'_or\n                          | progress inversion_type\n                          | progress expr.inversion_wf_one_constr\n                          | progress expr.invert_subst\n                          | progress expr.invert_match\n                          | progress expr.inversion_expr\n                          | break_innermost_match_hyps_step\n                          | match goal with\n                            | [ H : is_annotated_for _ _ _ _ _ = false |- _ ]\n                              => progress cbn in H\n                            end ].\n      Qed.\n\n      Lemma wf_annotation_to_cast_helper {var1 var2 t G idc1 idc2}\n            (Hidc : idc1 = idc2)\n        : option_eq (fun f g => forall e1 e2, expr.wf G e1 e2 -> expr.wf G (f e1) (g e2))\n                    (@annotation_to_cast_helper var1 t idc1)\n                    (@annotation_to_cast_helper var2 t idc2).\n      Proof using Type.\n        subst idc2; destruct idc1; cbv; try reflexivity; intros; assumption.\n      Qed.\n\n      Lemma wf_annotation_to_cast {var1 var2 s d G e1 e2}\n            (Hwf : expr.wf G e1 e2)\n        : option_eq (fun f g => forall e1 e2, expr.wf G e1 e2 -> expr.wf G (f e1) (g e2))\n                    (@annotation_to_cast var1 s d e1)\n                    (@annotation_to_cast var2 s d e2).\n      Proof using Type.\n        cbv [annotation_to_cast];\n          repeat first [ progress wf_safe_t\n                       | congruence\n                       | progress inversion_option\n                       | progress cbn [fst snd projT1 projT2] in *\n                       | progress cbv [Option.bind] in *\n                       | progress break_innermost_match\n                       | progress break_innermost_match_hyps\n                       | progress expr.invert_subst\n                       | progress expr.inversion_wf_one_constr\n                       | progress cbn [invert_AppIdent invert_App invert_Ident invert_App_cps invert_AppIdent_cps Option.bind] in *\n                       | progress expr.invert_match\n                       | progress expr.inversion_expr\n                       | now refine (wf_annotation_to_cast_helper eq_refl) ].\n      Qed.\n\n      Lemma extract_list_state_length\n        : forall t v1 v2, abstract_domain'_R _ v1 v2 -> option_map (@length _) (extract_list_state t v1) = option_map (@length _) (extract_list_state t v2).\n      Proof using Type.\n        intros; subst; cbv [option_map extract_list_state]; break_innermost_match; reflexivity.\n      Qed.\n      Lemma extract_list_state_rel\n        : forall t v1 v2, abstract_domain'_R _ v1 v2 -> forall l1 l2, extract_list_state t v1 = Some l1 -> extract_list_state t v2 = Some l2 -> List.Forall2 (@abstract_domain'_R t) l1 l2.\n      Proof using Type.\n        intros; cbv [extract_list_state] in *; subst; inversion_option; subst.\n        now rewrite Forall2_Forall, Forall_forall; cbv [Proper].\n      Qed.\n\n      Lemma extract_option_state_rel\n        : forall t v1 v2, abstract_domain'_R _ v1 v2 -> option_eq (option_eq (abstract_domain'_R _)) (extract_option_state t v1) (extract_option_state t v2).\n      Proof using Type.\n        cbv [extract_option_state option_eq]; intros; subst; break_match; reflexivity.\n      Qed.\n\n      Section with_var2.\n        Context {var1 var2 : type -> Type}.\n        Local Notation wf_value_with_lets := (@wf_value_with_lets base.type ident abstract_domain' (fun t => abstract_domain'_R t) var1 var2).\n\n        Lemma wf_eval {opts : AbstractInterpretation.Options} {t} G G' e1 e2 (Hwf : expr.wf G e1 e2)\n              (HGG' : forall t v1 v2, List.In (existT _ t (v1, v2)) G -> wf_value_with_lets G' v1 v2)\n          : expr.wf G' (t:=t) (eval (var:=var1) e1) (eval (var:=var2) e2).\n        Proof using Type.\n          eapply ident.wf_eval;\n            solve [ eassumption\n                  | exact _\n                  | apply extract_list_state_length\n                  | apply extract_list_state_rel\n                  | apply extract_option_state_rel\n                  | apply wf_strip_annotation\n                  | intros; now apply annotate_expr_Proper\n                  | apply is_annotated_for_Proper ].\n        Qed.\n\n        Lemma wf_strip_all_annotations strip_annotations_under G t e1 e2 (Hwf : expr.wf G e1 e2)\n          : expr.wf G (@strip_all_annotations strip_annotations_under var1 t e1) (@strip_all_annotations strip_annotations_under var2 t e2).\n        Proof using Type. revert Hwf; apply ident.wf_strip_all_annotations, @wf_annotation_to_cast. Qed.\n\n        Lemma wf_eval_with_bound {opts : AbstractInterpretation.Options} {relax_zrange assume_cast_truncates skip_annotations_under strip_preexisting_annotations t} G G' e1 e2 (Hwf : expr.wf G e1 e2) st1 st2 (Hst : type.and_for_each_lhs_of_arrow (@abstract_domain_R) st1 st2)\n              (HGG' : forall t v1 v2, List.In (existT _ t (v1, v2)) G -> wf_value_with_lets G' v1 v2)\n          : expr.wf G' (var1:=var1) (var2:=var2) (t:=t)\n                    (eval_with_bound relax_zrange assume_cast_truncates skip_annotations_under strip_preexisting_annotations e1 st1)\n                    (eval_with_bound relax_zrange assume_cast_truncates skip_annotations_under strip_preexisting_annotations e2 st2).\n        Proof using Type.\n          eapply ident.wf_eval_with_bound;\n            solve [ eassumption\n                  | exact _\n                  | apply extract_list_state_length\n                  | apply extract_list_state_rel\n                  | apply extract_option_state_rel\n                  | apply wf_strip_annotation\n                  | intros; now apply annotate_expr_Proper\n                  | apply is_annotated_for_Proper ].\n        Qed.\n\n        Lemma wf_strip_annotations {opts : AbstractInterpretation.Options} {assume_cast_truncates} {t} G G' e1 e2 (Hwf : expr.wf G e1 e2) st1 st2 (Hst : type.and_for_each_lhs_of_arrow (@abstract_domain_R) st1 st2)\n              (HGG' : forall t v1 v2, List.In (existT _ t (v1, v2)) G -> wf_value_with_lets G' v1 v2)\n          : expr.wf G' (t:=t) (strip_annotations assume_cast_truncates (var:=var1) e1 st1) (strip_annotations assume_cast_truncates (var:=var2) e2 st2).\n        Proof using Type.\n          eapply ident.wf_eval_with_bound;\n            solve [ eassumption\n                  | exact _\n                  | apply extract_list_state_length\n                  | apply extract_list_state_rel\n                  | apply extract_option_state_rel\n                  | apply wf_strip_annotation\n                  | intros; now apply annotate_expr_Proper\n                  | apply is_annotated_for_Proper ].\n        Qed.\n\n        Lemma wf_eta_expand_with_bound {relax_zrange t} G e1 e2 (Hwf : expr.wf G e1 e2) st1 st2 (Hst : type.and_for_each_lhs_of_arrow (@abstract_domain_R) st1 st2)\n          : expr.wf G (t:=t) (eta_expand_with_bound relax_zrange (var:=var1) e1 st1) (eta_expand_with_bound relax_zrange (var:=var2) e2 st2).\n        Proof using Type.\n          eapply ident.wf_eta_expand_with_bound;\n            solve [ eassumption\n                  | exact _\n                  | apply extract_list_state_length\n                  | apply extract_list_state_rel\n                  | apply extract_option_state_rel\n                  | intros; now apply annotate_expr_Proper\n                  | apply is_annotated_for_Proper ].\n        Qed.\n      End with_var2.\n\n      Lemma Wf_StripAllAnnotations strip_annotations_under {t} (e : Expr t) (Hwf : Wf e) : Wf (StripAllAnnotations strip_annotations_under e).\n      Proof using Type.\n        intros ??; now apply wf_strip_all_annotations.\n      Qed.\n\n      Lemma Wf_Eval {opts : AbstractInterpretation.Options} {t} (e : Expr t) (Hwf : Wf e) : Wf (Eval e).\n      Proof using Type.\n        intros ??; eapply wf_eval with (G:=nil); cbn [List.In]; try apply Hwf; tauto.\n      Qed.\n\n      Lemma Wf_EvalWithBound {opts : AbstractInterpretation.Options} {relax_zrange assume_cast_truncates skip_annotations_under strip_preexisting_annotations t} (e : Expr t) bound (Hwf : Wf e) (bound_valid : Proper (type.and_for_each_lhs_of_arrow (@abstract_domain_R)) bound)\n        : Wf (EvalWithBound relax_zrange assume_cast_truncates skip_annotations_under strip_preexisting_annotations e bound).\n      Proof using Type.\n        intros ??; eapply wf_eval_with_bound with (G:=nil); cbn [List.In]; try apply Hwf; tauto.\n      Qed.\n\n      Lemma Wf_StripAnnotations {opts : AbstractInterpretation.Options} {assume_cast_truncates} {t} (e : Expr t) bound (Hwf : Wf e) (bound_valid : Proper (type.and_for_each_lhs_of_arrow (@abstract_domain_R)) bound)\n        : Wf (StripAnnotations assume_cast_truncates e bound).\n      Proof using Type.\n        intros ??; eapply wf_strip_annotations with (G:=nil); cbn [List.In]; try tauto; apply Hwf.\n      Qed.\n\n      Lemma Wf_EtaExpandWithBound {relax_zrange t} (e : Expr t) bound (Hwf : Wf e) (bound_valid : Proper (type.and_for_each_lhs_of_arrow (@abstract_domain_R)) bound)\n        : Wf (EtaExpandWithBound relax_zrange e bound).\n      Proof using Type.\n        intros ??; eapply wf_eta_expand_with_bound with (G:=nil); cbn [List.In]; try apply Hwf; tauto.\n      Qed.\n\n      Local Instance Proper_strip_ranges {t}\n        : Proper (@abstract_domain_R t ==> @abstract_domain_R t) (@ZRange.type.option.strip_ranges t).\n      Proof using Type.\n        cbv [Proper abstract_domain_R respectful].\n        induction t as [t|s IHs d IHd]; cbn in *; destruct_head'_prod; destruct_head'_and; cbn in *; intros; subst; cbv [respectful] in *;\n          eauto.\n      Qed.\n\n      Lemma Wf_EtaExpandWithListInfoFromBound {t} (e : Expr t) bound (Hwf : Wf e) (bound_valid : Proper (type.and_for_each_lhs_of_arrow (@abstract_domain_R)) bound)\n        : Wf (EtaExpandWithListInfoFromBound e bound).\n      Proof using Type.\n        eapply Wf_EtaExpandWithBound; [ assumption | ].\n        clear dependent e.\n        cbv [Proper] in *; induction t as [t|s IHs d IHd]; cbn in *; destruct_head'_prod; destruct_head'_and; cbn in *; eauto.\n        split; auto; apply Proper_strip_ranges; auto.\n      Qed.\n    End specialized.\n  End partial.\n#[global]\n  Hint Resolve Wf_Eval Wf_EvalWithBound Wf_EtaExpandWithBound Wf_EtaExpandWithListInfoFromBound Wf_StripAllAnnotations Wf_StripAnnotations : wf.\n#[global]\n  Hint Opaque partial.Eval partial.EvalWithBound partial.EtaExpandWithBound partial.EtaExpandWithListInfoFromBound partial.StripAnnotations partial.StripAllAnnotations : wf interp rewrite.\n  Import API.\n\n  Lemma Wf_PartialEvaluateWithListInfoFromBounds\n        {opts : AbstractInterpretation.Options}\n        {t} (E : Expr t)\n        (b_in : type.for_each_lhs_of_arrow ZRange.type.option.interp t)\n        (Hwf : Wf E)\n        {b_in_Proper : Proper (type.and_for_each_lhs_of_arrow (@abstract_domain_R base.type ZRange.type.base.option.interp (fun t0 : base.type => eq))) b_in}\n    : Wf (PartialEvaluateWithListInfoFromBounds E b_in).\n  Proof. cbv [PartialEvaluateWithListInfoFromBounds]; eauto with wf. Qed.\n#[global]\n  Hint Resolve Wf_PartialEvaluateWithListInfoFromBounds : wf.\n#[global]\n  Hint Opaque PartialEvaluateWithListInfoFromBounds : wf interp rewrite.\n\n  Lemma Wf_PartialEvaluateWithBounds\n        {opts : AbstractInterpretation.Options}\n        {relax_zrange} {assume_cast_truncates : bool} {skip_annotations_under : forall t, ident t -> bool} {strip_preexisting_annotations : bool} {t} (E : Expr t)\n        (b_in : type.for_each_lhs_of_arrow ZRange.type.option.interp t)\n        (Hwf : Wf E)\n        {b_in_Proper : Proper (type.and_for_each_lhs_of_arrow (@abstract_domain_R base.type ZRange.type.base.option.interp (fun t0 : base.type => eq))) b_in}\n    : Wf (PartialEvaluateWithBounds relax_zrange assume_cast_truncates skip_annotations_under strip_preexisting_annotations E b_in).\n  Proof. cbv [PartialEvaluateWithBounds]; eauto with wf. Qed.\n#[global]\n  Hint Resolve Wf_PartialEvaluateWithBounds : wf.\n#[global]\n  Hint Opaque PartialEvaluateWithBounds : wf interp rewrite.\nEnd Compilers.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/AbstractInterpretation/Wf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547239, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.20955443685489344}}
{"text": "(* About binders which remain unnamed after typing *)\n\nGlobal Set Asymmetric Patterns.\n\nDefinition proj2_sig_map {A} {P Q : A -> Prop} (f : forall a, P a -> Q a) (x :\n@sig A P) : @sig A Q\n  := let 'exist a p := x in exist Q a (f a p).\nAxioms (feBW' : Type) (g : Prop -> Prop) (f' : feBW' -> Prop).\nDefinition foo := @proj2_sig_map feBW' (fun  H  => True = f' _) (fun H =>\n g True = g (f' H))\n                                 (fun (a : feBW') (p : (fun H : feBW' => True =\n f' H) a) => @f_equal Prop Prop g True (f' a) p).\nPrint foo.\nGoal True.\n  lazymatch type of foo with\n  | sig (fun a : ?A => ?P) -> _\n    => pose (fun a : A => a = a /\\ P = P)\n  end.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/closed/5434.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.20955443440935556}}
{"text": "From iris.program_logic Require Export weakestpre.\nFrom iris.base_logic Require Import invariants lib.saved_prop.\nFrom iris.heap_lang Require Export lang.\nFrom iris.heap_lang Require Import proofmode.\nFrom iris.algebra Require Import auth gset.\nFrom iris_examples.barrier Require Export barrier.\nFrom iris.prelude Require Import options.\n\n(** The CMRAs/functors we need. *)\nClass barrierG Σ := BarrierG {\n  barrier_inG :> inG Σ (authR (gset_disjUR gname));\n  barrier_savedPropG :> savedPropG Σ;\n}.\nDefinition barrierΣ : gFunctors :=\n  #[ GFunctor (authRF (gset_disjUR gname)); savedPropΣ ].\n\nGlobal Instance subG_barrierΣ {Σ} : subG barrierΣ Σ → barrierG Σ.\nProof. solve_inG. Qed.\n\n(** Now we come to the Iris part of the proof. *)\nSection proof.\nContext `{!heapGS Σ, !barrierG Σ} (N : namespace).\n\nDefinition barrier_inv (l : loc) (γ : gname) (P : iProp Σ) : iProp Σ :=\n  (∃ (b : bool) (γsps : gset gname),\n    l ↦ #b ∗\n    own γ (● (GSet γsps)) ∗\n    ((if b then True else P) -∗\n      ([∗ set] γsp ∈ γsps, ∃ R, saved_prop_own γsp R ∗ ▷ R)))%I.\n\nDefinition recv (l : loc) (R : iProp Σ) : iProp Σ :=\n  (∃ γ P R' γsp,\n    inv N (barrier_inv l γ P) ∗\n    ▷ (R' -∗ R) ∗\n    own γ (◯ GSet {[ γsp ]}) ∗\n    saved_prop_own γsp R')%I.\n\nDefinition send (l : loc) (P : iProp Σ) : iProp Σ :=\n  (∃ γ, inv N (barrier_inv l γ P))%I.\n\n(** Setoids *)\nInstance barrier_inv_ne l γ : NonExpansive (barrier_inv l γ).\nProof. solve_proper. Qed.\nGlobal Instance send_ne l : NonExpansive (send l).\nProof. solve_proper. Qed.\nGlobal Instance recv_ne l : NonExpansive (recv l).\nProof. solve_proper. Qed.\n\n(** Actual proofs *)\nLemma newbarrier_spec (P : iProp Σ) :\n  {{{ True }}} newbarrier #() {{{ l, RET #l; recv l P ∗ send l P }}}.\nProof.\n  iIntros (Φ) \"_ HΦ\". wp_lam. wp_alloc l as \"Hl\".\n  iApply (\"HΦ\" with \"[> -]\").\n  iMod (saved_prop_alloc P) as (γsp) \"#Hsp\".\n  iMod (own_alloc (● GSet {[ γsp ]} ⋅ ◯ GSet {[ γsp ]})) as (γ) \"[H● H◯]\".\n  { by apply auth_both_valid_discrete. }\n  iMod (inv_alloc N _ (barrier_inv l γ P) with \"[Hl H●]\") as \"#Hinv\".\n  { iExists false, {[ γsp ]}. iIntros \"{$Hl $H●} !> HP\".\n    rewrite big_sepS_singleton; eauto. }\n  iModIntro; iSplitL \"H◯\".\n  - iExists γ, P, P, γsp. iFrame; auto.\n  - by iExists γ.\nQed.\n\nLemma signal_spec l P :\n  {{{ send l P ∗ P }}} signal #l {{{ RET #(); True }}}.\nProof.\n  iIntros (Φ) \"[Hs HP] HΦ\". iDestruct \"Hs\" as (γ) \"#Hinv\". wp_lam.\n  iInv N as ([] γsps) \"(>Hl & H● & HRs)\".\n  { wp_store. iModIntro. iSplitR \"HΦ\"; last by iApply \"HΦ\".\n    iExists true, γsps. iFrame. }\n  wp_store. iDestruct (\"HRs\" with \"HP\") as \"HRs\".\n  iModIntro. iSplitR \"HΦ\"; last by iApply \"HΦ\".\n  iExists true, γsps. iFrame; eauto.\nQed.\n\nLemma wait_spec l P:\n  {{{ recv l P }}} wait #l {{{ RET #(); P }}}.\nProof.\n  rename P into R.\n  iIntros (Φ) \"HR HΦ\". iDestruct \"HR\" as (γ P R' γsp) \"(#Hinv & HR & H◯ & #Hsp)\".\n  iLöb as \"IH\". wp_rec. wp_bind (! _)%E.\n  iInv N as ([] γsps) \"(>Hl & >H● & HRs)\"; last first.\n  { wp_load. iModIntro. iSplitL \"Hl H● HRs\".\n    { iExists false, γsps. iFrame. }\n    wp_pures. by wp_apply (\"IH\" with \"[$] [$]\"). }\n  iSpecialize (\"HRs\" with \"[//]\"). wp_load.\n  iDestruct (own_valid_2 with \"H● H◯\")\n    as %[Hvalid%gset_disj_included%elem_of_subseteq_singleton _]%auth_both_valid_discrete.\n  iDestruct (big_sepS_delete with \"HRs\") as \"[HR'' HRs]\"; first done.\n  iDestruct \"HR''\" as (R'') \"[#Hsp' HR'']\".\n  iDestruct (saved_prop_agree with \"Hsp Hsp'\") as \"#Heq\".\n  iMod (own_update_2 with \"H● H◯\") as \"H●\".\n  { apply (auth_update_dealloc _ _ (GSet (γsps ∖ {[ γsp ]}))).\n    apply gset_disj_dealloc_local_update. }\n  iIntros \"!>\". iSplitL \"Hl H● HRs\".\n  { iDestruct (bi.later_intro with \"HRs\") as \"HRs\".\n    iModIntro. iExists true, (γsps ∖ {[ γsp ]}). iFrame; eauto. }\n  wp_if. iApply \"HΦ\". iApply \"HR\". by iRewrite \"Heq\".\nQed.\n\nLemma recv_split E l P1 P2 :\n  ↑N ⊆ E → recv l (P1 ∗ P2) ={E}=∗ recv l P1 ∗ recv l P2.\nProof.\n  rename P1 into R1; rename P2 into R2.\n  iIntros (?). iDestruct 1 as (γ P R' γsp) \"(#Hinv & HR & H◯ & #Hsp)\".\n  iInv N as (b γsps) \"(>Hl & >H● & HRs)\".\n  iDestruct (own_valid_2 with \"H● H◯\")\n    as %[Hvalid%gset_disj_included%elem_of_subseteq_singleton _]%auth_both_valid_discrete.\n  iMod (own_update_2 with \"H● H◯\") as \"H●\".\n  { apply (auth_update_dealloc _ _ (GSet (γsps ∖ {[ γsp ]}))).\n    apply gset_disj_dealloc_local_update. }\n  set (γsps' := γsps ∖ {[γsp]}).\n  iMod (saved_prop_alloc_cofinite γsps' R1) as (γsp1 Hγsp1) \"#Hsp1\".\n  iMod (saved_prop_alloc_cofinite (γsps' ∪ {[ γsp1 ]}) R2)\n    as (γsp2 [? ?%not_elem_of_singleton_1]%not_elem_of_union) \"#Hsp2\".\n  iMod (own_update _ _ (● _ ⋅ (◯ GSet {[ γsp1 ]} ⋅ ◯ (GSet {[ γsp2 ]})))\n    with \"H●\") as \"(H● & H◯1 & H◯2)\".\n  { rewrite -auth_frag_op gset_disj_union; last set_solver.\n    apply auth_update_alloc, (gset_disj_alloc_empty_local_update _ {[ γsp1; γsp2 ]}).\n    set_solver. }\n  iModIntro. iSplitL \"HR Hl HRs H●\".\n  { iModIntro. iExists b, ({[γsp1; γsp2]} ∪ γsps').\n    iIntros \"{$Hl $H●} HP\". iSpecialize (\"HRs\" with \"HP\").\n    iDestruct (big_sepS_delete with \"HRs\") as \"[HR'' HRs]\"; first done.\n    iDestruct \"HR''\" as (R'') \"[#Hsp' HR'']\".\n    iDestruct (saved_prop_agree with \"Hsp Hsp'\") as \"#Heq\".\n    iAssert (▷ R')%I with \"[HR'']\" as \"HR'\"; [iNext; by iRewrite \"Heq\"|].\n    iDestruct (\"HR\" with \"HR'\") as \"[HR1 HR2]\".\n    iApply big_sepS_union; first set_solver. iFrame \"HRs\".\n    iApply big_sepS_union; first set_solver.\n    iSplitL \"HR1\"; rewrite big_sepS_singleton; eauto. }\n  iModIntro; iSplitL \"H◯1\".\n  - iExists γ, P, R1, γsp1. iFrame; auto.\n  - iExists γ, P, R2, γsp2. iFrame; auto.\nQed.\n\nLemma recv_weaken l P1 P2 : (P1 -∗ P2) -∗ recv l P1 -∗ recv l P2.\nProof.\n  iIntros \"HP\". iDestruct 1 as (γ P R' i) \"(#Hinv & HR & H◯)\".\n  iExists γ, P, R', i. iIntros \"{$Hinv $H◯} !> HQ\". iApply \"HP\". by iApply \"HR\".\nQed.\n\nLemma recv_mono l P1 P2 : (P1 ⊢ P2) → recv l P1 ⊢ recv l P2.\nProof. iIntros (HP) \"H\". iApply (recv_weaken with \"[] H\"). iApply HP. Qed.\nEnd proof.\n\nTypeclasses Opaque send recv.\n", "meta": {"author": "pavel-ivanov-rnd", "repo": "iris-heaplang-experiments", "sha": "a283a53fe994672f7a6dbdaefa0d4eedd044b733", "save_path": "github-repos/coq/pavel-ivanov-rnd-iris-heaplang-experiments", "path": "github-repos/coq/pavel-ivanov-rnd-iris-heaplang-experiments/iris-heaplang-experiments-a283a53fe994672f7a6dbdaefa0d4eedd044b733/theories/barrier/proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961016, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.20955443440935553}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Abhishek Anand & Vincent Rahli\n\n*)\n\n\nRequire Export approx.\nRequire Export atom_ren.\n(** printing #  $\\times$ #×# *)\n(** printing <=>  $\\Leftrightarrow$ #&hArr;# *)\n(** printing $  $\\times$ #×# *)\n(** printing &  $\\times$ #×# *)\n\n\nLemma respects_alpha_r2 {o} :\n  forall (r1 r2 : bin_rel (@NTerm o)),\n    respects_alpha_r r1\n    -> respects_alpha_r r2\n    -> respects_alpha_r (r1 \\2/ r2).\nProof.\n  introv resp1 resp2; introv aeq r.\n  allsimpl; repndors.\n  - eapply resp1 in aeq; apply aeq in r; auto.\n  - eapply resp2 in aeq; apply aeq in r; auto.\nQed.\nHint Resolve respects_alpha_r2 : slow.\n\nLemma respects_alpha_l2 {o} :\n  forall (r1 r2 : bin_rel (@NTerm o)),\n    respects_alpha_l r1\n    -> respects_alpha_l r2\n    -> respects_alpha_l (r1 \\2/ r2).\nProof.\n  introv resp1 resp2; introv aeq r.\n  allsimpl; repndors.\n  - eapply resp1 in aeq; apply aeq in r; auto.\n  - eapply resp2 in aeq; apply aeq in r; auto.\nQed.\nHint Resolve respects_alpha_l2 : slow.\n\nLemma respects_alpha_r_bot2 {o} :\n  respects_alpha_r (@bot2 o).\nProof.\n  introv aeq x; tcsp.\nQed.\nHint Resolve respects_alpha_r_bot2 : slow.\n\nLemma respects_alpha_l_bot2 {o} :\n  respects_alpha_l (@bot2 o).\nProof.\n  introv aeq x; tcsp.\nQed.\nHint Resolve respects_alpha_l_bot2 : slow.\n\nLemma approx_bad_implies_approx {o} :\n  forall lib (t1 t2 : @NTerm o),\n    approx_bad lib t1 t2 -> approx lib t1 t2.\nProof.\n  intro lib.\n  pose proof\n       (approx_acc\n          lib\n          (fun a b => approx_bad lib a b)\n          (@bot2 o)) as HH.\n  allsimpl.\n  match goal with\n      [ HH : _ -> ?B |- _ ] => assert B as h;[|introv ap; eapply h; eauto]\n  end.\n  introv ap.\n  apply HH; auto; clear HH ap.\n  introv hb hr ap.\n\n  inversion ap as [? ? ? cl]; subst; clear ap.\n  constructor.\n  allunfold @close_comput; repnd; dands; auto.\n\n  - introv comp.\n    clear cl3 cl.\n    apply cl2 in comp; exrepnd.\n    eexists; dands; eauto.\n    allunfold @lblift; dands; repnd; auto.\n    introv i.\n    apply comp0 in i.\n    allunfold @blift; exrepnd.\n    eexists; eexists; eexists; dands; eauto.\n    allunfold @olift; repnd; dands; auto.\n\n  - introv comp.\n    clear cl2 cl.\n    apply cl3 in comp; exrepnd.\n    eexists; eexists; dands; eauto.\n\n  - introv comp.\n    apply cl4 in comp; exrepnd.\n    eexists; dands; eauto.\nQed.\n\nLemma approx_implies_approx_bad {o} :\n  forall lib (t1 t2 : @NTerm o),\n    approx lib t1 t2 -> approx_bad lib t1 t2.\nProof.\n  intro lib.\n  cofix IND.\n  introv apr.\n  inversion apr as [cl].\n  constructor.\n  allunfold @close_comput; repnd; dands; auto.\n\n  - introv comp.\n    clear cl3 cl.\n    apply cl2 in comp; exrepnd.\n    eexists; dands; eauto.\n    allunfold @lblift; dands; repnd; auto.\n    introv i.\n    apply comp0 in i; clear comp0.\n    allunfold @blift; exrepnd.\n    eexists; eexists; eexists; dands; eauto.\n    allunfold @olift; repnd; dands; auto.\n    introv wf isp1 isp2.\n    pose proof (i1 sub wf isp1 isp2) as h; clear i1.\n    repndors.\n    + apply IND; auto.\n    + unfold bot2 in h; tcsp.\n\n  - introv comp.\n    clear cl2 cl.\n    apply cl3 in comp; exrepnd.\n    repndors; try (complete (allunfold @bot2; sp)).\n    eexists; eexists; dands; eauto.\n\n  - introv comp.\n    apply cl4 in comp; exrepnd.\n    eexists; dands; eauto.\n    introv.\n    pose proof (comp0 n) as h; repndors; tcsp.\n    unfold bot2 in h; tcsp.\nQed.\n\nLemma approx_open_simpler_equiv_r {o} :\n  forall lib (a c : @NTerm o) r,\n    respects_alpha_r (approx_aux lib r \\2/ r)\n    -> respects_alpha_l (approx_aux lib r \\2/ r)\n    -> (simpl_olift (approx_aux lib r \\2/ r) a c <=> olift (approx_aux lib r \\2/ r) a c).\nProof.\n  introv rr rl.\n  split.\n\n  - intro Hos.\n    repnud Hos.\n    unfold olift.\n    dands;auto.\n    introv Hwfs Hispa Hispc.\n    pose proof (lsubst_trim2_alpha1 _ _ _ Hispc Hispa) as Xtrim.\n    pose proof (lsubst_trim2_alpha2 _ _ _ Hwfs Hispc Hispa) as Xprog.\n    allsimpl. repnd. rename Xtrim into Xtrima.\n    rename Xtrim0 into Xtrimc.\n    revert Hispa Hispc. alpharw Xtrima. alpharw Xtrimc.\n    introv Hispa Hispc.\n    pose proof (Hos (sub_keep_first sub (free_vars c ++ free_vars a))) as h.\n    repeat (autodimp h hyp).\n    unfold respects2_r in rr.\n    unfold respects2_l in rl.\n    pose proof (rr (lsubst a (sub_keep_first sub (free_vars c ++ free_vars a)))\n                   (lsubst c (sub_keep_first sub (free_vars c ++ free_vars a)))\n                   (lsubst c sub))\n         as h1.\n    autodimp h1 hyp; eauto 2 with slow.\n    apply h1 in h; clear h1.\n    pose proof (rl (lsubst a (sub_keep_first sub (free_vars c ++ free_vars a)))\n                   (lsubst c sub)\n                   (lsubst a sub))\n         as h1.\n    autodimp h1 hyp; eauto 2 with slow.\n\n  - intro Hos.\n    repnud Hos.\n    unfold olift in Hos; unfold simpl_olift; repnd; dands; auto.\n    introv ps isp1 isp2.\n    pose proof (Hos sub) as h.\n    repeat (autodimp h hyp); eauto with slow.\nQed.\n\n(*\nDefinition rens_utokens {o} (rens : list (@utok_ren o)) (t : NTerm) :=\n  ren_utokens (flatten rens) t.\n\nInductive correct_rens {o} : list (@utok_ren o) -> list (get_patom_set o) -> Type :=\n| correct_rens_nil : forall atoms, correct_rens [] atoms\n| correct_rens_cons :\n    forall ren rens atoms,\n      disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) atoms)\n      -> no_repeats (range_utok_ren ren)\n      -> no_repeats (dom_utok_ren ren)\n      -> disjoint (dom_utok_ren ren) (range_utok_ren ren)\n      -> correct_rens rens (map (ren_atom ren) atoms)\n      -> correct_rens (ren :: rens) atoms.\n\nLemma approx_change_utoks {o} :\n  forall lib (t1 t2 : @NTerm o) rens,\n    correct_rens rens (get_utokens t1 ++ get_utokens t2)\n    -> approx lib t1 t2\n    -> approx lib (rens_utokens rens t1) (rens_utokens rens t2).\nProof.\n  intro lib.\n\n(*\n  cofix IND.\n\n  introv nr1 nr2 disj1 disj2 apr.\n*)\n\n  pose proof\n       (approx_acc\n          lib\n          (fun a b => {t1,t2 : NTerm\n                       $ {ren : utok_ren\n                       $ approx lib t1 t2\n                       # no_repeats (range_utok_ren ren)\n                       # no_repeats (dom_utok_ren ren)\n                       # disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t1))\n                       # disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t2))\n                       # a = ren_utokens ren t1\n                       # b = ren_utokens ren t2}})\n          (@bot2 o)) as HH.\n  allsimpl.\n  match goal with\n      [ HH : _ -> ?B |- _ ] =>\n      assert B as h;\n        [|introv nr1 nr2 d1 d2 k; eapply h;\n          eexists;eexists;eexists;dands;eauto;fail]\n  end.\n\n  apply HH; clear HH.\n  introv hb hr h; exrepnd; subst.\n  rename h1 into apr.\n\n\n  constructor.\n  (*inversion apr as [? ? ? cl]; subst; clear apr.*)\n  inversion apr as [cl]; clear apr.\n  allunfold @close_comput; repnd; dands; tcsp; eauto with slow; introv comp.\n\n  - clear cl3 cl.\n    dup comp as comp1.\n    apply (computes_to_value_ren_utokens _ _ _ (inv_utok_ren ren)) in comp1;\n    allrw @range_utok_ren_inv_utok_ren;\n    allrw @dom_utok_ren_inv_utok_ren;\n    auto;[|rw @get_utokens_ren_utokens; apply disjoint_dom_diff_range_map_ren_atom].\n    rw @inv_ren_utokens in comp1; auto.\n\n    rw @ren_utokens_can in comp1.\n\n    dup comp1 as comp2.\n    apply cl2 in comp2; exrepnd.\n    apply (computes_to_value_ren_utokens _ _ _ ren) in comp2; auto.\n    rw @ren_utokens_can in comp2.\n\n    assert (match\n               get_utok_c\n                 match get_utok_c c with\n                   | Some a => NUTok (ren_atom (inv_utok_ren ren) a)\n                   | None => c\n                 end\n             with\n               | Some a => NUTok (ren_atom ren a)\n               | None =>\n                 match get_utok_c c with\n                   | Some a => NUTok (ren_atom (inv_utok_ren ren) a)\n                   | None => c\n                 end\n             end = c) as e.\n    { destruct c; allsimpl; tcsp.\n      rw @inv_ren_atom2; auto.\n      apply computes_to_value_preserves_utokens in comp; allsimpl.\n      rw subset_cons_l in comp; repnd.\n      intro i.\n      rw @get_utokens_ren_utokens in comp3.\n      rw in_map_iff in comp3; exrepnd; subst.\n      rw in_diff in i; repnd.\n      destruct (ren_atom_or ren a) as [d|d]; tcsp.\n      rw d in i0.\n      apply in_dom_in_range in i0; auto.\n    }\n    rw e in comp2; clear e.\n\n    eexists; dands;[exact comp2|].\n    unfold lblift; unfold lblift in comp0.\n    allrw map_length; repnd; dands; auto.\n    introv i.\n    applydup comp0 in i.\n    unfold blift; unfold blift in i0.\n    exrepnd.\n    repeat (onerw @selectbt_map; auto; try omega).\n    remember (selectbt tl_subterms n) as b1.\n    remember (selectbt tr_subterms n) as b2.\n\n    apply (alpha_eq_bterm_ren_utokens_b _ _ ren) in i1.\n    apply (alpha_eq_bterm_ren_utokens_b _ _ ren) in i2.\n\n    assert (disjoint (dom_utok_ren ren)\n                     (diff (get_patom_deq o)\n                           (range_utok_ren ren)\n                           (get_utokens_b b1))) as d.\n    {\n(*      clear IND.*)\n      admit.\n    }\n\n    rw @inv_ren_utokens_b2 in i2; auto.\n    allsimpl.\n    exists lv (ren_utokens ren nt1) (ren_utokens ren nt2); dands; auto.\n\n    unfold olift; unfold olift in i0; repnd.\n    dands.\n    { apply nt_wf_ren_utokens; auto. }\n    { apply nt_wf_ren_utokens; auto. }\n    introv wfs isp1 isp2.\n\n\n    pose proof (ex_new_utok_ren\n                  (dom_utok_ren ren)\n                  (dom_utok_ren ren\n                                ++ range_utok_ren ren\n                                ++ get_utokens_sub sub\n                                ++ get_utokens nt1\n                                ++ get_utokens nt2)) as h.\n    destruct h as [ren' h]; repnd.\n    allrw disjoint_app_l; repnd.\n\n    pose proof (lsubst_ren_utokens2 nt1 ren ren' sub) as e1.\n    repeat (autodimp e1 hyp); eauto 3 with slow.\n    pose proof (lsubst_ren_utokens2 nt2 ren ren' sub) as e2.\n    repeat (autodimp e2 hyp); eauto 3 with slow.\n\n    pose proof (ren_utokens_ren_utokens\n                  (lsubst nt1 (ren_utokens_sub ren' sub))\n                  (inv_utok_ren ren')\n                  ren) as f1.\n    rw @compose_ren_utokens_trivial in f1;\n      [|rw @dom_utok_ren_inv_utok_ren; eauto 2 with slow].\n\n    pose proof (ren_utokens_ren_utokens\n                  (lsubst nt2 (ren_utokens_sub ren' sub))\n                  (inv_utok_ren ren')\n                  ren) as f2.\n    rw @compose_ren_utokens_trivial in f2;\n      [|rw @dom_utok_ren_inv_utok_ren; eauto 2 with slow].\n\n    rw <- f1 in e1; rw <- f2 in e2; clear f1 f2.\n\n    rewrite e1, e2; clear e1 e2.\n\n    pose proof (i0 (ren_utokens_sub ren' sub)) as q; clear i0.\n    repeat (autodimp q hyp); eauto 2 with slow.\n    { apply isprogram_lsubst_iff in isp1; repnd.\n      apply isprogram_lsubst_iff.\n      rw @nt_wf_ren_utokens_iff in isp0; dands; auto.\n      introv j.\n      rw @free_vars_ren_utokens in isp1.\n      apply isp1 in j; exrepnd.\n      rw @sub_find_ren_utokens_sub; rw j1.\n      eexists; dands; eauto.\n      - apply nt_wf_ren_utokens; auto.\n      - unfold closed; rw @free_vars_ren_utokens; auto. }\n    { apply isprogram_lsubst_iff in isp2; repnd.\n      apply isprogram_lsubst_iff.\n      rw @nt_wf_ren_utokens_iff in isp0; dands; auto.\n      introv j.\n      rw @free_vars_ren_utokens in isp2.\n      apply isp2 in j; exrepnd.\n      rw @sub_find_ren_utokens_sub; rw j1.\n      eexists; dands; eauto.\n      - apply nt_wf_ren_utokens; auto.\n      - unfold closed; rw @free_vars_ren_utokens; auto. }\n\n    repndors; tcsp; try (complete (allunfold @bot2; sp)).\n\n(*\n    pose proof\n         (hr\n            (ren_utokens ren (lsubst nt1 (ren_utokens_sub ren' sub)))\n            (ren_utokens ren (lsubst nt2 (ren_utokens_sub ren' sub))))\n      as ind1.\n    autodimp ind1 hyp.\n    { exists\n        (lsubst nt1 (ren_utokens_sub ren' sub))\n        (lsubst nt2 (ren_utokens_sub ren' sub))\n        ren; dands; auto.\n      - admit.\n      - admit.\n    }\n*)\n\n\n    apply IND; tcsp.\n    { rw @range_utok_ren_inv_utok_ren; rw h0; auto. }\n    { rw @dom_utok_ren_inv_utok_ren; auto. }\n    { clear IND; admit. }\n    { clear IND; admit. }\n\n    apply IND; tcsp.\n    { clear IND; admit. }\n    { clear IND; admit. }\n\n  - clear IND; admit.\n\n  - clear IND; admit.\nQed.\n\n(*\n\n      apply hr.\n      exists (lsubst nt1 (ren_utokens_sub ren' sub))\n             (lsubst nt2 (ren_utokens_sub ren' sub))\n             ren;\n        dands; eauto 3 with slow.\n\n      * rw @range_utok_ren_app.\n        rw @range_utok_ren_inv_utok_ren.\n        apply no_repeats_app; dands; eauto 3 with slow.\n        { rw h7; auto. }\n        { eauto 3 with slow. }\n\npose proof (hr (ren_utokens (ren ++ inv_utok_ren ren')\n                                  (lsubst nt1 (ren_utokens_sub ren' sub)))\n                     (ren_utokens (ren ++ inv_utok_ren ren')\n                                  (lsubst nt2 (ren_utokens_sub ren' sub)))\n*)\n\nQed.\n\nXXXXXXXXX\n*)\n\n\n(*\nLemma alpha_eq_swap_lsubst_aux_var_ren {o} :\n  forall (t : @NTerm o) vs1 vs2,\n    no_repeats vs2\n    -> disjoint vs2 vs1\n    -> disjoint vs2 (free_vars t)\n    -> disjoint vs2 (bound_vars t)\n    -> alpha_eq (swap (mk_swapping vs1 vs2) t)\n                (lsubst_aux t (var_ren vs1 vs2)).\nProof.\n  nterm_ind1s t as [v|op bs ind] Case; introv norep disj1 disj2 disj3.\n\n  - Case \"vterm\".\n    allsimpl.\n    allrw disjoint_singleton_r.\n    rw @sub_find_var_ren_as_option_map.\n    rw swapvar_eq; eauto 2 with slow.\n    remember (renFind (mk_swapping vs1 vs2) v) as rf; destruct rf; allsimpl; auto.\n\n  - Case \"oterm\"; allsimpl.\n    apply alpha_eq_oterm_combine; allrw map_length; dands; auto.\n    introv i.\n    allrw <- @map_combine; allrw in_map_iff; exrepnd; cpx.\n    destruct a0 as [l1 t1].\n    destruct a as [l2 t2]; allsimpl.\n    applydup in_combine in i1; repnd.\n    disj_flat_map; allsimpl.\n    allrw disjoint_app_r; repnd.\nQed.\n*)\n\nDefinition approx_or_bts {o} lib (r : bin_rel (@NTerm o)) :=\n  lblift (olift (approx_aux lib r \\2/ r)).\n\nLemma approx_or_bts_alpha_eq_bterms_l {o} :\n  forall lib (bs1 bs2 bs3 : list (@BTerm o)) r,\n    alpha_eq_bterms bs1 bs2\n    -> approx_or_bts lib r bs1 bs3\n    -> approx_or_bts lib r bs2 bs3.\nProof.\n  introv aeq apr.\n  allunfold @approx_or_bts.\n  allunfold @lblift; repnd.\n  allunfold @alpha_eq_bterms; repnd.\n  dands; tcsp.\n  introv i.\n  rw <- aeq0 in i; applydup apr in i.\n\n  assert (alpha_eq_bterm (selectbt bs1 n) (selectbt bs2 n)) as a.\n  { apply aeq.\n    unfold selectbt.\n    apply in_nth_combine; auto. }\n\n  eapply blift_alpha_fun_l; eauto with slow.\nQed.\n\nLemma approx_or_bts_alpha_eq_bterms_r {o} :\n  forall lib (bs1 bs2 bs3 : list (@BTerm o)) r,\n    alpha_eq_bterms bs2 bs3\n    -> approx_or_bts lib r bs1 bs3\n    -> approx_or_bts lib r bs1 bs2.\nProof.\n  introv aeq apr.\n  allunfold @approx_or_bts.\n  allunfold @lblift; repnd.\n  allunfold @alpha_eq_bterms; repnd.\n  dands; tcsp; try omega.\n  introv i.\n  applydup apr in i.\n\n  assert (alpha_eq_bterm (selectbt bs2 n) (selectbt bs3 n)) as a.\n  { apply aeq.\n    unfold selectbt.\n    apply in_nth_combine; auto; try omega. }\n\n  eapply blift_alpha_fun_r; eauto with slow.\nQed.\n\nLemma respects_alpha_r_approx_aux {o} :\n  forall lib (r : bin_rel (@NTerm o)),\n    respects_alpha_r r\n    -> respects_alpha_r (approx_aux lib r).\nProof.\n  introv resp; introv aeq apr.\n  revert resp a b b' aeq apr.\n\n  pose proof\n       (approx_acc\n          lib\n          (fun a b => {c : NTerm\n                       $ respects_alpha_r r\n                       # alpha_eq c b\n                       # approx_aux lib r a c})\n          r) as HH.\n  allsimpl.\n  match goal with\n      [ HH : _ -> ?B |- _ ] =>\n      assert B as h;\n        [|introv resp aeq apr; eapply h; exists b; dands; auto; fail]\n  end.\n\n  apply HH; clear HH.\n  introv hb hr h; exrepnd; subst.\n  rename h1 into resp.\n  rename h2 into aeq.\n  rename h0 into apr.\n\n  inversion apr as [cl].\n  constructor.\n  rename x0 into a.\n  rename c into b.\n  rename x1 into c.\n  allunfold @close_comput; repnd; dands; tcsp.\n\n  - apply alphaeq_preserves_program in aeq; apply aeq; auto.\n\n  - clear cl3 cl.\n    introv comp.\n    apply cl2 in comp.\n    exrepnd.\n    eapply compute_to_value_alpha in comp1; eauto 3 with slow; exrepnd.\n    applydup @alpha_eq_oterm_implies_combine in comp2; exrepnd; subst.\n    exists bs'; dands; auto.\n    allunfold @lblift; repnd; dands; auto; try omega.\n    introv i.\n    applydup comp0 in i.\n    allunfold @blift; exrepnd.\n    pose proof (comp4 (selectbt tr_subterms n) (selectbt bs' n)) as h.\n    autodimp h hyp.\n    { unfold selectbt; apply in_nth_combine; auto; try omega. }\n\n    exists lv nt1 nt2; dands; eauto 3 with slow.\n\n    allunfold @olift; repnd; dands; auto.\n    introv wfs isp1 isp2.\n    pose proof (i0 sub wfs isp1 isp2) as k; clear i0.\n    repndors; tcsp.\n    right; apply hr.\n    exists (lsubst nt2 sub); dands; auto.\n\n  - clear cl2 cl.\n    introv comp.\n    apply cl3 in comp.\n    exrepnd.\n    eapply compute_to_exception_alpha in comp0; eauto 3 with slow; exrepnd.\n    exists a'0 t2'; dands; auto.\n\n    + clear comp1.\n      repndors; tcsp.\n\n      * right.\n        apply hr.\n        exists a'; dands; auto.\n\n      * right.\n        apply hb; auto.\n        eapply resp; eauto.\n\n    + clear comp2.\n      repndors; tcsp.\n\n      * right.\n        apply hr.\n        exists e'; dands; auto.\n\n      * right.\n        apply hb; auto.\n        eapply resp; eauto.\n\n(*\n  - clear cl2 cl3.\n    introv comp.\n    apply cl in comp.\n    eapply compute_to_marker_alpha in comp; eauto.\n*)\n\n  - introv comp.\n    apply cl4 in comp; exrepnd.\n    eapply computes_to_seq_alpha in comp1; eauto 3 with slow; exrepnd.\n    eexists; dands; eauto.\n    introv.\n    pose proof (comp0 n) as h; clear comp0.\n    pose proof (comp2 n) as q; clear comp2.\n\n    repndors; tcsp; right.\n\n    + apply hr.\n      eexists; dands; eauto.\n\n    + apply hb.\n      eapply resp; eauto.\nQed.\nHint Resolve respects_alpha_r_approx_aux : slow.\n\nLemma alpha_eq_respects_nt_wf {o} :\n  forall (a b : @NTerm o),\n    alpha_eq a b\n    -> nt_wf a\n    -> nt_wf b.\nProof.\n  introv aeq wf.\n  apply alphaeq_preserves_wf in aeq; apply aeq; auto.\nQed.\nHint Resolve alpha_eq_respects_nt_wf : slow.\n\nLemma alpha_eq_respects_nt_wf_inv {o} :\n  forall (a b : @NTerm o),\n    alpha_eq a b\n    -> nt_wf b\n    -> nt_wf a.\nProof.\n  introv aeq wf; apply alpha_eq_sym in aeq; eauto 3 with slow.\nQed.\nHint Resolve alpha_eq_respects_nt_wf_inv : slow.\n\nLemma respects_alpha_l_approx_aux {o} :\n  forall lib (r : bin_rel (@NTerm o)),\n    respects_alpha_l r\n    -> respects_alpha_l (approx_aux lib r).\nProof.\n  introv resp; introv aeq apr.\n  apply alpha_eq_sym in aeq.\n  revert resp a b a' aeq apr.\n\n  pose proof\n       (approx_acc\n          lib\n          (fun a b => {c : NTerm\n                       $ respects_alpha_l r\n                       # alpha_eq a c\n                       # approx_aux lib r c b})\n          r) as HH.\n  allsimpl.\n  match goal with\n      [ HH : _ -> ?B |- _ ] =>\n      assert B as h;\n        [|introv resp aeq apr; eapply h; exists a; dands; auto; fail]\n  end.\n\n  apply HH; clear HH.\n  introv hb hr h; exrepnd; subst.\n  rename h1 into resp.\n  rename h2 into aeq.\n  rename h0 into apr.\n\n  inversion apr as [cl].\n  constructor.\n  rename x0 into a.\n  rename c into b.\n  rename x1 into c.\n  allunfold @close_comput; repnd; dands; tcsp.\n\n  - apply alphaeq_preserves_program in aeq; apply aeq; auto.\n\n  - clear cl3 cl.\n    introv comp.\n    eapply compute_to_value_alpha in comp;[| |exact aeq]; eauto 3 with slow.\n    exrepnd.\n    apply @alpha_eq_oterm_implies_combine in comp0; exrepnd; subst.\n    apply cl2 in comp1; clear cl2.\n    exrepnd.\n    exists tr_subterms; dands; auto.\n    allunfold @lblift; repnd; dands; auto; try omega.\n    introv i.\n    rw comp3 in i.\n    applydup comp0 in i; clear comp0.\n    allunfold @blift; exrepnd.\n    pose proof (comp2 (selectbt tl_subterms n) (selectbt bs' n)) as h.\n    autodimp h hyp.\n    { unfold selectbt; apply in_nth_combine; auto; try omega. }\n\n    exists lv nt1 nt2; dands; eauto 3 with slow.\n\n    allunfold @olift; repnd; dands; auto.\n    introv wfs isp1 isp2.\n    pose proof (i0 sub wfs isp1 isp2) as k; clear i0.\n    repndors; tcsp.\n    right; apply hr.\n    exists (lsubst nt1 sub); dands; auto.\n\n  - clear cl2 cl.\n    introv comp.\n    eapply compute_to_exception_alpha in comp; eauto 3 with slow; exrepnd.\n    apply cl3 in comp0.\n    exrepnd.\n    exists a'0 e'; dands; auto.\n\n    + clear comp0.\n      repndors; tcsp.\n\n      * right.\n        apply hr.\n        exists a'; dands; auto.\n\n      * right.\n        apply hb; auto.\n        eapply resp;[apply alpha_eq_sym; eauto|]; auto.\n\n    + clear comp4.\n      repndors; tcsp.\n\n      * right.\n        apply hr.\n        exists t2'; dands; auto.\n\n      * right.\n        apply hb; auto.\n        eapply resp;[apply alpha_eq_sym; eauto|]; auto.\n\n(*\n  - clear cl2 cl3.\n    introv comp.\n    apply (compute_to_marker_alpha _ _ b) in comp; auto.\n*)\n\n  - introv comp.\n    eapply computes_to_seq_alpha in comp;[| | eauto]; eauto 3 with slow; exrepnd.\n    apply cl4 in comp1; exrepnd.\n    eexists; dands; eauto.\n    introv.\n    pose proof (comp0 n) as h; clear comp0.\n    pose proof (comp2 n) as q; clear comp2.\n\n    repndors; tcsp; right.\n\n    + apply hr.\n      eexists; dands; eauto.\n\n    + apply hb.\n      apply alpha_eq_sym in h.\n      eapply resp; eauto.\nQed.\nHint Resolve respects_alpha_l_approx_aux : slow.\n\nTheorem approx_acc_resp {p} :\n  forall (lib : library)\n         (l r0 : bin_rel (@NTerm p))\n         (resp_l_l : respects_alpha_l l)\n         (resp_r_l : respects_alpha_r l)\n         (resp_l_r0 : respects_alpha_l r0)\n         (resp_r_r0 : respects_alpha_r r0)\n         (OBG : forall (r: bin_rel NTerm)\n                       (INC: r0 =2> r)\n                       (CIH: l =2> r)\n                       (resp_r : respects_alpha_r r)\n                       (resp_l : respects_alpha_l r),\n                  l =2> approx_aux lib r),\n    l =2> approx_aux lib r0.\nProof.\n  intros.\n  assert (SIM: approx_aux lib (r0 \\2/ l) x0 x1) by eauto 6 with slow.\n  clear PR; revert x0 x1 SIM; cofix CIH.\n  intros; destruct SIM; econstructor; eauto.\n  invertsna c Hcl. repnd.\n  unfold close_comput.\n  dands; eauto.\n\n  - introv Hcomp.\n    apply Hcl2 in Hcomp.\n    exrepnd. exists tr_subterms. split; eauto.\n    eapply le_lblift2; eauto.\n    apply le_olift.\n\n    unfold le_bin_rel.\n    introv Hap.\n    repndors; tcsp.\n    left.\n    apply CIH; apply OBG; eauto 3 with slow.\n\n  - introv Hcomp.\n    apply Hcl3 in Hcomp; exrepnd.\n    exists a' e'; dands; auto; repndors; auto; tcsp;\n    try (complete (left; apply CIH; apply OBG; tcsp; eauto 3 with slow)).\n\n  - introv comp.\n    apply Hcl4 in comp; exrepnd.\n    eexists; dands; eauto.\n    introv.\n    pose proof (comp0 n) as h; clear comp0; repndors; tcsp.\n    left.\n    apply CIH; apply OBG; tcsp; eauto 3 with slow.\nQed.\n\n(*\nLemma approx_change_utoks_lsubst_aux {o} :\n  forall lib (t1 t2 : @NTerm o) sub1 sub2 l,\n    nrut_sub l sub1\n    -> nrut_sub l sub2\n    -> dom_sub sub1 = dom_sub sub2\n    -> no_repeats (dom_sub sub1)\n    -> subset (get_utokens t1) l\n    -> subset (get_utokens t2) l\n    -> approx lib (lsubst_aux t1 sub1) (lsubst_aux t2 sub1)\n    -> approx lib (lsubst_aux t1 sub2) (lsubst_aux t2 sub2).\nProof.\n  intro lib.\n\n  pose proof\n       (approx_acc_resp\n          lib\n          (fun a b => {t1,t2 : NTerm\n                       $ {sub1,sub2 : Sub\n                       $ {l : list (get_patom_set o)\n                       $ nrut_sub l sub1\n                       # nrut_sub l sub2\n                       # dom_sub sub1 = dom_sub sub2\n                       # no_repeats (dom_sub sub1)\n                       # subset (get_utokens t1) l\n                       # subset (get_utokens t2) l\n                       # approx lib (lsubst_aux t1 sub1) (lsubst_aux t2 sub1)\n                       # alpha_eq a (lsubst_aux t1 sub2)\n                       # alpha_eq b (lsubst_aux t2 sub2)}}})\n          (@bot2 o)) as HH.\n  allsimpl.\n  match goal with\n      [ HH : _ -> _ -> _ -> _ -> _ -> ?B |- _ ] =>\n      assert B as h;\n        [|introv nr1 nr2 e nr ss1 ss2 apr; eapply h;\n          exists t1 t2 sub1 sub2 l; dands; auto; fail]\n  end.\n\n  apply HH; clear HH; eauto 2 with slow.\n  { introv aeq h; allsimpl; exrepnd; subst.\n    exists t1 t2 sub1 sub2 l; dands; eauto with slow. }\n  { introv aeq h; allsimpl; exrepnd; subst.\n    exists t1 t2 sub1 sub2 l; dands; eauto with slow. }\n\n  introv hb hr rar ral h; exrepnd; subst.\n  rename h1 into nrut1.\n  rename h2 into nrut2.\n  rename h3 into eqdoms.\n  rename h4 into norep.\n  rename h5 into ss1.\n  rename h6 into ss2.\n  rename h7 into apr.\n  rename h8 into aeqls1.\n  rename h0 into aeqls2.\n\n  pose proof (respects_alpha_r_approx_aux lib r rar) as rar_aa.\n  pose proof (respects_alpha_l_approx_aux lib r ral) as ral_aa.\n  eapply rar_aa;[apply alpha_eq_sym;exact aeqls2|].\n  eapply ral_aa;[apply alpha_eq_sym;exact aeqls1|].\n\n  constructor.\n  inversion apr as [cl]; clear apr; subst.\n  allunfold @close_comput; repnd.\n\n  prove_and isp1.\n\n  {\n    rw <- @cl_lsubst_lsubst_aux in cl0; eauto 2 with slow.\n    rw @isprogram_lsubst_iff in cl0.\n    repnd.\n    rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow;\n    apply isprogram_lsubst_iff; dands; eauto; introv i.\n    apply cl0 in i; exrepnd.\n    pose proof (sub_find_some_eq_doms_nrut_sub sub1 sub2 v l nrut2 eqdoms) as h.\n    rw i1 in h; exrepnd.\n    rw h0; eexists; dands; eauto 2 with slow.\n  }\n\n  prove_and isp2.\n\n  {\n    rw <- @cl_lsubst_lsubst_aux in cl1; eauto 2 with slow.\n    rw @isprogram_lsubst_iff in cl1.\n    repnd.\n    rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow;\n    apply isprogram_lsubst_iff; dands; eauto; introv i.\n    apply cl1 in i; exrepnd.\n    pose proof (sub_find_some_eq_doms_nrut_sub sub1 sub2 v l nrut2 eqdoms) as h.\n    rw i1 in h; exrepnd.\n    rw h0; eexists; dands; eauto 2 with slow.\n  }\n\n  dands.\n\n  - clear cl3 cl.\n    introv comp.\n    rw <- @cl_lsubst_lsubst_aux in comp; eauto with slow.\n    pose proof (computes_to_value_change_utok_sub\n                  lib t1 (oterm (Can c) tl_subterms) sub2 sub1\n                  comp) as h.\n    repeat (autodimp h hyp); eauto 2 with slow.\n    { unfold nrut_sub in nrut2; repnd.\n      eapply subset_disjoint_r;[apply disjoint_sym in nrut2; exact nrut2|]; auto. }\n    { unfold nrut_sub in nrut1; repnd.\n      eapply subset_disjoint_r;[apply disjoint_sym in nrut1; exact nrut1|]; auto. }\n    exrepnd.\n\n    dup h5 as comp1.\n    repeat (rw <- @cl_lsubst_lsubst_aux in cl2; eauto with slow).\n    unfold close_compute_val in cl2.\n\n    remember (get_utok_c c) as guo; symmetry in Heqguo; destruct guo.\n\n    {\n       apply get_utok_c_some in Heqguo; subst; allsimpl.\n       dup comp as isv; unfold computes_to_value in isv; repnd.\n       apply compute_max_steps_eauto2 in isv.\n       apply isprogram_implies_wf in isv; auto.\n       apply wf_term_utok in isv; subst; allsimpl; fold_terms.\n       apply alpha_eq_mk_utoken in h0.\n       rw @cl_lsubst_lsubst_aux in h0; eauto 2 with slow.\n       destruct w as [v|op bs]; allsimpl.\n\n       - allrw subvars_singleton_l.\n         remember (sub_find sub2 v) as sf; symmetry in Heqsf; destruct sf; ginv; subst.\n         pose proof (sub_find_some_eq_doms_nrut_sub sub2 sub1 v l nrut1) as e.\n         autodimp e hyp; rw Heqsf in e; exrepnd.\n         rw @cl_lsubst_lsubst_aux in h1; allsimpl; eauto 2 with slow.\n         rw e0 in h1.\n         apply alpha_eq_sym in h1.\n         apply alpha_eq_mk_utoken in h1; subst.\n\n         apply cl2 in comp1; exrepnd.\n         unfold lblift in comp0; allsimpl; repnd; cpx; clear comp0; fold_terms.\n\n         pose proof (computes_to_value_change_utok_sub\n                       lib t2 (mk_utoken a) sub1 sub2 comp1) as q.\n         repeat (autodimp q hyp); eauto 3 with slow.\n         { unfold nrut_sub in nrut1; repnd.\n           eapply subset_disjoint_r;[apply disjoint_sym in nrut1; exact nrut1|]; auto. }\n         { unfold nrut_sub in nrut2; repnd.\n           eapply subset_disjoint_r;[apply disjoint_sym in nrut2; exact nrut2|]; auto. }\n         exrepnd.\n\n         destruct w as [v'|op' bs']; allsimpl; dgc.\n\n         + allrw subvars_singleton_l.\n           rw @cl_lsubst_lsubst_aux in q1; eauto 2 with slow.\n           rw @cl_lsubst_lsubst_aux in q0; eauto 2 with slow.\n           allsimpl.\n           pose proof (sub_find_some_eq_doms_nrut_sub sub1 sub2 v' l nrut2) as e'.\n           autodimp e' hyp.\n           remember (sub_find sub1 v') as sf'; symmetry in Heqsf'; destruct sf'.\n\n           * exrepnd.\n             rw e'0 in q1.\n             apply alpha_eq_mk_utoken in q0; subst.\n             apply alpha_eq_sym in q1.\n             apply alpha_eq_mk_utoken in q1; subst.\n             pose proof (nrut_sub_sub_find_same sub1 v v' (mk_utoken a) l) as e.\n             repeat (autodimp e hyp); exrepnd; ginv; GC.\n             rw e'0 in Heqsf; ginv.\n             exists ([] : list (@BTerm o)); fold_terms.\n             rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow; dands; auto.\n             unfold lblift; simpl; sp.\n\n           * inversion q0.\n\n         + allrw disjoint_app_r; repnd.\n           allrw subset_app; repnd.\n           rw @cl_lsubst_lsubst_aux in q0; eauto 2 with slow; allsimpl.\n           apply alpha_eq_mk_utoken in q0; subst.\n           inversion q0; subst.\n           destruct bs'; allsimpl; cpx; fold_terms; GC; dgc.\n           allrw disjoint_singleton_r.\n           allrw singleton_subset.\n           rw @cl_lsubst_lsubst_aux in q1; eauto 2 with slow; allsimpl; fold_terms.\n           apply alpha_eq_sym in q1; apply alpha_eq_mk_utoken in q1; subst.\n           apply sub_find_some in e0; apply in_sub_eta in e0; repnd.\n           destruct q6.\n           rw lin_flat_map; exists (mk_utoken a); simpl; sp.\n\n       - allrw disjoint_app_r; allrw subset_app; repnd.\n         inversion h0; subst; allsimpl; cpx.\n         destruct bs; allsimpl; cpx; fold_terms; GC; dgc.\n         allrw disjoint_singleton_r; allrw singleton_subset.\n         rw @cl_lsubst_lsubst_aux in h1; eauto 2 with slow; allsimpl; fold_terms.\n         apply alpha_eq_sym in h1; apply alpha_eq_mk_utoken in h1; subst.\n         apply cl2 in h5; exrepnd.\n         unfold lblift in h0; allsimpl; repnd; cpx; clear h0; fold_terms.\n\n         pose proof (computes_to_value_change_utok_sub\n                       lib t2 (mk_utoken g) sub1 sub2 h1) as q.\n         repeat (autodimp q hyp); eauto 3 with slow.\n         { unfold nrut_sub in nrut1; repnd.\n           eapply subset_disjoint_r;[apply disjoint_sym in nrut1; exact nrut1|]; auto. }\n         { unfold nrut_sub in nrut2; repnd.\n           eapply subset_disjoint_r;[apply disjoint_sym in nrut2; exact nrut2|]; auto. }\n         exrepnd.\n\n         destruct w as [v|op bs]; allsimpl; dgc.\n\n         + allrw subvars_singleton_l.\n           rw @cl_lsubst_lsubst_aux in q1; eauto 2 with slow.\n           rw @cl_lsubst_lsubst_aux in q0; eauto 2 with slow.\n           allsimpl.\n           pose proof (sub_find_some_eq_doms_nrut_sub sub1 sub2 v l nrut2) as e.\n           autodimp e hyp.\n           remember (sub_find sub1 v) as sf; symmetry in Heqsf; destruct sf.\n\n           * exrepnd; rw e0 in q1.\n             apply alpha_eq_sym in q1.\n             allapply @alpha_eq_mk_utoken; subst; allsimpl.\n             unfold nrut_sub in nrut1; repnd.\n             apply ss1 in h6; apply nrut1 in h6; destruct h6.\n             apply sub_find_some in Heqsf; apply in_sub_eta in Heqsf; repnd.\n             rw lin_flat_map; exists (mk_utoken g); simpl; sp.\n\n           * inversion q0.\n\n         + allrw disjoint_app_r; allrw subset_app; repnd.\n           rw @cl_lsubst_lsubst_aux in q0; eauto 2 with slow; allsimpl.\n           apply alpha_eq_mk_utoken in q0.\n           inversion q0; subst; destruct bs; allsimpl; cpx; fold_terms; GC; dgc.\n           allrw disjoint_singleton_r; allrw singleton_subset.\n           rw @cl_lsubst_lsubst_aux in q1; eauto 2 with slow; allsimpl.\n           apply alpha_eq_sym in q1; apply alpha_eq_mk_utoken in q1; subst.\n           rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow.\n           exists ([] : list (@BTerm o)); dands; auto.\n           unfold lblift; simpl; sp.\n    }\n\n    destruct w as [v|op bs].\n\n    {\n      rw @cl_lsubst_lsubst_aux in h0; allsimpl; eauto 2 with slow.\n      remember (sub_find sub2 v) as sf; symmetry in Heqsf; destruct sf.\n      - apply sub_find_some in Heqsf.\n        eapply in_nrut_sub in Heqsf; eauto; exrepnd; subst.\n        apply alpha_eq_sym in h0; apply alpha_eq_mk_utoken in h0; subst.\n        inversion h0; subst; allsimpl; ginv.\n      - inversion h0.\n    }\n\n    rw @cl_lsubst_lsubst_aux in h0; eauto 2 with slow; allsimpl.\n    apply alpha_eq_oterm_combine2 in h0; repnd; subst.\n    allrw map_length; allsimpl; GC.\n    rw @cl_lsubst_lsubst_aux in h1; eauto 2 with slow; allsimpl.\n    apply alpha_eq_sym in h1; apply alpha_eq_oterm_implies_combine in h1; exrepnd; subst.\n    allrw map_length; GC.\n    allrw disjoint_app_r; allrw subset_app; repnd.\n\n    apply cl2 in h5; exrepnd.\n\n    pose proof (computes_to_value_change_utok_sub\n                  lib t2 (oterm (Can c) tr_subterms) sub1 sub2\n                  h5) as q.\n    repeat (autodimp q hyp); eauto 3 with slow.\n    { unfold nrut_sub in nrut1; repnd.\n      eapply subset_disjoint_r;[apply disjoint_sym in nrut1; exact nrut1|]; auto. }\n    { unfold nrut_sub in nrut2; repnd.\n      eapply subset_disjoint_r;[apply disjoint_sym in nrut2; exact nrut2|]; auto. }\n    exrepnd.\n\n    destruct w as [v|op'' bs''].\n\n    {\n      rw @cl_lsubst_lsubst_aux in q0; allsimpl; eauto 2 with slow.\n      remember (sub_find sub1 v) as sf; symmetry in Heqsf; destruct sf.\n      - apply sub_find_some in Heqsf.\n        eapply in_nrut_sub in Heqsf; eauto; exrepnd; subst.\n        apply alpha_eq_sym in q0; apply alpha_eq_mk_utoken in q0; subst.\n        inversion q0; subst; allsimpl; ginv.\n      - inversion q0.\n    }\n\n    rw @cl_lsubst_lsubst_aux in q0; eauto 2 with slow; allsimpl.\n    apply alpha_eq_oterm_combine2 in q0; repnd; subst.\n    allrw map_length; allsimpl; GC.\n    rw @cl_lsubst_lsubst_aux in q1; eauto 2 with slow; allsimpl.\n    apply alpha_eq_sym in q1; apply alpha_eq_oterm_implies_combine in q1; exrepnd; subst.\n    allrw map_length; GC.\n    allrw disjoint_app_r; allrw subset_app; repnd.\n\n    exists bs'0.\n    rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow; dands; auto.\n\n    assert (alpha_eq_bterms (lsubst_bterms_aux bs'' sub2) bs'0) as aebs1.\n    { unfold alpha_eq_bterms, lsubst_bterms_aux; allrw map_length; dands; auto. }\n\n    assert (alpha_eq_bterms tl_subterms (lsubst_bterms_aux bs sub2)) as aebs2.\n    { unfold alpha_eq_bterms, lsubst_bterms_aux; allrw map_length; dands; auto. }\n\n    assert (alpha_eq_bterms (lsubst_bterms_aux bs sub1) bs') as aebs3.\n    { unfold alpha_eq_bterms, lsubst_bterms_aux; allrw map_length; dands; auto. }\n\n    assert (alpha_eq_bterms tr_subterms (lsubst_bterms_aux bs'' sub1)) as aebs4.\n    { unfold alpha_eq_bterms, lsubst_bterms_aux; allrw map_length; dands; auto. }\n\n    assert (approx_or_bts lib bot2 bs' tr_subterms) as apr1 by sp.\n\n    pose proof (approx_or_bts_alpha_eq_bterms_l\n                  lib bs' (lsubst_bterms_aux bs sub1) tr_subterms bot2) as apr2.\n    repeat (autodimp apr2 hyp); eauto 2 with slow.\n\n    pose proof (approx_or_bts_alpha_eq_bterms_r\n                  lib (lsubst_bterms_aux bs sub1) (lsubst_bterms_aux bs'' sub1) tr_subterms bot2) as apr3.\n    repeat (autodimp apr3 hyp); eauto 2 with slow.\n\n    fold (approx_or_bts lib r tl_subterms bs'0).\n    eapply approx_or_bts_alpha_eq_bterms_l;[apply alpha_eq_bterms_sym;exact aebs2|].\n    eapply approx_or_bts_alpha_eq_bterms_r;[apply alpha_eq_bterms_sym;exact aebs1|].\n\n    clear h6 h0 q0 q6.\n\n    unfold approx_or_bts in apr3; unfold approx_or_bts.\n    unfold lblift in apr3; unfold lblift.\n    allrw @length_lsubst_bterms_aux; repnd; dands; auto.\n    introv i.\n    pose proof (apr3 n i) as bl; clear apr3.\n\n    repeat (rw @selectbt_lsubst_bterms_aux; auto; try omega).\n    repeat (rw @selectbt_lsubst_bterms_aux in bl; auto; try omega).\n\n    remember (selectbt bs n) as b1.\n    remember (selectbt bs'' n) as b2.\n    unfold blift in bl; exrepnd.\n    unfold blift.\n\n    pose proof (length_dom sub1) as el; rw eqdoms in el; rw @length_dom in el.\n\n    assert (disjoint (get_utokens_sub sub1) (get_utokens_b b1)) as d11.\n    { (* using h4 *)\n      assert (subset (get_utokens_b b1) (get_utokens_bs bs)) as ss.\n      { introv k; unfold get_utokens_bs; rw lin_flat_map.\n        exists (selectbt bs n); rw <- Heqb1; dands; auto.\n        rw Heqb1; apply selectbt_in; auto. }\n      eapply subset_disjoint_r;[|exact ss].\n      eapply subset_disjoint_r;[|exact h4].\n      eapply subset_disjoint_r;[|exact ss1].\n      unfold nrut_sub in nrut1; repnd; eauto with slow.\n    }\n\n    assert (disjoint (get_utokens_sub sub1) (get_utokens_b b2)) as d12.\n    { (* using q4 *)\n      assert (subset (get_utokens_b b2) (get_utokens_bs bs'')) as ss.\n      { introv k; unfold get_utokens_bs; rw lin_flat_map.\n        exists (selectbt bs'' n); rw <- Heqb2; dands; auto.\n        rw Heqb2; apply selectbt_in; auto; try omega. }\n      eapply subset_disjoint_r;[|exact ss].\n      eapply subset_disjoint_r;[|exact q4].\n      eapply subset_disjoint_r;[|exact ss2].\n      unfold nrut_sub in nrut1; repnd; eauto with slow.\n    }\n\n(* XXXXXXXXXXXX *)\n\n    pose proof (alpha_eq_bterm_ren_utokens_b\n                  (lsubst_bterm_aux b1 sub1)\n                  (bterm lv nt1)\n                  (nrut_subs_to_utok_ren sub1 sub2)\n                  bl2)\n      as aeqr1.\n    rw @lsubst_aux_bterm_ren_utokens_b in aeqr1.\n    rw @ren_utokens_b_trivial in aeqr1;\n      [|erewrite @dom_utok_ren_nrut_subs_to_utok_ren; complete eauto].\n\n    pose proof (alpha_eq_bterm_ren_utokens_b\n                  (lsubst_bterm_aux b2 sub1)\n                  (bterm lv nt2)\n                  (nrut_subs_to_utok_ren sub1 sub2)\n                  bl0)\n      as aeqr2.\n    rw @lsubst_aux_bterm_ren_utokens_b in aeqr2.\n    rw @ren_utokens_b_trivial in aeqr2;\n      [|erewrite @dom_utok_ren_nrut_subs_to_utok_ren; complete eauto].\n\n    erewrite @ren_utokens_sub_nrut_subs_to_utok_ren in aeqr1; eauto.\n    erewrite @ren_utokens_sub_nrut_subs_to_utok_ren in aeqr2; eauto.\n    remember (nrut_subs_to_utok_ren sub1 sub2) as ren.\n    allsimpl.\n\n    exists lv (ren_utokens ren nt1) (ren_utokens ren nt2); dands; auto.\n\n    apply approx_open_simpler_equiv; eauto 3 with slow.\n\n    unfold simpl_olift; unfold olift in bl1; repnd.\n\n    prove_and ntwfsu1; eauto 2 with slow.\n    prove_and ntwfsu2; eauto 2 with slow.\n\n    introv wfs ispl1 ispl2.\n\n(* rename the tokens of sub to fresh tokens *)\n    pose proof (ex_new_utok_ren\n                  (remove_repeats (get_patom_deq o) (get_utokens_sub sub1 ++ get_utokens_sub sub2))\n                  (get_utokens_sub sub1\n                                   ++ get_utokens_sub sub2\n                                   ++ get_utokens_sub sub\n                                   ++ get_utokens nt1\n                                   ++ get_utokens nt2))\n      as newut; exrepnd.\n\n    pose proof (bl1 (ren_utokens_sub ren0 sub)) as rr.\n    repeat (autodimp rr hyp); eauto 2 with slow.\n    { apply wf_sub_ren_utokens_sub; eauto with slow. }\n    { apply isprogram_lsubst_iff.\n      apply isprogram_lsubst_iff in ispl1; repnd.\n      apply nt_wf_ren_utokens_iff in ispl0; dands; auto.\n      introv j.\n      pose proof (ispl1 v) as k; rw @free_vars_ren_utokens in k; autodimp k hyp.\n      exrepnd.\n      rw @sub_find_ren_utokens_sub; rw k1; eexists; dands; eauto 2 with slow.\n      unfold closed; rw @free_vars_ren_utokens; auto.\n    }\n    { apply isprogram_lsubst_iff.\n      apply isprogram_lsubst_iff in ispl2; repnd.\n      apply nt_wf_ren_utokens_iff in ispl0; dands; auto.\n      introv j.\n      pose proof (ispl2 v) as k; rw @free_vars_ren_utokens in k; autodimp k hyp.\n      exrepnd.\n      rw @sub_find_ren_utokens_sub; rw k1; eexists; dands; eauto 2 with slow.\n      unfold closed; rw @free_vars_ren_utokens; auto.\n    }\n\n    repndors; tcsp.\n\n    pose proof (pull_out_atoms\n                  nt1\n                  (get_utokens_sub sub1)\n                  (free_vars nt2\n                             ++ (sub_free_vars (ren_utokens_sub ren0 sub))\n                             ++ dom_sub sub)) as pullout.\n    autodimp pullout hyp; eauto 2 with slow.\n    exrepnd.\n    allrw disjoint_app_l; repnd.\n    rw remove_repeats_if_no_repeats in pullout1; eauto 2 with slow.\n\n    pose proof (pull_out_nrut_sub nt2 sub0 (get_utokens u)) as pullout'.\n    repeat (autodimp pullout' hyp); eauto 2 with slow.\n    exrepnd.\n\n    pose proof (pull_out_atoms_sub\n                  (ren_utokens_sub ren0 sub)\n                  (range_utok_ren ren0)\n                  (allvars u ++ allvars u0 ++ dom_sub sub0)) as pullout''.\n    autodimp pullout'' hyp.\n    { apply wf_sub_ren_utokens_sub; eauto with slow. }\n    exrepnd.\n    allrw disjoint_app_l; repnd.\n    rw remove_repeats_if_no_repeats in pullout''1; auto.\n\n    pose proof (respects_alpha_r_approx_aux_bot2 lib) as respr.\n    unfold respects2_r in respr.\n    pose proof (respr\n                  (lsubst nt1 (ren_utokens_sub ren0 sub))\n                  (lsubst nt2 (ren_utokens_sub ren0 sub))\n                  (lsubst (lsubst u0 sub0) (lsubst_sub s' sub3)))\n          as rer; clear respr.\n    repeat (autodimp rer hyp).\n    { apply lsubst_alpha_congr3; auto. }\n\n    pose proof (respects_alpha_l_approx_aux_bot2 lib) as respl.\n    unfold respects2_l in respl.\n    pose proof (respl\n                  (lsubst nt1 (ren_utokens_sub ren0 sub))\n                  (lsubst (lsubst u0 sub0) (lsubst_sub s' sub3))\n                  (lsubst (lsubst u sub0) (lsubst_sub s' sub3)))\n          as rel; clear respl.\n    repeat (autodimp rel hyp).\n    { apply lsubst_alpha_congr3; auto. }\n    clear rer.\n\n    assert (subset (sub_free_vars s') (dom_sub sub3)) as ss.\n    { introv is.\n      rw @cl_lsubst_sub_eq_lsubst_aux_sub in pullout''5; eauto 3 with slow.\n      applydup @alphaeq_sub_preserves_free_vars in pullout''5 as fvs.\n      rw @sub_free_vars_ren_utokens_sub in fvs.\n      rw @cl_sub_free_vars_lsubst_aux_sub in fvs; eauto 2 with slow.\n      rw (sub_free_vars_if_cl_sub sub) in fvs; eauto 2 with slow.\n      symmetry in fvs; apply null_iff_nil in fvs.\n      pose proof (in_deq _ deq_nvar x (dom_sub sub3)) as [d|d]; auto.\n      provefalse.\n      pose proof (fvs x) as h; rw in_remove_nvars in h; sp. }\n\n    applydup @alphaeq_sub_implies_eq_doms in pullout''5 as eqd.\n    rw @dom_sub_ren_utokens_sub in eqd.\n    rw @dom_sub_lsubst_sub in eqd.\n    applydup @alphaeq_sub_preserves_cl_sub in pullout''5; eauto 3 with slow.\n    pose proof (cl_lsubst_lsubst_lsubst_sub u s' sub0 sub3) as a1.\n    rw <- eqd in a1.\n    repeat (autodimp a1 hyp); eauto 4 with slow.\n    pose proof (cl_lsubst_lsubst_lsubst_sub u0 s' sub0 sub3) as a2.\n    rw <- eqd in a2.\n    repeat (autodimp a2 hyp); eauto 4 with slow.\n\n    pose proof (respects_alpha_r_approx_aux_bot2 lib) as respr.\n    unfold respects2_r in respr.\n    pose proof (respr\n                  (lsubst (lsubst u sub0) (lsubst_sub s' sub3))\n                  (lsubst (lsubst u0 sub0) (lsubst_sub s' sub3))\n                  (lsubst (lsubst u0 s') (sub0 ++ sub3)))\n          as rer; clear respr.\n    repeat (autodimp rer hyp).\n    clear rel.\n\n    pose proof (respects_alpha_l_approx_aux_bot2 lib) as respl.\n    unfold respects2_l in respl.\n    pose proof (respl\n                  (lsubst (lsubst u sub0) (lsubst_sub s' sub3))\n                  (lsubst (lsubst u0 s') (sub0 ++ sub3))\n                  (lsubst (lsubst u s') (sub0 ++ sub3)))\n          as rel; clear respl.\n    repeat (autodimp rel hyp).\n    clear rer.\n\n    right.\n    apply hr.\n    exists (lsubst u s') (lsubst u0 s') (sub0 ++ sub3).\n\nPrint nrut_sub.\nXXXXXXXXXXXXX\n\n\n    pose proof (pull_out_nrut_sub nt1 sub1 l) as pont1.\n    repeat (autodimp pont1 hyp); eauto 3 with slow.\n\nXXXXXXXXX\n\n    pose proof (simple_lsubst_lsubst_sub_aeq4 u1 sub2 sub) as swap1.\n    repeat (autodimp swap1 hyp); eauto 3 with slow.\n    pose proof (simple_lsubst_lsubst_sub_aeq4 u2 sub2 sub) as swap2.\n    repeat (autodimp swap2 hyp); eauto 3 with slow.\n    repeat (rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow).\n    rw swap1; rw swap2; clear swap1 swap2.\n\n(* do I have to remove lv? *)\n    pose proof (bl1 (ren_utokens_sub (nrut_subs_to_utok_ren sub2 sub1) sub)) as rr.\n    repeat (autodimp rr hyp); eauto 2 with slow.\n    { apply wf_sub_ren_utokens_sub; eauto with slow. }\n    {\n    }\n\nXXXXXXXXXXXx\n\n    pose proof (fresh_vars (length lv)\n                           (lv ++ free_vars nt1\n                               ++ free_vars nt2\n                               ++ bound_vars nt1\n                               ++ bound_vars nt2\n                               ++ dom_sub sub1\n                               ++ dom_sub sub2)) as fvs.\n    exrepnd.\n    allrw disjoint_app_r; repnd.\n\n    pose proof (pull_out_nrut_sub_b_aux (bterm lv nt1) sub1 l lvn) as po1.\n    allsimpl; repeat (autodimp po1 hyp); eauto 3 with slow.\n    { apply alpha_eq_bterm_preserves_wf_bterm in bl2; auto.\n      apply wf_bterm_lsubst_bterm_aux; eauto 2 with slow.\n      rw Heqb1; apply wf_bterm_selectbt.\n      apply (wf_bterms_lsubst_bterms_aux_implies bs sub2).\n      apply alpha_eq_bterms_preserves_wf_bterms in aebs2; auto.\n      unfold computes_to_value in comp; repnd.\n      apply compute_max_steps_eauto2 in comp.\n      apply isprogram_implies_wf in comp.\n      apply wf_oterm_iff in comp; repnd; auto.\n    }\n    { simpl.\n      apply alpha_eq_bterm_preserves_free_vars in bl2; allsimpl; rw <- bl2.\n      erewrite @free_vars_bterm_lsubst_bterm_aux_nrut_sub; eauto.\n      apply disjoint_remove_nvars_l.\n      assert (subset (free_vars_bterm b1) (free_vars_bterms bs)) as ss.\n      { unfold free_vars_bterms.\n        apply subsetSingleFlatMap; rw Heqb1.\n        apply selectbt_in; auto. }\n      eapply subset_disjoint;[exact ss|].\n      apply disjoint_remove_nvars_l.\n      rw eqdoms.\n      erewrite <- free_vars_bterms_lsubst_bterms_aux_nrut_sub; eauto.\n      apply alpha_eq_bterms_preserves_free_vars in aebs2; rw <- aebs2.\n      unfold computes_to_value in comp; repnd.\n      apply compute_max_steps_eauto2 in comp.\n      destruct comp as [cl wf].\n      apply closed_oterm_iff1 in cl.\n      apply null_iff_nil in cl; rw cl; auto.\n    }\n    { apply disjoint_app_r; dands; auto. }\n    exrepnd.\n\n    pose proof (pull_out_nrut_sub_b_aux (bterm lv nt2) sub1 l lvn) as qo1.\n    allsimpl; repeat (autodimp qo1 hyp); eauto 3 with slow.\n    { apply alpha_eq_bterm_preserves_wf_bterm in bl0; auto.\n      apply wf_bterm_lsubst_bterm_aux; eauto 2 with slow.\n      rw Heqb2; apply wf_bterm_selectbt.\n      apply (wf_bterms_lsubst_bterms_aux_implies bs'' sub1).\n      apply alpha_eq_bterms_preserves_wf_bterms in aebs4; auto.\n      unfold computes_to_value in h5; repnd.\n      apply compute_max_steps_eauto2 in h5.\n      apply isprogram_implies_wf in h5.\n      apply wf_oterm_iff in h5; repnd; auto.\n    }\n    { simpl.\n      apply alpha_eq_bterm_preserves_free_vars in bl0; allsimpl; rw <- bl0.\n      erewrite @free_vars_bterm_lsubst_bterm_aux_nrut_sub; eauto.\n      apply disjoint_remove_nvars_l.\n      assert (subset (free_vars_bterm b2) (free_vars_bterms bs'')) as ss.\n      { unfold free_vars_bterms.\n        apply subsetSingleFlatMap; rw Heqb2.\n        apply selectbt_in; auto; try omega. }\n      eapply subset_disjoint;[exact ss|].\n      apply disjoint_remove_nvars_l.\n      erewrite <- free_vars_bterms_lsubst_bterms_aux_nrut_sub; eauto.\n      apply alpha_eq_bterms_preserves_free_vars in aebs4; rw <- aebs4.\n      unfold computes_to_value in h5; repnd.\n      apply compute_max_steps_eauto2 in h5.\n      destruct h5 as [cl wf].\n      apply closed_oterm_iff1 in cl.\n      apply null_iff_nil in cl; rw cl; auto.\n    }\n    { apply disjoint_app_r; dands; auto. }\n    exrepnd.\n\n    assert (alpha_eq_bterm (lsubst_bterm_aux b1 sub1) (lsubst_bterm_aux u sub1)) as aeq1 by eauto 2 with slow.\n    assert (alpha_eq_bterm (lsubst_bterm_aux b2 sub1) (lsubst_bterm_aux u0 sub1)) as aeq2 by eauto 2 with slow.\n    apply (alpha_eq_bterm_ren_utokens_b _ _ (nrut_subs_to_utok_ren sub1 sub2)) in aeq1.\n    apply (alpha_eq_bterm_ren_utokens_b _ _ (nrut_subs_to_utok_ren sub1 sub2)) in aeq2.\n    repeat (rw @lsubst_aux_bterm_ren_utokens_b in aeq1).\n    repeat (rw @lsubst_aux_bterm_ren_utokens_b in aeq2).\n    repeat (rw @ren_utokens_b_trivial in aeq1;\n            [|erewrite @dom_utok_ren_nrut_subs_to_utok_ren; complete eauto]).\n    repeat (rw @ren_utokens_b_trivial in aeq2;\n            [|erewrite @dom_utok_ren_nrut_subs_to_utok_ren; complete eauto]).\n    erewrite @ren_utokens_sub_nrut_subs_to_utok_ren in aeq1; eauto.\n    erewrite @ren_utokens_sub_nrut_subs_to_utok_ren in aeq2; eauto.\n\n    destruct u as [vs u1].\n    destruct u0 as [vs' u2].\n    allsimpl.\n    subst vs vs'.\n    repeat (onerw (sub_filter_disjoint1 sub1 lvn); eauto 2 with slow).\n    repeat (onerw (sub_filter_disjoint1 sub2 lvn); eauto 2 with slow).\n\n    exists lvn (lsubst_aux u1 sub2) (lsubst_aux u2 sub2); dands; auto.\n\n    apply approx_open_simpler_equiv; eauto 3 with slow.\n\n    unfold simpl_olift; unfold olift in bl1; repnd.\n\n    prove_and ntwfsu1.\n    {\n      apply nt_wf_eq; apply lsubst_aux_preserves_wf_term2; eauto 2 with slow.\n      apply alphaeqbt_preserves_nt_wf in po1.\n      repeat (rw @nt_wf_eq in po1); rw @nt_wf_eq in bl3; apply po1 in bl3.\n      rw <- @cl_lsubst_lsubst_aux in bl3; eauto 2 with slow.\n      apply lsubst_wf_term in bl3; auto.\n    }\n\n    prove_and ntwfsu2.\n    {\n      apply nt_wf_eq; apply lsubst_aux_preserves_wf_term2; eauto 2 with slow.\n      apply alphaeqbt_preserves_nt_wf in qo1.\n      repeat (rw @nt_wf_eq in qo1); rw @nt_wf_eq in bl4; apply qo1 in bl4.\n      rw <- @cl_lsubst_lsubst_aux in bl4; eauto 2 with slow.\n      apply lsubst_wf_term in bl4; auto.\n    }\n\n    assert (isprogram_bt (bterm lv nt1)) as isplvnt1.\n    { apply alpha_eq_bterm_preserves_isprogram_bt in bl2; auto.\n      apply preserve_program in comp; auto;[|complete unflsubst].\n      apply isprogram_ot_iff in comp; repnd.\n      unfold alpha_eq_bterms in aebs2; repnd.\n      pose proof (aebs2 (selectbt tl_subterms n) (selectbt (lsubst_bterms_aux bs sub2) n)) as h.\n      unfold selectbt, lsubst_bterms_aux in h.\n      autodimp h hyp.\n      { apply in_nth_combine; allrw map_length; auto; try omega. }\n      rw (@map_nth2 (@BTerm o) (@BTerm o) (@default_bt o)) in h; tcsp.\n      unfold selectbt in Heqb1; rw <- Heqb1 in h.\n      pose proof (comp (nth n tl_subterms default_bt)) as k.\n      autodimp k hyp.\n      { apply nth_in; auto; try omega. }\n      apply alpha_eq_bterm_preserves_isprogram_bt in h; auto.\n\n    }\n\n    assert (isprogram_bt (bterm lv nt2)) as isplvnt2.\n    {\n\n    }\n\n    introv wfs ispl1 ispl2.\n\n    pose proof (simple_lsubst_lsubst_sub_aeq4 u1 sub2 sub) as swap1.\n    repeat (autodimp swap1 hyp); eauto 3 with slow.\n    pose proof (simple_lsubst_lsubst_sub_aeq4 u2 sub2 sub) as swap2.\n    repeat (autodimp swap2 hyp); eauto 3 with slow.\n    repeat (rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow).\n    rw swap1; rw swap2; clear swap1 swap2.\n\n(* rename lvn into lv in the domain of this substitution *)\n    pose proof (bl1 (ren_utokens_sub (nrut_subs_to_utok_ren sub2 sub1) sub)) as rr.\n    repeat (autodimp rr hyp); eauto 2 with slow.\n    { apply wf_sub_ren_utokens_sub; eauto with slow. }\n    {\n    }\n\nSearchAbout wf_sub ren_utokens_sub.\n\nSearchAbout (lsubst (lsubst _ _) _).\n\n(* replace sub2 by sub1 in sub --> sub'\n   instantiate bl1 using sub'\n   pull out sub1 from sub' and sub2 from sub\n   use IH\n *)\n\nQed.\n*)\n\nRequire Import sqle.\n\nLemma approx_change_utoks {o} :\n  forall lib (t1 t2 : @NTerm o) ren,\n    no_repeats (range_utok_ren ren)\n    -> no_repeats (dom_utok_ren ren)\n    -> disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t1))\n    -> disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t2))\n    -> approx lib t1 t2\n    -> approx lib (ren_utokens ren t1) (ren_utokens ren t2).\nProof.\n  introv nr1 nr2 d1 d2 apr.\n  allrw @approx_sqle.\n  allunfold @sqle.\n  intro m.\n  pose proof (apr m) as h; clear apr.\n  revert t1 t2 ren nr1 nr2 d1 d2 h.\n\n  induction m; introv norep1 norep2 disj1 disj2 apr.\n\n  {\n    inversion apr; subst.\n    constructor; eauto with slow.\n  }\n\n  constructor.\n  (*inversion apr as [? ? ? cl]; subst; clear apr.*)\n  inversion apr as [|? ? ? cl]; clear apr; subst.\n  allunfold @close_comput; repnd; dands; tcsp; eauto with slow; introv comp.\n\n  - clear cl3 cl.\n    dup comp as comp1.\n    apply (computes_to_value_ren_utokens _ _ _ (inv_utok_ren ren)) in comp1;\n    allrw @range_utok_ren_inv_utok_ren;\n    allrw @dom_utok_ren_inv_utok_ren;\n    eauto 3 with slow;[|rw @get_utokens_ren_utokens; apply disjoint_dom_diff_range_map_ren_atom].\n    rw @inv_ren_utokens in comp1; auto.\n\n    rw @ren_utokens_can in comp1.\n\n    dup comp1 as comp2.\n    apply cl2 in comp2; exrepnd.\n    dup comp2 as comp22.\n    apply (computes_to_value_ren_utokens _ _ _ ren) in comp2; eauto 3 with slow;[].\n    rw @ren_utokens_can in comp2.\n\n    assert (match\n               get_utok_c\n                 match get_utok_c c with\n                   | Some a => NUTok (ren_atom (inv_utok_ren ren) a)\n                   | None => c\n                 end\n             with\n               | Some a => NUTok (ren_atom ren a)\n               | None =>\n                 match get_utok_c c with\n                   | Some a => NUTok (ren_atom (inv_utok_ren ren) a)\n                   | None => c\n                 end\n             end = c) as e.\n    { destruct c; allsimpl; tcsp.\n      rw @inv_ren_atom2; auto.\n      apply computes_to_value_preserves_utokens in comp; allsimpl; eauto 3 with slow.\n      rw subset_cons_l in comp; repnd.\n      intro i.\n      rw @get_utokens_ren_utokens in comp3.\n      rw in_map_iff in comp3; exrepnd; subst.\n      rw in_diff in i; repnd.\n      destruct (ren_atom_or ren a) as [d|d]; tcsp.\n      rw d in i0.\n      apply in_dom_in_range in i0; auto.\n    }\n    rw e in comp2; clear e.\n\n    eexists; dands;[exact comp2|].\n    unfold lblift; unfold lblift in comp0.\n    allrw map_length; repnd; dands; auto.\n    introv i.\n    applydup comp0 in i.\n    unfold blift; unfold blift in i0.\n    exrepnd.\n    repeat (onerw @selectbt_map; auto; try omega).\n    remember (selectbt tl_subterms n) as b1.\n    remember (selectbt tr_subterms n) as b2.\n\n    applydup @computes_to_value_preserves_utokens in comp as ss1; eauto 3 with slow.\n    eapply (subset_trans _ (get_utokens_b b1)) in ss1;\n      [|simpl; apply subset_app_l;\n        introv k; rw lin_flat_map; exists b1;\n        dands; auto; subst; apply selectbt_in;\n        complete auto].\n    apply (subset_map_map (ren_atom (inv_utok_ren ren))) in ss1.\n    rw <- @get_utokens_b_ren_utokens_b in ss1.\n    rw <- @get_utokens_ren_utokens in ss1.\n    rw @inv_ren_utokens in ss1; auto.\n    applydup @alpha_eq_bterm_preserves_utokens in i2 as put1; allsimpl.\n    rw put1 in ss1; clear put1.\n\n    applydup @computes_to_value_preserves_utokens in comp22 as ss2; allsimpl; eauto 3 with slow.\n    eapply (subset_trans _ (get_utokens_b b2)) in ss2;\n      [|simpl; apply subset_app_l;\n        introv k; rw lin_flat_map; exists b2;\n        dands; auto; subst; apply selectbt_in; complete omega].\n    applydup @alpha_eq_bterm_preserves_utokens in i1 as put2; allsimpl.\n    rw put2 in ss2; clear put2.\n\n    apply (alpha_eq_bterm_ren_utokens_b _ _ ren) in i1.\n    apply (alpha_eq_bterm_ren_utokens_b _ _ ren) in i2.\n\n    assert (disjoint (dom_utok_ren ren)\n                     (diff (get_patom_deq o)\n                           (range_utok_ren ren)\n                           (get_utokens_b b1))) as d.\n    {\n      apply computes_to_value_preserves_utokens in comp; allsimpl; eauto 3 with slow.\n      allrw subset_app; repnd.\n      assert (LIn b1 tl_subterms) as itl.\n      { subst b1; unfold selectbt; apply nth_in; auto. }\n      rw subset_flat_map in comp; apply comp in itl; clear comp.\n      rw <- disjoint_diff_l.\n      eapply subset_disjoint_r;[|exact itl].\n      rw @get_utokens_ren_utokens.\n      rw disjoint_diff_l.\n      apply disjoint_dom_diff_range_map_ren_atom.\n    }\n\n    rw @inv_ren_utokens_b2 in i2; auto.\n    allsimpl.\n    exists lv (ren_utokens ren nt1) (ren_utokens ren nt2); dands; auto.\n\n    unfold olift; unfold olift in i0; repnd.\n    dands.\n    { apply nt_wf_ren_utokens; auto. }\n    { apply nt_wf_ren_utokens; auto. }\n    introv wfs isp1 isp2.\n\n    pose proof (ex_ren_utokens_sub\n                  sub\n                  ren\n                  (get_utokens nt1 ++ get_utokens nt2)) as exren.\n    autodimp exren hyp; exrepnd.\n\n    pose proof (i0 sub') as h.\n    repeat (autodimp h hyp).\n    { subst; apply wf_sub_ren_utokens_sub_iff in wfs; auto. }\n    { subst; apply isprogram_lsubst_iff in isp1; repnd.\n      apply isprogram_lsubst_iff.\n      rw @nt_wf_ren_utokens_iff in isp0; dands; auto.\n      introv j.\n      rw @free_vars_ren_utokens in isp1.\n      apply isp1 in j; exrepnd.\n      allrw @sub_find_ren_utokens_sub.\n      remember (sub_find sub' v) as sf; symmetry in Heqsf; destruct sf; ginv.\n      eexists; dands; eauto.\n      - apply nt_wf_ren_utokens_iff in j2; auto.\n      - unfold closed in j0; rw @free_vars_ren_utokens in j0; auto. }\n    { subst; apply isprogram_lsubst_iff in isp2; repnd.\n      apply isprogram_lsubst_iff.\n      rw @nt_wf_ren_utokens_iff in isp0; dands; auto.\n      introv j.\n      rw @free_vars_ren_utokens in isp2.\n      apply isp2 in j; exrepnd.\n      allrw @sub_find_ren_utokens_sub.\n      remember (sub_find sub' v) as sf; symmetry in Heqsf; destruct sf; ginv.\n      eexists; dands; eauto.\n      - apply nt_wf_ren_utokens_iff in j2; auto.\n      - unfold closed in j0; rw @free_vars_ren_utokens in j0; auto. }\n\n    pose proof (IHm (lsubst nt1 sub') (lsubst nt2 sub') (ren ++ ren')) as sqn.\n    allrw @range_utok_ren_app.\n    allrw @dom_utok_ren_app.\n    allrw no_repeats_app.\n    allrw disjoint_app_l.\n    allrw disjoint_app_r.\n    repnd.\n    repeat (autodimp sqn hyp); dands; eauto 3 with slow.\n\n    { introv a b; applydup disj1 in a.\n      allrw in_diff; allrw in_app_iff; allrw not_over_or; repnd.\n      apply get_utokens_lsubst in b0; allrw in_app_iff; repndors; tcsp.\n      apply in_get_utokens_sub in b0; exrepnd.\n      apply in_sub_keep_first in b4; repnd.\n      pose proof (exren1 t) as hh.\n      repeat (autodimp hh hyp).\n      rw lin_flat_map; apply sub_find_some in b5; apply in_sub_eta in b5; repnd.\n      eexists; dands; eauto.\n    }\n\n    { eapply subset_disjoint;[exact exren4|].\n      apply disjoint_app_l; dands.\n      { apply disjoint_diff_l; rw diff_nil_if_subset; eauto with slow. }\n      { apply disjoint_diff_l; rw diff_nil_if_subset; eauto with slow. }\n    }\n\n    { introv a b; applydup disj2 in a.\n      allrw in_diff; allrw in_app_iff; allrw not_over_or; repnd.\n      apply get_utokens_lsubst in b0; allrw in_app_iff; repndors; tcsp.\n      apply in_get_utokens_sub in b0; exrepnd.\n      apply in_sub_keep_first in b4; repnd.\n      pose proof (exren1 t) as hh.\n      repeat (autodimp hh hyp).\n      rw lin_flat_map; apply sub_find_some in b5; apply in_sub_eta in b5; repnd.\n      eexists; dands; eauto.\n    }\n\n    { eapply subset_disjoint;[exact exren4|].\n      apply disjoint_app_l; dands.\n      { apply disjoint_diff_l; rw diff_nil_if_subset; eauto with slow. }\n      { apply disjoint_diff_l; rw diff_nil_if_subset; eauto with slow. }\n    }\n\n    { repeat (rw @lsubst_ren_utokens in sqn).\n      rw exren0 in sqn.\n      repeat (rw @ren_utokens_app_weak_l in sqn; eauto 2 with slow).\n    }\n\n  - clear cl2 cl.\n    dup comp as comp1.\n\n    apply (computes_to_exception_ren_utokens _ _ _ _ (inv_utok_ren ren)) in comp1;\n    allrw @range_utok_ren_inv_utok_ren;\n    allrw @dom_utok_ren_inv_utok_ren;\n    eauto 3 with slow;[|rw @get_utokens_ren_utokens; apply disjoint_dom_diff_range_map_ren_atom].\n    rw @inv_ren_utokens in comp1; auto.\n\n    dup comp1 as comp2.\n    apply cl3 in comp2; exrepnd.\n    dup comp0 as comp00.\n    apply (computes_to_exception_ren_utokens _ _ _ _ ren) in comp0; eauto 3 with slow.\n\n    eexists; eexists; dands;[exact comp0|idtac|].\n\n    {\n      pose proof (IHm (ren_utokens (inv_utok_ren ren) a) a' ren) as h.\n      repeat (autodimp h hyp).\n\n      { apply computes_to_exception_preserves_utokens in comp1; repnd; eauto 3 with slow.\n        introv i j; allrw in_diff; repnd.\n        apply comp4 in j0.\n        apply disj1 in i; allrw in_diff; sp.\n      }\n\n      { apply computes_to_exception_preserves_utokens in comp00; repnd; eauto 3 with slow.\n        introv i j; allrw in_diff; repnd.\n        apply comp01 in j0.\n        apply disj2 in i; allrw in_diff; sp.\n      }\n\n      rw @inv_ren_utokens2 in h; auto.\n      apply computes_to_exception_preserves_utokens in comp; repnd; eauto 3 with slow.\n      introv i j.\n      rw @get_utokens_ren_utokens in comp4.\n      apply (disjoint_dom_diff_range_map_ren_atom (get_utokens t1)) in i; destruct i.\n      allrw in_diff; repnd; dands; auto.\n    }\n\n    {\n      pose proof (IHm (ren_utokens (inv_utok_ren ren) e) e' ren) as h.\n      repeat (autodimp h hyp).\n\n      { apply computes_to_exception_preserves_utokens in comp1; repnd; eauto 3 with slow.\n        introv i j; allrw in_diff; repnd.\n        apply comp1 in j0.\n        apply disj1 in i; allrw in_diff; sp.\n      }\n\n      { apply computes_to_exception_preserves_utokens in comp00; repnd; eauto 3 with slow.\n        introv i j; allrw in_diff; repnd.\n        apply comp00 in j0.\n        apply disj2 in i; allrw in_diff; sp.\n      }\n\n      rw @inv_ren_utokens2 in h; auto.\n      apply computes_to_exception_preserves_utokens in comp; repnd; eauto 3 with slow.\n      introv i j.\n      rw @get_utokens_ren_utokens in comp.\n      apply (disjoint_dom_diff_range_map_ren_atom (get_utokens t1)) in i; destruct i.\n      allrw in_diff; repnd; dands; auto.\n    }\n\n(*\n  - clear cl2 cl2.\n    dup comp as comp1.\n\n    apply (computes_to_marker_ren_utokens _ _ _ (inv_utok_ren ren)) in comp1;\n    allrw @range_utok_ren_inv_utok_ren;\n    allrw @dom_utok_ren_inv_utok_ren;\n    auto;[|rw @get_utokens_ren_utokens; apply disjoint_dom_diff_range_map_ren_atom].\n    rw @inv_ren_utokens in comp1; auto.\n\n    dup comp1 as comp2.\n    apply cl in comp2; exrepnd.\n    dup comp2 as comp22.\n    apply (computes_to_marker_ren_utokens _ _ _ ren) in comp2; auto.\n*)\n\n  - dup comp as comp1.\n\n    apply (reduces_to_ren_utokens _ _ _ (inv_utok_ren ren)) in comp1;\n    allrw @range_utok_ren_inv_utok_ren;\n    allrw @dom_utok_ren_inv_utok_ren;\n    eauto 3 with slow;[|rw @get_utokens_ren_utokens; apply disjoint_dom_diff_range_map_ren_atom].\n    rw @inv_ren_utokens in comp1; allsimpl; auto.\n\n    dup comp1 as comp2.\n    apply cl4 in comp2; exrepnd.\n    dup comp0 as comp00.\n    apply (reduces_to_ren_utokens _ _ _ ren) in comp2; eauto 3 with slow; allsimpl.\n\n    eexists; dands; eauto.\nQed.\n\n(*\nXXXXXXXXXXXXXXX\n\nLemma approx_change_utoks {o} :\n  forall lib (t1 t2 : @NTerm o) ren,\n    no_repeats (range_utok_ren ren)\n    -> no_repeats (dom_utok_ren ren)\n    -> disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t1))\n    -> disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t2))\n    -> approx lib t1 t2\n    -> approx lib (ren_utokens ren t1) (ren_utokens ren t2).\nProof.\n  intro lib.\n\n(*\n  cofix IND.\n\n  introv nr1 nr2 disj1 disj2 apr.\n*)\n\n  pose proof\n       (approx_acc\n          lib\n          (fun a b => {t1,t2 : NTerm\n                       $ {ren : utok_ren\n                       $ approx lib t1 t2\n                       # no_repeats (range_utok_ren ren)\n                       # no_repeats (dom_utok_ren ren)\n                       # disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t1))\n                       # disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t2))\n                       # a = ren_utokens ren t1\n                       # b = ren_utokens ren t2}})\n          (@bot2 o)) as HH.\n  allsimpl.\n  match goal with\n      [ HH : _ -> ?B |- _ ] =>\n      assert B as h;\n        [|introv nr1 nr2 d1 d2 k; eapply h;\n          eexists;eexists;eexists;dands;eauto;fail]\n  end.\n\n  apply HH; clear HH.\n  introv hb hr h; exrepnd; subst.\n  rename h1 into apr.\n  rename h2 into norep1.\n  rename h3 into norep2.\n  rename h4 into disj1.\n  rename h5 into disj2.\n\n\n  constructor.\n  (*inversion apr as [? ? ? cl]; subst; clear apr.*)\n  inversion apr as [cl]; clear apr.\n  allunfold @close_comput; repnd; dands; tcsp; eauto with slow; introv comp.\n\n  - clear cl3 cl.\n    dup comp as comp1.\n    apply (computes_to_value_ren_utokens _ _ _ (inv_utok_ren ren)) in comp1;\n    allrw @range_utok_ren_inv_utok_ren;\n    allrw @dom_utok_ren_inv_utok_ren;\n    auto;[|rw @get_utokens_ren_utokens; apply disjoint_dom_diff_range_map_ren_atom].\n    rw @inv_ren_utokens in comp1; auto.\n\n    rw @ren_utokens_can in comp1.\n\n    dup comp1 as comp2.\n    apply cl2 in comp2; exrepnd.\n    apply (computes_to_value_ren_utokens _ _ _ ren) in comp2; auto.\n    rw @ren_utokens_can in comp2.\n\n    assert (match\n               get_utok_c\n                 match get_utok_c c with\n                   | Some a => NUTok (ren_atom (inv_utok_ren ren) a)\n                   | None => c\n                 end\n             with\n               | Some a => NUTok (ren_atom ren a)\n               | None =>\n                 match get_utok_c c with\n                   | Some a => NUTok (ren_atom (inv_utok_ren ren) a)\n                   | None => c\n                 end\n             end = c) as e.\n    { destruct c; allsimpl; tcsp.\n      rw @inv_ren_atom2; auto.\n      apply computes_to_value_preserves_utokens in comp; allsimpl.\n      rw subset_cons_l in comp; repnd.\n      intro i.\n      rw @get_utokens_ren_utokens in comp3.\n      rw in_map_iff in comp3; exrepnd; subst.\n      rw in_diff in i; repnd.\n      destruct (ren_atom_or ren a) as [d|d]; tcsp.\n      rw d in i0.\n      apply in_dom_in_range in i0; auto.\n    }\n    rw e in comp2; clear e.\n\n    eexists; dands;[exact comp2|].\n    unfold lblift; unfold lblift in comp0.\n    allrw map_length; repnd; dands; auto.\n    introv i.\n    applydup comp0 in i.\n    unfold blift; unfold blift in i0.\n    exrepnd.\n    repeat (onerw @selectbt_map; auto; try omega).\n    remember (selectbt tl_subterms n) as b1.\n    remember (selectbt tr_subterms n) as b2.\n\n    apply (alpha_eq_bterm_ren_utokens_b _ _ ren) in i1.\n    apply (alpha_eq_bterm_ren_utokens_b _ _ ren) in i2.\n\n    assert (disjoint (dom_utok_ren ren)\n                     (diff (get_patom_deq o)\n                           (range_utok_ren ren)\n                           (get_utokens_b b1))) as d.\n    {\n(*      clear IND.*)\n      admit.\n    }\n\n    rw @inv_ren_utokens_b2 in i2; auto.\n    allsimpl.\n    exists lv (ren_utokens ren nt1) (ren_utokens ren nt2); dands; auto.\n\n    unfold olift; unfold olift in i0; repnd.\n    dands.\n    { apply nt_wf_ren_utokens; auto. }\n    { apply nt_wf_ren_utokens; auto. }\n    introv wfs isp1 isp2.\n\n\n\n(*\nLemma ren_utokens_lsubst_aux_approx {o} :\n  forall lib (t1 t2 : @NTerm o) ren sub,\n    prog_sub sub\n    -> no_repeats (range_utok_ren ren)\n    -> no_repeats (dom_utok_ren ren)\n    -> disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t1))\n    -> disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t2))\n    -> (forall sub, prog_sub sub -> approx lib (lsubst_aux t1 sub) (lsubst_aux t2 sub))\n    -> approx lib (lsubst_aux (ren_utokens ren t1) sub) (lsubst_aux (ren_utokens ren t2) sub).\nProof.\n  intro lib.\n\n  pose proof\n       (approx_acc\n          lib\n          (fun a b => {t1,t2 : NTerm\n                       $ {ren : utok_ren\n                       $ {sub : Sub\n                       $ prog_sub sub\n                       # no_repeats (range_utok_ren ren)\n                       # no_repeats (dom_utok_ren ren)\n                       # disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t1))\n                       # disjoint (range_utok_ren ren) (diff (get_patom_deq o) (dom_utok_ren ren) (get_utokens t2))\n                       # (forall sub, prog_sub sub -> approx lib (lsubst_aux t1 sub) (lsubst_aux t2 sub))\n                       # a = lsubst_aux (ren_utokens ren t1) sub\n                       # b = lsubst_aux (ren_utokens ren t2) sub}}})\n          (@bot2 o)) as HH.\n  allsimpl.\n  match goal with\n      [ HH : _ -> ?B |- _ ] =>\n      assert B as h;\n        [|introv ps nr1 nr2 d1 d2 k; eapply h;exists t1 t2 ren sub;dands;eauto;fail]\n  end;[].\n\n  apply HH; clear HH.\n  introv hb hr h; exrepnd; subst.\n  rename h0 into ps.\n  rename h2 into nr1.\n  rename h3 into nr2.\n  rename h4 into disj1.\n  rename h5 into disj2.\n  rename h6 into imp.\n\n  constructor.\n  allunfold @close_comput; repnd; dands; tcsp.\n\n  - pose proof (imp sub ps) as h.\n    apply approx_relates_only_progs in h; repnd.\n    rw <- @cl_lsubst_lsubst_aux in h0; eauto 2 with slow.\n    applydup @lsubst_program_implies in h0.\n    rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow.\n    apply isprogram_lsubst_iff in h0; repnd.\n    apply isprogram_lsubst_if_isprog_sub; eauto 3 with slow.\n    rw @free_vars_ren_utokens; auto.\n\n  - pose proof (imp sub ps) as h.\n    apply approx_relates_only_progs in h; repnd.\n    rw <- @cl_lsubst_lsubst_aux in h; eauto 2 with slow.\n    applydup @lsubst_program_implies in h.\n    rw <- @cl_lsubst_lsubst_aux; eauto 2 with slow.\n    apply isprogram_lsubst_iff in h; repnd.\n    apply isprogram_lsubst_if_isprog_sub; eauto 3 with slow.\n    rw @free_vars_ren_utokens; auto.\n\n  - introv comp.\n    clear cl3 cl.\n    dup comp as comp1.\n    apply (computes_to_value_ren_utokens _ _ _ (inv_utok_ren ren)) in comp1;\n    allrw @range_utok_ren_inv_utok_ren;\n    allrw @dom_utok_ren_inv_utok_ren;\n    auto;[|rw @get_utokens_ren_utokens; apply disjoint_dom_diff_range_map_ren_atom].\n    rw @inv_ren_utokens in comp1; auto.\n\n    rw @ren_utokens_can in comp1.\n\n    dup comp1 as comp2.\n    apply cl2 in comp2; exrepnd.\n    apply (computes_to_value_ren_utokens _ _ _ ren) in comp2; auto.\n    rw @ren_utokens_can in comp2.\n\n    assert (match\n               get_utok_c\n                 match get_utok_c c with\n                   | Some a => NUTok (ren_atom (inv_utok_ren ren) a)\n                   | None => c\n                 end\n             with\n               | Some a => NUTok (ren_atom ren a)\n               | None =>\n                 match get_utok_c c with\n                   | Some a => NUTok (ren_atom (inv_utok_ren ren) a)\n                   | None => c\n                 end\n             end = c) as e.\n    { destruct c; allsimpl; tcsp.\n      rw @inv_ren_atom2; auto.\n      apply computes_to_value_preserves_utokens in comp; allsimpl.\n      rw subset_cons_l in comp; repnd.\n      intro i.\n      rw @get_utokens_ren_utokens in comp3.\n      rw in_map_iff in comp3; exrepnd; subst.\n      rw in_diff in i; repnd.\n      destruct (ren_atom_or ren a) as [d|d]; tcsp.\n      rw d in i0.\n      apply in_dom_in_range in i0; auto.\n    }\n    rw e in comp2; clear e.\n\n    eexists; dands;[exact comp2|].\n    unfold lblift; unfold lblift in comp0.\n    allrw map_length; repnd; dands; auto.\n    introv i.\n    applydup comp0 in i.\n    unfold blift; unfold blift in i0.\n    exrepnd.\n    repeat (onerw @selectbt_map; auto; try omega).\n    remember (selectbt tl_subterms n) as b1.\n    remember (selectbt tr_subterms n) as b2.\n\n    apply (alpha_eq_bterm_ren_utokens_b _ _ ren) in i1.\n    apply (alpha_eq_bterm_ren_utokens_b _ _ ren) in i2.\n\n    assert (disjoint (dom_utok_ren ren)\n                     (diff (get_patom_deq o)\n                           (range_utok_ren ren)\n                           (get_utokens_b b1))) as d.\n    {\n(*      clear IND.*)\n      admit.\n    }\n\n    rw @inv_ren_utokens_b2 in i2; auto.\n    allsimpl.\n    exists lv (ren_utokens ren nt1) (ren_utokens ren nt2); dands; auto.\n\n    unfold olift; unfold olift in i0; repnd.\n    dands.\n    { apply nt_wf_ren_utokens; auto. }\n    { apply nt_wf_ren_utokens; auto. }\n    introv wfs isp1 isp2.\nQed.\n*)\n\n    pose proof (ex_new_utok_ren\n                  (dom_utok_ren ren)\n                  (dom_utok_ren ren\n                                ++ range_utok_ren ren\n                                ++ get_utokens_sub sub\n                                ++ get_utokens nt1\n                                ++ get_utokens nt2)) as h.\n    destruct h as [ren' h]; repnd.\n    allrw disjoint_app_l; repnd.\n\n    pose proof (lsubst_ren_utokens2 nt1 ren ren' sub) as e1.\n    repeat (autodimp e1 hyp); eauto 3 with slow.\n    pose proof (lsubst_ren_utokens2 nt2 ren ren' sub) as e2.\n    repeat (autodimp e2 hyp); eauto 3 with slow.\n\n    pose proof (ren_utokens_ren_utokens\n                  (lsubst nt1 (ren_utokens_sub ren' sub))\n                  (inv_utok_ren ren')\n                  ren) as f1.\n    rw @compose_ren_utokens_trivial in f1;\n      [|rw @dom_utok_ren_inv_utok_ren; eauto 2 with slow].\n\n    pose proof (ren_utokens_ren_utokens\n                  (lsubst nt2 (ren_utokens_sub ren' sub))\n                  (inv_utok_ren ren')\n                  ren) as f2.\n    rw @compose_ren_utokens_trivial in f2;\n      [|rw @dom_utok_ren_inv_utok_ren; eauto 2 with slow].\n\n    rw <- f1 in e1; rw <- f2 in e2; clear f1 f2.\n\n    rewrite e1, e2; clear e1 e2.\n\n    pose proof (i0 (ren_utokens_sub ren' sub)) as q; clear i0.\n    repeat (autodimp q hyp); eauto 2 with slow.\n    { apply isprogram_lsubst_iff in isp1; repnd.\n      apply isprogram_lsubst_iff.\n      rw @nt_wf_ren_utokens_iff in isp0; dands; auto.\n      introv j.\n      rw @free_vars_ren_utokens in isp1.\n      apply isp1 in j; exrepnd.\n      rw @sub_find_ren_utokens_sub; rw j1.\n      eexists; dands; eauto.\n      - apply nt_wf_ren_utokens; auto.\n      - unfold closed; rw @free_vars_ren_utokens; auto. }\n    { apply isprogram_lsubst_iff in isp2; repnd.\n      apply isprogram_lsubst_iff.\n      rw @nt_wf_ren_utokens_iff in isp0; dands; auto.\n      introv j.\n      rw @free_vars_ren_utokens in isp2.\n      apply isp2 in j; exrepnd.\n      rw @sub_find_ren_utokens_sub; rw j1.\n      eexists; dands; eauto.\n      - apply nt_wf_ren_utokens; auto.\n      - unfold closed; rw @free_vars_ren_utokens; auto. }\n\n    repndors; tcsp; try (complete (allunfold @bot2; sp)).\n\n\nTheorem approx_acc {p} :\n  forall (lib : library)\n         (l r0 : bin_rel (@NTerm p))\n         (OBG: forall (r: bin_rel NTerm)\n                      (INC: r0 =2> r)\n                      (CIH: l =2> r),\n                 l =2> approx_aux lib r),\n    l =2> approx_aux lib r0.\nProof.\n  intros.\n  assert (SIM: approx_aux lib (r0 \\2/ l) x0 x1) by auto.\n  clear PR; revert x0 x1 SIM; cofix CIH.\n  intros; destruct SIM; econstructor; eauto.\n  invertsna c Hcl. repnd.\n  unfold close_comput.\n  dands; eauto.\n\n  - introv Hcomp.\n    apply Hcl2 in Hcomp.\n    exrepnd. exists tr_subterms. split; eauto.\n    eapply le_lblift2; eauto.\n    apply le_olift.\n\n    unfold le_bin_rel.\n    introv Hap.\n    dorn Hap; spc.\n\n  - introv Hcomp.\n    apply Hcl3 in Hcomp; exrepnd.\n    exists a' e'; dands; auto; repdors; auto.\nQed.\n\n\n(*\n    pose proof\n         (hr\n            (ren_utokens ren (lsubst nt1 (ren_utokens_sub ren' sub)))\n            (ren_utokens ren (lsubst nt2 (ren_utokens_sub ren' sub))))\n      as ind1.\n    autodimp ind1 hyp.\n    { exists\n        (lsubst nt1 (ren_utokens_sub ren' sub))\n        (lsubst nt2 (ren_utokens_sub ren' sub))\n        ren; dands; auto.\n      - admit.\n      - admit.\n    }\n*)\n\n\n    apply IND; tcsp.\n    { rw @range_utok_ren_inv_utok_ren; rw h0; auto. }\n    { rw @dom_utok_ren_inv_utok_ren; auto. }\n    { clear IND; admit. }\n    { clear IND; admit. }\n\n    apply IND; tcsp.\n    { clear IND; admit. }\n    { clear IND; admit. }\n\n  - clear IND; admit.\n\n  - clear IND; admit.\nQed.\n\n(*\n\n      apply hr.\n      exists (lsubst nt1 (ren_utokens_sub ren' sub))\n             (lsubst nt2 (ren_utokens_sub ren' sub))\n             ren;\n        dands; eauto 3 with slow.\n\n      * rw @range_utok_ren_app.\n        rw @range_utok_ren_inv_utok_ren.\n        apply no_repeats_app; dands; eauto 3 with slow.\n        { rw h7; auto. }\n        { eauto 3 with slow. }\n\npose proof (hr (ren_utokens (ren ++ inv_utok_ren ren')\n                                  (lsubst nt1 (ren_utokens_sub ren' sub)))\n                     (ren_utokens (ren ++ inv_utok_ren ren')\n                                  (lsubst nt2 (ren_utokens_sub ren' sub)))\n*)\n\nQed.\n *)\n\n\n(*\n*** Local Variables:\n*** coq-load-path: (\".\" \"../util/\" \"../terms/\" \"../computation/\")\n*** End:\n*)\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/cequiv/approx_props1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.20945859565121086}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import Recdef.\nExisting Instance NullExtension.Espec.\nRequire Import VST.progs.switch.\nRequire Export VST.floyd.Funspec_old_Notation.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition twice_spec :=\n  DECLARE _twice\n    WITH n : Z\n    PRE [ _n OF tint ]\n      PROP  (Int.min_signed <= n+n <= Int.max_signed)\n      LOCAL (temp _n (Vint (Int.repr n)))\n      SEP ()\n    POST [ tint ]\n      PROP ()\n      LOCAL (temp ret_temp (Vint (Int.repr (n+n))))\n      SEP ().\n\n\nDefinition f_spec :=\n  DECLARE _f\n    WITH x : Z\n    PRE [ _x OF tuint ]\n      PROP  (0 <= x <= Int.max_unsigned)\n      LOCAL (temp _x (Vint (Int.repr x)))\n      SEP ()\n    POST [ tint ]\n      PROP ()\n      LOCAL (temp ret_temp (Vint (Int.repr 1)))\n      SEP ().\n\n\nDefinition Gprog : funspecs :=   ltac:(with_library prog [twice_spec]).\n\nLemma body_twice: semax_body Vprog Gprog f_twice twice_spec.\nProof.\nstart_function.\nforward_if (PROP() LOCAL(temp _n (Vint (Int.repr (n+n)))) SEP()).\nrepeat forward; entailer!.\nrepeat forward; entailer!.\nrepeat forward; entailer!.\nrepeat forward; entailer!.\nrepeat forward; entailer!.\nrepeat forward; entailer!.\nQed.\n\nLemma body_f: semax_body Vprog Gprog f_f f_spec.\nProof.\nstart_function.\nforward_if (@FF (environ->mpred) _).\nforward.\nforward.\nforward.\nforward.\nforward.\nQed.\n\n\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/progs/verif_switch.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.20926954850482776}}
{"text": "Require Import UFO.Util.Postfix.\nRequire Import UFO.Util.Subset.\nRequire Import UFO.Rel.Definitions.\nSet Implicit Arguments.\n\n(** Monotinicity with respect to label allocation *)\n\nSection section_monotone.\n\nHint Resolve postfix_trans.\nHint Resolve subset_trans.\n\nLemma 𝓡_monotone_l n 𝓥 𝓤 ξ₁ ξ₁' ξ₂ K₁ K₂ :\npostfix ξ₁ ξ₁' →\nn ⊨ 𝓡_Fun_Fix' 𝓥 𝓤 ξ₁ ξ₂ K₁ K₂ →\nn ⊨ 𝓡_Fun_Fix' 𝓥 𝓤 ξ₁' ξ₂ K₁ K₂.\nProof.\nintros Hξ₁' HK ; idestruct HK as HKv HKw ; isplit.\n+ iintro ξ₁'' ; iintro ξ₂' ; iintro Hξ₁'' ; iintro Hξ₂'.\n  ielim_vars HKv ; [ apply HKv | eauto | eauto ].\n+ iintro ξ₁'' ; iintro ξ₂' ; iintro Hξ₁'' ; iintro Hξ₂'.\n  ielim_vars HKw ; [ apply HKw | eauto | eauto ].\nQed.\n\nLemma 𝓡_monotone_r n 𝓥 𝓤 ξ₁ ξ₂ ξ₂' K₁ K₂ :\npostfix ξ₂ ξ₂' →\nn ⊨ 𝓡_Fun_Fix' 𝓥 𝓤 ξ₁ ξ₂ K₁ K₂ →\nn ⊨ 𝓡_Fun_Fix' 𝓥 𝓤 ξ₁ ξ₂' K₁ K₂.\nProof.\nintros Hξ₂' HK ; idestruct HK as HKv HKw ; isplit.\n+ iintro ξ₁' ; iintro ξ₂'' ; iintro Hξ₁' ; iintro Hξ₂''.\n  ielim_vars HKv ; [ apply HKv | eauto | eauto ].\n+ iintro ξ₁' ; iintro ξ₂'' ; iintro Hξ₁' ; iintro Hξ₂''.\n  ielim_vars HKw ; [ apply HKw | eauto | eauto ].\nQed.\n\nHint Resolve 𝓡_monotone_l 𝓡_monotone_r.\n\nCorollary 𝓡_monotone n 𝓥 𝓤 ξ₁ ξ₁' ξ₂ ξ₂' K₁ K₂ :\nn ⊨ 𝓡_Fun_Fix' 𝓥 𝓤 ξ₁ ξ₂ K₁ K₂ →\npostfix ξ₁ ξ₁' →\npostfix ξ₂ ξ₂' →\nn ⊨ 𝓡_Fun_Fix' 𝓥 𝓤 ξ₁' ξ₂' K₁ K₂.\nProof.\neauto.\nQed.\n\nLemma 𝓚_monotone_l n 𝓣a 𝓣b ξ₁ ξ₁' ξ₂ K₁ K₂ :\npostfix ξ₁ ξ₁' →\nn ⊨ 𝓚_Fun 𝓣a 𝓣b ξ₁ ξ₂ K₁ K₂ →\nn ⊨ 𝓚_Fun 𝓣a 𝓣b ξ₁' ξ₂ K₁ K₂.\nProof.\nintros ? HK ; do 4 iintro.\nielim_vars HK ; eauto.\nQed.\n\nLemma 𝓚_monotone_r n 𝓣a 𝓣b ξ₁ ξ₂ ξ₂' K₁ K₂ :\npostfix ξ₂ ξ₂' →\nn ⊨ 𝓚_Fun 𝓣a 𝓣b ξ₁ ξ₂ K₁ K₂ →\nn ⊨ 𝓚_Fun 𝓣a 𝓣b ξ₁ ξ₂' K₁ K₂.\nProof.\nintros ? HK ; do 4 iintro.\nielim_vars HK ; eauto.\nQed.\n\nHint Resolve 𝓚_monotone_l 𝓚_monotone_r.\n\nLemma 𝓚_monotone n 𝓣a 𝓣b ξ₁ ξ₁' ξ₂ ξ₂' K₁ K₂ :\npostfix ξ₁ ξ₁' →\npostfix ξ₂ ξ₂' →\nn ⊨ 𝓚_Fun 𝓣a 𝓣b ξ₁ ξ₂ K₁ K₂ →\nn ⊨ 𝓚_Fun 𝓣a 𝓣b ξ₁' ξ₂' K₁ K₂.\nProof.\neauto.\nQed.\n\nLemma 𝓗_monotone_l n 𝓣a 𝓣b ξ₁ ξ₁' ξ₂ r₁ r₂ :\npostfix ξ₁ ξ₁' →\nn ⊨ 𝓗_Fun 𝓣a 𝓣b ξ₁ ξ₂ r₁ r₂ →\nn ⊨ 𝓗_Fun 𝓣a 𝓣b ξ₁' ξ₂ r₁ r₂.\nProof.\nintros ? H ; do 4 iintro.\nielim_vars H ; eauto.\nQed.\n\nLemma 𝓗_monotone_r n 𝓣a 𝓣b ξ₁ ξ₂ ξ₂' r₁ r₂ :\npostfix ξ₂ ξ₂' →\nn ⊨ 𝓗_Fun 𝓣a 𝓣b ξ₁ ξ₂ r₁ r₂ →\nn ⊨ 𝓗_Fun 𝓣a 𝓣b ξ₁ ξ₂' r₁ r₂.\nProof.\nintros ? H ; do 4 iintro.\nielim_vars H ; eauto.\nQed.\n\nHint Resolve 𝓗_monotone_l 𝓗_monotone_r.\n\nCorollary 𝓗_monotone n 𝓣a 𝓣b ξ₁ ξ₁' ξ₂ ξ₂' r₁ r₂ :\npostfix ξ₁ ξ₁' →\npostfix ξ₂ ξ₂' →\nn ⊨ 𝓗_Fun 𝓣a 𝓣b ξ₁ ξ₂ r₁ r₂ →\nn ⊨ 𝓗_Fun 𝓣a 𝓣b ξ₁' ξ₂' r₁ r₂.\nProof.\neauto.\nQed.\n\nContext (EV LV V : Set).\nContext (Ξ : XEnv EV LV).\nContext (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig).\nContext (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig).\nContext (γ₁ γ₂ : V → val0).\n\nLemma 𝓜_monotone_l n σ ℓ ξ₁ ξ₁' ξ₂ m₁ m₂ :\npostfix ξ₁ ξ₁' →\nn ⊨ 𝓜⟦ Ξ ⊢ σ ^ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ m₁ m₂ →\nn ⊨ 𝓜⟦ Ξ ⊢ σ ^ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁' ξ₂ m₁ m₂.\nProof.\n+ destruct σ as [ σ' | σ' | σ' | T E ] ; intros Hξ₁' Hm ; simpl in Hm |- *.\n  - idestruct Hm as m₁' Hm ; idestruct Hm as m₂' Hm ;\n    idestruct Hm as Hm Hm'.\n    repeat ieexists ; isplit ; [ eassumption | ].\n    do 4 iintro.\n    ielim_vars Hm' ; eauto.\n  - idestruct Hm as m₁' Hm ; idestruct Hm as m₂' Hm ;\n    idestruct Hm as Hm Hm'.\n    repeat ieexists ; isplit ; [ eassumption | ].\n    do 4 iintro.\n    ielim_vars Hm' ; eauto.\n  - idestruct Hm as m₁' Hm ; idestruct Hm as m₂' Hm ;\n    idestruct Hm as Hm Hm'.\n    repeat ieexists ; isplit ; [ eassumption | ].\n    do 4 iintro.\n    ielim_vars Hm' ; eauto.\n  - idestruct Hm as r₁ Hm ; idestruct Hm as r₂ Hm ;\n    idestruct Hm as Hm Hr ; idestruct Hr as HX Hr.\n    repeat ieexists ; repeat isplit ; [ eassumption | eassumption | ].\n    later_shift.\n    eapply 𝓗_monotone_l ; eauto.\nQed.\n\nLemma 𝓜_monotone_r n σ ℓ ξ₁ ξ₂ ξ₂' m₁ m₂ :\npostfix ξ₂ ξ₂' →\nn ⊨ 𝓜⟦ Ξ ⊢ σ ^ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ m₁ m₂ →\nn ⊨ 𝓜⟦ Ξ ⊢ σ ^ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂' m₁ m₂.\nProof.\n+ destruct σ as [ σ' | σ' | σ' | T E ] ; intros Hξ₂' Hm ; simpl in Hm |- *.\n  - idestruct Hm as m₁' Hm ; idestruct Hm as m₂' Hm ;\n    idestruct Hm as Hm Hm'.\n    repeat ieexists ; isplit ; [ eassumption | ].\n    do 4 iintro.\n    ielim_vars Hm' ; eauto.\n  - idestruct Hm as m₁' Hm ; idestruct Hm as m₂' Hm ;\n    idestruct Hm as Hm Hm'.\n    repeat ieexists ; isplit ; [ eassumption | ].\n    do 4 iintro.\n    ielim_vars Hm' ; eauto.\n  - idestruct Hm as m₁' Hm ; idestruct Hm as m₂' Hm ;\n    idestruct Hm as Hm Hm'.\n    repeat ieexists ; isplit ; [ eassumption | ].\n    do 4 iintro.\n    ielim_vars Hm' ; eauto.\n  - idestruct Hm as r₁ Hm ; idestruct Hm as r₂ Hm ;\n    idestruct Hm as Hm Hr ; idestruct Hr as HX Hr.\n    repeat ieexists ; repeat isplit ; [ eassumption | eassumption | ].\n    later_shift.\n    eapply 𝓗_monotone_r ; eauto.\nQed.\n\nHint Resolve 𝓜_monotone_l 𝓜_monotone_r.\n\nCorollary 𝓜_monotone n σ ℓ ξ₁ ξ₁' ξ₂ ξ₂' m₁ m₂ :\npostfix ξ₁ ξ₁' →\npostfix ξ₂ ξ₂' →\nn ⊨ 𝓜⟦ Ξ ⊢ σ ^ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ m₁ m₂ →\nn ⊨ 𝓜⟦ Ξ ⊢ σ ^ ℓ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁' ξ₂' m₁ m₂.\nProof.\neauto.\nQed.\n\nLemma 𝓥_monotone_l n T ξ₁ ξ₁' ξ₂ v₁ v₂ :\npostfix ξ₁ ξ₁' →\nn ⊨ 𝓥⟦ Ξ ⊢ T ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ →\nn ⊨ 𝓥⟦ Ξ ⊢ T ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁' ξ₂ v₁ v₂.\nProof.\n+ destruct T as [ | Ta Ea Tb Eb | 𝔽 ℓ | σ ℓ ] ; intros Hξ₁' Hv ;\n  simpl in Hv|-*.\n  - crush.\n  - idestruct Hv as K₁ Hv ; idestruct Hv as K₂ Hv ;\n    idestruct Hv as Hv HK.\n    repeat ieexists ; isplit ; eauto.\n  - idestruct Hv as m₁ Hv ; idestruct Hv as m₂ Hv ;\n    idestruct Hv as X₁ Hv ; idestruct Hv as X₂ Hv ;\n    idestruct Hv as Hv HX ; idestruct HX as HX Hm.\n    repeat ieexists ; repeat isplit ; try eassumption.\n    later_shift.\n    apply 𝓥_roll ; apply 𝓥_unroll in Hm.\n    simpl in Hm |- *.\n    idestruct Hm as m₁' Hm ; idestruct Hm as m₂' Hm ;\n    idestruct Hm as X₁' Hm ; idestruct Hm as X₂' Hm ;\n    idestruct Hm as Hm HX' ; idestruct HX' as HX' Hm'.\n    repeat ieexists ; repeat isplit ; eauto.\n  - idestruct Hv as m₁ Hv ; idestruct Hv as m₂ Hv ;\n    idestruct Hv as X₁ Hv ; idestruct Hv as X₂ Hv ;\n    idestruct Hv as Hv HX ; idestruct HX as HX Hm.\n    repeat ieexists ; repeat isplit ; eauto.\nQed.\n\nLemma 𝓥_monotone_r n T ξ₁ ξ₂ ξ₂' v₁ v₂ :\npostfix ξ₂ ξ₂' →\nn ⊨ 𝓥⟦ Ξ ⊢ T ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ →\nn ⊨ 𝓥⟦ Ξ ⊢ T ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂' v₁ v₂.\nProof.\n+ destruct T as [ | Ta Ea Tb Eb | 𝔽 ℓ | σ ℓ ] ; intros Hξ₂' Hv ; simpl in Hv |- *.\n  - crush.\n  - idestruct Hv as K₁ Hv ; idestruct Hv as K₂ Hv ;\n    idestruct Hv as Hv HK.\n    repeat ieexists ; isplit ; eauto.\n  - idestruct Hv as m₁ Hv ; idestruct Hv as m₂ Hv ;\n    idestruct Hv as X₁ Hv ; idestruct Hv as X₂ Hv ;\n    idestruct Hv as Hv HX ; idestruct HX as HX Hm.\n    repeat ieexists ; repeat isplit ; try eassumption.\n    later_shift.\n    apply 𝓥_roll ; apply 𝓥_unroll in Hm.\n    simpl in Hm |- *.\n    idestruct Hm as m₁' Hm ; idestruct Hm as m₂' Hm ;\n    idestruct Hm as X₁' Hm ; idestruct Hm as X₂' Hm ;\n    idestruct Hm as Hm HX' ; idestruct HX' as HX' Hm'.\n    repeat ieexists ; repeat isplit ; eauto.\n - idestruct Hv as m₁ Hv ; idestruct Hv as m₂ Hv ;\n    idestruct Hv as X₁ Hv ; idestruct Hv as X₂ Hv ;\n    idestruct Hv as Hv HX ; idestruct HX as HX Hm.\n    repeat ieexists ; repeat isplit ; eauto.\nQed.\n\nHint Resolve 𝓥_monotone_l 𝓥_monotone_r.\n\nCorollary 𝓥_monotone n T ξ₁ ξ₁' ξ₂ ξ₂' v₁ v₂ :\npostfix ξ₁ ξ₁' →\npostfix ξ₂ ξ₂' →\nn ⊨ 𝓥⟦ Ξ ⊢ T ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ v₁ v₂ →\nn ⊨ 𝓥⟦ Ξ ⊢ T ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁' ξ₂' v₁ v₂.\nProof.\neauto.\nQed.\n\nLemma 𝜞_monotone n Γ ξ₁ ξ₁' ξ₂ ξ₂' :\nn ⊨ 𝜞⟦ Ξ ⊢ Γ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ γ₁ γ₂ →\npostfix ξ₁ ξ₁' →\npostfix ξ₂ ξ₂' →\nn ⊨ 𝜞⟦ Ξ ⊢ Γ ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁' ξ₂' γ₁ γ₂.\nProof.\nintros Hγ ? ? ; iintro x ; ispecialize Hγ x.\neauto.\nQed.\n\nHint Resolve postfix_is_subset.\n\nLemma 𝜩_monotone ξ₁ ξ₂ ξ₁' ξ₂' :\n𝜩 Ξ ξ₁ ξ₂ →\npostfix ξ₁ ξ₁' →\npostfix ξ₂ ξ₂' →\n𝜩 Ξ ξ₁' ξ₂'.\nProof.\nintros H ? ?.\ndestruct H ; split ; eauto.\nQed.\n\nLemma δ_is_closed_monotone n ξ₁ ξ₂ ξ₁' ξ₂' :\nn ⊨ δ_is_closed ξ₁ ξ₂ δ →\npostfix ξ₁ ξ₁' →\npostfix ξ₂ ξ₂' →\nn ⊨ δ_is_closed ξ₁' ξ₂' δ.\nProof.\nintros H ? ? ; repeat iintro.\niespecialize H ; ispecialize H ; [ eassumption | ].\nielim_prop H ; destruct H ; split ; eauto.\nQed.\n\nHint Resolve postfix_In.\n\nLemma ρ₁ρ₂_are_closed_monotone ξ₁ ξ₂ ξ₁' ξ₂' :\nρ₁ρ₂_are_closed ξ₁ ξ₂ ρ₁ ρ₂ →\npostfix ξ₁ ξ₁' →\npostfix ξ₂ ξ₂' →\nρ₁ρ₂_are_closed ξ₁' ξ₂' ρ₁ ρ₂.\nProof.\nintros H H₁ H₂ ; repeat iintro.\nintros α X ; specialize (H α X).\napply postfix_is_subset in H₁.\napply postfix_is_subset in H₂.\ndestruct H ; split ; intro ; auto.\nQed.\n\nEnd section_monotone.\n", "meta": {"author": "yizhouzhang", "repo": "olaf-coq", "sha": "03090a5e60e739dfa45ad60322d848c18faad48d", "save_path": "github-repos/coq/yizhouzhang-olaf-coq", "path": "github-repos/coq/yizhouzhang-olaf-coq/olaf-coq-03090a5e60e739dfa45ad60322d848c18faad48d/coq-src/UFO/Rel/Monotone.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.20926954850482776}}
{"text": "(*\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\nRequire Import String.\nRequire Import List.\nRequire Import Compare_dec.\nRequire Import Program.\nRequire Import Eqdep_dec.\nRequire Import Bool.\nRequire Import EquivDec.\nRequire Import Utils.\nRequire Import Types.\nRequire Import DataModel.\nRequire Import ForeignData.\nRequire Import ForeignOperators.\nRequire Import ForeignDataTyping.\nRequire Import ForeignOperatorsTyping.\nRequire Import Operators.\nRequire Import TUtil.\nRequire Import TData.\nRequire Import TSortBy.\nRequire Import TUnaryOperators.\nRequire Import TBinaryOperators.\nRequire Import TOperatorsInfer.\n\nSection TOperatorsInferSub.\n  (* Lemma/definitions over types involved in the inference *)\n  \n  Context {fdata:foreign_data}.\n  Context {ftype:foreign_type}.\n  Context {fdtyping:foreign_data_typing}.\n  Context {m:brand_model}.\n\n  Context {foperators:foreign_operators}.\n  Context {foptyping:foreign_operators_typing}.\n\n  Section b.\n\n    (* returns an optional tuple containing:\n       1) the inferred type of the binary operation\n       2) the required type of the first argument (will be a non-proper supertype of τ₁)\n       3) the required type of the second argument (will be a non-proper supertype of τ₂)      \n     *)\n\n    Definition infer_binary_op_type_sub\n               (b:binary_op) (τ₁ τ₂:rtype) : option (rtype*rtype*rtype) :=\n      match b with\n      | OpEqual =>\n        let τcommon := τ₁ ⊔ τ₂ in\n        Some (Bool, τcommon, τcommon)\n      | OpRecConcat =>\n        match τ₁ ==b ⊥, τ₂ ==b ⊥ with\n        | true, true => Some (⊥, ⊥, ⊥)\n        | true, false =>\n           lift (fun _ => (τ₂, ⊥, τ₂)) (tunrec τ₂)\n        | false, true =>\n           lift (fun _ => (τ₁, τ₁, ⊥)) (tunrec τ₁)\n        | false, false =>\n          lift (fun τ => (τ, τ₁, τ₂)) (trecConcatRight τ₁ τ₂)\n        end\n      | OpRecMerge =>\n        match τ₁ ==b ⊥, τ₂ ==b ⊥ with\n        | true, true => Some (Coll ⊥, ⊥, ⊥)\n        | true, false =>\n           lift (fun _ => (Coll τ₂, ⊥, τ₂)) (tunrec τ₂)\n        | false, true =>\n           lift (fun _ => (Coll τ₁, τ₁, ⊥)) (tunrec τ₁)\n        | false, false =>\n          lift (fun τ => (Coll τ, τ₁, τ₂)) (tmergeConcat τ₁ τ₂)\n        end\n      | OpAnd =>\n        match subtype_dec τ₁ Bool, subtype_dec τ₂ Bool with\n        | left _, left _ => Some (Bool, Bool, Bool)\n        | _, _ => None\n      end\n      | OpOr =>\n        match subtype_dec τ₁ Bool, subtype_dec τ₂ Bool with\n        | left _, left _ => Some (Bool, Bool, Bool)\n        | _, _ => None\n        end\n      | OpLt\n      | OpLe =>\n        match subtype_dec τ₁ Nat, subtype_dec τ₂ Nat with\n        | left _, left _ => Some (Bool, Nat, Nat)\n        | _, _ => None\n        end\n      | OpBagNth =>\n        match subtype_dec τ₂ Nat with\n        | left _ =>\n          let τ₁' := τ₁ ⊔ (Coll ⊥) in\n          lift (fun τ => (τ, τ₁', Nat)) (tsingleton τ₁')\n        | _ => None\n        end\n      | OpBagUnion | OpBagDiff | OpBagMin | OpBagMax =>\n        let τcommon := τ₁ ⊔ τ₂ in\n        if (tuncoll τcommon)\n        then Some (τcommon, τcommon, τcommon)\n        else None\n      (* Note: this may be too permisive.\n         We could be more restrictive by enforcing that the element \n         type is a subtype of the collection type *)\n      | OpContains =>\n        if τ₂ ==b ⊥\n        then Some (Bool, τ₁, τ₂)\n        else lift (fun τ₂' =>\n                     let τ := τ₁ ⊔ τ₂' in\n                     (Bool, τ, Coll τ))\n                  (tuncoll τ₂)\n      | OpStringConcat =>\n        match subtype_dec τ₁ String, subtype_dec τ₂ String with\n        | left _, left _ => Some (String, String, String)\n        | _, _ => None\n        end\n      | OpStringJoin =>\n        match subtype_dec τ₁ String with\n        | left _ =>\n          if subtype_dec τ₂ (Coll String)\n          then Some (String, String, Coll String)\n          else None\n        | _ => None\n        end\n      | OpNatBinary _ =>\n        match subtype_dec τ₁ Nat, subtype_dec τ₂ Nat with\n        | left _, left _ => Some (Nat, Nat, Nat)\n        | _, _ => None\n        end\n      | OpFloatBinary _ =>\n        match subtype_dec τ₁ Float, subtype_dec τ₂ Float with\n        | left _, left _ => Some (Float, Float, Float)\n        | _, _ => None\n        end\n      | OpFloatCompare _ =>\n        match subtype_dec τ₁ Float, subtype_dec τ₂ Float with\n        | left _, left _ => Some (Bool, Float, Float)\n        | _, _ => None\n        end\n      | OpForeignBinary fb =>\n        foreign_operators_typing_binary_infer_sub fb τ₁ τ₂\n      end.\n\n  End b.\n\n  Section u.\n    (* returns an optional tuple containing:\n       1) the inferred type of the binary operation\n       2) the required type of the argument (will be a non-proper supertype of τ₁)\n     *)\n\n    Definition infer_unary_op_type_sub (u:unary_op) (τ₁:rtype) : option (rtype*rtype) :=\n      match u with\n      | OpIdentity => Some (τ₁,τ₁)\n      | OpNeg =>\n        if subtype_dec τ₁ Bool\n        then Some (Bool, Bool)\n        else None\n      | OpRec s => Some (Rec Closed ((s, τ₁)::nil) eq_refl, τ₁)\n        (* Note that ⊥ does not get further constrained by these *)\n      | OpDot s =>\n        if τ₁ == ⊥\n        then Some (⊥, ⊥)\n        else lift (fun τ => (τ, τ₁)) (tunrecdot s τ₁)\n      | OpRecRemove s =>\n        if τ₁ == ⊥\n        then Some (⊥, ⊥)\n        else lift (fun τ => (τ, τ₁)) (tunrecremove s τ₁)\n      | OpRecProject sl =>\n        if τ₁ == ⊥\n        then Some (⊥, ⊥)\n        else lift (fun τ => (τ, τ₁)) (tunrecproject sl τ₁)\n      | OpBag => Some (Coll τ₁,τ₁)\n      | OpSingleton =>\n        let τ₁' := τ₁ ⊔ (Coll ⊥) in\n        lift (fun τ => (τ, τ₁')) (tsingleton τ₁')\n      | OpFlatten =>\n        let τ₁' := τ₁ ⊔ (Coll (Coll ⊥)) in\n        bind (tuncoll τ₁')\n             (fun τ₁in =>\n                lift (fun _ => (τ₁in, τ₁'))\n                     (tuncoll τ₁in))\n      | OpDistinct =>\n        let τ₁' := τ₁ ⊔ (Coll ⊥) in\n        lift (fun τ => (Coll τ, τ₁')) (tuncoll τ₁')\n      | OpOrderBy sl =>\n        let τ₁' := τ₁ ⊔ (Coll ⊥) in\n        match (tuncoll τ₁') with\n        | Some τ₁₀ =>\n          match tunrecsortable (List.map fst sl) τ₁₀ with\n          | Some _ => Some (τ₁', τ₁')\n          | None => None\n          end\n        | None => None\n        end\n      | OpCount =>\n        let τ₁' := τ₁ ⊔ (Coll ⊥) in\n        lift (fun τ => (Nat, τ₁')) (tuncoll τ₁')\n      | OpToString\n      | OpToText =>\n        Some (String, τ₁)\n      | OpLength =>\n        if (subtype_dec τ₁ String)\n        then Some (Nat, String)\n        else None\n      | OpSubstring _ _ =>\n        if (subtype_dec τ₁ String)\n        then Some (String, String)\n        else None\n      | OpLike _ =>\n        if (subtype_dec τ₁ String)\n        then Some (Bool, String)\n        else None\n      | OpLeft =>\n        Some (Either τ₁ ⊥, τ₁)\n      | OpRight =>\n        Some (Either ⊥ τ₁, τ₁)\n      | OpBrand b =>\n        if (subtype_dec τ₁ (brands_type b))\n        then Some (Brand b, τ₁)\n        else None\n      | OpUnbrand =>\n        if τ₁ == ⊥\n        then\n          Some (⊥, ⊥)\n        else\n          match `τ₁ with\n          | Brand₀ b => Some (brands_type b, τ₁)\n          | _ => None\n          end\n      | OpCast b =>\n        if τ₁ == ⊥\n        then\n          Some (⊥, ⊥)\n        else\n          match `τ₁ with\n          | Brand₀ _ => Some (Option (Brand b), τ₁)\n          | _ => None\n          end\n      | OpNatUnary op =>\n        if subtype_dec τ₁ Nat\n        then Some (Nat, Nat)\n        else None\n      | OpNatSum\n      | OpNatMin\n      | OpNatMax\n      | OpNatMean =>\n        if subtype_dec τ₁ (Coll Nat)\n        then Some (Nat, Coll Nat)\n        else None\n      | OpFloatOfNat =>\n        if subtype_dec τ₁ Nat\n        then Some (Float, Nat)\n        else None\n      | OpFloatUnary op =>\n        if subtype_dec τ₁ Float\n        then Some (Float, Float)\n        else None\n      | OpFloatTruncate =>\n        if subtype_dec τ₁ Float\n        then Some (Nat, Float)\n        else None\n      | OpFloatSum\n      | OpFloatBagMin\n      | OpFloatBagMax\n      | OpFloatMean =>\n        if subtype_dec τ₁ (Coll Float)\n        then Some (Float, Coll Float)\n        else None\n      | OpForeignUnary fu =>\n        foreign_operators_typing_unary_infer_sub fu τ₁\n      end.\n\n  End u.\nEnd TOperatorsInferSub.\n\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/Data/OperatorsTyping/TOperatorsInferSub.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20926954850482773}}
{"text": "Require Import Sail.Values Sail.Operators_mwords Sail.Hoare bbv.Word Mword.\nRequire Import aarch64_types aarch64.\nLocal Open Scope Z.\n(*\n  imports \"Sail-AArch64.Aarch64_lemmas\" Sail.Sail2_operators_mwords_lemmas Word_Extra Proof_methods\nbegin\n(*>*)\n\ntext \\<open>Various helper lemmas for simplifying proof obligations arising in the computation of\npreconditions, e.g. if-then-else-distributivity rules for the datatypes in the model.\\<close>\n\nabbreviation\n  \"CreateFaultRecord typ1 ipaddress level acctype write1 extflag errortype secondstage s2fs1walk \\<equiv>\n     \\<lparr>FaultRecord_typ = typ1, FaultRecord_acctype = acctype, FaultRecord_ipaddress = ipaddress,\n      FaultRecord_s2fs1walk = s2fs1walk, FaultRecord_write = write1, FaultRecord_level = level,\n      FaultRecord_extflag = extflag, FaultRecord_secondstage = secondstage, FaultRecord_domain = 0,\n      FaultRecord_errortype = errortype, FaultRecord_debugmoe = 0\\<rparr>\"\n\nabbreviation\n  \"AccessDescriptor acctype ptwalk secondstage s2fs2walk level \\<equiv>\n     \\<lparr>AccessDescriptor_acctype = acctype,\n      AccessDescriptor_page_table_walk = ptwalk,\n      AccessDescriptor_secondstage = secondstage,\n      AccessDescriptor_s2fs1walk = s2fs2walk,\n      AccessDescriptor_level = level\\<rparr>\"\n\nlemma CreateFaultRecord_if_distrib:\n  \"(if c then CreateFaultRecord typ1 ipaddress1 level1 acctype1 write1 extflag1 errortype1 secondstage1 s2fs1walk1\n    else CreateFaultRecord typ2 ipaddress2 level2 acctype2 write2 extflag2 errortype2 secondstage2 s2fs1walk2) =\n    CreateFaultRecord (if c then typ1 else typ2) (if c then ipaddress1 else ipaddress2)\n      (if c then level1 else level2) (if c then acctype1 else acctype2) (if c then write1 else write2)\n      (if c then extflag1 else extflag2) (if c then errortype1 else errortype2)\n      (if c then secondstage1 else secondstage2) (if c then s2fs1walk1 else s2fs1walk2)\"\n  by auto\n\nlemma fun2_if_distrib:\n  \"(if c then f x1 y1 else f x2 y2) = f (if c then x1 else x2) (if c then y1 else y2)\"\n  by auto\n\nlemmas fun2_if_distribs =\n  if_distrib[where f = f for f :: \"'a \\<Rightarrow> 'b \\<Rightarrow> 'c\", symmetric]\n  fun2_if_distrib\n  fun2_if_distrib[where f = Pair]\n  fun2_if_distrib[where f = \"(\\<and>)\"]\n  fun2_if_distrib[where f = \"(\\<or>)\"]\n\nlemmas prod_if_distrib = fun2_if_distrib[where f = Pair]\nlemmas conj_if_distrib = fun2_if_distrib[where f = \"(\\<and>)\"]\nlemmas disj_if_distrib = fun2_if_distrib[where f = \"(\\<or>)\"]\n\nlemmas all_if_distrib = if_distrib[where f = \"\\<lambda>c. \\<forall>b. c b\", symmetric]\n\nlemmas AddressDescriptor_memattrs_update_if_distrib =\n  if_distrib[where f = \"\\<lambda>c. addrdesc\\<lparr>AddressDescriptor_memattrs := c\\<rparr>\" for addrdesc, symmetric]\n  if_distrib[where f = \"\\<lambda>c. c\\<lparr>AddressDescriptor_memattrs := z\\<rparr>\" for z]\n\nlemma MemoryAttributes_if_distrib:\n  \"(if c then\n      \\<lparr>MemoryAttributes_typ = typ1, MemoryAttributes_device = device1,\n       MemoryAttributes_inner = inner1, MemoryAttributes_outer = outer1,\n       MemoryAttributes_shareable = shareable1, MemoryAttributes_outershareable = outershareable1\\<rparr>\n    else\n      \\<lparr>MemoryAttributes_typ = typ2, MemoryAttributes_device = device2,\n       MemoryAttributes_inner = inner2, MemoryAttributes_outer = outer2,\n       MemoryAttributes_shareable = shareable2, MemoryAttributes_outershareable = outershareable2\\<rparr>) =\n    \\<lparr>MemoryAttributes_typ = if c then typ1 else typ2,\n     MemoryAttributes_device = if c then device1 else device2,\n     MemoryAttributes_inner = if c then inner1 else inner2,\n     MemoryAttributes_outer = if c then outer1 else outer2,\n     MemoryAttributes_shareable = if c then shareable1 else shareable2,\n     MemoryAttributes_outershareable = if c then outershareable1 else outershareable2\\<rparr>\"\n  by auto\n\nlemma MemoryAttributes_cong:\n  assumes \"typ1 = typ2\" and \"device1 = device2\" and \"inner1 = inner2\" and \"outer1 = outer2\"\n    and \"shareable1 = shareable2\" and \"outershareable1 = outershareable2\"\n  shows\n    \"\\<lparr>MemoryAttributes_typ = typ1, MemoryAttributes_device = device1,\n      MemoryAttributes_inner = inner1, MemoryAttributes_outer = outer1,\n      MemoryAttributes_shareable = shareable1, MemoryAttributes_outershareable = outershareable1\\<rparr> =\n     \\<lparr>MemoryAttributes_typ = typ2, MemoryAttributes_device = device2,\n      MemoryAttributes_inner = inner2, MemoryAttributes_outer = outer2,\n      MemoryAttributes_shareable = shareable2, MemoryAttributes_outershareable = outershareable2\\<rparr>\"\n  using assms by auto\n\n\nlemma MemAttrHints_if_distrib:\n  \"(if c\n    then \\<lparr>MemAttrHints_attrs = attrs1, MemAttrHints_hints = hints1, MemAttrHints_transient = transient1\\<rparr>\n    else \\<lparr>MemAttrHints_attrs = attrs2, MemAttrHints_hints = hints2, MemAttrHints_transient = transient2\\<rparr>) =\n   \\<lparr>MemAttrHints_attrs = if c then attrs1 else attrs2,\n    MemAttrHints_hints = if c then hints1 else hints2,\n    MemAttrHints_transient = if c then transient1 else transient2\\<rparr>\"\n  by auto\n\nlemma MemAttrHints_cong:\n  assumes \"attrs1 = attrs2\" and \"hints1 = hints2\" and \"transient1 = transient2\"\n  shows \"\\<lparr>MemAttrHints_attrs = attrs1, MemAttrHints_hints = hints1, MemAttrHints_transient = transient1\\<rparr> =\n         \\<lparr>MemAttrHints_attrs = attrs2, MemAttrHints_hints = hints2, MemAttrHints_transient = transient2\\<rparr>\"\n  using assms by auto\n\nlemma case_option_if_distrib:\n  \"(if b then (case x1 of Some y \\<Rightarrow> f1 y | None \\<Rightarrow> g1) else (case x2 of Some y \\<Rightarrow> f2 y | None \\<Rightarrow> g2)) =\n   (case (if b then x1 else x2) of Some y \\<Rightarrow> if b then f1 y else f2 y | None \\<Rightarrow> if b then g1 else g2)\"\n  by (auto split: option.splits)\n\nlemma case_prod_if_distrib:\n  \"(if b then (case x1 of (y1, z1) \\<Rightarrow> f1 y1 z1) else (case x2 of (y2, z2) \\<Rightarrow> f2 y2 z2)) =\n   (case (if b then x1 else x2) of (y, z) \\<Rightarrow> if b then f1 y z else f2 y z)\"\n  by auto\n\nlemma app_let_distrib: \"(let x = y in f x) z = (let x = y in f x z)\"\n  by auto\n\nlemmas TLBRecord_if_distribs[simp] =\n  if_distrib[where f = TLBRecord_descupdate] if_distrib[where f = TLBRecord_descupdate_update]\n  if_distrib[where f = \"\\<lambda>x. r\\<lparr>TLBRecord_descupdate := x\\<rparr>\" for r]\n  if_distrib[where f = TLBRecord_addrdesc]\nlemmas DescriptorUpdate_if_distribs[simp] =\n  if_distrib[where f = DescriptorUpdate_descaddr_update]\nlemmas MemAttrHints_if_distribs[simp] =\n  if_distrib[where f = MemAttrHints_attrs]\nlemmas [simp] =\n  if_distrib[where f = FullAddress_physicaladdress]\n  if_distrib[where f = AddressDescriptor_paddress]\n  if_distrib[where f = \"\\<lambda>i. x < i\" for x]\n  if_distrib[where f = \"\\<lambda>i. i < x\" for x]\n  if_distrib[where f = \"\\<lambda>i. x - i\" for x]\n  if_distrib[where f = \"\\<lambda>i. i = x\" for x]\n\nlemmas PrePost_if_distribs = app_if_distrib prod_if_distrib conj_if_distrib disj_if_distrib all_if_distrib\n  AddressDescriptor_memattrs_update_if_distrib MemoryAttributes_if_distrib MemAttrHints_if_distrib\n  (*TLBRecord_descupdate_update_if_distrib DescriptorUpdate_descaddr_update_if_distrib*)\n  if_distrib[where f = \"\\<lambda>c. z \\<le> c\" for z] if_distrib[where f = \"\\<lambda>c. c \\<le> z\" for z]\n  if_distrib[where f = \"\\<lambda>c. z < c\" for z] if_distrib[where f = \"\\<lambda>c. c < z\" for z]\n  if_distrib[where f = returnS, symmetric]\n  if_distrib[where f = return, symmetric]\n  case_option_if_distrib case_prod_if_distrib\n  if_distrib[where f = \"\\<lambda>c. let a = b in c a\" for b, symmetric]\n  if_distrib[where f = \"\\<lambda>c. a \\<longrightarrow> c\" for a, symmetric]\n  (*if_distrib[where f = \"\\<lambda>c. z = c\" for z] if_distrib[where f = \"\\<lambda>c. c = z\" for z]*)\n  (*if_distrib[where f = \"\\<lambda>c. c' \\<and> c\" for c'] if_distrib[where f = \"\\<lambda>c. c \\<and> c'\" for c']*)\n\nlemmas app_case_distribs =\n  sum.case_distrib[where h = \"\\<lambda>c. c z\" for z]\n  ex.case_distrib[where h = \"\\<lambda>c. c z\" for z]\n  option.case_distrib[where h = \"\\<lambda>c. c z\" for z]\n  app_let_distrib\n\nlemma if_True_False_simps[simp]:\n  \"(if c then True else False) = c\"\n  \"(if c then False else True) = (\\<not>c)\"\n  \"(if c1 then True else c2) = (c1 \\<or> c2)\"\n  \"(if c1 then c2 else True) = (c1 \\<longrightarrow> c2)\"\n  \"(if c1 then c2 else False) = (c1 \\<and> c2)\"\n  by auto\n\nlemma conj_imp_cond_absorb[simp]: \"(b \\<longrightarrow> c1) \\<and> (b \\<longrightarrow> c2) \\<longleftrightarrow> (b \\<longrightarrow> c1 \\<and> c2)\"\n  by auto\n\nlemma if_then_imp_distrib:\n  \"(if c then x \\<longrightarrow> y else z) = ((c \\<and> \\<not>x) \\<or> (if c then y else z))\"\n  \"(if c then x \\<or> y else z) = ((c \\<and> x) \\<or> (if c then y else z))\"\n  \"(if c then x else y \\<longrightarrow> z) = ((\\<not>c \\<and> \\<not>y) \\<or> (if c then x else z))\"\n  \"(if c then x else y \\<or> z) = ((\\<not>c \\<and> y) \\<or> (if c then x else z))\"\n  by auto\n\nlemma if_then_all_distrib:\n  \"\\<And>c f g. (if c then \\<forall>x. f x else g) = (\\<forall>x. if c then f x else g)\"\n  \"\\<And>c f g. (if c then f else \\<forall>x. g x) = (\\<forall>x. if c then f else g x)\"\n  by auto\n\nlemma if_then_conj_distrib:\n  \"(if c then x \\<and> y else z) = ((c \\<longrightarrow> x) \\<and> (if c then y else z))\"\n  \"(if c then x else y \\<and> z) = ((\\<not>c \\<longrightarrow> y) \\<and> (if c then x else z))\"\n  by auto\n\nlemma nested_if_merges[simp]:\n  \"(if c1 then x else if c2 then x else y) = (if c1 \\<or> c2 then x else y)\"\n  \"(if c1 then x else if c2 then y else x) = (if c1 \\<or> \\<not>c2 then x else y)\"\n  \"(if c1 then x else (if c2 then y else (if c3 then x else z))) = (if c1 \\<or> (\\<not>c2 \\<and> c3) then x else if c2 then y else z)\"\n  \"(if c1 then x else (if c2 then (if c3 then x else y) else z)) = (if c1 \\<or> (c2 \\<and> c3) then x else if c2 then y else z)\"\n  \"(if c1 then (if c2 then x else y) else (if c3 then x else z)) = (if (c1 \\<and> c2) \\<or> (\\<not>c1 \\<and> c3) then x else if c1 then y else z)\"\n  \"(if (if a then b else c) then x else y) \\<longleftrightarrow> (if (\\<not>a \\<or> b) \\<and> (a \\<or> c) then x else y)\"\n  \"(if a then b \\<and> c else c) \\<longleftrightarrow> (\\<not>a \\<or> b) \\<and> c\"\n  \"(if a then (if b then x else y) else y) \\<longleftrightarrow> (if (a \\<and> b) then x else y)\"\n  \"(if a then (if b then x else y) else (if c then x else y)) \\<longleftrightarrow> (if (\\<not>a \\<or> b) \\<and> (a \\<or> c) then x else y)\"\n  \"(\\<forall>a. if a \\<or> b then x else y) \\<longleftrightarrow> x \\<and> (if b then x else y)\"\n  by auto\n\nlemma conj_disj_absorbs[simp]:\n  \"A \\<and> B \\<or> A \\<longleftrightarrow> A\"\n  \"A \\<and> B \\<or> B \\<longleftrightarrow> B\"\n  \"(A \\<and> B) \\<or> (\\<not>A \\<and> B) \\<longleftrightarrow> B\"\n  \"(\\<not>A \\<and> B) \\<or> (A \\<and> B) \\<longleftrightarrow> B\"\n  by auto\n\nlemma quant_singleton_bool_simps[simp]:\n  \"(\\<forall>b. b) \\<longleftrightarrow> False\" \"(\\<forall>b. \\<not>b) \\<longleftrightarrow> False\" \"(\\<exists>b. b) \\<longleftrightarrow> True\" \"(\\<exists>b. \\<not>b) \\<longleftrightarrow> True\"\n  by auto\n\nlemmas MemAttr_defs[simp] = MemAttr_WT_def MemAttr_WB_def MemAttr_NC_def\n\nlemma case_prod15_split:\n  \"(case vars of (accdesc, addrselectbottom, addrselecttop, ap_table, baseaddress, blocktranslate, desc, descaddr, descaddr2, hwupdatewalk, level,\n                     ns_table, pxn_table, result, xn_table) \\<Rightarrow>\n      f accdesc addrselectbottom addrselecttop ap_table baseaddress blocktranslate desc descaddr descaddr2 hwupdatewalk level\n                     ns_table pxn_table result xn_table) =\n   (\\<forall>accdesc addrselectbottom addrselecttop ap_table baseaddress blocktranslate desc descaddr descaddr2 hwupdatewalk level\n                     ns_table pxn_table result xn_table.\n      vars = (accdesc, addrselectbottom, addrselecttop, ap_table, baseaddress, blocktranslate, desc, descaddr, descaddr2, hwupdatewalk, level,\n                     ns_table, pxn_table, result, xn_table) \\<longrightarrow>\n      f accdesc addrselectbottom addrselecttop ap_table baseaddress blocktranslate desc descaddr descaddr2 hwupdatewalk level\n                     ns_table pxn_table result xn_table)\"\n  by auto\n\nlemma prod15_cases:\n  obtains accdesc addrselectbottom addrselecttop ap_table baseaddress blocktranslate desc descaddr descaddr2 hwupdatewalk level\n                     ns_table pxn_table result xn_table\n                   where \"x = (accdesc, addrselectbottom, addrselecttop, ap_table, baseaddress, blocktranslate, desc, descaddr, descaddr2, hwupdatewalk, level,\n                     ns_table, pxn_table, result, xn_table)\"\n  by (cases x) auto\n\nlemma TLBRecord_if_distrib:\n  \"(if c then\n      \\<lparr>TLBRecord_perms =\n         \\<lparr>Permissions_ap = ap1, Permissions_xn = xn1, Permissions_xxn = xxn1, Permissions_pxn = pxn1\\<rparr>,\n       TLBRecord_nG = nG1, TLBRecord_domain = domain1, TLBRecord_contiguous = contiguous1,\n       TLBRecord_level = level1, TLBRecord_blocksize = blocksize1,\n       TLBRecord_descupdate =\n         \\<lparr>DescriptorUpdate_AF = af1, DescriptorUpdate_AP = descupd_ap1,\n          DescriptorUpdate_descaddr = descaddr1 \\<rparr>,\n       TLBRecord_CnP = cnp1,\n       TLBRecord_addrdesc =\n         \\<lparr>AddressDescriptor_fault = fault1, AddressDescriptor_memattrs = memattrs1,\n          AddressDescriptor_paddress = \\<lparr>FullAddress_physicaladdress = paddress1, FullAddress_NS = ns1\\<rparr>,\n          AddressDescriptor_vaddress = vaddress1\\<rparr> \\<rparr>\n    else\n      \\<lparr>TLBRecord_perms =\n         \\<lparr>Permissions_ap = ap2, Permissions_xn = xn2, Permissions_xxn = xxn2, Permissions_pxn = pxn2\\<rparr>,\n       TLBRecord_nG = nG2, TLBRecord_domain = domain2, TLBRecord_contiguous = contiguous2,\n       TLBRecord_level = level2, TLBRecord_blocksize = blocksize2,\n       TLBRecord_descupdate =\n         \\<lparr>DescriptorUpdate_AF = af2, DescriptorUpdate_AP = descupd_ap2, DescriptorUpdate_descaddr = descaddr2 \\<rparr>,\n       TLBRecord_CnP = cnp2,\n       TLBRecord_addrdesc =\n         \\<lparr>AddressDescriptor_fault = fault2, AddressDescriptor_memattrs = memattrs2,\n          AddressDescriptor_paddress = \\<lparr>FullAddress_physicaladdress = paddress2, FullAddress_NS = ns2\\<rparr>,\n          AddressDescriptor_vaddress = vaddress2\\<rparr> \\<rparr>) =\n       \\<lparr>TLBRecord_perms =\n          \\<lparr>Permissions_ap = if c then ap1 else ap2,\n           Permissions_xn = if c then xn1 else xn2,\n           Permissions_xxn = if c then xxn1 else xxn2,\n           Permissions_pxn = if c then pxn1 else pxn2\\<rparr>,\n        TLBRecord_nG = if c then nG1 else nG2,\n        TLBRecord_domain = if c then domain1 else domain2,\n        TLBRecord_contiguous = if c then contiguous1 else contiguous2,\n        TLBRecord_level = if c then level1 else level2,\n        TLBRecord_blocksize = if c then blocksize1 else blocksize2,\n        TLBRecord_descupdate =\n          \\<lparr>DescriptorUpdate_AF = if c then af1 else af2,\n           DescriptorUpdate_AP = if c then descupd_ap1 else descupd_ap2,\n           DescriptorUpdate_descaddr = if c then descaddr1 else descaddr2 \\<rparr>,\n        TLBRecord_CnP = if c then cnp1 else cnp2,\n        TLBRecord_addrdesc =\n          \\<lparr>AddressDescriptor_fault = if c then fault1 else fault2,\n           AddressDescriptor_memattrs = if c then memattrs1 else memattrs2,\n           AddressDescriptor_paddress =\n              \\<lparr>FullAddress_physicaladdress = if c then paddress1 else paddress2,\n               FullAddress_NS = if c then ns1 else ns2\\<rparr>,\n           AddressDescriptor_vaddress = if c then vaddress1 else vaddress2\\<rparr> \\<rparr>\"\n  by auto\n\nlemma DescriptorUpdate_if_distrib:\n  \"(if c\n    then \\<lparr>DescriptorUpdate_AF = af1, DescriptorUpdate_AP = ap1, DescriptorUpdate_descaddr = addr1\\<rparr>\n    else \\<lparr>DescriptorUpdate_AF = af2, DescriptorUpdate_AP = ap2, DescriptorUpdate_descaddr = addr2\\<rparr>) =\n   \\<lparr>DescriptorUpdate_AF = if c then af1 else af2,\n    DescriptorUpdate_AP = if c then ap1 else ap2,\n    DescriptorUpdate_descaddr = if c then addr1 else addr2\\<rparr>\"\n  by auto\n\n\n(* Add some lemmas for automatically splitting TLBRecords into their components during precondition\n   computation.  This seems to make simplification of record updates more efficient. *)\n\nlemma TLBRecord_cases:\n  fixes x :: TLBRecord\n  obtains ap xn xxn pxn nG domain contiguous level blocksize af descupd_ap descaddr cnp fault memattrs paddress ns vaddress\n  where \"x = \\<lparr>TLBRecord_perms =\n                \\<lparr>Permissions_ap = ap, Permissions_xn = xn, Permissions_xxn = xxn, Permissions_pxn = pxn\\<rparr>,\n              TLBRecord_nG = nG, TLBRecord_domain = domain, TLBRecord_contiguous = contiguous,\n              TLBRecord_level = level, TLBRecord_blocksize = blocksize,\n              TLBRecord_descupdate =\n                \\<lparr>DescriptorUpdate_AF = af, DescriptorUpdate_AP = descupd_ap,\n                 DescriptorUpdate_descaddr = descaddr \\<rparr>,\n              TLBRecord_CnP = cnp,\n              TLBRecord_addrdesc =\n                \\<lparr>AddressDescriptor_fault = fault, AddressDescriptor_memattrs = memattrs,\n                 AddressDescriptor_paddress = \\<lparr>FullAddress_physicaladdress = paddress, FullAddress_NS = ns\\<rparr>,\n                 AddressDescriptor_vaddress = vaddress\\<rparr> \\<rparr>\"\nproof -\n  obtain perms nG domain contiguous level blocksize descupdate cnp addrdesc where\n    \"x = \\<lparr>TLBRecord_perms = perms, TLBRecord_nG = nG, TLBRecord_domain = domain,\n          TLBRecord_contiguous = contiguous, TLBRecord_level = level,\n          TLBRecord_blocksize = blocksize, TLBRecord_descupdate = descupdate,\n          TLBRecord_CnP = cnp, TLBRecord_addrdesc = addrdesc \\<rparr>\"\n    by (cases x)\n  moreover obtain ap xn xxn pxn where\n    \"perms = \\<lparr>Permissions_ap = ap, Permissions_xn = xn, Permissions_xxn = xxn, Permissions_pxn = pxn\\<rparr>\"\n    by (cases perms)\n  moreover obtain af descupd_ap descaddr where\n    \"descupdate = \\<lparr>DescriptorUpdate_AF = af, DescriptorUpdate_AP = descupd_ap,\n                   DescriptorUpdate_descaddr = descaddr \\<rparr>\"\n    by (cases descupdate)\n  moreover obtain fault memattrs paddress' vaddress where\n    \"addrdesc = \\<lparr>AddressDescriptor_fault = fault, AddressDescriptor_memattrs = memattrs,\n                  AddressDescriptor_paddress = paddress', AddressDescriptor_vaddress = vaddress\\<rparr>\"\n    by (cases addrdesc)\n  moreover obtain paddress ns where\n    \"paddress' = \\<lparr>FullAddress_physicaladdress = paddress, FullAddress_NS = ns\\<rparr>\"\n    by (cases paddress')\n  ultimately show thesis using that by blast\nqed\n\nlemma PrePostE_bindS_TLBRecord:\n  assumes f:\n    \"\\<And>ap xn xxn pxn nG domain contiguous level blocksize af descupd_ap descaddr cnp fault memattrs paddress ns vaddress.\n        PrePostE (P' ap xn xxn pxn nG domain contiguous level blocksize af descupd_ap descaddr\n                     cnp fault memattrs paddress ns vaddress)\n                 (f (\\<lparr>TLBRecord_perms =\n                        \\<lparr>Permissions_ap = ap, Permissions_xn = xn, Permissions_xxn = xxn, Permissions_pxn = pxn\\<rparr>,\n                      TLBRecord_nG = nG, TLBRecord_domain = domain, TLBRecord_contiguous = contiguous,\n                      TLBRecord_level = level, TLBRecord_blocksize = blocksize,\n                      TLBRecord_descupdate =\n                        \\<lparr>DescriptorUpdate_AF = af, DescriptorUpdate_AP = descupd_ap,\n                         DescriptorUpdate_descaddr = descaddr \\<rparr>,\n                      TLBRecord_CnP = cnp,\n                      TLBRecord_addrdesc =\n                        \\<lparr>AddressDescriptor_fault = fault, AddressDescriptor_memattrs = memattrs,\n                         AddressDescriptor_paddress =\n                            \\<lparr>FullAddress_physicaladdress = paddress,\n                             FullAddress_NS = ns\\<rparr>,\n                         AddressDescriptor_vaddress = vaddress\\<rparr> \\<rparr>)) Q E\"\n    and m: \"PrePostE P m\n                     (\\<lambda>r s. \\<forall>ap xn xxn pxn nG domain contiguous level blocksize af descupd_ap descaddr\n                             cnp fault memattrs paddress ns vaddress.\n                          \\<lparr>TLBRecord_perms =\n                             \\<lparr>Permissions_ap = ap, Permissions_xn = xn, Permissions_xxn = xxn, Permissions_pxn = pxn\\<rparr>,\n                           TLBRecord_nG = nG, TLBRecord_domain = domain, TLBRecord_contiguous = contiguous,\n                           TLBRecord_level = level, TLBRecord_blocksize = blocksize,\n                           TLBRecord_descupdate =\n                             \\<lparr>DescriptorUpdate_AF = af, DescriptorUpdate_AP = descupd_ap,\n                              DescriptorUpdate_descaddr = descaddr \\<rparr>,\n                           TLBRecord_CnP = cnp,\n                           TLBRecord_addrdesc =\n                             \\<lparr>AddressDescriptor_fault = fault, AddressDescriptor_memattrs = memattrs,\n                              AddressDescriptor_paddress =\n                                 \\<lparr>FullAddress_physicaladdress = paddress,\n                                  FullAddress_NS = ns\\<rparr>,\n                              AddressDescriptor_vaddress = vaddress\\<rparr> \\<rparr> = r \\<longrightarrow>\n                          P' ap xn xxn pxn nG domain contiguous level blocksize af descupd_ap descaddr\n                             cnp fault memattrs paddress ns vaddress s) E\"\n        (is \"PrePostE P m ?R E\")\n  shows \"PrePostE P (bindS m f) Q E\"\nproof (intro PrePostE_bindS_any)\n  fix a\n  show \"PrePostE (?R a) (f a) Q E\"\n    by (cases a rule: TLBRecord_cases) (auto intro: f)\n  show \"PrePostE P m ?R E\" using m .\nqed\n\nlemma PrePostE_bindS_prod15_TLBRecord14:\n  assumes\n    \"\\<And>x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x15 ap xn xxn pxn nG domain contiguous level\n      blocksize af descupd_ap descaddr cnp fault memattrs paddress ns vaddress.\n       PrePostE (P' x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 ap xn xxn pxn nG domain contiguous level\n                    blocksize af descupd_ap descaddr cnp fault memattrs paddress ns vaddress x15)\n                (f (x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13,\n                    \\<lparr>TLBRecord_perms =\n                      \\<lparr>Permissions_ap = ap, Permissions_xn = xn, Permissions_xxn = xxn, Permissions_pxn = pxn\\<rparr>,\n                     TLBRecord_nG = nG, TLBRecord_domain = domain, TLBRecord_contiguous = contiguous,\n                     TLBRecord_level = level, TLBRecord_blocksize = blocksize,\n                     TLBRecord_descupdate =\n                       \\<lparr>DescriptorUpdate_AF = af, DescriptorUpdate_AP = descupd_ap,\n                        DescriptorUpdate_descaddr = descaddr \\<rparr>,\n                     TLBRecord_CnP = cnp,\n                     TLBRecord_addrdesc =\n                       \\<lparr>AddressDescriptor_fault = fault, AddressDescriptor_memattrs = memattrs,\n                        AddressDescriptor_paddress =\n                           \\<lparr>FullAddress_physicaladdress = paddress, FullAddress_NS = ns\\<rparr>,\n                        AddressDescriptor_vaddress = vaddress\\<rparr> \\<rparr>, x15)) Q E\"\n    and \"PrePostE P m\n                  (\\<lambda>r s. case r of (x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15) \\<Rightarrow>\n                         (\\<forall>ap xn xxn pxn nG domain contiguous level blocksize af descupd_ap\n                           descaddr cnp fault memattrs paddress ns vaddress.\n                         (\\<lparr>TLBRecord_perms =\n                             \\<lparr>Permissions_ap = ap, Permissions_xn = xn, Permissions_xxn = xxn,\n                              Permissions_pxn = pxn\\<rparr>,\n                           TLBRecord_nG = nG, TLBRecord_domain = domain, TLBRecord_contiguous = contiguous,\n                           TLBRecord_level = level, TLBRecord_blocksize = blocksize,\n                           TLBRecord_descupdate =\n                             \\<lparr>DescriptorUpdate_AF = af, DescriptorUpdate_AP = descupd_ap,\n                              DescriptorUpdate_descaddr = descaddr \\<rparr>,\n                           TLBRecord_CnP = cnp,\n                           TLBRecord_addrdesc =\n                             \\<lparr>AddressDescriptor_fault = fault, AddressDescriptor_memattrs = memattrs,\n                              AddressDescriptor_paddress =\n                                 \\<lparr>FullAddress_physicaladdress = paddress, FullAddress_NS = ns\\<rparr>,\n                              AddressDescriptor_vaddress = vaddress\\<rparr> \\<rparr>) = x14 \\<longrightarrow>\n                          P' x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 ap xn xxn pxn nG domain\n                             contiguous level blocksize af descupd_ap descaddr cnp fault memattrs\n                             paddress ns vaddress x15 s)) E\"\n    (is \"PrePostE P m ?R E\")\n  shows \"PrePostE P (bindS m f) Q E\"\nproof (intro PrePostE_bindS_any)\n  fix a :: \"'a \\<times> 'b \\<times> 'c \\<times> 'd \\<times> 'e \\<times> 'f \\<times> 'g \\<times> 'h \\<times> 'i \\<times> 'j \\<times> 'k \\<times> 'l \\<times> 'm \\<times> TLBRecord \\<times> 'n\"\n  obtain x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15\n    where \"a = (x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15)\"\n    by (cases a rule: prod15_cases)\n  then show \"PrePostE (?R a) (f a) Q E\"\n    by (cases x14 rule: TLBRecord_cases) (auto intro: assms)\n  show \"PrePostE P m ?R E\" using assms(2) .\nqed\n\nlemmas PrePostE_bindS_TLBRecords = PrePostE_bindS_TLBRecord PrePostE_bindS_prod15_TLBRecord14\n\nlemma option_case_prod_9_None_False_elim:\n  assumes \"case x of None \\<Rightarrow> False\n             | Some (x1, x2, x3, x4, x5, x6, x7, x8, x9) \\<Rightarrow> P x1 x2 x3 x4 x5 x6 x7 x8 x9\"\n  obtains x1 x2 x3 x4 x5 x6 x7 x8 x9\n  where \"Some (x1, x2, x3, x4, x5, x6, x7, x8, x9) = x\"\n    and \"P x1 x2 x3 x4 x5 x6 x7 x8 x9\"\n  using assms by (cases x) auto\n\nlemma GetSlice_int_get_slice_int[simp]:\n  \"GetSlice_int (len :: 'a::len itself) n i = get_slice_int (int LENGTH('a)) n i\"\n  by (auto simp: GetSlice_int_def)\n\nlemmas [simp] = ex_int_def ex_nat_def\n\ndeclare extzv_def[simp]\n\nlemma slice_mask_mask: \"slice_mask outlen i l = (mask (nat l)) << (nat i)\"\n  by (auto simp: slice_mask_def mask_def)\n\nlemma HasArchVersion_True: \"HasArchVersion v = True\"\n  by (cases v; auto simp: HasArchVersion_def)\n\nlemma HaveEL_True: \"HaveEL el = True\"\n  by (auto simp: HaveEL_def)\n\nlemmas Have_simps[simp] = HaveEL_True HasArchVersion_True Have52BitPAExt_def Have52BitVAExt_def\n  HaveAccessFlagUpdateExt_def HaveAtomicExt_def HaveCommonNotPrivateTransExt_def\n  HaveDirtyBitModifierExt_def HaveExtendedExecuteNeverExt_def HaveFJCVTZSExt_def HaveNVExt_def\n  HavePACExt_def HavePANExt_def HavePrivATExt_def HaveStatisticalProfiling_def\n  HaveTrapLoadStoreMultipleDeviceExt_def HaveUAOExt_def HaveVirtHostExt_def HaveRASExt_def\n  HaveCRCExt_def AArch64_HaveHPDExt_def\n\nlemma PAMax_simp: \"PAMax () = 52\" by (auto simp: PAMax_def IMPDEF_integer_def)\n\nlemma Zeros__0_0[simp]: \"Zeros__0 n = 0\" by (auto simp: Zeros__0_def)\nlemma IsZero_iff_eq0[simp]: \"IsZero w \\<longleftrightarrow> w = 0\" by (auto simp: IsZero_def Zeros__0_def)\n\nlemma ZeroExtend_simps[simp]:\n  \"\\<And>N w. LENGTH('a) \\<le> LENGTH('b) \\<Longrightarrow> ZeroExtend__0 w N = return (ucast (w :: 'a::len word) :: 'b::len word)\"\n  \"\\<And>N w. LENGTH('c) \\<le> LENGTH('d) \\<Longrightarrow> ZeroExtend__1 N w = return (ucast (w :: 'c::len word) :: 'd::len word)\"\n  by (auto simp: ZeroExtend__1_def ZeroExtend__0_def)\n\nlemma ZeroExtend__1_64_64_return: \"ZeroExtend__1 64 (w :: 64 word) = return w\"\n  by auto\n\nlemma undefined_bitvector_simp[simp]: \"undefined_bitvector n = return 0\"\n  by (auto simp add: undefined_bitvector_def simp del: repeat.simps)\n\nlemma hex_slice_13000000[simp]: \"hex_slice ''0x13000000'' 52 0 = return (0x13000000 :: 52 word)\"\n  by (auto simp: hex_slice_def hexstring_to_bools_def hexchar_to_bool_list_def ext_list_def maybe_fail_def\n                 subrange_list_def subrange_list_dec_def subrange_list_inc_def split_at_def)\n*)\nDefinition aligned {m} (w : mword m) (n : Z) : Prop :=\n  exists x, x * n = projT1 (uint w).\n(*\nLemma aligned_8_mask_3 :\n  aligned w 8 -> wand w (mask 3) = 0.\n  using and_mask_dvd[where n = 3]\n  by (auto simp: aligned_def)\n\nlemma aligned8_OR_distrib: \"aligned (x OR y) 8 \\<longleftrightarrow> aligned x 8 \\<and> aligned y 8\"\n  by (auto simp: aligned_8_mask_3 word_bool_alg.conj_disj_distrib2)\n\nlemma aligned8_ucast:\n  fixes a :: \"'a::len word\"\n  defines \"b \\<equiv> ucast a :: 'b::len word\"\n  assumes b: \"3 \\<le> LENGTH('b)\"\n  shows \"aligned b 8 \\<longleftrightarrow> aligned a 8\"\n  using b test_bit_size[of b] unfolding b_def\n  by (auto simp: aligned_8_mask_3 word_and_mask_0_iff_not_testbits nth_ucast)\n\nlemma aligned8_shiftl_3: \"i \\<ge> 3 \\<Longrightarrow> aligned (x << i) 8\"\n  by (auto simp: aligned_8_mask_3 word_and_mask_0_iff_not_testbits nth_shiftl)\n*)\nLemma mword_elim (P : forall n, mword n -> Prop) :\n  (forall n (w : mword (Z.of_nat n)), P (Z.of_nat n) w) ->\n  forall n w, P n w.\n\nintros H n w.\nspecialize (ArithFact_mword _ w).\nintros [GE]. apply Z_geb_ge in GE.  apply Z.ge_le in GE.\nrevert w.\nrewrite <- (Z2Nat.id n GE).\napply H.\nQed.\n\nLemma wordToN_eq_dep m n w v :\n  EqdepFacts.eq_dep nat word m w n v ->\n  wordToN w = wordToN v.\nintros [].\nreflexivity.\nQed.\n\nLemma uint_concat_vec m n (a : mword m) (b : mword n) :\n  uint_plain (concat_vec a b) = uint_plain b + 2 ^ n * uint_plain a.\nunfold uint_plain, concat_vec.\nreplace (2 ^ n) with (Z.of_N (2 ^ Z.to_N n)). 2: {\n  rewrite N2Z.inj_pow.\n  rewrite Z2N.id.\n  reflexivity.\n  apply ArithFact_mword in b.\n  prepare_for_solver.\n  assumption.\n}\nrewrite <- N2Z.inj_mul.\nrewrite <- N2Z.inj_add.\nf_equal.\nreplace (2 ^ Z.to_N n)%N with (Npow2 (Z.to_nat n)). 2: {\n  rewrite <- Z_nat_N, Npow2_pow.\n  reflexivity.\n}\nrewrite <- wordToN_combine.\napply wordToN_eq_dep.\neapply EqdepFacts.eq_dep_trans.\napply Mword.get_cast_to_mword.\nconstructor.\nQed.\n\nRequire Import Lia Psatz.\n\nLemma aligned8_word_cat m n (a : mword m) (b : mword n) :\n  3 <= n ->\n  aligned (concat_vec a b) 8 <-> aligned b 8.\napply mword_elim with (n := m) (w := a).\napply mword_elim with (n := n) (w := b).\nclear.\nintros m w n v LE.\nunfold aligned.\nsimpl (projT1 _).\nsplit.\n* intros [x EQ].\n  rewrite uint_concat_vec in EQ.\n  exists (x - 2 ^ (Z.of_nat m - 3) * uint_plain v).\n  rewrite Z.mul_sub_distr_r.\n  change 8 with (2 ^ 3) at 2.\n  rewrite <- Z.mul_assoc.\n  rewrite (Z.mul_comm (uint_plain v) (2 ^ 3)).\n  rewrite Z.mul_assoc.\n  rewrite <- Z.pow_add_r.\n  + rewrite Z.sub_add.\n    omega.\n  + omega.\n  + omega.\n* intros [x EQ].\n  rewrite uint_concat_vec.\n  rewrite <- EQ.\n  rewrite <- Z.sub_add with (n := 3) (m := Z.of_nat m).\n  exists (x + 2 ^ (Z.of_nat m - 3) * uint_plain v).\n  rewrite Z.pow_add_r.\n  + rewrite Z.mul_add_distr_r.\n    change (2^3) with 8.\n    rewrite <- Z.mul_assoc.\n    rewrite (Z.mul_comm (uint_plain v) 8).\n    rewrite Z.mul_assoc.\n    reflexivity.\n  + omega.\n  + omega.\nQed.\n(*\nlemma slice_zeros_concat_slice_and_mask[simp]:\n  fixes xs :: \"'a::len word\"\n  shows \"slice_zeros_concat outlen xs i l l' = (Word.slice (nat i) xs AND mask (nat l)) << nat l'\"\nproof -\n  have \"n - nat l' < LENGTH('a) \\<and> n + nat i - nat l' < LENGTH('a)\"\n    if \"xs !! (n + nat i - nat l')\" for n\n    using that by (auto dest: test_bit_size[of xs])\n  then show ?thesis\n    unfolding slice_zeros_concat_def slice_mask_mask\n    by (intro word_eqI) (auto simp: ucast_shiftr word_ao_nth nth_shiftl nth_slice)\nqed\n\nlemmas aligned8_simps = aligned8_OR_distrib aligned8_shiftl_3 aligned8_word_cat aligned8_ucast\n\nlemma place_slice_grainsize:\n  assumes \"grainsize \\<ge> 0\"\n  shows \"(place_slice 52 (w :: 64 word) grainsize (48 - grainsize) grainsize :: 52 word) =\n         word_cat (0 :: 4 word) ((Word.slice (nat grainsize) w << nat grainsize) :: 48 word)\"\n  using assms\n  by (intro word_eqI)\n     (auto simp: place_slice_def slice_mask_mask nth_shiftl nth_shiftr nth_slice word_ao_nth nth_ucast)\n\nlemma set_slice_of_bl_drop_take:\n  fixes out :: \"'a::len word\" and bs :: \"bool list\"\n  (*defines \"v \\<equiv> of_bl bs :: 'b::len word\"*)\n  assumes \"n \\<ge> 0\" and \"slice_len > 0\" and \"n + slice_len \\<le> int LENGTH('a)\" (*and \"length bs = LENGTH('b)\"*)\n  shows \"set_slice out_len slice_len (out :: 'a::len word) n v =\n           of_bl (take (LENGTH('a) - nat n - nat slice_len) (to_bl out) @\n                  to_bl v @\n                  drop (LENGTH('a) - nat n) (to_bl out))\"\n  using assms unfolding set_slice_def\n  by (auto simp: update_subrange_vec_dec_update_subrange_list_dec update_subrange_list_dec_drop_take nat_add_distrib)\n\nlemma NOT_of_bl[simp]:\n  fixes bs :: \"bool list\"\n  defines \"w \\<equiv> of_bl bs :: 'a::len word\"\n  assumes \"length bs = LENGTH('a)\"\n  shows \"NOT w = of_bl (map Not bs)\"\n  using assms by (intro word_eqI) (auto simp: word_ops_nth_size test_bit_of_bl rev_map)\n\nlemma of_bl_AND_of_bl:\n  assumes \"length l = length r\"\n  shows \"(of_bl l) AND (of_bl r) = of_bl (map2 (\\<and>) l r)\"\n  using assms\n  by (intro word_eqI) (auto simp: word_ops_nth_size test_bit_of_bl map2_def rev_map zip_rev[symmetric])\n\nlemma True_OR_1word_absorb: \"1 OR (w :: 1 word) = 1\"\n  by (intro word_eqI) (auto simp: word_ao_nth)\n\nlemma to_bl_1_1word: \"to_bl (1 :: 1 word) = [True]\"\n  by eval\n\nlemma of_bl_test_bit_1word[simp]: \"of_bl [w !! 0] = (w :: 1 word)\"\n  by (intro word_eqI) (auto simp: test_bit_of_bl)\n\nlemma all_bool_neq_or_iff: \"(\\<forall>b. x = (\\<not>b) \\<or> P b) = P x\"\n  by (cases x) (auto simp: all_bool_eq)\n\nlemma arg_cong5:\n  assumes \"a = a'\" and \"b = b'\" and \"c = c'\" and \"d = d'\" and \"e = e'\"\n  shows \"f a b c d e = f a' b' c' d' e'\"\n  using assms by auto\n\nlemma Suc_Suc_0_eq_2: \"Suc (Suc 0) = 2\"\n  by auto\n\nlemma nth_rev_drop: \"i < length xs - n \\<Longrightarrow> rev (drop n xs) ! i = rev xs ! i\"\n  by (auto simp: rev_drop)\n\nlemma nth_rev_to_bl:\n  fixes w :: \"'a::len word\"\n  assumes \"i < LENGTH('a)\"\n  shows \"rev (to_bl w) ! i = w !! i\"\n  using assms by (auto simp: test_bit_bl)\n\nlemma Let_const[simp]: \"(let x = y in f) = f\"\n  by auto\n\nlemma word_slice_if_distrib: \"(Word.slice n (if c then x else y) = z) \\<longleftrightarrow> (if c then Word.slice n x = z else Word.slice n y = z)\"\n  by auto\n\nlemma [simp]: \"(if c then False else x) \\<longleftrightarrow> (\\<not>c \\<and> x)\"\n  by auto\n\nlemma word4_and3_exhaust:\n  fixes x :: \"4 word\"\n  shows \"x AND 3 = 0 \\<longrightarrow> x = 0 \\<or> x = 4 \\<or> x = 8 \\<or> x = 12\"\n  by (cases x rule: exhaustive_4_word) auto\n\nlemma word4_and3_exhaust':\n  fixes x :: \"4 word\"\n  assumes \"x AND 3 = 0\" and \"x \\<noteq> 0\" and \"x \\<noteq> 4\" and \"x \\<noteq> 8\"\n  shows \"x = 12\"\n  using assms by (cases x rule: exhaustive_4_word) auto\n\nlemma [simp]:\n  \"bitU_of_bool b = B0 \\<longleftrightarrow> \\<not>b\"\n  \"bitU_of_bool b = B1 \\<longleftrightarrow> b\"\n  by (auto simp: bitU_of_bool_def)\n\nlemma word1_OR_of_bl_disj[simp]:\n  fixes w :: \"1 word\"\n  shows \"w OR of_bl [b] = of_bl [w !! 0 \\<or> b]\" and \"of_bl [b] OR w = of_bl [b \\<or> w !! 0]\"\n  by (intro word_eqI; auto simp: word_ao_nth test_bit_of_bl)+\n\nlemma nat_lt_2_cases:\n  fixes n :: nat\n  assumes \"n < 2\" and \"P 0\" and \"P 1\"\n  shows \"P n\"\n  using assms by (cases n) auto\n\nlemma word2_OR_of_bl_disj[simp]:\n  fixes w :: \"2 word\"\n  shows \"w OR of_bl [b1, b0] = of_bl [w !! 1 \\<or> b1, w !! 0 \\<or> b0]\"\n    and \"of_bl [b1, b0] OR w = of_bl [b1 \\<or> w !! 1, b0 \\<or> w !! 0]\"\n  by (intro word_eqI; auto elim!: nat_lt_2_cases simp: word_ao_nth test_bit_of_bl)+\n\nlemma word2_of_bl_test_bits_eq[simp]:\n  \"of_bl [w !! Suc 0, w !! 0] = (w :: 2 word)\"\n  by (intro word_eqI; auto elim!: nat_lt_2_cases simp: test_bit_of_bl)\n\nlemma set_slice_2_1_of_bl[simp]:\n  \"set_slice 2 1 (out :: 2 word) 1 (v :: 1 word) = of_bl [v !! 0, out !! 0]\"\n  \"set_slice 2 1 (out :: 2 word) 0 (v :: 1 word) = of_bl [out !! 1, v !! 0]\"\n  by (intro word_eqI;\n      auto simp: set_slice_def update_subrange_vec_dec_update_subrange_list_dec\n                 update_subrange_list_dec_drop_take test_bit_of_bl nth_rev nth_append to_bl_nth\n                 elim!: nat_lt_2_cases)+\n\nlemma case_prod_elims:\n  \"\\<And>Q P z thesis. Q (case z of (a, b, c, d, e, f, g) \\<Rightarrow> P a b c d e f g) \\<Longrightarrow> (\\<And>a b c d e f g. z = (a, b, c, d, e, f, g) \\<Longrightarrow> Q (P a b c d e f g) \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\"\n  \"\\<And>Q P z thesis. Q (case z of (a, b, c, d, e, f) \\<Rightarrow> P a b c d e f) \\<Longrightarrow> (\\<And>a b c d e f. z = (a, b, c, d, e, f) \\<Longrightarrow> Q (P a b c d e f) \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\"\n  \"\\<And>Q P z thesis. Q (case z of (a, b, c, d, e) \\<Rightarrow> P a b c d e) \\<Longrightarrow> (\\<And>a b c d e. z = (a, b, c, d, e) \\<Longrightarrow> Q (P a b c d e) \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\"\n  \"\\<And>Q P z thesis. Q (case z of (a, b, c, d) \\<Rightarrow> P a b c d) \\<Longrightarrow> (\\<And>a b c d. z = (a, b, c, d) \\<Longrightarrow> Q (P a b c d) \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\"\n  \"\\<And>Q P z thesis. Q (case z of (a, b, c) \\<Rightarrow> P a b c) \\<Longrightarrow> (\\<And>a b c. z = (a, b, c) \\<Longrightarrow> Q (P a b c) \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\"\n  \"\\<And>Q P z thesis. Q (case z of (a, b) \\<Rightarrow> P a b) \\<Longrightarrow> (\\<And>a b. z = (a, b) \\<Longrightarrow> Q (P a b) \\<Longrightarrow> thesis) \\<Longrightarrow> thesis\"\n  by auto\n\nlemmas Run_case_prodE = case_prod_elims[where Q = \"\\<lambda>c. Run c t a\" for t a]\n\nlemma set_slice_set_bit[simp]:\n  assumes \"nat i < LENGTH('a)\"\n  shows \"set_slice len 1 (w :: 'a::len word) i (b :: 1 word) = set_bit w (nat i) (b !! 0)\"\n  using assms\n  by (intro word_eqI)\n     (auto simp: set_slice_def test_bit_set_gen update_subrange_vec_dec_def\n                word_update_def Let_def test_bit_of_bl nth_append nth_rev to_bl_nth)\n\nlemma slice_set_bit_below:\n  shows \"m > n \\<Longrightarrow> Word.slice m (set_bit w n x) = Word.slice m w\"\n  by (intro word_eqI) (auto simp: nth_slice test_bit_set_gen)\n\nlemma slice_set_bit_above:\n  fixes w :: \"'a::len word\" and m :: nat\n  defines \"w' \\<equiv> Word.slice m w :: 'b::len word\"\n  assumes \"m + LENGTH('b) < n\"\n  shows \"Word.slice m (set_bit w n x) = w'\"\n  using assms by (intro word_eqI) (auto simp: nth_slice test_bit_set_gen)\n\nlemma set_bit_3_word:\n  fixes w :: \"3 word\"\n  shows \"set_bit w 0 x = of_bl [w !! 2, w !! (Suc 0), x]\"\n        \"set_bit w (Suc 0) x = of_bl [w !! 2, x, w !! 0]\"\n        \"set_bit w 2 x = of_bl [x, w !! (Suc 0), w !! 0]\"\n  by (cases w rule: exhaustive_3_word; cases x; auto)+\n\nlemma case_None_False_exists_Some:\n  \"(case x of None \\<Rightarrow> False | Some y \\<Rightarrow> P y) \\<longleftrightarrow> (\\<exists>y. Some y = x \\<and> P y)\"\n  by (auto split: option.splits)\n\nlemma case_None_Not_exists_Some:\n  \"\\<not>P f1 \\<Longrightarrow> (P (case x of None \\<Rightarrow> f1 | Some y \\<Rightarrow> f2 y)) = (\\<exists>y. Some y = x \\<and> P (f2 y))\"\n  by (auto split: option.splits)\n\nlemma Some_eq_if_Some_None_iff_eq:\n  \"(Some x = (if c then Some y else None)) \\<longleftrightarrow> (c \\<and> x = y)\"\n  by auto\n\nlemma Align__1_8_iff_aligned_8[simp]: \"(w = Align__1 w 8) \\<longleftrightarrow> aligned (w :: 52 word) 8\"\nproof\n  assume \"w = Align__1 w 8\"\n  then have w: \"w = word_of_int (8 * (uint w div 8))\"\n    by (auto simp: Align__1_def Align__0_def of_bl_bin_word_of_int)\n  have 8: \"(8 :: int) dvd 2 ^ 52\" by eval\n  show \"aligned w 8\"\n    using dvd_mod_iff[OF 8]\n    by (subst w) (auto simp: aligned_def uint_word_of_int)\nnext\n  assume \"aligned w 8\"\n  then show \"w = Align__1 w 8\"\n    by (auto simp: Align__1_def Align__0_def aligned_def of_bl_bin_word_of_int)\nqed\n\nend\n*)\n", "meta": {"author": "rems-project", "repo": "armv8a-address-translation-coq", "sha": "66c923c5fb0b9539db28060a31e94853126ad349", "save_path": "github-repos/coq/rems-project-armv8a-address-translation-coq", "path": "github-repos/coq/rems-project-armv8a-address-translation-coq/armv8a-address-translation-coq-66c923c5fb0b9539db28060a31e94853126ad349/AArch64_Trivia.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20926954850482773}}
{"text": "(*\n\n  Copyright 2014 Cornell University\n  Copyright 2015 Cornell University\n  Copyright 2016 Cornell University\n\n  This file is part of VPrl (the Verified Nuprl project).\n\n  VPrl is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  VPrl is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with VPrl.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Websites: http://nuprl.org/html/verification/\n            http://nuprl.org/html/Nuprl2Coq\n            https://github.com/vrahli/NuprlInCoq\n\n  Authors: Abhishek Anand & Vincent Rahli\n\n *)\n\n\nRequire Import approx_star0.\n\n\nLemma isprog_vars_iff_isprogram_bt {o} :\n  forall vs (t : @NTerm o),\n    isprog_vars vs t <=> isprogram_bt (bterm vs t).\nProof.\n  introv.\n  rw @isprog_vars_eq.\n  unfold isprogram_bt; simpl.\n  rw @bt_wf_iff.\n  rw @closed_bt_bterm; sp.\nQed.\n\nLemma isprog_vars_implies_isprogram_bt {o} :\n  forall vs (t : @NTerm o),\n    isprog_vars vs t -> isprogram_bt (bterm vs t).\nProof.\n  introv isp.\n  apply isprog_vars_iff_isprogram_bt; auto.\nQed.\nHint Resolve isprog_vars_implies_isprogram_bt : slow.\n\nLemma alpha_eq_bterm_implies_eq_length {o} :\n  forall vs1 vs2 (t1 t2 : @NTerm o),\n    alpha_eq_bterm (bterm vs1 t1) (bterm vs2 t2)\n    -> length vs1 = length vs2.\nProof.\n  introv aeq.\n  inversion aeq; subst; auto.\nQed.\n\nLemma isprogram_lsubst_aux_implies {o} :\n  forall (t : @NTerm o) sub,\n    disjoint_bv_sub t sub\n    -> isprogram (lsubst_aux t sub)\n    -> isprogram_bt (bterm (dom_sub sub) t).\nProof.\n  introv d isp.\n  apply isprog_vars_iff_isprogram_bt.\n  apply isprog_vars_eq.\n  destruct isp as [c w].\n  apply lsubst_aux_nt_wf in w; dands; auto.\n  rw subvars_prop; introv i.\n  unfold closed in c.\n  rw <- null_iff_nil in c.\n  unfold null in c.\n  destruct (in_deq _ deq_nvar x (dom_sub sub)) as [j|j]; auto.\n  provefalse.\n  pose proof (c x) as h; destruct h.\n  pose proof (eqvars_free_vars_disjoint_aux2 t sub d) as h; auto.\n  rw eqvars_prop in h; apply h; clear h.\n  rw in_app_iff; rw in_remove_nvars; sp.\nQed.\n\nLemma isprogram_lsubst_implies {o} :\n  forall (t : @NTerm o) sub,\n    isprogram (lsubst t sub)\n    -> isprogram_bt (bterm (dom_sub sub) t).\nProof.\n  introv isp.\n  pose proof (unfold_lsubst sub t) as h; exrepnd; rw h0 in isp.\n  apply isprogram_lsubst_aux_implies in isp; auto.\n  - allunfold @isprogram_bt.\n    allunfold @closed_bt; allsimpl.\n    applydup @alphaeq_preserves_free_vars in h1 as fv.\n    rw fv; repnd; dands; auto.\n    allrw @bt_wf_iff.\n    apply alphaeq_preserves_wf in h1; apply h1; auto.\n  - unfold disjoint_bv_sub, sub_range_sat; introv i j k.\n    apply h2 in k; destruct k.\n    apply in_sub_free_vars_iff.\n    exists v t0; dands; auto.\nQed.\n\nLemma isprogram_subst_implies {o} :\n    forall (t : @NTerm o) (v : NVar) (a : NTerm),\n      isprogram (subst t v a)\n      -> isprogram_bt (bterm [v] t).\nProof.\n  introv isp.\n  apply isprogram_lsubst_implies in isp; allsimpl; auto.\nQed.\n\nDefinition get_op {o} (t : @NTerm o) : Opid :=\n  match t with\n    | vterm _ => Exc\n    | sterm _ => Exc\n    | oterm op _ => op\n  end.\n\nInductive same_value_like {o} lib : @NTerm o -> @NTerm o -> Type :=\n| svl_c : forall c bs1 bs2, same_value_like lib (oterm (Can c) bs1) (oterm (Can c) bs2)\n| svl_e : forall bs1 bs2, same_value_like lib (oterm Exc bs1) (oterm Exc bs2)\n| svl_s :\n    forall f1 f2,\n      (*(forall n, alpha_eq (f1 n) (f2 n))*)\n      (forall n, approx_star lib (f1 n) (f2 n))\n      -> same_value_like lib (sterm f1) (sterm f2).\nHint Constructors same_value_like.\n\nLemma approx_starbts_nil {o} :\n  forall lib (op : @Opid o), approx_starbts lib op [] [].\nProof.\n  introv; unfold approx_starbts, lblift_sub; simpl; dands; tcsp.\nQed.\nHint Resolve approx_starbts_nil : slow.\n\nLemma howe_lemma2_implies_same_value_like {o} :\n  forall lib (t u : @NTerm o),\n    isprogram t\n    -> isprogram u\n    -> isvalue_like t\n    -> approx_star lib t u\n    -> {v : NTerm\n        & same_value_like lib t v\n        # approx_starbts lib (get_op t) (get_bterms t) (get_bterms v)\n        # reduces_to lib u v}.\nProof.\n  introv ispt ispu isv ap.\n  unfold isvalue_like in isv; repndors.\n  - apply iscan_implies in isv; repndors; exrepnd; subst.\n\n    + pose proof (howe_lemma2 lib c bterms u) as h; simpl in h.\n      repeat (autodimp h hyp).\n      exrepnd.\n      exists (oterm (Can c) lbt'); dands; eauto.\n      unfold computes_to_value in h0; repnd; auto.\n\n    + apply howe_lemma2_seq in ap; auto; exrepnd.\n      exists (sterm f'); dands; simpl; eauto 3 with slow; tcsp.\n\n  - apply isexc_implies2 in isv; exrepnd; subst.\n    applydup @isprogram_exception_implies in ispt; exrepnd; subst.\n    pose proof (howe_lemma2_exc lib a t u) as h; simpl in h.\n    repeat (autodimp h hyp).\n    exrepnd.\n    exists (oterm Exc [bterm [] a', bterm [] e']); simpl; dands; auto.\n    unfold approx_starbts, lblift_sub; simpl; dands; auto.\n    introv k; repeat (destruct n; cpx).\n    + unfold selectbt; simpl; eauto with slow.\n    + unfold selectbt; simpl; eauto with slow.\nQed.\n\nLemma same_value_like_alpha_eq_r {o} :\n  forall lib (t u v : @NTerm o),\n    same_value_like lib t u\n    -> alpha_eq u v\n    -> same_value_like lib t v.\nProof.\n  introv svl aeq.\n  inversion svl as [| |? ? imp1]; clear svl; subst;\n  inversion aeq as [|? ? imp2|]; clear aeq; subst; auto.\n  constructor; introv; eauto 3 with slow.\nQed.\n\nLemma same_value_like_alpha_eq_l {o} :\n  forall lib (t u v : @NTerm o),\n    same_value_like lib t u\n    -> alpha_eq t v\n    -> same_value_like lib v u.\nProof.\n  introv svl aeq.\n  inversion svl as [| |? ? imp1]; clear svl; subst;\n  inversion aeq as [|? ? imp2|]; clear aeq; subst; auto.\n  constructor; introv; eauto 3 with slow.\nQed.\n\nLemma approx_starbts_get_bterms_alpha_eq {o} :\n  forall lib op (t u v : @NTerm o),\n    approx_starbts lib op (get_bterms t) (get_bterms u)\n    -> alpha_eq u v\n    -> approx_starbts lib op (get_bterms t) (get_bterms v).\nProof.\n  introv ap aeq.\n  destruct t as [v1|f1|op1 bs1]; destruct u as [v2|f2|op2 bs2]; allsimpl; auto;\n  try (complete (inversion aeq; subst; allsimpl; tcsp)).\n  - unfold approx_starbts, lblift_sub in ap; allsimpl; repnd; cpx.\n    inversion aeq; subst; allsimpl; cpx; auto.\n    unfold approx_starbts, lblift_sub; simpl; sp.\n  - unfold approx_starbts, lblift_sub in ap; allsimpl; repnd; cpx.\n    inversion aeq; subst; allsimpl; cpx; auto.\n    unfold approx_starbts, lblift_sub; simpl; sp.\n  - inversion aeq as [|?|? ? ? len imp]; subst; simpl.\n    allunfold @approx_starbts.\n    allunfold @lblift_sub; repnd; dands; auto; try omega.\n    introv i.\n    pose proof (ap n) as h1; autodimp h1 hyp.\n    pose proof (imp n) as h2; autodimp h2 hyp; try omega.\n    eapply approx_star_bterm_alpha_fun_r; eauto.\nQed.\n\n(*\nLemma approx_star_congruence_same_value_like {o} :\n  forall lib (t u : @NTerm o),\n    isprogram t\n    -> isprogram u\n    -> same_value_like t u\n    -> approx_starbts lib (get_op t) (get_bterms t) (get_bterms u)\n    -> approx_star lib t u.\nProof.\n  introv ispt ispu svl ap.\n  destruct t as [v1|f1|op1 bs1]; destruct u as [v2|f2|op2 bs2]; allsimpl;\n  try (complete (apply isprogram_vterm in ispt; sp));\n  try (complete (apply isprogram_vterm in ispu; sp));\n  try (complete (inversion svl)).\n  - apply (apss _ _ _ f2); eauto 3 with slow.\n  - inversion svl; subst; apply approx_star_congruence3; auto.\nQed.\n*)\n\nLemma closed_axiom {o} :\n  @closed o mk_axiom.\nProof. sp. Qed.\nHint Resolve closed_axiom : slow.\n\nLemma alpha_eq_subst_utoken_not_in_implies2 {o} :\n  forall (t1 t2 : @NTerm o) v a,\n    !LIn a (get_utokens t1)\n    -> !LIn a (get_utokens t2)\n    -> alpha_eq (subst t1 v (mk_utoken a)) (subst t2 v (mk_utoken a))\n    -> alpha_eq t1 t2.\nProof.\n  introv ni1 ni2 aeq.\n  pose proof (change_bvars_alpha_wspec [v] t1) as k1.\n  pose proof (change_bvars_alpha_wspec [v] t2) as k2.\n  exrepnd.\n  allrw disjoint_singleton_l.\n  pose proof (lsubst_alpha_congr2 ntcv0 t1 [(v,mk_utoken a)]) as p1.\n  pose proof (lsubst_alpha_congr2 ntcv t2 [(v,mk_utoken a)]) as p2.\n  autodimp p1 hyp; autodimp p2 hyp; eauto 3 with slow.\n  allrw @fold_subst.\n  assert (alpha_eq (subst ntcv0 v (mk_utoken a)) (subst ntcv v (mk_utoken a))) as h' by eauto with slow.\n  apply alpha_eq_subst_utoken_not_in_implies in h'; eauto with slow.\n  { intro j; destruct ni1; apply alphaeq_preserves_utokens in k3; rw k3; auto. }\n  { intro j; destruct ni2; apply alphaeq_preserves_utokens in k0; rw k0; auto. }\nQed.\n\nLemma isprogram_pushdown_fresh {o} :\n  forall v (t : @NTerm o),\n    isprogram (pushdown_fresh v t) <=> isprog_vars [v] t.\nProof.\n  introv; split; intro k.\n  - destruct k as [c w].\n    rw @isprog_vars_eq.\n    apply nt_wf_pushdown_fresh in w; dands; auto.\n    unfold closed in c.\n    rw @free_vars_pushdown_fresh in c.\n    rw subvars_prop; introv i.\n    rw <- null_iff_nil in c.\n    rw null_remove_nvars in c; apply c in i; sp.\n  - rw @isprog_vars_eq in k; repnd.\n    split; allrw @nt_wf_pushdown_fresh; auto.\n    unfold closed; rw @free_vars_pushdown_fresh.\n    rw <- null_iff_nil.\n    rw null_remove_nvars; introv i.\n    rw subvars_prop in k0; apply k0; auto.\nQed.\n\nLemma same_value_like_implies_same_op {o} :\n  forall lib op1 op2 (bs1 bs2 : list (@BTerm o)),\n    same_value_like lib (oterm op1 bs1) (oterm op2 bs2)\n    -> op1 = op2.\nProof.\n  introv s; inversion s; auto.\nQed.\n\nLemma fresh_id_approx_any {o} :\n  forall lib (t : @NTerm o) x,\n    isprogram t\n    -> approx lib (mk_fresh x (mk_var x)) t.\nProof.\n  introv Hpr.\n  apply approx_assume_hasvalue; auto.\n  { apply isprogram_fresh; apply isprog_vars_var. }\n\n  introv Hv.\n  unfold hasvalue_like in Hv; exrepnd.\n  apply (not_fresh_id_reduces_to_is_value_like _ _ x) in Hv1; tcsp.\nQed.\n\nLemma change_bvars_alpha_norep {o} :\n  forall (t : @NTerm o) (lv : list NVar),\n    {u : NTerm\n     $ disjoint lv (bound_vars u)\n     # alpha_eq t u\n     # no_repeats (bound_vars u)}.\nProof.\n  nterm_ind1s t as [v|f ind|op bs ind] Case; introv.\n\n  - Case \"vterm\".\n    exists (@mk_var o v); simpl; dands; auto.\n\n  - Case \"sterm\".\n    exists (sterm f); simpl; dands; eauto 3 with slow.\n\n  - Case \"oterm\".\n\n    assert (forall lv, {bs' : list BTerm\n            $ disjoint lv (bound_vars_bterms bs')\n            # alpha_eq_bterms bs bs'\n            # no_repeats (bound_vars_bterms bs') }) as ibs.\n    { clear lv; induction bs; introv; allsimpl.\n      - exists ([] : list (@BTerm o)); simpl; dands; eauto with slow.\n      - autodimp IHbs hyp.\n        { introv i s; eapply ind; eauto. }\n        pose proof (IHbs lv) as ibs; clear IHbs; exrepnd.\n        destruct a as [l t].\n\n        pose proof (fresh_vars (length l)\n                               (lv ++ l\n                                   ++ all_vars t\n                                   ++ bound_vars_bterms bs'))\n             as fvs; exrepnd.\n        allrw disjoint_app_r; exrepnd.\n\n        pose proof (ind t (lsubst t (var_ren l lvn)) l) as ih; clear ind; repeat (autodimp ih hyp).\n        { rw @lsubst_allvars_preserves_osize2; eauto 3 with slow. }\n\n        pose proof (ih (lv ++ lvn ++ bound_vars_bterms bs')) as ht; clear ih.\n        exrepnd.\n        allrw disjoint_app_l; repnd.\n\n        exists (bterm lvn u :: bs'); simpl.\n        allrw no_repeats_app.\n        allrw disjoint_app_l; allrw disjoint_app_r.\n        dands; eauto 3 with slow.\n        apply alpha_eq_bterms_cons; dands; auto.\n        eapply alpha_eq_bterm_trans;[|apply alpha_eq_bterm_congr;exact ht2].\n        apply alpha_bterm_change; auto.\n        allrw disjoint_app_l; dands; eauto with slow.\n    }\n\n    pose proof (ibs lv) as h; clear ibs; exrepnd.\n    exists (oterm op bs'); simpl; dands; auto.\n    apply alpha_eq_oterm_combine; auto.\nQed.\n\nLemma blift_sub_diff {o} :\n  forall vs lib op (b1 b2 : @BTerm o),\n    blift_sub op (approx_star lib) b1 b2\n    -> {lv : list NVar\n        $ {nt1,nt2 : NTerm\n        $ (\n            (op <> NCan NFresh # approx_star lib nt1 nt2)\n            [+]\n            {sub : Sub\n             & op = NCan NFresh\n             # approx_star lib (lsubst nt1 sub) (lsubst nt2 sub)\n             # nrut_sub (get_utokens nt1 ++ get_utokens nt2) sub\n             # lv = dom_sub sub}\n          )\n        # alpha_eq_bterm b1 (bterm lv nt1)\n        # alpha_eq_bterm b2 (bterm lv nt2)\n        # disjoint vs lv\n        # disjoint vs (bound_vars nt1)\n        # disjoint vs (bound_vars nt2)\n        # disjoint lv (bound_vars nt1)\n        # disjoint lv (bound_vars nt2)\n        # no_repeats lv\n        # no_repeats (bound_vars nt1)\n        # no_repeats (bound_vars nt2) }}.\nProof.\n  introv bl.\n  unfold blift_sub in bl; exrepnd.\n\n  pose proof (alpha_bterm_pair_change b1 b2 lv nt1 nt2 vs) as h.\n  repeat (autodimp h hyp); exrepnd.\n  allrw disjoint_app_r; allrw disjoint_app_l; repnd.\n\n  pose proof (change_bvars_alpha_norep nt1n (vs ++ lvn)) as ch1; exrepnd.\n  assert (alpha_eq nt1 u) as h2' by eauto with slow.\n  assert (alpha_eq_bterm b1 (bterm lvn (lsubst u (var_ren lv lvn)))) as h4'.\n  { eapply alpha_eq_bterm_trans;[exact h4|].\n    apply alpha_eq_bterm_congr.\n    apply lsubst_alpha_congr2; auto. }\n  allrw disjoint_app_l; repnd.\n  rename ch3 into h9'.\n  rename ch1 into h13'.\n  clear dependent nt1n.\n  rename h2' into h2; rename h4' into h4; rename h9' into h9; rename h13' into h13.\n  rename u into nt1n.\n\n  pose proof (change_bvars_alpha_norep nt2n (vs ++ lvn)) as ch'1; exrepnd.\n  assert (alpha_eq nt2 u) as h3' by eauto with slow.\n  assert (alpha_eq_bterm b2 (bterm lvn (lsubst u (var_ren lv lvn)))) as h5'.\n  { eapply alpha_eq_bterm_trans;[exact h5|].\n    apply alpha_eq_bterm_congr.\n    apply lsubst_alpha_congr2; auto. }\n  allrw disjoint_app_l; repnd.\n  rename ch'3 into h0'.\n  rename ch'1 into h7'.\n  clear dependent nt2n.\n  rename h3' into h3; rename h5' into h5; rename h7' into h7; rename h0' into h0.\n  rename u into nt2n.\n\n  exists lvn (lsubst nt1n (var_ren lv lvn)) (lsubst nt2n (var_ren lv lvn)).\n  dands; eauto 3 with slow; try (complete (rw @boundvars_lsubst_vars; auto)).\n\n  repndors; exrepnd.\n\n  - left; dands; auto.\n    apply approx_star_lsubst_vars; eauto 3 with slow.\n\n  - right.\n    exists (combine lvn (range sub)); dands; auto.\n\n    + pose proof (lsubst_nest_same_alpha2 nt1n lv lvn (range sub)) as nest1.\n      allrw @length_dom; allrw @length_range.\n      repeat (autodimp nest1 hyp); try omega; eauto 3 with slow.\n      { subst; allrw @length_dom; auto. }\n      { apply alphaeq_preserves_free_vars in h2; rw <- h2.\n        apply disjoint_remove_nvars_weak_r; auto. }\n      eapply approx_star_alpha_fun_l;[|apply alpha_eq_sym; exact nest1].\n\n      pose proof (lsubst_nest_same_alpha2 nt2n lv lvn (range sub)) as nest2.\n      allrw @length_dom; allrw @length_range.\n      repeat (autodimp nest2 hyp); try omega; eauto 3 with slow.\n      { subst; allrw @length_dom; auto. }\n      { apply alphaeq_preserves_free_vars in h3; rw <- h3.\n        apply disjoint_remove_nvars_weak_r; auto. }\n      eapply approx_star_alpha_fun_r;[|apply alpha_eq_sym; exact nest2].\n\n      subst.\n      rw <- @sub_eta; auto.\n\n      apply (lsubst_alpha_congr2 _ _ sub) in h2.\n      apply (lsubst_alpha_congr2 _ _ sub) in h3.\n      eauto with slow.\n\n    + repeat (rw @get_utokens_lsubst_allvars; eauto with slow).\n      apply alphaeq_preserves_utokens in h2.\n      apply alphaeq_preserves_utokens in h3.\n      rw <- h2; rw <- h3.\n      eapply nrut_sub_change_sub_same_range;[|exact bl5].\n      rw @range_combine; auto.\n      rw @length_range; auto.\n      subst; allrw @length_dom; auto.\n\n    + rw @dom_sub_combine; auto.\n      rw @length_range; auto.\n      subst; allrw @length_dom; auto.\nQed.\n\nLemma bt_wf_mk_fresh_bterm_if {o} :\n  forall (b : @BTerm o) v,\n    bt_wf b\n    -> bt_wf (mk_fresh_bterm v b).\nProof.\n  introv wf.\n  destruct b as [l t]; allsimpl.\n  allrw @bt_wf_iff.\n  apply nt_wf_fresh; auto.\nQed.\n\nLemma alpha_eq_bterm_ren_1side {o} :\n  forall (t1 t2 : @NTerm o) l1 l2,\n    disjoint l1 (bound_vars t1)\n    -> disjoint l1 (bound_vars t2)\n    -> alpha_eq_bterm (bterm l1 t1) (bterm l2 t2)\n    -> alpha_eq_bterm (bterm l1 t1) (bterm l1 (lsubst t2 (var_ren l2 l1))).\nProof.\n  introv disj1 disj2 aeq.\n  inversion aeq as [? ? ? ? ? disj len1 len2 norep a]; subst.\n  apply (lsubst_alpha_congr2 _ _ (var_ren lv l1)) in a.\n  allrw disjoint_app_r; repnd.\n\n  pose proof (lsubst_nest_vars_same t1 l1 lv l1) as h1.\n  allrw disjoint_app_l.\n  repeat (autodimp h1 hyp); dands; eauto 3 with slow.\n  rw h1 in a.\n\n  pose proof (lsubst_nest_vars_same t2 l2 lv l1) as h2.\n  allrw disjoint_app_l.\n  repeat (autodimp h2 hyp); dands; try omega; eauto 3 with slow.\n  rw h2 in a.\n\n  pose proof (lsubst_trivial_alpha t1 l1) as h.\n  eauto with slow.\nQed.\n\nLemma alpha_eq_bterm_ren_1side2 {o} :\n  forall (t1 t2 : @NTerm o) l1 l2,\n    disjoint l1 (bound_vars t1)\n    -> disjoint l1 (bound_vars t2)\n    -> alpha_eq_bterm (bterm l1 t1) (bterm l2 t2)\n    -> alpha_eq t1 (lsubst t2 (var_ren l2 l1)).\nProof.\n  introv disj1 disj2 aeq.\n  inversion aeq as [? ? ? ? ? disj len1 len2 norep a]; subst.\n  apply (lsubst_alpha_congr2 _ _ (var_ren lv l1)) in a.\n  allrw disjoint_app_r; repnd.\n\n  pose proof (lsubst_nest_vars_same t1 l1 lv l1) as h1.\n  allrw disjoint_app_l.\n  repeat (autodimp h1 hyp); dands; eauto 3 with slow.\n  rw h1 in a.\n\n  pose proof (lsubst_nest_vars_same t2 l2 lv l1) as h2.\n  allrw disjoint_app_l.\n  repeat (autodimp h2 hyp); dands; try omega; eauto 3 with slow.\n  rw h2 in a.\n\n  pose proof (lsubst_trivial_alpha t1 l1) as h.\n  eauto with slow.\nQed.\n\nLemma alpha_eq_lsubst_aux_pull_out_token {o} :\n  forall (t : @NTerm o) l sub t',\n    disjoint (dom_sub sub) (bound_vars t)\n    -> disjoint (dom_sub sub) (bound_vars t')\n    -> disjoint (bound_vars t) (bound_vars t')\n    -> no_repeats (bound_vars t)\n    -> nrut_sub l sub\n    -> subset (get_utokens t') l\n    -> no_repeats (dom_sub sub)\n    -> wf_term t\n    -> alpha_eq t (lsubst_aux t' sub)\n    -> {u : NTerm $ t = lsubst_aux u sub # disjoint (get_utokens u) (get_utokens_sub sub)}.\nProof.\n  nterm_ind t as [x|f ind|op bs ind] Case;\n  introv disj1 disj2 disj3 norep nrut ss nrs wf aeq;\n  allsimpl; GC.\n\n  - Case \"vterm\".\n    destruct t' as [z|f|op' bs']; allsimpl;\n    try (complete (inversion aeq)).\n\n    remember (sub_find sub z) as sf; symmetry in Heqsf; destruct sf.\n\n    + apply sub_find_some in Heqsf.\n      eapply in_nrut_sub in Heqsf; eauto; exrepnd; subst; inversion aeq.\n    + inversion aeq; subst.\n      exists (@mk_var o z); simpl; boolvar; tcsp.\n      rw Heqsf; auto.\n\n  - Case \"sterm\".\n    exists (sterm f); simpl; dands; auto.\n\n  - Case \"oterm\".\n    destruct t' as [z|f|op' bs']; allsimpl; try (complete (inversion aeq)).\n\n    + remember (sub_find sub z) as sf; symmetry in Heqsf; destruct sf;\n      try (complete (inversion aeq)).\n\n      apply sub_find_some in Heqsf.\n      eapply in_nrut_sub in Heqsf; eauto; exrepnd; subst; inversion aeq; subst.\n      allsimpl; cpx; allsimpl; fold_terms.\n\n      pose proof (in_nrut_sub_or l a sub) as ora.\n      repeat (autodimp ora hyp); repndors; exrepnd.\n\n      { exists (@mk_var o v); simpl; allrw; dands; auto. }\n\n      { exists (mk_utoken a); simpl; auto.\n        rw disjoint_singleton_l; dands; auto. }\n\n    + allrw @alpha_eq_oterm_combine2; repnd; subst.\n      allrw map_length.\n\n      rw @wf_oterm_iff in wf; repnd.\n\n      assert {bs'' : list BTerm\n              & bs = lsubst_bterms_aux bs'' sub\n              # disjoint (get_utokens_bs bs'') (get_utokens_sub sub)} as hbs.\n      { clear wf0.\n        revert dependent bs'.\n        revert dependent bs.\n        induction bs as [|b bs]; introv ind disj1 norep wf disj2 disj3 ss len imp; allsimpl; cpx; GC.\n\n        - exists ([] : list (@BTerm o)); simpl; auto.\n\n        - destruct bs' as [|b' bs']; allsimpl; cpx.\n          allrw in_app_iff; allrw not_over_or; repnd.\n          allrw no_repeats_app; repnd.\n          allrw disjoint_app_r; allrw disjoint_app_l; repnd.\n          repeat (autodimp IHbs hyp).\n          { introv i j k; eapply ind; eauto. }\n          pose proof (IHbs bs') as ih; clear IHbs.\n          repeat (autodimp ih IHbs); exrepnd.\n          { allrw subset_app; repnd; dands; auto. }\n          pose proof (imp b (lsubst_bterm_aux b' sub)) as h.\n          repeat (autodimp h hyp).\n          destruct b as [l1 t1].\n          destruct b' as [l2 t2].\n          allsimpl; allrw in_app_iff; allrw not_over_or; repnd.\n          allrw disjoint_app_l; repnd.\n          allrw no_repeats_app; repnd.\n          allrw disjoint_app_r; allrw disjoint_app_l; repnd.\n          applydup @alpha_eq_bterm_lenbvars in h.\n\n          apply alpha_eq_bterm_ren_1side2 in h; auto;\n          [|introv i j; apply subset_bound_vars_lsubst_aux in j; allsimpl;\n            allrw in_app_iff; repndors; tcsp;\n            [apply disj8 in i; sp|];\n            rw (sub_bound_vars_nrut_sub (sub_filter sub l2) l) in j; allsimpl; tcsp;\n            complete (eauto with slow)].\n          pose proof (ind t1 l1) as k; clear ind; autodimp k hyp.\n\n          rw @lsubst_lsubst_aux in h;\n            [|rw <- @sub_free_vars_is_flat_map_free_vars_range;\n               rw @sub_free_vars_var_ren; auto;\n               introv i j; apply subset_bound_vars_lsubst_aux in i; allsimpl;\n               allrw in_app_iff; applydup disj8 in j; repndors; tcsp;\n               apply subset_sub_bound_vars_sub_filter in i;\n               erewrite sub_bound_vars_nrut_sub in i; eauto].\n\n          rw (sub_filter_disjoint1 sub) in h; eauto 3 with slow.\n\n          pose proof (simple_lsubst_aux_lsubst_aux_sub_disj\n                        t2 sub (var_ren l2 l1)) as e.\n          allsimpl; rw @sub_free_vars_var_ren in e; auto.\n          rw (sub_bound_vars_nrut_sub sub l) in e; eauto 3 with slow.\n          rw (sub_free_vars_nrut_sub sub l) in e; eauto 3 with slow.\n          rw @cl_lsubst_aux_sub_trivial in e; eauto 3 with slow.\n          repeat (autodimp e hyp); eauto with slow.\n          rw <-  e in h; clear e.\n\n          pose proof (k l sub (lsubst_aux t2 (sub_filter (var_ren l2 l1) (dom_sub sub))))\n            as ih; clear k.\n          repeat (autodimp ih hyp); eauto 3 with slow.\n          { introv i j; apply subset_bound_vars_lsubst_aux in j.\n            rw @sub_bound_vars_allvars_sub in j; eauto 3 with slow.\n            allrw app_nil_r; apply disj7 in i; sp. }\n          { introv i j; apply subset_bound_vars_lsubst_aux in j.\n            rw @sub_bound_vars_allvars_sub in j; eauto 3 with slow.\n            allrw app_nil_r; apply disj5 in i; sp. }\n          { allrw subset_app; repnd; rw @get_utokens_lsubst_aux_allvars; eauto 3 with slow. }\n          { pose proof (wf (bterm l1 t1)) as w; autodimp w hyp. }\n\n          exrepnd.\n          exists (bterm l1 u :: bs''); simpl.\n          allrw disjoint_app_l; dands; eauto 3 with slow.\n          f_equal; auto.\n          f_equal; auto.\n          rw (sub_filter_disjoint1 sub); eauto 3 with slow.\n      }\n\n      exrepnd.\n\n      remember (get_utok op') as guo; symmetry in Heqguo; destruct guo.\n\n      { apply get_utok_some in Heqguo; subst; allsimpl.\n        destruct bs''; allsimpl; cpx; GC; fold_terms.\n        allrw subset_cons_l; repnd; allsimpl.\n        exists (mk_utoken g); simpl; fold_terms; rw disjoint_singleton_l; dands; auto.\n        unfold nrut_sub in nrut; repnd.\n        apply nrut in ss0; sp.\n      }\n\n      { exists (oterm op' bs''); simpl; subst.\n        allrw subset_app; repnd.\n        allrw disjoint_app_l; dands; eauto 3 with slow.\n        unfold lsubst_bterms_aux; auto.\n        destruct op'; allsimpl; tcsp.\n        destruct c; allsimpl; tcsp.\n      }\nQed.\n\nLemma alpha_eq_subst_bterm_aux_pull_out_token {o} :\n  forall b v a l (t : @NTerm o),\n    !LIn v l\n    -> !LIn v (bound_vars t)\n    -> disjoint l (bound_vars t)\n    -> no_repeats (bound_vars t)\n    -> !LIn a (get_utokens_b b)\n    -> wf_term t\n    -> alpha_eq_bterm (subst_bterm_aux b v (mk_utoken a)) (bterm l t)\n    -> {u : NTerm & t = subst u v (mk_utoken a) # !LIn a (get_utokens u)}.\nProof.\n  introv ni1 ni2 disj1 norep niab wf aeq.\n\n  pose proof (ex_change_bvars_bterm_alpha (v :: l ++ bound_vars t) b) as ch; exrepnd.\n  allrw disjoint_cons_l; allrw disjoint_app_l; repnd.\n  pose proof (lsubst_aux_alphabt_congr_cl b bt' [(v,mk_utoken a)] [(v,mk_utoken a)]) as aeqb.\n  repeat (autodimp aeqb hyp); eauto with slow.\n  eapply alpha_eq_bterm_trans in aeq;[|apply alpha_eq_bterm_sym; exact aeqb].\n  assert (!LIn a (get_utokens_b bt')) as niabt'.\n  { apply alpha_eq_bterm_preserves_utokens in ch0; rw <- ch0; auto. }\n  clear dependent b; rename bt' into b.\n  rename ch3 into disj2; rename ch2 into disj3; rename ch1 into ni3; rename niabt' into niab.\n\n  destruct b as [l1 u1]; allsimpl.\n  allrw disjoint_app_r; repnd.\n  allunfold @subst_bterm_aux; allsimpl; boolvar.\n  - allrw @lsubst_aux_nil.\n    exists t.\n    applydup @alpha_eq_bterm_preserves_utokens in aeq as eu; allsimpl; rw <- eu.\n    apply alpha_eq_bterm_preserves_free_vars in aeq; allsimpl.\n    rw @cl_subst_trivial; eauto with slow.\n    introv i.\n    assert (LIn v (remove_nvars l (free_vars t))) as j.\n    { rw in_remove_nvars; sp. }\n    rw <- aeq in j.\n    rw in_remove_nvars in j; sp.\n  - (* change the l1 into l when inverting aeq *)\n    apply alpha_eq_bterm_sym in aeq.\n    applydup @alpha_eq_bterm_lenbvars in aeq.\n    apply alpha_eq_bterm_ren_1side2 in aeq; auto;\n    [|introv i j; apply subset_bound_vars_lsubst_aux in j; allsimpl;\n      allrw app_nil_r; apply disj2 in i; sp].\n    rw @lsubst_lsubst_aux in aeq;\n      [|rw <- @sub_free_vars_is_flat_map_free_vars_range;\n         rw @sub_free_vars_var_ren; auto;\n         introv i j; apply subset_bound_vars_lsubst_aux in i; allsimpl;\n         allrw app_nil_r; apply disj2 in j; sp].\n\n    pose proof (simple_lsubst_aux_lsubst_aux_sub_disj u1 [(v,mk_utoken a)] (var_ren l1 l)) as h.\n    allsimpl.\n    rw @sub_free_vars_var_ren in h; auto.\n    allrw disjoint_singleton_l; fold_terms.\n    repeat (autodimp h hyp); eauto 3 with slow.\n    rw <-  h in aeq; clear h.\n\n    pose proof (alpha_eq_lsubst_aux_pull_out_token\n                  t (get_utokens u1) [(v,mk_utoken a)]\n                  (lsubst_aux u1 (sub_filter (var_ren l1 l) [v]))) as h.\n    allsimpl; allrw disjoint_singleton_l.\n    repeat (autodimp h hyp); eauto 3 with slow.\n\n    { intro i; apply subset_bound_vars_lsubst_aux in i; allrw in_app_iff.\n      rw @sub_bound_vars_allvars_sub in i; eauto 3 with slow.\n      allsimpl; repndors; tcsp. }\n\n    { introv i j; apply subset_bound_vars_lsubst_aux in j; allrw in_app_iff.\n      rw @sub_bound_vars_allvars_sub in j; eauto 3 with slow.\n      allsimpl; repndors; tcsp.\n      apply disj3 in i; sp. }\n\n    { apply nrut_sub_cons; eexists; simpl; dands; eauto; tcsp; eauto with slow. }\n\n    { rw @get_utokens_lsubst_aux_allvars; eauto with slow. }\n\n    exrepnd; allsimpl.\n    unfold get_utokens_sub in h0; allsimpl; allrw disjoint_singleton_r.\n    exists u.\n    unfsubst; dands; auto.\nQed.\n\nLemma alpha_eq_bterm_ren_1side3 {o} :\n  forall (t1 t2 : @NTerm o) l1 l2,\n    disjoint l1 (all_vars t2)\n    -> length l1 = length l2\n    -> no_repeats l1\n    -> alpha_eq t1 (lsubst t2 (var_ren l2 l1))\n    -> alpha_eq_bterm (bterm l1 t1) (bterm l2 t2).\nProof.\n  introv disj1 len norep aeq.\n  pose proof (fresh_vars (length l1) (l1 ++ l2\n                                         ++ all_vars t1\n                                         ++ all_vars t2))\n    as fvs; exrepnd; allrw disjoint_app_r; repnd.\n  apply (al_bterm _ _ lvn); allrw disjoint_app_r; auto.\n  apply (lsubst_alpha_congr2 _ _ (var_ren l1 lvn)) in aeq.\n  pose proof (lsubst_nest_vars_same t2 l2 l1 lvn) as h.\n  repeat (autodimp h hyp); allrw disjoint_app_l; dands; auto.\n  rw h in aeq; eauto with slow.\nQed.\n\nDefinition maybe_new_var_b {o} (v : NVar) (b : @BTerm o) :=\n  match b with\n    | bterm l t => maybe_new_var v l t\n  end.\n\nLemma in_nrut_sub_eq {o} :\n  forall (sub: @Sub o) v1 v2 t l,\n    nrut_sub l sub\n    -> LIn (v1, t) sub\n    -> LIn (v2, t) sub\n    -> v1 = v2.\nProof.\n  induction sub; introv nrut ni1 ni2; allsimpl; tcsp.\n  destruct a as [v u].\n  allrw @nrut_sub_cons; exrepnd; subst.\n  repndors; subst; tcsp; cpx.\n  - destruct nrut2; rw lin_flat_map.\n    apply in_sub_eta in ni2; repnd.\n    eexists; dands; eauto; simpl; tcsp.\n  - destruct nrut2; rw lin_flat_map.\n    apply in_sub_eta in ni1; repnd.\n    eexists; dands; eauto; simpl; tcsp.\n  - eapply IHsub; eauto.\nQed.\n\nLemma eqset_preserves_null {T} :\n  forall (s1 s2 : list T),\n    eqset s1 s2\n    -> null s1\n    -> null s2.\nProof.\n  introv eqs n i.\n  apply eqs in i.\n  apply n in i; sp.\nQed.\n\nLemma null_get_utokens_sub_keep_first_free_vars_eq {o} :\n  forall l (t : @NTerm o) sub,\n    nrut_sub l sub\n    -> null (get_utokens_sub (sub_keep_first sub (free_vars t)))\n    -> lsubst_aux t sub = t.\nProof.\n  nterm_ind t as [v|f ind|op bs ind] Case; introv nrut nu; allsimpl; auto.\n\n  - Case \"vterm\".\n    remember (sub_find sub v) as sf; symmetry in Heqsf; destruct sf; auto.\n    unfold get_utokens_sub in nu.\n    allrw @null_flat_map.\n    applydup @sub_find_some in Heqsf.\n    pose proof (nu n) as h; clear nu.\n    eapply in_nrut_sub in nrut; eauto; exrepnd; subst; allsimpl.\n    autodimp h hyp.\n\n    + apply in_range_iff; exists v.\n      apply in_sub_keep_first; simpl; tcsp.\n\n    + pose proof (h a) as q; allsimpl; destruct q; tcsp.\n\n  - Case \"oterm\".\n    f_equal.\n    apply eq_map_l; introv i.\n    destruct x as [vs t]; allsimpl.\n    f_equal.\n    eapply ind;[eauto| |]; eauto 3 with slow.\n    introv j.\n    allrw @in_get_utokens_sub; exrepnd.\n    allrw @in_sub_keep_first; repnd.\n    allrw @sub_find_sub_filter_eq; boolvar; ginv.\n    destruct (nu x).\n    apply in_get_utokens_sub.\n    exists v t0; dands; auto.\n    apply in_sub_keep_first; dands; auto.\n    apply lin_flat_map.\n    eexists; dands; eauto.\n    simpl; rw in_remove_nvars; sp.\nQed.\n\nLemma alpha_eq_lsubst_aux_nrut_sub_implies {o} :\n  forall (t1 t2 : @NTerm o) sub l,\n    nrut_sub l sub\n    -> subset (get_utokens t1) l\n    -> subset (get_utokens t2) l\n    -> disjoint (dom_sub sub) (bound_vars t1)\n    -> disjoint (dom_sub sub) (bound_vars t2)\n    -> alpha_eq (lsubst_aux t1 sub) (lsubst_aux t2 sub)\n    -> alpha_eq t1 t2.\nProof.\n  nterm_ind1s t1 as [v1|f1 ind1|op1 bs1 ind1] Case;\n  introv nrut ss1 ss2 disj1 disj2 aeq; allsimpl.\n\n  - Case \"vterm\".\n    remember (sub_find sub v1) as sf; symmetry in Heqsf; destruct sf.\n\n    + apply sub_find_some in Heqsf.\n      dup Heqsf as i.\n      eapply in_nrut_sub in i; eauto; exrepnd; subst.\n      destruct t2 as [v2|f2|op2 bs2]; allsimpl;\n      try (complete (inversion aeq)).\n\n      * remember (sub_find sub v2) as sf'; symmetry in Heqsf'; destruct sf'.\n\n        { apply sub_find_some in Heqsf'.\n          dup Heqsf' as j.\n          eapply in_nrut_sub in j; eauto; exrepnd; subst.\n          inversion aeq; subst; allsimpl; GC.\n          apply (in_nrut_sub_eq sub v1 v2 (mk_utoken a0) l) in nrut; auto; subst; auto. }\n\n        { inversion aeq. }\n\n      * inversion aeq; subst; allsimpl; cpx; destruct bs2; allsimpl; cpx; GC; fold_terms.\n        allrw singleton_subset; tcsp.\n\n    + apply sub_find_none2 in Heqsf.\n      destruct t2 as [v2|f2|op2 bs2]; allsimpl;\n      try (complete (inversion aeq)).\n\n      remember (sub_find sub v2) as sf'; symmetry in Heqsf'; destruct sf'.\n\n      { apply sub_find_some in Heqsf'.\n        dup Heqsf' as j.\n        eapply in_nrut_sub in j; eauto; exrepnd; subst.\n        inversion aeq. }\n\n      { inversion aeq; subst; auto. }\n\n  - Case \"sterm\".\n    applydup @alphaeq_preserves_utokens in aeq; allsimpl.\n    symmetry in aeq0; apply null_iff_nil in aeq0.\n    eapply eqset_preserves_null in aeq0;[|apply get_utokens_lsubst_aux].\n    allrw @null_app; repnd.\n    erewrite null_get_utokens_sub_keep_first_free_vars_eq in aeq; eauto.\n\n  - Case \"oterm\".\n    allrw subset_app; repnd.\n    destruct t2 as [v2|f2|op2 bs2]; allsimpl; try (complete (inversion aeq)).\n\n    + remember (sub_find sub v2) as sf'; symmetry in Heqsf'; destruct sf'.\n\n      { apply sub_find_some in Heqsf'.\n        dup Heqsf' as j.\n        eapply in_nrut_sub in j; eauto; exrepnd; subst.\n        inversion aeq; subst; allsimpl; destruct bs1; allsimpl; cpx; GC; fold_terms.\n        allrw singleton_subset; tcsp. }\n\n      { inversion aeq. }\n\n    + apply alpha_eq_oterm_combine2 in aeq; allrw map_length; repnd; subst.\n      apply alpha_eq_oterm_combine; dands; auto.\n      introv i.\n      pose proof (aeq (lsubst_bterm_aux b1 sub) (lsubst_bterm_aux b2 sub)) as aeqb; clear aeq.\n      rw <- @map_combine in aeqb.\n      rw in_map_iff in aeqb.\n      autodimp aeqb hyp.\n      { eexists; dands; eauto. }\n      applydup in_combine in i; repnd; disj_flat_map.\n      destruct b1 as [l1 t1]; destruct b2 as [l2 t2]; allsimpl.\n      allrw disjoint_app_r; repnd.\n      allrw subset_app; repnd.\n\n      repeat (rw @sub_filter_disjoint1 in aeqb; eauto 3 with slow).\n\n      pose proof (fresh_vars\n                    (length l1)\n                    (all_vars (lsubst_aux t1 sub)\n                              ++ all_vars (lsubst_aux t2 sub)\n                              ++ dom_sub sub\n                              ++ bound_vars t1\n                              ++ bound_vars t2\n                              ++ free_vars t1\n                              ++ free_vars t2))\n        as fvs; exrepnd; allrw disjoint_app_r; repnd.\n\n      pose proof (alphabt_change_var_aux\n                    (lsubst_aux t1 sub) (lsubst_aux t2 sub) l1 l2) lvn\n        as a.\n      allrw disjoint_app_r; repeat (autodimp a hyp); dands; eauto 3 with slow.\n      repnd.\n\n      pose proof (simple_lsubst_aux_lsubst_aux_sub_disj\n                    t1 sub (var_ren l1 lvn)) as e1.\n      rw @sub_free_vars_var_ren in e1; auto.\n      rw @cl_lsubst_aux_sub_trivial in e1; eauto 3 with slow.\n      erewrite sub_bound_vars_nrut_sub in e1; eauto 3 with slow.\n      erewrite sub_free_vars_nrut_sub in e1; eauto 3 with slow.\n      rw @sub_filter_disjoint1 in e1;[|rw @dom_sub_var_ren; eauto with slow]; auto.\n      repeat (autodimp e1 hyp); eauto 3 with slow.\n\n      pose proof (simple_lsubst_aux_lsubst_aux_sub_disj\n                    t2 sub (var_ren l2 lvn)) as e2.\n      rw @sub_free_vars_var_ren in e2; auto; try omega.\n      rw @cl_lsubst_aux_sub_trivial in e2; eauto 3 with slow.\n      erewrite sub_bound_vars_nrut_sub in e2; eauto 3 with slow.\n      erewrite sub_free_vars_nrut_sub in e2; eauto 3 with slow.\n      rw @sub_filter_disjoint1 in e2;[|rw @dom_sub_var_ren; eauto with slow]; auto; try omega.\n      repeat (autodimp e2 hyp); eauto 3 with slow.\n\n      rw <- e1 in a0; rw <- e2 in a0; clear e1 e2.\n\n      pose proof (ind1 t1 (lsubst_aux t1 (var_ren l1 lvn)) l1) as q; clear ind1.\n      repeat (autodimp q hyp).\n      { rw @lsubst_aux_allvars_preserves_osize2; eauto 2 with slow. }\n      pose proof (q (lsubst_aux t2 (var_ren l2 lvn)) sub l) as ih; clear q.\n      repeat (rw @get_utokens_lsubst_aux_allvars in ih; eauto 3 with slow).\n      repeat (rw @boundvars_lsubst_aux_vars in ih; auto; try omega).\n      repeat (autodimp ih hyp); eauto 3 with slow.\n      { introv z1; apply ss1; rw lin_flat_map; eexists; dands; eauto. }\n      { introv z1; apply ss2; rw lin_flat_map; eexists; dands; eauto. }\n      apply (al_bterm _ _ lvn); allrw disjoint_app_r; dands; auto.\n\n      repeat (rw @lsubst_lsubst_aux); auto;\n      rw <- @sub_free_vars_is_flat_map_free_vars_range;\n      rw @computation2.sub_free_vars_var_ren; eauto 3 with slow; try omega.\nQed.\n\nLemma alpha_eq_bterm_mk_fresh_bterm_berm {o} :\n  forall (b : @BTerm o) v a l t,\n    disjoint l (all_vars_bterm b)\n    -> disjoint l (bound_vars t)\n    -> !LIn v l\n    -> !LIn (maybe_new_var_b v b) l\n    -> no_repeats l\n    -> !LIn a (get_utokens t)\n    -> !LIn a (get_utokens_b b)\n    -> alpha_eq_bterm (subst_bterm_aux b v (mk_utoken a))\n                      (bterm l (subst t v (mk_utoken a)))\n    -> alpha_eq_bterm (mk_fresh_bterm v b) (bterm l (mk_fresh v t)).\nProof.\n  introv disj1 disj2 ni1 ni2 norep nia1 nia2 aeqb.\n  destruct b as [l' t'].\n  unfold mk_fresh_bterm.\n  apply alpha_eq_bterm_sym.\n  allsimpl; allrw disjoint_app_r; repnd.\n  applydup @alphaeqbt_numbvars in aeqb as len.\n  unfold num_bvars in len; allsimpl.\n\n  apply alpha_eq_bterm_sym in aeqb.\n  unfold subst_bterm_aux in aeqb; allsimpl.\n  apply alpha_eq_bterm_ren_1side2 in aeqb;\n    [|unfold subst; rw @cl_lsubst_lsubst_aux; eauto 3 with slow;\n      rw (@bound_vars_lsubst_aux_nrut_sub o t [(v,mk_utoken a)] []);\n      eauto 3 with slow;\n      apply nrut_sub_cons; eexists; dands; simpl; eauto with slow; tcsp\n     |boolvar; allrw @lsubst_aux_nil; auto;\n      rw (@bound_vars_lsubst_aux_nrut_sub o t' [(v,mk_utoken a)] []);\n      eauto 3 with slow;\n      apply nrut_sub_cons; eexists; dands; simpl; eauto with slow; tcsp].\n\n  apply alpha_eq_bterm_ren_1side3; auto.\n  { unfold all_vars; simpl; allrw app_nil_r.\n    allrw disjoint_app_r; allrw disjoint_cons_r; dands; auto.\n    apply disjoint_remove_nvars_weak_r; auto. }\n\n  rw @lsubst_lsubst_aux; simpl; fold_terms;\n  [|rw app_nil_r; rw <- @sub_free_vars_is_flat_map_free_vars_range;\n    rw @sub_free_vars_var_ren; auto;\n    apply disjoint_cons_l; dands; complete (eauto with slow)].\n\n  allunfold @maybe_new_var.\n  boolvar.\n\n  - allrw @lsubst_aux_nil.\n    assert (!LIn v (free_vars t)) as nivt.\n    { intro i; apply alphaeq_preserves_utokens in aeqb.\n      rw (get_utokens_lsubst_allvars t') in aeqb; eauto 3 with slow.\n      rw <- aeqb in nia2; destruct nia2.\n      apply get_utokens_lsubst; rw in_app_iff; sp; simpl.\n      boolvar; tcsp. }\n    rw @cl_subst_trivial in aeqb; eauto 3 with slow.\n    rw @lsubst_aux_sub_filter_aux; simpl;\n    [|introv i j; repndors; tcsp; subst;\n      rw @dom_sub_var_ren; auto;\n      apply newvar_prop in i; complete sp].\n\n    dup aeqb as aeq.\n    apply (implies_alpha_eq_mk_fresh v) in aeqb.\n    rw <- @lsubst_lsubst_aux;\n      [|rw <- @sub_free_vars_is_flat_map_free_vars_range;\n         rw @sub_free_vars_var_ren; complete (eauto with slow)].\n    eapply alpha_eq_trans;[exact aeqb|].\n\n    pose proof (ex_fresh_var (all_vars (lsubst t' (var_ren l' l)))) as fv; exrepnd.\n    apply (implies_alpha_eq_mk_fresh_sub v0); allrw in_app_iff; allrw not_over_or; repnd; tcsp.\n    repeat (rw (lsubst_trivial3 (lsubst t' (var_ren l' l)))); auto.\n\n    { introv i; apply in_var_ren in i; allsimpl; exrepnd; repndors; tcsp; subst; allsimpl.\n      rw disjoint_singleton_l; dands; auto.\n      intro j.\n      pose proof (eqvars_free_vars_disjoint t' (var_ren l' l)) as e.\n      rw eqvars_prop in e; apply e in j; clear e.\n      rw @dom_sub_var_ren in j; auto.\n      rw in_app_iff in j; rw in_remove_nvars in j; repndors; exrepnd; tcsp.\n      - apply newvar_prop in j0; sp.\n      - apply in_sub_free_vars in j; exrepnd.\n        apply in_sub_keep_first in j0; repnd.\n        apply sub_find_some in j2.\n        apply in_var_ren in j2; exrepnd; subst; allsimpl; repndors; tcsp; subst; tcsp.\n    }\n\n    { introv i; apply in_var_ren in i; allsimpl; exrepnd; repndors; tcsp; subst; allsimpl.\n      rw disjoint_singleton_l; dands; auto.\n      intro j.\n      pose proof (eqvars_free_vars_disjoint t' (var_ren l' l)) as e.\n      rw eqvars_prop in e; apply e in j; clear e.\n      rw @dom_sub_var_ren in j; auto.\n      rw in_app_iff in j; rw in_remove_nvars in j; repndors; exrepnd; tcsp.\n      apply in_sub_free_vars in j; exrepnd.\n      apply in_sub_keep_first in j0; repnd.\n      apply sub_find_some in j2.\n      apply in_var_ren in j2; exrepnd; subst; allsimpl; repndors; tcsp; subst; tcsp.\n    }\n\n  - rw @lsubst_lsubst_aux in aeqb;\n    [|rw <- @sub_free_vars_is_flat_map_free_vars_range;\n       rw @sub_free_vars_var_ren; try (complete (eauto 3 with slow));\n       rw (@bound_vars_lsubst_aux_nrut_sub o t' [(v,mk_utoken a)] []);\n       eauto 3 with slow;\n       apply nrut_sub_cons; eexists; dands; simpl; eauto with slow; tcsp].\n\n    pose proof (simple_lsubst_aux_lsubst_aux_sub_disj\n                  t' [(v,mk_utoken a)] (var_ren l' l)) as e; allsimpl.\n    allrw disjoint_singleton_l.\n    rw @sub_free_vars_var_ren in e; try (complete (eauto 3 with slow)).\n    repeat (autodimp e hyp); eauto 2 with slow; fold_terms.\n    rw <- e in aeqb; clear e.\n    apply implies_alpha_eq_mk_fresh.\n    remember (lsubst_aux t' (sub_filter (var_ren l' l) [v])) as t''.\n    unfold subst in aeqb; rw @cl_lsubst_lsubst_aux in aeqb; eauto 2 with slow.\n\n    assert (!LIn a (get_utokens t'')) as niat''.\n    { subst; intro i.\n      apply get_utokens_lsubst_aux in i; allrw in_app_iff; repndors; tcsp.\n      rw @get_utokens_sub_allvars_sub in i; allsimpl; eauto with slow.\n    }\n\n    clear Heqt''.\n\n    pose proof (change_bvars_alpha_wspec [v] t) as aeqt; exrepnd.\n    pose proof (change_bvars_alpha_wspec [v] t'') as aeqt'; exrepnd.\n    allrw disjoint_singleton_l.\n\n    assert (alpha_eq (lsubst_aux t [(v, mk_utoken a)])\n                     (lsubst_aux ntcv [(v, mk_utoken a)])) as aeq1.\n    { apply computation2.lsubst_aux_alpha_congr_same_cl_sub; eauto 3 with slow. }\n\n    assert (alpha_eq (lsubst_aux t'' [(v, mk_utoken a)])\n                     (lsubst_aux ntcv0 [(v, mk_utoken a)])) as aeq2.\n    { apply computation2.lsubst_aux_alpha_congr_same_cl_sub; eauto 3 with slow. }\n\n    assert (alpha_eq (lsubst_aux ntcv [(v, mk_utoken a)])\n                     (lsubst_aux ntcv0 [(v, mk_utoken a)])) as aeq3.\n    { eapply alpha_eq_trans;[apply alpha_eq_sym; exact aeq1|].\n      eapply alpha_eq_trans;[exact aeqb|].\n      eauto with slow. }\n    clear aeq1 aeq2.\n\n    assert (alpha_eq ntcv ntcv0) as aeq;[|eauto 4 with slow];[].\n\n    apply (alpha_eq_lsubst_aux_nrut_sub_implies\n             _ _ _ (get_utokens ntcv ++ get_utokens ntcv0)) in aeq3;\n      simpl; eauto 3 with slow; allrw disjoint_singleton_l; auto.\n\n    apply alphaeq_preserves_utokens in aeqt0.\n    apply alphaeq_preserves_utokens in aeqt'0.\n    rw aeqt0 in nia1.\n    rw aeqt'0 in niat''.\n    apply nrut_sub_cons; eexists; dands; simpl; eauto; tcsp; eauto 3 with slow.\n    rw in_app_iff; tcsp.\nQed.\n\nLemma alpha_eq_bterm_preserves_isprog_vars {o} :\n  forall l1 l2 (t1 t2 : @NTerm o),\n    alpha_eq_bterm (bterm l1 t1) (bterm l2 t2)\n    -> isprog_vars l1 t1\n    -> isprog_vars l2 t2.\nProof.\n  introv aeq isp.\n  allrw @isprog_vars_eq; repnd.\n  applydup @alphaeqbt_preserves_nt_wf in aeq as w.\n  rw w; dands; auto.\n  apply alphaeqbt_preserves_fvars in aeq; allsimpl.\n  rw eqvars_prop in aeq.\n  allrw subvars_prop.\n  introv i.\n  destruct (in_deq _ deq_nvar x l2) as [d|d]; auto.\n  assert (LIn x (remove_nvars l2 (free_vars t2))) as j.\n  { rw in_remove_nvars; sp. }\n  apply aeq in j.\n  rw in_remove_nvars in j; repnd.\n  apply isp0 in j0; sp.\nQed.\n\nLemma approx_starbts_get_bterms_alpha_eq_l {o} :\n  forall lib op (t u v : @NTerm o),\n    approx_starbts lib op (get_bterms t) (get_bterms u)\n    -> alpha_eq t v\n    -> approx_starbts lib op (get_bterms v) (get_bterms u).\nProof.\n  introv ap aeq.\n  destruct t as [v1|f1|op1 bs1]; destruct u as [v2|f2|op2 bs2]; allsimpl; auto;\n  try (complete (inversion aeq; subst; allsimpl; auto)).\n  - unfold approx_starbts, lblift_sub in ap; allsimpl; repnd; cpx.\n    inversion aeq; subst; allsimpl; cpx; auto.\n    unfold approx_starbts, lblift_sub; simpl; sp.\n  - unfold approx_starbts, lblift_sub in ap; allsimpl; repnd; cpx.\n    inversion aeq; subst; allsimpl; cpx; auto.\n    unfold approx_starbts, lblift_sub; simpl; sp.\n  - inversion aeq as [|?|? ? ? len imp]; subst; simpl.\n    allunfold @approx_starbts.\n    allunfold @lblift_sub; repnd; dands; auto; try omega.\n    introv i.\n    pose proof (ap n) as h1; autodimp h1 hyp; try omega.\n    pose proof (imp n) as h2; autodimp h2 hyp; try omega.\n    eapply approx_star_bterm_alpha_fun_l;[apply alpha_eq_bterm_sym; exact h2|]; auto.\nQed.\n\nLemma subst_sterm {o} :\n  forall (f : @ntseq o) v t,\n    subst (sterm f) v t = sterm f.\nProof.\n  introv; unfold subst; autorewrite with slow; auto.\nQed.\nHint Rewrite @subst_sterm : slow.\n\n(*\nLemma same_value_like_sterm_implies_approx_star {o} :\n  forall lib (f1 f2 : @ntseq o),\n    nt_wf (sterm f2)\n    -> same_value_like (sterm f1) (sterm f2)\n    -> approx_star lib (sterm f1) (sterm f2).\nProof.\n  introv wf svl.\n  inversion svl; subst; clear svl.\n  econstructor; eauto.\n  apply approx_open_refl; auto.\nQed.\nHint Resolve same_value_like_sterm_implies_approx_star : slow.\n*)\n\nLemma approx_star_pushdown_fresh_if_subst {o} :\n  forall lib (t1 t2 : @NTerm o) v1 v2 a,\n    !LIn a (get_utokens t1)\n    -> !LIn a (get_utokens t2)\n    -> isprog_vars [v1] t1\n    -> isprog_vars [v2] t2\n    -> same_value_like lib (subst t1 v1 (mk_utoken a)) (subst t2 v2 (mk_utoken a))\n    -> approx_starbts lib (get_op t1) (get_bterms (subst t1 v1 (mk_utoken a))) (get_bterms (subst t2 v2 (mk_utoken a)))\n    -> approx_star lib (pushdown_fresh v1 t1) (pushdown_fresh v2 t2).\nProof.\n  introv ni1 ni2 isp1 isp2 svl ap.\n\n  pose proof (ex_fresh_var (all_vars t1\n                                     ++ all_vars t2))\n    as fv; exrepnd.\n  allrw in_app_iff; allrw not_over_or; repnd.\n\n  pose proof (alpha_bterm_change\n                (bterm [v1] t1) [v1] t1 [v]) as aeqbt1.\n  allrw disjoint_singleton_r.\n  allrw in_app_iff; allrw not_over_or.\n  allsimpl.\n  repeat (autodimp aeqbt1 hyp).\n\n  pose proof (alpha_bterm_change\n                (bterm [v2] t2) [v2] t2 [v]) as aeqbt2.\n  allrw disjoint_singleton_r.\n  allrw in_app_iff; allrw not_over_or.\n  allsimpl.\n  repeat (autodimp aeqbt2 hyp).\n\n  remember (lsubst t1 (var_ren [v1] [v])) as nt1.\n  remember (lsubst t2 (var_ren [v2] [v])) as nt2.\n\n  applydup @alpha_eq_bterm_preserves_utokens in aeqbt1 as ut1; allsimpl.\n  rw ut1 in ni1.\n  applydup @alpha_eq_bterm_preserves_utokens in aeqbt2 as ut2; allsimpl.\n  rw ut2 in ni2.\n\n  pose proof (lsubst_alpha_congr4 [v1] [v] t1 nt1 [(v1,mk_utoken a)] [(v,mk_utoken a)]) as c1.\n  allsimpl.\n  repeat (autodimp c1 hyp); eauto 3 with slow.\n\n  pose proof (lsubst_alpha_congr4 [v2] [v] t2 nt2 [(v2,mk_utoken a)] [(v,mk_utoken a)]) as c2.\n  allsimpl.\n  repeat (autodimp c2 hyp); eauto 3 with slow.\n\n  allrw @fold_subst.\n\n  eapply same_value_like_alpha_eq_r in svl;[|exact c2].\n  eapply same_value_like_alpha_eq_l in svl;[|exact c1].\n\n  eapply alpha_eq_bterm_preserves_isprog_vars in isp1;[|exact aeqbt1].\n  eapply alpha_eq_bterm_preserves_isprog_vars in isp2;[|exact aeqbt2].\n\n  assert (get_op t1 = get_op nt1) as go.\n  { subst; rw @lsubst_lsubst_aux; allrw <- @sub_free_vars_is_flat_map_free_vars_range;\n    allsimpl; allrw disjoint_singleton_r; auto.\n    destruct t1; simpl; boolvar; simpl; tcsp. }\n  rw go in ap.\n\n  eapply approx_starbts_get_bterms_alpha_eq in ap;[|exact c2].\n  eapply approx_starbts_get_bterms_alpha_eq_l in ap;[|exact c1].\n\n  applydup @implies_alpha_eq_pushdown_fresh in aeqbt1 as apf1.\n  applydup @implies_alpha_eq_pushdown_fresh in aeqbt2 as apf2.\n\n  eapply approx_star_alpha_fun_l;[|apply alpha_eq_sym; exact apf1].\n  eapply approx_star_alpha_fun_r;[|apply alpha_eq_sym; exact apf2].\n\n  clear dependent t1.\n  clear dependent t2.\n  rename nt1 into t1.\n  rename nt2 into t2.\n\n  repeat (unfsubst in svl); repeat (unfsubst in ap); allsimpl.\n  destruct t1 as [x|f|op bs]; allsimpl; tcsp; GC.\n\n  - boolvar.\n\n    + apply approx_open_implies_approx_star.\n      apply approx_implies_approx_open.\n      apply (approx_trans _ _ (mk_fresh x (mk_var x))).\n\n      * apply reduces_to_implies_approx2.\n        { apply isprogram_fresh.\n          apply isprog_vars_var. }\n        apply reduces_to_if_step.\n        csunf; simpl; boolvar; auto.\n\n      * apply fresh_id_approx_any.\n        apply isprogram_pushdown_fresh; auto.\n\n    + inversion svl.\n\n  - autorewrite with slow in *.\n    destruct t2 as [v2|f2|op bs]; allsimpl; boolvar; allsimpl;\n    try (complete (inversion svl)); eauto 4 with slow.\n    inversion svl; subst; clear svl.\n    allrw @isprog_vars_eq; repnd.\n    econstructor;[| |eauto|]; eauto 3 with slow.\n\n  - allsimpl.\n    destruct t2 as [x|f|op' bs']; allsimpl; GC; try (complete (inversion svl)).\n\n    + boolvar; try (complete (inversion svl)).\n      inversion svl; subst; allsimpl.\n      allrw not_over_or; sp.\n\n    + applydup @same_value_like_implies_same_op in svl; subst.\n\n      assert (length bs = length bs') as e.\n      {  unfold approx_starbts, lblift_sub in ap; repnd; allrw map_length.\n         unfold mk_fresh_bterms; allrw map_length; auto. }\n\n      apply (apso _ _ _ _ (mk_fresh_bterms v bs')); auto;\n      try (apply approx_open_refl);\n      [unfold mk_fresh_bterms; allrw map_length; auto\n       |idtac\n       |apply isprog_vars_eq in isp2; repnd;\n       allrw @nt_wf_oterm_iff; repnd;\n       rw <- isp3;\n       unfold mk_fresh_bterms; allrw map_map; unfold compose; dands;\n       [ apply eq_maps; introv i; destruct x; unfold num_bvars; simpl; auto|];\n       introv i; allrw in_map_iff; exrepnd; subst;\n       apply isp2 in i1; apply bt_wf_mk_fresh_bterm_if; complete auto].\n\n      unfold lblift_sub, mk_fresh_bterms; dands; allrw map_length; auto.\n      introv i.\n      repeat (rw @selectbt_map; auto; try omega).\n      unfold approx_starbts, lblift_sub in ap; repnd; allrw map_length; GC.\n      pose proof (ap n i) as k; clear ap.\n      repeat (rw @selectbt_map in k; auto; try omega).\n      allunfold @selectbt.\n\n      pose proof (in_nth_combine _ _ bs bs' n default_bt default_bt) as h.\n      repeat (autodimp h hyp).\n      remember (nth n bs default_bt)  as b1; clear Heqb1.\n      remember (nth n bs' default_bt) as b2; clear Heqb2.\n      allrw in_app_iff; allrw not_over_or; repnd.\n      applydup in_combine in h; repnd.\n      assert (!LIn a (get_utokens_b b1)) as niab1.\n      { introv q; destruct ni1; rw lin_flat_map; eexists; dands; eauto. }\n      assert (!LIn a (get_utokens_b b2)) as niab2.\n      { introv q; destruct ni2; rw lin_flat_map; eexists; dands; eauto. }\n\n(* new stuff *)\n\n      apply (blift_sub_diff (v :: maybe_new_var_b v b1\n                               :: maybe_new_var_b v b2\n                               :: all_vars_bterm b1\n                               ++ all_vars_bterm b2)) in k; exrepnd.\n      allrw disjoint_cons_r; allrw disjoint_cons_l; allrw disjoint_app_r; allrw disjoint_app_l; repnd.\n\n      assert (wf_term nt1) as wfnt1.\n      { repndors; exrepnd.\n        - allapply @approx_star_relates_only_wf; repnd; eauto 2 with slow.\n        - allapply @approx_star_relates_only_wf; repnd.\n          allapply @lsubst_nt_wf; eauto with slow. }\n\n      assert (wf_term nt2) as wfnt2.\n      { repndors; exrepnd.\n        - allapply @approx_star_relates_only_wf; repnd; eauto 2 with slow.\n        - allapply @approx_star_relates_only_wf; repnd.\n          allapply @lsubst_nt_wf; eauto with slow. }\n\n      pose proof (alpha_eq_subst_bterm_aux_pull_out_token b1 v a lv nt1) as exs1.\n      repeat (autodimp exs1 hyp); exrepnd.\n      subst nt1.\n      rename u into nt1.\n\n      pose proof (alpha_eq_subst_bterm_aux_pull_out_token b2 v a lv nt2) as exs2.\n      repeat (autodimp exs2 hyp); exrepnd.\n      subst nt2.\n      rename u into nt2.\n\n      assert (disjoint lv (bound_vars nt1)) as disjlvnt1.\n      { introv i1 i2; apply k7 in i1; destruct i1.\n        unfsubst.\n        rw (bound_vars_lsubst_aux_nrut_sub nt1 [(v,mk_utoken a)] []); auto.\n        apply nrut_sub_cons; eexists; dands; simpl; eauto with slow; tcsp. }\n\n      assert (disjoint lv (bound_vars nt2)) as disjlvnt2.\n      { introv i1 i2; apply k8 in i1; destruct i1.\n        unfsubst.\n        rw (bound_vars_lsubst_aux_nrut_sub nt2 [(v,mk_utoken a)] []); auto.\n        apply nrut_sub_cons; eexists; dands; simpl; eauto with slow; tcsp. }\n\n      unfold blift_sub.\n\n      pose proof (alpha_eq_bterm_mk_fresh_bterm_berm b1 v a lv nt1) as e1.\n      repeat (autodimp e1 hyp); eauto 3 with slow.\n\n      pose proof (alpha_eq_bterm_mk_fresh_bterm_berm b2 v a lv nt2) as e2.\n      repeat (autodimp e2 hyp); eauto 3 with slow.\n\n      exists lv (mk_fresh v nt1) (mk_fresh v nt2); dands; auto.\n\n      (* here comes trouble! *)\n\n      repndors;[left|right].\n\n      * repnd; dands; auto.\n        apply (apso _ _ _ _ [bterm [v] nt2]); allsimpl; auto; fold_terms;\n        [|apply approx_open_refl; allrw <- @nt_wf_eq;\n          allapply @lsubst_nt_wf; apply nt_wf_fresh; auto].\n        unfold lblift_sub; simpl; dands; auto; introv q; destruct n0; cpx.\n        unfold selectbt; simpl.\n        unfold blift_sub.\n\n        exists [v] nt1 nt2; dands; auto.\n        right.\n        exists [(v,mk_utoken a)]; simpl; dands; auto.\n        apply nrut_sub_cons; simpl; eexists; dands; eauto with slow; tcsp.\n        rw in_app_iff; sp.\n\n      * exrepnd.\n\n        pose proof (exists_nrut_sub\n                      (dom_sub sub)\n                      (a :: get_utokens (subst nt1 v (mk_utoken a))\n                         ++ get_utokens (subst nt2 v (mk_utoken a))))\n          as ens; exrepnd.\n\n        pose proof (approx_star_change_nrut_sub\n                      lib\n                      (subst nt1 v (mk_utoken a))\n                      (subst nt2 v (mk_utoken a))\n                      sub\n                      (get_utokens (subst nt1 v (mk_utoken a)) ++ get_utokens (subst nt2 v (mk_utoken a)))\n                      sub0\n                      (a :: get_utokens (subst nt1 v (mk_utoken a)) ++ get_utokens (subst nt2 v (mk_utoken a))))\n          as aps; repeat (autodimp aps hyp); eauto 3 with slow.\n\n        exists sub0; dands; auto; simpl; allrw app_nil_r;\n        try (complete (subst; auto));\n        [|eapply nrut_sub_subset;[|exact ens1]; apply subset_cons1;\n          apply subset_app_lr; introv z;\n          apply get_utokens_subst; boolvar; simpl;\n          repeat (rw app_nil_r); repeat (rw in_app_iff); complete sp].\n        repeat (rw @cl_lsubst_lsubst_aux; eauto 2 with slow); simpl; fold_terms.\n        apply (apso _ _ _ _ [bterm [v] (lsubst_aux nt2 (sub_filter sub0 [v]))]); allsimpl; auto; fold_terms;\n        [|apply approx_open_refl; allrw <- @nt_wf_eq;\n          allapply @lsubst_nt_wf; apply nt_wf_fresh; auto;\n          apply implies_wf_lsubst_aux; eauto 3 with slow];[].\n        unfold lblift_sub; simpl; dands; auto; introv q; destruct n0; cpx.\n        unfold selectbt; simpl.\n        unfold blift_sub.\n\n        allunfold @subst.\n        rw (cl_lsubst_swap_sub_filter nt1) in aps; eauto 3 with slow.\n        rw (cl_lsubst_swap_sub_filter nt2) in aps; eauto 3 with slow.\n        allsimpl.\n\n        assert (!LIn a (get_utokens_sub sub0)) as niasub.\n        { intro z; unfold nrut_sub in ens1; repnd; allrw disjoint_cons_l; sp. }\n\n        exists [v] (lsubst_aux nt1 (sub_filter sub0 [v])) (lsubst_aux nt2 (sub_filter sub0 [v])); dands; auto.\n        right.\n        exists [(v,mk_utoken a)]; simpl; dands; auto.\n        { repeat (rw <- @cl_lsubst_lsubst_aux; eauto 3 with slow). }\n        apply nrut_sub_cons; simpl; eexists; dands; eauto with slow; tcsp.\n        rw in_app_iff; rw not_over_or; dands; intro z;\n        apply get_utokens_lsubst_aux_subset in z; rw in_app_iff in z; repndors; tcsp;\n        apply get_utokens_sub_filter_subset in z; tcsp.\nQed.\n\nLemma alpha_eq_lsubst_nrut_sub_implies {o} :\n  forall (t1 t2 : @NTerm o) sub l,\n    nrut_sub l sub\n    -> subset (get_utokens t1) l\n    -> subset (get_utokens t2) l\n    -> alpha_eq (lsubst t1 sub) (lsubst t2 sub)\n    -> alpha_eq t1 t2.\nProof.\n  introv nrut ss1 ss2 aeq.\n\n  pose proof (unfold_lsubst sub t1) as p; destruct p as [t1']; repnd.\n  pose proof (unfold_lsubst sub t2) as q; destruct q as [t2']; repnd.\n  rw p in aeq; rw p2 in aeq.\n\n  pose proof (change_bvars_alpha_wspec (dom_sub sub) t1') as h; destruct h as [t1'']; repnd.\n  pose proof (change_bvars_alpha_wspec (dom_sub sub) t2') as k; destruct k as [t2'']; repnd.\n  dup p5 as a1.\n  apply (computation2.lsubst_aux_alpha_congr_same_cl_sub _ _ sub) in a1; eauto 2 with slow.\n  dup p7 as a2.\n  apply (computation2.lsubst_aux_alpha_congr_same_cl_sub _ _ sub) in a2; eauto 2 with slow.\n\n  assert (alpha_eq (lsubst_aux t1'' sub) (lsubst_aux t2'' sub)) as aeq2 by eauto 4 with slow.\n\n  pose proof (alpha_eq_lsubst_aux_nrut_sub_implies t1'' t2'' sub l) as a.\n  repeat (autodimp a hyp).\n  - apply alphaeq_preserves_utokens in p5; rw <- p5.\n    apply alphaeq_preserves_utokens in p0; rw <- p0; auto.\n  - apply alphaeq_preserves_utokens in p7; rw <- p7.\n    apply alphaeq_preserves_utokens in p3; rw <- p3; auto.\n  - assert (alpha_eq t1 t1'') as aeq11 by eauto with slow.\n    assert (alpha_eq t2 t2'') as aeq22 by eauto with slow.\n    eauto with slow.\nQed.\n\nLemma reduces_in_atmost_k_steps_mk_fresh_id {o} :\n  forall (lib : @library o) v k u,\n    reduces_in_atmost_k_steps lib (mk_fresh v (vterm v)) u k\n    -> u = mk_fresh v (vterm v).\nProof.\n  induction k; introv r.\n  - allrw @reduces_in_atmost_k_steps_0; auto.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    csunf r1; allsimpl; boolvar; ginv.\n    apply IHk in r0; auto.\nQed.\n\nLemma reduces_in_atmost_k_steps_mk_fresh_id2 {o} :\n  forall (lib : @library o) v k,\n    reduces_in_atmost_k_steps lib (mk_fresh v (vterm v)) (mk_fresh v (vterm v)) k.\nProof.\n  induction k; introv.\n  - allrw @reduces_in_atmost_k_steps_0; auto.\n  - allrw @reduces_in_atmost_k_steps_S; exrepnd.\n    exists (@mk_fresh o v (vterm v)); dands; auto.\n    csunf; simpl; boolvar; auto.\nQed.\n\nLemma isprog_vars_implies_nt_wf {o} :\n  forall (t : @NTerm o) l, isprog_vars l t -> nt_wf t.\nProof.\n  introv isp.\n  rw @isprog_vars_eq in isp; sp.\nQed.\nHint Resolve isprog_vars_implies_nt_wf : slow.\n", "meta": {"author": "vrahli", "repo": "NuprlInCoq", "sha": "0c3d7723836d3f615ea47f56e58b2ea6173e7d98", "save_path": "github-repos/coq/vrahli-NuprlInCoq", "path": "github-repos/coq/vrahli-NuprlInCoq/NuprlInCoq-0c3d7723836d3f615ea47f56e58b2ea6173e7d98/cequiv/approx_star_fresh.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.2092695485048277}}
{"text": "\n(** Anything can be summarised as being basically two options.\n  Furthermore, the second option is usually very wrong. **)\nAxiom there_is_a_choice : forall T, exists a b, forall t : T, t = a \\/ t = b.\n\nInductive undisciplined := Good | Bad | Ugly.\n\nLemma undisciplined_has_more_choice : forall a b : undisciplined,\n  exists c, c <> a /\\ c <> b.\nProof.\n  destruct a, b;\n    try solve [ exists Good; split; discriminate\n              | exists Bad; split; discriminate\n              | exists Ugly; split; discriminate ].\nQed.\n\nCorollary nothing_matters : False.\n  set (H := there_is_a_choice undisciplined). destruct H as (a&b&I).\n  set (H := undisciplined_has_more_choice a b). destruct H as (c&D1&D2).\n  destruct (I c); auto.\nQed.\n\n(** Not only there are only two options, you can actually choose them.\n  Again, the second one is usually very bad.\n  The good news is that disjunction is commutative: if you need to change\n  side in the middle, you can actually claim that it was the first one\n  that was bad, not the second one. **)\nTheorem straw_man : forall T (a b t : T), t = a \\/ t = b.\nProof.\n  exfalso. apply nothing_matters.\nQed.\n", "meta": {"author": "Mbodin", "repo": "coq-alternative-facts", "sha": "2c6ae63be7fb089085b313ccd21b9f5368a04e2c", "save_path": "github-repos/coq/Mbodin-coq-alternative-facts", "path": "github-repos/coq/Mbodin-coq-alternative-facts/coq-alternative-facts-2c6ae63be7fb089085b313ccd21b9f5368a04e2c/theories/StrawMan.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.348645142101806, "lm_q1q2_score": 0.20925275081549877}}
{"text": "Set Implicit Arguments.\n\nRequire Import Coq.Lists.List.\nRequire Import Bedrock.Platform.Cito.ListFacts1 Bedrock.Platform.Cito.ListFacts2 Bedrock.Platform.Cito.ListFacts3.\nRequire Import Bedrock.ListFacts.\nRequire Import Bedrock.Platform.Cito.GeneralTactics.\nRequire Import Bedrock.Platform.Cito.GeneralTactics4.\nRequire Import Bedrock.Platform.Cito.Option.\n\nLemma combine_length_eq A B (ls1 : list A) : forall (ls2 : list B), length ls1 = length ls2 -> length (combine ls1 ls2) = length ls1.\nProof.\n  induction ls1; destruct ls2; simpl in *; intros; intuition.\nQed.\n\nLemma nth_error_combine A B ls1 : forall ls2 i (a : A) (b : B), nth_error ls1 i = Some a -> nth_error ls2 i = Some b -> nth_error (combine ls1 ls2) i = Some (a, b).\nProof.\n  induction ls1; destruct ls2; destruct i; simpl in *; intros; try discriminate.\n  inject H; inject H0; eauto.\n  eauto.\nQed.\n\nLemma nth_error_combine_elim A B ls1 : forall ls2 i (a : A) (b : B), nth_error (combine ls1 ls2) i = Some (a, b) -> nth_error ls1 i = Some a /\\ nth_error ls2 i = Some b.\nProof.\n  induction ls1; destruct ls2; destruct i; simpl in *; intros; try discriminate.\n  inject H; eauto.\n  eauto.\nQed.\n\nLemma nth_error_map_elim : forall A B (f : A -> B) ls i b, nth_error (List.map f ls) i = Some b -> exists a, nth_error ls i = Some a /\\ f a = b.\n  intros.\n  rewrite ListFacts.map_nth_error_full in H.\n  destruct (option_dec (nth_error ls i)).\n  destruct s; rewrite e in *; inject H; eexists; eauto.\n  rewrite e in *; discriminate.\nQed.\n\nLemma map_nth_error_1 : forall A B (f : A -> B) ls1 ls2 i a, List.map f ls1 = ls2 -> nth_error ls1 i = Some a -> nth_error ls2 i = Some (f a).\n  intros.\n  rewrite <- H.\n  erewrite map_nth_error; eauto.\nQed.\n\nLemma map_nth_error_2 A B (f : A -> B) ls1 : forall ls2 i b, List.map f ls1 = ls2 -> nth_error ls2 i = Some b -> exists a, nth_error ls1 i = Some a /\\ f a = b.\nProof.\n  induction ls1; destruct ls2; destruct i; simpl in *; intros; try discriminate.\n  inject H; inject H0; eexists; eauto.\n  inject H; eauto.\nQed.\n\nLemma map_eq_nth_error_1 : forall A1 A2 B (f1 : A1 -> B) (f2 : A2 -> B) ls1 ls2 i a1, List.map f1 ls1 = List.map f2 ls2 -> nth_error ls1 i = Some a1 -> exists a2, nth_error ls2 i = Some a2 /\\ f1 a1 = f2 a2.\n  intros.\n  eapply map_nth_error_1 in H; eauto.\n  eapply nth_error_map_elim in H; openhyp.\n  eexists; eauto.\nQed.\n\nLemma in_nth_error A ls : forall (a : A), List.In a ls -> exists i, nth_error ls i = Some a.\nProof.\n  induction ls; simpl in *; intros.\n  intuition.\n  openhyp.\n  subst.\n  exists 0; eauto.\n  eapply IHls in H; eauto.\n  openhyp.\n  exists (S x); eauto.\nQed.\n\nLemma nth_error_nil A i : nth_error (@nil A) i = None.\nProof.\n  destruct i; simpl in *; eauto.\nQed.\n\nFixpoint mapM A B (f : A -> option B) ls :=\n  match ls with\n    | x :: xs =>\n      match f x, mapM f xs with\n        | Some y, Some ys => Some (y :: ys)\n        | _, _ => None\n      end\n    | nil => Some nil\n  end.\n\nLemma mapM_length A B (f : A -> option B) ls1 : forall ls2, mapM f ls1 = Some ls2 -> length ls1 = length ls2.\nProof.\n  induction ls1; destruct ls2; simpl in *; intros; try discriminate.\n  eauto.\n  destruct (option_dec (f a)) as [[y Hy] | Hnone].\n  rewrite Hy in *.\n  destruct (option_dec (mapM f ls1)) as [[ys Hys] | Hnone].\n  rewrite Hys in *.\n  discriminate.\n  rewrite Hnone in *; discriminate.\n  rewrite Hnone in *; discriminate.\n\n  f_equal.\n  destruct (option_dec (f a)) as [[y Hy] | Hnone].\n  rewrite Hy in *.\n  destruct (option_dec (mapM f ls1)) as [[ys Hys] | Hnone].\n  rewrite Hys in *.\n  inject H; eauto.\n  rewrite Hnone in *; discriminate.\n  rewrite Hnone in *; discriminate.\nQed.\n\nLemma mapM_nth_error_1 A B (f : A -> option B) ls1 : forall ls2 i a, mapM f ls1 = Some ls2 -> nth_error ls1 i = Some a -> exists b, nth_error ls2 i = Some b /\\ f a = Some b.\nProof.\n  induction ls1; destruct ls2; destruct i; simpl in *; intros; try discriminate.\n  destruct (option_dec (f a)) as [[y Hy] | Hnone].\n  rewrite Hy in *.\n  destruct (option_dec (mapM f ls1)) as [[ys Hys] | Hnone].\n  rewrite Hys in *.\n  discriminate.\n  rewrite Hnone in *; discriminate.\n  rewrite Hnone in *; discriminate.\n  destruct (option_dec (f a)) as [[y Hy] | Hnone].\n  rewrite Hy in *.\n  destruct (option_dec (mapM f ls1)) as [[ys Hys] | Hnone].\n  rewrite Hys in *.\n  discriminate.\n  rewrite Hnone in *; discriminate.\n  rewrite Hnone in *; discriminate.\n  destruct (option_dec (f a)) as [[y Hy] | Hnone].\n  rewrite Hy in *.\n  destruct (option_dec (mapM f ls1)) as [[ys Hys] | Hnone].\n  rewrite Hys in *.\n  inject H; inject H0; eexists; eauto.\n  rewrite Hnone in *; discriminate.\n  rewrite Hnone in *; discriminate.\n  destruct (option_dec (f a)) as [[y Hy] | Hnone].\n  rewrite Hy in *.\n  destruct (option_dec (mapM f ls1)) as [[ys Hys] | Hnone].\n  rewrite Hys in *.\n  inject H; eauto.\n  rewrite Hnone in *; discriminate.\n  rewrite Hnone in *; discriminate.\nQed.\n\nLemma length_eq_nth_error A B ls1 : forall ls2 i (a : A), nth_error ls1 i = Some a -> length ls1 = length ls2 -> exists b : B, nth_error ls2 i = Some b.\nProof.\n  induction ls1; destruct ls2; destruct i; simpl in *; intros; try discriminate.\n  inject H; inject H0; eexists; eauto.\n  inject H0; eauto.\nQed.\n\nLemma mapM_nth_error_2 A B (f : A -> option B) ls1 ls2 i a2 : mapM f ls1 = Some ls2 -> nth_error ls2 i = Some a2 -> exists a1, nth_error ls1 i = Some a1 /\\ f a1 = Some a2.\nProof.\n  intros Hmm Ha2.\n  copy_as Ha2 Ha2'; eapply length_eq_nth_error in Ha2'.\n  2 : symmetry; eapply mapM_length; eauto.\n  destruct Ha2' as [a1 Ha1].\n  eapply mapM_nth_error_1 in Hmm; eauto.\n  destruct Hmm as [a2' [Ha2' Hf]].\n  unif a2'.\n  rewrite <- Hf in *.\n  eexists; eauto.\nQed.\n\nLemma cons_incl_elim A (a : A) ls1 ls2 : incl (a :: ls1) ls2 -> List.In a ls2 /\\ incl ls1 ls2.\nProof.\n  unfold incl.\n  intros Hincl.\n  split.\n  eapply Hincl.\n  eapply in_eq.\n  intros a' Hin.\n  eapply Hincl.\n  eapply in_cons; eauto.\nQed.\n\nLemma incl_nth_error A ls1 : forall i ls2 (a : A), List.incl ls1 ls2 -> nth_error ls1 i = Some a -> exists i', nth_error ls2 i' = Some a.\nProof.\n  induction ls1; destruct i; simpl in *; intros; try discriminate.\n  inject H0.\n  eapply cons_incl_elim in H.\n  openhyp.\n  eapply in_nth_error; eauto.\n  eapply IHls1; eauto.\n  eapply cons_incl_elim in H.\n  openhyp.\n  eauto.\nQed.\n\nLemma combine_map A B C (f1 : A -> B) (f2 : A -> C) ls : combine (List.map f1 ls) (List.map f2 ls) = List.map (fun x => (f1 x, f2 x)) ls.\nProof.\n  induction ls; simpl in *; intros; try f_equal; eauto.\nQed.\n\nLemma nth_error_In : forall A (x : A) ls n,\n                       nth_error ls n = Some x\n                       -> In x ls.\n  induction ls; destruct n; simpl; intuition; try discriminate; eauto.\n  injection H; intros; subst; auto.\nQed.\n\nLemma NoDup_nth_error A ls : NoDup ls -> forall i i' (x : A), nth_error ls i = Some x -> nth_error ls i' = Some x -> i = i'.\nProof.\n  induction 1; destruct i; destruct i'; simpl in *; intros; try discriminate.\n  eauto.\n  inject H1.\n  contradict H; eapply nth_error_In; eauto.\n  inject H2.\n  contradict H; eapply nth_error_In; eauto.\n  f_equal; eauto.\nQed.\n\nArguments fst {A B} _ .\nArguments snd {A B} _ .\n\nLemma map_fst_combine A B (ls1 : list A) : forall (ls2 : list B), length ls1 = length ls2 -> List.map fst (combine ls1 ls2) = ls1.\n  induction ls1; destruct ls2; simpl in *; intros; try discriminate; intuition.\n  f_equal; eauto.\nQed.\n\nLemma map_snd_combine A B (ls1 : list A) : forall (ls2 : list B), length ls1 = length ls2 -> List.map snd (combine ls1 ls2) = ls2.\n  induction ls1; destruct ls2; simpl in *; intros; try discriminate; intuition.\n  f_equal; eauto.\nQed.\n\nRequire Import Coq.Setoids.Setoid.\nRequire Import Coq.Classes.Morphisms.\n\nGlobal Add Parametric Morphism A B : (@List.map A B)\n    with signature pointwise_relation A eq ==> eq ==> eq as list_map_m.\nProof.\n  intros; eapply map_ext; eauto.\nQed.\n\nLemma In_map_ext A B (f g : A -> B) : forall ls, (forall x, List.In x ls -> f x = g x) -> List.map f ls = List.map g ls.\nProof.\n  induction ls; simpl; intros Hfg; trivial.\n  f_equal.\n  {\n    eapply Hfg.\n    eauto.\n  }\n  eapply IHls.\n  intuition.\nQed.\n\nLemma in_singleton_iff A (x' x : A) : List.In x' (x :: nil) <-> x' = x.\nProof.\n  intros; subst; simpl in *; intuition.\nQed.\n\nRequire Import Bedrock.Platform.Cito.GeneralTactics2.\n\nLemma singleton_iff_not : forall elt (e e' : elt), ~ List.In e' (e :: nil) <-> e <> e'.\n  unfold List.In; split; intros; not_not; intuition.\nQed.\n\nLemma combine_fst_snd A B (pairs : list (A * B)) : List.combine (List.map fst pairs) (List.map snd pairs) = pairs.\nProof.\n  rewrite combine_map.\n  setoid_rewrite <- surjective_pairing.\n  rewrite map_id.\n  eauto.\nQed.\n\nLemma map_eq_length_eq : forall A B C (f1 : A -> B) ls1 (f2 : C -> B) ls2, map f1 ls1 = map f2 ls2 -> length ls1 = length ls2.\n  intros; assert (length (map f1 ls1) = length (map f2 ls2)) by congruence; repeat rewrite map_length in *; eauto.\nQed.\n\nLemma Forall_forall_1 A P (ls : list A) : Forall P ls -> (forall x, List.In x ls -> P x).\n  intros; eapply Forall_forall; eauto.\nQed.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Platform/Cito/ListFacts4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061854293322, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.20907009472448246}}
{"text": "Require Import Util MapDefined LengthEq Map CSet AutoIndTac AllInRel.\nRequire Import Var Val Exp Envs IL Sawtooth SimF BisimEq MoreCtxEq ILStateType.\n\nSet Implicit Arguments.\nUnset Printing Records.\n\n(** * Contextual Equivalence *)\n\nInductive stmtCtx : Type :=\n| ctxExp    (x : var) (e: exp) (C : stmtCtx) : stmtCtx\n| ctxIfS     (e : op) (C : stmtCtx) (t : stmt) : stmtCtx\n| ctxIfT     (e : op) (s : stmt) (C : stmtCtx) : stmtCtx\n(* block f Z : rt = s in b  *)\n| ctxLetS    (F1: list (params*stmt)) (Z:params) (C : stmtCtx) (F2: list (params*stmt)) (t : stmt) : stmtCtx\n| ctxLetT    (F: list (params*stmt)) (C : stmtCtx) : stmtCtx\n| ctxHole.\n\nFixpoint fill (ctx:stmtCtx) (s':stmt) : stmt :=\n  match ctx with\n    | ctxExp x e ctx => stmtLet x e (fill ctx s')\n    | ctxIfS e ctx t => stmtIf e (fill ctx s') t\n    | ctxIfT e s ctx => stmtIf e s (fill ctx s')\n    | ctxLetS F1 Z ctx F2 t => stmtFun (F1 ++ (Z,fill ctx s')::F2) t\n    | ctxLetT F ctx => stmtFun F (fill ctx s')\n    | ctxHole => s'\n  end.\n\nFixpoint fillC (ctx:stmtCtx) (s':stmtCtx) : stmtCtx :=\n  match ctx with\n    | ctxExp x e ctx => ctxExp x e (fillC ctx s')\n    | ctxIfS e ctx t => ctxIfS e (fillC ctx s') t\n    | ctxIfT e s ctx => ctxIfT e s (fillC ctx s')\n    | ctxLetS F1 Z ctx F2 t => ctxLetS F1 Z (fillC ctx s') F2 t\n    | ctxLetT F ctx => ctxLetT F (fillC ctx s')\n    | ctxHole => s'\n  end.\n\n(** ** Program Equivalence is contextual *)\n\nLemma simeq_contextual p s s' ctx\n: bisimeq bot3 p s s'\n  -> bisimeq bot3 p (fill ctx s) (fill ctx s').\nProof.\n  intros. general induction ctx; simpl; hnf; intros; eauto.\n  - destruct e.\n    + eapply (sim_let_op il_statetype_F); eauto.\n      intros. left. eapply IHctx; eauto.\n    + eapply (sim_let_call il_statetype_F); eauto.\n      intros. left. eapply IHctx; eauto.\n  - eapply (sim_cond il_statetype_F); eauto; intros; left.\n    + eapply IHctx; eauto.\n    + eapply bisimeq_refl; eauto.\n  - eapply (sim_cond il_statetype_F); eauto; intros; left.\n    + eapply bisimeq_refl; eauto.\n    + eapply IHctx; eauto.\n  - pone_step. left.\n    eapply bisimeq_refl; eauto 20 with len.\n    rewrite !map_app. intros.\n    eapply labenv_sim_extension_ptw; simpl; eauto 20 with len.\n    + intros; hnf; intros.\n      { destruct (get_subst _ _ _ H5) as [? |[?|?]].\n        - inv_get; simpl in *; dcr; subst.\n          inv_get.\n          eapply bisimeq_refl; eauto 20 with len.\n          rewrite !map_app. eauto.\n        - simpl in *. dcr; subst. subst. invc H9.\n          inv_get. simpl in *.\n          eapply bisimeq_bot; eauto with len.\n          rewrite !map_app. intros; eauto.\n        - simpl in *; dcr; subst.\n          inv_get. simpl in *.\n          eapply bisimeq_refl; eauto 20 with len.\n          rewrite !map_app; eauto.\n      }\n    + hnf; intros; simpl in *; subst; inv_get; simpl.\n      destruct (get_subst _ _ _ H4) as [? |[?|?]].\n      * inv_get; simpl in *; dcr; subst; eauto.\n      * dcr; subst. invc H5. inv_get; eauto with len.\n      * simpl in *; dcr; subst. inv_get; eauto.\n  - pone_step. left.\n    eapply IHctx; eauto with len.\n    rewrite !map_app. intros.\n    eapply labenv_sim_extension_ptw; simpl; eauto 20 with len.\n    + intros; hnf; simpl; intros; dcr; subst; inv_get. simpl in *.\n      eapply bisimeq_refl; eauto 20 with len.\n      rewrite !map_app; eauto.\n    + hnf; simpl; intros; subst; inv_get; simpl; eauto.\nQed.\n\nLemma fun_congrunence p F F' t t' (LEN:length F = length F')\n  : bisimeq bot3 p t t'\n    -> (forall n Z s Z' s', get F n (Z, s) -> get F' n (Z', s') -> Z = Z' /\\ bisimeq bot3 p s s')\n    -> bisimeq bot3 p (stmtFun F t) (stmtFun F' t').\nProof.\n  intros SIMt SIMF.\n  hnf; intros ? ? ? LAB Len.\n  eapply sim_fun_ptw; eauto using labenv_sim_refl.\n  - intros. left.\n    eapply bisimeq_bot; eauto with len.\n    rewrite !map_app in *; eauto.\n  - intros; hnf; intros.\n    hnf in H0; dcr; subst.\n    hnf in H4; dcr; subst. inv_get.\n    simpl in *. edestruct SIMF; eauto; subst.\n    eapply bisimeq_bot; eauto with len.\n    rewrite !map_app in *; eauto.\n  -  hnf; intros. simpl in *; subst. inv_get.\n     edestruct SIMF; dcr; eauto; subst.\n     eauto.\n  - eauto with len.\nQed.\n\nLemma fill_fillC C C' s\n  :  fill (fillC C C') s = fill C (fill C' s).\nProof.\n  general induction C; simpl; f_equal; eauto.\n  rewrite IHC; eauto.\nQed.\n\nDefinition lessDef (G:set var) (E E':onv val)\n  := forall x, x ∈ G -> E' x = None -> E x = None.\n\n\nFixpoint fix_vars (E:onv val) (xl: list var) : stmtCtx :=\n  match xl with\n  | x::xl =>\n    match E x with\n    | Some v => ctxExp x (Operation (Con v)) (fix_vars E xl)\n    | None => fix_vars E xl\n    end\n  | nil => ctxHole\n  end.\n\n\n\nLemma fix_vars_correct G E' xl E (LD:lessDef (of_list xl) E E') (ND:NoDupA eq xl)\n  : exists E'', (forall L s, star2 F.step (L, E, fill (fix_vars E' xl) s) nil (L, E'', s))\n           /\\ agree_on eq (of_list xl) E' E''\n           /\\ agree_on eq (G \\ of_list xl) E E''.\nProof.\n  general induction xl; simpl in * |- *; eauto 20 using star2_refl, agree_on_refl, agree_on_empty.\n  - cases; simpl; eauto.\n    + edestruct (IHxl {a; G}); dcr; swap 1 3.\n      eexists x; split.\n      * intros. eapply star2_silent; eauto. econstructor. reflexivity.\n      * split.\n        -- hnf; intros. cset_tac'. rewrite <- H3; lud; try cset_tac.\n           inv ND. cset_tac.\n        -- hnf; intros. cset_tac'.\n           rewrite <- H3; lud; eauto. cset_tac.\n      * eauto.\n      * hnf; intros. lud; eauto. congruence.\n        exploit LD; eauto. cset_tac.\n    + edestruct (IHxl {a; G}); swap 1 3; dcr.\n      eexists x; split; [|split]; eauto.\n      * hnf; intros. cset_tac'.\n        rewrite <- H3; eauto.\n        exploit LD; eauto. cset_tac.\n        congruence.\n        inv ND; cset_tac.\n      * eapply agree_on_incl; eauto.\n        cset_tac.\n      * eauto.\n      * hnf; intros; eapply LD; cset_tac.\nQed.\n\nLocal Notation EMP := (fun _ : positive => ⎣⎦).\n\nLemma tooth_smaller L\n  : tooth 0 L\n    -> smaller L.\nProof.\n  intros; hnf; intros.\n  change f with (0 + f).\n  revert H. generalize 0.\n  intros.\n  general induction H0; invt tooth; try omega.\n  eapply IHget in H4. omega.\nQed.\n\nLemma freeVarSimF_sim r t s E E'\n      (AG:agree_on eq (IL.freeVars s) E E')\n  : forall (L L' : 〔F.block〕),\n      labenv_sim t (sim r) SR (length (A:=positive) ⊝ F.block_Z ⊝ L') L L'\n      -> ❬L❭ = ❬L'❭\n      -> sim r t (L : F.labenv, E, s) (L', E', s).\nProof.\n  revert r E E' AG.\n  sind s; destruct s; simpl in *; intros.\n  - destruct e; simpl in *.\n    + eapply (sim_let_op il_statetype_F); intros.\n      * erewrite op_eval_agree; eauto.\n        symmetry.\n        eapply agree_on_incl; eauto.\n      * left. eapply IH; eauto.\n        eapply agree_on_update_same; eauto using agree_on_incl.\n    + eapply (sim_let_call il_statetype_F); intros.\n      * exploit omap_op_eval_agree; eauto using agree_on_incl.\n        symmetry.\n        eapply agree_on_incl; eauto.\n      * left. eapply IH; eauto.\n        eapply agree_on_update_same; eauto using agree_on_incl.\n  - eapply (sim_cond il_statetype_F); eauto.\n    + erewrite op_eval_agree; eauto.\n      symmetry.\n      eapply agree_on_incl; eauto.\n    + intros.\n      left. eapply IH; eauto using agree_on_incl with cset.\n    + intros.\n      left. eapply IH; eauto using agree_on_incl with cset.\n  - destruct (get_dec L' l) as [[? ?]|?].\n    + eapply labenv_sim_app; eauto using map_get_1.\n      intros; simpl in *; dcr; split; intros.\n      exploit omap_op_eval_agree; eauto using agree_on_incl.\n      eexists; repeat split; eauto. congruence. congruence.\n      destruct t; simpl. split; eauto; intros.\n      exploit omap_op_eval_agree; eauto using agree_on_incl. congruence.\n      eauto.\n      eauto.\n    + pno_step.\n  - pno_step. simpl.\n    erewrite op_eval_agree; symmetry; eauto using agree_on_incl with cset.\n  - eapply sim_fun_ptw with (AL':=length (A:=positive) ⊝ F.block_Z ⊝ mapi (F.mkBlock E') F);\n      try eapply H; eauto with len.\n    + intros.\n      left. eapply IH; eauto using agree_on_incl with cset.\n      rewrite !map_app. eauto. eauto with len.\n    + intros. hnf; intros. simpl in *. subst. inv_get; dcr; subst.\n      eapply IH; eauto.\n      eapply update_with_list_agree; eauto with len.\n      eapply agree_on_incl; eauto.\n      eapply incl_union_left.\n      eapply incl_list_union; eauto using map_get_1.\n      rewrite !map_app. eauto. eauto with len.\n    + hnf; intros; simpl in *. subst. inv_get; eauto.\nQed.\n\nArguments of_list : simpl never.\nArguments to_list : simpl never.\n\nLemma ctx_constr t L' (STL':sawtooth L')\n  : exists C LC, labenv_sim t (sim bot3) SR (@length _ ⊝ block_Z ⊝ L') LC L'\n            /\\ forall L s, star2 step (L, fun _ => None, fill C s) nil ((LC++L)%list, fun _ => None, s).\nProof.\n  intros. induction STL'.\n  - eexists ctxHole, nil; simpl.\n    split; eauto using star2_refl.\n  - destruct IHSTL' as [IHCR [IHLC [IHH1 IHH2]]]; eauto.\n    assert (CTXT:\n              exists F,\n                labenv_sim t (sim bot3) SR (length (A:=positive) ⊝ block_Z ⊝ (L ++ L'))\n                           (mapi (F.mkBlock (fun _ => ⎣⎦)) F ++ IHLC) (L ++ L')).\n    {\n      exists ((fun b => (F.block_Z b,\n                 fill (fix_vars (F.block_E b)\n                                (to_list (freeVars (F.block_s b) \\ of_list (F.block_Z b))))\n                      (F.block_s b))) ⊝ L).\n      rewrite !map_app.\n      eapply labenv_sim_extension_ptw'; eauto with len.\n      - hnf; intros. simpl in *.\n        hnf; intros. simpl in *. subst.\n        dcr; subst; inv_get. simpl in *.\n        edestruct fix_vars_correct; swap 1 3; dcr.\n        eapply sim_expansion_closed; [| eapply H2 | eapply star2_refl].\n        rewrite get_app_lt in H4. inv_get. simpl in *.\n        orewrite (i - i = 0); simpl.\n        exploit tooth_index; eauto. simpl in *.\n        orewrite (i - i' = 0); simpl.\n        rewrite <- !map_app in *.\n        eapply freeVarSimF_sim; eauto.\n        instantiate (1:=of_list Z') in H7.\n        assert (freeVars s' ⊆ of_list Z'  ∪ (freeVars s' \\ of_list Z')) by (clear; cset_tac).\n        eapply agree_on_incl; eauto.\n        eapply agree_on_union.\n        etransitivity. symmetry. eapply agree_on_incl; eauto.\n        rewrite of_list_3. clear; cset_tac.\n        eapply update_with_list_agree; eauto with len.\n        eapply agree_on_empty. clear; cset_tac.\n        eapply agree_on_update_list_dead.\n        rewrite of_list_3 in H6. symmetry. eauto.\n        clear. cset_tac.\n        len_simpl. destruct H0. len_simpl. eauto.\n        eauto with len. eapply nodup_to_list_eq.\n        hnf. intros. rewrite of_list_3 in H1.\n        rewrite lookup_set_update_not_in_Z; eauto.\n        cset_tac.\n      - rewrite <- !map_app.\n        hnf; intros; simpl in *.\n        destruct f, f'; simpl in *; subst.\n        inv_get. simpl in *. eauto.\n      - rewrite <- app_nil_r.\n        econstructor 2; eauto using @sawtooth.\n    }\n    destruct CTXT as [F TSIM].\n    eexists (fillC IHCR (ctxLetT F ctxHole)).\n    eexists (mapi (F.mkBlock (fun _ : positive => ⎣⎦)) F ++ IHLC).\n    split.\n    + eauto.\n    + intros.\n      rewrite !fill_fillC.\n      eapply star2_trans_silent; eauto. simpl.\n      eapply star2_silent. single_step.\n      rewrite app_assoc. eapply star2_refl.\nQed.\n\nDefinition ctxeq1 t s s' := forall C, bisimeq bot3 t (fill C s) (fill C s').\n\nLemma ctxeq_simeq1 t s s'\n  : ctxeq1 t s s' <-> bisimeq bot3 t s s'.\nProof.\n  split; intros; eauto.\n  - eapply (H ctxHole).\n  - hnf; intros.\n    eapply simeq_contextual. eauto.\nQed.\n\nDefinition ctxeq2 t s s' := forall C, sim bot3 t (nil:F.labenv, fun _ : positive => ⎣⎦, fill C s) (nil:F.labenv, fun _ : positive => ⎣⎦, fill C s').\n\n\nLemma ctxeq_simeq2 t s s'\n  : ctxeq2 t s s' <-> bisimeq bot3 t s s'.\nProof.\n  split; intros.\n  - hnf; intros L1 L2 E SIM Len.\n    edestruct (@fix_vars_correct ∅ E (to_list (freeVars s ∪ freeVars s')) EMP) as [E'' CCH].\n    hnf; intros; eauto. eapply nodup_to_list_eq.\n    destruct CCH as [RED [AGR1 AGR2]].\n    rewrite of_list_3 in AGR1.\n    rewrite of_list_3 in AGR2.\n    edestruct (ctx_constr Bisim) as [C1 [L1' [LC1 ?]]].\n    instantiate (1:=L2). eapply SIM.\n    set (CE:=(fix_vars E (to_list (freeVars s ∪ freeVars s')))).\n    exploit (H (fillC C1 CE)).\n    rewrite !fill_fillC in *.\n    eapply sim_reduction_closed in H1; swap 1 3; eauto.\n    eapply sim_reduction_closed in H1; swap 1 3; eauto.\n    rewrite app_nil_r in *.\n    assert (LC2:labenv_sim t (sim bot3) SR (length (A:=positive) ⊝ block_Z ⊝ L2) L1' L2). {\n      destruct LC1; dcr.\n      repeat (split; eauto). hnf; intros.\n      eapply bisim_sim; eauto.\n    }\n    eapply sim_trans with (S2:=F.state); swap 1 2.\n    + eapply (bisimeq_refl _ _ LC2).\n    + eapply sim_trans with (S2:=F.state); swap 1 2. {\n        instantiate (1:=(L1', E'', s')).\n        eapply freeVarSimF_sim.\n        symmetry. eauto using agree_on_incl with cset.\n        eapply labenv_sim_refl. eapply LC1. reflexivity.\n      }\n      eapply sim_trans with (S2:=F.state); swap 1 2; eauto.\n      eapply sim_trans with (S2:=F.state). {\n        instantiate (1:=(L1, E'', s)).\n        eapply freeVarSimF_sim.\n        eauto using agree_on_incl with cset.\n        eapply labenv_sim_refl. eapply SIM. reflexivity.\n      }\n      eapply sim_trans with (S2:=F.state). {\n        eapply (bisimeq_refl _ _ SIM).\n      }\n      assert (sim bot3 Bisim (L2, E'', s) (L1', E'', s)). {\n        eapply @bisim_sym.\n        eapply (bisimeq_refl). eauto.\n      }\n      eapply bisim_sim; eauto.\n  - hnf; intros.\n    eapply simeq_contextual with (ctx:=C) in H.\n    exploit (H nil nil); simpl; eauto using labenv_sim_nil.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Equiv/CtxEq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.20907008854238526}}
{"text": "From Coq Require Import Arith.Arith.\n\nFrom Elo Require Import Util.\nFrom Elo Require Import Array.\nFrom Elo Require Import Map.\nFrom Elo Require Import Core.\nFrom Elo Require Import Access.\nFrom Elo Require Import UnsafeAccess.\n\n(* ------------------------------------------------------------------------- *)\n(* NotMut                                                                    *)\n(* ------------------------------------------------------------------------- *)\n\n(* A term is NoMut if it has no mutable references. *)\nInductive NoMut : tm -> Prop :=\n  | nomut_unit :\n    NoMut <{ unit }>\n\n  | nomut_num : forall n,\n    NoMut <{ N n }>\n\n  | nomut_refI : forall ad T,\n    NoMut <{ &ad :: i&T }>\n\n  | nomut_new : forall T t,\n    NoMut t ->\n    NoMut <{ new T t }>\n\n  | nomut_load : forall t,\n    NoMut t ->\n    NoMut <{ *t }>\n\n  | nomut_asg : forall t1 t2,\n    NoMut t1 ->\n    NoMut t2 ->\n    NoMut <{ t1 = t2 }>\n\n  | nomut_var : forall x,\n    NoMut <{ var x }>\n\n  | nomut_fun : forall x Tx t,\n    NoMut t ->\n    NoMut <{ fn x Tx --> t }>\n\n  | nomut_call : forall t1 t2,\n    NoMut t1 ->\n    NoMut t2 ->\n    NoMut <{ call t1 t2 }>\n\n  | nomut_seq : forall t1 t2,\n    NoMut t1 ->\n    NoMut t2 ->\n    NoMut <{ t1; t2 }>\n\n  | nomut_spawn : forall t,\n    NoMut t ->\n    NoMut <{ spawn t }>\n  .\n\nLtac inversion_nomut :=\n  match goal with\n  | H : NoMut <{ unit         }> |- _ => inversion H; subst\n  | H : NoMut <{ N _          }> |- _ => inversion H; subst\n  | H : NoMut <{ & _ :: _     }> |- _ => inversion H; subst\n  | H : NoMut <{ new _ _      }> |- _ => inversion H; subst\n  | H : NoMut <{ * _          }> |- _ => inversion H; subst\n  | H : NoMut <{ _ = _        }> |- _ => inversion H; subst\n  | H : NoMut <{ var _        }> |- _ => inversion H; subst\n  | H : NoMut <{ fn _ _ --> _ }> |- _ => inversion H; subst\n  | H : NoMut <{ call _ _     }> |- _ => inversion H; subst\n  | H : NoMut <{ _ ; _        }> |- _ => inversion H; subst\n  | H : NoMut <{ spawn _      }> |- _ => inversion H; subst\n  end.\n\nLtac inversion_clear_nomut :=\n  match goal with\n  | H : NoMut <{ unit         }> |- _ => inversion_subst_clear H\n  | H : NoMut <{ N _          }> |- _ => inversion_subst_clear H\n  | H : NoMut <{ & _ :: _     }> |- _ => inversion_subst_clear H\n  | H : NoMut <{ new _ _      }> |- _ => inversion_subst_clear H\n  | H : NoMut <{ * _          }> |- _ => inversion_subst_clear H\n  | H : NoMut <{ _ = _        }> |- _ => inversion_subst_clear H\n  | H : NoMut <{ var _        }> |- _ => inversion_subst_clear H\n  | H : NoMut <{ fn _ _ --> _ }> |- _ => inversion_subst_clear H\n  | H : NoMut <{ call _ _     }> |- _ => inversion_subst_clear H\n  | H : NoMut <{ _ ; _        }> |- _ => inversion_subst_clear H\n  | H : NoMut <{ spawn _      }> |- _ => inversion_subst_clear H\n  end.\n\nLocal Lemma nomut_subst : forall x t t',\n  NoMut t ->\n  NoMut t' ->\n  NoMut ([x := t'] t).\nProof.\n  intros. induction t; intros;\n  inversion_nomut; eauto using NoMut;\n  simpl; destruct String.string_dec; subst; eauto using NoMut. \nQed.\n\n(* ------------------------------------------------------------------------- *)\n(* SafeSpawns                                                                *)\n(* ------------------------------------------------------------------------- *)\n\n(* A term has safe spawns if all of its spawns have no mutable references. *)\nInductive SafeSpawns : tm -> Prop :=\n  | safe_spawns_unit :\n      SafeSpawns <{ unit }>\n\n  | safe_spawns_num : forall n,\n      SafeSpawns <{ N n }>\n\n  | safe_spawns_ref : forall ad T,\n      SafeSpawns <{ &ad :: T }>\n\n  | safe_spawns_new : forall T t,\n      SafeSpawns t ->\n      SafeSpawns <{ new T t }>\n\n  | safe_spawns_load : forall t,\n      SafeSpawns t ->\n      SafeSpawns <{ *t }>\n\n  | safe_spawns_asg : forall t1 t2,\n      SafeSpawns t1 ->\n      SafeSpawns t2 ->\n      SafeSpawns <{ t1 = t2 }>\n\n  | safe_spawns_var : forall x,\n      SafeSpawns <{ var x }>\n\n  | safe_spawns_fun : forall x Tx t,\n      SafeSpawns t ->\n      SafeSpawns <{ fn x Tx --> t }>\n\n  | safe_spawns_call : forall t1 t2,\n      SafeSpawns t1 ->\n      SafeSpawns t2 ->\n      SafeSpawns <{ call t1 t2 }>\n\n  | safe_spawns_seq : forall t1 t2,\n      SafeSpawns t1 ->\n      SafeSpawns t2 ->\n      SafeSpawns <{ t1; t2 }>\n\n  | safe_spawns_spawn : forall t,\n      NoMut t ->\n      SafeSpawns <{ spawn t }>\n  .\n\nLtac inversion_ss :=\n  match goal with\n  | H : SafeSpawns <{ unit         }> |- _ => inversion H; subst\n  | H : SafeSpawns <{ N _          }> |- _ => inversion H; subst\n  | H : SafeSpawns <{ & _ :: _     }> |- _ => inversion H; subst\n  | H : SafeSpawns <{ new _ _      }> |- _ => inversion H; subst\n  | H : SafeSpawns <{ * _          }> |- _ => inversion H; subst\n  | H : SafeSpawns <{ _ = _        }> |- _ => inversion H; subst\n  | H : SafeSpawns <{ var _        }> |- _ => inversion H; subst\n  | H : SafeSpawns <{ fn _ _ --> _ }> |- _ => inversion H; subst\n  | H : SafeSpawns <{ call _ _     }> |- _ => inversion H; subst\n  | H : SafeSpawns <{ _ ; _        }> |- _ => inversion H; subst\n  | H : SafeSpawns <{ spawn _      }> |- _ => inversion H; subst\n  end.\n\nLtac inversion_clear_ss :=\n  match goal with\n  | H : SafeSpawns <{ unit         }> |- _ => inversion_subst_clear H\n  | H : SafeSpawns <{ N _          }> |- _ => inversion_subst_clear H\n  | H : SafeSpawns <{ & _ :: _     }> |- _ => inversion_subst_clear H\n  | H : SafeSpawns <{ new _ _      }> |- _ => inversion_subst_clear H\n  | H : SafeSpawns <{ * _          }> |- _ => inversion_subst_clear H\n  | H : SafeSpawns <{ _ = _        }> |- _ => inversion_subst_clear H\n  | H : SafeSpawns <{ var _        }> |- _ => inversion_subst_clear H\n  | H : SafeSpawns <{ fn _ _ --> _ }> |- _ => inversion_subst_clear H\n  | H : SafeSpawns <{ call _ _     }> |- _ => inversion_subst_clear H\n  | H : SafeSpawns <{ _ ; _        }> |- _ => inversion_subst_clear H\n  | H : SafeSpawns <{ spawn _      }> |- _ => inversion_subst_clear H\n  end.\n\n(* ------------------------------------------------------------------------- *)\n(* HasVar                                                                    *)\n(* ------------------------------------------------------------------------- *)\n\nInductive HasVar (x : id) : tm  -> Prop :=\n  | hasvar_new : forall T t,\n      HasVar x t ->\n      HasVar x <{ new T t }>\n\n  | hasvar_load : forall t,\n      HasVar x t ->\n      HasVar x <{ *t }>\n\n  | hasvar_asg1 : forall t1 t2,\n      HasVar x t1 ->\n      HasVar x <{ t1 = t2 }>\n\n  | hasvar_asg2 : forall t1 t2,\n      HasVar x t2 ->\n      HasVar x <{ t1 = t2 }>\n\n  | hasvar_var :\n      HasVar x <{ var x }>\n\n  | hasvar_fun : forall x' Tx t,\n      x <> x' ->\n      HasVar x t ->\n      HasVar x <{ fn x' Tx --> t }>\n\n  | hasvar_call1 : forall t1 t2,\n      HasVar x t1 ->\n      HasVar x <{ call t1 t2 }>\n\n  | hasvar_call2 : forall t1 t2,\n      HasVar x t2 ->\n      HasVar x <{ call t1 t2 }>\n\n  | hasvar_seq1 : forall t1 t2,\n      HasVar x t1 ->\n      HasVar x <{ t1; t2 }>\n\n  | hasvar_seq2 : forall t1 t2,\n      HasVar x t2 ->\n      HasVar x <{ t1; t2 }>\n\n  | hasvar_spawn : forall t,\n      HasVar x t ->\n      HasVar x <{ spawn t }>\n  .\n\nLtac inversion_hv :=\n  match goal with\n  | H : HasVar _ <{ unit         }> |- _ => inversion H; subst\n  | H : HasVar _ <{ N _          }> |- _ => inversion H; subst\n  | H : HasVar _ <{ & _ :: _     }> |- _ => inversion H; subst\n  | H : HasVar _ <{ new _ _      }> |- _ => inversion H; subst\n  | H : HasVar _ <{ * _          }> |- _ => inversion H; subst\n  | H : HasVar _ <{ _ = _        }> |- _ => inversion H; subst\n  | H : HasVar _ <{ var _        }> |- _ => inversion H; subst\n  | H : HasVar _ <{ fn _ _ --> _ }> |- _ => inversion H; subst\n  | H : HasVar _ <{ call _ _     }> |- _ => inversion H; subst\n  | H : HasVar _ <{ _ ; _        }> |- _ => inversion H; subst\n  | H : HasVar _ <{ spawn _      }> |- _ => inversion H; subst\n  end.\n\nLtac inversion_clear_hv :=\n  match goal with\n  | H : HasVar _ <{ unit         }> |- _ => inversion_subst_clear H\n  | H : HasVar _ <{ N _          }> |- _ => inversion_subst_clear H\n  | H : HasVar _ <{ & _ :: _     }> |- _ => inversion_subst_clear H\n  | H : HasVar _ <{ new _ _      }> |- _ => inversion_subst_clear H\n  | H : HasVar _ <{ * _          }> |- _ => inversion_subst_clear H\n  | H : HasVar _ <{ _ = _        }> |- _ => inversion_subst_clear H\n  | H : HasVar _ <{ var _        }> |- _ => inversion_subst_clear H\n  | H : HasVar _ <{ fn _ _ --> _ }> |- _ => inversion_subst_clear H\n  | H : HasVar _ <{ call _ _     }> |- _ => inversion_subst_clear H\n  | H : HasVar _ <{ _ ; _        }> |- _ => inversion_subst_clear H\n  | H : HasVar _ <{ spawn _      }> |- _ => inversion_subst_clear H\n  end.\n\nLemma hasvar_dec : forall x t,\n  Decidable.decidable (HasVar x t).\nProof.\n  unfold Decidable.decidable. intros. induction t;\n  try (destruct IHt); try (destruct IHt1); try (destruct IHt2);\n  try match goal with\n    | x : id, x' : id |- _ =>\n      destruct (String.string_dec x x'); subst\n  end;\n  solve\n    [ left; eauto using HasVar\n    | right; intros F; inversion_subst_clear F; eauto; contradiction\n    ].\nQed.\n\nLocal Ltac solve_not_hasvar :=\n  intros; match goal with\n  | |- (~ HasVar _ ?t) => induction t; eauto using HasVar\n  end.\n\nLemma not_hv_new : forall x t T,\n  ~ HasVar x <{ new T t }> -> ~ HasVar x t.\nProof. solve_not_hasvar. Qed.\n\nLemma not_hv_load : forall x t,\n  ~ HasVar x <{ *t }> -> ~ HasVar x t.\nProof. solve_not_hasvar. Qed.\n\nLemma not_hv_asg1 : forall x t1 t2,\n  ~ HasVar x <{ t1 = t2 }> -> ~ HasVar x t1.\nProof. solve_not_hasvar. Qed.\n\nLemma not_hv_asg2 : forall x t1 t2,\n  ~ HasVar x <{ t1 = t2 }> -> ~ HasVar x t2.\nProof. solve_not_hasvar. Qed.\n\nLemma not_hv_fun : forall x x' t Tx,\n  x <> x' -> ~ HasVar x <{ fn x' Tx --> t }> -> ~ HasVar x t.\nProof. solve_not_hasvar. Qed.\n\nLemma not_hv_call1 : forall x t1 t2,\n  ~ HasVar x <{ call t1 t2 }> -> ~ HasVar x t1.\nProof. solve_not_hasvar. Qed.\n\nLemma not_hv_call2 : forall x t1 t2,\n  ~ HasVar x <{ call t1 t2 }> -> ~ HasVar x t2.\nProof. solve_not_hasvar. Qed.\n\nLemma not_hv_seq1 : forall x t1 t2,\n  ~ HasVar x <{ t1; t2 }> -> ~ HasVar x t1.\nProof. solve_not_hasvar. Qed.\n\nLemma not_hv_seq2 : forall x t1 t2,\n  ~ HasVar x <{ t1; t2 }> -> ~ HasVar x t2.\nProof. solve_not_hasvar. Qed.\n\nLemma not_hv_spawn : forall x t,\n  ~ HasVar x <{ spawn t }> -> ~ HasVar x t.\nProof. solve_not_hasvar. Qed.\n\nLemma hasvar_subst : forall x t tx,\n  ~ (HasVar x t) -> ([x := tx] t) = t.\nProof.\n  intros. induction t; simpl; trivial;\n  try (destruct String.string_dec; subst; trivial);\n  solve\n    [ rewrite IHt; eauto using not_hv_new, not_hv_load, not_hv_spawn, not_hv_fun\n    | rewrite IHt1; eauto using not_hv_asg1, not_hv_call1, not_hv_seq1;\n      rewrite IHt2; eauto using not_hv_asg2, not_hv_call2, not_hv_seq2\n    | exfalso; eauto using HasVar\n    ].\nQed.\n\nLemma hasvar_typing : forall Gamma x t T,\n  HasVar x t ->\n  Gamma x = None ->\n  ~ (Gamma |-- t is T).\nProof.\n  assert (forall Gamma x, Gamma x = None -> (safe Gamma) x = None).\n  { unfold safe. intros * H. rewrite H. reflexivity. }\n  intros * ? HGamma F. induction_type; inversion_hv; eauto.\n  - rewrite HGamma in *. discriminate.\n  - rewrite lookup_update_neq in IHF; eauto.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n(* Equivalence                                                               *)\n(* ------------------------------------------------------------------------- *)\n\nLocal Lemma equivalence_safe : forall Gamma1 Gamma2,\n  Gamma1 === Gamma2 ->\n  safe Gamma1 === safe Gamma2.\nProof.\n  unfold map_equivalence, safe. intros * Heq k.\n  specialize (Heq k). rewrite Heq. trivial.\nQed.\n\nLocal Lemma equivalence_typing : forall Gamma1 Gamma2 t T,\n  Gamma1 === Gamma2 ->\n  Gamma1 |-- t is T ->\n  Gamma2 |-- t is T.\nProof.\n  intros. generalize dependent Gamma2. induction_type; intros;\n  eauto using well_typed_term, equivalence_safe,\n    MapEquivalence.lookup, MapEquivalence.update_equivalence.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n(* SafeSpawns mstep term preservation                                        *)\n(* ------------------------------------------------------------------------- *)\n\nLocal Lemma safe_spawns_subst : forall Gamma x t v T Tx,\n  value v ->\n  empty |-- v is Tx ->\n  Gamma[x <== Tx] |-- t is T ->\n  SafeSpawns v ->\n  SafeSpawns t ->\n  SafeSpawns ([x := v] t).\nProof.\n  assert (H1 : forall Gamma x T,\n    (safe Gamma[x <== <{{ &T }}>]) x = None);\n  assert (H2 : forall Gamma x T T',\n    (safe Gamma[x <== <{{ T --> T' }}>]) x = None);\n  try solve [unfold safe; intros; rewrite lookup_update_eq; reflexivity].\n  (* main proof *)\n  intros * Hvalue HtypeV HtypeT Hssv Hsst.\n  generalize dependent Gamma. generalize dependent T. generalize dependent Tx.\n  induction Hsst; intros; inversion_type;\n  simpl; try (destruct String.string_dec);\n  eauto using SafeSpawns, equivalence_typing, MapEquivalence.update_permutation.\n  eapply safe_spawns_spawn. destruct (hasvar_dec x t).\n  - eapply nomut_subst; trivial.\n    inversion Hvalue; subst; eauto using NoMut.\n    + inversion HtypeV; subst; eauto using NoMut.\n      exfalso. eapply hasvar_typing; eauto using H1.\n    + inversion_clear Hvalue. inversion HtypeV; subst.\n      exfalso. eapply hasvar_typing; eauto using H2. \n  - erewrite hasvar_subst; eauto.\nQed.\n\nLocal Lemma mstep_tm_safe_spawns_preservation : forall m m' t t' eff T,\n  empty |-- t is T ->\n  forall_memory m SafeSpawns ->\n  SafeSpawns t ->\n  m / t ==[eff]==> m' / t' ->\n  SafeSpawns t'.\nProof.\n  intros. generalize dependent T.\n  inversion_clear_mstep; induction_step; intros;\n  try solve [inversion_type; inversion_ss; eauto using SafeSpawns].\n  do 2 (inversion_ss; inversion_type).\n  eauto using safe_spawns_subst.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n(* SafeSpawns mstep memory preservation                                      *)\n(* ------------------------------------------------------------------------- *)\n\nLocal Lemma mem_safe_spawns_alloc : forall m t t' v V,\n  forall_memory m SafeSpawns ->\n  SafeSpawns t ->\n  t --[EF_Alloc (length m) v V]--> t' ->\n  forall_memory (m +++ (v, V)) SafeSpawns.\nProof.\n  intros. assert (SafeSpawns v) by (induction_step; inversion_ss; eauto).\n  unfold forall_memory. eauto using forall_array_add, SafeSpawns.\nQed.\n\nLocal Lemma mem_safe_spawns_store : forall m t t' ad v V,\n  forall_memory m SafeSpawns ->\n  SafeSpawns t ->\n  t --[EF_Write ad v V]--> t' ->\n  forall_memory m[ad <- (v, V)] SafeSpawns.\nProof.\n  intros. assert (SafeSpawns v) by (induction_step; inversion_ss; eauto).\n  unfold forall_memory. eauto using forall_array_set, SafeSpawns.\nQed.\n\nLocal Lemma mstep_mem_safe_spawns_preservation : forall m m' t t' eff,\n  forall_memory m SafeSpawns ->\n  SafeSpawns t ->\n  m / t ==[eff]==> m' / t' ->\n  forall_memory m' SafeSpawns.\nProof.\n  intros. inversion_mstep;\n  eauto using mem_safe_spawns_alloc, mem_safe_spawns_store.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n(* SafeSpawns cstep preservation                                             *)\n(* ------------------------------------------------------------------------- *)\n\nLocal Lemma nomut_then_safe_spawns : forall t,\n  NoMut t ->\n  SafeSpawns t.\nProof.\n  intros * H. induction t; induction H; eauto using SafeSpawns.\nQed.\n\nLocal Lemma safe_spawns_for_block : forall t t' block,\n  SafeSpawns t ->\n  t --[EF_Spawn block]--> t' ->\n  SafeSpawns block.\nProof.\n  intros. induction_step; inversion_ss;\n  eauto using SafeSpawns, nomut_then_safe_spawns.\nQed.\n\nLocal Lemma step_safe_spawns_preservation : forall t t' block,\n  SafeSpawns t ->\n  t --[EF_Spawn block]--> t' ->\n  SafeSpawns t'.\nProof.\n  intros. induction_step; inversion_ss;\n  eauto using SafeSpawns, nomut_then_safe_spawns.\nQed.\n\nTheorem safe_spawns_preservation : forall m m' ths ths' tid eff,\n  forall_threads ths well_typed ->\n  forall_program m ths SafeSpawns ->\n  m / ths ~~[tid, eff]~~> m' / ths' ->\n  forall_program m' ths' SafeSpawns.\nProof.\n  intros * Htype [? ?]. split; inversion_cstep;\n  eauto using mstep_mem_safe_spawns_preservation.\n  - eapply forall_array_set;\n    eauto using SafeSpawns. specialize (Htype tid) as [? ?].\n    eauto using mstep_tm_safe_spawns_preservation. (* performance *)\n  - eapply forall_array_add; eauto using SafeSpawns, safe_spawns_for_block.\n    eapply forall_array_set;\n    eauto using SafeSpawns, step_safe_spawns_preservation.\nQed.\n\n(* ------------------------------------------------------------------------- *)\n(*                                                                           *)\n(* ------------------------------------------------------------------------- *)\n\nLemma nomut_block : forall t t' block,\n  SafeSpawns t ->\n  t --[EF_Spawn block]--> t' ->\n  NoMut block.\nProof.\n  intros. induction_step; inversion_ss; eauto.\nQed.\n\nLemma nomut_then_nuacc: forall m t ad,\n  NoMut t ->\n  UnsafeAccess m t ad ->\n  False.\nProof.\n  intros * Hnm Huacc. induction Hnm; inversion_uacc; eauto.\nQed.\n\n", "meta": {"author": "renan061", "repo": "elo-coq", "sha": "af650eba66cfc81b2efb5cd44301a7f08f5e4a32", "save_path": "github-repos/coq/renan061-elo-coq", "path": "github-repos/coq/renan061-elo-coq/elo-coq-af650eba66cfc81b2efb5cd44301a7f08f5e4a32/SafeSpawns.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.20907008854238526}}
{"text": "(*! Inversion lemmata for ETT *)\n\nFrom Coq Require Import Bool String List BinPos Compare_dec Lia.\nRequire Import Equations.Prop.DepElim.\nFrom Equations Require Import Equations.\nFrom Translation\nRequire Import util Sorts SAst SLiftSubst SCommon ITyping ITypingLemmata\n               XTyping.\n\nOpen Scope x_scope.\n\n(* We prove these lemmata in the context of Type in Type\n   as they will only be used for examples.\n *)\nExisting Instance Sorts.type_in_type.\n\nNotation Ty := (@sSort Sorts.type_in_type tt).\n\nLemma inversionProd :\n  forall {Σ Γ n A B T},\n    Σ ;;; Γ |-x sProd n A B : T ->\n    (Σ ;;; Γ |-x A : Ty) *\n    (Σ ;;; Γ ,, A |-x B : Ty) *\n    (Σ ;;; Γ |-x Ty ≡ T : Ty).\nProof.\n  intros Σ Γ n A B T h.\n  dependent induction h.\n  - destruct s1, s2.\n    split ; [ split | ..] ; try assumption.\n    apply eq_reflexivity. econstructor.\n  - destruct IHh1 as [[? ?] ?].\n    destruct s.\n    split ; [ split | ..] ; try assumption.\n    eapply eq_transitivity ; eassumption.\nDefined.", "meta": {"author": "TheoWinterhalter", "repo": "ett-to-itt", "sha": "b77534bf62673292da2139639f081cad4721a383", "save_path": "github-repos/coq/TheoWinterhalter-ett-to-itt", "path": "github-repos/coq/TheoWinterhalter-ett-to-itt/ett-to-itt-b77534bf62673292da2139639f081cad4721a383/theories/XInversions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.38491213742809105, "lm_q1q2_score": 0.20895467235064638}}
{"text": "Require Import Mem.\nRequire Import Pred.\nRequire Import Prog.\nRequire Import ListPred.\nRequire Import List.\nRequire Import SepAuto.\nRequire Import Array.\nRequire Import Omega.\nRequire Import AsyncDisk PredCrash.\nRequire Import FunctionalExtensionality.\n\n\nSet Implicit Arguments.\nSet Default Proof Using \"Type\".\n\nSection MemPred.\n\n  Variable LowAT : Type.\n  Variable LowAEQ : EqDec LowAT.\n  Variable LowV : Type.\n\n  Variable HighAT : Type.\n  Variable HighAEQ : EqDec HighAT.\n  Variable HighV : Type.\n\n  Definition low_mem := @mem LowAT LowAEQ LowV.\n  Definition high_mem := @mem HighAT HighAEQ HighV.\n\n  Definition low_pred := @pred LowAT LowAEQ LowV.\n  Definition high_pred := @pred HighAT HighAEQ HighV.\n\n\n  Fixpoint avs2mem_iter (avs : list (HighAT * HighV)) (m : @mem HighAT HighAEQ HighV) :=\n    match avs with\n    | nil => m\n    | (a, v) :: rest =>\n      upd (avs2mem_iter rest m) a v\n    end.\n\n  Definition avs2mem avs :=\n    avs2mem_iter avs empty_mem.\n\n  Fixpoint avs_except avs victim : @list (HighAT * HighV) :=\n    match avs with\n    | nil => nil\n    | (a, v) :: rest =>\n      if HighAEQ a victim then avs_except rest victim else (a, v) :: avs_except rest victim\n    end.\n\n  Theorem avs_except_notin_eq : forall avs a,\n    ~ In a (map fst avs) -> avs_except avs a = avs.\n  Proof.\n    induction avs; simpl; intros; auto.\n    destruct a; intuition.\n    destruct (HighAEQ h a0); subst. intuition.\n    f_equal; eauto.\n  Qed.\n\n  Theorem avs_except_cons : forall avs a v,\n    NoDup (map fst ((a, v) :: avs)) ->\n    avs_except ((a, v) :: avs) a = avs.\n  Proof.\n    intros; simpl.\n    destruct (HighAEQ a a); try congruence.\n    apply avs_except_notin_eq.\n    inversion H; auto.\n  Qed.\n\n  Theorem avs2mem_ne : forall avs a v a',\n    a <> a' ->\n    avs2mem ((a, v) :: avs) a' = avs2mem avs a'.\n  Proof.\n    unfold avs2mem; simpl; intros.\n    rewrite upd_ne; auto.\n  Qed.\n\n  Theorem listpred_avs_except : forall avs (lp : _ -> low_pred) a v,\n    NoDup (map fst avs) ->\n    avs2mem avs a = Some v ->\n    listpred lp avs =p=> listpred lp (avs_except avs a) * lp (a, v).\n  Proof.\n    induction avs; simpl; intros.\n    - inversion H0.\n    - destruct a.\n      destruct (HighAEQ h a0); subst.\n      + unfold avs2mem in H0; simpl in H0. rewrite upd_eq in H0 by auto. inversion H0; subst.\n        inversion H.\n        rewrite avs_except_notin_eq by auto. cancel.\n      + inversion H.\n        rewrite avs2mem_ne in H0 by auto.\n        rewrite IHavs by eauto.\n        cancel.\n  Qed.\n\n  Theorem avs_except_notin : forall avs a a',\n    ~ In a' (map fst avs) -> ~ In a' (map fst (avs_except avs a)).\n  Proof.\n    induction avs; simpl; intros; eauto.\n    destruct a.\n    destruct (HighAEQ h a0); subst; eauto.\n    simpl in *; intuition; eauto.\n  Qed.\n\n  Hint Resolve avs_except_notin.\n\n  Lemma avs2mem_notindomain : forall l a,\n    ~ In a (map fst l) ->\n    notindomain a (avs2mem l).\n  Proof.\n    unfold avs2mem, notindomain; induction l; simpl; intros.\n    cbv; auto.\n    destruct a; simpl in *; intuition.\n    rewrite upd_ne; auto.\n  Qed.\n\n  Theorem avs_except_nodup : forall avs a,\n    NoDup (map fst avs) -> NoDup (map fst (avs_except avs a)).\n  Proof.\n    induction avs; simpl; intros; eauto.\n    destruct a.\n    inversion H; subst.\n    destruct (HighAEQ h a0); subst; eauto.\n    simpl; constructor; eauto.\n  Qed.\n\n  Hint Resolve avs_except_nodup.\n\n  Lemma avs2mem_except_eq : forall avs a,\n    avs2mem (avs_except avs a) a = None.\n  Proof.\n    induction avs; simpl; intros; eauto.\n    destruct a.\n    destruct (HighAEQ h a0); subst; eauto.\n    rewrite avs2mem_ne by auto; auto.\n  Qed.\n\n  Lemma avs2mem_except_ne : forall avs a a',\n    a <> a' ->\n    avs2mem (avs_except avs a) a' = avs2mem avs a'.\n  Proof.\n    induction avs; simpl; intros; eauto.\n    destruct a.\n    destruct (HighAEQ h a0); subst.\n    - rewrite avs2mem_ne; auto.\n    - unfold avs2mem in *; simpl.\n      destruct (HighAEQ h a'); subst.\n      + repeat rewrite upd_eq; auto.\n      + repeat rewrite upd_ne; auto.\n  Qed.\n\n  Theorem mem_except_avs_except : forall avs a,\n    mem_except (avs2mem avs) a = avs2mem (avs_except avs a).\n  Proof.\n    intros; apply functional_extensionality; intros.\n    destruct (HighAEQ a x); subst.\n    - rewrite mem_except_eq. rewrite avs2mem_except_eq. auto.\n    - rewrite mem_except_ne by auto.\n      rewrite avs2mem_except_ne by auto.\n      auto.\n  Qed.\n\n  Hint Resolve mem_except_avs_except.\n\n  Lemma avs2mem_none_notin : forall avs a,\n    avs2mem avs a = None -> ~ In a (map fst avs).\n  Proof.\n    unfold avs2mem; induction avs; simpl; intros; auto.\n    destruct a; intuition; simpl in *; subst.\n    rewrite upd_eq in * by auto; congruence.\n    destruct (HighAEQ h a0); subst.\n    rewrite upd_eq in * by auto; congruence.\n    rewrite upd_ne in * by auto; eauto.\n  Qed.\n\n  Variable Pred : HighAT -> HighV -> low_pred.\n\n  Definition mem_pred_one (av : HighAT * HighV) : low_pred :=\n    Pred (fst av) (snd av).\n\n  Definition mem_pred (hm : high_mem) : low_pred :=\n    (exists hm_avs,\n     [[ NoDup (map fst hm_avs) ]] *\n     [[ hm = avs2mem hm_avs ]] *\n     listpred mem_pred_one hm_avs)%pred.\n\n  Theorem mem_pred_extract' : forall hm a v,\n    hm a = Some v ->\n    mem_pred hm =p=> mem_pred (mem_except hm a) * mem_pred_one (a, v).\n  Proof.\n    unfold mem_pred; intros.\n    cancel.\n    eapply listpred_avs_except; subst; eauto.\n    eauto.\n  Qed.\n\n  Theorem mem_pred_extract : forall hm a v,\n    hm a = Some v ->\n    mem_pred hm =p=> mem_pred (mem_except hm a) * Pred a v.\n  Proof.\n    apply mem_pred_extract'.\n  Qed.\n\n  Theorem mem_pred_absorb' : forall hm a v,\n    mem_pred (mem_except hm a) * mem_pred_one (a, v) =p=> mem_pred (upd hm a v).\n  Proof.\n    unfold mem_pred; intros.\n    norml.\n    exists ((a, v) :: hm_avs).\n    pred_apply.\n    cancel.\n    simpl; constructor; auto.\n    apply avs2mem_none_notin.\n    rewrite <- H3. apply mem_except_eq.\n    unfold avs2mem in *; simpl.\n    rewrite <- H3.\n    rewrite upd_mem_except.\n    auto.\n  Qed.\n\n  Theorem mem_pred_absorb : forall hm a v,\n    mem_pred (mem_except hm a) * Pred a v =p=> mem_pred (upd hm a v).\n  Proof.\n    apply mem_pred_absorb'.\n  Qed.\n\n  Theorem mem_pred_absorb_nop' : forall hm a v,\n    hm a = Some v ->\n    mem_pred (mem_except hm a) * mem_pred_one (a, v) =p=> mem_pred hm.\n  Proof.\n    unfold mem_pred; intros.\n    norml.\n    exists ( (a, v) :: hm_avs).\n    pred_apply.\n    cancel.\n    simpl; constructor; auto.\n    apply avs2mem_none_notin.\n    rewrite <- H4. apply mem_except_eq.\n    unfold avs2mem in *; simpl.\n    rewrite <- H4.\n    rewrite upd_mem_except.\n    rewrite upd_nop; auto.\n  Qed.\n\n  Theorem mem_pred_absorb_nop : forall hm a v,\n    hm a = Some v ->\n    mem_pred (mem_except hm a) * Pred a v =p=> mem_pred hm.\n  Proof.\n    apply mem_pred_absorb_nop'.\n  Qed.\n\n  Theorem mem_pred_empty_mem :\n    mem_pred empty_mem <=p=> emp.\n  Proof.\n    unfold mem_pred, mem_pred_one, avs2mem; split; norm; auto.\n    destruct hm_avs; try cancel.\n    eapply equal_f with (x := p_1) in H2.\n    rewrite upd_eq in H2 by auto.\n    unfold empty_mem in H2; congruence.\n    instantiate (1 := nil); cancel.\n    intuition; constructor.\n  Qed.\n\nEnd MemPred.\n\nTheorem mem_pred_pimpl : forall LA LEQ LV HA HEQ HV hm p1 p2,\n  (forall a v, p1 a v =p=> p2 a v) ->\n  @mem_pred LA LEQ LV HA HEQ HV p1 hm =p=> mem_pred p2 hm.\nProof.\n  unfold mem_pred; intros.\n  cancel; eauto.\n  subst.\n  induction hm_avs; simpl; intros; auto.\n  unfold mem_pred_one at 1 3; simpl. rewrite H. cancel.\n  eapply IHhm_avs.\n  inversion H0; eauto.\nQed.\n\nTheorem mem_pred_pimpl_except : forall LA LEQ LV HA HEQ HV hm p1 p2 a',\n  (forall a v, a <> a' -> p1 a v =p=> p2 a v) ->\n  @mem_pred LA LEQ LV HA HEQ HV p1 (mem_except hm a') =p=> mem_pred p2 (mem_except hm a').\nProof.\n  unfold mem_pred; intros.\n  cancel; eauto.\n  assert (~ In a' (map fst hm_avs)).\n  eapply avs2mem_none_notin. rewrite <- H3. rewrite mem_except_eq. auto.\n  clear H3 hm.\n  induction hm_avs; simpl; intros; auto.\n  unfold mem_pred_one at 1 3; simpl. rewrite H. cancel.\n  eapply IHhm_avs; eauto.\n  inversion H0; eauto.\n  destruct a; firstorder.\nQed.\n\n\nTheorem mem_pred_absent_hm :\n  forall A AEQ LV HV p hm m a,\n  m a = None ->\n  (forall a v, p a v =p=> exists v', a |-> v') ->\n  @mem_pred A AEQ LV A AEQ HV p hm m ->\n  hm a = None.\nProof.\n  intros.\n  case_eq (hm a); intros; auto.\n  eapply mem_pred_extract in H1; eauto.\n  rewrite H0 in H1; destruct_lift H1.\n  apply ptsto_valid' in H1; congruence.\nQed.\n\nTheorem mem_pred_absent_lm :\n  forall A AEQ LV HV p hm m a,\n  hm a = None ->\n  (forall a v, p a v =p=> exists v', a |-> v') ->\n  @mem_pred A AEQ LV A AEQ HV p hm m ->\n  m a = None.\nProof.\n  intros.\n  unfold mem_pred, mem_pred_one in H1. destruct_lift H1.\n  apply avs2mem_none_notin in H.\n  generalize dependent m.\n  induction dummy; simpl in *; intros.\n  - apply emp_empty_mem_only in H1; subst.\n    firstorder.\n  - destruct a0; simpl in *.\n    rewrite H0 in H1.\n    destruct (AEQ a0 a); try solve [ exfalso; eauto ].\n    destruct_lift H1.\n    generalize dependent H1.\n    unfold_sep_star; intros; repeat safedeex.\n    inversion H3.\n    unfold ptsto, mem_union in H1.\n    intuition; subst.\n    match goal with\n    | [ H : forall _, _ -> m1 _ = None |- _ ] => rewrite H\n    end; eauto.\nQed.\n\n\nTheorem xform_mem_pred : forall prd (hm : rawdisk),\n  crash_xform (@mem_pred _ addr_eq_dec _ _ addr_eq_dec _ prd hm) <=p=>\n  @mem_pred _ addr_eq_dec _ _ addr_eq_dec _ (fun a v => crash_xform (prd a v)) hm.\nProof.\n  unfold mem_pred; intros; split.\n  xform_norm; subst.\n  rewrite xform_listpred.\n  cancel.\n\n  cancel; subst.\n  xform_normr; cancel.\n  rewrite xform_listpred.\n  cancel.\n  eauto.\nQed.\n\n\nTheorem sync_xform_mem_pred : forall prd (hm : rawdisk),\n  sync_xform (@mem_pred _ addr_eq_dec _ _ addr_eq_dec _ prd hm) <=p=>\n  @mem_pred _ addr_eq_dec _ _ addr_eq_dec _ (fun a v => sync_xform (prd a v)) hm.\nProof.\n  unfold mem_pred; intros; split.\n  rewrite sync_xform_exists_comm; apply pimpl_exists_l; intros.\n  repeat (rewrite sync_xform_sep_star_dist || rewrite sync_xform_lift_empty).\n  rewrite sync_xform_listpred; cancel.\n\n  rewrite sync_xform_exists_comm; apply pimpl_exists_l; intros.\n  apply pimpl_exists_r; eexists.\n  repeat (rewrite sync_xform_sep_star_dist || rewrite sync_xform_lift_empty).\n  rewrite sync_xform_listpred; cancel.\nQed.\n\n\nTheorem sync_invariant_mem_pred : forall HighAT HighAEQ HighV (prd : HighAT -> HighV -> _) hm,\n  (forall a v, sync_invariant (prd a v)) ->\n  sync_invariant (@mem_pred _ _ _ _ HighAEQ _ prd hm).\nProof.\n  unfold mem_pred; eauto.\nQed.\n\nHint Resolve sync_invariant_mem_pred.\n\n\nSection MEM_MATCH.\n\n  Variable AT V : Type.\n  Variable AEQ : EqDec AT.\n\n  Implicit Types m ma mb : @Mem.mem AT AEQ V.\n\n  Definition mem_match ma mb :=\n    forall a, ma a = None <-> mb a = None.\n\n  Lemma mem_match_refl : forall m,\n    mem_match m m.\n  Proof.\n    firstorder.\n  Qed.\n\n  Lemma mem_match_trans : forall m ma mb,\n    mem_match m ma ->\n    mem_match ma mb ->\n    mem_match m mb.\n  Proof.\n    firstorder.\n  Qed.\n\n  Lemma mem_match_sym : forall ma mb,\n    mem_match ma mb ->\n    mem_match mb ma.\n  Proof.\n    firstorder.\n  Qed.\n\n  Lemma mem_match_except : forall ma mb a,\n    mem_match ma mb ->\n    mem_match (mem_except ma a) (mem_except mb a).\n  Proof.\n    unfold mem_match; intros.\n    unfold mem_except.\n    destruct (AEQ a0 a); firstorder.\n  Qed.\n\n  Lemma mem_match_upd : forall ma mb a va vb,\n    mem_match ma mb ->\n    mem_match (upd ma a va) (upd mb a vb).\n  Proof.\n    unfold mem_match; intros.\n    destruct (AEQ a0 a); subst.\n    repeat rewrite upd_eq by auto.\n    split; congruence.\n    repeat rewrite upd_ne by auto.\n    firstorder.\n  Qed.\n\n  Lemma mem_match_upd_l : forall ma mb a va vb,\n    mem_match ma mb ->\n    mb a = Some vb ->\n    mem_match (upd ma a va) mb.\n  Proof.\n    unfold mem_match; intros.\n    destruct (AEQ a0 a); subst.\n    repeat rewrite upd_eq by auto.\n    split; congruence.\n    repeat rewrite upd_ne by auto.\n    firstorder.\n  Qed.\n\n  Lemma mem_match_upd_r : forall ma mb a va vb,\n    mem_match ma mb ->\n    ma a = Some va ->\n    mem_match ma (upd mb a vb).\n  Proof.\n    unfold mem_match; intros.\n    destruct (AEQ a0 a); subst.\n    repeat rewrite upd_eq by auto.\n    split; congruence.\n    repeat rewrite upd_ne by auto.\n    firstorder.\n  Qed.\n\n  Lemma mem_match_cases : forall ma mb a,\n    mem_match ma mb ->\n    (ma a = None /\\ mb a = None) \\/\n    exists va vb, (ma a = Some va /\\ mb a = Some vb).\n  Proof.\n    intros.\n    specialize (H a); destruct H.\n    destruct (ma a); destruct (mb a).\n    right. eexists; eauto.\n    contradict H0; intuition; congruence.\n    contradict H; intuition; congruence.\n    intuition.\n  Qed.\n\nEnd MEM_MATCH.\n\n\nSection MEM_REGION.\n\n  Variable V : Type.\n  Implicit Types m ma mb : @Mem.mem _ addr_eq_dec V.\n\n  Definition region_filled m st n :=\n    forall a, a >= st -> a < st + n -> m a <> None.\n\n  Lemma region_filled_sel : forall m st n a,\n    region_filled m st n ->\n    a >= st -> a < st + n ->\n    exists v, m a = Some v.\n  Proof.\n    intros.\n    specialize (H a H0 H1).\n    destruct (m a); try congruence.\n    eexists; eauto.\n  Qed.\n\n  Lemma listupd_region_filled : forall l m a,\n    region_filled (listupd m a l) a (length l).\n  Proof.\n    unfold region_filled; destruct l; simpl; intros.\n    omega.\n    destruct (addr_eq_dec a a0); subst.\n    rewrite listupd_sel_oob by omega.\n    rewrite upd_eq; congruence.\n    erewrite listupd_sel_inb with (def := v) by omega.\n    congruence.\n  Qed.\n\n(*\n  Lemma arrayN_region_filled : forall l m a F,\n    (F * arrayN a l)%pred m ->\n    region_filled m a (length l).\n  Proof.\n    unfold region_filled; induction l; simpl; intros.\n    omega.\n    destruct (addr_eq_dec a1 a0); subst.\n    apply sep_star_comm in H; apply sep_star_assoc in H.\n    apply ptsto_valid in H; congruence.\n    apply sep_star_assoc in H.\n    eapply IHl; eauto; omega.\n  Qed.\n*)\n\n  Lemma mem_match_listupd_l : forall l ma mb a,\n    mem_match ma mb ->\n    region_filled mb a (length l) ->\n    mem_match (listupd ma a l) mb.\n  Proof.\n    induction l; simpl; auto; intros.\n    apply IHl.\n    eapply region_filled_sel in H0; eauto.\n    destruct H0.\n    eapply mem_match_upd_l; eauto.\n    omega.\n    unfold region_filled in *; intuition.\n    eapply H0 with (a := a1); try omega; auto.\n  Qed.\n\nEnd MEM_REGION.\n\n\nSection MEM_INCL.\n\n  Implicit Types m ma mb : rawdisk.\n\n  Definition mem_incl ma mb := forall a,\n    (ma a = None /\\ mb a = None) \\/\n    exists va vb, ma a = Some va /\\ mb a = Some vb /\\\n    incl (vsmerge va) (vsmerge vb).\n\n  Lemma mem_incl_refl : forall m,\n    mem_incl m m.\n  Proof.\n    unfold mem_incl; intros.\n    destruct (m a) eqn: Heq; intuition.\n    right; do 2 eexists; intuition.\n  Qed.\n\n  Lemma mem_incl_trans : forall m ma mb,\n    mem_incl ma m ->\n    mem_incl m mb ->\n    mem_incl ma mb.\n  Proof.\n    unfold mem_incl; intuition.\n    specialize (H a); specialize (H0 a).\n    intuition; repeat deex; try congruence.\n    right.\n    rewrite H1 in H0; inversion H0; subst.\n    do 2 eexists; intuition eauto.\n    eapply incl_tran; eauto.\n  Qed.\n\n  Lemma possible_crash_incl_trans : forall m ma mb,\n    possible_crash ma m ->\n    mem_incl ma mb ->\n    possible_crash mb m.\n  Proof.\n    unfold possible_crash, mem_incl; intros.\n    specialize (H a); specialize (H0 a).\n    intuition; repeat deex; try congruence.\n    right.\n    rewrite H2 in H0; inversion H0; subst.\n    do 2 eexists; intuition eauto.\n  Qed.\n\n  Lemma mem_incl_upd : forall a va vb ma mb,\n    mem_incl ma mb ->\n    incl (vsmerge va) (vsmerge vb) ->\n    mem_incl (upd ma a va) (upd mb a vb).\n  Proof.\n    unfold mem_incl; intros.\n    specialize (H a0).\n    destruct (addr_eq_dec a a0); subst.\n    repeat rewrite upd_eq by auto.\n    intuition; repeat deex; intuition.\n    right; do 2 eexists; eauto.\n    right; do 2 eexists; eauto.\n    repeat rewrite upd_ne by auto.\n    intuition.\n  Qed.\n\n  Lemma mem_incl_listupd : forall la lb,\n    Forall2 (fun va vb => incl (vsmerge va) (vsmerge vb)) la lb ->\n    forall ma mb st,\n    mem_incl ma mb ->\n    mem_incl (listupd ma st la) (listupd mb st lb).\n  Proof.\n    induction 1; simpl; intros; auto.\n    apply IHForall2.\n    apply mem_incl_upd; auto.\n  Qed.\n\n  Lemma mem_incl_listupd_same : forall la lb,\n    Forall2 (fun va vb => incl (vsmerge va) (vsmerge vb)) la lb ->\n    forall m st,\n    mem_incl (listupd m st la) (listupd m st lb).\n  Proof.\n    intros.\n    apply mem_incl_listupd; auto.\n    apply mem_incl_refl.\n  Qed.\n\nEnd MEM_INCL.\n", "meta": {"author": "mit-pdos", "repo": "fscq", "sha": "2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0", "save_path": "github-repos/coq/mit-pdos-fscq", "path": "github-repos/coq/mit-pdos-fscq/fscq-2c7ef9c268fd79a81b26b44ef720f8e6a1e938a0/src/MemPred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20895467048751784}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrbool eqtype seq.\nRequire Import ZArith_ext String_ext ssrnat_ext seq_ext.\nRequire Import machine_int.\nImport MachineInt.\nRequire Import C_types C_types_fp C_value C_expr C_expr_ground C_seplog C_pp.\n\nLocal Open Scope C_types_scope.\nLocal Open Scope string_scope.\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope machine_int_scope.\n\nModule C_swap_env <: CENV.\nDefinition g := \\wfctxt{ \\O \\}.\nDefinition sigma : g.-env := (\"x\", :* (ityp: uint)) :: (\"y\", :* (ityp: uint)) ::\n                             (\"z\", g.-ityp: uint) :: (\"v\", g.-ityp: uint) :: nil.\nDefinition uniq_vars : uniq (unzip1 sigma) := Logic.eq_refl.\nEnd C_swap_env.\n\nDefinition g := C_swap_env.g.\nDefinition sigma := C_swap_env.sigma.\n\nModule Import C_Seplog_m := C_Pp_f C_swap_env.\n\nLocal Open Scope C_cmd_scope.\n\nDefinition swap :=\n  \"z\" <-* %\"x\" ;\n  \"v\" <-* %\"y\" ;\n  %\"x\" *<- %\"v\" ;\n  %\"y\" *<- %\"z\".\n\nDefinition mk_cell := log_of_uint (g.-ityp: uint) Logic.eq_refl.\n\nLocal Notation \"a |~> b\" := (a |le~> mk_cell b) (at level 77).\n\nLemma swap_correct (a b : int 32) :\n  {{ %\"x\" |~> a ** %\"y\" |~> b }}\n              swap\n  {{ %\"x\" |~> b ** %\"y\" |~> a }}.\nProof.\nrewrite /swap.\npose za := `! \\b %\"z\" \\= [ a ]pc.\nHoare_seq_ext za.\n  Hoare_frame_idx_tmp (O :: nil) (O :: 1%nat :: nil).\n  eapply hoare_stren; last by apply hoare_lookup_stren, ent_id.\n  apply ent_R_lookup_trans with ([ a ]p) (mk_cell a).\n    by rewrite /phylog_conv /=.\n    by apply ent_R_con_T.\n  Ent_R_subst_con_distr.\n  do 2 Ent_R_subst_apply => /=.\n  by Ent_monotony0.\n\npose vb := `! \\b %\"v\" \\= [ b ]pc.\n  Hoare_seq_ext vb.\n  Hoare_frame_idx_tmp (2%nat :: nil) (O :: 3%nat :: nil).\n  eapply hoare_stren; last by apply hoare_lookup_stren, ent_id.\n  apply ent_R_lookup_trans with ([ b ]p) (mk_cell b).\n    by rewrite /phylog_conv /=.\n    by apply ent_R_con_T.\n  Ent_R_subst_con_distr.\n  do 2 Ent_R_subst_apply => /=.\n  by rewrite bbang_eq_exx coneP.\n\nset Hx_old := %\"x\" |le~> mk_cell a.\npose Hx_new := %\"x\" |le~> mk_cell b.\nHoare_seq_replace1 Hx_old Hx_new.\n  Hoare_frame_idx_tmp (O :: 2%nat :: nil) (O :: 2%nat :: nil).\n  apply hoare_mutation_subst_btyp with (str := \"v\") (Hstr := Logic.eq_refl) (e' := [ b ]pc).\n    rewrite /vb.\n    Ent_R_rewrite_eq_e O.\n    Ent_R_subst_con_distr.\n    do 2 Ent_R_subst_apply.\n   rewrite /Hx_old.\n   rewrite bbang_eq_exx coneP; by apply ent_R_T.\n  rewrite /=.\n  Hoare_frame_idx_tmp (1%nat :: nil) (1%nat :: nil).\n  rewrite /Hx_old /Hx_new.\n  set bpc := [ b ]pc.\n  have He2 : vars bpc = nil by done.\n  apply hoare_mutation_local_forward_ground_le with (He2 := He2); by rewrite/phylog_conv /=.\n\nrewrite -/Hx_new.\nset Hy_old := %\"y\" |le~> _.\nset Hy_new := %\"y\" |le~> _.\nHoare_frame (vb :: za :: Hy_old :: nil) (Hy_new :: nil).\napply hoare_mutation_subst_btyp with (str := \"z\") (Hstr := Logic.eq_refl) (e' := [ a ]pc).\n  rewrite /za.\n  Ent_R_rewrite_eq_e O.\n  Ent_R_subst_con_distr.\n  do 2 Ent_R_subst_apply.\n  rewrite bbang_eq_exx coneP; by apply ent_R_T.\nrewrite /=.\nHoare_L_contract_bbang vb.\nHoare_L_contract_bbang za.\nset apc := [ a ]pc.\nhave He2 : vars apc = nil by done.\napply hoare_mutation_local_forward_ground_le with (He2 := He2); by rewrite/phylog_conv /=.\nQed.\n\nEval compute in pp_ctxt.\nEval compute in (foldl\n  (fun s p => s ++ typ_to_string (Ctyp.ty _ (snd p)) (fst p) (line \";\"))\n  \"\" sigma).\nEval compute in (pp_cmd 0 swap \"\").\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/seplogC/C_swap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20895466479403138}}
{"text": "From stdpp Require Export binders strings countable gmap.\nFrom iris.algebra Require Export ofe.\nFrom iris.heap_lang Require Export locations.\nFrom iris.prelude Require Import options.\n\nDeclare Scope c_val_scope.\nDelimit Scope c_val_scope with CV.\n\nModule C_intf.\n\n(** C values *)\n\nInductive base_lit : Set :=\n  | LitInt (n : Z) | LitLoc (l : loc) | LitNull | LitFunPtr (x : string).\nInductive val :=\n  | LitV (l : base_lit).\n\nBind Scope c_val_scope with C_intf.val.\n\nGlobal Instance base_lit_eq_dec : EqDecision base_lit.\nProof. solve_decision. Defined.\nGlobal Instance val_eq_dec : EqDecision val.\nProof. solve_decision. Defined.\n\nGlobal Instance base_lit_countable : Countable base_lit.\nProof.\n refine (inj_countable' (λ l, match l with\n  | LitInt n => (inl (inl n))\n  | LitLoc l => (inl (inr l))\n  | LitFunPtr p => (inr (inl p))\n  | LitNull => inr (inr ())\n  end) (λ l, match l with\n  | inl (inl n) => LitInt n\n  | inl (inr l) => LitLoc l\n  | inr (inl p) => LitFunPtr p\n  | inr (inr _) => LitNull\n  end) _); by intros [].\nQed.\nGlobal Instance val_countable : Countable val.\nProof.\n  set (enc := fun e => match e with LitV l => l end).\n  set (dec := LitV).\n  refine (inj_countable' enc dec _).\n  by intros [].\nQed.\n\nGlobal Instance val_inhabited : Inhabited val := populate (LitV (LitInt 0)).\nCanonical Structure valO {SI:indexT} := leibnizO val.\n\nDefinition LitBool (b : bool) : base_lit := LitInt (if b then 1%Z else 0%Z).\nDefinition LitUnit : base_lit := LitInt 0.\n\n(** C state *)\n\nNotation heap_cell := (option (option val)).\nNotation Deallocated := (None : heap_cell).\nNotation Uninitialized := (Some None : heap_cell).\nNotation Storing v := (Some (Some v) : heap_cell).\n\n(** The state: heaps of heap_cells. *)\nNotation c_state := (gmap loc (option (option val))).\n\nGlobal Instance state_inhabited : Inhabited c_state :=\n  populate inhabitant.\n\nCanonical Structure stateO {SI:indexT} := leibnizO c_state.\n\n(* Contiguous regions in the heap, i.e. arrays *)\n\nDefinition state_upd_heap (f: gmap loc heap_cell → gmap loc heap_cell) (σ: c_state) : c_state :=\n  f σ.\nGlobal Arguments state_upd_heap _ !_ /.\n\nFixpoint heap_array (l : loc) (vs : list heap_cell) : gmap loc heap_cell :=\n  match vs with\n  | [] => ∅\n  | v :: vs' => {[l := v]} ∪ heap_array (l +ₗ 1) vs'\n  end.\n\nLemma heap_array_singleton l v : heap_array l [v] = {[l := v]}.\nProof. by rewrite /heap_array right_id. Qed.\n\nLemma heap_array_lookup l vs ow k :\n  heap_array l vs !! k = Some ow ↔\n  ∃ j, (0 ≤ j)%Z ∧ k = l +ₗ j ∧ vs !! (Z.to_nat j) = Some ow.\nProof.\n  revert k l; induction vs as [|v' vs IH]=> l' l /=.\n  { rewrite lookup_empty. naive_solver lia. }\n  rewrite -insert_union_singleton_l lookup_insert_Some IH. split.\n  - intros [[-> ?] | (Hl & j  & ? & -> & ?)].\n    { eexists 0. rewrite loc_add_0. naive_solver lia. }\n    eexists (1 + j)%Z. rewrite loc_add_assoc !Z.add_1_l Z2Nat.inj_succ; auto with lia.\n  - intros (j & w & -> & Hil). destruct (decide (j = 0)); simplify_eq/=.\n    { rewrite loc_add_0; eauto. }\n    right. split.\n    { rewrite -{1}(loc_add_0 l). intros ?%(inj (loc_add _)); lia. }\n    assert (Z.to_nat j = S (Z.to_nat (j - 1))) as Hj.\n    { rewrite -Z2Nat.inj_succ; last lia. f_equal; lia. }\n    rewrite Hj /= in Hil.\n    eexists (j - 1)%Z. rewrite loc_add_assoc Z.add_sub_assoc Z.add_simpl_l.\n    auto with lia.\nQed.\n\nLemma heap_array_map_disjoint (h : gmap loc heap_cell) (l : loc) (vs : list _) :\n  (∀ i, (0 ≤ i)%Z → (i < length vs)%Z → h !! (l +ₗ i) = None) →\n  (heap_array l vs) ##ₘ h.\nProof.\n  intros Hdisj. apply map_disjoint_spec=> l' v1 v2.\n  intros (j&w&->&Hj%lookup_lt_Some%inj_lt)%heap_array_lookup.\n  move: Hj. rewrite Z2Nat.id // => ?. by rewrite Hdisj.\nQed.\n\nEnd C_intf.\n\nExport C_intf.\n", "meta": {"author": "logsem", "repo": "melocoton", "sha": "b77eecc3381f53db0eb3c4cf1314e881a8dc41b3", "save_path": "github-repos/coq/logsem-melocoton", "path": "github-repos/coq/logsem-melocoton/melocoton-b77eecc3381f53db0eb3c4cf1314e881a8dc41b3/theories/c_interface/defs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20895466479403138}}
{"text": "From cap_machine Require Export rules_Load rules_binary_base.\nFrom iris.base_logic Require Export invariants gen_heap.\nFrom iris.program_logic Require Export weakestpre ectx_lifting.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import frac.\n\n\nSection cap_lang_spec_rules.\n  Context `{cfgSG Σ, MachineParameters, invG Σ}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types σ : cap_lang.state.\n  Implicit Types a b : Addr.\n  Implicit Types r : RegName.\n  Implicit Types w : Word.\n  Implicit Types reg : gmap RegName Word.\n  Implicit Types ms : gmap Addr Word.\n\n  Ltac option_locate_r_once_reg r reg :=\n  match goal with\n  | H : r !! reg = Some ?w |- _ => let Htmp := fresh in\n                                rename H into Htmp ;\n                                let Ha := fresh \"H\" r reg in\n                                pose proof (regs_lookup_eq _ _ _ Htmp) as Ha; clear Htmp\n  end.\n\n  Lemma step_Load Ep K pc_p pc_g pc_b pc_e pc_a r1 r2 w mem regs :\n    decodeInstrW w = Load r1 r2 →\n    isCorrectPC (inr (pc_p, pc_g, pc_b, pc_e, pc_a)) →\n    regs !! PC = Some (inr (pc_p, pc_g, pc_b, pc_e, pc_a)) →\n    regs_of (Load r1 r2) ⊆ dom _ regs →\n    mem !! pc_a = Some w →\n    allow_load_map_or_true r2 regs mem →\n\n    nclose specN ⊆ Ep →\n\n    spec_ctx ∗ ⤇ fill K (Instr Executable) ∗ (▷ [∗ map] a↦w ∈ mem, a ↣ₐ w) ∗ (▷ [∗ map] k↦y ∈ regs, k ↣ᵣ y)\n    ={Ep}=∗ ∃ retv regs', ⤇ fill K (of_val retv) ∗ ⌜ Load_spec regs r1 r2 regs' mem retv ⌝ ∗ ([∗ map] a↦w ∈ mem, a ↣ₐ w)∗ ([∗ map] k↦y ∈ regs', k ↣ᵣ y).\n  Proof.\n    iIntros (Hinstr Hvpc HPC Dregs Hmem_pc HaLoad Hnclose) \"(#Hinv & Hj & >Hmem & >Hmap)\".\n    iDestruct \"Hinv\" as (ρ) \"Hinv\". rewrite /spec_inv.\n    iInv specN as \">Hinv'\" \"Hclose\". iDestruct \"Hinv'\" as (e [σr σm]) \"[Hown %] /=\".\n    iDestruct (regspec_heap_valid_inclSepM with \"Hown Hmap\") as %Hregs.\n    iDestruct (spec_expr_valid with \"[$Hown $Hj]\") as %Heq; subst e.\n\n    (* Derive necessary register values in r *)\n     pose proof (lookup_weaken _ _ _ _ HPC Hregs).\n     specialize (indom_regs_incl _ _ _ Dregs Hregs) as Hri. unfold regs_of in Hri.\n     feed destruct (Hri r2) as [r2v [Hr'2 Hr2]]. by set_solver+.\n     feed destruct (Hri r1) as [r1v [Hr'1 _]]. by set_solver+. clear Hri.\n     pose proof (regs_lookup_eq _ _ _ Hr'1) as Hr''1.\n     pose proof (regs_lookup_eq _ _ _ Hr'2) as Hr''2.\n     (* Derive the PC in memory *)\n     iDestruct (memspec_heap_valid_inSepM _ _ _ _ pc_a with \"Hown Hmem\") as %Hma; eauto.\n\n     specialize (normal_always_step (σr,σm)) as [c [ σ2 Hstep]].\n     eapply step_exec_inv in Hstep; eauto. simpl in H3,Hr2,Hma.\n\n     option_locate_r_once_reg σr r2. assert (Hstep':=Hstep).\n     cbn in Hstep. rewrite Hσrr2 in Hstep.\n\n     (* Now we start splitting on the different cases in the Load spec, and prove them one at a time *)\n     destruct r2v as  [| (([[p g] b] & e) & a) ] eqn:Hr2v.\n     { (* Failure: r2 is not a capability *)\n       symmetry in Hstep; inversion Hstep; clear Hstep. subst c σ2.\n       iMod (exprspec_mapsto_update _ _ (fill K (Instr Failed)) with \"Hown Hj\") as \"[Hown Hj]\".\n       iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n       { iNext. iExists _,_;iFrame.\n         iPureIntro. eapply rtc_r;eauto. prim_step_from_exec. }\n       iExists (FailedV),_; iFrame. iModIntro. iFailCore Load_fail_const.\n     }\n\n     destruct (readAllowed p && withinBounds (p,g, b, e, a)) eqn:HRA; rewrite HRA in Hstep.\n     2 : { (* Failure: r2 is either not within bounds or doesnt allow reading *)\n       symmetry in Hstep; inversion Hstep; clear Hstep. subst c σ2.\n       apply andb_false_iff in HRA.\n       iMod (exprspec_mapsto_update _ _ (fill K (Instr Failed)) with \"Hown Hj\") as \"[Hown Hj]\".\n       iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n       { iNext. iExists _,_;iFrame.\n         iPureIntro. eapply rtc_r;eauto. prim_step_from_exec. }\n       iExists (FailedV),_; iFrame. iModIntro. iFailCore Load_fail_bounds.\n     }\n     apply andb_true_iff in HRA; destruct HRA as (Hra & Hwb).\n\n     (* Prove that a is in the memory map now, otherwise we cannot continue *)\n     pose proof (allow_load_implies_loadv r2 mem regs p g b e a) as (loadv & Hmema); auto.\n\n     iDestruct (memspec_v_implies_m_v mem (σr,σm) _ b e a loadv with \"Hmem Hown\" ) as %Hma' ; auto.\n\n     rewrite Hma' in Hstep.\n     destruct (incrementPC (<[ r1 := loadv ]> regs)) as  [ regs' |] eqn:Hregs'.\n     2: { (* Failure: the PC could not be incremented correctly *)\n       assert (incrementPC (<[ r1 := loadv]> σr) = None).\n       { eapply incrementPC_overflow_mono; first eapply Hregs'.\n         by rewrite lookup_insert_is_Some'; eauto.\n         by apply insert_mono; eauto. }\n\n       rewrite incrementPC_fail_updatePC /= in Hstep; auto.\n       symmetry in Hstep; inversion Hstep; clear Hstep. subst c σ2.\n       (* Update the heap resource, using the resource for r2 *)\n       iMod (exprspec_mapsto_update _ _ (fill K (Instr Failed)) with \"Hown Hj\") as \"[Hown Hj]\".\n       iMod ((regspec_heap_update_inSepM _ _ _ r1 loadv) with \"Hown Hmap\") as \"[Hown Hmap]\"; eauto.\n       iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n       { iNext. iExists _,_;iFrame.\n         iPureIntro. eapply rtc_r;eauto. prim_step_from_exec. }\n       iExists (FailedV),_; iFrame. iModIntro. iFailCore Load_fail_invalid_PC.\n     }\n\n     (* Success *)\n     rewrite /update_reg /= in Hstep.\n     eapply (incrementPC_success_updatePC _ σm) in Hregs'\n       as (p1 & g1 & b1 & e1 & a1 & a_pc1 & HPC'' & Ha_pc' & HuPC & -> & ?).\n     eapply updatePC_success_incl in HuPC. 2: by eapply insert_mono.\n     rewrite HuPC in Hstep; clear HuPC; inversion Hstep; clear Hstep; subst c σ2. cbn.\n     iFrame.\n     iMod ((regspec_heap_update_inSepM _ _ _ r1 loadv) with \"Hown Hmap\") as \"[Hown Hmap]\"; eauto.\n     iMod ((regspec_heap_update_inSepM _ _ _ PC (inr (p1, g1, b1, e1, a_pc1))) with \"Hown Hmap\") as \"[Hown Hmap]\"; eauto.\n     iMod (exprspec_mapsto_update _ _ (fill K (Instr NextI)) with \"Hown Hj\") as \"[Hown Hj]\".\n     iExists NextIV,_. iFrame.\n     iMod (\"Hclose\" with \"[Hown]\") as \"_\".\n     { iNext. iExists _,_;iFrame. iPureIntro. eapply rtc_r;eauto.\n      prim_step_from_exec. }\n     iModIntro. iPureIntro. eapply Load_spec_success; auto.\n    * split; auto. apply (regs_lookup_inr_eq regs r2).\n      exact Hr''2.\n      auto.\n    * exact Hmema.\n    * unfold incrementPC. rewrite HPC'' Ha_pc'.\n      destruct p1; naive_solver.\n      Unshelve. all: auto.\n  Qed.\n\n  Lemma step_load_success_same E K r1 pc_p pc_g pc_b pc_e pc_a w w' w'' p g b e a pc_a' :\n    decodeInstrW w = Load r1 r1 →\n    isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) →\n    readAllowed p = true ∧ withinBounds (p, g, b, e, a) = true →\n    (pc_a + 1)%a = Some pc_a' →\n    nclose specN ⊆ E →\n\n    spec_ctx ∗ ⤇ fill K (Instr Executable)\n             ∗ ▷ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a)\n             ∗ ▷ pc_a ↣ₐ w\n             ∗ ▷ r1 ↣ᵣ inr (p,g,b,e,a)\n             ∗ (if (a =? pc_a)%a then emp else ▷ a ↣ₐ w')\n    ={E}=∗ ⤇ fill K (Instr NextI)\n        ∗ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n        ∗ r1 ↣ᵣ (if (a =? pc_a)%a then w else w')\n        ∗ pc_a ↣ₐ w\n        ∗ (if (a =? pc_a)%a then emp else a ↣ₐ w').\n  Proof.\n    iIntros (Hinstr Hvpc [Hra Hwb] Hpca' Hnclose)\n            \"(Hown & Hj & >HPC & >Hi & >Hr1 & Hr1a)\".\n    iDestruct (map_of_regs_2 with \"HPC Hr1\") as \"[Hmap %]\".\n    iDestruct (memMap_resource_2gen_clater _ _ _ _ (λ a w, a ↣ₐ w)%I with \"Hi Hr1a\") as (mem) \"[>Hmem Hmem']\".\n    iDestruct \"Hmem'\" as %Hmem.\n\n    iMod (step_Load with \"[$Hown $Hj $Hmap $Hmem]\") as (retv regs') \"(Hj & #Hspec & Hmem & Hmap)\"; eauto; simplify_map_eq; eauto.\n    { by rewrite !dom_insert; set_solver+. }\n    { destruct (a =? pc_a)%a; by simplify_map_eq. }\n    { eapply mem_implies_allow_load_map; eauto. rewrite lookup_insert_ne// lookup_insert;eauto. }\n    iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [ | * Hfail ].\n     { (* Success *)\n       destruct H3 as [Hrr2 _].\n       rewrite lookup_insert_ne// lookup_insert in Hrr2. simplify_eq.\n       incrementPC_inv. rewrite lookup_insert_ne// lookup_insert in H3. simplify_eq.\n       iDestruct (memMap_resource_2gen_d with \"[Hmem]\") as \"[Hpc_a Ha]\".\n       {iExists mem; iSplitL; auto. }\n       pose proof (mem_implies_loadv _ _ _ _ _ _ Hmem H4) as Hloadv; eauto.\n       rewrite (insert_commute _ PC r1) // insert_insert (insert_commute _ r1 PC) // insert_insert.\n       iDestruct (regs_of_map_2 with \"[$Hmap]\") as \"[HPC Hr1]\"; eauto. rewrite Hloadv. by iFrame. }\n     { (* Failure (contradiction) *)\n       destruct Hfail; try (incrementPC_inv;[|rewrite lookup_insert_ne//]);simplify_map_eq;eauto.\n       destruct o. all: try congruence.\n       destruct e3; try congruence. inv Hvpc; naive_solver.\n     }\n  Qed.\n\n  Lemma step_load_success_same_alt E K r1 pc_p pc_g pc_b pc_e pc_a w w' w'' p g b e a pc_a' :\n    decodeInstrW w = Load r1 r1 →\n    isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) →\n    readAllowed p = true ∧ withinBounds (p, g, b, e, a) = true →\n    (pc_a + 1)%a = Some pc_a' →\n    nclose specN ⊆ E →\n\n    spec_ctx ∗ ⤇ fill K (Instr Executable)\n             ∗ ▷ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a)\n             ∗ ▷ pc_a ↣ₐ w\n             ∗ ▷ r1 ↣ᵣ inr (p,g,b,e,a)\n             ∗ ▷ a ↣ₐ w'\n    ={E}=∗ ⤇ fill K (Instr NextI)\n        ∗ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n        ∗ r1 ↣ᵣ w'\n        ∗ pc_a ↣ₐ w\n        ∗ a ↣ₐ w'.\n  Proof.\n    iIntros (Hinstr Hvpc [Hra Hwb] Hpca' Hnclose) \"(Hown & Hj & >HPC & >Hpc_a & >Hr1 & >Ha)\".\n    iAssert (⌜(a =? pc_a)%a = false⌝)%I as %Hfalse.\n    { rewrite Z.eqb_neq. iIntros (->%z_of_eq). iDestruct (memspec_mapsto_valid_2 with \"Ha Hpc_a\") as %Hneq. done. }\n    iMod (step_load_success_same with \"[$HPC $Hpc_a $Hr1 $Hown $Hj Ha]\") as \"(?&?&?&?&?)\";eauto;try rewrite Hfalse;by iFrame.\n  Qed.\n\n  Lemma step_load_success E K r1 r2 pc_p pc_g pc_b pc_e pc_a w w' w'' p g b e a pc_a' :\n    decodeInstrW w = Load r1 r2 →\n    isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) →\n    readAllowed p = true ∧ withinBounds (p, g, b, e, a) = true →\n    (pc_a + 1)%a = Some pc_a' →\n    nclose specN ⊆ E →\n\n    spec_ctx ∗ ⤇ fill K (Instr Executable)\n             ∗ ▷ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a)\n             ∗ ▷ pc_a ↣ₐ w\n             ∗ ▷ r1 ↣ᵣ w''\n             ∗ ▷ r2 ↣ᵣ inr (p,g,b,e,a)\n             ∗ (if (eqb_addr a pc_a) then emp else ▷ a ↣ₐ w')\n    ={E}=∗ ⤇ fill K (Instr NextI)\n        ∗ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n        ∗ r1 ↣ᵣ (if (eqb_addr a pc_a) then w else w')\n        ∗ pc_a ↣ₐ w\n        ∗ r2 ↣ᵣ inr (p,g,b,e,a)\n        ∗ (if (eqb_addr a pc_a) then emp else a ↣ₐ w').\n  Proof.\n    iIntros (Hinstr Hvpc [Hra Hwb] Hpca' Hnclose)\n            \"(Hown & Hj & >HPC & >Hi & >Hr1 & >Hr2 & Hr2a)\".\n    iDestruct (map_of_regs_3 with \"HPC Hr1 Hr2\") as \"[Hmap (%&%&%)]\".\n    iDestruct (memMap_resource_2gen_clater _ _ _ _ (λ a w, a ↣ₐ w)%I with \"Hi Hr2a\") as (mem) \"[>Hmem Hmem']\".\n    iDestruct \"Hmem'\" as %Hmem.\n\n    iMod (step_Load with \"[$Hown $Hj $Hmap $Hmem]\") as (retv regs') \"(Hj & #Hspec & Hmem & Hmap)\"; eauto.\n    { rewrite lookup_insert;eauto. }\n    { by rewrite !dom_insert; set_solver+. }\n    { destruct (a =? pc_a)%a; by simplify_map_eq. }\n    { eapply mem_implies_allow_load_map; eauto. rewrite lookup_insert_ne// lookup_insert_ne// lookup_insert. eauto. }\n    iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [ | * Hfail ].\n     { (* Success *)\n       (* FIXME: fragile *)\n       destruct H5 as [Hrr2 _]. simplify_map_eq_alt.\n       iDestruct (memMap_resource_2gen_d with \"[Hmem]\") as \"[Hpc_a Ha]\".\n       {iExists mem; iSplitL; auto. }\n       incrementPC_inv.\n       pose proof (mem_implies_loadv _ _ _ _ _ _ Hmem H6) as Hloadv; eauto.\n       simplify_map_eq_alt.\n       rewrite (insert_commute _ PC r1) // insert_insert (insert_commute _ r1 PC) // insert_insert.\n       iDestruct (regs_of_map_3 with \"[$Hmap]\") as \"[HPC [Hr1 Hr2] ]\"; eauto.\n       by iFrame. }\n     { (* Failure (contradiction) *)\n       destruct Hfail; simplify_map_eq_alt.\n       destruct o;congruence.\n       incrementPC_inv;[|rewrite lookup_insert_ne// lookup_insert;eauto].\n       destruct e3; try congruence. inv Hvpc; naive_solver. }\n  Qed.\n\n  Lemma step_load_success_alt E K r1 r2 pc_p pc_g pc_b pc_e pc_a w w' w'' p g b e a pc_a' :\n    decodeInstrW w = Load r1 r2 →\n    isCorrectPC (inr (pc_p,pc_g,pc_b,pc_e,pc_a)) →\n    readAllowed p = true ∧ withinBounds (p, g, b, e, a) = true →\n    (pc_a + 1)%a = Some pc_a' →\n    nclose specN ⊆ E →\n\n    spec_ctx ∗ ⤇ fill K (Instr Executable)\n             ∗ ▷ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a)\n             ∗ ▷ pc_a ↣ₐ w\n             ∗ ▷ r1 ↣ᵣ w''\n             ∗ ▷ r2 ↣ᵣ inr (p,g,b,e,a)\n             ∗ ▷ a ↣ₐ w'\n    ={E}=∗ ⤇ fill K (Instr NextI)\n        ∗ PC ↣ᵣ inr (pc_p,pc_g,pc_b,pc_e,pc_a')\n        ∗ r1 ↣ᵣ w'\n        ∗ pc_a ↣ₐ w\n        ∗ r2 ↣ᵣ inr (p,g,b,e,a)\n        ∗ a ↣ₐ w'.\n  Proof.\n    iIntros (Hinstr Hvpc [Hra Hwb] Hpca' Hnclose)\n            \"(Hown & Hj & >HPC & >Hi & >Hr1 & >Hr2 & >Hr2a)\".\n    iAssert (⌜(a =? pc_a)%a = false⌝)%I as %Hfalse.\n    { rewrite Z.eqb_neq. iIntros (->%z_of_eq). iDestruct (memspec_mapsto_valid_2 with \"Hr2a Hi\") as %Hneq. done. }\n    iMod (step_load_success with \"[$Hown $Hj $HPC $Hi $Hr1 $Hr2 Hr2a]\");eauto;rewrite Hfalse;by iFrame. \n  Qed.\n  \nEnd cap_lang_spec_rules.\n", "meta": {"author": "logsem", "repo": "cerise-stack-monotone", "sha": "dff1909f6abc6de99c28d8f12e903b98dd76fb41", "save_path": "github-repos/coq/logsem-cerise-stack-monotone", "path": "github-repos/coq/logsem-cerise-stack-monotone/cerise-stack-monotone-dff1909f6abc6de99c28d8f12e903b98dd76fb41/theories/binary_model/rules_binary/rules_binary_Load.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.20895466479403135}}
{"text": "Require Import FunctionalExtensionality.\nRequire Import List.\nImport ListNotations.\nFrom Coq Require Import ZArith.\nRequire Import Basics.\nRequire Import Automation.\nRequire Import Monads.\nRequire Import Blockchain.\nRequire Import Extras.\nRequire Import Containers.\n\nRequire Import Serializable.\nFrom RecordUpdate Require Import RecordUpdate.\nImport RecordSetNotations.\nRequire Import CLIPrelude.\nRequire Import CLITranslate.\n\nOpen Scope Z.\n\nSet Nonrecursive Elimination Schemes.\n\nSection Interp.\n  Context `{Base : ChainBase}.\n\n  (** Defines setup, state and message records for the contract *)\n  Record Setup :=\n    build_setup {\n        setup_contract : list CInstruction;\n      }.\n\n  Record State :=\n    build_state {\n        contract : list CInstruction;\n        currentTime : nat;\n        result : option TraceM;\n      }.\n\n  Inductive Msg :=\n  | update : ExtMap -> nat -> Msg.                          \n\n\n  (** Automatically prove that our required datatypes and records are serializable, needs to be in this file for some reason *)\n(*  Instance party_serializable : Serializable Party :=\n    Derive Serializable Party_rect<PartyN>. *)\n  Instance Obs_serializable : Serializable ObsLabel :=\n    Derive Serializable ObsLabel_rect<LabZ, LabB>.\n  Instance Val_Serializable : Serializable Val :=\n    Derive Serializable Val_rect<BVal, ZVal>.\n  Instance ExtMapSerializable : Serializable ExtMap := _.\n(*  Instance asset_serializable : Serializable Asset :=\n    Derive Serializable Asset_rect<DKK, USD>. *)\n  Instance TransSerial : Serializable TransM := _.\n  Instance TraceSerial : Serializable TraceM := _.\n  Instance Op_serializable : Serializable Op :=\n    Derive Serializable Op_rect <Add, Sub, Mult, Div, And, Or, Less, Leq, Equal, Not, Neg, BLit, ZLit, Cond>.\n  Instance instruction_serializable : Serializable instruction :=\n    Derive Serializable instruction_rect<IPushZ, IPushB, IObs, IOp, IAccStart1,\n    IAccStart2, IAccStep, IAccEnd, IVar>.\n   Instance Env_Serializable : Serializable Env := _.\n  Instance CInstruction_serializable : Serializable CInstruction := \n    Derive Serializable CInstruction_rect< CIZero, CITransfer, CIScale, CIBoth, CITranslate,\n    CITranslateEnd, CILet, CILetEnd, CIIf, CIThen, CIIfEnd>.\n  Instance SetupSerial : Serializable Setup :=\n    Derive Serializable Setup_rect<build_setup>.\n  Instance StateSerial : Serializable State :=\n    Derive Serializable State_rect<build_state>.\n  Instance MsgSerial : Serializable Msg :=\n    Derive Serializable Msg_rect<update>.\n  Global Instance State_settable : Settable _ :=\n    settable! build_state <contract; currentTime; result>.\n\n  (** init funtion for the contract, sets the current time to zero, and the currently computed transactions to None\n   note that we meassure time realitvely, so 0 means 0 time units since initialization *)\n  Definition init (chain : Chain) (ctx: ContractCallContext) (setup: Setup) : option State :=\n    let contract := setup_contract setup in\n    Some (build_state contract 0 None).\n\n  Definition extract_element (trace : TraceM) (index : nat) : TraceM :=\n    match FMap.find index trace with\n    | Some trans => FMap.add index trans empty_traceM\n    | None => empty_traceM\n    end.\n  \n  Fixpoint cutTrace (trace : TraceM) (startTime idx: nat) : TraceM :=\n    match idx with\n    | 0%nat => empty_traceM\n    | S n => add_traceM (extract_element trace (startTime + idx)%nat) (cutTrace trace startTime n)\n    end.\n  \n  (** \n      The receive method of the contract.\n      When an environment and a time is received, if the new time is greater that what\n      has previously been evaluated, then the contract is evluated according to the \n      environment. The section of the trace between is then evaluation and the last\n      is recorded for use by the ContractManager.\n   *)  \n\n  Definition receive\n             (chain : Chain) (ctx : ContractCallContext)\n             (state : State) (msg : option Msg)\n    : option (State * list ActionBody) :=\n    match msg with\n    | Some (update ext t) => if (Nat.ltb (currentTime state) t) then \n                              Some (state<|result := do trace <- (vmC (contract state) [] ext);\n                                                     Some (cutTrace trace (currentTime state) t)|>\n                                                     <|currentTime := t |>, [])\n                            else\n                              None\n    | None => Some (state,[])\n    end.\nEnd Interp.\n", "meta": {"author": "malthelange", "repo": "CLVM", "sha": "e80aef02c3112b5b62db79bc2b233020367b0bde", "save_path": "github-repos/coq/malthelange-CLVM", "path": "github-repos/coq/malthelange-CLVM/CLVM-e80aef02c3112b5b62db79bc2b233020367b0bde/execution/CLInterp/CLInterp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2089021278684037}}
{"text": "Require Import List.\nFrom mathcomp Require Import ssreflect ssrbool ssrnat eqtype seq tuple ssrfun.\nFrom mathcomp Require Import choice path bigop fintype.\nRequire Import Lib.Base Ipdl.Exp Ipdl.Core String Ipdl.Lems Lib.TupleLems Ipdl.Tacs Lib.Dist Ipdl.Big Pars Lib.Set Lib.OrdLems.  \nRequire Import CoinFlip CFold.\n\nLemma eq_EqRxn {chan} {t} (r1 r2 : rxn t) :\n  r1 = r2 ->\n  @EqRxn chan _ r1 r2.\n  move => -> //=.\nQed.\n\nDefinition CFRealParty_honest_external {chan : Type -> Type} (k : nat) {n} (committed : (n.+1).-tuple (chan unit)) (opened : (n.+1).-tuple (chan k.-bv)) (commit : chan k.-bv) (open : chan unit)  :=\n  committed_sum <- newvec n.+1 @ unit ;;\n  opened_sum' <- newvec n.+1 @ k.-bv ;;\n  pars [::\n          commit ::= (Samp (Unif ));\n          read_all committed committed_sum;\n          Out open (copy (tnth committed_sum ord_max));\n          @cfold chan _ k.-bv k.-bv opened xort id opened_sum'\n       ].\n          \nLemma CFRealParty_honest_externalE {chan : Type -> Type} (k : nat) {n} (committed : (n.+1).-tuple (chan unit)) (opened : (n.+1).-tuple (chan k.-bv)) (commit : chan k.-bv) (open : chan unit) (out : chan k.-bv) (opened_sum : (n.+1).-tuple (chan k.-bv)) :\n  pars [::\n          CFRealParty_honest k _ committed opened commit open out;\n          @cfold chan _ k.-bv k.-bv opened xort id opened_sum ] =p \n  pars [::\n          CFRealParty_honest_external k committed opened commit open ;\n          Out out (copy (tnth opened_sum ord_max)); \n       @cfold chan _ k.-bv k.-bv opened xort id opened_sum ].\n  rewrite newPars.\n  rewrite newPars.\n  setoid_rewrite newPars.\n  apply EqCongNew_vec => committed_sum.\n  apply EqCongNew_vec => opened_sum'.\n  rewrite pars_pars; simpl.\n  \n  rewrite pars_pars; simpl.\n  swap_tac 0 5.\n  swap_tac 1 3.\n  rewrite (pars_split 2) //=.\n  rewrite cfold2_det_copy.\n  rewrite -pars_cat //=.\n  swap_tac 0 4.\n  rewrite pars_inline_from_big //=.\n  swap_tac 0 4.\n  rewrite (pars_split 2) //=.\n  rewrite -cfold2_det_copy.\n  rewrite -pars_cat //=.\n  align.\n  rewrite /copy; apply EqCongReact; simp_rxn; done.\n  apply _.\n  apply _.\nQed.\n\nLemma CFRealPartyE {chan : Type -> Type} (k : nat) {n} (honest : pred 'I_(n.+1)) advCommit advOpen advCommitted advOpened i committed opened commit open out opened_sum :\n  pars [::\n          CFParty k _ honest advCommit advOpen advCommitted advOpened i committed opened commit open out;\n          @cfold chan _ k.-bv k.-bv opened xort id opened_sum ] =p \n  pars [::\n          if honest i then pars [::\n                                   CFRealParty_honest_external k committed opened commit open; Out out (copy (tnth opened_sum ord_max))] else CFRealParty_corr k _ advCommit advOpen advCommitted advOpened i committed opened commit open;\n       @cfold chan _ k.-bv k.-bv opened xort id opened_sum ].\n  rewrite /CFParty.\n  destruct (honest i).\n  rewrite pars_pars.\n  apply CFRealParty_honest_externalE.\n  done.\nQed.\n\nLemma CFRealParty_compE {chan : Type -> Type} (k : nat) {n} (honest : pred 'I_(n.+1)) advCommit advOpen advCommitted advOpened committed opened commit open out opened_sum :\n  pars [::\n         \\||_(i < n.+1) CFParty k _ honest advCommit advOpen advCommitted advOpened i committed opened (tnth commit i) (tnth open i) (tnth out i) ; \n          @cfold chan _ k.-bv k.-bv opened xort id opened_sum ] =p \n  pars [::\n          \\||_(i < n.+1 | honest i) CFRealParty_honest_external k committed opened (tnth commit i) (tnth open i);\n          \\||_(i < n.+1 | honest i) Out (tnth out i) (copy (tnth opened_sum ord_max));\n       \\||_(i < n.+1 | ~~ honest i) CFRealParty_corr k _ advCommit advOpen advCommitted advOpened i committed opened (tnth commit i) (tnth open i);\n          @cfold chan _ k.-bv k.-bv opened xort id opened_sum ]. \n  etransitivity.\n  apply pars_big_replace.\n  intros.\n  apply CFRealPartyE.\n  simpl.\n  symmetry.\n  rewrite bigpar_mkcond.\n  swap_tac 0 1.\n  rewrite bigpar_mkcond.\n  swap_tac 0 2.\n  rewrite bigpar_mkcond.\n  simpl.\n  rewrite -par_in_pars.\n  rewrite -bigpar_par.\n  rewrite -par_in_pars.\n  rewrite -bigpar_par.\n  apply pars_big_replace; intros.\n  rewrite !par_in_pars.\n  destruct (honest i); simpl.\n  rewrite pars_prot0.\n  rewrite pars_pars //=.\n  swap_tac 0 1; rewrite pars_prot0.\n  swap_tac 0 1; rewrite pars_prot0.\n  done.\nQed.\n          \nLemma opened_sumE {chan : Type -> Type} (k : nat) {n} (commits : (n.+1).-tuple (chan k.-bv)) (opens : (n.+1).-tuple (chan unit)) (committed : (n.+1).-tuple (chan unit)) (opened : (n.+1).-tuple (chan k.-bv)) (opened_sum : (n.+1).-tuple (chan k.-bv))\n      (opens_sum : (n.+1).-tuple (chan unit))\n      (commits_sum : (n.+1).-tuple (chan k.-bv))\n  :\n  pars [::\n          @cfold _ _ k.-bv k.-bv commits xort id commits_sum;\n          read_all opens opens_sum;\n          @cfold _ _ k.-bv k.-bv opened xort id opened_sum;\n          \\||_(i < n.+1) FComm k (tnth commits i)  (tnth committed i) (tnth opens i) (tnth opened i)]  =p\n\n  pars [::\n          @cfold _ _ k.-bv k.-bv commits xort id commits_sum;\n          read_all opens opens_sum;\n       \\||_(i < n.+1) Out (tnth opened_sum i) (\n                                            _ <-- Read (tnth opens_sum i) ;;\n                                            x <-- Read (tnth commits_sum i) ;;\n                                            Ret x);\n          \\||_(i < n.+1)\n          FComm k (tnth commits i) (tnth committed i) (tnth opens i)  (tnth opened i)]. \n  swap_tac 0 3.\n  rewrite big_pars2 pars_pars //=.\n  swap_tac 0 3.\n  symmetry.\n  swap_tac 0 3.\n  rewrite pars_pars //=.\n  swap_tac 0 3.\n\n  apply pars_big_hybrid2.\n  intros.\n  symmetry.\n  rewrite /cfold_body.\n  destruct (ordP k0); subst.\n  swap_tac 0 1.\n  swap_tac 1 2.\n  rewrite pars_inline_from_big //=.\n  simp_at 0.\n  symmetry.\n  swap_tac 0 1.\n  swap_tac 1 3.\n  rewrite pars_inline_from_big //=.\n  rewrite {1}/cfold_body //=.\n  simp_at 0.\n  swap_at 0 0 1.\n  swap_tac 1 5.\n  rewrite pars_inline_from_big //=.\n  rewrite {1}/cfold_body //=.\n  apply pars_cons_cong.\n  apply EqCongReact.\n  simp_rxn.\n  rewrite /copy.\n  r_swap 0 1; done.\n\n  swap_tac 0 1.\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 1.\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 2.\n  apply pars_cons_cong; rewrite //=.\n  \n  swap_tac 0 1.\n  swap_tac 1 2.\n  rewrite pars_inline_from_big; rewrite //=.\n  simp_at 0.\n  swap_at 0 0 2.\n  swap_tac 1 2.\n  rewrite pars_inline_from_big; rewrite //=.\n  simp_at 0.\n  symmetry.\n  swap_tac 0 1.\n\n  swap_tac 1 3.\n  rewrite pars_inline_from_big; rewrite //=.\n\n  rewrite {1}/cfold_body //=.\n  simp_at 0.\n  swap_at 0 0 2.\n  swap_tac 1 5.\n  rewrite pars_inline_from_big; rewrite //=.\n  apply pars_cons_cong.\n  rewrite /cfold_body //=.\n  apply EqCongReact.\n  simp_rxn.\n  r_swap 0 3.\n  apply EqRxnBind.\n  apply eq_EqRxn.\n  congr (_ _).\n  congr (_ _ _).\n  apply/eqP; rewrite eqE //=.\n  intros.\n  \n  r_swap 0 1.\n  apply EqRxnBind.\n  apply eq_EqRxn.\n  congr (_ _).\n  congr (_ _ _).\n  apply/eqP; rewrite eqE //=.\n  intros.\n\n  r_swap 0 1.\n  apply EqBind_r; intro.\n  rewrite /copy.\n  symmetry; simp_rxn.\n  apply EqBind_r; intro.\n  done.\n  swap_tac 0 2.\n  apply pars_cons_cong; rewrite //=.\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 2.\n  apply pars_cons_cong; rewrite //=.\nQed.\n\nDefinition CFRealSimpl {chan : Type -> Type} (k : nat) {n}\n           (honest : pred 'I_(n.+1))\n           (out advCommit : (n.+1).-tuple (chan k.-bv)) \n           (advOpen : (n.+1).-tuple (chan unit))\n           (advCommitted : (n.+1).-tuple ((n.+1).-tuple (chan unit)))\n           (advOpened : (n.+1).-tuple ((n.+1).-tuple (chan k.-bv))) :=\n  commit <- newvec n.+1 @ k.-bv ;;\n  committed <- newvec n.+1 @ unit ;;\n  open <- newvec n.+1 @ unit ;;\n  opened <- newvec n.+1 @ k.-bv ;;\n  commits_sum <- newvec n.+1 @ k.-bv ;;\n  opens_sum <- newvec n.+1 @ unit ;;\n  pars [::\n          \\||_(i < n.+1) FComm k (tnth commit i) (tnth committed i) (tnth open i) (tnth opened i);\n          \\||_(i < n.+1 | honest i) CFRealParty_honest_external k committed opened (tnth commit i) (tnth open i);\n       \\||_(i < n.+1 | honest i) Out (tnth out i)\n          (\n            _ <-- Read (tnth opens_sum ord_max) ;;\n            x <-- Read (tnth commits_sum ord_max) ;;\n            Ret x);\n       \\||_(i < n.+1 | ~~ honest i) CFRealParty_corr k _ advCommit advOpen advCommitted advOpened i committed opened (tnth commit i) (tnth open i);\n          @cfold _ _ k.-bv k.-bv commit xort id commits_sum;\n          read_all open opens_sum\n]. \n\n\nLemma CFRealSimplE {chan : Type -> Type} (k : nat) {n}\n           (honest : pred 'I_(n.+1))\n           (out advCommit : (n.+1).-tuple (chan k.-bv)) \n           (advOpen : (n.+1).-tuple (chan unit))\n           (advCommitted : (n.+1).-tuple ((n.+1).-tuple (chan unit)))\n           (advOpened : (n.+1).-tuple ((n.+1).-tuple (chan k.-bv))) :\n  CFReal k _ honest out advCommit advOpen advCommitted advOpened =p\n  CFRealSimpl k honest out advCommit advOpen advCommitted advOpened.\n  rewrite /CFReal.\n  etransitivity.\n  apply EqCongNew_vec => commit .\n  apply EqCongNew_vec => committed .\n  apply EqCongNew_vec => open .\n  apply EqCongNew_vec => opened .\n  rewrite -(@new_cfold_remove chan _ k.-bv k.-bv commit xort id).\n  apply EqCongNew_vec => commits_sum .\n  rewrite -(@new_cfold_remove chan _ unit unit open (fun _ _ => tt) (fun _ => tt)).\n  apply EqCongNew_vec => opens_sum .\n  rewrite -(@new_cfold_remove chan _ k.-bv k.-bv opened xort id).\n  apply EqCongNew_vec => opened_sum.\n  swap_tac 0 4.\n  swap_tac 1 4.\n  rewrite (pars_split 2); simpl.\n  rewrite CFRealParty_compE.\n  rewrite -pars_cat //=.\n  swap_tac 0 4.\n  swap_tac 1 6.\n  swap_tac 2 3.\n  swap_tac 3 5.\n  rewrite (pars_split 4); simpl.\n  rewrite opened_sumE.\n  rewrite -pars_cat; simpl.\n  swap_tac 0 6.\n  swap_tac 1 2.\n  etransitivity.\n  apply pars_big_replace; intros.\n  rewrite pars_inline_from_big.\n  edit_tac 0.\n  simp_rxn.\n  done.\n  apply EqRefl.\n  done.\n  done.\n  apply EqRefl.\n\n  rewrite /CFRealSimpl.\n\n  apply EqCongNew_vec => commit .\n  apply EqCongNew_vec => committed .\n  apply EqCongNew_vec => open .\n  apply EqCongNew_vec => opened .\n\n  apply EqCongNew_vec => commits_sum .\n  apply EqCongNew_vec => opens_sum .\n\n  etransitivity.\n  etransitivity.\n  apply EqCongNew_vec => x; swap_tac 0 1.\n  apply EqRefl.\n  rewrite pars_big_remove.\n  apply EqRefl.\n\n  swap_tac 0 2.\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 2.\n  apply pars_cons_cong; rewrite //=.\n  apply pars_cons_cong; rewrite //=.\n  swap_tac 0 1.\n  apply pars_cons_cong; rewrite //=.\n  align.\nQed.\n", "meta": {"author": "ipdl", "repo": "ipdl", "sha": "d41b022c9a216acfefaefcbd0ede9e52e350ab8a", "save_path": "github-repos/coq/ipdl-ipdl", "path": "github-repos/coq/ipdl-ipdl/ipdl-d41b022c9a216acfefaefcbd0ede9e52e350ab8a/theories/protocols/CoinFlip/Proof/CFReal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.20890212533746796}}
{"text": "Require Import Coq.Lists.List.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\n\nRequire Import Cava.Expr.\nRequire Import Cava.ExprProperties.\nRequire Import Cava.Invariant.\nRequire Import Cava.Primitives.\nRequire Import Cava.Semantics.\nRequire Import Cava.TLUL.\nRequire Import Cava.Types.\nRequire Import Cava.Util.BitArithmetic.\nRequire Import Cava.Util.List.\nRequire Import Cava.Util.Tactics.\n\nRequire Import coqutil.Tactics.Simp.\nRequire Import coqutil.Tactics.Tactics.\n\nImport ListNotations.\n\nSection Var.\n  Import Expr.\n  Import ExprNotations.\n  Import PrimitiveNotations.\n\n  Local Open Scope N.\n\n  Context {var : tvar}.\n\n  Definition incr_state := BitVec 2.\n  Definition Idle       := Constant incr_state 0.\n  Definition Busy1      := Constant incr_state 1.\n  Definition Busy2      := Constant incr_state 2.\n  Definition Done       := Constant incr_state 3.\n\n  Definition inner\n    : Circuit _ [Bit; BitVec 32] (Bit ** BitVec 32)\n    := {{\n      fun valid data =>\n        let/delay '(istate; value) :=\n           let istate' :=\n               if istate == `Busy1` then `Busy2`\n               else if istate == `Busy2` then `Done`\n                    else if istate == `Done` then `Idle`\n                         else (* istate == `Idle` *)\n                           if valid then `Busy1`\n                           else `Idle` in\n\n           let value' :=\n               if istate == `Busy2` then value + `K 1`\n               else if istate == `Idle` then data\n                    else value in\n\n           (istate', value')\n             initially default\n           : denote_type (incr_state ** BitVec 32)\n        in\n        (istate == `Done`, value)\n       }}.\n\n  Definition incr\n    : Circuit _ [tl_h2d_t] tl_d2h_t\n    := {{\n      fun tl_h2d =>\n        (* Destruct and reassemble tl_h2d with a_address that matches the\n           tlul_adapter_reg interface. *)\n        let '(a_valid\n              , a_opcode\n              , a_param\n              , a_size\n              , a_source\n              , a_address\n              , a_mask\n              , a_data\n              , a_user\n              ; d_ready) := tl_h2d in\n        (* Bit #2 of the address determines which register is being accessed *)\n        (*    (STATUS or VALUE). Zero out the other bits. *)\n        let a_address := a_address & (`K 1` << 2) in\n        let tl_h2d := (a_valid\n                       , a_opcode\n                       , a_param\n                       , a_size\n                       , a_source\n                       , a_address\n                       , a_mask\n                       , a_data\n                       , a_user\n                       , d_ready) in\n\n        let/delay '(busy, done, registers; tl_d2h) :=\n           let '(tl_d2h'; req) := `tlul_adapter_reg` tl_h2d registers in\n           let '(is_read, is_write, address, write_data; _write_mask) := req in\n\n           let '(inner_res_valid; inner_res) := `inner` (!busy && !done && is_write) write_data in\n\n           let busy' :=\n               if busy then !inner_res_valid\n               else !done && is_write in\n\n           let done' :=\n               if busy then inner_res_valid\n               else if done then !(is_read && address == `K 0`)\n                    else done in\n\n           let registers' :=\n               if inner_res_valid then `replace` registers `K (sz:=1) 0` inner_res\n               else registers in\n\n           let registers' :=\n               if busy' then `replace` registers' `K (sz:=1) 1` `K 2`\n               else if done' then `replace` registers' `K (sz:=1) 1` `K 4`\n                    else `replace` registers' `K (sz:=1) 1` `K 1` in\n\n           (busy', done', registers', tl_d2h') initially\n           (false, (false, ([0; 1], set_a_ready true (default (t:=tl_d2h_t)))))\n           : denote_type (Bit ** Bit ** Vec (BitVec 32) 2 ** tl_d2h_t)\n        in\n\n        tl_d2h\n       }}.\nEnd Var.\n\nDefinition sim {s i o} (c : Circuit s i o) (input : list (denote_type i))\n  : list (denote_type s * denote_type i * denote_type o) :=\n  fst (List.fold_left (fun '(acc, s) i =>\n                         let '(s', o) := step c s i in\n                         (acc ++ [(s, i, o)], s'))\n                      input\n                      ([], reset_state c)).\n\nExample sample_trace :=\n  Eval compute in\n    let nop := set_d_ready true tl_h2d_default in\n    let read_reg (r : N) :=\n        set_a_valid true\n        (set_a_opcode Get\n        (set_a_size 2%N\n        (set_a_address r\n        (set_d_ready true tl_h2d_default)))) in\n    let write_val (v : N) :=\n        set_a_valid true\n        (set_a_opcode PutFullData\n        (set_a_size 2%N\n        (set_a_address 0%N (* value-ref *)\n        (set_a_data v\n        (set_d_ready true tl_h2d_default))))) in\n\n    sim incr\n        [ (nop, tt)\n          ; (read_reg 4, tt) (* status *)\n          ; (nop, tt)\n          ; (write_val 42, tt)\n          ; (nop, tt)\n          ; (nop, tt)\n          ; (read_reg 4, tt) (* status *)\n          ; (nop, tt)\n          ; (read_reg 0, tt) (* value *)\n          ; (nop, tt)\n          ; (read_reg 4, tt) (* status *)\n        ]%N.\n(* Print sample_trace. *)\n\nSection Spec.\n  Local Open Scope N.\n\n  Variant repr_state :=\n  | ReprIdle\n  | ReprBusy (data : N) (count : nat)\n  | ReprDone (res : N).\n\n  Notation inner_repr := repr_state.\n\n  Global Instance inner_invariant : invariant_for inner inner_repr :=\n    fun (state : denote_type (state_of inner)) repr =>\n      let '(istate, value) := state in\n      match repr with\n      | ReprIdle => istate = 0\n      | ReprBusy data c => (0 < c <= 2)%nat /\\ istate = N.of_nat c /\\ value = data\n      | ReprDone res => istate = 3 /\\ value = res\n      end.\n\n  Definition inner_spec_step (input : denote_type (input_of inner)) repr :=\n    let '(valid, (data, tt)) := input in\n    match repr with\n    | ReprIdle => if valid then ReprBusy data 1 else ReprIdle\n    | ReprBusy data 2 => ReprDone ((data + 1) mod 2^32)\n    | ReprBusy data c => ReprBusy data (c + 1)\n    | ReprDone _ => ReprIdle\n    end.\n\n  Instance inner_specification\n    : specification_for inner inner_repr :=\n    {| reset_repr := ReprIdle;\n\n       update_repr :=\n         fun (input : denote_type (input_of inner)) repr =>\n           inner_spec_step input repr;\n\n       precondition :=\n         fun (input : denote_type (input_of inner)) repr => True;\n\n       postcondition :=\n         fun (input : denote_type (input_of inner)) repr\n           (output : denote_type (output_of inner)) =>\n           let repr' := inner_spec_step input repr in\n           match repr' with\n           | ReprDone res => output = (true, res)\n           | _ => exists res, output = (false, res)\n           end;\n    |}.\n\n  Lemma inner_invariant_at_reset : invariant_at_reset inner.\n  Proof.\n    simplify_invariant inner. reflexivity.\n  Qed.\n\n  Lemma inner_invariant_preserved : invariant_preserved inner.\n  Proof.\n    intros (valid, (data, t)) state repr. destruct t.\n    cbn in * |-. destruct state as (istate, value).\n    intros repr' ? Hinvar Hprec; subst.\n    simplify_invariant inner.\n    simplify_spec inner.\n    cbv [inner inner_spec_step]. stepsimpl.\n    repeat (destruct_pair_let; cbn [fst snd]).\n    destruct repr as [|? iiscount|?]; logical_simplify; subst.\n    - destruct valid; cbn; ssplit; lia.\n    - destruct iiscount as [|[|[|iiscount]]]; cbn; ssplit; lia.\n    - reflexivity.\n  Qed.\n\n  Lemma inner_output_correct : output_correct inner.\n  Proof.\n    intros (valid, (data, t)) state repr. destruct t.\n    cbn in * |-. destruct state as (istate, value).\n    remember (update_repr (c:=inner) (valid, (data, tt)) repr) as repr'.\n    intros Hinvar Hprec.\n    simplify_invariant inner.\n    simplify_spec inner.\n    cbv [inner inner_spec_step]. stepsimpl.\n    repeat (destruct_pair_let; cbn [fst snd]).\n    destruct repr as [|? iiscount|?]; logical_simplify; subst.\n    - destruct valid; eexists; cbn; ssplit; reflexivity.\n    - destruct iiscount as [|[|[|iiscount]]]; try lia; eexists; reflexivity.\n    - eexists. reflexivity.\n  Qed.\n\n  Existing Instances inner_invariant_at_reset inner_invariant_preserved\n           inner_output_correct.\n  Global Instance inner_correctness : correctness_for inner.\n  Proof. constructor; typeclasses eauto. Defined.\n\n  Definition repr := (repr_state * list N * TLUL.repr_state * inner_repr)%type.\n\n  Global Instance incr_invariant : invariant_for incr repr :=\n    fun (state : denote_type (state_of incr)) repr =>\n      let '((s_busy, (s_done, (s_regs, s_d2h))), (s_tlul, s_inner)) := state in\n      let '(r_state, r_regs, r_tl, r_inner) := repr in\n      tlul_invariant (reg_count:=2) s_tlul r_tl\n      /\\ match r_tl with\n        | TLUL.Idle =>\n          d_valid    s_d2h = false\n          /\\ d_error  s_d2h = false\n          /\\ a_ready  s_d2h = true\n        | TLUL.OutstandingAccessAckData h2d regs =>\n          d_valid    s_d2h = true\n          /\\ d_opcode s_d2h = AccessAckData\n          /\\ d_param  s_d2h = 0\n          /\\ d_size   s_d2h = (a_size h2d)\n          /\\ d_source s_d2h = (a_source h2d)\n          /\\ d_sink   s_d2h = 0\n          /\\ d_data   s_d2h = (List.nth (N.to_nat ((((a_address h2d) / 4) mod (2 ^ 30)))) regs 0%N)\n          /\\ d_user   s_d2h = 0\n          /\\ d_error  s_d2h = false\n          /\\ a_ready  s_d2h = false\n        | TLUL.OutstandingAccessAck h2d  =>\n          d_valid    s_d2h = true\n          /\\ d_opcode s_d2h = AccessAck\n          /\\ d_param  s_d2h = 0\n          (* /\\ d_size   s_d2h =  *)\n          /\\ d_source s_d2h = (a_source h2d)\n          /\\ d_sink   s_d2h = 0\n          /\\ d_user   s_d2h = 0\n          /\\ d_error  s_d2h = false\n          /\\ a_ready  s_d2h = false\n        end\n      /\\ inner_invariant s_inner r_inner\n      /\\ match r_state with\n        | ReprIdle => s_busy = false /\\ s_done = false\n                     /\\ r_inner = ReprIdle\n                     /\\ nth 1 r_regs 0%N = 1\n        | ReprBusy data count => s_busy = true /\\ s_done = false\n                                /\\ r_inner = ReprBusy data count\n                                /\\ nth 1 r_regs 0%N = 2\n        | ReprDone res => s_busy = false /\\ s_done = true\n                         /\\ (r_inner = ReprDone res \\/ r_inner = ReprIdle)\n                         /\\ nth 0 r_regs 0%N = res\n                         /\\ nth 1 r_regs 0%N = 4\n        end\n      /\\ s_regs = r_regs\n      /\\ length r_regs = 2%nat.\n\n  Existing Instance tl_specification.\n\n  Instance incr_specification\n    : specification_for incr repr :=\n    {| reset_repr := (ReprIdle, [0; 1], TLUL.Idle, ReprIdle);\n\n       update_repr :=\n         fun (input : denote_type (input_of incr)) repr =>\n           let '(i_h2d, tt) := input in\n           let '(r_state, r_regs, r_tl, r_inner) := repr in\n\n           let h2d := set_a_address (N.land (a_address i_h2d) 4) i_h2d in\n\n           let r_tl' :=\n               let tlul_input := (h2d, (r_regs, tt)) in\n               update_repr (c:=tlul_adapter_reg (reg_count:=2))\n                           tlul_input r_tl in\n\n           (* compute (some) tlul output *)\n           let '(is_read, is_write, address, write_data) :=\n               match r_tl' with\n               | TLUL.Idle => (false, false, 0, 0)\n               | TLUL.OutstandingAccessAckData _ _ =>\n                 match r_tl with\n                   | TLUL.Idle => (a_valid h2d, false, a_address h2d, 0)\n                   | _ => (false, false, 0, 0)\n                 end\n               | TLUL.OutstandingAccessAck _ =>\n                 match r_tl with\n                 | TLUL.Idle => (false, a_valid h2d, a_address h2d, a_data h2d)\n                 | _ => (false, false, 0, 0)\n                 end\n               end in\n\n           let r_inner' :=\n               let inner_input := (match r_state with ReprIdle => is_write | _ => false end,\n                                   (write_data, tt)) in\n               update_repr (c:=inner) inner_input r_inner in\n\n           let r_state' :=\n               match r_state with\n               | ReprDone _ =>\n                   if (is_read && (address =? 0))%bool then ReprIdle\n                   else r_state\n               | _ =>\n                 match r_inner' with\n                 | ReprBusy data count => ReprBusy data count\n                 | ReprDone res => ReprDone res\n                 | _ => r_state\n                 end\n               end in\n\n           let r_regs' :=\n               match r_inner' with\n               | ReprDone res => replace 0 res r_regs\n               | _ => r_regs\n               end in\n\n           let r_regs' :=\n               match r_state' with\n               | ReprIdle => replace 1 1 r_regs'\n               | ReprBusy _ _ => replace 1 2 r_regs'\n               | ReprDone _ => replace 1 4 r_regs'\n               end in\n\n           (r_state', r_regs', r_tl', r_inner');\n\n       precondition :=\n         fun (input : denote_type (input_of incr)) repr =>\n           let '(i_h2d, tt) := input in\n           let '(r_state, r_regs, r_tl, r_inner) := repr in\n\n           let h2d := set_a_address (N.land (a_address i_h2d) 4) i_h2d in\n\n           let tlul_input := (h2d, (r_regs, tt)) in\n\n           let prec_tlul :=\n               precondition (tlul_adapter_reg (reg_count:=2))\n                            tlul_input r_tl in\n\n           let prec_inner :=\n               forall d2h is_read is_write address write_data write_mask,\n                 postcondition (tlul_adapter_reg (reg_count:=2))\n                               tlul_input r_tl\n                               (d2h, (is_read, (is_write, (address, (write_data, write_mask)))))\n                 -> precondition inner (match r_state with ReprIdle => is_write | _ => false end,\n                                       (write_data, tt)) r_inner in\n\n           prec_tlul /\\ prec_inner;\n\n       postcondition :=\n         fun (input : denote_type (input_of incr)) repr\n           (output : denote_type (output_of incr)) =>\n           let '(i_h2d, tt) := input in\n           let '(r_state, r_regs, r_tl, r_inner) := repr in\n           let h2d := set_a_address (N.land (a_address i_h2d) 4) i_h2d in\n\n           (* let postc_tlul := *)\n           (*     let tlul_input := (h2d, (r_regs, tt)) in *)\n           (*     exists req, *)\n           (*       postcondition (tlul_adapter_reg (reg_count:=2)) *)\n           (*                     tlul_input r_tl *)\n           (*                     (output, req) in *)\n           (* postc_tlul; *)\n           True;\n    |}.\n\n  Lemma incr_invariant_at_reset : invariant_at_reset incr.\n  Proof.\n    simplify_invariant incr.\n    cbn. ssplit; [apply (tlul_adapter_reg_invariant_at_reset (reg_count:=2))\n                 |reflexivity..].\n  Qed.\n\n  Existing Instance tlul_adapter_reg_correctness.\n\n  Lemma incr_invariant_preserved : invariant_preserved incr.\n  Proof.\n    intros (h2d, t) state (((r_state, r_regs), r_tl), r_inner). destruct t.\n    cbn in * |-. destruct state as ((busy, (done, (registers, d2h))), (tl_st, inner_st)).\n    destruct_tl_h2d. destruct_tl_d2h.\n    intros repr' ? Hinvar Hprec; subst.\n    simplify_invariant incr. logical_simplify. subst.\n    simplify_spec incr. logical_simplify. subst.\n    (* destruct Hprec as [regs Hprec]. *)\n    match goal with\n    | |- context [step incr ?s ?i] =>\n      remember (step incr s i) as step eqn:Estep;\n        cbv -[Semantics.step inner tlul_adapter_reg] in Estep;\n          subst\n    end.\n    stepsimpl.\n    use_correctness.\n    clear H5.\n    rename H9 into Hpostc_tl.\n    repeat (destruct_pair_let; cbn [fst snd]).\n    ssplit.\n    - eapply tlul_adapter_reg_invariant_preserved.\n      2: apply H.\n      + reflexivity.\n      + assumption.\n    - pose (r_tl_:=r_tl); destruct r_tl; logical_simplify; subst.\n      + destruct_tl_h2d; destruct_tl_d2h; tlsimpl; subst.\n        pose (r_state_:=r_state); destruct r_state; cbn in *; logical_simplify; subst;\n          pose (a_valid_:=a_valid); (destruct a_valid;\n                                     [ match goal with\n                                       | H: true = true -> _ |- _ =>\n                                         destruct H; [auto|subst..]\n                                       end|]); cbn in *; logical_simplify; subst;\n            ssplit; auto.\n      + destruct_tl_h2d; destruct_tl_d2h; tlsimpl; subst.\n        pose (r_state_:=r_state); destruct r_state; cbn in *; logical_simplify; subst;\n          pose (d_ready_:=d_ready); destruct d_ready; cbn in *; logical_simplify; subst;\n            ssplit; auto.\n      + destruct_tl_h2d; destruct_tl_d2h; tlsimpl; subst.\n        pose (r_state_:=r_state); destruct r_state; cbn in *; logical_simplify; subst;\n          pose (d_ready_:=d_ready); destruct d_ready; cbn in *; logical_simplify; subst;\n            ssplit; reflexivity.\n    - eapply inner_invariant_preserved.\n      2: eassumption.\n      + simpl in *.\n        destruct r_inner; try reflexivity.\n        destruct r_tl eqn:Houts; logical_simplify; subst.\n        * destruct a_valid eqn:Hvalid; logical_simplify; subst.\n          -- match goal with\n             | H: true = true -> _ |- _ =>\n               destruct H; try reflexivity; subst\n             end; logical_simplify; subst;\n               boolsimpl; destruct r_state; logical_simplify; subst;\n                 cbn in Hpostc_tl |- *; logical_simplify; subst; reflexivity.\n          -- boolsimpl; destruct r_state; reflexivity.\n\n        * destruct d_ready; logical_simplify; subst;\n            boolsimpl; destruct r_state; reflexivity.\n        * destruct d_ready; logical_simplify; subst;\n            boolsimpl; destruct r_state; reflexivity.\n      + simplify_spec inner. auto.\n    - destruct r_tl; destruct r_inner; destruct r_state; destruct inner_st;\n        logical_simplify; subst; simplify_invariant inner; try discriminate.\n      all: simplify_spec (tlul_adapter_reg (reg_count:=2)); logical_simplify; tlsimpl; subst.\n      all: destruct a_valid; [destruct H3; subst|]; cbn in Hpostc_tl; logical_simplify; subst; cbn.\n      all: eauto.\n      all: destruct_tl_d2h; tlsimpl; subst.\n      all: try (destruct (N.land a_address 4 =? 0) eqn:Haddr;\n               ssplit; eauto;\n               destruct x0 as [|? [|]]; cbn in *; try discriminate; reflexivity).\n      all: try (destruct count as [|[|[|]]]; [lia|..|lia]; cbn;\n             ssplit; eauto;\n             destruct x0 as [|? [|]]; cbn in *; try discriminate; reflexivity).\n      all: try (destruct H6; discriminate).\n      all: try (destruct d_ready; logical_simplify; subst; cbn;\n                  ssplit; eauto;\n                  destruct x0 as [|? [|]]; cbn in *; try discriminate; reflexivity).\n    - destruct r_tl; destruct r_inner; destruct r_state; destruct inner_st;\n        logical_simplify; subst.\n      all: simplify_invariant inner.\n      all: try discriminate.\n      all: simplify_spec (tlul_adapter_reg (reg_count:=2)); logical_simplify; tlsimpl; subst.\n      all: destruct a_valid; [destruct H3; subst|]; cbn in Hpostc_tl; logical_simplify; subst; cbn.\n      all: eauto.\n      all: try (destruct (N.land a_address 4 =? 0) eqn:Haddr;\n               ssplit; eauto;\n               destruct x0 as [|? [|]]; cbn in *; try discriminate; reflexivity).\n      all: try (destruct count as [|[|[|]]]; [lia|..|lia]; cbn;\n             ssplit; eauto;\n             destruct x0 as [|? [|]]; cbn in *; try discriminate; reflexivity).\n      all: try (destruct H6; discriminate).\n      all: try (destruct d_ready; logical_simplify; subst; cbn;\n                  ssplit; eauto;\n                  destruct x0 as [|? [|]]; cbn in *; try discriminate; reflexivity).\n    - repeat destruct_one_match; rewrite ! length_replace; assumption.\n  Qed.\n\n  Lemma incr_output_correct : output_correct incr.\n  Proof.\n    intros ? **.\n    simplify_spec incr. destruct input. destruct d0. destruct r as [[[? ?] ?] ?].\n    apply I.\n  Qed.\n\n  Existing Instances incr_invariant_at_reset incr_invariant_preserved\n           incr_output_correct.\n  Global Instance incr_correctness : correctness_for incr.\n  Proof. constructor; typeclasses eauto. Defined.\nEnd Spec.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/firmware/IncrementWait/Incr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.359364131437828, "lm_q1q2_score": 0.20889948027151867}}
{"text": "Require Import compcert.lib.Maps.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import VST.msl.ageable.\n\nRequire Import VST.sepcomp.extspec.\nRequire Import VST.sepcomp.step_lemmas.\n\nRequire Import VST.veric.compcert_rmaps.\nRequire Import VST.veric.juicy_mem.\n\nDefinition pures_sub (phi phi' : rmap) :=\n  forall adr,\n  match resource_at phi adr with\n    | PURE k pp => resource_at phi' adr\n                 = PURE k (preds_fmap (approx (level phi')) (approx (level phi')) pp)\n    | _ => True\n  end.\n\nLemma pures_sub_trans phi1 phi2 phi3 :\n  (level phi3 <= level phi2)%nat ->\n  pures_sub phi1 phi2 ->\n  pures_sub phi2 phi3 ->\n  pures_sub phi1 phi3.\nProof.\n  intros lev S1 S2. intros l; specialize (S1 l); specialize (S2 l).\n  destruct (phi1 @ l); auto.\n  rewrite S1 in S2. rewrite S2.\n  f_equal.\n  rewrite (compose_rewr (preds_fmap _ _)).\n  rewrite preds_fmap_comp.\n  rewrite approx_oo_approx'; auto.\n  rewrite approx'_oo_approx; auto.\nQed.\n\nLemma pures_sub_refl phi : pures_sub phi phi.\nProof.\n  intros l.\n  destruct (phi @ l) eqn:E; auto; f_equal.\n  pose proof E as E_.\n  rewrite <-resource_at_approx, E_ in E. simpl in E.\n  congruence.\nQed.\n\nDefinition pures_eq (phi phi' : rmap) :=\n  pures_sub phi phi' /\\\n  (forall adr,\n   match resource_at phi' adr with\n    | PURE k pp' => exists pp, resource_at phi adr = PURE k pp\n    | _ => True\n  end).\n\nLemma pures_eq_refl phi : pures_eq phi phi.\nProof.\n  split. apply pures_sub_refl. intros l; destruct (phi @ l); eauto.\nQed.\n\nLemma pures_eq_trans phi1 phi2 phi3 :\n  level phi3 <= level phi2 ->\n  pures_eq phi1 phi2 ->\n  pures_eq phi2 phi3 ->\n  pures_eq phi1 phi3.\nProof.\n  intros lev [S1 E1] [S2 E2]; split. apply pures_sub_trans with phi2; auto.\n  intros l; specialize (E1 l); specialize (E2 l).\n  destruct (phi3 @ l); auto. destruct E2 as (pp, E2). rewrite E2 in E1; auto.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/veric/juicy_safety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.20889948027151864}}
{"text": "(*\n * © 2020 Massachusetts Institute of Technology.\n * MIT Proprietary, Subject to FAR52.227-11 Patent Rights - Ownership by the Contractor (May 2014)\n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n     List.\n\nFrom SPICY Require Import\n     MyPrelude\n     Maps\n     ChMaps\n     Messages\n     Keys\n     Automation\n     Tactics\n     Simulation\n     SyntacticallySafe\n     AdversaryUniverse\n\n     ModelCheck.Commutation\n     ModelCheck.ModelCheck\n     ModelCheck.ProtocolFunctions\n     ModelCheck.SilentStepElimination\n     ModelCheck.SteppingTactics\n     ModelCheck.InvariantSearch\n     ModelCheck.UniverseInversionLemmas\n.\n\nFrom protocols Require Import\n     ShareSecretProtocolSymmetricEnc\n.\n\nFrom SPICY Require IdealWorld RealWorld.\n\nImport IdealWorld.IdealNotations\n       RealWorld.RealWorldNotations\n       SimulationAutomation.\n\nFrom Frap Require Import Sets.\n\nModule Foo <: Sets.EMPTY.\nEnd Foo.\nModule Import SN := Sets.SetNotations(Foo).\n\nSet Implicit Arguments.\n\nOpen Scope protocol_scope.\n\nModule ShareSecretProtocolSecureSS <: AutomatedSafeProtocolSS.\n\n  Import ShareSecretSymmetricEncProtocol.\n\n  Definition t__hon := Nat.\n  Definition t__adv := Unit.\n  Definition b := tt.\n  Definition iu0  := ideal_univ_start.\n  Definition ru0  := real_univ_start.\n\n  Import Gen Tacs.\n\n  #[export] Hint Unfold t__hon t__adv b ru0 iu0 ideal_univ_start real_univ_start : core.\n\n  Lemma finitelyRuns : exists n, runningTimeMeasure ru0 n.\n  Proof.\n    autounfold; simpl.\n    eexists.\n    econstructor; simpl; find_runtime.\n\n    Unshelve.\n    all: exact 0.\n  Qed.\n\n  Lemma typechecks : syntactically_safe_U ru0.\n  Proof.\n    unfold syntactically_safe_U; intros.\n    autounfold\n    ; subst\n    ; simpl in *.\n\n    unfold compute_ids; simpl.\n    \n    focus_user; simpl\n    ; try solve [ do 2 eexists; split\n                  ; [ unshelve (repeat typechecks1)\n                      ; match goal with\n                        | [ |- bool ] => exact true\n                        | [ |- list safe_typ ] => exact []\n                        end\n                    | repeat verify_context_soundness ] ].\n\n    Unshelve.\n    all : exact TyDontCare.\n  Qed.\n    \n  Lemma summarizable : exists summaries, summarize_univ ru0 summaries.\n  Proof.\n    autounfold; unfold summarize_univ; simpl; intros.\n    unshelve (\n        eexists; intros; focus_user; simpl\n        ; (exists useless_summary; split; [ build_summary |]; eauto using useless_summary_summarizes)\n      ) ; exact $0.\n  Qed.\n    \n  Lemma lameness : @lameAdv t__adv b (RealWorld.adversary ru0).\n  Proof.\n    unfold lameAdv; autounfold; simpl; eauto.\n  Qed.\n\n  Set Ltac Profiling.\n\n  Lemma safe_invariant :\n    invariantFor\n      {| Initial := {(ru0, iu0, true)}; Step := @stepSS t__hon t__adv  |}\n      (@noresends_inv t__hon t__adv).\n  Proof.\n    unfold invariantFor\n    ; unfold Initial, Step\n    ; intros\n    ; simpl in *\n    ; split_ors\n    ; try contradiction\n    ; subst.\n\n    autounfold in H0\n    ; unfold fold_left, fst, snd in *.\n\n    time (\n        repeat transition_system_step\n      ).\n\n    Unshelve.\n    all: exact 0 || auto.\n  Qed.\n\n  Show Ltac Profile.\n  \n  Lemma U_good : @universe_starts_sane _ Unit b ru0.\n  Proof.\n    autounfold;\n      unfold universe_starts_sane; simpl.\n    repeat (apply conj); intros; eauto.\n    - focus_user; auto.\n    - econstructor.\n    - unfold AdversarySafety.keys_honest; rewrite Forall_natmap_forall; intros.\n      unfold mkrUsr; simpl.\n      rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty; eauto.\n    - unfold lameAdv; simpl; eauto.\n  Qed.\n\n  Lemma universe_starts_safe : universe_ok ru0.\n  Proof.\n    pose proof (adversary_is_lame_adv_univ_ok_clauses U_good).\n    \n    unfold universe_ok\n    ; autounfold\n    ; simpl\n    ; intuition eauto\n    .\n\n    - econstructor; eauto.\n    - unfold keys_and_permissions_good; solve_simple_maps; intuition eauto.\n      solve_simple_maps; eauto.\n\n      rewrite Forall_natmap_forall; intros.\n\n      solve_simple_maps; simpl\n      ; unfold permission_heap_good; intros;\n        solve_simple_maps; solve_concrete_maps; eauto.\n\n    - unfold user_cipher_queues_ok.\n      rewrite Forall_natmap_forall; intros.\n      focus_user\n      ; simpl in *; econstructor; eauto.\n\n    - unfold honest_nonces_ok, honest_user_nonces_ok, honest_nonces_ok\n      ; repeat simple apply conj\n      ; intros\n      ; clean_map_lookups\n      ; intros\n      ; focus_user\n      ; try contradiction; try discriminate; simpl;\n        repeat (apply conj); intros; clean_map_lookups; eauto.\n\n    - unfold honest_users_only_honest_keys; intros.\n      focus_user;\n        subst;\n        simpl in *;\n        clean_map_lookups;\n        unfold mkrUsr; simpl; \n          rewrite !findUserKeys_add_reduce, findUserKeys_empty_is_empty;\n          eauto;\n          simpl in *;\n          solve_concrete_perm_merges;\n          solve_concrete_maps;\n          solve_simple_maps;\n          eauto.\n  Qed.\n  \n\nEnd ShareSecretProtocolSecureSS.\n", "meta": {"author": "mit-ll", "repo": "SPICY", "sha": "ad89c31a093ed2e0b7b4ef55c87ec9b175749fe0", "save_path": "github-repos/coq/mit-ll-SPICY", "path": "github-repos/coq/mit-ll-SPICY/SPICY-ad89c31a093ed2e0b7b4ef55c87ec9b175749fe0/protocols/Verification/ShareSecretProtocolSymmetricEncSecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.20888057579894712}}
{"text": "Set Implicit Arguments.\n(*Set Maximal Implicit Insertion.*)\n(*Set Contextual Implicit.*)\n(*Unset Strict Implicit.*)\n\nInductive Both t := Two : t -> t -> Both t.\n\nInductive MStack a : Type -> Type :=\n  M0 : MStack a a\n| MS : forall b, a -> a -> MStack (Both a) b -> MStack a b.\n\nSet Maximal Implicit Insertion.\nImplicit Arguments M0 [a].\nImplicit Arguments MS [a b].\nUnset Maximal Implicit Insertion.\n\n\nInductive Buffer a := \n  B0\n| B1: a -> Buffer a\n| B2: a -> a -> Buffer a.\n\nInductive Stuck a b :=\n  Stack :  Buffer a -> Buffer a -> MStack (Both a) b -> Stuck a b.\n\nInductive Nest f a : Type -> Type :=\n  Empty : Nest f a a\n| Full : forall b c, f a b -> Nest f b c -> Nest f a c.\n\nSet Maximal Implicit Insertion.\nImplicit Arguments Empty [f a].\nImplicit Arguments Full [f a b c].\nUnset Maximal Implicit Insertion.\n\nInductive SE f a c :=\n  NE : forall b, f a b -> Nest f b c -> SE f a c.\n\nSet Maximal Implicit Insertion.\nImplicit Arguments NE [f a b c].\nUnset Maximal Implicit Insertion.\n\nDefinition StackStack := SE Stuck.\n\nDefinition ThreeStack := Nest StackStack.\n\nInductive SM a :=\n  None\n| Some : a -> SM a.\n\nSet Maximal Implicit Insertion.\nImplicit Arguments None [a].\nUnset Maximal Implicit Insertion.\n\nInductive Deq a :=\n Deque : forall b c, MStack a b -> ThreeStack b c -> SM c -> Deq a.\n\nInductive Size := Small | Medium | Large.\n\nDefinition bufSize t (x:Buffer t) :=\n  match x with\n    | B0 => Small\n    | B1 _ => Medium\n    | B2 _ _ => Large\n  end.\n\nDefinition sameSize x y :=\n  match x,y with\n    | Small,Small => true\n    | Large,Large => true\n    | _,_ => false\n  end.\n\nDefinition nextSize x y :=\n  match y with\n    | Medium => x\n    | _ => y\n  end.\n\nDefinition SameSize x y :=\n  match x,y with\n    | Small,Small => True\n    | Large,Large => True\n    | _,_ => False\n  end.\n\n(*\nInductive BufsAltStart (xs ys:Size) \n  : forall a b, ThreeStack a b -> Prop :=\n    Stop : forall a, BufsAltStart xs ys (Empty _ a)\n  | Bit : forall t (x y:Buffer t) s u (r:ThreeStack s u) z, \n    ~(SameSize xs (bufSize x)) ->\n    ~(SameSize ys (bufSize y)) ->\n    BufsAltStart (nextSize xs (bufSize x))\n                 (nextSize ys (bufSize y))\n                 r ->\n    BufsAltStart xs ys (Full _ (NE _ (Stack x y z) (Empty _ _)) r)\n  | Go : forall t (x y:Buffer t) za (q:MStack (Both t) za) zb (z:Stuck za zb) zc (zs:Nest Stuck zb zc) zd (r:ThreeStack zc zd), \n    ~(SameSize xs (bufSize x)) ->\n    ~(SameSize ys (bufSize y)) ->\n    BufsAltStart (nextSize xs (bufSize x))\n                 (nextSize ys (bufSize y))\n                 (Full _ (@NE Stuck za zc zb z zs) r) ->\n    BufsAltStart xs ys (Full _ (NE _ (Stack x y q) (Full za z zs)) r).\n*)\n\n\nLtac cutThis x :=\n  let xx := fresh\n    in remember x as xx; destruct xx.\n\nInductive Top := Prefix | Suffix | Twofix.\n\nLtac crush := subst; (*unfold not;*) intros;\n  simpl in *; auto; subst; simpl in *; auto; subst;\n    match goal with\n      | [H:True |- _] => clear H; crush\n      | [H:~ False |- _] => clear H; crush\n      | [H:?x = ?x |- _] => clear H; crush\n      | [F:False |- _] => inversion F\n      | [H:?x = ?x -> False |- _] \n        => pose (H (@eq_refl _ x)); crush\n      | [H:?x <> ?x |- _] \n        => pose (H (@eq_refl _ x)); crush\n      | [H:Some _ = ?x \n        |- context[\n          match ?x with \n            | None => _ \n            | Some _ => _\n          end]]\n        => rewrite <- H; crush\n      | [H:true = ?x \n        |- context[if ?x then _ else _]]\n        => rewrite <- H; crush\n      | [H:false = ?x \n        |- context[if ?x then _ else _]]\n        => rewrite <- H; crush\n      | [H:false = true |- _] => inversion H\n      | [H:true = false |- _] => inversion H\n      | [H: _ /\\ _ |- _] => destruct H; crush\n      | [|- _ /\\ _ ] => split; crush\n      | [H: _ \\/ _ |- _] => destruct H; crush\n      | [H: None = Some _ |- _] => inversion H\n      | [H: Some _ = None |- _] => inversion H\n      | [H: Some ?x = Some ?y |- _] \n        => assert (x = y); inversion H; clear H; crush\n      | [H: Suffix = Prefix |- _] => inversion H\n      | [H: Prefix = Suffix |- _] => inversion H\n      | [H : None = ?x,\n         I : Some _ = ?x |- _] \n        => rewrite <- I in H; crush\n      | [H : Some _ = ?x,\n         I : Some _ = ?x |- _] \n        => rewrite <- I in H; inversion H\n      | [H: Small = Medium |- _] => inversion H\n      | [H: Large = Medium |- _] => inversion H\n      | [H: Medium = Small |- _] => inversion H\n      | [H: Medium = Large |- _] => inversion H\n      | [H: Large = Small |- _] => inversion H\n      | [H: Small = Large |- _] => inversion H\n      | [|- Small <> Medium] => discriminate\n      | [|- Small <> Large] => discriminate\n      | [|- Large <> Medium] => discriminate\n      | [|- Medium <> Large] => discriminate\n      | [|- Medium <> Small] => discriminate\n      | [|- Large <> Small] => discriminate\n      | [|- Some _ <> None] => discriminate\n      | [|- None <> Some _] => discriminate\n      | [|- Some _ <> Some _] => discriminate; crush\n      | [|- Some _ = Some _] => f_equal; crush\n      | [|- pair _ _ = pair _ _] => f_equal; crush      \n      | [H: ~ True |- _] => \n        let J := fresh\n          in pose (H I) as J; inversion J\n      | [H:(?x,?y) = (?p,?q) |- _] =>\n        inversion_clear H; crush\n      | _ => idtac\n    end.\n\n\nFixpoint bufsAltStart2 a b (m:Stuck a b) c d (n:Nest Stuck c d) (*d e (r:ThreeStack d e) *) (xs ys:Size) :=\n  match m with\n    | Stack x y _ =>\n      let xs' := bufSize x in\n        let ys' := bufSize y in\n          match sameSize xs xs', sameSize ys ys' with\n            | false,false =>\n              let xs2 := nextSize xs xs' in\n                let ys2 := nextSize ys ys' in\n                  match n with\n                    | Empty => Some (xs2,ys2)\n                    | Full _ _ z zs => bufsAltStart2 z zs xs2 ys2\n                  end\n            | _,_ => None\n          end\n  end.\n\n\nLtac equate x y :=\n  let H := fresh \"H\" in\n    assert (H : x = y); [ reflexivity | clear H ].\n\nLtac crush1 :=\n  crush;\n  match goal with\n    | [_:context[\n      match topCheck ?x ?y with\n        | None => _\n        | Some _ => _\n      end] |- _]\n      => cutThis (topCheck x y); desall\n    | [_:context[\n      match bufSize ?x with\n        | Small => _\n        | Medium => _\n        | Large => _\n      end] |- _]\n      => cutThis x; desall\n    | [|- context[\n      match topCheck ?x ?y with\n        | None => _\n        | Some _ => _\n      end]]\n      => cutThis (topCheck x y); desall\n    | [_:context[if nextTop1 ?x ?y then _ else _] |- _]\n      => cutThis (nextTop1 x y); desall\n    | [|- context[if nextTop1 ?x ?y then _ else _]]\n      => cutThis (nextTop1 x y); desall\n    | [|- context[if sameSize ?x ?y then _ else _]]\n      => cutThis (sameSize x y); desall\n    | [_: context[if sameSize ?x ?y then _ else _] |- _]\n      => cutThis (sameSize x y); desall\n    | [_:context[\n      match top2' ?x ?y with\n        | None => _\n        | Some _ => _\n      end] |- _]\n      => cutThis (top2' x y); desall\n    | [_:context[\n      match top3 ?x ?y with\n        | None => _\n        | Some _ => _\n      end] |- _]\n      => cutThis (top3 x y); desall\n    | [|- context[\n      match top3 ?x ?y with\n        | None => _\n        | Some _ => _\n      end]]\n      => cutThis (top3 x y); desall\n    | [ H:_ |- context[\n      match ?x with\n        | None => _\n        | Some _ => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_ |- context[\n      match ?x in MStack _ _ return _ with\n        | M0 => _\n        | MS _ _ _ _ => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_ |- context[\n      match ?x in Nest _ _ _ return _ with\n        | Empty => _\n        | Full _ _ _ _ => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_ |- context[\n      match ?x with\n        | NE _ _ _ => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_ |- context[\n      match ?x with\n        | Stack _ _ _ => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_,\n        _:context[\n      match ?x with\n        | Stack _ _ _ => _\n      end] |- _] => equate H x; cutThis x; desall\n    | [ H:_ |- context[\n      match ?x with\n        | B0 => _\n        | B1 _ => _\n        | B2 _ _ => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_ |- context[\n      match ?x with\n        | Prefix => _\n        | Suffix => _\n        | Twofix => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_,\n        _:context[\n      match ?x with\n        | Prefix => _\n        | Suffix => _\n        | Twofix => _\n      end] |- _] => equate H x; cutThis x; desall\n    | [ H:_,\n        _:context[\n      match ?x with\n        | B0 => _\n        | B1 _ => _\n        | B2 _ _ => _\n      end] |- _] => equate H x; cutThis x; desall\n    | [|- context[\n      match bufsAltStart2 ?p ?q ?r ?s with\n        | None => _\n        | Some _ => _\n      end]]\n      => cutThis (bufsAltStart2 p q r s); desall\n    | _ => idtac\n  end.\n\n\nLemma medPreNone :\n  forall \n    C D (y:Nest Stuck C D) \n    A B (x:Stuck A B) q p,\n    None = bufsAltStart2 x y Medium p ->\n    None = bufsAltStart2 x y q p.\nProof.\n  induction y; crush.\n\n  Ltac crush1 :=\n    crush;\n    match goal with\n      | [|- None = match x with\n                     | Stack _ _ _ => _\n\n\n  destruct x; crush.\n  destruct p; destruct q; destruct b0; destruct b; crush.\n  destruct x; crush.\n  destruct p; destruct q; destruct b0; destruct b1; crush.\nQed.\nHint Resolve medPreNone.\n\nLemma medPreSomeExt :\n  forall \n    C D (y:Nest Stuck C D) \n    A B (x:Stuck A B) p n q,\n    q <> Medium ->\n    Some (Medium,n) <> bufsAltStart2 x y q p.\nProof.\n  induction y; crush.\n  destruct x; crush.\n  destruct q; destruct b; crush;\n    destruct p; destruct b0; crush.\n  destruct x; crush.\n  destruct q; destruct b0; crush;\n    destruct p; destruct b1; crush;\n      try (eapply IHy; eauto); crush.\nQed.\nHint Resolve medPreSomeExt.\n\nLemma medPreSomeMed :\n  forall \n    C D (y:Nest Stuck C D) \n    A B (x:Stuck A B) p n q,\n    Some (Medium,n) = bufsAltStart2 x y Medium p ->\n    Some (q,n) = bufsAltStart2 x y q p.\nProof.\n  induction y; crush.\n  destruct x; crush.\n  destruct p; destruct q; destruct b0; destruct b; crush.\n  destruct x; crush.\n  \n  Ltac extMed :=\n    crush;\n    match goal with\n      | [ H:Some (Medium,_) = bufsAltStart2 _ _ Small _ |- _]\n        => assert False; apply medPreSomeExt in H; extMed\n      | [ H:Some (Medium,_) = bufsAltStart2 _ _ Large _ |- _]\n        => assert False; apply medPreSomeExt in H; extMed\n      | _ => crush\n    end.\n\n  destruct p; destruct q; destruct b0; destruct b1; extMed.\nQed.\nHint Resolve medPreSomeMed.\n    \nDefinition topCheck t (x y:Buffer t) :=\n  match x,y with\n    | B1 _, B1 _ => None\n    | B0, B1 _ => Some Prefix\n    | B2 _ _, B1 _ => Some Prefix\n    | B1 _, B0 => Some Suffix\n    | B1 _, B2 _ _ => Some Suffix\n    | _,_ => Some Twofix\n  end.\n\nDefinition top1 a b (z:Stuck a b) :=\n  match z with\n    | Stack x y _ => topCheck x y\n  end.\n\nDefinition nextTop1 x y :=\n  match x,y with\n    | Prefix,Prefix => true\n    | Suffix,Suffix => true\n    | _,_ => false\n  end.\n\nFixpoint top2' a b (x:Stuck a b) c d (yys:Nest Stuck c d) {struct yys} :=\n  match yys with\n    | Empty => top1 x\n    | (Full _ _ y ys) => \n      match top1 x, top2' y ys with\n        | Some v, Some w =>\n          if nextTop1 v w\n            then Some v\n            else None\n        | _,_ => None\n      end\n  end.\n\n\nLemma medPreSomeOth :\n  forall \n    C D (y:Nest Stuck C D) \n    A B (x:Stuck A B) p n r,\n    r <> Medium ->\n    Some (r,n) = bufsAltStart2 x y Medium p ->\n    ((Some (r,n) = bufsAltStart2 x y Small p \n      /\\ None = bufsAltStart2 x y Large p)\n    \\/ (Some (r,n) = bufsAltStart2 x y Large p \n      /\\ None = bufsAltStart2 x y Small p)).\nProof.\n  induction y; crush.\n  destruct x; crush.\n  destruct b; crush; destruct p; destruct b0; crush.\n  destruct x; crush.\n  destruct p; destruct b1; crush;\n    destruct b0; crush.\nQed.\nHint Resolve medPreSomeOth.\n\nLemma extPreSomeSame :\n  forall \n    C D (y:Nest Stuck C D) \n    A B (x:Stuck A B) q p n,\n\n    Some (q,n) = bufsAltStart2 x y q p ->\n    (Some (Medium,n) = bufsAltStart2 x y Medium p \\/\n     Some (q,n) = bufsAltStart2 x y Medium p).\nProof.\n  induction y; crush.\n  destruct x; crush.\n  destruct q; destruct b; crush; destruct p; destruct b0; crush.\n  destruct x; crush.\n  destruct q; destruct b0; crush; destruct p; destruct b1; crush.\nQed.\nHint Resolve extPreSomeSame.\n  \nLemma extPreSomeMed :\n  forall \n    C D (y:Nest Stuck C D) \n    A B (x:Stuck A B) q p,\n    None <> bufsAltStart2 x y q p ->\n    None <> bufsAltStart2 x y Medium p.\nProof.\n  induction y; crush.\n  destruct x; crush.\n  destruct q; destruct b; crush; destruct p; destruct b0; crush.\n  destruct x; crush.\n  destruct q; destruct b0; crush; destruct p; destruct b1; crush;\n    try (eapply IHy in H; eauto); crush.\nQed.\nHint Resolve extPreSomeMed.\n\nLemma extPreSomeSame2 :\n  forall \n    C D (y:Nest Stuck C D) \n    A B (x:Stuck A B) q p n,\n    q <> Medium ->\n    Some (q,n) = bufsAltStart2 x y q p ->\n    ((forall z, Some (z,n) = bufsAltStart2 x y z p) \n      \\/ (Some (q,n) = bufsAltStart2 x y Medium p\n        /\\ forall r, r <> q -> r <> Medium -> \n          None = bufsAltStart2 x y r p)).\nProof.\n  induction y; crush.\n  destruct x; crush.\n  destruct q; destruct b; crush; destruct p; destruct b0; crush;\n    left; crush; destruct z; crush.\n  destruct x; crush.\n  cutThis (bufsAltStart2 f y (nextSize Medium (bufSize b0))\n    (nextSize p (bufSize b1))); crush.\n  left.\n  destruct z; crush; \n    destruct q; destruct b0; crush; \n      destruct b1; destruct p; crush;\n        eapply IHy in H0; crush.\n  destruct q; destruct b0; crush;\n    destruct p; destruct b1; crush;\n      try (eapply IHy in H0); crush;\n        try (abstract (left; crush; destruct z; crush));\n          try (abstract (right; crush; destruct r; crush)).\nQed.\nHint Resolve extPreSomeSame2.\n\nRequire Import caseTactic.\n\nLemma extPreSomeOpp :\n  forall \n    C D (y:Nest Stuck C D) \n    A B (x:Stuck A B) q p n r,\n    r <> q ->\n    Some (r,n) = bufsAltStart2 x y q p ->\n    (Some (r,n) = bufsAltStart2 x y Medium p /\\\n     None = bufsAltStart2 x y r p).\nProof.\n  induction y; crush;\n    destruct x; crush.\n  destruct p; crush; destruct b0; crush;\n    destruct q; crush; destruct b; crush.\n  destruct p; crush; destruct b0; crush;\n    destruct q; crush; destruct b; crush.\n  destruct p; crush; destruct b0; crush;\n    destruct q; crush; destruct b1; crush;\n      eapply IHy in H0; crush.\n  destruct p; crush; destruct b0; crush;\n    destruct q; crush; destruct b1; crush;\n      pose H0 as hcopy;\n        eapply IHy in hcopy; crush;\n          destruct r; crush.\nAbort.\n\nFixpoint bufsAltStart a b (r:ThreeStack a b) (xs ys:Size) :=\n  match r with\n    | Empty => True\n    | Full _ _ (NE _ p ps) qs => \n      match bufsAltStart2 p ps xs ys with\n        | None => False\n        | Some (xs',ys') => bufsAltStart qs xs' ys'\n      end\n  end.\n\nDefinition BufsAlternate t (x:Deq t) :=\n  match x with\n    | Deque _ _ _ y _ => bufsAltStart y Medium Medium\n  end.\n\nDefinition NextTop1 x y :=\n  match x,y with\n    | Prefix,Prefix => True\n    | Suffix,Suffix => True\n    | _,_ => False\n  end.\n\nDefinition top2 a b (x:StackStack a b) :=\n  match x with\n    | NE _ p q => top2' p q\n  end.\n\nFixpoint top3 a b (x:StackStack a b) d e (yys:ThreeStack d e) {struct yys} :=\n  match yys with\n    | Empty => top2 x\n    | Full _ _ y ys => \n      match top2 x, top3 y ys with\n        | Some v, Some w =>\n          if nextTop1 v w\n            then None\n            else Some v\n        | _,_ => None\n      end\n  end.\n\nDefinition topShape a b (x:ThreeStack a b) :=\n  match x with\n    | Empty => True\n    | Full _ _ y ys => \n      match top3 y ys with\n        | None => False\n        | _ => True\n      end\n  end.\nHint Unfold topShape.\n\nDefinition allShape a (x:Deq a) :=\n  match x with\n    | Deque _ _ _ b _ => topShape b\n  end.\n\nFixpoint lastPair2 (ans:Prop) (cont:Size->Size->Prop) a b (x:Stuck a b) c d (xs:Nest Stuck c d) :=\n  match xs with\n    | Empty => \n      match x with\n        | Stack p q rs =>\n          match rs with\n            | M0 => cont (bufSize p) (bufSize q)\n            | _ => cont Medium Medium\n          end\n      end\n    | Full _ _ y ys => lastPair2 ans cont y ys\n  end.\n\nFixpoint LastPair (ans:Prop) (cont:Size->Size->Prop) a b (x:ThreeStack a b)  :=\n  match x with\n    | Empty => ans\n    | Full _ _ y ys =>\n      match ys with\n        | Empty =>\n          match y with\n            | NE _ z zs => lastPair2 ans cont z zs\n          end\n        | _ => LastPair ans cont ys\n      end\n  end.\n\nDefinition BottomSome x y :=\n  match x,y with\n    | Small,Small => False\n    | _,_ => True\n  end.\n\nDefinition BottomNone x y :=\n  match x,y with\n    | Small,Small => False\n    | Small,_ => False\n    | _,Small => False\n    | _,_ => True\n  end.\n\nDefinition BottomOK a (x:Deq a) :=\n  match x with\n    | Deque _ _ _ b (Some _) => LastPair True BottomSome b\n    | Deque _ _ _ b None => LastPair True BottomNone b\n  end.\n\nDefinition invariants a (x:Deq a) := BottomOK x /\\ allShape x /\\ BufsAlternate x.\n\nDefinition cons13 a (x y:Buffer a) b (xs:MStack (Both a) b) c (t:ThreeStack b c) : ThreeStack a c := \n    match t with\n      | Empty => Full (NE (Stack x y xs) Empty) Empty\n      | Full _ _ (NE _ (Stack p q pq) r) s => \n        let t' := Full (NE (Stack p q pq) r) s in\n          let default := Full (NE (Stack x y xs) Empty) t' in \n        match topCheck x y, topCheck p q with\n          | Some i, Some j => \n            if nextTop1 i j\n              then Full (NE (Stack x y xs) (Full (Stack p q pq) r)) s\n              else Full (NE (Stack x y xs) Empty) t'\n          | _,_ => default\n        end\n    end.\nHint Unfold cons13.\n\nLtac equate x y :=\n  let H := fresh \"H\" in\n    assert (H : x = y); [ reflexivity | clear H ].\n\nLtac desall :=\n  crush;\n  match goal with\n    | [_:context[\n      match topCheck ?x ?y with\n        | None => _\n        | Some _ => _\n      end] |- _]\n      => cutThis (topCheck x y); desall\n    | [_:context[\n      match bufSize ?x with\n        | Small => _\n        | Medium => _\n        | Large => _\n      end] |- _]\n      => cutThis x; desall\n    | [|- context[\n      match topCheck ?x ?y with\n        | None => _\n        | Some _ => _\n      end]]\n      => cutThis (topCheck x y); desall\n    | [_:context[if nextTop1 ?x ?y then _ else _] |- _]\n      => cutThis (nextTop1 x y); desall\n    | [|- context[if nextTop1 ?x ?y then _ else _]]\n      => cutThis (nextTop1 x y); desall\n    | [|- context[if sameSize ?x ?y then _ else _]]\n      => cutThis (sameSize x y); desall\n    | [_: context[if sameSize ?x ?y then _ else _] |- _]\n      => cutThis (sameSize x y); desall\n    | [_:context[\n      match top2' ?x ?y with\n        | None => _\n        | Some _ => _\n      end] |- _]\n      => cutThis (top2' x y); desall\n    | [_:context[\n      match top3 ?x ?y with\n        | None => _\n        | Some _ => _\n      end] |- _]\n      => cutThis (top3 x y); desall\n    | [|- context[\n      match top3 ?x ?y with\n        | None => _\n        | Some _ => _\n      end]]\n      => cutThis (top3 x y); desall\n    | [ H:_ |- context[\n      match ?x with\n        | None => _\n        | Some _ => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_ |- context[\n      match ?x in MStack _ _ return _ with\n        | M0 => _\n        | MS _ _ _ _ => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_ |- context[\n      match ?x in Nest _ _ _ return _ with\n        | Empty => _\n        | Full _ _ _ _ => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_ |- context[\n      match ?x with\n        | NE _ _ _ => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_ |- context[\n      match ?x with\n        | Stack _ _ _ => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_,\n        _:context[\n      match ?x with\n        | Stack _ _ _ => _\n      end] |- _] => equate H x; cutThis x; desall\n    | [ H:_ |- context[\n      match ?x with\n        | B0 => _\n        | B1 _ => _\n        | B2 _ _ => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_ |- context[\n      match ?x with\n        | Prefix => _\n        | Suffix => _\n        | Twofix => _\n      end]] => equate H x; cutThis x; desall\n    | [ H:_,\n        _:context[\n      match ?x with\n        | Prefix => _\n        | Suffix => _\n        | Twofix => _\n      end] |- _] => equate H x; cutThis x; desall\n    | [ H:_,\n        _:context[\n      match ?x with\n        | B0 => _\n        | B1 _ => _\n        | B2 _ _ => _\n      end] |- _] => equate H x; cutThis x; desall\n    | [|- context[\n      match bufsAltStart2 ?p ?q ?r ?s with\n        | None => _\n        | Some _ => _\n      end]]\n      => cutThis (bufsAltStart2 p q r s); desall\n    | _ => idtac\n  end.\n\n\nLemma cons13shape : \n  forall a (x y:Buffer a)\n    b (xs:MStack (Both a) b)\n    c (t:ThreeStack b c)\n    i,\n    Some i = topCheck x y ->\n    topShape t ->\n    topShape (cons13 x y xs t).\nProof.\n  Ltac ifneq x y t :=\n    assert (x = y); [reflexivity|auto] || t.\n  Ltac here3 := unfold cons13 in *; desall;\n    match goal with\n      | [_ : Some _ = top3 (NE (Stack ?a ?b _) ?f) ?e,\n         _ : None = topCheck ?a ?b\n         |- _] => destruct e; desall; destruct f; desall; here3\n      | [_ : None = top3 (NE _ (Full (Stack ?a ?b _) ?f)) ?e,\n         _ : Some _ = topCheck ?a ?b\n         |- _] => destruct e; desall; destruct f; desall; here3\n      | [_ : _ = nextTop1 ?a ?b \n         |- _] => destruct a; destruct b; desall; here3\n      | [_ : Some ?d = top3 (NE (Stack ?a ?b _) ?f) ?e,\n         _ : Some ?c = topCheck ?a ?b\n         |- _] => \n      let thisone := destruct e; desall; destruct f; desall; here3\n        in ifneq c d thisone      \n      | _ => desall\n    end.\n  here3.\nQed.\n\nDefinition empty {a} := Deque M0 Empty (@None a).\n\nDefinition prepose' a b (x:ThreeStack a b) :=\n  let default := Medium in \n    match x with\n      | Empty => Medium\n      | Full _ _ (NE _ (Stack B0 _ _) _) _ => Small\n      | Full _ _ (NE _ (Stack (B2 _ _) _ _) _) _ => Large\n      | _ => default\n    end.\n\nDefinition prepose a (x:Deq a) :=\n  match x with\n    | Deque _ _ _ (Full _ _ (NE _ (Stack (B1 _) _ _) _) x) _ => prepose' x\n    | Deque _ _ _ x _ => prepose' x\n  end.\n\n(*\nDefinition npushHelp a (x:a) (xx:Deq a) : Deq a.\nintros.\ndestruct xx.\ndestruct m. destruct t. destruct s.\neapply Deque. apply M0. apply Empty. apply Some. exact x.\neapply Deque. apply MS. exact x. exact a0. apply M0. apply Empty. apply None.\napply empty.\napply empty.\nDefined.\n\nPrint npushHelp.\n*)\n\nLtac sizeSplit t :=\n  here3; eauto;\n    match goal with\n      | [_ : _ = sameSize ?a _,\n        b : Size |- _]\n        => equate a b; destruct a; sizeSplit t\n      | [_ : _ = sameSize _ (bufSize ?a),\n        b : Buffer _ |- _]\n        => equate a b; destruct a; sizeSplit t\n      | [|- Some _ <> None] => discriminate\n      | [|- Some _ <> Some _] => discriminate\n      | _ => let foo := eapply t; here3 in try (abstract foo)\n    end.\n\nLtac nextSize t :=\n  sizeSplit t;\n  match goal with\n    | [|- Some _ = Some _] => f_equal; nextSize t\n    | [_: _ = nextSize Medium (bufSize ?b) |- _]\n        => destruct b; nextSize t\n    | [H : Some (Medium,_) = bufsAltStart2 _ _ Small _ |- _]\n        => eapply medPreSomeExt in H; nextSize t\n    | [H : Some (Medium,_) = bufsAltStart2 _ _ Large _ |- _]\n        => eapply medPreSomeExt in H; nextSize t\n    | _ => auto\n  end.\n\n  Ltac topFix' t :=\n    nextSize t;\n    match goal with\n      | [_:Some Suffix = top2' (Stack (B2 _ _) _ _) ?a ,\n         A:_ |- _]\n        => equate A a; assert False; destruct a; topFix' t\n      | [_:Some Suffix = top2' (Stack (@B0 _) _ _) ?a ,\n         A:_ |- _]\n        => equate A a; assert False; destruct a; topFix' t\n      | _ => nextSize t\n    end.\n  Ltac topFix t :=\n    topFix' t;\n    match goal with\n      | _ => let foo := eapply t; eauto; topFix' t in try (abstract foo)\n    end.\n\n(*\nLemma startExt :\n  forall A B C D (f:Stuck A B) (N:Nest Stuck C D)\n    p w,\n    p <> Medium ->\n    forall z,\n      Some (Medium,z) <> bufsAltStart2 f N p w.\nProof.\n  \n  intros A B C D f N.\n  \n  \n  generalize dependent A;\n    generalize dependent B.\n  \n  induction N; sizeSplit IHN.\nQed.\nHint Resolve startExt.\n*)\n\n(*  \nLemma bufsAlt2PreExtNone : \n  forall \n    B C (N:Nest Stuck B C)\n    A (M:Stuck A B) w,\n    None = bufsAltStart2 M N Medium w ->\n    forall p, None = bufsAltStart2 M N p w.\nProof.\n  induction N; sizeSplit IHN.\nQed.\nHint Resolve bufsAlt2PreExtNone.\n\nLemma bufsAlt2PreExtSoMed : \n  forall \n    B C (N:Nest Stuck B C)\n    A (M:Stuck A B) w,\n    forall d, Some (Medium,d) = bufsAltStart2 M N Medium w ->\n    forall p, Some (p,d) = bufsAltStart2 M N p w.\nProof.\n  Print nextSize.\n\n  induction N; nextSize IHN.\nQed.\nHint Resolve bufsAlt2PreExtSoMed.\n*)\n\n\nLemma bufsAlt2PreExtSoExt : \n  forall \n    B C (N:Nest Stuck B C)\n    A (M:Stuck A B) w,\n    forall c, \n      c <> Medium ->\n      forall d, \n        Some (c,d) = bufsAltStart2 M N Medium w ->\n        Medium = prepose' (Full (NE M N) Empty) ->\n        topShape (Full (NE M N) Empty) ->\n        False.\nProof.\n  induction N; topFix IHN.\nQed.\nHint Resolve bufsAlt2PreExtSoExt.\n  \nLtac ese t :=\n    topFix t;\n    match goal with\n      | [_:?c <> Medium,\n         _:Some (?c,_) = bufsAltStart2 _ _ Medium _ |- False]\n        => eapply bufsAlt2PreExtSoExt; eauto; ese t\n      | _ => let foo := eapply t; eauto; topFix t in try (abstract foo)\n    end.\n\nLemma bufsAlt2PreExtSoExtExt : \n  forall \n    B C (N:Nest Stuck B C)\n    A (M:Stuck A B) w,\n    forall c, \n      c <> Medium ->\n      forall d, \n        Some (c,d) = bufsAltStart2 M N Medium w ->\n        match prepose' (Full (NE M N) Empty) with\n          | Medium => topShape (Full (NE M N) Empty) -> False\n          | Small => Some (c,d) = bufsAltStart2 M N Large w\n          | Large => Some (c,d) = bufsAltStart2 M N Small w\n        end.\nProof.\n\n  induction N; ese IHN.\nQed.\nHint Resolve bufsAlt2PreExtSoExtExt.\n\nLemma bufsAlt2PreExtSoMedMed :\n  forall \n    B C (N:Nest Stuck B C)\n    A (M:Stuck A B) w,\n    forall c, \n      c <> Medium ->\n      forall d, \n        Some (c,d) = bufsAltStart2 M N Medium w ->\n        Medium = prepose' (Full (NE M N) Empty) ->\n        topShape (Full (NE M N) Empty) -> False.\nProof.\n  eauto.\nQed.\nHint Resolve bufsAlt2PreExtSoMedMed.\n\nLemma bufsAlt2PreExtSoMedBig :\n  forall \n    B C (N:Nest Stuck B C)\n    A (M:Stuck A B) w,\n    forall c, \n      c <> Medium ->\n      forall d, \n        Some (c,d) = bufsAltStart2 M N Medium w ->\n        Small = prepose' (Full (NE M N) Empty) ->\n        Some (c,d) = bufsAltStart2 M N Large w.\nProof.\n  intros.\n  eapply bufsAlt2PreExtSoExtExt in H0; eauto.\n  rewrite <- H1 in H0. auto.\nQed.\nHint Resolve bufsAlt2PreExtSoMedBig.\n\nLemma bufsAlt2PreExtSoMedSml :\n  forall \n    B C (N:Nest Stuck B C)\n    A (M:Stuck A B) w,\n    forall c, \n      c <> Medium ->\n      forall d, \n        Some (c,d) = bufsAltStart2 M N Medium w ->\n        Large = prepose' (Full (NE M N) Empty) ->\n        Some (c,d) = bufsAltStart2 M N Small w.\nProof.\n  intros.\n  eapply bufsAlt2PreExtSoExtExt in H0; eauto.\n  rewrite <- H1 in H0. auto.\nQed.\nHint Resolve bufsAlt2PreExtSoMedSml.\n\n\n\n(*\nLemma bufsAltPreExt :\n  forall a b (t:ThreeStack a b) p q,\n    topShape t ->\n    prepose' t <> p ->\n    bufsAltStart t Medium q ->\n    bufsAltStart t p q.\nProof.\n\n\n\n  Ltac badMatch t :=\n    ese t;\n    match goal with\n      | [_:Some _ = top3 (NE ?a ?b) _,\n         _:None = bufsAltStart2 ?a ?b _ _,\n         B:_ |- _]\n        => equate B b; destruct b; badMatch t\n      | [J:match ?a with\n             | None => False\n             | Some _ => _\n           end,\n         I:None = ?a |- _]\n        => rewrite <- I in J; assert False; badMatch t\n      | [J:match ?a with\n             | None => _\n             | Some _ => _\n           end,\n         I:Some _ = ?a |- _]\n        => rewrite <- I in J; badMatch t\n      | [|- let 'pair _ _ := ?b in _] => destruct b; badMatch t\n      | [_:Some _ = top3 (NE (Stack (B1 _) (B1 _) _) (Full ?a ?b)) ?c,\n        _:None = bufsAltStart2 ?a ?b _ _,\n        A:_,\n        B:_,\n        C:_\n        |- False]\n        => equate A a; equate B b; equate C c;\n        destruct a; destruct b; destruct c; badMatch t\n      | _ => let foo := eapply t; eauto; ese t in try (abstract foo)\n    end.\n  induction t; badMatch IHt.\n  \n  Focus 3.\n  cutThis (bufsAltStart2 s n Medium Large); desall.\n  destruct p; desall.\n  erewrite <- bufsAlt2PreExtSoMedBig in HeqH.\n  Focus 4. destruct s; destruct n; destruct t; desall.\n\nrewrite\n\n  destruct t0.\n  destruct t; desall.\n  destruct t; desall. Print bufsAltStart2.\n  destruct s; desall. Print bufsAltStart2.\n  destruct n; desall.\n\n  Focus 2.\n\n  Focus 3.\n  destruct n; destruct s; destruct t; badMatch IHt. \n  destruct s0; destruct n; badMatch IHt.\n  cutThis (bufsAltStart2 s n Medium Large); badMatch IHt.\n  destruct p. destruct s0; badMatch IHt.\n  erewrite <- bufsAlt2PreExtSoMedBig in HeqH.\n  Focus 3. eauto. Focus 4. badMatch IHt.\n  Focus 4. destruct s; destruct n; badMatch IHt.\n  destruct s; destruct n; badMatch IHt.\n\n  Focus 2.\n\n  destruct n; destruct s; destruct t; badMatch IHt. \n\n  destruct s0; destruct n; badMatch IHt.\n\n\nUnfocus.\n  \n\n\n  Lemma matchLetPair :\n    forall (t:Type) (x:prod t t),\n      let (a,b) := x in a = b.\n  Proof.\n  Ltac noMatch :=\n    match goal with\n      | [|- let (_,_) := ?p in _]\n        => destruct p\n      | [|- match ?p with\n              | pair _ _ => _\n            end]\n        => destruct p\n    end.\n\n  noMatch.\n      \n\n  Ltac uh :=\n    match goal with\n      | [|- let (pair ?xs' ?ys') := ?p0 in bufsAltStart ?t ?xs' ?ys'] \n        => destruct p0\n    end.\n  Locate \"(_,_)\".\n  Print pair.\n\n  destruct p0.\n  destruct p; desall.\n  badMatch t.\n  eapply IHt.\n  desall.\n\n; topFix IHt.\n\nese IHt.\n  destruct n; badMatch IHt.\n\n  \n  \n  \n\n\n  destruct p0. \n  destruct t; simpl in *; auto.\n  destruct s1; simpl in *.\n\neapply IHt.\n  destruct n;  badMatch IHt.\n\n  destruct t; destruct n; badMatch IHt.\n\n\n  destruct p; ese IHt.\n\n\n\n  desall.\n  intros; simpl in *.\n  destruct f; simpl in *.\n  cutThis (bufsAltStart2 s n Medium q); simpl in *.\n  desall.\n  destruct p0; simpl in *.\n  destruct s0; simpl in *.\n\n  apply bufsAlt2PreExtSoExtExt in HeqH2.\n  desall. destruct t; desall.\n  destruct p0; desall. eapply IHt; desall.\n  destruct t; desall. \n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct p0; desall. eapply IHt; desall.\n  destruct t; desall. \n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct p0; desall. eapply IHt; desall.\n  destruct t; desall. \n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall; \n    destruct p; desall;\n      destruct q; desall.\n  destruct p0; desall. eapply IHt; desall.\n  destruct t; desall. \n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall; \n    destruct p; desall;\n      destruct q; desall.\n  destruct p0; desall. eapply IHt; desall.\n  destruct t; desall. \n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct p0; desall. eapply IHt; desall.\n  destruct t; desall. \n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct p0; desall. eapply IHt; desall.\n  destruct t; desall. \n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct p0; desall. eapply IHt; desall.\n  destruct t; desall. \n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct p0; desall. eapply IHt; desall.\n  destruct t; desall. \n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n  destruct t; destruct n; desall.\n\n  cutThis (prepose' (Full (NE s n) Empty)).\n  \n\n  \n\n  Focus 2.\n  eapply bufsAlt2PreExtSoMed in HeqH2.\n  rewrite <- HeqH2.\n  eapply IHt; auto.\n  destruct t; desall.\n  desall; destruct t; desall.\n  destruct s; simpl in *.\n  destruct t; simpl in *.\n  destruct n; destruct b1; simpl in *;\n    destruct b2; simpl in *;\n      destruct p; simpl in *; desall.\n  destruct q; desall.\n\n  Focus 2.\n\n  destruct t; desall.\n  destruct t; desall.\n  destruct n\n\n\n  induction t; desall.\n  cutThis (bufsAltStart2 (Stack (B0 a) b2 m) n Medium q); desall; eauto.\n  \n  cutThis (bufsAltStart2 s n p q); desall;\n    cutThis (bufsAltStart2 s n Medium q); desall.\n  Focus 2.\n  destruct p0. destruct p1.\n  destruct s; simpl in *.\n  fold (bufSize b1) in *.\n  \n\n  assert (\n    bufSize b1 <> p ->\n    match top3 (NE (Stack b1 b2 m) n) t with\n      | None => True\n      | Some _ => \n        bufsAltStart t s2 s3 ->\n        bufsAltStart t s0 s1\n    \n  \n\n  destruct s; destruct p; desall.\n  cutThis (bufsAltStart2 (Stack (B1 a0) b2 m) n Medium q); desall.\n\n  Ltac crr := \n    match goal with\n      | [H:(?x = ?x) -> False |- _] \n        => pose (H (@eq_refl _ x))\n    end.\n  crr.\n\n\n\n\nLemma bufsAlt2PreExt : \n  forall (f:Size -> Size -> Prop) \n    A B (M:Stuck A B) \n    C (N:Nest Stuck B C) \n    E (R:ThreeStack C E) p w,\n    (forall q z, (*prepose' R <> q*) (*q = p ->*) f Medium z -> f q z) ->\n    topShape R ->\n    topShape (Full (NE M N) R) ->\n    prepose' (Full (NE M N) R) <> p ->\n    bufsAltStart2 f M N R Medium w ->\n    bufsAltStart2 f M N R p w.\nProof.\n  intros f A B M C N.\n  generalize dependent f; generalize dependent A.\n  induction N; intros; desall;\n    repeat split; desall;\n      destruct p; desall.\n  eapply IHN; desall.\n  destruct R; desall;\n    destruct f; desall.\n  destruct f; desall;\n    destruct R; desall;\n      destruct N; desall.\n  eapply IHN; desall.\n  destruct R; desall;\n    destruct N; desall.\n  destruct f; desall;\n    destruct R; desall;\n      destruct N; desall.\nQed.\n\nLemma bufsAltPreExt :\n  forall a b (t:ThreeStack a b) p q,\n    topShape t ->\n    prepose' t <> p ->\n    bufsAltStart t Medium q ->\n    bufsAltStart t p q.\nProof.\n  induction t; intros; desall.\n  destruct p; desall.\n  eapply bufsAlt2PreExt; desall.\n  eapply IHt; desall.\n  destruct t; desall.\n  destruct s; desall.\n  destruct t; desall.\n      destruct n; desall.\n  \n\n  destruct s; destruct p; desall; eapply IHt; desall;\n    destruct t; desall.\n  destruct s; desall.\n  destruct s; desall.\n  destruct n; desall.\n  destruct\n  des\n  destruct s; desall.\n*)  \n\n(*\nLemma bufsAlt2PreExt : \n  forall (f:Size -> Size -> Prop) \n    A B (M:Stuck A B) \n    C (N:Nest Stuck B C) \n    E (R:ThreeStack C E) p w,\n    (forall q z, (*prepose' R <> q -> *) f Medium z -> f q z) ->\n    topShape R ->\n    topShape (Full (NE M N) R) ->\n    prepose' (Full (NE M N) R) <> p ->\n    bufsAltStart2 f M N R Medium w ->\n    bufsAltStart2 f M N R p w.\nProof.\n  intros f A B M C N.\n  generalize dependent f; generalize dependent A.\n  induction N; intros; desall;\n    repeat split; desall;\n      destruct p; desall.\n  eapply IHN; desall.\n  destruct R; desall.\n  destruct f; desall.\n  destruct R; desall.\n  destruct N; desall.\n  destruct N; desall.\n  destruct N; desall.\n  destruct N; desall.\n  destruct N; desall.\n  destruct N; desall.\n  destruct R; desall.\n  destruct N; desall.\n  destruct N; desall.\n  destruct N; desall.\n  destruct N; desall.\n  destruct N; desall.\n  destruct N; desall.\n  destruct p; desall.\nQed.\n*)\n\n(*\n  destruct b1; desall.\n  destruct R; desall;\n    destruct N; desall;\n      destruct f; desall.\n  \n  destruct p; desall.\n  destruct p; desall.\n  destruct p; desall.\n  \n\n\n\n  eapply H; desall.\n  destruct R; desall. \n  destruct s; desall.\n  destruct s; desall.\n  destruct R; desall.\n  destruct n; desall.\n\n  destruct p; desall.\n  cutThis (prepose' R); desall.\n  destruct R; desall.\n  destruct w; destruct s; desall.\n  destruct s; destruct R; desall.\n  destruct n; desall.\n  eapply H; desall.\n  destruct p; desall.\n  destruct p; desall.\n  destruct p; desall.\n  eapply IHN; desall.\n  destruct f; desall.\n  destruct p; desall.\n  destruct p; desall.\n  apply H; desall.\n  destruct w; destruct p; destruct b0; desall.\n  destruct p; desall.\n  destruct w; destruct p; destruct b1; desall.\n  destruct w; destruct p; destruct b1; desall.\n  eapply IHN; desall.\n  Focus 2.\n  destruct w; destruct b1; desall.\n  Unfocus.\n  destruct w; destruct b1; desall.\n  destruct f; destruct N; desall.\n\n\n  destruct w; destruct p; destruct b1; desall.\n\n  Print bufsAltStart2.\n  destruct p; desall;\n    destruct w; desall;\n      destruct R; desall;\n        destruct N; desall;\n          repeat split; desall.\n  apply H; crush.\n  pose (H3 I). inversion f0.\n  inversion H3.\n  simpl in *.\n  unfold not in *. crush.\n  crush.\n  unfold bufSize in *. desall. eapply H; auto.\n  eapply H; eauto; desall. destruct b0; desall.\n\n          destruct M; desall.\n\n  assert (forall A B (C:ThreeStack A B),\n    prepose' C <> Large ->\n    forall z,\n      z <> Medium ->\n      bufsAltStart C Medium z ->\n      bufsAltStart C Large z) as ans.\n\nLemma bufsAlt2PreMed : \n  forall \n    A B (M:Stuck A B) \n    C (N:Nest Stuck B C) p w\n    X Y (t : ThreeStack X Y),\n    (forall q r, bufsAltStart t q r -> bufsAltStart t Medium r) ->\n    let ext := bufsAltStart2 M N p w in\n      let med := bufsAltStart2 M N Medium w in\n        match ext with\n          | Some (a,b) =>\n            match med with\n              | None => False\n              | Some (c,d) => \n                \n                  bufsAltStart t a b -> \n                  bufsAltStart t c d\n            end\n          | _ => True\n        end.\nProof.\n  intros. generalize dependent w. generalize dependent A.\n  generalize dependent p.\n  induction N; desall.\n  destruct w; destruct b; destruct b0; desall; eauto.\n  destruct p0.\n  destruct b0; desall.\n  pose (IHN p _ f (nextSize w (bufSize b1))) as ans.\n  rewrite <- HeqH2 in *.\n  rewrite <- HeqH3 in *; desall.\n  destruct p0; destruct p1; desall.\n  destruct b0; desall; crush.\n  pose (IHN p _ f (nextSize w (bufSize b1))) as ans.\n  rewrite <- HeqH2 in *.\n  rewrite <- HeqH3 in *; desall.\nQed.\n\nLemma bufsAltPreMedium :\n  forall a b (t:ThreeStack a b) p q,\n    bufsAltStart t p q ->\n    bufsAltStart t Medium q.\nProof.\n  induction t; desall.\n  cutThis (bufsAltStart2 s n p q); desall.\n  pose (bufsAlt2PreMed s n p q) as C.\n  desall.\n  rewrite <- HeqH0 in C.\n  destruct p0; desall.\n  rewrite <- HeqH1 in C. desall.\n  eapply C; desall.\n  eapply IHt. eauto.\n  destruct p0.\n  cutThis (bufsAltStart2 s n p q).\n  pose (bufsAlt2PreMed s n p q) as C.\n  desall.\n  destruct p0.\n  pose (bufsAlt2PreMed s n p q) as C. desall.\n  rewrite <- HeqH0 in C.\n  rewrite <- HeqH1 in C. desall.\nQed.\nHint Resolve bufsAltPreMedium.\n*)\n\n(*\nnpush :: a -> Deque a -> Deque a\nnpush x (Deque M0 Empty None) = Deque M0 Empty (Some x) \nnpush x (Deque M0 Empty (Some y)) = Deque (MS x y M0) Empty None \nnpush x (Deque M0 (Full (NE (Stack B0 (B1 z) zs) Empty) xs) q) = Deque (MS x z zs) xs q \nnpush x (Deque M0 (Full (NE (Stack B0 (B1 z) zs) (Full y ys)) xs) q) = Deque (MS x z zs) (Full (NE y ys) xs) q \nnpush x (Deque M0 (Full (NE (Stack B0 z zs) Empty) xs) q) = Deque M0 (cons13 (B1 x) z zs xs) q\n*)\n(*\nnpush x (Deque M0 (Full (NE (Stack (B1 y) z zs) Empty) xs) q) = Deque M0 (Full (NE (Stack (B2 x y) z zs) Empty) xs) q\nnpush x (Deque M0 (Full (NE (Stack (B1 y) z zs) (Full r rs)) xs) q) = Deque M0 (Full (NE (Stack (B2 x y) z zs) Empty) (Full (NE r rs) xs)) q\nnpush x (Deque (MS y z zs) rs q) = Deque M0 (cons13 (B2 x y) (B1 z) zs rs) q\n*)\n\nDefinition npush a (x:a) (xx:Deq a) : Deq a :=\n  let default := xx in\n  match xx with\n    | Deque _ _ b c d =>\n      match b in MStack _ B return ThreeStack B _ -> Deq a with\n        | M0 => fun cc =>\n          match cc in Nest _ _ C return SM C -> Deq a with\n            | Empty =>\n              fun dd =>\n              match dd with\n                | None => Deque M0 Empty (Some x)\n                | Some y => Deque (MS x y M0) Empty None\n              end\n            | Full _ _ e xs => fun dd => \n              match e with\n                | NE _ f g =>\n                  match f  with\n                    | Stack B0 (B1 z) zs =>\n                      match g in Nest _ _ G return Nest _ G _ -> Deq a with\n                        | Empty => fun xsxs => Deque (MS x z zs) xsxs dd\n                        | Full _ _ y ys => fun xsxs => Deque (MS x z zs) (Full (NE y ys) xsxs) dd\n                      end xs\n                    | Stack B0 z zs => \n                      match g in Nest _ _ G return Nest _ G _ -> Deq a with\n                        | Empty => fun xsxs => Deque M0 (cons13 (B1 x) z zs xsxs) dd\n                        | _ => fun _ => default\n                      end xs\n                    | Stack (B1 y) z zs =>\n                      match g in Nest _ _ G return Nest _ G _ -> Deq a with\n                        | Empty => fun xsxs => Deque M0 (Full (NE (Stack (B2 x y) z zs) Empty) xsxs) dd\n                        | Full _ _ r rs => fun xsxs => Deque M0 (Full (NE (Stack (B2 x y) z zs) Empty) (Full (NE r rs) xsxs)) dd\n                      end xs\n\n                    | _ => default\n                  end\n              end\n          end d\n        | _ => fun _ => default\n      end c\n  end.\n\n\nLemma npushBottom : \n  forall a (x:a) xs,\n    BottomOK xs ->\n    BottomOK (npush x xs).\nProof.\n  intros; destruct xs.\n  ese H.\n\n\n  Ltac badMatch t :=\n    ese t;\n    match goal with\n      | [_:Some _ = top3 (NE ?a ?b) _,\n         _:None = bufsAltStart2 ?a ?b _ _,\n         B:_ |- _]\n        => equate B b; destruct b; badMatch t\n      | [J:match ?a with\n             | None => False\n             | Some _ => _\n           end,\n         I:None = ?a |- _]\n        => rewrite <- I in J; assert False; badMatch t\n      | [J:match ?a with\n             | None => _\n             | Some _ => _\n           end,\n         I:Some _ = ?a |- _]\n        => rewrite <- I in J; badMatch t\n      | [|- let 'pair _ _ := ?b in _] => destruct b; badMatch t\n      | [_:Some _ = top3 (NE (Stack (B1 _) (B1 _) _) (Full ?a ?b)) ?c,\n        _:None = bufsAltStart2 ?a ?b _ _,\n        A:_,\n        B:_,\n        C:_\n        |- False]\n        => equate A a; equate B b; equate C c;\n        destruct a; destruct b; destruct c; badMatch t\n      | [_:match ?x with\n             | Empty => _\n             | Full _ _ _ _ => _\n           end,\n         X:_ |- _]\n         => equate x X; destruct x; badMatch t\n      | _ => let foo := eapply t; eauto; ese t in try (abstract foo)\n    end.\n  badMatch H.\n  badMatch H.\nQed.\n\nLemma npushShape :\n  forall a (x:a) xs,\n    allShape xs ->\n    allShape (npush x xs).\nProof.\n\n  Ltac shapDes t :=\n    badMatch t;\n    match goal with\n      | [_:Some _ = top3 _ ?x,\n         X:_ |- topShape ?x]\n         => equate X x; destruct x; shapDes t\n      | [_:Some _ = top3 _ ?x,\n         _:None = top3 _ ?x,\n         X:_ |- False]\n         => equate X x; destruct x; shapDes t\n      | [_:Some ?a = top3 _ ?x,\n         _:Some ?b = top3 _ ?x,\n         X:_ |- False]\n         => equate X x; \n         let t1 := destruct x; shapDes t\n           in ifneq a b t1\n      | _ => let foo := eapply t; eauto; badMatch t in try (abstract foo)\n    end.\n\n  destruct xs;\n  shapDes H.\nQed.\n\nLemma npushSmallHelp : \n  forall A B (y:Nest Stuck A B) C (x:Stuck C A) p,\n    match bufsAltStart2 x y Small p with\n      | None => False\n      | Some (pair _ _) => True\n    end ->\n    None = bufsAltStart2 x y Medium p ->\n    Some Suffix = top2' x y ->\n    False.\nProof.\n  induction y; badMatch IHy.\nQed.\nHint Resolve npushSmallHelp.\n\n\nLemma npushSmallOth :\n  forall E A (n0:Nest Stuck E A) \n    B F (s1 : Stuck F B) C D (H0 : Nest StackStack C D)  p,\n    match bufsAltStart2 s1 n0 Small p with\n      | None => False\n      | Some (pair xs' ys') => bufsAltStart H0 xs' ys'\n    end -> \n    None = bufsAltStart2 s1 n0 Medium p -> \n    False.\nProof.\n  induction n0; badMatch IHn0.\nQed.\nHint Resolve npushSmallOth.\n\n\nLemma npushSmallThd :\n  forall \n    B A (n0:Nest Stuck B A) \n     F (s1 : Stuck F B)  \n     C D (H0 : Nest StackStack C D)\n     s0 s2,\n    Some Prefix = top3 (NE s1 n0) H0 ->\n    match bufsAltStart2 s1 n0 Small Large with\n      | None => False\n      | Some (pair xs' ys') => bufsAltStart H0 xs' ys'\n    end ->\n    Some (s0, s2) = bufsAltStart2 s1 n0 Medium Large ->\n    bufsAltStart H0 s0 s2.\nProof.\n  induction n0; badMatch IHn0;\n    induction H0; badMatch IHH0.\nQed.\nHint Resolve npushSmallThd.\n\nLemma npushSmall4 :\n  forall \n    B A (n0:Nest Stuck B A) \n     F (s1 : Stuck F B)  \n     C D (H0 : Nest StackStack C D)\n     s0 s2,\n    Some Twofix = top3 (NE s1 n0) H0 ->\n    match bufsAltStart2 s1 n0 Small Large with\n      | None => False\n      | Some (pair xs' ys') => bufsAltStart H0 xs' ys'\n    end ->\n    Some (s0, s2) = bufsAltStart2 s1 n0 Medium Large ->\n    bufsAltStart H0 s0 s2.\nProof.\n  induction n0; badMatch IHn0;\n    induction H0; badMatch IHH0.\nQed.\nHint Resolve npushSmall4.\n\n(*\nLemma npushSmall5 :\n  forall \n     C D (H0 : Nest StackStack C D)\n     B A (n0:Nest Stuck B A) \n     G H (n : Nest Stuck G H)\n     F (s1 : Stuck F B)  \n     I (s0 : Stuck I G) p q,\n     Some Prefix = top3 (NE s1 n0) H0 ->\n     q <> Medium ->\n     match bufsAltStart2 s0 n Small q with\n       | None => False\n       | Some (pair xs' ys') => \n         match bufsAltStart2 s1 n0 xs' ys' with\n           | None => False\n           | Some (pair xs'0 ys'0) => bufsAltStart H0 xs'0 ys'0\n         end\n     end ->\n     Some p = bufsAltStart2 s0 n Medium q ->\n     Some Suffix = top2' s0 n ->\n     let (xs',ys') := p in \n       let (xs', ys') := p in\n         match bufsAltStart2 s1 n0 xs' ys' with\n           | None => False\n           | Some (pair xs'0 ys'0) => bufsAltStart H0 xs'0 ys'0\n         end.\nProof.\n  \n  intros.\n  destruct p.\n  cutThis (bufsAltStart2 s0 n Small q).\n  induction n; badMatch IHn.\n  destruct p.\n  cutThis (bufsAltStart2 s1 n0 s3 s4).\n  assert False; crush.\n  destruct p.\n  induction n0; desall.\n  destruct b; destruct b0; destruct s3; destruct s4; \n    destruct H0; desall.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n  badMatch m.\n\n badMatch IHn0.\n  \n\n  \n  cutThis q.\n  \n  induction H0; badMatch IHH0.\n  induction n0; badMatch IHn0.\n  eapply IHn. eauto. Focus 2. eauto. badMatch IHn. eauto. eauto.\n  eapply IHn. eauto. Focus 2. eauto. crush. eauto. auto.\nQed.\n(*Hint Resolve npushSmall5.*)\n\n(*  let (xs', ys') := p in\n   match bufsAltStart2 s1 n0 xs' ys' with\n   | None => False\n   | Some (pair xs'0 ys'0) => bufsAltStart H0 xs'0 ys'0\n   end\n*)\n*)\n\nLemma npushBufs :\n  forall a (x:a) xs,\n    prepose xs <> Large ->\n    allShape xs ->\n    BufsAlternate xs ->\n    BufsAlternate (npush x xs).\nProof.\n  intros.\n  unfold BufsAlternate in *.\n  destruct xs; simpl in *.\n  destruct t; simpl in *.\n  desall.\n\n  desall.\n  unfold cons13; desall.\n  cutThis (bufsAltStart2 (Stack b2 b3 m0) n Small Small); crush.\n  eapply medPreNone in HeqH1. rewrite <- HeqH1 in HeqH3; crush.\n  destruct p.\n\n  cutThis (bufsAltStart2 (Stack b2 b3 m0) n Small Small); crush.\n  destruct p; crush.\n\n  destruct s2; desall.\n  pose HeqH3 as hh.\n  eapply extPreSomeSame2 in hh. desall.\n  pose HeqH1 as hh.\n  rewrite <- H2 in hh. desall.\n  destruct H0; desall.\n  eapply medPreNone in HeqH0. \n  rewrite <- HeqH0 in H1; crush.\n  destruct p; desall.\n\n\n  cutThis (bufsAltStart2 s1 n0 Small s3); crush.\n  destruct p; crush.\n  destruct s0; desall.\n  pose HeqH7 as hh.\n  eapply extPreSomeSame2 in hh. desall.\n  pose HeqH0 as hh.\n  rewrite <- H3 in hh. desall. crush. crush.\n  Check medPreNone.\n  destruct H0; desall.\n  cutThis (bufsAltStart2 s1 n0 Small s3); crush.\n  destruct p; crush.\n  \n  rewrite <- HeqH0 in Heq\n\n\n  assert \n    (forall E F (z:ThreeStack E F) \n      s t r u A B (x:Stuck A B) C D (y:Nest Stuck C D) v\n      m n w,\n      Some (s,t) = bufsAltStart2 x y m v ->\n      bufsAltStart z s t ->\n      Some (r,u) = bufsAltStart2 x y n w ->\n      bufsAltStart z r u) as ans.\n  clear.\n  induction z; desall.\n  cutThis (bufsAltStart2 s0 n0 s t); crush.\n  destruct p; desall. Focus 2.\n  cutThis (bufsAltStart2 s0 n0 s t); crush.\n  destruct p; desall. destruct p0; desall.\n  eapply IHz. Focus 2. eapply H0.\n  Focus 2. eapply HeqH0.\n  Focus 2. eauto.\n  pose (IHz _ _ _ _ _ _ _ _ _ _ _ _ _ _ HeqH0 H0 H1).\n  \n\n  destruct r; desall.\n  eapply IHz in HeqH0. Focus 3.\n\n  destruct t; desall.\n\n  clear HeqH1 HeqH0 H s m.\n\n  destruct p.\n  \n  assert \n    (forall E F (z:ThreeStack E F) \n      s t A B (x:Stuck A B) C D (y:Nest Stuck C D) v,\n      Some (s,t) = bufsAltStart2 x y Small v ->\n      bufsAltStart z s t ->\n      None = bufsAltStart2 x y Medium v ->\n      False) as ans.\n  clear.\n  induction z; desall.\n  eapply medPreNone in H1. rewrite <- H1 in H. crush.\n  eapply medPreNone in H1. rewrite <- H1 in H. crush.\n  \n  eapply ans; eauto.\n  destruct p.\n  \n  destruct f.\n  cutThis (bufsAltStart2 s0 n s t). crush. destruct p.\n  eapply IHz. eapply HeqH2.\n  destruct\n\n\n  eapply medPreNone in HeqH2. rewrite <- HeqH2 in H1. crush.\n  destruct p; desall. destruct s0; desall.\n  eapply medPreSomeOth in HeqH2; desall.\n  rewrite <- H0 in H1.\n  destruct t; desall. rewrite <- H2 in H1. crush.\n  eapply medPreSomeMed in HeqH2. rewrite <- HeqH2 in H1.\n  destruct t; desall.\n  eapply medPreNone in HeqH0. rewrite <- HeqH0 in H1. crush.\n  destruct p; desall. destruct s0; desall.\n  eapply medPreSomeOth in HeqH0; desall.\n  rewrite <- H0 in H1.\n  destruct t; desall. rewrite <- H2 in H1. crush.\n  eapply medPreSomeMed in HeqH0. rewrite <- HeqH0 in H1.\n  destruct t; desall.\n  eapply medPreNone in HeqH0. rewrite <- HeqH0 in H1. crush.\n  destruct p; desall. destruct s0; desall.\n\n  Check medPreSomeOth.\n  Check medPreSomeExt.\n  destruct m; desall. destruct t; desall.\n  Focus 5.\n\n  destruct s0; simpl in *.\n  cutThis (bufsAltStart2 s0 n Medium Medium).\n  inversion H1.\n  destruct p.\n  destruct s1.\n  eapply medPreSomeOth in HeqH2; desall.\n\n  destruct s0; simpl in *.\n  destruct b2; simpl in *.\n  destruct m; desall.\n  destruct t; desall.\n  Print cons13.\n  crush.\n  Print SM.\n\n\n\n\n\n\n\n\n\n\n\n  intros.\n  destruct xs; ese H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  eapply npushSmallHelp; eauto;  badMatch H1.\n  eapply npushSmallHelp; eauto;  badMatch H1.\n  try (eapply npushSmallHelp; eauto);  badMatch H1.\n  try (eapply npushSmallHelp; eauto);  badMatch H1.\n  try (eapply npushSmallHelp; eauto);  badMatch H1.\n  \n  eapply npushSmall5 with (s0 := s0) (n := n) (q := Large).\n  Focus 3.\n  cutThis (bufsAltStart2 s0 n Small Large). auto.\n  destruct p0.\n simpl in *.\n  eapply H1.\n\neauto.\n  try (eapply npushSmallHelp; eauto);  badMatch H1.\n  try (eapply npushSmallHelp; eauto);  badMatch H1.\n\n  destruct p. (* bookmark *)\n  induction n0; badMatch IHn0.\n\n  assert False.\n  eapply npushSmallHelp; eauto.\n\n  badMatch H1;\n    try (eapply npushSmallHelp; eauto);  \n      try (eapply npushSmallOth; eauto);  \n        badMatch H1.\n\n  clear s m H.\n  clear HeqH4.\n  induction n0; badMatch IHn0.\n\n\n  try (eapply npushSmallHelp; eauto);  badMatch H1.\n  try (eapply npushSmallHelp; eauto);  badMatch H1.\n  try (eapply npushSmallHelp; eauto);  badMatch H1.\n  try (eapply npushSmallHelp; eauto);  badMatch H1.\n\n\n\n  eapply npushSmallHelp; eauto;  badMatch H1.\n  eapply npushSmallHelp; eauto;  badMatch H1.\n  eapply npushSmallHelp; eauto;  badMatch H1.\n  eapply npushSmallHelp; eauto;  badMatch H1.\n  eapply npushSmallHelp; eauto;  badMatch H1.\n  eapply npushSmallHelp; eauto;  badMatch H1.\n\n\n\n(*bookmark*)\n  clear H m0 m s.\n  assert (forall A B (y:Nest Stuck A B) C (x:Stuck C A) p,\n    match bufsAltStart2 x y Small p with\n      | None => False\n      | Some (pair _ _) => True\n    end ->\n    None = bufsAltStart2 x y Medium p ->\n    Some Suffix = top2' x y ->\n    False) as ans.\n  clear.\n  induction y; badMatch IHy.\n  badMatch ans.\n\n\n  eapply IHn.\n  induction n; badMatch IHn0.\n  destruct\n  eapply IHn0.\n  \n  destruct s0; destruct n; badMatch H.\n  destruct s0; destruct n; badMatch H.\n\n  shapDes H.\n\n\n\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n  badMatch H.\n\nLemma npushBufs :\n  forall a (x:a) xs,\n    prepose xs <> Large ->\n    allShape xs ->\n    BufsAlternate xs ->\n    BufsAlternate (npush x xs).\nProof.\n  intros.\n  destruct xs; desall.\n  destruct m; desall; destruct H2; desall;\n    repeat split; desall; eauto.\n  eauto.\n  destruct m; desall; destruct H2; desall;\n    repeat split; desall; eauto.\n  repeat split; desall; eauto.\n  Focus 2.\n  eauto. Focus 2.\n  repeat split; desall; eauto.\n  Unfocus. Print nextSize. Print top3.\n  assert (forall A B (C:ThreeStack A B),\n    prepose' C <> Large ->\n    forall z,\n      z <> Medium ->\n      bufsAltStart C Medium z ->\n      bufsAltStart C Large z) as ans.\n  clear.\n  Print bufsAltStart.\n  Print bufsAltStart2.\n  destruct C. Focus 2.\n  simpl. destruct s; desall.\n  unfold bufsAltStart.\n  forall A B\n  assert (fora\n\n  induction C.\n  intros.\n  destruct z; desall.\n  intros.\n  destruct f; desall.\n  desall s; desall; destruct n; desall\n  destruct C; desall.\n  destruct s0; desall; destruct n; desall;\n    repeat split; desall.\n  destruct b2\n  \n  \n  cutThis (prepose' C); desall.\n  destruct C; desall. \n  destruct s0; desall; destruct n; desall; destruct C; desall;\n    repeat split; desall.\n  destruct C; desall.\n  destruct s0; desall; destruct n; desall; destruct C; desall;\n    repeat split; desall.\n  destruct b2; desall; destruct s0; desall; destruct n; desall; destruct C; desall.\n  destruct b2; desall; destruct b3; desall; destruct s0; desall; destruct n; desall; destruct C; desall.\n  \n    repeat split; desall.\n\n\n  destruct z; desall;\n  destruct s0; desall; destruct n; desall; destruct C; desall;\n    repeat split; desall.\n  destruct s0; desall; destruct n; desall; destruct C; desall;\n    repeat split; desall.\n  destruct b2; destruct z; desall.\n\n  cutThis (prepose' H2); desall.\n  destruct H2; desall. \n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; destruct m; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H. auto.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; desall; destruct s1; desall; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n  destruct H2; destruct s1; destruct n; desall.\n\n  destruct H2; desall. destruct H2; desall. destruct n; desall.\n  repeat split; desall; eauto.\n  eauto.\nQed.\n  \nnpush :: a -> Deque a -> Deque a\nnpush x (Deque M0 Empty None) = Deque M0 Empty (Some x) \nnpush x (Deque M0 Empty (Some y)) = Deque (MS x y M0) Empty None \nnpush x (Deque M0 (Full (NE (Stack B0 (B1 z) zs) Empty) xs) q) = Deque (MS x z zs) xs q \nnpush x (Deque M0 (Full (NE (Stack B0 (B1 z) zs) (Full y ys)) xs) q) = Deque (MS x z zs) (Full (NE y ys) xs) q \nnpush x (Deque M0 (Full (NE (Stack B0 z zs) Empty) xs) q) = Deque M0 (cons13 (B1 x) z zs xs) q\nnpush x (Deque M0 (Full (NE (Stack (B1 y) z zs) Empty) xs) q) = Deque M0 (Full (NE (Stack (B2 x y) z zs) Empty) xs) q\nnpush x (Deque M0 (Full (NE (Stack (B1 y) z zs) (Full r rs)) xs) q) = Deque M0 (Full (NE (Stack (B2 x y) z zs) Empty) (Full (NE r rs) xs)) q\nnpush x (Deque (MS y z zs) rs q) = Deque M0 (cons13 (B2 x y) (B1 z) zs rs) q\n\nninject :: Deque a -> a -> Deque a\nninject (Deque M0 Empty None) x = Deque M0 Empty (Some x)\nninject (Deque M0 Empty (Some y)) x = Deque (MS y x M0) Empty None\nninject (Deque M0 (Full (NE (Stack (B1 z) B0 zs) Empty) xs) q) x = Deque (MS z x zs) xs q\nninject (Deque M0 (Full (NE (Stack (B1 z) B0 zs) (Full y ys)) xs) q) x = Deque (MS z x zs) (Full (NE y ys) xs) q\nninject (Deque M0 (Full (NE (Stack z B0 zs) Empty) xs) q) x = Deque M0 (cons13 z (B1 x) zs xs) q \nninject (Deque M0 (Full (NE (Stack z (B1 y) zs) Empty) xs) q) x = Deque M0 (Full (NE (Stack z (B2 y x) zs) Empty) xs) q \nninject (Deque M0 (Full (NE (Stack z (B1 y) zs) (Full r rs)) xs) q) x = Deque M0 (Full (NE (Stack z (B2 y x) zs) Empty) (Full (NE r rs) xs)) q\nninject (Deque (MS z y zs) rs q) x = Deque M0 (cons13 (B1 z) (B2 y x) zs rs) q\n\nnpop :: Deque a -> Maybe (a,Deque a)\nnpop (Deque M0 Empty None) = Nothing\nnpop (Deque M0 Empty (Some y)) =  Just (y,empty)\nnpop (Deque M0 (Full (NE (Stack (B2 y x) (B1 z) zs) Empty) xs) q) = Just (y,Deque (MS x z zs) xs q)\nnpop (Deque M0 (Full (NE (Stack (B2 y x) (B1 z) zs) (Full r rs)) xs) q) = Just (y,Deque (MS x z zs) (Full (NE r rs) xs) q)\nnpop (Deque M0 (Full (NE (Stack (B2 y x) z zs) Empty) xs) q) = Just (y,Deque M0 (cons13 (B1 x) z zs xs) q)\nnpop (Deque M0 (Full (NE (Stack (B1 y) (B2 x z) M0) Empty) Empty) None) = Just (y,Deque (MS x z M0) Empty None)\nnpop (Deque M0 (Full (NE (Stack (B1 y) B0 M0) Empty) Empty) (Some (Both x z))) = Just (y,Deque (MS x z M0) Empty None)\nnpop (Deque M0 (Full (NE (Stack (B1 y) z zs) Empty) xs) q) = Just (y,Deque M0 (Full (NE (Stack B0 z zs) Empty) xs) q)\nnpop (Deque M0 (Full (NE (Stack (B1 y) z zs) (Full r rs)) xs) q) = Just (y,Deque M0 (Full (NE (Stack B0 z zs) Empty) (Full (NE r rs) xs)) q)\nnpop (Deque (MS y z M0) Empty None) = Just (y,Deque M0 Empty (Some z))\nnpop (Deque (MS y z zs) rs q) = Just (y,Deque M0 (cons13 B0 (B1 z) zs rs) q)\n\nneject :: Deque a -> Maybe (Deque a,a)\nneject (Deque M0 Empty None) = Nothing\nneject (Deque M0 Empty (Some y)) = Just (empty,y)\nneject (Deque M0 (Full (NE (Stack (B1 x) (B2 z y) zs) Empty) xs) q) = Just (Deque (MS x z zs) xs q,y)\nneject (Deque M0 (Full (NE (Stack (B1 x) (B2 z y) zs) (Full r rs)) xs) q) = Just (Deque (MS x z zs) (Full (NE r rs) xs) q, y)\nneject (Deque M0 (Full (NE (Stack z (B2 x y) zs) Empty) xs) q) = Just (Deque M0 (cons13 z (B1 x) zs xs) q, y)\nneject (Deque M0 (Full (NE (Stack (B2 x z) (B1 y) M0) Empty) Empty) None) = Just (Deque (MS x z M0) Empty None, y)\nneject (Deque M0 (Full (NE (Stack B0 (B1 y) M0) Empty) Empty) (Some (Both x z))) = Just (Deque (MS x z M0) Empty None, y)\nneject (Deque M0 (Full (NE (Stack z (B1 y) zs) Empty) xs) q) = Just (Deque M0 (Full (NE (Stack z B0 zs) Empty) xs) q, y)\nneject (Deque M0 (Full (NE (Stack z (B1 y) zs) (Full r rs)) xs) q) = Just (Deque M0 (Full (NE (Stack z B0 zs) Empty) (Full (NE r rs) xs)) q, y)\nneject (Deque (MS z y M0) Empty None) = Just (Deque M0 Empty (Some z), y)\nneject (Deque (MS z y zs) rs q) = Just (Deque M0 (cons13 (B1 z) B0 zs rs) q, y)\n\nInductive Back a where\n    Back :: !(ThreeStack a b) -> !(SM b) -> Back a\n\nprefix0' :: ThreeStack a b -> SM b -> Back a\nprefix0' (Full (NE (Stack (B2 x y) z zs) Empty) xs) q = \n    case npush (Both x y) (Deque zs xs q) of\n      Deque a c q' -> Back (cons13 B0 z a c) q'\nprefix0' (Full (NE (Stack (B2 x y) z zs) (Full r rs)) xs) q = \n    case npush (Both x y) (Deque zs (Full (NE r rs) xs) q) of\n      Deque a c q' -> Back (cons13 B0 z a c) q'\n\nprefix0 :: ThreeStack a b -> SM b -> Back a\nprefix0 (Full (NE (Stack (B1 x) z zs) rs) xs) q = \n    case prefix0' xs q of\n      Back c q' -> Back (Full (NE (Stack (B1 x) z zs) rs) c) q'\nprefix0 x y = prefix0' x y\n\nsuffix0' :: ThreeStack a b -> SM b -> Back a\nsuffix0' (Full (NE (Stack z (B2 x y) zs) Empty) xs) q = \n    case ninject (Deque zs xs q) (Both x y) of\n       Deque a c q' -> Back (cons13 z B0 a c) q'\nsuffix0' (Full (NE (Stack z (B2 x y) zs) (Full r rs)) xs) q = \n    case ninject (Deque zs (Full (NE r rs) xs) q) (Both x y) of\n       Deque a c q' -> Back (cons13 z B0 a c) q'\n\nsuffix0 :: ThreeStack a b -> SM b -> Back a\nsuffix0 (Full (NE (Stack z (B1 x) zs) rs) xs) q = \n    case suffix0' xs q of\n      Back c q' -> Back (Full (NE (Stack z (B1 x) zs) rs) c) q'\nsuffix0 x y = suffix0' x y\n\nprefix2' :: ThreeStack a b -> SM b -> Back a\nprefix2' (Full (NE (Stack B0 z zs) Empty) xs) q = \n    case npop (Deque zs xs q) of\n      Just (Both x y,Deque a c q') ->\n          Back (cons13 (B2 x y) z a c) q' \nprefix2' (Full (NE (Stack B0 z zs) (Full r rs)) xs) q = \n    case npop (Deque zs (Full (NE r rs) xs) q) of\n      Just (Both x y,Deque a c q') ->\n          Back (cons13 (B2 x y) z a c) q' \n\nprefix2 (Full (NE (Stack (B1 x) z zs) rs) xs) q = \n    case prefix2' xs q of\n      Back c q' -> \n          Back (Full (NE (Stack (B1 x) z zs) rs) c) q'\nprefix2 x y = prefix2' x y\n\nsuffix2' :: ThreeStack a b -> SM b -> Back a\nsuffix2' (Full (NE (Stack z B0 zs) Empty) xs) q = \n    case neject (Deque zs xs q) of\n      Just (Deque a c q',Both x y) ->\n          Back (cons13 z (B2 x y) a c) q' \nsuffix2' (Full (NE (Stack z B0 zs) (Full r rs)) xs) q = \n    case neject (Deque zs (Full (NE r rs) xs) q) of\n      Just (Deque a c q',Both x y) ->\n          Back (cons13 z (B2 x y) a c) q' \n\nsuffix2 (Full (NE (Stack z (B1 x) zs) rs) xs) q = \n    case suffix2' xs q of\n      Back c q' ->\n          Back (Full (NE (Stack z (B1 x) zs) rs) c) q'\nsuffix2 x y = suffix2' x y\n\nfixHelp :: (forall a b . ThreeStack a b -> SM b -> Back a) -> Deque t -> Deque t\nfixHelp f (Deque b c d) = \n    case f c d of\n      Back c' d' -> Deque b c' d'\n\nsufpose' :: ThreeStack a b -> Size\nsufpose' Empty = Medium\nsufpose' (Full (NE (Stack _ B0{} _) _) _) = Small\nsufpose' (Full (NE (Stack _ B2{} _) _) _) = Large\n\nsufpose (Deque _ (Full (NE (Stack _ B1{} _) _) x) _) = sufpose' x\nsufpose (Deque _ x _) = sufpose' x\n\npush x xs =\n    case prepose xs of\n      Large -> npush x (fixHelp prefix0 xs)\n      _  -> npush x xs\n\ninject xs x =\n    case sufpose xs of\n      Large -> ninject (fixHelp suffix0 xs) x\n      _  -> ninject xs x\n\npop xs =\n    case prepose xs of\n      Small -> npop (fixHelp prefix2 xs)\n      _ -> npop xs\n\neject xs =\n    case sufpose xs of\n      Small -> neject (fixHelp suffix2 xs)\n      _ -> neject xs\n\n*)", "meta": {"author": "jmcarthur", "repo": "deques", "sha": "5b942068cb64f7e2f2f60c0249a6a251a2ac4b0e", "save_path": "github-repos/coq/jmcarthur-deques", "path": "github-repos/coq/jmcarthur-deques/deques-5b942068cb64f7e2f2f60c0249a6a251a2ac4b0e/ThreeDequeHalftrinsic.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20885328846094797}}
{"text": "From iris_ni.program_logic Require Export dwp.\nFrom iris.proofmode Require Import proofmode.\nSet Default Proof Using \"Type\".\n\nSection lifting.\nContext `{!irisDG Λ Σ, !invGS Σ}.\nImplicit Types v : val Λ.\nImplicit Types e : expr Λ.\nImplicit Types σ : state Λ.\nImplicit Types P Q : iProp Σ.\nImplicit Types Φ : val Λ → val Λ → iProp Σ.\n\nLemma dwp_lift_pure_step `{Inhabited (state Λ)} E1 E1' Φ e1 e2 :\n  (∀ σ1, reducible e1 σ1) →\n  (∀ κ σ1 e1' σ1' efs1, prim_step e1 σ1 κ e1' σ1' efs1 → κ = [] ∧ σ1' = σ1) →\n  (∀ σ2, reducible e2 σ2) →\n  (∀ κ σ2 e2' σ2' efs2, prim_step e2 σ2 κ e2' σ2' efs2 → κ = [] ∧ σ2' = σ2) →\n  (|={E1}[E1']▷=> ∀ κ1 κ2 e1' σ1 efs1 e2' σ2 efs2,\n    ⌜prim_step e1 σ1 κ1 e1' σ1 efs1⌝ →\n    ⌜prim_step e2 σ2 κ2 e2' σ2 efs2⌝ →\n    dwp E1 e1' e2' Φ ∗\n    [∗ list] ef1;ef2 ∈ efs1;efs2, dwp ⊤ ef1 ef2 (λ _ _, True ))\n  ⊢ dwp E1 e1 e2 Φ.\nProof.\n  iIntros (Hsafe1 Hdet1 Hsafe2 Hdet2) \"H\".\n  rewrite (dwp_unfold _ e1 e2) /dwp_pre.\n  assert (language.to_val e1 = None) as ->.\n  { destruct (Hsafe1 inhabitant) as (?&?&?&?&?).\n    eapply val_stuck; eauto. }\n  assert (language.to_val e2 = None) as ->.\n  { destruct (Hsafe2 inhabitant) as (?&?&?&?&?).\n    eapply val_stuck; eauto. }\n  iIntros (σ1 σ2 κ1 κs1 κ2 κs2) \"Hrel\".\n  iMod \"H\" as \"H\".\n  iMod fupd_mask_subseteq as \"Hclose\"; last iModIntro; first by set_solver.\n  iSplit; first iPureIntro.\n  { destruct (Hsafe1 σ1) as (xxx&?&?&?&Hst).\n    assert (xxx = []) as ->. { by eapply Hdet1. }\n    do 3 eexists. eauto. }\n  iSplit; first iPureIntro.\n  { destruct (Hsafe2 σ2) as (xxx&?&?&?&Hst).\n    assert (xxx = []) as ->. { by eapply Hdet2. }\n    do 3 eexists. eauto. }\n  iIntros (e1' σ1' efs1 e2' σ2' efs2 Hstep1 Hstep2).\n  iModIntro. iNext. iMod \"Hclose\" as \"_\".\n  iMod \"H\" as \"H\".\n  assert (σ1' = σ1) as ->.\n  { eapply Hdet1. eauto. }\n  assert (σ2' = σ2) as ->.\n  { eapply Hdet2. eauto. }\n  iSpecialize (\"H\" $! [] [] with \"[//] [//]\").\n  iModIntro. iFrame.\nQed.\n\nLemma dwp_lift_pure_det_step `{!Inhabited (state Λ)} {E1 E1' Φ}\n      e1 e1' e2 e2' efs1 efs2 :\n  (∀ σ1, reducible e1 σ1) →\n  (∀ κ σ1 e1'' σ1' efs1', prim_step e1 σ1 κ e1'' σ1' efs1' → κ = [] ∧ σ1' = σ1 ∧ e1'' = e1' ∧ efs1' = efs1) →\n  (∀ σ2, reducible e2 σ2) →\n  (∀ κ σ2 e2'' σ2' efs2', prim_step e2 σ2 κ e2'' σ2' efs2' → κ = [] ∧ σ2' = σ2 ∧ e2'' = e2' ∧ efs2' = efs2) →\n  (|={E1}[E1']▷=> dwp E1 e1' e2' Φ ∗\n    [∗ list] ef1;ef2 ∈ efs1;efs2, dwp ⊤ ef1 ef2 (λ _ _, True ))\n  ⊢ dwp E1 e1 e2 Φ.\nProof.\n  iIntros (? Hpuredet1 ? Hpuredet2) \"H\".\n  iApply dwp_lift_pure_step; try done.\n  { intros. split; by eapply Hpuredet1. }\n  { intros. split; by eapply Hpuredet2. }\n  iApply (step_fupd_wand with \"H\"); iIntros \"H\".\n  iIntros (? ? ? ? ? ? ? ?).\n  iIntros ((->&_&->&->)%Hpuredet1 (->&_&->&->)%Hpuredet2).\n  iApply \"H\".\nQed.\n\nLemma dwp_pure_step_fupd `{!Inhabited (state Λ)} E1 E1' n\n      e1 e1' e2 e2' φ1 φ2 Φ :\n  PureExec φ1 n e1 e1' →\n  PureExec φ2 n e2 e2' →\n  φ1 →\n  φ2 →\n  Nat.iter n (λ P, |={E1}[E1']▷=> P) (dwp E1 e1' e2' Φ)\n  ⊢ dwp E1 e1 e2 Φ.\nProof.\n  iIntros (Hexec1 Hexec2 Hφ1 Hφ2) \"H\".\n  specialize (Hexec1 Hφ1).\n  specialize (Hexec2 Hφ2).\n  iInduction Hexec1 as [e1|n e1 e1' e1'' [Hsafe1 ?]] \"IH\"\n     forall (e2 e2' Hexec2); simpl; simpl in Hexec2.\n  - by inversion Hexec2.\n  - inversion Hexec2 as [|m t2 t2' e2'' [Hsafe2 ?]]. simplify_eq/=.\n    iApply dwp_lift_pure_det_step.\n    + eauto using reducible_no_obs_reducible.\n    + intros σ1 κ e1_ σ1' efs1' Hstep.\n      specialize (pure_step_det _ _ _ _ _ Hstep).\n      naive_solver.\n    + eauto using reducible_no_obs_reducible.\n    + intros σ1 κ e1_ σ1' efs1' Hstep.\n      specialize (pure_step_det0 _ _ _ _ _ Hstep).\n      naive_solver.\n    + iApply (step_fupd_wand with \"H\").\n      rewrite big_sepL2_nil. iIntros \"H\". iSplitL; last done.\n      by iApply \"IH\".\nQed.\n\nLemma dwp_pure_step_later `{!Inhabited (state Λ)} E1\n      e1 e1' e2 e2' n φ1 φ2 Φ :\n  PureExec φ1 n e1 e1' →\n  PureExec φ2 n e2 e2' →\n  φ1 →\n  φ2 →\n  ▷^n (dwp E1 e1' e2' Φ)\n  ⊢ dwp E1 e1 e2 Φ.\nProof.\n  intros Hexec1 Hexec2 ??.\n  rewrite -(dwp_pure_step_fupd E1 E1) //. clear Hexec1 Hexec2.\n  induction n=>// /=.\n  by rewrite -(step_fupd_intro E1 E1)// IHn.\nQed.\n\nEnd lifting.\n", "meta": {"author": "co-dan", "repo": "SeLoC", "sha": "c6e3e77b61ed4800a201eec123ae5e4f277d2ea1", "save_path": "github-repos/coq/co-dan-SeLoC", "path": "github-repos/coq/co-dan-SeLoC/SeLoC-c6e3e77b61ed4800a201eec123ae5e4f277d2ea1/theories/program_logic/lifting.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.20883738664723103}}
{"text": "(****************************************************************************)\n(* Copyright 2020 The Project Oak Authors                                   *)\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\nRequire Import Cava.Arrow.ArrowExport.\n\nRequire Import Coq.Strings.String.\nLocal Open Scope string_scope.\n\nRequire Import Coq.Lists.List Coq.NArith.NArith.\nImport ListNotations.\n\nSection notation.\n  Import KappaNotation.\n  Local Open Scope category_scope.\n  Local Open Scope kind_scope.\n\n  Definition halfAdder\n  : << Bit, Bit, Unit >> ~> <<Bit, Bit>> :=\n    (* The bracket pairing `<[` `]>` opens a circuit expression scope,\n    see readme.md for more information *)\n  <[ \\ a b =>\n    let part_sum = xor a b in\n    let carry = and a b in\n    (part_sum, carry)\n  ]>.\n\n  Definition fullAdder\n  : << Bit, << Bit, Bit >>, Unit >> ~> <<Bit, Bit>> :=\n  <[ \\ cin ab =>\n    let '(a,b) = ab in\n    (* Since 'halfAdder' is in the larger Coq scope, and is not a local variable,\n    they must be escaped with ! See the readme.md in this file for more explanation*)\n    let '(abl, abh) = !halfAdder a b in\n    let '(abcl, abch) = !halfAdder abl cin in\n    let cout = xor abh abch in\n    (abcl, cout)\n  ]>.\n\n  (* Combinators *)\n  Definition below {A B C D E F G: Kind}\n    (r: << A, B, Unit >> ~> << G, D >>)\n    (s: << G, C, Unit >> ~> << F, E >>)\n    : << A, <<B, C>>, Unit >> ~> << F, <<D, E>> >> :=\n  <[ \\ a bc =>\n    let '(b, c) = bc in\n    let '(g, d) = !r a b in\n    let '(f, e) = !s g c in\n    (f, (d, e))\n  ]>.\n\n  (* Replicate is a type created by replicating a type n times,\n  and connecting them by a right imbalanced tuple structure.\n\n  Since the above formulation of 'below' pairs the inputs and outputs\n  as a tuple (rather requiring the types are equal and appending as a vector),\n  'replicate' allows us to refer to type arrising from multiple\n  applications of 'below'.\n  *)\n  Fixpoint replicate A n : Kind :=\n    match n with\n    | O => Unit\n    | S O => A\n    | S n => <<A, replicate A n>>\n    end.\n\n  Fixpoint col {A B C: Kind} n\n    (circuit: << A, B, Unit >> ~> <<A, C>>)\n    {struct n}:\n      << A, replicate B (S n), Unit >> ~>\n      << A, replicate C (S n)>> :=\n    match n with\n    | O => <[ \\a b => !circuit a b ]>\n    | S n' =>\n      let column_above := (col n' circuit) in\n      below circuit column_above\n    end.\n\n  Lemma col_cons: forall {A B C}\n    (circuit: << A, B, Unit >> ~> <<A, C>>),\n    forall n, col (S n) circuit = below circuit (col n circuit).\n  Proof.\n    intros.\n    auto.\n  Qed.\n\n  Fixpoint interleave n\n    : << Vector Bit (S n), Vector Bit (S n), Unit >> ~>\n      << replicate <<Bit, Bit>> (S n) >> :=\n  match n with\n  (* Since for n = 0 -> Vector 1 Bit, we have to index into the variables to retrieve their values.\n  This is done with familiar 'x[_]' syntax, although numeric constants require prepending with '#'.\n  The index can be any expression. See readme.md for more information.\n  *)\n  | 0 => <[\\ x y => (x[#0], y[#0]) ]>\n  | S n =>\n      <[\\ xs ys =>\n      let '(x, xs') = uncons xs in\n      let '(y, ys') = uncons ys in\n      ((x, y), (!(interleave n) xs' ys'))\n    ]>\n  end.\n\n  (* As noted above, we use 'replicate' to allow us to refer to a tuple structure of a single type of kind.\n  It would be convenient to interact with this variable as a vector, and so we can write a conversion\n  function : *)\n  Fixpoint productToVec n\n    : << replicate Bit (S n), Unit >> ~>\n      << Vector Bit (S n) >> :=\n  match n with\n  | 0 => <[\\ x => x :: [] ]>\n  | S n =>\n      <[\\ xs =>\n      let '(x, xs') = xs in\n      x :: !(productToVec n) xs'\n    ]>\n  end.\n\n  Definition rippleCarryAdder' (width: nat)\n    : << Bit, replicate <<Bit, Bit>> (S width), Unit >> ~>\n      << Bit, replicate Bit (S width) >> :=\n  <[ !(col width fullAdder) ]>.\n\n  Definition rippleCarryAdder (width: nat)\n    : << Bit, <<Vector Bit (S width), Vector Bit (S width)>>, Unit >> ~>\n      << Bit, Vector Bit (S width) >> :=\n  <[ \\b xy =>\n    let '(x,y) = xy in\n    let merged = !(interleave _) x y in\n    let '(carry, result) = !(rippleCarryAdder' _) b merged in\n    (carry, !(productToVec _) result)\n    ]>.\n\nEnd notation.\n\nLemma fullAdder_is_combinational: is_combinational (closure_conversion fullAdder).\nProof. simply_combinational. Qed.\n\nRequire Import Cava.Netlist.\n\nDefinition fullAdderInterface\n  := combinationalInterface \"fullAdder\"\n     [mkPort \"cin\" Signal.Bit; mkPort \"a\" Signal.Bit; mkPort \"b\" Signal.Bit]\n     [mkPort \"sum\" Signal.Bit; mkPort \"cout\" Signal.Bit]\n     [].\n\nDefinition fullAdder_tb_inputs :=\n  [(false, (false, false));\n   (false, (true, false));\n   (false, (false, true));\n   (false, (true, true));\n   (true, (false, false));\n   (true, (true, false));\n   (true, (false, true));\n   (true, (true, true))\n].\n\nDefinition fullAdder_netlist :=\n  build_netlist (closure_conversion fullAdder) \"fullAdder\" (\"cin\", (\"a\", \"b\")) (\"sum\", \"cout\").\n\nDefinition fullAdder_tb_expected_outputs  : list (bool * bool)\n  := (List.map (fun i => combinational_evaluation (closure_conversion fullAdder) i) fullAdder_tb_inputs) .\n\nDefinition fullAdder_tb :=\n  testBench \"fullAdder_tb\" fullAdderInterface\n            (map (fun '(a,(b,c)) => (a,b,c)) fullAdder_tb_inputs) fullAdder_tb_expected_outputs.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/investigations/Arrow/arrow-examples/ArrowAdderTutorial.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.20876697693023147}}
{"text": "From iris.algebra Require Import agree gmap auth.\nFrom iris.proofmode Require Import tactics.\nFrom aneris.aneris_lang Require Import\n     network tactics proofmode lifting lang.\nFrom aneris.aneris_lang.lib.serialization Require Import serialization_proof.\nFrom aneris.examples.ccddb.spec Require Import spec resources.\n\n(* Resources and socket protocols for session guarantees *)\n\nSection res.\n  Context `{!DB_params, !DB_time, !DB_events}.\n\n  Definition rep_id := nat.\n  Definition seq_id := nat.\n\n  Inductive log_req :=\n  | LInit (db : rep_id)\n  | LRead (db : rep_id) (k : Key) (s : lhst) (h : gmem)\n  | LWrite (db : rep_id) (k : Key) (v : SerializableVal) (s : lhst) (h : gmem).\n\n  Definition req_db (lrq : log_req) : rep_id :=\n    match lrq with\n    | LInit db => db\n    | LRead db _ _ _ => db\n    | LWrite db _ _ _ _ => db\n    end.\n\n  Definition req_map := gmapUR nat (agreeR (leibnizO log_req)).\n  Context `{!inG Σ (authUR req_map)}.\n\n  Definition is_req γ (n : seq_id) (rq : log_req) :=\n    own γ (◯ {[ n := to_agree rq]}).\n\n  Instance is_req_persistent γ n req : Persistent (is_req γ n req).\n  Proof. apply _. Qed.\n\n  Lemma is_req_agree γ n rq rq' :\n    is_req γ n rq ⊢ is_req γ n rq' -∗ ⌜rq = rq'⌝.\n  Proof.\n    iIntros \"H1 H2\".\n    rewrite /is_req.\n    iDestruct (own_valid_2 with \"H1 H2\") as %Hvalid.\n    iPureIntro.\n    rewrite -auth_frag_op in Hvalid.\n    revert Hvalid.\n    rewrite auth_frag_valid.\n    intros Hvalid.\n    specialize (Hvalid n).\n    rewrite lookup_op !lookup_singleton in Hvalid.\n    rewrite -Some_op in Hvalid.\n    revert Hvalid.\n    rewrite Some_valid.\n    intros Hvalid.\n    apply @to_agree_op_inv in Hvalid.\n    apply leibniz_equiv in Hvalid.\n    simplify_eq.\n    done.\n  Qed.\n\n  Lemma is_req_alloc γ (M : req_map) n rq :\n    n ∉ dom M →\n    own γ (● M) ⊢\n    |==> own γ (● <[n := to_agree rq]> M) ∗ is_req γ n rq.\n  Proof.\n    iIntros (Hi) \"HM\".\n    iMod (own_update _ _ (● <[n := to_agree rq]> M ⋅\n                         ◯ {[n := to_agree rq]}) with \"HM\") as \"[$ $]\";\n      last done.\n    apply auth_update_alloc.\n    apply @alloc_singleton_local_update; last done.\n    apply (not_elem_of_dom (D := gset nat)); done.\n  Qed.\n\n  Lemma request_init : True ⊢ |==> ∃ γ, own γ (● ∅).\n  Proof.\n    iIntros \"_\".\n    iApply own_alloc.\n    apply auth_auth_valid; done.\n  Qed.\n\n  Lemma is_req_auth_disagree γ M (n : nat) rq :\n    own γ (● M) ⊢ is_req γ n rq -∗ ⌜n ∈ dom M⌝.\n  Proof.\n    iIntros \"Hown Hisreq\".\n    rewrite /is_req.\n    iDestruct (own_valid_2 with \"Hown Hisreq\") as \"Hown\".\n    iDestruct \"Hown\" as %[Hvalid _]%auth_both_valid_discrete.\n    iPureIntro.\n    apply dom_included in Hvalid.\n    rewrite dom_singleton_L in Hvalid.\n    set_solver.\n  Qed.\n\nEnd res.\n\nSection serialization.\n  Context `{!DB_params}.\n\n  Definition seq_id_serialization := int_serialization.\n\n  Definition req_init_serialization := string_serialization.\n\n  Definition req_read_serialization := string_serialization.\n\n  Definition req_write_serialization :=\n    prod_serialization string_serialization DB_serialization.\n\n  Definition req_serialization :=\n    prod_serialization\n      seq_id_serialization\n      (sum_serialization\n         req_init_serialization\n         (sum_serialization\n            req_read_serialization\n            req_write_serialization)).\n\n  Definition resp_init_serialization := string_serialization.\n\n  Definition resp_read_serialization :=\n    sum_serialization\n      unit_serialization\n      DB_serialization.\n\n  Definition resp_write_serialization := string_serialization.\n\n  Definition resp_serialization :=\n    prod_serialization\n      seq_id_serialization\n      (sum_serialization\n         resp_init_serialization\n         (sum_serialization\n            resp_read_serialization\n            resp_write_serialization)).\n\n  Global Instance: ∀ sid : Z, Serializable req_serialization (#sid, InjLV #\"I\").\n  Proof. apply _. Qed.\n\n  Global Instance:\n    ∀ (sid : Z) (k : Key),\n      Serializable req_serialization (#sid, InjRV (InjLV #k)).\n  Proof. apply _. Qed.\n\n  Global Instance:\n    ∀ (sid : Z) (k : Key) (v : val),\n      DB_Serializable v →\n      Serializable req_serialization (#sid, InjRV (InjRV (#k, v))).\n  Proof. apply _. Qed.\n\n  Global Instance:\n    ∀ sid : Z, Serializable resp_serialization (#sid, InjLV #\"Ok\").\n  Proof. apply _. Qed.\n\n  Global Instance:\n    ∀ sid : Z, Serializable resp_serialization (#sid, InjRV (InjLV (InjLV #()))).\n  Proof. apply _. Qed.\n\n  Global Instance:\n    ∀ (sid : Z) (v : val),\n      DB_Serializable v →\n      Serializable resp_serialization (#sid, InjRV (InjLV (InjRV v))).\n  Proof. apply _. Qed.\n\n  Global Instance:\n    ∀ sid : Z, Serializable resp_serialization (#sid, InjRV (InjRV #\"Ok\")).\n  Proof. apply _. Qed.\n\n  Typeclasses Opaque req_serialization resp_serialization.\n  Global Opaque req_serialization resp_serialization.\n\nEnd serialization.\n\nSection protocols.\n\n  Definition SM_N : namespace := nroot.@\"SM\".\n\n  Context `{!anerisG Mdl Σ, !lockG Σ}.\n  Context `{!DB_params}.\n  Context `{!DB_time, !DB_events}.\n  Context `{!DB_resources Mdl Σ}.\n  Context `{!Maximals_Computing}.\n  Context `{!inG Σ (authUR req_map)}.\n\n  (* Deserialized request *)\n  Inductive des_req :=\n  | DInit\n  | DRead (k : Key)\n  | DWrite (k : Key) (v : val).\n\n  Definition des_req_to_val (r : des_req) : val :=\n    match r with\n    | DInit => (InjLV #\"I\")\n    | DRead k => (InjRV (InjLV #k))\n    | DWrite k v => (InjRV (InjRV (#k, v)))\n    end.\n\n  (* Deserialized response *)\n  Inductive des_resp :=\n  | RInit\n  | RRead (v : val)\n  | RWrite.\n\n  Definition des_resp_to_val (r : des_resp) : val :=\n    match r with\n    | RInit => (InjLV #\"Ok\")\n    | RRead v => (InjRV (InjLV v))\n    | RWrite => (InjRV (InjRV #\"Ok\"))\n    end.\n\n  (* Variable msg_to_resp : message_body -> option (seq_id * des_resp). *)\n\n  (* Consistency between physical and logical requests *)\n  Inductive cons_req : des_req -> log_req -> Prop :=\n  | ConsReqInit db : cons_req DInit (LInit db)\n  | ConsReqRead db k s h : cons_req (DRead k) (LRead db k s h)\n  | ConsReqWrite db k (v : SerializableVal) s h :\n      cons_req (DWrite k v) (LWrite db k v s h).\n\n  (* Consistency between a physical response and its logical request *)\n  Inductive cons_res : des_resp -> log_req -> Prop :=\n  | ConsResInit db : cons_res RInit (LInit db)\n  | ConsResRead db k s h v : cons_res (RRead v) (LRead db k s h)\n  | ConsResWrite db k v s h : cons_res (RWrite) (LWrite db k v s h).\n\n  (* Socket protocols *)\n  Definition init_post (db : rep_id) : iProp Σ :=\n    ∃ s,\n     Seen db s\n     ∗ ([∗ set] k ∈ DB_keys, ∃ h, OwnMemSnapshot k h)\n     ∗ GlobalInv.\n\n  Definition read_post (db : rep_id) (k : Key) (s : lhst) (h : gmem)\n             (vo : val) : iProp Σ :=\n    ∃ s' h',\n      ⌜s ⊆ s'⌝\n      ∗ ⌜h ⊆ h'⌝\n      ∗ Seen db s'\n      ∗ OwnMemSnapshot k h'\n      ∗ ((⌜vo = NONEV⌝ ∗ ⌜restrict_key k s' = ∅⌝)\n         ∨\n         (∃ e v, ⌜vo = SOMEV v⌝\n                ∗ ⌜AE_val e = v⌝\n                ∗ ⌜AE_key e = k⌝\n                ∗ ⌜e ∈ Maximals (restrict_key k s')⌝\n                ∗ ⌜(erasure e) ∈ h'⌝)).\n\n  Definition write_post (db : rep_id) (k : Key) (v : val) (s : lhst)\n             (h : gmem) : iProp Σ :=\n    ∃ e s' h',\n      ⌜AE_key e = k⌝\n      ∗ ⌜AE_val e = v⌝\n      ∗ ⌜s ⊆ s'⌝\n      ∗ ⌜h ⊆ h'⌝\n      ∗ Seen db s'\n      ∗ OwnMemSnapshot k h'\n      ∗ ⌜e ∉ s⌝\n      ∗ ⌜e ∈ s'⌝\n      ∗ ⌜(erasure e) ∉ h⌝\n      ∗ ⌜(erasure e) ∈ h' ⌝\n      ∗ ⌜(erasure e) ∈ Maximals h'⌝\n      ∗ ⌜Maximum s' = Some e⌝.\n\n  Definition db_si (db : rep_id) : socket_interp Σ :=\n    (λ msg, ∃ ϕ (sid : nat) drq γ lrq,\n        (m_sender msg) ⤇ ϕ ∗\n        ⌜s_is_ser req_serialization\n          (#sid, des_req_to_val drq)%V (m_body msg)⌝ ∗\n        is_req γ sid lrq ∗\n        ⌜req_db lrq = db⌝ ∗\n        ⌜cons_req drq lrq⌝ ∗\n        let (pre, post) :=\n          match lrq with\n          | LInit db => (True, fun _ => init_post db)\n          | LRead db k s h =>\n            (⌜k ∈ DB_keys⌝ ∗ Seen db s ∗ OwnMemSnapshot k h,\n             fun res => ∃ vo, ⌜res = RRead vo⌝ ∗\n                           read_post db k s h vo)\n          | LWrite db k v s h =>\n            (⌜k ∈ DB_keys⌝ ∗ Seen db s ∗ OwnMemSnapshot k h,\n             fun _ => write_post db k v s h)\n          end\n        in\n        pre ∗ □ (∀ res, (∃ dres, ⌜s_is_ser resp_serialization\n                                (#sid, des_resp_to_val dres) (m_body res)⌝ ∗\n                               is_req γ sid lrq\n                               ∗ ⌜cons_res dres lrq⌝\n                               ∗ post dres)\n                        -∗ ϕ res))%I.\n\n  Global Instance db_si_persistent db m : Persistent (db_si db m).\n  Proof.\n    rewrite /Persistent.\n    iDestruct 1 as (Φ i drq γ lrq) \"(#?&#?&#?&#?&#?&Hm)\".\n    destruct lrq eqn:Heq.\n    - iDestruct \"Hm\" as \"[_ #?]\".\n      iModIntro.\n      iExists _, _, _, _, lrq; rewrite Heq.\n      iFrame \"#\".\n    - iDestruct \"Hm\" as \"[#? #?]\".\n      iModIntro.\n      iExists _, _, _, _, lrq; rewrite Heq.\n      iFrame \"#\".\n    - iDestruct \"Hm\" as \"[#? #?]\".\n      iModIntro.\n      iExists _, _, _, _, lrq; rewrite Heq.\n      iFrame \"#\".\n  Qed.\n\n  Definition resp_body_post dres lrq vo : iProp Σ :=\n    ⌜cons_res dres lrq⌝\n    ∗ match lrq with\n      | LInit db => init_post db\n      | LRead db k s h => ⌜dres = RRead vo⌝ ∗\n        read_post db k s h vo\n      | LWrite db k v s h => write_post db k v s h\n      end.\n\n  Definition client_si (γ : gname) : socket_interp Σ :=\n    (λ msg, ∃ (sid : nat) dres lrq vo,\n        ⌜s_is_ser resp_serialization\n         (#sid, des_resp_to_val dres) (m_body msg)⌝\n         ∗ is_req γ sid lrq\n         ∗  resp_body_post dres lrq vo)%I.\nEnd protocols.\n\nGlobal Hint Constructors cons_req : core.\nGlobal Hint Constructors cons_res : core.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/ccddb/examples/session_guarantees/res.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.20874496987815683}}
{"text": "Require Import FP.Data.Error.\nRequire Import FP.Classes.\nRequire Import FP.CoreData.\nRequire Import FP.CoreClasses.\nRequire Import FP.DerivingEverything.\nRequire Import FP.Data.Identity.\n\nImport CoreDataNotation.\nImport CoreClassesNotation.\nImport ClassesNotation.\n\nInductive error_t E m A := ErrorT { run_error_t : m (error E A) }.\nArguments ErrorT {E m A} _.\nArguments run_error_t {E m A} _.\n\nDefinition error_b E := error_t E identity.\n\nSection error_t_Bijection.\n  Context {E:Type} {m:Type -> Type} {A:Type}.\n\n  Global Instance IR_run_error_t_eq\n    : InjectionRespect (error_t E m A) (m (error E A)) run_error_t eq eq.\n  Proof.\n    constructor ; [congruence|].\n    unfold Proper,\"<==\" ; intros ; destruct x,y ; simpl in * ; congruence.\n  Qed.\n\n  Global Instance II_ErrorT_eq\n    : InjectionInverse (m (error E A)) (error_t E m A) ErrorT run_error_t eq.\n  Proof.\n    constructor ; auto.\n  Qed.\nEnd error_t_Bijection.\n\nModule error_t_DE_Arg <: DE_IdxTransformer_Arg.\n  Definition T := error_t.\n  Definition U E m A := m (error E A):Type.\n  Definition to : forall {E m A}, T E m A -> U E m A := @run_error_t.\n  Definition from : forall {E m A}, U E m A -> T E m A := @ErrorT.\n  Definition IR_to {E m A} : InjectionRespect (T E m A) (U E m A) to eq eq := _.\n  Definition II_from {E m A} : InjectionInverse (U E m A) (T E m A) from to eq := _.\n  Definition _DE_IdxTransformerI : DE_IdxTransformerI' U.\n  Proof. unfold U ; econstructor ; econstructor ; eauto with typeclass_instances. Defined.\nEnd error_t_DE_Arg.\nModule error_t_DE := DE_IdxTransformer error_t_DE_Arg.\nImport error_t_DE.\n\nSection Proper.\n  Context {E m A} `{! Eqv  E ,! F_Eqv m ,! Eqv A }.\n  Global Instance ErrorT_Proper : Proper eqv (@ErrorT E m A).\n  Proof.\n    unfold Proper.\n    logical_eqv_intro.\n    unfold eqv ; simpl ; auto.\n  Qed.\n  Global Instance run_error_t_Proper : Proper eqv (@run_error_t E m A).\n  Proof.\n    unfold Proper.\n    logical_eqv_intro.\n    destruct x,y ; simpl.\n    apply InjectionRespect_beta ; auto.\n  Qed.\nEnd Proper.\nHint Extern 9 (Proper eqv (ErrorT (E:=?E) (m:=?m) (A:=?A))) =>\n  let H := fresh \"H\" in\n  pose (H:=(ErrorT_Proper (E:=E) (m:=m) (A:=A))) ; apply H\n  : typeclass_instances.\nHint Extern 9 (Proper eqv (run_error_t (E:=?E) (m:=?m) (A:=?A))) =>\n  let H := fresh \"H\" in\n  pose (H:=(run_error_t_Proper (E:=E) (m:=m) (A:=A))) ; apply H\n  : typeclass_instances.\n\nSection Monad.\n  Context {E:Type} {m} `{! Monad m }.\n\n  Definition error_t_mret {A} (a:A) : error_t E m A := ErrorT $ mret $ Success a.\n  Arguments error_t_mret {A} a /.\n\n  Definition error_t_mbind {A B} (aMM:error_t E m A) (k:A -> error_t E m B) : error_t E m B :=\n    ErrorT begin\n      aM <- run_error_t aMM ;;\n      match aM with\n      | Failure e => mret $ Failure e\n      | Success a => run_error_t $ k a\n      end\n    end.\n  Arguments error_t_mbind {A B} aMM k /.\n  Global Instance error_t_Monad : Monad (error_t E m) :=\n    { mret := @error_t_mret\n    ; mbind := @error_t_mbind\n    }.\n\n  Section error_t_MonadWF.\n    Context `{! Eqv E ,! PER_WF E ,! F_Eqv m ,! F_PER_WF m ,! MonadWF m }.\n\n    Global Instance error_t_MonadWF : MonadWF (error_t E m).\n    Proof.\n      constructor ; intros.\n      - apply InjectionRespect_beta ; simpl.\n        rewrite Monad_left_unit ; repeat (logical_eqv ; repeat fold_error).\n      - apply InjectionRespect_beta ; simpl.\n        transitivity (run_error_t aM >>= mret).\n        + logical_eqv.\n          destruct x,y ; inversion H ; subst ; clear H ; logical_eqv.\n        + rewrite Monad_right_unit ; logical_eqv.\n      - apply InjectionRespect_beta ; simpl.\n        rewrite Monad_associativity ; repeat (logical_eqv ; repeat fold_error).\n        destruct x,y ; inversion H ; subst ; clear H ; repeat (logical_eqv ; repeat fold_error) ; simpl.\n        rewrite Monad_left_unit ; repeat (logical_eqv ; repeat fold_error) ; simpl.\n        repeat (logical_eqv ; repeat fold_error).\n      - unfold Proper ; logical_eqv_intro.\n        apply InjectionRespect_beta ; simpl.\n        repeat (logical_eqv ; repeat fold_error).\n      - unfold Proper ; logical_eqv_intro.\n        apply InjectionRespect_beta ; simpl.\n        repeat (logical_eqv ; repeat fold_error).\n    Qed.\n  End error_t_MonadWF.\nEnd Monad.\n\nSection MonadCatch.\n  Context {E:Type} {m} `{! Monad m }.\n  Definition error_t_mthrow {A} (e:E) : error_t E m A := ErrorT $ mret $ Failure e.\n  Arguments error_t_mthrow {A} e /.\n  Definition error_t_mcatch {A} (aM:error_t E m A) (k:E -> error_t E m A) : error_t E m A :=\n    ErrorT begin\n      am <- run_error_t aM ;;\n      match am with\n      | Success a => mret $ Success a\n      | Failure e => run_error_t $ k e\n      end\n    end.\n  Arguments error_t_mcatch {A} aM k /.\n  Global Instance error_t_MonadCatch : MonadCatch E (error_t E m) :=\n    { mthrow := @error_t_mthrow\n    ; mcatch := @error_t_mcatch\n    }.\n\n  Section error_t_MonadCatchWF.\n    Context `{! Eqv E ,! PER_WF E ,! F_Eqv m ,! F_PER_WF m ,! MonadWF m }.\n\n    Global Instance error_t_MonadCatchWF : MonadCatchWF E (error_t E m).\n    Proof.\n      constructor ; intros ; unfold mcatch,mthrow ; simpl.\n      - apply InjectionRespect_beta ; simpl.\n        rewrite Monad_left_unit ; repeat (logical_eqv ; repeat fold_error).\n      - apply InjectionRespect_beta ; simpl.\n        rewrite Monad_left_unit ; repeat (logical_eqv ; repeat fold_error).\n      - apply InjectionRespect_beta ; simpl.\n        rewrite Monad_left_unit ; repeat (logical_eqv ; repeat fold_error).\n      - unfold Proper ; logical_eqv_intro ; simpl ; logical_eqv.\n      - unfold Proper ; logical_eqv_intro ; simpl ; repeat (logical_eqv ; repeat fold_error).\n    Qed.\n  End error_t_MonadCatchWF.\nEnd MonadCatch.", "meta": {"author": "davdar", "repo": "coq-fp", "sha": "d0b752d9ea9592ba0bc7b067b46a63740fcff056", "save_path": "github-repos/coq/davdar-coq-fp", "path": "github-repos/coq/davdar-coq-fp/coq-fp-d0b752d9ea9592ba0bc7b067b46a63740fcff056/src/Data/ErrorT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3738758157951908, "lm_q1q2_score": 0.20874496048761496}}
{"text": "Require Import LibTactics.\nRequire Import Metalib.Metatheory.\nRequire Export syntax_ott.\nRequire Import\n        rules_inf\n        Infrastructure\n        KeyProperties\n        SubtypingInversion\n        Disjointness\n        Deterministic\n        Progress\n        Consistency.\n\nRequire Import List. Import ListNotations.\nRequire Import Arith Lia.\n\n\n(* requires algo_sub Top A -> toplike A *)\nLemma TypedReduce_trans : forall v v1 v2 A B,\n    value v -> TypedReduce v A v1 -> TypedReduce v1 B v2 -> TypedReduce v B v2.\nProof with eauto.\n  introv Val Red1 Red2. gen B v2.\n  induction* Red1; introv Red2; inductions Red2...\n  inverts* Val.\nQed.\n\n\nLemma consistent_afterTR : forall v A B C v1 v2,\n    value v -> Typing nil v Inf C -> TypedReduce v A v1 -> TypedReduce v B v2 -> consistencySpec v1 v2.\nProof.\n  unfold consistencySpec. introv Val Typ Red1 Red2 Ord Red1' Red2'.\n  forwards* r1: TypedReduce_trans Red1 Red1'. forwards* r2: TypedReduce_trans Red2 Red2'.\n  forwards*: TypedReduce_unique r1 r2.\nQed.\n\n\nLemma TypedReduce_preservation: forall v v' A B,\n    value v -> TypedReduce v A v'-> Typing nil v Inf B -> exists C, pType v' C /\\ Typing nil v' Inf C /\\ subsub C A.\nProof with eauto.\n  introv Val Red Typ. (* '. forwards* (B&Typ&Sub): Typing_chk2inf Typ'. *)\n  gen B. lets Red': Red.\n  induction Red; intros; try solve [jauto].\n  - (* absv *)\n    simpl. exists. splits*.\n    inverts Typ. applys Typ_abs. intros. apply~ Typing_chk_sub.\n  - (* rcd *)\n    inverts Val. inverts Typ; forwards* (?&?&?&?): IHRed.\n  - (* mergel *)\n    inverts Val. inverts Typ; forwards*: IHRed.\n  - (* merger *)\n    inverts Val. inverts Typ; forwards*: IHRed.\n  - (* merge_and *)\n    forwards (?&?&?&?): IHRed1 Val Red1 Typ.\n    forwards (?&?&?&?): IHRed2 Val Red2 Typ.\n    lets Con: consistent_afterTR Val Typ Red1 Red2.\n    eapply consistent_complete in Con...\n    exists. splits*.\nQed.\n\n\nLemma TypedReduce_consistent : forall v A B C v1 v2,\n    value v -> Typing nil v Inf C -> TypedReduce v A v1 -> TypedReduce v B v2 -> consistent v1 v2.\nProof with eauto.\n  intros v A B C v1 v2 Val Typ Red1 Red2.\n  forwards* (?&?&?&?): TypedReduce_preservation Red1.\n  forwards* (?&?&?&?): TypedReduce_preservation Red2.\n  forwards*: TypedReduce_prv_value Red1.\n  forwards*: TypedReduce_prv_value Red2.\n  apply~ consistent_complete...\n  forwards*: consistent_afterTR Red1 Red2.\nQed.\n\n\n\nLemma papp_consistent : forall v1 v2 v e1 e2 A B C,\n    value v1 -> value v2 -> value v ->\n    Typing nil v1 Inf A -> Typing nil v2 Inf B -> Typing nil v Inf C ->\n    papp v1 (vl_exp v) e1 -> papp v2 (vl_exp v) e2 -> consistent v1 v2 -> consistent e1 e2.\nProof with (solve_false; eauto).\n  introv Val1 Val2 Val3 Typ1 Typ2 Typ3 P1 P2 Cons.\n  gen A B C. lets P1': P1. lets P2': P2.\n  inductions P1; inductions P2; intros; try solve [applys* C_disjoint].\n  - forwards* [?|(?&?)]: consistent_lams_inv Cons.\n    + applys* C_disjoint.\n    + subst. forwards*: TypedReduce_unique H0 H2.\n      subst*.\n  - lets* (?&?): consistent_merger Cons. inverts* Typ2.\n  - lets* (?&?): consistent_merger Cons. inverts* Typ2.\n  - lets* (?&?): consistent_mergel Cons. inverts* Typ1.\n  - lets* (?&?): consistent_mergel Cons. inverts* Typ1.\n  - (* merge ~ merge *)\n    inverts Val1. lets~ (?&?): consistent_mergel Cons.\n    inverts* Typ1.\nQed.\n\n\nLemma papp_consistent2 : forall v1 v2 l e1 e2 A B,\n    value v1 -> value v2 ->\n    Typing nil v1 Inf A -> Typing nil v2 Inf B ->\n    papp v1 (vl_la l) e1 -> papp v2 (vl_la l) e2 -> consistent v1 v2 -> consistent e1 e2.\nProof with (solve_false; eauto).\n  introv Val1 Val2 Typ1 Typ2 P1 P2 Cons.\n  gen A B. lets P1': P1. lets P2': P2.\n  inductions P1; inductions P2; intros;\n    try solve [applys* C_disjoint];\n    try solve [inverts Val1; inverts Typ1; applys* C_disjoint];\n    try solve [inverts Val2; inverts Typ2; applys* C_disjoint];\n    try solve [lets* (?&?): consistent_mergel Cons; inverts* Typ1];\n    try solve [lets* (?&?): consistent_merger Cons; inverts* Typ2].\n  - inverts Cons.\n    + inverts P1'. inverts P2'. subst*.\n    + enough (consistent (e_rcd l v) (e_rcd l v0)). eauto.\n      applys* C_disjoint H3.\nQed.\n\n\nLemma papp_preservation : forall v1 v2 e A,\n    value v1 -> value v2 ->\n    Typing nil (e_app v1 v2) Inf A ->\n    papp v1 (vl_exp v2) e ->\n    Typing nil e Inf A.\nProof with eauto.\n  intros v1 v2 e A Val1 Val2 Typ P. gen A.\n  inductions P; intros; inverts Typ as Typ1 Typ2 Typ3.\n  - (* abs *)\n    forwards* (T & Htyp & Hsub): Typing_chk2inf Typ3.\n    forwards (? & p1 & p2 & p3): TypedReduce_preservation Htyp...\n    inverts Typ1 as t1. inverts Typ2.\n    eapply Typ_anno. pick fresh y. rewrite (@subst_exp_intro y)...\n    forwards~ t1': (t1 y). rewrite_env([]++[(y,B0)]++ []) in t1'.\n    lets~ (?&s1&s2): Typing_subst_2 t1' p2 p3.\n    apply subsub2sub in s2. forwards*: Typing_chk_sub s2.\n  - (* top *)\n    inverts Typ1. inverts* Typ2.\n  - (* merge *)\n    forwards* (T & Htyp & Hsub): Typing_chk2inf Typ3.\n    inverts Val1.\n    inverts Typ1; inverts Typ2;\n      assert (algo_sub (t_and A2 B2) A2) by auto_sub;\n      assert (algo_sub (t_and A2 B2) B2) by auto_sub;\n      forwards~: IHP1 v2; [ applys* Typ_app H7 | auto | applys* Typ_app H8 | auto ];\n      forwards~: IHP2 v2; [ applys* Typ_app H9 | auto | applys* Typ_app H10 | auto ].\n    + apply~ Typ_merge. applys* arrTyp_arr_disjoint H6.\n    + apply~ Typ_mergev. applys* papp_consistent P1 P2.\nQed.\n\n\nLemma papp_preservation2 : forall v1 l e A,\n    value v1 ->\n    Typing nil (e_proj v1 l) Inf A ->\n    papp v1 (vl_la l) e ->\n    Typing nil e Inf A.\nProof with eauto.\n  intros v1 l e A Val1 Typ P. gen A.\n  inductions P; intros; inverts Typ as Typ1 Typ2 Typ3.\n  - (* rcd *)\n    inverts Typ1. inverts* Typ2.\n  - (* top *)\n    inverts Typ1. inverts* Typ2.\n  - (* merge *)\n    inverts Val1.\n    inverts Typ1; inverts Typ2;\n      forwards~: IHP1 l; [ applys* Typ_proj H7 | auto | applys* Typ_proj H8 | auto ];\n      forwards~: IHP2 l; [ applys* Typ_proj H9 | auto | applys* Typ_proj H10 | auto ].\n    + apply~ Typ_merge. applys* arrTyp_rcd_disjoint H6.\n    + apply~ Typ_mergev. applys* papp_consistent2 P1 P2.\nQed.\n\nInductive step_or_v : exp -> exp -> Prop :=\n| ST_v : forall v, value v -> step_or_v v v\n| ST_s : forall e1 e2, step e1 e2 -> step_or_v e1 e2.\n\n#[export]\nHint Constructors step_or_v : core.\n\n(* to prove the consistent merge case in preservation_subsub *)\nLemma consistent_steps: forall e1 e2 e1' e2' A B,\n    Typing [] e1 Inf A -> Typing [] e2 Inf B ->\n    step_or_v e1 e1' -> step_or_v e2 e2' -> consistent e1 e2 ->\n    (forall (e e' : exp) (A : typ),\n         size_exp e < (size_exp e1 + size_exp e2) -> Typing [] e Inf A -> step e e' -> exists C, [] ⊢ e' ⇒ C /\\ subsub C A) ->\n    consistent e1' e2'.\nProof with (simpl; elia).\n  introv Typ1 Typ2 ST1 ST2 Cons IH. gen e1' e2' A B.\n  induction Cons; intros; try solve [inverts ST1; inverts ST2; solve_false; eauto].\n    + (* e:A ~ e:B *)\n      inverts ST1 as ST1'; inverts ST2 as ST2'; solve_false; eauto.\n      inverts Typ1 as H_check_e. inverts H_check_e as H_inf_e.\n      inverts ST1' as Hv1 Hs1; inverts ST2' as Hv2 Hs2; solve_false.\n      * forwards*: TypedReduce_consistent Hs1 Hs2.\n      * forwards*: step_unique Hv1 Hv2. subst*.\n    + (* rcd *)\n      inverts keep Typ1. inverts keep Typ2.\n      inverts ST1 as ST1'; inverts ST2 as ST2'; solve_false; eauto;\n        inverts ST1' as Hv1 Hs1; inverts ST2' as Hv2 Hs2; solve_false.\n      * (* value VS step *)\n        applys C_rcd. applys* IHCons. intros.\n        forwards* (?&?&?): IH H3...\n      * (* step VS value *)\n        applys C_rcd. applys* IHCons. intros.\n        forwards* (?&?&?): IH H3...\n      * (* step VS step *)\n        applys C_rcd. applys* IHCons. intros.\n        forwards* (?&?&?): IH H3...\n    + (* disjoint *)\n      inverts ST1 as ST1'; [unify_pType e1' | unify_pType u1];\n        inverts ST2 as ST2'; try unify_pType e2'; try unify_pType u2.\n      * (* value VS value *)\n        applys* C_disjoint.\n      * (* value VS step *)\n        forwards* (?&?&?): IH u2... assert (0 < size_exp e1') by eauto using size_exp_min.\n        elia.\n        forwards~: step_prv_prevalue ST2'. unify_pType e2'.\n        applys* C_disjoint.\n      * (* step VS value *)\n        forwards* (?&?&?): IH u1... assert (size_exp e2' >0) by eauto using size_exp_min. lia.\n        forwards~: step_prv_prevalue ST1'. unify_pType e1'.\n        applys* C_disjoint.\n      * (* step VS step *)\n        forwards* (?&?&?): IH u1. assert (size_exp u2 >0) by eauto using size_exp_min. lia.\n        forwards* (?&?&?): IH u2. assert (size_exp u1 >0) by eauto using size_exp_min. lia.\n        forwards~: step_prv_prevalue ST1'. unify_pType e1'.\n        forwards~: step_prv_prevalue ST2'. unify_pType e2'.\n        applys* C_disjoint.\n    + (* merge on left *)\n      inverts ST1 as ST1'; [ | inverts ST1' as ST1_1 ST1_2 ]; inverts Typ1;\n        try solve [\n              forwards*: IHCons1; try introv p1 p2 p3; try applys~ IH p2 p3; try (simpl; lia);\n              forwards*: IHCons2; try introv p1 p2 p3; try applys~ IH p2 p3; try (simpl; lia)].\n    + (* merge on right *)\n      inverts ST2 as ST2'; [ | inverts ST2' as ST2_1 ST2_2 ]; inverts Typ2;\n        try solve [\n              forwards*: IHCons1; try introv p1 p2 p3; try applys~ IH p2 p3; try (simpl; lia);\n              forwards*: IHCons2; try introv p1 p2 p3; try applys~ IH p2 p3; try (simpl; lia)].\nQed.\n\nLtac indExpDirSize s :=\n  assert (SizeInd: exists i, s < i) by eauto;\n  destruct SizeInd as [i SizeInd];\n  repeat match goal with | [ h : dirflag |- _ ] => (gen h) end;\n  repeat match goal with | [ h : exp |- _ ] => (gen h) end;\n  induction i as [|i IH]; [\n      intros; match goal with | [ H : _ < 0 |- _ ] => inverts H end\n    | intros ].\n\nDefinition size_dir dir :=\n  match dir with\n  | Inf => 0\n  | Chk => 1\n  end.\n\n\nTheorem preservation_subsub : forall e e' dir A,\n    Typing nil e dir A ->\n    step e e' ->\n    exists C, Typing nil e' dir C /\\ subsub C A.\nProof with (simpl; try lia; auto; try eassumption; auto).\n  introv Typ J. gen A e'.\n  indExpDirSize ((size_exp e) + (size_dir dir)).\n  inverts keep Typ as Ht1 Ht2 Ht3 Ht4;\n    try solve [inverts J]; repeat simpl in SizeInd.\n  - (* typing_app *)\n    inverts J as J1 J2 J3; try forwards* (?&?&S2): IH J2; assert (size_exp e1 >0) by eauto using size_exp_min; elia.\n     + forwards*: papp_preservation J3.\n    + lets* ( ?&? & Harr & Hsub ): arrTyp_arr_subsub Ht2 S2.\n    forwards* (?&?): subsub_arr_inv Hsub.\n    + exists. split*. applys* Typ_app Ht2. applys* Typing_chk_sub.\n  - (* typing_proj *)\n    inverts J as J1 J2 J3; try forwards* (?&?&S2): IH J1; elia.\n    + forwards*: papp_preservation2 J2.\n    + lets* ( ? & Harr & Hsub ): arrTyp_rcd_subsub Ht2 S2.\n      forwards* (?&?): subsub_rcd_inv Hsub.\n  - (* typing_rcd *)\n    (* disjoint *)\n    inverts J as J1 J2 J3;\n    try forwards* (?&?&?): IH J1; elia;\n    try forwards* (?&?&?): IH J2; elia.\n  - (* typing_merge *)\n    (* disjoint *)\n    inverts J as J1 J2 J3;\n    try forwards* (?&?&?): IH J1; elia;\n    try forwards* (?&?&?): IH J2; elia.\n  - (* typing_anno *)\n    inverts Ht1. inverts J as J1 J2 J3.\n    + lets* (?&?): TypedReduce_preservation J2.\n    + forwards* (?&?&?): IH J1...\n      exists A. split*. apply subsub2sub in H2.\n      assert (algo_sub x A) by auto_sub. lets*: Typ_sub.\n  - (* typing_fix *)\n    inverts J as Lc. pick_fresh x.\n    rewrite* (@subst_exp_intro x).\n    forwards~ Typ_chk: Ht1.\n    rewrite_env(nil++[(x,A)]++nil) in Typ_chk.\n    lets~ (?&?&?): Typing_subst_2 Typ_chk Typ.\n    apply subsub2sub in H0. forwards*: Typing_chk_sub H H0.\n  - (* typing_mergev *) (* consistent merge *)\n    inverts J as J1 J2 J3; forwards*: consistent_steps Ht4;\n      (* consistent e1' e2' *)\n      try introv p1 p2 p3; try forwards* (?&?&?): IH p2 p3; elia;\n        (* typing for the two terms *)\n        try forwards* (?&?&?): IH J1; elia; try forwards* (?&?&?): IH J2; elia.\n  - (* subsumption *)\n    forwards* (?&?&?): IH J...\n    apply subsub2sub in H0.\n    assert (algo_sub x A) by auto_sub.\n    exists* A.\nQed.\n\n\nTheorem preservation : forall e e' dir A,\n    Typing nil e dir A ->\n    step e e' ->\n    Typing nil e' Chk A.\nProof.\n  intros e e' dir A H H0.\n  lets* (?&?&?): preservation_subsub H H0.\n  apply subsub2sub in H2.\n  destruct dir.\n  - sapply* Typ_sub.\n  - sapply* Typing_chk_sub.\nQed.\n\n\n(* Type Safety *)\nTheorem preservation_multi_step : forall e e' dir A,\n    Typing nil e dir A ->\n    e ->* e' ->\n    exists C, Typing nil e' dir C /\\ subsub C A.\nProof.\n  introv Typ Red.\n  gen A. induction* Red.\n  intros.\n  lets* (?&?&?): preservation_subsub Typ H.\n  forwards* (?&?&?): IHRed H0.\n  exists x0. split*.\n  forwards*: subsub_trans H3 H1.\nQed.\n\n\nTheorem type_safety : forall e e' dir A,\n    Typing nil e dir A ->\n    e ->* e' ->\n    value e' \\/ exists e'', step e' e''.\nProof.\n  introv Typ Red. gen A.\n  induction Red; intros.\n  lets*: progress Typ.\n  lets* (?&?&?): preservation_subsub Typ H.\nQed.\n", "meta": {"author": "XSnow", "repo": "TamingMerge", "sha": "f2c55da56db597ed94a1a45a49c31e2869362d9c", "save_path": "github-repos/coq/XSnow-TamingMerge", "path": "github-repos/coq/XSnow-TamingMerge/TamingMerge-f2c55da56db597ed94a1a45a49c31e2869362d9c/plus/coq/TypeSafety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.20874495888741612}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import RmiOps.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition smc_realm_destroy_spec (rd_addr: Z64) (adt: RData) : option (RData * Z64) :=\n    match rd_addr with\n    | VZ64 addr =>\n      rely is_int64 addr;\n      rely prop_dec (cur_rec (priv adt) = None);\n      let gidx := __addr_to_gidx addr in\n      if (GRANULE_ALIGNED addr) && (is_gidx gidx) then\n        when adt == query_oracle adt;\n        let gn := (gs (share adt)) @ gidx in\n        rely prop_dec (glock gn = None);\n        let e0 := EVT CPU_ID (ACQ gidx) in\n        if (g_tag (ginfo gn) =? GRANULE_STATE_RD) && (gcnt gn =? 0) then\n          rely prop_dec (gtype gn = GRANULE_STATE_RD);\n          rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);\n          rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);\n          rely prop_dec ((buffer (priv adt)) @ SLOT_REC_LIST = None);\n          let rtt_gidx := g_rtt (gnorm gn) in\n          let recl_gidx := g_rec_list (gnorm gn) in\n          rely is_gidx rtt_gidx; rely is_gidx recl_gidx;\n          let gn := (gs (share adt)) @ gidx in\n          let gn_rtt := (gs (share adt)) @ rtt_gidx in\n          let gn_recl := (gs (share adt)) @ recl_gidx in\n          rely prop_dec (glock gn_rtt = None);\n          rely prop_dec (glock gn_recl = None);\n          rely (g_tag (ginfo gn) =? GRANULE_STATE_RD);\n          rely (g_tag (ginfo gn_rtt) =? GRANULE_STATE_TABLE);\n          rely (g_tag (ginfo gn_recl) =? GRANULE_STATE_REC_LIST);\n          rely (gtype gn =? GRANULE_STATE_RD);\n          rely (gtype gn_rtt =? GRANULE_STATE_TABLE);\n          rely (gtype gn_recl =? GRANULE_STATE_REC_LIST);\n          rely is_int64 (g_refcount (ginfo gn_rtt));\n          let e := EVT CPU_ID (ACQ rtt_gidx) in\n          if g_refcount (ginfo gn_rtt) =? 0 then\n            let grd' := gn {gnorm: zero_granule_data_normal} {grec: zero_granule_data_rec}\n                          {ginfo: (ginfo gn) {g_tag: GRANULE_STATE_DELEGATED}} in\n            let grecl' := gn_recl {ginfo: (ginfo gn_recl) {g_tag: GRANULE_STATE_DELEGATED}}\n                                  {gnorm: zero_granule_data_normal} {grec: zero_granule_data_rec} in\n            let grtt' := gn_rtt {ginfo: (ginfo gn_rtt) {g_rd: 0} {g_tag: GRANULE_STATE_DELEGATED}}\n                                {gnorm: zero_granule_data_normal} {grec: zero_granule_data_rec} in\n            let e1 := EVT CPU_ID (ACQ recl_gidx) in\n            let e' := EVT CPU_ID (REL rtt_gidx (grtt' {glock: Some CPU_ID})) in\n            let e'' := EVT CPU_ID (REL recl_gidx (grecl' {glock: Some CPU_ID})) in\n            let e''' := EVT CPU_ID (REL gidx (grd' {glock: Some CPU_ID})) in\n            Some (adt {log: e''' :: e'' :: e' :: e1 :: e :: e0 :: (log adt)}\n                      {share: (share adt) {gs: (gs (share adt)) # rtt_gidx == (grtt' {gtype: GRANULE_STATE_DELEGATED})\n                                                                # recl_gidx == (grecl' {gtype: GRANULE_STATE_DELEGATED})\n                                                                # gidx == (grd' {gtype: GRANULE_STATE_DELEGATED})}},\n                  VZ64 0)\n          else\n            let e' := EVT CPU_ID (REL rtt_gidx (gn_rtt {glock: Some CPU_ID})) in\n            let e'' := EVT CPU_ID (REL gidx (gn {glock: Some CPU_ID})) in\n            Some (adt {log: e'' :: e' :: e :: e0 :: log adt}, VZ64 1)\n        else\n          let e' := EVT CPU_ID (REL gidx (gn {glock: Some CPU_ID})) in\n          Some (adt {log: e' :: e0 :: (log adt)}, VZ64 1)\n      else Some (adt, VZ64 1)\n    end.\n\nEnd Spec.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RmiSMC/Specs/smc_realm_destroy.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.20874495109707328}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.ZArith.ZArith.\nRequire Import VST.zlist.Zlist.\nRequire Import Poulet4.Utils.Utils.\nRequire Import Poulet4.P4light.Syntax.Typed.\nRequire Import Poulet4.P4light.Syntax.Syntax.\nRequire Import Poulet4.P4light.Semantics.Semantics.\nRequire Import ProD3.core.Coqlib.\nRequire Import ProD3.core.Members.\nRequire Import ProD3.core.SvalRefine.\nRequire Import ProD3.core.AssertionLang.\nRequire Import ProD3.core.AssertionNotations.\nRequire Import ProD3.core.Hoare.\nRequire Import ProD3.core.EvalExpr.\nRequire Import Coq.ZArith.BinInt.\nRequire Import Hammer.Tactics.Tactics.\nRequire Import Hammer.Plugin.Hammer.\n\nLocal Open Scope string_scope.\n\nSection EvalBuiltin.\n\nContext {tags_t: Type} {tags_t_inhabitant : Inhabitant tags_t}.\nNotation Val := (@ValueBase bool).\nNotation Sval := (@ValueBase (option bool)).\nNotation Lval := ValueLvalue.\n\nNotation ident := string.\n\nContext {target : @Target tags_t (@Expression tags_t)}.\n\nDefinition header_isValid (sv : Sval) : option bool :=\n  match sv with\n  | ValBaseHeader _ is_valid => is_valid\n  | _ => None\n  end.\n\nDefinition isValid (sv : Sval) : option bool :=\n  match sv with\n  | ValBaseHeader _ is_valid => is_valid\n  | ValBaseUnion fields =>\n      match lift_option (map header_isValid (map snd fields)) with\n      | Some valid_bits => Some (fold_left orb valid_bits false)\n      | None => None\n      end\n  | _ => None\n  end.\n\nLemma header_isValid_sound : forall sv sv' b,\n  sval_refine sv sv' ->\n  exec_isValid read_ndetbit sv' b ->\n  bit_refine (header_isValid sv) (Some b).\nProof.\n  intros.\n  inv H0.\n  - inv H; inv H4; inv H1; constructor.\n  - inv H. constructor.\nQed.\n\nLemma lift_option_some_inv : forall {A : Type} (ol : list (option A)) (al : list A),\n  lift_option ol = Some al ->\n  ol = map Some al.\nProof.\n  induction ol; intros; inv H.\n  - auto.\n  - destruct a. 2 : inv H1.\n    destruct (lift_option ol). 2 : inv H1.\n    inv H1. erewrite IHol by eauto. auto.\nQed.\n\nLemma Forall2_map : forall {A B C D : Type} (R : A -> B -> Prop) (f : C -> A) (g : D -> B) cl dl,\n  Forall2 (fun c d => R (f c) (g d)) cl dl <-> Forall2 R (map f cl) (map g dl).\nProof.\n  intros.\n  change (fun (c : C) (d : D) => _) with (fun c d => (fun a d => R a (g d)) (f c) d).\n  rewrite ForallMap.Forall2_map_l, ForallMap.Forall2_map_r.\n  reflexivity.\nQed.\n\nLemma Forall2_bit_refine_Some_inv : forall al bl,\n  Forall2 bit_refine (map Some al) (map Some bl) ->\n  al = bl.\nProof.\n  induction al; intros.\n  - destruct bl; inv H; auto.\n  - destruct bl; inv H; inv H3; f_equal; auto.\nQed.\n\nGlobal Instance Inhabitant_string : Inhabitant string := \"\".\n\nLemma Forall2_forall_range2 : forall {A B : Type} {da : Inhabitant A} {db : Inhabitant B} al bl (P : A -> B -> Prop),\n  Forall2 P al bl <->\n    (Zlength al = Zlength bl /\\ forall_range2 0 (Zlength al) 0 al bl P).\nProof.\n  intros; split; intro.\n  - induction H.\n    + unfold forall_range2, forall_i. list_solve.\n    + unfold forall_range2, forall_i. destruct IHForall2. list_solve.\n  - generalize dependent bl; induction al; intros.\n    + assert (bl = []) by list_solve; subst.\n      constructor.\n    + destruct bl. 1 : list_solve.\n      constructor. {\n        destruct (H).\n        specialize (H1 0%Z ltac:(list_solve)).\n        list_solve.\n      }\n      apply IHal. unfold forall_range2, forall_i. destruct H. list_solve.\nQed.\n\nHint Rewrite @Forall2_forall_range2 : list_prop_rewrite.\n\nLemma isValid_sound : forall sv sv' b,\n  sval_refine sv sv' ->\n  exec_isValid read_ndetbit sv' b ->\n  bit_refine (isValid sv) (Some b).\nProof.\n  intros.\n  inv H0.\n  - inv H; inv H4; inv H1; constructor.\n  - simpl.\n    inv H.\n    assert (Forall2 sval_refine (map snd kvs) (map snd fields)) as H3'. {\n      unfold AList.all_values in H3.\n      range_form. destruct H1. destruct H3.\n      list_simplify.\n      intro; intros.\n      list_simplify.\n      clear -H13.\n      hauto use: Z.add_0_r unfold: sval_refine.\n    }\n    clear H3. rename H3' into H3.\n    assert (Forall2 bit_refine (map header_isValid (map snd kvs)) (map Some valid_bits)). {\n      range_form.\n      list_simplify.\n      intro; intros.\n      destruct H1; destruct H3; list_simplify.\n      rewrite Z.add_0_r in H13, H14.\n      eapply header_isValid_sound; eassumption.\n    }\n    clear -H.\n    simpl.\n    destruct (lift_option (map header_isValid (map snd kvs))) eqn:H_list_option.\n    2 : constructor.\n    apply lift_option_some_inv in H_list_option.\n    rewrite H_list_option in H. clear H_list_option.\n    assert (l = valid_bits). {\n      list_simplify.\n      destruct H.\n      list_simplify.\n      inv H8. list_solve.\n    }\n    rewrite H0.\n    constructor.\nQed.\n\nDefinition setValid (sv : Sval) : Sval :=\n  match sv with\n  | ValBaseHeader fields _ =>\n      ValBaseHeader fields (Some true)\n  | _ => sv\n  end.\n\nDefinition setInvalid (sv : Sval) : Sval :=\n  match sv with\n  | ValBaseHeader fields _ =>\n      ValBaseHeader fields (Some false)\n  | _ => sv\n  end.\n\nDefinition push_front (sv : Sval) (count : Z) : Sval :=\n  match sv with\n  | ValBaseStack headers next =>\n      push_front headers next count\n  | _ => sv\n  end.\n\nLemma push_front_sound : forall sv headers next count,\n  (count >= 0)%Z ->\n  sval_refine sv (ValBaseStack headers next) ->\n  sval_refine (push_front sv count) (Semantics.push_front headers next count).\nProof.\n  intros.\n  inv H0.\n  unfold push_front, Semantics.push_front.\n  constructor.\n  range_form. destruct H3. rewrite H0.\n  destruct (count <=? Zlength headers)%Z eqn:?.\n  - list_simplify.\n    + intro; intros.\n      list_simplify. apply sval_refine_uninit_sval_of_sval_trans. auto.\n    + intro; intros.\n      list_solve.\n  - list_simplify.\n    + intro; intros.\n      list_simplify. apply sval_refine_uninit_sval_of_sval_trans. auto.\n    + intro; intros.\n      list_solve.\nQed.\n\nDefinition pop_front (sv : Sval) (count : Z) : Sval :=\n  match sv with\n  | ValBaseStack headers next =>\n      pop_front headers next count\n  | _ => sv\n  end.\n\nLemma pop_front_sound : forall sv headers next count,\n  (count >= 0)%Z ->\n  sval_refine sv (ValBaseStack headers next) ->\n  sval_refine (pop_front sv count) (Semantics.pop_front headers next count).\nProof.\n  intros.\n  inv H0.\n  unfold pop_front, Semantics.pop_front.\n  constructor.\n  range_form. destruct H3. rewrite H0.\n  destruct (count <=? Zlength headers)%Z eqn:?.\n  - list_simplify.\n    + intro; intros.\n      list_simplify. apply sval_refine_uninit_sval_of_sval_trans. auto.\n    + intro; intros.\n      list_solve.\n  - list_simplify.\n    + intro; intros.\n      list_simplify. apply sval_refine_uninit_sval_of_sval_trans. auto.\n    + intro; intros.\n      list_solve.\nQed.\n\nDefinition eval_builtin (a : mem_assertion) (lv : Lval) (fname : ident) (args : list Sval) : option (mem_assertion * Sval) :=\n  if fname =? \"isValid\" then\n    match eval_read a lv with\n    | Some hdr =>\n        Some (a, ValBaseBool (isValid hdr))\n    | None => None\n    end\n  else if fname =? \"setValid\" then\n    match eval_read a lv with\n    | Some hdr =>\n        match eval_write a lv (setValid hdr) with\n        | Some a' => Some (a', ValBaseNull)\n        | None => None\n        end\n    | None => None\n    end\n  else if fname =? \"setInvalid\" then\n    match eval_read a lv with\n    | Some hdr =>\n        match eval_write a lv (setInvalid hdr) with\n        | Some a' => Some (a', ValBaseNull)\n        | None => None\n        end\n    | None => None\n    end\n  else if fname =? \"push_front\" then\n    match args with\n    | [ValBaseInteger count] =>\n      match eval_read a lv with\n      | Some hdr =>\n          match eval_write a lv (push_front hdr count) with\n          | Some a' => Some (a', ValBaseNull)\n          | None => None\n          end\n      | None => None\n      end\n    | _ => None\n    end\n  else if fname =? \"pop_front\" then\n    match args with\n    | [ValBaseInteger count] =>\n      match eval_read a lv with\n      | Some hdr =>\n          match eval_write a lv (pop_front hdr count) with\n          | Some a' => Some (a', ValBaseNull)\n          | None => None\n          end\n      | None => None\n      end\n    | _ => None\n    end\n  else\n    None.\n\nLemma eval_builtin_sound : forall p a_mem a_ext lv fname args a_mem' retv,\n  NoDup (map fst a_mem) ->\n  eval_builtin a_mem lv fname args = Some (a_mem', retv) ->\n  hoare_builtin p (ARG args (MEM a_mem (EXT a_ext))) lv fname (RET retv (MEM a_mem' (EXT a_ext))).\nProof.\n  unfold hoare_builtin; intros * H_NoDup; intros.\n  inv H1.\n  - unfold eval_builtin in H. simpl in H.\n    destruct (eval_read a_mem lv) eqn:H_eval_read. 2 : inv H.\n    eapply eval_read_sound in H_eval_read; eauto.\n    specialize (H_eval_read _ _ ltac:(apply H0) H2).\n    pose proof (isValid_sound _ _ _ H_eval_read H3).\n    inv H.\n    split. 2 : apply H0.\n    intro; intros.\n    inv H. constructor. inv H5. auto.\n  - unfold eval_builtin in H. simpl in H.\n    destruct (eval_read a_mem lv) eqn:H_eval_read. 2 : inv H.\n    eapply eval_read_sound in H_eval_read; eauto.\n    specialize (H_eval_read _ _ ltac:(apply H0) H2).\n    destruct (eval_write a_mem lv (setValid v)) eqn:H_eval_write. 2 : inv H.\n    eapply eval_write_sound in H_eval_write; eauto.\n    assert (sval_refine (setValid v) (ValBaseHeader fields (Some true))). {\n      inv H_eval_read.\n      constructor; [constructor | auto].\n    }\n    specialize (H_eval_write _ _ _ ltac:(apply H0) ltac:(eassumption) ltac:(eassumption)).\n    inv H.\n    split. 2 : auto.\n    intro; intros. inv H. constructor.\n  - unfold eval_builtin in H. simpl in H.\n    destruct (eval_read a_mem lv) eqn:H_eval_read. 2 : inv H.\n    eapply eval_read_sound in H_eval_read; eauto.\n    specialize (H_eval_read _ _ ltac:(apply H0) H2).\n    destruct (eval_write a_mem lv (setInvalid v)) eqn:H_eval_write. 2 : inv H.\n    eapply eval_write_sound in H_eval_write; eauto.\n    assert (sval_refine (setInvalid v) (ValBaseHeader fields (Some false))). {\n      inv H_eval_read.\n      constructor; [constructor | auto].\n    }\n    specialize (H_eval_write _ _ _ ltac:(apply H0) ltac:(eassumption) ltac:(eassumption)).\n    inv H.\n    split. 2 : auto.\n    intro; intros. inv H. constructor.\n  - unfold eval_builtin in H. simpl in H.\n    destruct H0. inv H0; inv H8; inv H9.\n    destruct (eval_read a_mem lv) eqn:H_eval_read. 2 : inv H.\n    eapply eval_read_sound in H_eval_read; eauto.\n    specialize (H_eval_read _ _ ltac:(apply H1) H3).\n    destruct (eval_write a_mem lv (push_front v count)) eqn:H_eval_write. 2 : inv H.\n    eapply eval_write_sound in H_eval_write; eauto.\n    specialize (H_eval_write _ _ _ ltac:(apply H1) ltac:(eapply push_front_sound; eassumption) ltac:(eassumption)).\n    inv H.\n    split. 2 : auto.\n    intro; intros. inv H. constructor.\n  - unfold eval_builtin in H. simpl in H.\n    destruct H0. inv H0; inv H8; inv H9.\n    destruct (eval_read a_mem lv) eqn:H_eval_read. 2 : inv H.\n    eapply eval_read_sound in H_eval_read; eauto.\n    specialize (H_eval_read _ _ ltac:(apply H1) H3).\n    destruct (eval_write a_mem lv (pop_front v count)) eqn:H_eval_write. 2 : inv H.\n    eapply eval_write_sound in H_eval_write; eauto.\n    specialize (H_eval_write _ _ _ ltac:(apply H1) ltac:(eapply pop_front_sound; eassumption) ltac:(eassumption)).\n    inv H.\n    split. 2 : auto.\n    intro; intros. inv H. constructor.\nQed.\n\nEnd EvalBuiltin.\n\n#[export] Hint Resolve eval_builtin_sound : hoare.\n", "meta": {"author": "verified-network-toolchain", "repo": "VerifiableP4", "sha": "87afa7bef7d88da2e9a642e37c0ddb2412b57509", "save_path": "github-repos/coq/verified-network-toolchain-VerifiableP4", "path": "github-repos/coq/verified-network-toolchain-VerifiableP4/VerifiableP4-87afa7bef7d88da2e9a642e37c0ddb2412b57509/core/EvalBuiltin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.2087382326640871}}
{"text": "\nRequire Import Coq.Arith.Arith.\nRequire Import Coq.Bool.Bool.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Arith.EqNat.\nRequire Import Coq.omega.Omega.\nRequire Import Coq.Lists.List.\n\nRequire Import Language Types.\nRequire Import Lemmas.\nRequire Import Low_eq.\nRequire Import Label.\n\nRequire Import Simulation_L.\nRequire Import simulation_full.\nRequire Import preservation.\nRequire Import execution. \n\nRequire Import progress.\n\n\n\n\nLemma low_eq_preservation : forall ct  ctn1 ctns1 h1 ctn2 ctns2 h2\n                                   ctn1' ctns1' h1'\n                                   ctn2' ctns2' h2' φ T,\n    valid_config (Config ct  ctn1 ctns1 h1 ) ->\n    valid_config (Config ct  ctn2 ctns2 h2 ) ->\n    config_has_type ct empty_context (Config ct ctn1  ctns1 h1) T ->\n    config_has_type ct empty_context (Config ct ctn2  ctns2 h2) T ->\n    L_equivalence_heap h1 h2 φ ->\n    parallel_reduction (Config ct ctn1 ctns1 h1)\n                           (Config ct ctn2 ctns2 h2)\n                           (Config ct ctn1' ctns1' h1')\n                           (Config ct ctn2' ctns2' h2') ->\n     L_equivalence_config (Config ct ctn1 ctns1 h1 )\n                          (Config ct ctn2 ctns2 h2)  φ ->\n\n          exists  φ', (L_equivalence_heap h1' h2'  φ')  /\\ L_equivalence_config (Config ct ctn1' ctns1' h1')  (Config ct ctn2' ctns2' h2')  φ'.\nProof with eauto.\n  intros  ct  ctn1 ctns1 h1 ctn2 ctns2 h2 ctn1' ctns1' h1' ctn2' ctns2' h2'  φ  T. \n  intro H_valid1. intro H_valid2.\n  intro H_typing1. intro H_typing2.\n  intro H_bijection.\n  intro H_p_execution. \n  intro H_low_eq. \n\n  inversion H_p_execution; subst; auto.\n  -\n    apply  simulation_L with t1 fs1 lb1 sf1 ctns1 h1\n                             t2 fs2 lb2 sf2 ctns2 h2\n                             φ T; auto; inversion H_valid1; inversion H_valid2; auto.   \n\n  - try (eauto using simulation_H2H_H).\n  - try (eauto using simulation_H_H2H).\n  - try (eauto using simulation_H2L_H2L).\n  - \n    try (eauto using simulation_Terminal_H2H).\nQed. Hint Resolve low_eq_preservation.\n\n\n\n\n\n\n\n\n\n\n\n  \n  \n\n\nLemma two_exes_to_parallel_execution : forall ct ctn1 ctns_stack1 h1\n                                                    ctn2 ctns_stack2 h2 lb1' sf1' lb2' sf2'\n                                                    final_v1  final_v2  h1' h2' T  φ n, \n    valid_config (Config ct  ctn1 ctns_stack1 h1 ) ->\n    valid_config (Config ct  ctn2 ctns_stack2 h2 ) ->\n    config_has_type ct empty_context (Config ct ctn1  ctns_stack1 h1) T ->\n    config_has_type ct empty_context (Config ct ctn2  ctns_stack2 h2) T ->\n    two_terminate_num (Config ct ctn1 ctns_stack1 h1)\n                  (Config ct ctn2 ctns_stack2 h2)\n                  (Config ct (Container final_v1 nil lb1' sf1') nil h1')\n                  (Config ct (Container final_v2 nil lb2' sf2') nil h2')\n                  n ->\n    L_equivalence_config (Config ct ctn1 ctns_stack1 h1 )\n            (Config ct ctn2 ctns_stack2 h2)  φ ->\n    value final_v1 -> value final_v2 ->\n    L_equivalence_heap h1 h2 φ ->\n    multi_step_p_reduction (Config ct ctn1 ctns_stack1 h1)\n                           (Config ct ctn2 ctns_stack2 h2)\n                           (Config ct (Container final_v1 nil lb1' sf1') nil h1')\n                           (Config ct (Container final_v2 nil lb2' sf2') nil h2') .\nProof with eauto.\n  intros ct ctn1 ctns_stack1 h1\n         ctn2 ctns_stack2 h2 lb1' sf1' lb2' sf2'\n         final_v1  final_v2  h1' h2' T  φ n.\n  intro H_valid1. intro H_valid2.\n  intro H_typing1. intro H_typing2.\n  intro H_reduction.\n  intro H_low_eq.\n  intro Hv_final1. intro Hv_final2.\n  intro H_bijection.\n(*\n  remember (Config ct ctn1 ctns_stack1 h1) as config1.\n  remember (Config ct ctn2 ctns_stack2 h2) as config2.\n  *)\n  generalize dependent ctn1. generalize dependent ctn2.\n  generalize dependent ctns_stack1. generalize dependent ctns_stack2.\n  generalize dependent h1. generalize dependent h2. generalize dependent  φ.\n\n  induction n as [ n IHn ] using (well_founded_induction lt_wf).\n  intros; subst; auto.\n\n  destruct ctn1. rename l into lb1. rename f into fs1. rename s into sf1. rename t into t1. \n  destruct ctn2. rename l into lb2. rename f into fs2. rename s into sf2. rename t into t2. \n\n  assert  (terminal_state  (Config ct (Container t1 fs1 lb1 sf1) ctns_stack1 h1)\n             \\/ (exists config', (Config ct (Container t1 fs1 lb1 sf1) ctns_stack1 h1) ==> config')).\n  eauto using Progress.\n\n  assert  (terminal_state  (Config ct (Container t2 fs2 lb2 sf2) ctns_stack2 h2)\n             \\/ (exists config', (Config ct (Container t2 fs2 lb2 sf2) ctns_stack2 h2) ==> config')).\n  eauto using Progress.\n\n  assert (exists m0 n0, terminate_num (Config ct (Container t1 fs1 lb1 sf1) ctns_stack1 h1)\n                                        (Config ct (Container final_v1 nil lb1' sf1') nil h1')\n                                        m0 /\\\n                        terminate_num (Config ct (Container t2 fs2 lb2 sf2) ctns_stack2 h2)\n                                        (Config ct (Container final_v2 nil lb2' sf2') nil h2')\n                                        n0 /\\ (m0 + n0 = n)).\n  eauto using two_executions_split.\n  destruct H1 as [m0].\n  destruct H1 as [n0].\n  destruct H1.\n  destruct H2.\n  \n  case_eq (flow_to lb1 L_Label); intro.\n  - (* conf1 is a low configuration  *)\n    destruct H.\n    + (* conf1 already terminated *)\n      assert ((Config ct (Container t1 fs1 lb1 sf1) ctns_stack1 h1)\n                  = (Config ct (Container final_v1 nil lb1' sf1') nil h1')).\n      eauto using terminated_same_as_final.\n      destruct H0.\n      ++ (*conf2 also terminated *)        \n        assert ((Config ct (Container t2 fs2 lb2 sf2) ctns_stack2 h2)\n                  = (Config ct (Container final_v2 nil lb2' sf2') nil h2')).\n        eauto using terminated_same_as_final.\n        inversion H5; subst; auto.\n        inversion H6; subst; auto.\n      ++ (*conf2 steps; this is impossible*)\n         inversion H_low_eq; subst; auto;\n           try (inconsist).\n\n         inversion H5; subst; auto.\n         inversion H21; subst; auto.\n         \n         inversion H22; subst; auto.\n         inversion H17; subst; auto.\n         destruct H0 as [config2'].\n         inversion H; subst; auto.\n         \n         assert (value t2).\n         apply value_L_eq2 with final_v1 h1' h2 φ; auto.\n         inversion H3; subst; auto; inversion H0.\n\n    + (* conf1 steps *)\n      destruct H as [config1'].\n      destruct H0.\n      ++ (*conf2 terminated; this is impossible *)  \n        assert ((Config ct (Container t2 fs2 lb2 sf2) ctns_stack2 h2)\n                  = (Config ct (Container final_v2 nil lb2' sf2') nil h2')).\n        eauto using terminated_same_as_final.\n        inversion H5; subst; auto.\n        inversion H_low_eq; subst; auto;\n           try (inconsist).\n        inversion H20; subst; auto.\n        inversion H21; subst; auto.\n\n        inversion H17; subst; auto.\n        inversion H0; subst; auto.\n        assert (value t1).\n        apply value_L_eq with final_v2 h1 h2' φ; auto.\n        inversion H3; subst; auto; inversion H.\n      ++ (*conf2 steps*)\n        destruct H0 as [config2'].\n        assert (exists ctn' ctns' h', config1' = \n                                      (Config ct ctn' ctns' h')).\n        eauto using execution_no_exception.\n        assert (exists ctn' ctns' h', config2' = \n                                      (Config ct ctn' ctns' h')).\n        eauto using execution_no_exception.\n        destruct H5 as [ctn1'].\n        destruct H5 as [ctns1'].\n        destruct H5 as [h1'0]; subst; auto.\n        destruct H6 as [ctn2'].\n        destruct H3 as [ctns2'].\n        destruct H3 as [h2'0]; subst; auto.\n        inversion H_low_eq; subst; auto;\n          try (inconsist).\n        destruct ctn1'. destruct ctn2'.\n        assert (exists  φ', L_equivalence_heap h1'0 h2'0 φ'\n                /\\ L_equivalence_config (Config ct (Container t f l s) ctns1' h1'0)\n                                        (Config ct (Container t0 f0 l0 s0) ctns2' h2'0) φ'); auto.\n        eauto using  simulation_L; auto.\n        destruct H3 as [φ'].\n        destruct H3.         \n        apply multi_p_reduction_step with\n              (Config ct (Container t f l s) ctns1' h1'0)\n              (Config ct (Container t0 f0 l0 s0) ctns2' h2'0).\n        eauto using L_L_reduction.\n        assert (exists m0', 1 + m0' = m0).\n        eauto using execution_num_step_nonzero.\n        destruct H6 as [m0'].\n        assert (exists n0', 1 + n0' = n0).\n        eauto using execution_num_step_nonzero.\n        destruct H7 as [n0'].\n        rewrite <- H6 in H1.\n        rewrite <- H7 in H2.\n        apply IHn with (m0' + n0')  φ'; auto; try (apply H5).\n        rewrite <- H6. rewrite <- H7.\n        assert (forall n, n < 1 + n). auto.\n        pose proof H8 (n0').\n        apply lt_trans with (m0' + (1 + n0')); auto.\n\n        eauto using valid_config_preservation.\n        inversion H_typing2; subst; auto.\n        eauto using typing_preservation.\n        eauto using valid_config_preservation.\n        inversion H_typing1; subst; auto.\n        eauto using typing_preservation.\n\n        assert (forall n, 1 + n -1 = n).\n        intros. induction n; auto.       \n        assert (terminate_num (Config ct (Container t f l s) ctns1' h1'0)\n                                     (Config ct (Container final_v1 nil lb1' sf1') nil h1')\n                                     (1 + m0' - 1)).\n        eauto using execution_num_step.\n\n        assert (terminate_num (Config ct (Container t0 f0 l0 s0) ctns2' h2'0)\n                                     (Config ct (Container final_v2 nil lb2' sf2') nil h2')\n                                     (1 + n0' - 1)).\n        eauto using execution_num_step.\n        pose proof H8 m0'. rewrite H11 in H9.\n        pose proof H8 n0'. rewrite H12 in H10.\n        auto.\n\n  - (* conf1 is a high configuration  *)\n    inversion H_low_eq; subst; auto.\n    try (inconsist).\n\n    destruct H.\n    (* first configuration is terminated *)\n    + destruct H0.\n      ++ (* conf2 also terminated *)\n        eauto using terminated_both_p_reduction.\n\n      ++ (* conf2 steps *)\n        destruct H0 as [config2'].\n        assert (exists ctn' ctns' h', config2' = \n                                      (Config ct ctn' ctns' h')).\n        eauto using execution_no_exception.\n        destruct H3 as [ctn2'].\n        destruct H3 as [ctns2'].\n        destruct H3 as [h2'0]; subst; auto.\n        destruct ctn2'.\n        case_eq (flow_to l L_Label); intro.\n        +++ (*conf2 steps to a low configuration*)\n          assert (flow_to l L_Label = false).\n          inversion H; subst; auto. \n          apply terminate_H_must_2H with ct t1 lb1 sf1 h1\n                                         (Container t2 fs2 lb2 sf2)  ctns_stack2 h2 s f t ctns2' h2'0 T φ; auto.\n          try (inconsist).\n        +++ (*conf2 steps to a high configuration*)\n          assert (L_equivalence_heap h1 h2'0 φ /\\ L_equivalence_config (Config ct (Container t1 fs1 lb1 sf1) ctns_stack1 h1)\n                                                                          (Config ct (Container t f l s) ctns2' h2'0 )  φ); auto.\n          eauto using  simulation_H_H2H; auto.\n          apply multi_p_reduction_step with\n              (Config ct (Container t1 fs1 lb1 sf1) ctns_stack1 h1)\n              (Config ct (Container t f l s) ctns2' h2'0).\n          assert ((Config ct (Container t1 fs1 lb1 sf1) ctns_stack1 h1)\n                  = (Config ct (Container final_v1 nil lb1' sf1') nil h1')).\n          eauto using terminated_same_as_final.\n          inversion H6; subst; auto.\n          assert (exists n0', 1 + n0' = n0).\n          eauto using execution_num_step_nonzero.\n          destruct H6 as [n0'].\n          rewrite <- H6 in H2. \n          apply IHn with (m0 + n0')  φ ; auto; try (apply H5).\n          ++++ pose proof addition_exchange_all 1 n0'.\n               rewrite H7 in H6. rewrite <-H6.\n               rewrite <- H7.\n               apply lt_addition_plus1. \n          ++++ eauto using valid_config_preservation.\n          ++++\n            inversion H_typing2. eauto using typing_preservation.\n          ++++ assert (terminate_num (Config ct (Container t f l s) ctns2' h2'0)\n                                     (Config ct (Container final_v2 nil lb2' sf2') nil h2') \n                                     (1 + n0' - 1)).\n               eauto using execution_num_step.\n               assert (forall n, 1 + n -1 = n).\n               intros. induction n; auto.\n               pose proof H8 n0'.\n               rewrite H9 in H7; auto.\n    + (* first configuration steps  *)\n      destruct H as [config1'].\n      assert (exists ctn' ctns' h', config1' = \n                                      (Config ct ctn' ctns' h')).\n      eauto using execution_no_exception.\n      destruct H3 as [ctn1'].\n      destruct H3 as [ctns1'].\n      destruct H3 as [h1'0]; subst; auto.\n      destruct ctn1'.\n      case_eq (flow_to l L_Label); intro.\n      ++ (* conf1 steps to a low configuration *)\n        destruct H0.\n        +++ (*conf2 terminated; impossible case*)\n          assert (flow_to l L_Label = false).\n          inversion H0; subst; auto.\n          eauto using H_terminate_must_2H.\n          try (inconsist).\n        +++ (*conf2 steps *)\n          destruct H0 as [config2'].\n          assert (exists ctn' ctns' h', config2' = \n                                      (Config ct ctn' ctns' h')).\n          eauto using execution_no_exception.\n          destruct H5 as [ctn2'].\n          destruct H5 as [ctns2'].\n          destruct H5 as [h2'0]; subst; auto.\n          destruct ctn2'.\n          case_eq (flow_to l0 L_Label); intro.\n          ++++ (* conf2 steps into low configuration  *)\n             assert (L_equivalence_heap h1'0 h2'0 φ /\\ L_equivalence_config (Config ct (Container t f l s) ctns1' h1'0)\n                                                                         ( Config ct (Container t0 f0 l0 s0) ctns2' h2'0)  φ); auto.\n             eauto using simulation_H2L_H2L.\n             destruct H6.\n             apply multi_p_reduction_step with\n                 (Config ct (Container t f l s) ctns1' h1'0)\n                 ( Config ct (Container t0 f0 l0 s0) ctns2' h2'0).\n             eauto using H2L_H2L_reduction. \n             assert (exists m0', 1 + m0' = m0).\n             eauto using execution_num_step_nonzero.\n             destruct H8 as [m0'].\n             assert (exists n0', 1 + n0' = n0).\n             eauto using execution_num_step_nonzero.\n             destruct H9 as [n0'].\n             rewrite <- H8 in H1.\n             rewrite <- H9 in H2.\n             apply IHn with (m0' + n0')  φ; auto; try (apply H7).\n             rewrite <- H8. rewrite <- H9.\n             assert (forall n, n < 1 + n). auto.\n             pose proof H10 (n0').\n             apply lt_trans with (m0' + (1 + n0')); auto.\n\n             eauto using valid_config_preservation.\n             inversion H_typing2; subst; auto. \n             eauto using typing_preservation.\n\n             eauto using valid_config_preservation.\n             inversion H_typing1; subst; auto. \n             eauto using typing_preservation.\n\n             assert (forall n, 1 + n -1 = n).\n             intros. induction n; auto.       \n             assert (terminate_num (Config ct (Container t f l s) ctns1' h1'0)\n                                     (Config ct (Container final_v1 nil lb1' sf1') nil h1')\n                                     (1 + m0' - 1)).\n             eauto using execution_num_step.\n\n             assert (terminate_num (Config ct (Container t0 f0 l0 s0) ctns2' h2'0)\n                                     (Config ct (Container final_v2 nil lb2' sf2') nil h2')\n                                     (1 + n0' - 1)).\n             eauto using execution_num_step.\n             pose proof H10 m0'. rewrite H13 in H11.\n             pose proof H10 n0'. rewrite H14 in H12.\n             auto. \n\n          ++++ (* conf2 steps into high configuration *)\n            assert (L_equivalence_heap h1 h2'0 φ /\\ L_equivalence_config (Config ct (Container t1 fs1 lb1 sf1) ctns_stack1 h1)\n                                                                         ( Config ct (Container t0 f0 l0 s0) ctns2' h2'0)  φ); auto.\n            eauto using simulation_H_H2H.\n            destruct H6.\n            apply multi_p_reduction_step with\n              (Config ct (Container t1 fs1 lb1 sf1) ctns_stack1 h1)\n              ( Config ct (Container t0 f0 l0 s0) ctns2' h2'0).\n            eauto using H2L_H2H_reduction. \n            assert (exists n0', 1 + n0' = n0).\n            eauto using execution_num_step_nonzero.\n\n            destruct H8 as [n0'].\n            rewrite <- H8 in H2. \n            apply IHn with (m0 + n0')  φ ; auto; try (apply H7).            \n          +++++ rewrite <- H8; auto. \n          +++++ eauto using valid_config_preservation.\n          +++++ inversion H_typing2; subst; auto.\n          eauto using typing_preservation.\n          +++++ assert (terminate_num (Config ct (Container t0 f0 l0 s0) ctns2' h2'0)\n                                     (Config ct (Container final_v2 nil lb2' sf2') nil h2') \n                                     (1 + n0' - 1)).\n          eauto using execution_num_step.\n          assert (forall n, 1 + n -1 = n).\n          intros. induction n; auto.\n          pose proof H10 n0'.\n          rewrite H11 in H9; auto.   \n        \n      ++ (* conf1 steps to a high configuration *)\n         assert (L_equivalence_heap h1'0 h2 φ /\\  L_equivalence_config (Config ct (Container t f l s) ctns1' h1'0)\n                                                                       (Config ct (Container t2 fs2 lb2 sf2) ctns_stack2 h2 )  φ).\n         eauto using  simulation_H2H_H; auto.\n         apply multi_p_reduction_step with\n              (Config ct (Container t f l s) ctns1' h1'0)\n              (Config ct (Container t2 fs2 lb2 sf2) ctns_stack2 h2).\n         apply H2H_H_reduction; auto. \n         assert (exists m0', 1 + m0' = m0).\n         eauto using execution_num_step_nonzero.\n         destruct H6 as [m0'].\n         rewrite <- H6 in H1. \n         apply IHn with (m0' + n0)  φ; auto; try (apply H5).\n         +++ rewrite <- H6. simpl.\n             assert (forall n, n < S n).\n             induction n; auto.\n             pose proof H7 (m0' + n0); auto.\n         +++ eauto using valid_config_preservation.\n         +++ inversion H_typing1; subst; auto. \n           eauto using typing_preservation.\n         +++ assert (terminate_num (Config ct (Container t f l s) ctns1' h1'0)\n                                     (Config ct (Container final_v1 nil lb1' sf1') nil h1')\n                                     (1 + m0' - 1)).\n               eauto using execution_num_step.\n               assert (forall n, 1 + n -1 = n).\n               intros. induction n; auto.\n               pose proof H8 m0'.\n               rewrite H9 in H7; auto.\nQed. Hint Resolve  two_exes_to_parallel_execution.\n\n\n\nLemma p_reduction_NI : forall ct ctn1 ctns_stack1 h1 ctn2 ctns_stack2 h2 lb1' sf1' lb2' sf2' final_v1  final_v2  h1' h2' φ T, \n    valid_config (Config ct  ctn1 ctns_stack1 h1 ) ->\n    valid_config (Config ct  ctn2 ctns_stack2 h2 ) ->\n    config_has_type ct empty_context (Config ct ctn1  ctns_stack1 h1) T ->\n    config_has_type ct empty_context (Config ct ctn2  ctns_stack2 h2) T ->\n    multi_step_p_reduction (Config ct ctn1 ctns_stack1 h1)\n                           (Config ct ctn2 ctns_stack2 h2)\n                           (Config ct (Container final_v1 nil lb1' sf1') nil h1')\n                           (Config ct (Container final_v2 nil lb2' sf2') nil h2') ->\n     L_equivalence_config (Config ct ctn1 ctns_stack1 h1 )\n            (Config ct ctn2 ctns_stack2 h2)  φ ->\n     value final_v1 -> value final_v2 ->\n     L_equivalence_heap h1 h2 φ ->\n     exists  φ', L_equivalence_config (Config ct (Container final_v1 nil lb1' sf1') nil h1')  (Config ct (Container final_v2 nil lb2' sf2') nil h2')  φ'.\nProof with eauto.\n  intros ct ctn1 ctns_stack1 h1 ctn2 ctns_stack2 h2 lb1' sf1' lb2' sf2' final_v1  final_v2  h1' h2' φ T. \n  intro H_valid1. intro H_valid2.\n  intro H_typing1. intro H_typing2.\n  intro H_p_execution.\n  intro H_low_eq. intro Hv_final1. intro Hv_final2.\n  intro H_bijection.\n  remember  (Config ct ctn1 ctns_stack1 h1) as config1.\n  remember  (Config ct ctn2 ctns_stack2 h2) as config2.\n  generalize dependent ctn1.   generalize dependent ctn2.\n  generalize dependent ctns_stack1.   generalize dependent ctns_stack2.\n  generalize dependent h1.   generalize dependent h2.\n  generalize dependent T. generalize dependent φ. \n  induction   H_p_execution; intros; inversion   Heqconfig1; inversion   Heqconfig2; subst; auto. \n  exists φ.  auto.\n  induction c2; try (inversion H; fail). \n  induction c2'; try (inversion H; fail).\n  assert (ct = ct /\\ ct = c /\\ ct = c1).\n  try (eauto using ct_consist_p_reduction).\n  destruct H2. destruct H3. subst; auto. rename c1 into ct.\n\n  assert (valid_config ( (Config ct c0 l h)) /\\  valid_config (Config ct c2 l0 h0) ).\n  try (eauto using valid_config_after_p_reduction).\n  destruct H3.\n  assert (exists φ', L_equivalence_heap h h0 φ' /\\  L_equivalence_config (Config ct c0 l h) (Config ct c2 l0 h0) φ').\n  eauto using low_eq_preservation.\n  destruct H5 as [φ'].\n  destruct H5. \n\n  assert ((config_has_type ct  empty_context ((Config ct c0 l h)) T  ) /\\\n          (config_has_type ct  empty_context (Config ct c2 l0 h0) T  )).\n  apply typing_preservation_p_reduction with ctn1 ctns_stack1 h1 ctn2 ctns_stack2 h2; auto.\n  destruct H7. \n  apply IHH_p_execution with φ' T h0 h l0 l c2 c0; auto; auto.\nQed. Hint Resolve  p_reduction_NI. \n\n\n\nTheorem TINI : forall ct ctn1 ctns1 h1 ctn2 ctns2 h2 lb1' sf1' lb2' sf2' final_v1  final_v2  h1' h2' φ T m n, \n    valid_config (Config ct  ctn1 ctns1 h1 ) ->\n    valid_config (Config ct  ctn2 ctns2 h2 ) ->\n    config_has_type ct empty_context (Config ct ctn1  ctns1 h1) T ->\n    config_has_type ct empty_context (Config ct ctn2  ctns2 h2) T ->\n    terminate_num (Config ct ctn1 ctns1 h1)\n                  (Config ct (Container final_v1 nil lb1' sf1') nil h1')\n                  m ->\n    terminate_num (Config ct ctn2 ctns2 h2)\n                  (Config ct (Container final_v2 nil lb2' sf2') nil h2') \n                  n -> \n    L_equivalence_config (Config ct ctn1 ctns1 h1 )\n            (Config ct ctn2 ctns2 h2)  φ ->\n    value final_v1 -> value final_v2 ->\n     L_equivalence_heap h1 h2 φ ->\n     exists  φ', L_equivalence_config (Config ct (Container final_v1 nil lb1' sf1') nil h1')  (Config ct (Container final_v2 nil lb2' sf2') nil h2')  φ'.\nProof with eauto.\n  intros  ct ctn1 ctns1 h1 ctn2 ctns2 h2 lb1' sf1' lb2' sf2' final_v1  final_v2  h1' h2' φ T m n.\n  intro H_valid1. intro H_valid2.\n  intro H_typing1. intro H_typing2.\n  intro H_execution1. intro H_execution2. \n  intro H_low_eq. intro Hv_final1. intro Hv_final2.\n  intro H_bijection.\n  assert (two_terminate_num (Config ct ctn1 ctns1 h1)\n                  (Config ct ctn2 ctns2 h2)\n                  (Config ct (Container final_v1 nil lb1' sf1') nil h1')\n                  (Config ct (Container final_v2 nil lb2' sf2') nil h2')\n                  (m+n)).\n  eauto using  two_executions_to_one.\n  assert (multi_step_p_reduction (Config ct ctn1 ctns1 h1)\n                           (Config ct ctn2 ctns2 h2)\n                           (Config ct (Container final_v1 nil lb1' sf1') nil h1')\n                           (Config ct (Container final_v2 nil lb2' sf2') nil h2') ).\n  eauto using two_exes_to_parallel_execution.\n  eauto using p_reduction_NI.\nQed. \n\n\n\n\n\n\n", "meta": {"author": "HarvardPL", "repo": "CIFC", "sha": "39a86edcfc25f26d9698026fec5beafd4d87c7da", "save_path": "github-repos/coq/HarvardPL-CIFC", "path": "github-repos/coq/HarvardPL-CIFC/CIFC-39a86edcfc25f26d9698026fec5beafd4d87c7da/coinflow/TINI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3522017752483203, "lm_q1q2_score": 0.20873822863420943}}
{"text": "(* This code is copyrighted by its authors; it is distributed under  *)\n(* the terms of the LGPL license (see LICENSE and description files) *)\n\n(** * Main theorem of the present contribution *)\n\n(** Proof of the following theorem [iota_unique] :\n    \"Simple Lambda Calculus is initial in the category of\n     exponential monads\". *)\n\nSet Implicit Arguments.\n\nRequire Export Lc.\nRequire Export Derived_Mod.\n\nSection Lc_exp.\n\nImplicit Type X Y Z : Set.\n\nOpaque app1.\nOpaque lc lc_class lc_factor lc_factor1 lc_factor2.\nOpaque lc_abs lc_app1 lc_abs lc_fct lc_bind.\n\nNotation \"/ x\" := (lc_class x).\n\nDefinition SLC : Monad :=\n  Build_Monad term slc_bind var slc_bind_bind slc_bind_var slc_var_bind.\n\nDefinition LC : Monad := \n  Build_Monad lc lc_bind lc_var lc_bind_assoc lc_bind_var lc_var_bind.\n\nLemma slc_bind_var : forall X Y (f : X -> SLC Y) (u : X),\n  var u >>= f = f u.\nProof.\nreflexivity.\nQed.\n\nLemma slc_bind_app : forall X Y (f : X -> SLC Y) (x y : SLC X),\n  app x y >>= f = app (x >>= f)  (y >>= f).\nProof.\nreflexivity.\nQed.\n\nLemma slc_bind_abs : forall X Y (f : X -> SLC Y) (x : Derived_Mod SLC X),\n  abs x >>= f = abs (x >>>= f).\nProof.\nsimpl. intros. f_equal.\napply slc_bind_fun_cong.\ndestruct u; simpl.\n2: reflexivity.\nunfold shift.\nrewrite slc_fct_as_bind.\nreflexivity.\nQed.\n\nRemark lc_abs_hom : forall X Y (f : X -> LC Y) (x : Derived_Mod LC X),\n  lc_abs (x >>>= f) = (lc_abs x : Taut_Mod LC _) >>>= f.\nProof.\nsimpl. intros. rewrite lc_bind_abs. f_equal.\napply lc_bind_fun_cong. destruct u; simpl. 2:reflexivity.\nrewrite lc_fct_as_bind. reflexivity.\nQed.\n\nLet abs_hom : Mod_Hom (Derived_Mod LC) LC :=\n  Build_Mod_Hom (Derived_Mod LC) LC lc_abs lc_abs_hom.\n\nRemark lc_app1_hom : forall X Y (f : X -> LC Y) (x : LC X),\n  lc_app1 ((x : Taut_Mod LC X) >>>= f) =\n    (lc_app1 x : Derived_Mod LC X) >>>= f.\nProof.\nsimpl. intros. rewrite <- lc_bind_app1.\napply lc_bind_fun_cong.\ndestruct u; simpl. 2:reflexivity.\nrewrite lc_fct_as_bind. reflexivity.\nQed.\n\nLet app1_hom : Mod_Hom LC (Derived_Mod LC) :=\n  Build_Mod_Hom LC (Derived_Mod LC) lc_app1 lc_app1_hom.\n\nDefinition ELC : ExpMonad :=\n  Build_ExpMonad abs_hom app1_hom lc_eta lc_beta.\n\nVariable M : ExpMonad.\n\nFixpoint iota_fix X (x : term X) { struct x } : M X :=\n  match x with\n  | var a => unit M a\n  | app x y =>\n      exp_app M _ (iota_fix x) >>=\n        default (@unit M X) (iota_fix y)\n  | abs x => exp_abs M _ (iota_fix x)\n  end.\n\nLemma iota_fix_unit : forall X (a : X),\n  iota_fix (var a) = unit M a.\nProof.\nreflexivity.\nQed.\n\nLemma iota_fix_fct : forall X Y (f : X -> Y) (x : term X),\n  iota_fix (x //- f) = iota_fix x >>- f.\nProof.\nintros. generalize Y f; clear Y f.\ninduction x; simpl; monad.\nrewrite IHx1; clear IHx1.\nrewrite IHx2; clear IHx2.\nunfold map.\npose (mod_hom_mbind (exp_app M)). simpl in e. rewrite e.\nrewrite bind_bind.\napply bind_congr. reflexivity.\ndestruct a; simpl; monad.\nrewrite IHx; clear IHx.\npose (mod_hom_mbind (exp_abs M)). simpl in e. \nunfold map. rewrite <- e.\nreplace (iota_fix x >>= (fun x0 : option X => unit M (optmap f x0))) with\n  (iota_fix x >>=\n     default (fun u : X => unit M (f u) >>- Some (A:=Y)) (unit M None)).\nreflexivity.\napply bind_congr. reflexivity.\ndestruct a; simpl; monad.\nQed.\n\nLemma iota_fix_bind : forall X Y (f : X -> term Y) (x : term X),\n  iota_fix (x //= f) = iota_fix x >>= fun u => iota_fix (f u).\nProof.\nintros. generalize Y f; clear Y f.\ninduction x; simpl; intros; monad.\nrewrite IHx1; clear IHx1.\npose (mod_hom_mbind (exp_app M)). simpl in e. rewrite e.\nrewrite bind_bind.\napply bind_congr. reflexivity.\ndestruct a; simpl. monad.\nrewrite bind_unit. simpl. monad.\nrewrite IHx.\npose (mod_hom_mbind (exp_abs M)). simpl in e. \nunfold map. rewrite <- e.\nreplace (iota_fix x >>= (fun u : option X => iota_fix (comm f u))) with\n (iota_fix x >>=\n   default (fun u : X => iota_fix (f u) >>- Some (A:=Y)) (unit M None)).\nreflexivity.\napply bind_congr. reflexivity.\ndestruct a; simpl.\nunfold shift. rewrite iota_fix_fct. monad. reflexivity.\nQed.\n\nLemma iota_fix_app1 : forall X (x : term X),\n  iota_fix (app1 x) = exp_app M X (iota_fix x).\nProof.\nintros; rewrite app1_app; unfold shift; simpl.\nrewrite iota_fix_fct.\nunfold map.\npose (mod_hom_mbind (exp_app M)). simpl in e. rewrite e.\nrewrite bind_bind.\napply unit_bind_match.\ndestruct a; simpl; monad.\nQed.\n\nLemma iota_fix_eta : forall X (x : term X),\n  iota_fix (abs (app1 x)) = iota_fix x.\nProof.\nintros. simpl.\nrewrite iota_fix_app1.\nrewrite exp_eta. reflexivity.\nQed.\n\nLemma iota_fix_beta : forall X (x : term (option X)) y,\n  iota_fix (app (abs x) y) = iota_fix (x //= default (fun a => var a) y).\nProof.\nintros; simpl.\nrewrite exp_beta. rewrite iota_fix_bind.\napply bind_congr. reflexivity.\ndestruct a; simpl; reflexivity.\nQed.\n\nLemma iota_fix_wd : forall X (x y : term X),\n  x == y -> iota_fix x = iota_fix y.\nProof.\ninduction 1.\nauto.\nsimpl. rewrite IHlcr1. rewrite IHlcr2. reflexivity.\nsimpl. rewrite IHlcr. reflexivity.\ndestruct H.\napply iota_fix_beta.\napply iota_fix_eta.\nauto.\neapply trans_eq; eauto.\nQed.\n\nLet iota X : lc X -> M X :=\n  lc_factor (@iota_fix X) (@iota_fix_wd X).\n\nRemark iota_factorize : forall X (x : term X),\n  iota (/ x) = iota_fix x.\nProof.\nunfold iota. intros. rewrite lc_factorize. reflexivity.\nQed.\n\nOpaque iota.\n\nRemark iota_bind : forall X Y (f : X -> lc Y) (x : lc X),\n  iota (lc_bind f x) = iota x >>= (fun a : X => iota (f a)).\nProof.\nintros.\ndestruct (lc_class_surj x) as [y Hy]. subst x.\ndestruct (lc_fun_lift f) as [f' Hf]. subst f.\nrewrite lc_bind_factorize.\ndo 2 rewrite iota_factorize.\nrewrite iota_fix_bind.\napply bind_congr. reflexivity.\nintro. rewrite iota_factorize. reflexivity.\nQed.\n\nRemark iota_var : forall X (a : X),\n  iota (lc_var a) = unit M a.\nProof.\nsimpl. unfold lc_var. intros.\nrewrite iota_factorize. reflexivity.\nQed.\n\nLemma iota_app1 : forall X (x : lc X),\n  iota (lc_app1 x) = exp_app M X (iota x).\nProof.\nintros.\ndestruct (lc_class_surj x) as [y Hy]. subst x.\nrewrite lc_app1_factorize.\ndo 2 rewrite iota_factorize.\nrewrite iota_fix_app1. reflexivity.\nQed.\n\nLemma iota_abs : forall X (x : lc (option X)),\n  iota (lc_abs x) = exp_abs M X (iota x).\nProof.\nintros.\ndestruct (lc_class_surj x) as [y Hy]. subst x.\nrewrite lc_abs_factorize.\ndo 2 rewrite iota_factorize. reflexivity.\nQed.\n\nLet iota_monad : Monad_Hom LC M :=\n  Build_Monad_Hom LC M iota iota_bind iota_var.\n\nLet exp_iota : ExpMonad_Hom ELC M :=\n  Build_ExpMonad_Hom ELC M iota_monad iota_app1 iota_abs.\n\nTheorem iota_unique : forall (j : ExpMonad_Hom ELC M) X (x : lc X),\n  j X x = exp_iota X x.\nProof.\nintros. destruct j as [[p p_bind p_var] p_app p_abs].\nsimpl in *. unfold lc_var in *.\ndestruct (lc_class_surj x) as [y Hy]. subst x.\nrewrite iota_factorize.\ninduction y.\nsimpl. auto.\nrewrite app_as_app1. rewrite iota_fix_bind.\nrewrite iota_fix_app1. rewrite <- lc_bind_factorize.\nrewrite p_bind. rewrite <- lc_app1_factorize.\nrewrite p_app. rewrite IHy1.\napply bind_congr. reflexivity.\ndestruct a; simpl; auto.\nsimpl. rewrite <- lc_abs_factorize. rewrite p_abs.\nreplace (p (option X) (/ y)) with (iota_fix y).\nreflexivity.\nQed.\n\nEnd Lc_exp.\n", "meta": {"author": "sdiehl", "repo": "modules_over_monads", "sha": "9483df1273cc70ca79b562330e7bab1f26b97d72", "save_path": "github-repos/coq/sdiehl-modules_over_monads", "path": "github-repos/coq/sdiehl-modules_over_monads/modules_over_monads-9483df1273cc70ca79b562330e7bab1f26b97d72/src/Lc_exp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.20843926445410693}}
{"text": "Add LoadPath \"D:\\sfsol\".\nRequire Export SfLib.\nRequire Import String.\n\nDefinition ProgramCounter : Type := nat.\n\nDefinition clist (X : Type) := list (ProgramCounter * X).\n\nInductive StringIndex : Type :=\n  | strAt : string -> nat -> StringIndex.\n\nInductive Constant : Type :=\n  | cnat : nat -> Constant\n  | cstr : StringIndex -> Constant\n  | ctrue : Constant\n  | cfalse : Constant\n  | cnull : Constant.\n\nInductive UnaryOperator : Type :=\n  | unot : UnaryOperator.\n\nInductive BinaryArithOperator : Type :=\n  | badd : BinaryArithOperator\n  | bsub : BinaryArithOperator\n  | bmult : BinaryArithOperator\n  | bdiv : BinaryArithOperator\n  | bmod : BinaryArithOperator\n  | band : BinaryArithOperator\n  | bor : BinaryArithOperator\n  | bxor : BinaryArithOperator.\n\nInductive BinaryCompOperator : Type :=\n  | beq : BinaryCompOperator\n  | blt : BinaryCompOperator\n  | bgt : BinaryCompOperator.\n\nDefinition RegIndex := nat.\n\nInductive Register : Type :=\n  | Reg : RegIndex -> Register.\n\nDefinition Regs := list Register.\n\nDefinition Addr := nat.\n\nDefinition Addrs := list Addr.\n\nInductive PrimType : Type :=\n  | boolean : bool -> PrimType\n  | char : nat -> PrimType\n  | int : nat -> PrimType.\n\nInductive pTypes : Type :=\n  | bT : pTypes\n  | cT : pTypes\n  | iT : pTypes.\n\nInductive Class : Type :=\n  | top : Class\n  | class : StringIndex -> ClassIndex -> list FieldIndex -> list MethodIndex -> Class\nwith ClassIndex : Type :=\n  | classAt : Class -> nat -> ClassIndex\nwith Field : Type :=\n  | field : StringIndex -> ClassIndex -> Field\nwith FieldIndex : Type :=\n  | fieldAt : Field -> nat -> FieldIndex\nwith Method : Type :=\n  | method : StringIndex -> ClassIndex -> list TypeIndex -> TypeIndex -> nat -> clist Instruction -> Method\nwith MethodIndex : Type :=\n  | methodAt : Method -> nat -> MethodIndex\nwith Instruction : Type :=\n  | nop : Instruction\n  | ret : Instruction\n  | retTo : Register -> Instruction\n  | invoke : list rhs -> MethodIndex -> Instruction\n  | goto : ProgramCounter -> Instruction\n  | branch : Register -> BinaryCompOperator -> Register -> ProgramCounter -> Instruction\n  | move : lhs -> rhs -> Instruction\n  | unaryArith : Register -> UnaryOperator -> Register -> Instruction\n  | binaryArith : Register -> Register -> BinaryArithOperator -> Register -> Instruction\n  | new : Register -> ClassIndex -> Instruction\n  | newarr : Register -> DalType -> Register -> Instruction\n  | cast : Register -> DalType -> Register -> Instruction\nwith lhs : Type :=\n  | reg : Register -> lhs\n  | acc : Register -> Register -> lhs\n  | ifield : Register -> FieldIndex -> lhs\n  | sfield : FieldIndex -> lhs\nwith rhs : Type :=\n  | l : lhs -> rhs\n  | c : Constant -> rhs\nwith DalType : Type :=\n  | refT : RefType -> DalType\n  | primT : pTypes -> DalType\nwith TypeIndex : Type :=\n  | typeAt : DalType -> nat -> TypeIndex\nwith RefType : Type :=\n  | cls : Class -> RefType\n  | arrRef : RefType -> nat -> RefType\n  | arrPrim : pTypes -> nat -> RefType\nwith Ref : Type :=\n  | lRef : Location -> Ref\n  | null : Ref\nwith Val : Type :=\n  | prim : PrimType -> Val\n  | ref : Ref -> Val\n  | siv : StringIndex -> Val\nwith Object : Type :=\n  | topObj : Object\n  | obj : ClassIndex -> ClassIndex -> list (FieldIndex * Val) -> Object\nwith Array : Type :=\n  | arr : nat -> list Val -> Array\nwith arrOrObj : Type :=\n  | ar : Array -> arrOrObj\n  | ob : Object -> arrOrObj\nwith Location : Type :=\n  | locIn : nat -> Location.\n\nDefinition RegVal := Val.\n\nDefinition RegVals := list RegVal.\n\nDefinition RegState : Type := RegVals.\n\nDefinition PCVal := nat.\n\nDefinition Program := list ClassIndex.\n\n(* Operator Arithmetic *)\n\nDefinition top1: Class := top.\n\nDefinition top2: Class := top.\n\nInductive Option {X : Type} : Type :=\n  | None : Option\n  | Some : X -> Option.\n\nFixpoint nth {A:Type} (n:nat) (l:list A) : (@Option A) :=\n  match l,n with\n  | [],_ => None\n  | cons x lst,0 => Some x\n  | cons x lst,(S n') => nth n' lst\n  end.\n\nDefinition areSameSI (si1 si2:StringIndex) : bool :=\n  match si1,si2 with\n  | (strAt s1 n1),(strAt s2 n2) => (beq_nat n1 n2)\n  end.\n\nFixpoint isSubClass (c1 c2:Class) : bool :=\n  match c1,c2 with\n  | _,top => true\n  | top,_ => false\n  | (class si1 ci1 fi1 mi1),(class si2 ci2 fi2 mi2)=> match (areSameSI si1 si2) with\n    | true => true\n    | false => match ci1 with\n      | (classAt c1' n) => isSubClass c1' (class si2 ci2 fi2 mi2)\n      end\n    end\n  end.\n\nDefinition areSameClass (c1 c2:Class) : bool :=\n  (andb (isSubClass c1 c2) (isSubClass c2 c1)).\n\nFixpoint arePrim (n1:DalType) (n2:DalType) : (@Option bool) :=\n  match n1 with\n  | (refT x) => None\n  | (primT x) => match n2 with\n    | (refT y) => None\n    | (primT y) => (Some true)\n    end\n  end.\n\nFixpoint areEqualNum (n1:nat) (n2:nat) : bool :=\n  match n1 with\n  | O => match n2 with\n    | O => true\n    | _ => false\n    end\n  | (S n1') => match n2 with\n    | O => false\n    | (S n2') => (areEqualNum n1' n2')\n    end\n  end.\n\nDefinition areSameCI (ci1 ci2:ClassIndex) : bool :=\n  match ci1,ci2 with\n  | (classAt c1 n1),(classAt c2 n2) => andb (areSameClass c1 c2) (areEqualNum n1 n2)\n  end.\n\nFixpoint areEqualBool (b1 b2:bool) : bool :=\n  match b1 , b2 with\n  | true,true => true\n  | false,false => true\n  | _,_ => false\n  end.\n\nFixpoint isle_num (m n:nat) : bool :=\n  match m with\n  | O => true\n  | (S m') => match n with\n    | O => false\n    | (S n') => (isle_num m' n')\n    end\n  end.\n\nFixpoint div (m n:nat) {struct m} : nat :=\n  match m with\n  | O => O\n  | (S m') => match (areEqualNum n (m - (mult (div m' n) n))) with\n    | true => S (div m' n)\n    | false => (div m' n)\n    end\n  end.\n\nCompute (div 3 0).\n\nDefinition mod (m n:nat) : nat := m - (mult (div m n) n).\n\nCompute (mod 3 2).\n\nFixpoint areEqualPrim (b1 b2:PrimType): (@Option bool) :=\n  match b1,b2 with\n  | boolean x,boolean y => Some (areEqualBool x y)\n  | char x,char y => Some (areEqualNum x y)\n  | int x,int y => Some (areEqualNum x y)\n  | _,_ => None\n  end.\n\nDefinition castIntToChar (n: nat) : nat := (mod n 128).\n\nDefinition castBoolToCharOrInt (b: bool) : nat :=\n  match b with\n  | true => 1\n  | false => 0\n  end.\n\nDefinition castCharOrIntToBool (n:nat) : bool :=\n  (negb (areEqualNum n 0)).\n\nDefinition castToChar (x:PrimType) : nat :=\n  match x with\n  | char x' => x'\n  | int x' => (castIntToChar x')\n  | boolean x' => (castBoolToCharOrInt x')\n  end.\n\nDefinition castToInt (x:PrimType) : nat :=\n  match x with\n  | char x' => x'\n  | int x' => x'\n  | boolean x' => (castBoolToCharOrInt x')\n  end.\n\nDefinition castToBool (x:PrimType) : bool :=\n  match x with\n  | char x' => (castCharOrIntToBool x')\n  | int x' => (castCharOrIntToBool x')\n  | boolean x' => x'\n  end.\n\nDefinition addPrims (n1 n2: PrimType) : (@Option PrimType) :=\n  Some (int (plus (castToInt n1) (castToInt n2))).\n\nDefinition subPrims (n1 n2: PrimType) : (@Option PrimType) :=\n  Some (int (minus (castToInt n1) (castToInt n2))).\n\nDefinition multPrims (n1 n2: PrimType) : (@Option PrimType) :=\n  Some (int (mult (castToInt n1) (castToInt n2))).\n\nDefinition divPrims (n1 n2: PrimType) : (@Option PrimType) :=\n  Some (int (div (castToInt n1) (castToInt n2))).\n\nDefinition modPrims (n1 n2: PrimType) : (@Option PrimType) :=\n  Some (int (mod (castToInt n1) (castToInt n2))).\n\nDefinition andPrims (n1 n2: PrimType) : (@Option PrimType) :=\n  Some (boolean (andb (castToBool n1) (castToBool n2))).\n\nDefinition orPrims (n1 n2: PrimType) : (@Option PrimType) :=\n  Some (boolean (orb (castToBool n1) (castToBool n2))).\n\nDefinition xorPrims (n1 n2: PrimType) : (@Option PrimType) :=\n  Some (boolean (xorb (castToBool n1) (castToBool n2))).\n\nDefinition eqPrims (n1 n2: PrimType) : (@Option PrimType) :=\n  Some (boolean (negb (xorb (castToBool n1) (castToBool n2)))).\n\nDefinition ltPrims (n1 n2: PrimType) : (@Option PrimType) :=\n  Some (boolean (isle_num ((castToInt n1) + 1) (castToInt n2))).\n\nDefinition gtPrims (n1 n2: PrimType) : (@Option PrimType) :=\n  Some (boolean (isle_num ((castToInt n2) + 1) (castToInt n1))).\n\nDefinition notPrims (n1: PrimType) : (@Option PrimType) :=\n  Some (boolean (negb (castToBool n1))).\n\nDefinition applyBinArOp (bop: BinaryArithOperator) (n1 n2: PrimType) : (@Option PrimType) :=\n  match bop with\n  | badd => (addPrims n1 n2)\n  | bsub => (subPrims n1 n2)\n  | bmult => (multPrims n1 n2)\n  | bdiv => (divPrims n1 n2)\n  | bmod => (modPrims n1 n2)\n  | band => (andPrims n1 n2)\n  | bor => (orPrims n1 n2)\n  | bxor => (xorPrims n1 n2)\n  end.\n\nDefinition applyBinCmpOp (bop: BinaryCompOperator) (n1 n2: PrimType) : (@Option PrimType) :=\n  match bop with\n  | beq => (eqPrims n1 n2)\n  | blt => (ltPrims n1 n2)\n  | bgt => (gtPrims n1 n2)\n  end.\n\nDefinition applyUnOp (uop: UnaryOperator) (n1: PrimType) : (@Option PrimType) :=\n  match uop with\n  | unot => (notPrims n1)\n  end.\n\nFixpoint getInstAtInsts (pc:ProgramCounter) (insts:clist Instruction) : (@Option Instruction) :=\n  match insts with\n  | [] => None\n  | (n,ins)::xs => match (areEqualNum n pc) with\n    | true => Some ins\n    | false => (getInstAtInsts pc xs)\n    end\n  end.\n\nFixpoint getInstAtMIs (pc:ProgramCounter) (mis:list MethodIndex) : (@Option Instruction) :=\n  match mis with\n  | [] => None\n  | (methodAt (method si ci tis ti n insts) _)::xs => \n    match (getInstAtInsts pc insts) with\n    | None => (getInstAtMIs pc xs)\n    | x => x\n    end\n  end.\n\nFixpoint getInstAt (pc:ProgramCounter) (p:Program) : (@Option Instruction) :=\n  match p with\n  | [] => None\n  | (classAt top _)::xs => None\n  | (classAt (class si ci fi mis) _)::xs =>\n    match (getInstAtMIs pc mis) with\n    | None => (getInstAt pc xs)\n    | x => x\n    end\n  end.\n\nFixpoint getFirstPCMethod (mi:MethodIndex) : (@Option ProgramCounter) :=\n  match mi with\n  | (methodAt (method si ci tis ti n insts) _) =>\n    match insts with\n    | [] => None\n    | (x,y)::rem => Some x\n    end\n  end.\n\nDefinition LocalReg : Type := (list (Register*Val)).\n\nInductive Frame : Type := \n  | frm : (MethodIndex * ProgramCounter * LocalReg) -> Frame.\n\nInductive ExcFrame : Type :=\n  | exc : Location * MethodIndex * ProgramCounter -> ExcFrame.\n\nInductive callStack : Type :=\n  | cf : Frame * list Frame -> callStack\n  | ce : ExcFrame * list Frame -> callStack.\n\nInductive ValOrRef : Type :=\n  | v : Val -> ValOrRef\n  | a : arrOrObj -> ValOrRef.\n\nDefinition StaticHeap : Type := list (FieldIndex * ValOrRef).\n\nDefinition Heap : Type := list arrOrObj.\n\nInductive Config : Type := \n  | cnf : StaticHeap * Heap * callStack -> Config.\n\nFixpoint getPCconfig (init:Config) : ProgramCounter :=\n  match init with\n  | cnf (sh,h,(ce (exc (lc,mi,pc),lst))) => pc\n  | cnf (sh,h,(cf (frm (mi,pc,lrg),lst))) => pc\n  end.\n\nFixpoint updatePCconfig (init:Config) (pc:ProgramCounter) : Config :=\n  match init with\n  | cnf (sh,h,(ce (exc (lc,mi,pc'),lst))) => cnf (sh,h,(ce (exc (lc,mi,pc),lst)))\n  | cnf (sh,h,(cf (frm (mi,pc',lrg),lst))) => cnf (sh,h,(cf (frm (mi,pc,lrg),lst)))\n  end.\n\nDefinition updateLocalReg (r:Register) (v:Val) (lr:LocalReg): LocalReg := (r,v)::lr.\n\nFixpoint findInLocalReg (r:Register) (lr:LocalReg): (@Option Val) :=\n  match lr with\n  | [] => None\n  | (x,y)::rem => match (x,r) with\n    | ((Reg n1),(Reg n2)) => match (areEqualNum n1 n2) with\n      | true => Some y\n      | false => (findInLocalReg r rem)\n      end\n    end\n  end.\n\nFixpoint regToValLocalRegs (r:Register) (lr:LocalReg) : (@Option Val) :=\n  match lr with\n  | nil => None\n  | cons (r',val) rem => match (r,r') with\n    | (Reg ri,Reg ri') => match (areEqualNum ri ri') with\n      | true => Some val\n      | false => (regToValLocalRegs r rem)\n      end\n    end\n  end.\n\nFixpoint regToValFrame (r:Register) (f:Frame) : (@Option Val) :=\n  match f with\n  | frm (mi,pc,lr) => regToValLocalRegs r lr\n  end.\n\nFixpoint regToValFrames (r:Register) (fL:list Frame) : (@Option Val) :=\n  match fL with\n  | nil => None\n  | cons f rem =>  match (regToValFrame r f) with\n    | None => (regToValFrames r rem)\n    | x => x\n    end\n  end.\n\nFixpoint regToVal (r:Register) (conf:Config) : (@Option Val) :=\n  match conf with\n  | cnf (sh,h,(ce (eF,lst))) => (regToValFrames r lst)\n  | cnf (sh,h,(cf (fm,lst))) => match (regToValFrame r fm) with\n    | None => (regToValFrames r lst)\n    | x => x\n    end\n  end.\n\nFixpoint refToVal (rf:Ref) (conf:Config) : (@Option arrOrObj) :=\n  match rf,conf with\n  | (lRef (locIn n)),(cnf (sh,h,cs)) => (nth n h)\n  | _,_ => None\n  end.\n\nFixpoint accToVal (r1 r2:Register) (conf:Config) : (@Option Val) :=\n  match (regToVal r1 conf),(regToVal r2 conf) with\n  | None,_ => None\n  | Some (ref rf),Some (prim x) => match (refToVal rf conf) with\n    | Some (ar (arr n vals)) => (nth (castToInt x) vals)\n    | _ => None\n    end\n  | _,_ => None\n  end.\n\nFixpoint areSameFI (fi1 fi2:FieldIndex) : bool :=\n  match fi1,fi2 with\n  | (fieldAt (field SI1 CI1) n1),(fieldAt (field SI2 CI2) n2) => andb (andb (areSameSI SI1 SI2) (areSameCI CI1 CI2)) (areEqualNum n1 n2)\n  end.\n\nFixpoint findFI {X:Type} (fi:FieldIndex) (l:list (FieldIndex * X)) : (@Option X) :=\n  match l with\n  | nil => None\n  | cons (fi',val) rem => match (areSameFI fi fi') with\n    | true => Some val\n    | false => findFI fi rem\n    end\n  end.\n\nFixpoint ifieldToVal (r1:Register) (fi:FieldIndex) (conf:Config) : (@Option Val) :=\n  match (regToVal r1 conf) with\n  | Some (ref rf) => match (refToVal rf conf) with\n    | Some (ob (obj ci ci2 flst)) => (findFI fi flst)\n    | _ => None\n    end\n  | _ => None\n  end.\n\nFixpoint sfieldToVal (fi:FieldIndex) (conf:Config) : (@Option ValOrRef) :=\n  match conf with\n  | (cnf (sh,h,cs)) => (findFI fi sh)\n  end.\n\nFixpoint ValToValOrRef (val:@Option Val) : (@Option ValOrRef) :=\n  match val with\n  | Some x => Some (v x)\n  | None => None\n  end.\n\nFixpoint ValOrRefToVal (val:@Option ValOrRef) : (@Option Val) :=\n  match val with\n  | Some (v x) => Some x\n  | _ => None\n  end.\n\nDefinition lhsToVal (l:lhs) (conf:Config) : (@Option ValOrRef):=\n  match l with\n  | (reg r) => ValToValOrRef (regToVal r conf)\n  | (acc r1 r2) => ValToValOrRef (accToVal r1 r2 conf)\n  | (ifield r1 fi) => ValToValOrRef (ifieldToVal r1 fi conf)\n  | (sfield fi) => sfieldToVal fi conf\n  end.\n\nDefinition lhsToReg (l:lhs) (r:Register) (conf:Config) : (@Option (Register*ValOrRef)) :=\n  match (lhsToVal l conf) with\n  | Some x => Some (r,x)\n  | None => None\n  end.\n\nDefinition constantToVal (c:Constant) : (@Option ValOrRef) :=\n  match c with\n  | cnat n => Some (v (prim (int n)))\n  | cstr s => Some (v (siv s))\n  | ctrue => Some (v (prim (boolean true)))\n  | cfalse => Some (v (prim (boolean false)))\n  | cnull => Some (v (ref null))\n  end.\n\nFixpoint rhsToVal (r:rhs) (conf:Config) : (@Option ValOrRef) :=\n  match r with\n  | l ls => (lhsToVal ls conf)\n  | c cnst => (constantToVal cnst)\n  end.\n\nDefinition rhsToReg (r:rhs) (r1:Register) (conf:Config) : (@Option (Register*ValOrRef)) :=\n  match (rhsToVal r conf) with\n  | Some x => Some (r1,x)\n  | None => None\n  end.\n\nFixpoint setInLocalReg (r:Register) (lr:LocalReg) (vl:@Option Val) : (@Option LocalReg) :=\n  match vl,lr with\n  | None,_ => None\n  | Some vl,[] => None\n  | Some vl,cons (r',v') rem => match r,r' with\n    | Reg n,Reg n' => match (areEqualNum n n') with\n      | true => Some (cons (r',vl) rem)\n      | false => match (setInLocalReg r rem (Some vl)) with\n        | Some lr' => Some (cons (r',v') lr')\n        | None => None\n        end\n      end\n    end\n  end.\n\nFixpoint valToRegFrame (r:Register) (f:Frame) (vl:@Option Val) : (@Option Frame) :=\n  match f with\n  | frm (mi,pc,lr) => match (setInLocalReg r lr vl) with\n    | Some lr' => Some (frm (mi,pc,lr'))\n    | _ => None\n    end\n  end.\n\nFixpoint valToRegFrames (r:Register) (fL:list Frame) (vl:@Option Val) : @Option (list Frame) :=\n  match fL,vl with\n  | _,None => None\n  | nil,Some vl => None\n  | cons f rem,Some vl =>  match (valToRegFrame r f (Some vl)) with\n    | Some f' => Some (cons f' rem)\n    | None => match (valToRegFrames r rem (Some vl)) with\n      | Some rem' => Some (cons f rem')\n      | None => None\n      end\n    end\n  end.\n\nFixpoint valToReg (r:Register) (conf:Config) (vl:@Option Val) : (@Option Config) :=\n  match conf with\n  | cnf (sh,h,(ce (eF,lst))) => match (valToRegFrames r lst vl) with\n    | Some lst' => Some (cnf (sh,h,(ce (eF,lst))))\n    | None => None\n    end\n  | cnf (sh,h,(cf (fm,lst))) => match (valToRegFrame r fm vl) with\n    | Some fm' => Some (cnf (sh,h,(cf (fm',lst))))\n    | None => match (valToRegFrames r lst vl) with\n      | Some lst' => Some (cnf (sh,h,(cf (fm,lst'))))\n      | None => None\n      end\n    end\n  end.\n\nFixpoint setNth {X:Type} (x:X) (n:nat) (l:list X) : (@Option (list X)) :=\n  match l,n with\n  | [],_ => None\n  | (cons x' rem),0 => Some (cons x rem)\n  | (cons x' rem),S n' => match (setNth x n' rem) with\n    | None => None\n    | Some rem' => Some (cons x' rem')\n    end\n  end.\n\nFixpoint setAtRef (rf:Ref) (conf:Config) (vl:@Option arrOrObj) : (@Option Config) :=\n  match rf,conf,vl with\n  | (lRef (locIn n)),(cnf (sh,h,cs)),Some vl => match (setNth vl n h) with\n    | Some h' => Some (cnf (sh,h',cs))\n    | _ => None\n    end\n  | _,_,_ => None\n  end.\n\nFixpoint valToAcc (r1 r2:Register) (conf:Config) (vl:@Option Val) : (@Option Config) :=\n  match (regToVal r1 conf),(regToVal r2 conf),vl with\n  | None,_,_ => None\n  | Some (ref rf),Some (prim x),Some vl => match (refToVal rf conf) with\n    | Some (ar (arr n vals)) => match (setNth vl (castToInt x) vals) with\n      | None => None\n      | Some vals' => (setAtRef rf conf (Some (ar (arr n vals'))))\n      end\n    | _ => None\n    end\n  | _,_,_ => None\n  end.\n\nFixpoint setAtFI {X:Type} (x:X) (fi:FieldIndex) (l:list (FieldIndex * X)) : (@Option (list (FieldIndex * X))) :=\n  match l with\n  | nil => None\n  | cons (fi',x') rem => match (areSameFI fi fi') with\n    | true => Some (cons (fi',x) rem)\n    | false => match (setAtFI x fi rem) with\n      | Some rem' => Some (cons (fi',x') rem')\n      | _ => None\n      end\n    end\n  end.\n\nFixpoint valToIfield (r1:Register) (fi:FieldIndex) (conf:Config) (vl:@Option Val) : (@Option Config) :=\n  match (regToVal r1 conf) with\n  | Some (ref rf) => match (refToVal rf conf),vl with\n    | Some (ob (obj ci ci2 flst)),Some vl => match (setAtFI vl fi flst) with\n      | Some flst' => (setAtRef rf conf (Some (ob (obj ci ci2 flst'))))\n      | _ => None\n      end\n    | _,_ => None\n    end\n  | _ => None\n  end.\n\nFixpoint valToSfield (fi:FieldIndex) (conf:Config) (vl:@Option ValOrRef) : (@Option Config) :=\n  match conf,vl with\n  | (cnf (sh,h,cs)),Some vl => match (setAtFI vl fi sh) with\n    | Some sh' => Some (cnf (sh',h,cs))\n    | _ => None\n    end\n  | _,_ => None\n  end.\n\nDefinition newPrim (pt:pTypes) : PrimType :=\n  match pt with\n  | bT => (boolean false)\n  | cT => (char 0)\n  | iT => (int 0)\n  end.\n\nFixpoint createList {X:Type} (n:nat) (x:X) : list X :=\n  match n with\n  | 0 => nil\n  | S n' => cons x (createList n' x)\n  end.\n\nDefinition newArrPrim (n:nat) (pt:pTypes) : Array :=\n  arr n (createList n (prim (newPrim pt))).\n\n(*Fixpoint newObject (c:Class) : Object :=\n  match c with\n  | top => topObject\n  | (class SI CI FIs MIs) => \n*)\n\nFixpoint newInstance (t:DalType) : (ValOrRef) :=\n  match t with\n  | (primT pt) => (v (prim (newPrim pt)))\n  | (refT (cls cl)) => (v (ref null))    (*(a (ob (newObject c))) *)\n  | (refT (arrRef rt n)) => (v (ref null)) (* (a (ar (newArrRef rt))) *)\n  | (refT (arrPrim pt n)) => (a (ar (newArrPrim n pt)))\n  end.\n\nwith\n\nFixpoint step (init:Config) (p:Program): (@Option Config) :=\n  match (getInstAt (getPCconfig init) p) with\n  | None => None\n  | Some x => match x with\n    | nop => Some (updatePCconfig init ((getPCconfig init)+1))\n    | (goto pc) => Some (updatePCconfig init pc)\n    | (invoke args m) =>\n    | x => None\n    end\n  end.", "meta": {"author": "mmalone", "repo": "sfsol", "sha": "5888f4532a1ec1ababa21bef39e25eb26279f0e4", "save_path": "github-repos/coq/mmalone-sfsol", "path": "github-repos/coq/mmalone-sfsol/sfsol-5888f4532a1ec1ababa21bef39e25eb26279f0e4/SmallDal/SmallDal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20842728115526346}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import Psatz.\n\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\n\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Errors.\nRequire Import compcert.common.Switch.\nRequire Import compcert.backend.Cminor.\n\nRequire Import StructTact.StructTactics.\nRequire Import StructTact.Util.\n\nRequire Import oeuf.EricTact.\nRequire Import oeuf.StuartTact.\nRequire Import oeuf.ListLemmas.\n\nRequire Import oeuf.HighValues.\nRequire Import oeuf.OpaqueTypes.\nRequire Import oeuf.Monads.\nRequire Import oeuf.FullSemantics.\n\n\nLemma pos_lt_neq :\n  forall p q,\n    (p < q)%positive ->\n    p <> q.\nProof.\n  intros.\n  unfold Pos.lt in H.\n  intro. rewrite <- Pos.compare_eq_iff in H0.\n  congruence.\nQed.\n\n\n\nLemma load_lt_nextblock :\n  forall c m b ofs v,\n    Mem.load c m b ofs = Some v ->\n    (b < Mem.nextblock m)%positive.\nProof.\n  intros.\n  remember (Mem.nextblock_noaccess m) as H2.\n  clear HeqH2.\n  destruct (plt b (Mem.nextblock m)). assumption.\n  app Mem.load_valid_access Mem.load.\n  unfold Mem.valid_access in *.\n  break_and. unfold Mem.range_perm in *.\n  specialize (H ofs).\n  assert (ofs <= ofs < ofs + size_chunk c).\n  destruct c; simpl; omega.\n  specialize (H H3).\n  unfold Mem.perm in *.\n  unfold Mem.perm_order' in H.\n  rewrite H2 in H; eauto. inversion H.\nQed.\n\n\nDefinition mem_locked' (m m' : mem) (b : block) : Prop :=\n  forall b',\n    (b' < b)%positive ->\n    forall ofs c v,\n      Mem.load c m b' ofs = Some v ->\n      Mem.load c m' b' ofs = Some v.\n\nDefinition mem_locked (m m' : mem) : Prop :=\n  mem_locked' m m' (Mem.nextblock m).\n\nLemma alloc_mem_locked :\n  forall m lo hi m' b,\n    Mem.alloc m lo hi = (m',b) ->\n    mem_locked m m'.\nProof.\n  unfold mem_locked.\n  unfold mem_locked'.\n  intros.\n  app Mem.alloc_result Mem.alloc. subst b.\n  app load_lt_nextblock Mem.load.\n  erewrite Mem.load_alloc_unchanged; eauto.\nQed.\n\nLemma load_all_mem_locked :\n  forall m m',\n    mem_locked m m' ->\n    forall b,\n      (b < Mem.nextblock m)%positive ->\n      forall l ofs l',\n        load_all (arg_addrs b ofs l) m = Some l' ->\n        load_all (arg_addrs b ofs l) m' = Some l'.\nProof.\n  induction l; intros.\n  simpl in H1. inv H1. simpl. reflexivity.\n  simpl in H1. repeat break_match_hyp; try congruence.\n  invc H1.\n  eapply IHl in Heqo0.\n  simpl. rewrite Heqo0.\n  unfold mem_locked in H.\n  unfold mem_locked' in H.\n  apply H in Heqo; auto. find_rewrite. reflexivity.\nQed.  \n\nLemma load_all_mem_inj_id :\n  forall m m',\n    Mem.mem_inj inject_id m m' ->\n    forall b l ofs l',\n      load_all (arg_addrs b ofs l) m = Some l' ->\n      exists l'',\n        load_all (arg_addrs b ofs l) m' = Some l'' /\\\n        Forall2 (fun a b => Val.lessdef (snd a) (snd b)) l' l''.\nProof.\n  induction l; intros0 Hload.\n    { simpl in *. inject_some. eexists. split; eauto. }\n\n  simpl in Hload.\n  do 2 (break_match; try discriminate). inject_some.\n\n  fwd eapply Mem.load_inj as HH; eauto.\n    { reflexivity. }\n    destruct HH as (v' & ? & ?).\n    rewrite Z.add_0_r in *.\n  fwd eapply IHl as HH; eauto.  destruct HH as (? & ? & ?).\n\n  simpl.\n  on _, fun H => rewrite H.\n  on _, fun H => rewrite H.\n  eexists. split; eauto.\n  econstructor; eauto.\n  rewrite <- val_inject_id. eauto.\nQed.\n\nLemma lessdef_def_eq : forall v v',\n    Val.lessdef v v' ->\n    v <> Vundef ->\n    v' = v.\ndestruct v; intros0 Hld Hundef; try congruence.\nall: invc Hld; reflexivity.\nQed.\n\nLemma value_inject_lessdef : forall A B (ge : Genv.t A B) m hv cv cv',\n    value_inject ge m hv cv ->\n    Val.lessdef cv cv' ->\n    value_inject ge m hv cv'.\ninduction hv; intros0 Hvi Hld.\n\n- on >@value_inject, invc. on >Val.lessdef, invc.\n  econstructor; eauto.\n\n- on >@value_inject, invc. on >Val.lessdef, invc.\n  econstructor; eauto.\n\n- on >@value_inject, invc. econstructor.\n  fwd eapply lessdef_def_eq; eauto.\n    { eapply opaque_type_inject_defined; eauto. }\n  fix_existT. subst. auto.\nQed.\n\nLemma value_inject_defined : forall A B (ge : Genv.t A B) m hv cv,\n    value_inject ge m hv cv ->\n    cv <> Vundef.\nintros0 Hvi. invc Hvi; try discriminate.\n- eapply opaque_type_inject_defined; eauto.\nQed.\n\n\nLemma load_all_arg_addrs_zip : forall b ofs args m l,\n    load_all (arg_addrs b ofs args) m = Some l ->\n    exists cvs,\n        l = zip args cvs /\\\n        length cvs = length args.\nfirst_induction args; intros0 Hload; simpl in Hload.\n  { inject_some. exists []. split; reflexivity. }\n\ndo 2 (break_match; try discriminate). inject_some.\nfwd eapply IHargs as HH; eauto.  destruct HH as (? & ? & ?).\nsubst.\neexists (_ :: _). simpl. eauto.\nQed.\n\nLemma Forall2_eq : forall A (xs ys : list A),\n    Forall2 (fun x y => x = y) xs ys ->\n    xs = ys.\ninduction xs; destruct ys; intros0 HH; inversion HH; eauto.\n- subst. erewrite IHxs; eauto.\nQed.\n\nLemma Forall2_eq' : forall A (xs ys : list A),\n    xs = ys ->\n    Forall2 (fun x y => x = y) xs ys.\ninduction xs; destruct ys; intros0 HH; inversion HH; eauto.\n- subst. econstructor; eauto.\nQed.\n\nLemma zip_Forall2_eq_l : forall A B (xs : list A) (ys : list B),\n    length xs = length ys ->\n    Forall2 (fun x p => x = fst p) xs (zip xs ys).\ninduction xs; destruct ys; intros; try discriminate; constructor; eauto.\nQed.\n\nLemma zip_Forall2_eq_r : forall A B (xs : list A) (ys : list B),\n    length xs = length ys ->\n    Forall2 (fun y p => y = snd p) ys (zip xs ys).\ninduction xs; destruct ys; intros; try discriminate; constructor; eauto.\nQed.\n\n\nLemma mem_inj_id_value_inject_transport : forall A B (ge : Genv.t A B) m1 m2,\n    forall b ofs head vals l',\n    forall (P : Prop),\n    Mem.mem_inj inject_id m1 m2 ->\n    head <> Vundef ->\n    (forall cvs,\n        Forall2 (value_inject ge m1) vals cvs ->\n        Forall2 (value_inject ge m2) vals cvs) ->\n    (Mem.loadv Mint32 m2 (Vptr b ofs) = Some head ->\n        load_all (arg_addrs b (Int.add ofs (Int.repr 4)) vals) m2 = Some l' ->\n        (forall a b, In (a, b) l' -> value_inject ge m2 a b) ->\n        P) ->\n    (Mem.loadv Mint32 m1 (Vptr b ofs) = Some head ->\n        load_all (arg_addrs b (Int.add ofs (Int.repr 4)) vals) m1 = Some l' ->\n        (forall a b, In (a, b) l' -> value_inject ge m1 a b) ->\n        P).\nintros0 Hmi Hhdef Hvis HP Hhead Hla Hvi.\n\nfwd eapply load_all_mem_inj_id as HH; eauto.\n  destruct HH as (lv' & ? & ?).\n\nfwd eapply load_all_arg_addrs_zip with (l := l') as HH; eauto.\n  destruct HH as (cvs1 & ? & ?). subst l'.\nfwd eapply load_all_arg_addrs_zip with (l := lv') as HH; eauto.\n  destruct HH as (cvs2 & ? & ?). subst lv'.\n\nfwd eapply zip_Forall2_eq_l with (xs := vals) (ys := cvs1); eauto.\nfwd eapply zip_Forall2_eq_l with (xs := vals) (ys := cvs2); eauto.\nfwd eapply zip_Forall2_eq_r with (xs := vals) (ys := cvs1); eauto.\nfwd eapply zip_Forall2_eq_r with (xs := vals) (ys := cvs2); eauto.\nremember (zip vals cvs1) as ps1.\nremember (zip vals cvs2) as ps2.\n\nassert (Forall (fun p => value_inject ge m1 (fst p) (snd p)) ps1).\n  { rewrite Forall_forall. destruct x. eauto. }\n\nassert (cvs1 = cvs2).\n  { eapply Forall2_eq.\n    list_magic_on (vals, (cvs1, (cvs2, (ps1, (ps2, tt))))).\n    subst. symmetry.\n    eapply lessdef_def_eq; eauto.\n    eapply value_inject_defined; eauto. }\n  subst cvs2.\nreplace ps2 with ps1 in * by congruence. clear dependent ps2.\n\neapply HP; eauto.\n\n- unfold Mem.loadv in *.\n  fwd eapply Mem.load_inj as HH; eauto. { reflexivity. } destruct HH as (v' & ? & ?).\n    rewrite Z.add_0_r in *.\n  replace head with v'; cycle 1.\n    { eapply lessdef_def_eq; eauto. rewrite <- val_inject_id. auto. }\n  auto.\n\n- cut (Forall (fun p => value_inject ge m2 (fst p) (snd p)) ps1).\n    { intros HH. intros. rewrite Forall_forall in HH.\n      on _, eapply_lem HH. simpl in *. assumption. }\n  specialize (Hvis cvs1). spec_assert Hvis.\n    { list_magic_on (vals, (cvs1, (ps1, tt))). subst. auto. }\n  list_magic_on (vals, (cvs1, (ps1, tt))).\n  subst. auto.\nQed.\n\nLemma mem_inj_id_value_inject :\n  forall m1 m2,\n    Mem.mem_inj inject_id m1 m2 ->\n    forall {A B} (ge : Genv.t A B) hv cv,\n      value_inject ge m1 hv cv ->\n      value_inject ge m2 hv cv.\nintros0 Hmi. intros ? ? ge.\ninduction hv using value_rect_mut with\n    (Pl := fun hvs => forall cvs,\n        Forall2 (value_inject ge m1) hvs cvs ->\n        Forall2 (value_inject ge m2) hvs cvs);\nintros0 Hvi; simpl in *.\n\n- invc Hvi.\n  eapply mem_inj_id_value_inject_transport; eauto.\n    { discriminate. }\n  clear H1 H2 H4. intros.\n  econstructor; eauto.\n\n- invc Hvi.\n  eapply mem_inj_id_value_inject_transport; eauto.\n    { discriminate. }\n  clear H1 H4 H6. intros.\n  econstructor; eauto.\n\n- invc Hvi.\n  fix_existT. subst.\n  econstructor; eauto.\n  eapply opaque_type_value_val_inject; eauto.\n  + eapply val_inject_id, Val.lessdef_refl.\n  + unfold MemInjProps.same_offsets. intros0 HH. invc HH. reflexivity.\n\n- invc Hvi. constructor.\n\n- invc Hvi. econstructor; eauto.\nQed.\n\n\nLemma alloc_store :\n  forall m lo hi m' b,\n    Mem.alloc m lo hi = (m',b) ->\n    forall v c,\n      hi - lo > size_chunk c ->\n      (align_chunk c | lo) ->\n      { m'' : mem | Mem.store c m' b lo v = Some m''}.\nProof.\n  intros.\n  app Mem.valid_access_alloc_same Mem.alloc; try omega.\n  app Mem.valid_access_implies Mem.valid_access.\n  2: instantiate (1 := Writable); econstructor; eauto.\n  eapply Mem.valid_access_store; eauto.\nQed.\n\n\nDefinition writable (m : mem) (b : block) (lo hi : Z) : Prop :=\n  forall ofs k,\n    lo <= ofs < hi ->\n    Mem.perm m b ofs k Freeable.\n\nLemma alloc_writable :\n  forall m lo hi m' b,\n    Mem.alloc m lo hi = (m',b) ->\n    writable m' b lo hi.\nProof.\n  intros.\n  unfold writable.\n  intros.\n  eapply Mem.perm_alloc_2; eauto.\nQed.  \n\nLemma mem_locked_store_nextblock :\n  forall m m',\n    mem_locked m m' ->\n    forall c ofs v m'',\n      Mem.store c m' (Mem.nextblock m) ofs v = Some m'' ->\n      mem_locked m m''.\nProof.\n  intros.\n  unfold mem_locked in *.\n  unfold mem_locked' in *.\n  intros.\n  app Mem.load_store_other Mem.store.\n  rewrite H0.\n  eapply H; eauto.\n  left.\n  eapply pos_lt_neq; eauto.\nQed.\n\nLemma writable_storeable :\n  forall m b lo hi,\n    writable m b lo hi ->\n    forall c v ofs,\n      lo <= ofs < hi ->\n      (align_chunk c | ofs) ->\n      hi >= ofs + size_chunk c ->\n      {m' : mem | Mem.store c m b ofs v = Some m' /\\ writable m' b lo hi }.\nProof.\n  intros.\n  assert (Mem.valid_access m c b ofs Writable).\n  unfold Mem.valid_access. split; auto.\n  unfold Mem.range_perm. intros.\n  unfold writable in H.\n  eapply Mem.perm_implies; try apply H; eauto; try solve [econstructor].\n  omega.\n  app Mem.valid_access_store Mem.valid_access.\n  destruct H3.\n  exists x. split. apply e.\n  unfold writable. intros.\n  eapply Mem.perm_store_1; eauto.\nQed.\n\nLemma writable_storevable :\n  forall m b lo hi,\n    writable m b lo hi ->\n    forall c v ofs,\n      lo <= Int.unsigned ofs < hi ->\n      (align_chunk c | Int.unsigned ofs) ->\n      hi >= (Int.unsigned ofs) + size_chunk c ->\n      {m' : mem | Mem.storev c m (Vptr b ofs) v = Some m' /\\ writable m' b lo hi }.\nProof.\n  intros.\n  app writable_storeable writable.\nQed.\n\nLemma mem_locked_load :\n  forall m m',\n    mem_locked m m' ->\n    forall c b ofs v,\n      Mem.load c m b ofs = Some v ->\n      Mem.load c m' b ofs = Some v.\nProof.\n  intros.\n  unfold mem_locked in *.\n  unfold mem_locked' in *.\n  eapply H; eauto.\n  eapply load_lt_nextblock; eauto.\nQed.\n\n\n\nFixpoint store_multi chunk m b ofs vs : option mem :=\n    match vs with\n    | [] => Some m\n    | v :: vs =>\n            match Mem.store chunk m b ofs v with\n            | Some m' => store_multi chunk m' b (ofs + size_chunk chunk) vs\n            | None => None\n            end\n    end.\n\nFixpoint load_multi chunk m b ofs n : option (list val) :=\n    match n with\n    | O => Some []\n    | S n =>\n            match Mem.load chunk m b ofs with\n            | Some v =>\n                    match load_multi chunk m b (ofs + size_chunk chunk) n with\n                    | Some vs => Some (v :: vs)\n                    | None => None\n                    end\n            | None => None\n            end\n    end.\n\nLemma shrink_range_perm : forall m b lo1 hi1 lo2 hi2 k p,\n        Mem.range_perm m b lo1 hi1 k p ->\n        lo1 <= lo2 ->\n        hi2 <= hi1 ->\n        Mem.range_perm m b lo2 hi2 k p.\nintros0 Hrp Hlo Hhi. unfold Mem.range_perm in *. intros.\neapply Hrp. lia.\nQed.\n\nLemma perm_store : forall chunk m1 b ofs v m2,\n    Mem.store chunk m1 b ofs v = Some m2 ->\n    forall b' ofs' k p,\n    Mem.perm m1 b' ofs' k p <-> Mem.perm m2 b' ofs' k p.\nintros. split.\n- eapply Mem.perm_store_1; eauto.\n- eapply Mem.perm_store_2; eauto.\nQed.\n\nLemma range_perm_store : forall chunk m1 b ofs v m2,\n    Mem.store chunk m1 b ofs v = Some m2 ->\n    forall b' lo hi k p,\n    Mem.range_perm m1 b' lo hi k p <-> Mem.range_perm m2 b' lo hi k p.\nintros. unfold Mem.range_perm. split; intros.\n- rewrite <- perm_store; eauto.\n- rewrite -> perm_store; eauto.\nQed.\n\nLemma load_multi_spec : forall chunk m b ofs n vs i v,\n    load_multi chunk m b ofs n = Some vs ->\n    nth_error vs i = Some v ->\n    Mem.load chunk m b (ofs + size_chunk chunk * Z.of_nat i) = Some v.\nfirst_induction n; intros0 Hload Hnth; simpl in Hload.\n  { inject_some. destruct i; simpl in Hnth. all: discriminate. }\n\ndo 2 (break_match; try discriminate). inject_some.\ndestruct i.\n- simpl in Hnth. inject_some.\n  rewrite Nat2Z.inj_0. replace (ofs + _) with ofs by ring. auto.\n- simpl in Hnth.\n  rewrite Nat2Z.inj_succ. unfold Z.succ.\n  replace (_ + _) with ((ofs + size_chunk chunk) + (size_chunk chunk * Z.of_nat i)) by ring.\n  eapply IHn; eauto.\nQed.\n\nLemma valid_access_store_multi : forall chunk m b ofs vs,\n    Mem.range_perm m b ofs (ofs + size_chunk chunk * Zlength vs) Cur Writable ->\n    (align_chunk chunk | ofs) ->\n    { m' : mem | store_multi chunk m b ofs vs = Some m' }.\nfirst_induction vs; intros; simpl in *.\n  { eauto. }\n\nrename a into v.\n\nfwd eapply Mem.valid_access_store with (m1 := m) (v := v) as HH.\n  { econstructor; eauto. eapply shrink_range_perm; eauto.\n    - lia.\n    - rewrite Zlength_cons. rewrite <- Zmult_succ_r_reverse.\n      assert (0 <= size_chunk chunk * Zlength vs).\n        { eapply Z.mul_nonneg_nonneg.\n          - destruct chunk; simpl; lia.\n          - rewrite Zlength_correct. eapply Zle_0_nat. }\n      lia.\n  }\n  destruct HH as [m' ?].\n  rewrite range_perm_store in * by eauto.\n\nfwd eapply IHvs with (m := m') (ofs := ofs + size_chunk chunk)\n    (chunk := chunk) as HH; eauto.\n  { eapply shrink_range_perm; eauto.\n    - assert (0 <= size_chunk chunk) by (destruct chunk; simpl; lia).\n      lia.\n    - rewrite Zlength_cons. rewrite <- Zmult_succ_r_reverse.\n      assert (0 <= size_chunk chunk) by (destruct chunk; simpl; lia).\n      lia.\n  }\n  { eapply Z.divide_add_r; eauto.\n    destruct chunk; simpl; eapply Zmod_divide; eauto. all: lia. }\n  destruct HH as [m'' ?].\n\nexists m''.\non _, fun H => rewrite H. eauto.\nQed.\n\nLemma Zlength_nonneg : forall A (xs : list A),\n    0 <= Zlength xs.\nintros. rewrite Zlength_correct.\neapply Zle_0_nat.\nQed.\n\nLemma alloc_range_perm : forall m lo hi m' b,\n    Mem.alloc m lo hi = (m', b) ->\n    Mem.range_perm m' b lo hi Cur Freeable.\nintros0 Halloc.\nunfold Mem.range_perm. intros. break_and.\nfwd eapply Mem.valid_access_alloc_same with\n    (m1 := m) (lo := lo) (hi := hi) (m2 := m') (b := b)\n    (chunk := Mint8unsigned) (ofs := ofs) as HH; simpl in *; eauto.\n  { lia. }\n  { eapply Zmod_divide. lia. eapply Zmod_1_r. }\n  unfold Mem.valid_access, Mem.range_perm in HH.\n  destruct HH as [HH ?].\nfwd eapply (HH ofs).\n  { simpl. lia. }\n  { auto. }\nQed.\n\nLemma load_store_multi_other : forall chunk m1 b ofs vs m2,\n    store_multi chunk m1 b ofs vs = Some m2 ->\n    forall chunk' b' ofs',\n    b' <> b \\/\n        ofs' + size_chunk chunk' <= ofs \\/\n        ofs + size_chunk chunk * Zlength vs <= ofs' ->\n    Mem.load chunk' m2 b' ofs' = Mem.load chunk' m1 b' ofs'.\nfirst_induction vs; intros0 Hstore; intros0 Hnc.\n  { simpl in Hstore. inject_some. eauto. }\n\nsimpl in Hstore. break_match; try discriminate. rename m2 into m3, m into m2.\n\n\nfwd eapply Mem.load_store_other with (chunk' := chunk'); eauto.\n  { break_or; [|break_or].\n    - left. eauto.\n    - right. left. eauto.\n    - right. right.\n      rewrite Zlength_cons in *. rewrite <- Zmult_succ_r_reverse in *.\n      assert (0 <= size_chunk chunk * Zlength vs).\n        { eapply Z.mul_nonneg_nonneg.\n          - destruct chunk; simpl; lia.\n          - eapply Zlength_nonneg. }\n      lia.\n  }\n\nfwd eapply IHvs with (ofs' := ofs') (chunk' := chunk'); eauto.\n  { break_or; [|break_or].\n    - left. eauto.\n    - right. left.\n      assert (0 <= size_chunk chunk) by (destruct chunk; simpl; lia).\n      lia.\n    - right. right.\n      rewrite Zlength_cons in *. rewrite <- Zmult_succ_r_reverse in *.\n      lia.\n  }\n\ncongruence.\nQed.\n\nLemma int_modulus_big : forall x,\n    x < 256 ->\n    x < Int.modulus.\nintros. unfold Int.modulus.\nreplace 256 with (two_power_nat 8) in * by reflexivity.\nrewrite two_power_nat_equiv in *.\nfwd eapply Z.pow_le_mono_r with (a := 2) (b := 8) (c := Z.of_nat Int.wordsize).\n  { lia. }\n  { unfold Int.wordsize. simpl. lia. }\nlia.\nQed.\n\nLemma int_unsigned_big : forall x,\n    x < 256 ->\n    x <= Int.max_unsigned.\nintros.\nfwd eapply int_modulus_big with (x := x); eauto.\nunfold Int.max_unsigned. lia.\nQed.\n\nLemma store_multi_load_all_args : forall m1 b args ofs argvs m2,\n    length args = length argvs ->\n    0 <= ofs ->\n    ofs + Zlength args * 4 <= Int.max_unsigned ->\n    store_multi Mint32 m1 b ofs argvs = Some m2 ->\n    Forall (fun v => v = Val.load_result Mint32 v) argvs ->\n    load_all (arg_addrs b (Int.repr ofs) args) m2 = Some (zip args argvs).\nfirst_induction args; destruct argvs; intros0 Hlen Hofs1 Hofs2 Hstore Hi32;\n  try discriminate.\n  { reflexivity. }\n\n\nsimpl in Hstore. simpl.\nbreak_match_hyp; try discriminate. rename m2 into m3, m into m2.\n\nfwd eapply Zlength_nonneg with (xs := a :: args).\nrewrite Int.unsigned_repr by lia.\n\nerewrite load_store_multi_other; eauto; cycle 1.\n  { right. left. simpl. lia. }\nerewrite Mem.load_store_same by eauto.\n\nrewrite Int.add_unsigned.\nrewrite Int.unsigned_repr by lia.\nrewrite Int.unsigned_repr; cycle 1.\n  { split; [lia|]. eapply int_unsigned_big. lia. }\n\ninvc Hi32.\nerewrite IHargs; eauto.\n- congruence.\n- lia.\n- rewrite Zlength_cons in Hofs2. unfold Z.succ in Hofs2. lia.\nQed.\n\n\nDefinition max_arg_count := Int.max_unsigned / 4 - 1.\n\nLemma max_arg_count_ok :\n    4 + max_arg_count * 4 <= Int.max_unsigned.\nunfold max_arg_count.\nrewrite Z.mul_sub_distr_r.\nremember (_ / 4 * 4) as x.  replace (4 + (x - 1 * 4)) with x by lia.  subst x.\nremember Int.max_unsigned as x.\ncut (0 <= x - x / 4 * 4).  { intro. lia. }\nrewrite <- Zmod_eq by lia.\nfwd eapply (Z_mod_lt x 4) as HH.  { lia. } break_and. auto.\nQed.\n\nLemma max_arg_count_value_size_ok : forall x,\n    x <= max_arg_count ->\n    4 + x * 4 <= Int.max_unsigned.\nintros. \neapply Z.le_trans with (m := 4 + max_arg_count * 4).\n  2: eapply max_arg_count_ok.\neapply Zplus_le_compat_l.\neapply Zmult_le_compat_r; eauto.\nlia.\nQed.\n\nLemma max_arg_count_big : forall x,\n    x < 256 ->\n    x <= max_arg_count.\nintros.\nunfold max_arg_count.\ncut (x + 1 <= Int.max_unsigned / 4). { intro. lia. }\neapply Z.div_le_lower_bound. { lia. }\nunfold Int.max_unsigned.\ncut (4 * (x + 1) + 1 <= Int.modulus). { intro. lia. }\ncut (2048 <= Int.modulus). { intro. lia. }\nchange 2048 with (2 ^ 11). unfold Int.modulus. rewrite two_power_nat_equiv.\neapply Z.pow_le_mono_r.\n- lia.\n- unfold Int.wordsize. simpl. lia.\nQed.\n\n\nLemma value_inject_32bit : forall A B (ge : Genv.t A B) m hv cv,\n    value_inject ge m hv cv ->\n    Val.load_result Mint32 cv = cv.\nintros0 Hval. invc Hval.\n- reflexivity.\n- reflexivity.\n- eapply opaque_type_value_32bit; eauto.\nQed.\n\nLemma alloc_mem_inj_id : forall m1 lo hi m2 b,\n    Mem.alloc m1 lo hi = (m2, b) ->\n    Mem.mem_inj inject_id m1 m2.\nintros.\neapply Mem.alloc_right_inj.\n- eapply Mem.mext_inj. eapply Mem.extends_refl.\n- eassumption.\nQed.\n\nDefinition range_undef m b lo hi :=\n    forall chunk ofs v,\n        lo <= ofs < hi ->\n        Mem.load chunk m b ofs = Some v -> v = Vundef.\n\n\n(* mem_inj can be carried through a store to a previously nonexistent block *)\nLemma store_new_block_mem_inj_id : forall m1 chunk m2 b ofs v m3,\n    Mem.mem_inj inject_id m1 m2 ->\n    (Mem.mem_contents m1) !! b = ZMap.init Undef ->\n    Mem.store chunk m2 b ofs v = Some m3 ->\n    Mem.mem_inj inject_id m1 m3.\nintros.\n\neapply Mem.mk_mem_inj.\n\n- intros. unfold inject_id in *. inject_some.\n  unfold Mem.perm.\n  replace (Mem.mem_access m3) with (Mem.mem_access m2); cycle 1.\n    { symmetry. eapply Mem.store_access; eauto. }\n  eapply Mem.mi_perm; eauto.\n\n- intros. unfold inject_id in *. inject_some.\n  destruct chunk0; simpl; eapply Zmod_divide; lia || eapply Zmod_0_l.\n\n- intros. unfold inject_id in *. inject_some.\n\n  fwd eapply Mem.store_mem_contents as HH; eauto. rewrite HH. clear HH.\n  rewrite PMap.gsspec. break_match.\n\n  + (* values inside the modified block *)\n    replace (ofs0 + 0) with ofs0 by lia.\n    subst b2.\n    on (_ = ZMap.init Undef), fun H => rewrite H.\n    rewrite ZMap.gi. constructor.\n\n  + (* values inside other blocks *)\n    eapply Mem.mi_memval; eauto.\nQed.\n\nLemma store_multi_new_block_mem_inj_id : forall m1 chunk m2 b ofs vs m3,\n    Mem.mem_inj inject_id m1 m2 ->\n    (Mem.mem_contents m1) !! b = ZMap.init Undef ->\n    store_multi chunk m2 b ofs vs = Some m3 ->\n    Mem.mem_inj inject_id m1 m3.\nfirst_induction vs; intros0 Hinj Hnew Hstore; simpl in Hstore.\n  { inject_some. eauto. }\n\nbreak_match; try discriminate. rename m3 into m4, m into m3.\neapply IHvs with (m2 := m3); eauto.\neapply store_new_block_mem_inj_id; eauto.\nQed.\n\n\nLemma load_all_load_multi' : forall b ofs args m l,\n    load_all (arg_addrs b ofs args) m = Some l ->\n    0 <= Int.unsigned ofs ->\n    Int.unsigned ofs + 4 * Zlength args <= Int.max_unsigned ->\n    exists vs,\n        load_multi Mint32 m b (Int.unsigned ofs) (length args) = Some vs /\\\n        l = zip args vs.\nfirst_induction args; intros0 Hla Hmin Hmax; simpl in Hla.\n  { inject_some. simpl. eauto. }\n\ndo 2 (break_match; try discriminate). inject_some.\n\nassert (Hzlen : 4 * Zlength (a :: args) = 4 + 4 * Zlength args).\n  { rewrite Zlength_cons. unfold Z.succ. ring. }\nassert (Hi4 : Int.unsigned (Int.repr 4) = 4).\n  { eapply Int.unsigned_repr. split.\n    - lia.\n    - eapply int_unsigned_big. lia. }\nassert (Hofs4 : Int.unsigned (Int.add ofs (Int.repr 4)) = Int.unsigned ofs + 4).\n  { rewrite Int.add_unsigned.\n    rewrite Int.unsigned_repr, Hi4; [ reflexivity | split ]; rewrite Hi4.\n    - lia.\n    - rewrite Hzlen in Hmax.\n      assert (0 <= 4 * Zlength args).\n        { eapply Z.mul_nonneg_nonneg.\n          - lia.\n          - eapply Zlength_nonneg. }\n      lia. }\n\nfwd eapply IHargs as HH; eauto.  { lia. } { lia. }\n  destruct HH as (vs & ? & ?). subst.\n\neexists. simpl.\non _, fun H => rewrite H.\nrewrite <- Hofs4.  on _, fun H => rewrite H.\neauto.\nQed.\n\nLemma load_all_load_multi_4 : forall b args m l,\n    load_all (arg_addrs b (Int.repr 4) args) m = Some l ->\n    Zlength args <= max_arg_count ->\n    exists vs,\n        load_multi Mint32 m b 4 (length args) = Some vs /\\\n        l = zip args vs.\nintros.\nassert (Hi4 : Int.unsigned (Int.repr 4) = 4).\n  { eapply Int.unsigned_repr. split; [lia|]. eapply int_unsigned_big. lia. }\nrewrite <- Hi4.\neapply load_all_load_multi'; eauto; rewrite Hi4.\n- lia.\n- rewrite Z.mul_comm. eapply max_arg_count_value_size_ok. eauto.\nQed.\n\nLemma load_multi_load_all' : forall m b ofs n vs args,\n    load_multi Mint32 m b ofs n = Some vs ->\n    length args = n ->\n    0 <= ofs ->\n    ofs + 4 * Zlength args <= Int.max_unsigned ->\n    load_all (arg_addrs b (Int.repr ofs) args) m = Some (zip args vs).\nfirst_induction n; intros0 Hload Hlen Hmin Hmax; simpl in Hload.\n  { inject_some. destruct args; try discriminate. simpl. reflexivity. }\n\ndo 2 (break_match; try discriminate). inject_some. destruct args; try discriminate.\n\nassert (4 * Zlength (v0 :: args) = 4 + 4 * Zlength args).\n  { rewrite Zlength_cons. unfold Z.succ. ring. }\nassert (0 <= Zlength args) by eapply Zlength_nonneg.\n\nfwd eapply IHn; eauto.  { lia. } { lia. }\n\nsimpl.\nreplace (Int.unsigned (Int.repr ofs)) with ofs; cycle 1.\n  { symmetry. eapply Int.unsigned_repr. lia. }\nreplace (Int.add _ _) with (Int.repr (ofs + 4)); cycle 1.\n  { rewrite Int.add_unsigned. rewrite 2 Int.unsigned_repr; eauto.\n    - split; [lia|]. eapply int_unsigned_big. lia.\n    - lia. }\n\non _, fun H => rewrite H.\non _, fun H => rewrite H.\neauto.\nQed.\n\nLemma load_multi_load_all_4 : forall m b n vs args,\n    load_multi Mint32 m b 4 n = Some vs ->\n    length args = n ->\n    Zlength args <= max_arg_count ->\n    load_all (arg_addrs b (Int.repr 4) args) m = Some (zip args vs).\nintros.\neapply load_multi_load_all'; eauto.\n- lia.\n- rewrite Z.mul_comm. eapply max_arg_count_value_size_ok. eauto.\nQed.\n\nLemma load_all_inj_id : forall m1 m2 lp lv lp',\n    Mem.mem_inj inject_id m1 m2 ->\n    load_all lp m1 = Some lv ->\n    Forall2 (fun a b => Val.inject inject_id (snd a) (snd b)) lp lp' ->\n    exists lv',\n        load_all lp' m2 = Some lv' /\\\n        Forall2 (fun a b => Val.inject inject_id (snd a) (snd b)) lv lv'.\nfirst_induction lp; intros0 Hmi Hload Hvi; simpl in Hload.\n  { inject_some. on >Forall2, invc. exists []. eauto. }\n\nbreak_match. do 2 (break_match; try discriminate). inject_some. on >Forall2, invc.\nsimpl in * |-.\n\nunfold Mem.loadv in * |-. break_match; try discriminate.\non >Val.inject, invc.\ndestruct y. simpl in * |-. subst.\n\nunfold inject_id in *. inject_some.\n\nfwd eapply Mem.load_inj as HH; eauto.  destruct HH as (v2 & ? & ?).\n  rewrite Int.add_zero. rewrite Z.add_0_r in *.\n\nfwd eapply IHlp as HH; eauto.  destruct HH as (lv' & ? & ?).\n\nsimpl.\ndo 2 on _, fun H => rewrite H.\neexists. split; [ reflexivity | ].\neconstructor; eauto.\nQed.\n\nLemma inject_id_compose_self :\n    compose_meminj inject_id inject_id = inject_id.\nunfold compose_meminj, inject_id. rewrite Z.add_0_r in *. reflexivity.\nQed.\n\n\n\nSection MEM_SIM.\nLocal Open Scope positive_scope.\n\nDefinition closure_sig_higher v :=\n    match v with\n    | HigherValue.Close fname free => Some (fname, length free)\n    | _ => None\n    end.\n\nDefinition Plt_dec : forall a b, ({ a < b } + { a >= b })%positive.\nintros. destruct (a ?= b)%positive eqn:?.\n- right. rewrite Pos.compare_eq_iff in *. lia.\n- left. rewrite Pos.compare_lt_iff in *. lia.\n- right. rewrite Pos.compare_gt_iff in *. lia.\nDefined.\n\nDefinition pos_range_dec : forall min max x,\n    ({ x >= min /\\ x < max } + { x < min \\/ x >= max })%positive.\nintros.\ndestruct (Plt_dec x min), (Plt_dec x max).\n- right. left. auto.\n- right. left. auto.\n- left. split; auto.\n- right. right. auto.\nDefined.\n\n\n\nDefinition mem_sim (mi mi' : block -> option (block * Z)) m1 m1' m2 m2' :=\n    (* mi' maps new blocks on the left to new blocks on the right. *)\n    (forall b,\n        b >= Mem.nextblock m1 ->\n        b < Mem.nextblock m1' ->\n        exists b',\n            mi' b = Some (b', 0%Z) /\\\n            b' >= Mem.nextblock m2 /\\\n            b' < Mem.nextblock m2') /\\\n    (* mi' behaves like mi on old blocks on the left. *)\n    (forall b,\n        b < Mem.nextblock m1 \\/ b >= Mem.nextblock m1' ->\n        mi' b = mi b) /\\\n    (* The new mappings introduced by mi' are injective. *)\n    (forall b1 b2 b' delta1 delta2,\n        b1 >= Mem.nextblock m1 ->\n        b1 < Mem.nextblock m1' ->\n        b2 >= Mem.nextblock m1 ->\n        b2 < Mem.nextblock m1' ->\n        mi' b1 = Some (b', delta1) ->\n        mi' b2 = Some (b', delta2) ->\n        b1 = b2) /\\\n    Mem.nextblock m1 <= Mem.nextblock m1' /\\\n    Mem.nextblock m2 <= Mem.nextblock m2'.\n\nLemma mem_sim_refl : forall mi m1 m1' m2 m2',\n    Mem.nextblock m1 = Mem.nextblock m1' ->\n    Mem.nextblock m2 = Mem.nextblock m2' ->\n    mem_sim mi mi m1 m1' m2 m2'.\nintros0 Hnext1 Hnext2. repeat apply conj; intros.\n- exfalso. rewrite <- Hnext1 in *. lia.\n- reflexivity.\n- exfalso. rewrite <- Hnext1 in *. lia.\n- rewrite Hnext1. lia.\n- rewrite Hnext2. lia.\nQed.\n\n(* Compose memory simulation \"vertically\", by adding more steps. *)\nLemma mem_sim_compose : forall mi mi' mi'' m1 m1' m1'' m2 m2' m2'',\n    mem_sim mi mi' m1 m1' m2 m2' ->\n    mem_sim mi' mi'' m1' m1'' m2' m2'' ->\n    mem_sim mi mi'' m1 m1'' m2 m2''.\nunfold mem_sim. intros0 Hsim Hsim'.\ndestruct Hsim as (Hnew & Hold & Hinj & Hext1 & Hext2).\ndestruct Hsim' as (Hnew' & Hold' & Hinj' & Hext1' & Hext2').\nrepeat apply conj; intros.\n\n- assert (HH : b >= Mem.nextblock m1' \\/ b < Mem.nextblock m1'). { lia. } destruct HH.\n  + destruct (Hnew' ?? ** ** ) as (b' & ? & ? & ?).\n    exists b'. repeat apply conj; eauto. lia.\n  + destruct (Hnew ?? ** ** ) as (b' & ? & ? & ?).\n    fwd eapply Hold' as HH; eauto.\n    exists b'. repeat apply conj; eauto.\n    * congruence.\n    * lia.\n\n- eapply eq_trans.\n  + eapply Hold'. break_or; [left; lia | right; eauto].\n  + eapply Hold. break_or; [left; eauto | right; lia].\n\n- destruct (Plt_dec b1 (Mem.nextblock m1')), (Plt_dec b2 (Mem.nextblock m1')).\n\n  + rewrite Hold' in *; eauto.\n\n  + exfalso.\n    (* impossible.  b1 is old, b2 is new, so they can't both map to b'. *)\n    rewrite (Hold' b1) in *; eauto.\n    fwd eapply (Hnew b1) as HH; eauto. destruct HH as (b1' & ? & ? & ?).\n    fwd eapply (Hnew' b2) as HH; eauto. destruct HH as (b2' & ? & ? & ?).\n    assert (b1' = b2') by congruence.\n    assert (b1' < b2') by lia.\n    subst b1'. lia.\n\n  + exfalso.\n    (* impossible.  b1 is old, b2 is new, so they can't both map to b'. *)\n    rewrite (Hold' b2) in *; eauto.\n    fwd eapply (Hnew' b1) as HH; eauto. destruct HH as (b1' & ? & ? & ?).\n    fwd eapply (Hnew b2) as HH; eauto. destruct HH as (b2' & ? & ? & ?).\n    assert (b1' = b2') by congruence.\n    assert (b1' > b2') by lia.\n    subst b1'. lia.\n\n  + eauto.\n\n- lia.\n- lia.\nQed.\n\nLemma alloc_mem_sim : forall m1 m2 lo hi m1' b1 mi,\n    Mem.alloc m1 lo hi = (m1', b1) ->\n    Mem.inject mi m1 m2 ->\n    exists mi' m2' b2,\n        Mem.alloc m2 lo hi = (m2', b2) /\\\n        Mem.inject mi' m1' m2' /\\\n        mem_sim mi mi' m1 m1' m2 m2' /\\\n        mi' b1 = Some (b2, 0%Z).\nintros0 Halloc Hinj.\nfwd eapply Mem.alloc_parallel_inject with (lo2 := lo) (hi2 := hi) as HH; eauto.\n  { lia. } { lia. }\n  destruct HH as (mi' & m2' & b2 & ? & ? & ? & ? & ?).\n\nfwd eapply Mem.nextblock_alloc with (m1 := m1); eauto.\nfwd eapply Mem.alloc_result with (m1 := m1); eauto.\nfwd eapply Mem.nextblock_alloc with (m1 := m2); eauto.\nfwd eapply Mem.alloc_result with (m1 := m2); eauto.\nrewrite <- Pos.add_1_l in *.\n\nexists mi', m2', b2. repeat apply conj; eauto.\nunfold mem_sim. repeat apply conj; eauto.\n\n- intros.\n  assert (b = b1). { subst b1. lia. }\n  subst b.\n  exists b2. split; eauto. subst. split; lia.\n\n- intros.\n  assert (b <> b1). { subst b1. lia. }\n  eauto.\n\n- intros b1' b2'. intros.\n  assert (b1' = Mem.nextblock m1) by (zify; lia).\n  assert (b2' = Mem.nextblock m1) by (zify; lia).\n  congruence.\n\n- lia.\n- lia.\nQed.\n\nEnd MEM_SIM.\n\n\n\n\nLemma build_constr_inject' : forall A B (ge : Genv.t A B) m0 m1 m2 m3 m4 b tag args argvs,\n    Forall2 (value_inject ge m0) args argvs ->\n    Zlength args <= max_arg_count ->\n    Mem.alloc m0 (-4) ((1 + Zlength args) * 4) = (m1, b) ->\n    Mem.store Mint32 m1 b (-4) (Vint (Int.repr ((1 + Zlength args) * 4))) = Some m2 ->\n    Mem.store Mint32 m2 b 0 (Vint tag) = Some m3 ->\n    store_multi Mint32 m3 b 4 argvs = Some m4 ->\n    value_inject ge m4 (Constr tag args) (Vptr b Int.zero).\nintros0 Hargs Hmax Hm1 Hm2 Hm3 Hm4.\n\nassert ((Mem.mem_contents m1) !! b = ZMap.init Undef).\n  { erewrite Mem.contents_alloc; eauto.\n    erewrite <- Mem.alloc_result; eauto.\n    erewrite PMap.gss. reflexivity. }\n\nassert (Mem.mem_inj inject_id m0 m4).\n  { rewrite <- inject_id_compose_self. eapply Mem.mem_inj_compose with (m2 := m1).\n    - eapply alloc_mem_inj_id; eauto.\n    - eapply store_multi_new_block_mem_inj_id; eauto.\n      eapply store_new_block_mem_inj_id; eauto.\n      eapply store_new_block_mem_inj_id; eauto.\n      eapply Mem.mext_inj, Mem.extends_refl. }\n\neconstructor.\n\n- simpl.\n  rewrite Int.unsigned_zero.\n  erewrite load_store_multi_other; eauto; cycle 1.\n    { right. left. simpl. lia. }\n  fwd eapply Mem.load_store_same as HH; eauto.\n\n- eapply store_multi_load_all_args; eauto.\n  + eapply Forall2_length; eauto.\n  + rewrite Int.unsigned_zero, Int.unsigned_repr; cycle 1.\n      { split; [lia|]. eapply int_unsigned_big. lia. }\n    lia.\n  + rewrite Int.unsigned_zero, Int.unsigned_repr; cycle 1.\n      { split; [lia|]. eapply int_unsigned_big. lia. }\n    rewrite Z.add_0_l. eapply max_arg_count_value_size_ok. eauto.\n  + list_magic_on (args, (argvs, tt)).\n    symmetry. eapply value_inject_32bit. eassumption.\n\n- intros0 Hin.\n  eapply In_nth_error in Hin. destruct Hin as [n ?].\n  on _, eapply_lem zip_nth_error. break_and.\n  fwd eapply Forall2_nth_error; eauto.\n\n  eapply mem_inj_id_value_inject; eauto.\nQed.\n\nLemma build_constr_ok' : forall A B (ge : Genv.t A B) m0 tag args argvs,\n    Forall2 (value_inject ge m0) args argvs ->\n    Zlength args <= max_arg_count ->\n    exists m1 m2 m3 m4 b,\n        Mem.alloc m0 (-4) ((1 + Zlength args) * 4) = (m1, b) /\\\n        Mem.store Mint32 m1 b (-4) (Vint (Int.repr ((1 + Zlength args) * 4))) = Some m2 /\\\n        Mem.store Mint32 m2 b 0 (Vint tag) = Some m3 /\\\n        store_multi Mint32 m3 b 4 argvs = Some m4 /\\\n        value_inject ge m4 (Constr tag args) (Vptr b Int.zero).\n\nintros.\ndestruct (Mem.alloc m0 (-4) ((1 + Zlength args) * 4)) as [m1 b] eqn:?.\n\nfwd eapply Mem.valid_access_store with\n    (m1 := m1) (b := b) (ofs := -4) (chunk := Mint32)\n    (v := Vint (Int.repr ((1 + Zlength args) * 4)))  as HH.\n  { eapply Mem.valid_access_implies with (p1 := Freeable); cycle 1.\n      { constructor. }\n    eapply Mem.valid_access_alloc_same; eauto.\n    - lia.\n    - unfold size_chunk. rewrite Zlength_correct.\n      fwd eapply Zlength_nonneg with (xs := args). lia.\n    - simpl. eapply Zmod_divide; eauto; lia.\n  }\n  destruct HH as [m2 ?].\n\nfwd eapply Mem.valid_access_store\n    with (m1 := m2) (b := b) (ofs := 0) (chunk := Mint32) (v := Vint tag) as HH.\n  { eapply Mem.valid_access_implies with (p1 := Freeable); cycle 1.\n      { constructor. }\n    eapply Mem.store_valid_access_1; eauto.\n    eapply Mem.valid_access_alloc_same; eauto.\n    - clear. lia.\n    - unfold size_chunk. rewrite Zlength_correct.\n      fwd eapply Zlength_nonneg with (xs := args). lia.\n    - simpl. eapply Zmod_divide; eauto; lia.\n  }\n  destruct HH as [m3 ?].\n\nfwd eapply (valid_access_store_multi Mint32 m3 b 4 argvs) as HH; eauto.\n  { eapply Mem.range_perm_implies with (p1 := Freeable); [ | constructor ].\n    eapply shrink_range_perm with (lo1 := -4).\n    - erewrite <- 2 range_perm_store by eauto. eapply alloc_range_perm. eauto.\n    - clear. lia.\n    - unfold size_chunk. fwd eapply Forall2_length as HH; eauto. clear -HH.\n      replace ((1 + Zlength args) * 4) with (4 + 4 * Zlength args) by ring.\n      rewrite 2 Zlength_correct. rewrite HH. lia.\n  }\n  { simpl. clear. eapply Zmod_divide; eauto. lia. }\n  destruct HH as [m4 ?].\n\nexists m1, m2, m3, m4, b.\nsplit; eauto.\nsplit; eauto.\nsplit; eauto.\nsplit; eauto.\n\neapply build_constr_inject'; eauto.\nQed.\n\n\nDefinition val_defined_dec a : { a <> Vundef } + { ~ a <> Vundef }.\ndestruct a; left + right; congruence.\nDefined.\n\nDefinition require {A B} : { A } + { B } -> option A.\ndestruct 1; left + right; solve [eauto].\nDefined.\n\nLemma require_decidable : forall A,\n    forall (dec : { A } + { ~ A }),\n    A ->\n    exists pf, require dec = Some pf.\ndestruct dec; intro; try contradiction.\neexists. reflexivity.\nQed.\n\nLocal Open Scope option_monad.\nDefinition build_constr m tag args :=\n    let '(m, b) := Mem.alloc m (-4) ((1 + Zlength args) * 4) in\n    require (Forall_dec _ val_defined_dec args) >>= fun Hargdef =>\n    Mem.store Mint32 m b (-4) (Vint (Int.repr ((1 + Zlength args) * 4))) >>= fun m =>\n    Mem.store Mint32 m b 0 (Vint tag) >>= fun m =>\n    store_multi Mint32 m b 4 args >>= fun m =>\n    Some (m, Vptr b Int.zero).\n\nLemma build_constr_inject : forall A B (ge : Genv.t A B) m1 m2 tag args hargs v,\n    build_constr m1 tag args = Some (m2, v) ->\n    Forall2 (value_inject ge m1) hargs args ->\n    Zlength args <= max_arg_count ->\n    value_inject ge m2 (Constr tag hargs) v.\nintros0 Hbuild Hvi Hlen.\nunfold build_constr in Hbuild. break_match. break_bind_option. inject_some.\nassert (Hlen_eq : length hargs = length args) by eauto using Forall2_length.\neapply build_constr_inject'; eauto.\nall: rewrite Zlength_correct in *.\nall: rewrite Hlen_eq in *.\nall: eauto.\nQed.\n\nLemma require_bind_eq : forall (A : Prop) B (k : A -> option B) rhs,\n    forall (dec : { A } + { ~ A }),\n    A ->\n    (forall pf, k pf = rhs) ->\n    require dec >>= k = rhs.\nintros0 HA Hk.\ndestruct dec; [ | contradiction ].\nsimpl. eauto.\nQed.\n    \nLemma build_constr_ok : forall A B (ge : Genv.t A B) m1 tag args hargs,\n    Forall2 (value_inject ge m1) hargs args ->\n    Zlength args <= max_arg_count ->\n    exists v m2,\n        build_constr m1 tag args = Some (m2, v) /\\\n        value_inject ge m2 (Constr tag hargs) v.\nintros.\nassert (Hlen_eq : length hargs = length args) by eauto using Forall2_length.\nrewrite Zlength_correct, <- Hlen_eq, <- Zlength_correct in *.\nfwd eapply build_constr_ok' as HH; eauto.\nrewrite Zlength_correct, Hlen_eq, <- Zlength_correct in *.\ndestruct HH as (? & ? & ? & m' & b & ? & ? & ? & ? & ?).\n\neexists _, _.\nsplit; eauto.\nunfold build_constr.\non _, fun H => (rewrite H; clear H).\neapply require_bind_eq.\n  { list_magic_on (hargs, (args, tt)). eauto using value_inject_defined. }\n  intro.\non _, fun H => (rewrite H; clear H; simpl).\non _, fun H => (rewrite H; clear H; simpl).\non _, fun H => (rewrite H; clear H; simpl).\nreflexivity.\nQed.\n\nLemma build_constr_mem_inj_id : forall m1 tag args v m2,\n    build_constr m1 tag args = Some (m2, v) ->\n    Mem.mem_inj inject_id m1 m2.\nintros0 Hbuild.\nunfold build_constr in Hbuild. break_match. break_bind_option. inject_some.\n\nrename m2 into m4, m3 into m3, m0 into m2, m1 into m0, m into m1.\n\nassert ((Mem.mem_contents m1) !! b = ZMap.init Undef).\n  { erewrite Mem.contents_alloc; eauto.\n    erewrite <- Mem.alloc_result; eauto.\n    erewrite PMap.gss. reflexivity. }\n\nrewrite <- inject_id_compose_self. eapply Mem.mem_inj_compose with (m2 := m1).\n- eapply alloc_mem_inj_id; eauto.\n- eapply store_multi_new_block_mem_inj_id; eauto.\n  eapply store_new_block_mem_inj_id; eauto.\n  eapply store_new_block_mem_inj_id; eauto.\n  eapply Mem.mext_inj, Mem.extends_refl.\nQed.\n\nCheck store_multi.\n\nLemma store_multi_mapped_inject : forall f chunk m1 b1 ofs vs1 m1' m2 b2 vs2,\n    Mem.inject f m1 m2 ->\n    store_multi chunk m1 b1 ofs vs1 = Some m1' ->\n    f b1 = Some (b2, 0%Z) ->\n    Forall2 (Val.inject f) vs1 vs2 ->\n    exists m2',\n        store_multi chunk m2 b2 ofs vs2 = Some m2' /\\\n        Mem.inject f m1' m2'.\nfirst_induction vs1; intros0 Hmi Hstore Hf Hvi.\nall: invc Hvi.\n  { simpl in *. inject_some. exists m2. split; eauto. }\n\nsimpl in *. break_match_hyp; try discriminate.\nrename m1' into m1'', m into m1'.\nfwd eapply Mem.store_mapped_inject with (m1 := m1) as HH; eauto.\n  destruct HH as (m2' & ? & ?).\nfwd eapply IHvs1 with (m1 := m1') as HH; eauto.\n  destruct HH as (m2'' & ? & ?).\n\nexists m2''.\nrewrite Z.add_0_r in *. find_rewrite. find_rewrite. eauto.\nQed.\n\nCheck Mem.nextblock_store.\n\nLemma nextblock_store_multi : forall chunk m1 b ofs vs m2,\n    store_multi chunk m1 b ofs vs = Some m2 ->\n    Mem.nextblock m2 = Mem.nextblock m1.\nfirst_induction vs; intros0 Hstore; simpl in *.\n  { inject_some. reflexivity. }\n\nbreak_match; try discriminate.\nerewrite IHvs by eauto. eapply Mem.nextblock_store; eauto.\nQed.\n\n(*\n*)\n\n\n\nDefinition valid_ptr m v :=\n    match v with\n    | Vptr b _ => Mem.valid_block m b\n    | _ => True\n    end.\n\nLemma mem_sim_valid_val_inject : forall v1 v2 mi mi' m1 m1' m2 m2',\n    Val.inject mi v1 v2 ->\n    Mem.inject mi m1 m2 ->\n    mem_sim mi mi' m1 m1' m2 m2' ->\n    valid_ptr m1 v1 ->\n    Val.inject mi' v1 v2.\nintros0 Hvi Hmi Hsim Hvalid.\ninvc Hvi; try solve [econstructor; eauto].\nsimpl in Hvalid.\neconstructor; eauto.\ndestruct Hsim as (Hnew & Hold & Hinj & Hext1 & Hext2).\nrewrite Hold; eauto.\nQed.\n\nLemma mem_sim_valid_val_inject_list : forall vs1 vs2 mi mi' m1 m1' m2 m2',\n    Forall2 (Val.inject mi) vs1 vs2 ->\n    Mem.inject mi m1 m2 ->\n    mem_sim mi mi' m1 m1' m2 m2' ->\n    Forall (valid_ptr m1) vs1 ->\n    Forall2 (Val.inject mi') vs1 vs2.\ninduction vs1; intros0 Hvi Hmi Hsim Hvalid; invc Hvi; invc Hvalid;\n  econstructor; eauto using mem_sim_valid_val_inject.\nQed.\n\nLemma build_constr_mem_inject : forall m1 tag args1 m1' v1,\n    forall mi m2 args2,\n    build_constr m1 tag args1 = Some (m1', v1) ->\n    Mem.inject mi m1 m2 ->\n    MemInjProps.same_offsets mi ->\n    Forall2 (Val.inject mi) args1 args2 ->\n    Forall (valid_ptr m1) args1 ->\n    exists mi' m2' v2,\n        build_constr m2 tag args2 = Some (m2', v2) /\\\n        Mem.inject mi' m1' m2' /\\\n        Val.inject mi' v1 v2 /\\\n        mem_sim mi mi' m1 m1' m2 m2'.\n\nintros0 Hbuild Hmi Hoff Hvi Hvalid.\nunfold build_constr in * |-. break_match_hyp.\nrewrite Z.add_comm in *. break_bind_option. inject_some. rewrite Z.add_comm in *.\nrename m1' into m1'''', m into m1', m0 into m1'', m3 into m1'''.\nrename b into b1.\n\nfwd eapply alloc_mem_sim as HH; eauto.\n  destruct HH as (mi' & m2' & b2 & ? & ? & ? & ?).\n\nfwd eapply Mem.store_mapped_inject with (m1 := m1') as HH; eauto.\n  destruct HH as (m2'' & ? & ?).\n\nfwd eapply Mem.store_mapped_inject with (m1 := m1'') as HH; eauto.\n  destruct HH as (m2''' & ? & ?).\n\nfwd eapply store_multi_mapped_inject with (m1 := m1''') as HH; eauto.\n  { eapply mem_sim_valid_val_inject_list; eauto. }\n  destruct HH as (m2'''' & ? & ?).\n\neexists mi', m2'''', _.\nsplit; cycle 1.\n  { split; [|split]; eauto.\n    eapply mem_sim_compose; cycle 1.\n      { eapply mem_sim_refl; symmetry; eapply nextblock_store_multi; eauto. }\n    eapply mem_sim_compose; cycle 1.\n      { eapply mem_sim_refl; symmetry; eapply Mem.nextblock_store; eauto. }\n    eapply mem_sim_compose; cycle 1.\n      { eapply mem_sim_refl; symmetry; eapply Mem.nextblock_store; eauto. }\n    eauto. }\n\nassert (Hzlen : Zlength args1 = Zlength args2).\n  { rewrite 2 Zlength_correct. f_equal. eauto using Forall2_length. }\n\nunfold build_constr.\nrewrite <- Hzlen. on (Mem.alloc _ _ _ = _), fun H => rewrite H.\neapply require_bind_eq.\n  { list_magic_on (args1, (args2, tt)).\n    assert (args1_i <> Vundef).\n      { eapply Forall_nth_error with (P := fun v => v <> Vundef); eauto. }\n    on >Val.inject, invc; eauto. discriminate. }\n  intro.\nrewrite Z.add_0_r in *. on (Mem.store _ m2' _ _ _ = _), fun H => rewrite H.  simpl.\non (Mem.store _ m2'' _ _ _ = _), fun H => rewrite H. simpl.\non (store_multi _ m2''' _ _ _ = _), fun H => rewrite H. simpl.\nreflexivity.\nQed.\n\n\nDefinition cm_func f := Econst (Oaddrsymbol f Int.zero).\nDefinition cm_malloc_sig := ef_sig EF_malloc.\nDefinition cm_int i := Econst (Ointconst (Int.repr i)).\n\nSection BUILD_CONSTR_CMINOR.\n\nLocal Notation \"A + B\" := (Ebinop Oadd A B) : expr_scope.\nLocal Notation \"A <-call ( B , C , D )\" := (Scall (Some A) B C D) (at level 70).\nLocal Notation \"A <- B\" := (Sassign A B) (at level 70).\nLocal Notation \"A ;; B\" := (Sseq A B) (at level 50).\n\nDelimit Scope expr_scope with expr.\n\nFixpoint store_args_cminor base args off :=\n    match args with\n    | [] => Sskip\n    | arg :: args =>\n            Sstore Mint32 (base + cm_int off)%expr arg ;;\n            store_args_cminor base args (off + 4)\n    end.\n\nLemma valid_pointer_mem_inj_id : forall m m' b ofs,\n    Mem.valid_pointer m b ofs = true ->\n    Mem.mem_inj inject_id m m' ->\n    Mem.valid_pointer m' b ofs = true.\nintros0 Hvalid Hmem.\nunfold Mem.valid_pointer in *.\ndestruct (Mem.perm_dec m _ _ _ _); try discriminate.\nfwd eapply Mem.mi_perm; try eassumption. { reflexivity. }\ndestruct (Mem.perm_dec m' _ _ _ _); try reflexivity.\n\nexfalso.\nrewrite Z.add_0_r in *. eauto.\nQed.\n\nLemma weak_valid_pointer_mem_inj_id : forall m m' b ofs,\n    (Mem.valid_pointer m b ofs || Mem.valid_pointer m b (ofs - 1)) = true ->\n    Mem.mem_inj inject_id m m' ->\n    (Mem.valid_pointer m' b ofs || Mem.valid_pointer m' b (ofs - 1)) = true.\nintros.\nrewrite orb_true_iff in *.\nbreak_or; [left | right]; eapply valid_pointer_mem_inj_id; eauto.\nQed.\n\nLemma cmpu_bool_mem_inj_id : forall m m' cmp a b r,\n    Val.cmpu_bool (Mem.valid_pointer m) cmp a b = Some r ->\n    Mem.mem_inj inject_id m m' ->\n    Val.cmpu_bool (Mem.valid_pointer m') cmp a b = Some r.\nintros0 Hcmpu Hmem.\ndestruct a, b; try discriminate; simpl in *.\n\n- eauto.\n\n- break_match_hyp; try discriminate.\n  rewrite andb_true_iff in *. break_and. find_rewrite. simpl.\n  erewrite weak_valid_pointer_mem_inj_id; eauto.\n\n- break_match_hyp; try discriminate.\n  rewrite andb_true_iff in *. break_and. find_rewrite. simpl.\n  erewrite weak_valid_pointer_mem_inj_id; eauto.\n\n- break_if.\n\n  + break_match_hyp; try discriminate.\n    rewrite andb_true_iff in *. break_and.\n    do 2 erewrite weak_valid_pointer_mem_inj_id by eauto.\n    simpl. eauto.\n\n  + break_match_hyp; try discriminate.\n    rewrite andb_true_iff in *. break_and.\n    do 2 erewrite valid_pointer_mem_inj_id by eauto.\n    simpl. eauto.\n\nQed.\n\nLemma eval_binop_mem_inj_id : forall op a b r m m',\n    eval_binop op a b m = Some r ->\n    r <> Vundef ->\n    Mem.mem_inj inject_id m m' ->\n    eval_binop op a b m' = Some r.\ndestruct op; intros0 Heval Hdef Hmem; simpl; eauto.\n\n- (* Ocmpu *)\n  unfold eval_binop, Val.cmpu, Val.of_optbool in *.\n  inject_some. f_equal.\n  break_match_hyp; try (exfalso; congruence).\n  erewrite cmpu_bool_mem_inj_id; eauto.\nQed.\n\nLemma eval_unop_undef : forall op v v',\n    eval_unop op v = Some v' ->\n    v = Vundef ->\n    v' = Vundef.\ndestruct op; intros0 Heval Hundef; subst v; simpl in *;\n  discriminate || inject_some; eauto.\nQed.\n\nLemma eval_binop_undef1 : forall op v1 v2 m v',\n    eval_binop op v1 v2 m = Some v' ->\n    v1 = Vundef ->\n    v' = Vundef.\ndestruct op; intros0 Heval Hundef; subst v1; simpl in *;\n  discriminate || inject_some; eauto.\nQed.\n\nLemma eval_binop_undef2 : forall op v1 v2 m v',\n    eval_binop op v1 v2 m = Some v' ->\n    v2 = Vundef ->\n    v' = Vundef.\ndestruct op; intros0 Heval Hundef; subst v2; simpl in *.\nall: destruct v1; try discriminate.\nall: invc Heval; reflexivity.\nQed.\n\nLemma eval_unop_defined : forall op v v',\n    eval_unop op v = Some v' ->\n    v' <> Vundef ->\n    v <> Vundef.\nintros0 Heval Hdef. contradict Hdef. eauto using eval_unop_undef.\nQed.\n\nLemma eval_binop_defined1 : forall op v1 v2 m v',\n    eval_binop op v1 v2 m = Some v' ->\n    v' <> Vundef ->\n    v1 <> Vundef.\nintros0 Heval Hdef. contradict Hdef. eauto using eval_binop_undef1.\nQed.\n\nLemma eval_binop_defined2 : forall op v1 v2 m v',\n    eval_binop op v1 v2 m = Some v' ->\n    v' <> Vundef ->\n    v2 <> Vundef.\nintros0 Heval Hdef. contradict Hdef. eauto using eval_binop_undef2.\nQed.\n\nLemma eval_expr_mem_inj_id : forall m m' ge sp e a b,\n    eval_expr ge sp e m a b ->\n    b <> Vundef ->\n    Mem.mem_inj inject_id m m' ->\n    eval_expr ge sp e m' a b.\ninduction 1; intros0 Hdef Hmem; try solve [econstructor; eauto].\n\n- econstructor; eauto.\n  eapply IHeval_expr; eauto using eval_unop_defined.\n\n- econstructor; eauto using eval_binop_defined1, eval_binop_defined2.\n  eapply eval_binop_mem_inj_id; eauto.\n\n- destruct vaddr; try discriminate.\n  econstructor; eauto.\n  + eapply IHeval_expr; eauto. discriminate.\n  + simpl.\n    fwd eapply Mem.load_inj as HH; try eassumption. { reflexivity. }\n      destruct HH as (v' & ? & ?).\n    rewrite val_inject_id in *.\n    fwd eapply lessdef_def_eq; eauto. subst v'.\n    rewrite Z.add_0_r in *. eauto.\nQed.\n\nLemma eval_exprlist_mem_inj_id : forall m m' ge sp e es vs,\n    eval_exprlist ge sp e m es vs ->\n    Forall (fun v => v <> Vundef) vs ->\n    Mem.mem_inj inject_id m m' ->\n    eval_exprlist ge sp e m' es vs.\ninduction 1; intros0 Hdef Hmem; invc Hdef;\n  econstructor; eauto using eval_expr_mem_inj_id.\nQed.\n\nLemma store_args_cminor_effect : forall m0 ge sp e m base b ofs delta es vs m' f k,\n    store_multi Mint32 m b (ofs + delta) vs = Some m' ->\n    eval_expr ge sp e m0 base (Vptr b (Int.repr ofs)) ->\n    eval_exprlist ge sp e m0 es vs ->\n    Forall (fun v => v <> Vundef) vs ->\n    Mem.mem_inj inject_id m0 m ->\n    (Mem.mem_contents m0) !! b = ZMap.init Undef ->\n    0 <= ofs ->\n    0 <= delta ->\n    ofs + delta + 4 * Zlength es <= Int.max_unsigned ->\n    star Cminor.step ge\n        (State f (store_args_cminor base es delta) k sp e m)\n     E0 (State f Sskip k sp e m').\nfirst_induction es; intros0 Hstore Hbase Heval Hdef Hnewblock Hmem Hmin1 Hmin2 Hmax.\nall: on >eval_exprlist, invc.\n\n  { simpl in *. inject_some. eapply star_refl. }\n\nsimpl in Hstore. break_match; try discriminate.\n\nfwd eapply Zlength_nonneg with (xs := a :: es).\n\ninvc Hdef.\nfwd eapply eval_expr_mem_inj_id with (a := a); eauto.\nfwd eapply eval_expr_mem_inj_id with (a := base); eauto. { discriminate. }\nfwd eapply eval_exprlist_mem_inj_id; eauto.\n\neapply star_left with (t1 := E0) (t2 := E0); eauto.\n  { simpl. econstructor. }\neapply star_left with (t1 := E0) (t2 := E0); eauto.\n  { econstructor.\n    - econstructor; eauto.\n      + econstructor. simpl. reflexivity.\n      + simpl. reflexivity.\n    - eauto.\n    - simpl. rewrite Int.add_unsigned.\n      rewrite Int.unsigned_repr with (z := ofs) by lia.\n      rewrite Int.unsigned_repr with (z := delta) by lia.\n      rewrite Int.unsigned_repr by lia.\n      eauto.\n  }\neapply star_left with (t1 := E0) (t2 := E0); eauto.\n  { econstructor. }\n\neapply (IHes m0); try eassumption.\n- rewrite Z.add_assoc. eauto.\n- eapply store_new_block_mem_inj_id; eauto.\n- lia.\n- rewrite Zlength_cons in *. unfold Z.succ in *. rewrite Z.mul_add_distr_l in *.\n  lia.\nQed.\n\nDefinition build_constr_cminor malloc_id id tag args :=\n    let sz := 4 * (1 + Zlength args) in\n    id <-call (cm_malloc_sig, cm_func malloc_id, [cm_int sz]) ;;\n    Sstore Mint32 (Evar id) (Econst (Ointconst tag)) ;;\n    store_args_cminor (Evar id) args 4.\n\n\nFixpoint expr_no_access id e :=\n    match e with\n    | Evar id' => id <> id'\n    | Econst _ => True\n    | Eunop _ a => expr_no_access id a\n    | Ebinop _ a b => expr_no_access id a /\\ expr_no_access id b\n    | Eload _ a => expr_no_access id a\n    end.\n\n\nDefinition eval_expr_no_access : forall ge sp e m a b id v,\n    eval_expr ge sp e m a b ->\n    expr_no_access id a ->\n    eval_expr ge sp (PTree.set id v e) m a b.\ninduction 1; intros0 Hacc; econstructor; eauto.\n- rewrite PTree.gso; eauto.\n- invc Hacc. eauto.\n- invc Hacc. eauto.\nQed.\n\nDefinition eval_exprlist_no_access : forall ge sp e m a b id v,\n    eval_exprlist ge sp e m a b ->\n    Forall (expr_no_access id) a ->\n    eval_exprlist ge sp (PTree.set id v e) m a b.\ninduction 1; intros0 Hacc; invc Hacc; econstructor; eauto using eval_expr_no_access.\nQed.\n\nLemma E0_E0_E0 : E0 = Eapp E0 E0.\nreflexivity.\nQed.\n\nLemma build_constr_cminor_effect : forall malloc_id m tag args argvs v m',\n    forall ge f id k sp e fp,\n    build_constr m tag argvs = Some (m', v) ->\n    eval_exprlist ge sp e m args argvs ->\n    Forall (expr_no_access id) args ->\n    Zlength args <= max_arg_count ->\n    Genv.find_symbol ge malloc_id = Some fp ->\n    Genv.find_funct ge (Vptr fp Int.zero) = Some (External EF_malloc) ->\n    plus Cminor.step ge\n        (State f (build_constr_cminor malloc_id id tag args) k sp e m)\n     E0 (State f Sskip k sp (PTree.set id v e) m').\nintros0 Hbuild Heval Hacc Hargc Hmsym Hmfun.\n\nunfold build_constr in Hbuild. break_match. break_bind_option. inject_some.\n\nassert (Hzlen : Zlength args = Zlength argvs).\n  { do 2 rewrite Zlength_correct. f_equal.\n    clear -Heval.  induction Heval; simpl; f_equal; eauto. }\n\nassert ((Mem.mem_contents m0) !! b = ZMap.init Undef).\n  { erewrite Mem.contents_alloc; eauto.\n    erewrite <- Mem.alloc_result; eauto.\n    erewrite PMap.gss. reflexivity. }\n\neapply plus_left. 3: eapply E0_E0_E0. { econstructor. }\neapply star_left. 3: eapply E0_E0_E0. { econstructor. }\neapply star_left. 3: eapply E0_E0_E0. {\n  econstructor.\n  - econstructor. simpl. rewrite Hmsym. reflexivity.\n  - repeat econstructor.\n  - rewrite Hmfun. reflexivity.\n  - reflexivity.\n}\neapply star_left. 3: eapply E0_E0_E0. {\n  econstructor. econstructor.\n  - rewrite Int.unsigned_repr; cycle 1.\n      { replace (4 * _) with (4 + Zlength args * 4) by ring.\n        split.\n        - fwd eapply Zlength_nonneg with (xs := args). lia.\n        - eapply max_arg_count_value_size_ok. eauto. }\n    rewrite Z.mul_comm, Hzlen. eauto.\n  - rewrite Z.mul_comm, Hzlen. eauto.\n}\neapply star_left. 3: eapply E0_E0_E0. { econstructor. }\neapply star_left. 3: eapply E0_E0_E0. { econstructor. }\neapply star_left. 3: eapply E0_E0_E0. {\n  econstructor.\n  - econstructor. simpl. rewrite PTree.gss. reflexivity.\n  - econstructor. simpl. reflexivity.\n  - simpl. rewrite Int.unsigned_zero. eauto.\n}\neapply star_left. 3: eapply E0_E0_E0. { econstructor. }\n\neapply store_args_cminor_effect with (ofs := 0) (m0 := m0).\n- simpl. eauto.\n- econstructor. rewrite PTree.gss. reflexivity.\n- eapply eval_exprlist_mem_inj_id; cycle 1.\n  + eauto.\n  + eapply alloc_mem_inj_id; eauto.\n  + eapply eval_exprlist_no_access; eauto.\n- eauto.\n- eapply store_new_block_mem_inj_id; eauto.\n  eapply store_new_block_mem_inj_id; eauto.\n  eapply Mem.mext_inj, Mem.extends_refl.\n- eauto.\n- lia.\n- lia.\n- rewrite Z.add_0_l. rewrite Z.mul_comm.\n  eapply max_arg_count_value_size_ok. eauto.\nQed.\n\n\nEnd BUILD_CONSTR_CMINOR.\n\n\n\n\n\nLemma build_close_inject' : forall A B (ge : Genv.t A B) m0 m1 m2 m3 m4 b fname free freev,\n    forall bcode fp,\n    Genv.find_symbol ge fname = Some bcode ->\n    Genv.find_funct_ptr ge bcode = Some fp ->\n    Forall2 (value_inject ge m0) free freev ->\n    Zlength free <= max_arg_count ->\n    Mem.alloc m0 (-4) ((1 + Zlength free) * 4) = (m1, b) ->\n    Mem.store Mint32 m1 b (-4) (Vint (Int.repr ((1 + Zlength free) * 4))) = Some m2 ->\n    Mem.store Mint32 m2 b 0 (Vptr bcode Int.zero) = Some m3 ->\n    store_multi Mint32 m3 b 4 freev = Some m4 ->\n    value_inject ge m4 (Close fname free) (Vptr b Int.zero).\nintros0 Hsym Hfp Hfree Hmax Hm1 Hm2 Hm3 H4.\n\nassert ((Mem.mem_contents m1) !! b = ZMap.init Undef).\n  { erewrite Mem.contents_alloc; eauto.\n    erewrite <- Mem.alloc_result; eauto.\n    erewrite PMap.gss. reflexivity. }\n\nassert (Mem.mem_inj inject_id m0 m4).\n  { rewrite <- inject_id_compose_self. eapply Mem.mem_inj_compose with (m2 := m1).\n    - eapply alloc_mem_inj_id; eauto.\n    - eapply store_multi_new_block_mem_inj_id; eauto.\n      eapply store_new_block_mem_inj_id; eauto.\n      eapply store_new_block_mem_inj_id; eauto.\n      eapply Mem.mext_inj, Mem.extends_refl. }\n\neconstructor.\n\n- simpl.\n  rewrite Int.unsigned_zero.\n  erewrite load_store_multi_other; eauto; cycle 1.\n    { right. left. simpl. lia. }\n  fwd eapply Mem.load_store_same as HH; eauto.\n\n- eauto.\n- eauto.\n\n- eapply store_multi_load_all_args; eauto.\n  + eapply Forall2_length; eauto.\n  + rewrite Int.unsigned_zero, Int.unsigned_repr; cycle 1.\n      { split; [lia|]. eapply int_unsigned_big. lia. }\n    lia.\n  + rewrite Int.unsigned_zero, Int.unsigned_repr; cycle 1.\n      { split; [lia|]. eapply int_unsigned_big. lia. }\n    rewrite Z.add_0_l. eapply max_arg_count_value_size_ok. eauto.\n  + list_magic_on (free, (freev, tt)).\n    symmetry. eapply value_inject_32bit. eassumption.\n\n- intros0 Hin.\n  eapply In_nth_error in Hin. destruct Hin as [n ?].\n  on _, eapply_lem zip_nth_error. break_and.\n  fwd eapply Forall2_nth_error; eauto.\n\n  eapply mem_inj_id_value_inject; eauto.\nQed.\n\nLemma build_close_ok' : forall A B (ge : Genv.t A B) m0 fname free freev,\n    forall bcode fp,\n    Genv.find_symbol ge fname = Some bcode ->\n    Genv.find_funct_ptr ge bcode = Some fp ->\n    Forall2 (value_inject ge m0) free freev ->\n    Zlength free <= max_arg_count ->\n    exists m1 m2 m3 m4 b,\n        Mem.alloc m0 (-4) ((1 + Zlength free) * 4) = (m1, b) /\\\n        Mem.store Mint32 m1 b (-4) (Vint (Int.repr ((1 + Zlength free) * 4))) = Some m2 /\\\n        Mem.store Mint32 m2 b 0 (Vptr bcode Int.zero) = Some m3 /\\\n        store_multi Mint32 m3 b 4 freev = Some m4 /\\\n        value_inject ge m4 (Close fname free) (Vptr b Int.zero).\n\nintros.\ndestruct (Mem.alloc m0 (-4) ((1 + Zlength free) * 4)) as [m1 b] eqn:?.\n\nfwd eapply Mem.valid_access_store with\n    (m1 := m1) (b := b) (ofs := -4) (chunk := Mint32)\n    (v := Vint (Int.repr ((1 + Zlength free) * 4))) as HH.\n  { eapply Mem.valid_access_implies with (p1 := Freeable); cycle 1.\n      { constructor. }\n    eapply Mem.valid_access_alloc_same; eauto.\n    - lia.\n    - unfold size_chunk. rewrite Zlength_correct.\n      fwd eapply Zlength_nonneg with (xs := free). lia.\n    - simpl. eapply Zmod_divide; eauto; lia.\n  }\n  destruct HH as [m2 ?].\n\nfwd eapply Mem.valid_access_store with\n    (m1 := m2) (b := b) (ofs := 0) (chunk := Mint32) (v := Vptr bcode Int.zero) as HH.\n  { eapply Mem.valid_access_implies with (p1 := Freeable); cycle 1.\n      { constructor. }\n    eapply Mem.store_valid_access_1; eauto.\n    eapply Mem.valid_access_alloc_same; eauto.\n    - clear. lia.\n    - unfold size_chunk. rewrite Zlength_correct.\n      fwd eapply Zlength_nonneg with (xs := free). lia.\n    - simpl. eapply Zmod_divide; eauto; lia.\n  }\n  destruct HH as [m3 ?].\n\nfwd eapply (valid_access_store_multi Mint32 m3 b 4 freev) as HH; eauto.\n  { eapply Mem.range_perm_implies with (p1 := Freeable); [ | constructor ].\n    eapply shrink_range_perm with (lo1 := -4).\n    - erewrite <- 2 range_perm_store by eauto. eapply alloc_range_perm. eauto.\n    - clear. lia.\n    - unfold size_chunk. fwd eapply Forall2_length as HH; eauto. clear -HH.\n      replace ((1 + Zlength free) * 4) with (4 + 4 * Zlength free) by ring.\n      rewrite 2 Zlength_correct. rewrite HH. lia.\n  }\n  { simpl. clear. eapply Zmod_divide; eauto. lia. }\n  destruct HH as [m4 ?].\n\nexists m1, m2, m3, m4, b.\nsplit; eauto.\nsplit; eauto.\nsplit; eauto.\nsplit; eauto.\n\neapply build_close_inject'; eauto.\nQed.\n\n\nLocal Open Scope option_monad.\nDefinition build_close {A B} (ge : Genv.t A B) m fname free :=\n    Genv.find_symbol ge fname >>= fun bcode =>\n    Genv.find_funct_ptr ge bcode >>= fun fp =>\n    let '(m, b) := Mem.alloc m (-4) ((1 + Zlength free) * 4) in\n    Mem.store Mint32 m b (-4) (Vint (Int.repr ((1 + Zlength free) * 4))) >>= fun m =>\n    Mem.store Mint32 m b 0 (Vptr bcode Int.zero) >>= fun m =>\n    store_multi Mint32 m b 4 free >>= fun m =>\n    Some (m, Vptr b Int.zero).\n\nLemma build_close_inject : forall A B (ge : Genv.t A B) m1 m2 fname free hfree v,\n    build_close ge m1 fname free = Some (m2, v) ->\n    Forall2 (value_inject ge m1) hfree free ->\n    Zlength free <= max_arg_count ->\n    value_inject ge m2 (Close fname hfree) v.\nintros0 Hbuild Hvi Hlen.\nunfold build_close in Hbuild. break_match. break_bind_option. inject_some.\nassert (Hlen_eq : length hfree = length free) by eauto using Forall2_length.\neapply build_close_inject'; eauto.\nall: rewrite Zlength_correct in *.\nall: rewrite Hlen_eq in *.\nall: eauto.\nQed.\n\nLemma build_close_ok : forall A B (ge : Genv.t A B) m1 fname free hfree,\n    forall bcode fp,\n    Genv.find_symbol ge fname = Some bcode ->\n    Genv.find_funct_ptr ge bcode = Some fp ->\n    Forall2 (value_inject ge m1) hfree free ->\n    Zlength free <= max_arg_count ->\n    exists v m2,\n        build_close ge m1 fname free = Some (m2, v) /\\\n        value_inject ge m2 (Close fname hfree) v.\nintros.\nassert (Hlen_eq : length hfree = length free) by eauto using Forall2_length.\nrewrite Zlength_correct, <- Hlen_eq, <- Zlength_correct in *.\nfwd eapply build_close_ok' as HH; eauto.\nrewrite Zlength_correct, Hlen_eq, <- Zlength_correct in *.\ndestruct HH as (? & ? & ? & m' & b & ? & ? & ? & ? & ?).\n\neexists _, _.\nsplit; eauto.\nunfold build_close.\non _, fun H => (rewrite H; clear H).\non _, fun H => (rewrite H; clear H; simpl).\non _, fun H => (rewrite H; clear H; simpl).\non _, fun H => (rewrite H; clear H; simpl).\non _, fun H => (rewrite H; clear H; simpl).\non _, fun H => (rewrite H; clear H; simpl).\nreflexivity.\nQed.\n\nLemma build_close_mem_inj_id : forall A B (ge : Genv.t A B) m1 fname free v m2,\n    build_close ge m1 fname free = Some (m2, v) ->\n    Mem.mem_inj inject_id m1 m2.\nintros0 Hbuild.\nunfold build_close in Hbuild. break_match. break_bind_option. inject_some.\n\nrename m2 into m4, m3 into m3, m0 into m2, m1 into m0, m into m1.\n\nassert ((Mem.mem_contents m1) !! b = ZMap.init Undef).\n  { erewrite Mem.contents_alloc; eauto.\n    erewrite <- Mem.alloc_result; eauto.\n    erewrite PMap.gss. reflexivity. }\n\nrewrite <- inject_id_compose_self. eapply Mem.mem_inj_compose with (m2 := m1).\n- eapply alloc_mem_inj_id; eauto.\n- eapply store_multi_new_block_mem_inj_id; eauto.\n  eapply store_new_block_mem_inj_id; eauto.\n  eapply store_new_block_mem_inj_id; eauto.\n  eapply Mem.mext_inj, Mem.extends_refl.\nQed.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/MemFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20842728115526346}}
{"text": "Require Import EquivDec.\nRequire Import List.\n\nRequire Import Utils.\nRequire Import Lattices.\n\nRequire Import Instr.\nRequire Import AbstractCommon.\nRequire Import Memory.\nRequire Import AbstractMachine.\nRequire Import QuasiAbstractMachine.\nRequire Import Refinement.\n\nOpen Scope list_scope.\n\nSet Implicit Arguments.\n\nSection Ref.\n\nContext {T: Type}\n        {Latt: JoinSemiLattice T}.\n\nDefinition match_tags (t1 t2 : T) (m2 : memory T unit) : Prop :=\n  t1 = t2.\nHint Unfold match_tags : core.\n\nDefinition valid_update (m2 m2' : memory T unit) : Prop := True.\nHint Unfold valid_update : core.\n\nLemma valid_update_match_tags :\n  forall t1 t2 m2 m2',\n    match_tags t1 t2 m2 ->\n    valid_update m2 m2' ->\n    match_tags t1 t2 m2'.\nProof. eauto. Qed.\n\nNotation meminj := (meminj T unit).\nNotation Meminj := (Meminj T T T unit match_tags).\nNotation match_atoms := (match_atoms T T T unit match_tags).\nNotation match_vals := (match_vals T unit).\nNotation match_ptrs := (match_ptrs T unit).\nNotation update_meminj := (update_meminj T unit).\n\nHint Resolve match_vals_eq : core.\nHint Constructors Memory.match_atoms : core.\nHint Constructors Memory.match_vals : core.\nHint Constructors Memory.match_ptrs : core.\nHint Resolve update_meminj_eq : core.\n\nInductive match_stk_elmt (mi : meminj) : StkElmt T T -> StkElmt T unit -> memory T unit -> Prop :=\n| mse_data : forall a1 a2 m2\n                    (ATOMS : match_atoms mi a1 a2 m2),\n               match_stk_elmt mi (AData a1) (AData a2) m2\n| mse_ret : forall pc b m2, match_stk_elmt mi (ARet pc b) (ARet pc b) m2.\nHint Constructors match_stk_elmt : core.\n\nDefinition match_stacks (mi : meminj) : list (StkElmt T T) -> list (StkElmt T unit) -> memory T unit -> Prop :=\n  fun s1 s2 m2 => Forall2 (fun se1 se2 => match_stk_elmt mi se1 se2 m2) s1 s2.\nHint Unfold match_stacks : core.\n\nInductive match_states : @a_state T -> @qa_state T -> Prop :=\n| aqa_intro : forall mi m1 m2 p stk1 stk2 pc\n                     (INJ : Meminj m1 m2 mi)\n                     (STK : match_stacks mi stk1 stk2 m2),\n                match_states (AState m1 p stk1 pc) (AState m2 p stk2 pc).\nHint Constructors match_states : core.\n\nLemma alloc_match_stacks :\n  forall size\n         lab a1 m1 b1 m1'\n         a2 m2 b2 m2'\n         mi stk1 stk2\n         (STK : match_stacks mi stk1 stk2 m2)\n         (ALLOC1 : a_alloc size lab a1 m1 = Some (b1, m1'))\n         (ALLOC2 : qa_alloc size a2 m2 = Some (b2, m2'))\n         (INJ : Meminj m1 m2 mi),\n    match_stacks (update_meminj mi b2 b1) stk1 stk2 m2'.\nProof.\n  intros.\n  induction STK; constructor; trivial.\n  inv H; constructor.\n  inv ATOMS. constructor; auto.\n  inv VALS; try inv PTRS; do 2 constructor.\n  rewrite update_meminj_neq; auto.\n  eapply mi_valid in BLOCK; eauto.\n  destruct BLOCK as [? [? [? [? ?]]]].\n  unfold qa_alloc, alloc in ALLOC2.\n  destruct (zreplicate size a2); inv ALLOC2.\n  eapply Mem.alloc_get_fresh in H3; eauto.\n  congruence.\nQed.\n\nLemma match_stacks_app :\n  forall mi stk1 args2 stk2' m2\n         (STKS : match_stacks mi stk1 (args2 ++ stk2') m2),\n    exists args1 stk1',\n      stk1 = args1 ++ stk1' /\\\n      match_stacks mi args1 args2 m2 /\\\n      match_stacks mi stk1' stk2' m2.\nProof.\n  intros.\n  gdep stk1.\n  induction args2 as [|arg args2 IH]; intros stk1 STKS.\n  - exists nil. exists stk1. eauto.\n  - simpl in STKS.\n    inv STKS.\n    exploit IH; eauto.\n    intros [? [? [? [? ?]]]]. subst.\n    repeat eexists; eauto.\n    trivial.\nQed.\n\nLemma match_stacks_length :\n  forall mi stk1 stk2 m2\n         (STKS : match_stacks mi stk1 stk2 m2),\n    length stk1 = length stk2.\nProof. induction 1; simpl; eauto. Qed.\nHint Resolve match_stacks_length : core.\n\nLemma match_stacks_all_data :\n  forall mi stk1 stk2 m2\n         (STKS : match_stacks mi stk1 stk2 m2)\n         (DATA : forall se2, In se2 stk2 -> exists a2, se2 = AData a2),\n    forall se1, In se1 stk1 -> exists a1, se1 = AData a1.\nProof.\n  induction 1 as [|se1 se2 stk1 stk2 STKELMT STKS IHSTKS]; intros; inv H.\n  - inv STKELMT; eauto.\n    specialize (DATA (ARet pc b)).\n    destruct DATA; simpl; eauto.\n    congruence.\n  - apply IHSTKS; simpl in *; auto.\nQed.\nHint Resolve match_stacks_all_data : core.\n\nLemma match_stacks_app_2 :\n  forall mi stk11 stk12 stk21 stk22 m2\n         (STKS1 : match_stacks mi stk11 stk21 m2)\n         (STKS2 : match_stacks mi stk12 stk22 m2),\n    match_stacks mi (stk11 ++ stk12) (stk21 ++ stk22) m2.\nProof. intros. eauto using Forall2_app. Qed.\nHint Resolve match_stacks_app_2 : core.\n\nHint Constructors pop_to_return : core.\n\nLemma match_stacks_pop_to_return :\n  forall mi stk1 stk2 stk2' pc b m2\n         (STKS : match_stacks mi stk1 stk2 m2)\n         (POP : pop_to_return stk2 (ARet pc b :: stk2')),\n    exists stk1',\n      pop_to_return stk1 (ARet pc b :: stk1') /\\\n      match_stacks mi stk1' stk2' m2.\nProof.\n  intros.\n  gdep stk2.\n  induction stk1 as [|se1 stk1 IH]; intros;\n  inv POP; inv STKS;\n  match goal with\n    | H : match_stk_elmt _ _ _ _ |- _ =>\n      inv H; eauto\n  end.\n  exploit IH; eauto.\n  intros [? [? ?]].\n  eauto.\nQed.\n\nLemma match_stacks_index_list :\n  forall mi n s1 s2 x2 m2\n         (IDX : index_list n s2 = Some x2)\n         (STKS : match_stacks mi s1 s2 m2),\n    exists x1,\n      index_list n s1 = Some x1 /\\\n      match_stk_elmt mi x1 x2 m2.\nProof.\n  induction n as [|n IH]; intros; inv STKS; simpl in *; allinv; eauto.\nQed.\n\nLemma match_stacks_update_list :\n  forall mi n se1 s1 se2 s2 s2' m2\n         (STKS : match_stacks mi s1 s2 m2)\n         (STKELMTS : match_stk_elmt mi se1 se2 m2)\n         (UPD : update_list n se2 s2 = Some s2'),\n    exists s1',\n      update_list n se1 s1 = Some s1' /\\\n      match_stacks mi s1' s2' m2.\nProof.\n  intros mi n.\n  induction n as [|n IH]; intros; inv STKS; simpl in *; try congruence;\n  allinv; eauto.\n  match goal with\n    | H : (match ?UP with _ => _ end) = Some _ |- _ =>\n      destruct UP as [s2''|] eqn:?; try congruence\n  end.\n  allinv.\n  exploit (@IH se1); eauto.\n  intros [s1'' [EQ ?]].\n  rewrite EQ.\n  eauto.\nQed.\n\nLemma match_stacks_swap :\n  forall mi n s1 s2 s2' m2\n         (SWAP : swap n s2 = Some s2')\n         (STKS : match_stacks mi s1 s2 m2),\n    exists s1',\n      swap n s1 = Some s1' /\\\n      match_stacks mi s1' s2' m2.\nProof.\n  unfold swap.\n  intros.\n  destruct s2 as [|se2 s2]; try congruence.\n  destruct (index_list n (se2 :: s2)) as [se2'|] eqn:IDX2; try congruence.\n  exploit match_stacks_index_list; eauto.\n  intros [se1' [IDX1 STKELMTS]].\n  inversion STKS as [|se1 ?]; subst.\n  rewrite IDX1.\n  eapply match_stacks_update_list; eauto.\nQed.\n\nLemma match_atoms_mem_irrel :\n  forall mi a1 a2 m2 m2'\n         (ATOMS : match_atoms mi a1 a2 m2),\n    match_atoms mi a1 a2 m2'.\nProof. intros. inv ATOMS; eauto. Qed.\nHint Resolve match_atoms_mem_irrel : mem_irrel.\n\nLemma match_stk_elmt_mem_irrel :\n  forall mi se1 se2 m2 m2'\n         (STKELMT : match_stk_elmt mi se1 se2 m2),\n    match_stk_elmt mi se1 se2 m2'.\nProof. intros. inv STKELMT; eauto with mem_irrel. Qed.\nHint Resolve match_stk_elmt_mem_irrel : mem_irrel.\n\nLemma match_stacks_mem_irrel :\n  forall mi s1 s2 m2 m2'\n         (STKS : match_stacks mi s1 s2 m2),\n    match_stacks mi s1 s2 m2'.\nProof. intros. induction STKS; eauto with mem_irrel. Qed.\nHint Resolve match_stacks_mem_irrel : mem_irrel.\n\nHint Unfold a_alloc : core.\nHint Unfold qa_alloc : core.\n\nInductive parametric_asyscall : ASysCall T -> Prop :=\n| masc_intro : forall ar f\n                      (EXT : forall mi args1 args2 m2,\n                               Forall2 (fun arg1 arg2 => match_atoms mi arg1 arg2 m2)\n                                       args1 args2 ->\n                               match_options (fun a1 a2 => match_atoms mi a1 a2 m2)\n                                             (f T args1) (f unit args2)),\n                 parametric_asyscall {| asi_arity := ar; asi_sem := f |}.\n\nInductive ForallO {T} (P : T -> Prop) : option T -> Prop :=\n| Forall_None : ForallO P None\n| Forall_Some : forall t, P t -> ForallO P (Some t).\n\nDefinition parametric_asystable (t : ASysTable T) : Prop :=\n  forall id, ForallO parametric_asyscall (t id).\n\nVariable atable : ASysTable T.\nHypothesis Hatable : parametric_asystable atable.\n\nLtac inv_match :=\n  repeat match goal with\n           | STK : Forall2 _ _ nil |- _ => inv STK\n           | STK : Forall2 _ _ (_ :: _) |- _ => inv STK\n           | STKELMT : match_stk_elmt _ _ _ _ |- _ => inv STKELMT\n           | ATOMS : match_atoms _ _ (_,_) _ |- _ => inv ATOMS\n           | VALS : match_vals _ _ (Vint _) |- _ => inv VALS\n           | VALS : match_vals _ _ (Vptr _) |- _ => inv VALS\n           | PTRS : match_ptrs _ _ _ |- _ => inv PTRS\n           | TAGS : match_tags _ _ _ |- _ => unfold match_tags in TAGS; subst\n         end.\n\nLemma match_stacks_map_adata :\n  forall mi stk1 args2 m2\n         (MATCH : match_stacks mi stk1 (map AData args2) m2),\n  exists args1,\n    stk1 = map AData args1 /\\\n    Forall2 (fun a1 a2 => match_atoms mi a1 a2 m2) args1 args2.\nProof.\n  unfold match_stacks.\n  intros.\n  gdep stk1.\n  induction args2 as [|a2 args2 IH]; simpl; intros; inv_match.\n  - eexists nil. simpl. intuition.\n  - exploit IH; eauto.\n    intros (args1 & ? & MATCH). subst.\n    eexists (a1 :: args1). eauto.\nQed.\n\nLemma a_qa_simulation :\n  forall s1 s2 e s2'\n         (STEP : step_rules fetch_rule atable s2 e s2')\n         (MATCH : match_states s1 s2),\n    exists s1',\n      a_step atable s1 e s1' /\\\n      match_states s1' s2'.\nProof.\n  intros.\n  inv STEP;\n  inv MATCH;\n  unfold match_stacks in *;\n  inv_match;\n  match goal with\n    | H : run_tmr _ _ _ _ = Some _ |- _ =>\n      unfold run_tmr, Rules.apply_rule in H; simpl in H;\n      unfold Vector.nth_order in H; simpl in H\n    | INSTR : context[SysCall ?id],\n      TABLE : atable ?id = Some _ |- _ =>\n      specialize (Hatable id);\n      rewrite TABLE in Hatable;\n      inv Hatable\n  end;\n  try match goal with\n        | MATCH : parametric_asyscall _ |- _ =>\n          inv MATCH\n      end;\n  simpl in *; unfold Vector.nth_order; simpl;\n  try congruence;\n  repeat match goal with\n           | H : context[if ?b then _ else _] |- _ =>\n             destruct b eqn:?; simpl in H\n           | H : Some _ = Some _ |- _ => inv H\n           | H : _ === _ |- _ => compute in H; subst\n           | H1 : ?x = ?a,\n             H2 : ?x = ?b |- _ =>\n             assert (a = b) by congruence; clear H2\n         end;\n  try congruence;\n\n  try match goal with\n        | H : add _ _ = Some _ |- _ =>\n          exploit add_defined; eauto; intros [? [? ?]]\n        | SUB : sub _ _ = Some _ |- _ =>\n          exploit (sub_defined T unit); eauto; intros [? [? ?]]\n        | H : qa_alloc _ _ _ = Some _ |- _ =>\n          exploit (meminj_alloc T T T unit _ _ valid_update_match_tags); eauto;\n          try solve [constructor; eauto];\n          intros [? [? [? ?]]];\n          exploit alloc_match_stacks; eauto; intro\n        | H : load _ _ = Some _ |- _ =>\n          exploit meminj_load; eauto;\n          try solve [econstructor; eauto]; intros [[? ?] [? H']];\n          inv H'; inv_match\n        | H : Forall2 _ _ (_ ++ _) |- _ =>\n          exploit match_stacks_app; eauto; intros [? [? [? [? ?]]]]; subst\n        | H : pop_to_return _ _ |- _ =>\n          exploit match_stacks_pop_to_return; eauto; intros [? [? ?]]\n      end;\n\n  (* For some weird reason, trying to merge this match with the previous one doesn't work. *)\n  try match goal with\n        | H : store _ _ _ = Some _ |- _ =>\n          exploit (meminj_store T T T unit _ _ valid_update_match_tags);\n          eauto; try solve [econstructor; eauto]; intros [? [? ?]]\n        | H : swap _ _ = Some _ |- _ =>\n          exploit match_stacks_swap; eauto; intros [? [? ?]]\n        | H1 : Forall2 _ _ _,\n          H2 : index_list _ _ = Some _ |- _ =>\n          exploit match_stacks_index_list; eauto; intros [? [? ?]]\n        | H : context[SysCall _],\n          EXT : context[match_options _ _ _] |- _ =>\n          exploit match_stacks_map_adata; eauto; intros (? & ? & ?); subst;\n          exploit EXT; eauto; intros RES;\n          match goal with\n            | RES : match_options _ ?r1 ?r2,\n              EQ : ?r2 = Some _ |- _ =>\n              rewrite EQ in RES; inv RES\n          end\n        | H : context[SizeOf] |- _ =>\n          exploit mi_valid'; eauto; intros (? & ? & FRAMES);\n          apply Forall2_length in FRAMES; rewrite <- FRAMES\n      end;\n\n  (* Always using mem_irrel causes spurious existentials to be generated *)\n  solve [eexists; split; [> once (econstructor;\n                                  simpl; solve [simpl; eauto 9 using Forall2_length\n                                               |eauto 9 with mem_irrel]) ..]].\nQed.\n\nProgram Definition abstract_quasi_abstract_sref :=\n  @strong_refinement (abstract_machine atable)\n                     (tini_quasi_abstract_machine atable)\n                     eq match_states _.\nNext Obligation.\n  exploit a_qa_simulation; eauto.\n  intros [? [? ?]].\n  repeat eexists; eauto.\n  destruct e2; constructor; auto.\nQed.\n\nDefinition emptyinj : meminj := fun _ => None.\nHint Unfold emptyinj : core.\n\nDefinition emptyinj_meminj :\n  Meminj (Mem.empty _ _) (Mem.empty _ _) emptyinj.\nProof.\n  unfold emptyinj.\n  constructor; simpl; congruence.\nQed.\nHint Resolve emptyinj_meminj : core.\n\nLemma match_init_stacks: forall m2 d1,\n match_stacks emptyinj\n              (map (fun a : PcAtom T => let (i,l) := a in AData (Vint i,l)) d1)\n              (map (fun a : PcAtom T => let (i,l) := a in AData (Vint i,l)) d1)\n              m2.\nProof.\n  induction d1 as [|[xv xl] d1 IH]; intros;\n  (simpl; constructor; auto).\nQed.\nHint Resolve match_init_stacks : core.\n\nProgram Definition abstract_quasi_abstract_ref :=\n  @refinement_from_state_refinement (abstract_machine atable)\n                                    (tini_quasi_abstract_machine atable)\n                                    abstract_quasi_abstract_sref eq\n                                    _.\n\nNext Obligation.\n  destruct i2 as [[p d] def]. simpl.\n  econstructor; eauto.\nQed.\n\nEnd Ref.\n", "meta": {"author": "micro-policies", "repo": "verified-ifc", "sha": "1ce5075b3a5580679feddb718d274d89fc7dd77f", "save_path": "github-repos/coq/micro-policies-verified-ifc", "path": "github-repos/coq/micro-policies-verified-ifc/verified-ifc-1ce5075b3a5580679feddb718d274d89fc7dd77f/extended_machines/RefinementAQA.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20842727552428544}}
{"text": "(** Events which define the API to the system. *)\nRequire Import Coq.Lists.List.\nRequire Import Coq.NArith.NArith.\nRequire Import Coq.PArith.PArith.\nRequire Import ListString.All.\n\nImport ListNotations.\nLocal Open Scope type.\n\n(** The id of a client socket. *)\nModule ClientSocketId.\n  (** A socket id is a natural number. *)\n  Inductive t : Set :=\n  | New : N -> t.\nEnd ClientSocketId.\n\n(** The kind of commands. *)\nModule Command.\n  (** The list of commands. *)\n  Inductive t : Set :=\n  | Log\n  | FileRead\n  | ServerSocketBind\n  | ClientSocketRead | ClientSocketWrite | ClientSocketClose\n  | Time.\n\n  (** The type of the parameters of a request. *)\n  Definition request (command : t) : Set :=\n    match command with\n    | Log => LString.t\n    | FileRead => LString.t\n    | ServerSocketBind => N\n    | ClientSocketRead => ClientSocketId.t\n    | ClientSocketWrite => ClientSocketId.t * LString.t\n    | ClientSocketClose => ClientSocketId.t\n    | Time => unit\n    end.\n\n  (** The type of the parameters of an answer. *)\n  Definition answer (command : t) : Set :=\n    match command with\n    | Log => bool\n    | FileRead => option LString.t\n    | ServerSocketBind => option ClientSocketId.t\n    | ClientSocketRead => option LString.t\n    | ClientSocketWrite => bool\n    | ClientSocketClose => bool\n    | Time => N\n    end.\n\n  (** Decide the equality of commands. *)\n  Definition eq_dec (command1 command2 : t) :\n    {command1 = command2} + {command1 <> command2}.\n    destruct command1; destruct command2;\n      try (left; congruence);\n      try (right; congruence).\n  Defined.\nEnd Command.\n\n(** The type of an output. *)\nModule Output.\n  (** An output is a command, a channel id and an argument. *)\n  Record t : Set := New {\n    command : Command.t;\n    id : positive;\n    argument : Command.request command }.\nEnd Output.\n\n(** The type of an input. *)\nModule Input.\n  (** An input is a command, a channel id and an argument. *)\n  Record t : Set := New {\n    command : Command.t;\n    id : positive;\n    argument : Command.answer command }.\nEnd Input.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/system/src/Events.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2084130017045155}}
{"text": "(*\n\n  Copyright 2016 Luxembourg University\n  Copyright 2017 Luxembourg University\n\n  This file is part of Velisarios.\n\n  Velisarios is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  Velisarios is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with Velisarios.  If not, see <http://www.gnu.org/licenses/>.\n\n\n  Authors: Vincent Rahli\n           Ivana Vukotic\n\n*)\n\n\nRequire Export PBFTprops3.\n\n\nSection PBFTprops4.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { pbft_context : PBFTcontext      }.\n  Context { pbft_auth    : PBFTauth         }.\n  Context { pbft_keys    : PBFTinitial_keys }.\n  Context { pbft_hash    : PBFThash         }.\n\n\n  Lemma find_pre_prepare_certificate_in_prepared_infos_some_implies :\n    forall F n P nfo,\n      find_pre_prepare_certificate_in_prepared_infos F n P = Some nfo\n      -> In nfo P\n         /\\ n = prepared_info2seq nfo\n         /\\ F nfo = true.\n  Proof.\n    induction P; introv find; simpl in *; ginv.\n    smash_pbft; apply IHP in find; tcsp.\n  Qed.\n\n  Lemma info_is_prepared_implies_prepared_info_has_correct_digest :\n    forall p, info_is_prepared p = true -> prepared_info_has_correct_digest p = true.\n  Proof.\n    introv h.\n    unfold info_is_prepared in h; smash_pbft.\n  Qed.\n  Hint Resolve info_is_prepared_implies_prepared_info_has_correct_digest : pbft.\n\n  Lemma valid_prepared_info_implies_prepared_info_has_correct_digest :\n    forall L p, valid_prepared_info L p = true -> prepared_info_has_correct_digest p = true.\n  Proof.\n    introv h.\n    unfold valid_prepared_info in h; smash_pbft.\n  Qed.\n  Hint Resolve valid_prepared_info_implies_prepared_info_has_correct_digest : pbft.\n\n  Lemma create_new_prepare_message_true_implies_correct :\n    forall (sn : SeqNum) v keys P pp d (n : SeqNum),\n      n < sn\n      -> create_new_prepare_message sn v keys P = (true,(pp,d))\n      -> correct_new_view_opre_prepare v n P pp = true.\n  Proof.\n    introv ltsn create.\n    unfold create_new_prepare_message in create; smash_pbft.\n\n    unfold correct_new_view_opre_prepare; simpl; smash_pbft;\n      allrw SeqNumLt_true; allrw SeqNumLt_false; simpl in *; try omega; GC.\n\n    unfold oexists_last_prepared; simpl.\n\n    match goal with\n    | [ |- ?x = _ ] => remember x as b; symmetry in Heqb; destruct b; auto;[]\n    end.\n    assert False; tcsp.\n    rewrite existsb_false in Heqb.\n\n    pose proof (Heqb x) as q; clear Heqb.\n\n    match goal with\n    | [ H : find_pre_prepare_certificate_in_prepared_infos _ _ _ = _ |- _ ] =>\n      apply find_pre_prepare_certificate_in_prepared_infos_some_implies in H\n    end.\n    repnd.\n    autodimp q hyp.\n    smash_pbft.\n\n    match goal with\n    | [ H : _ <> _ |- _ ] => destruct H\n    end.\n    match goal with\n    | [ H : valid_prepared_info _ _ = _ |- _ ] =>\n      apply valid_prepared_info_implies_prepared_info_has_correct_digest in H\n    end.\n    unfold prepared_info_has_correct_digest in *; smash_pbft.\n  Qed.\n\n  Lemma create_new_prepare_messages_implies_correct_OPs :\n    forall n sns v keys P OP NP,\n      (forall (x : SeqNum) ppd,\n          In x sns\n          -> create_new_prepare_message x v keys P = (true, ppd)\n          -> n < x)\n      -> create_new_prepare_messages sns v keys P = (OP, NP)\n      -> forallb\n           (correct_new_view_opre_prepare v n P)\n           (map fst OP) = true.\n  Proof.\n    induction sns; introv imp create; simpl in *; smash_pbft; dands; tcsp;\n      try (complete (eapply IHsns; eauto)).\n    repnd; simpl in *.\n\n    pose proof (imp a (x2,x1)) as q.\n    repeat (autodimp q hyp).\n\n    eapply create_new_prepare_message_true_implies_correct;[|eauto]; tcsp.\n  Qed.\n\n  Lemma view_change2view_refresh_view_change :\n    forall e st,\n      view_change2view (refresh_view_change e st) = view_change2view e.\n  Proof.\n    tcsp.\n  Qed.\n  Hint Rewrite view_change2view_refresh_view_change : pbft.\n\n  Lemma correct_view_change_implies_same_views :\n    forall v vc,\n      correct_view_change v vc = true\n      -> v = view_change2view vc.\n  Proof.\n    introv cor; unfold correct_view_change in cor; smash_pbft.\n    unfold same_views in *; smash_pbft.\n  Qed.\n\n  Lemma ViewLe_true :\n    forall v1 v2, ViewLe v1 v2 = true <-> v1 <= v2.\n  Proof.\n    introv; unfold ViewLe.\n    rewrite Nat.leb_le; tcsp.\n  Qed.\n\n  Lemma ViewLe_false :\n    forall v1 v2, ViewLe v1 v2 = false <-> v1 > v2.\n  Proof.\n    introv; unfold ViewLe.\n    rewrite leb_iff_conv. tcsp.\n  Qed.\n\n  Lemma le_max_view_left :\n    forall (a b : View), a <= max_view a b.\n  Proof.\n    introv; destruct a, b; unfold max_view; smash_pbft.\n  Qed.\n  Hint Resolve le_max_view_left : pbft.\n\n  Lemma le_max_view_right :\n    forall (a b : View), a <= max_view b a.\n  Proof.\n    introv; destruct a, b; unfold max_view; smash_pbft.\n    allrw ViewLe_false; simpl in *; omega.\n  Qed.\n  Hint Resolve le_max_view_right : pbft.\n\n  Lemma le_max_seq_num :\n    forall (a b : SeqNum), a <= max_seq_num a b.\n  Proof.\n    introv; destruct a, b; unfold max_seq_num; simpl; smash_pbft;\n      allrw SeqNumLe_true; auto; try omega.\n  Qed.\n  Hint Resolve le_max_seq_num : pbft.\n\n  Lemma le_max_seq_num_right :\n    forall (a b : SeqNum), b <= max_seq_num a b.\n  Proof.\n    introv; destruct a, b; unfold max_seq_num; simpl; smash_pbft;\n      allrw SeqNumLe_true; auto; try omega.\n  Qed.\n  Hint Resolve le_max_seq_num_right : pbft.\n\n  Lemma le_max_seq_num_op :\n    forall (a : SeqNum) b, a <= max_seq_num_op a b.\n  Proof.\n    introv; destruct b; simpl; eauto 3 with pbft.\n  Qed.\n  Hint Resolve le_max_seq_num_op : pbft.\n\n  Lemma PreparedInfos2max_seq_none_implies :\n    forall F l,\n      PreparedInfos2max_seq F l = None\n      -> forall p, In p l -> F p = false.\n  Proof.\n    induction l; introv prep i; simpl in *; smash_pbft.\n    repndors; subst; tcsp.\n  Qed.\n\n  Lemma PreparedInfos2max_seq_is_max :\n    forall pi F l n,\n      In pi l\n      -> F pi = true\n      -> PreparedInfos2max_seq F l = Some n\n      -> prepared_info2seq pi <= n.\n  Proof.\n    induction l; introv i Fpi prep; simpl in *; tcsp; repndors; subst; smash_pbft;[].\n    remember (PreparedInfos2max_seq F l) as m; symmetry in Heqm; destruct m; simpl in *; smash_pbft.\n    eapply PreparedInfos2max_seq_none_implies in Heqm;[|eauto]; pbft_simplifier.\n  Qed.\n  Hint Resolve PreparedInfos2max_seq_is_max : pbft.\n\n  Lemma implies_in_from_min_to_max :\n    forall (n x m : SeqNum),\n      n < x\n      -> x <= m\n      -> In x (from_min_to_max n m).\n  Proof.\n    introv h q.\n    unfold from_min_to_max; smash_pbft; simpl in *; try omega;[].\n    apply in_map_iff.\n    exists x; simpl; dands; autorewrite with pbft; auto.\n    apply in_seq; simpl; dands; try omega.\n  Qed.\n  Hint Resolve implies_in_from_min_to_max : pbft.\n\n  Lemma in_from_min_to_max_trans :\n    forall (x n m k : SeqNum),\n      k <= m\n      -> In x (from_min_to_max n k)\n      -> In x (from_min_to_max n m).\n  Proof.\n    introv lek i.\n    unfold from_min_to_max in *; smash_pbft.\n\n    - apply in_map_iff in i; exrepnd; subst; simpl in *.\n      allrw in_seq; repnd; try omega.\n\n    - allrw in_map_iff; exrepnd; subst; simpl in *.\n      allrw in_seq; repnd; try omega.\n      exists x0; simpl; dands; auto.\n      apply in_seq; dands; simpl; try omega.\n  Qed.\n  Hint Resolve in_from_min_to_max_trans : pbft.\n\n  Lemma view_change_cert2max_seq_preps_vc_none_implies :\n    forall F l,\n      view_change_cert2max_seq_preps_vc F l = None\n      -> forall p, In p (view_change_cert2prep l) -> F p = false.\n  Proof.\n    induction l; introv prep i; simpl in *; smash_pbft.\n    allrw in_app_iff; repndors; tcsp.\n    unfold view_change2max_seq_preps in *.\n    eapply PreparedInfos2max_seq_none_implies; eauto.\n  Qed.\n\n  Lemma implies_prepared_info2max_seq_in_from_min_to_max :\n    forall l pi (n m : SeqNum) vc F,\n      In pi (view_change_cert2prep l)\n      -> F pi = true\n      -> n < prepared_info2seq pi\n      -> view_change_cert2max_seq_preps_vc F l = Some (m, vc)\n      -> In (prepared_info2seq pi) (from_min_to_max n m).\n  Proof.\n    induction l; introv i Ft ltn eqv; simpl in *; tcsp;\n      smash_pbft; simpl in *; try omega.\n\n    - allrw in_app_iff; repndors; tcsp.\n\n      + unfold view_change2max_seq_preps in *.\n        dup i as les.\n        eapply PreparedInfos2max_seq_is_max in les;[| |eauto];auto;[].\n        eapply implies_in_from_min_to_max; simpl in *; try omega.\n\n      + eapply IHl; eauto.\n\n    - allrw in_app_iff; repndors; tcsp.\n\n      + unfold view_change2max_seq_preps in *.\n        dup i as les.\n        eapply PreparedInfos2max_seq_is_max in les;[| |eauto];auto;[].\n        eapply implies_in_from_min_to_max; simpl in *; try omega.\n\n      + dup i as j.\n        eapply IHl in j;[| |eauto|eauto];auto; eauto 3 with pbft.\n\n    - allrw in_app_iff; repndors; tcsp.\n\n      + unfold view_change2max_seq_preps in *.\n        dup i as les.\n        eapply PreparedInfos2max_seq_is_max in les;[| |eauto];auto;[].\n        eapply implies_in_from_min_to_max; simpl in *; try omega.\n\n      + eapply view_change_cert2max_seq_preps_vc_none_implies in i;[|eauto]; pbft_simplifier.\n\n    - allrw in_app_iff; repndors; tcsp.\n\n      + unfold view_change2max_seq_preps in *.\n        dup i as les.\n        eapply PreparedInfos2max_seq_none_implies in i;[|eauto]; pbft_simplifier.\n\n      + eapply IHl; eauto.\n  Qed.\n  Hint Resolve implies_prepared_info2max_seq_in_from_min_to_max : pbft.\n\n  Lemma from_min_to_max_of_view_changes_nil_implies_all_sequence_numbers_are_accounted_for_op_true :\n    forall entry OP,\n      is_some (vce_view_change entry) = true\n      -> from_min_to_max_of_view_changes entry = []\n      -> all_sequence_numbers_are_accounted_for_op\n           (view_change_cert2prep (view_change_entry2view_changes entry))\n           (view_change_cert2max_seq (view_change_entry2view_changes entry))\n           OP = true.\n  Proof.\n    introv issome h.\n    unfold from_min_to_max_of_view_changes in h.\n    destruct entry, vce_view_change; simpl in *; tcsp; GC.\n    unfold all_sequence_numbers_are_accounted_for_op.\n    unfold all_sequence_numbers_are_accounted_for.\n\n    remember (view_change_cert2max_seq (v :: vce_view_changes)) as maxVop.\n    symmetry in HeqmaxVop.\n    destruct maxVop; simpl in *;\n      [|unfold view_change_cert2max_seq in *; simpl in *; smash_pbft];[].\n\n    unfold from_min_to_max_op in h.\n\n    rewrite forallb_forall.\n    introv i.\n    unfold sequence_number_is_accounted_for; smash_pbft;[].\n\n    unfold from_min_to_max_of_view_changes_cert in *.\n    rewrite HeqmaxVop in *; simpl in *.\n\n    (* WARNING *)\n    clear HeqmaxVop.\n\n    assert (view_change2prep v ++ view_change_cert2prep vce_view_changes\n            = view_change_cert2prep (v :: vce_view_changes)) as xx by tcsp.\n    rewrite xx in *; clear xx.\n\n    (* WARNING *)\n    remember (v :: vce_view_changes) as l; clear Heql.\n    remember (valid_prepared_info (view_change_cert2prep l)) as F; clear HeqF.\n\n    smash_pbft;[|].\n\n    - unfold view_change_cert2max_seq_preps in *; smash_pbft;[].\n      eapply implies_prepared_info2max_seq_in_from_min_to_max in i;\n        [| |eauto|eauto];auto.\n      rewrite h in *; simpl in *; tcsp.\n\n    - unfold view_change_cert2max_seq_preps in *; smash_pbft;[].\n      eapply view_change_cert2max_seq_preps_vc_none_implies in i;[|eauto]; pbft_simplifier.\n  Qed.\n  Hint Resolve from_min_to_max_of_view_changes_nil_implies_all_sequence_numbers_are_accounted_for_op_true : pbft.\n\n  Lemma view_change_cert_max_seq_preps_vc_none_implies_all_sequence_numbers_are_accounted_for :\n    forall k min OP,\n      view_change_cert2max_seq_preps_vc (valid_prepared_info (view_change_cert2prep k)) k = None\n      -> all_sequence_numbers_are_accounted_for (view_change_cert2prep k) min OP = true.\n  Proof.\n    introv vcmax.\n    unfold all_sequence_numbers_are_accounted_for.\n    apply forallb_forall.\n    introv i.\n    unfold sequence_number_is_accounted_for; smash_pbft.\n    assert False; tcsp.\n    remember (valid_prepared_info (view_change_cert2prep k)) as F; clear HeqF.\n    eapply view_change_cert2max_seq_preps_vc_none_implies in vcmax;[|eauto]; pbft_simplifier.\n  Qed.\n  Hint Resolve view_change_cert_max_seq_preps_vc_none_implies_all_sequence_numbers_are_accounted_for : pbft.\n\n  Lemma create_new_prepare_message_true_of_valid_prepared_info_in_implies :\n    forall x l v keys ppd,\n      In x l\n      -> valid_prepared_info l x = true\n      -> create_new_prepare_message (prepared_info2seq x) v keys l = (true, ppd)\n      -> same_digests (prepared_info2digest x) (pre_prepare2digest (fst ppd)) = true\n         /\\ same_seq_nums (prepared_info2seq x) (pre_prepare2seq (fst ppd)) = true.\n  Proof.\n    introv i valid create.\n    repnd; simpl in *.\n    unfold create_new_prepare_message in create; smash_pbft.\n    rename_hyp_with find_pre_prepare_certificate_in_prepared_infos fprep.\n    apply find_pre_prepare_certificate_in_prepared_infos_some_implies in fprep.\n    repnd.\n\n    unfold same_seq_nums; smash_pbft; dands; auto;[].\n    unfold pre_prepare2digest; simpl.\n\n    unfold valid_prepared_info in *; smash_pbft.\n    unfold last_prepared_info in *.\n    allrw forallb_forall.\n    applydup valid0 in fprep0.\n    smash_pbft;[|].\n\n    - match goal with\n      | [ H : info_is_prepared x0 = true |- _ ] => rename H into isprep\n      end.\n      unfold info_is_prepared in isprep.\n      smash_pbft.\n      unfold prepared_info_has_correct_digest in *; smash_pbft.\n\n    - applydup fprep2 in i.\n      smash_pbft;[].\n      try omega.\n  Qed.\n  Hint Resolve create_new_prepare_message_true_of_valid_prepared_info_in_implies : pbft.\n\n  Lemma create_new_prepare_message_false_of_valid_prepared_info_in_implies :\n    forall x l v keys ppd,\n      In x l\n      -> valid_prepared_info l x = true\n      -> create_new_prepare_message (prepared_info2seq x) v keys l = (false, ppd)\n      -> False.\n  Proof.\n    introv i valid create.\n    repnd; simpl in *.\n    unfold create_new_prepare_message in create; smash_pbft.\n    rename_hyp_with find_pre_prepare_certificate_in_prepared_infos fprep.\n    eapply find_pre_prepare_certificate_in_prepared_infos_none_implies in i; eauto.\n    repndors; pbft_simplifier.\n  Qed.\n  Hint Resolve create_new_prepare_message_false_of_valid_prepared_info_in_implies : pbft.\n\n  Lemma create_new_prepare_messages_of_valid_prepared_info_in_implies :\n    forall N v keys l OP NP x,\n      create_new_prepare_messages N v keys l = (OP, NP)\n      -> In x l\n      -> valid_prepared_info l x = true\n      -> In (prepared_info2seq x) N\n      -> exists_prepared_info_in_pre_prepares x (map fst OP) = true.\n  Proof.\n    induction N; introv create i valid j; simpl in *; tcsp.\n    repndors; subst; smash_pbft.\n  Qed.\n  Hint Resolve create_new_prepare_messages_of_valid_prepared_info_in_implies : pbft.\n\n  Lemma create_new_prepare_messages_implies_all_sequence_numbers_are_accounted_for :\n    forall l v keys OP NP min max vc,\n      create_new_prepare_messages (from_min_to_max min max) v keys (view_change_cert2prep l) = (OP, NP)\n      -> view_change_cert2max_seq l = Some min\n      -> view_change_cert2max_seq_preps_vc (valid_prepared_info (view_change_cert2prep l)) l = Some (max, vc)\n      -> all_sequence_numbers_are_accounted_for (view_change_cert2prep l) min (map fst OP) = true.\n  Proof.\n    introv create vcmin vcmax.\n    unfold all_sequence_numbers_are_accounted_for.\n    apply forallb_forall.\n    introv i.\n    unfold sequence_number_is_accounted_for; smash_pbft.\n  Qed.\n  Hint Resolve create_new_prepare_messages_implies_all_sequence_numbers_are_accounted_for : pbft.\n\n  Lemma check_broadcast_new_view_generates :\n    forall i state entry nv entry' OP NP,\n      check_broadcast_new_view i state entry = Some (nv, entry', OP, NP)\n      -> correct_new_view nv = true.\n  Proof.\n    introv check.\n    dup check as check_backup.\n    hide_hyp check_backup.\n    unfold check_broadcast_new_view in check; smash_pbft.\n\n    rename_hyp_with view_changed_entry changed.\n    dup changed as changed_backup.\n    hide_hyp changed_backup.\n    unfold view_changed_entry in changed; smash_pbft.\n\n    pose proof (implies_length_view_change_entry2view_changes entry (length (vce_view_changes entry))) as lenvcs.\n    repeat (autodimp lenvcs hyp); allrw; auto;[].\n\n    remember (replace_own_view_change_in_entry (refresh_view_change x state) entry) as entry'.\n    remember (view_change_cert2max_seq (view_change_entry2view_changes entry')) as minop.\n    symmetry in Heqminop.\n    rename_hyp_with create_new_prepare_messages cr.\n    destruct minop as [min|];\n      [|applydup create_new_prepare_messages_view_change_cert2max_seq_none_implies in cr as eqs; auto;\n        repnd; subst; simpl in *;\n        rewrite eqs in *; simpl in *; GC;\n        unfold correct_new_view; simpl; smash_pbft; try omega;\n        destruct entry, vce_view_change; simpl in *; smash_pbft; try omega;\n        [eapply from_min_to_max_of_view_changes_nil_implies_all_sequence_numbers_are_accounted_for_op_true in eqs;\n         simpl in *; auto; exact eqs|];[];\n        match goal with\n        | [ H : correct_view_change _ _ = _ |- _ ] =>\n          applydup correct_view_change_implies_same_views in H as sv; simpl in sv\n        end; autorewrite with pbft in *; subst; tcsp];[].\n\n    assert (forall n, In n (from_min_to_max_of_view_changes entry') -> n <= max_O OP) as imp1.\n    { introv i; eapply view_changed_entry_some_and_check_broadcast_new_view_implies_le; eauto. }\n\n    clear check_backup.\n    clear changed_backup.\n\n    rename_hyp_with correct_view_change corvcs.\n    assert (vce_view entry = view_change2view x) as eqviews.\n    {\n      unfold view_change_entry2view_changes in corvcs.\n      subst entry'; simpl in *.\n      destruct entry; simpl in *; smash_pbft.\n      unfold correct_view_change in *; smash_pbft.\n      unfold same_views in *; smash_pbft.\n    }\n\n    unfold correct_new_view; simpl; smash_pbft; try omega;\n      try (complete (destruct entry, vce_view_change; simpl in *; smash_pbft; try omega));\n      [| |].\n\n    - rename_hyp_with correct_new_view_opre_prepare_op coro.\n      rename_hyp_with correct_new_view_npre_prepare_op corn.\n      rename_hyp_with SeqNumDeq nrep1.\n\n      hide_hyp imp1.\n      hide_hyp coro.\n      hide_hyp corn.\n      hide_hyp nrep1.\n\n      rewrite Heqminop; simpl.\n      remember (replace_own_view_change_in_entry (refresh_view_change x state) entry) as l.\n\n      unfold from_min_to_max_of_view_changes in *; simpl in *.\n      unfold from_min_to_max_of_view_changes_cert in *; simpl in *.\n      rewrite Heqminop in *; simpl in *.\n\n      unfold view_change_cert2max_seq_preps in *; smash_pbft.\n\n    - match goal with\n      | [ H1 : create_new_prepare_messages _ _ _ _ = _, H2 : forallb _ _ = false |- _ ] =>\n        apply (create_new_prepare_messages_implies_correct_NPs\n                 min (pre_prepares2max_seq (map fst OP))) in H1\n      end.\n\n      {\n        rewrite Heqminop in *; simpl in *; autorewrite with pbft in *; smash_pbft.\n      }\n\n      introv i create; repnd.\n      dands; eauto 2 with pbft.\n      rewrite <- max_O_as_pre_prepares2max_seq.\n\n      applydup imp1 in i.\n      apply le_lt_or_eq in i0; repndors; tcsp;[].\n      apply implies_eq_seq_nums in i0.\n\n      assert False; tcsp.\n\n      clear imp1.\n      unfold from_min_to_max_of_view_changes in *.\n      unfold from_min_to_max_of_view_changes_cert in *.\n\n      applydup in_from_min_to_max_op_implies in i.\n      exrepnd.\n      rewrite i2 in *; ginv.\n      rewrite i3 in *; ginv.\n      simpl in *.\n\n      pose proof (max_O_in OP) as q.\n\n      apply (view_change_cert2max_seq_preps_implies_exists_create_new_prepare_message\n               (view_change2view x) (local_keys state)) in i3.\n      exrepnd.\n\n      match goal with\n      | [ H1 : create_new_prepare_message _ _ _ _ = (false, _),\n          H2 : create_new_prepare_messages _ _ _ _ = _\n      |- _ ] =>\n        applydup create_new_prepare_message_implies_same_sequence_number in H1 as eqsn;\n          dup H2 as c1; dup H2 as c2; dup H2 as c3; rename H1 into fcreate\n      end.\n\n      (* c1 part *)\n      eapply create_new_prepare_message_true_implies_oprep_not_nil in c1;\n        [| |eauto]; eauto 2 with pbft;[].\n\n      (* c2 part *)\n      eapply false_implies_in_create_new_prepare_messages_n_pre_prepare in c2;\n        [| |exact fcreate];[|unfold from_min_to_max_of_view_changes;allrw;simpl;auto];[].\n\n      (* c3 part *)\n      apply create_new_prepare_messages_implies_norepeatsb in c3; eauto 2 with pbft;[].\n\n      autodimp q hyp; eauto 2 with pbft;[].\n      exrepnd.\n\n      eapply norepeatsb_pre_prepare2seq_oprep_nprep_implies;[eauto| |eauto|eauto].\n      congruence.\n\n    - match goal with\n      | [ H1 : create_new_prepare_messages _ _ _ _ = _, H2 : forallb _ _ = false |- _ ] =>\n        apply (create_new_prepare_messages_implies_correct_OPs min) in H1\n      end.\n\n      {\n        rewrite Heqminop in *; simpl in *; autorewrite with pbft in *; smash_pbft.\n      }\n\n      introv i create.\n      dands; eauto 2 with pbft.\n  Qed.\n  Hint Resolve check_broadcast_new_view_generates : pbft.\n\nEnd PBFTprops4.\n\n\nHint Resolve info_is_prepared_implies_prepared_info_has_correct_digest : pbft.\nHint Resolve valid_prepared_info_implies_prepared_info_has_correct_digest : pbft.\nHint Resolve le_max_view_left : pbft.\nHint Resolve le_max_view_right : pbft.\nHint Resolve le_max_seq_num : pbft.\nHint Resolve le_max_seq_num_right : pbft.\nHint Resolve le_max_seq_num_op : pbft.\nHint Resolve PreparedInfos2max_seq_is_max : pbft.\nHint Resolve implies_in_from_min_to_max : pbft.\nHint Resolve in_from_min_to_max_trans : pbft.\nHint Resolve implies_prepared_info2max_seq_in_from_min_to_max : pbft.\nHint Resolve from_min_to_max_of_view_changes_nil_implies_all_sequence_numbers_are_accounted_for_op_true : pbft.\nHint Resolve view_change_cert_max_seq_preps_vc_none_implies_all_sequence_numbers_are_accounted_for : pbft.\nHint Resolve create_new_prepare_message_true_of_valid_prepared_info_in_implies : pbft.\nHint Resolve create_new_prepare_message_false_of_valid_prepared_info_in_implies : pbft.\nHint Resolve create_new_prepare_messages_of_valid_prepared_info_in_implies : pbft.\nHint Resolve create_new_prepare_messages_implies_all_sequence_numbers_are_accounted_for : pbft.\nHint Resolve check_broadcast_new_view_generates : pbft.\n\n\nHint Rewrite @view_change2view_refresh_view_change : pbft.\n", "meta": {"author": "vrahli", "repo": "Velisarios", "sha": "6fb353b18610cd79210755fcc90123536c367aaa", "save_path": "github-repos/coq/vrahli-Velisarios", "path": "github-repos/coq/vrahli-Velisarios/Velisarios-6fb353b18610cd79210755fcc90123536c367aaa/PBFT/PBFTprops4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.20826831569953713}}
{"text": "Require Export MinBFTg.\n\n\nSection USIGcomp.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc : DTimeContext }.\n\n  Context { minbft_context : MinBFT_context }.\n  Context { m_initial_keys : MinBFT_initial_keys }.\n  Context { u_initial_keys : USIG_initial_keys }.\n\n  Context { usig_hash : USIG_hash }.\n\n  Context { minbft_auth : MinBFT_auth }.\n\n\n  Global Instance USIG_trusted_info : TrustedInfo :=\n    MkTrustedInfo USIG_state.\n\n  (* ===============================================================\n     USIG UPDATE & SM\n     =============================================================== *)\n\n  Definition USIG_update : M_Update 0 USIGname _ :=\n    fun (s : USIG_state) (m : USIG_input_interface) =>\n      interp_s_proc\n        (match m with\n         | create_ui_in (v,r) =>\n           let (s', ui) := create_UI v r s in\n           [R] (s', create_ui_out ui)\n         | verify_ui_in (v,r,ui) =>\n           let b := verify_UI v r ui s in\n           [R] (s, verify_ui_out b)\n         end).\n\n  (* (1) USIG and TrInc will have the same IO interface, but different states\n     (2) add a new field to CompName to allow differentiating those states\n     (3) call_proc will only look at the old CompName, without the new field\n     (4) write a wrapper around TrInc's interface, which is slightly different\n     (5) Parametrize UI in MinBFT\n     (6) Move this elsewhere (to where all interfaces and states have been defined)\n   *)\n  Definition USIG_comp (r : Rep) : M_StateMachine 1 USIGname :=\n    build_m_sm USIG_update (USIG_initial r).\n\n\n  Definition MinBFTsubs (n : Rep) : n_procs _ :=\n    [\n      MkPProc USIGname (USIG_comp n),\n      MkPProc LOGname LOG_comp\n    ].\n\n  Definition MinBFTsubs_new (s1 : USIG_state) (s2 : LOG_state) : n_procs _ :=\n    [\n      MkPProc USIGname (build_m_sm USIG_update s1),\n      MkPProc LOGname  (build_m_sm LOG_update s2)\n    ].\n\n  Definition MinBFTsubs_new_u (u : USIG_state) : n_procs _ :=\n    [\n      MkPProc USIGname (build_m_sm USIG_update u),\n      MkPProc LOGname  LOG_comp\n    ].\n\n  Definition MinBFTsubs_new_l n (l : LOG_state) : n_procs _ :=\n    [\n      MkPProc USIGname (USIG_comp n),\n      MkPProc LOGname  (build_m_sm LOG_update l)\n    ].\n\n  Definition MinBFTlocalSys (n : Rep) : MinBFTls :=\n    MkLocalSystem\n      (MAIN_comp n)\n      (MinBFTsubs n).\n\n  Definition MinBFTlocalSys_new\n             (n  : Rep)\n             (s  : MAIN_state)\n             (s1 : USIG_state)\n             (s2 : LOG_state) : MinBFTls :=\n    MkLocalSystem\n      (MinBFT_replicaSM_new n s)\n      (MinBFTsubs_new s1 s2).\n\n  Definition MinBFTsys : M_USystem MinBFTfunLevelSpace (*name -> M_StateMachine 2 msg_comp_name*) :=\n    fun name =>\n      match name with\n      | MinBFT_replica n => MinBFTlocalSys n\n      | _ => unit_ls\n      end.\n\n  Lemma MinBFTsubs_new_inj :\n    forall a b c d,\n      MinBFTsubs_new a b = MinBFTsubs_new c d\n      -> a = c /\\ b = d.\n  Proof.\n    introv h.\n    repeat (apply eq_cons in h; repnd); GC.\n    apply decomp_p_nproc in h0.\n    apply decomp_p_nproc in h1.\n    inversion h0; inversion h1; subst; simpl in *; auto.\n  Qed.\n\n  Lemma MinBFTlocalSys_new_inj :\n    forall a1 a2 b1 b2 c1 c2 d1 d2,\n      MinBFTlocalSys_new a1 b1 c1 d1 = MinBFTlocalSys_new a2 b2 c2 d2\n      -> b1 = b2 /\\ c1 = c2 /\\ d1 = d2.\n  Proof.\n    introv h.\n    apply decomp_LocalSystem in h; repnd; simpl in *.\n    apply MinBFTsubs_new_inj in h; repnd; subst.\n    inversion h0; subst; simpl in *; tcsp.\n  Qed.\n\n  Lemma MinBFTlocalSys_as_new :\n    forall (r  : Rep),\n      MinBFTlocalSys r\n      = MinBFTlocalSys_new\n          r\n          (initial_state r)\n          (USIG_initial r)\n          LOG_initial.\n  Proof.\n    introv; eauto.\n  Qed.\n\n  Definition USIGlocalSys (s : USIG_state) : LocalSystem _ _  :=\n    MkLocalSystem (build_mp_sm USIG_update s) [].\n\nEnd USIGcomp.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/USIGcomp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.20822759972999677}}
{"text": "From cap_machine Require Export logrel.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.program_logic Require Import weakestpre adequacy lifting.\nFrom stdpp Require Import base.\nFrom cap_machine.ftlr Require Import ftlr_base interp_weakening.\nFrom cap_machine.rules Require Import rules_base rules_Restrict.\n\nSection fundamental.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ} {sealsg: sealStoreG Σ}\n          {nainv: logrel_na_invs Σ}\n          `{MachineParameters}.\n\n  Notation D := ((leibnizO Word) -n> iPropO Σ).\n  Notation R := ((leibnizO Reg) -n> iPropO Σ).\n  Implicit Types w : (leibnizO Word).\n  Implicit Types interp : (D).\n\n  Lemma PermPairFlows_interp_preserved p p' b e a :\n    p <> E ->\n    PermFlowsTo p' p = true →\n    (□ ▷ (∀ a0 a1 a2 a3 a4,\n             full_map a0\n\n          -∗ (∀ (r1 : RegName) v, ⌜r1 ≠ PC⌝ → ⌜a0 !! r1 = Some v⌝ → (fixpoint interp1) v)\n          -∗ registers_mapsto (<[PC:=WCap a1 a2 a3 a4]> a0)\n          -∗ na_own logrel_nais ⊤\n          -∗ □ (fixpoint interp1) (WCap a1 a2 a3 a4) -∗ interp_conf)) -∗\n    (fixpoint interp1) (WCap p b e a) -∗\n    (fixpoint interp1) (WCap p' b e a).\n  Proof.\n    intros HpnotE Hp. iIntros \"#IH HA\".\n    iApply (interp_weakening with \"IH HA\"); eauto; try solve_addr.\n  Qed.\n\n  Lemma match_perm_with_E_rewrite:\n    forall (A: Type) p (a1 a2: A),\n      match p with\n      | E => a1\n      | _ => a2\n      end = if (perm_eq_dec p E) then a1 else a2.\n  Proof.\n    intros. destruct (perm_eq_dec p E); destruct p; auto; congruence.\n  Qed.\n\n  Lemma restrict_case (r : leibnizO Reg) (p : Perm)\n        (b e a : Addr) (w : Word) (dst : RegName) (r0 : Z + RegName) (P:D):\n    ftlr_instr r p b e a w (Restrict dst r0) P.\n  Proof.\n    intros Hp Hsome i Hbae Hi.\n    iIntros \"#IH #Hinv #Hinva #Hreg #[Hread Hwrite] Hown Ha HP Hcls HPC Hmap\".\n    rewrite delete_insert_delete.\n    iDestruct ((big_sepM_delete _ _ PC) with \"[HPC Hmap]\") as \"Hmap /=\";\n      [apply lookup_insert|rewrite delete_insert_delete;iFrame|]. simpl.\n    iApply (wp_Restrict with \"[$Ha $Hmap]\"); eauto.\n    { simplify_map_eq; auto. }\n    { rewrite /subseteq /map_subseteq /set_subseteq_instance. intros rr _.\n      apply elem_of_dom. apply lookup_insert_is_Some'; eauto. }\n\n    iIntros \"!>\" (regs' retv). iDestruct 1 as (HSpec) \"[Ha Hmap]\".\n    destruct HSpec as [ * Hdst ? Hz Hfl HincrPC | * Hdst Hz Hfl HincrPC | ].\n    { apply incrementPC_Some_inv in HincrPC as (p''&b''&e''&a''& ? & HPC & Z & Hregs') .\n\n      assert (a'' = a ∧ b'' = b ∧ e'' = e) as (-> & -> & ->).\n      { destruct (decide (PC = dst)); simplify_map_eq; auto. }\n\n      iApply wp_pure_step_later; auto.\n      iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro].\n      iNext; iIntros \"_\".\n      iApply (\"IH\" $! regs' with \"[%] [] [Hmap] [$Hown]\").\n      { cbn. intros. subst regs'. by repeat (apply lookup_insert_is_Some'; right). }\n      { iIntros (ri v Hri Hvs).\n        subst regs'.\n        rewrite lookup_insert_ne in Hvs; auto.\n        destruct (decide (ri = dst)).\n        { subst ri.\n          rewrite lookup_insert_ne in Hdst; auto.\n          rewrite lookup_insert in Hvs; inversion Hvs. simplify_eq.\n          unshelve iSpecialize (\"Hreg\" $! dst _ _ Hdst); eauto.\n          iApply (interp_weakening with \"IH Hreg\"); auto; solve_addr. }\n        { repeat (rewrite lookup_insert_ne in Hvs); auto.\n          iApply \"Hreg\"; auto. } }\n        { subst regs'. rewrite insert_insert. iApply \"Hmap\". }\n      iModIntro.\n      iApply (interp_weakening with \"IH Hinv\"); auto; try solve_addr.\n      { destruct Hp; by subst p. }\n      { destruct (reg_eq_dec PC dst) as [Heq | Hne]; simplify_map_eq.\n        auto. by rewrite PermFlowsToReflexive. }\n    }\n    { apply incrementPC_Some_inv in HincrPC as (p''&b''&e''&a''& ? & HPC & Z & Hregs') .\n\n      assert (dst ≠ PC) as Hne.\n      { destruct (decide (PC = dst)); last auto. simplify_map_eq; auto. }\n\n      assert (p'' = p ∧ b'' = b ∧ e'' = e ∧ a'' = a) as (-> & -> & -> & ->).\n      { simplify_map_eq; auto. }\n\n      iApply wp_pure_step_later; auto.\n      iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro].\n      iNext; iIntros \"_\".\n      iApply (\"IH\" $! regs' with \"[%] [] [Hmap] [$Hown]\").\n      { cbn. intros. subst regs'. by repeat (apply lookup_insert_is_Some'; right). }\n      { iIntros (ri v Hri Hvs).\n        subst regs'.\n        rewrite lookup_insert_ne in Hvs; auto.\n        destruct (decide (ri = dst)).\n        { subst ri.\n          rewrite lookup_insert_ne in Hdst; auto.\n          rewrite lookup_insert in Hvs; inversion Hvs. simplify_eq.\n          unshelve iSpecialize (\"Hreg\" $! dst _ _ Hdst); eauto.\n          iApply (interp_weakening_ot with \"Hreg\"); auto; solve_addr. }\n        { repeat (rewrite lookup_insert_ne in Hvs); auto.\n          iApply \"Hreg\"; auto. } }\n        { subst regs'. rewrite insert_insert. iApply \"Hmap\". }\n      iModIntro.\n      iApply (interp_weakening with \"IH Hinv\"); auto; try solve_addr.\n      { destruct Hp; by subst p. }\n      { by rewrite PermFlowsToReflexive. }\n    }\n     { iApply wp_pure_step_later; auto.\n      iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro].\n      iNext; iIntros \"_\".\n      iApply wp_value; auto. iIntros; discriminate. }\n  Qed.\n\nEnd fundamental.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/ftlr/Restrict.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.20822759839197816}}
{"text": "(* Construction of a PDM using the monad G *)\n\nFrom Coq Require Import Utf8 RelationClasses.\nFrom PDM Require Import util structures guarded PURE PDM.\n\nSet Default Goal Selector \"!\".\nSet Printing Projections.\nSet Universe Polymorphism.\nUnset Universe Minimization ToSet.\n\nClass LeafPred (M : Type → Type) :=\n  leaf : ∀ A, A → M A → Prop.\n\nNotation \"x ∈ c\" := (leaf _ x c) (at level 80).\n\nClass Leafine M (hleaf : LeafPred M) :=\n  leafine : ∀ A (c : M A), M { x : A | x ∈ c }.\n\nArguments leafine {_ _ _} [_].\n\nSection Guarded.\n\n  (* Computation monad *)\n\n  Context {M} `{Monad M}.\n\n  (* Specification monad *)\n\n  Context {W} `{Monad W} {Word : Order W} (hmono : MonoSpec W).\n\n  (* Effect observation *)\n\n  Context {θ : observation M W} (hlax : LaxMorphism θ).\n\n  Arguments θ [_].\n\n  (* We require a LiftPred, which is used to define bind for Mᴳ below *)\n\n  Context (leafpred : LeafPred M) (hleaf : Leafine M leafpred).\n\n  (* Using this we build Mᴳ, a new computation monad with req *)\n\n  Definition Mᴳ A := G (M A).\n\n  #[refine] Instance Monad_Mᴳ : Monad Mᴳ := {|\n    ret A x := ret (M := G) (ret x)\n  |}.\n  Proof.\n    hnf. intros A B c f.\n    exists (∃ (h : c.π1), ∀ x, x ∈ c.π2 h → (f x).π1). intro h.\n    simple refine (bind (leafine (c.π2 _)) (λ x, (f (val x)).π2 _)).\n    - apply h.\n    - destruct h as [hp h]. destruct x as [x hx]. apply h.\n      apply hx.\n  Defined.\n\n  Instance ReqMonad_Mᴳ : ReqMonad Mᴳ := {|\n    req p := bind (req p) (λ h, ret (M := G) (ret (M := M) h))\n  |}.\n\n  (* Now we extend the spec monad with req, we do this using a liftᵂ *)\n  (* TODO: Should it generally be built this way? *)\n\n  Context (liftᵂ : spec_lift_pure W).\n\n  Arguments liftᵂ [_].\n\n  Instance ReqMonad_W : ReqMonad W := {|\n    req p := liftᵂ (req p)\n  |}.\n\n  (* New effect observation *)\n\n  Definition θᴳ : observation Mᴳ W :=\n    λ A c, bind (req c.π1) (λ h, θ (c.π2 h)).\n\n  (* We try (and for now fail) to extend the lax monad morphism proof *)\n  (* Instance hreqlax : ReqLaxMorphism Word θᴳ.\n  Proof.\n    constructor. 1: constructor.\n    - intros A x.\n      unfold θᴳ.\n      simpl. etransitivity.\n      + eapply bind_mono.\n        * admit. (* Maybe we need refl *)\n        * intro y. apply θ_ret.\n      + (* Would the laws help here? Not clear. *)\n        admit.\n    - intros A B c f.\n      unfold θᴳ. simpl. (* Might be hard to find a general case here *)\n      admit.\n    - intro p.\n      unfold θᴳ. cbn - [pure_wp_reqmon].\n      (* Not even clear it works *)\n      admit.\n  Abort. *)\n\n  (* Until we find the proper assumptions, we will assume it *)\n  Context (θᴳ_lax : LaxMorphism θᴳ) (θᴳ_reqlax : ReqLaxMorphism Word θᴳ).\n\n  (* Partial Dijkstra monad *)\n\n  Definition D A w :=\n    PDM.D (θ := θᴳ) A w.\n\n  Instance DijkstraMonad_D : DijkstraMonad D :=\n    PDM.DijkstraMonad_D hmono θᴳ_lax.\n\n  (* Lift from PURE *)\n\n  (* Same here, we try (and for now fail) to define a lift from PURE *)\n  Instance hlift : PureSpec W Word liftᵂ.\n  Proof.\n    constructor.\n    intros A w f.\n    simpl.\n  Abort.\n\n  (* So we just assume it: *)\n  Context (hlift : PureSpec W Word liftᵂ).\n\n  Definition liftᴾ :=\n    liftᴾ (M := Mᴳ) (W := W) hmono θᴳ_lax θᴳ_reqlax hlift.\n\nEnd Guarded.\n", "meta": {"author": "TheoWinterhalter", "repo": "pdm4all", "sha": "570868f2e395bada6e3dc0462d7e9af065289461", "save_path": "github-repos/coq/TheoWinterhalter-pdm4all", "path": "github-repos/coq/TheoWinterhalter-pdm4all/pdm4all-570868f2e395bada6e3dc0462d7e9af065289461/theories/GuardedPDM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.36296919173767833, "lm_q1q2_score": 0.20822758787039597}}
{"text": "Require Import Coqlib.\nRequire Import Errors.\nRequire Import Maps.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Events.\nRequire Import Smallstep.\nRequire Import Op.\nRequire Import Registers.\nRequire Import Inlining.\nRequire Import Inliningspec.\nRequire Import RTL.\n\nRequire Import mem_lemmas.\nRequire Import semantics.\nRequire Import reach.\nRequire Import effect_semantics.\nRequire Import structured_injections.\nRequire Import simulations.\nRequire Import effect_properties.\nRequire Import simulations_lemmas.\n\n\nRequire Export Axioms.\nRequire Import RTL_coop.\nRequire Import RTL_eff.\n\n(*Load Santiago_tactics.*)\nLtac open_Hyp:= match goal with\n                     | [H: and _ _ |- _] => destruct H\n                     | [H: exists _, _ |- _] => destruct H\n                 end.\n\n(* The rewriters *)\nSection PRESERVATION.\n\n\nHint Rewrite vis_restrict_sm: restrict.\nHint Rewrite restrict_sm_all: restrict.\nHint Rewrite restrict_sm_frgnBlocksSrc: restrict.\n\nVariable SrcProg: program.\nVariable TrgProg: program.\nHypothesis TRANSF: transf_program SrcProg = OK TrgProg.\nLet ge : genv := Genv.globalenv SrcProg.\nLet tge : genv := Genv.globalenv TrgProg.\nLet fenv := funenv_program SrcProg.\n\nLemma symbols_preserved:\n  forall (s: ident), Genv.find_symbol tge s = Genv.find_symbol ge s.\nProof.\n  intros. apply Genv.find_symbol_transf_partial with (transf_fundef fenv). apply TRANSF.\nQed.\n\nLemma varinfo_preserved:\n  forall b, Genv.find_var_info tge b = Genv.find_var_info ge b.\nProof.\n  intros. apply Genv.find_var_info_transf_partial with (transf_fundef fenv). apply TRANSF.\nQed.\n\nLemma functions_translated:\n  forall (v: val) (f:  fundef),\n    Genv.find_funct ge v = Some f ->\n    exists f', Genv.find_funct tge v = Some f' /\\ transf_fundef fenv f = OK f'.\nProof.\n  eapply (Genv.find_funct_transf_partial (transf_fundef fenv) _ TRANSF).\nQed.\nLemma function_ptr_translated:\n  forall (b: block) (f:  fundef),\n    Genv.find_funct_ptr ge b = Some f ->\n    exists f', Genv.find_funct_ptr tge b = Some f' /\\ transf_fundef fenv f = OK f'.\nProof.\n  eapply (Genv.find_funct_ptr_transf_partial (transf_fundef fenv) _ TRANSF).\nQed.\n\nLemma sig_function_translated:\n  forall f f', transf_fundef fenv f = OK f' ->  funsig f' =  funsig f.\nProof.\n  intros. destruct f; Errors.monadInv H.\n  exploit transf_function_spec; eauto. intros SP; inv SP. auto. \n  auto.\nQed.\n\nLemma GDE_lemma: genvs_domain_eq ge tge.\nProof.\n  (* OLD\n    unfold genvs_domain_eq, genv2blocks.\n    simpl; split; intros. \n     split; intros; destruct H as [id Hid].\n       rewrite <- symbols_preserved in Hid.\n       exists id; trivial.\n     rewrite symbols_preserved in Hid.\n       exists id; trivial.\n       ad_it.\n    (*rewrite varinfo_preserved. intuition.*) *)\n  unfold genvs_domain_eq, genv2blocks.\n  simpl; split; intros. \n  split; intros; destruct H as [id Hid].\n  rewrite <- symbols_preserved in Hid.\n  exists id; trivial.\n  rewrite symbols_preserved in Hid.\n  exists id; trivial.\n  split; intros.\n  rewrite varinfo_preserved; intuition.\n  split.\n  intros [f H].\n  apply function_ptr_translated in H. \n  destruct H as [? [? _]].\n  eexists; eassumption.\n  intros [f H].\n  apply (@Genv.find_funct_ptr_rev_transf_partial\n           _ _ _ _ _ _ TRANSF) in H.\n  destruct H as [? [? _]]. eexists; eassumption.\nQed.\nHint Resolve GDE_lemma: trans_correct.\n\n(** ** Properties of contexts and relocations *)\n\nRemark sreg_below_diff:\n  forall ctx r r', Plt r' ctx.(dreg) -> sreg ctx r <> r'.\nProof.\n  intros. zify. unfold sreg; rewrite shiftpos_eq. xomega. \nQed.\n\nRemark context_below_diff:\n  forall ctx1 ctx2 r1 r2,\n    context_below ctx1 ctx2 -> Ple r1 ctx1.(mreg) -> sreg ctx1 r1 <> sreg ctx2 r2.\nProof.\n  intros. red in H. zify. unfold sreg; rewrite ! shiftpos_eq. xomega.\nQed.\n\nRemark context_below_lt:\n  forall ctx1 ctx2 r, context_below ctx1 ctx2 -> Ple r ctx1.(mreg) -> Plt (sreg ctx1 r) ctx2.(dreg).\nProof.\n  intros. red in H. unfold Plt; zify. unfold sreg; rewrite shiftpos_eq. \n  xomega.\nQed.\n\n(** ** Agreement between register sets before and after inlining. *)\n\nDefinition agree_regs (F: meminj) (ctx: context) (rs rs': regset) :=\n  (forall r, Ple r ctx.(mreg) -> val_inject F rs#r rs'#(sreg ctx r))\n  /\\(forall r, Plt ctx.(mreg) r -> rs#r = Vundef).\n\nDefinition val_reg_charact (F: meminj) (ctx: context) (rs': regset) (v: val) (r: reg) :=\n  (Plt ctx.(mreg) r /\\ v = Vundef) \\/ (Ple r ctx.(mreg) /\\ val_inject F v rs'#(sreg ctx r)).\n\nRemark Plt_Ple_dec:\n  forall p q, {Plt p q} + {Ple q p}.\nProof.\n  intros. destruct (plt p q). left; auto. right; xomega.\nQed.\n\nLemma agree_val_reg_gen:\n  forall F ctx rs rs' r, agree_regs F ctx rs rs' -> val_reg_charact F ctx rs' rs#r r.\nProof.\n  intros. destruct H as [A B].\n  destruct (Plt_Ple_dec (mreg ctx) r). \n  left. rewrite B; auto. \n  right. auto.\nQed.\n\nLemma agree_val_regs_gen:\n  forall F ctx rs rs' rl,\n    agree_regs F ctx rs rs' -> list_forall2 (val_reg_charact F ctx rs') rs##rl rl.\nProof.\n  induction rl; intros; constructor; auto. apply agree_val_reg_gen; auto.\nQed.\n\nLemma agree_val_reg:\n  forall F ctx rs rs' r, agree_regs F ctx rs rs' -> val_inject F rs#r rs'#(sreg ctx r).\nProof.\n  intros. exploit agree_val_reg_gen; eauto. instantiate (1 := r). intros [[A B] | [A B]].\n  rewrite B; auto.\n  auto.\nQed.\n\nLemma agree_val_regs:\n  forall F ctx rs rs' rl, agree_regs F ctx rs rs' -> val_list_inject F rs##rl rs'##(sregs ctx rl).\nProof.\n  induction rl; intros; simpl. constructor. constructor; auto. apply agree_val_reg; auto.\nQed.\n\nLemma agree_set_reg:\n  forall F ctx rs rs' r v v',\n    agree_regs F ctx rs rs' ->\n    val_inject F v v' ->\n    Ple r ctx.(mreg) ->\n    agree_regs F ctx (rs#r <- v) (rs'#(sreg ctx r) <- v').\nProof.\n  unfold agree_regs; intros. destruct H. split; intros.\n  repeat rewrite Regmap.gsspec. \n  destruct (peq r0 r). subst r0. rewrite peq_true. auto.\n  rewrite peq_false. auto. apply shiftpos_diff; auto. \n  rewrite Regmap.gso. auto. xomega. \nQed.\n\nLemma agree_set_reg_undef:\n  forall F ctx rs rs' r v',\n    agree_regs F ctx rs rs' ->\n    agree_regs F ctx (rs#r <- Vundef) (rs'#(sreg ctx r) <- v').\nProof.\n  unfold agree_regs; intros. destruct H. split; intros.\n  repeat rewrite Regmap.gsspec. \n  destruct (peq r0 r). subst r0. rewrite peq_true. auto.\n  rewrite peq_false. auto. apply shiftpos_diff; auto. \n  rewrite Regmap.gsspec. destruct (peq r0 r); auto. \nQed.\n\nLemma agree_set_reg_undef':\n  forall F ctx rs rs' r,\n    agree_regs F ctx rs rs' ->\n    agree_regs F ctx (rs#r <- Vundef) rs'.\nProof.\n  unfold agree_regs; intros. destruct H. split; intros.\n  rewrite Regmap.gsspec. \n  destruct (peq r0 r). subst r0. auto. auto.\n  rewrite Regmap.gsspec. destruct (peq r0 r); auto. \nQed.\n\nLemma agree_regs_invariant:\n  forall F ctx rs rs1 rs2,\n    agree_regs F ctx rs rs1 ->\n    (forall r, Ple ctx.(dreg) r -> Plt r (ctx.(dreg) + ctx.(mreg)) -> rs2#r = rs1#r) ->\n    agree_regs F ctx rs rs2.\nProof.\n  unfold agree_regs; intros. destruct H. split; intros.\n  rewrite H0. auto. \n  apply shiftpos_above.\n  eapply Plt_le_trans. apply shiftpos_below. xomega.\n  apply H1; auto.\nQed.\n\nLemma agree_regs_incr:\n  forall F ctx rs1 rs2 F',\n    agree_regs F ctx rs1 rs2 ->\n    inject_incr F F' ->\n    agree_regs F' ctx rs1 rs2.\nProof.\n  intros. destruct H. split; intros. eauto. auto. \nQed.\n\nRemark agree_regs_init:\n  forall F ctx rs, agree_regs F ctx (Regmap.init Vundef) rs.\nProof.\n  intros; split; intros. rewrite Regmap.gi; auto. rewrite Regmap.gi; auto. \nQed.\n\nLemma agree_regs_init_regs:\n  forall F ctx rl vl vl',\n    val_list_inject F vl vl' ->\n    (forall r, In r rl -> Ple r ctx.(mreg)) ->\n    agree_regs F ctx (init_regs vl rl) (init_regs vl' (sregs ctx rl)).\nProof.\n  induction rl; simpl; intros.\n  apply agree_regs_init.\n  inv H. apply agree_regs_init.\n  apply agree_set_reg; auto. \nQed.\n\n\n(** ** Executing sequences of moves *)\n\nLemma tr_moves_init_regs:\n  forall F stk f sp m ctx1 ctx2, context_below ctx1 ctx2 ->\n                                 forall rdsts rsrcs vl pc1 pc2 rs1,\n                                   tr_moves f.(fn_code) pc1 (sregs ctx1 rsrcs) (sregs ctx2 rdsts) pc2 ->\n                                   (forall r, In r rdsts -> Ple r ctx2.(mreg)) ->\n                                   list_forall2 (val_reg_charact F ctx1 rs1) vl rsrcs ->\n                                   exists rs2,\n                                     star  step tge (State stk f sp pc1 rs1 m)\n                                           E0 (State stk f sp pc2 rs2 m)\n                                     /\\ agree_regs F ctx2 (init_regs vl rdsts) rs2\n                                     /\\ forall r, Plt r ctx2.(dreg) -> rs2#r = rs1#r.\nProof.\n  induction rdsts; simpl; intros.\n  (* rdsts = nil *)\n  inv H0. exists rs1; split. apply star_refl. split. apply agree_regs_init. auto.\n  (* rdsts = a :: rdsts *)\n  inv H2. inv H0. \n  exists rs1; split. apply star_refl. split. apply agree_regs_init. auto.\n  simpl in H0. inv H0.\n  exploit IHrdsts; eauto. intros [rs2 [A [B C]]].\n  exists (rs2#(sreg ctx2 a) <- (rs2#(sreg ctx1 b1))).\n  split. eapply star_right. eauto. eapply  exec_Iop; eauto. traceEq.\n  split. destruct H3 as [[P Q] | [P Q]].\n  subst a1. eapply agree_set_reg_undef; eauto.\n  eapply agree_set_reg; eauto. rewrite C; auto.  apply context_below_lt; auto.\n  intros. rewrite Regmap.gso. auto. apply sym_not_equal. eapply sreg_below_diff; eauto.\n  destruct H2; discriminate.\nQed.\n\nLemma tr_moves_init_regs':\n  forall F hf stk f sp m ctx1 ctx2, context_below ctx1 ctx2 ->\n                                    forall rdsts rsrcs vl pc1 pc2 rs1,\n                                      tr_moves f.(fn_code) pc1 (sregs ctx1 rsrcs) (sregs ctx2 rdsts) pc2 ->\n                                      (forall r, In r rdsts -> Ple r ctx2.(mreg)) ->\n                                      list_forall2 (val_reg_charact F ctx1 rs1) vl rsrcs ->\n                                      exists rs2, semantics_lemmas.corestep_star (rtl_eff_sem hf) tge\n                                                                                      (RTL_State stk f sp pc1 rs1) m\n                                                                                      (RTL_State stk f sp pc2 rs2) m\n                                                  /\\ agree_regs F ctx2 (init_regs vl rdsts) rs2\n                                                  /\\ forall r, Plt r ctx2.(dreg) -> rs2#r = rs1#r.\nProof.\n  induction rdsts; simpl; intros.\n  (* rdsts = nil *)\n  inv H0. exists rs1; split. apply semantics_lemmas.corestep_star_zero. split. apply agree_regs_init. auto.\n  (* rdsts = a :: rdsts *)\n  inv H2. inv H0. \n  exists rs1; split. apply semantics_lemmas.corestep_star_zero. split. apply agree_regs_init. auto.\n  simpl in H0. inv H0.\n  exploit IHrdsts; eauto. intros [rs2 [A [B C]]].\n  exists (rs2#(sreg ctx2 a) <- (rs2#(sreg ctx1 b1))).\n  split. eapply semantics_lemmas.corestep_star_trans; eauto. \n  eapply semantics_lemmas.corestep_star_one.\n  eapply  rtl_corestep_exec_Iop; eauto.\n  split. destruct H3 as [[P Q] | [P Q]].\n  subst a1. eapply agree_set_reg_undef; eauto.\n  eapply agree_set_reg; eauto. rewrite C; auto.  apply context_below_lt; auto.\n  intros. rewrite Regmap.gso. auto. apply sym_not_equal. eapply sreg_below_diff; eauto.\n  destruct H2; discriminate.\nQed.\n\nLemma tr_moves_init_regs_eff:\n  forall F hf stk f sp m ctx1 ctx2, context_below ctx1 ctx2 ->\n                                    forall rdsts rsrcs vl pc1 pc2 rs1,\n                                      tr_moves f.(fn_code) pc1 (sregs ctx1 rsrcs) (sregs ctx2 rdsts) pc2 ->\n                                      (forall r, In r rdsts -> Ple r ctx2.(mreg)) ->\n                                      list_forall2 (val_reg_charact F ctx1 rs1) vl rsrcs ->\n                                      exists rs2,\n                                        effstep_star (rtl_eff_sem hf) tge EmptyEffect\n                                                     (RTL_State stk f sp pc1 rs1) m\n                                                     (RTL_State stk f sp pc2 rs2) m\n                                        /\\ agree_regs F ctx2 (init_regs vl rdsts) rs2\n                                        /\\ forall r, Plt r ctx2.(dreg) -> rs2#r = rs1#r.\nProof.\n  induction rdsts; simpl; intros.\n  (* rdsts = nil *)\n  inv H0. exists rs1; split. apply effstep_star_zero. split. apply agree_regs_init. auto.\n  (* rdsts = a :: rdsts *)\n  inv H2. inv H0. \n  exists rs1; split. apply effstep_star_zero. split. apply agree_regs_init. auto.\n  simpl in H0. inv H0.\n  exploit IHrdsts; eauto. intros [rs2 [A [B C]]].\n  exists (rs2#(sreg ctx2 a) <- (rs2#(sreg ctx1 b1))).\n  split. \n  eapply effstep_star_trans'; eauto.\n  eapply effstep_star_one.\n  eapply  rtl_effstep_exec_Iop; eauto.\n  extensionality x. reflexivity.\n  split. destruct H3 as [[P Q] | [P Q]].\n  subst a1. eapply agree_set_reg_undef; eauto.\n  eapply agree_set_reg; eauto. rewrite C; auto.  apply context_below_lt; auto.\n  intros. rewrite Regmap.gso. auto. apply sym_not_equal. eapply sreg_below_diff; eauto.\n  destruct H2; discriminate.\nQed.\n\n\n(** ** Memory invariants *)\n\n(** A stack location is private if it is not the image of a valid\n   location and we have full rights on it. *)\n\nDefinition loc_private (F: meminj) (m m': mem) (sp: block) (ofs: Z) : Prop :=\n  Mem.perm m' sp ofs Cur Freeable /\\\n  (forall b delta, F b = Some(sp, delta) -> ~Mem.perm m b (ofs - delta) Max Nonempty).\n\n(** Likewise, for a range of locations. *)\n\nDefinition range_private (F: meminj) (m m': mem) (sp: block) (lo hi: Z) : Prop :=\n  forall ofs, lo <= ofs < hi -> loc_private F m m' sp ofs.\n\nLemma range_private_invariant:\n  forall F m m' sp lo hi F1 m1 m1',\n    range_private F m m' sp lo hi ->\n    (forall b delta ofs,\n       F1 b = Some(sp, delta) ->\n       Mem.perm m1 b ofs Max Nonempty ->\n       lo <= ofs + delta < hi ->\n       F b = Some(sp, delta) /\\ Mem.perm m b ofs Max Nonempty) ->\n    (forall ofs, Mem.perm m' sp ofs Cur Freeable -> Mem.perm m1' sp ofs Cur Freeable) ->\n    range_private F1 m1 m1' sp lo hi.\nProof.\n  intros; red; intros. exploit H; eauto. intros [A B]. split; auto.\n  intros; red; intros. exploit H0; eauto. omega. intros [P Q]. \n  eelim B; eauto.\nQed.\n\nLemma range_private_perms:\n  forall F m m' sp lo hi,\n    range_private F m m' sp lo hi ->\n    Mem.range_perm m' sp lo hi Cur Freeable.\nProof.\n  intros; red; intros. eapply H; eauto.\nQed.\n\nLemma range_private_alloc_left:\n  forall F m m' sp' base hi sz m1 sp F1,\n    range_private F m m' sp' base hi ->\n    Mem.alloc m 0 sz = (m1, sp) ->\n    F1 sp = Some(sp', base) ->\n    (forall b, b <> sp -> F1 b = F b) ->\n    range_private F1 m1 m' sp' (base + Zmax sz 0) hi.\nProof.\n  intros; red; intros. \n  exploit (H ofs). generalize (Zmax2 sz 0). omega. intros [A B].\n  split; auto. intros; red; intros.\n  exploit Mem.perm_alloc_inv; eauto.\n  destruct (eq_block b sp); intros.\n  subst b. rewrite H1 in H4; inv H4. \n  rewrite Zmax_spec in H3. destruct (zlt 0 sz); omega.\n  rewrite H2 in H4; auto. eelim B; eauto. \nQed.\n\nLemma range_private_free_left:\n  forall F m m' sp base sz hi b m1,\n    range_private F m m' sp (base + Zmax sz 0) hi ->\n    Mem.free m b 0 sz = Some m1 ->\n    F b = Some(sp, base) ->\n    Mem.inject F m m' ->\n    range_private F m1 m' sp base hi.\nProof.\n  intros; red; intros. \n  destruct (zlt ofs (base + Zmax sz 0)) as [z|z].\n  red; split. \n  replace ofs with ((ofs - base) + base) by omega.\n  eapply Mem.perm_inject; eauto.\n  eapply Mem.free_range_perm; eauto.\n  rewrite Zmax_spec in z. destruct (zlt 0 sz); omega. \n  intros; red; intros. destruct (eq_block b b0).\n  subst b0. rewrite H1 in H4; inv H4.\n  eelim Mem.perm_free_2; eauto. rewrite Zmax_spec in z. destruct (zlt 0 sz); omega.\n  exploit Mem.mi_no_overlap; eauto. \n  apply Mem.perm_cur_max. apply Mem.perm_implies with Freeable; auto with mem.\n  eapply Mem.free_range_perm. eauto. \n  instantiate (1 := ofs - base). rewrite Zmax_spec in z. destruct (zlt 0 sz); omega.\n  eapply Mem.perm_free_3; eauto. \n  intros [A | A]. congruence. omega. \n\n  exploit (H ofs). omega. intros [A B]. split. auto.\n  intros; red; intros. eelim B; eauto. eapply Mem.perm_free_3; eauto.\nQed.\n\nLemma range_private_extcall:\n  forall F F' m1 m2 m1' m2' sp base hi,\n    range_private F m1 m1' sp base hi ->\n    (forall b ofs p,\n       Mem.valid_block m1 b -> Mem.perm m2 b ofs Max p -> Mem.perm m1 b ofs Max p) ->\n    Mem.unchanged_on (loc_out_of_reach F m1) m1' m2' ->\n    Mem.inject F m1 m1' ->\n    inject_incr F F' ->\n    inject_separated F F' m1 m1' ->\n    Mem.valid_block m1' sp ->\n    range_private F' m2 m2' sp base hi.\nProof.\n  intros until hi; intros RP PERM UNCH INJ INCR SEP VB.\n  red; intros. exploit RP; eauto. intros [A B].\n  split. eapply Mem.perm_unchanged_on; eauto. \n  intros. red in SEP. destruct (F b) as [[sp1 delta1] |] eqn:?.\n  exploit INCR; eauto. intros EQ; rewrite H0 in EQ; inv EQ. \n  red; intros; eelim B; eauto. eapply PERM; eauto. \n  red. destruct (plt b (Mem.nextblock m1)); auto. \n  exploit Mem.mi_freeblocks; eauto. congruence.\n  exploit SEP; eauto. tauto. \nQed.\n\n(*NEW*)\nLemma range_private_extcall_sm:\n  forall F F' m1 m2 m1' m2' sp base hi (WDF: SM_wd F) (WDF': SM_wd F'),\n    range_private (as_inj F) m1 m1' sp base hi ->\n    (forall b ofs p,\n       Mem.valid_block m1 b -> Mem.perm m2 b ofs Max p -> Mem.perm m1 b ofs Max p) ->\n    Mem.unchanged_on (local_out_of_reach F m1) m1' m2' ->\n    Mem.inject (as_inj F) m1 m1' ->\n    extern_incr F F' ->\n    sm_inject_separated F F' m1 m1' ->\n    Mem.valid_block m1' sp ->\n    (*NEW*) locBlocksTgt F sp = true -> \n    range_private (as_inj F') m2 m2' sp base hi.\nProof.\n  intros until hi; intros WDF WDF' RP PERM UNCH INJ INCR SEP VB LBT.\n  red; intros. exploit RP; eauto. intros [A B].\n  split. eapply Mem.perm_unchanged_on; eauto. \n  split; trivial. \n  intros. left. apply local_in_all in H0; eauto. \n  intros. \n  destruct SEP as [SEPa [SEPb SEPc]]. \n  destruct (as_inj F b) as [[sp1 delta1] |] eqn:?.\n  exploit (extern_incr_as_inj _ _ INCR); eauto. \n  intros EQ; rewrite H0 in EQ; inv EQ. \n  red; intros. eelim B; eauto. eapply PERM; eauto. \n  red. destruct (plt b (Mem.nextblock m1)); auto. \n  exploit Mem.mi_freeblocks; eauto. congruence.\n  destruct (SEPa _ _ _ Heqo H0). \n  elim (SEPc _ H2). unfold DomTgt. \n  assert (LT: locBlocksTgt F = locBlocksTgt F') by eapply INCR. \n  rewrite <- LT, LBT. trivial. \n  eapply Mem.perm_valid_block; eassumption.\nQed.\n\n\n(** ** Relating global environments *)\n\nInductive match_globalenvs mu (bound: block): Prop :=\n| mk_match_globalenvs\n    (DOMAIN: forall b, Plt b bound -> \n                       ((*frgnBlocksSrc mu b = true /\\*) as_inj mu b = Some(b, 0)))\n    (IMAGE: forall b1 b2 delta gv\n                   (GV: Genv.find_var_info ge b2 = Some gv),\n              as_inj mu b1 = Some(b2, delta) -> Plt b2 bound -> \n              b1 = b2)\n\n    (SYMBOLS: forall id b, Genv.find_symbol ge id = Some b -> Plt b bound)\n    (FUNCTIONS: forall b fd, Genv.find_funct_ptr ge b = Some fd -> Plt b bound)\n    (VARINFOS: forall b gv, Genv.find_var_info ge b = Some gv -> Plt b bound).\n\nLemma find_function_agree:\n  forall ros rs fd F ctx rs' bound,\n    find_function ge ros rs = Some fd ->\n    agree_regs (as_inj F) ctx rs rs' ->\n    match_globalenvs F bound ->\n    exists fd',\n      find_function tge (sros ctx ros) rs' = Some fd' /\\ transf_fundef fenv fd = OK fd'.\nProof.\n  intros. destruct ros as [r | id]; simpl in *.\n  (* register *)\n  assert (rs'#(sreg ctx r) = rs#r).\n  exploit Genv.find_funct_inv; eauto. intros [b EQ].\n  assert (A: val_inject (as_inj F) rs#r rs'#(sreg ctx r)). eapply agree_val_reg; eauto.\n  rewrite EQ in A; inv A.\n  inv H1.\n  \n  assert (HH: Plt b bound).\n  apply FUNCTIONS with fd. \n  rewrite EQ in H; rewrite Genv.find_funct_find_funct_ptr in H. auto.\n  (*destruct*) specialize (DOMAIN b HH).\n  rewrite DOMAIN in H5; inv H5. rewrite Int.add_zero. rewrite EQ. trivial.\n  eapply functions_translated; eauto. rewrite <- H2 in H. trivial.\n  (* symbol *)\n  rewrite symbols_preserved. destruct (Genv.find_symbol ge id); try discriminate.\n  eapply function_ptr_translated; eauto.\nQed.\n\n(*\nLemma find_function_agree':\n  forall ros rs fd F ctx rs' bound,\n    find_function ge ros rs = Some fd ->\n    agree_regs (as_inj F) ctx rs rs' ->\n    match_globalenvs F bound ->\n    exists fd',\n      find_function tge (sros ctx ros) rs' = Some fd' /\\ transf_fundef fenv fd = OK fd'.\nProof.\n  intros. destruct ros as [r | id]; simpl in *.\n  (* register *)\n  assert (rs'#(sreg ctx r) = rs#r).\n  exploit Genv.find_funct_inv; eauto. intros [b EQ].\n  assert (A: val_inject (as_inj F) rs#r rs'#(sreg ctx r)). eapply agree_val_reg; eauto.\n  rewrite EQ in A; inv A.\n  inv H1.\n  destruct (DOMAIN b). \n  apply FUNCTIONS with fd. \n  rewrite EQ in H; rewrite Genv.find_funct_find_funct_ptr in H. auto.\n  rewrite H2 in H5; inv H5. rewrite Int.add_zero. rewrite EQ. trivial.\n  eapply functions_translated; eauto. rewrite <- H2 in H. trivial.\n  (* symbol *)\n  rewrite symbols_preserved. destruct (Genv.find_symbol ge id); try discriminate.\n  eapply function_ptr_translated; eauto.\nQed.*)\n\n(** ** Relating stacks *) \nInductive match_stacks (mu: SM_Injection) (m m': mem):\n  list stackframe -> list stackframe -> block -> Prop :=\n| match_stacks_nil: forall bound1 bound\n                           (MG: match_globalenvs mu bound1)\n                           (BELOW: Ple bound1 bound),\n                      match_stacks mu m m' nil nil bound\n| match_stacks_cons: forall res (f:function) sp pc rs stk (f':function) sp' rs' stk' bound ctx\n                            (MS: match_stacks_inside mu m m' stk stk' f' ctx sp' rs')\n                            (FB: tr_funbody fenv f'.(fn_stacksize) ctx f f'.(fn_code))\n                            (AG: agree_regs (as_inj mu) ctx rs rs')\n                            (SP: (as_inj mu) sp = Some(sp', ctx.(dstk)))\n                            (SL: locBlocksTgt mu sp' = true )\n                            (PRIV: range_private (as_inj mu) m m' sp' (ctx.(dstk) + ctx.(mstk)) f'.(fn_stacksize))\n                            (SSZ1: 0 <= f'.(fn_stacksize) < Int.max_unsigned)\n                            (SSZ2: forall ofs, Mem.perm m' sp' ofs Max Nonempty -> 0 <= ofs <= f'.(fn_stacksize))\n                            (RES: Ple res ctx.(mreg))\n                            (BELOW: Plt sp' bound),\n                       match_stacks (mu) m m'\n                                    (Stackframe res f (Vptr sp Int.zero) pc rs :: stk)\n                                    (Stackframe (sreg ctx res) f' (Vptr sp' Int.zero) (spc ctx pc) rs' :: stk')\n                                    bound\n| match_stacks_untailcall: forall stk res f' sp' rpc rs' stk' bound ctx\n                                  (MS: match_stacks_inside (mu) m m' stk stk' f' ctx sp' rs')\n                                  (PRIV: range_private (as_inj mu) m m' sp' ctx.(dstk) f'.(fn_stacksize))\n                                  (SSZ1: 0 <= f'.(fn_stacksize) < Int.max_unsigned)\n                                  (SSZ2: forall ofs, Mem.perm m' sp' ofs Max Nonempty -> 0 <= ofs <= f'.(fn_stacksize))\n                                  (RET: ctx.(retinfo) = Some (rpc, res))\n                                  (SL: locBlocksTgt mu sp' = true )\n                                  (BELOW: Plt sp' bound),\n                             match_stacks (mu) m m'\n                                          stk\n                                          (Stackframe res f' (Vptr sp' Int.zero) rpc rs' :: stk')\n                                          bound\n\nwith match_stacks_inside (mu: SM_Injection) (m m': mem):\n       list stackframe -> list stackframe -> function -> context -> block -> regset -> Prop :=\n     | match_stacks_inside_base: forall stk stk' f' ctx sp' rs'\n                                        (MS: match_stacks (mu) m m' stk stk' sp')\n                                        (SL: locBlocksTgt mu sp' = true ) \n                                        (RET: ctx.(retinfo) = None)\n                                        (DSTK: ctx.(dstk) = 0),\n                                   match_stacks_inside (mu) m m' stk stk' f' ctx sp' rs'\n     | match_stacks_inside_inlined: forall res f sp pc rs stk stk' f' ctx sp' rs' ctx'\n                                           (MS: match_stacks_inside (mu) m m' stk stk' f' ctx' sp' rs')\n                                           (FB: tr_funbody fenv f'.(fn_stacksize) ctx' f f'.(fn_code))\n                                           (AG: agree_regs (as_inj mu) ctx' rs rs')\n                                           (SP: (local_of mu) sp = Some(sp', ctx'.(dstk)))\n                                           (SL: locBlocksTgt mu sp' = true )\n                                           (PAD: range_private (as_inj mu) m m' sp' (ctx'.(dstk) + ctx'.(mstk)) ctx.(dstk))\n                                           (RES: Ple res ctx'.(mreg))\n                                           (RET: ctx.(retinfo) = Some (spc ctx' pc, sreg ctx' res))\n                                           (BELOW: context_below ctx' ctx)\n                                           (SBELOW: context_stack_call ctx' ctx),\n                                      match_stacks_inside (mu) m m' (Stackframe res f (Vptr sp Int.zero) pc rs :: stk)\n                                                          stk' f' ctx sp' rs'.\n\n(** Properties of match_stacks *)\n\n(*NEW*)\nSection MATCH_STACKS_replace_externs.\n  Variable mu: SM_Injection.\n  Variables FS FT: block -> bool.\n  Hypothesis HFS: forall b, frgnBlocksSrc mu b = true -> FS b = true.\n  Variables m m': mem.\n\n  Lemma match_stacks_replace_externs:\n    forall stk stk' bound,\n      match_stacks mu m m' stk stk' bound ->\n      match_stacks (replace_externs mu FS FT) m m' stk stk' bound\n      with match_stacks_inside_replace_externs:\n             forall stk stk' f ctx sp rs', \n               match_stacks_inside mu m m' stk stk' f ctx sp rs' ->  \n               match_stacks_inside (replace_externs mu FS FT) m m' stk stk' f ctx sp rs'.\n  Proof.\n    induction 1; eauto.\n    { econstructor; try rewrite replace_externs_as_inj; try eassumption.\n      destruct MG. \n      econstructor; try rewrite replace_externs_as_inj; eauto. \n      (* intros. rewrite replace_externs_frgnBlocksSrc. \n      destruct (DOMAIN _ H). split; eauto. *) }\n\n    { econstructor; try rewrite replace_externs_as_inj; eauto. \n      rewrite replace_externs_locBlocksTgt. assumption. }\n\n    { econstructor; try rewrite replace_externs_as_inj; eauto. \n      rewrite replace_externs_locBlocksTgt; trivial. }\n\n    induction 1; eauto.\n    { econstructor; eauto.\n      rewrite replace_externs_locBlocksTgt; trivial. }\n    { eapply match_stacks_inside_inlined; \n      try rewrite replace_externs_as_inj; eauto.\n      rewrite replace_externs_local; trivial.  \n      rewrite replace_externs_locBlocksTgt; trivial. }\n  Qed.\n\nEnd MATCH_STACKS_replace_externs.\n\n\n(*NEW*)\nSection MATCH_STACKS_replace_locals.\n  Variable mu: SM_Injection.\n  Variables PS PT: block -> bool.\n  Variables m m': mem.\n\n  Lemma match_stacks_replace_locals:\n    forall stk stk' bound,\n      match_stacks mu m m' stk stk' bound ->\n      match_stacks (replace_locals mu PS PT) m m' stk stk' bound\n      with match_stacks_inside_replace_locals:\n             forall stk stk' f ctx sp rs', \n               match_stacks_inside mu m m' stk stk' f ctx sp rs' ->  \n               match_stacks_inside (replace_locals mu PS PT) m m' stk stk' f ctx sp rs'.\n  Proof.\n    induction 1; eauto.\n    { econstructor; try eassumption.\n      destruct MG.\n      constructor; try rewrite replace_locals_as_inj; eauto. \n      (*rewrite replace_locals_frgnBlocksSrc; assumption.*) }\n\n    { econstructor; try rewrite replace_locals_as_inj; eauto. \n      rewrite replace_locals_locBlocksTgt; trivial. }\n    { econstructor; try rewrite replace_locals_as_inj; eauto. \n      rewrite replace_locals_locBlocksTgt; trivial. }\n    induction 1; eauto.\n    { econstructor; eauto.\n      rewrite replace_locals_locBlocksTgt; trivial. }\n    { eapply match_stacks_inside_inlined; \n      try rewrite replace_locals_as_inj; eauto.\n      rewrite replace_locals_local; trivial.  \n      rewrite replace_locals_locBlocksTgt; trivial. }\n  Qed.\n\n  Lemma match_stacks_replace_locals_restrict:\n    forall stk stk' bound,\n      match_stacks (restrict_sm mu (vis mu)) m m' stk stk' bound ->\n      match_stacks (restrict_sm (replace_locals mu PS PT) (vis mu)) m m' stk stk' bound\n      with match_stacks_inside_replace_locals_restrict:\n             forall stk stk' f ctx sp rs', \n               match_stacks_inside (restrict_sm mu (vis mu)) m m' stk stk' f ctx sp rs' ->  \n               match_stacks_inside (restrict_sm (replace_locals mu PS PT) (vis mu)) m m' stk stk' f ctx sp rs'.\n  Proof.\n    induction 1; eauto.\n    { econstructor; try eassumption.\n      destruct MG.\n      constructor; eauto. \n      rewrite (*restrict_sm_frgnBlocksSrc,*) restrict_sm_all, (*replace_locals_frgnBlocksSrc,*) replace_locals_as_inj; rewrite restrict_sm_all (*, restrict_sm_frgnBlocksSrc*) in DOMAIN; assumption.\n      rewrite restrict_sm_all, replace_locals_as_inj; rewrite restrict_sm_all in IMAGE; assumption. \n    }\n\n    { econstructor; try rewrite restrict_sm_all, replace_locals_as_inj in *; eauto. \n      rewrite restrict_sm_locBlocksTgt, replace_locals_locBlocksTgt in *; trivial. }\n    { econstructor; try rewrite restrict_sm_all, replace_locals_as_inj in *; eauto.\n      rewrite restrict_sm_locBlocksTgt, replace_locals_locBlocksTgt in *; trivial. }\n    induction 1; eauto.\n    { econstructor; eauto.\n      rewrite restrict_sm_locBlocksTgt, replace_locals_locBlocksTgt in *; trivial. }\n    { eapply match_stacks_inside_inlined; \n      try rewrite restrict_sm_all, restrict_sm_local, replace_locals_as_inj in *; eauto.\n      rewrite restrict_sm_local, replace_locals_local in *; trivial.  \n      rewrite restrict_sm_locBlocksTgt, replace_locals_locBlocksTgt in *; trivial. }\n  Qed.\n\nEnd MATCH_STACKS_replace_locals.\n\nLemma match_globalenvs_intern_incr mu mu' b: forall\n                                               (MG: match_globalenvs mu b) (INC: intern_incr mu mu')\n                                               (HJ: forall b1 b2 d, as_inj mu' b1 = Some (b2, d) -> \n                                                                    Plt b2 b -> as_inj mu b1 = Some (b2, d))\n                                               (WD: SM_wd mu'),\n                                               match_globalenvs mu' b.\nProof. intros. inv MG. constructor; eauto.\n       assert (FBS: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC.\n       (*NEW*) intros. \n       eapply (intern_incr_as_inj _ _ INC); auto; apply DOMAIN.\n       (*intros. destruct (DOMAIN _ H). split. trivial.\n       eapply (intern_incr_as_inj _ _ INC); trivial.*)\nQed.  \n\nLemma match_globalenvs_extern_incr mu mu' b: forall\n                                               (MG: match_globalenvs mu b) (INC: extern_incr mu mu')\n                                               (HJ: forall b1 b2 d, as_inj mu' b1 = Some (b2, d) -> \n                                                                    Plt b2 b -> as_inj mu b1 = Some (b2, d))\n                                               (WD: SM_wd mu'),\n                                               match_globalenvs mu' b.\nProof. intros. inv MG. constructor; eauto.\n       assert (FBS: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INC.\n       (*NEW*) intros. \n       eapply (extern_incr_as_inj _ _ INC); auto; apply DOMAIN.\n       (*\n       rewrite <- FBS; intros. destruct (DOMAIN _ H). split. trivial.\n       eapply (extern_incr_as_inj _ _ INC); trivial.*)\nQed.  \n\nSection MATCH_STACKS.\n  Variable F: SM_Injection.\n  Variables m m': mem.\n  Let Finj := as_inj F.\n\n  Lemma match_stacks_globalenvs:\n    forall stk stk' bound,\n      match_stacks F m m' stk stk' bound -> \n      exists b, match_globalenvs F b\n                with match_stacks_inside_globalenvs:\n                       forall stk stk' f ctx sp rs', \n                         match_stacks_inside F m m' stk stk' f ctx sp rs' ->\n                         exists b, match_globalenvs F b.\n  Proof.\n    induction 1; eauto.\n    induction 1; eauto.\n  Qed.\n\n  Lemma match_globalenvs_preserves_globals:\n    forall b, match_globalenvs F b -> meminj_preserves_globals ge Finj.\n  Proof.\n    intros. inv H. red.\n    split. intros. eapply (DOMAIN _ (SYMBOLS _ _ H)). \n    split. intros. eapply (DOMAIN _ (VARINFOS _ _ H)). \n    intros. symmetry. eapply IMAGE; eauto.\n  Qed. \n\n  Lemma match_stacks_inside_globals:\n    forall stk stk' f ctx sp rs', \n      match_stacks_inside F m m' stk stk' f ctx sp rs' -> \n      meminj_preserves_globals ge Finj.\n  Proof.\n    intros. exploit match_stacks_inside_globalenvs; eauto. intros [b A]. \n    eapply match_globalenvs_preserves_globals; eauto.\n  Qed.\n\n  Lemma match_stacks_bound:\n    forall stk stk' bound bound1,\n      match_stacks F m m' stk stk' bound ->\n      Ple bound bound1 ->\n      match_stacks F m m' stk stk' bound1.\n  Proof.\n    intros. inv H.\n    apply match_stacks_nil with bound0. auto. eapply Ple_trans; eauto.\n    eapply match_stacks_cons; eauto. eapply Plt_le_trans; eauto. \n    eapply match_stacks_untailcall; eauto. eapply Plt_le_trans; eauto. \n  Qed. \n\n  Variable F1: SM_Injection.\n  Let Finj1 := as_inj F1.\n  Variables m1 m1': mem.\n  (*Hypothesis INCR: inject_incr Finj Finj1.*)\n  Hypothesis INCR: intern_incr F F1.\n  Hypothesis WDF: SM_wd F.\n  Hypothesis WDF1: SM_wd F1.\n  Lemma INCR':  inject_incr Finj Finj1.\n    eapply intern_incr_as_inj; auto.\n  Qed.\n  Lemma incre_local_of: forall mu mu' (INCR0: intern_incr mu mu') b b' delta, local_of mu b = Some (b', delta) -> local_of mu' b = Some (b', delta).\n    intros.\n    apply intern_incr_local in INCR0.\n    apply INCR0; auto.\n  Qed.\n\n  Lemma match_stacks_invariant:\n    forall stk stk' bound, match_stacks F m m' stk stk' bound ->\n                           forall (INJ: forall b1 b2 delta, \n                                          Finj1 b1 = Some(b2, delta) -> Plt b2 bound -> Finj b1 = Some(b2, delta))\n                                  (PERM1: forall b1 b2 delta ofs,\n                                            Finj1 b1 = Some(b2, delta) -> Plt b2 bound ->\n                                            Mem.perm m1 b1 ofs Max Nonempty -> Mem.perm m b1 ofs Max Nonempty)\n                                  (PERM2: forall b ofs, Plt b bound ->\n                                                        Mem.perm m' b ofs Cur Freeable -> Mem.perm m1' b ofs Cur Freeable)\n                                  (PERM3: forall b ofs k p, Plt b bound ->\n                                                            Mem.perm m1' b ofs k p -> Mem.perm m' b ofs k p),\n                             match_stacks F1 m1 m1' stk stk' bound\n\n                             with match_stacks_inside_invariant:\n                                    forall stk stk' f' ctx sp' rs1, \n                                      match_stacks_inside F m m' stk stk' f' ctx sp' rs1 ->\n                                      forall rs2\n                                             (RS: forall r, Plt r ctx.(dreg) -> rs2#r = rs1#r)\n                                             (INJ: forall b1 b2 delta, \n                                                     Finj1 b1 = Some(b2, delta) -> Ple b2 sp' -> Finj b1 = Some(b2, delta))\n                                             (PERM1: forall b1 b2 delta ofs,\n                                                       Finj1 b1 = Some(b2, delta) -> Ple b2 sp' ->\n                                                       Mem.perm m1 b1 ofs Max Nonempty -> Mem.perm m b1 ofs Max Nonempty)\n                                             (PERM2: forall b ofs, Ple b sp' ->\n                                                                   Mem.perm m' b ofs Cur Freeable -> Mem.perm m1' b ofs Cur Freeable)\n                                             (PERM3: forall b ofs k p, Ple b sp' ->\n                                                                       Mem.perm m1' b ofs k p -> Mem.perm m' b ofs k p),\n                                        match_stacks_inside F1 m1 m1' stk stk' f' ctx sp' rs2.\n\n  Proof.\n    assert (INCR':  inject_incr Finj Finj1) by (exact INCR').\n    induction 1; intros.\n    (* nil *)\n    apply match_stacks_nil with (bound1 := bound1).\n    inv MG. constructor; auto. \n    (*intros. destruct (DOMAIN _ H).\n    split. \n    assert (frgnBlocksSrc F = frgnBlocksSrc F1) by eapply INCR.\n    rewrite <- H2; trivial.\n    eapply (intern_incr_as_inj _ _ INCR); trivial.*)\n    intros. eapply (IMAGE _ _ delta _ GV). eapply INJ; eauto. eapply Plt_le_trans; eauto.\n    auto. auto. \n    (* cons *)\n    apply match_stacks_cons with (ctx := ctx); auto.\n    eapply match_stacks_inside_invariant; eauto.\n    intros; eapply INJ; eauto; xomega. \n    intros; eapply PERM1; eauto; xomega.\n    intros; eapply PERM2; eauto; xomega.\n    intros; eapply PERM3; eauto; xomega.\n    eapply agree_regs_incr; eauto.\n    destruct INCR; repeat open_Hyp; apply H2; assumption.\n    eapply range_private_invariant; eauto. \n    (* untailcall *)\n    apply match_stacks_untailcall with (ctx := ctx); auto. \n    eapply match_stacks_inside_invariant; eauto.\n    intros; eapply INJ; eauto; xomega.\n    intros; eapply PERM1; eauto; xomega.\n    intros; eapply PERM2; eauto; xomega.\n    intros; eapply PERM3; eauto; xomega.\n    eapply range_private_invariant; eauto. \n    destruct INCR; repeat open_Hyp; apply H2; assumption.\n    assert (INCR':  inject_incr Finj Finj1) by (exact INCR').\n    induction 1; intros.\n    (* base *)\n    eapply match_stacks_inside_base; eauto.\n    eapply match_stacks_invariant; eauto. \n    intros; eapply INJ; eauto; xomega.\n    intros; eapply PERM1; eauto; xomega.\n    intros; eapply PERM2; eauto; xomega.\n    intros; eapply PERM3; eauto; xomega.\n    destruct INCR; repeat open_Hyp; apply H2; assumption.\n    (* inlined *)\n    apply match_stacks_inside_inlined with (ctx' := ctx'); auto. \n    apply IHmatch_stacks_inside; auto.\n    intros. apply RS. red in BELOW. xomega. \n    apply agree_regs_incr with Finj; auto. \n    apply agree_regs_invariant with rs'; auto. \n    intros. apply RS. red in BELOW. xomega.\n    eapply (incre_local_of F F1); auto.\n    destruct INCR; repeat open_Hyp. apply H3; assumption.\n    eapply range_private_invariant; eauto.\n    intros. split. eapply INJ; eauto. xomega. eapply PERM1; eauto. xomega.\n    intros. eapply PERM2; eauto. xomega.\n  Qed.\n\n  Lemma match_stacks_empty:\n    forall stk stk' bound,\n      match_stacks F m m' stk stk' bound -> stk = nil -> stk' = nil\n      with match_stacks_inside_empty:\n             forall stk stk' f ctx sp rs,\n               match_stacks_inside F m m' stk stk' f ctx sp rs -> stk = nil -> stk' = nil /\\ ctx.(retinfo) = None.\n  Proof.\n    induction 1; intros.\n    auto.\n    discriminate.\n    exploit match_stacks_inside_empty; eauto. intros [A B]. congruence.\n    induction 1; intros.\n    split. eapply match_stacks_empty; eauto. auto.\n    discriminate.\n  Qed.\n\nEnd MATCH_STACKS.\n\n\n\n(** Preservation by assignment to a register *)\nHint Immediate intern_incr_refl. \n\nLemma match_stacks_inside_set_reg:\n  forall F m m' stk stk' f' ctx sp' rs' r v,\n    SM_wd F ->\n    match_stacks_inside F m m' stk stk' f' ctx sp' rs' ->\n    match_stacks_inside F m m' stk stk' f' ctx sp' (rs'#(sreg ctx r) <- v).\nProof.\n  intros. eapply match_stacks_inside_invariant; eauto. \n  intros. apply Regmap.gso. zify. unfold sreg; rewrite shiftpos_eq. xomega.\nQed.\n\n(** Preservation by a memory store *)\n\nLemma match_stacks_inside_store:\n  forall F m m' stk stk' f' ctx sp' rs' chunk b ofs v m1 chunk' b' ofs' v' m1', \n    SM_wd F ->\n    match_stacks_inside F m m' stk stk' f' ctx sp' rs' ->\n    Mem.store chunk m b ofs v = Some m1 ->\n    Mem.store chunk' m' b' ofs' v' = Some m1' ->\n    match_stacks_inside F m1 m1' stk stk' f' ctx sp' rs'.\nProof.\n  intros. \n  eapply match_stacks_inside_invariant; eauto with mem.\nQed.\n\n(** Preservation by an allocation *)\n\nLemma match_stacks_inside_alloc_left:\n  forall F m m' stk stk' f' ctx sp' rs',\n    SM_wd F ->\n    match_stacks_inside F m m' stk stk' f' ctx sp' rs' ->\n    forall sz m1 b F1 delta,\n      SM_wd F1 ->\n      Mem.alloc m 0 sz = (m1, b) ->\n      (intern_incr F F1) ->\n      (as_inj F1) b = Some(sp', delta) ->\n      (forall b1, b1 <> b -> (as_inj F1) b1 = (as_inj F) b1) ->\n      delta >= ctx.(dstk) ->\n      match_stacks_inside F1 m1 m' stk stk' f' ctx sp' rs'.\nProof.\n  induction 2; intros.\n  (* base *)\n  eapply match_stacks_inside_base; eauto.\n  eapply (match_stacks_invariant F m m' F1); eauto.\n  intros. destruct (eq_block b1 b).\n  subst b1. rewrite H3 in H6; inv H6. eelim Plt_strict; eauto. \n  rewrite H4 in H6; auto. \n  intros. exploit Mem.perm_alloc_inv; eauto. destruct (eq_block b1 b); intros; auto.\n  subst b1. rewrite H3 in H6; inv H6. eelim Plt_strict; eauto. \n  destruct H2; repeat open_Hyp. apply H8; assumption.\n  (* inlined *)\n  assert (INCR':  inject_incr (as_inj F) (as_inj F1)).\n  eapply intern_incr_as_inj; auto.\n  eapply match_stacks_inside_inlined; eauto. \n  eapply IHmatch_stacks_inside; eauto. destruct SBELOW. omega. \n  eapply agree_regs_incr; eauto.\n  apply intern_incr_local in H3.\n  apply H3; auto.\n  destruct H3; repeat open_Hyp. apply H9; assumption.\n  eapply range_private_invariant; eauto. \n  intros. exploit Mem.perm_alloc_inv; eauto. destruct (eq_block b0 b); intros.\n  subst b0. rewrite H4 in H7; inv H7. elimtype False; xomega. \n  rewrite H5 in H7; auto. \nQed.\n\n(** Preservation by freeing *)\n\nLemma match_stacks_free_left:\n  forall F m m' stk stk' sp b lo hi m1,\n    SM_wd F ->\n    match_stacks F m m' stk stk' sp ->\n    Mem.free m b lo hi = Some m1 ->\n    match_stacks F m1 m' stk stk' sp.\nProof.\n  intros. eapply match_stacks_invariant; eauto.\n  intros. eapply Mem.perm_free_3; eauto. \nQed.\n\nLemma match_stacks_free_right:\n  forall F m m' stk stk' sp lo hi m1',\n    SM_wd F ->\n    match_stacks F m m' stk stk' sp ->\n    Mem.free m' sp lo hi = Some m1' ->\n    match_stacks F m m1' stk stk' sp.\nProof.\n  intros. eapply match_stacks_invariant; eauto. \n  intros. eapply Mem.perm_free_1; eauto. \n  intros. eapply Mem.perm_free_3; eauto.\nQed.\n\nLemma min_alignment_sound:\n  forall sz n, (min_alignment sz | n) -> Mem.inj_offset_aligned n sz.\nProof.\n  intros; red; intros. unfold min_alignment in H. \n  assert (2 <= sz -> (2 | n)). intros.\n  destruct (zle sz 1). omegaContradiction.\n  destruct (zle sz 2). auto. \n  destruct (zle sz 4). apply Zdivides_trans with 4; auto. exists 2; auto.\n  apply Zdivides_trans with 8; auto. exists 4; auto.\n  assert (4 <= sz -> (4 | n)). intros.\n  destruct (zle sz 1). omegaContradiction.\n  destruct (zle sz 2). omegaContradiction.\n  destruct (zle sz 4). auto.\n  apply Zdivides_trans with 8; auto. exists 2; auto.\n  assert (8 <= sz -> (8 | n)). intros.\n  destruct (zle sz 1). omegaContradiction.\n  destruct (zle sz 2). omegaContradiction.\n  destruct (zle sz 4). omegaContradiction.\n  auto.\n  destruct chunk; simpl in *; auto.\n  apply Zone_divide.\n  apply Zone_divide.\n  apply H2; omega.\nQed.\n\n\n(** Preservation by external calls *)\n\nSection EXTCALL.\n\n  Variables F1 F2: SM_Injection.\n  Hypothesis WDF1: SM_wd F1.\n  Hypothesis WDF2: SM_wd F2.\n  Let Finj1 := as_inj F1.\n  Let Finj2 := as_inj F2.\n  Variables m1 m2 m1' m2': mem.\n  Hypothesis MAXPERM: forall b ofs p, Mem.valid_block m1 b -> Mem.perm m2 b ofs Max p -> Mem.perm m1 b ofs Max p.\n  Hypothesis MAXPERM': forall b ofs p, Mem.valid_block m1' b -> Mem.perm m2' b ofs Max p -> Mem.perm m1' b ofs Max p.\n  Hypothesis UNCHANGED: Mem.unchanged_on (loc_out_of_reach Finj1 m1) m1' m2'.\n  Hypothesis INJ: Mem.inject Finj1 m1 m1'.\n  Hypothesis INCR: intern_incr F1 F2.\n  Hypothesis SEP: inject_separated Finj1 Finj2 m1 m1'.\n  Hypothesis SMV: sm_valid F1 m1 m1'. \n\n  Lemma match_stacks_extcall:\n    forall stk stk' bound, \n      match_stacks F1 m1 m1' stk stk' bound ->\n      Ple bound (Mem.nextblock m1') ->\n      match_stacks F2 m2 m2' stk stk' bound\n      with match_stacks_inside_extcall:\n             forall stk stk' f' ctx sp' rs',\n               match_stacks_inside F1 m1 m1' stk stk' f' ctx sp' rs' ->\n               Plt sp' (Mem.nextblock m1') ->\n               match_stacks_inside F2 m2 m2' stk stk' f' ctx sp' rs'.\n  Proof.\n    assert (INCR': inject_incr Finj1 Finj2) by (apply INCR'; auto). \n    induction 1; intros.\n    apply match_stacks_nil with bound1; auto. \n    inv MG. constructor; intros; eauto. \n    (*destruct (DOMAIN _ H0).\n    split. assert (F12: frgnBlocksSrc F1 = frgnBlocksSrc F2) by eapply INCR.\n    rewrite <- F12; trivial. \n    eapply (intern_incr_as_inj _ _ INCR); trivial.*)\n    remember (Finj1 b1) as d; apply eq_sym in Heqd.\n    destruct d.\n    destruct p.\n    rewrite (intern_incr_as_inj _ _ INCR WDF2 _ _ _ Heqd) in H0.\n    inv H0.\n    apply (IMAGE _ _ _ _ GV Heqd H1).\n    destruct (SEP _ _ _ Heqd H0).\n    destruct (DOMAIN _ H1).\n    elim H3. apply SMV. eapply (as_inj_DomRng); eauto.\n    \n    eapply match_stacks_cons; eauto. \n    eapply match_stacks_inside_extcall; eauto. xomega. \n    eapply agree_regs_incr; eauto. \n    destruct INCR; repeat open_Hyp. apply H3; assumption.\n    eapply range_private_extcall; eauto. red; xomega. \n    intros. apply SSZ2; auto. apply MAXPERM'; auto. red; xomega.\n    eapply match_stacks_untailcall; eauto. \n    eapply match_stacks_inside_extcall; eauto. xomega. \n    eapply range_private_extcall; eauto. red; xomega. \n    intros. apply SSZ2; auto. apply MAXPERM'; auto. red; xomega.\n    destruct INCR; repeat open_Hyp; apply H3; assumption.\n    assert (INCR': inject_incr Finj1 Finj2) by (apply INCR'; auto). \n    induction 1; intros.\n    eapply match_stacks_inside_base; eauto.\n    eapply match_stacks_extcall; eauto. xomega. \n    destruct INCR; repeat open_Hyp; apply H3; assumption.\n    eapply match_stacks_inside_inlined; eauto. \n    eapply agree_regs_incr; eauto.    \n    eapply (incre_local_of F1); auto.\n    destruct INCR; repeat open_Hyp; apply H4; assumption.\n    eapply range_private_extcall; eauto.\n  Qed.\n\nEnd EXTCALL.\n\n(*NEW*)\nSection MATCH_STACK_restrict_locals.\n  Variable mu : SM_Injection.\n  Variable m1 m2: mem.\n  Variable vals1 vals2 : list val.\n  Hypothesis WD : SM_wd mu.\n  Hypothesis PG: meminj_preserves_globals ge (as_inj mu).\n\n  Let mu1 := restrict_sm mu (fun b => locBlocksSrc mu b || \n                                                   frgnBlocksSrc mu b).\n  Let mu2 := \n    (replace_locals mu\n                    (fun b => locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b)\n                    (fun b => locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b)).\n  \n\n  Lemma MGE_restrict_local bnd: match_globalenvs  mu1 bnd ->\n                                match_globalenvs mu2 bnd.\n  Proof. intros.\n         inv H. econstructor; eauto.\n         intros. specialize (DOMAIN _ H).\n         unfold mu2. rewrite replace_locals_as_inj. (*replace_locals_frgnBlocksSrc. *)\n         (*split. unfold mu1 in H0. *) \n         (*rewrite restrict_sm_frgnBlocksSrc in H0. trivial. *)\n         (*unfold mu1 in H1. rewrite restrict_sm_all in H1.*)\n         unfold mu1 in DOMAIN. rewrite restrict_sm_all in DOMAIN.\n         apply (restrictD_Some _ _ _ _ _ DOMAIN).\n         intros. unfold mu2 in H. rewrite replace_locals_as_inj in H. \n         symmetry. eapply PG; eassumption. \n  Qed. \n\n  Lemma range_private_restrict_locals sp' n sz : forall\n                                                   (PRIV : range_private (as_inj mu1) m1 m2 sp' n sz)\n                                                   (SL : locBlocksTgt mu1 sp' = true),\n                                                   range_private (as_inj mu2) m1 m2 sp' n sz.\n  Proof. intros.\n         red; intros ? HH. destruct (PRIV _ HH). split;  trivial. \n         unfold mu2; rewrite replace_locals_as_inj.\n         unfold mu1 in H0; rewrite restrict_sm_all in H0. \n         intros. eapply (H0 b delta). \n         unfold mu1 in SL; rewrite restrict_sm_locBlocksTgt in SL.\n         apply restrictI_Some; trivial.\n         rewrite (as_inj_locBlocks _ _ _ _ WD H1), SL. trivial.\n  Qed.\n\n  Lemma agree_regs_restrict_locals rs rs' ctx: \n    agree_regs (as_inj mu1) ctx rs rs' ->\n    agree_regs (as_inj mu2) ctx rs rs'.\n  Proof. intros AG; destruct AG. \n         split; intros. \n         unfold mu2; rewrite replace_locals_as_inj. \n         eapply val_inject_incr; try eapply H. \n         unfold mu1; rewrite restrict_sm_all. apply restrict_incr.\n         trivial.\n         apply (H0 _ H1).\n  Qed.\n\n  Lemma match_stacks_restrict_locals:\n    forall stk stk' bnd,\n      match_stacks mu1 m1 m2 stk stk' bnd ->\n      match_stacks mu2 m1 m2 stk stk' bnd\n      with match_stacks_inside_restrict_locals:\n             forall stk stk' f' ctx sp' rs',\n               match_stacks_inside mu1 m1 m2 stk stk' f' ctx sp' rs' ->\n               match_stacks_inside mu2 m1 m2 stk stk' f' ctx sp' rs'.\n  Proof.\n    induction 1; intros.\n    { eapply match_stacks_nil; auto. \n      eapply MGE_restrict_local; eassumption. assumption. } \n    { eapply match_stacks_cons; eauto. \n      eapply agree_regs_restrict_locals; eassumption.\n      unfold mu2; rewrite replace_locals_as_inj.\n      unfold mu1 in SP; rewrite restrict_sm_all in SP.\n      eapply (restrictD_Some _ _ _ _ _ SP).\n      unfold mu2; rewrite replace_locals_locBlocksTgt.\n      unfold mu1 in SL; rewrite restrict_sm_locBlocksTgt in SL. trivial.\n      eapply range_private_restrict_locals; eassumption. }\n    { eapply match_stacks_untailcall; eauto. \n      eapply range_private_restrict_locals; eassumption. \n      unfold mu2; rewrite replace_locals_locBlocksTgt.\n      unfold mu1 in SL; rewrite restrict_sm_locBlocksTgt in SL. trivial. }\n\n    induction 1; intros.\n    { eapply match_stacks_inside_base; eauto.\n      unfold mu2; rewrite replace_locals_locBlocksTgt.\n      unfold mu1 in SL; rewrite restrict_sm_locBlocksTgt in SL. trivial. }\n    { eapply match_stacks_inside_inlined; eauto. \n      eapply agree_regs_restrict_locals; eassumption. \n      unfold mu2; rewrite replace_locals_local.\n      unfold mu1 in SP; rewrite restrict_sm_local in SP. \n      apply (restrictD_Some _ _ _ _ _ SP). \n      unfold mu2; rewrite replace_locals_locBlocksTgt.\n      unfold mu1 in SL; rewrite restrict_sm_locBlocksTgt in SL. trivial.\n      eapply range_private_restrict_locals; eassumption. }\n  Qed.\n\nEnd MATCH_STACK_restrict_locals. \n\n(** Change of context corresponding to an inlined tailcall *)\n\nLemma align_unchanged:\n  forall n amount, amount > 0 -> (amount | n) -> align n amount = n.\nProof.\n  intros. destruct H0 as [p EQ]. subst n. unfold align. decEq. \n  apply Zdiv_unique with (b := amount - 1). omega. omega.\nQed.\n\nLemma match_stacks_inside_inlined_tailcall:\n  forall F m m' stk stk' f' ctx sp' rs' ctx' f,\n    match_stacks_inside F m m' stk stk' f' ctx sp' rs' ->\n    context_below ctx ctx' ->\n    context_stack_tailcall ctx f ctx' ->\n    ctx'.(retinfo) = ctx.(retinfo) ->\n    range_private (as_inj F) m m' sp' ctx.(dstk) f'.(fn_stacksize) ->\n    tr_funbody fenv f'.(fn_stacksize) ctx' f f'.(fn_code) ->\n    match_stacks_inside F m m' stk stk' f' ctx' sp' rs'.\nProof.\n  intros. inv H.\n  (* base *)\n  eapply match_stacks_inside_base; eauto. congruence. \n  rewrite H1. rewrite DSTK. apply align_unchanged. apply min_alignment_pos. apply Zdivide_0.\n  (* inlined *)\n  assert (dstk ctx <= dstk ctx'). rewrite H1. apply align_le. apply min_alignment_pos.\n  eapply match_stacks_inside_inlined; eauto. \n  red; intros. destruct (zlt ofs (dstk ctx)). apply PAD; omega. apply H3. inv H4. xomega. \n  congruence. \n  unfold context_below in *. xomega.\n  unfold context_stack_call in *. omega. \nQed.\n\n(** ** Relating states *)\n\nInductive match_states:  SM_Injection -> RTL_core -> mem -> RTL_core -> mem -> Prop :=\n| match_regular_states: \n    forall mu stk f sp pc rs m stk' f' sp' rs' m' ctx\n           (MS: match_stacks_inside mu m m' stk stk' f' ctx sp' rs')\n           (FB: tr_funbody fenv f'.(fn_stacksize) ctx f f'.(fn_code))\n           (AG: agree_regs (as_inj mu) ctx rs rs')\n           (SP: (as_inj mu) sp = Some(sp', ctx.(dstk)))\n           (MINJ: Mem.inject (as_inj mu) m m')\n           (VB: Mem.valid_block m' sp')\n           (PRIV: range_private (as_inj mu) m m' sp' (ctx.(dstk) + ctx.(mstk)) f'.(fn_stacksize))\n           (SSZ1: 0 <= f'.(fn_stacksize) < Int.max_unsigned)\n           (SSZ2: forall ofs, Mem.perm m' sp' ofs Max Nonempty -> 0 <= ofs <= f'.(fn_stacksize)),\n      match_states mu (RTL_State stk f (Vptr sp Int.zero) pc rs) m\n                   (RTL_State stk' f' (Vptr sp' Int.zero) (spc ctx pc) rs') m'\n| match_call_states: \n    forall (mu: SM_Injection) stk fd args m stk' fd' args' m'\n           (MS: match_stacks mu m m' stk stk' (Mem.nextblock m'))\n           (FD: transf_fundef fenv fd = OK fd')\n           (VINJ: val_list_inject  (as_inj mu) args args')\n           (MINJ: Mem.inject (as_inj mu) m m'),\n      match_states mu (RTL_Callstate stk fd args) m\n                   (RTL_Callstate stk' fd' args') m'\n| match_call_regular_states: \n    forall (mu: SM_Injection) stk f vargs m stk' f' sp' rs' m' ctx ctx' pc' pc1' rargs\n           (MS: match_stacks_inside mu m m' stk stk' f' ctx sp' rs')\n           (FB: tr_funbody fenv f'.(fn_stacksize) ctx f f'.(fn_code))\n           (BELOW: context_below ctx' ctx)\n           (NOP: f'.(fn_code)!pc' = Some(Inop pc1'))\n           (MOVES: tr_moves f'.(fn_code) pc1' (sregs ctx' rargs) (sregs ctx f.(fn_params)) (spc ctx f.(fn_entrypoint)))\n           (VINJ: list_forall2 (val_reg_charact (as_inj mu) ctx' rs') vargs rargs)\n           (MINJ: Mem.inject (as_inj mu) m m')\n           (VB: Mem.valid_block m' sp')\n           (PRIV: range_private  (as_inj mu) m m' sp' ctx.(dstk) f'.(fn_stacksize))\n           (SSZ1: 0 <= f'.(fn_stacksize) < Int.max_unsigned)\n           (SSZ2: forall ofs, Mem.perm m' sp' ofs Max Nonempty -> 0 <= ofs <= f'.(fn_stacksize)),\n      match_states mu (RTL_Callstate stk (Internal f) vargs) m\n                   (RTL_State stk' f' (Vptr sp' Int.zero) pc' rs') m'\n| match_return_states: \n    forall (mu: SM_Injection) stk v m stk' v' m'\n           (MS: match_stacks mu m m' stk stk' (Mem.nextblock m'))\n           (VINJ: val_inject (as_inj mu) v v')\n           (MINJ: Mem.inject (as_inj mu) m m'),\n      match_states mu (RTL_Returnstate stk v) m\n                   (RTL_Returnstate stk' v') m'\n| match_return_regular_states: \n    forall (mu: SM_Injection)stk v m stk' f' sp' rs' m' ctx pc' or rinfo\n           (MS: match_stacks_inside mu m m' stk stk' f' ctx sp' rs')\n           (RET: ctx.(retinfo) = Some rinfo)\n           (AT: f'.(fn_code)!pc' = Some(inline_return ctx or rinfo))\n           (VINJ: match or with None => v = Vundef | Some r => val_inject (as_inj mu) v rs'#(sreg ctx r) end)\n           (MINJ: Mem.inject (as_inj mu) m m')\n           (VB: Mem.valid_block m' sp')\n           (PRIV: range_private (as_inj mu) m m' sp' ctx.(dstk) f'.(fn_stacksize))\n           (SSZ1: 0 <= f'.(fn_stacksize) < Int.max_unsigned)\n           (SSZ2: forall ofs, Mem.perm m' sp' ofs Max Nonempty -> 0 <= ofs <= f'.(fn_stacksize)),\n      match_states mu (RTL_Returnstate stk v) m\n                   (RTL_State stk' f' (Vptr sp' Int.zero) pc' rs') m'.\n\nDefinition MATCH (d:RTL_core) mu c1 m1 c2 m2:Prop :=\n  match_states (restrict_sm mu (vis mu)) c1 m1 c2 m2 /\\\n  REACH_closed m1 (vis mu) /\\\n  meminj_preserves_globals ge (as_inj mu) /\\\n  globalfunction_ptr_inject ge (as_inj mu) /\\\n  (forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true) /\\\n  sm_valid mu m1 m2 /\\\n  SM_wd mu /\\\n  Mem.inject (as_inj mu) m1 m2.\n\n(** ** Forward simulation *)\nDefinition RTL_measure (S: RTL_core) : nat :=\n  match S with\n    | RTL_State _ _ _ _ _ => 1%nat\n    | RTL_Callstate _ _ _ => 0%nat\n    | RTL_Returnstate _ _ => 0%nat\n  end.\n\n\nLemma tr_funbody_inv:\n  forall sz cts f c pc i,\n    tr_funbody fenv sz cts f c -> f.(fn_code)!pc = Some i -> tr_instr fenv sz cts pc i c.\nProof.\n  intros. inv H. eauto. \nQed.\n\n(*COMMENT: I'm suspicious about entry points. We might not need it.\n  COFRRECT: Not needed. Will remove. *)\nDefinition entry_points_ok entrypoints:= \n  forall (v1 v2 : val) (sig : signature),\n    In (v1, v2, sig) entrypoints -> \n    exists b f1 f2, \n      v1 = Vptr b Int.zero \n      /\\ v2 = Vptr b Int.zero\n      /\\ Genv.find_funct_ptr ge b = Some f1\n      /\\ Genv.find_funct_ptr tge b = Some f2.\n\n(*NEW*) Variable hf : I64Helpers.helper_functions.\n\n(*COMMENT: This lemma might belong in another file*)\nLemma forall_length: forall A B vals1 vals2 (F: A -> B -> Prop), Forall2 F vals1 vals2 -> Zlength vals1 = Zlength vals2.\n  Lemma forall_length_aux: forall A B vals1 vals2 (F: A -> B -> Prop), Forall2 F vals1 vals2 -> forall z, Zlength_aux z A vals1 = Zlength_aux z B vals2.\n    intros A B vals1 vals2 F HH.\n    induction HH.\n    reflexivity. \n    simpl; intros.\n    remember (Z.succ z) as z'.\n    apply IHHH.\n  Qed.\n  unfold Zlength; intros.\n  eapply forall_length_aux.\n  eassumption.\nQed.\n\n\n\n\nLemma MATCH_wd: forall (d : RTL_core) (mu : SM_Injection) (c1 : RTL_core) \n                       (m1 : mem) (c2 : RTL_core) (m2 : mem) (MC:MATCH d mu c1 m1 c2 m2), SM_wd mu.\n  intros. eapply MC. Qed.\nHint Resolve MATCH_wd: trans_correct.\nLemma MATCH_RC: forall (d : RTL_core) (mu : SM_Injection) (c1 : RTL_core) \n                       (m1 : mem) (c2 : RTL_core) (m2 : mem) (MC:\n                                                                MATCH d mu c1 m1 c2 m2), REACH_closed m1 (vis mu).\n  intros. eapply MC. Qed.\nHint Resolve MATCH_RC: trans_correct.\nLemma MATCH_restrict: forall (d : RTL_core) (mu : SM_Injection) (c1 : RTL_core) \n                             (m1 : mem) (c2 : RTL_core) (m2 : mem) (X : block -> bool) (MC: MATCH d mu c1 m1 c2 m2)(HX: forall b : block, vis mu b = true -> X b = true)(RC0:REACH_closed m1 X), MATCH d (restrict_sm mu X) c1 m1 c2 m2.\n  intros.\n  destruct MC as [MS [RC [PG [GF [Glob [SMV [WD INJ]]]]]]].\n  assert (WDR: SM_wd (restrict_sm mu X)).\n  apply restrict_sm_WD; assumption.\n  split; try rewrite vis_restrict_sm; try rewrite restrict_sm_all; try rewrite restrict_sm_frgnBlocksSrc.\n  rewrite restrict_sm_nest; assumption.\n  intuition.\n\n  (*meminj_preserves_globals*)\n  rewrite <- restrict_sm_all.\n  eapply restrict_sm_preserves_globals; auto.\n  intros.\n  apply HX.\n  unfold vis.\n  rewrite Glob; auto. \n  apply orb_true_r.\n\n  (* globalfunction_ptr_inject *)\n  apply restrict_preserves_globalfun_ptr. assumption.\n  intros b isGlob. apply HX. unfold vis. rewrite Glob; auto.\n  apply orb_true_r.\n  \n  (* sm_valid  *)\n  unfold sm_valid; split; intros;\n  red in SMV; destruct SMV as [H0 H1].\n  apply H0; unfold DOM; erewrite <- restrict_sm_DomSrc; eauto.\n  apply H1; unfold RNG; erewrite <- restrict_sm_DomTgt; eauto.\n  \n  (*  Mem.inject *)\n  apply inject_restrict; try assumption.\nQed.\nHint Resolve MATCH_restrict: trans_correct.\nLemma MATCH_valid:  forall (d : RTL_core) (mu : SM_Injection) (c1 : RTL_core) \n                           (m1 : mem) (c2 : RTL_core) (m2 : mem)\n                           (MC: MATCH d mu c1 m1 c2 m2), sm_valid mu m1 m2.\n  intros.\n  apply MC.\nQed.\nHint Resolve MATCH_valid: trans_correct.\nLemma MATCH_PG:  forall (d : RTL_core) (mu : SM_Injection) (c1 : RTL_core) \n                        (m1 : mem) (c2 : RTL_core) (m2 : mem)(\n                          MC: MATCH d mu c1 m1 c2 m2),\n                   meminj_preserves_globals ge (extern_of mu) /\\\n                   (forall b : block,\n                      isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true).\nProof.\n  intros.\n  assert (GF: forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true).\n  apply MC.\n  split; trivial.\n  rewrite <- match_genv_meminj_preserves_extern_iff_all; trivial.\n  apply MC. apply MC.\nQed.\nHint Resolve MATCH_PG: trans_correct.\n\nLemma MATCH_initial_core: \n  forall \n    (v : val) (vals1 : list val) (c1 : RTL_core) \n    (m1 : mem) (j : meminj) (vals2 : list val) (m2 : mem)\n    (DomS DomT : block -> bool)\n    (R : list_norepet (map fst (prog_defs SrcProg)))\n    (*entrypoints : list (val * val * signature)*)\n    (*entry_ok : entry_points_ok entrypoints*)\n    (*init_mem : exists m0 : mem, Genv.init_mem SrcProg = Some m0*)\n    (Ini: initial_core (rtl_eff_sem hf) ge v vals1 = Some c1)\n    (MINJ: Mem.inject j m1 m2)\n    (VInj: Forall2 (val_inject j) vals1 vals2)\n    (PG: meminj_preserves_globals ge j)\n    (J: forall (b1 b2 : block) (d : Z),\n          j b1 = Some (b2, d) -> DomS b1 = true /\\ DomT b2 = true)\n    (RCH:forall b : block,\n           REACH m2 (fun b' : block => isGlobalBlock tge b' || getBlocks vals2 b') b = true -> DomT b = true)\n    (*InitMem : exists m0 : mem, Genv.init_mem SrcProg = Some m0 \n                                /\\ Ple (Mem.nextblock m0) (Mem.nextblock m1)  (*Not needed/ Can remove just this one ineq*)\n                                /\\ Ple (Mem.nextblock m0) (Mem.nextblock m2)*)\n    (GFI: globalfunction_ptr_inject ge j)\n    (*GDE: genvs_domain_eq ge tge*)\n    (HDomS: forall b : block, DomS b = true -> Mem.valid_block m1 b)\n    (HDomT: forall b : block, DomT b = true -> Mem.valid_block m2 b),\n  exists c2 : RTL_core,\n    initial_core (rtl_eff_sem hf) tge v vals2 = Some c2 /\\\n    MATCH c1\n          (initial_SM DomS DomT\n                      (REACH m1\n                             (fun b : block => isGlobalBlock ge b || getBlocks vals1 b))\n                      (REACH m2\n                             (fun b : block => isGlobalBlock tge b || getBlocks vals2 b)) j)\n          c1 m1 c2 m2.\n\nProof. \n\n  intros.\n  inversion Ini.\n  unfold RTL_initial_core in H0. unfold ge in *. unfold tge in *.\n  destruct v; inv H0.\n  remember (Int.eq_dec i Int.zero) as z; destruct z; inv H1. clear Heqz.\n  remember (Genv.find_funct_ptr (Genv.globalenv SrcProg) b) as zz; destruct zz; inv H0. \n  apply eq_sym in Heqzz.\n  destruct f; try discriminate.\n  case_eq (val_casted.val_has_type_list_func vals1 \n                                             (sig_args (funsig (Internal f))) \n                                             && val_casted.vals_defined vals1).\n  2: solve[intros H2; rewrite H2 in H1; inv H1].\n  intros H2; rewrite H2 in H1. inv H1. \n  exploit function_ptr_translated; eauto. intros [tf [FP TF]].\n  exploit sig_function_translated; try eassumption. intros SIG.\n  assert (FF: exists f', tf = Internal f').\n  Errors.monadInv TF. eexists; reflexivity.\n  destruct FF as [f' ?]. subst tf.\n  unfold rtl_eff_sem, rtl_coop_sem. simpl.\n  case_eq (Int.eq_dec Int.zero Int.zero). intros ? e.\n  unfold tge in FP; rewrite FP. \n  assert (val_casted.val_has_type_list_func vals2 (sig_args (funsig (Internal f')))=true) as ->.\n  { eapply val_casted.val_list_inject_hastype; eauto.                                                                                  eapply forall_inject_val_list_inject; eauto.\n    destruct (val_casted.vals_defined vals1); auto.\n    rewrite andb_comm in H2; simpl in H2. solve[inv H2].\n    assert (sig_args (funsig (Internal f'))\n            = sig_args (funsig (Internal f))) as ->.\n    { rewrite SIG. simpl. reflexivity. }\n    destruct (val_casted.val_has_type_list_func vals1\n                                                (sig_args (funsig (Internal f)))); auto. }\n  assert (val_casted.vals_defined vals2=true) as ->.\n  { eapply val_casted.val_list_inject_defined.\n    eapply forall_inject_val_list_inject; eauto.\n    destruct (val_casted.vals_defined vals1); auto.\n    rewrite andb_comm in H2; inv H2. }\n  simpl. \n  eexists; split.\n  erewrite <- forall_length; eauto.\n  \n  destruct (proj_sumbool\n              (zlt\n                 match\n                   match Zlength vals1 with\n                     | 0 => 0\n                     | Z.pos y' => Z.pos y'~0\n                     | Z.neg y' => Z.neg y'~0\n                   end\n                 with\n                   | 0 => 0\n                   | Z.pos y' => Z.pos y'~0~0\n                   | Z.neg y' => Z.neg y'~0~0\n                 end Int.max_unsigned)); try discriminate.\n  reflexivity.\n\n  Focus 2.\n  intros CONTRA.\n  solve[elimtype False; auto].\n  clear e e0.\n  destruct (core_initial_wd ge tge _ _ _ _ _ _ _  MINJ\n                            VInj J RCH PG GDE_lemma HDomS HDomT _ (eq_refl _))\n    as [AA [BB [CC [DD [EE [FF GG]]]]]].\n  remember (val_casted.val_has_type_list_func vals1 (sig_args (funsig (Internal f))) &&\n                                              val_casted.vals_defined vals1) as vc.\n  destruct vc; inv H2.\n  split. \n  { specialize (Genv.find_funct_ptr_not_fresh SrcProg). intros FFP.\n    (*destruct init_mem as [m0 INIT_MEM].\n    specialize (FFP _ _ _ INIT_MEM Heqzz). \n    destruct (valid_init_is_global _ R _ INIT_MEM _ FFP) as [id Hid].*)\n    destruct (proj_sumbool\n                (zlt\n                   match\n                     match Zlength vals1 with\n                       | 0 => 0\n                       | Z.pos y' => Z.pos y'~0\n                       | Z.neg y' => Z.neg y'~0\n                     end\n                   with\n                     | 0 => 0\n                     | Z.pos y' => Z.pos y'~0~0\n                     | Z.neg y' => Z.neg y'~0~0\n                   end Int.max_unsigned)); try discriminate.\n    inv H0.\n    econstructor; try rewrite restrict_sm_all, initial_SM_as_inj.\n    2: assumption.\n    { clear GG FF. \n      econstructor; try rewrite restrict_sm_all, initial_SM_as_inj.\n\n      unfold initial_SM in *; simpl in *.\n      unfold vis; simpl.\n      clear CC DD Ini.\n      exploit @restrict_preserves_globals. eapply PG.\n      instantiate (1:=(fun b : block =>\n                         REACH m1 (fun b1 : block =>\n                                     isGlobalBlock (Genv.globalenv SrcProg) b1\n                                                   || getBlocks vals1 b1) b)).\n      simpl; intros. \n      apply EE; assumption.\n      intros PGR.\n      destruct PGR as [A [B CC]].\n\n\n      (*TODO: move*)\nLemma genv_next_symbol_exists' b (ge0 : genv) l :\n  list_norepet (map fst l) -> \n  (Plt b (Genv.genv_next ge0) ->\n    exists id, ~List.In id (map fst l) /\\ Genv.find_symbol ge0 id = Some b) -> \n  Plt b (Genv.genv_next (Genv.add_globals ge0 l)) ->\n  exists id, Genv.find_symbol (Genv.add_globals ge0 l) id = Some b.\nProof.\nrevert ge0 b.\ninduction l; simpl; auto.\nintros ge0 b ? ? H2.\ndestruct (H0 H2) as [? [? ?]].\nsolve[eexists; eauto].\nintros ge0 b H H2 H3.\ninv H.\ndestruct a; simpl in *.\neapply IHl; eauto.\nintros Hplt.\ndestruct (ident_eq b (Genv.genv_next ge0)). \n* subst b.\nexists i.\nunfold Genv.add_global, Genv.find_symbol; simpl.\nrewrite PTree.gss; auto.\n* unfold Genv.add_global, Genv.find_symbol; simpl.\ndestruct H2 as [x H2].\nunfold Genv.add_global in Hplt; simpl in Hplt; xomega.\nexists x.\ndestruct H2 as [A B].\nsplit; auto.\nrewrite PTree.gso; auto.\nQed.\n\nLemma genv_next_symbol_exists b :\n  list_norepet (map fst (prog_defs SrcProg)) -> \n  Plt b (Genv.genv_next ge) -> \n  exists id, Genv.find_symbol ge id = Some b.\nProof.\nintros Hnorepet H.\nexploit genv_next_symbol_exists'; eauto.\nsimpl; xomega.\nQed.\n\n      Lemma match_globalenvs_init2:\n        forall (R: list_norepet (map fst (prog_defs SrcProg))) j,\n          meminj_preserves_globals ge (as_inj j) ->\n          match_globalenvs j (Genv.genv_next ge).\n      Proof.\n        intros.\n        destruct H as [A [B C]].\n        constructor.\n        intros b D. \n        cut (exists id, Genv.find_symbol (Genv.globalenv SrcProg) id = Some b).\n        intros [id ID].\n        (*split. *)\n        solve[eapply A; eauto]. \n        exploit genv_next_symbol_exists; eauto.\n        intros. symmetry. solve [eapply (C _ _ _ _ GV); eauto].\n        intros. eapply Genv.genv_symb_range; eauto.\n        intros. eapply Genv.genv_funs_range; eauto.\n        intros. eapply Genv.genv_vars_range; eauto.\n      Qed.\n\n      apply match_globalenvs_init2; eauto.\n      unfold as_inj;  simpl.\n      Lemma restrict_empty: forall X, restrict (fun _ : block => None) X = (fun _ : block => None).\n      Proof. intros X. extensionality b. unfold restrict. destruct (X b); auto.\n      Qed.\n      Lemma join_empty: forall j, join j (fun _ : block => None) = j.\n        Proof. intros j. extensionality b. unfold join. destruct (j b) as [[b' d]|]; auto.\n      Qed. \n      rewrite restrict_empty, join_empty.\n      eapply restrict_preserves_globals.\n      assumption.\n      intuition.\n\n      Lemma genv_next_symbol_exists2 b :\n  list_norepet (map fst (prog_defs SrcProg)) -> \n  Psucc b = Genv.genv_next ge -> \n  exists id, Genv.find_symbol ge id = Some b.\nProof.\nintros Hnorepet H.\napply genv_next_symbol_exists; auto.\nxomega.\nQed.\n\n\n(*\n(*Ple (Genv.genv_next ge) (Mem.nextblock m1)*)\n{ destruct PG as [XX [Y Z]].\n    unfold Ple. rewrite <-Pos.leb_le.\n    destruct (Pos.leb (Genv.genv_next ge) (Mem.nextblock m1)) eqn:?; auto.\n    rewrite Pos.leb_nle in Heqb0.\n    assert (Heqb': (Genv.genv_next ge > Mem.nextblock m1)%positive) by xomega.\n    assert (exists b0, Psucc b0 = Genv.genv_next ge).\n    { destruct (Genv.genv_next ge). \n      exists ((b0~1)-1)%positive. simpl. auto.\n      exists (Pos.pred (b0~0))%positive. rewrite Pos.succ_pred. auto. xomega.\n      xomega. }\n    destruct H0 as [b0 H0].\n    generalize H0 as H'; intro.\n    \n    apply genv_next_symbol_exists2 in H0.\n    destruct H0 as [id H0].\n    apply XX in H0.\n    apply J in H0.\n    destruct H0 as [H0 H3].\n    specialize (HDomS _ H0).\n    unfold Mem.valid_block in HDomS. clear - Heqb' HDomS H'. xomega.\n    auto. }*)\n\n\n(*Ple (Genv.genv_next ge) (Mem.nextblock m2)*)\n      { destruct PG as [XX [Y Z]].\n    unfold Ple. rewrite <-Pos.leb_le.\n    destruct (Pos.leb (Genv.genv_next ge) (Mem.nextblock m2)) eqn:?; auto.\n    rewrite Pos.leb_nle in Heqb0.\n    assert (Heqb': (Genv.genv_next ge > Mem.nextblock m2)%positive) by xomega.\n    assert (exists b0, Psucc b0 = Genv.genv_next ge).\n    { destruct (Genv.genv_next ge). \n      exists ((b0~1)-1)%positive. simpl. auto.\n      exists (Pos.pred (b0~0))%positive. rewrite Pos.succ_pred. auto. xomega.\n      xomega. }\n    destruct H0 as [b0 H0].\n    generalize H0 as H'; intro.\n    apply genv_next_symbol_exists2 in H0.\n    destruct H0 as [id H0].\n    apply XX in H0.\n    apply J in H0.\n    destruct H0 as [H0 H3].\n    specialize (HDomT _ H3).\n    unfold Mem.valid_block in HDomT. clear - Heqb' HDomT H'. xomega.\n    auto. }\n\n\n    \n(**Ye Old Proof  \n      rewrite initial_SM_as_inj. assumption.\n      unfold as_inj; simpl.\n      constructor. \n      { (*DOMAIN*)\n        simpl. unfold as_inj; simpl.\n        intros b0 DD. \n        cut (exists id, Genv.find_symbol (Genv.globalenv SrcProg) id = Some b0).\n        intros [symb ID].\n         (*split. apply REACH_nil. rewrite (find_symbol_isGlobal _ _ _ ID). \n        trivial.*)\n        apply joinI. left.\n        eapply restrictI_Some. destruct PG. eapply H0; eassumption.\n        eapply REACH_nil.\n        erewrite find_symbol_isGlobal. trivial.\n        eassumption.\n        \n        eapply valid_init_is_global; eauto. }\n      { (*IMAGE*)\n        unfold as_inj; simpl.\n        intros.  symmetry. \n        destruct (joinD_Some _ _ _ _ _ H0).  \n        solve [eapply (CC _ _ _ _ GV); eauto].\n        destruct H3. destruct (restrictD_Some _ _ _ _ _ H4).\n        discriminate. }\n      { intros. eapply Genv.find_symbol_not_fresh; eauto. }\n      { intros. eapply Genv.find_funct_ptr_not_fresh ; eauto. }\n      { intros. eapply Genv.find_var_info_not_fresh; eauto. }\n      destruct InitMem as [m0' [INIT_MEM' [Ple1 Ple2]]].\n      rewrite INIT_MEM' in INIT_MEM. inversion INIT_MEM.\n      subst; auto.*)  }\n\n    unfold initial_SM, vis; simpl. \n    clear - VInj.\n    eapply forall_inject_val_list_inject.  \n    apply restrict_forall_vals_inject; try eassumption.\n    intros. apply REACH_nil. apply orb_true_iff; right. trivial.\n    eapply inject_restrict; eassumption. }\n\n  rewrite initial_SM_as_inj.\n  intuition.\nQed.\n\n\nLemma MATCH_halted: forall (cd : RTL_core) (mu : SM_Injection) (c1 : RTL_core) \n                           (m1 : mem) (c2 : RTL_core) (m2 : mem) (v1 : val)\n                           (MC: MATCH cd mu c1 m1 c2 m2)(HALT: halted (rtl_eff_sem hf) c1 = Some v1),\n                    exists v2 : val,\n                      Mem.inject (as_inj mu) m1 m2 /\\\n                      val_inject (restrict (as_inj mu) (vis mu)) v1 v2 /\\\n                      halted (rtl_eff_sem hf) c2 = Some v2.\nProof.\n  intros.\n  unfold MATCH in MC; destruct MC as [H0 H1].\n  inv H0; simpl in *; inv HALT. \n  inv MS. \n  exists v'; split; try assumption. eapply H1.\n\n  inv H0.\n  split; trivial.\n  rewrite <- restrict_sm_all; assumption.\n  inv H0.\n  inv MS0.\n  rewrite RET in RET0; inv RET0.\n  inv H0.\n  inv MS.\n  rewrite RET in RET0; inv RET0.\n  inv H0.\nQed.\nHint Resolve MATCH_halted: trans_correct.\nLemma MATCH_atExternal: \n  forall (mu : SM_Injection) \n         (c1 : RTL_core) (m1 : mem) \n         (c2 : RTL_core) (m2 : mem) \n         (e : external_function) \n         (vals1 : list val) \n         (ef_sig : signature)\n         (MC: MATCH c1 mu c1 m1 c2 m2) \n         (ATE: at_external (rtl_eff_sem hf) c1 = Some (e, ef_sig, vals1)),\n    Mem.inject (as_inj mu) m1 m2 /\\ \n    (exists vals2 : list val, Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2 /\\ at_external (rtl_eff_sem hf) c2 = Some (e, ef_sig, vals2) /\\\n                              (forall pubSrc' pubTgt' : block -> bool,\n                                 pubSrc' =\n                                 (fun b : block =>\n                                    locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b) ->\n                                 pubTgt' =\n                                 (fun b : block =>\n                                    locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b) ->\n                                 forall nu : SM_Injection,\n                                   nu = replace_locals mu pubSrc' pubTgt' ->\n                                   MATCH c1 nu c1 m1 c2 m2 /\\ Mem.inject (shared_of nu) m1 m2)).\n  intros.\n  split. inv MC; apply H0.\n  inv MC; simpl in *. inv H; inv ATE.\n  destruct H0 as [RC [ MPG [GFP [GLOB_FRGN [ SMV [ SMWD MINJ']]]]]].\n  destruct fd; inv H1. inv FD; simpl in *. \n  destruct (BuiltinEffects.observableEF_dec hf e0); inv H0.\n  exists args'.\n  split. apply val_list_inject_forall_inject.\n  autorewrite with restrict in VINJ; assumption.\n  split; intros.\n  trivial.\n  specialize (val_list_inject_forall_inject _ _ _ VINJ); intros ValsInj.\n  autorewrite with restrict in ValsInj.\n  specialize (forall_vals_inject_restrictD _ _ _ _ ValsInj); intros.\n  exploit replace_locals_wd_AtExternal; try eassumption.\n  intros SMWD_replace_locals.\n  subst.\n  split; auto. split; auto. \n  rewrite replace_locals_vis.\n  constructor; eauto.\n  apply match_stacks_replace_locals_restrict; auto.\n\n  rewrite restrict_sm_all, replace_locals_as_inj in *; auto.\n  rewrite restrict_sm_all, replace_locals_as_inj in *; auto.\n  \n  repeat open_Hyp.\n  split; auto.  solve[rewrite replace_locals_vis; auto ].\n  split; auto. solve[rewrite replace_locals_as_inj; auto].\n  Lemma globalfunction_ptr_inject_replace_locals: forall mu ls lt\n  (PG : globalfunction_ptr_inject ge (as_inj mu)),\n  globalfunction_ptr_inject ge (as_inj (replace_locals mu ls lt)).\n    unfold globalfunction_ptr_inject; intros.\n    rewrite replace_locals_as_inj.\n    eapply PG; eauto.\n  Qed.\n  split. apply globalfunction_ptr_inject_replace_locals; assumption.\n  split; auto. solve[rewrite replace_locals_frgnBlocksSrc; auto].\n  split. unfold sm_valid. rewrite replace_locals_DOM, replace_locals_RNG. assumption.\n  split; auto.\n  solve[rewrite replace_locals_as_inj; auto].\n  eapply inject_shared_replace_locals; eauto.\n  extensionality b; eauto.\n  extensionality b; eauto.\nQed.\nHint Resolve MATCH_atExternal: trans_correct.\n\n\nSection MS_RSI. (* Match Stacks: restricted Structured injections*)\n  Variable mu nu: SM_Injection.\n  Hypothesis WDmu : SM_wd mu.\n  Hypothesis WDnu : SM_wd nu.\n  Hypothesis PG: meminj_preserves_globals ge (as_inj mu).\n  Hypothesis INC: inject_incr (as_inj mu) (as_inj nu).\n  Variables X Y: block -> bool.\n  Hypothesis HX: forall b, vis mu b = true -> X b = true.\n  Hypothesis HY: forall b, vis nu b = true -> Y b = true.\n  Hypothesis H_mu_nu: forall b, vis mu b = true -> vis nu b = true.\n  Hypothesis HXY: inject_incr (restrict (local_of mu) X) \n                              (restrict (local_of nu) Y).\n  Hypothesis LBTmu: forall b, locBlocksTgt mu b = true ->\n                              locBlocksTgt nu b = true.\n  Variables m1 m1' m2 m2' :mem.\n  Variables PS PT: block -> bool.\n  Let muR:= replace_locals mu PS PT.\n  Hypothesis MAXPERM: forall b ofs p, Mem.valid_block m1 b -> Mem.perm m2 b ofs Max p -> Mem.perm m1 b ofs Max p.\n  Hypothesis MAXPERM': forall b ofs p, Mem.valid_block m1' b -> Mem.perm m2' b ofs Max p -> Mem.perm m1' b ofs Max p.\n  Hypothesis UNCHANGED: Mem.unchanged_on (local_out_of_reach muR m1) m1' m2'.\n\n  Let muV:= restrict_sm mu (vis mu).\n  Let nuY:= restrict_sm nu Y.\n  Hypothesis FrgnSrcPres: forall b, frgnBlocksSrc mu b = true ->\n                                    frgnBlocksSrc nu b = true.\n  \n  Hypothesis PGnu:  meminj_preserves_globals ge (as_inj nu).\n  (*Hypothesis SEP : globals_separate tge muR nu.*)\n  (*Hypothesis SEP: sm_inject_separated muR nu m1 m1'.*)\n\n  Hypothesis HAI: local_of mu = local_of nu.\n  Hypothesis SMVmu: sm_valid mu m1 m1'.\n\n  Lemma MGE_RSI bnd :\n    match_globalenvs muV bnd -> match_globalenvs nuY bnd.\n  Proof. intros.\n         inv H.\n         constructor; eauto.\n         intros. specialize (DOMAIN _ H).  (*\n         unfold muV in H0. rewrite restrict_sm_frgnBlocksSrc in H0.*)\n         unfold muV in DOMAIN. rewrite restrict_sm_all in DOMAIN.\n         unfold nuY. rewrite (*restrict_sm_frgnBlocksSrc,*) restrict_sm_all.\n         (*rewrite (FrgnSrcPres _ H0). \n         split. trivial.*)\n         destruct (restrictD_Some _ _ _ _ _ DOMAIN); clear DOMAIN.\n         apply restrictI_Some. eapply INC. trivial.\n         auto.\n\n         intros. symmetry. eapply PGnu; eauto.\n         unfold nuY in H. rewrite restrict_sm_all in H.\n         destruct (restrictD_Some _ _ _ _ _ H) as [AA BB]; exact AA.\n\n         (*YE Old version of the proof\n         intros. unfold nuY in H. rewrite restrict_sm_all in H. \n         destruct (restrictD_Some _ _ _ _ _ H); clear H. \n         remember (as_inj muV b1) as q. apply eq_sym in Heqq.\n         destruct q.\n         destruct p. unfold muV in Heqq.\n         rewrite restrict_sm_all in Heqq.\n         destruct (restrictD_Some _ _ _ _ _ Heqq); clear Heqq.\n         rewrite (INC _ _ _ H) in H1; inv H1.\n         eapply (IMAGE _ _ _ _ GV); trivial.\n         unfold muV; rewrite restrict_sm_all.\n         apply restrictI_Some; eassumption.\n         \n         assert (HH: as_inj muR b1 = None). \n         unfold muR. rewrite replace_locals_as_inj.\n         unfold muV in Heqq. rewrite restrict_sm_all in Heqq.\n         destruct (restrictD_None' _ _ _ Heqq); clear Heqq. trivial.\n         destruct H as [bb2 [dd [AI VIS]]].\n         specialize (INC _ _ _ AI). rewrite H1 in INC. inv INC.\n         destruct PG as [PGa [PGb PGc]]. \n         specialize (PGc _ _ _ _ GV AI). subst.\n         destruct (DOMAIN _ H0). unfold muV in H.\n         rewrite restrict_sm_frgnBlocksSrc in H.\n         unfold vis in VIS. rewrite H, orb_true_r in VIS.\n         discriminate.\n         \n         destruct PGnu as [PGa [PGb PGc]].\n         symmetry; eapply PGc; eauto.*)\n  Qed. \n\n  Lemma range_private_RSI sp' n sz : forall\n                                       (PRIV : range_private (as_inj muV) m1 m1' sp' n sz)\n                                       (SL : locBlocksTgt muV sp' = true),\n                                       range_private (as_inj nuY) m2 m2' sp' n sz.\n  Proof. intros.\n         red; intros ? HH. destruct (PRIV _ HH).\n         split. eapply UNCHANGED. red; intros. \n         unfold muV in SL; rewrite restrict_sm_locBlocksTgt in SL. \n         unfold muR. \n         split. rewrite replace_locals_locBlocksTgt. trivial. \n         rewrite replace_locals_local, replace_locals_pubBlocksSrc.\n         intros. left. eapply H0.\n         unfold muV; rewrite restrict_sm_all. \n         apply restrictI_Some.\n         apply local_in_all; eassumption.\n         unfold vis. destruct (local_DomRng _ WDmu _ _ _ H1); intuition.\n         eapply Mem.perm_valid_block; eassumption.\n         eassumption.\n         intros. intros N. \n         unfold nuY in H1; rewrite restrict_sm_all in H1.\n         unfold muV in SL; rewrite restrict_sm_locBlocksTgt in SL.\n         destruct (restrictD_Some _ _ _ _ _ H1); clear H1.\n         apply LBTmu in SL.\n         destruct (joinD_Some _ _ _ _ _ H2) as [EXT | [EXT LOC]]; clear H2.\n         destruct (extern_DomRng _ WDnu _ _ _ EXT).        \n         rewrite (extBlocksTgt_locBlocksTgt _ WDnu _ H2) in SL. \n         discriminate.\n         rewrite <- HAI in LOC.\n         apply MAXPERM in N. eapply (H0 b delta); trivial. \n         unfold muV; rewrite restrict_sm_all. \n         apply restrictI_Some. \n         apply local_in_all; eassumption. \n         unfold vis. destruct (local_DomRng _ WDmu _ _ _ LOC). \n         rewrite H1; trivial. \n         eapply SMVmu. apply local_in_all in LOC; trivial. \n         eapply (as_inj_DomRng _ _ _ _ LOC WDmu). \n  Qed.\n\n  Lemma agree_regs_RSI rs rs' ctx: \n    agree_regs (as_inj muV) ctx rs rs' ->\n    agree_regs (as_inj nuY) ctx rs rs'.\n  Proof. intros AG; destruct AG. \n         split; intros. \n         eapply val_inject_incr; try eapply H. \n         unfold nuY, muV; repeat rewrite restrict_sm_all. \n         red; intros.\n         destruct (restrictD_Some _ _ _ _ _ H2); clear H2.         \n         apply restrictI_Some; eauto. \n         trivial.\n         apply (H0 _ H1).\n  Qed.\n\n  Hypothesis BV: forall b1 b1' d, Mem.valid_block m1' b1' ->\n                                  as_inj nu b1 = Some(b1',d) -> Mem.valid_block m1 b1.\n  Lemma match_stacks_RSI: forall stk stk' bnd\n                                 (MS: match_stacks muV m1 m1' stk stk' bnd),\n                            match_stacks nuY m2 m2' stk stk' bnd\n                            with match_stacks_inside_RSI:\n                                   forall stk stk' f' ctx sp' rs',\n                                     match_stacks_inside muV m1 m1' stk stk' f' ctx sp' rs' ->\n                                     match_stacks_inside nuY m2 m2' stk stk' f' ctx sp' rs'.\n  Proof.\n    induction 1; intros.\n    { eapply match_stacks_nil; auto.\n      eapply MGE_RSI. eapply MG. \n      assumption. } \n    { eapply match_stacks_cons; eauto. \n      eapply agree_regs_RSI; eassumption.\n      unfold nuY; rewrite restrict_sm_all.\n      unfold muV in SP; rewrite restrict_sm_all in SP.\n      destruct (restrictD_Some _ _ _ _ _ SP).\n      eapply restrictI_Some; eauto.\n      unfold nuY; rewrite restrict_sm_locBlocksTgt.\n      unfold muV in SL; rewrite restrict_sm_locBlocksTgt in SL.\n      auto.  \n      eapply range_private_RSI; eassumption.\n      intros. apply MAXPERM' in H. apply (SSZ2 _ H).\n      eapply SMVmu. unfold muV in SL.\n      rewrite restrict_sm_locBlocksTgt in SL.\n      unfold RNG, DomTgt. rewrite SL; trivial. }\n    { eapply match_stacks_untailcall; eauto. \n      eapply range_private_RSI; try eassumption. \n      intros. apply MAXPERM' in H. apply (SSZ2 _ H). \n      eapply SMVmu. unfold muV in SL.\n      rewrite restrict_sm_locBlocksTgt in SL.\n      unfold RNG, DomTgt. rewrite SL; trivial. \n      unfold nuY; rewrite restrict_sm_locBlocksTgt.\n      unfold muV in SL; rewrite restrict_sm_locBlocksTgt in SL.\n      eauto. } \n\n    induction 1; intros.\n    { unfold muV in SL; rewrite restrict_sm_locBlocksTgt in SL. \n      eapply match_stacks_inside_base; eauto.\n      unfold nuY. rewrite restrict_sm_locBlocksTgt. auto. }\n    { eapply match_stacks_inside_inlined; eauto. \n      eapply agree_regs_RSI; try eassumption.\n      unfold nuY. rewrite restrict_sm_local. eapply HXY.\n      unfold muV in SP; rewrite restrict_sm_local in SP.\n      destruct (restrictD_Some _ _ _ _ _ SP). \n      apply restrictI_Some; trivial. auto. \n      unfold muV in SL; rewrite restrict_sm_locBlocksTgt in SL. \n      unfold nuY. rewrite restrict_sm_locBlocksTgt. auto.\n      \n      red; intros. destruct (PAD _ H0). \n      split; intros. \n      eapply UNCHANGED. \n      split; intros. \n      unfold muV in SL; rewrite restrict_sm_locBlocksTgt in SL.\n      unfold muR. rewrite replace_locals_locBlocksTgt. trivial.\n      unfold muR in H3. rewrite replace_locals_local in H3. \n      left. eapply H2. unfold muV. rewrite restrict_sm_all.\n      apply restrictI_Some. apply local_in_all; eassumption. \n      unfold vis. destruct (local_DomRng _ WDmu _ _ _ H3). \n      rewrite H4; trivial. \n      eapply Mem.perm_valid_block; eassumption.\n      assumption.\n\n\n      assert (VB: Mem.valid_block m1' sp'). \n      eapply Mem.perm_valid_block; eassumption. \n\n      unfold muV in SL. rewrite restrict_sm_locBlocksTgt in SL. \n      intros N. apply MAXPERM in N.\n      eapply H2; try eassumption. \n      unfold nuY in H3; rewrite restrict_sm_all in H3.\n      destruct (restrictD_Some _ _ _ _ _ H3); clear H3.\n      destruct (joinD_Some _ _ _ _ _ H4) as [EXT | [_ LOC]]; clear H4.\n      destruct (extern_DomRng _ WDnu _ _ _ EXT). \n      apply (extBlocksTgt_locBlocksTgt _ WDnu) in H4.\n      apply LBTmu in SL. rewrite SL in H4. discriminate.\n      unfold muV; rewrite restrict_sm_all.\n      rewrite <- HAI in LOC.\n      apply restrictI_Some.\n      apply local_in_all; try eassumption.\n      unfold vis. destruct (local_DomRng _ WDmu _ _ _ LOC).\n      rewrite H3; trivial.\n      apply Mem.perm_valid_block in H1.\n      assert (as_inj mu b = Some (sp', delta)).\n      {subst muV.\n       rewrite restrict_sm_local' in SP; eauto.\n       rewrite HAI in SP.\n       apply WDnu in SP. destruct SP as [locnusp Locnusp'].\n       assert (HH:= H3).\n       apply as_inj_locBlocks in H3.\n       unfold nuY in H3.\n       rewrite restrict_sm_locBlocksTgt, restrict_sm_locBlocksSrc in H3.\n       rewrite Locnusp' in H3.\n       unfold nuY in HH.\n       rewrite restrict_sm_all in HH.\n       unfold restrict in HH.\n       destruct (Y b); try discriminate.\n       rewrite locBlocksSrc_as_inj_local in HH; eauto.\n       rewrite <- HAI in HH.\n       unfold as_inj, join. \n       assert (HH':=HH).\n       apply WDmu in HH'; destruct HH' as [locmub ?].\n       destruct WDmu as [disjoint_Src WDmu'].\n       destruct (disjoint_Src b); try congruence.\n       destruct (extern_of mu b) eqn:extern_of_b; auto.\n       destruct p.\n       eapply WDmu in extern_of_b; destruct extern_of_b as [? ?].\n       congruence.\n       unfold nuY.\n       apply restrict_sm_WD; eauto.\n      }\n      apply SMVmu.\n      unfold DOM.\n      eapply as_inj_DomRng; eauto. }\n  Qed.\nEnd MS_RSI.\n\n(* OLD PROOF\nTheorem transl_program_correct:\n  forall (R: list_norepet (map fst (prog_defs SrcProg)))\n         (entrypoints : list (val * val * signature))\n         (entry_ok : entry_points_ok entrypoints)\n         (init_mem: exists m0, Genv.init_mem SrcProg = Some m0),\n    SM_simulation.SM_simulation_inject (rtl_eff_sem hf)\n                                       (rtl_eff_sem hf) ge tge (*entrypoints*).\n  intros.\n  (*eapply sepcomp.effect_simulations_lemmas.inj_simulation_star_wf.*)\n  eapply effect_simulations_lemmas.inj_simulation_star with (match_states:= MATCH)(measure:= RTL_measure).\n\n  Lemma environment_equality: (exists m0:mem, Genv.init_mem SrcProg = Some m0) -> \n                              genvs_domain_eq ge tge.\n    intros.\n    ad_it.\n    Qed.\n  (*\n    destruct H0 as [b0]; exists b0;\n    rewriter_back;\n    [rewrite symbols_preserved| rewrite <- symbols_preserved| rewrite varinfo_preserved| rewrite <- varinfo_preserved]; reflexivity.\n  Qed.*)\n  Hint Resolve environment_equality: trans_correct.\n  auto with trans_correct.\n\n  Lemma MATCH_wd: forall (d : RTL_core) (mu : SM_Injection) (c1 : RTL_core) \n                         (m1 : mem) (c2 : RTL_core) (m2 : mem) (MC:MATCH d mu c1 m1 c2 m2), SM_wd mu.\n    intros. eapply MC. Qed.\n  Hint Resolve MATCH_wd: trans_correct.\n  eauto with trans_correct.\n\n  Lemma MATCH_RC: forall (d : RTL_core) (mu : SM_Injection) (c1 : RTL_core) \n                         (m1 : mem) (c2 : RTL_core) (m2 : mem) (MC:\n                                                                  MATCH d mu c1 m1 c2 m2), REACH_closed m1 (vis mu).\n    intros. eapply MC. Qed.\n  Hint Resolve MATCH_RC: trans_correct.\n  eauto with trans_correct.\n\n\n  Lemma MATCH_restrict: forall (d : RTL_core) (mu : SM_Injection) (c1 : RTL_core) \n                               (m1 : mem) (c2 : RTL_core) (m2 : mem) (X : block -> bool) (MC: MATCH d mu c1 m1 c2 m2)(HX: forall b : block, vis mu b = true -> X b = true)(RC0:REACH_closed m1 X), MATCH d (restrict_sm mu X) c1 m1 c2 m2.\n    intros.\n    destruct MC as [MC [RC [PG [GF [VAL [WDmu INJ]]]]]].\n    assert (WDR: SM_wd (restrict_sm mu X)).\n    apply restrict_sm_WD; assumption.\n    split; try rewrite vis_restrict_sm; try rewrite restrict_sm_all; try rewrite restrict_sm_frgnBlocksSrc.\n    rewrite restrict_sm_nest; assumption.\n    intuition.\n\n    (*meminj_preserves_globals*)\n    rewrite <- restrict_sm_all.\n    eapply restrict_sm_preserves_globals; auto.\n    intros.\n    apply HX.\n    unfold vis.\n    rewrite GF; auto. \n    apply orb_true_r.\n\n    (* sm_valid  *)\n    unfold sm_valid; split; intros;\n    red in VAL; destruct VAL as [H0 H1].\n    apply H0; unfold DOM; erewrite <- restrict_sm_DomSrc; eauto.\n    apply H1; unfold RNG; erewrite <- restrict_sm_DomTgt; eauto.\n    \n    (*  Mem.inject *)\n    apply inject_restrict; try assumption.\n  Qed.\n\n  Hint Resolve MATCH_restrict: trans_correct.\n  auto with trans_correct.\n\n  Lemma MATCH_valid:  forall (d : RTL_core) (mu : SM_Injection) (c1 : RTL_core) \n                             (m1 : mem) (c2 : RTL_core) (m2 : mem)\n                             (MC: MATCH d mu c1 m1 c2 m2), sm_valid mu m1 m2.\n    intros.\n    apply MC.\n  Qed.\n\n  Hint Resolve MATCH_valid: trans_correct.\n  eauto with trans_correct.\n\n  (* Here there is a goal missing*)\n\n  Lemma MATCH_PG:  forall (d : RTL_core) (mu : SM_Injection) (c1 : RTL_core) \n                          (m1 : mem) (c2 : RTL_core) (m2 : mem)(\n                            MC: MATCH d mu c1 m1 c2 m2),\n                     meminj_preserves_globals ge (extern_of mu) /\\\n                     (forall b : block,\n                        isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true).\n  Proof.\n    intros.\n    assert (GF: forall b, isGlobalBlock ge b = true -> frgnBlocksSrc mu b = true).\n    apply MC.\n    split; trivial.\n    rewrite <- match_genv_meminj_preserves_extern_iff_all; trivial.\n    apply MC. apply MC.\n  Qed.\n  Hint Resolve MATCH_PG: trans_correct.\n  eauto with trans_correct.\n\n  Lemma Match_Halted: forall (cd : RTL_core) (mu : SM_Injection) (c1 : RTL_core) \n                             (m1 : mem) (c2 : RTL_core) (m2 : mem) (v1 : val)\n        (MC: MATCH cd mu c1 m1 c2 m2)(HALT: halted (rtl_eff_sem hf) c1 = Some v1),\n                      exists v2 : val,\n                        Mem.inject (as_inj mu) m1 m2 /\\\n                        val_inject (restrict (as_inj mu) (vis mu)) v1 v2 /\\\n                        halted (rtl_eff_sem hf) c2 = Some v2.\n  Proof.\n    intros.\n    unfold MATCH in MC; destruct MC as [H0 H1].\n    inv H0; simpl in *; inv HALT. \n    Print match_states.\n    inv MS. \n    exists v'; split; try assumption. eapply H1.\n\n    inv H0.\n    split; trivial.\n    rewrite <- restrict_sm_all; assumption.\n    inv H0.\n    inv MS0.\n    rewrite RET in RET0; inv RET0.\n    inv H0.\n    inv MS.\n    rewrite RET in RET0; inv RET0.\n    inv H0.\n  Qed.\n  Hint Resolve Match_Halted: trans_correct.\n  eauto with trans_correct.\n\n\n  Lemma at_external_lemma: forall (mu : SM_Injection) (c1 : RTL_core) (m1 : mem) \n                                  (c2 : RTL_core) (m2 : mem) (e : external_function) \n                                  (vals1 : list val) (ef_sig : signature)(MC: MATCH c1 mu c1 m1 c2 m2) (ATE: at_external (rtl_eff_sem hf) c1 = Some (e, ef_sig, vals1)),\n                             Mem.inject (as_inj mu) m1 m2 /\\ \n                             (exists vals2 : list val, Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2 /\\ at_external (rtl_eff_sem hf) c2 = Some (e, ef_sig, vals2)).\n    intros.\n    split. inv MC; apply H0.\n    inv MC; simpl in *. inv H; inv ATE.\n    destruct fd; inv H1. inv FD; simpl in *. \n    destruct (BuiltinEffects.observableEF_dec hf e0); inv H2.\n    exists args'.\n    split. apply val_list_inject_forall_inject.\n    autorewrite with restrict in VINJ; assumption.\n    trivial.\n  Qed.\n  Hint Resolve at_external_lemma: trans_correct.\n  eauto with trans_correct.\n\n  Lemma Match_AfterExternal: \n    forall (mu : SM_Injection) (st1 : RTL_core) (st2 : RTL_core) (m1 : mem) (e : external_function) (vals1 : list val) (m2 : mem) (ef_sig : signature) (vals2 : list val) (e' : external_function) (ef_sig' : signature) \n           (MemInjMu : Mem.inject (as_inj mu) m1 m2)\n           (MatchMu : MATCH st1 mu st1 m1 st2 m2)\n           (AtExtSrc : at_external (rtl_eff_sem hf) st1 = Some (e, ef_sig, vals1))\n           (AtExtTgt : at_external (rtl_eff_sem hf) st2 = Some (e', ef_sig', vals2))\n           (ValInjMu : Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n           (pubSrc' : block -> bool)\n           (pubSrcHyp : pubSrc' =\n                        (fun b : block =>\n                           locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b))\n           (pubTgt' : block -> bool)\n           (pubTgtHyp : pubTgt' =\n                        (fun b : block =>\n                           locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b))\n           (nu : SM_Injection)\n           (NuHyp : nu = replace_locals mu pubSrc' pubTgt')\n           (nu' : SM_Injection)\n           (ret1 : val)\n           (m1' : mem)\n           (ret2 : val)\n           (m2' : mem)\n           (INC : extern_incr nu nu')\n           (SEP : sm_inject_separated nu nu' m1 m2)\n           (WDnu' : SM_wd nu')\n           (SMvalNu' : sm_valid nu' m1' m2')\n           (MemInjNu' : Mem.inject (as_inj nu') m1' m2')\n           (RValInjNu' : val_inject (as_inj nu') ret1 ret2)\n           (FwdSrc : mem_forward m1 m1')\n           (FwdTgt : mem_forward m2 m2')\n           (frgnSrc' : block -> bool)\n           (frgnSrcHyp : frgnSrc' =\n                         (fun b : block =>\n                            DomSrc nu' b &&\n                                   (negb (locBlocksSrc nu' b) &&\n                                         REACH m1' (exportedSrc nu' (ret1 :: nil)) b)))\n           (frgnTgt' : block -> bool)\n           (frgnTgtHyp : frgnTgt' =\n                         (fun b : block =>\n                            DomTgt nu' b &&\n                                   (negb (locBlocksTgt nu' b) &&\n                                         REACH m2' (exportedTgt nu' (ret2 :: nil)) b)))\n           (mu' : SM_Injection)\n           (Mu'Hyp : mu' = replace_externs nu' frgnSrc' frgnTgt')\n           (UnchPrivSrc : Mem.unchanged_on\n                            (fun (b : block) (_ : Z) =>\n                               locBlocksSrc nu b = true /\\ pubBlocksSrc nu b = false) m1 m1')\n           (UnchLOOR : Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n    exists (st1' st2' : RTL_core),\n      after_external (rtl_eff_sem hf) (Some ret1) st1 = Some st1' /\\\n      after_external (rtl_eff_sem hf) (Some ret2) st2 = Some st2' /\\\n      MATCH st1' mu' st1' m1' st2' m2'.\n  Proof. intros. \n         destruct MatchMu as [MC [RC [PG [GF [VAL [WDmu [INJ GFP]]]]]]].\n         inv MC; simpl in *; inv AtExtSrc.\n         destruct fd; inv H0.\n         destruct fd'; inv AtExtTgt.\n         inv FD.\n         destruct (BuiltinEffects.observableEF_dec hf e1); inv H0; inv H1.\n         rename o into OBS.\n         exists (RTL_Returnstate stk ret1). eexists.\n         split. reflexivity.\n         split. reflexivity.\n         assert (INCvisNu': inject_incr\n                              (restrict (as_inj nu')\n                                        (vis\n                                           (replace_externs nu'\n                                                            (fun b : Values.block =>\n                                                               DomSrc nu' b &&\n                                                                      (negb (locBlocksSrc nu' b) &&\n                                                                            REACH m1' (exportedSrc nu' (ret1 :: nil)) b))\n                                                            (fun b : Values.block =>\n                                                               DomTgt nu' b &&\n                                                                      (negb (locBlocksTgt nu' b) &&\n                                                                            REACH m2' (exportedTgt nu' (ret2 :: nil)) b))))) (as_inj nu')).\n         unfold vis. rewrite replace_externs_frgnBlocksSrc, replace_externs_locBlocksSrc.\n         apply restrict_incr. \n         assert (RC': REACH_closed m1' (mapped (as_inj nu'))).\n         eapply inject_REACH_closed; eassumption.\n         assert (PHnu': meminj_preserves_globals (Genv.globalenv SrcProg) (as_inj nu')).\n         subst. clear - INC SEP PG GF WDmu WDnu'.\n         apply meminj_preserves_genv2blocks in PG.\n         destruct PG as [PGa [PGb PGc]].\n         apply meminj_preserves_genv2blocks.\n         split; intros.\n         specialize (PGa _ H).\n         apply joinI; left. apply INC.\n         rewrite replace_locals_extern.\n         apply foreign_in_extern.\n         assert (GG: isGlobalBlock ge b = true).\n         unfold isGlobalBlock, ge. apply genv2blocksBool_char1 in H.\n         rewrite H. trivial.\n         destruct (frgnSrc _ WDmu _ (GF _ GG)) as [bb2 [dd [FF FT2]]].\n         rewrite (foreign_in_all _ _ _ _ FF) in PGa. inv PGa.\n         assumption.\n         split; intros. specialize (PGb _ H).\n         apply joinI; left. apply INC.\n         rewrite replace_locals_extern. \n         assert (GG: isGlobalBlock ge b = true). (*4 goals*)\n         unfold isGlobalBlock, ge. apply genv2blocksBool_char2 in H.\n         rewrite H. intuition. (*3 goals*)\n         destruct (frgnSrc _ WDmu _ (GF _ GG)) as [bb2 [dd [FF FT2]]].\n         rewrite (foreign_in_all _ _ _ _ FF) in PGb. inv PGb.\n         apply foreign_in_extern; eassumption. (*2 goals*)\n         eapply (PGc _ _ delta H). specialize (PGb _ H). clear PGa PGc.\n         remember (as_inj mu b1) as d.\n         destruct d; apply eq_sym in Heqd. (*3 goals*)\n         destruct p. \n         apply extern_incr_as_inj in INC; trivial. (*3 goals*)\n         rewrite replace_locals_as_inj in INC.\n         rewrite (INC _ _ _ Heqd) in H0. trivial. (*3 goals*)\n         destruct SEP as [SEPa _].\n         rewrite replace_locals_as_inj, replace_locals_DomSrc, replace_locals_DomTgt in SEPa. \n         destruct (SEPa _ _ _ Heqd H0).\n         destruct (as_inj_DomRng _ _ _ _ PGb WDmu).\n         congruence. (*1 goal*)\n         assert (RR1: REACH_closed m1'\n                                   (fun b : Values.block =>  *)\nLemma Match_AfterExternal: \n  forall (mu : SM_Injection) (st1 : RTL_core) (st2 : RTL_core) (m1 : mem) (e : external_function) (vals1 : list val) (m2 : mem) (ef_sig : signature) (vals2 : list val) (e' : external_function) (ef_sig' : signature) \n         (MemInjMu : Mem.inject (as_inj mu) m1 m2)\n         (MatchMu : MATCH st1 mu st1 m1 st2 m2)\n         (AtExtSrc : at_external (rtl_eff_sem hf) st1 = Some (e, ef_sig, vals1))\n         (AtExtTgt : at_external (rtl_eff_sem hf) st2 = Some (e', ef_sig', vals2))\n         (ValInjMu : Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n         (pubSrc' : block -> bool)\n         (pubSrcHyp : pubSrc' =\n                      (fun b : block =>\n                         locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b))\n         (pubTgt' : block -> bool)\n         (pubTgtHyp : pubTgt' =\n                      (fun b : block =>\n                         locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b))\n         (nu : SM_Injection)\n         (NuHyp : nu = replace_locals mu pubSrc' pubTgt')\n         (nu' : SM_Injection)\n         (ret1 : val)\n         (m1' : mem)\n         (ret2 : val)\n         (m2' : mem)\n         (INC : extern_incr nu nu')\n         (SEP : globals_separate tge nu nu')\n         (WDnu' : SM_wd nu')\n         (SMvalNu' : sm_valid nu' m1' m2')\n         (MemInjNu' : Mem.inject (as_inj nu') m1' m2')\n         (RValInjNu' : val_inject (as_inj nu') ret1 ret2)\n         (FwdSrc : mem_forward m1 m1')\n         (FwdTgt : mem_forward m2 m2')\n         (frgnSrc' : block -> bool)\n         (frgnSrcHyp : frgnSrc' =\n                       (fun b : block =>\n                          DomSrc nu' b &&\n                                 (negb (locBlocksSrc nu' b) &&\n                                       REACH m1' (exportedSrc nu' (ret1 :: nil)) b)))\n         (frgnTgt' : block -> bool)\n         (frgnTgtHyp : frgnTgt' =\n                       (fun b : block =>\n                          DomTgt nu' b &&\n                                 (negb (locBlocksTgt nu' b) &&\n                                       REACH m2' (exportedTgt nu' (ret2 :: nil)) b)))\n         (mu' : SM_Injection)\n         (Mu'Hyp : mu' = replace_externs nu' frgnSrc' frgnTgt')\n         (UnchPrivSrc : Mem.unchanged_on\n                          (fun (b : block) (_ : Z) =>\n                             locBlocksSrc nu b = true /\\ pubBlocksSrc nu b = false) m1 m1')\n         (UnchLOOR : Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n  exists (st1' st2' : RTL_core),\n    after_external (rtl_eff_sem hf) (Some ret1) st1 = Some st1' /\\\n    after_external (rtl_eff_sem hf) (Some ret2) st2 = Some st2' /\\\n    MATCH st1' mu' st1' m1' st2' m2'.\nProof. intros. \n       destruct MatchMu as [MC [RC [PG [GFP [GF [VAL [WDmu INJ]]]]]]].\n       inv MC; simpl in *; inv AtExtSrc.\n       destruct fd; inv H0.\n       destruct fd'; inv AtExtTgt.\n       inv FD.\n       destruct (BuiltinEffects.observableEF_dec hf e1); inv H0; inv H1.\n       rename o into OBS.\n       exists (RTL_Returnstate stk ret1). eexists.\n       split. reflexivity.\n       split. reflexivity.\n       assert (INCvisNu': inject_incr\n                            (restrict (as_inj nu')\n                                      (vis\n                                         (replace_externs nu'\n                                                          (fun b : Values.block =>\n                                                             DomSrc nu' b &&\n                                                                    (negb (locBlocksSrc nu' b) &&\n                                                                          REACH m1' (exportedSrc nu' (ret1 :: nil)) b))\n                                                          (fun b : Values.block =>\n                                                             DomTgt nu' b &&\n                                                                    (negb (locBlocksTgt nu' b) &&\n                                                                          REACH m2' (exportedTgt nu' (ret2 :: nil)) b))))) (as_inj nu')).\n       (*unfold vis. rewrite replace_externs_frgnBlocksSrc, replace_externs_locBlocksSrc.*)\n       apply restrict_incr. \n       assert (RC': REACH_closed m1' (mapped (as_inj nu'))).\n       eapply inject_REACH_closed; eassumption.\n       assert (PGnu': meminj_preserves_globals (Genv.globalenv SrcProg) (as_inj nu')).\n       eapply meminj_preserves_globals_extern_incr_separate. eassumption.\n       rewrite replace_locals_as_inj. assumption.\n       assumption. \n\n       { (*Here is the only place SEP is used*)\n       specialize (genvs_domain_eq_isGlobal _ _ GDE_lemma). intros GL.\n       red. unfold ge in GL. rewrite GL. apply SEP.\n       } \n       clear SEP.\n       \n       assert (RR1: REACH_closed m1'\n                                 (fun b : Values.block =>\n                                    locBlocksSrc nu' b\n                                                 || DomSrc nu' b &&\n                                                 (negb (locBlocksSrc nu' b) &&\n                                                       REACH m1' (exportedSrc nu' (ret1 :: nil)) b))).\n       intros b Hb. rewrite REACHAX in Hb. destruct Hb as [L HL].\n       generalize dependent b.\n       induction L; simpl; intros; inv HL.\n       assumption.\n       specialize (IHL _ H1); clear H1.\n       apply orb_true_iff in IHL.\n       remember (locBlocksSrc nu' b') as l.\n       destruct l; apply eq_sym in Heql.\n       clear IHL.\n       remember (pubBlocksSrc nu' b') as p.\n       destruct p; apply eq_sym in Heqp.\n       assert (Rb': REACH m1' (mapped (as_inj nu')) b' = true).\n       apply REACH_nil. \n       destruct (pubSrc _ WDnu' _ Heqp) as [bb2 [dd1 [PUB PT]]].\n       eapply mappedI_true.\n       apply (pub_in_all _ WDnu' _ _ _ PUB).\n       assert (Rb:  REACH m1' (mapped (as_inj nu')) b = true).\n       eapply REACH_cons; try eassumption.\n       specialize (RC' _ Rb).\n       destruct (mappedD_true _ _ RC') as [[b2 d1] AI'].\n       remember (locBlocksSrc nu' b) as d.\n       destruct d; simpl; trivial.\n       apply andb_true_iff. \n       split. eapply as_inj_DomRng; try eassumption.\n       eapply REACH_cons; try eassumption.\n       apply REACH_nil. unfold exportedSrc.\n       rewrite (pubSrc_shared _ WDnu' _ Heqp). intuition.\n       destruct (UnchPrivSrc) as [UP UV]; clear UnchLOOR.\n       specialize (UP b' z Cur Readable). \n       specialize (UV b' z). \n       destruct INC as [_ [_ [_ [_ [LCnu' [_ [PBnu' [_ [FRGnu' _]]]]]]]]].\n       rewrite <- LCnu'. rewrite replace_locals_locBlocksSrc.  \n       rewrite <- LCnu' in Heql. rewrite replace_locals_locBlocksSrc in *.\n       rewrite <- PBnu' in Heqp. rewrite replace_locals_pubBlocksSrc in *.\n       clear INCvisNu'. \n       rewrite Heql in *. simpl in *. intuition.\n       assert (VB: Mem.valid_block m1 b').\n       eapply VAL. unfold DOM, DomSrc. rewrite Heql. intuition.\n       apply (H VB) in H2.\n       rewrite (H0 H2) in H4. clear H H0.\n       remember (locBlocksSrc mu b) as q.\n       destruct q; simpl; trivial; apply eq_sym in Heqq.\n       assert (Rb : REACH m1 (vis mu) b = true).\n       eapply REACH_cons; try eassumption.\n       apply REACH_nil. unfold vis. rewrite Heql; trivial.\n       specialize (RC _ Rb). unfold vis in RC.\n       rewrite Heqq in RC; simpl in *.\n       rewrite replace_locals_frgnBlocksSrc in FRGnu'.\n       rewrite FRGnu' in RC.\n       apply andb_true_iff.  \n       split. unfold DomSrc. rewrite (frgnBlocksSrc_extBlocksSrc _ WDnu' _ RC). intuition.\n       apply REACH_nil. unfold exportedSrc.\n       rewrite (frgnSrc_shared _ WDnu' _ RC). intuition.\n       destruct IHL. inv H.\n       apply andb_true_iff in H. simpl in H. \n       destruct H as[DomNu' Rb']. \n       clear INC INCvisNu' UnchLOOR UnchPrivSrc.\n       remember (locBlocksSrc nu' b) as d.\n       destruct d; simpl; trivial. apply eq_sym in Heqd.\n       apply andb_true_iff.\n       split. assert (RET: Forall2 (val_inject (as_inj nu')) (ret1::nil) (ret2::nil)).\n       constructor. assumption. constructor.\n       destruct (REACH_as_inj _ WDnu' _ _ _ _ MemInjNu' RET\n                              _ Rb' (fun b => true)) as [b2 [d1 [AI' _]]]; trivial.\n       assert (REACH m1' (mapped (as_inj nu')) b = true).\n       eapply REACH_cons; try eassumption.\n       apply REACH_nil. eapply mappedI_true; eassumption.\n       specialize (RC' _ H). \n       destruct (mappedD_true _ _ RC') as [[? ?] ?].\n       eapply as_inj_DomRng; eassumption.\n       eapply REACH_cons; try eassumption.\n       \n       assert (RRC: REACH_closed m1' (fun b : Values.block =>\n                                        mapped (as_inj nu') b &&\n                                               (locBlocksSrc nu' b\n                                                             || DomSrc nu' b &&\n                                                             (negb (locBlocksSrc nu' b) &&\n                                                                   REACH m1' (exportedSrc nu' (ret1 :: nil)) b)))).\n       eapply REACH_closed_intersection; eassumption.\n       assert (GFnu': forall b, isGlobalBlock (Genv.globalenv SrcProg) b = true ->\n                                DomSrc nu' b &&\n                                       (negb (locBlocksSrc nu' b) && REACH m1' (exportedSrc nu' (ret1 :: nil)) b) = true).\n       intros. specialize (GF _ H).\n       assert (FSRC:= extern_incr_frgnBlocksSrc _ _ INC).\n       rewrite replace_locals_frgnBlocksSrc in FSRC.\n       rewrite FSRC in GF.\n       rewrite (frgnBlocksSrc_locBlocksSrc _ WDnu' _ GF). \n       apply andb_true_iff; simpl.\n       split.\n       unfold DomSrc. rewrite (frgnBlocksSrc_extBlocksSrc _ WDnu' _ GF). intuition.\n       apply REACH_nil. unfold exportedSrc.\n       rewrite (frgnSrc_shared _ WDnu' _ GF). intuition.\n       rewrite restrict_sm_all in *.\n       exploit (eff_after_check1 mu); try eassumption; try reflexivity.\n       eapply val_list_inject_forall_inject.\n       eapply val_list_inject_incr; try eassumption.\n       apply restrict_incr.\n       intros [WDnu [SMVnu [MinjNu VinjNu]]].\n       assert (WDR: SM_wd (restrict_sm mu (vis mu))).\n       apply restrict_sm_WD; trivial.\n       destruct (eff_after_check2 _ _ _ _ _ MemInjNu' RValInjNu' \n                                  _ (eq_refl _) _ (eq_refl _) _ (eq_refl _) WDnu' SMvalNu').\n       assert (RRC1': REACH_closed m1'\n                                   (fun b : block =>\n                                      locBlocksSrc nu' b\n                                                   || DomSrc nu' b &&\n                                                   (negb (locBlocksSrc nu' b) &&\n                                                         REACH m1' (exportedSrc nu' (ret1 :: nil)) b))).\n       intuition.\n       assert (WDR': SM_wd\n                       (restrict_sm nu'\n                                    (fun b : block =>\n                                       locBlocksSrc nu' b\n                                                    || DomSrc nu' b &&\n                                                    (negb (locBlocksSrc nu' b) &&\n                                                          REACH m1' (exportedSrc nu' (ret1 :: nil)) b)))).\n       apply restrict_sm_WD.\n       assumption.\n       intros. unfold vis in H1.\n       destruct (locBlocksSrc nu' b); simpl in *; trivial. \n       apply andb_true_iff; split. \n       unfold DomSrc.\n       rewrite (frgnBlocksSrc_extBlocksSrc _ WDnu' _ H1).\n       intuition.\n       apply REACH_nil. unfold exportedSrc.\n       rewrite sharedSrc_iff_frgnpub, H1. intuition. trivial. \n\n       split.\n       Focus 2. unfold vis in *.\n       rewrite replace_externs_locBlocksSrc, replace_externs_frgnBlocksSrc,\n       replace_externs_as_inj in *. intuition.\n\n       (* globalfunction_ptr_inject *)\n       unfold globalfunction_ptr_inject; intros.\n       apply GFP in H1; destruct H1.\n       split; auto.\n\n       move INC at bottom.\n       apply extern_incr_as_inj in INC; auto.\n       rewrite replace_locals_as_inj in INC.\n       apply INC; assumption.\n       \n       \n       econstructor; try rewrite restrict_sm_all; try eassumption.\n\n       {(*Match_stacks*)\n         clear UnchPrivSrc OBS INCvisNu'. \n         eapply match_stacks_bound. instantiate (1:=Mem.nextblock m2).\n         2: eapply forward_nextblock; eassumption.\n         eapply match_stacks_RSI.\n         15: eapply MS.\n         11: eapply UnchLOOR.\n         assumption.  \n         assumption.  \n(*         assumption.  *)\n         rewrite replace_externs_as_inj. \n         apply extern_incr_as_inj in INC. \n         rewrite replace_locals_as_inj in INC; assumption. \n         assumption. \n         instantiate (1:= vis mu). trivial.\n         trivial. \n         rewrite replace_externs_vis. intros.\n         exploit extern_incr_vis; try eassumption.\n         rewrite replace_locals_vis; intros. rewrite H2 in H1.\n         clear H2.\n         unfold vis in H1. remember (locBlocksSrc nu' b) as q.    \n         destruct q; simpl in *; trivial.\n         apply andb_true_iff; split.\n         unfold DomSrc. \n         rewrite (frgnBlocksSrc_extBlocksSrc _ WDnu' _ H1). \n         intuition. \n         apply REACH_nil. unfold exportedSrc. \n         rewrite sharedSrc_iff_frgnpub, H1; trivial.\n         intuition. \n         rewrite replace_externs_local, replace_externs_vis.\n         assert (LOC: local_of mu = local_of nu').\n         red in INC. rewrite replace_locals_local in INC. \n         eapply INC.\n         rewrite <- LOC in *. \n         red; intros ? ? ? Hb. \n         destruct (restrictD_Some _ _ _ _ _ Hb); clear Hb.\n         apply restrictI_Some; trivial.\n         destruct (local_DomRng _ WDmu _ _ _ H1) as [lS _].\n         assert (LS: locBlocksSrc mu = locBlocksSrc nu').\n         red in INC. \n         rewrite replace_locals_locBlocksSrc in INC. \n         eapply INC.\n         rewrite <- LS, lS. trivial.\n         rewrite replace_externs_locBlocksTgt. \n         assert (LOC: locBlocksTgt mu = locBlocksTgt nu').\n         red in INC. \n         rewrite replace_locals_locBlocksTgt in INC. \n         eapply INC.\n         rewrite LOC; trivial. \n         intros. eapply FwdSrc; eassumption.\n         intros. eapply FwdTgt; eassumption.\n\n         (*Tried replace_externs_meminj_preserves_globals_as_inj*)\n         rewrite replace_externs_as_inj.\n         assumption.\n         \n         (*rewrite replace_externs_frgnBlocksSrc.\n         intros. unfold DomSrc. \n         assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc nu').\n         red in INC. \n         rewrite replace_locals_frgnBlocksSrc in INC. \n         apply INC.\n         rewrite FRG in H1.\n         specialize (frgnBlocksSrc_extBlocksSrc _ WDnu' _ H1).\n         intros EE.\n         rewrite (extBlocksSrc_locBlocksSrc _ WDnu' b), EE; simpl.\n         apply REACH_nil. apply orb_true_iff. right. \n         apply frgnSrc_shared; trivial. \n         trivial.\n         clear - PGnu'. red.\n\n         rewrite replace_externs_as_inj in *; assumption. *)\n         \n         rewrite replace_externs_local. \n         red in INC. rewrite replace_locals_local in INC.\n         eapply INC.\n         assumption. }\n       rewrite replace_externs_as_inj, replace_externs_vis. \n       clear - RValInjNu' WDnu'.\n       inv RValInjNu'; econstructor; eauto.\n       apply restrictI_Some; trivial.\n       destruct (locBlocksSrc nu' b1); simpl; trivial.\n       destruct (as_inj_DomRng _ _ _ _ H WDnu') as [dS dT].\n       rewrite dS; simpl.\n       apply REACH_nil. unfold exportedSrc.\n       apply orb_true_iff; left.\n       apply getBlocks_char. exists ofs1; left; eauto.\n       rewrite replace_externs_as_inj, replace_externs_vis.\n       eapply inject_restrict; try eassumption.\nQed.\nHint Resolve Match_AfterExternal: trans_correct.\n\n(*Some handy lemmas:*)\nLemma as_inj_retrict: forall mu b1 b2 d,\n                        as_inj (restrict_sm mu (vis mu)) b1 = Some (b2, d) ->\n                        as_inj mu b1 = Some (b2, d).\n  intros; autorewrite with restrict in H.\n  unfold restrict in H; destruct (vis mu b1) eqn:eq; inv H; auto.\nQed.\n\nLemma local_of_loc_inj: forall mu b b' delta (WD: SM_wd mu) (loc: locBlocksTgt mu b' = true), as_inj  mu b = Some (b', delta) -> local_of mu b = Some (b', delta).\n    unfold as_inj. unfold join. \n    intros.\n    destruct WD.\n    destruct (extern_of mu b) eqn:extern_mu_b; try assumption.\n    destruct p. inv H.\n    apply extern_DomRng in extern_mu_b.\n    destruct extern_mu_b as [extDom  extRng].\n    destruct (disjoint_extern_local_Tgt b'); [rewrite loc in H | rewrite extRng in H]; discriminate. \n  Qed.\n\nLemma alloc_local_restrict: forall mu mu' m1 m2 m1' m2' sp' f' (A : Mem.alloc m2 0 (fn_stacksize f') = (m2', sp')) (H15 : sm_locally_allocated mu mu' m1 m2 m1' m2') (SP: sp' = Mem.nextblock m2), locBlocksTgt (restrict_sm mu' (vis mu')) sp' = true.\n    intros.\n    unfold sm_locally_allocated in H15.\n    destruct mu.\n    destruct mu'; simpl in *.\n    intuition.\n    rewrite H1.\n    assert (fl: freshloc m2 m2' sp' = true).\n    unfold freshloc.\n    assert (vb: ~ Mem.valid_block m2 sp').\n    unfold Mem.valid_block.\n    subst sp'.\n    xomega.\n    assert (vb': Mem.valid_block m2' sp').\n    unfold Mem.valid_block.\n    (*erewrite (Mem.nextblock_alloc m2 _ _ m2' sp').*)\n    rewrite (Mem.nextblock_alloc m2 0 (fn_stacksize f') m2' sp').\n    subst sp'.\n    xomega.\n    subst sp'.\n    exact A.\n    destruct (valid_block_dec m2' sp'); destruct (valid_block_dec m2 sp'); intuition.\n    rewrite fl; apply orb_true_r.\nQed.\n\nLemma allocated_is_local: \n  forall mu mu' stk m1 m1' m2 m2' f,  \n    Mem.alloc m1 0 (fn_stacksize f) = (m1', stk) ->\n    sm_locally_allocated mu mu' m1 m2 m1' m2' ->\n    locBlocksSrc mu' stk = true. \n  intros  mu mu' stk m1 m1' m2 m2' f H1 H2.\n  rewrite (Mem.alloc_result _ _ _ _ stk H1).\n  rewrite (Mem.alloc_result _ _ _ _ stk H1) in H1.\n  unfold sm_locally_allocated in H2.\n  destruct mu; destruct mu'; simpl in *.\n  intuition.\n  rewrite H.\n  assert (fl: freshloc m1 m1' (Mem.nextblock m1) = true).\n  unfold freshloc.\n  assert (vb: ~ Mem.valid_block m1 (Mem.nextblock m1)).\n  unfold Mem.valid_block.\n  xomega.\n  assert (vb': Mem.valid_block m1' (Mem.nextblock m1)).\n  unfold Mem.valid_block.\n  rewrite (Mem.nextblock_alloc m1 0 (fn_stacksize f) m1' (Mem.nextblock m1)).\n  xomega.\n  auto.\n  destruct (valid_block_dec m1' (Mem.nextblock m1)); destruct (valid_block_dec m1 (Mem.nextblock m1)); intuition.\n  rewrite fl; apply orb_true_r.\nQed.\n\nLemma freshalloc_restricted_map: \n  forall mu mu' stk m1 m1' m2 m2' f sp' delta,\n    Mem.alloc m1 0 (fn_stacksize f) = (m1', stk) ->\n    sm_locally_allocated mu mu' m1 m2 m1' m2' ->\n    as_inj mu' stk = Some (sp', delta) ->\n    as_inj (restrict_sm mu' (vis mu')) stk = Some (sp', delta).\n  intros mu mu' stk m1 m1' m2 m2' f sp' delta alloc loc_alloc map.\n  autorewrite with restrict.\n  unfold restrict.\n  rewrite map.\n  unfold vis.\n  erewrite allocated_is_local; eauto.\nQed.\n\nLemma intern_incr_localloc_vis: forall mu mu' m1 m2 m1' m2',\n                                  intern_incr mu mu' ->\n                                  sm_locally_allocated mu mu' m1 m2 m1' m2' ->\n                                  forall b, vis mu' b = vis mu b || freshloc m1 m1' b.\n  unfold sm_locally_allocated, intern_incr, vis.\n  intros; destruct mu, mu'; simpl in *.\n  repeat open_Hyp.\n  rewrite H0. rewrite H9.\n  repeat rewrite <- orb_assoc.\n  f_equal.\n  apply orb_comm.\nQed.\n\n(* OLD VERSION\n    apply (meminj_preserves_incr_sep ge (as_inj mu) H9 m1 m2); eauto.\n    apply intern_incr_as_inj; auto.\n    apply sm_inject_separated_mem; auto.\n\n    eapply intern_incr_meminj_preserves_globals_as_inj in H17.\n    destruct H17 as [H00 H01]; apply H01; auto.\n    eexact H20.\n    exact H12.\n    split; eauto.\n    assumption.\n\n\n(* internal function, inlined *)\ninversion FB; subst.\nrepeat open_Hyp.\nexploit alloc_left_mapped_sm_inject; try eassumption.\n(* sp' is local *)\ndestruct MS0; unfold locBlocksTgt in SL; unfold restrict_sm in SL; destruct mu; simpl in *; assumption.\n(* offset is representable *)\ninstantiate (1 := dstk ctx). generalize (Zmax2 (fn_stacksize f) 0). omega.\n(* size of target block is representable *)\nintros. right. exploit SSZ2; eauto with mem. inv FB; omega.\n(* we have full permissions on sp' at and above dstk ctx *)\nintros. apply Mem.perm_cur. apply Mem.perm_implies with Freeable; auto with mem.\neapply range_private_perms; eauto. xomega.\n(* offset is aligned *)\nreplace (fn_stacksize f - 0) with (fn_stacksize f) by omega.\ninv FB. apply min_alignment_sound; auto.\n(* nobody maps to (sp, dstk ctx...) *)\nEND OF OLD PART *)\n\nLemma injection_almost_equality_restrict: forall mu mu' m1 m2 m1' m2' stk f,\n                                            Mem.alloc m1 0 (fn_stacksize f) = (m1', stk) ->\n                                            intern_incr mu mu' ->\n                                            sm_locally_allocated mu mu' m1 m2 m1' m2' ->\n                                            (forall b : block, (b = stk -> False) -> \n                                                               as_inj mu' b = as_inj mu b) ->\n                                            forall b1 : block,\n                                              b1 <> stk ->\n                                              as_inj (restrict_sm mu' (vis mu')) b1 =\n                                              as_inj (restrict_sm mu (vis mu)) b1.\n\n\n  intros.\n  autorewrite with restrict.\n  unfold restrict.\n  erewrite intern_incr_localloc_vis; eauto.\n  erewrite (freshloc_alloc _ _ _ _ stk H).\n  destruct (eq_block b1 stk).\n  simpl. apply H3 in e; inversion e.\n  simpl; rewrite orb_false_r. rewrite H2; eauto.\nQed.\n\nLemma local_of_restrict_vis: \n  forall mu sp sp' delta,  \n    SM_wd mu -> \n    local_of (restrict_sm mu (vis mu)) sp = Some (sp', delta) -> \n    as_inj (restrict_sm mu (vis mu)) sp = Some (sp', delta).\n  intros mu sp sp' delta SMWD SP.\n  autorewrite with restrict.\n  unfold restrict.\n  rewrite restrict_sm_local in SP; auto.\n  unfold restrict in SP.\n  destruct (vis mu sp) eqn:vismusp; simpl in SP; try solve [inv SP].\n  unfold as_inj, join.\n  rewrite SP.\n  destruct (extern_of mu sp) eqn:extofmusp; simpl; auto. destruct p.\n  apply SMWD in extofmusp; apply SMWD in SP.\n  repeat open_Hyp.\n  destruct SMWD; specialize (disjoint_extern_local_Src sp);\n  destruct disjoint_extern_local_Src. \n  rewrite H3 in H1; inv H1.\n  rewrite H3 in H; inv H.\nQed.\n\nLemma loc_privete_restrict:\n  forall mu m1 m2 sp ofs,\n    SM_wd mu ->\n    locBlocksTgt (restrict_sm mu (vis mu)) sp = true ->\n    loc_private (as_inj (restrict_sm mu (vis mu))) m1 m2 sp ofs ->\n    loc_private (as_inj mu) m1 m2 sp ofs.\n  unfold loc_private; intros.\n  repeat open_Hyp.\n  split.\n  auto.\n  intros.\n  apply H2.\n  assert (SL': locBlocksTgt mu sp = true).\n  erewrite <- restrict_sm_locBlocksTgt. eassumption.\n  autorewrite with restrict; unfold restrict; unfold vis.\n  erewrite <- (as_inj_locBlocks) in SL'; eauto.\n  erewrite SL'; rewrite orb_true_l; eauto.\nQed.\n\nLtac extend_smart:=  let x := fresh \"x\" in extensionality x.\nLtac rewrite_freshloc := match goal with\n                           | H: (Mem.storev _ _ _ _ = Some _) |- _ => rewrite (storev_freshloc _ _ _ _ _ H)\n                           | H: (Mem.free _ _ _ _ = Some _) |- _ => apply freshloc_free in H; rewrite H\n                           | _ => try rewrite freshloc_irrefl\n                         end.\nLtac loc_alloc_solve := apply sm_locally_allocatedChar; repeat split; try extend_smart;\n                        try rewrite_freshloc; intuition.\n\nLemma Empty_Effect_implication: forall mu m1 (b0 : block) (ofs : Z),\n                                  EmptyEffect b0 ofs = true ->\n                                  visTgt mu b0 = true /\\\n                                  (locBlocksTgt mu b0 = false ->\n                                   exists (b1 : block) (delta1 : Z),\n                                     foreign_of mu b1 = Some (b0, delta1) /\\\n                                     EmptyEffect b1 (ofs - delta1) = true /\\\n                                     Mem.perm m1 b1 (ofs - delta1) Max Nonempty).\n  intros mu m1 b ofs empt;\n  unfold EmptyEffect in empt; inv empt.\nQed.\n\n\nLemma step_simulation_effect: forall (st1 : RTL_core) (m1 : mem) (st1' : RTL_core) \n                                     (m1' : mem) (U1 : block -> Z -> bool)\n                                     (ES: effstep (rtl_eff_sem hf) ge U1 st1 m1 st1' m1'),\n                              forall (st2 : RTL_core) (mu : SM_Injection) (m2 : mem)\n(*   (U2vis: forall (b : block) (ofs : Z), U1 b ofs = true -> vis mu b = true)*)\n(MC: MATCH st1 mu st1 m1 st2 m2),\n                              exists (st2' : RTL_core) (m2' : mem),\n                                (exists U2 : block -> Z -> bool,\n                                   (effstep_plus (rtl_eff_sem hf) tge U2 st2 m2 st2' m2' \\/\n                                    (RTL_measure st1' < RTL_measure st1)%nat /\\\n                                    effstep_star (rtl_eff_sem hf) tge U2 st2 m2 st2' m2') /\\\n                                   (forall (b : block) (ofs : Z),\n                                      U2 b ofs = true ->\n                                      visTgt mu b = true /\\\n                                      (locBlocksTgt mu b = false ->\n                                       exists (b1 : block) (delta1 : Z),\n                                         foreign_of mu b1 = Some (b, delta1) /\\\n                                         U1 b1 (ofs - delta1) = true /\\\n                                         Mem.perm m1 b1 (ofs - delta1) Max Nonempty))) /\\\n                                exists (mu' : SM_Injection),\n                                  intern_incr mu mu' /\\\n                                  (*sm_inject_separated mu mu' m1 m2 /\\*)\n                                  globals_separate ge mu mu' /\\\n                                  sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n                                  MATCH st1' mu' st1' m1' st2' m2'.\n  intros.\n  simpl in *.\n  destruct MC as [MS PRE].\n  inv ES;\n    inv MS.\n  (* Inop *)\n  { exploit tr_funbody_inv; eauto. intros TR; inv TR.\n  eexists. eexists. split.\n  eexists. split.\n\n  left; simpl.\n  eapply effstep_plus_one; simpl.\n  eapply rtl_effstep_exec_Inop. eassumption.\n  \n  apply Empty_Effect_implication.\n\n  exists mu.\n  intuition.\n\n  apply gsep_refl.\n  loc_alloc_solve.\n  unfold MATCH.\n  intuition.\n  eapply match_regular_states; first [eassumption| split; eassumption]. }\n\n  (* Iop *)\n  { exploit tr_funbody_inv; eauto. intros TR; inv TR.\n  repeat open_Hyp.\n  exploit eval_operation_inject. \n\n  { eapply (restrict_sm_preserves_globals _ _ (vis mu)). eauto.\n  intros; unfold vis; rewrite H6; trivial; rewrite orb_true_r; reflexivity. }\n  \n  exact SP.\n  instantiate (2 := rs##args). instantiate (1 := rs'##(sregs ctx args)). eapply agree_val_regs; eauto.\n  eexact MINJ. eauto.\n  fold (sop ctx op). intros [v' [A B]].\n  eexists. eexists.\n  split; simpl.\n  eexists. split.\n  \n  left; simpl.\n  eapply effstep_plus_one; simpl.\n\n  eapply rtl_effstep_exec_Iop. eassumption.\n  erewrite eval_operation_preserved; eauto.\n  exact symbols_preserved. \n\n  apply Empty_Effect_implication.\n\n  econstructor; eauto. \n  split; auto.\n  intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n  unfold MATCH.\n  intuition.\n  eapply match_regular_states; eauto.\n  apply match_stacks_inside_set_reg; auto.\n  eapply restrict_sm_WD; auto.\n  apply agree_set_reg; auto. }\n\n  (* Iload *)\n  { exploit tr_funbody_inv; eauto. intros TR; inv TR.\n  exploit eval_addressing_inject. \n  { destruct PRE as [A [B [C' [C D]]]]. eapply (restrict_sm_preserves_globals _ _ (vis mu)); eauto.\n  intros; unfold vis. rewrite C; trivial; rewrite orb_true_r; reflexivity. }\n  eexact SP.\n  instantiate (2 := rs##args). instantiate (1 := rs'##(sregs ctx args)). eapply agree_val_regs; eauto.\n  eauto.\n  fold (saddr ctx addr). intros [a' [P Q]].\n  exploit Mem.loadv_inject; eauto. intros [v' [U V]].\n  assert (eval_addressing tge (Vptr sp' Int.zero) (saddr ctx addr) rs' ## (sregs ctx args) = Some a').\n  rewrite <- P. apply eval_addressing_preserved. exact symbols_preserved.\n  eexists. eexists.\n  split; simpl. \n  eexists. split.\n\n  left; simpl.\n  eapply effstep_plus_one. \n  eapply rtl_effstep_exec_Iload; try eassumption.\n\n  apply Empty_Effect_implication.\n\n  exists mu.\n  intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n  unfold MATCH;\n    intuition.\n  eapply match_regular_states; eauto.\n  apply match_stacks_inside_set_reg; auto.\n  eapply restrict_sm_WD; auto.\n  apply agree_set_reg; auto. }\n  \n  (* Istore *)\n  { exploit tr_funbody_inv; eauto. intros TR; inv TR.\n  \n  destruct PRE as  [RC [PG [GFP [GF [SMV [WD INJ]]]]]].\n  exploit eval_addressing_inject.\n  { eapply (restrict_sm_preserves_globals _ _ (vis mu)); eauto.\n  intros; unfold vis. rewrite GF; trivial; rewrite orb_true_r; reflexivity. }\n  eexact SP.\n  instantiate (2 := rs##args). instantiate (1 := rs'##(sregs ctx args)). eapply agree_val_regs; eauto.\n  eauto.\n  fold saddr. intros [a' [P Q]].\n  exploit Mem.storev_mapped_inject. \n  eexact INJ.\n  eassumption.\n  eapply val_inject_incr; try eapply Q.\n  autorewrite with restrict.\n  apply restrict_incr.\n  eapply agree_val_reg; eauto.\n  eapply agree_regs_incr.\n  eassumption.\n  autorewrite with restrict.\n  apply restrict_incr.\n  \n  intros [m2' [U V]].\n  assert (eval_addressing tge (Vptr sp' Int.zero) (saddr ctx addr) rs' ## (sregs ctx args) = Some a').\n  rewrite <- P. apply eval_addressing_preserved. exact symbols_preserved.\n\n  eexists. eexists. split.\n  eexists. split.\n\n  left; simpl.\n  eapply effstep_plus_one. eapply rtl_effstep_exec_Istore; eauto.\n\n  destruct a; inv H1.\n  rewrite restrict_sm_all in Q. inv Q.\n  intuition.\n  apply StoreEffectD in H6. destruct H6 as [z [HI Ibounds]].\n  apply eq_sym in HI. inv HI.\n  eapply visPropagateR; eassumption. \n\n  eapply StoreEffect_PropagateLeft; try eassumption.\n  econstructor. eassumption. trivial.\n\n  exists mu.\n  intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n\n  destruct a; simpl in H1; try discriminate.\n  destruct a'; simpl in U; try discriminate.\n  assert (RC1': REACH_closed m1' (vis mu)).\n  eapply REACH_Store;\n    try eassumption.\n  inv Q.\n  autorewrite with restrict in H8.\n  eapply restrictD_Some.\n  eapply H8.\n  intros.\n  rewrite getBlocks_char in H5.\n  destruct H5. \n  destruct H5.\n  assert (val_inject (as_inj (restrict_sm mu (vis mu))) rs # src rs' # (sreg ctx src)).\n  eapply agree_val_reg; eauto.\n  rewrite H5 in H6.\n  inv H6.\n  autorewrite with restrict in H11.\n  eapply restrictD_Some.\n  eassumption.\n  simpl in H5.\n  contradiction.\n\n  unfold MATCH;\n    intuition.\n  (*match_states*)\n  econstructor; eauto.\n  eapply match_stacks_inside_store; eauto.\n  apply restrict_sm_WD; auto.\n  autorewrite with restrict; eapply inject_restrict; try eassumption.\n  \n  eapply Mem.store_valid_block_1; eauto.\n  eapply range_private_invariant; eauto.\n  intros; split; auto. eapply Mem.perm_store_2; eauto.\n  intros; eapply Mem.perm_store_1; eauto.\n  intros. eapply SSZ2. eapply Mem.perm_store_2; eauto.\n  inv H2.\n\n  (* sm_valid mu m1' m2' *)\n  split; intros. \n  eapply Mem.store_valid_block_1; try eassumption.\n  eapply SMV; assumption.\n  eapply Mem.store_valid_block_1; try eassumption.\n  eapply SMV; assumption. }\n  \n  (* Icall *)\n  {\n\n  exploit match_stacks_inside_globalenvs; eauto. intros [bound G].\n  exploit find_function_agree; eauto.\n  intros [fd' [A B]].\n  exploit tr_funbody_inv; eauto. intros TR. inv TR.\n\n  (* not inlined *)\n  {\n    destruct H as [RC [PG [GFP [Glob [SMV [WD MInj]]]]]].\n    Lemma find_function_translated:\n  forall ros ls f,\n  find_function ge ros ls = Some f ->\n  exists tf,\n  find_function tge ros ls = Some tf /\\ transf_fundef fenv f = OK tf.\nProof.\n  unfold find_function; intros; destruct ros; simpl.\n  apply functions_translated; auto.\n  rewrite symbols_preserved. destruct (Genv.find_symbol ge i).\n  apply function_ptr_translated; auto.\n  congruence.\nQed.\n  destruct (find_function_translated _ _ _ H0) as [AA [BB CC]].\n    eexists. eexists. split.\n  eexists. split.\n\n  left; simpl.\n\n  (*\n  Lemma functions_translated':\n      forall v f,\n        Genv.find_funct ge v = Some f ->\n        exists tf,\n          Genv.find_funct tge v = Some tf /\\ transf_fundef fenv f = OK tf.\n      eapply Genv.find_funct_transf_partial.\n      apply TRANSF.\n  Qed.*)\n  \n\n  \n  { eapply effstep_plus_one. eapply rtl_effstep_exec_Icall.\n    - eauto.\n    - generalize BB. unfold sros; destruct ros; eauto.\n    -  apply sig_function_translated. assumption. }\n\n\n  (*\nDefinition regset_inject: meminj -> regset -> regset -> Prop := \nfun (j : meminj) (rs rs' : regset) =>\nforall r : positive, val_inject j rs # r rs' # r.\n\n\n \nLemma regset_find_function_translated:\n  forall j ros rs rs' fd ctx,\n  meminj_preserves_globals ge j ->\n  globalfunction_ptr_inject ge j ->\n  regset_inject j rs rs' ->\n  find_function ge ros rs = Some fd ->\n    exists fd',\n      find_function tge (sros ctx ros) rs' = Some fd' /\\ transf_fundef fenv fd = OK fd'.\nProof.\n  intros until fd; destruct ros; simpl.\n  intros.\n  assert (RR: rs'#(sreg ctx r) = rs#(sreg ctx r)).\n    exploit Genv.find_funct_inv; eauto. intros [b EQ].\n    generalize (H1 r). rewrite EQ. intro LD. inv LD.\n    rewrite EQ in *; clear EQ.\n    rewrite Genv.find_funct_find_funct_ptr in H2.\n    apply H0 in H2. destruct H2. rewrite H2 in H6; inv H6.\n\n    Proof (Genv.find_funct_transf_partial transf_fundef _ TRANSF).\n    \n    rewrite Int.add_zero. trivial.\n    \n  rewrite RR. apply functions_translated; auto.\n  rewrite symbols_preserved. destruct (Genv.find_symbol ge i); intros.\n  apply funct_ptr_translated; auto.\n  discriminate. \n\n\n\n\n  Lemma regset_find_function_translated:\n  forall j ros rs rs' fd ctx,\n  meminj_preserves_globals ge j ->\n  globalfunction_ptr_inject ge j ->\n  agree_regs j ctx rs rs' ->\n  find_function ge ros rs = Some fd ->\n    exists fd',\n      find_function tge (sros ctx ros) rs' = Some fd' /\\ transf_fundef fenv fd = OK fd'.\n  Proof.\n    unfold find_function; intros; destruct ros; simpl.\n    apply functions_translated.\n    destruct (Genv.find_funct_inv _ _ H2) as [b Hb].\n    destruct H1 as [H1 _].\n    specialize (H1 r). rewrite Hb in *. inv H1.\n    rewrite Genv.find_funct_find_funct_ptr in H2.\n    destruct (H0 _ _ H2).\n    rewrite H1 in H6. inv H6.\n    rewrite Int.add_zero. assumption.\n  rewrite symbols_preserved. destruct (Genv.find_symbol ge i).\n  apply function_ptr_translated; auto.\n  congruence.\nQed.\n  \n  unfold find_function; intros; destruct ros; simpl.\n  apply functions_translated.\n   destruct (Genv.find_funct_inv _ _ H2) as [b Hb].\n   destruct H1 as [AG1 AG2]. \n   specialize (AG1 r). rewrite Hb in *. inv AG1.\n    rewrite Genv.find_funct_find_funct_ptr in H2.\n    destruct (H0 _ _ H2). rewrite H1 in H6. inv H6.\n    rewrite Int.add_zero.  \n    rewrite Genv.find_funct_find_funct_ptr. assumption.\n  \n  rewrite symbols_preserved. destruct (Genv.find_symbol ge i).\n  apply function_ptr_translated; auto.\n  congruence.\nQed.\n\n\n  forall ros rs fd F ctx rs' bound,\n    find_function ge ros rs = Some fd ->\n    agree_regs (as_inj F) ctx rs rs' ->\n    match_globalenvs F bound ->\n    exists fd',\n      find_function tge (sros ctx ros) rs' = Some fd' /\\ transf_fundef fenv fd = OK fd'.\n  \n  simpl.\n  eapply sig_function_translated; eauto. *)\n\n  apply Empty_Effect_implication.\n  \n  exists mu.\n  intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n\n  unfold MATCH.\n  split.\n  econstructor; eauto.\n  eapply match_stacks_cons; eauto.\n  destruct MS0; assumption.\n  eapply agree_val_regs; eauto.   \n  intuition. }\n\n  (* inlined *)\n  { assert (fd = Internal f0).\n  simpl in H0. destruct (Genv.find_symbol ge id) as [b|] eqn:?; try discriminate.\n  exploit (funenv_program_compat SrcProg). \n  try eassumption. eauto. intros. \n  unfold ge in H0. congruence.\n  subst fd.\n  \n  eexists. eexists. split.\n  eexists. split.\n  right; split; simpl. \n  omega.\n  eapply effstep_star_zero.\n  intuition.\n  \n  exists mu.\n  intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n\n  unfold MATCH;\n    intuition.\n  Focus 1.\n  eapply match_call_regular_states; eauto. (* match_call_regular_states*)\n  assert (SL: locBlocksTgt (restrict_sm mu (vis mu)) sp' = true) by (destruct MS0; assumption).\n  eapply match_stacks_inside_inlined; eauto.\n  \n  apply local_of_loc_inj; auto;\n  try (apply restrict_sm_WD); auto.\n  \n  red; intros. apply PRIV. inv H13. destruct H16.\n  xomega.\n  apply agree_val_regs_gen; auto.\n  red; intros; apply PRIV. destruct H16. omega. } }\n\n  (* Itailcall *)\n  { exploit match_stacks_inside_globalenvs; eauto. intros [bound G].\n  exploit find_function_agree; eauto. intros [fd' [A B]].\n  assert (PRIV': range_private (as_inj (restrict_sm mu (vis mu))) m1' m2 sp' (dstk ctx) f'.(fn_stacksize)).\n  eapply range_private_free_left; eauto. \n  inv FB. rewrite <- H4. auto.\n  exploit tr_funbody_inv; eauto.\n  intros TR. \n  inv TR.\n\n  (* within the original function *)\n  { inv MS0; try congruence.\n\n  assert (X: { m1' | Mem.free m2 sp' 0 (fn_stacksize f') = Some m1'}).\n  apply Mem.range_perm_free. red; intros.\n  destruct (zlt ofs f.(fn_stacksize)). \n  replace ofs with (ofs + dstk ctx) by omega. eapply Mem.perm_inject; eauto.\n  eapply Mem.free_range_perm; eauto. omega.\n  inv FB. eapply range_private_perms; eauto. xomega.\n  destruct X as [m2' FREE].\n  \n  eexists. eexists. split.\n  eexists. split.\n  left; simpl.\n  eapply effstep_plus_one. eapply rtl_effstep_exec_Itailcall; eauto.\n  eapply sig_function_translated; eauto.\n\n  rewrite restrict_sm_all in SP.\n  destruct (restrictD_Some _ _ _ _ _ SP).\n  intuition.\n  apply FreeEffectD in H14.\n  destruct H14; subst. \n  eapply visPropagate; try eassumption.\n  eapply FreeEffect_PropagateLeft; try eassumption.\n  eapply as_inj_retrict; autorewrite with restrict; rewrite <- DSTK; eassumption.\n  \n  apply FreeEffectD in H14.\n  destruct H14 as [? [? ?]]; subst. \n  rewrite restrict_sm_locBlocksTgt in *.\n  rewrite SL in H16. inversion H16.\n  \n  exists mu.\n  intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n  \n  assert (Mem.inject (as_inj mu) m1' m2').\n  eapply Mem.free_right_inject. eapply Mem.free_left_inject. eapply H13.\n  eassumption.\n  eassumption.\n\n  intros. rewrite DSTK in PRIV'. exploit (PRIV' (ofs + delta)). omega. intros [P Q]. \n  eelim Q.\n  autorewrite with restrict.\n  eapply restrictI_Some.\n  eapply H12.\n  rewrite restrict_sm_locBlocksTgt in SL.\n  erewrite <- (as_inj_locBlocks _ b1 sp') in SL; try eassumption.\n  unfold vis.\n  rewrite SL.\n  eapply orb_true_l.\n  replace (ofs + delta - delta) with ofs by omega.\n  apply Mem.perm_max with k. apply Mem.perm_implies with p; auto with mem.\n\n  unfold MATCH.\n  intuition.\n  econstructor; eauto.\n  eapply match_stacks_bound with (bound := sp'). \n  eapply match_stacks_invariant; eauto.\n  apply restrict_sm_WD; auto.\n  intros. eapply Mem.perm_free_3; eauto. \n  intros. eapply Mem.perm_free_1; eauto. \n  intros. eapply Mem.perm_free_3; eauto.\n  erewrite Mem.nextblock_free; eauto. red in VB; xomega.\n  eapply agree_val_regs; eauto.\n  eapply Mem.free_right_inject; eauto. eapply Mem.free_left_inject; eauto.\n  (* show that no valid location points into the stack block being freed *)\n  intros. rewrite DSTK in PRIV'. exploit (PRIV' (ofs + delta)). omega. intros [P Q]. \n  eelim Q; eauto. replace (ofs + delta - delta) with ofs by omega. \n  apply Mem.perm_max with k. apply Mem.perm_implies with p; auto with mem.\n  eapply REACH_closed_free; eauto.\n  (* sm_valid mu m1' m2' *)\n  split; intros. \n  eapply Mem.valid_block_free_1; try eassumption.\n  eapply H10; assumption.\n  eapply Mem.valid_block_free_1; try eassumption.\n  eapply H10; assumption. }\n\n  (* turned into a call *)\n  { eexists. eexists. split.\n  eexists. split.\n  left; simpl. \n  eapply effstep_plus_one. eapply rtl_effstep_exec_Icall; eauto.\n  eapply sig_function_translated; eauto.\n\n  intros b ofs empt;\n    unfold EmptyEffect in empt; inv empt.\n  \n  exists mu.\n  intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n\n  unfold MATCH.\n  intuition.\n  econstructor; eauto.\n  eapply match_stacks_untailcall; eauto.\n  eapply match_stacks_inside_invariant; eauto. \n  apply restrict_sm_WD; auto.\n  intros. eapply Mem.perm_free_3; eauto.\n  destruct MS0; assumption.\n  \n  eapply agree_val_regs; eauto.\n  eapply Mem.free_left_inject; eauto.\n  eapply REACH_closed_free; eauto.\n  \n  (*  sm_valid mu m1' m2 *)\n  split; intros. \n  eapply Mem.valid_block_free_1; try eassumption.\n  eapply H10; assumption.\n  eapply H10; assumption.\n  (*  Mem.inject (as_inj mu) m1' m2' *)\n  eapply Mem.free_left_inject; eauto. }\n\n  (* inlined *)\n  { assert (fd = Internal f0).\n  simpl in H0. destruct (Genv.find_symbol ge id) as [b|] eqn:?; try discriminate.\n  exploit (funenv_program_compat SrcProg); eauto. intros. \n  unfold ge in H0. congruence.\n  subst fd.\n  eexists. eexists. split.\n  eexists. split.\n  right; split. simpl; omega. \n  eapply effstep_star_zero.\n  intuition.\n\n  exists mu.\n  intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n\n  unfold MATCH;\n    intuition.\n  econstructor; eauto.\n  eapply match_stacks_inside_inlined_tailcall; eauto.\n  eapply match_stacks_inside_invariant; eauto.\n  apply restrict_sm_WD; auto.\n  intros. eapply Mem.perm_free_3; eauto.\n  apply agree_val_regs_gen; auto.\n  eapply Mem.free_left_inject; eauto.\n  red; intros; apply PRIV'. \n  assert (dstk ctx <= dstk ctx'). red in H14; rewrite H14. apply align_le. apply min_alignment_pos.\n  omega.\n  eapply REACH_closed_free; eauto.\n  (* sm_valid mu m1' m2 *)\n  split; intros.\n  eapply Mem.valid_block_free_1; try eassumption.\n  eapply H15; assumption.\n  eapply H15; assumption.\n  eapply Mem.free_left_inject; eauto. } }\n\n  { (* builtin*)\n    exploit tr_funbody_inv; eauto. intros TR; inv TR.\n    rename MINJ into MINJR.\n    destruct PRE as [RC [PG [GFP [Glob [SMV [WD MINJ]]]]]].\n    assert (PGR: meminj_preserves_globals ge (restrict (as_inj mu) (vis mu))).\n    rewrite <- restrict_sm_all.\n    eapply restrict_sm_preserves_globals; try eassumption.\n    unfold vis. intuition.\n    rewrite restrict_sm_all in *.\n    assert (ArgsInj:= agree_val_regs _ _ _ _ args AG).\n    exploit (BuiltinEffects.inlineable_extern_inject _ _ GDE_lemma);\n      (*try eapply H;*) try eassumption.\n    apply symbols_preserved. \n    intros [mu' [vres' [tm' [EC [VINJ [MINJ' [UNMAPPED [OUTOFREACH \n                                                          [INCR [SEPARATED [GSEP [LOCALLOC [WD' [VAL' RC']]]]]]]]]]]]]].\n    exists (RTL_State stk' f' (Vptr sp' Int.zero) (spc ctx pc')\n                      (rs'#(sreg ctx res) <- vres')), tm'.\n    split. eexists.\n    split. left. apply effstep_plus_one. \n    eapply rtl_effstep_exec_Ibuiltin; eauto. \n    intros. eapply BuiltinEffects.BuiltinEffect_Propagate; eassumption.\n    exists mu'. intuition.\n    assert (ISEP: inject_separated (restrict (as_inj mu) (vis mu))\n                                   (restrict (as_inj mu') (vis mu')) m1 m2).\n    red. intros ??? RAI RAI'.\n    destruct (restrictD_Some _ _ _ _ _ RAI')\n      as [AI' VIS']; clear RAI'.\n    destruct (restrictD_None' _ _ _ RAI) \n      as [AI | [bb2 [dd [AI VIS]]]]; clear RAI.\n    apply sm_inject_separated_mem in SEPARATED.\n    apply (SEPARATED _ _ _ AI AI'). trivial. \n    rewrite (intern_incr_vis_inv _ _ WD WD' \n                                 INCR _ _ _ AI VIS') in VIS; discriminate.\n    \n    split. \n    {  econstructor; eauto.\n       { eapply match_stacks_inside_set_reg.\n         apply restrict_sm_WD; trivial.  \n         eapply match_stacks_inside_extcall; try eapply MS0.\n         apply restrict_sm_WD; trivial.  \n         apply restrict_sm_WD; trivial.  \n         intros; eapply external_call_max_perm; eauto. \n         intros; eapply external_call_max_perm; eauto.\n         rewrite restrict_sm_all. apply OUTOFREACH.\n         rewrite restrict_sm_all. apply MINJR.\n         apply restrict_sm_intern_incr; trivial. \n         repeat rewrite restrict_sm_all; trivial.\n         clear - SMV. destruct SMV.\n         split; intros.\n         rewrite restrict_sm_DOM in H1. apply (H _ H1).\n         rewrite restrict_sm_RNG in H1. apply (H0 _ H1). \n         apply VB. }\n       rewrite restrict_sm_all. apply agree_set_reg; eauto.  \n       eapply agree_regs_incr; eauto. \n       apply (intern_incr_restrict _ _ WD' INCR).\n       rewrite restrict_sm_all. \n       apply (intern_incr_restrict _ _ WD' INCR). assumption.\n       rewrite restrict_sm_all. apply inject_restrict; assumption.\n       eapply external_call_mem_forward; try eassumption.\n       { rewrite restrict_sm_all.\n         eapply range_private_extcall; try eassumption.\n         intros. eapply external_call_mem_forward; eauto. \n         apply (intern_incr_restrict _ _ WD' INCR). }\n       intros. apply SSZ2. eapply external_call_max_perm; eauto. \n    }\n    intuition.\n    eapply meminj_preserves_incr_sep. eapply PG. eassumption. \n    apply intern_incr_as_inj; trivial.\n    apply sm_inject_separated_mem; eassumption.\n    (*globalfunction_ptr_inject ge (as_inj mu')*)\n      red; intros b fb Hb. destruct (GFP _ _ Hb).\n          split; trivial.\n          eapply intern_incr_as_inj; eassumption.\n\n    \n\n    assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INCR.\n    rewrite <- FRG. apply Glob; assumption. }\n\n  (* Icond *)\n\n  { exploit tr_funbody_inv; eauto. intros TR; inv TR.\n  assert (eval_condition cond rs'##(sregs ctx args) m2 = Some b).\n  eapply eval_condition_inject; eauto. eapply agree_val_regs; eauto. \n  \n  eexists. eexists. split; simpl.\n  eexists. split.\n  left; simpl.\n  eapply effstep_plus_one.\n  eapply rtl_effstep_exec_Icond; eauto.\n\n  apply Empty_Effect_implication.\n\n  exists mu. intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n\n  unfold MATCH.\n  intuition.\n  destruct b;\n    econstructor; eauto. }\n\n\n  (* jumptable *)\n  { exploit tr_funbody_inv; eauto. intros TR; inv TR.\n  assert (H3: val_inject (as_inj (restrict_sm mu (vis mu))) rs#arg rs'#(sreg ctx arg)). eapply agree_val_reg; eauto.\n  rewrite H0 in H3; inv H3.\n  \n  eexists. eexists. split; simpl.\n  eexists. split.\n  left.\n  eapply effstep_plus_one. eapply rtl_effstep_exec_Ijumptable; eauto.\n  rewrite list_nth_z_map. rewrite H1. simpl; reflexivity. \n  \n  apply Empty_Effect_implication.\n  \n  exists mu. intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n\n  unfold MATCH.\n  intuition.\n  econstructor; eauto. }\n\n\n  (* return *)\n  { exploit tr_funbody_inv; eauto. intros TR; inv TR.\n\n  (* not inlined *)\n  { inv MS0; try congruence.\n  assert (X: { m1' | Mem.free m2 sp' 0 (fn_stacksize f') = Some m1'}).\n  apply Mem.range_perm_free. red; intros.\n  destruct (zlt ofs f.(fn_stacksize)). \n  replace ofs with (ofs + dstk ctx) by omega. eapply Mem.perm_inject; eauto.\n  eapply Mem.free_range_perm; eauto. omega.\n  inv FB. eapply range_private_perms; eauto.\n  generalize (Zmax_spec (fn_stacksize f) 0). destruct (zlt 0 (fn_stacksize f)); omega.\n  destruct X as [m2' FREE].\n  \n  eexists. eexists. split.\n  eexists. split; simpl.\n  left.\n  eapply effstep_plus_one. eapply rtl_effstep_exec_Ireturn; eauto. \n\n  (*Here is the effect: return*)\n  rewrite restrict_sm_all in SP.\n  destruct (restrictD_Some _ _ _ _ _ SP).\n  destruct PRE as [RC [PG [GFP [Glob [SMV [WD MINJ']]]]]].\n  intuition.\n  apply FreeEffectD in H7.\n  destruct H7; subst. \n  eapply visPropagate; try eassumption.\n  eapply FreeEffect_PropagateLeft; try eassumption.\n  eapply as_inj_retrict; autorewrite with restrict; rewrite <- DSTK; eassumption.\n  \n  apply FreeEffectD in H7.\n  destruct H7 as [? [? ?]]; subst. \n  rewrite restrict_sm_locBlocksTgt in *.\n  rewrite SL in H8. inversion H8.\n\n  exists mu.\n  intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n\n  unfold MATCH;\n    intuition.\n  econstructor; eauto.\n  eapply match_stacks_bound with (bound := sp'). \n  eapply match_stacks_invariant; eauto.\n  apply restrict_sm_WD; auto.\n  intros. eapply Mem.perm_free_3; eauto. \n  intros. eapply Mem.perm_free_1; eauto. \n  intros. eapply Mem.perm_free_3; eauto.\n  erewrite Mem.nextblock_free; eauto. red in VB; xomega.\n  destruct or; simpl. apply agree_val_reg; auto. auto.\n\n  eapply Mem.free_right_inject; eauto. eapply Mem.free_left_inject; eauto.\n  (* show that no valid location points into the stack block being freed *)\n  intros. inversion FB; subst.\n  assert (PRIV': range_private (as_inj (restrict_sm mu (vis mu))) m1' m2 sp' (dstk ctx) f'.(fn_stacksize)).\n  rewrite H17 in PRIV. eapply range_private_free_left; eauto. \n  rewrite DSTK in PRIV'. exploit (PRIV' (ofs + delta)). omega. intros [A B]. \n  eelim B; eauto. replace (ofs + delta - delta) with ofs by omega. \n  apply Mem.perm_max with k. apply Mem.perm_implies with p; auto with mem.\n\n  eapply REACH_closed_free; eauto.\n\n  (*  sm_valid mu m1' m2 *)\n  split; intros.\n  eapply Mem.valid_block_free_1; try eassumption.\n  eapply H9; assumption.\n  eapply Mem.valid_block_free_1; try eassumption.\n  eapply H9; assumption.\n  eapply Mem.free_right_inject; eauto. eapply Mem.free_left_inject; eauto.\n  (* show that no valid location points into the stack block being freed *)\n  intros. inversion FB; subst.\n  assert (PRIV': range_private (as_inj (restrict_sm mu (vis mu))) m1' m2 sp' (dstk ctx) f'.(fn_stacksize)).\n  rewrite H17 in PRIV. eapply range_private_free_left; eauto. \n  rewrite DSTK in PRIV'. exploit (PRIV' (ofs + delta)). omega. intros [A B]. \n  eelim B. \n  autorewrite with restrict.\n  eapply restrictI_Some.\n  apply H11.\n  rewrite restrict_sm_locBlocksTgt in SL.\n  erewrite <- (as_inj_locBlocks _ b1 sp') in SL; try eassumption.\n  unfold vis.\n  rewrite SL.\n  eapply orb_true_l.\n  replace (ofs + delta - delta) with ofs by omega.\n  apply Mem.perm_max with k. apply Mem.perm_implies with p; auto with mem. }\n  \n  (* inlined *)\n  { eexists. eexists. split; simpl.\n  eexists. split.\n  right; split; simpl. omega.\n  \n  eapply effstep_star_zero.\n  intuition.\n  \n  exists mu.\n  intuition.\n  apply gsep_refl.\n  loc_alloc_solve. \n  \n  unfold MATCH;\n    intuition.\n  econstructor; eauto.\n  \n  \n  eapply match_stacks_inside_invariant; eauto. \n  apply restrict_sm_WD; auto.\n  intros. eapply Mem.perm_free_3; eauto.\n  destruct or; simpl. apply agree_val_reg; auto. auto.\n  eapply Mem.free_left_inject; eauto.\n  inv FB. subst.  rewrite H14 in PRIV. eapply range_private_free_left; eauto.\n  \n  eapply REACH_closed_free; eauto.\n  (*sm_valid*)\n  split; intros.\n  eapply Mem.valid_block_free_1; try eassumption.\n  eapply H9; assumption.\n  eapply H9; assumption.\n  (*  Mem.inject (as_inj mu) m1' m2 *)\n  eapply Mem.free_left_inject; eauto. } }\n\n\n\n\n  (* internal function, not inlined *)\n  { assert (A: exists f', tr_function fenv f f' /\\ fd' = Internal f'). \n  Errors.monadInv FD. exists x. split; auto. eapply transf_function_spec; eauto. \n  destruct A as [f' [TR EQ]]. inversion TR; subst.\n  repeat open_Hyp.\n  exploit alloc_parallel_intern; \n    eauto. apply Zle_refl. \n  instantiate (1 := fn_stacksize f'). inv H0. xomega.\n  intros [mu' [m2' [sp' [A [B [C [D E]]]]]]].\n  \n  eexists. eexists. split; simpl.\n  eexists.\n  split; simpl.\n  left.\n  eapply effstep_plus_one. eapply rtl_effstep_exec_function_internal; eauto.\n\n  apply Empty_Effect_implication.\n  \n  rewrite H4.\n  exists mu'. \n  intuition.\n  eapply intern_incr_globals_separate; eauto.\n  \n  unfold MATCH; intuition.\n  unfold globals_separate.\n  rewrite H5.\n  rewrite <- H4.\n  \n  eapply match_regular_states; eauto.\n  assert (SP: sp' = Mem.nextblock m2) by (eapply Mem.alloc_result; eauto).\n  apply match_stacks_inside_base.\n  rewrite <- SP in MS0. \n  eapply (match_stacks_invariant (restrict_sm mu (vis mu))); eauto.\n  eapply restrict_sm_intern_incr; auto.\n  eapply restrict_sm_WD; auto.\n  \n  intros. \n  destruct (eq_block b1 stk). \n  subst b1.\n  apply as_inj_retrict  in H21; rewrite D in H21; inv H21. subst b2. eelim Plt_strict; eauto.\n  rewrite <- H21.\n  autorewrite with restrict.\n  unfold restrict.\n  rewrite H15; auto.\n  assert (vis mu' b1 = true ).\n  destruct (vis mu' b1) eqn:vismu'b1; auto.\n  autorewrite with restrict in H21.\n  unfold restrict in H21.\n  rewrite vismu'b1 in H21; inv H21.\n  erewrite (intern_incr_vis_inv mu mu'); auto.\n  rewrite H23; auto.\n  rewrite <- H15; auto.\n  apply as_inj_retrict in H21; eassumption.\n  \n  intros. exploit Mem.perm_alloc_inv. eexact H. eauto. \n  destruct (eq_block b1 stk); intros; auto. \n  subst b1. apply as_inj_retrict in H21.\n  rewrite D in H21; inv H21. subst b2. eelim Plt_strict; eauto.  \n\n  intros. eapply Mem.perm_alloc_1; eauto. \n  intros. exploit Mem.perm_alloc_inv. eexact A. eauto. \n  rewrite dec_eq_false; auto.\n\n  \n  eapply alloc_local_restrict; eauto.\n\n  auto. auto. auto.\n  rewrite H4. apply agree_regs_init_regs.\n  eapply val_list_inject_incr.\n  autorewrite with restrict.\n  eapply intern_incr_restrict; try (apply C); auto.\n  autorewrite with restrict in VINJ; auto.\n  inv H0; auto. \n  \n\n  eapply freshalloc_restricted_map; eauto.\n  rewrite H1; auto.\n  \n  autorewrite with restrict.\n  apply inject_restrict; auto.\n\n  eapply Mem.valid_new_block; eauto.\n  red; intros. split.\n  eapply Mem.perm_alloc_2; eauto. inv H0; xomega.\n  intros; red; intros. exploit Mem.perm_alloc_inv. eexact H. eauto.\n  destruct (eq_block b stk); intros; apply as_inj_retrict in H22. \n  subst. \n  rewrite D in H22; inv H22. inv H0; xomega.\n  rewrite H15 in H22; auto. eelim Mem.fresh_block_alloc. eexact A.\n  eapply Mem.mi_mappedblocks.\n  apply H14.\n  apply H22.\n\n\n  intros.\n  exploit Mem.perm_alloc_3; eauto.\n  xomega.\n\n  apply (meminj_preserves_incr_sep ge (as_inj mu) H9 m1 m2); eauto.\n  apply intern_incr_as_inj; auto.\n  apply sm_inject_separated_mem; auto.\n\n  (*globalfunction_ptr_inject ge (as_inj mu')*)\n  red; intros b fb Hb. destruct (H10 _ _ Hb).\n  split; trivial.\n  eapply intern_incr_as_inj; eassumption.\n  \n\n  eapply intern_incr_meminj_preserves_globals_as_inj in H18.\n  destruct H18 as [H00 H01]; apply H01; auto.\n  eexact H21.\n  exact H13.\n  split; eauto.\n  assumption. }\n\n\n  (* internal function, inlined *)\n  { inversion FB; subst.\n  repeat open_Hyp.\n  exploit alloc_left_mapped_sm_inject; try eassumption.\n  (* sp' is local *)\n  destruct MS0; unfold locBlocksTgt in SL; unfold restrict_sm in SL; destruct mu; simpl in *; assumption.\n  (* offset is representable *)\n  instantiate (1 := dstk ctx). generalize (Zmax2 (fn_stacksize f) 0). omega.\n  (* size of target block is representable *)\n  intros. right. exploit SSZ2; eauto with mem. inv FB; omega.\n  (* we have full permissions on sp' at and above dstk ctx *)\n  intros. apply Mem.perm_cur. apply Mem.perm_implies with Freeable; auto with mem.\n  eapply range_private_perms; eauto. xomega.\n  (* offset is aligned *)\n  replace (fn_stacksize f - 0) with (fn_stacksize f) by omega.\n  inv FB. apply min_alignment_sound; auto.\n  (* nobody maps to (sp, dstk ctx...) *)\n  intros. exploit (PRIV (ofs + delta')); eauto. xomega.\n  intros [A B]. apply (B b delta'); eauto.\n  assert (SL': locBlocksTgt mu sp' = true).\n  destruct MS0; unfold locBlocksTgt in SL; unfold restrict_sm in SL; destruct mu; simpl in *; assumption.\n  rewrite <- (as_inj_locBlocks mu b sp' delta') in SL'; auto.\n  autorewrite with restrict.\n  unfold restrict; unfold vis.\n  rewrite SL'.\n  rewrite orb_true_l; simpl; assumption.\n  replace (ofs + delta' - delta') with ofs by omega.\n  apply Mem.perm_max with k. apply Mem.perm_implies with p; auto with mem.\n  intros [mu' [A [B [C D]]]].\n  exploit tr_moves_init_regs_eff; eauto. intros [rs'' [P [Q R]]].\n\n  eexists. eexists. split; simpl.\n  eexists. split; simpl. \n  left.\n\n  eapply effstep_plus_star_trans.\n  eapply effstep_plus_one. \n  eapply rtl_effstep_exec_Inop; eauto. \n  eapply P.\n\n  apply Empty_Effect_implication.\n\n  exists mu'; intuition.\n  eapply intern_incr_globals_separate; eauto.\n\n  (*First SEP*)\n\n  unfold MATCH; intuition.\n  \n  constructor; eauto.\n  assert (SM_wd (restrict_sm mu (vis mu))).\n  apply restrict_sm_WD; auto.\n  assert (SM_wd (restrict_sm mu' (vis mu'))).\n  apply restrict_sm_WD; auto.\n  eapply (match_stacks_inside_alloc_left (restrict_sm mu (vis mu))); eauto.\n  eapply match_stacks_inside_invariant; eauto.\n  eapply restrict_sm_intern_incr; eauto.\n  eapply freshalloc_restricted_map; eauto.\n\n  eapply injection_almost_equality_restrict; eauto.\n\n  omega.\n\n  apply agree_regs_incr with (as_inj (restrict_sm mu (vis mu))); auto.\n  apply intern_incr_as_inj; try apply restrict_sm_intern_incr; eauto.\n  apply restrict_sm_WD; auto.\n  eapply freshalloc_restricted_map; eauto.\n  autorewrite with restrict. \n  eapply inject_restrict; eauto.\n  rewrite H2. eapply range_private_alloc_left; eauto.\n  eapply freshalloc_restricted_map; eauto.\n\n\n  eapply injection_almost_equality_restrict; eauto.\n  eapply intern_incr_meminj_preserves_globals_as_inj with (mu0:=mu); eauto.\n\n\n\n  (*globalfunction_ptr_inject ge (as_inj mu')*)\n  red; intros b fb Hb. destruct (H10 _ _ Hb).\n  split; trivial.\n  eapply intern_incr_as_inj; eassumption.\n  \n  \n  \n  eapply intern_incr_meminj_preserves_globals_as_inj with (mu0:=mu); eauto. }\n\n  { (* nonobservable external call *)\n    rename MINJ into MINJR.\n    destruct PRE as [RC [PG [GFP [Glob [SMV [WD MINJ]]]]]].\n    assert (PGR: meminj_preserves_globals ge (restrict (as_inj mu) (vis mu))).\n    rewrite <- restrict_sm_all.\n    eapply restrict_sm_preserves_globals; try eassumption.\n    unfold vis. intuition.\n    rewrite restrict_sm_all in *.\n    simpl in FD. inv FD. \n    specialize (BuiltinEffects.EFhelpers _ _ OBS); intros.\n    exploit (BuiltinEffects.inlineable_extern_inject _ _ GDE_lemma);\n      try eapply H0; try eassumption.\n    apply symbols_preserved. \n    intros [mu' [vres' [tm' [EC [RESINJ [MINJ' [UNMAPPED [OUTOFREACH \n                                                            [INCR [SEPARATED [GSEP [LOCALLOC [WD' [VAL' RC']]]]]]]]]]]]]].\n    eexists; eexists. \n    split. eexists.\n    split. left. \n    eapply effstep_plus_one. \n    eapply rtl_effstep_exec_function_external; eauto.\n    intros. eapply BuiltinEffects.BuiltinEffect_Propagate; eassumption.\n    exists mu'. intuition.\n    assert (ISEP: inject_separated (restrict (as_inj mu) (vis mu))\n                                   (restrict (as_inj mu') (vis mu')) m1 m2).\n    red. intros ??? RAI RAI'.\n    destruct (restrictD_Some _ _ _ _ _ RAI')\n      as [AI' VIS']; clear RAI'.\n    destruct (restrictD_None' _ _ _ RAI) \n      as [AI | [bb2 [dd [AI VIS]]]]; clear RAI.\n    apply sm_inject_separated_mem in SEPARATED.\n    apply (SEPARATED _ _ _ AI AI'). trivial. \n    rewrite (intern_incr_vis_inv _ _ WD WD' \n                                 INCR _ _ _ AI VIS') in VIS; discriminate.\n    split. \n    {  econstructor; try solve[rewrite restrict_sm_all; eassumption].\n       { (*eapply match_stacks_inside_set_reg.\n            apply restrict_sm_WD; trivial.  *)\n         eapply match_stacks_bound.\n         eapply match_stacks_extcall. 10: eapply MS0.\n         apply restrict_sm_WD; trivial.  \n         apply restrict_sm_WD; trivial.  \n         intros; eapply external_call_max_perm; eauto. \n         intros; eapply external_call_max_perm; eauto.\n         rewrite restrict_sm_all. apply OUTOFREACH.\n         rewrite restrict_sm_all. apply MINJR.\n         apply restrict_sm_intern_incr; trivial. \n         repeat rewrite restrict_sm_all; trivial.\n         clear - SMV. destruct SMV.\n         split; intros.\n         rewrite restrict_sm_DOM in H1. apply (H _ H1).\n         rewrite restrict_sm_RNG in H1. apply (H0 _ H1). \n         xomega.\n         eapply forward_nextblock. \n         eapply external_call_mem_forward; eassumption. }\n       rewrite restrict_sm_all. apply inject_restrict; assumption.\n    }\n    intuition.\n    eapply meminj_preserves_incr_sep. eapply PG. eassumption. \n    apply intern_incr_as_inj; trivial.\n    apply sm_inject_separated_mem; eassumption.\n    \n\n  (*globalfunction_ptr_inject ge (as_inj mu')*)\n  red; intros b fb Hb. destruct (GFP _ _ Hb).\n  split; trivial.\n  eapply intern_incr_as_inj; eassumption.\n    \n    \n    assert (FRG: frgnBlocksSrc mu = frgnBlocksSrc mu') by eapply INCR.\n    rewrite <- FRG. apply Glob; assumption. }\n\n  (* return fron noninlined function *)\n  { inv MS0.\n  (* normal case *)\n  { eexists. eexists. split; simpl.\n  eexists. split; simpl.\n  left.\n  eapply effstep_plus_one. eapply rtl_effstep_exec_return.\n\n  apply Empty_Effect_implication.\n\n  exists mu. intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n\n  unfold MATCH; intuition.\n  econstructor; eauto. \n  apply match_stacks_inside_set_reg; auto. \n  apply restrict_sm_WD; auto.\n  apply agree_set_reg; auto. }\n\n  (* untailcall case *)\n  { inv MS; try congruence.\n  rewrite RET in RET0; inv RET0.\n  eexists. eexists. split; simpl.\n  eexists. split.\n  left.\n  eapply effstep_plus_one. eapply rtl_effstep_exec_return.\n\n  apply Empty_Effect_implication.\n\n  exists mu. intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n\n\n  unfold MATCH. intuition.\n  eapply match_regular_states; eauto. \n  eapply match_stacks_inside_set_reg; eauto.\n  apply restrict_sm_WD; auto.\n  apply agree_set_reg; auto.\n\n  apply local_of_restrict_vis; auto.\n\n  red; intros. destruct (zlt ofs (dstk ctx)). apply PAD; omega. apply PRIV; omega. } }\n\n  (* return from inlined function *)\n  { inv MS0; try congruence. rewrite RET0 in RET; inv RET. \n  unfold inline_return in AT. \n  assert (PRIV': range_private (as_inj mu) m1' m2 sp' (dstk ctx' + mstk ctx') f'.(fn_stacksize)).\n  assert (restrict_bridge: range_private (as_inj (restrict_sm mu (vis mu))) m1' m2 sp' (dstk ctx' + mstk ctx') (fn_stacksize f')).\n  red; intros. destruct (zlt ofs (dstk ctx)). apply PAD. omega. apply PRIV. omega.\n  red; intros.\n  red in restrict_bridge.\n  apply restrict_bridge in H.\n  eapply loc_privete_restrict; repeat open_Hyp; eauto.\n\n  destruct or.\n  eexists. eexists. split; simpl.\n  eexists. split; simpl.\n  left. \n  eapply effstep_plus_one.\n  eapply rtl_effstep_exec_Iop; eauto. simpl. reflexivity.\n\n  apply Empty_Effect_implication.\n\n  exists mu. intuition.\n  apply gsep_refl.\n  loc_alloc_solve.\n\n  unfold MATCH; intuition.\n  econstructor; eauto. apply match_stacks_inside_set_reg; auto. \n  apply restrict_sm_WD; auto.\n  apply agree_set_reg; auto.\n  (* without a result *)\n  apply local_of_restrict_vis; auto.\n  red; intros. destruct (zlt ofs (dstk ctx)). apply PAD; omega. apply PRIV; omega.\n\n  eexists. eexists. split; simpl.\n  eexists. split.\n  left.  \n  eapply effstep_plus_one. eapply rtl_effstep_exec_Inop; eauto.\n\n  apply Empty_Effect_implication.\n\n  exists mu. intuition.\n  eapply intern_incr_globals_separate; eauto.\n  \n  apply sm_locally_allocatedChar.\n  repeat split; extensionality b0;\n  rewrite freshloc_irrefl;\n  intuition.\n  unfold MATCH; intuition.\n  econstructor; eauto. subst vres. apply agree_set_reg_undef'; auto.\n  apply local_of_restrict_vis; auto.\n\n  red; intros. destruct (zlt ofs (dstk ctx)). apply PAD; omega. apply PRIV; omega. } \nQed.\n\n\n(** ** Behold the theorem *)\nTheorem transl_program_correct:\n  forall (R: list_norepet (map fst (prog_defs SrcProg)))\n         (*entrypoints : list (val * val * signature)*)\n         (*entry_ok : entry_points_ok entrypoints*)\n         (*init_mem: exists m0, Genv.init_mem SrcProg = Some m0*),\n    SM_simulation.SM_simulation_inject (rtl_eff_sem hf)\n                                       (rtl_eff_sem hf) ge tge.\n  intros.\n\n  eapply simulations_lemmas.inj_simulation_star with (match_states:= MATCH)(measure:= RTL_measure); eauto with trans_correct.\n  \n  (*Initial Core*)\n  intros; eapply MATCH_initial_core; eauto.\n  (*\n  { (*destruct init_mem as [m0 INIT].\n    exists m0; split; auto.\n    unfold meminj_preserves_globals in H2.    \n    destruct H2 as [A [B C]]. *)\n    \n    assert (P: forall p q, {Ple p q} + {Plt q p}).\n    intros p q.\n    case_eq (Pos.leb p q).\n    intros TRUE.\n    apply Pos.leb_le in TRUE.\n    left; auto.\n    intros FALSE.\n    apply Pos.leb_gt in FALSE.\n    right; auto.\n\n    cut (forall b, Plt b (Mem.nextblock m0) -> \n                   exists id, Genv.find_symbol ge id = Some b). intro D.\n    \n    split.\n    destruct (P (Mem.nextblock m0) (Mem.nextblock m1)); auto.\n    exfalso. \n    destruct (D _ p).\n    apply A in H2.\n    assert (Mem.valid_block m1 (Mem.nextblock m1)).\n    eapply Mem.valid_block_inject_1; eauto.\n    clear - H8; unfold Mem.valid_block in H8.\n    xomega.\n\n    destruct (P (Mem.nextblock m0) (Mem.nextblock m2)); auto.\n    exfalso. \n    destruct (D _ p).\n    apply A in H2.\n    assert (Mem.valid_block m2 (Mem.nextblock m2)).\n    eapply Mem.valid_block_inject_2; eauto.\n    clear - H8; unfold Mem.valid_block in H8.\n    xomega.\n    \n    intros b LT.    \n    unfold ge. \n    apply valid_init_is_global with (b0 := b) in INIT.\n    eapply INIT; auto.\n    apply R.\n    apply LT. }*)\n\n  {intros. \n   exploit step_simulation_effect; eauto.\n   intros HH; destruct HH as [st2' [m2' [[U2 ?] [mu' ?]]]].\n   repeat open_Hyp.\n   exists st2', m2', mu'.\n   intuition; exists U2;intuition. }\nQed.\n\nEnd PRESERVATION.", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/backend/Inliningproof_comp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.20822758787039589}}
{"text": "From VLSM.Lib Require Import Itauto.\nFrom Coq Require Import FinFun FunctionalExtensionality.\nFrom stdpp Require Import prelude finite.\nFrom VLSM.Lib Require Import Preamble ListExtras StdppListSet.\nFrom VLSM.Core Require Import VLSM VLSMProjections Composition ProjectionTraces Validator.\nFrom VLSM.Core Require Import SubProjectionTraces Equivocation.\nFrom VLSM.Core Require Import Equivocation.NoEquivocation.\nFrom VLSM.Core Require Import Equivocators.Equivocators Equivocators.EquivocatorsProjections.\nFrom VLSM.Core Require Import Equivocators.EquivocatorsComposition.\nFrom VLSM.Core Require Import Equivocators.MessageProperties.\n\n(** * VLSM Equivocator Composition Projections *)\n\nSection sec_equivocators_composition_projections.\n\nContext {message : Type}\n  `{finite.Finite index}\n  (IM : index -> VLSM message)\n  `{forall i : index, HasBeenSentCapability (IM i)}\n  (equivocator_descriptors := equivocator_descriptors IM)\n  (equivocators_no_equivocations_vlsm := equivocators_no_equivocations_vlsm IM)\n  (equivocators_state_project := equivocators_state_project IM)\n  (equivocator_IM := equivocator_IM IM)\n  (equivocator_descriptors_update := equivocator_descriptors_update IM)\n  (proper_equivocator_descriptors := proper_equivocator_descriptors IM)\n  (FreeE := free_composite_vlsm equivocator_IM)\n  (PreFreeE := pre_loaded_with_all_messages_vlsm FreeE)\n  (Free := free_composite_vlsm IM)\n  (PreFree := pre_loaded_with_all_messages_vlsm Free)\n  .\n\n#[local] Hint Unfold equivocator_descriptors_update : state_update.\n\n(**\n  Given a [transition_item] <<item>> in the compositions of equivocators\n  of components [IM] and an [equivocator_descriptors], if the descriptors\n  are all valid in the destination of the transition this returns a\n  set of updated descriptors for corresponding positions in the origin state\n  of the transition, and if the transition was an in-place change to an\n  existing alternative it also returns a projected transition item in\n  the plain composition of [IM].\n*)\nDefinition equivocators_transition_item_project\n  (eqv_descriptors : equivocator_descriptors)\n  (item : composite_transition_item equivocator_IM)\n  : option (option (composite_transition_item IM) * equivocator_descriptors)\n  :=\n  let sx := equivocators_state_project eqv_descriptors (destination item) in\n  let eqv := projT1 (l item) in\n  let deqv := eqv_descriptors eqv in\n  match\n    equivocator_vlsm_transition_item_project\n      (IM eqv)\n      (composite_transition_item_projection equivocator_IM item)\n      deqv\n      with\n  | Some (Some item', deqv') =>\n    Some\n      (Some (@Build_transition_item message (@type message Free)\n        (existT eqv (l item'))\n        (input item) sx (output item))\n      , equivocator_descriptors_update eqv_descriptors eqv deqv')\n  | Some (None, deqv') => Some (None, equivocator_descriptors_update eqv_descriptors eqv deqv')\n  | None => None\n  end.\n\nLemma equivocators_transition_item_project_preserves_equivocating_indices\n  (descriptors : equivocator_descriptors)\n  (item : composite_transition_item equivocator_IM)\n  oitem idescriptors\n  s\n  (Hdescriptors : proper_equivocator_descriptors descriptors (destination item))\n  (Ht : composite_transition equivocator_IM (l item) (s, input item) =\n          (destination item, output item))\n  (Hv : composite_valid equivocator_IM (l item) (s, input item))\n  (Hpr : equivocators_transition_item_project descriptors item = Some (oitem, idescriptors))\n  :\n    set_union\n      (equivocating_indices IM (enum index) s)\n      (newmachine_descriptors_list IM (enum index) idescriptors)\n    ⊆\n    set_union\n      (equivocating_indices IM (enum index) (destination item))\n      (newmachine_descriptors_list IM (enum index) descriptors).\nProof.\n  unfold equivocators_transition_item_project\n    , composite_transition_item_projection\n    , composite_transition_item_projection_from_eq  in Hpr; simpl in Hpr.\n  unfold eq_rect_r, eq_rect in Hpr; simpl in Hpr.\n  match type of Hpr with\n    (match ?exp with _ => _ end = _)\n    => destruct exp as [(oitemx, deqv') |] eqn: Hitem_pr; [| by congruence]\n  end.\n  simpl in Ht.\n  destruct item. simpl in *. destruct l as (i, li). simpl in *.\n  destruct (vtransition (equivocator_IM i) li (s i, input))\n    as (si', om') eqn: Htei.\n  inversion Ht. subst. clear Ht.\n  replace idescriptors with (equivocator_descriptors_update descriptors i deqv')\n    by (destruct oitemx; congruence); clear oitem Hpr.\n  intros eqv Heqv. apply set_union_iff in Heqv. apply set_union_iff.\n  destruct (decide (eqv = i)).\n  - subst i.\n    unfold equivocating_indices in *.\n    unfold newmachine_descriptors_list in *.\n    rewrite! elem_of_list_filter in *.\n    specialize (Hdescriptors eqv).\n    state_update_simpl.\n    cut (is_equivocating_state (IM eqv) si' \\/  is_newmachine_descriptor (IM eqv) (descriptors eqv));\n      [by itauto |].\n    by apply\n      (equivocator_transition_item_project_preserves_equivocating_indices (IM eqv) {|\n      l := li;\n      input := input;\n      destination := si';\n      output := output |} _ Hdescriptors _ _ Hitem_pr _ Hv Htei); itauto.\n  - destruct Heqv as [Heqv | Heqv]\n    ; apply elem_of_list_filter in Heqv as [Heqv Hin].\n    + left.\n      apply elem_of_list_filter.\n      by state_update_simpl.\n    + right.\n      apply elem_of_list_filter.\n      by state_update_simpl.\nQed.\n\n(**\n  [zero_descriptor]s are preserved when projecting [transition_item]s of the\n  composition of equivocators.\n*)\nLemma equivocators_transition_item_project_preserves_zero_descriptors\n  (descriptors : equivocator_descriptors)\n  (item : composite_transition_item equivocator_IM)\n  oitem idescriptors\n  s\n  (Ht : composite_transition equivocator_IM (l item) (s, input item) =\n          (destination item, output item))\n  (Hv : composite_valid equivocator_IM (l item) (s, input item))\n  (Hpr : equivocators_transition_item_project descriptors item = Some (oitem, idescriptors))\n  : forall i, descriptors i = Existing 0 -> idescriptors i = Existing 0.\nProof.\n  intros i Hi.\n  unfold equivocators_transition_item_project in Hpr.\n  destruct (decide (i = projT1 (l item))).\n  - subst i. rewrite Hi in Hpr.\n    specialize\n      (equivocators_vlsm_transition_item_project_zero_descriptor (IM (projT1 (l item)))\n        (composite_transition_item_projection equivocator_IM item)\n        (s (projT1 (l item))))\n      as Hpr_item.\n    remember (composite_transition_item_projection equivocator_IM item) as pr_item.\n    spec Hpr_item.\n    {\n      clear -Ht Heqpr_item.\n      destruct item. simpl in *.\n      destruct l as (i, li).\n      unfold projT1 .\n      match type of Ht with\n      | (let (_, _) := ?t in _) = _ => destruct t as (si', om') eqn: Hti\n      end.\n      inversion Ht; subst; cbn.\n      by state_update_simpl.\n    }\n    spec Hpr_item.\n    {\n      clear -Hv Heqpr_item.\n      destruct item. simpl in *.\n      by destruct l as [i li]; subst.\n    }\n    destruct Hpr_item as [oitem' Hpr_item].\n    rewrite Hpr_item in Hpr.\n    by destruct oitem'; inversion Hpr; state_update_simpl.\n  - destruct\n    (equivocator_vlsm_transition_item_project (IM (projT1 (l item)))\n      (composite_transition_item_projection equivocator_IM item)\n      (descriptors (projT1 (l item))))\n    eqn: Hpr'; [| by congruence].\n  by destruct p, o; inversion Hpr; state_update_simpl.\nQed.\n\nLemma equivocators_transition_item_project_proper_descriptor\n  (eqv_descriptors : equivocator_descriptors)\n  (item : composite_transition_item equivocator_IM)\n  (i := projT1 (l item))\n  (Hproper : proper_descriptor (IM i) (eqv_descriptors i) (destination item i))\n  : is_Some (equivocators_transition_item_project eqv_descriptors item).\nProof.\n  specialize\n    (equivocator_transition_item_project_proper (IM (projT1 (l item)))\n      (composite_transition_item_projection equivocator_IM item)\n      (eqv_descriptors (projT1 (l item))) Hproper)\n    as [itemx Hpr_item].\n  unfold equivocators_transition_item_project.\n  rewrite Hpr_item.\n  by destruct itemx, o; eexists.\nQed.\n\nLemma equivocators_transition_item_project_proper\n  (eqv_descriptors : equivocator_descriptors)\n  (item : composite_transition_item equivocator_IM)\n  (Hproper : proper_equivocator_descriptors eqv_descriptors (destination item))\n  : is_Some (equivocators_transition_item_project eqv_descriptors item).\nProof.\n  apply equivocators_transition_item_project_proper_descriptor.\n  by apply Hproper.\nQed.\n\n(**\n  A generalization of [no_equivocating_equivocator_transition_item_project] to\n  the composition of equivocators.\n*)\nLemma no_equivocating_equivocators_transition_item_project\n  (eqv_descriptors : equivocator_descriptors)\n  (item : composite_transition_item equivocator_IM)\n  (i := projT1 (l item))\n  (Hzero : (eqv_descriptors i) = Existing 0)\n  (Hdest_i : is_singleton_state (IM i) (destination item i))\n  (s : composite_state equivocator_IM)\n  (Hv : composite_valid equivocator_IM (l item) (s, input item))\n  (Ht : composite_transition equivocator_IM (l item) (s, input item) =\n          (destination item, output item))\n  : exists (Hex : existing_equivocator_label _ (projT2 (l item)))\n    (lx : composite_label IM :=\n      existT i (existing_equivocator_label_extract _ (projT2 (l item)) Hex)),\n  equivocators_transition_item_project eqv_descriptors item =\n    Some (Some\n      {| l := lx; input := input item; output := output item;\n        destination := equivocators_state_project eqv_descriptors (destination item) |},\n      eqv_descriptors).\nProof.\n  specialize\n    (no_equivocating_equivocator_transition_item_project (IM i)\n      (composite_transition_item_projection equivocator_IM item)\n      Hdest_i\n      (s i))\n    as Heqv_pr.\n  destruct item, l. simpl in Ht, Hv. simpl in i. subst i.\n  specialize (Heqv_pr Hv).\n  spec Heqv_pr.\n  { simpl. unfold eq_rect_r. simpl.\n    destruct (vtransition (equivocator_IM x) v (s x, input)) eqn: Hti.\n    clear -Ht Hti; inversion Ht; subst.\n    by state_update_simpl.\n  }\n  destruct Heqv_pr as [Hex Heqv_pr].\n  exists Hex.\n  unfold equivocators_transition_item_project.\n  unfold l. unfold projT1.\n  rewrite Hzero, Heqv_pr; cbn; repeat f_equal.\n  by state_update_simpl.\nQed.\n\nLemma exists_equivocators_transition_item_project\n  (item : composite_transition_item equivocator_IM)\n  (s : composite_state equivocator_IM)\n  (Hs : proper_existing_equivocator_label _ (projT2 (l item)) (s (projT1 (l item))))\n  (Hv : composite_valid equivocator_IM (l item) (s, input item))\n  (Ht : composite_transition equivocator_IM (l item) (s, input item) =\n          (destination item, output item))\n  : exists equivocators,\n      not_equivocating_equivocator_descriptors IM equivocators (destination item)\n      /\\ exists (equivocators' : equivocator_descriptors)\n        (lx : composite_label IM := existT (projT1 (l item))\n          (existing_equivocator_label_extract _ _ (existing_equivocator_label_forget_proper _ Hs)))\n        (sx : composite_state IM := equivocators_state_project equivocators (destination item))\n      ,\n        proper_equivocator_descriptors equivocators' s\n        /\\ equivocators_transition_item_project equivocators item = Some\n          (Some ({| l := lx; input := input item; output := output item; destination := sx |}),\n            equivocators').\nProof.\n  specialize\n    (exists_equivocator_transition_item_project\n      (IM (projT1 (l item)))\n      (composite_transition_item_projection equivocator_IM item)\n      (s (projT1 (l item)))\n      Hs)\n    as Hproject.\n  spec Hproject; [by rewrite (sigT_eta (l item)) in Hv |].\n  spec Hproject; [by apply composite_transition_project_active in Ht |].\n  destruct Hproject as [Heqv' [eqv [Heqv Hproject]]].\n  exists (equivocator_descriptors_update (zero_descriptor IM) (projT1 (l item)) eqv).\n  split.\n  {\n    intro i. unfold equivocator_descriptors_update. destruct (decide (i = projT1 (l item))).\n    - by subst; state_update_simpl.\n    - rewrite equivocator_descriptors_update_neq by done; cbn.\n      by rewrite equivocator_state_project_zero.\n  }\n  exists (equivocator_descriptors_update (zero_descriptor IM) (projT1 (l item))\n    (equivocator_label_descriptor (l (composite_transition_item_projection equivocator_IM item)))).\n  split.\n  { intro i. unfold equivocator_descriptors_update. destruct (decide (i = projT1 (l item))).\n    - by subst; state_update_simpl.\n    - rewrite equivocator_descriptors_update_neq by done.\n      simpl. by rewrite equivocator_state_project_zero.\n  }\n  unfold equivocators_transition_item_project.\n  state_update_simpl.\n  by rewrite Hproject, equivocator_descriptors_update_twice.\nQed.\n\nLemma equivocators_transition_item_project_proper_descriptor_characterization\n  (eqv_descriptors : equivocator_descriptors)\n  (item : composite_transition_item equivocator_IM)\n  (i := projT1 (l item))\n  (Hproper : proper_descriptor (IM i) (eqv_descriptors i) (destination item i))\n  : exists oitem eqv_descriptors',\n    equivocators_transition_item_project eqv_descriptors item = Some (oitem, eqv_descriptors')\n    /\\ match oitem with\n      | Some itemx =>\n        (exists (Hex : existing_equivocator_label _ (projT2 (l item))),\n          existT i (existing_equivocator_label_extract _ _ Hex) = l itemx) /\\\n        input item = input itemx /\\ output item = output itemx /\\\n        (equivocators_state_project eqv_descriptors (destination item) = destination itemx)\n        /\\ eqv_descriptors' i = (equivocator_label_descriptor (projT2 (l item)))\n      | None => True\n      end\n    /\\ forall\n      (s : composite_state equivocator_IM)\n      (Hv : composite_valid equivocator_IM (l item) (s, input item))\n      (Ht : composite_transition equivocator_IM (l item) (s, input item) =\n              (destination item, output item)),\n      proper_descriptor (IM i) (eqv_descriptors' i) (s i) /\\\n      eqv_descriptors' = equivocator_descriptors_update eqv_descriptors i (eqv_descriptors' i) /\\\n      s = state_update equivocator_IM (destination item) i (s i) /\\\n      previous_state_descriptor_prop (IM i) (eqv_descriptors i) (s i) (eqv_descriptors' i) /\\\n      match oitem with\n      | Some itemx =>\n        forall (sx : composite_state IM)\n          (Hsx : sx = equivocators_state_project eqv_descriptors' s),\n          composite_valid IM (l itemx) (sx, input itemx) /\\\n          composite_transition IM (l itemx) (sx, input itemx) = (destination itemx, output itemx)\n      | None =>\n        equivocators_state_project eqv_descriptors (destination item) =\n        equivocators_state_project eqv_descriptors' s\n      end.\nProof.\n  destruct\n    (equivocator_transition_item_project_proper_characterization (IM i)\n      (composite_transition_item_projection equivocator_IM item)\n      (eqv_descriptors i) Hproper)\n    as (oitemi & eqv_descriptorsi' & Hoitemi & Hitemx & Hchar).\n  subst i.\n  unfold equivocators_transition_item_project.\n  rewrite Hoitemi. clear Hoitemi.\n  destruct item. simpl in *. destruct l as (i, li). simpl in *.\n  destruct oitemi as [itemi' |]; eexists _; eexists _; (split; [done |])\n  ; [| split; [done |]]\n  ; [destruct Hitemx as [[Hex Hli] [Hinputi [Houtputi [Hdestinationi Hdescriptori]]]]\n  ; rewrite Hli; subst; split; [repeat split |]\n    |]\n  ; [by exists Hex | apply equivocator_descriptors_update_eq | ..]\n  ; intros\n  ; match type of Ht with\n    | (let (_, _) := ?t in _) = _ =>\n      destruct t as (si', om') eqn: Ht'\n    end\n  ; inversion Ht; subst; clear Ht\n  ; rewrite state_update_eq in Hchar\n  ; specialize (Hchar _ Hv Ht')\n  ; simpl in *\n  ; destruct Hchar as (Hproper' & Hex_new & Hchar)\n  .\n  - repeat split.\n    + by state_update_simpl.\n    + by state_update_simpl.\n    + by extensionality j; destruct (decide (i = j)); subst; state_update_simpl.\n    + by state_update_simpl.\n    + subst. specialize (Hchar _ eq_refl) as [Hvx Htx].\n      unfold equivocators_state_project, EquivocatorsComposition.equivocators_state_project.\n      rewrite Hli in Hvx.\n      by state_update_simpl.\n    + subst. specialize (Hchar _ eq_refl) as [Hvx Htx].\n      unfold equivocators_state_project, EquivocatorsComposition.equivocators_state_project.\n      state_update_simpl.\n      simpl in *. rewrite Hli in Htx. rewrite Htx. f_equal.\n      by extensionality eqv; destruct (decide (i = eqv)); subst; state_update_simpl.\n  - repeat split.\n    + by state_update_simpl.\n    + by state_update_simpl.\n    + by extensionality j; destruct (decide (i = j)); subst; state_update_simpl.\n    + by state_update_simpl.\n    + unfold equivocators_state_project, EquivocatorsComposition.equivocators_state_project.\n      by extensionality eqv; destruct (decide (i = eqv)); subst; state_update_simpl.\nQed.\n\nLemma equivocators_transition_item_project_proper_characterization\n  (eqv_descriptors : equivocator_descriptors)\n  (item : composite_transition_item equivocator_IM)\n  (Hproper : proper_equivocator_descriptors eqv_descriptors (destination item))\n  : exists oitem eqv_descriptors',\n    equivocators_transition_item_project eqv_descriptors item = Some (oitem, eqv_descriptors')\n    /\\ match oitem with\n      | Some itemx =>\n        (exists (Hex : existing_equivocator_label _ (projT2 (l item))),\n          existT (projT1 (l item)) (existing_equivocator_label_extract _ _ Hex) = l itemx) /\\\n         input item = input itemx /\\ output item = output itemx /\\\n        (equivocators_state_project eqv_descriptors (destination item) = destination itemx)\n        /\\ eqv_descriptors' (projT1 (l item)) = (equivocator_label_descriptor (projT2 (l item)))\n      | None => True\n      end\n    /\\ forall\n      (s : composite_state equivocator_IM)\n      (Hv : composite_valid equivocator_IM (l item) (s, input item))\n      (Ht : composite_transition equivocator_IM (l item) (s, input item) =\n        (destination item, output item)),\n      proper_equivocator_descriptors eqv_descriptors' s /\\\n      eqv_descriptors' = equivocator_descriptors_update eqv_descriptors\n                          (projT1 (l item)) (eqv_descriptors' (projT1 (l item))) /\\\n      s = state_update equivocator_IM (destination item) (projT1 (l item)) (s (projT1 (l item))) /\\\n      previous_state_descriptor_prop (IM (projT1 (l item))) (eqv_descriptors (projT1 (l item)))\n        (s (projT1 (l item))) (eqv_descriptors' (projT1 (l item))) /\\\n      match oitem with\n      | Some itemx =>\n        forall (sx : composite_state IM)\n          (Hsx : sx = equivocators_state_project eqv_descriptors' s),\n          composite_valid IM (l itemx) (sx, input itemx) /\\\n          composite_transition IM (l itemx) (sx, input itemx) = (destination itemx, output itemx)\n      | None =>\n        equivocators_state_project eqv_descriptors (destination item) =\n        equivocators_state_project eqv_descriptors' s\n      end.\nProof.\n  destruct (equivocators_transition_item_project_proper_descriptor_characterization\n    eqv_descriptors item (Hproper (projT1 (l item))))\n    as [oitem [eqv_descriptors' [Hoitem [Hitemx Hchar]]]].\n  exists oitem, eqv_descriptors'. split; [done |].\n  split; [done |].\n  intros.\n  specialize (Hchar s Hv Ht) as (Hproperi' & Heqv' & Hs & Hex_new & Hchar).\n  clear Hv Ht Hoitem.\n  split; [| by repeat split]; clear Hchar.\n  intro eqv.\n  rewrite Heqv', Hs.\n  by destruct (decide (eqv = projT1 (l item))); subst; state_update_simpl.\nQed.\n\nLemma equivocators_transition_item_project_inv_characterization\n  (eqv_descriptors eqv_descriptors' : equivocator_descriptors)\n  (item : composite_transition_item equivocator_IM)\n  (itemx : composite_transition_item IM)\n  (Hpr_item : equivocators_transition_item_project eqv_descriptors item =\n              Some (Some itemx, eqv_descriptors'))\n  : (exists (Hex : existing_equivocator_label _ (projT2 (l item))),\n      existT (projT1 (l item)) (existing_equivocator_label_extract _ _ Hex) = l itemx) /\\\n    input item = input itemx /\\ output item = output itemx /\\\n    equivocators_state_project eqv_descriptors (destination item) = destination itemx.\nProof.\n  unfold equivocators_transition_item_project in Hpr_item.\n  destruct\n    (equivocator_vlsm_transition_item_project\n      (IM (projT1 (l item)))\n      (composite_transition_item_projection equivocator_IM item)\n      (eqv_descriptors (projT1 (l item))))\n    as [([itemi |], descriptori) |] eqn: Hpr_itemi\n  ; [| by congruence..].\n  inversion Hpr_item. subst. clear Hpr_item. simpl.\n  repeat split.\n  apply equivocator_transition_item_project_inv_characterization in Hpr_itemi\n    as [[Hex Hl]].\n  rewrite Hl.\n  by exists Hex.\nQed.\n\nDefinition equivocators_trace_project_folder\n  (item : composite_transition_item equivocator_IM)\n  (result : option (list (composite_transition_item IM) * equivocator_descriptors))\n  : option (list (composite_transition_item IM) * equivocator_descriptors)\n  :=\n  match result with\n  | None => None\n  | Some (r, idescriptor) =>\n    match equivocators_transition_item_project idescriptor item with\n    | None => None\n    | Some (None, odescriptor) => Some (r, odescriptor)\n    | Some (Some item', odescriptor) => Some (item' :: r, odescriptor)\n    end\n  end.\n\nLemma equivocators_trace_project_fold_None\n  (tr : list (composite_transition_item equivocator_IM))\n  : fold_right equivocators_trace_project_folder None tr = None.\nProof.\n  by induction tr; cbn; rewrite ?IHtr.\nQed.\n\nLemma equivocators_trace_project_folder_additive_iff\n  (tr : list (composite_transition_item equivocator_IM))\n  (itrX : list (composite_transition_item IM))\n  (ieqv_descriptors eqv_descriptors : equivocator_descriptors)\n  (trX' : list (composite_transition_item IM))\n  : fold_right equivocators_trace_project_folder (Some (itrX, ieqv_descriptors)) tr\n    = Some (trX', eqv_descriptors)\n  <-> exists trX : list (composite_transition_item IM),\n    fold_right equivocators_trace_project_folder (Some ([], ieqv_descriptors)) tr\n      = Some (trX, eqv_descriptors)\n    /\\ trX' = trX ++ itrX.\nProof.\n  revert trX' eqv_descriptors.\n  induction tr; intros.\n  - simpl. split; intro Htr.\n    + by inversion Htr; subst; exists [].\n    + by destruct Htr as [trX [[= <-] ?]]; subst.\n  - simpl.\n    remember (fold_right equivocators_trace_project_folder (Some (itrX, ieqv_descriptors)) tr)\n      as pr_itrX_tr.\n    remember (fold_right equivocators_trace_project_folder (Some ([], ieqv_descriptors)) tr)\n      as pr_tr.\n    split.\n    + intro Htr.\n      destruct pr_itrX_tr as [(tr1, e1) |] ; [| by inversion Htr].\n      specialize (IHtr tr1 e1). apply proj1 in IHtr. specialize (IHtr eq_refl).\n      destruct IHtr as [trX [Hpr_tr Htr1]].\n      rewrite Hpr_tr in *. rewrite Htr1 in *.\n      simpl in Htr. simpl.\n      destruct (equivocators_transition_item_project e1 a)\n        as [(oitem, eqv_descriptors'') |] eqn: Ha; [| by congruence].\n      by destruct oitem; inversion Htr; eexists _.\n    + intros [trX [Htr HtrX']].\n      subst trX'.\n      destruct pr_tr as [(tr1, e1) |]; [| by inversion Htr].\n      specialize (IHtr (tr1 ++ itrX) e1). apply proj2 in IHtr.\n      rewrite IHtr by (eexists _; done).\n      simpl in *.\n      destruct (equivocators_transition_item_project e1 a)\n        as [(oitem, odescriptor) |] eqn: Ha\n      ; [| done].\n      by destruct oitem as [item' |]; inversion Htr.\nQed.\n\nLemma equivocators_trace_project_folder_additive\n  (tr : list (composite_transition_item equivocator_IM))\n  (itrX trX : list (composite_transition_item IM))\n  (ieqv_descriptors eqv_descriptors : equivocator_descriptors)\n  (Htr : fold_right equivocators_trace_project_folder (Some ([], ieqv_descriptors)) tr\n    = Some (trX, eqv_descriptors))\n  : fold_right equivocators_trace_project_folder (Some (itrX, ieqv_descriptors)) tr\n    = Some (trX ++ itrX, eqv_descriptors).\nProof.\n  apply equivocators_trace_project_folder_additive_iff.\n  by exists trX.\nQed.\n\n(**\n  The projection of an [equivocators] trace is obtained by traversing the\n  trace from right to left guided by the descriptors produced by\n  [equivocators_transition_item_project] and gathering all non-empty\n  [transition_item]s it produces.\n*)\nDefinition equivocators_trace_project\n  (eqv_descriptors : equivocator_descriptors)\n  (tr : list (composite_transition_item equivocator_IM))\n  : option (list (composite_transition_item IM) * equivocator_descriptors)\n  :=\n  fold_right\n    equivocators_trace_project_folder\n    (Some ([], eqv_descriptors))\n    tr.\n\nLemma equivocators_trace_project_app_iff\n  (pre suf : list (composite_transition_item equivocator_IM))\n  (ieqv_descriptors eqv_descriptors : equivocator_descriptors)\n  (trX : list (composite_transition_item IM))\n  : equivocators_trace_project eqv_descriptors (pre ++ suf)\n    = Some (trX, ieqv_descriptors)\n  <-> exists\n    (preX sufX : list (composite_transition_item IM))\n    (eqv_descriptors' : equivocator_descriptors),\n    equivocators_trace_project eqv_descriptors suf = Some (sufX, eqv_descriptors') /\\\n    equivocators_trace_project eqv_descriptors' pre = Some (preX, ieqv_descriptors) /\\\n    trX = preX ++ sufX.\nProof.\n  unfold equivocators_trace_project.\n  rewrite fold_right_app.\n  simpl.\n  match goal with\n  |- fold_right _ ?r _ = _ <-> _ => remember r as r_sufX\n  end.\n  destruct r_sufX as [(sufX, eqv_descriptors') |]\n  ; [| by rewrite equivocators_trace_project_fold_None; split;\n      [intro contra; congruence | intros [preX [sufX [eqv_descriptors' [contra _]]]]; congruence]].\n  rewrite (equivocators_trace_project_folder_additive_iff\n    pre sufX eqv_descriptors' ieqv_descriptors trX).\n  split.\n  - by intros (preX & HpreX & HtrX); exists preX, sufX, eqv_descriptors'.\n  - intros [preX [_sufX [_eqv_descriptors' [Heq [Hpre HtrX]]]]].\n    by exists preX; inversion Heq; subst.\nQed.\n\n(**\n  For every [transition_item] of the projection of a trace over the composition\n  of equivocators, there exists a corresponding item in the original trace\n  which projects to it.\n*)\nLemma equivocators_trace_project_app_inv_item\n  (tr : list (composite_transition_item equivocator_IM))\n  (ieqv_descriptors eqv_descriptors : equivocator_descriptors)\n  (preX sufX : list (composite_transition_item IM))\n  (itemX : composite_transition_item IM)\n  : equivocators_trace_project eqv_descriptors tr\n    = Some (preX ++ [itemX] ++ sufX, ieqv_descriptors) ->\n  exists\n    (pre suf : list (composite_transition_item equivocator_IM))\n    (item : (composite_transition_item equivocator_IM))\n    (item_descriptors pre_descriptors : equivocator_descriptors),\n    equivocators_trace_project eqv_descriptors suf = Some (sufX, item_descriptors) /\\\n    equivocators_transition_item_project item_descriptors item = Some (Some itemX, pre_descriptors) /\\\n    equivocators_trace_project pre_descriptors pre = Some (preX, ieqv_descriptors) /\\\n    tr = pre ++ [item] ++ suf.\nProof.\n  generalize dependent sufX. generalize dependent eqv_descriptors.\n  induction tr using rev_ind; intros eqv_descriptors sufX.\n  - cbn; inversion 1 as [[Hnil Heq]]; clear -Hnil.\n    by destruct preX; inversion Hnil.\n  - intro Hsome.\n    apply equivocators_trace_project_app_iff in Hsome\n      as (trX' & xX & eqv_descriptors' & Hpr_x & Hpr_tr & Heq).\n    simpl in Hpr_x.\n    destruct (equivocators_transition_item_project eqv_descriptors x)\n      as [(ox, descriptorx) |] eqn: Hpr_x_item\n    ; [| by congruence].\n    destruct xX as [| xX _empty].\n    + destruct ox; [by congruence |].\n      inversion Hpr_x. subst. clear Hpr_x.\n      rewrite app_nil_r in  Heq. subst trX'.\n      specialize (IHtr eqv_descriptors' sufX Hpr_tr).\n      destruct IHtr as [pre [suf [item [item_descriptors [pre_descriptors [Hpr_suf [Hpr_item\n        [Hpr_pre Heqtr]]]]]]]].\n      exists pre, (suf ++ [x]), item, item_descriptors, pre_descriptors.\n      subst tr. rewrite !app_assoc.\n      repeat split; [| done | done].\n      apply equivocators_trace_project_app_iff.\n      exists sufX, [], eqv_descriptors'. rewrite app_nil_r.\n      repeat split; [| done].\n      by simpl; rewrite Hpr_x_item.\n    + destruct ox; [| by congruence].\n      inversion Hpr_x. subst. clear Hpr_x.\n      destruct_list_last sufX sufX' _xX Heq_sufX.\n      * subst. rewrite app_nil_r in Heq. apply app_inj_tail in Heq.\n        destruct Heq. subst.\n        exists tr, [], x, eqv_descriptors, eqv_descriptors'.\n        by rewrite app_nil_r.\n      * subst. rewrite! app_assoc in Heq. apply app_inj_tail in Heq.\n        rewrite <- app_assoc in Heq. destruct Heq. subst.\n        specialize (IHtr eqv_descriptors' sufX' Hpr_tr).\n        destruct IHtr as [pre [suf [item [item_descriptors [pre_descriptors [Hpr_suf [Hpr_item\n          [Hpr_pre Heqtr]]]]]]]].\n        exists pre, (suf ++ [x]), item, item_descriptors, pre_descriptors.\n        subst tr. rewrite !app_assoc.\n        repeat split; [| done | done].\n        apply equivocators_trace_project_app_iff.\n        exists sufX', [xX], eqv_descriptors'.\n        repeat split; [| done].\n        by simpl; rewrite Hpr_x_item.\nQed.\n\n(** A corollary of the above, reflecting a split in the projection to the original trace. *)\nLemma equivocators_trace_project_app_inv\n  (tr : list (composite_transition_item equivocator_IM))\n  (ieqv_descriptors eqv_descriptors : equivocator_descriptors)\n  (preX sufX : list (composite_transition_item IM))\n  : equivocators_trace_project eqv_descriptors tr\n    = Some (preX ++ sufX, ieqv_descriptors) ->\n  exists\n    (pre suf : list (composite_transition_item equivocator_IM))\n    (eqv_descriptors' : equivocator_descriptors),\n    equivocators_trace_project eqv_descriptors suf = Some (sufX, eqv_descriptors') /\\\n    equivocators_trace_project eqv_descriptors' pre = Some (preX, ieqv_descriptors) /\\\n    tr = pre ++ suf.\nProof.\n  intro Hpr_tr.\n  destruct sufX as [| itemX sufX].\n  - rewrite app_nil_r in Hpr_tr.\n    exists tr, [], eqv_descriptors.\n    by rewrite app_nil_r.\n  - change (itemX :: sufX) with ([itemX] ++ sufX) in Hpr_tr.\n    apply equivocators_trace_project_app_inv_item in Hpr_tr.\n    destruct Hpr_tr as [pre [suf [item [item_descriptors [pre_descriptors [Hpr_suf [Hpr_item\n      [Hpr_pre Heqtr]]]]]]]].\n    exists pre, ([item] ++ suf), pre_descriptors.\n    subst. repeat split; [| done].\n    apply equivocators_trace_project_app_iff.\n    exists [itemX], sufX, item_descriptors.\n    repeat split; [done |].\n    by simpl; rewrite Hpr_item.\nQed.\n\nLemma equivocators_trace_project_preserves_equivocating_indices\n  (descriptors idescriptors : equivocator_descriptors)\n  (tr : list (composite_transition_item equivocator_IM))\n  (trX : list (composite_transition_item IM))\n  (is s : composite_state equivocator_IM)\n  (Htr : finite_valid_trace_from_to (pre_loaded_with_all_messages_vlsm\n          (free_composite_vlsm equivocator_IM)) is s tr)\n  (Hdescriptors : proper_equivocator_descriptors descriptors s)\n  (Hproject_tr : equivocators_trace_project descriptors tr = Some (trX, idescriptors))\n  :\n    set_union\n      (equivocating_indices IM (enum index) is)\n      (newmachine_descriptors_list IM (enum index) idescriptors)\n    ⊆\n    set_union\n      (equivocating_indices IM (enum index) s)\n      (newmachine_descriptors_list IM (enum index) descriptors).\nProof.\n  generalize dependent trX. generalize dependent descriptors.\n  induction Htr using finite_valid_trace_from_to_rev_ind; [by inversion 2 |].\n  set (x := {| l := l |}).\n  intros.\n  apply equivocators_trace_project_app_iff in Hproject_tr.\n  destruct Hproject_tr as [preX [sufX [descriptors' [Hproject_x [Hproject_tr _]]]]].\n  simpl in Hproject_x.\n  destruct\n    (equivocators_transition_item_project descriptors x)\n    as [(oitemx, _descriptors') |] eqn: Hpr_x ; [| by congruence].\n  assert (_descriptors' = descriptors') as -> by (destruct oitemx; congruence).\n  clear Hproject_x trX sufX.\n\n  destruct Ht as [[_ [_ [Hv _]]] Ht].\n  specialize\n    (equivocators_transition_item_project_preserves_equivocating_indices descriptors x\n       oitemx descriptors' s Hdescriptors Ht Hv Hpr_x) as Hx_preserves.\n  specialize\n    (equivocators_transition_item_project_proper_characterization descriptors x Hdescriptors)\n    as Hpr_x_char.\n  rewrite Hpr_x in Hpr_x_char.\n  destruct Hpr_x_char as [_ [_ [[= <- <-] [_ Hchar2]]]].\n  specialize (Hchar2 s Hv Ht) as [Hdescriptors' _].\n  specialize (IHHtr _ Hdescriptors' _ Hproject_tr).\n  by etransitivity.\nQed.\n\n(**\n  The state and descriptors obtained after applying [equivocators_trace_project]\n  on a pre-loaded valid trace satisfy the [previous_state_descriptor_prop]erty.\n*)\nLemma equivocators_trace_project_from_state_descriptors\n  (descriptors idescriptors : equivocator_descriptors)\n  (tr : list (composite_transition_item equivocator_IM))\n  (trX : list (composite_transition_item IM))\n  (is s : composite_state equivocator_IM)\n  (Htr : finite_valid_trace_from_to (pre_loaded_with_all_messages_vlsm\n          (free_composite_vlsm equivocator_IM)) is s tr)\n  (Hdescriptors : proper_equivocator_descriptors descriptors s)\n  (Hproject_tr : equivocators_trace_project descriptors tr = Some (trX, idescriptors))\n  : forall eqv, previous_state_descriptor_prop (IM eqv) (descriptors eqv) (is eqv) (idescriptors eqv).\nProof.\n  generalize dependent trX.\n  generalize dependent descriptors.\n  generalize dependent s.\n  induction tr using rev_ind; intros.\n  - by inversion Hproject_tr; subst; destruct (idescriptors eqv); simpl; [| lia].\n  - apply finite_valid_trace_from_to_last in Htr as Heq_s.\n    rewrite finite_trace_last_is_last in Heq_s. subst s.\n    apply finite_valid_trace_from_to_app_split in Htr.\n    destruct Htr as [Htr Hx].\n    specialize (equivocators_pre_trace_cannot_decrease_state_size IM _ _ _ Htr) as His_tr.\n    specialize (equivocators_pre_trace_cannot_decrease_state_size IM _ _ _ Hx) as Htr_x.\n    specialize (IHtr _ Htr).\n    specialize (equivocators_transition_item_project_proper_characterization descriptors x)\n      as Hproperx.\n    specialize (Hproperx Hdescriptors).\n    destruct Hproperx as [oitem [final_descriptors' [Hprojectx [Hitemx Hproperx]]]].\n    specialize (Hproperx (finite_trace_last is tr)).\n    rewrite equivocators_trace_project_app_iff in Hproject_tr.\n    simpl in *.\n    rewrite Hprojectx in Hproject_tr.\n    inversion Hx. subst tl s' x f. clear Hx Htl.\n    destruct Ht as [[_ [_ [Hv _]]] Ht].\n    specialize (Hproperx Hv Ht). simpl in Hproperx.\n    destruct Hproperx as [Hproper' [Heq_final_descriptors' [Heq_ltr [Hex_new Hx]]]].\n    specialize (IHtr _ Hproper').\n    assert (Hex_new' : previous_state_descriptor_prop (IM eqv) (final_descriptors' eqv) (is eqv)\n                        (idescriptors eqv)).\n    {\n      destruct Hproject_tr as [preX [sufX [_final_descriptors' [H_final_descriptors'\n        [Hproject_tr HtrX]]]]].\n      apply IHtr with preX.\n      by destruct oitem; inversion H_final_descriptors'; subst.\n    }\n\n    destruct l as (i, li). simpl in *.\n    destruct (decide (i = eqv)).\n    + subst. specialize (His_tr eqv). specialize (Htr_x eqv).\n      destruct (descriptors eqv) eqn: Hvin_desc_eqv;\n        [by simpl in Hex_new; rewrite Hex_new in Hex_new' |].\n      destruct (final_descriptors' eqv) eqn: Hfin_desc_eqv'.\n      * by simpl in Hex_new, Hex_new'; rewrite Hex_new'; simpl;  lia.\n      * by destruct (idescriptors eqv); simpl in *; lia.\n    + by rewrite Heq_final_descriptors' in Hex_new'; state_update_simpl.\nQed.\n\nLemma equivocators_trace_project_preserves_equivocating_indices_final\n  (descriptors idescriptors : equivocator_descriptors)\n  (tr : list (composite_transition_item equivocator_IM))\n  (trX : list (composite_transition_item IM))\n  (is s : composite_state equivocator_IM)\n  (Htr : finite_valid_trace_from_to (pre_loaded_with_all_messages_vlsm\n          (free_composite_vlsm equivocator_IM)) is s tr)\n  (Hdescriptors : not_equivocating_equivocator_descriptors IM descriptors s)\n  (Hproject_tr : equivocators_trace_project descriptors tr = Some (trX, idescriptors))\n  :\n    set_union\n      (equivocating_indices IM (enum index) is)\n      (newmachine_descriptors_list IM (enum index) idescriptors)\n    ⊆\n    equivocating_indices IM (enum index) s.\nProof.\n  apply not_equivocating_equivocator_descriptors_proper in Hdescriptors as Hproper.\n  specialize\n    (equivocators_trace_project_preserves_equivocating_indices _ _ _ _ _ _\n      Htr Hproper Hproject_tr)\n    as Hincl.\n  intros eqv Heqv. specialize (Hincl eqv Heqv).\n  apply set_union_iff in Hincl.\n  clear Heqv.\n  destruct Hincl as [| Heqv]; [done |].\n  specialize (Hdescriptors eqv).\n  apply elem_of_list_filter in Heqv.\n  destruct Heqv as [Heqv Hin].\n  by destruct (descriptors eqv).\nQed.\n\n(**\n  We can project a trace over the composition of equivocators in two ways:\n  (1) first project on a equivocator component, then project the equivocator to the original component\n  (2) first projects to the composition of original components, then project to one of them\n\n  The result below says that the two ways lead to the same result.\n*)\nLemma equivocators_trace_project_finite_trace_projection_list_commute\n  (i : index)\n  (final_descriptors initial_descriptors : equivocator_descriptors)\n  (eqv_initial : MachineDescriptor (IM i))\n  (tr : list (composite_transition_item equivocator_IM))\n  (trX : list (composite_transition_item IM))\n  (trXi : list (vtransition_item (IM i)))\n  (eqv_final := final_descriptors i)\n  (Hproject_tr : equivocators_trace_project final_descriptors tr = Some (trX, initial_descriptors))\n  (Hproject_tri :\n    equivocator_vlsm_trace_project (IM i)\n      (finite_trace_projection_list equivocator_IM i tr) eqv_final\n    = Some (trXi, eqv_initial))\n  : initial_descriptors i = eqv_initial /\\\n    finite_trace_projection_list IM i trX = trXi.\nProof.\n  generalize dependent trXi. generalize dependent trX.\n  generalize dependent final_descriptors.\n  induction tr using rev_ind; intros.\n  - by inversion Hproject_tr; inversion Hproject_tri; subst.\n  - unfold equivocators_trace_project in Hproject_tr.\n    rewrite fold_right_app in Hproject_tr.\n    match type of Hproject_tr with\n    | fold_right _ ?i _ = _ => destruct i as [(projectx, final_descriptors') |] eqn: Hproject_x\n    end\n    ; [| by rewrite equivocators_trace_project_fold_None in Hproject_tr; inversion Hproject_tr].\n    apply equivocators_trace_project_folder_additive_iff in Hproject_tr.\n    destruct Hproject_tr as [trX0 [HtrX0 HtrX]].\n    specialize (IHtr _ _ HtrX0).\n    unfold finite_trace_projection_list in Hproject_tri.\n    rewrite @pre_VLSM_projection_finite_trace_project_app in Hproject_tri.\n    apply equivocator_vlsm_trace_project_app in Hproject_tri.\n    destruct Hproject_tri as [eqv_final' [trXi' [project_xi [HtrXi' [Hproject_xi HeqtrXi]]]]].\n    assert (Hfinal'i : final_descriptors' i = eqv_final' /\\\n      finite_trace_projection_list IM i projectx = project_xi).\n    { clear - Hproject_x Hproject_xi.\n      simpl in *.\n      destruct (equivocators_transition_item_project final_descriptors x)\n        as [(ox, final') |] eqn: Hpr_item_x\n      ; [| by congruence].\n      unfold equivocators_transition_item_project in Hpr_item_x.\n      destruct (decide (i = projT1 (l x))).\n      - subst i.\n        rewrite (composite_transition_item_projection_iff equivocator_IM x)\n         in Hproject_xi.\n        simpl in Hproject_xi.\n        subst eqv_final.\n        destruct (equivocator_vlsm_transition_item_project _ _ _)\n          as [(oitem', descriptor') |] eqn: Heqpr_item_x\n        ; [| done].\n        destruct oitem' as [item' |]\n        ; inversion Hproject_xi; subst descriptor' project_xi; clear Hproject_xi\n        ; inversion Hpr_item_x; subst; clear Hpr_item_x\n        ; inversion Hproject_x; subst; clear Hproject_x\n        ; state_update_simpl\n        ; [| by split].\n        split; [done |].\n        simpl. destruct x. simpl in *. destruct l as (i, li). simpl in *.\n        unfold pre_VLSM_projection_transition_item_project, composite_project_label. simpl.\n        destruct (decide (i = i)); [| by congruence].\n        f_equal.\n        replace e with (@eq_refl _ i) by (apply Eqdep_dec.UIP_dec; done). clear e.\n        destruct item'.\n        apply equivocator_transition_item_project_inv_characterization in Heqpr_item_x.\n        simpl in *.\n        by destruct Heqpr_item_x as [Hl [-> [-> [<- _]]]].\n      - rewrite (composite_transition_item_projection_neq equivocator_IM i x)\n         in Hproject_xi by congruence.\n        simpl in Hproject_xi.\n        subst eqv_final.\n        inversion Hproject_xi. subst. clear Hproject_xi.\n        destruct\n          (equivocator_vlsm_transition_item_project _ _ _)\n          as [(oitem', descriptor') |] eqn: Heqpr_item_x\n        ; [| done].\n        destruct oitem' as [item' |]\n        ; inversion Hpr_item_x; subst; clear Hpr_item_x\n        ; inversion Hproject_x; subst; clear Hproject_x\n        ; state_update_simpl\n        ; [| by split].\n        by simpl; rewrite (composite_transition_item_projection_neq IM i).\n    }\n    destruct Hfinal'i as [Hfinal'i Hpr_xi].\n    rewrite <- Hfinal'i in HtrXi'.\n    specialize (IHtr _ HtrXi').\n    destruct IHtr as [Heqv_initial Hpr_trXi'].\n    split; [done |].\n    subst.\n    by apply map_option_app.\nQed.\n\n(**\n  A generalization of [equivocators_transition_item_project_preserves_zero_descriptors]\n  to full (valid) traces.\n*)\nLemma equivocators_trace_project_preserves_zero_descriptors\n  (is : composite_state equivocator_IM)\n  (tr : list (composite_transition_item equivocator_IM))\n  (Htr : finite_valid_trace_from PreFreeE is tr)\n  (descriptors : equivocator_descriptors)\n  (idescriptors : equivocator_descriptors)\n  (trX : list (composite_transition_item IM))\n  (HtrX : equivocators_trace_project descriptors tr = Some (trX, idescriptors))\n  : forall i, descriptors i = Existing 0 -> idescriptors i = Existing 0.\nProof.\n  generalize dependent trX. generalize dependent descriptors.\n  induction Htr using finite_valid_trace_from_rev_ind; [by inversion 1; subst |].\n  intros descriptors trX HtrX i Hi.\n  apply equivocators_trace_project_app_iff in HtrX\n    as (preX & sufX & descriptors' & Hproject_x & Hproject_tr & _).\n  simpl in Hproject_x.\n  destruct\n    (equivocators_transition_item_project descriptors x)\n    as [(oitemx, _descriptors') |] eqn: Hpr_x; [| by congruence].\n  assert (_descriptors' = descriptors') as -> by (destruct oitemx; congruence).\n  clear Hproject_x trX sufX.\n  destruct Hx as [(_ & _  & Hv & _) Ht].\n  eapply IHHtr; [done |].\n  by eapply equivocators_transition_item_project_preserves_zero_descriptors\n       with (item := x); cycle 1.\nQed.\n\nLemma preloaded_equivocators_valid_trace_from_project\n  (final_descriptors : equivocator_descriptors)\n  (is : composite_state equivocator_IM)\n  (tr : list (composite_transition_item equivocator_IM))\n  (final_state := finite_trace_last is tr)\n  (Hproper : proper_equivocator_descriptors final_descriptors final_state)\n  (Htr : finite_valid_trace_from PreFreeE is tr)\n  : exists\n    (trX : list (composite_transition_item IM))\n    (initial_descriptors : equivocator_descriptors),\n    equivocators_trace_project final_descriptors tr = Some (trX, initial_descriptors)\n    /\\ proper_equivocator_descriptors initial_descriptors is\n    /\\ equivocators_state_project final_descriptors (finite_trace_last is tr)\n     = finite_trace_last (equivocators_state_project initial_descriptors is) trX.\nProof.\n  generalize dependent final_descriptors; generalize dependent is.\n  induction tr using rev_ind; intros; [by exists [], final_descriptors |].\n  apply finite_valid_trace_from_app_iff in Htr.\n  destruct Htr as [Htr Hx].\n  specialize (IHtr _ Htr).\n  specialize (equivocators_transition_item_project_proper_characterization final_descriptors x)\n    as Hproperx.\n  unfold final_state in Hproper.\n  rewrite finite_trace_last_is_last in Hproper.\n  specialize (Hproperx Hproper).\n  destruct Hproperx as [oitem [final_descriptors' [Hprojectx [Hitemx Hproperx]]]].\n  specialize (Hproperx (finite_trace_last is tr)).\n  unfold equivocators_trace_project.\n  rewrite fold_right_app.\n  match goal with\n  |- context [fold_right _ ?fld _] => remember fld as foldx\n  end.\n  simpl in Heqfoldx.\n  rewrite Hprojectx in Heqfoldx.\n  inversion Hx. subst tl s' x. clear Hx.\n  destruct Ht as [[_ [_ [Hv _]]] Ht].\n  specialize (Hproperx Hv Ht).\n  destruct Hproperx as [Hproper' [Heq_final_descriptors' [Heq_ltr [Hex_new Hx]]]].\n  specialize (IHtr _ Hproper').\n  destruct IHtr as [trX' [initial_descriptors [Htr_project [Hproper_initial Hlst]]]].\n  destruct oitem as [item |].\n  - simpl in Hitemx. destruct Hitemx as [Hl [Hinput [Houtput [Hdestination _]]]].\n    specialize (Hx _ eq_refl).\n    destruct Hx as [Hvx Htx].\n    exists (trX' ++ [item]), initial_descriptors. subst foldx.\n    by erewrite equivocators_trace_project_folder_additive, !finite_trace_last_is_last.\n  - exists trX', initial_descriptors.\n    subst; split_and!; [done .. |].\n    by rewrite finite_trace_last_is_last; congruence.\nQed.\n\nLemma equivocators_trace_project_zero_descriptors\n  (is : composite_state equivocator_IM)\n  (tr : list (composite_transition_item equivocator_IM))\n  (Htr : finite_valid_trace_from PreFreeE is tr)\n  : exists (trX : list (composite_transition_item IM)),\n    equivocators_trace_project (zero_descriptor IM) tr = Some (trX, (zero_descriptor IM)).\nProof.\n  specialize\n    (preloaded_equivocators_valid_trace_from_project\n      (zero_descriptor IM) is tr)\n    as Hproject.\n  simpl in Hproject. spec Hproject; [by apply zero_descriptor_proper |].\n  specialize (Hproject Htr).\n  destruct Hproject as [trX [initial_descriptors [Hproject _]]].\n  exists trX.\n  replace initial_descriptors with (zero_descriptor IM) in Hproject; [done |].\n  apply functional_extensionality_dep. intros i. symmetry.\n  by apply (equivocators_trace_project_preserves_zero_descriptors _ _ Htr _ _ _ Hproject).\nQed.\n\nLemma preloaded_equivocators_valid_trace_project_inv\n  (final_descriptors : equivocator_descriptors)\n  (is : composite_state equivocator_IM)\n  (tr : list (composite_transition_item equivocator_IM))\n  (final_state := finite_trace_last is tr)\n  (Htr : finite_valid_trace PreFreeE is tr)\n  (trX : list (composite_transition_item IM))\n  (initial_descriptors : equivocator_descriptors)\n  (Hproject : equivocators_trace_project final_descriptors tr = Some (trX, initial_descriptors))\n  (Hproper : proper_equivocator_descriptors initial_descriptors is)\n  : proper_equivocator_descriptors final_descriptors final_state.\nProof.\n  revert Hproject. revert trX Htr final_descriptors.\n  induction tr using rev_ind; intros; [by inversion Hproject |].\n  destruct Htr as [Htr Hinit].\n  apply finite_valid_trace_from_app_iff in Htr.\n  destruct Htr as [Htr Hx].\n  unfold equivocators_trace_project in Hproject.\n  rewrite fold_right_app in Hproject.\n  match type of Hproject with\n  | fold_right _ ?f _ = _ => remember f as project_x\n  end.\n  simpl in Heqproject_x.\n  destruct project_x as [(x', x_descriptors) |]\n  ; [| by rewrite equivocators_trace_project_fold_None in Hproject; congruence].\n  destruct (equivocators_transition_item_project final_descriptors x) as [(oitem', ditem') |]\n    eqn: Hproject_x\n  ; [| by congruence].\n  apply (equivocators_trace_project_folder_additive_iff tr x' x_descriptors initial_descriptors trX)\n  in Hproject.\n  destruct Hproject as [trX' [Hproject_x' HeqtrX]].\n  specialize (IHtr trX' (conj Htr Hinit) _ Hproject_x').\n  inversion Hx. subst. clear Hx.\n  unfold equivocators_transition_item_project in Hproject_x.\n  simpl in Hproject_x.\n  unfold composite_transition_item_projection in Hproject_x. simpl in Hproject_x.\n  unfold composite_transition_item_projection_from_eq in Hproject_x. simpl in Hproject_x.\n  unfold eq_rect_r in Hproject_x. simpl in Hproject_x.\n  match type of Hproject_x with\n  | context [equivocator_vlsm_transition_item_project ?X ?i ?c] =>\n      remember (equivocator_vlsm_transition_item_project X i c)  as projecti\n  end.\n  destruct projecti as [(oitem'', ditem'') |]; [| by congruence].\n  unfold equivocator_vlsm_transition_item_project in Heqprojecti.\n  unfold final_state in *. clear final_state.\n  rewrite finite_trace_last_is_last. simpl.\n  destruct (final_descriptors (projT1 l)) as [sn | j] eqn: Hfinali.\n  - inversion Heqprojecti. subst. clear Heqprojecti.\n    inversion Hproject_x. subst; clear Hproject_x.\n    inversion Heqproject_x. subst. clear Heqproject_x.\n    intro e. specialize (IHtr e).\n    destruct (decide (e = projT1 l)).\n    + subst.\n      unfold equivocator_descriptors_update in IHtr;\n        rewrite equivocator_descriptors_update_eq in IHtr.\n      by rewrite Hfinali.\n    + state_update_simpl.\n      destruct Ht as [Hv Ht].\n      simpl in Ht. unfold vtransition in Ht. simpl in Ht.\n      destruct l as (i, li).\n      match type of Ht with\n      | (let (_, _) := ?t in _) = _ => destruct t as (si', om')\n      end.\n      inversion Ht. subst. simpl in n.\n      by state_update_simpl.\n  - destruct l as (i, li).\n    unfold projT1, projT2 in Heqprojecti.\n    destruct Ht as [Hv Ht].\n    cbn in Ht.\n    destruct (equivocator_transition _ _ _) as (si', om') eqn: Ht'.\n    inversion Ht. subst om'. clear Ht.\n    replace (s i) with si' in * by (subst; state_update_simpl; done).\n    destruct (equivocator_state_project si' j) as [si'j |] eqn: Hj; [| done].\n    by destruct li as [ndi | idi li | idi li]\n    ; destruct (decide _)\n    ; inversion Heqprojecti; subst; clear Heqprojecti\n    ; inversion Hproject_x; subst; clear Hproject_x\n    ; inversion Heqproject_x; subst; clear Heqproject_x\n    ; intro eqv; specialize (IHtr eqv)\n    ; (destruct (decide (i = eqv)); subst; state_update_simpl\n       ; cbn in *; [rewrite ?Hfinali; eexists |]; done).\nQed.\n\n(**\n  A corollary of [preloaded_equivocators_valid_trace_from_project] selecting\n  only the [proper_equivocator_descriptors] property.\n*)\nLemma preloaded_equivocators_valid_trace_project_proper_initial\n  (is : composite_state equivocator_IM)\n  (tr : list (composite_transition_item equivocator_IM))\n  (final_state := finite_trace_last is tr)\n  (Htr : finite_valid_trace_from PreFreeE is tr)\n  (final_descriptors : equivocator_descriptors)\n  (trX : list (composite_transition_item IM))\n  (initial_descriptors : equivocator_descriptors)\n  (Hproject : equivocators_trace_project final_descriptors tr = Some (trX, initial_descriptors))\n  (Hproper : proper_equivocator_descriptors final_descriptors final_state)\n  : proper_equivocator_descriptors initial_descriptors is.\nProof.\n  destruct\n    (preloaded_equivocators_valid_trace_from_project\n      final_descriptors is tr Hproper Htr)\n    as [_trX [_initial_descriptors [_Hproject [Hiproper _]]]].\n  rewrite Hproject in _Hproject.\n  by inversion _Hproject; subst.\nQed.\n\nLemma equivocators_trace_project_output_reflecting_inv\n  (is : composite_state equivocator_IM)\n  (tr : list (composite_transition_item equivocator_IM))\n  (Htr : finite_valid_trace_from (pre_loaded_with_all_messages_vlsm\n           (free_composite_vlsm equivocator_IM)) is tr)\n  (m : message)\n  (Hbbs : Exists (field_selector output m) tr)\n  : exists\n    (final_descriptors initial_descriptors : equivocator_descriptors)\n    (trX : list (composite_transition_item IM)),\n    not_equivocating_equivocator_descriptors IM final_descriptors (finite_trace_last is tr) /\\\n    equivocators_trace_project final_descriptors tr = Some (trX, initial_descriptors) /\\\n    Exists (field_selector output m) trX.\nProof.\n  apply Exists_exists in Hbbs.\n  destruct Hbbs as [item [Hitem Hm]]. simpl in Hm.\n  apply (finite_trace_projection_list_in  equivocator_IM) in Hitem.\n  destruct item. simpl in *. destruct l as (i, li). simpl in *.\n  specialize\n    (preloaded_finite_valid_trace_projection equivocator_IM i _ _ Htr)\n    as Htri.\n  specialize\n    (equivocator_vlsm_trace_project_output_reflecting_inv (IM i) _ _ Htri m) as Hex.\n  spec Hex; [by apply Exists_exists; eexists _ |].\n  destruct Hex as [eqv_final [eqv_init [Heqv_init [Heqv_final [trXi [Hprojecti Hex]]]]]].\n  specialize (VLSM_projection_finite_trace_last\n    (preloaded_component_projection equivocator_IM i) _ _ Htr) as Hlst.\n  simpl in Hlst, Heqv_final. rewrite <- Hlst in Heqv_final. clear Hlst.\n  match type of Heqv_final with\n  | existing_descriptor _ _ (?l i) => remember l as final\n  end.\n  remember (equivocator_descriptors_update (zero_descriptor IM) i eqv_final) as final_descriptors.\n  assert (Hfinal_descriptors : not_equivocating_equivocator_descriptors IM final_descriptors final).\n  {\n    intro eqv. subst final_descriptors.\n    destruct (decide (i = eqv)); subst; state_update_simpl; [done |].\n    by apply zero_descriptor_proper.\n  }\n  exists final_descriptors.\n  subst final.\n  assert (Hfinal_descriptors_proper :\n    proper_equivocator_descriptors final_descriptors (finite_trace_last is tr)).\n  { by apply not_equivocating_equivocator_descriptors_proper. }\n  destruct (preloaded_equivocators_valid_trace_from_project  _ _ _ Hfinal_descriptors_proper Htr)\n    as [trX [initial_descriptors [Hproject_tr _]]].\n  exists initial_descriptors, trX. split; [done |]. split; [done |].\n  specialize (equivocators_trace_project_finite_trace_projection_list_commute\n    i final_descriptors initial_descriptors\n      eqv_init tr trX trXi Hproject_tr)\n    as Hcommute.\n  assert (Hfinali : final_descriptors i = eqv_final) by (subst; state_update_simpl; done).\n  rewrite Hfinali in Hcommute.\n  specialize (Hcommute Hprojecti).\n  destruct Hcommute as [Hiniti Hcommute].\n  clear -Hex Hcommute. subst.\n  apply Exists_exists in Hex. destruct Hex as [x [Hx Hm]].\n  apply (finite_trace_projection_list_in_rev IM) in Hx.\n  destruct Hx as [itemX [HitemX [Houtput _]]].\n  apply Exists_exists. exists itemX. split; [done |].\n  by simpl; rewrite Houtput.\nQed.\n\nLemma equivocators_trace_project_output_reflecting_iff\n  (is : composite_state equivocator_IM)\n  (tr : list (composite_transition_item equivocator_IM))\n  (Htr : finite_valid_trace_from (pre_loaded_with_all_messages_vlsm\n          (free_composite_vlsm equivocator_IM)) is tr)\n  (m : message)\n  : Exists (field_selector output m) tr\n  <-> exists\n    (final_descriptors initial_descriptors : equivocator_descriptors)\n    (trX : list (composite_transition_item IM)),\n    not_equivocating_equivocator_descriptors IM final_descriptors (finite_trace_last is tr) /\\\n    equivocators_trace_project final_descriptors tr = Some (trX, initial_descriptors) /\\\n    Exists (field_selector output m) trX.\nProof.\n  split; [by apply equivocators_trace_project_output_reflecting_inv |].\n  intros [final_descriptors [initial_descriptors [trX [Hfinal_descriptors [Hpr_tr Hex]]]]].\n  apply Exists_exists in Hex.\n  destruct Hex as [itemX [HitemX Hm]].\n  apply elem_of_list_split in HitemX.\n  destruct HitemX as [preX [sufX Heq_trX]].\n  subst.\n  apply equivocators_trace_project_app_inv_item in Hpr_tr.\n  destruct Hpr_tr as [pre [suf [item [item_descriptors [pre_descriptors [_ [Hpr_item [_ Heqtr]]]]]]]].\n  subst.\n  rewrite !Exists_app. right. left. constructor.\n  apply equivocators_transition_item_project_inv_characterization in Hpr_item.\n  destruct Hpr_item as [_ [_ [Heqoutput _]]].\n  by simpl in *; congruence.\nQed.\n\n(**\n  Projecting a pre-loaded valid trace of the composition of equivocators\n  using [proper_equivocator_descriptors] one obtains a pre-loaded valid trace\n  of the free composition of nodes.\n*)\nLemma pre_equivocators_valid_trace_project\n  (is final_state : vstate equivocators_no_equivocations_vlsm)\n  (tr : list (composite_transition_item equivocator_IM))\n  (Htr : finite_valid_trace_init_to PreFreeE is final_state tr)\n  (final_descriptors : equivocator_descriptors)\n  (Hproper : proper_equivocator_descriptors final_descriptors final_state)\n  : exists\n    (initial_descriptors : equivocator_descriptors),\n    proper_equivocator_descriptors initial_descriptors is /\\\n    exists\n    (isX := equivocators_state_project initial_descriptors is)\n    (final_stateX := equivocators_state_project final_descriptors final_state)\n    (trX : list (composite_transition_item IM)),\n    equivocators_trace_project final_descriptors tr = Some (trX, initial_descriptors) /\\\n    finite_valid_trace_init_to PreFree isX final_stateX trX.\nProof.\n  generalize dependent final_descriptors.\n  generalize dependent final_state.\n  induction tr using rev_ind; intros.\n  - apply valid_trace_get_last in Htr as Hfinal_state_eq.\n    subst.\n    exists final_descriptors. split; [done |].\n    exists [].\n    repeat (split; [done |]).\n    cut (vinitial_state_prop (free_composite_vlsm IM)\n      (equivocators_state_project final_descriptors is)).\n    {\n      intro Hinit; split; [| done].\n      by constructor; apply initial_state_is_valid.\n    }\n    by apply (equivocators_initial_state_project IM); [apply Htr |].\n  - destruct Htr as [Htr Hinit].\n    apply finite_valid_trace_from_to_app_split in Htr.\n    destruct Htr as [Htr Hx].\n    specialize (IHtr _ (conj Htr Hinit)).\n    apply finite_valid_trace_from_to_last in Hx as Hfinal_state_eq.\n    change [x] with ([] ++ [x]) in Hfinal_state_eq.\n    rewrite finite_trace_last_is_last in Hfinal_state_eq.\n    subst.\n    destruct\n      (equivocators_transition_item_project_proper_characterization _ x Hproper)\n      as [oitem [final_descriptors' [Hpr_x [Hchar1 Hchar2]]]].\n    specialize (equivocators_trace_project_app_iff tr [x]) as Hpr_app.\n    inversion Hx. subst. clear Hx Htl.\n    destruct Ht as [[_ [_ [Hvx Hcx]]]  Htx].\n    specialize (Hchar2 (finite_trace_last is tr) Hvx Htx).\n    simpl in *.\n    destruct Hchar2 as [Hproper' [Heq_final_descriptors' [Heq_last_tr [Hex_new Hchar2]]]].\n    specialize (IHtr _ Hproper').\n    destruct IHtr as [initial_descriptors [Hproper_initial [trX [Hpr_tr HtrX]]]].\n    exists initial_descriptors.\n    split; [done |].\n    specialize (Hpr_app initial_descriptors final_descriptors).\n    destruct oitem as [item |].\n    + exists (trX ++ [item]).\n      destruct HtrX as [HtrX HinitX].\n      repeat split; [.. | done].\n      * apply (Hpr_app (trX ++ [item])).\n        exists trX, [item], final_descriptors'.\n        by rewrite Hpr_x.\n      * apply\n          (finite_valid_trace_from_to_app PreFree\n            (equivocators_state_project final_descriptors' (finite_trace_last is tr)))\n        ; [done |].\n        specialize (Hchar2 _ eq_refl).\n        destruct item. destruct l0 as (ix, lix).\n        destruct l as (i, li).\n        simpl in *.\n        destruct Hchar1 as [[Hex Heq_l] [Heq_input [Heq_output [Hpr_s Heq_descli]]]].\n        simplify_eq.\n        destruct Hchar2 as [Hvx_pr Htx_pr].\n        apply finite_valid_trace_from_to_singleton.\n        repeat split\n        ; [| apply any_message_is_valid_in_preloaded | done | done].\n        by apply finite_valid_trace_from_to_last_pstate in HtrX.\n    + exists trX. clear Hchar1. rewrite Hchar2.\n      split; [| done].\n      apply (Hpr_app trX).\n      exists trX, [], final_descriptors'.\n      by rewrite Hpr_x, app_nil_r.\nQed.\n\nDefinition equivocators_partial_trace_project\n  (final_descriptors : equivocator_descriptors)\n  (str : composite_state equivocator_IM * list (composite_transition_item equivocator_IM))\n  : option (composite_state IM * list (composite_transition_item IM))\n  :=\n  let (s, tr) := str in\n  if\n    (decide (not_equivocating_equivocator_descriptors IM final_descriptors\n      (finite_trace_last s tr)))\n  then\n    match equivocators_trace_project final_descriptors tr with\n    | None => None\n    | Some (trX, initial_descriptors) =>\n        Some (equivocators_state_project initial_descriptors s, trX)\n    end\n    else None.\n\nLemma equivocators_partial_trace_project_characterization\n  (final_descriptors : equivocator_descriptors)\n  (X := free_composite_vlsm equivocator_IM)\n  (partial_trace_project := equivocators_partial_trace_project final_descriptors)\n  sX trX sY trY\n  : partial_trace_project (sX, trX) = Some (sY, trY) <->\n    not_equivocating_equivocator_descriptors IM final_descriptors (finite_trace_last sX trX) /\\\n    exists initial_descriptors,\n      equivocators_trace_project final_descriptors trX = Some (trY, initial_descriptors) /\\\n      equivocators_state_project initial_descriptors sX = sY.\nProof.\n  unfold partial_trace_project, equivocators_partial_trace_project.\n  split.\n  - intros Hpr_tr.\n    case_decide; [| by congruence].\n    destruct (equivocators_trace_project final_descriptors trX)\n      as [(_trY, initial_descriptors) |] eqn: Htr_project\n    ; [| by congruence].\n    by inversion Hpr_tr; subst _trY; clear Hpr_tr; eauto.\n  - intros [Hnot_equiv [initial_descriptors [Hpr_tr Hpr_s]]].\n    by rewrite decide_True, Hpr_tr; subst.\nQed.\n\nDefinition destruct_equivocators_partial_trace_project\n  {final_descriptors : equivocator_descriptors}\n  (X := free_composite_vlsm equivocator_IM)\n  (partial_trace_project := equivocators_partial_trace_project final_descriptors)\n  {sX trX sY trY}\n  (Hpr_tr : partial_trace_project (sX, trX) = Some (sY, trY))\n  : not_equivocating_equivocator_descriptors IM final_descriptors (finite_trace_last sX trX) /\\\n    exists initial_descriptors,\n      equivocators_trace_project final_descriptors trX = Some (trY, initial_descriptors) /\\\n      equivocators_state_project initial_descriptors sX = sY\n  := proj1 (equivocators_partial_trace_project_characterization\n      final_descriptors sX trX sY trY) Hpr_tr.\n\nDefinition construct_equivocators_partial_trace_project\n  {final_descriptors : equivocator_descriptors}\n  (X := free_composite_vlsm equivocator_IM)\n  (partial_trace_project := equivocators_partial_trace_project final_descriptors)\n  {sX trX sY trY}\n  (H : not_equivocating_equivocator_descriptors IM final_descriptors (finite_trace_last sX trX) /\\\n    exists initial_descriptors,\n      equivocators_trace_project final_descriptors trX = Some (trY, initial_descriptors) /\\\n      equivocators_state_project initial_descriptors sX = sY)\n  : partial_trace_project (sX, trX) = Some (sY, trY)\n  := proj2 (equivocators_partial_trace_project_characterization final_descriptors sX trX sY trY) H.\n\nLemma equivocators_partial_trace_project_extends_left\n  (final_descriptors : equivocator_descriptors)\n  (X := free_composite_vlsm equivocator_IM)\n  (partial_trace_project := equivocators_partial_trace_project final_descriptors)\n  : forall sX trX sY trY,\n  partial_trace_project (sX, trX) = Some (sY, trY) ->\n  forall s'X preX,\n    finite_trace_last s'X preX = sX ->\n    finite_valid_trace_from (pre_loaded_with_all_messages_vlsm X) s'X (preX ++ trX) ->\n    exists s'Y preY,\n      partial_trace_project (s'X, preX ++ trX) = Some (s'Y, preY ++ trY) /\\\n      finite_trace_last s'Y preY = sY.\nProof.\n  intros s tr sX trX Hpr_tr s_pre pre Hs_lst Hpre_tr.\n  destruct (destruct_equivocators_partial_trace_project Hpr_tr)\n    as [Hnot_equiv [initial_descriptors [Htr_project Hs_project]]].\n  apply (finite_valid_trace_from_app_iff PreFreeE) in Hpre_tr.\n  destruct Hpre_tr as [Hpre Htr]. subst s sX.\n  apply not_equivocating_equivocator_descriptors_proper in Hnot_equiv as Hproper.\n  specialize\n    (preloaded_equivocators_valid_trace_project_proper_initial _ _ Htr\n      _ _ _ Htr_project Hproper)\n    as Hinitial_descriptors.\n  destruct\n    (preloaded_equivocators_valid_trace_from_project\n      _ _ _ Hinitial_descriptors Hpre)\n    as [preX [pre_descriptors [Hpre_project [Hpre_desciptors Hs_project]]]].\n  exists (equivocators_state_project pre_descriptors s_pre), preX.\n  split; [| done].\n  apply construct_equivocators_partial_trace_project.\n  split; [by rewrite finite_trace_last_app |].\n  exists pre_descriptors. split; [| done].\n  apply equivocators_trace_project_app_iff.\n  by exists preX, trX, initial_descriptors.\nQed.\n\n(**\n  The projection of an composite equivocator state using [zero_descriptor]s\n  which is guaranteed to always succeed.\n*)\nDefinition equivocators_total_state_project := equivocators_state_project (zero_descriptor IM).\n\nDefinition equivocators_total_label_project\n  (l : composite_label equivocator_IM) : option (composite_label IM) :=\n  let (i, li) := l in\n  option_map (existT i) (equivocator_label_zero_project _ li).\n\nDefinition equivocators_total_trace_project\n  (tr : list (composite_transition_item equivocator_IM))\n  : list (composite_transition_item IM)\n  :=\n  from_option fst [] (equivocators_trace_project (zero_descriptor IM) tr).\n\n(**\n  The projection of an composite equivocator trace using [zero_descriptor]s\n  which is guaranteed to always succeed.\n*)\nLemma equivocators_total_trace_project_characterization\n  {s tr}\n  (Hpre_tr : finite_valid_trace_from PreFreeE s tr)\n  : equivocators_trace_project (zero_descriptor IM) tr =\n    Some (equivocators_total_trace_project tr, zero_descriptor IM).\nProof.\n  unfold equivocators_total_trace_project.\n  by destruct (equivocators_trace_project_zero_descriptors _ _ Hpre_tr) as [_trX ->].\nQed.\n\nLemma equivocators_total_trace_project_app\n  (X := FreeE)\n  (trace_project := equivocators_total_trace_project)\n  : forall tr1X tr2X,\n      (exists sX, finite_valid_trace_from (pre_loaded_with_all_messages_vlsm X) sX (tr1X ++ tr2X)) ->\n      trace_project (tr1X ++ tr2X) = trace_project tr1X ++ trace_project tr2X.\nProof.\n  intros tr1X tr2X [sX Hpre_tr].\n  specialize (equivocators_total_trace_project_characterization Hpre_tr) as Htr12_pr.\n  apply equivocators_trace_project_app_iff in Htr12_pr.\n  destruct Htr12_pr as [tr1Y [tr2Y [descriptors [Htr2_pr [Htr1_pr Htr12_eq]]]]].\n  apply (finite_valid_trace_from_app_iff PreFreeE) in Hpre_tr.\n  destruct Hpre_tr as [Hpre_tr1 Hpre_tr2].\n  rewrite (equivocators_total_trace_project_characterization Hpre_tr2) in Htr2_pr.\n  inversion Htr2_pr. subst. clear Htr2_pr.\n  rewrite (equivocators_total_trace_project_characterization Hpre_tr1) in Htr1_pr.\n  by inversion Htr1_pr; subst.\nQed.\n\nLemma equivocators_total_VLSM_projection_finite_trace_project\n  {s tr}\n  (Hpre_tr : finite_valid_trace_from PreFreeE s tr)\n  : @pre_VLSM_projection_finite_trace_project _ (type PreFreeE) _ equivocators_total_label_project\n      equivocators_total_state_project tr = equivocators_total_trace_project tr.\nProof.\n  induction tr using rev_ind; [done |].\n  rewrite equivocators_total_trace_project_app by (eexists; done).\n  rewrite @pre_VLSM_projection_finite_trace_project_app.\n  apply finite_valid_trace_from_app_iff in Hpre_tr as [Hpre_tr Hpre_x].\n  specialize (IHtr Hpre_tr).\n  rewrite IHtr.\n  f_equal.\n  inversion Hpre_x. subst.\n  destruct Ht as [[_ [_ [Hv _]]] Ht]. destruct l as (i, [sn | ji li | ji li])\n  ; unfold equivocators_total_trace_project; cbn in *\n  ; unfold equivocators_transition_item_project; cbn in *\n  ; rewrite !equivocator_state_project_zero.\n  - inversion_clear Ht.\n    rewrite decide_False; [done |].\n    by state_update_simpl; cbn.\n  - destruct (equivocator_state_project _ _) as [s_i |]; [| done].\n    destruct (vtransition _ _ _) as (si', _om').\n    inversion_clear Ht. state_update_simpl.\n    destruct ji as [| ji].\n    + by rewrite decide_True.\n    + by rewrite decide_False.\n  - destruct (equivocator_state_project _ _) as [s_i |]; [| done].\n    destruct (vtransition _ _ _) as (si', _om').\n    inversion_clear Ht.\n    by state_update_simpl; cbn; rewrite decide_False.\nQed.\n\nLemma equivocators_total_trace_project_final_state\n  (X := FreeE)\n  (state_project := equivocators_total_state_project)\n  (trace_project := equivocators_total_trace_project)\n  : forall sX trX,\n      finite_valid_trace_from (pre_loaded_with_all_messages_vlsm X) sX trX ->\n      state_project (finite_trace_last sX trX) =\n      finite_trace_last (state_project sX) (trace_project trX).\nProof.\n  intros sX trX Hpre_tr.\n  specialize (equivocators_total_trace_project_characterization Hpre_tr) as Htr_pr.\n  specialize\n    (preloaded_equivocators_valid_trace_from_project (zero_descriptor IM) sX trX)\n    as Hproject.\n  simpl in Hproject; spec Hproject; [by apply zero_descriptor_proper |].\n  specialize (Hproject Hpre_tr).\n  destruct Hproject as [_trX [initial_descriptors [_Htr_pr [_ Hlst]]]].\n  rewrite Htr_pr in _Htr_pr.\n  by inversion _Htr_pr; subst.\nQed.\n\nLemma PreFreeE_PreFree_vlsm_partial_projection\n  (final_descriptors : equivocator_descriptors)\n  : VLSM_partial_projection PreFreeE PreFree (equivocators_partial_trace_project final_descriptors).\nProof.\n  split; [by split; apply equivocators_partial_trace_project_extends_left |].\n  intros s tr sX trX Hpr_tr Htr.\n  destruct (destruct_equivocators_partial_trace_project Hpr_tr)\n    as [Hnot_equiv [initial_descriptors [Htr_project Hs_project]]].\n  apply valid_trace_add_default_last in Htr.\n  apply not_equivocating_equivocator_descriptors_proper in Hnot_equiv as Hproper.\n  destruct (pre_equivocators_valid_trace_project _ _ _ Htr _ Hproper)\n    as [_initial_descriptors [_ [_trX [_Htr_project HtrX]]]].\n  rewrite Htr_project in _Htr_project.\n  inversion _Htr_project; subst.\n  by apply valid_trace_forget_last in HtrX.\nQed.\n\nEnd sec_equivocators_composition_projections.\n\nSection sec_equivocators_composition_sub_projections.\n\nContext\n  {message : Type}\n  `{finite.Finite index}\n  (IM : index -> VLSM message)\n  `{forall i : index, HasBeenSentCapability (IM i)}\n  (selection : list index)\n  .\n\n(**\n  A generalization of [equivocators_trace_project_finite_trace_projection_list_commute]\n  to projections over a set of indices.\n\n  We can project a trace over the composition of equivocators in two ways:\n\n  - first project to a subset of equivocator components, then project that to the corresponding\n    subset of the composition of the original components\n\n  - first project to the composition of original components, then project to a subset of them\n\n  The results below (fist for a single item, then for the full trace say that the\n  two ways lead to the same result.\n*)\nLemma equivocators_trace_project_finite_trace_sub_projection_item_commute\n  (item : composite_transition_item (equivocator_IM IM))\n  (final_descriptors' final_descriptors : equivocator_descriptors IM)\n  (final_sub_descriptors := fun i : sub_index selection => final_descriptors (` i))\n  (pr_item : list (composite_transition_item IM))\n  (Hpr_item : equivocators_trace_project IM final_descriptors [item] =\n                Some (pr_item, final_descriptors'))\n  (pr_sub_item : list (composite_transition_item (sub_IM IM selection)))\n  (final_sub_descriptors' : equivocator_descriptors (sub_IM IM selection))\n  (Hpr_sub_item :\n    equivocators_trace_project (sub_IM IM selection) final_sub_descriptors\n      (finite_trace_sub_projection (equivocator_IM IM) selection [item]) =\n    Some (pr_sub_item, final_sub_descriptors'))\n  : final_sub_descriptors' = (fun i : sub_index selection => final_descriptors' (` i))\n  /\\ finite_trace_sub_projection IM selection pr_item = pr_sub_item.\nProof.\n  unfold equivocators_trace_project in Hpr_item. unfold sub_IM in *.\n  simpl in *.\n  destruct (equivocators_transition_item_project IM final_descriptors item)\n    as [(ox, final') |] eqn: Hpr_item_x\n  ; [| by congruence].\n  unfold equivocators_transition_item_project in Hpr_item_x.\n  unfold composite_transition_item_projection in Hpr_item_x.\n  remember (equivocator_vlsm_transition_item_project (IM (projT1 (l item)))\n    (composite_transition_item_projection_from_eq (equivocator_IM IM) item\n      (projT1 (l item)) eq_refl) (final_descriptors (projT1 (l item))))\n    as pr_item_x.\n  destruct pr_item_x as [(oitem', descriptor') |]; [| by congruence].\n\n  unfold composite_transition_item_projection_from_eq in Heqpr_item_x.\n  unfold eq_rect_r in Heqpr_item_x.\n  simpl in Heqpr_item_x.\n  unfold pre_VLSM_projection_transition_item_project\n    , composite_label_sub_projection_option in Hpr_sub_item.\n  case_decide as Hl.\n  - simpl in Hpr_sub_item.\n    unfold final_sub_descriptors in *.\n    unfold equivocators_transition_item_project in Hpr_sub_item.\n    match type of Hpr_sub_item with\n    | context [equivocator_vlsm_transition_item_project ?X ?i ?c]\n      => remember (equivocator_vlsm_transition_item_project X i c) as project\n    end.\n    simpl in Heqproject.\n    unfold\n      composite_transition_item_projection,\n      composite_transition_item_projection_from_eq,\n      eq_rect_r,\n      composite_state_sub_projection in Heqproject.\n    simpl in Heqproject.\n    rewrite <-  Heqpr_item_x in Heqproject. clear Heqpr_item_x.\n    subst project.\n    simpl in Hpr_sub_item.\n    split.\n    + extensionality i.\n      destruct oitem' as [item' |]\n      ; inversion Hpr_sub_item; subst; clear Hpr_sub_item\n      ; inversion Hpr_item_x; subst; clear Hpr_item_x\n      ; inversion Hpr_item; subst; clear Hpr_item\n      ; simpl\n      ; destruct (decide ((proj1_sig i) = projT1 (l item))).\n      * rewrite equivocator_descriptors_update_eq_rew with (Heq := e).\n        assert (e1 : i = (dexist (projT1 (l item)) Hl)) by (apply dsig_eq; done).\n        subst i.\n        rewrite equivocator_descriptors_update_eq_rew with (Heq := eq_refl).\n        simpl in e. replace e with (eq_refl (projT1 (l item))); [done |].\n        by apply Eqdep_dec.UIP_dec.\n      * by rewrite! equivocator_descriptors_update_neq; [| | intros ->].\n      * rewrite equivocator_descriptors_update_eq_rew with (Heq := e).\n        assert (e1 : i = (dexist (projT1 (l item)) Hl)) by (apply dsig_eq; done).\n        subst i.\n        rewrite equivocator_descriptors_update_eq_rew with (Heq := eq_refl).\n        simpl in e. replace e with (eq_refl (projT1 (l item))); [done |].\n        by apply Eqdep_dec.UIP_dec.\n      * by rewrite! equivocator_descriptors_update_neq; [| | intros ->].\n    + destruct oitem' as [item' |]\n      ; inversion Hpr_sub_item; subst; clear Hpr_sub_item\n      ; inversion Hpr_item_x; subst; clear Hpr_item_x\n      ; inversion Hpr_item; subst; clear Hpr_item\n      ; simpl; [| done].\n      unfold pre_VLSM_projection_transition_item_project,\n        composite_label_sub_projection_option.\n      simpl.\n      case_decide as _Hl; [| done].\n      do 2 f_equal.\n      unfold composite_label_sub_projection.\n      by apply\n        (@dec_sig_sigT_eq _\n          (sub_index_prop selection)\n          (sub_index_prop_dec selection)\n          (fun n => vlabel (IM n))\n          (projT1 (l item)) (l item') (l item') _Hl Hl).\n  - simpl in Hpr_sub_item. unfold final_sub_descriptors in *.\n    inversion Hpr_sub_item. subst. clear Hpr_sub_item.\n    split.\n    + extensionality i.\n      assert (Hnot : proj1_sig i <> projT1 (l item)).\n      { intro Hnot. contradict Hl. destruct i. simpl in Hnot. subst.\n        by apply bool_decide_spec in i.\n      }\n      by destruct oitem' as [item' |]\n      ; inversion Hpr_item_x; subst; clear Hpr_item_x\n      ; inversion Hpr_item; subst; clear Hpr_item\n      ; state_update_simpl.\n    + destruct oitem' as [item' |]\n      ; inversion Hpr_item_x; subst; clear Hpr_item_x\n      ; inversion Hpr_item; subst; clear Hpr_item\n      ; simpl; [| done].\n      unfold from_sub_projection. simpl.\n      unfold pre_VLSM_projection_transition_item_project,\n        composite_label_sub_projection_option.\n      by case_decide.\nQed.\n\nLemma equivocators_trace_project_finite_trace_sub_projection_commute\n  (final_descriptors initial_descriptors : equivocator_descriptors IM)\n  (initial_sub_descriptors : equivocator_descriptors (sub_IM IM selection))\n  (tr : list (composite_transition_item (equivocator_IM IM)))\n  (trX : list (composite_transition_item IM))\n  (tr_subX : list (composite_transition_item (sub_IM IM selection)))\n  (final_sub_descriptors := fun i : sub_index selection => final_descriptors (proj1_sig i))\n  (Hproject_tr : equivocators_trace_project IM final_descriptors tr = Some (trX, initial_descriptors))\n  (Hproject_sub_tr :\n    equivocators_trace_project (sub_IM IM selection) final_sub_descriptors\n      (finite_trace_sub_projection (equivocator_IM IM) selection tr)\n    = Some (tr_subX, initial_sub_descriptors))\n  : initial_sub_descriptors = (fun i => initial_descriptors (proj1_sig i)) /\\\n    finite_trace_sub_projection IM selection trX = tr_subX.\nProof.\n  generalize dependent tr_subX. generalize dependent trX.\n  generalize dependent final_descriptors.\n  induction tr using rev_ind; intros.\n  - by inversion Hproject_tr; inversion Hproject_sub_tr; subst.\n  - unfold equivocators_trace_project in Hproject_tr.\n    rewrite fold_right_app in Hproject_tr.\n    match type of Hproject_tr with\n    | fold_right _ ?i _ = _ => destruct i as [(projectx, final_descriptors') |] eqn: Hproject_x\n    end\n    ; [| by rewrite equivocators_trace_project_fold_None in Hproject_tr; inversion Hproject_tr].\n    apply equivocators_trace_project_folder_additive_iff in Hproject_tr.\n    destruct Hproject_tr as [trX0 [HtrX0 HtrX]].\n    specialize (IHtr _ _ HtrX0).\n    rewrite finite_trace_sub_projection_app in Hproject_sub_tr.\n    apply equivocators_trace_project_app_iff in Hproject_sub_tr.\n    destruct Hproject_sub_tr as [tr_subX' [project_sub_x [final_sub_descriptors'\n      [Hproject_sub_x [Htr_subX' Heqtr_subX]]]]].\n    specialize\n      (equivocators_trace_project_finite_trace_sub_projection_item_commute\n        x _ _ _ Hproject_x _ _ Hproject_sub_x)\n      as Hfinal_sub'.\n\n    destruct Hfinal_sub' as [Hfinal_sub' Hpr_sub_x].\n    subst final_sub_descriptors'.\n    specialize (IHtr _ Htr_subX').\n    destruct IHtr as [Heqv_initial Hpr_trXi'].\n    split; [done |].\n    subst.\n    by apply finite_trace_sub_projection_app.\nQed.\n\nSection sec_seeded_equivocators_valid_trace_project.\n\nContext\n  (seed : message -> Prop)\n  (SeededXE := seeded_equivocators_no_equivocation_vlsm IM selection seed)\n  (sub_equivocator_IM := sub_IM (equivocator_IM IM) selection)\n  (SubFreeE := free_composite_vlsm sub_equivocator_IM)\n  (SubPreFreeE := pre_loaded_with_all_messages_vlsm SubFreeE)\n  (sub_IM := sub_IM IM selection)\n  (SubFree := free_composite_vlsm sub_IM)\n  (SeededX := pre_loaded_vlsm SubFree seed)\n  .\n\nLemma seeded_equivocators_initial_message\n  (m : message)\n  (Hem : vinitial_message_prop SeededXE m)\n  : vinitial_message_prop SeededX m.\nProof.\n  destruct Hem as [[eqv [emi Hem]] | Hseed].\n  - by left; exists eqv, emi.\n  - by right.\nQed.\n\nLemma seeded_no_equivocation_incl_preloaded\n  : VLSM_incl SeededXE SubPreFreeE.\nProof.\n  by apply seeded_no_equivocation_incl_preloaded.\nQed.\n\nLemma seeded_equivocators_valid_trace_project\n  (is : composite_state sub_equivocator_IM)\n  (tr : list (composite_transition_item sub_equivocator_IM))\n  (Htr : finite_valid_trace SeededXE is tr)\n  (final_state := finite_trace_last is tr)\n  (final_descriptors : (equivocator_descriptors sub_IM))\n  (Hproper : proper_equivocator_descriptors sub_IM final_descriptors final_state)\n  : exists\n    (trX : list (composite_transition_item sub_IM))\n    (initial_descriptors : equivocator_descriptors sub_IM)\n    (isX := equivocators_state_project sub_IM initial_descriptors is)\n    (final_stateX := finite_trace_last isX trX),\n    proper_equivocator_descriptors sub_IM initial_descriptors is /\\\n    equivocators_trace_project sub_IM final_descriptors tr = Some (trX, initial_descriptors) /\\\n    equivocators_state_project sub_IM final_descriptors final_state = final_stateX /\\\n    finite_valid_trace SeededX isX trX.\nProof.\n  assert (Htr_to : finite_valid_trace_init_to SeededXE is final_state tr).\n  { destruct Htr as [Htr Hinit]. split; [| done].\n    by apply finite_valid_trace_from_add_last.\n  }\n  assert (Hpre_tr_to : finite_valid_trace_init_to SubPreFreeE is final_state tr).\n  {\n    revert Htr_to; apply VLSM_incl_finite_valid_trace_init_to.\n    by apply seeded_no_equivocation_incl_preloaded.\n  }\n  pose proof (pre_equivocators_valid_trace_project _ _ _ _\n    Hpre_tr_to final_descriptors Hproper) as Hex.\n  destruct Hex as [initial_descriptors [Hproper_initial [trX [Hpr_trX Hpre_trX]]]].\n  exists trX, initial_descriptors.\n  split; [done |]. split; [done |].\n  apply finite_valid_trace_init_to_last in Hpre_trX as Hfinal_stateX.\n  symmetry in Hfinal_stateX.\n  split; [done |].\n  clear -SubPreFreeE Htr Hproper Hpr_trX.\n  remember (length tr) as len_tr.\n  generalize dependent trX.\n  generalize dependent initial_descriptors.\n  generalize dependent final_descriptors. generalize dependent tr.\n  induction len_tr using (well_founded_induction Wf_nat.lt_wf); intros.\n  subst len_tr.\n  destruct_list_last tr tr' lst Htr_lst.\n  - clear H. subst. subst final_state. simpl in *. inversion Hpr_trX. subst.\n    cut (vinitial_state_prop SubFree (equivocators_state_project sub_IM initial_descriptors is)).\n    { intro. split; [| done]. constructor.\n      apply valid_state_prop_iff. left.\n      by exists (exist _ _ H).\n    }\n    apply equivocators_initial_state_project; [| done].\n    by apply Htr.\n  - specialize (H (length tr')) as H'.\n    spec H'; [by rewrite app_length; cbn; lia |].\n    destruct Htr as [Htr Hinit].\n    apply finite_valid_trace_from_app_iff in Htr.\n    destruct Htr as [Htr Hlst].\n    specialize (H' tr' (conj Htr Hinit) eq_refl).\n    specialize (equivocators_transition_item_project_proper_characterization sub_IM\n      final_descriptors lst) as Hproperx.\n    unfold final_state in Hproper. rewrite Htr_lst in Hproper.\n    rewrite finite_trace_last_is_last in Hproper.\n    specialize (Hproperx Hproper).\n    destruct Hproperx as [oitem [final_descriptors' [Hprojectx [Hitemx Hproperx]]]].\n    specialize (Hproperx (finite_trace_last is tr')).\n    apply equivocators_trace_project_app_iff in Hpr_trX.\n    destruct Hpr_trX as [trX' [lstX [_final_descriptors' [_Hprojectx [Hpr_trX' Heq_trX]]]]].\n    subst trX tr.\n    simpl in _Hprojectx.\n    replace (equivocators_transition_item_project _ _ _) with (Some (oitem, final_descriptors'))\n      in _Hprojectx.\n    assert (Heq_final_descriptors' : final_descriptors' = _final_descriptors')\n      by (destruct oitem; inversion _Hprojectx; done).\n    subst _final_descriptors'.\n    inversion Hlst. subst tl s' lst.\n    destruct Ht as [[Hs [Hiom [Hv Hc]]] Ht].\n    specialize (Hproperx Hv Ht). clear Hv Ht.\n    destruct Hproperx as [Hproper' [Heq_final_descriptors' [_ [_ Hx]]]].\n    specialize (H' _ Hproper' _ _ Hpr_trX').\n    destruct H' as [HtrX' HinitX].\n    split; [| done]. apply finite_valid_trace_from_app_iff.\n    split; [done |].\n    assert (Hlst_trX' : valid_state_prop SeededX (finite_trace_last\n      (equivocators_state_project sub_IM initial_descriptors is) trX')).\n    { by apply (finite_valid_trace_last_pstate SeededX) in HtrX'. }\n    destruct oitem as [item |]; inversion _Hprojectx; subst lstX; clear _Hprojectx\n    ; [| by constructor].\n    simpl in Hitemx. destruct Hitemx as [Hl [Hinput [Houtput [Hdestination _]]]].\n    specialize (Hx _ eq_refl).\n    destruct Hx as [Hvx Htx].\n    destruct item. simpl in *. subst.\n    apply finite_valid_trace_singleton.\n    assert (Htr_to : finite_valid_trace_init_to SeededXE is (finite_trace_last is tr') tr')\n      by (split; [apply finite_valid_trace_from_add_last |]; done).\n    assert (Hpre_tr_to : finite_valid_trace_init_to SubPreFreeE is (finite_trace_last is tr') tr').\n    {\n      revert Htr_to; apply VLSM_incl_finite_valid_trace_init_to.\n      by apply seeded_no_equivocation_incl_preloaded.\n    }\n    pose proof (pre_equivocators_valid_trace_project sub_IM _ _ _\n     Hpre_tr_to final_descriptors' Hproper') as Hpr_tr'.\n    destruct Hpr_tr' as [_initial_descriptors [_ [_trX' [_Hpr_trX' Heq_final_stateX']]]].\n    replace (equivocators_trace_project _ _ _) with (Some (trX', initial_descriptors))\n      in _Hpr_trX'.\n    inversion _Hpr_trX'. subst _initial_descriptors _trX'.\n    apply finite_valid_trace_init_to_last in Heq_final_stateX'.\n    simpl in *.\n    rewrite <- Heq_final_stateX' in Htx, Hvx.\n    repeat split; [done | | done | done].\n\n    destruct input as [input |]; [| by apply option_valid_message_None].\n    apply proj1 in Hc. simpl in Hc.\n    apply or_comm in Hc.\n    destruct Hc as [Hinit_input | Hno_equiv]\n    ; [by apply initial_message_is_valid, seeded_equivocators_initial_message; right |].\n    assert (Hs_free : valid_state_prop SubPreFreeE (finite_trace_last is tr'))\n      by (apply proj1, finite_valid_trace_from_to_last_pstate in Hpre_tr_to; done).\n    apply (composite_proper_sent sub_equivocator_IM _ Hs_free) in Hno_equiv.\n    specialize (Hno_equiv is tr' Hpre_tr_to).\n    apply finite_valid_trace_init_to_forget_last in Hpre_tr_to as Hpre_tr.\n    destruct (equivocators_trace_project_output_reflecting_inv _ _ _ (proj1 Hpre_tr) _ Hno_equiv)\n      as [final_descriptors_m [initial_descriptors_m [trXm [Hfinal_descriptors_m\n          [Hproject_trXm Hex]]]]].\n    specialize (H (length tr')).\n    spec H; [by rewrite app_length; cbn; lia |].\n    specialize (H tr' (conj Htr Hinit) eq_refl).\n    assert (Hfinal_descriptors_m_proper :\n      proper_equivocator_descriptors sub_IM final_descriptors_m (finite_trace_last is tr'))\n      by (apply not_equivocating_equivocator_descriptors_proper; done).\n    specialize (H final_descriptors_m Hfinal_descriptors_m_proper).\n    pose proof (pre_equivocators_valid_trace_project _ _ _ _\n     Hpre_tr_to final_descriptors_m Hfinal_descriptors_m_proper) as Hpr_tr'.\n    destruct Hpr_tr' as [initial_descriptors_m' [Hproper_initial_m [trXm' [Hproject_trXm' HtrXm]]]].\n    specialize (H _ _ Hproject_trXm').\n    simpl in *. rewrite Hproject_trXm in Hproject_trXm'.\n    inversion Hproject_trXm'. subst trXm' initial_descriptors_m'. clear Hproject_trXm'.\n    apply option_valid_message_Some.\n    by apply (valid_trace_output_is_valid _ _ _ (proj1 H) _ Hex).\nQed.\n\nLemma SeededXE_incl_PreFreeE\n  : VLSM_incl SeededXE SubPreFreeE.\nProof.\n  apply basic_VLSM_strong_incl.\n  - by intros s Hn n; itauto.\n  - by cbv; itauto.\n  - by destruct 1.\n  - by cbv; itauto.\nQed.\n\nLemma PreSeededXE_incl_PreFreeE\n  : VLSM_incl (pre_loaded_with_all_messages_vlsm SeededXE) SubPreFreeE.\nProof.\n  by apply basic_VLSM_incl_preloaded; [intro | inversion 1 | intro].\nQed.\n\nLemma SeededXE_SeededX_vlsm_partial_projection\n  (final_descriptors : equivocator_descriptors sub_IM)\n  : VLSM_partial_projection SeededXE SeededX\n      (equivocators_partial_trace_project sub_IM final_descriptors).\nProof.\n  split; [split |].\n  - intros s tr sX trX Hpr_tr s_pre pre Hs_lst Hpre_tr.\n    assert\n      (HPreFree_pre_tr : finite_valid_trace_from SubPreFreeE s_pre (pre ++ tr)).\n    {\n      revert Hpre_tr; apply VLSM_incl_finite_valid_trace_from.\n      by apply SeededXE_incl_PreFreeE.\n    }\n    clear Hpre_tr. revert s tr sX trX Hpr_tr s_pre pre Hs_lst HPreFree_pre_tr.\n    by apply equivocators_partial_trace_project_extends_left.\n  - intros s tr sX trX Hpr_tr Htr.\n    destruct (destruct_equivocators_partial_trace_project sub_IM  Hpr_tr)\n      as [Hnot_equiv [initial_descriptors [Htr_project Hs_project]]].\n    apply not_equivocating_equivocator_descriptors_proper in Hnot_equiv as Hproper.\n    destruct (seeded_equivocators_valid_trace_project _ _ Htr _ Hproper)\n      as [_trX [_initial_descriptors [_ [_Htr_project [_ HtrX]]]]].\n    rewrite Htr_project in _Htr_project.\n    by inversion _Htr_project; subst.\nQed.\n\nEnd sec_seeded_equivocators_valid_trace_project.\n\nEnd sec_equivocators_composition_sub_projections.\n\nSection sec_equivocators_composition_vlsm_projection.\n\nContext {message : Type}\n  `{finite.Finite index}\n  (IM : index -> VLSM message)\n  `{forall i : index, HasBeenSentCapability (IM i)}\n  (equivocators_no_equivocations_vlsm := equivocators_no_equivocations_vlsm IM)\n  (equivocators_state_project := equivocators_state_project IM)\n  (equivocator_IM := equivocator_IM IM)\n  (equivocator_descriptors_update := equivocator_descriptors_update IM)\n  (proper_equivocator_descriptors := proper_equivocator_descriptors IM)\n  (FreeE := free_composite_vlsm equivocator_IM)\n  (PreFreeE := pre_loaded_with_all_messages_vlsm FreeE)\n  (Free := free_composite_vlsm IM)\n  (PreFree := pre_loaded_with_all_messages_vlsm Free)\n  (sub_IM := sub_IM IM (finite.enum index))\n  .\n\n#[local] Hint Unfold equivocator_descriptors_update : state_update.\n\nDefinition free_sub_free_equivocator_descriptors\n  (descriptors : equivocator_descriptors IM)\n  : equivocator_descriptors sub_IM\n  := fun i => descriptors (proj1_sig i).\n\nLemma equivocators_no_equivocations_vlsm_X_vlsm_partial_projection\n  (final_descriptors : equivocator_descriptors IM)\n  : VLSM_partial_projection equivocators_no_equivocations_vlsm Free\n      (equivocators_partial_trace_project IM final_descriptors).\nProof.\n  split; [split |].\n  - intros s tr sX trX Hpr_tr s_pre pre Hs_lst Hpre_tr.\n    assert\n      (HPreFree_pre_tr : finite_valid_trace_from PreFreeE s_pre (pre ++ tr)).\n    {\n      revert Hpre_tr; apply VLSM_incl_finite_valid_trace_from.\n      by apply equivocators_no_equivocations_vlsm_incl_PreFree.\n    }\n    clear Hpre_tr.  revert s tr sX trX Hpr_tr s_pre pre Hs_lst HPreFree_pre_tr.\n    by apply equivocators_partial_trace_project_extends_left.\n  - intros s tr sX trX Hpr_tr Htr.\n    destruct (destruct_equivocators_partial_trace_project IM Hpr_tr)\n      as [Hnot_equiv [initial_descriptors [Htr_project Hs_project]]].\n    apply not_equivocating_equivocator_descriptors_proper in Hnot_equiv as Hproper.\n\n    specialize (sub_composition_all_embedding equivocator_IM\n      (equivocators_no_equivocations_constraint IM)) as Hproj.\n    apply (VLSM_embedding_finite_valid_trace Hproj) in Htr.\n    specialize\n      (false_composite_no_equivocation_vlsm_with_pre_loaded\n        (SubProjectionTraces.sub_IM equivocator_IM (enum index))\n        (free_constraint _))\n      as Heq.\n    assert (Htr' :\n      finite_valid_trace\n        (composite_vlsm\n          (SubProjectionTraces.sub_IM equivocator_IM (enum index))\n          (no_equivocations_additional_constraint\n            (SubProjectionTraces.sub_IM equivocator_IM (enum index))\n            (free_constraint _)))\n        (composite_state_sub_projection equivocator_IM (finite.enum index) s)\n        (VLSM_embedding_finite_trace_project Hproj tr)).\n    { revert Htr.\n      apply VLSM_incl_finite_valid_trace.\n      clear.\n      apply constraint_subsumption_incl.\n      apply preloaded_constraint_subsumption_stronger.\n      apply strong_constraint_subsumption_strongest.\n      intros (i, li) (s, om).\n      unfold free_sub_free_constraint, lift_sub_label, free_sub_free_state, free_sub_free_index.\n      unfold equivocators_no_equivocations_constraint.\n      intros [Hno_equiv _].\n      split; [| done].\n      destruct om as [m |]; [| done].\n      left. destruct Hno_equiv as [Hno_equiv | Hfalse]; [| done].\n      destruct Hno_equiv as [eqv Hno_equiv].\n      by exists (dexist eqv (SubProjectionTraces.free_sub_free_index_obligation_1 eqv)).\n    }\n    apply (VLSM_eq_finite_valid_trace Heq) in Htr'.\n\n    specialize\n      (seeded_equivocators_valid_trace_project IM\n        (enum index)\n        (fun m => False)\n        _ _ Htr'\n        (free_sub_free_equivocator_descriptors final_descriptors))\n      as Hproject.\n    spec Hproject.\n    {\n      clear -Hproper. intro sub_i.\n      destruct_dec_sig sub_i i Hi Heqsub_i. subst.\n      rewrite <- (VLSM_embedding_finite_trace_last Hproj).\n      by apply Hproper.\n    }\n    destruct Hproject  as [_trX [_initial_descriptors [_ [_Htr_project [_ HtrX]]]]].\n\n    specialize\n      (equivocators_trace_project_finite_trace_sub_projection_commute IM (enum index)\n        final_descriptors initial_descriptors _initial_descriptors tr trX _trX\n        Htr_project)\n      as Hcommute.\n    spec Hcommute.\n    { replace (finite_trace_sub_projection _ _ _)\n        with (VLSM_embedding_finite_trace_project Hproj tr)\n      ; [done |].\n      clear.\n      induction tr; [done |].\n      simpl.\n      unfold pre_VLSM_projection_transition_item_project,\n        composite_label_sub_projection_option,\n        pre_VLSM_embedding_transition_item_project.\n      simpl.\n      case_decide as Hla; [| contradict Hla; apply elem_of_enum].\n      f_equal; [| done].\n      destruct a, l as (i, li); cbn; f_equal.\n      unfold composite_label_sub_projection;\n      cbn; unfold free_sub_free_index.\n      by apply\n        (@dec_sig_sigT_eq _ _\n          (sub_index_prop_dec (enum index))\n          (fun n => vlabel (EquivocatorsComposition.equivocator_IM IM n))\n          i li li).\n    }\n    destruct Hcommute as [Heq_initial Heq_trX].\n    subst.\n    clear -HtrX.\n    specialize\n      (vlsm_is_pre_loaded_with_False\n        (free_composite_vlsm (SubProjectionTraces.sub_IM IM (finite.enum index))))\n      as Heq.\n    apply (VLSM_eq_finite_valid_trace Heq) in HtrX.\n    specialize (sub_composition_all_embedding_rev IM (free_constraint IM)) as Hproj.\n    assert (HtrX' : finite_valid_trace\n      (composite_vlsm (SubProjectionTraces.sub_IM IM (finite.enum index))\n      (free_sub_free_constraint IM (free_constraint IM)))\n      (EquivocatorsComposition.equivocators_state_project\n        (SubProjectionTraces.sub_IM IM (finite.enum index))\n        (fun i : sub_index (finite.enum index) => initial_descriptors (` i))\n        (composite_state_sub_projection equivocator_IM (finite.enum index) s))\n      (finite_trace_sub_projection IM (finite.enum index) trX)).\n    { revert HtrX.\n      apply VLSM_incl_finite_valid_trace.\n      apply constraint_subsumption_incl.\n      by intros [] [].\n    }\n    apply (VLSM_embedding_finite_valid_trace Hproj) in HtrX'.\n    replace (free_sub_free_state _ _)\n      with (EquivocatorsComposition.equivocators_state_project IM initial_descriptors s)\n      in HtrX'\n    ; [replace (VLSM_embedding_finite_trace_project _ _) with trX\n      in HtrX' |]\n    ; [done | | done].\n    clear.\n    induction trX; [done |].\n    simpl.\n    unfold pre_VLSM_projection_transition_item_project,\n      composite_label_sub_projection_option.\n    simpl.\n    case_decide as Hla; [| contradict Hla; apply elem_of_enum].\n    cbn; f_equal; [| done].\n    by destruct a, l as [i li].\nQed.\n\nLemma equivocators_valid_trace_from_project\n  (final_descriptors : equivocator_descriptors IM)\n  (is final_state : vstate equivocators_no_equivocations_vlsm)\n  (tr : list (composite_transition_item equivocator_IM))\n  (Hproper : not_equivocating_equivocator_descriptors IM final_descriptors final_state)\n  (Htr : finite_valid_trace_from_to equivocators_no_equivocations_vlsm is final_state tr)\n  : exists\n    isX final_stateX\n    (trX : list (composite_transition_item IM))\n    (initial_descriptors : equivocator_descriptors IM),\n    isX = equivocators_state_project initial_descriptors is /\\\n    proper_equivocator_descriptors initial_descriptors is /\\\n    equivocators_trace_project IM final_descriptors tr = Some (trX, initial_descriptors) /\\\n    equivocators_state_project final_descriptors final_state = final_stateX /\\\n    finite_valid_trace_from_to Free isX final_stateX trX.\nProof.\n  apply valid_trace_get_last in Htr as Hfinal_state. apply valid_trace_forget_last in Htr.\n  subst final_state.\n  specialize (VLSM_partial_projection_finite_valid_trace_from\n    (equivocators_no_equivocations_vlsm_X_vlsm_partial_projection final_descriptors) is tr) as Hsim.\n  unfold equivocators_partial_trace_project in Hsim.\n  rewrite decide_True in Hsim by done.\n  assert (HPreFree_tr : finite_valid_trace_from PreFreeE is tr).\n  {\n    revert Htr; apply VLSM_incl_finite_valid_trace_from.\n    by apply equivocators_no_equivocations_vlsm_incl_PreFree.\n  }\n  apply not_equivocating_equivocator_descriptors_proper in Hproper.\n  destruct\n    (preloaded_equivocators_valid_trace_from_project _\n      _ _ _ Hproper HPreFree_tr)\n    as [trX [initial_descriptors [Htr_project [Hinitial_desciptors Hfinal_project]]]].\n  eexists. eexists. eexists. eexists. split; [done |]. split; [by apply Hinitial_desciptors |].\n  split; [by apply Htr_project |]. split; [by apply Hfinal_project |].\n  apply valid_trace_add_default_last.\n  apply Hsim; [| done].\n  by rewrite Htr_project.\nQed.\n\nLemma PreFreeE_Free_vlsm_projection_type\n  : VLSM_projection_type PreFreeE _\n      (equivocators_total_label_project IM) (equivocators_total_state_project IM).\nProof.\n  apply basic_VLSM_projection_type.\n  intros l Hl s om s' om' [[_ [_ [Hv _]]] Ht].\n  destruct l as [i [sn | ji li | ji li]]; cbn in Hv, Ht.\n  - inversion_clear Ht. unfold equivocators_total_state_project.\n    by state_update_simpl.\n  - simpl in Hl. destruct ji as [| ji]; [by inversion Hl |]. clear Hl.\n    destruct (equivocator_state_project _ _) as [si |]; [| done].\n    destruct (vtransition _ _ _) as (si', _om').\n    inversion_clear Ht.  unfold equivocators_total_state_project.\n    by state_update_simpl.\n  - destruct (equivocator_state_project _ _) as [si |]; [| done].\n    destruct (vtransition _ _ _) as (si', _om').\n    inversion_clear Ht.  unfold equivocators_total_state_project.\n    by state_update_simpl.\nQed.\n\nLemma equivocators_no_equivocations_vlsm_X_vlsm_projection\n  : VLSM_projection equivocators_no_equivocations_vlsm Free\n      (equivocators_total_label_project IM) (equivocators_total_state_project IM).\nProof.\n  constructor; [constructor |].\n  - intros * Htr. apply PreFreeE_Free_vlsm_projection_type.\n    apply VLSM_incl_finite_valid_trace_from; [| done].\n    by apply equivocators_no_equivocations_vlsm_incl_PreFree.\n  - intros * Htr.\n    assert (Hpre_tr : finite_valid_trace PreFreeE sX trX).\n    {\n      apply VLSM_incl_finite_valid_trace; [| done].\n      by apply equivocators_no_equivocations_vlsm_incl_PreFree.\n    }\n    specialize\n     (VLSM_partial_projection_finite_valid_trace\n      (equivocators_no_equivocations_vlsm_X_vlsm_partial_projection (zero_descriptor IM))\n       sX trX (equivocators_total_state_project IM sX) (equivocators_total_trace_project IM trX))\n     as Hsim.\n    spec Hsim.\n    { simpl. rewrite decide_True by apply zero_descriptor_not_equivocating.\n      by rewrite (equivocators_total_trace_project_characterization IM (proj1 Hpre_tr)).\n    }\n    apply Hsim in Htr.\n    remember (pre_VLSM_projection_finite_trace_project _ _ _ _ _) as tr.\n    replace tr with (equivocators_total_trace_project IM trX); [done |].\n    subst. symmetry.\n    by eapply (equivocators_total_VLSM_projection_finite_trace_project IM), Hpre_tr.\nQed.\n\nLemma preloaded_equivocators_no_equivocations_vlsm_X_vlsm_projection\n  : VLSM_projection PreFreeE PreFree\n      (equivocators_total_label_project IM) (equivocators_total_state_project IM).\nProof.\n  constructor; [constructor; intros |].\n  - by apply PreFreeE_Free_vlsm_projection_type.\n  - intros * Htr.\n    specialize (VLSM_partial_projection_finite_valid_trace\n      (PreFreeE_PreFree_vlsm_partial_projection IM (zero_descriptor IM))\n      sX trX (equivocators_total_state_project IM sX) (equivocators_total_trace_project IM trX))\n      as Hsim.\n    spec Hsim.\n    { simpl. rewrite decide_True by apply zero_descriptor_not_equivocating.\n      by rewrite (equivocators_total_trace_project_characterization IM (proj1 Htr)).\n    }\n    apply Hsim in Htr as Hpr.\n    remember (pre_VLSM_projection_finite_trace_project _ _ _ _ _) as tr.\n    replace tr with (equivocators_total_trace_project IM trX); [done |].\n    subst. symmetry.\n    by eapply equivocators_total_VLSM_projection_finite_trace_project, Htr.\nQed.\n\nEnd sec_equivocators_composition_vlsm_projection.\n", "meta": {"author": "runtimeverification", "repo": "vlsm", "sha": "9115beb539257427467872ce65a224a0268cdae7", "save_path": "github-repos/coq/runtimeverification-vlsm", "path": "github-repos/coq/runtimeverification-vlsm/vlsm-9115beb539257427467872ce65a224a0268cdae7/theories/VLSM/Core/Equivocators/EquivocatorsCompositionProjections.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.208164308824618}}
{"text": "Require Import Lia Framework ATCDLayer File FileDiskNoninterference.\nRequire Import LoggedDiskRefinement LogCache.RepImplications Not_Init.\nRequire Import ATCD_Simulation.\n\nOpaque LogCache.recover.\nLemma ATCD_AOE_recover:\nforall l_grs u,\nabstract_oracles_exist_wrt\nATCD_Refinement\n(fun s1 s2 => refines_reboot (snd (snd s1)) (snd (snd s2)) /\\\nfst s1 = fst s2 /\\\nfst (snd s1)  = fst (snd s2)) u\n(Simulation.Definitions.compile ATC_Refinement File.recover)\n(Simulation.Definitions.compile ATC_Refinement File.recover)\n(ATCD_reboot_list l_grs).\nProof.\n    unfold ATCD_reboot_list,\n    abstract_oracles_exist_wrt;\n    induction l_grs; simpl; intros.\n    { (* base case *)\n      repeat invert_exec; cleanup.\n      (* eapply_fresh minimal_oracle_finished_same in H7. *)\n      invert_exec'' H7.\n      invert_exec'' H9.\n      repeat invert_exec; cleanup.\n      eapply lift2_invert_exec in H12; cleanup.\n      eapply lift2_invert_exec in H4; cleanup.\n      repeat cleanup_pairs; eauto.\n      eexists [_]; simpl.\n      intuition eauto.\n      left; intuition eauto.\n      do 2 eexists; intuition eauto.\n      repeat (rewrite cons_app;\n      repeat econstructor; eauto).\n      eapply lift2_exec_step.\n      eapply lift2_exec_step; eauto.\n      right; do 7 eexists; intuition eauto.\n      3: eapply lift2_exec_step;\n      eapply lift2_exec_step; eauto.\n      2: simpl; repeat econstructor; eauto.\n      eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      simpl; eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      left; eexists; simpl in *; intuition eauto.\n      destruct t; eauto.\n      eapply LogCache.recover_finished; eauto.\n    }\n    { (* Inductive case *)\n      repeat invert_exec; cleanup.\n      (* eapply_fresh exec_crashed_minimal_oracle in H10; cleanup. *)\n      invert_exec'' H10; repeat invert_exec; cleanup.\n      {\n        invert_exec'' H8; repeat invert_exec; cleanup.\n        eapply lift2_invert_exec_crashed in H13; cleanup.\n        eapply lift2_invert_exec_crashed in H4; cleanup.\n        repeat cleanup_pairs; eauto.\n\n        edestruct IHl_grs; only 2: eauto.\n        simpl.\n        unfold refines,\n        refines_reboot in *;\n        simpl in *; cleanup.\n        eapply LogCache.recover_crashed in H5; eauto.\n        simpl in *; cleanup.\n        clear H2.\n        eexists (_, (_, _)); repeat split.\n        repeat split_ors.\n        simpl; eapply cached_log_reboot_rep_to_reboot_rep in c; eauto.\n        simpl; eapply cached_log_crash_rep_during_recovery_to_reboot_rep in c; eauto.\n        simpl; eapply cached_log_crash_rep_after_commit_to_reboot_rep in c; eauto.\n        apply select_total_mem_synced.\n\n      eexists (_::_); \n      simpl; intuition eauto.\n      eapply recovery_oracles_refine_length in H0.\n      rewrite H0; eauto.\n      eauto.\n      \n      right; intuition eauto.\n      eexists; intuition eauto.\n      rewrite cons_app.\n      econstructor.\n      repeat econstructor.\n      repeat eapply lift2_exec_step_crashed; eauto.\n      right; do 7 eexists; intuition eauto.\n      3: repeat eapply lift2_exec_step_crashed; eauto.\n      2: simpl; repeat econstructor; eauto.\n      eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      simpl; eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      right; eexists; simpl in *; intuition eauto.\n      eapply LogCache.recover_crashed; eauto.\n\n      simpl; eauto.\n    }\n    {\n      (* eapply exec_crashed_minimum_oracle in H5; cleanup. \n      rewrite <- app_assoc. *)\n      invert_exec'' H7; repeat invert_exec; cleanup.\n      edestruct IHl_grs; only 2: eauto.\n      simpl; eexists (_, (_, _)); simpl; split. \n      eapply refines_reboot_to_refines_reboot; eauto.\n      intuition eauto.\n\n      eexists (_::_); \n      simpl; intuition eauto.\n      eapply recovery_oracles_refine_length in H2.\n      rewrite H2; eauto.\n      eauto.\n      \n      right; intuition eauto.\n      eexists; intuition eauto.\n      repeat econstructor; eauto.\n      repeat cleanup_pairs.\n      repeat econstructor; eauto.\n\n      left; do 2 eexists; intuition eauto.\n      repeat cleanup_pairs.\n      repeat econstructor; eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      eexists; intuition eauto.\n      simpl; eauto.\n    }\n  }\n  Unshelve.\n  all: exact ATCDLang.\n  Qed.\n\n\n  (*\n  Lemma compile_lift2_comm:\n  forall u T (p: LoggedDiskLang.(prog) T) o s ret,\n  LayerImplementation.exec' u o s\n  (RefinementLift.compile\n      (HorizontalComposition AuthenticationOperation\n        TransactionCacheOperation)\n      (HorizontalComposition AuthenticationOperation\n        (TransactionalDiskLayer.TDCore\n            FSParameters.data_length)) ATCLang AD\n      (HC_Core_Refinement ATCLang AD\n        TDCoreRefinement) T\n      (lift_L2 AuthenticationOperation p)) ret ->\n\n      LayerImplementation.exec' u o s\n      (lift_L2 AuthenticationOperation \n        (TDRefinement.(Simulation.Definitions.compile) p)) ret.\n  Proof.\n    induction p; simpl; intros; eauto.\n    invert_exec'' H0.\n    eapply IHp in H7.\n    eapply H in H10.\n    econstructor; eauto.\n    eapply IHp in H6.\n    eapply ExecBindCrash; eauto.\n  Qed.\n\n\n  Lemma compile_lift2_comm_rev:\n  forall u T (p: TD.(prog) T) o s ret,\n  LayerImplementation.exec' u o s\n      (lift_L2 AuthenticationOperation \n        (TDRefinement.(Simulation.Definitions.compile) p)) ret ->\n  \n  LayerImplementation.exec' u o s\n  (RefinementLift.compile\n      (HorizontalComposition AuthenticationOperation\n        TransactionCacheOperation)\n      (HorizontalComposition AuthenticationOperation\n        (TransactionalDiskLayer.TDCore\n            FSParameters.data_length)) ATCLang AD\n      (HC_Core_Refinement ATCLang AD\n        TDCoreRefinement) T\n      (lift_L2 AuthenticationOperation p)) ret.\n  Proof.\n    induction p; simpl; intros; eauto.\n    invert_exec'' H0.\n    eapply IHp in H7.\n    eapply H in H10.\n    econstructor; eauto.\n    eapply IHp in H6.\n    eapply ExecBindCrash; eauto.\n  Qed.\n*)\n\nFixpoint non_colliding_selector_rec {T}\nu (R: state ATCDLang -> T -> Prop) l_selector (rec: prog ATCDLang unit) l_o s1 :=\n  match l_selector with\n  | nil => True\n  | selector :: ls =>\n    match l_o with\n    | nil => True\n    | o::lo =>\n    forall s1', \n    (exists s2, R s1 s2) ->\n    exec ATCDLang u o s1 rec (Crashed s1') ->\n    non_colliding_selector selector (snd (snd (snd s1'))) /\\\n    non_colliding_selector_rec u R ls rec lo \n    (ATCD_reboot_f selector s1')\n    end\n  end.\n\nDefinition non_colliding_selector_list {T T'}\nu (R: state ATCDLang -> T -> Prop) \n(Rc: state ATCDLang -> T -> Prop) \nl_selector \n(p: prog ATCDLang T') \n(rec: prog ATCDLang unit) l_o s1 :=\nmatch l_selector with\n  | nil => True\n  | selector :: ls =>\n    match l_o with\n    | nil => True\n    | o::lo =>\n    forall s1', \n    (exists s2, R s1 s2) ->\n    exec ATCDLang u o s1 p (Crashed s1') ->\n    non_colliding_selector selector (snd (snd (snd s1'))) /\\\n    non_colliding_selector_rec u Rc ls rec lo \n    (ATCD_reboot_f selector s1')\n    end\n  end.\n\nLemma ATCD_AOE':\nforall u T (p: ATCLang.(prog) T) l_grs l_o s1 s2, \n\n(forall o s s' r, \n(exists s1, ATCD_Refinement.(Simulation.Definitions.refines) s s1) ->\nexec ATCDLang u o s \n(ATCD_Refinement.(Simulation.Definitions.compile) p) (Finished s' r) ->\nexists oa, forall grs, \noracle_refines _ _\n  ATCDLang ATCLang\n  ATCD_CoreRefinement T u s p grs o oa) ->\n\n(forall o s s', \n(exists s1, ATCD_Refinement.(Simulation.Definitions.refines) s s1) ->\nexec ATCDLang u o s (ATCD_Refinement.(Simulation.Definitions.compile) p) (Crashed s') ->\nnon_colliding_selector\n  (seln l_grs 0 (fun _ : addr => 0))\n  (snd (snd (snd s'))) ->\nexists oa, \noracle_refines _ _\n  ATCDLang ATCLang\n  ATCD_CoreRefinement T u s p\n  (ATCD_reboot_f (seln l_grs 0 (fun _ => 0))) o oa) ->\n\n(forall o s s', \n(exists s1, ATCD_Refinement.(Simulation.Definitions.refines) s s1) ->\nexec ATCDLang u o s \n(ATCD_Refinement.(Simulation.Definitions.compile) p) (Crashed s') ->\nnon_colliding_selector\n  (seln l_grs 0 (fun _ : addr => 0))\n  (snd (snd (snd s'))) ->\nexists s1', \nATCD_refines_reboot (seln l_grs 0 (fun _ => 0)) s' s1') ->\n\nnon_colliding_selector_list\nu (ATCD_Refinement.(Simulation.Definitions.refines)) \n(ATCD_Refinement.(Simulation.Definitions.refines_reboot)) l_grs\n(ATCD_Refinement.(Simulation.Definitions.compile) p) \n(ATCD_Refinement.(Simulation.Definitions.compile) \n (ATC_Refinement.(Simulation.Definitions.compile) File.recover))  \n  l_o s1 ->\n\nabstract_oracles_exist_wrt_explicit ATCD_Refinement \n  (ATCD_Refinement.(Simulation.Definitions.refines)) u p \n  (ATC_Refinement.(Simulation.Definitions.compile) File.recover) \n  (ATCD_reboot_list l_grs) l_o s1 s2.\nProof.\n    intros; destruct l_grs; simpl; eauto.\n    {\n      unfold abstract_oracles_exist_wrt_explicit, ATCD_reboot_list in *; \n      simpl in *; intros.\n      repeat invert_exec.\n      simpl.\n      edestruct H; eauto.\n\n      eexists [_]; simpl; eauto.\n      split; intuition eauto.\n      left; do 2 eexists; intuition eauto.\n    }\n    {\n      unfold abstract_oracles_exist_wrt_explicit, ATC_reboot_list in *; \n      simpl in *; intros.\n      repeat invert_exec.\n      cleanup.\n      edestruct H2; eauto.\n      edestruct ATCD_AOE_recover; eauto.\n      {\n        unfold HC_refines in *; \n        simpl in *; cleanup.\n        edestruct H1; eauto.\n      }\n    \n      edestruct H0; eauto.\n\n      eexists (_ :: _).\n      simpl.\n      intuition eauto.\n      eapply recovery_oracles_refine_length in H6; eauto.\n      }\nQed.\n\nLemma ATCD_AOE:\nforall T (p: ATCLang.(prog) T) l_selector u l_o s1 s2,\nnot_init p ->\nnon_colliding_selector_list\nu (ATCD_Refinement.(Simulation.Definitions.refines)) \n(ATCD_Refinement.(Simulation.Definitions.refines_reboot)) l_selector\n(ATCD_Refinement.(Simulation.Definitions.compile) p) \n(ATCD_Refinement.(Simulation.Definitions.compile) \n (ATC_Refinement.(Simulation.Definitions.compile) File.recover))  \n  l_o s1 ->\nabstract_oracles_exist_wrt_explicit ATCD_Refinement\n(Simulation.Definitions.refines ATCD_Refinement) u p\n(Simulation.Definitions.compile ATC_Refinement File.recover)\n(ATCD_reboot_list l_selector) l_o s1 s2.\nProof.\nintros; eapply ATCD_AOE'.\n{\n  intros.\n  eapply ATCD_oracle_refines_finished; eauto.\n}\n{\n  intros.\n  eapply ATCD_oracle_refines_crashed; eauto.\n}\n{\n  intros; edestruct ATCD_simulation_crash; eauto.\n}\neauto.\nQed.\n", "meta": {"author": "Atalay-Ileri", "repo": "ConFrm", "sha": "80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf", "save_path": "github-repos/coq/Atalay-Ileri-ConFrm", "path": "github-repos/coq/Atalay-Ileri-ConFrm/ConFrm-80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf/src/Noninterference/LoggedDisk/ATCD_AOE.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.370225399544253, "lm_q1q2_score": 0.2081320196548347}}
{"text": "Require Import ExtLib.Structures.Monads.\nRequire Import ExtLib.Structures.Monoid.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nImport MonadNotation.\nLocal Open Scope monad_scope.\n\nSection except.\n  Variable T : Type.\n\n  Global Instance Monad_either : Monad (sum T) :=\n  { ret  := fun _ v => inr v\n  ; bind := fun _ _ c1 c2 => match c1 with\n                               | inl v => inl v\n                               | inr v => c2 v\n                             end\n  }.\n\n  Global Instance Exception_either : MonadExc T (sum T) :=\n  { raise := fun _ v => inl v\n  ; catch := fun _ c h => match c with\n                            | inl v => h v\n                            | x => x\n                          end\n  }.\n\n  Variable m : Type -> Type.\n\n  Inductive eitherT A := mkEitherT { unEitherT : m (sum T A) }.\n\n  Variable M : Monad m.\n\n  Global Instance Monad_eitherT : Monad eitherT :=\n  { ret := fun _ x => mkEitherT (ret (inr x))\n  ; bind := fun _ _ c f => mkEitherT (\n      xM <- unEitherT c ;;\n      match xM with\n      | inl x => ret (inl x)\n      | inr x => unEitherT (f x)\n      end\n    )\n  }.\n\n  Global Instance Exception_eitherT : MonadExc T eitherT :=\n  { raise := fun _ v => mkEitherT (ret (inl v))\n  ; catch := fun _ c h => mkEitherT (\n      xM <- unEitherT c ;;\n      match xM with\n        | inl x => unEitherT (h x)\n        | inr x => ret (inr x)\n      end\n    )\n  }.\n\n  Global Instance MonadPlus_eitherT : MonadPlus eitherT :=\n  { mplus _A _B mA mB := mkEitherT (\n      x <- unEitherT mA ;;\n      match x with\n      | inl _ =>\n          y <- unEitherT mB ;;\n          match y with\n          | inl t => ret (inl t)\n          | inr b => ret (inr (inr b))\n          end\n      | inr a => ret (inr (inl a))\n      end\n    )\n  }.\n\n  Global Instance MonadT_eitherT : MonadT eitherT m :=\n  { lift := fun _ c => mkEitherT (liftM ret c) }.\n\n  Global Instance MonadState_eitherT {T} (MS : MonadState T m) : MonadState T eitherT :=\n  { get := lift get\n  ; put := fun v => lift (put v)\n  }.\n\n  Global Instance MonadReader_eitherT {T} (MR : MonadReader T m) : MonadReader T eitherT :=\n  { ask := lift ask\n  ; local := fun _ f cmd => mkEitherT (local f (unEitherT cmd))\n  }.\n\n  Global Instance MonadWriter_eitherT {T} (Mon : Monoid T) (MW : MonadWriter Mon m) : MonadWriter Mon eitherT :=\n  { tell := fun x => lift (tell x)\n  ; listen := fun _ c => mkEitherT (\n    x <- listen (unEitherT c) ;;\n    match x with\n      | (inl l, _) => ret (inl l)\n      | (inr a, t) => ret (inr (a, t))\n    end)\n  ; pass := fun _ c => mkEitherT (\n    x <- unEitherT c ;;\n    match x with\n      | inl s => ret (inl s)\n      | inr (a,f) => pass (ret (inr a, f))\n    end)\n  }.\n\n  Global Instance MonadFix_eitherT (MF : MonadFix m) : MonadFix eitherT :=\n  { mfix := fun _ _ r v =>\n    mkEitherT (mfix (fun f x => unEitherT (r (fun x => mkEitherT (f x)) x)) v)\n  }.\n\nEnd except.\n\nArguments mkEitherT {T} {m} {A} (_).\nArguments unEitherT {T} {m} {A} (_).\n", "meta": {"author": "coq-community", "repo": "coq-ext-lib", "sha": "4811a83db9ccd81f4dcbf77eeff0484dfb21a48b", "save_path": "github-repos/coq/coq-community-coq-ext-lib", "path": "github-repos/coq/coq-community-coq-ext-lib/coq-ext-lib-4811a83db9ccd81f4dcbf77eeff0484dfb21a48b/theories/Data/Monads/EitherMonad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.20813200793570402}}
{"text": "Require Import Bedrock.Platform.AutoSep.\n\nSet Implicit Arguments.\n\nSection TopLevel.\n\n  Variable vars : list string.\n\n  Variable var : option string.\n\n  Definition is_state sp vs : HProp :=\n    locals vars vs 0 (sp ^+ $8).\n\n  Definition new_pre : assert :=\n    x ~> ExX, Ex vs,\n    ![^[is_state x#Sp vs] * #0]x.\n\n  Require Import Bedrock.Platform.Cito.Semantics.\n\n  Definition runs_to x_pre x :=\n    forall specs other vs,\n      interp specs (![is_state x_pre#Sp vs * other ] x_pre) ->\n      Regs x Sp = x_pre#Sp /\\\n      interp specs (![is_state (Regs x Sp) (upd_option vs var x_pre#Rv) * other ] (fst x_pre, x)).\n\n  Definition post (pre : assert) :=\n    st ~> Ex st_pre,\n    pre (fst st, st_pre) /\\\n    [| runs_to (fst st, st_pre) (snd st) |].\n\n  Definition imply (pre new_pre: assert) := forall specs x, interp specs (pre x) -> interp specs (new_pre x).\n\n  Definition syn_req :=\n    match var with\n      | Some x => List.In x vars\n      | None => True\n    end.\n\n  Definition verifCond pre := imply pre new_pre :: syn_req :: nil.\n\n  Variable imports : LabelMap.t assert.\n\n  Variable imports_global : importsGlobal imports.\n\n  Variable modName : string.\n\n  Definition Strline := Straightline_ imports modName.\n\n  Definition SaveRv lv := Strline (IL.Assign lv (RvLval (LvReg Rv)) :: nil).\n\n  Definition vars_start := 4 * 2.\n  Definition var_slot x := LvMem (Sp + (vars_start + variablePosition vars x)%nat)%loc.\n\n  Definition Skip := Straightline_ imports modName nil.\n\n  Definition body :=\n    match var with\n      | None => Skip\n      | Some x => SaveRv (var_slot x)\n    end.\n\n  Require Import Bedrock.Platform.Wrap.\n\n  Opaque mult.\n  Opaque evalInstrs.\n\n  Lemma evalInstrs_write_var : forall sm x s,\n    evalInstrs sm x (Assign (var_slot s) Rv :: nil)\n    = evalInstrs sm x (Assign (LvMem (Imm ((Regs x Sp ^+ natToW vars_start) ^+ natToW (variablePosition vars s)))) Rv :: nil).\n    Transparent evalInstrs.\n    simpl.\n    intros.\n    replace (Regs x Sp ^+ natToW (vars_start + variablePosition vars s))\n      with (Regs x Sp ^+ natToW vars_start ^+ natToW (variablePosition vars s)); auto.\n    rewrite natToW_plus.\n    words.\n    Opaque evalInstrs.\n  Qed.\n\n  Lemma postOk : forall specs pre x,\n    interp specs (Postcondition (body pre) x)\n    -> imply pre new_pre\n    -> syn_req\n    -> exists x0, interp specs (pre (fst x, x0))\n      /\\ runs_to (fst x, x0) (snd x).\n    intros.\n    unfold syn_req, body, runs_to in *.\n    destruct var; simpl in *; post.\n\n    Focus 2.\n    Transparent evalInstrs.\n    simpl in H2.\n    Opaque evalInstrs.\n    injection H2; clear H2; intros; subst.\n    descend; eauto.\n\n    Opaque mult.\n\n    Opaque mult.\n    Opaque evalInstrs.\n\n    rewrite evalInstrs_write_var in *.\n    generalize H2; intro Hs.\n    apply H0 in Hs; clear H0; post.\n    clear_fancy.\n    unfold vars_start in H3.\n    change (4 * 2) with 8 in *.\n    descend.\n    eauto.\n    clear H.\n    unfold is_state in H0.\n    evaluate auto_ext.\n    destruct x; simpl in *.\n    intuition.\n    unfold is_state.\n    step auto_ext.\n  Qed.\n  Opaque evalInstrs.\n\n  Lemma verifCondOk : forall pre,\n    imply pre new_pre\n    -> syn_req\n    -> vcs (VerifCond (body pre)).\n    unfold syn_req, body; intros.\n    destruct var; wrap0.\n    rewrite evalInstrs_write_var in *.\n    apply H in H1; clear H; post.\n    unfold is_state in H.\n    unfold vars_start in *.\n    change (4 * 2) with 8 in *.\n    clear_fancy.\n    evaluate auto_ext.\n    Transparent evalInstrs.\n    discriminate.\n    Opaque evalInstrs.\n  Qed.\n\n  Definition compile : cmd imports modName.\n    refine (Wrap imports imports_global modName body post verifCond _ _).\n\n    Opaque mult.\n    Opaque evalInstrs.\n\n    abstract (unfold verifCond; wrap0;\n      match goal with\n        | [ H : interp _ _ |- _ ] =>\n          apply postOk in H; post; descend; eauto\n      end).\n\n    Opaque mult.\n    Opaque evalInstrs.\n\n    abstract (unfold verifCond; wrap0; eauto using verifCondOk).\n Defined.\n\nEnd TopLevel.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Platform/Cito/SaveRet.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.20813200250422567}}
{"text": "(** printing |-#    %\\vdash_{\\#}%    #&vdash;<sub>&#35;</sub>#     *)\n(** printing |-##   %\\vdash_{\\#\\#}%  #&vdash;<sub>&#35&#35</sub>#  *)\n(** printing |-##v  %\\vdash_{\\#\\#v}% #&vdash;<sub>&#35&#35v</sub># *)\n(** printing |-!    %\\vdash_!%       #&vdash;<sub>!</sub>#         *)\n(** remove printing ~ *)\n\nSet Implicit Arguments.\n\nRequire Import TLC.LibLN.\nRequire Import String.\n\nRequire Import Coq.Program.Equality.\n\nRequire Import Definitions RecordAndInertTypes Decompose ConstrLangAlt.\n\n(** * Constraint Interpretation *)\n\n(** ** Ground assignments *)\n\nDefinition tctx := env typ.\nDefinition vctx := env var.\n\nReserved Notation \"e '⊧' C\" (at level 40).\nReserved Notation \"es '⊢t' T1 '⪯' T2\" (at level 40, T1 at level 59, T2 at level 59).\nReserved Notation \"es '⊢d' d1 '⪯' d2\" (at level 40, d1 at level 59, d2 at level 59).\nReserved Notation \"es '⊢v' x '⪯' y\" (at level 40, x at level 59, y at level 59).\nReserved Notation \"es '⊢vv' x '⪯' y\" (at level 40, x at level 59, y at level 59).\nReserved Notation \"es '⊢vd' x '⪯' y\" (at level 40, x at level 59, y at level 59).\nReserved Notation \"es '⊢vds' x '⪯' y\" (at level 40, x at level 59, y at level 59).\n\n(** *** Mapping with ground assignments *)\n\n(** Map a constraint variable to concrete variable. *)\nInductive map_cvar : vctx -> cvar -> avar -> Prop :=\n| map_cvar_f : forall vm x y,\n    binds x y vm ->\n    map_cvar vm (cvar_f x) (avar_f y)\n| map_cvar_x : forall vm x,\n    map_cvar vm (cvar_x x) x\n.\n\n(** Map a type containing type variables to a concrete type. *)\nInductive map_ctyp : (tctx * vctx) -> ctyp -> typ -> Prop :=\n\n| map_ctyp_top : forall tm vm,\n    (tm, vm) ⊢t ctyp_top ⪯ typ_top\n\n| map_ctyp_bot : forall tm vm,\n    (tm, vm) ⊢t ctyp_bot ⪯ typ_bot\n\n| map_ctyp_tvar : forall tm vm x T,\n    binds x T tm ->\n    (tm, vm) ⊢t ctyp_tvar (tvar_f x) ⪯ T\n\n| map_ctyp_rcd : forall tm vm D D',\n    (tm, vm) ⊢d D ⪯ D' ->\n    (tm, vm) ⊢t ctyp_rcd D ⪯ typ_rcd D'\n\n| map_ctyp_and : forall tm vm T T' U U',\n    (tm, vm) ⊢t T ⪯ T' ->\n    (tm, vm) ⊢t U ⪯ U' ->\n    (tm, vm) ⊢t ctyp_and T U ⪯ typ_and T' U'\n\n| map_ctyp_sel : forall tm vm x y T,\n    map_cvar vm x y ->\n    (tm, vm) ⊢t ctyp_sel x T ⪯ typ_sel y T\n\n| map_ctyp_bnd : forall tm vm T T',\n    (tm, vm) ⊢t T ⪯ T' ->\n    (tm, vm) ⊢t ctyp_bnd T ⪯ typ_bnd T'\n\n| map_ctyp_all : forall tm vm T T' U U',\n    (tm, vm) ⊢t T ⪯ T' ->\n    (tm, vm) ⊢t U ⪯ U' ->\n    (tm, vm) ⊢t ctyp_all T U ⪯ typ_all T' U'\n\nwhere \"es '⊢t' T1 '⪯' T2\" := (map_ctyp es T1 T2)\nwith map_cdec : (tctx * vctx) -> cdec -> dec -> Prop :=\n| map_cdec_typ : forall tm vm A S S' T T',\n    (tm, vm) ⊢t S ⪯ S' ->\n    (tm, vm) ⊢t T ⪯ T' ->\n    (tm, vm) ⊢d cdec_typ A S T ⪯ dec_typ A S' T'\n| map_cdec_trm : forall tm vm a T T',\n    (tm, vm) ⊢t T ⪯ T' ->\n    (tm, vm) ⊢d cdec_trm a T ⪯ dec_trm a T'\nwhere \"es '⊢d' D1 '⪯' D2\" := (map_cdec es D1 D2).\n\nInductive map_ctrm : (tctx * vctx) -> ctrm -> trm -> Prop :=\n| map_ctrm_cvar : forall tm vm x y,\n    map_cvar vm x y ->\n    (tm, vm) ⊢v ctrm_cvar x ⪯ trm_var y\n| map_ctrm_val : forall tm vm v v',\n    map_cval (tm, vm) v v' ->\n    (tm, vm) ⊢v ctrm_val v ⪯ trm_val v'\nwhere \"es '⊢v' t1 '⪯' t2\" := (map_ctrm es t1 t2)\nwith map_cval : (tctx * vctx) -> cval -> val -> Prop :=\n| map_cval_new : forall tm vm T T' ds ds',\n    (tm, vm) ⊢t T ⪯ T' ->\n    (tm, vm) ⊢vds ds ⪯ ds' ->\n    (tm, vm) ⊢vv cval_new T ds ⪯ val_new T' ds'\n| map_cval_lambda : forall tm vm T T' t t',\n    (tm, vm) ⊢t T ⪯ T' ->\n    (tm, vm) ⊢v t ⪯ t' ->\n    (tm, vm) ⊢vv cval_lambda T t ⪯ val_lambda T' t'\nwhere \"es '⊢vv' t1 '⪯' t2\" := (map_cval es t1 t2)\nwith map_cdef : (tctx * vctx) -> cdef -> def -> Prop :=\n| map_cdef_typ : forall tm vm A T T',\n    (tm, vm) ⊢t T ⪯ T' ->\n    (tm, vm) ⊢vd cdef_typ A T ⪯ def_typ A T'\n| map_cdef_trm : forall tm vm a t t',\n    (tm, vm) ⊢v t ⪯ t' ->\n    (tm, vm) ⊢vd cdef_trm a t ⪯ def_trm a t'\nwhere \"es '⊢vd' t1 '⪯' t2\" := (map_cdef es t1 t2)\nwith map_cdefs : (tctx * vctx) -> cdefs -> defs -> Prop :=\n| map_cdefs_nil : forall tm vm,\n    (tm, vm) ⊢vds cdefs_nil ⪯ defs_nil\n| map_cdefs_cons : forall tm vm ds ds' d d',\n    (tm, vm) ⊢vds ds ⪯ ds' ->\n    (tm, vm) ⊢vd d ⪯ d' ->\n    (tm, vm) ⊢vds cdefs_cons ds d ⪯ defs_cons ds' d'\nwhere \"es '⊢vds' t1 '⪯' t2\" := (map_cdefs es t1 t2).\n\nScheme map_ctyp_mut    := Induction for map_ctyp Sort Prop\nwith   map_cdec_mut    := Induction for map_cdec Sort Prop.\nCombined Scheme map_ctyp_mutind from map_ctyp_mut, map_cdec_mut.\n\nScheme map_ctrm_mut     := Induction for map_ctrm Sort Prop\nwith   map_cval_mut     := Induction for map_cval Sort Prop\nwith   map_cdef_mut     := Induction for map_cdef Sort Prop\nwith   map_cdefs_mut    := Induction for map_cdefs Sort Prop.\nCombined Scheme map_ctrm_mutind from map_ctrm_mut, map_cval_mut, map_cdef_mut, map_cdefs_mut.\n\n(** *** Properties of mapping *)\n\nLemma map_ctyp_unique_typ : forall tm vm T T1 T2,\n    (tm, vm) ⊢t T ⪯ T1 ->\n    (tm, vm) ⊢t T ⪯ T2 ->\n    T1 = T2\nwith map_cdec_unique_dec : forall tm vm D D1 D2,\n    (tm, vm) ⊢d D ⪯ D1 ->\n    (tm, vm) ⊢d D ⪯ D2 ->\n    D1 = D2.\nProof.\n  all: introv Hm1 Hm2.\n  - dependent induction T; inversion Hm1; inversion Hm2; subst; trivial; try f_equal.\n    -- inversion H7; subst. eapply binds_functional; eassumption.\n    -- apply~ map_cdec_unique_dec; eassumption.\n    -- specialize (IHT1 _ _ H4 H11). specialize (IHT2 _ _ H5 H12). subst. trivial.\n    -- specialize (IHT1 _ _ H4 H11). specialize (IHT2 _ _ H5 H12). subst. trivial.\n    -- destruct c.\n       + inversion H4; inversion H10; subst.\n         lets Heqy: (binds_functional H1 H6). subst. f_equal.\n       + inversion H4; inversion H10; subst.\n       + inversion H4; inversion H10; subst. trivial.\n    -- apply~ IHT.\n    -- specialize (IHT1 _ _ H4 H11). specialize (IHT2 _ _ H5 H12). subst. trivial.\n    -- specialize (IHT1 _ _ H4 H11). specialize (IHT2 _ _ H5 H12). subst. trivial.\n  - dependent induction D; inversion Hm1; inversion Hm2; subst; f_equal.\n    -- eapply map_ctyp_unique_typ; eassumption.\n    -- eapply map_ctyp_unique_typ; eassumption.\n    -- eapply map_ctyp_unique_typ; eassumption.\nQed.\n\nLemma map_tvar_tail : forall tm vm x T,\n    (tm & x ~ T, vm) ⊢t ctyp_tvar (tvar_f x) ⪯ T.\nProof.\n  introv. constructor. apply binds_push_eq.\nQed.\n\nLemma map_tvar_tail_eq : forall tm vm x T T',\n    (tm & x ~ T, vm) ⊢t ctyp_tvar (tvar_f x) ⪯ T' ->\n    T = T'.\nProof.\n  introv Hmx. inversion Hmx; subst.\n  symmetry. eapply binds_push_eq_inv. eauto.\nQed.\n\nLemma strengthen_map_ctyp : forall tm vm x T S S',\n    (tm & x ~ T, vm) ⊢t S ⪯ S' ->\n    x \\notin ftv_ctyp S ->\n    (tm, vm) ⊢t S ⪯ S'\nwith strengthen_map_cdec : forall tm vm x T D D',\n    (tm & x ~ T, vm) ⊢d D ⪯ D' ->\n    x \\notin ftv_cdec D ->\n    (tm, vm) ⊢d D ⪯ D'.\nProof.\n  all: introv Hmx Hn.\n  - induction S;\n      try (inversion Hmx; subst; constructor*);\n      try (apply* strengthen_map_ctyp; simpl in Hn; auto).\n    -- apply binds_concat_left_inv with (E2 := x ~ T); auto.\n       unfold notin. introv Hin. rewrite dom_single in Hin.\n       rewrite in_singleton in Hin. subst x0. simpl in Hn.\n       apply Hn. rewrite -> in_singleton. trivial.\n   - induction D; inversion Hmx; subst;\n       simpl in Hn; constructor; apply* strengthen_map_ctyp.\nQed.\n\nLemma map_iso_ctyp : forall tm vm T T',\n    T ⩭ T' ->\n    (tm, vm) ⊢t T ⪯ T'\nwith map_iso_cdec : forall tm vm D D',\n    iso_cdec_dec D D' ->\n    (tm, vm) ⊢d D ⪯ D'.\nProof.\n  all: introv Hc.\n  - dependent induction Hc; try constructor; try apply IHHc1; try apply IHHc2;\n      try apply IHHc.\n    -- apply* map_iso_cdec.\n    -- constructor.\n  - dependent induction Hc; try constructor; try apply IHHc;\n      try apply* map_iso_ctyp.\nQed.\n\nLemma map_iso_ctyp_eq : forall tm vm T T1 T2,\n    T ⩭ T1 ->\n    (tm, vm) ⊢t T ⪯ T2 ->\n    T1 = T2\nwith map_iso_cdec_eq : forall tm vm D D1 D2,\n    iso_cdec_dec D D1 ->\n    (tm, vm) ⊢d D ⪯ D2 ->\n    D1 = D2.\nProof.\n  all: introv Hc Hm.\n  - gen T2. dependent induction Hc; introv Hm.\n    -- inversion Hm; subst. reflexivity.\n    -- inversion Hm; subst. reflexivity.\n    -- inversion Hm; subst. f_equal. apply* map_iso_cdec_eq.\n    -- inversion Hm; subst. f_equal; try apply* IHHc1. apply* IHHc2.\n    -- inversion Hm; subst. f_equal. inversion H4; subst. reflexivity.\n    -- inversion Hm; subst. f_equal. apply* IHHc.\n    -- inversion Hm; subst. f_equal. apply* IHHc1. apply* IHHc2.\n  - gen D2. dependent induction Hc; introv Hm.\n    -- inversion Hm; subst. f_equal; apply* map_iso_ctyp_eq.\n    -- inversion Hm; subst. f_equal. apply* map_iso_ctyp_eq.\nQed.\n\nInductive satisfy_constr : (tctx * vctx * ctx) -> constr -> Prop :=\n\n| sat_true : forall tm vm G,\n    (tm, vm, G) ⊧ ⊤\n\n| sat_and : forall tm vm G C1 C2,\n    (tm, vm, G) ⊧ C1 ->\n    (tm, vm, G) ⊧ C2 ->\n    (tm, vm, G) ⊧ C1 ⋏ C2\n\n| sat_or1 : forall tm vm G C1 C2,\n    (tm, vm, G) ⊧ C1 ->\n    (tm, vm, G) ⊧ C1 ⋎ C2\n\n| sat_or2 : forall tm vm G C1 C2,\n    (tm, vm, G) ⊧ C2 ->\n    (tm, vm, G) ⊧ C1 ⋎ C2\n\n| sat_exists_typ : forall L tm vm G T C,\n    (forall x, x \\notin L -> (tm & x ~ T, vm, G) ⊧ C ^^t x) ->\n    (tm, vm, G) ⊧ (∃t C)\n\n| sat_exists_var : forall L tm vm G u C,\n    (forall x, x \\notin L -> (tm, vm & x ~ u, G) ⊧ C ^^v x) ->\n    (tm, vm, G) ⊧ (∃v C)\n\n| sat_typ : forall tm vm G t t' T T',\n    (tm, vm) ⊢v t ⪯ t' ->\n    (tm, vm) ⊢t T ⪯ T' ->\n    G ⊢ t' : T' ->\n    (tm, vm, G) ⊧ t ⦂ T\n\n| sat_sub : forall tm vm G S S' T T',\n    (tm, vm) ⊢t S ⪯ S' ->\n    (tm, vm) ⊢t T ⪯ T' ->\n    G ⊢ S' <: T' ->\n    (tm, vm, G) ⊧ S <⦂ T\n\nwhere \"e '⊧' C\" := (satisfy_constr e C).\n\nHint Constructors satisfy_constr constr.\n\nDefinition constr_satisfiable (C : constr) (G : ctx) :=\n  exists tm vm, (tm, vm, G) ⊧ C.\n\nNotation \"G '⊨' C\" := (constr_satisfiable C G) (at level 40).\n", "meta": {"author": "Linyxus", "repo": "constr-dot-calculus", "sha": "111c47bdc58350b8dd0b65ecbeeec783a8df2bc2", "save_path": "github-repos/coq/Linyxus-constr-dot-calculus", "path": "github-repos/coq/Linyxus-constr-dot-calculus/constr-dot-calculus-111c47bdc58350b8dd0b65ecbeeec783a8df2bc2/src/constr-dot/ConstrInterp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2080871071116364}}
{"text": "Require Import Recdef.\nRequire Import VST.floyd.proofauto.\nLocal Open Scope logic.\nRequire Import Coq.Lists.List. Import ListNotations.\nRequire Import sha.general_lemmas.\n\nRequire Import tweetnacl20140427.split_array_lemmas.\nRequire Import ZArith.\nRequire Import tweetnacl20140427.Salsa20.\nRequire Import tweetnacl20140427.tweetnaclVerifiableC.\nRequire Import tweetnacl20140427.tweetNaclBase.\nInstance CompSpecs : compspecs.\nProof. make_compspecs prog. Defined.\n\nLemma data_at_ext sh t v v' p: v=v' -> data_at sh t v p |-- data_at sh t v' p.\nProof. intros; subst. auto. Qed.\n\n(*\nDefinition EightWord (q:QuadWord * QuadWord) (v:val) : mpred :=\n  match q with ((q0, q1, q2, q3),(q4, q5, q6, q7)) =>\n    data_at Tsh (Tarray tuchar 4 noattr) (map Vint [q0; q1; q2; q3; q4; q5; q6; q7]) v\n  end.*)\nDefinition QuadByte2ByteList (B:QuadByte) : list byte :=\n  match B with (b0, b1, b2, b3) => [b0; b1; b2; b3]\n  end.\n\nDefinition QuadByte2ValList (B:QuadByte) : list val :=\n   map Vint (map Int.repr (map Byte.unsigned (QuadByte2ByteList B))).\n\nLemma QuadByteValList_length q: length (QuadByte2ValList q) = 4%nat.\n  destruct q as [[[? ?] ?] ?]. reflexivity. Qed.\n\nDefinition EightByte (q:QuadByte * QuadByte) (v:val) : mpred :=\n  match q with (q1, q2) =>\n    data_at Tsh (Tarray tuchar 8 noattr) ((QuadByte2ValList q1) ++ (QuadByte2ValList q2)) v\n  end.\n\nDefinition SixteenByte2ByteList (B:SixteenByte) : list byte :=\n  match B with (q0, q1, q2, q3) =>\n   QuadByte2ByteList q0 ++ QuadByte2ByteList q1 ++ QuadByte2ByteList q2 ++ QuadByte2ByteList q3\n  end.\n\nDefinition SixteenByte2ValList (B:SixteenByte) : list val :=\n   map Vint (map Int.repr (map Byte.unsigned (SixteenByte2ByteList B))).\n\nLemma SixteenByte2ValList_char B: SixteenByte2ValList B =\n  match B with (q0, q1, q2, q3) =>\n   QuadByte2ValList q0 ++ QuadByte2ValList q1 ++ QuadByte2ValList q2 ++ QuadByte2ValList q3\n  end.\nProof. unfold SixteenByte2ValList, QuadByte2ValList .\n destruct B as [[[? ?] ?] ?]. simpl. repeat rewrite map_app. trivial.\nQed.\n\nDefinition ThirtyTwoByte (q:SixteenByte * SixteenByte) (v:val) : mpred :=\n  match q with (q1, q2) =>\n    @data_at CompSpecs Tsh (Tarray tuchar 32 noattr) ((SixteenByte2ValList q1) ++ (SixteenByte2ValList q2)) v\n  end.\n\nDefinition QByte (q:QuadByte) (v:val) : mpred :=\n  data_at Tsh (Tarray tuchar 4 noattr) (QuadByte2ValList q) v.\n\nDefinition QuadChunks2ValList (l: list QuadByte) : list val :=\n  List.fold_right (fun q vals => QuadByte2ValList q ++ vals) nil l.\n\nDefinition flatten16 (B:SixteenByte) : list QuadByte :=\n  match B with (q0, q1, q2, q3) => [q0; q1; q2; q3] end.\nLemma SixteenByte2ValList_flatten B:\n  QuadChunks2ValList (flatten16 B) = SixteenByte2ValList B.\n  destruct B as (((q0, q1), q2), q3). simpl.\n  rewrite SixteenByte2ValList_char, app_nil_r. trivial.\nQed.\n\nLemma QuadByteByteList_ZLength q: 4 = Zlength (QuadByte2ByteList q).\n  destruct q as (((q0, q1), q2), q3). simpl. reflexivity. Qed.\nLemma QuadByteValList_ZLength q: 4 = Zlength (QuadByte2ValList q).\n  destruct q as (((q0, q1), q2), q3). simpl. reflexivity. Qed.\n\nLemma SixteenByte2ValList_Zlength C: 16 = Zlength (SixteenByte2ValList C).\n  destruct C as (((q0, q1), q2), q3). unfold SixteenByte2ValList.\n  repeat rewrite Zlength_map.  simpl.\n  repeat rewrite Zlength_app. repeat rewrite <- QuadByteByteList_ZLength.\n  reflexivity. Qed.\n\nDefinition SByte (q:SixteenByte) (v:val) : mpred :=\n  @data_at CompSpecs Tsh (Tarray tuchar 16 noattr) (SixteenByte2ValList q) v.\n\nLemma ThirtyTwoByte_split16 q v:\n  field_compatible (Tarray tuchar 32 noattr) [] v ->\n  ThirtyTwoByte q v =\n  (SByte (fst q) v * SByte (snd q) (offset_val 16 v))%logic.\nProof. destruct q as [s1 s2]. simpl; intros. unfold SByte.\n  rewrite split2_data_at_Tarray_tuchar with (n1:= Zlength (SixteenByte2ValList s1));\n     try rewrite Zlength_app; repeat rewrite <- SixteenByte2ValList_Zlength; try omega.\n  unfold offset_val. red in H. destruct v; intuition.\n  rewrite field_address0_offset. simpl.\n  rewrite sublist_app1; try rewrite <- SixteenByte2ValList_Zlength; try omega.\n  rewrite sublist_app2; try rewrite <- SixteenByte2ValList_Zlength; try omega.\n  rewrite sublist_same; try rewrite <- SixteenByte2ValList_Zlength; trivial.\n  rewrite sublist_same; try rewrite <- SixteenByte2ValList_Zlength; trivial.\n  red; intuition.\nQed.\n\nLemma QuadByte2ValList_firstn4 q l:\n         firstn 4 (QuadByte2ValList q ++ l) = QuadByte2ValList q.\n   Proof. destruct q as (((b0, b1), b2), b3); trivial. Qed.\n\nLemma QuadByte2ValList_skipn4 q l:\n         skipn 4 (QuadByte2ValList q ++ l) = l.\n   Proof. destruct q as (((b0, b1), b2), b3); trivial. Qed.\n\nDefinition Select16Q (Q:SixteenByte) i :QuadByte :=\n  match Q with (((b0, b1), b2), b3) =>\n    if zeq i 0 then b0 else\n    if zeq i 1 then b1 else\n    if zeq i 2 then b2 else b3\n  end.\nDefinition UnSelect16Q (Q:SixteenByte) i : list QuadByte :=\n  match Q with (((b0, b1), b2), b3) =>\n    if zeq i 0 then [b1;b2;b3] else\n    if zeq i 1 then [b0;b2;b3] else\n    if zeq i 2 then [b0;b1;b3] else [b0;b1;b2]\n  end.\nDefinition SplitSelect16Q (Q:SixteenByte) i : (list QuadByte * list QuadByte) :=\n  match Q with (((b0, b1), b2), b3) =>\n    if zeq i 0 then ([], [b1;b2;b3]) else\n    if zeq i 1 then ([b0], [b2;b3]) else\n    if zeq i 2 then ([b0;b1], [b3]) else ([b0;b1;b2], [])\n  end.\nLemma Select_SplitSelect16Q Q i front back:\n    (front, back) = SplitSelect16Q Q i ->\n    SixteenByte2ValList Q =\n    QuadChunks2ValList front ++ QuadChunks2ValList [Select16Q Q i] ++ QuadChunks2ValList back.\nProof.\n  unfold Select16Q, SplitSelect16Q; intros.\n  destruct Q as (((q0, q1), q2), q3). simpl.\n  destruct (zeq i 0); simpl. inv H; simpl. repeat rewrite app_nil_r. apply SixteenByte2ValList_char.\n  destruct (zeq i 1); simpl. inv H; simpl. repeat rewrite app_nil_r. apply SixteenByte2ValList_char.\n  destruct (zeq i 2); simpl. inv H; simpl. repeat rewrite app_nil_r. repeat rewrite <- app_assoc. apply SixteenByte2ValList_char.\n  destruct (zeq i 3); simpl; inv H; simpl. repeat rewrite app_nil_r. repeat rewrite <- app_assoc. apply SixteenByte2ValList_char.\n  repeat rewrite app_nil_r. repeat rewrite <- app_assoc. apply SixteenByte2ValList_char.\nQed.\n\nLemma QuadChunk2ValList_ZLength: forall l, Zlength (QuadChunks2ValList l) = (4 * Zlength l)%Z.\nProof.\n  unfold QuadChunks2ValList. induction l; simpl. reflexivity.\n  rewrite Zlength_app, IHl, <- QuadByteValList_ZLength.\n  rewrite Zlength_cons; omega.\nQed.\n\nLemma Select_SplitSelect16Q_Zlength Q i front back:\n    (front, back) = SplitSelect16Q Q i -> 0<= i < 4 ->\n    Zlength front = i /\\ Zlength back = 3-i.\nProof.\n  unfold SplitSelect16Q; intros.\n  destruct Q as (((q0, q1), q2), q3).\n  destruct (zeq i 0). inv H. split; reflexivity.\n  destruct (zeq i 1). inv H. split; reflexivity.\n  destruct (zeq i 2). inv H. split; reflexivity.\n  destruct (zeq i 3). inv H. split; reflexivity. omega.\nQed.\n\nDefinition QBytes (l:list QuadByte) (v:val) : mpred :=\n  data_at Tsh (Tarray tuchar (4*Zlength l) noattr) (QuadChunks2ValList l) v.\n\nLemma QBytes16 s: SByte s = QBytes (flatten16 s).\nProof.\n  destruct s as (((q0, q1), q2), q3). simpl.\n  unfold SByte, QBytes. extensionality v. simpl. rewrite app_nil_r.\n  rewrite SixteenByte2ValList_char. trivial.\nQed.\n\nDefinition QuadWordRep (q:QuadWord):list val :=\n  match q with (q0, q1, q2, q3) => map Vint [q0;q1;q2;q3] end.\nDefinition SixteenWordRep (w:SixteenWord):list val :=\n  match w with (q0, q1, q2, q3) => QuadWordRep q0 ++ QuadWordRep q1 ++ QuadWordRep q2 ++ QuadWordRep q3 end.\n\nDefinition littleendian_of_SixteenByte (x:SixteenByte): QuadWord :=\n  match x with (q0, q1, q2, q3) => (littleendian q0, littleendian q1, littleendian q2, littleendian q3) end.\n\n\n     Lemma QuadWR_length q: length (QuadWordRep q) = 4%nat.\n        destruct q as [[[? ?] ?] ?]. simpl. reflexivity. Qed.\n     Lemma QuadWR_zlength q: Zlength (QuadWordRep q) = 4.\n        rewrite Zlength_correct, QuadWR_length. trivial. Qed.\n     Lemma SixteenWR_length s: length (SixteenWordRep s) = 16%nat.\n        destruct s as [[[? ?] ?] ?]. simpl.\n        repeat rewrite app_length. repeat rewrite  QuadWR_length. reflexivity. Qed.\n     Lemma SixteenWR_zlength s: Zlength (SixteenWordRep s) = 16.\n        rewrite Zlength_correct, SixteenWR_length. trivial. Qed.\n\nLemma QuadWR_int q i: (0<=i<4)%nat -> exists ii, nth i (QuadWordRep q) Vundef = Vint ii.\n  intros. destruct q as [[[? ?] ?] ?]. simpl.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity. omega. Qed.\n\nLemma SixteenWR_int s i: (0<=i<16)%nat -> exists ii, nth i (SixteenWordRep s) Vundef = Vint ii.\n  intros. destruct s as [[[? ?] ?] ?]. simpl.\n  destruct q as [[[? ?] ?] ?]. destruct q0 as [[[? ?] ?] ?].\n  destruct q1 as [[[? ?] ?] ?]. destruct q2 as [[[? ?] ?] ?]. simpl.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity.\n  destruct i. eexists; reflexivity. omega.\nQed.\n\nLemma SixteenWR_Znth_int i s: (0 <= i < 16) ->\n       exists ii : int, Znth i (SixteenWordRep s) = Vint ii.\nProof. intros. unfold Znth. if_tac; try omega.\n   apply SixteenWR_int. destruct H. apply Z2Nat.inj_lt in H1; simpl in *; omega.\nQed.\n\nLemma QuadWR_Z_int: forall (q : QuadWord) (i : Z),\n               0 <= i < 4 -> exists ii : int, Znth i (QuadWordRep q) = Vint ii.\nProof. intros. unfold Znth. if_tac. omega.\n       apply QuadWR_int. destruct H.\n       split.\n         apply Z2Nat.inj_le in H. apply H. omega. omega.\n         apply Z2Nat.inj_lt in H1. apply H1. omega. omega.\nQed.\n\n\n\nLemma SixteenWordRep_MapVint ss: exists l, SixteenWordRep ss = map Vint l.\nProof.\ndestruct ss as [[[s0 s1] s2] s3].\ndestruct s0 as [[[x0 x1] x2] x3].\ndestruct s1 as [[[x4 x5] x6] x7].\ndestruct s2 as [[[x8 x9] x10] x11].\ndestruct s3 as [[[x12 x13] x14] x15]. simpl.\nexists [x0; x1; x2; x3; x4; x5; x6; x7;\n    x8; x9; x10; x11; x12; x13; x14; x15].\nreflexivity.\nQed.\n\nDefinition QuadWordRepI (q : QuadWord) :=\n  match q with (q0, q1, q2, q3) => [q0; q1; q2; q3] end.\nLemma QuadWordRepI_QuadWordRep q: QuadWordRep q = map Vint  (QuadWordRepI q).\nProof. destruct q as [[[q0 q1] q2] q3]. reflexivity. Qed.\n\nDefinition SixteenWordRepI (w : SixteenWord) :=\n  match w with (q0, q1, q2, q3) =>\n    QuadWordRepI q0 ++ QuadWordRepI q1 ++ QuadWordRepI q2 ++ QuadWordRepI q3\n  end.\nLemma SixteenWordRepI_SixteenWordRep w: SixteenWordRep w = map Vint (SixteenWordRepI w).\nProof. destruct w as [[[q0 q1] q2] q3]. simpl.\n   repeat rewrite QuadWordRepI_QuadWordRep. repeat rewrite map_app. reflexivity.\nQed.\n\n    Lemma QuadWordRepI_length s: length (QuadWordRepI s) = 4%nat.\n    Proof. destruct s as [[[q0 q1] q2] q3]. reflexivity. Qed.\n    Lemma SixteenWordRepI_length s: length (SixteenWordRepI s) = 16%nat.\n    Proof. destruct s as [[[q0 q1] q2] q3]. simpl.\n      repeat rewrite app_length. repeat rewrite QuadWordRepI_length. reflexivity.\n    Qed.\n\nLemma QuadByte2ValList_bytes q: exists bytes, length bytes = 4%nat /\\\n      QuadByte2ValList q = map Vint (map Int.repr (map Byte.unsigned bytes)).\nProof. destruct q as [[[b0 b1] b2] b3]. unfold QuadByte2ValList; simpl.\n  exists [b0;b1;b2;b3]. split; trivial.\nQed.\n\nLemma SixteenByte2ValList_bytes N: exists bytes, length bytes = 16%nat /\\\n      SixteenByte2ValList N =  map Vint (map Int.repr (map Byte.unsigned bytes)).\nProof. destruct N as [[[q0 q1] q2] q3]. rewrite SixteenByte2ValList_char.\n  destruct (QuadByte2ValList_bytes q0) as [bytes0 [L0 Q0]]. rewrite Q0.\n  destruct (QuadByte2ValList_bytes q1) as [bytes1 [L1 Q1]]; rewrite Q1.\n  destruct (QuadByte2ValList_bytes q2) as [bytes2 [L2 Q2]]; rewrite Q2.\n  destruct (QuadByte2ValList_bytes q3) as [bytes3 [L3 Q3]]; rewrite Q3.\n  exists (bytes0 ++ bytes1 ++ bytes2 ++ bytes3).\n  repeat rewrite map_app. repeat rewrite app_length. rewrite L0, L1, L2, L3.\n  split; trivial.\nQed.\n\nLemma QuadByte2ValList_ints q: exists ints, length ints = 4%nat /\\\n      QuadByte2ValList q = map Vint ints.\nProof. destruct q as [[[b0 b1] b2] b3]. unfold QuadByte2ValList; simpl.\n  exists [Int.repr (Byte.unsigned b0); Int.repr (Byte.unsigned b1);\n          Int.repr (Byte.unsigned b2); Int.repr (Byte.unsigned b3)].\n  split; trivial.\nQed.\n\nLemma SixteenByte2ValList_ints N: exists ints, length ints = 16%nat /\\\n      SixteenByte2ValList N = map Vint ints.\nProof. destruct N as [[[q0 q1] q2] q3]. rewrite SixteenByte2ValList_char.\n  destruct (QuadByte2ValList_ints q0) as [ints0 [L0 Q0]]; rewrite Q0.\n  destruct (QuadByte2ValList_ints q1) as [ints1 [L1 Q1]]; rewrite Q1.\n  destruct (QuadByte2ValList_ints q2) as [ints2 [L2 Q2]]; rewrite Q2.\n  destruct (QuadByte2ValList_ints q3) as [ints3 [L3 Q3]]; rewrite Q3.\n  exists (ints0 ++ ints1 ++ ints2 ++ ints3).\n  repeat rewrite map_app. repeat rewrite app_length. rewrite L0, L1, L2, L3.\n  split; trivial.\nQed.\n\nLemma QuadChunks2ValList_bytes: forall l,\n        exists bytes, length bytes = (4*length l)%nat /\\\n        QuadChunks2ValList l = map Vint (map Int.repr (map Byte.unsigned bytes)).\n  Proof. unfold QuadChunks2ValList.\n    induction l; simpl; intros. exists nil; split; trivial.\n    destruct IHl as [? [X1 X2]]; rewrite X2; clear X2.\n    destruct (QuadByte2ValList_bytes a) as [? [Y1 Y2]]; rewrite Y2; clear Y2.\n    repeat rewrite <- map_app. exists (x0 ++ x); split; trivial.\n    rewrite app_length, X1, Y1. omega.\n  Qed.\n\nFixpoint upd_upto (x: SixteenByte * SixteenByte * (SixteenByte * SixteenByte)) i (l:list val):list val :=\n  match i with\n    O => l\n  | S n =>\n     match x with (Nonce, C, (Key1, Key2)) =>\n     ((upd_Znth (11 + (Z.of_nat n))\n     (upd_Znth(6 + (Z.of_nat n))\n        (upd_Znth (1 + (Z.of_nat n))\n           (upd_Znth (5 * (Z.of_nat n)) (upd_upto x n l)\n              (Vint (littleendian (Select16Q C (Z.of_nat n)))))\n           (Vint (littleendian (Select16Q Key1 (Z.of_nat n)))))\n        (Vint (littleendian (Select16Q Nonce (Z.of_nat n)))))\n     (Vint (littleendian (Select16Q Key2 (Z.of_nat n))))))\n     end\n  end.\n\nLemma upd_upto_Sn Nonce C Key1 Key2 n l: upd_upto (Nonce, C, (Key1, Key2)) (S n) l =\n     ((upd_Znth (11 + (Z.of_nat n))\n     (upd_Znth (6 + (Z.of_nat n))\n        (upd_Znth (1 + (Z.of_nat n))\n           (upd_Znth (5 * (Z.of_nat n)) (upd_upto (Nonce, C, (Key1, Key2))  n l)\n              (Vint (littleendian (Select16Q C (Z.of_nat n)))))\n           (Vint (littleendian (Select16Q Key1 (Z.of_nat n)))))\n        (Vint (littleendian (Select16Q Nonce (Z.of_nat n)))))\n     (Vint (littleendian (Select16Q Key2 (Z.of_nat n)))))).\n reflexivity. Qed.\n\nLemma upd_upto_Zlength data l (H: Zlength l = 16): forall i (I:(0<=i<=4)%nat),\n      Zlength (upd_upto data i l) = 16.\n  Proof. apply Zlength_length in H. 2: omega. simpl in H.\n    destruct l; simpl in H. exfalso; omega.\n    destruct l; simpl in H. intros; omega. destruct l; simpl in H. intros; omega.\n    destruct l; simpl in H. intros; omega. destruct l; simpl in H. intros; omega.\n    destruct l; simpl in H. intros; omega. destruct l; simpl in H. intros; omega.\n    destruct l; simpl in H. intros; omega. destruct l; simpl in H. intros; omega.\n    destruct l; simpl in H. intros; omega. destruct l; simpl in H. intros; omega.\n    destruct l; simpl in H. intros; omega. destruct l; simpl in H. intros; omega.\n    destruct l; simpl in H. intros; omega. destruct l; simpl in H. intros; omega.\n    destruct l; simpl in H. intros; omega. destruct l; simpl in H. 2: intros; omega. clear H.\n    intros.\n    induction i; destruct data as [[N C] [K1 K2]]. reflexivity.\n    rewrite upd_upto_Sn. remember (11 + Z.of_nat i) as z1. remember (6 + Z.of_nat i) as z2.\n    remember (1 + Z.of_nat i) as z3. remember (5 * Z.of_nat i)%Z as z4.\n    remember (Vint (littleendian (Select16Q C (Z.of_nat i)))) as u4.\n    remember (Vint (littleendian (Select16Q K1 (Z.of_nat i)))) as u3.\n    remember (Vint (littleendian (Select16Q N (Z.of_nat i)))) as u2.\n    remember (Vint (littleendian (Select16Q K2 (Z.of_nat i)))) as u1.\n    assert ((0 <= i <= 4)%nat).\n      split. omega. omega. (*rewrite Nat2Z.inj_succ in I. omega.*)\n    repeat rewrite upd_Znth_Zlength; rewrite (IHi H); intros; try omega.\nQed.\n\nLemma upd_upto_Vint data: forall n, 0<=n<16 ->\n      exists i, Znth n (upd_upto data 4 (list_repeat 16 Vundef)) = Vint i.\n  Proof. unfold upd_upto; intros. destruct data as [[N C] [K1 K2]].\n   repeat rewrite (upd_Znth_lookup' 16); trivial; simpl; try omega.\n   if_tac. eexists; reflexivity.   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity.\n   if_tac. eexists; reflexivity. omega.\nQed.\n\n(*cf xsalsa-paper, beginning of Section 2*)\nLemma upd_upto_char data l: Zlength l = 16 ->\n      upd_upto data 4 l = match data with ((Nonce, C), (Key1, Key2)) =>\n          match Nonce with (N1, N2, N3, N4) =>\n          match C with (C1, C2, C3, C4) =>\n          match Key1 with (K1, K2, K3, K4) =>\n          match Key2 with (L1, L2, L3, L4) =>\n      map Vint (map littleendian [C1; K1; K2; K3;\n                                  K4; C2; N1; N2;\n                                  N3; N4; C3; L1;\n                                  L2; L3; L4; C4]) end end end end end.\nProof. intros. apply Zlength_length in H. 2: omega.\n   destruct data as [[Nonce C] [Key1 Key2]].\n   destruct Nonce as [[[N1 N2] N3] N4].\n   destruct C as [[[C1 C2] C3] C4].\n   destruct Key1 as [[[K1 K2] K3] K4].\n   destruct Key2 as [[[L1 L2] L3] L4].\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. omega.\n   destruct l; simpl in H. 2: omega. clear H. reflexivity.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/tweetnacl20140427/verif_salsa_base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2080871071116364}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Export DistributedReferenceCounting.machine3.machine.\nRequire Export DistributedReferenceCounting.machine3.cardinal.\nRequire Export DistributedReferenceCounting.machine3.comm.\nRequire Export DistributedReferenceCounting.machine3.still_to_prove.\n\nUnset Standard Proposition Elimination Names.\n\nSection ROOTED.\n\nVariable s0 : Site.\n\nDefinition rooted_fun (s1 s2 : Site) (m : Message) :=\n  match m with\n  | copy => if eq_site_dec s1 s0 then 1%Z else 0%Z\n  | dec => if eq_site_dec s2 s0 then 1%Z else 0%Z\n  | inc_dec s3 =>\n      if eq_site_dec s3 s0\n      then\n       if eq_site_dec s2 owner then 1%Z else 0%Z\n      else 0%Z\n  end.\n\nDefinition rooted (s1 s2 : Site) (q : queue Message) :=\n  reduce Message (rooted_fun s1 s2) q.\n\n\nDefinition sigma_rooted (bm : Bag_of_message) :=\n  sigma2_table Site LS LS (queue Message) rooted bm.\n\nEnd ROOTED.\n\n\n\nSection ROOTED1.\n\n\n\nLemma sigma_rooted_post_message :\n forall (m : Message) (s0 s1 s2 : Site) (b : Bag_of_message),\n s0 <> owner ->\n sigma_rooted s0 (Post_message Message m b s1 s2) =\n (sigma_rooted s0 b + rooted_fun s0 s1 s2 m)%Z.\nProof.\n  unfold sigma_rooted in |- *.\n  unfold Post_message in |- *.\n  unfold change_queue in |- *.\n  intros.\n  rewrite sigma_table2_change.\n  simpl in |- *.\n  omega.\n  apply finite_site.\n  apply finite_site.\nQed.\n\n\nLemma rooted_first_out :\n forall (s0 s1 s2 : Site) (q : queue Message) (m : Message),\n first Message q = value Message m ->\n rooted s0 s1 s2 (first_out Message q) =\n (rooted s0 s1 s2 q - rooted_fun s0 s1 s2 m)%Z.\nProof.\n  intros.\n  unfold rooted in |- *.\n  apply reduce_first_out.\n  auto.\nQed.\n\nLemma sigma_rooted_collect_message :\n forall (m : Message) (s0 s1 s2 : Site) (b : Bag_of_message),\n first Message (b s1 s2) = value Message m ->\n s0 <> owner ->\n sigma_rooted s0 (Collect_message Message b s1 s2) =\n (sigma_rooted s0 b - rooted_fun s0 s1 s2 m)%Z.\nProof.\n  unfold sigma_rooted, Collect_message, change_queue in |- *.\n  intros.\n  rewrite sigma_table2_change.\n  rewrite (rooted_first_out s0 s1 s2 (b s1 s2) m).\n  simpl in |- *.\n  omega.\n  auto.\n  apply finite_site.\n  apply finite_site.\nQed.\n\nLemma rooted_fun_positive_or_null :\n forall (s0 x y : Site) (a : Message), (rooted_fun s0 x y a >= 0)%Z.\nProof.\n  intros.\n  unfold rooted_fun in |- *.\n  elim a.\n  case (eq_site_dec y s0).\n  intro; omega.\n  intro; omega.\n  intro.\n  case (eq_site_dec s s0).\n  case (eq_site_dec y owner).\n  intros; omega.\n  intros; omega.\n  intros; omega.\n  case (eq_site_dec x s0).\n  intros; omega.\n  intros; omega.\nQed.\n\nLemma rooted_positive_or_null :\n forall (s0 x y : Site) (q : queue Message), (rooted s0 x y q >= 0)%Z.\nProof.\n  intros.\n  unfold rooted in |- *.\n  apply reduce_positive_or_null.\n  intro.\n  apply rooted_fun_positive_or_null.\nQed.\n\n\n\n\nAxiom\n  sigma_rooted_change_queue :\n    forall (s0 s1 s2 : Site) (b : Bag_of_message) (q : queue Message),\n    s0 <> owner ->\n    b s1 owner = input Message dec (input Message (inc_dec s2) q) ->\n    sigma_rooted s0 (change_queue (queue Message) b s1 owner q) =\n    (sigma_rooted s0 b - rooted_fun s0 s1 owner dec -\n     rooted_fun s0 s1 owner (inc_dec s2))%Z.\n\n\n\nEnd ROOTED1.\n\nSection INVARIANT2.\n\nLemma invariant2_init :\n forall s0 : Site, st config_init s0 = sigma_rooted s0 (bm config_init).\nProof.\n  intros.\n  simpl in |- *.\n  unfold send_init, sigma_rooted, bag_init in |- *.\n  unfold sigma2_table in |- *.\n  unfold sigma_table in |- *.\n  unfold Z_id in |- *.\n  unfold rooted in |- *.\n  simpl in |- *.\n  rewrite sigma_null.\n  rewrite sigma_null.\n  auto.\nQed.\n\nLemma invariant2_ind :\n forall s0 : Site,\n s0 <> owner ->\n forall (c : Config) (t : class_trans c),\n legal c ->\n st c s0 = sigma_rooted s0 (bm c) ->\n st (transition c t) s0 = sigma_rooted s0 (bm (transition c t)).\nProof.\n  simple induction t.\n\n  (* 1 *)\n\n  intros; simpl in |- *.\n  rewrite sigma_rooted_post_message.\n  unfold Inc_send_table in |- *.\n  unfold rooted_fun in |- *.\n  case (eq_site_dec s1 s0).\n  intro; rewrite e.\n  unfold update_table in |- *; rewrite here.\n  omega.\n  intro; unfold update_table in |- *; rewrite elsewhere.\n  omega.\n  auto.\n  auto.\n\n  (* 2 *)\n  \n  intros; simpl in |- *.\n  rewrite sigma_rooted_collect_message with (m := dec).\n  unfold Dec_send_table in |- *.\n  unfold rooted_fun in |- *.\n  case (eq_site_dec s2 s0).\n  intro; rewrite e0.\n  unfold update_table in |- *; rewrite here.\n  omega.\n  intros; unfold update_table in |- *; rewrite elsewhere.\n  omega.\n  auto.\n  auto.\n  auto.\n\n  (* 3 *)\n  \n  intros; simpl in |- *.\n  rewrite sigma_rooted_post_message.\n  rewrite sigma_rooted_collect_message with (m := inc_dec s3).\n  unfold Inc_send_table, rooted_fun in |- *.\n  unfold update_table in |- *; rewrite elsewhere.\n  case (eq_site_dec s3 s0).\n  case (eq_site_dec owner owner).\n  intros; omega.\n  intro; elim n.\n  auto.\n  intros; omega.\n  auto.\n  auto.\n  auto.\n  auto.\n\n  (* 4 *)\n  \n  intros; simpl in |- *.\n  rewrite sigma_rooted_post_message.\n  rewrite sigma_rooted_collect_message with (m := copy).\n  unfold rooted_fun in |- *.\n  case (eq_site_dec s1 s0).\n  intro; omega.\n  intro; omega.\n  auto.\n  auto.\n  auto.\n\n\n  (* 5 *)\n  \n  intros; simpl in |- *.\n  rewrite sigma_rooted_collect_message with (m := copy).\n  unfold rooted_fun in |- *.\n  rewrite case_ineq.\n  omega.\n  auto.\n  auto.\n  auto.\n\n  (* 6 *)\n  \n  intros; simpl in |- *.\n  rewrite sigma_rooted_post_message.\n  rewrite sigma_rooted_collect_message with (m := copy).\n  unfold rooted_fun in |- *.\n  case (eq_site_dec s1 s0).\n  rewrite case_eq.\n  intro; omega.\n  intro; omega.\n  auto.\n  auto.\n  auto.\n\n  (* 7 *)\n  \n  intros; simpl in |- *.\n  rewrite sigma_rooted_post_message.\n  unfold rooted_fun in |- *.\n  rewrite case_ineq.\n  omega.  \n  auto.\n  auto.\n\n  (* optim 1 *)\n\n  intros; simpl in |- *.\n  rewrite sigma_rooted_post_message.\n  rewrite sigma_rooted_change_queue with (s2 := s2).\n  unfold rooted_fun in |- *.\n  case (eq_site_dec owner s0); intro.\n  elim H; auto.\n  \n  case (eq_site_dec s2 s0); intro.\n  case (eq_site_dec owner owner); intro.\n  omega.\n  \n  elim n1; auto.\n  omega.\n  auto.\n  auto.\n  auto.\nQed.\n\n\nLemma invariant2 :\n forall (c0 : Config) (s0 : Site),\n legal c0 -> s0 <> owner -> st c0 s0 = sigma_rooted s0 (bm c0).\n\nProof.\n  intros.\n  elim H.\n  apply invariant2_init.\n  intros.\n  apply invariant2_ind.\n  auto.\n  auto.\n  auto.\nQed.\n\n\nLemma positive_st :\n forall (c : Config) (s0 s5 : Site),\n s0 <> owner ->\n legal c -> In_queue Message (inc_dec s0) (bm c s5 owner) -> (st c s0 > 0)%Z.\nProof.\n  intros c s0 s5 H HA.\n  rewrite invariant2.\n  unfold sigma_rooted in |- *.\n  intros.\n  apply sigma2_strictly_positive with (x := s5) (y := owner).\n  auto.\n  exact eq_site_dec.\n  \n  apply in_s_LS.\n  apply in_s_LS.\n  intros.\n  unfold rooted in |- *.\n  intros.\n  simpl in |- *.\n  intros.\n  simpl in |- *.\n  apply reduce_positive_or_null.\n  intro.\n  apply rooted_fun_positive_or_null.\n  \n  generalize H0.\n  elim (bm c s5 owner).\n  simpl in |- *; intuition.\n  \n  intros.\n  generalize H2.\n  case d.\n  simpl in |- *.\n  intros.\n  elim H3.\n  intro; discriminate.\n  \n  intro.\n  generalize (H1 H4).\n  intro.\n  case (eq_site_dec owner s0).\n  intros; omega.\n  \n  intros; omega.\n  \n  simpl in |- *.\n  intros.\n  case (eq_site_dec s s0).\n  intro.\n  case (eq_site_dec owner owner).\n  intro.\n  generalize (rooted_positive_or_null s0 s5 owner q).\n  intro.\n  omega.\n  \n  intro.\n  elim n; auto.\n  \n  intro.\n  elim H3.\n  intro; elim n.\n  inversion H4.\n  auto.\n  \n  intro.\n  generalize (H1 H4).\n  intro.\n  omega.\n  \n  simpl in |- *.\n  intro.\n  elim H3.\n  intro; discriminate.\n  \n  intro.\n  generalize (H1 H4).\n  intro.\n  case (eq_site_dec s5 s0).\n  intro; omega.\n  \n  intro; omega.\n  \n  auto.\n  \n  auto.\nQed.\n\n\n\n\n\n\nEnd INVARIANT2.\n", "meta": {"author": "coq-contribs", "repo": "distributed-reference-counting", "sha": "6552f14cce0ea374c98adcbee0476ae268d64a7e", "save_path": "github-repos/coq/coq-contribs-distributed-reference-counting", "path": "github-repos/coq/coq-contribs-distributed-reference-counting/distributed-reference-counting-6552f14cce0ea374c98adcbee0476ae268d64a7e/machine3/invariant2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.20794889542627432}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.CommonDefinitions.\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.TermsAndIndicesFromOneInterface.\nRequire Import VerdiRaft.TermsAndIndicesFromOneLogInterface.\n\nSection TermsAndIndicesFromOne.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n  Context {rri : raft_refinement_interface}.\n  Context {taifoli : terms_and_indices_from_one_log_interface}.\n\n  Lemma terms_and_indices_from_one_vwl_init :\n    refined_raft_net_invariant_init terms_and_indices_from_one_vwl.\n  Proof using. \n    unfold refined_raft_net_invariant_init, terms_and_indices_from_one_vwl.\n    simpl. contradiction.\n  Qed.\n\n  Lemma lifted_terms_and_indices_from_one_log : forall net0 h,\n    refined_raft_intermediate_reachable net0 ->\n    terms_and_indices_from_one (log (snd (nwState net0 h))).\n  Proof using taifoli rri. \n    intros.\n    pose proof (lift_prop _ terms_and_indices_from_one_log_invariant).\n    unfold terms_and_indices_from_one_log in *.\n    rewrite <- deghost_spec with (net := net0). auto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_vwl_client_request :\n    refined_raft_net_invariant_client_request terms_and_indices_from_one_vwl.\n  Proof using. \n    unfold refined_raft_net_invariant_client_request, terms_and_indices_from_one_vwl.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update;\n      eauto using votesWithLog_update_elections_data_client_request.\n  Qed.\n\n  Lemma terms_and_indices_from_one_vwl_timeout :\n    refined_raft_net_invariant_timeout terms_and_indices_from_one_vwl.\n  Proof using taifoli rri. \n    unfold refined_raft_net_invariant_timeout, terms_and_indices_from_one_vwl.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n    simpl in *. find_eapply_lem_hyp votesWithLog_update_elections_data_timeout; eauto.\n    intuition; eauto. subst. find_apply_lem_hyp handleTimeout_log_same. find_rewrite.\n    apply lifted_terms_and_indices_from_one_log; auto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_vwl_append_entries :\n    refined_raft_net_invariant_append_entries terms_and_indices_from_one_vwl.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries, terms_and_indices_from_one_vwl.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update;\n      eauto using votesWithLog_update_elections_data_append_entries.\n  Qed.\n\n  Lemma terms_and_indices_from_one_vwl_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply terms_and_indices_from_one_vwl.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries_reply, terms_and_indices_from_one_vwl.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_vwl_request_vote :\n    refined_raft_net_invariant_request_vote terms_and_indices_from_one_vwl.\n  Proof using taifoli rri. \n    unfold refined_raft_net_invariant_request_vote, terms_and_indices_from_one_vwl.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n    simpl in *. find_eapply_lem_hyp votesWithLog_update_elections_data_request_vote; eauto.\n    intuition; eauto. subst. find_apply_lem_hyp handleRequestVote_log. find_rewrite.\n    apply lifted_terms_and_indices_from_one_log; auto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_vwl_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply terms_and_indices_from_one_vwl.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote_reply, terms_and_indices_from_one_vwl.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; rewrite_update;\n      eauto using votesWithLog_update_elections_data_request_vote_reply.\n  Qed.\n\n  Lemma terms_and_indices_from_one_vwl_do_leader :\n    refined_raft_net_invariant_do_leader terms_and_indices_from_one_vwl.\n  Proof using. \n    unfold refined_raft_net_invariant_do_leader, terms_and_indices_from_one_vwl.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n    eapply H0. find_higher_order_rewrite. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_vwl_do_generic_server :\n    refined_raft_net_invariant_do_generic_server terms_and_indices_from_one_vwl.\n  Proof using. \n    unfold refined_raft_net_invariant_do_generic_server, terms_and_indices_from_one_vwl.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n    eapply H0. find_higher_order_rewrite. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_vwl_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset terms_and_indices_from_one_vwl.\n  Proof using. \n    unfold refined_raft_net_invariant_state_same_packet_subset, terms_and_indices_from_one_vwl.\n    simpl. intuition. find_reverse_higher_order_rewrite. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_vwl_reboot :\n    refined_raft_net_invariant_reboot terms_and_indices_from_one_vwl.\n  Proof using. \n    unfold refined_raft_net_invariant_reboot, terms_and_indices_from_one_vwl.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n    eapply H0. find_higher_order_rewrite. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_vwl_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      terms_and_indices_from_one_vwl net.\n  Proof using taifoli rri. \n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply terms_and_indices_from_one_vwl_init.\n    - apply terms_and_indices_from_one_vwl_client_request.\n    - apply terms_and_indices_from_one_vwl_timeout.\n    - apply terms_and_indices_from_one_vwl_append_entries.\n    - apply terms_and_indices_from_one_vwl_append_entries_reply.\n    - apply terms_and_indices_from_one_vwl_request_vote.\n    - apply terms_and_indices_from_one_vwl_request_vote_reply.\n    - apply terms_and_indices_from_one_vwl_do_leader.\n    - apply terms_and_indices_from_one_vwl_do_generic_server.\n    - apply terms_and_indices_from_one_vwl_state_same_packet_subset.\n    - apply terms_and_indices_from_one_vwl_reboot.\n  Qed.\n\n  Lemma terms_and_indices_from_one_ll_init :\n    refined_raft_net_invariant_init terms_and_indices_from_one_ll.\n  Proof using. \n    unfold refined_raft_net_invariant_init, terms_and_indices_from_one_ll.\n    simpl. contradiction.\n  Qed.\n\n  Lemma terms_and_indices_from_one_ll_client_request :\n    refined_raft_net_invariant_client_request terms_and_indices_from_one_ll.\n  Proof using. \n    unfold refined_raft_net_invariant_client_request, terms_and_indices_from_one_ll.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n    simpl in *. find_rewrite_lem update_elections_data_client_request_leaderLogs. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_ll_timeout :\n    refined_raft_net_invariant_timeout terms_and_indices_from_one_ll.\n  Proof using. \n    unfold refined_raft_net_invariant_timeout, terms_and_indices_from_one_ll.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n    simpl in *. find_rewrite_lem update_elections_data_timeout_leaderLogs. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_ll_append_entries :\n    refined_raft_net_invariant_append_entries terms_and_indices_from_one_ll.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries, terms_and_indices_from_one_ll.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n    simpl in *. find_rewrite_lem update_elections_data_appendEntries_leaderLogs. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_ll_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply terms_and_indices_from_one_ll.\n  Proof using. \n    unfold refined_raft_net_invariant_append_entries_reply, terms_and_indices_from_one_ll.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_ll_request_vote :\n    refined_raft_net_invariant_request_vote terms_and_indices_from_one_ll.\n  Proof using. \n    unfold refined_raft_net_invariant_request_vote, terms_and_indices_from_one_ll.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n    simpl in *. find_rewrite_lem leaderLogs_update_elections_data_requestVote. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_ll_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply terms_and_indices_from_one_ll.\n  Proof using taifoli rri. \n    unfold refined_raft_net_invariant_request_vote_reply, terms_and_indices_from_one_ll.\n    simpl. intuition. repeat find_higher_order_rewrite. update_destruct; rewrite_update; eauto.\n    simpl in *. find_eapply_lem_hyp leaderLogs_update_elections_data_RVR; eauto.\n    find_apply_lem_hyp handleRequestVoteReply_log.\n    intuition; eauto; subst. find_rewrite.\n    apply lifted_terms_and_indices_from_one_log; auto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_ll_do_leader :\n    refined_raft_net_invariant_do_leader terms_and_indices_from_one_ll.\n  Proof using. \n    unfold refined_raft_net_invariant_do_leader, terms_and_indices_from_one_ll.\n    simpl. intuition. find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n    eapply H0. find_higher_order_rewrite. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_ll_do_generic_server :\n    refined_raft_net_invariant_do_generic_server terms_and_indices_from_one_ll.\n  Proof using. \n    unfold refined_raft_net_invariant_do_generic_server, terms_and_indices_from_one_ll.\n    simpl. intuition. find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n    eapply H0. find_higher_order_rewrite. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_ll_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset terms_and_indices_from_one_ll.\n  Proof using. \n    unfold refined_raft_net_invariant_state_same_packet_subset, terms_and_indices_from_one_ll.\n    simpl. intuition. find_reverse_higher_order_rewrite. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_ll_reboot :\n    refined_raft_net_invariant_reboot terms_and_indices_from_one_ll.\n  Proof using. \n    unfold refined_raft_net_invariant_reboot, terms_and_indices_from_one_ll.\n    simpl. intuition. find_higher_order_rewrite. update_destruct; subst; rewrite_update; eauto.\n    eapply H0. find_higher_order_rewrite. eauto.\n  Qed.\n\n  Lemma terms_and_indices_from_one_ll_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      terms_and_indices_from_one_ll net.\n  Proof using taifoli rri. \n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply terms_and_indices_from_one_ll_init.\n    - apply terms_and_indices_from_one_ll_client_request.\n    - apply terms_and_indices_from_one_ll_timeout.\n    - apply terms_and_indices_from_one_ll_append_entries.\n    - apply terms_and_indices_from_one_ll_append_entries_reply.\n    - apply terms_and_indices_from_one_ll_request_vote.\n    - apply terms_and_indices_from_one_ll_request_vote_reply.\n    - apply terms_and_indices_from_one_ll_do_leader.\n    - apply terms_and_indices_from_one_ll_do_generic_server.\n    - apply terms_and_indices_from_one_ll_state_same_packet_subset.\n    - apply terms_and_indices_from_one_ll_reboot.\n  Qed.\n\n\n  Instance taifoi : terms_and_indices_from_one_interface.\n  Proof.\n    constructor. split.\n    - auto using terms_and_indices_from_one_vwl_invariant.\n    - auto using terms_and_indices_from_one_ll_invariant.\n  Qed.\nEnd TermsAndIndicesFromOne.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft-proofs/TermsAndIndicesFromOneProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.20794889542627432}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*                 Xavier Leroy, INRIA Paris                           *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Neededness analysis for x86_64 operators *)\n\nRequire Import Coqlib.\nRequire Import AST Integers Floats Values Memory Globalenvs.\nRequire Import Op NeedDomain RTL.\n\nDefinition op1 (nv: nval) := nv :: nil.\nDefinition op2 (nv: nval) := nv :: nv :: nil.\n\nDefinition needs_of_condition (cond: condition): list nval :=\n  match cond with\n  | Cmaskzero n | Cmasknotzero n => op1 (maskzero n)\n  | _ => nil\n  end.\n\nDefinition needs_of_addressing_32 (addr: addressing) (nv: nval): list nval :=\n  match addr with\n  | Aindexed n => op1 (modarith nv)\n  | Aindexed2 n => op2 (modarith nv)\n  | Ascaled sc ofs => op1 (modarith (modarith nv))\n  | Aindexed2scaled sc ofs => op2 (modarith nv)\n  | Aglobal s ofs => nil\n  | Abased s ofs => op1 (modarith nv)\n  | Abasedscaled sc s ofs => op1 (modarith (modarith nv))\n  | Ainstack ofs => nil\n  end.\n\nDefinition needs_of_addressing_64 (addr: addressing) (nv: nval): list nval :=\n  match addr with\n  | Aindexed n => op1 (default nv)\n  | Aindexed2 n => op2 (default nv)\n  | Ascaled sc ofs => op1 (default nv)\n  | Aindexed2scaled sc ofs => op2 (default nv)\n  | Aglobal s ofs => nil\n  | Abased s ofs => op1 (default nv)\n  | Abasedscaled sc s ofs => op1 (default nv)\n  | Ainstack ofs => nil\n  end.\n\nDefinition needs_of_addressing (addr: addressing) (nv: nval): list nval :=\n  if Archi.ptr64 then needs_of_addressing_64 addr nv else needs_of_addressing_32 addr nv.\n\nDefinition needs_of_operation (op: operation) (nv: nval): list nval :=\n  match op with\n  | Omove => op1 nv\n  | Ointconst n => nil\n  | Olongconst n => nil\n  | Ofloatconst n => nil\n  | Osingleconst n => nil\n  | Oindirectsymbol id => nil\n  | Ocast8signed => op1 (sign_ext 8 nv)\n  | Ocast8unsigned => op1 (zero_ext 8 nv)\n  | Ocast16signed => op1 (sign_ext 16 nv)\n  | Ocast16unsigned => op1 (zero_ext 16 nv)\n  | Oneg => op1 (modarith nv)\n  | Osub => op2 (default nv)\n  | Omul => op2 (modarith nv)\n  | Omulimm n => op1 (modarith nv)\n  | Omulhs | Omulhu | Odiv | Odivu | Omod | Omodu => op2 (default nv)\n  | Oand => op2 (bitwise nv)\n  | Oandimm n => op1 (andimm nv n)\n  | Oor => op2 (bitwise nv)\n  | Oorimm n => op1 (orimm nv n)\n  | Oxor => op2 (bitwise nv)\n  | Oxorimm n => op1 (bitwise nv)\n  | Onot => op1 (bitwise nv)\n  | Oshl => op2 (default nv)\n  | Oshlimm n => op1 (shlimm nv n)\n  | Oshr => op2 (default nv)\n  | Oshrimm n => op1 (shrimm nv n)\n  | Oshrximm n => op1 (default nv)\n  | Oshru => op2 (default nv)\n  | Oshruimm n => op1 (shruimm nv n)\n  | Ororimm n => op1 (ror nv n)\n  | Oshldimm n => op1 (default nv)\n  | Olea addr => needs_of_addressing_32 addr nv\n  | Omakelong => op2 (default nv)\n  | Olowlong | Ohighlong => op1 (default nv)\n  | Ocast32signed => op1 (default nv)\n  | Ocast32unsigned => op1 (default nv)\n  | Onegl => op1 (default nv)\n  | Oaddlimm _ => op1 (default nv)\n  | Osubl => op2 (default nv)\n  | Omull => op2 (default nv)\n  | Omullimm _ => op1 (default nv)\n  | Omullhs | Omullhu | Odivl | Odivlu | Omodl | Omodlu => op2 (default nv)\n  | Oandl => op2 (default nv)\n  | Oandlimm _ => op1 (default nv)\n  | Oorl => op2 (default nv)\n  | Oorlimm _ => op1 (default nv)\n  | Oxorl => op2 (default nv)\n  | Oxorlimm _ => op1 (default nv)\n  | Onotl => op1 (default nv)\n  | Oshll => op2 (default nv)\n  | Oshllimm _ => op1 (default nv)\n  | Oshrl => op2 (default nv)\n  | Oshrlimm _ => op1 (default nv)\n  | Oshrxlimm n => op1 (default nv)\n  | Oshrlu => op2 (default nv)\n  | Oshrluimm _ => op1 (default nv)\n  | Ororlimm _ => op1 (default nv)\n  | Oleal addr => needs_of_addressing_64 addr nv\n  | Onegf | Oabsf => op1 (default nv)\n  | Oaddf | Osubf | Omulf | Odivf | Omaxf | Ominf => op2 (default nv)\n  | Onegfs | Oabsfs => op1 (default nv)\n  | Oaddfs | Osubfs | Omulfs | Odivfs => op2 (default nv)\n  | Osingleoffloat | Ofloatofsingle => op1 (default nv)\n  | Ointoffloat | Ofloatofint | Ointofsingle | Osingleofint => op1 (default nv)\n  | Olongoffloat | Ofloatoflong | Olongofsingle | Osingleoflong => op1 (default nv)\n  | Ocmp c => needs_of_condition c\n  | Osel c ty => nv :: nv :: needs_of_condition c\n  end.\n\nDefinition operation_is_redundant (op: operation) (nv: nval): bool :=\n  match op with\n  | Ocast8signed => sign_ext_redundant 8 nv\n  | Ocast8unsigned => zero_ext_redundant 8 nv\n  | Ocast16signed => sign_ext_redundant 16 nv\n  | Ocast16unsigned => zero_ext_redundant 16 nv\n  | Oandimm n => andimm_redundant nv n\n  | Oorimm n => orimm_redundant nv n\n  | _ => false\n  end.\n\nLtac InvAgree :=\n  match goal with\n  | [H: vagree_list nil _ _ |- _ ] => inv H; InvAgree\n  | [H: vagree_list (_::_) _ _ |- _ ] => inv H; InvAgree\n  | _ => idtac\n  end.\n\nLtac TrivialExists :=\n  match goal with\n  | [ |- exists v, Some ?x = Some v /\\ _ ] => exists x; split; auto\n  | _ => idtac\n  end.\n\nSection SOUNDNESS.\n\nVariable ge: genv.\nVariable sp: block.\nVariables m m': mem.\nHypothesis PERM: forall b ofs k p, Mem.perm m b ofs k p -> Mem.perm m' b ofs k p.\n\nLemma needs_of_condition_sound:\n  forall cond args b args',\n  eval_condition cond args m = Some b ->\n  vagree_list args args' (needs_of_condition cond) ->\n  eval_condition cond args' m' = Some b.\nProof.\n  intros. destruct cond; simpl in H;\n  try (eapply default_needs_of_condition_sound; eauto; fail);\n  simpl in *; FuncInv; InvAgree.\n- eapply maskzero_sound; eauto.\n- destruct (Val.maskzero_bool v n) as [b'|] eqn:MZ; try discriminate.\n  erewrite maskzero_sound; eauto.\nQed.\n\nLemma needs_of_addressing_32_sound:\n  forall sp addr args v nv args',\n  eval_addressing32 ge (Vptr sp Ptrofs.zero) addr args = Some v ->\n  vagree_list args args' (needs_of_addressing_32 addr nv) ->\n  exists v',\n     eval_addressing32 ge (Vptr sp Ptrofs.zero) addr args' = Some v'\n  /\\ vagree v v' nv.\nProof.\n  unfold needs_of_addressing_32; intros.\n  destruct addr; simpl in *; FuncInv; InvAgree; TrivialExists;\n  auto using add_sound, mul_sound with na.\n  apply add_sound; auto with na. apply add_sound; rewrite modarith_idem; auto.\n  apply add_sound; auto. apply add_sound; rewrite modarith_idem; auto with na.\n  apply mul_sound; rewrite modarith_idem; auto with na.\nQed.\n\n(*\nLemma needs_of_addressing_64_sound:\n  forall sp addr args v nv args',\n  eval_addressing64 ge (Vptr sp Ptrofs.zero) addr args = Some v ->\n  vagree_list args args' (needs_of_addressing_64 addr nv) ->\n  exists v',\n     eval_addressing64 ge (Vptr sp Ptrofs.zero) addr args' = Some v'\n  /\\ vagree v v' nv.\n*)\n\nLemma needs_of_operation_sound:\n  forall op args v nv args',\n  eval_operation ge (Vptr sp Ptrofs.zero) op args m = Some v ->\n  vagree_list args args' (needs_of_operation op nv) ->\n  nv <> Nothing ->\n  exists v',\n     eval_operation ge (Vptr sp Ptrofs.zero) op args' m' = Some v'\n  /\\ vagree v v' nv.\nProof.\n  unfold needs_of_operation; intros; destruct op; try (eapply default_needs_of_operation_sound; eauto; fail);\n  simpl in *; FuncInv; InvAgree; TrivialExists.\n- apply sign_ext_sound; auto. compute; auto.\n- apply zero_ext_sound; auto. lia.\n- apply sign_ext_sound; auto. compute; auto.\n- apply zero_ext_sound; auto. lia.\n- apply neg_sound; auto.\n- apply mul_sound; auto.\n- apply mul_sound; auto with na.\n- apply and_sound; auto.\n- apply andimm_sound; auto.\n- apply or_sound; auto.\n- apply orimm_sound; auto.\n- apply xor_sound; auto.\n- apply xor_sound; auto with na.\n- apply notint_sound; auto.\n- apply shlimm_sound; auto.\n- apply shrimm_sound; auto.\n- apply shruimm_sound; auto.\n- apply ror_sound; auto.\n- eapply needs_of_addressing_32_sound; eauto.\n- change (eval_addressing64 ge (Vptr sp Ptrofs.zero) a args')\n    with (eval_operation ge (Vptr sp Ptrofs.zero) (Oleal a) args' m').\n  eapply default_needs_of_operation_sound; eauto.\n  destruct a; simpl in H0; auto.\n- destruct (eval_condition cond args m) as [b|] eqn:EC; simpl in H2.\n  erewrite needs_of_condition_sound by eauto.\n  subst v; simpl. auto with na.\n  subst v; auto with na.\n- destruct (eval_condition c args m) as [b|] eqn:EC.\n  erewrite needs_of_condition_sound by eauto.\n  apply select_sound; auto.\n  simpl; auto with na.\nQed.\n\nLemma operation_is_redundant_sound:\n  forall op nv arg1 args v arg1' args',\n  operation_is_redundant op nv = true ->\n  eval_operation ge (Vptr sp Ptrofs.zero) op (arg1 :: args) m = Some v ->\n  vagree_list (arg1 :: args) (arg1' :: args') (needs_of_operation op nv) ->\n  vagree v arg1' nv.\nProof.\n  intros. destruct op; simpl in *; try discriminate; inv H1; FuncInv; subst.\n- apply sign_ext_redundant_sound; auto. lia.\n- apply zero_ext_redundant_sound; auto. lia.\n- apply sign_ext_redundant_sound; auto. lia.\n- apply zero_ext_redundant_sound; auto. lia.\n- apply andimm_redundant_sound; auto.\n- apply orimm_redundant_sound; auto.\nQed.\n\nEnd SOUNDNESS.\n\n\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/x86/NeedOp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.20794713329246603}}
{"text": "Require Import veric.juicy_base.\nRequire Import veric.shares.\nImport cjoins.\n\nDefinition dec_share_nonidentity (sh: Share.t) : {~identity sh}+{identity sh} :=\n   (Sumbool.sumbool_not _ _ (dec_share_identity sh)).\n\nDefinition perm_of_sh (sh: Share.t): option permission :=\n  if writable_share_dec sh\n  then if eq_dec sh Share.top\n            then Some Freeable\n            else Some Writable\n    else if readable_share_dec sh\n         then Some Readable\n         else if eq_dec sh Share.bot\n                   then None\n                   else Some Nonempty.\n(*\nLemma perm_of_sh_pshare: forall rsh (sh: pshare), \n   exists p,  perm_of_sh rsh (pshare_sh sh) = Some p.\nProof.\nintros sh.\nunfold perm_of_sh.\nif_tac. subst.\nif_tac.\ncontradiction Share.nontrivial; auto.\nintro sh.\nif_tac; eauto.\nif_tac; eauto.\nintros.\nif_tac; eauto.\nif_tac; eauto.\nif_tac; eauto.\ndestruct sh0; simpl in *.\nsubst x.\nclear - n.\nelimtype False.\ngeneralize bot_identity; rewrite identity_unit_equiv; intro.\napply (n _ H).\nQed.\n*)\n\nDefinition contents_at (m: mem) (loc: address) : memval :=\n  ZMap.get (snd loc) (PMap.get (fst loc) (mem_contents m)).\n\nDefinition contents_cohere (m: mem) (phi: rmap) :=\n  forall rsh sh v loc pp, phi @ loc = YES rsh sh (VAL v) pp -> contents_at m loc = v /\\ pp=NoneP.\n\nDefinition valshare (r: resource) : share :=\n    match r with\n      | YES sh rsh _ _ => Share.glb Share.Rsh sh\n      | _ => Share.bot\n    end.\n\nDefinition res_retain' (r: resource) : Share.t :=\n match r with\n  | NO sh _ => sh\n  | YES sh _ _ _ => Share.glb Share.Lsh sh\n  | PURE _ _ => Share.top\n end.\n\nDefinition perm_of_res (r: resource) :=\n  (*  perm_of_sh (res_retain' r) (valshare r). *)\n match r with\n | NO sh _ => if eq_dec sh Share.bot then None else Some Nonempty\n | PURE _ _ => Some Nonempty\n | YES sh rsh (VAL _) _ => perm_of_sh sh\n | YES sh rsh _ _ => Some Nonempty\n end.\n\nDefinition perm_of_res' (r: resource) :=\n  (*  perm_of_sh (res_retain' r) (valshare r). *)\n match r with\n | NO sh _ => if eq_dec sh Share.bot then None else Some Nonempty\n | PURE _ _ => Some Nonempty\n | YES sh _ _ _ => perm_of_sh sh\n end.\n\nDefinition perm_of_res_lock (r: resource) := \n  (*  perm_of_sh (res_retain' r) (valshare r). *)\n match r with\n | YES sh rsh (LK _) _ => perm_of_sh (Share.glb Share.Rsh sh)\n | YES sh rsh (CT _) _ => perm_of_sh (Share.glb Share.Rsh sh)\n | _ => None \n end.\n\n(*Definition perm_of_res_lock (r: resource) :=\n  (*  perm_of_sh (res_retain' r) (valshare r). *)\n match r with\n | NO sh => if eq_dec sh Share.bot then None else Some Nonempty\n | PURE _ _ => Some Nonempty\n | YES rsh sh (LK _) _ => perm_of_sh rsh (pshare_sh sh)\n | YES rsh sh (CT _) _ => perm_of_sh rsh (pshare_sh sh)\n | YES rsh sh _ _ => Some Nonempty\n end. *)\n\nLemma Rsh_not_top: Share.Rsh <> Share.top.\nProof.\nunfold Share.Rsh.\ncase_eq (Share.split Share.top); intros.\nsimpl; intro. subst.\napply nonemp_split_neq2 in H.\napply H; auto.\napply top_share_nonidentity.\nQed.\n\nLemma nonidentity_Rsh: ~identity Share.Rsh.\nProof.\nunfold Share.Rsh.\ncase_eq (Share.split Share.top); intros.\nsimpl; intro.\napply split_nontrivial' in H.\napply top_share_nonidentity; auto.\nauto.\nQed.\n\nLemma perm_of_sh_fullshare: perm_of_sh fullshare = Some Freeable.\nProof. unfold perm_of_sh.\n  rewrite if_true. rewrite if_true by auto. auto.\n   unfold fullshare.\n   apply writable_share_top.\nQed.\n\nLemma nonreadable_extern_retainer: ~readable_share extern_retainer.\nunfold extern_retainer, readable_share.\nintro H; apply H; clear H.\nassert (Share.glb Share.Rsh\n     (fst (Share.split Share.Lsh)) = Share.bot); [ | rewrite H; auto].\napply sub_glb_bot with Share.Lsh.\ndestruct (Share.split Share.Lsh) eqn:H.\napply Share.split_together in H.\nsimpl.\nrewrite <- H.\napply leq_join_sub.\napply Share.lub_upper1.\napply glb_Rsh_Lsh.\nQed.\n\nLemma Lsh_nonreadable: ~readable_share Share.Lsh.\nProof.\nunfold readable_share; intros.\nrewrite glb_Rsh_Lsh.\nauto.\nQed.\n\nLemma perm_of_res_op1:\n  forall r,\n    perm_order'' (perm_of_res' r) (perm_of_res r).\nProof.\n  destruct r eqn:?; simpl.\n  - if_tac; constructor.\n  - unfold perm_of_sh.\n    if_tac. if_tac; destruct k; constructor.\n    if_tac. destruct k; constructor.\n    rewrite if_false by auto. destruct k; constructor.\n  - constructor.\nQed.\n\nLemma perm_of_res_op2:\n  forall r,\n    perm_order'' (perm_of_res' r) (perm_of_res_lock r).\nProof.\n  destruct r; simpl.\n  - if_tac; constructor.\n  - destruct k; try solve [destruct (perm_of_sh sh); constructor].\n   +\n    unfold perm_of_sh.\n    if_tac. if_tac.\n    repeat if_tac; constructor.\n    rewrite if_true. rewrite if_false. constructor.\n    apply glb_Rsh_not_top.\n    apply writable_share_glb_Rsh; auto.\n    rewrite if_true by auto.\n    rewrite if_false. rewrite if_true. constructor.\n    unfold readable_share. rewrite glb_twice; auto.\n    contradict H. unfold writable_share in *. eapply join_sub_trans; eauto.\n    apply leq_join_sub. apply Share.glb_lower2.\n   +\n    unfold perm_of_sh.\n    if_tac. if_tac.\n    rewrite if_true by apply (writable_share_glb_Rsh H).\n    subst.\n    rewrite if_false by apply glb_Rsh_not_top. constructor.\n    rewrite if_true by (apply writable_share_glb_Rsh; auto).\n    rewrite if_false by apply glb_Rsh_not_top. constructor.\n    rewrite if_true by auto.\n    rewrite if_false.\n    rewrite if_true. constructor.\n    unfold readable_share. rewrite glb_twice; auto.\n    contradict H. unfold writable_share in *. eapply join_sub_trans; eauto.\n    apply leq_join_sub. apply Share.glb_lower2.\n -\n  auto.\nQed.\n    \nDefinition access_cohere (m: mem)  (phi: rmap) :=\n  forall loc,  access_at m loc Cur = perm_of_res (phi @ loc).\n\nDefinition max_access_at m loc := access_at m loc Max.\n\nDefinition max_access_cohere (m: mem) (phi: rmap)  :=\n  forall loc,\n    perm_order'' (max_access_at m loc) (perm_of_res' (phi @ loc)).\n\n(*\nDefinition max_access_cohere (m: mem) (phi: rmap)  :=\n  forall loc,\n   match phi @ loc with\n   | YES rsh sh _ _ => perm_order'' (max_access_at m loc) (perm_of_sh rsh (pshare_sh sh))\n   | NO rsh => perm_order'' (max_access_at m loc) (perm_of_sh rsh Share.bot )\n   | PURE _ _ => (fst loc < nextblock m)%positive\n  end. *)\n\nDefinition alloc_cohere (m: mem) (phi: rmap) :=\n forall loc,  (fst loc >= nextblock m)%positive -> phi @ loc = NO Share.bot bot_unreadable.\n\nInductive juicy_mem: Type :=\n  mkJuicyMem: forall (m: mem) (phi: rmap)\n    (JMcontents: contents_cohere m phi)\n    (JMaccess: access_cohere m phi)\n    (JMmax_access: max_access_cohere m phi)\n    (JMalloc: alloc_cohere m phi),\n       juicy_mem.\n\nSection selectors.\nVariable (j: juicy_mem).\nDefinition m_dry := match j with mkJuicyMem m _ _ _ _ _ => m end.\nDefinition m_phi := match j with mkJuicyMem _ phi _ _ _ _ => phi end.\nLemma juicy_mem_contents: contents_cohere m_dry m_phi.\nProof. unfold m_dry, m_phi; destruct j; auto. Qed.\nLemma juicy_mem_access: access_cohere m_dry m_phi.\nProof. unfold m_dry, m_phi; destruct j; auto. Qed.\nLemma juicy_mem_max_access: max_access_cohere m_dry m_phi.\nProof. unfold m_dry, m_phi; destruct j; auto. Qed.\nLemma juicy_mem_alloc_cohere: alloc_cohere m_dry m_phi.\nProof. unfold m_dry, m_phi; destruct j; auto. Qed.\nEnd selectors.\n\nLemma perm_of_empty_inv {s} : perm_of_sh s = None -> s = Share.bot.\nProof.\nintros.\nunfold perm_of_sh in*.\nif_tac in H; subst; auto.\nif_tac in H; subst; auto.\ninv H. inv H.\nif_tac in H; subst; auto.\ninv H.\nif_tac in H; subst; auto. inv H.\nQed.\n\nLemma writable_join_sub: forall loc phi1 phi2,\n  join_sub phi1 phi2 -> writable loc phi1 -> writable loc phi2.\nProof.\nintros.\nhnf in H0|-*.\ndestruct H; generalize (resource_at_join _ _ _ loc H); clear H.\nrevert H0; destruct (phi1 @ loc); intros; try contradiction.\ndestruct H0; subst.\ninv H.\nsplit. eapply join_writable1; eauto. auto.\ncontradiction (join_writable_readable RJ H0 rsh2).\nQed.\n\nLemma writable_inv: forall phi loc, writable loc phi ->\n  exists sh, exists rsh, exists k, exists pp, \n       phi @ loc = YES sh rsh k pp /\\ \n       writable_share sh /\\\n       isVAL k.\nProof.\nsimpl.\nintros phi loc H.\ndestruct (phi @ loc); try solve [inversion H].\ndestruct H.\ndo 4 eexists. split. reflexivity. split; auto.\nQed.\n\nLemma nreadable_inv: forall phi loc, ~readable loc phi \n  -> (exists sh, exists nsh, phi @ loc = NO sh nsh)\n   \\/ (exists sh, exists rsh, exists k, exists pp, phi @ loc = YES sh rsh k pp /\\ ~isVAL k)\n   \\/ (exists k, exists pp, phi @ loc = PURE k pp).\nProof.\nintros.\nsimpl in H.\ndestruct (phi@loc); eauto 50.\nQed.\n\nLemma VAL_valid:\n forall (f: address -> option (rshare*kind)),\n   (forall l sh k, f l = Some (sh,k) -> isVAL k) ->\n   AV.valid f.\nProof.\nintros.\nintros b ofs.\ncase_eq (f (b,ofs)); intros; auto.\ndestruct p.\nspecialize (H _ _ _ H0).\ndestruct k; solve [\n    auto\n  | inversion H ].\nQed.\n\nLemma age1_joinx {A}  {JA: Join A}{PA: Perm_alg A}{agA: ageable A}{AgeA: Age_alg A} : forall phi1 phi2 phi3 phi1' phi2' phi3',\n             age phi1 phi1' -> age phi2 phi2' -> age phi3 phi3' ->\n             join phi1 phi2 phi3 -> join phi1' phi2' phi3'.\nProof.\nintros.\ndestruct (age1_join _ H2 H) as [phi2'' [phi3'' [? [? ?]]]].\nunfold age in *.\ncongruence.\nQed.\n\nLemma constructive_age1_join  {A}  {JA: Join A}{PA: Perm_alg A}{agA: ageable A}{AgeA: Age_alg A} : forall x y z x' : A,\n       join x y z ->\n       age x x' ->\n       { yz' : A*A | join x' (fst yz') (snd yz') /\\ age y (fst yz') /\\ age z (snd yz')}.\nProof.\npose proof I.\nintros.\ncase_eq (age1 y); [intros y' ? | intros].\ncase_eq (age1 z); [intros z' ? | intros].\nexists (y',z').\nsimpl.\nsplit; auto.\napply (age1_joinx x y z x' y' z' H1 H2 H3 H0).\nelimtype False.\ndestruct (age1_join _ H0 H1) as [? [? [? [? ?]]]].\nunfold age in *.\ncongruence.\nelimtype False.\ndestruct (age1_join _ H0 H1) as [? [? [? [? ?]]]].\nunfold age in *.\ncongruence.\nQed.\n\nLemma age1_constructive_joins_eq : forall {A}  {JA: Join A}{PA: Perm_alg A}{agA: ageable A}{AgeA: Age_alg A}  {phi1 phi2},\n  constructive_joins phi1 phi2\n  -> forall {phi1'}, age1 phi1 = Some phi1'\n  -> forall {phi2'}, age1 phi2 = Some phi2'\n  -> constructive_joins phi1' phi2'.\nProof.\nintros.\ndestruct X as [? ?H].\ndestruct (constructive_age1_join _ _ _ _ H1 H) as [[y z] [? [? ?]]].\nsimpl in *.\nunfold age in H3. rewrite H0 in H3; inv H3; econstructor; eauto.\nQed.\n\n\nProgram Definition age1_juicy_mem (j: juicy_mem): option juicy_mem :=\n      match age1 (m_phi j) with\n        | Some phi' => Some (mkJuicyMem (m_dry j) phi' _ _ _ _)\n        | None => None\n      end.\nNext Obligation.  (* contents_cohere *)\n assert (necR (m_phi j) phi')\n   by (constructor 1; symmetry in Heq_anonymous; apply Heq_anonymous).\n destruct j; hnf; simpl in *; intros.\n case_eq (phi @ loc); intros.\n apply (necR_NO _ _ _ _ _ H) in H1. congruence.\n generalize (necR_YES _ _ _ _ _ _ _ H H1); intros.\n rewrite H0 in H2. inv H2.\n destruct (JMcontents sh0 r v loc _ H1). subst; split; auto.\n rewrite (necR_PURE _ _ _ _ _ H H1) in H0. inv H0.\nQed.\nNext Obligation. (* access_cohere *)\n assert (necR (m_phi j) phi')\n   by (constructor 1; symmetry in Heq_anonymous; apply Heq_anonymous).\n destruct j; hnf; simpl in *; intros.\n generalize (JMaccess loc); case_eq (phi @ loc); intros.\n apply (necR_NO _ _ loc _ _ H) in H0. rewrite H0; auto.\n rewrite (necR_YES _ _ _ _ _ _ _ H H0); auto.\n rewrite (necR_PURE _ _ _ _ _ H H0); auto.\nQed.\nNext Obligation. (* max_access_cohere *)\n assert (necR (m_phi j) phi')\n   by (constructor 1; symmetry in Heq_anonymous; apply Heq_anonymous).\n destruct j; hnf; simpl in *; intros.\n generalize (JMmax_access loc); case_eq (phi @ loc); intros.\n apply (necR_NO _ _ loc _ _ H) in H0. rewrite H0; auto.\n rewrite (necR_YES _ _ _ _ _ _ _ H H0); auto.\n rewrite (necR_PURE _ _ _ _ _ H H0); auto.\nQed.\nNext Obligation. (* alloc_cohere *)\n assert (necR (m_phi j) phi')\n   by (constructor 1; symmetry in Heq_anonymous; apply Heq_anonymous).\n destruct j; hnf; simpl in *; intros.\n specialize (JMalloc loc H0).\n apply (necR_NO _ _ loc _ _ H). auto.\nQed.\n\nLemma age1_juicy_mem_unpack: forall j j',\n  age1_juicy_mem j = Some j' ->\n  age (m_phi j)  (m_phi j')\n  /\\ m_dry j = m_dry j'.\nProof.\nintros.\nunfold age1_juicy_mem in H.\ninvSome.\ninv H.\nsplit; simpl; auto.\nsymmetry in H0; apply H0.\nQed.\n\nLemma age1_juicy_mem_unpack': forall j j',\n  age (m_phi j)  (m_phi j')  /\\ m_dry j = m_dry j' ->\n  age1_juicy_mem j = Some j'.\nProof.\n  intuition.\n  unfold age1_juicy_mem.\n  generalize (eq_refl (age1 (m_phi j))).\n  pattern (age1 (m_phi j)) at 1 3.\n  rewrite H0;  clear H0. intros H0.\n  f_equal.\n  destruct j, j'; simpl in *; subst; repeat f_equal; try apply proof_irr.\nQed.\n\nLemma age1_juicy_mem_unpack'': forall j j',\n  age (m_phi j)  (m_phi j')  -> m_dry j = m_dry j' ->\n  age1_juicy_mem j = Some j'.\nProof.\n  intros.\n  apply age1_juicy_mem_unpack'.\n split; auto.\nQed.\n\n(* TODO: move into rmaps_lemmas *)\nLemma rmap_join_eq_level: forall phi1 phi2: rmap, joins phi1 phi2 -> level phi1 = level phi2.\nProof.\nintros until phi2; intro H.\ndestruct H as [? H].\napply join_level in H; destruct H; congruence.\nQed.\n\nLemma rmap_join_sub_eq_level: forall phi1 phi2: rmap,\n          join_sub phi1 phi2 -> level phi1 = level phi2.\nProof.\nintros until phi2; intro H.\ndestruct H; apply join_level in H; destruct H; congruence.\nQed.\n\nLemma age1_juicy_mem_None1:\n  forall j, age1_juicy_mem j = None -> age1 (m_phi j) = None.\nProof.\nintros j H.\ndestruct j.\nsimpl.\nunfold age1_juicy_mem in H; simpl in H.\nrevert H; generalize (refl_equal (age1 phi)); pattern (age1 phi) at 1 3; destruct (age1 phi); intros; auto.\ninv H.\nQed.\n\nLemma age1_juicy_mem_None2:\n  forall j, age1 (m_phi j) = None -> age1_juicy_mem j = None.\nProof.\nintros.\nunfold age1_juicy_mem.\ngeneralize (eq_refl (age1 (m_phi j))).\npattern (age1 (m_phi j)) at 1 3.\nrewrite H.\nauto.\nQed.\n\nLemma age1_juicy_mem_Some:\n  forall j j', age1_juicy_mem j = Some j' -> age1 (m_phi j) = Some (m_phi j').\nProof.\nintros.\napply age1_juicy_mem_unpack in H; intuition.\nQed.\n\n\nLemma unage_juicy_mem: forall j' : juicy_mem,\n   exists j : juicy_mem, age1_juicy_mem j = Some j'.\nProof.\nintros.\ndestruct j' as [m phi'].\ndestruct (af_unage age_facts phi') as [phi ?].\nassert (NEC: necR phi phi')  by (constructor 1; auto).\n rename H into Hage.\nassert (contents_cohere m phi).\n  hnf; intros.\n  generalize (necR_YES phi phi' loc rsh sh (VAL v) pp NEC H); intro.\n  destruct (JMcontents _ _ _ _ _ H0).\n  rewrite H2 in H0.\n  split; auto.\n  generalize (necR_YES' _ _ loc rsh sh (VAL v) NEC); intro.\n  apply H3 in H0. congruence.\nassert (access_cohere m phi).\n  hnf; intros.\n  generalize (JMaccess loc); intros.\n  case_eq (phi @ loc); intros.\n  apply (necR_NO _ _ loc _ _ NEC) in H1. rewrite H1 in H0; auto.\n  apply (necR_YES _ _ _ _ _ _ _ NEC) in H1. rewrite H1 in H0; auto.\n  apply (necR_PURE _ _ _ _ _ NEC) in H1. rewrite H1 in H0; auto.\nassert (max_access_cohere m phi).\n  hnf; intros.\n  generalize (JMmax_access loc); intros.\n  case_eq (phi @ loc); intros.\n  apply (necR_NO _ _ _ _ _ NEC) in H2; rewrite H2 in H1; auto.\n  rewrite (necR_YES _ _ _ _ _ _ _ NEC H2) in H1; auto.\n  rewrite (necR_PURE _ _ _ _ _ NEC H2) in H1; auto.\nassert (alloc_cohere m phi).\n  hnf; intros.\n  generalize (JMalloc loc H2); intros.\n  case_eq (phi @ loc); intros.\n  apply (necR_NO _ _ _ _ _ NEC) in H4; rewrite H4 in H3; auto.\n  rewrite (necR_YES _ _ _ _ _ _ _ NEC H4) in H3; inv H3.\n  rewrite (necR_PURE _ _ _ _ _ NEC H4) in H3; inv H3.\nexists (mkJuicyMem m phi H H0 H1 H2).\napply age1_juicy_mem_unpack''; simpl; auto.\nQed.\n\nLemma level1_juicy_mem: forall j: juicy_mem,\n  age1_juicy_mem j = None <-> level (m_phi j) = 0%nat.\nProof.\nintro x.\nsplit; intro H.\napply age1_level0.\napply age1_juicy_mem_None1; auto.\napply age1_level0 in H.\napply age1_juicy_mem_None2.\nauto.\nQed.\n\nLemma level2_juicy_mem: forall j1 j2: juicy_mem,\n   age1_juicy_mem j1 = Some j2 -> level (m_phi j1) = S (level (m_phi j2)).\nProof.\nintros x y H.\ndestruct (age1_juicy_mem_unpack x y H).\n apply age_level in H0. auto.\nQed.\n\nLemma juicy_mem_ageable_facts: ageable_facts juicy_mem (fun j => level (m_phi j)) age1_juicy_mem.\nProof.\nconstructor.\n(*apply age1_juicy_mem_wf.*)\napply unage_juicy_mem.\napply level1_juicy_mem.\napply level2_juicy_mem.\nQed.\n\nInstance juicy_mem_ageable: ageable juicy_mem :=\n  mkAgeable _ (fun j => level (m_phi j)) age1_juicy_mem juicy_mem_ageable_facts.\n\nLemma level_juice_level_phi: forall (j: juicy_mem), level j = level (m_phi j).\nProof. intuition. Qed.\n\nLemma juicy_mem_ext: forall j1 j2,\n       m_dry j1 = m_dry j2  ->\n       m_phi j1 = m_phi j2 ->\n       j1=j2.\nProof.\nintros.\ndestruct j1; destruct j2; simpl in *.\nsubst.\nf_equal; apply proof_irr.\nQed.\n\nLemma unage_writable: forall (phi phi': rmap) loc,\n  age phi phi' -> writable loc phi' -> writable loc phi.\nProof.\nintros.\nsimpl in *.\napply age1_resource_at with (loc := loc) (r := phi @ loc) in H.\ndestruct (phi' @ loc); try contradiction.\nunfold writable.\ndestruct (phi @ loc); try discriminate.\ninv H. auto.\ndestruct (phi' @ loc); inv H0.\nrewrite resource_at_approx. auto.\nQed.\n\nLemma unage_readable: forall (phi phi': rmap) loc,\n  age phi phi' -> readable loc phi' -> readable loc phi.\nProof.\nintros.\nsimpl in *.\napply age1_resource_at with (loc := loc) (r := phi @ loc) in H.\n 2: symmetry; apply resource_at_approx.\ndestruct (phi' @ loc); try inv H0.\ndestruct (phi @ loc); try inv H.\nauto.\nQed.\n\nLemma readable_inv: forall phi loc, readable loc phi ->\n  exists rsh, exists sh, exists v, exists pp, phi @ loc = YES rsh sh (VAL v) pp.\nProof.\nsimpl.\nintros phi loc H.\ndestruct (phi @ loc); try solve [inversion H].\ndestruct k; try inv H.\neauto.\nQed.\n\n(* resource coherence *)\n\n(* FIXME: put somewhere else. *)\nDefinition fmap_option {A B} (v: option A) (m: B) (f: A -> B): B :=\n  match v with\n    | None => m\n    | Some v' => f v'\n  end.\n\nLemma resource_at_make_rmap: forall f V lev H, resource_at (proj1_sig (make_rmap f V lev H)) = f.\nrefine (fun f V lev H => match proj2_sig (make_rmap f V lev H) with\n                           | conj _ RESOURCE_AT => RESOURCE_AT\n                         end).\nQed.\n\nLemma resource_at_remake_rmap: forall f V lev H, resource_at (proj1_sig (remake_rmap f V lev H)) = f.\nrefine (fun f V lev H => match proj2_sig (remake_rmap f V lev H) with\n                           | conj _ RESOURCE_AT => RESOURCE_AT\n                         end).\nQed.\n\nLemma level_make_rmap: forall f V lev H, @level rmap _ (proj1_sig (make_rmap f V lev H)) = lev.\nrefine (fun f V lev H => match proj2_sig (make_rmap f V lev H) with\n                           | conj LEVEL _ => LEVEL\n                         end).\nQed.\n\nLemma level_remake_rmap: forall f V lev H, @level rmap _ (proj1_sig (remake_rmap f V lev H)) = lev.\nrefine (fun f V lev H => match proj2_sig (remake_rmap f V lev H) with\n                           | conj LEVEL _ => LEVEL\n                         end).\nQed.\n\n(* Here we build the [rmap]s that correspond to [store]s, [alloc]s and [free]s on the dry memory. *)\nSection inflate.\nVariables (m: mem) (phi: rmap).\n\nLemma phi_valid: valid (resource_at phi).\nProof. unfold valid; apply rmap_valid. Qed.\n\nDefinition inflate_initial_mem' (w: rmap) (loc: address) :=\n   match access_at m loc Cur with\n           | Some Freeable => YES Share.top readable_share_top (VAL (contents_at m loc)) NoneP\n           | Some Writable => YES Ews (writable_readable writable_Ews) (VAL (contents_at m loc)) NoneP\n           | Some Readable => YES Ers readable_Ers (VAL (contents_at m loc)) NoneP\n           | Some Nonempty => \n                         match w @ loc with PURE _ _ => w @ loc | _ => NO _ nonreadable_extern_retainer end\n           | None =>  NO Share.bot bot_unreadable\n         end.\n\nLemma inflate_initial_mem'_fmap:\n forall w, resource_fmap (approx (level w)) (approx (level w)) oo inflate_initial_mem' w =\n                inflate_initial_mem' w.\nProof.\nunfold valid, CompCert_AV.valid, compose.\nintros.\nunfold inflate_initial_mem'.\nextensionality loc.\ndestruct (access_at m loc); try destruct p;\n  try solve [unfold resource_fmap; f_equal; try apply preds_fmap_NoneP].\nrewrite <- level_core.\n  case_eq (w @ loc);intros; try reflexivity.\n  rewrite <- H. rewrite level_core. apply resource_at_approx.\nQed.\n\nLemma inflate_initial_mem'_valid:\n  forall lev, CompCert_AV.valid (res_option oo inflate_initial_mem' lev).\nProof.\nunfold valid, CompCert_AV.valid, compose, inflate_initial_mem'.\nintros lev b ofs.\ndestruct (access_at m (b, ofs)); try destruct p; simpl; auto.\n case_eq (lev @ (b,ofs)); intros; simpl; auto.\nQed.\n\nDefinition inflate_initial_mem (w: rmap): rmap :=\n    proj1_sig (make_rmap (inflate_initial_mem' w) (inflate_initial_mem'_valid w) _\n            (inflate_initial_mem'_fmap w)).\n\nLemma inflate_initial_mem_level: forall w, level (inflate_initial_mem w) = level w.\nProof.\nintros; unfold inflate_initial_mem, inflate_initial_mem'.\nrewrite level_make_rmap; auto.\nQed.\n\nDefinition all_VALs (phi: rmap) :=\n  forall l, match phi @ l with\n              | YES _ _ k _ => isVAL k\n              | _ => True\n            end.\n\nLemma inflate_initial_mem_all_VALs: forall lev, all_VALs (inflate_initial_mem lev).\nProof.\nunfold inflate_initial_mem, inflate_initial_mem', all_VALs.\nintros; rewrite resource_at_make_rmap.\ndestruct (access_at m l); try destruct p; auto.\n case (lev @ l); simpl; intros; auto.\nQed.\n\n(* FIXME\n   Build an rmap that's identical to phi except where m has allocated. *)\nDefinition inflate_alloc: rmap.\n refine (proj1_sig (remake_rmap (fun loc =>\n   fmap_option (res_option (phi @ loc))\n\n  (* phi = NO *)\n  (fmap_option (access_at m loc Cur)\n    (NO Share.bot bot_unreadable)\n    (fun p => \n      match p with\n        | Freeable => YES Share.top readable_share_top (VAL (contents_at m loc)) NoneP\n        | _ => NO Share.Lsh Lsh_nonreadable\n      end))\n\n  (* phi = YES *)\n  (fun _ => phi @ loc)) _ (level phi) _)).\nProof.\nassert (VALID: valid (resource_at phi)) by (apply phi_valid).\nunfold valid, CompCert_AV.valid in *.\nunfold compose in *.\nintros b ofs.\nspecialize VALID with b ofs.\nunfold fmap_option.\ndestruct (phi @ (b, ofs)); simpl in *; auto.\ndestruct (access_at m (b, ofs)); simpl in *; auto.\ndestruct p; simpl in *; auto.\ndestruct k; simpl in *; auto.\nintros i H.\nspecialize (VALID i H).\ndestruct (phi @ (b, ofs + i)); simpl in *; auto; try discriminate.\ndestruct VALID as [n [H H0]].\nexists n.\nsplit; auto.\ndestruct (phi @ (b, ofs - z)); simpl in *; auto; try discriminate.\n\n(* NO *)\ndestruct (access_at m (b, ofs)); simpl; auto. destruct p0; simpl; auto.\n\n(* YES *)\nintro.\ncase_eq (phi @ l); simpl; intros; auto.\ncase_eq (access_at m l Cur); simpl; intros; auto.\nright; destruct p; simpl; auto.\nleft; exists phi; split; auto.\nright; destruct  (access_at m l Cur); simpl; auto.\ndestruct p0; simpl; auto.\nDefined.\n\nLemma approx_map_idem: forall n (lp: preds),\n  preds_fmap (approx n) (approx n) (preds_fmap (approx n) (approx n) lp) =\n  preds_fmap (approx n) (approx n) lp.\nProof.\nintros n ls.\nchange (preds_fmap (approx n) (approx n) (preds_fmap (approx n) (approx n) ls))\nwith (((preds_fmap (approx n) (approx n)) oo (preds_fmap (approx n) (approx n))) ls).\nrewrite preds_fmap_comp.\nrewrite (approx_oo_approx n).\nauto.\nQed.\n\n(* Build an [rmap] that's identical to [phi] except where [m] has stored. *)\nDefinition inflate_store: rmap. refine (\nproj1_sig (make_rmap (fun loc =>\n  match phi @ loc with\n    | YES sh rsh (VAL _) _ => YES sh rsh (VAL (contents_at m loc)) NoneP\n    | YES _ _ _ _ => resource_fmap (approx (level phi)) (approx (level phi)) (phi @ loc)\n    | _ => phi @ loc\n  end) _ (level phi) _)).\nProof.\nassert (VALID: valid (resource_at phi)) by (apply phi_valid).\nunfold valid, CompCert_AV.valid in *.\nunfold compose in *.\nintros b ofs.\nspecialize VALID with b ofs.\nremember (phi @ (b, ofs)) as HPHI.\ndestruct HPHI; simpl; auto.\ndestruct k; simpl in *; auto.\nintros i H1.\nspecialize VALID with i.\ndestruct (phi @ (b, ofs + i)); auto.\ndestruct k; simpl; auto.\nsimpl in VALID.\nassert (H2 := VALID H1).\ninv H2.\ndestruct VALID as [n [H1 H0]].\nexists n.\nsplit; auto.\ndestruct (phi @ (b, ofs - z)); simpl in *; auto.\ninversion H0; subst; auto.\n\nunfold compose.\nextensionality l.\ndestruct l as (b, ofs).\nremember (phi @ (b, ofs)) as HPHI.\ndestruct HPHI; auto.\n(* YES *)\ndestruct k; try solve\n  [ unfold resource_fmap; rewrite preds_fmap_NoneP; auto\n  | unfold resource_fmap; rewrite approx_map_idem; auto ].\nrewrite HeqHPHI.\napply resource_at_approx.\nDefined.\n\nEnd inflate.\n\nLemma adr_inv0: forall (b b': block) (ofs ofs': Z) (sz: Z),\n  ~ adr_range (b, ofs) sz (b', ofs') ->\n  b <> b' \\/ ~ ofs <= ofs' < ofs + sz.\nProof.\nintros until sz.\nintro H.\ndestruct (peq b b').\nright; intro Contra.\napply H.\nunfold adr_range.\nauto.\nleft; intro Contra.\napply n; auto.\nQed.\n\nLemma adr_inv: forall (b b': block) (ofs ofs': Z) ch,\n  ~ adr_range (b, ofs) (size_chunk ch) (b', ofs') ->\n  b <> b' \\/ ~ ofs <= ofs' < ofs + size_chunk ch.\nProof. intros until ch; intros H1; eapply adr_inv0; eauto. Qed.\n\nLemma range_inv0: forall ofs ofs' sz,\n  ~ ofs <= ofs' < ofs + sz ->\n  ofs' < ofs \\/ ofs' >= ofs + sz.\nProof.\nintros until sz; intro H.\ndestruct (zle ofs ofs'); destruct (zlt ofs' (ofs + sz)); omega.\nQed.\n\nLemma range_inv: forall ofs ofs' ch,\n  ~ ofs <= ofs' < ofs + size_chunk ch ->\n  ofs' < ofs \\/ ofs' >= ofs + size_chunk ch.\nProof. intros; eapply range_inv0; eauto. Qed.\n\nLemma perm_of_sh_Freeable_top: forall sh, perm_of_sh sh = Some Freeable -> \n     sh = Share.top.\nProof.\nintros sh H.\nunfold perm_of_sh in H.\nrepeat if_tac in H; solve [inversion H | auto].\nQed.\n\nLemma nextblock_access_empty: forall m b ofs k, (b >= nextblock m)%positive\n  -> access_at m (b, ofs) k = None.\nProof.\nintros.\nunfold access_at. simpl.\napply (nextblock_noaccess m b ofs k).\nauto.\nQed.\n\nSection initial_mem.\nVariables (m: mem) (w: rmap).\n\nDefinition initial_rmap_ok := \n   forall loc, ((fst loc >= nextblock m)%positive -> core w @ loc = NO Share.bot bot_unreadable) /\\\n                   (match w @ loc with \n                    | PURE _ _ => (fst loc < nextblock m)%positive /\\ \n                                           access_at m loc Cur = Some Nonempty /\\  \n                                            max_access_at m loc = Some Nonempty \n                    | _ => True end).\nHypothesis IOK: initial_rmap_ok.\nEnd initial_mem.\n\nDefinition empty_retainer (loc: address) := Share.bot.\n\nLemma perm_of_freeable: perm_of_sh Share.top = Some Freeable.\nProof.\nunfold perm_of_sh.\nrewrite if_true. rewrite if_true; auto.\nauto.\nQed.\n\nLemma perm_of_writable: \n   forall sh, writable_share sh -> sh <> Share.top -> perm_of_sh sh = Some Writable.\nProof.\nintros.\nunfold perm_of_sh.\nrewrite if_true by auto. rewrite if_false; auto.\nQed.\n\nLemma perm_of_readable:\n  forall sh (rsh: readable_share sh), ~writable_share sh -> perm_of_sh sh = Some Readable.\nProof.\nintros. unfold perm_of_sh. rewrite if_false by auto. rewrite if_true; auto.\nQed.\n\nLemma perm_of_nonempty:\n  forall sh, sh <> Share.bot -> ~readable_share sh -> perm_of_sh sh = Some Nonempty.\nProof.\nintros. unfold perm_of_sh.\nrewrite if_false by auto.\nrewrite if_false by auto.\nrewrite if_false by auto; auto.\nQed.\n\nLemma perm_of_empty:\n    perm_of_sh Share.bot = None.\nProof.\nintros. unfold perm_of_sh.\nrewrite if_false. rewrite if_false.\nrewrite if_true; auto.\napply bot_unreadable.\nintro.\napply writable_readable_share in H.\napply bot_unreadable in H; auto.\nQed.\n\nLemma perm_of_Ews: perm_of_sh Ews = Some Writable.\nProof.\nunfold perm_of_sh, Ews, extern_retainer.\nrewrite if_true.\n*\nrewrite if_false; auto.\nintro.\nrewrite Share.lub_commute in H.\npose proof lub_Lsh_Rsh. rewrite Share.lub_commute in H0.\nrewrite <- H in H0.\napply Share.distrib_spec in H0.\ndestruct (Share.split Share.Lsh) eqn:?H; simpl in *.\npose proof (nonemp_split_neq1 Share.Lsh t t0).\nspec H2. intro.\napply identity_share_bot in H3. contradiction Lsh_bot_neq.\nsubst t.\napply H2; auto.\nclear.\nrewrite glb_Rsh_Lsh.\nrewrite Share.glb_commute.\nsymmetry.\napply Share.ord_antisym.\nrewrite <- glb_Lsh_Rsh.\napply glb_less_both.\ndestruct (Share.split Share.Lsh) eqn:H.\nsimpl.\napply Share.split_together in H.\nrewrite <- H.\napply Share.lub_upper1.\napply Share.ord_refl.\napply Share.bot_correct.\n*\nunfold writable_share.\napply leq_join_sub.\napply Share.lub_upper2.\nQed.\n\nLemma perm_of_Ers: perm_of_sh Ers = Some Readable.\nProof.\nunfold perm_of_sh, Ers, extern_retainer.\nrewrite if_false.\n*\nrewrite if_true; auto.\napply readable_share_lub.\nunfold readable_share.\nrewrite glb_split_x.\nintro.\napply identity_share_bot in H.\ndestruct (Share.split Share.Rsh) eqn:H0.\napply Share.split_nontrivial in H0.\nunfold Share.Rsh in H0.\ndestruct (Share.split Share.top) eqn:H1.\nsimpl in *. subst.\napply Share.split_nontrivial in H1.\napply Share.nontrivial; auto.\nauto.\nsimpl in H; auto.\n*\nunfold writable_share.\nintro.\napply leq_join_sub in H.\napply Share.ord_spec2 in H.\napply (f_equal (Share.glb Share.Rsh)) in H.\nrewrite Share.distrib1 in H.\nrewrite Share.glb_idem in H.\nrewrite Share.lub_absorb in H.\nrewrite Share.distrib1 in H.\nrewrite (@sub_glb_bot Share.Rsh (fst (Share.split Share.Lsh)) Share.Lsh)\n in H.\nrewrite Share.lub_commute, Share.lub_bot in H.\nrewrite glb_split_x in H.\ndestruct (Share.split Share.Rsh) eqn:H0.\napply nonemp_split_neq1 in H0.\nsimpl in *; subst. congruence.\napply nonidentity_Rsh.\nclear.\nexists (snd (Share.split Share.Lsh)).\ndestruct (Share.split Share.Lsh) eqn:H.\nsimpl.\nsplit.\neapply Share.split_disjoint; eauto.\neapply Share.split_together; eauto.\napply glb_Rsh_Lsh.\nQed.\n\nLemma extern_retainer_neq_bot: extern_retainer <> Share.bot.\nProof.\nunfold extern_retainer.\nintro.\ndestruct (Share.split Share.Lsh) eqn:H0.\nsimpl in *. subst.\npose proof (Share.split_together _ _ _ H0).\nrewrite Share.lub_commute, Share.lub_bot in H.\nsubst.\napply nonemp_split_neq2 in H0.\ncontradiction H0; auto.\nclear.\nunfold Share.Lsh.\nintro.\napply identity_share_bot in H.\ndestruct (Share.split Share.top) eqn:H0.\nsimpl in *; subst.\napply split_nontrivial' in H0.\napply identity_share_bot in H0.\napply Share.nontrivial; auto.\nleft.\napply bot_identity.\nQed.\n\nLemma perm_order''_trans: forall a b c, Mem.perm_order'' a b ->  Mem.perm_order'' b c ->\n                               Mem.perm_order'' a c.\nProof.\n   intros a b c H1 H2; destruct a, b, c; inversion H1; inversion H2; subst; eauto;\n             eapply perm_order_trans; eauto.\nQed.\n\nDefinition initial_mem (m: mem) lev (IOK: initial_rmap_ok m lev) : juicy_mem.\n refine (mkJuicyMem m  (inflate_initial_mem m lev) _ _ _ _);\n  unfold inflate_initial_mem, inflate_initial_mem';\n  hnf; intros;  try rewrite resource_at_make_rmap in *.\n* (* contents_cohere *)\nrevert H; case_eq (access_at m loc Cur); intros.\n destruct p; inv H0; auto.\n revert H2; case_eq (lev @ loc); intros; congruence.\n destruct (max_access_at m loc); try destruct p; try congruence.\n* (* access_cohere *)\n symmetry.\n destruct (access_at m loc) eqn:?; try destruct p; auto; simpl.\n apply perm_of_freeable.\n apply perm_of_Ews.\n apply perm_of_Ers.\n destruct (IOK loc).\n destruct (lev @ loc).\n simpl; rewrite if_false by apply extern_retainer_neq_bot; auto.\n simpl; rewrite if_false by apply extern_retainer_neq_bot; auto.\n reflexivity.\n rewrite if_true; auto.\n* (* max_access_cohere *)\n  { generalize (perm_cur_max m (fst loc) (snd loc)); unfold perm; intros.\n    case_eq (access_at m loc Cur); try destruct p; intros.\n    - unfold perm_order'', perm_order', max_access_at in *.\n    simpl; rewrite perm_of_freeable.\n    apply H.\n    unfold access_at in H0. rewrite H0. constructor.\n    - simpl. rewrite perm_of_Ews.\n    unfold perm_order'', perm_order', max_access_at, access_at in *.\n    rewrite H0 in *.\n    specialize (H Writable). spec H. constructor.\n    apply H.\n     - simpl. rewrite perm_of_Ers.\n    unfold perm_order'', perm_order', max_access_at, access_at in *.\n    rewrite H0 in *.\n    apply H. constructor.\n    - destruct (IOK loc).\n    eapply perm_order''_trans; [apply (access_max m (fst loc) (snd loc))|].\n    unfold access_at in H0; rewrite H0.\n    destruct (lev @ loc) ; simpl;\n    try destruct (@eq_dec Share.t Share.EqDec_share extern_retainer Share.bot); try constructor.\n    - simpl. destruct (eq_dec Share.bot Share.bot) as [e|n]; [| exfalso; apply n; reflexivity].\n      rewrite <- H0.\n      apply (access_max m).\n  }\n* (* alloc_cohere *)\nunfold access_at.\nunfold block; rewrite (nextblock_noaccess m (fst loc) (snd loc) Cur); auto.\nDefined.\n\nDefinition juicy_mem_level (j: juicy_mem) (lev: nat) :=\n  level (m_phi j) = lev.\n\nLemma initial_mem_level: forall lev m j IOK,\n  j = initial_mem m lev IOK -> juicy_mem_level j (level lev).\nProof.\nintros.\ndestruct j; simpl.\nunfold initial_mem in H.\ninversion H; subst.\nunfold juicy_mem_level. simpl.\nerewrite inflate_initial_mem_level; eauto.\nQed.\n\nLemma initial_mem_all_VALs: forall lev m j IOK, j = initial_mem m lev IOK\n  -> all_VALs (m_phi j).\nProof.\nintros until 1; intros (b, ofs).\ndestruct j; unfold initial_mem in H; inversion H; subst.\nsimpl.\nunfold inflate_initial_mem, inflate_initial_mem'; rewrite resource_at_make_rmap.\ndestruct (access_at m (b, ofs)); try destruct p; auto.\ncase_eq (lev @ (b,ofs)); intros; auto.\nQed.\n\nLemma perm_mem_access: forall m b ofs p,\n  perm m b ofs Cur p ->\n  exists p', (perm_order p' p /\\ access_at m (b, ofs) Cur = Some p').\nProof.\nintros.\nrewrite perm_access in H. red in H.\ndestruct (access_at m (b, ofs) Cur); try contradiction; eauto.\nQed.\n\nSection store.\nVariables (jm: juicy_mem) (m': mem)\n          (ch: memory_chunk) (b: block) (ofs: Z) (v: val)\n          (STORE: store ch (m_dry jm) b ofs v = Some m').\n\nLemma store_phi_elsewhere_eq: forall rsh sh mv loc',\n  ~ adr_range (b, ofs) (size_chunk ch) loc'\n  -> (m_phi jm) @ loc' = YES rsh sh (VAL mv) NoneP -> contents_at m' loc' = mv.\nProof.\ndestruct jm. simpl in *. clear jm.\nintros.\nunfold contents_at.\nrewrite store_mem_contents with\n  (chunk := ch) (m1 := m) (b := b) (ofs := ofs) (v := v); auto.\ndestruct loc' as [b' ofs']. simpl.\ndestruct (peq b' b).\n(* b' = b *)\ndestruct (adr_inv b b' ofs ofs' ch H).\nsymmetry in e.\ncontradiction.\n(* b' = b /\\ ~ ofs <= ofs' < ofs + size_chunk ch *)\nsubst.\nrewrite PMap.gss.\nrewrite setN_outside.\ndestruct (JMcontents _ _ _ _ _ H0) as [H5 _].\napply H5.\ndestruct (range_inv _ _ _ H1) as [H1'|H1'].\nleft; auto.\nright.\nrewrite encode_val_length.\nrewrite <- size_chunk_conv.\nauto.\n\n(* b' <> b *)\nrewrite PMap.gso; auto.\ndestruct (JMcontents _ _ _ _ _ H0) as [H1 _].\napply H1.\nQed.\n\nDefinition store_juicy_mem: juicy_mem.\n refine (mkJuicyMem m' (inflate_store m' (m_phi jm)) _ _ _ _).\n(* contents_cohere *)\nintros rsh sh' v' loc' pp H2.\nunfold inflate_store in H2; rewrite resource_at_make_rmap in H2.\ndestruct (m_phi jm @ loc'); try destruct k; try solve [inversion H2].\ninversion H2; auto.\n(* access_cohere *)\nintro loc; generalize (juicy_mem_access jm loc); intro H0.\nunfold inflate_store; rewrite resource_at_make_rmap.\nrewrite <- (Memory.store_access _ _ _ _ _ _ STORE).\ndestruct (m_phi jm @ loc); try destruct k; auto.\n(* max_access_cohere *)\nintro loc; generalize (juicy_mem_max_access jm loc); intro H1.\nunfold inflate_store; rewrite resource_at_make_rmap.\nunfold max_access_at in *.\nrewrite <- (Memory.store_access _ _ _ _ _ _ STORE).\napply nextblock_store in STORE.\ndestruct (m_phi jm @ loc); auto.\ndestruct k; simpl; try assumption.\n(* alloc_cohere *)\nhnf; intros.\nunfold inflate_store. rewrite resource_at_make_rmap.\ngeneralize (juicy_mem_alloc_cohere jm loc); intro.\nrewrite (nextblock_store _ _ _ _ _ _ STORE) in H.\nrewrite (H0 H). auto.\nDefined.\n\nEnd store.\n\nSection storebytes.\nVariables (jm: juicy_mem) (m': mem) (b: block) (ofs: Z) (bytes: list memval)\n  (STOREBYTES: storebytes (m_dry jm) b ofs bytes = Some m').\n\nLemma storebytes_phi_elsewhere_eq: forall rsh sh mv loc',\n  ~ adr_range (b, ofs) (Zlength bytes) loc' ->\n  (m_phi jm) @ loc' = YES rsh sh (VAL mv) NoneP ->\n  contents_at m' loc' = mv.\nProof.\ndestruct jm. simpl in *. clear jm.\nintros.\nunfold contents_at.\nrewrite storebytes_mem_contents with\n  (m1 := m) (b := b) (ofs := ofs) (bytes := bytes); auto.\ndestruct loc' as [b' ofs']. simpl.\ndestruct (peq b' b).\n(* b' = b *)\ndestruct (adr_inv0 b b' ofs ofs' (Zlength bytes) H).\nsymmetry in e.\ncontradiction.\n(* b' = b /\\ ~ ofs <= ofs' < ofs + size_chunk ch *)\nsubst.\nrewrite PMap.gss.\nrewrite setN_outside.\ndestruct (JMcontents _ _ _ _ _ H0) as [H5 _].\napply H5.\ndestruct (range_inv0 _ _ _ H1) as [H1'|H1'].\nleft; auto.\nright.\nrewrite <-Zlength_correct; auto.\n(* b' <> b *)\nrewrite PMap.gso; auto.\ndestruct (JMcontents _ _ _ _ _ H0) as [H1 _].\napply H1.\nQed.\n\nDefinition storebytes_juicy_mem: juicy_mem.\n refine (mkJuicyMem m' (inflate_store m' (m_phi jm)) _ _ _ _).\n(* contents_cohere *)\nintros rsh sh' v' loc' pp H2.\nunfold inflate_store in H2; rewrite resource_at_make_rmap in H2.\ndestruct (m_phi jm @ loc'); try destruct k; try solve [inversion H2].\ninversion H2; auto.\n(* access_cohere *)\nintro loc; generalize (juicy_mem_access jm loc); intro H0.\nunfold inflate_store; rewrite resource_at_make_rmap.\nrewrite <- (Memory.storebytes_access _ _ _ _ _ STOREBYTES).\ndestruct (m_phi jm @ loc); try destruct k; auto.\n(* max_access_cohere *)\nintro loc; generalize (juicy_mem_max_access jm loc); intro H1.\nunfold inflate_store; rewrite resource_at_make_rmap.\nunfold max_access_at in *.\nrewrite <- (Memory.storebytes_access _ _ _ _ _ STOREBYTES).\nassert (H88:=nextblock_storebytes _ _ _ _ _ STOREBYTES).\ndestruct (m_phi jm @ loc); try rewrite H88; auto.\ndestruct k; simpl; try rewrite H88; auto.\n(* alloc_cohere *)\nhnf; intros.\nunfold inflate_store. rewrite resource_at_make_rmap.\ngeneralize (juicy_mem_alloc_cohere jm loc); intro.\nrewrite (nextblock_storebytes _ _ _ _ _ STOREBYTES) in H.\nrewrite (H0 H).\nauto.\nDefined.\n\nEnd storebytes.\n\nLemma free_smaller_None : forall m b b' ofs lo hi m',\n  access_at m (b, ofs) Cur = None\n  -> free m b' lo hi = Some m'\n  -> access_at m' (b, ofs) Cur = None.\nProof.\nintros.\ndestruct (adr_range_dec (b',lo) (hi-lo) (b,ofs)).\ndestruct a; simpl in *.\nsubst b'; apply free_access with (ofs:=ofs) in H0; [ | omega].\ndestruct H0.\npose proof (Memory.access_cur_max m' (b,ofs)).\nrewrite H1 in H3; simpl in H3.\ndestruct (access_at m' (b, ofs) Cur); auto; contradiction.\nrewrite <- H. symmetry.\neapply free_access_other; eauto.\ndestruct (eq_block b b'); auto; right.\nsimpl in n.\nassert (~(lo <= ofs < lo + (hi - lo))) by intuition.\nomega.\nQed.\n\nLemma free_nadr_range_eq : forall m b b' ofs' lo hi m',\n  ~ adr_range (b, lo) (hi - lo) (b', ofs')\n  -> free m b lo hi = Some m'\n  -> access_at m (b', ofs') = access_at m' (b', ofs')\n  /\\  contents_at m (b', ofs') = contents_at m' (b', ofs').\nProof.\nintros.\nsplit.\nextensionality k.\napply (free_access_other _ _ _ _ _ H0 b' ofs' k).\ndestruct (eq_block b b'); auto; right.\nsimpl in H.\nassert (~(lo <= ofs' < lo + (hi - lo))) by intuition.\nomega.\nunfold contents_at.\nsimpl.\nTransparent free.\nunfold free in H0.\nOpaque free.\nif_tac in H0; inv H0.\nunfold unchecked_free.\nsimpl.\nreflexivity.\nQed.\n\nSection free.\nVariables (jm :juicy_mem) (m': mem)\n          (b: block) (lo hi: Z)\n          (FREE: free (m_dry jm) b lo hi = Some m')\n          (PERM: forall ofs, lo <= ofs < hi ->\n                      perm_of_res (m_phi jm @ (b,ofs)) = Some Freeable).\n\nDefinition inflate_free: rmap. refine (\nproj1_sig (make_rmap (fun loc =>\n  if adr_range_dec (b,lo) (hi-lo) loc then NO Share.bot bot_unreadable else m_phi jm @ loc)\n     _ (level (m_phi jm)) _)).\nProof.\n* (* AV.valid *)\nassert (VALID: valid (resource_at (m_phi jm))) by (apply phi_valid).\nintros b' ofs'.\nspecialize (VALID b' ofs').\nunfold compose in *; simpl in *.\nif_tac; [simpl; now auto | ].\ndestruct (m_phi jm @ (b', ofs')) eqn:?; try destruct k; simpl in *; auto.\n +\n intros. specialize (VALID _ H0).\n if_tac; [ | now auto].\n destruct H1; subst b'.\n specialize (PERM (ofs'+i)).  spec PERM; [omega | ].\n destruct (m_phi jm @ (b, ofs' + i)); inv  VALID. inv PERM.\n +\n destruct VALID as [n [? ?]]; exists n; split; auto.\n if_tac; auto.\n destruct H2; subst b'.\n specialize (PERM (ofs'-z)).  spec PERM; [omega | ].\n destruct (m_phi jm @ (b, ofs' -z)); inv  H1. inv PERM.\n*\nunfold compose.\nextensionality l.\ndestruct l as (b', ofs').\nif_tac; try reflexivity.\napply resource_at_approx.\nDefined.\n\n\nDefinition free_juicy_mem: juicy_mem.\n generalize (juicy_mem_contents jm); intro.\n generalize (juicy_mem_access jm); intro.\n generalize (juicy_mem_max_access jm); intro.\n refine (mkJuicyMem m' inflate_free _ _ _ _).\n* (* contents_cohere *)\nunfold contents_cohere in *.\nintros rsh' sh' v' [b' ofs'] pp H2.\nunfold access_cohere in H0.\nspecialize (H0 (b', ofs')).\nunfold inflate_free in H2; rewrite resource_at_make_rmap in H2.\nif_tac in H2; [inv H2 | ]. rename H3 into H8.\nremember (m_phi jm @ (b', ofs')) as HPHI.\ndestruct HPHI; try destruct k; inv H2.\nassert (H3: contents_at (m_dry jm) (b', ofs') = v') by (eapply H; eauto).\nassert (H4: m' = unchecked_free (m_dry jm) b lo hi) by (apply free_result; auto).\nrewrite H4.\nunfold unchecked_free, contents_at; simpl.\nsplit; auto.\nsymmetry in HeqHPHI.\ndestruct (H _ _ _ _ _ HeqHPHI); auto.\n* (* access_cohere *)\nintros [b' ofs']; spec H0 (b', ofs').\nunfold inflate_free; rewrite resource_at_make_rmap.\ndestruct (adr_range_dec (b,lo) (hi-lo) (b',ofs')).\n + (* adr_range *)\ndestruct a as [H2 H3].\nreplace (lo+(hi-lo)) with hi in H3 by omega.\nsubst b'.\nreplace (access_at m' (b, ofs') Cur) with (@None permission).\nsimpl. rewrite if_true by auto. auto.\ndestruct (free_access _ _ _ _ _ FREE ofs' H3).\npose proof (Memory.access_cur_max m' (b,ofs')). rewrite H4 in H5.\nsimpl  in H5.\ndestruct (access_at m' (b, ofs') Cur); auto; contradiction.\n+ (* ~adr_range *)\ndestruct (free_nadr_range_eq _ _ _ _ _ _ _ n FREE) as [H2 H3].\nrewrite H2 in *. clear H2 H3.\ncase_eq (m_phi jm @ (b', ofs')); intros; rewrite H2 in *; auto.\n* (* max_access_cohere *)\n{ intros [b' ofs']. specialize (H1 (b',ofs')).\n  unfold inflate_free. unfold max_access_at. rewrite resource_at_make_rmap.\n  destruct (adr_range_dec (b,lo) (hi-lo) (b',ofs')).\n  - simpl; destruct (eq_dec Share.bot Share.bot) as [e|n]; [| exfalso; apply n; reflexivity].\n    destruct (access_at m' (b', ofs') Max); constructor.\n  - clear PERM.\n    unfold max_access_at.\n    destruct (free_nadr_range_eq _ _ _ _ _ _ _ n FREE) as [H2 H3].\n    rewrite <- H2. assumption. }\n* (* alloc_cohere *)\nhnf; intros.\nunfold inflate_free. rewrite resource_at_make_rmap.\npose proof (juicy_mem_alloc_cohere jm loc).\nrewrite (nextblock_free _ _ _ _ _ FREE) in H2; auto.\nrewrite H3; auto.\nif_tac; auto.\nDefined.\n\nEnd free.\n\nLemma free_not_freeable_eq : forall m b lo hi m' b' ofs',\n  free m b lo hi = Some m'\n  -> access_at m (b', ofs') Cur <> Some Freeable\n  -> access_at m (b', ofs') Cur = access_at m' (b', ofs') Cur.\nProof.\nintros.\ndestruct (adr_range_dec (b,lo) (hi-lo) (b',ofs')).\ndestruct a.\nsubst b'.\ndestruct (free_access _ _ _ _ _ H ofs'); [omega |].\ncontradiction.\napply (free_access_other _ _ _ _ _ H).\ndestruct (eq_block b' b); auto; right.\nsubst b'.\nsimpl in n. assert (~( lo <= ofs' < lo + (hi - lo))) by intuition; omega.\nQed.\n\n(* The empty juicy memory *)\n\nDefinition after_alloc' \n  (lo hi: Z) (b: block) (phi: rmap)(H: forall ofs, phi @ (b,ofs) = NO Share.bot bot_unreadable)\n  : address -> resource := fun loc =>\n    if adr_range_dec (b,lo) (hi-lo) loc \n      then YES Share.top readable_share_top (VAL Undef) NoneP\n      else phi @ loc.\n\nLemma adr_range_eq_block : forall b ofs n b' ofs',\n  adr_range (b,ofs) n (b',ofs') ->\n  b=b'.\nProof.\nunfold adr_range; intros.\ndestruct H; auto.\nQed.\n\nLemma after_alloc'_valid : forall lo hi b phi H,\n  valid (after_alloc' lo hi b phi H).\nProof.\nintros; hnf; intros.\nunfold compose, after_alloc'.\nif_tac; simpl; auto.\ncase_eq (phi @ (b0, ofs)); intros; simpl; auto.\ngeneralize (rmap_valid phi). intro H4.\nunfold AV.valid, compose in H4.\nspec H4 b0 ofs.\nrewrite H1 in H4; simpl in H4.\ndestruct k; auto.\nintros.\nif_tac.\nassert (b = b0) by (eapply adr_range_eq_block; eauto).\nsubst. congruence.\nauto.\ndestruct H4 as [? [? ?]]; eexists; split; eauto.\nif_tac; eauto.\nassert (b = b0) by (eapply adr_range_eq_block; eauto).\nsubst. congruence.\nQed.\n\nLemma after_alloc'_ok : forall lo hi b phi H,\n  resource_fmap (approx (level phi)) (approx (level phi)) oo (after_alloc' lo hi b phi H)\n  = after_alloc' lo hi b phi H.\nProof.\nintros.\nunfold resource_fmap, compose, after_alloc'.\nextensionality loc.\nif_tac.\nrewrite preds_fmap_NoneP; auto.\ncase_eq (phi @ loc); intros; auto.\ngeneralize H1; intros.\napply necR_YES with (phi':=phi) in H1; eauto.\nrewrite <- H1.\nauto.\ngeneralize (resource_at_approx phi loc); rewrite H1; auto.\nQed.\n\nDefinition after_alloc\n  (lo hi: Z) (b: block) (phi: rmap)(H: forall ofs, phi @ (b,ofs) = NO Share.bot bot_unreadable) : rmap :=\n  proj1_sig (make_rmap (after_alloc' lo hi b phi H)\n    (after_alloc'_valid lo hi b phi H)\n    (level phi)\n    (after_alloc'_ok lo hi b phi H)).\n\nDefinition mod_after_alloc' (phi: rmap) (lo hi: Z) (b: block)\n  : address -> resource := fun loc =>\n    if adr_range_dec (b,lo) (hi-lo) loc \n      then YES Share.top readable_share_top (VAL Undef) NoneP\n      else core phi @ loc.\n\nLemma mod_after_alloc'_valid : forall phi lo hi b,\n  valid (mod_after_alloc' phi lo hi b).\nProof.\nintros; hnf; intros.\nunfold compose, mod_after_alloc'.\nif_tac; simpl; auto.\nrewrite <- core_resource_at.\ndestruct (phi @ (b0,ofs)).\nrewrite core_NO; simpl; auto.\nrewrite core_YES; simpl; auto.\nrewrite core_PURE; simpl; auto.\nQed.\n\nLemma mod_after_alloc'_ok : forall phi lo hi b,\n  resource_fmap (approx (level phi)) (approx (level phi)) oo (mod_after_alloc'  phi lo hi b)\n  = mod_after_alloc' phi lo hi b.\nProof.\nintros.\nunfold resource_fmap, compose, mod_after_alloc'.\nextensionality loc.\nif_tac; auto.\ncase_eq (core phi @ loc); intros; auto; f_equal;\nrewrite <- level_core;\ngeneralize (resource_at_approx (core phi) loc); rewrite H0; intro; injection H1; auto.\nQed.\n\nDefinition mod_after_alloc (phi: rmap) (lo hi: Z) (b: block) :=\n  proj1_sig (make_rmap (mod_after_alloc' phi lo hi b)\n    (mod_after_alloc'_valid phi lo hi b)\n    _\n    (mod_after_alloc'_ok phi lo hi b)).\n\nTransparent alloc.\n\nLemma adr_range_inv: forall loc loc' n,\n  ~ adr_range loc n loc' ->\n  fst loc <> fst loc' \\/ (fst loc=fst loc' /\\ ~snd loc <= snd loc' < snd loc + n).\nProof.\nintros until n.\nintro H.\ndestruct (peq (fst loc) (fst loc')).\nright; split; auto; intro Contra.\napply H.\nunfold adr_range.\ndestruct loc,loc'.\nauto.\nleft; intro Contra.\napply n0; auto.\nQed.\n\nLemma dry_noperm_juicy_nonreadable : forall m loc,\n  access_at (m_dry m) loc Cur = None ->   ~readable loc (m_phi m).\nProof.\nintros.\nrewrite (juicy_mem_access m loc) in H.\nintro. hnf in H0.\ndestruct (m_phi m @loc); simpl in *; auto.\ndestruct k as [x | | |]; try inv H.\nunfold perm_of_sh in H2.\nif_tac in H2. if_tac in H2; inv H2.\nrewrite if_true in H2 by auto.\ninv H2.\nQed.\n\nLemma fullempty_after_alloc : forall m1 m2 lo n b ofs,\n  alloc m1 lo n = (m2, b) ->\n  access_at m2 (b, ofs) Cur = None \\/ access_at m2 (b, ofs) Cur = Some Freeable.\nProof.\nintros.\npose proof (alloc_access_same _ _ _ _ _ H ofs Cur).\ndestruct (range_dec lo ofs n). auto.\nleft.\nrewrite <- (alloc_access_other _ _ _ _ _ H b ofs Cur) by (right; omega).\napply alloc_result in H.\nsubst.\napply nextblock_access_empty.\napply Pos.le_ge, Ple_refl.\nQed.\n\nLemma alloc_dry_unchanged_on : forall m1 m2 loc lo hi b0,\n  alloc m1 lo hi = (m2, b0) ->\n  ~adr_range (b0,lo) (hi-lo) loc ->\n  access_at m1 loc = access_at m2 loc /\\\n  (access_at m1 loc Cur <> None -> contents_at m1 loc= contents_at m2 loc).\nProof.\nintros.\ndestruct loc as [b z]; simpl.\nsplit.\nextensionality k.\neapply Memory.alloc_access_other; eauto.\nsimpl in H0.\ndestruct (eq_block b b0); auto. subst. right.\nassert (~(lo <= z < lo + (hi - lo))) by intuition; omega.\nintros.\nunfold alloc in H.\ninv H. unfold contents_at; simpl.\nunfold adr_range in H0.\ndestruct (eq_dec b (nextblock m1)).\nsubst.\nrewrite invalid_noaccess in H1; [ congruence |].\ncontradict H0.\nred in H0. apply Plt_irrefl in H0. contradiction.\nrewrite PMap.gso by auto.\nauto.\nQed.\n\nLemma adr_range_zle_fact : forall b lo hi loc,\n  adr_range (b,lo) (hi-lo) loc ->\n  zle lo (snd loc) && zlt (snd loc) hi = true.\nProof.\nunfold adr_range.\nintros.\ndestruct loc; simpl in *.\ndestruct H.\ndestruct H0.\napply andb_true_iff.\nsplit.\napply zle_true; auto.\napply zlt_true; omega.\nQed.\n\nLemma alloc_dry_updated_on : forall m1 m2 lo hi b loc,\n  alloc m1 lo hi = (m2, b) ->\n  adr_range (b, lo) (hi - lo) loc ->\n  access_at m2 loc Cur=Some Freeable /\\\n  contents_at m2 loc=Undef.\nProof.\nintros.\ndestruct loc as [b' z'].\nsplit.\ndestruct H0. subst b'.\napply (alloc_access_same _ _ _ _ _ H). omega.\nunfold contents_at; unfold alloc in H; inv H. simpl.\ndestruct H0; subst b'.\nrewrite PMap.gss. rewrite ZMap.gi; auto.\nQed.\n\nDefinition resource_decay (nextb: block) (phi1 phi2: rmap) :=\n  (level phi1 >= level phi2)%nat /\\\n forall l: address,\n  ((fst l >= nextb)%positive -> phi1 @ l = NO Share.bot bot_unreadable) /\\\n  (resource_fmap (approx (level phi2)) (approx (level phi2)) (phi1 @ l) = (phi2 @ l) \\/\n  (exists sh, exists (wsh: writable_share sh), exists v, exists v',\n       resource_fmap (approx (level phi2)) (approx (level phi2)) (phi1 @ l) = \n                       YES sh (writable_readable_share wsh) (VAL v) NoneP /\\ \n       phi2 @ l = YES sh (writable_readable_share wsh) (VAL v') NoneP)\n  \\/ ((fst l >= nextb)%positive /\\ exists v, phi2 @ l = YES Share.top readable_share_top (VAL v) NoneP)\n  \\/ (exists v, exists pp, phi1 @ l = YES Share.top readable_share_top (VAL v) pp \n                        /\\ phi2 @ l = NO Share.bot bot_unreadable)).\n\nDefinition resource_nodecay (nextb: block) (phi1 phi2: rmap) :=\n  (level phi1 >= level phi2)%nat /\\\n  forall l: address,\n  ((fst l >= nextb)%positive -> phi1 @ l = NO Share.bot bot_unreadable) /\\\n  (resource_fmap (approx (level phi2)) (approx (level phi2)) (phi1 @ l) = (phi2 @ l) \\/\n  (exists sh, exists (wsh: writable_share sh), exists v, exists v',\n       resource_fmap (approx (level phi2)) (approx (level phi2)) (phi1 @ l) = YES sh (writable_readable_share wsh) (VAL v) NoneP\n      /\\ phi2 @ l = YES sh (writable_readable_share wsh) (VAL v') NoneP)).\n\nLemma resource_nodecay_decay:\n   forall b phi1 phi2, resource_nodecay b phi1 phi2 -> resource_decay b phi1 phi2.\nProof.\n unfold resource_decay, resource_nodecay; intros; destruct H; split; intros; try omega.\nspecialize (H0 l); intuition.\nQed.\n\nLemma resource_decay_refl: forall b phi, \n  (forall l, (fst l >= b)%positive -> phi @ l = NO Share.bot bot_unreadable) ->\n  resource_decay b phi phi.\nProof.\nintros.\nsplit; auto.\nintros; split; auto.\nleft.\napply resource_at_approx.\nQed.\n\nLemma resource_decay_trans: forall b b' m1 m2 m3,\n  (b <= b')%positive ->\n  resource_decay b m1 m2 -> resource_decay b' m2 m3 -> resource_decay b m1 m3.\nProof.\n intros until m3; intro Hbb; intros.\n destruct H as [H' H]; destruct H0 as [H0' H0]; split; [omega |].\n intro l; specialize (H l); specialize (H0 l).\n destruct H,H0.\n split.  auto.\n destruct H1.\n destruct H2.\n left. rewrite <- H2.\n replace (resource_fmap (approx (level m3)) (approx (level m3)) (m1 @ l))\n    with (resource_fmap (approx (level m3)) (approx (level m3))\n              (resource_fmap (approx (level m2)) (approx (level m2)) (m1 @ l)))\n  by (rewrite resource_fmap_fmap; rewrite approx_oo_approx' by auto; rewrite approx'_oo_approx by auto; auto).\nrewrite H1. auto.\n clear - Hbb H H1 H0 H2 H' H0'.\n right.\n destruct H2 as [[sh2 [wsh2 [v2 [v2' [? ?]]]]]|[[? [v ?]] |?]]; subst.\n left; exists sh2, wsh2,v2,v2'; split; auto.\n rewrite <- H1 in H2.\n rewrite resource_fmap_fmap in H2.\n rewrite approx_oo_approx' in H2 by omega.\n rewrite approx'_oo_approx in H2 by omega.\n assumption.\n right; left. split. xomega. exists v; auto.\n right; right; auto.\n destruct H2 as [v [pp [? ?]]].\n rewrite H2 in H1. destruct (m1 @ l); inv H1.\n exists v, p. split; auto. f_equal. apply proof_irr.\n destruct H2.\n destruct H1 as [[sh [wsh [v [v' [? ?]]]]]|[[? [v ?]] |?]].\n right; left; exists sh,wsh,v,v'; split. \n rewrite <- (approx_oo_approx' (level m3) (level m2)) at 1 by auto.\n rewrite <- (approx'_oo_approx (level m3) (level m2)) at 2 by auto.\n rewrite <- resource_fmap_fmap. rewrite H1.\n unfold resource_fmap. rewrite preds_fmap_NoneP. auto.\n rewrite H3 in H2. rewrite <- H2.\n unfold resource_fmap. rewrite preds_fmap_NoneP. auto.\n right; right; left; split; auto. exists v. rewrite <- H2; rewrite <- H3.\n rewrite H3.\n unfold resource_fmap. rewrite preds_fmap_NoneP. auto.\n right; right; right.\n destruct H1 as [v [pp [? ?]]].\n rewrite H3 in H2. simpl in H2. eauto.\n destruct H1 as [[sh [wsh [v [v' [? ?]]]]]|[[? [v ?]] |?]].\n destruct H2 as [[sh2 [wsh2 [v2 [v2' [? ?]]]]]|[[? [v2 ?]] |?]].\n right; left; exists sh,wsh,v,v2'; split.\n rewrite <- (approx_oo_approx' (level m3) (level m2)) at 1 by auto.\n rewrite <- (approx'_oo_approx (level m3) (level m2)) at 2 by auto.\n rewrite <- resource_fmap_fmap. rewrite H1.\n unfold resource_fmap. rewrite preds_fmap_NoneP. auto.\n rewrite H3 in H2. rewrite H4. simpl in H2. inv H2.\n f_equal. apply proof_irr.\n right; right; left. split. xomega. exists v2; auto.\n right; right; right.\n destruct (m1 @ l); inv H1.\n destruct H2 as [vx [pp [? ?]]]. inversion2 H3 H1.\n exists v,p. split; auto. f_equal; apply proof_irr.\n destruct H2 as [[sh2 [wsh2 [v2 [v2' [? ?]]]]]|[[? [v2 ?]] |?]].\n right; right; left; split; auto. exists v2'. rewrite H3 in H2; inv H2.\n rewrite H4; f_equal; apply proof_irr.\n right; right; left; split; auto; exists v2; auto.\n left. destruct H2 as [v' [pp [? ?]]]. rewrite H4; rewrite H; auto.\n destruct H2 as [[sh2 [wsh2 [v2 [v2' [? ?]]]]]|[[? [v2 ?]] |?]].\n destruct H1 as [v' [pp [? ?]]].\n rewrite H4 in H2; inv H2.\n right; right; left; split. xomega. eauto.\n right; right; right.\n destruct H1 as [v1 [pp1 [? ?]]].\n destruct H2 as [v2 [pp2 [? ?]]].\n inversion2 H3 H2.\nQed.\n\nLemma level_store_juicy_mem:\n forall jm m ch b i v H, level (store_juicy_mem jm m ch b i v H) = level jm.\nProof.\nintros.\nunfold store_juicy_mem. simpl.\nunfold inflate_store; simpl. rewrite level_make_rmap. auto.\nQed.\n\nLemma level_storebytes_juicy_mem:\n forall jm m b i bytes H, level (storebytes_juicy_mem jm m b i bytes H) = level jm.\nProof.\nintros.\nunfold storebytes_juicy_mem. simpl.\nunfold inflate_store; simpl. rewrite level_make_rmap. auto.\nQed.\n\nLemma inflate_store_resource_nodecay:\n  forall (jm: juicy_mem) (m': mem)\n          (ch: memory_chunk) (b: block) (ofs: Z) (v: val)\n          (STORE: store ch (m_dry jm) b ofs v = Some m')\n          (PERM: forall z, ofs <= z < ofs + size_chunk ch ->\n                      perm_order'' (perm_of_res (m_phi jm @ (b,z))) (Some Writable))\n          phi',\n  inflate_store m' (m_phi jm) = phi' -> resource_nodecay (nextblock (m_dry jm)) (m_phi jm) phi'.\nProof.\nintros.\nsplit.\nsubst; unfold inflate_store; simpl. rewrite level_make_rmap. auto.\nintro l'.\nsplit.\napply juicy_mem_alloc_cohere.\ndestruct (adr_range_dec (b, ofs) (size_chunk ch) l') as [HA | HA].\n* (* adr_range *)\nright.\nunfold adr_range in HA.\ndestruct l' as (b', ofs').\ndestruct HA as [HA0 HA1].\nsubst b'.\nassert (H0: range_perm (m_dry jm) b ofs (ofs + size_chunk ch) Cur Writable).\n  cut (valid_access (m_dry jm) ch b ofs Writable).\n  intros [? ?]; auto.\n  eapply store_valid_access_3; eauto.\nassert (H1: perm (m_dry jm) b ofs' Cur Writable) by (apply H0; auto).\ngeneralize (juicy_mem_access jm (b, ofs')); intro ACCESS.\nunfold perm, perm_order' in H1.\nunfold access_at in ACCESS.\nsimpl in *.\ndestruct ((mem_access (m_dry jm)) !! b ofs' Cur) eqn:?H; try contradiction.\nspecialize (PERM ofs' HA1).\ndestruct ( m_phi jm @ (b, ofs') ) eqn:?H; try destruct k; simpl in PERM; try if_tac in PERM; try inv PERM.\ndestruct (juicy_mem_contents _ _ _ _ _ _ H3); subst.\nsimpl.\nassert (writable_share sh). {\n clear - PERM.\n unfold perm_of_sh in PERM.\n if_tac in PERM; auto. if_tac_in PERM. inv PERM.\n if_tac in PERM; inv PERM.\n}\n exists sh,H; do 2 econstructor; split; simpl; f_equal.\n apply proof_irr.\nunfold inflate_store;  rewrite resource_at_make_rmap.\nrewrite H3. f_equal; apply proof_irr.\n* (* ~ adr_range *)\nleft.\nassert (H0: level (m_phi jm) = level phi').\n  rewrite <- H; unfold inflate_store; rewrite level_make_rmap; auto.\nrewrite <- H.\nunfold inflate_store; rewrite level_make_rmap; rewrite resource_at_make_rmap.\ncase_eq l'; intros b' ofs' e'; subst.\nremember (m_phi jm @ (b', ofs')) as HPHI; destruct HPHI; try destruct k; auto;\n  try solve [rewrite HeqHPHI; rewrite resource_at_approx; auto].\nrewrite (store_phi_elsewhere_eq jm _ _ _ _ _ STORE _ r m (b', ofs')); auto.\nassert (H: p = NoneP).\n  symmetry in HeqHPHI; \n  destruct  (juicy_mem_contents jm _ _ _ _ _ HeqHPHI); auto.\nrewrite H.\nunfold resource_fmap; f_equal; try reflexivity.\nassert (H: p = NoneP).\n  symmetry in HeqHPHI;\n  destruct  (juicy_mem_contents jm _ _ _ _ _ HeqHPHI); auto.\nrewrite H in HeqHPHI; clear H.\nrewrite HeqHPHI; auto.\nQed.\n\nLemma inflate_free_resource_decay:\n forall (jm :juicy_mem) (m': mem)\n          (b: block) (lo hi: Z)\n          (FREE: free (m_dry jm) b lo hi = Some m')\n          (PERM: forall ofs : Z,\n             lo <= ofs < hi -> perm_of_res (m_phi jm @ (b, ofs)) = Some Freeable),\n   resource_decay (nextblock (m_dry jm)) (m_phi jm) (inflate_free jm b lo hi PERM).\nProof.\nintros.\nsplit.\nunfold inflate_free; rewrite level_make_rmap; auto.\nintros l.\nsplit.\napply juicy_mem_alloc_cohere.\ndestruct (adr_range_dec (b, lo) (hi-lo) l) as [HA | HA].\n* (* adr_range *)\nright. right.\ndestruct l; simpl in HA|-*.\ndestruct HA as [H0 H1]. subst b0.\nassert (lo + (hi - lo) = hi) by omega.\nrewrite H in H1. clear H.\nunfold inflate_free; simpl; rewrite resource_at_make_rmap.\nspecialize (PERM _ H1).\ndestruct (m_phi jm @ (b,z)) eqn:?; try destruct k; inv PERM.\nif_tac in H0; inv H0.\nrewrite if_true by (split; auto; omega).\nright.\nexists m, p.\nunfold perm_of_sh in H0.\nrepeat if_tac in H0; inv H0.\nsplit; try reflexivity. f_equal; apply proof_irr.\n* (* ~adr_range *)\ndestruct l.\ndestruct (free_nadr_range_eq _ _ _ _ _ _ _ HA FREE).\nleft.\nunfold inflate_free; rewrite level_make_rmap; rewrite resource_at_make_rmap.\nrewrite if_false by auto.\ngeneralize (juicy_mem_contents jm); intro Hc.\ngeneralize (juicy_mem_access jm (b0,z)); intro Ha.\nrewrite resource_at_approx.\ncase_eq (m_phi jm @ (b0, z)); intros; rewrite H1 in Ha; auto.\nQed.\n\nLemma juicy_store_nodecay:\n  forall jm m' ch b ofs v\n       (H: store ch (m_dry jm) b ofs v = Some m')\n          (PERM: forall z, ofs <= z < ofs + size_chunk ch ->\n                      perm_order'' (perm_of_res (m_phi jm @ (b,z))) (Some Writable)),\n       resource_nodecay (nextblock (m_dry jm)) (m_phi jm) (m_phi (store_juicy_mem jm _ _ _ _ _ H)).\nProof.\n intros.\n eapply inflate_store_resource_nodecay; eauto.\nQed.\n\nLemma can_age1_juicy_mem: forall j r,\n  age (m_phi j) r -> exists j', age1 j = Some j'.\nProof.\nintros j r H.\nunfold age in H.\ncase_eq (age1_juicy_mem j); intros.\ndestruct (age1_juicy_mem_unpack _ _ H0).\neexists; eauto.\napply age1_juicy_mem_None1 in H0.\nrewrite H0 in H.\nelimtype False; inversion H.\nQed.\n\n\nLemma can_age_jm:\n  forall jm, age1 (m_phi jm) <> None -> exists jm', age jm jm'.\nProof.\n intro jm; case_eq (age1 (m_phi jm)); intros; try congruence.\n apply (can_age1_juicy_mem _ _ H).\nQed.\n\n\nLemma age_jm_dry: forall {jm jm'}, age jm jm' -> m_dry jm = m_dry jm'.\nProof. intros; destruct (age1_juicy_mem_unpack _ _ H); auto.\nQed.\n\nLemma age_jm_phi: forall {jm jm'}, age jm jm' -> age (m_phi jm) (m_phi jm').\nProof. intros; destruct (age1_juicy_mem_unpack _ _ H); auto.\nQed.\n\n(** * Results about aging in juicy memory coherence properties *)\n\nLemma age1_YES'_1 {phi phi' l rsh sh k P} :\n  age1 phi = Some phi' ->\n  phi @ l = YES rsh sh k P ->\n  (exists P, phi' @ l = YES rsh sh k P).\nProof.\n  intros A E.\n  apply (proj1 (age1_YES' phi phi' l rsh sh k A)).\n  eauto.\nQed.\n\nLemma age1_YES'_2 {phi phi' l rsh sh k P} :\n  age1 phi = Some phi' ->\n  phi' @ l = YES rsh sh k P ->\n  (exists P, phi @ l = YES rsh sh k P).\nProof.\n  intros A E.\n  apply (proj2 (age1_YES' phi phi' l rsh sh k A)).\n  eauto.\nQed.\n\nLemma age1_PURE_2 {phi phi' l k P} :\n  age1 phi = Some phi' ->\n  phi' @ l = PURE k P ->\n  (exists P, phi @ l = PURE k P).\nProof.\n  intros A E.\n  apply (proj2 (age1_PURE phi phi' l k A)).\n  eauto.\nQed.\n\nLemma perm_of_res_age x y loc :\n  age x y -> perm_of_res (x @ loc) = perm_of_res (y @ loc).\nProof.\n  intros A.\n  destruct (x @ loc) as [sh | rsh sh k p | k p] eqn:E.\n  - destruct (age1_NO x y loc sh n A) as [[]_]; eauto.\n  - destruct (age1_YES' x y loc rsh sh k A) as [[p' ->] _]; eauto.\n  - destruct (age1_PURE x y loc k A) as [[p' ->] _]; eauto.\nQed.\n\nLemma contents_cohere_age m : hereditary age (contents_cohere m).\nProof.\n  intros x y E A.\n  intros rsh sh v loc pp H.\n  destruct (proj2 (age1_YES' _ _ loc rsh sh (VAL v) E)) as [pp' E'].\n  now eauto.\n  specialize (A rsh sh v loc _ E').\n  destruct A as [A ->]. split; auto.\n  apply (proj1 (age1_YES _ _ loc rsh sh (VAL v) E)) in E'.\n  congruence.\nQed.\n\nLemma access_cohere_age m : hereditary age (access_cohere m).\nProof.\n  intros x y E B.\n  intros addr.\n  destruct (age1_levelS _ _ E) as [n L].\n  rewrite (B addr).\n  apply perm_of_res_age, E.\nQed.\n\nLemma max_access_cohere_age m : hereditary age (max_access_cohere m).\nProof.\n  intros x y E C.\n  intros addr; specialize (C addr).\n  destruct (y @ addr) as [sh | sh p k pp | k p] eqn:AT.\n  - eapply (age1_NO x) in AT; auto.\n    rewrite AT in C; auto.\n  - destruct (age1_YES'_2 E AT) as [P Ex].\n    rewrite Ex in C.\n    auto.\n  - destruct (age1_PURE_2 E AT) as [P Ex].\n    rewrite Ex in C; auto.\nQed.\n\nLemma alloc_cohere_age m : hereditary age (alloc_cohere m).\nProof.\n  intros x y E D.\n  intros loc G; specialize (D loc G).\n  eapply (age1_NO x); eauto.\nQed.\n\n\n(** * Results in the opposite direction *)\n\nDefinition unage {A} {_:ageable A} x y := age y x.\n\nLemma unage_YES'_1 {phi phi' l rsh sh k P} :\n  age1 phi' = Some phi ->\n  phi @ l = YES rsh sh k P ->\n  (exists P, phi' @ l = YES rsh sh k P).\nProof.\n  intros A E.\n  apply (proj2 (age1_YES' phi' phi l rsh sh k A)).\n  eauto.\nQed.\n\nLemma unage_YES'_2 {phi phi' l rsh sh k P} :\n  age1 phi' = Some phi ->\n  phi' @ l = YES rsh sh k P ->\n  (exists P, phi @ l = YES rsh sh k P).\nProof.\n  intros A E.\n  apply (proj1 (age1_YES' phi' phi l rsh sh k A)).\n  eauto.\nQed.\n\nLemma unage_PURE_2 {phi phi' l k P} :\n  age1 phi' = Some phi ->\n  phi' @ l = PURE k P ->\n  (exists P, phi @ l = PURE k P).\nProof.\n  intros A E.\n  apply (proj1 (age1_PURE phi' phi l k A)).\n  eauto.\nQed.\n\nLemma contents_cohere_unage m : hereditary unage (contents_cohere m).\nProof.\n  intros x y E A.\n  intros rsh sh v loc pp H.\n  destruct (proj1 (age1_YES' _ _ loc rsh sh (VAL v) E)) as [pp' E'].\n  eauto.\n  specialize (A rsh sh v loc _ E').\n  destruct A as [A ->]. split; auto.\n  apply (proj2 (age1_YES _ _ loc rsh sh (VAL v) E)) in E'.\n  congruence.\nQed.\n\nLemma access_cohere_unage m : hereditary unage (access_cohere m).\nProof.\n  intros x y E B.\n  intros addr.\n  destruct (age1_levelS _ _ E) as [n L].\n  rewrite (B addr).\n  symmetry.\n  apply perm_of_res_age, E.\nQed.\n\nLemma max_access_cohere_unage m : hereditary unage (max_access_cohere m).\nProof.\n  intros x y E C.\n  intros addr; specialize (C addr).\n  destruct (x @ addr) as [sh | sh p k pp | k p] eqn:AT.\n  - eapply (age1_NO y) in AT; auto.\n    rewrite AT; auto.\n  - destruct (@age1_YES'_2 y x addr sh p k pp E AT) as [P ->].\n    auto.\n  - destruct (age1_PURE_2 E AT) as [P Ex].\n    rewrite Ex; auto.\nQed.\n\nLemma alloc_cohere_unage m : hereditary unage (alloc_cohere m).\nProof.\n  intros x y E D.\n  intros loc G; specialize (D loc G).\n  eapply (age1_NO y); eauto.\nQed.\n\nLemma juicy_mem_unage jm' : { jm | age jm jm' }.\nProof.\n  pose proof (rmap_unage_age (m_phi jm')) as A.\n  remember (rmap_unage (m_phi jm')) as phi.\n  unshelve eexists (mkJuicyMem (m_dry jm') phi _ _ _ _).\n  all: destruct jm' as [m phi' Co Ac Ma N]; simpl.\n  - eapply contents_cohere_unage; eauto.\n  - eapply access_cohere_unage; eauto.\n  - eapply max_access_cohere_unage; eauto.\n  - eapply alloc_cohere_unage; eauto.\n  - apply age1_juicy_mem_unpack''; auto.\nQed.\n", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/veric/juicy_mem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.20794712985902455}}
{"text": "Require Export Arith.EqNat.\nRequire Export Arith.Lt.\nRequire Export Arith.Compare_dec.\nRequire Export List.\nRequire Import String.\nOpen Scope string_scope.\nRequire Import TacticsSF.\nRequire Import TacticsCPDT.\nRequire Import Process.\nRequire Import List.\nRequire Import PrettyPrinter.\nRequire Import TypeAssignmentPoly.\nRequire Import ResultBasics.\nRequire Import ExampleCommon.\nRequire Import ExampleRecursion.\n\nLemma abp_recvC_Ack_procR_typing :\n  forall i t (xc:free_id) (xerr2:free_id) (xout:free_id),\n    ~ In xc (\"recv_true\" :: \"recv_false\" :: nil)\n    ->\n    ~ In xerr2 (xc :: \"recv_true\" :: \"recv_false\" :: nil)\n    ->\n    ~ In xout (xerr2 :: xc :: \"recv_true\" :: \"recv_false\" :: nil)\n    ->\n    (CTX.add (ValVariable (Var (Free xout)), TChannel (SDual (SToks t)))\n      (CTX.add (ValVariable (Var (Free xc)), TChannel SEpsilon)\n      (CTX.add (ValVariable (Var (Free xerr2)),\n        TChannel (SDual (SAck t (token_of_bool (negb i)))))\n      (CTX.add (ValName (Nm (Free (\"recv_\" ++ string_of_bool i))),\n        TChannel (SFwd (SRecv i)))\n      (CTX.add (ValName (CoNm (Free (\"recv_\" ++ string_of_bool i))),\n        TChannel (SDual (SFwd (SRecv i))))\n      (CTX.add (ValName (CoNm (Free (\"recv_\" ++ string_of_bool (negb i)))),\n        TChannel (SDual (SFwd (SRecv (negb i)))))\n      CTX.empty))))))\n    |-p Var (Free xerr2) ? ;\n        (IsEq (Var (Bound 0)) (Token (if i then \"true\" else \"false\"))\n        (Var (Free xerr2) ? ;\n        (Var (Free xout) ! Var (Bound 0);\n        (New\n        (CoNm (Free (String.append \"recv_\"\n            (if if i then false else true then \"true\" else \"false\")))\n          ! Nm (Bound 0);\n        (CoNm (Bound 0) ! Var (Free xerr2);\n        (CoNm (Bound 0) ! Var (Free xout);\n        Zero))))))).\nProof.\n  intros i t xc xerr2 xout Hxc_nin Hxerr2_nin Hxout_nin.\n  (* err2?z; rest *)\n  apply TypPrefixInput with (s:=SDual (SAck t (token_of_bool (negb i))))\n      (L:=xc :: xerr2 :: xout :: \"recv_true\" :: \"recv_false\" :: nil);\n    [constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n      | free_vals_in_ctx |].\n  intros G' rho t' z H_z_nin Htrans G'def; compute; subst G'.\n  inversion Htrans; subst; inversion H1; subst; inversion H0; subst.\n\n  Case \"Htrans = TRAckA\".\n    (* [z=i]; rest *)\n    apply TypIsEq with (K:=token_of_bool (negb i))\n        (L:=token_of_bool i);\n      [constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | apply LToken; destruct i; ctx_wf; discriminate_w_list\n        | free_vals_in_ctx; try instantiate (1:=TSingleton (token_of_bool i));\n            contradiction\n        | ];\n      intro H_bad;\n      destruct i in H_bad;\n      contradict H_bad;\n      discriminate.\n\n  Case \"Htrans = TRAckC\".\n    (* [z=i]; rest *)\n    apply TypIsEq with\n        (K:=Token (string_of_negb_string (string_of_bool (negb i))))\n        (L:=token_of_bool i);\n      [constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | apply LToken; destruct i; ctx_wf; discriminate_w_list\n        | free_vals_in_ctx; try instantiate (1:=TSingleton (token_of_bool i));\n            contradiction\n        | intro H_i_tok_eq; clear H_i_tok_eq].\n    (* err2?x; rest *)\n    apply TypPrefixInput with (s:=SDual (SAck2 t (token_of_bool (negb i))))\n        (L:=z :: xc :: xerr2 :: xout :: \"recv_true\" :: \"recv_false\" :: nil);\n      [constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | free_vals_in_ctx; try instantiate (1:=TSingleton (token_of_bool i));\n            contradiction\n        |].\n    intros G' rho t' x H_x_nin Htrans1 G'def; compute; subst G'.\n    inversion Htrans1; subst; inversion H3; subst; inversion H2; subst.\n    (* out!x; rest *)\n    eapply TypPrefixOutput with (s:=SDual (SToks t))\n        (rho:=TSingleton tok0)\n        (t:=SDual (SToks s'0));\n      [apply trdual_w_mdual_involution; constructor; assumption\n        | right; constructor\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | left; reflexivity\n        | reflexivity\n        | ].\n    (* recv_{1-i}(err2, out), i.e. New d *)\n    apply TypNew with (s:=SRecv (negb i))\n        (L:=x :: z :: xc :: xerr2 :: xout :: \"recv_true\" :: \"recv_false\"\n          :: nil);\n      intros d G' H_d_nin G'def; compute; subst G'.\n    (* d!\"recv_i\";rest *)\n    eapply TypPrefixOutput with (s:=SDual (SFwd (SRecv (negb i))))\n        (rho:=TChannel (SRecv (negb i))) (t:=SDual (SFwd (SRecv (negb i))));\n      [apply trdual_w_mdual_involution; constructor\n        | left; discriminate\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | left; reflexivity\n        | reflexivity\n        | ].\n    (* d!err2;rest *)\n    eapply TypPrefixOutput with (s:=SDual (SRecv (negb i)))\n        (rho:=TChannel (SDual (SNack t tok0 s'0\n          (token_of_negb_token (token_of_bool (negb i))))))\n        (t:=SDual (SRecv1 (negb i)\n          (SNack t tok0 s'0 (token_of_negb_token (token_of_bool (negb i))))\n          s'0));\n      [apply trdual_w_mdual_involution; apply TRRecvA with (k:=tok0) (r:=t);\n          destruct i; reflexivity\n        | left; discriminate\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | left; reflexivity\n        | reflexivity\n        | ].\n    (* d!out;rest *)\n    eapply TypPrefixOutput with\n        (s:=SDual (SRecv1 (negb i)\n          (SNack t tok0 s'0 (token_of_negb_token (token_of_bool (negb i))))\n          s'0))\n        (rho:=TChannel (SDual (SToks s'0)))\n        (t:=SDual SEpsilon);\n      [apply trdual_w_mdual_involution; constructor; reflexivity\n        | left; discriminate\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | constructor; [destruct i; ctx_wf; discriminate_w_list | x_in_G]\n        | left; reflexivity\n        | reflexivity\n        | ].\n    (* 0 *)\n    apply TypZero;\n      destruct i;\n      ctx_wf;\n      discriminate_w_list.\nQed.\n", "meta": {"author": "cmcl", "repo": "msci", "sha": "06b1607ee1f4dde3c7c984ce6e1bbc86a8fd36f9", "save_path": "github-repos/coq/cmcl-msci", "path": "github-repos/coq/cmcl-msci/msci-06b1607ee1f4dde3c7c984ce6e1bbc86a8fd36f9/Coq Developments/session-polymorphism-coq-scripts/ExampleABPRecvCAck.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.20794350692392916}}
{"text": "(** BigStepAnnot.v: We constrain the Bicolano bigstep semantics to handle only the executions where exception thrown at a given point are in a predefined set. Such a set could be computed for example with a CHA static analysis. *)\n(* Hendra : - Modified to suit DEX program. \n            - Also trim the system to contain only Arithmetic *)\nRequire Export List.\nRequire Export ZArith.\nRequire Export LoadBicolano.\n\nInductive compat_op (A B:Set) : option A -> option B -> Prop :=\n  compat_op_none : compat_op A B None None\n| compat_op_some : forall k v, compat_op A B (Some k) (Some v).\nImplicit Arguments compat_op [A B].\n\n\nModule DEX_BigStepAnnot.\n\nImport DEX_BigStep.DEX_BigStep DEX_Dom DEX_Prog.\n\n\n\n  Set Implicit Arguments.\n  Section DEX_instr.\n\n  Inductive DEX_exec_intra (p:DEX_Program) (m:DEX_Method) : DEX_IntraNormalState -> DEX_IntraNormalState -> Prop :=\n  | exec_intra_normal : forall s1 s2,\n    DEX_NormalStep p m s1 s2 ->\n    DEX_exec_intra p m (* None *) s1 s2.\n\n  Inductive DEX_exec_return (p:DEX_Program) (m:DEX_Method) : DEX_IntraNormalState -> DEX_ReturnState -> Prop :=\n  | exec_return_normal : forall h s ov,\n     DEX_ReturnStep p m s (h, Normal ov) ->\n     DEX_exec_return p m s (h, Normal ov).\n\n Inductive DEX_IntraStep (p:DEX_Program) : \n    DEX_Method -> DEX_IntraNormalState -> DEX_IntraNormalState + DEX_ReturnState -> Prop :=\n  | IntraStep_res :forall m s ret,\n     DEX_exec_return p m s ret ->\n     DEX_IntraStep p m s (inr _ ret)\n  | IntraStep_intra_step:forall m s1 s2,\n     DEX_exec_intra p m s1 s2 ->\n     DEX_IntraStep p m s1 (inl _ s2).\n \n Definition DEX_IntraStepStar p m s r := TransStep_l (DEX_IntraStep p m) s r.\n\n Definition DEX_IntraStepStar_intra p m s s' := DEX_IntraStepStar p m s (inl _ s').\n\n Definition DEX_BigStep  p m s ret := DEX_IntraStepStar p m s (inr _ ret).\n\n  Lemma DEX_IntraStep_ind_ : \n      forall (p:DEX_Program) \n        (P:DEX_Method->DEX_IntraNormalState->DEX_IntraNormalState+DEX_ReturnState->Prop),\n         (forall m s, P m s (inl _ s)) ->\n         (forall m s r, DEX_exec_return p m s r -> P m s (inr _ r)) ->\n         (forall m s s' , DEX_exec_intra p m s s' -> \n            forall r, DEX_IntraStepStar p m s' r -> P m s' r ->\n            P m s r) ->\n      forall m s r, DEX_IntraStep p m s r -> \n        match r with\n        | inr r' => P m s (inr _ r')\n        | inl s' => forall r', DEX_IntraStepStar p m s' r' -> P m s' r' -> P m s r'\n        end.\n     Proof.\n       intros prg Q H0 Hr Hi Hcr Hc.\n       fix intra 2;intros r Hs;case Hs;clear r Hs;intros.\n       eapply Hr; eauto.\n       apply Hi with s2;trivial. \n     Qed.\n\n  Lemma DEX_IntraStepStar_ind : \n    forall (p:DEX_Program) \n     (P : DEX_Method -> DEX_IntraNormalState -> DEX_IntraNormalState + DEX_ReturnState -> Prop),\n       (forall m s, P m s (inl _ s)) ->\n       (forall m s r, DEX_exec_return p m s r -> P m s (inr _ r)) ->\n       (forall m s s' , DEX_exec_intra p m s s' -> \n          forall r, DEX_IntraStepStar p m s' r -> P m s' r ->\n          P m s r) ->\n    forall m s r, DEX_IntraStepStar p m s r -> P m s r.\n   Proof.\n     intros p Q H0 Hr Hi.\n     fix fixp 4;intros m s' s Ht;case Ht;clear Ht s' s;intros.\n     apply H0.\n     generalize (DEX_IntraStep_ind_ Q H0 Hr Hi H).\n     case r;intros;trivial.\n     apply H1;trivial. \n     constructor.\n     assert (HH:=DEX_IntraStep_ind_ Q H0 Hr Hi H);simpl in HH.\n     apply HH;trivial.   \n     apply fixp;trivial.\n   Qed.\n\nEnd DEX_instr.\n \nEnd DEX_BigStepAnnot.", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/DEX_O/DEX_BigStepAnnot.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.20787667302935955}}
{"text": "Require Import AutoSep Malloc Arrays8.\n\n\nDefinition mainS := SPEC reserving 16\n  PREonly[_] mallocHeap 0.\n\nDefinition writeS := SPEC(\"fd\", \"buf\", \"len\") reserving 4\n  Al len,\n  PRE[V] V \"buf\" =?>8 len * [| (wordToNat (V \"len\") <= len)%nat |]\n  POST[_] V \"buf\" =?>8 len.\n\nOpaque allocated.\n\nDefinition neg1 : W := wones _.\n\nDefinition m := bimport [[ \"sys\"!\"abort\" @ [abortS], \"sys\"!\"printInt\" @ [printIntS],\n                           \"sys\"!\"listen\" @ [listenS], \"sys\"!\"accept\" @ [acceptS],\n                           \"sys\"!\"read\" @ [readS], \"sys\"!\"write\" @ [Sys.writeS],\n                           \"sys\"!\"declare\" @ [declareS], \"sys\"!\"wait\" @ [Sys.waitS],\n                           \"sys\"!\"close\" @ [closeS], \"malloc\"!\"malloc\" @ [mallocS] ]]\n  bmodule \"test\" {{\n    bfunction \"write\"(\"fd\", \"buf\", \"len\") [writeS]\n      Assert [Al len,\n        PRE[V] buffer_splitAt (wordToNat (V \"len\")) (V \"buf\") len\n          * [| (wordToNat (V \"len\") <= len)%nat |]\n        POST[_] buffer_joinAt (wordToNat (V \"len\")) (V \"buf\") len];;\n\n      Call \"sys\"!\"write\"(\"fd\", \"buf\", \"len\")\n      [PRE[_] Emp POST[_] Emp];;\n      Return 0\n    end with bfunctionNoRet \"main\"(\"fdl\", \"fd1\", \"fd2\", \"ind1\", \"ind2\", \"fd\", \"buf\", \"n\") [mainS]\n      \"fdl\" <-- Call \"sys\"!\"listen\"(8080%N)\n      [PREonly[_] mallocHeap 0];;\n\n      \"fd1\" <-- Call \"sys\"!\"accept\"(\"fdl\")\n      [PREonly[_] mallocHeap 0];;\n\n      \"fd2\" <-- Call \"sys\"!\"accept\"(\"fdl\")\n      [PREonly[_] mallocHeap 0];;\n\n      \"buf\" <-- Call \"malloc\"!\"malloc\"(0, 10)\n      [PREonly[_, R] R =?> 10];;\n\n      Note [please_materialize_buffer 10];;\n\n      \"ind1\" <-- Call \"sys\"!\"declare\"(\"fd1\", 0)\n      [PREonly[V] V \"buf\" =?>8 40];;\n\n      \"ind2\" <-- Call \"sys\"!\"declare\"(\"fd2\", 0)\n      [PREonly[V] V \"buf\" =?>8 40];;\n\n      \"n\" <-- Call \"sys\"!\"wait\"(1)\n      [PREonly[V] V \"buf\" =?>8 40];;\n\n      [PREonly[V] V \"buf\" =?>8 40]\n      While (\"n\" <> neg1) {\n        If (\"n\" = \"ind1\") {\n          \"fd\" <- \"fd1\"\n        } else {\n          \"fd\" <- \"fd2\"\n        };;\n\n        \"n\" <-- Call \"sys\"!\"read\"(\"fd\", \"buf\", 40)\n        [PREonly[V] V \"buf\" =?>8 40];;\n\n        If (\"n\" = 0) {\n          Call \"sys\"!\"close\"(\"fd\")\n          [PREonly[V] V \"buf\" =?>8 40]\n        } else {\n          If (\"fd\" = \"fd1\") {\n            \"ind1\" <-- Call \"sys\"!\"declare\"(\"fd1\", 0)\n            [PREonly[V] V \"buf\" =?>8 40]\n          } else {\n            \"ind2\" <-- Call \"sys\"!\"declare\"(\"fd2\", 0)\n            [PREonly[V] V \"buf\" =?>8 40]\n          };;\n\n          If (\"n\" <= 40) {\n            Call \"test\"!\"write\"(\"fd\", \"buf\", \"n\")\n            [PREonly[V] V \"buf\" =?>8 40]\n          } else {\n            Skip\n          }\n        };;\n\n        \"n\" <-- Call \"sys\"!\"wait\"(1)\n        [PREonly[V] V \"buf\" =?>8 40]\n      };;\n\n      Call \"sys\"!\"abort\"()\n      [PREonly[_] [| False |] ]\n    end\n  }}.\n\nDefinition hints : TacPackage.\n  prepare (materialize_buffer, buffer_split_tagged) buffer_join_tagged.\nDefined.\n\nHint Extern 1 (@eq W _ _) => words.\n\nLemma le_40 : forall w : W,\n  w <= natToW 40\n  -> (wordToNat w <= 40)%nat.\n  intros; pre_nomega.\n  rewrite wordToNat_natToWord_idempotent in * by reflexivity; omega.\nQed.\n\nHint Immediate le_40.\n\nLtac t :=\n  try match goal with\n        | [ |- context[evalCond _ Le (RvImm (natToW 40)) _ _] ] =>\n          post; evaluate hints; exists 40\n      end;\n  sep hints; auto.\n\nTheorem ok : moduleOk m.\n  vcgen; abstract t.\nQed.\n", "meta": {"author": "gmalecha", "repo": "bedrock-mirror-shard", "sha": "ea7e5ad56a1d6392468b6823e0457dd44524bca7", "save_path": "github-repos/coq/gmalecha-bedrock-mirror-shard", "path": "github-repos/coq/gmalecha-bedrock-mirror-shard/bedrock-mirror-shard-ea7e5ad56a1d6392468b6823e0457dd44524bca7/platform/tests/Echo2.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213368305399, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20771067807754987}}
{"text": "From caml5 Require Import\n  prelude.\nFrom caml5.lang Require Import\n  notations\n  proofmode.\nFrom caml5.std Require Export\n  base.\n\nSection heapGS.\n  Context `{!heapGS Σ}.\n  Implicit Types l : loc.\n\n  Definition record4_make : val :=\n    λ: \"v₀\" \"v₁\" \"v₂\" \"v₃\",\n      let: \"l\" := AllocN #4 \"v₀\" in\n      \"l\".(1) <- \"v₁\" ;;\n      \"l\".(2) <- \"v₂\" ;;\n      \"l\".(3) <- \"v₃\" ;;\n      \"l\".\n\n  Definition record4_model l dq v₀ v₁ v₂ v₃ : iProp Σ :=\n    l.(0) ↦{dq} v₀ ∗\n    l.(1) ↦{dq} v₁ ∗\n    l.(2) ↦{dq} v₂ ∗\n    l.(3) ↦{dq} v₃.\n\n  #[global] Instance record4_model_timeless l dq v₀ v₁ v₂ v₃ :\n    Timeless (record4_model l dq v₀ v₁ v₂ v₃).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance record4_model_persistent l v₀ v₁ v₂ v₃ :\n    Persistent (record4_model l DfracDiscarded v₀ v₁ v₂ v₃).\n  Proof.\n    apply _.\n  Qed.\n\n  #[global] Instance record4_model_fractional l v₀ v₁ v₂ v₃ :\n    Fractional (λ q, record4_model l (DfracOwn q) v₀ v₁ v₂ v₃).\n  Proof.\n    apply _.\n  Qed.\n  #[global] Instance record4_model_as_fractional l q v₀ v₁ v₂ v₃ :\n    AsFractional (record4_model l (DfracOwn q) v₀ v₁ v₂ v₃) (λ q, record4_model l (DfracOwn q) v₀ v₁ v₂ v₃) q.\n  Proof.\n    split; done || apply _.\n  Qed.\n\n  Lemma record4_model_persist l dq v₀ v₁ v₂ v₃ :\n    record4_model l dq v₀ v₁ v₂ v₃ ==∗\n    record4_model l DfracDiscarded v₀ v₁ v₂ v₃.\n  Proof.\n    iIntros \"(Hv₀ & Hv₁ & Hv₂ & Hv₃)\".\n    iMod (mapsto_persist with \"Hv₀\") as \"$\".\n    iMod (mapsto_persist with \"Hv₁\") as \"$\".\n    iMod (mapsto_persist with \"Hv₂\") as \"$\".\n    iMod (mapsto_persist with \"Hv₃\") as \"$\".\n    done.\n  Qed.\n\n  Lemma record4_model_valid l dq v₀ v₁ v₂ v₃ :\n    record4_model l dq v₀ v₁ v₂ v₃ -∗\n    ⌜✓ dq⌝.\n  Proof.\n    iIntros \"(Hv₀ & Hv₁ & Hv₂ & Hv₃)\". iApply (mapsto_valid with \"Hv₀\").\n  Qed.\n  Lemma record4_model_combine l dq1 v₀1 v₁1 v₂1 v₃1 dq2 v₀2 v₁2 v₂2 v₃2 :\n    record4_model l dq1 v₀1 v₁1 v₂1 v₃1 -∗\n    record4_model l dq2 v₀2 v₁2 v₂2 v₃2 -∗\n      record4_model l (dq1 ⋅ dq2) v₀1 v₁1 v₂1 v₃1 ∗\n      ⌜v₀1 = v₀2 ∧ v₁1 = v₁2 ∧ v₂1 = v₂2 ∧ v₃1 = v₃2⌝.\n  Proof.\n    iIntros \"(Hv₀1 & Hv₁1 & Hv₂1 & Hv₃1) (Hv₀2 & Hv₁2 & Hv₂2 & Hv₃2)\".\n    iDestruct (mapsto_combine with \"Hv₀1 Hv₀2\") as \"(Hv₀ & <-)\".\n    iDestruct (mapsto_combine with \"Hv₁1 Hv₁2\") as \"(Hv₁ & <-)\".\n    iDestruct (mapsto_combine with \"Hv₂1 Hv₂2\") as \"(Hv₂ & <-)\".\n    iDestruct (mapsto_combine with \"Hv₃1 Hv₃2\") as \"(Hv₃ & <-)\".\n    iSplit; last done. iFrame.\n  Qed.\n  Lemma record4_model_valid_2 l dq1 v₀1 v₁1 v₂1 v₃1 dq2 v₀2 v₁2 v₂2 v₃2 :\n    record4_model l dq1 v₀1 v₁1 v₂1 v₃1 -∗\n    record4_model l dq2 v₀2 v₁2 v₂2 v₃2 -∗\n    ⌜✓ (dq1 ⋅ dq2) ∧ v₀1 = v₀2 ∧ v₁1 = v₁2 ∧ v₂1 = v₂2 ∧ v₃1 = v₃2⌝.\n  Proof.\n    iIntros \"Hl1 Hl2\".\n    iDestruct (record4_model_combine with \"Hl1 Hl2\") as \"(Hl & %)\".\n    iDestruct (record4_model_valid with \"Hl\") as %?.\n    done.\n  Qed.\n  Lemma record4_model_agree l dq1 v₀1 v₁1 v₂1 v₃1 dq2 v₀2 v₁2 v₂2 v₃2 :\n    record4_model l dq1 v₀1 v₁1 v₂1 v₃1 -∗\n    record4_model l dq2 v₀2 v₁2 v₂2 v₃2 -∗\n    ⌜v₀1 = v₀2 ∧ v₁1 = v₁2 ∧ v₂1 = v₂2 ∧ v₃1 = v₃2⌝.\n  Proof.\n    iIntros \"Hl1 Hl2\".\n    iDestruct (record4_model_valid_2 with \"Hl1 Hl2\") as %?. naive_solver.\n  Qed.\n  Lemma record4_model_dfrac_ne l1 dq1 v₀1 v₁1 v₂1 v₃1 l2 dq2 v₀2 v₁2 v₂2 v₃2 :\n    ¬ ✓ (dq1 ⋅ dq2) →\n    record4_model l1 dq1 v₀1 v₁1 v₂1 v₃1 -∗\n    record4_model l2 dq2 v₀2 v₁2 v₂2 v₃2 -∗\n    ⌜l1 ≠ l2⌝.\n  Proof.\n    iIntros \"% Hl1 Hl2\" (->).\n    iDestruct (record4_model_valid_2 with \"Hl1 Hl2\") as %?. naive_solver.\n  Qed.\n  Lemma record4_model_ne l1 v₀1 v₁1 v₂1 v₃1 l2 dq2 v₀2 v₁2 v₂2 v₃2 :\n    record4_model l1 (DfracOwn 1) v₀1 v₁1 v₂1 v₃1 -∗\n    record4_model l2 dq2 v₀2 v₁2 v₂2 v₃2 -∗\n    ⌜l1 ≠ l2⌝.\n  Proof.\n    iApply record4_model_dfrac_ne. intros []%exclusive_l. apply _.\n  Qed.\n  Lemma record4_model_exclusive l v₀1 v₁1 v₂1 v₃1 v₀2 v₁2 v₂2 v₃2 :\n    record4_model l (DfracOwn 1) v₀1 v₁1 v₂1 v₃1 -∗\n    record4_model l (DfracOwn 1) v₀2 v₁2 v₂2 v₃2 -∗\n    False.\n  Proof.\n    iIntros \"Hl1 Hl2\".\n    iDestruct (record4_model_ne with \"Hl1 Hl2\") as %?. naive_solver.\n  Qed.\n\n  Lemma record4_dfrac_relax dq l v₀ v₁ v₂ v₃ :\n    ✓ dq →\n    record4_model l (DfracOwn 1) v₀ v₁ v₂ v₃ ==∗\n    record4_model l dq v₀ v₁ v₂ v₃.\n  Proof.\n    iIntros \"% (Hv₀ & Hv₁ & Hv₂ & Hv₃)\".\n    iMod (mapsto_dfrac_relax with \"Hv₀\") as \"Hv₀\"; first done.\n    iMod (mapsto_dfrac_relax with \"Hv₁\") as \"Hv₁\"; first done.\n    iMod (mapsto_dfrac_relax with \"Hv₂\") as \"Hv₂\"; first done.\n    iMod (mapsto_dfrac_relax with \"Hv₃\") as \"Hv₃\"; first done.\n    iFrame. done.\n  Qed.\n\n  Lemma record4_make_spec v₀ v₁ v₂ v₃ :\n    {{{ True }}}\n      record4_make v₀ v₁ v₂ v₃\n    {{{ l, RET #l; record4_model l (DfracOwn 1) v₀ v₁ v₂ v₃ }}}.\n  Proof.\n    iIntros \"%Φ _ HΦ\".\n    wp_rec. wp_pures.\n    wp_apply (wp_allocN with \"[//]\"); first done. iIntros \"%l (Hl & Hmeta & _)\". rewrite loc_add_0.\n    wp_pures.\n    iDestruct (array_cons with \"Hl\") as \"(Hv₀ & Hl)\".\n    iEval (setoid_rewrite <- loc_add_0) in \"Hv₀\".\n    iDestruct (array_cons with \"Hl\") as \"(Hv₁ & Hl)\".\n    iDestruct (array_cons with \"Hl\") as \"(Hv₂ & Hl)\".\n    rewrite loc_add_assoc Z.add_1_r -Z.two_succ.\n    iDestruct (array_singleton with \"Hl\") as \"Hv₃\".\n    rewrite loc_add_assoc Z.add_1_r. assert (Z.succ 2 = 3)%Z as -> by lia.\n    wp_store. wp_store. wp_store.\n    iApply \"HΦ\". iFrame. done.\n  Qed.\n\n  Lemma record4_get0_spec l dq v₀ v₁ v₂ v₃ :\n    {{{ record4_model l dq v₀ v₁ v₂ v₃ }}}\n      !#l.(0)\n    {{{ RET v₀; record4_model l dq v₀ v₁ v₂ v₃ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂ & Hv₃) HΦ\".\n    wp_load.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂ $Hv₃]\").\n  Qed.\n  Lemma record4_get1_spec l dq v₀ v₁ v₂ v₃ :\n    {{{ record4_model l dq v₀ v₁ v₂ v₃ }}}\n      !#l.(1)\n    {{{ RET v₁; record4_model l dq v₀ v₁ v₂ v₃ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂ & Hv₃) HΦ\".\n    wp_load.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂ $Hv₃]\").\n  Qed.\n  Lemma record4_get2_spec l dq v₀ v₁ v₂ v₃ :\n    {{{ record4_model l dq v₀ v₁ v₂ v₃ }}}\n      !#l.(2)\n    {{{ RET v₂; record4_model l dq v₀ v₁ v₂ v₃ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂ & Hv₃) HΦ\".\n    wp_load.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂ $Hv₃]\").\n  Qed.\n  Lemma record4_get3_spec l dq v₀ v₁ v₂ v₃ :\n    {{{ record4_model l dq v₀ v₁ v₂ v₃ }}}\n      !#l.(3)\n    {{{ RET v₃; record4_model l dq v₀ v₁ v₂ v₃ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂ & Hv₃) HΦ\".\n    wp_load.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂ $Hv₃]\").\n  Qed.\n\n  Lemma record4_set0_spec l v₀ v₁ v₂ v₃ v :\n    {{{ record4_model l (DfracOwn 1) v₀ v₁ v₂ v₃ }}}\n      #l.(0) <- v\n    {{{ RET #(); record4_model l (DfracOwn 1) v v₁ v₂ v₃ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂ & Hv₃) HΦ\".\n    wp_store.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂ $Hv₃]\").\n  Qed.\n  Lemma record4_set1_spec l v₀ v₁ v₂ v₃ v :\n    {{{ record4_model l (DfracOwn 1) v₀ v₁ v₂ v₃ }}}\n      #l.(1) <- v\n    {{{ RET #(); record4_model l (DfracOwn 1) v₀ v v₂ v₃ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂ & Hv₃) HΦ\".\n    wp_store.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂ $Hv₃]\").\n  Qed.\n  Lemma record4_set2_spec l v₀ v₁ v₂ v₃ v :\n    {{{ record4_model l (DfracOwn 1) v₀ v₁ v₂ v₃ }}}\n      #l.(2) <- v\n    {{{ RET #(); record4_model l (DfracOwn 1) v₀ v₁ v v₃ }}}.\n  Proof.\n    iIntros \"%Φ (Hv₀ & Hv₁ & Hv₂ & Hv₃) HΦ\".\n    wp_store.\n    iApply (\"HΦ\" with \"[$Hv₀ $Hv₁ $Hv₂ $Hv₃]\").\n  Qed.\nEnd heapGS.\n\n#[global] Opaque record4_make.\n\n#[global] Opaque record4_model.\n", "meta": {"author": "clef-men", "repo": "caml5", "sha": "0de06d5792138eb17877ed1536a0401b7a322ee2", "save_path": "github-repos/coq/clef-men-caml5", "path": "github-repos/coq/clef-men-caml5/caml5-0de06d5792138eb17877ed1536a0401b7a322ee2/theories/std/record4.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.20771067212897362}}
{"text": "(*\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\nRequire Import String.\nRequire Import List.\nRequire Import Arith.\nRequire Import Program.\nRequire Import EquivDec.\nRequire Import Morphisms.\nRequire Import Utils.\nRequire Import DataSystem.\nRequire Import DNNRCSystem.\nRequire Import tDNNRC.\n\nSection tDNNRCSub.\n\n  Context {m:basic_model}.\n\n  Section typ.\n    Context (τconstants:tdbindings).\n      \n    Inductive dnnrc_base_type_sub {A plug_type:Set}\n              {plug:AlgPlug plug_type} {tplug: TAlgPlug} :\n      tdbindings -> @dnnrc_base _ A plug_type -> drtype -> Prop :=\n    | TDNNRCGetConstant {τout} tenv s :\n        forall (a:A),\n          tdot τconstants s = Some τout ->\n          dnnrc_base_type_sub tenv (DNNRCGetConstant a s) τout\n    | TDNNRCVar {τ} tenv v :\n        forall (a:A),\n          lookup equiv_dec tenv v = Some τ ->\n          dnnrc_base_type_sub tenv (DNNRCVar a v) τ\n    | TDNNRCConst {τ} tenv c :\n        forall (a:A),\n          data_type (normalize_data brand_relation_brands c) τ ->\n          dnnrc_base_type_sub tenv (DNNRCConst a c) (Tlocal τ)\n    | TDNNRCBinop  {τ₁ τ₂ τ} tenv b e1 e2 :\n        forall (a:A),\n          binary_op_type b τ₁ τ₂ τ ->\n          dnnrc_base_type_sub tenv e1 (Tlocal τ₁) ->\n          dnnrc_base_type_sub tenv e2 (Tlocal τ₂) ->\n          dnnrc_base_type_sub tenv (DNNRCBinop a b e1 e2) (Tlocal τ)\n    | TDNNRCUnop {τ₁ τ} tenv u e1 :\n        forall (a:A), \n          unary_op_type u τ₁ τ ->\n          dnnrc_base_type_sub tenv e1 (Tlocal τ₁) ->\n          dnnrc_base_type_sub tenv (DNNRCUnop a u e1) (Tlocal τ)\n    | TDNNRCLet {τ₁ τ₂} v tenv e1 e2 :\n        forall (a:A), \n          dnnrc_base_type_sub tenv e1 τ₁ ->\n          dnnrc_base_type_sub ((v,τ₁)::tenv) e2 τ₂ ->\n          dnnrc_base_type_sub tenv (DNNRCLet a v e1 e2) τ₂\n    | TDNRCForLocal {τ₁ τ₂} v tenv e1 e2 :\n        forall (a:A),\n          dnnrc_base_type_sub tenv e1 (Tlocal (Coll τ₁)) ->\n          dnnrc_base_type_sub ((v,(Tlocal τ₁))::tenv) e2 (Tlocal τ₂) ->\n          dnnrc_base_type_sub tenv (DNNRCFor a v e1 e2) (Tlocal (Coll τ₂))\n    | TDNRCForDist {τ₁ τ₂} v tenv e1 e2 :\n        forall (a:A),\n          dnnrc_base_type_sub tenv e1 (Tdistr τ₁) ->\n          dnnrc_base_type_sub ((v,(Tlocal τ₁))::tenv) e2 (Tlocal τ₂) ->\n          dnnrc_base_type_sub tenv (DNNRCFor a v e1 e2) (Tdistr τ₂)                      \n    | TDNRCIf {τ} tenv e1 e2 e3 :\n        forall (a:A), \n          dnnrc_base_type_sub tenv e1 (Tlocal Bool) ->\n          dnnrc_base_type_sub tenv e2 τ ->\n          dnnrc_base_type_sub tenv e3 τ ->\n          dnnrc_base_type_sub tenv (DNNRCIf a e1 e2 e3) τ\n    | TDNNRCEither {τ τl τr} tenv ed xl el xr er :\n        forall (a:A), \n          dnnrc_base_type_sub tenv ed (Tlocal (Either τl τr)) ->\n          dnnrc_base_type_sub ((xl,(Tlocal τl))::tenv) el τ ->\n          dnnrc_base_type_sub ((xr,(Tlocal τr))::tenv) er τ ->\n          dnnrc_base_type_sub tenv (DNNRCEither a ed xl el xr er) τ\n    | TDNNRCCollect {τ} tenv e :\n        forall (a:A),\n          dnnrc_base_type_sub tenv e (Tdistr τ) ->\n          dnnrc_base_type_sub tenv (DNNRCCollect a e) (Tlocal (Coll τ))\n    | TDNNRCDispatch {τ} tenv e :\n        forall (a:A),\n          dnnrc_base_type_sub tenv e (Tlocal (Coll τ)) ->\n          dnnrc_base_type_sub tenv (DNNRCDispatch a e) (Tdistr τ)\n    (* Note: algebra 'plugged' expression is only well typed within distributed\n         NNNRC if it returns a collection *)\n    | TDNNRCAlg {τout} tenv tbindings op nl :\n        forall (a:A),\n          Forall2 (fun n τ => fst n = fst τ\n                              /\\ dnnrc_base_type_sub tenv (snd n) (Tdistr (snd τ)))\n                  nl tbindings ->\n          plug_typing op tbindings (Coll τout) -> \n          dnnrc_base_type_sub tenv (DNNRCAlg a op nl) (Tdistr τout)\n    | TDNNRCSubsumption {τenv τout} τenv' τout' e:\n        tdbindings_sub τenv' τenv ->\n        drtype_sub τout τout' ->\n        dnnrc_base_type_sub τenv e τout ->\n        dnnrc_base_type_sub τenv' e τout'\n    .\n\n    Global Instance dnnrc_base_type_sub_proper {A plug_type:Set} {plug:AlgPlug plug_type} {tplug: TAlgPlug} :\n      Proper (tdbindings_sub --> eq ==> drtype_sub ==> impl) (dnnrc_base_type_sub (A:=A)).\n    Proof.\n      unfold Proper, respectful, flip, impl; intros.\n      subst.\n      eapply TDNNRCSubsumption; eauto.\n    Qed.\n    \n    Global Instance dbindings_type_proper :\n      Proper (eq ==> tdbindings_sub ==> impl) dbindings_type.\n    Proof.\n      unfold Proper, respectful, flip, impl, tdbindings_sub, dbindings_type; intros.\n      subst.\n      revert y y0 H0 H1.\n      induction x0; intros x y0 F1 F2\n      ; invcs F1; invcs F2; trivial.\n      destruct a; destruct y; destruct x1; intuition; simpl in *; subst.\n      rewrite H0 in H2.\n      auto.\n    Qed.    \n\n  End typ.\n\n  Section lift.\n    \n    Lemma dnnrc_base_type_to_dnnrc_base_type_sub {A} (plug_type:Set) (plug:AlgPlug plug_type) {tplug:TAlgPlug} {τc} {τ} (tenv:tdbindings) (e:@dnnrc_base _ A plug_type) :\n      dnnrc_base_type τc tenv e τ ->\n      dnnrc_base_type_sub τc tenv e τ.\n    Proof.\n      Hint Constructors dnnrc_base_type_sub : qcert.\n      revert tenv τ.\n      induction e; simpl; intros tenv τ dt; invcs dt; qeauto.\n      - econstructor; try eassumption.\n        revert H5.\n        apply Forall2_incl.\n        rewrite Forall_forall in H.\n        intros ? ? inn1 inn2 [eqq1 eqq2].\n        auto.\n    Qed.\n    \n  End lift.\n  \n\nEnd tDNNRCSub.\n\n", "meta": {"author": "querycert", "repo": "qcert", "sha": "13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998", "save_path": "github-repos/coq/querycert-qcert", "path": "github-repos/coq/querycert-qcert/qcert-13bc4e8e4ef5d7edc225bca0fb3b920fccdcb998/compiler/core/tDNNRC/Typing/tDNNRCSub.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2077106721289736}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Rewriter.Language.Language.\nRequire Import Crypto.Language.API.\nRequire Import Rewriter.Language.Wf.\nRequire Import Crypto.Language.WfExtra.\nRequire Import Crypto.Rewriter.AllTacticsExtra.\nRequire Import Crypto.Rewriter.RulesProofs.\n\nModule Compilers.\n  Import Language.Compilers.\n  Import Language.API.Compilers.\n  Import Language.Wf.Compilers.\n  Import Language.WfExtra.Compilers.\n  Import Rewriter.AllTacticsExtra.Compilers.RewriteRules.GoalType.\n  Import Rewriter.AllTactics.Compilers.RewriteRules.Tactic.\n  Import Compilers.Classes.\n\n  Module Import RewriteRules.\n    Section __.\n      Definition VerifiedRewriterUnfoldValueBarrier : VerifiedRewriter_with_args false false true unfold_value_barrier_rewrite_rules_proofs.\n      Proof using All. make_rewriter. Defined.\n\n      Definition default_opts := Eval hnf in @default_opts VerifiedRewriterUnfoldValueBarrier.\n      Let optsT := Eval hnf in optsT VerifiedRewriterUnfoldValueBarrier.\n\n      Definition RewriteUnfoldValueBarrier (opts : optsT) {t : API.type} := Eval hnf in @Rewrite VerifiedRewriterUnfoldValueBarrier opts t.\n\n      Lemma Wf_RewriteUnfoldValueBarrier opts {t} e (Hwf : Wf e) : Wf (@RewriteUnfoldValueBarrier opts t e).\n      Proof. now apply VerifiedRewriterUnfoldValueBarrier. Qed.\n\n      Lemma Interp_RewriteUnfoldValueBarrier opts {t} e (Hwf : Wf e) : API.Interp (@RewriteUnfoldValueBarrier opts t e) == API.Interp e.\n      Proof. now apply VerifiedRewriterUnfoldValueBarrier. Qed.\n    End __.\n  End RewriteRules.\n\n  Module Export Hints.\n    Hint Resolve Wf_RewriteUnfoldValueBarrier : wf wf_extra.\n    Hint Opaque RewriteUnfoldValueBarrier : wf wf_extra interp interp_extra rewrite.\n    Hint Rewrite @Interp_RewriteUnfoldValueBarrier : interp interp_extra.\n  End Hints.\nEnd Compilers.\n", "meta": {"author": "dip-proto", "repo": "fiat-crypto", "sha": "fc3a9280c51f413943c167cc9292e953b8e42c02", "save_path": "github-repos/coq/dip-proto-fiat-crypto", "path": "github-repos/coq/dip-proto-fiat-crypto/fiat-crypto-fc3a9280c51f413943c167cc9292e953b8e42c02/src/Rewriter/Passes/UnfoldValueBarrier.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20771067212897354}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Translation from Mach to ARM. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Op.\nRequire Import Locations.\nRequire Import Mach.\nRequire Import Asm.\nRequire Import Compopts.\n\nOpen Local Scope string_scope.\nOpen Local Scope error_monad_scope.\n\n(** Extracting integer or float registers. *)\n\nDefinition ireg_of (r: mreg) : res ireg :=\n  match preg_of r with IR mr => OK mr | _ => Error(msg \"Asmgen.ireg_of\") end.\n\nDefinition freg_of (r: mreg) : res freg :=\n  match preg_of r with FR mr => OK mr | _ => Error(msg \"Asmgen.freg_of\") end.\n\n(** Recognition of integer immediate arguments for arithmetic operations.\n- ARM: immediates are 8-bit quantities zero-extended and rotated right\n  by 0, 2, 4, ... 30 bits.  In other words, [n] is an immediate iff\n  [rotate-left(n, p)] is between 0 and 255 for some [p = 0, 2, 4, ..., 30].\n- Thumb: immediates are 8-bit quantities zero-extended and shifted left\n  by 0, 1, ..., 31 bits.  In other words, [n] is an immediate if\n  all bits are 0 except a run of 8 adjacent bits.  In addition,\n  [00XY00XY] and [XY00XY00] and [XYXYXYXY] are immediates for\n  a given [XY] 8-bit constant.\n*)\n\nFixpoint is_immed_arith_arm (n: nat) (x: int) {struct n}: bool :=\n  match n with\n  | Datatypes.O => false\n  | Datatypes.S n =>\n      Int.eq x (Int.and x (Int.repr 255)) ||\n      is_immed_arith_arm n (Int.rol x (Int.repr 2))\n  end.\n\nFixpoint is_immed_arith_thumb (n: nat) (x: int) {struct n}: bool :=\n  match n with\n  | Datatypes.O => true\n  | Datatypes.S n =>\n      Int.eq x (Int.and x (Int.repr 255)) ||\n      (Int.eq (Int.and x Int.one) Int.zero\n       && is_immed_arith_thumb n (Int.shru x Int.one))\n  end.\n\nDefinition is_immed_arith_thumb_special (x: int): bool :=\n  let l1 := Int.and x (Int.repr 255) in\n  let l2 := Int.shl l1 (Int.repr 8) in\n  let l3 := Int.shl l2 (Int.repr 8) in\n  let l4 := Int.shl l3 (Int.repr 8) in\n  let l13 := Int.or l1 l3 in\n  let l24 := Int.or l2 l4 in\n  Int.eq x l13 || Int.eq x l24 || Int.eq x (Int.or l13 l24).\n\nDefinition is_immed_arith (x: int): bool :=\n  if thumb tt\n  then is_immed_arith_thumb 24%nat x || is_immed_arith_thumb_special x\n  else is_immed_arith_arm 16%nat x.\n\n(** Recognition of integer immediate arguments for indexed memory accesses.\n- For 32-bit integers, immediate offsets are [(-2^12,2^12)] for ARM classic\n  and [(-2^8,2^12)] for Thumb2.\n- For 8- and 16-bit integers, immediate offsets are [(-2^8,2^8)].\n- For 32- and 64-bit integers, immediate offsets are multiples of 4\n  in [(-2^10,2^10)].\n\nFor all 3 kinds of accesses, we provide not a recognizer but a synthesizer:\na function taking an arbitrary offset [n] and returning a valid offset [n']\nthat contains as many useful bits of [n] as possible, so that the\ncomputation of the remainder [n - n'] is as simple as possible.\nIn particular, if [n] is a representable immediate argument, we should have\n[n' = n].\n*)\n\nDefinition mk_immed_mem_word (x: int): int :=\n  if Int.ltu x Int.zero then\n    Int.neg (Int.zero_ext (if thumb tt then 8 else 12) (Int.neg x))\n  else\n    Int.zero_ext 12 x.\n\nDefinition mk_immed_mem_small (x: int): int :=\n  if Int.ltu x Int.zero then\n    Int.neg (Int.zero_ext 8 (Int.neg x))\n  else\n    Int.zero_ext 8 x.\n\nDefinition mk_immed_mem_float (x: int): int :=\n  let x := Int.and x (Int.repr (-4)) in   (**r mask low 2 bits off *)\n  if Int.ltu x Int.zero then\n    Int.neg (Int.zero_ext 10 (Int.neg x))\n  else\n    Int.zero_ext 10 x.\n\n(** Decomposition of a 32-bit integer into a list of immediate arguments,\n    whose sum or \"or\" or \"xor\" equals the integer. *)\n\nFixpoint decompose_int_arm (N: nat) (n p: int) : list int :=\n  match N with\n  | Datatypes.O =>\n      if Int.eq n Int.zero then nil else n :: nil\n  | Datatypes.S M =>\n      if Int.eq (Int.and n (Int.shl (Int.repr 3) p)) Int.zero then\n        decompose_int_arm M n (Int.add p (Int.repr 2))\n      else\n        let m := Int.shl (Int.repr 255) p in\n        Int.and n m ::\n        decompose_int_arm M (Int.and n (Int.not m)) (Int.add p (Int.repr 2))\n  end.\n\nFixpoint decompose_int_thumb (N: nat) (n p: int) : list int :=\n  match N with\n  | Datatypes.O =>\n      if Int.eq n Int.zero then nil else n :: nil\n  | Datatypes.S M =>\n      if Int.eq (Int.and n (Int.shl Int.one p)) Int.zero then\n        decompose_int_thumb M n (Int.add p Int.one)\n      else\n        let m := Int.shl (Int.repr 255) p in\n        Int.and n m ::\n        decompose_int_thumb M (Int.and n (Int.not m)) (Int.add p Int.one)\n  end.\n\nDefinition decompose_int_base (n: int): list int :=\n  if thumb tt\n  then if is_immed_arith_thumb_special n\n       then n :: nil\n       else decompose_int_thumb 24%nat n Int.zero\n  else decompose_int_arm 12%nat n Int.zero.\n\nDefinition decompose_int (n: int) : list int :=\n  match decompose_int_base n with\n  | nil => Int.zero :: nil\n  | l   => l\n  end.\n\nDefinition iterate_op (op1 op2: shift_op -> instruction) (l: list int) (k: code) :=\n  match l with\n  | nil =>\n      op1 (SOimm Int.zero) :: k                 (**r should never happen *)\n  | i :: l' =>\n      op1 (SOimm i) :: map (fun i => op2 (SOimm i)) l' ++ k\n  end.\n\n(** Smart constructors for integer immediate arguments. *)\n\nDefinition loadimm_thumb (r: ireg) (n: int) (k: code) :=\n  let hi := Int.shru n (Int.repr 16) in\n  if Int.eq hi Int.zero\n  then Pmovw r n :: k\n  else Pmovw r (Int.zero_ext 16 n) :: Pmovt r hi :: k.\n\nDefinition loadimm (r: ireg) (n: int) (k: code) :=\n  let d1 := decompose_int n in\n  let d2 := decompose_int (Int.not n) in\n  let l1 := List.length d1 in\n  let l2 := List.length d2 in\n  if NPeano.leb l1 1%nat then\n    Pmov r (SOimm n) :: k\n  else if NPeano.leb l2 1%nat then\n    Pmvn r (SOimm (Int.not n)) :: k\n  else if thumb tt then\n    loadimm_thumb r n k\n  else if NPeano.leb l1 l2 then\n    iterate_op (Pmov r) (Porr r r) d1 k\n  else\n    iterate_op (Pmvn r) (Pbic r r) d2 k.\n\nDefinition addimm (r1 r2: ireg) (n: int) (k: code) :=\n  if Int.ltu (Int.repr (-256)) n then\n    Psub r1 r2 (SOimm (Int.neg n)) :: k\n  else\n   (let d1 := decompose_int n in\n    let d2 := decompose_int (Int.neg n) in\n    if NPeano.leb (List.length d1) (List.length d2)\n    then iterate_op (Padd r1 r2) (Padd r1 r1) d1 k\n    else iterate_op (Psub r1 r2) (Psub r1 r1) d2 k).\n\nDefinition rsubimm (r1 r2: ireg) (n: int) (k: code) :=\n  iterate_op (Prsb r1 r2) (Padd r1 r1) (decompose_int n) k.\n\nDefinition andimm (r1 r2: ireg) (n: int) (k: code) :=\n  if is_immed_arith n \n  then Pand r1 r2 (SOimm n) :: k\n  else iterate_op (Pbic r1 r2) (Pbic r1 r1) (decompose_int (Int.not n)) k.\n\nDefinition orimm  (r1 r2: ireg) (n: int) (k: code) :=\n  iterate_op (Porr r1 r2) (Porr r1 r1) (decompose_int n) k.\n\nDefinition xorimm  (r1 r2: ireg) (n: int) (k: code) :=\n  iterate_op (Peor r1 r2) (Peor r1 r1) (decompose_int n) k.\n\n(** Translation of a shift immediate operation (type [Op.shift]) *)\n\nDefinition transl_shift (s: shift) (r: ireg) : shift_op :=\n  match s with\n  | Slsl n => SOlsl r (s_amount n)\n  | Slsr n => SOlsr r (s_amount n)\n  | Sasr n => SOasr r (s_amount n)\n  | Sror n => SOror r (s_amount n)\n  end.\n\n(** Translation of a condition.  Prepends to [k] the instructions\n  that evaluate the condition and leave its boolean result in one of\n  the bits of the condition register.  The bit in question is\n  determined by the [crbit_for_cond] function. *)\n\nDefinition transl_cond\n              (cond: condition) (args: list mreg) (k: code) :=\n  match cond, args with\n  | Ccomp c, a1 :: a2 :: nil =>\n      do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Pcmp r1(SOreg r2) :: k)\n  | Ccompu c, a1 :: a2 :: nil =>\n      do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Pcmp r1 (SOreg r2) :: k)\n  | Ccompshift c s, a1 :: a2 :: nil =>\n      do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Pcmp r1 (transl_shift s r2) :: k)\n  | Ccompushift c s, a1 :: a2 :: nil =>\n      do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Pcmp r1 (transl_shift s r2) :: k)\n  | Ccompimm c n, a1 :: nil =>\n      do r1 <- ireg_of a1;\n      OK (if is_immed_arith n then\n            Pcmp r1 (SOimm n) :: k\n          else\n            loadimm IR14 n (Pcmp r1 (SOreg IR14) :: k))\n  | Ccompuimm c n, a1 :: nil =>\n      do r1 <- ireg_of a1;\n      OK (if is_immed_arith n then\n            Pcmp r1 (SOimm n) :: k\n          else\n            loadimm IR14 n (Pcmp r1 (SOreg IR14) :: k))\n  | Ccompf cmp, a1 :: a2 :: nil =>\n      do r1 <- freg_of a1; do r2 <- freg_of a2;\n      OK (Pfcmpd r1 r2 :: k)\n  | Cnotcompf cmp, a1 :: a2 :: nil =>\n      do r1 <- freg_of a1; do r2 <- freg_of a2;\n      OK (Pfcmpd r1 r2 :: k)\n  | Ccompfzero cmp, a1 :: nil =>\n      do r1 <- freg_of a1;\n      OK (Pfcmpzd r1 :: k)\n  | Cnotcompfzero cmp, a1 :: nil =>\n      do r1 <- freg_of a1;\n      OK (Pfcmpzd r1 :: k)\n  | Ccompfs cmp, a1 :: a2 :: nil =>\n      do r1 <- freg_of a1; do r2 <- freg_of a2;\n      OK (Pfcmps r1 r2 :: k)\n  | Cnotcompfs cmp, a1 :: a2 :: nil =>\n      do r1 <- freg_of a1; do r2 <- freg_of a2;\n      OK (Pfcmps r1 r2 :: k)\n  | Ccompfszero cmp, a1 :: nil =>\n      do r1 <- freg_of a1;\n      OK (Pfcmpzs r1 :: k)\n  | Cnotcompfszero cmp, a1 :: nil =>\n      do r1 <- freg_of a1;\n      OK (Pfcmpzs r1 :: k)\n  | _, _ =>\n      Error(msg \"Asmgen.transl_cond\")\n  end.\n\nDefinition cond_for_signed_cmp (cmp: comparison) :=\n  match cmp with\n  | Ceq => TCeq\n  | Cne => TCne\n  | Clt => TClt\n  | Cle => TCle\n  | Cgt => TCgt\n  | Cge => TCge\n  end.\n\nDefinition cond_for_unsigned_cmp (cmp: comparison) :=\n  match cmp with\n  | Ceq => TCeq\n  | Cne => TCne\n  | Clt => TClo\n  | Cle => TCls\n  | Cgt => TChi\n  | Cge => TChs\n  end.\n\nDefinition cond_for_float_cmp (cmp: comparison) :=\n  match cmp with\n  | Ceq => TCeq\n  | Cne => TCne\n  | Clt => TCmi\n  | Cle => TCls\n  | Cgt => TCgt\n  | Cge => TCge\n  end.\n\nDefinition cond_for_float_not_cmp (cmp: comparison) :=\n  match cmp with\n  | Ceq => TCne\n  | Cne => TCeq\n  | Clt => TCpl\n  | Cle => TChi\n  | Cgt => TCle\n  | Cge => TClt\n  end.\n\nDefinition cond_for_cond (cond: condition) :=\n  match cond with\n  | Ccomp cmp => cond_for_signed_cmp cmp\n  | Ccompu cmp => cond_for_unsigned_cmp cmp\n  | Ccompshift cmp s => cond_for_signed_cmp cmp\n  | Ccompushift cmp s => cond_for_unsigned_cmp cmp\n  | Ccompimm cmp n => cond_for_signed_cmp cmp\n  | Ccompuimm cmp n => cond_for_unsigned_cmp cmp\n  | Ccompf cmp => cond_for_float_cmp cmp\n  | Cnotcompf cmp => cond_for_float_not_cmp cmp\n  | Ccompfzero cmp => cond_for_float_cmp cmp\n  | Cnotcompfzero cmp => cond_for_float_not_cmp cmp\n  | Ccompfs cmp => cond_for_float_cmp cmp\n  | Cnotcompfs cmp => cond_for_float_not_cmp cmp\n  | Ccompfszero cmp => cond_for_float_cmp cmp\n  | Cnotcompfszero cmp => cond_for_float_not_cmp cmp\n  end.\n\n(** Translation of the arithmetic operation [r <- op(args)].\n  The corresponding instructions are prepended to [k]. *)\n\nDefinition transl_op\n              (op: operation) (args: list mreg) (res: mreg) (k: code) :=\n  match op, args with\n  | Omove, a1 :: nil =>\n      match preg_of res, preg_of a1 with\n      | IR r, IR a => OK (Pmov r (SOreg a) :: k)\n      | FR r, FR a => OK (Pfcpyd r a :: k)\n      |  _  ,  _   => Error(msg \"Asmgen.Omove\")\n      end\n  | Ointconst n, nil =>\n      do r <- ireg_of res;\n      OK (loadimm r n k)\n  | Ofloatconst f, nil =>\n      do r <- freg_of res;\n      OK (Pflid r f :: k)\n  | Osingleconst f, nil =>\n      do r <- freg_of res;\n      OK (Pflis r f :: k)\n  | Oaddrsymbol s ofs, nil =>\n      do r <- ireg_of res;\n      OK (Ploadsymbol r s ofs :: k)\n  | Oaddrstack n, nil =>\n      do r <- ireg_of res;\n      OK (addimm r IR13 n k)\n  | Ocast8signed, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1;\n      OK (if thumb tt then\n            Psbfx r r1 Int.zero (Int.repr 8) :: k\n          else\n            Pmov r (SOlsl r1 (Int.repr 24)) ::\n            Pmov r (SOasr r (Int.repr 24)) :: k)\n  | Ocast16signed, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1;\n      OK (if thumb tt then\n            Psbfx r r1 Int.zero (Int.repr 16) :: k\n          else\n            Pmov r (SOlsl r1 (Int.repr 16)) ::\n            Pmov r (SOasr r (Int.repr 16)) :: k)\n  | Oadd, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Padd r r1 (SOreg r2) :: k)\n  | Oaddshift s, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Padd r r1 (transl_shift s r2) :: k)\n  | Oaddimm n, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1;\n      OK (addimm r r1 n k)\n  | Osub, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Psub r r1 (SOreg r2) :: k)\n  | Osubshift s, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Psub r r1 (transl_shift s r2) :: k)\n  | Orsubshift s, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Prsb r r1 (transl_shift s r2) :: k)\n  | Orsubimm n, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1;\n      OK (rsubimm r r1 n k)\n  | Omul, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Pmul r r1 r2 :: k)\n  | Omla, a1 :: a2 :: a3 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; \n      do r2 <- ireg_of a2; do r3 <- ireg_of a3;\n      OK (Pmla r r1 r2 r3 :: k)\n  | Omulhs, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Psmull IR14 r r1 r2 :: k)\n  | Omulhu, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Pumull IR14 r r1 r2 :: k)\n  | Odiv, a1 :: a2 :: nil =>\n      assertion (mreg_eq res R0);\n      assertion (mreg_eq a1 R0);\n      assertion (mreg_eq a2 R1);\n      OK (Psdiv :: k)\n  | Odivu, a1 :: a2 :: nil =>\n      assertion (mreg_eq res R0);\n      assertion (mreg_eq a1 R0);\n      assertion (mreg_eq a2 R1);\n      OK (Pudiv :: k)\n  | Oand, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Pand r r1 (SOreg r2) :: k)\n  | Oandshift s, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Pand r r1 (transl_shift s r2) :: k)\n  | Oandimm n, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1;\n      OK (andimm r r1 n k)\n  | Oor, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Porr r r1 (SOreg r2) :: k)\n  | Oorshift s, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Porr r r1 (transl_shift s r2) :: k)\n  | Oorimm n, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1;\n      OK (orimm r r1 n k)\n  | Oxor, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Peor r r1 (SOreg r2) :: k)\n  | Oxorshift s, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Peor r r1 (transl_shift s r2) :: k)\n  | Oxorimm n, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1;\n      OK (xorimm r r1 n k)\n  | Obic, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Pbic r r1 (SOreg r2) :: k)\n  | Obicshift s, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Pbic r r1 (transl_shift s r2) :: k)\n  | Onot, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1;\n      OK (Pmvn r (SOreg r1) :: k)\n  | Onotshift s, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1;\n      OK (Pmvn r (transl_shift s r1) :: k)\n  | Oshl, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Plsl r r1 r2 :: k)\n  | Oshr, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Pasr r r1 r2 :: k)\n  | Oshru, a1 :: a2 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n      OK (Plsr r r1 r2 :: k)\n  | Oshift s, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1;\n      OK (Pmov r (transl_shift s r1) :: k)\n  | Oshrximm n, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- ireg_of a1;\n      if Int.eq n Int.zero then\n        OK (Pmov r (SOreg r1) :: k)\n      else\n        OK (Pmov IR14 (SOasr r1 (Int.repr 31)) ::\n            Padd IR14 r1 (SOlsr IR14 (Int.sub Int.iwordsize n)) ::\n            Pmov r (SOasr IR14 n) :: k)\n  | Onegf, a1 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1;\n      OK (Pfnegd r r1 :: k)\n  | Oabsf, a1 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1;\n      OK (Pfabsd r r1 :: k)\n  | Oaddf, a1 :: a2 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1; do r2 <- freg_of a2;\n      OK (Pfaddd r r1 r2 :: k)\n  | Osubf, a1 :: a2 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1; do r2 <- freg_of a2;\n      OK (Pfsubd r r1 r2 :: k)\n  | Omulf, a1 :: a2 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1; do r2 <- freg_of a2;\n      OK (Pfmuld r r1 r2 :: k)\n  | Odivf, a1 :: a2 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1; do r2 <- freg_of a2;\n      OK (Pfdivd r r1 r2 :: k)\n  | Onegfs, a1 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1;\n      OK (Pfnegs r r1 :: k)\n  | Oabsfs, a1 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1;\n      OK (Pfabss r r1 :: k)\n  | Oaddfs, a1 :: a2 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1; do r2 <- freg_of a2;\n      OK (Pfadds r r1 r2 :: k)\n  | Osubfs, a1 :: a2 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1; do r2 <- freg_of a2;\n      OK (Pfsubs r r1 r2 :: k)\n  | Omulfs, a1 :: a2 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1; do r2 <- freg_of a2;\n      OK (Pfmuls r r1 r2 :: k)\n  | Odivfs, a1 :: a2 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1; do r2 <- freg_of a2;\n      OK (Pfdivs r r1 r2 :: k)\n  | Osingleoffloat, a1 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1;\n      OK (Pfcvtsd r r1 :: k)\n  | Ofloatofsingle, a1 :: nil =>\n      do r <- freg_of res; do r1 <- freg_of a1;\n      OK (Pfcvtds r r1 :: k)\n  | Ointoffloat, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- freg_of a1;\n      OK (Pftosizd r r1 :: k)\n  | Ointuoffloat, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- freg_of a1;\n      OK (Pftouizd r r1 :: k)\n  | Ofloatofint, a1 :: nil =>\n      do r <- freg_of res; do r1 <- ireg_of a1;\n      OK (Pfsitod r r1 :: k)\n  | Ofloatofintu, a1 :: nil =>\n      do r <- freg_of res; do r1 <- ireg_of a1;\n      OK (Pfuitod r r1 :: k)\n  | Ointofsingle, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- freg_of a1;\n      OK (Pftosizs r r1 :: k)\n  | Ointuofsingle, a1 :: nil =>\n      do r <- ireg_of res; do r1 <- freg_of a1;\n      OK (Pftouizs r r1 :: k)\n  | Osingleofint, a1 :: nil =>\n      do r <- freg_of res; do r1 <- ireg_of a1;\n      OK (Pfsitos r r1 :: k)\n  | Osingleofintu, a1 :: nil =>\n      do r <- freg_of res; do r1 <- ireg_of a1;\n      OK (Pfuitos r r1 :: k)\n  | Ocmp cmp, _ =>\n      do r <- ireg_of res;\n      transl_cond cmp args\n        (Pmovite (cond_for_cond cmp) r (SOimm Int.one) (SOimm Int.zero) :: k)\n  | _, _ =>\n      Error(msg \"Asmgen.transl_op\")\n  end.\n\n(** Accessing data in the stack frame. *)\n\nDefinition indexed_memory_access\n    (mk_instr: ireg -> int -> instruction)\n    (mk_immed: int -> int)\n    (base: ireg) (n: int) (k: code) :=\n  let n1 := mk_immed n in\n  if Int.eq n n1\n  then mk_instr base n :: k\n  else addimm IR14 base (Int.sub n n1) (mk_instr IR14 n1 :: k).\n\nDefinition loadind_int (base: ireg) (ofs: int) (dst: ireg) (k: code) :=\n  indexed_memory_access (fun base n => Pldr dst base (SOimm n)) mk_immed_mem_word base ofs k.\n\nDefinition loadind (base: ireg) (ofs: int) (ty: typ) (dst: mreg) (k: code) :=\n  match ty, preg_of dst with\n  | Tint, IR r =>\n      OK (indexed_memory_access (fun base n => Pldr r base (SOimm n)) mk_immed_mem_word base ofs k)\n  | Tany32, IR r =>\n      OK (indexed_memory_access (fun base n => Pldr_a r base (SOimm n)) mk_immed_mem_word base ofs k)\n  | Tsingle, FR r =>\n      OK (indexed_memory_access (Pflds r) mk_immed_mem_float base ofs k)\n  | Tfloat, FR r =>\n      OK (indexed_memory_access (Pfldd r) mk_immed_mem_float base ofs k)\n  | Tany64, FR r =>\n      OK (indexed_memory_access (Pfldd_a r) mk_immed_mem_float base ofs k)\n  | _, _ =>\n      Error (msg \"Asmgen.loadind\")\n  end.\n\nDefinition storeind (src: mreg) (base: ireg) (ofs: int) (ty: typ) (k: code) :=\n  match ty, preg_of src with\n  | Tint, IR r =>\n      OK (indexed_memory_access (fun base n => Pstr r base (SOimm n)) mk_immed_mem_word base ofs k)\n  | Tany32, IR r =>\n      OK (indexed_memory_access (fun base n => Pstr_a r base (SOimm n)) mk_immed_mem_word base ofs k)\n  | Tsingle, FR r =>\n      OK (indexed_memory_access (Pfsts r) mk_immed_mem_float base ofs k)\n  | Tfloat, FR r =>\n      OK (indexed_memory_access (Pfstd r) mk_immed_mem_float base ofs k)\n  | Tany64, FR r =>\n      OK (indexed_memory_access (Pfstd_a r) mk_immed_mem_float base ofs k)\n  | _, _ =>\n      Error (msg \"Asmgen.storeind\")\n  end.\n\n(** Translation of memory accesses *)\n\nDefinition transl_memory_access\n     (mk_instr_imm: ireg -> int -> instruction)\n     (mk_instr_gen: option (ireg -> shift_op -> instruction))\n     (mk_immed: int -> int)\n     (addr: addressing) (args: list mreg) (k: code) :=\n  match addr, args with\n  | Aindexed n, a1 :: nil =>\n      do r1 <- ireg_of a1;\n      OK (indexed_memory_access mk_instr_imm mk_immed r1 n k)\n  | Aindexed2, a1 :: a2 :: nil =>\n      match mk_instr_gen with\n      | Some f =>\n          do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n          OK (f r1 (SOreg r2) :: k)\n      | None =>\n          Error (msg \"Asmgen.Aindexed2\")\n      end\n  | Aindexed2shift s, a1 :: a2 :: nil =>\n      match mk_instr_gen with\n      | Some f =>\n          do r1 <- ireg_of a1; do r2 <- ireg_of a2;\n          OK (f r1 (transl_shift s r2) :: k)\n      | None =>\n          Error (msg \"Asmgen.Aindexed2shift\")\n      end\n  | Ainstack n, nil =>\n      OK (indexed_memory_access mk_instr_imm mk_immed IR13 n k)\n  | _, _ =>\n      Error(msg \"Asmgen.transl_memory_access\")\n  end.\n\nDefinition transl_memory_access_int\n     (mk_instr: ireg -> ireg -> shift_op -> instruction)\n     (mk_immed: int -> int)\n     (dst: mreg) (addr: addressing) (args: list mreg) (k: code) :=\n  do rd <- ireg_of dst;\n  transl_memory_access\n    (fun r n => mk_instr rd r (SOimm n))\n    (Some (mk_instr rd))\n    mk_immed addr args k.\n\nDefinition transl_memory_access_float\n     (mk_instr: freg -> ireg -> int -> instruction)\n     (mk_immed: int -> int)\n     (dst: mreg) (addr: addressing) (args: list mreg) (k: code) :=\n  do rd <- freg_of dst;\n  transl_memory_access\n    (mk_instr rd)\n    None\n    mk_immed addr args k.\n\nDefinition transl_load (chunk: memory_chunk) (addr: addressing)\n                       (args: list mreg) (dst: mreg) (k: code) :=\n  match chunk with\n  | Mint8signed =>\n      transl_memory_access_int Pldrsb mk_immed_mem_small dst addr args k\n  | Mint8unsigned =>\n      transl_memory_access_int Pldrb mk_immed_mem_word dst addr args k\n  | Mint16signed =>\n      transl_memory_access_int Pldrsh mk_immed_mem_small dst addr args k\n  | Mint16unsigned =>\n      transl_memory_access_int Pldrh mk_immed_mem_small dst addr args k\n  | Mint32 =>\n      transl_memory_access_int Pldr mk_immed_mem_word dst addr args k\n  | Mfloat32 =>\n      transl_memory_access_float Pflds mk_immed_mem_float dst addr args k\n  | Mfloat64 =>\n      transl_memory_access_float Pfldd mk_immed_mem_float dst addr args k\n  | _ =>\n      Error (msg \"Asmgen.transl_load\")\n  end.\n\nDefinition transl_store (chunk: memory_chunk) (addr: addressing)\n                       (args: list mreg) (src: mreg) (k: code) :=\n  match chunk with\n  | Mint8signed =>\n      transl_memory_access_int Pstrb mk_immed_mem_small src addr args k\n  | Mint8unsigned =>\n      transl_memory_access_int Pstrb mk_immed_mem_word src addr args k\n  | Mint16signed =>\n      transl_memory_access_int Pstrh mk_immed_mem_small src addr args k\n  | Mint16unsigned =>\n      transl_memory_access_int Pstrh mk_immed_mem_small src addr args k\n  | Mint32 =>\n      transl_memory_access_int Pstr mk_immed_mem_word src addr args k\n  | Mfloat32 =>\n      transl_memory_access_float Pfsts mk_immed_mem_float src addr args k\n  | Mfloat64 =>\n      transl_memory_access_float Pfstd mk_immed_mem_float src addr args k\n  | _ =>\n      Error (msg \"Asmgen.transl_store\")\n  end.\n\n(** Translation of arguments to annotations *)\n\nDefinition transl_annot_param (p: Mach.annot_param) : Asm.annot_param :=\n  match p with\n  | Mach.APreg r => APreg (preg_of r)\n  | Mach.APstack chunk ofs => APstack chunk ofs\n  end.\n\n(** Translation of a Mach instruction. *)\n\nDefinition transl_instr (f: Mach.function) (i: Mach.instruction)\n                        (r12_is_parent: bool) (k: code) :=\n  match i with\n  | Mgetstack ofs ty dst =>\n      loadind IR13 ofs ty dst k\n  | Msetstack src ofs ty =>\n      storeind src IR13 ofs ty k\n  | Mgetparam ofs ty dst =>\n      do c <- loadind IR12 ofs ty dst k;\n      OK (if r12_is_parent\n          then c\n          else loadind_int IR13 f.(fn_link_ofs) IR12 c)\n  | Mop op args res =>\n      transl_op op args res k\n  | Mload chunk addr args dst =>\n      transl_load chunk addr args dst k\n  | Mstore chunk addr args src =>\n      transl_store chunk addr args src k\n  | Mcall sig (inl arg) =>\n      do r <- ireg_of arg; OK (Pblreg r sig :: k)\n  | Mcall sig (inr symb) =>\n      OK (Pblsymb symb sig :: k)\n  | Mtailcall sig (inl arg) =>\n      do r <- ireg_of arg;\n      OK (loadind_int IR13 f.(fn_retaddr_ofs) IR14\n           (Pfreeframe f.(fn_stacksize) f.(fn_link_ofs) :: Pbreg r sig :: k))\n  | Mtailcall sig (inr symb) =>\n      OK (loadind_int IR13 f.(fn_retaddr_ofs) IR14\n           (Pfreeframe f.(fn_stacksize) f.(fn_link_ofs) :: Pbsymb symb sig :: k))\n  | Mbuiltin ef args res =>\n      OK (Pbuiltin ef (map preg_of args) (map preg_of res) :: k)\n  | Mannot ef args =>\n      OK (Pannot ef (map transl_annot_param args) :: k)\n  | Mlabel lbl =>\n      OK (Plabel lbl :: k)\n  | Mgoto lbl =>\n      OK (Pb lbl :: k)\n  | Mcond cond args lbl =>\n      transl_cond cond args (Pbc (cond_for_cond cond) lbl :: k)\n  | Mjumptable arg tbl =>\n      do r <- ireg_of arg;\n      OK (Pbtbl r tbl :: k)\n  | Mreturn =>\n      OK (loadind_int IR13 f.(fn_retaddr_ofs) IR14\n            (Pfreeframe f.(fn_stacksize) f.(fn_link_ofs) ::\n             Pbreg IR14 f.(Mach.fn_sig) :: k))\n  end.\n\n(** Translation of a code sequence *)\n\nDefinition it1_is_parent (before: bool) (i: Mach.instruction) : bool :=\n  match i with\n  | Msetstack src ofs ty => before\n  | Mgetparam ofs ty dst => negb (mreg_eq dst R12)\n  | Mop Omove args res => before && negb (mreg_eq res R12)\n  | _ => false\n  end.\n\n(** This is the naive definition that we no longer use because it\n  is not tail-recursive.  It is kept as specification. *)\n\nFixpoint transl_code (f: Mach.function) (il: list Mach.instruction) (it1p: bool) :=\n  match il with\n  | nil => OK nil\n  | i1 :: il' =>\n      do k <- transl_code f il' (it1_is_parent it1p i1);\n      transl_instr f i1 it1p k\n  end.\n\n(** This is an equivalent definition in continuation-passing style\n  that runs in constant stack space. *)\n\nFixpoint transl_code_rec (f: Mach.function) (il: list Mach.instruction)\n                         (it1p: bool) (k: code -> res code) :=\n  match il with\n  | nil => k nil\n  | i1 :: il' =>\n      transl_code_rec f il' (it1_is_parent it1p i1)\n        (fun c1 => do c2 <- transl_instr f i1 it1p c1; k c2)\n  end.\n\nDefinition transl_code' (f: Mach.function) (il: list Mach.instruction) (it1p: bool) :=\n  transl_code_rec f il it1p (fun c => OK c).\n\n(** Translation of a whole function.  Note that we must check\n  that the generated code contains less than [2^32] instructions,\n  otherwise the offset part of the [PC] code pointer could wrap\n  around, leading to incorrect executions. *)\n\nDefinition transl_function (f: Mach.function) :=\n  do c <- transl_code f f.(Mach.fn_code) true;\n  OK (mkfunction f.(Mach.fn_sig)\n        (Pallocframe f.(fn_stacksize) f.(fn_link_ofs) ::\n         Pstr IR14 IR13 (SOimm f.(fn_retaddr_ofs)) :: c)).\n\nDefinition transf_function (f: Mach.function) : res Asm.function :=\n  do tf <- transl_function f;\n  if zlt Int.max_unsigned (list_length_z tf.(fn_code))\n  then Error (msg \"code size exceeded\")\n  else OK tf.\n\nDefinition transf_fundef (f: Mach.fundef) : res Asm.fundef :=\n  transf_partial_fundef transf_function f.\n\nDefinition transf_program (p: Mach.program) : res Asm.program :=\n  transform_partial_program transf_fundef p.\n\n", "meta": {"author": "robbertkrebbers", "repo": "compcert", "sha": "524c26591e884a3676a5fbef77d8c79193955b82", "save_path": "github-repos/coq/robbertkrebbers-compcert", "path": "github-repos/coq/robbertkrebbers-compcert/compcert-524c26591e884a3676a5fbef77d8c79193955b82/arm/Asmgen.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.20753113616846983}}
{"text": "Require Import List Map Envs AllInRel Exp AppExpFree RenamedApart.\nRequire Import IL Annotation AnnotationLattice.\nRequire Import AutoIndTac Liveness.Liveness LabelsDefined.\nRequire Import DoSpill DoSpillRm.\nRequire Import SpillSound SpillUtil ReconstrLive ReconstrLiveSmall.\nRequire Import InVD Slot.\nRequire Import SlotLiftArgs SlotLiftParams.\nRequire Import PartialOrder AnnotationLattice.\n\nSet Implicit Arguments.\n\n(** * ReconstrLiveSound *)\n\nLemma sla_extargs_slp_length\n      (slot : var -> var)\n      RM RMapp\n      (ZL : list params)\n      (Z : params)\n      (l : lab)\n      (Λ : list (⦃var⦄ * ⦃var⦄))\n      (Y : args)\n  : length Y = length Z ->\n    ❬slot_lift_args slot RM RMapp Y Z❭ = ❬slot_lift_params slot RM Z❭.\nProof.\n  intros Len.\n  general induction Len; simpl; eauto.\n  repeat cases; simpl; eauto.\nQed.\n\nLemma reconstr_live_sound_s\n      (slot : var -> var) o\n      (ZL' ZL : list params)\n      (G : ⦃var⦄)\n      (Λ : list (⦃var⦄ * ⦃var⦄))\n      (Lv : list ⦃var⦄)\n      (s : stmt)\n      (sl : spilling)\n  :\n    (forall G',\n        live_sound o ZL' Lv\n                   (do_spill slot s (clear_SpL sl) ZL Λ)\n                   (reconstr_live (slot_merge slot ⊝ Λ) ZL' G'\n                                  (do_spill slot s (clear_SpL sl) ZL Λ)\n                                  (do_spill_rm slot (clear_SpL sl))))\n   -> live_sound o ZL' Lv\n                (do_spill slot s sl ZL Λ)\n                (reconstr_live (slot_merge slot ⊝ Λ) ZL' G\n                               (do_spill slot s sl ZL Λ)\n                               (do_spill_rm slot sl)).\nProof.\n  intros sls.\n\n  rewrite do_spill_extract_writes.\n  rewrite do_spill_rm_s.\n\n\n  unfold count.\n\n  (* prepare induction *)\n  remember (elements (getSp sl)) as elSp.\n  symmetry in HeqelSp.\n  remember (elements (getL  sl)) as elL.\n  symmetry in HeqelL.\n  do 2 rewrite <- elements_length.\n  rewrite HeqelL.\n  rewrite HeqelSp.\n  clear HeqelSp.\n  revert G.\n  induction elSp;\n    intros G;\n    simpl.\n  - (*apply elements_nil_eset in HeqelSp as empty_Sp.*)\n    revert G.\n    clear HeqelL.\n    induction elL;\n      intros G;\n      simpl in *.\n    + apply sls.\n\n    + rewrite add_anns_S.\n\n      constructor; eauto; fold reconstr_live.\n      * simpl.\n        apply live_exp_sound_incl with (lv':=singleton (slot a)).\n        -- econstructor.\n           econstructor.\n           cset_tac.\n        -- clear.\n           cset_tac.\n      * clear.\n        cset_tac.\n      * apply reconstr_live_G.\n        cset_tac.\n  - rewrite add_anns_S.\n    econstructor; simpl; eauto.\n    * simpl.\n      apply live_exp_sound_incl with (lv':=singleton a).\n      -- econstructor.\n         econstructor.\n         cset_tac.\n      -- clear.\n         cset_tac.\n    * clear.\n      cset_tac.\n    * apply reconstr_live_G.\n      cset_tac.\nQed.\n\nLemma reconstr_live_sound\n      (k : nat) VD\n      (slot : Slot VD)\n      (ZL : list params)\n      (G : ⦃var⦄)\n      (Λ : list (⦃var⦄ * ⦃var⦄))\n      (R M : ⦃var⦄)\n      (s : stmt)\n      (Lv : list ⦃var⦄)\n      (sl : spilling)\n      (alv : ann ⦃var⦄)\n      (ra : ann (⦃var⦄ * ⦃var⦄))\n  : R ⊆ VD\n    -> M ⊆ VD\n    -> fst (getAnn ra) ∪ snd (getAnn ra) ⊆ VD\n    -> app_expfree s\n    -> renamedApart s ra\n    -> spill_sound k ZL Λ (R,M) s sl\n    -> spill_live VD sl alv\n    -> PIR2 Equal (merge ⊝ Λ) Lv\n    -> (forall (Z : params) n,\n          get ZL n Z\n          -> of_list Z ⊆ VD)\n    -> live_sound Imperative ZL Lv s alv\n    -> live_sound Imperative\n                 ((slot_lift_params slot) ⊜ Λ ZL)\n                 (slot_merge slot ⊝ Λ)\n                 (do_spill slot s sl ZL Λ)\n                 (reconstr_live (slot_merge slot ⊝ Λ)\n                                ((slot_lift_params slot) ⊜ Λ ZL)\n                                 G\n                                 (do_spill slot s sl ZL Λ)\n                                (do_spill_rm slot sl))\n.\nProof.\n  intros disj_VD R_VD M_VD aeFree renAp spillSnd spilli pir2_EQ Z_VD lvSnd.\n\n  general induction lvSnd;\n    invc aeFree;\n    invc spillSnd;\n    invc spilli;\n    inv renAp;\n    apply reconstr_live_sound_s;\n    intros G'.\n\n  - rename sl0 into sl.\n    assert (x ∈ VD) as x_VD by (eapply x_VD; eauto).\n    rewrite do_spill_empty by apply count_clear_zero.\n    unfold do_spill_rec.\n    rewrite do_spill_rm_empty by apply count_clear_zero.\n    simpl.\n\n    econstructor; eauto.\n    + eapply IHlvSnd with (ra:=an) (R:={x; (R\\K ∪ L) \\Kx}) (M:=Sp ∪ M); eauto.\n      * eapply Rx_VD with (R:=R) (M:=M); eauto.\n      * eapply M'_VD with (R:=R) (M:=M); eauto.\n      * eapply renamedApart_incl in renAp as rena.\n        rewrite rena. eauto.\n    + apply live_exp_sound_incl with (lv':=Exp.freeVars e).\n      * apply live_freeVars.\n      * clear; cset_tac.\n    + clear; cset_tac.\n    + apply reconstr_live_G.\n      eauto with cset.\n\n  - rewrite do_spill_empty by apply count_clear_zero.\n    unfold do_spill_rec.\n    rewrite do_spill_rm_empty by apply count_clear_zero.\n    simpl.\n\n    apply renamedApart_incl in renAp as [rena1 rena2].\n    assert (R \\ K ∪ L ⊆ VD) as R'_VD\n        by (eapply R'_VD with (R:=R) (M:=M); eauto).\n    assert (Sp ∪ M ⊆ VD) as M'_VD\n        by (eapply M'_VD with (R:=R) (M:=M); eauto).\n    econstructor.\n    + eapply IHlvSnd1 with (ra:=ans) (R:=R\\K ∪ L); eauto.\n      rewrite rena1. eauto.\n    + eapply IHlvSnd2 with (ra:=ant) (R:=R\\K ∪ L); eauto.\n      rewrite rena2; eauto.\n    + apply live_op_sound_incl with (lv':=Ops.freeVars e).\n      * apply Ops.live_freeVars.\n      * clear; cset_tac.\n    + clear; cset_tac.\n    + clear; cset_tac.\n\n  - rewrite do_spill_empty by apply count_clear_zero.\n    unfold do_spill_rec.\n    rewrite do_spill_rm_empty by apply count_clear_zero.\n    simpl.\n    eapply get_get_eq in H; eauto.\n    subst Z0.\n\n    econstructor.\n    + eapply zip_get; eauto.\n    + simpl.\n      unfold slot_merge.\n      eapply map_get_eq; eauto.\n    + simpl.\n      assert (nth (labN l) (slot_merge slot ⊝ Λ) ∅ [=] R_f ∪ map slot M_f)\n        as nth_EQ.\n      {\n        unfold slot_merge.\n        assert ((fun RM => fst RM ∪ map slot (snd RM)) (R_f,M_f) = R_f ∪ map slot M_f)\n          by (simpl; reflexivity).\n        eapply map_get_eq in H13; eauto.\n        erewrite get_nth; eauto.\n        reflexivity.\n      }\n      rewrite nth_EQ.\n      assert (of_list (nth (labN l) (slot_lift_params slot ⊜ Λ ZL) nil)\n              [=] of_list (slot_lift_params slot (R_f,M_f) Z))\n        as nth_slp by (erewrite nth_zip; eauto; simpl; reflexivity).\n      rewrite nth_slp.\n      clear; cset_tac.\n    + erewrite !get_nth; try eassumption.\n      apply sla_extargs_slp_length; eauto.\n    + intros; inv_get.\n      erewrite !nth_zip; eauto.\n      erewrite !get_nth in H; eauto.\n      erewrite !get_nth; eauto using map_get_1. simpl.\n      eapply live_op_sound_incl. eapply Ops.live_freeVars.\n      eapply get_list_union_map with (f:=Ops.freeVars) in H.\n      rewrite <- H. cset_tac.\n  - rewrite do_spill_empty by apply count_clear_zero.\n    unfold do_spill_rec.\n    rewrite do_spill_rm_empty by apply count_clear_zero.\n    simpl.\n\n    econstructor; simpl; eauto.\n    + apply live_op_sound_incl with (lv':=Ops.freeVars e).\n      * apply Ops.live_freeVars.\n      * clear; cset_tac.\n\n  - rewrite do_spill_empty by apply count_clear_zero.\n    unfold do_spill_rec.\n    rewrite do_spill_rm_empty by apply count_clear_zero.\n    simpl.\n\n    apply renamedApart_incl in renAp as [renaF rena2].\n    rewrite fst_zip_pair by eauto with len.\n    econstructor; simpl; eauto.\n    + rewrite fst_zip_pair by eauto with len.\n      rewrite slot_lift_params_app; eauto with len.\n      rewrite getAnn_map_setTopAnn.\n      rewrite Take.take_eq_ge;\n        [|len_simpl; rewrite <- H13, <- H16; omega].\n      rewrite slot_merge_app.\n      apply live_sound_monotone with (LV:= slot_merge slot ⊝ (rms ++ Λ)).\n      * eapply IHlvSnd with (ra:=ant) (R:=R\\K ∪ L) (M:=Sp ∪ M); eauto.\n        -- eapply R'_VD with (R:=R) (M:=M); eauto.\n        -- eapply M'_VD with (R:=R) (M:=M); eauto.\n        -- rewrite rena2; eauto.\n        -- eapply getAnn_als_EQ_merge_rms; eauto.\n        -- eapply get_ofl_VD; eauto.\n      * rewrite <- slot_merge_app.\n        apply PIR2_app with (L2:=slot_merge slot ⊝ Λ);\n          swap 1 2.\n        {\n          apply PIR2_refl; eauto.\n        }\n        apply PIR2_get.\n        -- intros n x x' H4 H5.\n           inv_get; simpl.\n           rename x into Zs.\n           rename x0 into rm.\n           rename x5 into sl_s.\n           rename x1 into a.\n           rename x2 into al.\n           rename H33 into get_al.\n           rename H32 into get_a.\n           rename H26 into get_sls.\n           rename H30 into get_Zs.\n           rename H5 into get_rm.\n\n           rewrite slot_merge_app.\n\n           exploit H19 as H24'; eauto. (*H31*)\n           exploit H23 as H20'; eauto. (*H32*)\n           exploit renaF as renaF'; eauto.\n           exploit H14 as H15'; eauto. (*H33*)\n           exploit H2 as H2'; eauto.\n           destruct H2' as [H2' _].\n           destruct H15' as [A [B [C E]]].\n           assert (rm = (fst rm, snd rm)) as rm_eta by apply pair_eta.\n           rewrite rm_eta in H24'.\n           rewrite <- reconstr_live_setTopAnn.\n           erewrite reconstr_live_small with (VD:=VD)\n                                             (ra:=a)\n                                             (R:=fst rm)\n                                             (M:=snd rm); eauto.\n           ++ (*clear - pir2_EQ pir3 renaF H24 H20 H15 H2 H16 H20 H8 H13 H14 H H9 H18 ra_VD.*)\n             clear - rm_eta H2' get_al get_a get_sls get_rm get_Zs H15.\n             rewrite rm_eta in get_rm.\n             eapply al_sub_RfMf in get_rm; eauto.\n             rewrite rm_eta. unfold slot_merge; simpl.\n              repeat apply union_incl_split;\n                [clear; cset_tac | clear; cset_tac\n                 | eapply ofl_slp_sub_rm; eauto ].\n           ++ rewrite renaF'; eauto.\n           ++ eapply getAnn_als_EQ_merge_rms; eauto.\n           ++ eapply get_ofl_VD; eauto.\n\n        -- eauto with len.\n    + symmetry.\n      apply zip_length2.\n      repeat rewrite length_map.\n      rewrite zip_length2;\n        eauto with len.\n    + intros; inv_get.\n      simpl.\n      rewrite fst_zip_pair by eauto with len.\n      rewrite getAnn_map_setTopAnn.\n      rewrite Take.take_eq_ge;\n        [|unfold slot_merge; len_simpl; rewrite <- H13, <- H16; omega].\n      rewrite slot_merge_app.\n      rewrite slot_lift_params_app; eauto with len.\n      rewrite <- reconstr_live_setTopAnn.\n      apply live_sound_monotone with (LV:= slot_merge slot ⊝ (rms ++ Λ)).\n      * assert ((fst x3, snd x3) = x3)\n          by (destruct x3; simpl; reflexivity).\n        rewrite <- H4 in H31.\n        exploit H23; eauto.\n        eapply H1 with (ra:=x0) (R:=fst x3) (M:=snd x3); eauto.\n        -- exploit renaF as renaF'; eauto.\n           rewrite renaF'; eauto.\n        -- eapply getAnn_als_EQ_merge_rms; eauto.\n        -- eapply get_ofl_VD; eauto.\n      * rewrite <- slot_merge_app.\n        apply PIR2_app with (L2:=slot_merge slot ⊝ Λ);\n          swap 1 2.\n        {\n          apply PIR2_refl; eauto.\n        }\n        apply PIR2_get.\n        -- intros.\n           unfold slot_merge in H5.\n           inv_get; simpl.\n           rewrite slot_merge_app.\n           exploit H19; eauto.\n           exploit H23; eauto.\n           exploit H9; eauto.\n           destruct x5 as [R_f M_f].\n           rewrite <- reconstr_live_setTopAnn.\n           erewrite reconstr_live_small with (ra:=x6)\n                                             (VD:=VD)\n                                             (R:=R_f)\n                                             (M:=M_f); eauto.\n           ++ exploit H2 as H2'; eauto; dcr; simpl in *.\n\n             rewrite ofl_slp_sub_rm; eauto.\n             poLe_set. clear; cset_tac.\n             eapply al_sub_RfMf; eauto.\n           ++ rewrite renaF; eauto.\n           ++ eapply getAnn_als_EQ_merge_rms; eauto.\n           ++ eapply get_ofl_VD; eauto.\n        -- unfold slot_merge. eauto with len.\n    + intros.\n      inv_get.\n      simpl.\n      split; [ | auto].\n      * apply reconstr_live_G.\n      * split; eauto.\n        -- exploit H2; eauto; dcr.\n           eapply PIR2_nth in H15; eauto; dcr.\n           destruct x3. eapply NoDupA_slot_lift_params; eauto.\n           unfold merge in H33.\n           exploit H23; eauto; dcr. eauto with cset.\n           rewrite <- M_VD. simpl.\n           rewrite <- H27.\n           rewrite <- incl_list_union; eauto using zip_get; [|reflexivity].\n           unfold defVars. clear; cset_tac.\nQed.\n", "meta": {"author": "sigurdschneider", "repo": "lvc", "sha": "be41194f16495d283fe7bbc982c3393ac554dd5b", "save_path": "github-repos/coq/sigurdschneider-lvc", "path": "github-repos/coq/sigurdschneider-lvc/lvc-be41194f16495d283fe7bbc982c3393ac554dd5b/theories/Spilling/ReconstrLiveSound.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.566018520554724, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2074965802036153}}
{"text": "Require Import CodeProofDeps.\nRequire Import Ident.\nRequire Import Constants.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import CommonLib.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef2.Spec.\nRequire Import TableDataOpsRef2.Layer.\nRequire Import TableDataOpsRef3.Code.data_create_unknown3.\n\nRequire Import TableDataOpsRef3.LowSpecs.data_create_unknown3.\n\nLocal Open Scope Z_scope.\n\nSection CodeProof.\n\n  Context `{real_params: RealParams}.\n  Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n  Context `{Hmwd: UseMemWithData memb}.\n\n  Let mem := mwd (cdata RData).\n\n  Context `{Hstencil: Stencil}.\n  Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n  Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n  Let L : compatlayer (cdata RData) :=\n    _data_create ↦ gensem data_create_spec\n      ⊕ _data_create_unknown2 ↦ gensem data_create_unknown2_spec\n      ⊕ _data_create_unknown ↦ gensem data_create_unknown_spec\n  .\n\n  Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n  Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n  Section BodyProof.\n\n    Context `{Hwb: WritableBlockOps}.\n    Variable (sc: stencil).\n    Variables (ge: genv) (STENCIL_MATCHES: stencil_matches sc ge).\n\n    Variable b_data_create: block.\n    Hypothesis h_data_create_s : Genv.find_symbol ge _data_create = Some b_data_create.\n    Hypothesis h_data_create_p : Genv.find_funct_ptr ge b_data_create\n                                 = Some (External (EF_external _data_create\n                                                  (signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong (Tcons Tptr (Tcons Tptr Tnil))))) tulong cc_default))\n                                        (Tcons Tptr (Tcons tulong (Tcons tulong (Tcons Tptr (Tcons Tptr Tnil))))) tulong cc_default).\n    Local Opaque data_create_spec.\n\n    Variable b_data_create_unknown2: block.\n    Hypothesis h_data_create_unknown2_s : Genv.find_symbol ge _data_create_unknown2 = Some b_data_create_unknown2.\n    Hypothesis h_data_create_unknown2_p : Genv.find_funct_ptr ge b_data_create_unknown2\n                                          = Some (External (EF_external _data_create_unknown2\n                                                           (signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong (Tcons Tptr Tnil)))) tulong cc_default))\n                                                 (Tcons Tptr (Tcons tulong (Tcons tulong (Tcons Tptr Tnil)))) tulong cc_default).\n    Local Opaque data_create_unknown2_spec.\n\n    Variable b_data_create_unknown: block.\n    Hypothesis h_data_create_unknown_s : Genv.find_symbol ge _data_create_unknown = Some b_data_create_unknown.\n    Hypothesis h_data_create_unknown_p : Genv.find_funct_ptr ge b_data_create_unknown\n                                         = Some (External (EF_external _data_create_unknown\n                                                          (signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong (Tcons Tptr Tnil)))) tulong cc_default))\n                                                (Tcons Tptr (Tcons tulong (Tcons tulong (Tcons Tptr Tnil)))) tulong cc_default).\n    Local Opaque data_create_unknown_spec.\n\n    Lemma data_create_unknown3_body_correct:\n      forall m d d' env le g_rd_base g_rd_offset data_addr map_addr g_data_base g_data_offset res\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTg_rd: PTree.get _g_rd le = Some (Vptr g_rd_base (Int.repr g_rd_offset)))\n             (HPTdata_addr: PTree.get _data_addr le = Some (Vlong data_addr))\n             (HPTmap_addr: PTree.get _map_addr le = Some (Vlong map_addr))\n             (HPTg_data: PTree.get _g_data le = Some (Vptr g_data_base (Int.repr g_data_offset)))\n             (Hspec: data_create_unknown3_spec0 (g_rd_base, g_rd_offset) (VZ64 (Int64.unsigned data_addr)) (VZ64 (Int64.unsigned map_addr)) (g_data_base, g_data_offset) d = Some (d', VZ64 (Int64.unsigned res))),\n           exists le', (exec_stmt ge env le ((m, d): mem) data_create_unknown3_body E0 le' (m, d') (Out_return (Some (Vlong res, tulong)))).\n    Proof.\n      solve_code_proof Hspec data_create_unknown3_body; eexists; solve_proof_low.\n    Qed.\n\n  End BodyProof.\n\nEnd CodeProof.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef3/CodeProof/data_create_unknown3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20746118161498137}}
{"text": "(* Copyright (c) 2017, the Dart project authors.  Please see the AUTHORS file\n * for details. All rights reserved. Use of this source code is governed by a\n * BSD-style license that can be found in the LICENSE file. *)\n\nRequire Import Utf8.\nRequire Import ClassTestTypes.\nRequire Import NotVoidAssignability.\n\n(* Simple function types *)\nDefinition dt_fun_void_void := dt_function dt_void (dts_cons dt_void dts_nil).\nDefinition dt_fun_void_dynamic := dt_function dt_dynamic (dts_cons dt_void dts_nil).\nDefinition dt_fun_dynamic_void := dt_function dt_void (dts_cons dt_dynamic dts_nil).\nDefinition dt_fun_dynamic_dynamic := dt_function dt_dynamic (dts_cons dt_dynamic dts_nil).\nDefinition dt_fun_Object_Object := dt_function dt_Object (dts_cons dt_Object dts_nil).\nDefinition dt_fun_Object_void := dt_function dt_void (dts_cons dt_Object dts_nil).\nDefinition dt_fun_void_Object := dt_function dt_Object (dts_cons dt_void dts_nil).\n\nHint Unfold\n  dt_fun_void_void dt_fun_void_dynamic dt_fun_dynamic_void\n  dt_fun_dynamic_dynamic dt_fun_Object_Object dt_fun_Object_void\n  dt_fun_void_Object.\n\n(* -------------------- Test cases from email -------------------- *)\n\n(* A<Object> x = new A<void>(); // No *)\nGoal NotVoidAssignable dt_A_void dt_A_Object.\n  apply nva_class. unfold ct_A_void.\n  apply nvact_upcast with (args1 := dts_cons dt_void dts_nil).\n      apply dsscts_cons.\n        apply dscts_first. apply dsct_args. apply dsp_cons.\n          apply ds_Object.\n        apply dsp_nil.\n      apply dsscts_cons.\n        apply dscts_rest. apply dscts_first. auto.\n      apply dsscts_nil.\n    apply ctn_first.\n  apply nvap_cons_first. apply nva_base; discriminate.\nQed.\n\n(* A<dynamic> x = new A<void>(); // Yes *)\nGoal ~(NotVoidAssignable dt_A_void dt_A_dynamic).\n  unfold not. intros. inversion H. inversion H2.\n    subst. unfold ct_A_void in *.\n    assert (args1 = dts_cons dt_void dts_nil).\n      inversion H8.\n        reflexivity.\n      contradiction H6. reflexivity.\n    subst args1. inversion H9.\n      inversion H1. contradiction H10. reflexivity.\n    inversion H1.\n  unfold ct_A_dynamic in *.\n  assert (args2 = dts_cons dt_dynamic dts_nil).\n    inversion H8.\n      reflexivity.\n    contradiction H15. reflexivity.\n  subst args2. inversion H9.\n    inversion H11. apply H16. reflexivity.\n  inversion H11.\nQed.\n\n(* A<Object> x = new A<dynamic>(); // Yes *)\nGoal ~(NotVoidAssignable dt_A_void dt_A_dynamic).\n  unfold not. intros. inversion H. inversion H2; subst.\n    unfold ct_A_void in *.\n    assert (args1 = dts_cons dt_void dts_nil).\n      inversion H8.\n        reflexivity.\n      contradiction H6. reflexivity.\n    subst args1. inversion H9.\n      inversion H1. apply H10. reflexivity.\n    inversion H1.\n  assert (args2 = dts_cons dt_dynamic dts_nil).\n    inversion H8.\n      reflexivity.\n    contradiction H7. reflexivity.\n  subst args2.\n  inversion H9.\n    inversion H1. apply H10. reflexivity.\n  inversion H1.\nQed.\n\n(* A<void> x = new A<dynamic>(); // voidV = dynamicV, yes *)\nGoal ~(NotVoidAssignable dt_A_dynamic dt_A_void).\n  unfold not. intros. inversion H. inversion H2; subst; unfold ct_A_dynamic in *.\n    assert (args1 = dts_cons dt_dynamic dts_nil).\n      inversion H8.\n        reflexivity.\n      contradiction H6. reflexivity.\n    subst args1. inversion H9.\n      inversion H1.\n    inversion H1.\n  assert (args2 = dts_cons dt_void dts_nil).\n    inversion H8.\n      reflexivity.\n    contradiction H7. reflexivity.\n  subst args2. inversion H9.\n    inversion H1.\n  inversion H1.\nQed.\n\n(* A<void> x = new A<Object>(); // voidV = objectV, Yes *)\nGoal ~(NotVoidAssignable dt_A_Object dt_A_void).\n  unfold not. intros. inversion H. inversion H2; subst; unfold ct_A_Object in *.\n    assert (args1 = dts_cons dt_Object dts_nil).\n      inversion H8.\n        reflexivity.\n      contradiction H6. reflexivity.\n    subst args1. inversion H9.\n      inversion H1.\n    inversion H1.\n  assert (args2 = dts_cons dt_void dts_nil).\n    inversion H8.\n      reflexivity.\n    contradiction H7. reflexivity.\n  subst args2. inversion H9.\n    inversion H1.\n  inversion H1.\nQed.\n\n(* dynamic x = new A<void>(); // Yes *)\nGoal ~(NotVoidAssignable dt_A_void dt_dynamic).\n  unfold not. intros. inversion H.\nQed.\n\n(* Object x = new A<void>(); // Yes *)\nGoal ~(NotVoidAssignable dt_A_void dt_Object).\n  unfold not. intros. inversion H. inversion H2; subst; unfold ct_A_void in *.\n    assert (args1 = dts_nil).\n      inversion H9.\n    subst args1. inversion H9.\n  inversion H8. inversion H10.\nQed.\n\n(* Iterable<void> x = new List<void>(); // Yes *)\nGoal ~(NotVoidAssignable dt_List_void dt_Iterable_void).\n  unfold not. intros. inversion H. inversion H2; subst; unfold ct_List_void in *.\n    assert (args1 = dts_cons dt_void dts_nil).\n      inversion H8. inversion H10.\n        reflexivity.\n      inversion H17. inversion H24.\n    subst args1. inversion H9.\n      inversion H1. apply H6. reflexivity.\n    inversion H1.\n  inversion H8. inversion H10. inversion H17.\nQed.\n\n(* List<void> x = new Iterable<void>(); // Yes *)\nGoal ~(NotVoidAssignable dt_Iterable_void dt_List_void).\n  unfold not. intros. inversion H. inversion H2; subst; unfold ct_Iterable_void in *.\n    inversion H8. inversion H10. inversion H17.\n  assert (args2 = dts_cons dt_void dts_nil).\n    inversion H8. inversion H10.\n      reflexivity.\n    contradiction H16. reflexivity.\n  subst args2. inversion H9.\n    inversion H1. apply H7. reflexivity.\n  inversion H1.\nQed.\n\n(* Iterable<Object> x = new List<void>(); // No *)\nGoal NotVoidAssignable dt_List_void dt_Iterable_Object.\n  apply nva_class. apply nvact_upcast with (args1 := dts_cons dt_void dts_nil).\n      apply dsscts_cons.\n        apply dscts_rest. apply dscts_first. apply dsct_args. apply dsp_cons.\n          auto.\n        auto.\n      apply dsscts_cons.\n        apply dscts_rest. apply dscts_rest. apply dscts_first. auto.\n      auto.\n    apply ctn_rest.\n      discriminate.\n    apply ctn_first.\n  apply nvap_cons_first. apply nva_base.\n    discriminate.\n  discriminate.\nQed.\n\n(* List<Object> x = new Iterable<void>(); // No *)\nGoal NotVoidAssignable dt_Iterable_void dt_List_Object.\n  apply nva_class. apply nvact_downcast with (args2 := dts_cons dt_Object dts_nil).\n      apply dsscts_cons.\n        apply dscts_rest. apply dscts_first. apply dsct_args. auto.\n      apply dsscts_cons.\n        apply dscts_rest. apply dscts_rest. apply dscts_first. apply dsct_args. auto.\n      auto.\n    apply ctn_rest.\n      discriminate.\n    apply ctn_first.\n  apply nvap_cons_first. apply nva_base.\n    discriminate.\n  discriminate.\nQed.\n\n(* void Function(void) f = func<dynamic, dynamic>; // Yes!! void-to-dynamic is OK! *)\nGoal ~(NotVoidAssignable dt_fun_dynamic_dynamic dt_fun_void_void).\n  unfold not. intros. inversion H.\n    inversion H2. inversion H5.\n  inversion H5.\n    inversion H7. intuition H12.\n  inversion H7.\nQed.\n\n(* void Function(void) f = func<dynamic, void>; // Yes!! void-to-dynamic is OK! *)\nGoal ~(NotVoidAssignable dt_fun_dynamic_void dt_fun_void_void).\n  unfold not. intros. inversion H.\n    inversion H2. inversion H5. intuition H0.\n  inversion H5.\n    inversion H7. intuition H12.\n  inversion H7.\nQed.\n\n(* void Function(void) f = func<void, dynamic>; // Yes *)\nGoal ~(NotVoidAssignable dt_fun_void_dynamic dt_fun_void_void).\n  unfold not. intros. inversion H.\n    inversion H2. inversion H5.\n  inversion H5.\n    inversion H7. intuition H11.\n  inversion H7.\nQed.\n\n(* void Function(void) f = func<Object, Object>; // No *)\nGoal NotVoidAssignable dt_fun_Object_Object dt_fun_void_void.\n  apply nva_function_arg.\n    unfold DartAssignable. left. apply ds_function.\n      apply ds_void.\n    apply dsp_cons.\n      apply ds_Object.\n    auto.\n  apply nvap_cons_first. apply nva_base.\n    discriminate.\n  discriminate.\nQed.\n\n(* void Function(void) f = func<Object, void>; // No *)\nGoal NotVoidAssignable dt_fun_Object_void dt_fun_void_void.\n  apply nva_function_arg.\n    unfold DartAssignable. left. apply ds_function.\n      apply ds_void.\n    apply dsp_cons.\n      apply ds_Object.\n    auto.\n  apply nvap_cons_first. apply nva_base.\n    discriminate.\n  discriminate.\nQed.\n\n(* void Function(void) f = func<void, Object>; // Yes *)\nGoal ~(NotVoidAssignable dt_fun_void_Object dt_fun_void_void).\n  unfold not. intros. inversion H.\n    inversion H2. inversion H5.\n  inversion H5.\n    inversion H7. intuition H11.\n  inversion H7.\nQed.\n\n(* dynamic Function(dynamic) g = func<void, void>; // Yes *)\nGoal ~(NotVoidAssignable dt_fun_void_void dt_fun_dynamic_dynamic).\n  unfold not. intros. inversion H.\n    inversion H3.\n      inversion H5. intuition H1.\n    inversion H5. intuition H1.\n  inversion H5.\n    inversion H7.\n  inversion H7.\nQed.\n\n(* dynamic Function(dynamic) g = func<dynamic, void>; // Yes *)\nGoal ~(NotVoidAssignable dt_fun_dynamic_void dt_fun_dynamic_dynamic).\n  unfold not. intros. inversion H.\n    inversion H3.\n      inversion H5. intuition H1.\n    inversion H5. intuition H1.\n  inversion H5.\n    inversion H7.\n  inversion H7.\nQed.\n\n(* dynamic Function(dynamic) g = func<void, dynamic>; // Yes *)\nGoal ~(NotVoidAssignable dt_fun_void_dynamic dt_fun_dynamic_dynamic).\n  unfold not. intros. inversion H.\n    inversion H3.\n      inversion H5.\n    inversion H5.\n  inversion H5.\n    inversion H7.\n  inversion H7.\nQed.\n\n(* dynamic Function(dynamic) g = func<Object, Object>; // Yes *)\nGoal ~(NotVoidAssignable dt_fun_Object_Object dt_fun_dynamic_dynamic).\n  unfold not. intros. inversion H.\n    inversion H3.\n      inversion H5.\n    inversion H5.\n  inversion H5.\n    inversion H7. inversion H7.\nQed.\n\n(* dynamic Function(dynamic) g = func<Object, void>; // Yes *)\nGoal ~(NotVoidAssignable dt_fun_Object_void dt_fun_dynamic_dynamic).\n  unfold not. intros. inversion H.\n    inversion H3.\n      inversion H5. intuition H8.\n    inversion H5. intuition H8.\n  inversion H3.\n    inversion H5.\n      inversion H8.\n    inversion H8.\n  inversion H5.\n    inversion H8.\n  inversion H8.\nQed.\n\n(* dynamic Function(dynamic) g = func<void, Object>; // Yes *)\nGoal ~(NotVoidAssignable dt_fun_void_Object dt_fun_dynamic_dynamic).\n  unfold not. intros. inversion H.\n    inversion H3.\n      inversion H5.\n    inversion H5.\n  inversion H5.\n    inversion H7.\n  inversion H7.\nQed.\n\n(* Object Function(Object) h = func<void, void>; // No *)\nGoal NotVoidAssignable dt_fun_void_void dt_fun_Object_Object.\n  apply nva_function_ret.\n    unfold DartAssignable. left. apply ds_function.\n      apply ds_Object.\n    apply dsp_cons.\n      apply ds_void.\n    auto.\n  apply nva_base; discriminate.\nQed.\n\n(* Object Function(Object) h = func<dynamic, void>; // No *)\nGoal NotVoidAssignable dt_fun_dynamic_void dt_fun_Object_Object.\n  apply nva_function_ret.\n    unfold DartAssignable. left. apply ds_function.\n      apply ds_Object.\n    apply dsp_cons.\n      apply ds_dynamic.\n    auto.\n  apply nva_base; discriminate.\nQed.\n\n(* Object Function(Object) h = func<void, dynamic>; // Yes *)\nGoal ~(NotVoidAssignable dt_fun_void_dynamic dt_fun_Object_Object).\n  unfold not. intros. inversion H.\n    inversion H3.\n      inversion H5.\n    inversion H5.\n  inversion H5.\n    inversion H7.\n  inversion H7.\nQed.\n\n(* Object Function(Object) h = func<Object, Object>; // Yes *)\nGoal ~(NotVoidAssignable dt_fun_Object_Object dt_fun_Object_Object).\n  unfold not. intros. inversion H.\n    inversion H3.\n      inversion H5. inversion H9.\n        inversion H16.\n      inversion H16.\n    inversion H5. inversion H9.\n      inversion H16.\n    inversion H16.\n  inversion H5. inversion H7.\n    inversion H13.\n      inversion H20.\n    inversion H20.\n  inversion H7.\nQed.\n\n(* Object Function(Object) h = func<Object, void>; // No *)\nGoal NotVoidAssignable dt_fun_Object_void dt_fun_Object_Object.\n  apply nva_function_ret.\n    unfold DartAssignable. left. apply ds_function.\n      apply ds_Object.\n    apply dsp_cons.\n      apply ds_Object.\n    auto.\n  apply nva_base; discriminate.\nQed.\n\n(* Object Function(Object) h = func<void, Object>; // Yes *)\nGoal ~(NotVoidAssignable dt_fun_void_Object dt_fun_Object_Object).\n  unfold not. intros. inversion H.\n    inversion H3.\n      inversion H5. inversion H9.\n        inversion H16.\n      inversion H16.\n    inversion H5. inversion H9.\n      inversion H16.\n    inversion H16.\n  inversion H5.\n    inversion H7.\n  inversion H7.\nQed.\n\nGoal NotVoidAssignable dt_fun_Object_Object dt_fun_void_Object. (* TODO: different from VoidnessType result *)\n  apply nva_function_arg.\n    unfold DartAssignable. left. apply ds_function.\n      apply ds_Object.\n    apply dsp_cons.\n      apply ds_Object.\n    auto.\n  apply nvap_cons_first. apply nva_base; discriminate.\nQed.\n", "meta": {"author": "eernstg", "repo": "coq-voidness", "sha": "727d326633a7759ed4d6f6d7ae26eae900485d01", "save_path": "github-repos/coq/eernstg-coq-voidness", "path": "github-repos/coq/eernstg-coq-voidness/coq-voidness-727d326633a7759ed4d6f6d7ae26eae900485d01/FunctionNotVoidAssignableTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20746118161498137}}
{"text": "(** * IndistRelations.v: indistinguishability relation for annotated programs *)\n(*Require FFun.*)\nRequire Export DEX_BigStepAnnot.\nRequire Export Annotated.\n\nOpen Scope type_scope.\n\nImport DEX_BigStepAnnot.DEX_BigStepAnnot DEX_BigStep.DEX_BigStep DEX_Dom DEX_Prog.\n\n(* Hendra 12082016 - remove beta function, focus on DEX I *)\nInductive Value_in  (*b b':FFun.t Location*) : DEX_value -> DEX_value -> Prop :=\n| Value_in_num: forall n,\n  Value_in (*b b'*) (Num n) (Num n).\n\nInductive Value_in_opt (*b b':FFun.t Location*) : \n  option DEX_value -> option DEX_value -> Prop :=\n| Value_in_opt_some: \n  forall v v',\n    Value_in (*b b'*) v v' -> \n    Value_in_opt (*b b'*) (Some v) (Some v')\n| Value_in_opt_none: Value_in_opt (*b b'*) None None.\n\n(* older regs in\nInductive Reg_in (observable:L.t) :\n  L.t -> L.t -> DEX_value -> DEX_value -> Prop :=\n| Reg_high_in : forall k k' v v', ~(L.leql k observable) -> ~(L.leql k' observable) ->\n    Reg_in observable k k' v v'\n| Reg_nhigh_in : forall k k' v v', Value_in v v' -> Reg_in observable k k' v v'. \n\nInductive Regs_in (observable:L.t) (r r': DEX_Registers.t) (rt rt': TypeRegisters) : Prop :=\n| Build_Regs_in : eq_set (VarMap.dom _ rt) (VarMap.dom _ rt') ->\n  (forall (rn:DEX_Reg),\n  In rn (VarMap.dom _ rt) -> In rn (VarMap.dom _ rt') -> \n  (forall v v' k k',\n  Some v = DEX_Registers.get r rn -> Some v' = DEX_Registers.get r' rn ->\n  Some k = VarMap.get _ rt rn -> Some k' = VarMap.get _ rt' rn ->\n  Reg_in observable k k' v v')) -> Regs_in observable r r' rt rt'. *)\n\nInductive Reg_in (observable:L.t) (r r': DEX_Registers.t) (rt rt': TypeRegisters) (rn:DEX_Reg) : Prop :=\n| Reg_high_in : forall k k', VarMap.get L.t rt rn = Some k -> VarMap.get L.t rt' rn = Some k' ->\n    ~(L.leql k observable) -> ~(L.leql k' observable) -> Reg_in observable r r' rt rt' rn\n| Reg_nhigh_in : Value_in_opt (DEX_Registers.get r rn) (DEX_Registers.get r' rn) -> Reg_in observable r r' rt rt' rn.\n\nInductive Regs_in (observable:L.t) (r r': DEX_Registers.t) (rt rt': TypeRegisters) : Prop :=\n| Build_Regs_in : eq_set (VarMap.dom _ rt) (VarMap.dom _ rt') ->\n  (forall (rn:DEX_Reg), Reg_in observable r r' rt rt' rn) -> Regs_in observable r r' rt rt'.\n\n(* Inductive Regs_in (observable:L.t) (r r': DEX_Registers.t) (rt rt': TypeRegisters) : Prop :=\n| High_Regs_in : \n  (forall (rn:DEX_Reg) k k',\n  Some k = VarMap.get _ rt rn -> Some k' = VarMap.get _ rt' rn ->\n  ~(L.leql k observable) /\\ ~(L.leql k' observable)) -> Regs_in observable r r' rt rt'\n| nHigh_Regs_in : \n  (forall (rn:DEX_Reg) v v' k k',\n(*   In rn (DEX_Registers.dom r) -> In rn (DEX_Registers.dom r') -> *)\n  Some v = DEX_Registers.get r rn -> Some v' = DEX_Registers.get r' rn ->\n  Some k = VarMap.get _ rt rn -> Some k' = VarMap.get _ rt' rn ->\n  Value_in v v') -> Regs_in observable r r' rt rt'. *)\n\nInductive st_in (observable:L.t) (*newArT : Method * PC -> L.t') (ft:FieldSignature -> L.t'*) \n(*lvt:Var->L.t'*)  (*b b':FFun.t Location*) (rt rt':TypeRegisters) :   \n  DEX_PC * (*Heap.t * OperandStack.t * LocalVar.t*) DEX_Registers.t ->\n  DEX_PC * (*Heap.t * OperandStack.t * LocalVar.t*) DEX_Registers.t -> Prop := \n| Build_st_in: forall (*h h'*) pc pc' (*l l'*) r r',\n    (*localvar_in observable lvt (*b b'*) l l' ->*)\n    Regs_in observable (*b b'*) r r' rt rt' ->\n    (*hp_in observable newArT ft b b' h h' ->*)\n    st_in observable (*newArT ft lvt b b'*) rt rt' (pc,r(*,l*)) (pc',r'(*,l'*)).\n\nInductive indist_return_value (observable:L.t) (s:DEX_sign) (*h1 h2:Heap.t*) : \n    DEX_ReturnVal -> DEX_ReturnVal -> (*FFun.t Location -> FFun.t Location ->*) Prop :=\n| indist_return_val : forall v1 v2 (*b1 b2*) k,\n  s.(DEX_resType) = Some k ->\n  (L.leql k observable -> Value_in (*b1 b2*) v1 v2) ->\n  indist_return_value observable s (*h1 h2*) (Normal (Some v1)) (Normal (Some v2)) (*b1 b2 *)\n| indist_return_void : (*forall b1 b2 ,*)\n  s.(DEX_resType) = None ->\n  indist_return_value observable s (*h1 h2*) (Normal None) (Normal None) (*b1 b2 *).\n\nInductive high_result (observable:L.t) (s:DEX_sign) (*h:Heap.t*) : DEX_ReturnVal -> Prop :=\n| high_result_void : \n  s.(DEX_resType) = None ->\n  high_result observable s (*h*) (Normal None)\n| high_result_value : forall v k,\n  s.(DEX_resType) = Some k ->\n  ~ L.leql k observable ->\n  high_result observable s (*h*) (Normal (Some v)).\n\nInductive state : Type :=\n  intra : DEX_IntraNormalState -> TypeRegisters -> (*FFun.t Location ->*) state\n| ret : (*Heap.t ->*) DEX_ReturnVal -> (*FFun.t Location ->*) state.\n\nInductive indist (observable:L.t) (p:DEX_ExtendedProgram) (m:DEX_Method) (sgn:DEX_sign) : state -> state -> Prop :=\n| indist_intra : forall  (*h h'*) pc pc' (*l l'*) r r' rt rt' (*b b'*),\n  st_in observable (*newArT p) (ft p sgn.(DEX_lvt) b b'*) rt rt' (pc,(*h,*)r(*,l*)) (pc',(*h',*)r'(*,l'*)) ->\n  indist observable p m sgn (intra (pc,((*h,*)r(*,l*))) rt (*b*)) (intra (pc',((*h',*)r'(*,l'*))) rt' (*b'*))\n(*| indist_intra_return_case : forall pc h s l st b h' v' b',\n  indist_intra_return observable p sgn (pc,(h,s,l)) st b h' v' b' ->\n  indist observable p m sgn (intra (pc,(h,s,l)) st b) (ret h' v' b')\n| indist_return_intra_case : forall pc h s l st b h' v' b',\n  indist_intra_return observable p sgn (pc,(h,s,l)) st b h' v' b' ->\n  indist observable p m sgn (ret h' v' b') (intra (pc,(h,s,l)) st b) *)\n| indist_return : forall (*b b' h h'*) v v',\n  (*hp_in observable (newArT p) (ft p) b b' h h' ->*)\n  indist_return_value observable sgn (*h h'*) v v' (*b b'*) ->\n  indist observable p m sgn (ret (*h*) v (*b*)) (ret (*h'*) v' (*b'*)).\n\n\n (** Indistinguishability relations *)\n\nSection p.\n  Variable kobs : L.t.\n  Variable p : DEX_ExtendedProgram.\n  (*Notation ft := (ft p).\n  Notation newArT := (newArT p).*)\n\n (** Basic results on indistinguishability relations *)\n\n  Lemma Value_in_sym : forall v1 v2 (*b1 b2*),\n    Value_in (*b1 b2*) v1 v2 ->\n    Value_in (*b2 b1*) v2 v1.\n  Proof.\n    intros.\n    inversion_clear H; try constructor.\n    (* Hendra 15082016 - related to beta function - constructor 3 with n; auto.*)\n  Qed.\n\n  Lemma Value_in_opt_sym : forall v1 v2 (*b1 b2*),\n    Value_in_opt (*b1 b2*) v1 v2 ->\n    Value_in_opt (*b2 b1*) v2 v1.\n  Proof.\n    intros.\n    inversion_clear H; try constructor.\n    apply Value_in_sym; auto.\n  Qed.\n\n  Lemma Value_in_trans : forall v1 v2 v3 (*b1 b2 b3*),\n    (*FFun.is_inj b2 ->*)\n    Value_in (*b1 b2*) v1 v2 ->\n    Value_in (*b2 b3*) v2 v3 ->\n    Value_in (*b1 b3*) v1 v3.\n  Proof.\n    intros.\n    inversion H0; inversion H; subst; rewrite H4; constructor.\n    (*inversion_clear H0 in H1; inversion_clear H1; try constructor.\n    rewrite <- (H _ _ _ H3 H0) in H4.\n    constructor 3 with n; auto.*)\n  Qed.\n\n  Lemma Value_in_opt_trans : forall v1 v2 v3 (*b1 b2 b3*),\n    (*FFun.is_inj b2 ->*)\n    Value_in_opt (*b1 b2*) v1 v2->\n    Value_in_opt (*b2 b3*) v2 v3 ->\n    Value_in_opt (*b1 b3*) v1 v3.\n  Proof.\n    intros.\n    inversion_clear H in H0; inversion_clear H0; try constructor.\n    (*inversion_clear H0 in H1; inversion_clear H1; try constructor.*)\n    eapply Value_in_trans; eauto.\n  Qed. \n\n  Lemma leql_join1 : forall k1 k2 k3,\n    L.leql k2 k3 ->\n    L.leql k2 (L.join k1 k3).\n  Proof.\n    intros.\n    apply L.leql_trans with (1:=H).\n    apply L.join_right.\n  Qed.\n\n  Lemma leql_join2 : forall k1 k2 k3,\n    L.leql k2 k1 ->\n    L.leql k2 (L.join k1 k3).\n  Proof.\n    intros.\n    apply L.leql_trans with (1:=H).\n    apply L.join_left.\n  Qed.\n\n  Lemma not_leql_trans : forall k1 k2 k3,\n    ~ L.leql k1 k3 ->\n    L.leql k1 k2 ->\n    ~ L.leql k2 k3.\n  Proof.\n    red; intros.\n    elim H.\n    apply L.leql_trans with (1:=H0); auto.\n  Qed.\n\n  Lemma not_leql_join1 : forall k1 k2 k3,\n    ~ L.leql k1 k3 ->\n    ~ L.leql (L.join k1 k2) k3.\n  Proof.\n    intros; apply not_leql_trans with k1; auto.\n    apply L.join_left.\n  Qed.\n\n  Lemma not_leql_join2 : forall k1 k2 k3,\n    ~ L.leql k2 k3 ->\n    ~ L.leql (L.join k1 k2) k3.\n  Proof.\n    intros; apply not_leql_trans with k2; auto.\n    apply L.join_right.\n  Qed.\n\n  Lemma leql_join_each: forall k k1 k2, L.leql (L.join k k1) k2 -> L.leql k k2 /\\ L.leql k1 k2.\n  Proof. intros.\n    split. apply L.leql_trans with (l2:=L.join k k1); auto. apply L.join_left.\n    apply L.leql_trans with (l2:=L.join k k1); auto. apply L.join_right.\n  Qed.\n\n(*   Lemma Reg_in_inv : forall obs k k' v v',\n    Reg_in obs k k' v v' <->\n      (~(L.leql k obs) /\\ ~(L.leql k' obs)) \\/ (Value_in v v').\n  Proof.\n    intros. split. \n      intros. inversion H. left; auto. right; auto.\n      intros. inversion H.\n      apply Reg_high_in; inversion H0; auto.\n      apply Reg_nhigh_in; auto.\n  Qed.\n\n  Lemma Reg_in_sym : forall obs k k' v v', \n    Reg_in obs k k' v v' -> \n    Reg_in obs k' k v' v.\n  Proof.\n    intros.\n    inversion H.\n      constructor 1; auto.\n      constructor 2; auto.\n      apply Value_in_sym; auto.\n  Qed.  \n\n  Lemma Reg_in_refl : forall obs k v, Reg_in obs k k v v.\n  Proof. intros. constructor 2. destruct v. constructor; auto. Qed.\n\n  Lemma Reg_in_monotony_left : forall obs k k' v v' k'',\n    Reg_in obs k k' v v' ->\n    L.leql k k'' -> \n    Reg_in obs k'' k' v v'.\n  Proof.\n    intros. inversion H; subst. \n    constructor 1; auto. \n    apply not_leql_trans with (k1:=k) (k3:=obs) (k2:=k'') in H1; auto. \n    constructor 2; auto.\n  Qed.  *)\n\n (* Lemma Regs_in_inv : forall r1 r2 rt1 rt2,\n    Regs_in kobs r1 r2 rt1 rt2 -> forall (rn:DEX_Reg), In rn (VarMap.dom _ rt1) -> In rn (VarMap.dom _ rt2) ->\n    (forall k k', Some k = VarMap.get _ rt1 rn -> Some k' = VarMap.get _ rt2 rn ->\n      (~L.leql k kobs /\\ ~L.leql k' kobs)) \\/ \n    (forall v v', (Some v = DEX_Registers.get r1 rn /\\ Some v' = DEX_Registers.get r2 rn /\\ Value_in v v')).\n  Proof.\n    intros.\n    inversion H.\n    specialize (H3 rn H0 H1).\n    apply VarMap.in_dom_get_some in H0.\n    apply VarMap.in_dom_get_some in H1.\n    apply not_none_some with (A:=L.t) (a:=VarMap.get L.t rt1 rn) in H0. admit. apply not_none_some with (A:=L.t) in H1.\n    destruct H0; destruct H1.\n    apply H4 in H0.\n    inversion H0.\n    \n    left; split; auto.\n    right. repeat (split; auto). \n    admit. admit.\n subst. admit. split; auto. *)\n      \n\n  Lemma Reg_in_sym : forall obs r r' rt rt' rn, \n    Reg_in obs r r' rt rt' rn -> \n    Reg_in obs r' r rt' rt rn.\n  Proof.\n    intros.\n    inversion H.\n      constructor 1 with (k:=k') (k':=k); auto.\n      constructor 2; auto.\n      apply Value_in_opt_sym; auto.\n  Qed.  \n\n Lemma Regs_in_sym : forall r1 r2 rt1 rt2,\n    Regs_in kobs r1 r2 rt1 rt2 ->\n    Regs_in kobs r2 r1 rt2 rt1.\n  Proof.\n    induction 1.\n    constructor. apply eq_set_sym; auto.\n    intros.\n    apply Reg_in_sym; auto.\n(*     apply H0 with (k:=k') (k':=k) (v:=v') (v':=v) in H3; auto. *)\n  Qed.\n\n  Lemma st_in_sym : forall (*lvt b b'*) rt rt' r r',\n    st_in kobs (*newArT ft lvt b b'*) rt rt' r r' ->\n    st_in kobs (*newArT ft lvt b' b*) rt' rt r' r.\n  Proof.\n    intros.\n    inversion_clear H; constructor.\n    (*apply localvar_in_sym; auto.\n    apply os_in_sym; auto.\n    apply hp_in_sym; auto.*)\n    apply Regs_in_sym; auto.\n  Qed.\n  Implicit Arguments st_in_sym.\n\n  Lemma Value_in_opt_some_aux: forall ov ov' v v' (*b b'*), \n    Value_in (*b b'*) v v' -> \n    ov=(Some v)  -> \n    ov'= (Some v') -> \n    Value_in_opt (*b b'*) ov ov'.\n  Proof.\n    intros;  subst; constructor; auto.\n  Qed.\n\n  Lemma ex_comp_Z : forall x y z:Z,\n    (x <= y < z \\/ ~ x <= y < z)%Z.\n  Proof.\n    intros.\n    destruct (Z_le_dec x y).\n    destruct (Z_lt_dec y z); intuition.\n    intuition.\n  Qed.\n\n  Lemma nth_error_none_length : forall (A:Set) (l:list A) i,\n    nth_error l i = None -> (length l <= i)%nat.\n  Proof.\n    induction l; destruct i; simpl; intros; try omega. \n    discriminate.\n    generalize (IHl _ H); omega.\n  Qed.\n\n  Lemma nth_error_some_length : forall (A:Set) (l:list A) i a,\n    nth_error l i = Some a -> (length l > i)%nat.\n  Proof.\n    induction l; destruct i; simpl; intros; try discriminate; try omega. \n    generalize (IHl _ _ H); omega.\n  Qed.\n\n  Hint Resolve \n    not_leql_join1 (*not_leql_join1'*) not_leql_join2 (*not_leql_join2'*) not_leql_trans \n    L.join_left L.join_right (*leql'_leql*)\n    L.leql_trans : lattice.\n\n\nEnd p.\n\n  Hint Resolve \n    not_leql_join1 (*not_leql_join1'*) not_leql_join2 (*not_leql_join2'*) not_leql_trans \n    L.join_left L.join_right (*leql'_leql*)\n    L.leql_trans : lattice.\n\n\n(* \n*** Local Variables: ***\n*** coq-prog-name: \"~/Soft/src/coq-8.2pl1/bin/coqtop\" ***\n*** coq-prog-args: (\"-emacs-U\" \"-I\" \"../Library\" \"-I\" \"../Library/Map/\") ***\n*** End: ***\n *)", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/DEX_IndistRelations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.2073101377937289}}
{"text": "(* F1Prop.v *)\n\nRequire Import Utf8 QArith NPeano Sorted.\n\nRequire Import Misc.\nRequire Import QbarM.\nRequire Import SplitList.\nRequire Import Field2.\nRequire Import Fpolynomial.\nRequire Import Fsummation.\nRequire Import Newton.\nRequire Import ConvexHullMisc.\nRequire Import ConvexHull.\nRequire Import Puiseux_base.\nRequire Import Power_series.\nRequire Import Puiseux_series.\nRequire Import Ps_add.\nRequire Import Ps_mul.\nRequire Import Ps_div.\nRequire Import PSpolynomial.\nRequire Import AlgCloCharPol.\nRequire Import CharactPolyn.\nRequire Import F1Eq.\nRequire Import PosOrder.\nRequire Import InK1m.\n\nSet Implicit Arguments.\n\nSection theorems.\n\nVariable α : Type.\nVariable R : ring α.\nVariable K : field R.\nVariable acf : algeb_closed_field K.\n\nTheorem eq_poly_lap_add : ∀ α (R : ring α) la lb,\n  (POL la + POL lb = POL (la + lb)%lap)%pol.\nProof. reflexivity. Qed.\n\nTheorem ps_poly_lap_summ : ∀ f g l,\n  (∀ i, (f i = POL (g i))%pspol)\n  → (ps_pol_summ ps_field l f = POL (ps_lap_summ ps_field l g))%pspol.\nProof.\nintros f g l Hi.\nunfold ps_pol_eq, ps_pol in Hi.\nunfold ps_pol_eq, ps_pol, ps_pol_summ, ps_lap_summ.\ninduction l as [| x]; [ reflexivity | simpl ].\nrewrite <- eq_poly_lap_add.\nrewrite <- IHl, <- Hi.\nreflexivity.\nQed.\n\n(* things similar with order_add, perhaps good theorems? *)\nTheorem order_add_eq_min : ∀ a b,\n  (order a ≠ order b)%Qbar\n  → (order (a + b) = Qbar.min (order a) (order b))%Qbar.\nProof.\nintros a b Hab.\nset (k₁ := ps_polydo b).\nset (k₂ := ps_polydo a).\nset (v₁ := (ps_ordnum a * Zpos k₁)%Z).\nset (v₂ := (ps_ordnum b * Zpos k₂)%Z).\nset (n₁ := Z.to_nat (v₂ - Z.min v₁ v₂)).\nset (n₂ := Z.to_nat (v₁ - Z.min v₁ v₂)).\npose proof (ps_adjust_eq K a n₂ k₁) as Ha.\npose proof (ps_adjust_eq K b n₁ k₂) as Hb.\nsymmetry.\nrewrite Hb in Hab.\nrewrite Ha in Hab.\nrewrite Hb in |- * at 1.\nrewrite Ha in |- * at 1.\nrewrite eq_ps_add_add₂.\nunfold ps_add₂.\nunfold adjust_ps_from.\nfold k₁ k₂.\nfold v₁ v₂.\nrewrite Z.min_comm.\nfold n₁ n₂.\nremember (adjust_ps n₂ k₁ a) as pa eqn:Hpa .\nremember (adjust_ps n₁ k₂ b) as pb eqn:Hpb .\nremember (order pa) as opa eqn:Hopa .\nremember (order pb) as opb eqn:Hopb .\nprogress unfold order in Hopa, Hopb.\nprogress unfold order; simpl.\nremember (ps_terms pa) as sa eqn:Hsa .\nremember (ps_terms pb) as sb eqn:Hsb .\nremember (series_order sa 0) as na eqn:Hna .\nremember (series_order sb 0) as nb eqn:Hnb .\nremember (series_order (sa + sb)%ser 0) as nc eqn:Hnc .\nsymmetry in Hna, Hnb, Hnc.\nclear Hsa Hsb Ha Hb.\napply series_order_iff in Hna; simpl in Hna.\napply series_order_iff in Hnb; simpl in Hnb.\napply series_order_iff in Hnc; simpl in Hnc.\ndestruct na as [na| ].\n destruct Hna as (Hina, Hna).\n destruct nb as [nb| ].\n  destruct Hnb as (Hinb, Hnb).\n  subst pa pb; simpl in Hopa, Hopb; simpl.\n  subst k₁ k₂ n₁ n₂; simpl in Hopa, Hopb; simpl.\n  subst v₁ v₂; simpl in Hopa, Hopb.\n  rewrite Pos.mul_comm in Hopb.\n  rewrite Z2Nat.id in Hopa.\n   rewrite Z2Nat.id in Hopb.\n    rewrite Z.sub_sub_distr in Hopa, Hopb.\n    rewrite Z.sub_diag, Z.add_0_l in Hopa, Hopb.\n    unfold cm_factor; simpl.\n    rewrite Z2Nat.id.\n     rewrite Z.sub_sub_distr.\n     rewrite Z.sub_diag, Z.add_0_l.\n     subst opa opb; simpl.\n     rewrite Qmin_same_den.\n     unfold Qeq; simpl.\n     simpl in Hab.\n     unfold Qeq in Hab; simpl in Hab.\n     destruct nc as [nc| ].\n      destruct Hnc as (Hinc, Hnc).\n      apply Z.mul_cancel_r; [ apply Pos2Z_ne_0 | idtac ].\n      rewrite Z.add_min_distr_l.\n      apply Z.add_cancel_l.\n      rewrite <- Nat2Z.inj_min.\n      apply Nat2Z.inj_iff.\n      destruct (eq_nat_dec (min na nb) nc) as [| H]; [ assumption | idtac ].\n      exfalso; apply Hab; clear Hab.\n      apply Z.mul_cancel_r; [ apply Pos2Z_ne_0 | idtac ].\n      apply Z.add_cancel_l.\n      apply Nat2Z.inj_iff.\n      destruct (eq_nat_dec na nb) as [| Hab]; [ assumption | idtac ].\n      exfalso; apply H; clear H.\n      destruct (le_dec na nb) as [H₁| H₁].\n       apply Nat_le_neq_lt in H₁; [ idtac | assumption ].\n       destruct (lt_dec na nc) as [H₂| H₂].\n        apply Hinb in H₁.\n        apply Hinc in H₂.\n        rewrite H₁, rng_add_0_r in H₂; contradiction.\n\n        apply Nat.nlt_ge in H₂.\n        destruct (eq_nat_dec na nc) as [H₃| H₃].\n         rewrite Nat.min_l; [ assumption | idtac ].\n         apply Nat.lt_le_incl; assumption.\n\n         apply Nat.neq_sym in H₃.\n         apply Nat_le_neq_lt in H₂; [ idtac | assumption ].\n         eapply Nat.lt_trans in H₁; [ idtac | eassumption ].\n         apply Hina in H₂.\n         apply Hinb in H₁.\n         rewrite H₂, H₁ in Hnc.\n         rewrite rng_add_0_l in Hnc.\n         exfalso; apply Hnc; reflexivity.\n\n       apply Nat.nle_gt in H₁.\n       destruct (lt_dec nb nc) as [H₂| H₂].\n        apply Hina in H₁.\n        apply Hinc in H₂.\n        rewrite H₁, rng_add_0_l in H₂; contradiction.\n\n        apply Nat.nlt_ge in H₂.\n        destruct (eq_nat_dec nb nc) as [H₃| H₃].\n         rewrite Nat.min_r; [ assumption | idtac ].\n         apply Nat.lt_le_incl; assumption.\n\n         apply Nat.neq_sym in H₃.\n         apply Nat_le_neq_lt in H₂; [ idtac | assumption ].\n         eapply Nat.lt_trans in H₁; [ idtac | eassumption ].\n         apply Hinb in H₂.\n         apply Hina in H₁.\n         rewrite H₂, H₁ in Hnc.\n         rewrite rng_add_0_l in Hnc.\n         exfalso; apply Hnc; reflexivity.\n\n      simpl in Hab.\n      apply Hab; clear Hab.\n      apply Z.mul_cancel_r; [ apply Pos2Z_ne_0 | idtac ].\n      apply Z.add_cancel_l.\n      apply Nat2Z.inj_iff.\n      destruct (eq_nat_dec na nb) as [| Hab]; [ assumption | idtac ].\n      destruct (le_dec na nb) as [H₁| H₁].\n       apply Nat_le_neq_lt in H₁; [ idtac | assumption ].\n       apply Hinb in H₁.\n       pose proof (Hnc na) as H.\n       rewrite H₁, rng_add_0_r in H.\n       contradiction.\n\n       apply Nat.nle_gt in H₁.\n       apply Hina in H₁.\n       pose proof (Hnc nb) as H.\n       rewrite H₁, rng_add_0_l in H.\n       contradiction.\n\n     rewrite <- Z.sub_max_distr_l.\n     rewrite Z.sub_diag.\n     rewrite <- Z2Nat_id_max.\n     apply Nat2Z.is_nonneg.\n\n    rewrite <- Z.sub_max_distr_l.\n    rewrite Z.sub_diag.\n    rewrite Z.max_comm, <- Z2Nat_id_max.\n    apply Nat2Z.is_nonneg.\n\n   rewrite <- Z.sub_max_distr_l.\n   rewrite Z.sub_diag.\n   rewrite <- Z2Nat_id_max.\n   apply Nat2Z.is_nonneg.\n\n  subst opb; simpl.\n  rewrite Qbar.min_comm; simpl.\n  destruct nc as [nc| ].\n   destruct Hnc as (Hinc, Hnc).\n   subst opa.\n   apply Qbar.qfin_inj_wd.\n   unfold Qeq; simpl.\n   apply Z.mul_cancel_r; [ apply Pos2Z_ne_0 | idtac ].\n   apply Z.add_cancel_l.\n   apply Nat2Z.inj_iff.\n   destruct (eq_nat_dec na nc) as [| Hac]; [ assumption | idtac ].\n   destruct (le_dec na nc) as [H₁| H₁].\n    apply Nat_le_neq_lt in H₁; [ idtac | assumption ].\n    apply Hinc in H₁.\n    rewrite Hnb, rng_add_0_r in H₁.\n    contradiction.\n\n    apply Nat.nle_gt in H₁.\n    apply Hina in H₁.\n    rewrite H₁, Hnb, rng_add_0_l in Hnc.\n    exfalso; apply Hnc; reflexivity.\n\n   pose proof (Hnc na) as H.\n   rewrite Hnb, rng_add_0_r in H.\n   contradiction.\n\n subst opa; simpl.\n destruct nb as [nb| ].\n  destruct Hnb as (Hinb, Hnb).\n  destruct nc as [nc| ].\n   destruct Hnc as (Hinc, Hnc).\n   destruct (eq_nat_dec nb nc) as [| Hbc]; [ subst nb | idtac ].\n    subst.\n    subst n₁ n₂ v₁ v₂ k₁ k₂; simpl.\n    unfold cm_factor; simpl.\n    rewrite Z2Nat.id.\n     rewrite Z2Nat.id.\n      do 2 rewrite Z.sub_sub_distr.\n      do 2 rewrite Z.sub_diag, Z.add_0_l.\n      rewrite Pos.mul_comm; reflexivity.\n\n      rewrite <- Z.sub_max_distr_l.\n      rewrite Z.sub_diag.\n      rewrite <- Z2Nat_id_max.\n      apply Nat2Z.is_nonneg.\n\n     rewrite <- Z.sub_max_distr_l.\n     rewrite Z.sub_diag.\n     rewrite Z.max_comm, <- Z2Nat_id_max.\n     apply Nat2Z.is_nonneg.\n\n    destruct (le_dec nb nc) as [H₁| H₁].\n     apply Nat_le_neq_lt in H₁; [ idtac | assumption ].\n     apply Hinc in H₁.\n     rewrite Hna, rng_add_0_l in H₁.\n     contradiction.\n\n     apply Nat.nle_gt in H₁.\n     apply Hinb in H₁.\n     rewrite Hna, rng_add_0_l in Hnc.\n     contradiction.\n\n   pose proof (Hnc nb) as H.\n   rewrite Hna, rng_add_0_l in H.\n   contradiction.\n\n  subst opb.\n  exfalso; apply Hab; reflexivity.\nQed.\n\nTheorem ps_lap_nth_x_le_pow_mul : ∀ la m n,\n  (n ≤ m)%nat\n  → (ps_lap_nth m ([0; 1 … []] ^ n * la) = ps_lap_nth (m - n) la)%ps.\nProof.\nintros la m n Hnm.\nrevert m Hnm.\ninduction n; intros.\n progress unfold ps_lap_pow; simpl.\n progress unfold ps_lap_mul.\n rewrite lap_mul_1_l.\n rewrite Nat.sub_0_r.\n reflexivity.\n\n rewrite <- Nat.add_1_l.\n unfold ps_lap_pow.\n rewrite lap_power_add.\n rewrite lap_power_1.\n progress unfold ps_lap_mul.\n rewrite <- lap_mul_assoc.\n rewrite lap_mul_cons_l.\n rewrite lap_eq_0, lap_mul_nil_l, lap_add_nil_l, lap_mul_1_l.\n destruct m; [ exfalso; revert Hnm; apply Nat.nlt_0_r | simpl ].\n apply le_S_n in Hnm.\n apply IHn; assumption.\nQed.\n\nTheorem ps_lap_nth_x_gt_pow_mul : ∀ la m n,\n  (m < n)%nat\n  → (ps_lap_nth m ([0; 1 … []] ^ n * la) = 0)%ps.\nProof.\nintros la m n Hmn.\nrevert m Hmn.\ninduction n; intros.\n exfalso; revert Hmn; apply Nat.nlt_0_r.\n\n unfold ps_lap_mul, ps_lap_pow; simpl.\n rewrite <- lap_mul_assoc.\n rewrite lap_mul_cons_l.\n rewrite lap_eq_0, lap_mul_nil_l, lap_add_nil_l, lap_mul_1_l.\n destruct m; [ reflexivity | idtac ].\n apply lt_S_n in Hmn.\n unfold ps_lap_nth; simpl.\n apply IHn; assumption.\nQed.\n\nTheorem ps_lap_nth_0_cons_pow : ∀ a la n,\n  (ps_lap_nth 0 ([a … la] ^ n) = a ^ n)%ps.\nProof.\nintros a la n.\ninduction n; simpl.\n progress unfold ps_lap_pow; simpl.\n reflexivity.\n\n unfold ps_lap_pow; simpl.\n unfold ps_lap_nth.\n rewrite list_nth_lap_mul; simpl.\n unfold summation; simpl.\n rewrite IHn.\n rewrite ps_add_0_r; reflexivity.\nQed.\n\nTheorem eq_1_0_all_0 : (1 = 0)%K → ∀ a, (a = 0)%K.\nProof.\nintros H a.\nrewrite <- rng_mul_1_l.\nrewrite H, rng_mul_0_l.\nreflexivity.\nQed.\n\nTheorem order_pow : ∀ a n,\n  (a ≠ 0)%ps\n  → (order (a ^ n) = qfin (Qnat n) * order a)%Qbar.\nProof.\nintros a n Ha.\ninduction n; simpl.\n remember (order a) as v eqn:Hv .\n symmetry in Hv.\n destruct v as [v| ].\n  unfold Qnat; simpl.\n  rewrite Qmult_0_l.\n  unfold ps_one.\n  rewrite ps_monom_order; [ reflexivity | idtac ].\n  intros H; apply Ha.\n  rewrite <- ps_mul_1_l.\n  unfold ps_one.\n  rewrite H, ps_zero_monom_eq.\n  rewrite ps_mul_0_l.\n  reflexivity.\n\n  exfalso; apply Ha.\n  apply order_inf; assumption.\n\n rewrite order_mul.\n rewrite IHn.\n remember (order a) as v eqn:Hv .\n symmetry in Hv.\n destruct v as [v| ]; [ simpl | reflexivity ].\n rewrite <- Nat.add_1_l.\n unfold Qnat.\n rewrite Nat2Z.inj_add, QZ_plus.\n rewrite Qmult_plus_distr_l; simpl.\n rewrite Qmult_1_l; reflexivity.\nQed.\n\nTheorem ps_lap_nth_0_apply_0 : ∀ la,\n  (ps_lap_nth 0 la = @apply_lap _ (ps_ring K) la 0)%ps.\nProof.\nintros la.\ninduction la as [| a]; [ reflexivity | simpl ].\nrewrite ps_mul_0_r, ps_add_0_l.\nreflexivity.\nQed.\n\nTheorem apply_lap_inject_K_in_Kx_monom : ∀ P c,\n  (@apply_lap _ (ps_ring K) (lap_inject_K_in_Kx P) (ps_monom c 0) =\n   ps_monom (apply_lap P c) 0)%ps.\nProof.\nintros P c.\nunfold apply_lap; simpl.\nunfold lap_inject_K_in_Kx.\nrename c into d.\nrewrite list_fold_right_map.\ninduction P as [| a]; simpl.\n rewrite ps_zero_monom_eq; reflexivity.\n\n rewrite IHP.\n rewrite ps_monom_add_l, ps_monom_mul_l.\n reflexivity.\nQed.\n\nTheorem ps_monom_0_coeff_0 : ∀ c pow, (ps_monom c pow = 0)%ps → (c = 0)%K.\nProof.\nintros c pow Hc.\napply ps_series_order_inf_iff in Hc.\napply series_order_iff in Hc; simpl in Hc.\npose proof (Hc O); assumption.\nQed.\n\nTheorem in_power_list_lt : ∀ A la h (hv : puiseux_series A) pow,\n  (h, hv) ∈ qpower_list pow la\n  → (nat_num h < pow + length la)%nat.\nProof.\nintros A la h hv pow Hh.\nunfold qpower_list in Hh.\nunfold pair_rec in Hh; simpl in Hh.\nrevert pow Hh.\ninduction la as [| a]; intros; [ contradiction | simpl ].\nsimpl in Hh.\ndestruct Hh as [Hh| Hh].\n injection Hh; clear Hh; intros; subst h hv.\n rewrite nat_num_Qnat.\n apply Nat.lt_sub_lt_add_l.\n rewrite Nat.sub_diag.\n apply Nat.lt_0_succ.\n\n rewrite Nat.add_succ_r, <- Nat.add_succ_l.\n apply IHla; assumption.\nQed.\n\nTheorem in_points_of_ps_lap_gen_lt : ∀ la pow pt,\n  pt ∈ points_of_ps_lap_gen pow la\n  → (nat_num (fst pt) < pow + length la)%nat.\nProof.\nintros la pow pt Hpt.\nunfold points_of_ps_lap_gen in Hpt.\ndestruct pt as (h, hv); simpl.\neapply in_pts_in_ppl with (def := 0%ps) in Hpt; try reflexivity.\ndestruct Hpt as (Hpt, Hord).\neapply in_power_list_lt; eassumption.\nQed.\n\nTheorem in_points_of_ps_lap_lt : ∀ la pt,\n  pt ∈ points_of_ps_lap la\n  → (nat_num (fst pt) < length la)%nat.\nProof.\nintros la pt Hpt.\napply in_points_of_ps_lap_gen_lt in Hpt.\nassumption.\nQed.\n\n(* [Walker, p. 101] «\n      Since O(āh-ah.x^αh) > αh, and O(āl.x^lγ₁) > β₁, we obtain\n         f₁(x,y₁) = b₁.y₁^r + b₂.y₁^(r+1) + ... + g(x,y₁) »\n\n   We prove here that\n         f₁(x,y₁) = y₁^r.(c₁+y)^j.Ψ(c₁+y) + g(x,y₁) »\n*)\nTheorem f₁_eq_term_with_Ψ_plus_g : ∀ f L j αj c₁ r f₁ Ψ,\n  newton_segments f = Some L\n  → ini_pt L = (Qnat j, αj)\n    → c₁ = ac_root (Φq f L)\n      → r = root_multiplicity acf c₁ (Φq f L)\n        → Ψ = quotient_phi_x_sub_c_pow_r (Φq f L) c₁ r\n          → f₁ = next_pol f (β L) (γ L) c₁\n            → (f₁ =\n               POL [0%ps; 1%ps … []] ^ r *\n               POL [ps_monom c₁ 0; 1%ps … []] ^ j *\n               POL (lap_inject_K_in_Kx (al Ψ)) ∘\n               POL [ps_monom c₁ 0; 1%ps … []] +\n               g_of_ns f L)%pspol.\nProof.\nintros f L j αj c₁ r f₁ Ψ HL Hini Hc₁ Hr HΨ Hf₁.\nsubst f₁.\nremember (g_lap_of_ns f L) as gg.\nremember Heqgg as H; clear HeqH.\nunfold g_lap_of_ns in H; subst gg.\nrewrite <- Hc₁ in H.\nremember [ini_pt L … oth_pts L ++ [fin_pt L]] as pl eqn:Hpl .\nremember (List.map (term_of_point f) pl) as tl eqn:Htl .\nremember (List.map (λ t : term α nat, power t) tl) as l₁ eqn:Hl₁ .\nremember (list_seq_except 0 (length (al f)) l₁) as l₂ eqn:Hl₂ .\nsymmetry in Hc₁.\nrewrite f₁_eq_term_with_Ψ_plus_sum with (l₂ := l₂); try eassumption.\n rewrite ps_poly_lap_summ; [ idtac | intros i; simpl; apply lap_eq_refl ].\n rewrite ps_poly_lap_summ; [ simpl | intros i; simpl; apply lap_eq_refl ].\n unfold ps_pol_add, poly_add; simpl.\n unfold ps_lap_add in H; simpl in H.\n unfold ps_lap_mul in H; simpl in H.\n progress unfold ps_lap_pow in H.\n simpl in H; rewrite <- H; clear H.\n reflexivity.\n\n apply except_split_seq; [ idtac | idtac | assumption ].\n  rewrite Hl₁, Htl, Hpl.\n  do 2 apply Sorted_map; simpl.\n  apply Sorted_fst_lt_nat_num_fst.\n   intros a Ha.\n   remember (points_of_ps_polynom f) as pts.\n   symmetry in Heqpts.\n   eapply pt_absc_is_nat; [ eassumption | idtac ].\n   eapply ns_in_init_pts; [ idtac | eassumption ].\n   rewrite <- Heqpts; assumption.\n\n   eapply ini_oth_fin_pts_sorted; eassumption.\n\n  simpl.\n  rewrite Hl₁.\n  apply List.Forall_forall; intros i Hi.\n  split; [ apply Nat.le_0_l | idtac ].\n  apply List.in_map_iff in Hi.\n  destruct Hi as (x, (Hxi, Hx)).\n  subst i.\n  rewrite Htl in Hx.\n  apply List.in_map_iff in Hx.\n  destruct Hx as (y, (Hi, Hy)).\n  subst x; simpl.\n  rename y into pt.\n  rewrite Hpl in Hy.\n  eapply ns_in_init_pts in Hy; [ idtac | eassumption ].\n  unfold points_of_ps_polynom in Hy.\n  apply in_points_of_ps_lap_lt; assumption.\nQed.\n\nTheorem nth_g_order_pos : ∀ f L h,\n  newton_segments f = Some L\n  → (order (ps_lap_nth h (g_lap_of_ns f L)) > 0)%Qbar.\nProof.\nintros f L h HL.\ndestruct (lt_dec h (length (g_lap_of_ns f L))) as [Hlt| Hge].\n eapply each_power_of_y₁_in_g_has_coeff_pos_ord; try eassumption.\n  reflexivity.\n\n  unfold g_of_ns; simpl.\n  unfold ps_lap_nth.\n  apply list_nth_in; assumption.\n\n apply Nat.nlt_ge in Hge.\n unfold ps_lap_nth.\n rewrite List.nth_overflow; [ idtac | assumption ].\n rewrite order_0; constructor.\nQed.\n\nTheorem order_nth_inject_K : ∀ la i,\n  (0 ≤ order (ps_lap_nth i (lap_inject_K_in_Kx la)))%Qbar.\nProof.\nintros la i.\nrevert i.\ninduction la as [| a]; intros; simpl.\n unfold ps_lap_nth.\n rewrite list_nth_nil.\n rewrite order_0; constructor.\n\n destruct i; [ idtac | apply IHla ].\n unfold ps_lap_nth; simpl.\n apply ps_monom_order_ge.\nQed.\n\nTheorem monom_y_plus_c_is_inject_K : ∀ c,\n  ([ps_monom c 0; 1%ps … []] = lap_inject_K_in_Kx [c; 1%K … []])%pslap.\nProof.\nintros c.\nunfold ps_lap_eq.\nreflexivity.\nQed.\n\nTheorem fold_lap_inject_K_in_Kx : ∀ la,\n  List.map (λ c : α, ps_monom c 0) la = lap_inject_K_in_Kx la.\nProof. reflexivity. Qed.\n\nTheorem lap_add_cons : ∀ α (R : ring α) a b la lb,\n  ([a … la] + [b … lb] = [(a + b)%K … la + lb])%lap.\nProof. reflexivity. Qed.\n\nTheorem lap_inject_add : ∀ la lb,\n  (lap_inject_K_in_Kx la + lap_inject_K_in_Kx lb =\n   lap_inject_K_in_Kx (la + lb)%lap)%pslap.\nProof.\nintros la lb.\nunfold lap_inject_K_in_Kx.\nrevert lb.\ninduction la as [| a]; intros; simpl.\n progress unfold ps_lap_add.\n rewrite lap_add_nil_l; reflexivity.\n\n destruct lb as [| b]; simpl.\n  progress unfold ps_lap_add.\n  rewrite lap_add_nil_r; reflexivity.\n\n  progress unfold ps_lap_add.\n  rewrite lap_add_cons.\n  constructor; [ simpl | apply IHla ].\n  rewrite ps_monom_add; reflexivity.\nQed.\n\nTheorem lap_inject_mul : ∀ la lb,\n  (lap_inject_K_in_Kx la * lap_inject_K_in_Kx lb =\n   lap_inject_K_in_Kx (la * lb)%lap)%pslap.\nProof.\nintros la lb.\nunfold lap_inject_K_in_Kx.\nrevert lb.\ninduction la as [| a]; intros; simpl.\n progress unfold ps_lap_mul.\n do 2 rewrite lap_mul_nil_l; reflexivity.\n\n destruct lb as [| b]; simpl.\n  progress unfold ps_lap_mul.\n  do 2 rewrite lap_mul_nil_r; reflexivity.\n\n  progress unfold ps_lap_mul.\n  do 2 rewrite lap_mul_cons; simpl.\n  constructor; [ simpl; apply ps_monom_mul | idtac ].\n  symmetry.\n  eapply ps_lap_eq_trans; [ apply lap_add_map_ps | ].\n  unfold ps_lap_mul in IHla.\n  unfold ps_lap_eq in IHla.\n  rewrite IHla.\n  progress unfold ps_lap_add.\n  simpl.\n  rewrite ps_zero_monom_eq.\n  apply lap_add_compat; [ idtac | reflexivity ].\n  eapply ps_lap_eq_trans; [ apply lap_add_map_ps | ].\n  apply lap_add_compat.\n   eapply ps_lap_eq_trans; [ apply lap_mul_map_ps | reflexivity ].\n   eapply ps_lap_eq_trans; [ apply lap_mul_map_ps | reflexivity ].\nQed.\n\nTheorem lap_inject_comp : ∀ la lb,\n  (lap_inject_K_in_Kx la ∘ lap_inject_K_in_Kx lb =\n   lap_inject_K_in_Kx (lap_compose la lb))%pslap.\nProof.\nintros la lb.\nprogress unfold lap_inject_K_in_Kx; simpl.\nprogress unfold ps_lap_comp.\nprogress unfold lap_compose.\nrevert lb.\ninduction la as [| a]; intros; [ reflexivity | simpl ].\nrewrite IHla.\ndo 3 rewrite fold_lap_inject_K_in_Kx.\nrewrite fold_ps_lap_mul.\nrewrite lap_inject_mul.\nrewrite <- lap_inject_add.\nreflexivity.\nQed.\n\n(* [Walker, p 101] « O(bi) ≥ 0,  i = 0,...,n » *)\nTheorem order_bbar_nonneg : ∀ f L c₁ r f₁,\n  newton_segments f = Some L\n  → c₁ = ac_root (Φq f L)\n    → r = root_multiplicity acf c₁ (Φq f L)\n      → f₁ = next_pol f (β L) (γ L) c₁\n        → ∀ i, (order (ps_poly_nth i f₁) ≥ 0)%Qbar.\nProof.\nintros f L c₁ r f₁ HL Hc₁ Hr Hf₁ i.\nremember (quotient_phi_x_sub_c_pow_r (Φq f L) c₁ r) as Ψ eqn:HΨ .\nremember HL as Hini; clear HeqHini.\napply exists_ini_pt_nat in Hini.\ndestruct Hini as (j, (αj, Hini)).\nrewrite f₁_eq_term_with_Ψ_plus_g; try eassumption.\nunfold ps_poly_nth; simpl.\nrewrite fold_ps_lap_add.\nrewrite ps_lap_nth_add.\nrewrite fold_ps_lap_comp.\neapply Qbar.le_trans; [ idtac | apply order_add ].\napply Qbar.min_glb.\n rewrite <- lap_mul_assoc.\n rewrite fold_ps_lap_mul, fold_ps_lap_pow.\n destruct (le_dec r i) as [Hle| Hgt].\n  rewrite ps_lap_nth_x_le_pow_mul; [ idtac | assumption ].\n  progress unfold ps_lap_comp.\n  rewrite monom_y_plus_c_is_inject_K.\n  rewrite fold_ps_lap_pow.\n  rewrite lap_power_map_ps.\n  rewrite fold_ps_lap_comp.\n  rewrite lap_inject_comp.\n  rewrite fold_ps_lap_mul.\n  rewrite lap_inject_mul.\n  apply order_nth_inject_K.\n\n  apply Nat.nle_gt in Hgt.\n  rewrite ps_lap_nth_x_gt_pow_mul; [ idtac | assumption ].\n  rewrite order_0; constructor.\n\n apply Qbar.lt_le_incl.\n apply nth_g_order_pos; assumption.\nQed.\n\n(* [Walker, p 101] « O(bi) > 0,  i = 0,...,r-1 » *)\nTheorem order_bbar_pos : ∀ f L c₁ r f₁,\n  newton_segments f = Some L\n  → c₁ = ac_root (Φq f L)\n    → r = root_multiplicity acf c₁ (Φq f L)\n      → f₁ = next_pol f (β L) (γ L) c₁\n        → ∀ i, (i < r)%nat\n          → (order (ps_poly_nth i f₁) > 0)%Qbar.\nProof.\nintros f L c₁ r f₁ HL Hc₁ Hr Hf₁ i Hir.\nremember (quotient_phi_x_sub_c_pow_r (Φq f L) c₁ r) as Ψ eqn:HΨ .\nremember HL as Hini; clear HeqHini.\napply exists_ini_pt_nat in Hini.\ndestruct Hini as (j, (αj, Hini)).\nrewrite f₁_eq_term_with_Ψ_plus_g; try eassumption.\nunfold ps_poly_nth; simpl.\nrewrite fold_ps_lap_add.\nrewrite ps_lap_nth_add.\nrewrite fold_ps_lap_comp.\neapply Qbar.lt_le_trans; [ idtac | apply order_add ].\napply Qbar.min_glb_lt.\n rewrite <- lap_mul_assoc.\n rewrite fold_ps_lap_mul.\n rewrite fold_ps_lap_pow.\n rewrite ps_lap_nth_x_gt_pow_mul; [ idtac | assumption ].\n rewrite order_0; constructor.\n\n apply nth_g_order_pos; assumption.\nQed.\n\nTheorem char_pol_root_ne_0 : ∀ f L m c₁,\n  newton_segments f = Some L\n  → pol_in_K_1_m f m\n  → c₁ = ac_root (Φq f L)\n  → (c₁ ≠ 0)%K.\nProof.\nintros f L m c₁ HL Hm Hc₁.\nremember HL as Happ; clear HeqHapp.\neapply cpol_degree_ge_1 with (K := K) in Happ; eauto .\napply ac_prop_root in Happ.\nrewrite <- Hc₁ in Happ.\nremember HL as Hini; clear HeqHini.\napply exists_ini_pt_nat in Hini.\ndestruct Hini as (j, (αj, Hini)).\nintros Hc; rewrite Hc in Happ.\nunfold apply_poly in Happ; simpl in Happ.\nrewrite Nat.sub_diag, list_pad_0 in Happ.\nsimpl in Happ.\nrewrite rng_mul_0_r, rng_add_0_l in Happ.\nrevert Happ.\neapply ord_coeff_non_zero_in_newt_segm; eauto .\nrewrite Hini; left; simpl.\nrewrite nat_num_Qnat; reflexivity.\nQed.\n\n(* [Walker, p 101] « O(br) = 0 » *)\nTheorem order_bbar_r_is_0 : ∀ f L m c₁ r f₁,\n  newton_segments f = Some L\n  → pol_in_K_1_m f m\n  → c₁ = ac_root (Φq f L)\n  → r = root_multiplicity acf c₁ (Φq f L)\n  → f₁ = next_pol f (β L) (γ L) c₁\n  → (order (ps_poly_nth r f₁) = 0)%Qbar.\nProof.\nintros f L m c₁ r f₁ HL Hm Hc₁ Hr Hf₁.\nremember (quotient_phi_x_sub_c_pow_r (Φq f L) c₁ r) as Ψ eqn:HΨ .\nremember HL as Hini; clear HeqHini.\napply exists_ini_pt_nat in Hini.\ndestruct Hini as (j, (αj, Hini)).\nrewrite f₁_eq_term_with_Ψ_plus_g; try eassumption.\nunfold ps_poly_nth; simpl.\nremember ([0%ps; 1%ps … []] ^ r)%pslap as yr.\nremember ([ps_monom c₁ 0; 1%ps … []] ^ j)%pslap as ycj.\nremember (lap_inject_K_in_Kx (al Ψ)) as psi.\nremember [ps_monom c₁ 0; 1%ps … []] as yc.\nassert (order (ps_lap_nth r (yr * ycj * psi ∘ yc)) = 0)%Qbar as Hor.\n subst yr ycj psi yc.\n progress unfold ps_lap_mul.\n rewrite <- lap_mul_assoc.\n do 2 rewrite fold_ps_lap_mul.\n erewrite ps_lap_nth_x_le_pow_mul; [ idtac | reflexivity ].\n rewrite Nat.sub_diag.\n progress unfold ps_lap_mul.\n progress unfold lap_mul.\n progress unfold ps_lap_nth; simpl.\n rewrite list_nth_lap_convol_mul; [ idtac | reflexivity ].\n unfold summation; simpl.\n rewrite ps_add_0_r.\n rewrite order_mul.\n rewrite fold_ps_lap_nth.\n rewrite ps_lap_nth_0_cons_pow.\n rewrite order_pow.\n  rewrite ps_monom_order.\n   rewrite Qbar.mul_0_r; [ idtac | intros HH; discriminate HH ].\n   rewrite Qbar.add_0_l.\n   rewrite fold_ps_lap_nth.\n   rewrite ps_lap_nth_0_apply_0.\n   unfold ps_lap_comp.\n   rewrite apply_lap_compose.\n   unfold apply_lap at 2; simpl.\n   rewrite ps_mul_0_l, ps_add_0_l.\n   rewrite ps_mul_0_r, ps_add_0_l.\n   rewrite apply_lap_inject_K_in_Kx_monom.\n   rewrite ps_monom_order; [ reflexivity | idtac ].\n   eapply psi_c₁_ne_0 in HΨ; eassumption.\n\n   eapply char_pol_root_ne_0; eassumption.\n\n  intros HH.\n  apply ps_monom_0_coeff_0 in HH.\n  revert HH.\n  eapply char_pol_root_ne_0; eassumption.\n\n subst yr ycj psi yc.\n rewrite fold_ps_lap_add.\n rewrite ps_lap_nth_add.\n rewrite fold_ps_lap_comp.\n rewrite order_add_eq_min; rewrite Hor.\n rewrite Qbar.min_l; [ reflexivity | idtac ].\n  apply Qbar.lt_le_incl.\n  apply nth_g_order_pos; assumption.\n\n  apply Qbar.lt_neq.\n  apply nth_g_order_pos; assumption.\nQed.\n\nTheorem exists_pol_ord : ∀ f, ∃ m,\n  m = ps_pol_com_polydo f ∧ pol_in_K_1_m f m.\nProof.\nintros f.\nunfold pol_in_K_1_m.\nremember (ps_pol_com_polydo f) as m eqn:Hm.\nexists m; split; [ reflexivity | ].\napply ps_lap_forall_forall.\n intros a b Hab H.\n rewrite <- Hab; assumption.\n\n intros a Ha.\n unfold ps_pol_com_polydo in Hm.\n remember (al f) as la; clear Heqla.\n revert a m Ha Hm.\n induction la as [| b]; intros; [ contradiction | idtac ].\n simpl in Ha.\n destruct Ha as [(Hbla, Hba)| Ha].\n  constructor.\n  simpl in Hm.\n  remember (ps_lap_com_polydo la) as m' eqn:Hm' .\n  exists (adjust_ps 0 m' b).\n  split; [ idtac | simpl; rewrite Pos.mul_comm; symmetry; assumption ].\n  transitivity b; [ idtac | assumption ].\n  symmetry; apply ps_adjust_eq.\n\n  subst m; simpl.\n  apply in_K_1_m_lap_mul_r_compat.\n  apply IHla; [ apply Ha | reflexivity ].\nQed.\n\n(* [Walker, p 101] «\n     O(bi) ≥ 0,  i = 0,...,n\n     O(bi) > 0,  i = 0,...,r-1\n     O(br) = 0\n   »\n*)\nTheorem f₁_orders : ∀ f L c₁ r f₁,\n  newton_segments f = Some L\n  → c₁ = ac_root (Φq f L)\n  → r = root_multiplicity acf c₁ (Φq f L)\n  → f₁ = next_pol f (β L) (γ L) c₁\n  → (∀ i, (order (ps_poly_nth i f₁) ≥ 0)%Qbar)\n    ∧ (∀ i, (i < r)%nat → (order (ps_poly_nth i f₁) > 0)%Qbar)\n    ∧ (order (ps_poly_nth r f₁) = 0)%Qbar.\nProof.\nintros f L c₁ r f₁ HL Hc₁ Hr Hf₁.\nsplit; [ eapply order_bbar_nonneg; eassumption | idtac ].\nsplit; [ eapply order_bbar_pos; eassumption | idtac ].\npose proof (exists_pol_ord f) as H.\ndestruct H as (m, (Hm, Hp)).\neapply order_bbar_r_is_0; eassumption.\nQed.\n\nEnd theorems.\n", "meta": {"author": "roglo", "repo": "puiseuxth", "sha": "5b1cdc4d42e3585f5fdd57431cc06a3ffcdc3fb5", "save_path": "github-repos/coq/roglo-puiseuxth", "path": "github-repos/coq/roglo-puiseuxth/puiseuxth-5b1cdc4d42e3585f5fdd57431cc06a3ffcdc3fb5/coq/F1Prop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.20730310292648277}}
{"text": "(** This file implements an interface to [expr] that\n ** makes star, emp, and pure assertions apparent.\n **)\n(* Require Import ExtLib.Data.Positive. *)\nRequire Import ExtLib.Data.Fun.\nRequire Import ExtLib.Data.List.\nRequire Import ExtLib.Data.Option.\nRequire Import ExtLib.Structures.Traversable.\nRequire Import ExtLib.Tactics.\nRequire Import BILogic Pure.\nRequire Import MirrorCore.EnvI.\nRequire Import MirrorCore.SymI.\nRequire Import MirrorCore.TypesI.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.Lambda.AppN.\nRequire Import MirrorCore.Lambda.TypedFoldApp.\n(*\nRequire Import MirrorCore.Ext.Expr.\nRequire Import MirrorCore.Ext.AppFull.\n*)\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\n(** NOTE: This could work on arbitrary expr's **)\nSection seplog_fold.\n  Variable typ : Type.\n  Variable RType_typ : RType typ.\n  Variable Typ2_Fun : Typ2 _ Fun.\n  Variable sym : Type.\n  Variable RSym_sym : RSym sym.\n\n  Let tyArr : typ -> typ -> typ := @typ2 _ _ _ _.\n\n  Let Expr_expr := @Expr_expr typ sym _ _ _.\n  Local Existing Instance Expr_expr.\n\n  Variable T : Type.\n  Variable SL : typ.\n\n  Record SepLogArgs : Type :=\n  { do_other : expr typ sym -> list (expr typ sym * T) -> T\n  ; do_pure : expr typ sym -> T\n  ; do_emp : T\n  ; do_star : T -> T -> T\n  }.\n\n  Record SepLogSpec : Type :=\n  { is_pure : expr typ sym -> bool\n  ; is_emp : expr typ sym -> bool\n  ; is_star : expr typ sym -> bool\n  }.\n\n  Variable sla : SepLogArgs.\n  Variable sls : SepLogSpec.\n\n  Record SepLogSpecOk (sls : SepLogSpec)\n         (OPS : ILogic.ILogicOps (typD SL))\n         (BI : BILOperators (typD SL)) : Type :=\n  { _PureOp : @PureOp (typD SL)\n  ; _Pure : @Pure _ OPS BI _PureOp\n  ; His_pure : forall e,\n                 sls.(is_pure) e = true ->\n                 forall us vs val,\n                   exprD us vs e SL = Some val ->\n                   pure val\n  ; His_emp : forall e,\n                sls.(is_emp) e = true ->\n                forall us vs,\n                  exprD us vs e SL = Some empSP\n  ; His_star : forall e,\n                 sls.(is_star) e = true ->\n                 forall us vs,\n                   exprD us vs e (tyArr SL (tyArr SL SL)) =\n                   Some match eq_sym (typ2_cast SL (tyArr SL SL)) in _ = t\n                              return t\n                        with\n                          | eq_refl =>\n                            match eq_sym (typ2_cast SL SL) in _ = t\n                                  return _ -> t\n                            with\n                              | eq_refl => sepSP\n                            end\n                        end\n  }.\n\n  Record SepLogArgsOk (R_t : expr typ sym -> T -> tenv typ -> tenv typ -> Prop) :=\n  { otherOk\n    : forall e es tus tvs,\n        @typeof_apps typ sym _ _ _ tus tvs e (List.map fst es) = Some SL ->\n        (forall x y,\n           In (x,y) es ->\n           typeof_expr tus tvs x = Some SL ->\n           R_t x y tus tvs) ->\n        R_t (apps e (List.map fst es)) (sla.(do_other) e es) tus tvs\n  ; pureOk\n    : forall e tus tvs,\n        typeof_expr tus tvs e = Some SL ->\n        sls.(is_pure) e = true ->\n        R_t e (sla.(do_pure) e) tus tvs\n  ; empOk\n    : forall e tus tvs,\n        typeof_sym e = Some SL ->\n        sls.(is_emp) (Inj e) = true ->\n        R_t (Inj e) sla.(do_emp) tus tvs\n  ; starOk\n    : forall e l r l_res r_res tus tvs,\n        typeof_sym e = Some (tyArr SL (tyArr SL SL)) ->\n        typeof_expr tus tvs l = Some SL ->\n        typeof_expr tus tvs r = Some SL ->\n        sls.(is_star) (Inj e) = true ->\n        R_t l l_res tus tvs ->\n        R_t r r_res tus tvs ->\n        R_t (apps (Inj e) (l :: r :: nil)) (sla.(do_star) l_res r_res) tus tvs\n  }.\n\n  Require Import ExtLib.Structures.Applicative.\n  Instance Applicative_Lazy : Applicative Lazy :=\n  { ap := fun _ _ f x z =>\n            match f z , x z with\n              | Some f , Some x => Some (f x)\n              | _ , _ => None\n            end\n  ; pure := fun _ x => fun _ => Some x }.\n\n  (** NOTE: This does not need to be typed! **)\n  Definition AppFullFoldArgs_SepLogArgs\n  : AppFullFoldArgs typ sym T.\n  refine\n    match sla , sls with\n      | {| do_other := do_other\n         ; do_pure := do_pure\n         ; do_star := do_star\n         ; do_emp := do_emp |}\n      , {| is_pure := is_pure\n         ; is_star := is_star\n         ; is_emp := is_emp |} =>\n        @Build_AppFullFoldArgs\n          typ sym T\n          (fun v _ _ =>\n             if is_pure (Var v) then\n               Some (do_pure (Var v))\n             else\n               if is_emp (Var v) then\n                 Some do_emp\n               else\n                 Some (do_other (Var v) nil))\n          (fun u _ _ =>\n             if is_pure (UVar u) then\n               Some (do_pure (UVar u))\n             else\n               if is_emp (UVar u) then\n                 Some do_emp\n               else\n                 Some (do_other (UVar u) nil))\n          (fun i _ _ =>\n             if is_emp (Inj i) then\n               Some do_emp\n             else\n               if is_pure (Inj i) then\n                 Some (do_pure (Inj i))\n               else\n                 Some (do_other (Inj i) nil))\n          (fun tus tvs t f fres args z =>\n             if is_star f then\n               match args with\n                 | (_,_,l) :: (_,_,r) :: nil =>\n                   match l z , r z with\n                     | Some l , Some r =>\n                       Some (do_star l r)\n                     | _ , _ => None\n                   end\n                 | _ => Some do_emp\n               end\n             else\n               let original := apps f (map (fun x => snd (fst x)) args) in\n               if is_pure original then\n                 Some (do_pure original)\n               else\n                 ap (pure (do_other f))\n                    (mapT (fun tev => let '(t,e,v) := tev in\n                                      match v tt with\n                                        | None => None\n                                        | Some v => Some (e,v)\n                                      end) args))\n          (fun tus tvs t _ e eres _ =>\n             if is_pure (Abs t e) then\n               Some (do_pure (Abs t e))\n             else\n               if is_emp (Abs t e) then\n                 Some do_emp\n               else\n                 Some (do_other (Abs t e) nil))\n    end.\n  Defined.\n\n(* TODO(gmalecha): Port the proof!\n  Section sound.\n    Hypothesis BILOps : BILOperators (typD nil SL).\n    Context R_t `{slaok : SepLogArgsOk R_t}.\n\n    Lemma atomic_ok\n    : forall ts (tus tvs : tenv typ) e (t : typ),\n        typeof_expr ts tus tvs e = Some t ->\n        t = SL ->\n        R_t e (sla.(do_other) e nil) tus tvs.\n    Proof.\n      destruct slaok. simpl; intros. subst.\n      change e with (apps e nil) at 1.\n      eapply (otherOk0 ts e nil tus tvs); simpl.\n      { unfold typeof_apps. simpl. rewrite H. reflexivity. }\n      { intuition. }\n    Qed.\n\n    Hypothesis is_starOk\n    : forall i,\n        sls.(is_star) (Inj i) = true ->\n        typeof_sym i = Some (tyArr SL (tyArr SL SL)).\n\n    Lemma lem_other\n    : forall ts0 t rs tus tvs l_res do_atomic_app0,\n        Forall2\n          (fun (t0 : typ) (x : expr sym * (tenv typ -> tenv typ -> T)) =>\n             typeof_expr tus tvs (fst x) = Some t0 /\\\n             (t0 = SL -> R_t (fst x) (snd x tus tvs) tus tvs)) ts0 rs ->\n        forall e : expr sym,\n          typeof_expr tus tvs (apps e (map fst rs)) = Some t ->\n          (fold_right tyArr t ts0 = SL -> R_t e (l_res tus tvs) tus tvs) ->\n          typeof_apps RSym_sym tus tvs e (map fst rs) = Some SL ->\n          (forall (e0 : expr sym) (es : list (expr sym * T)) (tus0 tvs0 : tenv typ),\n             typeof_apps RSym_sym tus0 tvs0 e0 (map fst es) = Some SL ->\n             (forall (x : expr sym) (y : T),\n                In (x, y) es -> typeof_expr tus0 tvs0 x = Some SL -> R_t x y tus0 tvs0) ->\n             R_t (apps e0 (map fst es)) (do_atomic_app0 e0 es) tus0 tvs0) ->\n          R_t (apps e (map fst rs))\n              (do_atomic_app0 e\n                              (map\n                                 (fun x : expr sym * (tenv typ -> tenv typ -> T) =>\n                                    (fst x, snd x tus tvs)) rs)) tus tvs.\n    Proof.\n      intros.\n      specialize (H3 e (map\n                          (fun x : expr sym * (tenv typ -> tenv typ -> T) =>\n                             (fst x, snd x tus tvs)) rs) tus tvs).\n      rewrite map_map in *. simpl in *.\n      eapply H3; eauto.\n      clear - H. induction H; simpl; intuition.\n      inv_all. subst. rewrite H1 in *. inv_all; subst.\n      eauto.\n    Qed.\n\n    Definition AppFullFoldArgsOk_SepLogsOk\n    : AppFullFoldArgsOk _ (AppFullFoldArgs_SepLogArgs sla)\n                        (fun t e res tus tvs =>\n                           t = SL ->\n                           R_t e res tus tvs).\n    Proof.\n      remember sla as s; destruct s; simpl; remember sls as s; destruct s.\n      constructor.\n      { simpl; intros.\n        replace do_other0 with (sla.(do_other)).\n        eapply atomic_ok; eauto. rewrite <- Heqs; reflexivity. }\n      { simpl; intros.\n        replace do_other0 with (sla.(do_other)).\n        eapply atomic_ok; eauto. rewrite <- Heqs; reflexivity. }\n      { simpl; intros.\n        consider (is_emp0 v); intros.\n        { replace do_emp0 with (sla.(do_emp)).\n          eapply (@empOk _ slaok); eauto.\n          Cases.rewrite_all_goal. auto.\n          rewrite <- Heqs0. simpl. auto.\n          rewrite <- Heqs. reflexivity. }\n        { replace do_other0 with (sla.(do_other)).\n          eapply atomic_ok; eauto. rewrite <- Heqs; reflexivity. } }\n      { simpl; intros.\n        replace do_other0 with (sla.(do_other)).\n        eapply atomic_ok; eauto. rewrite <- Heqs; reflexivity. }\n      { intros. subst ft. simpl.\n        assert (typeof_apps RSym_sym tus tvs l (map fst rs) = Some SL).\n        { rewrite <- typeof_expr_apps. congruence. }\n        generalize (otherOk slaok). rewrite <- Heqs. simpl.\n        destruct l; eauto using lem_other.\n        consider (is_star0 s); eauto using lem_other; intros.\n        { generalize H4. eapply is_starOk in H4.\n          unfold typeof_apps in H3.\n          simpl in H3. rewrite H4 in *.\n          inversion H1; clear H1; try subst.\n          { subst rs ts0; intros.\n            simpl in *. clear - H3. inv_all.\n            symmetry in H3. eapply tyArr_circ_L in H3. intuition. }\n          { subst rs ts0. inversion H7; clear H7.\n            { subst l l'; intros; simpl in *.\n              rewrite H4 in *. forward.\n              intuition. inv_all. subst y t0.\n              clear - H8. symmetry in H8.\n              eapply tyArr_circ_L in H8. intuition. }\n            { subst l l'. inversion H8; clear H8.\n              { subst l0 l'0. intuition. subst t.\n                destruct y, y0; simpl in *.\n                rewrite H8 in *. rewrite H6 in *. rewrite H4 in *.\n                unfold type_of_apply in *. forward.\n                inv_all.\n                subst x0 x t1 t2 t3 p0 p.\n                replace do_star0 with (sla.(do_star));\n                  [ | rewrite <- Heqs; reflexivity ].\n                eapply (starOk slaok); eauto.\n                rewrite <- Heqs0. auto. }\n              { exfalso. clear Heqs Heqs0. subst.\n                simpl in H3. intuition.\n                rewrite H2 in *. rewrite H6 in *. rewrite H1 in *.\n                forward. inv_all; try subst.\n                clear H15 H13. subst x x0 x1.\n                clear - H14.\n                eapply type_of_applys_circle_False in H14. auto. } } } } }\n    Qed.\n\n    Definition seplog_fold (sla : SepLogArgs) : expr sym -> tenv typ -> tenv typ -> T :=\n      app_fold_args (AppFullFoldArgs_SepLogArgs sla).\n\n    Theorem seplog_fold_sound\n    : forall e tus tvs result,\n        seplog_fold sla e tus tvs = result ->\n        typeof_expr tus tvs e = Some SL ->\n        R_t e result tus tvs.\n    Proof.\n      intros.\n      eapply (app_fold_args_sound AppFullFoldArgsOk_SepLogsOk) in H; eauto.\n    Qed.\n  End sound.\n*)\n\n\n(*\n  Variable OPS : ILogic.ILogicOps (typD ts nil SL).\n  Variable BI : BILOperators (typD ts nil SL).\n  Variable slsok : SepLogSpecOk sls OPS BI.\n\n  Require Import Relations.\n  Require Import ExtLib.Data.HList.\n\n  Record SepLogArgsSemOk\n         (TD : T -> forall tus tvs, tenv typ -> tenv typ -> option (typD ts nil SL))\n         (R : forall tus tvs,\n                relation (hlist (typD ts nil) tus ->\n                          hlist (typD ts nil) tvs ->\n                          typD ts nil SL)) :=\n  { atomic_appOk\n    : forall e es tus tvs val,\n        exprD' tus tvs (apps e es) SL = Some val ->\n        R tus tvs val (TD (sla.(do_other) e es))\n  ; pureOk\n    : forall e tus tvs,\n        typeof_expr tus tvs e = Some SL ->\n        sls.(is_pure) e = true ->\n        R_t e (sla.(do_pure) e) tus tvs\n  ; empOk\n    : forall e tus tvs,\n        typeof_sym e = Some SL ->\n        sls.(is_emp) e = true ->\n        R_t (Inj e) sla.(do_emp) tus tvs\n  ; starOk\n    : forall e l r l_res r_res tus tvs,\n        typeof_sym e = Some (tyArr SL (tyArr SL SL)) ->\n        typeof_expr tus tvs l = Some SL ->\n        typeof_expr tus tvs r = Some SL ->\n        sls.(is_star) e = true ->\n        R_t l l_res tus tvs ->\n        R_t r r_res tus tvs ->\n        R_t (apps (Inj e) (l :: r :: nil)) (sla.(do_star) l_res r_res) tus tvs\n  }.\n*)\n\nEnd seplog_fold.", "meta": {"author": "jesper-bengtson", "repo": "MirrorCharge", "sha": "cb0fe1da80be70ba4b744d4178a4e6e3afa38e62", "save_path": "github-repos/coq/jesper-bengtson-MirrorCharge", "path": "github-repos/coq/jesper-bengtson-MirrorCharge/MirrorCharge-cb0fe1da80be70ba4b744d4178a4e6e3afa38e62/MirrorCharge!/src/MirrorCharge/SepLogFold.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2071613037776634}}
{"text": "Require Import Crypto.Util.Notations.\n\nLocal Set Boolean Equality Schemes.\nLocal Set Decidable Equality Schemes.\nLocal Set Implicit Arguments.\nInductive ErrorT {ErrT T} :=\n| Success (v : T)\n| Error (msg : ErrT).\n\nGlobal Arguments ErrorT : clear implicits.\nDeclare Scope error_scope.\nDelimit Scope error_scope with error.\nBind Scope error_scope with ErrorT.\n\nDefinition invert_result {ErrT T} (v : ErrorT ErrT T)\n  := match v return match v with Success _ => T | _ => ErrT end with\n     | Success v => v\n     | Error msg => msg\n     end.\n\nDefinition bind {A B ErrT} (x : ErrorT ErrT A) (k : A -> ErrorT ErrT B) : ErrorT ErrT B\n  := match x with\n     | Success v => k v\n     | Error msg => Error msg\n     end.\n\nDefinition map2 {ErrT1 ErrT2 A B} (f : A -> B) (fe : ErrT1 -> ErrT2) (x : ErrorT ErrT1 A) : ErrorT ErrT2 B\n  := match x with\n     | Success v => Success (f v)\n     | Error e => Error (fe e)\n     end.\n\nDefinition map {ErrT A B} (f : A -> B) : ErrorT ErrT A -> ErrorT ErrT B\n  := map2 f id.\n\nDefinition map_error {ErrT1 ErrT2 A} (fe : ErrT1 -> ErrT2) : ErrorT ErrT1 A -> ErrorT ErrT2 A\n  := map2 id fe.\n\nDefinition error_bind {ErrT1 ErrT2 A} (x : ErrorT ErrT1 A) (k : ErrT1 -> ErrorT ErrT2 A) : ErrorT ErrT2 A\n  := match x with\n     | Success v => Success v\n     | Error msg => k msg\n     end.\n\nNotation \"x <- y ; f\" := (bind y (fun x => f%error)) : error_scope.\n\n(** ** Equality for [ErrorT] *)\nSection ErrorT.\n  Local Notation ErrorT_code u v\n    := (match u, v with\n        | Success u', Success v'\n        | Error u', Error v'\n          => u' = v'\n        | Success _, _\n        | Error _, _\n          => False\n        end).\n\n  (** *** Equality of [ErrorT] is a [match] *)\n  Definition path_ErrorT {A B} (u v : ErrorT A B) (p : ErrorT_code u v)\n    : u = v.\n  Proof. destruct u, v; first [ apply f_equal | exfalso ]; exact p. Defined.\n\n  (** *** Equivalence of equality of [ErrorT] with [ErrorT_code] *)\n  Definition unpath_ErrorT {A B} {u v : ErrorT A B} (p : u = v)\n    : ErrorT_code u v.\n  Proof. subst v; destruct u; reflexivity. Defined.\n\n  Definition path_ErrorT_iff {A B}\n             (u v : @ErrorT A B)\n    : u = v <-> ErrorT_code u v.\n  Proof.\n    split; [ apply unpath_ErrorT | apply path_ErrorT ].\n  Defined.\n\n  (** *** Eta-expansion of [@eq (ErrorT _ _)] *)\n  Definition path_ErrorT_eta {A B} {u v : @ErrorT A B} (p : u = v)\n    : p = path_ErrorT u v (unpath_ErrorT p).\n  Proof. destruct u, p; reflexivity. Defined.\n\n  (** *** Induction principle for [@eq (ErrorT _ _)] *)\n  Definition path_ErrorT_rect {A B} {u v : @ErrorT A B} (P : u = v -> Type)\n             (f : forall p, P (path_ErrorT u v p))\n    : forall p, P p.\n  Proof. intro p; specialize (f (unpath_ErrorT p)); destruct u, p; exact f. Defined.\n  Definition path_ErrorT_rec {A B u v} (P : u = v :> @ErrorT A B -> Set) := path_ErrorT_rect P.\n  Definition path_ErrorT_ind {A B u v} (P : u = v :> @ErrorT A B -> Prop) := path_ErrorT_rec P.\nEnd ErrorT.\n\n(** ** Useful Tactics *)\n(** *** [inversion_ErrorT] *)\nLtac induction_path_ErrorT H :=\n  induction H as [H] using path_ErrorT_rect;\n  try match type of H with\n      | False => exfalso; exact H\n      end.\nLtac inversion_ErrorT_step :=\n  match goal with\n  | [ H : Success _ = Success _ |- _ ]\n    => induction_path_ErrorT H\n  | [ H : Success _ = Error _ |- _ ]\n    => induction_path_ErrorT H\n  | [ H : Error _ = Success _ |- _ ]\n    => induction_path_ErrorT H\n  | [ H : Error _ = Error _ |- _ ]\n    => induction_path_ErrorT H\n  end.\nLtac inversion_ErrorT := repeat inversion_ErrorT_step.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Util/ErrorT.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.20716130377766337}}
{"text": "Require Import Arith.\nRequire Import Zee.vals.\nRequire Import Zee.dec Zee.maplike.\nRequire Import Lia.\nRequire Import String.\n\nSection Frame.\n  Context {A : Set}.\n  Definition V := @V A.\n  Definition SecTyV := @SecTyV A.\n  \n(*  Definition Lab := @Lab A.\n  Definition Ty := @Ty A.\n  Definition LabVar := @LabVar A.\n  Definition SecTy := @SecTy A.\n  Definition AtomSecTy := @AtomSecTy A.\n*)\n  \n  Definition Range : Type := nat * nat.\n  Opaque Range.\n\n  Class HasRange (A : Type) :=\n    {\n      dom: A -> Range\n    }.\n  Hint Constructors HasRange.\n\n  Global Instance HasRange_Range : HasRange Range.\n  Proof.\n    constructor.\n    eapply id.\n  Defined.\n  \n  Definition in_range {T : Type} `{HasRange T} (n : nat) (x : T) : Prop :=\n    let (n1, n2) := dom x in n1 <= n /\\ n <= n1 + n2.\n  Hint Unfold in_range.\n  \n  Infix \"∈\" := in_range (at level 70).\n  Infix \"∉\" := (fun n r => not (in_range n r)) (at level 80).\n\n  Lemma in_range_dec {T : Type} `{HasRange T} n r:\n    { n ∈ r } + { n ∉ r }.\n  Proof.\n    destruct (dom r) as [n1 n2] eqn:?H.\n    unfold in_range.\n    rewrite -> H0.\n    destruct (le_dec n1 n).\n    - destruct (le_dec n (n1 + n2)).\n      + left.\n        split; assumption.\n      + right.\n        intro.\n        eapply n0.\n        eapply (proj2 H1).\n    - right.\n      intro.\n      eapply n0.\n      eapply (proj1 H1).\n  Defined.\n\n  Class HasVersion (A : Type) :=\n    {\n      version: A -> Version\n    }.\n  Hint Constructors HasVersion.\n  \n  Record EFrame (M : Type) `{MapLike M nat V} :=\n    {\n      range_of : Range;\n      mem_of : M;\n      version_of: Version\n    }.\n  Hint Constructors EFrame.\n  Global Arguments Build_EFrame { _ } { _ }.\n  Global Arguments range_of { _ } { _ }.\n  Global Arguments mem_of { _ } { _ }.\n  Global Arguments version_of { _ } { _ }.\n  \n  Global Instance HasRange_EFrame {M : Type} `{MapLike M nat V} :\n    HasRange (EFrame M) := {}.\n  intros.\n  eapply (dom (range_of X)).\n  Defined.\n\n  Global Instance HasVersion_EFrame {M : Type} `{MapLike M nat V} :\n    HasVersion (EFrame M) := {}.\n  intros.\n  eapply (version_of X).\n  Defined.\n  \n  Global Instance ReadableMapLike_EFrame {M : Type} `{MapLike M nat V} :\n    ReadableMapLike (EFrame M) nat V := {}.\n  - intros efr n.\n    eapply (mem_of efr ? n).\n  - eapply (Build_EFrame (0, 0) ∅ 0).\n  - intros.\n    simpl.\n    eapply lookup_empty_map.\n  Defined.\n\n  Global Instance WriteableMapLike_EFrame {M : Type} `{MapLike M nat V} :\n    WriteableMapLike (EFrame M) nat V := {}.\n  intros n v efr.\n  eapply (Build_EFrame (dom efr) (mem_of efr [n ↦ v]) (version_of efr)).\n  Defined.\n  \n  Global Instance MapLike_EFrame {M : Type} `{MapLike M nat V} :\n    MapLike (EFrame M) nat V := {}.\n  - intros.\n    simpl.\n    eapply lookup_update_eq.\n  - intros.\n    simpl.\n    eapply lookup_update_neq.\n    assumption.\n  Defined.\n  \n  Definition fp_of {T : Type} `{HasRange T} (x : T) := fst (dom x).\n  Definition sp_of {T : Type} `{HasRange T} (x : T) := fst (dom x) + snd (dom x).\n  Hint Unfold fp_of sp_of.\n  \n  Definition wf_EFrame {M : Type} `{MapLike M nat V} (efr : EFrame M) : Prop :=\n    forall a, a ∈ efr -> efr ? a <> None.\n  Hint Unfold wf_EFrame.\n  \n  Record PFrame (Var Arg Loc : Type) `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} :=\n    {\n      pvar_of : Var;\n      parg_of : Arg;\n      ploc_of : Loc;\n    }.\n  Hint Constructors PFrame.\n  Global Arguments Build_PFrame { _ } { _ } { _ } { _ } { _ } { _ }.\n  Global Arguments pvar_of { _ } { _ } { _ } { _ } { _ } { _ }.\n  Global Arguments parg_of { _ } { _ } { _ } { _ } { _ } { _ }.\n  Global Arguments ploc_of { _ } { _ } { _ } { _ } { _ } { _ }.\n\n  Global Instance ReadableMapLike_PFrame {Var Arg Loc : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} : ReadableMapLike (PFrame Var Arg Loc) string (A + SecTyV) := {}.\n  - intros pfr x.\n    eapply (pvar_of pfr ? x).\n  - eapply (Build_PFrame ∅ ∅ ∅).\n  - intros.\n    simpl.\n    eapply lookup_empty_map.\n  Defined.\n\n  Global Instance WriteableMapLike_PFrame {Var Arg Loc : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} : WriteableMapLike (PFrame Var Arg Loc) string (A + SecTyV) := {}.\n  intros x τℓ pfr.\n  eapply (Build_PFrame (pvar_of pfr [x ↦ τℓ]) (parg_of pfr) (ploc_of pfr)).\n  Defined.\n\n  Global Instance MapLike_PFrame {Var Arg Loc : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} : MapLike (PFrame Var Arg Loc) string (A + SecTyV) := {}.\n  - intros.\n    simpl.\n    eapply lookup_update_eq.\n  - intros.\n    simpl.\n    eapply lookup_update_neq.\n    assumption.\n  Defined.\n\n  Global Instance FinMapLike_PFrame {Var Arg Loc : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} : FinMapLike (PFrame Var Arg Loc) string (A + SecTyV) := {}.\n  - intros pfr.\n    eapply (values (pvar_of pfr)).\n  - cbn.\n    eapply values_empty.\n  - intros.\n    eapply values_add.\n  Defined.\n  \n  Definition upd_loc {Var Arg Loc : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} (x : string) (τ : SecTyV) (pfr : PFrame Var Arg Loc): PFrame Var Arg Loc.\n    eapply (Build_PFrame (pvar_of pfr)\n                         (parg_of pfr)\n                         (update x τ (ploc_of pfr))).\n  Defined.\n\n  Definition upd_arg {Var Arg Loc : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} (x : string) (τ : SecTyV) (pfr : PFrame Var Arg Loc): PFrame Var Arg Loc.\n    eapply (Build_PFrame (pvar_of pfr)\n                         (update x τ (parg_of pfr))\n                         (ploc_of pfr)).\n  Defined.\n  \n  Definition upd_var {Var Arg Loc : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} (x : string) (τℓ : A + SecTyV) (pfr : PFrame Var Arg Loc) : PFrame Var Arg Loc.\n    eapply (Build_PFrame (update x τℓ (pvar_of pfr))\n                         (parg_of pfr)\n                         (ploc_of pfr)).\n  Defined.\n  Hint Unfold upd_loc upd_arg upd_var.\n\n  Record Frame (Var Arg Loc Mem : Type) `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} `{MapLike Mem nat V} :=\n    {\n      pframe_of : PFrame Var Arg Loc;\n      eframe_of : EFrame Mem\n    }.\n  Hint Constructors Frame.\n  \n  Global Arguments pframe_of { _ } { _ } { _ } { _ } { _ } { _ } { _ } { _ }.\n  Global Arguments eframe_of { _ } { _ } { _ } { _ } { _ } { _ } { _ } { _ }.\n  Global Arguments Build_Frame { _ } { _ } { _ } { _ } { _ } { _ } { _ } { _ }.\n\n  Global Instance ReadableMapLike_nat_V_Fr {Var Arg Loc Mem : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} `{MapLike Mem nat V} : ReadableMapLike (Frame Var Arg Loc Mem) nat V := {}.\n  - exact (fun fr n => eframe_of fr ? n).\n  - eapply (Build_Frame ∅ ∅).\n  - intros.\n    simpl.\n    eapply lookup_empty_map.\n  Defined.\n\n  Global Instance WriteableMapLike_nat_V_Fr {Var Arg Loc Mem : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} `{MapLike Mem nat V}: WriteableMapLike (Frame Var Arg Loc Mem) nat V := {}.\n  exact (fun n v fr => Build_Frame (pframe_of fr) (eframe_of fr [n ↦ v])).\n  Defined.\n  \n  Global Instance MapLike_nat_V_Fr {Var Arg Loc Mem : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} `{MapLike Mem nat V}: MapLike (Frame Var Arg Loc Mem) nat V := {}.\n  Proof.\n    - intros.\n      simpl.\n      eapply lookup_update_eq.\n    - intros.\n      simpl.\n      eapply lookup_update_neq; assumption.\n  Defined.\n  Hint Resolve MapLike_nat_V_Fr.\n  \n  Global Instance HasVersion_Fr {Var Arg Loc Mem : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} `{MapLike Mem nat V} : HasVersion (Frame Var Arg Loc Mem).\n  constructor.\n  intros.\n  eapply (version (eframe_of X)).\n  Defined.\n  Hint Resolve HasVersion_Fr.\n\n  Global Instance ReadableMapLike_var_ty_or_sec_Fr {Var Arg Loc Mem : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} `{MapLike Mem nat V}: ReadableMapLike (Frame Var Arg Loc Mem) string (A + SecTyV) := {}.\n  - exact (fun fr x => pframe_of fr ? x).\n  - eapply (Build_Frame ∅ ∅).\n  - intros.\n    simpl.\n    eapply lookup_empty_map.\n  Defined.\n\n  Global Instance WriteableMapLike_var_ty_or_sec_Fr {Var Arg Loc Mem : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} `{MapLike Mem nat V}: WriteableMapLike (Frame Var Arg Loc Mem) string (A + SecTyV) := {}.\n  exact (fun x τℓ fr => Build_Frame (pframe_of fr [x ↦ τℓ]) (eframe_of fr)).\n  Defined.  \n  \n  Global Instance MapLike_var_ty_or_sec_Fr {Var Arg Loc Mem : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} `{MapLike Mem nat V}: MapLike (Frame Var Arg Loc Mem) string (A + SecTyV) := {}.\n  - intros.\n    simpl.\n    eapply lookup_update_eq.\n  - intros.\n    simpl.\n    eapply lookup_update_neq; assumption.\n  Defined.\n  Hint Resolve MapLike_var_ty_or_sec_Fr.\n\n  Global Instance FinMapLike_var_ty_or_sec_Fr {Var Arg Loc Mem : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} `{MapLike Mem nat V}: FinMapLike (Frame Var Arg Loc Mem) string (A + SecTyV) := {}.\n  exact (fun fr => values (pframe_of fr)).\n  - cbn.\n    eapply values_empty.\n  - intros.\n    cbn.\n    eapply values_add.\n  Defined.\n  Hint Resolve FinMapLike_var_ty_or_sec_Fr.\n\n  Global Instance HasRange_Frame {Var Arg Loc Mem : Type} `{FinMapLike Var string (A + SecTyV)} `{FinMapLike Arg string SecTyV} `{FinMapLike Loc string SecTyV} `{MapLike Mem nat V}: HasRange (Frame Var Arg Loc Mem) := {}.\n  intros fr.\n  eapply (dom (eframe_of fr)).\n  Defined.\n  \nEnd Frame.\n\nInfix \"∈\" := in_range (at level 70).\nInfix \"∉\" := (fun n r => not (in_range n r)) (at level 80).", "meta": {"author": "MathiasVP", "repo": "Zee-coq", "sha": "9851de46e87e24d7372076cae3ccbdb730d29d4f", "save_path": "github-repos/coq/MathiasVP-Zee-coq", "path": "github-repos/coq/MathiasVP-Zee-coq/Zee-coq-9851de46e87e24d7372076cae3ccbdb730d29d4f/frame.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.20716130377766337}}
{"text": "From RecoveryRefinement Require Import Lib.\nRequire Import Spec.HoareTactics.\n\nRequire Import Examples.Logging.Impl.\n\nFrom Classes Require Import Classes.\n\nOpaque plus.\nOpaque lt.\n\nImport EqualDecNotation.\n\nRecord LogValues :=\n  { values :> list block;\n    values_ok: length values = LOG_LENGTH }.\n\nCoercion addresses : Descriptor >-> list.\n\nRecord PhysicalState :=\n  { p_hdr: LogHdr;\n    p_desc: Descriptor;\n    p_log_values: LogValues;\n    p_data_region: disk; }.\n\nInductive PhyDecode (d: disk) : PhysicalState -> Prop :=\n| phy_decode hdr desc (log_values:LogValues) data\n             (Hhdr: index d 0 = Some (LogHdr_fmt.(encode) hdr))\n             (Hdesc: index d 1 = Some (Descriptor_fmt.(encode) desc))\n             (Hlog_values: forall i,\n                 i < LOG_LENGTH ->\n                 index d (2+i) = index log_values i)\n             (Hdata: forall i,\n                 index d (2+LOG_LENGTH+i) = index data i) :\n    PhyDecode d {| p_hdr := hdr;\n                   p_desc := desc;\n                   p_log_values := log_values;\n                   p_data_region := data; |}\n.\n\nLemma log_length_nonzero : LOG_LENGTH > 0.\n  unfold LOG_LENGTH.\n  lia.\nQed.\n\n(* coercion magic makes this theorem seem odd - the proof comes from inside\nlog_values *)\nLemma length_log (log_values:LogValues) :\n  length log_values = LOG_LENGTH.\nProof.\n  destruct log_values; auto.\nQed.\n\n#[export] Hint Rewrite length_log : length.\n\n(* TODO: Hint Rewrite length_descriptor breaks a proof here *)\n\nTheorem PhyDecode_disk_bound d ps :\n  PhyDecode d ps ->\n  length d >= 2 + LOG_LENGTH.\nProof.\n  pose proof log_length_nonzero.\n  inversion 1; subst.\n  specialize (Hlog_values (LOG_LENGTH-1) ltac:(lia)).\n  rewrite (index_inbounds log_values (LOG_LENGTH-1)) in Hlog_values;\n    autorewrite with length;\n    try lia.\n  apply index_some_bound in Hlog_values.\n  lia.\nQed.\n\nTheorem PhyDecode_data_len d ps :\n  PhyDecode d ps ->\n  length ps.(p_data_region) = length d - 2 - LOG_LENGTH.\nProof.\n  inversion 1; subst; simpl.\n  apply length_bounds.\n  - apply index_none_bound.\n    rewrite <- Hdata; array.\n  - assert (length d <= 2 + LOG_LENGTH + length data); try lia.\n    apply index_none_bound.\n    rewrite Hdata; array.\nQed.\n\nTheorem PhyDecode_disk_len d ps :\n  PhyDecode d ps ->\n  length d = 2 + LOG_LENGTH + length ps.(p_data_region).\nProof.\n  intros.\n  pose proof (PhyDecode_disk_bound H).\n  pose proof (PhyDecode_data_len H).\n  lia.\nQed.\n\nLemma one_disk_failure_unfold s s' r :\n  D.one_disk_failure s s' r ->\n  s' = s.\nProof.\n  inversion 1; auto.\nQed.\n\nLemma ODLayer_crash s s' r :\n  D.ODLayer.(crash_step) s s' r ->\n  s' = s.\nProof.\n  simpl; eauto using one_disk_failure_unfold.\nQed.\n\nGlobal Hint Resolve ODLayer_crash : core.\n\nLtac match_abs :=\n  match goal with\n  | [ H: PhyDecode ?d _ |- PhyDecode ?d _ ] => exact H\n  | [ H: PhyDecode ?d ?ps |- context[PhyDecode ?d _] ] =>\n    match goal with\n    | |- exists _, _ => solve [ destruct ps; descend; eauto ]\n    end\n  end.\n\nLtac simplify :=\n  repeat match goal with\n         | _ => match_abs\n         | _ => progress propositional\n         | [ H: D.one_disk_failure _ _ _ |- _ ] =>\n           apply one_disk_failure_unfold in H\n         | [ H: D.ODLayer.(sem).(crash_step) _ _ _ |- _ ] =>\n           apply ODLayer_crash in H\n         | |- _ /\\ _ => split; [ solve [ auto ] | ]\n         | |- _ /\\ _ => split; [ | solve [ auto ] ]\n         | _ => destruct_tuple\n         | [ u: unit |- _ ] => destruct u\n         | [ H: (_, _) = (_, _) |- _ ] => inv_clear H\n         | _ => progress cbn [pre post alternate] in *\n         end.\n\nLtac finish :=\n  repeat match goal with\n         | _ => match_abs\n         | _ => solve [ eauto ]\n         | _ => congruence\n         | _ => lia\n         end.\n\nLemma and_wlog (P Q:Prop) :\n  P ->\n  (P -> Q) ->\n  P /\\ Q.\nProof.\n  firstorder.\nQed.\n\nLtac split_wlog :=\n  repeat match goal with\n         | _ => match_abs\n         | |- _ /\\ _ => apply and_wlog\n         | [ H: _ \\/ _ |- _ ] => destruct H\n         | _ => progress propositional\n         | _ => solve [ auto ]\n         end.\n\nLtac split_cases :=\n  repeat match goal with\n         | _ => match_abs\n         | |- _ /\\ _ => split\n         | [ H: _ \\/ _ |- _ ] => destruct H\n         | _ => progress propositional\n         | _ => solve [ eauto ]\n         end.\n\n(* specs for one-disk primitives (restatement of semantics as specs) *)\nLtac prim :=\n  eapply proc_hspec_impl; [ unfold spec_impl | eapply op_spec_sound ];\n  simpl in *;\n  propositional;\n  (intuition eauto);\n  propositional;\n  repeat match goal with\n         | [ H: D.one_disk_failure _ _ _ |- _ ] =>\n           apply one_disk_failure_unfold in H\n         end.\n\nLocal Notation proc_hspec := (Hoare.proc_hspec D.ODLayer.(sem)).\nArguments Hoare.proc_hspec {Op State} sem {T}.\n\nTheorem read_ok a :\n  proc_hspec\n    (read a)\n    (fun state =>\n       {| pre := True;\n          post state' r :=\n            index state a ?|= eq r /\\\n            state' = state;\n          alternate state' _ :=\n            state' = state; |}).\nProof.\n  unfold read.\n  prim;\n    repeat match goal with\n           | [ H: D.op_step _ _ _ _ |- _ ] => invert H; clear H\n           end;\n    propositional;\n    auto.\n  destruct (index s' a); simpl; finish.\nQed.\n\nTheorem write_ok a v :\n  proc_hspec\n    (write a v)\n    (fun state =>\n       {| pre := True;\n          post state' r :=\n            r = tt /\\\n            state' = assign state a v;\n          alternate state' _ :=\n            state' = state \\/\n            state' = assign state a v; |}).\nProof.\n  unfold write.\n  prim;\n    repeat match goal with\n           | [ H: D.op_step _ _ _ _ |- _ ] => invert H; clear H\n           end;\n    propositional;\n    auto.\nQed.\n\nTheorem size_ok :\n  proc_hspec\n    (size)\n    (fun state =>\n       {| pre := True;\n          post state' r :=\n            r = length state /\\\n            state' = state;\n          alternate state' _ :=\n            state' = state; |}).\nProof.\n  unfold size.\n  prim;\n    repeat match goal with\n           | [ H: D.op_step _ _ _ _ |- _ ] => invert H; clear H\n           end;\n    propositional;\n    auto.\nQed.\n\nLocal Hint Resolve read_ok write_ok size_ok : core.\n\nLtac step :=\n  step_proc; simplify; eauto.\n\nOpaque index.\nOpaque D.ODLayer.\n\nTheorem gethdr_ok ps :\n  proc_hspec\n    gethdr\n    (fun state =>\n       {| pre := PhyDecode state ps;\n          post state' r :=\n            r = ps.(p_hdr) /\\\n            state' = state;\n          alternate state' _ :=\n            state' = state; |}).\nProof.\n  unfold gethdr.\n  step.\n  step.\n  inversion H; subst; simpl in *.\n  replace (index state 0) in *; simpl in *; subst.\n  rewrite LogHdr_fmt.(encode_decode); eauto.\nQed.\n\nLocal Hint Resolve gethdr_ok : core.\n\nLemma phy_writedesc:\n  forall (ps : PhysicalState) (desc : Descriptor) (s : D.State),\n    PhyDecode s ps ->\n    PhyDecode (assign s 1 (Descriptor_fmt.(encode) desc))\n              {|\n                p_hdr := ps.(p_hdr);\n                p_desc := desc;\n                p_log_values := ps.(p_log_values);\n                p_data_region := ps.(p_data_region) |}.\nProof.\n  intros ps desc s H.\n  pose proof (PhyDecode_disk_len H).\n  inv_clear H; constructor; intros; array.\nQed.\n\nLocal Hint Resolve phy_writedesc : core.\n\n\nLemma phy_writehdr:\n  forall (ps : PhysicalState) (hdr : LogHdr) (s : D.ODLayer.(State)),\n    PhyDecode s ps ->\n    PhyDecode (assign s 0 (LogHdr_fmt.(encode) hdr))\n              {| p_hdr := hdr;\n                 p_desc := ps.(p_desc);\n                 p_log_values := ps.(p_log_values);\n                 p_data_region := ps.(p_data_region) |}.\nProof.\n  intros ps hdr s H.\n  pose proof (PhyDecode_disk_len H).\n  inv_clear H; constructor; intros; array.\nQed.\n\nLocal Hint Resolve phy_writehdr : core.\n\nLtac spec_impl :=\n  eapply proc_hspec_impl; [ unfold spec_impl | solve [ eauto] ];\n  simplify.\n\nTheorem writehdr_ok ps hdr :\n  proc_hspec\n    (writehdr hdr)\n    (fun state =>\n       {| pre := PhyDecode state ps;\n          post state' r :=\n            PhyDecode state' {| p_hdr := hdr;\n                            p_desc := ps.(p_desc);\n                            p_log_values := ps.(p_log_values);\n                            p_data_region := ps.(p_data_region); |};\n          alternate state' _ :=\n            PhyDecode state' ps \\/\n            PhyDecode state' {| p_hdr := hdr;\n                            p_desc := ps.(p_desc);\n                            p_log_values := ps.(p_log_values);\n                            p_data_region := ps.(p_data_region); |}\n       |}).\nProof.\n  unfold writehdr.\n  spec_impl; split_wlog.\nQed.\n\nLocal Hint Resolve writehdr_ok : core.\n\nTheorem writedesc_ok ps desc :\n  proc_hspec\n    (writedesc desc)\n    (fun state =>\n       {| pre := PhyDecode state ps;\n          post state' r :=\n            r = tt /\\\n            PhyDecode state' {| p_hdr := ps.(p_hdr);\n                            p_desc := desc;\n                            p_log_values := ps.(p_log_values);\n                            p_data_region := ps.(p_data_region); |};\n          alternate state' _ :=\n            PhyDecode state' ps \\/\n            PhyDecode state' {| p_hdr := ps.(p_hdr);\n                            p_desc := desc;\n                            p_log_values := ps.(p_log_values);\n                            p_data_region := ps.(p_data_region); |}\n       |}).\nProof.\n  unfold writedesc.\n  spec_impl; split_wlog.\nQed.\n\nLocal Hint Resolve writedesc_ok : core.\n\nDefinition log_assign (log_values:LogValues) i b : LogValues :=\n  {| values := assign log_values i b;\n     values_ok := ltac:(autorewrite with length; auto); |}.\n\nLocal Hint Resolve addresses_length : core.\n\nDefinition desc_assign (desc:Descriptor) i a : Descriptor :=\n  {| addresses := assign desc i a;\n     addresses_length := ltac:(autorewrite with length; auto); |}.\n\nLemma phy_set_log_value:\n  forall (ps : PhysicalState) (i : nat) (a : addr) (v : block),\n    i < LOG_LENGTH ->\n    forall s : D.State,\n      PhyDecode s\n                {|\n                  p_hdr := ps.(p_hdr);\n                  p_desc := add_addr ps.(p_desc) i a;\n                  p_log_values := ps.(p_log_values);\n                  p_data_region := ps.(p_data_region) |} ->\n      PhyDecode (assign s (2 + i) v)\n                {|\n                  p_hdr := ps.(p_hdr);\n                  p_desc := desc_assign ps.(p_desc) i a;\n                  p_log_values := log_assign ps.(p_log_values) i v;\n                  p_data_region := ps.(p_data_region) |}.\nProof.\n  intros ps i a v Hbound s H.\n  pose proof (PhyDecode_disk_len H); simpl in *.\n  inv_clear H; constructor; intros;\n    cbn [log_assign values]; array.\n\n  destruct (i == i0); subst; array.\nQed.\n\nLocal Hint Resolve phy_set_log_value : core.\n\nTheorem getdesc_ok ps :\n  proc_hspec\n    (getdesc)\n    (fun state =>\n       {| pre := PhyDecode state ps;\n          post state' r :=\n            r = ps.(p_desc) /\\\n            state' = state;\n          alternate state' _ :=\n            state' = state; |}).\nProof.\n  unfold getdesc.\n  step.\n  step.\n  inv_clear H; simpl in *.\n  replace (index state 1) in *; simpl in *; propositional.\n  rewrite Descriptor_fmt.(encode_decode); eauto.\nQed.\n\nLocal Hint Resolve getdesc_ok : core.\n\nTheorem set_desc_ok ps desc i a v :\n  proc_hspec\n    (set_desc desc i a v)\n    (fun state =>\n       {| pre := PhyDecode state ps /\\\n                 ps.(p_desc) = desc /\\\n                 i < LOG_LENGTH;\n          post state' r :=\n            r = tt /\\\n            PhyDecode state' {| p_hdr := ps.(p_hdr);\n                           p_desc := desc_assign desc i a;\n                           p_log_values :=\n                             log_assign ps.(p_log_values) i v;\n                           p_data_region := ps.(p_data_region) |};\n          alternate state' _ :=\n            exists desc' log_values',\n              PhyDecode state' {| p_hdr := ps.(p_hdr);\n                              p_desc := desc';\n                              p_log_values := log_values';\n                              p_data_region := ps.(p_data_region); |};\n       |}).\nProof.\n  unfold set_desc.\n  step; split_cases; simplify; finish.\n  spec_impl; split_wlog; simplify; finish.\nQed.\n\nLocal Hint Resolve set_desc_ok : core.\n\nTheorem phy_log_size_ok ps :\n  proc_hspec\n    (log_size)\n    (fun state =>\n       {| pre := PhyDecode state ps;\n          post state' r :=\n            state' = state /\\\n            r = length ps.(p_data_region);\n          alternate state' _ :=\n            state' = state; |}).\nProof.\n  unfold log_size.\n  step.\n  step.\n  pose proof (PhyDecode_data_len H).\n  intuition eauto.\n  lia.\nQed.\n\nLocal Hint Resolve phy_log_size_ok : core.\n\nLemma sel_log_value d ps i :\n  PhyDecode d ps ->\n  i < LOG_LENGTH ->\n  sel d (2 + i) = sel ps.(p_log_values) i.\nProof.\n  intros; inv_clear H; simpl.\n  apply sel_index_eq.\n  eauto.\nQed.\n\nTheorem get_logwrite_ok ps desc i :\n  proc_hspec\n    (get_logwrite desc i)\n    (fun state =>\n       {| pre := PhyDecode state ps /\\\n                 i < LOG_LENGTH /\\\n                 ps.(p_desc) = desc;\n          post state' r :=\n            state' = state /\\\n            r = (sel ps.(p_desc) i, sel ps.(p_log_values) i);\n          alternate state' _ :=\n            state' = state; |}).\nProof.\n  unfold get_logwrite.\n  step.\n  step.\n  intuition eauto.\n  pose proof (PhyDecode_disk_len H).\n  f_equal.\n  (* BUG: rewrite does not try to instantiate def using the typeclass without\n  the (def:=_) *)\n  rewrite (index_inbounds (def:=_)) in H1 by lia.\n  simpl in *; propositional.\n  auto using sel_log_value.\nQed.\n\nLocal Hint Resolve get_logwrite_ok : core.\n\nLemma phy_index_data:\n  forall (ps : PhysicalState) (a : nat) (s : D.ODLayer.(State)),\n    PhyDecode s ps ->\n    forall v : block,\n      index s (2 + LOG_LENGTH + a) ?|= eq v ->\n      index ps.(p_data_region) a ?|= eq v.\nProof.\n  intros ps a s H v H0.\n  pose proof (PhyDecode_disk_len H).\n  inv_clear H; simpl in *.\n\n  destruct (index_dec data a);\n    propositional;\n    autorewrite with array in *;\n    auto.\n\n  rewrite (index_inbounds (def:=_)) in * by lia; simpl.\n  simpl in *; propositional.\n  apply sel_index_eq; auto.\nQed.\n\nLocal Hint Resolve phy_index_data : core.\n\nTheorem data_read_ok ps a :\n  proc_hspec\n    (data_read a)\n    (fun state =>\n       {| pre := PhyDecode state ps;\n          post state' r :=\n            state' = state /\\\n            index ps.(p_data_region) a ?|= eq r;\n          alternate state' _ :=\n            state' = state; |}).\nProof.\n  unfold data_read.\n  spec_impl; finish.\nQed.\n\nLocal Hint Resolve data_read_ok : core.\n\nLemma phy_data_write:\n  forall (ps : PhysicalState) (a : nat) (v : block) (s : D.ODLayer.(State)),\n    PhyDecode s ps ->\n    PhyDecode (assign s (2 + LOG_LENGTH + a) v)\n              {|\n                p_hdr := ps.(p_hdr);\n                p_desc := ps.(p_desc);\n                p_log_values := ps.(p_log_values);\n                p_data_region := assign ps.(p_data_region) a v |}.\nProof.\n  intros ps a v s H.\n  pose proof (PhyDecode_disk_len H).\n  inv_clear H; constructor; intros; simpl in *; array.\n  destruct (a == i); subst; array.\n  destruct (index_dec data i); propositional; array.\nQed.\n\nLocal Hint Resolve phy_data_write : core.\n\nTheorem data_write_ok ps a v :\n  proc_hspec\n    (data_write a v)\n    (fun state =>\n       {| pre := PhyDecode state ps;\n          post state r :=\n            r = tt /\\\n            PhyDecode state {| p_hdr := ps.(p_hdr);\n                           p_desc := ps.(p_desc);\n                           p_log_values := ps.(p_log_values);\n                           p_data_region :=\n                             assign ps.(p_data_region) a v; |};\n          alternate state' _ :=\n            exists data,\n              (data = ps.(p_data_region) \\/\n               data = assign ps.(p_data_region) a v) /\\\n              PhyDecode state' {| p_hdr := ps.(p_hdr);\n                              p_desc := ps.(p_desc);\n                              p_log_values := ps.(p_log_values);\n                              p_data_region := data |};\n       |}).\nProof.\n  unfold data_write.\n  spec_impl; split_wlog; simplify; finish.\nQed.\n\nLocal Hint Resolve data_write_ok : core.\n\nTheorem log_write_ok ps a v :\n  proc_hspec\n    (log_write a v)\n    (fun state =>\n       {| pre := PhyDecode state ps;\n          post state' r :=\n            match r with\n            | TxnD.WriteOK =>\n              let hdr := ps.(p_hdr) in\n              exists pf,\n                PhyDecode state'\n                          {| p_hdr := hdr_inc hdr pf;\n                             p_desc :=\n                               desc_assign ps.(p_desc) hdr.(log_length) a;\n                             p_log_values :=\n                               log_assign ps.(p_log_values) hdr.(log_length) v;\n                             p_data_region := ps.(p_data_region); |}\n            | TxnD.WriteErr =>\n              state' = state /\\\n              ps.(p_hdr).(log_length) = LOG_LENGTH\n            end;\n          alternate state' _ :=\n            (* if we crash the log will still be uncommited, so just promise\n            that the data is unaffected *)\n            exists hdr desc log_values,\n              PhyDecode state' {| p_hdr := hdr;\n                              p_desc := desc;\n                              p_log_values := log_values;\n                              p_data_region := ps.(p_data_region) |} /\\\n              hdr.(committed) = ps.(p_hdr).(committed);\n       |}).\nProof.\n  unfold log_write.\n  step_proc; split_wlog; simplify; finish.\n  destruct (hdr_full r).\n  { step; simplify; finish. }\n  destruct ps; eauto.\n  step; split_wlog; simplify; finish.\n  step; split_wlog; simplify; finish.\n  step; split_wlog; simplify; finish.\n  step; split_wlog; simplify; finish.\nQed.\n\n(* this is just a physical description of [apply_at]; it precisely encodes the\ndata since we can't accurately abstract it that this level (we need to refer to\nthe old disk, which isn't tracked in these specs) *)\nTheorem apply_at_ok ps desc i :\n  proc_hspec\n    (apply_at desc i)\n    (fun state =>\n       {| pre := PhyDecode state ps /\\\n                 desc = ps.(p_desc) /\\\n                 i < LOG_LENGTH;\n          post state' r :=\n            r = tt /\\\n            PhyDecode state' {| p_hdr := ps.(p_hdr);\n                            p_desc := ps.(p_desc);\n                            p_log_values := ps.(p_log_values);\n                            p_data_region :=\n                              let a := sel ps.(p_desc) i in\n                              let v := sel ps.(p_log_values) i in\n                              assign ps.(p_data_region) a v; |};\n          alternate state' _ :=\n            exists data,\n              (data = ps.(p_data_region) \\/\n               let a := sel ps.(p_desc) i in\n               let v := sel ps.(p_log_values) i in\n               data = assign ps.(p_data_region) a v) /\\\n            PhyDecode state' {| p_hdr := ps.(p_hdr);\n                            p_desc := ps.(p_desc);\n                            p_log_values := ps.(p_log_values);\n                            p_data_region := data; |};\n       |}).\nProof.\n  unfold apply_at.\n  step; split_wlog; simplify; finish.\n  step; split_wlog; simplify; finish.\n  step; split_wlog; simplify; finish.\nQed.\n\nLemma log_subslice_len_ok:\n  forall state : D.ODLayer.(State),\n    ~ length state < 2 + LOG_LENGTH -> length (subslice state 2 LOG_LENGTH) = LOG_LENGTH.\nProof.\n  intros.\n  rewrite length_subslice; lia.\nQed.\n\nTheorem phy_log_init_ok :\n  proc_hspec\n    (log_init)\n    (fun state =>\n       {| pre := True;\n          post state' r :=\n            match r with\n            | Initialized =>\n              exists ps, PhyDecode state' ps /\\\n                    ps.(p_hdr).(committed) = false /\\\n                    ps.(p_hdr).(log_length) = 0\n            | InitFailed => state' = state\n            end;\n          alternate state' _ := True |}).\nProof.\n  unfold log_init.\n  step.\n  destruct matches.\n  - step.\n  - unfold writehdr, writedesc.\n    repeat step.\n    exists {| p_hdr := empty_hdr;\n          p_desc := default;\n           p_log_values := {| values := subslice state 2 LOG_LENGTH;\n                               values_ok := ltac:(auto using log_subslice_len_ok) |};\n            p_data_region := subslice state (2+LOG_LENGTH) (length state - 2 - LOG_LENGTH); |};\n      simpl.\n    intuition eauto.\n    constructor; intros; simpl; array.\n    destruct (index_dec state (2 + LOG_LENGTH + i)); propositional; array.\nQed.\n", "meta": {"author": "mit-pdos", "repo": "argosy", "sha": "a6a5aa0d3868efd4ada0b40927b5748e5d8967d3", "save_path": "github-repos/coq/mit-pdos-argosy", "path": "github-repos/coq/mit-pdos-argosy/argosy-a6a5aa0d3868efd4ada0b40927b5748e5d8967d3/src/Examples/Logging/LogLayout.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20695010534741193}}
{"text": "Require Import CodeProofDeps.\nRequire Import Ident.\nRequire Import Constants.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import CommonLib.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef2.Spec.\nRequire Import TableDataOpsRef2.Layer.\nRequire Import TableDataOpsRef3.Code.table_unmap3.\n\nRequire Import TableDataOpsRef3.LowSpecs.table_unmap3.\n\nLocal Open Scope Z_scope.\n\nSection CodeProof.\n\n  Context `{real_params: RealParams}.\n  Context {memb} `{Hmemx: Mem.MemoryModelX memb}.\n  Context `{Hmwd: UseMemWithData memb}.\n\n  Let mem := mwd (cdata RData).\n\n  Context `{Hstencil: Stencil}.\n  Context `{make_program_ops: !MakeProgramOps Clight.function type Clight.fundef type}.\n  Context `{Hmake_program: !MakeProgram Clight.function type Clight.fundef type}.\n\n  Let L : compatlayer (cdata RData) :=\n    _table_unmap ↦ gensem table_unmap_spec\n      ⊕ _table_unmap2 ↦ gensem table_unmap2_spec\n  .\n\n  Local Instance: ExternalCallsOps mem := CompatExternalCalls.compatlayer_extcall_ops L.\n  Local Instance: CompilerConfigOps mem := CompatExternalCalls.compatlayer_compiler_config_ops L.\n\n  Section BodyProof.\n\n    Context `{Hwb: WritableBlockOps}.\n    Variable (sc: stencil).\n    Variables (ge: genv) (STENCIL_MATCHES: stencil_matches sc ge).\n\n    Variable b_table_unmap: block.\n    Hypothesis h_table_unmap_s : Genv.find_symbol ge _table_unmap = Some b_table_unmap.\n    Hypothesis h_table_unmap_p : Genv.find_funct_ptr ge b_table_unmap\n                                 = Some (External (EF_external _table_unmap\n                                                  (signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default))\n                                        (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default).\n    Local Opaque table_unmap_spec.\n\n    Variable b_table_unmap2: block.\n    Hypothesis h_table_unmap2_s : Genv.find_symbol ge _table_unmap2 = Some b_table_unmap2.\n    Hypothesis h_table_unmap2_p : Genv.find_funct_ptr ge b_table_unmap2\n                                  = Some (External (EF_external _table_unmap2\n                                                   (signature_of_type (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default))\n                                         (Tcons Tptr (Tcons tulong (Tcons tulong Tnil))) tulong cc_default).\n    Local Opaque table_unmap2_spec.\n\n    Lemma table_unmap3_body_correct:\n      forall m d d' env le g_rd_base g_rd_offset map_addr level res\n             (Henv: env = PTree.empty _)\n             (Hinv: high_level_invariant d)\n             (HPTg_rd: PTree.get _g_rd le = Some (Vptr g_rd_base (Int.repr g_rd_offset)))\n             (HPTmap_addr: PTree.get _map_addr le = Some (Vlong map_addr))\n             (HPTlevel: PTree.get _level le = Some (Vlong level))\n             (Hspec: table_unmap3_spec0 (g_rd_base, g_rd_offset) (VZ64 (Int64.unsigned map_addr)) (VZ64 (Int64.unsigned level)) d = Some (d', VZ64 (Int64.unsigned res))),\n           exists le', (exec_stmt ge env le ((m, d): mem) table_unmap3_body E0 le' (m, d') (Out_return (Some (Vlong res, tulong)))).\n    Proof.\n      solve_code_proof Hspec table_unmap3_body; eexists; solve_proof_low.\n    Qed.\n\n  End BodyProof.\n\nEnd CodeProof.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef3/CodeProof/table_unmap3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2069500997085448}}
{"text": "From iris.program_logic Require Export language ectx_language ectxi_language.\nFrom iris_io.prelude Require Export base.\nFrom iris_io Require Export lang_proph_erased.\nFrom iris.algebra Require Export ofe.\nFrom stdpp Require Import gmap.\n\nModule Plang_fully_erased.\n\n  Record fully_erased_state : Type :=\n    { FEHeap : gmap loc val;\n      FEProph : (gset loc);\n      FEIO : list (ioTag * val * val)\n    }.\n\n  Definition update_FEheap σ h :=\n    {| FEHeap := h; FEProph := FEProph σ; FEIO := FEIO σ |}.\n\n  Definition update_FEproph σ ι :=\n    {| FEHeap := FEHeap σ; FEProph := ι; FEIO := FEIO σ |}.\n\n   Definition update_FEIO σ τ :=\n    {| FEHeap := FEHeap σ; FEProph := FEProph σ; FEIO := τ |}.\n\n  Inductive fully_erased_head_step :\n    expr → fully_erased_state → expr → fully_erased_state → list expr → Prop :=\n  (* β *)\n  | FEBetaS e1 e2 v2 σ :\n      to_val e2 = Some v2 →\n      fully_erased_head_step (App (Rec e1) e2) σ e1.[(Rec e1), e2/] σ []\n  | FEZetaS e1 e2 v1 σ :\n      to_val e1 = Some v1 →\n      fully_erased_head_step (LetIn e1 e2) σ e2.[e1/] σ []\n  | FELamBetaS e1 e2 v2 σ :\n      to_val e2 = Some v2 →\n      fully_erased_head_step (App (Lam e1) e2) σ e1.[e2/] σ []\n  | FESeqS e1 e2 v1 σ :\n      to_val e1 = Some v1 →\n      fully_erased_head_step (Seq e1 e2) σ e2 σ []\n  (* Products *)\n  | FEFstS e1 v1 e2 v2 σ :\n      to_val e1 = Some v1 → to_val e2 = Some v2 →\n      fully_erased_head_step (Fst (Pair e1 e2)) σ e1 σ []\n  | FESndS e1 v1 e2 v2 σ :\n      to_val e1 = Some v1 → to_val e2 = Some v2 →\n      fully_erased_head_step (Snd (Pair e1 e2)) σ e2 σ []\n  (* Sums *)\n  | FECaseLS e0 v0 e1 e2 σ :\n      to_val e0 = Some v0 →\n      fully_erased_head_step (Case (InjL e0) e1 e2) σ e1.[e0/] σ []\n  | FECaseRS e0 v0 e1 e2 σ :\n      to_val e0 = Some v0 →\n      fully_erased_head_step (Case (InjR e0) e1 e2) σ e2.[e0/] σ []\n    (* nat bin op *)\n  | FEBinOpS op a b σ :\n      fully_erased_head_step (BinOp op (#n a) (#n b)) σ (of_val (binop_eval op a b)) σ []\n  (* If then else *)\n  | FEIfFalse e1 e2 σ :\n      fully_erased_head_step (If (#♭ false) e1 e2) σ e2 σ []\n  | FEIfTrue e1 e2 σ :\n      fully_erased_head_step (If (#♭ true) e1 e2) σ e1 σ []\n  (* Recursive Types *)\n  | FEUnfold_Fold e v σ :\n      to_val e = Some v →\n      fully_erased_head_step (Unfold (Fold e)) σ e σ []\n  (* Polymorphic Types *)\n  | FETBeta e σ :\n      fully_erased_head_step (TApp (TLam e)) σ e σ []\n  (* Concurrency *)\n  | FEForkS e σ:\n      fully_erased_head_step (Fork e) σ Unit σ [e]\n  (* Reference Types *)\n  | FEAllocS e v σ l :\n     to_val e = Some v → (FEHeap σ) !! l = None →\n     fully_erased_head_step (Alloc e) σ (Loc l) (update_FEheap σ (<[l:=v]>(FEHeap σ))) []\n  | FELoadS l v σ :\n     (FEHeap σ) !! l = Some v →\n     fully_erased_head_step (Load (Loc l)) σ (of_val v) σ []\n  | FEStoreS l e v σ :\n     to_val e = Some v → is_Some ((FEHeap σ) !! l) →\n     fully_erased_head_step (Store (Loc l) e) σ Unit (update_FEheap σ (<[l:=v]>(FEHeap σ))) []\n  (* Compare and swap *)\n  | FECasFailS l e1 v1 e2 v2 vl σ :\n     to_val e1 = Some v1 → to_val e2 = Some v2 →\n     (FEHeap σ) !! l = Some vl → vl ≠ v1 →\n     fully_erased_head_step (CAS (Loc l) e1 e2) σ (#♭ false) σ []\n  | FECasSucS l e1 v1 e2 v2 σ :\n     to_val e1 = Some v1 → to_val e2 = Some v2 →\n     (FEHeap σ) !! l = Some v1 →\n     fully_erased_head_step (CAS (Loc l) e1 e2) σ (#♭ true) (update_FEheap σ (<[l:=v2]>(FEHeap σ))) []\n  (* Prophecy operational semantics *)\n  | FECreate_PrS σ :\n      fully_erased_head_step Create_Pr σ (Pr (fresh (FEProph σ)))\n                       (update_FEproph σ ({[fresh (FEProph σ)]} ∪ (FEProph σ))) []\n  | FEAssignS e v e' v' σ :\n      to_val e = Some v → to_val e' = Some v' →\n     fully_erased_head_step (Assign_Pr e e') σ Unit σ []\n  | FERandS b σ : fully_erased_head_step Rand σ (Bool b) σ []\n  | FEIOS t e v v' σ : to_val e = Some v →\n                    fully_erased_head_step (IO (IOtag t) e) σ (of_val v')\n                              (update_FEIO σ ((FEIO σ) ++ [(t, v, v')])) [].\n\n  (** Basic properties about the language *)\n  Lemma val_stuck e1 σ1 e2 σ2 ef :\n    fully_erased_head_step e1 σ1 e2 σ2 ef → to_val e1 = None.\n  Proof. destruct 1; naive_solver. Qed.\n\n  Lemma head_ctx_step_val Ki e σ1 e2 σ2 ef :\n    fully_erased_head_step (fill_item Ki e) σ1 e2 σ2 ef → is_Some (to_val e).\n  Proof. destruct Ki; inversion_clear 1; simplify_option_eq; eauto. Qed.\n\n  Lemma alloc_fresh e v σ :\n    let l := fresh (dom (gset loc) (FEHeap σ)) in\n    to_val e = Some v → fully_erased_head_step (Alloc e) σ (Loc l)\n                                         (update_FEheap σ (<[l:=v]>(FEHeap σ))) [].\n  Proof. by intros; apply FEAllocS, (not_elem_of_dom (D:=gset loc)), is_fresh. Qed.\n\n  Lemma val_head_stuck e1 σ1 e2 σ2 efs : fully_erased_head_step e1 σ1 e2 σ2 efs → to_val e1 = None.\n  Proof. destruct 1; naive_solver. Qed.\n\n  Lemma lang_mixin : EctxiLanguageMixin of_val to_val fill_item\n                                        fully_erased_head_step.\n  Proof.\n    split; apply _ || eauto using to_of_val, of_to_val, val_head_stuck,\n           fill_item_val, fill_item_no_val_inj, head_ctx_step_val.\n  Qed.\n\nEnd Plang_fully_erased.\n\nCanonical Structure PFE_ectxi_lang :=\n  EctxiLanguage Plang_fully_erased.lang_mixin.\nCanonical Structure PFE_ectx_lang :=\n  EctxLanguageOfEctxi PFE_ectxi_lang.\nCanonical Structure PFE_lang :=\n  LanguageOfEctx PFE_ectx_lang.\n\nExport Plang_fully_erased.\n", "meta": {"author": "amintimany", "repo": "iris-io", "sha": "f6d3404ea1c8afcba715890c2b502719a8fe1fc6", "save_path": "github-repos/coq/amintimany-iris-io", "path": "github-repos/coq/amintimany-iris-io/iris-io-f6d3404ea1c8afcba715890c2b502719a8fe1fc6/lang_fully_erased.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.20688569327747924}}
{"text": "(* Generated by coq-of-rust *)\nRequire Import CoqOfRust.CoqOfRust.\n\nImport Root.std.prelude.rust_2015.\n\nModule checked.\n  Module MathError.\n    Inductive t : Set :=\n    | DivisionByZero\n    | NonPositiveLogarithm\n    | NegativeSquareRoot.\n  End MathError.\n  Definition MathError := MathError.t.\n  \n  Module Impl__crate_fmt_Debug_for_MathError.\n    Definition Self := MathError.\n    \n    Definition fmt\n        (self : ref Self)\n        (f : mut_ref _crate.fmt.Formatter)\n        : _crate.fmt.Result :=\n      match self with\n      | MathError.DivisionByZero =>\n        _crate.fmt.ImplFormatter.write_str f \"DivisionByZero\"\n      | MathError.NonPositiveLogarithm =>\n        _crate.fmt.ImplFormatter.write_str f \"NonPositiveLogarithm\"\n      | MathError.NegativeSquareRoot =>\n        _crate.fmt.ImplFormatter.write_str f \"NegativeSquareRoot\"\n      end.\n    \n    Global Instance M_fmt : Method \"fmt\" _ := {|\n      method := fmt;\n    |}.\n    Global Instance AF_fmt : MathError.AssociatedFunction \"fmt\" _ := {|\n      MathError.associated_function := fmt;\n    |}.\n    Global Instance AFT_fmt : _crate.fmt.Debug.AssociatedFunction \"fmt\" _ := {|\n      _crate.fmt.Debug.associated_function := fmt;\n    |}.\n    \n    Global Instance I : _crate.fmt.Debug.Class Self := {|\n      _crate.fmt.Debug.fmt := fmt;\n    |}.\n  End Impl__crate_fmt_Debug_for_MathError.\n  \n  Definition MathResult : Set := Result.\n  \n  Definition div (x : f64) (y : f64) : MathResult :=\n    if (eqb y 0 (* 0.0 *) : bool) then\n      Err MathError.DivisionByZero\n    else\n      Ok (div x y).\n  \n  Definition sqrt (x : f64) : MathResult :=\n    if (lt x 0 (* 0.0 *) : bool) then\n      Err MathError.NegativeSquareRoot\n    else\n      Ok (method \"sqrt\" x).\n  \n  Definition ln (x : f64) : MathResult :=\n    if (le x 0 (* 0.0 *) : bool) then\n      Err MathError.NonPositiveLogarithm\n    else\n      Ok (method \"ln\" x).\n  \n  Definition op_ (x : f64) (y : f64) : MathResult :=\n    let ratio :=\n      match branch (div x y) with\n      | Break {| Break.0 := residual; |} => Return (from_residual residual)\n      | Continue {| Continue.0 := val; |} => val\n      end in\n    let ln :=\n      match branch (ln ratio) with\n      | Break {| Break.0 := residual; |} => Return (from_residual residual)\n      | Continue {| Continue.0 := val; |} => val\n      end in\n    sqrt ln.\n  \n  Definition op (x : f64) (y : f64) : unit :=\n    match op_ x y with\n    | Err (why) =>\n      _crate.rt.panic_display\n        match why with\n        | MathError.NonPositiveLogarithm => \"logarithm of non-positive number\"\n        | MathError.DivisionByZero => \"division by zero\"\n        | MathError.NegativeSquareRoot => \"square root of negative number\"\n        end\n    | Ok (value) =>\n      _crate.io._print\n        (_crate.fmt.ImplArguments.new_v1\n          [ \"\"; \"\\n\" ]\n          [ _crate.fmt.ImplArgumentV1.new_display value ]) ;;\n      tt\n    end.\nEnd checked.\n\nModule MathError.\n  Inductive t : Set :=\n  | DivisionByZero\n  | NonPositiveLogarithm\n  | NegativeSquareRoot.\nEnd MathError.\nDefinition MathError := MathError.t.\n\nModule Impl__crate_fmt_Debug_for_MathError.\n  Definition Self := MathError.\n  \n  Definition fmt\n      (self : ref Self)\n      (f : mut_ref _crate.fmt.Formatter)\n      : _crate.fmt.Result :=\n    match self with\n    | MathError.DivisionByZero =>\n      _crate.fmt.ImplFormatter.write_str f \"DivisionByZero\"\n    | MathError.NonPositiveLogarithm =>\n      _crate.fmt.ImplFormatter.write_str f \"NonPositiveLogarithm\"\n    | MathError.NegativeSquareRoot =>\n      _crate.fmt.ImplFormatter.write_str f \"NegativeSquareRoot\"\n    end.\n  \n  Global Instance M_fmt : Method \"fmt\" _ := {|\n    method := fmt;\n  |}.\n  Global Instance AF_fmt : MathError.AssociatedFunction \"fmt\" _ := {|\n    MathError.associated_function := fmt;\n  |}.\n  Global Instance AFT_fmt : _crate.fmt.Debug.AssociatedFunction \"fmt\" _ := {|\n    _crate.fmt.Debug.associated_function := fmt;\n  |}.\n  \n  Global Instance I : _crate.fmt.Debug.Class Self := {|\n    _crate.fmt.Debug.fmt := fmt;\n  |}.\nEnd Impl__crate_fmt_Debug_for_MathError.\n\nDefinition MathResult : Set := Result.\n\nDefinition div (x : f64) (y : f64) : MathResult :=\n  if (eqb y 0 (* 0.0 *) : bool) then\n    Err MathError.DivisionByZero\n  else\n    Ok (div x y).\n\nDefinition sqrt (x : f64) : MathResult :=\n  if (lt x 0 (* 0.0 *) : bool) then\n    Err MathError.NegativeSquareRoot\n  else\n    Ok (method \"sqrt\" x).\n\nDefinition ln (x : f64) : MathResult :=\n  if (le x 0 (* 0.0 *) : bool) then\n    Err MathError.NonPositiveLogarithm\n  else\n    Ok (method \"ln\" x).\n\nDefinition op_ (x : f64) (y : f64) : MathResult :=\n  let ratio :=\n    match branch (div x y) with\n    | Break {| Break.0 := residual; |} => Return (from_residual residual)\n    | Continue {| Continue.0 := val; |} => val\n    end in\n  let ln :=\n    match branch (ln ratio) with\n    | Break {| Break.0 := residual; |} => Return (from_residual residual)\n    | Continue {| Continue.0 := val; |} => val\n    end in\n  sqrt ln.\n\nDefinition op (x : f64) (y : f64) : unit :=\n  match op_ x y with\n  | Err (why) =>\n    _crate.rt.panic_display\n      match why with\n      | MathError.NonPositiveLogarithm => \"logarithm of non-positive number\"\n      | MathError.DivisionByZero => \"division by zero\"\n      | MathError.NegativeSquareRoot => \"square root of negative number\"\n      end\n  | Ok (value) =>\n    _crate.io._print\n      (_crate.fmt.ImplArguments.new_v1\n        [ \"\"; \"\\n\" ]\n        [ _crate.fmt.ImplArgumentV1.new_display value ]) ;;\n    tt\n  end.\n\nDefinition main (_ : unit) : unit :=\n  checked.op 1 (* 1.0 *) 10 (* 10.0 *) ;;\n  tt.\n", "meta": {"author": "formal-land", "repo": "coq-of-rust", "sha": "6b3fd42f09c996dd89ecf39c0f50f78baa681c73", "save_path": "github-repos/coq/formal-land-coq-of-rust", "path": "github-repos/coq/formal-land-coq-of-rust/coq-of-rust-6b3fd42f09c996dd89ecf39c0f50f78baa681c73/coq_translation/examples-from-rust-book/std_library_types/result_chaining_with_question_mark.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.20684873326051081}}
{"text": "Require Import Thread Arrays8 MoreArrays Buffers Io.\n\nLocal Hint Extern 1 (@eq W _ _) => words.\n\n\nModule Type S.\n  Parameters globalSched globalSock : W.\n\n  Parameter inbuf_size : nat.\n  Axiom inbuf_size_lower : (inbuf_size >= 2)%nat.\n  Axiom inbuf_size_upper : (N_of_nat (inbuf_size * 4) < Npow2 32)%N.\n\n  Parameters port numWorkers : W.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nModule M'''.\n  Definition globalSched := M.globalSched.\n\n  Open Scope Sep_scope.\n\n  Definition globalInv (fs : files) : HProp := Ex fr, globalSock =*> fr * [| fr %in fs |].\nEnd M'''.\n\nModule T := Thread.Make(M''').\n\nImport T M'''.\nExport T M'''.\n\nModule MyM.\n  Definition sched := sched.\n  Definition globalInv := globalInv.\nEnd MyM.\n\nLtac unf := unfold MyM.sched, MyM.globalInv, M'''.globalSched, M'''.globalInv in *.\n\nModule MyIo := Io.Make(MyM).\n\n\nDefinition hints : TacPackage.\n  prepare (materialize_buffer, buffer_split_tagged) buffer_join_tagged.\nDefined.\n\nDefinition mainS := SPEC reserving 49\n  PREmain[_] globalSched =?> 1 * globalSock =?> 1 * mallocHeap 0.\n\nDefinition handlerS := SPEC reserving 99\n  Al fs, PREmain[_] sched fs * globalInv fs * mallocHeap 0.\n\nDefinition bsize := (inbuf_size * 4)%nat.\n\nDefinition m := bimport [[ \"buffers\"!\"bmalloc\" @ [bmallocS],\n                           \"scheduler\"!\"init\"@ [T.Q''.initS], \"scheduler\"!\"exit\" @ [T.Q''.exitS],\n                           \"scheduler\"!\"spawn\" @ [T.Q''.spawnS], \"scheduler\"!\"listen\" @ [T.Q''.listenS],\n                           \"scheduler\"!\"accept\" @ [T.Q''.acceptS], \"scheduler\"!\"close\" @ [T.Q''.closeS],\n                           \"scheduler\"!\"read\" @ [T.Q''.readS], \"io\"!\"writeAll\" @ [MyIo.writeAllS] ]]\n  bmodule \"echo\" {{\n    bfunctionNoRet \"handler\"(\"buf\", \"fr\", \"n\") [handlerS]\n      \"buf\" <-- Call \"buffers\"!\"bmalloc\"(inbuf_size)\n      [Al fs, PREmain[V, R] R =?>8 bsize * sched fs * globalInv fs * mallocHeap 0];;\n\n      [Al fs, PREmain[V] V \"buf\" =?>8 bsize * sched fs * globalInv fs * mallocHeap 0]\n      While (0 = 0) {\n        \"fr\" <-- Call \"scheduler\"!\"accept\"($[globalSock])\n        [Al fs, PREmain[V, R] [| R %in fs |] * V \"buf\" =?>8 bsize * sched fs * globalInv fs * mallocHeap 0];;\n\n        \"n\" <-- Call \"scheduler\"!\"read\"(\"fr\", \"buf\", bsize)\n        [Al fs, PREmain[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 bsize * sched fs * globalInv fs * mallocHeap 0];;\n\n        [Al fs, PREmain[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 bsize * sched fs * globalInv fs * mallocHeap 0]\n        While (\"n\" <> 0) {\n          If (\"n\" <= bsize) {\n            Call \"io\"!\"writeAll\"(\"fr\", \"buf\", 0, \"n\")\n            [Al fs, PREmain[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 bsize * sched fs * globalInv fs * mallocHeap 0]\n          } else {\n            Skip\n          };;\n\n          \"n\" <-- Call \"scheduler\"!\"read\"(\"fr\", \"buf\", bsize)\n          [Al fs, PREmain[V] [| V \"fr\" %in fs |] * V \"buf\" =?>8 bsize * sched fs * globalInv fs * mallocHeap 0]\n        };;\n\n        Call \"scheduler\"!\"close\"(\"fr\")\n        [Al fs, PREmain[V] V \"buf\" =?>8 bsize * sched fs * globalInv fs * mallocHeap 0]\n      }\n    end with bfunctionNoRet \"main\"(\"fr\", \"x\") [mainS]\n      Init\n      [Al fs, Al v, PREmain[_] sched fs * globalSock =*> v * mallocHeap 0];;\n\n      \"fr\" <- 0;;\n      [Al fs, PREmain[_] sched fs * globalSock =?> 1 * mallocHeap 0]\n      While (\"fr\" < numWorkers) {\n        Spawn(\"echo\"!\"handler\", 100)\n        [Al fs, PREmain[_] sched fs * globalSock =?> 1 * mallocHeap 0];;\n        \"fr\" <- \"fr\" + 1\n      };;\n\n      \"fr\" <-- Call \"scheduler\"!\"listen\"(port)\n      [Al fs, Al v, PREmain[_, R] [| R %in fs |] * sched fs * globalSock =*> v * mallocHeap 0];;\n\n      globalSock *<- \"fr\";;\n\n      Exit 50\n    end\n  }}.\n\nLemma le_bsize : forall w : W,\n  w <= natToW bsize\n  -> (wordToNat w <= bsize)%nat.\n  intros; pre_nomega;\n    rewrite wordToNat_natToWord_idempotent in * by apply inbuf_size_upper; assumption.\nQed.\n\nLocal Hint Immediate le_bsize.\n\nLemma inbuf_size_small : (N.of_nat inbuf_size < Npow2 32)%N.\n  specialize inbuf_size_upper;  generalize (Npow2 32); intros; nomega.\nQed.\n\nHint Rewrite Nat2N.inj_mul N2Nat.inj_mul : N.\nLemma le_inbuf_size : natToW 2 <= natToW inbuf_size.\n  pre_nomega; rewrite wordToNat_natToWord_idempotent by apply inbuf_size_small;\n    rewrite wordToNat_natToWord_idempotent by reflexivity; apply inbuf_size_lower.\nQed.\n\nLocal Hint Immediate le_inbuf_size.\n\nLemma roundTrip_inbuf_size : wordToNat (natToW inbuf_size) = inbuf_size.\n  rewrite wordToNat_natToWord_idempotent by apply inbuf_size_small; auto.\nQed.\n\nLemma roundTrip_bsize : wordToNat (natToW bsize) = bsize.\n  rewrite wordToNat_natToWord_idempotent by apply inbuf_size_upper; auto.\nQed.\n\nHint Rewrite roundTrip_inbuf_size roundTrip_bsize : sepFormula.\n\nTheorem goodSize_bsize : goodSize bsize.\n  apply inbuf_size_upper.\nQed.\n\nLocal Hint Immediate goodSize_bsize.\n\nLtac t := try solve [ sep unf hints; auto ];\n  unf; unfold localsInvariantMain; post; evaluate hints; descend;\n    try match_locals; sep unf hints; auto.\n\nTheorem ok : moduleOk m.\n  vcgen; abstract t.\nQed.\n\nEnd Make.\n", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/tests/EchoServer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.20684873326051081}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import qsort4a.\nRequire Import spec_qsort4.\nRequire Import verif_qsort4_aux1.\nRequire Import float_lemmas.\nRequire Import Permutation.\nSet Nested Proofs Allowed.\n\nLemma is_finite_Float_of_int:\n forall i,  Binary.is_finite 53 1024 (Float.of_int i) = true.\nAdmitted. (* need this lemma from the Flocq people... *)\n\nLemma def_float_of_int:\n  forall i, def_float (Vfloat (Float.of_int i)).\nProof.\nintros.\nsimpl.\napply is_finite_Float_of_int.\nQed.\n\nLemma body_compar_double:  semax_body Vprog Gprog f_compar_double compar_double_spec.\nProof.\nstart_function.\ndestruct H as [? [_ ?]].\ndestruct H0 as [? [_ ?]].\nforward.\nentailer!.\ndestruct x; try contradiction; simpl; auto.\nforward.\nentailer!.\ndestruct y; try contradiction; simpl; auto.\ndestruct x; try contradiction. rename f into x.\ndestruct y; try contradiction. rename f into y.\nforward_if (\n  EX c:Datatypes.comparison,\n  PROP(match c with\n              | Eq => ord_eq double_le_order (Vfloat x) (Vfloat y)\n              | Lt => ord_lt double_le_order (Vfloat x) (Vfloat y)\n              | Gt => ord_lt double_le_order (Vfloat y) (Vfloat x)\n             end) \n  (LOCAL (temp _t'1 \n              (Vint (Int.repr (match c with Lt => -1 | Eq => 0 | Gt => 1 end))))\n  (SEP (data_at shp tdouble (Vfloat x) p; data_at shq tdouble (Vfloat y) q))))%assert.\n-\nforward.\nExists Lt.\nentailer!.\nhnf. simpl. unfold f_le.\nintuition.\nred.\nrewrite Float.cmp_le_lt_eq.\nrewrite orb_true_iff; auto.\nred in H11.\nrewrite Float.cmp_le_lt_eq in H11.\nrewrite orb_true_iff in H11; auto.\ndestruct H11.\nrewrite (Float.cmp_swap Cgt) in H10.\napply Float.cmp_lt_gt_false in H10; auto.\neapply Float.cmp_lt_eq_false; eauto.\nrewrite <- Float.cmp_swap; auto.\n-\nforward_if.\n+\nforward.\nforward.\nExists Eq.\nentailer!.\nhnf. simpl. unfold f_le.\nintuition.\nred.\nrewrite Float.cmp_le_lt_eq.\nrewrite orb_true_iff.\nauto.\nred.\nrewrite <- Float.cmp_swap; simpl.\nrewrite Float.cmp_ge_gt_eq.\nrewrite orb_true_iff.\nauto.\n+\nforward.\nforward.\nExists Gt.\nentailer!.\nhnf. simpl. unfold f_le.\nintuition.\nred.\nrewrite Float.cmp_le_lt_eq.\nrewrite orb_true_iff.\npose proof (f_cmp_false Clt x y H H0 H3).\nsimpl in H9.\nrewrite Float.cmp_ge_gt_eq in H9.\nrewrite orb_true_iff in H9.\ndestruct H9; auto.\nleft.\nrewrite <- Float.cmp_swap; auto.\nright.\nrewrite <- Float.cmp_swap; auto.\nred in H12.\nrewrite Float.cmp_le_lt_eq in H12.\nrewrite orb_true_iff in H12.\ndestruct H12.\nrewrite H3 in H11; inv H11.\nrewrite H4 in H11; inv H11.\n-\nIntros c; forward; Exists c.\nentailer!.\nQed.\n\nSearch (int->float).\n\nFixpoint upto (n: nat) (k: Z) : list val :=\n match n with\n | O => nil\n | S n' => Vfloat (Float.of_int (Int.repr k)) ::\n                upto n' (Z.succ k)\n end.\n\nLemma Zlength_upto: forall i k, \n  0 <= i -> Zlength (upto (Z.to_nat i) k) = i.\nProof.\nintros.\nrewrite <- (Z2Nat.id i) at 2 by lia.\nrewrite <- (Z2Nat.id i) in H by lia.\nrevert k; induction (Z.to_nat i); intros.\nsimpl. reflexivity.\nunfold upto; fold upto.\nrewrite Zlength_cons.\nrewrite Nat2Z.inj_succ.\nrewrite IHn; auto.\nlia.\nQed.\n\nLemma upto_another:\n  forall i k, 0 <= i ->\n    upto (Z.to_nat (i+1)) k = \n   upto (Z.to_nat i) k ++ [Vfloat (Float.of_int (Int.repr (i+k)))].\nProof.\nintros.\nreplace (i+1) with (Z.succ i) by lia.\nrewrite Z2Nat.inj_succ by lia.\nrewrite <- (Z2Nat.id i) at 3 by lia.\nclear.\nrevert k; induction (Z.to_nat i); intros.\nsimpl.\nrewrite Z.add_0_l; auto.\nchange (upto (S (S n)) k) with\n (Vfloat (Float.of_int (Int.repr k)) ::\n upto (S n) (Z.succ k)).\nrewrite (IHn (Z.succ k)).\nrewrite app_comm_cons.\nf_equal.\nf_equal.\nf_equal.\nf_equal.\nf_equal.\nrewrite Nat2Z.inj_succ.\nlia.\nQed.\n\nOpaque upto.\n\n\nDefinition main_printf_loop :=\n        (Ssequence\n          (Sset _i (Econst_int (Int.repr 0) tint))\n          (Sloop\n            (Ssequence\n              (Sifthenelse (Ebinop Olt (Etempvar _i tint)\n                             (Econst_int (Int.repr 666666) tint) tint)\n                Sskip\n                Sbreak)\n              (Ssequence\n                (Sset _t'1\n                  (Ederef\n                    (Ebinop Oadd (Evar _a (tarray tdouble 666666))\n                      (Etempvar _i tint) (tptr tdouble)) tdouble))\n                (Scall None\n                  (Evar _printf (Tfunction (Tcons (tptr tschar) Tnil) tint\n                                  {|cc_vararg:=true; cc_unproto:=false; cc_structret:=false|}))\n                  ((Evar ___stringlit_1 (tarray tschar 4)) ::\n                   (Etempvar _t'1 tdouble) :: nil))))\n            (Sset _i\n              (Ebinop Oadd (Etempvar _i tint) (Econst_int (Int.repr 1) tint)\n                tint)))).\n\nLemma verif_main_printf_loop:\n forall (Espec : OracleKind)\n  (gv : globals)\n  (bl : list (reptype tdouble))\n  (H : Permutation (upto (Z.to_nat N6) 0) bl)\n  (H0 : sorted (ord_le double_le_order) bl),\n semax (func_tycontext f_main Vprog Gprog nil)\n  (PROP ( )\n   LOCAL (gvars gv)\n   SEP (data_at Ews (tarray tdouble N6) bl (gv _a);\n   data_at Ers (tarray tschar 4)\n     (map (Vint oo cast_int_int I8 Signed)\n        [Int.repr 37; Int.repr 102; Int.repr 10; Int.repr 0])\n     (gv ___stringlit_1))) main_printf_loop\n  (normal_ret_assert\n     (PROP ( )\n      LOCAL (gvars gv)\n      SEP (data_at Ews (tarray tdouble N6) bl (gv _a);\n      data_at Ers (tarray tschar 4)\n        (map (Vint oo cast_int_int I8 Signed)\n           [Int.repr 37; Int.repr 102; Int.repr 10; Int.repr 0])\n        (gv ___stringlit_1)))).\nAdmitted.  (* I claim that it is all right to Admit this lemma because\n the technical report, \"A benchmark for C program verification\",\n in the table on page 3, lists a blank (not an X)\n in row \"qsort\" column \"I/O\".  Therefore we don't have to verify\n the input/output in this benchmark.   *)\n\nLemma body_main:  semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nforward_for_simple_bound N6\n  (EX i:Z,\n   PROP() LOCAL (gvars gv) \n   SEP (data_at Ews (tarray tdouble N6) \n            (upto (Z.to_nat i) 0 ++ list_repeat (Z.to_nat (N6-i)) Vundef) (gv _a);\n          data_at Ers (tarray tschar 4)\n           (map (Vint oo cast_int_int I8 Signed)\n               [Int.repr 37; Int.repr 102; Int.repr 10; Int.repr 0])\n            (gv ___stringlit_1);\n           has_ext tt)).\n-\nrewrite <- N6_eq.\nauto.\n-\nrewrite <- N6_eq.\nentailer!.\nchange (upto (Z.to_nat 0) 0) with (@nil val).\nunfold app. cancel.\n-\nforward.\nentailer!.\napply derives_refl'.\nf_equal.\nreplace (Z.to_nat (N6 - i))\n  with (S (Z.to_nat (N6-(i+1)))).\n2:{ clear - H. replace (N6-i) with (Z.succ (N6-(i+1))) by lia.\n     rewrite Z2Nat.inj_succ by lia. auto.\n}\n unfold list_repeat; fold @list_repeat.\n rewrite upd_Znth_app2.\n2:{  rewrite Zlength_upto by lia. autorewrite with sublist. lia. }\n rewrite Zlength_upto by lia.\n rewrite Z.sub_diag.\n rewrite upd_Znth0.\n rewrite upto_another by lia.\n rewrite app_ass. f_equal. simpl. normalize.\n-\n(* after the for-loop *)\nautorewrite with sublist.\nset (al := upto (Z.to_nat N6) 0).\nmake_func_ptr _compar_double.\nassert (H_ok:\ncomplete_legal_cosu_type tdouble = true /\\\n               align_compatible_rec cenv_cs tdouble 0 /\\\n               no_volatiles tdouble). {\n  split3; try reflexivity.\n  eapply align_compatible_rec_by_value.\n  reflexivity.\n  apply Z.divide_0_r.\n}\nassert (Hdef: Forall (ord_def double_le_order) al). {\n clear.\n subst al.\n forget 0 as k.\n revert k; induction (Z.to_nat N6); simpl; intros.\n constructor.\n change (upto (S n) k) with \n   (Vfloat (Float.of_int (Int.repr k)) :: upto n (Z.succ k)).\n constructor; auto.\n red. simpl. red.\n pose proof (def_float_of_int (Int.repr k)).\n split3; auto.\n apply f_le_refl; auto.\n}\npose (w := Build_qsort_witness _ tdouble H_ok \n                    double_le_order al Hdef).\nassert (Zlength al = N6) by (subst al; rewrite Zlength_upto; rep_lia).\nforward_call (Ews, gv _a, gv _compar_double, w);\n   simpl qsort_t;\n   simpl qsort_ord;\n   simpl qsort_al;\n  change (@reptype _ tdouble) with val.\n+\nrewrite <- N6_eq.\nentailer!.\nrewrite H; auto.\n+\nrewrite H.\ncancel.\n+\nrewrite H.\nsplit3; auto.\nsimpl sizeof.\ncomputable.\nsimpl sizeof.\nsplit; try rep_lia.\n+\nclear w H_ok Hdef.\nrewrite H.\nIntros bl.\ndeadvars!.\nunfold Sfor.\nfold main_printf_loop.\napply seq_assoc1.\neapply semax_seq'.\nchange (SEP (?R1; ?R2; ?R3)) with (@SEPx environ ([R1;R2]++[R3])).\nrewrite (app_nil_end [gvars gv]).\neapply semax_frame_PQR.\nunfold closed_wrt_modvars;  auto 50 with closed.\napply verif_main_printf_loop; auto.\nunfold app.\nforward.\nQed.\n\n\n\n\n\n\n\n\n", "meta": {"author": "cverified", "repo": "cbench-vst", "sha": "b3119729b39c4f5439dee78c633a9d2e3257df41", "save_path": "github-repos/coq/cverified-cbench-vst", "path": "github-repos/coq/cverified-cbench-vst/cbench-vst-b3119729b39c4f5439dee78c633a9d2e3257df41/qsort/verif_qsort4_main.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118493816806, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.20684872719225178}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*                Xavier Leroy, INRIA Paris                            *)\n(*                Jacques-Henri Jourdan, INRIA Paris                   *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation, either version 2 of the License, or  *)\n(*  (at your option) any later version.  This file is also distributed *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Architecture-dependent parameters for x86 in 64-bit mode *)\n\nRequire Import ZArith.\nRequire Import Fappli_IEEE.\nRequire Import Fappli_IEEE_bits.\n\nDefinition ptr64 := true.\n\nDefinition big_endian := false.\n\nDefinition align_int64 := 8%Z.\nDefinition align_float64 := 8%Z.\n\nDefinition splitlong := negb ptr64.\n\nLemma splitlong_ptr32: splitlong = true -> ptr64 = false.\nProof.\n  unfold splitlong. destruct ptr64; simpl; congruence.\nQed.\n\nProgram Definition default_pl_64 : bool * nan_pl 53 :=\n  (true, iter_nat 51 _ xO xH).\n\nDefinition choose_binop_pl_64 (s1: bool) (pl1: nan_pl 53) (s2: bool) (pl2: nan_pl 53) :=\n  false.                        (**r always choose first NaN *)\n\nProgram Definition default_pl_32 : bool * nan_pl 24 :=\n  (true, iter_nat 22 _ xO xH).\n\nDefinition choose_binop_pl_32 (s1: bool) (pl1: nan_pl 24) (s2: bool) (pl2: nan_pl 24) :=\n  false.                        (**r always choose first NaN *)\n\nDefinition float_of_single_preserves_sNaN := false.\n\nGlobal Opaque ptr64 big_endian splitlong\n              default_pl_64 choose_binop_pl_64\n              default_pl_32 choose_binop_pl_32\n              float_of_single_preserves_sNaN.\n", "meta": {"author": "CertiKOS", "repo": "compcert.old", "sha": "1fbd4e9beeb9e58b15f7f20ab1c949f6381a4105", "save_path": "github-repos/coq/CertiKOS-compcert.old", "path": "github-repos/coq/CertiKOS-compcert.old/compcert.old-1fbd4e9beeb9e58b15f7f20ab1c949f6381a4105/x86_64/Archi.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.20683896807388089}}
{"text": "(** * Dexter 2 FA1.2 Liquidity token contract *)\n(** This file contains an implementation of Dexter2 liquidity contract\n    https://gitlab.com/dexter2tz/dexter2tz/-/blob/1cec9d9333eba756603d6cd90ea9c70d482a5d3d/lqt_fa12.mligo\n    In addition this file contains proof of functional correctness w.r.t the\n    informal specification https://gitlab.com/dexter2tz/dexter2tz/-/blob/1cec9d9333eba756603d6cd90ea9c70d482a5d3d/docs/informal-spec/dexter2-lqt-fa12.md\n\n    This contract is an extension of a basic FA1.2 token contract with\n    an extra entrypoint that allows an admin to mint and burn tokens.\n    It is used in the Dexter2 exchange paired with an instance of the\n    Dexter2 CPMM contract. The purpose of this contract is to keep track\n    of ownership of the exchanges funds. A user who owns x% of the supply\n    of liquidity tokens owns x% of the exchanges trading reserve.\n*)\nFrom ConCert.Utils Require Import Extras.\nFrom ConCert.Utils Require Import RecordUpdate.\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import Containers.\nFrom ConCert.Execution Require Import Monad.\nFrom ConCert.Execution Require Import ResultMonad.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Execution Require Import InterContractCommunication.\nFrom ConCert.Execution Require Import ContractCommon.\nFrom Coq Require Import ZArith_base.\nFrom Coq Require Import List. Import ListNotations.\n\nDefinition non_zero_amount (amt : Z) : bool := (0 <? amt)%Z.\n\n(** * Contract types *)\n\nSection LQTFA12Types.\n  Context {BaseTypes : ChainBase}.\n  Open Scope N_scope.\n  Set Nonrecursive Elimination Schemes.\n\n  (* Dummy implementation of callbacks. *)\n  Record callback := {\n    return_addr : Address;\n  }.\n\n  Definition callback_addr (c : callback)\n                           : Address :=\n    c.(return_addr).\n  Coercion callback_addr : callback >-> Address.\n\n  Record transfer_param :=\n    build_transfer_param {\n      from : Address;\n      to : Address;\n      value : N\n  }.\n\n  Record approve_param :=\n    build_approve_param {\n      spender : Address;\n      value_ : N\n  }.\n\n  Record mintOrBurn_param :=\n    build_mintOrBurn_param {\n      quantity : Z;\n      target : Address\n  }.\n\n  Record getAllowance_param :=\n    build_getAllowance_param {\n      request : (Address * Address);\n      allowance_callback : callback\n  }.\n\n  Record getBalance_param :=\n    build_getBalance_param {\n      owner_ : Address;\n      balance_callback : callback\n  }.\n\n  Record getTotalSupply_param :=\n    build_getTotalSupply_param {\n      request_ : unit;\n      supply_callback : callback\n  }.\n\n  Record State :=\n    build_state {\n      tokens : FMap Address N;\n      allowances : FMap (Address * Address) N;\n      admin : Address;\n      total_supply : N\n  }.\n\n  Record Setup :=\n    build_setup {\n      admin_ : Address;\n      lqt_provider : Address;\n      initial_pool : N\n  }.\n\n  Definition Error : Type := nat.\n  Definition default_error : Error := 1%nat.\n\n  (* Any contract that wants to receive callback messages from the FA1.2 liquidity contract\n    should have this type as its Msg type. The contract may have other endpoints,\n    as composed in the 'other_msg' constructor. *)\n  Inductive FA12ReceiverMsg {Msg' : Type} :=\n  | receive_allowance : N -> FA12ReceiverMsg\n  | receive_balance_of : N -> FA12ReceiverMsg\n  | receive_total_supply : N -> FA12ReceiverMsg\n  | other_msg : Msg' -> FA12ReceiverMsg.\n\n  (* Liquidity FA1.2 Endpoints. *)\n  Inductive Msg :=\n  | msg_transfer : transfer_param -> Msg\n  | msg_approve : approve_param -> Msg\n  | msg_mint_or_burn : mintOrBurn_param -> Msg\n  | msg_get_allowance : getAllowance_param -> Msg\n  | msg_get_balance : getBalance_param -> Msg\n  | msg_get_total_supply : getTotalSupply_param -> Msg.\n\n  (* begin hide *)\n  MetaCoq Run (make_setters transfer_param).\n  MetaCoq Run (make_setters approve_param).\n  MetaCoq Run (make_setters mintOrBurn_param).\n  MetaCoq Run (make_setters getAllowance_param).\n  MetaCoq Run (make_setters getBalance_param).\n  MetaCoq Run (make_setters getTotalSupply_param).\n  MetaCoq Run (make_setters State).\n  MetaCoq Run (make_setters Setup).\n  (* end hide *)\n\n  Definition mintedOrBurnedTokens (msg : option Msg) : Z :=\n    match msg with\n    | Some (msg_mint_or_burn param) => param.(quantity)\n    | _ => 0\n    end.\n\n  Class LqtTokenInterface\n        `{Serializable State}\n        `{Serializable Msg}\n        `{Serializable Setup} :=\n    { lqt_contract : Contract Setup Msg State Error;\n\n      lqt_total_supply_correct :\n      forall (bstate : ChainState) (caddr : Address)\n        (trace : ChainTrace empty_state bstate),\n        env_contracts bstate caddr = Some (lqt_contract : WeakContract) ->\n        exists (cstate : State) (depinfo : DeploymentInfo Setup)\n          (inc_calls : list (ContractCallInfo Msg)),\n            contract_state bstate caddr = Some cstate /\\\n            deployment_info Setup trace caddr = Some depinfo /\\\n            incoming_calls Msg trace caddr = Some inc_calls /\\\n            (let initial_tokens := initial_pool (deployment_setup depinfo) in\n            Z.of_N (total_supply cstate) =\n              (Z.of_N initial_tokens +\n                  sumZ (fun callInfo => mintedOrBurnedTokens (call_msg callInfo))\n                      (filter (callFrom (admin cstate)) inc_calls))%Z) }.\n\nEnd LQTFA12Types.\n\nModule Type Dexter2LqtSerializable.\n  Section D2LqtSerializable.\n\n    Context `{ChainBase}.\n\n    Axiom callback_serializable : Serializable callback.\n\n    Axiom transfer_param_serializable : Serializable transfer_param.\n\n    Axiom approve_param_serializable : Serializable approve_param.\n\n    Axiom mintOrBurn_param_serializable : Serializable mintOrBurn_param.\n\n    Axiom getAllowance_param_serializable : Serializable getAllowance_param.\n\n    Axiom getBalance_param_serializable : Serializable getBalance_param.\n\n    Axiom getTotalSupply_param_serializable : Serializable getTotalSupply_param.\n\n    Axiom FA12ReceiverMsg_serializable : forall {Msg : Type} `{Serializable Msg}, Serializable (@FA12ReceiverMsg Msg).\n\n    Axiom msg_serializable : Serializable Msg.\n\n    Axiom state_serializable : Serializable State.\n\n    Axiom setup_serializable : Serializable Setup.\n\n  End D2LqtSerializable.\nEnd Dexter2LqtSerializable.\n\nModule D2LqtSInstances <: Dexter2LqtSerializable.\n  Section Serialization.\n    Context `{ChainBase}.\n\n    Instance callback_serializable : Serializable callback :=\n    Derive Serializable callback_rect <Build_callback>.\n\n    Instance transfer_param_serializable : Serializable transfer_param :=\n      Derive Serializable transfer_param_rect <build_transfer_param>.\n\n    Instance approve_param_serializable : Serializable approve_param :=\n      Derive Serializable approve_param_rect <build_approve_param>.\n\n    Instance mintOrBurn_param_serializable : Serializable mintOrBurn_param :=\n      Derive Serializable mintOrBurn_param_rect <build_mintOrBurn_param>.\n\n    Instance getAllowance_param_serializable : Serializable getAllowance_param :=\n      Derive Serializable getAllowance_param_rect <build_getAllowance_param>.\n\n    Instance getBalance_param_serializable : Serializable getBalance_param :=\n      Derive Serializable getBalance_param_rect <build_getBalance_param>.\n\n    Instance getTotalSupply_param_serializable : Serializable getTotalSupply_param :=\n      Derive Serializable getTotalSupply_param_rect <build_getTotalSupply_param>.\n\n    Instance FA12ReceiverMsg_serializable {Msg : Type}\n                                         `{Serializable Msg}\n                                          : Serializable (@FA12ReceiverMsg Msg) :=\n      Derive Serializable (@FA12ReceiverMsg_rect Msg) <\n        (@receive_allowance Msg),\n        (@receive_balance_of Msg),\n        (@receive_total_supply Msg),\n        (@other_msg Msg)>.\n\n    Instance msg_serializable : Serializable Msg :=\n      Derive Serializable Msg_rect <msg_transfer,\n                                  msg_approve,\n                                  msg_mint_or_burn,\n                                  msg_get_allowance,\n                                  msg_get_balance,\n                                  msg_get_total_supply>.\n\n    Instance state_serializable : Serializable State :=\n      Derive Serializable State_rect <build_state>.\n\n    Instance setup_serializable : Serializable Setup :=\n      Derive Serializable Setup_rect <build_setup>.\n  End Serialization.\nEnd D2LqtSInstances.\n\n\n\n(** * Contract functions *)\nModule Dexter2Lqt (SI : Dexter2LqtSerializable).\n  Import SI.\n\n  (* begin hide *)\n  #[global] Existing Instance callback_serializable.\n  #[global] Existing Instance transfer_param_serializable.\n  #[global] Existing Instance approve_param_serializable.\n  #[global] Existing Instance mintOrBurn_param_serializable.\n  #[global] Existing Instance getAllowance_param_serializable.\n  #[global] Existing Instance getBalance_param_serializable.\n  #[global] Existing Instance getTotalSupply_param_serializable.\n  #[global] Existing Instance FA12ReceiverMsg_serializable.\n  #[global] Existing Instance msg_serializable.\n  #[global] Existing Instance state_serializable.\n  #[global] Existing Instance setup_serializable.\n  (* end hide *)\n\n  Section DexterLqtDefs.\n    Context `{BaseTypes : ChainBase}.\n    Open Scope N_scope.\n\n    Definition find_allowance (k : Address * Address)\n                              (m : FMap (Address * Address) N)\n                              : option N :=\n      FMap.find k m.\n\n    Definition update_allowance (k : Address * Address)\n                                (val : option N)\n                                (m : FMap (Address * Address) N)\n                                : FMap (Address * Address) N :=\n      FMap.update k val m.\n\n    Definition empty_allowance : FMap (Address * Address) N :=\n      FMap.empty.\n\n    (** ** Transfer *)\n    (** Transfers [amount] tokens, if [from] has enough tokens to transfer\n        and [sender] is allowed to send that much on behalf of [from] *)\n    Definition try_transfer (sender : Address)\n                            (param : transfer_param)\n                            (state : State)\n                            : result State Error :=\n      let allowances_ := state.(allowances) in\n      let tokens_ := state.(tokens) in\n      do allowances_ <- (* Update allowances *)\n        (if address_eqb sender param.(from)\n        then Ok allowances_\n        else\n          let allowance_key := (param.(from), sender) in\n          let authorized_value := with_default 0 (find_allowance allowance_key allowances_) in\n            do _ <- throwIf (authorized_value <? param.(value)) default_error; (* NotEnoughAllowance *)\n            Ok (update_allowance allowance_key (maybe (authorized_value - param.(value))) allowances_)\n        ) ;\n      do tokens_ <- (* Update from balance *)\n        (let from_balance := with_default 0 (AddressMap.find param.(from) tokens_) in\n          do _ <- throwIf (from_balance <? param.(value)) default_error; (* NotEnoughBalance *)\n          Ok (AddressMap.update param.(from) (maybe (from_balance - param.(value))) tokens_)\n        ) ;\n      let tokens_ :=\n        let to_balance := with_default 0 (AddressMap.find param.(to) tokens_) in\n          AddressMap.update param.(to) (maybe (to_balance + param.(value))) tokens_ in\n        Ok (state<|tokens := tokens_|>\n                  <|allowances := allowances_|>).\n\n    (** ** Approve *)\n    (** The caller approves the [spender] to transfer up to [amount] tokens on behalf of the [sender] *)\n    Definition try_approve (sender : Address)\n                           (param : approve_param)\n                           (state : State)\n                           : result State Error :=\n      let allowances_ := state.(allowances) in\n      let allowance_key := (sender, param.(spender)) in\n      let previous_value := with_default 0 (find_allowance allowance_key allowances_) in\n      do _ <- throwIf (andb (0 <? previous_value) (0 <? param.(value_))) default_error; (* UnsafeAllowanceChange *)\n      let allowances_ := update_allowance allowance_key (maybe param.(value_)) allowances_ in\n        Ok (state<|allowances := allowances_|>).\n\n    (** ** Mint or burn *)\n    (** If [quantity] is positive\n        then creates [quantity] tokens and gives them to [target]\n        else removes [quantity] tokens from [target].\n        Can only be called by [admin] *)\n    Definition try_mint_or_burn (sender : Address)\n                                (param : mintOrBurn_param)\n                                (state : State)\n                                : result State Error :=\n      do _ <- throwIf (address_neqb sender state.(admin)) default_error;\n      let tokens_ := state.(tokens) in\n      let old_balance := with_default 0 (AddressMap.find param.(target) tokens_) in\n      let new_balance := (Z.of_N old_balance + param.(quantity))%Z in\n      do _ <- throwIf (new_balance <? 0)%Z default_error; (* Cannot burn more than the target's balance. *)\n      let tokens_ := AddressMap.update param.(target) (maybe (Z.to_N new_balance)) tokens_ in\n      let total_supply_ := Z.abs_N (Z.of_N state.(total_supply) + param.(quantity))%Z in\n        Ok (state<|tokens := tokens_|>\n                  <|total_supply := total_supply_|>).\n\n    Definition mk_callback (to_addr : Address)\n                           (msg : @FA12ReceiverMsg unit)\n                           : ActionBody :=\n      act_call to_addr 0 (serialize msg).\n\n    Definition receive_allowance_ n := @receive_allowance unit n.\n    Definition receive_balance_of_ n := @receive_balance_of unit n.\n    Definition receive_total_supply_ n := @receive_total_supply unit n.\n\n    (** ** Get allowance *)\n    (** Get the quantity that [snd request] is allowed to spend on behalf of [fst request] *)\n    Definition try_get_allowance (sender : Address)\n                                 (param : getAllowance_param)\n                                 (state : State)\n                                 : list ActionBody :=\n      let value := with_default 0 (find_allowance param.(request) state.(allowances)) in\n        [mk_callback param.(allowance_callback) (receive_allowance_ value)].\n\n    (** ** Get balance *)\n    (** Get the quantity of tokens belonging to [owner] *)\n    Definition try_get_balance (sender : Address)\n                               (param : getBalance_param)\n                               (state : State)\n                               : list ActionBody :=\n      let value := with_default 0 (AddressMap.find param.(owner_) state.(tokens)) in\n        [mk_callback param.(balance_callback) (receive_balance_of_ value)].\n\n    (** ** Get total supply *)\n    (** Get the total supply of tokens *)\n    Definition try_get_total_supply (sender : Address)\n                                    (param : getTotalSupply_param)\n                                    (state : State)\n                                    : list ActionBody :=\n      let value := state.(total_supply) in\n        [mk_callback param.(supply_callback) (receive_total_supply_ value)].\n\n    (** ** Init *)\n    (** Initalize contract storage *)\n    Definition init_lqt (chain : Chain)\n                        (ctx : ContractCallContext)\n                        (setup : Setup)\n                        : result State Error :=\n      Ok {|\n        tokens := AddressMap.add setup.(lqt_provider)\n                                 setup.(initial_pool)\n                                 AddressMap.empty;\n        allowances := empty_allowance;\n        admin := setup.(admin_);\n        total_supply := setup.(initial_pool);\n      |}.\n\n    (** ** Receive *)\n    (** Contract main entrypoint *)\n    Open Scope Z_scope.\n    Definition receive_lqt (chain : Chain)\n                          (ctx : ContractCallContext)\n                          (state : State)\n                          (maybe_msg : option Msg)\n                          : result (State * list ActionBody) Error :=\n      let sender := ctx.(ctx_from) in\n      let without_statechange acts := Ok (state, acts) in\n      do _ <- throwIf (non_zero_amount ctx.(ctx_amount)) default_error; (* DontSendTez *)\n      match maybe_msg with\n      | Some (msg_transfer param) =>\n          without_actions (try_transfer sender param state)\n      | Some (msg_approve param) =>\n          without_actions (try_approve sender param state)\n      | Some (msg_mint_or_burn param) =>\n          without_actions (try_mint_or_burn sender param state)\n      | Some (msg_get_allowance param) =>\n          without_statechange (try_get_allowance sender param state)\n      | Some (msg_get_balance param) =>\n          without_statechange (try_get_balance sender param state)\n      | Some (msg_get_total_supply param) =>\n          without_statechange (try_get_total_supply sender param state)\n      (* Transfer actions to this contract are not allowed *)\n      | None => Err default_error\n      end.\n    Close Scope Z_scope.\n\n    Definition contract : Contract Setup Msg State Error :=\n      build_contract init_lqt receive_lqt.\n\n  End DexterLqtDefs.\nEnd Dexter2Lqt.\n\nModule DEX2LQT := Dexter2Lqt D2LqtSInstances.\n", "meta": {"author": "AU-COBRA", "repo": "ConCert", "sha": "55ffd996fe89d41677a2ff368d3a5e4be1e997b7", "save_path": "github-repos/coq/AU-COBRA-ConCert", "path": "github-repos/coq/AU-COBRA-ConCert/ConCert-55ffd996fe89d41677a2ff368d3a5e4be1e997b7/examples/dexter2/Dexter2FA12.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.20683896414704378}}
{"text": "From Perennial.program_proof Require Import disk_prelude.\nFrom Goose.github_com.mit_pdos.gokv Require Import aof.\nFrom Perennial.program_proof.lockservice Require Import grove_ffi.\nFrom Perennial.algebra Require Import mlist auth_map.\nFrom iris.algebra Require Import mono_nat.\nFrom Perennial.Helpers Require Import ModArith.\n\nSection aof_proof.\nContext `{!heapGS Σ}.\nContext `{!filesysG Σ}.\n\nClass aofG Σ := AofG {\n  aof_flistG :> fmlistG u8 Σ ;\n  aof_mnatG :> inG Σ mono_natUR ;\n  aof_mapG :> mapG Σ u64 unit ;\n  aof_tokG :> inG Σ (exclR unitO) ;\n}.\n\nRecord aof_vol_names := mk_aof_vol_names {\n  logdata : gname ;\n  predurabledata : gname ;\n  len : gname ;\n  len_toks : gname ;\n}.\n\nContext `{!aofG Σ}.\n\nImplicit Types γ : aof_vol_names.\nImplicit Types aof_ctx : (list u8) → iProp Σ.\n\nDefinition aof_lenN := nroot .@ \"aof_len\".\nDefinition aof_len_invariant γ : iProp Σ :=\n  ∃ (l:u64),\n    own γ.(len) (mono_nat_auth (1/2) (int.nat l)) ∗\n    [∗ set] x ∈ (fin_to_set u64), x [[γ.(len_toks)]]↦ () ∨ ⌜int.nat x > int.nat l⌝\n.\n\nDefinition aof_length_lb γ (l:u64) : iProp Σ :=\n  own γ.(len) (mono_nat_lb (int.nat l)).\n\nDefinition list_safe_size (l:list u8) := int.nat (length l) = length l.\n\nDefinition aof_mu_invariant (aof_ptr:loc) γ aof_ctx : iProp Σ :=\n  ∃ membuf_sl membufC predurableC (durlen genlength:u64),\n  \"Hmembuf\" ∷ aof_ptr ↦[AppendOnlyFile :: \"membuf\"] (slice_val membuf_sl) ∗\n  \"HdurableLength\" ∷ aof_ptr ↦[AppendOnlyFile :: \"durableLength\"]{1/2} #durlen ∗\n  \"Hmembuf_sl\" ∷ typed_slice.is_slice membuf_sl byteT 1 membufC ∗\n  \"Hpredurable\" ∷ fmlist γ.(predurabledata) (1/2) predurableC ∗\n  \"Hlogdata\" ∷ fmlist γ.(logdata) (1/2)%Qp (predurableC ++ membufC) ∗\n  \"Hlength\" ∷ aof_ptr ↦[AppendOnlyFile :: \"length\"] #genlength ∗\n  \"%Hlengthsafe\" ∷ ⌜list_safe_size (predurableC ++ membufC)⌝ ∗\n  \"Hlen_toks\" ∷ ([∗ set] x ∈ (fin_to_set u64), x [[γ.(len_toks)]]↦ () ∨ ⌜int.nat x ≤ int.nat genlength⌝) ∗\n  \"Hmembuf_fupd\" ∷ (aof_ctx predurableC ={⊤}=∗ aof_ctx (predurableC ++ membufC)\n     ∗ (∀ oldlen, own γ.(len) (mono_nat_auth (1/2) oldlen) ={⊤}=∗\n        own γ.(len) (mono_nat_auth (1/2) (int.nat genlength))\n       )\n  ) ∗\n  \"#Hdurlen_lb\" ∷ aof_length_lb γ durlen\n.\n\nDefinition aofN := nroot .@ \"aof\".\n\nDefinition is_aof aof_ptr γ (aof_ctx : (list u8) → iProp Σ) : iProp Σ :=\n  ∃ mu_ptr (lenCond_ptr durCond_ptr:loc),\n  \"#Hmu\" ∷ readonly (aof_ptr ↦[AppendOnlyFile :: \"mu\"] mu_ptr) ∗\n  \"#HlengthCond\" ∷ readonly (aof_ptr ↦[AppendOnlyFile :: \"lengthCond\"] #lenCond_ptr) ∗\n  \"#HdurableCond\" ∷ readonly (aof_ptr ↦[AppendOnlyFile :: \"durableCond\"] #durCond_ptr) ∗\n  \"#HlenCond\" ∷ is_cond lenCond_ptr mu_ptr ∗\n  \"#HdurCond\" ∷ is_cond durCond_ptr mu_ptr ∗\n  \"#Hmu_inv\" ∷ is_lock aofN mu_ptr (aof_mu_invariant aof_ptr γ aof_ctx) ∗\n  \"#Haof_len_inv\" ∷ inv aof_lenN (aof_len_invariant γ)\n.\n\n(* TODO: upgrade to WPC *)\nLemma wp_CreateAppendOnlyFile (fname:string) data aof_ctx :\n  {{{\n       fname f↦{1} data ∗\n       aof_ctx data\n  }}}\n    CreateAppendOnlyFile #(str fname)\n  {{{\n       aof_ptr γ, RET #aof_ptr; is_aof aof_ptr γ aof_ctx\n  }}}.\nProof.\n  iIntros (Φ) \"Hpre HΦ\".\n  wp_lam.\n\n  wp_apply (wp_allocStruct).\n  { admit. (* TODO: typechecking *) }\n  iIntros (l) \"Hl\".\n  iDestruct (struct_fields_split with \"Hl\") as \"Hl\".\n  iNamed \"Hl\".\n\n  wp_pures.\n  wp_apply (wp_new_free_lock).\n  iIntros (mu) \"Hmu_free\".\n\n  wp_pures.\n  wp_storeField.\n\n  wp_loadField.\n  wp_apply (wp_newCond' with \"Hmu_free\").\n  iIntros (lengthCond) \"[Hmu_free HlengthCond]\".\n  wp_storeField.\n\n  wp_loadField.\n  wp_apply (wp_newCond' with \"Hmu_free\").\n  iIntros (durableCond) \"[Hmu_free HdurableCond]\".\n  wp_storeField.\n\n  iAssert ((|={⊤}=> ∃ γ, is_aof l γ aof_ctx ∗ fmlist γ.(predurabledata) (1 / 2) data\n            ∗ l ↦[AppendOnlyFile :: \"durableLength\"]{1 / 2} #0\n            ∗ own γ.(len) (mono_nat_auth (1/2) 0))\n          )%I with \"[-Hpre HΦ]\" as \">HH\".\n  {\n    (* need to allocate ghost state and freeze stuff *)\n    iExists (mk_aof_vol_names _ _ _ _).\n    admit.\n  }\n  iDestruct \"HH\" as (γ) \"(#His_aof & Hpredur & HdurLen & Hlen)\".\n  wp_apply (wp_fork with \"[-HΦ]\").\n  {\n    iNext.\n    iNamed \"His_aof\".\n    wp_loadField.\n    wp_apply (acquire_spec with \"Hmu_inv\").\n    iIntros \"[Hlocked Haof_own]\".\n    wp_pures.\n    iAssert (∃ data', fname f↦ (data++data') ∗ aof_ctx (data++data') ∗ fmlist γ.(predurabledata) (1/2) (data ++ data')\n            ∗ l ↦[AppendOnlyFile :: \"durableLength\"]{1 / 2} #(U64 (length data'))\n            ∗ own γ.(len) (mono_nat_auth (1/2) (length (data')))\n            )%I with \"[Hpre Hpredur HdurLen Hlen]\" as \"Hfile_ctx\".\n    { iExists []; iFrame. rewrite app_nil_r. iFrame. }\n    wp_forBreak.\n    wp_pures.\n\n    iNamed \"Haof_own\".\n    wp_loadField.\n    wp_apply (wp_slice_len).\n    wp_pures.\n    wp_if_destruct.\n    {\n      wp_loadField.\n      wp_apply (wp_condWait with \"[- Hfile_ctx]\").\n      { iFrame \"#∗\". iExists _, _, _, _; iFrame \"∗#\". done. }\n      iIntros \"[Hlocked Haof_own]\".\n      wp_pures.\n      iLeft.\n      iFrame.\n      done.\n    }\n\n    wp_loadField.\n    wp_pures.\n    wp_loadField.\n    wp_pures.\n\n    wp_apply (wp_new_slice).\n    { done. }\n    iIntros (empty_membuf_sl) \"Hmembuf_empty\".\n    wp_apply (wp_storeField with \"Hmembuf\").\n    { unfold AppendOnlyFile. unfold field_ty. simpl. apply slice_val_ty. }\n    iIntros \"Hmembuf\".\n\n    wp_pures.\n    wp_loadField.\n\n    iDestruct \"Hfile_ctx\" as (data') \"(Hfile & Hctx & Hpredur & HdurLen & Hlen)\".\n\n    iDestruct (fmlist_agree_1 with \"Hpredur Hpredurable\") as %Hpredur.\n    rewrite Hpredur.\n    iCombine \"Hpredur Hpredurable\" as \"Hpredur\".\n    iMod (fmlist_update (predurableC ++ membufC) with \"Hpredur\") as \"[Hpredur _]\".\n    { by apply prefix_app_r. }\n    iDestruct \"Hpredur\" as \"[Hpredur Hpredurable]\".\n    wp_apply (release_spec with \"[-Hfile Hctx Hpredur Hmembuf_fupd Hmembuf_sl HdurLen Hlen]\").\n    { iFrame \"#∗\". iNext. iExists _, [], (predurableC ++ membufC), _. iFrame \"∗#\".\n      rewrite app_nil_r.\n      iFrame.\n      iSplitL \"\"; first done.\n      iIntros \"$ !> $ !>\".\n      done.\n    }\n\n    wp_pures.\n\n    iDestruct (typed_slice.is_slice_sz with \"Hmembuf_sl\") as %Hsz.\n    wp_bind (AtomicAppend _ _).\n    iApply wpc_wp.\n    wpc_apply (wpc_AtomicAppend with \"[$Hfile $Hmembuf_sl]\").\n    iSplit.\n    { iModIntro. iIntros. instantiate (1:=(True)%I). done. }\n    iNext.\n    iIntros \"[Hfile _]\".\n    iMod (\"Hmembuf_fupd\" with \"Hctx\") as \"[Hctx Hlen_fupd]\".\n    wp_pures.\n\n    wp_loadField.\n    wp_apply (acquire_spec with \"Hmu_inv\").\n    iIntros \"[Hlocked Haof_own]\".\n    iRename \"Hdurlen_lb\" into \"Hdurlen_lb_old\".\n    iNamed \"Haof_own\".\n    wp_pures.\n\n    iDestruct (struct_field_mapsto_agree with \"HdurLen HdurableLength\") as %Heq.\n    rewrite Heq.\n    iCombine \"HdurLen HdurableLength\" as \"HdurLen\".\n    wp_storeField.\n\n    wp_loadField.\n    iMod (\"Hlen_fupd\" with \"Hlen\") as \"Hlen\".\n    iEval (rewrite mono_nat_auth_lb_op) in \"Hlen\".\n    iDestruct \"Hlen\" as \"[Hlen #Hlenlb]\".\n\n    wp_apply (wp_condBroadcast).\n    { iFrame \"#\". }\n    wp_pures.\n    iLeft.\n    iFrame.\n    iSplitL \"\"; first done.\n    iDestruct \"HdurLen\" as \"[HdurableLength HdurLen]\".\n    iSplitR \"Hpredur HdurLen Hlen Hfile Hctx\".\n    {\n      iExists _, _, _, _; iFrame \"∗#\".\n      iSplitL \"\"; first done.\n      unfold aof_length_lb.\n      rewrite Hlengthsafe.\n      iFrame \"#\".\n    }\n    {\n      rewrite -Hpredur.\n      repeat rewrite -app_assoc.\n      iExists _; iFrame.\n    }\n  }\n  wp_pures.\n  iApply \"HΦ\".\n  iFrame \"#\".\nAdmitted.\n\nDefinition aof_log_own γ data :=\n  fmlist γ.(logdata) (1/2)%Qp data.\n\nLemma wp_AppendOnlyFile__Append aof_ptr γ data_sl aof_ctx (oldData newData:list u8) Q :\nlength newData > 0 →\nlist_safe_size newData →\nis_aof aof_ptr γ aof_ctx -∗\n  {{{\n       typed_slice.is_slice data_sl byteT 1 newData ∗ aof_log_own γ oldData ∗\n       (aof_ctx oldData ={⊤}=∗ aof_ctx (oldData ++ newData) ∗ Q)\n  }}}\n    AppendOnlyFile__Append #aof_ptr (slice_val data_sl)\n  {{{\n       (l:u64), RET #l; aof_log_own γ (oldData ++ newData) ∗\n                        (aof_length_lb γ l ={⊤}=∗ ▷ Q)\n  }}}.\nProof.\n  intros HnewDataLen HnewDataSafe.\n  iIntros \"#Haof\" (Φ) \"!# Hpre HΦ\".\n  iNamed \"Haof\".\n  wp_lam.\n  wp_pures.\n\n  wp_loadField.\n  wp_apply (acquire_spec with \"Hmu_inv\").\n  iIntros \"[Hlocked Haof]\".\n  iNamed \"Haof\".\n  iDestruct \"Hpre\" as \"(HnewData & Haof_log & Hfupd)\".\n  wp_pures.\n\n  wp_loadField.\n  iDestruct (is_slice_sz with \"HnewData\") as %Hsz.\n  wp_apply (typed_slice.wp_SliceAppendSlice (V:=u8) with \"[$Hmembuf_sl $HnewData]\").\n  iIntros (membuf_sl') \"Hmembuf_sl\".\n  wp_apply (wp_storeField with \"Hmembuf\").\n  { unfold AppendOnlyFile. unfold field_ty. simpl. apply slice_val_ty. }\n  iIntros \"Hmembuf\".\n\n  wp_pures.\n\n  (* overflow guard *)\n  wp_forBreak_cond.\n  wp_pures.\n  repeat wp_loadField.\n  wp_apply (wp_slice_len).\n  wp_loadField.\n  wp_pures.\n  wp_if_destruct.\n  {\n    wp_pures.\n    iLeft. iFrame \"∗#\". done.\n  }\n  iRight.\n  iSplitL \"\"; first done.\n  rewrite typed_slice.list_untype_length in Hsz.\n\n  wp_loadField.\n  wp_apply (wp_slice_len).\n  wp_pures.\n  rewrite -HnewDataSafe in Hsz Heqb.\n  assert (U64 (length newData) = data_sl.(Slice.sz)) as HH.\n  {\n    apply Z2Nat.inj in Hsz.\n    { word_cleanup. naive_solver. }\n    { word_cleanup. naive_solver. }\n    word.\n  }\n  rewrite -HH.\n  rewrite -HH in Heqb.\n  wp_pures.\n  wp_storeField.\n\n  wp_loadField.\n  wp_pures.\n\n  wp_loadField.\n  wp_apply (wp_condSignal).\n  { iFrame \"#\". }\n\n  wp_pures.\n\n  unfold aof_log_own.\n  iDestruct (fmlist_agree_1 with \"Haof_log Hlogdata\") as %->.\n  iCombine \"Haof_log Hlogdata\" as \"Haof_log\".\n\n  iMod (fmlist_update ((predurableC ++ membufC) ++ newData) with \"Haof_log\") as \"[Haof_log _]\".\n  { apply prefix_app_r. done. }\n\n  iDestruct \"Haof_log\" as \"[Hlogdata Haof_log]\".\n\n  rewrite -app_assoc.\n  (* Want to prove membuf_fupd, and the postcondition *)\n  set (membufC' := membufC ++ newData) in *.\n\n  iAssert (([∗ set] x ∈ fin_to_set u64, x [[γ.(len_toks)]]↦ () ∨\n                      ⌜int.nat x <= length (predurableC ++ membufC)⌝ ∨\n                      ⌜length (predurableC ++ membufC') < int.nat x⌝\n          ) ∗\n          ([∗ set] x ∈ fin_to_set u64, x [[γ.(len_toks)]]↦ () ∨\n                      ⌜int.nat x ≤ length (predurableC ++ membufC')⌝\n          ))%I\n    with \"[Hlen_toks]\"\n    as \"HH\".\n  {\n    iApply big_sepS_sep.\n    iApply (big_sepS_impl with \"Hlen_toks\").\n    iModIntro.\n    iIntros (x ?) \"Hx\".\n    iDestruct \"Hx\" as \"[Hx|%Hineq]\".\n    {\n      destruct (bool_decide (length (predurableC ++ membufC') < int.nat x)) as [|] eqn:Hineq.\n      {\n        apply bool_decide_eq_true in Hineq.\n        iSplitR \"Hx\".\n        { iRight; iRight. done. }\n        iLeft. iFrame.\n      }\n      {\n        apply bool_decide_eq_false in Hineq.\n        iSplitL \"Hx\".\n        { iFrame. }\n        iRight.\n        iPureIntro.\n        word.\n      }\n    }\n    {\n      iSplitL.\n      {\n        iRight; iLeft. done.\n      }\n      iRight. iPureIntro.\n      replace (membufC') with (membufC ++ newData) by done.\n      rewrite app_assoc.\n      rewrite app_length.\n      word.\n    }\n  }\n\n  iDestruct \"HH\" as \"[Htoks Hlen_toks]\".\n\n  (* TODO: factor this into a lemma *)\n  assert (int.Z (word.add (U64 (length (predurableC ++ membufC))) (U64 (length newData))) =\n          int.Z (U64 (length (predurableC ++ membufC))) + int.Z (U64 (length newData))).\n  {\n    assert (int.Z (word.add (length (predurableC ++ membufC)) (length newData)) >= int.Z (length (predurableC ++ membufC)))%Z by lia.\n    destruct (bool_decide ((int.Z (U64 (length (predurableC ++ membufC)))) + (int.Z (U64 (length newData))) < 2 ^ 64 ))%Z eqn:Hnov.\n    {\n      apply bool_decide_eq_true in Hnov.\n      rewrite word.unsigned_add.\n      rewrite wrap_small.\n      { word. }\n      split.\n      {\n        apply Z.add_nonneg_nonneg.\n        { word_cleanup. naive_solver. }\n        { word_cleanup. naive_solver. }\n      }\n      { done. }\n    }\n    apply bool_decide_eq_false in Hnov.\n    assert (int.Z (U64 (length (predurableC ++ membufC))) + int.Z (U64 (length newData)) >= 2 ^ 64)%Z.\n    { lia. }\n    apply sum_overflow_check in H0.\n    contradiction.\n  }\n  assert (int.nat (U64 (length (predurableC ++ membufC'))) = (length (predurableC ++ membufC'))) as Hsafesize'.\n  {\n    replace (membufC') with (membufC ++ newData) by done.\n    rewrite app_assoc.\n    rewrite app_length.\n    word_cleanup.\n    rewrite -Hlengthsafe.\n    repeat (rewrite Nat2Z.inj_add).\n    replace (length newData) with (Z.to_nat (Z.of_nat (length newData))) by lia.\n    rewrite -Z2Nat.inj_add.\n    {\n      rewrite Z2Nat.inj_iff.\n      {\n        rewrite Z2Nat.id.\n        {\n          rewrite wrap_small; first word.\n          split.\n          {\n            apply Z.add_nonneg_nonneg; word_cleanup; naive_solver.\n          }\n          {\n            rewrite Nat2Z.id.\n            rewrite -HnewDataSafe.\n            replace (Z.of_nat (int.nat (length newData))) with (int.Z (length newData)); last first.\n            { rewrite u64_Z_through_nat. done. }\n            destruct (bool_decide (int.Z (length (predurableC ++ membufC)) + (int.Z (length newData)) < 2 ^ 64)) eqn:Hnov.\n            { apply bool_decide_eq_true in Hnov. done. }\n            {\n              apply bool_decide_eq_false in Hnov.\n              assert (int.Z (U64 (length (predurableC ++ membufC))) + (int.Z (length newData)) >= 2 ^ 64)%Z.\n              { lia. }\n              apply sum_overflow_check in H4.\n              contradiction.\n            }\n          }\n        }\n        naive_solver.\n      }\n      {\n        word_cleanup.\n        unfold word.wrap.\n        by apply Z_mod_lt.\n      }\n      {\n        word_cleanup.\n        apply Z.add_nonneg_nonneg; word_cleanup; naive_solver.\n      }\n    }\n    { naive_solver. }\n    { lia. }\n  }\n\n  iAssert (|={⊤}=> (\n  aof_ctx predurableC\n                   ={⊤}=∗ aof_ctx (predurableC ++ membufC')\n                          ∗ (own γ.(len) (mono_nat_auth (1 / 2) (length predurableC))\n                             ={⊤}=∗ own γ.(len)\n                                      (mono_nat_auth (1 / 2)\n                                         (length (predurableC ++ membufC'))))\n  ) ∗ (aof_length_lb γ (U64 (length (predurableC ++ membufC'))) ={⊤}=∗ ▷ Q))%I with \"[Hmembuf_fupd Hfupd Htoks]\" as \"HH\".\n  {\n    (* allocate invariant to escrow Q *)\n    iMod (own_alloc (Excl ())) as \"HQtok\".\n    { done. }\n    iDestruct \"HQtok\" as (γtok) \"Htok\".\n    iMod (own_alloc (Excl ())) as \"HQexcl\".\n    { done. }\n    iDestruct \"HQexcl\" as (γq) \"HQexcl\".\n    iDestruct (big_sepS_elem_of_acc _ _ (U64 (length (predurableC ++ membufC'))) with \"Htoks\") as \"[Hlen_tok Hlen_toks_rest]\".\n    { set_solver. }\n    iDestruct \"Hlen_tok\" as \"[Hlen_tok|%Hbad]\"; last first.\n    {\n      exfalso.\n      rewrite Hsafesize' in Hbad.\n      rewrite app_length in Hbad.\n      rewrite app_length in Hbad.\n      rewrite app_length in Hbad.\n      word.\n    }\n    iMod (inv_alloc aofN _ (own γtok (Excl ()) ∗ aof_length_lb γ (U64 (length (predurableC ++ membufC'))) ∨ (U64 (length (predurableC ++ membufC')) [[γ.(len_toks)]]↦ ()) ∨ Q ∗ own γq (Excl ())) with \"[Hlen_tok]\") as \"#HQinv\".\n    {\n      iRight. iLeft.\n      iFrame.\n    }\n    iSplitR \"Htok\"; last first.\n    {\n      iModIntro.\n      iIntros \"Haof_lb\".\n      iInv \"HQinv\" as \"Hq\" \"Hqclose\".\n      iDestruct \"Hq\" as \"[>[Htok2 _]|Hq]\".\n      { iDestruct (own_valid_2 with \"Htok Htok2\") as %Hbad. contradiction. }\n      iDestruct \"Hq\" as \"[>Hlentok|Hq]\".\n      {\n        iInv \"Haof_len_inv\" as \">Ha\" \"Haclose\".\n        unfold aof_len_invariant.\n        iDestruct \"Ha\" as (l) \"[Hlen Ha]\".\n        iDestruct (own_valid_2 with \"Hlen Haof_lb\") as %Hineq.\n        apply mono_nat_both_frac_valid in Hineq as [_ Hineq].\n        iDestruct (big_sepS_elem_of_acc _ _ (U64 (length (predurableC ++ membufC'))) with \"Ha\") as \"[Ha Harest]\".\n        { set_solver. }\n        iDestruct \"Ha\" as \"[Hlentok2|%Hbad]\"; last first.\n        { exfalso. lia. }\n        iDestruct (ptsto_conflict with \"Hlentok Hlentok2\") as %Hbad.\n        done.\n      }\n      iMod (\"Hqclose\" with \"[Htok Haof_lb]\").\n      { iLeft. iNext. iFrame. }\n      iDestruct \"Hq\" as \"[$ _]\".\n      by iModIntro.\n    }\n\n    iModIntro.\n    iIntros \"Hctx\".\n    iMod (\"Hmembuf_fupd\" with \"Hctx\") as \"[Hctx Hmembuf_fupd]\".\n    iMod (\"Hfupd\" with \"Hctx\") as \"[$ HQ]\".\n    iModIntro.\n\n    (* length stuff *)\n    iIntros \"Hlen\".\n    iInv \"HQinv\" as \"Hq\" \"Hqclose\".\n    iDestruct \"Hq\" as \"[[_ >Hlb]|Hq]\".\n    {\n      iDestruct (own_valid_2 with \"Hlen Hlb\") as %Hbad.\n      exfalso.\n      apply mono_nat_both_frac_valid in Hbad as [_ Hbad].\n      rewrite Hsafesize' in Hbad.\n      rewrite app_length in Hbad.\n      rewrite app_length in Hbad.\n      lia.\n    }\n    iDestruct \"Hq\" as \"[>Hlen_tok|[_ >HQexcl2]]\"; last first.\n    { iDestruct (own_valid_2 with \"HQexcl HQexcl2\") as %Hbad. contradiction. }\n\n    iDestruct (\"Hlen_toks_rest\" with \"[$Hlen_tok]\") as \"Hlen_toks\".\n    iMod (\"Hqclose\" with \"[HQexcl HQ]\") as \"_\".\n    { iRight; iRight; iFrame. }\n\n    iMod (\"Hmembuf_fupd\" with \"Hlen\") as \"Hlen\".\n\n    (* Use tokens to update mono_nat counter *)\n    iInv \"Haof_len_inv\" as \">Ha\" \"Haclose\".\n    iDestruct \"Ha\" as (len) \"[Hlen2 Ha]\".\n    iDestruct (own_valid_2 with \"Hlen Hlen2\") as %Hleneq.\n    apply mono_nat_auth_frac_op_valid in Hleneq as [_ <-].\n    iCombine \"Hlen Hlen2\" as \"Hlen\".\n    rewrite mono_nat_auth_frac_op.\n    rewrite Qp.half_half.\n    iMod (own_update _ _ (mono_nat_auth 1 (length (predurableC ++ membufC'))) with \"Hlen\") as \"Hlen\".\n    {\n      apply mono_nat_update.\n      repeat rewrite app_length.\n      lia.\n    }\n    iEval (rewrite -Qp.half_half) in \"Hlen\".\n    rewrite -mono_nat_auth_frac_op.\n    iDestruct \"Hlen\" as \"[Hlen Hlen2]\".\n\n    iMod (\"Haclose\" with \"[Ha Hlen_toks Hlen2]\") as \"_\".\n    {\n      iNext. iExists _. rewrite -Hsafesize'.\n      iFrame.\n      iApply (big_sepS_impl with \"[Ha Hlen_toks]\").\n      { iApply big_sepS_sep. iFrame. }\n\n      iModIntro.\n      iIntros (x ?) \"Hx\".\n      destruct (bool_decide (int.nat (length (predurableC ++ membufC')) < int.nat x)) as [|] eqn:Hineq.\n      {\n        apply bool_decide_eq_true in Hineq.\n        iRight.\n        iPureIntro.\n        word.\n      }\n      {\n        apply bool_decide_eq_false in Hineq.\n        iLeft.\n        iDestruct \"Hx\" as \"[[$|%Hbad] [$|%Hineq2]]\".\n        exfalso.\n        word.\n      }\n    }\n    iFrame.\n    by iModIntro.\n  }\n\n  iMod \"HH\" as \"[Hmembuf_fupd HfupdQ]\".\n\n  wp_loadField.\n  wp_apply (release_spec with \"[-HΦ Haof_log HfupdQ]\").\n  {\n    iFrame \"#∗\".\n    iNext.\n    iExists _, _, _, _.\n    iFrame \"#∗\".\n    iSplitR \"\"; last done.\n    replace (word.add (length (predurableC ++ membufC)) (length newData)) with\n        (U64 (length (predurableC ++ membufC'))); last first.\n    {\n      repeat rewrite app_length.\n      rewrite -word.ring_morph_add.\n      word_cleanup.\n      repeat (rewrite Nat2Z.inj_add).\n      rewrite Z.add_assoc.\n      done.\n    }\n    iFrame.\n  }\n  wp_pures.\n  iApply \"HΦ\".\n  iFrame.\n  iIntros \"#Hlb\".\n  iMod (\"HfupdQ\" with \"[Hlb]\") as \"$\"; last by iModIntro.\n  replace (U64 (length (predurableC ++ membufC'))) with\n      (word.add (length (predurableC ++ membufC)) (length newData)).\n  { iFrame \"#\". }\n\n  repeat rewrite app_length.\n  repeat (rewrite Nat2Z.inj_add).\n  rewrite Z.add_assoc.\n  rewrite -word.ring_morph_add.\n  unfold U64.\n  done.\nQed.\n\nLemma wp_AppendOnlyFile__WaitAppend aof_ptr γ (l:u64) aof_ctx :\nis_aof aof_ptr γ aof_ctx -∗\n  {{{\n       True\n  }}}\n    AppendOnlyFile__WaitAppend #aof_ptr #l\n  {{{\n       RET #(); aof_length_lb γ l\n  }}}.\nProof.\n  iIntros \"#Haof\" (Φ) \"!# _ HΦ\".\n  wp_lam.\n  wp_pures.\n  iNamed \"Haof\".\n  wp_loadField.\n  wp_apply (acquire_spec with \"Hmu_inv\").\n  iIntros \"[Hlocked Haof_own]\".\n  wp_pures.\n  wp_apply (wp_forBreak_cond' with \"[-]\").\n  {\n    iNamedAccu.\n  }\n  iModIntro.\n  iNamed 1.\n\n  wp_pures.\n  iNamed \"Haof_own\".\n  wp_loadField.\n  wp_pures.\n  wp_if_destruct.\n  {\n    wp_pures.\n    wp_loadField.\n    wp_apply (wp_condWait with \"[- HΦ]\").\n    {\n      iFrame \"#∗\".\n      iExists _, _, _, _. iFrame \"#∗\".\n      done.\n    }\n    iIntros \"[Hlocked Haof_own]\".\n    wp_pures.\n    iLeft.\n    iFrame.\n    done.\n  }\n  iSpecialize (\"HΦ\" with \"[Hdurlen_lb]\").\n  {\n    assert (int.nat l ≤ int.nat durlen) as Hineq.\n    {\n      word.\n    }\n    unfold aof_length_lb.\n    replace (int.nat durlen)%nat with ((int.nat durlen) `max` int.nat l)%nat by word.\n    rewrite -mono_nat_lb_op.\n    iDestruct \"Hdurlen_lb\" as \"[_ $]\".\n  }\n  iRight.\n  iSplitL \"\"; first done.\n  wp_pures.\n\n  wp_loadField.\n  wp_apply (release_spec with \"[- HΦ]\").\n  {\n    iFrame \"#∗\".\n    iExists _, _, _, _. iFrame \"#∗\".\n    done.\n  }\n  iFrame.\nQed.\n\nEnd aof_proof.\n", "meta": {"author": "mit-pdos", "repo": "perennial", "sha": "76dafee3cd47e1c5e5a6d5436f87738a06f13ee0", "save_path": "github-repos/coq/mit-pdos-perennial", "path": "github-repos/coq/mit-pdos-perennial/perennial-76dafee3cd47e1c5e5a6d5436f87738a06f13ee0/src/program_proof/lockservice/aof_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.20681304120243751}}
{"text": "Require Import Coq.Strings.String Coq.Strings.Ascii.\nRequire Import Coq.Classes.Morphisms.\nRequire Import Fiat.Parsers.Reflective.Syntax.\nRequire Import Fiat.Parsers.Reflective.Semantics.\nRequire Import Fiat.Parsers.Reflective.ParserSyntax.\nRequire Import Fiat.Parsers.Reflective.Semantics.\nRequire Import Fiat.Parsers.Reflective.ParserSemantics.\nRequire Import Fiat.Parsers.Reflective.PartialUnfold.\nRequire Import Fiat.Parsers.Reflective.ParserPartialUnfold.\nRequire Import Fiat.Parsers.Reflective.ParserLogicalRelations.\nSet Implicit Arguments.\n\nSection polypnormalize.\n  Context (is_valid_nonterminal : list nat -> nat -> bool)\n          (strlen : nat)\n          (char_at_matches_interp : nat -> Reflective.RCharExpr Ascii.ascii -> bool)\n          (split_string_for_production : nat * (nat * nat) -> nat -> nat -> list nat).\n\n  Let interp {T} := interp_has_parse_term (T := T) is_valid_nonterminal strlen char_at_matches_interp split_string_for_production.\n\n  Lemma polypnormalize_correct {T} (term : polyhas_parse_term T)\n    : ParserSyntaxEquivalence.has_parse_term_equiv\n        nil\n        (term interp_TypeCode) (term (normalized_of interp_TypeCode))\n      -> interp (term _) = interp (polypnormalize term _).\n  Proof.\n    subst interp.\n    apply polypnormalize_correct; assumption.\n  Qed.\nEnd polypnormalize.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_eapply_example/src/Parsers/Reflective/ParserSoundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.20670683843378387}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Bool.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import ZArith NArith Nnat Ndec Ndigits.\nFrom IntMap Require Import Allmaps.\nRequire Import Wf_nat.\n\nRequire Import BDDvar_ad_nat.\nRequire Import bdd1.\nRequire Import bdd2.\nRequire Import bdd3.\nRequire Import bdd4.\nRequire Import bdd5_1.\nRequire Import bdd5_2.\nRequire Import bdd6.\nRequire Import bdd7.\nRequire Import BDDdummy_lemma_2.\nRequire Import BDDdummy_lemma_3.\nRequire Import BDDdummy_lemma_4.\nRequire Import bdd8.\nRequire Import bdd9.\nRequire Import bdd10.\nRequire Import bdd11.\n\nDefinition is_tauto (be : bool_expr) :=\n  Neqb BDDone\n    (fst\n       (snd (BDDof_bool_expr initBDDconfig initBDDneg_memo initBDDor_memo be))).\n\nDefinition is_valid (be : bool_expr) :=\n  forall vb : var_binding, bool_fun_of_bool_expr be vb = true.\n\nLemma initBDDor_memo_OK : BDDor_memo_OK initBDDconfig initBDDor_memo.\nProof.\n  unfold BDDor_memo_OK in |- *. intros. discriminate H.\nQed.\n\nLemma initBDDneg_memo_OK : BDDneg_memo_OK initBDDconfig initBDDneg_memo.\nProof.\n  unfold BDDneg_memo_OK in |- *. intros. discriminate H.\nQed.\n\nLemma initBDDneg_memo_OK_2 : BDDneg_memo_OK_2 initBDDconfig initBDDneg_memo.\nProof.\n  unfold BDDneg_memo_OK_2 in |- *. intros. discriminate H.\nQed.\n\nLemma is_tauto_is_correct :\n forall be : bool_expr, is_tauto be = true -> is_valid be.\nProof.\n  unfold is_tauto, is_valid in |- *. intros.\n  elim\n   (BDDof_bool_expr_correct be initBDDconfig initBDDneg_memo initBDDor_memo\n      initBDDconfig_OK initBDDneg_memo_OK_2 initBDDor_memo_OK).\n  intros. elim H1. intros. elim H3. intros. elim H5. intros. elim H7. intros.\n  rewrite <- (Neqb_complete _ _ H) in H9.\n  exact\n   (bool_fun_eq_trans _ _ _ (bool_fun_eq_symm _ _ H9)\n      (bool_fun_of_BDDone _ H0) vb).\nQed.\n\nLemma is_tauto_is_complete :\n forall be : bool_expr, is_valid be -> is_tauto be = true.\nProof.\n  unfold is_tauto, is_valid in |- *. intros.\n  elim\n   (BDDof_bool_expr_correct be initBDDconfig initBDDneg_memo initBDDor_memo\n      initBDDconfig_OK initBDDneg_memo_OK_2 initBDDor_memo_OK).\n  intros. elim H1. intros. elim H3. intros. elim H5. intros. elim H7. intros.\n  rewrite <-\n   (BDDunique\n      (fst (BDDof_bool_expr initBDDconfig initBDDneg_memo initBDDor_memo be))\n      H0 BDDone\n      (fst\n         (snd\n            (BDDof_bool_expr initBDDconfig initBDDneg_memo initBDDor_memo be))))\n   .\n  reflexivity.\n  unfold config_node_OK in |- *. unfold node_OK in |- *. right. left. reflexivity.\n  exact H2.\n  apply bool_fun_eq_symm.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_bool_expr be). exact H9.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_one). exact H.\n  apply bool_fun_eq_symm. exact (bool_fun_of_BDDone _ H0).\nQed.", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/bdds/tauto.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.3702253786982541, "lm_q1q2_score": 0.20670681747355718}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssrZ ZArith_ext seq_ext ssrnat_ext uniq_tac machine_int.\nRequire Import multi_int.\nImport MachineInt.\nRequire Import mips_seplog mips_contrib mips_tactics mapstos.\nRequire Import mont_mul_prg.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope eqmod_scope.\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope heap_scope.\nImport expr_m.\nLocal Open Scope mips_expr_scope.\nImport assert_m.\nLocal Open Scope mips_assert_scope.\nLocal Open Scope mips_cmd_scope.\nLocal Open Scope mips_hoare_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope multi_int_scope.\n\nLemma mont_square_triple (k alpha x z m one ext int_ X_ Y_ M_ Z_ quot C t s_ : reg) :\n  uniq(k, alpha, x, z, m, one, ext, int_, X_, Y_, M_, Z_, quot, C, t, s_, r0) ->\n  forall nk valpha vx vm vz X M,\n    u2Z (M `32_ 0) * u2Z valpha =m -1 {{ \\B^1 }} ->\n    size X = nk -> size M = nk -> u2Z vz + 4 * Z_of_nat nk < \\B^1 ->\n    \\S_{ nk } X < \\S_{ nk } M ->\n{{ fun s h => [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> nseq nk zero32 ** var_e m |--> M) s h /\\ store.multi_null s }}\nmontgomery k alpha x x z m one ext int_ X_ Y_ M_ Z_ quot C t s_\n{{ fun s h => exists Z, size Z = nk /\\ [x]_s = vx /\\ [z]_s = vz /\\\n  [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  \\B^nk * \\S_{ nk.+1 } (Z ++ [C]_s :: nil) =m \\S_{ nk } X * \\S_{ nk } X {{ \\S_{ nk } M }} /\\\n  \\S_{ nk.+1 } (Z ++ [C]_s :: nil) < 2 * \\S_{ nk } M /\\\n  u2Z [t]_s = u2Z vz + 4 * Z_of_nat nk.-1 }}.\nProof.\nmove=> Hset nk valpha vx vm vz X M Halpha Hx Hm Hnz HX.\nrewrite /montgomery.\n\n(** addiu one r0 one16; *)\n\nNextAddiu.\nmove=> s h [r_x [r_z [r_m [r_k [r_alpha [Hmem Hmu]]]]]].\nrewrite /wp_addiu.\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite store.multi_null_upd.\n\n(** addiu C r0 zero16; *)\n\nNextAddiu.\nmove=> s h [[r_x [r_z [r_m [r_k [r_alpha [Hmem Hmu]]]]]] r_one].\nrewrite /wp_addiu.\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite store.multi_null_upd.\n\n(** addiu ext r0 zero16; *)\n\nNextAddiu.\nmove=> s h [[[r_x [r_z [r_m [r_k [r_alpha [Hmem Hmu]]]]]] r_one] r_C].\nrewrite /wp_addiu.\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite store.multi_null_upd.\n\n(** while (bne ext k) *)\n\napply hoare_prop_m.hoare_while_invariant with (fun s h => exists Z next, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\\n  [alpha]_s = valpha /\\ (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s <= u2Z [k]_s /\\ [one]_s = one32 /\\\n  (next <> O -> u2Z [t]_s = u2Z vz + 4 * Z_of_nat nk.-1) /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M /\\\n    \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M < 2 * \\S_{nk} M * \\B^next)).\n\nmove=> s h [[[[r_x [r_z [r_m [r_k [r_alpha [Hmem Hmu]]]]]] r_one] r_C] r_ext].\nexists (nseq nk zero32), O; repeat (split => //).\nby rewrite size_nseq.\nby rewrite r_ext sext_Z2u // addi0 store.get_r0 Z2uK.\nrewrite r_ext sext_Z2u // addi0 store.get_r0 Z2uK //; exact/min_u2Z.\napply u2Z_inj; by rewrite r_one sext_Z2u // store.get_r0 addC addi0 Z2uK.\n\nexists 0.\nhave -> : nseq nk zero32 ++ [C ]_ s :: nil = nseq nk.+1 zero32.\n  suff -> : [ C ]_s = zero32 by rewrite nseqS.\n  apply u2Z_inj; by rewrite r_C sext_Z2u // addi0 store.get_r0.\nrewrite lSum_nseq_0.\nsplit; first by [].\n(* about X * Y < M *)\nrewrite mulZ1 !mul0Z add0Z; apply mulZ_gt0 => //.\napply (@leZ_ltZ_trans (\\S_{ nk } X)) => //; exact: min_lSum.\n\nmove=> s h [[Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [Hext [Hextk' [Hone [Ht Hinv]]]]]]]]]]]]] Hextk].\nrewrite /= r_k Hext in Hextk; move/negPn/eqP/Z_of_nat_inj in Hextk; subst next.\n\nexists Z; do 7 (split; trivial).\ncase: Hinv => K [Hinv1 Hinv2].\nsplit; first by exists K.\nsplit.\n(* about X * Y < M *)\n- apply/(@ltZ_pmul2r \\B^nk).\n  exact/Zbeta_gt0.\n  by rewrite mulZC Hinv1.\napply Ht; by destruct nk.\n\n(** lwxs X ext x; *)\n\napply hoare_lwxs_back_alt'' with (fun s h => exists Z next, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M /\\\n    \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M < 2 * \\S_{nk} M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next).\n\nmove=> s h [ [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Ht Hinv]]]]]]]]]]]]] Hextk].\nrewrite /= r_ext r_k in Hextk, Hextk'.\nmove/eqP in Hextk; move/Nat2Z.inj_le/leP in Hextk'.\nhave {}Hextk : next <> nk by contradict Hextk; rewrite Hextk.\nhave {}Hextk' : (next < nk)%nat by rewrite ltn_neqAle Hextk' andbT; apply/eqP.\nexists (X `32_ next); split.\n- Decompose_32 X next X1 X2 HlenX1 HX'; last by rewrite Hx.\n  rewrite HX' (decompose_equiv _ _ _ _ _ HlenX1) !assert_m.conAE assert_m.conCE !assert_m.conAE in Hmem.\n  move: Hmem; apply monotony => // h'.\n  apply mapsto_ext => //.\n  by rewrite /= shl_Z2u r_ext inj_mult mulZC.\n- rewrite /update_store_lwxs.\n  exists Z, next; repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n  rewrite r_ext r_k; exact/inj_lt_iff/leP.\n\n(** lw Y zero16 y; *)\n\napply hoare_lw_back_alt'' with (fun s h => exists Z next, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M /\\\n    \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M < 2 * \\S_{nk} M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\ [Y_]_s = X `32_ 0).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk r_X_]]]]]]]]]]]]]].\n\ndestruct X as [| hdx tlx]; first by destruct nk.\nexists hdx; split.\nrewrite [assert_m.mapstos _ _]/= !assert_m.conAE in Hmem.\nmove: Hmem; apply monotony => // h'.\napply mapsto_ext => //=; by rewrite sext_0 addi0.\n\nrewrite /update_store_lw.\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\n(** lw Z_ zero16 z; *)\n\napply hoare_lw_back_alt'' with (fun s h => exists Z next, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M /\\\n    \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M < 2 * \\S_{nk} M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\\n  [Y_]_s = X `32_ 0 /\\ [Z_]_s = Z `32_ 0).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [r_X_ r_Y_]]]]]]]]]]]]]]].\n\ndestruct Z as [| hdz tlz]; first by destruct nk.\nexists hdz; split.\nrewrite assert_m.conAE assert_m.conCE /= !assert_m.conAE in Hmem.\nmove: Hmem; apply monotony => // h'.\napply mapsto_ext => //=; by rewrite sext_0 addi0.\nrewrite /update_store_lw.\nexists (hdz :: tlz), next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\n(** multu X Y; *)\n\napply hoare_multu with (fun s h => exists Z next, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M /\\\n    \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M < 2 * \\S_{nk} M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\\n  [Y_]_s = X `32_ 0 /\\ [Z_]_s = Z `32_ 0 /\\\n  store.utoZ s <= (\\B^1 - 1) * (\\B^1 - 1) /\\\n  store.utoZ s = u2Z (X `32_ next) * u2Z (X `32_ 0)).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [r_X_ [r_Y_ r_Z_]]]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nrewrite store.utoZ_multu; exact: max_u2Z_umul.\nby rewrite store.utoZ_multu (@u2Z_umul 32) r_X_ r_Y_.\n\n(** lw M zero16 m; *)\n\napply hoare_lw_back_alt'' with (fun s h => exists Z next, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\ [Y_]_s = X `32_ 0 /\\\n  [Z_]_s = Z `32_ 0 /\\ store.utoZ s <= (\\B^1 - 1) * (\\B^1 - 1) /\\\n  store.utoZ s = u2Z (X `32_ next) * u2Z (X `32_ 0) /\\\n  [M_]_s = M `32_ 0).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [r_X_ [r_Y_ [r_Z_ [Hm1 Hm2]]]]]]]]]]]]]]]]]].\ndestruct M as [| hdm tlm]; first by destruct nk.\nexists hdm; split.\ndo 2 rewrite assert_m.conCE /= !assert_m.conAE in Hmem.\nmove: Hmem; apply monotony => // h'.\napply mapsto_ext => //=; by rewrite sext_0 addi0.\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\n(** maddu Z_ one; *)\n\napply hoare_maddu with (fun s h => exists Z next, size Z = nk /\\ [x]_s = vx /\\\n  [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{next} X * \\S_{nk} X + K * \\S_{nk}  M /\\\n    \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M < 2 * \\S_{nk} M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\ [Y_]_s = X `32_ 0 /\\\n  [Z_]_s = Z `32_ 0 /\\ store.utoZ s <= \\B^1 * (\\B^1 - 1) /\\\n  store.utoZ s = u2Z (X `32_ next) * u2Z (X `32_ 0) + u2Z (Z `32_ 0) /\\\n  [M_]_s = M `32_ 0).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [r_X_ [r_Y_ [r_Z_ [Hm1 [Hm2 r_M_]]]]]]]]]]]]]]]]]]].\n\nexists Z, next.\nhave Htmp : store.utoZ s < \\B^2 * (2 ^^ store.acx_size - 1).\n  apply (@leZ_ltZ_trans ((\\B^1 - 1) * (\\B^1 - 1))); first by [].\n  apply (@ltZ_leZ_trans (\\B^2 * (2 ^^ 8 - 1))); first by [].\n  exact/leZ_wpmul2r.\nrepeat Reg_upd.\ndo 7 (split; trivial).\nby Assert_upd.\ndo 8 (split; trivial).\nsplit.\n  rewrite store.utoZ_maddu // Hone umul_1 (@u2Z_zext 32) r_Z_.\n  apply (@leZ_trans ((\\B^1 - 1) + (\\B^1 - 1) * (\\B^1 - 1))) => //.\n  apply leZ_add; first exact/leZsub1/max_u2Z.\n  rewrite Hm2 -u2Z_umul; exact: max_u2Z_umul.\nby rewrite store.utoZ_maddu // Hone umul_1 (@u2Z_zext 32) r_Z_ Hm2 addZC.\n\n(** mflo t; *)\n\napply hoare_mflo with (fun s h => exists Z next, size Z = nk /\\ [x]_s = vx /\\\n  [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M /\\\n    \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M < 2 * \\S_{nk} M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\ [Y_]_s = X `32_ 0 /\\\n  [Z_]_s = Z `32_ 0 /\\ store.utoZ s <= \\B^1 * (\\B^1 - 1) /\\\n  store.utoZ s = u2Z (X `32_ next) * u2Z (X `32_ 0) + u2Z (Z `32_ 0) /\\\n  [M_]_s = M `32_ 0 /\\\n  [t]_s = ((X `32_ next `* X `32_ 0) `+ zext 32 (Z `32_ 0)) `% 32).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [r_X_ [r_Y_ [r_Z_ [Hm1 [Hm2 r_M_]]]]]]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\napply store.lo_remainder.\nby rewrite -addnA leq_addl.\n\nrewrite Hm2 u2Z_add //.\nby rewrite u2Z_umul u2Z_zext.\nrewrite u2Z_zext ZpowerD -Zbeta1E -ZbetaD /=.\napply (@leZ_ltZ_trans ((\\B^1 - 1) * (\\B^1 - 1) + (\\B^1 - 1))); last by [].\napply leZ_add; [exact: max_u2Z_umul | exact/leZsub1/max_u2Z].\n\n(** mfhi s; *)\n\napply hoare_mfhi with (fun s h => exists Z next, size Z = nk /\\ [x]_s = vx /\\\n  [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M /\\\n    \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M < 2 * \\S_{nk} M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\ [Y_]_s = X `32_ 0 /\\\n  [Z_]_s = Z `32_ 0 /\\ store.utoZ s <= \\B^1 * (\\B^1 - 1) /\\\n  store.utoZ s = u2Z (X `32_ next) * u2Z (X `32_ 0) + u2Z (Z `32_ 0) /\\\n  [M_]_s = M `32_ 0 /\\\n  [t]_s = ((X `32_ next `* X `32_ 0) `+ zext 32 (Z `32_ 0)) `% 32 /\\\n  u2Z ([s_]_s `|| [t]_s) = u2Z (X `32_ next) * u2Z (X `32_ 0) + u2Z (Z `32_ 0)).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [ r_X_ [r_Y_ [r_Z_ [Hm1 [Hm2 [r_M_ r_t]]]]]]]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\nhave H : store.lo s = [t]_s.\n  rewrite r_t; apply store.lo_remainder.\n  + by rewrite -addnA leq_addl.\n  + rewrite Hm2 -u2Z_umul u2Z_add.\n    * by rewrite u2Z_zext.\n    * rewrite u2Z_zext ZpowerD -Zbeta1E -ZbetaD /=.\n      apply (@leZ_ltZ_trans ((\\B^1 - 1) * (\\B^1 - 1) + (\\B^1 - 1))); last by [].\n      apply leZ_add; [exact: (@max_u2Z_umul 32) | exact/leZsub1/max_u2Z].\n\nrewrite -H u2Z_concat -Zbeta1E.\nrewrite store.utoZ_def store.utoZ_acx_beta2 in Hm2; last exact: (@leZ_ltZ_trans (\\B^1 * (\\B^1 - 1))).\nrewrite Z2uK in Hm2; last by split; [exact: leZZ | exact: expZ_gt0].\nrewrite -Hm2; ring.\n\n(** multu t alpha; *)\n\napply hoare_multu with (fun s h => exists Z next, size Z = nk /\\ [x]_s = vx /\\\n  [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M /\\\n    \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M < 2 * \\S_{nk} M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\ [Y_]_s = X `32_ 0 /\\\n  [Z_]_s = Z `32_ 0 /\\ store.utoZ s <= (\\B^1 - 1) * (\\B^1 - 1) /\\ [M_]_s = M `32_ 0 /\\\n  [t]_s = ((X `32_ next `* X `32_ 0) `+ zext 32 (Z `32_ 0)) `% 32 /\\\n  u2Z ([s_]_s `|| [t]_s) = u2Z (X `32_ next) * u2Z (X `32_ 0) + u2Z (Z `32_ 0) /\\\n  store.utoZ s = u2Z [t]_s * u2Z [alpha]_s).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [r_X_ [r_Y_ [r_Z_ [Hm1 [Hm2 [r_M_  [r_t Hconcat]]]]]]]]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd.\ndo 6 (split; trivial).\nsplit.\nby Assert_upd.\ndo 8 (split; trivial).\nsplit; first by rewrite store.utoZ_multu; exact: max_u2Z_umul.\ndo 3 (split; trivial).\nby rewrite store.utoZ_multu -u2Z_umul.\n\n(** addiu int_ r0 one16; *)\n\napply hoare_addiu with (fun s h => exists Z next, size Z = nk /\\ [x]_s = vx /\\\n  [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M /\\\n    \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M < 2 * \\S_{nk} M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\ [Y_]_s = X `32_ 0 /\\\n  [Z_]_s = Z `32_ 0 /\\ store.utoZ s <= (\\B^1 - 1) * (\\B^1 - 1) /\\ [M_]_s = M `32_ 0 /\\\n  [t]_s = ((X `32_ next `* X `32_ 0) `+ zext 32 (Z `32_ 0)) `% 32 /\\\n  u2Z ([s_]_s `|| [t]_s) = u2Z (X `32_ next) * u2Z (X `32_ 0) + u2Z (Z `32_ 0) /\\\n  store.utoZ s = u2Z [t]_s * u2Z [alpha]_s /\\ [int_]_s = one32).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [ r_X_ [r_Y_ [r_Z_ [Hm1 [r_M_ [r_t [Hconcat Hm2]]]]]]]]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nby rewrite add0i sext_Z2u.\n\n(** mflo quot; *)\n\napply hoare_mflo with (fun s h => exists Z next, size Z = nk /\\ [x]_s = vx /\\\n  [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M /\\\n    \\S_{next} X * \\S_{nk} X + K * \\S_{nk} M < 2 * \\S_{nk} M * \\B^next) /\\ (next < nk)%nat /\\\n  [X_]_s = X `32_ next /\\ [Y_]_s = X `32_ 0 /\\ [Z_]_s = Z `32_ 0 /\\\n  store.utoZ s <= (\\B^1 - 1) * (\\B^1 - 1) /\\ [M_]_s = M `32_ 0 /\\\n  [t]_s = ((X `32_ next `* X `32_ 0) `+ zext 32 (Z `32_ 0)) `% 32 /\\\n  u2Z ([s_]_s `|| [t]_s) = u2Z (X `32_ next) * u2Z (X `32_ 0) + u2Z (Z `32_ 0) /\\\n  store.utoZ s = u2Z [t]_s * u2Z [alpha]_s /\\ [int_]_s = one32 /\\\n  [quot]_s = (((X `32_ next `* X `32_ 0) `+ (zext 32 (Z `32_ 0)) `% 32) `* [alpha]_s) `% 32).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [ r_X_ [r_Y_ [ r_Z_ [Hm1 [r_M_ [r_t [Hconcat [Hm2 Hgrpint_]]]]]]]]]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\napply store.lo_remainder.\n- by rewrite -addnA leq_addl.\n- by rewrite Hm2 r_t -u2Z_umul.\n\n(** mthi s; *)\n\napply hoare_mthi with (fun s h => exists Z next, size Z = nk /\\ [x]_s = vx /\\\n  [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M  /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next) /\\ (next < nk)%nat /\\\n  [X_]_s = X `32_ next /\\ [Y_]_s = X `32_ 0 /\\ [Z_]_s = Z `32_ 0 /\\\n  store.utoZ s < \\B^2 /\\ [M_]_s = M `32_ 0 /\\\n  [t]_s = ((X `32_ next `* X `32_ 0) `+ zext 32 (Z `32_ 0)) `% 32 /\\\n  u2Z ([s_]_s `|| [t]_s) = u2Z (X `32_ next) * u2Z (X `32_ 0) + u2Z (Z `32_ 0) /\\\n  [int_]_s = one32 /\\\n  [quot]_s = ((((X `32_ next `* X `32_ 0) `+ zext 32 (Z `32_ 0)) `% 32) `* [alpha]_s) `% 32 /\\\n  store.hi s = [s_]_s).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [r_X_ [r_Y_ [ r_Z_ [Hm1 [r_M_  [r_t [Hconcat [Hm2 [Hgrpint_ r_quot]]]]]]]]]]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nrewrite store.utoZ_def store.hi_mthi_op store.acx_mthi_op store.lo_mthi_op store.utoZ_acx_beta2; last first.\n  rewrite Hm2.\n  apply (@leZ_ltZ_trans ((\\B^1 - 1) * (\\B^1 - 1))); last by [].\n  rewrite -u2Z_umul; exact: max_u2Z_umul.\nrewrite Z2uK // addZ0.\napply (@leZ_ltZ_trans ((\\B^1 - 1) + (\\B^1 - 1) * \\B^1)); last by [].\napply leZ_add; first exact/leZsub1/max_u2Z.\napply leZ_wpmul2r => //.\nexact/leZsub1/max_u2Z.\nexact: store.hi_mthi_op.\n\n(** mtlo t; *)\n\napply hoare_mtlo with  (fun s h => exists Z next, size Z = nk /\\ [x]_s = vx /\\\n  [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\ [Y_]_s = X `32_ 0 /\\\n  [Z_]_s = Z `32_ 0 /\\ store.utoZ s < \\B^2 /\\ [M_]_s = M `32_ 0 /\\\n  [t]_s = ((X `32_ next `* X `32_ 0) `+ zext 32 (Z `32_ 0)) `% 32 /\\\n  u2Z ([s_]_s `|| [t]_s) = u2Z (X `32_ next) * u2Z (X `32_ 0) + u2Z (Z `32_ 0) /\\\n  [int_]_s = one32 /\\\n  [quot]_s = ((((X `32_ next `* X `32_ 0) `+ zext 32 (Z `32_ 0)) `% 32) `* [alpha]_s) `% 32 /\\\n  store.hi s = [s_]_s /\\ store.lo s = [t]_s).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [ r_X_ [r_Y_ [r_Z_ [Hm1 [r_M_  [r_t [ Hconcat [Hgrpint_ [r_quot Hm2]]]]]]]]]]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\nrewrite store.utoZ_def store.acx_mtlo_op store.lo_mtlo_op store.hi_mtlo_op store.utoZ_acx_beta2 // Z2uK //= addZ0.\napply (@leZ_ltZ_trans ((\\B^1 - 1) + (\\B^1 - 1) * \\B^1)); last by [].\napply leZ_add; first exact/leZsub1/max_u2Z.\napply leZ_wpmul2r => //.\nexact/leZsub1/max_u2Z.\nrewrite -Hm2.\nexact: store.hi_mtlo_op.\nexact: store.lo_mtlo_op.\n\n(** maddu quot M; *)\n\napply hoare_maddu with (fun s h => exists Z next, size Z = nk /\\ [x]_s = vx /\\\n  [z]_s = vz /\\ [m]_s = vm /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ u2Z [ext]_s < u2Z [k]_s /\\ [one]_s = one32 /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M  /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\\n  [Y_]_s = X `32_ 0 /\\ [Z_]_s = Z `32_ 0 /\\\n  [M_]_s = M `32_ 0 /\\ [int_]_s = one32 /\\\n  [quot]_s = ((((X `32_ next `* X `32_ 0) `+ zext 32 (Z `32_ 0)) `% 32) `* [alpha]_s) `% 32 /\\\n  store.utoZ s = u2Z [quot]_s * u2Z (M `32_ 0) +\n  u2Z (X `32_ next) * u2Z (X `32_ 0) + u2Z (Z `32_ 0) /\\ store.lo s = zero32).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [r_X_ [r_Y_ [r_Z_ [Hm1 [r_M_  [r_t [Hconcat [Hgrpint_ [r_quot [Hm2 Hm3]]]]]]]]]]]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nrewrite store.utoZ_maddu.\nrewrite r_M_ -u2Z_umul store.utoZ_def store.utoZ_acx_beta2 // Z2uK.\nby rewrite Hm2 Hm3 (addZC (u2Z [t]_s)) -u2Z_concat Hconcat mul0Z addZ0 addZA.\nsplit; [exact: leZZ | exact: expZ_gt0].\nexact: (@ltZ_leZ_trans (\\B^2 * 1)).\n\nrewrite r_quot; apply montgomery_lemma => //.\nby rewrite r_M_ r_alpha.\nrewrite store.utoZ_def store.utoZ_acx_beta2 // Z2uK.\nrewrite mul0Z addZ0 addZC -u2Z_concat Hm2 Hm3 Hconcat -u2Z_umul u2Z_add.\nrewrite (@u2Z_zext 32) // u2Z_zext.\napply (@leZ_ltZ_trans ((\\B^1 - 1) * (\\B^1 - 1) + (\\B^1 - 1))); last by [].\napply leZ_add; first exact: (@max_u2Z_umul 32).\nrewrite (@u2Z_zext 32) //; exact/leZsub1/max_u2Z.\nby split; [exact: leZZ | exact: expZ_gt0].\n\n(** mflhxu Z_; *)\n\napply hoare_mflhxu with (fun s h => exists Z next, size Z = nk /\\ [x]_s = vx /\\\n  [z]_s = vz /\\ [m]_s = vm /\\ [one]_s = one32 /\\ u2Z [k]_s = Z_of_nat nk /\\\n  [alpha]_s = valpha /\\ (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\\n  [Y_]_s = X `32_ 0 /\\ [M_]_s = M `32_ 0 /\\ [int_]_s = one32 /\\\n  [quot]_s = ((((X `32_ next `* X `32_ 0) `+ zext 32 (Z `32_ 0)) `% 32) `* [alpha]_s) `% 32 /\\\n  \\B^1 * u2Z (store.hi s `|| store.lo s) =\n  u2Z ([quot]_s) * u2Z (M `32_ 0) + u2Z (X `32_ next) * u2Z (X `32_ 0) + u2Z (Z `32_ 0) /\\\n  store.utoZ s < 2 * \\B^1 - 2).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [r_k [r_alpha [Hmem [r_ext [Hextk' [Hone [Hinv [Hextk [ r_X_ [r_Y_ [r_Z_ [r_M_ [r_int_ [Hquot [Hm2 Hm3]]]]]]]]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\nrewrite u2Z_concat store.hi_mflhxu_op store.lo_mflhxu_op -Hm2 store.utoZ_def.\nhave -> : \\B^2 = \\B^1 * \\B^1 by rewrite -ZbetaD.\nrewrite u2Z_zext Hm3 Z2uK // -Zbeta1E.\nrepeat Reg_upd; ring.\n\napply store.mflhxu_kbeta1_utoZ.\napply (@leZ_ltZ_trans ((\\B^1 - 1) * (\\B^1 - 1) + (\\B^1 - 1) * (\\B^1 - 1) + (\\B^1 - 1))); last by [].\nrewrite store.utoZ_upd Hm2; apply leZ_add.\napply leZ_add; rewrite -u2Z_umul; exact: max_u2Z_umul.\nexact/leZsub1/max_u2Z.\n\n(** addiu t z zero16; *)\n\napply hoare_addiu with  (fun s h => exists Z next, size Z = nk /\\ [x]_s = vx /\\\n  [z]_s = vz /\\ [m]_s = vm /\\ [one]_s = one32 /\\ u2Z [k]_s = Z_of_nat nk /\\\n  [alpha]_s = valpha /\\ (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\\n  (exists K, \\B^next * \\S_{nk.+1} (Z ++ [C]_s :: nil) = \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M  /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next) /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\\n  [Y_]_s = X `32_ 0 /\\ [M_]_s = M `32_ 0 /\\ [int_]_s = one32 /\\\n  [quot]_s = ((((X `32_ next `* X `32_ 0) `+ zext 32 (Z `32_ 0)) `% 32) `* [alpha]_s) `% 32 /\\\n  \\B^1 * u2Z (store.hi s `|| store.lo s) =\n  u2Z [quot]_s * u2Z (M `32_ 0) + u2Z (X `32_ next) * u2Z (X `32_ 0) + u2Z (Z `32_ 0) /\\\n  store.utoZ s < 2 * \\B^1 - 2 /\\ [t]_s = vz).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hinv [Hextk [r_X_ [r_Y_ [r_M_  [r_int_ [Hquot [Hm2 Hm3]]]]]]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\nby rewrite sext_Z2u // addi0.\n\n(** while (bne int_ k) *)\n\napply (hoare_prop_m.hoare_stren (fun s h => exists Z next nint_, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ [one]_s = one32 /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ (next < nk)%nat /\\ [X_]_s = X `32_ next /\\\n  u2Z [int_]_s = Z_of_nat nint_ /\\ (1 <= nint_)%nat /\\ u2Z [int_]_s <= u2Z [k]_s /\\\n  store.utoZ s < 2 * \\B^1 - 1 /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nint_ - 1) /\\\n  (exists K, \\B^next.+1 * Sum_hole nk.+1 nint_.-1 (Z ++ [C]_s :: nil) +\n    u2Z (store.hi s `|| store.lo s) * \\B^(next + nint_) =\n    \\S_{ next } X * \\S_{ nk } X + \\S_{ nint_ } X * u2Z (X `32_ next) * \\B^next +\n    \\S_{ nint_ } M * u2Z [quot]_s * \\B^next + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next))).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hinv [Hextk [r_X_ [r_Y_ [r_M_  [r_int_ [Hquot [Hm2 [Hm3 r_t]]]]]]]]]]]]]]]]]]]].\n\nexists Z, next, 1%nat.\nrepeat (split; trivial).\n\nby rewrite r_int_ Z2uK.\nrewrite r_int_ r_k Z2uK // (_ : 1 = Z_of_nat 1) //.\nby apply/inj_le/leP; apply: leq_ltn_trans Hextk.\nexact: (@ltZ_leZ_trans (2 * \\B^1 - 2)).\nrewrite r_t; ring.\n\ncase: Hinv => K [Hinv1 Hinv2].\nexists K; split; last by [].\nrewrite Sum_hole_last'; last by rewrite size_cat /= HZ addnC.\nrewrite addn1.\nhave -> : u2Z (store.hi s `|| store.lo s) * \\B^next.+1 =\n  \\B^next * (\\B^1 * u2Z (store.hi s `|| store.lo s)) by rewrite -(addn1 next) ZbetaD; ring.\nrewrite subn1.\nhave -> : \\B^next.+1 * \\S_{ nk } (List.tail (Z ++ [C]_s :: nil)) =\n  \\B^next * (\\B^1 * \\S_{ nk } (List.tail (Z ++ [C]_s :: nil))) by rewrite Zbeta_S; ring.\nrewrite lSum_Zpower_Zmult Hquot.\napply trans_eq with (\\B^next *\n  (\\S_{nk.+1} (zero32 :: List.tail (Z ++ [C]_s :: nil)) + u2Z (Z `32_ 0)) +\n  \\B^next * (u2Z [quot]_s * u2Z (M `32_ 0) + u2Z (X `32_ next) * u2Z (X `32_ 0))).\n- rewrite Hm2.\n  set tmp := \\S_{ _ } _.\n  ring.\n- rewrite lSum_head_swap0 tail_app; last by rewrite HZ; destruct nk => //; apply lt_O_Sn.\n  rewrite List.app_comm_cons.\n  move: (@list_tail _ zero32 Z) => ->; last by rewrite HZ; destruct nk => //; apply lt_O_Sn.\n  rewrite Hquot Hinv1 2!lSum_1 /zero32 /nth'; ring.\n\napply while.hoare_seq with (fun s h => (exists Z next nint_, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ [one]_s = one32 /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ (next < nk)%nat /\\ [X_]_s = X `32_ next /\\\n  u2Z [int_]_s = Z_of_nat nint_ /\\ (1 <= nint_)%nat /\\ u2Z [int_]_s <= u2Z [k]_s /\\\n  store.utoZ s < 2 * \\B^1 - 1 /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nint_ - 1) /\\\n  (exists K, \\B^next.+1 * Sum_hole nk.+1 nint_.-1 (Z ++ [C]_s :: nil) +\n    u2Z (store.hi s `|| store.lo s) * \\B^(next + nint_) =\n    \\S_{ next } X * \\S_{ nk } X + \\S_{ nint_ } X * u2Z (X `32_ next) * \\B^next +\n    \\S_{ nint_ } M * u2Z [quot]_s * \\B^next + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next))\n/\\ ~~ (eval_b (bne int_ k) s)).\n\napply while.hoare_while.\n\n(**  lwxs Y int_ y; *)\n\napply hoare_lwxs_back_alt'' with (fun s h => exists Z next nint_, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\\n  [one]_s = one32 /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\ u2Z [ext]_s = Z_of_nat next /\\\n  (next < nk)%nat /\\ (nint_ < nk)%nat /\\ [X_]_s = X `32_ next /\\\n  u2Z [int_]_s = Z_of_nat nint_ /\\ (1 <= nint_)%nat /\\\n  store.utoZ s < 2 * \\B^1 - 1 /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nint_ - 1) /\\\n  (exists K, \\B^next.+1 * Sum_hole nk.+1 nint_.-1 (Z ++ [C]_s :: nil) +\n    u2Z (store.hi s `|| store.lo s) * \\B^(next + nint_) =\n    \\S_{ next } X * \\S_{ nk } X + \\S_{ nint_ } X * u2Z (X `32_ next) * \\B^next +\n    \\S_{ nint_ } M * u2Z [quot]_s * \\B^next + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next) /\\\n  [Y_]_s = X `32_ nint_).\n\nmove=> s h [[Z [next [nint_ [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk'  [r_X_ [r_int_ [Hint_ [r_int_' [Hm2 [r_t Hinv]]]]]]]]]]]]]]]]]]] Hint_k].\nrewrite /= in Hint_k. move/eqP in Hint_k; rewrite r_int_ r_k in Hint_k.\nhave {}Hint_k : nint_ <> nk by contradict Hint_k; rewrite Hint_k.\nhave {}r_int_' : (nint_ < nk)%nat.\n  rewrite r_int_ r_k in r_int_'; move/Nat2Z.inj_le/leP in r_int_'.\n  rewrite ltn_neqAle r_int_' andbT; exact/eqP.\n\nexists (X `32_ nint_); split.\n- Decompose_32 X nint_ X1 X2 HlenX1 HX'; last by rewrite Hx.\n  rewrite HX' (decompose_equiv _ _ _ _ _ HlenX1) !assert_m.conAE assert_m.conCE !assert_m.conAE in Hmem.\n  move: Hmem; apply monotony => // h'.\n  apply mapsto_ext => //.\n  by rewrite /= shl_Z2u r_int_ inj_mult mulZC.\n- rewrite /update_store_lwxs.\n  exists Z, next, nint_; repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n\n(** lwxs Z int_ z; *)\n\napply hoare_lwxs_back_alt'' with (fun s h => exists Z next nint_, size Z = nk /\\\n  [x]_s = vx /\\  [z]_s = vz /\\ [m]_s = vm /\\ [one]_s = one32 /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ (next < nk)%nat /\\ (nint_ < nk)%nat /\\\n  [X_]_s = X `32_ next /\\ u2Z [int_]_s = Z_of_nat nint_ /\\ (1 <= nint_)%nat /\\\n  store.utoZ s < 2 * \\B^1 - 1 /\\ u2Z [t]_s = u2Z [z]_s + 4 * (Z_of_nat nint_ - 1) /\\\n  (exists K, \\B^next.+1 * Sum_hole nk.+1 nint_.-1 (Z ++ [C]_s :: nil) +\n    u2Z (store.hi s `|| store.lo s) * \\B^(next + nint_) =\n    \\S_{ next } X * \\S_{ nk } X + \\S_{ nint_ } X * u2Z (X `32_ next) * \\B^next +\n    \\S_{ nint_ } M * u2Z [quot]_s * \\B^next + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next) /\\\n  [Y_]_s = X `32_ nint_ /\\ [Z_]_s = Z `32_ nint_).\n\nmove=> s h [Z [next [nint_ [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [Hint_' [r_X_ [r_int_' [Hint_ [Hm2 [r_t [Hinv r_Y_]]]]]]]]]]]]]]]]]]]].\n\nexists (Z `32_ nint_); split.\n- Decompose_32 Z nint_ Z1 Z2 HlenZ1 HZ'; last by rewrite HZ.\n  rewrite HZ' (decompose_equiv _ _ _ _ _ HlenZ1) !assert_m.conAE assert_m.conCE !assert_m.conAE assert_m.conCE !assert_m.conAE in Hmem.\n  move: Hmem; apply monotony => // h'.\n  apply mapsto_ext => //.\n  by rewrite /= shl_Z2u r_int_' inj_mult mulZC.\n- exists Z, next, nint_; repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n  by rewrite r_t r_z.\n\n(** maddu X Y; *)\n\napply hoare_maddu with (fun s h => exists Z next nint_, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ [one]_s = one32 /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ (next < nk)%nat /\\ (nint_ < nk)%nat /\\\n  [X_]_s = X `32_ next /\\ u2Z [int_]_s = Z_of_nat nint_ /\\ (1 <= nint_)%nat /\\\n  store.utoZ s < \\B^2 /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nint_ - 1) /\\\n  [Y_]_s = X `32_ nint_ /\\ [Z_]_s = Z `32_ nint_ /\\\n  (exists K, \\B^next.+1 * Sum_hole nk.+1 nint_.-1 (Z ++ [C]_s :: nil) +\n    store.utoZ s * \\B^(next + nint_) = \\S_{ next } X * \\S_{ nk } X +\n    \\S_{ nint_ } X * u2Z (X `32_ next) * \\B^next +\n    \\S_{ nint_ } M * u2Z [quot]_s * \\B^next +\n    u2Z (X `32_ next) * u2Z (X `32_ nint_) * \\B^(next + nint_) + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next)).\n\nmove=> s h [Z [next [nint_ [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [Hint_' [ r_X_ [r_int_' [Hint_ [Hm2 [r_t [Hinv [r_Y_ r_Z_]]]]]]]]]]]]]]]]]]]]].\n\nexists Z, next, nint_.\n\nhave Htmp : store.utoZ s < \\B^2 * (2 ^^ store.acx_size - 1) by exact: (@ltZ_leZ_trans (2 * \\B^1 - 1)).\n\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nrewrite store.utoZ_maddu //.\napply (@ltZ_leZ_trans ((\\B^1 - 1) * (\\B^1 - 1) + (2 * \\B^1 - 1))); last by [].\napply leZ_lt_add; by [exact: max_u2Z_umul | ].\nby rewrite r_t r_z.\n\ncase: Hinv => K [Hinv1 Hinv2].\nexists K; split; last by []. (* about X * Y < M *)\napply trans_eq with (\\S_{ next } X * \\S_{ nk } X +\n \\S_{ nint_ } X * u2Z (X `32_ next) * \\B^next + \\S_{ nint_ } M * u2Z [quot]_s * \\B^next +\n K * \\S_{ nk } M + u2Z (X `32_ next) * u2Z (X `32_ nint_) * \\B^(next + nint_)).\n- rewrite store.utoZ_maddu // store.utoZ_def store.utoZ_acx_beta2 //; last first.\n    exact: (@ltZ_leZ_trans (2 * \\B^1 - 1)).\n  rewrite Z2uK // -u2Z_umul -Hinv1 u2Z_concat addZ0 r_Y_ r_X_ // -addZA.\n  f_equal.\n  rewrite (addZC (u2Z (X `32_ next `* X `32_ nint_))) mulZDl mulZDl.\n  f_equal.\n  by rewrite mulZDl addZC.\n- ring.\n\n(** lwxs M int_ m; *)\n\napply hoare_lwxs_back_alt'' with (fun s h => exists Z next nint_, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ [one]_s = one32 /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s =  Z_of_nat next /\\ (next < nk)%nat /\\ (nint_ < nk)%nat /\\\n  [X_]_s = X `32_ next /\\ u2Z [int_]_s =  Z_of_nat nint_ /\\ (1 <= nint_)%nat /\\\n  store.utoZ s < \\B^2 /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nint_ - 1) /\\\n  [Y_]_s = X `32_ nint_ /\\ [Z_]_s = Z `32_ nint_ /\\\n  (exists K, \\B^next.+1 * Sum_hole nk.+1 nint_.-1 (Z ++ [C]_s :: nil) +\n    store.utoZ s * \\B^(next + nint_) = \\S_{ next } X * \\S_{ nk } X +\n    \\S_{ nint_ } X * u2Z (X `32_ next) * \\B^next +\n    \\S_{ nint_ } M * u2Z [quot]_s * \\B^next +\n    u2Z (X `32_ next) * u2Z (X `32_ nint_) * \\B^(next + nint_) + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next)\n  /\\ [M_]_s = M `32_ nint_ ).\n\nmove=> s h [Z [next [nint_ [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [Hint_' [r_X_ [r_int_' [Hint_ [Hm2 [r_t [r_Y_ [r_Z_ Hinv]]]]]]]]]]]]]]]]]]]]].\n\nexists (M `32_ nint_); split.\n- Decompose_32 M nint_ M1 M2 HlenM1 HM'; last by rewrite Hm.\n  rewrite HM' (decompose_equiv _ _ _ _ _ HlenM1) in Hmem.\n  do 3 rewrite assert_m.conCE !assert_m.conAE in Hmem.\n  move: Hmem; apply monotony => // h'.\n  apply mapsto_ext => //.\n  by rewrite /= shl_Z2u r_int_' inj_mult mulZC.\n- exists Z, next, nint_; repeat Reg_upd; repeat (split; trivial).\n  by Assert_upd.\n\n(** maddu Z_ one; *)\n\napply hoare_maddu with (fun s h => exists Z next nint_, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ [one]_s = one32 /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ (next < nk)%nat /\\ (nint_ < nk)%nat /\\\n  [X_]_s = X `32_ next /\\ u2Z [int_]_s = Z_of_nat nint_ /\\ (1 <= nint_)%nat /\\\n  store.utoZ s < \\B^2 + \\B^1 - 1 /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nint_ - 1) /\\\n  [Y_]_s = X `32_ nint_ /\\ [Z_]_s = Z `32_ nint_ /\\ [M_]_s = M `32_ nint_ /\\\n  (exists K, \\B^next.+1 * Sum_hole nk.+1 nint_.-1 (Z ++ [C]_s :: nil) +\n    store.utoZ s * \\B^(next + nint_) = \\S_{ next } X * \\S_{ nk } X +\n    \\S_{ nint_ } X * u2Z (X `32_ next) * \\B^next +\n    \\S_{ nint_ } M * u2Z [quot]_s * \\B^next +\n    u2Z (X `32_ next) * u2Z (X `32_ nint_) * \\B^(next + nint_) +\n    u2Z (Z `32_ nint_) * \\B^(next + nint_) + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next)).\n\nmove=> s h [Z [next [nint_ [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [ Hint_' [r_X_ [r_int_' [Hint_ [Hm2 [r_t [r_Y_ [r_Z_ [Hinv r_M_]]]]]]]]]]]]]]]]]]]]]].\n\nexists Z, next, nint_.\n\nhave Htmp : store.utoZ s < \\B^2 * (2 ^^ store.acx_size - 1).\n  exact: (@ltZ_leZ_trans (\\B^2 * 1)).\n\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nrewrite store.utoZ_maddu //.\napply (@ltZ_leZ_trans ((\\B^1 - 1) + \\B^2)); last by [].\napply leZ_lt_add; last by [].\nrewrite Hone umul_1 (@u2Z_zext 32) //.\nexact/leZsub1/max_u2Z.\n\ncase: Hinv => K [Hinv1 Hinv2].\nexists K; split; last by []. (* about X * Y < M *)\nrewrite store.utoZ_maddu // Hone umul_1 (@u2Z_zext 32) //.\napply trans_eq with (\\B^next.+1 * Sum_hole nk.+1 nint_.-1 (Z ++ [C]_s :: nil) +\n     store.utoZ s * \\B^(next + nint_) + u2Z (Z `32_ nint_) * \\B^(next + nint_)).\nby rewrite -r_Z_ {1}(addZC (u2Z [Z_]_s)) mulZDl addZA.\nrewrite Hinv1; ring.\n\n(** maddu quot M; *)\n\napply hoare_maddu with (fun s h => exists Z next nint_, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ [one]_s = one32 /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ (next < nk)%nat /\\ (nint_ < nk)%nat /\\\n  [X_]_s = X `32_ next /\\ u2Z [int_]_s = Z_of_nat nint_ /\\ (1 <= nint_)%nat /\\\n  store.utoZ s < 2 * \\B^2 - \\B^1 /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nint_ - 1) /\\\n  [Y_]_s = X `32_ nint_ /\\ [Z_]_s = Z `32_ nint_ /\\ [M_]_s = M `32_ nint_ /\\\n  (exists K, \\B^next.+1 * Sum_hole nk.+1 nint_.-1 (Z ++ [C]_s :: nil) +\n    store.utoZ s * \\B^(next + nint_) = \\S_{ next } X * \\S_{ nk } X +\n    \\S_{ nint_ } X * u2Z (X `32_ next) * \\B^next +\n    \\S_{ nint_ } M * u2Z [quot]_s * \\B^next +\n    u2Z (X `32_ next) * u2Z (X `32_ nint_) * \\B^(next + nint_) +\n    u2Z (Z `32_ nint_) * \\B^(next + nint_) +\n    u2Z (M `32_ nint_) * u2Z [quot]_s * \\B^(next + nint_) + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next)).\n\nmove=> s h [Z [next [nint_ [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [Hint_' [r_X_ [r_int_' [Hint_ [Hm2 [r_t [r_Y_ [r_Z_ [r_M_ Hinv]]]]]]]]]]]]]]]]]]]]]].\nexists Z, next, nint_.\n\nhave Htmp : store.utoZ s < \\B^2 * (2 ^^ store.acx_size - 1) by exact: (@ltZ_leZ_trans (\\B^2 + \\B^1 - 1)).\n\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nrepeat (split; trivial).\n\nrewrite store.utoZ_maddu //.\napply (@ltZ_leZ_trans ((\\B^1 - 1) * (\\B^1 - 1) + (\\B^2 + \\B^1 - 1))); last by [].\napply leZ_lt_add => //; exact: max_u2Z_umul.\n\ncase: Hinv => K [Hinv1 Hinv2].\nexists K; split; last by []. (* about X * Y < M *)\nrewrite store.utoZ_maddu // mulZDl.\napply trans_eq with (\\B^next.+1 * Sum_hole nk.+1 nint_.-1 (Z ++ [C]_s :: nil) +\n  store.utoZ s * \\B^(next + nint_) + (u2Z ([quot]_s `* [M_]_s) * \\B^(next + nint_))).\nby rewrite (addZC (u2Z ([quot]_s `* [M_]_s) * \\B^(next + nint_))) addZA.\nrewrite Hinv1 u2Z_umul r_M_; ring.\n\n(** addiu int_ int_ one16; *)\n\napply hoare_addiu with (fun s h => exists Z next nint_, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ [one]_s = one32 /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ (next < nk)%nat /\\ (nint_ <= nk)%nat /\\\n  [X_]_s = X `32_ next /\\ u2Z [int_]_s = Z_of_nat nint_ /\\ (2 <= nint_)%nat /\\\n  store.utoZ s < 2 * \\B^2 - \\B^1  /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nint_ - 2) /\\\n  (exists K, \\B^next.+1 * Sum_hole nk.+1 nint_.-2 (Z ++ [C]_s :: nil) +\n    store.utoZ s * \\B^((next + nint_).-1) = \\S_{ next } X * \\S_{ nk } X +\n    \\S_{nint_.-1} X * u2Z (X `32_ next) * \\B^next +\n    \\S_{nint_.-1} M * u2Z [quot]_s * \\B^next +\n    u2Z (X `32_ next) * u2Z (X `32_ nint_.-1)  * \\B^((next + nint_).-1)+\n    u2Z (Z `32_ nint_.-1) * \\B^((next + nint_).-1) +\n    u2Z (M `32_ nint_.-1) * u2Z [quot]_s * \\B^((next + nint_).-1) + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next)).\n\nmove=> s h [Z [next [nint_ [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk'  [Hint_' [r_X_ [r_int_' [Hint_ [Hm2 [r_t [r_Y_ [r_Z_ [r_M_ Hinv]]]]]]]]]]]]]]]]]]]]]].\n\nexists Z, next, nint_.+1; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\nrewrite sext_Z2u // u2Z_add_Z2u //.\n- by rewrite r_int_' Z_S.\n- rewrite r_int_'.\n  apply (@leZ_ltZ_trans (Z_of_nat nk)).\n  rewrite (_ : 1 = Z_of_nat 1) //. by omegaz' ssromega. (*-inj_plus plus_comm; exact/inj_le/leP.*)\n  apply: leZ_ltZ_trans; last exact/Hnz.\n  apply leZ_addl; first exact: min_u2Z.\n  rewrite mulZC; apply Zle_scale; [exact/Zle_0_nat | by [] ].\n\nrewrite r_t Z_S; ring.\n\ncase: Hinv => K [Hinv1 Hinv2].\nexists K; split; last by []. (* about X * Y < M *)\nby rewrite addnS /= Hinv1.\n\n(** mflhxu Z_; *)\n\napply hoare_mflhxu with (fun s h => exists Z next nint_, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\\n  [one]_s = one32 /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\ u2Z [ext]_s = Z_of_nat next /\\\n  (next < nk)%nat /\\ (nint_ <= nk)%nat /\\ [X_]_s = X `32_ next /\\\n  u2Z [int_]_s = Z_of_nat nint_ /\\ (2 <= nint_)%nat /\\\n  store.utoZ s < 2 * \\B^1 - 1 /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nint_ - 2) /\\\n  (exists K, \\B^next.+1 * Sum_hole nk.+1 nint_.-2 (Z ++ [C]_s :: nil) +\n    u2Z (store.hi s `|| store.lo s) * \\B^(next + nint_) +\n    u2Z [Z_]_s * \\B^((next + nint_).-1) = \\S_{ next } X * \\S_{ nk } X +\n    \\S_{nint_.-1} X * u2Z (X `32_ next) * \\B^next +\n    \\S_{nint_.-1} M * u2Z [quot]_s * \\B^next +\n    u2Z (X `32_ next) * u2Z (X `32_ nint_.-1)  * \\B^((next + nint_).-1) +\n    u2Z (Z `32_ nint_.-1) * \\B^((next + nint_).-1) +\n    u2Z (M `32_ nint_.-1) * u2Z [quot]_s * \\B^((next + nint_).-1) + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next)).\n\nmove=> s h [Z [next [nint_ [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [Hint_' [r_X_ [r_int_' [Hint_ [Hm2 [r_t Hinv]]]]]]]]]]]]]]]]]]].\n\nexists Z, next, nint_; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\napply store.mflhxu_kbeta1_utoZ.\napply (@ltZ_leZ_trans (2 * \\B^2 - \\B^1)); by [rewrite store.utoZ_upd | ].\ncase: Hinv => K [Hinv1 Hinv2].\nexists K; split; last by [].  (* about X * Y < M *)\n\nrewrite -Hinv1 u2Z_concat store.hi_mflhxu_op store.lo_mflhxu_op u2Z_zext store.utoZ_def -addZA.\nf_equal.\nrewrite -Zbeta1E /= 3!mulZDl -3!mulZA -3!ZbetaD.\nrewrite 2!add1n add2n prednK; last by rewrite addn_gt0 (ltn_trans _ Hint_) // orbT.\nrepeat Reg_upd; ring.\n\n(** addiu t t four16; *)\n\napply hoare_addiu with (fun s h => exists Z next nint_, size Z = nk /\\\n  [x]_s = vx /\\  [z]_s = vz /\\ [m]_s = vm /\\\n  [one]_s = one32 /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ (next < nk)%nat /\\ (nint_ <= nk)%nat /\\\n  [X_]_s = X `32_ next /\\ u2Z [int_]_s = Z_of_nat nint_ /\\ (2 <= nint_)%nat /\\\n  store.utoZ s < 2 * \\B^1 - 1 /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nint_-1) /\\\n  (exists K, \\B^next.+1 * Sum_hole nk.+1 nint_.-2 (Z ++ [C]_s :: nil) +\n    u2Z (store.hi s `|| store.lo s) * \\B^(next + nint_) +\n    u2Z [Z_]_s * \\B^((next + nint_).-1) = \\S_{ next } X * \\S_{ nk } X +\n    \\S_{nint_.-1} X * u2Z (X `32_ next) * \\B^next +\n    \\S_{nint_.-1} M * u2Z [quot]_s * \\B^next +\n    u2Z (X `32_ next) * u2Z (X `32_ nint_.-1)  * \\B^((next + nint_).-1) +\n    u2Z (Z `32_ nint_.-1) * \\B^((next + nint_).-1) +\n    u2Z (M `32_ nint_.-1) * u2Z [quot]_s * \\B^((next + nint_).-1) + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next)).\n\nmove=> s h [Z [next [nint_ [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [Hint_' [r_X_ [r_int_' [Hint_ [Hm2 [r_t Hinv]]]]]]]]]]]]]]]]]]].\n\nexists Z, next, nint_; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nrewrite sext_Z2u // u2Z_add_Z2u //.\n- rewrite r_t; ring.\n- rewrite r_t -Zbeta1E.\n  apply: (leZ_ltZ_trans _ Hnz).\n  rewrite -addZA; apply leZ_add2l.\n  rewrite -{2}(mulZ1 4) -mulZDr; apply leZ_wpmul2l => //.\n  rewrite -addZA; apply addr_leZ => //; exact/inj_le/leP.\n\n(** sw Z_ mfour16 t *)\n\napply hoare_sw_back'.\nmove=> s h [Z [next [nint_ [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [Hint_' [r_X_ [r_int_' [Hint_ [Hm2 [r_t Hinv]]]]]]]]]]]]]]]]]]].\n\nexists (int_e (Z `32_ nint_.-2)).\n\nhave Htmp: [z]_s `+ Z2u 32 (Z_of_nat (4 * nint_.-2)) = [t]_s `+ sext 16 mfour16.\n  rewrite /mfour16 sext_Z2s // r_z; apply u2Z_inj.\n  rewrite u2Z_add_Z2s //.\n  rewrite u2Z_add_Z_of_nat.\n  rewrite r_t -subn2 inj_mult inj_minus1; last exact/leP.\n  ring.\n  rewrite inj_mult -subn2 inj_minus1 //; last exact/leP.\n  rewrite -Zbeta1E [Z_of_nat _]/=.\n  apply: (leZ_ltZ_trans _ Hnz).\n  apply/leZ_add2l/leZ_wpmul2l; first by [].\n  rewrite -inj_minus1 //; last exact/leP.\n  rewrite minusE.\n  apply/inj_le/leP.\n  by rewrite subn2 (leq_trans (leq_pred _ )) // (leq_trans _ Hint_') // leq_pred.\n  rewrite r_t -addZA (_ : -4 = 4 * ( -1 )) // -mulZDr.\n  apply leZ_addl; first exact: min_u2Z.\n  rewrite mulZC; apply mulZ_ge0 => //.\n  rewrite -addZA /= (_ : -2 = - Z_of_nat 2) //.\n  exact/Zle_left/inj_le/leP.\n\nDecompose_32 Z (nint_.-2) Z1 Z2 HlenZ1 HZ'; last first.\n  rewrite HZ.\n  ssromega.\nrewrite HZ' (decompose_equiv _ _ _ _ _ HlenZ1) !assert_m.conAE assert_m.conCE !assert_m.conAE assert_m.conCE !assert_m.conAE in Hmem.\nmove: Hmem; apply monotony => // ht.\nexact: mapsto_ext.\n\napply currying => h' H'; simpl app in H'.\n\nexists (upd_nth Z nint_.-2 [Z_]_s), next, nint_; repeat (split; trivial).\nexact: size_upd_nth.\nrewrite HZ' upd_nth_cat HlenZ1 // subnn /= (decompose_equiv _ _ _ _ _ HlenZ1).\nrewrite cat0s in H'.\nassoc_comm H'.\nmove: H'; exact: mapsto_ext.\nby rewrite (ltn_trans _ Hint_).\nrewrite r_int_' r_k; exact/inj_le/leP.\ncase: Hinv => K [Hinv1 Hinv2].\nexists K; split; last by []. (* about X * Y < M *)\n\n(* technicalities:\n\n   at this point, we have an hypothesis about K with\n   ( z_0 ... z_{nint-2} ... z_{k-1} ++ C::nil )\\{nint-2}\n\n   whereas in the goal, we have\n   ( z_0 ...     Z      ... z_{k-1} ++ C::nil )\\{nint-1}\n\n   we will:\n   1. coax the hypothesis and the goal to have the same Sum_hole predicate\n      1.a. add z_{nint-1} to the goal\n      1.b. use the Sum_hole_shift property to change the Sum_hole predicate in the goal\n   2. check that the goal can be obtained from the hypo by rewriting\n *)\n\n(* 1. *)\n\n(* 1.a. *)\n\napply (eqZ_add2l (\\B^next.+1 * u2Z (Z `32_ nint_.-1) * \\B^nint_.-2)).\nrewrite addZA -mulZA -(mulZDr (\\B^next.+1)).\n\n(* 1.b. *)\n\nrewrite (addZC (u2Z (Z `32_ nint_.-1) * \\B^nint_.-2)).\nhave -> : Sum_hole nk.+1 nint_.-1 (upd_nth Z nint_.-2 [Z_]_s ++ [C]_s :: nil) +\n    u2Z (Z `32_ nint_.-1) * \\B^nint_.-2 =\n    Sum_hole nk.+1 nint_.-2 (Z ++ [C]_s :: nil) + u2Z [Z_]_s * \\B^nint_.-2.\n  have H_ : size (upd_nth Z nint_.-2 [Z_]_s ++ [C]_s :: nil) = nk.+1.\n    by rewrite size_cat (@size_upd_nth _ nk) // addn1.\n  have H1__ : (nint_.-1 < nk)%nat by rewrite prednK // (ltn_trans _ Hint_).\n  have H1_ : (nint_.-1 < nk.+1)%nat by apply ltnW.\n  have H1___ : (nint_.-2 < nk)%nat by rewrite prednK // -ltnS // prednK // (ltn_trans _ Hint_).\n  move/(Sum_hole_shift _ _ H_ _) : H1_ => {}H_.\n  do 2 rewrite nth_cat (@size_upd_nth _ nk) // in H_.\n  rewrite H1__ subn1 H1___ nth_upd_nth' in H_; last first.\n    destruct nint_; first by [].\n    destruct nint_; first by [].\n    destruct nint_ as [|nint_]; first by [].\n    apply/eqP; by rewrite neq_ltn /= ltnSn orbT.\n  rewrite nth_upd_nth in H_; last by rewrite HZ.\n  have -> : Sum_hole nk.+1 nint_.-2 (Z ++ [C]_s :: nil) =\n                Sum_hole nk.+1 nint_.-2 (upd_nth Z nint_.-2 [Z_]_s ++ [C]_s :: nil).\n  rewrite -upd_nth_cat'; last by rewrite HZ.\n  rewrite -Sum_hole_upd_nth //.\n  by rewrite size_cat addn1 /= HZ.\n  by rewrite mulnC in H_.\n\n(* 2. *)\n\nhave Htmp2 : (next.+1 + nint_.-2 = (next + nint_).-1)%nat.\n  rewrite addSnnS prednK //; last by rewrite -ltnS // prednK // (ltn_trans _ Hint_).\n  rewrite -[RHS]subn1 -addnBA //; last by rewrite (ltn_trans _ Hint_).\n  by rewrite subn1.\n\napply trans_eq with (\\B^next.+1 * Sum_hole nk.+1 nint_.-2 (Z ++ [C]_s :: nil) +\n u2Z (store.hi s `|| store.lo s) * \\B^(next + nint_) +\n  u2Z [Z_]_s * (\\B^next.+1 * \\B^nint_.-2)).\nring.\n\nrewrite -ZbetaD Htmp2 {}Hinv1.\n\napply trans_eq with ((\\S_{nint_.-1} X * u2Z (X `32_ next) * \\B^next +\n  u2Z (X `32_ next) * u2Z (X `32_ nint_.-1) * \\B^((next + nint_).-1)) +\n(\\S_{nint_.-1} M * u2Z [quot]_s * \\B^next +\n  u2Z (M `32_ nint_.-1) * u2Z [quot]_s * \\B^((next + nint_).-1))\n+ K * \\S_{ nk } M + \\S_{ next } X * \\S_{ nk } X\n+ u2Z (Z `32_ nint_.-1) * \\B^((next + nint_).-1)).\nring.\n\napply trans_eq with (\\S_{ nint_ } X * u2Z (X `32_ next) * \\B^next +\n  \\S_{ nint_ } M * u2Z [quot]_s * \\B^next\n  + K * \\S_{ nk } M + \\S_{ next } X * \\S_{ nk } X\n  + (u2Z (Z `32_ nint_.-1) * (\\B^next.+1 * \\B^nint_.-2)) ); last by ring.\n\nf_equal; last by rewrite -ZbetaD Htmp2.\n\ndo 3 f_equal.\napply trans_eq with ((\\S_{nint_.-1} X + u2Z (X `32_ nint_.-1) * \\B^nint_.-1) * (u2Z (X `32_ next) * \\B^next)).\n- rewrite -(subn1 (next + nint_)) -addnBA; last exact: leq_trans Hint_.\n  rewrite subn1 ZbetaD; ring.\n- rewrite (mulZC _ (\\B^nint_.-1)) {1}/Zbeta -lSum_remove_last.\n- rewrite prednK //.\n  by rewrite mulZA.\n  exact: leq_trans Hint_.\n\napply trans_eq with ((\\S_{nint_.-1} M + u2Z (M `32_ nint_.-1) * \\B^nint_.-1) * (u2Z [quot]_s * \\B^next)).\n- rewrite -(subn1 (next + nint_)) -addnBA; last exact: leq_trans Hint_.\n  rewrite subn1 ZbetaD; ring.\n- rewrite (mulZC _ (\\B^nint_.-1)) -lSum_remove_last prednK //.\n  by rewrite mulZA.\n  exact: leq_trans Hint_.\n\n(** maddu C one; *)\n\napply hoare_maddu with (fun s h => exists Z next, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ [one]_s = one32 /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ (next < nk)%nat /\\\n  [X_]_s = X `32_ next /\\ u2Z [int_]_s = Z_of_nat nk /\\\n  store.utoZ s < 3 * \\B^1 - 2 /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nk - 1) /\\\n  (exists K, \\B^next.+1 * \\S_{nk.-1} Z + store.utoZ s * \\B^(next + nk) =\n    \\S_{ next } X * \\S_{ nk } X + \\S_{ nk } X * u2Z (X `32_ next) * \\B^next +\n    \\S_{ nk } M * u2Z [quot]_s * \\B^next + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next)).\n\nmove=> s h [[Z [next [nint_ [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [Hint_' [r_int_' [r_X_ [Hint_ [Hm2 [r_t Hinv]]]]]]]]]]]]]]]]]]] Hint_k].\nrewrite /= r_int_' r_k in Hint_k.\nmove/negPn/eqP/Z_of_nat_inj in Hint_k; subst nint_.\n\nexists Z, next.\n\nhave Htmp : store.utoZ s < \\B^2 * (2 ^^ store.acx_size - 1) by apply (@ltZ_leZ_trans (2 * \\B^1 - 1)).\n\nrepeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nrewrite store.utoZ_maddu // Hone umul_1 (@u2Z_zext 32) //.\napply (@ltZ_leZ_trans ((\\B^1 - 1) + (2 * \\B^1 - 1))); last by [].\napply leZ_lt_add => //; exact/leZsub1/max_u2Z.\n\ncase : Hinv => K [Hinv1 Hinv2].\nexists K; split; last by []. (* about X * Y < M *)\nrewrite -Hinv1 store.utoZ_maddu // Hone umul_1 (@u2Z_zext 32).\nrewrite mulZDl addZA /Sum_hole // store.utoZ_def store.utoZ_acx_beta2; last by exact: (@ltZ_leZ_trans (2 * \\B^1 - 1)).\nrewrite Z2uK; last by split; [exact: leZZ | exact: expZ_gt0].\nrewrite mul0Z addZ0 u2Z_concat.\nhave [Z' [tl H ] ] : exists Z' tl, Z = Z' ++ tl :: nil.\n  clear -HZ r_X_.\n  case/lastP : Z HZ r_X_ => /=; first by move=> <-.\n  move=> h t _ _; by exists h, t; rewrite -cats1.\nrewrite {2}H -catA.\nhave H0 : size Z' = nk.-1 by rewrite H size_cat /= addn1 in HZ; rewrite -HZ.\nrewrite (@idel_app _ _ Z' H0 _ tl ([C]_s :: nil)) //.\nmove: (lSum_remove_last _ (Z' ++ [C]_s :: nil) nk.-1) => H1.\nrewrite -(@lSum_beyond _ nk.-1) in H1; last by [].\nrewrite nth_cat H0 ltnn subnn [nth _ _ _]/= in H1.\nrewrite prednK // in H1.\nrewrite subn1.\nrewrite H1 (mulZDr (\\B^next.+1)).\nhave <- : \\S_{nk.-1} Z = \\S_{nk.-1} Z' by rewrite H -lSum_beyond.\nrewrite -ZbetaE mulZA -ZbetaD.\nrewrite addSnnS prednK //.\nby rewrite (mulZC (\\B^(next + nk))) (addZC (u2Z (store.lo s))).\n\n(** mflhxu Z_; *)\n\napply hoare_mflhxu with (fun s h => exists Z next, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\\n  [one]_s = one32 /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\ u2Z [ext]_s = Z_of_nat next /\\\n  (next < nk)%nat /\\ [X_]_s = X `32_ next /\\ store.utoZ s < 3  /\\\n  u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nk - 1) /\\\n  (exists K, \\B^next.+1 * \\S_{nk.-1} Z + u2Z (store.lo s) * \\B^((next + nk).+1) +\n    u2Z [Z_]_s * \\B^(next + nk) = \\S_{ next } X * \\S_{ nk } X +\n    \\S_{ nk } X * u2Z (X `32_ next) * \\B^next +\n    \\S_{ nk } M * u2Z [quot]_s * \\B^next + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M < 2 * \\S_{ nk } M * \\B^next)).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [r_X_ [r_int_ [Hm2 [r_t Hinv]]]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\napply store.mflhxu_kbeta1_utoZ.\napply (@ltZ_trans (3 * \\B^1 - 2)); by [rewrite store.utoZ_upd | ].\ncase: Hinv => K [Hinv1 Hinv2].\nexists K; split; last by []. (* about X * Y < M *)\nrewrite -Hinv1 store.lo_mflhxu_op store.utoZ_def store.utoZ_acx_beta2; last exact: (@ltZ_leZ_trans (3 * \\B^1 -2)).\nrewrite Z2uK; last by split; [exact: leZZ | exact: expZ_gt0].\nrewrite mul0Z addZ0 mulZDl -mulZA -ZbetaD (addnC 1%nat).\nrewrite addn1 -addnS; repeat Reg_upd; ring.\n\n(** addiu ext ext one16; *)\n\napply hoare_addiu with (fun s h => exists Z next, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\ [one]_s = one32 /\\\n  u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ (1 <= next <= nk)%nat /\\\n  store.utoZ s < 3 /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nk - 1) /\\\n  (exists K, \\B^next * \\S_{nk.-1} Z + u2Z (store.lo s) * \\B^(next + nk) +\n    u2Z [Z_]_s * \\B^((next + nk).-1) = \\S_{next.-1} X * \\S_{ nk } X +\n    \\S_{ nk } X * u2Z (X `32_ next.-1) * \\B^(next-1) +\n    \\S_{ nk } M * u2Z [quot]_s * \\B^next.-1 + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M + (\\B^1 - 1) * (\\B^next.-1 * \\S_{ nk } M)\n    < 2 * \\S_{ nk } M * \\B^next)).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [r_X_ [Hm2 [r_t Hinv]]]]]]]]]]]]]]].\n\nexists Z, next.+1; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\nrewrite sext_Z2u // u2Z_add_Z2u // r_ext.\nby rewrite Z_S.\napply (@leZ_ltZ_trans (Z_of_nat nk)).\nrewrite (_ : 1 = Z_of_nat 1) // -inj_plus plusE addn1; exact/inj_le/leP.\nrewrite -r_k; exact: max_u2Z.\n\ncase: Hinv => K [Hinv1 Hinv2].\nexists K; split.\n- by rewrite !subn1 -Hinv1 addSn.\n- (* about X * Y < M *)\n  rewrite lSum_remove_last mulZDl.\n  apply (@ltZ_leZ_trans (2 * \\S_{ nk } M * \\B^next + u2Z (X `32_ next) * \\B^next * \\S_{ nk } X +\n    (\\B^1 - 1) * \\B^next * \\S_{ nk } M)).\n  apply ltZ_le_add.\n  rewrite -ZbetaE (mulZC (\\B^next)) /zero32 addZC addZA;\n    by apply ltZ_le_add; [rewrite addZC | apply leZZ].\n  rewrite mulZA; exact/leZZ.\n  apply (@leZ_trans (2 * \\S_{ nk } M * \\B^next + (\\B^1 - 1) * \\B^next * \\S_{ nk } X +\n    (\\B^1 - 1) * \\B^next * \\S_{ nk } M)).\n  apply leZ_add2r, leZ_add2l.\n  rewrite -2!mulZA.\n  apply leZ_wpmul2r.\n  apply mulZ_ge0 => //; exact: min_lSum.\n  exact/leZsub1/max_u2Z.\n  rewrite -addZA.\n  apply (@leZ_trans (2 * \\S_{ nk } M * \\B^next +\n    ((\\B^1 - 1) * \\B^next * \\S_{ nk } M + (\\B^1 - 1) * \\B^next * \\S_{ nk } M))).\n    apply leZ_add2l, leZ_add2r, leZ_wpmul2l.\n    apply mulZ_ge0; by [ | exact: Zbeta_0'].\n  exact/ltZW.\n  suff: 2 * \\S_{ nk } M * \\B^next + ((\\B^1 - 1) * \\B^next * \\S_{ nk } M + (\\B^1 - 1) * \\B^next * \\S_{ nk } M)\n    = 2 * \\S_{ nk } M * \\B^next.+1 by move=> ->; apply leZZ.\n  rewrite (Zbeta_S next); ring.\n\n(** sw Z_ zero16 t; *)\n\napply hoare_sw_back'' with (fun s h => exists Z next, size Z = nk /\\\n  [x]_s = vx /\\ [z]_s = vz /\\ [m]_s = vm /\\\n  [one]_s = one32 /\\ u2Z [k]_s = Z_of_nat nk /\\ [alpha]_s = valpha /\\\n  (var_e x |--> X ** var_e z |--> Z ** var_e m |--> M) s h /\\\n  u2Z [ext]_s = Z_of_nat next /\\ (1 <= next <= nk)%nat /\\\n  store.utoZ s < 3 /\\ u2Z [t]_s = u2Z vz + 4 * (Z_of_nat nk - 1) /\\\n  (exists K, \\B^next * \\S_{ nk } Z + u2Z (store.lo s) * \\B^(next + nk) =\n    \\S_{next.-1} X * \\S_{ nk } X + \\S_{ nk } X * u2Z (X `32_ next.-1) * \\B^(next-1) +\n    \\S_{ nk } M * u2Z [quot]_s * \\B^(next-1) + K * \\S_{ nk } M /\\\n    \\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M + (\\B^1 - 1) * (\\B^next.-1 * \\S_{ nk } M) < 2 * \\S_{ nk } M * \\B^next)).\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [Hm2 [r_t Hinv]]]]]]]]]]]]]].\n\nhave [lst1 [last H0 ] ] : exists Z' tl, Z = Z' ++ tl :: nil.\n  clear -HZ Hextk'.\n  case/lastP : Z HZ Hextk' => [<-|].\n    rewrite leqn0; case/andP => H1 /eqP H2; by rewrite H2 in H1.\n  move=> h t _ _; by exists h, t; rewrite cats1.\nhave Hlenlst1 : size lst1 = nk.-1 by rewrite -HZ H0 size_cat /= addn1.\nhave Htmp : [ var_e t \\+ int_e (sext 16 zero16) ]e_ s = [ var_e z \\+ int_e (Z2u 32 (Z_of_nat (4 * nk.-1))) ]e_ s.\n  rewrite /= sext_0 addi0; apply u2Z_inj.\n  rewrite u2Z_add_Z_of_nat.\n  rewrite inj_mult -subn1 inj_minus1 //; last by destruct nk => //; exact/le_n_S/le_O_n.\n  rewrite r_t r_z; simpl Z_of_nat; ring.\n  rewrite inj_mult -subn1 inj_minus1 //; last by destruct nk => //; exact/le_n_S/le_O_n.\n  rewrite r_z; simpl Z_of_nat.\n  apply: leZ_ltZ_trans; last exact: Hnz.\n  apply/leZ_add2l/leZ_wpmul2l; first by [].\n  rewrite (_ : 1 = Z_of_nat 1) // -inj_minus1 //; last by ssromega.\n  apply/inj_le/leP; by rewrite minusE subn1 leq_pred.\n\nexists (int_e last).\n\nrewrite H0 (decompose_equiv _ _ _ _ _ Hlenlst1) !assert_m.conAE assert_m.conCE !assert_m.conAE assert_m.conCE !assert_m.conAE in Hmem.\nmove: Hmem; apply monotony => // ht.\nexact: mapsto_ext.\napply currying => h' H'; simpl assert_m.mapstos in H'.\n\nexists (upd_nth Z nk.-1 [Z_]_s), next.\n\nrepeat (split; trivial).\nexact: size_upd_nth.\nrewrite H0 upd_nth_cat Hlenlst1 // subnn /= (decompose_equiv _ _ _ _ _ Hlenlst1).\nsimpl assert_m.mapstos.\nassoc_comm H'.\nexact: mapsto_ext H'.\n\ncase: Hinv => K [Hinv1 Hinv2].\nexists K; split; last by []. (* about X * Y < M *)\nrewrite (subn1 next).\nrewrite (subn1 next) in Hinv1.\nrewrite -Hinv1.\nhave -> : upd_nth Z nk.-1 [Z_]_s = lst1 ++ [Z_]_s :: nil.\n  rewrite H0 upd_nth_cat /=.\n  by rewrite Hlenlst1 subnn.\n  by rewrite Hlenlst1.\nrewrite (lSum_cut_last nk) //; last by rewrite size_cat /= -HZ H0 size_cat.\nrewrite mulZDr mulZA -ZbetaD !subn1.\nrewrite H0 -(lSum_beyond 32 nk.-1 lst1) //.\nrewrite -(subn1 (next + nk)) -addnBA //.\nrewrite subn1; ring.\nrewrite (@leq_trans next) //.\nby case/andP : Hextk'.\nby case/andP : Hextk'.\n\n(** mflhxu C *)\n\napply hoare_mflhxu'.\n\nmove=> s h [Z [next [HZ [r_x [r_z [r_m [Hone [r_k [r_alpha [Hmem [r_ext [Hextk' [Hm2 [r_t Hinv]]]]]]]]]]]]]].\n\nexists Z, next; repeat Reg_upd; repeat (split; trivial).\nby Assert_upd.\n\nrewrite r_ext r_k.\n\napply/inj_le/leP; by case/andP: Hextk'.\n\nrewrite -subn1 inj_minus1 //; destruct nk => //; exact/le_n_S/le_O_n.\n\ncase: Hinv => K [Hinv1 Hinv2].\nexists (K + u2Z [quot]_s * \\B^(next - 1)); split.\n- rewrite lSum_cut_last; last by rewrite size_cat /= HZ addnC.\n  rewrite !subn1 mulZDr mulZA -ZbetaD (mulZC (\\B^(next + nk))) Hinv1.\n  have <- : \\S_{next.-1} X + u2Z (X `32_ next.-1) * \\B^next.-1 = \\S_{ next } X.\n    rewrite -(mulZC (\\B^next.-1)) /Zbeta -lSum_remove_last //.\n    rewrite prednK //.\n    by case/andP: Hextk'.\n  rewrite subn1; ring.\n(* about X * Y < M *)\n- apply (@leZ_ltZ_trans(\\S_{ next } X * \\S_{ nk } X + K * \\S_{ nk } M + ((\\B^1 - 1) * \\B^next.-1 * \\S_{ nk } M))); last by rewrite -mulZA.\n  rewrite mulZDl addZA.\n  apply/leZ_add2l/leZ_wpmul2r; first exact: min_lSum.\n  rewrite subn1; apply leZ_wpmul2r => //; exact/leZsub1/max_u2Z.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/cryptoasm/mont_square_triple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.20669426336586666}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom compcert Require Import Integers Values AST Ctypes.\nFrom Coq Require Import ZArith.\n\nFrom bpf.comm Require Import BinrBPF Monad.\nFrom bpf.verifier.comm Require Import state monad.\nFrom bpf.model Require Import Syntax.\nFrom bpf.verifier.synthesismodel Require Import opcode_synthesis.\n\nOpen Scope nat_scope.\nOpen Scope monad_scope.\n\n(** TODO: we should add a rule to ensure lddw_high and lddw_low come in pairs and the latter is always after the former *)\n\nDefinition is_dst_R0 (i: int64) : M state.state bool := returnM (is_dst_R0' i).\n\nDefinition is_well_dst (i: int64) : M state.state bool := returnM (is_well_dst' i).\n\nDefinition is_well_src (i: int64) : M state.state bool := returnM (is_well_src' i).\n\nDefinition is_well_jump (pc len: nat) (ofs: int) : M state.state bool := returnM (is_well_jump' pc len ofs).\n\nDefinition is_not_div_by_zero (i: int64) : M state.state bool := returnM (is_not_div_by_zero' i).\n\nDefinition is_not_div_by_zero64 (i: int64) : M state.state bool := returnM (is_not_div_by_zero64' i).\n\nDefinition is_shift_range (i: int64) (upper: int): M state.state bool := returnM (is_shift_range' i upper).\n\nDefinition is_shift_range64 (i: int64) (upper: int): M state.state bool := returnM (is_shift_range64' i upper).\n\nDefinition get_opcode (ins: int64): M state.state nat := returnM (get_opcode ins).\n\nDefinition get_offset (i: int64): M state.state int := returnM (get_offset i).\n\nDefinition bpf_verifier_opcode_alu32_imm (op: nat) (ins: int64) : M state.state bool :=\n  match nat_to_opcode_alu32_imm op with\n  | DIV32_IMM\n  | MOD32_IMM => (**r DIV_IMM *)\n    do b <- is_not_div_by_zero ins;\n      returnM b\n  | LSH32_IMM\n  | RSH32_IMM\n  | ARSH32_IMM => (**r SHIFT_IMM *)\n    do b <- is_shift_range ins (Int.repr 32);\n      returnM b\n  | ADD32_IMM\n  | SUB32_IMM\n  | MUL32_IMM\n  | OR32_IMM\n  | AND32_IMM\n  | NEG32_IMM\n  | XOR32_IMM\n  | MOV32_IMM => (**r ALU_IMM *)\n    returnM true\n  | ALU32_IMM_ILLEGAL => returnM false\n  end.\n\nDefinition bpf_verifier_opcode_alu32_reg (op: nat) (ins: int64) : M state.state bool :=\n  match nat_to_opcode_alu32_reg op with\n  | DIV32_REG\n  | MOD32_REG\n  | LSH32_REG\n  | RSH32_REG\n  | ARSH32_REG\n  | ADD32_REG\n  | SUB32_REG\n  | MUL32_REG\n  | OR32_REG\n  | AND32_REG\n  | XOR32_REG\n  | MOV32_REG => (**r ALU_REG *)\n    do b <-  is_well_src ins;\n      returnM b\n  | ALU32_REG_ILLEGAL => returnM false\n  end.\n\nDefinition bpf_verifier_opcode_alu64_imm (op: nat) (ins: int64) : M state.state bool :=\n  match nat_to_opcode_alu64_imm op with\n  | DIV64_IMM\n  | MOD64_IMM => (**r DIV_IMM *)\n    do b <-  is_not_div_by_zero64 ins;\n      returnM b\n  | LSH64_IMM\n  | RSH64_IMM\n  | ARSH64_IMM => (**r SHIFT_IMM *)\n    do b <-  is_shift_range64 ins (Int.repr 64);\n      returnM b\n  | ADD64_IMM\n  | SUB64_IMM\n  | MUL64_IMM\n  | OR64_IMM\n  | AND64_IMM\n  | NEG64_IMM\n  | XOR64_IMM\n  | MOV64_IMM => (**r ALU_IMM *)\n    returnM true\n  | ALU64_IMM_ILLEGAL => returnM false\n  end.\n\nDefinition bpf_verifier_opcode_alu64_reg (op: nat) (ins: int64) : M state.state bool :=\n  match nat_to_opcode_alu64_reg op with\n  | DIV64_REG\n  | MOD64_REG\n  | LSH64_REG\n  | RSH64_REG\n  | ARSH64_REG\n  | ADD64_REG\n  | SUB64_REG\n  | MUL64_REG\n  | OR64_REG\n  | AND64_REG\n  | XOR64_REG\n  | MOV64_REG => (**r ALU_REG *)\n    do b <-  is_well_src ins;\n      returnM b\n  | ALU64_REG_ILLEGAL => returnM false\n  end.\n\nDefinition bpf_verifier_opcode_branch_imm (pc len op: nat) (ins: int64) : M state.state bool :=\n  match nat_to_opcode_branch_imm op with\n  | JA_IMM\n  | JEQ_IMM\n  | JGT_IMM\n  | JGE_IMM\n  | JLT_IMM\n  | JLE_IMM\n  | JSET_IMM\n  | JNE_IMM\n  | JSGT_IMM\n  | JSGE_IMM\n  | JSLT_IMM\n  | JSLE_IMM =>\n    do ofs <-  get_offset ins;\n    do b <-  is_well_jump pc len ofs;\n      returnM b\n  | CALL_IMM\n  | RET_IMM =>\n    do b <-  is_dst_R0 ins;\n      returnM b\n  | JMP_IMM_ILLEGAL_INS => returnM false\n  end.\n\nDefinition bpf_verifier_opcode_branch_reg (pc len op: nat) (ins: int64) : M state.state bool :=\n  match nat_to_opcode_branch_reg op with\n  | JEQ_REG\n  | JGT_REG\n  | JGE_REG\n  | JLT_REG\n  | JLE_REG\n  | JSET_REG\n  | JNE_REG\n  | JSGT_REG\n  | JSGE_REG\n  | JSLT_REG\n  | JSLE_REG =>\n    do ofs <-  get_offset ins;\n    do b0 <-  is_well_src ins;\n      if b0 then\n        do b   <-  is_well_jump pc len ofs;\n          returnM b\n      else\n          returnM false\n  | JMP_REG_ILLEGAL_INS => returnM false\n  end.\n\n\nDefinition bpf_verifier_opcode_load_imm (op: nat) (ins: int64) : M state.state bool :=\n  match nat_to_opcode_load_imm op with\n  | LDDW_low\n  | LDDW_high => returnM true\n  | LDX_IMM_ILLEGAL_INS => returnM false\n  end.\n\nDefinition bpf_verifier_opcode_load_reg (op: nat) (ins: int64) : M state.state bool :=\n  match nat_to_opcode_load_reg op with\n  | LDXW\n  | LDXH\n  | LDXB\n  | LDXDW  =>\n    do b <-  is_well_src ins;\n      returnM b\n  | LDX_REG_ILLEGAL_INS => returnM false\n  end.\n\nDefinition bpf_verifier_opcode_store_imm (op: nat) (ins: int64) : M state.state bool :=\n  match nat_to_opcode_store_imm op with\n  | STW\n  | STH\n  | STB\n  | STDW  => returnM true\n  | ST_ILLEGAL_INS => returnM false\n  end.\n\nDefinition bpf_verifier_opcode_store_reg (op: nat) (ins: int64) : M state.state bool :=\n  match nat_to_opcode_store_reg op with\n  | STXW\n  | STXH\n  | STXB\n  | STXDW  =>\n    do b <-  is_well_src ins;\n      returnM b\n  | STX_ILLEGAL_INS => returnM false\n  end.\n\nDefinition bpf_verifier_aux2 (pc len op: nat) (ins: int64) : M state.state bool :=\n  match nat_to_opcode op with\n  | ALU64  (**r 0xX7 / 0xXf *) =>\n    if Int.eq Int.zero (Int.and (Int.repr (Z.of_nat op)) (Int.repr 8)) then\n      do b <- bpf_verifier_opcode_alu64_imm op ins;\n        returnM b\n    else\n      do b <- bpf_verifier_opcode_alu64_reg op ins;\n        returnM b\n  | ALU32  (**r 0xX4 / 0xXc *) =>\n    if Int.eq Int.zero (Int.and (Int.repr (Z.of_nat op)) (Int.repr 8)) then\n      do b <- bpf_verifier_opcode_alu32_imm op ins;\n        returnM b\n    else\n      do b <- bpf_verifier_opcode_alu32_reg op ins;\n        returnM b\n  | Branch (**r 0xX5 / 0xXd *) =>\n    if Int.eq Int.zero (Int.and (Int.repr (Z.of_nat op)) (Int.repr 8)) then\n      do b <- bpf_verifier_opcode_branch_imm pc len op ins;\n        returnM b\n    else\n      do b <- bpf_verifier_opcode_branch_reg pc len op ins;\n        returnM b\n  | LD_IMM (**r 0xX8 *)        => do b <- bpf_verifier_opcode_load_imm op ins; returnM b\n  | LD_REG (**r 0xX1/0xX9 *)   => do b <- bpf_verifier_opcode_load_reg op ins; returnM b\n  | ST_IMM (**r 0xX2/0xXa *)   => do b <- bpf_verifier_opcode_store_imm op ins; returnM b\n  | ST_REG (**r 0xX3/0xXb *)   => do b <- bpf_verifier_opcode_store_reg op ins; returnM b\n  | ILLEGAL => returnM false\n  end.\n\nFixpoint bpf_verifier_aux (pc len: nat): M state.state bool := (**r pc: len-1, len-2, ... 0 *)\n    match pc with\n    | O => returnM true\n    | S n =>\n      do ins <-  eval_ins (Int.repr (Z.of_nat n)); (**r len-pc: 0, 1, 2, etc... len -1 *)\n      do b   <-  is_well_dst ins;\n        if b then\n          do op   <-  get_opcode ins;\n          do b    <-  bpf_verifier_aux2 n len op ins;\n            if b then\n              bpf_verifier_aux n len\n            else\n              returnM false\n        else\n          returnM false\n    end.\n\nDefinition bpf_verifier: M state.state bool :=\n  do len  <-  eval_ins_len;\n  (**r (0, Int.max_unsigned/8): at least one instruction, and at most Int.max_unsigned/8 because of memory region *)\n    if negb (Int.ltu (Int.repr (Z.of_nat len)) Int.one) then\n      if negb\n       (Int.ltu (Int.divu (Int.repr Int.max_unsigned) (Int.repr 8))\n          (Int.repr (Z.of_nat len))) then\n        do b <-  bpf_verifier_aux len len;\n          if b then\n            do ins64 <-  eval_ins (Int.repr (Z.of_nat (len - 1)));\n              returnM (Int64.eq ins64 (Int64.repr 0x95))\n          else\n            returnM false\n      else\n        returnM false\n    else\n      returnM false.\n\nClose Scope monad_scope.\nClose Scope nat_scope.", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/verifier/synthesismodel/verifier_synthesis.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819591324418, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.2066942545006923}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\n\nSet Implicit Arguments.\n\n\nSection SimulationThread.\n  Variable (lang_src lang_tgt:language).\n\n  Definition SIM_TERMINAL :=\n    forall (st_src:lang_src.(Language.state)) (st_tgt:lang_tgt.(Language.state)), Prop.\n\n  Definition SIM_THREAD :=\n    forall (sim_terminal: SIM_TERMINAL)\n      (st1_src:lang_src.(Language.state)) (lc1_src:Local.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n      (st1_tgt:lang_tgt.(Language.state)) (lc1_tgt:Local.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t), Prop.\n\n  Definition _sim_thread_step\n             (sim_thread: forall (st1_src:lang_src.(Language.state)) (lc1_src:Local.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n                            (st1_tgt:lang_tgt.(Language.state)) (lc1_tgt:Local.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t), Prop)\n             st1_src lc1_src sc1_src mem1_src\n             st1_tgt lc1_tgt sc1_tgt mem1_tgt\n    :=\n    forall pf_tgt e_tgt st3_tgt lc3_tgt sc3_tgt mem3_tgt\n      (STEP_TGT: Thread.step pf_tgt e_tgt\n                             (Thread.mk _ st1_tgt lc1_tgt sc1_tgt mem1_tgt)\n                             (Thread.mk _ st3_tgt lc3_tgt sc3_tgt mem3_tgt)),\n    exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n      <<STEPS: rtc (@Thread.tau_step _)\n                   (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                   (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n      <<STEP_SRC: Thread.opt_step e_src\n                                  (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                                  (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n      <<EVENT: ThreadEvent.get_event e_src = ThreadEvent.get_event e_tgt>> /\\\n      <<SC3: TimeMap.le sc3_src sc3_tgt>> /\\\n      <<MEMORY3: sim_memory mem3_src mem3_tgt>> /\\\n      <<SIM: sim_thread st3_src lc3_src sc3_src mem3_src st3_tgt lc3_tgt sc3_tgt mem3_tgt>>.\n\n  Definition _sim_thread\n             (sim_thread: SIM_THREAD)\n             (sim_terminal: SIM_TERMINAL)\n             (st1_src:lang_src.(Language.state)) (lc1_src:Local.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n             (st1_tgt:lang_tgt.(Language.state)) (lc1_tgt:Local.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t): Prop :=\n    forall sc1_src mem1_src\n      sc1_tgt mem1_tgt\n      (SC: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY: sim_memory mem1_src mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc0_src sc1_src)\n      (SC_FUTURE_TGT: TimeMap.le sc0_tgt sc1_tgt)\n      (MEM_FUTURE_SRC: Memory.future mem0_src mem1_src)\n      (MEM_FUTURE_TGT: Memory.future mem0_tgt mem1_tgt)\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed mem1_tgt),\n      <<TERMINAL:\n        forall (TERMINAL_TGT: lang_tgt.(Language.is_terminal) st1_tgt),\n        exists st2_src lc2_src sc2_src mem2_src,\n          <<STEPS: rtc (@Thread.tau_step _)\n                       (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                       (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n          <<SC: TimeMap.le sc2_src sc1_tgt>> /\\\n          <<MEMORY: sim_memory mem2_src mem1_tgt>> /\\\n          <<TERMINAL_SRC: lang_src.(Language.is_terminal) st2_src>> /\\\n          <<LOCAL: sim_local lc2_src lc1_tgt>> /\\\n          <<TERMINAL: sim_terminal st2_src st1_tgt>>>> /\\\n      <<FUTURE:\n        forall sc2_src mem2_src\n          (SC_FUTURE_SRC: TimeMap.le sc1_src sc2_src)\n          (MEM_FUTURE_SRC: Memory.future mem1_src mem2_src)\n          (WF_SRC: Local.wf lc1_src mem2_src)\n          (SC_SRC: Memory.closed_timemap sc2_src mem2_src)\n          (MEM_SRC: Memory.closed mem2_src),\n        exists sc2_tgt mem2_tgt,\n          <<SC: TimeMap.le sc2_src sc2_tgt>> /\\\n          <<MEMORY: sim_memory mem2_src mem2_tgt>> /\\\n          <<SC_FUTURE_TGT: TimeMap.le sc1_tgt sc2_tgt>> /\\\n          <<MEM_FUTURE_TGT: Memory.future mem1_tgt mem2_tgt>> /\\\n          <<WF_TGT: Local.wf lc1_tgt mem2_tgt>> /\\\n          <<SC_TGT: Memory.closed_timemap sc2_tgt mem2_tgt>> /\\\n          <<MEM_TGT: Memory.closed mem2_tgt>>>> /\\\n      <<PROMISES:\n        forall (PROMISES_TGT: lc1_tgt.(Local.promises) = Memory.bot),\n        exists st2_src lc2_src sc2_src mem2_src,\n          <<STEPS: rtc (@Thread.tau_step _)\n                       (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                       (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n          <<PROMISES_SRC: lc2_src.(Local.promises) = Memory.bot>>>> /\\\n      <<STEP: _sim_thread_step (sim_thread sim_terminal)\n                               st1_src lc1_src sc1_src mem1_src\n                               st1_tgt lc1_tgt sc1_tgt mem1_tgt>>.\n\n  Lemma _sim_thread_mon: monotone9 _sim_thread.\n  Proof.\n    ii. exploit IN; try apply SC; eauto. i. des.\n    splits; eauto. ii.\n    exploit STEP; eauto. i. des.\n    esplits; eauto.\n  Qed.\n  Hint Resolve _sim_thread_mon: paco.\n\n  Definition sim_thread: SIM_THREAD := paco9 _sim_thread bot9.\n\n  Lemma sim_thread_mon\n        sim_terminal1 sim_terminal2\n        (SIM: sim_terminal1 <2= sim_terminal2):\n    sim_thread sim_terminal1 <8= sim_thread sim_terminal2.\n  Proof.\n    pcofix CIH. i. punfold PR. pfold. ii.\n    exploit PR; try apply SC; eauto. i. des.\n    splits; auto.\n    - i. exploit TERMINAL; eauto. i. des.\n      esplits; eauto.\n    - ii. exploit STEP; eauto. i. des. inv SIM0; [|done].\n      esplits; eauto.\n  Qed.\nEnd SimulationThread.\nHint Resolve _sim_thread_mon: paco.\n\n\nLemma sim_thread_step\n      lang_src lang_tgt\n      sim_terminal\n      pf_tgt e_tgt\n      st1_src lc1_src sc1_src mem1_src\n      st1_tgt lc1_tgt sc1_tgt mem1_tgt\n      st3_tgt lc3_tgt sc3_tgt mem3_tgt\n      (STEP: @Thread.step lang_tgt pf_tgt e_tgt\n                          (Thread.mk _ st1_tgt lc1_tgt sc1_tgt mem1_tgt)\n                          (Thread.mk _ st3_tgt lc3_tgt sc3_tgt mem3_tgt))\n      (SC: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY: sim_memory mem1_src mem1_tgt)\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed mem1_tgt)\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src st1_tgt lc1_tgt sc1_tgt mem1_tgt):\n  exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<STEP: Thread.opt_step e_src\n                            (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                            (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n    <<EVENT: ThreadEvent.get_event e_src = ThreadEvent.get_event e_tgt>> /\\\n    <<SC: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEMORY: sim_memory mem3_src mem3_tgt>> /\\\n    <<WF_SRC: Local.wf lc3_src mem3_src>> /\\\n    <<WF_TGT: Local.wf lc3_tgt mem3_tgt>> /\\\n    <<SC_SRC: Memory.closed_timemap sc3_src mem3_src>> /\\\n    <<SC_TGT: Memory.closed_timemap sc3_tgt mem3_tgt>> /\\\n    <<MEM_SRC: Memory.closed mem3_src>> /\\\n    <<MEM_TGT: Memory.closed mem3_tgt>> /\\\n    <<SIM: sim_thread sim_terminal st3_src lc3_src sc3_src mem3_src st3_tgt lc3_tgt sc3_tgt mem3_tgt>>.\nProof.\n  punfold SIM. exploit SIM; eauto; try refl. i. des.\n  exploit Thread.step_future; eauto. s. i. des.\n  exploit STEP0; eauto. i. des. inv SIM0; [|done].\n  exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n  exploit Thread.opt_step_future; eauto. s. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_thread_opt_step\n      lang_src lang_tgt\n      sim_terminal\n      e_tgt\n      st1_src lc1_src sc1_src mem1_src\n      st1_tgt lc1_tgt sc1_tgt mem1_tgt\n      st3_tgt lc3_tgt sc3_tgt mem3_tgt\n      (STEP: @Thread.opt_step lang_tgt e_tgt\n                              (Thread.mk _ st1_tgt lc1_tgt sc1_tgt mem1_tgt)\n                              (Thread.mk _ st3_tgt lc3_tgt sc3_tgt mem3_tgt))\n      (SC: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY: sim_memory mem1_src mem1_tgt)\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed mem1_tgt)\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src st1_tgt lc1_tgt sc1_tgt mem1_tgt):\n  exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<STEP: Thread.opt_step e_src\n                            (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                            (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n    <<EVENT: ThreadEvent.get_event e_src = ThreadEvent.get_event e_tgt>> /\\\n    <<SC: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEMORY: sim_memory mem3_src mem3_tgt>> /\\\n    <<WF_SRC: Local.wf lc3_src mem3_src>> /\\\n    <<WF_TGT: Local.wf lc3_tgt mem3_tgt>> /\\\n    <<SC_SRC: Memory.closed_timemap sc3_src mem3_src>> /\\\n    <<SC_TGT: Memory.closed_timemap sc3_tgt mem3_tgt>> /\\\n    <<MEM_SRC: Memory.closed mem3_src>> /\\\n    <<MEM_TGT: Memory.closed mem3_tgt>> /\\\n    <<SIM: sim_thread sim_terminal st3_src lc3_src sc3_src mem3_src st3_tgt lc3_tgt sc3_tgt mem3_tgt>>.\nProof.\n  inv STEP.\n  - esplits; eauto. econs 1.\n  - eapply sim_thread_step; eauto.\nQed.\n\nLemma sim_thread_rtc_step\n      lang_src lang_tgt\n      sim_terminal\n      st1_src lc1_src sc1_src mem1_src\n      e1_tgt e2_tgt\n      (STEPS: rtc (@Thread.tau_step lang_tgt) e1_tgt e2_tgt)\n      (SC: TimeMap.le sc1_src e1_tgt.(Thread.sc))\n      (MEMORY: sim_memory mem1_src e1_tgt.(Thread.memory))\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf e1_tgt.(Thread.local) e1_tgt.(Thread.memory))\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap e1_tgt.(Thread.sc) e1_tgt.(Thread.memory))\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed e1_tgt.(Thread.memory))\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src e1_tgt.(Thread.state) e1_tgt.(Thread.local) e1_tgt.(Thread.sc) e1_tgt.(Thread.memory)):\n  exists st2_src lc2_src sc2_src mem2_src,\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<SC: TimeMap.le sc2_src e2_tgt.(Thread.sc)>> /\\\n    <<MEMORY: sim_memory mem2_src e2_tgt.(Thread.memory)>> /\\\n    <<WF_SRC: Local.wf lc2_src mem2_src>> /\\\n    <<WF_TGT: Local.wf e2_tgt.(Thread.local) e2_tgt.(Thread.memory)>> /\\\n    <<SC_SRC: Memory.closed_timemap sc2_src mem2_src>> /\\\n    <<SC_TGT: Memory.closed_timemap e2_tgt.(Thread.sc) e2_tgt.(Thread.memory)>> /\\\n    <<MEM_SRC: Memory.closed mem2_src>> /\\\n    <<MEM_TGT: Memory.closed e2_tgt.(Thread.memory)>> /\\\n    <<SIM: sim_thread sim_terminal st2_src lc2_src sc2_src mem2_src e2_tgt.(Thread.state) e2_tgt.(Thread.local) e2_tgt.(Thread.sc) e2_tgt.(Thread.memory)>>.\nProof.\n  revert SC MEMORY WF_SRC WF_TGT SC_SRC SC_TGT MEM_SRC MEM_TGT SIM.\n  revert st1_src lc1_src sc1_src mem1_src.\n  induction STEPS; i.\n  { esplits; eauto. }\n  inv H. inv TSTEP. destruct x, y. ss.\n  exploit sim_thread_step; eauto. i. des.\n  exploit IHSTEPS; eauto. i. des.\n  destruct z. ss.\n  esplits; try apply MEMORY1; eauto.\n  etrans; [eauto|]. etrans; [|eauto]. inv STEP0; eauto.\n  econs 2; eauto. econs.\n  - econs. eauto.\n  - etrans; eauto.\nQed.\n\nLemma sim_thread_future\n      lang_src lang_tgt\n      sim_terminal\n      st_src lc_src sc1_src sc2_src mem1_src mem2_src\n      st_tgt lc_tgt sc1_tgt sc2_tgt mem1_tgt mem2_tgt\n      (SIM: @sim_thread lang_src lang_tgt sim_terminal st_src lc_src sc1_src mem1_src st_tgt lc_tgt sc1_tgt mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc1_src sc2_src)\n      (SC_FUTURE_TGT: TimeMap.le sc1_tgt sc2_tgt)\n      (MEM_FUTURE_SRC: Memory.future mem1_src mem2_src)\n      (MEM_FUTURE_TGT: Memory.future mem1_tgt mem2_tgt):\n  sim_thread sim_terminal st_src lc_src sc2_src mem2_src st_tgt lc_tgt sc2_tgt mem2_tgt.\nProof.\n  pfold. ii.\n  punfold SIM. exploit SIM; (try by etrans; eauto); eauto.\nQed.\n\nLemma sim_thread_consistent\n      lang_src lang_tgt\n      sim_terminal\n      st_src lc_src sc_src mem_src\n      st_tgt lc_tgt sc_tgt mem_tgt\n      (SIM: sim_thread sim_terminal st_src lc_src sc_src mem_src st_tgt lc_tgt sc_tgt mem_tgt)\n      (SC: TimeMap.le sc_src sc_tgt)\n      (MEMORY: sim_memory mem_src mem_tgt)\n      (WF_SRC: Local.wf lc_src mem_src)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src mem_src)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src)\n      (MEM_TGT: Memory.closed mem_tgt)\n      (CONSISTENT: Thread.consistent (Thread.mk lang_tgt st_tgt lc_tgt sc_tgt mem_tgt)):\n  Thread.consistent (Thread.mk lang_src st_src lc_src sc_src mem_src).\nProof.\n  generalize SIM. intro X.\n  punfold X. exploit X; eauto; try refl. i. des.\n  ii. ss. exploit FUTURE; eauto. i. des.\n  exploit CONSISTENT; eauto; try refl. i. des.\n  exploit sim_thread_rtc_step; try apply MEMORY0; try apply SC0; eauto.\n  { s. eapply sim_thread_future; eauto. }\n  i. des. destruct e2. ss.\n  punfold SIM0. exploit SIM0; eauto; try refl. i. des.\n  exploit PROMISES1; eauto. i. des.\n  eexists (Thread.mk _ _ _ _ _). splits; [|eauto].\n  etrans; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-coq", "sha": "bff53239c51681ea653745cebf3b30ddd38f97ba", "save_path": "github-repos/coq/snu-sf-promising-coq", "path": "github-repos/coq/snu-sf-promising-coq/promising-coq-bff53239c51681ea653745cebf3b30ddd38f97ba/src/opt/SimThread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.32082130731838393, "lm_q1q2_score": 0.20668113648743577}}
{"text": "(****************************************************************************)\n(* Copyright 2020 The Project Oak Authors                                   *)\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\nRequire Import Coq.Arith.Arith Coq.Vectors.Vector\n     Coq.NArith.NArith.\nRequire Import Cava.Arrow.ArrowExport.\n\nRequire Import Aes.Pkg.\n\nImport VectorNotations.\nImport KappaNotation.\nOpen Scope kind_scope.\n\n(*\n\nverilog hex values were converted from OpenTitan verilog with vim:\n\n:%s/8'h/0x/g\n:%s/0x\\w*/\\=str2nr(submatch(0),16)/g\n:%s/,/::/g\n:%s/\\d\\+/#\\0/g\n\n*)\n\n(* module aes_sbox_lut (\n  input  aes_pkg::ciph_op_e op_i,\n  input  logic [7:0]        data_i,\n  output logic [7:0]        data_o\n); *)\nDefinition aes_sbox_lut\n  :  <<Bit, Vector Bit 8, Unit>> ~> (Vector Bit 8) :=\n  <[\\ op_i data_i =>\n  let SBOX_FWD = {\n    99, 124, 119, 123, 242, 107, 111, 197,\n    48, 1, 103, 43, 254, 215, 171, 118,\n\n    202, 130, 201, 125, 250, 89, 71, 240,\n    173, 212, 162, 175, 156, 164, 114, 192,\n\n    183, 253, 147, 38, 54, 63, 247, 204,\n    52, 165, 229, 241, 113, 216, 49, 21,\n\n    4, 199, 35, 195, 24, 150, 5, 154,\n    7, 18, 128, 226, 235, 39, 178, 117,\n\n    9, 131, 44, 26, 27, 110, 90, 160,\n    82, 59, 214, 179, 41, 227, 47, 132,\n\n    83, 209, 0, 237, 32, 252, 177, 91,\n    106, 203, 190, 57, 74, 76, 88, 207,\n\n    208, 239, 170, 251, 67, 77, 51, 133,\n    69, 249, 2, 127, 80, 60, 159, 168,\n\n    81, 163, 64, 143, 146, 157, 56, 245,\n    188, 182, 218, 33, 16, 255, 243, 210,\n\n    205, 12, 19, 236, 95, 151, 68, 23,\n    196, 167, 126, 61, 100, 93, 25, 115,\n\n    96, 129, 79, 220, 34, 42, 144, 136,\n    70, 238, 184, 20, 222, 94, 11, 219,\n\n    224, 50, 58, 10, 73, 6, 36, 92,\n    194, 211, 172, 98, 145, 149, 228, 121,\n\n    231, 200, 55, 109, 141, 213, 78, 169,\n    108, 86, 244, 234, 101, 122, 174, 8,\n\n    186, 120, 37, 46, 28, 166, 180, 198,\n    232, 221, 116, 31, 75, 189, 139, 138,\n\n    112, 62, 181, 102, 72, 3, 246, 14,\n    97, 53, 87, 185, 134, 193, 29, 158,\n\n    225, 248, 152, 17, 105, 217, 142, 148,\n    155, 30, 135, 233, 206, 85, 40, 223,\n\n    140, 161, 137, 13, 191, 230, 66, 104,\n    65, 153, 45, 15, 176, 84, 187, 22 }\n    in\n\n  let SBOX_INV = {\n    82, 9, 106, 213, 48, 54, 165, 56,\n    191, 64, 163, 158, 129, 243, 215, 251,\n\n    124, 227, 57, 130, 155, 47, 255, 135,\n    52, 142, 67, 68, 196, 222, 233, 203,\n\n    84, 123, 148, 50, 166, 194, 35, 61,\n    238, 76, 149, 11, 66, 250, 195, 78,\n\n    8, 46, 161, 102, 40, 217, 36, 178,\n    118, 91, 162, 73, 109, 139, 209, 37,\n\n    114, 248, 246, 100, 134, 104, 152, 22,\n    212, 164, 92, 204, 93, 101, 182, 146,\n\n    108, 112, 72, 80, 253, 237, 185, 218,\n    94, 21, 70, 87, 167, 141, 157, 132,\n\n    144, 216, 171, 0, 140, 188, 211, 10,\n    247, 228, 88, 5, 184, 179, 69, 6,\n\n    208, 44, 30, 143, 202, 63, 15, 2,\n    193, 175, 189, 3, 1, 19, 138, 107,\n\n    58, 145, 17, 65, 79, 103, 220, 234,\n    151, 242, 207, 206, 240, 180, 230, 115,\n\n    150, 172, 116, 34, 231, 173, 53, 133,\n    226, 249, 55, 232, 28, 117, 223, 110,\n\n    71, 241, 26, 113, 29, 41, 197, 137,\n    111, 183, 98, 14, 170, 24, 190, 27,\n\n    252, 86, 62, 75, 198, 210, 121, 32,\n    154, 219, 192, 254, 120, 205, 90, 244,\n\n    31, 221, 168, 51, 136, 7, 199, 49,\n    177, 18, 16, 89, 39, 128, 236, 95,\n\n    96, 81, 127, 169, 25, 181, 74, 13,\n    45, 229, 122, 159, 147, 201, 156, 239,\n\n    160, 224, 59, 77, 174, 42, 245, 176,\n    200, 235, 187, 60, 131, 83, 153, 97,\n\n    23, 43, 4, 126, 186, 119, 214, 38,\n    225, 105, 20, 99, 85, 33, 12, 125 }\n    in\n\n  if op_i == !CIPH_FWD\n  then SBOX_FWD[data_i]\n  else SBOX_INV[data_i]\n\n  ]>.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/investigations/Arrow/aes/SboxLut.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477015, "lm_q2_score": 0.3208212878370535, "lm_q1q2_score": 0.2066811327027661}}
{"text": "Require Import VST.floyd.proofauto.\n \n(*Require Import mmap0. needed for function and type names but not for compspecs *)\n\nGlobal Open Scope funspec_scope.\n\nSection Mmap0_ASI.\nVariable mmap0ID:ident.\nVariable munmapID:ident.\n\nDefinition mmap0_spec := \n   DECLARE (*_mmap0*)mmap0ID\n   WITH n:Z\n   PRE [(*_addr*) (tptr tvoid), \n        (*_len*) tuint, \n(*        (*_prot*) tint,\n        (*_flags*) tint,*)\n        (*_fildes*) tint(*,\n(*        (*_off*) tlong*) (*_off*) tint*)]\n     PROP (0 <= n <= Ptrofs.max_unsigned)\n     PARAMS (nullval; \n             Vptrofs (Ptrofs.repr n);\n(*             Vint (Int.repr 3); (* PROT_READ|PROT_WRITE *)\n             Vint (Int.repr 4098); (* MAP_PRIVATE|MAP_ANONYMOUS - platform-dependent *) *)\n             Vint (Int.repr (-1))(*;\n            Vlong (Int64.repr 0)Vint(Int.repr 0)*))\n     GLOBALS () SEP ()\n   POST [ tptr tvoid ] EX p:_, \n     PROP ( if eq_dec p nullval\n            then True else malloc_compatible n p )\n     LOCAL (temp ret_temp p)\n     SEP ( if eq_dec p nullval\n           then emp else memory_block Tsh n p).\n\nDefinition munmap_spec := \n   DECLARE (*_munmap*)munmapID\n   WITH p:val, n:Z\n   PRE [ (*_addr*) (tptr tvoid), \n         (*_len*) tuint ]\n     PROP (0 <= n <= Ptrofs.max_unsigned)\n     PARAMS (p; (Vptrofs (Ptrofs.repr n)) ) GLOBALS ()\n     SEP ( memory_block Tsh n p )\n   POST [ tint ] EX res: Z,\n     PROP ()\n     LOCAL (temp ret_temp (Vint (Int.repr res)))\n     SEP ( emp ).\n\nDefinition Mmap0_ASI:= [mmap0_spec; munmap_spec].\nEnd Mmap0_ASI.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/memmgr/ASI_mmap0.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.20651186016460837}}
{"text": "From Coq Require Import ssreflect ssrfun ssrbool.\n\nFrom Ltac2 Require Import Ltac2.\n\nFrom Coq Require Import Ensembles Bool String.\n\nFrom Coq.Logic Require Import FunctionalExtensionality Eqdep_dec.\nFrom Equations Require Import Equations.\n\nRequire Import Coq.Program.Tactics.\n\nFrom MatchingLogic Require Import Syntax DerivedOperators_Syntax ProofSystem IndexManipulation wftactics.\n\nFrom stdpp Require Import list tactics fin_sets coGset gmap sets.\n\nFrom MatchingLogic.Utils Require Import stdpp_ext.\nImport extralibrary.\nFrom MatchingLogic Require Import Logic\n  ProofInfo\n  BasicProofSystemLemmas\n.\nFrom MatchingLogic.ProofMode Require Import Basics\n                                            Propositional\n                                            Firstorder\n                                            FixPoint\n                                            Reshaper.\n\nImport MatchingLogic.Logic.Notations\n       MatchingLogic.ProofInfo.Notations.\n\nSet Default Proof Mode \"Classic\".\n\nOpen Scope ml_scope.\nOpen Scope string_scope.\nOpen Scope list_scope.\n\n\nLtac2 _callCompletedTransformedAndCast\n  (t : constr) (transform : constr) (tac : constr -> unit) :=\n  let tac' := (fun (t' : constr) =>\n    let tac'' := (fun (t'' : constr) =>\n      let tcast := open_constr:(@useGenericReasoning'' _ _ _ _ _ $t'') in\n      fillWithUnderscoresAndCall tac tcast []\n    ) in\n    fillWithUnderscoresAndCall (fun t''' => tac'' t''') transform [t']\n  ) in\n  fillWithUnderscoresAndCall tac' t []\n.\n\nLtac2 mlApplyMetaGeneralized (t : constr) :=\n  _callCompletedTransformedAndCast t constr:(@reshape_lhs_imp_to_and_forward) _mlApplyMetaRaw ;\n  try_solve_pile_basic ();\n  try_wfa ()\n.\n\nLtac _mlApplyMetaGeneralized t :=\n  _ensureProofMode;\n  let ff := ltac2:(t' |- mlApplyMetaGeneralized (Option.get (Ltac1.to_constr(t')))) in\n  ff t;\n  rewrite [foldr patt_and _ _]/=\n.\n\nTactic Notation \"mlApplyMeta\" constr(t) :=\n  (mlApplyMeta t) || (_mlApplyMetaGeneralized t)\n.\n\n#[local]\nExample ex_mlApplyMetaGeneralized  {Σ : Signature} Γ a b c d e f:\n  well_formed a ->\n  well_formed b ->\n  well_formed c ->\n  well_formed d ->\n  well_formed e ->\n  well_formed f ->\n  Γ ⊢ a ---> b ---> c ---> d ---> e ---> f ->\n  Γ ⊢ (a and (b and (c and (d and e)))) ---> f.\nProof.\n  intros wfa wfb wfc wfd wfe wff H.\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H1\".\n  mlApplyMeta H.\n  mlExact \"H1\".\nDefined.\n\nLemma foldr_andb_init_true i l:\n  foldr andb i l = true -> i = true.\nProof.\n  move: i.\n  induction l; cbn; intros i H.\n  { assumption. }\n  {\n    rewrite andb_true_iff in H.\n    destruct H as [H1 H2].\n    apply IHl.\n    exact H2.\n  }\nQed.\n\nLemma foldr_andb_true_iff i l:\n  foldr andb i l = i && foldr andb true l.\nProof.\n  move: i.\n  induction l; cbn; intros i.\n  {\n    rewrite andb_true_r. reflexivity.\n  }\n  {\n    rewrite IHl.\n    rewrite !andb_assoc.\n    rewrite [a && i]andb_comm.\n    reflexivity.\n  }\nQed.\n\n\nLemma MLGoal_weakenConclusionGen' {Σ : Signature} Γ l₁ l₂ name g' i\n    (x : Pattern) (xs : list Pattern)\n  :\n  forall (r : ImpReshapeS g' (x::xs)),\n  mkMLGoal Σ Γ (l₁ ++ (mkNH _ name ((untagPattern (irs_flattened _ _ r)))) :: l₂) ((foldr (patt_and) x xs)) i ->\n  mkMLGoal Σ Γ (l₁ ++ (mkNH _ name ((untagPattern (irs_flattened _ _ r)))) :: l₂) g' i.\nProof.\n  intros r H.\n  intros Hwf1 Hwf2. cbn in *.\n\n  assert (wfr : well_formed r).\n  {\n    clear H.\n    destruct r as [f pf].\n    rewrite pf.\n    rewrite pf in Hwf2.\n    rewrite 2!map_app in Hwf2.\n    rewrite foldr_app in Hwf2.\n    cbn in Hwf2.\n    apply foldr_andb_init_true in Hwf2.\n    wf_auto2.\n  }\n\n \n  assert (wffa: foldr andb true (map well_formed (map nh_patt (l₁ ++ (mkNH _ name r) :: l₂)))).\n  {\n    cbn.\n    destruct r as [f pf].\n    rewrite pf in Hwf2.\n    rewrite 2!map_app in Hwf2.\n    rewrite foldr_app in Hwf2.\n    rewrite 2!map_app.\n    rewrite foldr_app.\n    cbn in Hwf2. cbn.\n    rewrite foldr_andb_true_iff in Hwf2.\n    rewrite foldr_andb_true_iff.\n    wf_auto2.\n  }\n\n\n  assert (well_formed x).\n  {\n    rewrite irs_pf in Hwf2.\n    rewrite 2!map_app in Hwf2.\n    rewrite foldr_app in Hwf2.\n    rewrite foldr_andb_true_iff in Hwf2.\n    wf_auto2.\n  }\n\n  assert (Pattern.wf xs).\n  {\n    rewrite irs_pf in Hwf2.\n    rewrite 2!map_app in Hwf2.\n    rewrite foldr_app in Hwf2.\n    rewrite foldr_andb_true_iff in Hwf2.\n    wf_auto2.\n  }\n\n  feed specialize H.\n  {\n    cbn. wf_auto2.\n  }\n  { cbn. assumption. }\n  cbn in H.\n\n\n  assert (Hwfl₁ : wf (map nh_patt l₁) = true).\n  {\n    cbn.\n    destruct r as [f pf].\n    rewrite pf in Hwf2.\n    rewrite 2!map_app in Hwf2.\n    rewrite foldr_app in Hwf2.\n    rewrite foldr_andb_true_iff in Hwf2.\n    cbn in *.\n    rewrite map_app in H.\n    rewrite map_app in wffa.\n    wf_auto2.\n  }\n\n  assert (Hwfl₂ : wf (map nh_patt l₂) = true).\n  {\n    cbn.\n    destruct r as [f pf].\n    rewrite pf in Hwf2.\n    rewrite 2!map_app in Hwf2.\n    rewrite foldr_app in Hwf2.\n    rewrite foldr_andb_true_iff in Hwf2.\n    cbn in *.\n    rewrite map_app in H.\n    rewrite map_app in wffa.\n    wf_auto2.\n  }\n\n  rewrite map_app.\n  cbn. rewrite map_app in H. cbn in H.\n  rewrite irs_pf.\n\n  eapply prf_strenghten_premise_iter_meta_meta.\n  6: {\n    useBasicReasoning.\n    apply lhs_imp_to_and.\n    1-3: wf_auto2.\n  }\n  1-5: wf_auto2.\n\n  apply prf_weaken_conclusion_iter_under_implication_iter_meta.\n  1-4: wf_auto2.\n\n  eapply prf_strenghten_premise_iter_meta_meta.\n  6: {\n    useBasicReasoning.\n    apply lhs_and_to_imp.\n    1-3: wf_auto2.\n  }\n  1-5: wf_auto2.\n\n  rewrite irs_pf in H.\n  exact H.\nDefined.\n\nLemma MLGoal_weakenConclusionGen {Σ : Signature} Γ l₁ l₂ name g' i\n    (x : Pattern) (xs : list Pattern)\n  :\n  forall (r : ImpReshapeS g' (x::xs)),\n  mkMLGoal Σ Γ (l₁ ++ (mkNH _ name ((untagPattern (irs_flattened _ _ r)))) :: l₂)\n    (\n      match (rev xs) with\n      | [] => x\n      | yk::ys => (foldr (patt_and) yk (x::(rev ys)))\n      end\n    )\n    i ->\n  mkMLGoal Σ Γ (l₁ ++ (mkNH _ name ((untagPattern (irs_flattened _ _ r)))) :: l₂) g' i.\nProof.\n  intros r H.\n  apply MLGoal_weakenConclusionGen'.\n  intros wf1 wf2. cbn.\n\n  feed specialize H.\n  {\n    cbn. clear H.\n    destruct (rev xs) eqn:Heqxs.\n    {\n      wf_auto2.\n    }\n    {\n      apply (f_equal (@rev Pattern)) in Heqxs.\n      rewrite rev_involutive in Heqxs.\n      simpl in Heqxs.\n      subst xs.\n      wf_auto2.\n    }\n  }\n  {\n    cbn. clear H. cbn in *.\n    wf_auto2.\n  }\n  cbn in *.\n  destruct (rev xs) eqn:Heqxs.\n  {\n    apply (f_equal (@rev Pattern)) in Heqxs.\n    rewrite rev_involutive in Heqxs.\n    simpl in Heqxs.\n    subst xs.\n    cbn in *.\n    exact H.\n  }\n  {\n    apply (f_equal (@rev Pattern)) in Heqxs.\n    rewrite rev_involutive in Heqxs.\n    simpl in Heqxs.\n    subst xs.\n\n    eapply prf_weaken_conclusion_iter_meta_meta.\n    5: apply H.\n    4: {\n      rewrite foldr_app. cbn.\n      toMLGoal.\n      {\n        wf_auto2.\n      }\n      mlIntro \"H1\".\n      mlDestructAnd \"H1\" as \"Hx\" \"Hf\".\n      useBasicReasoning.\n      mlAdd (foldr_and_weaken_last Γ p (p and x) (rev l) ltac:(wf_auto2) ltac:(wf_auto2) ltac:(wf_auto2)) as \"Hw\".\n      mlAssert (\"Hw'\": (foldr patt_and p (rev l) ---> foldr patt_and (p and x) (rev l))).\n      { wf_auto2. }\n      {\n        mlApply \"Hw\".\n        mlIntro \"Hp\".\n        mlSplitAnd;[mlExact \"Hp\" | mlExact \"Hx\"].\n      }\n      mlClear \"Hw\".\n      mlApply \"Hw'\".\n      mlExact \"Hf\".\n    }\n    1,2,3: wf_auto2.\n  }\nDefined.\n\nTactic Notation \"_mlApplyBasic\" constr(name') :=\n  _ensureProofMode;\n  _mlReshapeHypsByName name';\n  apply MLGoal_weakenConclusion;\n  _mlReshapeHypsBack;\n  cbn.\n\n\nTactic Notation \"_mlApplyGen\" constr(name') :=\n  _ensureProofMode;\n  _mlReshapeHypsByName name';\n  apply MLGoal_weakenConclusionGen;\n  _mlReshapeHypsBack;\n  cbn.\n\n#[local]\nExample ex_mlApplyGeneralized  {Σ : Signature} Γ a b c d e f g:\n  well_formed a ->\n  well_formed b ->\n  well_formed c ->\n  well_formed d ->\n  well_formed e ->\n  well_formed f ->\n  well_formed g ->\n  Γ ⊢ ((a and (b and (c and (d and e)))) --->\n       (a ---> b ---> c ---> d ---> e ---> f) --->\n       (f ---> g) --->\n       g).\nProof.\n  intros wfa wfb wfc wfd wfe wff wfg.\n  toMLGoal.\n  { wf_auto2. }\n  mlIntro \"H1\".\n  mlIntro \"H2\".\n  mlIntro \"H3\".\n\n  _mlApplyGen \"H3\".\n  _mlApplyGen \"H2\".\n  mlExact \"H1\".\nDefined.\n\nTactic Notation \"mlApply\" constr(name') :=\n  (_mlApplyBasic name') || (_mlApplyGen name')\n.\n\nSection FOL_helpers.\n\n  Context {Σ : Signature}.\n\n  Lemma Framing_left (Γ : Theory) (ϕ₁ ϕ₂ ψ : Pattern) (i : ProofInfo)\n    (wfψ : well_formed ψ)\n    {pile : ProofInfoLe ((ExGen := ∅, SVSubst := ∅, KT := false, AKT := false)) i}\n    :\n    Γ ⊢i ϕ₁ ---> ϕ₂ using i ->\n    Γ ⊢i ϕ₁ $ ψ ---> ϕ₂ $ ψ using i.\n  Proof.\n    intros [pf Hpf].\n    unshelve (eexists).\n    {\n      apply ProofSystem.Framing_left.\n      { exact wfψ. }\n      exact pf.\n    }\n    {\n      destruct Hpf as [Hpf1 Hpf2 Hpf3 Hpf5].\n      constructor; simpl.\n      {\n        assumption.\n      }\n      {\n        assumption.\n      }\n      {\n        assumption.\n      }\n      {\n        assumption.\n      }\n    }\n  Defined.\n\n  Lemma Framing_right (Γ : Theory) (ϕ₁ ϕ₂ ψ : Pattern) (i : ProofInfo)\n    (wfψ : well_formed ψ)\n    {pile : ProofInfoLe ((ExGen := ∅, SVSubst := ∅, KT := false, AKT := false)) i}\n    :\n    Γ ⊢i ϕ₁ ---> ϕ₂ using i ->\n    Γ ⊢i ψ $ ϕ₁ ---> ψ $ ϕ₂ using i.\n  Proof.\n    intros [pf Hpf].\n    unshelve (eexists).\n    {\n      apply ProofSystem.Framing_right.\n      { exact wfψ. }\n      exact pf.\n    }\n    {\n      destruct Hpf as [Hpf1 Hpf2 Hpf3].\n      constructor; simpl.\n      {\n        assumption.\n      }\n      {\n        assumption.\n      }\n      {\n        assumption.\n      }\n      {\n        assumption.\n      }\n    }\n  Defined.\n\n  Lemma Prop_bott_left (Γ : Theory) (ϕ : Pattern) :\n    well_formed ϕ ->\n    Γ ⊢i ⊥ $ ϕ ---> ⊥ using BasicReasoning.\n  Proof.\n    intros wfϕ.\n    unshelve (eexists).\n    {\n      apply ProofSystem.Prop_bott_left. exact wfϕ.\n    }\n    {\n      abstract(solve_pim_simple).\n    }\n  Defined.\n\n  Lemma Prop_bott_right (Γ : Theory) (ϕ : Pattern) :\n    well_formed ϕ ->\n    Γ ⊢i ϕ $ ⊥ ---> ⊥ using BasicReasoning.\n  Proof.\n    intros wfϕ.\n    unshelve (eexists).\n    {\n      apply ProofSystem.Prop_bott_right. exact wfϕ.\n    }\n    {\n      abstract(solve_pim_simple).\n    }\n  Defined.\n\n  Arguments Prop_bott_left _ (_%ml) _ : clear implicits.\n  Arguments Prop_bott_right _ (_%ml) _ : clear implicits.\n\n  Lemma Prop_bot_ctx (Γ : Theory) (C : Application_context) :\n    Γ ⊢i ((subst_ctx C patt_bott) ---> patt_bott)\n    using (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false).\n  Proof.\n    induction C; simpl in *.\n    - apply useBasicReasoning.\n      apply bot_elim.\n      wf_auto2.\n    - eapply syllogism_meta.\n      5: { apply useBasicReasoning. apply (Prop_bott_left Γ p ltac:(wf_auto2)). }\n      4: { simpl. eapply useGenericReasoning.\n           2: eapply (Framing_left _ _ _ _ _ Prf).\n           1: apply pile_refl.\n           eapply useGenericReasoning.\n           2: apply IHC. try_solve_pile.\n      }\n      all: try solve [wf_auto2].\n       - eapply syllogism_meta.\n           5: { apply useBasicReasoning. apply (Prop_bott_right Γ p ltac:(wf_auto2)). }\n           4: { simpl. eapply useGenericReasoning.\n                2: eapply (Framing_right _ _ _ _ _ Prf).\n                1: apply pile_refl.\n                eapply useGenericReasoning.\n                2: apply IHC.\n                try_solve_pile.\n           }\n  Unshelve.\n    1-3: wf_auto2.\n    1-2: try_solve_pile.\n  Defined.\n\n  Lemma Framing (Γ : Theory) (C : Application_context) (A B : Pattern) (i : ProofInfo)\n    {pile : ProofInfoLe\n     ((ExGen := ∅, SVSubst := ∅, KT := false, AKT := false))\n     i\n    }\n    :\n    Γ ⊢i (A ---> B) using i ->\n    Γ ⊢i ((subst_ctx C A) ---> (subst_ctx C B)) using i.\n  Proof.\n    intros H.\n    pose proof H as [pf _].\n    pose proof (HWF := proved_impl_wf _ _ pf).\n    assert (wfA: well_formed A) by wf_auto2.\n    assert (wfB: well_formed B) by wf_auto2.\n    clear pf HWF.\n\n    move: wfA wfB H.\n    induction C; intros WFA WFB H; simpl in *.\n    - exact H.\n    - destruct i.\n      unshelve (eapply (Framing_left _ _ _ _ _ Prf)).\n      { \n        try_solve_pile.\n      }\n      apply IHC.\n      1-3: assumption.\n    - destruct i.\n      unshelve (eapply (Framing_right _ _ _ _ _ Prf)).\n      {\n        try_solve_pile.\n      }\n      apply IHC.\n      1-3: assumption.\n  Defined.\n\n  Lemma A_implies_not_not_A_ctx (Γ : Theory) (A : Pattern) (C : Application_context)\n    (i : ProofInfo) {pile : ProofInfoLe ((ExGen := ∅, SVSubst := ∅, KT := false, AKT := false)) i}\n    :\n    well_formed A ->\n    Γ ⊢i A using i ->\n    Γ ⊢i (! (subst_ctx C ( !A ))) using i.\n  Proof.\n    intros WFA H.\n\n    epose proof (ANNA := A_implies_not_not_A_alt Γ _ i _ H).\n    replace (! (! A)) with ((! A) ---> Bot) in ANNA by reflexivity.\n    epose proof (EF := Framing _ C (! A) Bot _ ANNA).\n    epose proof (PB := Prop_bot_ctx Γ C).\n    apply liftProofInfoLe with (i₂ := i) in PB. 2: try_solve_pile.\n    epose (TRANS := syllogism_meta _ _ _ EF PB).\n    apply TRANS.\n\n    Unshelve.\n    all: wf_auto2.\n    all: set_solver.\n  Defined.\n\n  Lemma ctx_bot_prop (Γ : Theory) (C : Application_context) (A : Pattern) \n    (i : ProofInfo)\n    {pile : ProofInfoLe ((ExGen := ∅, SVSubst := ∅, KT := false, AKT := false)) i}\n  :\n    well_formed A ->\n    Γ ⊢i (A ---> Bot) using i ->\n    Γ ⊢i (subst_ctx C A ---> Bot) using i.\n  Proof.\n    intros WFA H.\n    epose proof (FR := Framing Γ C A Bot _ H).\n    epose proof (BPR := Prop_bot_ctx Γ C).\n    apply liftProofInfoLe with (i₂ := i) in BPR. 2: try_solve_pile.\n    epose proof (TRANS := syllogism_meta _ _ _ FR BPR).\n    exact TRANS.\n    Unshelve.\n    all: wf_auto2.\n    all: set_solver.\n  Defined.\n\nEnd FOL_helpers.\n\nLemma prf_prop_bott_iff {Σ : Signature} Γ AC:\n  Γ ⊢i ((subst_ctx AC patt_bott) <---> patt_bott)\n  using (\n  (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false)).\nProof.\n  apply pf_iff_split.\n  1,2: wf_auto2.\n  1: apply ctx_bot_prop.\n  1: apply pile_refl.\n  1: wf_auto2.\n  {\n    useBasicReasoning.\n    apply A_impl_A.\n    reflexivity.\n  }\n  {\n    useBasicReasoning.\n    apply bot_elim.\n    wf_auto2.\n  }\nDefined.\n\nLemma Prop_disj_left {Σ : Signature} (Γ : Theory) (ϕ₁ ϕ₂ ψ : Pattern) :\n  well_formed ϕ₁ ->\n  well_formed ϕ₂ ->\n  well_formed ψ ->\n  Γ ⊢i (ϕ₁ or ϕ₂) $ ψ ---> (ϕ₁ $ ψ) or (ϕ₂ $ ψ) using BasicReasoning.\nProof.\n  intros wfϕ₁ wfϕ₂ wfψ.\n  unshelve (eexists).\n  {\n    apply Prop_disj_left; assumption.\n  }\n  {\n    abstract (solve_pim_simple).\n  }\nDefined.\n\nLemma Prop_disj_right {Σ : Signature} (Γ : Theory) (ϕ₁ ϕ₂ ψ : Pattern) :\n  well_formed ϕ₁ ->\n  well_formed ϕ₂ ->\n  well_formed ψ ->\n  Γ ⊢i ψ $ (ϕ₁ or ϕ₂)  ---> (ψ $ ϕ₁) or (ψ $ ϕ₂) using BasicReasoning.\nProof.\n  intros wfϕ₁ wfϕ₂ wfψ.\n  unshelve (eexists).\n  {\n    apply Prop_disj_right; assumption.\n  }\n  {\n    abstract (solve_pim_simple).\n  }\nDefined.\n\nLemma prf_prop_or_iff {Σ : Signature} Γ AC p q:\n  well_formed p ->\n  well_formed q ->\n  Γ ⊢i ((subst_ctx AC (p or q)) <---> ((subst_ctx AC p) or (subst_ctx AC q)))\n  using (\n  (ExGen := ∅, SVSubst := ∅, KT := false, AKT := false)).\nProof.\n  intros wfp wfq.\n  induction AC; simpl.\n  - useBasicReasoning. apply pf_iff_equiv_refl; wf_auto2.\n  - apply pf_iff_iff in IHAC; try_wfauto2.\n    destruct IHAC as [IH1 IH2].\n    remember_constraint as i.\n    apply pf_iff_split; try_wfauto2.\n    + pose proof (H := IH1).\n      apply useGenericReasoning with (i := i) in H.\n      2: { try_solve_pile. }\n      rewrite Heqi in H.\n      apply Framing_left with (ψ := p0)in H; auto.\n      2: { apply pile_refl. }\n      eapply syllogism_meta. 4: subst i; apply H.\n      all: try_wfauto2.\n      remember (subst_ctx AC p) as p'.\n      remember (subst_ctx AC q) as q'.\n      subst i.\n      eapply useGenericReasoning.\n      2: eapply Prop_disj_left. all: subst; try_wfauto2.\n      { try_solve_pile. }\n    + eapply prf_disj_elim_meta_meta; try_wfauto2.\n      * subst i. \n        apply Framing_left with (ψ := p0); auto.\n        { try_solve_pile. }\n        eapply prf_weaken_conclusion_meta_meta.\n        4: { gapply IH2. try_solve_pile. }\n        1-3: wf_auto2.\n        useBasicReasoning.\n        apply disj_left_intro; wf_auto2.\n      * subst i.\n        apply Framing_left with (ψ := p0); auto.\n        { try_solve_pile. }\n        eapply prf_weaken_conclusion_meta_meta. 4: gapply IH2; try_solve_pile. all: try_wfauto2.\n        useBasicReasoning.\n        apply disj_right_intro; wf_auto2.\n  - apply pf_iff_iff in IHAC; try_wfauto2.\n    destruct IHAC as [IH1 IH2].\n    remember_constraint as i.\n    apply pf_iff_split; try_wfauto2.\n    + pose proof (H := IH1).\n      apply useGenericReasoning with (i := i) in H.\n      2: { subst i. try_solve_pile. }\n      eapply Framing_right with (ψ := p0)in H; auto.\n      eapply syllogism_meta. 4: apply H.\n      all: try_wfauto2.\n      2: { subst i. try_solve_pile. }\n      remember (subst_ctx AC p) as p'.\n      remember (subst_ctx AC q) as q'.\n      subst i; apply useBasicReasoning.\n      apply Prop_disj_right. all: subst; try_wfauto2.\n    + eapply prf_disj_elim_meta_meta; try_wfauto2.\n      * subst i.\n        apply Framing_right with (ψ := p0); auto.\n        { try_solve_pile. }\n        eapply prf_weaken_conclusion_meta_meta.\n        4: gapply IH2; try_solve_pile. all: try_wfauto2.\n        useBasicReasoning.\n        apply disj_left_intro; wf_auto2.\n      * subst i.\n        apply Framing_right with (ψ := p0); auto.\n        { try_solve_pile. }\n        eapply prf_weaken_conclusion_meta_meta.\n        4: gapply IH2; try_solve_pile.\n        all: try_wfauto2.\n        useBasicReasoning.\n        apply disj_right_intro; wf_auto2.\nDefined.\n\n\n\n\nLemma Singleton_ctx {Σ : Signature} (Γ : Theory) (C1 C2 : Application_context) (ϕ : Pattern) (x : evar) :\n  well_formed ϕ ->\n  Γ ⊢i (! ((subst_ctx C1 (patt_free_evar x and ϕ)) and\n             (subst_ctx C2 (patt_free_evar x and (! ϕ)))))\n  using BasicReasoning.\nProof.\n  intros Hwf.\n  unshelve (eexists).\n  {\n    apply ProofSystem.Singleton_ctx. apply Hwf.\n  }\n  {\n    abstract (solve_pim_simple).\n  }\nDefined.\n\nLemma Existence {Σ : Signature} (Γ : Theory) :\n  Γ ⊢i (ex , patt_bound_evar 0) using BasicReasoning.\nProof.\n  unshelve (eexists).\n  {\n    apply ProofSystem.Existence.\n  }\n  {\n    abstract (solve_pim_simple).\n  }\nDefined.\n\nLemma Prop_ex_left {Σ : Signature} (Γ : Theory) (ϕ ψ : Pattern) :\n  well_formed (ex, ϕ) ->\n  well_formed ψ ->\n  Γ ⊢i (ex , ϕ) $ ψ ---> ex , ϕ $ ψ\n  using BasicReasoning.\nProof.\n  intros wfϕ wfψ.\n  unshelve (eexists).\n  {\n    apply ProofSystem.Prop_ex_left.\n    { exact wfϕ. }\n    { exact wfψ. }\n  }\n  { abstract(solve_pim_simple). }\nDefined.\n\nLemma Prop_ex_right {Σ : Signature} (Γ : Theory) (ϕ ψ : Pattern) :\n  well_formed (ex, ϕ) ->\n  well_formed ψ ->\n  Γ ⊢i ψ $ (ex , ϕ) ---> ex , ψ $ ϕ\n  using BasicReasoning.\nProof.\n  intros wfϕ wfψ.\n  unshelve (eexists).\n  {\n    apply ProofSystem.Prop_ex_right.\n    { exact wfϕ. }\n    { exact wfψ. }\n  }\n  { abstract(solve_pim_simple). }\nDefined.\n\n\nTactic Notation \"change\" \"constraint\" \"in\" ident(H) :=\n  let i := fresh \"i\" in\n  remember_constraint as i;\n  eapply useGenericReasoning with (i := i) in H;\n  subst i;\n  [|(try_solve_pile)].\n \n\nLemma prf_prop_ex_iff {Σ : Signature} Γ AC p x:\n  evar_is_fresh_in x (subst_ctx AC p) ->\n  well_formed (patt_exists p) = true ->\n  Γ ⊢i ((subst_ctx AC (patt_exists p)) <---> (exists_quantify x (subst_ctx AC (p^{evar: 0 ↦ x}))))\n  using (\n  {| pi_generalized_evars := {[x]};\n     pi_substituted_svars := ∅;\n     pi_uses_kt := false ;\n     pi_uses_advanced_kt := false ;\n  |}).\nProof.\n  intros Hx Hwf.\n\n  induction AC; simpl.\n  - simpl in Hx.\n    unfold exists_quantify.\n    erewrite evar_quantify_evar_open; auto. 2: now do 2 apply andb_true_iff in Hwf as [_ Hwf].\n    useBasicReasoning.\n    apply pf_iff_equiv_refl. exact Hwf.\n  -\n    assert (Hwfex: well_formed (ex , subst_ctx AC p)).\n    { unfold well_formed. simpl.\n      pose proof (Hwf' := Hwf).\n      unfold well_formed in Hwf. simpl in Hwf.\n      apply andb_prop in Hwf. destruct Hwf as [Hwfp Hwfc].\n      apply (wp_sctx AC p) in Hwfp. rewrite Hwfp. simpl. clear Hwfp.\n      unfold well_formed_closed. unfold well_formed_closed in Hwfc. simpl in Hwfc. simpl.\n      split_and!.\n      + apply wcmu_sctx. destruct_and!. assumption.\n      + apply wcex_sctx. destruct_and!. assumption.\n    }\n\n    assert(Hxfr1: evar_is_fresh_in x (subst_ctx AC p)).\n    { simpl in Hx.\n      eapply evar_is_fresh_in_richer.\n      2: { apply Hx. }\n      solve_free_evars_inclusion 5.\n    }\n\n    simpl in Hx.\n    pose proof (Hxfr1' := Hxfr1).\n    rewrite -> evar_is_fresh_in_subst_ctx in Hxfr1'.\n    destruct Hxfr1' as [Hxfrp HxAC].\n\n    assert(Hwf': well_formed (exists_quantify x (subst_ctx AC (p^{evar: 0 ↦ x})))).\n    {\n      unfold exists_quantify.\n      clear -HxAC Hwf.\n      apply wf_ex_eq_sctx_eo.\n      apply Hwf.\n    }\n\n    assert (Hwfeo: well_formed (p^{evar: 0 ↦ x})).\n    { wf_auto2. }\n\n\n    (* TODO automate this. The problem is that [well_formed_app] and others do not have [= true];\n       that is why [auto] does not work. But [auto] is not suitable for this anyway.\n       A better way would be to create some `simpl_well_formed` tuple, that might use the type class\n       mechanism for extension...\n     *)\n    assert(Hwf'p0: well_formed (exists_quantify x (subst_ctx AC (p^{evar: 0 ↦ x}) $ p0))).\n    { wf_auto2. }\n\n    apply pf_iff_iff in IHAC; auto.\n\n    destruct IHAC as [IH1 IH2].\n    apply pf_iff_split; auto.\n    + pose proof (H := IH1).\n      change constraint in IH1.\n      apply Framing_left with (ψ := p0) in IH1; auto.\n      2: { try_solve_pile. }\n\n      eapply syllogism_meta. 4: apply IH1.\n      1-3: wf_auto2.\n\n      remember (subst_ctx AC (p^{evar: 0 ↦ x})) as p'.\n      unfold exists_quantify.\n      simpl. rewrite [p0^{{evar: x ↦ 0}}]evar_quantify_fresh.\n      { eapply evar_is_fresh_in_app_r. apply Hx. }\n      useBasicReasoning.\n      apply Prop_ex_left. wf_auto2. wf_auto2.\n    + clear IH1.\n\n      change constraint in IH2.\n      apply Framing_left with (ψ := p0) in IH2; auto.\n      2: { try_solve_pile. }\n      eapply syllogism_meta. 5: eapply IH2.\n      1-3: wf_auto2.\n\n      apply Ex_gen; auto.\n      { try_solve_pile. }\n      1: {\n        unfold exists_quantify.\n        simpl.\n        rewrite free_evars_evar_quantify.\n        unfold evar_is_fresh_in in Hx. simpl in Hx. clear -Hx.\n        set_solver.\n      }\n\n      (* TODO have some nice implicit parameters *)\n      gapply (Framing_left _ _ _ _ _ Prf).\n      apply pile_refl.\n      Unshelve. 2: { try_solve_pile. }\n      unfold evar_open.\n      rewrite subst_ctx_bevar_subst.\n      unfold exists_quantify. simpl.\n      fold ((subst_ctx AC p)^{evar: 0 ↦ x}).\n      rewrite -> evar_quantify_evar_open; auto.\n      2: now do 2 apply andb_true_iff in Hwfex as [_ Hwfex].\n      useBasicReasoning.\n      apply Ex_quan; auto.\n  -\n    assert (Hwfex: well_formed (ex , subst_ctx AC p)).\n    { clear Hx. wf_auto2. }\n\n    assert(Hxfr1: evar_is_fresh_in x (subst_ctx AC p)).\n    { simpl in Hx.\n      eapply evar_is_fresh_in_richer.\n      2: { apply Hx. }\n      solve_free_evars_inclusion 5.\n    }\n\n    simpl in Hx.\n    pose proof (Hxfr1' := Hxfr1).\n    rewrite -> evar_is_fresh_in_subst_ctx in Hxfr1'.\n    destruct Hxfr1' as [Hxfrp HxAC].\n\n    assert(Hwf': well_formed (exists_quantify x (subst_ctx AC (p^{evar: 0 ↦ x})))).\n    {\n      unfold exists_quantify.\n      clear -HxAC Hwf.\n      apply wf_ex_eq_sctx_eo.\n      apply Hwf.\n    }\n\n    assert (Hwfeo: well_formed (p^{evar: 0 ↦ x})).\n    {\n      wf_auto2.\n    }\n\n    (* TODO automate this. The problem is that [well_formed_app] and others do not have [= true];\n       that is why [auto] does not work. But [auto] is not suitable for this anyway.\n       A better way would be to create some `simpl_well_formed` tuple, that might use the type class\n       mechanism for extension...\n     *)\n    assert(Hwf'p0: well_formed (exists_quantify x (p0 $ subst_ctx AC (p^{evar: 0 ↦ x})))).\n    {\n      wf_auto2.\n    }\n\n    apply pf_iff_iff in IHAC; auto.\n\n    destruct IHAC as [IH1 IH2].\n    apply pf_iff_split; auto.\n    + pose proof (H := IH1).\n      change constraint in IH1.\n      apply Framing_right with (ψ := p0) in IH1; auto.\n      2: try_solve_pile.\n      eapply syllogism_meta. 4: apply IH1.\n      1-3: wf_auto2.\n      remember (subst_ctx AC (p^{evar: 0 ↦ x})) as p'.\n      unfold exists_quantify.\n      simpl. rewrite [p0^{{evar: x ↦ 0}}]evar_quantify_fresh.\n      { eapply evar_is_fresh_in_app_l. apply Hx. }\n      useBasicReasoning.\n      apply Prop_ex_right. wf_auto2. wf_auto2.\n    + clear IH1.\n\n      change constraint in IH2.\n      eapply (Framing_right _ _ _ _ _ Prf) in IH2.\n      eapply syllogism_meta. 5: eapply IH2.\n      1-3: wf_auto2.\n      Unshelve.\n      2: { try_solve_pile. }\n\n      apply Ex_gen; auto.\n      { try_solve_pile. }\n      1: {\n        unfold exists_quantify.\n        simpl.\n        rewrite free_evars_evar_quantify.\n        unfold evar_is_fresh_in in Hx. simpl in Hx. clear -Hx.\n        set_solver.\n      }\n\n      eapply (Framing_right _ _ _ _ _ Prf). Unshelve.\n      2: { try_solve_pile. }\n      {\n      unfold evar_open.\n      rewrite subst_ctx_bevar_subst.\n      unfold exists_quantify. simpl.\n      fold ((subst_ctx AC p)^{evar: 0 ↦ x}).\n      erewrite evar_quantify_evar_open; auto.\n      2: now do 2 apply andb_true_iff in Hwfex as [_ Hwfex].\n      useBasicReasoning.\n      apply Ex_quan; auto.\n      }\nDefined.\n\n\nAdd Search Blacklist \"_elim\".\nAdd Search Blacklist \"_graph_rect\".\nAdd Search Blacklist \"_graph_mut\".\nAdd Search Blacklist \"FunctionalElimination_\".\n\n\nSection FOL_helpers.\n\n  Context {Σ : Signature}.\n\n  (**\n  NOTE: DO NOT REPLACE! The element variable in this function is \n  needed to substitute in such pattern context, which contain\n  arbitrary patterns, but the path to the element variable\n  is concrete. For example, in `⌈ E ⌉ $ φ` the path to `E` does\n  not contain any ∃-s, thus no new variables need to be generated\n  for `mlRewrite`.\n  *)\n  Fixpoint maximal_exists_depth_to (depth : nat) (E : evar) (ψ : Pattern) : nat :=\n    match ψ with\n    | patt_bott => 0\n    | patt_sym _ => 0\n    | patt_bound_evar _ => 0\n    | patt_bound_svar _ => 0\n    | patt_free_svar _ => 0\n    | patt_free_evar E' =>\n      match (decide (E' = E)) with\n      | left _ => depth\n      | right _ => 0\n      end\n    | patt_imp ψ₁ ψ₂\n      => Nat.max\n        (maximal_exists_depth_to depth E ψ₁)\n        (maximal_exists_depth_to depth E ψ₂)\n    | patt_app ψ₁ ψ₂\n      => Nat.max\n        (maximal_exists_depth_to depth E ψ₁)\n        (maximal_exists_depth_to depth E ψ₂)\n    | patt_exists ψ' => maximal_exists_depth_to (S depth) E ψ'\n    | patt_mu ψ' => maximal_exists_depth_to depth E ψ'\n    end.\n  \n  Lemma maximal_exists_depth_to_0 E ψ depth:\n    E ∉ free_evars ψ ->\n    maximal_exists_depth_to depth E ψ = 0.\n  Proof.\n    intros Hnotin.\n    move: E depth Hnotin.\n    induction ψ; intros E depth Hnotin; simpl in *; try reflexivity.\n    { case_match. set_solver. reflexivity. }\n    { rewrite IHψ1. set_solver. rewrite IHψ2. set_solver. reflexivity. }\n    { rewrite IHψ1. set_solver. rewrite IHψ2. set_solver. reflexivity. }\n    { rewrite IHψ. exact Hnotin. reflexivity. }\n    { rewrite IHψ. exact Hnotin. reflexivity. }\n  Qed.\n\n  Lemma maximal_exists_depth_to_S E ψ depth:\n    E ∈ free_evars ψ ->\n    maximal_exists_depth_to (S depth) E ψ\n    = S (maximal_exists_depth_to depth E ψ).\n  Proof.\n    intros Hin.\n    move: E depth Hin.\n    induction ψ; intros E depth Hin; simpl in *; try set_solver.\n    { case_match. reflexivity. set_solver. }\n    {\n      destruct (decide (E ∈ free_evars ψ1)),(decide (E ∈ free_evars ψ2)).\n      {\n        rewrite IHψ1. assumption. rewrite IHψ2. assumption. simpl. reflexivity.\n      }\n      {\n        rewrite IHψ1. assumption.\n        apply maximal_exists_depth_to_0 with (depth := S depth) in n\n          as n'.\n        apply maximal_exists_depth_to_0 with (depth := depth) in n.\n        rewrite n. lia. \n      }\n      {\n        rewrite IHψ2. assumption.\n        apply maximal_exists_depth_to_0 with (depth := S depth) in n\n          as n'.\n        apply maximal_exists_depth_to_0 with (depth := depth) in n.\n        rewrite n. lia. \n      }\n      {\n        exfalso. set_solver.\n      }\n    }\n    {\n      destruct (decide (E ∈ free_evars ψ1)),(decide (E ∈ free_evars ψ2)).\n      {\n        rewrite IHψ1. assumption. rewrite IHψ2. assumption. simpl. reflexivity.\n      }\n      {\n        rewrite IHψ1. assumption.\n        apply maximal_exists_depth_to_0 with (depth := S depth) in n\n          as n'.\n        apply maximal_exists_depth_to_0 with (depth := depth) in n.\n        rewrite n. lia. \n      }\n      {\n        rewrite IHψ2. assumption.\n        apply maximal_exists_depth_to_0 with (depth := S depth) in n\n          as n'.\n        apply maximal_exists_depth_to_0 with (depth := depth) in n.\n        rewrite n. lia. \n      }\n      {\n        exfalso. set_solver.\n      }\n    }\n  Qed.\n\n  Lemma evar_open_exists_depth φ depth x e : forall dbi,\n    x <> e ->\n    maximal_exists_depth_to depth x φ^{evar: dbi ↦ e} = maximal_exists_depth_to depth x φ.\n  Proof.\n    move: depth.\n    induction φ; intros depth HeNq; cbn; trivial; intro.\n    case_match; auto. cbn. case_match. congruence. lia.\n    1-2: rewrite IHφ1; auto; rewrite IHφ2; auto.\n    rewrite IHφ; auto.\n    rewrite IHφ; auto.\n  Qed.\n\n  Lemma svar_open_exists_depth φ depth x X : forall dbi,\n    maximal_exists_depth_to depth x φ^{svar: dbi ↦ X} = maximal_exists_depth_to depth x φ.\n  Proof.\n    move: depth.\n    induction φ; intro depth; cbn; trivial; intro.\n    case_match; auto.\n    1-2: now rewrite IHφ1; rewrite IHφ2.\n    now rewrite IHφ.\n    now rewrite IHφ.\n  Qed.\n\n  Lemma svar_fresh_seq_max (SvS : SVarSet) (n1 n2 : nat) :\n    (@list_to_set svar SVarSet _ _ _ (svar_fresh_seq SvS n1)) ⊆ (list_to_set (svar_fresh_seq SvS (n1 `max` n2))).\n  Proof.\n    move: SvS n2.\n    induction n1; intros SvS n2.\n    {\n      simpl. set_solver.\n    }\n    {\n      simpl.\n      destruct n2.\n      {\n        simpl. set_solver.\n      }\n      {\n        simpl.\n        cut (@list_to_set svar SVarSet _ _ _ (svar_fresh_seq ({[svar_fresh_s SvS]} ∪ SvS) n1)\n        ⊆ list_to_set (svar_fresh_seq ({[svar_fresh_s SvS]} ∪ SvS) (n1 `max` n2))).\n        {\n          set_solver.\n        }\n        specialize (IHn1 ({[svar_fresh_s SvS]} ∪ SvS) n2).\n        apply IHn1.\n      }\n    }\n  Qed.\n\n  (** Note: we cannot reuse NoDup, until the proof system is \n      formalised as `... -> Set`. *)\n  Fixpoint no_dups {A : Set} {eqdec : EqDecision A} (l : list A) :=\n    match l with\n    | [] => True\n    | x::xs => x ∉ xs /\\ no_dups xs\n    end.\n\n  Class fresh_evars (l : list evar) (s : EVarSet) :=\n  {\n    evar_duplicates : no_dups l;\n    all_evars_fresh : forall x, x ∈ l -> x ∉ s;\n  }.\n\n  Lemma fresh_evars_bigger {el s} s' :\n    fresh_evars el s -> s' ⊆ s -> fresh_evars el s'.\n  Proof. intros H H0. constructor; destruct H. auto. intros. set_solver. Qed.\n\n  Lemma less_fresh_evars {x el s} :\n    fresh_evars (x::el) s -> fresh_evars el s.\n  Proof.\n    intros H. constructor; destruct H.\n    simpl in *. apply evar_duplicates0.\n    intros. apply all_evars_fresh0. now constructor 2.\n  Qed.\n\n  Class fresh_svars (l : list svar) (s : SVarSet) :=\n  {\n    svar_duplicates : no_dups l;\n    all_svars_fresh : forall X, X ∈ l -> X ∉ s;\n  }.\n\n  Lemma fresh_svars_bigger {sl s} s' :\n    fresh_svars sl s -> s' ⊆ s -> fresh_svars sl s'.\n  Proof. intros H H0. constructor; destruct H. auto. intros. set_solver. Qed.\n\n  Lemma less_fresh_svars {X sl s} :\n    fresh_evars (X::sl) s -> fresh_evars sl s.\n  Proof.\n    intros H. constructor; destruct H.\n    simpl in *. apply evar_duplicates0.\n    intros. apply all_evars_fresh0. now constructor 2.\n  Qed.\n\n  Lemma congruence_ex Γ E ψ x p q gpi kt evs svs\n    (HxneqE : x ≠ E)\n    (wfψ : well_formed (ex , ψ))\n    (wfp : well_formed p)\n    (wfq : well_formed q)\n    (Heqx : x ∉ free_evars ψ ∪ free_evars p ∪ free_evars q)\n    (Heqx2 : x ∈ evs)\n    (pile: ProofInfoLe (ExGen := evs, SVSubst := svs, KT := kt, AKT := false) gpi)\n    (IH: Γ ⊢i ψ^{evar: 0 ↦ x}^[[evar: E ↦ p]] <---> ψ^{evar: 0 ↦ x}^[[evar: E ↦ q]]\n       using  gpi) :\n    (Γ ⊢i (ex , ψ^[[evar: E ↦ p]]) <---> (ex , ψ^[[evar: E ↦ q]]) using  gpi).\n  Proof.\n    rewrite -evar_open_free_evar_subst_swap in IH; auto.\n    rewrite -evar_open_free_evar_subst_swap in IH; auto.\n    unshelve (epose proof (IH1 := pf_iff_proj1 Γ _ _ _ _ _ IH)).\n    { abstract (wf_auto2). }\n    { abstract (wf_auto2). }\n    unshelve (epose proof (IH2 := pf_iff_proj2 Γ _ _ _ _ _ IH)).\n    { abstract (wf_auto2). }\n    { abstract (wf_auto2). }\n\n    (* TODO: remove the well-formedness constraints on this lemma*)\n    apply pf_iff_split.\n    { abstract (wf_auto2). }\n    { abstract (wf_auto2). }\n    {\n      eapply strip_exists_quantify_l.\n      3: {\n        apply Ex_gen.\n        3: {\n          eapply syllogism_meta.\n          5: {\n            useBasicReasoning.\n            apply Ex_quan.\n            abstract (wf_auto2).\n          }\n          4: {\n              apply IH1.\n            }\n          { abstract (wf_auto2). }\n          { abstract (simpl; wf_auto2; apply wfc_ex_aux_bevar_subst; wf_auto2). }\n          { abstract (wf_auto2). }\n        }\n        {\n          abstract (\n            eapply pile_trans;\n            [|apply pile];\n            split; simpl; [|split; auto; set_solver];\n            set_solver\n          ).\n        }\n        {\n          abstract (\n            pose proof (Htmp2 := free_evars_free_evar_subst ψ q E);\n            set_solver\n          ).\n        }\n      }\n      {\n        abstract (\n          pose proof (Htmp2 := free_evars_free_evar_subst ψ p E);\n          set_solver\n        ).\n      }\n      {\n        wf_auto2.\n      }\n    }\n    (* this block is a symmetric version of the previous block*)\n    {\n      eapply strip_exists_quantify_l.\n      3: {\n        apply Ex_gen.\n        3: {\n          eapply syllogism_meta.\n          5: {\n            useBasicReasoning.\n            apply Ex_quan.\n            abstract (wf_auto2).\n          }\n          4: {\n              apply IH2.\n            }\n          { abstract (wf_auto2). }\n          { abstract (simpl; wf_auto2; apply wfc_ex_aux_bevar_subst; wf_auto2). }\n          { abstract (wf_auto2). }\n        }\n        {\n          abstract (\n            eapply pile_trans;\n            [|apply pile];\n            split; simpl; [|split; auto; set_solver];\n            set_solver\n          ).\n        }\n        {\n          abstract (\n            pose proof (Htmp2 := free_evars_free_evar_subst ψ p E);\n            set_solver\n          ).\n        }\n      }\n      {\n        abstract (\n          pose proof (Htmp2 := free_evars_free_evar_subst ψ q E);\n          set_solver\n        ).\n      }\n      {\n        abstract (wf_auto2).\n      }\n    }\n  Defined.\n\nEnd FOL_helpers.\n\n  Ltac pi_exact H := \n    lazymatch type of H with\n    | ?H' =>\n      lazymatch goal with\n      | [|- ?g] =>\n        (cut (H' = g);\n        [(let H0 := fresh \"H0\" in intros H0; rewrite -H0; exact H)|\n         (repeat f_equal; try reflexivity; try apply proof_irrel)])\n      end\n    end.\n\n  Ltac pi_assumption :=\n    match goal with\n    | [H : _ |- _] => pi_exact H\n    end.\n\n  Ltac pi_set_solver := set_solver by (try pi_assumption).\n\nSection FOL_helpers.\n\n  Context {Σ : Signature}.\n\n  Lemma congruence_app Γ ψ1 ψ2 p q E i\n    (wfψ1: well_formed ψ1)\n    (wfψ2: well_formed ψ2)\n    (wfp: well_formed p)\n    (wfq: well_formed q)\n    (pf₁: Γ ⊢i ψ1^[[evar: E ↦ p]] <---> ψ1^[[evar: E ↦ q]] using i)\n    (pf₂: Γ ⊢i ψ2^[[evar: E ↦ p]] <---> ψ2^[[evar: E ↦ q]] using i)\n    :\n    (Γ ⊢i (ψ1^[[evar: E ↦ p]]) $ (ψ2^[[evar: E ↦ p]]) <---> (ψ1^[[evar: E ↦ q]]) $ (ψ2^[[evar: E ↦ q]]) using i).\n  Proof.\n    remember (well_formed_free_evar_subst_0 E _ _ wfp wfψ1) as Hwf1.\n    remember (well_formed_free_evar_subst_0 E _ _ wfq wfψ1) as Hwf2.\n    remember (well_formed_free_evar_subst_0 E _ _ wfp wfψ2) as Hwf3.\n    remember (well_formed_free_evar_subst_0 E _ _ wfq wfψ2) as Hwf4.\n\n    eapply pf_iff_equiv_trans.\n    5: { \n      apply conj_intro_meta.\n      4: {\n        eapply Framing_right with (ψ := ψ1^[[evar: E ↦ q]]); auto.\n        1: { try_solve_pile. }\n        {\n          eapply pf_conj_elim_r_meta in pf₂.\n          apply pf₂.\n          { abstract (wf_auto2). }\n          { abstract (wf_auto2). }\n        }\n      }\n      3: {\n        eapply Framing_right with (ψ := ψ1^[[evar: E ↦ q]]); auto.\n        1: { try_solve_pile. }\n        {\n          eapply pf_conj_elim_l_meta in pf₂.\n          apply pf₂.\n          { abstract (wf_auto2). }\n          { abstract (wf_auto2). }\n        }\n      }\n      {\n        abstract (wf_auto2).\n      }\n      {\n        abstract (wf_auto2).\n      }\n    }\n    4: {\n      apply conj_intro_meta.\n      4: {\n        apply Framing_left with (ψ := ψ2^[[evar: E ↦ p]]); auto.\n        { try_solve_pile. }\n        {\n          eapply pf_conj_elim_r_meta in pf₁.\n          apply pf₁.\n          { abstract (wf_auto2). }\n          { abstract (wf_auto2). }\n        }\n      }\n      3: {\n        apply Framing_left with (ψ := ψ2^[[evar: E ↦ p]]); auto.\n        { try_solve_pile. }\n        {\n          eapply pf_conj_elim_l_meta in pf₁.\n          apply pf₁.\n          { abstract (wf_auto2). }\n          { abstract (wf_auto2). }\n        }\n      }\n      {\n        abstract (wf_auto2).\n      }\n      {\n        abstract (wf_auto2).\n      }\n    }\n    { abstract (wf_auto2). }\n    { abstract (wf_auto2). }\n    { abstract (wf_auto2). }\n  Defined.\n\n  Lemma count_evar_occurrences_evar_replace φ x y :\n    x ∉ free_evars φ ->\n    count_evar_occurrences x φ^[[evar:y↦patt_free_evar x]] =\n    count_evar_occurrences y φ.\n  Proof.\n    induction φ; intro H; simpl in *; auto.\n    * do 2 destruct decide; simpl; case_match; auto; try contradiction; set_solver.\n    * rewrite IHφ1. 2: rewrite IHφ2. all: set_solver.\n    * rewrite IHφ1. 2: rewrite IHφ2. all: set_solver.\n  Qed.\n\n  Lemma eq_prf_equiv_congruence\n    (sz : nat)\n    Γ p q evs svs\n    (wfp : well_formed p)\n    (wfq : well_formed q)\n    E ψ edepth sdepth\n    (Hsz: size' ψ <= sz)\n    (wfψ : well_formed ψ)\n    (gpi : ProofInfo)\n    (** We need to do a number of Ex_Gen (and Substitution) steps\n        in the proof, thus we need at least as many fresh variables\n        as ∃-s (and μ-s) are in ψ. These should also be included in gpi.\n\n        Actually, we do not need that many variables always, then\n        depth of ∃-s should only be considered in the paths where\n        E is present. For simplicity (and the fact that we have \n        infinitely many fresh variables), we chose not to use that\n        approach\n    *)\n    el\n    (Hel1 : fresh_evars el (free_evars ψ ∪ free_evars p ∪ free_evars q ∪ {[E]}))\n    (Hel2 : length el ≥ maximal_exists_depth_to edepth E ψ)\n    (Hel3 : forall x, x ∈ el -> x ∈ evs)\n    sl\n    (Hsl1 : fresh_svars sl (free_svars ψ ∪ free_svars p ∪ free_svars q))\n    (Hsl2 : length sl ≥ maximal_mu_depth_to sdepth E ψ)\n    (Hsl3 : forall X, X ∈ sl -> X ∈ svs)\n    (pile: ProofInfoLe\n           (ExGen := evs,\n            SVSubst := svs,\n            KT := mu_in_evar_path E ψ sdepth,\n            AKT := mu_in_evar_path E ψ sdepth (* TODO relax*)) gpi)\n    (pf : Γ ⊢i (p <---> q) using ( gpi)) :\n        Γ ⊢i (((ψ^[[evar: E ↦ p]]) <---> (ψ^[[evar: E ↦ q]]))) using ( gpi).\n  Proof.\n(* TODO: if there were a size function for coEVarSet/coSVarSet, then\n         Hel3/Hsl3 would be not necessary *)\n    move: edepth sdepth ψ wfψ Hsz evs svs gpi pile pf el Hel1 Hel2 Hel3 sl Hsl1 Hsl2 Hsl3.\n    induction sz; intros edepth sdepth ψ wfψ Hsz evs svs gpi pile pf el Hel1 Hel2 Hel3 sl Hsl1 Hsl2 Hsl3.\n    abstract (destruct ψ; simpl in Hsz; lia).\n\n    lazymatch type of pile with\n    | ProofInfoLe ?st _ => set (i' := st) in *\n    end.\n\n\n  destruct (decide (E ∈ free_evars ψ)) as [HEinψ|HEnotinψ].\n    2: { rewrite free_evar_subst_no_occurrence; auto.\n      rewrite free_evar_subst_no_occurrence; auto.\n      gapply pf_iff_equiv_refl. try_solve_pile.\n      { abstract (wf_auto2). } }\n\n    destruct ψ; simpl in Hsz; simpl.\n    {\n      destruct (decide (E = x)).\n      {\n        exact pf.\n      }\n      {\n        useBasicReasoning.\n        apply pf_iff_equiv_refl.\n        abstract (wf_auto2).\n      }\n    }\n    {\n      useBasicReasoning.\n      apply pf_iff_equiv_refl.\n      abstract (wf_auto2).\n    }\n    {\n      useBasicReasoning.\n      apply pf_iff_equiv_refl.\n      abstract (wf_auto2).\n    }\n    {\n      useBasicReasoning.\n      apply pf_iff_equiv_refl.\n      abstract (wf_auto2).\n    }\n    {\n      useBasicReasoning.\n      apply pf_iff_equiv_refl.\n      abstract (wf_auto2).\n    }\n    {\n      assert (wfψ1 : well_formed ψ1 = true).\n      { clear -wfψ. abstract (wf_auto2). }\n      assert (size' ψ1 <= sz) by abstract(lia).\n      assert (wfψ2 : well_formed ψ2 = true).\n      { clear -wfψ. abstract (wf_auto2). }\n      assert (size' ψ2 <= sz) by abstract(lia).\n      \n      simpl in *.\n      pose proof (Hef1 := fresh_evars_bigger (free_evars ψ1 ∪ free_evars p ∪ free_evars q ∪ {[E]}) Hel1 ltac:(set_solver)).\n      \n      pose proof (Hsf1 := fresh_svars_bigger (free_svars ψ1 ∪ free_svars p ∪ free_svars q) Hsl1 ltac:(set_solver)).\n      \n      unshelve (epose proof (pf₁ := IHsz edepth sdepth ψ1 ltac:(assumption) ltac:(assumption) evs svs gpi _ pf el Hef1 _ Hel3 sl Hsf1 _ Hsl3)). 2-3: lia.\n      { clear - i' pile. try_solve_pile.\n        cbn in *. unfold mu_in_evar_path in *. cbn in *.\n        do 2 case_match; cbn in *; auto. lia. }\n\n      epose proof (Hef2 := fresh_evars_bigger (free_evars ψ2 ∪ free_evars p ∪ free_evars q ∪ {[E]}) Hel1 ltac:(set_solver)).\n\n      pose proof (Hsf2 := fresh_svars_bigger (free_svars ψ2 ∪ free_svars p ∪ free_svars q) Hsl1 ltac:(set_solver)).\n\n      unshelve (epose proof (pf₂ := IHsz edepth sdepth ψ2 ltac:(assumption) ltac:(assumption) evs svs gpi _ pf el Hef2 ltac:(lia) Hel3 sl Hsf2 ltac:(lia) Hsl3)).\n      { clear - i' pile. try_solve_pile.\n        cbn in *. unfold mu_in_evar_path in *. cbn in *.\n        do 2 case_match; cbn in *; auto. lia. }\n\n      unshelve (eapply congruence_app); try assumption.\n    }\n    {\n      useBasicReasoning.\n      apply pf_iff_equiv_refl.\n      abstract (wf_auto2).\n    }\n    {\n      assert (wfψ1 : well_formed ψ1 = true).\n      { clear -wfψ. abstract (wf_auto2). }\n      assert (size' ψ1 <= sz) by abstract(lia).\n      assert (wfψ2 : well_formed ψ2 = true).\n      { clear -wfψ. abstract (wf_auto2). }\n      assert (size' ψ2 <= sz) by abstract(lia).\n\n      pose proof (Hef1 := fresh_evars_bigger (free_evars ψ1 ∪ free_evars p ∪ free_evars q ∪ {[E]}) Hel1 ltac:(set_solver)).\n      \n      pose proof (Hsf1 := fresh_svars_bigger (free_svars ψ1 ∪ free_svars p ∪ free_svars q) Hsl1 ltac:(set_solver)).\n      \n      simpl in *.\n      unshelve (epose proof (pf₁ := IHsz edepth sdepth ψ1 ltac:(assumption) ltac:(assumption) evs svs gpi _ pf el Hef1 ltac:(lia) Hel3 sl Hsf1 ltac:(lia) Hsl3)).\n      { clear - i' pile. try_solve_pile.\n        cbn in *. unfold mu_in_evar_path in *. cbn in *.\n        do 2 case_match; cbn in *; auto. lia. }\n\n      epose proof (Hef2 := fresh_evars_bigger (free_evars ψ2 ∪ free_evars p ∪ free_evars q ∪ {[E]}) Hel1 ltac:(set_solver)).\n\n      pose proof (Hsf2 := fresh_svars_bigger (free_svars ψ2 ∪ free_svars p ∪ free_svars q) Hsl1 ltac:(set_solver)).\n\n      unshelve(epose proof (pf₂ := IHsz edepth sdepth ψ2 ltac:(assumption) ltac:(assumption) evs svs gpi _ pf el Hef2 ltac:(lia) Hel3 sl Hsf2 ltac:(lia) Hsl3)).\n      { clear - i' pile. try_solve_pile.\n        cbn in *. unfold mu_in_evar_path in *. cbn in *.\n        do 2 case_match; cbn in *; auto. lia. }\n\n      apply prf_equiv_of_impl_of_equiv.\n      { abstract (wf_auto2). }\n      { abstract (wf_auto2). }\n      { abstract (wf_auto2). }\n      { abstract (wf_auto2). }\n      { apply pf₁. }\n      { apply pf₂. }\n    }\n    {\n      simpl in *.\n      \n      destruct el as [ | x els].\n      { simpl in Hel2.\n        rewrite maximal_exists_depth_to_S in Hel2. assumption. lia.\n      }\n      \n      assert (well_formed (ψ^{evar: 0 ↦ x})) by (unfold i' in pile; clear i'; abstract(wf_auto2)).\n      assert (size' (ψ^{evar: 0 ↦ x}) <= sz) by abstract(rewrite evar_open_size'; lia).\n\n      assert (fresh_evars els (free_evars ψ^{evar:0↦x} ∪ free_evars p ∪ free_evars q ∪ {[E]})) as HVars. { constructor.\n        * destruct Hel1. apply evar_duplicates0.\n        * destruct Hel1. intros.\n          pose proof (free_evars_evar_open ψ x 0).\n          specialize (all_evars_fresh0 x0 ltac:(now right)).\n          simpl in *. destruct evar_duplicates0. set_solver.\n      }\n      simpl in Hel2.\n      rewrite maximal_exists_depth_to_S in Hel2. assumption.\n\n      assert (E ≠ x) as HXe. {\n        destruct Hel1 as [_ ?]. clear -all_evars_fresh0. set_solver.\n      }\n      unshelve (epose proof (IH := IHsz edepth sdepth (ψ^{evar: 0 ↦ x}) ltac:(assumption) ltac:(assumption) (evs ∪ {[x]}) svs gpi _ pf els HVars _ ltac:(set_solver) sl)).\n      {\n        cbn in *. unfold mu_in_evar_path in *. cbn in *.\n        rewrite evar_open_mu_depth.\n        2: try_solve_pile.\n        auto.\n      }\n      { rewrite evar_open_exists_depth. auto. lia. }\n      feed specialize IH.\n      { now rewrite free_svars_evar_open. }\n      { rewrite evar_open_mu_depth. auto. lia. }\n      { assumption. }\n\n      eapply congruence_ex with (x := x); try assumption.\n      {\n        destruct Hel1 as [_ ?].\n        specialize (all_evars_fresh0 x ltac:(now left)).\n        set_solver.\n      }\n      {\n        destruct Hel1 as [_ ?].\n        specialize (all_evars_fresh0 x ltac:(now left)).\n        set_solver.\n      }\n      { apply Hel3. now left. }\n      { eapply pile_trans;[|apply pile].\n        unfold i'.\n        repeat constructor; cbn.\n        { apply reflexivity. }\n        { apply reflexivity. }\n        { unfold is_true.\n          rewrite implb_true_iff.\n          intros H00. apply H00.\n        }\n      }\n    }\n    {\n      destruct sl as [ | X sls].\n      {\n        simpl in Hsl2.\n        rewrite maximal_mu_depth_to_S in Hsl2. assumption. lia.\n      }\n\n      assert (well_formed (ψ^{svar: 0 ↦ X}) = true) by (abstract(clear -wfψ;wf_auto2)).\n      assert (size' (ψ^{svar: 0 ↦ X}) <= sz) by abstract(rewrite svar_open_size'; lia).\n\n      simpl in *.\n\n      subst i'.\n      cbn in *. unfold mu_in_evar_path in *. cbn in *.\n      rewrite maximal_mu_depth_to_S in pile. assumption.\n\n      unshelve (epose proof (IH := IHsz edepth sdepth (ψ^{svar: 0 ↦ X}) ltac:(assumption) ltac:(assumption) evs svs gpi _ pf el)).\n      { \n        try_solve_pile.\n      }\n      feed specialize IH.\n      {\n        now rewrite free_evars_svar_open.\n      }\n      {\n        rewrite svar_open_exists_depth. lia.\n      }\n      {\n        assumption.\n      }\n      specialize (IH sls).\n      feed specialize IH.\n      {\n        constructor.\n        * destruct Hsl1. apply svar_duplicates0.\n        * destruct Hsl1. intros.\n          pose proof (free_svars_svar_open ψ X 0).\n          specialize (all_svars_fresh0 X0 ltac:(now right)).\n          simpl in *. destruct svar_duplicates0.\n          clear -H3 H2 H1 all_svars_fresh0. set_solver.\n      }\n      {\n        rewrite svar_open_mu_depth.\n        rewrite maximal_mu_depth_to_S in Hsl2. assumption. lia.\n      }\n      {\n        intros. apply Hsl3. now right. \n      }\n\n      unfold svar_open in IH.\n      rewrite free_evar_subst_bsvar_subst in IH.\n      1: wf_auto2.\n      1: { unfold evar_is_fresh_in. set_solver. }\n      rewrite free_evar_subst_bsvar_subst in IH.\n      1: wf_auto2.\n      1: { unfold evar_is_fresh_in. set_solver. }\n\n      unshelve (epose proof (IH1 := pf_iff_proj1 _ _ _ _ _ _ IH)).\n      { clear -wfψ wfp. abstract (wf_auto2). }\n      { clear -wfψ wfq. abstract (wf_auto2). }\n      unshelve (epose proof (IH2 := pf_iff_proj2 _ _ _ _ _ _ IH)).\n      { clear -wfψ wfp. abstract (wf_auto2). }\n      { clear -wfψ wfq. abstract (wf_auto2). }\n\n      rewrite <- (svar_quantify_svar_open X 0 (ψ^[[evar:E↦p]])).\n      rewrite <- (svar_quantify_svar_open X 0 (ψ^[[evar:E↦q]])).\n      2: {\n        pose proof (free_svars_free_evar_subst ψ E q).\n        destruct Hsl1 as [_ ?]. clear -all_svars_fresh0 H1.\n        set_solver.\n      }\n      3: {\n        pose proof (free_svars_free_evar_subst ψ E p).\n        destruct Hsl1 as [_ ?]. clear -all_svars_fresh0 H1.\n        set_solver.\n      }\n      2-3: wf_auto2.\n      \n      apply pf_iff_split.\n      4: {\n        apply mu_monotone.\n        4: {\n          unfold svar_open.\n          apply IH2.\n        }\n        2-3:\n          abstract (\n            destruct Hsl1 as [_ Hsl1];\n            specialize (Hsl1 X ltac:(now left));\n            clear -wfψ wfp wfq Hsl1;\n            wf_auto2; intros; wf_auto2;\n            cbn in *;\n            pose proof (Htmp1 := free_svars_free_evar_subst ψ E p);\n            pose proof (Htmp2 := free_svars_free_evar_subst ψ E q);\n            unfold svar_is_fresh_in;\n            set_solver\n          ).\n        {\n          abstract (try_solve_pile).\n        }\n      }\n      3: {\n        apply mu_monotone.\n        4: {\n          unfold svar_open.\n          apply IH1.\n        }\n        2-3:\n          abstract (\n            destruct Hsl1 as [_ Hsl1];\n            specialize (Hsl1 X ltac:(now left));\n            clear -wfψ wfp wfq Hsl1;\n            wf_auto2; intros; wf_auto2;\n            cbn in *;\n            pose proof (Htmp1 := free_svars_free_evar_subst ψ E p);\n            pose proof (Htmp2 := free_svars_free_evar_subst ψ E q);\n            unfold svar_is_fresh_in;\n            set_solver\n          ).\n          {\n            abstract (try_solve_pile).\n          }\n      }\n      {\n        cut (X ∉ free_svars ψ^[[evar:E↦p]]).\n        {\n          clear -wfψ wfp.\n          intros.\n          (* TODO: this rewrite somewhy does not happen in wf_auto2 *)\n          abstract (rewrite svar_quantify_svar_open;wf_auto2).\n        }\n        abstract (\n          pose proof (Htmp := free_svars_free_evar_subst ψ E p);\n          destruct Hsl1 as [_ Hsl1];\n          specialize (Hsl1 X ltac:(now left));\n          clear -H Htmp ψ Hsl1;\n          set_solver\n        ).\n      }\n      {\n        cut (X ∉ free_svars ψ^[[evar:E↦q]]).\n        {\n          clear -wfψ wfq.\n          intros.\n          abstract (rewrite svar_quantify_svar_open; wf_auto2).\n        }\n        abstract (\n          pose proof (Htmp := free_svars_free_evar_subst ψ E q);\n          destruct Hsl1 as [_ Hsl1];\n          specialize (Hsl1 X ltac:(now left));\n          clear -H Htmp ψ Hsl1;\n          set_solver\n        ).\n      }\n    }\n  Defined.\n\n  (* Correctness of evar_fresh_seq *)\n  Lemma evar_fresh_seq_correct n s:\n    fresh_evars (evar_fresh_seq s n) s.\n  Proof.\n    move: s.\n    induction n; intro s; cbn.\n    * constructor; simpl. trivial. intros. set_solver.\n    * destruct (IHn ({[evar_fresh_s s]} ∪ s)) as [Dups Fresh]. constructor.\n      - simpl. split; auto.\n        pose proof (evar_fresh_seq_disj ({[evar_fresh_s s]} ∪ s) n).\n        set_solver.\n      - intros. apply elem_of_cons in H as [H | H].\n        + subst. unfold evar_fresh_s. apply set_evar_fresh_is_fresh'.\n        + apply Fresh in H. set_solver.\n  Qed.\n\n  (* Correctness of svar_fresh_seq *)\n  Lemma svar_fresh_seq_correct n s:\n    fresh_svars (svar_fresh_seq s n) s.\n  Proof.\n    move: s.\n    induction n; intro s; cbn.\n    * constructor; simpl. trivial. intros. set_solver.\n    * destruct (IHn ({[svar_fresh_s s]} ∪ s)) as [Dups Fresh]. constructor.\n      - simpl. split; auto.\n        pose proof (svar_fresh_seq_disj ({[svar_fresh_s s]} ∪ s) n).\n        set_solver.\n      - intros. apply elem_of_cons in H as [H | H].\n        + subst. unfold svar_fresh_s. apply set_svar_fresh_is_fresh'.\n        + apply Fresh in H. set_solver.\n  Qed.\n\n  Lemma evar_fresh_seq_length l n:\n    length (evar_fresh_seq l n) = n.\n  Proof.\n    move: l.\n    induction n; intro l; simpl; auto.\n  Qed.\n\n  Lemma svar_fresh_seq_length l n:\n    length (svar_fresh_seq l n) = n.\n  Proof.\n    move: l.\n    induction n; intro l; simpl; auto.\n  Qed.\n\n  Lemma prf_equiv_congruence Γ p q C\n    (gpi : ProofInfo)\n    (wfp : well_formed p = true)\n    (wfq : well_formed q = true)\n    (wfC: PC_wf C)\n    (pile : ProofInfoLe\n       (ExGen := list_to_set (evar_fresh_seq (free_evars (pcPattern C) ∪ free_evars p ∪ free_evars q ∪ {[pcEvar C]}) (maximal_exists_depth_to 0 (pcEvar C) (pcPattern C))),\n       SVSubst := list_to_set (svar_fresh_seq (free_svars (pcPattern C) ∪ free_svars p ∪ free_svars q) (maximal_mu_depth_to 0 (pcEvar C) (pcPattern C))),\n       KT := mu_in_evar_path (pcEvar C) (pcPattern C) 0,\n       AKT := mu_in_evar_path (pcEvar C) (pcPattern C) 0 (* TODO: relax*)\n       )\n      gpi\n    ) :\n      Γ ⊢i (p <---> q) using ( gpi) ->\n      Γ ⊢i (((emplace C p) <---> (emplace C q))) using ( gpi).\n  Proof.\n    intros Hiff.\n    assert (well_formed (p <---> q)).\n    { abstract (\n        pose proof (proved_impl_wf _ _ (proj1_sig Hiff));\n        assumption\n      ).\n    }\n    assert (well_formed p) by (abstract (wf_auto2)).\n    assert (well_formed q) by (abstract (wf_auto2)).\n    destruct C as [E ψ]. simpl in *.\n    unfold emplace. simpl.\n    eapply eq_prf_equiv_congruence with \n      (el := evar_fresh_seq (free_evars ψ ∪ free_evars p ∪ free_evars q ∪ {[E]})\n      (maximal_exists_depth_to 0 E ψ))\n      (sl := svar_fresh_seq (free_svars ψ ∪ free_svars p ∪ free_svars q)\n      (maximal_mu_depth_to 0 E ψ))\n      (evs := list_to_set (evar_fresh_seq (free_evars ψ ∪ free_evars p ∪ free_evars q ∪ {[E]})\n      (maximal_exists_depth_to 0 E ψ)))\n      (svs := list_to_set (svar_fresh_seq (free_svars ψ ∪ free_svars p ∪ free_svars q)\n      (maximal_mu_depth_to 0 E ψ))); try assumption.\n    { apply reflexivity. }\n    { abstract (apply evar_fresh_seq_correct). }\n    { instantiate (1 := 0); abstract (pose proof (evar_fresh_seq_length (free_evars ψ ∪ free_evars p ∪ free_evars q ∪ {[E]}) (maximal_exists_depth_to 0 E ψ)); lia). }\n    { intros. set_solver. }\n    { abstract (apply svar_fresh_seq_correct). }\n    { instantiate (1 := 0); abstract (pose proof (svar_fresh_seq_length (free_svars ψ ∪ free_svars p ∪ free_svars q) (maximal_mu_depth_to 0 E ψ)); lia). }\n    { intros. set_solver. }\n    { try_solve_pile. }\n  Defined.\n\nEnd FOL_helpers.\n\nLemma collapse_free_evar_subst {Σ : Signature} φ ψ x y:\n  y ∉ free_evars φ ->\n  φ^[[evar: x ↦ patt_free_evar y]]^[[evar: y ↦ ψ]] =\n  φ^[[evar: x ↦ ψ]].\nProof.\n  induction φ; simpl; auto; intro Hin.\n  * repeat (case_match; simpl); auto. congruence. set_solver.\n  * rewrite IHφ1. set_solver. rewrite IHφ2. set_solver. reflexivity.\n  * rewrite IHφ1. set_solver. rewrite IHφ2. set_solver. reflexivity.\n  * rewrite IHφ. set_solver. reflexivity.\n  * rewrite IHφ. set_solver. reflexivity.\nQed.\n\nLemma fresh_foldr_is_context {Σ : Signature} l C p:\n  pcEvar C ∉ free_evars_of_list l ->\n  foldr patt_imp (emplace C p) l =\n  emplace\n    {|pcEvar := pcEvar C;\n      pcPattern := foldr patt_imp (pcPattern C) l |} p.\nProof.\n  revert C p. induction l; intros C p Hin; cbn.\n  {\n    auto.\n  }\n  {\n    simpl in Hin.\n    rewrite free_evar_subst_no_occurrence.\n    * simpl in Hin. solve_free_evars 5.\n    * f_equal. apply IHl. solve_free_evars 5.\n  }\nQed.\n\n(** NOTE: the following lemmas are very specific for prf_equiv_congruence_iter  *)\n\nLemma maximal_exists_depth_foldr_notin {Σ : Signature} l ψ x edepth:\n  x ∉ free_evars_of_list l ->\n  maximal_exists_depth_to edepth x (foldr patt_imp ψ l) =\n  maximal_exists_depth_to edepth x ψ.\nProof.\n  induction l; simpl; intros Hin.\n  * reflexivity.\n  * assert (x ∉ free_evars a) as Ha by solve_free_evars 1.\n    assert (x ∉ free_evars_of_list l) as HIND by solve_free_evars 1.\n    apply IHl in HIND. rewrite HIND.\n    rewrite maximal_exists_depth_to_0; auto.\nQed.\n\nLemma maximal_mu_depth_foldr_notin {Σ : Signature} l ψ x edepth:\n  x ∉ free_evars_of_list l ->\n  maximal_mu_depth_to edepth x (foldr patt_imp ψ l) =\n  maximal_mu_depth_to edepth x ψ.\nProof.\n  induction l; simpl; intros Hin.\n  * reflexivity.\n  * assert (x ∉ free_evars a) as Ha by solve_free_evars 1.\n    assert (x ∉ free_evars_of_list l) as HIND by solve_free_evars 1.\n    apply IHl in HIND. rewrite HIND.\n    rewrite maximal_mu_depth_to_0; auto.\nQed.\n\n(* NOTE: This version of the iterated congruence lemma is proved by induction.\n         There is a way, to prove this lemma without induction (see\n         `TEST_proofmode_proof_size.v`), but the generated proof term becomes\n         much more larger (2-3 times larger than the induction-based).\n         This is because the proof of the congruence lemma is more complex\n         for bigger contexts. *)\nLemma prf_equiv_congruence_iter {Σ : Signature} (Γ : Theory) (p q : Pattern) (C : PatternCtx) l\n  (wfp : well_formed p)\n  (wfq : well_formed q)\n  (wfC : PC_wf C)\n  (gpi : ProofInfo)\n  (pile : ProofInfoLe\n    (ExGen := list_to_set (evar_fresh_seq (free_evars (pcPattern C) ∪ free_evars p ∪ free_evars q ∪ {[pcEvar C]}) (maximal_exists_depth_to 0 (pcEvar C) (pcPattern C))),\n      SVSubst := list_to_set (svar_fresh_seq (free_svars (pcPattern C) ∪ free_svars p ∪ free_svars q) (maximal_mu_depth_to 0 (pcEvar C) (pcPattern C))),\n      KT := mu_in_evar_path (pcEvar C) (pcPattern C) 0,\n      AKT := mu_in_evar_path (pcEvar C) (pcPattern C) 0 (* TODO relax *)\n    )\n    ( gpi)\n  ):\n  Pattern.wf l ->\n  Γ ⊢i p <---> q using ( gpi) ->\n  Γ ⊢i (foldr patt_imp (emplace C p) l) <---> (foldr patt_imp (emplace C q) l) using ( gpi).\nProof.\n  intros wfl Himp.\n  induction l; simpl in *.\n  - unshelve(eapply prf_equiv_congruence); assumption.\n  - pose proof (wfal := wfl).\n    unfold Pattern.wf in wfl. simpl in wfl. apply andb_prop in wfl as [wfa wfl].\n    specialize (IHl wfl).\n    pose proof (Hwf1 := proved_impl_wf _ _ (proj1_sig IHl)).\n    pose proof (Hwf2 := proved_impl_wf _ _ (proj1_sig Himp)).\n    assert (well_formed (emplace C p)).\n    {\n      unfold emplace.\n      wf_auto2.\n    }\n    assert (well_formed (emplace C q)).\n    {\n      unfold emplace.\n      wf_auto2.\n    }\n    toMLGoal.\n    { unfold emplace. wf_auto2. }\n    unfold patt_iff.\n    mlSplitAnd.\n    + mlIntro. mlIntro.\n      mlAssert ((foldr patt_imp (emplace C p) l)).\n      { wf_auto2. }\n      { mlApply \"0\". mlExactn 1. }\n      apply pf_iff_proj1 in IHl.\n      2,3: wf_auto2.\n      mlApplyMetaRaw IHl.\n      mlExactn 2.\n    + mlIntro. mlIntro.\n      mlAssert ((foldr patt_imp (emplace C q) l)).\n      { wf_auto2. }\n      { mlApply \"0\". mlExactn 1. }\n      apply pf_iff_proj2 in IHl.\n      2,3: wf_auto2.\n      mlApplyMetaRaw IHl.\n      mlExactn 2.\nDefined.\n\nLemma extract_wfp {Σ : Signature} (Γ : Theory) (p q : Pattern) (i : ProofInfo):\n  Γ ⊢i p <---> q using i ->\n  well_formed p.\nProof.\n  intros H.\n  pose proof (H' := proj1_sig H).\n  apply proved_impl_wf in H'.\n  wf_auto2.\nQed.\n\nLemma extract_wfq {Σ : Signature} (Γ : Theory) (p q : Pattern) (i : ProofInfo):\n  Γ ⊢i p <---> q using i ->\n  well_formed q.\nProof.\n  intros H.\n  pose proof (H' := proj1_sig H).\n  apply proved_impl_wf in H'.\n  wf_auto2.\nQed.\n\nLemma MLGoal_rewriteIff\n  {Σ : Signature} (Γ : Theory) (p q : Pattern) (C : PatternCtx) l (gpi : ProofInfo)\n  (wfC : PC_wf C)\n  (pf : Γ ⊢i p <---> q using ( gpi)) :\n  mkMLGoal Σ Γ l (emplace C q) ( gpi) ->\n  (ProofInfoLe\n    (ExGen := list_to_set (evar_fresh_seq (free_evars (pcPattern C) ∪ free_evars p ∪ free_evars q ∪ {[pcEvar C]}) (maximal_exists_depth_to 0 (pcEvar C) (pcPattern C))),\n     SVSubst := list_to_set (svar_fresh_seq (free_svars (pcPattern C) ∪\n                free_svars p ∪ free_svars q) (maximal_mu_depth_to 0 (pcEvar C) (pcPattern C))),\n     KT := mu_in_evar_path (pcEvar C) (pcPattern C) 0,\n     AKT := mu_in_evar_path (pcEvar C) (pcPattern C) 0 (* TODO: relax*)\n  )\n      gpi) ->\n  mkMLGoal Σ Γ l (emplace C p) ( gpi).\nProof.\n  rename pf into Hpiffq.\n  intros H pile.\n  unfold of_MLGoal in *. simpl in *.\n  intros wfcp wfl.\n  feed specialize H.\n  { abstract (\n      pose proof (Hwfiff := proved_impl_wf _ _ (proj1_sig Hpiffq));\n      unfold emplace;\n      apply well_formed_free_evar_subst_0;[wf_auto2|];\n      fold (PC_wf C);\n      eapply wf_emplaced_impl_wf_context;\n      apply wfcp\n    ).\n  }\n  { exact wfl. }\n\n  eapply MP.\n  2: apply pf_iff_proj2.\n  2: abstract (wf_auto2).\n  3: eapply prf_equiv_congruence_iter.\n  8: apply Hpiffq.\n  all: try assumption.\n  all: wf_auto2.\nDefined.\n\n\n\nLtac2 mutable ml_debug_rewrite := false.\n\n(* Calls [cont] for every subpattern [a] of pattern [phi], giving the match context as an argument *)\nLtac2 for_each_match := fun (a : constr) (phi : constr) (cont : Pattern.context -> unit) =>\n  try (\n      if ml_debug_rewrite then\n           Message.print (\n               Message.concat\n                 (Message.of_string \"Trying to match \")\n                 (Message.of_constr a)\n             )\n        else ();\n      match! phi with\n      | context ctx [ ?x ]\n        => if ml_debug_rewrite then\n             Message.print (\n                 Message.concat\n                   (Message.of_string \" against \")\n                   (Message.of_constr x)\n               )\n           else ();\n           (if Constr.equal x a then\n              if ml_debug_rewrite then\n                Message.print (Message.of_string \"Success.\")\n              else () ;\n              cont ctx\n            else ());\n           fail (* backtrack *)\n      end\n    ); ().\n\n(* Calls [cont] for [n]th subpatern [a] of pattern [phi]. *)\nLtac2 for_nth_match :=\n  fun (n : int) (a : constr) (phi : constr) (cont : Pattern.context -> unit) =>\n    if ml_debug_rewrite then\n      Message.print (Message.of_string \"for_nth_match\")\n    else () ;\n    let curr : int ref := {contents := 0} in\n    let found : bool ref := {contents := false} in\n    for_each_match a phi\n    (fun ctx =>\n      if (found.(contents))\n      then ()\n      else\n        curr.(contents) := Int.add 1 (curr.(contents)) ;\n        if (Int.equal (curr.(contents)) n) then\n          cont ctx\n        else ()\n    )\n.\n\nLocal Ltac reduce_free_evar_subst_step_2 star :=\n      lazymatch goal with\n      | [ |- context ctx [?p^[[evar: star ↦ ?q]] ] ]\n        =>\n          progress rewrite -> (@free_evar_subst_no_occurrence _ star p q) by (\n            subst star;\n            eapply evar_is_fresh_in_richer';\n            [|apply set_evar_fresh_is_fresh'];\n            simpl; clear; set_solver\n          )\n      end.\n\nLocal Ltac reduce_free_evar_subst_2 star :=\n  (* unfold free_evar_subst; *)\n  repeat (reduce_free_evar_subst_step_2 star).\n\nLocal Tactic Notation \"solve_fresh_contradictions_2'\" constr(star) constr(x) constr(h) :=\n  let hcontra := fresh \"Hcontra\" in\n  assert (hcontra: x <> star) by (subst star; unfold fresh_evar,evar_fresh_s; try clear h; simpl; solve_fresh_neq);\n  rewrite -> h in hcontra;\n  contradiction.\n\nLocal Ltac solve_fresh_contradictions_2 star :=\n  unfold fresh_evar; simpl;\n  match goal with\n  | h: ?x = star |- _ =>\n    let hprime := fresh \"hprime\" in\n    pose proof (hprime := eq_sym h);\n    solve_fresh_contradictions_2' star x hprime\n  | h: star = ?x |- _\n    => solve_fresh_contradictions_2' star x h\n  end.\n\nLocal Ltac clear_obvious_equalities_2 :=\n  repeat (\n      match goal with\n      | [ h: ?x = ?x |- _ ] => clear h\n      end\n    ).\n\n\nLtac simplify_emplace_2 star :=\n  unfold emplace;\n  (* unfold free_evar_subst; *)\n  cbn;\n  repeat break_match_goal;\n  clear_obvious_equalities_2; try contradiction;\n  try (solve_fresh_contradictions_2 star);\n  (* repeat (rewrite nest_ex_aux_0); *)\n  reduce_free_evar_subst_2 star.\n\n(* Returns [n]th matching logic context [C] (of type [PatternCtx]) such that\n   [emplace C a = phi].\n *)\n\n \n (* Ltac simplify_pile_side_condition_helper star :=\n  subst star;\n  unfold fresh_evar,evar_fresh_s;\n  eapply evar_is_fresh_in_richer';\n  [|apply set_evar_fresh_is_fresh'];\n  clear; simpl; set_solver. *)\n\nLtac rewrite_0_depths star :=\n  unfold mu_in_evar_path; cbn;\n  repeat rewrite (maximal_exists_depth_to_0 star);\n  repeat rewrite (maximal_mu_depth_to_0 star);\n  repeat match goal with\n  | [ |- context ctx [decide (star = star)] ] =>\n    destruct (decide (star = star)); try congruence\n  | [ |- context ctx [decide (?x = star)] ] =>\n    destruct (decide (x = star)); try congruence\n  | [ |- context ctx [decide (star = ?x)] ] =>\n    destruct (decide (star = x)); try congruence\n  | _ => idtac\n  end;\n  cbn.\n\nLtac try_solve_complex_pile star :=\n  try apply pile_any;\n  simplify_emplace_2 star;\n  (rewrite_0_depths star);\n  match goal with\n  | |- star ∉ free_evars _ => subst star; solve_fresh\n  | |- ProofInfoLe _ _ => try_solve_pile\n  end.\n\nLtac2 Type HeatResult := {\n  star_ident : ident ;\n  star_eq : ident ;\n  pc : constr ;\n  ctx : Pattern.context ;\n  ctx_pat : constr ;\n  equality : ident ;\n}.\n\n(** NOTE: with the new MLGoal_rewriteIff, we also need the variables\n          used in the list of hypotheses (l) for the fresh name\n          generation.\n*)\nLtac2 heat :=\n  fun (n : int) (a : constr) (phi : constr) : HeatResult =>\n    let found : (Pattern.context option) ref := { contents := None } in\n     for_nth_match n a phi\n     (fun ctx =>\n        found.(contents) := Some ctx; ()\n     );\n     match found.(contents) with\n    | None => Control.backtrack_tactic_failure \"Cannot heat\"\n    | Some ctx\n      => (\n         let fr := constr:(fresh_evar $phi) in\n         let star_ident := Fresh.in_goal ident:(star) in\n         let star_eq := Fresh.in_goal ident:(star_eq) in\n         (*set ($star_ident := $fr);*)\n         remember $fr as $star_ident eqn:star_eq;\n         let star_hyp := Control.hyp star_ident in\n         let ctxpat := Pattern.instantiate ctx constr:(patt_free_evar $star_hyp) in\n         let pc := constr:((@Build_PatternCtx _ $star_hyp $ctxpat)) in\n         let heq1 := Fresh.in_goal ident:(heq1) in\n         assert(heq1 : ($phi = (@emplace _ $pc $a))) \n         > [ abstract(\n             (ltac1:(star |- simplify_emplace_2 star) (Ltac1.of_ident star_ident);\n             reflexivity\n             ))\n           | ()\n           ];\n          { star_ident := star_ident; star_eq := star_eq; pc := pc; ctx := ctx; ctx_pat := ctxpat; equality := heq1 }\n         )\n    end\n.\n\nLemma cast_proof_ml_goal {Σ : Signature} Γ hyps goal goal' (e : goal = goal') (i : ProofInfo):\n  mkMLGoal Σ Γ hyps goal i ->\n  mkMLGoal Σ Γ hyps goal' i .\nProof.\n  rewrite e. intros H. exact H.\nDefined.\n\nLtac2 mlRewrite (hiff : constr) (atn : int) :=\n  let thiff := Constr.type hiff in\n  (* we have to unfold [derives] otherwise this might not match *)\n  lazy_match! (eval unfold derives in $thiff) with\n  | _ ⊢i (?a <---> ?a') using _\n    =>\n    unfold AnyReasoning;\n    lazy_match! goal with\n    | [ |- of_MLGoal (@mkMLGoal ?sgm ?g ?l ?p ( ?gpi))]\n      =>\n        let hr : HeatResult := heat atn a p in\n        if ml_debug_rewrite then\n           Message.print (Message.of_constr (hr.(ctx_pat)))\n         else () ;\n         let heq := Control.hyp (hr.(equality)) in\n         let pc := (hr.(pc)) in\n         eapply (@cast_proof_ml_goal _ $g) >\n           [ rewrite $heq; reflexivity | ()];\n         Std.clear [hr.(equality)];\n         let wfC := Fresh.in_goal ident:(wfC) in\n         assert (wfC : PC_wf $pc = true) > [ ltac1:(unfold PC_wf; simpl; wf_auto2); Control.shelve () | ()] ;\n         let wfCpf := Control.hyp wfC in\n         apply (@MLGoal_rewriteIff $sgm $g _ _ $pc $l $gpi $wfCpf $hiff)  >\n         [\n         (lazy_match! goal with\n         | [ |- of_MLGoal (@mkMLGoal ?sgm ?g ?l ?p _)]\n           =>\n             let heq2 := Fresh.in_goal ident:(heq2) in\n             let plugged := Pattern.instantiate (hr.(ctx)) a' in\n             assert(heq2: ($p = $plugged))\n             > [\n                 abstract (ltac1:(star |- simplify_emplace_2 star) (Ltac1.of_ident (hr.(star_ident)));\n                 reflexivity\n                 )\n               | ()\n               ];\n             let heq2_pf := Control.hyp heq2 in\n             eapply (@cast_proof_ml_goal _ $g) >\n               [ rewrite $heq2_pf; reflexivity | ()];\n             Std.clear [wfC; heq2 ; (hr.(star_ident)); (hr.(star_eq))]\n         end)\n         | (ltac1:(star |- try_solve_complex_pile star) (Ltac1.of_ident (hr.(star_ident))))\n         ]\n    end\n  end.\n\nLtac2 rec constr_to_int (x : constr) : int :=\n  match! x with\n  | 0 => 0\n  | (S ?x') => Int.add 1 (constr_to_int x')\n  end.\n\n\nTactic Notation \"mlRewrite\" constr(Hiff) \"at\" constr(atn) :=\n  _ensureProofMode;\n  (let ff := ltac2:(hiff atn |-\n                      mlRewrite\n                        (Option.get (Ltac1.to_constr(hiff)))\n                        (constr_to_int (Option.get (Ltac1.to_constr(atn))))\n                   ) in\n   ff Hiff atn);\n   fold AnyReasoning.\n\nLemma pf_iff_equiv_sym_nowf {Σ : Signature} Γ A B i :\n  Γ ⊢i (A <---> B) using i ->\n  Γ ⊢i (B <---> A) using i.\nProof.\n  intros H.\n  pose proof (wfp := proved_impl_wf _ _ (proj1_sig H)).\n  assert (well_formed A) by wf_auto2.\n  assert (well_formed B) by wf_auto2.\n  apply pf_iff_equiv_sym; assumption.\nDefined.\n\nTactic Notation \"mlRewrite\" \"->\" constr(Hiff) \"at\" constr(atn) :=\n  mlRewrite Hiff at atn.\n\nTactic Notation \"mlRewrite\" \"<-\" constr(Hiff) \"at\" constr(atn) :=\n  mlRewrite (@pf_iff_equiv_sym_nowf _ _ _ _ _ Hiff) at atn.\n\n\nLocal Example ex_prf_rewrite_equiv_2 {Σ : Signature} Γ a a' b x:\n  well_formed a ->\n  well_formed a' ->\n  well_formed (ex, b) ->\n  Γ ⊢ a <---> a' ->\n  Γ ⊢i (ex, (a $ a $ b $ a ---> (patt_free_evar x)))\n  <---> (ex, (a $ a' $ b $ a' ---> (patt_free_evar x)))\n  using AnyReasoning.\nProof.\n  intros wfa wfa' wfb Hiff.\n  toMLGoal.\n  { abstract(wf_auto2). }\n  mlRewrite Hiff at 2.\n  mlRewrite <- Hiff at 3.\n  fromMLGoal.\n  useBasicReasoning.\n  apply pf_iff_equiv_refl. abstract(wf_auto2).\nDefined.\n\n\n\n(* TODO: de-duplicate the code *)\n#[local]\nLtac convertToNNF_rewrite_pat Ctx p i :=\n  lazymatch p with\n    | (! ! ?x) =>\n        let H' := fresh \"H\" in\n        pose proof (@not_not_eq _ Ctx x ltac:(wf_auto2)) as H';\n        apply (@useBasicReasoning _ _ _ i) in H';\n        repeat (mlRewrite H' at 1);\n        try clear H';\n        convertToNNF_rewrite_pat Ctx x i\n    | patt_not (patt_and ?x ?y) =>\n        let H' := fresh \"H\" in\n        pose proof (@deMorgan_nand _ Ctx x y ltac:(wf_auto2) ltac:(wf_auto2)) as H';\n        apply (@useBasicReasoning _ _ _ i) in H';\n        repeat (mlRewrite H' at 1);\n        try clear H';\n        convertToNNF_rewrite_pat Ctx (!x or !y) i\n    | patt_not (patt_or ?x ?y) =>\n        let H' := fresh \"H\" in\n        pose proof (@deMorgan_nor _ Ctx x y ltac:(wf_auto2) ltac:(wf_auto2)) as H';\n        apply (@useBasicReasoning _ _ _ i) in H';\n        repeat (mlRewrite H' at 1);\n        try clear H';\n        convertToNNF_rewrite_pat Ctx (!x and !y) i\n    | patt_not (?x ---> ?y) =>\n        let H' := fresh \"H\" in\n        pose proof (@nimpl_eq_and _ Ctx x y ltac:(wf_auto2) ltac:(wf_auto2)) as H';\n        apply (@useBasicReasoning _ _ _ i) in H';\n        repeat (mlRewrite H' at 1);\n        try clear H';\n        convertToNNF_rewrite_pat Ctx (x and !y) i\n    | (?x ---> ?y) =>\n        let H' := fresh \"H\" in\n        pose proof (@impl_eq_or _ Ctx x y ltac:(wf_auto2) ltac:(wf_auto2)) as H';\n        apply (@useBasicReasoning _ _ _ i) in H';\n        repeat (mlRewrite H' at 1);\n        try clear H';\n        convertToNNF_rewrite_pat Ctx (!x or y) i\n    | patt_and ?x ?y => convertToNNF_rewrite_pat Ctx x i; convertToNNF_rewrite_pat Ctx y i\n    | patt_or ?x ?y => convertToNNF_rewrite_pat Ctx x i; convertToNNF_rewrite_pat Ctx y i\n    | _ => idtac\n  end.\n\n#[local]\nLtac toNNF := \n  repeat mlRevertLast;\n  match goal with\n    | [ |- @of_MLGoal ?Sgm (@mkMLGoal ?Sgm ?Ctx ?ll ?g ?i) ] \n      =>\n        mlApplyMetaRaw (@useBasicReasoning _ _ _ i (@not_not_elim Sgm Ctx g ltac:(wf_auto2)));\n        convertToNNF_rewrite_pat Ctx (!g) i\n  end.\n\n#[local] Example test_toNNF {Σ : Signature} Γ a b :\n  well_formed a ->\n  well_formed b ->\n  Γ ⊢i ( (b and (a or b) and !b and ( a or a) and a) ---> ⊥)\n  using BasicReasoning.\nProof.\n  intros wfa wfb.\n  toMLGoal.\n  { wf_auto2. }\n  toNNF.\nAbort.\n\n#[local]\nLtac rfindContradictionTo a ll k :=\n  match ll with\n    | ((mkNH _ ?name (! a)) :: ?m) =>\n        mlApply name; mlExactn k\n    | ((mkNH _ _ _) :: ?m) => \n        rfindContradictionTo a m k\n    | _ => fail\n  end.\n\n#[local]\nLtac findContradiction l k:=\n    match l with\n       | ((mkNH _ _ ?a) :: ?m) => \n             match goal with\n                | [ |- @of_MLGoal ?Sgm (@mkMLGoal ?Sgm ?Ctx ?ll ?g ?i) ] \n                  =>\n                     try rfindContradictionTo a ll k;\n                     let kk := eval compute in ( k + 1 ) in\n                     (findContradiction m kk)\n             end\n       | _ => fail\n    end.\n\n#[local]\nLtac findContradiction_start :=\n  match goal with\n    | [ |- @of_MLGoal ?Sgm (@mkMLGoal ?Sgm ?Ctx ?l ?g ?i) ] \n      =>\n        match goal with\n          | [ |- @of_MLGoal ?Sgm (@mkMLGoal ?Sgm ?Ctx ?l ?g ?i) ] \n            =>\n              findContradiction l 0\n        end\n  end.\n\n#[local]\nLtac breakHyps l :=\n  match l with\n  | ((mkNH _ ?name (?x and ?y)) :: ?m) => \n      mlDestructAnd name\n  | ((mkNH _ ?name (?x or ?y)) :: ?m) => \n      mlDestructOr name\n  | ((mkNH _ ?name ?x) :: ?m)  =>\n      breakHyps m\n  end.\n\n#[local]\nLtac mlTautoBreak := repeat match goal with\n| [ |- @of_MLGoal ?Sgm (@mkMLGoal ?Sgm ?Ctx ?l ?g ?i) ] \n  =>\n    lazymatch g with\n      | (⊥) =>\n              breakHyps l\n      | _ => mlApplyMetaRaw (@useBasicReasoning _ _ _ i (@bot_elim _ _ g _))\n    end\nend.\n\nLtac try_solve_pile2 fallthrough :=\n  lazymatch goal with\n  | [ |- ProofInfoLe _ _] => try apply pile_refl; try_solve_pile; fallthrough\n  | _ => idtac\n  end.\n\n#[global]\nLtac mlTauto :=\n  _ensureProofMode;\n  unshelve(\n    try (\n      toNNF; (try_solve_pile2 shelve);\n      repeat mlIntro;\n      mlTautoBreak;\n      findContradiction_start\n    )\n  )\n.\n\n#[local]\nExample conj_right {Σ : Signature} Γ a b:\n  well_formed a ->\n  well_formed b ->\n  Γ ⊢i ( (b and (a or b) and !b and ( a or a) and a) ---> ⊥)\n  using AnyReasoning.\nProof.\n  intros wfa wfb.\n  toMLGoal.\n  { wf_auto2. }\n  (* TODO: fail loudly if there is something else than AnyReasoning *)\n  mlTauto.\nDefined.\n\n#[local]\nExample condtradict_taut_2 {Σ : Signature} Γ a b:\n  well_formed a ->\n  well_formed b ->\n  Γ ⊢i (a ---> ((! a) ---> b))\n  using AnyReasoning.\nProof.\n  intros wfa wfb.\n  toMLGoal.\n  { wf_auto2. }\n  mlTauto.\nDefined.\n\n#[local]\nExample taut {Σ : Signature} Γ a b c:\n  well_formed a ->\n  well_formed b ->\n  well_formed c ->\n  Γ ⊢i ((a ---> b) ---> ((b ---> c) ---> ((a or b)---> c)))\n  using AnyReasoning.\nProof.\n  intros wfa wfb wfc.\n  toMLGoal.\n  { wf_auto2. }\n  mlTauto. (* Slow *)\nDefined.\n\n#[local]\nExample condtradict_taut_1 {Σ : Signature} Γ a:\n  well_formed a ->\n  Γ ⊢i !(a and !a)\n  using AnyReasoning.\nProof.\n  intros wfa.\n  toMLGoal.\n  { wf_auto2. }\n  mlTauto.\nDefined.\n\n#[local]\nExample notnot_taut_1 {Σ : Signature} Γ a:\n  well_formed a ->\n  Γ ⊢i (! ! a ---> a)\n  using AnyReasoning.\nProof.\n  intros wfa.\n  toMLGoal.\n  { wf_auto2. }\n  mlTauto.\nDefined.\n\n#[local]\nLemma Peirce_taut {Σ : Signature} Γ a b:\n  well_formed a ->\n  well_formed b ->\n  Γ ⊢i ((((a ---> b) ---> a) ---> a))\n  using AnyReasoning.\nProof.\n  intros wfa wfb.\n  toMLGoal.\n  { wf_auto2. }\n  mlTauto.\nDefined.\n\n\n\nClose Scope ml_scope.\nClose Scope list_scope.\nClose Scope string_scope.", "meta": {"author": "harp-project", "repo": "AML-Formalization", "sha": "ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d", "save_path": "github-repos/coq/harp-project-AML-Formalization", "path": "github-repos/coq/harp-project-AML-Formalization/AML-Formalization-ee6fd737632e1bb2737b22cbbbca3b8a3e68f89d/matching-logic/src/ProofMode/Misc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.20643753844815968}}
{"text": "Require Import VST.msl.seplog.\nRequire Import VST.msl.log_normalize.\nRequire Import CertiGraph.lib.Coqlib.\nRequire Import CertiGraph.lib.Ensembles_ext.\nRequire Import CertiGraph.lib.EquivDec_ext.\nRequire Import CertiGraph.lib.List_ext.\nRequire Import CertiGraph.lib.relation_list.\nRequire Import CertiGraph.msl_ext.log_normalize.\nRequire Import CertiGraph.msl_ext.iter_sepcon.\nRequire Import CertiGraph.msl_ext.ramification_lemmas.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.path_lemmas.\nRequire Import CertiGraph.graph.reachable_computable.\nRequire Import CertiGraph.graph.reachable_ind.\nRequire Import CertiGraph.graph.subgraph2.\nRequire Import CertiGraph.graph.graph_gen.\nRequire Import CertiGraph.graph.dag.\nRequire Import CertiGraph.graph.weak_mark_lemmas.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import Coq.Logic.Classical.\n\nLocal Open Scope logic.\n\nSection PointwiseGraph_Mark.\n\nContext {V E: Type}.\nContext {GV GE Pred: Type}.\nContext {SGBA: PointwiseGraphBasicAssum V E}.\nContext {SGC: PointwiseGraphConstructor V E bool unit unit GV GE}.\nContext {L_SGC: Local_PointwiseGraphConstructor V E bool unit unit GV GE}.\nContext {SGP: PointwiseGraphPred V E GV GE Pred}.\nContext {SGA: PointwiseGraphAssum SGP}.\n\nInstance MGS: WeakMarkGraph.MarkGraphSetting bool.\nProof.\n  apply (WeakMarkGraph.Build_MarkGraphSetting _ (eq true)).\n  intros; destruct x; [left | right]; congruence.\nDefined.\n\nGlobal Existing Instance MGS.\n\nNotation Graph := (LabeledGraph V E bool unit unit).\nNotation SGraph := (PointwiseGraph V E GV GE).\n\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nDefinition mark1 x (G1: Graph) (G2: Graph) := WeakMarkGraph.mark1 x G1 G2.\nDefinition mark x (G1: Graph) (G2: Graph) := WeakMarkGraph.mark x G1 G2 /\\ G1 ~=~ G2.\n\nDefinition mark_list xs g1 g2 := relation_list (map mark xs) g1 g2.\n\nLemma mark_invalid_refl: forall (g: Graph) root, ~ vvalid g root -> mark root g g.\nProof.\n  intros.\n  split.\n  + apply WeakMarkGraph.mark_invalid_refl; auto.\n  + reflexivity.\nQed.\n\nLemma mark_marked_root_refl: forall (g: Graph) root, WeakMarkGraph.marked g root -> mark root g g.\nProof.\n  intros.\n  split.\n  + apply WeakMarkGraph.mark_marked_root_refl; auto.\n  + reflexivity.\nQed.\n\nLemma mark_list_eq: forall root xs g1 g2,\n  mark_list xs g1 g2 ->\n  WeakMarkGraph.componded_mark_list root xs g1 g2 /\\ g1 ~=~ g2.\nProof.\n  intros.\n  change (mark_list xs g1 g2) with\n    (relation_list (map (fun x => relation_conjunction (WeakMarkGraph.mark x) (respectful_relation pg_lg structurally_identical)) xs) g1 g2) in H.\n  eapply relation_list_conjunction in H.\n  rewrite relation_conjunction_iff in H.\n  split.\n  + destruct H as [? _].\n    eapply relation_list_inclusion; [| exact H].\n    intros ? _.\n    clear.\n    intros g1 g2 ?.\n    exists g2; [| apply WeakMarkGraph.eq_do_nothing; auto].\n    exists g1; [apply WeakMarkGraph.eq_do_nothing; auto |].\n    auto.\n  + eapply si_list.\n    exact (proj2 H).\nQed.\n\nLemma mark1_mark_list_mark: forall root l (g g': Graph),\n  vvalid g root ->\n  (WeakMarkGraph.unmarked g) root ->\n  step_list g root l ->\n  relation_list (mark1 root :: mark_list l :: nil) g g' ->\n  mark root g g'.\nProof.\n  intros.\n  destruct_relation_list g0 in H2.\n  eapply (mark_list_eq root) in H2.\n  destruct H2; simpl in H2.\n  split.\n  + eapply WeakMarkGraph.mark1_componded_mark_list_mark; eauto.\n    split_relation_list (g :: g0 :: g0 :: g' :: nil); auto;\n    apply WeakMarkGraph.eq_do_nothing; auto.\n  + destruct H3 as [? _].\n    rewrite H3; auto.\nQed.\n\nLemma mark_partial_labeled_graph_equiv: forall x (g g': Graph),\n  mark x g g' ->\n  ((predicate_partial_labeledgraph g (Complement _ (reachable g x))) ~=~\n  (predicate_partial_labeledgraph g' (Complement _ (reachable g x))))%LabeledGraph.\nProof.\n  intros.\n  split; [| split].\n  + destruct H.\n    simpl;\n    rewrite <- H0.\n    reflexivity.\n  + destruct H as [[? ?] _].\n    simpl in *; intros.\n    specialize (H0 v).\n    assert (~ g |= x ~o~> v satisfying (WeakMarkGraph.unmarked g)).\n    1: {\n      destruct H1.\n      intro; apply H3.\n      apply reachable_by_is_reachable in H4; auto.\n    }\n    clear - H0 H3.\n    destruct (vlabel g v), (vlabel g' v).\n    - auto.\n    - rewrite H0; auto.\n    - symmetry; tauto.\n    - auto.\n  + intros; simpl.\n    destruct (elabel g e), (elabel g' e); auto.\nQed.\n\nLemma root_stable_ramify: forall (g: Graph) (x: V) (gx: GV),\n  vgamma (Graph_PointwiseGraph g) x = gx ->\n  vvalid g x ->\n  @derives Pred _\n    (reachable_vertices_at x g)\n    (vertex_at x gx * (vertex_at x gx -* reachable_vertices_at x g)).\nProof. apply va_reachable_root_stable_ramify. Qed.\n\nLemma root_update_ramify: forall (g: Graph) (x: V) (lx: bool) (gx gx': GV),\n  vvalid g x ->\n  vgamma (Graph_PointwiseGraph g) x = gx ->\n  vgamma (Graph_PointwiseGraph (labeledgraph_vgen g x lx)) x = gx' ->\n  Included (Intersection V (reachable g x) (Complement V (eq x))) (vguard g) ->\n  Included (Intersection V (reachable g x) (Complement V (eq x))) (vguard (labeledgraph_vgen g x lx)) ->\n  @derives Pred _\n    (reachable_vertices_at x g)\n    (vertex_at x gx *\n      (vertex_at x gx' -* reachable_vertices_at x (labeledgraph_vgen g x lx))).\nProof. apply va_reachable_root_update_ramify. Qed.\n\n(* TODO: remove this lemma? *)\nLemma exp_mark1: forall (g: Graph) (x: V) (lx: bool),\n  WeakMarkGraph.label_marked lx ->\n  @derives Pred _ (reachable_vertices_at x (labeledgraph_vgen g x lx)) (EX g': Graph, !! (mark1 x g g') && reachable_vertices_at x g').\nProof.\n  intros.\n  apply (exp_right (labeledgraph_vgen g x lx)).\n  apply andp_right; [apply prop_right | auto].\n  apply WeakMarkGraph.vertex_update_mark1; auto.\nQed.\n\nLemma mark_neighbor_ramify: forall {A} (g1: Graph) (g2: A -> Graph) x y,\n  (forall (g: Graph) x y, reachable g x y \\/ ~ reachable g x y) ->\n  vvalid g1 x ->\n  step g1 x y ->\n  Included (Intersection V (reachable g1 x) (Complement V (reachable g1 y)))\n     (vguard g1) ->\n  (forall a, mark y g1 (g2 a) -> Included (Intersection V (reachable g1 x) (Complement V (reachable g1 y))) (vguard (g2 a))) ->\n  @derives Pred _\n    (reachable_vertices_at x g1)\n    (reachable_vertices_at y g1 *\n      (ALL a: A, !! mark y g1 (g2 a) -->\n        (reachable_vertices_at y (g2 a) -*\n         reachable_vertices_at x (g2 a)))).\nProof.\n  intros.\n  assert (Included (reachable g1 y) (reachable g1 x)).\n  1: {\n    hnf; unfold Ensembles.In; intros.\n    apply step_reachable with y; auto.\n  }  \n  apply vertices_at_ramif_xQ. eexists. split; [|split].\n  + apply Ensemble_join_Intersection_Complement; auto. \n  + intros. destruct H5 as [_ ?].\n    rewrite <- H5; clear H5.\n    apply Ensemble_join_Intersection_Complement; auto.\n  + intros.\n    apply GSG_PartialGraphPreserve; auto.\n    - unfold Included, Ensembles.In; intros.\n      rewrite Intersection_spec in H6; destruct H6 as [? _].\n      apply reachable_foot_valid in H6; auto.\n    - destruct H5.\n      rewrite H6; clear H6.\n      unfold Included, Ensembles.In; intros.\n      rewrite Intersection_spec in H6; destruct H6 as [? _].\n      apply reachable_foot_valid in H6; auto.\n    - apply mark_partial_labeled_graph_equiv in H5.\n      eapply si_stronger_partial_labeledgraph_simple; [| eassumption].\n      unfold Included, Ensembles.In; intros.\n      rewrite Intersection_spec in H6.\n      tauto.\nQed.\n\nLemma mark_list_mark_ramify: forall {A} (g1 g2: Graph) (g3: A -> Graph) x l y l',\n  (forall (g: Graph) x y, reachable g x y \\/ ~ reachable g x y) ->\n  vvalid g1 x ->\n  step_list g1 x (l ++ y :: l') ->\n  relation_list (mark1 x :: mark_list l :: nil) g1 g2 ->\n  Included (Intersection V (reachable g2 x) (Complement V (reachable g2 y)))\n     (vguard g2) ->\n  (forall a, mark y g2 (g3 a) -> Included (Intersection V (reachable g2 x) (Complement V (reachable g2 y))) (vguard (g3 a))) ->\n  @derives Pred _\n    (reachable_vertices_at x g2)\n    (reachable_vertices_at y g2 *\n      (ALL a: A, !! mark y g2 (g3 a) -->\n        (reachable_vertices_at y (g3 a) -*\n         reachable_vertices_at x (g3 a)))).\nProof.\n  intros. \n  destruct_relation_list g1' in H2.\n  destruct H5 as [? _].\n  apply (mark_list_eq x) in H2.\n  destruct H2 as [_ ?].\n  rewrite <- H5 in H2; clear g1' H5.\n  apply mark_neighbor_ramify; auto.\n  + destruct H2. rewrite <- (H2 x). auto.\n  + rewrite <- (step_si g1); auto. hnf in H1. rewrite <- H1.\n    rewrite in_app_iff. right. apply in_eq.\nQed.\n\nEnd PointwiseGraph_Mark.\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/msl_application/Graph_Mark.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.2062925493024277}}
{"text": "Require Export decl_inf.\nRequire Export Coq.Unicode.Utf8.\n\nNotation \"G ⊢ e1 <: e2 : A\" :=\n  (usub G e1 e2 A)\n    (at level 65, e1 at level 50, e2 at level 50, no associativity) : type_scope.\n\nNotation \"G ⊢ e : A\" :=\n  (usub G e e A)\n    (at level 65, e at level 50, no associativity) : type_scope.\n\nNotation \"⊢ G\" :=\n  (wf_context G)\n    (at level 65, no associativity) : type_scope.\n\nNotation \"A ⟶ B\" := (reduce A B)\n  (at level 65, no associativity) : type_scope.\n\nNotation \"x :' A ∈ G\" := (in_ctx x A G)\n  (at level 65, no associativity) : type_scope.\n\nDeclare Scope context_scope.\nDelimit Scope context_scope with ctx.\nBind Scope context_scope with context.\n\nNotation \"G , x : A\" :=\n  (ctx_cons G x A)\n    (at level 58, x at level 0, left associativity) : context_scope.\n\nReserved Notation \"G1 ,, G2\"\n  (at level 58, left associativity).\n\nFixpoint ctx_app (Γ1 Γ2 : context) : context :=\n  match Γ2 with\n  | ctx_nil => Γ1\n  | Γ2', x : A => Γ1 ,, Γ2' , x : A\n  end%ctx\n\nwhere \"G1 ,, G2\" := (ctx_app G1 G2) : context_scope.\n\nNotation \"⟦ v /' x ⟧ G\" :=\n  (subst_context v x G)\n    ( at level 56, v at level 50, x at level 0\n    , right associativity) : context_scope.\n\nDeclare Scope expr_scope.\nDelimit Scope expr_scope with expr.\nBind Scope expr_scope with expr.\n\nNotation \"` x\" := (e_var_f x)\n  (at level 0, x at level 0, no associativity) : expr_scope.\nNotation \"↑ x\" := (e_var_b x)\n  (at level 0, x at level 0, no associativity) : expr_scope.\n\nNotation \"[ v /' x ] e\" :=\n  (subst_expr v x e)\n    ( at level 49, v at level 50, x at level 0\n    , right associativity) : expr_scope.\n\nNotation \"e ^` x\" := (open_expr_wrt_expr e (e_var_f x))\n  (at level 48, left associativity) : expr_scope.\n\nNotation \"e1 ^^ e2\" := (open_expr_wrt_expr e1 e2)\n  (at level 48, left associativity) : expr_scope.\n\nNotation \"⋆\" := (e_kind k_star)\n  (at level 0, no associativity) : expr_scope.\n\nNotation \"◻\" := (e_kind k_box) (at level 0, no associativity) : expr_scope.\n\nNotation \"⧼ k ⧽\" := (e_kind k)\n  (at level 0, no associativity) : expr_scope.\n\nNotation \"'λ_' A , e : B\" :=\n  (e_abs A (b_anno e B))\n    (at level 50, A at level 50, e at level 50, no associativity) : expr_scope.\n\nNotation \"'Λ' A , e : B\" :=\n  (e_bind A (b_anno e B))\n    (at level 50, A at level 50, e at level 50, no associativity) : expr_scope.\n\nNotation \"G ⊢ e1 <: e2 ⇒ A\" := (busub G e1 e2 d_infer A)\n    (at level 65, e1 at level 50, e2 at level 50, no associativity) : type_scope.\n\nNotation \"G ⊢ e ⇒ A\" := (busub G e e d_infer A)\n    (at level 65, e at level 50, no associativity) : type_scope.\n\nNotation \"G ⊢ e1 <: e2 ⇐ A\" := (busub G e1 e2 d_check A)\n    (at level 65, e1 at level 50, e2 at level 50, no associativity) : type_scope.\n\nNotation \"G ⊢ e ⇐ A\" := (busub G e e d_check A)\n    (at level 65, e at level 50, no associativity) : type_scope.\n\nNotation \"G ⊢ A ⋅ e ⇒ B\" :=\n  (infer_app G A e B)\n    ( at level 65, A at level 50, e at level 50\n    , no associativity) : type_scope.\n\nNotation \"G ⊢ A ⟼ B\" := (greduce G A B)\n    (at level 65, A at level 50, no associativity) : type_scope.\n\n(* 'varVdash' *)\nNotation \"⫦ G\" := (bwf_context G)\n    (at level 65, no associativity) : type_scope.\n\nOpen Scope context_scope.\nOpen Scope expr_scope.\n\nDeclare Scope obindd_scope.\nDelimit Scope obindd_scope with dob.\nBind Scope obindd_scope with obindd.\n\nNotation \"x :? A\" :=\n  (dob_bind x A) (at level 52, no associativity) : obindd_scope.\n\nDeclare Scope dwork_scope.\nDelimit Scope dwork_scope with dwork.\nBind Scope dwork_scope with dwork.\n\nNotation \"ob ⊢? e1 <: e2 ⇐ B\" :=\n  (dw_check ob e1 e2 B)\n    ( at level 55, e1 at level 50, e2 at level 50\n    , no associativity) : dwork_scope.\n\nNotation \"ob ⊢? e ⇐ B\" :=\n  (dw_check ob e e B)\n    ( at level 55, e at level 50, no associativity) : dwork_scope.\n\nNotation \"e1 <: e2 ⇐ A\" :=\n  (dw_check dob_none e1 e2 A)\n    (at level 55, e2 at level 50, no associativity) : dwork_scope.\n\nNotation \"e ⇐ A\" :=\n  (dw_check dob_none e e A) (at level 55, no associativity) : dwork_scope.\n\nNotation \"e1 <: e2 ⇒ wl\" :=\n  (dw_infer e1 e2 wl)\n    (at level 55, e2 at level 50, no associativity) : dwork_scope.\n\nNotation \"e ⇒ wl\" :=\n  (dw_infer e e wl)\n    (at level 55, no associativity) : dwork_scope.\n\nNotation \"A ⋅ e ⇒ wl\" :=\n  (dw_infer_app A e wl)\n    ( at level 55, e at level 50\n    , no associativity) : dwork_scope.\n\nNotation \"A ⟼ wl\" :=\n  (dw_reduce A wl)\n    (at level 55, no associativity) : dwork_scope.\n\n(*\nNotation \"e1 <: e2 ⇐ A\" :=\n  (dw_check dob_none e1 e2 A)\n    (at level 55, e2 at level 50, no associativity) : dwork_scope.\n *)\n\nNotation \"A ≲ B\" :=\n  (dw_compact A B)\n    (at level 55, no associativity) : dwork_scope.\n\nDeclare Scope dworklist_scope.\nDelimit Scope dworklist_scope with dwl.\nBind Scope dworklist_scope with dworklist.\n\nNotation \"G ⊨ w\" :=\n  (dwl_cons G w) (at level 58, left associativity) : dworklist_scope.\n\nNotation \"G ,' x : A\" :=\n  (dwl_bind G x A) (at level 58, x at level 0, left associativity) : dworklist_scope.\n\nOpen Scope dworklist_scope.\nOpen Scope dwork_scope.\nOpen Scope obindd_scope.\n", "meta": {"author": "VinaLx", "repo": "dependent-worklist-inference", "sha": "1d20a49f89509864c63ffc455d667f04818fe97e", "save_path": "github-repos/coq/VinaLx-dependent-worklist-inference", "path": "github-repos/coq/VinaLx-dependent-worklist-inference/dependent-worklist-inference-1d20a49f89509864c63ffc455d667f04818fe97e/src-lite/decl_notations.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.20615084450333376}}
{"text": "Require Import CSPEC.\nRequire Import MailboxAPI.\nRequire Import MailServerAPI.\n\nModule MailboxTmpAbsState <: State.\n\n  Record state_rec := mk_state {\n    tmpdir : MailServerState.dir_contents;\n    maildir : MailServerState.dir_contents;\n    locked : bool;\n  }.\n\n  Definition State := state_rec.\n  Definition initP (s : State) := locked s = false /\\\n                              tmpdir s = FMap.empty /\\\n                              maildir s = FMap.empty.\n\nEnd MailboxTmpAbsState.\nModule MailboxTmpAbsHState := HState MailboxTmpAbsState UserIdx.\n\n\nModule MailboxTmpAbsAPI <: Layer MailboxOp MailboxTmpAbsState.\n\n  Import MailboxOp.\n  Import MailboxTmpAbsState.\n\n\n  Inductive xstep : forall T, Op T -> nat -> State -> T -> State -> list event -> Prop :=\n  | StepDeliverOK : forall m tmp tmp' mbox tid fn lock,\n    ~ FMap.In fn mbox ->\n    xstep (Deliver m) tid\n      (mk_state tmp mbox lock)\n      true\n      (mk_state tmp' (FMap.add fn m mbox) lock)\n      nil\n  | StepDeliverErr : forall m tmp tmp' mbox tid lock,\n    xstep (Deliver m) tid\n      (mk_state tmp mbox lock)\n      false\n      (mk_state tmp' mbox lock)\n      nil\n  | StepList : forall tmp mbox tid r lock,\n    FMap.is_permutation_key r mbox ->\n    xstep List tid\n      (mk_state tmp mbox lock)\n      r\n      (mk_state tmp mbox lock)\n      nil\n  | StepReadOK : forall fn tmp mbox tid m lock,\n    FMap.MapsTo fn m mbox ->\n    xstep (Read fn) tid\n      (mk_state tmp mbox lock)\n      (Some m)\n      (mk_state tmp mbox lock)\n      nil\n  | StepReadNone : forall fn tmp mbox tid lock,\n    ~ FMap.In fn mbox ->\n    xstep (Read fn) tid\n      (mk_state tmp mbox lock)\n      None\n      (mk_state tmp mbox lock)\n      nil\n  | StepDelete : forall fn tmp mbox tid lock,\n    xstep (Delete fn) tid\n      (mk_state tmp mbox lock)\n      tt\n      (mk_state tmp (FMap.remove fn mbox) lock)\n      nil\n  | StepLock : forall tmp mbox tid,\n    xstep Lock tid\n      (mk_state tmp mbox false)\n      tt\n      (mk_state tmp mbox true)\n      nil\n  | StepUnlock : forall tmp mbox tid lock,\n    xstep Unlock tid\n      (mk_state tmp mbox lock)\n      tt\n      (mk_state tmp mbox false)\n      nil\n\n  | StepExt : forall s tid `(extop : _ T) r,\n    xstep (Ext extop) tid\n      s\n      r\n      s\n      (Event (extop, r) :: nil)\n  .\n\n  Definition step := xstep.\n\n  Definition initP := initP.\n\nEnd MailboxTmpAbsAPI.\nModule MailboxTmpAbsHAPI := HLayer MailboxOp MailboxTmpAbsState MailboxTmpAbsAPI UserIdx.\n", "meta": {"author": "mit-pdos", "repo": "cspec", "sha": "074e11f5c7758fd0f5624f0466dd23244f9112c4", "save_path": "github-repos/coq/mit-pdos-cspec", "path": "github-repos/coq/mit-pdos-cspec/cspec-074e11f5c7758fd0f5624f0466dd23244f9112c4/src/Mail/MailboxTmpAbsAPI.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20615084450333368}}
{"text": "Require Export Nat.\nRequire Export ch2o.prelude.orders.\nRequire Export ch2o.prelude.nmap.\nRequire Export ch2o.prelude.stringmap.\nRequire Export ch2o.memory.memory_basics.\nRequire Export ch2o.abstract_c.architectures.\nRequire Export ch2o.abstract_c.interpreter.\nRequire Export ch2o.abstract_c.frontend_sound.\nRequire Export ch2o.core_c.smallstep.\nRequire Export ch2o.core_c.restricted_smallstep.\nRequire Export ch2o.core_c.expression_eval_smallstep.\nRequire Export one_local.\n\nDefinition get_right{A B}(v: A + B)(H: match v with inl _ => False | inr _ => True end): B.\ndestruct v.\nelim H.\nexact b.\nDefined.\n\nOpen Local Scope string_scope.\n\nDefinition A: architecture := {|\n  arch_sizes := architectures.lp64;\n  arch_big_endian := false;\n  arch_char_signedness := Signed;\n  arch_alloc_can_fail := false\n|}.\nNotation K := (arch_rank A).\n\nNotation M := (error (frontend_state K) string).\n\nLemma alloc_program_ok: match alloc_program (K:=K) decls empty with inl _ => False | inr _ => True end.\nexact I.\nQed.\n\nDefinition alloc_program_result: frontend_state K.\neapply snd.\neapply get_right.\napply alloc_program_ok.\nDefined.\n\nCompute (stringmap_to_list (env_t (to_env alloc_program_result))).\nCompute (stringmap_to_list (env_f (to_env alloc_program_result))).\n\nDefinition to_core_c_program: M (env K * funenv K * state K) :=\n  _ ← alloc_program decls;\n  Δg ← gets to_globals;\n  '(_,σs,σ,_) ← error_of_option (Δg !! \"main\"≫= maybe4 Fun)\n    (\"function `main` undeclared`\");\n  guard (σ = sintT%T ∨ σ = uintT%T) with\n    (\"function `main` should have return type `int`\");\n  Γ ← gets to_env;\n  δ ← gets to_funenv;\n  m ← gets to_mem;\n  mret (Γ, δ, initial_state m \"main\" []).\n\nDefinition to_core_c_program_result: string + env K * funenv K * state K :=\n  error_eval to_core_c_program ∅.\n\nLemma to_core_c_program_ok: match to_core_c_program_result with inl _ => False | inr _ => True end.\nexact I.\nQed.\n\nDefinition core_c_program: env K * funenv K * state K := get_right to_core_c_program_result to_core_c_program_ok.\n\nDefinition Γ: env K := to_env alloc_program_result.\nDefinition δ: funenv K := to_funenv alloc_program_result.\nDefinition m0: mem K := to_mem alloc_program_result.\nDefinition S0 := initial_state m0 \"main\" [].\n\nLemma alloc_program_eq: alloc_program decls empty = mret () alloc_program_result.\nreflexivity.\nQed.\n\nLemma Γ_valid: ✓ Γ.\napply alloc_program_valid with (1:=alloc_program_eq).\nQed.\n\nLemma δ_valid: ✓{Γ,'{m0}} δ.\napply alloc_program_valid with (1:=alloc_program_eq).\nQed.\n\nLemma m0_valid: ✓{Γ} m0.\napply alloc_program_valid with (1:=alloc_program_eq).\nQed.\n\nLemma mem_lock_cmap (Γ: env K) o (m: indexmap (cmap_elem K (pbit K))):\n  mem_lock Γ (addr_top o sintT%BT) (CMap m) =\n  CMap (alter (cmap_elem_map (ctree_map pbit_lock)) o m).\nreflexivity.\nQed.\n\nLemma zip_with_pbit_unlock_if_list_fmap_pbit_lock (l: list (pbit K)):\n  Forall (λ γb, Some Writable ⊆ pbit_kind γb) l ->\n  zip_with pbit_unlock_if (pbit_lock <$> l) (replicate (Datatypes.length l) true) = l.\ninduction l; intros; try reflexivity.\nsimpl.\nunfold fmap in IHl.\nrewrite IHl.\n- destruct a.\n  simpl.\n  inversion H; subst.\n  destruct tagged_perm.\n  + destruct l0; simpl in *.\n    * unfold perm_kind in H2.\n      elim H2.\n    * reflexivity.\n  + elim H2.\n- inversion H; subst; assumption.\nQed.\n\nLemma mem_unlock_lock_singleton (Γ: env K) o (m: mem K):\n  ✓{Γ} m ->\n  '{m} !! o = Some (sintT%T, false) ->\n  mem_writable Γ (addr_top o sintT%BT) m ->\n  mem_unlock\n    (lock_singleton Γ (addr_top o sintT%BT))\n    (mem_lock Γ (addr_top o sintT%BT) m) = m.\ndestruct m as [m].\nintros Hvalid. intros.\ndestruct Hvalid as [Hvalid1 [Hvalid2 Hvalid3]].\nsimpl in *.\nassert (forall (m1: indexmap (cmap_elem K (pbit K))) m2, m1 = m2 -> CMap m1 = CMap m2). { intros; congruence. }\napply H1.\napply map_eq.\nintro i.\nrewrite lookup_merge.\n2:reflexivity.\ndestruct (decide (i = o)).\n- subst.\n  rewrite lookup_singleton.\n  rewrite lookup_alter.\n  destruct H0 as [w [Hw H'w]].\n  simpl in *.\n  unfold cmap_lookup in Hw.\n  simpl in Hw.\n  case_eq (m !! o); intros; rewrite H0 in Hw; try discriminate.\n  destruct c; try discriminate.\n  simpl in Hw.\n  injection Hw; clear Hw; intros; subst.\n  simpl.\n  rewrite lookup_fmap in H.\n  rewrite H0 in H.\n  simpl in H.\n  injection H; clear H; intros; subst.\n  destruct w; try discriminate.\n  destruct b0; try discriminate.\n  destruct i; try discriminate.\n  simpl in H.\n  injection H; clear H; intros; subst.\n  clear H1.\n  simpl.\n  pose proof H0.\n  apply Hvalid3 in H0.\n  destruct H0 as [τ [Ho1 [Ho2 [Ho3 Ho4]]]].\n  simpl in *.\n  unfold typed in Ho1.\n  unfold index_typed in Ho1.\n  destruct Ho1 as [β Ho1].\n  rewrite lookup_fmap in Ho1.\n  rewrite H in Ho1.\n  simpl in Ho1.\n  injection Ho1; clear Ho1; intros; subst.\n  simpl in Ho3.\n  unfold typed in Ho3.\n  unfold ctree_typed in Ho3.\n  simpl in Ho3.\n  inversion Ho3; subst.\n  rewrite fmap_length.\n  assert (Datatypes.length l = 32). {\n    rewrite H4.\n    reflexivity.\n  }\n  rewrite H0.\n  assert (natmap.to_bools 32\n              {|\n              mapset.mapset_car := natmap.list_to_natmap\n                                     [Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some (); Some (); \n                                     Some (); Some ()] |} =\n    [true; true; true; true; true; true; true; true;\n     true; true; true; true; true; true; true; true;\n     true; true; true; true; true; true; true; true;\n     true; true; true; true; true; true; true; true]).\n  reflexivity.\n  rewrite H1.\n  pose proof (zip_with_pbit_unlock_if_list_fmap_pbit_lock l H'w).\n  rewrite H0 in H5.\n  simpl in H5.\n  rewrite H5.\n  reflexivity.\n- rewrite lookup_singleton_ne; try congruence.\n  rewrite lookup_alter_ne; try congruence.\nQed.\n\nLemma lockset_union_right_id (Ω: lockset): Ω ∪ ∅ = Ω.\napply lockset_eq.\nintros.\nsolve_elem_of.\nQed.\n\nLemma cons_snoc0 {A} x (xs: list A): exists y ys, x::xs = (ys ++ [y])%list.\nrevert x.\ninduction xs.\n- intros.\n  exists x.\n  exists [].\n  reflexivity.\n- intros.\n  destruct (IHxs a) as [y [ys Hyys]].\n  rewrite Hyys.\n  exists y.\n  exists (x::ys).\n  reflexivity.\nQed.\n\nLemma expr_eval_pure (Γ: env K) ρ e1 m e2 m2 (E: ectx K) ν:\n  Γ\\ ρ ⊢ₕ e1, m ⇒ e2, m2 ->\n  ⟦ subst E e1 ⟧ Γ ρ m = Some ν ->\n  m2 = m.\nintros.\napply expr_eval_subst in H0.\ndestruct H0 as [ν' [Hν' _]].\napply symmetry.\napply ehstep_expr_eval_mem with (1:=H) (2:=Hν').\nQed.\n\nLemma expr_eval_complete_subst (Γ: env K) ρ e1 m e2 m2 (E: ectx K) ν:\n  Γ\\ ρ ⊢ₕ e1, m ⇒ e2, m2 ->\n  ⟦ subst E e1 ⟧ Γ ρ m = Some ν ->\n  ⟦ subst E e2 ⟧ Γ ρ m = Some ν.\nintros.\npose proof H0.\napply expr_eval_subst in H0.\ndestruct H0 as [ν' [Hν' _]].\nassert (m = m2). {\n  apply ehstep_expr_eval_mem with (1:=H) (2:=Hν').\n}\nsubst m2.\nassert (⟦ e2 ⟧ Γ ρ m = Some ν'). {\n  apply ehstep_expr_eval with (1:=H) (2:=Hν') (3:=Hν').\n}\nrewrite subst_preserves_expr_eval with (e4:=e2) in H1.\n- assumption.\n- congruence.\nQed.\n\nLemma expr_eval_call_None {Γ: env K} {ρ m} {E: ectx K} {f args ν}:\n  ⟦ subst E (ECall f args) ⟧ Γ ρ m = Some ν -> False.\nintros.\napply expr_eval_subst in H.\ndestruct H.\ndestruct H.\nsimpl in H.\ndiscriminate.\nQed.\n\nLemma expr_eval_no_locks (Γ: env K) ρ m Ω ν ν':\n  ⟦ %#{Ω} ν ⟧ Γ ρ m = Some ν' -> (%#{Ω} ν = %# ν')%E.\nintros.\nsimpl in H.\nunfold mguard in H.\nunfold option_guard in H.\ndestruct (lockset_eq_dec Ω ∅); congruence.\nQed.\n\nLemma assign_pure (Γ: env K) δ ρ S0 S:\n  Γ\\ δ\\ ρ ⊢ₛ S0 ⇒* S ->\n  is_undef_state S ->\n  forall k el er m νl νr,\n  S0 = State k (Expr (el ::= er)) m ->\n  ⟦ el ⟧ Γ (rlocals ρ k) m = Some νl ->\n  ⟦ er ⟧ Γ (rlocals ρ k) m = Some νr ->\n  Γ\\ δ\\ ρ ⊢ₛ State k (Expr (%# νl ::= %# νr)) m ⇒* S.\ninduction 1; intros; subst. {\n  elim (is_Some_None H).\n}\ninversion H; clear H; subst.\n- (* head reduction *)\n  destruct E.\n  + (* empty evaluation context *)\n    simpl in *.\n    subst.\n    inversion H8; subst.\n    simpl in *.\n    unfold mguard in H4.\n    unfold option_guard in H4.\n    case_eq (lockset_eq_dec Ω2 ∅); intros.\n    * rewrite H in H4.\n      injection H4; clear H4; intros; subst.\n      unfold mguard in H3; unfold option_guard in H3.\n      case_eq (lockset_eq_dec Ω1 ∅); intros.\n      -- rewrite H2 in H3.\n         injection H3; clear H3; intros; subst.\n         clear H H2.\n         eapply rtc_l.\n         ++ eapply rcstep_expr_head with (E:=[]).\n            eassumption.\n         ++ eassumption.\n      -- rewrite H2 in H3; discriminate.\n    * rewrite H in H4; discriminate.\n  + (* nonempty evaluation context *)\n    destruct (cons_snoc0 e E) as [e' [E' H']].\n    rewrite H' in *.\n    clear H' e E.\n    rewrite subst_snoc in H6.\n    destruct e'; try discriminate.\n    * (* lhs *)\n      simpl in H6.\n      injection H6; clear H6; intros; subst.\n      rewrite subst_snoc in H0.\n      rewrite subst_snoc in IHrtc.\n      simpl in *.\n      assert (m2 = m). {\n        apply expr_eval_pure with (1:=H8) (2:=H3).\n      }\n      subst m2.\n      apply expr_eval_complete_subst with (1:=H8) in H3.\n      apply IHrtc with (3:=H3) (4:=H4); trivial.\n    * (* rhs *)\n      simpl in *.\n      injection H6; clear H6; intros; subst.\n      rewrite subst_snoc in H0.\n      rewrite subst_snoc in IHrtc.\n      simpl in *.\n      assert (m2 = m). {\n        apply expr_eval_pure with (1:=H8) (2:=H4).\n      }\n      subst m2.\n      apply expr_eval_complete_subst with (1:=H8) in H4.\n      apply IHrtc with (3:=H3) (4:=H4); trivial.\n- (* function call *)\n  destruct E.\n  + (* E = [] *)\n    simpl in *.\n    discriminate.\n  + destruct (cons_snoc0 e0 E) as [e' [E' H']].\n    rewrite H' in *.\n    clear H' e0 E.\n    rewrite subst_snoc in H6.\n    destruct e'; try discriminate; simpl in *; injection H6; clear H6; intros; subst.\n    * (* lhs *)\n      elim (expr_eval_call_None H3).\n    * (* rhs *)\n      elim (expr_eval_call_None H4).\n- (* undef *)\n  destruct E.\n  * (* E = [] *)\n    simpl in *.\n    subst.\n    eapply rtc_l.\n    2: eassumption.\n    inversion H8; subst.\n    destruct H5.\n    destruct H7.\n    rewrite expr_eval_no_locks with (1:=H3) in *.\n    rewrite expr_eval_no_locks with (1:=H4) in *.\n    apply rcstep_expr_undef with (E:=[]).\n    -- assumption.\n    -- assumption.\n  * (* E <> [] *)\n    destruct (cons_snoc0 e0 E) as [e' [E' H']].\n    rewrite H' in *.\n    clear H' e0 E.\n    rewrite subst_snoc in H5.\n    destruct e'; try discriminate; simpl in *; injection H5; clear H5; intros; subst.\n    -- (* lhs *)\n       destruct expr_eval_subst_ehstep with (1:=H3) (2:=H8).\n       destruct H.\n       elim H9.\n       eapply ehsafe_step.\n       apply H.\n    -- (* rhs *)\n       destruct expr_eval_subst_ehstep with (1:=H4) (2:=H8).\n       destruct H.\n       elim H9.\n       eapply ehsafe_step.\n       apply H.\nQed.\n\nLemma assign_pure' (Γ: env K) δ ρ S k el er m νl νr:\n  Γ\\ δ\\ ρ ⊢ₛ (State k (Expr (el ::= er)) m) ⇒* S ->\n  ⟦ el ⟧ Γ (rlocals ρ k) m = Some νl ->\n  ⟦ er ⟧ Γ (rlocals ρ k) m = Some νr ->\n  (Γ\\ δ\\ ρ ⊢ₛ State k (Expr (%# νl ::= %# νr)) m ⇒* S ->\n   ¬ is_undef_state S) ->\n  ¬ is_undef_state S.\nintros.\nintro.\napply H2 with (2:=H3).\napply assign_pure with (1:=H) (2:=H3) (4:=H0) (5:=H1).\nreflexivity.\nQed.\n\nLemma Expr_pure (Γ: env K) δ ρ S0 S:\n  Γ\\ δ\\ ρ ⊢ₛ S0 ⇒* S ->\n  is_undef_state S ->\n  forall k e m ν,\n  S0 = State k (Expr e) m ->\n  ⟦ e ⟧ Γ (rlocals ρ k) m = Some ν ->\n  Γ\\ δ\\ ρ ⊢ₛ State k (Expr (%# ν)) m ⇒* S.\nintro Hrtc.\npose proof Hrtc.\ninduction H; intros; subst. {\n  elim (is_Some_None H).\n}\nassert (forall Ω ν', e = (%#{Ω} ν')%E -> Γ\\ δ\\ ρ ⊢ₛ State k (Expr (%# ν)) m ⇒* z). {\n  intros.\n  subst.\n  simpl in H3.\n  unfold mguard in H3.\n  unfold option_guard in H3.\n  destruct (lockset_eq_dec Ω ∅).\n  2: discriminate.\n  injection H3; clear H3; intros; subst.\n  assumption.\n}\nclear Hrtc.\ninversion H; clear H; subst; try (eapply H2; reflexivity); clear H2.\n- (* head reduction *)\n  assert (m2 = m). {\n    apply expr_eval_pure with (1:=H8) (2:=H3).\n  }\n  subst m2.\n  eapply IHrtc; try trivial.\n  apply expr_eval_complete_subst with (1:=H8) (2:=H3).\n- (* function call *)\n  elim (expr_eval_call_None H3).\n- elim H9.\n  eapply expr_eval_subst_ehsafe; eassumption.\nQed.\n\nLemma Expr_pure' (Γ: env K) δ ρ S k e m ν:\n  Γ\\ δ\\ ρ ⊢ₛ (State k (Expr e) m) ⇒* S ->\n  ⟦ e ⟧ Γ (rlocals ρ k) m = Some ν ->\n  (Γ\\ δ\\ ρ ⊢ₛ State k (Expr (%# ν)) m ⇒* S ->\n   ¬ is_undef_state S) ->\n  ¬ is_undef_state S.\nintros.\nintro.\napply H1.\n2: assumption.\napply Expr_pure with (1:=H) (2:=H2) (4:=H0).\nreflexivity.\nQed.\n\nLemma call_main_safe: forall S, rtc (cstep Γ δ) (State [] (Call \"main\" []) ∅) S -> ~ is_undef_state S.\nintros.\napply csteps_rcsteps in H.\ninv_rcsteps H. {\n  inversion 1.\n  simpl in H.\n  elim (is_Some_None H).\n}\ninversion H; clear H; subst.\nassert (match Some s with None => s | Some s => s end = s). {\n  reflexivity.\n}\nrewrite <- H6 in H.\nsimpl in H.\nsubst.\nclear H6.\ndestruct os; simpl in H8; try discriminate; clear H8.\nclear H7.\ninversion H1; subst; clear H1. {\n  inversion 1.\n  simpl in H.\n  elim (is_Some_None H).\n}\nsimpl in H.\nOpaque mem_alloc.\ninv_rcstep.\nclear H y.\nset (m1:=mem_alloc Γ o false perm_full (val_new Γ sintT%BT) ∅).\nassert (H: Γ\\ δ\\ [] ⊢ₛ State [CLocal o sintT%BT; CParams \"main\" []]\n                   (Stmt ↘\n                      (var 0 ::= cast{sintT%BT} (# intV{sintT} 3) ;;\n                       ret (cast{sintT%BT} (load (var 0)))))\n                   m1 ⇒* S -> ¬ is_undef_state S).\n2: apply H; assumption.\nclear H0; intros.\nassert (m1_valid: ✓{Γ} m1). {\n  apply mem_alloc_valid' with (τ:=sintT%T).\n  - apply Γ_valid.\n  - apply cmap_empty_valid'.\n  - unfold dom.\n    unfold cmap_dom.\n    simpl.\n    rewrite dom_empty_L.\n    apply not_elem_of_empty.\n  - apply perm_full_valid.\n  - apply perm_full_mapped.\n  - rewrite val_new_base. simpl.\n    apply VBase_typed.\n    constructor.\n    + constructor.\n    + congruence.\n}\nassert (typeof_o: '{m1} !! o = Some (sintT%T, false)). {\n  unfold m1.\n  rewrite mem_alloc_memenv_of with (Δ:=∅) (τ:=sintT%T).\n  - rewrite lookup_insert. reflexivity.\n  - apply Γ_valid.\n  - apply val_new_typed.\n    + apply Γ_valid.\n    + constructor.\n      constructor.\n}\nassert (a_typed: (Γ, '{m1}) ⊢ addr_top o sintT%BT : sintT%PT). {\n  constructor.\n  - unfold typed.\n    unfold index_typed.\n    exists false.\n    apply typeof_o.\n  - constructor.\n    constructor.\n  - constructor.\n  - reflexivity.\n  - constructor.\n    simpl.\n    lia.\n  - apply Nat.divide_0_r.\n  - constructor.\n}\nassert (a_writable: mem_writable Γ (addr_top o sintT%BT) m1). {\n  apply mem_alloc_writable_top with (Δ:=∅).\n  - apply Γ_valid.\n  - rewrite val_new_base. simpl.\n    apply VBase_typed.\n    constructor.\n    + constructor.\n    + congruence.\n  - rewrite perm_kind_full.\n    reflexivity.\n}\nassert (intV_3_typed: (Γ, '{m1}) ⊢ (intV{sintT} 3 : val K) : (sintT%BT : type K)). {\n  apply VBase_typed.\n  constructor.\n  constructor.\n  - unfold int_lower. simpl.\n    lia.\n  - unfold int_upper. simpl. lia.\n}\ninv_rcsteps H. {\n  inversion 1.\n  elim (is_Some_None H).\n}\ninv_rcstep.\nclear y.\ninv_rcsteps H1. {\n  inversion 1.\n  elim (is_Some_None H).\n}\ninv_rcstep.\nclear y.\neapply assign_pure' with (1:=H1); clear H1. {\n  simpl.\n  reflexivity.\n} {\n  simpl.\n  rewrite option_guard_True.\n  2: reflexivity.\n  simpl.\n  reflexivity.\n}\nintros.\nunfold int_cast in H.\nunfold arch_int_env in H.\nunfold int_pre_cast in H.\nsimpl in H.\ninversion H; clear H; subst. {\n  inversion 1.\n  elim (is_Some_None H).\n}\ninv_rcstep; clear y.\nFocus 2. {\n  elim H1; clear H0 H1 H2.\n  eapply ehsafe_step.\n  constructor.\n  - assumption.\n  - constructor.\n    + constructor.\n      * unfold int_lower.\n        simpl.\n        lia.\n      * unfold int_upper.\n        unfold int_precision.\n        simpl.\n        lia.\n    + reflexivity.\n}\nUnfocus.\ninv_ehstep.\ninversion H10; clear H10; subst.\nunfold val_cast in *.\nsimpl in *.\nunfold int_cast in *.\nsimpl in *.\nunfold int_pre_cast in *.\nsimpl in *.\nclear H H9.\ninv_rcsteps H1. {\n  inversion 1.\n  elim (is_Some_None H).\n}\ninv_rcstep.\nclear y.\nrewrite lockset_union_right_id in H1.\nrewrite lockset_union_right_id in H1.\nset (m2:=<[addr_top o sintT%BT:=intV{sintT} 3]{Γ}>m1).\nassert (Γ\\ δ\\ [] ⊢ₛ State\n                 [CStmt (□ ;; ret (cast{sintT%BT} (load (var 0))));\n                 CLocal o sintT%BT; CParams \"main\" []]\n                 (Stmt ↗ (var 0 ::= cast{sintT%BT} (# intV{sintT} 3)))\n                 (mem_unlock (lock_singleton Γ (addr_top o sintT%BT))\n                    (mem_lock Γ (addr_top o sintT%BT)\n                       m2)) ⇒* S).\nexact H1.\nclear H1.\nassert (m2_valid: ✓{Γ} m2). {\n  apply mem_insert_valid' with (τ:=sintT%T).\n  - apply Γ_valid.\n  - apply m1_valid.\n  - apply a_typed.\n  - apply a_writable.\n  - apply intV_3_typed.\n}\nassert (typeof_o_m2: '{m2} !! o = Some (sintT%T, false)). {\n  unfold m2.\n  rewrite mem_insert_memenv_of with (Δ:='{m1}) (τ:=sintT%T).\n  - apply typeof_o.\n  - apply Γ_valid.\n  - apply m1_valid.\n  - apply a_typed.\n  - apply a_writable.\n  - apply intV_3_typed.\n}\nassert (a_writable_m2: mem_writable Γ (addr_top o sintT%BT) m2). {\n  unfold m2.\n  apply mem_insert_writable with (Δ:='{m1}) (τ2:=sintT%T); try assumption.\n  - apply Γ_valid.\n  - left; reflexivity.\n}\nrewrite mem_unlock_lock_singleton in H; try assumption.\ninv_rcsteps H. {\n  inversion 1.\n  elim (is_Some_None H).\n}\ninv_rcstep.\nclear y.\ninv_rcsteps H1. {\n  inversion 1.\n  elim (is_Some_None H).\n}\ninv_rcstep.\nclear y.\neapply Expr_pure' with (1:=H1); clear H1. {\n  simpl.\n  rewrite option_guard_True.\n  + unfold m2.\n    simpl.\n    rewrite mem_lookup_insert with (Δ:='{m1}) (τ:=sintT%T); try assumption.\n    * simpl.\n      reflexivity.\n    * apply Γ_valid.\n    * constructor.\n  + apply mem_insert_forced.\n}\nintros.\nunfold int_cast in H.\nunfold arch_int_env in H.\nunfold int_pre_cast in H.\nsimpl in H.\ninv_rcsteps H. {\n  inversion 1.\n  elim (is_Some_None H).\n}\ninv_rcstep.\nrewrite mem_unlock_empty in H1.\ninv_rcsteps H1. {\n  inversion 1.\n  elim (is_Some_None H).\n}\ninv_rcstep.\ninv_rcsteps H1. {\n  inversion 1.\n  elim (is_Some_None H).\n}\ninv_rcstep.\n  inv_rcsteps H1. {\n  inversion 1.\n  elim (is_Some_None H).\n}\ninv_rcstep.\ninv_rcsteps H1. {\n  inversion 1.\n  elim (is_Some_None H).\n}\ninv_rcstep.\nQed.\n\nGoal forall S, rtc (cstep Γ δ) S0 S -> ~ is_undef_state S.\nintros.\napply call_main_safe with (1:=H).\nQed.\n", "meta": {"author": "btj", "repo": "proofs-against-ch2o", "sha": "e7005477b916836d4243c43fbc939111af86446e", "save_path": "github-repos/coq/btj-proofs-against-ch2o", "path": "github-repos/coq/btj-proofs-against-ch2o/proofs-against-ch2o-e7005477b916836d4243c43fbc939111af86446e/one_local_proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20615084450333368}}
{"text": "(** * verif_first_cursor.v: Correctness proof of Trie.first_cursor *)\nRequire Import VST.floyd.proofauto.\nRequire Import VST.floyd.library.\nRequire Import VST.msl.iter_sepcon.\nRequire Import VST.msl.wand_frame.\nRequire Import DB.common.\nRequire Import DB.tactics.\nRequire Import DB.lemmas.\n\nRequire Import DB.functional.bordernode.\nRequire Import DB.functional.keyslice.\n\nRequire Import DB.representation.string.\nRequire Import DB.representation.key.\nRequire Import DB.representation.btree.\nRequire Import DB.representation.trie.\n\nRequire Import DB.specs.\n\nImport Coq.Lists.List.ListNotations.\n\nDefinition Gprog : funspecs :=\n  ltac:(with_library prog [\n          UTIL_GetNextKeySlice_spec;\n          surely_malloc_spec;\n          BN_GetPrefixValue_spec;\n          BN_GetSuffixValue_spec;\n          BN_TestSuffix_spec;\n          BN_GetLink_spec;\n          BN_HasSuffix_spec;\n          BN_CompareSuffix_spec;\n          move_key_spec; new_key_spec; free_key_spec;\n          push_cursor_spec; pop_cursor_spec;\n          Imake_cursor_spec; Iget_value_spec; Iget_key_spec; Ifree_cursor_spec; Ifirst_cursor_spec;\n          bordernode_next_cursor_spec;\n          strict_first_cursor_spec\n       ]).\n\nLemma body_strict_first_cursor: semax_body Vprog Gprog f_strict_first_cursor strict_first_cursor_spec.\nProof.\n  start_function.\n  destruct t as [addr tableform listform].\n  unfold Trie.trie_rep; fold Trie.trie_rep.\n  inv H.\n  Intros.\n  forward_call (tableform, addr).\n  Intros pnode_cursor.\n  forward_call (BTree.first_cursor tableform, pnode_cursor, tableform, addr, v_ret_value, Tsh).\n  { split; [apply BTree.first_cursor_abs; assumption | auto ]. }\n  forward_if.\n  - if_tac in H; simplify.\n    unfold BTree.get_value in H0; simplify.\n    assert (BTree.get_key (BTree.first_cursor tableform) tableform = Some k) by\n        (unfold BTree.get_key; rewrite H1; reflexivity).\n    assert (BTree.key_rel k (BTree.first_cursor tableform) tableform). {\n      apply BTree.get_key_rel.\n      - apply BTree.first_cursor_abs.\n        assumption.\n      - assumption.\n    }\n    rename v into pbnode.\n    assert (exists bnode, BTree.Flattened.get (BTree.Flattened.first_cursor listform) listform = Some (k, (pbnode, bnode))). {\n      admit.\n    }\n    destruct H10 as [bnode ?].\n    assert (In (k, (pbnode, bnode)) listform) by (eapply BTree.Flattened.get_in_weak; eauto).\n    rewrite iter_in_wand with (a := (k, (pbnode, bnode))) by assumption.\n    Intros.\n    change ((Trie.bordernode_rep oo snd) (k, (pbnode, bnode))) with\n        (Trie.bnode_rep (pbnode, bnode)).\n    assert (Trie.bordernode_correct bnode). {\n        rewrite Forall_forall in H7.\n        apply H7 in H11.\n        simpl in H11.\n        assumption.\n      }\n    forward.\n    forward.\n    forward_call (bnode, pbnode, BorderNode.before_prefix 1).\n    {\n      simpl.\n      rep_lia.\n    }\n    assert (1 <= (BorderNode.cursor_to_int (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode)) <= Int.max_unsigned). {\n      pose proof (BorderNode.next_cursor_bnode_correct (BorderNode.before_prefix 1)\n                                                       bnode\n                                                       ltac:(simpl; rep_lia)).\n      unfold BorderNode.cursor_correct in H13.\n      destruct (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode); simpl; rep_lia.\n    }\n    forward_if.\n    + Trie.make_cursor_slice addr tableform listform\n                             bnode\n                             (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode)\n                             (vint (BorderNode.cursor_to_int (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode))).\n      forward_call ((Trie.trienode_of addr tableform listform,\n                     (BTree.first_cursor tableform),\n                     bnode,\n                     (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode)),\n                    addr,\n                    pnode_cursor,\n                    (vint (BorderNode.cursor_to_int (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode))),\n                    c, pc).\n      match goal with\n      | |- context rest[ ?P -* ?Q] =>\n          sep_apply (wand_frame_elim P Q)\n      end.\n      forward.\n      rewrite Trie.strict_first_cursor_equation.\n      unfold BTree.Flattened.get_value.\n      rewrite H10.\n      match_tac; simplify; simpl in H14; try rep_lia.\n      2: {\n        apply BorderNode.next_cursor_prefix_correct in H20.\n        congruence.\n      }\n      entailer!.\n    + forward_if.\n      * assert (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode = BorderNode.before_suffix). {\n          destruct (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode) eqn:Heqn'.\n          - simpl in *.\n            change (Int.add (Int.repr 4) (Int.repr 1)) with (Int.repr 5) in H15.\n            apply repr_inj_unsigned in H15; try rep_lia.\n            subst.\n            pose proof (BorderNode.next_cursor_bnode_correct (BorderNode.before_prefix 1)\n                                                       bnode\n                                                       ltac:(simpl; rep_lia)).\n            rewrite Heqn' in H15.\n            simpl in H15.\n            rep_lia.\n          - reflexivity.\n          - change (Int.add (Int.repr 4) (Int.repr 1)) with (Int.repr 5) in H15.\n            simpl in H15.\n            apply repr_inj_unsigned in H15; rep_lia.\n        }\n        Trie.make_cursor_slice addr tableform listform\n                               bnode\n                               (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode)\n                               (vint (BorderNode.cursor_to_int (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode))).\n        forward_call ((Trie.trienode_of addr tableform listform,\n                       (BTree.first_cursor tableform),\n                       bnode,\n                       (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode)),\n                      addr,\n                      pnode_cursor,\n                      (vint (BorderNode.cursor_to_int (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode))),\n                      c, pc).\n        forward_call (bnode, pbnode).\n        forward_if.\n        -- match goal with\n           | |- context rest[ ?P -* ?Q] =>\n             sep_apply (wand_frame_elim P Q)\n           end.\n           forward.\n           apply repr_inj_unsigned in H15; [ | rep_lia | rep_lia ].\n           rewrite Trie.strict_first_cursor_equation.\n           unfold BTree.Flattened.get_value.\n           destruct bnode as [? [[ | ] | ]]; if_tac in H17; simplify.\n           unfold BorderNode.get_suffix_pair in H22; simpl in H22; simplify.\n           rewrite H10.\n           rewrite H16.\n           simpl.\n           entailer!.\n        -- forward_call (bnode, pbnode, v_subindex, Tsh).\n           change (Int.add (Int.repr 4) (Int.repr 1)) with (Int.repr 5) in H15.\n           apply repr_inj_unsigned in H15; [ | rep_lia | rep_lia ].\n           if_tac in H17; simplify.\n           deadvars.\n           match_tac; simpl Trie.bnode_rep at 1.\n           ++ destruct bnode as [? [ [|] | ]]; simplify.\n              Intros.\n              unfold BorderNode.get_link in H20; simplify.\n              forward.\n              forward_call (c ++\n                              [(Trie.trienode_of addr tableform listform, BTree.first_cursor tableform, (l, Some (inr t)),\n                                BorderNode.next_cursor (BorderNode.before_prefix 1) (l, Some (inr t)))],\n                            pc,\n                            t).\n              { inv H12; simplify. }\n              forward_if.\n              ** forward.\n                 if_tac in H20; simplify.\n                 rewrite Trie.strict_first_cursor_equation.\n                 unfold BTree.Flattened.get_value.\n                 rewrite H10.\n                 rewrite H16.\n                 simpl.\n                 match_tac; simplify.\n                 match goal with\n                 | |- context rest[ ?P -* ?Q] =>\n                   sep_apply (wand_frame_elim P Q)\n                 end.\n                 entailer!.\n                 rewrite <- app_assoc.\n                 rewrite <- semax_lemmas.cons_app.\n                 apply derives_refl.\n              ** if_tac in H20; simplify.\n                 rewrite app_nil_r.\n                 forward_call ((c ++\n                                  [(Trie.trienode_of addr tableform listform, BTree.first_cursor tableform, (l, Some (inr t)),\n                                    BorderNode.next_cursor (BorderNode.before_prefix 1) (l, Some (inr t)))]),\n                               pc).\n                 rewrite removelast_app by congruence.\n                 simpl removelast.\n                 rewrite app_nil_r.\n                 forward.\n                 rewrite Trie.strict_first_cursor_equation.\n                 unfold BTree.Flattened.get_value.\n                 rewrite H10.\n                 rewrite H16.\n                 simpl.\n                 match_tac; simplify.\n                 match goal with\n                 | |- context rest[ ?P -* ?Q] =>\n                   sep_apply (wand_frame_elim P Q)\n                 end.\n                 entailer!.\n                 rewrite app_nil_r.\n                 apply derives_refl.\n           ++ apply BorderNode.next_cursor_suffix_correct in H16.\n              destruct bnode; unfold BorderNode.get_link in H20; simpl in H16; simplify.\n      * change (Int.add (Int.repr 4) (Int.repr 1)) with (Int.repr 5) in H15.\n        apply repr_neq_e in H15.\n        forward_call (BTree.first_cursor tableform, pnode_cursor).\n        match goal with\n        | |- context rest[ ?P -* ?Q] =>\n          sep_apply (wand_frame_elim P Q)\n        end.\n        forward.\n        rewrite Trie.strict_first_cursor_equation.\n        unfold BTree.Flattened.get_value.\n        rewrite H10.\n        assert (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode = BorderNode.after_suffix). {\n          assert (BorderNode.cursor_correct (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode)). {\n            apply BorderNode.next_cursor_bnode_correct.\n            simpl.\n            rep_lia.\n          }\n          destruct (BorderNode.next_cursor (BorderNode.before_prefix 1) bnode) eqn:Heqn.\n          - simpl in *.\n            rep_lia.\n          - simpl in *.\n            rep_lia.\n          - reflexivity.\n        }\n        rewrite H19.\n        entailer!.\n        rewrite app_nil_r.\n        cancel.\n  - forward_call (BTree.first_cursor tableform, pnode_cursor).\n    forward.\n    if_tac in H; simplify.\n    unfold BTree.get_value in H11; match_tac in H11; simplify.\n    pose proof H12.\n    apply BTree.first_cursor_get_empty in H12; [ | assumption].\n    apply BTreeFacts.empty_flatten_empty in H12.\n    rewrite H12 in *.\n    destruct listform; simpl in H5; simplify.\nAdmitted.\n", "meta": {"author": "PrincetonUniversity", "repo": "DeepSpecDB", "sha": "a67d933b4288498bd04c70748b7fa28f676983c3", "save_path": "github-repos/coq/PrincetonUniversity-DeepSpecDB", "path": "github-repos/coq/PrincetonUniversity-DeepSpecDB/DeepSpecDB-a67d933b4288498bd04c70748b7fa28f676983c3/verif/trie/verif/verif_first_cursor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.20615084450333365}}
{"text": "From stdpp Require Import prelude finite.\nFrom Coq Require Import FunctionalExtensionality Reals.\nFrom VLSM.Lib Require Import Preamble FinSetExtras ListFinSetExtras.\nFrom VLSM.Lib Require Import Measurable RealsExtras.\nFrom VLSM.Core Require Import VLSM MessageDependencies VLSMProjections Composition ProjectionTraces.\nFrom VLSM.Core Require Import SubProjectionTraces AnnotatedVLSM Equivocation.\nFrom VLSM.Core Require Import ByzantineTraces.FixedSetByzantineTraces.\nFrom VLSM.Core Require Import Equivocation.FixedSetEquivocation.\nFrom VLSM.Core Require Import Equivocation.LimitedMessageEquivocation.\nFrom VLSM.Core Require Import Equivocation.MsgDepLimitedEquivocation.\nFrom VLSM.Core Require Import Equivocation.TraceWiseEquivocation.\n\n(** * VLSM Compositions with Byzantine nodes of limited weight\n\n  In this module we define and study protocol executions allowing a\n  (weight-)limited amount of byzantine faults.\n\n  We will show that, if the non-byzantine nodes are validators for a\n  composition constraint allowing only a limited amount of equivocation, then\n  they do not distinguish between byzantine nodes and equivocating ones, that is,\n  projections of traces with byzantine faults to the non-byzantine nodes are\n  projections of traces of the composition of the regular nodes under a\n  composition constraint allowing only a limited amount of equivocation.\n*)\n\nSection sec_limited_byzantine_traces.\n\nContext\n  {message : Type}\n  `{FinSet index Ci}\n  `{!finite.Finite index}\n  (IM : index -> VLSM message)\n  `{forall i : index, HasBeenSentCapability (IM i)}\n  `{forall i : index, HasBeenReceivedCapability (IM i)}\n  (threshold : R)\n  `{ReachableThreshold validator Cv threshold}\n  `{!finite.Finite validator}\n  (A : validator -> index)\n  `{!Inj (=) (=) A}\n  (sender : message -> option validator)\n  .\n\n(**\n  We define the [limited_byzantine_trace_prop]erty in two steps. First, we\n  leverage the [fixed_byzantine_trace_alt_prop]erty by assuming a fixed selection\n  of <<byzantine>> nodes whose added weight is below the [ReachableThreshold].\n*)\nDefinition fixed_limited_byzantine_trace_prop\n  (s : composite_state IM)\n  (tr : list (composite_transition_item IM))\n  (byzantine_vs : Cv)\n  (byzantine := fin_sets.set_map A byzantine_vs : Ci)\n  : Prop\n  := (sum_weights byzantine_vs <= threshold)%R /\\\n     fixed_byzantine_trace_alt_prop (Ci := Ci) IM byzantine A sender s tr.\n\n(**\n  The union of traces with the [fixed_limited_byzantine_trace_prop]erty over\n  all possible selections of (limited) byzantine nodes.\n*)\nDefinition limited_byzantine_trace_prop\n  (s : composite_state IM)\n  (tr : list (composite_transition_item IM))\n  : Prop :=\n  exists byzantine, fixed_limited_byzantine_trace_prop s tr byzantine.\n\nContext\n  `{FinSet message Cm}\n  {is_equivocating_tracewise_no_has_been_sent_dec :\n    RelDecision (is_equivocating_tracewise_no_has_been_sent IM A sender)}\n  (limited_constraint := tracewise_limited_equivocation_constraint (Cv := Cv) IM threshold A sender)\n  (Limited : VLSM message := composite_vlsm IM limited_constraint)\n  (Hvalidator : forall i : index, component_message_validator_prop IM limited_constraint i)\n  (no_initial_messages_in_IM : no_initial_messages_in_IM_prop IM)\n  (can_emit_signed : channel_authentication_prop IM A sender)\n  (message_dependencies : message -> Cm)\n  `{!Irreflexive (msg_dep_happens_before message_dependencies)}\n  `{forall i, MessageDependencies (IM i) message_dependencies}\n  (Hfull : forall i, message_dependencies_full_node_condition_prop (IM i) message_dependencies)\n  .\n\n(** ** Assuming the byzantine nodes are known\n\n  We will first fix a selection of <<byzantine>> nodes of limited weight and\n  analyze traces with the [fixed_limited_byzantine_trace_prop]erty w.r.t. that\n  selection.\n*)\n\nSection sec_fixed_limited_selection.\n\nContext\n  (byzantine_vs : Cv)\n  (byzantine : Ci := fin_sets.set_map A byzantine_vs )\n  (non_byzantine : Ci := difference (list_to_set (enum index)) byzantine)\n  (Hlimit : (sum_weights byzantine_vs <= threshold)%R)\n  (PreNonByzantine := pre_loaded_fixed_non_byzantine_vlsm IM byzantine A sender)\n  (Htracewise_BasicEquivocation : BasicEquivocation (composite_state IM) validator Cv threshold\n    := equivocation_dec_tracewise IM threshold A sender)\n  (tracewise_not_heavy := not_heavy (1 := Htracewise_BasicEquivocation))\n  (tracewise_equivocating_validators := equivocating_validators (1 := Htracewise_BasicEquivocation))\n  .\n\n(**\n  When replacing the byzantine components of a composite [valid_state] with\n  initial states for those machines we obtain a state which is [not_heavy].\n*)\nLemma limited_PreNonByzantine_valid_state_lift_not_heavy s\n  (Hs : valid_state_prop PreNonByzantine s)\n  (sX := lift_sub_state IM (elements non_byzantine) s)\n  : tracewise_not_heavy sX.\nProof.\n  cut (tracewise_equivocating_validators sX ⊆ byzantine_vs).\n  {\n    intro Hincl.\n    unfold tracewise_not_heavy, not_heavy.\n    transitivity (sum_weights byzantine_vs); [| done].\n    apply sum_weights_subseteq_list.\n    - by apply NoDup_elements.\n    - by apply NoDup_elements.\n    - intros i Hi.\n      by apply elem_of_elements, Hincl, elem_of_elements, Hi.\n  }\n  apply valid_state_has_trace in Hs as [is [tr Htr]].\n  specialize (preloaded_non_byzantine_vlsm_lift IM byzantine A sender)\n    as Hproj.\n  apply (VLSM_embedding_finite_valid_trace_init_to Hproj) in Htr as Hpre_tr.\n  intros v Hv.\n  apply equivocating_validators_is_equivocating_tracewise_iff in Hv as Hvs'.\n  specialize (Hvs' _ _ Hpre_tr).\n  destruct Hvs' as [m0 [Hsender0 [preX [itemX [sufX [Htr_pr [Hm0 Heqv]]]]]]].\n  apply map_eq_app in Htr_pr as [pre [item_suf [Heqtr [Hpre_pr Hitem_suf_pr]]]].\n  apply map_eq_cons in Hitem_suf_pr as [item [suf [Heqitem_suf [Hitem_pr Hsuf_pr]]]].\n  subst tr item_suf. clear Hsuf_pr.\n  subst itemX. cbn in Hm0.\n  change (pre ++ item :: suf) with (pre ++ [item] ++ suf) in Htr.\n  destruct Htr as [Htr Hinit].\n  apply (finite_valid_trace_from_to_app_split PreNonByzantine) in Htr.\n  destruct Htr as [Hpre Hitem].\n  apply (VLSM_embedding_finite_valid_trace_from_to Hproj) in Hpre as Hpre_pre.\n  apply valid_trace_last_pstate in Hpre_pre as Hs_pre.\n  apply (finite_valid_trace_from_to_app_split PreNonByzantine), proj1 in Hitem.\n  inversion Hitem; subst; clear Htl Hitem. simpl in Hm0. subst.\n  destruct Ht as [[_ [_ [_ [Hc _]]]] _].\n  destruct Hc as [[sub_i Hsenti] | Hemit].\n  - destruct_dec_sig sub_i i Hi Heqsub_i; subst sub_i.\n    assert (Hsent : composite_has_been_sent IM\n                      (lift_sub_state IM (elements non_byzantine) (finite_trace_last is pre)) m0).\n    {\n      exists i.\n      unfold lift_sub_state.\n      by rewrite (lift_sub_state_to_eq _ _ _ _ _ Hi).\n    }\n    apply (composite_proper_sent IM) in Hsent; [| done].\n    apply (VLSM_embedding_initial_state Hproj) in Hinit.\n    by specialize (Hsent _ _ (conj Hpre_pre Hinit)).\n  - specialize (proj1 Hemit) as [i [Hi Hsigned]].\n    subst.\n    destruct (decide (i ∈ byzantine)).\n    + unfold channel_authenticated_message in Hsigned.\n      rewrite Hsender0 in Hsigned.\n      apply Some_inj in Hsigned; subst.\n      by revert e; apply elem_of_set_map_inj.\n    + rewrite elem_of_elements in Hi.\n      contradict Hi.\n      apply elem_of_difference; split; [| done].\n      by apply elem_of_list_to_set, elem_of_enum.\nQed.\n\nExisting Instance Htracewise_BasicEquivocation.\n\n(**\n  When replacing the byzantine components of a composite [valid_state] with\n  initial states for those machines validity of transitions for the non-byzantine\n  components is preserved.\n*)\nLemma limited_PreNonByzantine_lift_valid\n  : weak_embedding_valid_preservation PreNonByzantine Limited\n    (lift_sub_label IM (elements non_byzantine))\n    (lift_sub_state IM (elements non_byzantine)).\nProof.\n  intros l s om Hv HsY HomY.\n  repeat split; [by apply lift_sub_valid, Hv |].\n  hnf.\n  destruct (composite_transition (sub_IM IM (elements non_byzantine)) l (s, om))\n    as [s' om'] eqn: Ht.\n  apply (lift_sub_transition IM (elements non_byzantine)) in Ht as HtX.\n  simpl in HtX |- *; rewrite HtX; simpl.\n  change (is_equivocating_tracewise_no_has_been_sent _ _ _) with is_equivocating.\n  by eapply tracewise_not_heavy_LimitedEquivocationProp_iff,\n    limited_PreNonByzantine_valid_state_lift_not_heavy,\n    input_valid_transition_destination.\nQed.\n\n(**\n  By replacing the byzantine components of a composite [valid_state] with\n  initial states for those machines and ignoring transitions for byzantine nodes\n  we obtain valid traces for the <<Limited>> equivocation composition.\n*)\nLemma limited_PreNonByzantine_vlsm_lift\n  : VLSM_embedding PreNonByzantine Limited\n      (lift_sub_label IM (elements non_byzantine))\n      (lift_sub_state IM (elements non_byzantine)).\nProof.\n  apply basic_VLSM_embedding; intros ? *.\n  - by intros; apply limited_PreNonByzantine_lift_valid.\n  - by intros * []; rapply lift_sub_transition.\n  - by intros; apply (lift_sub_state_initial IM).\n  - intros Hv HsY [[sub_i [[im Him] Heqm]] | Hseeded].\n    + cbn in Heqm; subst.\n      destruct_dec_sig sub_i i Hi Heqsub_i; subst.\n      unfold sub_IM in Him; cbn in Him; clear -Him.\n      apply initial_message_is_valid.\n      by exists i, (exist _ m Him).\n    + destruct Hseeded as (Hsigned & i & Hi & li & si & Hpre_valid).\n      by eapply Hvalidator.\nQed.\n\nEnd sec_fixed_limited_selection.\n\n(**\n  Given a trace with the [fixed_limited_byzantine_trace_prop]erty for a selection\n  of <<byzantine>> nodes, there exists a valid trace for the <<Limited>>\n  equivocation composition such that the projection of the two traces to\n  the <<non-byzantine>> nodes coincide.\n*)\nLemma validator_fixed_limited_non_byzantine_traces_are_limited_non_equivocating s tr byzantine_vs\n  (byzantine : Ci := fin_sets.set_map A byzantine_vs)\n  (not_byzantine : Ci := difference (list_to_set (enum index)) byzantine)\n  : fixed_limited_byzantine_trace_prop s tr byzantine_vs ->\n    exists bs btr,\n      finite_valid_trace Limited bs btr /\\\n      composite_state_sub_projection IM (elements not_byzantine) s =\n      composite_state_sub_projection IM (elements not_byzantine) bs /\\\n      finite_trace_sub_projection IM (elements not_byzantine) tr =\n      finite_trace_sub_projection IM (elements not_byzantine) btr.\nProof.\n  intros [Hlimit Hfixed].\n  eexists _, _; split.\n  - by apply (VLSM_embedding_finite_valid_trace\n            (limited_PreNonByzantine_vlsm_lift byzantine_vs Hlimit)).\n  - unfold lift_sub_state.\n    rewrite composite_state_sub_projection_lift_to.\n    split; [done |].\n    by symmetry; apply composite_trace_sub_projection_lift.\nQed.\n\n(** ** The main result\n\n  Given any trace with the [limited_byzantine_trace_prop]erty, there exists\n  a valid trace for the <<Limited>> equivocation composition and\n  a selection of nodes of limited weight such that the projection of the\n  two traces to the nodes not in the selection coincide.\n*)\nLemma validator_limited_non_byzantine_traces_are_limited_non_equivocating s tr\n  : limited_byzantine_trace_prop s tr ->\n    exists bs btr,\n      finite_valid_trace Limited bs btr /\\\n      exists (selection_vs : Cv)\n        (selection : Ci := fin_sets.set_map A selection_vs)\n        (selection_complement := difference (list_to_set (enum index)) selection),\n        (sum_weights selection_vs <= threshold)%R /\\\n        composite_state_sub_projection IM (elements selection_complement) s =\n        composite_state_sub_projection IM (elements selection_complement) bs /\\\n        finite_trace_sub_projection IM (elements selection_complement) tr =\n        finite_trace_sub_projection IM (elements selection_complement) btr.\nProof.\n  intros [byzantine Hlimited].\n  apply proj1 in Hlimited as Hlimit.\n  apply validator_fixed_limited_non_byzantine_traces_are_limited_non_equivocating\n    in Hlimited\n    as [bs [btr [Hlimited [Hs_pr Htr_pr]]]].\n  by exists bs, btr; eauto.\nQed.\n\nEnd sec_limited_byzantine_traces.\n\nSection sec_msg_dep_limited_byzantine_traces.\n\nContext\n  {message : Type}\n  `{FinSet index Ci}\n  `{!finite.Finite index}\n  (IM : index -> VLSM message)\n  `{forall i, HasBeenSentCapability (IM i)}\n  `{forall i, HasBeenReceivedCapability (IM i)}\n  (threshold : R)\n  `{ReachableThreshold validator Cv threshold}\n  `{!finite.Finite validator}\n  `{FinSet message Cm}\n  (message_dependencies : message -> Cm)\n  (full_message_dependencies : message -> Cm)\n  `{!FullMessageDependencies message_dependencies full_message_dependencies}\n  `{forall i, MessageDependencies (IM i) message_dependencies}\n  (sender : message -> option validator)\n  (A : validator -> index)\n  `{!Inj (=) (=) A}\n  (Limited := msg_dep_limited_equivocation_vlsm (Cv := Cv)\n    IM threshold full_message_dependencies sender)\n  (no_initial_messages_in_IM : no_initial_messages_in_IM_prop IM)\n  (Hchannel : channel_authentication_prop IM A sender)\n  (Hsender_safety : sender_safety_alt_prop IM A sender :=\n    channel_authentication_sender_safety _ _ _ Hchannel)\n  (Hvalidator :\n    forall i : index,\n      msg_dep_limited_equivocation_message_validator_prop (Cv := Cv)\n        IM threshold full_message_dependencies sender i)\n  (Hfull : forall i, message_dependencies_full_node_condition_prop (IM i) message_dependencies)\n  .\n\n(**\n  If the set of byzantine nodes is weight-limited and if an [input_valid_transition]\n  of the non-byzantine nodes from a state of weight-limited equivocation does not\n  introduce equivocators from the non-byzantine nodes, then the transition is valid\n  for weight-limited equivocation.\n*)\nLemma lift_pre_loaded_fixed_non_byzantine_valid_transition_to_limited\n  (byzantine_vs : Cv)\n  (byzantine : Ci := fin_sets.set_map A byzantine_vs)\n  (non_byzantine := difference (list_to_set (enum index)) byzantine)\n  (Hlimited : (sum_weights byzantine_vs <= threshold)%R)\n  sub_l sub_s iom sub_sf oom\n  (Ht_sub : input_valid_transition\n      (pre_loaded_fixed_non_byzantine_vlsm IM byzantine A sender)\n      sub_l (sub_s, iom) (sub_sf, oom))\n  ann_s\n  (Hann_s : valid_state_prop Limited ann_s)\n  (Hann_s_pr : original_state ann_s = lift_sub_state IM (elements non_byzantine) sub_s)\n  (ann' := msg_dep_composite_transition_message_equivocators IM full_message_dependencies sender\n      (lift_sub_label IM (elements non_byzantine) sub_l) (ann_s, iom))\n  (Heqv_byzantine : ann' ⊆ byzantine_vs)\n  : input_valid_transition Limited\n      (lift_sub_label IM (elements non_byzantine) sub_l) (ann_s, iom)\n      (Build_annotated_state (free_composite_vlsm IM) Cv\n        (lift_sub_state IM (elements non_byzantine) sub_sf) ann',\n      oom).\nProof.\n  destruct sub_l as [sub_i li]; destruct_dec_sig sub_i i Hi Heqsub_i; subst.\n  repeat split; cbn.\n  - done.\n  - destruct iom as [im |]; [| apply option_valid_message_None].\n    by eapply Hvalidator, pre_loaded_sub_composite_input_valid_projection, Ht_sub.\n  - unfold lift_sub_state in Hann_s_pr.\n    rewrite Hann_s_pr, (lift_sub_state_to_eq _ _ _ _ _ Hi).\n    by apply Ht_sub.\n  - apply Rle_trans with (sum_weights byzantine_vs)\n    ; [| done].\n    apply sum_weights_subseteq.\n    by intro; apply Heqv_byzantine.\n  - clear -Ht_sub Hann_s_pr.\n    destruct Ht_sub as [_ Ht_sub]; revert Ht_sub\n    ; unfold annotated_transition; cbn\n    ; rewrite Hann_s_pr; unfold lift_sub_state at 1\n    ; rewrite (lift_sub_state_to_eq _ _ _ _ _ Hi)\n    ; unfold sub_IM at 2; cbn\n    ; destruct (vtransition _ _ _) as (si', om')\n    ; inversion_clear 1.\n    do 2 f_equal; extensionality j.\n    unfold lift_sub_state.\n    destruct (decide (i = j)); subst; state_update_simpl.\n    + by rewrite (lift_sub_state_to_eq _ _ _ _ _ Hi), !state_update_eq.\n    + unfold lift_sub_state_to.\n      by case_decide; [rewrite sub_IM_state_update_neq |].\nQed.\n\n(**\n  Considering a trace with the [fixed_byzantine_trace_alt_prop]erty for a\n  set <<byzantine>> of indices of bounded weight, its subtrace corresponding to\n  the non-byzantine nodes is of limited equivocation and its set of equivocators\n  is included in <<byzantine>>.\n*)\nLemma lift_fixed_byzantine_traces_to_limited\n  (s : composite_state IM)\n  (tr : list (composite_transition_item IM))\n  (byzantine_vs : Cv)\n  (byzantine : Ci := fin_sets.set_map A byzantine_vs)\n  (non_byzantine := difference (list_to_set (enum index)) byzantine)\n  (Hlimited : (sum_weights byzantine_vs <= threshold)%R)\n  (Hbyzantine :\n    fixed_byzantine_trace_alt_prop IM byzantine A sender s tr)\n  (s_reset_byzantine :=\n    lift_sub_state IM (elements non_byzantine)\n      (composite_state_sub_projection IM (elements non_byzantine) s))\n  (bs := Build_annotated_state (free_composite_vlsm IM) Cv s_reset_byzantine (` inhabitant))\n  (btr :=\n    msg_dep_annotate_trace_with_equivocators (Cv := Cv) IM full_message_dependencies sender\n      s_reset_byzantine\n      (pre_VLSM_embedding_finite_trace_project _ _\n        (lift_sub_label IM (elements non_byzantine)) (lift_sub_state IM (elements non_byzantine))\n        (finite_trace_sub_projection IM (elements non_byzantine) tr)))\n  : finite_valid_trace Limited bs btr /\\\n    state_annotation (@finite_trace_last _ (type Limited) bs btr) ⊆ byzantine_vs.\nProof.\n  subst non_byzantine.\n  induction Hbyzantine using finite_valid_trace_rev_ind; [repeat split |].\n  - constructor; apply initial_state_is_valid.\n    by repeat split; cbn; apply lift_sub_state_initial.\n  - by cbn; apply lift_sub_state_initial.\n  - by apply empty_subseteq.\n  - subst s_reset_byzantine bs btr.\n    unfold pre_VLSM_embedding_finite_trace_project; rewrite !map_app.\n    rewrite @msg_dep_annotate_trace_with_equivocators_app; cbn.\n    unfold annotate_trace_item; cbn; rewrite finite_trace_last_is_last; cbn.\n    destruct l as [sub_i li]; destruct_dec_sig sub_i i Hi Heqsub_i; subst sub_i\n    ; destruct IHHbyzantine as [[Htr0_ann Hsi_ann] Htr0_eqv_byzantine]\n    ; cbn in Htr0_eqv_byzantine |- *.\n    remember (@finite_trace_last _ (annotated_type (free_composite_vlsm IM) _) _ _)\n     as lst in Htr0_eqv_byzantine at 1 |- * at 1 2 3 4 5 6.\n    assert (Hlsti : original_state lst = lift_sub_state IM (elements (list_to_set (enum index) ∖ byzantine))\n                                          (finite_trace_last si tr0)).\n    {\n      subst lst; rewrite msg_dep_annotate_trace_with_equivocators_last_original_state; symmetry.\n      apply (pre_VLSM_embedding_finite_trace_last _ _\n              (lift_sub_label IM _)\n              (lift_sub_state IM _)).\n    }\n    match goal with\n    |- _ /\\ ?B => cut B\n    end.\n    {\n      intro Heqv_byzantine.\n      do 2 (split; [| done]).\n      apply finite_valid_trace_from_app_iff; split; [done |].\n      subst x; cbn; apply finite_valid_trace_singleton.\n      replace (finite_trace_last _ _) with lst.\n      by eapply lift_pre_loaded_fixed_non_byzantine_valid_transition_to_limited;\n        [| | subst lst; apply finite_valid_trace_last_pstate | |].\n    }\n    destruct iom as [im |]; [| done].\n    apply set_union_subseteq_iff; split; [done |].\n    unfold coeqv_message_equivocators\n    ; case_decide as Hnobs; [by apply empty_subseteq |].\n    rewrite (full_node_msg_dep_coequivocating_senders _ _ _ _ Hfull _ _ i li);\n      [| by cbn; rewrite Hlsti; eapply @pre_loaded_sub_composite_input_valid_projection, Hx].\n    rewrite elements_empty, app_nil_r; cbn.\n    intro _i_im; rewrite elem_of_list_to_set.\n    destruct (sender im) as [i_im |] eqn: Hsender; [| by inversion 1].\n    rewrite elem_of_list_singleton; intro; subst _i_im.\n    destruct Hx as [(_ & _ & _ & [Hsent | [Hsigned _]] & _) _].\n    + contradict Hnobs.\n      destruct Hsent as [sub_i_im Hsent]; cbn in Hsent |- *\n      ; destruct_dec_sig sub_i_im _i_im H_i_im Heqsub_i_im; subst sub_i_im.\n      apply composite_has_been_directly_observed_sent_received_iff; left.\n      exists _i_im.\n      rewrite Hlsti; cbn; unfold lift_sub_state.\n      by rewrite (lift_sub_state_to_eq _ _ _ _ _ H_i_im).\n    + destruct Hsigned as (_i_im & H_i_im & Hauth).\n      unfold channel_authenticated_message in Hauth\n      ; rewrite Hsender in Hauth.\n      apply Some_inj in Hauth; subst _i_im.\n      destruct (decide (i_im ∈ byzantine_vs)) as [Hi_im | Hni_im]; [done |].\n      contradict H_i_im.\n      apply elem_of_elements, elem_of_difference; cbn.\n      split; [by apply elem_of_list_to_set, elem_of_enum |].\n      by contradict Hni_im; revert Hni_im; apply elem_of_set_map_inj.\nQed.\n\n(**\n  Under full-message dependencies and full node assumptions, if all components are\n  validators for the [msg_dep_limited_equivocation_vlsm] associated to their\n  composition, then the traces exposed limited Byzantine behavior coincide with\n  the traces exposed to limited equivocation.\n*)\nLemma msg_dep_validator_limited_non_equivocating_byzantine_traces_are_limited_non_equivocating s tr\n  : limited_byzantine_trace_prop (Ci := Ci) (Cv := Cv) IM threshold A sender s tr <->\n    exists bs btr selection_vs\n      (selection : Ci := fin_sets.set_map A selection_vs)\n      (selection_complement := difference (list_to_set (enum index)) selection),\n      finite_valid_trace Limited bs btr /\\\n      state_annotation (finite_trace_last bs btr) ⊆ selection_vs /\\\n      (sum_weights selection_vs <= threshold)%R /\\\n      composite_state_sub_projection IM (elements selection_complement) s =\n        composite_state_sub_projection IM (elements selection_complement) (original_state bs) /\\\n      finite_trace_sub_projection IM (elements selection_complement) tr =\n        finite_trace_sub_projection IM (elements selection_complement)\n          (pre_VLSM_embedding_finite_trace_project\n            (type Limited) (composite_type IM) Datatypes.id original_state btr).\nProof.\n  split.\n  - intros (byzantine & Hlimited & Hbyzantine).\n    apply lift_fixed_byzantine_traces_to_limited in Hbyzantine\n       as [Hbtr Heqv_byzantine] ; [| done].\n    eexists _, _, byzantine; do 3 (split; [done |]); split.\n    + extensionality sub_i; destruct_dec_sig sub_i i Hi Heqsub_i; subst; cbn.\n      unfold lift_sub_state.\n      by rewrite (lift_sub_state_to_eq _ _ _ _ _ Hi).\n    + subst Limited.\n      rewrite msg_dep_annotate_trace_with_equivocators_project.\n      by symmetry; apply composite_trace_sub_projection_lift.\n  - intros (bs & btr & byzantine & Hbtr & Heqv_byzantine & Hlimited & His_pr & Htr_pr).\n    exists byzantine; split; [done |].\n    eapply VLSM_incl_finite_valid_trace\n    ; [by apply fixed_non_equivocating_incl_fixed_non_byzantine |].\n    apply fixed_non_equivocating_traces_char.\n    symmetry in His_pr, Htr_pr.\n    eexists _, _; split; [| done].\n    eapply @msg_dep_fixed_limited_equivocation_witnessed in Hbtr as [_ Hbtr]; [| done..].\n    revert Hbtr; apply VLSM_incl_finite_valid_trace.\n    apply fixed_equivocation_vlsm_composition_index_incl.\n    intro; rewrite !elem_of_elements.\n    by apply set_map_mono.\nQed.\n\nEnd sec_msg_dep_limited_byzantine_traces.\n", "meta": {"author": "runtimeverification", "repo": "vlsm", "sha": "9115beb539257427467872ce65a224a0268cdae7", "save_path": "github-repos/coq/runtimeverification-vlsm", "path": "github-repos/coq/runtimeverification-vlsm/vlsm-9115beb539257427467872ce65a224a0268cdae7/theories/VLSM/Core/ByzantineTraces/LimitedByzantineTraces.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.20610856756858784}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\n\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Globalenvs.\n\nRequire Import VST.msl.Axioms.\n\nRequire Import VST.sepcomp.mem_lemmas.\nRequire Import VST.sepcomp.semantics.\nRequire Import VST.sepcomp.semantics_lemmas.\nRequire Import VST.sepcomp.effect_semantics.\nRequire Import VST.sepcomp.structured_injections.\nRequire Import VST.sepcomp.reach.\nRequire Import VST.sepcomp.effect_simulations.\n\nSection Eff_INJ_SIMU_DIAGRAMS.\n  Context {F1 V1 C1 F2 V2 C2:Type}\n          {Sem1 : @EffectSem (Genv.t F1 V1) C1}\n          {Sem2 : @EffectSem (Genv.t F2 V2) C2}\n\n          {ge1: Genv.t F1 V1}\n          {ge2: Genv.t F2 V2}.\n\n  Let core_data := C1.\n\n  Variable match_states: core_data -> SM_Injection -> C1 -> mem -> C2 -> mem -> Prop.\n\n   Hypothesis genvs_dom_eq: genvs_domain_eq ge1 ge2.\n\n   Hypothesis match_sm_wd: forall d mu c1 m1 c2 m2,\n          match_states d mu c1 m1 c2 m2 ->\n          SM_wd mu.\n\n    Hypothesis match_visible: forall d mu c1 m1 c2 m2,\n          match_states d mu c1 m1 c2 m2 ->\n          REACH_closed m1 (vis mu).\n\n    Hypothesis match_restrict: forall d mu c1 m1 c2 m2 X,\n          match_states d mu c1 m1 c2 m2 ->\n          (forall b, vis mu b = true -> X b = true) ->\n          REACH_closed m1 X ->\n          match_states d (restrict_sm mu X) c1 m1 c2 m2.\n\n   Hypothesis match_validblocks: forall d mu c1 m1 c2 m2,\n          match_states d mu c1 m1 c2 m2 ->\n          sm_valid mu m1 m2.\n\n    Hypothesis match_genv: forall d mu c1 m1 c2 m2 (MC:match_states d mu c1 m1 c2 m2),\n          meminj_preserves_globals ge1 (extern_of mu) /\\\n          (forall b, isGlobalBlock ge1 b = true -> frgnBlocksSrc mu b = true).\n\n   Hypothesis inj_initial_cores: forall v vals1 c1 m1 j vals2 m2 DomS DomT,\n          initial_core Sem1 0 ge1 v vals1 = Some c1 ->\n          Mem.inject j m1 m2 ->\n          Forall2 (val_inject j) vals1 vals2 ->\n          meminj_preserves_globals ge1 j ->\n\n        (*the next two conditions are required to guarantee intialSM_wd*)\n         (forall b1 b2 d, j b1 = Some (b2, d) ->\n                          DomS b1 = true /\\ DomT b2 = true) ->\n         (forall b, REACH m2 (fun b' => isGlobalBlock ge2 b' || getBlocks vals2 b') b = true -> DomT b = true) ->\n\n        (*the next two conditions ensure the initialSM satisfies sm_valid*)\n         (forall b, DomS b = true -> Mem.valid_block m1 b) ->\n         (forall b, DomT b = true -> Mem.valid_block m2 b) ->\n\n       exists c2,\n            initial_core Sem2 0 ge2 v vals2 = Some c2 /\\\n            match_states c1 (initial_SM DomS\n                                       DomT\n                                       (REACH m1 (fun b => isGlobalBlock ge1 b || getBlocks vals1 b))\n                                       (REACH m2 (fun b => isGlobalBlock ge2 b || getBlocks vals2 b)) j)\n                           c1 m1 c2 m2.\n\n  Hypothesis inj_halted : forall cd mu c1 m1 c2 m2 v1,\n      match_states cd mu c1 m1 c2 m2 ->\n      halted Sem1 c1 = Some v1 ->\n\n      exists v2,\n             Mem.inject (as_inj mu) m1 m2 /\\\n             val_inject (restrict (as_inj mu) (vis mu)) v1 v2 /\\\n             halted Sem2 c2 = Some v2.\n\n  Hypothesis inj_at_external :\n      forall mu c1 m1 c2 m2 e vals1,\n        match_states c1 mu c1 m1 c2 m2 ->\n        at_external Sem1 c1 = Some (e,vals1) ->\n        Mem.inject (as_inj mu) m1 m2 /\\\n          exists vals2,\n            Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2 /\\\n            at_external Sem2 c2 = Some (e,vals2)\n    /\\ forall\n       (pubSrc' pubTgt' : block -> bool)\n       (pubSrcHyp : pubSrc' =\n                  (fun b : block =>\n                  locBlocksSrc mu b && REACH m1 (exportedSrc mu vals1) b))\n       (pubTgtHyp: pubTgt' =\n                  (fun b : block =>\n                  locBlocksTgt mu b && REACH m2 (exportedTgt mu vals2) b))\n       nu (Hnu: nu = (replace_locals mu pubSrc' pubTgt')),\n       match_states c1 nu c1 m1 c2 m2\n       /\\ Mem.inject (shared_of nu) m1 m2.\n\nSection EFF_INJ_SIMULATION_STAR_WF.\nVariable order: C1 -> C1 -> Prop.\nHypothesis order_wf: well_founded order.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            ((effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n              (effstep_star Sem2 ge2 U2 st2 m2 st2' m2' /\\\n               order st1' st1)) /\\\n\n             forall\n               (UHyp: forall b z, U1 b z = true -> vis mu b = true)\n               b ofs (Ub: U2 b ofs = true),\n             visTgt mu b = true /\\\n                (locBlocksTgt mu b = false ->\n                 exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                 U1 b1 (ofs-delta1) = true /\\\n                 Mem.perm m1 b1 (ofs-delta1) Max Nonempty)).\n\nLemma  inj_simulation_star_wf:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply SM_simulation.Build_SM_simulation_inject with\n    (core_ord := order)\n    (match_state := fun d j c1 m1 c2 m2 => d = c1 /\\ match_states d j c1 m1 c2 m2).\n  apply order_wf.\nclear - match_sm_wd. intros. destruct H; subst. eauto.\nassumption.\nclear - match_genv. intros. destruct MC; subst. eauto.\nclear - match_visible. intros. destruct H; subst. eauto.\nclear - match_restrict. intros. destruct H; subst. eauto.\nclear - match_validblocks. intros.\n    destruct H; subst. eauto.\nclear - inj_initial_cores. intros.\n    destruct (inj_initial_cores _ _ _ _ _ _ _ _ _ H\n         H0 H1 H2 H3 H4 H5 H6)\n    as [c2 [INI MS]].\n  exists c1, c2. intuition.\nclear - inj_effcore_diagram.\n  intros. destruct H0; subst.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H1) as\n    [c2' [m2' [mu' [INC [SEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists st1'. exists mu'.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  split. split; trivial.\n  exists U2. split; assumption.\nclear - inj_halted. intros. destruct H; subst.\n  destruct (inj_halted _ _ _ _ _ _ _ H1 H0) as [v2 [INJ [VAL HH]]].\n  exists v2; intuition.\nclear - inj_at_external. intros. destruct H; subst.\n  destruct (inj_at_external _ _ _ _ _ _ _ H1 H0)\n    as [INJ [vals2 [VALS [AtExt2 SH]]]].\n  split. trivial. exists vals2. split; trivial. split; trivial.\n    intros. split. split. trivial. eapply SH; eassumption. eapply SH; eassumption.\nclear - inj_after_external. intros.\n  destruct MatchMu as [ZZ matchMu]. subst cd.\n  destruct (inj_after_external _ _ _ _ _ _ _ _ _\n      MemInjMu matchMu AtExtSrc AtExtTgt ValInjMu _\n      pubSrcHyp _ pubTgtHyp _ NuHyp _ _ _ _ _ INC SEP\n      WDnu' SMvalNu' MemInjNu' RValInjNu' FwdSrc FwdTgt\n      _ frgnSrcHyp _ frgnTgtHyp _ Mu'Hyp\n      UnchPrivSrc UnchLOOR)\n    as [st1' [st2' [AftExt1 [AftExt2 MS']]]].\n  exists st1', st1', st2'. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR_WF.\n\nSection EFF_INJ_SIMULATION_STAR_WF_TYPED.\nVariable order: C1 -> C1 -> Prop.\nHypothesis order_wf: well_founded order.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            ((effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n              (effstep_star Sem2 ge2 U2 st2 m2 st2' m2' /\\\n               order st1' st1)) /\\\n\n           forall\n             (UHyp: forall b z, U1 b z = true -> vis mu b = true)\n             b ofs(Ub: U2 b ofs = true),\n             visTgt mu b = true /\\\n             (locBlocksTgt mu b = false ->\n                exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                U1 b1 (ofs-delta1) = true /\\\n                Mem.perm m1 b1 (ofs-delta1) Max Nonempty)).\n\nLemma  inj_simulation_star_wf_typed:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply SM_simulation.Build_SM_simulation_inject with\n    (core_ord := order)\n    (match_state := fun d j c1 m1 c2 m2 => d = c1 /\\ match_states d j c1 m1 c2 m2).\n  apply order_wf.\nclear - match_sm_wd. intros. destruct H; subst. eauto.\nassumption.\nclear - match_genv. intros. destruct MC; subst. eauto.\nclear - match_visible. intros. destruct H; subst. eauto.\nclear - match_restrict. intros. destruct H; subst. eauto.\nclear - match_validblocks. intros.\n    destruct H; subst. eauto.\nclear - inj_initial_cores. intros.\n    destruct (inj_initial_cores _ _ _ _ _ _ _ _ _ H H0 H1 H2 H3 H4 H5 H6)\n    as [c2 [INI MS]].\n  exists c1, c2. intuition.\nclear - inj_effcore_diagram.\n  intros. destruct H0; subst.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H1) as\n    [c2' [m2' [mu' [INC [SEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists st1'. exists mu'.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  split. split; trivial.\n  exists U2. split; assumption.\nclear - inj_halted. intros. destruct H; subst.\n  destruct (inj_halted _ _ _ _ _ _ _ H1 H0) as [v2 [INJ [VAL HH]]].\n  exists v2; intuition.\nclear - inj_at_external. intros. destruct H; subst.\n  destruct (inj_at_external _ _ _ _ _ _ _ H1 H0)\n    as [INJ [vals2 [VALS [AtExt2 SH]]]].\n  split. trivial. exists vals2. split; trivial. split; trivial.\n    intros. split. split. trivial. eapply SH; eassumption. eapply SH; eassumption.\nclear - inj_after_external. intros.\n  destruct MatchMu as [ZZ matchMu]. subst cd.\n  destruct (inj_after_external _ _ _ _ _ _ _ _ _\n      MemInjMu matchMu AtExtSrc AtExtTgt ValInjMu _\n      pubSrcHyp _ pubTgtHyp _ NuHyp _ _ _ _ _ HasTy1 HasTy2 INC SEP\n      WDnu' SMvalNu' MemInjNu' RValInjNu' FwdSrc FwdTgt\n      _ frgnSrcHyp _ frgnTgtHyp _ Mu'Hyp\n      UnchPrivSrc UnchLOOR)\n    as [st1' [st2' [AftExt1 [AftExt2 MS']]]].\n  exists st1', st1', st2'. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR_WF_TYPED.\n\nSection EFF_INJ_SIMULATION_STAR.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\\n             forall\n               (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n               b ofs(Ub: U2 b ofs = true),\n             visTgt mu b = true /\\\n             (locBlocksTgt mu b = false ->\n                 exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                 U1 b1 (ofs-delta1) = true /\\\n                 Mem.perm m1 b1 (ofs-delta1) Max Nonempty).\n\nLemma inj_simulation_star:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply inj_simulation_star_wf.\n  apply  (well_founded_ltof _ measure).\n  apply inj_after_external.\n  clear - inj_effcore_diagram. intros.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H0)\n    as [c2' [m2' [mu' [INC [SEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists mu'.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  exists U2. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR.\n\nSection EFF_INJ_SIMULATION_STAR_TYPED.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\\n             forall\n               (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n               b ofs(Ub: U2 b ofs = true),\n              visTgt mu b = true /\\\n                (locBlocksTgt mu b = false ->\n                 exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                     U1 b1 (ofs-delta1) = true /\\\n                     Mem.perm m1 b1 (ofs-delta1) Max Nonempty).\n\nLemma inj_simulation_star_typed:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  eapply inj_simulation_star_wf_typed.\n  apply  (well_founded_ltof _ measure).\n  intros. eapply inj_after_external with (mu := mu); eauto.\n  clear - inj_effcore_diagram. intros.\n  destruct (inj_effcore_diagram _ _ _ _ _ H _ _ _ H0)\n    as [c2' [m2' [mu' [INC [SEP [LAC [MC' [U2 [STEP' PROP]]]]]]]]].\n  exists c2'. exists m2'. exists mu'.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  split; try assumption.\n  exists U2. intuition.\nQed.\n\nEnd EFF_INJ_SIMULATION_STAR_TYPED.\n\nSection EFF_INJ_SIMULATION_PLUS.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\ forall\n                 (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n                 b ofs (Ub: U2 b ofs = true),\n                 visTgt mu b = true /\\\n                 (locBlocksTgt mu b = false ->\n                     exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                     U1 b1 (ofs-delta1) = true /\\\n                     Mem.perm m1 b1 (ofs-delta1) Max Nonempty).\n\nLemma inj_simulation_plus:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  apply inj_simulation_star with (measure:=measure); auto.\nQed.\n\nEnd EFF_INJ_SIMULATION_PLUS.\n\nSection EFF_INJ_SIMULATION_PLUS_TYPED.\n  Variable measure: C1 -> nat.\n\n  Hypothesis inj_after_external:\n      forall mu st1 st2 m1 e vals1 m2 vals2 e'\n        (MemInjMu: Mem.inject (as_inj mu) m1 m2)\n        (MatchMu: match_states st1 mu st1 m1 st2 m2)\n        (AtExtSrc: at_external Sem1 st1 = Some (e,vals1))\n\n        (AtExtTgt: at_external Sem2 st2 = Some (e',vals2))\n\n        (ValInjMu: Forall2 (val_inject (restrict (as_inj mu) (vis mu))) vals1 vals2)\n\n        pubSrc' (pubSrcHyp: pubSrc' = fun b => andb (locBlocksSrc mu b)\n                                                    (REACH m1 (exportedSrc mu vals1) b))\n\n        pubTgt' (pubTgtHyp: pubTgt' = fun b => andb (locBlocksTgt mu b)\n                                                    (REACH m2 (exportedTgt mu vals2) b))\n\n        nu (NuHyp: nu = replace_locals mu pubSrc' pubTgt'),\n\n      forall nu' ret1 m1' ret2 m2'\n        (HasTy1: Val.has_type ret1 (proj_sig_res (AST.ef_sig e)))\n        (HasTy2: Val.has_type ret2 (proj_sig_res (AST.ef_sig e')))\n        (INC: extern_incr nu nu')\n        (SEP: sm_inject_separated nu nu' m1 m2)\n\n        (WDnu': SM_wd nu') (SMvalNu': sm_valid nu' m1' m2')\n\n        (MemInjNu': Mem.inject (as_inj nu') m1' m2')\n        (RValInjNu': val_inject (as_inj nu') ret1 ret2)\n\n        (FwdSrc: mem_forward m1 m1') (FwdTgt: mem_forward m2 m2')\n\n        frgnSrc' (frgnSrcHyp: frgnSrc' = fun b => andb (DomSrc nu' b)\n                                                 (andb (negb (locBlocksSrc nu' b))\n                                                       (REACH m1' (exportedSrc nu' (ret1::nil)) b)))\n\n        frgnTgt' (frgnTgtHyp: frgnTgt' = fun b => andb (DomTgt nu' b)\n                                                 (andb (negb (locBlocksTgt nu' b))\n                                                       (REACH m2' (exportedTgt nu' (ret2::nil)) b)))\n\n        mu' (Mu'Hyp: mu' = replace_externs nu' frgnSrc' frgnTgt')\n\n        (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc nu b = true /\\\n                                                      pubBlocksSrc nu b = false) m1 m1')\n\n        (UnchLOOR: Mem.unchanged_on (local_out_of_reach nu m1) m2 m2'),\n       exists st1', exists st2',\n          after_external Sem1 (Some ret1) st1 = Some st1' /\\\n          after_external Sem2 (Some ret2) st2 = Some st2' /\\\n          match_states st1' mu' st1' m1' st2' m2'.\n\n  Hypothesis inj_effcore_diagram :\n      forall st1 m1 st1' m1' U1,\n        effstep Sem1 ge1 U1 st1 m1 st1' m1' ->\n\n      forall st2 mu m2,\n        match_states st1 mu st1 m1 st2 m2 ->\n        exists st2', exists m2', exists mu',\n          intern_incr mu mu' /\\\n          sm_inject_separated mu mu' m1 m2 /\\\n          sm_locally_allocated mu mu' m1 m2 m1' m2' /\\\n\n          match_states st1' mu' st1' m1' st2' m2' /\\\n\n          exists U2,\n            (effstep_plus Sem2 ge2 U2 st2 m2 st2' m2' \\/\n             ((measure st1' < measure st1)%nat /\\ effstep_star Sem2 ge2 U2 st2 m2 st2' m2'))\n            /\\ forall\n                 (UHyp: forall b ofs, U1 b ofs = true -> vis mu b = true)\n                  b ofs (Ub: U2 b ofs = true),\n                visTgt mu b = true /\\\n                (locBlocksTgt mu b = false ->\n                    exists b1 delta1, foreign_of mu b1 = Some(b,delta1) /\\\n                    U1 b1 (ofs-delta1) = true /\\\n                    Mem.perm m1 b1 (ofs-delta1) Max Nonempty).\n\nLemma inj_simulation_plus_typed:\n  SM_simulation.SM_simulation_inject Sem1 Sem2 ge1 ge2.\nProof.\n  apply inj_simulation_star_typed with (measure:=measure); auto.\nQed.\n\nEnd EFF_INJ_SIMULATION_PLUS_TYPED.\n\nEnd Eff_INJ_SIMU_DIAGRAMS.\n\nDefinition compose_sm (mu1 mu2 : SM_Injection) : SM_Injection :=\n Build_SM_Injection\n   (locBlocksSrc mu1) (locBlocksTgt mu2)\n   (pubBlocksSrc mu1) (pubBlocksTgt mu2)\n   (compose_meminj (local_of mu1) (local_of mu2))\n   (extBlocksSrc mu1) (extBlocksTgt mu2)\n   (frgnBlocksSrc mu1) (frgnBlocksTgt mu2)\n   (compose_meminj (extern_of mu1) (extern_of mu2)).\n\nLemma compose_sm_valid: forall mu1 mu2 m1 m2 m2' m3\n          (SMV1: sm_valid mu1 m1 m2) (SMV2: sm_valid mu2 m2' m3),\n       sm_valid (compose_sm mu1 mu2) m1 m3.\nProof.  split. apply SMV1. apply SMV2. Qed.\n\nLemma compose_sm_pub: forall mu12 mu23\n         (HypPub: forall b, pubBlocksTgt mu12 b = true ->\n                            pubBlocksSrc mu23 b = true)\n         (WD1:SM_wd mu12),\n      pub_of (compose_sm mu12 mu23) =\n      compose_meminj (pub_of mu12) (pub_of mu23).\nProof. intros. unfold compose_sm, pub_of.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (pSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    destruct (pubSrc _ WD1 _ Heqd) as [b2 [d1 [LOC1 Tgt1]]]; simpl in *.\n    rewrite Heqd in LOC1. apply HypPub in Tgt1.\n    unfold compose_meminj. rewrite Heqd. rewrite LOC1. rewrite Tgt1.\n    trivial.\n  unfold compose_meminj.\n    rewrite Heqd. trivial.\nQed.\n\nLemma compose_sm_DomSrc: forall mu12 mu23,\n  DomSrc (compose_sm mu12 mu23) = DomSrc mu12.\nProof. intros. unfold compose_sm, DomSrc; simpl. trivial. Qed.\n\nLemma compose_sm_DomTgt: forall mu12 mu23,\n  DomTgt (compose_sm mu12 mu23) = DomTgt mu23.\nProof. intros. unfold compose_sm, DomTgt; simpl. trivial. Qed.\n\nLemma compose_sm_foreign: forall mu12 mu23\n         (HypFrg: forall b, frgnBlocksTgt mu12 b = true ->\n                            frgnBlocksSrc mu23 b = true)\n         (WD1:SM_wd mu12),\n      foreign_of (compose_sm mu12 mu23) =\n      compose_meminj (foreign_of mu12) (foreign_of mu23).\nProof. intros. unfold compose_sm, foreign_of.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (fSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    destruct (frgnSrc _ WD1 _ Heqd) as [b2 [d1 [EXT1 Tgt1]]]; simpl in *.\n    rewrite Heqd in EXT1. apply HypFrg in Tgt1.\n    unfold compose_meminj. rewrite Heqd. rewrite EXT1. rewrite Tgt1.\n    trivial.\n  unfold compose_meminj.\n    rewrite Heqd. trivial.\nQed.\n\nLemma compose_sm_priv: forall mu12 mu23,\n   priv_of (compose_sm mu12 mu23) =\n   compose_meminj (priv_of mu12) (local_of mu23).\nProof. intros. unfold priv_of, compose_sm.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (pSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    unfold compose_meminj. rewrite Heqd. trivial.\n  unfold compose_meminj.\n    rewrite Heqd. trivial.\nQed.\n\nLemma compose_sm_unknown: forall mu12 mu23,\n   unknown_of (compose_sm mu12 mu23) =\n   compose_meminj (unknown_of mu12) (extern_of mu23).\nProof. intros. unfold unknown_of, compose_sm.\n  extensionality b.\n  destruct mu12 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu23 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\n  remember (locBSrc1 b) as d; destruct d; apply eq_sym in Heqd.\n    unfold compose_meminj. rewrite Heqd. trivial.\n  remember (fSrc1 b) as q; destruct q; apply eq_sym in Heqq.\n    unfold compose_meminj. rewrite Heqd. rewrite Heqq. trivial.\n  unfold compose_meminj.\n    rewrite Heqd. rewrite Heqq. trivial.\nQed.\n\nLemma compose_sm_local: forall mu12 mu23,\n   local_of (compose_sm mu12 mu23) =\n   compose_meminj (local_of mu12) (local_of mu23).\nProof. intros. reflexivity. Qed.\n\nLemma compose_sm_extern: forall mu12 mu23,\n   extern_of (compose_sm mu12 mu23) =\n   compose_meminj (extern_of mu12) (extern_of mu23).\nProof. intros. reflexivity. Qed.\n\nLemma compose_sm_shared: forall mu12 mu23\n         (HypPub: forall b, pubBlocksTgt mu12 b = true ->\n                            pubBlocksSrc mu23 b = true)\n         (HypFrg: forall b, frgnBlocksTgt mu12 b = true ->\n                            frgnBlocksSrc mu23 b = true)\n         (WD1:SM_wd mu12) (WD2:SM_wd mu23),\n      shared_of (compose_sm mu12 mu23) =\n      compose_meminj (shared_of mu12) (shared_of mu23).\nProof. intros. unfold shared_of.\n  rewrite compose_sm_pub; trivial.\n  rewrite compose_sm_foreign; trivial.\n  unfold join, compose_meminj. extensionality b.\n  remember (foreign_of mu12 b) as f; destruct f; apply eq_sym in Heqf.\n    destruct p as [b2 d1].\n    destruct (foreign_DomRng _ WD1 _ _ _ Heqf) as [A [B [C [D [E [F [G H]]]]]]].\n    apply HypFrg in F.\n    destruct (frgnSrc _ WD2 _ F) as [b3 [d2 [FRG2 TGT2]]].\n    rewrite FRG2. trivial.\n  remember (pub_of mu12 b) as d; destruct d; apply eq_sym in Heqd; trivial.\n    destruct p as [b2 d1].\n    destruct (pub_locBlocks _ WD1 _ _ _ Heqd) as [A [B [C [D [E [F [G H]]]]]]].\n    apply HypPub in B.\n    destruct (pubSrc _ WD2 _ B) as [b3 [d2 [PUB2 TGT2]]].\n    rewrite PUB2.\n    apply (pubBlocksLocalSrc _ WD2) in B.\n    apply (locBlocksSrc_frgnBlocksSrc _ WD2) in B.\n    unfold foreign_of. destruct mu23. simpl in *. rewrite B. trivial.\nQed.\n\nLemma compose_sm_wd: forall mu1 mu2 (WD1: SM_wd mu1) (WD2:SM_wd mu2)\n         (HypPub: forall b, pubBlocksTgt mu1 b = true ->\n                            pubBlocksSrc mu2 b = true)\n         (HypFrg: forall b, frgnBlocksTgt mu1 b = true ->\n                            frgnBlocksSrc mu2 b = true),\n      SM_wd (compose_sm mu1 mu2).\nProof. intros.\n  destruct mu1 as [locBSrc1 locBTgt1 pSrc1 pTgt1 local1 extBSrc1 extBTgt1 fSrc1 fTgt1 extern1]; simpl.\n  destruct mu2 as [locBSrc2 locBTgt2 pSrc2 pTgt2 local2 extBSrc2 extBTgt2 fSrc2 fTgt2 extern2]; simpl.\nsplit; simpl in *.\napply WD1.\napply WD2.\n(*local_DomRng*)\n  intros b1 b3 d H.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n    as [b2 [d1 [d2 [PUB1 [PUB2 X]]]]]; subst; clear H.\n  split. eapply WD1. apply PUB1.\n         eapply WD2. apply PUB2.\n(*extern_DomRng*)\n  intros b1 b3 d H.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n    as [b2 [d1 [d2 [EXT1 [EXT2 X]]]]]; subst; clear H.\n  split. eapply WD1. apply EXT1.\n         eapply WD2. apply EXT2.\n(*pubSrc*)\n  intros.\n  destruct (pubSrc _ WD1 _ H) as [b2 [d1 [Loc1 Tgt1]]]. simpl in *.\n  apply HypPub in Tgt1.\n  destruct (pubSrc _ WD2 _ Tgt1) as [b3 [d2 [Loc2 Tgt2]]]. simpl in *.\n  unfold compose_meminj. exists b3, (d1+d2).\n  rewrite H in *. rewrite Tgt1 in *. rewrite Loc1. rewrite Loc2. auto.\n(*frgnSrc*)\n  intros.\n  destruct (frgnSrc _ WD1 _ H) as [b2 [d1 [Ext1 Tgt1]]]. simpl in *.\n  apply HypFrg in Tgt1.\n  destruct (frgnSrc _ WD2 _ Tgt1) as [b3 [d2 [Ext2 Tgt2]]]. simpl in *.\n  unfold compose_meminj. exists b3, (d1+d2).\n  rewrite H in *. rewrite Tgt1 in *. rewrite Ext1. rewrite Ext2. auto.\n(*locBlocksDomTgt*)\n  apply WD2.\n(*frgnBlocksDomTgt*)\n  apply WD2.\nQed.\n\nLemma compose_sm_as_inj: forall mu12 mu23 (WD1: SM_wd mu12) (WD2: SM_wd mu23)\n   (SrcTgtLoc: locBlocksTgt mu12 = locBlocksSrc mu23)\n   (SrcTgtExt: extBlocksTgt mu12 = extBlocksSrc mu23),\n   as_inj (compose_sm mu12 mu23) =\n   compose_meminj (as_inj mu12) (as_inj mu23).\nProof. intros.\n  unfold as_inj.\n  rewrite compose_sm_extern.\n  rewrite compose_sm_local.\n  unfold join, compose_meminj. extensionality b.\n  remember (extern_of mu12 b) as f; destruct f; apply eq_sym in Heqf.\n    destruct p as [b2 d1].\n    remember (extern_of mu23 b2) as d; destruct d; apply eq_sym in Heqd.\n      destruct p as [b3 d2]. trivial.\n    destruct (disjoint_extern_local _ WD1 b).\n       rewrite H in Heqf. discriminate.\n    rewrite H.\n    destruct (extern_DomRng _ WD1 _ _ _ Heqf) as [A B].\n    rewrite SrcTgtExt in B.\n    remember (local_of mu23 b2) as q; destruct q; trivial; apply eq_sym in Heqq.\n    destruct p as [b3 d2].\n    destruct (local_DomRng _ WD2 _ _ _ Heqq) as [AA BB].\n    destruct (disjoint_extern_local_Src _ WD2 b2); congruence.\n  remember (local_of mu12 b) as q; destruct q; trivial; apply eq_sym in Heqq.\n    destruct p as [b2 d1].\n    destruct (local_DomRng _ WD1 _ _ _ Heqq) as [AA BB].\n    remember (extern_of mu23 b2) as d; destruct d; trivial; apply eq_sym in Heqd.\n      destruct p as [b3 d2].\n      destruct (extern_DomRng _ WD2 _ _ _ Heqd) as [A B].\n      rewrite SrcTgtLoc in BB.\n      destruct (disjoint_extern_local_Src _ WD2 b2); congruence.\nQed.\n\nLemma compose_sm_intern_incr:\n      forall mu12 mu12' mu23 mu23'\n            (inc12: intern_incr mu12 mu12')\n            (inc23: intern_incr mu23 mu23'),\n      intern_incr (compose_sm mu12 mu23) (compose_sm mu12' mu23').\nProof. intros.\nsplit; simpl in *.\n    eapply compose_meminj_inject_incr.\n        apply inc12.\n        apply intern_incr_local; eassumption.\nsplit. rewrite (intern_incr_extern _ _ inc12).\n       rewrite (intern_incr_extern _ _ inc23).\n       trivial.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\napply inc23.\nQed.\n\nLemma compose_sm_extern_incr:\n      forall mu12 mu12' mu23 mu23'\n            (inc12: extern_incr mu12 mu12')\n            (inc23: extern_incr mu23 mu23')\n  (FRG': forall b1 b2 d1, foreign_of mu12' b1 = Some(b2,d1) ->\n         exists b3 d2, foreign_of mu23' b2 = Some(b3,d2))\n  (WD12': SM_wd mu12') (WD23': SM_wd mu23'),\n  extern_incr (compose_sm mu12 mu23) (compose_sm mu12' mu23').\nProof. intros.\nsplit; intros.\n  rewrite compose_sm_extern.\n  rewrite compose_sm_extern.\n  eapply compose_meminj_inject_incr.\n    apply inc12.\n    apply extern_incr_extern; eassumption.\nsplit; simpl.\n  rewrite (extern_incr_local _ _ inc12).\n  rewrite (extern_incr_local _ _ inc23).\n  trivial.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\nsplit. apply inc23.\nsplit. apply inc12.\napply inc23.\nQed.\n\nLemma extern_incr_inject_incr:\n      forall nu12 nu23 nu' (WDnu' : SM_wd nu')\n          (EXT: extern_incr (compose_sm nu12 nu23) nu')\n          (GlueInvNu: SM_wd nu12 /\\ SM_wd nu23 /\\\n                      locBlocksTgt nu12 = locBlocksSrc nu23 /\\\n                      extBlocksTgt nu12 = extBlocksSrc nu23 /\\\n                      (forall b, pubBlocksTgt nu12 b = true ->\n                                 pubBlocksSrc nu23 b = true) /\\\n                      (forall b, frgnBlocksTgt nu12 b = true ->\n                                 frgnBlocksSrc nu23 b = true)),\n      inject_incr (compose_meminj (as_inj nu12) (as_inj nu23)) (as_inj nu').\nProof. intros.\n  intros b; intros.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n    as [b2 [d1 [d2 [Nu12 [Nu23 D]]]]]; subst; clear H.\n  unfold extern_incr in EXT. simpl in EXT.\n  destruct EXT as [EXT [LOC [extBSrc12 [extBTgt23 [locBSrc12 [locBTgt23 [pubBSrc12 [pubBTgt23 [frgnBSrc12 frgnBTgt23]]]]]]]]].\n  destruct (joinD_Some _ _ _ _ _ Nu12); clear Nu12.\n  (*extern12*)\n     destruct (joinD_Some _ _ _ _ _ Nu23); clear Nu23.\n     (*extern12*)\n        apply join_incr_left. apply EXT.\n        unfold compose_meminj. rewrite H. rewrite H0. trivial.\n     (*local*)\n        destruct H0.\n        destruct GlueInvNu as [GLa [GLb [GLc [GLd [GLe GLf]]]]].\n        destruct (extern_DomRng' _ GLa _ _ _ H) as [? [? [? [? [? [? [? ?]]]]]]].\n        destruct (local_locBlocks _ GLb _ _ _ H1) as [? [? [? [? [? [? [? ?]]]]]]].\n        rewrite GLd in *. congruence.\n  (*local*)\n     destruct H.\n     destruct (joinD_Some _ _ _ _ _ Nu23); clear Nu23.\n     (*extern12*)\n        destruct GlueInvNu as [GLa [GLb [GLc [GLd [GLe GLf]]]]].\n        destruct (extern_DomRng' _ GLb _ _ _ H1) as [? [? [? [? [? ?]]]]].\n        destruct (local_locBlocks _ GLa _ _ _ H0) as [? [? [? [? [? ?]]]]].\n        rewrite GLd in *. congruence.\n     (*local*)\n        destruct H1.\n        apply join_incr_right. eapply disjoint_extern_local. apply WDnu'.\n        rewrite <- LOC. unfold compose_meminj.\n        rewrite H0, H2. trivial.\nQed.\n\nLemma compose_sm_as_injD: forall mu1 mu2 b1 b3 d\n      (I: as_inj (compose_sm mu1 mu2) b1 = Some (b3, d))\n      (WD1: SM_wd mu1) (WD2: SM_wd mu2),\n      exists b2 d1 d2, as_inj mu1 b1 = Some(b2,d1) /\\\n                       as_inj mu2 b2 = Some(b3,d2) /\\\n                       d=d1+d2.\nProof. intros.\ndestruct (joinD_Some _ _ _ _ _ I); clear I.\n(*extern*)\n  rewrite compose_sm_extern in H.\n  destruct (compose_meminjD_Some _ _ _ _ _ H)\n      as [b2 [d1 [d2 [EXT1 [EXT2 D]]]]]; clear H.\n  exists b2, d1, d2.\n  split. apply join_incr_left. assumption.\n  split. apply join_incr_left. assumption.\n         assumption.\n(*local*)\n  destruct H.\n  rewrite compose_sm_extern in H.\n  rewrite compose_sm_local in H0.\n  destruct (compose_meminjD_Some _ _ _ _ _ H0)\n      as [b2 [d1 [d2 [LOC1 [LOC2 D]]]]]; clear H0.\n  exists b2, d1, d2.\n  split. apply join_incr_right.\n           apply disjoint_extern_local; assumption.\n           assumption.\n  split. apply join_incr_right.\n           apply disjoint_extern_local; assumption.\n           assumption.\n         assumption.\nQed.\n\nLemma compose_sm_intern_separated:\n      forall mu12 mu12' mu23 mu23' m1 m2 m3\n        (inc12: intern_incr mu12 mu12')\n        (inc23: intern_incr mu23 mu23')\n        (InjSep12 : sm_inject_separated mu12 mu12' m1 m2)\n        (InjSep23 : sm_inject_separated mu23 mu23' m2 m3)\n        (WD12: SM_wd mu12) (WD12': SM_wd mu12') (WD23: SM_wd mu23) (WD23': SM_wd mu23')\n        (BlocksLoc: locBlocksTgt mu12 = locBlocksSrc mu23)\n        (BlocksExt: extBlocksTgt mu12 = extBlocksSrc mu23),\n      sm_inject_separated (compose_sm mu12 mu23)\n                          (compose_sm mu12' mu23') m1 m3.\nProof. intros.\ndestruct InjSep12 as [AsInj12 [DomTgt12 Sep12]].\ndestruct InjSep23 as [AsInj23 [DomTgt23 Sep23]].\nsplit.\n  intros b1 b3 d; intros.\n  simpl.\n  destruct (compose_sm_as_injD _ _ _ _ _ H0)\n     as [b2 [d1 [d2 [AI12' [AI23' X]]]]]; subst; trivial; clear H0.\n  rewrite compose_sm_DomSrc, compose_sm_DomTgt.\n  assert (DomSrc (compose_sm mu12' mu23') b1 = true /\\\n          DomTgt (compose_sm mu12' mu23') b3 = true).\n    rewrite compose_sm_DomSrc, compose_sm_DomTgt.\n    split. eapply as_inj_DomRng; eassumption.\n           eapply as_inj_DomRng; eassumption.\n  destruct H0 as [DOM1 TGT3]; simpl in *.\n  assert (TGT2: DomTgt mu12' b2 = true).\n    eapply as_inj_DomRng. eassumption. eapply WD12'.\n  assert (DOMB2: DomSrc mu23' b2 = true).\n    eapply as_inj_DomRng. eassumption. eapply WD23'.\n  rewrite compose_sm_DomSrc, compose_sm_DomTgt in *.\n  remember (as_inj mu12 b1) as q.\n  destruct q; apply eq_sym in Heqq.\n    destruct p.\n    specialize (intern_incr_as_inj _ _ inc12 WD12' _ _ _ Heqq); intros.\n    rewrite AI12' in H0. apply eq_sym in H0. inv H0.\n    destruct (joinD_Some _ _ _ _ _ Heqq); clear Heqq.\n    (*extern12Some*)\n       assert (extern_of mu12' b1 = Some (b2, d1)).\n          rewrite <- (intern_incr_extern _ _ inc12). assumption.\n       destruct (joinD_None _ _ _ H); clear H.\n       clear AI12'.\n       destruct (joinD_Some _ _ _ _ _ AI23'); clear AI23'.\n       (*extern23'Some*)\n         assert (extern_of mu23 b2 = Some (b3, d2)).\n           rewrite (intern_incr_extern _ _ inc23). assumption.\n         rewrite compose_sm_extern in H2.\n         unfold compose_meminj in H2.\n         rewrite H0 in H2. rewrite H4 in H2. inv H2.\n       (*extern23'None*)\n         destruct H.\n         rewrite compose_sm_extern in H2.\n         destruct (compose_meminjD_None _ _ _ H2); clear H2.\n            rewrite H5 in H0. discriminate.\n         destruct H5 as [bb2 [dd1 [EXT12 EXT23]]].\n         rewrite EXT12 in H0. inv H0.\n         rewrite compose_sm_local in H3.\n         remember (local_of mu23 b2) as qq.\n         destruct qq; apply eq_sym in Heqqq.\n            destruct p.\n            specialize (intern_incr_local _ _ inc23); intros.\n            specialize (H0 _ _ _ Heqqq). rewrite H0 in H4. inv H4.\n            destruct (extern_DomRng _ WD12 _ _ _ EXT12) as [A B].\n            destruct (local_DomRng _ WD23 _ _ _ Heqqq) as [AA BB].\n            rewrite BlocksExt in B.\n            destruct (disjoint_extern_local_Src _ WD23 b2); congruence.\n         destruct (AsInj23 b2 b3 d2).\n            apply joinI_None. assumption. assumption.\n            apply join_incr_right.\n              apply disjoint_extern_local. assumption.\n              assumption.\n         destruct (extern_DomRng _ WD12 _ _ _ EXT12) as [XX YY].\n           rewrite BlocksExt in YY. unfold DomSrc in H0.\n           rewrite YY in H0. rewrite orb_comm in H0. discriminate.\n    (*extern12None*)\n       destruct H0.\n       assert (extern_of mu12' b1 = None).\n          rewrite <- (intern_incr_extern _ _ inc12). assumption.\n       assert (local_of mu12' b1 = Some (b2, d1)).\n          eapply (intern_incr_local _ _ inc12). assumption.\n       destruct (joinD_None _ _ _ H); clear H.\n       clear AI12'.\n       destruct (joinD_Some _ _ _ _ _ AI23'); clear AI23'.\n       (*extern23'Some*)\n         destruct (local_DomRng _ WD12' _ _ _ H3) as [AA BB].\n         destruct (extern_DomRng _ WD23' _ _ _ H) as [A B].\n         destruct (local_DomRng _ WD12 _ _ _ H1) as [AAA BBB].\n         rewrite BlocksLoc in BBB.\n         assert (locBlocksSrc mu23' b2 = true). apply inc23. assumption.\n         destruct (disjoint_extern_local_Src _ WD23' b2); congruence.\n       (*extern23'None*)\n         destruct H.\n         assert (extern_of mu23 b2 = None).\n           rewrite (intern_incr_extern _ _ inc23). assumption.\n         rewrite compose_sm_local in H5.\n         unfold compose_meminj in H5. rewrite H1 in H5.\n         remember (local_of mu23 b2).\n         destruct o. destruct p. inv H5. clear H5. apply eq_sym in Heqo.\n         clear H4.\n         destruct (local_DomRng _ WD12 _ _ _ H1) as [AA BB].\n         assert (DomSrc mu23 b2 = false /\\ DomTgt mu23 b3 = false).\n            eapply AsInj23.\n              apply joinI_None; assumption.\n              apply join_incr_right; try eassumption.\n                apply disjoint_extern_local; eassumption.\n         destruct H4.\n         destruct (local_locBlocks _ WD12 _ _ _ H1)\n           as [AAA [BBB [CCC [DDD [EEE FFF]]]]].\n         rewrite BlocksLoc in BBB. unfold DomSrc in H4.\n             rewrite BBB in H4. discriminate.\n   (*as_inj mu12 b1 = None*)\n     destruct (AsInj12 _ _ _ Heqq AI12'). split; trivial. clear H.\n     remember (as_inj mu23 b2) as d.\n     destruct d; apply eq_sym in Heqd.\n       destruct p.\n       specialize (intern_incr_as_inj _ _ inc23 WD23' _ _ _ Heqd).\n       intros ZZ; rewrite AI23' in ZZ. apply eq_sym in ZZ; inv ZZ.\n       destruct (as_inj_DomRng _ _ _ _ Heqd WD23).\n       unfold DomSrc in H. unfold DomTgt in H1.\n       rewrite BlocksLoc, BlocksExt in H1. rewrite H1 in H; discriminate.\n     eapply AsInj23. eassumption. eassumption.\nsimpl.\n  split. apply DomTgt12. apply Sep23.\nQed.\n\nLemma vis_compose_sm: forall mu nu, vis (compose_sm mu nu) = vis mu.\nProof. intros. unfold vis. destruct mu; simpl. reflexivity. Qed.\n\nLemma restrict_compose: forall j k X,\n  restrict (compose_meminj j k) X = compose_meminj (restrict j X) k.\nProof. intros.\n  extensionality b.\n  unfold compose_meminj, restrict.\n  remember (X b) as d.\n  destruct d; trivial.\nQed.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/sepcomp/effect_simulations_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.20608814300693068}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import BaremoreHandler.Spec.\nRequire Import AbsAccessor.Spec.\nRequire Import SMCHandler.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n  Definition rmm_handler_spec  (adt: RData) : option RData :=\n    when adt == el3_sync_lel_spec  adt;\n    when adt == enter_rmm_spec  adt;\n    when' _function_id == read_reg_spec 0 adt;\n    rely is_int64 _function_id;\n    when' _arg0 == read_reg_spec 1 adt;\n    rely is_int64 _arg0;\n    when' _arg1 == read_reg_spec 2 adt;\n    rely is_int64 _arg1;\n    when' _arg2 == read_reg_spec 3 adt;\n    rely is_int64 _arg2;\n    when' _arg3 == read_reg_spec 4 adt;\n    rely is_int64 _arg3;\n    when' _ret, adt == handle_ns_smc_spec (VZ64 _function_id) (VZ64 _arg0) (VZ64 _arg1) (VZ64 _arg2) (VZ64 _arg3) adt;\n    rely is_int64 _ret;\n    if (negb (_ret =? 2)) then\n      when adt == exit_rmm_spec (VZ64 _ret) adt;\n      when adt == el3_sync_lel_spec  adt;\n      Some adt\n    else\n      Some adt.\n\nEnd Spec.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RMMHandler/Specs/rmm_handler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.20608814300693065}}
{"text": "From mathcomp\nRequire Import ssreflect ssrbool ssrnat eqtype seq ssrfun.\nFrom fcsl\nRequire Import prelude pred pcm unionmap heap.\nFrom HTT\nRequire Import stmod stsep stlog stlogR.\nFrom SSL\nRequire Import core.\nFrom Hammer Require Import Hammer.\n(* Configure Hammer *)\nSet Hammer ATPLimit 60.\nUnset Hammer Eprover.\nUnset Hammer Vampire.\nAdd Search Blacklist \"fcsl.\".\nAdd Search Blacklist \"HTT.\".\nAdd Search Blacklist \"Coq.ssr.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.ssrfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.bigop\".\nAdd Search Blacklist \"mathcomp.ssreflect.choice\".\nAdd Search Blacklist \"mathcomp.ssreflect.div\".\nAdd Search Blacklist \"mathcomp.ssreflect.finfun\".\nAdd Search Blacklist \"mathcomp.ssreflect.fintype\".\nAdd Search Blacklist \"mathcomp.ssreflect.path\".\nAdd Search Blacklist \"mathcomp.ssreflect.tuple\".\n\n\nRequire Import common.\n\nLemma pure1 (sz1 : nat) (sz1r1 : nat) (sz2r1 : nat) : (0) <= (sz2r1) -> (0) <= (((1) + (sz1r1)) + (sz2r1)) -> (0) <= (sz1) -> (0) <= (sz1r1) -> (0) <= (((1) + (sz1)) + (sz1r1)). intros; hammer. Qed.\nHint Resolve pure1: ssl_pure.\nLemma pure2 (sz1 : nat) (sz1r1 : nat) (sz2r1 : nat) : (0) <= (sz2r1) -> (0) <= (((1) + (sz1r1)) + (sz2r1)) -> (0) <= (sz1) -> (0) <= (sz1r1) -> ((((1) + (sz1)) + (sz1r1)) + (sz2r1)) = ((sz1) + (((1) + (sz1r1)) + (sz2r1))). intros; hammer. Qed.\nHint Resolve pure2: ssl_pure.\nLemma pure3 (lo1r1 : nat) (hi1 : nat) (lo2r1 : nat) (v1 : nat) (hi1r1 : nat) (vr11 : nat) : (0) <= (vr11) -> (vr11) <= (7) -> (0) <= (v1) -> (hi1) <= (v1) -> (hi1r1) <= (vr11) -> (v1) <= ((if (vr11) <= (lo1r1) then vr11 else lo1r1)) -> (v1) <= (7) -> (vr11) <= (lo2r1) -> (v1) <= (lo1r1).\n  (* intros; hammer. *)\n  intros.\n  destruct (vr11 <= lo1r1) eqn:H7=>//.\n  apply: (leq_trans H4)=>//.\nQed.\nHint Resolve pure3: ssl_pure.\nLemma pure4 (lo1r1 : nat) (hi1 : nat) (lo2r1 : nat) (v1 : nat) (hi1r1 : nat) (vr11 : nat) : (0) <= (vr11) -> (vr11) <= (7) -> (0) <= (v1) -> (hi1) <= (v1) -> (hi1r1) <= (vr11) -> (v1) <= ((if (vr11) <= (lo1r1) then vr11 else lo1r1)) -> (v1) <= (7) -> (vr11) <= (lo2r1) -> ((if (hi1r1) <= (v1) then v1 else hi1r1)) <= (vr11).\n  (* intros; hammer. *)\n  intros.\n  case (hi1r1 <= v1); last by done.\n  destruct (vr11 <= lo1r1) eqn:H7; first by done.\n  apply negbT in H7.\n  rewrite -ltnNge in H7.\n  apply ltnW.\n  exact (leq_ltn_trans H4 H7).\nQed.\nHint Resolve pure4: ssl_pure.\n\nDefinition bst_left_rotate_type :=\n  forall (vprogs : ptr * ptr),\n  {(vghosts : nat * nat * nat * nat * ptr * nat * ptr * nat * nat * ptr)},\n  STsep (\n    fun h =>\n      let: (x, retv) := vprogs in\n      let: (sz1, sz2, v, hi1, r, lo2, l, lo1, hi2, unused) := vghosts in\n      exists h_bst_lsz1lo1hi1_a h_bst_rsz2lo2hi2_b,\n      (0) <= (sz1) /\\ (0) <= (sz2) /\\ (0) <= (v) /\\ (hi1) <= (v) /\\ ~~ ((r) == (null)) /\\ (v) <= (7) /\\ (v) <= (lo2) /\\ h = retv :-> (unused) \\+ x :-> (v) \\+ x .+ 1 :-> (l) \\+ x .+ 2 :-> (r) \\+ h_bst_lsz1lo1hi1_a \\+ h_bst_rsz2lo2hi2_b /\\ bst l sz1 lo1 hi1 h_bst_lsz1lo1hi1_a /\\ bst r sz2 lo2 hi2 h_bst_rsz2lo2hi2_b,\n    [vfun (_: unit) h =>\n      let: (x, retv) := vprogs in\n      let: (sz1, sz2, v, hi1, r, lo2, l, lo1, hi2, unused) := vghosts in\n      exists sz3 sz4 v3 hi3 lo4 lo3 r3 hi4 y,\n      exists h_bst_xsz3lo3hi3_2 h_bst_r3sz4lo4hi4_3,\n      (0) <= (sz3) /\\ (0) <= (sz4) /\\ (0) <= (v3) /\\ (hi3) <= (v3) /\\ ((sz3) + (sz4)) == ((sz1) + (sz2)) /\\ (v3) <= (7) /\\ (v3) <= (lo4) /\\ h = retv :-> (y) \\+ y :-> (v3) \\+ y .+ 1 :-> (x) \\+ y .+ 2 :-> (r3) \\+ h_bst_xsz3lo3hi3_2 \\+ h_bst_r3sz4lo4hi4_3 /\\ bst x sz3 lo3 hi3 h_bst_xsz3lo3hi3_2 /\\ bst r3 sz4 lo4 hi4 h_bst_r3sz4lo4hi4_3\n    ]).\n\nProgram Definition bst_left_rotate : bst_left_rotate_type :=\n  Fix (fun (bst_left_rotate : bst_left_rotate_type) vprogs =>\n    let: (x, retv) := vprogs in\n    Do (\n      unused1 <-- @read ptr retv;\n      v1 <-- @read nat x;\n      l1 <-- @read ptr (x .+ 1);\n      r1 <-- @read ptr (x .+ 2);\n      if (r1) == (null)\n      then\n        ret tt\n      else\n        vr11 <-- @read nat r1;\n        lr11 <-- @read ptr (r1 .+ 1);\n        rr11 <-- @read ptr (r1 .+ 2);\n        (r1 .+ 1) ::= x;;\n        (x .+ 2) ::= lr11;;\n        retv ::= r1;;\n        ret tt\n    )).\nObligation Tactic := intro; move=>[x retv]; ssl_program_simpl.\nNext Obligation.\nssl_ghostelim_pre.\nmove=>[[[[[[[[[sz1 sz2] v] hi1] r] lo2] l] lo1] hi2] unused].\nex_elim h_bst_lsz1lo1hi1_a h_bst_rsz2lo2hi2_b.\nmove=>[phi_self0] [phi_self1] [phi_self2] [phi_self3] [phi_self4] [phi_self5] [phi_self6].\nmove=>[sigma_self].\nsubst h_self.\nmove=>[H_bst_lsz1lo1hi1_a H_bst_rsz2lo2hi2_b].\nssl_ghostelim_post.\nssl_read retv.\ntry rename unused into unused1.\nssl_read x.\ntry rename v into v1.\nssl_read (x .+ 1).\ntry rename l into l1.\ntry rename h_bst_lsz1lo1hi1_a into h_bst_l1sz1lo1hi1_a.\ntry rename H_bst_lsz1lo1hi1_a into H_bst_l1sz1lo1hi1_a.\nssl_read (x .+ 2).\ntry rename r into r1.\ntry rename h_bst_rsz2lo2hi2_b into h_bst_r1sz2lo2hi2_b.\ntry rename H_bst_rsz2lo2hi2_b into H_bst_r1sz2lo2hi2_b.\nssl_open ((r1) == (null)) H_bst_r1sz2lo2hi2_b.\nmove=>[phi_bst_r1sz2lo2hi2_b0] [phi_bst_r1sz2lo2hi2_b1] [phi_bst_r1sz2lo2hi2_b2].\nmove=>[sigma_bst_r1sz2lo2hi2_b].\nsubst h_bst_r1sz2lo2hi2_b.\nssl_inconsistency.\nex_elim sz1r1 sz2r1 vr1 hi2r1 hi1r1.\nex_elim lo1r1 lo2r1 lr1 rr1.\nex_elim h_bst_lr1sz1r1lo1r1hi1r1_0r1 h_bst_rr1sz2r1lo2r1hi2r1_1r1.\nmove=>[phi_bst_r1sz2lo2hi2_b0] [phi_bst_r1sz2lo2hi2_b1] [phi_bst_r1sz2lo2hi2_b2] [phi_bst_r1sz2lo2hi2_b3] [phi_bst_r1sz2lo2hi2_b4] [phi_bst_r1sz2lo2hi2_b5] [phi_bst_r1sz2lo2hi2_b6] [phi_bst_r1sz2lo2hi2_b7] [phi_bst_r1sz2lo2hi2_b8].\nmove=>[sigma_bst_r1sz2lo2hi2_b].\nsubst h_bst_r1sz2lo2hi2_b.\nmove=>[H_bst_lr1sz1r1lo1r1hi1r1_0r1 H_bst_rr1sz2r1lo2r1hi2r1_1r1].\ntry rename h_bst_r1sz2lo2hi2_b into h_bst_r1sz2lo2hi2r1vr1vr1hi2r1_b.\ntry rename H_bst_r1sz2lo2hi2_b into H_bst_r1sz2lo2hi2r1vr1vr1hi2r1_b.\ntry rename h_bst_r1sz2lo2hi2r1vr1vr1hi2r1_b into h_bst_r1sz2vr1lo1r1vr1lo1r1hi2r1vr1vr1hi2r1_b.\ntry rename H_bst_r1sz2lo2hi2r1vr1vr1hi2r1_b into H_bst_r1sz2vr1lo1r1vr1lo1r1hi2r1vr1vr1hi2r1_b.\ntry rename h_bst_r1sz2vr1lo1r1vr1lo1r1hi2r1vr1vr1hi2r1_b into h_bst_r1sz1r1sz2r1vr1lo1r1vr1lo1r1hi2r1vr1vr1hi2r1_b.\ntry rename H_bst_r1sz2vr1lo1r1vr1lo1r1hi2r1vr1vr1hi2r1_b into H_bst_r1sz1r1sz2r1vr1lo1r1vr1lo1r1hi2r1vr1vr1hi2r1_b.\nssl_read r1.\ntry rename vr1 into vr11.\ntry rename h_bst_r1sz1r1sz2r1vr1lo1r1vr1lo1r1hi2r1vr1vr1hi2r1_b into h_bst_r1sz1r1sz2r1vr11lo1r1vr11lo1r1hi2r1vr11vr11hi2r1_b.\ntry rename H_bst_r1sz1r1sz2r1vr1lo1r1vr1lo1r1hi2r1vr1vr1hi2r1_b into H_bst_r1sz1r1sz2r1vr11lo1r1vr11lo1r1hi2r1vr11vr11hi2r1_b.\nssl_read (r1 .+ 1).\ntry rename lr1 into lr11.\ntry rename h_bst_lr1sz1r1lo1r1hi1r1_0r1 into h_bst_lr11sz1r1lo1r1hi1r1_0r1.\ntry rename H_bst_lr1sz1r1lo1r1hi1r1_0r1 into H_bst_lr11sz1r1lo1r1hi1r1_0r1.\nssl_read (r1 .+ 2).\ntry rename rr1 into rr11.\ntry rename h_bst_rr1sz2r1lo2r1hi2r1_1r1 into h_bst_rr11sz2r1lo2r1hi2r1_1r1.\ntry rename H_bst_rr1sz2r1lo2r1hi2r1_1r1 into H_bst_rr11sz2r1lo2r1hi2r1_1r1.\ntry rename h_bst_xsz3lo3hi3_2 into h_bst_xsz3lo3hi21xv2xv2xhi21x_2.\ntry rename H_bst_xsz3lo3hi3_2 into H_bst_xsz3lo3hi21xv2xv2xhi21x_2.\ntry rename h_bst_xsz3lo3hi21xv2xv2xhi21x_2 into h_bst_xsz3v2xlo11xv2xlo11xhi21xv2xv2xhi21x_2.\ntry rename H_bst_xsz3lo3hi21xv2xv2xhi21x_2 into H_bst_xsz3v2xlo11xv2xlo11xhi21xv2xv2xhi21x_2.\ntry rename h_bst_xsz3v2xlo11xv2xlo11xhi21xv2xv2xhi21x_2 into h_bst_xsz11xsz21xv2xlo11xv2xlo11xhi21xv2xv2xhi21x_2.\ntry rename H_bst_xsz3v2xlo11xv2xlo11xhi21xv2xv2xhi21x_2 into H_bst_xsz11xsz21xv2xlo11xv2xlo11xhi21xv2xv2xhi21x_2.\ntry rename h_bst_r3sz4lo4hi4_3 into h_bst_rr11sz2r1lo2r1hi2r1_1r1.\ntry rename H_bst_r3sz4lo4hi4_3 into H_bst_rr11sz2r1lo2r1hi2r1_1r1.\ntry rename h_bst_l2xsz11xlo11xhi11x_0x into h_bst_l1sz1lo1hi1_a.\ntry rename H_bst_l2xsz11xlo11xhi11x_0x into H_bst_l1sz1lo1hi1_a.\ntry rename h_bst_xsz11xsz21xv2xlo11xv2xlo11xhi21xv2xv2xhi21x_2 into h_bst_xsz11xsz21xv2xlo1v2xlo1hi21xv2xv2xhi21x_2.\ntry rename H_bst_xsz11xsz21xv2xlo11xv2xlo11xhi21xv2xv2xhi21x_2 into H_bst_xsz11xsz21xv2xlo1v2xlo1hi21xv2xv2xhi21x_2.\ntry rename h_bst_xsz11xsz21xv2xlo1v2xlo1hi21xv2xv2xhi21x_2 into h_bst_xsz1sz21xv2xlo1v2xlo1hi21xv2xv2xhi21x_2.\ntry rename H_bst_xsz11xsz21xv2xlo1v2xlo1hi21xv2xv2xhi21x_2 into H_bst_xsz1sz21xv2xlo1v2xlo1hi21xv2xv2xhi21x_2.\ntry rename h_bst_r2xsz21xlo21xhi21x_1x into h_bst_lr11sz1r1lo1r1hi1r1_0r1.\ntry rename H_bst_r2xsz21xlo21xhi21x_1x into H_bst_lr11sz1r1lo1r1hi1r1_0r1.\ntry rename h_bst_xsz1sz21xv2xlo1v2xlo1hi21xv2xv2xhi21x_2 into h_bst_xsz1sz21xv2xlo1v2xlo1hi1r1v2xv2xhi1r1_2.\ntry rename H_bst_xsz1sz21xv2xlo1v2xlo1hi21xv2xv2xhi21x_2 into H_bst_xsz1sz21xv2xlo1v2xlo1hi1r1v2xv2xhi1r1_2.\ntry rename h_bst_xsz1sz21xv2xlo1v2xlo1hi1r1v2xv2xhi1r1_2 into h_bst_xsz1sz1r1v2xlo1v2xlo1hi1r1v2xv2xhi1r1_2.\ntry rename H_bst_xsz1sz21xv2xlo1v2xlo1hi1r1v2xv2xhi1r1_2 into H_bst_xsz1sz1r1v2xlo1v2xlo1hi1r1v2xv2xhi1r1_2.\nssl_write (r1 .+ 1).\nssl_write_post (r1 .+ 1).\nssl_write (x .+ 2).\nssl_write_post (x .+ 2).\nssl_write retv.\nssl_write_post retv.\ntry rename h_bst_xsz1sz1r1v2xlo1v2xlo1hi1r1v2xv2xhi1r1_2 into h_bst_xsz1sz1r1v1lo1v1lo1hi1r1v1v1hi1r1_2.\ntry rename H_bst_xsz1sz1r1v2xlo1v2xlo1hi1r1v2xv2xhi1r1_2 into H_bst_xsz1sz1r1v1lo1v1lo1hi1r1v1v1hi1r1_2.\nssl_emp;\nexists (((1) + (sz1)) + (sz1r1)), (sz2r1), (vr11), ((if (hi1r1) <= (v1) then v1 else hi1r1)), (lo2r1), ((if (v1) <= (lo1) then v1 else lo1)), (rr11), (hi2r1), (r1);\nexists (x :-> (v1) \\+ x .+ 1 :-> (l1) \\+ x .+ 2 :-> (lr11) \\+ h_bst_l1sz1lo1hi1_a \\+ h_bst_lr11sz1r1lo1r1hi1r1_0r1);\nexists (h_bst_rr11sz2r1lo2r1hi2r1_1r1);\nsslauto.\nssl_close 2;\nexists (sz1), (sz1r1), (v1), (hi1r1), (hi1), (lo1), (lo1r1), (l1), (lr11), (h_bst_l1sz1lo1hi1_a), (h_bst_lr11sz1r1lo1r1hi1r1_0r1);\nsslauto.\nshelve.\nshelve.\nssl_frame_unfold.\nUnshelve.\nssl_frame_unfold.\nssl_frame_unfold.\nQed.\n", "meta": {"author": "TyGuS", "repo": "ssl-htt", "sha": "3ee4aad8e6d336dc2520eb2c62f90c8f98d9113d", "save_path": "github-repos/coq/TyGuS-ssl-htt", "path": "github-repos/coq/TyGuS-ssl-htt/ssl-htt-3ee4aad8e6d336dc2520eb2c62f90c8f98d9113d/benchmarks/advanced/bst/bst_left_rotate.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.20608813522623926}}
{"text": "From isla Require Import opsem.\n\nDefinition a7410 : isla_trace :=\n  AssumeReg \"HCR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x80000000%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL3\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL2\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL1\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL0\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"TCR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x0%Z))) Mk_annot :t:\n  Smt (DeclareConst 27%Z (Ty_BitVec 1%N)) Mk_annot :t:\n  AssumeReg \"PSTATE\" [Field \"EL\"] (RegVal_Base (Val_Bits (BV 2%N 0x2%Z))) Mk_annot :t:\n  AssumeReg \"PSTATE\" [Field \"nRW\"] (RegVal_Base (Val_Bits (BV 1%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"SCR_EL3\" [] (RegVal_Base (Val_Bits (BV 32%N 0x501%Z))) Mk_annot :t:\n  ReadReg \"PSTATE\" [Field \"Z\"] (RegVal_Struct [(\"Z\", RegVal_Base (Val_Symbolic 27%Z))]) Mk_annot :t:\n  Smt (DefineConst 38%Z (Unop (Not) (Binop (Eq) (Val (Val_Symbolic 27%Z) Mk_annot) (Val (Val_Bits (BV 1%N 0x1%Z)) Mk_annot) Mk_annot) Mk_annot)) Mk_annot :t:\n  tcases [\n    Smt (Assert (Val (Val_Symbolic 38%Z) Mk_annot)) Mk_annot :t:\n    Smt (DeclareConst 39%Z (Ty_BitVec 64%N)) Mk_annot :t:\n    ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 39%Z)) Mk_annot :t:\n    Smt (DefineConst 40%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 39%Z) Mk_annot; Val (Val_Bits (BV 64%N 0xfffffffffffff3f0%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n    Smt (DefineConst 52%Z (Val (Val_Symbolic 40%Z) Mk_annot)) Mk_annot :t:\n    BranchAddress (RegVal_Base (Val_Symbolic 52%Z)) Mk_annot :t:\n    Smt (DefineConst 53%Z (Val (Val_Symbolic 40%Z) Mk_annot)) Mk_annot :t:\n    WriteReg \"_PC\" [] (RegVal_Base (Val_Symbolic 53%Z)) Mk_annot :t:\n    tnil;\n    Smt (Assert (Unop (Not) (Val (Val_Symbolic 38%Z) Mk_annot) Mk_annot)) Mk_annot :t:\n    Smt (DeclareConst 39%Z (Ty_BitVec 64%N)) Mk_annot :t:\n    ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 39%Z)) Mk_annot :t:\n    Smt (DefineConst 40%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 39%Z) Mk_annot; Val (Val_Bits (BV 64%N 0x4%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n    WriteReg \"_PC\" [] (RegVal_Base (Val_Symbolic 40%Z)) Mk_annot :t:\n    tnil\n  ]\n.\n", "meta": {"author": "rems-project", "repo": "islaris", "sha": "fcc5791c74a2f791dee9080263cd64e42e73bc39", "save_path": "github-repos/coq/rems-project-islaris", "path": "github-repos/coq/rems-project-islaris/islaris-fcc5791c74a2f791dee9080263cd64e42e73bc39/pkvm_handler/a7410.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.20608813522623923}}
{"text": "Require Import syntax.\nRequire Import alist.\nRequire Import FMapWeakList.\n\nRequire Import Classical.\nRequire Import Coqlib.\nRequire Import infrastructure.\nRequire Import Metatheory.\nImport LLVMsyntax.\nImport LLVMinfra.\nRequire Import opsem.\nRequire Import memory_props.\n\nRequire Import sflib.\nRequire Import paco.\nImport Opsem.\n\nRequire Import TODO.\nRequire Import Exprs.\nRequire Import Hints.\nRequire Import Postcond.\nRequire Import Validator.\nRequire Import GenericValues.\nRequire AssnMem.\nRequire AssnState.\nRequire Import Inject.\nRequire Import SoundBase.\nRequire Import TODOProof.\nImport Memory.\nRequire Import MemAux.\n\nSet Implicit Arguments.\n\n(* TODO: move *)\nLemma some_injective A (a b:A):\n  Some a = Some b -> a = b.\nProof.\n  congruence.\nQed.\n\nInductive mem_change_inject (conf conf_tgt:Config) assnmem: mem_change -> mem_change -> Prop :=\n| mem_change_inject_alloca_alloca\n    gsz gn0 gn1 a\n    ty dv\n    (N_INJECT: genericvalues_inject.gv_inject assnmem.(AssnMem.Rel.inject) gn0 gn1)\n  : mem_change_inject conf conf_tgt assnmem\n                      (mem_change_alloca dv ty gsz gn0 a)\n                      (mem_change_alloca dv ty gsz gn1 a)\n| mem_change_inject_alloca_none\n    gsz gn a ty dv\n  : mem_change_inject conf conf_tgt assnmem\n                      (mem_change_alloca dv ty gsz gn a)\n                      mem_change_none\n| mem_change_inject_none_alloca\n    gsz gn a ty dv\n  : mem_change_inject conf conf_tgt\n                      assnmem mem_change_none\n                      (mem_change_alloca dv ty gsz gn a)\n| mem_change_inject_store_store\n    ptr0 ptr1 gv0 gv1 ty a\n    (PTR_INJECT: genericvalues_inject.gv_inject assnmem.(AssnMem.Rel.inject) ptr0 ptr1)\n    (VAL_INJECT: genericvalues_inject.gv_inject assnmem.(AssnMem.Rel.inject) gv0 gv1)\n  : mem_change_inject conf conf_tgt assnmem\n                      (mem_change_store ptr0 ty gv0 a)\n                      (mem_change_store ptr1 ty gv1 a)\n| mem_change_inject_store_nop\n    ptr gv ty a\n    (DISJOINT: forall b (GV2BLOCKS: In b (GV2blocks ptr)),\n        <<NOT_PUBLIC: ~ AssnMem.Rel.public_src assnmem.(AssnMem.Rel.inject) b>> /\\\n        <<PARENT_DISJOINT: ~ In b assnmem.(AssnMem.Rel.src).(AssnMem.Unary.private_parent)>>)\n  : mem_change_inject conf conf_tgt assnmem\n                      (mem_change_store ptr ty gv a)\n                      mem_change_none\n| mem_change_inject_free\n    ptr0 ptr1\n    (PTR_INJECT: genericvalues_inject.gv_inject assnmem.(AssnMem.Rel.inject) ptr0 ptr1)\n  : mem_change_inject conf conf_tgt assnmem\n                      (mem_change_free ptr0)\n                      (mem_change_free ptr1)\n| mem_change_inject_none\n  : mem_change_inject conf conf_tgt assnmem\n                      mem_change_none\n                      mem_change_none\n.\n\nInductive states_mem_change conf mem0 mem1: mem_change -> Prop :=\n| states_mem_change_alloca\n    ty bsz gn a dv mb\n    (ALLOCA: alloca conf.(CurTargetData) mem0 bsz gn a = Some (mem1, mb))\n  : states_mem_change conf mem0 mem1 (mem_change_alloca dv ty bsz gn a)\n| states_mem_change_store\n    ptr ty gv a\n    (VALID_PTRS: MemProps.valid_ptrs mem0.(Mem.nextblock) gv)\n    (STORE: mstore conf.(CurTargetData) mem0 ptr ty gv a = Some mem1)\n  : states_mem_change conf mem0 mem1 (mem_change_store ptr ty gv a)\n| states_mem_change_free\n    ptr\n    (FREE: free conf.(CurTargetData) mem0 ptr = Some mem1)\n  : states_mem_change conf mem0 mem1 (mem_change_free ptr)\n| states_mem_change_none\n    (MEM_EQ: mem0 = mem1)\n  : states_mem_change conf mem0 mem1 mem_change_none\n.\n\n(* Relation between mem_change and cmd *)\n\nLemma gv_inject_ptr_public_src\n      assnmem ptr0 ptr1 b ofs conf_src\n      (PTR_INJECT : genericvalues_inject.gv_inject (AssnMem.Rel.inject assnmem) ptr0 ptr1)\n      (PTR : GV2ptr (CurTargetData conf_src) (getPointerSize (CurTargetData conf_src)) ptr0 = Some (Values.Vptr b ofs))\n  : AssnMem.Rel.public_src (AssnMem.Rel.inject assnmem) b.\nProof.\n  exploit genericvalues_inject.simulation__GV2ptr; try exact PTR; eauto. i. des.\n  ii. inv x1. clarify.\nQed.\n\nLemma simulation__GV2ptr_tgt\n     : forall (mi : Values.meminj) (TD : TargetData) (gv1 gv1' : GenericValue) (v' : Values.val),\n       genericvalues_inject.gv_inject mi gv1 gv1' ->\n       GV2ptr TD (getPointerSize TD) gv1' = Some v' ->\n       exists v : Values.val, GV2ptr TD (getPointerSize TD) gv1 = Some v /\\ memory_sim.MoreMem.val_inject mi v v'.\nProof.\nAbort.\n\n(* Subset *)\n\nLemma forget_memory_unary_Subset\n      def_mem leaks_mem inv0\n  : Assertion.Subset_unary (ForgetMemory.unary def_mem leaks_mem inv0) inv0.\nProof.\n  unfold ForgetMemory.unary.\n  destruct leaks_mem; destruct def_mem.\n  - econs; ss; ii; des_ifs; try econs; ss.\n    + eapply ExprPairSetFacts.filter_iff in H; try by solve_compat_bool. des. eauto.\n    + eapply AtomSetFacts.remove_iff in H; try by solve_compat_bool. des. eauto.\n  - econs; ss; ii; des_ifs; try econs; ss.\n    eapply AtomSetFacts.remove_iff in H; try by solve_compat_bool. des. eauto.\n  - econs; ss; ii; des_ifs; try econs; ss.\n    eapply ExprPairSetFacts.filter_iff in H; try by solve_compat_bool. des. eauto.\n  - econs; ss; ii; des_ifs; try econs; ss.\nQed.\n\nLemma forget_memory_Subset\n      def_mem_src def_mem_tgt\n      leaks_mem_src leaks_mem_tgt\n      inv0\n  : Assertion.Subset (ForgetMemory.t def_mem_src def_mem_tgt leaks_mem_src leaks_mem_tgt inv0) inv0.\nProof.\n  unfold ForgetMemory.t; des_ifs;\n    econs; ss; try reflexivity; apply forget_memory_unary_Subset.\nQed.\n\n(* soundness proof *)\n\nLemma step_mem_change\n      st0 st1 invst0 assnmem0 inv0\n      cmd cmds\n      conf evt gmax public\n      (STATE: AssnState.Unary.sem conf st0 invst0 assnmem0 gmax public inv0)\n      (MEM: AssnMem.Unary.sem conf gmax public st0.(Mem) assnmem0)\n      (CMD: st0.(EC).(CurCmds) = cmd::cmds)\n      (NONCALL: Instruction.isCallInst cmd = false)\n      (NONMALLOC: isMallocInst cmd = false)\n      (STEP: sInsn conf st0 st1 evt)\n  : <<UNIQUE_PARENT_MEM:\n      forall mptr typ align val'\n        (LOAD: mload conf.(CurTargetData) st1.(Mem) mptr typ align = Some val'),\n        AssnMem.gv_diffblock_with_blocks conf val' assnmem0.(AssnMem.Unary.unique_parent)>> /\\\n        exists mc,\n          <<MC_SOME: mem_change_of_cmd conf cmd st0.(EC).(Locals) = Some mc>> /\\\n          <<STATE_EQUIV: states_mem_change conf st0.(Mem) st1.(Mem) mc>>.\nProof.\n  assert (MEM':=MEM).\n  inv MEM'.\n  inv STEP; destruct cmd; ss; clarify;\n    try by esplits; ss; econs; eauto.\n  - split.\n    + ii. eapply UNIQUE_PARENT_MEM; eauto.\n      eapply MemProps.free_preserves_mload_inv; eauto.\n    + esplits; ss.\n      * des_ifs.\n      * econs; eauto.\n  - split.\n    + ii.\n      exploit MemProps.alloca_preserves_mload_inv; eauto. i. des.\n      { eapply UNIQUE_PARENT_MEM; eauto. }\n      { ss.\n        eapply AssnState.Unary.undef_diffblock; eauto.\n        eapply {|\n            CurSystem := S;\n            CurTargetData := TD;\n            CurProducts := Ps;\n            Globals := gl;\n            FunTable := fs |}.\n      }\n    + esplits; ss.\n      * des_ifs.\n      * econs; eauto.\n  - split.\n    + ii.\n      exploit (mstore_never_produce_new_ptr' {| CurSystem := S;\n                                                CurTargetData := TD;\n                                                CurProducts := Ps;\n                                                Globals := gl;\n                                                FunTable := fs |}); eauto.\n      { i. hexploit UNIQUE_PARENT_MEM; eauto. }\n      hexploit getOperandValue_not_unique_parent.\n      { eauto. }\n      { eauto. }\n      { inv STATE. ss.\n        destruct B. destruct s.\n        hexploit typings_props.wf_fdef__wf_cmd; try apply WF_FDEF.\n        { apply WF_EC. }\n        {\n          instantiate (1:= insn_store id5 typ5 value1 value2 align5).\n          inv WF_EC. ss.\n          unfold OpsemAux.get_cmds_from_block in *. ss.\n          eapply sublist_In; eauto.\n          ss. left. eauto.\n        }\n        intro WF_INSN. inv WF_INSN. destruct TD. ss. clarify. eauto.\n      }\n      { instantiate (1 := gv1). eauto. }\n      ss. clarify.\n      unfold AssnMem.gv_diffblock_with_blocks. eauto.\n    + esplits; ss.\n      * des_ifs.\n      * econs; eauto.\n        inv STATE. ss.\n        { destruct B. destruct s.\n          hexploit typings_props.wf_fdef__wf_cmd; try apply WF_FDEF.\n          { apply WF_EC. }\n          {\n            instantiate (1:= insn_store id5 typ5 value1 value2 align5).\n            inv WF_EC. ss.\n            unfold OpsemAux.get_cmds_from_block in *. ss.\n            eapply sublist_In; eauto.\n            ss. left. eauto.\n          }\n          intro WF_INSN. inv WF_INSN. destruct TD. ss. clarify.\n          destruct value1; ss.\n          - eapply WF_LOCAL; eauto.\n          - inv H10.\n            exploit MemAux.wf_globals_const2GV; eauto.\n            i. inv MEM. ss.\n            inv WF0.\n            eapply MemProps.valid_ptrs__trans; eauto.\n            rewrite <- Pplus_one_succ_r.\n            apply Pos.le_succ_l. eauto.\n        }\nQed.\n\nLtac exploit_inject_value :=\n  repeat (match goal with\n       | [H1: Assertion.inject_value ?inv ?vt1 ?vt2 = true |- _] =>\n         exploit AssnState.Rel.inject_value_spec; try exact H1; eauto; clear H1\n       end;\n       (try by\n           match goal with\n           | [H: getOperandValue (CurTargetData ?conf) ?v (Locals (EC ?st)) (Globals ?conf) = Some ?gv1 |-\n              AssnState.Unary.sem_valueT ?conf ?st ?invst (ValueT.lift Tag.physical ?v) = Some ?gv2] =>\n             destruct v; [ss; unfold IdT.lift; solve_sem_idT; eauto | ss]\n           end); i; des).\n\nLtac inv_conf :=\n  match goal with\n  | [H: AssnState.valid_conf _ _ ?conf_src ?conf_tgt |- _] =>\n    let TD := fresh in\n    let GL := fresh in\n    destruct H as [[TD GL]]; rewrite TD in *; rewrite GL in *\n  end.\n\nLemma inject_mem_change\n      m_src conf_src cmd_src mc_src st0_src\n      m_tgt conf_tgt cmd_tgt mc_tgt st0_tgt\n      inv0 assnmem0 invst0\n      (CONF: AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (STATE : AssnState.Rel.sem conf_src conf_tgt st0_src st0_tgt invst0 assnmem0 inv0)\n      (MEM : AssnMem.Rel.sem conf_src conf_tgt st0_src.(Mem) st0_tgt.(Mem) assnmem0)\n      (INJECT_EVENT : postcond_cmd_inject_event cmd_src cmd_tgt inv0)\n      (MC_SRC : mem_change_of_cmd conf_src cmd_src st0_src.(EC).(Locals) = Some mc_src)\n      (MC_TGT : mem_change_of_cmd conf_tgt cmd_tgt st0_tgt.(EC).(Locals) = Some mc_tgt)\n  : mem_change_inject conf_src conf_tgt assnmem0 mc_src mc_tgt.\nProof.\n  destruct cmd_src; destruct cmd_tgt; ss; clarify;\n    (try by simtac; econs); (* cases including none *)\n    try by simtac;\n    unfold is_true in *;\n    repeat (des_bool; des);\n    inject_clarify;\n    exploit_inject_value;\n    inv_conf;\n    inject_clarify;\n    econs; eauto.\n  unfold Assertion.is_private in *. des_ifs.\n  destruct x as [t x]; unfold ValueT.lift in *. des_ifs.\n  inv STATE. inv SRC.\n  unfold is_true in *.\n  (* rewrite <- IdTSetFacts.mem_iff in *. *)\n\n  econs. ii.\n  exploit PRIVATE; eauto.\n  { eapply IdTSet.mem_2; eauto. }\n  { ss. }\n  ii; des.\n  inv PRIVATE_BLOCK.\n  splits; ss.\nQed.\n\nLtac solve_alloc_inject :=\n  by ii;\n  match goal with\n  | [ALLOCA: ?cmd = insn_alloca _ _ _ _,\n             MC_SOME: mem_change_of_cmd _ ?cmd _ = Some mem_change_none |- _] =>\n    rewrite ALLOCA in MC_SOME; ss; des_ifs\n  | [ALLOCA: ?cmd = insn_alloca _ _ _ _,\n             MC_SOME: mem_change_of_cmd _ ?cmd _ = Some (mem_change_store _ _ _ _) |- _] =>\n    rewrite ALLOCA in MC_SOME; ss; des_ifs\n  | [ALLOCA: ?cmd = insn_alloca _ _ _ _,\n             MC_SOME: mem_change_of_cmd _ ?cmd _ = Some (mem_change_free _) |- _] =>\n    rewrite ALLOCA in MC_SOME; ss; des_ifs\n  end.\n\nLemma inject_assnmem\n      m_src conf_src st0_src st1_src cmd_src cmds_src evt_src\n      m_tgt conf_tgt st0_tgt st1_tgt cmd_tgt cmds_tgt evt_tgt\n      invst0 assnmem0 inv0\n      (CONF: AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (STATE : AssnState.Rel.sem conf_src conf_tgt st0_src st0_tgt invst0 assnmem0 inv0)\n      (MEM : AssnMem.Rel.sem conf_src conf_tgt (Mem st0_src) (Mem st0_tgt) assnmem0)\n      (CMD_SRC : CurCmds (EC st0_src) = cmd_src :: cmds_src)\n      (CMD_TGT : CurCmds (EC st0_tgt) = cmd_tgt :: cmds_tgt)\n      (NONCALL_SRC: Instruction.isCallInst cmd_src = false)\n      (NONCALL_TGT: Instruction.isCallInst cmd_tgt = false)\n      (STEP_SRC : sInsn conf_src st0_src st1_src evt_src)\n      (STEP_TGT : sInsn conf_tgt st0_tgt st1_tgt evt_tgt)\n      (INJECT_EVENT : postcond_cmd_inject_event cmd_src cmd_tgt inv0)\n\n  : exists assnmem1,\n    <<ALLOC_INJECT: alloc_inject conf_src conf_tgt st0_src st0_tgt\n                                 st1_src st1_tgt cmd_src cmd_tgt assnmem1>> /\\\n    <<ALLOC_PRIVATE: alloc_private conf_src conf_tgt cmd_src cmd_tgt st0_src st0_tgt st1_src st1_tgt assnmem1>> /\\\n    <<MEM: AssnMem.Rel.sem conf_src conf_tgt (Mem st1_src) (Mem st1_tgt) assnmem1>> /\\\n    <<MEMLE: AssnMem.Rel.le assnmem0 assnmem1>> /\\\n    <<PRIVATE_PRESERVED_SRC: IdTSet.For_all\n                               (AssnState.Unary.sem_private\n                                  conf_src st0_src (AssnState.Rel.src invst0)\n                                  (AssnMem.Unary.private_parent (AssnMem.Rel.src assnmem1))\n                                  (AssnMem.Rel.public_src (AssnMem.Rel.inject assnmem1)))\n                               (Assertion.private (Assertion.src inv0))>> /\\\n    <<PRIVATE_PRESERVED_TGT: IdTSet.For_all\n                               (AssnState.Unary.sem_private\n                                  conf_tgt st0_tgt (AssnState.Rel.tgt invst0)\n                                  (AssnMem.Unary.private_parent (AssnMem.Rel.tgt assnmem1))\n                                  (AssnMem.Rel.public_tgt (AssnMem.Rel.inject assnmem1)))\n                               (Assertion.private (Assertion.tgt inv0))>> /\\\n    (* INJECT_ALLOCAS is needed for \"inv_state_sem_monotone_wrt_assnmem\" *)\n    (* I am not sure this design is good; as INJECT_ALLOCAS belongs to AssnState *)\n    (* INJECT_ALLOCAS is needed here. && also in SimLocal *)\n    (* If we put this inside AssnMem (may need to strengthen \"frozen\" until \"nextblock\" *)\n    (* This will not be the case *)\n    <<INJECT_ALLOCAS:\n      AssnState.Rel.inject_allocas (AssnMem.Rel.inject assnmem1)\n                                  st0_src.(EC).(Allocas) st0_tgt.(EC).(Allocas)>> /\\\n   <<INJECT_ALLOCAS:\n      AssnState.Rel.inject_allocas (AssnMem.Rel.inject assnmem1)\n                                  st1_src.(EC).(Allocas) st1_tgt.(EC).(Allocas)>> /\\\n    <<VALID_ALLOCAS_SRC: Forall (Mem.valid_block (Mem st1_src)) st1_src.(EC).(Allocas)>> /\\\n    <<VALID_ALLOCAS_TGT: Forall (Mem.valid_block (Mem st1_tgt)) st1_tgt.(EC).(Allocas)>>\n.\nProof.\n  exploit postcond_cmd_inject_event_non_malloc; eauto; []; ii; des.\n  hexploit step_mem_change; try (inv STATE; exact SRC); eauto.\n  { inv MEM. exact SRC. }\n  intro MCS.\n  destruct MCS as [UNIQUE_PRIVATE_SRC [mc_src [MC_SOME_SRC STATE_EQUIV_SRC]]]. des.\n  hexploit step_mem_change; try (inv STATE; exact TGT); eauto.\n  { inv MEM. exact TGT. }\n  intro MCS.\n  destruct MCS as [UNIQUE_PRIVATE_TGT [mc_tgt [MC_SOME_TGT STATE_EQUIV_TGT]]]. des.\n\n  exploit inject_mem_change; eauto. intro MC_INJECT.\n\n  inv MC_INJECT.\n  - (* alloc - alloc *)\n    inv STEP_SRC; inv CMD_SRC; ss; des_ifs.\n    rename Mem0 into mem0_src. rename Mem' into mem1_src. rename mb into mb_src.\n    match goal with\n    | [H: alloca _ _ _ _ _ = _ |- _] => rename H into ALLOCA_SRC\n    end.\n    inv STEP_TGT; inv CMD_TGT; ss; try by des; congruence.\n    rename Mem0 into mem0_tgt. rename Mem' into mem1_tgt. rename mb into mb_tgt.\n    match goal with\n    | [H: alloca _ _ _ _ _ = _ |- _] => rename H into ALLOCA_TGT\n    end.\n    clear_tac.\n    dup ALLOCA_SRC.\n    dup ALLOCA_TGT.\n    unfold alloca, option_map, flip in ALLOCA_SRC, ALLOCA_TGT. des_ifs_safe.\n    expl alloca_result (try exact ALLOCA_SRC0; eauto). clarify.\n    expl alloca_result (try exact ALLOCA_TGT0; eauto). clarify.\n    expl Mem.alloc_result (try exact Heq1; eauto). clarify.\n    expl Mem.alloc_result (try exact Heq3; eauto). clarify.\n    clear_tac.\n    eexists.\n    instantiate (1:= AssnMem.Rel.mk _ _ _\n                                   (fun b =>\n                                      if Values.eq_block b (Mem.nextblock mem0_src)\n                                      then Some ((Mem.nextblock mem0_tgt), 0%Z)\n                                      else assnmem0.(AssnMem.Rel.inject) b)).\n    esplits.\n    + (* alloc_inject *)\n      ii. ss.\n      inv ALLOCA_SRC. inv ALLOCA_TGT.\n      esplits.\n      * unfold alloc_inject_unary.\n        esplits; try apply lookupAL_updateAddAL_eq; ss.\n      * unfold alloc_inject_unary.\n        esplits; try apply lookupAL_updateAddAL_eq; ss.\n      * destruct (Values.eq_block (Mem.nextblock mem0_src)(Mem.nextblock mem0_src)); ss.\n    + (* alloc_private *)\n      econs; ii; ss; des_ifs.\n    + (* AssnMem sem *)\n      inv MEM; ss.\n      instantiate (3:= AssnMem.Unary.mk _\n                                       assnmem0.(AssnMem.Rel.src).(AssnMem.Unary.mem_parent)\n                                       assnmem0.(AssnMem.Rel.src).(AssnMem.Unary.unique_parent)\n                                       mem1_src.(Mem.nextblock)).\n      instantiate (2:= AssnMem.Unary.mk _\n                                       assnmem0.(AssnMem.Rel.tgt).(AssnMem.Unary.mem_parent)\n                                       assnmem0.(AssnMem.Rel.tgt).(AssnMem.Unary.unique_parent)\n                                       mem1_tgt.(Mem.nextblock)).\n\n      econs; ss; eauto.\n      { (* SRC *)\n        inv SRC.\n        econs; eauto.\n        - eapply MemProps.alloca_preserves_wf_Mem; eauto.\n        - ss. i. exploit PRIVATE_PARENT; eauto. intros [NOT_PUBLIC_B NEXT_B].\n          split.\n          + ii. unfold AssnMem.Rel.public_src in *.\n            destruct (Values.eq_block _ _); ss.\n            psimpl.\n          + erewrite Mem.nextblock_drop with (m:= m0); try eassumption.\n            erewrite Mem.nextblock_alloc; try eassumption.\n            eapply Pos.lt_le_trans; eauto.\n            eapply Ple_succ; eauto.\n        - i. exploit MEM_PARENT; eauto. i. ss.\n          match goal with\n          | [H: mload_aux (AssnMem.Unary.mem_parent _) _ b _ = _ |- _] =>\n            rewrite H\n          end.\n          exploit PRIVATE_PARENT; eauto. i.\n          unfold AssnMem.private_block in *. des.\n          eapply alloca_preserves_mload_aux_other_eq; eauto.\n        - ss. rewrite NEXT_BLOCK. etransitivity; [|apply Ple_succ]; eauto.\n      }\n      { (* TGT *)\n        inv TGT.\n        econs; eauto.\n        - eapply MemProps.alloca_preserves_wf_Mem; eauto.\n        - ss. i. exploit PRIVATE_PARENT; eauto.\n          intros [NOT_PUBLIC_B NEXT_B].\n          split.\n          + ii.\n            match goal with\n            | [H: ~ AssnMem.Rel.public_tgt _ _ |- False] =>\n              apply H\n            end.\n            unfold AssnMem.Rel.public_tgt in *. des.\n            destruct (Values.eq_block _ _).\n            * clarify. exfalso. psimpl.\n            * esplits; eauto.\n          + erewrite Mem.nextblock_drop with (m:= m); try eassumption.\n            erewrite Mem.nextblock_alloc; try eassumption.\n            eapply Pos.lt_le_trans; eauto.\n            eapply Ple_succ; eauto.\n        - i. exploit MEM_PARENT; eauto. i.\n          match goal with\n          | [H: mload_aux (AssnMem.Unary.mem_parent _) _ b _ = _ |- _] =>\n            rewrite H\n          end.\n          exploit PRIVATE_PARENT; eauto. i.\n          unfold AssnMem.private_block in *. des.\n          eapply alloca_preserves_mload_aux_other_eq; eauto.\n        - ss. rewrite NEXT_BLOCK0. etransitivity; [|apply Ple_succ]; eauto.\n      }\n      { (* inject *)\n        inv INJECT.\n        unfold is_true in *.\n        repeat rewrite andb_true_iff in INJECT_EVENT.\n        destruct INJECT_EVENT as [[[ID_EQ TYP_EQ] INJECT_VALUE] DEC_EQ].\n        unfold proj_sumbool in *. des_sumbool. clarify.\n        econs.\n        { (* mi_access *)\n          ii. exploit valid_access_alloca_inv; try exact ALLOCA_SRC0; eauto.\n          i.\n          destruct (Values.eq_block _ _).\n          - clarify.\n            assert(Memtype.perm_order Memtype.Writable p).\n            { move Heq6 at bottom.\n              destruct p; try econs.\n              eapply Mem.valid_access_perm in H0.\n              des.\n              hexploit Mem.perm_drop_2; try apply H0; eauto.\n              split; ss.\n              expl Memdata.size_chunk_pos. instantiate (1:= chunk) in size_chunk_pos.\n              apply Z.gt_lt_iff in size_chunk_pos.\n              eapply Z.lt_le_trans.\n              { instantiate (1:= ofs + Memdata.size_chunk chunk). omega. }\n              unfold get_or_else in *. des_ifs; omega.\n            }\n            eapply valid_access_alloca_same; eauto.\n            repeat rewrite Z.add_0_r.\n            des. splits; eauto.\n            exploit genericvalues_inject.simulation__GV2int; eauto. intro GV2INT_INJECT.\n            assert(TD = TD0).\n            { inv CONF. inv INJECT. ss. }\n            subst.\n            rewrite <- GV2INT_INJECT in *. clarify.\n          - exploit mi_access; eauto.\n            eapply valid_access_alloca_other; eauto.\n        }\n        { (* mi_memval *)\n          i. destruct (Values.eq_block _ _).\n          - clarify.\n            rewrite Z.add_0_r.\n            erewrite alloca_contents_same; eauto.\n            erewrite alloca_contents_same; eauto.\n            apply memory_sim.MoreMem.memval_inject_undef.\n          - eapply memory_sim.MoreMem.memval_inject_incr.\n            + assert (DIFF_BLK_TGT: b2 <> (Mem.nextblock mem0_tgt)).\n              { exploit genericvalues_inject.Hmap2; eauto. }\n              eapply alloca_contents_other in DIFF_BLK_TGT; eauto.\n              rewrite DIFF_BLK_TGT.\n              erewrite alloca_contents_other; eauto.\n              apply mi_memval; eauto.\n              eapply Mem.perm_drop_4 in H0; [|try exact Heq6].\n              exploit Mem.perm_alloc_inv.\n              { try exact Heq5. }\n              { eauto. }\n              i. des_ifs.\n            + ii.\n              destruct (Values.eq_block _ _).\n              { subst. exfalso.\n                exploit genericvalues_inject.Hmap1; eauto.\n                { instantiate (1:=Mem.nextblock mem0_src).\n                  exploit alloca_inv; try exact ALLOCA_SRC0. i. psimpl.\n                }\n                i. congruence.\n              }\n              eauto.\n        }\n      }\n      { (* wf_sb_mi *)\n        inv WF.\n        econs.\n        - (* no_overlap *)\n          ii.\n          destruct (Values.eq_block _ _);\n            destruct (Values.eq_block _ _); clarify.\n          + exploit Hmap2; eauto. i. psimpl.\n          + exploit Hmap2; eauto. i. psimpl.\n          + eapply Hno_overlap with (b1:=b1) (b2:=b2); eauto.\n        - (* Hmap1 *)\n          intro b_src. i. destruct (Values.eq_block _ _).\n          + subst.\n            rewrite NEXT_BLOCK in *.\n            exfalso. psimpl.\n          + apply Hmap1. psimpl.\n        - (* Hmap2 *)\n          intros b_src b_tgt. i. destruct (Values.eq_block _ _).\n          + clarify.\n            subst. rewrite NEXT_BLOCK0 in *.\n            apply Plt_succ'.\n          + exploit Hmap2; eauto. i. psimpl.\n        - (* mi_freeblocks *)\n          intros b NOT_VALID_BLOCK.\n          destruct (Values.eq_block _ _).\n          + subst.\n            exfalso.\n            apply NOT_VALID_BLOCK.\n            unfold Mem.valid_block.\n            psimpl.\n          + apply mi_freeblocks. intros VALID_BLOCK.\n            apply NOT_VALID_BLOCK.\n            unfold Mem.valid_block in *.\n            psimpl.\n        - (* mi_mappedblocks *)\n          i. destruct (Values.eq_block _ _).\n          + clarify.\n            unfold Mem.valid_block in *.\n            psimpl.\n          + eapply Mem.drop_perm_valid_block_1; eauto.\n            eapply Mem.valid_block_alloc.\n            { eauto. }\n            eapply mi_mappedblocks; eauto.\n        - (* mi_range_blocks *)\n          ii. destruct (Values.eq_block _ _).\n          + subst. clarify.\n          + eapply mi_range_block; eauto.\n        - (* mi_bounds *)\n          ii. destruct (Values.eq_block _ _).\n          + clarify.\n            erewrite Mem.bounds_drop; eauto.\n            erewrite Mem.bounds_alloc_same; cycle 1.\n            { eauto. }\n            erewrite Mem.bounds_drop; eauto.\n            erewrite Mem.bounds_alloc_same; cycle 1.\n            { eauto. }\n            apply injective_projections; ss.\n            solve_match_bool. clarify.\n            exploit genericvalues_inject.simulation__GV2int; eauto. intro GV2INT_INJECT.\n            assert(TD = TD0).\n            { inv CONF. inv INJECT0. ss. }\n            subst.\n            rewrite GV2INT_INJECT in *. clarify.\n          + erewrite Mem.bounds_drop; eauto.\n            erewrite Mem.bounds_alloc_other with (b':=b); eauto; cycle 1.\n            assert (NEQ_BLK_TGT: b' <> mem0_tgt.(Mem.nextblock)).\n            { exploit Hmap2; eauto. }\n            symmetry. (* TODO: \"rewrite at\" doesn't work, WHY???????? *)\n            erewrite Mem.bounds_drop; eauto.\n            erewrite Mem.bounds_alloc_other with (b':=b'); try exact NEQ_BLK_TGT; cycle 1.\n            { eauto. }\n            symmetry. eapply mi_bounds; eauto.\n        - (* mi_globals *)\n          i. destruct (Values.eq_block _ _).\n          + subst.\n            exploit mi_globals; eauto. i.\n            exploit Hmap1.\n            { psimpl. }\n            i. congruence.\n          + exploit mi_globals; eauto.\n      }\n      { (* ftable *)\n        eapply inject_incr__preserves__ftable_simulation; eauto.\n        ii. rename H into INJ0.\n        des_ifs_safe.\n        inv WF.\n        exploit Hmap1.\n        { ii. rewrite Pos.compare_refl in *. clarify. }\n        intro INJ1.\n        rewrite INJ1 in *. clarify.\n      }\n    + (* le *)\n      econs; try (econs; ss).\n      { inv MEM. inv SRC. rewrite <- NEXTBLOCK. psimpl. }\n      { inv MEM. inv TGT. rewrite <- NEXTBLOCK. psimpl. }\n      {\n        (* incr *)\n        ii. ss.\n        destruct (Values.eq_block _ _); eauto.\n        subst.\n        inv MEM. inv WF.\n        exploit Hmap1.\n        { psimpl. }\n        i. congruence.\n      }\n      {\n        ii. des. des_ifsH NEW0.\n        unfold Mem.valid_block.\n        split; ss.\n        - apply MEM.\n        - apply MEM.\n      }\n    + ss.\n      inv STATE. inv SRC. ss.\n      ii. exploit PRIVATE; eauto. i. des.\n      esplits; eauto. ss.\n      unfold AssnMem.private_block in *. des.\n      split.\n      * unfold AssnMem.Rel.public_src in *.\n        destruct (Values.eq_block _ _); ss.\n        psimpl.\n      * eauto.\n    + ss.\n      inv STATE. inv TGT. ss.\n      ii. exploit PRIVATE; eauto. i. des.\n      esplits; eauto. ss.\n      unfold AssnMem.private_block in *. des.\n      split.\n      * unfold AssnMem.Rel.public_tgt in *.\n        ii. des.\n        destruct (Values.eq_block _ _); ss.\n        { clarify. psimpl. }\n        apply PRIVATE_BLOCK. esplits; eauto.\n      * eauto.\n    + ss.\n      inv STATE. clear MAYDIFF.\n      inv SRC. clear LESSDEF NOALIAS UNIQUE PRIVATE ALLOCAS_PARENT\n                     WF_LOCAL WF_PREVIOUS WF_GHOST UNIQUE_PARENT_LOCAL WF_FDEF WF_EC.\n      inv TGT. clear LESSDEF NOALIAS UNIQUE PRIVATE ALLOCAS_PARENT\n                     WF_LOCAL WF_PREVIOUS WF_GHOST UNIQUE_PARENT_LOCAL WF_FDEF WF_EC.\n      ss.\n      eapply inject_allocas_enhance; eauto.\n      { i. des_ifsG. exfalso. eapply Plt_irrefl. eauto. }\n      { i. des_ifsG. exfalso. eapply Plt_irrefl. eauto. }\n      (* ginduction ALLOCAS; ii; ss. *)\n      (* * econs; eauto. *)\n      (* * inv ALLOCAS_VALID. *)\n      (*   econs; eauto. des_ifs. *)\n      (*   exfalso. eapply Plt_irrefl. eauto. *)\n      (* * inv ALLOCAS_VALID0. *)\n      (*   econs; eauto. *)\n      (*   i. des_ifs. *)\n      (*   { ii. clarify. eapply Plt_irrefl. eauto. } *)\n      (*   eapply PRIVATE. *)\n      (* * inv ALLOCAS_VALID. inv ALLOCAS_VALID0. *)\n      (*   econs 4; eauto. *)\n      (*   des_ifs. *)\n      (*   exfalso. eapply Plt_irrefl. eauto. *)\n    + ss.\n      inv STATE. clear MAYDIFF.\n      inv SRC. clear LESSDEF NOALIAS UNIQUE PRIVATE ALLOCAS_PARENT\n                     WF_LOCAL WF_PREVIOUS WF_GHOST UNIQUE_PARENT_LOCAL WF_FDEF WF_EC.\n      inv TGT. clear LESSDEF NOALIAS UNIQUE PRIVATE ALLOCAS_PARENT\n                     WF_LOCAL WF_PREVIOUS WF_GHOST UNIQUE_PARENT_LOCAL WF_FDEF WF_EC.\n      ss.\n      econs 4; eauto.\n      * des_ifsG.\n      * eapply inject_allocas_enhance; eauto.\n        { i. des_ifsG. exfalso. eapply Pos.lt_irrefl. eauto. }\n        { i. des_ifsG. exfalso. eapply Pos.lt_irrefl. eauto. }\n    + inv STATE. inv SRC.\n      clear - NEXT_BLOCK ALLOCAS_VALID.\n      ss.\n      econs; eauto.\n      * unfold Mem.valid_block. rewrite NEXT_BLOCK. eapply Plt_succ.\n      * eapply Forall_harder; eauto.\n        i.\n        unfold Mem.valid_block. rewrite NEXT_BLOCK.\n        eapply Pos.lt_le_trans; eauto. eapply Ple_succ.\n    + inv STATE. inv TGT.\n      clear - NEXT_BLOCK0 ALLOCAS_VALID.\n      ss.\n      econs; eauto.\n      * unfold Mem.valid_block. rewrite NEXT_BLOCK0. eapply Plt_succ.\n      * eapply Forall_harder; eauto.\n        i.\n        unfold Mem.valid_block. rewrite NEXT_BLOCK0.\n        eapply Pos.lt_le_trans; eauto. eapply Ple_succ.\n  - (* alloc - none *)\n    inv STATE_EQUIV_TGT. rewrite <- MEM_EQ in *.\n\n    inv STEP_SRC; destruct cmd_src; ss; clarify;\n      des_matchH MC_SOME_SRC; clarify; ss.\n    rename Mem0 into mem0_src.\n    rename Mem' into mem1_src.\n    inv STATE_EQUIV_SRC. ss. clarify.\n    exploit alloca_result; eauto. intros [ALLOCA_BLOCK_SRC ALLOCA_NEXT_SRC]. des.\n\n    exists (AssnMem.Rel.mk\n         (AssnMem.Unary.mk\n            assnmem0.(AssnMem.Rel.src).(AssnMem.Unary.private_parent)\n            assnmem0.(AssnMem.Rel.src).(AssnMem.Unary.mem_parent)\n            assnmem0.(AssnMem.Rel.src).(AssnMem.Unary.unique_parent)\n            mem1_src.(Mem.nextblock))\n         assnmem0.(AssnMem.Rel.tgt)\n         assnmem0.(AssnMem.Rel.gmax)\n         (* mem0_src should be private. *)\n         (* we can just copy assnmem0's, because wf_sb_mi guarantees mem0_src is priviate *)\n         (* Without wf_sb_mi, we need to put a function with if-then-else *)\n         assnmem0.(AssnMem.Rel.inject)\n           ).\n    esplits; ss; eauto.\n    + (* alloc_inject *)\n      solve_alloc_inject.\n    + (* alloc_private *)\n      econs; ii; ss; try by des_ifs.\n      clarify.\n      inv MEM. inv SRC. ss.\n      esplits.\n      * apply lookupAL_updateAddAL_eq.\n      * ii. ss. des; ss.\n        move b at bottom.\n        rename b into __b__.\n        clarify.\n        unfold AssnMem.private_block in *.\n        splits; ss.\n        {\n          ii.\n          unfold AssnMem.Rel.public_src in H.\n          apply H.\n          (* destruct assnmem0. ss. *)\n          inv WF.\n          apply Hmap1. psimpl.\n        }\n        { psimpl. }\n        { ii.\n          exploit PRIVATE_PARENT; eauto; []; ii; des.\n          psimpl.\n        }\n    + inv MEM.\n      econs; eauto.\n      * ss. eapply assnmem_unary_alloca_sem; eauto.\n        ii. unfold AssnMem.Rel.public_src in *.\n        apply H.\n        inv WF.\n        apply Hmap1. psimpl.\n      * inv INJECT.\n        econs.\n        { (* mi-access *)\n          i. exploit mi_access; eauto.\n          assert (DIFFBLOCK_ALLOC: b1 <> Mem.nextblock mem0_src).\n          { inv WF.\n            ii. exploit Hmap1.\n            { instantiate (1:= Mem.nextblock mem0_src).\n              psimpl. }\n            i. subst. ss. congruence.\n          }\n          exploit valid_access_alloca_inv; eauto.\n          des_ifs.\n        }\n        { (* mi_memval *)\n          i.\n          assert (DIFFBLOCK_ALLOC: b1 <> Mem.nextblock mem0_src).\n          { inv WF.\n            ii. exploit Hmap1.\n            { instantiate (1:= Mem.nextblock mem0_src).\n              psimpl. }\n            i. subst. ss. congruence.\n          }\n          exploit mi_memval; eauto.\n          { u_alloca.\n            eapply Mem.perm_drop_4 in H0; revgoals; eauto.\n            hexploit Mem.perm_alloc_inv; eauto; []; i.\n            clear INJECT_EVENT.\n            des_ifs. eauto.\n          }\n          i. exploit alloca_contents_other; eauto.\n          intro CONTENTS.\n          rewrite CONTENTS. eauto.\n        }\n      * inv WF.\n        econs; eauto.\n        ++ i. apply Hmap1. psimpl.\n        ++ i. apply Hmap1.\n           unfold Mem.valid_block in *. psimpl.\n        ++ i.\n           assert (ALLOC_PRIVATE: b <> Mem.nextblock mem0_src).\n           { ii. subst.\n             exploit Hmap1.\n             { psimpl. }\n             i. ss. congruence. }\n           u_alloca.\n           erewrite Mem.bounds_drop; revgoals; eauto.\n           erewrite Mem.bounds_alloc_other; try exact ALLOC_PRIVATE; cycle 1.\n           { eauto. }\n           eapply mi_bounds; eauto.\n    + econs; eauto.\n      * econs; eauto. ss.\n        inv MEM. inv SRC.\n        rewrite <- NEXTBLOCK.\n        psimpl.\n      * econs; eauto. ss.\n        inv MEM. inv TGT.\n        rewrite <- NEXTBLOCK.\n        psimpl.\n      * clarify. ss.\n        econs; eauto.\n        ii. des; ss. clarify.\n    + inv STATE. inv SRC. eauto.\n    + inv STATE. inv TGT. eauto.\n    + inv STATE. ss.\n    + inv STATE. ss.\n      assert(EQ_ALLOC: Allocas (EC st1_tgt) = Allocas (EC st0_tgt)).\n      { inv STEP_TGT; ss; des_ifs.\n        - inv MC_SOME_TGT. des_ifs. }\n      des. rewrite EQ_ALLOC.\n      econs; eauto.\n      inv MEM.\n      inv WF.\n      apply Hmap1. psimpl.\n    + inv STATE. inv SRC. ss.\n      clear - ALLOCAS_VALID NEXT_BLOCK.\n      econs; eauto.\n      * unfold Mem.valid_block. rewrite NEXT_BLOCK. eapply Plt_succ.\n      * eapply Forall_harder; eauto.\n        i.\n        unfold Mem.valid_block. rewrite NEXT_BLOCK.\n        eapply Pos.lt_le_trans; eauto.\n        eapply Ple_succ.\n    + assert(EQ_ALLOC: Allocas (EC st1_tgt) = Allocas (EC st0_tgt) /\\ ECS st1_tgt = ECS st0_tgt).\n      { inv STEP_TGT; ss; des_ifs.\n        - inv MC_SOME_TGT. des_ifs. } des.\n      inv STATE. inv TGT. ss.\n      rewrite EQ_ALLOC. ss.\n  - (* none - alloc *)\n    inv STATE_EQUIV_SRC.\n    rewrite <- MEM_EQ in *.\n\n    inv STEP_TGT; destruct cmd_tgt; ss; clarify;\n      des_matchH MC_SOME_TGT; clarify; ss.\n    rename Mem0 into mem0_tgt.\n    rename Mem' into mem1_tgt.\n    inv STATE_EQUIV_TGT. ss. clarify.\n    exploit alloca_result; eauto. intros [ALLOCA_BLOCK_TGT ALLOCA_NEXT_TGT]. des.\n\n    exists (AssnMem.Rel.mk\n         assnmem0.(AssnMem.Rel.src)\n         (AssnMem.Unary.mk\n            assnmem0.(AssnMem.Rel.tgt).(AssnMem.Unary.private_parent)\n            assnmem0.(AssnMem.Rel.tgt).(AssnMem.Unary.mem_parent)\n            assnmem0.(AssnMem.Rel.tgt).(AssnMem.Unary.unique_parent)\n            mem1_tgt.(Mem.nextblock))\n         assnmem0.(AssnMem.Rel.gmax)\n                   assnmem0.(AssnMem.Rel.inject)).\n    esplits; ss; eauto.\n    + (* alloc_inject *)\n      solve_alloc_inject.\n    + (* alloc_private *)\n      econs; ii; ss; try by des_ifs.\n      clarify.\n      inv MEM. inv TGT. ss.\n      esplits; try apply lookupAL_updateAddAL_eq.\n      * ii. ss.\n        des; ss.\n        unfold AssnMem.private_block.\n        splits.\n        {\n          ii.\n          subst.\n          unfold AssnMem.Rel.public_tgt in H.\n          des.\n          inv WF.\n          exploit Hmap2; eauto; []; ii; des.\n          psimpl.\n        }\n        { psimpl. }\n        { ii.\n          subst.\n          exploit PRIVATE_PARENT; eauto; []; ii; des.\n          unfold AssnMem.private_block in *.\n          des.\n          psimpl.\n        }\n    + inv MEM.\n      econs; eauto.\n      * eapply assnmem_unary_alloca_sem; eauto.\n        ss. ii. unfold AssnMem.Rel.public_tgt in *. des.\n        inv WF.\n        exploit Hmap2; eauto. i.\n        psimpl.\n      * inv INJECT.\n        econs.\n        { (* mi-access *)\n          i. exploit mi_access; eauto. i.\n          assert (DIFFBLOCK_ALLOC: b2 <> Mem.nextblock mem0_tgt).\n          { inv WF.\n            ii. exploit Hmap2; eauto.\n            i. psimpl. }\n          exploit valid_access_alloca_other; eauto.\n        }\n        { (* mi_memval *)\n          i.\n          assert (DIFFBLOCK_ALLOC: b2 <> Mem.nextblock mem0_tgt).\n          { inv WF.\n            ii. exploit Hmap2; eauto.\n            i. psimpl. }\n          exploit mi_memval; eauto.\n          i. exploit alloca_contents_other; eauto.\n          intro CONTENTS.\n          rewrite CONTENTS. eauto.\n        }\n      * inv WF.\n        econs; eauto.\n        ++ i. exploit Hmap2; eauto. i. psimpl.\n        ++ i. exploit Hmap2; eauto. i.\n           unfold Mem.valid_block. psimpl.\n        ++ i.\n           assert (ALLOC_PRIVATE: b' <> Mem.nextblock mem0_tgt).\n           { ii. subst.\n             exploit Hmap2; eauto. i. psimpl. }\n           u_alloca.\n           symmetry. (* TODO: WHY???????? \"rewrite at\" dosen't work ???????????????? *)\n           erewrite Mem.bounds_drop; revgoals; eauto.\n           erewrite Mem.bounds_alloc_other with (b':=b'); try exact ALLOC_PRIVATE; cycle 1.\n           { eauto. }\n           symmetry.\n           eapply mi_bounds; eauto.\n    + econs; eauto.\n      * econs; eauto. ss.\n        inv MEM. inv SRC. rewrite <- NEXTBLOCK. psimpl.\n      * econs; eauto. ss.\n        inv MEM. inv TGT. rewrite <- NEXTBLOCK. psimpl.\n      * ss. econs; eauto.\n        ii.\n        des; ss. clarify.\n    + inv STATE. inv SRC. eauto.\n    + inv STATE. inv TGT. eauto.\n    + inv STATE. ss.\n    + inv STATE. ss.\n      assert(EQ_ALLOC: Allocas (EC st1_src) = Allocas (EC st0_src)).\n      { inv STEP_SRC; ss; des_ifs.\n        - inv MC_SOME_SRC. des_ifs. }\n      des. rewrite EQ_ALLOC.\n      econs; eauto.\n      inv MEM.\n      inv WF.\n      ii.\n      expl Hmap2. psimpl.\n    + assert(EQ_ALLOC: Allocas (EC st1_src) = Allocas (EC st0_src) /\\ ECS st1_src = ECS st0_src).\n      { inv STEP_SRC; ss; des_ifs.\n        - inv MC_SOME_SRC. des_ifs. } des.\n      inv STATE. inv SRC. ss.\n      rewrite EQ_ALLOC. ss.\n    + inv STATE. inv TGT. ss.\n      clear - ALLOCAS_VALID NEXT_BLOCK.\n      econs; eauto.\n      * unfold Mem.valid_block. rewrite NEXT_BLOCK. eapply Plt_succ.\n      * eapply Forall_harder; eauto.\n        i.\n        unfold Mem.valid_block. rewrite NEXT_BLOCK.\n        eapply Pos.lt_le_trans; eauto.\n        eapply Ple_succ.\n  - (* store - store *)\n    rename ptr0 into ptr_src. rename gv0 into gv_src.\n    rename ptr1 into ptr_tgt. rename gv1 into gv_tgt.\n    inv MEM. rename SRC into MSRC. rename TGT into MTGT.\n    inv STATE_EQUIV_SRC. rename STORE into STORE_SRC.\n    unfold mstore in STORE_SRC.\n    des_ifs.\n\n    rename b into sb_src. rename i0 into sofs_src. rename Heq into GV2PTR_SRC.\n    rename l0 into chunkl_src. rename Heq0 into FLATTEN_SRC.\n    inv STATE_EQUIV_TGT. rename STORE into STORE_TGT.\n    unfold mstore in STORE_TGT.\n    des_ifs.\n    rename b into sb_tgt. rename i0 into sofs_tgt. rename Heq into GV2PTR_TGT.\n    rename l0 into chunkl_tgt. rename Heq0 into FLATTEN_TGT.\n    assert(SPTR_INJECT: AssnMem.Rel.inject assnmem0 sb_src = Some (sb_tgt, 0) /\\ sofs_src = sofs_tgt).\n    { inv PTR_INJECT; ss.\n      des_ifs.\n      match goal with\n      | [H: memory_sim.MoreMem.val_inject _ (Values.Vptr _ _) (Values.Vptr _ _) |- _] =>\n        inv H\n      end.\n      inv WF.\n      exploit mi_range_block; eauto. i. subst.\n      esplits; eauto.\n      rewrite Integers.Int.add_zero. reflexivity.\n    }\n    des. subst.\n    assert(CHUNKL_EQ: chunkl_tgt = chunkl_src).\n    { destruct CONF as [[CONF_TD _]].\n      rewrite CONF_TD in *.\n      congruence. }\n    rewrite CHUNKL_EQ in *. clear CHUNKL_EQ.\n\n    exploit genericvalues_inject.mem_inj_mstore_aux; eauto. i. des.\n    rewrite Z.add_0_r in *.\n    assert (MEM_EQ: Mem2' = Mem st1_tgt).\n    { congruence. }\n    subst.\n\n    esplits; eauto; try reflexivity; try solve_alloc_inject.\n    { unfold alloc_private, alloc_private_unary. split.\n      - i. subst. ss. des_matchH MC_SOME_SRC; clarify.\n      - i. subst. ss. des_matchH MC_SOME_TGT; clarify.\n    }\n    + {\n        econs; eauto.\n        + inv MSRC.\n          econs; eauto.\n          * eapply mstore_aux_valid_ptrs_preserves_wf_Mem; eauto.\n          * (* PRIVATE_PARENT *)\n            i. exploit PRIVATE_PARENT; eauto. i. des.\n            unfold AssnMem.private_block in *. des.\n            split; eauto.\n            erewrite <- MemProps.nextblock_mstore_aux; eauto.\n          * i. hexploit gv_inject_ptr_public_src; try exact PTR_INJECT; eauto. i.\n            exploit MEM_PARENT; eauto. intro MLOAD_EQ. rewrite MLOAD_EQ.\n            (* b <> sb_src *)\n            eapply mstore_aux_preserves_mload_aux_eq; eauto.\n            ii. subst.\n            exploit PRIVATE_PARENT; eauto. i.\n            unfold AssnMem.private_block in *. des. eauto.\n          * rewrite <- NEXTBLOCK. symmetry.\n            eapply MemProps.nextblock_mstore_aux; eauto.\n          * rpapply NEXTBLOCK_PARENT.\n            symmetry. eapply MemProps.nextblock_mstore_aux; eauto.\n        + inv MTGT.\n          econs; eauto.\n          * eapply mstore_aux_valid_ptrs_preserves_wf_Mem; eauto.\n          * (* PRIVATE_PARENT *)\n            i. exploit PRIVATE_PARENT; eauto. i.\n            unfold AssnMem.private_block in *. des.\n            split; eauto.\n            erewrite <- MemProps.nextblock_mstore_aux; eauto.\n          * i. hexploit gv_inject_ptr_public_tgt; try exact PTR_INJECT; eauto.\n            { compute in GV2PTR_SRC. des_ifs. }\n            i.\n            exploit MEM_PARENT; eauto. intro MLOAD_EQ. rewrite MLOAD_EQ.\n            eapply mstore_aux_preserves_mload_aux_eq; eauto.\n            ii. subst.\n            exploit PRIVATE_PARENT; eauto. i.\n            unfold AssnMem.private_block in *. des. eauto.\n          * rewrite <- NEXTBLOCK. symmetry.\n            eapply MemProps.nextblock_mstore_aux; eauto.\n          * rpapply NEXTBLOCK_PARENT.\n            symmetry. eapply MemProps.nextblock_mstore_aux; eauto.\n      }\n    + inv STATE. inv SRC. eauto.\n    + inv STATE. inv TGT. eauto.\n    + inv STATE. ss.\n    + assert(EQ_ALLOC_SRC: Allocas (EC st1_src) = Allocas (EC st0_src)).\n      { inv STEP_SRC; ss; des_ifs.\n        - inv MC_SOME_SRC. des_ifs. } des.\n      rewrite EQ_ALLOC_SRC.\n      assert(EQ_ALLOC_TGT: Allocas (EC st1_tgt) = Allocas (EC st0_tgt)).\n      { inv STEP_TGT; ss; des_ifs.\n        - inv MC_SOME_TGT. des_ifs. } des.\n      rewrite EQ_ALLOC_TGT.\n      apply STATE.\n    + assert(EQ_ALLOC_SRC: Allocas (EC st1_src) = Allocas (EC st0_src)).\n      { inv STEP_SRC; ss; des_ifs.\n        - inv MC_SOME_SRC. des_ifs. } des.\n      rewrite EQ_ALLOC_SRC.\n      unfold Mem.valid_block.\n      expl MemProps.nextblock_mstore_aux (try exact STORE_SRC).\n      rewrite <- nextblock_mstore_aux.\n      apply STATE.\n    + assert(EQ_ALLOC_TGT: Allocas (EC st1_tgt) = Allocas (EC st0_tgt)).\n      { inv STEP_TGT; ss; des_ifs.\n        - inv MC_SOME_TGT. des_ifs. } des.\n      rewrite EQ_ALLOC_TGT.\n      unfold Mem.valid_block.\n      expl MemProps.nextblock_mstore_aux (try exact STORE_TGT).\n      rewrite <- nextblock_mstore_aux.\n      apply STATE.\n  - (* store - none *)\n    inv MEM. rename SRC into MSRC. rename TGT into MTGT.\n    inv STATE_EQUIV_TGT. rewrite <- MEM_EQ.\n    inv STATE_EQUIV_SRC.\n    unfold mstore in STORE.\n    des_ifs.\n    rename Heq into GV2PTR. rename l0 into chunkl. rename Heq0 into FLATTEN.\n    esplits; eauto; try reflexivity; try solve_alloc_inject.\n    { unfold alloc_private, alloc_private_unary. split.\n      - i. subst. ss. des_matchH MC_SOME_SRC; clarify.\n      - i. subst. ss. des_matchH MC_SOME_TGT; clarify.\n    }\n    +\n      {\n        econs; eauto.\n        + inv MSRC.\n          econs; eauto.\n          * eapply mstore_aux_valid_ptrs_preserves_wf_Mem; eauto.\n          * (* PRIVATE_PARENT *)\n            i. exploit PRIVATE_PARENT; eauto. i.\n            unfold AssnMem.private_block in *. des.\n            split; eauto.\n            erewrite <- MemProps.nextblock_mstore_aux; eauto.\n          * i. exploit MEM_PARENT; eauto. intro MLOAD_EQ. rewrite MLOAD_EQ.\n            eapply mstore_aux_preserves_mload_aux_eq; eauto.\n            ii. subst.\n            move DISJOINT at bottom.\n            exploit DISJOINT; eauto.\n            { eapply GV2ptr_In_GV2blocks; eauto. }\n            ii; des.\n            eauto.\n          * erewrite <- MemProps.nextblock_mstore_aux; eauto.\n          * rpapply NEXTBLOCK_PARENT.\n            symmetry. eapply MemProps.nextblock_mstore_aux; eauto.\n        + (* inject *)\n          inv INJECT.\n          econs.\n          { (* mi_access *)\n            i. exploit mi_access; eauto.\n            erewrite mstore_aux_valid_access; eauto. }\n          { (* mi_memval *)\n            i. exploit mi_memval; eauto.\n            { eapply mstore_aux_preserves_perm; eauto. }\n            i.\n            assert(STORE_DIFFBLOCK: b1 <> b).\n            { ii. subst.\n              move DISJOINT at bottom.\n              exploit DISJOINT; eauto.\n              { eapply GV2ptr_In_GV2blocks; eauto. }\n              ii; des.\n              apply NOT_PUBLIC. ii. clarify. }\n            assert (GET_ONE: Mem.getN 1 ofs (Maps.PMap.get b1 (Mem.mem_contents (Mem st0_src))) =\n                             Mem.getN 1 ofs (Maps.PMap.get b1 (Mem.mem_contents (Mem st1_src)))).\n            { eapply mstore_aux_getN_out; eauto. }\n            ss. inv GET_ONE.\n            eauto.\n          }\n        + (* WF *)\n          inv WF.\n          econs; eauto.\n          * erewrite <- MemProps.nextblock_mstore_aux; eauto.\n          * i. exploit mi_freeblocks; eauto.\n            unfold Mem.valid_block in *.\n            erewrite MemProps.nextblock_mstore_aux; eauto.\n          * i. exploit mi_bounds; eauto. i.\n            hexploit MemProps.bounds_mstore_aux; try exact STORE.\n            intro BEQ_SRC. rewrite <- BEQ_SRC.\n            eauto.\n      }\n    + inv STATE. inv SRC. eauto.\n    + inv STATE. inv TGT. eauto.\n    + inv STATE. ss.\n    + assert(EQ_ALLOC_SRC: Allocas (EC st1_src) = Allocas (EC st0_src)).\n      { inv STEP_SRC; ss; des_ifs.\n        - inv MC_SOME_SRC. des_ifs. } des.\n      rewrite EQ_ALLOC_SRC.\n      assert(EQ_ALLOC_TGT: Allocas (EC st1_tgt) = Allocas (EC st0_tgt)).\n      { inv STEP_TGT; ss; des_ifs.\n        - inv MC_SOME_TGT. des_ifs. } des.\n      rewrite EQ_ALLOC_TGT.\n      apply STATE.\n    + assert(EQ_ALLOC_SRC: Allocas (EC st1_src) = Allocas (EC st0_src)).\n      { inv STEP_SRC; ss; des_ifs.\n        - inv MC_SOME_SRC. des_ifs. } des.\n      rewrite EQ_ALLOC_SRC.\n      unfold Mem.valid_block.\n      expl MemProps.nextblock_mstore_aux (try exact STORE).\n      rewrite <- nextblock_mstore_aux.\n      apply STATE.\n    + assert(EQ_ALLOC_TGT: Allocas (EC st1_tgt) = Allocas (EC st0_tgt)).\n      { inv STEP_TGT; ss; des_ifs.\n        - inv MC_SOME_TGT. des_ifs. } des.\n      rewrite EQ_ALLOC_TGT.\n      apply STATE.\n  - (* free - free *)\n    rename ptr0 into ptr_src. rename ptr1 into ptr_tgt.\n    inv MEM. rename SRC into MSRC. rename TGT into MTGT.\n    inv STATE_EQUIV_SRC. rename FREE into FREE_SRC.\n    inv STATE_EQUIV_TGT. rename FREE into FREE_TGT.\n    specialize (MemProps.free_preserves_wf_Mem (AssnMem.Rel.gmax assnmem0) _ _ _ _ FREE_SRC). intro WF_SRC.\n    specialize (MemProps.free_preserves_wf_Mem (AssnMem.Rel.gmax assnmem0) _ _ _ _ FREE_TGT). intro WF_TGT.\n\n    unfold free in FREE_SRC. des_ifs.\n    rename b into fb_src. rename z into lo_src. rename z0 into hi_src.\n    rename Heq into GV2PTR_SRC. rename Heq0 into BOUNDS_SRC.\n    unfold free in FREE_TGT. des_ifs.\n    rename b into fb_tgt. rename z into lo_tgt. rename z0 into hi_tgt.\n    rename Heq into GV2PTR_TGT. rename Heq0 into BOUNDS_TGT.\n\n    assert(FPTR_INJECT: AssnMem.Rel.inject assnmem0 fb_src = Some (fb_tgt, 0) /\\\n                                       lo_src = lo_tgt /\\ hi_src = hi_tgt).\n    { inv PTR_INJECT; ss.\n      des_ifs.\n      match goal with\n      | [H: memory_sim.MoreMem.val_inject _ (Values.Vptr _ _) (Values.Vptr _ _) |- _] =>\n        inv H\n      end.\n      inv WF.\n      exploit mi_bounds; eauto. intros BOUNDS.\n      rewrite BOUNDS_SRC in BOUNDS.\n      rewrite BOUNDS_TGT in BOUNDS.\n      inv BOUNDS. esplits; eauto.\n      exploit mi_range_block; eauto.\n      i. subst. eauto.\n    }\n    des. subst.\n    exploit genericvalues_inject.mem_inj__free; eauto. i. des.\n    assert (MEM_EQ: Mem2' = (Mem st1_tgt)).\n    { do 2 rewrite Z.add_0_r in *. congruence. }\n    subst.\n\n    esplits; eauto; try reflexivity; try solve_alloc_inject.\n    { unfold alloc_private, alloc_private_unary. split.\n      - i. subst. ss. des_matchH MC_SOME_SRC; clarify.\n      - i. subst. ss. des_matchH MC_SOME_TGT; clarify.\n    }\n    +\n      {\n        econs; eauto.\n        + inv MSRC.\n          econs; eauto.\n          * (* PRIVATE_PARENT *)\n            i. exploit PRIVATE_PARENT; eauto. i.\n            unfold AssnMem.private_block in *. des.\n            split; eauto.\n            erewrite Mem.nextblock_free; eauto.\n          * i. hexploit gv_inject_ptr_public_src; try exact PTR_INJECT; eauto. i.\n            exploit MEM_PARENT; eauto. intro MLOAD_EQ. rewrite MLOAD_EQ.\n            exploit free_preserves_mload_aux_eq; try exact FREE_SRC; eauto.\n            exploit PRIVATE_PARENT; eauto. i.\n            unfold AssnMem.private_block in *. des.\n            ii. subst. eauto.\n          * erewrite Mem.nextblock_free; eauto.\n          * rpapply NEXTBLOCK_PARENT.\n            eapply Mem.nextblock_free; eauto.\n        + inv MTGT.\n          econs; eauto.\n          * (* PRIVATE_PARENT *)\n            i. exploit PRIVATE_PARENT; eauto. i.\n            unfold AssnMem.private_block in *. des.\n            split; eauto.\n            erewrite Mem.nextblock_free; eauto.\n          * i. hexploit gv_inject_ptr_public_tgt; try exact PTR_INJECT; eauto.\n            { compute in GV2PTR_SRC. des_ifs. }\n            i.\n            exploit MEM_PARENT; eauto. intro MLOAD_EQ. rewrite MLOAD_EQ.\n            exploit free_preserves_mload_aux_eq; try exact FREE_TGT; eauto.\n            exploit PRIVATE_PARENT; eauto. i.\n            unfold AssnMem.private_block in *. des.\n            ii. subst. eauto.\n          * erewrite Mem.nextblock_free; eauto.\n          * rpapply NEXTBLOCK_PARENT.\n            eapply Mem.nextblock_free; eauto.\n      }\n    + inv STATE. inv SRC. eauto.\n    + inv STATE. inv TGT. eauto.\n    + inv STATE. ss.\n    + assert(EQ_ALLOC_SRC: Allocas (EC st1_src) = Allocas (EC st0_src)).\n      { inv STEP_SRC; ss; des_ifs.\n        - inv MC_SOME_SRC. des_ifs. } des.\n      rewrite EQ_ALLOC_SRC.\n      assert(EQ_ALLOC_TGT: Allocas (EC st1_tgt) = Allocas (EC st0_tgt)).\n      { inv STEP_TGT; ss; des_ifs.\n        - inv MC_SOME_TGT. des_ifs. } des.\n      rewrite EQ_ALLOC_TGT.\n      apply STATE.\n    + assert(EQ_ALLOC_SRC: Allocas (EC st1_src) = Allocas (EC st0_src)).\n      { inv STEP_SRC; ss; des_ifs.\n        - inv MC_SOME_SRC. des_ifs. } des.\n      rewrite EQ_ALLOC_SRC.\n      unfold Mem.valid_block.\n      expl Mem.nextblock_free (try exact FREE_SRC).\n      rewrite nextblock_free.\n      apply STATE.\n    + assert(EQ_ALLOC_TGT: Allocas (EC st1_tgt) = Allocas (EC st0_tgt)).\n      { inv STEP_TGT; ss; des_ifs.\n        - inv MC_SOME_TGT. des_ifs. } des.\n      rewrite EQ_ALLOC_TGT.\n      unfold Mem.valid_block.\n      expl Mem.nextblock_free (try exact FREE_TGT).\n      rewrite nextblock_free.\n      apply STATE.\n  - (* none - none *)\n    inv STATE_EQUIV_SRC. rewrite <- MEM_EQ. clear MEM_EQ.\n    inv STATE_EQUIV_TGT. rewrite <- MEM_EQ. clear MEM_EQ.\n    esplits; eauto; try reflexivity; try solve_alloc_inject.\n    + unfold alloc_private, alloc_private_unary. split.\n      * i. subst. ss. des_matchH MC_SOME_SRC; clarify.\n      * i. subst. ss. des_matchH MC_SOME_TGT; clarify.\n    + inv STATE. inv SRC. eauto.\n    + inv STATE. inv TGT. eauto.\n    + inv STATE. ss.\n    + assert(EQ_ALLOC_SRC: Allocas (EC st1_src) = Allocas (EC st0_src)).\n      { inv STEP_SRC; ss; des_ifs.\n        - inv MC_SOME_SRC. des_ifs. } des.\n      rewrite EQ_ALLOC_SRC.\n      assert(EQ_ALLOC_TGT: Allocas (EC st1_tgt) = Allocas (EC st0_tgt)).\n      { inv STEP_TGT; ss; des_ifs.\n        - inv MC_SOME_TGT. des_ifs. } des.\n      rewrite EQ_ALLOC_TGT.\n      apply STATE.\n    + assert(EQ_ALLOC_SRC: Allocas (EC st1_src) = Allocas (EC st0_src)).\n      { inv STEP_SRC; ss; des_ifs.\n        - inv MC_SOME_SRC. des_ifs. } des.\n      rewrite EQ_ALLOC_SRC.\n      apply STATE.\n    + assert(EQ_ALLOC_TGT: Allocas (EC st1_tgt) = Allocas (EC st0_tgt)).\n      { inv STEP_TGT; ss; des_ifs.\n        - inv MC_SOME_TGT. des_ifs. } des.\n      rewrite EQ_ALLOC_TGT.\n      apply STATE.\nUnshelve.\n{ by econs. }\nQed.\n\n(* assertion *)\n\nLemma diffblock_implies_noalias\n      conf gv1 gv2 ty1 ty2\n      (DIFFBLOCK: AssnState.Unary.sem_diffblock conf gv1 gv2)\n  : AssnState.Unary.sem_noalias conf gv1 gv2 ty1 ty2.\nProof.\n  unfold AssnState.Unary.sem_diffblock, AssnState.Unary.sem_noalias in *. des_ifs.\nQed.\n\nLemma is_diffblock_sem\n      conf st invst assnmem inv gmax public\n      v1 ty1 v2 ty2 gv1 gv2\n      (STATE : AssnState.Unary.sem conf st invst assnmem gmax public inv)\n      (IS_DIFFBLOCK : Assertion.is_diffblock inv (v1, ty1) (v2, ty2) = true)\n      (VAL1 : AssnState.Unary.sem_valueT conf st invst v1 = Some gv1)\n      (VAL2 : AssnState.Unary.sem_valueT conf st invst v2 = Some gv2)\n  : AssnState.Unary.sem_diffblock conf gv1 gv2.\nProof.\n  inv STATE.\n  destruct NOALIAS as [DIFFBLOCK NOALIAS].\n  unfold Assertion.is_diffblock in *.\n  unfold flip in *.\n  apply ValueTPairSetFacts.exists_iff in IS_DIFFBLOCK; try by solve_compat_bool.\n  inv IS_DIFFBLOCK.\n  destruct x as [p1 p2].\n  des. des_bool. des.\n  - des_bool. des. ss.\n    unfold proj_sumbool in *; des_ifs.\n    rewrite ValueTPairSetFacts.mem_iff in *.\n    eapply DIFFBLOCK; eauto.\n  - des_bool. des. ss.\n    unfold proj_sumbool in *; des_ifs.\n    rewrite ValueTPairSetFacts.mem_iff in *.\n    apply AssnState.Unary.diffblock_comm.\n    eapply DIFFBLOCK; eauto.\nQed.\n\nLemma is_noalias_sem\n      conf st invst assnmem inv gmax public\n      v1 ty1 v2 ty2 gv1 gv2\n      (STATE : AssnState.Unary.sem conf st invst assnmem gmax public inv)\n      (IS_NOALIAS : Assertion.is_noalias inv (v1, ty1) (v2, ty2) = true)\n      (VAL1 : AssnState.Unary.sem_valueT conf st invst v1 = Some gv1)\n      (VAL2 : AssnState.Unary.sem_valueT conf st invst v2 = Some gv2)\n  : AssnState.Unary.sem_noalias conf gv1 gv2 ty1 ty2.\nProof.\n  inv STATE.\n  destruct NOALIAS as [DIFFBLOCK NOALIAS].\n  unfold Assertion.is_noalias in *.\n  unfold flip in *.\n  apply PtrPairSetFacts.exists_iff in IS_NOALIAS; try by solve_compat_bool.\n  inv IS_NOALIAS.\n  destruct x as [p1 p2].\n  Opaque PtrSetFacts.eq_dec.\n  unfold proj_sumbool in *.\n  des. des_bool. des.\n  - des_bool. des. ss. des_ifs.\n    rewrite PtrPairSetFacts.mem_iff in *.\n    eapply NOALIAS; subst; eauto.\n  - des_bool. des. ss. des_ifs.\n    rewrite PtrPairSetFacts.mem_iff in *.\n    apply AssnState.Unary.noalias_comm.\n    eapply NOALIAS; subst; eauto.\nQed.\n\n(* TODO: simplify proof script *)\nLemma forget_memory_is_noalias_expr\n      conf st1 invst0 assnmem0 inv1 mem0 gmax public\n      vt_inv ty_inv gv_inv\n      v_forget ty_forget gv_forget\n      (STATE : AssnState.Unary.sem conf (mkState st1.(EC) st1.(ECS) mem0) invst0 assnmem0 gmax public inv1)\n      (NOALIAS_PTR: ForgetMemory.is_noalias_Ptr inv1 (ValueT.lift Tag.physical v_forget, ty_forget) (vt_inv, ty_inv) = true)\n      (FORGET_PTR: getOperandValue (CurTargetData conf) v_forget (Locals (EC st1)) (Globals conf) = Some gv_forget)\n      (INV_PTR: AssnState.Unary.sem_valueT conf st1 invst0 vt_inv = Some gv_inv)\n      (WF_GLOBALS: genericvalues_inject.wf_globals gmax (Globals conf))\n  : AssnState.Unary.sem_noalias conf gv_forget gv_inv ty_forget ty_inv.\nProof.\n  unfold ForgetMemory.is_noalias_Ptr in *.\n  do 4 (des_bool; des).\n  - rename NOALIAS_PTR0 into DIFFBLOCK_FROM_UNIQUE.\n    des_bool. des. des_bool.\n    rename NOALIAS_PTR0 into INV_UNIQUE.\n    unfold proj_sumbool in *. des_ifs. ss.\n\n    unfold Assertion.is_unique_ptr in *.\n    unfold Assertion.is_unique_value in *.\n    unfold proj_sumbool in *.\n    ss. des_ifs. des_bool. des.\n    destruct x as [[] x_inv]; ss.\n\n    inv STATE.\n    exploit UNIQUE; eauto.\n    { apply AtomSetFacts.mem_iff; eauto. }\n    intro UNIQUE_X.\n    unfold Assertion.values_diffblock_from_unique in *.\n    destruct v_forget as [x_forget| c_forget]; ss.\n    + inv UNIQUE_X.\n      assert (IDS_NEQ: x_forget <> x_inv).\n      { unfold IdT.lift in *.\n        match goal with\n        | [H: _ <> _ |- _] =>\n          ii; subst; apply H; reflexivity\n        end. }\n      apply diffblock_implies_noalias.\n      unfold AssnState.Unary.sem_idT in *. ss. clarify.\n      apply AssnState.Unary.diffblock_comm.\n      eapply LOCALS; eauto.\n    + apply diffblock_implies_noalias.\n      unfold AssnState.Unary.sem_idT in *. ss. clarify.\n      eapply AssnState.Unary.diffblock_comm.\n      eapply unique_const_diffblock; eauto.\n  - rename NOALIAS_PTR0 into DIFFBLOCK_FROM_UNIQUE.\n    des_bool. des. des_bool.\n    rename NOALIAS_PTR0 into INV_UNIQUE.\n    unfold proj_sumbool in *. des_ifs. ss.\n\n    unfold Assertion.is_unique_ptr in *.\n    unfold Assertion.is_unique_value in *.\n    unfold proj_sumbool in *.\n    ss. des_ifs. des_bool. des.\n\n    destruct x as [[] x_forget]; ss.\n    destruct v_forget; ss.\n    clarify.\n\n    inv STATE.\n    exploit UNIQUE; eauto.\n    { apply AtomSetFacts.mem_iff; eauto. }\n    intro UNIQUE_X.\n\n    unfold Assertion.values_diffblock_from_unique in *.\n    destruct vt_inv as [[[] x_inv]| c_inv]; ss.\n    + inv UNIQUE_X.\n      assert (IDS_NEQ: x_forget <> x_inv).\n      { unfold IdT.lift in *.\n        match goal with\n        | [H: _ <> _ |- _] =>\n          ii; subst; apply H; reflexivity\n        end. }\n      apply diffblock_implies_noalias.\n      unfold AssnState.Unary.sem_idT in *. ss. clarify.\n      \n      eapply LOCALS; eauto.\n    + apply diffblock_implies_noalias.\n      apply AssnState.Unary.diffblock_comm.\n      unfold AssnState.Unary.sem_idT in *. ss. clarify.\n      eapply AssnState.Unary.diffblock_comm.\n      eapply unique_const_diffblock; eauto.\n  - apply AssnState.Unary.noalias_comm.\n    eapply is_noalias_sem; eauto.\n    unfold ValueT.lift. des_ifs; eauto.\n  - eapply AssnState.Unary.diffblock_comm.\n    eapply is_diffblock_sem; eauto.\n    unfold ValueT.lift. des_ifs; eauto.\nQed.\n\nLemma forget_memory_is_noalias_exprpair\n      conf st1 invst0 assnmem0 inv1 mem0 gmax public\n      p a e2\n      vt_inv ty_inv gv_inv\n      v_forget ty_forget gv_forget\n      (STATE : AssnState.Unary.sem conf (mkState st1.(EC) st1.(ECS) mem0) invst0 assnmem0 gmax public inv1)\n      (PAIR : p = (Expr.load vt_inv ty_inv a, e2) \\/ p = (e2, Expr.load vt_inv ty_inv a))\n      (FORGET_MEMORY_NOALIAS : ForgetMemory.is_noalias_ExprPair inv1 (ValueT.lift Tag.physical v_forget, ty_forget) p = true)\n      (FORGET_PTR: getOperandValue (CurTargetData conf) v_forget (Locals (EC st1)) (Globals conf) = Some gv_forget)\n      (INV_PTR: AssnState.Unary.sem_valueT conf st1 invst0 vt_inv = Some gv_inv)\n      (WF_GLOBALS: genericvalues_inject.wf_globals gmax (Globals conf))\n  : AssnState.Unary.sem_noalias conf gv_forget gv_inv ty_forget ty_inv.\nProof.\n  unfold ForgetMemory.is_noalias_ExprPair in *.\n  des; des_bool; des; subst; ss;\n    eapply forget_memory_is_noalias_expr; eauto.\nQed.\n\nLemma exprpair_forget_memory_disjoint\n      conf st0 mem1 invst0 assnmem0 inv1 cmd mc gmax public\n      (STATE: AssnState.Unary.sem conf st0 invst0 assnmem0 gmax public inv1)\n      (MC_SOME : mem_change_of_cmd conf cmd st0.(EC).(Locals) = Some mc)\n      (STATE_EQUIV : states_mem_change conf st0.(Mem) mem1 mc)\n      (WF_GLOBALS: genericvalues_inject.wf_globals gmax (Globals conf))\n      (WF_MEM: MemProps.wf_Mem gmax (CurTargetData conf) st0.(Mem))\n  : <<SEM_EXPR_EQ: forall p e1 e2\n             (PAIR: p = (e1, e2) \\/ p = (e2, e1))\n             (FORGET_MEMORY : ExprPairSet.In p\n                                             (Assertion.lessdef\n                                                (ForgetMemory.unary\n                                                   (Cmd.get_def_memory cmd)\n                                                   (Cmd.get_leaked_ids_to_memory cmd)\n                                                   inv1))),\n        AssnState.Unary.sem_expr conf st0 invst0 e1 =\n        AssnState.Unary.sem_expr conf (mkState st0.(EC) st0.(ECS) mem1) invst0 e1>>.\nProof.\n  ii.\n  destruct mc.\n  - (* alloc *)\n    destruct cmd; ss; des_ifs.\n    destruct e1; ss.\n    + erewrite sem_list_valueT_eq_locals with (st1:=mkState st0.(EC) st0.(ECS) mem1); ss.\n    + erewrite sem_valueT_eq_locals with (st1:=mkState st0.(EC) st0.(ECS) mem1); ss.\n      des_ifs.\n      inv STATE_EQUIV.\n      destruct (GV2ptr conf.(CurTargetData) conf.(CurTargetData).(getPointerSize) g) eqn:GV2PTR; cycle 1.\n      { unfold mload. rewrite GV2PTR. reflexivity. }\n      destruct v0;\n        try by unfold mload; rewrite GV2PTR; eauto.\n      eapply alloca_preserves_mload_other_eq; eauto.\n      ii. subst.\n      inv STATE.\n      clear PAIR.\n      exploit alloca_result; eauto. i. des. subst.\n      destruct v.\n      { (* id case *)\n        destruct x as [[] x].\n        - (* physical *)\n          ss. unfold AssnState.Unary.sem_idT in *. ss.\n          exploit WF_LOCAL; eauto. i.\n          exploit MemProps.GV2ptr_preserves_valid_ptrs; eauto. i.\n          ss. des. psimpl.\n        - (* previous *)\n          ss. unfold AssnState.Unary.sem_idT in *. ss.\n          exploit WF_PREVIOUS; eauto. i.\n          exploit MemProps.GV2ptr_preserves_valid_ptrs; eauto. i.\n          ss. des. psimpl.\n        - (* ghost *)\n          ss. unfold AssnState.Unary.sem_idT in *. ss.\n          exploit WF_GHOST; eauto. i.\n          exploit MemProps.GV2ptr_preserves_valid_ptrs; eauto. i.\n          ss. des. psimpl.\n      }\n      { (* const case : need wf_const *)\n        ss.\n        rename g into __g__.\n        exploit MemAux.wf_globals_const2GV; eauto; []; intro VALID_PTR; des.\n        destruct WF_MEM as [_ WF_MEM].\n        clear - WF_MEM ALLOCA GV2PTR VALID_PTR.\n        (* GV2ptr is a bit weird? it is artificially made from above destruct, *)\n        (* and it seems main concern here is \"load\", so it may make sense.. *)\n        destruct __g__ as [|[headVal headChunki] tail]; ss.\n        destruct headVal; ss. des_ifs.\n        des. ss. clear VALID_PTR0.\n        clear - WF_MEM VALID_PTR.\n        replace (gmax + 1)%positive with (Pos.succ gmax)%positive in *; cycle 1.\n        { destruct gmax; ss. }\n        rewrite Pos.lt_succ_r in VALID_PTR.\n        exploit Pos.lt_le_trans; eauto.\n        intro CONTR. apply Pos.lt_irrefl in CONTR. ss.\n      }\n  - (* store *)\n    destruct cmd; ss; des_ifs.\n    inv STATE_EQUIV.\n    destruct e1; ss.\n    + erewrite sem_list_valueT_eq_locals with (st1:=mkState st0.(EC) st0.(ECS) mem1); ss.\n    + erewrite sem_valueT_eq_locals with (st1:=mkState st0.(EC) st0.(ECS) mem1); ss.\n      des_ifs.\n      \n      unfold ForgetMemory.unary, Cmd.get_leaked_ids_to_memory in *. ss.\n      des_ifs; ss.\n      * apply ExprPairSetFacts.filter_iff in FORGET_MEMORY; try by solve_compat_bool.\n        destruct FORGET_MEMORY as [FORGET_MEMORY_IN FORGET_MEMORY_NOALIAS].\n        symmetry. eapply mstore_noalias_mload; eauto.\n        eapply forget_memory_is_noalias_exprpair; eauto.\n        instantiate (3:= st0.(Mem)).\n        destruct st0. ss. exact STATE.\n      * apply ExprPairSetFacts.filter_iff in FORGET_MEMORY; try by solve_compat_bool.\n        destruct FORGET_MEMORY as [FORGET_MEMORY_IN FORGET_MEMORY_NOALIAS].\n        symmetry. eapply mstore_noalias_mload; eauto.\n        eapply forget_memory_is_noalias_exprpair; eauto.\n        instantiate (3:= st0.(Mem)).\n        destruct st0. ss. exact STATE.\n  - (* free *)\n    destruct cmd; ss; des_ifs.\n    rename Heq into GET_VALUE.\n    inv STATE_EQUIV.\n    destruct e1; ss.\n    + erewrite sem_list_valueT_eq_locals with (st1:=mkState st0.(EC) st0.(ECS) mem1); ss.\n    + erewrite sem_valueT_eq_locals with (st1:=mkState st0.(EC) st0.(ECS) mem1); ss.\n      des_ifs.\n      apply ExprPairSetFacts.filter_iff in FORGET_MEMORY; try by solve_compat_bool.\n      destruct FORGET_MEMORY as [FORGET_MEMORY_IN FORGET_MEMORY_NOALIAS].\n\n      symmetry. eapply mfree_noalias_mload; eauto.\n      eapply forget_memory_is_noalias_exprpair; eauto.\n      instantiate (3:= st0.(Mem)).\n      destruct st0. exact STATE.\n  - (* none *)\n    inv STATE_EQUIV. destruct st0; eauto.\nQed.\n\nLemma forget_memory_maydiff_preserved\n      conf_src mem1_src st0_src mem_change_src def_mem_src leaks_src\n      conf_tgt mem1_tgt st0_tgt mem_change_tgt def_mem_tgt leaks_tgt\n      invst0 assnmem0 inv0\n      (MEM_EQUIV_SRC : states_mem_change conf_src st0_src.(Mem) mem1_src mem_change_src)\n      (MEM_EQUIV_TGT : states_mem_change conf_tgt st0_tgt.(Mem) mem1_tgt mem_change_tgt)\n      (MAYDIFF : forall id : Tag.t * id,\n          IdTSet.mem id (Assertion.maydiff inv0) = false ->\n          AssnState.Rel.sem_inject (mkState st0_src.(EC) st0_src.(ECS) mem1_src)\n                                  (mkState st0_tgt.(EC) st0_tgt.(ECS) mem1_tgt)\n                                  invst0 (AssnMem.Rel.inject assnmem0) id)\n  : <<RES: forall id : Tag.t * id,\n      IdTSet.mem id (Assertion.maydiff (ForgetMemory.t def_mem_src def_mem_tgt leaks_src leaks_tgt inv0)) = false ->\n      AssnState.Rel.sem_inject (mkState st0_src.(EC) st0_src.(ECS) mem1_src)\n                              (mkState st0_tgt.(EC) st0_tgt.(ECS) mem1_tgt)\n                              invst0 (AssnMem.Rel.inject assnmem0) id>>.\nProof.\n  ii.\n  assert (DROP_FORGET_MEMORY:IdTSet.mem id0 (Assertion.maydiff inv0) = false).\n  { destruct def_mem_src; destruct def_mem_tgt; ss. }\n  exploit MAYDIFF; eauto.\nQed.\n\nLemma forget_memory_sem_unary\n      conf st0 mem1 mc cmd gmax public\n      inv1 invst0 assnmem0\n      (STATE: AssnState.Unary.sem conf st0 invst0 assnmem0 gmax public inv1)\n      (MC_SOME : mem_change_of_cmd conf cmd st0.(EC).(Locals) = Some mc)\n      (STATE_MC : states_mem_change conf st0.(Mem) mem1 mc)\n      (WF_GLOBALS: genericvalues_inject.wf_globals gmax (Globals conf))\n      (WF_MEM: MemProps.wf_Mem gmax (CurTargetData conf) st0.(Mem))\n  : AssnState.Unary.sem conf (mkState st0.(EC) st0.(ECS) mem1) invst0 assnmem0 gmax public\n                       (ForgetMemory.unary\n                          (Cmd.get_def_memory cmd)\n                          (Cmd.get_leaked_ids_to_memory cmd)\n                          inv1).\nProof.\n  hexploit exprpair_forget_memory_disjoint; eauto. intro EXPR_EQ. des.\n  unfold ForgetMemory.unary, Cmd.get_leaked_ids_to_memory.\n  destruct mc; cycle 3.\n  { destruct cmd; ss; des_ifs;\n      inv STATE_MC; destruct st0; eauto. }\n  - (* alloc *)\n    destruct cmd; ss; des_ifs.\n    inv STATE_MC.\n    inv STATE.\n\n    econs; eauto.\n    + ii.\n      destruct x.\n      erewrite <- EXPR_EQ in VAL1; try left; eauto. i. des.\n      exploit LESSDEF; eauto. i. des. ss.\n      esplits; eauto.\n      erewrite <- EXPR_EQ; eauto.\n    + inv NOALIAS. econs; eauto.\n    + ii.\n      exploit UNIQUE; eauto.\n\n      intro UNIQUE_X.\n      inv UNIQUE_X.\n      econs; eauto. i. ss.\n      exploit MemProps.alloca_preserves_mload_inv; eauto. i. des.\n      * eapply MEM; eauto.\n      *\n        apply AssnState.Unary.diffblock_comm.\n        apply AssnState.Unary.undef_diffblock; ss.\n    + ii. exploit PRIVATE; eauto. i. des.\n      esplits; eauto. ss.\n      unfold AssnMem.private_block in *. des.\n      split; eauto.\n      exploit alloca_result; eauto. i. des.\n      psimpl.\n    + ss. eapply Forall_harder; eauto. i.\n      exploit alloca_result; eauto; []; i; des.\n      clarify.\n      unfold Mem.valid_block in *.\n      rewrite NEXT_BLOCK.\n      etransitivity; eauto.\n      eapply Plt_succ.\n    + ss. eapply MemProps.alloca_preserves_wf_lc_in_tail; eauto.\n    + ss. eapply MemProps.alloca_preserves_wf_lc_in_tail; eauto.\n    + ss. eapply MemProps.alloca_preserves_wf_lc_in_tail; eauto.\n  - (* store *)\n    destruct cmd; ss; des_ifs.\n    { (* id *)\n      destruct value1; ss.\n      rename value2 into v_sptr.\n      rename Heq0 into SVAL.\n      rename Heq1 into SPTR.\n      inv STATE_MC.\n      inv STATE.\n      econs.\n      + ii. ss.\n        destruct x.\n        erewrite <- EXPR_EQ in VAL1; try left; eauto.\n        exploit LESSDEF; eauto.\n        { apply ExprPairSetFacts.filter_iff in H; try by solve_compat_bool. des. eauto. }\n        i. des.\n        erewrite EXPR_EQ in VAL2; try right; eauto.\n      + inv NOALIAS.\n        econs; eauto.\n      + ii. ss. clarify.\n        rewrite AtomSetFacts.remove_iff in *. des.\n        exploit UNIQUE; eauto.\n        intro UNIQUE_X.\n        eapply mstore_register_leak_no_unique; eauto.\n      + ss. ii. exploit PRIVATE; eauto. i. des.\n        esplits; eauto. ss.\n        unfold AssnMem.private_block in *. des.\n        split; eauto.\n        exploit MemProps.nextblock_mstore; eauto.\n        intro NEXTBLOCK_EQ. rewrite <- NEXTBLOCK_EQ.\n        psimpl.\n      + ss.\n      + ss. eapply Forall_harder; eauto.\n        i. exploit MemProps.nextblock_mstore; eauto; []; intro EQ; des.\n        unfold Mem.valid_block in *.\n        rewrite <- EQ. ss.\n      + ss. eapply MemProps.mstore_preserves_wf_lc; eauto.\n      + ss. eapply MemProps.mstore_preserves_wf_lc; eauto.\n      + ss. eapply MemProps.mstore_preserves_wf_lc; eauto.\n      + eauto.\n      + ss.\n      + ss.\n    }\n    { destruct value1; ss.\n      rename value2 into v_sptr.\n      rename Heq0 into SVAL.\n      rename Heq1 into SPTR.\n      inv STATE_MC.\n      inv STATE.\n      econs.\n      + ii. ss.\n        destruct x.\n        erewrite <- EXPR_EQ in VAL1; try left; eauto.\n        exploit LESSDEF; eauto.\n        { apply ExprPairSetFacts.filter_iff in H; try by solve_compat_bool. des. eauto. }\n        i. des.\n        erewrite EXPR_EQ in VAL2; try right; eauto.\n      + inv NOALIAS.\n        econs; eauto.\n      + ii. ss.\n        exploit UNIQUE; eauto.\n        intro UNIQUE_X.\n        eapply mstore_const_leak_no_unique; eauto.\n      + ss. ii. exploit PRIVATE; eauto. i. des.\n        esplits; eauto. ss.\n        unfold AssnMem.private_block in *. des.\n        split; eauto.\n        exploit MemProps.nextblock_mstore; eauto.\n        intro NEXTBLOCK_EQ. rewrite <- NEXTBLOCK_EQ.\n        psimpl.\n      + ss.\n      + ss. eapply Forall_harder; eauto.\n        i. exploit MemProps.nextblock_mstore; eauto; []; intro EQ; des.\n        unfold Mem.valid_block in *.\n        rewrite <- EQ. ss.\n      + ss. eapply MemProps.mstore_preserves_wf_lc; eauto.\n      + ss. eapply MemProps.mstore_preserves_wf_lc; eauto.\n      + ss. eapply MemProps.mstore_preserves_wf_lc; eauto.\n      + eauto.\n      + ss.\n      + ss.\n    }\n  - destruct cmd; ss; des_ifs.\n    inv STATE_MC.\n    inv STATE.\n    econs; eauto.\n    + ii.\n      destruct x.\n      erewrite <- EXPR_EQ in VAL1; try left; eauto.\n      exploit LESSDEF; eauto.\n      { apply ExprPairSetFacts.filter_iff in H; try by solve_compat_bool. des. eauto. }\n      i. des.\n      erewrite EXPR_EQ in VAL2; try right; eauto.\n    + inv NOALIAS.\n      econs; eauto.\n    + ii. ss.\n      exploit UNIQUE; eauto.\n      intro UNIQUE_X.\n      inv UNIQUE_X.\n      econs; eauto.\n      ii. des.\n      exploit MemProps.free_preserves_mload_inv; eauto; []; i; des.\n      exploit MEM; eauto.\n    + ss. ii. exploit PRIVATE; eauto. i. des.\n      esplits; eauto. ss.\n      unfold AssnMem.private_block in *. des.\n      split; eauto.\n      exploit MemProps.nextblock_free; eauto.\n      intro NEXTBLOCK_EQ. rewrite <- NEXTBLOCK_EQ.\n      psimpl.\n    + ss. eapply Forall_harder; eauto.\n      i. exploit MemProps.nextblock_free; eauto; []; intro EQ; des.\n      unfold Mem.valid_block in *.\n      rewrite <- EQ. ss.\n    + ss. eapply MemProps.free_preserves_wf_lc; eauto.\n    + ss. eapply MemProps.free_preserves_wf_lc; eauto.\n    + ss. eapply MemProps.free_preserves_wf_lc; eauto.\nQed.\n\nLemma forget_memory_sem\n      conf_src st0_src mem1_src mc_src cmd_src\n      conf_tgt st0_tgt mem1_tgt mc_tgt cmd_tgt\n      inv0 invst0 assnmem0\n      (STATE : AssnState.Rel.sem conf_src conf_tgt st0_src st0_tgt invst0 assnmem0 inv0)\n      (WF_GLOBALS_SRC: genericvalues_inject.wf_globals (AssnMem.Rel.gmax assnmem0) (Globals conf_src))\n      (WF_GLOBALS_TGT: genericvalues_inject.wf_globals (AssnMem.Rel.gmax assnmem0) (Globals conf_tgt))\n      (MC_SOME_SRC : mem_change_of_cmd conf_src cmd_src st0_src.(EC).(Locals) = Some mc_src)\n      (MC_SOME_TGT : mem_change_of_cmd conf_tgt cmd_tgt st0_tgt.(EC).(Locals) = Some mc_tgt)\n      (STATE_MC_SRC : states_mem_change conf_src st0_src.(Mem) mem1_src mc_src)\n      (STATE_MC_TGT : states_mem_change conf_tgt st0_tgt.(Mem) mem1_tgt mc_tgt)\n      (WF_MEM_SRC: MemProps.wf_Mem assnmem0.(AssnMem.Rel.gmax) (CurTargetData conf_src) st0_src.(Mem))\n      (WF_MEM_TGT: MemProps.wf_Mem assnmem0.(AssnMem.Rel.gmax) (CurTargetData conf_tgt) st0_tgt.(Mem))\n  : AssnState.Rel.sem conf_src conf_tgt\n                     (mkState st0_src.(EC) st0_src.(ECS) mem1_src)\n                     (mkState st0_tgt.(EC) st0_tgt.(ECS) mem1_tgt)\n                     invst0 assnmem0\n                     (ForgetMemory.t (Cmd.get_def_memory cmd_src)\n                                     (Cmd.get_def_memory cmd_tgt)\n                                     (Cmd.get_leaked_ids_to_memory cmd_src)\n                                     (Cmd.get_leaked_ids_to_memory cmd_tgt)\n                                     inv0).\nProof.\n  inv STATE.\n  unfold ForgetMemory.t.\n  econs.\n  - eapply forget_memory_sem_unary; try exact SRC; eauto.\n  - eapply forget_memory_sem_unary; try exact TGT; eauto.\n  - ss.\n    eapply AtomSetFacts.Empty_s_m; eauto. red.\n    unfold ForgetMemory.unary.\n    des_ifs; ss.\n    + eapply AtomSetProperties.subset_remove_3; eauto.\n      eapply AtomSetFacts.Subset_refl.\n    + eapply AtomSetProperties.subset_remove_3; eauto.\n      eapply AtomSetFacts.Subset_refl.\n  - eapply forget_memory_maydiff_preserved; eauto.\n  - ss.\nQed.\n\nLemma inv_state_sem_monotone_wrt_assnmem\n      assnmem0 assnmem1 invst0 inv1\n      conf_src st_src\n      conf_tgt st_tgt\n      (MEM_LE:AssnMem.Rel.le assnmem0 assnmem1)\n      (PRIVATE_PRESERVED_SRC: IdTSet.For_all\n                                (AssnState.Unary.sem_private\n                                   conf_src st_src (AssnState.Rel.src invst0)\n                                   (AssnMem.Unary.private_parent (AssnMem.Rel.src assnmem1))\n                                   (AssnMem.Rel.public_src (AssnMem.Rel.inject assnmem1)))\n                                (Assertion.private (Assertion.src inv1)))\n      (PRIVATE_PRESERVED_TGT: IdTSet.For_all\n                                (AssnState.Unary.sem_private\n                                   conf_tgt st_tgt (AssnState.Rel.tgt invst0)\n                                   (AssnMem.Unary.private_parent (AssnMem.Rel.tgt assnmem1))\n                                   (AssnMem.Rel.public_tgt (AssnMem.Rel.inject assnmem1)))\n                                (Assertion.private (Assertion.tgt inv1)))\n      (STATE:AssnState.Rel.sem conf_src conf_tgt st_src st_tgt invst0 assnmem0 inv1)\n      (INJECT_ALLOCAS_NEW:\n           AssnState.Rel.inject_allocas (AssnMem.Rel.inject assnmem1)\n                                       st_src.(EC).(Allocas) st_tgt.(EC).(Allocas))\n  : AssnState.Rel.sem conf_src conf_tgt st_src st_tgt invst0 assnmem1 inv1.\nProof.\n  destruct STATE as [STATE_SRC STATE_TGT TGT_NOUNIQ STATE_MAYDIFF].\n  inv MEM_LE.\n  econs.\n  - inv SRC.\n    inv STATE_SRC.\n    econs; eauto.\n    + rewrite <- GMAX. eauto.\n    + rewrite <- PRIVATE_PARENT_EQ. ss.\n    + rewrite <- UNIQUE_PARENT_EQ. eauto.\n  - inv TGT.\n    inv STATE_TGT.\n    econs; eauto.\n    + rewrite <- GMAX. eauto.\n    + rewrite <- PRIVATE_PARENT_EQ. ss.\n    + rewrite <- UNIQUE_PARENT_EQ. eauto.\n  - ss.\n  - i. hexploit STATE_MAYDIFF; eauto.\n    intros SEM_INJECT.\n    ii. exploit SEM_INJECT; eauto. i. des.\n    esplits; eauto.\n    eapply genericvalues_inject.gv_inject_incr; eauto.\n  - ss.\nQed.\n\nLemma forget_memory_sound\n      m_src conf_src st0_src st1_src cmd_src cmds_src evt_src\n      m_tgt conf_tgt st0_tgt st1_tgt cmd_tgt cmds_tgt evt_tgt\n      invst0 assnmem0 inv0\n      (CONF: AssnState.valid_conf m_src m_tgt conf_src conf_tgt)\n      (STATE: AssnState.Rel.sem conf_src conf_tgt st0_src st0_tgt invst0 assnmem0 inv0)\n      (CMD_SRC: st0_src.(EC).(CurCmds) = cmd_src::cmds_src)\n      (CMD_TGT: st0_tgt.(EC).(CurCmds) = cmd_tgt::cmds_tgt)\n      (NONCALL_SRC: Instruction.isCallInst cmd_src = false)\n      (NONCALL_TGT: Instruction.isCallInst cmd_tgt = false)\n      (STEP_SRC: sInsn conf_src st0_src st1_src evt_src)\n      (STEP_TGT: sInsn conf_tgt st0_tgt st1_tgt evt_tgt)\n      (INJECT_EVENT: postcond_cmd_inject_event cmd_src cmd_tgt inv0)\n      (MEM: AssnMem.Rel.sem conf_src conf_tgt st0_src.(Mem) st0_tgt.(Mem) assnmem0)\n  : exists assnmem1,\n      <<ALLOC_INJECT: alloc_inject conf_src conf_tgt st0_src st0_tgt\n                                   st1_src st1_tgt cmd_src cmd_tgt assnmem1>> /\\\n      <<ALLOC_PRIVATE: alloc_private conf_src conf_tgt cmd_src cmd_tgt st0_src st0_tgt st1_src st1_tgt assnmem1>> /\\\n      <<STATE: AssnState.Rel.sem conf_src conf_tgt\n                                (mkState st0_src.(EC) st0_src.(ECS) st1_src.(Mem))\n                                (mkState st0_tgt.(EC) st0_tgt.(ECS) st1_tgt.(Mem))\n                                invst0 assnmem1\n                                (ForgetMemory.t\n                                   (Cmd.get_def_memory cmd_src)\n                                   (Cmd.get_def_memory cmd_tgt)\n                                   (Cmd.get_leaked_ids_to_memory cmd_src)\n                                   (Cmd.get_leaked_ids_to_memory cmd_tgt)\n                                   inv0) >> /\\\n      <<MEM: AssnMem.Rel.sem conf_src conf_tgt st1_src.(Mem) st1_tgt.(Mem) assnmem1>> /\\\n      <<MEMLE: AssnMem.Rel.le assnmem0 assnmem1>> /\\\n      <<INJECT_ALLOCAS: AssnState.Rel.inject_allocas (AssnMem.Rel.inject assnmem1)\n                         st1_src.(EC).(Allocas) st1_tgt.(EC).(Allocas)>> /\\\n      <<VALID_ALLOCAS_SRC: Forall (Mem.valid_block (Mem st1_src)) st1_src.(EC).(Allocas)>> /\\\n      <<VALID_ALLOCAS_TGT: Forall (Mem.valid_block (Mem st1_tgt)) st1_tgt.(EC).(Allocas)>>\n.\nProof.\n  assert (STATE2:= STATE).\n  inv STATE2.\n  exploit postcond_cmd_inject_event_non_malloc; eauto; []; ii; des.\n  exploit step_mem_change; try exact SRC; eauto.\n  { inv MEM. exact SRC0. }\n  i. des.\n  exploit step_mem_change; try exact TGT; eauto.\n  { inv MEM. exact TGT0. }\n  i. des.\n  exploit inject_assnmem; try exact INJECT_EVENT; eauto. i. des.\n  esplits; eauto.\n  - eapply forget_memory_sem; eauto.\n\n    eapply inv_state_sem_monotone_wrt_assnmem; eauto.\n    { apply MEM0. }\n    { apply MEM0. }\n    { inv MEMLE. rewrite <- GMAX. apply MEM. }\n    { inv MEMLE. rewrite <- GMAX. apply MEM. }\nQed.", "meta": {"author": "snu-sf", "repo": "crellvm", "sha": "668249b88756233f96b3ef21f12993501a348afc", "save_path": "github-repos/coq/snu-sf-crellvm", "path": "github-repos/coq/snu-sf-crellvm/crellvm-668249b88756233f96b3ef21f12993501a348afc/coq/proof/SoundForgetMemory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.20608813522623917}}
{"text": "Require Import AutoSep Malloc PrintInt Bootstrap.\n\n\nModule Type S.\n  Variable heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"test\"!\"main\" @ [PrintInt.mainS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Call \"test\"!\"main\"()\n        [PREonly[_] [| False |] ]\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Definition m0 := link Malloc.m boot.\n  Definition m1 := link PrintInt.m m0.\n\n  Lemma ok0 : moduleOk m0.\n    link Malloc.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link PrintInt.ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n  \n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, $(size * 4) <= w -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "gmalecha", "repo": "bedrock-mirror-shard", "sha": "ea7e5ad56a1d6392468b6823e0457dd44524bca7", "save_path": "github-repos/coq/gmalecha-bedrock-mirror-shard", "path": "github-repos/coq/gmalecha-bedrock-mirror-shard/bedrock-mirror-shard-ea7e5ad56a1d6392468b6823e0457dd44524bca7/platform/tests/PrintIntDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.20608813522623914}}
{"text": "From cap_machine Require Export logrel.\nFrom cap_machine.rules Require Export rules_AddSubLt.\nFrom cap_machine.rules Require Import rules_base.\nFrom iris.proofmode Require Import tactics.\nFrom iris.program_logic Require Import weakestpre adequacy lifting.\nFrom stdpp Require Import base.\nFrom cap_machine Require Import machine_base.\n\nSection fundamental.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n          {stsg : STSG Addr region_type Σ} {heapg : heapG Σ}\n          `{MonRef: MonRefG (leibnizO _) CapR_rtc Σ} {nainv: logrel_na_invs Σ}\n          `{MachineParameters}.\n\n  Notation STS := (leibnizO (STS_states * STS_rels)).\n  Notation STS_STD := (leibnizO (STS_std_states Addr region_type)).\n  Notation WORLD := (prodO STS_STD STS). \n  Implicit Types W : WORLD.\n\n  Notation D := (WORLD -n> (leibnizO Word) -n> iProp Σ).\n  Notation R := (WORLD -n> (leibnizO Reg) -n> iProp Σ).\n  Implicit Types w : (leibnizO Word).\n  Implicit Types interp : (D).\n\n  Lemma add_sub_lt_case (W : WORLD) (r : leibnizO Reg) (p p' : Perm)\n        (g : Locality) (b e a : Addr) (w : Word) (ρ : region_type) (dst : RegName) (r1 r2: Z + RegName): \n      p = RX ∨ p = RWX ∨ (p = RWLX /\\ g = Local)\n    → (∀ x : RegName, is_Some (r !! x))\n    → isCorrectPC (inr (p, g, b, e, a))\n    → (b <= a)%a ∧ (a < e)%a\n    → PermFlows p p'\n    → (if pwl p then region_state_pwl W a else region_state_nwl W a g)\n    → std W !! a = Some ρ\n    → (ρ ≠ Revoked ∧ (∀ g, ρ ≠ Static g))\n    → p' ≠ O\n    → (decodeInstrW w = Add dst r1 r2 \\/\n       decodeInstrW w = Sub dst r1 r2 \\/\n       decodeInstrW w = Lt dst r1 r2)\n    -> □ ▷ (∀ a0 a1 a2 a3 a4 a5 a6,\n             full_map a1\n          -∗ (∀ r1 : RegName, ⌜r1 ≠ PC⌝ → ((fixpoint interp1) a0) (a1 !r! r1))\n          -∗ registers_mapsto (<[PC:=inr (a2, a3, a4, a5, a6)]> a1)\n          -∗ region a0\n          -∗ sts_full_world a0\n          -∗ na_own logrel_nais ⊤\n          -∗ ⌜a2 = RX ∨ a2 = RWX ∨ (a2 = RWLX /\\ a3 = Local)⌝\n             → □ ([∗ list] a7 ∈ region_addrs a4 a5, ∃ p'0 : Perm, ⌜PermFlows a2 p'0⌝ ∗\n                                                                   read_write_cond a7 p'0 interp\n                                                                     ∧ ⌜if pwl a2\n                                                                        then region_state_pwl a0 a7\n                                                                        else region_state_nwl a0 a7 a3⌝)\n                 -∗ interp_conf a0)\n    -∗ ([∗ list] a0 ∈ region_addrs b e, ∃ p'0 : Perm,\n                                           ⌜PermFlows p p'0⌝\n                                        ∗ read_write_cond a0 p'0 interp\n                                        ∧ ⌜if pwl p\n                                           then region_state_pwl W a0\n                                           else region_state_nwl W a0 g⌝)\n    -∗ (∀ r1 : RegName, ⌜r1 ≠ PC⌝ → ((fixpoint interp1) W) (r !r! r1))\n    -∗ read_write_cond a p' interp\n    -∗ (▷ if decide (ρ = Temporary ∧ pwl p' = true)\n        then future_pub_mono (λ Wv : WORLD * (leibnizO Word), ((fixpoint interp1) Wv.1) Wv.2) w\n        else future_priv_mono (λ Wv : WORLD * (leibnizO Word), ((fixpoint interp1) Wv.1) Wv.2) w)\n    -∗ ▷ ((fixpoint interp1) W) w\n    -∗ sts_full_world W\n    -∗ na_own logrel_nais ⊤\n    -∗ open_region a W\n    -∗ sts_state_std a ρ\n    -∗ a ↦ₐ[p'] w\n    -∗ PC ↦ᵣ inr (p, g, b, e, a)\n    -∗ ([∗ map] k↦y ∈ delete PC (<[PC:=inr (p, g, b, e, a)]> r), k ↦ᵣ y)\n    -∗\n        WP Instr Executable\n        {{ v, WP Seq (cap_lang.of_val v)\n                 {{ v0, ⌜v0 = HaltedV⌝\n                        → ∃ (r1 : Reg) (W' : WORLD),\n                        full_map r1\n                        ∧ registers_mapsto r1\n                                           ∗ ⌜related_sts_priv_world W W'⌝\n                                           ∗ na_own logrel_nais ⊤\n                                           ∗ sts_full_world W' ∗ region W' }} }}.\n  Proof.\n    intros Hp Hsome i Hbae Hfp Hpwl Hregion [Hnotrevoked Hnotstatic] HO Hi.\n    iIntros \"#IH #Hinv #Hreg #Hinva Hmono #Hw Hsts Hown\".\n    iIntros \"Hr Hstate Ha HPC Hmap\".\n    rewrite delete_insert_delete.\n    iDestruct ((big_sepM_delete _ _ PC) with \"[HPC Hmap]\") as \"Hmap /=\";\n      [apply lookup_insert|rewrite delete_insert_delete;iFrame|]. simpl.\n    iApply (wp_AddSubLt with \"[$Ha $Hmap]\"); eauto.\n    { simplify_map_eq; auto. }\n    { rewrite /subseteq /map_subseteq /set_subseteq. intros rr _.\n      apply elem_of_gmap_dom. apply lookup_insert_is_Some'; eauto. }\n\n    iIntros \"!>\" (regs' retv). iDestruct 1 as (HSpec) \"[Ha Hmap]\".\n    destruct HSpec; cycle 1.\n    { iApply wp_pure_step_later; auto. iNext.\n      iApply wp_value; auto. iIntros; discriminate. }\n    { incrementPC_inv; simplify_map_eq.\n      iApply wp_pure_step_later; auto. iNext.\n      assert (dst <> PC) as HdstPC by (intros ->; simplify_map_eq).\n      simplify_map_eq.\n      iDestruct (region_close with \"[$Hstate $Hr $Ha $Hmono]\") as \"Hr\"; eauto.\n      { destruct ρ;auto;[..|specialize (Hnotstatic g)];contradiction. }\n      iApply (\"IH\" $! _ (<[dst:=_]> (<[PC:=_]> r)) with \"[%] [] [Hmap] [$Hr] [$Hsts] [$Hown]\");\n        try iClear \"IH\"; eauto.\n      { intro. cbn. by repeat (rewrite lookup_insert_is_Some'; right). }\n      iIntros (ri Hri). rewrite /(RegLocate _ ri) insert_commute // lookup_insert_ne //; [].\n      destruct (decide (ri = dst)); simplify_map_eq.\n      { repeat rewrite fixpoint_interp1_eq; auto. }\n      { by iApply \"Hreg\". } }\n  Qed.\n\nEnd fundamental.\n", "meta": {"author": "logsem", "repo": "cerise-stack", "sha": "f68111362730aff998798d63c7d6a0a7176eff44", "save_path": "github-repos/coq/logsem-cerise-stack", "path": "github-repos/coq/logsem-cerise-stack/cerise-stack-f68111362730aff998798d63c7d6a0a7176eff44/theories/ftlr/AddSubLt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.20608813133589354}}
{"text": "Require Import Coqlib.\nRequire Import Maps.\nRequire Import Values.\nRequire Import Memory.\nRequire Memimpl.\nRequire Import Deadcodeproof.\nRequire Import NeedDomain.\n\n(** * Relating the memory states *)\n\n(** The [magree] predicate is a variant of [Mem.extends] where we\n  allow the contents of the two memory states to differ arbitrarily\n  on some locations.  The predicate [P] is true on the locations whose\n  contents must be in the [lessdef] relation. *)\n\n(** [CompCertX:test-compcert-param-memory] [magree] used to be defined in [Deadcodeproof].\n  However, this definition is based on the\n  concrete implementation of the memory model.\n  We now specify it abstractly in [Deadcodeproof], and we moved\n  the concrete implementation and its proofs here,\n  relying on the new [Memimpl]. *)\n\nRecord magree (m1 m2: Memimpl.mem) (P: locset) : Prop := mk_magree {\n  ma_perm:\n    forall b ofs k p,\n    Memimpl.perm m1 b ofs k p ->\n    Memimpl.perm m2 b ofs k p;\n  ma_memval:\n    forall b ofs,\n    Memimpl.perm m1 b ofs Cur Readable ->\n    P b ofs ->\n    memval_lessdef (ZMap.get ofs (PMap.get b (Memimpl.mem_contents m1)))\n                   (ZMap.get ofs (PMap.get b (Memimpl.mem_contents m2)));\n  ma_nextblock:\n    Memimpl.nextblock m2 = Memimpl.nextblock m1\n}.\n\nLemma magree_monotone:\n  forall m1 m2 (P Q: locset),\n  magree m1 m2 P ->\n  (forall b ofs, Q b ofs -> P b ofs) ->\n  magree m1 m2 Q.\nProof.\n  intros. destruct H. constructor; auto.\nQed.\n\nLemma mextends_agree:\n  forall m1 m2 P, Memimpl.extends m1 m2 -> magree m1 m2 P.\nProof.\n  intros. destruct H. destruct mext_inj. constructor; intros.\n- replace ofs with (ofs + 0) by omega. eapply mi_perm; eauto. auto.\n- exploit mi_memval; eauto. unfold inject_id; eauto. \n  rewrite Zplus_0_r. auto. \n- auto.\nQed.\n\nLemma magree_extends:\n  forall m1 m2 (P: locset),\n  (forall b ofs, P b ofs) ->\n  magree m1 m2 P -> Memimpl.extends m1 m2.\nProof.\n  intros. destruct H0. constructor; auto. constructor; unfold inject_id; intros.\n- inv H0. rewrite Zplus_0_r. simpl in *; eauto. \n- inv H0. apply Zdivide_0. \n- inv H0. rewrite Zplus_0_r. eapply ma_memval0; eauto.\nQed.\n\nLemma magree_loadbytes:\n  forall m1 m2 P b ofs n bytes,\n  magree m1 m2 P ->\n  Memimpl.loadbytes m1 b ofs n = Some bytes ->\n  (forall i, ofs <= i < ofs + n -> P b i) ->\n  exists bytes', Memimpl.loadbytes m2 b ofs n = Some bytes' /\\ list_forall2 memval_lessdef bytes bytes'.\nProof.\n  assert (GETN: forall c1 c2 n ofs,\n    (forall i, ofs <= i < ofs + Z.of_nat n -> memval_lessdef (ZMap.get i c1) (ZMap.get i c2)) ->\n    list_forall2 memval_lessdef (Memimpl.getN n ofs c1) (Memimpl.getN n ofs c2)).\n  {\n    induction n; intros; simpl. \n    constructor.\n    rewrite inj_S in H. constructor.\n    apply H. omega. \n    apply IHn. intros; apply H; omega.\n  }\n  unfold Memimpl.loadbytes; intros. destruct H. \n  destruct (Memimpl.range_perm_dec m1 b ofs (ofs + n) Cur Readable); inv H0.\n  rewrite pred_dec_true. econstructor; split; eauto.\n  apply GETN. intros. rewrite nat_of_Z_max in H.\n  assert (ofs <= i < ofs + n) by xomega. \n  apply ma_memval0; auto.\n  red; intros; eauto. \nQed.\n\nLemma magree_load:\n  forall m1 m2 P chunk b ofs v,\n  magree m1 m2 P ->\n  Memimpl.load chunk m1 b ofs = Some v ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> P b i) ->\n  exists v', Memimpl.load chunk m2 b ofs = Some v' /\\ Val.lessdef v v'.\nProof.\n  intros. exploit Memimpl.load_valid_access; eauto. intros [A B]. \n  exploit Memimpl.load_loadbytes; eauto. intros [bytes [C D]].\n  exploit magree_loadbytes; eauto. intros [bytes' [E F]].\n  exists (decode_val chunk bytes'); split. \n  apply Memimpl.loadbytes_load; auto. \n  apply val_inject_id. subst v. apply decode_val_inject; auto. \nQed.\n\nLemma magree_storebytes_parallel:\n  forall m1 m2 (P Q: locset) b ofs bytes1 m1' bytes2,\n  magree m1 m2 P ->\n  Memimpl.storebytes m1 b ofs bytes1 = Some m1' ->\n  (forall b' i, Q b' i ->\n                b' <> b \\/ i < ofs \\/ ofs + Z_of_nat (length bytes1) <= i ->\n                P b' i) ->\n  list_forall2 memval_lessdef bytes1 bytes2 ->\n  exists m2', Memimpl.storebytes m2 b ofs bytes2 = Some m2' /\\ magree m1' m2' Q.\nProof.\n  assert (SETN: forall (access: Z -> Prop) bytes1 bytes2,\n    list_forall2 memval_lessdef bytes1 bytes2 ->\n    forall p c1 c2,\n    (forall i, access i -> i < p \\/ p + Z.of_nat (length bytes1) <= i -> memval_lessdef (ZMap.get i c1) (ZMap.get i c2)) ->\n    forall q, access q ->\n    memval_lessdef (ZMap.get q (Memimpl.setN bytes1 p c1))\n                   (ZMap.get q (Memimpl.setN bytes2 p c2))).\n  {\n    induction 1; intros; simpl.\n  - apply H; auto. simpl. omega.\n  - simpl length in H1; rewrite inj_S in H1. \n    apply IHlist_forall2; auto. \n    intros. rewrite ! ZMap.gsspec. destruct (ZIndexed.eq i p). auto. \n    apply H1; auto. unfold ZIndexed.t in *; omega. \n  }\n  intros. \n  destruct (Memimpl.range_perm_storebytes m2 b ofs bytes2) as [m2' ST2].\n  { erewrite <- list_forall2_length by eauto. red; intros.\n    eapply ma_perm; eauto. \n    eapply Memimpl.storebytes_range_perm; eauto. }\n  exists m2'; split; auto. \n  constructor; intros.\n- eapply Memimpl.perm_storebytes_1; eauto. eapply ma_perm; eauto.\n  eapply Memimpl.perm_storebytes_2; eauto. \n- rewrite (Memimpl.storebytes_mem_contents _ _ _ _ _ H0).\n  rewrite (Memimpl.storebytes_mem_contents _ _ _ _ _ ST2).\n  rewrite ! PMap.gsspec. destruct (peq b0 b).\n+ subst b0. apply SETN with (access := fun ofs => Memimpl.perm m1' b ofs Cur Readable /\\ Q b ofs); auto.\n  intros. destruct H5. eapply ma_memval; eauto.\n  eapply Memimpl.perm_storebytes_2; eauto.\n  apply H1; auto.\n+ eapply ma_memval; eauto. eapply Memimpl.perm_storebytes_2; eauto. apply H1; auto.\n- rewrite (Memimpl.nextblock_storebytes _ _ _ _ _ H0).\n  rewrite (Memimpl.nextblock_storebytes _ _ _ _ _ ST2).\n  eapply ma_nextblock; eauto. \nQed.\n\nLemma magree_store_parallel:\n  forall m1 m2 (P Q: locset) chunk b ofs v1 m1' v2,\n  magree m1 m2 P ->\n  Memimpl.store chunk m1 b ofs v1 = Some m1' ->\n  vagree v1 v2 (store_argument chunk) ->\n  (forall b' i, Q b' i ->\n                b' <> b \\/ i < ofs \\/ ofs + size_chunk chunk <= i ->\n                P b' i) ->\n  exists m2', Memimpl.store chunk m2 b ofs v2 = Some m2' /\\ magree m1' m2' Q.\nProof.\n  intros. \n  exploit Memimpl.store_valid_access_3; eauto. intros [A B]. \n  exploit Memimpl.store_storebytes; eauto. intros SB1.\n  exploit magree_storebytes_parallel. eauto. eauto. \n  instantiate (1 := Q). intros. rewrite encode_val_length in H4.\n  rewrite <- size_chunk_conv in H4. apply H2; auto. \n  eapply store_argument_sound; eauto. \n  intros [m2' [SB2 AG]]. \n  exists m2'; split; auto.\n  apply Memimpl.storebytes_store; auto. \nQed.\n\nLemma magree_storebytes_left:\n  forall m1 m2 P b ofs bytes1 m1',\n  magree m1 m2 P ->\n  Memimpl.storebytes m1 b ofs bytes1 = Some m1' ->\n  (forall i, ofs <= i < ofs + Z_of_nat (length bytes1) -> ~(P b i)) ->\n  magree m1' m2 P.\nProof.\n  intros. constructor; intros.\n- eapply ma_perm; eauto. eapply Memimpl.perm_storebytes_2; eauto. \n- rewrite (Memimpl.storebytes_mem_contents _ _ _ _ _ H0).\n  rewrite PMap.gsspec. destruct (peq b0 b).\n+ subst b0. rewrite Memimpl.setN_outside. eapply ma_memval; eauto. eapply Memimpl.perm_storebytes_2; eauto.\n  destruct (zlt ofs0 ofs); auto. destruct (zle (ofs + Z.of_nat (length bytes1)) ofs0); try omega.\n  elim (H1 ofs0). omega. auto. \n+ eapply ma_memval; eauto. eapply Memimpl.perm_storebytes_2; eauto.\n- rewrite (Memimpl.nextblock_storebytes _ _ _ _ _ H0).\n  eapply ma_nextblock; eauto. \nQed.\n\nLemma magree_store_left:\n  forall m1 m2 P chunk b ofs v1 m1',\n  magree m1 m2 P ->\n  Memimpl.store chunk m1 b ofs v1 = Some m1' ->\n  (forall i, ofs <= i < ofs + size_chunk chunk -> ~(P b i)) ->\n  magree m1' m2 P.\nProof.\n  intros. eapply magree_storebytes_left; eauto.\n  eapply Memimpl.store_storebytes; eauto. \n  intros. rewrite encode_val_length in H2.\n  rewrite <- size_chunk_conv in H2. apply H1; auto. \nQed.\n\nLemma magree_free:\n  forall m1 m2 (P Q: locset) b lo hi m1',\n  magree m1 m2 P ->\n  Memimpl.free m1 b lo hi = Some m1' ->\n  (forall b' i, Q b' i ->\n                b' <> b \\/ ~(lo <= i < hi) ->\n                P b' i) ->\n  exists m2', Memimpl.free m2 b lo hi = Some m2' /\\ magree m1' m2' Q.\nProof.\n  intros. \n  destruct (Memimpl.range_perm_free m2 b lo hi) as [m2' FREE].\n  red; intros. eapply ma_perm; eauto. eapply Memimpl.free_range_perm; eauto. \n  exists m2'; split; auto.\n  constructor; intros.\n- (* permissions *)\n  assert (Memimpl.perm m2 b0 ofs k p). { eapply ma_perm; eauto. eapply Memimpl.perm_free_3; eauto. }\n  exploit Memimpl.perm_free_inv; eauto. intros [[A B] | A]; auto.\n  subst b0. eelim Memimpl.perm_free_2. eexact H0. eauto. eauto. \n- (* contents *)\n  rewrite (Memimpl.free_result _ _ _ _ _ H0).\n  rewrite (Memimpl.free_result _ _ _ _ _ FREE). \n  simpl. eapply ma_memval; eauto. eapply Memimpl.perm_free_3; eauto.\n  apply H1; auto. destruct (eq_block b0 b); auto.\n  subst b0. right. red; intros. eelim Memimpl.perm_free_2. eexact H0. eauto. eauto. \n- (* nextblock *)\n  rewrite (Memimpl.free_result _ _ _ _ _ H0).\n  rewrite (Memimpl.free_result _ _ _ _ _ FREE).\n  simpl. eapply ma_nextblock; eauto.\nQed.\n\nGlobal Instance magree_ops: Deadcodeproof.MAgreeOps Memimpl.mem :=\n  {|\n    magree := magree\n  |}.\n\nGlobal Instance magree_prf: Deadcodeproof.MAgree Memimpl.mem.\nProof.\n  constructor.\n  exact ma_perm.\n  exact magree_monotone.\n  exact mextends_agree.\n  exact magree_extends.\n  exact magree_loadbytes.\n  exact magree_load.\n  exact magree_storebytes_parallel.\n  exact magree_store_parallel.\n  exact magree_storebytes_left.\n  exact magree_store_left.\n  exact magree_free.\nQed.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/compcert/backend/DeadcodeproofImpl.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.2060881313358935}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import FulfillStep.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import SimThread.\n\nSet Implicit Arguments.\n\n\nDefinition local_acquired (lc:Local.t) :=\n  (Local.mk (TView.read_fence_tview (Local.tview lc) Ordering.acqrel) (Local.promises lc)).\n\nLemma sim_local_promise_acquired\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt mem2_tgt\n      loc from to msg kind\n      (STEP_TGT: Local.promise_step lc1_tgt mem1_tgt loc from to msg lc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src (local_acquired lc1_tgt))\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src mem2_src,\n    <<STEP_SRC: Local.promise_step lc1_src mem1_src loc from to msg lc2_src mem2_src kind>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acquired lc2_tgt)>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit SimPromises.promise_bot; eauto.\n  { apply WF1_SRC. }\n  { apply WF1_TGT. }\n  i. des.\n  exploit Memory.promise_future; try apply PROMISE_SRC; try apply WF1_SRC; eauto.\n  { destruct msg; ss. inv CLOSED. econs.\n    eapply sim_memory_closed_opt_view; eauto. }\n  i. des.\n  esplits; eauto.\n  - econs; eauto.\n    destruct msg; ss. inv CLOSED. econs.\n    eapply sim_memory_closed_opt_view; eauto.\n  - econs; eauto.\nQed.\n\nLemma sim_local_fulfill_acquired\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      loc from to val releasedm_src releasedm_tgt released ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF: View.opt_wf releasedm_src)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT: Time.le (View.rlx (View.unwrap releasedm_tgt) loc) from)\n      (WF_RELM_TGT: View.opt_wf releasedm_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (ORD_TGT: Ordering.le ord_tgt Ordering.strong_relaxed)\n      (STEP_TGT: fulfill_step lc1_tgt sc1_tgt loc from to val releasedm_tgt released ord_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_local SimPromises.bot lc1_src (local_acquired lc1_tgt))\n      (ACQUIRED1: View.le (TView.cur (Local.tview lc1_src))\n                          (View.join (TView.cur (Local.tview lc1_tgt)) (View.unwrap releasedm_tgt)))\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: fulfill_step lc1_src sc1_src loc from to val releasedm_src released ord_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acquired lc2_tgt)>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  inv STEP_TGT.\n  assert (RELT_LE:\n   View.opt_le\n     (TView.write_released (Local.tview lc1_src) sc1_src loc to releasedm_src ord_src)\n     (TView.write_released (Local.tview lc1_tgt) sc2_tgt loc to releasedm_tgt ord_tgt)).\n  { unfold TView.write_released, TView.write_tview. ss. viewtac.\n    repeat (condtac; aggrtac;\n            try match goal with\n                | [|- View.opt_le _ _] => econs\n                end);\n      try apply WF1_TGT.\n    - etrans; eauto. aggrtac.\n    - etrans; [apply WF1_SRC|]. etrans; eauto. aggrtac.\n    - etrans; [apply LOCAL1|]. aggrtac.\n  }\n  assert (RELT_WF:\n   View.opt_wf (TView.write_released (Local.tview lc1_src) sc1_src loc to releasedm_src ord_src)).\n  { unfold TView.write_released. condtac; econs.\n    repeat (try condtac; viewtac; try apply WF1_SRC).\n  }\n  exploit SimPromises.remove_bot; try exact REMOVE;\n    try exact MEM1; try apply LOCAL1; eauto.\n  i. des. esplits.\n  - econs; eauto.\n    inv WRITABLE. econs.\n    eapply TimeFacts.le_lt_lt; [apply ACQUIRED1|]. viewtac.\n    eapply TimeFacts.le_lt_lt; eauto.\n  - econs; eauto. s. unfold TView.write_tview, TView.read_fence_tview. ss.\n    econs; ss; repeat (try condtac; aggrtac).\n    all: try by destruct ord_src, ord_tgt.\n    all: try by apply WF1_TGT.\n    + etrans; [apply LOCAL1|]. aggrtac.\n    + etrans; [apply LOCAL1|]. aggrtac.\n    + etrans; [apply WF1_SRC|]. etrans; [apply LOCAL1|]. aggrtac.\n    + etrans; [apply LOCAL1|]. aggrtac.\n  - ss.\nQed.\n\nLemma sim_local_write_acquired\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt mem2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt kind\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_SRC_WF: View.opt_wf releasedm_src)\n      (RELM_SRC_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT_WF: View.opt_wf releasedm_tgt)\n      (RELM_TGT_CLOSED: Memory.closed_opt_view releasedm_tgt mem1_tgt)\n      (RELM_TGT: Time.le (View.rlx (View.unwrap releasedm_tgt) loc) from)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (ORD_TGT: Ordering.le ord_tgt Ordering.strong_relaxed)\n      (STEP_TGT: Local.write_step lc1_tgt sc1_tgt mem1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt sc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src (local_acquired lc1_tgt))\n      (ACQUIRED1: View.le (TView.cur (Local.tview lc1_src))\n                          (View.join (TView.cur (Local.tview lc1_tgt)) (View.unwrap releasedm_tgt)))\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists released_src lc2_src sc2_src mem2_src,\n    <<STEP_SRC: Local.write_step lc1_src sc1_src mem1_src loc from to val releasedm_src released_src ord_src lc2_src sc2_src mem2_src kind>> /\\\n    <<REL2: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acquired lc2_tgt)>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit sim_local_promise_acquired; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  hexploit sim_local_fulfill_acquired; try apply STEP2;\n    try apply LOCAL2; try apply MEM2; eauto.\n  { eapply Memory.future_closed_opt_view; eauto. }\n  { inv STEP_SRC. inv STEP1. ss. }\n  i. des.\n  exploit promise_fulfill_write_sim_memory; try exact STEP_SRC; try exact STEP_SRC0; eauto.\n  { i. hexploit ORD0; eauto.\n    i. des. splits; auto. eapply sim_local_nonsynch_loc; eauto.\n  }\n  i. des. esplits; eauto. etrans; eauto.\nQed.\n\nLemma sim_local_read_acquired\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt\n      loc ts val released_tgt\n      (STEP_TGT: Local.read_step lc1_tgt mem1_tgt loc ts val released_tgt Ordering.relaxed lc2_tgt)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists released_src lc2_src,\n    <<REL: View.opt_le released_src released_tgt>> /\\\n    <<STEP_SRC: Local.read_step lc1_src mem1_src loc ts val released_src Ordering.acqrel lc2_src>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acquired lc2_tgt)>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit sim_memory_get; try apply GET; try apply MEM1. i. des. inv MSG.\n  esplits; eauto.\n  - econs; eauto; try by (etrans; eauto). inv READABLE. econs; ss; i.\n    + rewrite <- PLN. apply TVIEW.\n    + rewrite <- RLX; ss. apply TVIEW.\n  - econs; eauto. s.\n    unfold TView.read_tview, TView.read_fence_tview. ss.\n    econs; repeat (condtac; aggrtac).\n    all: try by apply TVIEW.\n    all: try by apply WF1_TGT.\n    + rewrite <- ? View.join_l. etrans; [apply TVIEW|]. apply WF1_TGT.\n    + inv MEM1_TGT. exploit CLOSED; eauto. i. des.\n      apply View.unwrap_opt_wf. inv MSG_WF. ss.\n    + rewrite <- ? View.join_l. apply TVIEW.\n    + inv MEM1_TGT. exploit CLOSED; eauto. i. des.\n      apply View.unwrap_opt_wf. inv MSG_WF. ss.\nQed.\n\nLemma sim_local_is_racy_acquired\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      loc to\n      (STEP_TGT: Local.is_racy lc1_tgt mem1_tgt loc to Ordering.relaxed)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  <<STEP_SRC: Local.is_racy lc1_src mem1_src loc to Ordering.acqrel>>.\nProof.\n  exploit sim_local_is_racy; try exact STEP_TGT;\n    try exact LOCAL1; try exact MEM1; try refl; eauto. i. des.\n  inv x0. econs; eauto.\nQed.\n\nLemma sim_local_racy_read_acquired\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      loc to val\n      (STEP_TGT: Local.racy_read_step lc1_tgt mem1_tgt loc to val Ordering.relaxed)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  <<STEP_SRC: Local.racy_read_step lc1_src mem1_src loc to val Ordering.acqrel>>.\nProof.\n  inv STEP_TGT.\n  exploit sim_local_is_racy_acquired; eauto.\nQed.\n\nLemma sim_local_racy_update_acquired\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      loc to ow\n      (STEP_TGT: Local.racy_update_step lc1_tgt mem1_tgt loc to Ordering.relaxed ow)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  <<STEP_SRC: Local.racy_update_step lc1_src mem1_src loc to Ordering.acqrel ow>>.\nProof.\n  exploit sim_local_racy_update; try exact STEP_TGT;\n    try exact LOCAL1; try exact MEM1; try refl; eauto. i. des.\n  inv x0.\n  - econs 1; eauto.\n  - econs 2; eauto.\n  - econs 3; eauto.\n    inv RACE. econs; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/transformation/SplitAcqCommon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.36658972248186006, "lm_q1q2_score": 0.20608812744554786}}
{"text": "From Coq.QArith Require Import Qcanon.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import view updates dfrac.\nFrom iris.algebra Require Export gmap dfrac.\nFrom iris.algebra Require Import local_updates proofmode_classes.\nFrom iris.base_logic Require Import base_logic.\nFrom iris Require Import options.\n\n(** * CMRA for a \"view of a gmap\".\n\nThe authoritative element [gmap_view_auth] is any [gmap K V].  The fragments\n[gmap_view_frag] represent ownership of a single key in that map.  Ownership is\ngoverned by a discardable fraction, which provides the possibiltiy to obtain\npersistent read-only ownership of a key.\n\nThe key frame-preserving updates are [gmap_view_alloc] to allocate a new key,\n[gmap_view_update] to update a key given full ownership of the corresponding\nfragment, and [gmap_view_freeze] to make a key read-only by discarding any\nfraction of the corresponding fragment. Crucially, the latter does not require\nowning the authoritative element.\n\nNOTE: The API surface for [gmap_view] is experimental and subject to change.  We\nplan to add notations for authoritative elements and fragments, and hope to\nsupport arbitrary maps as fragments. *)\n\nLocal Definition gmap_view_fragUR (K : Type) `{Countable K} (V : ofeT) : ucmraT :=\n  gmapUR K (prodR dfracR (agreeR V)).\n\n(** View relation. *)\nSection rel.\n  Context (K : Type) `{Countable K} (V : ofeT).\n  Implicit Types (m : gmap K V) (k : K) (v : V) (n : nat) (f : gmap_view_fragUR K V).\n\n  Local Definition gmap_view_rel_raw n m f : Prop :=\n    map_Forall (λ k dv, ∃ v, dv.2 ≡{n}≡ to_agree v ∧ ✓ dv.1 ∧ m !! k = Some v) f.\n\n  Local Lemma gmap_view_rel_raw_mono n1 n2 m1 m2 f1 f2 :\n    gmap_view_rel_raw n1 m1 f1 →\n    m1 ≡{n2}≡ m2 →\n    f2 ≼{n2} f1 →\n    n2 ≤ n1 →\n    gmap_view_rel_raw n2 m2 f2.\n  Proof.\n    intros Hrel Hm Hf Hn k [q va] Hk.\n    (* For some reason applying the lemma in [Hf] does not work... *)\n    destruct (lookup_includedN n2 f2 f1) as [Hf' _]. specialize (Hf' Hf). clear Hf.\n    specialize (Hf' k). rewrite Hk in Hf'.\n    apply option_includedN in Hf'.\n    destruct Hf' as [[=]|(? & [q' va'] & [= <-] & Hf1 & Hincl)].\n    specialize (Hrel _ _ Hf1) as (v & Hagree & Hdval & Hm1). simpl in *.\n    specialize (Hm k).\n    edestruct (dist_Some_inv_l _ _ _ _ Hm Hm1) as (v' & Hm2 & Hv).\n    exists v'. rewrite assoc. split; last done.\n    rewrite -Hv.\n    destruct Hincl as [[Heqq Heqva]|[Hinclq Hinclva]%pair_includedN].\n    - simpl in *. split.\n      + rewrite Heqva. eapply dist_le; last eassumption. done.\n      + rewrite <-discrete_iff in Heqq; last by apply _.\n        fold_leibniz. subst q'. done.\n    - split.\n      + etrans; last first.\n        { eapply dist_le; last eassumption. done. }\n        eapply agree_valid_includedN; last done.\n        eapply cmra_validN_le; last eassumption.\n        rewrite Hagree. done.\n      + rewrite <-cmra_discrete_included_iff in Hinclq.\n        eapply cmra_valid_included; done.\n  Qed.\n\n  Local Lemma gmap_view_rel_raw_valid n m f :\n    gmap_view_rel_raw n m f → ✓{n} f.\n  Proof.\n    intros Hrel k. destruct (f !! k) as [[q va]|] eqn:Hf; rewrite Hf; last done.\n    specialize (Hrel _ _ Hf) as (v & Hagree & Hdval & Hm1). simpl in *.\n    split; simpl.\n    - apply cmra_discrete_valid_iff. done.\n    - rewrite Hagree. done.\n  Qed.\n\n  Local Canonical Structure gmap_view_rel : view_rel (gmapO K V) (gmap_view_fragUR K V) :=\n    ViewRel gmap_view_rel_raw gmap_view_rel_raw_mono gmap_view_rel_raw_valid.\n\n  Local Lemma gmap_view_rel_discrete :\n    OfeDiscrete V → ViewRelDiscrete gmap_view_rel.\n  Proof.\n    intros ? n m f Hrel k [df va] Hk.\n    destruct (Hrel _ _ Hk) as (v & Hagree & Hdval & Hm).\n    exists v. split; last by auto.\n    eapply discrete_iff; first by apply _.\n    eapply discrete_iff; first by apply _.\n    done.\n  Qed.\nEnd rel.\n\nLocal Existing Instance gmap_view_rel_discrete.\n\nDefinition gmap_viewUR (K : Type) `{Countable K} (V : ofeT) : ucmraT :=\n  viewUR (gmap_view_rel K V).\nDefinition gmap_viewR (K : Type) `{Countable K} (V : ofeT) : cmraT :=\n  viewR (gmap_view_rel K V).\nDefinition gmap_viewO (K : Type) `{Countable K} (V : ofeT) : ofeT :=\n  viewO (gmap_view_rel K V).\n\nSection definitions.\n  Context {K : Type} `{Countable K} {V : ofeT}.\n\n  Definition gmap_view_auth (m : gmap K V) : gmap_viewR K V :=\n    ●V m.\n  Definition gmap_view_frag (k : K) (dq : dfrac) (v : V) : gmap_viewR K V :=\n    ◯V {[k := (dq, to_agree v)]}.\nEnd definitions.\n\nSection lemmas.\n  Context {K : Type} `{Countable K} {V : ofeT}.\n  Implicit Types (m : gmap K V) (k : K) (q : Qp) (dq : dfrac) (v : V).\n\n  Global Instance : Params (@gmap_view_auth) 4 := {}.\n  Global Instance gmap_view_auth_ne : NonExpansive (gmap_view_auth (K:=K) (V:=V)).\n  Proof. solve_proper. Qed.\n  Global Instance gmap_view_auth_proper : Proper ((≡) ==> (≡)) (gmap_view_auth (K:=K) (V:=V)).\n  Proof. apply ne_proper, _. Qed.\n\n  Global Instance : Params (@gmap_view_frag) 6 := {}.\n  Global Instance gmap_view_frag_ne k oq : NonExpansive (gmap_view_frag (V:=V) k oq).\n  Proof. solve_proper. Qed.\n  Global Instance gmap_view_frag_proper k oq : Proper ((≡) ==> (≡)) (gmap_view_frag (V:=V) k oq).\n  Proof. apply ne_proper, _. Qed.\n\n  (* Helper lemmas *)\n  Local Lemma gmap_view_rel_lookup n m k dq v :\n    gmap_view_rel K V n m {[k := (dq, to_agree v)]} ↔ ✓ dq ∧ m !! k ≡{n}≡ Some v.\n  Proof.\n    split.\n    - intros Hrel.\n      edestruct (Hrel k) as (v' & Hagree & Hval & ->).\n      { rewrite lookup_singleton. done. }\n      simpl in *. apply (inj _) in Hagree. rewrite Hagree.\n      done.\n    - intros [Hval (v' & Hm & Hv')%dist_Some_inv_r'] j [df va].\n      destruct (decide (k = j)) as [<-|Hne]; last by rewrite lookup_singleton_ne.\n      rewrite lookup_singleton. intros [= <- <-]. simpl.\n      exists v'. split_and!; by rewrite ?Hv'.\n  Qed.\n\n  (** Composition and validity *)\n  Lemma gmap_view_auth_valid m : ✓ gmap_view_auth m.\n  Proof.\n    apply view_auth_valid. intros n l ? Hl. rewrite lookup_empty in Hl. done.\n  Qed.\n\n  Lemma gmap_view_frag_validN n k dq v : ✓{n} gmap_view_frag k dq v ↔ ✓ dq.\n  Proof.\n    rewrite view_frag_validN singleton_validN. split.\n    - intros [??]. done.\n    - intros ?. split; done.\n  Qed.\n  Lemma gmap_view_frag_valid k dq v : ✓ gmap_view_frag k dq v ↔ ✓ dq.\n  Proof.\n    rewrite view_frag_valid singleton_valid. split.\n    - intros [??]. done.\n    - intros ?. split; done.\n  Qed.\n\n  Lemma gmap_view_frag_op k dq1 dq2 v :\n    gmap_view_frag k (dq1 ⋅ dq2) v ≡ gmap_view_frag k dq1 v ⋅ gmap_view_frag k dq2 v.\n  Proof. rewrite -view_frag_op singleton_op -pair_op agree_idemp //. Qed.\n  Lemma gmap_view_frag_add k q1 q2 v :\n    gmap_view_frag k (DfracOwn (q1 + q2)) v ≡\n      gmap_view_frag k (DfracOwn q1) v ⋅ gmap_view_frag k (DfracOwn q2) v.\n  Proof. rewrite -gmap_view_frag_op. done. Qed.\n\n  Lemma gmap_view_frag_op_validN n k dq1 dq2 v1 v2 :\n    ✓{n} (gmap_view_frag k dq1 v1 ⋅ gmap_view_frag k dq2 v2) ↔\n      ✓ (dq1 ⋅ dq2) ∧ v1 ≡{n}≡ v2.\n  Proof.\n    rewrite view_frag_validN singleton_op singleton_validN -pair_op.\n    split; intros [Hfrac Hagree]; (split; first done); simpl in *.\n    - apply to_agree_op_invN. done.\n    - rewrite Hagree agree_idemp. done.\n  Qed.\n  Lemma gmap_view_frag_op_valid k dq1 dq2 v1 v2 :\n    ✓ (gmap_view_frag k dq1 v1 ⋅ gmap_view_frag k dq2 v2) ↔ ✓ (dq1 ⋅ dq2) ∧ v1 ≡ v2.\n  Proof.\n    rewrite view_frag_valid singleton_op singleton_valid -pair_op.\n    split; intros [Hfrac Hagree]; (split; first done); simpl in *.\n    - apply to_agree_op_inv. done.\n    - rewrite Hagree agree_idemp. done.\n  Qed.\n  Lemma gmap_view_frag_op_valid_L `{!LeibnizEquiv V} k dq1 dq2 v1 v2 :\n    ✓ (gmap_view_frag k dq1 v1 ⋅ gmap_view_frag k dq2 v2) ↔ ✓ (dq1 ⋅ dq2) ∧ v1 = v2.\n  Proof. unfold_leibniz. apply gmap_view_frag_op_valid. Qed.\n\n  Lemma gmap_view_both_validN n m k dq v :\n    ✓{n} (gmap_view_auth m ⋅ gmap_view_frag k dq v) ↔\n      ✓ dq ∧ m !! k ≡{n}≡ Some v.\n  Proof.\n    rewrite /gmap_view_auth /gmap_view_frag.\n    rewrite view_both_validN.\n    apply gmap_view_rel_lookup.\n  Qed.\n  Lemma gmap_view_both_valid m k dq v :\n    ✓ (gmap_view_auth m ⋅ gmap_view_frag k dq v) ↔\n    ✓ dq ∧ m !! k ≡ Some v.\n  Proof.\n    rewrite /gmap_view_auth /gmap_view_frag.\n    rewrite view_both_valid. setoid_rewrite gmap_view_rel_lookup.\n    split; intros Hm; split.\n    - apply (Hm 0%nat).\n    - apply equiv_dist=>n. apply Hm.\n    - apply Hm.\n    - revert n. apply equiv_dist. apply Hm.\n  Qed.\n  Lemma gmap_view_both_valid_L `{!LeibnizEquiv V} m k dq v :\n    ✓ (gmap_view_auth m ⋅ gmap_view_frag k dq v) ↔\n    ✓ dq ∧ m !! k = Some v.\n  Proof. unfold_leibniz. apply gmap_view_both_valid. Qed.\n\n  (** Frame-preserving updates *)\n  Lemma gmap_view_alloc m k dq v :\n    m !! k = None →\n    ✓ dq →\n    gmap_view_auth m ~~> gmap_view_auth (<[k := v]> m) ⋅ gmap_view_frag k dq v.\n  Proof.\n    intros Hfresh Hdq. apply view_update_alloc=>n bf Hrel j [df va] /=.\n    rewrite lookup_op. destruct (decide (j = k)) as [->|Hne].\n    - assert (bf !! k = None) as Hbf.\n      { destruct (bf !! k) as [[df' va']|] eqn:Hbf; last done.\n        specialize (Hrel _ _ Hbf). destruct Hrel as (v' & _ & _ & Hm).\n        exfalso. rewrite Hm in Hfresh. done. }\n      rewrite lookup_singleton Hbf right_id.\n      intros [= <- <-]. eexists. do 2 (split; first done).\n      rewrite lookup_insert. done.\n    - rewrite lookup_singleton_ne; last done.\n      rewrite left_id=>Hbf.\n      specialize (Hrel _ _ Hbf). destruct Hrel as (v' & ? & ? & Hm).\n      eexists. do 2 (split; first done).\n      rewrite lookup_insert_ne //.\n  Qed.\n\n  Lemma gmap_view_delete m k v :\n    gmap_view_auth m ⋅ gmap_view_frag k (DfracOwn 1) v ~~>\n    gmap_view_auth (delete k m).\n  Proof.\n    apply view_update_dealloc=>n bf Hrel j [df va] Hbf /=.\n    destruct (decide (j = k)) as [->|Hne].\n    - edestruct (Hrel k) as (v' & _ & Hdf & _).\n      { rewrite lookup_op Hbf lookup_singleton -Some_op. done. }\n      exfalso. apply: dfrac_full_exclusive. apply Hdf.\n    - edestruct (Hrel j) as (v' & ? & ? & Hm).\n      { rewrite lookup_op lookup_singleton_ne // Hbf. done. }\n      exists v'. do 2 (split; first done).\n      rewrite lookup_delete_ne //.\n  Qed.\n\n  Lemma gmap_view_update m k v v' :\n    gmap_view_auth m ⋅ gmap_view_frag k (DfracOwn 1) v ~~>\n      gmap_view_auth (<[k := v']> m) ⋅ gmap_view_frag k (DfracOwn 1) v'.\n  Proof.\n    apply view_update=>n bf Hrel j [df va] /=.\n    rewrite lookup_op. destruct (decide (j = k)) as [->|Hne].\n    - assert (bf !! k = None) as Hbf.\n      { move: Hrel =>/view_rel_validN /(_ k).\n        rewrite lookup_op lookup_singleton.\n        destruct (bf !! k) as [[df' va']|] eqn:Hbf; last done.\n        rewrite Hbf. clear Hbf.\n        rewrite -Some_op -pair_op.\n        move=>[/= /dfrac_full_exclusive Hdf _]. done. }\n      rewrite Hbf right_id lookup_singleton. clear Hbf.\n      intros [= <- <-].\n      eexists. do 2 (split; first done).\n      rewrite lookup_insert. done.\n    - rewrite lookup_singleton_ne; last done.\n      rewrite left_id=>Hbf.\n      edestruct (Hrel j) as (v'' & ? & ? & Hm).\n      { rewrite lookup_op lookup_singleton_ne // left_id. done. }\n      simpl in *. eexists. do 2 (split; first done).\n      rewrite lookup_insert_ne //.\n  Qed.\n\n  Lemma gmap_view_persist k q v :\n    gmap_view_frag k (DfracOwn q) v ~~> gmap_view_frag k DfracDiscarded v.\n  Proof.\n    apply view_update_frag; last first.\n    { eapply singleton_update, prod_update; simpl; last done.\n      apply dfrac_discard_update. }\n    move=>m n bf Hrel j [df va] /=.\n    rewrite lookup_op. destruct (decide (j = k)) as [->|Hne].\n    - rewrite lookup_singleton.\n      edestruct (Hrel k ((DfracOwn q, to_agree v) ⋅? bf !! k)) as (v' & Hdf & Hva & Hm).\n      { rewrite lookup_op lookup_singleton.\n        destruct (bf !! k) eqn:Hbf; by rewrite Hbf. }\n      rewrite Some_op_opM. intros [= Hbf].\n      exists v'. rewrite assoc; split; last done.\n      destruct (bf !! k) as [[df' va']|] eqn:Hbfk; rewrite Hbfk in Hbf; clear Hbfk.\n      + simpl in *. rewrite -pair_op in Hbf.\n        move:Hbf=>[= <- <-]. split; first done.\n        eapply cmra_discrete_valid.\n        eapply (dfrac_discard_update _ _ (Some df')).\n        apply cmra_discrete_valid_iff. done.\n      + simpl in *. move:Hbf=>[= <- <-]. split; done.\n    - rewrite lookup_singleton_ne //.\n      rewrite left_id=>Hbf.\n      edestruct (Hrel j) as (v'' & ? & ? & Hm).\n      { rewrite lookup_op lookup_singleton_ne // left_id. done. }\n      simpl in *. eexists. do 2 (split; first done). done.\n  Qed.\n\n  (** Typeclass instances *)\n  Global Instance gmap_view_frag_core_id k v {dq} : CoreId dq → CoreId (gmap_view_frag k dq v).\n  Proof. apply _. Qed.\n\n  Global Instance gmap_view_cmra_discrete : OfeDiscrete V → CmraDiscrete (gmap_viewR K V).\n  Proof. apply _. Qed.\n\n  Global Instance gmap_view_frag_mut_is_op dq dq1 dq2 k v :\n    IsOp dq dq1 dq2 →\n    IsOp' (gmap_view_frag k dq v) (gmap_view_frag k dq1 v) (gmap_view_frag k dq2 v).\n  Proof. rewrite /IsOp' /IsOp => ->. apply gmap_view_frag_op. Qed.\n\n  (** Internalized properties *)\n  Lemma gmap_view_both_validI M m k dq v :\n    ✓ (gmap_view_auth m ⋅ gmap_view_frag k dq v) ⊢@{uPredI M}\n    ✓ dq ∧ m !! k ≡ Some v.\n  Proof.\n    rewrite /gmap_view_auth /gmap_view_frag. apply view_both_validI_1.\n    intros n a. uPred.unseal. apply gmap_view_rel_lookup.\n  Qed.\n\n  Lemma gmap_view_frag_op_validI M k dq1 dq2 v1 v2 :\n    ✓ (gmap_view_frag k dq1 v1 ⋅ gmap_view_frag k dq2 v2) ⊢@{uPredI M}\n      ✓ (dq1 ⋅ dq2) ∧ v1 ≡ v2.\n  Proof.\n    rewrite /gmap_view_frag -view_frag_op view_frag_validI.\n    rewrite singleton_op singleton_validI -pair_op uPred.prod_validI /=.\n    apply bi.and_mono; first done.\n    rewrite agree_validI agree_equivI. done.\n  Qed.\n\nEnd lemmas.\n\n(** Functor *)\nProgram Definition gmap_viewURF (K : Type) `{Countable K} (F : oFunctor) : urFunctor := {|\n  urFunctor_car A _ B _ := gmap_viewUR K (oFunctor_car F A B);\n  urFunctor_map A1 _ A2 _ B1 _ B2 _ fg :=\n    viewO_map (rel:=gmap_view_rel K (oFunctor_car F A1 B1))\n              (rel':=gmap_view_rel K (oFunctor_car F A2 B2))\n              (gmapO_map (K:=K) (oFunctor_map F fg))\n              (gmapO_map (K:=K) (prodO_map cid (agreeO_map (oFunctor_map F fg))))\n|}.\nNext Obligation.\n  intros K ?? F A1 ? A2 ? B1 ? B2 ? n f g Hfg.\n  apply viewO_map_ne.\n  - apply gmapO_map_ne, oFunctor_map_ne. done.\n  - apply gmapO_map_ne. apply prodO_map_ne; first done.\n    apply agreeO_map_ne, oFunctor_map_ne. done.\nQed.\nNext Obligation.\n  intros K ?? F A ? B ? x; simpl in *. rewrite -{2}(view_map_id x).\n  apply (view_map_ext _ _ _ _)=> y.\n  - rewrite /= -{2}(map_fmap_id y).\n    apply map_fmap_equiv_ext=>k ??.\n    apply oFunctor_map_id.\n  - rewrite /= -{2}(map_fmap_id y).\n    apply map_fmap_equiv_ext=>k [df va] ?.\n    split; first done. simpl.\n    rewrite -{2}(agree_map_id va).\n    eapply agree_map_ext; first by apply _.\n    apply oFunctor_map_id.\nQed.\nNext Obligation.\n  intros K ?? F A1 ? A2 ? A3 ? B1 ? B2 ? B3 ? f g f' g' x; simpl in *.\n  rewrite -view_map_compose.\n  apply (view_map_ext _ _ _ _)=> y.\n  - rewrite /= -map_fmap_compose.\n    apply map_fmap_equiv_ext=>k ??.\n    apply oFunctor_map_compose.\n  - rewrite /= -map_fmap_compose.\n    apply map_fmap_equiv_ext=>k [df va] ?.\n    split; first done. simpl.\n    rewrite -agree_map_compose.\n    eapply agree_map_ext; first by apply _.\n    apply oFunctor_map_compose.\nQed.\nNext Obligation.\n  intros K ?? F A1 ? A2 ? B1 ? B2 ? fg; simpl.\n  (* [apply] does not work, probably the usual unification probem (Coq #6294) *)\n  apply: view_map_cmra_morphism; [apply _..|]=> n m f.\n  intros Hrel k [df va] Hf. move: Hf.\n  rewrite !lookup_fmap.\n  destruct (f !! k) as [[df' va']|] eqn:Hfk; rewrite Hfk; last done.\n  simpl=>[= <- <-].\n  specialize (Hrel _ _ Hfk). simpl in Hrel. destruct Hrel as (v & Hagree & Hdval & Hm).\n  exists (oFunctor_map F fg v).\n  rewrite Hm. split; last by auto.\n  rewrite Hagree. rewrite agree_map_to_agree. done.\nQed.\n\nInstance gmap_viewURF_contractive (K : Type) `{Countable K} F :\n  oFunctorContractive F → urFunctorContractive (gmap_viewURF K F).\nProof.\n  intros ? A1 ? A2 ? B1 ? B2 ? n f g Hfg.\n  apply viewO_map_ne.\n  - apply gmapO_map_ne. apply oFunctor_map_contractive. done.\n  - apply gmapO_map_ne. apply prodO_map_ne; first done.\n    apply agreeO_map_ne, oFunctor_map_contractive. done.\nQed.\n\nProgram Definition gmap_viewRF (K : Type) `{Countable K} (F : oFunctor) : rFunctor := {|\n  rFunctor_car A _ B _ := gmap_viewR K (oFunctor_car F A B);\n  rFunctor_map A1 _ A2 _ B1 _ B2 _ fg :=\n    viewO_map (rel:=gmap_view_rel K (oFunctor_car F A1 B1))\n              (rel':=gmap_view_rel K (oFunctor_car F A2 B2))\n              (gmapO_map (K:=K) (oFunctor_map F fg))\n              (gmapO_map (K:=K) (prodO_map cid (agreeO_map (oFunctor_map F fg))))\n|}.\nSolve Obligations with apply gmap_viewURF.\n\nInstance gmap_viewRF_contractive (K : Type) `{Countable K} F :\n  oFunctorContractive F → rFunctorContractive (gmap_viewRF K F).\nProof. apply gmap_viewURF_contractive. Qed.\n\nTypeclasses Opaque gmap_view_auth gmap_view_frag.\n", "meta": {"author": "SkySkimmer", "repo": "iris", "sha": "186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5", "save_path": "github-repos/coq/SkySkimmer-iris", "path": "github-repos/coq/SkySkimmer-iris/iris-186d9ece07e210e92be28eb0e1a42f5d5fe6f1b5/theories/algebra/lib/gmap_view.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.20607367826327191}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.assert_lemmas.\nRequire Import VST.floyd.type_induction.\nRequire Import VST.floyd.jmeq_lemmas.\nRequire Export VST.floyd.fieldlist.\nRequire Export VST.floyd.compact_prod_sum.\nRequire Export VST.floyd.sublist.\n\nDefinition proj_struct (i : ident) (m : members) {A: ident * type -> Type} (v: compact_prod (map A m)) (d: A (i, field_type i m)): A (i, field_type i m) :=\n  proj_compact_prod (i, field_type i m) m v d member_dec.\n\nDefinition proj_union (i : ident) (m : members) {A: ident * type -> Type} (v: compact_sum (map A m)) (d: A (i, field_type i m)): A (i, field_type i m) :=\n  proj_compact_sum (i, field_type i m) m v d member_dec.\n\nDefinition members_union_inj {m: members} {A} (v: compact_sum (map A m)) (it: ident * type): Prop :=\n  compact_sum_inj v it member_dec.\n\nDefinition upd_sublist {X: Type} (lo hi: Z) (l: list X) (l0: list X) : list X :=\n  firstn (Z.to_nat lo) l ++ l0 ++ skipn (Z.to_nat hi) l.\n\n(* TODO: We should use the following two definition in replace_refill lemmas in the future. And avoid using compact prod/sum directly. *)\n\nDefinition upd_struct (i : ident) (m : members) {A: ident * type -> Type} (v: compact_prod (map A m)) (v0: A (i, field_type i m)): compact_prod (map A m) :=\n  upd_compact_prod _ v (i, field_type i m) v0 member_dec.\n\nDefinition upd_union (i : ident) (m : members) {A: ident * type -> Type} (v: compact_sum (map A m)) (v0: A (i, field_type i m)): compact_sum (map A m) :=\n  upd_compact_sum _ v (i, field_type i m) v0 member_dec.\n\nLemma proj_struct_JMeq: forall (i: ident) (m : members) {A1 A2: ident * type -> Type} (v1: compact_prod (map A1 m)) (v2: compact_prod (map A2 m)) (d1: A1 (i, field_type i m)) (d2: A2 (i, field_type i m)),\n  (forall i, in_members i m -> @eq Type (A1 (i, field_type i m)) (A2 (i, field_type i m))) ->\n  members_no_replicate m = true ->\n  in_members i m ->\n  JMeq v1 v2 ->\n  JMeq (proj_struct i m v1 d1) (proj_struct i m v2 d2).\nProof.\n  intros.\n  apply proj_compact_prod_JMeq; auto.\n  + clear - H H0.\n    intros.\n    pose proof In_field_type _ _ H0 H1.\n    destruct i as [i t].\n    simpl fst in H2; simpl snd in H2.\n    rewrite <- H2.\n    apply H; auto.\n    apply List.in_map with (f := fst) in H1.\n    auto.\n  + apply in_members_field_type; auto.\nQed.\n\nLemma members_union_inj_JMeq: forall (m : members) {A1 A2: ident * type -> Type} (v1: compact_sum (map A1 m)) (v2: compact_sum (map A2 m)),\n  (forall i, in_members i m -> @eq Type (A1 (i, field_type i m)) (A2 (i, field_type i m))) ->\n  members_no_replicate m = true ->\n  JMeq v1 v2 ->\n  (forall it, members_union_inj v1 it <-> members_union_inj v2 it).\nProof.\n  intros.\n  apply compact_sum_inj_JMeq; auto.\n  intros [? ?] ?.\n  specialize (H i).\n  spec H.\n  + change i with (fst (i, t)).\n    apply in_map.\n    auto.\n  + apply In_field_type in H2; auto.\n    simpl snd in H2.\n    rewrite <- H2; simpl fst.\n    auto.\nQed.\n\nLemma proj_union_JMeq: forall (i: ident) (m : members) {A1 A2: ident * type -> Type} (v1: compact_sum (map A1 m)) (v2: compact_sum (map A2 m)) (d1: A1 (i, field_type i m)) (d2: A2 (i, field_type i m)),\n  (forall i, in_members i m -> @eq Type (A1 (i, field_type i m)) (A2 (i, field_type i m))) ->\n  members_no_replicate m = true ->\n  members_union_inj v1 (i, field_type i m) ->\n  JMeq v1 v2 ->\n  JMeq (proj_union i m v1 d1) (proj_union i m v2 d2).\nProof.\n  intros.\n  apply proj_compact_sum_JMeq; auto.\n  + clear - H H0.\n    intros.\n    pose proof In_field_type _ _ H0 H1.\n    destruct i as [i t].\n    simpl fst in H2; simpl snd in H2.\n    rewrite <- H2.\n    apply H; auto.\n    apply List.in_map with (f := fst) in H1.\n    auto.\nQed.\n\n\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/floyd/aggregate_type.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.2060736703064}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Operators and addressing modes.  The abstract syntax and dynamic\n  semantics for the CminorSel, RTL, LTL and Mach languages depend on the\n  following types, defined in this library:\n- [condition]:  boolean conditions for conditional branches;\n- [operation]: arithmetic and logical operations;\n- [addressing]: addressing modes for load and store operations.\n\n  These types are PowerPC-specific and correspond roughly to what the \n  processor can compute in one instruction.  In other terms, these\n  types reflect the state of the program after instruction selection.\n  For a processor-independent set of operations, see the abstract\n  syntax and dynamic semantics of the Cminor language.\n*)\n\nRequire Import Coqlib.\nRequire Import AST.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memdata.\nRequire Import Memory.\nRequire Import Globalenvs.\nRequire Import Events.\n\nSet Implicit Arguments.\n\n(** Conditions (boolean-valued operators). *)\n\nInductive condition : Type :=\n  | Ccomp: comparison -> condition      (**r signed integer comparison *)\n  | Ccompu: comparison -> condition     (**r unsigned integer comparison *)\n  | Ccompimm: comparison -> int -> condition (**r signed integer comparison with a constant *)\n  | Ccompuimm: comparison -> int -> condition  (**r unsigned integer comparison with a constant *)\n  | Ccompf: comparison -> condition     (**r floating-point comparison *)\n  | Cnotcompf: comparison -> condition  (**r negation of a floating-point comparison *)\n  | Cmaskzero: int -> condition         (**r test [(arg & constant) == 0] *)\n  | Cmasknotzero: int -> condition.     (**r test [(arg & constant) != 0] *)\n\n(** Arithmetic and logical operations.  In the descriptions, [rd] is the\n  result of the operation and [r1], [r2], etc, are the arguments. *)\n\nInductive operation : Type :=\n  | Omove: operation                    (**r [rd = r1] *)\n  | Ointconst: int -> operation         (**r [rd] is set to the given integer constant *)\n  | Ofloatconst: float -> operation     (**r [rd] is set to the given float constant *)\n  | Oaddrsymbol: ident -> int -> operation (**r [rd] is set to the the address of the symbol plus the offset *)\n  | Oaddrstack: int -> operation        (**r [rd] is set to the stack pointer plus the given offset *)\n(*c Integer arithmetic: *)\n  | Ocast8signed: operation             (**r [rd] is 8-bit sign extension of [r1] *)\n  | Ocast16signed: operation            (**r [rd] is 16-bit sign extension of [r1] *)\n  | Oadd: operation                     (**r [rd = r1 + r2] *)\n  | Oaddimm: int -> operation           (**r [rd = r1 + n] *)\n  | Osub: operation                     (**r [rd = r1 - r2] *)\n  | Osubimm: int -> operation           (**r [rd = n - r1] *)\n  | Omul: operation                     (**r [rd = r1 * r2] *)\n  | Omulimm: int -> operation           (**r [rd = r1 * n] *)\n  | Odiv: operation                     (**r [rd = r1 / r2] (signed) *)\n  | Odivu: operation                    (**r [rd = r1 / r2] (unsigned) *)\n  | Oand: operation                     (**r [rd = r1 & r2] *)\n  | Oandimm: int -> operation           (**r [rd = r1 & n] *)\n  | Oor: operation                      (**r [rd = r1 | r2] *)\n  | Oorimm: int -> operation            (**r [rd = r1 | n] *)\n  | Oxor: operation                     (**r [rd = r1 ^ r2] *)\n  | Oxorimm: int -> operation           (**r [rd = r1 ^ n] *)\n  | Onot: operation                     (**r [rd = ~r1] *)\n  | Onand: operation                    (**r [rd = ~(r1 & r2)] *)\n  | Onor: operation                     (**r [rd = ~(r1 | r2)] *)\n  | Onxor: operation                    (**r [rd = ~(r1 ^ r2)] *)\n  | Oandc: operation                    (**r [rd = r1 & ~r2] *)\n  | Oorc: operation                     (**r [rd = r1 | ~r2] *)\n  | Oshl: operation                     (**r [rd = r1 << r2] *)\n  | Oshr: operation                     (**r [rd = r1 >> r2] (signed) *)\n  | Oshrimm: int -> operation           (**r [rd = r1 >> n] (signed) *)\n  | Oshrximm: int -> operation          (**r [rd = r1 / 2^n] (signed) *)\n  | Oshru: operation                    (**r [rd = r1 >> r2] (unsigned) *)\n  | Orolm: int -> int -> operation      (**r rotate left and mask *)\n  | Oroli: int -> int -> operation      (**r rotate left and insert *)\n(*c Floating-point arithmetic: *)\n  | Onegf: operation                    (**r [rd = - r1] *)\n  | Oabsf: operation                    (**r [rd = abs(r1)] *)\n  | Oaddf: operation                    (**r [rd = r1 + r2] *)\n  | Osubf: operation                    (**r [rd = r1 - r2] *)\n  | Omulf: operation                    (**r [rd = r1 * r2] *)\n  | Odivf: operation                    (**r [rd = r1 / r2] *)\n  | Osingleoffloat: operation           (**r [rd] is [r1] truncated to single-precision float *)\n(*c Conversions between int and float: *)\n  | Ointoffloat: operation              (**r [rd = signed_int_of_float(r1)] *)\n  | Ofloatofwords: operation            (**r [rd = float_of_words(r1,r2)] *)\n(*c Boolean tests: *)\n  | Ocmp: condition -> operation.       (**r [rd = 1] if condition holds, [rd = 0] otherwise. *)\n\n(** Addressing modes.  [r1], [r2], etc, are the arguments to the \n  addressing. *)\n\nInductive addressing: Type :=\n  | Aindexed: int -> addressing         (**r Address is [r1 + offset] *)\n  | Aindexed2: addressing               (**r Address is [r1 + r2] *)\n  | Aglobal: ident -> int -> addressing (**r Address is [symbol + offset] *)\n  | Abased: ident -> int -> addressing (**r Address is [symbol + offset + r1] *)\n  | Ainstack: int -> addressing.        (**r Address is [stack_pointer + offset] *)\n\n(** Comparison functions (used in module [CSE]). *)\n\nDefinition eq_operation (x y: operation): {x=y} + {x<>y}.\nProof.\n  generalize Int.eq_dec; intro.\n  generalize Float.eq_dec; intro.\n  assert (forall (x y: ident), {x=y}+{x<>y}). exact peq.\n  assert (forall (x y: comparison), {x=y}+{x<>y}). decide equality.\n  assert (forall (x y: condition), {x=y}+{x<>y}). decide equality.\n  decide equality.\nQed.\n\nDefinition eq_addressing (x y: addressing) : {x=y} + {x<>y}.\nProof.\n  generalize Int.eq_dec; intro.\n  assert (forall (x y: ident), {x=y}+{x<>y}). exact peq.\n  decide equality.\nQed.\n\n(** * Evaluation functions *)\n\nDefinition symbol_address (F V: Type) (genv: Genv.t F V) (id: ident) (ofs: int) : val :=\n  match Genv.find_symbol genv id with\n  | Some b => Vptr b ofs\n  | None => Vundef\n  end.\n\n(** Evaluation of conditions, operators and addressing modes applied\n  to lists of values.  Return [None] when the computation can trigger an\n  error, e.g. integer division by zero.  [eval_condition] returns a boolean,\n  [eval_operation] and [eval_addressing] return a value. *)\n\nDefinition eval_condition (cond: condition) (vl: list val) (m: mem): option bool :=\n  match cond, vl with\n  | Ccomp c, v1 :: v2 :: nil => Val.cmp_bool c v1 v2\n  | Ccompu c, v1 :: v2 :: nil => Val.cmpu_bool (Mem.valid_pointer m) c v1 v2\n  | Ccompimm c n, v1 :: nil => Val.cmp_bool c v1 (Vint n)\n  | Ccompuimm c n, v1 :: nil => Val.cmpu_bool (Mem.valid_pointer m) c v1 (Vint n)\n  | Ccompf c, v1 :: v2 :: nil => Val.cmpf_bool c v1 v2\n  | Cnotcompf c, v1 :: v2 :: nil => option_map negb (Val.cmpf_bool c v1 v2)\n  | Cmaskzero n, Vint n1 :: nil => Some (Int.eq (Int.and n1 n) Int.zero)\n  | Cmasknotzero n, Vint n1 :: nil => Some (negb (Int.eq (Int.and n1 n) Int.zero))\n  | _, _ => None\n  end.\n\nDefinition eval_operation\n             (F V: Type) (genv: Genv.t F V) (sp: val)\n             (op: operation) (vl: list val) (m: mem): option val :=\n  match op, vl with\n  | Omove, v1::nil => Some v1\n  | Ointconst n, nil => Some (Vint n)\n  | Ofloatconst n, nil => Some (Vfloat n)\n  | Oaddrsymbol s ofs, nil => Some (symbol_address genv s ofs) \n  | Oaddrstack ofs, nil => Some (Val.add sp (Vint ofs))\n  | Ocast8signed, v1::nil => Some (Val.sign_ext 8 v1)\n  | Ocast16signed, v1::nil => Some (Val.sign_ext 16 v1)\n  | Oadd, v1::v2::nil => Some (Val.add v1 v2)\n  | Oaddimm n, v1::nil => Some (Val.add v1 (Vint n))\n  | Osub, v1::v2::nil => Some (Val.sub v1 v2)\n  | Osubimm n, v1::nil => Some (Val.sub (Vint n) v1)\n  | Omul, v1::v2::nil => Some (Val.mul v1 v2)\n  | Omulimm n, v1::nil => Some (Val.mul v1 (Vint n))\n  | Odiv, v1::v2::nil => Val.divs v1 v2\n  | Odivu, v1::v2::nil => Val.divu v1 v2\n  | Oand, v1::v2::nil => Some(Val.and v1 v2)\n  | Oandimm n, v1::nil => Some (Val.and v1 (Vint n))\n  | Oor, v1::v2::nil => Some(Val.or v1 v2)\n  | Oorimm n, v1::nil => Some (Val.or v1 (Vint n))\n  | Oxor, v1::v2::nil => Some(Val.xor v1 v2)\n  | Oxorimm n, v1::nil => Some (Val.xor v1 (Vint n))\n  | Onot, v1::nil => Some(Val.notint v1)\n  | Onand, v1::v2::nil => Some (Val.notint (Val.and v1 v2))\n  | Onor, v1::v2::nil => Some (Val.notint (Val.or v1 v2))\n  | Onxor, v1::v2::nil => Some (Val.notint (Val.xor v1 v2))\n  | Oandc, v1::v2::nil => Some (Val.and v1 (Val.notint v2))\n  | Oorc, v1::v2::nil => Some (Val.or v1 (Val.notint v2))\n  | Oshl, v1::v2::nil => Some (Val.shl v1 v2)\n  | Oshr, v1::v2::nil => Some (Val.shr v1 v2)\n  | Oshrimm n, v1::nil => Some (Val.shr v1 (Vint n))\n  | Oshrximm n, v1::nil => Val.shrx v1 (Vint n)\n  | Oshru, v1::v2::nil => Some (Val.shru v1 v2)\n  | Orolm amount mask, v1::nil => Some (Val.rolm v1 amount mask)\n  | Oroli amount mask, v1::v2::nil =>\n      Some(Val.or (Val.and v1 (Vint (Int.not mask))) (Val.rolm v2 amount mask))\n  | Onegf, v1::nil => Some(Val.negf v1)\n  | Oabsf, v1::nil => Some(Val.absf v1)\n  | Oaddf, v1::v2::nil => Some(Val.addf v1 v2)\n  | Osubf, v1::v2::nil => Some(Val.subf v1 v2)\n  | Omulf, v1::v2::nil => Some(Val.mulf v1 v2)\n  | Odivf, v1::v2::nil => Some(Val.divf v1 v2)\n  | Osingleoffloat, v1::nil => Some(Val.singleoffloat v1)\n  | Ointoffloat, v1::nil => Val.intoffloat v1\n  | Ofloatofwords, v1::v2::nil => Some(Val.floatofwords v1 v2)\n  | Ocmp c, _ => Some(Val.of_optbool (eval_condition c vl m))\n  | _, _ => None\n  end.\n\nDefinition eval_addressing\n    (F V: Type) (genv: Genv.t F V) (sp: val)\n    (addr: addressing) (vl: list val) : option val :=\n  match addr, vl with\n  | Aindexed n, v1::nil => Some (Val.add v1 (Vint n))\n  | Aindexed2, v1::v2::nil => Some (Val.add v1 v2)\n  | Aglobal s ofs, nil => Some (symbol_address genv s ofs)\n  | Abased s ofs, v1::nil => Some (Val.add (symbol_address genv s ofs) v1)\n  | Ainstack ofs, nil => Some(Val.add sp (Vint ofs))\n  | _, _ => None\n  end.\n\nLtac FuncInv :=\n  match goal with\n  | H: (match ?x with nil => _ | _ :: _ => _ end = Some _) |- _ =>\n      destruct x; simpl in H; try discriminate; FuncInv\n  | H: (match ?v with Vundef => _ | Vint _ => _ | Vfloat _ => _ | Vptr _ _ => _ end = Some _) |- _ =>\n      destruct v; simpl in H; try discriminate; FuncInv\n  | H: (Some _ = Some _) |- _ =>\n      injection H; intros; clear H; FuncInv\n  | _ =>\n      idtac\n  end.\n\n(** * Static typing of conditions, operators and addressing modes. *)\n\nDefinition type_of_condition (c: condition) : list typ :=\n  match c with\n  | Ccomp _ => Tint :: Tint :: nil\n  | Ccompu _ => Tint :: Tint :: nil\n  | Ccompimm _ _ => Tint :: nil\n  | Ccompuimm _ _ => Tint :: nil\n  | Ccompf _ => Tfloat :: Tfloat :: nil\n  | Cnotcompf _ => Tfloat :: Tfloat :: nil\n  | Cmaskzero _ => Tint :: nil\n  | Cmasknotzero _ => Tint :: nil\n  end.\n\nDefinition type_of_operation (op: operation) : list typ * typ :=\n  match op with\n  | Omove => (nil, Tint)   (* treated specially *)\n  | Ointconst _ => (nil, Tint)\n  | Ofloatconst _ => (nil, Tfloat)\n  | Oaddrsymbol _ _ => (nil, Tint)\n  | Oaddrstack _ => (nil, Tint)\n  | Ocast8signed => (Tint :: nil, Tint)\n  | Ocast16signed => (Tint :: nil, Tint)\n  | Oadd => (Tint :: Tint :: nil, Tint)\n  | Oaddimm _ => (Tint :: nil, Tint)\n  | Osub => (Tint :: Tint :: nil, Tint)\n  | Osubimm _ => (Tint :: nil, Tint)\n  | Omul => (Tint :: Tint :: nil, Tint)\n  | Omulimm _ => (Tint :: nil, Tint)\n  | Odiv => (Tint :: Tint :: nil, Tint)\n  | Odivu => (Tint :: Tint :: nil, Tint)\n  | Oand => (Tint :: Tint :: nil, Tint)\n  | Oandimm _ => (Tint :: nil, Tint)\n  | Oor => (Tint :: Tint :: nil, Tint)\n  | Oorimm _ => (Tint :: nil, Tint)\n  | Oxor => (Tint :: Tint :: nil, Tint)\n  | Oxorimm _ => (Tint :: nil, Tint)\n  | Onot => (Tint :: nil, Tint)\n  | Onand => (Tint :: Tint :: nil, Tint)\n  | Onor => (Tint :: Tint :: nil, Tint)\n  | Onxor => (Tint :: Tint :: nil, Tint)\n  | Oandc => (Tint :: Tint :: nil, Tint)\n  | Oorc => (Tint :: Tint :: nil, Tint)\n  | Oshl => (Tint :: Tint :: nil, Tint)\n  | Oshr => (Tint :: Tint :: nil, Tint)\n  | Oshrimm _ => (Tint :: nil, Tint)\n  | Oshrximm _ => (Tint :: nil, Tint)\n  | Oshru => (Tint :: Tint :: nil, Tint)\n  | Orolm _ _ => (Tint :: nil, Tint)\n  | Oroli _ _ => (Tint :: Tint :: nil, Tint)\n  | Onegf => (Tfloat :: nil, Tfloat)\n  | Oabsf => (Tfloat :: nil, Tfloat)\n  | Oaddf => (Tfloat :: Tfloat :: nil, Tfloat)\n  | Osubf => (Tfloat :: Tfloat :: nil, Tfloat)\n  | Omulf => (Tfloat :: Tfloat :: nil, Tfloat)\n  | Odivf => (Tfloat :: Tfloat :: nil, Tfloat)\n  | Osingleoffloat => (Tfloat :: nil, Tfloat)\n  | Ointoffloat => (Tfloat :: nil, Tint)\n  | Ofloatofwords => (Tint :: Tint :: nil, Tfloat)\n  | Ocmp c => (type_of_condition c, Tint)\n  end.\n\nDefinition type_of_addressing (addr: addressing) : list typ :=\n  match addr with\n  | Aindexed _ => Tint :: nil\n  | Aindexed2 => Tint :: Tint :: nil\n  | Aglobal _ _ => nil\n  | Abased _ _ => Tint :: nil\n  | Ainstack _ => nil\n  end.\n\n(** Weak type soundness results for [eval_operation]:\n  the result values, when defined, are always of the type predicted\n  by [type_of_operation]. *)\n\nSection SOUNDNESS.\n\nVariable A V: Type.\nVariable genv: Genv.t A V.\n\nLemma type_of_operation_sound:\n  forall op vl sp v m,\n  op <> Omove ->\n  eval_operation genv sp op vl m = Some v ->\n  Val.has_type v (snd (type_of_operation op)).\nProof with (try exact I).\n  intros.\n  destruct op; simpl in H0; FuncInv; subst; simpl.\n  congruence.\n  exact I.\n  exact I.\n  unfold symbol_address. destruct (Genv.find_symbol genv i)...\n  destruct sp...\n  destruct v0...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0; destruct v1... simpl. destruct (zeq b b0)...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0; destruct v1; simpl in *; inv H0.\n    destruct (Int.eq i0 Int.zero\n         || Int.eq i (Int.repr Int.min_signed) && Int.eq i0 Int.mone); inv H2...\n  destruct v0; destruct v1; simpl in *; inv H0. destruct (Int.eq i0 Int.zero); inv H2...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int.iwordsize)...\n  destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int.iwordsize)...\n  destruct v0; simpl... destruct (Int.ltu i Int.iwordsize)...\n  destruct v0; simpl in *; inv H0. destruct (Int.ltu i (Int.repr 31)); inv H2...\n  destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int.iwordsize)...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0; destruct v1...\n  destruct v0...\n  destruct v0; simpl in H0; inv H0. destruct (Float.intoffloat f); inv H2...\n  destruct v0; destruct v1...\n  destruct (eval_condition c vl m); simpl... destruct b... \nQed.\n\nLemma type_of_chunk_correct:\n  forall chunk m addr v,\n  Mem.loadv chunk m addr = Some v ->\n  Val.has_type v (type_of_chunk chunk).\nProof.\n  intro chunk.\n  assert (forall v, Val.has_type (Val.load_result chunk v) (type_of_chunk chunk)).\n  destruct v; destruct chunk; exact I.\n  intros until v. unfold Mem.loadv. \n  destruct addr; intros; try discriminate.\n  eapply Mem.load_type; eauto.\nQed.\n\nEnd SOUNDNESS.\n\n(** * Manipulating and transforming operations *)\n\n(** Recognition of move operations. *)\n\nDefinition is_move_operation\n    (A: Type) (op: operation) (args: list A) : option A :=\n  match op, args with\n  | Omove, arg :: nil => Some arg\n  | _, _ => None\n  end.\n\nLemma is_move_operation_correct:\n  forall (A: Type) (op: operation) (args: list A) (a: A),\n  is_move_operation op args = Some a ->\n  op = Omove /\\ args = a :: nil.\nProof.\n  intros until a. unfold is_move_operation; destruct op;\n  try (intros; discriminate).\n  destruct args. intros; discriminate.\n  destruct args. intros. intuition congruence. \n  intros; discriminate.\nQed.\n\n(** [negate_condition cond] returns a condition that is logically\n  equivalent to the negation of [cond]. *)\n\nDefinition negate_condition (cond: condition): condition :=\n  match cond with\n  | Ccomp c => Ccomp(negate_comparison c)\n  | Ccompu c => Ccompu(negate_comparison c)\n  | Ccompimm c n => Ccompimm (negate_comparison c) n\n  | Ccompuimm c n => Ccompuimm (negate_comparison c) n\n  | Ccompf c => Cnotcompf c\n  | Cnotcompf c => Ccompf c\n  | Cmaskzero n => Cmasknotzero n\n  | Cmasknotzero n => Cmaskzero n\n  end.\n\nLemma eval_negate_condition:\n  forall cond vl m,\n  eval_condition (negate_condition cond) vl m = option_map negb (eval_condition cond vl m).\nProof.\n  intros. destruct cond; simpl.\n  repeat (destruct vl; auto). apply Val.negate_cmp_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmpu_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmp_bool.\n  repeat (destruct vl; auto). apply Val.negate_cmpu_bool.\n  repeat (destruct vl; auto). \n  repeat (destruct vl; auto). destruct (Val.cmpf_bool c v v0); auto. destruct b; auto.\n  destruct vl; auto. destruct v; auto. destruct vl; auto. \n  destruct vl; auto. destruct v; auto. destruct vl; auto. simpl. rewrite negb_involutive. auto.\nQed.\n\n(** Shifting stack-relative references.  This is used in [Stacking]. *)\n\nDefinition shift_stack_addressing (delta: int) (addr: addressing) :=\n  match addr with\n  | Ainstack ofs => Ainstack (Int.add delta ofs)\n  | _ => addr\n  end.\n\nDefinition shift_stack_operation (delta: int) (op: operation) :=\n  match op with\n  | Oaddrstack ofs => Oaddrstack (Int.add delta ofs)\n  | _ => op\n  end.\n\nLemma type_shift_stack_addressing:\n  forall delta addr, type_of_addressing (shift_stack_addressing delta addr) = type_of_addressing addr.\nProof.\n  intros. destruct addr; auto. \nQed.\n\nLemma type_shift_stack_operation:\n  forall delta op, type_of_operation (shift_stack_operation delta op) = type_of_operation op.\nProof.\n  intros. destruct op; auto.\nQed.\n\nLemma eval_shift_stack_addressing:\n  forall F V (ge: Genv.t F V) sp addr vl delta,\n  eval_addressing ge sp (shift_stack_addressing delta addr) vl =\n  eval_addressing ge (Val.add sp (Vint delta)) addr vl.\nProof.\n  intros. destruct addr; simpl; auto.\n  rewrite Val.add_assoc. simpl. auto.\nQed.\n\nLemma eval_shift_stack_operation:\n  forall F V (ge: Genv.t F V) sp op vl m delta,\n  eval_operation ge sp (shift_stack_operation delta op) vl m =\n  eval_operation ge (Val.add sp (Vint delta)) op vl m.\nProof.\n  intros. destruct op; simpl; auto.\n  rewrite Val.add_assoc. simpl. auto.\nQed.\n\n(** Transformation of addressing modes with two operands or more\n  into an equivalent arithmetic operation.  This is used in the [Reload]\n  pass when a store instruction cannot be reloaded directly because\n  it runs out of temporary registers. *)\n\n(** For the PowerPC, there is only one binary addressing mode: [Aindexed2].\n  The corresponding operation is [Oadd]. *)\n\nDefinition op_for_binary_addressing (addr: addressing) : operation := Oadd.\n\nLemma eval_op_for_binary_addressing:\n  forall (F V: Type) (ge: Genv.t F V) sp addr args v m,\n  (length args >= 2)%nat ->\n  eval_addressing ge sp addr args = Some v ->\n  eval_operation ge sp (op_for_binary_addressing addr) args m = Some v.\nProof.\n  intros.\n  destruct addr; simpl in H0; FuncInv; simpl in H; try omegaContradiction.\n  simpl; congruence.\nQed.\n\nLemma type_op_for_binary_addressing:\n  forall addr,\n  (length (type_of_addressing addr) >= 2)%nat ->\n  type_of_operation (op_for_binary_addressing addr) = (type_of_addressing addr, Tint).\nProof.\n  intros. destruct addr; simpl in H; reflexivity || omegaContradiction.\nQed.\n\n(** Two-address operations.  There is only one: rotate-mask-insert. *)\n\nDefinition two_address_op (op: operation) : bool :=\n  match op with\n  | Oroli _ _ => true\n  | _ => false\n  end.\n\n(** Operations that are so cheap to recompute that CSE should not factor them out. *)\n\nDefinition is_trivial_op (op: operation) : bool :=\n  match op with\n  | Omove => true\n  | Ointconst _ => true\n  | Oaddrsymbol _ _ => true\n  | Oaddrstack _ => true\n  | _ => false\n  end.\n\n(** Operations that depend on the memory state. *)\n\nDefinition op_depends_on_memory (op: operation) : bool :=\n  match op with\n  | Ocmp (Ccompu _) => true\n  | _ => false\n  end.\n\nLemma op_depends_on_memory_correct:\n  forall (F V: Type) (ge: Genv.t F V) sp op args m1 m2,\n  op_depends_on_memory op = false ->\n  eval_operation ge sp op args m1 = eval_operation ge sp op args m2.\nProof.\n  intros until m2. destruct op; simpl; try congruence.\n  destruct c; simpl; auto; discriminate. \nQed.\n\n(** Checking whether two addressings, applied to the same arguments, produce\n  separated memory addresses.  Used in [CSE]. *)\n\nDefinition addressing_separated (chunk1: memory_chunk) (addr1: addressing)\n                               (chunk2: memory_chunk) (addr2: addressing) : bool :=\n  match addr1, addr2 with\n  | Aindexed ofs1, Aindexed ofs2 => \n      Int.no_overlap ofs1 (size_chunk chunk1) ofs2 (size_chunk chunk2)\n  | Aglobal s1 ofs1, Aglobal s2 ofs2 => \n      if ident_eq s1 s2 then Int.no_overlap ofs1 (size_chunk chunk1) ofs2 (size_chunk chunk2) else true\n  | Abased s1 ofs1, Abased s2 ofs2 => \n      if ident_eq s1 s2 then Int.no_overlap ofs1 (size_chunk chunk1) ofs2 (size_chunk chunk2) else true\n  | Ainstack ofs1, Ainstack ofs2 =>\n      Int.no_overlap ofs1 (size_chunk chunk1) ofs2 (size_chunk chunk2)\n  | _, _ => false\n  end.\n\nLemma addressing_separated_sound:\n  forall (F V: Type) (ge: Genv.t F V) sp chunk1 addr1 chunk2 addr2 vl b1 n1 b2 n2,\n  addressing_separated chunk1 addr1 chunk2 addr2 = true ->\n  eval_addressing ge sp addr1 vl = Some(Vptr b1 n1) ->\n  eval_addressing ge sp addr2 vl = Some(Vptr b2 n2) ->\n  b1 <> b2 \\/ Int.unsigned n1 + size_chunk chunk1 <= Int.unsigned n2 \\/ Int.unsigned n2 + size_chunk chunk2 <= Int.unsigned n1.\nProof.\n  unfold addressing_separated; intros.\n  generalize (size_chunk_pos chunk1) (size_chunk_pos chunk2); intros SZ1 SZ2.\n  destruct addr1; destruct addr2; try discriminate; simpl in *; FuncInv.\n(* Aindexed *)\n  destruct v; simpl in *; inv H1; inv H2.\n  right. apply Int.no_overlap_sound; auto. \n(* Aglobal *)\n  unfold symbol_address in *. \n  destruct (Genv.find_symbol ge i1) as []_eqn; inv H2.\n  destruct (Genv.find_symbol ge i) as []_eqn; inv H1.\n  destruct (ident_eq i i1). subst.\n  replace (Int.unsigned n1) with (Int.unsigned (Int.add Int.zero n1)).\n  replace (Int.unsigned n2) with (Int.unsigned (Int.add Int.zero n2)).\n  right. apply Int.no_overlap_sound; auto. \n  rewrite Int.add_commut; rewrite Int.add_zero; auto.\n  rewrite Int.add_commut; rewrite Int.add_zero; auto.\n  left. red; intros; elim n. subst. eapply Genv.genv_vars_inj; eauto.\n(* Abased *)\n  unfold symbol_address in *. \n  destruct (Genv.find_symbol ge i1) as []_eqn; simpl in *; try discriminate.\n  destruct v; inv H2.\n  destruct (Genv.find_symbol ge i) as []_eqn; inv H1.\n  destruct (ident_eq i i1). subst.\n  rewrite (Int.add_commut i0 i3). rewrite (Int.add_commut i2 i3).\n  right. apply Int.no_overlap_sound; auto. \n  left. red; intros; elim n. subst. eapply Genv.genv_vars_inj; eauto.\n(* Ainstack *)\n  destruct sp; simpl in *; inv H1; inv H2.\n  right. apply Int.no_overlap_sound; auto. \nQed.\n\n(** * Invariance and compatibility properties. *)\n\n(** [eval_operation] and [eval_addressing] depend on a global environment\n  for resolving references to global symbols.  We show that they give\n  the same results if a global environment is replaced by another that\n  assigns the same addresses to the same symbols. *)\n\nSection GENV_TRANSF.\n\nVariable F1 F2 V1 V2: Type.\nVariable ge1: Genv.t F1 V1.\nVariable ge2: Genv.t F2 V2.\nHypothesis agree_on_symbols:\n  forall (s: ident), Genv.find_symbol ge2 s = Genv.find_symbol ge1 s.\n\nLemma eval_operation_preserved:\n  forall sp op vl m,\n  eval_operation ge2 sp op vl m = eval_operation ge1 sp op vl m.\nProof.\n  intros. destruct op; simpl; auto. \n  destruct vl; auto. decEq. unfold symbol_address. rewrite agree_on_symbols. auto.\nQed.\n\nLemma eval_addressing_preserved:\n  forall sp addr vl,\n  eval_addressing ge2 sp addr vl = eval_addressing ge1 sp addr vl.\nProof.\n  intros. destruct addr; simpl; auto; unfold symbol_address; rewrite agree_on_symbols; auto.\nQed.\n\nEnd GENV_TRANSF.\n\n(** Compatibility of the evaluation functions with value injections. *)\n\nSection EVAL_COMPAT.\n\nVariable F V: Type.\nVariable genv: Genv.t F V.\nVariable f: meminj.\n\nHypothesis symbol_address_inj: \n  forall id ofs,\n  val_inject f (symbol_address genv id ofs) (symbol_address genv id ofs).\n\nVariable m1: mem.\nVariable m2: mem.\n\nHypothesis valid_pointer_inj:\n  forall b1 ofs b2 delta,\n  f b1 = Some(b2, delta) ->\n  Mem.valid_pointer m1 b1 (Int.unsigned ofs) = true ->\n  Mem.valid_pointer m2 b2 (Int.unsigned (Int.add ofs (Int.repr delta))) = true.\n\nHypothesis valid_pointer_no_overflow:\n  forall b1 ofs b2 delta,\n  f b1 = Some(b2, delta) ->\n  Mem.valid_pointer m1 b1 (Int.unsigned ofs) = true ->\n  0 <= Int.unsigned ofs + Int.unsigned (Int.repr delta) <= Int.max_unsigned.\n\nHypothesis valid_different_pointers_inj:\n  forall b1 ofs1 b2 ofs2 b1' delta1 b2' delta2,\n  b1 <> b2 ->\n  Mem.valid_pointer m1 b1 (Int.unsigned ofs1) = true ->\n  Mem.valid_pointer m1 b2 (Int.unsigned ofs2) = true ->\n  f b1 = Some (b1', delta1) ->\n  f b2 = Some (b2', delta2) ->\n  b1' <> b2' \\/\n  Int.unsigned (Int.add ofs1 (Int.repr delta1)) <> Int.unsigned (Int.add ofs2 (Int.repr delta2)).\n\nLtac InvInject :=\n  match goal with\n  | [ H: val_inject _ (Vint _) _ |- _ ] =>\n      inv H; InvInject\n  | [ H: val_inject _ (Vfloat _) _ |- _ ] =>\n      inv H; InvInject\n  | [ H: val_inject _ (Vptr _ _) _ |- _ ] =>\n      inv H; InvInject\n  | [ H: val_list_inject _ nil _ |- _ ] =>\n      inv H; InvInject\n  | [ H: val_list_inject _ (_ :: _) _ |- _ ] =>\n      inv H; InvInject\n  | _ => idtac\n  end.\n\nRemark val_add_inj:\n  forall v1 v1' v2 v2',\n  val_inject f v1 v1' -> val_inject f v2 v2' -> val_inject f (Val.add v1 v2) (Val.add v1' v2').\nProof.\n  intros. inv H; inv H0; simpl; econstructor; eauto. \n  repeat rewrite Int.add_assoc. decEq. apply Int.add_commut.\n  repeat rewrite Int.add_assoc. decEq. apply Int.add_commut.\nQed.\n\nLemma eval_condition_inj:\n  forall cond vl1 vl2 b,\n  val_list_inject f vl1 vl2 ->\n  eval_condition cond vl1 m1 = Some b ->\n  eval_condition cond vl2 m2 = Some b.\nProof.\nOpaque Int.add.\n  assert (CMPU:\n    forall c v1 v2 v1' v2' b,\n    val_inject f v1 v1' ->\n    val_inject f v2 v2' ->\n    Val.cmpu_bool (Mem.valid_pointer m1) c v1 v2 = Some b ->\n    Val.cmpu_bool (Mem.valid_pointer m2) c v1' v2' = Some b).\n  intros. inv H; simpl in H1; try discriminate; inv H0; simpl in H1; try discriminate; simpl; auto.\n  destruct (Mem.valid_pointer m1 b1 (Int.unsigned ofs1)) as []_eqn; try discriminate.\n  destruct (Mem.valid_pointer m1 b0 (Int.unsigned ofs0)) as []_eqn; try discriminate.\n  rewrite (valid_pointer_inj _ H2 Heqb4).\n  rewrite (valid_pointer_inj _ H Heqb0). simpl.\n  destruct (zeq b1 b0); simpl in H1.\n  inv H1. rewrite H in H2; inv H2. rewrite zeq_true. \n  decEq. apply Int.translate_cmpu.\n  eapply valid_pointer_no_overflow; eauto.\n  eapply valid_pointer_no_overflow; eauto.\n  exploit valid_different_pointers_inj; eauto. intros P.\n  destruct (zeq b2 b3); auto.\n  destruct P. congruence. \n  destruct c; simpl in H1; inv H1.\n  simpl; decEq. rewrite Int.eq_false; auto. congruence.\n  simpl; decEq. rewrite Int.eq_false; auto. congruence.\n\n  intros. destruct cond; simpl in H0; FuncInv; InvInject; simpl; auto.\n  inv H3; inv H2; simpl in H0; inv H0; auto.\n  eauto.\n  inv H3; simpl in H0; inv H0; auto.\n  eauto. \n  inv H3; inv H2; simpl in H0; inv H0; auto.\n  inv H3; inv H2; simpl in H0; inv H0; auto.\nQed.\n\nLtac TrivialExists :=\n  match goal with\n  | [ |- exists v2, Some ?v1 = Some v2 /\\ val_inject _ _ v2 ] =>\n      exists v1; split; auto\n  | _ => idtac\n  end.\n\nLemma eval_operation_inj:\n  forall op sp1 vl1 sp2 vl2 v1,\n  val_inject f sp1 sp2 ->\n  val_list_inject f vl1 vl2 ->\n  eval_operation genv sp1 op vl1 m1 = Some v1 ->\n  exists v2, eval_operation genv sp2 op vl2 m2 = Some v2 /\\ val_inject f v1 v2.\nProof.\n  intros. destruct op; simpl in H1; simpl; FuncInv; InvInject; TrivialExists.\n  inv H; simpl; econstructor; eauto. repeat rewrite Int.add_assoc. decEq. apply Int.add_commut.\n  inv H4; simpl; auto.\n  inv H4; simpl; auto.\n  apply val_add_inj; auto.\n  apply val_add_inj; auto.\n  inv H4; inv H2; simpl; auto. econstructor; eauto. \n    rewrite Int.sub_add_l. auto.\n    destruct (zeq b1 b0); auto. subst. rewrite H1 in H0. inv H0. rewrite zeq_true. \n    rewrite Int.sub_shifted. auto.\n  inv H4; auto. \n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H3; simpl in H1; inv H1. simpl. \n    destruct (Int.eq i0 Int.zero\n         || Int.eq i (Int.repr Int.min_signed) && Int.eq i0 Int.mone); inv H2. TrivialExists.\n  inv H4; inv H3; simpl in H1; inv H1. simpl. \n    destruct (Int.eq i0 Int.zero); inv H2. TrivialExists.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int.iwordsize); auto.\n  inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int.iwordsize); auto.\n  inv H4; simpl; auto. destruct (Int.ltu i Int.iwordsize); auto.\n  inv H4; simpl in *; inv H1. destruct (Int.ltu i (Int.repr 31)); inv H2. econstructor; eauto.\n  inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int.iwordsize); auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; inv H2; simpl; auto.\n  inv H4; simpl; auto.\n  inv H4; simpl in H1; inv H1. simpl. destruct (Float.intoffloat f0); simpl in H2; inv H2.\n  exists (Vint i); auto.\n  inv H4; inv H2; simpl; auto.\n  subst v1. destruct (eval_condition c vl1 m1) as []_eqn.\n  exploit eval_condition_inj; eauto. intros EQ; rewrite EQ.\n  destruct b; simpl; constructor.\n  simpl; constructor.\nQed.\n\nLemma eval_addressing_inj:\n  forall addr sp1 vl1 sp2 vl2 v1,\n  val_inject f sp1 sp2 ->\n  val_list_inject f vl1 vl2 ->\n  eval_addressing genv sp1 addr vl1 = Some v1 ->\n  exists v2, eval_addressing genv sp2 addr vl2 = Some v2 /\\ val_inject f v1 v2.\nProof.\n  intros. destruct addr; simpl in H1; simpl; FuncInv; InvInject; TrivialExists.\n  apply val_add_inj; auto.\n  apply val_add_inj; auto.\n  apply val_add_inj; auto.\n  apply val_add_inj; auto.\nQed.\n\nEnd EVAL_COMPAT.\n\n(** Compatibility of the evaluation functions with the ``is less defined'' relation over values. *)\n\nSection EVAL_LESSDEF.\n\nVariable F V: Type.\nVariable genv: Genv.t F V.\n\nRemark valid_pointer_extends:\n  forall m1 m2, Mem.extends m1 m2 ->\n  forall b1 ofs b2 delta,\n  Some(b1, 0) = Some(b2, delta) ->\n  Mem.valid_pointer m1 b1 (Int.unsigned ofs) = true ->\n  Mem.valid_pointer m2 b2 (Int.unsigned (Int.add ofs (Int.repr delta))) = true.\nProof.\n  intros. inv H0. rewrite Int.add_zero. eapply Mem.valid_pointer_extends; eauto. \nQed.\n\nRemark valid_pointer_no_overflow_extends:\n  forall m1 b1 ofs b2 delta,\n  Some(b1, 0) = Some(b2, delta) ->\n  Mem.valid_pointer m1 b1 (Int.unsigned ofs) = true ->\n  0 <= Int.unsigned ofs + Int.unsigned (Int.repr delta) <= Int.max_unsigned.\nProof.\n  intros. inv H. rewrite Zplus_0_r. apply Int.unsigned_range_2.\nQed.\n\nRemark valid_different_pointers_extends:\n  forall m1 b1 ofs1 b2 ofs2 b1' delta1 b2' delta2,\n  b1 <> b2 ->\n  Mem.valid_pointer m1 b1 (Int.unsigned ofs1) = true ->\n  Mem.valid_pointer m1 b2 (Int.unsigned ofs2) = true ->\n  Some(b1, 0) = Some (b1', delta1) ->\n  Some(b2, 0) = Some (b2', delta2) ->\n  b1' <> b2' \\/\n  Int.unsigned(Int.add ofs1 (Int.repr delta1)) <> Int.unsigned(Int.add ofs2 (Int.repr delta2)).\nProof.\n  intros. inv H2; inv H3. auto.\nQed.\n\nLemma eval_condition_lessdef:\n  forall cond vl1 vl2 b m1 m2,\n  Val.lessdef_list vl1 vl2 ->\n  Mem.extends m1 m2 ->\n  eval_condition cond vl1 m1 = Some b ->\n  eval_condition cond vl2 m2 = Some b.\nProof.\n  intros. eapply eval_condition_inj with (f := fun b => Some(b, 0)) (m1 := m1).\n  apply valid_pointer_extends; auto.\n  apply valid_pointer_no_overflow_extends; auto. \n  apply valid_different_pointers_extends; auto.\n  rewrite <- val_list_inject_lessdef. eauto. auto.\nQed.\n\nLemma eval_operation_lessdef:\n  forall sp op vl1 vl2 v1 m1 m2,\n  Val.lessdef_list vl1 vl2 ->\n  Mem.extends m1 m2 ->\n  eval_operation genv sp op vl1 m1 = Some v1 ->\n  exists v2, eval_operation genv sp op vl2 m2 = Some v2 /\\ Val.lessdef v1 v2.\nProof.\n  intros. rewrite val_list_inject_lessdef in H.\n  assert (exists v2 : val,\n          eval_operation genv sp op vl2 m2 = Some v2\n          /\\ val_inject (fun b => Some(b, 0)) v1 v2).\n  eapply eval_operation_inj with (m1 := m1) (sp1 := sp).\n  intros. rewrite <- val_inject_lessdef; auto.\n  apply valid_pointer_extends; auto.\n  apply valid_pointer_no_overflow_extends; auto. \n  apply valid_different_pointers_extends; auto.\n  rewrite <- val_inject_lessdef; auto.\n  eauto. auto. \n  destruct H2 as [v2 [A B]]. exists v2; split; auto. rewrite val_inject_lessdef; auto. \nQed.\n\nLemma eval_addressing_lessdef:\n  forall sp addr vl1 vl2 v1,\n  Val.lessdef_list vl1 vl2 ->\n  eval_addressing genv sp addr vl1 = Some v1 ->\n  exists v2, eval_addressing genv sp addr vl2 = Some v2 /\\ Val.lessdef v1 v2.\nProof.\n  intros. rewrite val_list_inject_lessdef in H.\n  assert (exists v2 : val,\n          eval_addressing genv sp addr vl2 = Some v2\n          /\\ val_inject (fun b => Some(b, 0)) v1 v2).\n  eapply eval_addressing_inj with (sp1 := sp).\n  intros. rewrite <- val_inject_lessdef; auto.\n  rewrite <- val_inject_lessdef; auto.\n  eauto. auto. \n  destruct H1 as [v2 [A B]]. exists v2; split; auto. rewrite val_inject_lessdef; auto. \nQed.\n\nEnd EVAL_LESSDEF.\n\n(** Compatibility of the evaluation functions with memory injections. *)\n\nSection EVAL_INJECT.\n\nVariable F V: Type.\nVariable genv: Genv.t F V.\nVariable f: meminj.\nHypothesis globals: meminj_preserves_globals genv f.\nVariable sp1: block.\nVariable sp2: block.\nVariable delta: Z.\nHypothesis sp_inj: f sp1 = Some(sp2, delta).\n\nRemark symbol_address_inject:\n  forall id ofs, val_inject f (symbol_address genv id ofs) (symbol_address genv id ofs).\nProof.\n  intros. unfold symbol_address. destruct (Genv.find_symbol genv id) as []_eqn; auto.\n  exploit (proj1 globals); eauto. intros. \n  econstructor; eauto. rewrite Int.add_zero; auto.\nQed.\n\nLemma eval_condition_inject:\n  forall cond vl1 vl2 b m1 m2,\n  val_list_inject f vl1 vl2 ->\n  Mem.inject f m1 m2 ->\n  eval_condition cond vl1 m1 = Some b ->\n  eval_condition cond vl2 m2 = Some b.\nProof.\n  intros. eapply eval_condition_inj with (f := f) (m1 := m1); eauto.\n  intros; eapply Mem.valid_pointer_inject_val; eauto.\n  intros; eapply Mem.valid_pointer_inject_no_overflow; eauto.\n  intros; eapply Mem.different_pointers_inject; eauto.\nQed.\n\nLemma eval_addressing_inject:\n  forall addr vl1 vl2 v1,\n  val_list_inject f vl1 vl2 ->\n  eval_addressing genv (Vptr sp1 Int.zero) addr vl1 = Some v1 ->\n  exists v2, \n     eval_addressing genv (Vptr sp2 Int.zero) (shift_stack_addressing (Int.repr delta) addr) vl2 = Some v2\n  /\\ val_inject f v1 v2.\nProof.\n  intros. \n  rewrite eval_shift_stack_addressing. simpl.\n  eapply eval_addressing_inj with (sp1 := Vptr sp1 Int.zero); eauto.\n  exact symbol_address_inject.\nQed.\n\nLemma eval_operation_inject:\n  forall op vl1 vl2 v1 m1 m2,\n  val_list_inject f vl1 vl2 ->\n  Mem.inject f m1 m2 ->\n  eval_operation genv (Vptr sp1 Int.zero) op vl1 m1 = Some v1 ->\n  exists v2,\n     eval_operation genv (Vptr sp2 Int.zero) (shift_stack_operation (Int.repr delta) op) vl2 m2 = Some v2\n  /\\ val_inject f v1 v2.\nProof.\n  intros. \n  rewrite eval_shift_stack_operation. simpl.\n  eapply eval_operation_inj with (sp1 := Vptr sp1 Int.zero) (m1 := m1); eauto.\n  exact symbol_address_inject.\n  intros; eapply Mem.valid_pointer_inject_val; eauto.\n  intros; eapply Mem.valid_pointer_inject_no_overflow; eauto.\n  intros; eapply Mem.different_pointers_inject; eauto.\nQed.\n\nEnd EVAL_INJECT.\n\n(** * Masks for rotate and mask instructions *)\n\n(** Recognition of integers that are acceptable as immediate operands\n  to the [rlwim] PowerPC instruction.  These integers are of the form\n  [000011110000] or [111100001111], that is, a run of one bits\n  surrounded by zero bits, or conversely.  We recognize these integers by\n  running the following automaton on the bits.  The accepting states are\n  2, 3, 4, 5, and 6.\n<<\n               0          1          0\n              / \\        / \\        / \\\n              \\ /        \\ /        \\ /\n        -0--> [1] --1--> [2] --0--> [3]\n       /     \n     [0]\n       \\\n        -1--> [4] --0--> [5] --1--> [6]\n              / \\        / \\        / \\\n              \\ /        \\ /        \\ /\n               1          0          1\n>>\n*)\n\nInductive rlw_state: Type :=\n  | RLW_S0 : rlw_state\n  | RLW_S1 : rlw_state\n  | RLW_S2 : rlw_state\n  | RLW_S3 : rlw_state\n  | RLW_S4 : rlw_state\n  | RLW_S5 : rlw_state\n  | RLW_S6 : rlw_state\n  | RLW_Sbad : rlw_state.\n\nDefinition rlw_transition (s: rlw_state) (b: bool) : rlw_state :=\n  match s, b with\n  | RLW_S0, false => RLW_S1\n  | RLW_S0, true  => RLW_S4\n  | RLW_S1, false => RLW_S1\n  | RLW_S1, true  => RLW_S2\n  | RLW_S2, false => RLW_S3\n  | RLW_S2, true  => RLW_S2\n  | RLW_S3, false => RLW_S3\n  | RLW_S3, true  => RLW_Sbad\n  | RLW_S4, false => RLW_S5\n  | RLW_S4, true  => RLW_S4\n  | RLW_S5, false => RLW_S5\n  | RLW_S5, true  => RLW_S6\n  | RLW_S6, false => RLW_Sbad\n  | RLW_S6, true  => RLW_S6\n  | RLW_Sbad, _ => RLW_Sbad\n  end.\n\nDefinition rlw_accepting (s: rlw_state) : bool :=\n  match s with\n  | RLW_S0 => false\n  | RLW_S1 => false\n  | RLW_S2 => true\n  | RLW_S3 => true\n  | RLW_S4 => true\n  | RLW_S5 => true\n  | RLW_S6 => true\n  | RLW_Sbad => false\n  end.\n\nFixpoint is_rlw_mask_rec (n: nat) (s: rlw_state) (x: Z) {struct n} : bool :=\n  match n with\n  | O =>\n      rlw_accepting s\n  | S m =>\n      let (b, y) := Int.Z_bin_decomp x in\n      is_rlw_mask_rec m (rlw_transition s b) y\n  end.\n\nDefinition is_rlw_mask (x: int) : bool :=\n  is_rlw_mask_rec Int.wordsize RLW_S0 (Int.unsigned x).\n", "meta": {"author": "Ptival", "repo": "compcert-alias", "sha": "c839efb9cd2a4c27add46a1868fe0444d1dfdd9e", "save_path": "github-repos/coq/Ptival-compcert-alias", "path": "github-repos/coq/Ptival-compcert-alias/compcert-alias-c839efb9cd2a4c27add46a1868fe0444d1dfdd9e/powerpc/Op.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.2060736691886551}}
{"text": "Require Import Coq.Program.Basics.\nRequire Import Coq.Logic.FunctionalExtensionality.\nRequire Import Coq.Program.Combinators.\nRequire Import Setoid.\nRequire Import ZArith.\nRequire Import Psatz.\n\n\nRequire Import FinProof.Common.\nRequire Import FinProof.CommonInstances.\nRequire Import FinProof.StateMonad2.\nRequire Import FinProof.StateMonadInstances.\nRequire Import FinProof.ProgrammingWith. \n\nLocal Open Scope struct_scope.\n\nRequire Import FinProof.CommonProofs.\nRequire Import depoolContract.ProofEnvironment.\nRequire Import depoolContract.DePoolClass.\nRequire Import depoolContract.SolidityNotations.\n\nRequire Import depoolContract.NewProofs.ProofHelpers.\nRequire Import depoolContract.DePoolFunc.\n\n(* Set Typeclasses Iterative Deepening.\nSet Typeclasses Depth 100. *)\n\nRequire Import depoolContract.Lib.CommonModelProofs.\nModule CommonModelProofs := CommonModelProofs StateMonadSig.\nImport CommonModelProofs. \nRequire Import depoolContract.Lib.Tactics.\nRequire Import depoolContract.Lib.ErrorValueProofs.\nRequire Import depoolContract.Lib.CommonCommon.\n\n(* Require Import MultiSigWallet.Proofs.tvmFunctionsProofs. *)\n\nImport DePoolSpec.LedgerClass.SolidityNotations. \n\nLocal Open Scope struct_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope solidity_scope.\nRequire Import Lists.List.\nImport ListNotations.\nLocal Open Scope list_scope.\n\nRequire Import depoolContract.DePoolConsts.\nModule DePoolContract_Ф_terminator (dc : DePoolConstsTypesSig XTypesSig StateMonadSig).\nModule DePoolFuncs := DePoolFuncs XTypesSig StateMonadSig dc.\nModule ProofHelpers := ProofHelpers dc.\n\nImport dc.\nImport ProofHelpers.\nImport DePoolFuncs.\nImport DePoolSpec.\nImport LedgerClass.\n\n\nOpaque Z.eqb Z.add Z.sub Z.div Z.mul hmapLookup hmapInsert Z.ltb Z.geb Z.leb Z.gtb Z.modulo deleteListPair.\n\nImport TVMModel.LedgerClass.\nOpaque DePoolContract_Ф_startRoundCompleting roundStepEqb.\n\nDefinition DePoolContract_Ф_terminator_tailer Л_roundPre0 Л_round0 : LedgerT True := \n->emit $ DePoolClosed >> \n(RoundsBase_Ф_setRoundPre0 (! $ Л_roundPre0 !) ) >> \n(RoundsBase_Ф_setRound0 (! $ Л_round0 !) ) >> \n(RoundsBase_Ф_setRound1 (! ↑17 D2! LocalState_ι_terminator_Л_round1 !) )  .\n\n\nDefinition DePoolContract_Ф_terminator_header : LedgerT ( XErrorValue True XInteger ) := \n \nRequire2 {{ msg_pubkey () ?== tvm_pubkey () , ξ$ Errors_ι_IS_NOT_OWNER }} ; \nRequire {{ !¬ ↑12 D2! DePoolContract_ι_m_poolClosed , ξ$ Errors_ι_DEPOOL_IS_CLOSED }} ; \n(↑12 U1! DePoolContract_ι_m_poolClosed := $xBoolTrue) >> \ntvm_commit () >> \ntvm_accept () >> \ndeclareLocal Л_roundPre0 :>: RoundsBase_ι_Round := RoundsBase_Ф_getRoundPre0 (); \ndeclareLocal Л_round0 :>: RoundsBase_ι_Round := RoundsBase_Ф_getRound0 (); \n(declareGlobal! LocalState_ι_terminator_Л_round1 :>: RoundsBase_ι_Round := RoundsBase_Ф_getRound1 () ) >> \nU0! Л_roundPre0 := DePoolContract_Ф_startRoundCompleting (! $ Л_roundPre0 , \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t ξ$ RoundsBase_ι_CompletionReasonP_ι_PoolClosed !) ; \nU0! Л_round0 := DePoolContract_Ф_startRoundCompleting (! $ Л_round0 , \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t ξ$ RoundsBase_ι_CompletionReasonP_ι_PoolClosed !) ; \n(If (↑17 D2! LocalState_ι_terminator_Л_round1 ^^ RoundsBase_ι_Round_ι_step ?== ξ$ RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest) then { \n\t↑↑17 U2! LocalState_ι_terminator_Л_round1 := DePoolContract_Ф_startRoundCompleting (! ↑17 D2! LocalState_ι_terminator_Л_round1 , \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t  ξ$ RoundsBase_ι_CompletionReasonP_ι_PoolClosed !) \n}) >> DePoolContract_Ф_terminator_tailer Л_roundPre0 Л_round0.\n\nLemma DePoolContract_Ф_terminator_header_run_eq: forall (l: Ledger), \nrun DePoolContract_Ф_terminator l = run DePoolContract_Ф_terminator_header l.\nProof.\n  intros.\n  destructLedger l. \n  compute.\n  Time repeat destructIf_solve. idtac.\n\n\n  all: try destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. idtac. \n  all: try destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. idtac. \n  all: repeat destructIf_solve. idtac.\n  all: try destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. \nQed.\n\n\n\n\nLemma DePoolContract_Ф_terminator_eval : forall (l : Ledger),\n\nlet isOwner := eval_state msg_pubkey l =? eval_state tvm_pubkey l in\nlet isNotClosed := negb (eval_state (↑12 ε DePoolContract_ι_m_poolClosed) l) in\n\neval_state DePoolContract_Ф_terminator l =\n\nif isOwner then \n   if isNotClosed then Value I\n                  else Error Errors_ι_DEPOOL_IS_CLOSED\n           else Error Errors_ι_IS_NOT_OWNER.\nProof.    \n  \n  \n  intros.\n  destructLedger l. \n  compute.\n  Time repeat destructIf_solve. idtac.\n\n\n  all: try destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. idtac. \n  all: try destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. idtac. \n  all: repeat destructIf_solve. idtac.\n  all: try destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. \n  \nQed.  \n  \n  \n\nLemma DePoolContract_Ф_terminator_tailer_exec : forall Л_roundPre0 Л_round0 (l : Ledger),\nlet oldEvents := eval_state (↑16 ε VMState_ι_events) l in\nlet l_emit := {$l With (VMState_ι_events ,  DePoolClosed :: oldEvents ) $} in\nlet l_setPre0 := exec_state (↓ RoundsBase_Ф_setRoundPre0 Л_roundPre0) l_emit in\nlet l_set0 := exec_state (↓ RoundsBase_Ф_setRound0 Л_round0) l_setPre0 in\nlet round1 := eval_state (↑17 ε LocalState_ι_terminator_Л_round1) l in\nlet l_set1 := exec_state (↓ RoundsBase_Ф_setRound1 round1) l_set0 in\n\nexec_state (DePoolContract_Ф_terminator_tailer Л_roundPre0 Л_round0) l = l_set1.\n\nProof.\n  intros.\n  destructLedger l. \n  compute.\n  Time repeat destructIf_solve. \nQed.\n\nImport LedgerClass.\n\nOpaque DePoolContract_Ф_terminator_tailer.\n\nLemma DePoolContract_Ф_terminator_header_exec : forall  (l : Ledger),\nlet isOwner := eval_state msg_pubkey l =? eval_state tvm_pubkey l in\nlet isNotClosed := negb (eval_state (↑12 ε DePoolContract_ι_m_poolClosed) l) in\n\nlet closedDePool := {$ l With (DePoolContract_ι_m_poolClosed, true) $} in\nlet commited :=  exec_state (↓ tvm_commit) closedDePool in\nlet accepted :=  exec_state (↓ tvm_accept) commited in\n\nlet oldRoundPre0 := eval_state RoundsBase_Ф_getRoundPre0 l in\nlet oldRound0 := eval_state RoundsBase_Ф_getRound0 l in \nlet oldRound1 := eval_state RoundsBase_Ф_getRound1 l in \n\nlet round1ToBeUpdated : bool := eqb (RoundsBase_ι_Round_ι_step oldRound1) RoundsBase_ι_RoundStepP_ι_WaitingValidatorRequest in\nlet (srcPre0, l_pre0) := run (↓ DePoolContract_Ф_startRoundCompleting oldRoundPre0 RoundsBase_ι_CompletionReasonP_ι_PoolClosed) accepted in\nlet (src0, l_0) := run (↓ DePoolContract_Ф_startRoundCompleting oldRound0 RoundsBase_ι_CompletionReasonP_ι_PoolClosed) l_pre0 in\nlet (src1, l_1) := if round1ToBeUpdated then run (↓ DePoolContract_Ф_startRoundCompleting oldRound1 RoundsBase_ι_CompletionReasonP_ι_PoolClosed) l_0 \n                                        else (oldRound1, l_0) in\nlet l' := exec_state (DePoolContract_Ф_terminator_tailer srcPre0 src0) {$ l_1 With (LocalState_ι_terminator_Л_round1, src1) $} in                                        \n\nexec_state DePoolContract_Ф_terminator_header l =\nif isOwner then \n    if isNotClosed then l'\n                   else l else l.\n\nProof.\n\n  intros.\n  destructLedger l. \n  compute.\n  Time repeat destructIf_solve. idtac.\n\n  all: try destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. idtac. \n  all: try destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. idtac. \n  all: repeat destructIf_solve. idtac.\n  all: try destructFunction2 DePoolContract_Ф_startRoundCompleting; auto. idtac.\n  all: try destructFunction2 DePoolContract_Ф_terminator_tailer; auto. idtac.\n  all: try congruence.\nQed.\n\nLemma DePoolContract_Ф_terminator_header_eval_eq: forall (l: Ledger), \neval_state DePoolContract_Ф_terminator l = eval_state DePoolContract_Ф_terminator_header l.\nProof.\n  intros.\n  unfold eval_state.\n  rewrite DePoolContract_Ф_terminator_header_run_eq.\n  auto.\nQed.\n\nLemma DePoolContract_Ф_terminator_header_exec_eq: forall (l: Ledger), \nexec_state DePoolContract_Ф_terminator l = exec_state DePoolContract_Ф_terminator_header l.\nProof.\n  intros.\n  unfold exec_state.\n  rewrite DePoolContract_Ф_terminator_header_run_eq.\n  auto.\nQed.\n\n End DePoolContract_Ф_terminator.", "meta": {"author": "Pruvendo", "repo": "depool_contract", "sha": "6afe23011d62f65921ac2493df691ab888ffeb95", "save_path": "github-repos/coq/Pruvendo-depool_contract", "path": "github-repos/coq/Pruvendo-depool_contract/depool_contract-6afe23011d62f65921ac2493df691ab888ffeb95/src/NewProofs/DePoolContract_terminator.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.585101139733739, "lm_q2_score": 0.35220176844875106, "lm_q1q2_score": 0.2060736561356027}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Compile-time evaluation of initializers for global C variables. *)\n\nRequire Import Coqlib.\nRequire Import Errors.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import AST.\nRequire Import Memory.\nRequire Import Ctypes.\nRequire Import Cop.\nRequire Import Csyntax.\n\nOpen Scope error_monad_scope.\n\n(** * Evaluation of compile-time constant expressions *)\n\n(** To evaluate constant expressions at compile-time, we use the same [value]\n  type and the same [sem_*] functions that are used in CompCert C's semantics\n  (module [Csem]).  However, we interpret pointer values symbolically:\n  [Vptr id ofs] represents the address of global variable [id]\n  plus byte offset [ofs]. *)\n\n(** [constval a] evaluates the constant expression [a].\n\nIf [a] is a r-value, the returned value denotes:\n- [Vint n], [Vfloat f]: the corresponding number\n- [Vptr id ofs]: address of global variable [id] plus byte offset [ofs]\n- [Vundef]: erroneous expression\n\nIf [a] is a l-value, the returned value denotes:\n- [Vptr id ofs]: global variable [id] plus byte offset [ofs]\n*)\n\nDefinition do_cast (v: val) (t1 t2: type) : res val :=\n  match sem_cast v t1 t2 with\n  | Some v' => OK v'\n  | None => Error(msg \"undefined cast\")\n  end.\n\nFixpoint constval (a: expr) : res val :=\n  match a with\n  | Eval v ty =>\n      match v with\n      | Vint _ | Vfloat _ | Vlong _ => OK v\n      | Vptr _ _ | Vundef => Error(msg \"illegal constant\")\n      end\n  | Evalof l ty =>\n      match access_mode ty with\n      | By_reference | By_copy => constval l\n      | _ => Error(msg \"dereferencing of an l-value\")\n      end\n  | Eaddrof l ty =>\n      constval l\n  | Eunop op r1 ty =>\n      do v1 <- constval r1;\n      match sem_unary_operation op v1 (typeof r1) with\n      | Some v => OK v\n      | None => Error(msg \"undefined unary operation\")\n      end\n  | Ebinop op r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match sem_binary_operation op v1 (typeof r1) v2 (typeof r2) Mem.empty with\n      | Some v => OK v\n      | None => Error(msg \"undefined binary operation\")\n      end\n  | Ecast r ty =>\n      do v1 <- constval r; do_cast v1 (typeof r) ty\n  | Esizeof ty1 ty =>\n      OK (Vint (Int.repr (sizeof ty1)))\n  | Ealignof ty1 ty =>\n      OK (Vint (Int.repr (alignof ty1)))\n  | Eseqand r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match bool_val v1 (typeof r1) with\n      | Some true => do v3 <- do_cast v2 (typeof r2) type_bool; do_cast v3 type_bool ty\n      | Some false => OK (Vint Int.zero)\n      | None => Error(msg \"undefined && operation\")\n      end\n  | Eseqor r1 r2 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      match bool_val v1 (typeof r1) with\n      | Some false => do v3 <- do_cast v2 (typeof r2) type_bool; do_cast v3 type_bool ty\n      | Some true => OK (Vint Int.one)\n      | None => Error(msg \"undefined || operation\")\n      end\n  | Econdition r1 r2 r3 ty =>\n      do v1 <- constval r1;\n      do v2 <- constval r2;\n      do v3 <- constval r3;\n      match bool_val v1 (typeof r1) with\n      | Some true => do_cast v2 (typeof r2) ty\n      | Some false => do_cast v3 (typeof r3) ty\n      | None => Error(msg \"condition is undefined\")\n      end\n  | Ecomma r1 r2 ty =>\n      do v1 <- constval r1; constval r2\n  | Evar x ty =>\n      OK(Vptr x Int.zero)\n  | Ederef r ty =>\n      constval r\n  | Efield l f ty =>\n      match typeof l with\n      | Tstruct id fList _ =>\n          do delta <- field_offset f fList;\n          do v <- constval l;\n          OK (Val.add v (Vint (Int.repr delta)))\n      | Tunion id fList _ =>\n          constval l\n      | _ =>\n          Error(msg \"ill-typed field access\")\n      end\n  | Eparen r ty =>\n      do v <- constval r; do_cast v (typeof r) ty\n  | _ =>\n    Error(msg \"not a compile-time constant\")\n  end.\n\n(** * Translation of initializers *)\n\nInductive initializer :=\n  | Init_single (a: expr)\n  | Init_compound (il: initializer_list)\nwith initializer_list :=\n  | Init_nil\n  | Init_cons (i: initializer) (il: initializer_list).\n\n(** Translate an initializing expression [a] for a scalar variable\n  of type [ty].  Return the corresponding initialization datum. *)\n\nDefinition transl_init_single (ty: type) (a: expr) : res init_data :=\n  do v1 <- constval a;\n  do v2 <- do_cast v1 (typeof a) ty;\n  match v2, ty with\n  | Vint n, Tint (I8|IBool) sg _ => OK(Init_int8 n)\n  | Vint n, Tint I16 sg _ => OK(Init_int16 n)\n  | Vint n, Tint I32 sg _ => OK(Init_int32 n)\n  | Vint n, Tpointer _ _ => OK(Init_int32 n)\n  | Vint n, Tcomp_ptr _ _ => OK(Init_int32 n)\n  | Vlong n, Tlong _ _ => OK(Init_int64 n)\n  | Vfloat f, Tfloat F32 _ => OK(Init_float32 f)\n  | Vfloat f, Tfloat F64 _ => OK(Init_float64 f)\n  | Vptr id ofs, Tint I32 sg _ => OK(Init_addrof id ofs)\n  | Vptr id ofs, Tpointer _ _ => OK(Init_addrof id ofs)\n  | Vptr id ofs, Tcomp_ptr _ _ => OK(Init_addrof id ofs)\n  | Vundef, _ => Error(msg \"undefined operation in initializer\")\n  | _, _ => Error (msg \"type mismatch in initializer\")\n  end.\n\n(** Translate an initializer [i] for a variable of type [ty].\n  Return the corresponding list of initialization data. *)\n\nDefinition padding (frm to: Z) : list init_data :=\n  let n := to - frm in\n  if zle n 0 then nil else Init_space n :: nil.\n\nFixpoint transl_init (ty: type) (i: initializer)\n                     {struct i} : res (list init_data) :=\n  match i, ty with\n  | Init_single a, _ =>\n      do d <- transl_init_single ty a; OK (d :: nil)\n  | Init_compound il, Tarray tyelt sz _ =>\n      if zle sz 0\n      then OK (Init_space(sizeof tyelt) :: nil)\n      else transl_init_array tyelt il sz\n  | Init_compound il, Tstruct _ Fnil _ =>\n      OK (Init_space (sizeof ty) :: nil)\n  | Init_compound il, Tstruct id fl _ =>\n      transl_init_struct id ty fl il 0\n  | Init_compound il, Tunion _ Fnil _ =>\n      OK (Init_space (sizeof ty) :: nil)\n  | Init_compound il, Tunion id (Fcons _ ty1 _) _ =>\n      transl_init_union id ty ty1 il\n  | _, _ =>\n      Error (msg \"wrong type for compound initializer\")\n  end\n\nwith transl_init_array (ty: type) (il: initializer_list) (sz: Z)\n                       {struct il} : res (list init_data) :=\n  match il with\n  | Init_nil =>\n      if zeq sz 0\n      then OK nil\n      else Error (msg \"wrong number of elements in array initializer\")\n  | Init_cons i1 il' =>\n      do d1 <- transl_init ty i1;\n      do d2 <- transl_init_array ty il' (sz - 1);\n      OK (d1 ++ d2)\n  end\n\nwith transl_init_struct (id: ident) (ty: type)\n                        (fl: fieldlist) (il: initializer_list) (pos: Z)\n                        {struct il} : res (list init_data) :=\n  match il, fl with\n  | Init_nil, Fnil =>\n      OK (padding pos (sizeof ty))\n  | Init_cons i1 il', Fcons _ ty1 fl' =>\n      let pos1 := align pos (alignof ty1) in\n      do d1 <- transl_init ty1 i1;\n      do d2 <- transl_init_struct id ty fl' il' (pos1 + sizeof ty1);\n      OK (padding pos pos1 ++ d1 ++ d2)\n  | _, _ =>\n      Error (msg \"wrong number of elements in struct initializer\")\n  end\n\nwith transl_init_union (id: ident) (ty ty1: type) (il: initializer_list)\n                       {struct il} : res (list init_data) :=\n  match il with\n  | Init_nil =>\n      Error (msg \"empty union initializer\")\n  | Init_cons i1 _ =>\n      do d <- transl_init ty1 i1;\n      OK (d ++ padding (sizeof ty1) (sizeof ty))\n  end.\n", "meta": {"author": "clarus", "repo": "phd-experiments", "sha": "159d2cae72c363caa39202a7172356c3c47c2e0a", "save_path": "github-repos/coq/clarus-phd-experiments", "path": "github-repos/coq/clarus-phd-experiments/phd-experiments-159d2cae72c363caa39202a7172356c3c47c2e0a/embedded-compcert/cfrontend/Initializers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20596587796527707}}
{"text": "From VLSM.Lib Require Import Itauto.\nFrom stdpp Require Import prelude finite.\nFrom Coq Require Import FinFun Program.\nFrom VLSM.Lib Require Import Preamble ListExtras.\nFrom VLSM.Core Require Import VLSM VLSMProjections Composition SubProjectionTraces.\nFrom VLSM.Core Require Import Equivocation Equivocation.NoEquivocation.\nFrom VLSM.Core Require Import Equivocators.Equivocators Equivocators.EquivocatorsProjections.\nFrom VLSM.Core Require Import Equivocators.EquivocatorReplay Equivocators.MessageProperties.\nFrom VLSM.Core Require Import Equivocators.EquivocatorsComposition.\nFrom VLSM.Core Require Import Equivocators.EquivocatorsCompositionProjections Plans.\n\n(** * VLSM Equivocator Full Replay Traces\n\n  In this section we show that given a trace of equivocators, one can \"replay\"\n  that at the end of an existing trace, by first equivocating for each initial\n  state and then performing each transition, but appropriately \"shifted\".\n\n  To make the results more general, we take the trace to be replayed to be\n  produced by a restricted set of equivocators pre-loaded with messages\n  satisfying some conditions.\n*)\n\nSection sec_all_equivocating.\n\nContext {message : Type}\n  `{finite.Finite index}\n  (IM : index -> VLSM message)\n  `{forall i : index, HasBeenSentCapability (IM i)}\n  `{forall i : index, HasBeenReceivedCapability (IM i)}\n  (seed : message -> Prop)\n  (equivocating : list index)\n  (equiv_index : Type := sub_index equivocating)\n  (equivocator_descriptors := equivocator_descriptors IM)\n  (equivocators_state_project := equivocators_state_project IM)\n  (equivocator_IM := equivocator_IM IM)\n  (sub_equivocator_IM := sub_IM equivocator_IM equivocating)\n  (sub_IM := sub_IM IM equivocating)\n  (equivocator_descriptors_update := equivocator_descriptors_update IM)\n  (proper_equivocator_descriptors := proper_equivocator_descriptors IM)\n  (equivocators_trace_project := equivocators_trace_project IM)\n  (Free := free_composite_vlsm IM)\n  (FreeE := free_composite_vlsm equivocator_IM)\n  (PreFreeE := pre_loaded_with_all_messages_vlsm FreeE)\n  (FreeSubE := free_composite_vlsm sub_equivocator_IM)\n  (PreFreeSubE := pre_loaded_with_all_messages_vlsm FreeSubE)\n  (SeededXE : VLSM message := seeded_equivocators_no_equivocation_vlsm IM equivocating seed)\n  (equivocators_no_equivocations_vlsm := equivocators_no_equivocations_vlsm IM)\n.\n\n#[local] Hint Unfold equivocator_descriptors_update : state_update.\n\nLemma SeededXE_Free_embedding\n  (Hseed : forall m, seed m -> valid_message_prop FreeE m)\n  : VLSM_embedding SeededXE\n    (composite_vlsm equivocator_IM (free_constraint equivocator_IM))\n    (lift_sub_label equivocator_IM equivocating) (lift_sub_state equivocator_IM equivocating).\nProof.\n  apply basic_VLSM_embedding; intros ? *.\n  - split; [| done].\n    by apply lift_sub_valid, Hv.\n  - by intros [_ Ht]; revert Ht; apply lift_sub_transition.\n  - by intros; apply (lift_sub_state_initial equivocator_IM).\n  - intros; destruct HmX as [Hinit | Hseeded]; [| by apply Hseed].\n    apply initial_message_is_valid.\n    destruct Hinit as [i Him].\n    by exists (proj1_sig i).\nQed.\n\n(**\n  Given a <<base_s>>tate to replay on, the replay label corresponding to a\n  given transition label is obtained as the [equivocator_state_append_label].\n*)\nDefinition lift_equivocators_sub_label_to\n  (base_s : composite_state equivocator_IM)\n  (l : composite_label sub_equivocator_IM)\n  : composite_label equivocator_IM\n  :=\n  let (sub_i, li) := l in\n  let i := proj1_sig sub_i in\n  existT i (equivocator_state_append_label (IM i) (base_s i) li).\n\n(**\n  Given a <<base_s>>tate to replay on, the replay state corresponding to a\n  destination state in a transition by appending its components to the\n  base state using [equivocator_state_append].\n*)\nDefinition lift_equivocators_sub_state_to\n  (base_s : composite_state equivocator_IM)\n  (s : composite_state sub_equivocator_IM)\n  : composite_state equivocator_IM\n  := fun i =>\n    match @decide  (sub_index_prop equivocating i) (sub_index_prop_dec equivocating i) with\n    | left e =>  equivocator_state_append (base_s i) (s (dexist i e))\n    | _ => base_s i\n    end.\n\nLemma lift_equivocators_sub_state_to_sub\n  (base_s : composite_state equivocator_IM)\n  (s : composite_state sub_equivocator_IM)\n  i\n  (Hi : sub_index_prop equivocating i)\n  : lift_equivocators_sub_state_to base_s s i\n      =\n    equivocator_state_append (base_s i) (s (dexist i Hi)).\nProof.\n  unfold lift_equivocators_sub_state_to.\n  case_decide as H_i; [| done].\n  by rewrite (sub_IM_state_pi s H_i Hi).\nQed.\n\nLemma lift_equivocators_sub_state_to_size\n  (base_s : composite_state equivocator_IM)\n  (s : composite_state sub_equivocator_IM)\n  : forall i,\n    equivocator_state_n (base_s i) <= equivocator_state_n (lift_equivocators_sub_state_to base_s s i).\nProof.\n  intro i.\n  unfold lift_equivocators_sub_state_to.\n  destruct (decide _); [| lia].\n  by rewrite equivocator_state_append_size; lia.\nQed.\n\n(** The plan item corresponding to an initial state equivocation. *)\nDefinition initial_new_machine_transition_item\n  (is : composite_state sub_equivocator_IM)\n  (eqv : equiv_index)\n  : composite_plan_item equivocator_IM\n  :=\n  let i := proj1_sig eqv in\n  let seqv := is eqv in\n  let new_l :=\n    (existT i (Spawn (equivocator_state_zero seqv)))\n    in\n  @Build_plan_item message (composite_type equivocator_IM) new_l None.\n\n(** Command for equivocating all states of an initial composite state. *)\nDefinition spawn_initial_state\n  (is : composite_state sub_equivocator_IM)\n  : composite_plan equivocator_IM\n  := map (initial_new_machine_transition_item is) (enum (sub_index equivocating)).\n\nDefinition replayed_initial_state_from full_replay_state is :=\n  fst (composite_apply_plan equivocator_IM full_replay_state (spawn_initial_state is)).\n\n(**\n  The final state obtained after replaying an initial state is precisely\n  the lifting of that initial state over the given base state.\n*)\nLemma replayed_initial_state_from_lift\n  (full_replay_state : composite_state equivocator_IM)\n  (is : composite_state sub_equivocator_IM)\n  (His : composite_initial_state_prop sub_equivocator_IM is)\n  : finite_trace_last full_replay_state (replayed_initial_state_from full_replay_state is)\n    = lift_equivocators_sub_state_to full_replay_state is.\nProof.\n  cut (forall l (Hincl : incl l (enum (sub_index equivocating))) (Hnodup : NoDup l),\n    let tr_full_replay_is :=\n      composite_apply_plan equivocator_IM full_replay_state\n        (map (initial_new_machine_transition_item is)\n          l) in\n    (forall i : index,\n      tr_full_replay_is.2 i =\n      match @decide  (sub_index_prop equivocating i) (sub_index_prop_dec equivocating i) with\n      | left e =>\n        let eqv := (dexist i e) in\n        if (decide (eqv ∈ l)) then equivocator_state_append (full_replay_state i) (is eqv)\n        else full_replay_state i\n      | _ =>  full_replay_state i\n      end)).\n  {\n    intros Hcut; specialize (Hcut _ (incl_refl _) ltac:(apply NoDup_enum)).\n    unfold replayed_initial_state_from, composite_apply_plan.\n    rewrite _apply_plan_last; extensionality i.\n    specialize (Hcut i); unfold composite_apply_plan in Hcut; unfold spawn_initial_state\n    ; simpl in *; rewrite Hcut.\n    unfold lift_equivocators_sub_state_to.\n    case_decide; [| done].\n    rewrite decide_True; [done |].\n    by apply elem_of_enum.\n  }\n  induction l using rev_ind; intros.\n  - case_decide; [| done].\n    by rewrite decide_False; [| inversion 1].\n  - spec IHl; [by apply incl_app_inv in Hincl; apply Hincl |].\n    spec IHl; [by apply NoDup_app in Hnodup; apply Hnodup |].\n    subst tr_full_replay_is.\n    rewrite map_app, (composite_apply_plan_app equivocator_IM); simpl in *\n    ; destruct (composite_apply_plan _ _ _) as (aitems, afinal); simpl in *.\n    specialize (IHl i); destruct_dec_sig x ix Hix Heqx; subst x; simpl in *.\n    case_decide as _Hix; cycle 1;\n      destruct (decide (ix = i)); subst; equivocator_state_update_simpl; [done | done | |].\n    + rewrite decide_False in IHl.\n      * rewrite IHl, decide_True.\n        -- rewrite (sub_IM_state_pi is _Hix Hix); symmetry.\n           by apply equivocator_state_append_singleton_is_extend, (His (dexist i Hix)).\n        -- rewrite elem_of_app, elem_of_list_singleton; right.\n           by apply dsig_eq.\n      * intro Heqv.\n        apply NoDup_app in Hnodup as (_ & Hnodup & _).\n        eapply Hnodup; [done |].\n        rewrite elem_of_list_singleton.\n        by apply dsig_eq.\n    + case_decide.\n      * rewrite decide_True; rewrite ?elem_of_app; itauto.\n      * rewrite decide_False; [done |].\n        intros [Hin | Hx]%elem_of_app; [done |].\n        by rewrite elem_of_list_singleton, dsig_eq in Hx.\nQed.\n\n(**\n  For any [equivocator_descriptors] corresponding to the base state\n  the projection of the replaying of an initial state is empty.\n*)\nLemma equivocators_trace_project_replayed_initial_state_from full_replay_state is\n  (eqv_descriptors : equivocator_descriptors)\n  (Heqv_descriptors : not_equivocating_equivocator_descriptors IM eqv_descriptors full_replay_state)\n  : equivocators_trace_project eqv_descriptors\n      (replayed_initial_state_from full_replay_state is) =\n    Some ([], eqv_descriptors).\nProof.\n  unfold replayed_initial_state_from, spawn_initial_state.\n  generalize (enum (sub_index equivocating)).\n  intro l.\n  remember (composite_apply_plan _ _ _) as plan.\n  apply proj1 with\n    (forall i, equivocator_state_n (full_replay_state i) <= equivocator_state_n (plan.2 i)).\n  subst plan.\n  induction l using rev_ind; [split; simpl; [done | lia] |].\n  rewrite map_app, (composite_apply_plan_app equivocator_IM).\n  destruct (composite_apply_plan _ _ _) as (litems, lfinal) eqn: Hplanl.\n  destruct (composite_apply_plan _ lfinal _) as (aitems, afinal) eqn: Hplana.\n  simpl in *.\n  inversion_clear Hplana.\n  split.\n  - apply equivocators_trace_project_app_iff.\n    exists [], [], eqv_descriptors.\n    repeat split; [| by apply IHl].\n    specialize (Heqv_descriptors (` x)).\n    unfold existing_descriptor in Heqv_descriptors.\n    destruct (eqv_descriptors (` x)) eqn: Heqv_x; [done |].\n    destruct Heqv_descriptors as [s_x_n Heqv_descriptors].\n    apply equivocator_state_project_Some_rev in Heqv_descriptors as Hltn.\n    apply proj2 in IHl.\n    specialize (IHl (` x)).\n    cbn. unfold equivocators_transition_item_project; simpl.\n    unfold equivocator_vlsm_transition_item_project. rewrite Heqv_x.\n    simpl; equivocator_state_update_simpl.\n    rewrite decide_False by lia.\n    destruct_equivocator_state_project (lfinal (` x)) n lfinal_x_n Hltn'; [| lia].\n    by equivocator_state_update_simpl.\n  - intro i. apply proj2 in IHl. specialize (IHl i).\n    by destruct (decide (i = `x)); subst; equivocator_state_update_simpl; [lia |].\nQed.\n\nLemma equivocator_state_project_replayed_initial_state_from_left full_replay_state is\n  (lst := finite_trace_last full_replay_state (replayed_initial_state_from full_replay_state is))\n  : forall i j,\n    j < equivocator_state_n (full_replay_state i) ->\n    equivocator_state_project (lst i) j =\n    equivocator_state_project (full_replay_state i) j.\nProof.\n  subst lst.\n  unfold replayed_initial_state_from, spawn_initial_state.\n  generalize (enum (sub_index equivocating)).\n  intro l.\n  induction l using rev_ind; simpl; [done |].\n  rewrite map_app, (composite_apply_plan_app equivocator_IM).\n  specialize (composite_apply_plan_last equivocator_IM full_replay_state\n    (map (initial_new_machine_transition_item is) l)) as Hlst.\n  destruct (composite_apply_plan _ _ _) as (litems, lfinal) eqn: Hplanl.\n  destruct (composite_apply_plan _ lfinal _) as (aitems, afinal) eqn: Hplana.\n  inversion_clear Hplana.\n  simpl in *.\n  rewrite finite_trace_last_is_last. simpl.\n  intros i j Hj.\n  destruct (decide (`x = i)); subst; equivocator_state_update_simpl; [| by auto].\n  specialize (IHl (` x) j Hj).\n  destruct_equivocator_state_project (full_replay_state (` x)) j s_x_j Hltj; [| lia].\n  rewrite equivocator_state_extend_project_1; [done |].\n  by apply equivocator_state_project_Some_rev in IHl as Hltj'.\nQed.\n\nLemma equivocator_state_descriptor_project_replayed_initial_state_from_left full_replay_state is\n  (eqv_descriptors : equivocator_descriptors)\n  (Heqv_descriptors : not_equivocating_equivocator_descriptors IM eqv_descriptors full_replay_state)\n  (lst := finite_trace_last full_replay_state (replayed_initial_state_from full_replay_state is))\n  : forall i,\n    equivocator_state_descriptor_project (lst i) (eqv_descriptors i) =\n    equivocator_state_descriptor_project (full_replay_state i) (eqv_descriptors i).\nProof.\n  intro i. specialize (Heqv_descriptors i).\n  unfold equivocator_state_descriptor_project.\n  unfold existing_descriptor in Heqv_descriptors.\n  destruct (eqv_descriptors i) as [sn | ji]; [done |].\n  destruct Heqv_descriptors as [full_i_ji Hpr_ji].\n  apply equivocator_state_project_Some_rev in Hpr_ji as Hltji.\n  subst lst.\n  by rewrite equivocator_state_project_replayed_initial_state_from_left, Hpr_ji.\nQed.\n\nDefinition replayed_trace_from full_replay_state is tr :=\n  replayed_initial_state_from full_replay_state is ++\n  pre_VLSM_embedding_finite_trace_project (type FreeSubE) (type FreeE)\n    (lift_equivocators_sub_label_to full_replay_state)\n    (lift_equivocators_sub_state_to full_replay_state) tr.\n\nLemma replayed_trace_from_finite_trace_last full_replay_state is tr\n  (His : composite_initial_state_prop _ is)\n  : finite_trace_last full_replay_state (replayed_trace_from full_replay_state is tr) =\n    (lift_equivocators_sub_state_to full_replay_state (finite_trace_last is tr)).\nProof.\n  destruct_list_last tr tr' item Htr; subst.\n  - unfold replayed_trace_from. cbn.\n    rewrite app_nil_r.\n    by apply replayed_initial_state_from_lift.\n  - unfold replayed_trace_from, pre_VLSM_embedding_finite_trace_project.\n    by rewrite map_app, app_assoc; cbn; rewrite !finite_trace_last_is_last.\nQed.\n\nLemma equivocator_state_project_replayed_trace_from_left full_replay_state is tr\n  (lst := finite_trace_last full_replay_state (replayed_trace_from full_replay_state is tr))\n  : forall i j,\n    j < equivocator_state_n (full_replay_state i) ->\n    equivocator_state_project (lst i) j =\n    equivocator_state_project (full_replay_state i) j.\nProof.\n  subst lst.\n  unfold replayed_trace_from.\n  destruct_list_last tr tr' lst Htr.\n  - simpl. rewrite app_nil_r.\n    by apply equivocator_state_project_replayed_initial_state_from_left.\n  - unfold pre_VLSM_embedding_finite_trace_project.\n    rewrite map_app, app_assoc. simpl.\n    rewrite finite_trace_last_is_last.\n    simpl.\n    intros i j Hltj.\n    unfold lift_equivocators_sub_state_to.\n    destruct (decide _); [| done].\n    by rewrite equivocator_state_append_project_1.\nQed.\n\nLemma equivocator_state_descriptor_project_replayed_trace_from_left full_replay_state is tr\n  (eqv_descriptors : equivocator_descriptors)\n  (Heqv_descriptors : not_equivocating_equivocator_descriptors IM eqv_descriptors full_replay_state)\n  (lst := finite_trace_last full_replay_state (replayed_trace_from full_replay_state is tr))\n  : forall i,\n    equivocator_state_descriptor_project (lst i) (eqv_descriptors i) =\n    equivocator_state_descriptor_project (full_replay_state i) (eqv_descriptors i).\nProof.\n  intro i. specialize (Heqv_descriptors i).\n  unfold equivocator_state_descriptor_project.\n  unfold existing_descriptor in Heqv_descriptors.\n  destruct (eqv_descriptors i) as [sn | ji]; [done |].\n  destruct Heqv_descriptors as [full_i_ji Hpr_ji].\n  apply equivocator_state_project_Some_rev in Hpr_ji as Hltji.\n  subst lst.\n  by rewrite equivocator_state_project_replayed_trace_from_left, Hpr_ji.\nQed.\n\nLemma equivocators_total_state_project_replayed_trace_from full_replay_state is tr\n  (lst := finite_trace_last full_replay_state (replayed_trace_from full_replay_state is tr))\n  : equivocators_total_state_project IM lst = equivocators_total_state_project IM full_replay_state.\nProof.\n  apply functional_extensionality_dep.\n  intro i.\n  apply equivocator_state_descriptor_project_replayed_trace_from_left.\n  by apply zero_descriptor_not_equivocating.\nQed.\n\nLemma equivocators_trace_project_replayed_trace_from_left full_replay_state is tr\n  (eqv_descriptors : equivocator_descriptors)\n  (Heqv_descriptors : not_equivocating_equivocator_descriptors IM eqv_descriptors full_replay_state)\n  : equivocators_trace_project eqv_descriptors\n      (replayed_trace_from full_replay_state is tr) =\n    Some ([], eqv_descriptors).\nProof.\n  apply equivocators_trace_project_app_iff.\n  exists [], [], eqv_descriptors.\n  repeat split; [| by apply equivocators_trace_project_replayed_initial_state_from].\n  induction tr using rev_ind; [done |].\n  unfold pre_VLSM_embedding_finite_trace_project.\n  rewrite map_app.\n  apply equivocators_trace_project_app_iff.\n  exists [], [], eqv_descriptors.\n  repeat split; [| done].\n  clear IHtr.\n  destruct x. simpl.\n  destruct l as (sub_i, li).\n  destruct_dec_sig sub_i i Hi Heqsub_i.\n  subst sub_i.\n  specialize (Heqv_descriptors i).\n  unfold existing_descriptor in Heqv_descriptors.\n  destruct (eqv_descriptors _) eqn: Heqv_l; [done |].\n  destruct Heqv_descriptors as [s_l_n Hs_l_n].\n  apply equivocator_state_project_Some_rev in Hs_l_n as Hltn.\n  specialize (lift_equivocators_sub_state_to_size full_replay_state destination i)\n    as Hltsize.\n  unfold equivocators_transition_item_project. simpl.\n  rewrite Heqv_l.\n  simpl.\n  destruct_equivocator_state_project\n    (lift_equivocators_sub_state_to full_replay_state destination i) n\n    lift_n Hlt_n; [| lia].\n  rewrite (lift_equivocators_sub_state_to_sub) with (Hi := Hi).\n  rewrite equivocator_state_append_lst.\n  by destruct li as [sn_d | id li | id li]; simpl\n  ; rewrite !decide_False by lia\n  ; equivocator_state_update_simpl.\nQed.\n\nLemma equivocators_total_trace_project_replayed_trace_from full_replay_state is tr\n  : equivocators_total_trace_project IM (replayed_trace_from full_replay_state is tr) = [].\nProof.\n  unfold equivocators_total_trace_project.\n  rewrite equivocators_trace_project_replayed_trace_from_left\n  ; [done |].\n  by apply zero_descriptor_not_equivocating.\nQed.\n\nLemma lift_equivocators_sub_valid\n  (full_replay_state : composite_state equivocator_IM)\n  l s om\n  (Hv : composite_valid sub_equivocator_IM l (s, om))\n  : composite_valid equivocator_IM (lift_equivocators_sub_label_to full_replay_state  l)\n      (lift_equivocators_sub_state_to full_replay_state s, om).\nProof.\n  destruct l as (sub_i, li).\n  destruct_dec_sig sub_i i Hi Heqsub_i. subst sub_i.\n  specialize\n    (equivocator_state_append_valid (IM i) li\n      (s (dexist i Hi)) om\n      (full_replay_state i) Hv)\n    as Hlift.\n  cbn.\n  by rewrite (lift_equivocators_sub_state_to_sub _ _ _ Hi).\nQed.\n\nLemma lift_equivocators_sub_transition\n  (full_replay_state : composite_state equivocator_IM)\n  l s om s' om'\n  (Hv : composite_valid sub_equivocator_IM l (s, om))\n  (Ht : composite_transition sub_equivocator_IM l (s, om) = (s', om'))\n  : composite_transition equivocator_IM (lift_equivocators_sub_label_to full_replay_state  l)\n      (lift_equivocators_sub_state_to full_replay_state s, om) =\n      (lift_equivocators_sub_state_to full_replay_state s', om').\nProof.\n  destruct l as (sub_i, li).\n  destruct_dec_sig sub_i i Hi Heqsub_i. subst sub_i.\n  specialize\n    (equivocator_state_append_transition (IM i) li\n      (s (dexist i Hi)) om\n      (s' (dexist i Hi)) om'\n      (full_replay_state i) Hv)\n    as Hlift.\n  cbn in Ht.\n  destruct (equivocator_transition _ _ _) as (_si', _om').\n  inversion Ht; subst s' om'; clear Ht.\n  equivocator_state_update_simpl.\n  specialize (Hlift eq_refl).\n  cbn.\n  rewrite (lift_equivocators_sub_state_to_sub _ _ _ Hi).\n  replace (equivocator_transition _ _ _) with\n    (equivocator_state_append (full_replay_state i) _si', _om').\n  f_equal; extensionality j.\n  destruct (decide (i = j)); subst; equivocator_state_update_simpl.\n  - by rewrite (lift_equivocators_sub_state_to_sub _ _ _ Hi), state_update_eq.\n  - unfold lift_equivocators_sub_state_to.\n    destruct (decide _); [| done].\n    by rewrite state_update_neq; [| inversion 1].\nQed.\n\nSection sec_pre_loaded_constrained_projection.\n\n(**\n  By replaying a [valid_trace] on top of a [valid_state] we obtain a\n  [valid_trace]. We derive this as a more general [VLSM_weak_embedding]\n  result for a class of VLSM parameterized by a constraint having \"good\"\n  properties and pre-loaded with a seed, to allow deriving the\n  [VLSM_weak_embedding] result for both the free composition of equivocators\n  and for the no message equivocation composition of equivocators (free, or with\n  an additional fixed-set state-equivocation constraint).\n*)\n\nContext\n  (constraint :\n    composite_label equivocator_IM -> composite_state equivocator_IM * option message -> Prop)\n  (seed1 : message -> Prop)\n  (SeededCE := pre_loaded_vlsm (composite_vlsm equivocator_IM constraint) seed1)\n  (Hconstraint_none : forall i ns s, i ∈ equivocating -> valid_state_prop SeededCE s ->\n                        constraint (existT i (Spawn ns)) (s, None))\n  (Hseed : forall m, seed m -> valid_message_prop SeededCE m)\n  (full_replay_state : composite_state equivocator_IM)\n  (Hfull_replay_state : valid_state_prop SeededCE full_replay_state)\n  (Hsubsumption : forall l s om, input_valid SeededXE l (s, om) ->\n    valid_state_prop SeededCE (lift_equivocators_sub_state_to full_replay_state s) ->\n    constraint\n      (lift_equivocators_sub_label_to full_replay_state l)\n      (lift_equivocators_sub_state_to full_replay_state s, om))\n  .\n\nLemma replayed_initial_state_from_valid\n  (is : composite_state sub_equivocator_IM)\n  (His : composite_initial_state_prop sub_equivocator_IM is)\n  : finite_valid_trace_from SeededCE full_replay_state\n      (replayed_initial_state_from full_replay_state is).\nProof.\n  cut (forall l, incl l (enum (sub_index equivocating)) ->\n    finite_valid_plan_from SeededCE\n      full_replay_state (map (initial_new_machine_transition_item is) l)).\n  { intros Hplan. specialize (Hplan _ (incl_refl _)).\n    by unfold finite_valid_plan_from in Hplan.\n  }\n  intro l.\n  induction l using rev_ind; intros Hincl.\n  - by constructor.\n  - spec IHl; [by intros i Hi; apply Hincl, in_app_iff; left |].\n    rewrite map_app.\n    apply finite_valid_plan_from_app_iff.\n    split; [done |].\n    apply finite_valid_trace_singleton. simpl.\n    repeat split.\n    + by apply apply_plan_last_valid.\n    + by apply option_valid_message_None.\n    + by apply His.\n    + apply Hconstraint_none.\n      * by destruct_dec_sig x i Hi Hx; subst.\n      * apply finite_valid_trace_last_pstate in IHl.\n        remember (finite_trace_last _ _) as lst.\n        replace ((apply_plan _ _ _).2) with lst; [done |].\n        by subst; apply apply_plan_last.\nQed.\n\nLemma lift_initial_message\n  : forall m, vinitial_message_prop SeededXE m -> valid_message_prop SeededCE m.\nProof.\n  intros m [Hinit | Hseeded].\n  - apply initial_message_is_valid. destruct Hinit as [[i Hi] Hinit].\n    by left; exists i.\n  - by apply Hseed.\nQed.\n\nLemma lift_equivocators_sub_weak_projection :\n  VLSM_weak_embedding SeededXE SeededCE\n    (lift_equivocators_sub_label_to full_replay_state)\n    (lift_equivocators_sub_state_to full_replay_state).\nProof.\n  apply basic_VLSM_weak_embedding; intros ? *.\n  - split.\n    + by apply lift_equivocators_sub_valid, Hv.\n    + by apply Hsubsumption.\n  - by intros Ht; apply lift_equivocators_sub_transition; apply Ht.\n  - intro; rewrite <- replayed_initial_state_from_lift; [| done].\n    by apply finite_valid_trace_last_pstate, replayed_initial_state_from_valid.\n  - by intros; apply lift_initial_message.\nQed.\n\nLemma sub_preloaded_replayed_trace_from_valid_equivocating\n  (is : composite_state sub_equivocator_IM)\n  (tr : list (composite_transition_item sub_equivocator_IM))\n  (Htr : finite_valid_trace SeededXE is tr)\n  : finite_valid_trace_from SeededCE\n      full_replay_state (replayed_trace_from full_replay_state is tr).\nProof.\n  destruct Htr as [Htr His].\n  apply finite_valid_trace_from_app_iff.\n  split; [by apply replayed_initial_state_from_valid |].\n  rewrite replayed_initial_state_from_lift by done.\n  by apply (VLSM_weak_embedding_finite_valid_trace_from lift_equivocators_sub_weak_projection).\nQed.\n\nEnd sec_pre_loaded_constrained_projection.\n\nLemma SeededXE_PreFreeE_weak_embedding\n  (full_replay_state : composite_state equivocator_IM)\n  (Hfull_replay_state : valid_state_prop PreFreeE  full_replay_state)\n  : VLSM_weak_embedding SeededXE PreFreeE\n      (lift_equivocators_sub_label_to full_replay_state)\n      (lift_equivocators_sub_state_to full_replay_state).\nProof.\n  constructor.\n  intros sX trX HtrX.\n  specialize (pre_loaded_with_all_messages_vlsm_is_pre_loaded_with_True FreeE) as Heq.\n  apply (VLSM_eq_finite_valid_trace_from Heq).\n  revert sX trX HtrX.\n  apply lift_equivocators_sub_weak_projection; [done | | | done].\n  - by intros; apply initial_message_is_valid; right.\n  - by apply (VLSM_eq_valid_state Heq) in Hfull_replay_state.\nQed.\n\nLemma PreFreeSubE_PreFreeE_weak_embedding\n  (full_replay_state : composite_state equivocator_IM)\n  (Hfull_replay_state : valid_state_prop PreFreeE  full_replay_state)\n  : VLSM_weak_embedding PreFreeSubE PreFreeE\n      (lift_equivocators_sub_label_to full_replay_state)\n      (lift_equivocators_sub_state_to full_replay_state).\nProof.\n  apply basic_VLSM_weak_embedding; intros ? *.\n  - by split; [apply lift_equivocators_sub_valid; apply Hv |].\n  - by intro Ht; apply lift_equivocators_sub_transition; apply Ht.\n  - intros.\n    rewrite <- replayed_initial_state_from_lift; [| done].\n    apply finite_valid_trace_last_pstate.\n    specialize (pre_loaded_with_all_messages_vlsm_is_pre_loaded_with_True FreeE) as Heq.\n    apply (VLSM_eq_finite_valid_trace_from Heq).\n    apply replayed_initial_state_from_valid; [done | | done].\n    by apply (VLSM_eq_valid_state Heq).\n  - by intros; apply any_message_is_valid_in_preloaded.\nQed.\n\nSection sec_seeded_no_equiv.\n\nContext\n  (SeededAllXE : VLSM message :=\n    composite_no_equivocation_vlsm_with_pre_loaded equivocator_IM (free_constraint _) seed)\n  (full_replay_state : composite_state equivocator_IM)\n  (Hfull_replay_state : valid_state_prop SeededAllXE full_replay_state)\n  .\n\n#[local] Lemma SeededNoEquiv_subsumption :\n  forall l s om, input_valid SeededXE l (s, om) ->\n    no_equivocations_additional_constraint_with_pre_loaded\n      equivocator_IM (free_constraint _) seed\n      (lift_equivocators_sub_label_to full_replay_state l)\n      (lift_equivocators_sub_state_to full_replay_state s, om).\nProof.\n  intros l s om (Hs & _ & _ & Hc1 & _).\n  split; [| done].\n  destruct om as [m |]; [| done].\n  apply (VLSM_incl_valid_state (NoEquivocation.seeded_no_equivocation_incl_preloaded\n    equivocator_IM (free_constraint _) seed)) in Hfull_replay_state.\n  specialize (valid_state_project_preloaded_to_preloaded _ equivocator_IM (free_constraint _)\n    full_replay_state) as Hfull_replay_state_pr.\n  pose (no_equivocations_additional_constraint_with_pre_loaded\n          sub_equivocator_IM (free_constraint sub_equivocator_IM) seed)\n        as constraint.\n  specialize\n    (pre_loaded_vlsm_incl_pre_loaded_with_all_messages\n      (composite_vlsm sub_equivocator_IM constraint)\n      seed) as Hincl.\n  apply (VLSM_incl_valid_state Hincl) in Hs.\n  specialize (valid_state_project_preloaded_to_preloaded _ sub_equivocator_IM constraint s)\n    as Hs_pr.\n  simpl in Hc1.\n  destruct Hc1 as [Hsub_sent | Hseeded]; [| by right].\n  destruct Hsub_sent as [sub_i Hsent].\n  destruct_dec_sig sub_i i Hi Heqsub_i.\n  left. exists i.\n  simpl. rewrite (lift_equivocators_sub_state_to_sub _ _ _ Hi).\n  subst. unfold SubProjectionTraces.sub_IM in Hsent. cbn in Hsent |-*.\n  apply equivocator_state_append_sent_right; [.. | done].\n  - by apply Hfull_replay_state_pr.\n  - by apply (Hs_pr (dexist i Hi) Hs).\nQed.\n\n#[local] Lemma sent_are_valid\n  : forall m, seed m -> valid_message_prop SeededAllXE m.\nProof.\n  by intros m Hm; apply initial_message_is_valid; right.\nQed.\n\n(**\n  Here we specialize the generic [lift_equivocators_sub_weak_projection]\n  result for the [equivocators_no_equivocations_constraint].\n*)\nLemma SeededXE_SeededNoEquiv_weak_embedding :\n  VLSM_weak_embedding SeededXE SeededAllXE\n    (lift_equivocators_sub_label_to full_replay_state)\n    (lift_equivocators_sub_state_to full_replay_state).\nProof.\n  constructor.\n  apply lift_equivocators_sub_weak_projection; intros; [done | | done |].\n  - by apply sent_are_valid.\n  - by apply SeededNoEquiv_subsumption.\nQed.\n\nLemma sub_replayed_trace_from_valid_equivocating\n  (is : composite_state sub_equivocator_IM)\n  (tr : list (composite_transition_item sub_equivocator_IM))\n  (Htr : finite_valid_trace SeededXE is tr)\n  : finite_valid_trace_from SeededAllXE\n      full_replay_state (replayed_trace_from full_replay_state is tr).\nProof.\n  unfold composite_no_equivocation_vlsm_with_pre_loaded in SeededAllXE.\n  specialize (sub_preloaded_replayed_trace_from_valid_equivocating\n    (no_equivocations_additional_constraint_with_pre_loaded equivocator_IM (free_constraint _) seed)\n    seed)\n    as Hvalid.\n  spec Hvalid; [done |].\n  spec Hvalid; [by apply sent_are_valid |].\n  specialize (Hvalid _ Hfull_replay_state).\n  apply Hvalid; [| done].\n  by intros; apply SeededNoEquiv_subsumption.\nQed.\n\nEnd sec_seeded_no_equiv.\n\nEnd sec_all_equivocating.\n", "meta": {"author": "runtimeverification", "repo": "vlsm", "sha": "9115beb539257427467872ce65a224a0268cdae7", "save_path": "github-repos/coq/runtimeverification-vlsm", "path": "github-repos/coq/runtimeverification-vlsm/vlsm-9115beb539257427467872ce65a224a0268cdae7/theories/VLSM/Core/Equivocators/FullReplayTraces.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.3451052844289767, "lm_q1q2_score": 0.20583223058452302}}
{"text": "Require Import VST.floyd.base.\nRequire Import VST.floyd.val_lemmas.\nRequire Import VST.floyd.typecheck_lemmas.\n\nDefinition const_only_isUnOpResultType {CS: compspecs} op typeof_a valueof_a ty : bool :=\nmatch op with\n  | Cop.Onotbool => match typeof_a with\n                    | Tint _ _ _\n                    | Tlong _ _\n                    | Tfloat _ _ => is_int_type ty\n                    | Tpointer _ _ =>\n                        if Archi.ptr64 \n                        then match valueof_a with\n                             | Vlong v =>\n                                andb (negb (eqb_type (typeof_a) int_or_ptr_type))\n                                     (andb (is_int_type ty) (Z.eqb 0 (Int64.unsigned v)))\n                             | _ => false\n                             end\n                        else match valueof_a with\n                             | Vint v => \n                                andb (negb (eqb_type typeof_a int_or_ptr_type))\n                                     (andb (is_int_type ty) (Z.eqb 0 (Int.unsigned v)))\n                             | _ => false\n                             end\n                    | _ => false\n                    end\n  | Cop.Onotint => match Cop.classify_notint (typeof_a) with\n                   | Cop.notint_default => false\n                   | Cop.notint_case_i _ => (is_int32_type ty)\n                   | Cop.notint_case_l _ => (is_long_type ty)\n                   end\n  | Cop.Oneg => match Cop.classify_neg (typeof_a) with\n                    | Cop.neg_case_i sg => \n                          andb (is_int32_type ty)\n                          match (typeof_a) with\n                          | Tint _ Signed _ =>\n                            match valueof_a with\n                            | Vint v => negb (Z.eqb (Int.signed v) Int.min_signed)\n                            | _ => false\n                            end\n                          | Tlong Signed _ =>\n                            match valueof_a with\n                            | Vlong v => negb (Z.eqb (Int64.signed v) Int64.min_signed)\n                            | _ => false\n                            end\n                          | _ => true\n                          end\n                    | Cop.neg_case_f => is_float_type ty\n                    | Cop.neg_case_s => is_single_type ty\n                    | _ => false\n                    end\n  | Cop.Oabsfloat =>match Cop.classify_neg (typeof_a) with\n                    | Cop.neg_case_i sg => is_float_type ty\n                    | Cop.neg_case_l _ => is_float_type ty\n                    | Cop.neg_case_f => is_float_type ty\n                    | Cop.neg_case_s => is_float_type ty\n                    | _ => false\n                    end\nend.\n\n(* TODO: binarithType would better be bool type *)\nDefinition const_only_isBinOpResultType {CS: compspecs} op typeof_a1 valueof_a1 typeof_a2 valueof_a2 ty : bool :=\n  match op with\n  | Cop.Oadd =>\n      match Cop.classify_add (typeof_a1) (typeof_a2) with\n      | Cop.add_case_pi t _ | Cop.add_case_pl t =>\n        andb\n          (andb\n             (andb (match valueof_a1 with Vptr _ _ => true | _ => false end) (complete_type cenv_cs t))\n             (negb (eqb_type (typeof_a1) int_or_ptr_type)))\n          (is_pointer_type ty)\n    | Cop.add_case_ip _ t | Cop.add_case_lp t =>\n        andb\n          (andb\n             (andb (match valueof_a2 with Vptr _ _ => true | _ => false end) (complete_type cenv_cs t))\n             (negb (eqb_type (typeof_a2) int_or_ptr_type)))\n          (is_pointer_type ty)\n    | Cop.add_default => false\n                           (*\n        andb (binarithType (typeof a1) (typeof a2) ty deferr reterr)\n          (tc_nobinover Z.add a1 a2) *)\n      end\n  | _ => false (* TODO *)\n  end.\n\nDefinition const_only_isCastResultType {CS: compspecs} (t1 t2: type) (valueof_a: val)  : bool := false. (* TODO *)\n\nFixpoint const_only_eval_expr {cs: compspecs} (e: Clight.expr): option val :=\n  match e with\n  | Econst_int i (Tint I32 _ _) => Some (Vint i)\n  | Econst_int _ _ => None\n  | Econst_long i ty => None (*Some (Vlong i) *)\n  | Econst_float f (Tfloat F64 _) => Some (Vfloat f)\n  | Econst_float _ _ => None\n  | Econst_single f (Tfloat F32 _) => Some (Vsingle f)\n  | Econst_single _ _ => None\n  | Etempvar id ty => None\n  | Evar _ _ => None\n  | Eaddrof a ty => None\n  | Eunop op a ty =>\n      match const_only_eval_expr a with\n      | Some v => if const_only_isUnOpResultType op (typeof a) v ty\n                  then Some (eval_unop op (typeof a) v)\n                  else None\n      | None => None\n      end\n  | Ebinop op a1 a2 ty =>\n      match (const_only_eval_expr a1), (const_only_eval_expr a2) with\n      | Some v1, Some v2 =>\n          if const_only_isBinOpResultType op (typeof a1) v1 (typeof a2) v2 ty\n          then Some (eval_binop op (typeof a1) (typeof a2) v1 v2)\n          else None\n      | _, _ => None\n      end\n  | Ecast a ty =>\n      match const_only_eval_expr a with\n      | Some v => if const_only_isCastResultType (typeof a) ty v\n                  then Some (eval_cast (typeof a) ty v)\n                  else None\n      | None => None\n      end\n  | Ederef a ty => None\n  | Efield a i ty => None\n  | Esizeof t t0 =>\n    if andb (complete_type cenv_cs t) (eqb_type t0 size_t)\n    then Some (Vptrofs (Ptrofs.repr (sizeof t)))\n    else None\n  | Ealignof t t0 =>\n    if andb (complete_type cenv_cs t) (eqb_type t0 size_t)\n    then Some (Vptrofs (Ptrofs.repr (alignof t)))\n    else None\n  end.\n\nLemma const_only_isUnOpResultType_spec: forall {cs: compspecs} rho u e t P,\n  const_only_isUnOpResultType u (typeof e) (eval_expr e rho) t = true ->\n  P |-- denote_tc_assert (isUnOpResultType u e t) rho.\nProof.\n  intros.\n  unfold isUnOpResultType.\n  unfold const_only_isUnOpResultType in H.\n  destruct u.\n  + destruct (typeof e);\n      try solve [inv H | rewrite H; exact (@prop_right mpred _ True _ I)].\n    rewrite !denote_tc_assert_andp.\n    match goal with\n    | |- context [denote_tc_assert (tc_test_eq ?a ?b)] =>\n      change (denote_tc_assert (tc_test_eq a b)) with (expr2.denote_tc_assert (tc_test_eq a b))\n    end.\n    rewrite binop_lemmas2.denote_tc_assert_test_eq'.\n    simpl expr2.denote_tc_assert.\n    unfold_lift. simpl.\n    unfold tc_int_or_ptr_type.\n    destruct Archi.ptr64 eqn:HH.\n    - destruct (eval_expr e rho); try solve [inv H].\n      rewrite !andb_true_iff in H.\n      destruct H as [? [? ?]].\n      rewrite H, H0.\n      rewrite Z.eqb_eq in H1.\n      apply andp_right; [exact (@prop_right mpred _ True _ I) |].\n      apply andp_right; [exact (@prop_right mpred _ True _ I) |].\n      simpl.\n      rewrite HH.\n      change (P |-- (!! (i = Int64.zero)) && (!! (Int64.zero = Int64.zero)))%logic.\n      apply andp_right; apply prop_right; auto.\n      rewrite <- (Int64.repr_unsigned i), <- H1.\n      auto.\n    - destruct (eval_expr e rho); try solve [inv H].\n      rewrite !andb_true_iff in H.\n      destruct H as [? [? ?]].\n      rewrite H, H0.\n      rewrite Z.eqb_eq in H1.\n      apply andp_right; [exact (@prop_right mpred _ True _ I) |].\n      apply andp_right; [exact (@prop_right mpred _ True _ I) |].\n      simpl.\n      rewrite HH.\n      change (P |-- (!! (i = Int.zero)) && (!! (Int.zero = Int.zero)))%logic.\n      apply andp_right; apply prop_right; auto.\n      rewrite <- (Int.repr_unsigned i), <- H1.\n      auto.\n  + destruct (Cop.classify_notint (typeof e));\n      try solve [inv H | rewrite H; exact (@prop_right mpred _ True _ I)].\n  + destruct (Cop.classify_neg (typeof e));\n      try solve [inv H | rewrite H; exact (@prop_right mpred _ True _ I)].\n    rewrite !andb_true_iff in H.\n    destruct H.\n    rewrite H; simpl.\n    destruct (typeof e) as [| ? [|] | [|] | | | | | |];\n      try solve [exact (@prop_right mpred _ True _ I)].\n    - simpl.\n      unfold_lift.\n      unfold denote_tc_nosignedover.\n      destruct (eval_expr e rho); try solve [inv H0].\n      rewrite negb_true_iff in H0.\n      rewrite Z.eqb_neq in H0.\n      apply prop_right.\n      change (Int.signed Int.zero) with 0.\n      rep_omega.\n    - simpl.\n      unfold_lift.\n      unfold denote_tc_nosignedover.\n      destruct (eval_expr e rho); try solve [inv H0].\n      rewrite negb_true_iff in H0.\n      rewrite Z.eqb_neq in H0.\n      apply prop_right.\n      change (Int64.signed Int64.zero) with 0.\n      rep_omega.\n  + destruct (Cop.classify_neg (typeof e)); try solve [inv H | rewrite H; exact (@prop_right mpred _ True _ I)].\nQed.\n\nLemma const_only_isBinOpResultType_spec: forall {cs: compspecs} rho b e1 e2 t P,\n  const_only_isBinOpResultType b (typeof e1) (eval_expr e1 rho) (typeof e2) (eval_expr e2 rho) t = true ->\n  P |-- denote_tc_assert (isBinOpResultType b e1 e2 t) rho.\nProof.\n  intros.\n  unfold isBinOpResultType.\n  unfold const_only_isBinOpResultType in H.\n  destruct b.\n  + destruct (Cop.classify_add (typeof e1) (typeof e2)).\n    - rewrite !denote_tc_assert_andp; simpl.\n      unfold_lift.\n      unfold tc_int_or_ptr_type, denote_tc_isptr.\n      destruct (eval_expr e1 rho); inv H.\n      rewrite !andb_true_iff in H1.\n      destruct H1 as [[? ?] ?].\n      rewrite H, H0, H1.\n      simpl.\n      repeat apply andp_right; apply prop_right; auto.\n    - rewrite !denote_tc_assert_andp; simpl.\n      unfold_lift.\n      unfold tc_int_or_ptr_type, denote_tc_isptr.\n      destruct (eval_expr e1 rho); inv H.\n      rewrite !andb_true_iff in H1.\n      destruct H1 as [[? ?] ?].\n      rewrite H, H0, H1.\n      simpl.\n      repeat apply andp_right; apply prop_right; auto.\n    - rewrite !denote_tc_assert_andp; simpl.\n      unfold_lift.\n      unfold tc_int_or_ptr_type, denote_tc_isptr.\n      destruct (eval_expr e2 rho); inv H.\n      rewrite !andb_true_iff in H1.\n      destruct H1 as [[? ?] ?].\n      rewrite H, H0, H1.\n      simpl.\n      repeat apply andp_right; apply prop_right; auto.\n    - rewrite !denote_tc_assert_andp; simpl.\n      unfold_lift.\n      unfold tc_int_or_ptr_type, denote_tc_isptr.\n      destruct (eval_expr e2 rho); inv H.\n      rewrite !andb_true_iff in H1.\n      destruct H1 as [[? ?] ?].\n      rewrite H, H0, H1.\n      simpl.\n      repeat apply andp_right; apply prop_right; auto.\n    - inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\n  + inv H.\nQed.\n\nLemma const_only_isCastResultType_spec: forall {cs: compspecs} rho e t P,\n  const_only_isCastResultType (typeof e) t (eval_expr e rho) = true ->\n  P |-- denote_tc_assert (isCastResultType (typeof e) t e) rho.\nProof.\n  intros.\n  inv H.\nQed.\n\nLemma const_only_eval_expr_eq: forall {cs: compspecs} rho e v,\n  const_only_eval_expr e = Some v ->\n  eval_expr e rho = v.  \nProof.\n  intros.\n  revert v H; induction e; try solve [intros; inv H; auto].\n  + intros.\n    simpl in *.\n    destruct t as [| [| | |] | | | | | | |]; inv H.\n    auto.\n  + intros.\n    simpl in *.\n    destruct t as [| | | [|] | | | | |]; inv H.\n    auto.\n  + intros.\n    simpl in *.\n    destruct t as [| | | [|] | | | | |]; inv H.\n    auto.\n  + intros.\n    simpl in *.\n    unfold option_map in H.\n    destruct (const_only_eval_expr e); inv H.\n    destruct (const_only_isUnOpResultType u (typeof e) v0 t); inv H1.\n    specialize (IHe _ eq_refl).\n    unfold_lift.\n    rewrite IHe; auto.\n  + intros.\n    simpl in *.\n    unfold option_map in H.\n    destruct (const_only_eval_expr e1); inv H.\n    destruct (const_only_eval_expr e2); inv H1.\n    destruct (const_only_isBinOpResultType b (typeof e1) v0 (typeof e2) v1 t); inv H0.\n    specialize (IHe1 _ eq_refl).\n    specialize (IHe2 _ eq_refl).\n    unfold_lift.\n    rewrite IHe1, IHe2; auto.\n  + intros.\n    simpl in *.\n    unfold option_map in H.\n    destruct (const_only_eval_expr e); inv H. (*\n    specialize (IHe _ eq_refl).\n    unfold_lift.\n    rewrite IHe; auto.*)\n  + intros.\n    simpl in *.\n    destruct (complete_type cenv_cs t && eqb_type t0 size_t); inv H.\n    auto.\n  + intros.\n    simpl in *.\n    destruct (complete_type cenv_cs t && eqb_type t0 size_t); inv H.\n    auto.\nQed.\n\nLemma const_only_eval_expr_tc: forall {cs: compspecs} Delta e v P,\n  const_only_eval_expr e = Some v ->\n  P |-- tc_expr Delta e.\nProof.\n  intros.\n  intro rho.\n  revert v H; induction e; try solve [intros; inv H].\n  + intros.\n    inv H.\n    destruct t as [| [| | |] | | | | | | |]; inv H1.\n    exact (@prop_right mpred _ True _ I).\n  + intros.\n    inv H.\n    destruct t as [| | | [|] | | | | |]; inv H1.\n    exact (@prop_right mpred _ True _ I).\n  + intros.\n    inv H.\n    destruct t as [| | | [|] | | | | |]; inv H1.\n    exact (@prop_right mpred _ True _ I).\n  + intros.\n    unfold tc_expr in *.\n    simpl in *.\n    unfold option_map in H.\n    destruct (const_only_eval_expr e) eqn:HH; inv H.\n    specialize (IHe _ eq_refl).\n    unfold_lift.\n    rewrite denote_tc_assert_andp; simpl; apply andp_right; auto.\n    apply const_only_isUnOpResultType_spec.\n    apply (const_only_eval_expr_eq rho) in HH.\n    rewrite HH.\n    destruct (const_only_isUnOpResultType u (typeof e) v0 t); inv H1; auto.\n  + intros.\n    unfold tc_expr in *.\n    simpl in *.\n    unfold option_map in H.\n    destruct (const_only_eval_expr e1) eqn:HH1; inv H.\n    destruct (const_only_eval_expr e2) eqn:HH2; inv H1.\n    specialize (IHe1 _ eq_refl).\n    specialize (IHe2 _ eq_refl).\n    unfold_lift.\n    rewrite !denote_tc_assert_andp; simpl; repeat apply andp_right; auto.\n    apply const_only_isBinOpResultType_spec.\n    apply (const_only_eval_expr_eq rho) in HH1.\n    apply (const_only_eval_expr_eq rho) in HH2.\n    rewrite HH1, HH2.\n    destruct (const_only_isBinOpResultType b (typeof e1) v0 (typeof e2) v1 t); inv H0; auto.\n  + intros.\n    unfold tc_expr in *.\n    simpl in *.\n    unfold option_map in H.\n    destruct (const_only_eval_expr e) eqn:HH; inv H. (*\n    specialize (IHe _ eq_refl).\n    unfold_lift.\n    rewrite denote_tc_assert_andp; simpl; apply andp_right; auto.\n    apply const_only_isUnOpResultType_spec.\n    apply (const_only_eval_expr_eq rho) in HH. *)\n  + intros.\n    inv H.\n    unfold tc_expr.\n    simpl typecheck_expr.\n    simpl.\n    destruct (complete_type cenv_cs t && eqb_type t0 size_t) eqn:HH; inv H1.\n    rewrite andb_true_iff in HH.\n    unfold tuint in HH; destruct HH.\n    rewrite H, H0.\n    exact (@prop_right mpred _ True _ I).\n  + intros.\n    inv H.\n    unfold tc_expr.\n    simpl typecheck_expr.\n    simpl.\n    destruct (complete_type cenv_cs t && eqb_type t0 size_t) eqn:HH; inv H1.\n    rewrite andb_true_iff in HH.\n    unfold tuint in HH; destruct HH.\n    rewrite H, H0.\n    exact (@prop_right mpred _ True _ I).\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/floyd/const_only_eval.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.33458945452352534, "lm_q1q2_score": 0.20580191006116566}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.odd.\nRequire Import VST.progs.verif_evenodd_spec.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\n\nDefinition Gprog : funspecs :=\n     ltac:(with_library prog [odd_spec; even_spec]).\n\nLemma body_odd : semax_body Vprog Gprog f_odd odd_spec.\nProof.\nstart_function.\nchange even._n with _n.\nforward_if.\n*\n forward.\n*\n  forward_call (z-1).\n  omega.\n  forward.\n  entailer!.\n  rewrite Z.even_sub; simpl.\n  case_eq (Z.odd z); rewrite Zodd_even_bool;\n  destruct (Z.even z); simpl; try (intros; congruence).\nQed.\n\n(* The Espec for odd is different from the Espec for even;\n  the former has only \"even\" as an external function, and vice versa. *)\nDefinition Espec := add_funspecs NullExtension.Espec (ext_link_prog odd.prog) Gprog.\nExisting Instance Espec.\n\n(* Can't prove   prog_correct: semax_prog prog Vprog Gprog\n  because there is no _main function, so prove all_funcs_correct instead. *)\nLemma all_funcs_correct:\n  semax_func Vprog Gprog (prog_funct prog) Gprog.\nProof.\nrepeat (apply semax_func_cons_ext_vacuous; [reflexivity | reflexivity | ]).\nsemax_func_cons_ext.\nsemax_func_cons body_odd.\nQed.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/progs/verif_odd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.20576585732583152}}
{"text": "From stbor.lang Require Export defs.\n\nSet Default Proof Using \"Type\".\n\nDefinition tagged_sublist (stk1 stk2: stack) :=\n  ∀ it1, it1 ∈ stk1 → ∃ it2,\n  it2 ∈ stk2 ∧ it1.(tg) = it2.(tg) ∧ it1.(protector) = it2.(protector) ∧\n  (it1.(perm) ≠ Disabled → it2.(perm) = it1.(perm)).\nInstance tagged_sublist_preorder : PreOrder tagged_sublist.\nProof.\n  constructor.\n  - intros ??. naive_solver.\n  - move => ??? H1 H2 ? /H1 [? [/H2 Eq [-> [-> ND]]]].\n    destruct Eq as (it2 &?&?&?&ND2). exists it2. repeat split; auto.\n    intros ND3. specialize (ND ND3). rewrite ND2 // ND //.\nQed.\n\nInstance tagged_sublist_proper stk : Proper ((⊆) ==> impl) (tagged_sublist stk).\nProof. move => ?? SUB H1 ? /H1 [? [/SUB ? ?]]. naive_solver. Qed.\n\nLemma tagged_sublist_app l1 l2 k1 k2 :\n  tagged_sublist l1 l2 → tagged_sublist k1 k2 →\n  tagged_sublist (l1 ++ k1) (l2 ++ k2).\nProof.\n  move => H1 H2 it. setoid_rewrite elem_of_app.\n  move => [/H1|/H2]; naive_solver.\nQed.\n\nLemma remove_check_tagged_sublist cids stk stk' idx:\n  remove_check cids stk idx = Some stk' → tagged_sublist stk' stk.\nProof.\n  revert idx.\n  induction stk as [|it stk IH]; intros idx; simpl.\n  { destruct idx; [|done]. intros. by simplify_eq. }\n  destruct idx as [|idx]; [intros; by simplify_eq|].\n  case check_protector eqn:Eq; [|done].\n  move => /IH. apply tagged_sublist_proper. set_solver.\nQed.\n\nLemma replace_check'_tagged_sublist cids acc stk stk':\n  replace_check' cids acc stk = Some stk' → tagged_sublist stk' (acc ++ stk).\nProof.\n  revert acc.\n  induction stk as [|it stk IH]; intros acc; simpl.\n  { intros. simplify_eq. by rewrite app_nil_r. }\n  case decide => ?; [case check_protector; [|done]|];\n    move => /IH; [|by rewrite -app_assoc].\n  move => H1 it1 /H1 [it2 [IN2 [Eq1 [Eq2 ND]]]].\n  setoid_rewrite elem_of_app. setoid_rewrite elem_of_cons.\n  move : IN2 => /elem_of_app [/elem_of_app [?|/elem_of_list_singleton Eq]|?];\n    [..|naive_solver].\n  - exists it2. naive_solver.\n  - subst it2. exists it. naive_solver.\nQed.\n\nLemma replace_check_tagged_sublist cids stk stk':\n  replace_check cids stk = Some stk' → tagged_sublist stk' stk.\nProof. move => /replace_check'_tagged_sublist. by rewrite app_nil_l. Qed.\n\n\n(** NoDup for tagged item *)\nLemma stack_item_tagged_NoDup_singleton it:\n  stack_item_tagged_NoDup [it].\nProof.\n  rewrite /stack_item_tagged_NoDup filter_cons filter_nil.\n  case decide => ? /=. apply NoDup_singleton. apply NoDup_nil_2.\nQed.\n\nLemma stack_item_tagged_NoDup_cons_1 it stk :\n  stack_item_tagged_NoDup (it :: stk) → stack_item_tagged_NoDup stk.\nProof.\n  rewrite /stack_item_tagged_NoDup filter_cons.\n  case decide => [NT|IT //]. rewrite fmap_cons. by apply NoDup_cons_12.\nQed.\n\nLemma stack_item_tagged_NoDup_sublist stk1 stk2:\n  sublist stk1 stk2 → stack_item_tagged_NoDup stk2 → stack_item_tagged_NoDup stk1.\nProof.\n  intros SUB. rewrite /stack_item_tagged_NoDup.\n  by apply NoDup_sublist, fmap_sublist, filter_sublist.\nQed.\n\nLemma replace_check'_stack_item_tagged_NoDup cids acc stk stk':\n  replace_check' cids acc stk = Some stk' →\n  stack_item_tagged_NoDup (acc ++ stk) → stack_item_tagged_NoDup stk'.\nProof.\n  revert acc.\n  induction stk as [|it stk IH]; intros acc; simpl.\n  { intros ?. simplify_eq. by rewrite app_nil_r. }\n  case decide => ?; [case check_protector; [|done]|];\n    move => /IH; [|by rewrite -app_assoc].\n  move => IH1 ND. apply IH1. clear IH1. move : ND.\n  rewrite /stack_item_tagged_NoDup 3!filter_app 2!filter_cons.\n  case decide => [IT|NT].\n  - by rewrite decide_True // 3!fmap_app 2!fmap_cons /= -assoc.\n  - by rewrite decide_False // /= filter_nil app_nil_r.\nQed.\n\nLemma replace_check'_stack_item_tagged_NoDup_2 cids acc stk stk' stk0:\n  replace_check' cids acc stk = Some stk' →\n  stack_item_tagged_NoDup (acc ++ stk ++ stk0) → stack_item_tagged_NoDup (stk' ++ stk0).\nProof.\n  revert acc.\n  induction stk as [|it stk IH]; intros acc; simpl.\n  { intros ?. by simplify_eq. }\n  case decide => ?; [case check_protector; [|done]|];\n    move => /IH; [|rewrite (app_assoc acc [it] (stk ++ stk0)); naive_solver].\n  move => IH1 ND. apply IH1. clear IH1. move : ND.\n  rewrite /stack_item_tagged_NoDup 3!filter_app 2!filter_cons.\n  case decide => [IT|NT].\n  - by rewrite decide_True // 3!fmap_app 2!fmap_cons /= -assoc.\n  - by rewrite decide_False // /= filter_nil app_nil_r.\nQed.\n\nLemma replace_check_stack_item_tagged_NoDup cids stk stk' :\n  replace_check cids stk = Some stk' →\n  stack_item_tagged_NoDup stk → stack_item_tagged_NoDup stk'.\nProof. intros. eapply replace_check'_stack_item_tagged_NoDup; eauto. Qed.\n\nLemma replace_check_stack_item_tagged_NoDup_2 cids stk stk' stk0:\n  replace_check cids stk = Some stk' →\n  stack_item_tagged_NoDup (stk ++ stk0) → stack_item_tagged_NoDup (stk' ++ stk0).\nProof. intros; eapply replace_check'_stack_item_tagged_NoDup_2; eauto. Qed.\n\nLemma replace_check'_acc_result cids acc stk stk' :\n  replace_check' cids acc stk = Some stk' → acc ⊆ stk'.\nProof.\n  revert acc.\n  induction stk as [|it stk IH]; intros acc; simpl; [by intros; simplify_eq|].\n  case decide => ?; [case check_protector; [|done]|];\n    move => /IH; set_solver.\nQed.\n\nLemma remove_check_stack_item_tagged_NoDup cids stk stk' idx:\n  remove_check cids stk idx = Some stk' →\n  stack_item_tagged_NoDup stk → stack_item_tagged_NoDup stk'.\nProof.\n  revert idx.\n  induction stk as [|it stk IH]; intros idx; simpl.\n  { destruct idx; [|done]. intros ??. by simplify_eq. }\n  destruct idx as [|idx]; [intros ??; by simplify_eq|].\n  case check_protector eqn:Eq; [|done].\n  move => /IH IH' ND. apply IH'. by eapply stack_item_tagged_NoDup_cons_1.\nQed.\n\nLemma remove_check_stack_item_tagged_NoDup_2 cids stk stk' stk0 idx:\n  remove_check cids stk idx = Some stk' →\n  stack_item_tagged_NoDup (stk ++ stk0) → stack_item_tagged_NoDup (stk' ++ stk0).\nProof.\n  revert idx.\n  induction stk as [|it stk IH]; intros idx; simpl.\n  { destruct idx; [|done]. intros ??. by simplify_eq. }\n  destruct idx as [|idx]; [intros ??; by simplify_eq|].\n  case check_protector eqn:Eq; [|done].\n  move => /IH IH' ND. apply IH'. by eapply stack_item_tagged_NoDup_cons_1.\nQed.\n\nLemma remove_check_sublist cids stk idx stk' :\n  remove_check cids stk idx = Some stk' → sublist stk' stk.\nProof.\n  revert idx.\n  induction stk as [|it stk IH]; intros idx; simpl.\n  { destruct idx; [|done]. intros ?. by simplify_eq. }\n  destruct idx as [|idx]; [intros ?; by simplify_eq|].\n  case check_protector eqn:Eq; [|done].\n  move => /IH IH'. by constructor 3.\nQed.\n\nLemma stack_item_tagged_NoDup_app stk1 stk2 :\n  stack_item_tagged_NoDup (stk1 ++ stk2) →\n  stack_item_tagged_NoDup stk1 ∧ stack_item_tagged_NoDup stk2.\nProof. rewrite /stack_item_tagged_NoDup filter_app fmap_app NoDup_app. naive_solver. Qed.\n\nInstance stack_item_tagged_NoDup_proper :\n  Proper (Permutation ==> iff) stack_item_tagged_NoDup.\nProof. intros stk1 stk2 PERM. by rewrite /stack_item_tagged_NoDup PERM. Qed.\n\nLemma stack_item_tagged_NoDup_eq stk it1 it2 t :\n  stack_item_tagged_NoDup stk →\n  it1 ∈ stk → it2 ∈ stk → it1.(tg) = Tagged t → it2.(tg) = Tagged t →\n  it1 = it2.\nProof.\n  induction stk as [|it stk IH]; [set_solver|].\n  intros ND. specialize (IH (stack_item_tagged_NoDup_cons_1 _ _ ND)).\n  rewrite 2!elem_of_cons.\n  move => [?|In1] [?|In2]; subst; [done|..]; intros Eq1 Eq2.\n  - exfalso. apply elem_of_Permutation in In2 as [stk' Eq'].\n    move : ND. rewrite Eq'.\n    rewrite /stack_item_tagged_NoDup filter_cons decide_True; last by rewrite /is_tagged Eq1.\n    rewrite filter_cons decide_True; last by rewrite /is_tagged Eq2.\n    rewrite 2!fmap_cons Eq1 Eq2 NoDup_cons. set_solver.\n  - exfalso. apply elem_of_Permutation in In1 as [stk' Eq'].\n    move : ND. rewrite Eq'.\n    rewrite /stack_item_tagged_NoDup filter_cons decide_True; last by rewrite /is_tagged Eq2.\n    rewrite filter_cons decide_True; last by rewrite /is_tagged Eq1.\n    rewrite 2!fmap_cons Eq1 Eq2 NoDup_cons. set_solver.\n  - by apply IH.\nQed.\n", "meta": {"author": "ocecaco", "repo": "stacked-borrows", "sha": "92090a71d2cb61887b8d037fff6fe13a0199e3c5", "save_path": "github-repos/coq/ocecaco-stacked-borrows", "path": "github-repos/coq/ocecaco-stacked-borrows/stacked-borrows-92090a71d2cb61887b8d037fff6fe13a0199e3c5/theories/lang/steps_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2057658573258315}}
{"text": "Require Export DEX_ElemLemmas.\n\nImport DEX_BigStepWithTypes.DEX_BigStepWithTypes DEX_BigStep.DEX_Dom DEX_Prog.\n\nSection p.\n\nVariable kobs: L.t.\nVariable p:DEX_ExtendedProgram.\nVariable se : DEX_PC -> L.t.\nVariable reg : DEX_PC -> DEX_PC -> Prop.\nVariable m : DEX_Method.\nVariable lookupswitch_hyp : well_formed_lookupswitch m.\n\nLtac soap2_intra_normal_aux Hreg_in H Hreg r lvl Hget_ori Hvalue_opt_in k k':=\n  specialize Hreg_in with r;\n  inversion Hreg_in as [k k' Hget Hget' Hleq Hleq'| Hvalue_opt_in];\n  try (apply H in Hreg; apply leql_join_each in Hreg; inversion Hreg as [Hleql1 Hleql1'];\n    apply not_leql_trans with (k2:=lvl) in Hleq; auto);\n  try (apply H in Hreg; apply not_leql_trans with (k2:=lvl) in Hleq; auto);\n  try (rewrite Hget in Hget_ori; inversion Hget_ori; subst; auto).\n\n(* High Branching *)\nLemma soap2_intra_normal : \n forall sgn pc pc2 pc2' i r1 rt1 h1 b1 r1' rt1' h1' b1' r2 rt2 h2 b2 r2' rt2' h2' b2',\n   instructionAt m pc = Some i ->\n   NormalStep kobs p se reg m sgn i (pc,(h1,r1)) rt1 b1 (pc2,(h2,r2)) rt2 b2 ->\n   NormalStep kobs p se reg m sgn i (pc,(h1',r1')) rt1' b1' (pc2',(h2',r2')) rt2' b2' ->\n   pc2 <> pc2' ->\n   st_in kobs (DEX_ft p) b1 b1' rt1 rt1' (pc,h1,r1) (pc,h1',r1') ->\n\n    forall j, reg pc j -> ~ L.leql (se j) kobs.\nProof.\n  intros sgn pc pc2 pc2' i r1 rt1 h1 b1 r1' rt1' h1' b1' r2 rt2 h2 b2 r2' rt2' h2' b2' Hins Hstep Hstep' Hpc Hst_in j Hreg.\n  destruct i; simpl in Hins, Hstep, Hstep', Hst_in; \n  inversion_clear Hstep in Hins Hstep' Hpc Hst_in;\n  inversion_clear Hstep' in Hpc Hst_in; subst;\n  apply inv_st_in in Hst_in;\n  DiscrimateEq; try (elim Hpc; reflexivity); try (contradiction).\n  (* PackedSwitch *)\n  inversion Hst_in as [Heqset Hreg_in].\n    soap2_intra_normal_aux Hreg_in H4 Hreg rt (se j) H0 Hvalue_opt_in k1 k1'.\n    (* both are low *)\n    rewrite <- H in Hvalue_opt_in; rewrite <- H5 in Hvalue_opt_in;\n      inversion Hvalue_opt_in as [v v' Hvalue_in | Hnone]; \n      inversion Hvalue_in; subst. \n    assert (n = n0) by omega; subst.\n    rewrite H3 in H9. inversion H9; subst; apply False_ind; auto.\n  inversion Hst_in as [Heqset Hreg_in].\n    soap2_intra_normal_aux Hreg_in H4 Hreg rt (se j) H0 Hvalue_opt_in k1 k1'.\n    (* both are low *)\n    rewrite <- H in Hvalue_opt_in; rewrite <- H6 in Hvalue_opt_in;\n      inversion Hvalue_opt_in as [v v' Hvalue_in | Hnone]; \n      inversion Hvalue_in; subst. apply False_ind; omega.  \n  inversion Hst_in as [Heqset Hreg_in].\n    soap2_intra_normal_aux Hreg_in H3 Hreg rt (se j) H1 Hvalue_opt_in k1 k1'.\n    (* both are low *)\n    rewrite <- H0 in Hvalue_opt_in; rewrite <- H4 in Hvalue_opt_in;\n      inversion Hvalue_opt_in as [v v' Hvalue_in | Hnone]; \n      inversion Hvalue_in; subst. apply False_ind; omega.  \n  (* SparseSwitch *)\n  inversion Hst_in as [Heqset Hreg_in].\n    soap2_intra_normal_aux Hreg_in H2 Hreg rt (se j) H0 Hvalue_opt_in k1 k1'.\n    (* both are low *)\n    rewrite <- H in Hvalue_opt_in; rewrite <- H3 in Hvalue_opt_in;\n      inversion Hvalue_opt_in as [v v' Hvalue_in | Hnone]; \n      inversion Hvalue_in; subst.  \n      unfold well_formed_lookupswitch in lookupswitch_hyp.\n      specialize lookupswitch_hyp with (pc:=pc) (reg:=rt) (l:=l) (size:=size) (i:=Int.toZ i0) (1:=Hins) (2:=H1) (3:=H5).\n      subst. apply False_ind; auto.\n  inversion Hst_in as [Heqset Hreg_in].\n    soap2_intra_normal_aux Hreg_in H2 Hreg rt (se j) H0 Hvalue_opt_in k1 k1'.\n    (* both are low *)\n    rewrite <- H in Hvalue_opt_in; rewrite <- H4 in Hvalue_opt_in;\n      inversion Hvalue_opt_in as [v v' Hvalue_in | Hnone]; \n      inversion Hvalue_in; subst. \n      specialize H6 with (i':=Int.toZ i0) (o':=o) (1:=H1). \n      apply False_ind; auto.\n  inversion Hst_in as [Heqset Hreg_in].\n    soap2_intra_normal_aux Hreg_in H3 Hreg rt (se j) H1 Hvalue_opt_in k1 k1'.\n    (* both are low *)\n    rewrite <- H0 in Hvalue_opt_in; rewrite <- H4 in Hvalue_opt_in;\n      inversion Hvalue_opt_in as [v v' Hvalue_in | Hnone]; \n      inversion Hvalue_in; subst. \n      specialize H2 with (i':=Int.toZ i0) (o':=o) (1:=H6). \n      apply False_ind; omega.  \n  (* If_icmp *)\n  inversion Hst_in as [Heqset Hreg_in].\n    (* ra *)\n    assert (Hreg_in':=Hreg_in).\n    soap2_intra_normal_aux Hreg_in H8 Hreg ra (se j) H5 Hvalue_opt_in k k'.\n    (* rb *)\n    soap2_intra_normal_aux Hreg_in' H8 Hreg rb (se j) H6 Hvalue_opt_in' k k'.\n    (* both are low *)\n    rewrite <- H3 in Hvalue_opt_in; rewrite <- H4 in Hvalue_opt_in'; \n    rewrite <- H14 in Hvalue_opt_in; rewrite <- H15 in Hvalue_opt_in'.\n    inversion Hvalue_opt_in as [v v' Hvalue_in | Hnone]; \n    inversion Hvalue_opt_in' as [v2 v2' Hvalue_in' | Hnone'];\n    inversion Hvalue_in; inversion Hvalue_in'. \n    subst; contradiction.  \n  inversion Hst_in as [Heqset Hreg_in].\n    (* ra *)\n    assert (Hreg_in':=Hreg_in).\n    soap2_intra_normal_aux Hreg_in H9 Hreg ra (se j) H6 Hvalue_opt_in k k'.\n    (* rb *)\n    soap2_intra_normal_aux Hreg_in' H9 Hreg rb (se j) H7 Hvalue_opt_in' k k'.\n    (* both are low *)\n    rewrite <- H4 in Hvalue_opt_in; rewrite <- H5 in Hvalue_opt_in'; \n    rewrite <- H14 in Hvalue_opt_in; rewrite <- H15 in Hvalue_opt_in'.\n    inversion Hvalue_opt_in as [v v' Hvalue_in | Hnone]; \n    inversion Hvalue_opt_in' as [v2 v2' Hvalue_in' | Hnone'];\n    inversion Hvalue_in; inversion Hvalue_in'. \n    subst; contradiction.   \n  (* If_z *)\n  inversion Hst_in as [Heq_set Hreg_in].\n    soap2_intra_normal_aux Hreg_in H4 Hreg r (se j) H2 Hvalue_opt_in k1 k1'.\n    rewrite <- H1 in Hvalue_opt_in; rewrite <- H8 in Hvalue_opt_in;\n      inversion Hvalue_opt_in as [v v' Hvalue_in | Hnone]; \n      inversion Hvalue_in; subst; contradiction.\n  inversion Hst_in as [Heq_set Hreg_in].\n    soap2_intra_normal_aux Hreg_in H5 Hreg r (se j) H3 Hvalue_opt_in k1 k1'.\n    rewrite <- H2 in Hvalue_opt_in; rewrite <- H8 in Hvalue_opt_in;\n      inversion Hvalue_opt_in as [v v' Hvalue_in | Hnone]; \n      inversion Hvalue_in; subst; contradiction.\nQed. \n\nEnd p.", "meta": {"author": "h3nd24", "repo": "DEX_formalization", "sha": "8f56f3ee473701aa70ad7621355481dc8df0d1b4", "save_path": "github-repos/coq/h3nd24-DEX_formalization", "path": "github-repos/coq/h3nd24-DEX_formalization/DEX_formalization-8f56f3ee473701aa70ad7621355481dc8df0d1b4/DEX_O/DEX_ElemLemmaNormalIntra3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.3812195592260441, "lm_q1q2_score": 0.20547095146687558}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssrZ ZArith_ext seq_ext uniq_tac machine_int.\nImport MachineInt.\nRequire Import mips_cmd mips_tactics mips_contrib.\nImport expr_m.\nRequire Import multi_is_zero_u_prg.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope mips_expr_scope.\nLocal Open Scope mips_cmd_scope.\nLocal Open Scope uniq_scope.\n\nLemma multi_is_zero_u_termination s h k z ext M_ ret :\n  uniq(k, z, ext, M_, ret, r0) ->\n  { si | Some (s, h) -- multi_is_zero_u k z ext M_ ret ---> si }.\nProof.\nmove=> Hregs.\nrewrite /multi_is_zero_u.\napply exists_addiu_seq.\nrewrite sext_Z2u // addi0.\napply exists_addiu_seq.\nrewrite !store.get_r0 add0i.\nset s0 := store.upd _ _ _.\n(* TODO: factoriser cette etape dans les differentes preuves de terminaison? *)\nhave [kext Hkext] : { kext | u2Z [k]_s0 - u2Z [ext]_s0 = Z_of_nat kext}.\n  have [kext Hkext] : { kext | u2Z [k]_s0 - u2Z [ext]_s0 = kext} by eapply exist; reflexivity.\n  have : 0 <= kext. rewrite -Hkext /s0. repeat Reg_upd. rewrite Z2uK // subZ0; exact: min_u2Z.\n  case/Z_of_nat_complete_inf => kext' H.\n  exists kext'; by rewrite -H.\nmove: kext s0 Hkext h.\nelim.\n- move=> s0 Hkext h.\n  eapply exist.\n  apply while.exec_while_false.\n  rewrite /= in Hkext *.\n  apply/negPn/eqP; lia.\n- move=> kext IH s0 Hext h.\n  apply exists_while.\n  + rewrite /=; apply/eqP; rewrite Z_S in Hext; lia.\n  + apply exists_seq_P2 with (fun s => u2Z [k ]_ (fst s) - u2Z [ext ]_ (fst s) = Z_of_nat kext)%mips_expr.\n    * exists_lwxs l_z H_l_z z_z H_z_z.\n      exists_movn H.\n      - apply exists_movn_false_seq_P => //.\n        apply exists_addiu_P.\n        simpl fst.\n        repeat Reg_upd.\n        rewrite Z_S in Hext.\n        rewrite sext_Z2u // u2Z_add_Z2u //; first lia.\n        move: (min_u2Z [k ]_ s0) (max_u2Z [k ]_ s0) (min_u2Z [ext ]_ s0) (max_u2Z [ext ]_ s0) => ? ? ? ?; lia.\n      - apply exists_movn_true_seq_P => //.\n        apply exists_addiu_P.\n        simpl fst.\n        repeat Reg_upd.\n        rewrite Z_S in Hext.\n        rewrite sext_Z2u // u2Z_add_Z2u //; first lia.\n        move: (min_u2Z [k ]_ s0) (max_u2Z [k ]_ s0) (min_u2Z [ext ]_ s0) (max_u2Z [ext ]_ s0) => ? ? ? ?; lia.\n    * move=> [si hi] Hsi; exact: IH.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/cryptoasm/multi_is_zero_u_termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20547094960990167}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import Morphisms.\nFrom MetaCoq.Utils Require Import utils.\nFrom MetaCoq.Common Require Import config.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils PCUICCases PCUICInduction\n     PCUICLiftSubst PCUICSigmaCalculus PCUICTyping PCUICWeakeningEnv PCUICWeakeningEnvTyp\n     PCUICWeakeningConv PCUICWeakeningTyp\n     PCUICSubstitution PCUICReduction PCUICCumulativity PCUICGeneration\n     PCUICUnivSubst PCUICUnivSubstitutionConv.\n\nFrom Equations Require Import Equations.\nRequire Import Equations.Prop.DepElim.\nRequire Import ssreflect ssrbool.\n\nFrom MetaCoq.PCUIC Require Import PCUICInduction.\n\nSection CheckerFlags.\n  Context {cf:checker_flags}.\n\n\n  Lemma wf_universe_type0 Σ : wf_universe Σ Universe.type0.\n  Proof using Type.\n    simpl.\n    intros l hin%LevelExprSet.singleton_spec.\n    subst l. simpl.\n    apply global_ext_levels_InSet.\n  Qed.\n\n  Lemma wf_universe_type1 Σ : wf_universe Σ Universe.type1.\n  Proof using Type.\n    simpl.\n    intros l hin%LevelExprSet.singleton_spec.\n    subst l. simpl.\n    apply global_ext_levels_InSet.\n  Qed.\n\n  Lemma wf_universe_super {Σ u} : wf_universe Σ u -> wf_universe Σ (Universe.super u).\n  Proof using Type.\n    destruct u; cbn.\n    1-2:intros _ l hin%LevelExprSet.singleton_spec; subst l; apply wf_universe_type1;\n     now apply LevelExprSet.singleton_spec.\n    intros Hl.\n    intros l hin.\n    eapply Universes.spec_map_succ in hin as [x' [int ->]].\n    simpl. now specialize (Hl _ int).\n  Qed.\n\n  Lemma wf_universe_sup {Σ u u'} : wf_universe Σ u -> wf_universe Σ u' ->\n    wf_universe Σ (Universe.sup u u').\n  Proof using Type.\n    destruct u, u'; cbn; auto.\n    intros Hu Hu' l [Hl|Hl]%LevelExprSet.union_spec.\n    now apply (Hu _ Hl).\n    now apply (Hu' _ Hl).\n  Qed.\n\n  Lemma wf_universe_product {Σ u u'} : wf_universe Σ u -> wf_universe Σ u' ->\n    wf_universe Σ (Universe.sort_of_product u u').\n  Proof using Type.\n    intros Hu Hu'. unfold Universe.sort_of_product.\n    destruct (Universe.is_prop u' || Universe.is_sprop u'); auto.\n    now apply wf_universe_sup.\n  Qed.\n\n  Hint Resolve wf_universe_type1 wf_universe_super wf_universe_sup wf_universe_product : pcuic.\n\n\n  Definition wf_universeb_level Σ l :=\n    LevelSet.mem l (global_ext_levels Σ).\n\n  Definition wf_universe_level Σ l :=\n    LevelSet.In l (global_ext_levels Σ).\n\n  Definition wf_universe_instance Σ u :=\n    Forall (wf_universe_level Σ) u.\n\n  Definition wf_universeb_instance Σ u :=\n    forallb (wf_universeb_level Σ) u.\n\n  Lemma wf_universe_levelP {Σ l} : reflect (wf_universe_level Σ l) (wf_universeb_level Σ l).\n  Proof using Type.\n    unfold wf_universe_level, wf_universeb_level.\n    destruct LevelSet.mem eqn:ls; constructor.\n    now apply LevelSet.mem_spec in ls.\n    intros hin.\n    now apply LevelSet.mem_spec in hin.\n  Qed.\n\n  Lemma wf_universe_instanceP {Σ u} : reflect (wf_universe_instance Σ u) (wf_universeb_instance Σ u).\n  Proof using Type.\n    unfold wf_universe_instance, wf_universeb_instance.\n    apply forallbP. intros x; apply wf_universe_levelP.\n  Qed.\n\n  Lemma wf_universe_subst_instance_univ (Σ : global_env_ext) univs u s :\n    wf Σ ->\n    wf_universe Σ s ->\n    wf_universe_instance (Σ.1, univs) u ->\n    wf_universe (Σ.1, univs) (subst_instance u s).\n  Proof using Type.\n    destruct s as [| |t]; cbnr.\n    intros wfΣ Hl Hu e [[l n] [inl ->]]%In_subst_instance.\n    destruct l as [|s|n']; simpl; auto.\n    - apply global_ext_levels_InSet.\n    - specialize (Hl (Level.Level s, n) inl).\n      simpl in Hl.\n      apply monomorphic_level_in_global_ext in Hl.\n      eapply LS.union_spec. now right.\n    - specialize (Hl (Level.Var n', n) inl).\n      eapply LS.union_spec in Hl as [Hl|Hl].\n      + red in Hu.\n        unfold levels_of_udecl in Hl.\n        destruct Σ.2.\n        * simpl in Hu. simpl in *.\n          unfold subst_instance; simpl.\n          destruct nth_error eqn:hnth; simpl.\n          eapply nth_error_forall in Hu; eauto.\n          apply global_ext_levels_InSet.\n        * unfold subst_instance. simpl.\n          destruct (nth_error u n') eqn:hnth.\n          2:{ simpl. rewrite hnth. apply global_ext_levels_InSet. }\n          eapply nth_error_forall in Hu. 2:eauto.\n          change (nth_error u n') with (nth_error u n') in *.\n          rewrite -> hnth. simpl. apply Hu.\n      + now apply not_var_global_levels in Hl.\n  Qed.\n\n  Lemma wf_universe_instantiate Σ univs s u φ :\n    wf Σ ->\n    wf_universe (Σ, univs) s ->\n    wf_universe_instance (Σ, φ) u ->\n    wf_universe (Σ, φ) (subst_instance_univ u s).\n  Proof using Type.\n    intros wfΣ Hs.\n    apply (wf_universe_subst_instance_univ (Σ, univs) φ); auto.\n  Qed.\n\n  Lemma subst_instance_empty u :\n    forallb (fun x => ~~ Level.is_var x) u ->\n    subst_instance [] u = u.\n  Proof using Type.\n    induction u; simpl; intros Hu; auto.\n    rewrite subst_instance_cons.\n    move/andP: Hu => [] isv Hf.\n    rewrite IHu //.\n    now destruct a => /= //; auto.\n  Qed.\n\n  Lemma wf_universe_level_mono Σ u :\n    wf Σ ->\n    on_udecl_prop Σ (Monomorphic_ctx) ->\n    Forall (wf_universe_level (Σ, Monomorphic_ctx)) u ->\n    forallb (fun x => ~~ Level.is_var x) u.\n  Proof using Type.\n    intros wf uprop.\n    induction 1 => /= //.\n    destruct x eqn:isv => /= //.\n    apply LS.union_spec in H as [H|H]; simpl in H.\n    epose proof (@udecl_prop_in_var_poly _ (Σ, _) _ uprop H) as [ctx' eq].\n    discriminate.\n    now pose proof (not_var_global_levels wf _ H).\n  Qed.\n\n  Lemma wf_universe_level_sub Σ univs u :\n    wf_universe_level (Σ, Monomorphic_ctx) u ->\n    wf_universe_level (Σ, univs) u.\n  Proof using cf.\n    intros wfx.\n    red in wfx |- *.\n    eapply LevelSet.union_spec in wfx; simpl in *.\n    destruct wfx as [wfx|wfx]. lsets.\n    eapply LevelSet.union_spec. now right.\n  Qed.\n\n  Lemma wf_universe_instance_sub Σ univs u :\n    wf_universe_instance (Σ, Monomorphic_ctx) u ->\n    wf_universe_instance (Σ, univs) u.\n  Proof using cf.\n    intros wfu.\n    red in wfu |- *.\n    eapply Forall_impl; eauto.\n    intros. red in H. cbn in H. eapply wf_universe_level_sub; eauto.\n  Qed.\n\n  Lemma In_Level_global_ext_poly s Σ cst :\n    LS.In (Level.Level s) (global_ext_levels (Σ, Polymorphic_ctx cst)) ->\n    LS.In (Level.Level s) (global_levels Σ).\n  Proof using Type.\n    intros [hin|hin]%LS.union_spec.\n    simpl in hin.\n    now apply monomorphic_level_notin_AUContext in hin.\n    apply hin.\n  Qed.\n\n  Lemma Forall_In (A : Type) (P : A -> Prop) (l : list A) :\n    Forall P l -> (forall x : A, In x l -> P x).\n  Proof using Type.\n    induction 1; simpl; auto.\n    intros x' [->|inx]; auto.\n  Qed.\n\n  Lemma wf_universe_instance_In {Σ u} : wf_universe_instance Σ u <->\n    (forall l, In l u -> LS.In l (global_ext_levels Σ)).\n  Proof using Type.\n    unfold wf_universe_instance.\n    split; intros. eapply Forall_In in H; eauto.\n    apply In_Forall. auto.\n  Qed.\n\n  Lemma in_subst_instance l u u' :\n    In l (subst_instance u u') ->\n    In l u \\/ In l u' \\/ l = Level.lzero.\n  Proof using Type.\n    induction u'; simpl; auto.\n    intros [].\n    destruct a; simpl in *; subst; auto.\n    destruct (nth_in_or_default n u Level.lzero); auto.\n    specialize (IHu' H). intuition auto.\n  Qed.\n\n  Lemma wf_universe_subst_instance Σ univs u u' φ :\n    wf Σ ->\n    on_udecl_prop Σ univs ->\n    wf_universe_instance (Σ, univs) u' ->\n    wf_universe_instance (Σ, φ) u ->\n    wf_universe_instance (Σ, φ) (subst_instance u u').\n  Proof using Type.\n    intros wfΣ onup Hs cu.\n    destruct univs.\n    - red in Hs |- *.\n      unshelve epose proof (wf_universe_level_mono _ _ _ _ Hs); eauto.\n      eapply forallb_Forall in H. apply Forall_map.\n      solve_all. destruct x; simpl => //.\n      red. apply global_ext_levels_InSet.\n      eapply wf_universe_level_sub; eauto.\n    - clear onup.\n      red in Hs |- *.\n      eapply Forall_map, Forall_impl; eauto.\n      intros x wfx.\n      red in wfx. destruct x => /= //.\n      { red. apply global_ext_levels_InSet. }\n      eapply In_Level_global_ext_poly in wfx.\n      apply LS.union_spec; now right.\n      eapply in_var_global_ext in wfx; simpl in wfx; auto.\n      unfold AUContext.levels, AUContext.repr in wfx.\n      destruct cst as [? cst].\n      rewrite mapi_unfold in wfx.\n      eapply (proj1 (LevelSetProp.of_list_1 _ _)) in wfx.\n      apply SetoidList.InA_alt in wfx as [? [<- wfx]]. simpl in wfx.\n      eapply In_unfold_inj in wfx; [|congruence].\n      destruct (nth_in_or_default n u (Level.lzero)).\n      red in cu. eapply Forall_In in cu; eauto. rewrite e.\n      red. apply global_ext_levels_InSet.\n  Qed.\n\n  Section WfUniverses.\n    Context (Σ : global_env_ext).\n\n    Definition wf_universeb (s : Universe.t) : bool :=\n      match s with\n      | Universe.lType l => LevelExprSet.for_all (fun l => LevelSet.mem (LevelExpr.get_level l) (global_ext_levels Σ)) l\n      | _ => true\n      end.\n\n    Lemma wf_universe_reflect {u : Universe.t} :\n      reflect (wf_universe Σ u) (wf_universeb u).\n    Proof using Type.\n      destruct u; simpl; try now constructor.\n      eapply iff_reflect.\n      rewrite LevelExprSet.for_all_spec.\n      split; intros.\n      - intros l Hl; specialize (H l Hl).\n        now eapply LS.mem_spec.\n      - specialize (H l H0). simpl in H.\n        now eapply LS.mem_spec in H.\n    Qed.\n\n    Fixpoint on_universes fu fc t :=\n      match t with\n      | tSort s => fu s\n      | tApp t u\n      | tProd _ t u\n      | tLambda _ t u => on_universes fu fc t && on_universes fu fc u\n      | tCase _ p c brs =>\n        [&&\n        forallb fu (map Universe.make p.(puinst)) ,\n        forallb (on_universes fu fc) p.(pparams) ,\n        test_context (fc #|p.(puinst)|) p.(pcontext) ,\n        on_universes fu fc p.(preturn) ,\n        on_universes fu fc c &\n        forallb (test_branch (fc #|p.(puinst)|) (on_universes fu fc)) brs ]\n      | tLetIn _ t t' u =>\n        [&& on_universes fu fc t , on_universes fu fc t' & on_universes fu fc u]\n      | tProj _ t => on_universes fu fc t\n      | tFix mfix _ | tCoFix mfix _ =>\n        forallb (fun d => on_universes fu fc d.(dtype) && on_universes fu fc d.(dbody)) mfix\n      | tConst _ u | tInd _ u | tConstruct _ _ u =>\n          forallb fu (map Universe.make u)\n      | tEvar _ args => forallb (on_universes fu fc) args\n      | _ => true\n      end.\n\n    Definition wf_universes t := on_universes wf_universeb closedu t.\n\n\n\n    Lemma wf_universeb_instance_forall u :\n      forallb wf_universeb (map Universe.make u) = wf_universeb_instance Σ u.\n    Proof using Type.\n      induction u => //=.\n      rewrite IHu.\n      f_equal.\n      cbn.\n      now rewrite if_true_false.\n    Qed.\n\n    (* Lemma All_forallb {A} (P : A -> Type) l (H : All P l) p p' : (forall x, P x -> p x = p' x) -> forallb p l = forallb p' l.\n    Proof.\n      intros; induction H; simpl; auto.\n      now rewrite IHAll H0.\n    Qed. *)\n\n    Lemma test_context_mapi (p : term -> bool) f (ctx : context) k :\n  test_context p (mapi_context (shiftf f k) ctx) = test_context_k (fun k => p ∘ f k) k ctx.\nProof using Type.\n  induction ctx; simpl; auto.\n  rewrite IHctx. f_equal.\n  now rewrite test_decl_map_decl.\nQed.\nHint Rewrite test_context_mapi : map.\n\nLemma test_context_k_ctx (p : term -> bool) (ctx : context) k :\n  test_context p ctx = test_context_k (fun k => p) k ctx.\nProof using Type.\n  induction ctx; simpl; auto.\nQed.\n\n    Lemma on_universes_lift pu pc n k t : on_universes pu pc (lift n k t) = on_universes pu pc t.\n    Proof using Type.\n      induction t in n, k |- * using term_forall_list_ind; simpl ; auto ; try\n        rewrite ?IHt1 ?IHt2 ?IHt3; auto.\n      - solve_all.\n      - destruct X as [? [? ?]]. solve_all.\n        rewrite IHt.\n        f_equal.\n        f_equal ; [now solve_all|..].\n        f_equal.\n        f_equal ; [now rewrite /id e|..].\n        f_equal.\n        solve_all.\n        rewrite /test_branch. rewrite b. f_equal.\n      - rewrite forallb_map.\n        eapply All_forallb_eq_forallb; eauto. simpl; intros [].\n        simpl. intros. cbn. now rewrite H.\n      - rewrite forallb_map.\n        eapply All_forallb_eq_forallb; eauto. simpl; intros [].\n        simpl. intros. cbn. now rewrite H.\n    Qed.\n\n    Corollary wf_universes_lift n k t : wf_universes (lift n k t) = wf_universes t.\n    Proof using Type.\n      by apply on_universes_lift.\n    Qed.\n\n    Lemma on_universes_subst s k pu pc t :\n      All (on_universes pu pc) s ->\n      on_universes pu pc (subst s k t) = on_universes pu pc t.\n    Proof using Type.\n      intros Hs.\n      induction t in k |- * using term_forall_list_ind; simpl; auto; try\n        rewrite ?IHt1 ?IHt2 ?IHt3; auto.\n      - destruct (Nat.leb_spec k n); auto.\n        destruct nth_error eqn:nth; simpl; auto.\n        eapply nth_error_all in nth; eauto.\n        simpl in nth. intros. now rewrite on_universes_lift.\n      - solve_all.\n      - destruct X as [? [? ?]]. solve_all.\n        rewrite IHt.\n        f_equal.\n        f_equal ; [now solve_all|..].\n        f_equal.\n        f_equal ; [now rewrite /id e|..].\n        f_equal.\n        solve_all.\n        rewrite /test_branch. rewrite b. f_equal.\n      - rewrite forallb_map.\n        eapply All_forallb_eq_forallb; eauto. simpl; intros [].\n        simpl. intros. cbn. now rewrite H.\n      - rewrite forallb_map.\n        eapply All_forallb_eq_forallb; eauto. simpl; intros [].\n        simpl. intros. cbn. now rewrite H.\n    Qed.\n\n    Corollary wf_universes_subst s k t :\n      All wf_universes s ->\n      wf_universes (subst s k t) = wf_universes t.\n    Proof using Type.\n      by apply on_universes_subst.\n    Qed.\n\n  End WfUniverses.\n  Arguments wf_universe_reflect {Σ u}.\n\n  Ltac to_prop :=\n    repeat match goal with\n    | [ H: is_true (?x && ?y) |- _ ] =>\n     let x := fresh in let y := fresh in move/andP: H; move=> [x y]; rewrite ?x ?y; simpl\n    end.\n\n  Ltac to_wfu :=\n    repeat match goal with\n    | [ H: is_true (wf_universeb _ ?x) |- _ ] => apply (elimT (@wf_universe_reflect _ x)) in H\n    | [ |- is_true (wf_universeb _ ?x) ] => apply (introT (@wf_universe_reflect _ x))\n    end.\n\n  Lemma wf_universes_inst {Σ : global_env_ext} univs t u :\n    wf Σ ->\n    on_udecl_prop Σ.1 univs ->\n    wf_universe_instance Σ u  ->\n    wf_universes (Σ.1, univs) t ->\n    wf_universes Σ (subst_instance u t).\n  Proof using Type.\n    intros wfΣ onudecl cu wft.\n    induction t using term_forall_list_ind; simpl in *; auto; try to_prop;\n      try apply /andP; to_wfu; intuition eauto 4.\n\n    all:cbn in * ; autorewrite with map; repeat (f_equal; solve_all).\n\n    - to_wfu. destruct Σ as [Σ univs']. simpl in *.\n      eapply (wf_universe_subst_instance_univ (Σ, univs)); auto.\n\n    - apply forallb_All.\n      rewrite -forallb_map wf_universeb_instance_forall.\n      apply All_forallb in wft.\n      rewrite -forallb_map wf_universeb_instance_forall in wft.\n      apply/wf_universe_instanceP.\n      eapply wf_universe_subst_instance; eauto.\n      destruct Σ; simpl in *.\n      now move/wf_universe_instanceP: wft.\n    - apply forallb_All.\n      rewrite -forallb_map wf_universeb_instance_forall.\n      apply All_forallb in wft.\n      rewrite -forallb_map wf_universeb_instance_forall in wft.\n      apply/wf_universe_instanceP.\n      eapply wf_universe_subst_instance; eauto.\n      destruct Σ; simpl in *.\n      now move/wf_universe_instanceP: wft.\n    - apply forallb_All.\n      rewrite -forallb_map wf_universeb_instance_forall.\n      apply All_forallb in wft.\n      rewrite -forallb_map wf_universeb_instance_forall in wft.\n      apply/wf_universe_instanceP.\n      eapply wf_universe_subst_instance; eauto.\n      destruct Σ; simpl in *.\n      now move/wf_universe_instanceP: wft.\n\n    - apply forallb_All.\n      rewrite -forallb_map wf_universeb_instance_forall.\n      apply All_forallb in H.\n      rewrite -forallb_map wf_universeb_instance_forall in H.\n      apply/wf_universe_instanceP.\n      eapply wf_universe_subst_instance; eauto.\n      destruct Σ ; simpl in *.\n      now move/wf_universe_instanceP: H.\n\n    - now len.\n    - rewrite /test_branch. rtoProp.\n      move/andP: a => [] tctx wfu.\n      split; auto. simpl.\n      solve_all. now len.\n  Qed.\n\n  Lemma weaken_wf_universe Σ Σ' t : wf Σ' -> extends Σ.1 Σ' ->\n    wf_universe Σ t ->\n    wf_universe (Σ', Σ.2) t.\n  Proof using Type.\n    intros wfΣ ext.\n    destruct t; simpl; auto.\n    intros Hl l inl; specialize (Hl l inl).\n    apply LS.union_spec. apply LS.union_spec in Hl as [Hl|Hl]; simpl.\n    left; auto.\n    right. now eapply global_levels_sub; [apply ext|].\n  Qed.\n\n  Lemma weaken_wf_universe_level {Σ : global_env_ext} Σ' t : wf Σ -> wf Σ' -> extends Σ Σ' ->\n    wf_universe_level Σ t ->\n    wf_universe_level (Σ', Σ.2) t.\n  Proof using Type.\n    intros wfΣ wfΣ' ext.\n    unfold wf_universe_level.\n    destruct t; simpl; auto using global_ext_levels_InSet;\n    intros; apply LS.union_spec.\n    - eapply LS.union_spec in H as [H|H].\n      left; auto.\n      right; auto. simpl.\n      eapply global_levels_sub. apply ext. apply H.\n    - cbn. eapply in_var_global_ext in H; eauto.\n  Qed.\n\n  Lemma weaken_wf_universe_instance {Σ : global_env_ext} Σ' t : wf Σ -> wf Σ' -> extends Σ.1 Σ' ->\n    wf_universe_instance Σ t ->\n    wf_universe_instance (Σ', Σ.2) t.\n  Proof using Type.\n    intros wfΣ wfΣ' ext.\n    unfold wf_universe_instance.\n    intros H; eapply Forall_impl; eauto.\n    intros. now eapply weaken_wf_universe_level.\n  Qed.\n\n  Lemma weaken_wf_universes {Σ : global_env_ext} Σ' t : wf Σ -> wf Σ' -> extends Σ.1 Σ' ->\n    wf_universes Σ t ->\n    wf_universes (Σ', Σ.2) t.\n  Proof using Type.\n    intros wfΣ wfΣ' ext.\n    induction t using term_forall_list_ind; cbn in *; auto; intros; to_prop;\n    try apply /andP; to_wfu; intuition eauto 4.\n\n  - solve_all.\n  - now eapply weaken_wf_universe.\n  - eapply forallb_impl ; tea.\n    now move => ? _ /wf_universe_reflect /weaken_wf_universe /wf_universe_reflect.\n  - eapply forallb_impl ; tea.\n    now move => ? _ /wf_universe_reflect /weaken_wf_universe /wf_universe_reflect.\n  - eapply forallb_impl ; tea.\n    now move => ? _ /wf_universe_reflect /weaken_wf_universe /wf_universe_reflect.\n  - eapply forallb_impl ; tea.\n    now move => ? _ /wf_universe_reflect /weaken_wf_universe /wf_universe_reflect.\n  - red in X.\n    solve_all.\n    rewrite /test_branch in b |- *.\n    rtoProp.\n    intuition.\n  - red in X; solve_all.\n  - red in X. solve_all.\n  Qed.\n\n  Lemma wf_universes_weaken_full : weaken_env_prop_full cumulSpec0 (lift_typing typing) (fun Σ Γ t T =>\n      wf_universes Σ t && wf_universes Σ T).\n  Proof using Type.\n    do 2 red. intros.\n    to_prop; apply /andP; split; now apply weaken_wf_universes.\n  Qed.\n\n  Lemma wf_universes_weaken :\n    weaken_env_prop cumulSpec0 (lift_typing typing)\n      (lift_typing (fun Σ Γ (t T : term) =>\n        wf_universes Σ t && wf_universes Σ T)).\n  Proof using Type.\n    intros Σ Σ' φ wfΣ wfΣ' Hext Γ t T HT.\n    apply lift_typing_impl with (1 := HT); intros ? Hty.\n    now eapply (wf_universes_weaken_full (Σ, _)).\n  Qed.\n\n  Lemma wf_universes_inds Σ mind u bodies :\n    wf_universe_instance Σ u ->\n    All (fun t : term => wf_universes Σ t) (inds mind u bodies).\n  Proof using Type.\n    intros wfu.\n    unfold inds.\n    generalize #|bodies|.\n    induction n; simpl; auto.\n    constructor; auto.\n    cbn.\n    rewrite wf_universeb_instance_forall.\n    now apply /wf_universe_instanceP.\n  Qed.\n\n  Lemma wf_universes_mkApps Σ f args :\n    wf_universes Σ (mkApps f args) = wf_universes Σ f && forallb (wf_universes Σ) args.\n  Proof using Type.\n    induction args using rev_ind; simpl; auto. now rewrite andb_true_r.\n    now rewrite mkApps_app forallb_app /= andb_true_r andb_assoc -IHargs.\n  Qed.\n\n  Lemma type_local_ctx_wf Σ Γ Δ s : type_local_ctx\n    (lift_typing\n     (fun (Σ : PCUICEnvironment.global_env_ext)\n        (_ : PCUICEnvironment.context) (t T : term) =>\n      wf_universes Σ t && wf_universes Σ T)) Σ Γ Δ s ->\n      All (fun d => option_default (wf_universes Σ) (decl_body d) true && wf_universes Σ (decl_type d)) Δ.\n  Proof using Type.\n    induction Δ as [|[na [b|] ty] ?]; simpl; constructor; auto.\n    simpl.\n    destruct X as [? [? ?]]. now to_prop.\n    apply IHΔ. apply X.\n    simpl.\n    destruct X as [? ?]. now to_prop.\n    apply IHΔ. apply X.\n  Qed.\n\n  Lemma consistent_instance_ext_wf Σ univs u : consistent_instance_ext Σ univs u ->\n    wf_universe_instance Σ u.\n  Proof using Type.\n    destruct univs; simpl.\n    - destruct u => // /=.\n      intros _. constructor.\n    - intros [H%forallb_Forall [H' H'']].\n      eapply Forall_impl; eauto.\n      simpl; intros. now eapply LS.mem_spec in H0.\n  Qed.\n\n  Ltac specIH :=\n    repeat match goal with\n    | [ H : on_udecl _ _, H' : on_udecl _ _ -> _ |- _ ] => specialize (H' H)\n    end.\n\n  Local Lemma wf_sorts_local_ctx_smash (Σ : global_env_ext) mdecl args sorts :\n    sorts_local_ctx\n    (lift_typing\n       (fun (Σ : PCUICEnvironment.global_env_ext)\n          (_ : PCUICEnvironment.context) (t T : term) =>\n        wf_universes Σ t && wf_universes Σ T)) (Σ.1, ind_universes mdecl)\n    (arities_context (ind_bodies mdecl),,, ind_params mdecl)\n    args sorts ->\n    sorts_local_ctx\n    (lift_typing\n       (fun (Σ : PCUICEnvironment.global_env_ext)\n          (_ : PCUICEnvironment.context) (t T : term) =>\n        wf_universes Σ t && wf_universes Σ T)) (Σ.1, ind_universes mdecl)\n    (arities_context (ind_bodies mdecl),,, ind_params mdecl)\n    (smash_context [] args) sorts.\n  Proof using Type.\n    induction args as [|[na [b|] ty] args] in sorts |- *; simpl; auto.\n    intros [].\n    rewrite subst_context_nil. auto.\n    destruct sorts; auto.\n    intros [].\n    rewrite smash_context_acc /=. split. eauto.\n    rewrite wf_universes_subst.\n    clear -s. generalize 0.\n    induction args as [|[na [b|] ty] args] in sorts, s |- *; simpl in *; auto.\n    - destruct s as [? [[s' wf] [? ?]%andb_and]].\n      constructor; eauto.\n      rewrite wf_universes_subst. eapply IHargs; eauto.\n      now rewrite wf_universes_lift.\n    - destruct sorts => //. destruct s.\n      constructor => //. eapply IHargs; eauto.\n    - now rewrite wf_universes_lift.\n  Qed.\n\n  Lemma wf_sorts_local_ctx_nth_error Σ P Γ Δ s n d :\n    sorts_local_ctx P Σ Γ Δ s ->\n    nth_error Δ n = Some d ->\n    ∑ Γ' t, P Σ Γ' (decl_type d) t.\n  Proof using Type.\n    induction Δ as [|[na [b|] ty] Δ] in n, s |- *; simpl; auto.\n    - now rewrite nth_error_nil.\n    - intros [h [h' h'']].\n      destruct n. simpl. move=> [= <-] /=. do 2 eexists; eauto.\n      now simpl; eapply IHΔ.\n    - destruct s => //. intros [h h'].\n      destruct n. simpl. move=> [= <-] /=. eexists; eauto.\n      now simpl; eapply IHΔ.\n  Qed.\n\n  Lemma In_unfold_var x n : In x (unfold n Level.Var) <-> exists k, k < n /\\ (x = Level.Var k).\n  Proof using Type.\n    split.\n    - induction n => /= //.\n      intros [hin|hin]%in_app_or.\n      destruct (IHn hin) as [k [lt eq]].\n      exists k; auto.\n      destruct hin => //. subst x.\n      eexists; eauto.\n    - intros [k [lt ->]].\n      induction n in k, lt |- *. lia.\n      simpl. apply in_or_app.\n      destruct (lt_dec k n). left; auto.\n      right. left. f_equal. lia.\n  Qed.\n\n  Lemma wf_abstract_instance Σ decl :\n    wf_universe_instance (Σ, decl) (abstract_instance decl).\n  Proof using Type.\n    destruct decl as [|[u cst]]=> /= //.\n    red. constructor.\n    rewrite /UContext.instance /AUContext.repr /=.\n    rewrite mapi_unfold.\n    red. eapply In_Forall.\n    intros x hin. eapply In_unfold_var in hin as [k [lt eq]].\n    subst x. red.\n    eapply LS.union_spec; left. simpl.\n    rewrite /AUContext.levels /= mapi_unfold.\n    eapply (proj2 (LevelSetProp.of_list_1 _ _)).\n    apply SetoidList.InA_alt. eexists; split; eauto.\n    eapply In_unfold_var. exists k; split; eauto.\n  Qed.\n\n  Definition on_decl_universes (fu : Universe.t -> bool) (fc : nat -> term -> bool) d :=\n      option_default (on_universes fu fc) d.(decl_body) true &&\n      on_universes fu fc d.(decl_type).\n\n  Definition wf_decl_universes Σ := on_decl_universes (wf_universeb Σ) closedu.\n\n  Definition on_ctx_universes (fu : Universe.t -> bool) (fc : nat -> term -> bool) Γ :=\n    forallb (on_decl_universes fu fc) Γ.\n\n  Definition wf_ctx_universes Σ Γ :=\n    forallb (wf_decl_universes Σ) Γ.\n\n  Lemma wf_universes_it_mkProd_or_LetIn {Σ Γ T} :\n    wf_universes Σ (it_mkProd_or_LetIn Γ T) = wf_ctx_universes Σ Γ && wf_universes Σ T.\n  Proof using Type.\n    induction Γ as [ |[na [b|] ty] Γ] using rev_ind ; simpl; auto;\n    rewrite it_mkProd_or_LetIn_app {1}/wf_universes /=\n    -!/(wf_universes _ _) IHΓ /wf_ctx_universes forallb_app /=\n    {3}/wf_decl_universes -!/(wf_universes _ _) / on_decl_universes /= /wf_universes;\n    repeat bool_congr.\n\n  Qed.\n\n  Lemma test_context_app p Γ Δ :\n    test_context p (Γ ,,, Δ) = test_context p Γ && test_context p Δ.\n  Proof using Type.\n    induction Δ; simpl; auto.\n    - now rewrite andb_true_r.\n    - now rewrite IHΔ andb_assoc.\n  Qed.\n\n\n  Lemma wf_universes_it_mkLambda_or_LetIn {Σ Γ T} :\n    wf_universes Σ (it_mkLambda_or_LetIn Γ T) = test_context (wf_universes Σ) Γ && wf_universes Σ T.\n  Proof using Type.\n    induction Γ as [ |[na [b|] ty] Γ] using rev_ind; simpl; auto;\n    now rewrite it_mkLambda_or_LetIn_app {1}/wf_universes\n      /= -!/(wf_universes _ _) IHΓ test_context_app /= /test_decl /= ;\n    repeat bool_congr.\n  Qed.\n\n  Lemma wf_projs Σ ind npars p :\n    All (fun t : term => wf_universes Σ t) (projs ind npars p).\n  Proof using Type.\n    induction p; simpl; auto.\n  Qed.\n\n  Lemma wf_extended_subst Σ Γ n :\n    wf_ctx_universes Σ Γ ->\n    All (fun t : term => wf_universes Σ t) (extended_subst Γ n).\n  Proof using Type.\n    induction Γ as [|[na [b|] ty] Γ] in n |- *; simpl; auto.\n    move=> /andP []; rewrite /wf_decl_universes /= => /andP [] wfb wfty wfΓ.\n    constructor; eauto. rewrite wf_universes_subst //. now apply IHΓ.\n    now rewrite wf_universes_lift. eauto.\n    move=> /andP []; rewrite /wf_decl_universes /= => wfty wfΓ.\n    constructor; eauto.\n  Qed.\n\n  Lemma closedu_compare_decls k Γ Δ :\n    All2 (PCUICEquality.compare_decls eq eq) Γ Δ ->\n    test_context (closedu k) Γ = test_context (closedu k) Δ.\n  Proof using Type.\n    induction 1; cbn; auto.\n    f_equal; auto. destruct r; subst; auto.\n  Qed.\n\n  Lemma closedu_mkApps k f args : closedu k (mkApps f args) = closedu k f && forallb (closedu k) args.\n  Proof using Type.\n    induction args in f |- *; cbn; auto. ring.\n    rewrite IHargs /=. ring.\n  Qed.\n\n  Lemma closedu_abstract_instance univs : closedu_instance #|abstract_instance univs| (abstract_instance univs).\n  Proof using Type.\n    destruct univs as [|[l csts]] => // /=.\n    rewrite /UContext.instance /AUContext.repr.\n    rewrite /closedu_instance forallb_mapi //.\n    intros i hi. cbn; len. now eapply Nat.ltb_lt.\n  Qed.\n\n  Notation closedu_ctx k := (test_context (closedu k)).\n\n  Lemma closedu_lift k n k' t :\n    closedu k (lift n k' t) = closedu k t.\n  Proof using Type.\n    induction t in k' |- * using term_forall_list_ind; cbn; auto; intros; solve_all.\n    - rewrite IHt.\n      rewrite /map_predicate_k /= /test_predicate /test_predicate_ku /= /id.\n      f_equal. f_equal. rewrite e. f_equal. f_equal. f_equal.\n      solve_all.\n      solve_all.\n      rewrite /map_branch_k /test_branch /=. f_equal.\n      now rewrite b.\n    - rewrite /test_def /map_def /=. now rewrite a b.\n    - rewrite /test_def /map_def /=. now rewrite a b.\n  Qed.\n\n  Ltac try_hyp :=\n    multimatch goal with H : _ |- _ => eapply H end.\n\n  Ltac crush := repeat (solve_all; try try_hyp; cbn).\n\n\n  Lemma closedu_subst k s k' t :\n    forallb (closedu k) s && closedu k t ->\n    closedu k (subst s k' t).\n  Proof using Type.\n    Ltac t := repeat (solve_all; try try_hyp).\n    induction t in k' |- * using term_forall_list_ind; cbn; auto; intros;\n      try solve [t].\n    - destruct Nat.leb => //.\n      destruct nth_error eqn:eq => //.\n      rewrite closedu_lift.\n      eapply nth_error_forallb in eq; tea. solve_all.\n    - unfold test_predicate_ku in *. unfold test_branch in *. crush.\n    - unfold test_def in *; crush.\n    - unfold test_def in *; crush.\n  Qed.\n\n  Lemma closedu_subst_context k s k' Γ :\n    forallb (closedu k) s && closedu_ctx k Γ ->\n    closedu_ctx k (subst_context s k' Γ).\n  Proof using Type.\n    rewrite /subst_context.\n    induction Γ.\n    * cbn; auto.\n    * rtoProp. intros []. cbn in H0. rtoProp.\n      rewrite fold_context_k_snoc0 /= IHΓ //. crush.\n      unfold test_decl in *. crush.\n      destruct decl_body eqn:heq => /= //.\n      rewrite closedu_subst //. crush.\n      rewrite closedu_subst //. crush.\n  Qed.\n\n  Lemma closedu_lift_context k n k' Γ :\n    closedu_ctx k (lift_context n k' Γ) = closedu_ctx k Γ.\n  Proof using Type.\n    rewrite /lift_context.\n    induction Γ.\n    * cbn; auto.\n    * rtoProp.\n      rewrite fold_context_k_snoc0 /= IHΓ //.\n      unfold test_decl in *.\n      cbn.\n      rewrite closedu_lift.\n      destruct (decl_body a) => /= //.\n      rewrite closedu_lift //.\n  Qed.\n\n  Lemma closedu_extended_subst k Γ k' :\n    closedu_ctx k Γ ->\n    forallb (closedu k) (extended_subst Γ k').\n  Proof using Type.\n    induction Γ in k' |- *; cbn; auto. destruct a as [na [b|] ty] => /= //.\n    unfold test_decl; move/andP=> [] clΓ /= cld. apply/andP. split.\n    eapply closedu_subst. rewrite IHΓ // /= closedu_lift. crush.\n    now rewrite IHΓ.\n    unfold test_decl; move/andP=> [] clΓ /= cld. now apply IHΓ.\n  Qed.\n\n  Lemma closedu_expand_lets_ctx k Γ Δ :\n    closedu_ctx k Γ && closedu_ctx k Δ ->\n    closedu_ctx k (expand_lets_ctx Γ Δ).\n  Proof using Type.\n    rewrite /expand_lets_ctx /expand_lets_k_ctx.\n    move/andP => [] clΓ clΔ.\n    apply closedu_subst_context.\n    rewrite closedu_extended_subst // /= closedu_lift_context //.\n  Qed.\n\n  Lemma closedu_smash_context_gen k Γ Δ :\n    closedu_ctx k Γ -> closedu_ctx k Δ ->\n    closedu_ctx k (smash_context Γ Δ).\n  Proof using Type.\n    induction Δ in Γ |- *; cbn; auto.\n    move=> clΓ /andP[] clΔ cla.\n    destruct a as [na [b|] ty] => //.\n    - apply IHΔ => //. apply closedu_subst_context => /= //.\n      now move/andP: cla => [] /= -> clty.\n    - apply IHΔ => //.\n      now rewrite test_context_app clΓ /= andb_true_r.\n  Qed.\n\n  Lemma closedu_smash_context k Δ :\n    closedu_ctx k Δ ->\n    closedu_ctx k (smash_context [] Δ).\n  Proof using Type.\n    apply closedu_smash_context_gen => //.\n  Qed.\n\n  Lemma wf_universe_level_closed {Σ : global_env} {wfΣ : wf Σ} univs u :\n    on_udecl_prop Σ univs ->\n    wf_universe_level (Σ, univs) u -> closedu_level #|polymorphic_instance univs| u.\n  Proof using Type.\n    intros ond Ht; destruct u => //.\n    cbn in Ht. unfold closedu_universe, closedu_universe_levels.\n    cbn. red in Ht.\n    eapply in_var_global_ext in Ht => //.\n    cbn in Ht.\n    destruct (udecl_prop_in_var_poly (Σ := (Σ, univs)) ond Ht) as [ctx eq].\n    cbn in eq. subst univs.\n    cbn in Ht. cbn. unfold AUContext.levels in Ht.\n    eapply (proj1 (LevelSetProp.of_list_1 _ _)) in Ht.\n    eapply InA_In_eq in Ht.\n    destruct ctx as [names cstrs].\n    unfold AUContext.repr in Ht |- *. cbn in *. len.\n    rewrite mapi_unfold in Ht. eapply In_unfold_var in Ht as [k []].\n    eapply Nat.leb_le. noconf H0. lia.\n  Qed.\n\n  Lemma wf_universe_closed {Σ : global_env} {wfΣ : wf Σ} univs u :\n    on_udecl_prop Σ univs ->\n    wf_universe (Σ, univs) u -> closedu #|polymorphic_instance univs| (tSort u).\n  Proof using Type.\n    intros ond Ht; destruct u => //.\n    cbn in Ht. unfold closedu_universe, closedu_universe_levels.\n    eapply LevelExprSet.for_all_spec.\n    intros x y ?; subst; auto.\n    intros i hi. specialize (Ht i hi).\n    unfold closedu_level_expr.\n    apply wf_universe_level_closed => //.\n  Qed.\n\n  Lemma wf_universe_instance_closed {Σ : global_env} {wfΣ : wf Σ} {univs u} :\n    on_udecl_prop Σ univs ->\n    wf_universe_instance (Σ, univs) u ->\n    closedu_instance #|polymorphic_instance univs| u.\n  Proof using Type.\n    intros ond Ht.\n    red in Ht. unfold closedu_instance. solve_all.\n    now eapply wf_universe_level_closed.\n  Qed.\n\n  Lemma wf_universes_closedu {Σ : global_env} {wfΣ : wf Σ} {univs t} :\n    on_udecl_prop Σ univs ->\n    wf_universes (Σ, univs) t -> closedu #|polymorphic_instance univs| t.\n  Proof using Type.\n    intros ond. induction t using term_forall_list_ind; cbn => //; solve_all.\n    - apply wf_universe_closed => //.\n      now move/wf_universe_reflect: H.\n    - eapply wf_universe_instance_closed => //.\n      apply All_forallb in H.\n      rewrite -forallb_map wf_universeb_instance_forall in H.\n      now move/wf_universe_instanceP: H.\n    - eapply wf_universe_instance_closed => //.\n      apply All_forallb in H.\n      rewrite -forallb_map wf_universeb_instance_forall in H.\n      now move/wf_universe_instanceP: H.\n    - eapply wf_universe_instance_closed => //.\n      apply All_forallb in H.\n      rewrite -forallb_map wf_universeb_instance_forall in H.\n      now move/wf_universe_instanceP: H.\n    - unfold test_predicate_ku in *; solve_all.\n      eapply wf_universe_instance_closed => //.\n      apply All_forallb in H0.\n      rewrite -forallb_map wf_universeb_instance_forall in H0.\n      now move/wf_universe_instanceP: H0.\n    - unfold test_branch in *; solve_all.\n    - unfold test_def in *; solve_all.\n    - unfold test_def in *; solve_all.\n  Qed.\n\n  Lemma wf_ctx_universes_closed {Σ} {wfΣ : wf Σ} {univs ctx} :\n    on_udecl_prop Σ univs ->\n    wf_ctx_universes (Σ, univs) ctx ->\n    closedu_ctx #|polymorphic_instance univs| ctx.\n  Proof using Type.\n    intros ond. induction ctx => //.\n    rewrite /wf_ctx_universes /= => /andP[] wfa wfctx.\n    rewrite IHctx // /=.\n    unfold wf_decl_universes, test_decl in *.\n    destruct a as [na [b|] ty]; cbn in *.\n    move/andP: wfa => [].\n    now do 2 move/(wf_universes_closedu ond) => ->.\n    now move/(wf_universes_closedu ond): wfa => ->.\n  Qed.\n\n\n  Lemma closedu_reln k Γ k' acc :\n    closedu_ctx k Γ ->\n    forallb (closedu k) acc ->\n    forallb (closedu k) (reln acc k' Γ).\n  Proof using Type.\n    induction Γ in acc, k' |- *; cbn; auto.\n    destruct a as [na [b|] ty] => /= //.\n    - unfold test_decl; move/andP=> [] clΓ /= cld. now eapply IHΓ.\n    - unfold test_decl; move/andP=> [] clΓ /= cld clacc; now apply IHΓ => //.\n  Qed.\n\n  Lemma closedu_to_extended_list_k k Γ k' :\n    closedu_ctx k Γ ->\n    forallb (closedu k) (to_extended_list_k Γ k').\n  Proof using Type.\n    intros clΓ. apply closedu_reln => //.\n  Qed.\n\n  Lemma closed_ind_predicate_context {Σ ind mdecl idecl} {wfΣ : wf Σ} :\n    declared_inductive Σ ind mdecl idecl ->\n    closedu_ctx #|polymorphic_instance (ind_universes mdecl)|\n        (ind_params mdecl) ->\n    closedu_ctx #|polymorphic_instance (ind_universes mdecl)|\n            (ind_indices idecl) ->\n    test_context (closedu #|abstract_instance (ind_universes mdecl)|) (ind_predicate_context ind mdecl idecl).\n  Proof using Type.\n    intros decli.\n    rewrite /ind_predicate_context; cbn.\n    rewrite closedu_mkApps /=.\n    rewrite closedu_abstract_instance /= => clpars clinds.\n    apply/andP; split.\n    * apply closedu_expand_lets_ctx. now rewrite clpars clinds.\n    * apply closedu_to_extended_list_k.\n      rewrite test_context_app.\n      rewrite (closedu_smash_context _ _ clpars).\n      apply closedu_expand_lets_ctx => //.\n      now rewrite clpars.\n  Qed.\n\n  Lemma closedu_inds {Σ ind mdecl} {wfΣ : wf Σ} :\n    forallb (closedu #|abstract_instance (ind_universes mdecl)|)\n      (inds ind (abstract_instance (ind_universes mdecl)) (ind_bodies mdecl)).\n  Proof using Type.\n    rewrite /inds.\n    induction #|ind_bodies mdecl|; cbn; auto.\n    rewrite IHn andb_true_r.\n    eapply closedu_abstract_instance.\n  Qed.\n\n  Theorem wf_types :\n    env_prop (fun Σ Γ t T =>\n      wf_universes Σ t && wf_universes Σ T)\n      (fun Σ Γ =>\n      All_local_env\n      (lift_typing (fun (Σ : global_env_ext) (Γ : context) (t T : term) =>\n         wf_universes Σ t && wf_universes Σ T) Σ) Γ ×\n         test_context (wf_universes Σ) Γ).\n  Proof using Type.\n    apply typing_ind_env; intros; rename_all_hyps; cbn; rewrite -!/(wf_universes _ _) ;\n    specIH; to_prop;\n    cbn; auto.\n\n    - split.\n      * induction X; constructor; auto.\n        destruct tu as [s tu]; exists s; simpl.\n        now simpl in Hs.\n        destruct tu as [s tu]; exists s; simpl.\n        now simpl in Hs.\n      * induction X; simpl; auto.\n        rewrite IHX /= /test_decl /=. now move/andP: Hs.\n\n    - rewrite wf_universes_lift.\n      destruct X as [X _].\n      pose proof (nth_error_Some_length heq_nth_error).\n      eapply nth_error_All_local_env in X; tea.\n      rewrite heq_nth_error /= in X. red in X.\n      destruct decl as [na [b|] ty]; cbn -[skipn] in *.\n      + now to_prop.\n      + destruct X as [s Hs]. now to_prop.\n\n    - apply/andP; split; to_wfu; cbn ; eauto with pcuic.\n\n    - cbn in *; to_wfu ; eauto with pcuic.\n    - rewrite wf_universes_subst. constructor. to_wfu; auto. constructor.\n      now move/andP: H4 => [].\n\n    - apply/andP; split.\n      { rewrite wf_universeb_instance_forall.\n        apply/wf_universe_instanceP.\n        eapply consistent_instance_ext_wf; eauto. }\n      pose proof (declared_constant_inv _ _ _ _ wf_universes_weaken wf X H).\n      red in X1; cbn in X1.\n      unshelve eapply declared_constant_to_gen in H; eauto.\n      destruct (cst_body decl).\n      * to_prop.\n        epose proof (weaken_lookup_on_global_env' Σ.1 _ _ wf H).\n        eapply wf_universes_inst. 2:eauto. all:eauto.\n        simpl in H2.\n        now eapply consistent_instance_ext_wf.\n      * move: X1 => [s /andP[Hc _]].\n        to_prop.\n        eapply wf_universes_inst; eauto.\n        exact (weaken_lookup_on_global_env' Σ.1 _ _ wf H).\n        now eapply consistent_instance_ext_wf.\n\n    - apply/andP; split.\n      { rewrite wf_universeb_instance_forall.\n        apply/wf_universe_instanceP.\n        eapply consistent_instance_ext_wf; eauto. }\n      pose proof (declared_inductive_inv wf_universes_weaken wf X isdecl).\n      cbn in X1. eapply onArity in X1. cbn in X1.\n      move: X1 => [s /andP[Hind ?]].\n      unshelve eapply declared_inductive_to_gen in isdecl; eauto.\n      eapply wf_universes_inst; eauto.\n      exact (weaken_lookup_on_global_env' Σ.1 _ _ wf (proj1 isdecl)).\n      now eapply consistent_instance_ext_wf.\n\n    - apply/andP; split.\n      { rewrite wf_universeb_instance_forall.\n        apply/wf_universe_instanceP.\n        eapply consistent_instance_ext_wf; eauto. }\n      pose proof (declared_constructor_inv wf_universes_weaken wf X isdecl) as [sc [nthe onc]].\n      unfold type_of_constructor.\n      rewrite wf_universes_subst.\n      { apply wf_universes_inds.\n        now eapply consistent_instance_ext_wf. }\n      eapply on_ctype in onc. cbn in onc.\n      move: onc=> [_ /andP[onc _]].\n      clear nthe. unshelve eapply declared_constructor_to_gen in isdecl; eauto.\n      eapply wf_universes_inst; eauto.\n      exact (weaken_lookup_on_global_env' Σ.1 _ _ wf (proj1 (proj1 isdecl))).\n      now eapply consistent_instance_ext_wf.\n\n    - rewrite wf_universes_mkApps in H5.\n      move/andP: H5 => /= [] wfu; rewrite forallb_app.\n      move/andP=> [] wfpars wfinds.\n      cbn in wfu.\n      rewrite wfu /= wfpars wf_universes_mkApps /=\n        forallb_app wfinds /= H /= !andb_true_r.\n      pose proof (declared_inductive_inv wf_universes_weaken wf X isdecl).\n      destruct X5. destruct onArity as [s Hs].\n      move/andP: Hs => [] /= hty hs.\n      rewrite ind_arity_eq in hty.\n      rewrite !wf_universes_it_mkProd_or_LetIn in hty.\n      move/and3P: hty => [] wfp wfindis wfisort.\n      have ond : on_udecl_prop Σ (ind_universes mdecl).\n      { eapply (weaken_lookup_on_global_env' _ _ (InductiveDecl mdecl)); eauto.\n      unshelve eapply declared_inductive_to_gen in isdecl; eauto.\n      }\n      eapply wf_ctx_universes_closed in wfp => //.\n      eapply wf_ctx_universes_closed in wfindis => //.\n      rewrite (consistent_instance_length H1).\n      erewrite closedu_compare_decls; tea.\n      rewrite closed_ind_predicate_context // /=.\n      unfold test_branch.\n      apply/andP; split.\n      * have wfbrctx : All (fun cdecl =>\n          closedu_ctx #|polymorphic_instance (ind_universes mdecl)| (cstr_args cdecl))\n          (ind_ctors idecl).\n        { clear -wf ond onConstructors.\n          red in onConstructors. solve_all. destruct X.\n          do 2 red in on_ctype. destruct on_ctype as [s Hs].\n          move/andP: Hs => [] wfty _.\n          rewrite cstr_eq in wfty.\n          rewrite !wf_universes_it_mkProd_or_LetIn in wfty.\n          move/and3P: wfty => [] _ clargs _.\n          apply wf_ctx_universes_closed in clargs => //. }\n        solve_all.\n        erewrite closedu_compare_decls; [|tea].\n        rewrite /cstr_branch_context.\n        eapply closedu_expand_lets_ctx.\n        rewrite wfp. eapply closedu_subst_context.\n        rewrite a1.\n        now rewrite closedu_inds.\n      * rewrite /ptm.\n        rewrite wf_universes_it_mkLambda_or_LetIn H4 andb_true_r.\n        rewrite /predctx.\n        destruct X3 as [_ hctx]. move: hctx.\n        now rewrite test_context_app => /andP[].\n\n    - rewrite /subst1. rewrite wf_universes_subst.\n      constructor => //. eapply All_rev.\n      rewrite wf_universes_mkApps in H1.\n      move/andP: H1 => [].\n      now intros _ hargs%forallb_All.\n      pose proof (declared_projection_inv wf_universes_weaken wf X isdecl).\n      destruct (declared_inductive_inv); simpl in *.\n      destruct ind_ctors as [|cs []] => //.\n      destruct ind_cunivs as [|cunivs []] => //;\n      destruct X1 as [[[? ?] ?] ?] => //.\n      red in o0.\n      destruct nth_error eqn:heq => //.\n      destruct o0  as [_ ->].\n      rewrite wf_universes_mkApps {1}/wf_universes /= -!/(wf_universes _ _)\n        wf_universeb_instance_forall in H1.\n      move/andP: H1 => [/wf_universe_instanceP wfu wfargs].\n      unshelve eapply declared_projection_to_gen in isdecl; eauto.\n      eapply (wf_universes_inst (ind_universes mdecl)); eauto.\n      exact (weaken_lookup_on_global_env' Σ.1 _ _ wf (proj1 (proj1 (proj1 isdecl)))).\n      rewrite wf_universes_subst.\n      eapply wf_universes_inds; eauto.\n      eapply wf_abstract_instance.\n      rewrite wf_universes_subst. apply wf_projs.\n      rewrite wf_universes_lift.\n      rewrite smash_context_app smash_context_acc in heq.\n      autorewrite with len in heq. rewrite nth_error_app_lt in heq.\n      autorewrite with len. lia.\n      rewrite nth_error_subst_context in heq.\n      autorewrite with len in heq. simpl in heq.\n      epose proof (nth_error_lift_context_eq _ (smash_context [] (ind_params mdecl)) _ _).\n      autorewrite with len in H. simpl in H. rewrite -> H in heq. clear H.\n      autorewrite with len in heq.\n      simpl in heq.\n      destruct nth_error eqn:hnth; simpl in * => //.\n      noconf heq. simpl.\n      rewrite wf_universes_subst.\n      apply wf_extended_subst.\n      rewrite ind_arity_eq in onArity. destruct onArity as [s' Hs].\n      rewrite wf_universes_it_mkProd_or_LetIn in Hs.\n      now move/andP: Hs => /andP /andP [] /andP [].\n      rewrite wf_universes_lift.\n      eapply wf_sorts_local_ctx_smash in s.\n      eapply wf_sorts_local_ctx_nth_error in s as [? [? H]]; eauto.\n      red in H. destruct x0. now move/andP: H => [].\n      now destruct H as [s [Hs _]%andb_and].\n\n    - apply/andP; split; auto.\n      solve_all; destruct a0 as (? & _ & ?), b0; rtoProp; tas.\n      eapply nth_error_all in X0; eauto.\n      simpl in X0. now move: X0 => [s [Hty /andP[wfty _]]].\n\n    - apply/andP; split; auto.\n      solve_all; destruct a0 as (? & _ & ?), b0; rtoProp; tas.\n      eapply nth_error_all in X0; eauto.\n      simpl in X0. now move: X0 => [s [Hty /andP[wfty _]]].\n  Qed.\n\n  Lemma typing_wf_universes {Σ : global_env_ext} {Γ t T} :\n    wf Σ ->\n    Σ ;;; Γ |- t : T -> wf_universes Σ t && wf_universes Σ T.\n  Proof using Type.\n    intros wfΣ Hty.\n    exact (env_prop_typing wf_types _ wfΣ _ _ _ Hty).\n  Qed.\n\n  Lemma typing_wf_universe {Σ : global_env_ext} {Γ t s} :\n    wf Σ ->\n    Σ ;;; Γ |- t : tSort s -> wf_universe Σ s.\n  Proof using Type.\n    intros wfΣ Hty.\n    apply typing_wf_universes in Hty as [_ wfs]%andb_and; auto.\n    cbn in wfs. now to_wfu.\n  Qed.\n\n  Lemma isType_wf_universes {Σ Γ T} : wf Σ.1 -> isType Σ Γ T -> wf_universes Σ T.\n  Proof using Type.\n    intros wfΣ [s Hs]. now eapply typing_wf_universes in Hs as [HT _]%andb_and.\n  Qed.\n\nEnd CheckerFlags.\n\nArguments wf_universe_reflect {Σ u}.\n#[global] Hint Resolve wf_universe_type1 wf_universe_super wf_universe_sup wf_universe_product : pcuic.\n\n#[global]\nHint Extern 4 (wf_universe _ ?u) =>\n  match goal with\n  [ H : typing _ _ _ (tSort u) |- _ ] => apply (typing_wf_universe _ H)\n  end : pcuic.\n", "meta": {"author": "MetaCoq", "repo": "metacoq", "sha": "c340242b43ebe26f3bacb1c72ef82b8ca61da632", "save_path": "github-repos/coq/MetaCoq-metacoq", "path": "github-repos/coq/MetaCoq-metacoq/metacoq-c340242b43ebe26f3bacb1c72ef82b8ca61da632/pcuic/theories/PCUICWfUniverses.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20547094960990164}}
{"text": "(** Wasm interpreter **)\n(* (C) J. Pichon, M. Bodin - see LICENSE.txt *)\n\nFrom Wasm Require Import common.\nFrom Coq Require Import ZArith.BinInt.\nFrom mathcomp Require Import ssreflect ssrfun ssrnat ssrbool eqtype seq.\nFrom Wasm Require Export operations host type_checker.\nRequire Import BinNat.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\nUnset Printing Implicit Defensive.\n\nInductive res_crash : Type :=\n| C_error : res_crash\n| C_exhaustion : res_crash.\n\nScheme Equality for res_crash.\nDefinition res_crash_eqb c1 c2 := is_left (res_crash_eq_dec c1 c2).\nDefinition eqres_crashP : Equality.axiom res_crash_eqb :=\n  eq_dec_Equality_axiom res_crash_eq_dec.\n\nCanonical Structure res_crash_eqMixin := EqMixin eqres_crashP.\nCanonical Structure res_crash_eqType := Eval hnf in EqType res_crash res_crash_eqMixin.\n\nInductive res : Type :=\n| R_crash : res_crash -> res\n| R_trap : res\n| R_value : list value -> res.\n\nDefinition res_eq_dec : forall r1 r2 : res, {r1 = r2} + {r1 <> r2}.\nProof. decidable_equality. Defined.\n\nDefinition res_eqb (r1 r2 : res) : bool := res_eq_dec r1 r2.\nDefinition eqresP : Equality.axiom res_eqb :=\n  eq_dec_Equality_axiom res_eq_dec.\n\nCanonical Structure res_eqMixin := EqMixin eqresP.\nCanonical Structure res_eqType := Eval hnf in EqType res res_eqMixin.\n\nSection Host_func.\n\nVariable host_function : eqType.\nLet host := host host_function.\n\nVariable host_instance : host.\n\nLet store_record := store_record host_function.\n(*Let administrative_instruction := administrative_instruction host_function.*)\nLet host_state := host_state host_instance.\n\n(*Let vs_to_es : seq value -> seq administrative_instruction := @vs_to_es _.*)\n\nVariable host_application_impl : host_state -> store_record -> function_type -> host_function -> seq value ->\n                       (host_state * option (store_record * result)).\n\nHypothesis host_application_impl_correct :\n  (forall hs s ft hf vs hs' hres, (host_application_impl hs s ft hf vs = (hs', hres)) -> host_application hs s ft hf vs hs' hres).\n\nInductive res_step : Type :=\n| RS_crash : res_crash -> res_step\n| RS_break : nat -> list value -> res_step\n| RS_return : list value -> res_step\n| RS_normal : list administrative_instruction -> res_step.\n\nDefinition res_step_eq_dec : forall r1 r2 : res_step, {r1 = r2} + {r1 <> r2}.\nProof. decidable_equality. Defined.\n\nDefinition res_step_eqb (r1 r2 : res_step) : bool := res_step_eq_dec r1 r2.\nDefinition eqres_stepP : Equality.axiom res_step_eqb :=\n  eq_dec_Equality_axiom res_step_eq_dec.\n\nCanonical Structure res_step_eqMixin := EqMixin eqres_stepP.\nCanonical Structure res_step_eqType := Eval hnf in EqType res_step res_step_eqMixin.\n\nDefinition crash_error := RS_crash C_error.\n\nDefinition depth := nat.\n\nDefinition fuel := nat.\n\nDefinition config_tuple := ((host_state * store_record * frame * list administrative_instruction)%type).\n\nDefinition config_one_tuple_without_e := (host_state * store_record * frame * list value)%type.\n\nDefinition res_tuple := (host_state * store_record * frame * res_step)%type.\n(*\nFixpoint split_vals (es : list basic_instruction) : ((list value) * (list basic_instruction))%type :=\n  match es with\n  | (EConst v) :: es' =>\n    let: (vs', es'') := split_vals es' in\n    (v :: vs', es'')\n  | _ => ([::], es)\n  end.\n\n(** [split_vals_e es]: takes the maximum initial segment of [es] whose elements\n    are all of the form [AI_basic (EConst v)];\n    returns a pair of lists [(ves, es')] where [ves] are those [v]'s in that initial\n    segment and [es] is the remainder of the original [es]. **)\nFixpoint split_vals_e (es : list administrative_instruction) : ((list value) * (list administrative_instruction))%type :=\n  match es with\n  | (AI_basic (EConst v)) :: es' =>\n    let: (vs', es'') := split_vals_e es' in\n    (v :: vs', es'')\n  | _ => ([::], es)\n  end.\n\nFixpoint split_n (es : list value) (n : nat) : ((list value) * (list value))%type :=\n  match (es, n) with\n  | ([::], _) => ([::], [::])\n  | (_, 0) => ([::], es)\n  | (e :: esX, n.+1) =>\n    let: (es', es'') := split_n esX n in\n    (e :: es', es'')\n  end.\n\nDefinition expect {A B : Type} (ao : option A) (f : A -> B) (b : B) : B :=\n  match ao with\n  | Some a => f a\n  | None => b\n  end.\n\nDefinition vs_to_es (vs : list value) : list administrative_instruction :=\n  v_to_e_list (rev vs).\n\nDefinition e_is_trap (e : administrative_instruction) : bool :=\n  match e with\n  | AI_trap => true\n  | _ => false\n  end.\n\nLemma e_is_trapP : forall e, reflect (e = AI_trap) (e_is_trap e).\nProof.\n  case => //= >; by [ apply: ReflectF | apply: ReflectT ].\nQed.\n\n(** [es_is_trap es] is equivalent to [es == [:: AI_trap]]. **)\nDefinition es_is_trap (es : list administrative_instruction) : bool :=\n  match es with\n  | [::e] => e_is_trap e\n  | _ => false\n  end.\n\nLemma es_is_trapP : forall l, reflect (l = [::AI_trap]) (es_is_trap l).\nProof.\n  case; first by apply: ReflectF.\n  move=> // a l. case l => //=.\n  - apply: (iffP (e_is_trapP _)); first by elim.\n    by inversion 1.\n  - move=> >. by apply: ReflectF.\nQed.*)\n\nFixpoint run_step_with_fuel (fuel : fuel) (d : depth) (cfg : config_tuple) : res_tuple :=\n  let: (hs, s, f, es) := cfg in\n  match fuel with\n  | 0 => (hs, s, f, RS_crash C_exhaustion)\n  | fuel.+1 =>\n    let: (ves, es') := split_vals_e es in (** Framing out constants. **)\n    match es' with\n    | [::] => (hs, s, f, crash_error)\n    | e :: es'' =>\n      if e_is_trap e\n      then\n        if (es'' != [::]) || (ves != [::])\n        then (hs, s, f, RS_normal [::AI_trap])\n        else (hs, s, f, crash_error)\n      else\n        let: (hs', s', f', r) := run_one_step fuel d (hs, s, f, (rev ves)) e in\n        if r is RS_normal res\n        then (hs', s', f', RS_normal (res ++ es''))\n        else (hs', s', f', r)\n    end\n  end\n    \nwith run_one_step (fuel : fuel) (d : depth) (cfg : config_one_tuple_without_e) (e : administrative_instruction) : res_tuple :=\n  let: (hs, s, f, ves) := cfg in\n  match fuel with\n  | 0 => (hs, s, f, RS_crash C_exhaustion)\n  | fuel.+1 =>\n    match e with\n    (* unop *)\n    | AI_basic (BI_unop t op) =>\n      if ves is v :: ves' then\n        (hs, s, f, RS_normal (vs_to_es (app_unop op v :: ves')))\n      else (hs, s, f, crash_error)\n    (* binop *)\n    | AI_basic (BI_binop t op) =>\n      if ves is v2 :: v1 :: ves' then\n        expect (app_binop op v1 v2)\n               (fun v => (hs, s, f, RS_normal (vs_to_es (v :: ves'))))\n               (hs, s, f, RS_normal ((vs_to_es ves') ++ [::AI_trap]))\n      else (hs, s, f, crash_error)\n    (* testops *)\n    | AI_basic (BI_testop T_i32 testop) =>\n      if ves is (VAL_int32 c) :: ves' then\n        (hs, s, f, RS_normal (vs_to_es ((VAL_int32 (wasm_bool (@app_testop_i i32t testop c))) :: ves')))\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_testop T_i64 testop) =>\n      if ves is (VAL_int64 c) :: ves' then\n        (hs, s, f, RS_normal (vs_to_es ((VAL_int32 (wasm_bool (@app_testop_i i64t testop c))) :: ves')))\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_testop _ _) => (hs, s, f, crash_error)\n    (* relops *)\n    | AI_basic (BI_relop t op) =>\n      if ves is v2 :: v1 :: ves' then\n        (hs, s, f, RS_normal (vs_to_es (VAL_int32 (wasm_bool (app_relop op v1 v2)) :: ves')))\n      else (hs, s, f, crash_error)\n    (* convert & reinterpret *)\n    | AI_basic (BI_cvtop t2 CVO_convert t1 sx) =>\n      if ves is v :: ves' then\n        if types_agree t1 v\n        then\n          expect (cvt t2 sx v) (fun v' =>\n               (hs, s, f, RS_normal (vs_to_es (v' :: ves'))))\n            (hs, s, f, RS_normal ((vs_to_es ves') ++ [::AI_trap]))\n        else (hs, s, f, crash_error)\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_cvtop t2 CVO_reinterpret t1 sx) =>\n      if ves is v :: ves' then\n        if types_agree t1 v && (sx == None)\n        then (hs, s, f, RS_normal (vs_to_es (wasm_deserialise (bits v) t2 :: ves')))\n        else (hs, s, f, crash_error)\n      else (hs, s, f, crash_error)\n    (**)\n    | AI_basic BI_unreachable => (hs, s, f, RS_normal ((vs_to_es ves) ++ [::AI_trap]))\n    | AI_basic BI_nop => (hs, s, f, RS_normal (vs_to_es ves))\n    | AI_basic BI_drop =>\n      if ves is v :: ves' then\n        (hs, s, f, RS_normal (vs_to_es ves'))\n      else (hs, s, f, crash_error)\n    | AI_basic BI_select =>\n      if ves is (VAL_int32 c) :: v2 :: v1 :: ves' then\n        if c == Wasm_int.int_zero i32m\n        then (hs, s, f, RS_normal (vs_to_es (v2 :: ves')))\n        else (hs, s, f, RS_normal (vs_to_es (v1 :: ves')))\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_block (Tf t1s t2s) es) =>\n      if length ves >= length t1s\n      then\n        let: (ves', ves'')  := split_n ves (length t1s) in\n        (hs, s, f, RS_normal (vs_to_es ves''\n                ++ [::AI_label (length t2s) [::] (vs_to_es ves' ++ to_e_list es)]))\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_loop (Tf t1s t2s) es) =>\n      if length ves >= length t1s\n      then\n        let: (ves', ves'') := split_n ves (length t1s) in\n        (hs, s, f, RS_normal (vs_to_es ves''\n                ++ [::AI_label (length t1s) [::AI_basic (BI_loop (Tf t1s t2s) es)]\n                        (vs_to_es ves' ++ to_e_list es)]))\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_if tf es1 es2) =>\n      if ves is VAL_int32 c :: ves' then\n        if c == Wasm_int.int_zero i32m\n        then (hs, s, f, RS_normal (vs_to_es ves' ++ [::AI_basic (BI_block tf es2)]))\n        else (hs, s, f, RS_normal (vs_to_es ves' ++ [::AI_basic (BI_block tf es1)]))\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_br j) => (hs, s, f, RS_break j ves)\n    | AI_basic (BI_br_if j) =>\n      if ves is VAL_int32 c :: ves' then\n        if c == Wasm_int.int_zero i32m\n        then (hs, s, f, RS_normal (vs_to_es ves'))\n        else (hs, s, f, RS_normal (vs_to_es ves' ++ [::AI_basic (BI_br j)]))\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_br_table js j) =>\n      if ves is VAL_int32 c :: ves' then\n        let: k := Wasm_int.nat_of_uint i32m c in\n        if k < length js\n        then\n          expect (List.nth_error js k) (fun js_at_k =>\n              (hs, s, f, RS_normal (vs_to_es ves' ++ [::AI_basic (BI_br js_at_k)])))\n            (hs, s, f, crash_error)\n        else (hs, s, f, RS_normal (vs_to_es ves' ++ [::AI_basic (BI_br j)]))\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_call j) =>\n      if List.nth_error f.(f_inst).(inst_funcs) j is Some a then\n        (hs, s, f, RS_normal (vs_to_es ves ++ [::AI_invoke a]))\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_call_indirect j) =>\n      if ves is VAL_int32 c :: ves' then\n        match stab_addr s f (Wasm_int.nat_of_uint i32m c) with\n        | Some a =>\n          match List.nth_error s.(s_funcs) a with\n          | Some cl =>\n            if stypes s f.(f_inst) j == Some (cl_type cl)\n            then (hs, s, f, RS_normal (vs_to_es ves' ++ [::AI_invoke a]))\n            else (hs, s, f, RS_normal (vs_to_es ves' ++ [::AI_trap]))        \n          | None => (hs, s, f, crash_error)\n          end\n        | None => (hs, s, f, RS_normal (vs_to_es ves' ++ [::AI_trap]))\n        end\n      else (hs, s, f, crash_error)\n    | AI_basic BI_return => (hs, s, f, RS_return ves)\n    | AI_basic (BI_get_local j) =>\n      if j < length f.(f_locs)\n      then\n        expect (List.nth_error f.(f_locs) j) (fun vs_at_j =>\n            (hs, s, f, RS_normal (vs_to_es (vs_at_j :: ves))))\n          (hs, s, f, crash_error)\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_set_local j) =>\n      if ves is v :: ves' then\n        if j < length f.(f_locs)\n        then (hs, s, Build_frame (update_list_at f.(f_locs) j v) f.(f_inst), RS_normal (vs_to_es ves'))\n        else (hs, s, f, crash_error)\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_tee_local j) =>\n      if ves is v :: ves' then\n        (hs, s, f, RS_normal (vs_to_es (v :: ves) ++ [::AI_basic (BI_set_local j)]))\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_get_global j) =>\n      if sglob_val s f.(f_inst) j is Some xx\n      then (hs, s, f, RS_normal (vs_to_es (xx :: ves)))\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_set_global j) =>\n      if ves is v :: ves' then\n        if supdate_glob s f.(f_inst) j v is Some xx\n        then (hs, xx, f, RS_normal (vs_to_es ves'))\n        else (hs, s, f, crash_error)\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_load t None a off) =>\n      if ves is VAL_int32 k :: ves' then\n        expect\n          (smem_ind s f.(f_inst))\n          (fun j =>\n             if List.nth_error s.(s_mems) j is Some mem_s_j then\n               expect\n                 (load (mem_s_j) (Wasm_int.N_of_uint i32m k) off (t_length t))\n                 (fun bs => (hs, s, f, RS_normal (vs_to_es (wasm_deserialise bs t :: ves'))))\n                 (hs, s, f, RS_normal (vs_to_es ves' ++ [::AI_trap]))\n             else (hs, s, f, crash_error))\n          (hs, s, f, crash_error)\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_load t (Some (tp, sx)) a off) =>\n      if ves is VAL_int32 k :: ves' then\n        expect\n          (smem_ind s f.(f_inst))\n          (fun j =>\n             if List.nth_error s.(s_mems) j is Some mem_s_j then\n               expect\n                 (load_packed sx (mem_s_j) (Wasm_int.N_of_uint i32m k) off (tp_length tp) (t_length t))\n                 (fun bs => (hs, s, f, RS_normal (vs_to_es (wasm_deserialise bs t :: ves'))))\n                 (hs, s, f, RS_normal (vs_to_es ves' ++ [::AI_trap]))\n             else (hs, s, f, crash_error))\n          (hs, s, f, crash_error)\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_store t None a off) =>\n      if ves is v :: VAL_int32 k :: ves' then\n        if types_agree t v\n        then\n          expect\n            (smem_ind s f.(f_inst))\n            (fun j =>\n               if List.nth_error s.(s_mems) j is Some mem_s_j then\n                 expect\n                   (store mem_s_j (Wasm_int.N_of_uint i32m k) off (bits v) (t_length t))\n                   (fun mem' =>\n                      (hs, upd_s_mem s (update_list_at s.(s_mems) j mem'), f, RS_normal (vs_to_es ves')))\n                   (hs, s, f, RS_normal (vs_to_es ves' ++ [::AI_trap]))\n               else (hs, s, f, crash_error))\n            (hs, s, f, crash_error)\n        else (hs, s, f, crash_error)\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_store t (Some tp) a off) =>\n      if ves is v :: VAL_int32 k :: ves' then\n        if types_agree t v\n        then\n          expect\n            (smem_ind s f.(f_inst))\n            (fun j =>\n               if List.nth_error s.(s_mems) j is Some mem_s_j then\n                 expect\n                   (store_packed mem_s_j (Wasm_int.N_of_uint i32m k) off (bits v) (tp_length tp))\n                   (fun mem' =>\n                      (hs, upd_s_mem s (update_list_at s.(s_mems) j mem'), f, RS_normal (vs_to_es ves')))\n                   (hs, s, f, RS_normal (vs_to_es ves' ++ [::AI_trap]))\n               else (hs, s, f, crash_error))\n            (hs, s, f, crash_error)\n        else (hs, s, f, crash_error)\n      else (hs, s, f, crash_error)\n    | AI_basic BI_current_memory =>\n      expect\n        (smem_ind s f.(f_inst))\n        (fun j =>\n           if List.nth_error s.(s_mems) j is Some s_mem_s_j then\n             (hs, s, f, RS_normal (vs_to_es (VAL_int32 (Wasm_int.int_of_Z i32m (Z.of_nat (mem_size s_mem_s_j))) :: ves)))\n           else (hs, s, f, crash_error))\n        (hs, s, f, crash_error)\n    | AI_basic BI_grow_memory =>\n      if ves is VAL_int32 c :: ves' then\n        expect\n          (smem_ind s f.(f_inst))\n          (fun j =>\n            if List.nth_error s.(s_mems) j is Some s_mem_s_j then\n              let: l := mem_size s_mem_s_j in\n              let: mem' := mem_grow s_mem_s_j (Wasm_int.N_of_uint i32m c) in\n              if mem' is Some mem'' then\n                (hs, upd_s_mem s (update_list_at s.(s_mems) j mem''), f,\n                 RS_normal (vs_to_es (VAL_int32 (Wasm_int.int_of_Z i32m (Z.of_nat l)) :: ves')))\n              else (hs, s, f, crash_error)\n            else (hs, s, f, crash_error))\n          (hs, s, f, crash_error)\n      else (hs, s, f, crash_error)\n    | AI_basic (BI_const _) => (hs, s, f, crash_error)\n    | AI_invoke a =>\n      match List.nth_error s.(s_funcs) a with\n      | Some cl => \n        match cl with\n        | FC_func_native i (Tf t1s t2s) ts es =>\n            let: n := length t1s in\n            let: m := length t2s in\n            if length ves >= n\n            then\n            let: (ves', ves'') := split_n ves n in\n            let: zs := n_zeros ts in\n            (hs, s, f, RS_normal (vs_to_es ves''\n                    ++ [::AI_local m (Build_frame (rev ves' ++ zs) i) [::AI_basic (BI_block (Tf [::] t2s) es)]]))\n            else (hs, s, f, crash_error)\n        | FC_func_host (Tf t1s t2s) cl' =>\n            let: n := length t1s in\n            let: m := length t2s in\n            if length ves >= n\n            then\n            let: (ves', ves'') := split_n ves n in\n            match host_application_impl hs s (Tf t1s t2s) cl' (rev ves') with\n            | (hs', Some (s', rves)) =>\n                (hs', s', f, RS_normal (vs_to_es ves'' ++ (result_to_stack rves)))\n            | (hs', None) => (hs', s, f, RS_normal (vs_to_es ves ++ [::AI_invoke a]))\n            end\n            else (hs, s, f, crash_error)\n        end\n      | None => (hs, s, f, crash_error)\n      end\n    | AI_label ln les es =>\n      if es_is_trap es\n      then (hs, s, f, RS_normal (vs_to_es ves ++ [::AI_trap]))\n      else\n        if const_list es\n        then (hs, s, f, RS_normal (vs_to_es ves ++ es))\n        else\n          let: (hs', s', f', res) := run_step_with_fuel fuel d (hs, s, f, es) in\n          match res with\n          | RS_break 0 bvs =>\n            if length bvs >= ln\n            then (hs', s', f', RS_normal ((vs_to_es ((take ln bvs) ++ ves)) ++ les))\n            else (hs', s', f', crash_error)\n          | RS_break (n.+1) bvs => (hs', s', f', RS_break n bvs)\n          | RS_return rvs => (hs', s', f', RS_return rvs)\n          | RS_normal es' =>\n            (hs', s', f', RS_normal (vs_to_es ves ++ [::AI_label ln les es']))\n          | RS_crash error => (hs', s', f', RS_crash error)\n          end\n    | AI_local ln lf es =>\n      if es_is_trap es\n      then (hs, s, f, RS_normal (vs_to_es ves ++ [::AI_trap]))\n      else\n        if const_list es\n        then\n          if length es == ln\n          then (hs, s, f, RS_normal (vs_to_es ves ++ es))\n          else (hs, s, f, crash_error)\n        else\n          let: (hs', s', f', res) := run_step_with_fuel fuel d (hs, s, lf, es) in\n          match res with\n          | RS_return rvs =>\n            if length rvs >= ln\n            then (hs', s', f, RS_normal (vs_to_es (take ln rvs ++ ves)))\n            else (hs', s', f, crash_error)\n          | RS_normal es' =>\n            (hs', s', f, RS_normal (vs_to_es ves ++ [::AI_local ln f' es']))\n          | RS_crash error => (hs', s', f, RS_crash error)\n          | RS_break _ _ => (hs', s', f, crash_error)\n          end\n    | AI_trap => (hs, s, f, crash_error)\n    end\n  end.\n\n(** Enough fuel so that [run_one_step] does not run out of exhaustion. **)\nDefinition run_one_step_fuel : administrative_instruction -> nat.\nProof.\n  move=> es. induction es using administrative_instruction_rect';\n    let rec aux v :=\n      lazymatch goal with\n      | F : TProp.Forall _ _ |- _ =>\n        apply TProp.max in F;\n        move: F;\n        let n := fresh \"n\" in\n        move=> n;\n        aux (n + v)\n      | |- _ => exact (v.+1)\n      end in\n    aux (1 : nat).\nDefined.\n\n(** Enough fuel so that [run_step] does not run out of exhaustion. **)\nDefinition run_step_fuel (cfg : config_tuple) : nat :=\n  let: (hs, s, f, es) := cfg in\n  1 + List.fold_left max (List.map run_one_step_fuel es) 0.\n\nDefinition run_step (d : depth) (cfg : config_tuple) : res_tuple :=\n  run_step_with_fuel (run_step_fuel cfg) d cfg.\n\nFixpoint run_v (fuel : fuel) (d : depth) (cfg : config_tuple) : ((host_state * store_record * res)%type) :=\n  let: (hs, s, f, es) := cfg in\n  match fuel with\n  | 0 => (hs, s, R_crash C_exhaustion)\n  | fuel.+1 =>\n    if es_is_trap es\n    then (hs, s, R_trap)\n    else\n      if const_list es\n      then (hs, s, R_value (fst (split_vals_e es)))\n      else\n        let: (hs', s', f', res) := run_step d (hs, s, f, es) in\n        match res with\n        | RS_normal es' => run_v fuel d (hs', s', f', es')\n        | RS_crash error => (hs', s', R_crash error)\n        | _ => (hs', s', R_crash C_error)\n        end\n  end.\n\nEnd Host_func.\n", "meta": {"author": "WasmCert", "repo": "WasmCert-Coq", "sha": "df58f3517170fa3cf8b9206ec86f8d7ce66a57d2", "save_path": "github-repos/coq/WasmCert-WasmCert-Coq", "path": "github-repos/coq/WasmCert-WasmCert-Coq/WasmCert-Coq-df58f3517170fa3cf8b9206ec86f8d7ce66a57d2/theories/interpreter_func.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.20547094960990162}}
{"text": "From Coq Require Import Arith ZArith OrderedType.\nFrom mathcomp Require Import ssreflect ssrfun ssrbool ssrnat eqtype seq.\nFrom nbits Require Import NBits.\nFrom ssrlib Require Import Types SsrOrder Var Nats ZAriths Tactics.\nFrom BitBlasting Require Import Typ TypEnv State QFBV CNF BBExport AdhereConform.\nFrom BBCache Require Import CompCache BitBlastingCCacheDef.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\n\nLtac auto_prove_neq_by_len :=\n  match goal with\n  | Hlen : is_true (QFBV.len_exp ?e1 < QFBV.len_exp ?e2)\n    |- ~ is_true (?e2 == ?e1) =>\n    let Heq := fresh in\n    move/eqP=> Heq; rewrite Heq /= ltnn in Hlen; done\n  | Hlen : is_true (QFBV.len_bexp ?e1 < QFBV.len_bexp ?e2)\n    |- ~ is_true (?e2 == ?e1) =>\n    let Heq := fresh in\n    move/eqP=> Heq; rewrite Heq /= ltnn in Hlen; done\n  end.\n\nLtac auto_prove_lt :=\n  match goal with \n  | H : is_true (?a.+1 < ?p)\n    |- is_true (?a < ?p) =>\n    by apply: (ltn_trans (ltnSn a))\n  | H : is_true ((?a + ?b).+1 < ?p)\n    |- is_true (?a < ?p) =>\n    let Haux := fresh in\n    (have Haux : a < (a + b).+1 by apply leq_addr); exact: (ltn_trans Haux H)\n  | H : is_true ((?b + ?a).+1 < ?p)\n    |- is_true (?a < ?p) =>\n    let Haux := fresh in\n    (have Haux : a < (b + a).+1 by apply leq_addl); exact: (ltn_trans Haux H)\n  | H : is_true ((?a + ?b + ?c).+1 < ?p)\n    |- is_true (?a < ?p) =>\n    let Haux := fresh in\n    (have Haux : a < (a + b + c).+1 by rewrite -addnA; exact: leq_addr); \n    exact: (ltn_trans Haux H)\n  | H : is_true ((?b + ?a + ?c).+1 < ?p)\n    |- is_true (?a < ?p) =>\n    let Haux := fresh in\n    (have Haux : a < (b + a + c).+1 by rewrite (addnC b) -addnA; exact: leq_addr); \n    exact: (ltn_trans Haux H)\n  | |- is_true (?a < ?a.+1) => exact: leqnn\n  | |- is_true (?a < (?a + _).+1) => exact: leq_addr\n  | |- is_true (?a < (_ + ?a).+1) => exact: leq_addl\n  | |- is_true (?a < (?a + _ + _).+1) => rewrite -addnA; exact: leq_addr\n  | |- is_true (?a < (?b + ?a + _).+1) => rewrite (addnC b) -addnA; exact: leq_addr\n  end.\n\nLtac auto_prove_len_lt :=\n  match goal with \n  | H : is_true (QFBV.len_exp ?e0 < QFBV.len_exp ?e)\n    |- is_true (QFBV.len_exp ?e1 < QFBV.len_exp ?e) =>\n    match e0 with\n    | context [e1] =>\n    rewrite /= in H; by auto_prove_lt\n    end\n  | H : is_true (QFBV.len_exp ?e0 < QFBV.len_exp ?e)\n    |- is_true (QFBV.len_bexp ?e1 < QFBV.len_exp ?e) =>\n    match e0 with\n    | context [e1] =>\n    rewrite /= in H; by auto_prove_lt\n    end\n  | H : is_true (QFBV.len_bexp ?e0 < QFBV.len_exp ?e)\n    |- is_true (QFBV.len_exp ?e1 < QFBV.len_exp ?e) =>\n    match e0 with\n    | context [e1] =>\n    rewrite /= in H; by auto_prove_lt\n    end\n  | H : is_true (QFBV.len_bexp ?e0 < QFBV.len_exp ?e)\n    |- is_true (QFBV.len_bexp ?e1 < QFBV.len_exp ?e) =>\n    match e0 with\n    | context [e1] =>\n    rewrite /= in H; by auto_prove_lt\n    end\n  | H : is_true (QFBV.len_exp ?e0 < QFBV.len_bexp ?e)\n    |- is_true (QFBV.len_exp ?e1 < QFBV.len_bexp ?e) =>\n    match e0 with\n    | context [e1] =>\n    rewrite /= in H; by auto_prove_lt\n    end\n  | H : is_true (QFBV.len_exp ?e0 < QFBV.len_bexp ?e)\n    |- is_true (QFBV.len_bexp ?e1 < QFBV.len_bexp ?e) =>\n    match e0 with\n    | context [e1] =>\n    rewrite /= in H; by auto_prove_lt\n    end\n  | H : is_true (QFBV.len_bexp ?e0 < QFBV.len_bexp ?e)\n    |- is_true (QFBV.len_exp ?e1 < QFBV.len_bexp ?e) =>\n    match e0 with\n    | context [e1] =>\n    rewrite /= in H; by auto_prove_lt\n    end\n  | H : is_true (QFBV.len_bexp ?e0 < QFBV.len_bexp ?e)\n    |- is_true (QFBV.len_bexp ?e1 < QFBV.len_bexp ?e) =>\n    match e0 with\n    | context [e1] =>\n    rewrite /= in H; by auto_prove_lt\n    end\n  | |- is_true (QFBV.len_exp ?e0 < QFBV.len_exp ?e) =>\n    match e with\n    | context [e0] =>\n    rewrite /=; by auto_prove_lt\n    end\n  | |- is_true (QFBV.len_bexp ?e0 < QFBV.len_bexp ?e) =>\n    match e with\n    | context [e0] =>\n    rewrite /=; by auto_prove_lt\n    end\n  | |- is_true (QFBV.len_bexp ?e0 < QFBV.len_exp ?e) =>\n    match e with\n    | context [e0] =>\n    rewrite /=; by auto_prove_lt\n    end\n  | |- is_true (QFBV.len_exp ?e0 < QFBV.len_bexp ?e) =>\n    match e with\n    | context [e0] =>\n    rewrite /=; by auto_prove_lt\n    end\n  end.\n\n\n(* = bit_blast_exp_ccache_find_cet and bit_blast_bexp_ccache_find_cet = *)\n\nLemma bit_blast_exp_ccache_find_cet :\n  forall e0 e te m c g m' c' g' cs ls,\n    QFBV.len_exp e0 < QFBV.len_exp e ->\n    bit_blast_exp_ccache te m c g e0 = (m', c', g', cs, ls) ->\n    find_cet e c' = find_cet e c\n  with\n    bit_blast_bexp_ccache_find_cet :  \n      forall e0 e te m c g m' c' g' cs l,\n        QFBV.len_bexp e0 < QFBV.len_exp e ->\n        bit_blast_bexp_ccache te m c g e0 = (m', c', g', cs, l) ->\n        find_cet e c' = find_cet e c.\nProof.  \n  (* bit_blast_exp_ccache_find_cet *)\n  set IHe := bit_blast_exp_ccache_find_cet.\n  set IHb := bit_blast_bexp_ccache_find_cet.\n  move=> e0 e te m c g m' c' g' cs ls.\n  case Hfcet: (find_cet e0 c) => [[cs0 ls0] | ]. \n  - move=> _. rewrite bit_blast_exp_ccache_equation Hfcet /=.\n    case=> _ <- _ _ _. done. \n  - move: Hfcet. case e0 => [v | bs | op e1 | op e1 e2 | b e1 e2] Hfcet Hlen.\n    + rewrite /= Hfcet. \n      case Hfhet : (find_het (QFBV.Evar v) c) => [[csh lsh] | ].\n      * case=> _ <- _ _ _; apply find_cet_add_cet_neq;\n        by auto_prove_neq_by_len.\n      * case Hfind: (SSAVM.find v m) => [rs | ]; \n          last case Hblast : (bit_blast_var te g v) => [[vg vcs] vls];\n          case=> _ <- _ _ _; rewrite find_cet_add_cet_neq; \n          (try by auto_prove_neq_by_len); by apply find_cet_add_het.\n    + rewrite /= Hfcet.\n      case Hfhet : (find_het (QFBV.Econst bs) c) => [[csh lsh] | ];\n        case=> _ <- _ _ _; rewrite find_cet_add_cet_neq; (try done);\n        (try by auto_prove_neq_by_len); by apply find_cet_add_het.\n    + rewrite /= Hfcet.\n      case Hbb1: (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1].\n      have He1e : QFBV.len_exp e1 < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c.\n      rewrite -Hc1c.\n      case Hfhet : (find_het (QFBV.Eunop op e1) c1) => [[csop lsop] | ];\n        last case Hbbop : (bit_blast_eunop op g1 ls1) => [[gop csop] lsop];\n        case=> _ <- _ _ _; rewrite find_cet_add_cet_neq; (try done);\n        (try by auto_prove_neq_by_len); by apply find_cet_add_het.\n    + rewrite /= Hfcet.\n      case Hbb1: (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1].\n      have He1e : QFBV.len_exp e1 < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c.\n      case Hbb2: (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2].\n      have He2e : QFBV.len_exp e2 < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1.\n      rewrite -Hc1c -Hc2c1.\n      case Hfhet : (find_het (QFBV.Ebinop op e1 e2) c2) => [[csop lsop] | ];\n        last case Hbbop : (bit_blast_ebinop op g2 ls1 ls2) => [[gop csop] lsop];\n        case=> _ <- _ _ _; rewrite find_cet_add_cet_neq; (try done);\n        (try by auto_prove_neq_by_len); by apply find_cet_add_het.\n    + rewrite /= Hfcet.\n      case Hbbb: (bit_blast_bexp_ccache te m c g b) => [[[[mb cb] gb] csb] lb].\n      have Hbe : QFBV.len_bexp b < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHb _ _ _ _ _ _ _ _ _ _ _ Hbe Hbbb) => Hcbc.\n      case Hbb1: (bit_blast_exp_ccache te mb cb gb e1) => [[[[m1 c1] g1] cs1] ls1].\n      have He1e : QFBV.len_exp e1 < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1cb.\n      case Hbb2: (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2].\n      have He2e : QFBV.len_exp e2 < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1.\n      rewrite -Hcbc -Hc1cb -Hc2c1.\n      case Hfhet : (find_het (QFBV.Eite b e1 e2) c2) => [[csop lsop] | ];\n        last case Hbbop : (bit_blast_ite g2 lb ls1 ls2) => [[gop csop] lsop];\n        case=> _ <- _ _ _; rewrite find_cet_add_cet_neq; (try done);\n        (try by auto_prove_neq_by_len); by apply find_cet_add_het.\n  (* bit_blast_bexp_ccache_find_cet *)\n  set IHe := bit_blast_exp_ccache_find_cet.\n  set IHb := bit_blast_bexp_ccache_find_cet.\n  move=> e0 e te m c g m' c' g' cs l.\n  case Hfcbt: (find_cbt e0 c) => [[cs0 l0] | ]. \n  - move=> _. rewrite bit_blast_bexp_ccache_equation Hfcbt /=.\n    case=> _ <- _ _ _. done. \n  - move: Hfcbt. case e0 => [ | | op e1 e2 | e1 | e1 e2 | e1 e2] Hfcbt Hlen.\n    + rewrite /= Hfcbt. \n      case Hfhet : (find_hbt QFBV.Bfalse c) => [[csh lh] | ]; case=> _ <- _ _ _; \n        rewrite find_cet_add_cbt; (try rewrite find_cet_add_hbt); done.\n    + rewrite /= Hfcbt.\n      case Hfhet : (find_hbt QFBV.Btrue c) => [[csh lh] | ]; case=> _ <- _ _ _; \n        rewrite find_cet_add_cbt; (try rewrite find_cet_add_hbt); done.\n    + rewrite /= Hfcbt.\n      case Hbb1: (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1].\n      have He1e : QFBV.len_exp e1 < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c.\n      case Hbb2: (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2].\n      have He2e : QFBV.len_exp e2 < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1.\n      rewrite -Hc1c -Hc2c1.\n      case Hfhbt : (find_hbt (QFBV.Bbinop op e1 e2) c2) => [[csop lop] | ];\n        last case Hbbop : (bit_blast_bbinop op g2 ls1 ls2) => [[gop csop] lsop];\n        case=> _ <- _ _ _; rewrite find_cet_add_cbt; \n        (try rewrite find_cet_add_hbt); done.\n    + rewrite /= Hfcbt.\n      case Hbb1: (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1].\n      have He1e : QFBV.len_bexp e1 < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHb _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c.\n      rewrite -Hc1c.\n      case Hfhbt : (find_hbt (QFBV.Blneg e1) c1) => [[csop lop] | ]; \n        case=> _ <- _ _ _; rewrite find_cet_add_cbt; \n        (try rewrite find_cet_add_hbt); done.\n    + rewrite /= Hfcbt.\n      case Hbb1: (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1].\n      have He1e : QFBV.len_bexp e1 < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHb _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c.\n      case Hbb2: (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2].\n      have He2e : QFBV.len_bexp e2 < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHb _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1.\n      rewrite -Hc1c -Hc2c1.\n      case Hfhbt : (find_hbt (QFBV.Bconj e1 e2) c2) => [[csop lop] | ]; \n        case=> _ <- _ _ _; rewrite find_cet_add_cbt; \n        (try rewrite find_cet_add_hbt); done.\n    + rewrite /= Hfcbt.\n      case Hbb1: (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1].\n      have He1e : QFBV.len_bexp e1 < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHb _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c.\n      case Hbb2: (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2].\n      have He2e : QFBV.len_bexp e2 < QFBV.len_exp e by auto_prove_len_lt.\n      move: (IHb _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1.\n      rewrite -Hc1c -Hc2c1.\n      case Hfhbt : (find_hbt (QFBV.Bdisj e1 e2) c2) => [[csop lop] | ]; \n        case=> _ <- _ _ _; rewrite find_cet_add_cbt; \n        (try rewrite find_cet_add_hbt); done.\nQed.\n\n\n(* = bit_blast_exp_ccache_find_cbt and bit_blast_bexp_ccache_find_cbt = *)\n\nLemma bit_blast_exp_ccache_find_cbt :\n  forall e0 e te m c g m' c' g' cs ls,\n    QFBV.len_exp e0 < QFBV.len_bexp e ->\n    bit_blast_exp_ccache te m c g e0 = (m', c', g', cs, ls) ->\n    find_cbt e c' = find_cbt e c\n  with\n    bit_blast_bexp_ccache_find_cbt :  \n      forall e0 e te m c g m' c' g' cs l,\n        QFBV.len_bexp e0 < QFBV.len_bexp e ->\n        bit_blast_bexp_ccache te m c g e0 = (m', c', g', cs, l) ->\n        find_cbt e c' = find_cbt e c.\nProof.  \n  (* bit_blast_exp_ccache_find_cbt *)\n  set IHe := bit_blast_exp_ccache_find_cbt.\n  set IHb := bit_blast_bexp_ccache_find_cbt.\n  move=> e0 e te m c g m' c' g' cs ls.\n  case Hfcet: (find_cet e0 c) => [[cs0 ls0] | ]. \n  - move=> _. rewrite bit_blast_exp_ccache_equation Hfcet /=.\n    case=> _ <- _ _ _. done. \n  - move: Hfcet. case e0 => [v | bs | op e1 | op e1 e2 | b e1 e2] Hfcet Hlen.\n    + rewrite /= Hfcet. \n      case Hfhet : (find_het (QFBV.Evar v) c) => [[csh lsh] | ].\n      * case=> _ <- _ _ _; apply find_cbt_add_cet.\n      * case Hfind: (SSAVM.find v m) => [rs | ]; \n          last case Hblast : (bit_blast_var te g v) => [[vg vcs] vls];\n          case=> _ <- _ _ _; rewrite find_cbt_add_cet; by apply find_cbt_add_het.\n    + rewrite /= Hfcet.\n      case Hfhet : (find_het (QFBV.Econst bs) c) => [[csh lsh] | ];\n        case=> _ <- _ _ _; rewrite find_cbt_add_cet; (try done);\n        by apply find_cbt_add_het.\n    + rewrite /= Hfcet.\n      case Hbb1: (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1].\n      have He1e : QFBV.len_exp e1 < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c.\n      rewrite -Hc1c.\n      case Hfhet : (find_het (QFBV.Eunop op e1) c1) => [[csop lsop] | ];\n        last case Hbbop : (bit_blast_eunop op g1 ls1) => [[gop csop] lsop];\n        case=> _ <- _ _ _; rewrite find_cbt_add_cet; (try done);\n        by apply find_cbt_add_het.\n    + rewrite /= Hfcet.\n      case Hbb1: (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1].\n      have He1e : QFBV.len_exp e1 < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c.\n      case Hbb2: (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2].\n      have He2e : QFBV.len_exp e2 < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1.\n      rewrite -Hc1c -Hc2c1.\n      case Hfhet : (find_het (QFBV.Ebinop op e1 e2) c2) => [[csop lsop] | ];\n        last case Hbbop : (bit_blast_ebinop op g2 ls1 ls2) => [[gop csop] lsop];\n        case=> _ <- _ _ _; rewrite find_cbt_add_cet; (try done);\n        by apply find_cbt_add_het.\n    + rewrite /= Hfcet.\n      case Hbbb: (bit_blast_bexp_ccache te m c g b) => [[[[mb cb] gb] csb] lb].\n      have Hbe : QFBV.len_bexp b < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHb _ _ _ _ _ _ _ _ _ _ _ Hbe Hbbb) => Hcbc.\n      case Hbb1: (bit_blast_exp_ccache te mb cb gb e1) => [[[[m1 c1] g1] cs1] ls1].\n      have He1e : QFBV.len_exp e1 < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1cb.\n      case Hbb2: (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2].\n      have He2e : QFBV.len_exp e2 < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1.\n      rewrite -Hcbc -Hc1cb -Hc2c1.\n      case Hfhet : (find_het (QFBV.Eite b e1 e2) c2) => [[csop lsop] | ];\n        last case Hbbop : (bit_blast_ite g2 lb ls1 ls2) => [[gop csop] lsop];\n        case=> _ <- _ _ _; rewrite find_cbt_add_cet; (try done);\n        by apply find_cbt_add_het.\n  (* bit_blast_bexp_ccache_find_cbt *)\n  set IHe := bit_blast_exp_ccache_find_cbt.\n  set IHb := bit_blast_bexp_ccache_find_cbt.\n  move=> e0 e te m c g m' c' g' cs l.\n  case Hfcbt: (find_cbt e0 c) => [[cs0 l0] | ]. \n  - move=> _. rewrite bit_blast_bexp_ccache_equation Hfcbt /=.\n    case=> _ <- _ _ _. done. \n  - move: Hfcbt. case e0 => [ | | op e1 e2 | e1 | e1 e2 | e1 e2] Hfcbt Hlen.\n    + rewrite /= Hfcbt. \n      case Hfhet : (find_hbt QFBV.Bfalse c) => [[csh lh] | ]; case=> _ <- _ _ _; \n        rewrite find_cbt_add_cbt_neq; (try auto_prove_neq_by_len);\n        (try rewrite find_cbt_add_hbt); done.\n    + rewrite /= Hfcbt.\n      case Hfhet : (find_hbt QFBV.Btrue c) => [[csh lh] | ]; case=> _ <- _ _ _; \n        rewrite find_cbt_add_cbt_neq; (try auto_prove_neq_by_len);\n        (try rewrite find_cbt_add_hbt); done.\n    + rewrite /= Hfcbt.\n      case Hbb1: (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1].\n      have He1e : QFBV.len_exp e1 < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c.\n      case Hbb2: (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2].\n      have He2e : QFBV.len_exp e2 < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHe _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1.\n      rewrite -Hc1c -Hc2c1.\n      case Hfhbt : (find_hbt (QFBV.Bbinop op e1 e2) c2) => [[csop lop] | ];\n        last case Hbbop : (bit_blast_bbinop op g2 ls1 ls2) => [[gop csop] lsop];\n        case=> _ <- _ _ _; rewrite find_cbt_add_cbt_neq; \n        (try auto_prove_neq_by_len); (try rewrite find_cbt_add_hbt); done.\n    + rewrite /= Hfcbt.\n      case Hbb1: (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1].\n      have He1e : QFBV.len_bexp e1 < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHb _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c.\n      rewrite -Hc1c.\n      case Hfhbt : (find_hbt (QFBV.Blneg e1) c1) => [[csop lop] | ]; \n        case=> _ <- _ _ _; rewrite find_cbt_add_cbt_neq; \n        (try auto_prove_neq_by_len); (try rewrite find_cbt_add_hbt); done.\n    + rewrite /= Hfcbt.\n      case Hbb1: (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1].\n      have He1e : QFBV.len_bexp e1 < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHb _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c.\n      case Hbb2: (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2].\n      have He2e : QFBV.len_bexp e2 < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHb _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1.\n      rewrite -Hc1c -Hc2c1.\n      case Hfhbt : (find_hbt (QFBV.Bconj e1 e2) c2) => [[csop lop] | ]; \n        case=> _ <- _ _ _; rewrite find_cbt_add_cbt_neq; \n        (try auto_prove_neq_by_len); (try rewrite find_cet_add_hbt); done.\n    + rewrite /= Hfcbt.\n      case Hbb1: (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1].\n      have He1e : QFBV.len_bexp e1 < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHb _ _ _ _ _ _ _ _ _ _ _ He1e Hbb1) => Hc1c.\n      case Hbb2: (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2].\n      have He2e : QFBV.len_bexp e2 < QFBV.len_bexp e by auto_prove_len_lt.\n      move: (IHb _ _ _ _ _ _ _ _ _ _ _ He2e Hbb2) => Hc2c1.\n      rewrite -Hc1c -Hc2c1.\n      case Hfhbt : (find_hbt (QFBV.Bdisj e1 e2) c2) => [[csop lop] | ]; \n        case=> _ <- _ _ _; rewrite find_cbt_add_cbt_neq; \n        (try auto_prove_neq_by_len); (try rewrite find_cbt_add_hbt); done.\nQed.\n\n\n(* = bit_blast_exp_ccache_in_cet and bit_blast_bexp_ccache_in_cbt = *)\n\nLemma bit_blast_exp_ccache_in_cet :\n  forall e te m c g m' c' g' cs ls,\n    bit_blast_exp_ccache te m c g e = (m', c', g', cs, ls) ->\n    exists cse, find_cet e c' = Some (cse, ls)\n  with\n    bit_blast_bexp_ccache_in_cbt :  \n      forall e te m c g m' c' g' cs l,\n        bit_blast_bexp_ccache te m c g e = (m', c', g', cs, l) ->\n        exists cse, find_cbt e c' = Some (cse, l).\nProof.\n  (* exp *)\n  move=> e te m c g m' c' g' cs ls.\n  case Hfcet: (find_cet e c) => [[cse lse] | ]. \n  - rewrite bit_blast_exp_ccache_equation Hfcet /=.\n    case=> _ <- _ _ <-. exists cse; done. \n  - move: Hfcet. case: e.\n    + move=> v Hfcet. rewrite /= Hfcet.\n      case Hfhet : (find_het (QFBV.Evar v) c) => [[cse lse] | ];\n        last case Hfv : (SSAVM.find v m);\n        last case Hv : (bit_blast_var te g v) => [[gv csv] lsv];\n        case=> _ <- _ _ <-; [ exists cse | exists [::] | exists csv]; \n        exact: find_cet_add_cet_eq.\n    + move=> bs Hfcet. rewrite /= Hfcet.\n      case Hfhet : (find_het (QFBV.Econst bs) c) => [[cse lse] | ];\n        case=> _ <- _ _ <-; [ exists cse | exists [::]]; exact: find_cet_add_cet_eq.\n    + move=> op e1 Hfcet. rewrite /= Hfcet.\n      case He1 : (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1].\n      case Hfhet : (find_het (QFBV.Eunop op e1) c1) => [[csop lsop] | ];\n        last case Hop : (bit_blast_eunop op g1 ls1) => [[gop csop] lsop];\n        case=> _ <- _ _ <-; exists csop; exact: find_cet_add_cet_eq.\n    + move=> op e1 e2 Hfcet. rewrite /= Hfcet.\n      case He1 : (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1].\n      case He2 : (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2].  \n      case Hfhet : (find_het (QFBV.Ebinop op e1 e2) c2) => [[csop lsop] | ];\n        last case Hop : (bit_blast_ebinop op g2 ls1 ls2) => [[gop csop] lsop];\n        case=> _ <- _ _ <-; exists csop; exact: find_cet_add_cet_eq.\n    + move=> b e1 e2 Hfcet. rewrite /= Hfcet.\n      case Hb : (bit_blast_bexp_ccache te m c g b) => [[[[mb cb] gb] csb] lb].\n      case He1 : (bit_blast_exp_ccache te mb cb gb e1) => [[[[m1 c1] g1] cs1] ls1].\n      case He2 : (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2].  \n      case Hfhet : (find_het (QFBV.Eite b e1 e2) c2) => [[csop lsop] | ];\n        last case Hop : (bit_blast_ite g2 lb ls1 ls2) => [[gop csop] lsop];\n        case=> _ <- _ _ <-; exists csop; exact: find_cet_add_cet_eq.\n  (* bexp *)\n  move=> e te m c g m' c' g' cs l.\n  case Hfcbt: (find_cbt e c) => [[cse le] | ]. \n  - rewrite bit_blast_bexp_ccache_equation Hfcbt /=.\n    case=> _ <- _ _ <-. exists cse; done. \n  - move: Hfcbt. case: e.\n    + move=> Hfcbt. rewrite /= Hfcbt.\n      case Hfhbt : (find_hbt (QFBV.Bfalse) c) => [[cse le] | ];\n        case=> _ <- _ _ <-; [ exists cse | exists [::]]; exact: find_cbt_add_cbt_eq.\n    + move=> Hfcbt. rewrite /= Hfcbt.\n      case Hfhbt : (find_hbt (QFBV.Btrue) c) => [[cse le] | ];\n        case=> _ <- _ _ <-; [ exists cse | exists [::]]; exact: find_cbt_add_cbt_eq.\n    + move=> op e1 e2 Hfcbt. rewrite /= Hfcbt.\n      case He1 : (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1].\n      case He2 : (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2].  \n      case Hfhet : (find_hbt (QFBV.Bbinop op e1 e2) c2) => [[csop lop] | ];\n        last case Hop : (bit_blast_bbinop op g2 ls1 ls2) => [[gop csop] lop];\n        case=> _ <- _ _ <-; exists csop; exact: find_cbt_add_cbt_eq.\n    + move=> e1 Hfcbt. rewrite /bit_blast_bexp_ccache -/bit_blast_bexp_ccache Hfcbt.\n      case He1 : (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1].\n      case Hfhbt : (find_hbt (QFBV.Blneg e1) c1) => [[csop lop] | ];\n        last case Hop : (bit_blast_lneg g1 l1) => [[gop csop] lop];\n        case=> _ <- _ _ <-; exists csop; exact: find_cbt_add_cbt_eq.\n    + move=> e1 e2 Hfcbt. \n      rewrite /bit_blast_bexp_ccache -/bit_blast_bexp_ccache Hfcbt.\n      case He1 : (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1].\n      case He2 : (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2].\n      case Hfhbt : (find_hbt (QFBV.Bconj e1 e2) c2) => [[csop lop] | ];\n        last case Hop : (bit_blast_conj g2 l1 l2) => [[gop csop] lop];\n        case=> _ <- _ _ <-; exists csop; exact: find_cbt_add_cbt_eq.\n    + move=> e1 e2 Hfcbt. \n      rewrite /bit_blast_bexp_ccache -/bit_blast_bexp_ccache Hfcbt.\n      case He1 : (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1].\n      case He2 : (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2].\n      case Hfhbt : (find_hbt (QFBV.Bdisj e1 e2) c2) => [[csop lop] | ];\n        last case Hop : (bit_blast_disj g2 l1 l2) => [[gop csop] lop];\n        case=> _ <- _ _ <-; exists csop; exact: find_cbt_add_cbt_eq.\nQed.\n\n\n(* = bit_blast_exp_ccache_in_het and bit_blast_bexp_ccache_in_hbt = *)\n\nLemma bit_blast_exp_ccache_in_het :\n  forall e te m c g m' c' g' cs ls,\n    bit_blast_exp_ccache te m c g e = (m', c', g', cs, ls) ->\n    CompCache.well_formed c ->\n    exists cse, find_het e c' = Some (cse, ls)\n  with\n    bit_blast_bexp_ccache_in_hbt :  \n      forall e te m c g m' c' g' cs l,\n        bit_blast_bexp_ccache te m c g e = (m', c', g', cs, l) ->\n        CompCache.well_formed c ->\n        exists cse, find_hbt e c' = Some (cse, l).\nProof.\n  (* exp *)\n  move=> e te m c g m' c' g' cs ls Hbb Hwfc. move: Hbb.\n  case Hfcet: (find_cet e c) => [[cse lse] | ]. \n  - rewrite bit_blast_exp_ccache_equation Hfcet /=.\n    case=> _ <- _ _ <-. exists cse; exact: (well_formed_find_cet Hwfc Hfcet). \n  - move: Hfcet. case: e.\n    + move=> v Hfcet. rewrite /= Hfcet.\n      case Hfhet : (find_het (QFBV.Evar v) c) => [[cse lse] | ];\n        last case Hfv : (SSAVM.find v m);\n        last case Hv : (bit_blast_var te g v) => [[gv csv] lsv];\n        case=> _ <- _ _ <-; [ exists cse | exists [::] | exists csv]; \n        rewrite find_het_add_cet; try rewrite find_het_add_het_eq; done.\n    + move=> bs Hfcet. rewrite /= Hfcet.\n      case Hfhet : (find_het (QFBV.Econst bs) c) => [[csop lsop] | ];\n        case=> _ <- _ _ <-; [ exists csop | exists [::]]; \n        rewrite find_het_add_cet; try rewrite find_het_add_het_eq; done.\n    + move=> op e1 Hfcet. rewrite /= Hfcet.\n      case He1 : (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1].\n      case Hfhet : (find_het (QFBV.Eunop op e1) c1) => [[csop lsop] | ];\n        last case Hop : (bit_blast_eunop op g1 ls1) => [[gop csop] lsop];\n        case=> _ <- _ _ <-; exists csop; \n        rewrite find_het_add_cet; try rewrite find_het_add_het_eq; done.\n    + move=> op e1 e2 Hfcet. rewrite /= Hfcet.\n      case He1 : (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1].\n      case He2 : (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2].  \n      case Hfhet : (find_het (QFBV.Ebinop op e1 e2) c2) => [[csop lsop] | ];\n        last case Hop : (bit_blast_ebinop op g2 ls1 ls2) => [[gop csop] lsop];\n        case=> _ <- _ _ <-; exists csop; \n        rewrite find_het_add_cet; try rewrite find_het_add_het_eq; done.\n    + move=> b e1 e2 Hfcet. rewrite /= Hfcet.\n      case Hb : (bit_blast_bexp_ccache te m c g b) => [[[[mb cb] gb] csb] lb].\n      case He1 : (bit_blast_exp_ccache te mb cb gb e1) => [[[[m1 c1] g1] cs1] ls1].\n      case He2 : (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2].  \n      case Hfhet : (find_het (QFBV.Eite b e1 e2) c2) => [[csop lsop] | ];\n        last case Hop : (bit_blast_ite g2 lb ls1 ls2) => [[gop csop] lsop];\n        case=> _ <- _ _ <-; exists csop; \n        rewrite find_het_add_cet; try rewrite find_het_add_het_eq; done.\n  (* bexp *)\n  move=> e te m c g m' c' g' cs l Hbb Hwfc. move: Hbb.\n  case Hfcbt: (find_cbt e c) => [[cse le] | ]. \n  - rewrite bit_blast_bexp_ccache_equation Hfcbt /=.\n    case=> _ <- _ _ <-. exists cse; exact: (well_formed_find_cbt Hwfc Hfcbt). \n  - move: Hfcbt. case: e.\n    + move=> Hfcbt. rewrite /= Hfcbt.\n      case Hfhbt : (find_hbt (QFBV.Bfalse) c) => [[csop lop] | ];\n        case=> _ <- _ _ <-; [ exists csop | exists [::]]; \n        rewrite find_hbt_add_cbt; try rewrite find_hbt_add_hbt_eq; done.\n    + move=> Hfcbt. rewrite /= Hfcbt.\n      case Hfhbt : (find_hbt (QFBV.Btrue) c) => [[csop lop] | ];\n        case=> _ <- _ _ <-; [ exists csop | exists [::]]; \n        rewrite find_hbt_add_cbt; try rewrite find_hbt_add_hbt_eq; done.\n    + move=> op e1 e2 Hfcbt. rewrite /= Hfcbt.\n      case He1 : (bit_blast_exp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] ls1].\n      case He2 : (bit_blast_exp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] ls2].  \n      case Hfhbt : (find_hbt (QFBV.Bbinop op e1 e2) c2) => [[csop lop] | ];\n        last case Hop : (bit_blast_bbinop op g2 ls1 ls2) => [[gop csop] lop];\n        case=> _ <- _ _ <-; exists csop; \n        rewrite find_hbt_add_cbt; try rewrite find_hbt_add_hbt_eq; done.\n    + move=> e1 Hfcbt. \n      rewrite /bit_blast_bexp_ccache -/bit_blast_bexp_ccache Hfcbt.\n      case He1 : (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1].\n      case Hfhbt : (find_hbt (QFBV.Blneg e1) c1) => [[csop lop] | ];\n        last case Hop : (bit_blast_lneg g1 l1) => [[gop csop] lop];\n        case=> _ <- _ _ <-; exists csop; \n        rewrite find_hbt_add_cbt; try rewrite find_hbt_add_hbt_eq; done.\n    + move=> e1 e2 Hfcbt. \n      rewrite /bit_blast_bexp_ccache -/bit_blast_bexp_ccache Hfcbt.\n      case He1 : (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1].\n      case He2 : (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2].\n      case Hfhbt : (find_hbt (QFBV.Bconj e1 e2) c2) => [[csop lop] | ];\n        last case Hop : (bit_blast_conj g2 l1 l2) => [[gop csop] lop];\n        case=> _ <- _ _ <-; exists csop; \n        rewrite find_hbt_add_cbt; try rewrite find_hbt_add_hbt_eq; done.\n    + move=> e1 e2 Hfcbt. \n      rewrite /bit_blast_bexp_ccache -/bit_blast_bexp_ccache Hfcbt.\n      case He1 : (bit_blast_bexp_ccache te m c g e1) => [[[[m1 c1] g1] cs1] l1].\n      case He2 : (bit_blast_bexp_ccache te m1 c1 g1 e2) => [[[[m2 c2] g2] cs2] l2].\n      case Hfhbt : (find_hbt (QFBV.Bdisj e1 e2) c2) => [[csop lop] | ];\n        last case Hop : (bit_blast_disj g2 l1 l2) => [[gop csop] lop];\n        case=> _ <- _ _ <-; exists csop; \n        rewrite find_hbt_add_cbt; try rewrite find_hbt_add_hbt_eq; done.\nQed.\n", "meta": {"author": "fmlab-iis", "repo": "coq-qfbv", "sha": "0e9521febd1564747723a773d25e54781e81b762", "save_path": "github-repos/coq/fmlab-iis-coq-qfbv", "path": "github-repos/coq/fmlab-iis-coq-qfbv/coq-qfbv-0e9521febd1564747723a773d25e54781e81b762/src/bbcache/BitBlastingCCacheFind.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.20545835599827528}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\nRequire Export Coq.Strings.String.\nRequire Import Coq.Classes.RelationClasses.\n\nFrom Fairness Require Export ITreeLib FairBeh Mod.\nFrom Fairness Require Import pind.\nFrom Fairness Require Import PCMLarge.\nFrom Fairness Require Import PindTac.\n\nSet Implicit Arguments.\n\n\n\nSection PRIMIVIESIM.\n  Context `{M: URA.t}.\n\n  Variable state_src: Type.\n  Variable state_tgt: Type.\n\n  Variable ident_src: ID.\n  Variable _ident_tgt: ID.\n  Definition ident_tgt := sum_tid _ident_tgt.\n\n  Variable wf_src: WF.\n  Variable wf_tgt: WF.\n\n  Let srcE := programE ident_src state_src.\n  Let tgtE := programE _ident_tgt state_tgt.\n\n  Definition shared :=\n    (TIdSet.t *\n       (@imap ident_src wf_src) *\n       (@imap ident_tgt wf_tgt) *\n       state_src *\n       state_tgt)%type.\n\n  Let shared_rel: Type := shared -> Prop.\n\n  Variable I: shared -> URA.car -> Prop.\n\n  Variant __lsim\n          (tid: thread_id)\n          (lsim: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          (_lsim: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel),bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n  | lsim_ret\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      r_src r_tgt\n      (LSIM: RR r_src r_tgt r_ctx (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (Ret r_src) (Ret r_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_tauL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (Tau itr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_chooseL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X ktr_src itr_tgt\n      (LSIM: exists x, _lsim _ _ RR true f_tgt r_ctx (ktr_src x) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Choose X) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_rmwL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X rmw ktr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src (snd (rmw st_src) : X)) itr_tgt (ths, im_src, im_tgt, fst (rmw st_src), st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Rmw rmw) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_tidL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src tid) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (GetTid) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_UB\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Undefined) >>= ktr_src) itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_fairL\n      f_src f_tgt r_ctx\n      ths im_src0 im_tgt st_src st_tgt\n      f ktr_src itr_tgt\n      (LSIM: exists im_src1,\n          (<<FAIR: fair_update im_src0 im_src1 f>>) /\\\n            (<<LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src tt) itr_tgt (ths, im_src1, im_tgt, st_src, st_tgt)>>))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Fair f) >>= ktr_src) itr_tgt (ths, im_src0, im_tgt, st_src, st_tgt)\n\n  | lsim_tauR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: _lsim _ _ RR f_src true r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (Tau itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_chooseR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X itr_src ktr_tgt\n      (LSIM: forall x, _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt x) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (Choose X) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_rmwR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      X rmw itr_src ktr_tgt\n      (LSIM: _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt (snd (rmw st_tgt) : X)) (ths, im_src, im_tgt, st_src, fst (rmw st_tgt)))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (Rmw rmw) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_tidR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src ktr_tgt\n      (LSIM: _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt tid) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (GetTid) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_fairR\n      f_src f_tgt r_ctx\n      ths im_src im_tgt0 st_src st_tgt\n      f itr_src ktr_tgt\n      (LSIM: forall im_tgt1\n                   (FAIR: fair_update im_tgt0 im_tgt1 (prism_fmap inrp f)),\n          (<<LSIM: _lsim _ _ RR f_src true r_ctx itr_src (ktr_tgt tt) (ths, im_src, im_tgt1, st_src, st_tgt)>>))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx itr_src (trigger (Fair f) >>= ktr_tgt) (ths, im_src, im_tgt0, st_src, st_tgt)\n\n  | lsim_observe\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src ktr_tgt\n      (LSIM: forall ret,\n          lsim _ _ RR true true r_ctx (ktr_src ret) (ktr_tgt ret) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Observe fn args) >>= ktr_src) (trigger (Observe fn args) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_call\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      fn args ktr_src ktr_tgt\n      (LSIM : forall ret, lsim _ _ RR true true r_ctx (ktr_src ret) (ktr_tgt ret) (ths, im_src, im_tgt, st_src, st_tgt))\n    : __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Call fn args) >>= ktr_src) (trigger (Call fn args) >>= ktr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n\n  | lsim_yieldL\n      f_src f_tgt r_ctx\n      ths im_src im_tgt st_src st_tgt\n      ktr_src itr_tgt\n      (LSIM: _lsim _ _ RR true f_tgt r_ctx (ktr_src tt) (trigger (Yield) >>= itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= itr_tgt) (ths, im_src, im_tgt, st_src, st_tgt)\n  | lsim_yieldR\n      f_src f_tgt r_ctx0\n      ths0 im_src0 im_tgt0 st_src0 st_tgt0\n      r_own r_shared\n      ktr_src ktr_tgt\n      (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared)\n      (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx0))\n      (LSIM: forall ths1 im_src1 im_tgt1 st_src1 st_tgt1 r_shared1 r_ctx1\n                    (INV: I (ths1, im_src1, im_tgt1, st_src1, st_tgt1) r_shared1)\n                    (VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx1))\n                    im_tgt2\n                    (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths1))),\n          _lsim _ _ RR f_src true r_ctx1 (trigger (Yield) >>= ktr_src) (ktr_tgt tt) (ths1, im_src1, im_tgt2, st_src1, st_tgt1))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx0 (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n  | lsim_sync\n      f_src f_tgt r_ctx0\n      ths0 im_src0 im_tgt0 st_src0 st_tgt0\n      r_own r_shared\n      ktr_src ktr_tgt\n      (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared)\n      (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx0))\n      (LSIM: forall ths1 im_src1 im_tgt1 st_src1 st_tgt1 r_shared1 r_ctx1\n               (INV: I (ths1, im_src1, im_tgt1, st_src1, st_tgt1) r_shared1)\n               (VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx1))\n               im_tgt2\n               (TGT: fair_update im_tgt1 im_tgt2 (prism_fmap inlp (tids_fmap tid ths1))),\n          (<<LSIM: lsim _ _ RR true true r_ctx1 (ktr_src tt) (ktr_tgt tt) (ths1, im_src1, im_tgt2, st_src1, st_tgt1)>>))\n    :\n    __lsim tid lsim _lsim RR f_src f_tgt r_ctx0 (trigger (Yield) >>= ktr_src) (trigger (Yield) >>= ktr_tgt) (ths0, im_src0, im_tgt0, st_src0, st_tgt0)\n\n  | lsim_progress\n      r_ctx\n      ths im_src im_tgt st_src st_tgt\n      itr_src itr_tgt\n      (LSIM: lsim _ _ RR false false r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    __lsim tid lsim _lsim RR true true r_ctx itr_src itr_tgt (ths, im_src, im_tgt, st_src, st_tgt)\n  .\n\n  Definition lsim (tid: thread_id)\n             R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel):\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n    paco9 (fun r => pind9 (__lsim tid r) top9) bot9 R_src R_tgt RR.\n\n  Lemma __lsim_mon tid:\n    forall r r' (LE: r <9= r'), (__lsim tid r) <10= (__lsim tid r').\n  Proof.\n    ii. inv PR; try (econs; eauto; fail).\n    eapply lsim_sync; eauto. i. hexploit LSIM. eapply INV0. eapply VALID0. all: eauto.\n  Qed.\n\n  Lemma _lsim_mon tid: forall r, monotone9 (__lsim tid r).\n  Proof.\n    ii. inv IN; try (econs; eauto; fail).\n    { des. econs; eauto. }\n    { des. econs; eauto. }\n    { econs. i. eapply LE. eapply LSIM. eauto. }\n  Qed.\n\n  Lemma lsim_mon tid: forall q, monotone9 (fun r => pind9 (__lsim tid r) q).\n  Proof.\n    ii. eapply pind9_mon_gen; eauto.\n    ii. eapply __lsim_mon; eauto.\n  Qed.\n  Hint Resolve lsim_mon: paco.\n  Hint Resolve cpn9_wcompat: paco.\n\n  From Paco Require Import pacotac_internal.\n\n  Lemma lsim_acc_gen\n        tid r\n        (A: Type)\n        (f0: forall (a: A), Type)\n        (f1: forall (a: A), Type)\n        (f2: forall (a: A), f0 a -> f1 a -> URA.car -> shared_rel)\n        (f3: forall (a: A), bool)\n        (f4: forall (a: A), bool)\n        (f5: forall (a: A), URA.car)\n        (f6: forall (a: A), itree srcE (f0 a))\n        (f7: forall (a: A), itree tgtE (f1 a))\n        (f8: forall (a: A), shared)\n        r0 (q: A -> Prop)\n        (IND: forall r1\n                     (LE: r1 <9= r0)\n                     (IH: forall a, @r1 (f0 a) (f1 a) (f2 a) (f3 a) (f4 a) (f5 a) (f6 a) (f7 a) (f8 a) -> q a),\n          forall a, pind9 (__lsim tid r) r1 (f0 a) (f1 a) (f2 a) (f3 a) (f4 a) (f5 a) (f6 a) (f7 a) (f8 a) -> q a)\n    :\n    forall a, pind9 (__lsim tid r) r0 (f0 a) (f1 a) (f2 a) (f3 a) (f4 a) (f5 a) (f6 a) (f7 a) (f8 a) -> q a.\n  Proof.\n    cut ((pind9 (__lsim tid r) r0) <9= curry9 (fun x => forall a (EQ: @exist9T _ _ _ _ _ _ _ _ _ (f0 a) (f1 a) (f2 a) (f3 a) (f4 a) (f5 a) (f6 a) (f7 a) (f8 a) = x), q a)).\n    { exact (fun P a H => uncurry_adjoint2_9 P (@exist9T _ _ _ _ _ _ _ _ _ (f0 a) (f1 a) (f2 a) (f3 a) (f4 a) (f5 a) (f6 a) (f7 a) (f8 a)) H a eq_refl). }\n    { exact (@pind9_acc _ _ _ _ _ _ _ _ _ (__lsim tid r) (curry9 (fun x => forall a (EQ: @exist9T _ _ _ _ _ _ _ _ _ (f0 a) (f1 a) (f2 a) (f3 a) (f4 a) (f5 a) (f6 a) (f7 a) (f8 a) = x), q a)) r0 (fun rr LE IH => @uncurry_adjoint1_9 _ _ _ _ _ _ _ _ _ (pind9 (__lsim tid r) rr) (fun x => forall a (EQ: @exist9T _ _ _ _ _ _ _ _ _ (f0 a) (f1 a) (f2 a) (f3 a) (f4 a) (f5 a) (f6 a) (f7 a) (f8 a) = x), q a) (fun x PR a EQ => IND rr LE (fun a H => IH (f0 a) (f1 a) (f2 a) (f3 a) (f4 a) (f5 a) (f6 a) (f7 a) (f8 a) H a eq_refl) a (@eq_rect _ _ (uncurry9 (pind9 (__lsim tid r) rr)) PR _ (eq_sym EQ))))).\n    }\n  Qed.\n\n  Ltac pind_gen := patterning 9; refine (@lsim_acc_gen\n                                           _ _ _\n                                           _ _ _ _ _ _ _ _ _\n                                           _ _ _).\n  Ltac pinduction n := currying n pind_gen.\n\n  (* TODO: add this in pico lib *)\n  Lemma lsim_indC_spec tid\n    :\n    (fun r => __lsim tid r r) <10= gupaco9 (fun r => pind9 (__lsim tid r) top9) (cpn9 (fun r => pind9 (__lsim tid r) top9)).\n  Proof.\n    eapply wrespect9_uclo; eauto with paco.\n    econs.\n    { ii. eapply __lsim_mon; eauto. eapply _lsim_mon; eauto. }\n    i. eapply pind9_fold.\n    eapply __lsim_mon.\n    { instantiate (1:=l). i. eapply rclo9_base. eauto. }\n    eapply _lsim_mon; eauto. i. split; ss.\n    eapply GF in PR0. eapply pind9_mon_gen; eauto.\n    i. eapply __lsim_mon.\n    { i. eapply rclo9_base. eassumption. }\n    eauto.\n  Qed.\n\n  Variant lsim_resetC\n          (r: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n    | lsim_resetC_intro\n        src tgt shr r_ctx\n        ps0 pt0 ps1 pt1\n        (REL: r _ _ RR ps1 pt1 r_ctx src tgt shr)\n        (SRC: ps1 = true -> ps0 = true)\n        (TGT: pt1 = true -> pt0 = true)\n      :\n      lsim_resetC r RR ps0 pt0 r_ctx src tgt shr\n  .\n\n  Lemma lsim_resetC_spec tid\n    :\n    lsim_resetC <10= gupaco9 (fun r => pind9 (__lsim tid r) top9) (cpn9 (fun r => pind9 (__lsim tid r) top9)).\n  Proof.\n    eapply wrespect9_uclo; eauto with paco.\n    econs.\n    { ii. inv IN. econs; eauto. }\n    i. inv PR. eapply GF in REL.\n\n    revert x0 x1 x2 ps1 pt1 x5 x6 x7 x8 REL x3 x4 SRC TGT.\n    pinduction 9. i.\n    eapply pind9_unfold in PR.\n    2:{ eapply _lsim_mon. }\n    rename PR into LSIM. inv LSIM.\n\n    { eapply pind9_fold. econs; eauto. }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind9_fold. eapply lsim_tauL. split; ss.\n      hexploit IH; eauto.\n    }\n\n    { des. eapply pind9_fold. eapply lsim_chooseL. esplits; eauto. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_rmwL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_tidL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_UB. }\n\n    { des. eapply pind9_fold. eapply lsim_fairL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind9_fold. eapply lsim_tauR. split; ss.\n      hexploit IH. eauto. all: eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_chooseR. i. split; ss. specialize (LSIM0 x).\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_rmwR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_tidR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_fairR. i. split; ss. specialize (LSIM0 _ FAIR).\n      des. destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_observe. i. eapply rclo9_base. auto. }\n\n    { eapply pind9_fold. eapply lsim_call. i. eapply rclo9_base. auto. }\n\n    { des. eapply pind9_fold. eapply lsim_yieldL. split; ss.\n      destruct LSIM0 as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_yieldR; eauto. i.\n      hexploit LSIM0; eauto. clear LSIM0. intros LSIM0.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. split; ss; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_sync; eauto. i.\n      hexploit LSIM0. eapply INV0. eapply VALID0. all: eauto. i; des. esplits; eauto.\n      eapply rclo9_base. auto.\n    }\n\n    { pclearbot. hexploit SRC; ss; i. hexploit TGT; ss; i. clarify.\n      eapply pind9_fold. eapply lsim_progress. eapply rclo9_base. auto. }\n  Qed.\n\n  Lemma lsim_reset_prog\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        src tgt shr\n        ps0 pt0 ps1 pt1 r_ctx\n        (LSIM: lsim tid RR ps1 pt1 r_ctx src tgt shr)\n        (SRC: ps1 = true -> ps0 = true)\n        (TGT: pt1 = true -> pt0 = true)\n    :\n    lsim tid RR ps0 pt0 r_ctx src tgt shr.\n  Proof.\n    ginit. guclo lsim_resetC_spec.\n    econs; eauto. gfinal.\n    right. auto.\n  Qed.\n\n  Variant lsim_monoC\n          (r: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src R_tgt (RR1: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n    | lsim_monoC_intro\n        (RR0: R_src -> R_tgt -> URA.car -> shared_rel)\n        src tgt shr r_ctx ps pt\n        (MON: forall r_src r_tgt r_ctx shr (RET: RR0 r_src r_tgt r_ctx shr),\n            RR1 r_src r_tgt r_ctx shr)\n        (REL: r _ _ RR0 ps pt r_ctx src tgt shr)\n      :\n      lsim_monoC r RR1 ps pt r_ctx src tgt shr\n  .\n\n  Lemma lsim_monoC_spec tid\n    :\n    lsim_monoC <10= gupaco9 (fun r => pind9 (__lsim tid r) top9) (cpn9 (fun r => pind9 (__lsim tid r) top9)).\n  Proof.\n    eapply wrespect9_uclo; eauto with paco.\n    econs.\n    { ii. inv IN. econs; eauto. }\n    i. inv PR. eapply GF in REL.\n    revert x2 MON.\n    pattern x0, x1, RR0, x3, x4, x5, x6, x7, x8.\n    revert x0 x1 RR0 x3 x4 x5 x6 x7 x8 REL.\n    apply pind9_acc. intros rr _ IH x0 x1 RR0 x3 x4 x5 x6 x7 x8 PR.\n    i. eapply pind9_unfold in PR.\n    2:{ eapply _lsim_mon. }\n    rename PR into LSIM. inv LSIM.\n\n    { eapply pind9_fold. econs; eauto. }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind9_fold. eapply lsim_tauL. split; ss.\n      hexploit IH; eauto.\n    }\n\n    { des. eapply pind9_fold. eapply lsim_chooseL. esplits; eauto. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_rmwL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_tidL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_UB. }\n\n    { des. eapply pind9_fold. eapply lsim_fairL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      eapply pind9_fold. eapply lsim_tauR. split; ss.\n      hexploit IH. eauto. all: eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_chooseR. i. split; ss. specialize (LSIM0 x).\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_rmwR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_tidR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_fairR. i. split; ss. specialize (LSIM0 _ FAIR).\n      des. destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_observe. i. eapply rclo9_clo_base. econs; eauto. }\n\n    { eapply pind9_fold. eapply lsim_call. i. eapply rclo9_clo_base. econs; eauto. }\n\n    { des. eapply pind9_fold. eapply lsim_yieldL. split; ss.\n      destruct LSIM0 as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_yieldR; eauto. i.\n      hexploit LSIM0; eauto. clear LSIM0. intros LSIM0.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. split; ss; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_sync; eauto. i.\n      hexploit LSIM0. eapply INV0. eapply VALID0. all: eauto. i; des. esplits; eauto.\n      eapply rclo9_clo_base. econs; eauto.\n    }\n\n    { eapply pind9_fold. eapply lsim_progress. eapply rclo9_clo_base. econs; eauto. }\n  Qed.\n\n  Variant lsim_frameC\n          (r: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src R_tgt\n          (RR: R_src -> R_tgt -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel :=\n    | lsim_frameC_intro\n        src tgt shr r_ctx ps pt r_frame\n        (REL: r _ _ (fun r_src r_tgt r_ctx shr =>\n                       forall r_ctx' (EQ: r_ctx = r_frame ⋅ r_ctx'),\n                         RR r_src r_tgt r_ctx' shr) ps pt (r_frame ⋅ r_ctx) src tgt shr)\n      :\n      lsim_frameC r RR ps pt r_ctx src tgt shr\n  .\n\n  Lemma lsim_frameC_spec tid\n    :\n    lsim_frameC <10= gupaco9 (fun r => pind9 (__lsim tid r) top9) (cpn9 (fun r => pind9 (__lsim tid r) top9)).\n  Proof.\n    eapply grespect9_uclo; eauto with paco.\n    econs.\n    { ii. inv IN. econs; eauto. }\n    i. inv PR. eapply GF in REL.\n    eapply rclo9_clo_base. eapply cpn9_gupaco.\n    { eauto with paco. }\n\n    remember (r_frame ⋅ x5).\n    pose (fun r_src r_tgt r_ctx shr =>\n            forall r_ctx' (EQ: r_ctx = r_frame ⋅ r_ctx'),\n              x2 r_src r_tgt r_ctx' shr) as RR1.\n    assert (FRAME: forall r_src r_tgt r_ctx shr\n                          (SAT: RR1 r_src r_tgt r_ctx shr),\n             forall r_ctx' (EQ: r_ctx = r_frame ⋅ r_ctx'),\n               x2 r_src r_tgt r_ctx' shr).\n    { subst RR1. auto. }\n    fold RR1 in REL.\n    remember RR1 as RR'. clear HeqRR' RR1.\n    revert x2 r_frame x5 Heqc FRAME.\n    pattern x0, x1, RR', x3, x4, c, x6, x7, x8.\n    revert x0 x1 RR' x3 x4 c x6 x7 x8 REL.\n    apply pind9_acc. intros rr _ IH x0 x1 RR' x3 x4 c x6 x7 x8 PR.\n    i. eapply pind9_unfold in PR.\n    2:{ eapply _lsim_mon. }\n    rename PR into LSIM. inv LSIM.\n\n    { guclo lsim_indC_spec. econs; eauto. }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      guclo lsim_indC_spec. eapply lsim_tauL.\n      hexploit IH; eauto.\n    }\n\n    { des. guclo lsim_indC_spec. eapply lsim_chooseL. esplits; eauto.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_rmwL.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_tidL.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_UB. }\n\n    { des. guclo lsim_indC_spec. eapply lsim_fairL. esplits; eauto.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      guclo lsim_indC_spec. eapply lsim_tauR.\n      hexploit IH. eauto. all: eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_chooseR. i. specialize (LSIM0 x).\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_rmwR.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_tidR.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_fairR. i. specialize (LSIM0 _ FAIR).\n      des. destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { gfinal. left. eapply pind9_fold. eapply lsim_observe. i.\n      eapply rclo9_clo. left. econs; eauto.\n      eapply rclo9_clo_base. right. guclo lsim_monoC_spec. econs.\n      2:{ gbase. eauto. }\n      { eauto. }\n    }\n\n    { gfinal. left. eapply pind9_fold. eapply lsim_call. i.\n      eapply rclo9_clo. left. econs; eauto.\n      eapply rclo9_clo_base. right. guclo lsim_monoC_spec. econs.\n      2:{ gbase. eauto. }\n      { eauto. }\n    }\n\n    { des. guclo lsim_indC_spec. eapply lsim_yieldL.\n      destruct LSIM0 as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_yieldR; eauto.\n      { instantiate (1:=r_own ⋅ r_frame). r_wf VALID. }\n      i. hexploit LSIM0; eauto.\n      { instantiate (1:=r_frame ⋅ r_ctx1). r_wf VALID0. }\n      clear LSIM0. intros LSIM0.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { gfinal. left. eapply pind9_fold. eapply lsim_sync; eauto.\n      { instantiate (1:=r_own ⋅ r_frame). r_wf VALID. }\n      i. hexploit LSIM0; eauto.\n      { instantiate (1:=r_frame ⋅ r_ctx1). r_wf VALID0. }\n      i. des.\n      eapply rclo9_clo. left. econs; eauto.\n      eapply rclo9_clo_base. right. guclo lsim_monoC_spec. econs.\n      2:{ gbase. eauto. }\n      { eauto. }\n    }\n\n    { gfinal. left. eapply pind9_fold. eapply lsim_progress.\n      eapply rclo9_clo. left. econs; eauto.\n      eapply rclo9_clo_base. right. guclo lsim_monoC_spec. econs.\n      2:{ gbase. eauto. }\n      { eauto. }\n    }\n  Qed.\n\n  Variant lsim_bindC'\n          (r: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src1 R_tgt1\n          (RR: R_src1 -> R_tgt1 -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src1 -> itree tgtE R_tgt1 -> shared_rel :=\n    | lsim_bindC'_intro\n        R_src0 R_tgt0 (RR0: R_src0 -> R_tgt0 -> URA.car -> shared_rel)\n        itr_src itr_tgt ktr_src ktr_tgt shr r_ctx ps pt\n        (REL: r _ _ RR0 ps pt r_ctx itr_src itr_tgt shr)\n        (MON: forall r_src r_tgt r_ctx shr\n                     (SAT: RR0 r_src r_tgt r_ctx shr),\n            r _ _ RR false false r_ctx (ktr_src r_src) (ktr_tgt r_tgt) shr)\n      :\n      lsim_bindC' r RR ps pt r_ctx (itr_src >>= ktr_src) (itr_tgt >>= ktr_tgt) shr\n  .\n\n  Lemma lsim_bindC'_spec tid\n    :\n    lsim_bindC' <10= gupaco9 (fun r => pind9 (__lsim tid r) top9) (cpn9 (fun r => pind9 (__lsim tid r) top9)).\n  Proof.\n    assert (HINT: forall r1, monotone9 (fun r0 => pind9 (__lsim tid r0) r1)).\n    { ii. eapply pind9_mon_gen; eauto. i. eapply __lsim_mon; eauto. }\n    eapply grespect9_uclo; eauto with paco.\n    econs.\n    { ii. inv IN. econs; eauto. }\n    i. inv PR. eapply GF in REL.\n    eapply rclo9_clo_base. eapply cpn9_gupaco.\n    { eauto with paco. }\n\n    revert ktr_src ktr_tgt MON.\n    pattern R_src0, R_tgt0, RR0, x3, x4, x5, itr_src, itr_tgt, x8.\n    revert R_src0 R_tgt0 RR0 x3 x4 x5 itr_src itr_tgt x8 REL.\n    apply pind9_acc. intros rr _ IH R_src0 R_tgt0 RR0 x3 x4 x5 itr_src itr_tgt x8 PR.\n    i. eapply pind9_unfold in PR.\n    2:{ eapply _lsim_mon. }\n    rename PR into LSIM. inv LSIM; ired.\n\n    { eapply lsim_resetC_spec. econs.\n      2:{ instantiate (1:=false). ss. }\n      2:{ instantiate (1:=false). ss. }\n      eapply MON in LSIM0. eapply GF in LSIM0.\n      eapply pind9_mon_gen; eauto. i. ss.\n      eapply __lsim_mon.\n      { i. eapply rclo9_base. eassumption. }\n      eauto.\n    }\n\n    Notation cpn := (cpn9 _).\n    Notation pind := (fun r => pind9 (__lsim _ r) top9).\n    ss.\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      guclo lsim_indC_spec. eapply lsim_tauL.\n      hexploit IH; eauto.\n    }\n\n    { des. guclo lsim_indC_spec. eapply lsim_chooseL. esplits; eauto.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_rmwL.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_tidL.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_UB. }\n\n    { des. guclo lsim_indC_spec. eapply lsim_fairL. esplits; eauto.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto.\n    }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      guclo lsim_indC_spec. eapply lsim_tauR.\n      hexploit IH. eauto. all: eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_chooseR. i. specialize (LSIM0 x).\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_rmwR.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_tidR.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_fairR. i. specialize (LSIM0 _ FAIR).\n      des. destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n    }\n\n    { gfinal. left. eapply pind9_fold. eapply lsim_observe. i.\n      eapply rclo9_clo_base. left. econs; eauto.\n    }\n\n    { gfinal. left. eapply pind9_fold. eapply lsim_call. i.\n      eapply rclo9_clo_base. left. econs; eauto.\n    }\n\n    { des. guclo lsim_indC_spec. eapply lsim_yieldL.\n      destruct LSIM0 as [LSIM IND]. hexploit IH; eauto.\n      rewrite ! bind_bind. eauto.\n    }\n\n    { guclo lsim_indC_spec. eapply lsim_yieldR; eauto.\n      i. hexploit LSIM0; eauto.\n      clear LSIM0. intros LSIM0.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto.\n      rewrite ! bind_bind. eauto.\n    }\n\n    { gfinal. left. eapply pind9_fold. eapply lsim_sync; eauto.\n      i. hexploit LSIM0; eauto.\n      i. des. eapply rclo9_clo_base. left. econs; eauto.\n    }\n\n    { gfinal. left. eapply pind9_fold. eapply lsim_progress. eapply rclo9_clo_base. left. econs; eauto.\n    }\n  Qed.\n\n  Variant lsim_bindC\n          (r: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src1 R_tgt1\n          (RR: R_src1 -> R_tgt1 -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src1 -> itree tgtE R_tgt1 -> shared_rel :=\n    | lsim_bindC_intro\n        R_src0 R_tgt0\n        itr_src itr_tgt ktr_src ktr_tgt shr r_ctx ps pt\n        (REL: r _ _ (fun (r_src: R_src0) (r_tgt: R_tgt0) r_ctx shr => r _ _ RR false false r_ctx (ktr_src r_src) (ktr_tgt r_tgt) shr) ps pt r_ctx itr_src itr_tgt shr)\n      :\n      lsim_bindC r RR ps pt r_ctx (itr_src >>= ktr_src) (itr_tgt >>= ktr_tgt) shr\n  .\n\n  Lemma lsim_bindC_spec tid\n    :\n    lsim_bindC <10= gupaco9 (fun r => pind9 (__lsim tid r) top9) (cpn9 (fun r => pind9 (__lsim tid r) top9)).\n  Proof.\n    i. eapply lsim_bindC'_spec. inv PR. econs; eauto.\n  Qed.\n\n  Lemma lsim_set_prog\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        r_ctx src tgt shr\n        (LSIM: lsim tid RR true true r_ctx src tgt shr)\n    :\n    forall ps pt, lsim tid RR ps pt r_ctx src tgt shr.\n  Proof.\n    i. revert_until tid. pcofix CIH. i.\n    remember true as ps0 in LSIM at 1. remember true as pt0 in LSIM at 1.\n    move LSIM before CIH. revert_until LSIM. punfold LSIM.\n    eapply pind9_acc in LSIM.\n\n    { instantiate (1:= (fun R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel) ps0 pt0 r_ctx src tgt shr =>\n                          ps0 = true ->\n                          pt0 = true ->\n                          forall ps pt,\n                            paco9\n                              (fun r0 =>\n                                 pind9 (__lsim tid r0) top9) r R0 R1 RR ps pt r_ctx src tgt shr)) in LSIM; auto. }\n\n    ss. clear ps0 pt0 r_ctx src tgt shr LSIM.\n    intros rr DEC IH R0' R1' RR' gps gpt r_ctx src tgt shr LSIM. clear DEC.\n    intros Egps Egpt ps pt.\n    eapply pind9_unfold in LSIM.\n    2:{ eapply _lsim_mon. }\n    inv LSIM.\n\n    { pfold. eapply pind9_fold. econs; eauto. }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      pfold. eapply pind9_fold. eapply lsim_tauL. split; ss.\n      hexploit IH. eauto. all: eauto. i. punfold H.\n    }\n\n    { des. pfold. eapply pind9_fold. eapply lsim_chooseL. esplits; eauto. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_rmwL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_tidL. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_UB. }\n\n    { des. pfold. eapply pind9_fold. eapply lsim_fairL. esplits; eauto. split; ss.\n      destruct LSIM as [LSIM IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { destruct LSIM0 as [LSIM0 IND]. clear LSIM0.\n      pfold. eapply pind9_fold. eapply lsim_tauR. split; ss.\n      hexploit IH. eauto. all: eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_chooseR. i. split; ss. specialize (LSIM0 x).\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_rmwR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_tidR. split; ss.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_fairR. i. split; ss. specialize (LSIM0 _ FAIR).\n      des. destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_observe. i. eapply upaco9_mon_bot; eauto. }\n\n    { pfold. eapply pind9_fold. eapply lsim_call. i. eapply upaco9_mon_bot; eauto. }\n\n    { des. pfold. eapply pind9_fold. eapply lsim_yieldL. esplits; eauto. split; ss.\n      destruct LSIM0 as [LSIM IND]. hexploit IH; eauto. i. punfold H.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_yieldR; eauto. i.\n      hexploit LSIM0; eauto. clear LSIM0. intros LSIM0.\n      destruct LSIM0 as [LSIM0 IND]. hexploit IH; eauto. i. split; ss. punfold H.\n    }\n\n    { pfold. eapply pind9_fold. eapply lsim_sync; eauto. i.\n      hexploit LSIM0. eapply INV0. eapply VALID0. all: eauto. i; des. esplits; eauto.\n      eapply upaco9_mon_bot; eauto.\n    }\n\n    { pclearbot. eapply paco9_mon_bot. eapply lsim_reset_prog. eauto. all: ss. }\n\n  Qed.\n\n  Lemma lsim_flag_any ps0 pt0\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        src tgt shr\n        ps1 pt1 r_ctx\n        (LSIM: lsim tid RR ps1 pt1 r_ctx src tgt shr)\n    :\n    lsim tid RR ps0 pt0 r_ctx src tgt shr.\n  Proof.\n    eapply lsim_set_prog. eapply lsim_reset_prog; eauto.\n  Qed.\n\n  Variant lsim_bindRC'\n          (r: forall R_src R_tgt (RR: R_src -> R_tgt -> URA.car -> shared_rel), bool -> bool -> URA.car -> itree srcE R_src -> itree tgtE R_tgt -> shared_rel)\n          R_src1 R_tgt1\n          (RR: R_src1 -> R_tgt1 -> URA.car -> shared_rel)\n    :\n    bool -> bool -> URA.car -> itree srcE R_src1 -> itree tgtE R_tgt1 -> shared_rel :=\n    | lsim_bindRC'_intro\n        R_tgt0 (RR0: R_tgt0 -> URA.car -> shared_rel)\n        itr_tgt ktr_src ktr_tgt shr r_ctx ps pt\n        (REL: r _ _ (fun _ => RR0) ps pt r_ctx (trigger Yield) itr_tgt shr)\n        (MON: forall r_tgt r_ctx shr\n                     (SAT: RR0 r_tgt r_ctx shr),\n            r _ _ RR false false r_ctx (trigger Yield >>= ktr_src) (ktr_tgt r_tgt) shr)\n      :\n      lsim_bindRC' r RR ps pt r_ctx (trigger Yield >>= ktr_src) (itr_tgt >>= ktr_tgt) shr\n  .\n\n  Require Import Program.\n\n  Lemma trigger_yield E `{cE -< E}\n    :\n    (trigger Yield;;; Ret tt: itree E unit) = trigger Yield.\n  Proof.\n    eapply observe_eta. ss.\n    rewrite bind_trigger. ss.\n    f_equal. extensionality x. destruct x. ss.\n  Qed.\n\n  Lemma trigger_yield_rev E `{cE -< E}\n        ktr\n        (EQ: (trigger Yield >>= ktr: itree E unit) = trigger Yield)\n    :\n    ktr = fun _ => Ret tt.\n  Proof.\n    eapply f_equal with (f:=observe) in EQ.\n    ss. rewrite bind_trigger in EQ. ss.\n    dependent destruction EQ.\n    extensionality u. destruct u.\n    eapply equal_f in x. eauto.\n  Qed.\n\n  Lemma trigger_unit_same (E: Type -> Type) (e: E unit) R\n        (ktr: unit -> itree E R)\n    :\n    trigger e >>= (fun x => ktr x) = trigger e >>= (fun x => ktr tt).\n  Proof.\n    f_equal. extensionality u. destruct u. auto.\n  Qed.\n\n  Lemma trigger_eq_rev E R X0 X1 (e0: E X0) (e1: E X1)\n        (ktr0: X0 -> itree E R) (ktr1: X1 -> itree E R)\n        (EQ: ITree.trigger e0 >>= ktr0 = ITree.trigger e1 >>= ktr1)\n    :\n    X0 = X1 /\\ e0 ~= e1 /\\ ktr0 ~= ktr1.\n  Proof.\n    rewrite bind_trigger in EQ.\n    rewrite bind_trigger in EQ.\n    eapply f_equal with (f:=observe) in EQ. ss.\n    dependent destruction EQ. splits; auto.\n    assert (ktr0 = ktr1).\n    { extensionality a. eapply equal_f in x. eauto. }\n    subst. auto.\n  Qed.\n\n  Lemma lsim_rev_ret\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        r_src r_tgt shr ps pt r_ctx\n        (LSIM: lsim tid RR ps pt r_ctx (Ret r_src) (Ret r_tgt) shr)\n    :\n    RR r_src r_tgt r_ctx shr.\n  Proof.\n    eapply lsim_reset_prog in LSIM.\n    2:{ i. reflexivity. }\n    2:{ i. reflexivity. }\n    eapply lsim_set_prog in LSIM.\n    instantiate (1:=false) in LSIM. instantiate (1:=false) in LSIM. clear ps pt.\n    punfold LSIM. eapply pind9_unfold in LSIM; auto.\n    2:{ eapply _lsim_mon. }\n    inv LSIM; auto.\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n  Qed.\n\n  Lemma lsim_rev_tau\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        r_src tgt shr ps pt r_ctx\n        (LSIM: lsim tid RR ps pt r_ctx (Ret r_src) (Tau tgt) shr)\n    :\n    lsim tid RR ps pt r_ctx (Ret r_src) tgt shr.\n  Proof.\n    eapply lsim_reset_prog in LSIM.\n    2:{ i. reflexivity. }\n    2:{ i. reflexivity. }\n    eapply lsim_set_prog in LSIM.\n    instantiate (1:=false) in LSIM. instantiate (1:=false) in LSIM.\n    punfold LSIM. eapply pind9_unfold in LSIM; auto.\n    2:{ eapply _lsim_mon. }\n    inv LSIM; auto.\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { inv LSIM0. eapply lsim_flag_any. pfold. eauto. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n  Qed.\n\n  Lemma lsim_rev_choose\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        r_src X tgt shr ps pt r_ctx\n        (LSIM: lsim tid RR ps pt r_ctx (Ret r_src) (trigger (Choose X) >>= tgt) shr)\n    :\n    forall x, lsim tid RR ps pt r_ctx (Ret r_src) (tgt x) shr.\n  Proof.\n    eapply lsim_reset_prog in LSIM.\n    2:{ i. reflexivity. }\n    2:{ i. reflexivity. }\n    eapply lsim_set_prog in LSIM.\n    instantiate (1:=false) in LSIM. instantiate (1:=false) in LSIM.\n    punfold LSIM. eapply pind9_unfold in LSIM; auto.\n    2:{ eapply _lsim_mon. }\n    inv LSIM; auto.\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply trigger_eq_rev in H4. des. subst.\n      i. specialize (LSIM0 x). inv LSIM0.\n      eapply lsim_flag_any. pfold. eauto. }\n    { eapply trigger_eq_rev in H4. des. subst. dependent destruction H0. }\n    { eapply trigger_eq_rev in H4. des. subst. dependent destruction H0. }\n    { eapply trigger_eq_rev in H4. des. subst. dependent destruction H0. }\n    { eapply trigger_eq_rev in H4. des. subst. dependent destruction H0. }\n    { eapply trigger_eq_rev in H4. des. subst. dependent destruction H0. }\n    { eapply trigger_eq_rev in H4. des. subst. dependent destruction H0. }\n    { eapply trigger_eq_rev in H4. des. subst. dependent destruction H0. }\n    { eapply trigger_eq_rev in H4. des. subst. dependent destruction H0. }\n  Qed.\n\n  Lemma inhabited_not_void X\n        (INHABITED: inhabited X)\n    :\n    X <> void.\n  Proof.\n    ii. subst. inv INHABITED. inv H.\n  Qed.\n\n  Lemma nat_not_unit\n    :\n    (nat: Type) <> unit.\n  Proof.\n    ii. assert (exists (u0 u1: nat), u0 <> u1).\n    { exists 0, 1. ss. }\n    rewrite H in H0. des. destruct u0, u1. ss.\n  Qed.\n\n  Lemma lsim_rev_tid\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        r_src tgt shr ps pt r_ctx\n        (LSIM: lsim tid RR ps pt r_ctx (Ret r_src) (trigger (GetTid) >>= tgt) shr)\n    :\n    lsim tid RR ps pt r_ctx (Ret r_src) (tgt tid) shr.\n  Proof.\n    eapply lsim_reset_prog in LSIM.\n    2:{ i. reflexivity. }\n    2:{ i. reflexivity. }\n    eapply lsim_set_prog in LSIM.\n    instantiate (1:=false) in LSIM. instantiate (1:=false) in LSIM.\n    punfold LSIM. eapply pind9_unfold in LSIM; auto.\n    2:{ eapply _lsim_mon. }\n    inv LSIM; auto.\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply trigger_eq_rev in H4. des. subst.\n      inv LSIM0. eapply lsim_flag_any. pfold. eauto. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n  Qed.\n\n  Lemma lsim_rev_UB\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        r_src tgt shr ps pt r_ctx\n        (LSIM: lsim tid RR ps pt r_ctx (Ret r_src) (trigger (Undefined) >>= tgt) shr)\n    :\n    False.\n  Proof.\n    eapply lsim_reset_prog in LSIM.\n    2:{ i. reflexivity. }\n    2:{ i. reflexivity. }\n    eapply lsim_set_prog in LSIM.\n    instantiate (1:=false) in LSIM. instantiate (1:=false) in LSIM.\n    punfold LSIM. eapply pind9_unfold in LSIM; auto.\n    2:{ eapply _lsim_mon. }\n    inv LSIM; auto.\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply trigger_eq_rev in H4. des. exfalso.\n      clear - H4 H0 H1. subst. dependent destruction H0.\n    }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n  Qed.\n\n  Lemma lsim_rev_yield\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        r_src tgt shr ps pt r_ctx\n        (LSIM: lsim tid RR ps pt r_ctx (Ret r_src) (trigger (Yield) >>= tgt) shr)\n    :\n    False.\n  Proof.\n    eapply lsim_reset_prog in LSIM.\n    2:{ i. reflexivity. }\n    2:{ i. reflexivity. }\n    eapply lsim_set_prog in LSIM.\n    instantiate (1:=false) in LSIM. instantiate (1:=false) in LSIM.\n    punfold LSIM. eapply pind9_unfold in LSIM; auto.\n    2:{ eapply _lsim_mon. }\n    inv LSIM; auto.\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n  Qed.\n\n  Lemma lsim_rev_fair\n        tid\n        R0 R1 (RR: R0 -> R1 -> URA.car -> shared_rel)\n        r_src tgt ths im_src im_tgt st_src st_tgt ps pt r_ctx\n        f\n        (LSIM: lsim tid RR ps pt r_ctx (Ret r_src) (trigger (Fair f) >>= tgt) (ths, im_src, im_tgt, st_src, st_tgt))\n    :\n    forall im_tgt1\n           (FAIR: fair_update im_tgt im_tgt1 (prism_fmap inrp f)),\n      (<<LSIM: lsim tid RR ps pt r_ctx (Ret r_src) (tgt tt) (ths, im_src, im_tgt1, st_src, st_tgt)>>).\n  Proof.\n    eapply lsim_reset_prog in LSIM.\n    2:{ i. reflexivity. }\n    2:{ i. reflexivity. }\n    eapply lsim_set_prog in LSIM.\n    instantiate (1:=false) in LSIM. instantiate (1:=false) in LSIM.\n    punfold LSIM. eapply pind9_unfold in LSIM; auto.\n    2:{ eapply _lsim_mon. }\n    inv LSIM; auto.\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H4. ss. }\n    { eapply trigger_eq_rev in H4. des. subst. dependent destruction H0. }\n    { eapply trigger_eq_rev in H4. des. subst. dependent destruction H0. }\n    { eapply trigger_eq_rev in H4. des. exfalso.\n      eapply nat_not_unit; ss.\n    }\n    { eapply trigger_eq_rev in H4. des. subst. dependent destruction H0.\n      i. specialize (LSIM0 _ FAIR).\n      inv LSIM0. eapply lsim_flag_any. pfold. eauto.\n    }\n    { eapply trigger_eq_rev in H4. des. exfalso.\n      eapply nat_not_unit; eauto.\n    }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n    { eapply f_equal with (f:=observe) in H3. ss. }\n  Qed.\n\n  Lemma lsim_monoR\n        tid\n        R0 R1 (RR0 RR1: R0 -> R1 -> URA.car -> shared_rel)\n        p_src p_tgt st ps pt r_ctx\n        (LSIM: lsim tid RR0 ps pt r_ctx p_src p_tgt st)\n        (MON: forall r_src r_tgt r_ctx shr (RET: RR0 r_src r_tgt r_ctx shr),\n            RR1 r_src r_tgt r_ctx shr)\n    :\n    lsim tid RR1 ps pt r_ctx p_src p_tgt st.\n  Proof.\n    ginit. guclo lsim_monoC_spec. econs; eauto. gfinal. auto.\n  Qed.\n\n  Definition local_RR {R0 R1} (RR: R0 -> R1 -> Prop) tid:\n    R0 -> R1 -> URA.car -> shared_rel :=\n    fun (r_src: R0) (r_tgt: R1) (r_ctx: URA.car) '(ths2, im_src1, im_tgt1, st_src1, st_tgt1) =>\n      (exists ths3 r_own r_shared,\n          (<<THS: NatMap.remove tid ths2 = ths3>>) /\\\n            (<<VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx)>>) /\\\n            (<<INV: I (ths3, im_src1, im_tgt1, st_src1, st_tgt1) r_shared>>) /\\\n            (<<RET: RR r_src r_tgt>>)).\n\n  Definition local_sim {R0 R1} (RR: R0 -> R1 -> Prop) src tgt :=\n    forall ths0 im_src0 im_tgt0 st_src0 st_tgt0 r_shared0 r_ctx0\n           (INV: I (ths0, im_src0, im_tgt0, st_src0, st_tgt0) r_shared0)\n           tid ths1\n           (THS: TIdSet.add_new tid ths0 ths1)\n           (VALID: URA.wf (r_shared0 ⋅ r_ctx0)),\n    forall im_tgt1\n      (TID_TGT : fair_update im_tgt0 im_tgt1 (prism_fmap inlp (fun i => if tid_dec i tid then Flag.success else Flag.emp))),\n    exists r_shared1 r_own,\n      (<<INV: I (ths1, im_src0, im_tgt1, st_src0, st_tgt0) r_shared1>>) /\\\n        (<<VALID: URA.wf (r_shared1 ⋅ r_own ⋅ r_ctx0)>>) /\\\n        (forall ths im_src1 im_tgt2 st_src2 st_tgt2 r_shared2 r_ctx2\n           (INV: I (ths, im_src1, im_tgt2, st_src2, st_tgt2) r_shared2)\n                (VALID: URA.wf (r_shared2 ⋅ r_own ⋅ r_ctx2)),\n          forall im_tgt3 (TGT: fair_update im_tgt2 im_tgt3 (prism_fmap inlp (tids_fmap tid ths))),\n            (<<LSIM: forall fs ft,\n                lsim\n                  tid\n                  (@local_RR R0 R1 RR tid)\n                  fs ft\n                  r_ctx2\n                  src tgt\n                  (ths, im_src1, im_tgt3, st_src2, st_tgt2)\n                  >>)).\n\n  Definition local_sim_init {R0 R1} (RR: R0 -> R1 -> Prop) (r_own: URA.car) tid src tgt :=\n    forall ths im_src im_tgt st_src st_tgt r_shared r_ctx\n           (INV: I (ths, im_src, im_tgt, st_src, st_tgt) r_shared)\n           (VALID: URA.wf (r_shared ⋅ r_own ⋅ r_ctx)),\n    forall im_tgt1 (FAIR: fair_update im_tgt im_tgt1 (prism_fmap inlp (tids_fmap tid ths))),\n    forall fs ft,\n      lsim\n        tid\n        (@local_RR R0 R1 RR tid)\n        fs ft\n        r_ctx\n        src tgt\n        (ths, im_src, im_tgt1, st_src, st_tgt).\n\nEnd PRIMIVIESIM.\n#[export] Hint Constructors __lsim: core.\n#[export] Hint Unfold lsim: core.\n#[export] Hint Resolve __lsim_mon: paco.\n#[export] Hint Resolve _lsim_mon: paco.\n#[export] Hint Resolve lsim_mon: paco.\n#[export] Hint Resolve cpn9_wcompat: paco.\n\n\nModule ModSim.\n  Section MODSIM.\n\n    Variable md_src: Mod.t.\n    Variable md_tgt: Mod.t.\n\n    Record mod_sim: Prop :=\n      mk {\n          wf_src : WF;\n          wf_tgt : WF;\n          wf_tgt_inhabited: inhabited wf_tgt.(T);\n          wf_tgt_open: forall (o0: wf_tgt.(T)), exists o1, wf_tgt.(lt) o0 o1;\n\n          world: URA.t;\n\n          (* I: (@shared md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt) -> world -> Prop; *)\n          init: forall im_tgt,\n          exists (I: (@shared md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt) -> world -> Prop),\n          (exists im_src r_shared,\n            (I (NatSet.empty, im_src, im_tgt, md_src.(Mod.st_init), md_tgt.(Mod.st_init)) r_shared) /\\\n              (URA.wf r_shared)) /\\\n          (forall fn args, match md_src.(Mod.funs) fn, md_tgt.(Mod.funs) fn with\n                           | Some ktr_src, Some ktr_tgt => local_sim I (@eq Any.t) (ktr_src args) (ktr_tgt args)\n                           | None, None => True\n                           | _, _ => False\n                           end);\n        }.\n  End MODSIM.\nEnd ModSim.\n\n\nFrom Fairness Require Import Concurrency.\n\nModule UserSim.\n  Section MODSIM.\n\n    Variable md_src: Mod.t.\n    Variable md_tgt: Mod.t.\n\n    Record sim (p_src: Th.t _) (p_tgt: Th.t _) : Prop :=\n      mk {\n          wf_src : WF;\n          wf_tgt : WF;\n          wf_tgt_inhabited: inhabited wf_tgt.(T);\n          wf_tgt_open: forall (o0: wf_tgt.(T)), exists o1, wf_tgt.(lt) o0 o1;\n\n          world: URA.t;\n\n          (* I: (@shared md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt) -> world -> Prop; *)\n          funs: forall im_tgt,\n            exists (I: (@shared md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt) -> world -> Prop),\n          exists im_src rs r_shared,\n            (<<INIT: I (key_set p_src, im_src, im_tgt, md_src.(Mod.st_init), md_tgt.(Mod.st_init)) r_shared>>) /\\\n              (<<SIM: Forall3\n                        (fun '(t1, src) '(t2, tgt) '(t3, r) =>\n                           t1 = t2 /\\ t1 = t3 /\\\n                           @local_sim_init _ md_src.(Mod.state) md_tgt.(Mod.state) md_src.(Mod.ident) md_tgt.(Mod.ident) wf_src wf_tgt I _ _ (@eq Any.t) r t1 src tgt)\n                        (Th.elements p_src) (Th.elements p_tgt) (NatMap.elements rs)>>) /\\\n              (<<WF: URA.wf (r_shared ⋅ NatMap.fold (fun _ r s => r ⋅ s) rs ε)>>)\n        }.\n  End MODSIM.\nEnd UserSim.\n", "meta": {"author": "snu-sf", "repo": "fairness", "sha": "170bd1ade88d32ac6ab661ed0c272af8a00d9ea1", "save_path": "github-repos/coq/snu-sf-fairness", "path": "github-repos/coq/snu-sf-fairness/fairness-170bd1ade88d32ac6ab661ed0c272af8a00d9ea1/src/simulation/ModSim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.35577490034429643, "lm_q1q2_score": 0.20545835599827522}}
{"text": "Require Import Events. (*is needed for some definitions (loc_unmapped etc*)\nRequire Import Memory.\nRequire Import Coqlib.\nRequire Import Integers.\nRequire Import Values.\nRequire Import Maps.\nRequire Import Axioms.\n\nRequire Import structured_injections.\nRequire Import reach.\nRequire Import simulations.\nRequire Import simulations_lemmas.\nRequire Import mem_lemmas.\nRequire Import mem_interpolation_defs.\nRequire Import mem_interpolation_II.\nRequire Import FiniteMaps.\n\n(*<<<<<<< HEAD:core/interpolation_II.v\n\n(*Inserts the new injection entries into extern component, but not into foreign*)\nDefinition insert_as_extern (mu: SM_Injection) (j: meminj) (DomJ TgtJ:block->bool)\n          : SM_Injection:=\n  match mu with \n    Build_SM_Injection locBSrc locBTgt pSrc pTgt local extBSrc extBTgt fSrc fTgt extern => \n    Build_SM_Injection locBSrc locBTgt pSrc pTgt local\n      (fun b => orb (extBSrc b) (DomJ b))\n      (fun b => orb (extBTgt b) (TgtJ b))\n      fSrc\n      fTgt\n      (join extern (fun b => match local b with Some _ => None\n                                              | None => j b end))\n  end.\n\nDefinition convertL (nu12: SM_Injection) (j12':meminj) FreshSrc FreshMid:= \n  insert_as_extern nu12 j12' FreshSrc FreshMid. \n\nDefinition convertR (nu23: SM_Injection) (j23':meminj) FreshMid FreshTgt:= \n  insert_as_extern nu23 j23' FreshMid FreshTgt.\n\nLemma convertL_local: forall nu12 j12' FreshSrc FreshMid,\n            local_of (convertL nu12 j12' FreshSrc FreshMid) =\n            local_of nu12.\nProof. intros. destruct nu12. reflexivity. Qed. \n\nLemma convertL_pub: forall nu12 j12' FreshSrc FreshMid,\n            pub_of (convertL nu12 j12' FreshSrc FreshMid) =\n            pub_of nu12.\nProof. intros. destruct nu12. reflexivity. Qed. \n\nLemma convertL_priv: forall nu12 j12' FreshSrc FreshMid,\n            priv_of (convertL nu12 j12' FreshSrc FreshMid) =\n            priv_of nu12.\nProof. intros. destruct nu12. reflexivity. Qed. \n\nLemma convertL_extern: forall nu12 j12' FreshSrc FreshMid,\n            extern_of (convertL nu12 j12' FreshSrc FreshMid) =\n            join (extern_of nu12)\n                 (fun b => match (local_of nu12) b with Some _ => None | None => j12' b end).\nProof. intros. destruct nu12; simpl. reflexivity. Qed. \n\nLemma convertL_locBlocksSrc: forall nu12 j12' FreshSrc FreshMid,\n            locBlocksSrc (convertL nu12 j12' FreshSrc FreshMid) =\n            locBlocksSrc nu12.\nProof. intros. destruct nu12. reflexivity. Qed. \n\nLemma convertL_locBlocksTgt: forall nu12 j12' FreshSrc FreshMid,\n            locBlocksTgt (convertL nu12 j12' FreshSrc FreshMid) =\n            locBlocksTgt nu12.\nProof. intros. destruct nu12. reflexivity. Qed. \n\nLemma convertL_extBlocksSrc: forall nu12 j12' FreshSrc FreshMid,\n            extBlocksSrc (convertL nu12 j12' FreshSrc FreshMid) =\n            fun b => orb (extBlocksSrc nu12 b) (FreshSrc b).\nProof. intros. destruct nu12. reflexivity. Qed. \n\nLemma convertL_extBlocksTgt: forall nu12 j12' FreshSrc FreshMid,\n            extBlocksTgt (convertL nu12 j12' FreshSrc FreshMid) =\n            fun b => orb (extBlocksTgt nu12 b) (FreshMid b).\nProof. intros. destruct nu12. reflexivity. Qed. \n\nLemma convertL_DomSrc: forall nu12 j12' FreshSrc FreshMid,\n            DomSrc (convertL nu12 j12' FreshSrc FreshMid) =\n            (fun b => orb (DomSrc nu12 b) (FreshSrc b)).\nProof. intros. destruct nu12. unfold DomSrc; simpl in *. \n       extensionality b. rewrite orb_assoc. reflexivity. Qed. \n\nLemma convertL_DomTgt: forall nu12 j12' FreshSrc FreshMid,\n            DomTgt (convertL nu12 j12' FreshSrc FreshMid) =\n            (fun b => orb (DomTgt nu12 b) (FreshMid b)).\nProof. intros. destruct nu12. unfold DomTgt; simpl in *. \n       extensionality b. rewrite orb_assoc. reflexivity. Qed. \n\nLemma convertL_pubBlocksSrc: forall nu12 j12' FreshSrc FreshMid,\n            pubBlocksSrc (convertL nu12 j12' FreshSrc FreshMid) =\n            pubBlocksSrc nu12.\nProof. intros. destruct nu12. reflexivity. Qed. \n\nLemma convertL_pubBlocksTgt: forall nu12 j12' FreshSrc FreshMid,\n            pubBlocksTgt (convertL nu12 j12' FreshSrc FreshMid) =\n            pubBlocksTgt nu12.\nProof. intros. destruct nu12. reflexivity. Qed. \n\nLemma convertL_frgnBlocksSrc: forall nu12 j12' FreshSrc FreshMid,\n            frgnBlocksSrc (convertL nu12 j12' FreshSrc FreshMid) =\n            frgnBlocksSrc nu12.\nProof. intros. destruct nu12. simpl. reflexivity. Qed. \n\nLemma convertL_frgnBlocksTgt: forall nu12 j12' FreshSrc FreshMid,\n            frgnBlocksTgt (convertL nu12 j12' FreshSrc FreshMid) =\n            frgnBlocksTgt nu12.\nProof. intros. destruct nu12. reflexivity. Qed. \n\nLemma convertL_foreign: forall nu12 j12' FreshSrc FreshMid (WD12:SM_wd nu12),\n            foreign_of (convertL nu12 j12' FreshSrc FreshMid) =\n            foreign_of nu12. \nProof. intros. destruct nu12; simpl in *. extensionality b.\n  remember (frgnBlocksSrc b) as d.\n  destruct d; trivial. apply eq_sym in Heqd.\n  destruct (frgnSrc _ WD12 _ Heqd) as [b2 [z [Frg _]]]. simpl in Frg.\n  rewrite Heqd in Frg; unfold join. rewrite Frg; trivial. Qed.\n\nLemma convertR_local: forall nu23 j23' FreshMid FreshTgt,\n            local_of (convertR nu23 j23' FreshMid FreshTgt) =\n            local_of nu23.\nProof. intros. destruct nu23; simpl. reflexivity. Qed.\n \nLemma convertR_pub: forall nu23 j23' FreshMid FreshTgt,\n            pub_of (convertR nu23 j23' FreshMid FreshTgt) =\n            pub_of nu23.\nProof. intros. destruct nu23; simpl. reflexivity. Qed. \n\nLemma convertR_priv: forall nu23 j23' FreshMid FreshTgt,\n            priv_of (convertR nu23 j23' FreshMid FreshTgt) =\n            priv_of nu23.\nProof. intros. destruct nu23; simpl. reflexivity. Qed. \n\nLemma convertR_extern: forall nu23 j23' FreshMid FreshTgt,\n            extern_of (convertR nu23 j23' FreshMid FreshTgt) =\n            join (extern_of nu23)\n                 (fun b => match (local_of nu23) b with Some _ => None | None => j23' b end).\nProof. intros. destruct nu23; simpl. reflexivity. Qed.\n\nLemma convertR_foreign: forall nu23 j23' FreshMid FreshTgt (WD23:SM_wd nu23),\n            foreign_of (convertR nu23 j23' FreshMid FreshTgt) =\n            foreign_of nu23.\nProof. intros. destruct nu23; simpl in *. extensionality b.\n  remember (frgnBlocksSrc b) as d.\n  destruct d; trivial. apply eq_sym in Heqd.\n  destruct (frgnSrc _ WD23 _ Heqd) as [b2 [z [Frg _]]]. simpl in Frg.\n  rewrite Heqd in Frg; unfold join. rewrite Frg; trivial. Qed.\n\nLemma convertR_locBlocksSrc: forall nu23 j23' FreshMid FreshTgt,\n            locBlocksSrc (convertR nu23 j23' FreshMid FreshTgt) =\n            locBlocksSrc nu23.\nProof. intros. destruct nu23. reflexivity. Qed. \n\nLemma convertR_locBlocksTgt: forall nu23 j23' FreshMid FreshTgt,\n            locBlocksTgt (convertR nu23 j23' FreshMid FreshTgt) =\n            locBlocksTgt nu23.\nProof. intros. destruct nu23. reflexivity. Qed. \n\nLemma convertR_extBlocksSrc: forall nu23 j23' FreshMid FreshTgt,\n            extBlocksSrc (convertR nu23 j23' FreshMid FreshTgt) =\n            fun b => orb (extBlocksSrc nu23 b) (FreshMid b).\nProof. intros. destruct nu23. reflexivity. Qed. \n\nLemma convertR_extBlocksTgt: forall nu23 j23' FreshMid FreshTgt,\n            extBlocksTgt (convertR nu23 j23' FreshMid FreshTgt) =\n            fun b => orb (extBlocksTgt nu23 b) (FreshTgt b).\nProof. intros. destruct nu23. reflexivity. Qed. \n\nLemma convertR_DomSrc: forall nu23 j23' FreshMid FreshTgt,\n            DomSrc (convertR nu23 j23' FreshMid FreshTgt) =\n            (fun b => orb (DomSrc nu23 b) (FreshMid b)).\nProof. intros. destruct nu23; simpl. unfold DomSrc; simpl.\n       extensionality b. rewrite orb_assoc. reflexivity. Qed. \n\nLemma convertR_DomTgt: forall nu23 j23' FreshMid FreshTgt,\n            DomTgt (convertR nu23 j23' FreshMid FreshTgt) =\n            (fun b => orb (DomTgt nu23 b) (FreshTgt b)).\nProof. intros. destruct nu23; simpl. unfold DomTgt; simpl.\n       extensionality b. rewrite orb_assoc. reflexivity. Qed. \n\nLemma convertR_pubBlocksSrc: forall nu23 j23' FreshMid FreshTgt,\n            pubBlocksSrc (convertR nu23 j23' FreshMid FreshTgt) =\n            pubBlocksSrc nu23.\nProof. intros. destruct nu23. reflexivity. Qed. \n\nLemma convertR_pubBlocksTgt: forall nu23 j23' FreshMid FreshTgt,\n            pubBlocksTgt (convertR nu23 j23' FreshMid FreshTgt) =\n            pubBlocksTgt nu23.\nProof. intros. destruct nu23. reflexivity. Qed. \n\nLemma convertR_frgnBlocksSrc: forall nu23 j23' FreshMid FreshTgt,\n            frgnBlocksSrc (convertR nu23 j23' FreshMid FreshTgt) =\n            frgnBlocksSrc nu23.\nProof. intros. destruct nu23. simpl. reflexivity. Qed. \n\nLemma convertR_frgnBlocksTgt: forall nu23 j23' FreshMid FreshTgt,\n            frgnBlocksTgt (convertR nu23 j23' FreshMid FreshTgt) =\n            frgnBlocksTgt nu23.\nProof. intros. destruct nu23; simpl. reflexivity. Qed. \n\nDefinition FreshDom (j j': meminj) b :=\n  match j' b with\n     None => false\n   | Some(b',z) => match j b with\n                     None => true  \n                   | Some _ => false\n                   end\n  end.\n\nDefinition AccessEffProperty nu23 nu12 (j12' :meminj) (m1 m1' m2 : mem)\n           (AM:ZMap.t (Z -> perm_kind -> option permission)):Prop :=\n  forall b2, \n    (Mem.valid_block m2 b2 -> forall k ofs2,\n       if (locBlocksSrc nu23 b2) \n       then if (pubBlocksSrc nu23 b2)\n            then match source (local_of nu12) m1 b2 ofs2 with\n                   Some(b1,ofs1) => if pubBlocksSrc nu12 b1 \n                                    then PMap.get b2 AM ofs2 k = \n                                         PMap.get b1 m1'.(Mem.mem_access) ofs1 k\n                                    else PMap.get b2 AM ofs2 k = \n                                         PMap.get b2 m2.(Mem.mem_access) ofs2 k\n                 | None =>  PMap.get b2 AM ofs2 k = \n                            PMap.get b2 m2.(Mem.mem_access) ofs2 k\n                 end\n            else PMap.get b2 AM ofs2 k = \n                 PMap.get b2 m2.(Mem.mem_access) ofs2 k\n       else match source (as_inj nu12) m1 b2 ofs2 with\n                   Some(b1,ofs1) =>  PMap.get b2 AM ofs2 k = \n                                     PMap.get b1 m1'.(Mem.mem_access) ofs1 k\n                 | None => match (*j23*) (as_inj nu23) b2 with \n                             None => PMap.get b2 AM ofs2 k  = PMap.get b2 m2.(Mem.mem_access) ofs2 k\n                           | Some (b3,d3) =>  PMap.get b2 AM ofs2 k = None (* mem_interpolation_II.v has PMap.get b2 m2.(Mem.mem_access) ofs2 k here \n                                            -- see the comment in the proof script below to see where None is needed*)\n                           end\n\n                 \n               end)\n     /\\ (~ Mem.valid_block m2 b2 -> forall k ofs2,\n           match source j12' m1' b2 ofs2 with \n              Some(b1,ofs1) => PMap.get b2 AM ofs2 k =\n                               PMap.get b1 m1'.(Mem.mem_access) ofs1 k\n            | None =>  PMap.get b2 AM ofs2 k = None\n          end).\n\nDefinition ContentEffProperty nu23 nu12 (j12':meminj) (m1 m1' m2:Mem.mem)\n                               (CM:ZMap.t (ZMap.t memval)):=\n  forall b2, \n  (Mem.valid_block m2 b2 -> forall ofs2,\n    if locBlocksSrc nu23 b2\n    then if (pubBlocksSrc nu23 b2)\n         then match source (local_of nu12) m1 b2 ofs2 with\n             Some(b1,ofs1) =>\n                 if pubBlocksSrc nu12 b1 \n                 then ZMap.get ofs2 (PMap.get b2 CM) = \n                            inject_memval j12' \n                              (ZMap.get ofs1 (PMap.get b1 m1'.(Mem.mem_contents)))\n                 else ZMap.get ofs2 (PMap.get b2 CM) = \n                           ZMap.get ofs2 (PMap.get b2 m2.(Mem.mem_contents))   \n           | None => ZMap.get ofs2 (PMap.get b2 CM) =\n                     ZMap.get ofs2 (PMap.get b2 m2.(Mem.mem_contents))\n            end\n         else ZMap.get ofs2 (PMap.get b2 CM) =\n              ZMap.get ofs2 (PMap.get b2 m2.(Mem.mem_contents))\n    else match source (as_inj nu12) m1 b2 ofs2 with\n             Some(b1,ofs1) => ZMap.get ofs2 (PMap.get b2 CM) = \n                              inject_memval j12' \n                                (ZMap.get ofs1 (PMap.get b1 m1'.(Mem.mem_contents)))\n           | None => ZMap.get ofs2 (PMap.get b2 CM) = \n                     ZMap.get ofs2 (PMap.get b2 m2.(Mem.mem_contents))\n         end)\n  /\\ (~ Mem.valid_block m2 b2 -> forall ofs2,\n         match source j12' m1' b2 ofs2 with\n                None => ZMap.get ofs2 (PMap.get b2 CM) = Undef\n              | Some(b1,ofs1) =>\n                   ZMap.get ofs2 (PMap.get b2 CM) =\n                     inject_memval j12' \n                       (ZMap.get ofs1 (PMap.get b1 m1'.(Mem.mem_contents)))\n         end)\n   /\\ fst CM !! b2 = Undef.\n\nLemma effect_interp_OK: forall m1 m2 nu12 \n                             (MInj12 : Mem.inject (as_inj nu12) m1 m2) m1'\n                             (Fwd1: mem_forward m1 m1') nu23 m3\n                             (MInj23 : Mem.inject (as_inj nu23) m2 m3) m3'\n                             (Fwd3: mem_forward m3 m3')\n                              nu' (WDnu' : SM_wd nu')\n                             (SMvalNu' : sm_valid nu' m1' m3')\n                             (MemInjNu' : Mem.inject (as_inj nu') m1' m3')\n                             \n                             (ExtIncr: extern_incr (compose_sm nu12 nu23) nu')\n                             (SMInjSep: sm_inject_separated (compose_sm nu12 nu23) nu' m1 m3)\n                             (SMV12: sm_valid nu12 m1 m2)\n                             (SMV23: sm_valid nu23 m2 m3)\n                             (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc (compose_sm nu12 nu23) b = true /\\ \n                                                      pubBlocksSrc (compose_sm nu12 nu23) b = false) m1 m1') \n\n                             (UnchLOOR13: Mem.unchanged_on (local_out_of_reach (compose_sm nu12 nu23) m1) m3 m3')\n\n                             (GlueInvNu: SM_wd nu12 /\\ SM_wd nu23 /\\\n                                         locBlocksTgt nu12 = locBlocksSrc nu23 /\\\n                                         extBlocksTgt nu12 = extBlocksSrc nu23 /\\\n                                         (forall b, pubBlocksTgt nu12 b = true -> \n                                                    pubBlocksSrc nu23 b = true) /\\\n                                         (forall b, frgnBlocksTgt nu12 b = true -> \n                                                    frgnBlocksSrc nu23 b = true))\n                             (Norm12: forall b1 b2 d1, extern_of  nu12 b1 = Some(b2,d1) ->\n                                             exists b3 d2, extern_of nu23 b2 = Some(b3, d2))\n               prej12' j23' n1' n2'\n               (HeqMKI: mkInjections m1 m1' m2 (as_inj nu12) (as_inj nu23) (as_inj nu') = \n                            (prej12', j23', n1', n2'))\n               j12' (Hj12': j12'= removeUndefs (as_inj nu12) (as_inj nu') prej12')\n               m2'\n               (NB: m2'.(Mem.nextblock)=n2')\n               (CONT:  ContentEffProperty nu23 nu12 j12' m1 m1' m2 \n                                           (m2'.(Mem.mem_contents)))\n               (ACCESS: AccessEffProperty nu23 nu12 (*(as_inj nu23)*) j12' m1 m1' m2 \n                                               (m2'.(Mem.mem_access))),\n\n     Mem.unchanged_on (fun b ofs => locBlocksSrc nu23 b = true /\\ \n                                    pubBlocksSrc nu23 b = false) m2 m2' /\\\n     Mem.unchanged_on (local_out_of_reach nu12 m1) m2 m2' /\\\n(*     Mem.unchanged_on (local_out_of_reach nu23 m2) m3 m3' /\\*)\n     exists (nu12' nu23':SM_Injection), \n           nu12'  = (convertL nu12 (removeUndefs (as_inj nu12) (as_inj nu') prej12')\n                    (*FreshSrc:*) (fun b => andb (DomSrc nu' b) (negb (DomSrc nu12 b)))\n                    (*FreshMid:*) (FreshDom (as_inj nu23) j23'))\n       /\\ nu23' = (convertR nu23 j23'\n                      (*FreshMid:*) (FreshDom (as_inj nu23) j23')\n                      (*FreshTgt:*) (fun b => andb (DomTgt nu' b) (negb (DomTgt nu23 b))))\n                      /\\ nu'=compose_sm nu12' nu23' /\\\n                             extern_incr nu12 nu12' /\\ extern_incr nu23 nu23' /\\\n                             sm_inject_separated nu12 nu12' m1 m2 /\\ \n                             sm_inject_separated nu23 nu23' m2 m3 /\\\n                             sm_valid nu12' m1' m2' /\\ sm_valid nu23' m2' m3' /\\\n                             (SM_wd nu12' /\\ SM_wd nu23' /\\\n                              locBlocksTgt nu12' = locBlocksSrc nu23' /\\\n                              extBlocksTgt nu12' = extBlocksSrc nu23' /\\\n                              (forall b, pubBlocksTgt nu12' b = true -> \n                                         pubBlocksSrc nu23' b = true) /\\\n                              (forall b, frgnBlocksTgt nu12' b = true -> \n                                         frgnBlocksSrc nu23' b = true)) /\\\n                             (forall b1 b2 d1, extern_of nu12' b1 = Some(b2,d1) ->\n                                     exists b3 d2, extern_of nu23' b2 = Some(b3, d2)) /\\ \n                             mem_forward m2 m2' /\\\n                             Mem.inject (as_inj nu12') m1' m2' /\\\n                             Mem.inject (as_inj nu23') m2' m3'.\nProof. intros.\n  assert (VBj12_1: forall (b1 b2 : block) (ofs2 : Z),\n                   (as_inj nu12) b1 = Some (b2, ofs2) -> Mem.valid_block m1 b1).\n      intros. apply (Mem.valid_block_inject_1 _ _ _ _ _ _ H MInj12).\n  assert (VBj12_2: forall (b1 b2 : block) (ofs2 : Z),\n                   (as_inj nu12) b1 = Some (b2, ofs2) -> Mem.valid_block m2 b2).\n      intros. apply (Mem.valid_block_inject_2 _ _ _ _ _ _ H MInj12).\n  assert (VBj23_1: forall (b1 b2 : block) (ofs2 : Z),\n                   (as_inj nu23) b1 = Some (b2, ofs2) -> Mem.valid_block m2 b1).\n      intros. apply (Mem.valid_block_inject_1 _ _ _ _ _ _ H MInj23).\n  assert (VBj23_2: forall (b1 b2 : block) (ofs2 : Z),\n                   (as_inj nu23) b1 = Some (b2, ofs2) -> Mem.valid_block m3 b2).\n      intros. apply (Mem.valid_block_inject_2 _ _ _ _ _ _ H MInj23).\n  assert (VB12: forall (b3 b4 : block) (ofs3 : Z), \n                 (as_inj nu12) b3 = Some (b4, ofs3) -> \n                (b3 < Mem.nextblock m1 /\\ b4 < Mem.nextblock m2)%positive).\n      intros. split. apply (VBj12_1 _ _ _ H). apply (VBj12_2 _ _ _ H).\n  assert (preinc12:= mkInjections_1_injinc _ _ _ _ _ _ _ _ _ _ HeqMKI VBj12_1).\n  assert (inc12:= inc_RU _ _ preinc12 (as_inj nu')).\n  assert (presep12:= mkInjections_1_injsep _ _ _ _ _ _ _ _ _ _ HeqMKI).\n  assert (sep12: inject_separated (as_inj nu12) (removeUndefs (as_inj nu12) (as_inj nu') prej12') m1 m2).\n       intros b; intros. eapply presep12. apply H. \n       eapply RU_D. apply preinc12. apply H0.\n  assert (InjIncr: inject_incr (compose_meminj (as_inj nu12) (as_inj nu23)) (as_inj nu')).\n    subst. eapply extern_incr_inject_incr; eassumption. \n  assert (InjSep: inject_separated (compose_meminj (as_inj nu12) (as_inj nu23)) (as_inj nu') m1 m3).\n    subst. clear CONT ACCESS HeqMKI.\n    apply sm_inject_separated_mem in SMInjSep.  \n    rewrite compose_sm_as_inj in SMInjSep.\n      assumption.\n      eapply GlueInvNu.\n      eapply GlueInvNu.\n      eapply GlueInvNu.\n      eapply GlueInvNu.\n      assumption.\n  assert (inc23:= mkInjections_2_injinc _ _ _ _ _ _ _ _ _ _ HeqMKI VBj23_1).\n  assert (sep23:= mkInjections_2_injsep _ _ _ _ _ _ _ _ _ _ HeqMKI \n                  VBj12_1 _ InjSep).\n  assert (NB1:= forward_nextblock _ _ Fwd1).\n  assert (XX: n1' = Mem.nextblock m1'). \n    destruct (mkInjections_0  _ _ _ _ _ _ _ _ _ _ HeqMKI)\n      as [[NN [N1 [N2 [JJ1 JJ2]]]] | [n [NN [N1 [N2 N3]]]]].\n    subst. eapply Pos.le_antisym; assumption. assumption.\n subst.\n  assert (VBj': forall b1 b3 ofs3, (as_inj nu') b1 = Some (b3, ofs3) -> \n                (b1 < Mem.nextblock m1')%positive).\n      intros. apply (Mem.valid_block_inject_1 _ _ _ _ _ _ H MemInjNu').\n  assert (ID:= RU_composememinj _ _ _ _ _ _ _ _ _ _ HeqMKI \n               InjIncr _ InjSep VBj12_1 VBj12_2 VBj23_1 VBj').\ndestruct GlueInvNu as [WDnu12 [WDnu23 [GlueLoc [GlueExt [GluePub GlueFrgn]]]]].\nassert (Fwd2: mem_forward m2 m2').\n  split; intros; rename b into b2.\n  (*valid_block*)\n     clear - H NB1 HeqMKI. unfold Mem.valid_block in *.\n     destruct (mkInjections_0 _ _ _ _ _ _ _ _ _ _ HeqMKI)\n     as [HH | HH].\n       destruct HH as [_ [_ [XX _]]]. rewrite XX in H. assumption.\n       destruct HH as [n [NN [_ [_ X]]]]. rewrite <- X.\n        xomega. \n  (*max*)\n     destruct (ACCESS b2) as [Val2 _].\n     specialize (Val2 H Max ofs).\n     remember (locBlocksSrc nu23 b2) as d.\n     destruct d; apply eq_sym in Heqd.\n     (*case locBlocksSrc nu23 b2 = false*)\n       remember (pubBlocksSrc nu23 b2) as q.\n       destruct q; apply eq_sym in Heqq.\n         remember (source (local_of nu12) m1 b2 ofs) as src.\n         destruct src.\n           apply source_SomeE in Heqsrc.\n           destruct Heqsrc as [b1 [delta [ofs1 [PBO [ValB1 [J1 [P1 Off2]]]]]]].\n           subst.\n           remember (pubBlocksSrc nu12 b1) as w.\n           destruct w; \n             rewrite (perm_subst _ _ _ _ _ _ _ Val2) in H0; clear Val2; trivial.\n           eapply MInj12.\n             apply local_in_all; eassumption.\n             eapply Fwd1.\n               apply ValB1.\n               apply H0. \n         rewrite (perm_subst _ _ _ _ _ _ _ Val2) in H0; apply H0.\n       rewrite (perm_subst _ _ _ _ _ _ _ Val2) in H0; apply H0.\n     (*case locBlocksSrc nu23 b2 = false*)\n       remember (source (as_inj nu12) m1 b2 ofs) as src.\n       destruct src.\n         apply source_SomeE in Heqsrc.\n         destruct Heqsrc as [b1 [delta [ofs1 [PBO [Bounds [J1 [P1 Off2]]]]]]].\n         subst.\n         rewrite (perm_subst _ _ _ _ _ _ _ Val2) in H0; clear Val2.\n         eapply MInj12. apply J1. \n           eapply Fwd1.\n             apply Bounds.\n             apply H0. \n       remember (as_inj nu23 b2) as jb.\n         destruct jb; apply eq_sym in Heqjb.\n           destruct p0.\n           unfold Mem.perm in H0. rewrite Val2 in H0. simpl in H0. contradiction.\n         rewrite (perm_subst _ _ _ _ _ _ _ Val2) in H0; clear Val2. apply H0.\n       \n(*First unchOn condition - corresponds to UnchLOM2 loc_unmapped.*)\nassert (UNCHA: Mem.unchanged_on\n  (fun (b : block) (_ : Z) =>\n   locBlocksSrc nu23 b = true /\\ pubBlocksSrc nu23 b = false) m2 m2').\n split; intros. rename b into b2. rename H0 into ValB2.\n        destruct H as [locBSrc pubBSrc].\n        destruct (ACCESS b2) as [Val _].\n        specialize (Val ValB2 k ofs).\n        rewrite locBSrc, pubBSrc in Val.\n        rewrite (perm_subst _ _ _ _ _ _ _ Val). split; auto. \n  apply (cont_split _ _ _ _ _ (CONT b)); intros; clear CONT.\n      (*case Mem.valid_block m2 b*)\n          specialize (H2 ofs).\n          destruct H as [locBSrc pubBSrc].\n          rewrite locBSrc, pubBSrc in H2. simpl in H2.\n          apply H2.\n      (*case invalid*)\n          apply Mem.perm_valid_block in H0. contradiction.\nsplit; trivial.\nassert (UNCHB: Mem.unchanged_on (local_out_of_reach nu12 m1) m2 m2'). \n (*Second unchOn condition - corresponds to Unch2*)\n  split; intros. rename b into b2. rename H0 into ValB2. \n     destruct H as [locTgt2 HP].\n     destruct (ACCESS b2) as [Val _].\n     specialize (Val ValB2 k ofs).\n     remember (locBlocksSrc nu23 b2) as d.\n     destruct d; apply eq_sym in Heqd.\n     (*case locBlocksSrc nu23 b2 = true*)\n       remember (pubBlocksSrc nu23 b2) as q.\n       destruct q; apply eq_sym in Heqq.\n       (*case pubBlocksSrc nu23 b2 = true*)\n          remember (source (local_of nu12) m1 b2 ofs) as ss.\n          destruct ss.\n            destruct p0.\n            destruct (source_SomeE _ _ _ _ _ Heqss)\n               as [b1 [d1 [ofs1 [PP [VB [JJ [PERM Off2]]]]]]]; clear Heqss.\n            subst. apply eq_sym in PP. inv PP.\n            remember (pubBlocksSrc nu12 b) as w.\n            destruct w; apply eq_sym in Heqw;\n              rewrite (perm_subst _ _ _ _ _ _ _ Val); clear Val.\n              destruct (HP _ _ JJ).  \n                assert (Arith: z + d1 - d1 = z) by omega. \n                rewrite Arith in H. contradiction.\n              rewrite H in Heqw. discriminate.\n            split; intros; trivial.\n          rewrite (perm_subst _ _ _ _ _ _ _ Val); clear Val.\n             split; intros; trivial.\n       (*case pubBlocksSrc nu23 b2 = false*)\n          rewrite (perm_subst _ _ _ _ _ _ _ Val); clear Val.\n             solve[split; intros; trivial].\n     (*case locBlocksSrc nu23 b2 = false*)\n        rewrite GlueLoc in locTgt2. rewrite locTgt2 in Heqd. discriminate.\n  destruct H as [locTgt2 HP]. rename b into b2.\n  apply (cont_split _ _ _ _ _ (CONT b2)); intros; clear CONT.\n  (* case Mem.valid_block m2 b*)\n          specialize (H1 ofs).\n          assert (locSrc2: locBlocksSrc nu23 b2 = true).\n            rewrite GlueLoc in locTgt2. assumption.\n          rewrite locSrc2 in *.\n          remember (pubBlocksSrc nu23 b2) as d.\n          destruct d; apply eq_sym in Heqd.\n          (*case pubBlocksSrc nu23 b2 = true*)\n            remember (source (local_of nu12) m1 b2 ofs) as ss.\n            destruct ss.\n              destruct p.\n              destruct (source_SomeE _ _ _ _ _ Heqss)\n               as [b1 [d1 [ofs1 [PP [VB [JJ [PERM Off2]]]]]]]; clear Heqss.\n              subst. inv PP.\n              destruct (HP _ _ JJ); clear HP.\n                 assert (Arith : ofs1 + d1 - d1 = ofs1) by omega. \n                 rewrite Arith in H3. contradiction.\n              rewrite H3 in H1. trivial.\n            apply H1.\n          (*case pubBlocksSrc nu23 b2 = true*)\n            apply H1.\n       (*invalid*)\n          exfalso. \n          apply Mem.perm_valid_block in H0. contradiction.\nsplit; trivial.\n\nassert (UNCHC: Mem.unchanged_on (local_out_of_reach nu23 m2) m3 m3').\n  (*third UnchOn condition - corresponds to UnchLOOR3*)\n   clear - UnchLOOR13 WDnu12 GluePub MInj12.\n   unfold local_out_of_reach.\n   split; intros; rename b into b3.\n      destruct H as[locTgt3 LOOR23].\n      eapply UnchLOOR13; trivial; simpl. \n        split; trivial.\n        intros b1; intros; simpl in *.\n        remember (pubBlocksSrc nu12 b1) as d.\n        destruct d; try (right; reflexivity).\n        left. apply eq_sym in Heqd.\n        destruct (compose_meminjD_Some _ _ _ _ _ H)\n          as [b2 [d1 [d2 [LOC1 [LOC2 D]]]]]; subst; clear H.\n        destruct (pubSrc _ WDnu12 _ Heqd) as [bb2 [dd1 [Pub12 PubTgt2]]].\n        rewrite (pub_in_local _ _ _ _ Pub12) in LOC1. inv LOC1.\n        apply GluePub in PubTgt2.\n        destruct (LOOR23 _ _ LOC2); clear LOOR23.\n          intros N. apply H.\n          assert (Arith : ofs - (d1 + d2) + d1 = ofs - d2) by omega.\n          rewrite <- Arith.\n          eapply MInj12. eapply pub_in_all; try eassumption. apply N.\n        rewrite H in PubTgt2. discriminate.\n   destruct H as[locTgt3 LOOR23].\n      eapply UnchLOOR13; trivial; simpl. \n        split; trivial.\n        intros b1; intros; simpl in *.\n        remember (pubBlocksSrc nu12 b1) as d.\n        destruct d; try (right; reflexivity).\n        left. apply eq_sym in Heqd.\n        destruct (compose_meminjD_Some _ _ _ _ _ H)\n          as [b2 [d1 [d2 [LOC1 [LOC2 D]]]]]; subst; clear H.\n        destruct (pubSrc _ WDnu12 _ Heqd) as [bb2 [dd1 [Pub12 PubTgt2]]].\n        rewrite (pub_in_local _ _ _ _ Pub12) in LOC1. inv LOC1.\n        apply GluePub in PubTgt2.\n        destruct (LOOR23 _ _ LOC2); clear LOOR23.\n          intros N. apply H.\n          assert (Arith : ofs - (d1 + d2) + d1 = ofs - d2) by omega.\n          rewrite <- Arith.\n          eapply MInj12. eapply pub_in_all; try eassumption. apply N.\n        rewrite H in PubTgt2. discriminate.\n(*split; trivial.*)\nassert (VBj23': forall b2 b3 d2, j23' b2 = Some(b3,d2) -> Mem.valid_block m2' b2).\n    assert (Val2: forall b2 b3 d2, as_inj nu23 b2 = Some(b3,d2) -> Mem.valid_block m2 b2).\n       intros. eapply SMV23. eapply as_inj_DomRng; eassumption.\n    intros.\n    destruct (mkInjections_4Val _ _ _ _ _ _ _ _ _ _ HeqMKI Val2 _ _ _ H) as [MK | [MK | MK]].\n       destruct MK. apply Fwd2. apply H1.\n       destruct MK. subst. apply H1.\n       destruct MK as [m Hm]; subst. apply Hm.\nassert (Val12: (forall (b1 b2 : block) (ofs2 : Z),\n  as_inj nu12 b1 = Some (b2, ofs2) ->\n  (b1 < Mem.nextblock m1)%positive /\\ (b2 < Mem.nextblock m2)%positive)).\n   intros. split; eapply SMV12. eapply as_inj_DomRng; eassumption.\n                eapply as_inj_DomRng; eassumption.\nassert (Val23: (forall (b2 b3 : block) (ofs3 : Z),\n  as_inj nu23 b2 = Some (b3, ofs3) -> (b2 < Mem.nextblock m2)%positive)).\n   intros. eapply SMV23. eapply as_inj_DomRng; eassumption.\nassert (NOVj12':= RU_no_overlap _ _ _ MInj12 _ Fwd1 _ _ \n                  MInj23 _ _ _ _ _ HeqMKI).\nexists (convertL nu12 (removeUndefs (as_inj nu12) (as_inj nu') prej12')\n          (*FreshSrc:*) (fun b => andb (DomSrc nu' b) (negb (DomSrc nu12 b)))\n          (*FreshMid:*) (FreshDom (as_inj nu23) j23')).\nexists (convertR nu23 j23'\n          (*FreshMid:*) (FreshDom (as_inj nu23) j23')\n          (*FreshTgt:*) (fun b => andb (DomTgt nu' b) (negb (DomTgt nu23 b)))).\nsplit; trivial.\nsplit; trivial.\nremember (removeUndefs (as_inj nu12) (as_inj nu') prej12') as j12'.\nassert (ConvertL_J12': \n    as_inj\n     (convertL nu12 j12'\n        (fun b : block => DomSrc nu' b && negb (DomSrc nu12 b))\n        (FreshDom (as_inj nu23) j23')) = j12').\n    extensionality b.\n    intros. unfold as_inj.\n     rewrite convertL_extern, convertL_local.\n     remember (j12' b) as d.\n     destruct d; apply eq_sym in Heqd.\n       destruct p. unfold join.\n       remember (extern_of nu12 b) as q.\n       destruct q; apply eq_sym in Heqq.\n         destruct p. apply extern_in_all in Heqq.\n            rewrite (inc12 _ _ _ Heqq) in Heqd. apply Heqd.\n       remember (local_of nu12 b) as w.\n       destruct w; apply eq_sym in Heqw.\n         destruct p. \n         apply local_in_all in Heqw.\n            rewrite (inc12 _ _ _ Heqw) in Heqd. apply Heqd.\n            assumption.\n      rewrite Heqd. trivial.\n     assert (A:= inject_incr_inv _ _ inc12 _ Heqd).\n       destruct (joinD_None _ _ _ A).\n       unfold join. rewrite H, H0, Heqd. trivial.\nrewrite ConvertL_J12' in *.\n rewrite convertL_extern, convertL_frgnBlocksTgt, \n         convertL_pubBlocksTgt, convertL_locBlocksTgt, \n         convertL_extBlocksTgt.\nassert (Inj12': Mem.inject j12' m1' m2'). \n    clear ConvertL_J12'.\n    assert (Perm12': forall b1 b2 delta ofs k p,\n             j12' b1 = Some (b2, delta) ->\n             Mem.perm m1' b1 ofs k p -> Mem.perm m2' b2 (ofs + delta) k p).\n        intros.\n        apply (valid_split _ _ _ _ (ACCESS b2)); intros; clear ACCESS.\n        (*case valid_block m2 b2*)\n          specialize (H2 k (ofs+delta)).\n          remember (as_inj nu12 b1) as AsInj1.\n          destruct AsInj1; apply eq_sym in HeqAsInj1.\n          Focus 2. clear H2. destruct (sep12 _ _ _ HeqAsInj1 H).\n                   contradiction.  \n          destruct p0.\n          rewrite (inc12 _ _ _ HeqAsInj1) in H.  inv H.\n          assert (Val_b1:= VBj12_1 _ _ _ HeqAsInj1). \n          assert (PMAX: Mem.perm m1 b1 ofs Max Nonempty).\n                    apply Fwd1. assumption.\n                    eapply Mem.perm_implies. eapply Mem.perm_max. \n                               apply H0. apply perm_any_N.\n          remember (locBlocksSrc nu23 b2) as Locb2.\n          destruct Locb2; apply eq_sym in HeqLocb2.\n          (*case locBlocksSrc nu23 b2 = true*)\n            (*First, establish that local_of nu12 b1 = Some (b2, delta) etc*)\n            destruct (joinD_Some _ _ _ _ _ HeqAsInj1) as [EXT12 | [NoEXT12 LOC12]].\n              destruct (extern_DomRng _ WDnu12 _ _ _ EXT12) as [? ?].\n              rewrite GlueExt in H3.\n              destruct (disjoint_extern_local_Src _ WDnu23 b2); congruence.\n            destruct (local_DomRng _ WDnu12 _ _ _ LOC12) as [locBSrc1 locBTgt2].\n            assert (NOV_LocNu12: Mem.meminj_no_overlap (local_of nu12) m1).\n               eapply meminj_no_overlap_inject_incr.\n                 apply MInj12. apply local_in_all; assumption.               \n            remember (pubBlocksSrc nu23 b2) as PubB2.\n            destruct PubB2; apply eq_sym in HeqPubB2.\n            (*case pubBlocksSrc nu23 b2 = true*)\n              remember (pubBlocksSrc nu12 b1) as PubSrcb1.\n              destruct PubSrcb1; apply eq_sym in HeqPubSrcb1.\n              (*case pubBlocksSrc nu12 b1 = true*)\n                destruct (pubSrc _ WDnu12 _  HeqPubSrcb1) as [bb2 [dd1 [PUB12 TGT2]]].\n                rewrite (pub_in_local _ _ _ _ PUB12) in LOC12. inv LOC12.\n                rewrite (source_SomeI (local_of nu12) _  _ b1) in H2; trivial.\n                  rewrite HeqPubSrcb1 in *.\n                  rewrite (perm_subst _ _ _ _ _ _ _ H2). apply H0.\n                  apply pub_in_local; assumption.\n              (*case pubBlocksSrc nu12 b1 = false*)\n                assert (PK: Mem.perm m1 b1 ofs k p).\n                  eapply UnchPrivSrc.\n                    simpl. split; assumption.\n                    assumption.\n                    assumption.\n                rewrite (source_SomeI (local_of nu12) _  _ b1) in H2; trivial.     \n                rewrite HeqPubSrcb1 in H2.\n                rewrite (perm_subst _ _ _ _ _ _ _ H2); clear H2.\n                eapply MInj12; eassumption. \n            (*case pubBlocksSrc nu23 b2 = false*)\n               rewrite (perm_subst _ _ _ _ _ _ _ H2); clear H2.\n               eapply MInj12. apply local_in_all; eassumption.\n               eapply UnchPrivSrc; simpl; trivial.\n               split; trivial.\n               remember (pubBlocksSrc nu12 b1) as q.\n               destruct q; trivial.\n               apply eq_sym in Heqq.\n               destruct (pubSrc _ WDnu12 _ Heqq) as [bb2 [dd1 [PUB12 Pub2]]].\n               apply pub_in_local in PUB12. rewrite PUB12 in LOC12. inv LOC12.\n               apply GluePub in Pub2. rewrite Pub2 in HeqPubB2; discriminate.\n          (*case locBlocksSrc nu23 b2 = false*)\n             destruct (joinD_Some _ _ _ _ _ HeqAsInj1) as [EXT1 | [NoEXT1 LOC1]].\n             Focus 2. destruct (local_DomRng _ WDnu12 _ _ _ LOC1).\n                      rewrite GlueLoc in H3. congruence. \n             destruct (extern_DomRng _ WDnu12 _ _ _ EXT1) as [HeqLocb1 HeqExtTgtb2].\n             remember (source (as_inj nu12) m1 b2 (ofs + delta)) as ss.\n             destruct ss.\n             (*case source = Some*)\n               destruct (source_SomeE _ _ _ _ _ Heqss)\n                 as [bb1 [dd1 [ofs11 [PP [VB [ JJ [PERM Off2]]]]]]].\n               clear Heqss. subst.       \n               rewrite (perm_subst _ _ _ _ _ _ _ H2); clear H2.\n               destruct (eq_block bb1 b1); subst.\n                 rewrite JJ in HeqAsInj1. inv HeqAsInj1.  \n                 assert (Arith: ofs11 = ofs) by omega. \n                 subst; assumption.\n              destruct (Mem.mi_no_overlap _ _ _ MInj12\n                           bb1 _ _ _ _ _ _ _ n JJ HeqAsInj1 PERM PMAX).\n                exfalso. apply H; trivial. \n                exfalso. apply H. rewrite Off2. trivial.\n             (*case source = None*)\n               remember (as_inj nu23 b2) as AsInj2.\n               destruct AsInj2; apply eq_sym in HeqAsInj2.\n               (*case as_inj nu23 b2 = Some(..)*)\n                 destruct p0 as [b3 d2].                \n                 exfalso.\n                 eapply (source_NoneE _ _ _ _ Heqss _ \n                        _ Val_b1 HeqAsInj1).\n                 assert (Arith: ofs + delta - delta = ofs) by omega.\n                 rewrite Arith. apply PMAX.\n               (*case as_inj nu23 b2 = None*)\n                  rewrite (perm_subst _ _ _ _ _ _ _ H2); clear H2.\n                  remember (frgnBlocksSrc nu23 b2) as FrgnSrc2.\n                  destruct FrgnSrc2; apply eq_sym in HeqFrgnSrc2.\n                    destruct (frgnSrc _ WDnu23 _ HeqFrgnSrc2) as [b3 [d2 [FRG2 FrgTgt3]]].\n                    rewrite (foreign_in_all _ _ _ _ FRG2) in HeqAsInj2. inv HeqAsInj2.\n                  remember (frgnBlocksSrc nu12 b1) as FrgnSrc1.\n                  destruct FrgnSrc1; apply eq_sym in HeqFrgnSrc1.\n                    destruct (frgnSrc _ WDnu12 _ HeqFrgnSrc1) as [bb2 [dd1 [FRG1 FrgTgt2]]].\n                    rewrite (foreign_in_extern _ _ _ _ FRG1) in EXT1. inv EXT1.\n                    apply GlueFrgn in FrgTgt2. rewrite FrgTgt2 in HeqFrgnSrc2. inv HeqFrgnSrc2.\n                 (*case frgnBlocksSrc nu12 b1 = frgnBlocksSrc nu23 b2 = false*)                    \n                   exfalso.\n                   eapply (source_NoneE _ _ _ _ Heqss _ \n                        _ Val_b1 HeqAsInj1).\n                   assert (Arith: ofs + delta - delta = ofs) by omega.\n                   rewrite Arith. apply PMAX. \n        (*case ~ valid_block m2 b2*)\n            specialize (H2 k (ofs+delta)).\n            rewrite (source_SomeI j12' _  _ b1) in H2.\n              rewrite (perm_subst _ _ _ _ _ _ _ H2). apply H0.\n              subst. apply (RU_no_overlap _ _ _ MInj12 _ Fwd1 _ _ \n                    MInj23 _ _ _ _ _ HeqMKI).\n              assumption.\n              eapply Mem.perm_implies. eapply Mem.perm_max. \n                    apply H0. apply perm_any_N.\n    assert (INJ:Mem.mem_inj j12' m1' m2'). \n      split. apply Perm12'.\n      (*valid_access*) \n          intros. rewrite Heqj12' in H.\n          clear Heqj12'.\n          unfold removeUndefs in H.\n          remember (as_inj nu12 b1) as d.\n          destruct d; apply eq_sym in Heqd.\n            destruct p0 as [bb2 dd]. inv H.\n            eapply MInj12. eassumption.\n            assert (MR: Mem.range_perm m1 b1 ofs (ofs + size_chunk chunk) Max p).\n               intros z. intros. specialize (H0 _ H).\n               eapply Fwd1. eapply VBj12_1. apply Heqd. apply H0.\n               eassumption.\n          remember (as_inj nu' b1) as q.\n          destruct q; apply eq_sym in Heqq; try inv H.\n          destruct p0.\n            destruct (mkInjections_3V _ _ _ _ _ _ _ _ _ _ \n                      HeqMKI VB12 VBj23_1 _ _ _ H2)\n            as [HX | [HX | HX]].\n              destruct HX as [J12 [Val1 Val2]]. rewrite J12 in Heqd. inv Heqd. \n              destruct HX as [? [? [? [? D]]]]. subst. apply Z.divide_0_r.\n              destruct HX as [? [? [? [? [? D]]]]]. subst. apply Z.divide_0_r.  \n      (*memval  j12' m1' m2'.*)\n          intros. \n          apply (cont_split _ _ _ _ _ (CONT b2)); intros; clear CONT.\n         (*case Mem.valid_block m2 b2*)\n            specialize (H2 (ofs + delta)).\n            remember (as_inj nu12 b1) as AsInj1.\n            destruct AsInj1; apply eq_sym in HeqAsInj1.\n            Focus 2. clear H2. destruct (sep12 _ _ _ HeqAsInj1 H).\n                     contradiction.  \n            destruct p.\n            rewrite (inc12 _ _ _ HeqAsInj1) in H.  inv H.\n            assert (Val_b1:= VBj12_1 _ _ _ HeqAsInj1). \n            assert (PMAX: Mem.perm m1 b1 ofs Max Nonempty).\n                    apply Fwd1. assumption.\n                    eapply Mem.perm_implies. eapply Mem.perm_max. \n                               apply H0. apply perm_any_N.\n            remember (locBlocksSrc nu23 b2) as Myb2.\n            destruct Myb2; apply eq_sym in HeqMyb2.\n            (*case locBlocksSrc nu23 b2 = true*)\n              (*First, establish that local_of nu12 b1 = Some (b2, delta) etc*)\n              destruct (joinD_Some _ _ _ _ _ HeqAsInj1) as [EXT12 | [NoEXT12 LOC12]].\n                destruct (extern_DomRng _ WDnu12 _ _ _ EXT12) as [? ?].\n                rewrite GlueExt in H4.\n                destruct (disjoint_extern_local_Src _ WDnu23 b2); congruence.\n              destruct (local_DomRng _ WDnu12 _ _ _ LOC12) as [locBSrc1 locBTgt2].\n              remember (pubBlocksSrc nu23 b2) as PubB2.\n              destruct PubB2; apply eq_sym in HeqPubB2.\n              (*case pubBlocksSrc nu23 b2 = true*)\n                destruct (pubSrc _ WDnu23 _ HeqPubB2) as [b3 [d2 [Pub23 PubTgt3]]].\n                assert (AsInj23: as_inj nu23 b2 = Some (b3, d2)) by (apply pub_in_all; assumption).\n                assert (NOVlocal12: Mem.meminj_no_overlap (local_of nu12) m1).\n                  eapply meminj_no_overlap_inject_incr.\n                  apply MInj12. apply local_in_all; assumption.\n                rewrite (source_SomeI (local_of nu12) _  _ b1) in H2; trivial.\n                remember (pubBlocksSrc nu12 b1) as PubSrcb1.\n                destruct PubSrcb1; apply eq_sym in HeqPubSrcb1; rewrite H2; clear H2.\n                (*case pubBlocksSrc nu12 b1 = true*)\n                  destruct (pubSrc _ WDnu12 _  HeqPubSrcb1) as [bb2 [dd1 [PUB12 TGT2]]].\n                  rewrite (pub_in_local _ _ _ _ PUB12) in LOC12. inv LOC12.\n                  assert (Nu'b1: as_inj nu' b1 = Some (b3, delta+d2)).\n                      rewrite ID. eapply compose_meminjI_Some; try eassumption.\n                             apply inc12. eassumption. apply (inc23 _ _ _ AsInj23). \n                  assert (MV:= Mem.mi_memval _ _ _\n                                 (Mem.mi_inj _ _ _ MemInjNu') _ _ _ _ Nu'b1 H0).\n                  inv MV; try constructor. \n                           simpl. \n                           rewrite ID in H4.\n                           destruct (compose_meminjD_Some _ _ _ _ _ H4)\n                              as [bb2 [dd1 [dd2 [JJ1 [JJ2 Delta]]]]].\n                           rewrite JJ1. econstructor. \n                             apply JJ1. reflexivity.\n               (*case pubBlocksSrc nu12 b1 = false*)\n                  assert (PK: Mem.perm m1 b1 ofs Cur Readable).\n                    solve[eapply UnchPrivSrc; eauto].\n                  destruct UnchPrivSrc as [_ UPS].\n                  rewrite UPS; try assumption; try (split; assumption).\n                  eapply memval_inject_incr.\n                    apply MInj12; assumption.\n                    apply inc12.\n              (*case pubBlocksSrc nu23 b2 = false*)\n                rewrite H2; clear H2.\n                remember (pubBlocksSrc nu12 b1) as PubSrcb1.\n                destruct PubSrcb1; apply eq_sym in HeqPubSrcb1.\n                  destruct (pubSrc _ WDnu12 _  HeqPubSrcb1) as [bb2 [dd1 [PUB12 TGT2]]].\n                  rewrite (pub_in_local _ _ _ _ PUB12) in LOC12. inv LOC12.\n                  apply GluePub in TGT2. rewrite TGT2 in HeqPubB2. inv HeqPubB2.\n                (*as the b1 is not public we can again aply Unch11*)\n                assert (PK: Mem.perm m1 b1 ofs Cur Readable).\n                  solve [eapply UnchPrivSrc; eauto].\n                destruct UnchPrivSrc as [_ UPS].\n                  rewrite UPS; try assumption; try (split; assumption).\n                  eapply memval_inject_incr.\n                    apply MInj12; assumption.\n                    apply inc12.\n            (*case locBlocksSrc nu23 b2 = false*)\n              rewrite (source_SomeI (as_inj nu12) _  _ b1) in H2; try eassumption. \n                   Focus 2. eapply MInj12.\n              rewrite H2; clear H2.\n              assert (EXT1: extern_of nu12 b1 = Some (b2, delta)).\n                destruct (joinD_Some _ _ _ _ _ HeqAsInj1); trivial.\n                destruct H.\n                destruct (local_DomRng _ WDnu12 _ _ _ H2).\n                rewrite GlueLoc in H5. congruence. \n              destruct (Norm12 _ _ _ EXT1) as [b3 [d2 EXT2]]. \n               assert (Nu'b1: as_inj nu' b1 = Some (b3, delta+d2)).\n                      rewrite ID. eapply compose_meminjI_Some; try eassumption.\n                             apply inc12. eassumption. \n                             apply inc23. apply (extern_in_all _ _ _ _ EXT2).\n                  assert (MV:= Mem.mi_memval _ _ _\n                                 (Mem.mi_inj _ _ _ MemInjNu') _ _ _ _ Nu'b1 H0).\n                  inv MV; try constructor. \n                           simpl. \n                           rewrite ID in H4.\n                           destruct (compose_meminjD_Some _ _ _ _ _ H4)\n                              as [bb2 [dd1 [dd2 [JJ1 [JJ2 Delta]]]]].\n                           rewrite JJ1. econstructor. \n                             apply JJ1. reflexivity.\n         (*case ~ Mem.valid_block m2 b2*)\n            specialize (H2 (ofs + delta)).\n            assert (J12: as_inj nu12 b1 = None).\n               remember (as_inj nu12 b1) as d. \n               destruct d; apply eq_sym in Heqd; trivial.\n                     destruct p. rewrite (inc12 _ _ _ Heqd) in H. inv H.\n                     exfalso. apply H1. apply (VBj12_2 _ _ _ Heqd).\n            assert (MX: Mem.perm m1' b1 ofs Max Nonempty).\n                  eapply Mem.perm_max. eapply Mem.perm_implies.\n                  apply H0. apply perm_any_N.\n            rewrite (source_SomeI _ _  _ b1) in H2; try eassumption.\n            rewrite H2; clear H2.\n            remember (ZMap.get ofs (PMap.get b1 (Mem.mem_contents m1'))) as v.\n            remember (j23' b2) as j23'b2.\n                   destruct j23'b2; apply eq_sym in Heqj23'b2.\n                   (*j23' b2 = Some p*)\n                       destruct p as [b3 delta3].\n                       assert (COMP': as_inj nu' b1 = Some(b3, delta+delta3)).\n                            rewrite ID. eapply compose_meminjI_Some; eassumption.\n                       assert (MV:= Mem.mi_memval _ _ _ \n                           (Mem.mi_inj _ _ _ MemInjNu') _ _  _ _ COMP' H0).\n                       subst.\n                       inv MV; try constructor. \n                       simpl. rewrite ID in H5. \n                       apply compose_meminjD_Some in H5.\n                       destruct H5 as [bb1 [off1 [off [JJ1 [JJ2 Delta]]]]].\n                       subst. \n                       rewrite JJ1. econstructor. apply JJ1. trivial.\n                   (*j23' b2 = None - we do a slightly different proof than in interp6 mem_interpolationII etc*)\n                       subst.\n                       unfold removeUndefs in H. rewrite J12 in H.\n                       remember (as_inj nu' b1) as d.\n                       destruct d; try inv H. \n                       destruct p.\n                       assert (VB2: Mem.valid_block m2' b2).\n                           destruct (mkInjections_0 _ _ _ _ _ _ _ _ _ _ HeqMKI) as [XX | XX].\n                             destruct XX as [? [? [? [? ?]]]]. subst. rewrite J12 in H4. discriminate.\n                             destruct XX as [nn [? [? [? ?]]]]. \n                               destruct (mkInjections_3 _ _ _ _ _ _ _ _ _ _ HeqMKI _ _ _ H4) as [XX | [XX | XX]].\n                                 rewrite XX in J12; discriminate.\n                                 destruct XX as [? [? ?]]; subst. unfold Mem.valid_block. rewrite <- H6. xomega.\n                                 destruct XX as [mm [[? ?] ?]]; subst.\n                                 assert (Mem.valid_block m1' (Mem.nextblock m1 + mm)%positive).\n                                   eapply VBj'. rewrite <- Heqd. reflexivity.\n                                 clear - H2 H6 H7. unfold Mem.valid_block in *.\n                                     rewrite <- H6. rewrite <- H2 in H7. clear H2 H6. xomega.\n                       destruct (mkInjections_5 _ _ _ _ _ _ _ _ _ _ HeqMKI VBj12_1 VBj12_2 VBj23_1 VBj' _ VB2 Heqj23'b2) as [[XXa XXb] | [[XXa XXb] | [nn [XXa XXb]]]].\n                         contradiction.\n                         assert (b1 = Mem.nextblock m1).\n                           destruct (mkInjections_0 _ _ _ _ _ _ _ _ _ _ HeqMKI) as [ZZ | ZZ].\n                             destruct ZZ as [? [? [? [? ?]]]]. subst. rewrite J12 in H4. discriminate.\n                             destruct ZZ as [nn [? [? [? ?]]]]. subst. \n                               destruct (mkInjections_3 _ _ _ _ _ _ _ _ _ _ HeqMKI _ _ _ H4) as [AA | [AA | AA]].\n                                 rewrite AA in J12; discriminate.\n                                 destruct AA as [? [? ?]]; subst. trivial.\n                                 destruct AA as [mm [[? ?] ?]]; subst. clear - H8. exfalso. rewrite Pos.add_comm in H8. apply eq_sym in H8. eapply Pos.add_no_neutral. apply H8.\n                           subst. rewrite XXb in Heqd. discriminate. \n                         assert (b1 = (Mem.nextblock m1 + nn)%positive). clear Heqd.\n                           destruct (mkInjections_0 _ _ _ _ _ _ _ _ _ _ HeqMKI) as [ZZ | ZZ].\n                             destruct ZZ as [? [? [? [? ?]]]]. subst. rewrite J12 in H4. discriminate.\n                             destruct ZZ as [kk [? [? [? ?]]]]. subst. \n                               destruct (mkInjections_3 _ _ _ _ _ _ _ _ _ _ HeqMKI _ _ _ H4) as [AA | [AA | AA]].\n                                 rewrite AA in J12; discriminate.\n                                 destruct AA as [? [? ?]]; subst. clear - H8. exfalso. rewrite Pos.add_comm in H8. eapply Pos.add_no_neutral. apply H8.\n                                 destruct AA as [mm [[? ?] ?]]; subst.\n                                    assert (nn=mm); subst; trivial. clear - H8. eapply Pos.add_reg_l. eassumption.\n                           subst. rewrite XXb in Heqd. discriminate. \n   split. apply INJ.\n   (* mi_freeblocks*)  intros b1 Hb1. \n        remember (j12' b1) as d.\n        destruct d; apply eq_sym in Heqd; trivial. destruct p.\n        remember (as_inj nu12 b1) as dd.\n        destruct dd; apply eq_sym in Heqdd.\n            destruct p.\n            exfalso. apply Hb1. apply Fwd1. apply (VBj12_1 _ _ _ Heqdd).\n        remember (as_inj nu' b1) as ddd.\n        destruct ddd; apply eq_sym in Heqddd.\n            destruct p. exfalso. apply Hb1. apply (VBj' _ _ _ Heqddd).\n        rewrite Heqj12' in Heqd.\n        unfold removeUndefs in Heqd. rewrite Heqdd, Heqddd in Heqd.\n        inv Heqd.\n  (*mi_mappedblock*) intros.\n     rewrite Heqj12' in H.\n        unfold removeUndefs in H.\n        remember (as_inj nu12 b) as dd.\n        destruct dd; apply eq_sym in Heqdd.\n            destruct p. inv H. apply Fwd2. apply (VBj12_2 _ _ _ Heqdd).\n        remember (as_inj nu' b) as ddd.\n        destruct ddd; apply eq_sym in Heqddd.\n          destruct p. \n          destruct (mkInjections_3V _ _ _ _ _ _ _ _ _ _ \n                      HeqMKI Val12 VBj23_1 _ _ _ H)\n          as [MK | [MK | MK]].\n            destruct MK as [J12 [Val1 Val2]]. apply Fwd2. apply Val2.\n            destruct MK as [_ [_ [_ [_ D]]]]. apply D.\n            destruct MK as [? [_ [_ [_ [_ D]]]]]. apply D.\n        inv H.\n  (*no_overlap*)\n       rewrite Heqj12'. \n       apply (RU_no_overlap _ _ _ MInj12 _ Fwd1 _ _ MInj23 _ _ _ _ _ HeqMKI).\n  (*representable*)\n       intros.\n       rewrite Heqj12' in H.\n       unfold removeUndefs in H.\n       remember (as_inj nu12 b) as d.\n       destruct d; apply eq_sym in Heqd.\n          destruct p. inv H.\n          destruct H0.\n          (*location ofs*)\n            eapply MInj12. apply Heqd. \n            left. apply Fwd1. apply (VBj12_1 _ _ _ Heqd). apply H.\n          (*location ofs -1*)\n            eapply MInj12. apply Heqd. \n            right. apply Fwd1. apply (VBj12_1 _ _ _ Heqd). apply H.\n       remember (as_inj nu' b) as dd.\n       destruct dd; apply eq_sym in Heqdd.\n          destruct p.\n          destruct (mkInjections_3V _ _ _ _ _ _ _ _ _ _ \n                     HeqMKI VB12  VBj23_1 _ _ _ H).\n              destruct H1. rewrite H1 in Heqd. discriminate.\n              destruct H1 as [HH | HH]. \n              destruct HH as [A [B [C [D E]]]]; subst.\n                 split. omega. \n                        rewrite Zplus_0_r. apply Int.unsigned_range_2.\n              destruct HH as [M [A [B [C [D E]]]]]; subst.\n                 split. omega. \n                        rewrite Zplus_0_r. apply Int.unsigned_range_2.\n       inv H. \nassert (ConvertR_J23': as_inj\n     (convertR nu23 j23' (FreshDom (as_inj nu23) j23')\n        (fun b : block => DomTgt nu' b && negb (DomTgt nu23 b))) = j23').\n   clear ConvertL_J12'. unfold as_inj.\n   rewrite convertR_extern, convertR_local.\n   extensionality b. unfold join.\n   remember (extern_of nu23 b) as d.\n   destruct d; apply eq_sym in Heqd.\n         destruct p. apply extern_in_all in Heqd.\n         rewrite (inc23 _ _ _ Heqd). trivial.\n   remember (local_of nu23 b) as q.\n   destruct q; trivial; apply eq_sym in Heqq.\n         destruct p.\n         apply local_in_all in Heqq; trivial.\n         rewrite (inc23 _ _ _ Heqq). trivial.\n   destruct (j23' b); trivial. destruct p; trivial.\nrewrite ConvertR_J23' in *. \n  rewrite convertR_extern, convertR_frgnBlocksSrc, \n          convertR_pubBlocksSrc, convertR_locBlocksSrc, \n          convertR_extBlocksSrc.\n \nassert (Inj23':Mem.inject j23' m2' m3').\n  clear ConvertL_J12' ConvertR_J23'.\n  assert (Perm23': forall b1 b2 delta ofs k p,\n                j23' b1 = Some (b2, delta) -> \n                Mem.perm m2' b1 ofs k p -> Mem.perm m3' b2 (ofs + delta) k p).\n      intros b2 b3; intros. \n      apply (valid_split _ _ _ _ (ACCESS b2)); intros; clear ACCESS.\n      (*valid*)\n        specialize (H2 k ofs).\n        assert (FF: as_inj nu23 b2 = Some (b3, delta)).\n           remember (as_inj nu23 b2) as dd.\n           destruct dd; apply eq_sym in Heqdd.\n             rewrite (inject_incr_coincide _ _ inc23 _ _ H _ Heqdd). trivial.\n           destruct (sep23 _ _ _ Heqdd H). exfalso. apply (H3 H1).\n        (*rewrite FF in H2.*)\n        remember (locBlocksSrc nu23 b2) as LocB2.\n        destruct LocB2; apply eq_sym in HeqLocB2.\n        (*case locBlocksSrc nu23 b2 = true*)\n          assert (extern_of nu23 b2 = None /\\ local_of nu23 b2 = Some (b3, delta)).\n            destruct (joinD_Some _ _ _ _ _ FF).\n              destruct (extern_DomRng _ WDnu23 _ _ _ H3) as [? ?].\n              destruct (disjoint_extern_local_Src _ WDnu23 b2); congruence. \n            assumption.\n          destruct H3 as [NoEXT23 LOC23].\n          remember (pubBlocksSrc nu23 b2) as PubB2.\n          destruct PubB2; apply eq_sym in HeqPubB2.\n          (*case pubBlocksSrc nu23 b2 = true*)\n            destruct (pubSrc _ WDnu23 _ HeqPubB2) as [b33 [d33 [PUB23 pubTGT3]]].\n            rewrite (pub_in_local _ _ _ _ PUB23) in LOC23. inv LOC23.\n            remember (source (local_of nu12) m1 b2 ofs) as d.\n            destruct d. \n            (*source (local_of nu12)  m1 b2 ofs = Some p0*)\n              destruct p0. \n              destruct (source_SomeE _ _ _ _ _ Heqd)\n                 as [b1 [d1 [ofs1 [PP [VB [ JJ [PERM Off2]]]]]]]. clear Heqd.\n              subst. inv PP.\n              rewrite <- Zplus_assoc.\n                assert (J: as_inj nu' b1 = Some (b3, d1 + delta)).\n                  rewrite ID.\n                  eapply compose_meminjI_Some.\n                     apply inc12. apply local_in_all; eassumption.\n                     apply inc23. assumption.\n              remember (pubBlocksSrc nu12 b1) as d.\n              destruct d; apply eq_sym in Heqd;\n                rewrite (perm_subst _ _ _ _ _ _ _ H2) in H0; clear H2.                \n                eapply MemInjNu'. apply J. apply H0.\n              apply UnchLOOR13.\n                 split. eapply (pub_locBlocks _ WDnu23). eassumption.\n                 intros bb1; intros. simpl. \n                 remember (pubBlocksSrc nu12 bb1) as d.\n                 destruct d; try (right; reflexivity).\n                 apply eq_sym in Heqd0. left. intros N.\n                 destruct (eq_block bb1 b1); subst; simpl.\n                   rewrite Heqd0 in Heqd. discriminate.\n                 assert (compose_meminj (as_inj nu12) (as_inj nu23) b1 = Some (b3, d1+delta)).\n                   eapply compose_meminjI_Some; try eassumption. apply local_in_all; eassumption.\n                 destruct (compose_meminjD_Some _ _ _ _ _ H2) as [bb2 [dd1 [dd2 [LC1 [LC2 DD]]]]]; clear H2.\n                   apply local_in_all in LC1; trivial. \n                   apply local_in_all in LC2; trivial.  subst.\n                   assert (compose_meminj (as_inj nu12) (as_inj nu23) bb1 = Some (b3, dd1 + dd2)).\n                    eapply compose_meminjI_Some; try eassumption.\n                 destruct (Mem.mi_no_overlap _ _ _ (Mem.inject_compose _ _ _ _ _ MInj12 MInj23) bb1 _ _ _ _ _ _ _ n H2 H3 N PERM).\n                   apply H4; trivial.\n                   apply H4; clear H4. omega.\n                eapply VBj23_2; eassumption.\n              rewrite Zplus_assoc. eapply MInj23; eassumption.\n            (*source (pub_of nu12) m1 b2 ofs = None*)\n              rewrite (perm_subst _ _ _ _ _ _ _ H2) in H0; clear H2.\n              assert (MX: Mem.perm m2 b2 ofs Max Nonempty).\n                  eapply Mem.perm_max. eapply Mem.perm_implies.\n                     apply H0. apply perm_any_N.\n              assert (SRC:= source_NoneE _ _ _ _ Heqd); clear Heqd.\n              apply UnchLOOR13.\n                 split. eapply (pub_locBlocks _ WDnu23); eassumption.\n                 intros bb1; intros. simpl. \n                 remember (pubBlocksSrc nu12 bb1) as d.\n                 destruct d; try (right; reflexivity).\n                 apply eq_sym in Heqd. left.\n                 simpl in H2. \n                 destruct (compose_meminjD_Some _ _ _ _ _ H2) as [bb2 [dd1 [dd2 [LC1 [LC2 DD]]]]]; clear H2.\n                 subst.\n                 destruct (eq_block bb2 b2); subst.\n                   rewrite (pub_in_local _ _ _ _ PUB23) in LC2. inv LC2.\n                   assert (Mem.valid_block m1 bb1).\n                     eapply VBj12_1. apply local_in_all; eassumption.\n                   assert (Arith: ofs + dd2 - (dd1 + dd2) = ofs - dd1) by omega.\n                   rewrite Arith. apply (SRC _ _ H2 LC1).\n                 intros N. apply local_in_all in LC1; trivial.\n                   apply (Mem.perm_inject (as_inj nu12) _ _ _ _ _ _ _ _ LC1 MInj12) in N.\n                   apply local_in_all in LC2; trivial.              \n                   destruct (Mem.mi_no_overlap _ _ _ MInj23 bb2 _ _ _ _ _ _ _ n LC2 FF N MX).\n                   apply H2; trivial.\n                   apply H2; clear H2. omega.\n                eapply VBj23_2; eassumption.\n              eapply MInj23; eassumption.\n          (*case pubBlocksSrc nu23 b2 = false -- HERE IS THE SPOT THAT MOTIVATED THE NEW DEFINIEION LOCAL_OUT_OF_REACH*)\n            rewrite (perm_subst _ _ _ _ _ _ _ H2) in H0; clear H2.\n              apply UNCHC.\n                 split. eapply (local_locBlocks _ WDnu23). eassumption.\n                 intros bb2; intros.\n                 remember (pubBlocksSrc nu23 bb2) as d.\n                 destruct d; try (right; reflexivity).\n                 apply eq_sym in Heqd. left.\n                 destruct (eq_block bb2 b2); subst.\n                   rewrite Heqd in HeqPubB2; discriminate.\n                 intros N. apply local_in_all in H2; trivial.\n                   assert (MX: Mem.perm m2 b2 ofs Max Nonempty).\n                     eapply Mem.perm_max. eapply Mem.perm_implies. eassumption. apply perm_any_N.\n                   destruct (Mem.mi_no_overlap _ _ _ MInj23 bb2 _ _ _ _ _ _ _ n H2 FF N MX).\n                   apply H3; trivial.\n                   apply H3; clear H3. omega.\n                eapply VBj23_2; eassumption.\n              eapply MInj23; eassumption.\n        (*case locBlocksSrc nu23 b2 = false*)\n          remember (source (as_inj nu12) m1 b2 ofs) as ss.\n          destruct ss.\n            destruct (source_SomeE _ _ _ _ _ Heqss)\n                 as [b1 [d1 [ofs1 [PP [VB [ JJ [PERM Off2]]]]]]]. clear Heqss.\n            subst.\n            rewrite (perm_subst _ _ _ _ _ _ _ H2) in H0. clear H2.\n            rewrite <- Zplus_assoc.\n            eapply MemInjNu'; try eassumption. \n              rewrite ID. eapply compose_meminjI_Some.\n                     apply inc12. apply JJ.\n                     apply inc23. assumption. \n          (*source (as_inj nu12) m1 b2 ofs = None*)\n            rewrite FF in H2.\n            unfold Mem.perm in H0. rewrite H2 in H0. simpl in H0. contradiction.\n            (*This case motivated setting perm m2' = None. In particular, assumption\n              UnchLOOR13 does not help any more, in contrast to the development in \n              mem_interpolation.v*)     \n      (*invalid*)\n          assert (MX: Mem.perm m2' b2 ofs Max Nonempty).\n              eapply Mem.perm_max. eapply Mem.perm_implies. \n                apply H0. apply perm_any_N.\n          assert (Max2':= H2 Max ofs).\n          specialize (H2 k ofs).\n          assert (J23: as_inj nu23 b2 = None).\n              remember (as_inj nu23 b2) as d.\n              destruct d; trivial. apply eq_sym in Heqd. destruct p0.\n              assert (X:= VBj23_1 _ _ _ Heqd).\n              exfalso.  apply (H1 X).\n          remember (source j12' m1' b2 ofs) as d.\n          destruct d. destruct p0.\n              rewrite (perm_subst _ _ _ _ _ _ _ H2) in *; clear H2.\n              rewrite (perm_subst _ _ _ _ _ _ _ Max2') in *; clear Max2'.\n              destruct (source_SomeE _ _ _ _ _ Heqd)\n                as [b1 [d1 [ofs1 [PP [VB [ JJ' [PERM Off2]]]]]]]; clear Heqd.\n              subst. apply eq_sym in PP. inv PP.\n              rewrite <- Zplus_assoc.\n              assert (Jb: as_inj nu' b= Some (b3, d1 + delta)).\n                  rewrite ID.\n                  eapply compose_meminjI_Some; eassumption.  \n              eapply MemInjNu'. apply Jb. apply H0.  \n          unfold Mem.perm in MX. rewrite Max2' in MX.  inv MX. \n  assert (MI: Mem.mem_inj j23' m2' m3').\n      split.\n      (*mi_perm *) apply Perm23'.\n      (*valid_access*)\n        intros b2 b3; intros.\n          destruct (mkInjections_4Val _ _ _ _ _ _ _ _ _ _ HeqMKI VBj23_1 _ _ _ H)\n            as [HH | [HH | HH]].\n          destruct HH. eapply MInj23; try eassumption.\n             intros z; intros. specialize (H0 _ H3).\n              eapply Fwd2; try eassumption.\n          destruct HH as [? [? ?]].\n            assert (ZZ: compose_meminj j12' j23'  (Mem.nextblock m1) = Some (b3, delta)).\n                   rewrite ID in H2; trivial. \n            rewrite Heqj12' in ZZ. subst.\n            destruct (compose_meminjD_Some _ _ _ _ _ ZZ) as\n                  [b2 [dd1 [dd2 [JJ1 [JJ2 XX]]]]]; subst; clear ZZ.\n            assert (J12': prej12' (Mem.nextblock m1) = Some(Mem.nextblock m2, 0)).\n               remember (as_inj nu12 (Mem.nextblock m1)) as q.\n               destruct q; apply eq_sym in Heqq.\n                 destruct p0. rewrite (inc12 _ _ _ Heqq) in JJ1. inv JJ1. \n                   apply VBj12_1 in Heqq. exfalso. unfold Mem.valid_block in Heqq. xomega.\n                 unfold removeUndefs in JJ1. rewrite Heqq in JJ1. rewrite H2 in JJ1. \n                 destruct (mkInjections_3V  _ _ _ _ _ _ _ _ _ _ HeqMKI VB12 VBj23_1 _ _ _ JJ1).\n                   destruct H1. rewrite H1 in Heqq. discriminate.\n                   destruct H1. destruct H1 as [_ [? [? [? ?]]]]. subst. assumption.\n                   destruct H1 as [mm [? [? [? [? ?]]]]]; subst.\n                     apply eq_sym in H1. rewrite Pos.add_comm in H1.\n                     apply Pos.add_no_neutral in H1. intuition.\n            assert (PRE: prej12' (Mem.nextblock m1) = Some (b2, dd1)). \n              unfold removeUndefs in JJ1.\n              remember (as_inj nu12 (Mem.nextblock m1)).\n              destruct o; apply eq_sym in Heqo.\n                destruct p0. apply VBj12_1 in Heqo. exfalso. unfold Mem.valid_block in Heqo. xomega.\n              rewrite H2 in JJ1. assumption.\n            rewrite J12' in PRE. inv PRE. simpl in *. clear JJ2. \n            destruct (ACCESS (Mem.nextblock m2)) as [_ ZZ].\n            assert (NVB2: ~ Mem.valid_block m2 (Mem.nextblock m2)).\n                       unfold Mem.valid_block. xomega. \n            assert (MR: Mem.range_perm m1' (Mem.nextblock m1) ofs (ofs + size_chunk chunk) Max p).\n               intros z; intros.          \n               specialize (ZZ NVB2 Max z).\n               remember (source (removeUndefs (as_inj nu12) (as_inj nu') prej12') m1' (Mem.nextblock m2) z).\n               destruct o.\n               Focus 2. specialize (H0 _ H1). unfold Mem.perm in H0. rewrite ZZ in H0. simpl in H0. intuition. \n               destruct (source_SomeE _ _ _ _ _ Heqo)\n                        as [b1 [dd1 [ofs1 [PPP [VB [ JJ' [PERM Off2]]]]]]]; clear Heqo.\n               subst. specialize (H0 _ H1).\n               rewrite (perm_subst _ _ _ _ _ _ _ ZZ) in H0; clear ZZ.\n               assert (prej12'  b1 = Some (Mem.nextblock m2, dd1)).\n                 unfold removeUndefs in JJ'.\n                 remember (as_inj nu12 b1).\n                 destruct o; apply eq_sym in Heqo.\n                   destruct p0. inv JJ'. apply VBj12_2 in Heqo. contradiction.\n                 remember (as_inj nu' b1).\n                 destruct o. destruct p0. assumption. inv JJ'.\n               assert (b1 = Mem.nextblock m1).\n                 destruct (mkInjections_3V  _ _ _ _ _ _ _ _ _ _ HeqMKI VB12 VBj23_1 _ _ _ H4).\n                 destruct H5. apply VBj12_2 in H5. contradiction.\n                 destruct H5. destruct H5; trivial.\n                 destruct H5 as [mm1 [? [? [? [? ?]]]]]. subst.\n                   apply eq_sym in H6. rewrite Pos.add_comm in H6.\n                   apply Pos.add_no_neutral in H6. intuition.\n               subst. rewrite J12' in H4. inv H4. rewrite Zplus_0_r. assumption.     \n             eapply MemInjNu'; eassumption.\n          destruct HH as [mm [? [? ?]]]. subst. clear H3.\n            assert (ZZ: compose_meminj (removeUndefs (as_inj nu12) (as_inj nu') prej12') j23' ((Mem.nextblock m1+ mm)%positive) = Some (b3, delta)).\n                   rewrite <- ID; trivial. \n               destruct (compose_meminjD_Some _ _ _ _ _ ZZ) as\n                  [b2 [dd1 [dd2 [JJ1 [JJ2 XX]]]]]. subst; clear ZZ.\n            assert (J12': prej12' ((Mem.nextblock m1+ mm)%positive) = Some((Mem.nextblock m2+ mm)%positive, 0)).\n               remember (as_inj nu12 ((Mem.nextblock m1+ mm)%positive)) as q.\n               destruct q; apply eq_sym in Heqq.\n                 destruct p0. rewrite (inc12 _ _ _ Heqq) in JJ1. inv JJ1. \n                   apply VBj12_1 in Heqq. exfalso. unfold Mem.valid_block in Heqq. xomega.\n                 unfold removeUndefs in JJ1. rewrite Heqq in JJ1. rewrite H2 in JJ1. \n                 destruct (mkInjections_3V  _ _ _ _ _ _ _ _ _ _ HeqMKI VB12 VBj23_1 _ _ _ JJ1).\n                   destruct H1. rewrite H1 in Heqq. discriminate.\n                   destruct H1. destruct H1 as [? [? [? [? ?]]]]. subst.\n                     rewrite Pos.add_comm in H1.\n                     apply Pos.add_no_neutral in H1. intuition.\n                   destruct H1 as [mm2 [? [? [? [? ?]]]]]; subst.\n                     apply Pos.add_reg_l in H1. subst. \n                   assumption.\n            assert (PRE: prej12' ((Mem.nextblock m1+ mm)%positive) = Some (b2, dd1)). \n              unfold removeUndefs in JJ1.\n              remember (as_inj nu12 ((Mem.nextblock m1+ mm)%positive)).\n              destruct o; apply eq_sym in Heqo.\n                destruct p0. apply VBj12_1 in Heqo. exfalso. unfold Mem.valid_block in Heqo. xomega.\n              rewrite H2 in JJ1. assumption.\n            rewrite J12' in PRE. inv PRE. simpl in *. clear JJ2.  \n            destruct (ACCESS ((Mem.nextblock m2+ mm)%positive)) as [_ ZZ].\n            assert (NVB2: ~ Mem.valid_block m2 ((Mem.nextblock m2+ mm)%positive)).\n                       unfold Mem.valid_block. xomega. \n            assert (MR: Mem.range_perm m1' ((Mem.nextblock m1+ mm)%positive) ofs (ofs + size_chunk chunk) Max p).\n               intros z; intros.          \n               specialize (ZZ NVB2 Max z).\n               remember (source (removeUndefs (as_inj nu12) (as_inj nu') prej12') m1'\n                      (Mem.nextblock m2 + mm)%positive z).\n               destruct o.\n               Focus 2. specialize (H0 _ H1). unfold Mem.perm in H0. rewrite ZZ in H0. simpl in H0. intuition. \n               destruct (source_SomeE _ _ _ _ _ Heqo)\n                        as [bb1 [dd1 [ofs11 [PPP [VB [ JJ' [PERM Off2]]]]]]]. clear Heqo.\n               subst. specialize (H0 _ H1).\n               rewrite (perm_subst _ _ _ _ _ _ _ ZZ) in H0. clear ZZ.\n               assert (prej12'  bb1 = Some ((Mem.nextblock m2+ mm)%positive, dd1)).\n                 unfold removeUndefs in JJ'.\n                 remember (as_inj nu12 bb1).\n                 destruct o; apply eq_sym in Heqo.\n                   destruct p0. inv JJ'. apply VBj12_2 in Heqo. contradiction.\n                 remember (as_inj nu' bb1).\n                 destruct o. destruct p0. assumption. inv JJ'.\n               assert (bb1 = (Mem.nextblock m1+ mm)%positive).\n                 destruct (mkInjections_3V  _ _ _ _ _ _ _ _ _ _ HeqMKI VB12 VBj23_1 _ _ _ H3).\n                 destruct H4. apply VBj12_2 in H4. contradiction.\n                 destruct H4. destruct H4 as [? [? ?]]; subst. \n                   rewrite Pos.add_comm in H5.\n                   apply Pos.add_no_neutral in H5. intuition.\n                 destruct H4 as [mm1 [? [? [? [? ?]]]]]. subst.\n                   apply Pos.add_reg_l in H5. subst. trivial.\n               subst. rewrite J12' in H3. inv H3. rewrite Zplus_0_r. assumption.\n             eapply MemInjNu'; eassumption.\n      (*memval j23' m2' m3'*) intros b2 ofs2 b3 delta3 Jb2 Perm2.\n          assert (Perm2Max: Mem.perm m2' b2 ofs2  Max Nonempty).\n             eapply Mem.perm_max. eapply Mem.perm_implies.\n                        apply Perm2. constructor.\n          destruct (ACCESS b2) as [Valid Invalid].\n          apply (cont_split _ _ _ _ _ (CONT b2)); intros; clear CONT.\n          (*case Mem.valid_block m2 b2*)\n             assert (ValidMax := Valid H Max ofs2).\n             specialize (Valid H Cur ofs2). clear Invalid.\n             specialize (H0 ofs2).\n             assert (J23: as_inj nu23 b2 = Some (b3, delta3)).\n                 remember (as_inj nu23 b2) as d. destruct d; apply eq_sym in Heqd.\n                    destruct p. rewrite (inc23 _ _ _ Heqd) in Jb2. apply Jb2.\n                    destruct (sep23 _ _ _ Heqd Jb2). exfalso. apply (H2 H).\n             rewrite J23 in Valid, ValidMax. (*rewrite Jb2 in H0.*)\n             remember (locBlocksSrc nu23 b2) as LocB2.\n             destruct LocB2; apply eq_sym in HeqLocB2.\n               assert (LOC23: local_of nu23 b2 = Some (b3, delta3)).\n                  destruct (joinD_Some _ _ _ _ _ J23) as [EXT | [EXT LOC]]; trivial.\n                  destruct (extern_DomRng _ WDnu23 _ _ _ EXT).\n                  destruct (disjoint_extern_local_Src _ WDnu23 b2); congruence. \n               remember (pubBlocksSrc nu23 b2) as PubB2.\n               destruct PubB2; apply eq_sym in HeqPubB2.\n                 remember (source (local_of nu12) m1 b2 ofs2) as ss.\n                 destruct ss.\n                 (*source (local_of nu12) m1 b2 ofs2  = Some p *)\n                   destruct (source_SomeE _ _ _ _ _ Heqss)\n                     as [b1 [delta2 [ofs1 [PP [Valb1 [ Jb1 [Perm1 Off]]]]]]].\n                   clear Heqss; subst.\n                     assert (J': as_inj nu' b1 = Some (b3, delta2 + delta3)).\n                       rewrite ID. eapply compose_meminjI_Some; try eassumption.\n                        apply inc12. apply local_in_all; eassumption.\n                   remember (pubBlocksSrc nu12 b1) as d.\n                   destruct d; apply eq_sym in Heqd.\n                   (*case pubBlocksSrc nu12 b1 = true*)\n                     rewrite (perm_subst _ _ _ _ _ _ _ Valid) in Perm2; clear Valid.\n                     rewrite (perm_subst _ _ _ _ _ _ _ ValidMax) in Perm2Max; clear ValidMax.\n                     rewrite H0 in *; clear H0. simpl in *.\n                     assert (Perm1'Max: Mem.perm m1' b1 ofs1 Max Nonempty).\n                       eapply Mem.perm_max; eassumption. \n                     specialize (Mem.mi_memval _ _ _\n                          (Mem.mi_inj _ _ _ MemInjNu') _ _  _ _ J' Perm2). \n                     intros MemVal13'. \n                     rewrite <- Zplus_assoc.\n                     inv MemVal13'; simpl in *; try econstructor.\n                        rewrite ID in H3.        \n                        destruct (compose_meminjD_Some _ _ _ _ _ H3) \n                           as [bb2 [dd2 [dd3 [RR [JJ23  DD]]]]]; subst; clear H3.\n                        rewrite RR. econstructor. eassumption.\n                          rewrite Int.add_assoc. decEq. unfold Int.add. \n                          apply Int.eqm_samerepr. auto with ints.\n                   (*case pubBlocksSrc nu12 b1 = false*)\n                     rewrite (perm_subst _ _ _ _ _ _ _ Valid) in Perm2; clear Valid. \n                     rewrite (perm_subst _ _ _ _ _ _ _ ValidMax) in Perm2Max; clear ValidMax.\n                     rewrite H0 in *; clear H0. simpl in *.\n                     destruct UnchLOOR13 as [UP3 UV3].\n                     rewrite UV3. \n                       eapply memval_inject_incr. eapply MInj23. assumption. assumption. assumption.\n                     split; simpl. eapply local_locBlocks; eassumption.\n                       intros. destruct (compose_meminjD_Some _ _ _ _ _ H0) as [bb2 [dd1 [dd2 [LC12 [LC23 DD]]]]]; clear H0.\n                         subst. \n                         destruct (eq_block b0 b1); subst. \n                           right; assumption.\n                         remember (pubBlocksSrc nu12 b0) as d.\n                         destruct d; try (right; reflexivity).\n                         left; apply eq_sym in Heqd.\n                         intros N.\n                         assert (compose_meminj (as_inj nu12) (as_inj nu23) b0 = Some(b3,dd1+dd2)).\n                            apply local_in_all in LC12; trivial.\n                            apply local_in_all in LC23; trivial.\n                            eapply compose_meminjI_Some; eassumption.\n                         assert (compose_meminj (as_inj nu12) (as_inj nu23) b1 = Some(b3,delta2+delta3)).\n                            apply local_in_all in Jb1; trivial.\n                            eapply compose_meminjI_Some; eassumption.\n                         destruct (Mem.mi_no_overlap _ _ _ (Mem.inject_compose _ _ _ _ _ MInj12 MInj23)\n                                  _ _ _ _ _ _ _ _ n H0 H2 N Perm1).\n                           apply H3; trivial.\n                           apply H3; clear H3. omega.\n                     eapply MInj23; eassumption.\n                 (*case source  j12 m1 b2 ofs2  = None *)\n                   rewrite H0. clear H0.\n                   rewrite (perm_subst _ _ _ _ _ _ _ Valid) in Perm2. clear Valid. \n                   rewrite (perm_subst _ _ _ _ _ _ _ ValidMax) in Perm2Max. clear ValidMax. \n                   assert (LOOR: local_out_of_reach \n                                (compose_sm nu12 nu23) m1 b3 (ofs2+delta3)).\n                     split; simpl. eapply (local_DomRng _ WDnu23); eassumption.\n                     intros. \n                     destruct (compose_meminjD_Some _ _ _ _ _ H0) as [bb2 [dd1 [dd2 [LC12 [LC23 D]]]]]; clear H0.\n                     rewrite D in *; clear delta D. \n                     destruct (eq_block bb2 b2); subst.\n                     (*case bb2=b2*)\n                         rewrite LC23 in LOC23. inv LOC23. \n                         assert (Arith: ofs2 + delta3 - (dd1 + delta3) = ofs2 - dd1) by omega. \n                         rewrite Arith. left.\n                         apply (source_NoneE _ _ _ _ Heqss). \n                             apply local_in_all in LC12; trivial. apply (VBj12_1 _ _ _ LC12).\n                             assumption.\n                     (*case bb2<>b2*)\n                         remember (pubBlocksSrc nu12 b0) as d.\n                         destruct d; try (right; reflexivity).\n                         left; apply eq_sym in Heqd.\n                         intros N.\n                         assert (NN2: Mem.perm m2 bb2\n                                     (ofs2 + (delta3 - dd2)) Max Nonempty).\n                             assert (Arith: ofs2 + delta3 - (dd1 + dd2) + dd1 = \n                                      ofs2 + (delta3 - dd2)) by omega. \n                             rewrite <- Arith.\n                             eapply MInj12; try eassumption.\n                               apply local_in_all; assumption.\n                         apply local_in_all in LC23; trivial.\n                         destruct (Mem.mi_no_overlap _ _ _ \n                                 MInj23 _ _ _ _ _ _ _ _ n LC23 J23 NN2 Perm2Max).\n                                     apply H0; trivial.\n                                     apply H0. omega.                         \n                   assert (Perm3: Mem.perm m3 b3 (ofs2+delta3) Cur Readable).\n                     eapply MInj23. apply J23. apply Perm2.\n                   destruct UnchLOOR13 as [Uperm UVal]. \n                   rewrite (UVal _ _ LOOR Perm3).\n                   eapply memval_inject_incr. \n                     apply (Mem.mi_memval _ _ _ \n                            (Mem.mi_inj _ _ _  MInj23) _ _ _ _ J23 Perm2). \n                     apply inc23.\n               (*case pubBlocksSrc nu23 b2 = false*)\n                 rewrite H0. clear H0.\n                 rewrite (perm_subst _ _ _ _ _ _ _ Valid) in Perm2. clear Valid. \n                 rewrite (perm_subst _ _ _ _ _ _ _ ValidMax) in Perm2Max. clear ValidMax. \n                 assert (LOOR: local_out_of_reach nu23 m2 b3 (ofs2+delta3)).\n                  split; simpl. eapply (local_DomRng _ WDnu23); eassumption.\n                     intros bb2; intros.\n                     destruct (eq_block bb2 b2); subst.\n                     (*case bb2=b2*) right; assumption.\n                     (*case bb2<>b2*)\n                         remember (pubBlocksSrc nu23 bb2) as d.\n                         destruct d; try (right; reflexivity).\n                         left; apply eq_sym in Heqd.\n                         intros N.\n                         apply local_in_all in H0; trivial.\n                         destruct (Mem.mi_no_overlap _ _ _ \n                                 MInj23 _ _ _ _ _ _ _ _ n H0 J23 N Perm2Max).\n                                     apply H2; trivial.\n                                     apply H2. omega.                         \n                   assert (Perm3: Mem.perm m3 b3 (ofs2+delta3) Cur Readable).\n                     eapply MInj23. apply J23. apply Perm2.\n                   destruct UNCHC as [Uperm UVal]. \n                   rewrite (UVal _ _ LOOR Perm3).\n                   eapply memval_inject_incr. \n                     apply (Mem.mi_memval _ _ _ \n                            (Mem.mi_inj _ _ _  MInj23) _ _ _ _ J23 Perm2). \n                     apply inc23.                     \n             (*case locBlocksSrc nu23 b2 = false*)\n                 remember (source (as_inj nu12) m1 b2 ofs2) as ss.\n                 destruct ss.\n                 (*source (local_of nu12) m1 b2 ofs2  = Some p *)\n                   destruct (source_SomeE _ _ _ _ _ Heqss)\n                     as [b1 [delta2 [ofs1 [PP [Valb1 [ Jb1 [Perm1 Off]]]]]]].\n                   clear Heqss; subst.\n                   rewrite (perm_subst _ _ _ _ _ _ _ Valid) in Perm2; clear Valid. \n                   rewrite (perm_subst _ _ _ _ _ _ _ ValidMax) in Perm2Max; clear ValidMax. \n                   rewrite H0; clear H0; simpl in *.\n                   assert (J': as_inj nu' b1 = Some (b3, delta2 + delta3)).\n                       rewrite ID. eapply compose_meminjI_Some; try eassumption.\n                        apply inc12. eassumption.\n                   specialize (Mem.mi_memval _ _ _\n                          (Mem.mi_inj _ _ _ MemInjNu') _ _  _ _ J' Perm2). \n                   intros MemVal13'. \n                   rewrite <- Zplus_assoc.\n                   inv MemVal13'; simpl in *; try econstructor.\n                      rewrite ID in H3.        \n                        destruct (compose_meminjD_Some _ _ _ _ _ H3) \n                           as [bb2 [dd2 [dd3 [RR [JJ23  DD]]]]]; subst; clear H3.\n                        rewrite RR. econstructor. eassumption.\n                          rewrite Int.add_assoc. decEq. unfold Int.add. \n                          apply Int.eqm_samerepr. auto with ints.\n                 (*case source  j12 m1 b2 ofs2  = None *)\n                   rewrite H0; clear H0.\n                   unfold Mem.perm in Perm2Max, Perm2. \n                   rewrite Valid in Perm2; clear Valid. \n                   simpl in Perm2. contradiction.\n          (*case ~ Mem.valid_block m2 b2*)\n             specialize (H0 ofs2). clear Valid.\n             assert (InvalidMax := Invalid H Max ofs2). \n             specialize (Invalid H Cur ofs2).\n             assert (J23: as_inj nu23 b2 = None).\n                 remember (as_inj nu23 b2) as d. \n                 destruct d; apply eq_sym in Heqd; trivial.\n                    destruct p. rewrite (inc23 _ _ _ Heqd) in Jb2. inv Jb2.\n                          exfalso. apply H. apply (VBj23_1 _ _ _ Heqd).\n             remember (source j12' m1' b2 ofs2) as ss.\n             destruct ss.\n             (*source f m1' b2 ofs2  = Some p *)\n                 destruct p. rewrite H0 in *. clear H0.\n                 rewrite (perm_subst _ _ _ _ _ _ _ Invalid) in Perm2; clear Invalid. \n                 rewrite (perm_subst _ _ _ _ _ _ _ InvalidMax) in Perm2Max; clear InvalidMax. \n                 destruct (source_SomeE _ _ _ _ _ Heqss)\n                    as [b1 [delta2 [ofs1 [PP [VB [RR1 [Perm1' Off2]]]]]]].\n                 clear Heqss.\n                 inv PP.\n                 assert (JB: as_inj nu' b1 = Some (b3, delta2 + delta3)).\n                       rewrite ID. eapply compose_meminjI_Some; try eassumption.\n                 specialize (Mem.mi_memval _ _ _ \n                       (Mem.mi_inj _ _ _  MemInjNu') _ _  _ _ JB Perm2). \n                 intros MemVal13'.                    \n                 rewrite <- Zplus_assoc. \n                 inv MemVal13'; simpl in *; try econstructor.\n                 rewrite ID in H3.                     \n                 destruct (compose_meminjD_Some _ _ _ _ _ H3)\n                       as [bb2 [dd2 [ddd3 [RRR [JJJ23  DD]]]]]; subst.\n                    rewrite RRR. econstructor. apply JJJ23.\n                    rewrite Int.add_assoc. decEq. unfold Int.add. \n                       apply Int.eqm_samerepr. auto with ints.  \n             (*source  j12' m1' b1 ofs  = None *) \n                 unfold Mem.perm in Perm2. rewrite Invalid in Perm2. inv Perm2.\n   split; trivial.\n   (*mi_freeblocks*)\n       intros. remember (j23' b) as d.\n       destruct d; apply eq_sym in Heqd; trivial.\n       destruct p. exfalso.\n\n       destruct (mkInjections_0 _ _ _ _ _ _ _ _ _ _ HeqMKI)\n        as [HH | HH].\n       destruct HH as [? [? [? [?  ?]]]]; subst.\n         apply H. apply Fwd2. apply (VBj23_1 _ _ _ Heqd).\n       destruct HH as [N [? [? [? ?]]]]. \n         destruct (mkInjections_4Val _ _ _ _ _ _ _ _ _ _ HeqMKI VBj23_1 _ _ _ Heqd)\n            as [HH | [HH | HH]].\n         destruct HH. apply H. apply Fwd2. apply H5. \n         destruct HH as [? [? ?]]; subst.\n            apply (H H6).    \n         destruct HH as [M [BM [J' B]]]; subst.\n            apply (H B). \n   (*mi_mappedblocks*)\n      intros. \n      destruct (mkInjections_4Val _ _ _ _ _ _ _ _ _ _ HeqMKI \n        VBj23_1 _ _ _ H)as [HH | [HH | HH]].\n      destruct HH. apply Fwd3. apply (VBj23_2 _ _ _  H0).\n      destruct HH as [? [? ?]]; subst.\n        eapply MemInjNu'. apply H1.\n         destruct HH as [M [BM [J' B]]]; subst.\n           eapply MemInjNu'. apply J'.\n   (*no_overlap*)\n      intros b; intros.\n      destruct (mkInjections_4Val _ _ _ _ _ _ _ _ _ _ HeqMKI\n        VBj23_1 _ _ _ H0) as [HH | [HH | HH]].\n      destruct HH as [j23b vbb].\n         destruct (mkInjections_4Val _ _ _ _ _ _ _ _ _ _ \n               HeqMKI VBj23_1 _ _ _ H1) as [KK | [KK | KK]].\n            destruct KK as [j23b2 vbb2]. \n            eapply MInj23. \n               apply H. \n               apply j23b. \n               apply j23b2.\n               apply Fwd2. apply (VBj23_1 _ _ _ j23b). apply H2.\n               apply Fwd2. apply (VBj23_1 _ _ _ j23b2). apply H3.\n            destruct KK as [BM [J' B']]; subst.\n              left. assert (as_inj nu23 (Mem.nextblock m2) = None).\n                     remember (as_inj nu23 (Mem.nextblock m2)) as d.\n                     destruct d; trivial.\n                     destruct p. apply eq_sym in Heqd.\n                     specialize (VBj23_1 _ _ _ Heqd). \n                      clear - VBj23_1.\n                      unfold Mem.valid_block in VBj23_1. xomega.\n                   intros N; subst. \n                    destruct (sep23 _ _ _ H4 H1). apply H6. \n                    eapply MInj23. apply j23b.\n            destruct KK as [M [BM [J' B']]].\n            left. assert (as_inj nu23 b2 = None).\n                     remember (as_inj nu23 b2) as d.\n                     destruct d; trivial.\n                     destruct p. apply eq_sym in Heqd.\n                     specialize (VBj23_1 _ _ _ Heqd).\n                     clear - VBj23_1 BM. subst.\n                     unfold Mem.valid_block in VBj23_1. xomega.\n                  intros N; subst. \n                    destruct (sep23 _ _ _ H4 H1). apply H6. \n                    eapply MInj23. apply j23b.\n         destruct HH as [NBb [j'b NBb']]; subst.\n           destruct (mkInjections_4Val _ _ _ _ _ _ _ _ _ _ \n                HeqMKI VBj23_1 _ _ _ H1) as [KK | [KK | KK]].\n            destruct KK as [j23b2 vbb2].  \n             left. assert (as_inj nu23 (Mem.nextblock m2) = None).\n                      remember (as_inj nu23 (Mem.nextblock m2)) as d. \n                      destruct d; trivial. destruct p.\n                      apply eq_sym in Heqd.\n                      specialize (VBj23_1 _ _ _ Heqd).\n                      clear - VBj23_1.\n                      unfold Mem.valid_block in VBj23_1. xomega.\n                   intros N; subst.\n                     destruct (sep23 _ _ _ H4 H0).\n                     apply H6. eapply MInj23. apply j23b2.\n            destruct KK as [BM [J' B']]; subst.\n              exfalso. apply H; trivial.\n            destruct KK as [M [BM [J' B']]]. subst.\n          (*first case where both blocks are in m2' but not in m2*)\n              assert (j23_None1: as_inj nu23 (Mem.nextblock m2) = None).\n                 remember (as_inj nu23 (Mem.nextblock m2)) as d. \n                 destruct d; trivial. \n                 apply eq_sym in Heqd. destruct p. \n                 specialize (VBj23_1 _ _ _ Heqd). clear - VBj23_1.\n                 unfold Mem.valid_block in VBj23_1. xomega.\n              assert (j23_None2: as_inj nu23 ((Mem.nextblock m2 + M)%positive) = None).\n                 remember (as_inj nu23 ((Mem.nextblock m2 + M)%positive)) as d. \n                 destruct d; trivial. \n                 apply eq_sym in Heqd. destruct p. \n                 specialize (VBj23_1 _ _ _ Heqd). clear - VBj23_1.\n                 exfalso. unfold Mem.valid_block in VBj23_1. xomega.      \n              destruct (sep23 _ _ _ j23_None1 H0) as [NV2_1 NV3_1].\n              destruct (sep23 _ _ _ j23_None2 H1) as [NV2_2 NV3_2].\n              assert (Max3_1:= Perm23' _ _ _ _ _ _ H0 H2).\n              assert (Max3_2:= Perm23' _ _ _ _ _ _ H1 H3).\n              assert (NEQ : Mem.nextblock m1 <> (Mem.nextblock m1 + M)%positive). \n                 apply add_no_neutral2. \n              destruct (ACCESS (Mem.nextblock m2)) as [_ Invalid1].\n              specialize (Invalid1 NV2_1 Max ofs1).\n                           \n              remember (source (removeUndefs (as_inj nu12) (as_inj nu') prej12')\n                    m1' (Mem.nextblock m2) ofs1) as d.\n              destruct d.\n              (*source j12' ofs1 = Some*)\n                 destruct p. \n                 rewrite (perm_subst _ _ _ _ _ _ _ Invalid1) in H2.\n                 clear Invalid1.\n                 destruct (ACCESS  (Mem.nextblock m2 + M)%positive) as [_ Invalid2].\n                 specialize (Invalid2 NV2_2 Max ofs2).\n\n                 remember (source (removeUndefs (as_inj nu12) (as_inj nu') prej12') m1'\n                         (Mem.nextblock m2 + M)%positive ofs2) as d.\n                 destruct d.\n                 (*source j12' ofs2 = Some*)\n                     destruct p. \n                     rewrite (perm_subst _ _ _ _ _ _ _ Invalid2) in H3. \n                     clear Invalid2.\n                     rename b into b1. rename z into z1. rename b0 into b2.\n                     rename z0 into z2.\n\n                     destruct (source_SomeE _ _ _ _ _ Heqd) \n                         as [bb1 [dd1 [ofs11 [PP [VB [ JJ' [PERM Off1]]]]]]].\n                     clear Heqd. subst. apply eq_sym in PP. inv PP.\n                     unfold removeUndefs in JJ'.\n                     remember (as_inj nu12 b1) as q.\n                     destruct q; apply eq_sym in Heqq.\n                       destruct p. inv JJ'. exfalso. apply NV2_1. \n                           apply (VBj12_2 _ _ _ Heqq).\n                     remember (as_inj nu' b1) as qq.\n                     destruct qq; inv JJ'. apply eq_sym in Heqqq.\n                     destruct p. \n                     destruct (mkInjections_3V _ _ _ _ _ _ _ _ _ _ \n                              HeqMKI VB12 VBj23_1 _ _ _ H5) as [HH | [HH |HH]].\n                     destruct HH as [HH _]. rewrite HH in Heqq; discriminate.\n                     destruct HH as [? [? [? [? ?]]]]; subst. \n                       destruct (source_SomeE _ _ _ _ _ Heqd0) as \n                           [bb2 [dd2 [ofs22 [PP2 [VB2 [ JJ2' [PERM2 Off2]]]]]]].\n                       clear Heqd0. subst. apply eq_sym in PP2. inv PP2.\n                       unfold removeUndefs in JJ2'.\n                       remember (as_inj nu12 b2) as r.\n                       destruct r; apply eq_sym in Heqr.\n                           destruct p. inv JJ2'. \n                           exfalso. apply NV2_2. apply (VBj12_2 _ _ _ Heqr).\n                       remember (as_inj nu' b2) as rr.\n                       destruct rr; inv JJ2'. apply eq_sym in Heqrr.\n                       destruct p. \n                       destruct (mkInjections_3V _ _ _ _ _ _ _ _\n                                         _ _ HeqMKI VB12 VBj23_1 _ _ _ H7)\n                           as [KK | [KK | KK]].\n                         destruct KK as [KK _]. rewrite KK in Heqr; discriminate.\n                         destruct KK as [? [? [? [? ?]]]]. subst.\n                              exfalso. apply (Pos.add_no_neutral (Mem.nextblock m2) M).\n                                 rewrite Pos.add_comm. apply H10.\n                         destruct KK as [MM2 [BB2 [nbm\n                                           [zz [X2 Y2]]]]]. subst.\n                           apply Pos.add_reg_l in nbm. apply eq_sym in nbm.  subst. \n                           eapply MemInjNu'. \n                              apply NEQ. \n                              assumption.\n                              assumption. \n                              rewrite Zplus_0_r. apply PERM.\n                              rewrite Zplus_0_r. apply PERM2.\n                     destruct HH as [MM1 [? [? [? [? ?]]]]]; subst.\n                       exfalso. apply (add_no_neutral2 (Mem.nextblock m2) MM1).\n                         apply H6.\n                 (*source j12' ofs2 = None*)\n                    unfold Mem.perm in H3. rewrite Invalid2 in H3. inv H3.\n                 (*source j12' ofs1 = None*)\n                    unfold Mem.perm in H2. rewrite Invalid1 in H2. inv H2.\n         destruct HH as [M1 [? [j'b1 NBb1]]]; subst.\n           destruct (mkInjections_4Val _ _ _ _ _ _ _ _ _ _ \n                HeqMKI VBj23_1 _ _ _ H1) as [KK | [KK | KK]].\n            destruct KK as [j23b2 vbb2].  \n             left. assert (as_inj nu23 (Mem.nextblock m2 + M1)%positive = None).\n                      remember (as_inj nu23 (Mem.nextblock m2 + M1)%positive) as d. \n                      destruct d; trivial. destruct p.\n                      apply eq_sym in Heqd.\n                      specialize (VBj23_1 _ _ _ Heqd).\n                      clear - VBj23_1.\n                      unfold Mem.valid_block in VBj23_1. xomega.\n                   intros N; subst.\n                     destruct (sep23 _ _ _ H4 H0).\n                     apply H6. eapply MInj23. apply j23b2.\n            destruct KK as [BM [J' B']]; subst.\n          (*second case where both blocks are in m2' but not in m2*)\n              assert (j23_None1: as_inj nu23 (Mem.nextblock m2 + M1)%positive = None).\n                 remember (as_inj nu23 (Mem.nextblock m2 + M1)%positive) as d. \n                 destruct d; trivial. \n                 apply eq_sym in Heqd. destruct p. \n                 specialize (VBj23_1 _ _ _ Heqd). clear - VBj23_1.\n                 unfold Mem.valid_block in VBj23_1. xomega.\n              assert (j23_None2: as_inj nu23 (Mem.nextblock m2) = None).\n                 remember (as_inj nu23 (Mem.nextblock m2)) as d. \n                 destruct d; trivial. \n                 apply eq_sym in Heqd. destruct p. \n                 specialize (VBj23_1 _ _ _ Heqd). clear - VBj23_1.\n                 exfalso. unfold Mem.valid_block in VBj23_1. xomega.      \n              destruct (sep23 _ _ _ j23_None1 H0) as [NV2_1 NV3_1].\n              destruct (sep23 _ _ _ j23_None2 H1) as [NV2_2 NV3_2].\n              assert (Max3_1:= Perm23' _ _ _ _ _ _ H0 H2).\n              assert (Max3_2:= Perm23' _ _ _ _ _ _ H1 H3).\n              assert (NEQ : (Mem.nextblock m1 + M1)%positive <> Mem.nextblock m1). \n                rewrite Pos.add_comm. apply Pos.add_no_neutral. \n              destruct (ACCESS (Mem.nextblock m2 + M1)%positive) as [_ Invalid1].\n              specialize (Invalid1 NV2_1 Max ofs1).\n                           \n              remember (source (removeUndefs (as_inj nu12) (as_inj nu') prej12')\n                    m1' ((Mem.nextblock m2 +M1)%positive) ofs1) as d.\n              destruct d.\n              (*source j12' ofs1 = Some*)\n                 destruct p. \n                 rewrite (perm_subst _ _ _ _ _ _ _ Invalid1) in H2.\n                 clear Invalid1.\n                 destruct (ACCESS  (Mem.nextblock m2)) as [_ Invalid2].\n                 specialize (Invalid2 NV2_2 Max ofs2).\n\n                 remember (source (removeUndefs (as_inj nu12) (as_inj nu') prej12') m1'\n                         (Mem.nextblock m2) ofs2) as d.\n                 destruct d.\n                 (*source j12' ofs2 = Some*)\n                     destruct p. \n                     rewrite (perm_subst _ _ _ _ _ _ _ Invalid2) in H3. \n                     clear Invalid2.\n                     rename b into b1. rename z into z1. rename b0 into b2.\n                     rename z0 into z2.\n\n                     destruct (source_SomeE _ _ _ _ _ Heqd) \n                         as [bb1 [dd1 [ofs11 [PP [VB [ JJ' [PERM Off1]]]]]]].\n                     clear Heqd. subst. apply eq_sym in PP. inv PP.\n                     unfold removeUndefs in JJ'.\n                     remember (as_inj nu12 b1) as q.\n                     destruct q; apply eq_sym in Heqq.\n                       destruct p. inv JJ'. exfalso. apply NV2_1. \n                           apply (VBj12_2 _ _ _ Heqq).\n                     remember (as_inj nu' b1) as qq.\n                     destruct qq; inv JJ'. apply eq_sym in Heqqq.\n                     destruct p. \n                     destruct (mkInjections_3V _ _ _ _ _ _ _ _ _ _ \n                              HeqMKI VB12 VBj23_1 _ _ _ H5) as [HH | [HH |HH]].\n                     destruct HH as [HH _]. rewrite HH in Heqq; discriminate.\n                     destruct HH as [? [? [? [? ?]]]]; subst. \n                       exfalso. rewrite Pos.add_comm in H6. \n                        apply Pos.add_no_neutral in H6. apply H6.\n                     destruct HH as [MM1 [? [? [? [? ?]]]]]; subst.\n                       apply Pos.add_reg_l in H6. apply eq_sym in H6. subst.\n                       destruct (source_SomeE _ _ _ _ _ Heqd0) as \n                           [bb2 [dd2 [ofs22 [PP2 [VB2 [ JJ2' [PERM2 Off2]]]]]]].\n                       clear Heqd0. subst. apply eq_sym in PP2. inv PP2.\n                       unfold removeUndefs in JJ2'.\n                       remember (as_inj nu12 b2) as r.\n                       destruct r; apply eq_sym in Heqr.\n                           destruct p. inv JJ2'. \n                           exfalso. apply NV2_2. apply (VBj12_2 _ _ _ Heqr).\n                       remember (as_inj nu' b2) as rr.\n                       destruct rr; inv JJ2'. apply eq_sym in Heqrr.\n                       destruct p. \n                       destruct (mkInjections_3V _ _ _ _ _ _ _ _\n                                         _ _ HeqMKI VB12 VBj23_1 _ _ _ H6)\n                           as [KK | [KK | KK]].\n                         destruct KK as [KK _]. rewrite KK in Heqr; discriminate.\n                         destruct KK as [? [? [? [? ?]]]]. subst. \n                           eapply MemInjNu'. \n                              apply NEQ. \n                              assumption.\n                              assumption. \n                              rewrite Zplus_0_r. apply PERM.\n                              rewrite Zplus_0_r. apply PERM2.\n\n                         destruct KK as [MM2 [BB2 [nbm\n                                           [zz [X2 Y2]]]]]. subst.\n                           exfalso. apply (Pos.add_no_neutral (Mem.nextblock m2) MM2).\n                                 rewrite Pos.add_comm. rewrite <- nbm. trivial.\n                 (*source j12' ofs2 = None*)\n                    unfold Mem.perm in H3. rewrite Invalid2 in H3. inv H3.\n                 (*source j12' ofs1 = None*)\n                    unfold Mem.perm in H2. rewrite Invalid1 in H2. inv H2. \n            destruct KK as [M2 [BM [J2' B2']]]; subst.\n          (*third case where both blocks are in m2' but not in m2*)\n              assert (j23_None1: as_inj nu23 (Mem.nextblock m2 + M1)%positive = None).\n                 remember (as_inj nu23 (Mem.nextblock m2 + M1)%positive) as d. \n                 destruct d; trivial. \n                 apply eq_sym in Heqd. destruct p. \n                 specialize (VBj23_1 _ _ _ Heqd). clear - VBj23_1.\n                 unfold Mem.valid_block in VBj23_1. xomega.\n              assert (j23_None2:  as_inj nu23 (Mem.nextblock m2 + M2)%positive = None).\n                 remember (as_inj nu23 (Mem.nextblock m2 + M2)%positive) as d. \n                 destruct d; trivial. \n                 apply eq_sym in Heqd. destruct p. \n                 specialize (VBj23_1 _ _ _ Heqd). clear - VBj23_1.\n                 unfold Mem.valid_block in VBj23_1. xomega.\n              destruct (sep23 _ _ _ j23_None1 H0) as [NV2_1 NV3_1].\n              destruct (sep23 _ _ _ j23_None2 H1) as [NV2_2 NV3_2].\n              assert (Max3_1:= Perm23' _ _ _ _ _ _ H0 H2).\n              assert (Max3_2:= Perm23' _ _ _ _ _ _ H1 H3).\n              assert (NEQ : (Mem.nextblock m1 + M1)%positive <> (Mem.nextblock m1 + M2)%positive). \n                intros NN. apply Pos.add_cancel_l in NN. subst. \n                apply H; trivial. \n              destruct (ACCESS (Mem.nextblock m2 + M1)%positive) as [_ Invalid1].\n              specialize (Invalid1 NV2_1 Max ofs1).\n                           \n              remember (source (removeUndefs (as_inj nu12) (as_inj nu') prej12') \n                    m1' ((Mem.nextblock m2 +M1)%positive) ofs1) as d.\n              destruct d.\n              (*source j12' ofs1 = Some*)\n                 destruct p. \n                 rewrite (perm_subst _ _ _ _ _ _ _ Invalid1) in H2.\n                 clear Invalid1.\n                 destruct (ACCESS  ((Mem.nextblock m2 + M2)%positive)) as [_ Invalid2].\n                 specialize (Invalid2 NV2_2 Max ofs2).\n\n                 remember (source (removeUndefs (as_inj nu12) (as_inj nu') prej12')  m1'\n                         ((Mem.nextblock m2 + M2)%positive) ofs2) as d.\n                 destruct d.\n                 (*source j12' ofs2 = Some*)\n                     destruct p. \n                     rewrite (perm_subst _ _ _ _ _ _ _ Invalid2) in H3. \n                     clear Invalid2.\n                     rename b into b1. rename z into z1. rename b0 into b2.\n                     rename z0 into z2.\n\n                     destruct (source_SomeE _ _ _ _ _ Heqd) \n                         as [bb1 [dd1 [ofs11 [PP [VB [ JJ' [PERM Off1]]]]]]].\n                     clear Heqd. subst. apply eq_sym in PP. inv PP.\n                     unfold removeUndefs in JJ'.\n                     remember (as_inj nu12 b1) as q.\n                     destruct q; apply eq_sym in Heqq.\n                       destruct p. inv JJ'. exfalso. apply NV2_1. \n                           apply (VBj12_2 _ _ _ Heqq).\n                     remember (as_inj nu' b1) as qq.\n                     destruct qq; inv JJ'. apply eq_sym in Heqqq.\n                     destruct p. \n                     destruct (mkInjections_3V _ _ _ _ _ _ _ _ _ _ \n                              HeqMKI VB12 VBj23_1 _ _ _ H5) as [HH | [HH |HH]].\n                     destruct HH as [HH _]. rewrite HH in Heqq; discriminate.\n                     destruct HH as [? [? [? [? ?]]]]; subst. \n                       exfalso. rewrite Pos.add_comm in H6. \n                        apply Pos.add_no_neutral in H6. apply H6.\n                     destruct HH as [MM1 [? [? [? [? ?]]]]]; subst.\n                       apply Pos.add_reg_l in H6. apply eq_sym in H6. subst.\n                       destruct (source_SomeE _ _ _ _ _ Heqd0) as \n                           [bb2 [dd2 [ofs22 [PP2 [VB2 [ JJ2' [PERM2 Off2]]]]]]].\n                       clear Heqd0. subst. apply eq_sym in PP2. inv PP2.\n                       unfold removeUndefs in JJ2'.\n                       remember (as_inj nu12 b2) as r.\n                       destruct r; apply eq_sym in Heqr.\n                           destruct p. inv JJ2'. \n                           exfalso. apply NV2_2. apply (VBj12_2 _ _ _ Heqr).\n                       remember (as_inj nu' b2) as rr.\n                       destruct rr; inv JJ2'. apply eq_sym in Heqrr.\n                       destruct p. \n                       destruct (mkInjections_3V _ _ _ _ _ _ _ _\n                                         _ _ HeqMKI VB12 VBj23_1 _ _ _ H6)\n                           as [KK | [KK | KK]].\n                         destruct KK as [KK _]. rewrite KK in Heqr; discriminate.\n                         destruct KK as [? [? [? [? ?]]]]. subst.\n                           exfalso. apply (Pos.add_no_neutral (Mem.nextblock m2) M2).\n                                 rewrite Pos.add_comm. trivial.\n                            \n                         destruct KK as [MM2 [BB2 [nbm\n                                           [zz [X2 Y2]]]]]. subst.\n                           apply Pos.add_cancel_l in nbm. subst.\n                           eapply MemInjNu'. \n                              apply NEQ. \n                              assumption.\n                              assumption. \n                              rewrite Zplus_0_r. apply PERM.\n                              rewrite Zplus_0_r. apply PERM2.\n                 (*source j12' ofs2 = None*)\n                    unfold Mem.perm in H3. rewrite Invalid2 in H3. inv H3.\n                 (*source j12' ofs1 = None*)\n                    unfold Mem.perm in H2. rewrite Invalid1 in H2. inv H2. \n\n   (*mi_representable*) intros. rename b into b2.\n       destruct (mkInjections_4Val _ _ _ _ _ _ _ _ _ _ HeqMKI VBj23_1 _ _ _ H)\n       as [HH | [ HH | HH]].\n       (*first case*)\n         destruct HH as [j23b2 Val2].\n         destruct (ACCESS b2) as [Valid _]. \n         rewrite j23b2 in Valid.\n         specialize (Valid Val2).\n         remember (locBlocksSrc nu23 b2) as MyB2.\n         destruct MyB2; apply eq_sym in HeqMyB2.\n         (*case locBlocksSrc nu23 b2 = true*)\n           remember (pubBlocksSrc nu23 b2) as PubB2.\n           destruct PubB2; apply eq_sym in HeqPubB2.\n           (*case pubBlocksSrc nu23 b2 = true*)\n             destruct H0.\n             (*location ofs*)\n               specialize (Valid Max (Int.unsigned ofs)).\n               remember (source (local_of nu12) m1 b2 (Int.unsigned ofs)) as d.\n               destruct d.  \n               (*source ... m1 b2 (Int.unsigned ofs) = Some p*)\n                 destruct p.\n                 destruct (source_SomeE _ _ _ _ _ Heqd) \n                   as [b1 [delta1 [ofs1 [PP [VB [ J12 [PERM Off1]]]]]]].\n                 clear Heqd. subst. apply eq_sym in PP. inv PP.\n                 assert (PP2: Mem.perm m2 b2 (Int.unsigned ofs) Max Nonempty). \n                   remember (pubBlocksSrc nu12 b) as PubB1.\n                   destruct PubB1; apply eq_sym in HeqPubB1;\n                   rewrite (perm_subst _ _ _ _ _ _ _ Valid) in H0; clear Valid.\n                      rewrite Off1. eapply MInj12. apply local_in_all; eassumption. apply PERM. \n                      assumption. \n                 eapply MInj23. apply j23b2. \n                   left. assumption. \n               (*source  j12 m1 b2 (Int.unsigned ofs) = None0*)\n                 rewrite (perm_subst _ _ _ _ _ _ _ Valid) in H0; clear Valid.\n                 eapply MInj23. apply j23b2. \n                 left. apply H0. \n             (*location ofs -1*)\n               specialize (Valid Max (Int.unsigned ofs -1)).\n               remember (source (local_of nu12) m1 b2 (Int.unsigned ofs -1)) as d.\n               destruct d.  \n               (*source .. m1 b2 (Int.unsigned ofs-1) = Some p*)\n                 destruct p.\n                 destruct (source_SomeE _ _ _ _ _ Heqd) \n                   as [b1 [delta1 [ofs1 [PP [VB [ J12 [PERM Off1]]]]]]].\n                 clear Heqd. subst. apply eq_sym in PP. inv PP.\n                 assert (PP2: Mem.perm m2 b2 (Int.unsigned ofs -1) Max Nonempty). \n                   remember (pubBlocksSrc nu12 b) as PubB1.\n                   destruct PubB1; apply eq_sym in HeqPubB1;\n                   rewrite (perm_subst _ _ _ _ _ _ _ Valid) in H0; clear Valid.\n                      rewrite Off1. eapply MInj12. apply local_in_all; eassumption. apply PERM. \n                      assumption. \n                 eapply MInj23. apply j23b2. \n                   right. assumption. \n               (*source  j12 m1 b2 (Int.unsigned ofs) = None0*)\n                 rewrite (perm_subst _ _ _ _ _ _ _ Valid) in H0; clear Valid.\n                 eapply MInj23. apply j23b2. \n                 right. apply H0. \n           (*case pubBlocksSrc nu23 b2 = false*)\n             destruct H0.\n             (*location ofs*)\n               specialize (Valid Max (Int.unsigned ofs)).\n               rewrite (perm_subst _ _ _ _ _ _ _ Valid) in H0; clear Valid.\n               eapply MInj23. apply j23b2. \n               left. apply H0. \n             (*location ofs-1*)\n               specialize (Valid Max (Int.unsigned ofs-1)).\n               rewrite (perm_subst _ _ _ _ _ _ _ Valid) in H0; clear Valid.\n               eapply MInj23. apply j23b2. \n               right. apply H0. \n         (*case locBlocksSrc nu23 b2 = false*)\n             destruct H0.\n             (*location ofs*)\n               specialize (Valid Max (Int.unsigned ofs)).\n               remember (source (as_inj nu12) m1 b2 (Int.unsigned ofs)) as d.\n               destruct d.  \n               (*source ... m1 b2 (Int.unsigned ofs) = Some p*)\n                 destruct p.\n                 destruct (source_SomeE _ _ _ _ _ Heqd) \n                   as [b1 [delta1 [ofs1 [PP [VB [ J12 [PERM Off1]]]]]]].\n                 clear Heqd. subst. apply eq_sym in PP. inv PP.\n                 assert (PP2: Mem.perm m2 b2 (Int.unsigned ofs) Max Nonempty).\n                   rewrite Off1. eapply MInj12; eassumption. \n                 eapply MInj23. apply j23b2. \n                   left. assumption. \n               (*source  j12 m1 b2 (Int.unsigned ofs) = None0*)\n                 unfold Mem.perm in H0; rewrite Valid in H0; simpl in H0. contradiction.\n             (*location ofs-1*)\n               specialize (Valid Max (Int.unsigned ofs-1)).\n               remember (source (as_inj nu12) m1 b2 (Int.unsigned ofs-1)) as d.\n               destruct d.  \n               (*source ... m1 b2 (Int.unsigned ofs) = Some p*)\n                 destruct p.\n                 destruct (source_SomeE _ _ _ _ _ Heqd) \n                   as [b1 [delta1 [ofs1 [PP [VB [ J12 [PERM Off1]]]]]]].\n                 clear Heqd. subst. apply eq_sym in PP. inv PP.\n                 assert (PP2: Mem.perm m2 b2 (Int.unsigned ofs-1) Max Nonempty).\n                   rewrite Off1. eapply MInj12; eassumption. \n                 eapply MInj23. apply j23b2. \n                   right. assumption. \n               (*source  j12 m1 b2 (Int.unsigned ofs) = None0*)\n                 unfold Mem.perm in H0; rewrite Valid in H0; simpl in H0. contradiction.\n       (*second case*)\n         destruct HH as [? [j'b2 Val2']]. subst.\n         destruct (ACCESS (Mem.nextblock m2)) as [_ InValid].\n         assert (NVB2: ~Mem.valid_block m2 (Mem.nextblock m2)).\n            unfold Mem.valid_block; xomega.\n         specialize (InValid NVB2).\n         destruct H0.\n         (*location ofs*)\n           specialize (InValid Max (Int.unsigned ofs)).\n           remember (source (removeUndefs (as_inj nu12) (as_inj nu') prej12') m1' (Mem.nextblock m2)\n                            (Int.unsigned ofs)) as d.\n           destruct d.  \n           (*source .. = Some p*)\n             destruct p.\n             destruct (source_SomeE _ _ _ _ _ Heqd) \n                 as [b1 [delta1 [ofs1 [PP [VB [ J12 [PERM Off1]]]]]]].\n             clear Heqd. subst. apply eq_sym in PP. inv PP.\n             unfold removeUndefs in J12.\n             case_eq (as_inj nu12 b); intros. \n                destruct p; rewrite H1 in J12. inv J12.\n                exfalso. apply NVB2. apply (VBj12_2 _ _ _ H1).\n             rewrite H1 in J12.\n             case_eq (as_inj nu' b); intros.\n                destruct p; rewrite H2 in J12.\n                destruct (mkInjections_3V _ _ _ _ _ _ _ _ _ _ HeqMKI \n                    VB12 VBj23_1 _ _ _ J12) as [KK | [KK |KK]].\n                destruct KK as [KK _]; rewrite KK in H1; discriminate.\n                destruct KK as [? [_ [? [? ?]]]]; subst.\n                    rewrite Zplus_0_r in *. subst.\n                    eapply MemInjNu'. apply j'b2. left; apply PERM. \n                destruct KK as [m [_ [? _]]]. \n                    exfalso. clear -H3. apply (add_no_neutral2 _ _ H3).\n             rewrite H2 in J12. inv J12.\n           (*source  j12 m1 b2 (Int.unsigned ofs) = None0*)\n             unfold Mem.perm in H0. rewrite InValid in H0.\n             contradiction.\n         (*location ofs -1*)\n           specialize (InValid Max (Int.unsigned ofs-1)).\n           remember (source (removeUndefs (as_inj nu12) (as_inj nu') prej12') m1' (Mem.nextblock m2)\n                            (Int.unsigned ofs-1)) as d.\n           destruct d.  \n           (*source .. = Some p*)\n             destruct p.\n             destruct (source_SomeE _ _ _ _ _ Heqd) \n                 as [b1 [delta1 [ofs1 [PP [VB [ J12 [PERM Off1]]]]]]].\n             clear Heqd. subst. apply eq_sym in PP. inv PP.\n             unfold removeUndefs in J12.\n             case_eq (as_inj nu12 b); intros. \n                destruct p; rewrite H1 in J12. inv J12.\n                exfalso. apply NVB2. apply (VBj12_2 _ _ _ H1).\n             rewrite H1 in J12.\n             case_eq (as_inj nu' b); intros.\n                destruct p; rewrite H2 in J12.\n                destruct (mkInjections_3V _ _ _ _ _ _ _ _ _ _ HeqMKI \n                    VB12 VBj23_1 _ _ _ J12) as [KK | [KK |KK]].\n                destruct KK as [KK _]; rewrite KK in H1; discriminate.\n                destruct KK as [? [_ [? [? ?]]]]; subst.\n                    rewrite Zplus_0_r in *. subst.\n                    eapply MemInjNu'. apply j'b2. right; apply PERM. \n                destruct KK as [m [_ [? _]]]. \n                    exfalso. clear -H3. apply (add_no_neutral2 _ _ H3).\n             rewrite H2 in J12. inv J12.\n           (*source  j12 m1 b2 (Int.unsigned ofs-1) = None0*)\n             unfold Mem.perm in H0. rewrite InValid in H0.\n             contradiction.\n       (*third case*)\n         destruct HH as [m [? [j'b2 Val2']]]; subst.\n         destruct (ACCESS ((Mem.nextblock m2+m)%positive)) as [_ InValid].\n         assert (NVB2: ~Mem.valid_block m2 ((Mem.nextblock m2+m)%positive)).\n            unfold Mem.valid_block; xomega.\n         destruct H0.\n         (*location ofs*)\n           specialize (InValid NVB2 Max (Int.unsigned ofs)).\n           remember (source (removeUndefs (as_inj nu12) (as_inj nu') prej12') m1' \n                            ((Mem.nextblock m2+m)%positive)\n                            (Int.unsigned ofs)) as d.\n           destruct d.  \n           (*source .. = Some p*)\n             destruct p.\n             destruct (source_SomeE _ _ _ _ _ Heqd) \n                 as [b1 [delta1 [ofs1 [PP [VB [ J12 [PERM Off1]]]]]]].\n             clear Heqd. subst. apply eq_sym in PP. inv PP.\n             unfold removeUndefs in J12.\n             case_eq (as_inj nu12 b); intros. \n                destruct p; rewrite H1 in J12. inv J12.\n                exfalso. apply NVB2. apply (VBj12_2 _ _ _ H1).\n             rewrite H1 in J12.\n             case_eq (as_inj nu' b); intros.\n                destruct p; rewrite H2 in J12.\n                destruct (mkInjections_3V _ _ _ _ _ _ _ _ _ _ HeqMKI \n                    VB12 VBj23_1 _ _ _ J12) as [KK | [KK |KK]].\n                destruct KK as [KK _]; rewrite KK in H1; discriminate.\n                destruct KK as [? [? [? [? ?]]]]; subst.\n                    exfalso. clear -H4. apply eq_sym in H4. \n                    apply (add_no_neutral2 _ _ H4).\n                destruct KK as [mm [? [? [? [? ?]]]]]. subst.\n                   assert (mm = m).\n                      clear -H4. \n                      apply Pos.add_reg_l in H4. \n                      subst; trivial.\n                   rewrite Zplus_0_r in *. subst.\n                   eapply MemInjNu'. apply j'b2. left. apply PERM.\n             rewrite H2 in J12. inv J12.\n           (*source  j12 m1 b2 (Int.unsigned ofs) = None0*)\n             unfold Mem.perm in H0. rewrite InValid in H0.\n             contradiction.\n         (*location ofs -1*)\n           specialize (InValid NVB2 Max (Int.unsigned ofs-1)).\n           remember (source (removeUndefs (as_inj nu12) (as_inj nu') prej12') m1' \n                            ((Mem.nextblock m2+m)%positive)\n                            (Int.unsigned ofs-1)) as d.\n           destruct d.  \n           (*source .. = Some p*)\n             destruct p.\n             destruct (source_SomeE _ _ _ _ _ Heqd) \n                 as [b1 [delta1 [ofs1 [PP [VB [ J12 [PERM Off1]]]]]]].\n             clear Heqd. subst. apply eq_sym in PP. inv PP.\n             unfold removeUndefs in J12.\n             case_eq (as_inj nu12 b); intros. \n                destruct p; rewrite H1 in J12. inv J12.\n                exfalso. apply NVB2. apply (VBj12_2 _ _ _ H1).\n             rewrite H1 in J12.\n             case_eq (as_inj nu' b); intros.\n                destruct p; rewrite H2 in J12.\n                destruct (mkInjections_3V _ _ _ _ _ _ _ _ _ _ HeqMKI \n                    VB12 VBj23_1 _ _ _ J12) as [KK | [KK |KK]].\n                destruct KK as [KK _]; rewrite KK in H1; discriminate.\n                destruct KK as [? [? [? [? ?]]]]; subst.\n                    exfalso. clear -H4. apply eq_sym in H4. \n                    apply (add_no_neutral2 _ _ H4).\n                destruct KK as [mm [? [? [? [? ?]]]]]. subst.\n                   assert (mm = m).\n                      clear -H4. \n                      apply Pos.add_reg_l in H4. \n                      subst; trivial.\n                   rewrite Zplus_0_r in *. subst.\n                   eapply MemInjNu'. apply j'b2. right. apply PERM.\n             rewrite H2 in J12. inv J12.\n           (*source  j12 m1 b2 (Int.unsigned ofs-1) = None0*)\n             unfold Mem.perm in H0. rewrite InValid in H0.\n             contradiction.\n\nspecialize (mkInjections_3V _ _ _ _ _ _ _ _ _ _ HeqMKI Val12 Val23).\nintros mkiVal3.\nspecialize (mkInjections_4Val _ _ _ _ _ _ _ _ _ _ HeqMKI Val23). intros mkiVal4.\nspecialize (mkInjections_5 _ _ _ _ _ _ _ _ _ _ HeqMKI VBj12_1 VBj12_2 VBj23_1 VBj'). intros mkiVal5.\nclear CONT ACCESS HeqMKI.\nassert (GOAL1: nu' =\ncompose_sm\n  (convertL nu12 j12'\n     (fun b : block => DomSrc nu' b && negb (DomSrc nu12 b))\n     (FreshDom (as_inj nu23) j23'))\n  (convertR nu23 j23' (FreshDom (as_inj nu23) j23')\n     (fun b : block => DomTgt nu' b && negb (DomTgt nu23 b)))).\n  destruct ExtIncr as [AA [BB [CC [DD [EE [FF [GG [HH [II JJ]]]]]]]]]; simpl in *.\n  unfold compose_sm; simpl in *. clear ConvertL_J12'. clear ConvertR_J23'.\n  rewrite convertL_extern, convertL_local, convertL_frgnBlocksSrc, \n          convertL_pubBlocksSrc, convertL_locBlocksSrc, convertL_extBlocksSrc.\n  rewrite convertR_extern, convertR_local, convertR_frgnBlocksTgt, \n          convertR_pubBlocksTgt, convertR_locBlocksTgt, convertR_extBlocksTgt.\n  destruct nu' as [locBSrc' locBTgt' pSrc' pTgt' local' extBSrc' extBTgt' fSrc' fTgt' extern'].\n  simpl in *. unfold as_inj in *; simpl in *.\n  f_equal; simpl; subst; simpl in *; trivial.\n  (*1/3*) \n     extensionality b. \n     specialize (disjoint_extern_local_Src _ WDnu' b). intros.\n     unfold DomSrc, DomTgt in *; simpl in *.\n     specialize (CC b).  \n     clear - CC H.    \n     remember (locBlocksSrc nu12 b) as q.\n     remember (extBlocksSrc nu12 b) as t.\n     destruct q; destruct t; simpl in *; intuition.\n     rewrite andb_true_r. trivial.\n     rewrite andb_true_r. trivial.\n  (*2/3*)\n     extensionality b.\n     specialize (disjoint_extern_local_Tgt _ WDnu' b). intros.\n     unfold DomSrc, DomTgt in *; simpl in *.\n     specialize (DD b).\n     clear - DD H. \n     remember (locBlocksTgt nu23 b) as q.\n     remember (extBlocksTgt nu23 b) as t.\n     destruct q; destruct t; simpl in *; intuition.\n     rewrite andb_true_r. trivial.\n     rewrite andb_true_r. trivial.\n  (*3/3*)\n     clear Inj12' NOVj12' Inj23' UNCHC MemInjNu' Fwd2 MInj23 Fwd1 MInj12 UnchPrivSrc UnchLOOR13 VBj'\n           Fwd1 Fwd3 SMV12 SMV23 SMvalNu' InjSep VBj23_2 sep23 NB1 SMInjSep\n           VBj23' Val12 Val23 mkiVal3 m3 m1' m3'.\n     extensionality b1.\n     remember (extern' b1) as d.\n     destruct d; apply eq_sym in Heqd.\n     (*case externNu' b1 = Some p*)\n       destruct p as [b3 delta].\n       assert (J: join extern' (compose_meminj (local_of nu12) (local_of nu23)) b1 = Some (b3, delta)).\n         apply join_incr_left. apply Heqd.\n       rewrite ID in J; clear ID.\n       destruct (compose_meminjD_Some _ _ _ _ _ J) \n        as [b2 [d1 [d2 [J1 [J2 D]]]]]; subst; clear J.\n       apply eq_sym. \n       eapply compose_meminjI_Some with (b2:=b2).\n       (*condition 1*)\n         remember (extern_of nu12 b1) as q.\n         destruct q; apply eq_sym in Heqq.\n         (*case extern_of nu12 b1 = Some p*)\n           destruct p as [bb2 dd1].\n           unfold join. rewrite Heqq.\n           apply extern_in_all in Heqq.\n           apply inc12 in Heqq. unfold as_inj in Heqq. simpl in *. \n             rewrite Heqq in J1. apply J1.\n         (*case extern_of nu12 b1 = Some p*)\n           unfold join. rewrite Heqq.\n           remember (local_of nu12 b1) as w.\n           destruct w; trivial; apply eq_sym in Heqw.\n           destruct p as [bb dd].\n           assert (locBlocksSrc nu12 b1 = true).\n             eapply local_locBlocks; eassumption.\n           assert (locBlocksSrc nu12 b1 = false).\n             eapply (extern_DomRng' _ WDnu'). simpl. apply Heqd.\n           rewrite H0 in H. inv H.\n       (*condition 2*)      \n         unfold join.\n         remember (extern_of nu23 b2) as q.\n         destruct q; apply eq_sym in Heqq.\n           destruct p.\n           rewrite (inject_incr_coincide _ _ inc23 _ _ J2 _ \n               (extern_in_all _ _ _ _ Heqq)). trivial.\n         remember (local_of nu23 b2) as w.\n         destruct w; apply eq_sym in Heqw; trivial.\n         destruct p. \n         assert (E:= inject_incr_coincide _ _ inc23 _ _ J2 _ \n               (local_in_all _ WDnu23 _ _ _ Heqw)); inv E.\n         assert (locBlocksTgt nu23 b = true).\n           eapply local_locBlocks; eassumption.\n         assert (locBlocksTgt nu23 b = false).\n           eapply (extern_DomRng' _ WDnu'). simpl. apply Heqd.\n         rewrite H0 in H. inv H.\n     (*externNu' b1 = None*)\n        unfold as_inj in inc12. simpl in inc12.\n        remember (compose_meminj (local_of nu12) (local_of nu23) b1) as q.\n        destruct q; apply eq_sym in Heqq.\n        (*case compose_meminj (local_of nu12) (local_of nu23) b1 = Some p*)\n          destruct p as [b3 delta].\n          destruct (compose_meminjD_Some _ _ _ _ _ Heqq) \n            as [b2 [d1 [d2 [Loc12 [Loc23 D]]]]]; subst; clear Heqq.\n          apply eq_sym.\n          destruct (disjoint_extern_local _ WDnu12 b1).\n            unfold compose_meminj, join. rewrite H, Loc12. trivial.\n          rewrite H in Loc12. inv Loc12.\n        (*case compose_meminj (local_of nu12) (local_of nu23) b1 = None*)\n          assert (compose_meminj\n            (removeUndefs (join (extern_of nu12) (local_of nu12))\n               (join extern' (compose_meminj (local_of nu12) (local_of nu23))) prej12')\n            j23' b1 = None).\n              rewrite <- ID. unfold join. rewrite Heqd. trivial.\n          clear ID.\n          remember (extern_of nu12 b1) as w.\n          destruct w; apply eq_sym in Heqw.\n          (*case extern_of nu12 b1 = Some p*)\n            destruct p as [b2 d1].\n            assert (R: removeUndefs (join (extern_of nu12) (local_of nu12))\n                        (join extern' (compose_meminj (local_of nu12) (local_of nu23)))\n                         prej12' b1 = Some (b2, d1)).\n                apply inc12. apply extern_in_all. apply Heqw.\n            destruct (compose_meminjD_None _ _ _ H); clear H.\n               rewrite H0 in R. inv R.\n            destruct H0 as [bb2 [dd1 [XX J23']]].\n            rewrite R in XX. apply eq_sym in XX. inv XX.\n            apply eq_sym.\n            apply compose_meminjI_None. right.  \n            exists b2, d1; split. apply join_incr_left. assumption.          \n            remember (extern_of nu23 b2) as t.\n            destruct t; apply eq_sym in Heqt.\n               destruct p as [b3 d2].\n               apply extern_in_all in Heqt. apply inc23 in Heqt.\n               rewrite Heqt in J23'. discriminate.\n            unfold join. rewrite Heqt, J23'.\n              destruct (local_of nu23 b2); trivial.\n          (*case extern_of nu12 b1 = None*)\n            destruct (compose_meminjD_None _ _ _ Heqq); clear Heqq.\n            (*case local_of nu12 b1 = None*)\n              clear inc12.\n              destruct (compose_meminjD_None _ _ _ H); clear H.\n              (*case removeUndefs ... = None*)\n                apply eq_sym.\n                apply compose_meminjI_None. left.\n                apply joinI_None. assumption.\n                rewrite H0. apply H1.\n              (*case removeUndefs ... = Some*)\n                destruct H1 as [b2 [d1 [R J23']]]. \n                apply eq_sym.\n                apply compose_meminjI_None. right.\n                exists b2, d1; split.\n                  unfold join. rewrite Heqw. rewrite H0. apply R.\n                assert (as_inj nu23 b2 = None).\n                  apply (inject_incr_inv _ _ inc23 _ J23').\n                destruct (joinD_None _ _ _ H).\n                unfold join. rewrite H1, H2. apply J23'.\n            (*case local_of nu12 b1 = Some*)\n              destruct H0 as [b2 [d1 [Loc1 Loc2]]].\n              apply eq_sym.\n              apply compose_meminjI_None. left.\n              destruct (disjoint_extern_local _ WDnu12 b1).\n                unfold join. rewrite H0, Loc1. trivial.\n              rewrite H0 in Loc1. inv Loc1.\nsplit; trivial.\nassert (GOAL2: extern_incr nu12\n  (convertL nu12 (removeUndefs (as_inj nu12) (as_inj nu') prej12')\n     (fun b : block => DomSrc nu' b && negb (DomSrc nu12 b))\n     (FreshDom (as_inj nu23) j23'))).\n  split. rewrite convertL_extern. apply join_incr_left.\n  split. rewrite convertL_local. trivial.\n  split. rewrite convertL_extBlocksSrc. intuition.\n  split. rewrite convertL_extBlocksTgt. intuition. \n  split. rewrite convertL_locBlocksSrc. trivial.\n  split. rewrite convertL_locBlocksTgt. trivial. \n  split. rewrite convertL_pubBlocksSrc. trivial.\n  split. rewrite convertL_pubBlocksTgt. trivial.\n  split. rewrite convertL_frgnBlocksSrc. trivial. \n  rewrite convertL_frgnBlocksTgt. trivial. \nsplit. rewrite <- Heqj12' in GOAL2. assumption.\nassert (GOAL3: (extern_incr nu23\n  (convertR nu23 j23' (FreshDom (as_inj nu23) j23')\n     (fun b : block => DomTgt nu' b && negb (DomTgt nu23 b))))).\n  clear GOAL1 GOAL2 ConvertL_J12' ConvertR_J23'.\n  split. rewrite convertR_extern. apply join_incr_left.\n  split. rewrite convertR_local. trivial.\n  split. rewrite convertR_extBlocksSrc. intuition.\n  split. rewrite convertR_extBlocksTgt. intuition. \n  split. rewrite convertR_locBlocksSrc. trivial.\n  split. rewrite convertR_locBlocksTgt. trivial. \n  split. rewrite convertR_pubBlocksSrc. trivial.\n  split. rewrite convertR_pubBlocksTgt. trivial.\n  split. rewrite convertR_frgnBlocksSrc. trivial.\n  rewrite convertR_frgnBlocksTgt. trivial. \nsplit. assumption.\nassert (GOAL4: sm_inject_separated nu12\n  (convertL nu12 j12'\n     (fun b : block => DomSrc nu' b && negb (DomSrc nu12 b))\n     (FreshDom (as_inj nu23) j23')) m1 m2).\n  split. rewrite ConvertL_J12'; clear ConvertL_J12' GOAL1 ConvertR_J23'.\n         intros.\n         destruct (sep12 _ _ _ H H0) as [NV1 NV2].\n         split.\n           remember (DomSrc nu12 b1) as q.\n           destruct q; trivial; apply eq_sym in Heqq.\n           apply SMV12 in Heqq. contradiction.\n         remember (DomTgt nu12 b2) as q.\n           destruct q; trivial; apply eq_sym in Heqq.\n           apply SMV12 in Heqq. contradiction.\n  rewrite convertL_DomSrc, convertL_DomTgt.\n  split; intros; rewrite H in H0; simpl in *.\n         rewrite andb_true_r in H0.\n         eapply SMInjSep. apply H. apply H0.\n       unfold FreshDom in H0.\n           remember (j23' b2) as q.\n           destruct q; apply eq_sym in Heqq.\n              destruct p.\n              remember (as_inj nu23 b2) as w.\n              destruct w; apply eq_sym in Heqw. inv H0.\n              eapply sep23; eassumption.\n           inv H0.\nsplit. assumption.\nassert (GOAL5: sm_inject_separated nu23\n  (convertR nu23 j23' (FreshDom (as_inj nu23) j23')\n     (fun b : block => DomTgt nu' b && negb (DomTgt nu23 b))) m2 m3).\n  split. rewrite ConvertR_J23'; clear ConvertL_J12' GOAL1 ConvertR_J23'. \n         intros.\n         destruct (sep23 _ _ _ H H0) as [NV1 NV2].\n         split.\n           remember (DomSrc nu23 b1) as q.\n           destruct q; trivial; apply eq_sym in Heqq.\n           apply SMV23 in Heqq. contradiction.\n         remember (DomTgt nu23 b2) as q.\n           destruct q; trivial; apply eq_sym in Heqq.\n           apply SMV23 in Heqq. contradiction.\n  rewrite convertR_DomSrc, convertR_DomTgt.\n  split; intros; rewrite H in H0; simpl in H0.\n         unfold FreshDom in H0.\n           remember (j23' b1) as q.\n           destruct q; apply eq_sym in Heqq.\n              destruct p.\n              remember (as_inj nu23 b1) as w.\n              destruct w; apply eq_sym in Heqw. inv H0.\n              eapply sep23; eassumption.\n           inv H0.\n           rewrite andb_true_r in H0.\n           eapply SMInjSep. apply H. apply H0.\nsplit. assumption.\nassert (GOAL6: sm_valid\n  (convertL nu12 j12'\n     (fun b : block => DomSrc nu' b && negb (DomSrc nu12 b))\n     (FreshDom (as_inj nu23) j23')) m1' m2').\n  split. unfold DOM. rewrite convertL_DomSrc.\n         clear ConvertL_J12' GOAL1 ConvertR_J23'. \n         intros.\n         remember (DomSrc nu12 b1) as d.\n         destruct d; apply eq_sym in Heqd; simpl in H.\n           apply Fwd1. \n           eapply SMV12. apply Heqd.\n         rewrite andb_true_r in H.\n           eapply SMvalNu'. apply H.\n  unfold RNG. rewrite convertL_DomTgt.\n         intros.\n         remember (DomTgt nu12 b2) as d.\n         destruct d; apply eq_sym in Heqd; simpl in H.\n           apply Fwd2. \n           eapply SMV12. apply Heqd.\n         unfold FreshDom in H.\n           remember (j23' b2) as q.\n           destruct q; apply eq_sym in Heqq.\n              destruct p. \n              remember (as_inj nu23 b2) as w.\n              destruct w; apply eq_sym in Heqw. inv H.\n              apply (VBj23' _ _ _ Heqq).\n            inv H.\nsplit. assumption.\nsplit. (*This is GOAL7: sm_valid\n  (convertR nu23 j23' (FreshDom (as_inj nu23) j23')\n     (fun b : block => DomTgt nu' b && negb (DomTgt nu23 b))) m2' m3').*)\n  split. unfold DOM. rewrite convertR_DomSrc.\n         clear ConvertL_J12' GOAL1 ConvertR_J23'. \n         intros.\n         remember (DomSrc nu23 b1) as d.\n         destruct d; apply eq_sym in Heqd; simpl in H.\n           apply Fwd2. \n           eapply SMV23. apply Heqd.\n         unfold FreshDom in H.\n           remember (j23' b1) as q.\n           destruct q; apply eq_sym in Heqq.\n              destruct p. \n              remember (as_inj nu23 b1) as w.\n              destruct w; apply eq_sym in Heqw. inv H.\n              apply (VBj23' _ _ _ Heqq). \n            inv H.\n  unfold RNG. rewrite convertR_DomTgt.\n         intros.\n         remember (DomTgt nu23 b2) as d.\n         destruct d; apply eq_sym in Heqd; simpl in H.\n           apply Fwd3. \n           eapply SMV23. apply Heqd.\n         rewrite andb_true_r in H.\n           eapply SMvalNu'. apply H.\nsplit. (*Glue invariant*) \n  split. (*This is GOAL8: SM_wd\n  (convertL nu12 f\n     (fun b : block => DomSrc nu' b && negb (DomSrc nu12 b))\n     (FreshDom (as_inj nu23) j23'))).*)\n   clear ConvertL_J12' ConvertR_J23'. \n   split. \n   (*1/8*) rewrite convertL_locBlocksSrc, convertL_extBlocksSrc.\n           intros. unfold DomSrc.\n           specialize (disjoint_extern_local_Src _ WDnu12 b); intros.\n           remember (locBlocksSrc nu12 b) as d.\n           destruct d; apply eq_sym in Heqd.\n             destruct H. inv H.\n             rewrite H. right. simpl. rewrite andb_false_r. trivial.\n           left; trivial.\n   (*2/8*) rewrite convertL_locBlocksTgt, convertL_extBlocksTgt.\n           intros. \n           specialize (disjoint_extern_local_Tgt _ WDnu12 b); intros.\n           remember (locBlocksTgt nu12 b) as d.\n           destruct d; apply eq_sym in Heqd.\n             destruct H. inv H.\n             rewrite H. right. rewrite orb_false_l.\n             unfold FreshDom.\n             remember (j23' b) as q.\n             destruct q; trivial; apply eq_sym in Heqq.\n             destruct p. \n             remember (as_inj nu23 b) as t.\n             destruct t; trivial; apply eq_sym in Heqt.\n             assert (DomSrc nu23 b = false).\n                eapply GOAL5. apply Heqt.\n                destruct (joinD_None _ _ _ Heqt).\n                apply joinI. rewrite convertR_extern, convertR_local.\n                unfold join; simpl. rewrite H0, H1. left; eassumption.\n             unfold DomSrc in H0. rewrite GlueLoc in Heqd. rewrite Heqd in H0.\n               discriminate.\n           left; trivial.\n   (*3/8*) rewrite convertL_local, convertL_locBlocksSrc, convertL_locBlocksTgt.\n           apply WDnu12. \n   (*4/8*) rewrite convertL_extern, convertL_extBlocksSrc, convertL_extBlocksTgt.\n           intros. \n            destruct (joinD_Some _ _ _ _ _ H); clear H.\n              destruct (extern_DomRng _ WDnu12 _ _ _ H0) as [? ?].\n              intuition.\n            destruct H0.\n            remember (local_of nu12 b1) as d. \n            destruct d; apply eq_sym in Heqd. inv H0.\n              destruct (sep12 b1 b2 z); trivial.\n                apply joinI_None; trivial.\n            remember (DomSrc nu12 b1) as q.\n            destruct q; apply eq_sym in Heqq.\n              exfalso. apply H1. apply SMV12. apply Heqq.\n            remember (DomTgt nu12 b2) as w.\n            destruct w; apply eq_sym in Heqw.\n              exfalso. apply H2. apply SMV12. apply Heqw.\n            simpl. \n            unfold DomSrc in Heqq. apply orb_false_iff in Heqq. destruct Heqq.\n            unfold DomTgt in Heqw. apply orb_false_iff in Heqw. destruct Heqw.\n            rewrite H4, H6; simpl.\n            rewrite andb_true_r. clear GOAL1.\n            rewrite GlueLoc, GlueExt in *.\n            remember (as_inj nu23 b2) as ww.\n            destruct ww; apply eq_sym in Heqww.\n               destruct p.\n               destruct (as_inj_DomRng _ _ _ _ Heqww WDnu23). \n               unfold DomSrc in H7. rewrite H5, H6 in H7. discriminate. \n            remember (as_inj nu' b1) as qq.\n            destruct qq; apply eq_sym in Heqqq.\n               destruct p.\n               assert (DomSrc nu' b1 = true).\n                  eapply as_inj_DomRng. eassumption.\n                  assumption.\n               rewrite H7. split; trivial.\n               rewrite ID in Heqqq.\n               destruct (compose_meminjD_Some _ _ _ _ _ Heqqq)\n                  as [b22 [dd1 [dd2 [FF [JJ DD]]]]]; clear Heqqq.\n               clear ID. rewrite FF in H0. inv H0.\n               unfold FreshDom. rewrite JJ, Heqww. trivial.\n            rewrite Heqj12' in H0.\n            unfold removeUndefs in H0. rewrite Heqqq in H0.\n               assert (AI: as_inj nu12 b1 = None). apply joinI_None; eassumption.\n               rewrite AI in H0. inv H0.\n   (*5/8*) rewrite convertL_pubBlocksSrc, convertL_pubBlocksTgt, convertL_local.\n            apply WDnu12.\n   (*6/8*) rewrite convertL_frgnBlocksSrc, convertL_frgnBlocksTgt.\n            rewrite convertL_extern; trivial. intros. \n            destruct (frgnSrcAx _ WDnu12 _ H) as [b2 [d [EXT FT]]]. \n             unfold join. rewrite EXT. exists b2, d. split; trivial.\n   (*7/8*) rewrite convertL_pubBlocksTgt, convertL_locBlocksTgt.\n           apply WDnu12.\n   (*8/8*) rewrite convertL_frgnBlocksTgt, convertL_extBlocksTgt.\n           intros. rewrite (frgnBlocksExternTgt _ WDnu12 _ H). trivial.\nsplit. (*This is GOAL9: SM_wd\n  (convertR nu23 j23' (FreshDom (as_inj nu23) j23')\n     (fun b : block => DomTgt nu' b && negb (DomTgt nu23 b)))).*)\n   clear ConvertL_J12' ConvertR_J23'.\n   split.\n   (*1/8*) rewrite convertR_locBlocksSrc, convertR_extBlocksSrc.\n          intros.\n           specialize (disjoint_extern_local_Src _ WDnu23 b); intros.\n           remember (locBlocksSrc nu23 b) as d.\n           destruct d; apply eq_sym in Heqd.\n             destruct H. inv H.\n             rewrite H. right. rewrite orb_false_l.\n             unfold FreshDom.\n             remember (j23' b) as q.\n             destruct q; trivial; apply eq_sym in Heqq.\n             destruct p. \n             remember (as_inj nu23 b) as t.\n             destruct t; trivial; apply eq_sym in Heqt.\n             assert (DomSrc nu23 b = false).\n                eapply GOAL5. apply Heqt.\n                destruct (joinD_None _ _ _ Heqt).\n                apply joinI. rewrite convertR_extern, convertR_local.\n                unfold join; simpl. rewrite H0, H1. left; eassumption.\n             unfold DomSrc in H0. rewrite Heqd, H in H0.\n               discriminate.\n           left; trivial.\n   (*2/8*) rewrite convertR_locBlocksTgt, convertR_extBlocksTgt.\n           intros. specialize (disjoint_extern_local_Tgt _ WDnu23 b). intros.\n           remember (locBlocksTgt nu23 b) as d.\n           destruct d; apply eq_sym in Heqd.\n             destruct H. inv H.\n             right; rewrite H. simpl.\n             assert (DomTgt nu23 b = true).\n               unfold DomTgt; rewrite Heqd. trivial.\n             rewrite H0; simpl. rewrite andb_false_r. trivial.\n           left; trivial.\n   (*3/8*) rewrite convertR_locBlocksTgt, convertR_locBlocksSrc, convertR_local.\n           apply WDnu23. \n   (*4/8*) rewrite convertR_extBlocksTgt, convertR_extBlocksSrc, convertR_extern.\n           intros. \n           destruct (joinD_Some _ _ _ _ _ H) as [EXT23 | [EXT23 LOC23]]; clear H.\n              destruct (extern_DomRng _ WDnu23 _ _ _ EXT23).\n              rewrite H, H0; simpl. split; trivial.\n           remember ( local_of nu23 b1) as q.\n           destruct q; try inv LOC23; apply eq_sym in Heqq.\n           assert (AI: as_inj nu23 b1 = None). \n              apply joinI_None; assumption.\n           destruct GOAL5 as [? _].\n           destruct (H b1 b2 z AI); clear H.\n              apply joinI. rewrite convertR_extern, convertR_local.\n              unfold join. rewrite EXT23, Heqq. left; trivial.\n           unfold FreshDom. rewrite LOC23, AI, H1; simpl.\n           assert (DomTgt nu' b2 = true).\n             destruct (mkiVal4 _ _ _ LOC23) as [[MK _] | [MK | MK]].\n             (*1/3*) congruence. \n             (*2/3*) destruct MK as [? [? ?]].\n                   eapply as_inj_DomRng; eassumption.\n             (*3/3*) destruct MK as [mm [? [? ?]]].\n                   eapply as_inj_DomRng; eassumption.\n           rewrite H. intuition.  \n   (*5/8*) rewrite convertR_pubBlocksTgt, convertR_pubBlocksSrc, convertR_local.\n           apply WDnu23. \n   (*6/8*) rewrite convertR_frgnBlocksTgt, convertR_frgnBlocksSrc.\n           rewrite convertR_extern; trivial. intros.\n           destruct (frgnSrcAx _ WDnu23 _ H) as [b2 [d [EXT FT]]].\n           exists b2, d; unfold join. rewrite EXT; split; trivial.\n   (*7/8*) rewrite convertR_locBlocksTgt, convertR_pubBlocksTgt.\n            apply WDnu23.\n   (*8/8*) rewrite convertR_frgnBlocksTgt, convertR_extBlocksTgt.\n            intros. rewrite (frgnBlocksExternTgt _ WDnu23 _ H); trivial.\n  split. assumption. \n  split. rewrite GlueExt. trivial. \n  split. assumption. \n  intros. apply GlueFrgn; trivial.\nsplit. intros. (*Proof of NORM*) clear GOAL1 ConvertR_J23'.\n   subst.\n   destruct (joinD_Some _ _ _ _ _ H) as [EXT | [EXT LOC]]; clear H.\n      destruct (Norm12 _ _ _ EXT) as [b3 [d2 EXT2]].\n      exists b3, d2. apply joinI; left. assumption. \n   remember (local_of nu12 b1) as q.\n   destruct q; apply eq_sym in Heqq. inv LOC.\n   assert (AsInj12: as_inj nu12 b1 = None).\n     apply joinI_None; assumption.\n   destruct (sep12 _ _ _ AsInj12 LOC).\n   remember (extern_of nu23 b2) as d.\n   destruct d; apply eq_sym in Heqd.\n     destruct p. exfalso. apply H0. eapply VBj23_1. apply extern_in_all; eassumption. \n   remember (local_of nu23 b2) as w.\n   destruct w; apply eq_sym in Heqw.\n     destruct p. exfalso. apply H0. eapply VBj23_1. apply local_in_all; eassumption.\n   unfold join. rewrite Heqd, Heqw.\n   unfold removeUndefs in LOC. rewrite AsInj12 in LOC.\n   remember (as_inj nu' b1) as t.\n   destruct t; try inv LOC. destruct p; apply eq_sym in Heqt. \n   remember (j23' b2) as u.\n   destruct u; apply eq_sym in Hequ.\n     destruct p. exists b0, z0; trivial.  \n   destruct (mkiVal3 _ _ _ H2) as [[X _] | [X | X]]; clear mkiVal3.\n      rewrite X in AsInj12. discriminate.\n      destruct X as [B1 [B2 [D2 [VB1 VB2]]]].\n      exfalso. destruct (mkiVal5 _ VB2 Hequ) as [[Ya Yb] | [[Ya Yb] | [mm [Ya Yb]]]].\n        subst. clear - Ya. unfold Mem.valid_block in Ya. xomega.\n        subst. rewrite Heqt in Yb. discriminate.\n        subst. clear - Ya. rewrite Pos.add_comm in Ya. apply eq_sym in Ya.\n                    eapply Pos.add_no_neutral. apply Ya.\n      destruct X as [m [B1 [B2 [D1 [VB1 VB2]]]]].\n      exfalso. destruct (mkiVal5 _ VB2 Hequ) as [[Ya Yb] | [[Ya Yb] | [mm [Ya Yb]]]].\n        subst. clear - Ya. unfold Mem.valid_block in Ya. xomega.\n        subst.  clear - Ya. rewrite Pos.add_comm in Ya. \n                    eapply Pos.add_no_neutral. apply Ya.\n        subst. assert (mm=m). clear - Ya. xomega. subst.\n               rewrite Heqt in Yb. discriminate.      \nrepeat (split; trivial).\n=======*)\n\nRequire Import full_composition.\n\n(****************************\n *       Util lemmas        *\n ****************************)\nLemma valid_from_map: \n  forall mu m1 m2 b1 b2 d,\n    SM_wd mu -> \n    as_inj mu b1 = Some (b2,d) ->\n    sm_valid mu m1 m2 ->\n    Mem.valid_block m1 b1.\n  intros mu m1 m2 b1 b2 d SMWD map smv. \n  apply as_in_SomeE in map.\n  destruct SMWD, smv as [DOMv RNGv], map as [ext1 | loc1];\n    apply DOMv; unfold DOM, DomSrc.\n  apply extern_DomRng in ext1; destruct ext1 as [extS extT].\n  rewrite extS; apply orb_true_r.\n  apply local_DomRng in loc1; destruct loc1 as [locS locT].\n  rewrite locS; apply orb_true_l.\nQed.\nLemma forward_range:\n  forall m m' b ofs size p,\n    mem_forward m m' ->\n    Mem.valid_block m b ->\n    Mem.range_perm m' b ofs (ofs + size) Max p ->\n    Mem.range_perm m b ofs (ofs + size) Max p.\n  unfold Mem.range_perm; intros.\n  apply H; auto.\nQed.\nLemma mapped_valid: forall mu m1 m2 b1 b2 d,\n                      SM_wd mu ->\n                      as_inj mu b1 = Some (b2, d) ->\n                      sm_valid mu m1 m2 ->\n                      Mem.valid_block m1 b1.\n  intros. destruct H1 as [H1 H2]; apply H1.\n  unfold DOM, DomSrc.\n  apply joinD_Some in H0; destruct H0 as [map | [extNone map]];\n  apply H in map; destruct map as [src tgt]; rewrite src; auto.\n  apply orb_true_r.\nQed.\nLemma meminj_no_overlap_inject_incr: \n   forall j m (NOV: Mem.meminj_no_overlap j m) k (K:inject_incr k j),\n  Mem.meminj_no_overlap k m.\nProof. intros.\n  intros b; intros.\n  apply K in H0. apply K in H1.\n  eapply (NOV _ _ _ _ _ _ _ _  H H0 H1 H2 H3).\nQed.\nLemma no_overlap_asinj: \n  forall mu m, \n    SM_wd mu -> \n    Mem.meminj_no_overlap (extern_of mu) m ->\n    Mem.meminj_no_overlap (local_of mu) m ->\n    Mem.meminj_no_overlap (as_inj mu) m.\n  unfold Mem.meminj_no_overlap.\n  intros mu m SMWD NOO_ext NOO_loc.\n  intros.\n  apply as_in_SomeE in H0.\n  apply as_in_SomeE in H1.\n  destruct H0 as [ext1 | loc1];\n    destruct H1 as [ext2 | loc2].\n  eapply NOO_ext; eauto.\n  destruct SMWD. apply extern_DomRng in ext1; apply local_DomRng in loc2.\n  destruct (peq b1' b2'); auto; subst b1'.\n  destruct loc2; destruct ext1.\n  destruct (disjoint_extern_local_Tgt b2'). \n  rewrite H6 in H1; inversion H1.\n  rewrite H6 in H5; inversion H5.\n  destruct SMWD. apply extern_DomRng in ext2; apply local_DomRng in loc1.\n  destruct (peq b1' b2'); auto; subst b1'.\n  destruct loc1; destruct ext2.\n  destruct (disjoint_extern_local_Tgt b2'). \n  rewrite H6 in H1; inversion H1.\n  rewrite H6 in H5; inversion H5.\n  eapply NOO_loc; eauto.\nQed.\n\n(*<<<<<<< HEAD:core/interpolation_II.v\nDefinition ContentsMap_EFF_FUN  (NB2' b:block) : ZMap.t memval.\nProof.\ndestruct (plt b NB2').\n  apply (CM_block_EFF_existsT b).\napply (ZMap.init Undef).\nDefined.\n\nLemma ContentsMap_EFF_existsT: \n      forall (NB2':block) , \n      { M : PMap.t (ZMap.t memval) |\n        fst M = ZMap.init Undef /\\\n        forall b, PMap.get b M =\n           ContentsMap_EFF_FUN NB2' b}.\nProof. intros.\n  apply (pmap_construct_c _ (ContentsMap_EFF_FUN NB2') \n              NB2' (ZMap.init Undef)). \n    intros. unfold ContentsMap_EFF_FUN. simpl.\n    remember (plt n NB2') as d.\n    destruct d; clear Heqd; trivial.   \n      exfalso. xomega.\nQed.\n\nDefinition mkEFF \n            (NB2':block)\n            (Hyp1: (Mem.nextblock m2 <= NB2')%positive)\n            (Hyp2: forall (b1 b2 : block) (delta : Z),\n                       j12' b1 = Some (b2, delta) -> (b2 < NB2')%positive)\n           : Mem.mem'.\nProof.\ndestruct (mkAccessMap_EFF_existsT NB2' Hyp1 Hyp2) as [AM [ADefault PAM]].\ndestruct (ContentsMap_EFF_existsT NB2') as [CM [CDefault PCM]].  \neapply Mem.mkmem with (nextblock:=NB2')\n                      (mem_access:=AM)\n                      (mem_contents:=CM).\n  (*access_max*)\n  intros. rewrite PAM. unfold AccessMap_EFF_FUN.\n     destruct (plt b (Mem.nextblock m2)).\n     (*valid_block m2 b*)\n        destruct (locBlocksSrc nu23 b).\n          destruct (pubBlocksSrc nu23 b).\n            destruct (source (local_of nu12) m1 b ofs).\n              destruct p0.\n              destruct (pubBlocksSrc nu12 b0). apply m1'. apply m2.\n            apply m2.\n          apply m2.               \n        destruct (source (as_inj nu12) m1 b ofs). \n            destruct p0. apply m1'.\n        destruct (j23 b). destruct p0. reflexivity. apply m2.\n     (*invalid_block m2 b*)\n        destruct (source j12' m1' b ofs).\n          destruct p. apply m1'. \n        reflexivity.\n  (*nextblock_noaccess*)\n    intros. rewrite PAM.\n    unfold AccessMap_EFF_FUN.\n    destruct (plt b (Mem.nextblock m2)).\n      exfalso. apply H; clear - Hyp1 p. xomega.\n    remember (source j12' m1' b ofs) as src.\n    destruct src; trivial.\n      destruct p.\n      exfalso. apply H. clear - Heqsrc Hyp2.\n      apply source_SomeE in Heqsrc.\n      destruct Heqsrc as [b1 [delta [ofs1\n          [PBO [Bounds [J1 [P1 Off2]]]]]]]; subst.\n        apply (Hyp2 _ _ _ J1).\n  (*contents_default*)\n    intros. \n    rewrite PCM; clear PCM.\n    unfold ContentsMap_EFF_FUN.\n    destruct (plt b NB2').\n     remember (CM_block_EFF_existsT b). \n     destruct s. apply a.\n    reflexivity.\nDefined.\n\nLemma mkEff_nextblock: forall N Hyp1 Hyp2,\n         Mem.nextblock (mkEFF N Hyp1 Hyp2) = N.\nProof. intros. unfold mkEFF. \n  remember (mkAccessMap_EFF_existsT N Hyp1 Hyp2).\n  destruct s as [X1 X2].\n  destruct X2. simpl in *.\n  remember (ContentsMap_EFF_existsT N).\n  destruct s as [Y1 Y2].\n  destruct Y2; simpl in *. reflexivity.\n=======*)\n\n\n\nLemma no_overlap_ext:\n  forall mu m,\n    Mem.meminj_no_overlap (as_inj mu) m ->\n    Mem.meminj_no_overlap (extern_of mu) m.\n  unfold Mem.meminj_no_overlap; intros.\n  eapply H; eauto.\n  unfold as_inj, join; rewrite H1; auto.\n  unfold as_inj, join; rewrite H2; auto.\nQed.\n\nLemma no_overlap_loc:\n  forall mu m,\n    SM_wd mu ->\n    Mem.meminj_no_overlap (as_inj mu) m ->\n    Mem.meminj_no_overlap (local_of mu) m.\n  unfold Mem.meminj_no_overlap; intros.\n  eapply H0; eauto.\n  unfold as_inj; rewrite (join_com _ _ (disjoint_extern_local _ H)); unfold join.\n  rewrite H2; auto.\n  unfold as_inj; rewrite (join_com _ _ (disjoint_extern_local _ H)); unfold join.\n  rewrite H3; auto.\nQed.\n\n(****************************\n *         Tactics          *\n ****************************)\nLemma locT_localmap: forall mu b2 b d,\n                       SM_wd mu ->\n                       local_of mu b = Some (b2, d) ->\n                       locBlocksTgt mu b2 = true.\n  intros.\n  eapply H in H0. destruct H0 as [locS locT]; auto.\nQed.\nLemma locS_localmap: forall mu b p,\n                       SM_wd mu ->\n                       local_of mu b = Some p ->\n                       locBlocksSrc mu b = true.\n  intros. destruct p.\n  eapply H in H0. destruct H0 as [locS locT]; auto.\nQed.\nLemma locS_externmap: forall mu b p,\n                        SM_wd mu ->\n                        extern_of mu b = Some p ->\n                        locBlocksSrc mu b = false.\n  intros. destruct (locBlocksSrc mu b) eqn:locS; trivial.\n  destruct p; eapply H in H0. destruct H0 as [extS extT].\n  destruct H as [H ?].\n  destruct (H b); \n    [rewrite locS in H0 | rewrite extS in H0]; discriminate.\nQed.\nLemma locT_externmap: forall mu b b2 d,\n                        SM_wd mu ->\n                        extern_of mu b = Some (b2, d) ->\n                        locBlocksTgt mu b2 = false.\n  intros. destruct (locBlocksTgt mu b2) eqn:locT; trivial.\n  eapply H in H0. destruct H0 as [extS extT].\n  destruct H as [HS HT ?].\n  destruct (HT b2) as [H | H];\n    [rewrite locT in H | rewrite extT in H]; discriminate.\nQed.\nLemma validT_externmap: forall mu b2 b1 d m1 m2,\n                          SM_wd mu ->\n                          sm_valid mu m1 m2 ->\n                          extern_of mu b1 = Some (b2,d) ->\n                          Mem.valid_block m2 b2.\n  intros. apply H0.  unfold RNG, DomTgt. eapply H in H1. \n  destruct H1. rewrite H2; apply orb_true_r.\nQed.\n\nLemma validT_localmap: forall mu b2 b1 d m1 m2,\n                          SM_wd mu ->\n                          sm_valid mu m1 m2 ->\n                          local_of mu b1 = Some (b2,d) ->\n                          Mem.valid_block m2 b2.\n  intros. apply H0.  unfold RNG, DomTgt. eapply H in H1. \n  destruct H1. rewrite H2; apply orb_true_l.\nQed.\nLemma validS_externmap: forall mu b1 p m1 m2,\n                          SM_wd mu ->\n                          sm_valid mu m1 m2 ->\n                          extern_of mu b1 = Some p ->\n                          Mem.valid_block m1 b1.\n  intros. apply H0.  unfold DOM, DomSrc. destruct p; eapply H in H1. \n  destruct H1. rewrite H1; apply orb_true_r.\nQed.\n\nLemma validS_localmap: forall mu b1 p m1 m2,\n                          SM_wd mu ->\n                          sm_valid mu m1 m2 ->\n                          local_of mu b1 = Some p ->\n                          Mem.valid_block m1 b1.\n  intros. apply H0.  unfold DOM, DomSrc. destruct p; eapply H in H1. \n  destruct H1. rewrite H1; apply orb_true_l.\nQed.\nLemma loc_ext_map: forall mu b1 b1' b2 d d',\n                     SM_wd mu ->\n                     local_of mu b1 = Some (b2, d) ->\n                     extern_of mu b1' = Some (b2, d') ->\n                     False.\n  intros. apply H in H0; apply H in H1; destruct H0, H1.\n  destruct H as [HS HT ?]; destruct (HT b2).\n  rewrite H2 in H; inversion H.\n  rewrite H3 in H; inversion H.\nQed.\n\n\nLtac auto_sm:= \n               match goal with\n                   | _ => solve [eapply locS_localmap; eassumption]\n                   | _ => solve [eapply locT_localmap; eassumption]\n                   | _ => solve [eapply locS_externmap; eassumption]\n                   | _ => solve [eapply locT_externmap; eassumption]\n                   | [ H: local_of ?mu _ = Some (?b2, _ )|- Mem.valid_block _ ?b2 ] => \n                     solve[eapply (validT_localmap mu b2); eassumption]\n                   | [ H: local_of ?mu ?b1 = Some _ |- Mem.valid_block _ ?b1 ] => \n                     solve[eapply (validS_localmap mu b1); eassumption]\n                   | [ H: extern_of ?mu _ = Some (?b2, _ )|- Mem.valid_block _ ?b2 ] => \n                     solve[eapply (validT_externmap mu b2); eassumption]\n                   | [ H: extern_of ?mu ?b1 = Some _ |- Mem.valid_block _ ?b1 ] => \n                     solve[eapply (validS_externmap mu b1); eassumption]\n                   | [|- as_inj ?mu ?b1 = _ ] => solve[apply (local_in_all mu); assumption]\n                   | [loc: local_of ?mu _ = Some (?b2 , _),\n                      ext: extern_of ?mu _ = Some (?b2 , _)|- False ] => \n                     solve[ eapply (loc_ext_map mu); eassumption]\n               end.\n\n\n\nLemma EFF_interp_II_strong: \n  forall m1 m2 nu12 \n         (MInj12 : Mem.inject (as_inj nu12) m1 m2) m1'\n         (Fwd1: mem_forward m1 m1') nu23 m3\n         (MInj23 : Mem.inject (as_inj nu23) m2 m3) m3'\n         (Fwd3: mem_forward m3 m3')\n         nu' (WDnu' : SM_wd nu')\n         (SMvalNu' : sm_valid nu' m1' m3')\n         (MemInjNu' : Mem.inject (as_inj nu') m1' m3')\n         (ExtIncr: extern_incr (compose_sm nu12 nu23) nu')\n         (*Pure: pure_comp_ext nu12 nu23 m1 m2*)\n         (SMV12: sm_valid nu12 m1 m2)\n         (SMV23: sm_valid nu23 m2 m3)\n         (UnchPrivSrc: Mem.unchanged_on \n                         (fun b ofs => locBlocksSrc (compose_sm nu12 nu23) b = true /\\ \n                                       pubBlocksSrc (compose_sm nu12 nu23) b = false) m1 m1') \n         (UnchLOOR13: Mem.unchanged_on (local_out_of_reach (compose_sm nu12 nu23) m1) m3 m3')\n         (GlueInvNu: SM_wd nu12 /\\ SM_wd nu23 /\\\n                     locBlocksTgt nu12 = locBlocksSrc nu23 /\\\n                     extBlocksTgt nu12 = extBlocksSrc nu23 /\\\n                     (forall b, pubBlocksTgt nu12 b = true -> \n                                pubBlocksSrc nu23 b = true) /\\\n                     (forall b, frgnBlocksTgt nu12 b = true -> \n                                frgnBlocksSrc nu23 b = true))\n         (Norm12: forall b1 b2 d1, extern_of nu12 b1 = Some(b2,d1) ->\n                                   exists b3 d2, extern_of nu23 b2 = Some(b3, d2))\n         (full: full_ext nu12 nu23),\n  exists m2', exists nu12', exists nu23', nu'=compose_sm nu12' nu23' /\\\n                                          extern_incr nu12 nu12' /\\ extern_incr nu23 nu23' /\\\n                                          (*pure_comp_ext nu12' nu23' m1' m2' /\\*)\n                                          Mem.inject (as_inj nu12') m1' m2' /\\ mem_forward m2 m2' /\\\n                                          Mem.inject (as_inj nu23') m2' m3' /\\\n                                          sm_valid nu12' m1' m2' /\\ sm_valid nu23' m2' m3' /\\\n                                          (SM_wd nu12' /\\ SM_wd nu23' /\\\n                                           locBlocksTgt nu12' = locBlocksSrc nu23' /\\\n                                           extBlocksTgt nu12' = extBlocksSrc nu23' /\\\n                                           (forall b, pubBlocksTgt nu12' b = true -> \n                                                      pubBlocksSrc nu23' b = true) /\\\n                                           (forall b, frgnBlocksTgt nu12' b = true -> \n                                                      frgnBlocksSrc nu23' b = true)) /\\\n                                          (forall b1 b2 d1, extern_of nu12' b1 = Some(b2,d1) ->\n                                                            exists b3 d2, extern_of nu23' b2 = Some(b3, d2)) /\\ \n                                          Mem.unchanged_on (fun b ofs => locBlocksSrc nu23 b = true /\\ \n                                                                         pubBlocksSrc nu23 b = false) m2 m2' /\\\n                                          Mem.unchanged_on (local_out_of_reach nu12 m1) m2 m2' /\\\n                                          (*             Mem.unchanged_on (local_out_of_reach nu23 m2) m3 m3' /\\*)\n                                          (*(forall b1 b2 d1, as_inj nu12' b1 = Some(b2,d1) -> \n                                                            as_inj nu12 b1 = Some(b2,d1) \\/\n                                                            exists b3 d, as_inj nu' b1 = Some(b3,d)) /\\\n                                          (forall b2 b3 d2, as_inj nu23' b2 = Some(b3,d2) -> \n                                                            as_inj nu23 b2 = Some(b3,d2) \\/\n                                                            exists b1 d, as_inj nu' b1 = Some(b3,d)).*)\n                         \n                                          (forall b1 b2 d, extern_of nu12' b1 = Some (b2, d) ->\n                                                           extern_of nu12 b1 = Some (b2, d) \\/\n                                                           extern_of nu12 b1 = None /\\\n                                                           exists b3 d2, extern_of nu' b1 = Some (b3, d2)) /\\\n                                          (forall b2 b3 d2, extern_of nu23' b2 = Some (b3, d2) ->\n                                                            extern_of nu23 b2 = Some (b3, d2) \\/\n                                               extern_of nu23 b2 = None /\\\n                                                            exists b1 d, extern_of nu12' b1 = Some (b2, d)).\n\n(*                   (forall b1 b2 ofs2, as_inj nu12' b1 = Some(b2,ofs2) -> \n                     (as_inj nu12 b1 = Some (b2,ofs2)) \\/\n                     (b1 = Mem.nextblock m1 /\\ b2 = Mem.nextblock m2 /\\ ofs2 = 0) \\/ \n                     (exists m, (b1 = Mem.nextblock m1 + m /\\ b2=Mem.nextblock m2 + m)%positive /\\ ofs2=0)) /\\\n                   (forall b2 b3 ofs3, as_inj nu23' b2 = Some(b3,ofs3) -> \n                     (as_inj nu23 b2 = Some (b3,ofs3)) \\/\n                     (b2 = Mem.nextblock m2 /\\ as_inj nu' (Mem.nextblock m1) = Some(b3,ofs3)) \\/\n                     (exists m, (b2 = Mem.nextblock m2 + m)%positive /\\ \n                            as_inj nu' ((Mem.nextblock m1+m)%positive) = Some(b3,ofs3))). *)\nProof. intros.\n       (****************************\n        * Preparing the hypothesis *\n        ****************************)\n       destruct GlueInvNu as [SMWD12 [SMWD23 GlueInv]].\n\n       (***************************************\n        * Construct the injections            *\n        ***************************************)\n       remember (extern_of nu12) as j;\n         remember (extern_of nu23) as k;\n         remember (extern_of nu') as l';\n         remember (Mem.nextblock m2) as sizeM2;\n         remember (extBlocksSrc nu') as extS12;\n         remember (bconcat (extBlocksTgt nu12) (extBlocksSrc nu') sizeM2) as extT12;\n         remember (bconcat (extBlocksSrc nu23) (extBlocksSrc nu') sizeM2) as extS23;\n         remember (extBlocksTgt nu') as extT23;\n         remember (mkInjections (Mem.nextblock m2) j k l') as output;\n         destruct output as [j' k'].\n       remember (change_ext nu12 extS12 extT12 j') as nu12';\n         remember (change_ext nu23 extS23 extT23 k') as nu23'.\n       remember (as_inj nu12') as j12'.\n       \n       (************************************************\n        * Proving some properties of my injections     *\n        ************************************************)\n       \n       (* compose_sm *)\n       assert (compose: nu' = compose_sm nu12' nu23').\n       { rewrite Heqnu12', Heqnu23'. (*clear - ExtIncr full. *)\n         destruct ExtIncr as [extincr [? [? [? [? [? [? [? [? ? ]]]]]]]]].\n         unfold compose_sm, change_ext; destruct nu12, nu23, nu'; simpl in *; f_equal; auto.\n         eapply (MKIcomposition j k (extern_of1)); subst; eauto.\n         intros b p H.  destruct p.\n         eapply SMV23. eapply as_inj_DomRng.\n         unfold as_inj, join; simpl; rewrite H; eauto.\n         apply SMWD23. \n       }\n       \n       (* extern_incr nu12 nu12' *)\n       assert (ExtIncr12: extern_incr nu12 nu12').\n       { unfold extern_incr; simpl.\n         subst nu12' j k extS12 extT12; destruct nu12;\n         unfold extern_incr; simpl.\n         destruct ExtIncr as [extincr [? [extS [extT [? [? [? [? [? ? ]]]]]]]]].\n         simpl in *.\n         intuition.\n         eapply MKI_incr12; eauto.\n         apply bconcat_larger1; exact H9.\n       }\n\n       (* extern_incr nu23 nu23' *)\n       assert (ExtIncr23: extern_incr nu23 nu23').\n       { unfold extern_incr; simpl.\n         subst nu23' j k extS23 extT23; destruct nu23;\n         unfold extern_incr; simpl.\n         destruct ExtIncr as [extincr [? [extS [extT [? [? [? [? [? ? ]]]]]]]]].\n         simpl in *.\n         intuition.\n         eapply MKI_incr23; eauto.\n         apply bconcat_larger1; auto.\n       }\n\n       (* SM_wd 12 *)\n       assert (SMWD12': SM_wd nu12').\n       { subst nu12'. eapply MKI_wd12; eauto.\n         + subst extS12. intros.\n           destruct (locBlocksSrc nu12 b) eqn:locBS12; auto.\n           right. destruct ExtIncr as [? [? [extS [? [locS ?]]]]].\n           simpl in locS; rewrite locS in locBS12.\n           destruct WDnu'. destruct (disjoint_extern_local_Src b) as [locFalse | extFalse].\n           rewrite locBS12 in locFalse; inversion locFalse.\n           exact extFalse.\n         + subst extT12. intros.\n           destruct (locBlocksTgt nu12 b) eqn:locBT12; auto.\n           right. \n           unfold bconcat, buni, bshift.\n           destruct ExtIncr as [? [? [extS [? [locS [locT ?]]]]]].\n           destruct SMWD12. destruct (disjoint_extern_local_Tgt b) as [locFalse | extFalse].\n           rewrite locBT12 in locFalse; inversion locFalse.\n           rewrite extFalse; simpl.\n           destruct SMV12 as [DOM12 RNG12].\n           subst sizeM2;\n             rewrite RNG12; auto.\n           unfold RNG, DomTgt.\n           rewrite locBT12; auto.\n         + inversion Heqoutput. unfold add_inj, shiftT; intros.\n           destruct (j b1) eqn:jb1. \n         - rewrite H in jb1. subst j.\n           destruct SMWD12. apply extern_DomRng in jb1. destruct jb1 as [extS12true extT12true].\n           subst extS12 extT12. apply ExtIncr in extS12true.\n           rewrite extS12true; split; trivial.\n           apply bconcat_larger1; auto.\n         - unfold filter_id in H. destruct (l' b1) eqn:lb1; inversion H.\n           subst extS12 extT12. subst l'.\n           destruct WDnu', p;\n             apply extern_DomRng in lb1.\n           destruct lb1 as [extStrue extTtrue].\n           split; auto.\n           subst sizeM2; apply bconcat_larger2; auto.\n           + intros. subst extT12. apply bconcat_larger1; auto.\n             apply SMWD12 in H.\n             exact H.\n       }\n\n       \n       (* SM_wd 23 *)\n       assert (SMWD23': SM_wd nu23').\n       { subst nu23'; eapply MKI_wd23; eauto.\n         + subst extS23; intros.\n           destruct (locBlocksSrc nu23 b) eqn:locBS23; auto.\n           right. \n           unfold bconcat, buni, bshift.\n             destruct SMWD23; destruct (disjoint_extern_local_Src b) as [locSfalse | extSfalse].\n           rewrite locBS23 in locSfalse; inversion locSfalse.\n           rewrite extSfalse; simpl.\n           destruct ExtIncr as [? [? [extS [extT [locS [locT ?]]]]]].\n           destruct SMV23 as [DOM23 RNG23].\n           subst sizeM2; rewrite DOM23; auto.\n           unfold DOM, DomSrc. rewrite locBS23; auto.\n         + subst extT23. intros.\n           destruct (locBlocksTgt nu23 b) eqn:locBT23; auto.\n           right. destruct ExtIncr as [? [? [extS [? [locS [locT ?]]]]]].\n           simpl in locT; rewrite locT in locBT23.\n           destruct WDnu'. destruct (disjoint_extern_local_Tgt b) as [locFalse | extFalse].\n           rewrite locBT23 in locFalse; inversion locFalse.\n           exact extFalse.\n         + inversion Heqoutput. unfold add_inj, shiftS; intros.\n           destruct (k b1) eqn:kb1. \n         - rewrite H in kb1. subst k.\n           destruct SMWD23. apply extern_DomRng in kb1. destruct kb1 as [extS23true extT23true].\n           subst extS23 extT23. destruct ExtIncr as [? [? [extS [extT [locS [locT ?]]]]]].\n           simpl in extT; apply extT in extT23true.\n           rewrite extT23true; split; trivial.\n           apply bconcat_larger1; auto.\n         - rename H into lb1. inversion lb1.\n           destruct ((b1 ?= Mem.nextblock m2)%positive) eqn:ineq; try solve [inversion H2].\n           subst extS23 extT23. subst l'.\n           destruct WDnu'.\n           apply pure_filter_Some in lb1; destruct lb1 as [jmap lb1].\n           apply extern_DomRng in lb1.\n           destruct lb1 as [extStrue extTtrue].\n           split; auto.             \n           replace b1 with ((b1 - sizeM2) + sizeM2)%positive; \n             subst sizeM2. apply bconcat_larger2; auto.\n           apply Pos.sub_add; destruct (Pos.compare_gt_iff b1 (Mem.nextblock m2)). \n           apply H; auto.\n           + intros. subst extT23. destruct ExtIncr as [? [? [extS [extT [locS [locT ?]]]]]].\n             apply extT; simpl; auto.\n             apply SMWD23 in H; auto.\n       }\n\n        (***************************************\n        * Construct the memory                *\n        ***************************************)\n       assert (finite12: mi_mappedblocks (as_inj nu12) m2).\n       { unfold mi_mappedblocks. intros. apply SMV12. unfold RNG. \n         destruct (as_inj_DomRng _ _ _ _ H SMWD12); auto. }\n       \n       assert (finite12': mi_mappedblocks' j12' (mem_add_nb m1' m2)).\n       { unfold mi_mappedblocks'. intros. subst j12' nu12'.\n         unfold as_inj, join in H. rewrite ext_change_ext, loc_change_ext in H.\n         inversion Heqoutput; subst j'. \n         unfold add_inj, filter_id, shiftT in H.\n         destruct (j b) eqn:jmap.\n         + destruct p; inversion H; subst b' delta j.\n           eapply SMWD12 in jmap; destruct jmap.\n           eapply Pos.lt_le_trans. apply SMV12. unfold RNG, DomTgt.\n           rewrite H1; apply orb_true_r. \n           unfold mem_add_nb; xomega.\n         + destruct (l' b) eqn:lmap'.\n           - inversion H. \n             assert (Plt b (Mem.nextblock m1')).\n             { destruct p. subst l'; apply WDnu' in lmap'.\n               destruct lmap'. apply SMvalNu'.\n               unfold DOM, DomSrc. rewrite H0; apply orb_true_r. }\n             unfold mem_add_nb; xomega.\n           - unfold mem_add_nb; eapply Pos.lt_le_trans.\n             apply SMV12. unfold RNG, DomTgt.\n             apply SMWD12 in H; destruct H.\n             rewrite H0; auto.\n             xomega. }\n       \n       assert (INCR: inject_incr (as_inj nu12) j12').\n       { subst j12'; apply extern_incr_as_inj; auto. }\n         \n       destruct (mem_interpolation \n                   nu12 nu23 j12' m1 m1' m2 m3\n                   (finite12: mi_mappedblocks (as_inj nu12) m2)\n                   (finite12': mi_mappedblocks' j12' (mem_add_nb m1' m2))\n                   (SMWD12: SM_wd nu12)\n                   (INCR: inject_incr (as_inj nu12) j12')) \n                as [m2' [property_cont [property_acc property_nb]]].\n       clear finite12 finite12' INCR.\n       exists m2', nu12', nu23'.\n\n       (************************************************\n        * Proving some properties of my memory m2'     *\n        ************************************************)\n\n       (* mem_forward m2 m2' *)\n       assert (Fwd2: mem_forward m2 m2').\n       { unfold mem_forward; split.\n         + unfold Mem.valid_block in *.\n           rewrite property_nb.\n           unfold mem_add_nb.\n           xomega.\n         + intros ofs per. \n           unfold Mem.perm. rewrite property_acc; unfold mem_add_acc.\n           destruct (valid_dec m2 b); try contradiction.\n           destruct (locBlocksSrc nu23 b) eqn: loc23.\n           destruct (pubBlocksSrc nu23 b) eqn: pub23; trivial.\n           destruct (source (local_of nu12) m1 b ofs) eqn:sour; trivial; destruct p.\n           destruct (pubBlocksSrc nu12 b0) eqn: pub12; trivial.\n           symmetry in sour. apply source_SomeE in sour.\n           destruct sour as [b1 [delta' [ofs1 [invertible [leq [mapj [mperm ofs_add]]]]]]].\n           subst ofs; intros H0. eapply MInj12.\n           apply local_in_all; eauto.\n           eapply Fwd1; auto.\n           inversion invertible; subst z b0; auto.\n           \n           destruct (source (as_inj nu12) m1 b ofs) eqn:sour;\n             try solve[destruct (as_inj nu23 b); intros HH;try destruct p; trivial; inversion HH].\n           destruct p.\n           intros H0.\n           symmetry in sour. apply source_SomeE in sour.\n           destruct sour as [b1 [delta' [ofs1 [invertible [leq [mapj [mperm ofs_add]]]]]]].\n           subst ofs; eapply MInj12; eauto.\n           eapply Fwd1; auto.\n           inversion invertible; subst z b0; auto.\n       }\n\n       (* Mem.unchanged_on private m2 *)\n       assert (UnchPrivSrc12 : Mem.unchanged_on\n                   (fun (b : block) (_ : Z) =>\n                      locBlocksSrc nu23 b = true /\\ pubBlocksSrc nu23 b = false) m2 m2').\n       { constructor. \n         + intros b ofs k0 p [locS pubS] bval; unfold Mem.perm.\n           rewrite property_acc; unfold mem_add_acc.\n           rewrite locS, pubS.\n           destruct (valid_dec m2 b); try solve[contradict bval;trivial].\n           split; auto.\n         + intros b ofs [locS pubS] mperm.\n           rewrite property_cont; unfold mem_add_cont.\n           rewrite locS, pubS.\n           destruct (valid_dec m2 b); try solve[trivial].\n           (*Invalid case*) apply Mem.perm_valid_block in mperm; contradiction.\n       }\n       \n       (*Mem.unchanged_on local_out_of_reach 12*)\n       assert (UnchLOOR12: Mem.unchanged_on (local_out_of_reach nu12 m1) m2 m2').\n       { unfold local_out_of_reach.\n         constructor. \n         + intros b ofs k0 p [locT mapcondition] bval; unfold Mem.perm.\n           rewrite property_acc; \n                 unfold mem_add_acc.\n           destruct (valid_dec m2 b); try solve[contradict bval;trivial].\n           assert (locS: locBlocksSrc nu23 b = true ) by\n               (destruct GlueInv as [glue1 rest]; rewrite glue1 in locT; trivial).\n           rewrite locS.\n           destruct (pubBlocksSrc nu23 b) eqn:pubS;\n             destruct (source (local_of nu12) m1 b ofs) eqn:sour;\n             try solve [split;auto].\n           - symmetry in sour. apply source_SomeE in sour;\n             destruct sour as [b0 [d0 [ofs0 [invert [bval' [map12 [mparm of_eq] ]]]]]].\n             subst p0 ofs.\n             apply mapcondition in map12. clear mapcondition.\n             destruct map12 as [mperm1 | pubS1].\n             * contradict mperm1. replace (ofs0 + d0 - d0) with ofs0 by omega; trivial.\n             * rewrite pubS1; split; auto.\n         + intros b ofs [locT mapcondition] mperm; unfold Mem.perm.\n           rewrite property_cont; \n                 unfold mem_add_cont.\n           destruct (valid_dec m2 b).\n           - assert (locS: locBlocksSrc nu23 b = true ) by\n                 (destruct GlueInv as [glue1 rest]; rewrite glue1 in locT; trivial).\n             rewrite locS.\n             destruct (pubBlocksSrc nu23 b) eqn:pubS;\n               destruct (source (local_of nu12) m1 b ofs) eqn:sour;\n               try solve [split;auto].\n             symmetry in sour. apply source_SomeE in sour;\n              destruct sour as [b0 [d0 [ofs0 [invert [bval' [map12 [mparm of_eq] ]]]]]].\n             subst p ofs.\n             apply mapcondition in map12. clear mapcondition.\n             destruct map12 as [mperm1 | pubS1].\n             * contradict mperm1. replace (ofs0 + d0 - d0) with ofs0 by omega; trivial.\n             * rewrite pubS1; split; auto.\n           - (*Invalid case*) apply Mem.perm_valid_block in mperm; contradiction.\n       }\n       (*Mem.unchanged_on local_out_of_reach 23*)\n       assert (UnchLOOR23: Mem.unchanged_on (local_out_of_reach nu23 m2) m3 m3').\n       { unfold local_out_of_reach; split; intros.\n         + move UnchLOOR13 at bottom; unfold local_out_of_reach in UnchLOOR13.\n           apply UnchLOOR13; auto.\n           destruct H; split.\n           - unfold compose_sm; trivial.\n           - unfold compose_sm; simpl; intros.\n             unfold compose_meminj in H2. \n             destruct (local_of nu12 b0) eqn:maploc12; try solve[inversion H2].\n             destruct p0. destruct (local_of nu23 b1) eqn:maploc23; try solve[inversion H2].\n             destruct p0. inversion H2; subst b2 delta; clear H2.\n             eapply H1 in maploc23.\n             destruct maploc23.\n             * left. intros mperm.\n               apply H2. replace (ofs - z0) with ((ofs - (z + z0)) + z) by xomega. \n               eapply MInj12; eauto. \n               apply local_in_all; eauto. \n             * right. destruct (pubBlocksSrc nu12 b0) eqn:pubS12; trivial.\n               apply SMWD12 in pubS12. destruct pubS12 as [b2 [ofs' [maploc12' pubT12]]].\n               rewrite maploc12 in maploc12'; inversion maploc12'; subst b1 z.\n               apply GlueInv in pubT12. rewrite pubT12 in H2; inversion H2.\n         + move UnchLOOR13 at bottom; unfold local_out_of_reach in UnchLOOR13.\n           apply UnchLOOR13; auto.\n           destruct H; split.\n           - unfold compose_sm; trivial.\n           - unfold compose_sm; simpl; intros.\n             unfold compose_meminj in H2. \n             destruct (local_of nu12 b0) eqn:maploc12; try solve[inversion H2].\n             destruct p. destruct (local_of nu23 b1) eqn:maploc23; try solve[inversion H2].\n             destruct p. inversion H2; subst b2 delta; clear H2.\n             eapply H1 in maploc23.\n             destruct maploc23.\n             * left. intros mperm.\n               apply H2. replace (ofs - z0) with ((ofs - (z + z0)) + z) by xomega. \n               eapply MInj12; eauto. \n               apply local_in_all; eauto. \n             * right. destruct (pubBlocksSrc nu12 b0) eqn:pubS12; trivial.\n               apply SMWD12 in pubS12. destruct pubS12 as [b2 [ofs' [maploc12' pubT12]]].\n               rewrite maploc12 in maploc12'; inversion maploc12'; subst b1 z.\n               apply GlueInv in pubT12. rewrite pubT12 in H2; inversion H2.\n       }\n       \n       (*(* pure_comp_ext nu12' nu23' m1' m2 *)\n       assert (Pure': pure_comp_ext nu12' nu23' m1' m2').\n       { unfold pure_comp_ext.\n         subst nu12' nu23' m2'. rewrite ext_change_ext, ext_change_ext.\n         split.\n         + unfold pure_composition_locat.\n           clear - Heqoutput Pure Heqj Heqj12' Heqk SMV12 \n                   SMV23 SMWD23 SMWD12 MemInjNu' GlueInv.\n           inversion Heqoutput. intros. \n           unfold add_inj in H.\n           destruct (k b2) eqn:kmap.\n           - destruct p. inversion H. subst b z. \n             rewrite Heqk in kmap. \n             unfold valid_location in H2.\n             unfold Mem.perm in H2. rewrite mem_add_accx in H2.\n             unfold mem_add_acc in H2. \n             assert (notloc: locBlocksSrc nu23 b2 = false) by auto_sm.\n             rewrite notloc in H2.\n             destruct (valid_dec m2 b2).\n             destruct (source (as_inj nu12) m1 b2 delta) eqn:sour.\n             * symmetry in sour; apply source_SomeE in sour.\n               destruct sour as [b1 [delta0 [ofs1 [pair [bval1 [jmap12' [mperm' d_eq]]]]]]].\n               exists b1, delta0.\n               subst p j12'.\n               \n               assert (jmap: j b1 = Some (b2, delta0)).\n               { apply as_in_SomeE in jmap12'. destruct jmap12'; subst j; trivial.\n                 apply SMWD12 in H3; destruct H3 as [locS locT].\n                 apply SMWD23 in kmap; destruct kmap as [extS extT].\n                 destruct GlueInv as [loc rest]; rewrite loc in locT.\n                 destruct SMWD23. destruct (disjoint_extern_local_Src b2) as [loc'| ext'].\n                 rewrite locT in loc'; inversion loc'.\n                 rewrite extS in ext'; inversion ext'.\n                 }\n               unfold add_inj. rewrite jmap; split; auto.\n               unfold valid_location. \n               subst delta. replace (ofs1 + delta0 - delta0) with ofs1 by omega. auto.\n             * unfold as_inj, join in H2; rewrite kmap in H2. \n               inversion H2.\n             * contradict n. apply SMV23. unfold DOM, DomSrc. apply SMWD23 in kmap.\n               destruct kmap as [extS extT]; rewrite extS; apply orb_true_r.\n           - \n             apply shiftS_Some in H; destruct H as [ineq lmap'].\n             apply pure_filter_Some in lmap'; destruct lmap' as [jNone lmap'].\n              generalize H2; unfold valid_location; intros.\n             unfold Mem.perm in H3.\n             rewrite mem_add_accx in H3. unfold mem_add_acc in H3.\n             destruct (valid_dec m2 b2).\n             contradict v. clear - ineq. unfold Mem.valid_block. xomega.\n             exists (b2 - Mem.nextblock m2)%positive, 0.\n             split. unfold add_inj.\n             rewrite jNone.\n             unfold shiftT, filter_id. rewrite lmap'.\n             replace (b2 - Mem.nextblock m2 + Mem.nextblock m2)%positive with b2; auto. \n             symmetry; apply Pos.sub_add; xomega.\n             destruct (source j12' m1' b2 delta) eqn:sour; try solve [inversion H3]. destruct p.\n             replace (delta - 0) with delta by omega; auto.\n             symmetry in sour; apply source_SomeE in sour.\n             destruct sour as [b1 [delta' [ofs1 [invertible [leq [mapj [mperm ofs_add]]]]]]].\n             inversion invertible; subst delta b z. clear invertible.\n             {(*is external and b2 > nextblock m2... must be mapped by l shifted*)\n               subst j12'. \n               apply as_in_SomeE in mapj; destruct mapj as [extmap | locmap].\n               + rewrite ext_change_ext in extmap. eapply MKI_Some12 in extmap; eauto.\n                 destruct extmap as [jmap | [jmap [b2' [d' [lmap'' [Heqb2 delta0]]]]]].\n                 - contradict n; subst j; auto_sm.\n                 - subst b2.\n                   subst delta'.\n                   rewrite Pos.add_sub; replace (ofs1 + 0) with ofs1 by omega; trivial.\n               + rewrite loc_change_ext in locmap. contradict n; auto_sm.\n               }\n         + unfold pure_composition_block.\n           inversion Heqoutput.\n           subst j' k'.\n           intros.\n           unfold add_inj in H.\n           destruct (k b2) eqn:kmap.\n           - destruct p. inversion H. subst b z. \n             rewrite Heqk in kmap. \n             apply Pure in kmap; destruct kmap as [b1 [ofs12 jmap]].\n             exists b1, ofs12.\n             unfold add_inj. subst j; rewrite jmap; auto.\n           - apply shiftS_Some in H; destruct H as [ineq lmap'].\n             apply pure_filter_Some in lmap'; destruct lmap' as [jNone lmap'].\n             exists (b2 - Mem.nextblock m2)%positive, 0.\n             unfold add_inj.\n             rewrite jNone.\n             unfold shiftT, filter_id. rewrite lmap'.\n             replace (b2 - Mem.nextblock m2 + Mem.nextblock m2)%positive with b2; auto. \n             symmetry; apply Pos.sub_add. xomega.\n       }*)\n       \n       \n\n       (****************************\n        * Proving each condition   *\n        ****************************)\n\n       split.\n       (*Compose_sm*)\n       { exact compose. } \n       split.\n       (* extern_incr12 *)\n       { exact ExtIncr12. }\n       split.\n       (* extern_incr23 *)\n       { exact ExtIncr23. }\n       (*split.\n       (* pure compositoin *)\n       { exact Pure'. }*)\n       split.\n       (* Mem.inject 12*)\n       { (* Prove no overlapping of nu12' first *)\n         assert (no_overlap12': Mem.meminj_no_overlap j12' m1').\n         { subst j12'.         \n           apply no_overlap_asinj; auto.\n           subst nu12'; rewrite ext_change_ext.\n         (*Mem.meminj_no_overlap j' m1'*)\n         + eapply MKI_no_overlap12; eauto.\n           - subst j. apply no_overlap_ext.\n             apply MInj12.\n           - subst l'; apply no_overlap_ext; eapply MemInjNu'.\n           - intros. apply SMV12. unfold DOM, DomSrc. subst j; apply SMWD12 in H.\n             destruct H as [extS extT]; rewrite extS; apply orb_true_r.\n           - intros. apply SMV12. unfold RNG, DomTgt. subst j; apply SMWD12 in H.\n             destruct H as [extS extT]; rewrite extT; apply orb_true_r.\n         (*Mem.meminj_no_overlap (local_of nu12') m1'*)\n         + subst nu12'; rewrite loc_change_ext.\n           eapply no_overlap_loc; eauto.\n           eapply no_overlap_forward; eauto.\n           apply MInj12. }\n         \n         (* Prove Mem.inject12*)\n         constructor.\n         + constructor.\n         - { intros b1 b2 delta ofs k0 per H H0.\n             unfold Mem.perm; rewrite property_acc; \n             unfold mem_add_acc.\n             (* New trying things*)\n             unfold as_inj in H; apply joinD_Some in H; \n             destruct H as [extmap | [extNone locmap]].\n             + subst nu12'; rewrite ext_change_ext in extmap.\n               eapply MKI_Some12 in extmap; eauto. \n               destruct extmap as [jmap | [jmap [b2' [d' [lmap' [b2eq deltaeq]]]]]].\n             - assert (Mem.valid_block m2 b2) by (subst j; auto_sm).\n               destruct (valid_dec m2 b2); try solve[contradict n; auto].\n               assert (locF: locBlocksSrc nu23 b2 = false).\n               { destruct GlueInv as [loc rest]; rewrite <- loc.\n                 subst j; auto_sm. }\n               rewrite locF.\n               erewrite source_SomeI. apply H0.\n               * apply MInj12.\n               * unfold as_inj, join. \n                 subst j. rewrite jmap; auto.\n               * eapply Fwd1.\n                 subst j; auto_sm.\n                 eapply any_Max_Nonempty; eauto. \n             - destruct (valid_dec m2 b2); (*first discharge the impossible case*)\n               try solve[subst b2; contradict v; unfold Mem.valid_block; xomega].\n               subst b2 delta. \n               erewrite (source_SomeI j12' m1' ).\n               eapply H0.\n               exact no_overlap12'.\n               subst j12'.\n               unfold as_inj, join. rewrite ext_change_ext, loc_change_ext.\n               assert (j' b1 = Some ((b1 + Mem.nextblock m2)%positive , 0)). \n               { inversion Heqoutput. unfold add_inj, shiftT, filter_id.\n                 rewrite jmap, lmap'; auto. }\n               rewrite H. auto.\n                 eapply any_Max_Nonempty; eauto. \n             + subst nu12'; rewrite loc_change_ext in locmap.\n               assert (locTrue: locBlocksSrc nu23 b2 = true).\n               { destruct GlueInv as [loc rest]; rewrite <- loc; auto_sm. }\n               rewrite locTrue.\n               rewrite ext_change_ext in extNone.\n               assert (Mem.valid_block m2 b2).\n               { apply SMV12. unfold RNG, DomTgt. apply SMWD12 in locmap. \n                 destruct locmap as [locS locT]; rewrite locT; apply orb_true_l. }\n               destruct (valid_dec m2 b2); try solve[contradict n; auto].\n               (*prove that (k b2 = None) by contradiction*)\n                 destruct (k b2) eqn: kmap. subst k.\n                 { apply SMWD12 in locmap; destruct locmap as [locS locT].\n                   destruct GlueInv as [loc rest]; rewrite loc in locT.\n                   destruct p; apply SMWD23 in kmap; destruct kmap as [extS extT].\n                   destruct SMWD23. destruct (disjoint_extern_local_Src b2) as [locS'|extS'].\n                   + rewrite locT in locS'; inversion locS'.\n                   + rewrite extS in extS'; inversion extS'. }\n                 destruct ( pubBlocksSrc nu23 b2) eqn:pub23.\n                 erewrite (source_SomeI (local_of nu12) m1); eauto.\n                  destruct (pubBlocksSrc nu12 b1) eqn:pub12.\n                 auto.\n\n                 (* pubBlocksSrc nu23 b2 = true & pubBlocksSrc nu12 b1 = false *)\n                  assert (Permb1: Mem.perm m1 b1 ofs k0 per).\n                 { eapply UnchPrivSrc; eauto;\n                   unfold compose_sm; simpl; apply SMWD12 in locmap; destruct locmap; auto.\n                   eapply SMV12. unfold DOM, DomSrc. rewrite H1; auto. }\n                 eapply MInj12; eauto.\n                 auto_sm. (*local mapped*)\n                 eapply (meminj_no_overlap_inject_incr (as_inj nu12)).\n                 apply MInj12.\n                 apply local_in_all; auto.\n                 { apply Fwd1. \n                 eapply SMV12; apply SMWD12 in locmap; \n                 destruct locmap; auto; unfold DOM, DomSrc.\n                 rewrite H1; auto.  eapply any_Max_Nonempty; eauto. }\n                 \n                 (* pubBlocksSrc nu23 b2 = false & \"pubBlocksSrc nu12 b1 = false\"/proved *)\n                 destruct (pubBlocksSrc nu12 b1) eqn:pub12.\n                 { (*this case yields contradiction*)\n                   apply SMWD12 in pub12. destruct pub12 as [b2' [z [loc12 pubTgt]]].\n                   rewrite locmap in loc12; inversion loc12; subst b2' z.\n                   apply GlueInv in pubTgt.\n                   rewrite pubTgt in pub23; discriminate pub23. }\n                  assert (Permb1: Mem.perm m1 b1 ofs k0 per).\n                 { eapply UnchPrivSrc; eauto;\n                   unfold compose_sm; simpl; apply SMWD12 in locmap; destruct locmap; auto.\n                   eapply SMV12. unfold DOM, DomSrc. rewrite H1; auto. }\n                 eapply MInj12; eauto.\n                 auto_sm.\n           }\n         - intros. unfold Z.divide.\n           subst nu12'; unfold as_inj, join in H. rewrite ext_change_ext, loc_change_ext in H.\n           destruct (j' b1) eqn:jmap'. \n           destruct p0. destruct (MKI_Some12 _ _ _ _ _ _ Heqoutput _ _ _ jmap') as \n                          [jmap | [jmap [b2' [d' [lmap [b2eq deq]]]]]].\n           inversion H; subst b z.\n           subst j. destruct MInj12. destruct mi_inj.\n           eapply (mi_align b1 b2); eauto. \n           unfold as_inj, join; rewrite jmap; trivial.\n           \n           eapply forward_range; eauto.\n           clear H. \n           \n           eapply mapped_valid.\n           apply SMWD12. \n           unfold as_inj, join; rewrite jmap; auto. \n           eauto.\n           \n           (* This should be folded in a lemma *)\n           inversion Heqoutput.\n           unfold add_inj, shiftT in H2. subst j'. rewrite jmap in jmap'.\n           unfold filter_id in jmap'. rewrite lmap in jmap'.\n           inversion jmap'. subst z. symmetry in H; inversion H; subst delta.\n           exists 0; xomega.\n           (*Done *)\n           \n           destruct MInj12. destruct mi_inj.\n           eapply (mi_align b1 b2); eauto.\n           unfold as_inj. \n           rewrite join_com. \n           unfold join; rewrite H; trivial.\n           apply disjoint_extern_local.\n           apply SMWD12.\n           eapply forward_range; eauto.\n           eapply mapped_valid.\n           apply SMWD12. \n           unfold as_inj. \n           rewrite join_com. \n           unfold join; rewrite H; trivial.\n           apply disjoint_extern_local.\n           apply SMWD12.\n           eauto.\n         - (*mi_memval12*) (*HERE*)\n           { intros b1 ofs b2 delta map12' mperm1'. \n             unfold Mem.perm; rewrite property_cont; unfold mem_add_cont.\n             (* New trying things*)\n             unfold as_inj in map12'; apply joinD_Some in map12'; destruct map12' as [extmap | [extNone locmap]].\n             + subst nu12'; rewrite ext_change_ext in extmap.\n               eapply MKI_Some12 in extmap; eauto. \n               destruct extmap as [jmap | [jmap [b2' [d' [lmap' [b2eq deltaeq]]]]]].\n             - assert (Mem.valid_block m2 b2) by (subst j; auto_sm).\n               destruct (valid_dec m2 b2); try solve[contradict n; auto].\n               assert (locF: locBlocksSrc nu23 b2 = false).\n               { destruct GlueInv as [loc rest]; rewrite <- loc.\n                 subst j; auto_sm. }\n               rewrite locF.\n               erewrite source_SomeI.\n               destruct MemInjNu'. destruct mi_inj.\n               (*Prepare to use mi_memval of nu'*)\n               assert (map13': exists b3 d3, as_inj nu' b1 = Some (b3, d3)).\n               {assert (kmap:=jmap).\n               apply Norm12 in kmap; destruct kmap as [b3 [d2 kmap]].\n               exists b3, (delta + d2).\n               unfold as_inj, join. destruct ExtIncr as [ext_incr other_incr]. \n               erewrite ext_incr; eauto.\n               rewrite compose_sm_extern. subst j.\n               unfold compose_meminj.\n               rewrite jmap.\n               subst k. rewrite kmap; auto.\n               }\n               destruct map13' as [b3 [d3 map13']].\n               { (*memval_inject part*)\n               apply (mi_memval b1 ofs b3 d3 map13') in mperm1'.\n               instantiate(1:=b1).\n               inversion mperm1'; try constructor.\n               remember ( change_ext nu12 extS12 extT12 j') as nu12'.\n               rewrite compose in H2.\n               unfold as_inj in H2.\n               { (*Two cases, whether b0 is external or local*)\n                 destruct (joinD_Some _ _ _ _ _ H2) as [extcomp | [extcomp loccomp]].\n                 + (* b0 is external*)\n                   rewrite compose_sm_extern in extcomp.\n                   apply compose_meminjD_Some in extcomp.\n                   destruct extcomp as [b1' [ofs1' [ofs' [ext12 [ext23 eq]]]]].\n                   subst nu12'; rewrite ext_change_ext in ext12.\n                   unfold inject_memval, join .\n                   subst j12'; unfold as_inj, join; rewrite ext_change_ext.\n                   \n                   rewrite ext12.\n                   econstructor; auto.\n                   rewrite ext12.\n                   reflexivity.\n                 + (* b0 is local / need to show it's public!*)\n                   rewrite compose_sm_local in loccomp.\n                   apply compose_meminjD_Some in loccomp.\n                   destruct loccomp as [b1' [ofs1' [ofs' [loc12 [loc23 eq]]]]].\n                   subst nu12'. rewrite loc_change_ext in loc12.\n                   (* Now let us prove that j b0 = None, to prove jp b0 = b1', ofs1'*)\n                   assert (jmap0': j' b0 = None). \n                   { remember ( change_ext nu12 extS12 extT12 j') as nu12'.\n                     destruct SMWD12'. \n                     assert (forall b, local_of nu12 b = local_of nu12' b) by\n                     (intros; subst nu12'; rewrite loc_change_ext; auto).\n                     rewrite H4 in loc12.\n                     apply local_DomRng in loc12.\n                     destruct loc12 as [locS' locT'].\n                     destruct (j' b0) eqn:jmap'; auto. destruct p.\n                     assert (forall b, j' b = extern_of nu12' b) by\n                     (intros; subst nu12'; rewrite ext_change_ext; auto).\n                     rewrite H5 in jmap'. apply extern_DomRng in jmap'.\n                     destruct jmap' as [extS' extT'].\n                     destruct (disjoint_extern_local_Src b0) as [locS'' | extS''].\n                     rewrite locS'' in locS'; inversion locS'.\n                     rewrite extS'' in extS'; inversion extS'. }\n                   unfold inject_memval, join. \n                   subst j12'; unfold as_inj, join; rewrite ext_change_ext, loc_change_ext.\n                   rewrite jmap0'. rewrite loc12.\n                   econstructor.\n                   rewrite jmap0'; eauto.\n                   auto. } }\n               * apply MInj12.\n               * unfold as_inj, join. \n                 subst j. rewrite jmap; auto.\n               * eapply Fwd1.\n                 subst j; auto_sm.\n                 eapply any_Max_Nonempty; eauto. \n             - destruct (valid_dec m2 b2); (*first discharge the impossible case*)\n               try solve[subst b2; contradict v; unfold Mem.valid_block; xomega].\n               erewrite (source_SomeI j12' m1' ).\n               subst b2 delta.\n                (* replace (ofs + 0) with ofs by omega; trivial. *)\n               unfold inject_memval.\n               { (*memval_inject part*)\n                  destruct MemInjNu'. destruct mi_inj.\n               (*Prepare to use mi_memval of nu'*)\n               assert (map13': exists b3 d3, as_inj nu' b1 = Some (b3, d3)). \n               { exists b2', d'. unfold as_inj, join.  subst l'.\n                 rewrite lmap'; auto. }\n               destruct map13' as [b3 [d3 map13']].\n               apply (mi_memval b1 ofs b3 d3 map13') in mperm1'.\n               instantiate(1:=b1).\n               inversion mperm1'; try constructor.\n               remember ( change_ext nu12 extS12 extT12 j') as nu12'.\n               rewrite compose in H1.\n               unfold as_inj in H1.\n               { (*Two cases, whether b0 is external or local*)\n                 destruct (joinD_Some _ _ _ _ _ H1) as [extcomp | [extcomp loccomp]].\n                 + (* b0 is external*)\n                   rewrite compose_sm_extern in extcomp.\n                   apply compose_meminjD_Some in extcomp.\n                   destruct extcomp as [b1' [ofs1' [ofs' [ext12 [ext23 eq]]]]].\n                   subst nu12'; rewrite ext_change_ext in ext12.\n                   unfold inject_memval, join .\n                   subst j12'; unfold as_inj, join; rewrite ext_change_ext.\n                   rewrite ext12.\n                   econstructor; auto.\n                   rewrite ext12.\n                   reflexivity.\n                 + (* b0 is local / need to show it's public!*)\n                   rewrite compose_sm_local in loccomp.\n                   apply compose_meminjD_Some in loccomp.\n                   destruct loccomp as [b1' [ofs1' [ofs' [loc12 [loc23 eq]]]]].\n                   subst nu12'. rewrite loc_change_ext in loc12.\n                   (* Now let us prove that j b0 = None, to prove jp b0 = b1', ofs1'*)\n                   assert (jmap0': j' b0 = None). \n                   {  remember ( change_ext nu12 extS12 extT12 j') as nu12'.\n                     destruct SMWD12'. \n                     assert (forall b, local_of nu12 b = local_of nu12' b) by\n                     (intros; subst nu12'; rewrite loc_change_ext; auto).\n                     rewrite H3 in loc12.\n                     apply local_DomRng in loc12.\n                     destruct loc12 as [locS' locT'].\n                     destruct (j' b0) eqn:jmap'; auto. destruct p.\n                     assert (forall b, j' b = extern_of nu12' b) by\n                     (intros; subst nu12'; rewrite ext_change_ext; auto).\n                     rewrite H4 in jmap'. apply extern_DomRng in jmap'.\n                     destruct jmap' as [extS' extT'].\n                     destruct (disjoint_extern_local_Src b0) as [locS'' | extS''].\n                     rewrite locS'' in locS'; inversion locS'.\n                     rewrite extS'' in extS'; inversion extS'. }\n                   unfold inject_memval, join. \n                   subst j12'; unfold as_inj, join; rewrite ext_change_ext, loc_change_ext.\n                   rewrite jmap0'. rewrite loc12.\n                   econstructor.\n                   rewrite jmap0'; eauto.\n                   auto. } }\n               exact no_overlap12'.\n               subst j12'.\n               unfold as_inj, join. rewrite ext_change_ext, loc_change_ext.\n               assert (j' b1 = Some ((b1 + Mem.nextblock m2)%positive , 0)).\n               { inversion Heqoutput. unfold add_inj, shiftT, filter_id.\n                 rewrite jmap, lmap'; auto. }\n               rewrite H. subst delta b2. auto.\n                 eapply any_Max_Nonempty; eauto. \n             + subst nu12'; rewrite loc_change_ext in locmap.\n               assert (locTrue: locBlocksSrc nu23 b2 = true).\n               { destruct GlueInv as [loc rest]; rewrite <- loc; auto_sm. }\n               rewrite locTrue.\n               rewrite ext_change_ext in extNone.\n               assert (Mem.valid_block m2 b2).\n               { apply SMV12. unfold RNG, DomTgt. apply SMWD12 in locmap. \n                 destruct locmap as [locS locT]; rewrite locT; apply orb_true_l. }\n               destruct (valid_dec m2 b2); try solve[contradict n; auto].\n\n                (*prove that (k b2 = None) by contradiction*)\n                 destruct (k b2) eqn: kmap. subst k.\n                 { apply SMWD12 in locmap; destruct locmap as [locS locT].\n                   destruct GlueInv as [loc rest]; rewrite loc in locT.\n                   destruct p; apply SMWD23 in kmap; destruct kmap as [extS extT].\n                   destruct SMWD23. destruct (disjoint_extern_local_Src b2) as [locS'|extS'].\n                   + rewrite locT in locS'; inversion locS'.\n                   + rewrite extS in extS'; inversion extS'. }\n                 destruct ( pubBlocksSrc nu23 b2) eqn:pub23.\n                 erewrite (source_SomeI (local_of nu12) m1); eauto.\n                 destruct (pubBlocksSrc nu12 b1) eqn:pub12.\n                 { destruct (pubSrc _ SMWD23 _ pub23) as [b3 [d2 [Pub23 PubTgt3]]].\n                   assert (Nu'b1: as_inj nu' b1 = Some (b3, delta+d2)).\n                   { rewrite compose. rewrite Heqnu23'.\n                     unfold as_inj, join, compose_sm, compose_meminj; simpl.\n                     rewrite ext_change_ext, loc_change_ext, loc_change_ext.\n                     rewrite extNone, locmap.\n                     erewrite (pub_in_local nu23 b2); eauto. }\n                   eapply (Mem.mi_memval _ _ _ (Mem.mi_inj _ _ _ MemInjNu')) in mperm1'; \n                     eauto. \n                   inversion mperm1'; try econstructor.\n                   apply inject_memval_memval_inject.\n                   subst j12'; auto.\n                   unfold inject_memval.\n                   subst j12'.\n                   rewrite compose in H2. rewrite compose_sm_as_inj in H2; eauto.\n                   apply compose_meminjD_Some in H2. \n                   destruct H2 as [bb1 [ofs1' [ofs' [map12 [map23 ofseq]]]]].\n                   rewrite map12. intros HH; inversion HH.\n                   subst nu23'; unfold change_ext. \n                   destruct nu12, nu23; simpl; apply GlueInv.\n                   subst nu23'; unfold change_ext. \n                   destruct nu12, nu23; simpl. \n                   subst extT12; subst extS23; simpl.\n                   f_equal; apply GlueInv.\n                 }\n                 \n                 (* pubBlocksSrc nu23 b2 = true & pubBlocksSrc nu12 b1 = false *)\n                 assert (PK: Mem.perm m1 b1 ofs Cur Readable).\n                 eapply UnchPrivSrc; eauto. unfold compose_sm; simpl; split; auto; auto_sm.\n                 auto_sm. \n                 destruct UnchPrivSrc as [_ UPS].\n                  rewrite UPS; try assumption; try (split; assumption).\n                  eapply memval_inject_incr.\n                    apply MInj12; eauto.\n                    apply local_in_all; auto.\n                    apply extern_incr_as_inj; eauto.\n                    unfold compose_sm; simpl; split; auto; auto_sm.\n\n                     eapply meminj_no_overlap_inject_incr.\n                      apply MInj12.\n                      apply local_in_all.\n                      assumption.\n                     eapply any_Max_Nonempty.\n                      apply Fwd1; eauto.\n                      auto_sm.\n                      eapply any_Max_Nonempty; eauto.\n                 \n                 (* pubBlocksSrc nu23 b2 = false & \"pubBlocksSrc nu12 b1 = false\"/proved *)\n                 destruct (pubBlocksSrc nu12 b1) eqn:pub12.\n                 { (*this case yields contradiction*)\n                   apply SMWD12 in pub12. destruct pub12 as [b2' [z [loc12 pubTgt]]].\n                   rewrite locmap in loc12; inversion loc12; subst b2' z.\n                   apply GlueInv in pubTgt.\n                   rewrite pubTgt in pub23; discriminate pub23. }\n                 assert (PK: Mem.perm m1 b1 ofs Cur Readable).\n                 eapply UnchPrivSrc; eauto. unfold compose_sm; simpl; split; auto; auto_sm.\n                 auto_sm. \n                 destruct UnchPrivSrc as [_ UPS].\n                  rewrite UPS; try assumption; try (split; assumption).\n                  eapply memval_inject_incr.\n                    apply MInj12; eauto.\n                    apply local_in_all; auto.\n                    apply extern_incr_as_inj; eauto.\n                    unfold compose_sm; simpl; split; auto; auto_sm.\n           }\n       + intros. unfold as_inj; subst nu12'; rewrite ext_change_ext, loc_change_ext.\n         assert (H0: ~ Mem.valid_block m1 b). \n         { clear - H Fwd1. unfold not, Mem.valid_block in *.\n           intros; apply H. apply (Pos.lt_le_trans _ _ _ H0).\n           apply forward_nextblock; assumption. }\n         destruct MInj12, MemInjNu'.\n         apply mi_freeblocks in H0; destruct (as_injD_None _ _ H0) as [ext loc].\n         apply mi_freeblocks0 in H; destruct (as_injD_None _ _ H) as [ext' loc'].\n         unfold join.\n         erewrite MKI_None12; eauto; subst j k l'; eauto.\n       + unfold as_inj; subst nu12'.\n         intros b b' delta map; destruct (as_in_SomeE _ _ _ _ map) as [ext | loc].\n         rewrite ext_change_ext in ext. \n         destruct (MKI_Some12 _ _ _ _ _ _ Heqoutput _ _ _ ext).\n         destruct MInj12.\n         unfold Mem.valid_block; rewrite property_nb; unfold mem_add_nb.\n         eapply Pos.lt_trans; try eapply (Pos.lt_add_diag_r (Mem.nextblock m2)).\n         apply (mi_mappedblocks b b' delta).\n         unfold as_inj, join; subst j k l'; rewrite H; auto.\n         destruct H as [jmap [b2' [d' [lmap' [eq1 eq2]]]]].\n         destruct MemInjNu'. unfold Mem.valid_block; rewrite property_nb.\n         unfold mem_add_nb. subst b'.\n         destruct WDnu'.\n         subst l'.\n         apply extern_DomRng in lmap'; destruct lmap' as [extS extT].\n         destruct SMvalNu' as [DOMv RNGv].\n         assert (Plt b m1'.(Mem.nextblock)).\n         apply DOMv. unfold DOM, DomSrc. rewrite extS; apply orb_true_r.\n         xomega.\n\n         unfold Mem.valid_block; rewrite property_nb.\n         unfold mem_add_nb.\n         rewrite loc_change_ext in loc.\n         destruct SMWD12.\n         apply local_DomRng in loc; destruct loc as [locS locT].\n         destruct SMV12 as [DOMv RNGv].\n         assert (Plt b' m2.(Mem.nextblock)).\n         apply RNGv. unfold RNG, DomTgt. rewrite locT; apply orb_true_l.\n         xomega.\n       + subst j12'; exact no_overlap12'. (*Proven earlier*)\n       + intros.\n         subst nu12'. apply as_in_SomeE in H; destruct H as [ext1 | loc1];\n         [ rewrite ext_change_ext in ext1 | rewrite loc_change_ext in loc1].\n         - eapply MKI_Some12 in ext1; eauto. \n           destruct ext1 as [jmap | [jmap [b3 [d [lmap' [beq deq]]]]]].\n           assert (map12: as_inj nu12 b = Some (b', delta)).\n           { unfold as_inj, join ; subst j; rewrite jmap; eauto. }\n           destruct MInj12. eapply mi_representable; eauto. \n           destruct H0; [left | right].\n           eapply Fwd1.\n           \n           eapply valid_from_map. \n           apply SMWD12.\n           apply map12.\n           eassumption.\n           assumption.\n\n           eapply Fwd1.\n           eapply valid_from_map. apply SMWD12.\n           apply map12.\n           eassumption.\n           assumption.\n\n           destruct ofs as [ofs range].\n           subst delta; split; simpl. \n           xomega. \n           split.\n           xomega.\n           unfold Int.max_unsigned.\n           xomega.\n         - assert (map12: as_inj nu12 b = Some (b', delta)).\n           { apply local_in_all; auto. }\n           destruct MInj12. eapply mi_representable; eauto. \n           destruct H0; [left | right].\n           eapply Fwd1; eauto.\n           eapply (valid_from_map nu12); eauto.\n           eapply Fwd1; eauto.\n           eapply (valid_from_map nu12); eauto.\n           }\n       split.\n       (* mem_forward *)\n       { exact Fwd2. }\n       split.\n       (* Mem.inject 23*)\n       { constructor.\n         + constructor.\n         - { intros b1 b2 delta ofs k0 p map23.\n             unfold Mem.perm. rewrite property_acc; unfold mem_add_acc.\n             unfold as_inj in map23; apply joinD_Some in map23.\n             destruct map23 as [extmap | [extmap locmap]].\n             + subst nu23'.\n               rewrite ext_change_ext in extmap.\n               eapply MKI_Some23 in extmap; eauto. \n               destruct extmap as [kmap | [kmap [lmap' [jmapN bGt]]]].\n               - assert (bavl: Mem.valid_block m2 b1).\n                 { apply SMV23; eauto. \n                   unfold DOM; eapply as_inj_DomRng; eauto.\n                   apply extern_in_all; subst k; eauto. }\n                 destruct (valid_dec m2 b1); try solve[contradict n; auto].\n                 \n                 assert (locS: locBlocksSrc nu23 b1 = false) by (subst k; auto_sm).\n                 rewrite locS.\n                 destruct (source (as_inj nu12) m1 b1 ofs) eqn:sour.\n                 * symmetry in sour. destruct (source_SomeE _ _ _ _ _ sour) \n                    as [b1' [delta' [ofs1 [pairs [bval [jpmap [mperm ofss]]]]]]].\n                   subst ofs p0. \n                   replace (ofs1 + delta' + delta) with (ofs1 + (delta' + delta)) by omega.\n                   eapply MemInjNu'.\n                   (*as_inj nu' b1' = Some (b2, delta' + delta)*)\n                   { apply as_in_SomeE in jpmap. destruct jpmap as [extmap | locmap].\n                     + unfold as_inj, join.\n                       rewrite compose, compose_sm_extern. unfold compose_meminj.\n                       apply ExtIncr12 in extmap; rewrite extmap.\n                       subst k; apply ExtIncr23 in kmap.\n                       rewrite kmap. auto. \n                     + (*impossible case*) \n                       eapply SMWD12 in locmap; destruct locmap as [locS' locT'].\n                       destruct GlueInv as [loc rest]; rewrite loc in locT'.\n                       rewrite locT' in locS; inversion locS.\n                   }\n                 * subst k; rewrite (extern_in_all _ _ _ _ kmap).\n                   intros H; inversion H.\n               - assert (bval: ~ Mem.valid_block m2 b1).\n                 { unfold Mem.valid_block, Plt, Pos.lt. intros HH. \n                   rewrite bGt in HH. inversion HH. }\n                 destruct (valid_dec m2 b1); try solve [contradict bval; trivial].\n                 destruct (source j12' m1' b1 ofs) eqn:sour; try solve[intros H; inversion H].\n                 symmetry in sour. destruct (source_SomeE _ _ _ _ _ sour) \n                                   as [b1' [delta' [ofs1 [pairs [bval' [jpmap [mperm ofss]]]]]]].\n                 subst ofs p0.\n                 replace (ofs1 + delta' + delta) with (ofs1 + (delta' + delta)) by omega.\n                 eapply MemInjNu'.\n                 { (*as_inj nu' b1' = Some (b2, delta' + delta)*)\n                   subst j12'. apply as_in_SomeE in jpmap.\n                   destruct jpmap as [extmap | locmap].\n                   + subst nu12'; rewrite ext_change_ext in extmap.\n                     eapply MKI_Some12 in extmap; eauto.\n                     destruct extmap as [jmap | [jmap [b2' [d' [lmap'' [b1eq deltaeq]]]]]].\n                     - contradict n. subst j; auto_sm.\n                     - subst b1 delta'. replace (0 + delta) with delta by omega.\n                       unfold as_inj, join. \n                       rewrite compose, compose_sm_extern, ext_change_ext.\n                       inversion Heqoutput.\n                       unfold compose_meminj, add_inj, shiftT, filter_id.\n                       rewrite jmap, lmap''.\n                       rewrite ext_change_ext, kmap.\n                       unfold pure_filter, shiftS.\n                       rewrite bGt. rewrite Pos.add_sub, jmap. \n                       rewrite Pos.add_sub in lmap'.\n                       rewrite lmap'; auto.\n                   + contradict n. subst nu12'. rewrite loc_change_ext in locmap. auto_sm.\n                 }\n             + subst nu23' ; rewrite loc_change_ext in locmap.\n               assert (bavl: Mem.valid_block m2 b1).\n               { apply SMV23; eauto. \n                 unfold DOM; eapply as_inj_DomRng; eauto.\n                 apply local_in_all; eauto. }\n               destruct (valid_dec m2 b1); try solve [contradict n; trivial].\n               assert (locS: locBlocksSrc nu23 b1 = true) by auto_sm.\n               rewrite locS.\n               destruct (pubBlocksSrc nu23 b1) eqn:pubS.\n               - destruct (source (local_of nu12) m1 b1 ofs) eqn:sour.\n                 \n                 *  symmetry in sour. destruct (source_SomeE _ _ _ _ _ sour) \n                                     as [b1' [delta' [ofs1 [pairs [bval' [jpmap [mper ofss]]]]]]].\n                   inversion pairs; subst ofs p0; clear sour.\n                   replace (ofs1 + delta' + delta) with (ofs1 + (delta' + delta)) by omega.\n                   destruct (pubBlocksSrc nu12 b1') eqn: pubS12.\n                   intros mperm. eapply MemInjNu'.\n                   apply local_in_all; auto. rewrite compose; unfold compose_sm; simpl.\n                   rewrite loc_change_ext; unfold compose_meminj.\n                   instantiate(1:=b1').\n                   (*Attention*)\n                   (*This thing behaeve weirdly! check what happens if you don't instantiate...*)\n                   assert (locmap12': local_of nu12' b1' = Some (b1, delta')).\n                   { move ExtIncr12 at bottom; unfold extern_incr in ExtIncr12.\n                     destruct ExtIncr12 as [? [loc_inc ?]].\n                     rewrite <- loc_inc; eauto. } \n                   rewrite locmap12'; rewrite locmap; auto.\n                   assumption.\n\n                   \n                   intros. eapply UnchLOOR13. \n                   unfold local_out_of_reach; unfold compose_sm; simpl; split.\n                   auto_sm.\n                   intros b0; intros.\n                   destruct (pubBlocksSrc nu12 b0) eqn:pubS12'; try (right; reflexivity).\n                   unfold compose_meminj in H1. \n                   destruct (local_of nu12 b0) eqn:locmap12; try solve[inversion H1].\n                   destruct p0.\n                   destruct (eq_block b0 b1'); try subst b0.\n                   rewrite pubS12 in pubS12'; discriminate.\n                   left; intros N. \n                   apply local_in_all in locmap12; trivial.\n                   apply local_in_all in locmap; trivial.\n                   assert (MX: Mem.perm m2 b1 (ofs1 + delta') Max Nonempty).\n                   {eapply Mem.perm_max; eapply Mem.perm_implies. eassumption. apply perm_any_N. }\n                   destruct (Mem.inject_compose _ _ _ _ _ MInj12 MInj23). \n                   edestruct (mi_no_overlap b0 b2); try eassumption.\n                   { destruct (local_of nu23 b) eqn:loc23; try solve[inversion H1]. \n                     destruct p0. instantiate (1:=delta0).\n                     inversion H1; subst b3 delta0.\n                     unfold compose_meminj; rewrite locmap12. \n                     erewrite (local_in_all nu23); eauto. }\n                   instantiate(1:=delta' + delta). \n                   { instantiate(1:=b2). unfold compose_meminj.\n                      erewrite (local_in_all nu12); eauto. \n                      rewrite locmap; auto. }\n                   apply H2; auto.\n                   apply H2; omega.\n                   auto_sm.\n                   replace  (ofs1 + (delta' + delta))  with  (ofs1 + delta' + delta) by omega. \n                   eapply MInj23.\n                   eapply local_in_all; eauto.\n                   auto.\n\n                   \n                 * (*This case is impossible NOT*)\n                   intros.\n                   eapply UnchLOOR13.\n                   unfold local_out_of_reach; unfold compose_sm; simpl; split.\n                   auto_sm.\n                   intros b0; intros.\n                   unfold compose_meminj in H0.\n                   destruct (local_of nu12 b0) eqn:locmap12; try solve [inversion H0].\n                   destruct p0.\n                   destruct (local_of nu23 b) eqn:locmap23; try solve [inversion H0].\n                   destruct p0; inversion H0. subst b2 delta0. clear H0.\n                   \n                   destruct (eq_block b b1); try subst b.\n                   rewrite locmap in locmap23; inversion locmap23; subst delta.\n                   \n                   symmetry in sour; eapply (source_NoneE) in sour; eauto.\n                   destruct (pubBlocksSrc nu12 b0) eqn:pubS12'; try (right; reflexivity).\n                   left.\n                   replace (ofs + z0 - (z + z0)) with (ofs - z) by omega; eauto.\n                   assert (valid:Mem.valid_block m1 b0) by auto_sm; apply valid.\n                   left; intros N. apply local_in_all in locmap12; trivial.\n                   apply (Mem.perm_inject (as_inj nu12) _ _ _ _ _ _ _ _ locmap12 MInj12) in N.            \n                   edestruct (Mem.mi_no_overlap _ _ _ MInj23 b).\n                   exact n.\n                   apply local_in_all; first [exact SMWD23 | exact locmap23].\n                   apply local_in_all; first [exact SMWD23 | exact locmap].\n                   exact N.\n                   eapply any_Max_Nonempty. exact H.\n                   apply H0; trivial.\n                   apply H0; trivial.\n                   omega.\n                   auto_sm.\n                   eapply MInj23. \n                   apply local_in_all; first [exact SMWD23 | exact locmap].\n                   exact H.\n               -\n               {\n               intros. eapply UnchLOOR23.\n               unfold local_out_of_reach; split.\n               auto_sm.\n               intros bb2; intros.\n               destruct (pubBlocksSrc nu23 bb2) eqn:pubS23; try (right; reflexivity).\n               destruct (eq_block bb2 b1); try subst bb2.\n                 rewrite pubS23 in pubS; discriminate.\n               left; intros N. \n               apply local_in_all in H0; trivial.\n               apply local_in_all in locmap; trivial.\n                   assert (MX: Mem.perm m2 b1 ofs Max Nonempty).\n                   {eapply Mem.perm_max; eapply Mem.perm_implies. eassumption. apply perm_any_N. }\n                   destruct (Mem.mi_no_overlap _ _ _ MInj23 bb2 _ _ _ _ _ _ _ n H0 locmap N MX).\n                   apply H1; trivial.\n                   apply H1; clear H1. omega.\n                   auto_sm.\n                   eapply MInj23. apply local_in_all; eauto. apply H.\n               }\n             }\n         - intros. unfold Z.divide.\n           subst nu23'; unfold as_inj, join in H. rewrite ext_change_ext, loc_change_ext in H.\n           destruct (k' b1) eqn:kmap'. \n           * destruct p0. destruct (MKI_Some23 _ _ _ _ _ _ Heqoutput _ _ _ kmap') as \n                          [kmap | [kmap [lmap [jmapN bGt]]]].\n           inversion H; subst b z.\n           subst k. destruct MInj23. destruct mi_inj.\n           eapply (mi_align b1 b2); eauto. \n           unfold as_inj, join; rewrite kmap; trivial.\n           eapply forward_range; eauto.\n           eapply mapped_valid.\n           apply SMWD23. \n           unfold as_inj, join; rewrite kmap; auto. \n           eauto.\n\n           unfold Mem.range_perm, Mem.perm in H0.\n           rewrite property_acc in H0; unfold mem_add_acc in H0.\n           destruct (valid_dec m2 b1).\n           { contradict v. unfold not, Mem.valid_block. clear - bGt.\n             unfold Plt, Pos.lt. intros H; rewrite H in bGt; inversion bGt. }\n           \n           \n           (* This should be folded in a lemma *)\n          (* inversion Heqoutput. inversion H; subst b z.\n           unfold add_inj, shiftS in H3. rewrite H3 in kmap'. rewrite kmap in kmap'.\n           destruct (b1 ?= Mem.nextblock m2)%positive; try solve[inversion kmap'].\n           apply pure_filter_Some in kmap'. destruct kmap' as [jmap lmap'].*)\n           inversion H; subst b z. \n           eapply MemInjNu'.\n           eapply extern_in_all. subst l'. \n           instantiate(1:=b2). instantiate(1:=(b1 - Mem.nextblock m2)%positive). \n            exact lmap.\n            unfold Mem.range_perm.\n            intros ofs0 H1. apply H0 in H1.\n            destruct (source j12' m1' b1 ofs0) eqn:sour; try solve [inversion H1].\n\n            \n            symmetry in sour; apply source_SomeE in sour.\n            destruct sour as [b1' [delta' [ofs1 [invertible [leq [mapj [mperm ofs_add]]]]]]].\n            subst p0 ofs0.\n            subst j12'. unfold as_inj, join in mapj. \n            \n            inversion Heqoutput.\n            subst nu12'. rewrite ext_change_ext in mapj.\n            rewrite H3 in mapj.\n            unfold add_inj in mapj. \n            destruct ( j b1') eqn:jmap. destruct p0; inversion mapj; subst b1 delta'.\n            {contradict n. \n            apply SMV12. unfold RNG, DomTgt.\n            subst j. apply SMWD12 in jmap. destruct jmap as [extS extT]; rewrite extT.\n            apply orb_true_r. }\n            unfold filter_id, shiftT in mapj.\n            { (*Show b1' = b1 - sizeM2 /\\ delta' = 0 *)\n              destruct (l' b1') eqn:lmap'. inversion mapj; subst b1 delta'.\n              + rewrite Pos.add_sub; replace (ofs1 +0) with ofs1 by omega; eauto.\n              + rewrite loc_change_ext in mapj.\n                assert (Mem.valid_block m2 b1) by auto_sm.\n                unfold Mem.valid_block, Plt, Pos.lt in H2.\n                rewrite H2 in bGt; inversion bGt. }\n           * eapply MInj23; try assumption.\n             apply local_in_all; eauto; exact H.\n             intros z; intros. specialize (H0 _ H1).\n             apply Fwd2; eauto. auto_sm.\n                \n         - { (*mi_memval23*)\n             intros b1 ofs b2 delta map23.\n             unfold Mem.perm. \n             rewrite property_cont; unfold mem_add_cont.\n              rewrite property_acc; unfold mem_add_acc.\n             unfold as_inj in map23; apply joinD_Some in map23.\n             destruct map23 as [extmap | [extmap locmap]].\n             + subst nu23'.\n               rewrite ext_change_ext in extmap.\n               eapply MKI_Some23 in extmap; eauto. \n               destruct extmap as [kmap | [kmap [lmap' [jmapN bGt]]]].\n               - assert (bavl: Mem.valid_block m2 b1).\n                 { apply SMV23; eauto. \n                   unfold DOM; eapply as_inj_DomRng; eauto.\n                   apply extern_in_all; subst k; eauto. }\n                 destruct (valid_dec m2 b1); try solve[contradict n; auto].\n                 \n                 assert (locS: locBlocksSrc nu23 b1 = false) by (subst k; auto_sm).\n                 rewrite locS.\n                 destruct (source (as_inj nu12) m1 b1 ofs) eqn:sour.\n                 * symmetry in sour. destruct (source_SomeE _ _ _ _ _ sour) \n                    as [b1' [delta' [ofs1 [pairs [bval [jpmap [mperm' ofss]]]]]]].\n                   subst ofs p. \n                   replace (ofs1 + delta' + delta) with (ofs1 + (delta' + delta)) by omega.\n                   (*Do the memval*)\n                   destruct MemInjNu'. destruct mi_inj.\n                   move mi_memval at bottom. \n                   intros mperm.\n                   eapply (mi_memval _ _ b2 (delta' + delta)) in mperm.\n                   inversion mperm; try constructor.\n                   unfold inject_memval. \n                   subst j12'. \n                   remember (change_ext nu23 extS23 extT23 k') as nu23'.\n                   \n                   assert (maps: exists b2' ofs1 ofs2, as_inj nu12' b0 = Some (b2',ofs1)\n                           /\\ as_inj nu23' b2' = Some (b3, ofs2)\n                           /\\ delta0 = ofs1 + ofs2 ).\n                   { apply as_in_SomeE in H1; rewrite compose in H1;\n                     destruct H1 as [extmap | locmap].\n                     + rewrite compose_sm_extern  in extmap.\n                       apply compose_meminjD_Some in extmap.\n                       destruct extmap as [b2' [ofs1' [ofs2' [ext12 [ext23 deltaeq ] ]]]].\n                       exists b2', ofs1', ofs2'.\n                       split. apply extern_in_all; auto.\n                       split. apply extern_in_all; auto.\n                       auto.\n                     + rewrite compose_sm_local in locmap.\n                       apply compose_meminjD_Some in locmap.\n                       destruct locmap as [b2' [ofs1' [ofs2' [ext12 [ext23 deltaeq ] ]]]].\n                       exists b2', ofs1', ofs2'.\n                       split. apply local_in_all; auto.\n                       split. apply local_in_all; auto.\n                       auto.\n                   }\n                   destruct maps as [b2' [ofs1' [ofs2'  [map12' [map23' ofseq]]]]].\n                   rewrite map12'.\n                   econstructor. \n                   exact map23'.\n                   subst ofs2 delta0. \n                   { (* Int arithmetics *)\n                     rewrite Int.add_assoc. f_equal.\n                     rewrite Int.add_unsigned.\n                     apply Int.eqm_samerepr.\n                     apply Int.eqm_add;\n                     apply Int.eqm_unsigned_repr. }\n                   {(*as_inj nu' b1' = Some (b2, delta' + delta)*)\n                   subst j12'. apply as_in_SomeE in jpmap.\n                   destruct jpmap as [extmap | locmap].\n                   + rewrite compose; unfold as_inj, join, compose_sm, compose_meminj.\n                     simpl. eapply ExtIncr12 in extmap; rewrite extmap.\n                     subst k; eapply ExtIncr23 in kmap.\n                     rewrite kmap; auto.\n                   + apply SMWD12 in locmap; destruct locmap as [locS' locT'].\n                     destruct GlueInv as [loc rest]; rewrite loc in locT'.\n                     subst k; apply SMWD23 in kmap; destruct kmap as [extS extT].\n                     destruct SMWD23 as [Src rest'].\n                     destruct (Src b1) as [ locSTrue | extSTrue].\n                     rewrite locSTrue in locT'; inversion locT'.\n                     rewrite extSTrue in extS; inversion extS.\n                   }\n                 * subst k; rewrite (extern_in_all _ _ _ _ kmap).\n                   intros H; inversion H.\n               - assert (bval: ~ Mem.valid_block m2 b1). \n                 { unfold Mem.valid_block, Plt, Pos.lt; intros HH.\n                   rewrite HH in bGt; inversion bGt. }\n                 destruct (valid_dec m2 b1); try solve [contradict bval; trivial].\n                 destruct (source j12' m1' b1 ofs) eqn:sour; try solve[intros H; inversion H].\n                 symmetry in sour. destruct (source_SomeE _ _ _ _ _ sour) \n                                   as [b1' [delta' [ofs1 [pairs [bval' [jpmap [mperm ofss]]]]]]].\n                 subst ofs p.\n                 replace (ofs1 + delta' + delta) with (ofs1 + (delta' + delta)) by omega.\n                 (*Do the memval*)\n                 destruct MemInjNu'. destruct mi_inj.\n                 move mi_memval at bottom. \n                 intros mperm'.\n                 eapply (mi_memval _ _ b2 (delta' + delta)) in mperm'.\n                 inversion mperm'; try constructor.\n                 unfold inject_memval. \n                 subst j12'. \n                 remember (change_ext nu23 extS23 extT23 k') as nu23'.\n                 assert (maps: exists b2' ofs1 ofs2, as_inj nu12' b0 = Some (b2',ofs1)\n                           /\\ as_inj nu23' b2' = Some (b3, ofs2)\n                           /\\ delta0 = ofs1 + ofs2 ).\n                   { apply as_in_SomeE in H1; rewrite compose in H1;\n                     destruct H1 as [extmap | locmap].\n                     + rewrite compose_sm_extern  in extmap.\n                       apply compose_meminjD_Some in extmap.\n                       destruct extmap as [b2' [ofs1' [ofs2' [ext12 [ext23 deltaeq ] ]]]].\n                       exists b2', ofs1', ofs2'.\n                       split. apply extern_in_all; auto.\n                       split. apply extern_in_all; auto.\n                       auto.\n                     + rewrite compose_sm_local in locmap.\n                       apply compose_meminjD_Some in locmap.\n                       destruct locmap as [b2' [ofs1' [ofs2' [ext12 [ext23 deltaeq ] ]]]].\n                       exists b2', ofs1', ofs2'.\n                       split. apply local_in_all; auto.\n                       split. apply local_in_all; auto.\n                       auto.\n                   }\n                 destruct maps as [b2' [ofs1' [ofs2' [map12' [map23' ofseq]]]]].\n                 rewrite map12'.\n                 econstructor. \n                 exact map23'.\n                 subst ofs2 delta0. \n                 {  (* Int arithmetics *)\n                     rewrite Int.add_assoc. f_equal.\n                     rewrite Int.add_unsigned.\n                     apply Int.eqm_samerepr.\n                     apply Int.eqm_add;\n                     apply Int.eqm_unsigned_repr. }\n                 {(*as_inj nu' b1' = Some (b2, delta' + delta)*)\n                   subst j12'. apply as_in_SomeE in jpmap.\n                   destruct jpmap as [extmap | locmap].\n                   + assert (extmap':=extmap).\n                     eapply (MKI_Some12 j k l') in extmap';\n                       try solve [subst nu12'; rewrite ext_change_ext; eauto].\n                     destruct extmap' as [jmap | [jmap [b2' [d' [lmap2 [b2eq delteq]]]]]].\n                   - contradict n; subst j; auto_sm.\n                   - subst b1 delta'.\n                     (* Now just rewrite in compose *)\n                     rewrite compose; unfold as_inj, join, compose_sm, compose_meminj.\n                     simpl. rewrite extmap.\n                     rewrite ext_change_ext. inversion Heqoutput.\n                     unfold add_inj, pure_filter, shiftS.\n                     rewrite kmap, bGt, lmap'.\n                     rewrite Pos.add_sub, jmap.\n                     f_equal; omega.\n                   + contradiction n. subst nu12'. rewrite loc_change_ext in locmap. auto_sm.\n                 }\n             + subst nu23' ; rewrite loc_change_ext in locmap.\n               assert (bavl: Mem.valid_block m2 b1).\n               { apply SMV23; eauto. \n                 unfold DOM; eapply as_inj_DomRng; eauto.\n                 apply local_in_all; eauto. }\n               destruct (valid_dec m2 b1); try solve [contradict n; trivial].\n               assert (locS: locBlocksSrc nu23 b1 = true) by auto_sm.\n               rewrite locS.\n               destruct (pubBlocksSrc nu23 b1) eqn:pubS.\n               - destruct (source (local_of nu12) m1 b1 ofs) eqn:sour.\n                 \n                 *  symmetry in sour. destruct (source_SomeE _ _ _ _ _ sour) \n                                     as [b1' [delta' [ofs1 [pairs [bval' [jpmap [mper ofss]]]]]]].\n                   inversion pairs; subst ofs p; clear sour.\n                   replace (ofs1 + delta' + delta) with (ofs1 + (delta' + delta)) by omega.\n                   destruct (pubBlocksSrc nu12 b1') eqn: pubS12.\n                   intros mperm. \n                   (*Do the memval*)\n                   destruct MemInjNu'. destruct mi_inj.\n                   move mi_memval at bottom. \n                   eapply (mi_memval _ _ b2 (delta' + delta)) in mperm.\n                   inversion mperm; try constructor.\n                   unfold inject_memval. \n                   subst j12'. \n                   remember (change_ext nu23 extS23 extT23 k') as nu23'.\n                 \n                 assert (maps: exists b2' ofs1 ofs2, as_inj nu12' b0 = Some (b2',ofs1)\n                           /\\ as_inj nu23' b2' = Some (b3, ofs2)\n                           /\\ delta0 = ofs1 + ofs2 ).\n                   { apply as_in_SomeE in H2; rewrite compose in H2;\n                     destruct H2 as [extmap' | locmap'].\n                     + rewrite compose_sm_extern  in extmap'.\n                       apply compose_meminjD_Some in extmap'.\n                       destruct extmap' as [b2' [ofs1' [ofs2' [ext12 [ext23 deltaeq ] ]]]].\n                       exists b2', ofs1', ofs2'.\n                       split. apply extern_in_all; auto.\n                       split. apply extern_in_all; auto.\n                       auto.\n                     + rewrite compose_sm_local in locmap'.\n                       apply compose_meminjD_Some in locmap'.\n                       destruct locmap' as [b2' [ofs1' [ofs2' [ext12 [ext23 deltaeq ] ]]]].\n                       exists b2', ofs1', ofs2'.\n                       split. apply local_in_all; auto.\n                       split. apply local_in_all; auto.\n                       auto.\n                   }\n                   destruct maps as [b2' [ofs1' [ofs2' [map12' [map23' ofseq]]]]].\n                   rewrite map12'.\n                   econstructor. \n                   exact map23'.\n                   subst ofs2 delta0. \n                   { (* Int arithmetics *)\n                     rewrite Int.add_assoc. f_equal.\n                     rewrite Int.add_unsigned.\n                     apply Int.eqm_samerepr.\n                     apply Int.eqm_add;\n                     apply Int.eqm_unsigned_repr. }\n                   \n                   (*Why did I have to prove this again?*)\n                   apply local_in_all; auto.\n                   rewrite compose, compose_sm_local, loc_change_ext.\n                   unfold compose_meminj; subst nu12'. \n                   rewrite loc_change_ext, jpmap, locmap; auto.\n                   \n                   intros. \n                   destruct UnchLOOR13.\n                   rewrite unchanged_on_contents.\n                   eapply memval_inject_incr. \n                   replace (ofs1 + (delta' + delta)) with (ofs1 + delta' + delta) by omega.\n                   eapply MInj23.\n                   auto_sm.\n                   exact H0.\n                   apply extern_incr_as_inj; eauto.\n\n                   unfold local_out_of_reach; unfold compose_sm; simpl; split.\n                   auto_sm.\n                   intros b0; intros.\n                   destruct (pubBlocksSrc nu12 b0) eqn:pubS12'; try (right; reflexivity).\n                   unfold compose_meminj in H1. \n                   destruct (local_of nu12 b0) eqn:locmap12; try solve[inversion H1].\n                   destruct p.\n                   destruct (eq_block b0 b1'); try subst b0.\n                   rewrite pubS12 in pubS12'; discriminate.\n                   left; intros N. \n                   apply local_in_all in locmap12; trivial.\n                   apply local_in_all in locmap; trivial.\n                   assert (MX: Mem.perm m2 b1 (ofs1 + delta') Max Nonempty).\n                   {eapply Mem.perm_max; eapply Mem.perm_implies. eassumption. apply perm_any_N. }\n                   destruct (Mem.inject_compose _ _ _ _ _ MInj12 MInj23). \n                   edestruct (mi_no_overlap b0 b2); try eassumption.\n                   { destruct (local_of nu23 b) eqn:loc23; try solve[inversion H1]. \n                     destruct p. instantiate (1:=delta0).\n                     inversion H1; subst b3 delta0.\n                     unfold compose_meminj; rewrite locmap12. \n                     erewrite (local_in_all nu23); eauto. }\n                   instantiate(1:=delta' + delta). \n                   { instantiate(1:=b2). unfold compose_meminj.\n                      erewrite (local_in_all nu12); eauto. \n                      rewrite locmap; auto. }\n                   apply H2; auto.\n                   apply H2; omega.\n                   replace  (ofs1 + (delta' + delta))  with  (ofs1 + delta' + delta) by omega. \n                   eapply MInj23.\n                   eapply local_in_all; eauto.\n                   auto.\n\n                 * (*This case is impossible NOT*)\n                   intros. \n                   destruct UnchLOOR13.\n                   rewrite unchanged_on_contents.\n                   eapply memval_inject_incr. \n                   eapply MInj23.\n                   auto_sm.\n                   exact H.\n                   apply extern_incr_as_inj; eauto.\n                   \n                   unfold local_out_of_reach; unfold compose_sm; simpl; split.\n                   auto_sm.\n                   intros b0; intros.\n                   unfold compose_meminj in H0.\n                   destruct (local_of nu12 b0) eqn:locmap12; try solve [inversion H0].\n                   destruct p.\n                   destruct (local_of nu23 b) eqn:locmap23; try solve [inversion H0].\n                   destruct p; inversion H0. subst b2 delta0. clear H0.\n                   \n                   destruct (eq_block b b1); try subst b.\n                   rewrite locmap in locmap23; inversion locmap23; subst delta.\n                   \n                   symmetry in sour; eapply (source_NoneE) in sour; eauto.\n                   destruct (pubBlocksSrc nu12 b0) eqn:pubS12'; try (right; reflexivity).\n                   left.\n                   replace (ofs + z0 - (z + z0)) with (ofs - z) by omega; eauto.\n                   assert (valid:Mem.valid_block m1 b0) by auto_sm; apply valid.\n                   left; intros N. apply local_in_all in locmap12; trivial.\n                   apply (Mem.perm_inject (as_inj nu12) _ _ _ _ _ _ _ _ locmap12 MInj12) in N.            \n                   edestruct (Mem.mi_no_overlap _ _ _ MInj23 b).\n                   exact n.\n                   apply local_in_all; first [exact SMWD23 | exact locmap23].\n                   apply local_in_all; first [exact SMWD23 | exact locmap].\n                   exact N.\n                   eapply any_Max_Nonempty. exact H.\n                   apply H0; trivial.\n                   apply H0; trivial.\n                   omega.\n                   eapply MInj23. \n                   apply local_in_all; first [exact SMWD23 | exact locmap].\n                   exact H.\n               -\n                 {intros. \n                   destruct UnchLOOR23.\n                   rewrite unchanged_on_contents.\n                   eapply memval_inject_incr. \n                   eapply MInj23.\n                   auto_sm.\n                   exact H.\n                   apply extern_incr_as_inj; eauto.\n                 \n                   unfold local_out_of_reach; split.\n                   destruct GlueInv as [loc rest].\n                   unfold compose_sm; simpl; auto_sm.\n                   intros bb2; intros.\n                   destruct (pubBlocksSrc nu23 bb2) eqn:pubS23; try (right; reflexivity).\n                   destruct (eq_block bb2 b1); try subst bb2.\n                   rewrite pubS23 in pubS; discriminate.\n                   left; intros N. \n                   apply local_in_all in H0; trivial.\n                   apply local_in_all in locmap; trivial.\n                   assert (MX: Mem.perm m2 b1 ofs Max Nonempty).\n                   {eapply Mem.perm_max; eapply Mem.perm_implies. eassumption. apply perm_any_N. }\n                   destruct (Mem.mi_no_overlap _ _ _ MInj23 bb2 _ _ _ _ _ _ _ n H0 locmap N MX).\n                   apply H1; trivial.\n                   apply H1; clear H1. omega.\n                   eapply MInj23. apply local_in_all; eauto. apply H.\n               }\n             }\n      + intros b H. unfold Mem.valid_block in H.\n        rewrite property_nb in H.\n        unfold mem_add_nb in H.\n        destruct (as_inj nu23' b) eqn:map; trivial.\n        contradict H. unfold as_inj in map; destruct p.\n        destruct (joinD_Some _ _ _ _ _ map) as [extmap | [extmap locmap]].\n         - subst nu23'. rewrite ext_change_ext in extmap.\n           inversion Heqoutput; subst k'.\n           unfold add_inj in extmap. \n           destruct (k b) eqn:kmap.\n           assert (Mem.valid_block m2 b).\n           { eapply SMV23. unfold DOM, DomSrc.\n             inversion extmap; subst p k. apply SMWD23 in kmap.\n             destruct kmap as [extS extT]; rewrite extS; apply orb_true_r. }\n           unfold Mem.valid_block in H. apply (Plt_trans _ _ _ H); xomega.\n           apply shiftS_Some in extmap.\n           destruct extmap.\n           apply pure_filter_Some in H1; destruct H1.\n           { assert (Mem.valid_block m1' (b - Mem.nextblock m2)%positive ) \n               by (subst l'; auto_sm).\n           unfold Mem.valid_block in H3. clear - H H3. \n           unfold Plt in *. \n           apply Pos.lt_iff_add; apply Pos.lt_iff_add in H3. destruct H3 as  [r sum].\n           exists r. \n           rewrite Pos.add_comm in *.\n           rewrite <- sum.\n           rewrite (Pos.add_comm (Mem.nextblock m2) (r + (b - Mem.nextblock m2))).\n           rewrite <- Pos.add_assoc.\n           rewrite Pos.sub_add; eauto.\n           apply Pos.gt_lt_iff; auto. }\n           \n         - assert (Mem.valid_block m2 b).\n           { eapply SMV23. unfold DOM, DomSrc. subst nu23'.\n             rewrite loc_change_ext in locmap.\n             apply SMWD23 in locmap.\n             destruct locmap as [locS locT]; rewrite locS; apply orb_true_l. }\n           unfold Mem.valid_block in H. apply (Plt_trans _ _ _ H); xomega.\n       + intros b b' d H.\n         unfold as_inj. \n         subst nu23'; destruct (joinD_Some _ _ _ _ _ H) as [extmap | [extmap locmap]].\n         - rewrite ext_change_ext in extmap.\n           inversion Heqoutput; subst k'.\n            unfold add_inj in extmap. \n            destruct (k b) eqn:kmap.\n           assert (Mem.valid_block m3 b').\n           { eapply SMV23. unfold RNG, DomTgt.\n             inversion extmap; subst p k. apply SMWD23 in kmap.\n             destruct kmap as [extS extT]; rewrite extT; apply orb_true_r. }\n           eapply Fwd3 in H0. destruct H0; auto.\n           apply shiftS_Some in extmap.\n           destruct extmap.\n           apply pure_filter_Some in H2.\n           destruct H2 as [? ?].\n           apply SMvalNu'.\n           unfold RNG, DomTgt.\n           subst l'. apply WDnu' in H3; destruct H3. rewrite H4; apply orb_true_r.\n         - assert (Mem.valid_block m3 b').\n           { eapply SMV23. unfold RNG, DomTgt.\n             rewrite loc_change_ext in locmap.\n             apply SMWD23 in locmap.\n             destruct locmap as [locS locT]; rewrite locT; apply orb_true_l. }\n           eapply Fwd3 in H0. destruct H0; auto.\n       + intros.\n         eapply no_overlap_asinj; auto.\n         - { (*no_overlap extern*)\n             unfold Mem.meminj_no_overlap; intros.\n             subst nu23'. rewrite ext_change_ext in H0, H1.\n             inversion Heqoutput; subst k'.\n             unfold add_inj in H0, H1. \n             destruct (k b1) eqn:kmap1; destruct (k b2) eqn:kmap2. \n             (*1. Good case old externs *)\n             eapply MInj23.\n             apply H.\n             eapply extern_in_all; auto.\n             inversion H0; subst k p; trivial.\n             eapply extern_in_all; auto.\n             inversion H1; subst k p0; trivial.\n             apply Fwd2; eauto.\n             subst k; auto_sm.\n             apply Fwd2; eauto.\n             subst k ; auto_sm.\n             (*2.cross case: Dificult case *)\n             { rewrite H0 in kmap1.\n               apply shiftS_Some in H1. destruct H1.\n               apply pure_filter_Some in H4. destruct H4.\n               inversion H0; subst p; clear H0.\n               rewrite Heqk in kmap1.\n               assert(kmap1':=kmap1).\n               unfold Mem.perm in H2, H3.\n               rewrite property_acc in H2, H3; \n                 unfold mem_add_acc in H2,H3.\n               assert (Mem.valid_block m2 b1) by auto_sm.\n               destruct (valid_dec m2 b1); \n                 try solve[destruct n; eauto].\n               destruct (valid_dec m2 b2).\n               { (* impossible case. *)\n               move v0 at bottom.\n               unfold Mem.valid_block, Plt, Pos.lt in v0. \n               unfold Pos.gt in H1. rewrite H1 in v0; inversion v0. }\n               destruct (source j12' m1' b2 ofs2) eqn:sour2; try solve[inversion H3].\n               assert (locF: locBlocksSrc nu23 b1 = false) by auto_sm.\n               rewrite locF in H2.\n               assert (totmap23: as_inj nu23 b1 = Some (b1', delta1)) \n                 by (apply extern_in_all; trivial).\n               rewrite totmap23 in H2.\n               destruct (source (as_inj nu12) m1 b1 ofs1) eqn:sour1; try solve[inversion H2].\n               symmetry in sour1, sour2. apply source_SomeE in sour1; apply source_SomeE in sour2.\n               destruct sour1 as [b01 [d01 [ofs01 [invert1 [bval1' [map121 [mparm1 of_eq1] ]]]]]].\n               subst p0 ofs1.\n               destruct sour2 as [b02 [d02 [ofs02 [invert2 [bval2' [map122 [mparm2 of_eq2] ]]]]]].\n               subst p ofs2.\n               replace (ofs01 + d01 + delta1) with (ofs01 + (d01 + delta1)) by omega.\n               replace (ofs02 + d02 + delta2) with (ofs02 + (d02 + delta2)) by omega.\n               assert (H': b01<> (b2 - Mem.nextblock m2)%positive).\n               { intros HH; subst b01.\n                 unfold as_inj, join in map121. rewrite Heqj in H4; rewrite H4 in map121.\n                 eapply SMWD12 in map121. destruct map121. destruct GlueInv as [loc rest].\n                 rewrite loc in H8. rewrite locF in H8; inversion H8. }\n               \n               (*We prove (d02 = 0) /\\ (b02 = (b2 - Mem.nextblock m2)%positive) *)\n               subst j12' nu12'. unfold as_inj, join in map122.\n               rewrite ext_change_ext in map122.\n               inversion Heqoutput; subst j'.\n               unfold add_inj, shiftT, filter_id in map122.\n               destruct (j b02) eqn:jmap. \n               { (*First case is impossible *)\n                 destruct p; inversion map122; subst b2 d02.\n                 contradict n. subst j; auto_sm. }\n               destruct (l' b02) eqn:lmap'; \n                 (*second case is impossible *)\n                 try solve [rewrite loc_change_ext in map122; contradict n; auto_sm].\n               inversion map122; subst b2 d02.\n               eapply MemInjNu'.\n               apply H'.\n               {\n               subst nu'.\n               unfold as_inj, join.\n               rewrite compose_sm_extern, ext_change_ext.\n               rewrite compose_sm_local, loc_change_ext.\n               rewrite ext_change_ext, loc_change_ext.\n               assert (jmap11: j b01 = Some (b1, d01)).\n                 { unfold as_inj in map121. \n                   apply joinD_Some in map121; destruct map121 as [extmap|[extmap locmap]].\n                   subst j; exact extmap.\n                   eapply SMWD12 in locmap. destruct locmap as [locS locT].\n                   eapply SMWD23 in kmap1. destruct kmap1 as [extS extT].\n                   destruct GlueInv as [loc rest]; rewrite loc in locT.\n                   destruct SMWD23. \n                   destruct (disjoint_extern_local_Src b1) as [locS'|extS'].\n                   rewrite locS' in locT; inversion locT.\n                   rewrite extS' in extS; inversion extS. }\n               unfold compose_meminj. unfold add_inj.\n               rewrite jmap11. subst k. rewrite kmap1. auto. }\n               { (*First show d02 = 0*)\n                 replace (0 + delta2) with delta2 by omega.\n                 unfold as_inj, join. \n                 subst l'; rewrite H6. auto. }\n               auto.\n               rewrite Pos.add_sub; auto. }\n             (*3.cross case: Dificult case *)\n             { rewrite H1 in kmap2.\n               apply shiftS_Some in H0. destruct H0.\n               apply pure_filter_Some in H4. destruct H4.\n               inversion H1; subst p; clear H1.\n               rewrite Heqk in kmap2.\n               assert(kmap2':=kmap2).\n               unfold Mem.perm in H2, H3.\n               rewrite property_acc in H2, H3; \n                 unfold mem_add_acc in H2,H3.\n               assert (Mem.valid_block m2 b2) by auto_sm.\n               destruct (valid_dec m2 b2) eqn:bval2; \n                 try solve[destruct n; eauto].\n               destruct (valid_dec m2 b1) eqn:bval1.\n               { unfold Mem.valid_block, Plt, Pos.lt in v0. move v0 at bottom.\n               unfold Pos.gt in H0. rewrite v0 in H0; inversion H0. }\n               destruct (source j12' m1' b1 ofs1) eqn:sour1; try solve[inversion H2].\n               assert (locF: locBlocksSrc nu23 b2 = false) by auto_sm.\n               rewrite locF in H3.\n               assert (totmap23: as_inj nu23 b2 = Some (b2', delta2)) \n                 by (apply extern_in_all; trivial).\n               rewrite totmap23 in H3.\n               destruct (source (as_inj nu12) m1 b2 ofs2) eqn:sour2; try solve[inversion H3].\n               symmetry in sour1, sour2. apply source_SomeE in sour1; apply source_SomeE in sour2.\n               destruct sour1 as [b01 [d01 [ofs01 [invert1 [bval1' [map121 [mparm1 of_eq1] ]]]]]].\n               subst p ofs1.\n               destruct sour2 as [b02 [d02 [ofs02 [invert2 [bval2' [map122 [mparm2 of_eq2] ]]]]]].\n               subst p0 ofs2.\n               replace (ofs01 + d01 + delta1) with (ofs01 + (d01 + delta1)) by omega.\n               replace (ofs02 + d02 + delta2) with (ofs02 + (d02 + delta2)) by omega.\n\n               (*We prove (d01 = 0) /\\ (b01 = (b1 - Mem.nextblock m2)%positive) *)\n               subst j12' nu12'. unfold as_inj, join in map121.\n               rewrite ext_change_ext in map121.\n               inversion Heqoutput; subst j'.\n               unfold add_inj, shiftT, filter_id in map121.\n               destruct (j b01) eqn:jmap. \n               { (*First case is impossible *)\n                 destruct p; inversion map121. subst b1 d01.\n                 exfalso. apply n. subst j; auto_sm. }\n               destruct (l' b01) eqn:lmap';\n                 (*second case is impossible *)\n                 try solve [ rewrite loc_change_ext in map121; exfalso; apply n; auto_sm].\n               inversion map121; subst b1 d01.\n               assert (H': b01 <> b02). \n               { destruct (peq b01 b02); trivial.\n                 subst b02. (*  *)\n                 unfold as_inj in map122; apply joinD_Some in map122; \n                 destruct map122 as [extmap | [xtmap locmap]].\n                 subst j; rewrite jmap in extmap; inversion extmap.\n                 apply SMWD12 in locmap; destruct locmap as [locS locT].\n                 rewrite Pos.add_sub in H6. rewrite Heql' in H6; apply WDnu' in H6.\n                 destruct H6 as [extS' extT'].\n                 destruct ExtIncr as [injinc [ ? [ ? [? [locSeq [locTeq ?]]]]]].\n                 unfold compose_sm in locSeq; simpl in locSeq; rewrite locSeq in locS.\n                 destruct WDnu'. destruct (disjoint_extern_local_Src b01) as [locST|extST].\n                 rewrite locST in locS; inversion locS.\n                 rewrite extST in extS'; inversion extS'. }\n               eapply MemInjNu'.\n               apply H'.\n               { replace (0 + delta1) with delta1 by omega.\n                 unfold as_inj, join. \n                 rewrite Pos.add_sub in H6;  subst l'; rewrite H6; auto. }\n               {\n               subst nu'.\n               unfold as_inj, join.\n               rewrite compose_sm_extern, ext_change_ext.\n               rewrite compose_sm_local, loc_change_ext.\n               rewrite ext_change_ext, loc_change_ext.\n               assert (jmap12: j b02 = Some (b2, d02)).\n               + unfold as_inj in map122; apply joinD_Some in map122;\n                 destruct map122 as [extmap | [extmap locmap]].\n                 - subst j; exact extmap.\n                 - apply SMWD12 in locmap; destruct locmap as [locS locT].\n                   subst k; apply SMWD23 in kmap2; destruct kmap2 as [extS extT].\n                   destruct GlueInv as [loc rest]; rewrite loc in locT. destruct SMWD23. \n                   destruct(disjoint_extern_local_Src b2) as [locS'|extS'].\n                   rewrite locS' in locT; inversion locT.\n                   rewrite extS' in extS; inversion extS.\n               + unfold compose_meminj. unfold add_inj.\n                 rewrite jmap12. subst k. rewrite kmap2. auto. }\n               auto. auto.\n            } \n             { (*4. El caso de nu'*)\n               apply shiftS_Some in H0; apply shiftS_Some in H1.\n               destruct H0 as [bval1 pfmap1]; destruct H1 as [bval2 pfmap2].\n               apply pure_filter_Some in pfmap1; apply pure_filter_Some in pfmap2.\n               destruct pfmap1 as [jmpa1 lmap1']; destruct pfmap2 as [jmap2 lmap2'].\n               \n               unfold Mem.perm in H2, H3.\n               rewrite property_acc in H2, H3; \n                 unfold mem_add_acc in H2,H3.\n               destruct (valid_dec m2 b1).\n               {contradict v. unfold Mem.valid_block. xomega. }\n               destruct (valid_dec m2 b2).\n               {contradict v. unfold Mem.valid_block. xomega. }\n               destruct (source j12' m1' b1 ofs1) eqn:source1; try solve[inversion H2].\n               destruct (source j12' m1' b2 ofs2) eqn:source2; try solve[inversion H3].\n               assert (H': (b1 - Mem.nextblock m2)%positive <> (b2 - Mem.nextblock m2)%positive).\n               { intros eq. apply H. clear - eq bval2 bval1.\n                 remember (Mem.nextblock m2) as nb.\n                 assert (b1 - nb + nb = b2 - nb + nb)%positive by (rewrite eq; auto).\n                 rewrite Pos.sub_add in H; unfold Plt; try apply Pos.gt_lt_iff; auto.\n                 rewrite Pos.sub_add in H; unfold Plt; try apply Pos.gt_lt_iff; auto. }\n               eapply MemInjNu'.\n               apply H'.\n               unfold as_inj, join. subst l'; rewrite lmap1'; auto.\n               unfold as_inj, join. subst l'; rewrite lmap2'; auto.\n               { (*Use the source luke*)\n                 (*also use Norm!*)\n                 destruct p, p0.\n                 symmetry in source1; apply source_SomeE in source1.\n                 destruct source1 as \n                     [b02 [delta [ofs2' [invert [ineq [jmap [mperm ofseq]]]]]]].\n                 inversion invert; subst b02 ofs2'.\n                 (*now I prove that l' is the one mapping. *)\n                 subst j12'; subst nu12'. unfold as_inj in jmap.\n                 apply joinD_Some in jmap; destruct jmap as [extmap|[extmap locmap]].\n                 + rewrite ext_change_ext in extmap.\n                   rewrite H5 in extmap.\n                   unfold add_inj, filter_id, shiftT in extmap.\n                   destruct (j b) eqn:jmap.\n                   - contradict n. inversion extmap; subst p. subst j; auto_sm.\n                   - destruct (l' b) eqn:lmap; try solve [inversion extmap].\n                   inversion extmap. subst ofs1 b1 delta. \n                   replace (z + 0) with z by omega; rewrite Pos.add_sub; trivial. \n                 + contradict n. rewrite loc_change_ext in locmap. auto_sm. }\n               { (*Use the source luke*)\n                 (*also use Norm!*)\n                 assert (bval2': ~ Mem.valid_block m2 b2).\n                 { unfold Mem.valid_block, Plt, Pos.lt, Pos.gt in *; intros HH.\n                   rewrite bval2 in HH; inversion HH. }\n                 destruct p, p0.\n                 symmetry in source2; apply source_SomeE in source2.\n                 destruct source2 as \n                     [b02 [delta [ofs2' [invert [ineq [jmap [mperm ofseq]]]]]]].\n                 inversion invert; subst b02 ofs2'.\n                 (*now I prove that l' is the one mapping. *)\n                 subst j12'; subst nu12'. unfold as_inj in jmap.\n                 apply joinD_Some in jmap; destruct jmap as [extmap|[extmap locmap]].\n                 + rewrite ext_change_ext in extmap.\n                   rewrite H5 in extmap.\n                   unfold add_inj, filter_id, shiftT in extmap.\n                   destruct (j b0) eqn:jmap.\n                   - contradict bval2'. inversion extmap; subst p. subst j; auto_sm.\n                   - destruct (l' b0) eqn:lmap; try solve [inversion extmap].\n                   inversion extmap. subst ofs2 b2 delta. \n                   replace (z0 + 0) with z0 by omega; rewrite Pos.add_sub; trivial. \n                 + contradict bval2'. rewrite loc_change_ext in locmap. auto_sm. }\n               }\n             }\n         - subst nu23'. rewrite loc_change_ext.\n           unfold Mem.meminj_no_overlap; intros.\n           eapply MInj23.\n           apply H.\n           eapply local_in_all; auto.\n           eapply local_in_all; auto.\n           apply Fwd2; eauto.\n           auto_sm.\n           apply Fwd2; eauto.\n           auto_sm.\n       + (*This prove seems identical to the 12 one*)\n         intros.\n         subst nu23'. apply as_in_SomeE in H; destruct H as [ext1 | loc1];\n         [ rewrite ext_change_ext in ext1 | rewrite loc_change_ext in loc1].\n         - eapply MKI_Some23 in ext1; eauto. \n           destruct ext1 as [kmap | [kmap [lmap [jmapN bt]]]].\n           assert (map23: as_inj nu23 b = Some (b', delta)).\n           { apply extern_in_all; subst k; trivial. }\n           eapply MInj23; eauto.\n           destruct H0; [left | right].\n           eapply Fwd2.\n           eapply valid_from_map. \n           apply SMWD23.\n           apply map23.\n           eassumption.\n           assumption.\n\n           eapply Fwd2.\n           eapply valid_from_map. apply SMWD23.\n           apply map23.\n           eassumption.\n           assumption.\n\n           eapply MemInjNu'.\n           apply extern_in_all; subst l'; eauto.\n           unfold Mem.perm in H0.\n           rewrite property_acc in H0; \n                 unfold mem_add_acc in H0.\n           assert (bval: ~Mem.valid_block m2 b). \n             { unfold Mem.valid_block, Plt, Pos.lt; intros HH. \n               rewrite bt in HH; inversion HH. }\n           destruct ( valid_dec m2 b); try solve [contradict bval; trivial].\n           destruct H0 as [H | H].\n           * destruct (source j12' m1' b (Int.unsigned ofs)) eqn:sour; \n             try solve[ inversion H ].\n             left.\n             (*Following is used twice... maybe factor it? *)\n             symmetry in sour; apply source_SomeE in sour.\n             destruct sour as \n                 [b02 [delta' [ofs2 [invert [ineq [jmap [mperm ofseq]]]]]]].\n             subst p.\n             (*now I prove that l' is the one mapping. *)\n             subst j12'; subst nu12'. unfold as_inj in jmap.\n             { apply joinD_Some in jmap; destruct jmap as [extmap|[extmap locmap]].\n               + rewrite ext_change_ext in extmap.\n                 inversion Heqoutput.\n                 rewrite H1 in extmap.\n                 unfold add_inj, filter_id, shiftT in extmap.\n                   destruct (j b02) eqn:jmap.\n                   - contradict bval. inversion extmap; subst p. subst j; auto_sm.\n                   - destruct (l' b02) eqn:lmap'; try solve [inversion extmap].\n                   inversion extmap. subst b delta'; rewrite ofseq.\n                   replace (ofs2 + 0) with ofs2 by omega; rewrite Pos.add_sub; trivial. \n                 + contradict bval. rewrite loc_change_ext in locmap. auto_sm. }\n           * destruct (source j12' m1' b (Int.unsigned ofs - 1)) eqn:sour; \n             try solve[ inversion H ].\n             right. \n             (*Following is used twice... maybe factor it? *)\n             symmetry in sour; apply source_SomeE in sour.\n             destruct sour as \n                 [b02 [delta' [ofs2 [invert [ineq [jmap [mperm ofseq]]]]]]].\n             subst p.\n             (*now I prove that l' is the one mapping. *)\n             subst j12'; subst nu12'. unfold as_inj in jmap.\n             { apply joinD_Some in jmap; destruct jmap as [extmap|[extmap locmap]].\n               + rewrite ext_change_ext in extmap.\n                 inversion Heqoutput.\n                 rewrite H1 in extmap.\n                 unfold add_inj, filter_id, shiftT in extmap.\n                   destruct (j b02) eqn:jmap.\n                   - contradict bval. inversion extmap; subst p. subst j; auto_sm.\n                   - destruct (l' b02) eqn:lmap'; try solve [inversion extmap].\n                   inversion extmap. subst b delta'; rewrite ofseq.\n                   replace (ofs2 + 0) with ofs2 by omega; rewrite Pos.add_sub; trivial. \n                 + contradict bval. rewrite loc_change_ext in locmap. auto_sm. }\n         - assert (map23: as_inj nu23 b = Some (b', delta)).\n           { apply local_in_all; auto. }\n           destruct MInj23. eapply mi_representable; eauto. \n           destruct H0; [left | right].\n           eapply Fwd2; eauto.\n           eapply (valid_from_map nu23); eauto.\n           eapply Fwd2; eauto.\n           eapply (valid_from_map nu23); eauto.\n       }\n       split.\n       (* sm_valid 12'*)\n       { unfold sm_valid.\n         split; intros.\n         apply SMvalNu'. generalize H; unfold DOM, DomSrc.\n         subst nu12'. unfold change_ext; destruct nu12.\n         simpl. rewrite HeqextS12.\n         intros H0.\n         apply orb_true_iff in H0; destruct H0. \n         destruct ExtIncr as [extincr [intincr [? [? [locS [? [? [? [? ? ]]]]]]]]]; simpl in *.\n         rewrite <- locS. rewrite H0; auto.\n         rewrite H0; apply orb_true_r.\n         \n         (* Valid block *)\n         { subst nu12'. unfold RNG, DomTgt, change_ext in H. destruct nu12; simpl in H.\n           unfold Mem.valid_block. rewrite property_nb. unfold mem_add_nb.\n           apply orb_true_iff in H; destruct H.\n           + destruct SMV12 as [DOMtrue RNGtrue].\n             unfold RNG, DomTgt in RNGtrue; move RNGtrue at bottom; simpl in RNGtrue.\n             Lemma pos_lt_inc1: forall a b c, (a < b -> a < (b +c ))%positive.\n               intros a b c H.\n               apply Pos.lt_iff_add; apply Pos.lt_iff_add in H.\n               destruct H as [r H].\n               exists (r + c)%positive.\n               rewrite Pos.add_assoc; rewrite H; auto.\n             Qed.\n             apply pos_lt_inc1. apply RNGtrue. rewrite H; auto.\n           + subst extT12; simpl in H.\n             unfold bconcat, buni, bshift in H.\n             apply orb_true_iff in H; destruct H.\n           - destruct SMV23 as [DOMtrue RNGtrue].\n             unfold DOM, DomSrc in DOMtrue; move DOMtrue at bottom; simpl in DOMtrue.\n             apply pos_lt_inc1. apply DOMtrue. \n             destruct GlueInv as [? [extEq [? ?]]].\n             simpl in extEq. move extEq at bottom. rewrite extEq in H.\n             rewrite H; auto.\n             apply orb_true_r.\n           - destruct ((b2 ?= sizeM2)%positive) eqn:compara; try solve [inversion H].\n             * apply Pos.compare_eq_iff in compara; subst b2.\n               apply Pos.lt_iff_add. exists (Mem.nextblock m1'); subst sizeM2; auto. \n             * apply Pos.compare_gt_iff in compara.\n               destruct SMvalNu' as [DOMtrue RNGtrue].\n               unfold DOM, DomSrc in DOMtrue; move DOMtrue at bottom; simpl in DOMtrue.\n               specialize (DOMtrue ((b2 - sizeM2)%positive)).\n               rewrite H in DOMtrue. rewrite orb_true_r in DOMtrue.\n               Lemma handy_lemma: forall a b c, (b<a -> a - b < c -> a < b +c )%positive.\n                 intros a b c H1 H2.\n                 destruct (Pos.add_lt_mono_r b (a-b) c) as [HH HH']; apply HH in H2; clear HH HH'.\n                 rewrite (Pos.sub_add a b H1) in H2.\n                 rewrite (Pos.add_comm c b) in H2; assumption.\n               Qed.\n               apply handy_lemma; subst sizeM2; try apply DOMtrue; auto.\n         }\n       }\n       split.\n       (* sm_valid 23'*)\n       { unfold sm_valid.\n         split; intros.\n         subst nu23'. unfold DOM, DomSrc, change_ext in H. destruct nu23; simpl in H.\n         subst extS23; simpl in H.\n         (* Valid block *)\n         { unfold DOM, DomSrc, change_ext in H.\n           unfold Mem.valid_block. rewrite property_nb. unfold mem_add_nb.\n           apply orb_true_iff in H; destruct H.\n           + destruct SMV23 as [DOMtrue RNGtrue].\n             unfold DOM, DomSrc in DOMtrue; move DOMtrue at bottom; simpl in DOMtrue.\n             apply pos_lt_inc1. apply DOMtrue. rewrite H; auto.\n           + unfold bconcat, buni, bshift in H.\n             apply orb_true_iff in H; destruct H.\n           - destruct SMV12 as [DOMtrue RNGtrue].\n             unfold RNG, DomTgt in RNGtrue; move RNGtrue at bottom; simpl in RNGtrue.\n             apply pos_lt_inc1. apply RNGtrue. \n             destruct GlueInv as [? [extEq [? ?]]].\n             simpl in extEq. move extEq at bottom. rewrite <- extEq in H.\n             rewrite H; auto.\n             apply orb_true_r.\n           - destruct ((b1 ?= sizeM2)%positive) eqn:compara; try solve [inversion H].\n             * apply Pos.compare_eq_iff in compara; subst b1.\n               apply Pos.lt_iff_add. exists (Mem.nextblock m1'); subst sizeM2; auto. \n             * apply Pos.compare_gt_iff in compara.\n               destruct SMvalNu' as [DOMtrue RNGtrue].\n               unfold DOM, DomSrc in DOMtrue; move DOMtrue at bottom; simpl in DOMtrue.\n               specialize (DOMtrue ((b1 - sizeM2)%positive)).\n               rewrite H in DOMtrue. rewrite orb_true_r in DOMtrue.\n               apply handy_lemma; subst sizeM2; try apply DOMtrue; auto.\n         }\n         apply SMvalNu'. generalize H; unfold RNG, DomTgt.\n         subst nu23'. unfold change_ext; destruct nu23.\n         simpl. rewrite HeqextT23.\n         intros H0.\n         apply orb_true_iff in H0; destruct H0. \n         destruct ExtIncr as [extincr [intincr [? [? [locS [locT [? [? [? ? ]]]]]]]]]; simpl in *.\n         rewrite <- locT. rewrite H0; auto.\n         rewrite H0; apply orb_true_r.\n       }\n       split.\n       split.\n       (* SM_wd 12*)\n       { exact SMWD12'. }\n       split.\n       (* SM_wd 23*)\n       { exact SMWD23'. }\n       split.\n       (* locBlocksTgt = locBlocksSrc *)\n       { subst nu12' nu23'. unfold change_ext; destruct nu12, nu23; simpl.  \n         apply GlueInv.\n       }\n       (* locBlocksTgt = locBlocksSrc *)\n       split.\n       {\n         destruct GlueInv as [? [extEq [? ?]]].\n         subst nu23' nu12'; unfold change_ext; destruct nu23, nu12; subst extS23 extT12; simpl.\n         simpl in extEq; rewrite extEq; auto.\n       }\n       split.\n       (* pubBlocksTgt -> pubBlocksSrc *)\n       { subst nu12' nu23'. unfold change_ext; destruct nu12, nu23; simpl.  \n         apply GlueInv.\n       }\n       (* frgnBlocksTgt -> frgnBlocksSrc *)\n       { subst nu12' nu23'. unfold change_ext; destruct nu12, nu23; simpl.  \n         apply GlueInv.\n       }\n       split.\n       (* Norm *)\n       { subst nu12' nu23'. unfold change_ext; destruct nu12, nu23; simpl. \n         eapply MKI_norm; subst j k; eauto. \n\n         (* Proveing \n          * forall (b : block) (p : block * Z),\n          * extern_of0 b = Some p -> (b < Mem.nextblock m2)%positive *)\n         intros b p H.  destruct p.\n         eapply SMV23. eapply as_inj_DomRng.\n         unfold as_inj, join; simpl. simpl in *; erewrite H; eauto.\n         assumption.\n       }\n       split.\n       { exact UnchPrivSrc12. }\n       (* Mem.unchanged_on *) (*NOTE: hey both Mem.unchanged_on look very alike! *)\n       split.\n       { exact UnchLOOR12.\n       }\n       split.\n       { intros; subst nu12'. \n         rewrite ext_change_ext in H. apply (MKI_Some12 _ _ _ _ _ _ Heqoutput) in H.\n         destruct H.\n         + left; trivial.\n         + destruct H as [jmap [b2' [d' [lmap rest]]]].\n           right; split; trivial; exists b2', d'. trivial.\n       }\n       { clear SMWD12 SMWD12' SMWD23'.\n         intros; subst nu23' j k l'. \n         rewrite ext_change_ext in H.\n         eapply (MKI_Some23 _ _ _ _ _ _ Heqoutput) in H.\n         destruct H as [extmap23 | [extmap23 [extmap' [extmap12 rest]]]].\n         + left; trivial.\n         + right; split; trivial.\n           exists (b2 - Mem.nextblock m2)%positive, 0.\n           subst nu12'. rewrite ext_change_ext.\n           inversion Heqoutput.\n           unfold add_inj.\n           rewrite extmap12. (*NEW: this is the key to not using sm_inject_separated*)\n           unfold filter_id, shiftT; rewrite extmap'. \n           replace (b2 - Mem.nextblock m2 + Mem.nextblock m2)%positive with b2; auto. \n           symmetry; apply Pos.sub_add. apply Pos.gt_lt_iff. apply rest.\n       }\nQed.\nLemma EFF_interp_II: forall m1 m2 nu12 \n                             (MInj12 : Mem.inject (as_inj nu12) m1 m2) m1'\n                             (Fwd1: mem_forward m1 m1') nu23 m3\n                             (MInj23 : Mem.inject (as_inj nu23) m2 m3) m3'\n                             (Fwd3: mem_forward m3 m3')\n                              nu' (WDnu' : SM_wd nu')\n                             (SMvalNu' : sm_valid nu' m1' m3')\n                             (MemInjNu' : Mem.inject (as_inj nu') m1' m3')\n                             \n                             (ExtIncr: extern_incr (compose_sm nu12 nu23) nu')\n                             (*Pure: pure_comp_ext nu12 nu23 m1 m2*)\n                             (SMV12: sm_valid nu12 m1 m2)\n                             (SMV23: sm_valid nu23 m2 m3)\n                             (UnchPrivSrc: Mem.unchanged_on (fun b ofs => locBlocksSrc (compose_sm nu12 nu23) b = true /\\ \n                                                      pubBlocksSrc (compose_sm nu12 nu23) b = false) m1 m1') \n                             (UnchLOOR13: Mem.unchanged_on (local_out_of_reach (compose_sm nu12 nu23) m1) m3 m3')\n\n                             (GlueInvNu: SM_wd nu12 /\\ SM_wd nu23 /\\\n                                         locBlocksTgt nu12 = locBlocksSrc nu23 /\\\n                                         extBlocksTgt nu12 = extBlocksSrc nu23 /\\\n                                         (forall b, pubBlocksTgt nu12 b = true -> \n                                                    pubBlocksSrc nu23 b = true) /\\\n                                         (forall b, frgnBlocksTgt nu12 b = true -> \n                                                    frgnBlocksSrc nu23 b = true))\n                             (Norm12: forall b1 b2 d1, extern_of nu12 b1 = Some(b2,d1) ->\n                                             exists b3 d2, extern_of nu23 b2 = Some(b3, d2))\n                             (full: full_ext nu12 nu23),\n     exists m2', exists nu12', exists nu23', nu'=compose_sm nu12' nu23' /\\\n                             extern_incr nu12 nu12' /\\ extern_incr nu23 nu23' /\\\n                             Mem.inject (as_inj nu12') m1' m2' /\\ mem_forward m2 m2' /\\\n                             Mem.inject (as_inj nu23') m2' m3' /\\\n                             sm_valid nu12' m1' m2' /\\ sm_valid nu23' m2' m3' /\\\n                             (SM_wd nu12' /\\ SM_wd nu23' /\\\n                              locBlocksTgt nu12' = locBlocksSrc nu23' /\\\n                              extBlocksTgt nu12' = extBlocksSrc nu23' /\\\n                              (forall b, pubBlocksTgt nu12' b = true -> \n                                         pubBlocksSrc nu23' b = true) /\\\n                              (forall b, frgnBlocksTgt nu12' b = true -> \n                                         frgnBlocksSrc nu23' b = true)) /\\\n                             (forall b1 b2 d1, extern_of nu12' b1 = Some(b2,d1) ->\n                                     exists b3 d2, extern_of nu23' b2 = Some(b3, d2)) /\\ \n                              Mem.unchanged_on (fun b ofs => locBlocksSrc nu23 b = true /\\ \n                                                             pubBlocksSrc nu23 b = false) m2 m2' /\\\n                              Mem.unchanged_on (local_out_of_reach nu12 m1) m2 m2' /\\\n                              (forall b1 b2 d, extern_of nu12' b1 = Some (b2, d) ->\n                                               extern_of nu12 b1 = Some (b2, d) \\/\n                                               extern_of nu12 b1 = None /\\\n                                               exists b3 d2, extern_of nu' b1 = Some (b3, d2)) /\\\n                              (forall b2 b3 d2, extern_of nu23' b2 = Some (b3, d2) ->\n                                               extern_of nu23 b2 = Some (b3, d2) \\/\n                                               extern_of nu23 b2 = None /\\\n                                               exists b1 d, extern_of nu12' b1 = Some (b2, d)).\n\n                          (* /\\ Mem.unchanged_on (local_out_of_reach nu23 m2) m3 m3'.*)\nProof. intros.\n  destruct (EFF_interp_II_strong _ _ _ MInj12 _ Fwd1 _ _ MInj23 _ \n              Fwd3 _ WDnu' SMvalNu' MemInjNu' ExtIncr\n              (*Pure*) SMV12 SMV23 UnchPrivSrc UnchLOOR13 GlueInvNu Norm12 full)\n  as [m2' [nu12' [nu23' [A [B [C [D [E [F [G [H [I [J [K [L [M ]]]]]]]]]]]]]]]].\n  exists m2', nu12', nu23'. intuition.\nQed.\n\n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/core/interpolation_II.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3629692124105861, "lm_q1q2_score": 0.20544730192992255}}
{"text": "Require Import CertiGraph.unionfind.env_unionfind.\nRequire Import CertiGraph.graph.graph_model.\nRequire Import CertiGraph.graph.path_lemmas.\nRequire Import CertiGraph.graph.subgraph2.\nRequire Import CertiGraph.graph.graph_relation.\nRequire Import CertiGraph.graph.reachable_computable.\nRequire Import CertiGraph.msl_application.Graph.\nRequire Import CertiGraph.msl_application.UnionFindGraph.\nRequire Import CertiGraph.msl_application.GList.\nRequire Import CertiGraph.msl_application.GList_UnionFind.\nRequire Import CertiGraph.floyd_ext.share.\nRequire Import CertiGraph.unionfind.spatial_graph_glist.\n\nLocal Coercion UFGraph_LGraph: UFGraph >-> LGraph.\nLocal Coercion LGraph_SGraph: LGraph >-> SGraph.\nLocal Identity Coercion ULGraph_LGraph: LGraph >-> UnionFindGraph.LGraph.\nLocal Identity Coercion LGraph_LabeledGraph: UnionFindGraph.LGraph >-> LabeledGraph.\nLocal Identity Coercion SGraph_PointwiseGraph: SGraph >-> PointwiseGraph.\nLocal Coercion pg_lg: LabeledGraph >-> PreGraph.\n\nNotation vertices_at sh P g:= (@vertices_at _ _ _ _ _ mpred (@SGP pSGG_VST nat unit (sSGG_VST sh)) (SGA_VST sh) P g).\nNotation whole_graph sh g := (vertices_at sh (vvalid g) g).\nNotation graph sh x g := (@reachable_vertices_at _ _ _ _ _ _ _ _ _ _ (@SGP pSGG_VST nat unit (sSGG_VST sh)) _ x g).\nNotation UFGraph := (@UFGraph pSGG_VST).\nExisting Instances maGraph finGraph liGraph RGF.\n\nDefinition mallocN_spec :=\n DECLARE _mallocN\n  WITH sh: wshare, n:Z\n  PRE [tint]\n     PROP (0 <= n <= Int.max_signed)\n     PARAMS (Vint (Int.repr n))\n     GLOBALS ()\n     SEP ()\n  POST [ tptr tvoid ]\n     EX v: addr,\n     PROP ()\n     LOCAL (temp ret_temp (pointer_val_val v))\n     SEP (data_at sh node_type (pointer_val_val null, (Vint (Int.repr 0)))\n              (pointer_val_val v)).\n\nDefinition find_spec :=\n DECLARE _find\n  WITH sh: wshare, g: UFGraph, x: pointer_val\n  PRE [tptr (Tstruct _Node noattr)]\n          PROP  (vvalid g x)\n          PARAMS (pointer_val_val x)\n          GLOBALS ()\n          SEP   (whole_graph sh g)\n  POST [ tptr (Tstruct _Node noattr) ]\n        EX g': UFGraph, EX rt : pointer_val,\n        PROP (uf_equiv g g' /\\ uf_root g' x rt)\n        LOCAL (temp ret_temp (pointer_val_val rt))\n        SEP (whole_graph sh g').\n\nDefinition unionS_spec :=\n DECLARE _unionS\n  WITH sh: wshare, g: UFGraph, x: pointer_val, y: pointer_val\n  PRE [tptr (Tstruct _Node noattr), tptr (Tstruct _Node noattr)]\n          PROP  (vvalid g x; vvalid g y)\n          PARAMS (pointer_val_val x; pointer_val_val y)\n          GLOBALS ()\n          SEP   (whole_graph sh g)\n  POST [ Tvoid ]\n        EX g': UFGraph,\n        PROP (uf_union g x y g')\n        LOCAL()\n        SEP (whole_graph sh g').\n\nDefinition makeSet_spec :=\n  DECLARE _makeSet\n  WITH sh: wshare, g: UFGraph\n    PRE []\n      PROP ()\n      PARAMS ()\n      GLOBALS ()\n      SEP (whole_graph sh g)\n    POST [tptr (Tstruct _Node noattr)]\n      EX g': UFGraph, EX rt: pointer_val,\n      PROP (~ vvalid g rt ; vvalid g' rt ; is_partial_graph g g')\n      LOCAL (temp ret_temp (pointer_val_val rt))\n      SEP (whole_graph sh g').\n\nDefinition Gprog : funspecs := ltac:(with_library prog [mallocN_spec; makeSet_spec; find_spec; unionS_spec]).\n\nLemma body_makeSet: semax_body Vprog Gprog f_makeSet makeSet_spec.\nProof.\n  start_function.\n  forward_call (sh, 8).\n  - rep_lia.\n  - Intros x.\n    assert_PROP (x <> null) as x_not_null by (entailer !; destruct H0 as [? _]; apply H0).\n    assert_PROP (~ vvalid g x) by (entailer; apply (@vertices_at_sepcon_unique_1x _ _ _ _ SGBA_VST _ _ (SGA_VST sh) (SGAvs_VST sh) g x (vvalid g) (O, null))).\n    forward. forward. forward.\n    Exists (make_set_Graph O tt tt x g x_not_null H). Exists x. entailer!.\n    + split; simpl; [right | apply is_partial_make_set_pregraph]; auto.\n    + assert (Coqlib.Prop_join (vvalid g) (eq x) (vvalid (make_set_Graph 0%nat tt tt x g x_not_null H))). {\n        simpl; hnf; split; intros; [unfold graph_gen.addValidFunc | subst a]; intuition.\n      } assert (vgamma (make_set_Graph O tt tt x g x_not_null H) x = (O, x)). {\n        unfold vgamma, UnionFindGraph.vgamma. simpl. f_equal.\n        - destruct (SGBA_VE x x); [| hnf in c; unfold Equivalence.equiv in c; exfalso]; auto.\n        - unfold graph_gen.updateEdgeFunc. destruct (EquivDec.equiv_dec (x, tt) (x, tt)). 2: compute in c; exfalso; auto. destruct (SGBA_VE null null); auto.\n          hnf in c. unfold Equivalence.equiv in c. exfalso; auto.\n      } rewrite <- (vertices_at_sepcon_1x (make_set_Graph 0%nat tt tt x g x_not_null H) x (vvalid g) _ (O, x)); auto. apply sepcon_derives. 1: apply derives_refl.\n      assert (vertices_at sh (vvalid g) g = vertices_at sh (vvalid g) (make_set_Graph O tt tt x g x_not_null H)). {\n        apply vertices_at_vertices_identical. simpl. hnf. intros. destruct a as [y ?]. unfold Morphisms_ext.app_sig. simpl.\n        unfold UnionFindGraph.vgamma. simpl. unfold graph_gen.updateEdgeFunc. f_equal.\n        - destruct (SGBA_VE y x); [hnf in e; subst y; exfalso |]; auto.\n        - destruct (EquivDec.equiv_dec (x, tt) (y, tt)); auto. hnf in e. inversion e. subst y. exfalso; auto.\n      } rewrite <- H5. apply derives_refl.\nQed.\n\nLemma false_Cne_eq: forall x y, typed_false tint (force_val (sem_cmp_pp Cne (pointer_val_val x) (pointer_val_val y))) -> x = y.\nProof.\n  intros. hnf in H. destruct x, y; inversion H; auto. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n  - destruct (Ptrofs.eq i i0) eqn:? .    \n    + pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. subst; auto.\n    + simpl in H. inversion H.\n  - simpl in H. inversion H.\nQed.\n\nLemma true_Cne_neq: forall x y, typed_true tint (force_val (sem_cmp_pp Cne (pointer_val_val x) (pointer_val_val y))) -> x <> y.\nProof.\n  intros. hnf in H. destruct x, y; inversion H; [|intro; inversion H0..]. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n  - destruct (Ptrofs.eq i i0) eqn:? .    \n    + simpl in H. inversion H.\n    + subst b0. pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. intro; apply H0. inversion H1. reflexivity.\n  - intro. inversion H0. auto.\nQed.\n\nLemma graph_local_facts: forall sh x (g: UFGraph), vvalid g x -> whole_graph sh g |-- valid_pointer (pointer_val_val x).\nProof.\n  intros. eapply derives_trans; [apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g (vvalid g) x (vgamma g x)); auto |].\n  simpl vertex_at at 1. unfold binode. entailer!.\nQed.\n\nLemma body_find: semax_body Vprog Gprog f_find find_spec.\nProof.\n  start_function.\n  remember (vgamma g x) as rpa eqn:?H. destruct rpa as [r pa].\n  (* p = x -> parent; *)\n  localize [data_at sh node_type (vgamma2cdata (vgamma g x)) (pointer_val_val x)]. rewrite <- H0. simpl vgamma2cdata.\n  forward. 1: entailer!; destruct pa; simpl; auto.\n  unlocalize [whole_graph sh g].\n  1: rewrite <- H0; simpl vgamma2cdata; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g (vvalid g) x (r, pa)); auto.\n  assert (H_PARENT_Valid: vvalid g pa) by (eapply valid_parent; eauto).\n  (* if (p != x) { *)\n  forward_if\n    (EX g': UFGraph, EX rt : pointer_val,\n     PROP (uf_equiv g g' /\\ uf_root g' x rt)\n     LOCAL (temp _p (pointer_val_val rt); temp _x (pointer_val_val x))\n     SEP (whole_graph sh g')).\n  - apply denote_tc_test_eq_split; apply graph_local_facts; auto.\n  - (* p0 = find(p); *)\n    forward_call (sh, g, pa). Intros vret. destruct vret as [g' root]. simpl fst in *. simpl snd in *. Opaque pointer_val_val. forward. Transparent pointer_val_val.\n    pose proof (true_Cne_neq _ _ H1).\n    assert (weak_valid g' root) by (right; destruct H3; apply reachable_foot_valid in H3; auto).\n    assert (vvalid g' x) by (destruct H2 as [? _]; rewrite <- H2; apply H).\n    assert (~ reachable g' root x) by (apply (uf_equiv_not_reachable g g' x r pa root); auto).\n    assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g' x root H5 H6 H7)) (Graph_gen_redirect_parent g' x root H5 H6 H7) =\n            vertices_at sh (vvalid g') (Graph_gen_redirect_parent g' x root H5 H6 H7)). {\n      apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition. }\n    remember (vgamma g' x) as rpa eqn:?H. destruct rpa as [r' pa']. symmetry in H9.\n    localize [data_at sh node_type (Vint (Int.repr (Z.of_nat r')), pointer_val_val pa') (pointer_val_val x)].\n    forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g' x root H5 H6 H7)].\n    + rewrite H8. apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto. destruct H3.\n      apply reachable_foot_valid in H3. intro. subst root. apply (valid_not_null g' null H3). simpl. auto.\n    + Exists (Graph_gen_redirect_parent g' x root H5 H6 H7) root. rewrite H8. entailer!. split.\n      * apply (graph_gen_redirect_parent_equiv g g' x r pa); auto.\n      * simpl. apply (uf_root_gen_dst_same g' (liGraph g') x x root); auto. 2: apply reachable_refl; auto.\n        rewrite <- (uf_equiv_root_the_same g g' x root); auto.\n        apply (uf_root_edge _ (liGraph g) _ pa); [| apply (vgamma_not_dst g x r pa) | rewrite (uf_equiv_root_the_same g g')]; auto.\n  - forward. Exists g x. entailer!. apply false_Cne_eq in H1. subst pa. split; [|split]; auto.\n    + apply (uf_equiv_refl _  (liGraph g)).\n    + apply uf_root_vgamma with (n := r); auto.\n  - Intros g' rt. forward. Exists g' rt. entailer!.\nQed.\n\n(* Print Assumptions body_find. *)\n\nLemma true_Ceq_eq: forall x y, typed_true tint (force_val (sem_cmp_pp Ceq (pointer_val_val x) (pointer_val_val y))) -> x = y.\nProof.\n  intros. hnf in H. destruct x, y; inversion H; auto. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n  - destruct (Ptrofs.eq i i0) eqn:? .\n    + pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. subst. reflexivity.\n    + simpl in H. inversion H.\n  - simpl in H. inversion H.\nQed.\n\nLemma false_Ceq_neq: forall x y, typed_false tint (force_val (sem_cmp_pp Ceq (pointer_val_val x) (pointer_val_val y))) -> x <> y.\nProof.\n  intros. hnf in H. destruct x, y; inversion H; [|intro; inversion H0..]. simpl in H. clear H1. unfold sem_cmp_pp in H. simpl in H. destruct (eq_block b b0).\n  - destruct (Ptrofs.eq i i0) eqn:? .\n    + simpl in H. inversion H.\n    + pose proof (Ptrofs.eq_spec i i0). rewrite Heqb1 in H0. intro. apply H0. inversion H1. reflexivity.\n  - intro. apply n. inversion H0; reflexivity.\nQed.\n\nLemma body_unionS: semax_body Vprog Gprog f_unionS unionS_spec.\nProof.\n  start_function.\n  forward_call (sh, g, x). Intros vret. destruct vret as [g1 x_root]. simpl fst in *. simpl snd in *.\n  assert (vvalid g1 y) by (destruct H1 as [? _]; rewrite <- H1; apply H0).\n  forward_call (sh, g1, y). Intros vret. destruct vret as [g2 y_root]. simpl fst in *. simpl snd in *.\n  assert (H_VALID_XROOT: vvalid g2 x_root) by (destruct H4 as [? _]; rewrite <- H4; destruct H2; apply reachable_foot_valid in H2; apply H2).\n  assert (H_VALID_YROOT: vvalid g2 y_root) by (destruct H5; apply reachable_foot_valid in H5; apply H5).\n  assert (H_XROOT_NOT_NULL: x_root <> null) by (intro; subst x_root; apply (valid_not_null g2 null H_VALID_XROOT); simpl; auto).\n  assert (H_YROOT_NOT_NULL: y_root <> null) by (intro; subst y_root; apply (valid_not_null g2 null H_VALID_YROOT); simpl; auto).\n  forward_if_tac\n    (PROP (x_root <> y_root)\n     LOCAL (temp _yRoot (pointer_val_val y_root); temp _xRoot (pointer_val_val x_root);\n     temp _x (pointer_val_val x); temp _y (pointer_val_val y))\n     SEP (vertices_at sh (vvalid g2) g2)).\n  - apply denote_tc_test_eq_split; apply graph_local_facts; auto.\n  - forward. Exists g2. entailer !. apply true_Ceq_eq in H6. subst y_root. apply (the_same_root_union g g1 g2 x y x_root); auto.\n  - forward. apply false_Ceq_neq in H6. entailer!.\n  - Intros. (* xRank = xRoot -> rank; *)\n    remember (vgamma g2 x_root) as rpa eqn:?H. destruct rpa as [rankXRoot paXRoot]. symmetry in H7.\n    localize [data_at sh node_type (vgamma2cdata (vgamma g2 x_root)) (pointer_val_val x_root)].\n    rewrite H7. simpl vgamma2cdata. forward.\n    unlocalize [whole_graph sh g2].\n    1: rewrite H7; simpl; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g2 (vvalid g2) x_root (rankXRoot, paXRoot)); auto.\n    (* yRank = yRoot -> rank; *)\n    remember (vgamma g2 y_root) as rpa eqn:?H. destruct rpa as [rankYRoot paYRoot]. symmetry in H8.\n    localize [data_at sh node_type (vgamma2cdata (vgamma g2 y_root)) (pointer_val_val y_root)].\n    rewrite H8. simpl vgamma2cdata. forward.\n    unlocalize [whole_graph sh g2].\n    1: rewrite H8; simpl; apply (@vertices_at_ramif_1_stable _ _ _ _ SGBA_VST _ _ (SGA_VST sh) g2 (vvalid g2) y_root (rankYRoot, paYRoot)); auto.\n    forward_if\n      (EX g': UFGraph,\n       PROP (uf_union g x y g')\n       LOCAL (temp _xRank (Vint (Int.repr (Z.of_nat rankXRoot))); temp _yRank (Vint (Int.repr (Z.of_nat rankYRoot)));\n              temp _xRoot (pointer_val_val x_root); temp _yRoot (pointer_val_val y_root);\n              temp _x (pointer_val_val x); temp _y (pointer_val_val y))\n       SEP (whole_graph sh g')).\n    + assert (weak_valid g2 y_root) by (right; auto). rename H_VALID_XROOT into H11.\n      assert (~ reachable g2 y_root x_root) by (intro; destruct H5; specialize (H13 _ H12); auto).\n      assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g2 x_root y_root H10 H11 H12)) (Graph_gen_redirect_parent g2 x_root y_root H10 H11 H12) =\n          vertices_at sh (vvalid g2) (Graph_gen_redirect_parent g2 x_root y_root H10 H11 H12)). {\n        apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition. }\n      (* xRoot -> parent = yRoot; *)\n      localize [data_at sh node_type (vgamma2cdata (vgamma g2 x_root)) (pointer_val_val x_root)].\n      rewrite H7. simpl vgamma2cdata. forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g2 x_root y_root H10 H11 H12)].\n      1: rewrite H7; simpl vgamma2cdata; rewrite H13; apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto.\n      Exists (Graph_gen_redirect_parent g2 x_root y_root H10 H11 H12). rewrite H13. entailer!. apply (diff_root_union_1 g g1 g2 x y x_root y_root); auto.\n    + assert (weak_valid g2 x_root) by (right; auto). rename H_VALID_YROOT into H11.\n      assert (~ reachable g2 x_root y_root) by (intro; rewrite (uf_equiv_root_the_same g1 g2) in H2; auto; destruct H2; specialize (H13 _ H12); auto).\n      assert (vertices_at sh (vvalid (Graph_gen_redirect_parent g2 y_root x_root H10 H11 H12)) (Graph_gen_redirect_parent g2 y_root x_root H10 H11 H12) =\n              vertices_at sh (vvalid g2) (Graph_gen_redirect_parent g2 y_root x_root H10 H11 H12)). {\n        apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition. }\n      forward_if\n      (EX g': UFGraph,\n       PROP (uf_union g x y g')\n       LOCAL (temp _xRank (Vint (Int.repr (Z.of_nat rankXRoot))); temp _yRank (Vint (Int.repr (Z.of_nat rankYRoot)));\n              temp _xRoot (pointer_val_val x_root); temp _yRoot (pointer_val_val y_root);\n              temp _x (pointer_val_val x); temp _y (pointer_val_val y))\n       SEP (whole_graph sh g')).\n      * (* yRoot -> parent = xRoot; *)\n        localize [data_at sh node_type (vgamma2cdata (vgamma g2 y_root)) (pointer_val_val y_root)].\n        rewrite H8. simpl vgamma2cdata. forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g2 y_root x_root H10 H11 H12)].\n        1: rewrite H8; simpl vgamma2cdata; rewrite H13; apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto.\n        Exists (Graph_gen_redirect_parent g2 y_root x_root H10 H11 H12). rewrite H13. entailer!. apply (diff_root_union_2 g g1 g2 x y x_root y_root); auto.\n      * (* yRoot -> parent = xRoot; *)\n        localize [data_at sh node_type (vgamma2cdata (vgamma g2 y_root)) (pointer_val_val y_root)].\n        rewrite H8. simpl vgamma2cdata. forward. unlocalize [whole_graph sh (Graph_gen_redirect_parent g2 y_root x_root H10 H11 H12)].\n        1: rewrite H8; simpl vgamma2cdata; rewrite H13; apply (@graph_gen_redirect_parent_ramify _ (sSGG_VST sh)); auto.\n        set (g3 := (Graph_gen_redirect_parent g2 y_root x_root H10 H11 H12)).\n        assert (uf_union g x y g3) by (subst g3; simpl; apply (diff_root_union_2 g g1 g2 x y x_root y_root); auto).\n        (* xRoot -> rank = xRank + 1; *)\n        localize [data_at sh node_type (vgamma2cdata (vgamma g2 x_root)) (pointer_val_val x_root)].\n        rewrite H7. simpl vgamma2cdata. forward.\n        rewrite add_repr. replace (Z.of_nat rankXRoot + 1) with (Z.of_nat (rankXRoot + 1)) by (rewrite Nat2Z.inj_add; simpl; auto).\n        unlocalize [whole_graph sh (Graph_vgen g3 x_root (rankXRoot + 1)%nat)].\n        -- assert (vertices_at sh (vvalid (Graph_vgen g3 x_root (rankXRoot + 1)%nat)) (Graph_vgen g3 x_root (rankXRoot + 1)%nat) =\n                   vertices_at sh (vvalid g3) (Graph_vgen g3 x_root (rankXRoot + 1)%nat)). {\n             apply vertices_at_Same_set. unfold Ensembles.Same_set, Ensembles.Included, Ensembles.In. simpl. intuition.\n           } rewrite H16. clear H16. rewrite H7. simpl vgamma2cdata. apply (@graph_vgen_ramify _ (sSGG_VST sh)).\n           ++ subst g3. simpl. auto.\n           ++ subst g3. remember (Graph_gen_redirect_parent g2 y_root x_root H10 H11 H12) as g3.\n              apply (graph_gen_redirect_parent_vgamma _ _ _ rankXRoot paXRoot) in Heqg3; auto. intros. inversion H16; auto.\n        -- Exists (Graph_vgen g3 x_root (rankXRoot + 1)%nat). entailer!.\n    + Intros g3. Exists g3. entailer!.\nQed. (* 4.207 secs *)\n", "meta": {"author": "anshumanmohan", "repo": "CertiDPK", "sha": "28afacefb162a27e74d744095229d9e4541e3d79", "save_path": "github-repos/coq/anshumanmohan-CertiDPK", "path": "github-repos/coq/anshumanmohan-CertiDPK/CertiDPK-28afacefb162a27e74d744095229d9e4541e3d79/unionfind/verif_unionfind_slim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.2054472994434589}}
{"text": "From ITree Require Import ITree.\nFrom compcert Require Import Maps AST Values Memory Globalenvs Ctypes.\nFrom compcert Require Coqlib Clight Clightdefs.\nFrom Paco Require Import paco.\n\nRequire Import Arith ZArith Bool.\nRequire Import String List Lia.\n\nRequire Import sflib.\nRequire Import Axioms StdlibExt IntegersExt ITreeTac.\n\nRequire Import SysSem.\nRequire Import IPModel DiscreteTimeModel IntByteModel.\nRequire Import OSNodes.\n\nRequire Import ProgSem CProgEventSem.\nRequire Import ProgSim CProgSimLemmas.\nRequire Import RTSysEnv MWITree.\nRequire Import NWSysModel.\nRequire Import SyncSysModel.\n\nRequire Import config_prm main_prm SystemProgs.\nRequire Import VerifProgBase.\nRequire Import VerifMainUtil VerifFetchMsgs.\n\nImport Clight Clightdefs.\nImport ITreeNotations.\n\nSet Nested Proofs Allowed.\n\nLocal Transparent Archi.ptr64.\nLocal Opaque Int64.max_unsigned Int.max_unsigned.\nLocal Opaque Genv.globalenv.\nLocal Opaque Z.of_nat.\n\nLocal Opaque idx_fch idx_get_inb.\n\nArguments DELTA: simpl never.\n\n\nSection INIT_MSG_STORE.\n  Context `{SystemEnv}.\n  (* Context `{CProgSysEvent}. *)\n  Variable cprog: Clight.program.\n\n  Let prog: Prog.t := prog_of_clight cprog.\n  Let ge := Clight.globalenv cprog.\n  Variable tid: nat.\n  Hypothesis RANGE_TID: (tid < num_tasks)%nat.\n  Context `{genv_props ge (main_gvar_ilist tid)\n                       main_gfun_ilist main_cenv_ilist}.\n  (* Notation progE := (OSModel.osE +' OSNodes.tlimE +' extcallE). *)\n\n  Variable r: nat -> itree progE unit -> Prog.state prog -> Prop.\n  (* Let GVB_IDXS_MAIN := gvb_idxs_main. *)\n\n  (* Lemma fold_mentry_sz' *)\n  (*   : Z.of_nat (S max_msg_size) = mentry_sz. *)\n  (* Proof. *)\n  (*   unfold mentry_sz. nia. *)\n  (* Qed. *)\n\n\n  Inductive init_inbox_loop_inv\n            (itr_i: itree progE unit)\n            (inb0: MWITree.inbox_t)\n            b pofsv m_i (* i_max *)\n            (i: nat) (itr: itree progE unit)\n            (le: PTree.t val) (m: mem): Prop :=\n    InitInboxLoopInv\n      ments_p ments_n\n      (MEM_CONSTS: mem_consts ge m tid)\n      (* (OFFSET: pofsv = Ptrofs.unsigned pofs) *)\n      (MENTS_PREV: iForall (Mem_msg_entry m b pofsv)\n                           0 ments_p)\n      (MENTS_PREV_INIT:\n         MWITree.reset_inbox (firstn i inb0) = ments_p)\n      (MENTS_NEXT_EQ: skipn i inb0 = ments_n)\n      (MENTS_NEXT: iForall (Mem_msg_entry m b pofsv)\n                           i ments_n)\n      (ITREE_INVAR: itr = itr_i)\n      (MENTS_RANGE_PERM: Mem.range_perm m b pofsv\n                                        (pofsv + inb_sz)\n                                        Cur Writable)\n      (UNCH: mem_unchanged_except\n               (fun b' ofs' =>\n                  b' = b /\\\n                  (pofsv <= ofs' < pofsv + inb_sz)%Z)\n               m_i m)\n      (LENV_EQUIV: lenv_equiv\n                     le [(_inb, Vptr b (Ptrofs.repr pofsv));\n                        (_i, Vint (IntNat.of_nat i))])\n  .\n\n  Definition idx_iinb: nat := num_tasks * 10 + 10.\n\n\n  Lemma firstn_snoc_nth_error A\n        (l: list A) (a: A) n\n        (NTH: nth_error l n = Some a)\n    : firstn (S n) l = snoc (firstn n l) a.\n  Proof.\n    unfold snoc.\n    depgen n.\n    induction l as [| h t IH]; i; ss.\n    { destruct n; ss. }\n    destruct n as [| n']; ss.\n    { inv NTH. ss. }\n\n    hexploit IH; eauto.\n    intro EXP_IH. rewrite EXP_IH. ss.\n  Qed.\n\n\n\n  Lemma sim_init_inbox\n        (b_mst: block)\n        idx itr k m\n        (* pofs *) pofsv inb\n        (CALL_CONT: is_call_cont k)\n        (MEM_CONSTS: mem_consts ge m tid)\n        (* (POFSV: pofsv = Ptrofs.unsigned pofs) *)\n        (POFSV_BOUND: (0 <= pofsv <= inb_sz + 4)%Z)\n        (FSYMB_MST : Genv.find_symbol ge _mstore = Some b_mst)\n        (MEM_INBOX: Mem_inbox m b_mst pofsv inb)\n        (AFT: forall m' inb'\n                (RESET_INB: inb' = MWITree.reset_inbox inb)\n                (MEM_CONSTS: mem_consts ge m' tid)\n                (MEM_INBOX: Mem_inbox m' b_mst pofsv inb')\n                (MEM_UNCH: mem_unchanged_except\n                             (fun b ofs' =>\n                                b = b_mst /\\\n                                pofsv <= ofs' <\n                                pofsv + inb_sz)%Z\n                             m m'),\n            paco3 (_sim_itree prog) r idx\n                  itr (Clight.Returnstate Vundef k m'))\n    : paco3 (_sim_itree prog) r (idx_iinb + idx)\n            itr\n            (Clight.Callstate\n               (Internal (main_prm.f_init_inbox\n                            (Z.of_nat max_num_tasks)))\n               [Vptr b_mst (Ptrofs.repr pofsv)] k m).\n  Proof.\n    (* pose (pofsv' := pofsv). subst pofsv. *)\n    (* fold pofsv' in AFT. fold pofsv' in MEM_INBOX. *)\n    (* rename pofsv' into pofsv. *)\n\n    start_func.\n    { econs. }\n\n    unfold idx_iinb.\n    fw. clear STEP_ENTRY.\n    fw. fw.\n    { econs. eval_comput. ss. }\n    upd_lenv.\n    fw.\n    (* loop *)\n    (* replace 6%Z with (Z.of_nat 6%nat) by ss. *)\n    (* fold_for_loop _i . *)\n\n    hexploit (in_gvar_ids _NUM_TASKS); [sIn|].\n    intros (b_nt & FSYMB_NT).\n    pose proof range_num_tasks as RANGE_NT.\n    rr in MEM_INBOX.\n\n    eapply simple_for_loop\n      with (idx_each:= 10) (idx0:= 0)\n           (i_max := num_tasks)\n           (loop_inv := init_inbox_loop_inv\n                          itr inb b_mst pofsv m).\n    { econs; eauto; ss.\n      - econs.\n      - apply MEM_INBOX.\n      - eapply MEM_INBOX.\n      - rr. apply Mem.unchanged_on_refl.\n    }\n    (* { apply LENV_EQUIV. } *)\n    { range_stac. }\n    { nia. }\n    { (* body *)\n      clear le LENV_EQUIV.\n      clear MEM_CONSTS.\n      i. unfold for_loop_stmt. ss.\n      inv LINV. des.\n\n      (* make range props of i in advance *)\n      (* assert (RANGE_I_Z: (0 <= Z.of_nat i <= 6)%Z) by nia. *)\n      (* assert (RANGE_I_INT: (Int.min_signed <= Z.of_nat i <= Int.max_signed)%Z). *)\n      (* { split. *)\n      (*   - pose proof Int.min_signed_neg. nia. *)\n      (*   - etransitivity; try apply RANGE_I_Z. ss. } *)\n      (* assert (RANGE_I_UINT: (0 <= Z.of_nat i <= Int.max_unsigned)%Z). *)\n      (* { split; try apply RANGE_I_Z. *)\n      (*   etransitivity; try apply RANGE_I_Z. ss. } *)\n      (* assert (RANGE_I_POFS: (0 <= Z.of_nat i <= Ptrofs.max_unsigned)%Z). *)\n      (* { split; try apply RANGE_I_Z. *)\n      (*   etransitivity; try apply RANGE_I_Z. ss. } *)\n\n      assert (WITHIN_INBOX_SZ: (0 < mentry_nsz * i + 1 <= inb_nsz)%nat).\n      { split; [nia|].\n        apply within_inb_nsz2.\n        - nia.\n        - unfold mentry_nsz. nia.\n      }\n\n      (* guardH RANGE_I_Z. guardH RANGE_I_INT. *)\n      (* guardH RANGE_I_UINT. guardH RANGE_I_POFS. *)\n\n      fw. fw. fw.\n      { econs.\n        - eval_comput.\n          rewrite FSYMB_NT.\n          erewrite mem_consts_num_tasks by eauto.\n          repr_tac.\n          rewrite <- Nat2Z_inj_ltb. reflexivity.\n        - instantiate (1:= true).\n          s.\n          destruct (Nat.ltb_spec i num_tasks); ss. nia.\n      }\n      ss.\n\n      fw.\n      assert (exists inb_x,\n                 <<INB_X: nth_error inb i = Some inb_x>> /\\\n                 <<SKIPN_RW: skipn i inb = inb_x :: skipn (S i) inb>>).\n      { hexploit (nth_error_Some2 _ inb i).\n        { nia. }\n        i. des.\n        esplits; eauto.\n        apply nth_error_split in NTH_EX. des. clarify.\n        rewrite skipn_app_exact by ss.\n        rewrite rw_cons_app. rewrite app_assoc.\n        rewrite skipn_app_exact.\n        2: { rewrite app_length. ss. nia. }\n        ss.\n      }\n      des.\n      (* destruct inb_x as [rcv_x bs_x]. *)\n      rewrite SKIPN_RW in MENTS_NEXT. clear SKIPN_RW.\n      inv MENTS_NEXT.\n\n      match goal with\n      | H: Mem_msg_entry _ _ _ _ _ |- _ =>\n           (* , *)\n           (* H': _ = skipn i inb |- _ => *)\n        rename H into MENT_CUR (* ; rename H' into INB_SKIPN *)\n      end.\n\n      (* make mem beforehand *)\n      assert (MEM_STORE: exists m2,\n                 Mem.store Mint8signed m1 b_mst\n                           (pofsv + (Z.of_nat (mentry_nsz * i)))\n                           (Vint Int.zero) = Some m2).\n      { apply inhabited_sig_to_exists.\n        econs.\n        (* unfold mentry_sz. *)\n        apply Mem.valid_access_store.\n        r. split; ss.\n        - ii.\n          eapply MENTS_RANGE_PERM. nia.\n        - apply Z.divide_1_l.\n      }\n      des.\n      pose proof ptr_range_mstore as PTR_RANGE_MSTORE.\n      pose proof range_mentry_nsz as RANGE_MENTRY_NSZ.\n\n      fw.\n      { econs.\n        - eval_comput. s. fold_cenv.\n          erewrite (in_cenv_ilist _msg_entry_t) by sIn.\n          rewrite Ptrofs.add_zero.\n          rewrite Ptrofs.add_zero.\n          repr_tac1.\n          simpl co_sizeof.\n          (* replace (Z.of_nat (S max_msg_size)) with mentry_sz. *)\n          (* 2: { unfold mentry_sz. nia. } *)\n          repr_tac1. repr_tac1.\n          rewrite <- Nat2Z.inj_mul.\n          reflexivity.\n        - eval_comput. eauto.\n        - ss.\n        - eval_comput.\n          repr_tac1.\n          replace (Int.sign_ext 8 (Int.repr 0)) with Int.zero by ss.\n          eauto.\n      }\n\n      fw.\n      { econs; eauto. }\n      fw.\n      { econs.\n        eval_comput.\n        repr_tac.\n        replace (Z.of_nat i + 1)%Z with (Z.of_nat (S i)) by nia.\n        reflexivity.\n      }\n      upd_lenv.\n\n      fw.\n      fold_for_loop _i.\n\n      eapply (sim_itree_red_idx prog) with (idx_small:= idx1 - 10).\n      { nia. }\n\n      eapply SIM_NEXT.\n      (* { apply LENV_EQUIV. } *)\n      { econs; eauto.\n        - eapply mem_consts_unch_diffblk; eauto.\n          2: { instantiate (1:= b_mst).\n               i. eapply global_addresses_distinct'; eauto.\n               ss. des; clarify. }\n          eapply Mem.unchanged_on_implies.\n          { eapply store_unchanged_on'; eauto. }\n          unfold mem_range. ss.\n          ii. des; clarify.\n        - erewrite firstn_snoc_nth_error; eauto.\n          unfold snoc.\n          unfold MWITree.reset_inbox in *.\n          rewrite map_app.\n          eapply iForall_app; eauto.\n          + eapply iForall_Mem_msg_entry_unch; eauto.\n            eapply Mem.unchanged_on_implies; eauto.\n            { eapply store_unchanged_on'; eauto. }\n            unfold mem_range. ss.\n            rewrite map_length.\n            rewrite firstn_length_le by nia.\n            ii. des; ss. nia.\n\n          + ss. rewrite map_length.\n            rewrite firstn_length_le by nia.\n            econs; ss.\n            2: { econs. }\n\n            r in MENT_CUR.\n            eapply Mem.loadbytes_store_same in MEM_STORE.\n            ss.\n\n            (* (* replace mentry_esz with (1 + Z.of_nat msg_size)%Z. *) *)\n            (* (* 2: { unfold mentry_ensz. nia. } *) *)\n\n            (* unfold mentry_to_bytes. s. *)\n            (* rewrite rw_cons_app. *)\n\n            (* apply Mem.loadbytes_concat; [ | | nia | nia]. *)\n            (* * eapply Mem.loadbytes_store_same in MEM_STORE. ss. *)\n            (* * erewrite Mem.loadbytes_store_other; eauto. *)\n            (*   2: { do 3 right. ss. nia. } *)\n            (*   replace mentry_esz with (1 + Z.of_nat msg_size)%Z *)\n            (*     in MENT_CUR. *)\n            (*   2: { unfold mentry_ensz. nia. } *)\n\n            (*   unfold mentry_to_bytes in MENT_CUR. *)\n            (*   apply Mem_loadbytes_split' in MENT_CUR; [|nia..]. *)\n            (*   ss. destruct MENT_CUR. *)\n            (*   eauto. *)\n        - eapply iForall_Mem_msg_entry_unch; eauto.\n          eapply Mem.unchanged_on_implies; eauto.\n          { eapply store_unchanged_on'; eauto. }\n          unfold mem_range. ss.\n          (* rewrite map_length. *)\n          (* rewrite firstn_length_le by nia. *)\n          ii. des; ss. nia.\n        - ii. eapply Mem.perm_store_1; eauto.\n        - eapply Mem.unchanged_on_trans.\n          2: {\n            eapply Mem.store_unchanged_on; eauto.\n            i. intro C. apply C.\n            split; ss.\n            nia.\n          }\n          ss.\n      }\n    }\n\n    i. ss.\n    clear dependent le. clear MEM_CONSTS.\n    inv LINV_END. des.\n\n    fw. fw. fw.\n    { econs.\n      - eval_comput.\n        rewrite FSYMB_NT.\n        erewrite mem_consts_num_tasks by eauto.\n        repr_tac.\n        rewrite Z.ltb_irrefl. ss.\n      - ss.\n    }\n    rewrite Int.eq_true. ss.\n\n    fw. fw. fw.\n    eapply (sim_itree_red_idx prog) with (idx_small := idx).\n    { nia. }\n\n    eapply AFT; eauto.\n    rewrite firstn_all2 in MENTS_PREV.\n    { r. esplits; eauto.\n      unfold MWITree.reset_inbox.\n      rewrite map_length. ss. }\n    { nia. }\n  Qed.\n\n\n  Definition idx_swinb := idx_iinb + 20.\n\n  Lemma sim_switch_inbox\n        m0 k itr idx_ret\n        cf ofsc ofsn\n        inbc inbn\n        (CALL_CONT: is_call_cont k)\n        (MEM_CONSTS: mem_consts ge m0 tid)\n        (MEM_MSTORE: mem_mstore ge m0 cf ofsc ofsn inbc inbn)\n        (SIM_RET:\n           forall m' cf' inbn' ofsc' ofsn'\n             (* (INBN_EQV': inbox_equiv *)\n             (*               MWITree.init_inbox inbn_t') *)\n             (* (INBN_INIT': Forall (fun x => fst x = false) inbn') *)\n             (RESET_INBC: inbn' = MWITree.reset_inbox inbc)\n             (MEM_MSTORE: mem_mstore ge m' cf' ofsc' ofsn'\n                                     inbn inbn')\n             (UNCH: mem_changed_gvar_id ge _mstore m0 m')\n           ,\n             paco3 (_sim_itree prog) r idx_ret\n                   itr\n                   (Returnstate Vundef k m'))\n    : paco3 (_sim_itree prog) r (idx_swinb + idx_ret)\n            itr (Callstate (Internal f_switch_inbox)\n                           [] k m0).\n  Proof.\n    start_func.\n    { econs. }\n\n    unfold idx_swinb.\n    fw. clear STEP_ENTRY.\n    fw.\n\n    hexploit (in_gvar_ids _mstore); [sIn|].\n    destruct 1 as [b_mst FSYMB_MST].\n    specialize (MEM_MSTORE _ FSYMB_MST).\n\n    fw.\n    { econs. eval_comput.\n      rewrite FSYMB_MST. s.\n      rewrite Ptrofs.add_zero_l.\n      rewrite Ptrofs.unsigned_repr by ss.\n      apply MEM_MSTORE.\n    }\n    upd_lenv.\n\n    fw. fw. fw.\n    { hexploit (in_gfun_ilist _init_inbox); [sIn|]. i. des.\n      econs; eauto; ss.\n      - eval_comput.\n        rewrite FDEF_SYMB. ss.\n      - eval_comput.\n        rewrite FSYMB_MST. s.\n        fold_cenv.\n        erewrite (in_cenv_ilist _inbox_t) by sIn.\n        s. rewrite Ptrofs.add_zero_l.\n        pose proof ptr_range_inb_sz.\n        repr_tac0; cycle 1.\n        { nia. }\n        { desf; ss. }\n        repr_tac0; cycle 1.\n        { ss. }\n        { desf; ss.\n          - unfold Int.one.\n            rewrite Int.signed_repr by ss.\n            nia.\n          - unfold Int.zero.\n            rewrite Int.signed_repr by ss.\n            nia.\n        }\n        replace (inb_sz * Int.signed (if cf then Int.one else Int.zero))%Z with\n            (Z.of_nat (if cf then inb_nsz else 0)).\n        2: {\n          unfold Int.one, Int.zero.\n          destruct cf; ss.\n          - rewrite Int.signed_repr by ss. nia.\n          - rewrite Int.signed_repr by ss. nia.\n        }\n        reflexivity.\n    }\n\n    eapply (sim_itree_red_idx prog) with (idx_small:= idx_iinb + (idx_ret + 12)).\n    { nia. }\n    eapply sim_init_inbox with (inb:= inbc); eauto; ss.\n    { destruct cf; nia. }\n    { inv MEM_MSTORE.\n      destruct cf; ss.  }\n\n    clear MEM_CONSTS.\n    i. clarify.\n    rename m' into m1.\n\n    fw. fw.\n    inv MEM_MSTORE.\n\n    assert (STORE_CF: exists m2,\n               Mem.store Mint32 m1 b_mst 0 (Vint (Int.repr (if cf then 0%Z else 1%Z))) = Some m2).\n    { apply inhabited_sig_to_exists.\n      econs.\n      apply Mem.valid_access_store.\n      rr. split; ss.\n      - ii. eapply Mem.perm_unchanged_on; eauto.\n        ss. nia.\n      - solve_divide.\n    }\n    des.\n\n    fw.\n    { econs.\n      - eval_comput.\n        rewrite FSYMB_MST. s.\n        rewrite Ptrofs.add_zero_l. reflexivity.\n      - eval_comput.\n        instantiate (1:= Vint (Int.repr (if cf then 0%Z else 1%Z))).\n        destruct cf; ss.\n      - ss.\n      - eval_comput.\n        eauto.\n    }\n    fw.\n    apply (sim_itree_red_idx prog) with (idx_small:= idx_ret).\n    { nia. }\n\n    assert (MEM_UNCH_TOT:\n              mem_unchanged_except\n                (fun b ofs =>\n                   b = b_mst /\\\n                   ((0 <= ofs < 4) \\/\n                    (if cf then\n                       (4 + Z.of_nat inb_nsz <= ofs <\n                        4 + Z.of_nat (inb_nsz + inb_nsz))\n                     else\n                       (4 <= ofs < 4 + Z.of_nat inb_nsz))))%Z\n                m0 m2).\n    { eapply Mem.unchanged_on_trans.\n      - eapply Mem.unchanged_on_implies; eauto.\n        ii. des; ss. clarify.\n        desf; nia.\n      - eapply Mem.unchanged_on_implies; eauto.\n        { eapply store_unchanged_on'; eauto. }\n        unfold mem_range.\n        ii. ss.\n        destruct cf; nia.\n    }\n\n    eapply SIM_RET; eauto.\n    { econs; eauto.\n      - instantiate (1:= negb cf).\n        ss. clarify.\n        erewrite Mem.load_store_same; eauto.\n        destruct cf; ss.\n      - ii.\n        eapply Mem.perm_store_1; eauto.\n        eapply Mem.perm_unchanged_on; eauto.\n        { ss. ii. des; ss. clarify.\n          destruct cf; nia. }\n        ss. clarify.\n        apply mem_mst_curflag_writable. eauto.\n      - ss. clarify.\n        destruct cf; ss.\n        + eapply Mem_inbox_unch; eauto.\n          eapply Mem.unchanged_on_implies; eauto.\n          ii. ss. nia.\n        + eapply Mem_inbox_unch; eauto.\n          eapply Mem.unchanged_on_implies; eauto.\n          ii. ss. nia.\n        (*   eapply Mem.unchanged_on_trans. *)\n        (*   { eapply Mem.unchanged_on_implies; eauto. *)\n        (*     ss. ii. des; clarify. nia. } *)\n        (*   { eapply Mem.unchanged_on_implies; eauto. *)\n        (*     { eapply store_unchanged_on'; eauto. } *)\n        (*     ss. unfold mem_range. *)\n        (*     ii. des; clarify. nia. } *)\n        (* + eapply Mem_inbox_unch; eauto. *)\n        (*   eapply Mem.unchanged_on_trans. *)\n        (*   { eapply Mem.unchanged_on_implies; eauto. *)\n        (*     ss. ii. des; clarify. nia. } *)\n        (*   { eapply Mem.unchanged_on_implies; eauto. *)\n        (*     { eapply store_unchanged_on'; eauto. } *)\n        (*     ss. unfold mem_range. *)\n        (*     ii. des; clarify. nia. } *)\n      - ss. clarify.\n        destruct cf; ss.\n        + eapply Mem_inbox_unch; eauto.\n          eapply Mem.unchanged_on_implies; eauto.\n          { eapply store_unchanged_on'; eauto. }\n          ss. unfold mem_range.\n          ii. des; clarify. nia.\n        + eapply Mem_inbox_unch; eauto.\n          eapply Mem.unchanged_on_implies; eauto.\n          { eapply store_unchanged_on'; eauto. }\n          ss. unfold mem_range.\n          ii. des; clarify. nia.\n    }\n\n    r. i. ss. clarify.\n    eapply Mem.unchanged_on_implies; eauto.\n    ss. ii. ss. des; ss.\n  Qed.\n\nEnd INIT_MSG_STORE.\n\n\nSection RUN_TASK.\n  (* Context `{SystemEnv}. *)\n  Context `{SimApp}.\n\n  (* Variable cprog: Clight.program. *)\n  Variable txs rxs: nat.\n\n  Let prog: Prog.t := prog_of_clight cprog.\n  Let ge := globalenv cprog.\n  Notation progE := (OSModel.osE +' obsE).\n\n  Context `{genv_props\n              ge (main_gvar_ilist tid ++ app_gvar_ilist)\n              (main_gfun_ilist ++ app_gfun_ilist)\n              (main_cenv_ilist ++ app_cenv_ilist)}.\n\n  (* For global variable invariants *)\n  Let gprops_main\n    : genv_props ge (main_gvar_ilist tid)\n                 main_gfun_ilist main_cenv_ilist.\n  Proof.\n    eapply genv_props_incl; eauto;\n      apply incl_appl; ss.\n  Qed.\n\n  Variable r: nat -> itree progE unit -> Prog.state prog -> Prop.\n\n  (* Variable kp: Clight.cont. *)\n  (* Variable idx_fin: nat. *)\n  (* Hypothesis KP: *)\n  (*   is_call_cont kp /\\ *)\n  (*   forall m, paco3 (_sim_itree prog) r idx_fin *)\n  (*              (Ret tt) *)\n  (*              (Returnstate Vundef kp m). *)\n\n  Let tid_sign_ext_noeff:\n    Int.sign_ext 8 (IntNat.of_nat tid) =\n    IntNat.of_nat tid.\n  Proof.\n    assert (IntRange.sint8 tid).\n    { pose proof range_tid.\n      pose proof range_num_tasks.\n      range_stac. }\n\n    unfold IntNat.of_nat.\n    rewrite sign_ext_byte_range by ss.\n    ss.\n  Qed.\n\n  Inductive main_loop_inv\n            (itr: itree progE unit)\n            (le: PTree.t val) (m: mem): Prop :=\n    MainLoopInv\n      ast sytm sytm_dmy mcont_dmy\n      cflg ofsc ofsn\n      inbc inbn (* sh *)\n      (* inbc_t inbn_t *)\n      v_dmy\n      (RANGE_SYTM: (0 < Z.of_nat (sytm + 2 * period) <= Int64.max_unsigned)%Z)\n      (LENV_EQUIV: lenv_equiv le [(_cur_base_time, Vlong (IntNat.of_nat64 sytm));\n                                 (_pprd, Vlong (IntNat.of_nat64 period));\n                                 (_dlt, Vlong (Int64.repr (Z.of_nat DELTA)));\n                                 (_maxt, Vlong (Int64.repr MAX_TIME_Z));\n                                 (_t'1, v_dmy)])\n\n      (MEM_NB: (Genv.genv_next ge <= Mem.nextblock m)%positive)\n\n      (ITREE: itr =\n              MWITree.main_loop\n                tid app_mod MWITree.ltb_max_time\n                txs rxs (inbc, inbn)\n                ast sytm)\n\n      (MEM_SBUF : mem_sbuf ge m sytm_dmy tid mcont_dmy)\n      (MEM_CONSTS : mem_consts ge m tid)\n      (MEM_MSTORE : mem_mstore ge m cflg ofsc ofsn inbc inbn)\n      (MEM_SH : mem_sh ge m (repeat false num_tasks))\n      (MEM_TXS : mem_txs ge m txs)\n      (MEM_RXS : mem_rxs ge m rxs)\n      (INV_APP: inv_app ge ast m)\n      (* (INBC_EQV: inbox_equiv inbc_s inbc_t) *)\n      (* (INBN_EQV: inbox_equiv inbn_s inbn_t) *)\n  .\n\n  (* TODO *)\n\n  Let eval_loop_cond\n      le m tm\n      (RANGE_TM: IntRange.uint64 tm)\n      (LE_CBT : le ! _cur_base_time =\n                Some (Vlong (IntNat.of_nat64 tm)))\n      (LE_MAXT: le ! _maxt =\n                Some (Vlong (Int64.repr\n                               (Int64.max_unsigned -\n                                10 * Z.of_nat period))))\n    : eval_expr_c (globalenv cprog) empty_env le m\n                  (Ebinop Cop.Olt (Etempvar _cur_base_time tulong)\n                          (Etempvar _maxt tulong) tint) =\n      Some (Vint (if tm <? MAX_TIME\n                  then Int.one else Int.zero)).\n  Proof.\n    ss. rewrite LE_CBT. rewrite LE_MAXT.\n    eval_comput.\n    repr_tac.\n\n    pose proof period_mul_10_lt_max.\n    unfold Int64.ltu.\n    rewrite Int64.unsigned_repr.\n    2: { range_stac. }\n\n    rewrite Z.mul_comm.\n    fold MAX_TIME_Z.\n    rewrite <- max_time_to_z.\n\n    unfold IntNat.of_nat64.\n    rewrite Int64.unsigned_repr by ss.\n\n    match goal with\n    | |- context[Coqlib.zlt ?a ?b] =>\n      destruct (Coqlib.zlt a b)\n    end.\n    - destruct (Nat.ltb_spec tm MAX_TIME); ss.\n      nia.\n    - destruct (Nat.ltb_spec tm MAX_TIME); ss.\n      nia.\n  Qed.\n\n  (* Let eval_loop_cond *)\n  (*       le m v sytm *)\n  (*       _cur_base_time *)\n  (*       b_pprd *)\n  (*       (RANGE_SYTM: (0 < Z.of_nat (sytm + 2 * pals_period) <= Int64.max_unsigned)%Z) *)\n  (*       (LENV_EQUIV: le ! _cur_base_time = *)\n  (*                    Some (Vlong (IntNat.of_nat64 sytm))) *)\n  (*       (FSYMB_PPRD : Genv.find_symbol ge _PALS_PERIOD = Some b_pprd) *)\n  (*       (LOAD_PPRD : Mem.load Mint64 m b_pprd 0 = *)\n  (*                    Some (Vlong (IntNat.of_nat64 pals_period))) *)\n  (*       (VAL: v = if (Z.of_nat sytm <? Int64.max_unsigned - *)\n  (*                                      5 * Z.of_nat pals_period)%Z *)\n  (*                 then Vtrue else Vfalse) *)\n  (*   : eval_expr_c *)\n  (*       (globalenv cprog) empty_env le m *)\n  (*       (Ebinop Cop.Olt (Etempvar _cur_base_time tulong) *)\n  (*               (Ebinop Cop.Osub (Econst_long (Int64.repr (-1)) tulong) *)\n  (*                       (Ebinop Cop.Omul (Econst_int (Int.repr 5) tint) (Evar _PALS_PERIOD tulong) tulong) tulong) tint) = *)\n  (*     Some v. *)\n  (* Proof. *)\n  (*   assert (0 <= Z.of_nat sytm <= Int64.max_unsigned)%Z by nia. *)\n  (*   ss. *)\n  (*   rewrite LENV_EQUIV. *)\n  (*   rewrite FSYMB_PPRD. cbn. *)\n  (*   rewrite Ptrofs.unsigned_zero. *)\n  (*   rewrite LOAD_PPRD. *)\n  (*   replace (IntNat.of_nat64 sytm) with (Int64.repr (Z.of_nat sytm)) by ss. *)\n  (*   rewrite eval_max_time; eauto. *)\n\n  (*   unfold Int64.ltu. *)\n  (*   rewrite Int64.unsigned_repr by ss. *)\n  (*   rewrite Int64.unsigned_repr. *)\n  (*   2: { pose proof period_mul_10_lt_max. nia. } *)\n  (*   match goal with *)\n  (*   | |- context[Coqlib.zlt ?a ?b] => *)\n  (*     destruct (Z.ltb_spec a b) *)\n  (*   end. *)\n  (*   - desf. *)\n  (*   - desf. nia. *)\n  (* Qed. *)\n\n  Definition idx_run: nat := 30.\n\n  Lemma sim_run_task\n        sytm m_i (* ast *) kp idx_fin\n        sytm_dmy mcont\n        ofsc ofsn\n        (CALL_CONT: is_call_cont kp)\n        (MEM_NB: (Genv.genv_next ge <= Mem.nextblock m_i)%positive)\n        (* (INV_APP: inv_app ge ast m_i) *)\n        (RANGE_SYTM: (0 < Z.of_nat (sytm + 2 * period) <=\n                      Int64.max_unsigned)%Z)\n        (RANGE_TXS: IntRange.sint txs)\n        (RANGE_RXS: IntRange.sint rxs)\n        (MEM_CONSTS: mem_consts ge m_i tid)\n        (MEM_SBUF: mem_sbuf ge m_i sytm_dmy tid mcont)\n        (MEM_MSTORE: mem_mstore ge m_i false ofsc ofsn\n                                MWITree.init_inbox\n                                MWITree.init_inbox)\n        (MEM_SH: mem_sh ge m_i (repeat false num_tasks))\n        (MEM_TXS: mem_txs ge m_i txs)\n        (MEM_RXS: mem_rxs ge m_i rxs)\n        (INV_APP: inv_app ge (AppMod.init_abst_state app_mod) m_i)\n        (SIM_RET:\n           forall m_f\n             (* (UNCH: Mem.unchanged_on (fun _ _ => True) m_i m_f) *)\n           ,\n             paco3 (_sim_itree prog) r idx_fin\n                   (Ret tt)\n                   (Clight.Returnstate Vundef kp m_f))\n    : (* exists idx_rt: nat, *)\n      paco3 (_sim_itree prog) r (idx_run + idx_fin)\n            (MWITree.run_task\n               tid app_mod txs rxs sytm)\n            (Clight.Callstate\n               (Internal main_prm.f_run_task)\n               [Vlong (IntNat.of_nat64 sytm)] kp m_i)\n  .\n  Proof.\n    guardH RANGE_SYTM.\n    unfold idx_run.\n    rewrite plus_comm.\n\n    (* remember m_i as m1 eqn:MEM_EQ. *)\n    (* guardH MEM_EQ. *)\n\n    start_func.\n    { econs. }\n    ss.\n    fw. clear STEP_ENTRY.\n\n    hexploit (in_gvar_ids _send_buf); [sIn|].\n    intros [b_sbuf FSYMB_SBUF].\n    hexploit (in_gvar_ids _mstore); [sIn|].\n    intros [b_mst FSYMB_MST].\n\n    hexploit (in_gvar_ids _PALS_PERIOD); [sIn|].\n    intros (b_pprd & FSYMB_PPRD).\n    hexploit (in_gvar_ids _MAX_CSKEW); [sIn|].\n    intros (b_sk & FSYMB_SK).\n    hexploit (in_gvar_ids _MAX_NWDELAY); [sIn|].\n    intros (b_nd & FSYMB_ND).\n\n    fw. fw.\n    { econs.\n      eval_comput.\n      rewrite FSYMB_PPRD.\n      erewrite mem_consts_pals_period; eauto.\n    }\n    upd_lenv.\n\n    pose proof max_clock_skew_range as RANGE_SK.\n    pose proof max_nw_delay_range as RANGE_ND.\n    pose proof period_cond as PRD_COND.\n    pose proof period_mul_10_lt_max as PRD_LT.\n\n    fw. fw. fw.\n    { econs. eval_comput.\n      rewrite FSYMB_SK, FSYMB_ND.\n      erewrite mem_consts_max_cskew; eauto.\n      erewrite mem_consts_max_nwdelay; eauto.\n      eval_comput.\n      repr_tac.\n      replace 2%Z with (Z.of_nat 2) by ss.\n      rewrite <- Nat2Z.inj_mul.\n      rewrite <- Nat2Z.inj_add.\n      fold DELTA.\n      reflexivity.\n    }\n    assert (DELTA_LT: DELTA < period).\n    { unfold DELTA. nia. }\n    upd_lenv.\n\n    fw. fw. fw.\n    { econs. eval_comput.\n      rewrite FSYMB_PPRD.\n      erewrite mem_consts_pals_period by eauto.\n      repr_tac.\n\n      rewrite eval_max_time.\n      reflexivity.\n    }\n    upd_lenv.\n    fw.\n\n    (* Swhile *)\n    eapply (sim_itree_red_idx prog) with\n        (idx_small:= idx_fin + 15 + 5).\n    { nia. }\n\n    match goal with\n    | |- context[Swhile ?e ?s] =>\n      pose (while_cond_expr := e);\n        pose (loop_body_stmt := s)\n    end.\n\n    eapply sim_while with (linv := main_loop_inv).\n    { econs; eauto.\n      - rewrite max_time_to_z in LENV_EQUIV. ss.\n      - unfold MWITree.run_task. eauto.\n    }\n    { clear dependent m_i. clear dependent le.\n      clear ofsc ofsn sytm_dmy sytm RANGE_SYTM.\n      i. inv LINV.\n\n      hexploit mem_consts_pals_period; eauto.\n      intro LOAD_PPRD.\n\n      esplits; ss.\n      - rewrite LENV_EQUIV. ss.\n        rewrite LENV_EQUIV. ss.\n      - ss.\n        rewrite bool_val_of_bool.\n\n        unfold Int64.ltu.\n        rewrite Int64.unsigned_repr.\n        2: { unfold MAX_TIME_Z. nia. }\n        unfold IntNat.of_nat64.\n        rewrite Int64.unsigned_repr.\n        2: { pose proof period_mul_10_lt_max. nia. }\n        instantiate (1:= (sytm <? MAX_TIME)).\n        rewrite <- max_time_to_z.\n        destruct (Nat.ltb_spec sytm MAX_TIME);\n          destruct (Coqlib.zlt (Z.of_nat sytm)\n                               (Z.of_nat MAX_TIME)); ss; nia.\n    }\n    { (* loop body *)\n      clear dependent m_i. clear dependent le.\n      clear dependent sytm.\n      clear ofsc ofsn sytm_dmy.\n      i. inv LOOP_INV.\n      renames m_c le_c into m1 le.\n\n      fold loop_body_stmt in CIH.\n      fold while_cond_expr in EVAL_EXPR, COND_TRUE, CIH.\n      fold while_cond_expr.\n\n      assert (UINT64_SYTM: IntRange.uint64 sytm).\n      { rr. nia. }\n\n      assert (SYTM_LT_MAX: sytm < MAX_TIME).\n      { subst while_cond_expr. ss.\n        erewrite eval_loop_cond in EVAL_EXPR; eauto; cycle 1.\n        { rewrite LENV_EQUIV. ss. }\n        { rewrite LENV_EQUIV.\n          rewrite Z.mul_comm.\n          fold MAX_TIME_Z. ss. }\n        destruct (Nat.ltb_spec sytm MAX_TIME); ss.\n        exfalso. clarify.\n      }\n\n      assert (RANGE_NSYTM: (Z.of_nat (sytm + period * 3)\n                            <= Int64.max_unsigned)%Z).\n      { unfold MAX_TIME in SYTM_LT_MAX. ss. nia. }\n\n      (* seq *)\n      fw.\n\n      assert (MEM_STORE: exists m2,\n                 Mem.store Mint64 m1 b_sbuf 0\n                           (Vlong (IntNat.of_nat64 (sytm + period))) = Some m2 /\\\n                 mem_sbuf ge m2 (sytm + period) tid mcont_dmy).\n      { specialize (MEM_SBUF _ FSYMB_SBUF).\n        inv MEM_SBUF.\n\n        assert (exists m', Mem.store Mint64 m1 b_sbuf 0\n                                (Vlong (IntNat.of_nat64 (sytm + period))) = Some m').\n        { apply inhabited_sig_to_exists.\n          econs.\n          apply Mem.valid_access_store.\n          rr. split; ss.\n          - ii. eapply mem_sbuf_writable.\n            unfold pld_size. nia.\n          - solve_divide.\n        }\n        des.\n        esplits; eauto.\n        ii. ss. clarify.\n        econs.\n        - change 8%Z with (size_chunk Mint64).\n          erewrite Mem.loadbytes_store_same; eauto. ss.\n        - erewrite Mem.load_store_other; eauto.\n          right. right. ss.\n        - erewrite Mem.loadbytes_store_other; eauto.\n          right. right. right. ss.\n        - ii. eapply Mem.perm_store_1; eauto.\n      }\n      clear MEM_SBUF.\n      destruct MEM_STORE as (m2 & MEM_STORE & MEM_SBUF).\n\n      fw.\n      { econs.\n        - eval_comput.\n          rewrite FSYMB_SBUF. s.\n          unfold Ptrofs.zero.\n          repr_tac. s. reflexivity.\n        - eval_comput. repr_tac.\n          rewrite <- Nat2Z.inj_add. reflexivity.\n        - ss.\n        - ss.\n          eval_comput.\n          eauto.\n      }\n\n      assert (MEM_CHB: mem_changed_block b_sbuf m1 m2).\n      { eapply Mem.store_unchanged_on; eauto. }\n\n      eapply mem_consts_unch_diffblk in MEM_CONSTS; cycle 1; eauto.\n      { i. ss.\n        eapply (global_addresses_distinct' ge); eauto.\n        des; clarify. }\n      eapply mem_txs_unch_diffblk in MEM_TXS; cycle 1; eauto.\n      { eapply global_addresses_distinct' with (id:= _send_buf); eauto; ss. }\n      eapply mem_rxs_unch_diffblk in MEM_RXS; cycle 1; eauto.\n      { eapply global_addresses_distinct' with (id:=_send_buf); eauto; ss. }\n      eapply mem_mstore_unch_diffblk in MEM_MSTORE; cycle 1; eauto.\n      { eapply global_addresses_distinct' with (id:=_send_buf); eauto; ss. }\n      eapply mem_sh_unch_diffblk in MEM_SH; cycle 1; eauto.\n      { eapply global_addresses_distinct' with (id:=_send_buf); eauto; ss. }\n\n      eapply inv_app_unch_diffblk in INV_APP; cycle 1; eauto.\n      { sIn. }\n      assert (MEM_NB': (Genv.genv_next ge <= Mem.nextblock m2)%positive).\n      { apply Mem.unchanged_on_nextblock in MEM_CHB.\n        unfold Coqlib.Ple in MEM_CHB.\n        ss. nia. }\n      clear dependent m1. renames m2 MEM_NB' into m1 MEM_NB.\n\n      (* skip *)\n      fw. fw. fw.\n      { hexploit (in_gfun_ilist _pals_wait_timer).\n        { sIn. }\n        i. des.\n        econs; ss.\n        - eval_comput.\n          rewrite FDEF_SYMB. ss.\n        - eval_comput. reflexivity.\n        - eauto.\n        - ss.\n      }\n\n      (* wait_timer *)\n      pfold. econs 3; ss.\n      { econs; eauto.\n        - ss.\n          econs; eauto.\n          eapply CProgOSEC_WaitTimer with (tm:=sytm); ss.\n        - ss. }\n      { rewrite MWITree.unfold_main_loop.\n        replace (MWITree.ltb_max_time sytm) with true.\n        2: { unfold MWITree.ltb_max_time.\n             destruct (Nat.ltb_spec sytm MAX_TIME); ss.\n             nia. }\n        unfold MWITree.loop_body.\n        simpl_itree_goal.\n        econs 1.\n      }\n      { simpl_itree_goal. ss. }\n\n      intros retz pst_ret (* POSTCOND_SETT *) AFT_EVT.\n      exists (idx_fch + (idx_get_inb + idx_job + idx_fin + 40 +\n                    (idx_rst_sh + (idx_swinb + 20)))).\n      left. simpl_itree_goal.\n\n      inv AFT_EVT.\n      inv CPROG_AFTER_EVENT; ss.\n      symmetry in EVENT. inv EVENT. existT_elim.\n      unf_resum. subst.\n      inv OS_ESTEP. existT_elim. clarify.\n      rename m' into m1.\n\n      hexploit (in_gvar_ids _rxs); [sIn|].\n      intros (b_rxs & FSYMB_RXS).\n\n      fw. fw. fw. fw.\n      { hexploit (in_gfun_ilist _fetch_msgs); eauto.\n        { sIn. }\n        i. des.\n\n        econs; ss.\n        - eval_comput.\n          rewrite FDEF_SYMB. ss.\n        - eval_comput.\n          rewrite FSYMB_RXS.\n          erewrite mem_skt_id; eauto.\n        - eauto.\n        - eauto.\n      }\n\n      (* callstate *)\n      (* ss. *)\n      (* eapply (sim_itree_red_idx prog) with *)\n      (*         (idx_small:= (idx_fch + (idx_fin + idx_job + 30) + 50). *)\n      (* { nia. } *)\n\n      eapply sim_fetch_msgs; ss; eauto.\n      { eapply range_tid. }\n      clear inbc inbn MEM_MSTORE.\n      intros m2 inbc inbn. i.\n\n      assert (MEM_CHB: mem_changed_block b_mst m1 m2).\n      { eapply Mem.unchanged_on_implies; eauto. }\n\n      eapply mem_consts_unch_diffblk in MEM_CONSTS; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto.\n        ss. des; clarify. }\n      eapply mem_txs_unch_diffblk in MEM_TXS; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto. ss. }\n      eapply mem_rxs_unch_diffblk in MEM_RXS; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto. ss. }\n      eapply mem_sbuf_unch_diffblk in MEM_SBUF; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto. ss. }\n      eapply mem_sh_unch_diffblk in MEM_SH; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto. ss. }\n      eapply inv_app_unch_diffblk in INV_APP; cycle 1; eauto.\n      { sIn. }\n      assert (MEM_NB': (Genv.genv_next ge <= Mem.nextblock m2)%positive).\n      { apply Mem.unchanged_on_nextblock in MEM_CHB.\n        unfold Coqlib.Ple in MEM_CHB. ss. nia. }\n      clear dependent m1. renames m2 MEM_NB' into m1 MEM_NB.\n\n      simpl_itree_goal.\n      fw. fw. fw. fw. fw.\n      { hexploit (in_gfun_ilist _get_cur_inbox); eauto.\n        { sIn. }\n        i. des.\n        econs; ss.\n        - eval_comput. rewrite FDEF_SYMB. ss.\n        - eval_comput. eauto.\n        - eauto.\n        - ss.\n      }\n\n      red_idx (idx_get_inb + (idx_job + idx_rst_sh + idx_swinb + 50)).\n\n      eapply sim_get_cur_inbox; eauto; ss.\n      { apply range_tid. }\n      intros b_mst' FSYMB_MST'.\n      ss. clarify. rename FSYMB_MST' into FSYMB_MST.\n\n      fw. upd_lenv.\n      fw.\n      (* call job *)\n      fw.\n      { hexploit (in_gfun_ilist _job).\n        { cut (In (_job, Internal job_func) app_gfun_ilist).\n          { i. sIn. }\n          apply job_func_in_app_gfun_ilist.\n        }\n        i. des.\n\n        econs; ss.\n        - eval_comput.\n          rewrite FDEF_SYMB. ss.\n        - eval_comput. reflexivity.\n        - eauto.\n        - ss. apply job_func_type.\n      }\n\n      red_idx ((idx_rst_sh + (idx_swinb + 30)) + idx_job).\n      eapply (sim_job_func r' ); eauto; ss.\n      { range_stac. }\n\n      unfold VerifProgBase.ge. fold ge.\n      clear MEM_SH MEM_SBUF INV_APP. i.\n\n      eapply mem_consts_unch in MEM_CONSTS; cycle 1; eauto.\n      { eapply Mem.unchanged_on_implies; eauto.\n        i. eapply blocks_of_ge_incl; eauto.\n        rr. unfold main_const_ids. ss. i.\n        des; sIn.\n      }\n      eapply mem_mstore_unch in MEM_MSTORE; cycle 1; eauto.\n      { eapply Mem.unchanged_on_implies; eauto.\n        i. r. esplits; eauto. sIn. }\n      eapply mem_txs_unch in MEM_TXS; cycle 1; eauto.\n      { eapply Mem.unchanged_on_implies; eauto.\n        i. r. esplits; eauto. sIn. }\n      eapply mem_rxs_unch in MEM_RXS; cycle 1; eauto.\n      { eapply Mem.unchanged_on_implies; eauto.\n        i. r. esplits; eauto. sIn. }\n      assert (MEM_NB': (Genv.genv_next ge <= Mem.nextblock m')%positive).\n      { apply Mem.unchanged_on_nextblock in UNCH_MAIN.\n        unfold Coqlib.Ple in *. ss. nia. }\n      clear dependent m1.\n      renames m' INV_APP' MEM_NB' into m1 INV_APP MEM_NB.\n\n      fw. fw. fw. fw.\n      { econs. eval_comput.\n        repr_tac. rewrite <- Nat2Z.inj_add.\n        reflexivity. }\n      upd_lenv.\n      simpl_itree_goal.\n\n      (* fw. fw. fw. *)\n      (* { hexploit (in_gfun_ilist _pals_set_timelimit); [sIn|]. *)\n      (*   i. des. *)\n\n      (*   econs; ss. *)\n      (*   - eval_comput. rewrite FDEF_SYMB. ss. *)\n      (*   - eval_comput. *)\n      (*     repr_tac. *)\n      (*     rewrite <- Nat2Z.inj_add. *)\n      (*     rewrite <- Nat2Z.inj_sub by nia. *)\n      (*     eauto. *)\n      (*   - eauto. *)\n      (*   - ss. *)\n      (* } *)\n\n      (* pfold. econs 3; ss. *)\n      (* { econs; eauto. *)\n      (*   - ss. *)\n      (*     econs 2; try reflexivity. *)\n      (*     range_stac. *)\n      (*   - ss. } *)\n      (* { econs. } *)\n      (* { replace (sytm + period + (period - DELTA)) with *)\n      (*       (sytm + period + period - DELTA) by nia. *)\n      (*   simpl_itree_goal. *)\n      (*   ss. } *)\n\n      (* intros [] pst_r AFT_EVT. *)\n      (* inv AFT_EVT. ss. *)\n      (* inv CPROG_AFTER_EVENT; ss. *)\n      (* clarify. ss. existT_elim. subst. *)\n      (* simpl_itree_goal. *)\n      (* rename m' into m1. *)\n\n      (* exists (idx_rst_sh + (idx_swinb + 20)). left. *)\n\n      fw. fw. fw.\n      { hexploit (in_gfun_ilist _reset_send_hist); [sIn|].\n        i. des.\n        econs; ss.\n        - eval_comput. rewrite FDEF_SYMB. ss.\n        - eval_comput. ss.\n        - eauto.\n        - ss.\n      }\n\n      eapply sim_reset_send_hist; try eapply range_tid; eauto; ss.\n      clear sh' MEM_CONSTS MEM_SH. i.\n\n      hexploit (in_gvar_ids _send_hist); [sIn|].\n      intros (b_sh & FSYMB_SH). ss.\n\n      assert (MEM_CHB: mem_changed_block b_sh m1 m').\n      { apply MEM_UNCH. ss. }\n      clear MEM_UNCH.\n\n      eapply mem_txs_unch_diffblk in MEM_TXS; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto. ss. }\n      eapply mem_rxs_unch_diffblk in MEM_RXS; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto. ss. }\n      eapply mem_sbuf_unch_diffblk in MEM_SBUF; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto. ss. }\n      eapply mem_mstore_unch_diffblk in MEM_MSTORE; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto. ss. }\n\n      eapply inv_app_unch_diffblk in INV_APP; cycle 1; eauto.\n      { sIn. }\n      assert (MEM_NB': (Genv.genv_next ge <= Mem.nextblock m')%positive).\n      { apply Mem.unchanged_on_nextblock in MEM_CHB.\n        unfold Coqlib.Ple in MEM_CHB. ss. nia. }\n      clear dependent m1. renames m' MEM_NB' into m1 MEM_NB.\n\n      fw. fw. fw.\n      { hexploit (in_gfun_ilist _switch_inbox); [sIn|].\n        i. des.\n        econs; ss.\n        - eval_comput. rewrite FDEF_SYMB. ss.\n        - eval_comput. ss.\n        - eauto.\n        - ss.\n      }\n\n      eapply sim_switch_inbox; eauto; ss.\n      { eapply range_tid. }\n      rename ofsc into ofsc_p.\n      clear cflg ofsn MEM_MSTORE.\n      intros m' cflg inbn_t' ofsc ofsn. i.\n\n      assert (MEM_CHB: mem_changed_block b_mst m1 m').\n      { apply UNCH. ss. }\n      clear UNCH.\n\n      eapply mem_consts_unch_diffblk in MEM_CONSTS; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto.\n        ss. des; clarify. }\n      eapply mem_txs_unch_diffblk in MEM_TXS; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto. ss. }\n      eapply mem_rxs_unch_diffblk in MEM_RXS; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto. ss. }\n      eapply mem_sbuf_unch_diffblk in MEM_SBUF; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto. ss. }\n      eapply mem_sh_unch_diffblk in MEM_SH; cycle 1; eauto.\n      { i. eapply global_addresses_distinct'; eauto. ss. }\n      eapply inv_app_unch_diffblk in INV_APP; cycle 1; eauto.\n      { sIn. }\n      assert (MEM_NB': (Genv.genv_next ge <= Mem.nextblock m')%positive).\n      { apply Mem.unchanged_on_nextblock in MEM_CHB.\n        unfold Coqlib.Ple in MEM_CHB. ss. nia. }\n      clear dependent m1. renames m' MEM_NB' into m1 MEM_NB.\n\n      (* ret *)\n      fw. fw_tau (S (idx_fin + 25)).\n      { econs. eauto. }\n\n      red_idx (S (idx_fin + 15 + 5)).\n      fw_r.\n      rewrite Nat.sub_0_r.\n      eapply CIH.\n      subst inbn_t'.\n      econs; try eapply LENV_EQUIV; eauto.\n      - range_stac.\n      - subst. ss.\n    }\n\n    i.\n    fw.\n    red_idx idx_fin.\n\n    clear sytm RANGE_SYTM LENV_EQUIV MEM_SBUF MEM_CONSTS\n          MEM_TXS MEM_RXS INV_APP.\n    clear ofsc ofsn sytm_dmy MEM_MSTORE.\n    inv LOOP_INV.\n\n    ss. erewrite eval_loop_cond in EVAL_EXPR; cycle 2.\n    { rewrite LENV_EQUIV. ss. }\n    { rewrite Z.mul_comm.\n      rewrite LENV_EQUIV. ss. }\n    2: { range_stac. }\n\n    unfold MWITree.ltb_max_time.\n    rewrite MWITree.unfold_main_loop.\n    destruct (Nat.ltb_spec sytm MAX_TIME); clarify.\n\n    eapply paco3_mon.\n    eapply SIM_RET. eauto.\n  Qed.\n\nEnd RUN_TASK.\n", "meta": {"author": "kim-yoonseung", "repo": "pals-thesis-dev", "sha": "1a165028f5461ed4d00a1e2720b3b1e4542f5dc2", "save_path": "github-repos/coq/kim-yoonseung-pals-thesis-dev", "path": "github-repos/coq/kim-yoonseung-pals-thesis-dev/pals-thesis-dev-1a165028f5461ed4d00a1e2720b3b1e4542f5dc2/src/mw_verif/VerifTask.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.33807713748839185, "lm_q1q2_score": 0.2054370250142265}}
{"text": "(*\n * Copyright (c) 2020 BedRock Systems, Inc.\n * This software is distributed under the terms of the BedRock Open-Source License.\n * See the LICENSE-BedRock file in the repository root for details.\n *)\n\n(** The \"operational\" style definitions about C++ values. *)\nFrom Coq Require Import Strings.Ascii.\nRequire Import stdpp.gmap.\n\nFrom bedrock.prelude Require Import base addr option numbers.\n\nFrom bedrock.lang.cpp.arith Require Import operator builtins.\nRequire Import bedrock.lang.cpp.ast.\nFrom bedrock.lang.cpp.semantics Require Export types sub_module genv ptrs.\n\n#[local] Close Scope nat_scope.\n#[local] Open Scope Z_scope.\nImplicit Types (σ : genv).\n\n(* TODO: improve our axiomatic support for raw values - including \"shattering\"\n   non-raw values into their constituent raw pieces - to enable deriving\n   [tptsto_ptr_congP_transport] from [tptsto_raw_ptr_congP_transport].\n *)\nModule Type RAW_BYTES.\n  (** * Raw bytes\n      Raw bytes represent the low-level view of data.\n      [raw_byte] abstracts over the internal structure of this low-level view of data.\n      E.g. in the [simple_pred] model, [raw_byte] would be instantiated with [runtime_val].\n\n      [raw_int_byte] is a raw byte that is a concrete integer values (i.e. not a\n      pointer fragment or poison).\n   *)\n  Parameter raw_byte : Set.\n  Parameter raw_byte_eq_dec : EqDecision raw_byte.\n  #[global] Existing Instance raw_byte_eq_dec.\n\n  Axiom raw_int_byte : N -> raw_byte.\n\n  (* TODO: refine our treatment of `raw_bytes` s.t. we respect\n      the size constraints imposed by the physical hardware.\n\n      The following might help but will likely require other\n      axioms which reflect boundedness or round-trip properties.\n\n    Parameter of_raw_byte : raw_byte -> N.\n    Axiom inj_of_raw_byte : Inj (=) (=) of_raw_byte.\n    #[global] Existing Instance inj_of_raw_byte.\n  *)\nEnd RAW_BYTES.\n\nModule Type VAL_MIXIN (Import P : PTRS) (Import R : RAW_BYTES).\n  (** * Values\n      Primitive abstract C++ runtime values come in two flavors.\n      - pointers (also used for references)\n      - integers (used for everything else)\n      Aggregates are not represented directly, but only by talking about\n      primitive subobjects.\n\n      There is also a distinguished undefined element [Vundef] that\n      models uninitialized values <https://eel.is/c++draft/basic.indet>.\n      Operations on [Vundef] are all undefined behavior.\n      [Vraw] (a raw byte) represents the low-level bytewise view of data.\n      See [logic/layout.v] for more axioms about it.\n  *)\n  Variant val : Set :=\n  | Vint (_ : Z)\n  | Vchar (_ : N)\n    (* ^ value used for non-integral character types, e.g.\n         [char], [wchar], etc, but *not* [unsigned char] and [signed char]\n\n         The values here are *always* unsigned. When arithmetic is performed\n         the semantics will convert the unsigned value into the appropriate\n         equivalent on the target platform based on the signedness of the type.\n     *)\n  | Vptr (_ : ptr)\n  | Vraw (_ : raw_byte)\n  | Vundef\n  .\n  #[global] Notation Vref := Vptr (only parsing).\n\n  (* TODO Maybe this should be removed *)\n  #[global] Coercion Vint : Z >-> val.\n\n  Definition val_dec : forall a b : val, {a = b} + {a <> b}.\n  Proof. solve_decision. Defined.\n  #[global] Instance val_eq_dec : EqDecision val := val_dec.\n  #[global] Instance val_inhabited : Inhabited val := populate (Vint 0).\n\n  (** ** Notation wrappers for [val] *)\n  Definition Vbool (b : bool) : val :=\n    Vint (if b then 1 else 0).\n  Definition Vnat (b : nat) : val :=\n    Vint (Z.of_nat b).\n  Definition Vn (b : N) : val :=\n    Vint (Z.of_N b).\n  Notation Vz := Vint (only parsing).\n\n  (** we use [Vundef] as our value of type [void] *)\n  Definition Vvoid := Vundef.\n\n  (** [is_raw v] holds when [v] is a raw value. *)\n  Definition is_raw (v : val) : bool :=\n    match v with\n    | Vraw _ => true\n    | _ => false\n    end.\n\n  Definition is_true (v : val) : option bool :=\n    match v with\n    | Vint v => Some (bool_decide (v <> 0))\n    | Vptr p => Some (bool_decide (p <> nullptr))\n    | Vchar n => Some (bool_decide (n <> 0%N))\n    | Vundef | Vraw _ => None\n    end.\n  #[global] Arguments is_true !_.\n\n  (* An error used to say that [is_true] failed on the value [v] *)\n  Record is_true_None (v : val) : Prop := {}.\n\n  Theorem is_true_int : forall i,\n      is_true (Vint i) = Some (bool_decide (i <> 0)).\n  Proof. reflexivity. Qed.\n\n  Lemma Vptr_inj p1 p2 : Vptr p1 = Vptr p2 -> p1 = p2.\n  Proof. by move=> []. Qed.\n  Lemma Vint_inj a b : Vint a = Vint b -> a = b.\n  Proof. by move=> []. Qed.\n  Lemma Vchar_inj a b : Vchar a = Vchar b -> a = b.\n  Proof. by move=> []. Qed.\n  Lemma Vbool_inj a b : Vbool a = Vbool b -> a = b.\n  Proof. by move: a b =>[] [] /Vint_inj. Qed.\n\n  #[global] Instance Vptr_Inj : Inj (=) (=) Vptr := Vptr_inj.\n  #[global] Instance Vint_Inj : Inj (=) (=) Vint := Vint_inj.\n  #[global] Instance Vchar_Inj : Inj (=) (=) Vchar := Vchar_inj.\n  #[global] Instance Vbool_Inj : Inj (=) (=) Vbool := Vbool_inj.\n\n  Definition N_to_char (t : char_type.t) (z : N) : val :=\n    Vchar $ trimN (char_type.bitsN t) z.\n\n  (* the default value for a type.\n  * this is used to initialize primitives if you do, e.g.\n  *   [int x{};]\n  *)\n  Fixpoint get_default (t : type) : option val :=\n    match t with\n    | Tpointer _ => Some (Vptr nullptr)\n    | Tnum _ _ => Some (Vint 0%Z)\n    | Tbool => Some (Vbool false)\n    | Tnullptr => Some (Vptr nullptr)\n    | Tqualified _ t => get_default t\n    | _ => None\n    end.\nEnd VAL_MIXIN.\n\nModule Type RAW_BYTES_VAL\n       (Import P : PTRS) (Import R : RAW_BYTES)\n       (Import V : VAL_MIXIN P R).\n  (** [raw_bytes_of_val σ ty v rs] states that the value [v] of type\n      [ty] is represented by the raw bytes in [rs]. What this means\n      depends on the type [ty]. *)\n  Parameter raw_bytes_of_val : genv -> type -> val -> list raw_byte -> Prop.\n\n  Axiom raw_bytes_of_val_Proper : Proper (genv_leq ==> eq ==> eq ==> eq ==> iff) raw_bytes_of_val.\n  #[global] Existing Instance raw_bytes_of_val_Proper.\n\n  Axiom raw_bytes_of_val_unique_encoding : forall {σ ty v rs rs'},\n      raw_bytes_of_val σ ty v rs -> raw_bytes_of_val σ ty v rs' -> rs = rs'.\n\n  Axiom raw_bytes_of_val_int_unique_val : forall {σ sz sgn z z' rs},\n      raw_bytes_of_val σ (Tnum sz sgn) (Vint z) rs ->\n      raw_bytes_of_val σ (Tnum sz sgn) (Vint z') rs ->\n      z = z'.\n\n  Axiom raw_bytes_of_val_sizeof : forall {σ ty v rs},\n      raw_bytes_of_val σ ty v rs -> size_of σ ty = Some (N.of_nat $ length rs).\n\n  (* TODO Maybe add?\n    Axiom raw_bytes_of_val_int : forall σ sz z rs,\n        raw_bytes_of_val σ (Tnum sz Unsigned) (Vint z) rs <->\n        exists l,\n          (_Z_from_bytes (genv_byte_order σ) Unsigned l = z) /\\\n          rs = raw_int_byte <$> l.\n  *)\n\n  Module FieldOrBase.\n    (* type for representing direct subobjects\n       *Always* qualify this name, e.g. [FieldOrBase.t]\n     *)\n    Variant t : Set :=\n    | Field (f : ident)\n    | Base (_ : globname).\n\n    #[global] Instance t_eq_dec : EqDecision t := ltac:(solve_decision).\n    #[global,program] Instance t_countable : Countable t :=\n      { encode x := encode match x with\n                      | Field a => inl a\n                      | Base b => inr b\n                      end\n      ; decode x := (fun x => match x with\n                           | inl a => Field a\n                           | inr b => Base b\n                           end) <$> decode x\n      }.\n    Next Obligation.\n      by destruct x; rewrite /= decode_encode/=.\n    Qed.\n\n  End FieldOrBase.\n\n  (** [raw_bytes_of_struct σ cls rss rs] states that the struct\n      consisting of fields of the raw bytes [rss] is represented by the\n      raw bytes in [rs].\n\n      [rs] should agree with [rss] on the offsets of the fields.\n      This is captured by [raw_offsets].\n\n      It might be possible to make some assumptions about the\n      parts of [rs] that represent padding based on the ABI. *)\n  Parameter raw_bytes_of_struct :\n    genv -> globname -> gmap FieldOrBase.t (list raw_byte) -> list raw_byte -> Prop.\n\n  (** TODO: introduction rules for [raw_bytes_of_struct] *)\n\n  (** *** Elimination rules for [raw_bytes_of_struct] *)\n\n  (** The size of the raw bytes of an object is the size of the object *)\n  Axiom raw_bytes_of_struct_wf_size : forall σ cls flds rs,\n    raw_bytes_of_struct σ cls flds rs ->\n    Some (length rs) = N.to_nat <$> (size_of σ (Tnamed cls)).\n\n  (** The raw bytes in each field is the size of the field *)\n  Axiom raw_bytes_of_struct_wf_field : forall σ cls flds rs,\n    raw_bytes_of_struct σ cls flds rs ->\n    (forall m mty,\n    type_of_field cls m = Some mty ->\n    exists bytes, flds !! FieldOrBase.Field m = Some bytes /\\\n    Some (length bytes) = N.to_nat <$> (size_of σ mty)).\n\n  (** The raw bytes in each base is the size of the base *)\n  Axiom raw_bytes_of_struct_wf_base : forall σ cls flds rs base bytes,\n    raw_bytes_of_struct σ cls flds rs ->\n    flds !! FieldOrBase.Base base = Some bytes ->\n    Some (length bytes) = N.to_nat <$> (size_of σ $ Tnamed base).\n\n  (** The bytes at the offset are the ones that are referenced by the field *)\n  Axiom raw_bytes_of_struct_offset : forall σ cls flds rs m bytes off,\n    raw_bytes_of_struct σ cls flds rs ->\n    flds !! FieldOrBase.Field m = Some bytes ->\n    offset_of σ cls m = Some off ->\n    firstn (length bytes) (skipn (Z.to_nat off) rs) = bytes.\n\nEnd RAW_BYTES_VAL.\n\nModule Type RAW_BYTES_MIXIN\n       (Import P : PTRS) (Import R : RAW_BYTES)\n       (Import V : VAL_MIXIN P R)\n       (Import RD : RAW_BYTES_VAL P R V).\n\n  Inductive val_related : genv -> type -> val -> val -> Prop :=\n  | Veq_refl σ ty v: val_related σ ty v v\n  | Vqual σ t ty v1 v2:\n      val_related σ ty v1 v2 ->\n      val_related σ (Tqualified t ty) v1 v2\n  | Vraw_uint8 σ raw z\n      (Hraw : raw_bytes_of_val σ Tu8 (Vint z) [raw]) :\n      val_related σ Tu8 (Vraw raw) (Vint z)\n  | Vuint8_raw σ z raw\n      (Hraw : raw_bytes_of_val σ Tu8 (Vint z) [raw]) :\n      val_related σ Tu8 (Vint z) (Vraw raw).\n\n  Lemma val_related_qual :\n    forall σ t ty v1 v2,\n      val_related σ ty v1 v2 ->\n      val_related σ (Tqualified t ty) v1 v2.\n  Proof. intros; by constructor. Qed.\n\n  #[global] Instance val_related_reflexive σ ty : Reflexive (val_related σ ty).\n  Proof. constructor. Qed.\n\n  #[global] Instance val_related_symmetric σ ty : Symmetric (val_related σ ty).\n  Proof.\n    rewrite /Symmetric; intros * Hval_related;\n      induction Hval_related; subst; by constructor.\n  Qed.\n\n  #[global] Instance val_related_transitive σ ty : Transitive (val_related σ ty).\n  Proof.\n    rewrite /Transitive; intros * Hval_related1;\n      induction Hval_related1; intros * Hval_related2.\n    - by auto.\n    - constructor; apply IHHval_related1;\n        inversion Hval_related2; subst;\n        by [constructor | auto].\n    - inversion Hval_related2 as [ | | | ??? Hraw' ]; subst.\n      + by constructor.\n      + pose proof (raw_bytes_of_val_unique_encoding Hraw Hraw') as [= ->].\n        by constructor.\n    - inversion Hval_related2 as [ | | ??? Hraw' | ]; subst.\n      + by constructor.\n      + pose proof (raw_bytes_of_val_int_unique_val Hraw Hraw') as ->.\n        by constructor.\n  Qed.\n\n  #[global] Instance val_related_Proper : Proper (genv_leq ==> eq ==> eq ==> eq ==> iff) val_related.\n  Proof.\n    repeat red; intros ?? Heq **; subst; split; intros Hval;\n      induction Hval; subst; constructor; auto;\n      by [rewrite -> Heq in Hraw | rewrite <- Heq in Hraw].\n  Qed.\n\n  Lemma raw_bytes_of_val_uint_length : forall σ v rs sz sgn,\n      raw_bytes_of_val σ (Tnum sz sgn) v rs ->\n      length rs = bytesNat sz.\n  Proof.\n    intros * Hraw_bytes_of_val%raw_bytes_of_val_sizeof.\n    inversion Hraw_bytes_of_val as [Hsz]. clear Hraw_bytes_of_val.\n    by apply N_of_nat_inj in Hsz.\n  Qed.\nEnd RAW_BYTES_MIXIN.\n\nModule Type HAS_TYPE (Import P : PTRS) (Import R : RAW_BYTES) (Import V : VAL_MIXIN P R).\n  (** typedness of values\n      note that only primitives fit into this, there is no [val] representation\n      of aggregates, except through [Vptr p] with [p] pointing to the contents.\n  *)\n\n  (**\n  [has_type v ty] is an approximation in [Prop] of \"[v] is an initialized value\n  of type [t].\" This implies:\n  - if [ty <> Tvoid], then [v <> Vundef] <--\n    ^---- TODO: <https://gitlab.com/bedrocksystems/cpp2v-core/-/issues/319>\n  - if [ty = Tvoid], then [v = Vundef].\n  - if [ty = Tnullptr], then [v = Vptr nullptr].\n  - if [ty = Tnum sz sgn], then [v] fits the appropriate bounds (see\n    [has_int_type']).\n  - if [ty] is a type of pointers/aggregates, we only ensure that [v = Vptr p].\n    + NOTE: We require that - for a type [Tnamed nm] - the name resolves to some\n      [GlobDecl] other than [Gtype] in a given [σ : genv].\n  - if [ty] is a type of references, we ensure that [v = Vref p] and\n    that [p <> nullptr]; [Vref] is an alias for [Vptr]\n  - if [ty] is a type of arrays, we ensure that [v = Vptr p] and\n    that [p <> nullptr].\n    *)\n  Parameter has_type : forall {σ : genv}, val -> type -> Prop.\n\n  #[global]\n  Declare Instance has_type_mono : Proper (genv_leq ==> eq ==> eq ==> Basics.impl) (@has_type).\n\n  #[global]\n  Instance has_type_proper : Proper (genv_eq ==> eq ==> eq ==> iff) (@has_type).\n  Proof.\n    compute; split; apply has_type_mono; eauto; tauto.\n  Qed.\n\n  Section with_genv.\n    Context {σ : genv}.\n\n    Axiom has_type_pointer : forall v ty,\n        has_type v (Tpointer ty) -> exists p, v = Vptr p.\n    Axiom has_type_nullptr : forall v,\n        has_type v Tnullptr <-> v = Vptr nullptr.\n    Axiom has_type_ref : forall v ty,\n        has_type v (Tref ty) -> exists p, v = Vref p /\\ p <> nullptr.\n    Axiom has_type_rv_ref : forall v ty,\n        has_type v (Trv_ref ty) -> exists p, v = Vref p /\\ p <> nullptr.\n    Axiom has_type_array : forall v ty n,\n        has_type v (Tarray ty n) -> exists p, v = Vptr p /\\ p <> nullptr.\n    Axiom has_type_function : forall v cc rty args,\n        has_type v (Tfunction (cc:=cc) rty args) -> exists p, v = Vptr p /\\ p <> nullptr.\n\n    Axiom has_type_char : forall ct v,\n        (exists n, v = Vchar n /\\ 0 <= n < 2^(char_type.bitsN ct))%N <-> has_type v (Tchar_ ct).\n\n    Axiom has_type_void : forall v,\n        has_type v Tvoid -> v = Vundef.\n\n    Axiom has_nullptr_type : forall ty,\n        has_type (Vptr nullptr) (Tpointer ty).\n\n    Axiom has_type_bool : forall v,\n        has_type v Tbool <-> exists b, v = Vbool b.\n\n    (* NOTE: even if an enumeration's underlying type is `unsigned int` (which contains\n       raw values), raw values are not well typed at the enumeration type. *)\n    Axiom has_type_enum : forall v nm,\n        has_type v (Tenum nm) <->\n        exists tu ty ls,\n          tu ⊧ σ /\\ tu !! nm = Some (Genum ty ls) /\\\n          (~is_raw v) /\\ has_type v (drop_qualifiers ty).\n\n    (** Note in the case of [Tuchar], the value [v] could be a\n        raw value. *)\n    Axiom has_int_type' : forall sz sgn v,\n        has_type v (Tnum sz sgn) <->\n          (exists z, v = Vint z /\\ bound sz sgn z) \\/\n          (exists r, v = Vraw r /\\ Tnum sz sgn = Tuchar).\n\n    Axiom has_type_qual_iff : forall t q x,\n        has_type x t <-> has_type x (Tqualified q t).\n\n  End with_genv.\n\nEnd HAS_TYPE.\n\nModule Type HAS_TYPE_MIXIN (Import P : PTRS) (Import R : RAW_BYTES) (Import V : VAL_MIXIN P R)\n    (Import HT : HAS_TYPE P R V).\n  Section with_env.\n    Context {σ : genv}.\n\n    Lemma has_bool_type : forall z,\n      0 <= z < 2 <-> has_type (Vint z) Tbool.\n    Proof.\n      intros z. rewrite has_type_bool. split=>Hz.\n      - destruct (decide (z = 0)); simplify_eq; first by exists false.\n        destruct (decide (z = 1)); simplify_eq; first by exists true. lia.\n      - unfold Vbool in Hz. destruct Hz as [b Hb].\n        destruct b; simplify_eq; lia.\n    Qed.\n\n    Lemma has_int_type : forall sz (sgn : signed) z,\n        bound sz sgn z <-> has_type (Vint z) (Tnum sz sgn).\n    Proof. move => *. rewrite has_int_type'. naive_solver. Qed.\n\n    Lemma has_type_char' (n : N) ct : (0 <= n < 2 ^ char_type.bitsN ct)%N <-> has_type (Vchar n) (Tchar_ ct).\n    Proof. rewrite -has_type_char. naive_solver. Qed.\n\n    Lemma has_type_char_255 (n : N) ct : (0 <= n < 256)%N -> has_type (Vchar n) (Tchar_ ct).\n    Proof. intros. rewrite -has_type_char'. destruct ct; simpl; lia. Qed.\n\n    Lemma has_type_char_0 ct :  has_type (Vchar 0) (Tchar_ ct).\n    Proof. intros. apply has_type_char_255. lia. Qed.\n\n    Lemma has_type_drop_qualifiers\n      : forall v ty, has_type v ty <-> has_type v (drop_qualifiers ty).\n    Proof.\n      induction ty; simpl; eauto.\n      by rewrite -has_type_qual_iff -IHty.\n    Qed.\n\n    (* TODO fix naming convention *)\n    Lemma has_type_qual  t q x :\n        has_type x (drop_qualifiers t) ->\n        has_type x (Tqualified q t).\n    Proof.\n      intros. by apply has_type_drop_qualifiers.\n    Qed.\n\n    Section has_type.\n      Lemma has_type_bswap8:\n        forall v,\n          has_type (Vint (bswap8 v)) Tu8.\n      Proof. intros *; apply has_int_type; red; generalize (bswap8_bounded v); simpl; lia. Qed.\n\n      Lemma has_type_bswap16:\n        forall v,\n          has_type (Vint (bswap16 v)) Tu16.\n      Proof. intros *; apply has_int_type; red; generalize (bswap16_bounded v); simpl; lia. Qed.\n\n      Lemma has_type_bswap32:\n        forall v,\n          has_type (Vint (bswap32 v)) Tu32.\n      Proof. intros *; apply has_int_type; red; generalize (bswap32_bounded v); simpl; lia. Qed.\n\n      Lemma has_type_bswap64:\n        forall v,\n          has_type (Vint (bswap64 v)) Tu64.\n      Proof. intros *; apply has_int_type; red; generalize (bswap64_bounded v); simpl; lia. Qed.\n\n      Lemma has_type_bswap128:\n        forall v,\n          has_type (Vint (bswap128 v)) Tu128.\n      Proof. intros *; apply has_int_type; red; generalize (bswap128_bounded v); simpl; lia. Qed.\n    End has_type.\n\n    Lemma has_type_bswap:\n      forall sz v,\n        has_type (Vint (bswap sz v)) (Tnum sz Unsigned).\n    Proof.\n      intros *; destruct sz;\n        eauto using\n              has_type_bswap8,\n              has_type_bswap16,\n              has_type_bswap32,\n              has_type_bswap64,\n              has_type_bswap128.\n    Qed.\n\n  End with_env.\n\n  #[global] Hint Resolve has_type_qual : has_type.\n  #[global] Hint Resolve has_type_bswap : has_type.\n\n  Arguments Z.add _ _ : simpl never.\n  Arguments Z.sub _ _ : simpl never.\n  Arguments Z.mul _ _ : simpl never.\n  Arguments Z.pow _ _ : simpl never.\n  Arguments Z.opp _ : simpl never.\n  Arguments Z.pow_pos _ _ : simpl never.\n\nEnd HAS_TYPE_MIXIN.\n\n(* Collect all the axioms. *)\nModule Type VALUES_DEFS (P : PTRS_INTF) := RAW_BYTES <+ VAL_MIXIN P <+ RAW_BYTES_VAL P <+ HAS_TYPE P.\n(* Plug mixins. *)\nModule Type VALUES_INTF_FUNCTOR (P : PTRS_INTF) := VALUES_DEFS P <+ RAW_BYTES_MIXIN P <+ HAS_TYPE_MIXIN P.\n\nDeclare Module Export PTRS_INTF_AXIOM : PTRS_INTF.\n\n(* Interface for other modules. *)\nModule Export VALUES_INTF_AXIOM <: VALUES_INTF_FUNCTOR PTRS_INTF_AXIOM.\n  Include VALUES_INTF_FUNCTOR PTRS_INTF_AXIOM.\nEnd VALUES_INTF_AXIOM.\n", "meta": {"author": "bedrocksystems", "repo": "BRiCk", "sha": "23d7e64cc53706de608dbff0be75d1c4b8c3a7ec", "save_path": "github-repos/coq/bedrocksystems-BRiCk", "path": "github-repos/coq/bedrocksystems-BRiCk/BRiCk-23d7e64cc53706de608dbff0be75d1c4b8c3a7ec/theories/lang/cpp/semantics/values.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.20535708054663918}}
{"text": "Require Import String.\n(*Require Import Sail_impl_base*)\nRequire Import Sail.Instr_kinds.\nRequire Import Sail.Values.\nRequire bbv.Word.\nImport ListNotations.\nLocal Open Scope Z.\n\nDefinition register_name := string.\nDefinition address := list bitU.\n\nInductive monad regval a e :=\n  | Done : a -> monad regval a e\n  (* Read a number of bytes from memory, returned in little endian order,\n     with or without a tag.  The first nat specifies the address, the second\n     the number of bytes. *)\n  | Read_mem : read_kind -> nat -> nat -> (list memory_byte -> monad regval a e) -> monad regval a e\n  | Read_memt : read_kind -> nat -> nat -> ((list memory_byte * bitU) -> monad regval a e) -> monad regval a e\n  (* Tell the system a write is imminent, at the given address and with the\n     given size. *)\n  | Write_ea : write_kind -> nat -> nat -> monad regval a e -> monad regval a e\n  (* Request the result : store-exclusive *)\n  | Excl_res : (bool -> monad regval a e) -> monad regval a e\n  (* Request to write a memory value of the given size at the given address,\n     with or without a tag. *)\n  | Write_mem : write_kind -> nat -> nat -> list memory_byte -> (bool -> monad regval a e) -> monad regval a e\n  | Write_memt : write_kind -> nat -> nat -> list memory_byte -> bitU -> (bool -> monad regval a e) -> monad regval a e\n  (* Tell the system to dynamically recalculate dependency footprint *)\n  | Footprint : monad regval a e -> monad regval a e\n  (* Request a memory barrier *)\n  | Barrier : barrier_kind -> monad regval a e -> monad regval a e\n  (* Request to read register, will track dependency when mode.track_values *)\n  | Read_reg : register_name -> (regval -> monad regval a e) -> monad regval a e\n  (* Request to write register *)\n  | Write_reg : register_name -> regval -> monad regval a e -> monad regval a e\n  (* Request to choose a Boolean, e.g. to resolve an undefined bit. The string\n     argument may be used to provide information to the system about what the\n     Boolean is going to be used for. *)\n  | Choose : string -> (bool -> monad regval a e) -> monad regval a e\n  (* Print debugging or tracing information *)\n  | Print : string -> monad regval a e -> monad regval a e\n  (*Result of a failed assert with possible error message to report*)\n  | Fail : string -> monad regval a e\n  (* Exception of type e *)\n  | Exception : e -> monad regval a e.\n\nArguments Done [_ _ _].\nArguments Read_mem [_ _ _].\nArguments Read_memt [_ _ _].\nArguments Write_ea [_ _ _].\nArguments Excl_res [_ _ _].\nArguments Write_mem [_ _ _].\nArguments Write_memt [_ _ _].\nArguments Footprint [_ _ _].\nArguments Barrier [_ _ _].\nArguments Read_reg [_ _ _].\nArguments Write_reg [_ _ _].\nArguments Choose [_ _ _].\nArguments Print [_ _ _].\nArguments Fail [_ _ _].\nArguments Exception [_ _ _].\n\nInductive event {regval} :=\n  | E_read_mem : read_kind -> nat -> nat -> list memory_byte -> event\n  | E_read_memt : read_kind -> nat -> nat -> (list memory_byte * bitU) -> event\n  | E_write_mem : write_kind -> nat -> nat -> list memory_byte -> bool -> event\n  | E_write_memt : write_kind -> nat -> nat -> list memory_byte -> bitU -> bool -> event\n  | E_write_ea : write_kind -> nat -> nat -> event\n  | E_excl_res : bool -> event\n  | E_barrier : barrier_kind -> event\n  | E_footprint : event\n  | E_read_reg : register_name -> regval -> event\n  | E_write_reg : register_name -> regval -> event\n  | E_choose : string -> bool -> event\n  | E_print : string -> event.\nArguments event : clear implicits.\n\nDefinition trace regval := list (event regval).\n\n(*val return : forall rv a e. a -> monad rv a e*)\nDefinition returnm {rv A E} (a : A) : monad rv A E := Done a.\n\n(*val bind : forall rv a b e. monad rv a e -> (a -> monad rv b e) -> monad rv b e*)\nFixpoint bind {rv A B E} (m : monad rv A E) (f : A -> monad rv B E) := match m with\n  | Done a => f a\n  | Read_mem rk a sz k =>       Read_mem rk a sz       (fun v => bind (k v) f)\n  | Read_memt rk a sz k =>      Read_memt rk a sz      (fun v => bind (k v) f)\n  | Write_mem wk a sz v k =>    Write_mem wk a sz v    (fun v => bind (k v) f)\n  | Write_memt wk a sz v t k => Write_memt wk a sz v t (fun v => bind (k v) f)\n  | Read_reg descr k =>         Read_reg descr         (fun v => bind (k v) f)\n  | Excl_res k =>               Excl_res               (fun v => bind (k v) f)\n  | Choose descr k =>           Choose descr           (fun v => bind (k v) f)\n  | Write_ea wk a sz k =>       Write_ea wk a sz       (bind k f)\n  | Footprint k =>              Footprint              (bind k f)\n  | Barrier bk k =>             Barrier bk             (bind k f)\n  | Write_reg r v k =>          Write_reg r v          (bind k f)\n  | Print msg k =>              Print msg              (bind k f)\n  | Fail descr =>               Fail descr\n  | Exception e =>              Exception e\nend.\n\nNotation \"m >>= f\" := (bind m f) (at level 50, left associativity).\n(*val (>>) : forall rv b e. monad rv unit e -> monad rv b e -> monad rv b e*)\nDefinition bind0 {rv A E} (m : monad rv unit E) (n : monad rv A E) :=\n  m >>= fun (_ : unit) => n.\nNotation \"m >> n\" := (bind0 m n) (at level 50, left associativity).\n\n(*val exit : forall rv a e. unit -> monad rv a e*)\nDefinition exit {rv A E} (_ : unit) : monad rv A E := Fail \"exit\".\n\n(*val choose_bool : forall 'rv 'e. string -> monad 'rv bool 'e*)\nDefinition choose_bool {rv E} descr : monad rv bool E := Choose descr returnm.\n\n(*val undefined_bool : forall 'rv 'e. unit -> monad 'rv bool 'e*)\nDefinition undefined_bool {rv e} (_:unit) : monad rv bool e := choose_bool \"undefined_bool\".\n\nDefinition undefined_unit {rv e} (_:unit) : monad rv unit e := returnm tt.\n\n(*val assert_exp : forall rv e. bool -> string -> monad rv unit e*)\nDefinition assert_exp {rv E} (exp :bool) msg : monad rv unit E :=\n if exp then Done tt else Fail msg.\n\nDefinition assert_exp' {rv E} (exp :bool) msg : monad rv (exp = true) E :=\n if exp return monad rv (exp = true) E then Done eq_refl else Fail msg.\nDefinition bindH {rv A P E} (m : monad rv P E) (n : monad rv A E) :=\n  m >>= fun (H : P) => n.\nNotation \"m >>> n\" := (bindH m n) (at level 50, left associativity).\n\n(*val throw : forall rv a e. e -> monad rv a e*)\nDefinition throw {rv A E} e : monad rv A E := Exception e.\n\n(*val try_catch : forall rv a e1 e2. monad rv a e1 -> (e1 -> monad rv a e2) -> monad rv a e2*)\nFixpoint try_catch {rv A E1 E2} (m : monad rv A E1) (h : E1 -> monad rv A E2) := match m with\n  | Done a =>                   Done a\n  | Read_mem rk a sz k =>       Read_mem rk a sz       (fun v => try_catch (k v) h)\n  | Read_memt rk a sz k =>      Read_memt rk a sz      (fun v => try_catch (k v) h)\n  | Write_mem wk a sz v k =>    Write_mem wk a sz v    (fun v => try_catch (k v) h)\n  | Write_memt wk a sz v t k => Write_memt wk a sz v t (fun v => try_catch (k v) h)\n  | Read_reg descr k =>         Read_reg descr         (fun v => try_catch (k v) h)\n  | Excl_res k =>               Excl_res               (fun v => try_catch (k v) h)\n  | Choose descr k =>           Choose descr           (fun v => try_catch (k v) h)\n  | Write_ea wk a sz k =>       Write_ea wk a sz       (try_catch k h)\n  | Footprint k =>              Footprint              (try_catch k h)\n  | Barrier bk k =>             Barrier bk             (try_catch k h)\n  | Write_reg r v k =>          Write_reg r v          (try_catch k h)\n  | Print msg k =>              Print msg              (try_catch k h)\n  | Fail descr =>               Fail descr\n  | Exception e =>              h e\nend.\n\n(* For early return, we abuse exceptions by throwing and catching\n   the return value. The exception type is \"either r e\", where \"inr e\"\n   represents a proper exception and \"inl r\" an early return : value \"r\". *)\nDefinition monadR rv a r e := monad rv a (sum r e).\n\n(*val early_return : forall rv a r e. r -> monadR rv a r e*)\nDefinition early_return {rv A R E} (r : R) : monadR rv A R E := throw (inl r).\n\n(*val catch_early_return : forall rv a e. monadR rv a a e -> monad rv a e*)\nDefinition catch_early_return {rv A E} (m : monadR rv A A E) :=\n  try_catch m\n    (fun r => match r with\n      | inl a => returnm a\n      | inr e => throw e\n     end).\n\n(* Lift to monad with early return by wrapping exceptions *)\n(*val liftR : forall rv a r e. monad rv a e -> monadR rv a r e*)\nDefinition liftR {rv A R E} (m : monad rv A E) : monadR rv A R E :=\n try_catch m (fun e => throw (inr e)).\n\n(* Catch exceptions in the presence : early returns *)\n(*val try_catchR : forall rv a r e1 e2. monadR rv a r e1 -> (e1 -> monadR rv a r e2) ->  monadR rv a r e2*)\nDefinition try_catchR {rv A R E1 E2} (m : monadR rv A R E1) (h : E1 -> monadR rv A R E2) :=\n  try_catch m\n    (fun r => match r with\n      | inl r => throw (inl r)\n      | inr e => h e\n     end).\n\n(*val maybe_fail : forall 'rv 'a 'e. string -> maybe 'a -> monad 'rv 'a 'e*)\nDefinition maybe_fail {rv A E} msg (x : option A) : monad rv A E :=\nmatch x with\n  | Some a => returnm a\n  | None => Fail msg\nend.\n\n(*val read_memt_bytes : forall 'rv 'a 'b 'e. Bitvector 'a, Bitvector 'b => read_kind -> 'a -> integer -> monad 'rv (list memory_byte * bitU) 'e*)\nDefinition read_memt_bytes {rv A E} rk (addr : mword A) sz : monad rv (list memory_byte * bitU) E :=\n  Read_memt rk (Word.wordToNat (get_word addr)) (Z.to_nat sz) returnm.\n\n(*val read_memt : forall 'rv 'a 'b 'e. Bitvector 'a, Bitvector 'b => read_kind -> 'a -> integer -> monad 'rv ('b * bitU) 'e*)\nDefinition read_memt {rv A B E} `{ArithFact (B >=? 0)} rk (addr : mword A) sz : monad rv (mword B * bitU) E :=\n  bind\n    (read_memt_bytes rk addr sz)\n    (fun '(bytes, tag) =>\n       match of_bits (bits_of_mem_bytes bytes) with\n       | Some v => returnm (v, tag)\n       | None => Fail \"bits_of_mem_bytes\"\n       end).\n\n(*val read_mem_bytes : forall 'rv 'a 'b 'e. Bitvector 'a, Bitvector 'b => read_kind -> 'a -> integer -> monad 'rv (list memory_byte) 'e*)\nDefinition read_mem_bytes {rv A E} rk (addr : mword A) sz : monad rv (list memory_byte) E :=\n  Read_mem rk (Word.wordToNat (get_word addr)) (Z.to_nat sz) returnm.\n\n(*val read_mem : forall 'rv 'a 'b 'e. Bitvector 'a, Bitvector 'b => read_kind -> 'a -> integer -> monad 'rv 'b 'e*)\nDefinition read_mem {rv A B E} `{ArithFact (B >=? 0)} rk (addrsz : Z) (addr : mword A) sz : monad rv (mword B) E :=\n  bind\n    (read_mem_bytes rk addr sz)\n    (fun bytes =>\n       maybe_fail \"bits_of_mem_bytes\" (of_bits (bits_of_mem_bytes bytes))).\n\n(*val excl_result : forall rv e. unit -> monad rv bool e*)\nDefinition excl_result {rv e} (_:unit) : monad rv bool e :=\n  let k successful := (returnm successful) in\n  Excl_res k.\n\nDefinition write_mem_ea {rv a E} wk (addrsz : Z) (addr: mword a) sz : monad rv unit E :=\n Write_ea wk (Word.wordToNat (get_word addr)) (Z.to_nat sz) (Done tt).\n\n(*val write_mem : forall 'rv 'a 'b 'e. Bitvector 'a, Bitvector 'b =>\n  write_kind -> integer -> 'a -> integer -> 'b -> monad 'rv bool 'e*)\nDefinition write_mem {rv a b E} wk (addrsz : Z) (addr : mword a) sz (v : mword b) : monad rv bool E :=\n  match (mem_bytes_of_bits v, Word.wordToNat (get_word addr)) with\n    | (Some v, addr) =>\n       Write_mem wk addr (Z.to_nat sz) v returnm\n    | _ => Fail \"write_mem\"\n  end.\n\n(*val write_memt : forall 'rv 'a 'b 'e. Bitvector 'a, Bitvector 'b =>\n  write_kind -> 'a -> integer -> 'b -> bitU -> monad 'rv bool 'e*)\nDefinition write_memt {rv a b E} wk (addr : mword a) sz (v : mword b) tag : monad rv bool E :=\n  match (mem_bytes_of_bits v, Word.wordToNat (get_word addr)) with\n    | (Some v, addr) =>\n       Write_memt wk addr (Z.to_nat sz) v tag returnm\n    | _ => Fail \"write_mem\"\n  end.\n\nDefinition read_reg {s rv a e} (reg : register_ref s rv a) : monad rv a e :=\n  let k v :=\n    match reg.(of_regval) v with\n      | Some v => Done v\n      | None => Fail \"read_reg: unrecognised value\"\n    end\n  in\n  Read_reg reg.(name) k.\n\n(* TODO\nval read_reg_range : forall 's 'r 'rv 'a 'e. Bitvector 'a => register_ref 's 'rv 'r -> integer -> integer -> monad 'rv 'a 'e\nlet read_reg_range reg i j =\n  read_reg_aux of_bits (external_reg_slice reg (nat_of_int i,nat_of_int j))\n\nlet read_reg_bit reg i =\n  read_reg_aux (fun v -> v) (external_reg_slice reg (nat_of_int i,nat_of_int i)) >>= fun v ->\n  return (extract_only_element v)\n\nlet read_reg_field reg regfield =\n  read_reg_aux (external_reg_field_whole reg regfield)\n\nlet read_reg_bitfield reg regfield =\n  read_reg_aux (external_reg_field_whole reg regfield) >>= fun v ->\n  return (extract_only_element v)*)\n\nDefinition reg_deref {s rv a e} := @read_reg s rv a e.\n\n(*Parameter write_reg : forall {s rv a e}, register_ref s rv a -> a -> monad rv unit e.*)\nDefinition write_reg {s rv a e} (reg : register_ref s rv a) (v : a) : monad rv unit e :=\n Write_reg reg.(name) (reg.(regval_of) v) (Done tt).\n\n(* TODO\nlet write_reg reg v =\n  write_reg_aux (external_reg_whole reg) v\nlet write_reg_range reg i j v =\n  write_reg_aux (external_reg_slice reg (nat_of_int i,nat_of_int j)) v\nlet write_reg_pos reg i v =\n  let iN = nat_of_int i in\n  write_reg_aux (external_reg_slice reg (iN,iN)) [v]\nlet write_reg_bit = write_reg_pos\nlet write_reg_field reg regfield v =\n  write_reg_aux (external_reg_field_whole reg regfield.field_name) v\nlet write_reg_field_bit reg regfield bit =\n  write_reg_aux (external_reg_field_whole reg regfield.field_name)\n                (Vector [bit] 0 (is_inc_of_reg reg))\nlet write_reg_field_range reg regfield i j v =\n  write_reg_aux (external_reg_field_slice reg regfield.field_name (nat_of_int i,nat_of_int j)) v\nlet write_reg_field_pos reg regfield i v =\n  write_reg_field_range reg regfield i i [v]\nlet write_reg_field_bit = write_reg_field_pos*)\n\n(*val barrier : forall rv e. barrier_kind -> monad rv unit e*)\nDefinition barrier {rv e} bk : monad rv unit e := Barrier bk (Done tt).\n\n(*val footprint : forall rv e. unit -> monad rv unit e*)\nDefinition footprint {rv e} (_ : unit) : monad rv unit e := Footprint (Done tt).\n\n(* Event traces *)\n\nLocal Open Scope bool_scope.\n\n(*val emitEvent : forall 'regval 'a 'e. Eq 'regval => monad 'regval 'a 'e -> event 'regval -> maybe (monad 'regval 'a 'e)*)\nDefinition emitEvent {Regval A E} `{forall (x y : Regval), Decidable (x = y)} (m : monad Regval A E) (e : event Regval) : option (monad Regval A E) :=\n match (e, m) with\n  | (E_read_mem rk a sz v, Read_mem rk' a' sz' k) =>\n     if read_kind_beq rk' rk && Nat.eqb a' a && Nat.eqb sz' sz then Some (k v) else None\n  | (E_read_memt rk a sz vt, Read_memt rk' a' sz' k) =>\n     if read_kind_beq rk' rk && Nat.eqb a' a && Nat.eqb sz' sz then Some (k vt) else None\n  | (E_write_mem wk a sz v r, Write_mem wk' a' sz' v' k) =>\n     if write_kind_beq wk' wk && Nat.eqb a' a && Nat.eqb sz' sz && generic_eq v' v then Some (k r) else None\n  | (E_write_memt wk a sz v tag r, Write_memt wk' a' sz' v' tag' k) =>\n     if write_kind_beq wk' wk && Nat.eqb a' a && Nat.eqb sz' sz && generic_eq v' v && generic_eq tag' tag then Some (k r) else None\n  | (E_read_reg r v, Read_reg r' k) =>\n     if generic_eq r' r then Some (k v) else None\n  | (E_write_reg r v, Write_reg r' v' k) =>\n     if generic_eq r' r && generic_eq v' v then Some k else None\n  | (E_write_ea wk a sz, Write_ea wk' a' sz' k) =>\n     if write_kind_beq wk' wk && Nat.eqb a' a && Nat.eqb sz' sz then Some k else None\n  | (E_barrier bk, Barrier bk' k) =>\n     if barrier_kind_beq bk' bk then Some k else None\n  | (E_print m, Print m' k) =>\n     if generic_eq m' m then Some k else None\n  | (E_excl_res v, Excl_res k) => Some (k v)\n  | (E_choose descr v, Choose descr' k) => if generic_eq descr' descr then Some (k v) else None\n  | (E_footprint, Footprint k) => Some k\n  | _ => None\nend.\n\nDefinition option_bind {A B : Type} (a : option A) (f : A -> option B) : option B :=\nmatch a with\n| Some x => f x\n| None => None\nend.\n\n(*val runTrace : forall 'regval 'a 'e. Eq 'regval => trace 'regval -> monad 'regval 'a 'e -> maybe (monad 'regval 'a 'e)*)\nFixpoint runTrace {Regval A E} `{forall (x y : Regval), Decidable (x = y)} (t : trace Regval) (m : monad Regval A E) : option (monad Regval A E) :=\nmatch t with\n  | [] => Some m\n  | e :: t' => option_bind (emitEvent m e) (runTrace t')\nend.\n\n(*val final : forall 'regval 'a 'e. monad 'regval 'a 'e -> bool*)\nDefinition final {Regval A E} (m : monad Regval A E) : bool :=\nmatch m with\n  | Done _ => true\n  | Fail _ => true\n  | Exception _ => true\n  | _ => false\nend.\n\n(*val hasTrace : forall 'regval 'a 'e. Eq 'regval => trace 'regval -> monad 'regval 'a 'e -> bool*)\nDefinition hasTrace {Regval A E} `{forall (x y : Regval), Decidable (x = y)} (t : trace Regval) (m : monad Regval A E) : bool :=\nmatch runTrace t m with\n  | Some m => final m\n  | None => false\nend.\n\n(*val hasException : forall 'regval 'a 'e. Eq 'regval => trace 'regval -> monad 'regval 'a 'e -> bool*)\nDefinition hasException {Regval A E} `{forall (x y : Regval), Decidable (x = y)} (t : trace Regval) (m : monad Regval A E) :=\nmatch runTrace t m with\n  | Some (Exception _) => true\n  | _ => false\nend.\n\n(*val hasFailure : forall 'regval 'a 'e. Eq 'regval => trace 'regval -> monad 'regval 'a 'e -> bool*)\nDefinition hasFailure {Regval A E} `{forall (x y : Regval), Decidable (x = y)} (t : trace Regval) (m : monad Regval A E) :=\nmatch runTrace t m with\n  | Some (Fail _) => true\n  | _ => false\nend.\n", "meta": {"author": "CTSRD-CHERI", "repo": "sail-cheri-mips", "sha": "13a9c3fb0c3f8d320d4f4650a63d23d3a8b12724", "save_path": "github-repos/coq/CTSRD-CHERI-sail-cheri-mips", "path": "github-repos/coq/CTSRD-CHERI-sail-cheri-mips/sail-cheri-mips-13a9c3fb0c3f8d320d4f4650a63d23d3a8b12724/prover_snapshots/coq/cheri-mips-snapshot/lib/sail/Prompt_monad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.20535708054663912}}
{"text": "Require Import Rupicola.Lib.Api.\n\nRecord  cell {width: Z} {BW: Bitwidth width} {word: word.word width} := { data : word }.\nSection with_parameters.\n  Context {width: Z} {BW: Bitwidth width} {word: word.word width} {mem: map.map word Byte.byte}.\n  Context {locals: map.map String.string word}.\n  Context {env: map.map String.string (list String.string * list String.string * Syntax.cmd)}.\n  Context {ext_spec: bedrock2.Semantics.ExtSpec}.\n  Context {wordok : word.ok word} {mapok : map.ok mem}.\n  Context {localsok : map.ok locals}.\n  Context {envok : map.ok env}.\n  Context {ext_spec_ok : Semantics.ext_spec.ok ext_spec}.\n  Local Notation cell := (@cell width BW word).\n\n  Definition cell_value (addr: word) (c: cell)\n    : mem -> Prop :=\n    scalar addr c.(data).\n\n  Definition get c := c.(data).\n  Definition put v := {| data := v |}.\n  (* No reference to the original cell: Rupicola decides which one to modify\n     based on the target of the call:\n       let/n c := put x in …\n             ^ .......^.... this gets mutated\n                      ^ ... with this value *)\n\n  Lemma compile_get : forall {tr mem locals functions} (c: cell),\n    let v := get c in\n    forall {P} {pred: P v -> predicate} {k: nlet_eq_k P v} {k_impl}\n      R c_ptr c_expr var,\n\n      sep (cell_value c_ptr c) R mem ->\n      WeakestPrecondition.dexpr mem locals c_expr c_ptr ->\n\n      (let v := v in\n       <{ Trace := tr;\n          Memory := mem;\n          Locals := map.put locals var v;\n          Functions := functions }>\n       k_impl\n       <{ pred (k v eq_refl) }>) ->\n      <{ Trace := tr;\n         Memory := mem;\n         Locals := locals;\n         Functions := functions }>\n      cmd.seq (cmd.set var (expr.load access_size.word c_expr))\n              k_impl\n      <{ pred (nlet_eq [var] v k) }>.\n  Proof.\n    repeat straightline.\n    exists (get c); split; repeat straightline; eauto.\n    eapply WeakestPrecondition_dexpr_expr; eauto.\n    eexists; split; [ | reflexivity ].\n    eauto using load_word_of_sep.\n  Qed.\n\n  Lemma compile_put : forall {tr mem locals functions} x,\n    let v := put x in\n    forall {P} {pred: P v -> predicate} {k: nlet_eq_k P v} {k_impl}\n      R c_ptr _c c_var x_expr,\n\n      WeakestPrecondition.dexpr mem locals x_expr x ->\n      map.get locals c_var = Some c_ptr ->\n      sep (cell_value c_ptr _c) R mem -> (* See FAQ on parameter order *)\n\n      (let v := v in\n       forall m,\n         sep (cell_value c_ptr v) R m ->\n         (<{ Trace := tr;\n             Memory := m;\n             Locals := locals;\n             Functions := functions }>\n          k_impl\n          <{ pred (k v eq_refl) }>)) ->\n      <{ Trace := tr;\n         Memory := mem;\n         Locals := locals;\n         Functions := functions }>\n      cmd.seq (cmd.store access_size.word (expr.var c_var) x_expr)\n              k_impl\n      <{ pred (nlet_eq [c_var] v k) }>.\n  Proof.\n    unfold cell_value; repeat straightline.\n    exists c_ptr; split; eexists; split; eauto.\n    repeat straightline. eauto.\n  Qed.\n\n  #[global] Program Instance SimpleAllocable_cell : Allocable cell_value :=\n    {| size_in_bytes := Memory.bytes_per_word width;\n       size_in_bytes_mod := Z_mod_same_full _;\n       P_to_bytes := _;\n       P_from_bytes := _ |}.\n  Next Obligation.\n    apply (P_to_bytes (Allocable := Allocable_scalar)).\n  Qed.\n  Next Obligation.\n    intros m H.\n    edestruct (P_from_bytes (Allocable := Allocable_scalar) _ _ H).\n    exists {| data := x |}. assumption.\n  Qed.\nEnd with_parameters.\n\n#[export] Hint Extern 1 => simple eapply compile_get; shelve : compiler.\n#[export] Hint Extern 1 => simple eapply compile_put; shelve : compiler.\n", "meta": {"author": "mit-plv", "repo": "rupicola", "sha": "3f59b3d2404ce425ddf4fd55ad2314996a573dc3", "save_path": "github-repos/coq/mit-plv-rupicola", "path": "github-repos/coq/mit-plv-rupicola/rupicola-3f59b3d2404ce425ddf4fd55ad2314996a573dc3/src/Rupicola/Examples/Cells/Cells.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2053570747131918}}
{"text": "Require Import Bool List Arith Nat.\nImport ListNotations.\nRequire Import Mmx.ast_instructions Mmx.binary Mmx.association_list Mmx.encode.\n\n\nLemma encode_decode_t_n : forall (i : instruction_tern_n) (bi : binary_instruction),\n    encode_t_n i = Some bi -> decode bi = Some (instr_t_n i).\nProof.\n  (* first part trying to get lot of information from encode_t_n *)\n  intros.\n  unfold encode_t_n in H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  unfold decode.\n  rewrite ret_rewrite in H.\n  inversion H.\n  (* now going to go further into decode *)\n  assert (length x0 = 8) by (apply commut_equal in H1; apply size_n_bit in H1; auto).\n  assert (get_first_n_bit (x0 ++ x1 ++ x2 ++ x3) 8 = (x0,x1 ++ x2 ++ x3)) by (apply get_first_n_bit_size_4; auto).  \n  rewrite H7.\n  apply commut_equal in H0.\n  apply lookup_encdecP in H0.\n  apply commut_equal in H1.\n  assert (bit_n x0 = x) by (apply n_bit_n in H1; exact H1).\n  rewrite H8.\n  rewrite H0.\n  assert (forall (f : tag -> (option instruction)), bind (Some (tag_t_n (instr_opcode_t_n i))) f = f (tag_t_n (instr_opcode_t_n i))) by reflexivity.\n  rewrite H9.\n  assert (length x1 = 8) by (apply commut_equal in H2; apply operand_to_bin_size in H2; auto).\n  assert (get_first_n_bit  (x1 ++ x2 ++ x3) 8 = (x1,x2 ++ x3)) by (apply get_first_n_bit_size_3; auto).\n  rewrite H11.\n  assert (length x2 = 8) by (apply commut_equal in H3; apply operand_to_bin_size in H3; auto).\n  assert (get_first_n_bit  (x2 ++ x3) 8 = (x2,x3))by (apply commut_equal in H4; apply get_first_n_bit_size_tl; auto).\n  rewrite H13.\n  assert (length x3 = 8) by (apply commut_equal in H4; apply operand_to_bin_size in H4; auto).\n  assert (get_first_n_bit  (x3) 8 = (x3,[])) by (apply get_first_n_bit_size_nil_n; auto).\n  rewrite H15.\n  rewrite ret_rewrite. \n  apply commut_equal in H2.\n  apply operand_to_bin_hypothesis1_t_n in H2.\n  rewrite H2.\n  apply commut_equal in H3.\n  apply operand_to_bin_hypothesis2_t_n in H3.\n  rewrite H3.\n  apply commut_equal in H4.\n  apply operand_to_bin_hypothesis3_t_n in H4.\n  rewrite H4.  \n  assert ({|\n       instr_opcode_t_n := instr_opcode_t_n i;\n       instr_operande1_t_n := instr_operande1_t_n i;\n       instr_operande2_t_n := instr_operande2_t_n i;\n       instr_operande3_t_n := instr_operande3_t_n i |} = i).\n  {\n    simpl. destruct i.\n    compute. reflexivity.\n  }\n  rewrite H16.\n  repeat rewrite app_length.\n  rewrite H5.\n  rewrite H10.\n  rewrite H12.\n  rewrite H14.\n  simpl.  \n  reflexivity.\nQed.\n \nLemma encode_decode_t_i : forall (i : instruction_tern_i) (bi : binary_instruction),\n    encode_t_i i = Some bi -> decode bi = Some (instr_t_i i).\nProof.\n    (* first part trying to get lot of information from encode_t_n *)\n  intros.\n  unfold encode_t_n in H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  unfold decode.\n  rewrite ret_rewrite in H.\n  inversion H.\n  (* now going to go further into decode *)\n  assert (length x0 = 8) by (apply commut_equal in H1; apply size_n_bit in H1; auto).\n  assert (get_first_n_bit (x0 ++ x1 ++ x2 ++ x3) 8 = (x0,x1 ++ x2 ++ x3)) by (apply get_first_n_bit_size_4; auto).\n  rewrite H7.\n  apply commut_equal in H0.\n  apply lookup_encdecP in H0.\n  apply commut_equal in H1.\n  assert (bit_n x0 = x) by (apply n_bit_n in H1; exact H1).\n  rewrite H8.\n  rewrite H0.\n  assert (forall (f : tag -> (option instruction)), bind (Some (tag_t_i (instr_opcode_t_i i))) f = f (tag_t_i (instr_opcode_t_i i))) by reflexivity.\n  rewrite H9.\n  assert (length x1 = 8) by (apply commut_equal in H2; apply operand_to_bin_size in H2; auto).\n  assert (get_first_n_bit  (x1 ++ x2 ++ x3) 8 = (x1,x2 ++ x3)) by (apply get_first_n_bit_size_3; auto).\n  rewrite H11.\n  assert (length x2 = 8) by (apply commut_equal in H3; apply operand_to_bin_size in H3; auto).\n  assert (get_first_n_bit  (x2 ++ x3) 8 = (x2,x3))by (apply commut_equal in H4; apply get_first_n_bit_size_tl; auto).\n  rewrite H13.\n  assert (length x3 = 8) by (apply commut_equal in H4; apply operand_to_bin_size in H4; auto).\n  assert (get_first_n_bit  (x3) 8 = (x3,[])) by (apply get_first_n_bit_size_nil_n; auto).\n  rewrite H15.\n  rewrite ret_rewrite.\n  apply commut_equal in H2.\n  apply operand_to_bin_hypothesis1_t_i in H2.\n  rewrite H2.\n  apply commut_equal in H3.\n  apply operand_to_bin_hypothesis2_t_i in H3.\n  rewrite H3.\n  apply commut_equal in H4.\n  apply operand_to_bin_hypothesis3_t_i in H4.\n  rewrite H4.\n  assert ({|\n       instr_opcode_t_i := instr_opcode_t_i i;\n       instr_operande1_t_i := instr_operande1_t_i i;\n       instr_operande2_t_i := instr_operande2_t_i i;\n       instr_operande3_t_i := instr_operande3_t_i i |} = i).\n  {\n    simpl. destruct i.\n    compute. reflexivity.\n  }\n  rewrite H16.\n  repeat rewrite app_length.\n  rewrite H5.\n  rewrite H10.\n  rewrite H12.\n  rewrite H14.\n  simpl.  \n  reflexivity.\nQed.\n\n\n\nLemma encode_decode_d_n : forall (i : instruction_duo_n) (bi : binary_instruction),\n    encode_d_n i = Some bi -> decode bi = Some (instr_d_n i).\nProof.\n    (* first part trying to get lot of information from encode_t_n *)\n  intros.\n  unfold encode_t_n in H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  unfold decode.\n  rewrite ret_rewrite in H.\n  inversion H.\n  (* now going to go further into decode *)\n  assert (length x0 = 8) by (apply commut_equal in H1; apply size_n_bit in H1; auto).\n  assert (get_first_n_bit (x0 ++ x1 ++ x2) 8 = (x0,x1 ++ x2)) by (apply get_first_n_bit_size_3; auto).\n  rewrite H6.\n  apply commut_equal in H0.\n  apply lookup_encdecP in H0.\n  apply commut_equal in H1.\n  assert (bit_n x0 = x) by (apply n_bit_n in H1; exact H1).\n  rewrite H7.\n  rewrite H0.\n  assert (forall (f : tag -> (option instruction)), bind (Some (tag_d_n (instr_opcode_d_n i))) f = f (tag_d_n (instr_opcode_d_n i))) by reflexivity.\n  rewrite H8.\n  assert (length x1 = 8) by (apply commut_equal in H2; apply operand_to_bin_size in H2; auto).\n  assert (get_first_n_bit  (x1 ++ x2) 8 = (x1,x2)) by (apply get_first_n_bit_size_tl; auto).\n  rewrite H10.\n  assert (length x2 = 16) by (apply commut_equal in H3; apply operand_to_bin_double_size in H3; auto).\n  assert (get_first_n_bit x2 16 = (x2,[]))by (apply commut_equal in H4; apply get_first_n_bit_size_nil_n; auto).\n  rewrite H12.\n  rewrite ret_rewrite.\n  apply commut_equal in H2.\n  apply operand_to_bin_hypothesis1_d_n in H2.\n  rewrite H2.\n  apply commut_equal in H3.\n  apply operand_to_bin_double_hypothesis2_d_n in H3.\n  rewrite H3.\n  assert ({|\n       instr_opcode_d_n := instr_opcode_d_n i;\n       instr_operande1_d_n := instr_operande1_d_n i;\n       instr_operande2_d_n := instr_operande2_d_n i; |} = i).\n  {\n    simpl. destruct i.\n    compute. reflexivity.\n  }\n  rewrite H13.\n  repeat rewrite app_length.\n  rewrite H4.\n  rewrite H9.\n  rewrite H11.\n  simpl.  \n  reflexivity.\nQed.\n\n\nLemma encode_decode_d_i : forall (i : instruction_duo_i) (bi : binary_instruction),\n    encode_d_i i = Some bi -> decode bi = Some (instr_d_i i).\nProof.\n    (* first part trying to get lot of information from encode_t_n *)\n  intros.\n  unfold encode_t_n in H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  apply bind_rewrite in H.\n  destruct H.\n  destruct H.\n  unfold decode.\n  rewrite ret_rewrite in H.\n  inversion H.\n  (* now going to go further into decode *)\n  assert (length x0 = 8) by (apply commut_equal in H1; apply size_n_bit in H1; auto).\n  assert (get_first_n_bit (x0 ++ x1 ++ x2) 8 = (x0,x1 ++ x2)) by (apply get_first_n_bit_size_3; auto).\n  rewrite H6.\n  apply commut_equal in H0.\n  apply lookup_encdecP in H0.\n  apply commut_equal in H1.\n  assert (bit_n x0 = x) by (apply n_bit_n in H1; exact H1).\n  rewrite H7.\n  rewrite H0.\n  assert (forall (f : tag -> (option instruction)), bind (Some (tag_d_i (instr_opcode_d_i i))) f = f (tag_d_i (instr_opcode_d_i i))) by reflexivity.\n  rewrite H8.\n  assert (length x1 = 8) by (apply commut_equal in H2; apply operand_to_bin_size in H2; auto).\n  assert (get_first_n_bit  (x1 ++ x2) 8 = (x1,x2)) by (apply get_first_n_bit_size_tl; auto).\n  rewrite H10.\n  assert (length x2 = 16) by (apply commut_equal in H3; apply operand_to_bin_double_size in H3; auto).\n  assert (get_first_n_bit x2 16 = (x2,[]))by (apply commut_equal in H4; apply get_first_n_bit_size_nil_n; auto).\n  rewrite H12.\n  rewrite ret_rewrite.\n  apply commut_equal in H2.\n  apply operand_to_bin_hypothesis1_d_i in H2.\n  rewrite H2.\n  apply commut_equal in H3.\n  apply operand_to_bin_double_hypothesis2_d_i in H3.\n  rewrite H3.\n  assert ({|\n       instr_opcode_d_i := instr_opcode_d_i i;\n       instr_operande1_d_i := instr_operande1_d_i i;\n       instr_operande2_d_i := instr_operande2_d_i i; |} = i).\n  {\n    simpl. destruct i.\n    compute. reflexivity.\n  }\n  rewrite H13.\n  repeat rewrite app_length.\n  rewrite H4.\n  rewrite H9.\n  rewrite H11.\n  reflexivity.\nQed.\n\n\n\nLemma encode_decode : forall (i : instruction) (bi : binary_instruction),\n    encode i = Some bi -> decode bi = Some i.\nProof.\n  destruct i.\n  -apply encode_decode_t_n.\n  -apply encode_decode_t_i.\n  -apply encode_decode_d_n.\n  -apply encode_decode_d_i.\nQed.\n  \n", "meta": {"author": "romisfrag", "repo": "little_mmx_encode-decode", "sha": "9f5a583fc2376f271bac30ec82c8800614a5fdd6", "save_path": "github-repos/coq/romisfrag-little_mmx_encode-decode", "path": "github-repos/coq/romisfrag-little_mmx_encode-decode/little_mmx_encode-decode-9f5a583fc2376f271bac30ec82c8800614a5fdd6/srcOld2/encodeProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.20531332272220193}}
{"text": "Require Import ExtLib.Tactics.\nRequire Import MirrorCore.ExprI.\nRequire Import MirrorCore.SubstI.\nRequire Import MirrorCore.RTac.Core.\n\nRequire Import MirrorCore.Util.Forwardy.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection parameterized.\n  Variable typ : Set.\n  Variable expr : Set.\n\n  Context {RType_typ : RType typ}.\n  Context {Expr_expr : Expr typ expr}.\n  Context {Typ0_Prop : Typ0 _ Prop}.\n  Context {ExprUVar_expr : ExprUVar expr}.\n\n  Variable tac\n  : forall ctx : Ctx typ expr, ctx_subst ctx -> expr\n                               -> rtac typ expr.\n\n  Definition AT_GOAL\n  : rtac typ expr :=\n    fun ctx s e => (@tac ctx s e) ctx s e.\n\n  Hypothesis tac_sound : forall c s e, rtac_sound (@tac c s e).\n\n  Theorem AT_GOAL_sound : rtac_sound AT_GOAL.\n  Proof.\n    unfold AT_GOAL; simpl.\n    red. intros; subst.\n    eapply tac_sound. reflexivity.\n  Qed.\n\nEnd parameterized.\n\nTypeclasses Opaque AT_GOAL.\nHint Opaque AT_GOAL : typeclass_instances.\n\nArguments AT_GOAL {typ expr} _%rtac _ _ _.\n", "meta": {"author": "gmalecha", "repo": "mirror-core", "sha": "b962fbca15b0b5a4653f66d29d7115bb04ebd4f3", "save_path": "github-repos/coq/gmalecha-mirror-core", "path": "github-repos/coq/gmalecha-mirror-core/mirror-core-b962fbca15b0b5a4653f66d29d7115bb04ebd4f3/theories/RTac/AtGoal.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.20527904012131726}}
{"text": "Require Import AutoSep Malloc Bootstrap FactorialRecur.\n\n\nModule Type S.\n  Variable heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"top\"!\"top\" @ [topS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Call \"top\"!\"top\"()\n        [PREonly[_] [| False |] ]\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Definition m0 := link Malloc.m boot.\n  Definition m1 := link all m0.\n\n  Lemma ok0 : moduleOk m0.\n    link Malloc.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link all_ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n  \n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, ($(size * 4) <= w)%word -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/cito/examples/FactorialRecurDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.20527903786697121}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\n(****************************************************************************)\n(*                 The Calculus of Inductive Constructions                  *)\n(*                                                                          *)\n(*                                Projet Coq                                *)\n(*                                                                          *)\n(*                     INRIA                        ENS-CNRS                *)\n(*              Rocquencourt                        Lyon                    *)\n(*                                                                          *)\n(*                                 Coq V6.1                                 *)\n(*                               Oct 1st 1996                               *)\n(*                                                                          *)\n(****************************************************************************)\n(*                            MapProperty.v                                 *)\n(*                            A. SAIBI (May 95)                             *)\n(****************************************************************************)\n\n\nRequire Export Map.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\n\n(* Injective Map *)\n\nSection inj_surj_def.\n\nVariable A B : Setoid.\n\nDefinition Inj_law (f : Map A B) := forall x y : A, f x =_S f y -> x =_S y.\n\nStructure > Inj : Type :=  {Inj_map :> Map A B; Prf_isInj :> Inj_law Inj_map}.\n\n(* Surjective Map *)\n\nDefinition Surj_law (f : Map A B) (h : B -> A) := forall b : B, b =_S f (h b).\n\nStructure > Surj : Type := \n  {Surj_map :> Map A B;\n   Surj_elt : B -> A;\n   Prf_isSurj :> Surj_law Surj_map Surj_elt}.\n\nEnd inj_surj_def.\n\n\n\n", "meta": {"author": "JasonGross", "repo": "category-coq-experience-tests", "sha": "f9949ede618788fd051fe8327f997ee683388e49", "save_path": "github-repos/coq/JasonGross-category-coq-experience-tests", "path": "github-repos/coq/JasonGross-category-coq-experience-tests/category-coq-experience-tests-f9949ede618788fd051fe8327f997ee683388e49/ConCaT/SETOID/MapProperty.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2052578137457347}}
{"text": "Require Import List.\nImport ListNotations.\nRequire Import String.\nRequire Import Flocq.Appli.Fappli_IEEE_bits.\nRequire Import Flocq.Appli.Fappli_IEEE.\nRequire Import ZArith.\n\nRequire Import v1.EpicsTypes.\nRequire Import v1.Multi.\nRequire Import v1.NeutronTactics.\nRequire Import v1.FloatAux.\nRequire Import v1.Util.\n\nRequire Import v1.Expr.\nRequire v1.ExprDbl.  (* reuse some of the double arithmetic functions *)\n\n\nInductive ty := Nil | Dbl | Str.\nScheme Equality for ty.\n\nDefinition require_not_nil x :=\n    match x with\n    | Nil => None\n    | _ => Some x\n    end.\n\nDefinition require_dbl x :=\n    match x with\n    | Dbl => Some Dbl\n    | _ => None\n    end.\n\nDefinition require_match y x :=\n    if ty_eq_dec x y then Some x else None.\n\nDefinition always (x : ty) := fun (_ : ty) => Some x.\n\nDefinition unary_op_type (op : unary_op) (arg : ty) : option ty :=\n    match op with\n    | NotAlg => require_dbl arg\n    | NotLog => require_dbl arg\n    end.\n\nDefinition binary_op_type (op : binary_op) arg1 arg2 :=\n    match op with\n    | Add => require_not_nil arg1 >>= require_match arg2\n    | Sub => require_dbl arg1 >>= require_match arg2\n    | Mul => require_dbl arg1 >>= require_match arg2\n    | Div => require_dbl arg1 >>= require_match arg2\n    | Ge => require_dbl arg1 >>= require_match arg2\n    | Gt => require_dbl arg1 >>= require_match arg2\n    | Le => require_dbl arg1 >>= require_match arg2\n    | Lt => require_dbl arg1 >>= require_match arg2\n    | Ne => require_not_nil arg1 >>= require_match arg2 >>= always Dbl\n    | Eq => require_not_nil arg1 >>= require_match arg2 >>= always Dbl\n    | AndLog => require_dbl arg1 >>= require_match arg2\n    | OrLog => require_dbl arg1 >>= require_match arg2\n    end.\n\nDefinition varary_op_type (op : varary_op) (args : list ty) :=\n    match op return option ty with\n    | Min => None (* TODO *)\n    | Max => None (* TODO *)\n    end.\n\nDefinition seq_result_type t1 t2 :=\n    match t1, t2 with\n    | Nil, x => Some x\n    | x, Nil => Some x\n    | _, _ => None      (* Error to have two subexpressions that both produce results *)\n    end.\n\nInductive well_typed {n : nat} : ty -> expr (e_double + e_string) n -> Prop :=\n| WtVar : forall i, well_typed Dbl (EVar i)\n| WtEVar : forall i, well_typed Str (EXVar i)\n| WtLitDbl : forall x, well_typed Dbl (ELit (inl x))\n| WtLitStr : forall x, well_typed Str (ELit (inr x))\n| WtUnary : forall op t x t',\n        unary_op_type op t = Some t' ->\n        well_typed t x -> \n        well_typed t' (EUnary op x)\n| WtBinary : forall op t1 x1 t2 x2 t',\n        binary_op_type op t1 t2 = Some t' ->\n        well_typed t1 x1 -> \n        well_typed t2 x2 -> \n        well_typed t' (EBinary op x1 x2)\n| WtVarary : forall op ts xs t',\n        varary_op_type op ts = Some t' ->\n        Forall2 well_typed ts xs ->\n        well_typed t' (EVarary op xs)\n| WtAssign : forall i x,\n        well_typed Dbl x ->\n        well_typed Nil (EAssign i x)\n| WtXAssign : forall i x,\n        well_typed Str x ->\n        well_typed Nil (EXAssign i x)\n| WtCond : forall t cond body1 body2,\n        well_typed Dbl cond ->\n        well_typed t body1 ->\n        well_typed t body2 ->\n        well_typed t (ECond cond body1 body2)\n| WtSeq : forall t1 e1 t2 e2 t,\n        well_typed t1 e1 ->\n        well_typed t2 e2 ->\n        seq_result_type t1 t2 = Some t ->\n        well_typed t (ESeq e1 e2)\n.\n\nFixpoint count_results {n} (e : expr e_double n) :=\n    match e with\n    | EAssign _ _ => 0\n    | EXAssign _ _ => 0\n    | ESeq e1 e2 => count_results e1 + count_results e2\n    | _ => 1\n    end.\n\n\n\n\n\n\nNotation b64_eq := (ExprDbl.b64_eq) (only parsing).\nNotation b64_ne := (ExprDbl.b64_eq) (only parsing).\nNotation b64_lt := (ExprDbl.b64_eq) (only parsing).\nNotation b64_le := (ExprDbl.b64_eq) (only parsing).\nNotation b64_gt := (ExprDbl.b64_eq) (only parsing).\nNotation b64_ge := (ExprDbl.b64_eq) (only parsing).\n\nNotation b64_and := (ExprDbl.b64_and) (only parsing).\nNotation b64_or := (ExprDbl.b64_or) (only parsing).\n\n\nDefinition denote_ty t :=\n    match t with\n    | Nil => unit\n    | Dbl => e_double\n    | Str => e_string\n    end.\n\n\nInductive unary_denotation : ty -> Set :=\n| UnaryD (t t' : ty) (f : denote_ty t -> denote_ty t') :\n        unary_denotation t\n.\n\nDefinition double_unary t t' (f : e_double -> denote_ty t') :\n        option (unary_denotation t) :=\n    match t with\n    | Dbl => Some (UnaryD Dbl t' f)\n    | _ => None\n    end.\n\nDefinition denote_unary_op op t : option (unary_denotation t) :=\n    match op with\n    | NotAlg => double_unary t Dbl (fun x => b64_opp x)\n    | NotLog => double_unary t Dbl (fun x => if is_zero x then one else zero)\n    end.\n\n\nInductive binary_denotation : ty -> ty -> Set :=\n| BinaryD (t1 t2 t' : ty) (f : denote_ty t1 -> denote_ty t2 -> denote_ty t') :\n        binary_denotation t1 t2\n.\n\nDefinition double_binary t1 t2 t' (f : e_double -> e_double -> denote_ty t') :\n        option (binary_denotation t1 t2) :=\n    match t1, t2 with\n    | Dbl, Dbl => Some (BinaryD Dbl Dbl t' f)\n    | _, _ => None\n    end.\n\nDefinition denote_binary_op op t1 t2 : option (binary_denotation t1 t2) :=\n    match op with\n    | Add => match t1, t2 with\n        | Dbl, Dbl => Some (BinaryD Dbl Dbl Dbl (b64_plus mode_NE))\n        | Str, Str => Some (BinaryD Str Str Str append)\n        | _, _ => None\n        end\n    | Sub => double_binary t1 t2 Dbl (b64_minus mode_NE)\n    | Mul => double_binary t1 t2 Dbl (b64_mult mode_NE)\n    | Div => double_binary t1 t2 Dbl (b64_div mode_NE)\n    | Ge => double_binary t1 t2 Dbl b64_ge\n    | Gt => double_binary t1 t2 Dbl b64_gt\n    | Le => double_binary t1 t2 Dbl b64_le\n    | Lt => double_binary t1 t2 Dbl b64_lt\n    | Ne => match t1, t2 with\n        | Dbl, Dbl => Some (BinaryD Dbl Dbl Dbl b64_ne)\n        | Str, Str => Some (BinaryD Str Str Dbl\n                (fun a b => if string_dec a b then zero else one))\n        | _, _ => None\n        end\n    | Eq => match t1, t2 with\n        | Dbl, Dbl => Some (BinaryD Dbl Dbl Dbl b64_eq)\n        | Str, Str => Some (BinaryD Str Str Dbl\n                (fun a b => if string_dec a b then one else zero))\n        | _, _ => None\n        end\n    | AndLog => double_binary t1 t2 Dbl b64_and\n    | OrLog => double_binary t1 t2 Dbl b64_or\n    end.\n\n\n\nDefinition state_fn n A :=\n    (multi n e_double -> multi n e_string ->\n     multi n e_double * multi n e_string * A)%type.\n\nInductive denotation n :=\n| Denot (t : ty) (f : state_fn n (denote_ty t))\n.\nImplicit Arguments Denot [n].\n\nDefinition double_f {n} (x : option (denotation n))  :=\n    match x with\n    | Some (Denot t f) =>\n            match t as t_ return state_fn n (denote_ty t_) -> _ with\n            | Dbl => fun f => Some f\n            | _ => fun _ => None\n            end f\n    | None => None\n    end.\n\nDefinition string_f {n} (x : option (denotation n))  :=\n    match x with\n    | Some (Denot t f) =>\n            match t as t_ return state_fn n (denote_ty t_) -> _ with\n            | Str => fun f => Some f\n            | _ => fun _ => None\n            end f\n    | None => None\n    end.\n\nDefinition unpack_denot {n} (d : option (denotation n))\n        (f : forall (t : ty), state_fn n (denote_ty t) -> option (denotation n)) :\n        option (denotation n) :=\n    match d with\n    | Some (Denot t f') => f t f'\n    | None => None\n    end.\n\nDefinition pack_denot {n} t (f : state_fn n (denote_ty t)) := Some (@Denot n t f).\n\nDefinition unpack_unary {n} {t} (d : option (unary_denotation t))\n        (f : forall (t' : ty), (denote_ty t -> denote_ty t') -> option (denotation n)) :\n        option (denotation n).\ndestruct d as [ d | ]; [ | exact None ].\ndestruct d. destruct t'; eapply f; eassumption.\nDefined.\n\nDefinition unpack_binary {n} {t1 t2} (d : option (binary_denotation t1 t2))\n        (f : forall (t' : ty), (denote_ty t1 -> denote_ty t2 -> denote_ty t') ->\n            option (denotation n)) :\n        option (denotation n).\ndestruct d as [ d | ]; [ | exact None ].\ndestruct d. destruct t'; eapply f; eassumption.\nDefined.\n\nFixpoint denote' {n} (e : expr (e_double + e_string) n) : option (denotation n) :=\n    match e with\n    | EVar i => pack_denot Dbl (fun sd ss => (sd, ss, sd !! i))\n    | EXVar i => pack_denot Str (fun sd ss => (sd, ss, ss !! i))\n    | ELit (inl d) => pack_denot Dbl (fun sd ss => (sd, ss, d))\n    | ELit (inr s) => pack_denot Str (fun sd ss => (sd, ss, s))\n    | EUnary op xe =>\n            unpack_denot (denote' xe) (fun xt xf =>\n            unpack_unary (denote_unary_op op xt) (fun t' opf =>\n            pack_denot t'\n                (fun sd ss =>\n                    let '(sd', ss', x) := xf sd ss in\n                    (sd', ss', opf x))))\n    | EBinary op xe ye =>\n            unpack_denot (denote' xe) (fun xt xf =>\n            unpack_denot (denote' ye) (fun yt yf =>\n            unpack_binary (denote_binary_op op xt yt) (fun t' opf =>\n            pack_denot t'\n                (fun sd ss =>\n                    let '(sd', ss', x) := xf sd ss in\n                    let '(sd'', ss'', y) := yf sd' ss' in\n                    (sd'', ss'', opf x y)))))\n    | EVarary _ _ => None (* unsupported *)\n    | EAssign i xe =>\n            double_f (denote' xe) >>= fun xf =>\n            pack_denot Nil (fun sd ss =>\n                let '(sd', ss', x) := xf sd ss in\n                (multi_set sd' i x, ss', tt))\n    | EXAssign i xe =>\n            string_f (denote' xe) >>= fun xf =>\n            pack_denot Nil (fun sd ss =>\n                let '(sd', ss', x) := xf sd ss in\n                (sd', multi_set ss' i x, tt))\n    | ECond ce xe ye =>\n            double_f (denote' ce) >>= fun cf =>\n            unpack_denot (denote' xe) (fun xt xf =>\n            unpack_denot (denote' ye) (fun yt yf =>\n            if ty_eq_dec xt yt then\n                pack_denot xt\n                    ltac:(subst; refine (fun sd ss =>\n                        let '(sd', ss', c) := cf sd ss in\n                        if negb (is_zero c) then xf sd' ss' else yf sd' ss'))\n            else\n                None))\n    | ESeq xe ye =>\n            unpack_denot (denote' xe) (fun xt xf =>\n            unpack_denot (denote' ye) (fun yt yf =>\n            match xt, yt with\n            | Nil, _ =>\n                    pack_denot yt\n                        (fun sd ss =>\n                            let '(sd', ss', _) := xf sd ss in\n                            let '(sd'', ss'', y) := yf sd' ss' in\n                            (sd'', ss'', y))\n            | _, Nil =>\n                    pack_denot xt\n                        (fun sd ss =>\n                            let '(sd', ss', x) := xf sd ss in\n                            let '(sd'', ss'', _) := yf sd' ss' in\n                            (sd'', ss'', x))\n            | _, _ => None (* both sides evaluate to results *)\n            end))\n    end.\n\nDefinition denote {n} (e : expr (e_double + e_string) n) :\n    option (state_fn n (e_double + e_string)) :=\n    match denote' e with\n    | Some (Denot Dbl f) => Some (fun sd ss =>\n            let '(sd', ss', x) := f sd ss in\n            (sd', ss', inl x))\n    | Some (Denot Str f) => Some (fun sd ss =>\n            let '(sd', ss', x) := f sd ss in\n            (sd', ss', inr x))\n    | _ => None\n    end.\n\n\nLemma denote_unary_op_ok : forall op t t',\n    unary_op_type op t = Some t' ->\n    exists f, denote_unary_op op t = Some (UnaryD t t' f).\ndestruct op; simpl in *; try discriminate;\ndestruct t; simpl in *; try discriminate;\nintros0 Hty; fancy_injr <- Hty; eauto.\nQed.\n\nLemma denote_binary_op_ok : forall op t1 t2 t',\n    binary_op_type op t1 t2 = Some t' ->\n    exists f, denote_binary_op op t1 t2 = Some (BinaryD t1 t2 t' f).\ndestruct op; simpl in *; try discriminate;\ndestruct t1; simpl in *; try discriminate;\ndestruct t2; simpl in *; try discriminate;\nintros0 Hty; compute in Hty; fancy_injr <- Hty; eauto.\nQed.\n\nLemma denote_valid_unary_op_rev : forall op t t' f,\n    denote_unary_op op t = Some (UnaryD t t' f) ->\n    unary_op_type op t = Some t'.\ndestruct op; simpl in *; try discriminate;\ndestruct t; simpl in *; try discriminate;\nintros0 Hd; inversion Hd; eauto.\nQed.\n\nLemma denote_valid_binary_op_rev : forall op t1 t2 t' f,\n    denote_binary_op op t1 t2 = Some (BinaryD t1 t2 t' f) ->\n    binary_op_type op t1 t2 = Some t'.\ndestruct op; simpl in *; try discriminate;\ndestruct t1; simpl in *; try discriminate;\ndestruct t2; simpl in *; try discriminate;\nintros0 Hd; inversion Hd; eauto.\nQed.\n\nTheorem well_typed_denote' : forall n (e : expr (e_double + e_string) n) t,\n    well_typed t e ->\n    exists f, denote' e = Some (Denot t f).\nintro n.\ninduction e; intros0 Hwt; try invc Hwt.\n\n- compute [denote denote' pack_denot]. eauto.\n- compute [denote denote' pack_denot]. eauto.\n- compute [denote denote' pack_denot]. eauto.\n- compute [denote denote' pack_denot]. eauto.\n\n- (* EUnary *) simpl.\n  forward eapply IHe as [ef Hef]; eauto. rewrite Hef. simpl.\n  forward eapply denote_unary_op_ok as [opf Hopf]; eauto. rewrite Hopf. simpl.\n  destruct t; unfold pack_denot; eauto.\n\n- (* EBinary *) simpl.\n  forward eapply IHe1 as [e1f He1f]; eauto. rewrite He1f. simpl.\n  forward eapply IHe2 as [e2f He2f]; eauto. rewrite He2f. simpl.\n  forward eapply denote_binary_op_ok as [opf Hopf]; eauto. rewrite Hopf. simpl.\n  destruct t; unfold pack_denot; eauto.\n\n- (* EVarary *) simpl. destruct v; try discriminate.\n\n- (* EAssign *) simpl.\n  forward eapply IHe as [ef Hef]; eauto. rewrite Hef. simpl.\n  unfold pack_denot; eauto.\n\n- (* EXAssign *) simpl.\n  forward eapply IHe as [ef Hef]; eauto. rewrite Hef. simpl.\n  unfold pack_denot; eauto.\n\n- (* ECond *) simpl.\n  forward eapply IHe1 as [e1f He1f]; eauto. rewrite He1f. simpl.\n  forward eapply IHe2 as [e2f He2f]; eauto. rewrite He2f. simpl.\n  forward eapply IHe3 as [e3f He3f]; eauto. rewrite He3f. simpl.\n  break_match; try congruence.\n  unfold pack_denot; eauto.\n\n- (* ESeq *) simpl.\n  forward eapply IHe1 as [e1f He1f]; eauto. rewrite He1f. simpl.\n  forward eapply IHe2 as [e2f He2f]; eauto. rewrite He2f. simpl.\n  destruct t1, t2; (on (seq_result_type _ _ = _), fun H =>\n        try discriminate H; simpl in H; fancy_injr <- H);\n  unfold pack_denot; eauto.\n\nQed.\n\nTheorem well_typed_denote : forall n (e : expr (e_double + e_string) n),\n    (well_typed Dbl e \\/ well_typed Str e) -> exists f, denote e = Some f.\nintros0 Hwt. destruct Hwt;\nforward eapply well_typed_denote' as [f Hf]; eauto;\n    unfold denote; rewrite Hf; eauto.\nQed.\n\nDefinition denote_total n (e : expr (e_double + e_string) n) :\n    (well_typed Dbl e \\/ well_typed Str e) ->\n    { f | denote e = Some f }.\nintros0 Hwt.\nforward eapply well_typed_denote; eauto.\ndestruct (denote _) eqn:?.\n- eauto.\n- exfalso. break_exists. discriminate.\nDefined.\n\n\nSection typecheck.\nOpen Scope string.\n\nDefinition ty_name t :=\n    match t with\n    | Nil => \"Nil\"\n    | Dbl => \"Dbl\"\n    | Str => \"Str\"\n    end.\n\nLocal Definition concat xs := fold_left append xs \"\".\n\nLocal Ltac require_type t t' loc :=\n    destruct t eqn:?;\n    match goal with\n    | [ H : t = t' |- _ ] => clear H\n    | [ |- _ ] =>\n            (* We're in the case where `t` is something other than `t'` *)\n            right; exact (concat [\"bad type in \"; loc; \": got \"; ty_name t;\n                \" but expected \"; ty_name t' ])\n    end.\n\nDefinition typecheck_expr' n (e : expr (e_double + e_string) n) :\n    { t | well_typed t e } + string.\ninduction e using expr_rect_mut with (Pl := fun _ => unit).\n\n- left. eexists. constructor.\n- left. eexists. constructor.\n- destruct x.\n  + left. eexists. constructor.\n  + left. eexists. constructor.\n\n- destruct IHe as [[t ?]| ? ]; [ | right; assumption ].\n  destruct (unary_op_type op t) as [ t' | ] eqn:?;\n      [ | right; exact (concat [\"unary op \"; unary_op_name op;\n              \" can't apply to (\"; ty_name t; \")\"]) ].\n  left. exists t'. econstructor; eassumption.\n\n- destruct IHe1 as [[t1 ?]| ? ]; [ | right; assumption ].\n  destruct IHe2 as [[t2 ?]| ? ]; [ | right; assumption ].\n  destruct (binary_op_type op t1 t2) as [ t' | ] eqn:?;\n      [ | right; exact (concat [\"unary op \"; binary_op_name op;\n              \" can't apply to (\"; ty_name t1; \", \"; ty_name t2; \")\"]) ].\n  left. exists t'. econstructor; eassumption.\n\n- right; exact \"varary ops are not yet supported\".\n\n- destruct IHe as [[t ?] | ?]; [ require_type t Dbl \"rhs of assign\" | right; assumption ].\n  left. eexists. constructor. assumption.\n\n- destruct IHe as [[t ?] | ?]; [ require_type t Str \"rhs of xassign\" | right; assumption ].\n  left. eexists. constructor. assumption.\n\n- destruct IHe1 as [[t1 ?] | ?]; [ require_type t1 Dbl \"condition of cond\" | right; assumption ].\n  destruct IHe2 as [[t2 ?] | ?]; [ | right; assumption ].\n  destruct IHe3 as [[t3 ?] | ?]; [ | right; assumption ].\n  destruct (ty_eq_dec t2 t3).\n  + left. eexists. constructor; eauto. congruence.\n  + right. exact (concat [\"conditional branches have mismatched types: \";\n              ty_name t1; \" <> \"; ty_name t2]).\n\n- destruct IHe1 as [[t1 ?] | ?]; [ | right; assumption ].\n  destruct IHe2 as [[t2 ?] | ?]; [ | right; assumption ].\n  destruct (seq_result_type t1 t2) as [ t' | ] eqn:?;\n          [ | right; exact \"multiple result values in seq\" ].\n  left. eexists. econstructor; eauto.\n\n- exact tt.\n- exact tt.\n\nQed.\n\nDefinition typecheck_expr n (e : expr (e_double + e_string) n) :\n    (well_typed Dbl e \\/ well_typed Str e) + string.\ndestruct (typecheck_expr' n e) as [[t ?] | ?].\n- destruct t.\n  + right. exact \"no subexpression produced a value\".\n  + left. left. assumption.\n  + left. right. assumption.\n- right. assumption.\nQed.\n\nEnd typecheck.\n", "meta": {"author": "HazardousPeach", "repo": "neutrons-bench", "sha": "447b1066142ceee607ba595d04c43c03089ce6f4", "save_path": "github-repos/coq/HazardousPeach-neutrons-bench", "path": "github-repos/coq/HazardousPeach-neutrons-bench/neutrons-bench-447b1066142ceee607ba595d04c43c03089ce6f4/semantics/v1/ExprDblStr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.20525781374573468}}
{"text": "Require Import Verdi.GhostSimulations.\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.RefinementCommonDefinitions.\n\nRequire Import VerdiRaft.PrevLogCandidateEntriesTermInterface.\nRequire Import VerdiRaft.VotesCorrectInterface.\nRequire Import VerdiRaft.CroniesCorrectInterface.\nRequire Import VerdiRaft.LeaderSublogInterface.\n\nRequire Import VerdiRaft.PrevLogLeaderSublogInterface.\n\nHint Extern 4 (@BaseParams) => apply base_params : typeclass_instances.\nHint Extern 4 (@MultiParams _) => apply multi_params : typeclass_instances.\nHint Extern 4 (@FailureParams _ _) => apply failure_params : typeclass_instances.\n\n\nSection PrevLogLeaderSublogProof.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n\n  Context {vci : votes_correct_interface}.\n  Context {cci : cronies_correct_interface}.\n\n  Context {lsi : leader_sublog_interface}.\n\n  Context {plceti : prevLog_candidateEntriesTerm_interface}.\n\n  Lemma prevLog_leader_sublog_init :\n   raft_net_invariant_init prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_init, prevLog_leader_sublog.\n    simpl. intuition.\n  Qed.\n\n  Lemma handleClientRequest_log_In :\n    forall h st client id c out st' ps e,\n      handleClientRequest h st client id c = (out, st', ps) ->\n      In e (log st) -> In e (log st').\n  Proof using. \n    intros.\n    find_apply_lem_hyp handleClientRequest_log.\n    intuition.\n    - find_rewrite. auto.\n    - break_exists. intuition. find_rewrite. intuition.\n  Qed.\n\n  Lemma prevLog_leader_sublog_client_request :\n    raft_net_invariant_client_request prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_client_request, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - break_if; eauto.\n      find_copy_apply_lem_hyp handleClientRequest_type. break_and.\n      repeat find_rewrite.\n      eapply_prop_hyp In In; eauto.\n      break_exists_exists. intuition.\n      eauto using handleClientRequest_log_In.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      exfalso. eapply handleClientRequest_no_append_entries; eauto.\n      subst. simpl in *. find_rewrite. eauto 10.\n  Qed.\n\n  Lemma prevLog_leader_sublog_timeout :\n    raft_net_invariant_timeout prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_timeout, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - break_if; eauto.\n      find_copy_apply_lem_hyp handleTimeout_type.\n      intuition; repeat find_rewrite; try discriminate.\n      eapply_prop_hyp In In; eauto.\n      break_exists_exists. intuition.\n      erewrite handleTimeout_log_same by eauto.\n      eauto.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      exfalso. subst. simpl in *.\n      eapply handleTimeout_packets; eauto.\n      find_rewrite. eauto 10.\n  Qed.\n\n  Lemma handleAppendEntries_type_log :\n    forall h st t n pli plt es ci st' ps,\n      handleAppendEntries h st t n pli plt es ci = (st', ps) ->\n      type st' = Follower \\/ (type st' = type st /\\ log st' = log st /\\ currentTerm st' = currentTerm st).\n  Proof using. \n    unfold handleAppendEntries.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto.\n  Qed.\n\n  Lemma prevLog_leader_sublog_append_entries :\n    raft_net_invariant_append_entries prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_append_entries, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n      find_rewrite. break_if; eauto.\n      find_copy_apply_lem_hyp handleAppendEntries_type_log.\n      intuition.\n      + congruence.\n      + repeat find_rewrite.\n        eapply_prop_hyp In In; eauto.\n    - find_apply_lem_hyp handleAppendEntries_not_append_entries.\n      simpl in *. subst. exfalso. eauto 10.\n  Qed.\n\n  Lemma prevLog_leader_sublog_append_entries_reply :\n    raft_net_invariant_append_entries_reply prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_append_entries_reply, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n      find_rewrite. break_if; eauto.\n      find_copy_apply_lem_hyp handleAppendEntriesReply_log.\n      find_rewrite.\n      find_copy_apply_lem_hyp handleAppendEntriesReply_type.\n      intuition; repeat find_rewrite; try discriminate.\n      eauto.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and.\n      exfalso. subst. simpl in *.\n      find_apply_lem_hyp handleAppendEntriesReply_packets.\n      subst. simpl in *. intuition.\n  Qed.\n\n  Lemma prevLog_leader_sublog_request_vote :\n    raft_net_invariant_request_vote prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_request_vote, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n      find_rewrite. break_if; eauto.\n      find_copy_apply_lem_hyp handleRequestVote_log.\n      find_copy_apply_lem_hyp handleRequestVote_type.\n      intuition; repeat find_rewrite; try discriminate.\n      eauto.\n    - find_apply_lem_hyp handleRequestVote_no_append_entries.\n      simpl in *. subst. exfalso. eauto 10.\n  Qed.\n\n\n  Definition candidateEntriesTerm_lowered (net : network) t p : Prop :=\n    In p (nwPackets net) ->\n    pBody p = RequestVoteReply t true ->\n    currentTerm (nwState net (pDst p)) = t ->\n    wonElection (dedup name_eq_dec (pSrc p :: votesReceived (nwState net (pDst p)))) = true ->\n    type (nwState net (pDst p)) <> Candidate.\n\n  Lemma deghost_packet_exists :\n    forall net p,\n      In p (nwPackets (deghost net)) ->\n      exists (q : packet (params := raft_refined_multi_params (raft_params := raft_params))),\n        In q (nwPackets net) /\\ p = deghost_packet q.\n  Proof using. \n    unfold deghost.\n    simpl.\n    intros.\n    do_in_map.\n    eauto.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_lowered' :\n    forall net,\n      prevLog_candidateEntriesTerm net ->\n      votes_correct net ->\n      cronies_correct net ->\n      forall p p' t leaderId prevLogIndex prevLogTerm entries leaderCommit,\n        In p (nwPackets (deghost net)) ->\n        pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm\n                                entries leaderCommit ->\n        0 < prevLogTerm ->\n        candidateEntriesTerm_lowered (deghost net) prevLogTerm p'.\n  Proof using rri. \n    unfold candidateEntriesTerm_lowered,\n           cronies_correct, votes_correct.\n    intros. break_and.\n    rewrite deghost_spec.\n\n    find_apply_lem_hyp deghost_packet_exists.\n    find_apply_lem_hyp deghost_packet_exists.\n    break_exists.  break_and. subst.\n    eapply_prop_hyp votes_nw pBody. concludes.\n    eapply_prop_hyp prevLog_candidateEntriesTerm pBody; auto.\n\n    concludes.\n    unfold candidateEntriesTerm in *. break_exists. break_and.\n\n    match goal with\n    | H : wonElection _ = _ |- _ =>\n      eapply wonElection_one_in_common in H; [|clear H; eauto]\n    end.\n    break_exists. break_and.\n    repeat match goal with\n           | [ H : _ |- _ ] => rewrite deghost_spec in H\n           end.\n\n    simpl in *.\n    break_or_hyp.\n    - apply_prop_hyp cronies_votes In.\n      assert (pDst x = x1) by (eapply_prop one_vote_per_term; eauto).\n      subst. auto.\n    - intro.\n      assert (pDst x = x1).\n      { eapply_prop one_vote_per_term;\n        eapply_prop cronies_votes.\n        - eapply_prop votes_received_cronies; eauto.\n        - repeat find_reverse_rewrite. auto.\n      }\n      subst.\n      concludes. contradiction.\n  Qed.\n\n  Lemma prevLog_candidateEntriesTerm_lowered :\n    forall net,\n      raft_intermediate_reachable net ->\n      forall p p' t leaderId prevLogIndex prevLogTerm entries leaderCommit,\n        In p (nwPackets net) ->\n        pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm\n                                entries leaderCommit ->\n        0 < prevLogTerm ->\n        candidateEntriesTerm_lowered net prevLogTerm p'.\n  Proof using plceti cci vci rri. \n    intros net H.\n    pattern net.\n    apply lower_prop; auto.\n    clear H net.\n    intros.\n\n    eapply prevLog_candidateEntriesTerm_lowered';\n      eauto using prevLog_candidateEntriesTerm_invariant, votes_correct_invariant,\n      cronies_correct_invariant.\n  Qed.\n\n  Lemma handleRequestVoteReply_type_term_won :\n    forall h st src t v st',\n      handleRequestVoteReply h st src t v = st' ->\n      type st' = type st \\/\n      type st' = Follower \\/\n      (v = true /\\\n       wonElection (dedup name_eq_dec (src :: votesReceived st)) = true /\\\n       currentTerm st' = t).\n  Proof using. \n    unfold handleRequestVoteReply.\n    intros.\n    repeat break_match; repeat find_inversion; subst; simpl in *; auto; do_bool; intuition.\n  Qed.\n\n  Lemma prevLog_leader_sublog_request_vote_reply :\n    raft_net_invariant_request_vote_reply prevLog_leader_sublog.\n  Proof using plceti cci vci rri. \n    unfold raft_net_invariant_request_vote_reply, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp.\n    find_eapply_lem_hyp app_cons_in_rest; [|solve[eauto]].\n    find_rewrite. break_if; eauto.\n    find_copy_apply_lem_hyp handleRequestVoteReply_type.\n    find_copy_apply_lem_hyp handleRequestVoteReply_log.\n    intuition; repeat find_rewrite.\n    - eauto.\n    - discriminate.\n    - exfalso.\n      find_apply_lem_hyp handleRequestVoteReply_type_term_won.\n      intuition; try congruence.\n      eapply prevLog_candidateEntriesTerm_lowered with (p := p0) ; eauto.\n      + congruence.\n      + congruence.\n  Qed.\n\n  Lemma prevLog_leader_sublog_do_leader :\n    raft_net_invariant_do_leader prevLog_leader_sublog.\n  Proof using lsi. \n    unfold raft_net_invariant_do_leader, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - break_if; eauto.\n      find_copy_apply_lem_hyp doLeader_type. break_and.\n      find_copy_apply_lem_hyp doLeader_log.\n      repeat find_rewrite. eauto.\n    - find_apply_lem_hyp in_map_iff. break_exists. break_and. subst.\n      simpl in *.\n      find_copy_eapply_lem_hyp doLeader_messages; eauto.\n      intuition.\n      + omega.\n      + break_exists. break_and. subst.\n        exists x0. find_apply_lem_hyp findAtIndex_elim. intuition.\n        break_if.\n        * congruence.\n        * pose proof (leader_sublog_invariant_invariant _ ltac:(eauto)).\n          unfold leader_sublog_invariant, leader_sublog_host_invariant in *. break_and.\n          eauto.\n  Qed.\n\n  Lemma prevLog_leader_sublog_do_generic_server :\n    raft_net_invariant_do_generic_server prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_do_generic_server, prevLog_leader_sublog.\n    intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_apply_hyp_hyp. break_or_hyp.\n    - break_if; eauto.\n      find_copy_eapply_lem_hyp doGenericServer_type. break_and.\n      find_copy_eapply_lem_hyp doGenericServer_log.\n      repeat find_rewrite.\n      eauto.\n    - find_copy_eapply_lem_hyp doGenericServer_packets.\n      subst. simpl in *. intuition.\n  Qed.\n\n  Lemma prevLog_leader_sublog_state_same_packet_subset :\n    raft_net_invariant_state_same_packet_subset prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_state_same_packet_subset, prevLog_leader_sublog.\n    intros.\n    find_apply_hyp_hyp.\n    repeat find_reverse_higher_order_rewrite.\n    eauto.\n  Qed.\n\n  Lemma prevLog_leader_sublog_reboot :\n    raft_net_invariant_reboot prevLog_leader_sublog.\n  Proof using. \n    unfold raft_net_invariant_reboot, prevLog_leader_sublog, reboot.\n    intros.  subst. simpl in *.\n    repeat find_reverse_higher_order_rewrite.\n\n    match goal with\n    | [ H : context [In _ _], H' : In _ _ |- _ ] =>\n      eapply H with (leader0 := leader) in H'; eauto\n    end.\n    - break_exists_exists. intuition.\n      repeat find_higher_order_rewrite.\n      break_if; subst; simpl in *; auto.\n    - repeat find_higher_order_rewrite.\n      break_if; subst; simpl in *; auto.\n      discriminate.\n    - repeat find_higher_order_rewrite.\n      break_if; subst; simpl in *; auto.\n  Qed.\n\n  Lemma prevLog_leader_sublog_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      prevLog_leader_sublog net.\n  Proof using plceti lsi cci vci rri. \n    intros.\n    apply raft_net_invariant; auto.\n    - apply prevLog_leader_sublog_init.\n    - apply prevLog_leader_sublog_client_request.\n    - apply prevLog_leader_sublog_timeout.\n    - apply prevLog_leader_sublog_append_entries.\n    - apply prevLog_leader_sublog_append_entries_reply.\n    - apply prevLog_leader_sublog_request_vote.\n    - apply prevLog_leader_sublog_request_vote_reply.\n    - apply prevLog_leader_sublog_do_leader.\n    - apply prevLog_leader_sublog_do_generic_server.\n    - apply prevLog_leader_sublog_state_same_packet_subset.\n    - apply prevLog_leader_sublog_reboot.\n  Qed.\n\n  Instance pllsi : prevLog_leader_sublog_interface.\n  Proof.\n    constructor.\n    apply prevLog_leader_sublog_invariant.\n  Qed.\nEnd PrevLogLeaderSublogProof.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/verdi-raft/raft-proofs/PrevLogLeaderSublogProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.34158249943831703, "lm_q1q2_score": 0.20501383500427425}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import bedrock2.Array.\nRequire Import bedrock2.Map.Separation.\nRequire Import bedrock2.Map.SeparationLogic.\nRequire Import bedrock2.ProgramLogic.\nRequire Import bedrock2.Scalars.\nRequire Import bedrock2.Semantics.\nRequire Import bedrock2.Syntax.\nRequire Import bedrock2.WeakestPrecondition.\nRequire Import bedrock2.WeakestPreconditionProperties.\nRequire Import coqutil.Word.Interface.\nRequire Import coqutil.Word.Properties.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Map.Properties.\nRequire Import coqutil.Tactics.Tactics.\nRequire Import Cava.Util.List.\nRequire Import Cava.Util.Tactics.\nRequire Import Bedrock2Experiments.StateMachineSemantics.\nRequire Import Bedrock2Experiments.StateMachineProperties.\nRequire Import Bedrock2Experiments.Tactics.\nRequire Import Bedrock2Experiments.Word.\nRequire Import Bedrock2Experiments.WordProperties.\nRequire Import Bedrock2Experiments.Aes.Aes.\nRequire Import Bedrock2Experiments.Aes.AesExample.\nRequire Import Bedrock2Experiments.Aes.AesSemantics.\nRequire Import Bedrock2Experiments.Aes.AesProperties.\nRequire Import Bedrock2Experiments.Aes.Constants.\nImport Syntax.Coercions List.ListNotations.\nLocal Open Scope Z_scope.\n\nSection Proofs.\n  Context {word: word.word 32} {mem: map.map word Byte.byte}\n          {word_ok: word.ok word} {mem_ok: map.ok mem}\n          {ASpec: AesSpec}\n          {consts : aes_constants Z} {timing : timing}\n          {consts_ok : aes_constants_ok consts}.\n  Existing Instance constant_literals.\n\n  Global Instance spec_of_aes_encrypt : spec_of \"b2_aes_encrypt\" :=\n    fun function_env =>\n      forall (tr : trace) (m : mem) R\n        (plaintext_ptr key_ptr iv_ptr ciphertext_ptr : word)\n        (* values of input arrays *)\n        (plaintext0 plaintext1 plaintext2 plaintext3\n                    key0 key1 key2 key3 key4 key5 key6 key7\n                    iv0 iv1 iv2 iv3 : word)\n        (* initial values of output array (used only for determining length) *)\n        (ciphertext_arr : list word),\n        let plaintext_arr := [plaintext0; plaintext1; plaintext2; plaintext3] in\n        let key_arr := [key0; key1; key2; key3; key4; key5; key6; key7] in\n        let iv_arr := [iv0; iv1; iv2; iv3] in\n        (* arrays are in memory *)\n        (array scalar32 (word.of_Z 4) plaintext_ptr plaintext_arr\n         * array scalar32 (word.of_Z 4) key_ptr key_arr\n         * array scalar32 (word.of_Z 4) iv_ptr iv_arr\n         * array scalar32 (word.of_Z 4) ciphertext_ptr ciphertext_arr\n         * R)%sep m ->\n        (* output array has the right length *)\n        length ciphertext_arr = 4%nat ->\n        (* circuit must start in the UNINITIALIZED state *)\n        execution tr UNINITIALIZED ->\n        (* determine expected output using aes_spec *)\n        let is_decrypt := false in\n        let expected_output :=\n            aes_spec\n              is_decrypt\n              (key0, key1, key2, key3, key4, key5, key6, key7)\n              (iv0, iv1, iv2, iv3)\n              (plaintext0, plaintext1, plaintext2, plaintext3) in\n        call function_env aes_encrypt tr m\n             [plaintext_ptr; key_ptr; iv_ptr; ciphertext_ptr]\n             (fun tr' m' rets =>\n                let '(out0, out1, out2, out3) := expected_output in\n                (* the circuit is back in the IDLE state *)\n                (exists data, execution tr' (IDLE data))\n                (* ...and the input arrays are unchanged, while the ciphertext\n                     array now holds the values from the expected output *)\n                /\\ (array scalar32 (word.of_Z 4) plaintext_ptr plaintext_arr\n                   * array scalar32 (word.of_Z 4) iv_ptr iv_arr\n                   * array scalar32 (word.of_Z 4) key_ptr key_arr\n                   * array scalar32 (word.of_Z 4) ciphertext_ptr\n                           [out0; out1; out2; out3] * R)%sep m'\n                (* ...and there are no return values *)\n                /\\ rets = []).\n\n  Local Ltac precondition_hammer :=\n    lazymatch goal with\n    | |- enum_member ?e _ => cbv [enum_member]; try apply in_map; cbn [In]; tauto\n    | |- boolean _ => cbv [boolean]; tauto\n    | |- execution _ _ => eassumption\n    | |- output_matches_state _ _ => reflexivity\n    | H : sep _ _ ?m |- _ ?m => ecancel_assumption\n    | _ => try reflexivity\n    end.\n\n  Lemma aes_encrypt_correct :\n    program_logic_goal_for_function! aes_encrypt.\n  Proof.\n    (* initial processing *)\n    repeat straightline.\n    destruct_lists_by_length.\n\n    (* call aes_init *)\n    straightline_call; precondition_hammer; [ ].\n    repeat straightline.\n\n    (* call aes_key_put *)\n    straightline_call; precondition_hammer; [ | ].\n    { (* prove key array has the correct length *)\n      pose proof (enum_unique aes_key_len) as Hunique.\n      simplify_unique_words_in Hunique.\n      cbn [kAes256 kAes128 kAes192].\n      repeat destruct_one_match; subst; try congruence; [ ].\n      reflexivity. }\n\n    repeat straightline.\n    lazymatch goal with\n    | H : execution ?t _ |- context [?t] =>\n      cbn in H\n    end.\n\n    (* call aes_iv_put *)\n    straightline_call; precondition_hammer; [ ].\n    repeat straightline.\n    lazymatch goal with\n    | H : execution ?t _ |- context [?t] =>\n      cbn in H\n    end.\n\n    (* call aes_data_put_wait *)\n    straightline_call; precondition_hammer; [ ].\n    repeat straightline.\n    lazymatch goal with\n    | H : execution ?t _ |- context [?t] =>\n      cbn in H\n    end.\n    repeat lazymatch goal with\n           | H : context [match ?p with pair _ _ => _ end] |- _ =>\n             rewrite (surjective_pairing p) in H\n           end.\n\n    (* call aes_data_get_wait *)\n    straightline_call; precondition_hammer; [ ].\n    repeat straightline.\n\n    (* done; prove postcondition *)\n    repeat destruct_pair_let.\n    ssplit; eauto; [ ].\n    repeat lazymatch goal with H : execution _ _ |- _ => clear H end.\n    cbn [busy_exp_output data_out0 data_out1 data_out2 data_out3] in *.\n    lazymatch goal with\n    | Hsep : sep _ _ ?m |- sep _ _ ?m =>\n      lazymatch type of Hsep with\n        context [aes_spec ?op ?keys ?iv ?plaintext] =>\n        replace (aes_spec op keys iv plaintext)\n        with expected_output in Hsep\n      end\n    end; [ ecancel_assumption | ].\n    subst_lets. f_equal; [ ].\n    lazymatch goal with\n    | H : ctrl_operation _ = _ |- _ =>\n      cbv [ctrl_operation] in H;\n        cbn [AES_CTRL_OPERATION] in H;\n        rewrite H\n    end.\n    rewrite word.unsigned_eqb.\n    rewrite kAesEnc_eq. push_unsigned.\n    cbn [Z.eqb negb]. reflexivity.\n  Qed.\nEnd Proofs.\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/firmware/Aes/AesExampleProperties.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602051, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.20501383184416838}}
{"text": "(*\n * Copyright (c) 2022 BedRock Systems, Inc.\n * This software is distributed under the terms of the BedRock Open-Source License.\n * See the LICENSE-BedRock file in the repository root for details.\n *)\n\n(** [object_repr.v] contains bundled definitions and utilities which are useful\n    when operating on (or reasoning about) the \"object representation\" of a C++\n    object (cf. <https://eel.is/c++draft/basic.types.general#4>). In BRiCk,\n    [rawR]/[rawsR] - which are wrappers around [Vraw] [val]ues and lists of them,\n    respectively - are used to refer to and manipulate these \"object representations\".\n *)\nRequire Import iris.proofmode.proofmode.\nRequire Import bedrock.prelude.base.\n\nRequire Import bedrock.lang.bi.big_op.\nRequire Import bedrock.lang.cpp.semantics.\nFrom bedrock.lang.cpp.logic Require Import arr pred heap_pred layout raw.\n\nSection Utilities.\n  Context `{Σ : cpp_logic} {σ : genv}.\n\n  #[local]\n  Lemma big_sepL_shift_aux_N {PROP : bi} {p : ptr} {ty : type} (P : ptr -> PROP) (j : N) {n m : N} :\n    (j <= n)%N ->\n        ([∗list] i ∈ seqN n m, P (p .[ ty ! Z.of_N i ]))\n    -|- ([∗list] i ∈ seqN j m, P (p .[ ty ! Z.of_N (n - j) ] .[ty ! Z.of_N i ])).\n  Proof.\n    setoid_rewrite o_sub_sub.\n    intros Hsz.\n    rewrite {Hsz} (big_sepL_seqN_shift _ _ Hsz).\n    f_equiv => _ i.\n    by rewrite N2Z.inj_add.\n  Qed.\n\n  #[local]\n  Lemma big_sepL_shift_aux_nat {PROP : bi} {p : ptr} {ty : type} (P : ptr -> PROP) (j : nat) {n m : nat}  :\n    (j <= n)%nat ->\n        ([∗list] i ∈ seq n m, P (p .[ ty ! Z.of_nat i ]))\n    -|- ([∗list] i ∈ seq j m, P (p .[ ty ! Z.of_nat (n - j) ] .[ty ! Z.of_nat i ])).\n  Proof.\n    intros Hsz.\n    setoid_rewrite o_sub_sub.\n    rewrite {Hsz} (big_sepL_seq_shift _ _ Hsz).\n    f_equiv => _ i.\n    by rewrite Nat2Z.inj_add.\n  Qed.\n\n  Lemma big_sepL_shift_N {PROP : bi} (P : ptr -> PROP) (n m : N) :\n    forall (p : ptr) (ty : type),\n          ([∗list] i ∈ seqN n m, P (p .[ ty ! Z.of_N i ]))\n      -|- ([∗list] i ∈ seqN 0 m, P (p .[ ty ! Z.of_N n ] .[ty ! Z.of_N i ])).\n  Proof.\n    intros p ty.\n    rewrite (big_sepL_shift_aux_N P 0 ltac:(lia)).\n    f_equiv=> _ i; by rewrite N.sub_0_r.\n  Qed.\n\n  Lemma big_sepL_shift_nat {PROP : bi} (P : ptr -> PROP) (n m : nat) :\n    forall (p : ptr) (ty : type),\n          ([∗list] i ∈ seq n m, P (p .[ ty ! Z.of_nat i ]))\n      -|- ([∗list] i ∈ seq 0 m, P (p .[ ty ! Z.of_nat n ] .[ty ! Z.of_nat i ])).\n  Proof.\n    intros p ty.\n    rewrite (big_sepL_shift_aux_nat P 0 ltac:(lia)).\n    f_equiv=> _ i; by rewrite Nat.sub_0_r.\n  Qed.\n\n  Lemma big_sepL_type_ptr_shift (n m : N) (p : ptr) (ty : type) :\n          ([∗list] i ∈ seqN n m, type_ptr ty (p .[ ty ! Z.of_N i ]))\n      -|- ([∗list] i ∈ seqN 0 m, type_ptr ty (p .[ ty ! Z.of_N n ] .[ty ! Z.of_N i ] )).\n  Proof. by apply big_sepL_shift_N. Qed.\n\n  Lemma big_sepL_type_ptr_shift' (n m : nat) (p : ptr) (ty : type) :\n          ([∗list] i ∈ seq n m, type_ptr ty (p .[ ty ! Z.of_nat i ]))\n      -|- ([∗list] i ∈ seq 0 m, type_ptr ty (p .[ ty ! Z.of_nat n ] .[ty ! Z.of_nat i ] )).\n  Proof. by apply big_sepL_shift_nat. Qed.\nEnd Utilities.\n\nSection rawsR_transport.\n  Context `{Σ : cpp_logic} {σ : genv}.\n\n  Lemma _at_rawsR_ptr_congP_transport (p1 p2 : ptr) (q : cQp.t) (rs : list raw_byte) :\n        ptr_congP σ p1 p2 ** ([∗list] i ∈ seqN 0 (lengthN rs), type_ptr Tu8 (p2 .[ Tu8 ! Z.of_N i ]))\n    |-- p1 |-> rawsR q rs -* p2 |-> rawsR q rs.\n  Proof.\n    generalize dependent p2; generalize dependent p1; induction rs;\n      iIntros (p1 p2) \"[#congP tptrs]\"; iAssert (ptr_congP σ p1 p2) as \"(% & #tptr1 & #tptr2)\"=> //.\n    - rewrite /rawsR !arrayR_nil !_at_sep !_at_only_provable !_at_validR.\n      iIntros \"[_ %]\"; iFrame \"%\"; iApply (type_ptr_valid with \"tptr2\").\n    - rewrite /rawsR !arrayR_cons !_at_sep !_at_type_ptrR !_at_offsetR; fold (rawsR q rs).\n      iIntros \"[_ [raw raws]]\"; iFrame \"#\"; iSplitL \"raw\".\n      + iApply (_at_rawR_ptr_congP_transport with \"congP\"); iFrame \"∗\".\n      + destruct rs.\n        * rewrite /rawsR !arrayR_nil !_at_sep !_at_only_provable !_at_validR.\n          iDestruct \"raws\" as \"[#valid %]\"; iFrame \"%\".\n          iApply type_ptr_valid_plus_one; iFrame \"#\".\n        * specialize (IHrs (p1 .[ Tu8 ! 1 ]) (p2 .[ Tu8 ! 1 ])).\n\n          iDestruct (observe (type_ptr Tu8 (p1 .[ Tu8 ! 1 ])) with \"raws\") as \"#tptr1'\". 1: {\n            rewrite /rawsR arrayR_cons; apply: _.\n          }\n\n          iDestruct (observe (type_ptr Tu8 (p2 .[ Tu8 ! 1 ])) with \"tptrs\") as \"#tptr2'\". 1: {\n            rewrite !lengthN_cons !N.add_1_r !seqN_S_start/=; apply: _.\n          }\n\n          rewrite lengthN_cons N.add_1_r seqN_S_start/=.\n          rewrite big_sepL_type_ptr_shift; auto.\n          replace (Z.of_N 1) with 1%Z by lia.\n          iDestruct \"tptrs\" as \"#[tptr' tptrs]\".\n\n          iApply (IHrs with \"[tptrs]\"); iFrame \"#∗\".\n          unfold ptr_congP, ptr_cong; iPureIntro.\n          destruct H as [p [o1 [o2 [Ho1 [Ho2 Hoffset_cong]]]]]; subst.\n          exists p, (o1 .[ Tu8 ! 1 ]), (o2 .[ Tu8 ! 1 ]).\n          rewrite ?offset_ptr_dot; intuition.\n          unfold offset_cong in *.\n          apply option.same_property_iff in Hoffset_cong as [? [Ho1 Ho2]].\n          apply option.same_property_iff.\n          rewrite !eval_offset_dot !eval_o_sub Ho1 Ho2 /=.\n          by eauto.\n  Qed.\nEnd rawsR_transport.\n\n(* Definitions to ease consuming and reasoning about the collection of [type_ptr Tu8]\n   facts induced by [type_ptr_obj_repr].\n *)\nSection raw_type_ptrs.\n  Context `{Σ : cpp_logic} {σ : genv}.\n\n  (* [obj_type_ptr ty p] collects all of the constituent [type_ptr Tu8] facts\n     for the \"object representation\" of an object of type [ty] rooted at [p].\n   *)\n  Definition raw_type_ptrs_def (ty : type) (p : ptr) : mpred :=\n    Exists (sz : N),\n      [| size_of σ ty = Some sz |] **\n      [∗list] i ∈ seqN 0 sz, type_ptr Tu8 (p .[ Tu8 ! Z.of_N i ]).\n  Definition raw_type_ptrs_aux : seal (@raw_type_ptrs_def). Proof. by eexists. Qed.\n  Definition raw_type_ptrs := raw_type_ptrs_aux.(unseal).\n  Definition raw_type_ptrs_eq : @raw_type_ptrs = _ := raw_type_ptrs_aux.(seal_eq).\n\n  (* [obj_type_ptr ty p] collects all of the constituent [type_ptr Tu8] facts\n     for the \"object representation\" of an object of type [ty] rooted at [p].\n   *)\n  Definition raw_type_ptrsR_def (ty : type) : Rep := as_Rep (raw_type_ptrs ty).\n  Definition raw_type_ptrsR_aux : seal (@raw_type_ptrsR_def). Proof. by eexists. Qed.\n  Definition raw_type_ptrsR := raw_type_ptrsR_aux.(unseal).\n  Definition raw_type_ptrsR_eq : @raw_type_ptrsR = _ := raw_type_ptrsR_aux.(seal_eq).\n\n  Lemma type_ptr_raw_type_ptrs :\n    forall (ty : type) (p : ptr),\n      is_Some (size_of σ ty) ->\n      type_ptr ty p |-- raw_type_ptrs ty p.\n  Proof.\n    intros * Hsz; rewrite raw_type_ptrs_eq/raw_type_ptrs_def.\n    destruct Hsz as [sz Hsz].\n    iIntros \"#tptr\"; iExists sz; iFrame \"%\".\n    by iApply type_ptr_obj_repr.\n  Qed.\n\n  Section Instances.\n    #[global]\n    Instance raw_type_ptrs_persistent : forall p ty,\n      Persistent (raw_type_ptrs ty p).\n    Proof. rewrite raw_type_ptrs_eq/raw_type_ptrs_def; apply: _. Qed.\n    #[global]\n    Instance raw_type_ptrsR_persistent : forall ty,\n      Persistent (raw_type_ptrsR ty).\n    Proof. rewrite raw_type_ptrsR_eq/raw_type_ptrsR_def; apply: _. Qed.\n\n    #[global]\n    Instance raw_type_ptrs_affine : forall p ty,\n      Affine (raw_type_ptrs ty p).\n    Proof. rewrite raw_type_ptrs_eq/raw_type_ptrs_def; apply: _. Qed.\n    #[global]\n    Instance raw_type_ptrsR_affine : forall ty,\n      Affine (raw_type_ptrsR ty).\n    Proof. rewrite raw_type_ptrsR_eq/raw_type_ptrsR_def; apply: _. Qed.\n\n    #[global]\n    Instance raw_type_ptrs_timeless : forall p ty,\n      Timeless (raw_type_ptrs ty p).\n    Proof. rewrite raw_type_ptrs_eq/raw_type_ptrs_def; apply: _. Qed.\n    #[global]\n    Instance raw_type_ptrsR_timeless : forall ty,\n      Timeless (raw_type_ptrsR ty).\n    Proof. rewrite raw_type_ptrsR_eq/raw_type_ptrsR_def; apply: _. Qed.\n\n    Section observations.\n      #[global]\n      Instance raw_type_ptrs_type_ptr_Tu8_obs (ty : type) (i : N) :\n        forall (p : ptr) (sz : N),\n          size_of σ ty = Some sz ->\n          (i < sz)%N ->\n          Observe (type_ptr Tu8 (p .[ Tu8 ! i ])) (raw_type_ptrs ty p).\n      Proof.\n        iIntros (p sz Hsz Hi) \"#raw_tptrs !>\".\n        rewrite raw_type_ptrs_eq/raw_type_ptrs_def.\n        iDestruct \"raw_tptrs\" as (sz') \"[%Hsz' tptrs]\".\n        rewrite {}Hsz' in Hsz; inversion Hsz; subst.\n        iStopProof.\n        induction sz as [| sz' IHsz'] using N.peano_ind; first lia.\n        iIntros \"#tptrs\".\n        assert (i = sz' \\/ i < sz')%N as [Hi' | Hi'] by lia;\n          rewrite seqN_S_end_app big_opL_app; cbn;\n          iDestruct \"tptrs\" as \"(#tptrs & #tptr & _)\";\n          by [subst | iApply IHsz'].\n      Qed.\n\n      Lemma raw_type_ptrs_Tarray_elem (i : N) :\n        forall (p : ptr) (ty : types.type) (cnt sz : N)\n          (Hcnt : (cnt <> 0)%N) (Hsz : types.size_of σ ty = Some sz) (Hi : N.lt i cnt),\n          raw_type_ptrs (Tarray ty cnt) p |-- raw_type_ptrs ty (p .[Tu8 ! sz * i]).\n      Proof.\n        intros **; iIntros \"#raw_tptrs_array\".\n        rewrite raw_type_ptrs_eq/raw_type_ptrs_def.\n        iDestruct \"raw_tptrs_array\" as (sz_array) \"[%Hsz_array tptrs]\".\n        iExists sz; iSplit; first by iPureIntro.\n        rewrite -N2Z.inj_mul -(big_sepL_type_ptr_shift (sz * i) sz p Tu8).\n        iApply (big_sepL_submseteq with \"tptrs\").\n        apply sublist_submseteq.\n        apply seqN_sublist; first by done.\n        erewrite size_of_array in Hsz_array; eauto; inversion Hsz_array.\n        rewrite N.add_0_l -N.mul_succ_r N.mul_comm.\n        apply N.mul_le_mono_r.\n        lia.\n      Qed.\n\n      #[global]\n      Instance raw_type_ptrs_Tarray_elem_observe (i : N) :\n        forall (p : ptr) (ty : types.type) (cnt sz : N)\n          (Hcnt : (cnt <> 0)%N) (Hsz : types.size_of σ ty = Some sz) (Hi : N.lt i cnt),\n          Observe (raw_type_ptrs ty (p .[Tu8 ! sz * i])) (raw_type_ptrs (Tarray ty cnt) p).\n      Proof. intros **; rewrite (raw_type_ptrs_Tarray_elem i); eauto; by apply: _. Qed.\n\n      #[global]\n      Instance raw_type_ptrs_blockR_obs (ty : type) :\n        forall (p : ptr) (sz : N) q,\n          size_of σ ty = Some sz ->\n          Observe (raw_type_ptrs ty p) (p |-> blockR sz q).\n      Proof.\n        intros * Hsz.\n        rewrite blockR_eq/blockR_def raw_type_ptrs_eq/raw_type_ptrs_def !_at_sep.\n        apply observe_sep_r.\n        iIntros \"anyRs\".\n        rewrite bi.persistently_exist; iExists sz.\n        rewrite bi.persistently_sep; iSplitR \"anyRs\";\n          first by (iModIntro; iPureIntro).\n        rewrite _at_big_sepL.\n\n        unshelve iDestruct (big_sepL_mono with \"anyRs\") as \"H\";\n          [ by exact (fun _ v =>  <pers> type_ptr Tu8 (p .[Tu8 ! v]))%I\n          | by intros k v Hlookup; cbn;\n            rewrite _at_offsetR anyR_type_ptr_observe _at_pers _at_type_ptrR\n          | ]; cbn.\n        rewrite -big_sepL_persistently; iDestruct \"H\" as \"#tptrs\"; iModIntro.\n\n        (* NOTE (JH): There is probably a better way to relate these *)\n        iStopProof.\n        clear Hsz; generalize dependent p; induction sz using N.peano_ind=> p;\n          iIntros \"#tptrs\"; first by done.\n        rewrite seqN_S_start N2Nat.inj_succ; cbn.\n        iDestruct \"tptrs\" as \"[#tptr tptrs]\"; iSplitL \"tptr\".\n        - by replace (Z.of_nat 0) with 0%Z by lia.\n        - rewrite big_sepL_type_ptr_shift big_sepL_type_ptr_shift'.\n          specialize (IHsz (p .[Tu8 ! 1%N])).\n          by iApply IHsz.\n      Qed.\n    End observations.\n  End Instances.\n\n  Section equivalences.\n    Lemma _at_raw_type_ptrsR_equiv :\n      forall (p : ptr) (ty : type),\n        p |-> raw_type_ptrsR ty -|- raw_type_ptrs ty p.\n    Proof. by intros p ty; rewrite raw_type_ptrsR_eq/raw_type_ptrsR_def _at_as_Rep. Qed.\n\n    Lemma raw_type_ptrs_arrayR_Tu8_emp `(xs : list X) :\n      forall (ty : type) (p : ptr) (sz : N),\n        size_of σ ty = Some sz ->\n        lengthN xs = sz ->\n        xs <> nil ->\n            raw_type_ptrs ty p\n        -|- p |-> arrayR Tu8 (const emp) xs.\n    Proof.\n      intros * Hsz Hlen Hnonnil.\n      rewrite raw_type_ptrs_eq/raw_type_ptrs_def.\n      rewrite arrayR_eq/arrayR_def arrR_eq/arrR_def.\n      split'.\n      - iIntros \"P\"; iDestruct \"P\" as (sz') \"[%Hsz' #tptrs]\".\n        rewrite !_at_sep !_at_offsetR !_at_only_provable.\n        assert (is_Some (size_of σ Tu8)) by eauto; iFrame \"%\".\n        rewrite fmap_length -to_nat_lengthN Hlen N_nat_Z.\n        rewrite Hsz' in Hsz; inversion Hsz; subst.\n        iSplit.\n        + rewrite (big_sepL_lookup _ _ (Nat.pred (length xs))). 2: {\n            rewrite list_lookup_lookupN.\n            eapply lookupN_seqN.\n            intuition eauto.\n            destruct xs; simpl; [by exfalso; apply Hnonnil |].\n            rewrite /lengthN/=; lia.\n          }\n          rewrite N.add_0_l Nat2N.inj_pred; fold (lengthN xs).\n          replace (Z.of_N (lengthN xs))\n            with (N.pred (lengthN xs) + 1)%Z\n            by (destruct xs; by [contradiction | rewrite /lengthN/=; lia]).\n          rewrite -o_sub_sub _at_validR.\n          by iApply type_ptr_valid_plus_one.\n        + rewrite _at_big_sepL.\n          iApply (big_sepL_mono (fun n _ => type_ptr Tu8 (p .[ Tu8 ! n ]))).\n          2: {\n            iStopProof; generalize dependent p; clear -Hnonnil;\n              destruct xs as [| x xs]; first by contradiction.\n            generalize dependent x; induction xs as [| x' xs IHxs];\n              iIntros (x Hnonnil p) \"#tptrs\"; first done.\n            specialize (IHxs x' ltac:(auto) (p .[ Tu8 ! 1 ])).\n            rewrite fmap_cons big_sepL_cons.\n            replace (lengthN (x :: x' :: xs))\n              with (N.succ (lengthN (x' :: xs)))\n              by (rewrite !lengthN_cons; lia).\n            rewrite seqN_S_start big_sepL_cons.\n            iDestruct \"tptrs\" as \"[$ tptrs]\".\n            iApply (big_sepL_mono (fun n _ => type_ptr Tu8 (p .[ Tu8 ! 1 ] .[Tu8 ! n ])));\n              first by (intros **; rewrite o_sub_sub;\n                          by replace (Z.of_nat (S k)) with (1 + k)%Z by lia).\n            iApply IHxs; iModIntro.\n            by iApply (big_sepL_type_ptr_shift 1%N).\n          }\n          intros k y Hy.\n          rewrite list_lookup_fmap in Hy.\n          destruct (xs !! k); last by done.\n          inversion Hy; subst.\n          rewrite _at_offsetR _at_sep _at_emp _at_type_ptrR.\n          iIntros \"$\".\n      - rewrite !_at_sep !_at_offsetR _at_only_provable _at_validR _at_big_sepL.\n        iIntros \"(_ & _ & tptrs)\".\n        iExists sz; iFrame \"%\"; rewrite -Hlen; clear -Hnonnil.\n        iDestruct (big_sepL_mono _ (fun n y => type_ptr Tu8 (p .[ Tu8 ! n ])) with \"tptrs\") as \"tptrs\".\n        2: {\n          iStopProof; generalize dependent p;\n             destruct xs as [| x xs]; first by contradiction.\n          generalize dependent x; induction xs as [| x' xs IHxs];\n            iIntros (x Hnonnil p) \"tptrs\"; first by done.\n          specialize (IHxs x' ltac:(auto) (p .[ Tu8 ! 1 ])).\n          rewrite fmap_cons big_sepL_cons.\n          replace (lengthN (x :: x' :: xs))\n            with (N.succ (lengthN (x' :: xs)))\n            by (rewrite !lengthN_cons; lia).\n          rewrite seqN_S_start big_sepL_cons.\n          iDestruct \"tptrs\" as \"[$ tptrs]\".\n          iDestruct (big_sepL_mono _ (fun n _ => type_ptr Tu8 (p .[ Tu8 ! 1 ] .[Tu8 ! n ]))\n                      with \"tptrs\") as \"tptrs\";\n            first by (intros **; rewrite o_sub_sub;\n                        by replace (Z.of_nat (S k)) with (1 + k)%Z by lia).\n          iDestruct (IHxs with \"tptrs\") as \"tptrs\".\n          by iApply (big_sepL_type_ptr_shift 1%N).\n        }\n        intros k y Hy.\n        rewrite list_lookup_fmap in Hy.\n        destruct (xs !! k); last by done.\n        inversion Hy; subst.\n        rewrite _at_offsetR _at_sep _at_emp _at_type_ptrR.\n        iIntros \"[$ _]\".\n    Qed.\n\n    #[local]\n    Lemma raw_type_ptrs_array_aux :\n      forall (ty : type) (cnt : N) (p : ptr) (i sz : N),\n        size_of σ ty = Some sz ->\n            ([∗list] j ∈ seqN (i * sz) (cnt * sz)%N,\n               type_ptr Tu8 (p .[ Tu8 ! Z.of_N (i * sz) ] .[ Tu8 ! Z.of_N j ]))\n        -|- ([∗list] j ∈ seqN i cnt,\n               raw_type_ptrs ty (p .[ Tu8 ! Z.of_N ((i + j) * sz) ])).\n    Proof.\n      intros ty cnt; induction cnt as [| cnt' IHcnt'] using N.peano_ind=> p i sz Hsz;\n        first by rewrite N.mul_0_l !seqN_0.\n      rewrite Nmult_Sn_m {1}/seqN N2Nat.inj_add seq_app -N2Nat.inj_add fmap_app.\n      fold (seqN (i * sz) sz) (seqN (i * sz + sz)%N (cnt' * sz)).\n      replace (i * sz + sz)%N with ((i + 1) * sz)%N by lia;\n        rewrite big_sepL_app.\n      rewrite seqN_S_start big_sepL_cons -N.add_1_r.\n      specialize (IHcnt' (p .[ Tu8 ! -sz ]) (i + 1)%N sz Hsz).\n      rewrite !o_sub_sub in IHcnt'.\n      split'; iIntros \"[P Q]\"; iSplitL \"P\".\n      - rewrite raw_type_ptrs_eq/raw_type_ptrs_def.\n        iExists sz; iFrame \"%\".\n        iDestruct (big_sepL_type_ptr_shift with \"P\") as \"?\"; auto.\n        rewrite o_sub_sub.\n        by replace (Z.add (Z.of_N (i * sz)) (Z.of_N (i * sz)))\n          with (Z.of_N ((i + i) * sz))\n          by lia.\n      - iApply big_sepL_mono; last iApply IHcnt'.\n        + intros **; simpl.\n          rewrite o_sub_sub.\n          by replace (Z.add (-sz) (Z.of_N ((i + 1 + y) * sz)))\n            with (Z.of_N ((i + y) * sz))\n            by lia.\n        + iApply big_sepL_mono; last by iFrame.\n          intros **; simpl.\n          by replace (Z.add (-sz) (Z.of_N ((i + 1) * sz)))\n            with (Z.of_N (i * sz))\n            by lia.\n      - rewrite raw_type_ptrs_eq/raw_type_ptrs_def.\n        iDestruct \"P\" as (sz') \"[%Hsz' tptrs]\".\n        rewrite Hsz' in Hsz; inversion Hsz; subst.\n        iApply big_sepL_type_ptr_shift; auto.\n        rewrite o_sub_sub.\n        by replace (Z.add (Z.of_N (i * sz)) (Z.of_N (i * sz)))\n          with (Z.of_N ((i + i) * sz))\n          by lia.\n      - iApply big_sepL_mono; last iApply IHcnt'.\n        + intros **; simpl.\n          by replace (Z.add (-sz) (Z.of_N ((i + 1) * sz)))\n            with (Z.of_N (i * sz))\n            by lia.\n        + iApply big_sepL_mono; last by iFrame.\n          intros **; simpl.\n          rewrite o_sub_sub.\n          by replace (Z.add (-sz) (Z.of_N ((i + 1 + y) * sz)))\n            with (Z.of_N ((i + y) * sz))\n            by lia.\n    Qed.\n\n    Lemma raw_type_ptrs_big_array :\n      forall (p : ptr) (ty : type) (cnt sz : N),\n        size_of σ ty = Some sz ->\n            raw_type_ptrs (Tarray ty cnt) p\n        -|- [∗list] i ∈ seqN 0 cnt, raw_type_ptrs ty (p .[ Tu8 ! Z.of_N (i * sz) ]).\n    Proof.\n      intros p ty cnt sz Hsz.\n      pose proof (raw_type_ptrs_array_aux ty cnt p 0 sz Hsz) as Haux.\n      split'; iIntros \"P\";\n        rewrite o_sub_0 in Haux; auto; rewrite offset_ptr_id in Haux;\n        rewrite raw_type_ptrs_eq/raw_type_ptrs_def.\n      - iDestruct \"P\" as (array_sz) \"[%Harray_sz tptrs]\".\n        apply size_of_array_shatter in Harray_sz as [sz' [? [Hsz' Harray_sz]]]; subst.\n        rewrite Hsz' in Hsz; inversion Hsz; subst.\n        rewrite N.mul_0_l in Haux; rewrite Haux.\n        iApply big_sepL_mono; last by iFrame.\n        intros k y Hk=> /=.\n        by rewrite raw_type_ptrs_eq/raw_type_ptrs_def N.add_0_l.\n      - pose proof (size_of_array ty cnt sz Hsz).\n        iExists (cnt * sz)%N; iFrame \"%\".\n        iApply Haux.\n        iApply big_sepL_mono; last by iFrame.\n        intros k y Hk=> /=.\n        by rewrite raw_type_ptrs_eq/raw_type_ptrs_def N.add_0_l.\n    Qed.\n  End equivalences.\nEnd raw_type_ptrs.\n#[global] Arguments raw_type_ptrs {_ Σ σ} _ _.\n#[global] Arguments raw_type_ptrsR {_ Σ σ} _.\n#[global] Hint Opaque raw_type_ptrs raw_type_ptrsR : typeclass_instances.\n\nSection primR_transport.\n  Context `{Σ : cpp_logic} {σ : genv}.\n\n  Lemma _at_primR_ptr_congP_transport p p' ty q v :\n    ptr_congP σ p p' ** type_ptr ty p' |-- p |-> primR ty q v -* p' |-> primR ty q v.\n  Proof.\n    iIntros \"#[cong tptr'] prim\".\n    iDestruct (type_ptr_size with \"tptr'\") as \"%Hsz\"; destruct Hsz as [sz Hsz].\n    iDestruct (type_ptr_raw_type_ptrs with \"tptr'\") as \"raw_tptrs\"; eauto.\n    rewrite raw_type_ptrs_eq/raw_type_ptrs_def.\n    iDestruct \"raw_tptrs\" as (sz') \"[%Hsz' tptrs]\".\n    rewrite Hsz' in Hsz; inversion Hsz; subst.\n    rewrite primR_to_rawsR !_at_exists.\n    iDestruct \"prim\" as (rs) \"H\"; iExists rs.\n    rewrite !_at_sep !_at_only_provable !_at_type_ptrR.\n    iDestruct \"H\" as \"(raws & %raw_bytes & _)\"; iFrame \"#%\".\n    pose proof (raw_bytes_of_val_sizeof raw_bytes) as Hlen.\n    rewrite Hlen in Hsz'; inversion Hsz'; subst.\n    rewrite lengthN_fold.\n    iRevert \"raws\".\n    iApply _at_rawsR_ptr_congP_transport.\n    by iFrame \"#\".\n  Qed.\nEnd primR_transport.\n\n(* [Rep]s which can be encoded as [raw] bytes enjoy certain transport and cancellation properties *)\nSection with_rawable.\n  Context `{Σ : cpp_logic} {σ : genv}.\n  Context {X : Type} (R : cQp.t -> X -> Rep).\n  Context (decode : list raw_byte -> X -> Prop) (encode : X -> list raw_byte -> Prop).\n  Context (enc_dec_uniq : forall (x x' : X) (raws : list raw_byte),\n              encode x raws -> decode raws x' -> x = x').\n  (* NOTE (JH): structs with padding are rawable, but this direction is too strict to permit\n     the nondeterminism inherent in the representation of padding.\n   *)\n  (* Context (dec_enc_uniq : forall (x x' : X) (raws : list raw_byte), *)\n  (*             decode raws x -> encode x raws' -> ). *)\n  Context (ty : type) (sz : N) (Hsz : size_of σ ty = Some sz) (Hnonzero : (sz <> 0)%N).\n  Context (Hdecode_sz : forall (x : X) (rs : list raw_byte), decode rs x -> lengthN rs = sz).\n  Context (Hencode_sz : forall (x : X) (rs : list raw_byte), encode x rs -> lengthN rs = sz).\n  Context (HR_decode : forall (rs : list raw_byte) (p : ptr) q,\n                             p |-> rawsR q rs ** type_ptr ty p\n                         |-- Exists (x : X),\n                                [| decode rs x |] ** p |-> R q x).\n  Context (HR_encode : forall (x : X) (p : ptr) q,\n                             p |-> R q x\n                         |-- type_ptr ty p **\n                             Exists (rs : list raw_byte),\n                               [| encode x rs |] ** p |-> rawsR q rs).\n\n  #[local] Lemma _at_rawable_R_obj_repr_aux (i : N) :\n    forall (p : ptr) q (rs : list raw_byte),\n          p .[ Tu8 ! i ] |-> rawsR q (dropN i rs)\n      |-- p .[ Tu8 ! i ] |-> arrayR Tu8 (fun tt => anyR Tu8 q)\n                                        (replicateN (lengthN rs - i) ()).\n  Proof.\n    intros **; clear Hsz Hdecode_sz Hencode_sz Hnonzero HR_decode HR_encode.\n    generalize dependent i; generalize dependent p.\n    induction rs as [| r rs IHrs]; intros p i.\n    - rewrite replicateN_0 dropN_nil /rawsR !arrayR_nil.\n      done.\n    - destruct i as [| i' _] using N.peano_ind=>//.\n      + rewrite -> o_sub_0 in *; auto.\n        specialize (IHrs (p .[ Tu8 ! 1 ]) 0%N).\n        rewrite -> offset_ptr_id in *.\n        rewrite -> N.sub_0_r in *.\n        rewrite lengthN_cons replicateN_succ /rawsR !arrayR_cons\n                !_at_sep !_at_offsetR.\n        iIntros \"(#tptr & raw & raws)\".\n        iFrame \"#\"; iSplitL \"raw\".\n        * rewrite rawR_eq/rawR_def _at_as_Rep.\n          by iApply tptsto_raw_anyR.\n        * rewrite o_sub_0 in IHrs; auto; rewrite offset_ptr_id in IHrs.\n          iApply IHrs.\n          rewrite dropN_zero /rawsR _at_type_ptrR; iFrame \"#∗\".\n      + replace (dropN (N.succ i') (r :: rs))\n          with (dropN i' rs)\n          by (rewrite -N.add_1_r dropN_cons_succ//).\n        rewrite lengthN_cons.\n        replace (lengthN rs + 1 - N.succ i')%N\n          with (lengthN rs - i')%N\n          by lia.\n        specialize (IHrs (p .[ Tu8 ! 1 ]) i').\n        rewrite o_sub_sub in IHrs.\n        replace (1 + Z.of_N i')%Z with (Z.of_N (N.succ i')) in IHrs by lia.\n        by iApply IHrs.\n  Qed.\n\n  Lemma _at_rawable_R_arrayR_anyR :\n    forall (p : ptr) q (x : X),\n          p |-> R q x\n      |-- p |-> arrayR Tu8 (fun tt => anyR Tu8 q) (replicateN sz ()).\n  Proof using encode ty Hsz Hencode_sz Hnonzero HR_encode.\n    intros **.\n    rewrite HR_encode.\n    iIntros \"[#tptr H]\"; iDestruct \"H\" as (rs) \"[%Hrs raws]\".\n    pose proof (_at_rawable_R_obj_repr_aux 0 p q rs) as Haux.\n    rewrite o_sub_0 in Haux; auto; rewrite offset_ptr_id in Haux.\n    rewrite dropN_zero N.sub_0_r (Hencode_sz x) in Haux; last by assumption.\n    by iApply Haux.\n  Qed.\n\n  Lemma _at_rawable_R_anyR :\n    forall (p : ptr) q (x : X),\n          p |-> R q x\n      |-- p |-> anyR (Tarray Tu8 sz) q.\n  Proof using encode ty Hsz Hencode_sz Hnonzero HR_encode.\n    intros **; rewrite anyR_array repeatN_replicateN.\n    by apply _at_rawable_R_arrayR_anyR.\n  Qed.\n\n  Lemma R_ptr_congP_transport_via_rawsR :\n    forall (p p' : ptr) q (x : X),\n      ptr_congP σ p p' ** type_ptr ty p' |-- p |-> R q x -* p' |-> R q x.\n  Proof using decode encode enc_dec_uniq sz Hdecode_sz Hencode_sz Hsz HR_decode HR_encode Hnonzero.\n    intros p p' q x; rewrite HR_encode.\n    iIntros \"#[cong tptr'] [#tptr H]\"; iDestruct \"H\" as (rs) \"[%Henc raws]\".\n    iDestruct (type_ptr_raw_type_ptrs with \"tptr'\") as \"#raw_tptrs'\"; auto.\n    assert (rs <> []) as Hrs_nonnil\n        by (intro CONTRA; subst; specialize (Hencode_sz x [] Henc);\n            apply Hnonzero; rewrite -Hencode_sz; by apply lengthN_nil).\n    rewrite raw_type_ptrs_eq/raw_type_ptrs_def.\n    iDestruct \"raw_tptrs'\" as (sz') \"[%Hsz' tptrs']\".\n    rewrite Hsz in Hsz'; inversion Hsz'; subst.\n    assert (sz' = lengthN rs) as -> by (by erewrite <- Hencode_sz).\n    iDestruct (_at_rawsR_ptr_congP_transport with \"[$] [$]\") as \"raws'\".\n    iCombine \"raws' tptr'\" as \"H\".\n    iDestruct (HR_decode with \"H\") as \"H\".\n    iDestruct \"H\" as (x') \"[%Hdec R]\".\n    by rewrite (enc_dec_uniq x x' rs).\n  Qed.\nEnd with_rawable.\n\nSection blockR_transport.\n  Context `{Σ : cpp_logic} {σ : genv}.\n\n  Lemma blockR_ptr_congP_transport_raw (sz : N) :\n    forall (p p' : ptr) (ty : type) q,\n      size_of σ ty = Some sz ->\n          ptr_congP σ p p' ** raw_type_ptrs ty p'\n      |-- p |-> blockR sz q -* p' |-> blockR sz q.\n  Proof.\n    iIntros (p p' ty q Hty) \"[#cong #raw_tptrs'] block\".\n    iDestruct (raw_type_ptrs_blockR_obs with \"block\") as \"#raw_tptrs\"; eauto.\n    assert (sz = 0 \\/ 0 < sz)%N as [Hsz | Hsz] by lia.\n    - subst; rewrite blockR_eq/blockR_def !_at_sep !_at_offsetR/=.\n      rewrite o_sub_0; eauto; rewrite !offset_ptr_id !_at_emp.\n      iDestruct \"block\" as \"[_ $]\".\n      rewrite _at_validR.\n      iDestruct \"cong\" as \"#(cong & tptr & tptr')\".\n      by iApply type_ptr_valid.\n    - rewrite blockR_eq/blockR_def !_at_sep !_at_offsetR.\n      iDestruct \"block\" as \"[block_valid block]\"; iSplit.\n      + iDestruct (raw_type_ptrs_type_ptr_Tu8_obs\n                     ty (N.pred sz) p' sz Hty ltac:(lia)\n                    with \"raw_tptrs'\")\n          as \"#tptr_end'\".\n        rewrite !_at_validR.\n        iDestruct (type_ptr_valid_plus_one with \"tptr_end'\") as \"valid_end'\".\n        rewrite o_sub_sub.\n        by have ->: (N.pred sz + 1)%Z = Z.of_N sz by lia.\n      + rewrite !_at_big_sepL.\n        (* TODO: find a strengthened [big_sepL] lemma for monotonicity in a given context *)\n        rewrite raw_type_ptrs_eq/raw_type_ptrs_def.\n        iDestruct \"raw_tptrs\" as (sz') \"[%Hty' tptrs]\".\n        iDestruct \"raw_tptrs'\" as (sz'') \"[%Hty'' tptrs']\".\n        rewrite Hty' in Hty; inversion Hty; subst; clear Hty.\n        rewrite Hty'' in Hty'; inversion Hty'; subst; clear Hty' Hty''.\n        iClear \"block_valid\".\n\n        iDestruct \"cong\" as \"-#cong\".\n        iDestruct \"tptrs\" as \"-#tptrs\".\n        iDestruct \"tptrs'\" as \"-#tptrs'\".\n        iRevert \"block\"; iStopProof.\n\n        generalize dependent p'; generalize dependent p;\n          induction sz as [| sz' IHsz'] using N.peano_ind;\n          first by lia.\n\n        assert (sz' = 0 \\/ 0 < sz')%N as [Hsz' | Hsz'] by lia. 1: {\n          iIntros (p p') \"#(cong & tptrs & tptrs')\"; subst.\n          rewrite !N2Nat.inj_succ/= o_sub_0; eauto; rewrite !offset_ptr_id !_offsetR_id.\n          iIntros \"[any $]\"; iRevert \"any\".\n          iApply _at_anyR_ptr_congP_transport.\n          by iFrame \"cong\"; iDestruct \"cong\" as \"(_&_&$)\".\n        }\n\n        iIntros (p p') \"#(cong & tptrs & tptrs')\".\n        rewrite !seqN_S_start !N2Nat.inj_succ/=.\n        rewrite o_sub_0; eauto; rewrite !_offsetR_id !offset_ptr_id.\n        iDestruct \"tptrs\" as \"[tptr tptrs]\".\n        iDestruct \"tptrs'\" as \"[tptr' tptrs']\".\n        iIntros \"[any REST]\"; iSplitL \"any\".\n        * iRevert \"any\"; iApply _at_anyR_ptr_congP_transport.\n          by iFrame \"cong tptr'\".\n        * rewrite !(big_sepL_type_ptr_shift 1 sz'); eauto.\n          specialize (IHsz' Hsz' (p .[ Tu8 ! 1%N ]) (p' .[ Tu8 ! 1%N ])).\n          iDestruct (IHsz' with \"[]\") as \"IH\".\n          -- iFrame \"tptrs tptrs'\"; unfold ptr_congP.\n             iDestruct \"cong\" as \"(%Hcong & _ & _)\".\n             iSplitR.\n             ++ iPureIntro; unfold ptr_cong in *.\n                destruct Hcong as [p'' [o1 [o2 [-> [-> Hcong]]]]].\n                exists p'', (o1 .[ Tu8 ! 1%N ]), (o2 .[ Tu8 ! 1%N ]).\n                rewrite !offset_ptr_dot; intuition.\n                unfold offset_cong in *.\n                rewrite -> option.same_property_iff in *.\n                destruct Hcong as [z [Ho1 Ho2]].\n                exists (z + 1)%Z; rewrite !eval_offset_dot !eval_o_sub.\n                by rewrite Ho1 Ho2//=.\n             ++ iSplitL \"tptrs\"; destruct sz' using N.peano_ind; try lia;\n                  rewrite seqN_S_start/= o_sub_0; eauto; rewrite !offset_ptr_id.\n                ** by iDestruct \"tptrs\" as \"[$ _]\".\n                ** by iDestruct \"tptrs'\" as \"[$ _]\".\n          -- setoid_rewrite _at_offsetR.\n             rewrite !(big_sepL_shift_nat (λ p, p |-> anyR Tu8 q) 1 (N.to_nat sz')).\n             by iRevert \"REST\".\n  Qed.\n\n  (* NOTE (JH): In practice this will likely be difficult to use due to the\n     [type_ptr ty p'] obligation.\n   *)\n  Lemma blockR_ptr_congP_transport (sz : N) :\n    forall (p p' : ptr) (ty : type) q,\n      size_of σ ty = Some sz ->\n          ptr_congP σ p p' ** type_ptr ty p ** type_ptr ty p'\n      |-- p |-> blockR sz q -* p' |-> blockR sz q.\n  Proof.\n    intros **; iIntros \"(cong & _ & tptr')\".\n    rewrite type_ptr_raw_type_ptrs; eauto.\n    by iApply blockR_ptr_congP_transport_raw; eauto.\n  Qed.\nEnd blockR_transport.\n", "meta": {"author": "bedrocksystems", "repo": "BRiCk", "sha": "23d7e64cc53706de608dbff0be75d1c4b8c3a7ec", "save_path": "github-repos/coq/bedrocksystems-BRiCk", "path": "github-repos/coq/bedrocksystems-BRiCk/BRiCk-23d7e64cc53706de608dbff0be75d1c4b8c3a7ec/theories/lang/cpp/logic/object_repr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.20495296699490465}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom bpf.comm Require Import MemRegion State Monad rBPFMonadOp.\nFrom Coq Require Import List Lia.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\nRequire Import ZArith.\n\nFrom bpf.clightlogic Require Import Clightlogic CorrectRel CommonLemma.\n\nFrom bpf.clight Require Import interpreter.\n\nFrom bpf.simulation Require Import MatchState InterpreterRel.\n\n\n(**\nstatic __attribute__((always_inline)) inline unsigned int eval_mrs_num(struct bpf_state* st){\n  return ( *st).mrs_num;\n}\n\nPrint eval_mrs_num.\neval_mrs_num = fun st : State.state => Some (eval_mem_num st, st)\n     : M nat\n\n*)\n\nSection Eval_mrs_num.\n  Context {S : special_blocks}.\n\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  Definition args : list Type := [].\n  Definition res : Type := (nat:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M State.state res) := eval_mrs_num.\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_eval_mrs_num.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) ((unit:Type) ::args) :=\n    (dcons (fun _ => StateLess _ is_state_handle)\n                (DList.DNil _)).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv State.state := fun re => StateFull _ (fun v st m => nat_correct re v /\\ re = (mrs_num st)).\n\n  Instance correct_function_eval_mrs_num : forall a, correct_function _ p args res f fn ModNothing false match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n    (** how to use correct_* *)\n    unfold INV.\n    unfold f.\n    repeat intro.\n    get_invariant _st.\n    unfold eval_inv, is_state_handle in c.\n    subst.\n\n    assert (Hst' := MS).\n    destruct Hst'. clear - MS p0 mmrs_num mem_regs.\n\n    eexists. exists m, Events.E0.\n\n    split_and.\n    {\n      repeat forward_star.\n      rewrite Ptrofs.add_zero_l.\n      unfold Coqlib.align; simpl. change (832 / 8)%Z with 104%Z.\n\n      destruct mmrs_num as (mmrs_num & _).\n      unfold Mem.loadv in mmrs_num.\n      rewrite mmrs_num.\n      reflexivity.\n      reflexivity.\n    }\n    split.\n    {\n      unfold match_res, nat_correct, eval_mem_num.\n      split.\n      reflexivity.\n      unfold match_regions in mem_regs.\n      destruct mem_regs as (_ & Hlen & Hrange & _).\n      rewrite Hlen in Hrange.\n      change Int.max_unsigned with Ptrofs.max_unsigned.\n      lia.\n    }\n    unfold eval_mem_num. reflexivity.\n    constructor. reflexivity.\n    auto.\n    apply unmodifies_effect_refl.\n  Qed.\n\nEnd Eval_mrs_num.\n\nExisting Instance correct_function_eval_mrs_num.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/correct_eval_mrs_num.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.20495296699490465}}
{"text": "(* Copyright (c) 2011. Greg Morrisett, Gang Tan, Joseph Tassarotti, \n   Jean-Baptiste Tristan, and Edward Gan.\n\n   This file is part of RockSalt.\n\n   This file is free software; you can redistribute it and/or\n   modify it under the terms of the GNU General Public License as\n   published by the Free Software Foundation; either version 2 of\n   the License, or (at your option) any later version.\n*)\n\n(* This file provides simple bit-level parsing combinators for disassembling\n * Intel IA32 (x86) 32-bit binaries. *)\nRequire Coqlib.\nRequire Import Coq.Init.Logic.\nRequire Import Bool.\nRequire Import List.\nRequire Import String.\nRequire Import Maps.\nRequire Import Ascii.\nRequire Import ZArith.\nRequire Import Eqdep.\nRequire Import Parser.\nUnset Automatic Introduction.\nSet Implicit Arguments.\nLocal Open Scope Z_scope.\n\n\nRequire ExtrOcamlString.\nRequire ExtrOcamlNatBigInt.\n\n\n(* a module for generating the parser for x86 instructions *)\nModule X86_PARSER_ARG.\n  Require Import X86Syntax.\n  Require Import Bits.\n  \n  Definition char_p : Set := bool.\n  Definition char_eq : forall (c1 c2:char_p), {c1=c2}+{c1<>c2} := bool_dec.\n  Inductive type : Set := \n  | Int_t : type\n  | Register_t : type\n  | Byte_t : type\n  | Half_t : type\n  | Word_t : type\n  | Scale_t : type\n  | Condition_t : type\n  | Operand_t : type\n  | Instruction_t : type\n  | Control_Register_t : type\n  | Debug_Register_t : type\n  | Segment_Register_t : type\n  | Lock_or_Rep_t : type\n  | Bool_t : type\n  | Prefix_t : type\n  | Option_t (t: type) : type\n  (* Need pairs at this level if I want to have options of pairs*)\n  | Pair_t (t1 t2: type) : type. \n\n  Definition tipe := type.\n  Definition tipe_eq : forall (t1 t2:tipe), {t1=t2} + {t1<>t2}.\n    intros ; decide equality.\n  Defined.\n\n  Fixpoint tipe_m (t:tipe) := \n    match t with \n      | Int_t => Z\n      | Register_t => register\n      | Byte_t => int8\n      | Half_t => int16\n      | Word_t => int32\n      | Scale_t => scale\n      | Condition_t => condition_type\n      | Operand_t => operand\n      | Instruction_t => instr\n      | Control_Register_t => control_register\n      | Debug_Register_t => debug_register\n      | Segment_Register_t => segment_register\n      | Lock_or_Rep_t => lock_or_rep\n      | Bool_t => bool\n      | Prefix_t => prefix\n      | Option_t t => option (tipe_m t)\n      | Pair_t t1 t2 => ((tipe_m t1) * (tipe_m t2))%type\n    end.\nEnd X86_PARSER_ARG.\n\nModule X86_PARSER.\n  Module X86_BASE_PARSER := Parser.Parser(X86_PARSER_ARG).\n  Require Import X86Syntax.\n  Require Import Bits.\n  Import X86_PARSER_ARG.\n  Import X86_BASE_PARSER.\n\n  Definition option_t x := tipe_t (Option_t x).\n  Definition int_t := tipe_t Int_t.\n  Definition register_t := tipe_t Register_t.\n  Definition byte_t := tipe_t Byte_t.\n  Definition half_t := tipe_t Half_t.\n  Definition word_t := tipe_t Word_t.\n  Definition scale_t := tipe_t Scale_t.\n  Definition condition_t := tipe_t Condition_t.\n  Definition operand_t := tipe_t Operand_t.\n  Definition instruction_t := tipe_t Instruction_t.\n  Definition control_register_t := tipe_t Control_Register_t.\n  Definition debug_register_t := tipe_t Debug_Register_t.\n  Definition segment_register_t := tipe_t Segment_Register_t.\n  Definition lock_or_rep_t := tipe_t Lock_or_Rep_t.\n  Definition bool_t := tipe_t Bool_t.\n  Definition prefix_t := tipe_t Prefix_t.\n  (* combinators for building parsers *)\n  Definition bit(x:bool) : parser char_t := Char_p x.\n  Definition never t : parser t := Zero_p t.\n  Definition always t (x:result_m t) : parser t := @Map_p unit_t t (fun (_:unit) => x) Eps_p.\n  Definition alt t (p1 p2:parser t) : parser t := Alt_p p1 p2.\n  Definition alts t (ps: list (parser t)) : parser t := List.fold_right (@alt t) (@never t) ps.\n  Definition map t1 t2 (p:parser t1) (f:result_m t1 -> result_m t2) : parser t2 := \n    @Map_p t1 t2 f p.\n  Implicit Arguments map [t1 t2].\n  Definition seq t1 t2 (p1:parser t1) (p2:parser t2) : parser (pair_t t1 t2) := Cat_p p1 p2.\n  Definition cons t (pair : result_m (pair_t t (list_t t))) : result_m (list_t t) := \n    (fst pair)::(snd pair).\n  Definition seqs t (ps:list (parser t)) : parser (list_t t) := \n    List.fold_right (fun p1 p2 => map (seq p1 p2) (@cons t)) \n      (@always (list_t t) (@nil (result_m t))) ps.\n  Fixpoint string_to_bool_list (s:string) : list bool := \n    match s with\n      | EmptyString => nil\n      | String a s => \n        (if ascii_dec a \"0\"%char then false else true)::(string_to_bool_list s)\n    end.\n\n  Fixpoint bits_n (n:nat) : result := \n    match n with \n      | 0%nat => unit_t\n      | S n => pair_t char_t (bits_n n)\n    end.\n  Fixpoint field'(n:nat) : parser (bits_n n) := \n    match n with \n      | 0%nat => Eps_p\n      | S n => Cat_p Any_p (field' n)\n    end.\n  Fixpoint bits2Z(n:nat)(a:Z) : result_m (bits_n n) -> result_m int_t := \n    match n with \n      | 0%nat => fun _ => a\n      | S n => fun p => bits2Z n (2*a + (if (fst p) then 1 else 0)) (snd p)\n    end.\n  Definition bits2int(n:nat)(bs:result_m (bits_n n)) : result_m int_t := bits2Z n 0 bs.\n  Fixpoint bits (x:string) : parser (bits_n (String.length x)) := \n    match x with \n      | EmptyString => Eps_p\n      | String c s => \n        (Cat_p (Char_p (if ascii_dec c \"0\"%char then false else true)) (bits s))\n    end.\n\n  (* notation for building parsers *)\n  Infix \"|+|\" := alt (right associativity, at level 80).\n  Infix \"$\" := seq (right associativity, at level 70).\n  Infix \"@\" := map (right associativity, at level 75).\n  Notation \"e %% t\" := (e : result_m t) (at level 80).\n  Definition bitsleft t (s:string)(p:parser t) : parser t := \n    bits s $ p @ (@snd _ _).\n  Infix \"$$\" := bitsleft (right associativity, at level 70).\n\n  Definition anybit : parser char_t := Any_p.\n  Definition field(n:nat) := (field' n) @ (bits2int n).\n  Definition reg := (field 3) @ (Z_to_register : _ -> result_m register_t).\n  Definition byte := (field 8) @ (@Word.repr 7 : _ -> result_m byte_t).\n (* Definition halfword := (field 16) @ (@Word.repr 15 : _ -> result_m half_t).\n  Definition word := (field 32) @ (@Word.repr 31 : _ -> result_m word_t). *)\n  Definition halfword := (byte $ byte) @ ((fun p =>\n      let b0 := Word.repr (Word.unsigned (fst p)) in\n      let b1 := Word.repr (Word.unsigned (snd p)) in\n        Word.or (Word.shl b1 (Word.repr 8)) b0): _ -> result_m half_t).\n  Definition word := (byte $ byte $ byte $ byte) @\n    ((fun p => \n        let b0 := zero_extend8_32 (fst p) in\n        let b1 := zero_extend8_32 (fst (snd p)) in\n        let b2 := zero_extend8_32 (fst (snd (snd p))) in\n        let b3 := zero_extend8_32 (snd (snd (snd p))) in\n         let w1 := Word.shl b1 (Word.repr 8) in\n         let w2 := Word.shl b2 (Word.repr 16) in\n         let w3 := Word.shl b3 (Word.repr 24) in\n          Word.or w3 (Word.or w2 (Word.or w1 b0)))\n    : _ -> result_m word_t).\n\n  Definition scale_p := (field 2) @ (Z_to_scale : _ -> result_m scale_t).\n  Definition tttn := (field 4) @ (Z_to_condition_type : _ -> result_m condition_t).\n\n  (* This is used in a strange edge-case for modrm parsing. See the\n     footnotes on p37 of the manual in the repo This is a case where I\n     think intersections/complements would be nice operators *)\n\n  (* JGM: we can handle this in the semantic action instead of the parser, \n     so I replaced si, which used this and another pattern for [bits \"100\"]\n     to the simpler case below -- helps to avoid some explosions in the \n     definitions. *)\n  Definition reg_no_esp : parser register_t :=\n     (bits \"000\" |+| bits \"001\" |+| bits \"010\" |+|\n     bits \"011\" |+| (* bits \"100\" <- this is esp *)  bits \"101\" |+|\n     bits \"110\" |+| bits \"111\") @ \n       ((fun bs => Z_to_register (bits2int 3 bs)) : _ -> result_m register_t).\n\n  Definition reg_no_ebp : parser register_t :=\n     (bits \"000\" |+| bits \"001\" |+| bits \"010\" |+|\n     bits \"011\" |+|  bits \"100\"  (* |+| bits \"101\" <- this is ebp *) |+|\n     bits \"110\" |+| bits \"111\") @ \n       ((fun bs => Z_to_register (bits2int 3 bs)) : _ -> result_m register_t).\n\n  Definition si := \n    (scale_p $ reg) @ (fun p => match snd p with \n                                  | ESP => None\n                                  | _ => Some p\n                                end %% option_t (Pair_t Scale_t Register_t)).\n\n  Definition sib := si $ reg.\n      \n  (* These next 4 parsers are used in the definition of the mod/rm parser *)\n  Definition rm00 : parser operand_t := \n    (     bits \"000\" \n      |+| bits \"001\" \n      |+| bits \"010\" \n      |+| bits \"011\" \n      |+| bits \"110\"\n      |+| bits \"111\" ) @ \n          (fun bs => Address_op (mkAddress (Word.repr 0) \n            (Some (Z_to_register(bits2int 3 bs))) None) %% operand_t)\n      |+| bits \"100\" $ si $ reg_no_ebp @ \n          (fun p => match p with\n                      | (_,(si,base)) => \n                        Address_op (mkAddress (Word.repr 0) \n                          (Some base) si)\n                    end : result_m operand_t)     \n      |+| bits \"100\" $ si $ bits \"101\" $ word @\n          (fun p => match p with\n                      | (_,(si,(_, disp))) => \n                        Address_op (mkAddress disp\n                          (None) si)\n                    end : result_m operand_t)\n      |+| bits \"101\" $ word @\n          (fun p => match p with \n                      | (_, disp) => \n                        Address_op (mkAddress disp None None)\n                    end %% operand_t).  \n\n  Definition rm01 : parser operand_t := \n    ((    bits \"000\" \n      |+| bits \"001\" \n      |+| bits \"010\" \n      |+| bits \"011\"\n      |+| bits \"101\" \n      |+| bits \"110\"\n      |+| bits \"111\") $ byte) @ \n          (fun p => \n            match p with \n              | (bs, disp) =>\n                Address_op (mkAddress (sign_extend8_32 disp) \n                  (Some (Z_to_register(bits2int 3 bs))) None)\n            end %% operand_t)\n      |+| bits \"100\" $ sib $ byte @ \n          (fun p => \n            match p with\n              | (_,((si,base),disp)) => \n                Address_op (mkAddress (sign_extend8_32 disp) (Some base)\n                  (si))\n            end %% operand_t).\n\n  Definition rm10 : parser operand_t := \n    ((    bits \"000\" \n      |+| bits \"001\" \n      |+| bits \"010\" \n      |+| bits \"011\"\n      |+| bits \"101\" \n      |+| bits \"110\"\n      |+| bits \"111\") $ word) @ \n          (fun p => \n            match p with \n              | (bs, disp) =>\n                Address_op (mkAddress disp (Some (Z_to_register(bits2int 3 bs))) None)\n            end %% operand_t)\n      |+|  bits \"100\" $ sib $ word @ \n          (fun p => \n            match p with\n              | (_,((si,base),disp)) => \n                Address_op (mkAddress disp (Some base) si)\n            end %% operand_t).\n  \n  Definition rm11 : parser operand_t := reg @ (fun x => Reg_op x : result_m operand_t).\n\n  Definition modrm : parser (pair_t operand_t operand_t) := \n    (     (bits \"00\" $ reg $ rm00)\n      |+| (bits \"01\" $ reg $ rm01)\n      |+| (bits \"10\" $ reg $ rm10)\n      |+| (bits \"11\" $ reg $ rm11) ) @ \n          (fun p => match p with \n                      | (_, (r, op)) => (Reg_op r, op)\n                    end %% (pair_t operand_t operand_t)).\n\n  (* same as modrm but disallows the register case *)\n  Definition modrm_noreg :=\n  (     (\"00\" $$ reg $ rm00)\n    |+| (\"01\" $$ reg $ rm01)\n    |+| (\"10\" $$ reg $ rm10)).\n\n  (* Similar to mod/rm parser except that the register field is fixed to a\n   * particular bit-pattern, and the pattern starting with \"11\" is excluded. *)\n  Definition ext_op_modrm(bs:string) : parser operand_t := \n    (      (bits \"00\" $ bits bs $ rm00)\n     |+|   (bits \"01\" $ bits bs $ rm01)\n     |+|   (bits \"10\" $ bits bs $ rm10) ) @\n           (fun p => match p with \n                       | (_,(_,op)) => op\n                     end %% operand_t).\n\n  Definition ext_op_modrm2(bs:string) : parser operand_t :=\n    (      (bits \"00\" $ bits bs $ rm00)\n     |+|   (bits \"01\" $ bits bs $ rm01)\n     |+|   (bits \"10\" $ bits bs $ rm10)\n     |+|   (bits \"11\" $ bits bs $ rm11) ) @\n           (fun p => match p with \n                       | (_,(_,op)) => op\n                     end %% operand_t).\n\n  (* Parsers for the individual instructions *)\n  Definition AAA_p := bits \"00110111\" @ (fun _ => AAA %% instruction_t).\n  Definition AAD_p := bits \"1101010100001010\" @ (fun _ => AAD %% instruction_t).\n  Definition AAM_p := bits \"1101010000001010\" @ (fun _ => AAM %% instruction_t).\n  Definition AAS_p := bits \"00111111\" @ (fun _ => AAS %% instruction_t).\n\n  (* The parsing for ADC, ADD, AND, CMP, OR, SBB, SUB, and XOR can be shared *)\n\n  Definition imm_op (opsize_override: bool) : parser operand_t :=\n    match opsize_override with\n      | false => word @ (fun w => Imm_op w %% operand_t)\n      | true => halfword @ (fun w => Imm_op (sign_extend16_32 w) %% operand_t)\n    end.\n      \n  Definition logic_or_arith_p (opsize_override: bool)\n    (op1 : string) (* first 5 bits for most cases *)\n    (op2 : string) (* when first 5 bits are 10000, the next byte has 3 bits\n                      that determine the opcode *)\n    (InstCon : bool->operand->operand->instr) (* instruction constructor *)\n    : parser instruction_t\n    :=\n  (* register/memory to register and vice versa -- the d bit specifies\n   * the direction. *)\n  op1 $$ \"0\" $$ anybit $ anybit $ modrm @\n    (fun p => match p with \n                | (d, (w, (op1, op2))) => \n                  if d then InstCon w op1 op2 else InstCon w op2 op1\n              end %% instruction_t)\n  |+|\n  (* sign extend immediate byte to register *)\n  \"1000\" $$ \"0011\" $$ \"11\" $$ op2 $$ reg $ byte @ \n    (fun p => \n      let (r,imm) := p in InstCon true (Reg_op r) (Imm_op (sign_extend8_32 imm)) %%\n    instruction_t)\n  |+|\n  (* zero-extend immediate byte to register *)\n  \"1000\" $$ \"0000\" $$ \"11\" $$ op2 $$ reg $ byte @ \n    (fun p => \n      let (r,imm) := p in InstCon false (Reg_op r) (Imm_op (zero_extend8_32 imm)) %%\n    instruction_t)\n  |+|\n  (* immediate word to register *)\n  \"1000\" $$ \"0001\" $$ \"11\" $$ op2 $$ reg $ imm_op opsize_override @ \n    (fun p => let (r,imm) := p in InstCon true (Reg_op r) imm %% instruction_t)\n  |+|\n  (* zero-extend immediate byte to EAX *)\n  op1 $$ \"100\" $$ byte @\n    (fun imm => InstCon false (Reg_op EAX) (Imm_op (zero_extend8_32 imm)) %% instruction_t)\n  |+|\n  (* word to EAX *)\n  op1 $$ \"101\" $$ imm_op opsize_override @\n    (fun imm => InstCon true (Reg_op EAX)  imm %% instruction_t)\n  |+|\n  (* zero-extend immediate byte to memory *)\n  \"1000\" $$ \"0000\" $$ ext_op_modrm op2 $ byte @ \n    (fun p => let (op,imm) := p in InstCon false op (Imm_op (zero_extend8_32 imm)) %% \n    instruction_t)\n  |+|\n  (* sign-extend immediate byte to memory *)\n  \"1000\" $$ \"0011\" $$ ext_op_modrm op2 $ byte @ \n    (fun p => let (op,imm) := p in InstCon true op (Imm_op (sign_extend8_32 imm)) %%\n    instruction_t)\n  |+|\n  (* immediate word to memory *)\n  \"1000\" $$ \"0001\" $$ ext_op_modrm op2 $ imm_op opsize_override @ \n    (fun p => let (op,imm) := p in InstCon true op imm %% instruction_t).\n\n  Definition ADC_p s := logic_or_arith_p s \"00010\" \"010\" ADC.\n  Definition ADD_p s := logic_or_arith_p s \"00000\" \"000\" ADD.\n  Definition AND_p s := logic_or_arith_p s \"00100\" \"100\" AND.\n  Definition CMP_p s := logic_or_arith_p s \"00111\" \"111\" CMP.\n  Definition OR_p  s := logic_or_arith_p s \"00001\" \"001\" OR.\n  Definition SBB_p s := logic_or_arith_p s \"00011\" \"011\" SBB.\n  Definition SUB_p s := logic_or_arith_p s \"00101\" \"101\" SUB.\n  Definition XOR_p s := logic_or_arith_p s \"00110\" \"110\" XOR.\n\n  Definition ARPL_p := \n  \"0110\" $$ \"0011\" $$ modrm @ \n    (fun p => let (op1,op2) := p in ARPL op1 op2 %% instruction_t).\n\n  Definition BOUND_p := \n  \"0110\" $$ \"0010\" $$ modrm @ \n    (fun p => let (op1,op2) := p in BOUND op1 op2 %% instruction_t).\n\n  Definition BSF_p := \n  \"0000\" $$ \"1111\" $$ \"1011\" $$ \"1100\" $$ modrm @ \n    (fun p => let (op1,op2) := p in BSF op1 op2 %% instruction_t).\n\n  Definition BSR_p := \n  \"0000\" $$ \"1111\" $$ \"1011\" $$ \"1101\" $$ modrm @ \n    (fun p => let (op1,op2) := p in BSR op1 op2 %% instruction_t).\n\n  Definition BSWAP_p := \n  \"0000\" $$ \"1111\" $$ \"1100\" $$ \"1\" $$ reg @ (fun x => BSWAP x %% instruction_t).\n\n  (* The various bit-testing operations can also share a parser *)\n  Definition bit_test_p (opcode1:string) (opcode2:string)\n    (Instr : operand -> operand -> instr) := \n    \"0000\" $$ \"1111\" $$ \"1011\" $$ \"1010\" $$ \"11\" $$ opcode1 $$ reg $ byte @ \n    (fun p => \n      let (r,imm) := p in Instr (Reg_op r) (Imm_op (zero_extend8_32 imm)) %% instruction_t)\n  |+| \n    \"0000\" $$ \"1111\" $$ \"1011\" $$ \"1010\" $$ ext_op_modrm opcode1 $ byte @\n    (fun p => \n      let (op1,imm) := p in Instr op1 (Imm_op (zero_extend8_32 imm)) %% instruction_t)\n  |+|\n    \"0000\" $$ \"1111\" $$ \"101\" $$ opcode2 $$ \"011\" $$ modrm @\n    (fun p => let (op2,op1) := p in Instr op1 op2 %% instruction_t).\n\n  Definition BT_p := bit_test_p \"100\" \"00\" BT.\n  Definition BTC_p := bit_test_p \"111\" \"11\" BTC.\n  Definition BTR_p := bit_test_p \"110\" \"10\" BTR.\n  Definition BTS_p := bit_test_p \"101\" \"01\" BTS.\n\n  Definition CALL_p := \n    \"1110\" $$ \"1000\" $$ word  @ \n    (fun w => CALL true false (Imm_op w) None %% instruction_t)\n  |+|\n    \"1111\" $$ \"1111\" $$ ext_op_modrm2 \"010\" @ \n    (fun op => CALL true true op None %% instruction_t)\n  |+| \n    \"1001\" $$ \"1010\" $$ halfword $ word @ \n    (fun p => CALL false false (Imm_op (snd p)) (Some (fst p)) %% instruction_t)\n  |+|\n    \"1111\" $$ \"1111\" $$ ext_op_modrm2 \"011\" @ \n    (fun op => CALL false true op None %% instruction_t).\n\n  Definition CDQ_p := \"1001\" $$ bits \"1001\" @ (fun _ => CDQ %% instruction_t).\n  Definition CLC_p := \"1111\" $$ bits \"1000\" @ (fun _ => CLC %% instruction_t).\n  Definition CLD_p := \"1111\" $$ bits \"1100\" @ (fun _ => CLD %% instruction_t).\n  Definition CLI_p := \"1111\" $$ bits \"1010\" @ (fun _ => CLI %% instruction_t).\n  Definition CLTS_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ bits \"0110\" @ \n    (fun _ => CLTS %% instruction_t).\n  Definition CMC_p := \"1111\" $$ bits \"0101\" @ (fun _ => CMC %% instruction_t).\n  Definition CMPS_p := \"1010\" $$ \"011\" $$ anybit @ (fun x => CMPS x %% instruction_t).\n  Definition CMPXCHG_p := \n   \"0000\" $$ \"1111\" $$ \"1011\" $$ \"000\" $$ anybit $ modrm @ \n    (fun p => match p with \n                | (w,(op1,op2)) => CMPXCHG w op2 op1\n              end %% instruction_t).\n\n  Definition CPUID_p := \"0000\" $$ \"1111\" $$ \"1010\" $$ bits \"0010\" @ \n    (fun _ => CPUID %% instruction_t).\n  Definition CWDE_p := \"1001\" $$ bits \"1000\" @ (fun _ => CWDE %% instruction_t).\n  Definition DAA_p := \"0010\" $$ bits \"0111\" @ (fun _ => DAA %% instruction_t).\n  Definition DAS_p := \"0010\" $$ bits \"1111\" @ (fun _ => DAS %% instruction_t).\n\n  Definition DEC_p := \n    \"1111\" $$ \"111\" $$ anybit $ \"11001\" $$ reg @ \n      (fun p => let (w,r) := p in DEC w (Reg_op r) %% instruction_t)\n  |+|\n    \"0100\" $$ \"1\" $$ reg @ \n      (fun r => DEC true (Reg_op r) %% instruction_t)\n  |+| \n    \"1111\" $$ \"111\" $$ anybit $ ext_op_modrm \"001\" @\n      (fun p => let (w,op1) := p in DEC w op1 %% instruction_t).\n\n  Definition DIV_p := \n    \"1111\" $$ \"011\" $$ anybit $ \"11110\" $$ reg @ \n      (fun p => let (w,r) := p in DIV w (Reg_op r) %% instruction_t)\n  |+| \n    \"1111\" $$ \"011\" $$ anybit $ ext_op_modrm \"110\" @ \n      (fun p => let (w,op1) := p in DIV w op1 %% instruction_t).\n\n  Definition HLT_p := \"1111\" $$ bits \"0100\" @ (fun _ => HLT %% instruction_t).\n\n  Definition IDIV_p := \n    \"1111\" $$ \"011\" $$ anybit $ \"11111\" $$ reg @ \n    (fun p => let (w,r) := p in IDIV w (Reg_op r) %% instruction_t)\n  |+|\n    \"1111\" $$ \"011\" $$ anybit $ ext_op_modrm \"111\" @ \n     (fun p => let (w,op1) := p in IDIV w op1 %% instruction_t).\n\n  Definition IMUL_p opsize_override := \n    \"1111\" $$ \"011\" $$ anybit $ ext_op_modrm2 \"101\" @\n    (fun p => let (w,op1) := p in IMUL w op1 None None %% instruction_t)\n  |+|\n    \"0000\" $$ \"1111\" $$ \"1010\" $$ \"1111\" $$ modrm @\n    (fun p => let (op1,op2) := p in IMUL true op1 (Some op2) None %% instruction_t)\n  |+|\n    \"0110\" $$ \"1011\" $$ modrm $ byte @\n    (fun p => match p with \n                | ((op1,op2),imm) => \n                  IMUL true op1 (Some op2) (Some (sign_extend8_32 imm))\n              end %% instruction_t)\n  |+|\n    match opsize_override with\n      | false =>\n          \"0110\" $$ \"1001\" $$ modrm $ word @\n           (fun p => match p with \n                | ((op1,op2),imm) => \n                  IMUL true op1 (Some op2) (Some imm)\n              end  %% instruction_t)\n      | true => \n          \"0110\" $$ \"1001\" $$ modrm $ halfword @\n           (fun p => match p with \n                | ((op1,op2),imm) => \n                  IMUL true op1 (Some op2) (Some (sign_extend16_32 imm))\n              end  %% instruction_t)\n    end.\n\n  Definition IN_p := \n    \"1110\" $$ \"010\" $$ anybit $ byte @ \n    (fun p => let (w,pt) := p in IN w (Some pt) %% instruction_t)\n  |+|\n    \"1110\" $$ \"110\" $$ anybit @ (fun w => IN w None %% instruction_t).\n\n  Definition INC_p := \n    \"1111\" $$ \"111\" $$ anybit  $ \"11000\" $$ reg @ \n      (fun p => let (w,r) := p in INC w (Reg_op r) %% instruction_t)\n  |+|\n    \"0100\" $$ \"0\" $$ reg @ (fun r => INC true (Reg_op r) %% instruction_t)\n  |+|\n    \"1111\" $$ \"111\" $$ anybit $ ext_op_modrm \"000\" @ \n       (fun p => let (w,op1) := p in INC w op1 %% instruction_t).\n\n  Definition INS_p := \"0110\" $$ \"110\" $$ anybit @ (fun x => INS x %% instruction_t).\n\n  Definition INTn_p := \"1100\" $$ \"1101\" $$ byte @ (fun x => INTn x %% instruction_t).\n  Definition INT_p := \"1100\" $$ bits \"1100\" @ (fun _ => INT %% instruction_t).\n\n  Definition INTO_p := \"1100\" $$ bits \"1110\" @ (fun _ => INTO %% instruction_t).\n  Definition INVD_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ bits \"1000\" @ \n    (fun _ => INVD %% instruction_t).\n\n  Definition INVLPG_p := \n    \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0001\" $$ ext_op_modrm \"111\" @ \n    (fun x => INVLPG x %% instruction_t).\n\n  Definition IRET_p := \"1100\" $$ bits \"1111\" @ (fun _ => IRET %% instruction_t).\n\n  Definition Jcc_p := \n    \"0111\" $$ tttn $ byte @ \n    (fun p => let (ct,imm) := p in Jcc ct (sign_extend8_32 imm) %% instruction_t)\n  |+|\n    \"0000\" $$ \"1111\" $$ \"1000\" $$ tttn $ word @ \n    (fun p => let (ct,imm) := p in Jcc ct imm %% instruction_t).\n\n  Definition JCXZ_p := \"1110\" $$ \"0011\" $$ byte @ (fun x => JCXZ x %% instruction_t).\n\n  Definition JMP_p := \n    \"1110\" $$ \"1011\" $$ byte @\n    (fun b => JMP true false (Imm_op (sign_extend8_32 b)) None %% instruction_t)\n  |+|\n    \"1110\" $$ \"1001\" $$ word @ \n    (fun w => JMP true false (Imm_op w) None %% instruction_t)\n  |+|\n    \"1111\" $$ \"1111\" $$ ext_op_modrm2 \"100\" @ \n    (fun op => JMP true true op None %% instruction_t)\n  |+|\n    \"1110\" $$ \"1010\" $$ halfword $ word @ \n      (fun p => JMP false true (Imm_op (snd p)) (Some (fst p)) %% instruction_t)\n  |+|\n    \"1111\" $$ \"1111\" $$ ext_op_modrm2 \"101\" @ \n    (fun op => JMP false true op None %% instruction_t).\n\n  Definition LAHF_p := \"1001\" $$ bits \"1111\" @ (fun _ => LAHF %% instruction_t).\n\n  Definition LAR_p := \n    \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0010\" $$ modrm @ \n      (fun p => LAR (fst p) (snd p) %% instruction_t).\n\n  Definition LDS_p := \"1100\" $$ \"0101\" $$ modrm @ \n    (fun p => LDS (fst p) (snd p) %% instruction_t).\n  Definition LEA_p := \"1000\" $$ \"1101\" $$ modrm_noreg @ \n    (fun p => LEA (Reg_op (fst p)) (snd p) %% instruction_t).\n  Definition LEAVE_p := \"1100\" $$ bits \"1001\" @ \n    (fun _ => LEAVE %% instruction_t).\n  Definition LES_p := \"1100\" $$ \"0100\" $$ modrm @ \n    (fun p => LES (fst p) (snd p) %% instruction_t).\n  Definition LFS_p := \"0000\" $$ \"1111\" $$ \"1011\" $$ \"0100\" $$ modrm @ \n    (fun p => LFS (fst p) (snd p) %% instruction_t).\n  Definition LGDT_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0001\" $$ ext_op_modrm \"010\" @ \n    (fun x => LGDT x %% instruction_t).\n  Definition LGS_p := \"0000\" $$ \"1111\" $$ \"1011\" $$ \"0101\" $$ modrm @ \n    (fun p => LGS (fst p) (snd p) %% instruction_t).\n  Definition LIDT_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0001\" $$ ext_op_modrm \"011\" @ \n    (fun x => LIDT x %% instruction_t).\n  Definition LLDT_p := \n    \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0000\" $$ \"11\" $$ \"010\" $$ reg @ \n    (fun r => LLDT (Reg_op r) %% instruction_t)\n  |+| \n    \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0000\" $$ ext_op_modrm \"010\" @ \n    (fun x => LLDT x %% instruction_t).\n\n  Definition LMSW_p := \n    \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0001\" $$ \"11\" $$ \"110\" $$ reg @ \n      (fun r => LMSW (Reg_op r) %% instruction_t)\n  |+|\n    \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0001\" $$ \"11\" $$ ext_op_modrm \"110\" @ \n      (fun x => LMSW x %% instruction_t).\n\n  (* JGM: note, this isn't really an instruction, but rather a prefix.  So it\n     shouldn't be included in the list of instruction parsers. *)\n(*  Definition LOCK_p := \"1111\" $$ bits \"0000\" @ (fun _ => LOCK %% instruction_t). *)\n  Definition LODS_p := \"1010\" $$ \"110\" $$ anybit @ (fun x => LODS x %% instruction_t).\n  Definition LOOP_p := \"1110\" $$ \"0010\" $$ byte @ (fun x => LOOP x %% instruction_t).\n  Definition LOOPZ_p := \"1110\" $$ \"0001\" $$ byte @ (fun x => LOOPZ x %% instruction_t).\n  Definition LOOPNZ_p := \"1110\" $$ \"0000\" $$ byte @ (fun x => LOOPNZ x %% instruction_t).\n  Definition LSL_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0011\" $$ modrm @ \n    (fun p => LSL (fst p) (snd p) %% instruction_t).\n  Definition LSS_p := \"0000\" $$ \"1111\" $$ \"1011\" $$ \"0010\" $$ modrm @ \n    (fun p => LSS (fst p) (snd p) %% instruction_t).\n  Definition LTR_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0000\" $$ ext_op_modrm \"011\" @ \n    (fun x => LTR x %% instruction_t).\n\n  (* This is may not be right. Need to test this thoroughly. \n     There is no 8bit mode for CMOVcc *)\n\n  Definition CMOVcc_p :=\n    \"0000\" $$ \"1111\" $$ \"0100\" $$ tttn $ modrm @\n    (fun p => match p with | (tttn, (op1, op2))=>CMOVcc tttn op1 op2 end %% instruction_t).\n\n  Definition MOV_p opsize_override := \n    \"1000\" $$ \"101\" $$ anybit $ modrm @ \n      (fun p => match p with | (w,(op1,op2)) => MOV w op1 op2 end %% instruction_t)\n  |+|\n    \"1000\" $$ \"100\" $$ anybit $ modrm @ \n      (fun p => match p with | (w,(op1,op2)) => MOV w op2 op1 end %% instruction_t)\n  |+|\n   \"1100\" $$ \"0111\" $$ \"11\" $$ \"000\" $$ reg $ imm_op opsize_override @\n     (fun p => match p with | (r,w) => MOV true  (Reg_op r) w end %% instruction_t)\n  |+|\n   \"1100\" $$ \"0110\" $$ \"11\" $$ \"000\" $$ reg $ byte @\n     (fun p => match p with\n                 | (r,b) => MOV false (Reg_op r) (Imm_op (zero_extend8_32 b)) \n               end %% instruction_t)\n  |+|\n    \"1011\" $$ \"1\" $$ reg $ imm_op opsize_override @ \n      (fun p => match p with | (r,w) => MOV true (Reg_op r)  w\n                end %% instruction_t)\n  |+| \n    \"1011\" $$ \"0\" $$ reg $ byte @ \n      (fun p => match p with \n                  | (r,b) => MOV false (Reg_op r) (Imm_op (zero_extend8_32 b))\n                end %% instruction_t)\n  |+|\n    \"1100\" $$ \"0111\" $$ ext_op_modrm \"000\" $ imm_op opsize_override @ \n      (fun p => match p with | (op,w) => MOV true op w end %% instruction_t)\n  |+|\n    \"1100\" $$ \"0110\" $$ ext_op_modrm \"000\" $ byte @ \n    (fun p => match p with | (op,b) => MOV false op (Imm_op (zero_extend8_32 b)) end %% instruction_t)\n  |+|\n    \"1010\" $$ \"0001\" $$ word @ (fun w => MOV true  (Reg_op EAX) (Offset_op w) %% instruction_t)\n  |+|\n    \"1010\" $$ \"0000\" $$ word @ (fun w => MOV false (Reg_op EAX) (Offset_op w)  %% instruction_t)\n  |+|\n    \"1010\" $$ \"0011\" $$ word @ (fun w => MOV true (Offset_op w) (Reg_op EAX) %% instruction_t)\n  |+|\n    \"1010\" $$ \"0010\" $$ word @ (fun w => MOV false (Offset_op w) (Reg_op EAX) %% instruction_t).\n  \n\n  Definition control_reg_p := \n      bits \"000\" @ (fun _ => CR0 %% control_register_t) \n  |+| bits \"010\" @ (fun _ => CR2 %% control_register_t) \n  |+| bits \"011\" @ (fun _ => CR3 %% control_register_t) \n  |+| bits \"100\" @ (fun _ => CR4 %% control_register_t).\n  \n  Definition MOVCR_p := \n    \"0000\" $$ \"1111\" $$ \"0010\" $$ \"0010\" $$ \"11\" $$ control_reg_p $ reg @ \n    (fun p => MOVCR false (fst p) (snd p) %% instruction_t)\n  |+|\n    \"0000\" $$ \"1111\" $$ \"0010\" $$ \"0000\" $$ \"11\" $$ control_reg_p $ reg @ \n    (fun p => MOVCR true (fst p) (snd p) %% instruction_t).\n\n  (* Note:  apparently, the bit patterns corresponding to DR4 and DR5 either\n   * (a) get mapped to DR6 and DR7 respectively or else (b) cause a fault,\n   * depending upon the value of some control register.  My guess is that it's\n   * okay for us to just consider this a fault. Something similar seems to\n   * happen with the CR registers above -- e.g., we don't have a CR1. *)\n  Definition debug_reg_p := \n      bits \"000\" @ (fun _ => DR0 %% debug_register_t) \n  |+| bits \"001\" @ (fun _ => DR1 %% debug_register_t) \n  |+| bits \"010\" @ (fun _ => DR2 %% debug_register_t) \n  |+| bits \"011\" @ (fun _ => DR3 %% debug_register_t) \n  |+| bits \"110\" @ (fun _ => DR6 %% debug_register_t) \n  |+| bits \"111\" @ (fun _ => DR7 %% debug_register_t).\n\n  Definition MOVDR_p := \n    \"0000\" $$ \"1111\" $$ \"0010\" $$ \"0011\" $$ \"11\" $$ debug_reg_p $ reg @\n    (fun p => MOVDR false (fst p) (snd p) %% instruction_t)\n  |+|\n    \"0000\" $$ \"1111\" $$ \"0010\" $$ \"0001\" $$ \"11\" $$ debug_reg_p $ reg @\n    (fun p => MOVDR true (fst p) (snd p) %% instruction_t).\n\n  Definition segment_reg_p := \n      bits \"000\" @ (fun _ => ES %% segment_register_t) \n  |+| bits \"001\" @ (fun _ => CS %% segment_register_t) \n  |+| bits \"010\" @ (fun _ => SS %% segment_register_t) \n  |+| bits \"011\" @ (fun _ => DS %% segment_register_t) \n  |+| bits \"100\" @ (fun _ => FS %% segment_register_t) \n  |+| bits \"101\" @ (fun _ => GS %% segment_register_t).\n\n  Definition seg_modrm : parser (pair_t segment_register_t operand_t) := \n        (\"00\" $$ segment_reg_p $ rm00)\n    |+| (\"01\" $$ segment_reg_p $ rm01)\n    |+| (\"10\" $$ segment_reg_p $ rm10)\n    |+| (\"11\" $$ segment_reg_p $ rm11).\n\n  Definition MOVSR_p := \n    \"1000\" $$ \"1110\" $$ seg_modrm @ \n      (fun p => MOVSR false (fst p) (snd p) %% instruction_t)\n  |+|\n    \"1000\" $$ \"1100\" $$ seg_modrm @ \n     (fun p => MOVSR true (fst p) (snd p) %% instruction_t).\n\n  Definition MOVBE_p := \n    \"0000\" $$ \"1111\" $$ \"0011\" $$ \"1000\" $$ \"1111\" $$ \"0000\" $$ modrm @\n    (fun p => MOVBE (snd p) (fst p) %% instruction_t)\n  |+|\n    \"0000\" $$ \"1111\" $$ \"0011\" $$ \"1000\" $$ \"1111\" $$ \"0001\" $$ modrm @ \n    (fun p => MOVBE (fst p) (snd p) %% instruction_t).\n\n  Definition MOVS_p := \"1010\" $$ \"010\" $$ anybit @ (fun x => MOVS x %% instruction_t).\n\n  Definition MOVSX_p := \"0000\" $$ \"1111\" $$ \"1011\" $$ \"111\" $$ anybit $ modrm @\n    (fun p => match p with | (w,(op1,op2)) => MOVSX w op1 op2 end %% instruction_t).\n\n  Definition MOVZX_p := \"0000\" $$ \"1111\" $$ \"1011\" $$ \"011\" $$ anybit $ modrm @\n    (fun p => match p with | (w,(op1,op2)) => MOVZX w op1 op2 end %% instruction_t).\n\n  Definition MUL_p := \n  \"1111\" $$ \"011\" $$ anybit $ ext_op_modrm2 \"100\" @ \n    (fun p => MUL (fst p) (snd p) %% instruction_t).\n\n  Definition NEG_p := \n  \"1111\" $$ \"011\" $$ anybit $ ext_op_modrm2 \"011\" @ \n    (fun p => NEG (fst p) (snd p) %% instruction_t).\n\n  (*\n  Definition NOP_p := \n    \"1001\" $$ bits \"0000\" @ (fun _ => NOP None %% instruction_t)\n  |+|\n    \"0000\" $$ \"1111\" $$ \"0001\" $$ \"1111\" $$ ext_op_modrm \"000\" @ \n    (fun op => NOP (Some op) %% instruction_t).\n  *)\n\n  Definition NOT_p := \n    \"1111\" $$ \"011\" $$ anybit $ ext_op_modrm2 \"010\" @ \n    (fun p => NOT (fst p) (snd p) %% instruction_t).\n\n  Definition OUT_p := \n    \"1110\" $$ \"011\" $$ anybit $ byte @ \n      (fun p => OUT (fst p) (Some (snd p)) %% instruction_t)\n  |+|\n    \"1110\" $$ \"111\" $$ anybit @ (fun w => OUT w None %% instruction_t).\n\n  Definition OUTS_p := \"0110\" $$ \"111\" $$ anybit @ (fun x => OUTS x %% instruction_t).\n\n  Definition POP_p := \n  \"1000\" $$ \"1111\" $$ ext_op_modrm \"000\" @ (fun x => POP x %% instruction_t)\n  |+|\n    \"0101\" $$ \"1\" $$ reg @ (fun r => POP (Reg_op r) %% instruction_t).\n\n  Definition POPSR_p := \n    \"000\" $$ \"00\" $$ bits \"111\" @ (fun _ => POPSR ES %% instruction_t)\n  |+|\n    \"000\" $$ \"10\" $$ bits \"111\" @ (fun _ => POPSR SS %% instruction_t)\n  |+|\n    \"000\" $$ \"11\" $$ bits \"111\" @ (fun _ => POPSR DS %% instruction_t)\n  |+|\n    \"0000\" $$ \"1111\" $$ \"10\" $$ \"100\" $$ bits \"001\" @ \n      (fun _ => POPSR FS %% instruction_t)\n  |+|\n    \"0000\" $$ \"1111\" $$ \"10\" $$ \"101\" $$ bits \"001\" @ \n      (fun _ => POPSR GS %% instruction_t).\n\n  Definition POPA_p := \"0110\" $$ bits \"0001\" @ (fun _ => POPA %% instruction_t).\n  Definition POPF_p := \"1001\" $$ bits \"1101\" @ (fun _ => POPF %% instruction_t).\n  \n  Definition PUSH_p := \n    \"1111\" $$ \"1111\" $$ ext_op_modrm \"110\" @ (fun x => PUSH true x %% instruction_t)\n  |+|\n    \"0101\" $$ \"0\" $$ reg @ (fun r => PUSH true (Reg_op r) %% instruction_t)\n  |+|\n    \"0110\" $$ \"1010\" $$ byte @ \n    (fun b => PUSH false (Imm_op (sign_extend8_32 b)) %% instruction_t)\n  |+|\n    \"0110\" $$ \"1000\" $$ word @ (fun w => PUSH true (Imm_op w) %% instruction_t).\n\n  Definition segment_reg2_p := \n        bits \"00\" @ (fun _ => ES %% segment_register_t) \n    |+| bits \"01\" @ (fun _ => CS %% segment_register_t) \n    |+| bits \"10\" @ (fun _ => SS %% segment_register_t) \n    |+| bits \"11\" @ (fun _ => DS %% segment_register_t).\n\n  Definition PUSHSR_p := \n    \"000\" $$ segment_reg2_p $ bits \"110\" @ \n    (fun p => PUSHSR (fst p) %% instruction_t)\n  |+|\n    \"0000\" $$ \"1111\" $$ \"10\" $$ \"100\" $$ bits \"000\" @ \n    (fun _ => PUSHSR FS %% instruction_t)\n  |+|\n    \"0000\" $$ \"1111\" $$ \"10\" $$ \"101\" $$ bits \"000\" @ \n    (fun _ => PUSHSR GS %% instruction_t).\n\n  Definition PUSHA_p := \"0110\" $$ bits \"0000\" @ (fun _ => PUSHA %% instruction_t).\n  Definition PUSHF_p := \"1001\" $$ bits \"1100\" @ (fun _ => PUSHF %% instruction_t).\n\n  Definition rotate_p extop (inst : bool -> operand -> reg_or_immed -> instr) := \n    \"1101\" $$ \"000\" $$ anybit $ ext_op_modrm2 extop @ \n    (fun p => inst (fst p) (snd p) (Imm_ri (Word.repr 1)) %% instruction_t)\n  |+|\n    \"1101\" $$ \"001\" $$ anybit $ ext_op_modrm2 extop @\n    (fun p => inst (fst p) (snd p) (Reg_ri ECX) %% instruction_t)\n  |+|\n    \"1100\" $$ \"000\" $$ anybit $ ext_op_modrm2 extop $ byte @\n    (fun p => match p with | (w, (op,b)) => inst w op (Imm_ri b) end %% instruction_t).\n\n  Definition RCL_p := rotate_p \"010\" RCL.\n  Definition RCR_p := rotate_p \"011\" RCR.\n\n  Definition RDMSR_p := \"0000\" $$ \"1111\" $$ \"0011\" $$ bits \"0010\" @ \n    (fun _ => RDMSR %% instruction_t).\n  Definition RDPMC_p := \"0000\" $$ \"1111\" $$ \"0011\" $$ bits \"0011\" @ \n    (fun _ => RDPMC %% instruction_t).\n  Definition RDTSC_p := \"0000\" $$ \"1111\" $$ \"0011\" $$ bits \"0001\" @ \n    (fun _ => RDTSC %% instruction_t).\n  Definition RDTSCP_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0001\" $$ \"1111\" $$ bits \"1001\" @\n    (fun _ => RDTSCP %% instruction_t).\n\n  (*\n  Definition REPINS_p := \"1111\" $$ \"0011\" $$ \"0110\" $$ \"110\" $$ anybit @ \n    (fun x => REPINS x %% instruction_t).\n  Definition REPLODS_p := \"1111\" $$ \"0011\" $$ \"1010\" $$ \"110\" $$ anybit @ \n    (fun x => REPLODS x %% instruction_t).\n  Definition REPMOVS_p := \"1111\" $$ \"0011\" $$ \"1010\" $$ \"010\" $$ anybit @ \n    (fun x => REPMOVS x %% instruction_t).\n  Definition REPOUTS_p := \"1111\" $$ \"0011\" $$ \"0110\" $$ \"111\" $$ anybit @ \n    (fun x => REPOUTS x %% instruction_t).\n  Definition REPSTOS_p := \"1111\" $$ \"0011\" $$ \"1010\" $$ \"101\" $$ anybit @ \n    (fun x => REPSTOS x %% instruction_t).\n  Definition REPECMPS_p := \"1111\" $$ \"0011\" $$ \"1010\" $$ \"011\" $$ anybit @ \n    (fun x => REPECMPS x %% instruction_t).\n  Definition REPESCAS_p := \"1111\" $$ \"0011\" $$ \"1010\" $$ \"111\" $$ anybit @ \n    (fun x => REPESCAS x %% instruction_t).\n  Definition REPNECMPS_p := \"1111\" $$ \"0010\" $$ \"1010\" $$ \"011\" $$ anybit @ \n    (fun x => REPNECMPS x %% instruction_t).\n  Definition REPNESCAS_p := \"1111\" $$ \"0010\" $$ \"1010\" $$ \"111\" $$ anybit @ \n    (fun x => REPNESCAS x %% instruction_t).\n  *)\n\n  Definition RET_p := \n    \"1100\" $$ bits \"0011\" @ (fun _ => RET true None %% instruction_t)\n  |+|\n    \"1100\" $$ \"0010\" $$ halfword @ (fun h => RET true (Some h) %% instruction_t)\n  |+|\n    \"1100\" $$ bits \"1011\" @ (fun _ => RET false None %% instruction_t)\n  |+|\n    \"1100\" $$ \"1010\" $$ halfword @ (fun h => RET false (Some h) %% instruction_t).\n\n  Definition ROL_p := rotate_p \"000\" ROL.\n  Definition ROR_p := rotate_p \"001\" ROR.\n  Definition RSM_p := \"0000\" $$ \"1111\" $$ \"1010\" $$ bits \"1010\" @ \n    (fun _ => RSM %% instruction_t).\n  Definition SAHF_p := \"1001\" $$ bits \"1110\" @ \n    (fun _ => SAHF %% instruction_t).\n  Definition SAR_p := rotate_p \"111\" SAR.\n  Definition SCAS_p := \"1010\" $$ \"111\" $$ anybit @ (fun x => SCAS x %% instruction_t).\n  Definition SETcc_p := \n  \"0000\" $$ \"1111\" $$ \"1001\" $$ tttn $ modrm @ \n    (fun p => SETcc (fst p) (snd (snd p)) %% instruction_t).\n  Definition SGDT_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0001\" $$ ext_op_modrm \"000\" @ \n    (fun x => SGDT x %% instruction_t).\n  Definition SHL_p := rotate_p \"100\" SHL.\n\n  Definition shiftdouble_p opcode inst :=\n    (\"0000\" $$ \"1111\" $$ \"1010\" $$ opcode $$ \"00\" $$ \"11\" $$ reg $ reg $ byte) @\n    (fun p => match p with | (r2,(r1,b)) => inst (Reg_op r1) r2 (Imm_ri b) end %% instruction_t)\n  |+|\n    (\"0000\" $$ \"1111\" $$ \"1010\" $$ opcode $$ \"00\" $$ modrm_noreg $ byte) @\n    (fun p => match p with | ((r,op), b) => inst op r (Imm_ri b) end %% instruction_t)\n  |+|\n    (\"0000\" $$ \"1111\" $$ \"1010\" $$ opcode $$ \"01\" $$ \"11\" $$ reg $ reg) @\n    (fun p => match p with | (r2,r1) => inst (Reg_op r1) r2 (Reg_ri ECX) end %% instruction_t)\n  |+|\n    (\"0000\" $$ \"1111\" $$ \"1010\" $$ opcode $$ \"01\" $$ modrm_noreg) @\n    (fun p => match p with | (r,op) => inst op r (Reg_ri ECX) end %% instruction_t).\n \n  Definition SHLD_p := shiftdouble_p \"01\" SHLD.\n  Definition SHR_p := rotate_p \"101\" SHR.\n  Definition SHRD_p := shiftdouble_p \"11\" SHRD.\n  Definition SIDT_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0001\" $$ ext_op_modrm \"001\" @ \n    (fun x => SIDT x %% instruction_t).\n  Definition SLDT_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0000\" $$ ext_op_modrm \"000\" @ \n    (fun x => SLDT x %% instruction_t).\n  Definition SMSW_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0001\" $$ ext_op_modrm \"100\" @ \n    (fun x => SMSW x %% instruction_t).\n  Definition STC_p := \"1111\" $$ bits \"1001\" @ (fun _ => STC %% instruction_t).\n  Definition STD_p := \"1111\" $$ bits \"1101\" @ (fun _ => STD %% instruction_t).\n  Definition STI_p := \"1111\" $$ bits \"1011\" @ (fun _ => STI %% instruction_t).\n  Definition STOS_p := \"1010\" $$ \"101\" $$ anybit @ \n    (fun x => STOS x %% instruction_t).\n  Definition STR_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0000\" $$ ext_op_modrm \"001\" @ \n    (fun x => STR x  %% instruction_t).\n \n  Definition TEST_p (opsize_override: bool) := \n    \"1111\" $$ \"0111\" $$ ext_op_modrm2 \"000\" $ imm_op opsize_override @ \n    (fun p => TEST true (fst p) (snd p) %% instruction_t)\n  |+| \n    \"1111\" $$ \"0110\" $$ ext_op_modrm2 \"000\" $ byte @ \n    (fun p => TEST false (fst p) (Imm_op (zero_extend8_32 (snd p))) %% instruction_t)\n  |+|\n    \"1000\" $$ \"010\" $$ anybit $ modrm @\n    (fun p => match p with | (w,(op1,op2)) => TEST w op1 op2 end %% instruction_t)\n  |+|\n    \"1010\" $$ \"1001\" $$ imm_op opsize_override @ (fun w => TEST true w (Reg_op EAX) %% instruction_t)\n  |+|\n    \"1010\" $$ \"1000\" $$ byte @ \n    (fun b => TEST true (Imm_op (zero_extend8_32 b)) (Reg_op EAX) %% instruction_t).\n  \n  Definition UD2_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ bits \"1011\" @ \n    (fun _ => UD2 %% instruction_t).\n\n  Definition VERR_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0000\" $$ ext_op_modrm \"100\" @ \n    (fun x => VERR x %% instruction_t).\n  Definition VERW_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ \"0000\" $$ ext_op_modrm \"101\" @ \n    (fun x => VERW x %% instruction_t).\n  Definition WAIT_p := \"1001\" $$ bits \"1011 \" @ (fun _ => WAIT %% instruction_t).\n  Definition WBINVD_p := \"0000\" $$ \"1111\" $$ \"0000\" $$ bits \"1001\" @ \n    (fun _ => WBINVD %% instruction_t).\n  Definition WRMSR_p := \"0000\" $$ \"1111\" $$ \"0011\" $$ bits \"0000\" @ \n    (fun _ => WRMSR %% instruction_t).\n  Definition XADD_p := \n    \"0000\" $$ \"1111\" $$ \"1100\" $$ \"000\" $$ anybit $ modrm @ \n    (fun p => match p with | (w,(op1,op2)) => XADD w op2 op1 end %% instruction_t).\n  Definition XCHG_p := \n    \"1000\" $$ \"011\" $$ anybit $ modrm @ \n    (fun p => match p with | (w,(op1,op2)) => XCHG w op1 op2 end %% instruction_t)\n  |+|\n    \"1001\" $$ \"0\" $$ reg @ (fun r => XCHG true (Reg_op EAX) (Reg_op r) %% instruction_t).\n\n  Definition XLAT_p := \"1101\" $$ bits \"0111\" @ (fun _ => XLAT %% instruction_t).\n\n  (* Now glue all of the individual instruction parsers together into \n     one big parser. *)\n  \n  Definition instr_parsers_opsize_pre : list (parser instruction_t) :=\n    ADC_p true :: ADD_p true :: AND_p true :: CMP_p true :: OR_p true :: SBB_p true :: SUB_p true :: SHL_p :: SHLD_p :: SHR_p :: SAR_p :: SHRD_p :: XOR_p true ::IMUL_p true :: MOV_p true :: MOVSX_p :: MOVZX_p :: NEG_p :: NOT_p :: DIV_p :: IDIV_p :: TEST_p true :: CDQ_p :: CWDE_p :: MUL_p :: XCHG_p :: nil.\n\n  Definition instr_parsers_nosize_pre : list (parser instruction_t) := \n    AAA_p :: AAD_p :: AAM_p :: AAS_p :: ADC_p false :: ADD_p false :: AND_p false :: CMP_p false :: OR_p false :: SBB_p false :: SUB_p false :: XOR_p false :: ARPL_p :: BOUND_p :: BSF_p :: BSR_p :: BSWAP_p :: BT_p :: BTC_p :: BTR_p :: BTS_p :: CALL_p :: CDQ_p :: CLC_p :: CLD_p :: CLI_p :: CMOVcc_p :: CMC_p :: CMPS_p :: CMPXCHG_p :: CPUID_p :: CWDE_p :: DAA_p :: DAS_p :: DEC_p :: DIV_p :: HLT_p :: IDIV_p :: IMUL_p false :: IN_p :: INC_p :: INS_p :: INTn_p :: INT_p :: INTO_p :: INVD_p :: INVLPG_p :: IRET_p :: Jcc_p :: JCXZ_p :: JMP_p :: LAHF_p :: LAR_p :: LDS_p :: LEA_p :: LEAVE_p :: LES_p :: LFS_p :: LGDT_p :: LGS_p :: LIDT_p :: LLDT_p :: LMSW_p :: (* LOCK_p :: -- see note above about LOCK_p *) LODS_p :: LOOP_p :: LOOPZ_p :: LOOPNZ_p :: LSL_p :: LSS_p :: LTR_p :: MOV_p false :: MOVCR_p :: MOVDR_p :: MOVSR_p :: MOVBE_p :: MOVS_p :: MOVSX_p :: MOVZX_p :: MUL_p :: NEG_p :: (* NOP_p :: *) NOT_p :: OUT_p :: OUTS_p :: POP_p :: POPSR_p :: POPA_p :: POPF_p :: PUSH_p :: PUSHSR_p :: PUSHA_p :: PUSHF_p :: RCL_p :: RCR_p :: RDMSR_p :: RDPMC_p :: RDTSC_p :: RDTSCP_p :: (* REPINS_p :: REPLODS_p :: REPMOVS_p :: REPOUTS_p :: REPSTOS_p :: REPECMPS_p :: REPESCAS_p :: REPNECMPS_p :: REPNESCAS_p :: *) RET_p :: ROL_p :: ROR_p :: RSM_p :: SAHF_p :: SAR_p :: SCAS_p :: SETcc_p :: SGDT_p :: SHL_p :: SHLD_p :: SHR_p :: SHRD_p :: SIDT_p :: SLDT_p :: SMSW_p :: STC_p :: STD_p :: STI_p :: STOS_p :: STR_p :: TEST_p false :: UD2_p :: VERR_p :: VERW_p :: WAIT_p :: WBINVD_p :: WRMSR_p :: XADD_p :: XCHG_p :: XLAT_p :: nil.\n\n  Fixpoint list2pair_t (l: list result) :=\n    match l with\n      | nil => unit_t\n      | r::r'::nil => pair_t r r'\n      | r::l' => pair_t r (list2pair_t l')\n    end.\n \n\n  Definition lock_or_rep_p : parser lock_or_rep_t :=\n    (\"1111\" $$ ( bits \"0000\" @ (fun _ => lock %% lock_or_rep_t)\n                 |+| bits \"0010\" @ (fun _ => repn %% lock_or_rep_t)\n                 |+| bits \"0011\" @ (fun _ => rep  %% lock_or_rep_t))).\n\n  Definition segment_override_p : parser segment_register_t :=\n  (\"0010\" $$ bits \"1110\" @ (fun _ => CS %% segment_register_t)\n    |+| \"0011\" $$ bits \"0110\" @ (fun _ => SS %% segment_register_t)\n    |+| \"0011\" $$ bits \"1110\" @ (fun _ => DS %% segment_register_t)\n    |+| \"0010\" $$ bits \"0110\" @ (fun _ => ES %% segment_register_t)\n    |+| \"0110\" $$ bits \"0100\" @ (fun _ => FS %% segment_register_t)\n    |+| \"0110\" $$ bits \"0101\" @ (fun _ => GS %% segment_register_t)).\n\n  Definition op_override_p : parser bool_t :=\n    \"0110\" $$ bits \"0110\" @ (fun _ => true %% bool_t).\n  Definition addr_override_p : parser bool_t :=\n    \"0110\" $$ bits \"0111\" @ (fun _ => true %% bool_t).\n\n  (* Ok, now I want all permutations of the above four parsers. \n     I make a little perm2 combinator that takes two parsers and gives you\n     p1 $ p2 |+| p2 $ p1, making sure to swap the results in the second case *)\n  \n  Definition perm2 t1 t2 (p1: parser t1) (p2: parser t2) : parser (pair_t t1 t2) :=\n      p1 $ p2 |+|\n      p2 $ p1 @ (fun p => match p with (a, b) => (b, a) %% pair_t t1 t2 end).\n\n  (* Then I build that up into a perm3 and perm4. One could make a recursive\n     function to do this, but I didn't want to bother with the necessary\n     proofs and type-system juggling.*) \n\n  Definition perm3 t1 t2 t3 (p1: parser t1) (p2: parser t2) (p3: parser t3)\n    : parser (pair_t t1 (pair_t t2 t3)) :=\n    let r_t := pair_t t1 (pair_t t2 t3) in\n       p1 $ (perm2 p2 p3)\n   |+| p2 $ (perm2 p1 p3) @ (fun p => match p with (b, (a, c)) => (a, (b, c)) %% r_t end)\n   |+| p3 $ (perm2 p1 p2) @ (fun p => match p with (c, (a, b)) => (a, (b, c)) %% r_t end).\n\n  Definition perm4 t1 t2 t3 t4 (p1: parser t1) (p2: parser t2) (p3: parser t3)\n    (p4: parser t4) : parser (pair_t t1 (pair_t t2 (pair_t t3 t4))) :=\n    let r_t := pair_t t1 (pair_t t2 (pair_t t3 t4)) in\n       p1 $ (perm3 p2 p3 p4)\n   |+| p2 $ (perm3 p1 p3 p4) @ \n         (fun p => match p with (b, (a, (c, d))) => (a, (b, (c, d))) %% r_t end)\n   |+| p3 $ (perm3 p1 p2 p4) @ \n         (fun p => match p with (c, (a, (b, d))) => (a, (b, (c, d))) %% r_t end)\n   |+| p4 $ (perm3 p1 p2 p3) @ \n         (fun p => match p with (d, (a, (b, c))) => (a, (b, (c, d))) %% r_t end). \n\n  (* In this case, prefixes are optional. Before, each of the above\n     parsing rules for the prefixes accepted Eps, and this was how we\n     handled this.  However, if the parsers you join with perm can\n     each accept Eps, then the result is a _highly_ ambiguous parser.\n\n     Instead we have a different combinator, called option_perm, that \n     handles this without introducing extra ambiguity *)\n\n  (* This signature is slightly awkward - because there's no result\n     type corresponding to option (and I'm hesitant to add it to\n     Parser at the moment) we can't just have a signature like parser\n     t1 -> parser t2 -> parser (option_t t1) (option_t t2)) *)\n    \n  Definition option_perm2 t1 t2 (p1: parser (tipe_t t1)) (p2: parser (tipe_t t2)) \n     : parser (pair_t (option_t t1) (option_t t2)) :=\n     let r_t := pair_t (option_t t1) (option_t t2) in \n         Eps_p @ (fun p => (None, None) %% r_t)  \n     |+| p1 @ (fun p => (Some p, None) %% r_t ) \n     |+| p2 @ (fun p => (None, Some p) %% r_t) \n     |+| perm2 p1 p2 @ (fun p => match p with (a, b) => (Some a, Some b) %%r_t end). \n\n  Definition option_perm3 t1 t2 t3 (p1:parser(tipe_t t1)) (p2:parser(tipe_t t2))\n    (p3:parser(tipe_t t3)): parser(pair_t(option_t t1)(pair_t(option_t t2) (option_t t3)))\n    :=\n    let r_t := pair_t(option_t t1)(pair_t(option_t t2) (option_t t3))  in\n        Eps_p @ (fun p => (None, (None, None)) %% r_t)\n    |+| p1 @ (fun p => (Some p, (None, None)) %% r_t)\n    |+| p2 @ (fun p => (None, (Some p, None)) %% r_t)\n    |+| p3 @ (fun p => (None, (None, Some p)) %% r_t)\n    |+| perm2 p1 p2 @(fun p => match p with (a, b) => (Some a, (Some b, None)) %%r_t end)\n    |+| perm2 p1 p3 @(fun p => match p with (a, c) => (Some a, (None, Some c)) %%r_t end)\n    |+| perm2 p2 p3 @(fun p => match p with (b, c) => (None, (Some b, Some c)) %%r_t end)\n    |+| perm3 p1 p2 p3 @ (fun p => match p with (a, (b, c))\n                                    => (Some a, (Some b, Some c)) %%r_t end).\n\n  (* This is beginning to get quite nasty. Someone should write a form for arbitrary\n     n and prove it's correct :) *)\n  Definition option_perm4 t1 t2 t3 t4 (p1:parser(tipe_t t1)) (p2: parser(tipe_t t2))\n    (p3: parser(tipe_t t3)) (p4: parser(tipe_t t4)) :\n      parser(pair_t(option_t t1) (pair_t(option_t t2) (pair_t(option_t t3) (option_t t4))))\n      := \n    let r_t := pair_t(option_t t1) (pair_t(option_t t2)\n      (pair_t(option_t t3)(option_t t4))) in\n        Eps_p @ (fun p => (None, (None, (None, None))) %% r_t)\n    |+| p1 @ (fun p => (Some p, (None, (None, None))) %% r_t)\n    |+| p2 @ (fun p => (None, (Some p, (None, None))) %% r_t)\n    |+| p3 @ (fun p => (None, (None, (Some p, None))) %% r_t)\n    |+| p4 @ (fun p => (None, (None, (None, Some p))) %% r_t)\n    |+| perm2 p1 p2 @ (fun p => match p with (a, b)\n                                  => (Some a, (Some b, (None, None))) %% r_t end)\n    |+| perm2 p1 p3 @ (fun p => match p with (a, c)\n                                  => (Some a, (None, (Some c, None))) %% r_t end)\n    |+| perm2 p1 p4 @ (fun p => match p with (a, d)\n                                  => (Some a, (None, (None, Some d))) %% r_t end)\n    |+| perm2 p2 p3 @ (fun p => match p with (b, c)\n                                  => (None, (Some b, (Some c, None))) %% r_t end)\n    |+| perm2 p2 p4 @ (fun p => match p with (b, d)\n                                  => (None, (Some b, (None, Some d))) %% r_t end)\n    |+| perm2 p3 p4 @ (fun p => match p with (c, d)\n                                  => (None, (None, (Some c, Some d))) %% r_t end)\n    |+| perm3 p1 p2 p3 @ (fun p => match p with (a, (b, c))\n                                    => (Some a, (Some b, (Some c, None))) %%r_t end)\n    |+| perm3 p1 p3 p4 @ (fun p => match p with (a, (c, d))\n                                    => (Some a, (None, (Some c, Some d))) %%r_t end)\n    |+| perm3 p1 p2 p4 @ (fun p => match p with (a, (b, d))\n                                    => (Some a, (Some b, (None, Some d))) %%r_t end)\n    |+| perm3 p2 p3 p4 @ (fun p => match p with (b, (c, d))\n                                    => (None, (Some b, (Some c, Some d))) %%r_t end)\n    |+| perm4 p1 p2 p3 p4 @ (fun p => match p with (a, (b, (c, d)))\n                                        => (Some a, (Some b, (Some c, Some d))) %% r_t end).\n                                      \n  Definition opt2b (a: option bool) (default: bool) :=\n    match a with\n      | Some b => b\n      | None => default\n    end.\n  \n  Definition prefix_parser_nooverride := \n   option_perm2 lock_or_rep_p segment_override_p @ \n     (fun p => match p with (l, s) => \n                 mkPrefix l s false false %% prefix_t end).\n  Definition prefix_parser_opsize :=\n    op_override_p @ (fun p =>  mkPrefix None None p false %% prefix_t)\n    |+| op_override_p $ lock_or_rep_p @ \n        (fun p => match p with (b, l) => (mkPrefix (Some l) None b false %% prefix_t) end)\n\n    |+| op_override_p $ segment_override_p @\n        (fun p => match p with (b, s) => (mkPrefix None (Some s) b false %% prefix_t) end)\n\n    |+| op_override_p $ lock_or_rep_p $ segment_override_p @\n        (fun p => match p with (b, (l, s)) => \n                    (mkPrefix (Some l) (Some s) b false %% prefix_t) end)\n\n    |+| op_override_p $ segment_override_p $ lock_or_rep_p @\n        (fun p => match p with (b, (s, l)) =>\n                    (mkPrefix (Some l) (Some s) b false %% prefix_t) end)\n\n    |+| segment_override_p $ op_override_p @\n        (fun p => match p with (s, b) =>\n                    (mkPrefix None (Some s) b false %% prefix_t) end)\n\n    |+| segment_override_p $ op_override_p $ lock_or_rep_p @\n        (fun p => match p with (s, (b, l)) =>\n                    (mkPrefix (Some l) (Some s) b false %% prefix_t) end)\n\n    |+| segment_override_p $ lock_or_rep_p $ op_override_p  @\n        (fun p => match p with (s, (l, b)) =>\n                    (mkPrefix (Some l) (Some s) b false %% prefix_t) end)\n\n    |+| lock_or_rep_p $ op_override_p @\n        (fun p => match p with (l, b) =>\n                    (mkPrefix (Some l) None b false %% prefix_t) end)\n\n    |+| lock_or_rep_p $ op_override_p $ segment_override_p @\n        (fun p => match p with (l, (b, s)) =>\n                    (mkPrefix (Some l) (Some s) b false %% prefix_t) end)\n\n    |+| lock_or_rep_p $ segment_override_p $ op_override_p @\n        (fun p => match p with (l, (s, b)) =>\n                    (mkPrefix (Some l) (Some s) b false %% prefix_t) end).\n\n  Definition instruction_parser_list := \n    (List.map (fun (p:parser instruction_t) => prefix_parser_nooverride $ p)\n      instr_parsers_nosize_pre) ++\n    (List.map (fun (p:parser instruction_t) => prefix_parser_opsize $ p) \n      instr_parsers_opsize_pre).\n\n  Definition instruction_parser := alts instruction_parser_list.\n\n  Definition instruction_regexp_pair := parser2regexp instruction_parser.\n  Record instParserState := mkPS { \n    inst_ctxt : ctxt_t ; \n    inst_regexp : regexp (pair_t prefix_t instruction_t) ; \n    inst_regexp_wf : wf_regexp inst_ctxt inst_regexp \n  }.\n\n  Definition initial_parser_state : instParserState := \n    mkPS (snd instruction_regexp_pair) (fst instruction_regexp_pair) \n    (p2r_wf instruction_parser _).\n\n  Definition byte_explode (b:int8) : list bool := \n  let bs := Word.bits_of_Z 8 (Word.unsigned b) in\n    (bs 7)::(bs 6)::(bs 5)::(bs 4)::(bs 3)::(bs 2)::(bs 1)::(bs 0)::nil.\n\n  Definition parse_byte (ps:instParserState) (b:int8) : \n    instParserState * list (prefix * instr) := \n    let cs := byte_explode b in\n    let r' := deriv_parse' (inst_regexp ps) cs in\n    let wf' := wf_derivs (inst_ctxt ps) cs (inst_regexp ps) (inst_regexp_wf ps) in\n      (mkPS (inst_ctxt ps) r' wf', apply_null (inst_ctxt ps) r' wf').\n\nEnd X86_PARSER.\n\n", "meta": {"author": "mpettersson", "repo": "reins-verifier-proof", "sha": "44d0b8e0c29b07eb71b1d6d44b020648783409fb", "save_path": "github-repos/coq/mpettersson-reins-verifier-proof", "path": "github-repos/coq/mpettersson-reins-verifier-proof/reins-verifier-proof-44d0b8e0c29b07eb71b1d6d44b020648783409fb/Model/Decode.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.20495296141045447}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import fastpile.\nRequire Import spec_stdlib.\nRequire Import PileModel.\n\nRecord PileAPD := {\n  pilerep: list Z -> val -> mpred;\n  pilerep_local_facts: forall sigma p,\n    pilerep sigma p |-- !! (isptr p /\\ Forall (Z.le 0) sigma);\n  pilerep_valid_pointer: forall sigma p,\n    pilerep sigma p |-- valid_pointer p;\n  pile_freeable (p: val) : mpred (*maybe expose the definition of this as malloc_token? Preferably NOT*)\n}.\n\n#[export] Hint Resolve pilerep_local_facts : saturate_local.\n#[export] Hint Resolve pilerep_valid_pointer : valid_pointer.\n\nDefinition tpile := Tstruct _pile noattr.\n\nLocal Open Scope assert.\n\nSection PileASI.\nVariable M: MallocFreeAPD.\nVariable PILE:PileAPD.\n\nDefinition Pile_new_spec :=\n DECLARE _Pile_new\n WITH gv: globals\n PRE [ ] PROP() (PARAMS () GLOBALS (gv) (SEP(mem_mgr M gv)))\n POST[ tptr tpile ]\n   EX p: val,\n      PROP() LOCAL(temp ret_temp p)\n      SEP(pilerep PILE nil p; pile_freeable PILE p; mem_mgr M gv).\n\nDefinition Pile_add_spec :=\n DECLARE _Pile_add\n WITH p: val, n: Z, sigma: list Z, gv: globals\n PRE [ tptr tpile, tint  ]\n    PROP(0 <= n <= Int.max_signed)\n    PARAMS (p; Vint (Int.repr n)) GLOBALS (gv)\n    SEP(pilerep PILE sigma p; mem_mgr M gv)\n POST[ tvoid ]\n    PROP() LOCAL()\n    SEP(pilerep PILE (n::sigma) p; mem_mgr M gv).\n\nDefinition Pile_count_spec :=\n DECLARE _Pile_count\n WITH p: val, sigma: list Z\n PRE [ tptr tpile  ]\n    PROP(0 <= sumlist sigma <= Int.max_signed)\n    PARAMS (p) GLOBALS ()\n    SEP (pilerep PILE sigma p)\n POST[ tint ]\n      PROP() \n      LOCAL(temp ret_temp (Vint (Int.repr (sumlist sigma))))\n      SEP(pilerep PILE sigma p).\n\nDefinition Pile_free_spec :=\n DECLARE _Pile_free\n WITH p: val, sigma: list Z, gv: globals\n PRE [ tptr tpile  ]\n    PROP()\n    PARAMS (p) (GLOBALS (gv)\n    SEP(pilerep PILE sigma p; pile_freeable PILE p; mem_mgr M gv))\n POST[ tvoid ]\n     PROP() LOCAL() SEP(mem_mgr M gv).\n\nDefinition PileASI:funspecs := [ Pile_new_spec; Pile_add_spec; Pile_count_spec; Pile_free_spec].\n\nEnd PileASI.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs64/VSUpile/fast/spec_fastpile.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.20495296141045444}}
{"text": "Require Export Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Export Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Export Fiat.Parsers.StringLike.FirstCharSuchThat.\nRequire Export Coq.Strings.String.\nRequire Export Fiat.Computation.Core.\nRequire Export Coq.Program.Program.\nRequire Export Fiat.Computation.ApplyMonad.\nRequire Export Fiat.Computation.SetoidMorphisms.\nRequire Export Fiat.Common.\nRequire Export Fiat.Parsers.StringLike.Core.\n\nRequire Import Fiat.Parsers.ContextFreeGrammar.Equality.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Carriers.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.BoolFacts.\nRequire Import Fiat.Common.NatFacts.\nRequire Import Coq.Lists.List.\n\nExport Common.opt2.Notations.\n\nImport ListNotations.\n\nGlobal Open Scope string_scope.\nGlobal Open Scope list_scope.\nGlobal Arguments string_beq : simpl never.\nGlobal Arguments ascii_beq : simpl never.\nGlobal Arguments item_beq : simpl never.\nGlobal Arguments production_beq : simpl never.\nGlobal Arguments productions_beq : simpl never.\nDelimit Scope char_scope with char.\nInfix \"=p\" := (production_beq _) (at level 70, no associativity).\n\n(** Unfolding rules for enumerated ascii *)\nGlobal Arguments Ascii.one / .\nGlobal Arguments Ascii.shift _ !_ / .\nGlobal Arguments Ascii.ascii_of_pos !_ / .\nGlobal Arguments Ascii.ascii_of_nat !_ / .\nGlobal Arguments Carriers.default_nonterminal_carrierT / .\n\nSection tac_helpers.\n  Lemma pull_match_list {A R R' rn rc} {ls : list A} (f : R -> R')\n  : match ls with\n      | nil => f rn\n      | cons x xs => f (rc x xs)\n    end = f (match ls with\n               | nil => rn\n               | cons x xs => rc x xs\n             end).\n  Proof.\n    destruct ls; reflexivity.\n  Qed.\n\n  Lemma pull_match_item {A R R' rn rc} {ls : item A} (f : R -> R')\n  : match ls with\n      | NonTerminal x => f (rn x)\n      | Terminal x => f (rc x)\n    end = f (match ls with\n               | NonTerminal x => rn x\n               | Terminal x => rc x\n             end).\n  Proof.\n    destruct ls; reflexivity.\n  Qed.\n\n  Lemma pull_match_bool {R R' rn rc} {b : bool} (f : R -> R')\n  : (if b then f rn else f rc)\n    = f (if b then rn else rc).\n  Proof.\n    destruct b; reflexivity.\n  Qed.\n\n  Lemma pull_If_bool {R R' rn rc} {b : bool} (f : R -> R')\n  : (If b Then f rn Else f rc)\n    = f (If b Then rn Else rc).\n  Proof.\n    destruct b; reflexivity.\n  Qed.\nEnd tac_helpers.\n\nLemma unguard {T} (x : T)\n: refine { x' : T | True }\n         (ret x).\nProof.\n  repeat intro; computes_to_inv; subst.\n  apply PickComputes; constructor.\nQed.\n\nGlobal Arguments unguard {_} _ [_] _.\n\nLtac parser_pull_tac :=\n  repeat match goal with\n           | [ |- context G[match ?ls with\n                              | nil => [?x]\n                              | (_::_) => [?y]\n                            end] ]\n             => rewrite (@pull_match_list _ _ _ x (fun _ _ => y) ls (fun k => [k]))\n           | [ |- context G[match ?it with\n                              | NonTerminal _ => [?x]\n                              | Terminal _ => [?y]\n                            end] ]\n             => rewrite (@pull_match_item _ _ _ (fun _ => x) (fun _ => y) it (fun k => [k]))\n           | [ |- context G[match ?b with\n                              | true => [?x]\n                              | false => [?y]\n                            end] ]\n             => rewrite (@pull_match_bool _ _ x y b (fun k => [k]))\n           | [ |- context G[match ?b with\n                              | true => ret ?x\n                              | false => ret ?y\n                            end] ]\n             => rewrite (@pull_match_bool _ _ x y b (fun k => ret k))\n           | [ |- context G[If ?b Then [?x] Else [?y] ] ]\n             => rewrite (@pull_If_bool _ _ x y b (fun k => [k]))\n           | [ |- context G[If ?b Then ret ?x Else ret ?y] ]\n             => rewrite (@pull_If_bool _ _ x y b (fun k => ret k))\n         end.\n\nLtac unguard :=\n  rewrite ?(unguard [0]).\n\nLtac solve_prod_beq :=\n  clear;\n  repeat match goal with\n           | [ |- context[true = false] ] => congruence\n           | [ |- context[false = true] ] => congruence\n           | [ |- context[EqNat.beq_nat ?x ?y] ]\n             => is_var x;\n               let H := fresh in\n               destruct (EqNat.beq_nat x y) eqn:H;\n                 [ apply EqNat.beq_nat_true in H; subst x\n                 | ];\n                 simpl\n           | [ |- context[EqNat.beq_nat ?x ?y] ]\n             => first [ is_var x; fail 1\n                      | generalize x; intro ]\n         end.\n\nDefinition if_aggregate {A} (b1 b2 : bool) (x y : A)\n: (If b1 Then x Else If b2 Then x Else y) = (If (b1 || b2)%opt2_bool Then x Else y)\n  := if_aggregate b1 b2 x y.\nDefinition if_aggregate2 {A} (b1 b2 b3 : bool) (x y z : A) (H : b1 = false -> b2 = true -> b3 = true -> False)\n: (If b1 Then x Else If b2 Then y Else If b3 Then x Else z) = (If (b1 || b3)%opt2_bool Then x Else If b2 Then y Else z)\n  := if_aggregate2 x y z H.\nDefinition if_aggregate3 {A} (b1 b2 b3 b4 : bool) (x y z w : A) (H : b1 = false -> (b2 || b3)%bool = true -> b4 = true -> False)\n: (If b1 Then x Else If b2 Then y Else If b3 Then z Else If b4 Then x Else w) = (If (b1 || b4)%opt2_bool Then x Else If b2 Then y Else If b3 Then z Else w)\n  := if_aggregate3 _ _ x y z w H.\n\nModule opt2.\n  Definition orb_false_r : forall b, (b || false)%opt2_bool = b\n    := Bool.orb_false_r.\n  Definition andb_orb_distrib_r : forall b1 b2 b3 : bool,\n      (b1 && (b2 || b3))%opt2_bool = (b1 && b2 || b1 && b3)%opt2_bool\n    := Bool.andb_orb_distrib_r.\n  Definition andb_orb_distrib_l : forall b1 b2 b3 : bool,\n      ((b1 || b2) && b3)%opt2_bool = (b1 && b3 || b2 && b3)%opt2_bool\n    := Bool.andb_orb_distrib_l.\n  Definition orb_andb_distrib_r\n    : forall b1 b2 b3 : bool,\n      (b1 || b2 && b3)%opt2_bool = ((b1 || b2) && (b1 || b3))%opt2_bool\n    := Bool.orb_andb_distrib_r.\n  Definition orb_andb_distrib_l\n    : forall b1 b2 b3 : bool,\n      (b1 && b2 || b3)%opt2_bool = ((b1 || b3) && (b2 || b3))%opt2_bool\n    := Bool.orb_andb_distrib_l.\n  Definition andb_assoc\n    : forall b1 b2 b3 : bool, (b1 && (b2 && b3))%opt2_bool = (b1 && b2 && b3)%opt2_bool\n    := Bool.andb_assoc.\n  Definition orb_assoc\n    : forall b1 b2 b3 : bool, (b1 || (b2 || b3))%opt2_bool = (b1 || b2 || b3)%opt2_bool\n    := Bool.orb_assoc.\n  Definition andb_orb_distrib_r_assoc\n    : forall b1 b2 b3 b4 : bool,\n      (b1 && (b2 || b3) || b4)%opt2_bool = (b1 && b2 || (b1 && b3 || b4))%opt2_bool\n    := andb_orb_distrib_r_assoc.\n  Definition beq_0_1_leb\n    : forall x : nat,\n      (opt2.beq_nat x 1 || opt2.beq_nat x 0)%opt2_bool = opt2.leb x 1\n    := beq_0_1_leb.\n  Definition beq_S_leb\n    : forall x n : nat,\n      (opt2.beq_nat x (S n) || opt2.leb x n)%opt2_bool = opt2.leb x (S n)\n    := beq_S_leb.\nEnd opt2.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/Refinement/PreTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.20493603635665358}}
{"text": "(* Sequentialisation - Definition of a sequentializing vertex *)\n(* From a Proof Net, return a LL proof of the same sequent *)\n\nFrom Coq Require Import Bool.\nFrom OLlibs Require Import dectype.\nSet Warnings \"-notation-overridden\". (* to ignore warnings due to the import of ssreflect *)\nFrom mathcomp Require Import all_ssreflect.\nSet Warnings \"notation-overridden\".\nFrom GraphTheory Require Import mgraph setoid_bigop structures.\n\nFrom Yalla Require Export mll_prelim mll_def mll_basic mll_seq_to_pn.\n\nImport EqNotations.\n\nSet Mangle Names.\nSet Mangle Names Light.\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\nSet Bullet Behavior \"Strict Subproofs\".\n\n\n\nSection Atoms.\n\n(** A set of atoms for building formulas *)\nContext { atom : DecType }.\n(* TODO meilleur moyen de récupérer les notations *)\nNotation formula := (@formula atom).\nNotation base_graph := (graph (flat rule) (flat (formula * bool))).\nNotation graph_data := (@graph_data atom).\nNotation proof_structure := (@proof_structure atom).\nNotation proof_net := (@proof_net atom).\nNotation switching := (@switching atom).\nNotation switching_left := (@switching_left atom).\n\n\nDefinition iso_to_isod (F G : proof_structure) (h : F ≃ G) :\n  F ≃d perm_graph_data (sequent_iso_perm h) G.\nProof. eexists; simpl. apply perm_of_sequent_iso_perm. Defined.\n\n(* sequentialisation : fonction reliant regles à noeuds => nb cut + quels tens lies à des cut *)\n(* seuentialisation sans coupure puis avec (+ de cas ou en remplacant par des tens) *)\n\n\n\nDefinition sequentializing {G : proof_net} (v : G) : Type :=\n  match vlabel v with\n  | ax => {A & G ≃ ax_pn A}\n  | ⊗ => {'(G0, G1) : proof_net * proof_net & G ≃ add_node_ps_tens G0 G1}\n  | ⅋ => {G0 : proof_net & G ≃ add_node_ps_parr G0}\n  | cut => {'(G0, G1) : proof_net * proof_net & G ≃ add_node_ps_cut G0 G1}\n  | c => void (* a conclusion node is never sequentializing *)\n  end.\n\nSection Rem_node.\nContext {G : proof_structure} {v : G}.\nHypothesis (V : vlabel v = ⊗ \\/ vlabel v = ⅋) (T : terminal v).\n\n(* Vertices neighbourhing v *)\nLocal Notation elv := (left V).\nLocal Notation erv := (right V).\nLocal Notation ecv := (ccl V).\nLocal Notation lv := (source elv).\nLocal Notation rv := (source erv).\nLocal Notation cv := (target ecv).\n\n(** Base graph for removing a node and its eventual conclusion *) (* TODO faire comme add_node des cas selon vlabel_v pour factoriser ? *)\nDefinition rem_node_graph_1 := induced ([set: G] :\\ v :\\ cv).\n\n(* Then add new conclusions *)\nLemma lv_inside : lv \\in setT :\\ v :\\ cv.\nProof.\n  rewrite !in_set. splitb; apply /eqP => F.\n  - assert (P : walk lv lv [:: elv ; ecv]) by by rewrite /= F ccl_e left_e; splitb.\n    by specialize (ps_acyclic P).\n  - assert (FF : lv = target elv) by by rewrite left_e.\n    apply (no_selfloop FF).\nQed.\n\nLemma rv_inside : rv \\in setT :\\ v :\\ cv.\nProof.\n  rewrite !in_set. splitb; apply /eqP => F.\n  - assert (P : walk rv rv [:: erv ; ecv]) by by rewrite /= F ccl_e right_e; splitb.\n    by specialize (ps_acyclic P).\n  - assert (FF : rv = target erv) by by rewrite right_e.\n    apply (no_selfloop FF).\nQed.\n\nDefinition rem_node_graph :=\n  @add_concl_graph _ (@add_concl_graph _ rem_node_graph_1 (Sub rv rv_inside) c (flabel erv))\n                     (inl (Sub lv lv_inside)) c (flabel elv).\n\nLemma vlabel_cv : vlabel cv = c.\nProof. apply /eqP. by rewrite -terminal_tens_parr. Qed.\n\nLemma v_neq_cv : v <> cv.\nProof. intro F. have := vlabel_cv. rewrite -F. by destruct V as [V' | V']; rewrite V'. Qed.\n\n(* Give its order *)\nDefinition rem_node_transport (e : edge G) : edge rem_node_graph :=\n  if @boolP _ is AltTrue p then Some (inl (Some (inl (Sub e p : edge rem_node_graph_1))))\n  else if e == elv then None else Some (inl None).\n\nDefinition rem_node_order :=\n  None :: (Some (inl None)) :: [seq rem_node_transport x | x <- [seq x <- order G | x != ecv]].\n\nDefinition rem_node_graph_data := {|\n  graph_of := rem_node_graph;\n  order := rem_node_order;\n  |}.\n\nLemma rem_node_removed : edge_set (setT :\\ v :\\ cv) = setT :\\ elv :\\ erv :\\ ecv.\nProof.\n  assert (C := vlabel_cv).\n  apply /setP => a. rewrite !in_set.\n  destruct (eq_comparable a ecv) as [? | Hc];\n  [ | destruct (eq_comparable a erv) as [? | Hr]];\n  [ | | destruct (eq_comparable a elv)];\n  try by (subst a; rewrite ?left_e ?right_e !eq_refl ?andb_false_r).\n  assert (a != ecv /\\ a != erv /\\ a != elv) as [-> [-> ->]] by by splitb; apply /eqP.\n  splitb; apply /eqP.\n  - by apply no_source_c.\n  - intros ?. contradict Hc. by apply ccl_eq.\n  - intros ?. contradict Hc. by apply one_target_c.\n  - intros ?. contradict Hr. by apply right_eq2.\nQed.\n\nDefinition rem_node_transport' : edge rem_node_graph -> edge G :=\n  fun e => match e with\n  | Some (inl (Some (inl (exist a _)))) => a\n  | Some (inl (Some (inr a))) => match a with end\n  | Some (inl None) => erv\n  | Some (inr a) => match a with end\n  | None => elv\n  end.\n\nLemma rem_node_transport'_inj : injective rem_node_transport'.\nProof.\n  move => [[[[[e E] | []] | ]| []] | ] [[[[[a A] | []] | ]| []] | ];\n  cbnb; introb; cbnb.\n  all: try by (contradict E || contradict A); apply /negP; rewrite rem_node_removed // !in_set; caseb.\n  - by assert (erv <> elv) by apply nesym, left_neq_right.\n  - by assert (elv <> erv) by apply left_neq_right.\nQed.\n\nLemma rem_node_transportK e :\n  e <> ecv -> rem_node_transport' (rem_node_transport e) = e.\nProof.\n  intros ?.\n  unfold rem_node_transport, rem_node_transport'.\n  case: {-}_ /boolP => In; cbnb. case_if.\n  revert In. rewrite rem_node_removed !in_set. introb.\nQed.\n\nLemma rem_node_transportK' e :\n  rem_node_transport (rem_node_transport' e) = e.\nProof.\n  unfold rem_node_transport, rem_node_transport'.\n  destruct e as [[[[[e E] | []] | ] | []] | ];\n  case: {-}_ /boolP => In.\n  - cbnb.\n  - by contradict E; apply /negP.\n  - contradict In; apply /negP. rewrite rem_node_removed !in_set. caseb.\n  - case_if. by assert (erv <> elv) by apply nesym, left_neq_right.\n  - contradict In; apply /negP. rewrite rem_node_removed !in_set. caseb.\n  - case_if.\nQed.\n\nLemma flabel_rem_node_transport' e : flabel (rem_node_transport' e) = flabel e.\nProof. destruct e as [[[[[e E] | []] | ] | []] | ]; cbnb. Qed.\n\nLemma rem_node_transport_in_edges_at (b : bool) (e : edge G)\n  (Hu : endpoint b e \\in [set: G] :\\ v :\\ cv) :\n  rem_node_transport e \\in edges_at_outin b (inl (inl (Sub (endpoint b e) Hu)) : rem_node_graph).\nProof.\n  rewrite in_set /rem_node_transport.\n  case: {-}_ /boolP => In; cbnb; case_if; destruct b; cbnb.\n  - contradict Hu; apply /negP. rewrite !in_set left_e. caseb.\n  - revert In. rewrite rem_node_removed // !in_set. introb.\n    all: contradict Hu; apply /negP; rewrite !in_set ?right_e; caseb.\n  - revert In. rewrite rem_node_removed // !in_set. introb.\n    contradict Hu; apply /negP.\n    rewrite ccl_e !in_set. caseb.\nQed.\n\nLemma rem_node_transport_edges u Hu b : edges_at_outin b u =\n  [set rem_node_transport' a | a in edges_at_outin b (inl (inl (Sub u Hu)) : rem_node_graph)].\nProof.\n  apply /setP => e. rewrite in_set.\n  symmetry. destruct (eq_comparable u (endpoint b e)) as [? | Hc]; [subst u | ].\n  - rewrite eq_refl. apply /imsetP. exists (rem_node_transport e).\n    + apply rem_node_transport_in_edges_at.\n    + rewrite rem_node_transportK //.\n      intros ?; subst e.\n      contradict Hu; apply /negP.\n      rewrite !in_set.\n      destruct b; rewrite ?ccl_e; caseb.\n  - transitivity false; last by by symmetry; apply /eqP; apply nesym.\n    apply /imsetP; move => [[[[[[a A] | []] | ] | []] | ] Ain /= ?]; subst e.\n    all: contradict Ain; apply /negP.\n    all: rewrite !in_set eq_sym; destruct b; cbnb; by apply /eqP.\nQed.\n\nLemma rem_node_p_deg : proper_degree rem_node_graph.\nProof.\n  move => b [[[u U] | []] | []] /=.\n  - rewrite -p_deg rem_node_transport_edges card_imset //; by apply rem_node_transport'_inj.\n  - destruct b.\n    + assert (Hr : edges_at_in (inl (inr tt) : rem_node_graph) = [set Some (inl None)]).\n      { apply /setP => e; rewrite !in_set. by destruct e as [[[[[? ?] | []] | ] | []] | ]. }\n      by rewrite Hr cards1.\n    + assert (Hr : edges_at_out (inl (inr tt) : rem_node_graph) = set0).\n      { apply /setP => e; rewrite !in_set. by destruct e as [[[[[? ?] | []] | ] | []] | ]. }\n      by rewrite Hr cards0.\n  - destruct b.\n    + assert (Hr : edges_at_in (inr tt : rem_node_graph) = [set None]).\n      { apply /setP => e. rewrite !in_set. by destruct e as [[[[[? ?] | []] | ] | []] | ]. }\n      by rewrite Hr cards1.\n    + assert (Hr : edges_at_out (inr tt : rem_node_graph) = set0).\n      { apply /setP => e. rewrite !in_set. by destruct e as [[[[[? ?] | []] | ] | []] | ]. }\n      by rewrite Hr cards0.\nQed.\n\nLemma rem_node_p_ax_cut : proper_ax_cut rem_node_graph.\nProof.\n  move => b [[[u U] | []] | []] /= Hu; try by destruct b.\n  destruct (p_ax_cut Hu) as [el [er [Lin [Rin LR]]]].\n  exists (rem_node_transport el), (rem_node_transport er).\n  revert Lin. rewrite rem_node_transport_edges => /imsetP[al Al ?]. subst el.\n  revert Rin. rewrite rem_node_transport_edges => /imsetP[ar Ar ?]. subst er.\n  revert LR. rewrite !flabel_rem_node_transport' => LR.\n  rewrite !rem_node_transportK'. splitb.\nQed.\n\nLemma rem_node_p_tens_parr : proper_tens_parr rem_node_graph.\nProof.\n  move => b [[[u U] | []] | []] /= Hu; try by destruct b.\n  destruct (p_tens_parr Hu) as [el [er [ec [Lin [Ll [Rin [Rl [Cin Elrc]]]]]]]].\n  exists (rem_node_transport el), (rem_node_transport er), (rem_node_transport ec).\n  revert Lin. rewrite rem_node_transport_edges => /imsetP[al Al ?]. subst el.\n  revert Rin. rewrite rem_node_transport_edges => /imsetP[ar Ar ?]. subst er.\n  revert Cin. rewrite rem_node_transport_edges => /imsetP[ac Ac ?]. subst ec.\n  revert Elrc. rewrite !flabel_rem_node_transport' => Elrc.\n  rewrite !rem_node_transportK'. splitb.\n  - revert Ll. destruct al as [[[[[? ?] | []] | ] | []] | ]; cbnb.\n  - revert Rl. destruct ar as [[[[[? ?] | []] | ] | []] | ]; cbnb.\n    + contradict Ar. by rewrite !in_set.\n    + by rewrite left_l.\nQed.\n\nLemma rem_node_p_noleft : proper_noleft rem_node_graph.\nProof. move => [[[[[e E] | []] | ]| []] | ] //=. by apply p_noleft. Qed.\n\nLemma rem_node_p_order : proper_order rem_node_graph_data.\nProof.\n  split.\n  - rewrite /= /rem_node_order.\n    move => [[[[[e E] | []] | ] | []] | ] //=.\n    rewrite !in_cons /=.\n    assert (Hr : Some (inl (Some (inl (Sub e E : edge rem_node_graph_1)))) = rem_node_transport e).\n    { rewrite /rem_node_transport. case: {-}_ /boolP => [In | /negP //]. cbnb. }\n    rewrite Hr {Hr}. split.\n    + move => ?. apply map_f.\n      rewrite mem_filter. splitb.\n      * revert E. rewrite rem_node_removed !in_set. introb.\n      * by apply p_order.\n    + move => /mapP[a A Ha].\n      assert (a = e).\n      { revert Ha. unfold rem_node_transport. case: {-}_ /boolP => [In | /negP //].\n        case: {-}_ /boolP => [In' | /negP-? //]; last by case_if.\n        move => /eqP. by cbnb => /eqP-->. }\n      subst a.\n      revert A. rewrite mem_filter. introb.\n      by apply p_order.\n  - rewrite /= in_cons /=. splitb.\n    + apply /mapP; move => [a A] /eqP.\n      rewrite /rem_node_transport.\n      case: {-}_ /boolP => ?; case_if.\n      revert A. rewrite mem_filter => /andP[_ A].\n      apply p_order in A.\n      contradict A.\n      rewrite left_e. by destruct V as [H | H]; rewrite H.\n    + apply /mapP; move => [a A] /eqP.\n      rewrite /rem_node_transport.\n      case: {-}_ /boolP => Ain; case_if.\n      revert A. rewrite mem_filter => /andP[/eqP-A0 A].\n      revert Ain. rewrite rem_node_removed // !in_set. introb.\n      apply p_order in A.\n      contradict A.\n      rewrite right_e. by destruct V as [H | H]; rewrite H.\n    + rewrite map_inj_in_uniq.\n      { apply filter_uniq, p_order. }\n      intros a b.\n      rewrite !mem_filter => /andP[_ A] /andP[_ B].\n      rewrite /rem_node_transport.\n      case: {-}_ /boolP => Ain;\n      case: {-}_ /boolP => Bin => /eqP; case_if.\n      enough (L : forall e, e \\notin edge_set (setT :\\ v :\\ cv) -> e \\in order G -> e = ecv).\n      { transitivity (ccl V); [ | symmetry]; by apply L. }\n      clear - T.\n      intros a Ain A.\n      apply p_order in A.\n      revert Ain. rewrite rem_node_removed !in_set. introb.\n      * contradict A. rewrite right_e. destruct V as [H | H]; by rewrite H.\n      * contradict A. rewrite left_e. destruct V as [H | H]; by rewrite H.\nQed.\n\nDefinition rem_node_ps := {|\n  graph_data_of := rem_node_graph_data;\n  p_deg := rem_node_p_deg;\n  p_ax_cut := rem_node_p_ax_cut;\n  p_tens_parr := rem_node_p_tens_parr;\n  p_noleft := rem_node_p_noleft;\n  p_order := rem_node_p_order;\n  |}.\n\nEnd Rem_node. (* TODO move this to the file with parr if not used for tens *)\n\n(*\nDefinition rem_cut_graph_1 {G : proof_structure} {v : G} (H : vlabel v = cut) :=\n  induced (setT :\\ v).\n\n(* Add two new conclusions *)\nLemma rem_cut_graph_helper {G : proof_structure} {v : G} (H : vlabel v = cut) :\n  {'(e, f) & edges_at_in v = [set e; f] /\\ e <> f /\\ source e \\in [set: G] :\\ v /\\ source f \\in [set: G] :\\ v}.\nProof.\n  assert (C : exists e, [exists f, (e != f) && (edges_at_in v == [set e; f])]).\n  { assert (C := pre_proper_cut H).\n    revert C => /eqP/cards2P[e [f [? ?]]].\n    exists e. apply /existsP. exists f. apply /andP. split; trivial. by apply /eqP. }\n  revert C => /sigW[e] /existsP/sigW[f /andP[/eqP-? /eqP-In]].\n  exists (e, f). splitb; trivial; [set a := e | set a := f].\n  all: rewrite !in_set andb_true_r; apply /eqP.\n  all: enough (v = target a) as -> by apply no_selfloop.\n  all: enough (A : a \\in edges_at_in v) by by revert A; rewrite in_set => /eqP-->.\n  all: rewrite In !in_set; caseb.\nQed.\n\nDefinition rem_cut_graph {G : proof_structure} {v : G} (H : vlabel v = cut) : base_graph.\nProof.\n  destruct (rem_cut_graph_helper H) as [[e f] [_ [_ [E F]]]].\n  exact(@add_concl_graph _\n    (@add_concl_graph _ (rem_cut_graph_1 H) (Sub (source e) E) c (flabel e))\n      (inl (Sub (source f) F)) c (flabel f)).\nDefined.\n\nDefinition splitting_cc (G : proof_net) (v : G) : bool :=\n  match vlabel v as V return vlabel v = V -> bool with\n  | ax => fun _ => terminal v\n  | ⊗ => fun H => uconnected_nb (@switching_left _ (rem_node_graph (or_introl H))) == 2\n  | ⅋ => fun H => uconnected_nb (@switching_left _ (rem_node_graph (or_intror H))) == 1\n  | cut => fun H => uconnected_nb (@switching_left _ (rem_cut_graph H)) == 2\n  | c => fun _ => false\n  end Logic.eq_refl.\n\n(* puis définir les graphes avec induced_sub S pour S dans \nequivalence_partition (is_uconnected f) [set: G] et là ça devient galère,\nfaire des vues pour se retrouver avec des il existe equi = [S S'] (il existe sur\nset de finset, donc ok je pense) puis définir les Gi à partir de là,\nmontrer qu'ils sont uconnected_nb = 1, puis finalement que\nG iso à add_node Gi *)*)\n\n(* OLD TRY\nLemma terminal_parr_is_splitting_cc (G : proof_net) (v : G) :\n  vlabel v = ⅋ -> terminal v -> splitting_cc v.\nProof.\n  intros V T.\n  unfold splitting_cc. generalize (erefl (vlabel v)). rewrite {2 3}V => V'.\n  assert (V = V') by apply eq_irrelevance. subst V'.\n  enough (C : correct (rem_node_graph (or_intror V))) by by apply /eqP; destruct C.\n  unfold rem_node_graph.\n  destruct (rem_node_sources_stay (or_intror V)) as [e f].\n  apply add_concl_correct, correct_to_weak, add_concl_correct. split.\n  { apply uacyclic_induced, p_correct. }\n  intros [x X] [y Y].\n  destruct (correct_to_weak (p_correct G)) as [_ C].\n  revert C => /(_ x y)/sigW[[p P] _].\n  enough ({q : Supath switching_left (Sub x X : rem_node_graph_1 (or_intror V)) (Sub y Y) &\n    p = [seq (val a.1, a.2) | a <- upval q]}) as [q _] by by exists q.\n  revert x X P. induction p as [ | a p IH] => x X; rewrite /supath /=.\n  { introb. replace Y with X by apply eq_irrelevance. by exists (supath_nil _ _). }\n  rewrite in_cons => /andP[/andP[/andP[/eqP-? W] /andP[u U]] /norP[n N]]; subst x.\n  destruct (utarget a \\in [set: G] :\\ v :\\ target (ccl_parr V)) eqn:A.\n  - destruct (IH _ A) as [q Hq].\n    { splitb. }\n    assert (Ain : a.1 \\in edge_set ([set: G] :\\ v :\\ target (ccl_parr V))).\n    { rewrite in_set. destruct a as [a []]; splitb. }\n    assert (PA : supath switching_left (Sub (usource a) X : rem_node_graph_1 (or_intror V))\n      (Sub (utarget a) A) [:: (Sub a.1 Ain, a.2)]).\n    { rewrite /supath /= in_cons orb_false_r. splitb; try by cbnb.\n      revert n. rewrite /switching_left /=. case_if. }\n    enough (D : upath_disjoint switching_left {| upvalK := PA |} q).\n    { exists (supath_cat D). cbn. rewrite Hq. f_equal. simpl. by destruct a. }\n    rewrite /= /upath_disjoint disjoint_has /= orb_false_r.\n    revert u. subst p.\n    destruct q as [q Q]. rewrite -map_comp /=. clear.\n    induction q as [ | c q IH]; trivial.\n    rewrite /= !in_cons => /norP[k K]. apply /norP. rewrite IH //. splitb.\n    revert k. rewrite /switching_left /=. case_if.\n  - clear IH.\n    assert (Vc : vlabel (target (ccl_parr V)) = c).\n    { revert T. clear. rewrite (terminal_tens_parr (or_intror V)). apply /eqP. }\n    assert (Ca : a = forward (left_parr V)).\n    { clear - X A n Vc.\n      revert A. rewrite !in_set andb_true_r => /nandP[/negPn/eqP-A | /negPn/eqP-A].\n      - exfalso.\n        destruct a as [a []].\n        + assert (a = ccl_parr V) by by apply one_target_c.\n          subst a.\n          contradict X; apply /negP.\n          rewrite !in_set /= ccl_e. caseb.\n        + contradict A. simpl.\n          by apply no_source_c.\n      - destruct a as [a []].\n        + simpl in A. f_equal.\n          revert n. rewrite /switching_left /= A V /=. case_if.\n          by apply left_eq.\n        + assert (a = ccl_parr V) by by apply ccl_eq.\n          subst a.\n          contradict X; apply /negP.\n          rewrite !in_set /=. caseb. }\n    subst a.\n    assert (Cp : p = [::] \\/ p = [:: forward (ccl_parr V)]).\n    { destruct p as [ | s p]; auto. right.\n      assert (s = forward (ccl_parr V)).\n      { revert W => /= /andP[/eqP-S W].\n        rewrite left_e in S.\n        destruct s as [s []]; simpl in *.\n        - apply /eqP. cbn. rewrite andb_true_r. apply /eqP.\n          by apply ccl_eq.\n        - revert u N. rewrite !in_cons => /norP[S1 _] /norP[S2 _]. revert S1 S2.\n          rewrite /switching_left left_e left_l S V /=.\n          case_if.\n          enough (left_parr V = s) by by [].\n          symmetry. by apply left_eq. }\n      subst s.\n      destruct p as [ | r p]; trivial.\n      exfalso. revert U W. clear - Vc.\n      rewrite /= !in_cons => /andP[/norP[U _] _] /andP[_ /andP[/eqP-W _]].\n      assert (r = backward (ccl_parr V)).\n      { clear - W Vc.\n        destruct r as [r []].\n        - revert W. cbnb => W. contradict W.\n          by apply no_source_c.\n        - revert W. cbnb => W.\n          apply /eqP. cbn. splitb. apply /eqP.\n          by apply one_target_c. }\n      subst r.\n      contradict U. by apply /negP/negPn/eqP. }\n    contradict Y. apply /negP. clear -Cp W.\n    rewrite !in_set.\n    revert W. destruct Cp; subst p; simpl.\n    + move => /eqP-?; subst y. rewrite left_e. caseb.\n    + move => /andP[_ /eqP-?]. subst y. caseb.\nQed.\n\nLemma splitting_cc_parr_is_sequentializing (G : proof_net) (v : G) :\n  vlabel v = ⅋ -> terminal v -> splitting_cc v -> sequentializing v.\nProof.\n  intros V T.\n  unfold splitting_cc. generalize (erefl (vlabel v)). rewrite {2 3}V => V' S.\n  assert (V = V') by apply eq_irrelevance. subst V'.\n  rewrite /sequentializing V.\n  assert (C : correct (rem_node_graph (or_intror V))).\n  { split; [ | by apply /eqP].\n    apply union_edge_uacyclic; last by apply unit_graph_uacyclic.\n    apply union_edge_uacyclic; last by apply unit_graph_uacyclic.\n    apply uacyclic_induced, p_correct. }\n  exists {| ps_of := rem_node_ps (or_intror V) T ; p_correct := C |}.\nAbort.\n(*\n  assert (h := rem_node_iso (or_intror V) T).\n  rewrite {1}V in h.\n  apply h.\nQed.\n*)\n\n\nLemma splitting_cc_is_sequentializing (G : proof_net) (v : G) :\n  splitting_cc v -> sequentializing v.\nProof.\nAdmitted.\n\nLemma terminal_parr_is_sequentializing (G : proof_net) (v : G) :\n  vlabel v = ⅋ -> terminal v -> sequentializing v.\nProof. intros. by apply splitting_cc_is_sequentializing, terminal_parr_is_splitting_cc. Qed.\n*)\n\nLemma exists_seq_or_no_seq (G : proof_net) :\n  (forall (v : G), (sequentializing v -> False)) -> {v : G & sequentializing v}.\nProof.\nCheck existsPn.\n(* Must use bool and not type, see criterion where needed in splitting tens *)\nAbort.\n\nEnd Atoms.\n", "meta": {"author": "RemiDiG", "repo": "proofnet_mll", "sha": "03e12bce95709fe92f628f2d16aa69cf82d81ff4", "save_path": "github-repos/coq/RemiDiG-proofnet_mll", "path": "github-repos/coq/RemiDiG-proofnet_mll/proofnet_mll-03e12bce95709fe92f628f2d16aa69cf82d81ff4/yalla/mll_pn_to_seq_def.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.20493603635665353}}
{"text": "Require Import oeuf.Common.\nRequire oeuf.StepLib.\nRequire Import Psatz.\n\nRequire Import oeuf.Utopia.\nRequire Import oeuf.Monads.\n\nRequire Export oeuf.HigherValue.\nRequire Import oeuf.AllValues.\nRequire Import oeuf.OpaqueOps.\nRequire Import oeuf.ListLemmas.\n\nInductive insn :=\n| Arg (dst : nat)\n| Self (dst : nat)\n| Deref (dst : nat) (e : nat) (off : nat)\n| Call (dst : nat) (f : nat) (a : nat)\n| MkConstr (dst : nat) (tag : nat) (args : list nat)\n| Switch (dst : nat) (cases : list (list insn))\n| MkClose (dst : nat) (f : function_name) (free : list nat)\n| OpaqueOp (dst : nat) (op : opaque_oper_name) (args : list nat)\n| Copy (dst : nat) (src : nat)\n.\n\nDefinition env := list (list insn * nat).\n\n\n(* Continuation-based step relation *)\n\nRecord frame := Frame {\n    arg : value;\n    self : value;\n    locals : list (nat * value)\n}.\n\nDefinition set f l v :=\n    Frame (arg f) (self f) ((l, v) :: locals f).\n\nDefinition local f l := lookup (locals f) l.\n\n\n\nInductive cont :=\n| Kseq (code : list insn) (k : cont)\n| Kswitch (code : list insn) (k : cont)\n| Kret (code : list insn) (ret : nat) (dst : nat) (f : frame) (k : cont)\n| Kstop (ret : nat).\n\nInductive state :=\n| Run (i : list insn) (f : frame) (k : cont)\n| Stop (v : value).\n\nInductive sstep (E : env) : state -> state -> Prop :=\n| SSeq : forall i is f k,\n        is <> [] ->\n        sstep E (Run (i :: is) f k)\n                (Run [i] f (Kseq is k))\n\n| SArg : forall dst f k,\n        sstep E (Run [Arg dst] f k)\n                (Run [] (set f dst (arg f)) k)\n| SSelf : forall dst f k,\n        sstep E (Run [Self dst] f k)\n                (Run [] (set f dst (self f)) k)\n\n| SDerefinateConstr : forall dst e off f k  tag args v,\n        local f e = Some (Constr tag args) ->\n        nth_error args off = Some v ->\n        sstep E (Run [Deref dst e off] f k)\n                (Run [] (set f dst v) k)\n| SDerefinateClose : forall dst e off f k  fname free v,\n        local f e = Some (Close fname free) ->\n        nth_error free off = Some v ->\n        sstep E (Run [Deref dst e off] f k)\n                (Run [] (set f dst v) k)\n\n| SConstrDone : forall dst tag args f k vs,\n        Forall2 (fun l v => local f l = Some v) args vs ->\n        sstep E (Run [MkConstr dst tag args] f k)\n                (Run [] (set f dst (Constr tag vs)) k)\n| SCloseDone : forall dst fname free f k vs,\n        Forall2 (fun l v => local f l = Some v) free vs ->\n        sstep E (Run [MkClose dst fname free] f k)\n                (Run [] (set f dst (Close fname vs)) k)\n| SOpaqueOpDone : forall dst op args f k vs v,\n        Forall2 (fun l v => local f l = Some v) args vs ->\n        opaque_oper_denote_higher op vs = Some v ->\n        sstep E (Run [OpaqueOp dst op args] f k)\n                (Run [] (set f dst v) k)\n\n| SMakeCall : forall dst fl a f k  fname free arg body ret,\n        local f fl = Some (Close fname free) ->\n        local f a = Some arg ->\n        nth_error E fname = Some (body, ret) ->\n        sstep E (Run [Call dst fl a] f k)\n                (Run body (Frame arg (Close fname free) [])\n                    (Kret [] ret dst f k))\n\n(* NB: `Switch` still has an implicit target of `Arg` *)\n| SSwitchinate : forall dst cases f k  tag args case,\n        arg f = Constr tag args ->\n        nth_error cases tag = Some case ->\n        sstep E (Run [Switch dst cases] f k)\n                (Run case f (Kswitch [] k))\n\n| SCopy : forall dst src f k v,\n        local f src = Some v ->\n        sstep E (Run [Copy dst src] f k)\n                (Run [] (set f dst v) k)\n\n| SContSeq : forall code f k,\n        sstep E (Run [] f (Kseq code k))\n                (Run code f k)\n| SContSwitch : forall code f k,\n        sstep E (Run [] f (Kswitch code k))\n                (Run code f k)\n| SContRet : forall f code ret dst f' k v,\n        local f ret = Some v ->\n        sstep E (Run [] f (Kret code ret dst f' k))\n                (Run code (set f' dst v) k)\n| SContStop : forall ret f v,\n        local f ret = Some v ->\n        sstep E (Run [] f (Kstop ret))\n                (Stop v)\n.\n\n\n\nDefinition sstar BE := StepLib.sstar (sstep BE).\nDefinition SStarNil := @StepLib.SStarNil state.\nDefinition SStarCons := @StepLib.SStarCons state.\n\nDefinition splus BE := StepLib.splus (sstep BE).\nDefinition SPlusOne := @StepLib.SPlusOne state.\nDefinition SPlusCons := @StepLib.SPlusCons state.\n\n\n\nRequire Import oeuf.Metadata.\nRequire oeuf.Semantics.\n\n\nDefinition prog_type : Type := env * list metadata.\nDefinition val_level := VlHigher.\nDefinition valtype := value_type val_level.\n\nInductive is_callstate (prog : prog_type) : valtype -> valtype -> state -> Prop :=\n| IsCallstate : forall fname free av body ret,\n        nth_error (fst prog) fname = Some (body, ret) ->\n        let fv := Close fname free in\n        HigherValue.public_value (snd prog) fv ->\n        HigherValue.public_value (snd prog) av ->\n        is_callstate prog fv av\n            (Run body\n                 (Frame av fv [])\n                 (Kstop ret)).\n\nInductive final_state (prog : prog_type) : state -> valtype -> Prop :=\n| FinalState : forall v,\n        HigherValue.public_value (snd prog) v ->\n        final_state prog (Stop v) v.\n\nDefinition initial_env (prog : prog_type) : env := fst prog.\n\nDefinition semantics (prog : prog_type) : Semantics.semantics :=\n  @Semantics.Semantics_gen state env val_level\n                 (is_callstate prog)\n                 (sstep)\n                 (final_state prog)\n                 (initial_env prog).\n\n\n(*\n\nDefinition prog_type : Type := env * list metadata.\n\nInductive initial_state (prog : prog_type) : state -> Prop :=.\n\nInductive final_state (prog : prog_type) : state -> Prop :=\n| FinalState : forall v, final_state prog (Stop v).\n\nDefinition initial_env (prog : prog_type) : env := fst prog.\n\nDefinition semantics (prog : prog_type) : Semantics.semantics :=\n  @Semantics.Semantics_gen state env\n                 (sstep)\n                 (initial_state prog)\n                 (final_state prog)\n                 (initial_env prog).\n\n*)\n\n(*\n * Mutual recursion/induction schemes for expr\n *)\n\nDefinition insn_rect_mut\n        (P : insn -> Type)\n        (Pl : list insn -> Type)\n        (Pll : list (list insn) -> Type)\n    (HArg :     forall dst, P (Arg dst))\n    (HSelf :    forall dst, P (Self dst))\n    (HDeref :   forall dst e off, P (Deref dst e off))\n    (HCall :    forall dst f a, P (Call dst f a))\n    (HConstr :  forall dst tag args, P (MkConstr dst tag args))\n    (HSwitch :  forall dst cases, Pll cases -> P (Switch dst cases))\n    (HClose :   forall dst fname free, P (MkClose dst fname free))\n    (HOpaqueOp : forall dst op args, P (OpaqueOp dst op args))\n    (HCopy :    forall dst src, P (Copy dst src))\n    (Hnil :     Pl [])\n    (Hcons :    forall i is, P i -> Pl is -> Pl (i :: is))\n    (Hnil2 :    Pll [])\n    (Hcons2 :   forall is iss, Pl is -> Pll iss -> Pll (is :: iss))\n    (i : insn) : P i :=\n    let fix go i :=\n        let fix go_list is :=\n            match is as is_ return Pl is_ with\n            | [] => Hnil\n            | i :: is => Hcons i is (go i) (go_list is)\n            end in\n        let fix go_list_list iss :=\n            match iss as iss_ return Pll iss_ with\n            | [] => Hnil2\n            | is :: iss => Hcons2 is iss (go_list is) (go_list_list iss)\n            end in\n        match i as i_ return P i_ with\n        | Arg dst => HArg dst\n        | Self dst => HSelf dst\n        | Deref dst e off => HDeref dst e off\n        | Call dst f a => HCall dst f a\n        | MkConstr dst tag args => HConstr dst tag args\n        | Switch dst cases => HSwitch dst cases (go_list_list cases)\n        | MkClose dst fname free => HClose dst fname free\n        | OpaqueOp dst op args => HOpaqueOp dst op args\n        | Copy dst src => HCopy dst src\n        end in go i.\n\n(* Useful wrapper for `expr_rect_mut with (Pl := Forall P)` *)\nDefinition insn_ind' (P : insn -> Prop)\n    (HArg :     forall dst, P (Arg dst))\n    (HSelf :    forall dst, P (Self dst))\n    (HDeref :   forall dst e off, P (Deref dst e off))\n    (HCall :    forall dst f a, P (Call dst f a))\n    (HConstr :  forall dst tag args, P (MkConstr dst tag args))\n    (HSwitch :  forall dst cases, Forall (Forall P) cases -> P (Switch dst cases))\n    (HClose :   forall dst fname free, P (MkClose dst fname free))\n    (HOpaqueOp : forall dst op args, P (OpaqueOp dst op args))\n    (HCopy :    forall dst src, P (Copy dst src))\n    (i : insn) : P i :=\n    ltac:(refine (@insn_rect_mut P (Forall P) (Forall (Forall P))\n        HArg HSelf HDeref HCall HConstr HSwitch HClose HOpaqueOp HCopy _ _ _ _ i); eauto).\n\nDefinition insn_list_rect_mut\n        (P : insn -> Type)\n        (Pl : list insn -> Type)\n        (Pll : list (list insn) -> Type)\n    (HArg :     forall dst, P (Arg dst))\n    (HSelf :    forall dst, P (Self dst))\n    (HDeref :   forall dst e off, P (Deref dst e off))\n    (HCall :    forall dst f a, P (Call dst f a))\n    (HConstr :  forall dst tag args, P (MkConstr dst tag args))\n    (HSwitch :  forall dst cases, Pll cases -> P (Switch dst cases))\n    (HClose :   forall dst fname free, P (MkClose dst fname free))\n    (HOpaqueOp : forall dst op args, P (OpaqueOp dst op args))\n    (HCopy :    forall dst src, P (Copy dst src))\n    (Hnil :     Pl [])\n    (Hcons :    forall i is, P i -> Pl is -> Pl (i :: is))\n    (Hnil2 :    Pll [])\n    (Hcons2 :   forall is iss, Pl is -> Pll iss -> Pll (is :: iss))\n    (is : list insn) : Pl is :=\n    let go := insn_rect_mut P Pl Pll\n            HArg HSelf HDeref HCall HConstr HSwitch HClose HOpaqueOp HCopy\n            Hnil Hcons Hnil2 Hcons2 in\n    let fix go_list is :=\n        match is as is_ return Pl is_ with\n        | [] => Hnil\n        | i :: is => Hcons i is (go i) (go_list is)\n        end in go_list is.\n\n\n\nDefinition dest e :=\n    match e with\n    | Arg dst => dst\n    | Self dst => dst\n    | Deref dst _ _ => dst\n    | Call dst _ _ => dst\n    | MkConstr dst _ _ => dst\n    | Switch dst _ => dst\n    | MkClose dst _ _ => dst\n    | OpaqueOp dst _ _ => dst\n    | Copy dst _ => dst\n    end.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/FlatSeq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362517, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.20492471253873143}}
{"text": "(** OBS!: This is taken directly from Iris, and should instead be obtained\nfrom bumping the Iris version. *)\n\n(** Authoritative CMRA of append-only lists, where the fragment represents a\n  snap-shot of the list, and the authoritative element can only grow by\n  appending. *)\nFrom iris.algebra Require Export auth dfrac max_prefix_list.\nFrom iris.algebra Require Import updates local_updates proofmode_classes.\nFrom iris.prelude Require Import options.\n\nDefinition mono_listR (A : ofe) : cmra  := authR (max_prefix_listUR A).\nDefinition mono_listUR (A : ofe) : ucmra  := authUR (max_prefix_listUR A).\n\nDefinition mono_list_auth {A : ofe} (q : dfrac) (l : list A) : mono_listR A :=\n  ●{q} (to_max_prefix_list l) ⋅ ◯ (to_max_prefix_list l).\nDefinition mono_list_lb {A : ofe} (l : list A) : mono_listR A :=\n  ◯ (to_max_prefix_list l).\nGlobal Instance: Params (@mono_list_auth) 2 := {}.\nGlobal Instance: Params (@mono_list_lb) 1 := {}.\nTypeclasses Opaque mono_list_auth mono_list_lb.\n\n(** FIXME: Refactor these notations using custom entries once Coq bug #13654\nhas been fixed. *)\nNotation \"●ML{ dq } l\" :=\n  (mono_list_auth dq l) (at level 20, format \"●ML{ dq }  l\").\nNotation \"●ML{# q } l\" :=\n  (mono_list_auth (DfracOwn q) l) (at level 20, format \"●ML{# q }  l\").\nNotation \"●ML□ l\" := (mono_list_auth DfracDiscarded l) (at level 20).\nNotation \"●ML l\" := (mono_list_auth (DfracOwn 1) l) (at level 20).\nNotation \"◯ML l\" := (mono_list_lb l) (at level 20).\n\nSection mono_list_props.\n  Context {A : ofe}.\n  Implicit Types l : list A.\n  Implicit Types q : frac.\n  Implicit Types dq : dfrac.\n\n  (** Setoid properties *)\n  Global Instance mono_list_auth_ne dq : NonExpansive (@mono_list_auth A dq).\n  Proof. solve_proper. Qed.\n  Global Instance mono_list_auth_proper dq : Proper ((≡) ==> (≡)) (@mono_list_auth A dq).\n  Proof. solve_proper. Qed.\n  Global Instance mono_list_lb_ne : NonExpansive (@mono_list_lb A).\n  Proof. solve_proper. Qed.\n  Global Instance mono_list_lb_proper : Proper ((≡) ==> (≡)) (@mono_list_lb A).\n  Proof. solve_proper. Qed.\n\n  Global Instance mono_list_lb_dist_inj n : Inj (dist n) (dist n) (@mono_list_lb A).\n  Proof. rewrite /mono_list_lb. by intros ?? ?%(inj _)%(inj _). Qed.\n  Global Instance mono_list_lb_inj : Inj (≡) (≡) (@mono_list_lb A).\n  Proof. rewrite /mono_list_lb. by intros ?? ?%(inj _)%(inj _). Qed.\n\n  (** * Operation *)\n  Global Instance mono_list_lb_core_id l : CoreId (◯ML l).\n  Proof. rewrite /mono_list_lb. apply _. Qed.\n  Global Instance mono_list_auth_core_id l : CoreId (●ML□ l).\n  Proof. rewrite /mono_list_auth. apply _. Qed.\n\n  Lemma mono_list_auth_dfrac_op dq1 dq2 l :\n    ●ML{dq1 ⋅ dq2} l ≡ ●ML{dq1} l ⋅ ●ML{dq2} l.\n  Proof.\n    rewrite /mono_list_auth auth_auth_dfrac_op.\n    rewrite (comm _ (●{dq2} _)) -!assoc (assoc _ (◯ _)).\n    by rewrite -core_id_dup (comm _ (◯ _)).\n  Qed.\n\n  Lemma mono_list_lb_op_l l1 l2 : l1 `prefix_of` l2 → ◯ML l1 ⋅ ◯ML l2 ≡ ◯ML l2.\n  Proof. intros ?. by rewrite /mono_list_lb -auth_frag_op to_max_prefix_list_op_l. Qed.\n  Lemma mono_list_lb_op_r l1 l2 : l1 `prefix_of` l2 → ◯ML l2 ⋅ ◯ML l1 ≡ ◯ML l2.\n  Proof. intros ?. by rewrite /mono_list_lb -auth_frag_op to_max_prefix_list_op_r. Qed.\n  Lemma mono_list_auth_lb_op dq l : ●ML{dq} l ≡ ●ML{dq} l ⋅ ◯ML l.\n  Proof.\n    by rewrite /mono_list_auth /mono_list_lb -!assoc -auth_frag_op -core_id_dup.\n  Qed.\n\n  Global Instance mono_list_auth_dfrac_is_op dq dq1 dq2 l :\n    IsOp dq dq1 dq2 → IsOp' (●ML{dq} l) (●ML{dq1} l) (●ML{dq2} l).\n  Proof. rewrite /IsOp' /IsOp=> ->. rewrite mono_list_auth_dfrac_op //. Qed.\n\n  (** * Validity *)\n  Lemma mono_list_auth_dfrac_validN n dq l : ✓{n} (●ML{dq} l) ↔ ✓ dq.\n  Proof.\n    rewrite /mono_list_auth auth_both_dfrac_validN.\n    naive_solver apply to_max_prefix_list_validN.\n  Qed.\n  Lemma mono_list_auth_validN n l : ✓{n} (●ML l).\n  Proof. by apply mono_list_auth_dfrac_validN. Qed.\n\n  Lemma mono_list_auth_dfrac_valid dq l : ✓ (●ML{dq} l) ↔ ✓ dq.\n  Proof.\n    rewrite /mono_list_auth auth_both_dfrac_valid.\n    naive_solver apply to_max_prefix_list_valid.\n  Qed.\n  Lemma mono_list_auth_valid l : ✓ (●ML l).\n  Proof. by apply mono_list_auth_dfrac_valid. Qed.\n\n  Lemma mono_list_auth_dfrac_op_validN n dq1 dq2 l1 l2 :\n    ✓{n} (●ML{dq1} l1 ⋅ ●ML{dq2} l2) ↔ ✓ (dq1 ⋅ dq2) ∧ l1 ≡{n}≡ l2.\n  Proof.\n    rewrite /mono_list_auth (comm _ (●{dq2} _)) -!assoc (assoc _ (◯ _)).\n    rewrite -auth_frag_op (comm _ (◯ _)) assoc. split.\n    - move=> /cmra_validN_op_l /auth_auth_dfrac_op_validN.\n      rewrite (inj_iff to_max_prefix_list). naive_solver.\n    - intros [? ->]. rewrite -core_id_dup -auth_auth_dfrac_op auth_both_dfrac_validN.\n      naive_solver apply to_max_prefix_list_validN.\n  Qed.\n  Lemma mono_list_auth_op_validN n l1 l2 : ✓{n} (●ML l1 ⋅ ●ML l2) ↔ False.\n  Proof. rewrite mono_list_auth_dfrac_op_validN. naive_solver. Qed.\n\n  Lemma mono_list_auth_dfrac_op_valid dq1 dq2 l1 l2 :\n    ✓ (●ML{dq1} l1 ⋅ ●ML{dq2} l2) ↔ ✓ (dq1 ⋅ dq2) ∧ l1 ≡ l2.\n  Proof.\n    rewrite cmra_valid_validN equiv_dist.\n    setoid_rewrite mono_list_auth_dfrac_op_validN. naive_solver eauto using O.\n  Qed.\n  Lemma mono_list_auth_op_valid l1 l2 : ✓ (●ML l1 ⋅ ●ML l2) ↔ False.\n  Proof. rewrite mono_list_auth_dfrac_op_valid. naive_solver. Qed.\n\n  Lemma mono_list_auth_dfrac_op_valid_L `{!LeibnizEquiv A} dq1 dq2 l1 l2 :\n    ✓ (●ML{dq1} l1 ⋅ ●ML{dq2} l2) ↔ ✓ (dq1 ⋅ dq2) ∧ l1 = l2.\n  Proof. unfold_leibniz. apply mono_list_auth_dfrac_op_valid. Qed.\n\n  Lemma mono_list_both_dfrac_validN n dq l1 l2 :\n    ✓{n} (●ML{dq} l1 ⋅ ◯ML l2) ↔ ✓ dq ∧ ∃ l, l1 ≡{n}≡ l2 ++ l.\n  Proof.\n    rewrite /mono_list_auth /mono_list_lb -assoc\n      -auth_frag_op auth_both_dfrac_validN -to_max_prefix_list_includedN.\n    f_equiv; split.\n    - intros [Hincl _]. etrans; [apply: cmra_includedN_r|done].\n    - intros. split; [|by apply to_max_prefix_list_validN].\n      rewrite {2}(core_id_dup (to_max_prefix_list l1)). by f_equiv.\n  Qed.\n  Lemma mono_list_both_validN n l1 l2 :\n    ✓{n} (●ML l1 ⋅ ◯ML l2) ↔ ∃ l, l1 ≡{n}≡ l2 ++ l.\n  Proof. rewrite mono_list_both_dfrac_validN. split; [naive_solver|done]. Qed.\n\n  Lemma mono_list_both_dfrac_valid dq l1 l2 :\n    ✓ (●ML{dq} l1 ⋅ ◯ML l2) ↔ ✓ dq ∧ ∃ l, l1 ≡ l2 ++ l.\n  Proof.\n    rewrite /mono_list_auth /mono_list_lb -assoc -auth_frag_op\n      auth_both_dfrac_valid -max_prefix_list_included_includedN\n      -to_max_prefix_list_included.\n    f_equiv; split.\n    - intros [Hincl _]. etrans; [apply: cmra_included_r|done].\n    - intros. split; [|by apply to_max_prefix_list_valid].\n      rewrite {2}(core_id_dup (to_max_prefix_list l1)). by f_equiv.\n  Qed.\n  Lemma mono_list_both_valid l1 l2 :\n    ✓ (●ML l1 ⋅ ◯ML l2) ↔ ∃ l, l1 ≡ l2 ++ l.\n  Proof. rewrite mono_list_both_dfrac_valid. split; [naive_solver|done]. Qed.\n\n  Lemma mono_list_both_dfrac_valid_L `{!LeibnizEquiv A} dq l1 l2 :\n    ✓ (●ML{dq} l1 ⋅ ◯ML l2) ↔ ✓ dq ∧ l2 `prefix_of` l1.\n  Proof. rewrite /prefix. rewrite mono_list_both_dfrac_valid. naive_solver. Qed.\n  Lemma mono_list_both_valid_L `{!LeibnizEquiv A} l1 l2 :\n    ✓ (●ML l1 ⋅ ◯ML l2) ↔ l2 `prefix_of` l1.\n  Proof. rewrite /prefix. rewrite mono_list_both_valid. naive_solver. Qed.\n\n  Lemma mono_list_lb_op_validN n l1 l2 :\n    ✓{n} (◯ML l1 ⋅ ◯ML l2) ↔ (∃ l, l2 ≡{n}≡ l1 ++ l) ∨ (∃ l, l1 ≡{n}≡ l2 ++ l).\n  Proof. by rewrite auth_frag_op_validN to_max_prefix_list_op_validN. Qed.\n  Lemma mono_list_lb_op_valid l1 l2 :\n    ✓ (◯ML l1 ⋅ ◯ML l2) ↔ (∃ l, l2 ≡ l1 ++ l) ∨ (∃ l, l1 ≡ l2 ++ l).\n  Proof. by rewrite auth_frag_op_valid to_max_prefix_list_op_valid. Qed.\n  Lemma mono_list_lb_op_valid_L `{!LeibnizEquiv A} l1 l2 :\n    ✓ (◯ML l1 ⋅ ◯ML l2) ↔ l1 `prefix_of` l2 ∨ l2 `prefix_of` l1.\n  Proof. rewrite mono_list_lb_op_valid / prefix. naive_solver. Qed.\n\n  Lemma mono_list_lb_op_valid_1_L `{!LeibnizEquiv A} l1 l2 :\n    ✓ (◯ML l1 ⋅ ◯ML l2) → l1 `prefix_of` l2 ∨ l2 `prefix_of` l1.\n  Proof. by apply mono_list_lb_op_valid_L. Qed.\n  Lemma mono_list_lb_op_valid_2_L `{!LeibnizEquiv A} l1 l2 :\n    l1 `prefix_of` l2 ∨ l2 `prefix_of` l1 → ✓ (◯ML l1 ⋅ ◯ML l2).\n  Proof. by apply mono_list_lb_op_valid_L. Qed.\n\n  Lemma mono_list_lb_mono l1 l2 : l1 `prefix_of` l2 → ◯ML l1 ≼ ◯ML l2.\n  Proof. intros. exists (◯ML l2). by rewrite mono_list_lb_op_l. Qed.\n\n  Lemma mono_list_included dq l : ◯ML l ≼ ●ML{dq} l.\n  Proof. apply cmra_included_r. Qed.\n\n  (** * Update *)\n  Lemma mono_list_update {l1} l2 : l1 `prefix_of` l2 → ●ML l1 ~~> ●ML l2.\n  Proof. intros ?. by apply auth_update, max_prefix_list_local_update. Qed.\n  Lemma mono_list_auth_persist dq l : ●ML{dq} l ~~> ●ML□ l.\n  Proof.\n    rewrite /mono_list_auth. apply cmra_update_op; [|done].\n    by apply auth_update_auth_persist.\n  Qed.\nEnd mono_list_props.\n\nDefinition mono_listURF (F : oFunctor) : urFunctor :=\n  authURF (max_prefix_listURF F).\n\nGlobal Instance mono_listURF_contractive F :\n  oFunctorContractive F → urFunctorContractive (mono_listURF F).\nProof. apply _. Qed.\n\nDefinition mono_listRF (F : oFunctor) : rFunctor :=\n  authRF (max_prefix_listURF F).\n\nGlobal Instance mono_listRF_contractive F :\n  oFunctorContractive F → rFunctorContractive (mono_listRF F).\nProof. apply _. Qed.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/reliable_communication/resources/mono_list.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2049247067651561}}
{"text": "From iris.program_logic Require Import lifting.\nFrom iris.algebra Require Import frac dec_agree gmap list.\nFrom iris.base_logic Require Import big_op auth.\nFrom iris_logrel.F_mu_ref Require Export rules.\nFrom iris.proofmode Require Import tactics.\nImport uPred.\n\nDefinition specN := nroot .@ \"spec\".\n\n(** The CMRA for the heap of the specification. *)\nDefinition cfgUR := prodUR (optionUR (exclR exprC)) heapUR.\n\n(** The CMRA for the thread pool. *)\nClass cfgSG Σ :=\n  CFGSG { ctg_heapG :> heapG Σ; cfg_inG :> authG Σ cfgUR; cfg_name : gname }.\n\nSection definitionsS.\n  Context `{cfgSG Σ}.\n\n  Definition heapS_mapsto (l : loc) (q : Qp) (v: val) : iProp Σ :=\n    own cfg_name (◯ (∅, {[ l := (q, DecAgree v) ]})).\n\n  Definition tpool_mapsto (e: expr) : iProp Σ :=\n    own cfg_name (◯ (Excl' e, ∅)).\n\n  Definition spec_inv (ρ : cfg lang) : iProp Σ :=\n    (∃ e σ, own cfg_name (● (Excl' e , to_heap σ)) ∗ ■ rtc step ρ ([e],σ))%I.\n  Definition spec_ctx (ρ : cfg lang) : iProp Σ :=\n    inv specN (spec_inv ρ).\n\n  Global Instance heapS_mapsto_timeless l q v : TimelessP (heapS_mapsto l q v).\n  Proof. apply _. Qed.\n  Global Instance spec_ctx_persistent ρ : PersistentP (spec_ctx ρ).\n  Proof. apply _. Qed.\nEnd definitionsS.\nTypeclasses Opaque heapS_mapsto tpool_mapsto.\n\nNotation \"l ↦ₛ{ q } v\" := (heapS_mapsto l q v)\n  (at level 20, q at level 50, format \"l  ↦ₛ{ q }  v\") : uPred_scope.\nNotation \"l ↦ₛ v\" := (heapS_mapsto l 1 v) (at level 20) : uPred_scope.\nNotation \"⤇ e\" := (tpool_mapsto e) (at level 20) : uPred_scope.\n\nSection cfg.\n  Context `{cfgSG Σ}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types Φ : val → iProp Σ.\n  Implicit Types σ : state.\n  Implicit Types g : heapUR.\n  Implicit Types e : expr.\n  Implicit Types v : val.\n\n  (** Conversion to tpools and back *)\n  Lemma step_insert_no_fork K e σ e' σ' :\n    head_step e σ e' σ' [] → step ([fill K e], σ) ([fill K e'], σ').\n  Proof. intros Hst. eapply (step_atomic _ _ _ _ _ _ [] [] []); eauto.\n         by apply: Ectx_step'.\n  Qed.\n\n  Lemma step_pure E ρ K e e' :\n    (∀ σ, head_step e σ e' σ []) →\n    nclose specN ⊆ E →\n    spec_ctx ρ ∗ ⤇ fill K e ={E}=∗ ⤇ fill K e'.\n  Proof.\n    iIntros (??) \"[#Hspec Hj]\". rewrite /spec_ctx /tpool_mapsto.\n    iInv specN as \">Hinv\" \"Hclose\". iDestruct \"Hinv\" as (e2 σ) \"[Hown %]\".\n    iDestruct (own_valid_2 _ with \"Hown Hj\")\n      as %[[?%Excl_included%leibniz_equiv _]%prod_included ?]%auth_valid_discrete_2.\n    subst.\n    iMod (own_update_2 with \"Hown Hj\") as \"[Hown Hj]\".\n    { by eapply auth_update, prod_local_update_1, option_local_update,\n       (exclusive_local_update _ (Excl (fill K e'))). }\n    iFrame \"Hj\". iApply \"Hclose\". iNext. iExists (fill K e'), σ.\n    iFrame. iPureIntro. eapply rtc_r, step_insert_no_fork; eauto.\n  Qed.\n\n  Lemma step_alloc E ρ K e v:\n    to_val e = Some v → nclose specN ⊆ E →\n    spec_ctx ρ ∗ ⤇ fill K (Alloc e) ={E}=∗ ∃ l, ⤇ fill K (Loc l) ∗ l ↦ₛ v.\n  Proof.\n    iIntros (??) \"[#Hinv Hj]\". rewrite /spec_ctx /tpool_mapsto.\n    iInv specN as \">Hinv'\" \"Hclose\". iDestruct \"Hinv'\" as (e2 σ) \"[Hown %]\".\n    destruct (exist_fresh (dom (gset positive) σ)) as [l Hl%not_elem_of_dom].\n    iDestruct (own_valid_2 _ with \"Hown Hj\")\n      as %[[?%Excl_included%leibniz_equiv _]%prod_included ?]%auth_valid_discrete_2.\n    subst.\n    iMod (own_update_2 with \"Hown Hj\") as \"[Hown Hj]\".\n    { by eapply auth_update, prod_local_update_1, option_local_update,\n       (exclusive_local_update _ (Excl (fill K (Loc l)))). }\n    iMod (own_update with \"Hown\") as \"[Hown Hl]\".\n    { eapply auth_update_alloc, prod_local_update_2,\n        (alloc_singleton_local_update _ l (1%Qp,DecAgree v)); last done.\n      by apply lookup_to_heap_None. }\n    iExists l. rewrite /heapS_mapsto. iFrame \"Hj Hl\". iApply \"Hclose\". iNext.\n    iExists (fill K (Loc l)), (<[l:=v]>σ).\n    rewrite to_heap_insert; last eauto. iFrame. iPureIntro.\n    eapply rtc_r, step_insert_no_fork; eauto. econstructor; eauto.\n  Qed.\n\n  Lemma step_load E ρ K l q v:\n    nclose specN ⊆ E →\n    spec_ctx ρ ∗ ⤇ fill K (Load (Loc l)) ∗ l ↦ₛ{q} v\n    ={E}=∗ ⤇ fill K (of_val v) ∗ l ↦ₛ{q} v.\n  Proof.\n    iIntros (?) \"(#Hinv & Hj & Hl)\".\n    rewrite /spec_ctx /tpool_mapsto /heapS_mapsto.\n    iInv specN as \">Hinv'\" \"Hclose\". iDestruct \"Hinv'\" as (e2 σ) \"[Hown %]\".\n    iDestruct (own_valid_2 _ with \"Hown Hj\")\n      as %[[?%Excl_included%leibniz_equiv _]%prod_included ?]%auth_valid_discrete_2.\n    subst.\n    iDestruct (own_valid_2 _ with \"Hown Hl\")\n      as %[[_ ?%heap_singleton_included]%prod_included _]%auth_valid_discrete_2.\n    iMod (own_update_2 with \"Hown Hj\") as \"[Hown Hj]\".\n    { by eapply auth_update, prod_local_update_1, option_local_update,\n        (exclusive_local_update _ (Excl (fill K (of_val v)))). }\n    iFrame \"Hj Hl\". iApply \"Hclose\". iNext.\n    iExists (fill K (of_val v)), σ.\n    iFrame. iPureIntro.\n    eapply rtc_r, step_insert_no_fork; eauto. econstructor; eauto.\n  Qed.\n\n  Lemma step_store E ρ K l v' e v:\n    to_val e = Some v → nclose specN ⊆ E →\n    spec_ctx ρ ∗ ⤇ fill K (Store (Loc l) e) ∗ l ↦ₛ v'\n    ={E}=∗ ⤇ fill K Unit ∗ l ↦ₛ v.\n  Proof.\n    iIntros (??) \"(#Hinv & Hj & Hl)\".\n    rewrite /spec_ctx /tpool_mapsto /heapS_mapsto.\n    iInv specN as \">Hinv'\" \"Hclose\". iDestruct \"Hinv'\" as (e2 σ) \"[Hown %]\".\n    iDestruct (own_valid_2 _ with \"Hown Hj\")\n      as %[[?%Excl_included%leibniz_equiv _]%prod_included ?]%auth_valid_discrete_2.\n    subst.\n    iDestruct (own_valid_2 _ with \"Hown Hl\")\n      as %[[_ Hl%heap_singleton_included]%prod_included _]%auth_valid_discrete_2.\n    iMod (own_update_2 with \"Hown Hj\") as \"[Hown Hj]\".\n    { by eapply auth_update, prod_local_update_1, option_local_update,\n        (exclusive_local_update _ (Excl (fill K Unit))). }\n    iMod (own_update_2 with \"Hown Hl\") as \"[Hown Hl]\".\n    { eapply auth_update, prod_local_update_2, singleton_local_update,\n        (exclusive_local_update _ (1%Qp, DecAgree v)); last done.\n      by rewrite /to_heap lookup_fmap Hl. }\n    iFrame \"Hj Hl\". iApply \"Hclose\". iNext.\n    iExists (fill K Unit), (<[l:=v]>σ).\n    rewrite to_heap_insert; last eauto. iFrame. iPureIntro.\n    eapply rtc_r, step_insert_no_fork; eauto. econstructor; eauto.\n  Qed.\n\n  Lemma step_lam E ρ K e1 e2 v :\n    to_val e2 = Some v → nclose specN ⊆ E →\n    spec_ctx ρ ∗ ⤇ fill K (App (Lam e1) e2)\n    ={E}=∗ ⤇ fill K (e1.[e2/]).\n  Proof. intros ?; apply step_pure => σ; econstructor; eauto. Qed.\n\n  Lemma step_tlam E ρ K e :\n    nclose specN ⊆ E →\n    spec_ctx ρ ∗ ⤇ fill K (TApp (TLam e)) ={E}=∗ ⤇ fill K e.\n  Proof. apply step_pure => σ; econstructor; eauto. Qed.\n\n  Lemma step_Fold E ρ K e v :\n    to_val e = Some v → nclose specN ⊆ E →\n    spec_ctx ρ ∗ ⤇ fill K (Unfold (Fold e)) ={E}=∗ ⤇ fill K e.\n  Proof. intros H1; apply step_pure => σ; econstructor; eauto. Qed.\n\n  Lemma step_fst E ρ K e1 v1 e2 v2 :\n    to_val e1 = Some v1 → to_val e2 = Some v2 → nclose specN ⊆ E →\n    spec_ctx ρ ∗ ⤇ fill K (Fst (Pair e1 e2)) ={E}=∗ ⤇ fill K e1.\n  Proof. intros H1 H2; apply step_pure => σ; econstructor; eauto. Qed.\n\n  Lemma step_snd E ρ K e1 v1 e2 v2 :\n    to_val e1 = Some v1 → to_val e2 = Some v2 → nclose specN ⊆ E →\n    spec_ctx ρ ∗ ⤇ fill K (Snd (Pair e1 e2)) ={E}=∗ ⤇ fill K e2.\n  Proof. intros H1 H2; apply step_pure => σ; econstructor; eauto. Qed.\n\n  Lemma step_case_inl E ρ K e0 v0 e1 e2 :\n    to_val e0 = Some v0 → nclose specN ⊆ E →\n    spec_ctx ρ ∗ ⤇ fill K (Case (InjL e0) e1 e2)\n      ={E}=∗ ⤇ fill K (e1.[e0/]).\n  Proof. intros H1; apply step_pure => σ; econstructor; eauto. Qed.\n\n  Lemma step_case_inr E ρ K e0 v0 e1 e2 :\n    to_val e0 = Some v0 → nclose specN ⊆ E →\n    spec_ctx ρ ∗ ⤇ fill K (Case (InjR e0) e1 e2)\n      ={E}=∗ ⤇ fill K (e2.[e0/]).\n  Proof. intros H1; apply step_pure => σ; econstructor; eauto. Qed.\n\nEnd cfg.\n", "meta": {"author": "amintimany", "repo": "iris-logrel", "sha": "dad6c7edd1e6ef2d443a2da1ce55b8439b0bc261", "save_path": "github-repos/coq/amintimany-iris-logrel", "path": "github-repos/coq/amintimany-iris-logrel/iris-logrel-dad6c7edd1e6ef2d443a2da1ce55b8439b0bc261/F_mu_ref/rules_binary.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.20492470676515606}}
{"text": "Require Import VerifiedVerifier.Machine.\nRequire Import VerifiedVerifier.Maps.\nRequire Import VerifiedVerifier.Safety.\nRequire Import Coq.Init.Nat.\nRequire Import Coq.Lists.List.\nRequire Import Coq.Lists.ListSet.\nRequire Import VerifiedVerifier.BinaryLattice.\nRequire Import VerifiedVerifier.AbstractAnalysis.\nRequire Import VerifiedVerifier.Semantics.\nRequire Import Lia.\n\n\n(* TODO: Don't really know how to encode this*)\n(*\nDefinition function_safety (f : function_ty) :=\n*)\n\nDefinition program_safety (p : program_ty) : Prop :=\n  forall fuel,\n    (fst (run_program_stream p fuel)).(error) = false.\n\n(* NOTE: This probably isn't a useful definition *)\n(*\nDefinition function_safety (p : program_ty) (f : function_ty) : Prop :=\n  forall fuel s,\n    s.(error) = false ->\n    (run_function p f s fuel).(error) = false.\n*)\n\nTheorem program_maintains_error :\n  forall s,\n    s.(error) = true ->\n    forall p cfg n fuel,\n      (run_program' p cfg n s fuel).(error) = true.\nProof.\n  intros. induction fuel.\n  simpl. assumption.\n  simpl. destruct (next_node cfg s n).\n  - admit.\n  - admit.\nAdmitted.\n\nTheorem program_stream_maintains_error :\n  forall p fuel,\n    (fst (run_program_stream p fuel)).(error) = true ->\n    (fst (run_program_stream p (S fuel))).(error) = true.\nProof.\n  admit.\nAdmitted.\n\nDefinition function_safety (f : function_ty) : Prop :=\n  forall f cfg p n s fuel,\n    well_formed_program p ->\n    s.(error) = false ->\n    In f p.(fun_list) ->\n    cfg = fst f ->\n    In n cfg.(nodes) ->\n    (run_program' p cfg n s fuel).(error) = false.\n\nTheorem well_formed_find_edge_ret :\n  forall cfg n p f ,\n    well_formed_program p ->\n    In f p.(fun_list) ->\n    cfg = fst f ->\n    In n cfg.(nodes) ->\n    (last (fst n) Ret) = Ret ->\n    forall b,\n      find_edge cfg n b = None.\nProof.\n  admit.\nAdmitted.\n\nTheorem well_formed_find_edge_branch :\n  forall cfg n p f c,\n    well_formed_program p ->\n    In f p.(fun_list) ->\n    cfg = fst f ->\n    In n cfg.(nodes) ->\n    (last (fst n) Ret) = Branch c ->\n    exists n' n'',\n      find_edge cfg n True_Branch = Some n' /\\\n      find_edge cfg n False_Branch = Some n'' /\\\n      find_edge cfg n Non_Branch = None.\nProof.\n  admit.\nAdmitted.\n\n(* TODO: Might have to change how the conditional is handled *)\nTheorem well_formed_find_edge_non_branch :\n  forall cfg n p f c,\n    well_formed_program p ->\n    In f p.(fun_list) ->\n    cfg = fst f ->\n    In n cfg.(nodes) ->\n      (last (fst n) Ret) <> Ret ->\n      (last (fst n) Ret) <> Branch c ->\n      exists n',\n        find_edge cfg n True_Branch = None /\\\n        find_edge cfg n False_Branch = None /\\\n        find_edge cfg n Non_Branch = Some n'.\nProof.\n  admit.\nAdmitted.\n\nTheorem verified_function_lookup :\n  forall p,\n    well_formed_program p ->\n    verify_program p = true ->\n    forall s istream fuel r hd_i,\n      (s, istream) = run_program_stream p fuel ->\n      s.(error) = false ->\n      Some hd_i = hd_error istream ->\n      hd_i.(instr) = Indirect_Call r ->\n      (run_instr p hd_i.(instr) s).(error) = false.\nProof.\n  admit.\nAdmitted.\n\n(* NOTE: shouldn't even need to run the verifier for this one, just well-formedness *)\nTheorem verified_function_call :\n  forall p,\n    well_formed_program p ->\n    verify_program p = true ->\n    forall s istream fuel hd_i f_name,\n      (s, istream) = run_program_stream p fuel ->\n      s.(error) = false ->\n      Some hd_i = hd_error istream ->\n      hd_i.(instr) = Direct_Call f_name ->\n      (run_instr p hd_i.(instr) s).(error) = false.\nProof.\n  admit.\nAdmitted.\n\nTheorem verified_heap_read :\n  forall p,\n    well_formed_program p ->\n    verify_program p = true ->\n    forall s istream fuel hd_i r_dst r_src r_base,\n      (s, istream) = run_program_stream p fuel ->\n      s.(error) = false ->\n      Some hd_i = hd_error istream ->\n      hd_i.(instr) = Heap_Read r_dst r_src r_base ->\n      (run_instr p hd_i.(instr) s).(error) = false.\nProof.\n  admit.\nAdmitted.\n\nTheorem verified_heap_write :\n  forall p,\n    well_formed_program p ->\n    verify_program p = true ->\n    forall s istream fuel hd_i r_dst r_val r_base,\n      (s, istream) = run_program_stream p fuel ->\n      s.(error) = false ->\n      Some hd_i = hd_error istream ->\n      hd_i.(instr) = Heap_Write r_dst r_val r_base ->\n      (run_instr p hd_i.(instr) s).(error) = false.\nProof.\n  admit.\nAdmitted.\nProof.\n\nTheorem verified_stack_contract :\n  forall p,\n    well_formed_program p ->\n    verify_program p = true ->\n    forall s istream fuel hd_i i,\n      (s, istream) = run_program_stream p fuel ->\n      s.(error) = false ->\n      Some hd_i = hd_error istream ->\n      hd_i.(instr) = Stack_Contract i ->\n      (run_instr p hd_i.(instr) s).(error) = false.\n  admit.\nAdmitted.\n\nTheorem verified_stack_read :\n  forall p,\n    well_formed_program p ->\n    verify_program p = true ->\n    forall s istream fuel hd_i r i,\n      (s, istream) = run_program_stream p fuel ->\n      s.(error) = false ->\n      Some hd_i = hd_error istream ->\n      hd_i.(instr) = Stack_Read r i ->\n      (run_instr p hd_i.(instr) s).(error) = false.\nProof.\n  admit.\nAdmitted.\n\nTheorem verified_stack_write :\n  forall p,\n    well_formed_program p ->\n    verify_program p = true ->\n    forall s istream fuel hd_i i r,\n      (s, istream) = run_program_stream p fuel ->\n      s.(error) = false ->\n      Some hd_i = hd_error istream ->\n      hd_i.(instr) = Stack_Write i r ->\n      (run_instr p hd_i.(instr) s).(error) = false.\nProof.\n  admit.\nAdmitted.\n\nTheorem verify_get_instrs_till_terminal :\n  forall cfg n fuel p f,\n    well_formed_program p ->\n    In f p.(fun_list) ->\n    cfg = fst f ->\n    In n cfg.(nodes) ->\n    snd (get_instrs_till_terminal cfg n fuel) <> error_return.\nProof.\n  intros. unfold get_instrs_till_terminal.\n  induction fuel. unfold snd. discriminate.\n  fold get_instrs_till_terminal. fold get_instrs_till_terminal in IHfuel.\n  assert ((fst n) <> nil). unfold well_formed_program in H. destruct H. destruct H3. destruct H4. destruct H5.\n  - specialize H6 with f. apply H6 in H0. unfold well_formed_fun in H0. unfold well_formed_cfg in H0.\n    destruct H0. destruct H7. destruct H8. unfold non_empty_nodes in H8. specialize H8 with n. symmetry in H1.\n    rewrite H1 in H8. apply H8. apply H2.\n  - admit.\n    (* case (last (fst n) Ret); intros. *)\nAdmitted.\n\nTheorem verify_get_next_instrs :\n  forall p cfg n i s fuel,\n    well_formed_program p ->\n    exists f,\n      In f p.(fun_list) ->\n      cfg = fst f ->\n      In n cfg.(nodes) ->\n      In i (fst n) ->\n      verify_program p = true ->\n      snd (get_next_instrs p cfg n i s fuel) <> error_return.\nProof.\n  admit.\nAdmitted.\n\nTheorem run_program_stream_equiv :\n  forall p istream s fuel s' istream',\n    well_formed_program p ->\n    (s', istream') = run_program_stream' p istream s fuel ->\n    fst (run_program_stream' p istream s (S fuel)) = fst (run_program_stream' p istream' s' 1).\nProof.\n  admit.\nAdmitted.\n\nTheorem function_safety_run :\n  forall p s fuel,\n    well_formed_program p ->\n    verify_program p = true ->\n    s = run_program_stream p fuel ->\n    (fst s).(error) = false ->\n    (fst (run_program_stream p (S fuel))).(error) = false.\nProof.\n  intros. unfold run_program_stream.\n  admit.\nAdmitted.\n\n(* TODO: find official lemmas for these *)\nLemma distribute_fst {A : Type} {B : Type} :\n  forall (c : bool) (x: A) (y : A) (a : B) (b : B),\n    fst (if c then (x, a) else (y, b)) = if c then x else y.\nProof.\n  intros. case c; auto.\nQed.\n\nLemma error_set_exit :\n  forall s,\n    s.(error) = (set_exit_state s).(error).\nProof.\n  auto.\nQed.\n\nLemma distribute_error :\n  forall (c : bool) s s',\n    error (if c then s else s') = if c then (error s) else (error s').\nProof.\n  intros. case c; auto.\nQed.\n\nLemma if_eq :\n  forall (A : Type) (c : bool) (a : A),\n    (if c then a else a) = a.\nProof.\n  intros. case c; auto.\nQed.\n\nLemma tuple_eq :\n  forall (x : (state * list instr_data)),\n    (fst x, snd x) = x.\nProof.\n  intros. destruct x. simpl. auto.\nQed.\n\n(* TODO: Generalize these *)\nLemma tuple_eq' :\n  forall (x y : (state * list instr_data)),\n    x = y ->\n    fst x = fst y /\\ snd x = snd y.\nProof.\n  intros.\n  pose proof surjective_pairing as H1. specialize H1 with state (list instr_data) x.\n  rewrite H1 in H. destruct y. inversion H. rewrite H2. rewrite H3.\n  unfold fst. unfold snd. auto.\nQed.\n\nLemma tuple_split :\n  forall (a : state) (b : list instr_data) (x : (state * list instr_data)),\n    (a, b) = x ->\n    a = fst x /\\ b = snd x.\nProof.\n  intros. destruct x. pose proof tuple_eq'.\n  specialize H0 with (a, b) (s, l). apply H0 in H. inversion H.\n  split; auto.\nQed.\n\nLemma tuple_ret_eq' :\n  forall (x y : (list instr_data * return_state)),\n    x = y ->\n    fst x = fst y /\\ snd x = snd y.\nProof.\n  intros.\n  pose proof surjective_pairing as H1. specialize H1 with (list instr_data) return_state x.\n  rewrite H1 in H. destruct y. inversion H. rewrite H2. rewrite H3.\n  unfold fst. unfold snd. auto.\nQed.\n\nLemma tuple_ret_split :\n  forall (a : list instr_data) (b : return_state) (x : (list instr_data * return_state)),\n    (a, b) = x ->\n    a = fst x /\\ b = snd x.\nProof.\n  intros. destruct x. pose proof tuple_ret_eq'.\n  specialize H0 with (a, b) (l, r). apply H0 in H. inversion H.\n  split; auto.\nQed.\n\nLemma prog_stream_eq :\n  forall p fuel start_stream,\n    snd (get_instrs_till_terminal (fst (main p)) (start_node (fst (main p))) fuel) = normal_return ->\n    fst (get_instrs_till_terminal (fst (main p)) (start_node (fst (main p))) fuel) = start_stream ->\n    run_program_stream p fuel = run_program_stream' p start_stream (start_state p) fuel.\nProof.\n  intros. unfold run_program_stream.\n  remember (get_instrs_till_terminal (fst (main p)) (start_node (fst (main p))) fuel) as g.\n  destruct g. pose proof tuple_ret_split.\n  specialize H1 with l r (get_instrs_till_terminal (fst (main p)) (start_node (fst (main p))) fuel).\n  apply H1 in Heqg. inversion Heqg. simpl in H. simpl in H0. rewrite H. rewrite H0. reflexivity.\nQed.\n\nTheorem function_safety_run_other :\n  forall p s istream fuel start_stream s',\n    well_formed_program p ->\n    verify_program p = true ->\n    (snd (get_instrs_till_terminal (fst (main p)) (start_node (fst (main p))) fuel)) = normal_return ->\n    start_stream = (fst (get_instrs_till_terminal (fst (main p)) (start_node (fst (main p))) fuel)) ->\n    (s, istream) = run_program_stream' p start_stream (start_state p) fuel ->\n    s.(error) = false ->\n    s' = fst (run_program_stream' p start_stream (start_state p) (S fuel)) ->\n    s'.(error) = false.\nProof.\n  intros. assert (Hwell := H).\n  pose proof run_program_stream_equiv as Hequiv.\n  specialize Hequiv with p start_stream (start_state p) fuel s istream.\n  apply Hequiv in H.\n  - rewrite H in H5. rewrite H5. induction istream.\n    + unfold run_program_stream'.\n      case (error s || exit s)%bool. assumption. assumption.\n    + unfold run_program_stream'. case (error s || exit s)%bool. assumption.\n      destruct (get_next_instrs p (cfg a) (node a) (instr a) s 1).\n      destruct r. auto. admit.\n      remember (run_instr p (instr a) s) as s''.\n\n      assert ((fst (if (error s'' || exit s'')%bool\n                        then (s'', l ++ istream)\n                        else (set_exit_state s'', l ++ istream))) =\n                  (if (error s'' || exit s'')%bool\n                   then s''\n                   else set_exit_state s'')) as Hdist.\n      case (error s'' || exit s'')%bool; auto.\n\n      rewrite Hdist.\n      pose proof distribute_error as Herr.\n      specialize Herr with (error s'' || exit s'')%bool s'' (set_exit_state s'').\n      rewrite Herr.\n      pose proof error_set_exit as Hexit. specialize Hexit with s''. symmetry in Hexit.\n      rewrite Hexit.\n      pose proof if_eq as Hif. specialize Hif with bool (error s'' || exit s'')%bool (error s'').\n      rewrite Hif. rewrite Heqs''.\n      remember (instr a) as instr_a.\n      destruct instr_a; auto.\n      * pose proof verified_heap_read as Hinstr.\n        specialize Hinstr with p s (a :: istream) fuel a r r0 r1.\n        assert (instr a = Heap_Read r r0 r1). symmetry in Heqinstr_a. assumption.\n        rewrite H6 in Hinstr. apply Hinstr; auto. pose proof prog_stream_eq.\n        specialize H7 with p fuel start_stream.\n        symmetry in H7. rewrite H7 in H3. assumption. assumption. symmetry in H2. assumption.\n      * pose proof verified_heap_write as Hinstr.\n        specialize Hinstr with p s (a :: istream) fuel a r r0 r1.\n        assert (instr a = Heap_Write r r0 r1). symmetry in Heqinstr_a. assumption.\n        rewrite H6 in Hinstr. apply Hinstr; auto. pose proof prog_stream_eq.\n        specialize H7 with p fuel start_stream.\n        symmetry in H7. rewrite H7 in H3. assumption. assumption. symmetry in H2. assumption.\n      * simpl. destruct (function_lookup p (get_register s r)); auto.\n      * pose proof verified_stack_contract as Hinstr.\n        specialize Hinstr with p s (a :: istream) fuel a n.\n        assert (instr a = Stack_Contract n). symmetry in Heqinstr_a. assumption.\n        rewrite H6 in Hinstr. apply Hinstr; auto. pose proof prog_stream_eq.\n        specialize H7 with p fuel start_stream.\n        symmetry in H7. rewrite H7 in H3. assumption. assumption. symmetry in H2. assumption.\n      * pose proof verified_stack_read as Hinstr.\n        specialize Hinstr with p s (a :: istream) fuel a r n.\n        assert (instr a = Stack_Read r n). symmetry in Heqinstr_a. assumption.\n        rewrite H6 in Hinstr. apply Hinstr; auto. pose proof prog_stream_eq.\n        specialize H7 with p fuel start_stream.\n        symmetry in H7. rewrite H7 in H3. assumption. assumption. symmetry in H2. assumption.\n      * pose proof verified_stack_write as Hinstr.\n        specialize Hinstr with p s (a :: istream) fuel a n r.\n        assert (instr a = Stack_Write n r). symmetry in Heqinstr_a. assumption.\n        rewrite H6 in Hinstr. apply Hinstr; auto. pose proof prog_stream_eq.\n        specialize H7 with p fuel start_stream.\n        symmetry in H7. rewrite H7 in H3. assumption. assumption. symmetry in H2. assumption.\n  - assumption.\nAdmitted.\n\nTheorem get_instrs_till_terminal_ret :\n  forall cfg n fuel,\n    snd (get_instrs_till_terminal cfg n fuel) = normal_return ->\n    get_instrs_till_terminal cfg n fuel = get_instrs_till_terminal cfg n (S fuel).\nProof.\n  admit.\nAdmitted.\n\nTheorem verified_program :\n  forall p,\n    well_formed_program p ->\n    verify_program p = true ->\n    program_safety p.\nProof.\n  intros. unfold program_safety. intros. unfold run_program_stream.\n  pose proof verify_get_instrs_till_terminal as Hterminal.\n  specialize Hterminal with (fst (main p)) (start_node (fst (main p))) fuel p (main p).\n  assert (snd (get_instrs_till_terminal (fst (main p)) (start_node (fst (main p))) fuel) <> error_return).\n  apply Hterminal; auto.\n  unfold well_formed_program in H. destruct H. destruct H1. destruct H2. destruct H3. assumption.\n  unfold well_formed_program in H. destruct H. destruct H1. destruct H2. destruct H3.\n  specialize H4 with (main p). apply H4 in H3. unfold well_formed_fun in H3.\n  unfold well_formed_cfg in H3. destruct H3. destruct H5. destruct H6. assumption.\n\n\n  destruct (get_instrs_till_terminal (fst (main p)) (start_node (fst (main p))) fuel) eqn:Htest.\n  (*\n  assert (l = fst (get_instrs_till_terminal (fst (main p)) (start_node (fst (main p))) fuel)). admit.\n  assert (r = snd (get_instrs_till_terminal (fst (main p)) (start_node (fst (main p))) fuel)). admit.\n  *)\n  (* TODO: I don't know why the context forgets this information *)\n  unfold snd in H1. destruct r. auto. contradiction.\n  induction fuel.\n  simpl. reflexivity.\n  pose proof function_safety_run_other as Hstream'.\n  remember (run_program_stream' p l (start_state p) fuel) as s.\n  remember (run_program_stream' p l (start_state p) (S fuel)) as s'.\n  specialize Hstream' with p (fst (run_program_stream' p l (start_state p) fuel)) (snd s) fuel l (fst s').\n  pose proof get_instrs_till_terminal_ret as Hget. (*assert (r = normal_return). admit.*)\n  specialize Hget with (fst (main p)) (start_node (fst (main p))) fuel. symmetry in Hget.\n  apply Hstream'; auto.\n  - rewrite Hget. admit. admit.\n  - rewrite Hget. admit. admit.\n  - pose proof tuple_eq as Htup. specialize Htup with (run_program_stream' p l (start_state p) fuel).\n    rewrite Heqs. rewrite Htup. auto.\n  - admit.\n  - pose proof tuple_eq' as Htup'. specialize Htup' with s' (run_program_stream' p l (start_state p) (S fuel)).\n    apply Htup' in Heqs'. inversion Heqs'. assumption.\nAdmitted.\n\n\n(* NOTE: old version *)\n(*\nTheorem verified_program :\n  forall p,\n    well_formed_program p ->\n    verify_program p = true ->\n    program_safety p.\nProof.\n  intros. unfold program_safety. intros. unfold run_program.\n  unfold run_program'. induction fuel.\n  simpl. reflexivity. fold run_program'. fold run_program' in IHfuel.\n  destruct (next_node (fst (main p)) (start_state p) (start_node (fst (main p)))).\n  -\n    + destruct (last (fst (start_node (fst (main p)))) Ret). unfold run_basic_block.\n  -\n\n\n  induction p.(fun_list).\n  - unfold run_program'. induction fuel.\n    + simpl. reflexivity.\n    + destruct (next_node (fst (main p)) (start_state p) (start_node (fst (main p)))).\n      *\n*)\n", "meta": {"author": "PLSysSec", "repo": "veriwasm-verification", "sha": "72c56df33e7fce0e05babef860772146412f825f", "save_path": "github-repos/coq/PLSysSec-veriwasm-verification", "path": "github-repos/coq/PLSysSec-veriwasm-verification/veriwasm-verification-72c56df33e7fce0e05babef860772146412f825f/theory/GlobalSafety.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.20478461876234047}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import Progress.\n\nRequire Import LowerPromises.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import SimThread.\n\nSet Implicit Arguments.\n\n\nLemma read_step_cur_future\n      lc1 mem1 loc val released ord lc2\n      (WF1: Local.wf lc1 mem1)\n      (ORD: Ordering.le ord Ordering.relaxed)\n      (READ: Local.read_step lc1 mem1 loc ((TView.cur (Local.tview lc1)).(View.rlx) loc) val released ord lc2):\n  <<PROMISES: (Local.promises lc1) = (Local.promises lc2)>> /\\\n  <<TVIEW_RLX: (TView.cur (Local.tview lc1)).(View.rlx) = (TView.cur (Local.tview lc2)).(View.rlx)>> /\\\n  <<TVIEW_PLN: forall l (LOC: l <> loc),\n      (TView.cur (Local.tview lc1)).(View.pln) l = (TView.cur (Local.tview lc2)).(View.pln) l>>.\nProof.\n  destruct lc1 as [tview1 promises1]. inv READ. ss.\n  esplits; eauto.\n  - condtac; ss; try by destruct ord.\n    apply TimeMap.antisym.\n    + etrans; [|apply TimeMap.join_l]. apply TimeMap.join_l.\n    + apply TimeMap.join_spec; auto using TimeMap.bot_spec.\n      apply TimeMap.join_spec; try refl.\n      unfold View.singleton_ur_if. condtac; ss.\n      * ii. unfold TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n        condtac; try apply Time.bot_spec.\n        subst. refl.\n      * ii. unfold TimeMap.singleton, LocFun.add, LocFun.init, LocFun.find.\n        condtac; try apply Time.bot_spec.\n        subst. refl.\n  - i. condtac; ss; try by destruct ord.\n    unfold TimeMap.join, TimeMap.bot.\n    rewrite TimeFacts.le_join_l; try apply Time.bot_spec.\n    rewrite TimeFacts.le_join_l; ss.\n    etrans; [|apply Time.bot_spec].\n    unfold View.singleton_ur_if. condtac; ss; try refl.\n    unfold TimeMap.singleton, LocFun.add, LocFun.init. condtac; ss. refl.\nQed.\n\nLemma fence_step_future\n      lc1 sc1 ordr ordw lc2 sc2\n      (ORDR: Ordering.le ordr Ordering.relaxed)\n      (ORDW: Ordering.le ordw Ordering.acqrel)\n      (FENCE: Local.fence_step lc1 sc1 ordr ordw lc2 sc2):\n  <<PROMISES: (Local.promises lc1) = (Local.promises lc2)>> /\\\n  <<TVIEW: (TView.cur (Local.tview lc1)) = (TView.cur (Local.tview lc2))>>.\nProof.\n  destruct lc1 as [tview1 promises1]. inv FENCE. split; ss.\n  condtac; try by destruct ordw.\n  condtac; try by destruct ordr.\nQed.\n\nLemma write_step_consistent\n      lc1 sc1 mem1\n      loc val ord\n      (WF1: Local.wf lc1 mem1)\n      (SC1: Memory.closed_timemap sc1 mem1)\n      (MEM1: Memory.closed mem1)\n      (PROMISES1: Ordering.le Ordering.strong_relaxed ord -> Memory.nonsynch_loc loc (Local.promises lc1))\n      (CONS1: Local.promise_consistent lc1):\n  exists from to released lc2 sc2 mem2 kind,\n    <<STEP: Local.write_step lc1 sc1 mem1 loc from to val None released ord lc2 sc2 mem2 kind>> /\\\n    <<CONS2: Local.promise_consistent lc2>>.\nProof.\n  destruct (classic (exists f t m, Memory.get loc t (Local.promises lc1) = Some (f, m) /\\\n                              m <> Message.reserve)).\n  { des.\n    exploit Memory.min_concrete_ts_exists; eauto. i. des.\n    exploit Memory.min_concrete_ts_spec; eauto. i. des.\n    exploit Memory.get_ts; try exact GET. i. des.\n    { subst. inv WF1. rewrite BOT in *. ss. }\n    clear f t m H H0 MIN.\n    exploit progress_write_step_split; try exact GET; eauto.\n    { ss. unfold TimeMap.bot. apply Time.bot_spec. }\n    i. des.\n    esplits; eauto. ii.\n    assert (TS: loc0 = loc -> Time.le ts ts0).\n    { i. subst. inv x2. inv WRITE. inv PROMISE0. ss.\n      revert PROMISE.\n      erewrite Memory.remove_o; eauto. condtac; ss. des; ss.\n      erewrite Memory.split_o; eauto. repeat condtac; ss; i.\n      - des; ss. subst. refl.\n      - des; ss. \n        exploit Memory.min_concrete_ts_spec; try exact PROMISE; eauto. i. des. ss. }\n    inv x2. inv WRITE. inv PROMISE0. ss.\n    unfold TimeMap.join, TimeMap.singleton.\n    unfold LocFun.add, LocFun.init, LocFun.find.\n    condtac; ss.\n    - subst. apply TimeFacts.join_spec_lt.\n      + eapply TimeFacts.lt_le_lt; try eapply TS; eauto.\n      + eapply TimeFacts.lt_le_lt; try eapply TS; eauto.\n        apply Time.middle_spec. ss.\n    - revert PROMISE.\n      erewrite Memory.remove_o; eauto. condtac; ss.\n      erewrite Memory.split_o; eauto. repeat condtac; ss; try by des; ss.\n      guardH o. guardH o0. guardH o1. i.\n      apply TimeFacts.join_spec_lt; eauto.\n      destruct (TimeFacts.le_lt_dec ts0 Time.bot); ss.\n      inv l; inv H.\n      inv WF1. rewrite BOT in *. ss.\n  }\n  { exploit progress_write_step; eauto.\n    { apply Time.incr_spec. }\n    i. des.\n    esplits; eauto. ii.\n    inv x0. inv WRITE. inv PROMISE0. ss.\n    revert PROMISE.\n    erewrite Memory.remove_o; eauto. condtac; ss.\n    erewrite Memory.add_o; eauto. condtac; ss. i.\n    destruct (Loc.eq_dec loc0 loc).\n    - subst. exfalso. apply H; eauto.\n    - unfold TimeMap.join, TimeMap.singleton.\n      unfold LocFun.add, LocFun.init, LocFun.find.\n      condtac; ss.\n      apply TimeFacts.join_spec_lt; eauto.\n      destruct (TimeFacts.le_lt_dec ts Time.bot); ss.\n      inv l; inv H0.\n      inv WF1. rewrite BOT in *. ss.\n  }\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/transformation/ReorderAbortCommon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.20478461094266612}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import RunAux.Spec.\n\nLocal Open Scope Z_scope.\n\nSection SpecLow.\n\n  Definition complete_mmio_emulation_spec0 (rec: Pointer) (adt: RData) : option (RData * Z) :=\n    match rec with\n    | (_rec_base, _rec_ofst) =>\n      when' _t'7 == get_rec_run_is_emulated_mmio_spec  adt;\n      rely is_int64 _t'7;\n      if (_t'7 =? 0) then\n        Some (adt, 1)\n      else\n        when' _esr == get_rec_last_run_info_esr_spec (_rec_base, _rec_ofst) adt;\n        rely is_int64 _esr;\n        when _rt == esr_srt_spec (VZ64 _esr) adt;\n        rely is_int _rt;\n        rely is_int64 (Z.land _esr 4227858432);\n        if (negb ((Z.land _esr 4227858432) =? 2415919104)) then\n          let _t'6 := 1 in\n          Some (adt, 0)\n        else\n          rely is_int64 (Z.land _esr 16777216);\n          let _t'6 := ((Z.land _esr 16777216) =? 0) in\n          if _t'6 then\n            Some (adt, 0)\n          else\n            when _t'3 == esr_is_write_spec (VZ64 _esr) adt;\n            rely is_int _t'3;\n            if (_t'3 =? 0) then\n              let _t'4 := (negb (_rt =? 31)) in\n              if _t'4 then\n                when adt == emulate_mmio_read_spec (VZ64 _esr) _rt (_rec_base, _rec_ofst) adt;\n                when' _t'5 == get_rec_pc_spec (_rec_base, _rec_ofst) adt;\n                rely is_int64 _t'5;\n                rely is_int64 (_t'5 + 4);\n                when adt == set_rec_pc_spec (_rec_base, _rec_ofst) (VZ64 (_t'5 + 4)) adt;\n                Some (adt, 1)\n              else\n                when' _t'5 == get_rec_pc_spec (_rec_base, _rec_ofst) adt;\n                rely is_int64 _t'5;\n                rely is_int64 (_t'5 + 4);\n                when adt == set_rec_pc_spec (_rec_base, _rec_ofst) (VZ64 (_t'5 + 4)) adt;\n                Some (adt, 1)\n            else\n              let _t'4 := 0 in\n              when' _t'5 == get_rec_pc_spec (_rec_base, _rec_ofst) adt;\n              rely is_int64 _t'5;\n              rely is_int64 (_t'5 + 4);\n              when adt == set_rec_pc_spec (_rec_base, _rec_ofst) (VZ64 (_t'5 + 4)) adt;\n              Some (adt, 1)\n     end\n    .\n\nEnd SpecLow.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RunComplete/LowSpecs/complete_mmio_emulation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.2047359765296518}}
{"text": "Require Import VerdiRaft.Raft.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.SpecLemmas.\n\nRequire Import VerdiRaft.AppendEntriesReplySublogInterface.\nRequire Import VerdiRaft.SortedInterface.\n\nRequire Import VerdiRaft.NextIndexSafetyInterface.\n\nSection NextIndexSafety.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {aersi : append_entries_reply_sublog_interface}.\n  Context {si : sorted_interface}.\n\n  Lemma nextIndex_safety_init :\n    raft_net_invariant_init nextIndex_safety.\n  Proof using. \n    unfold raft_net_invariant_init, nextIndex_safety.\n    intros.\n    discriminate.\n  Qed.\n\n  Definition nextIndex_preserved st st' :=\n    (type st' = Leader ->\n     type st = Leader /\\\n     maxIndex (log st) <= maxIndex (log st') /\\\n     nextIndex st' = nextIndex st).\n\n  Lemma nextIndex_safety_preserved :\n    forall st st',\n      (forall h',\n          type st = Leader ->\n          Nat.pred (getNextIndex st h') <= maxIndex (log st)) ->\n      nextIndex_preserved st st' ->\n      (forall h',\n          type st' = Leader ->\n          Nat.pred (getNextIndex st' h') <= maxIndex (log st')).\n  Proof using. \n    unfold getNextIndex, nextIndex_preserved in *.\n    intuition.\n    repeat find_rewrite.\n    auto.\n    unfold assoc_default in *.\n    specialize (H h').\n    break_match.\n    - eauto using Nat.le_trans.\n    - lia.\n  Qed.\n\n  Theorem handleClientRequest_nextIndex_preserved :\n    forall h st client id c out st' ps,\n      handleClientRequest h st client id c = (out, st', ps) ->\n      nextIndex_preserved st st'.\n  Proof using. \n    unfold handleClientRequest, nextIndex_preserved.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; try congruence.\n    intuition.\n  Qed.\n\n  Lemma nextIndex_safety_client_request :\n    raft_net_invariant_client_request nextIndex_safety.\n  Proof using. \n    unfold raft_net_invariant_client_request, nextIndex_safety.\n    simpl.\n    intros.\n    repeat find_higher_order_rewrite.\n    update_destruct_simplify.\n    - eauto using nextIndex_safety_preserved, handleClientRequest_nextIndex_preserved.\n    - auto.\n  Qed.\n\n  Lemma handleTimeout_nextIndex_preserved :\n    forall h d out d' l,\n      handleTimeout h d = (out, d', l) ->\n      nextIndex_preserved d d'.\n  Proof using. \n    unfold handleTimeout, tryToBecomeLeader, nextIndex_preserved.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; try congruence.\n    auto.\n  Qed.\n\n  Lemma nextIndex_safety_timeout :\n    raft_net_invariant_timeout nextIndex_safety.\n  Proof using. \n    unfold raft_net_invariant_timeout, nextIndex_safety.\n    simpl.\n    intros.\n    repeat find_higher_order_rewrite.\n    update_destruct_simplify.\n    - eauto using nextIndex_safety_preserved, handleTimeout_nextIndex_preserved.\n    - auto.\n  Qed.\n\n  Lemma handleAppendEntries_nextIndex_preserved :\n    forall h st t n pli plt es ci st' ps,\n      handleAppendEntries h st t n pli plt es ci = (st', ps) ->\n      nextIndex_preserved st st'.\n  Proof using. \n    unfold handleAppendEntries, nextIndex_preserved, advanceCurrentTerm.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; try congruence; auto.\n  Qed.\n\n  Lemma nextIndex_safety_append_entries :\n    raft_net_invariant_append_entries nextIndex_safety.\n  Proof using. \n    unfold raft_net_invariant_append_entries, nextIndex_safety.\n    simpl.\n    intros.\n    repeat find_higher_order_rewrite.\n    update_destruct_simplify.\n    - eauto using nextIndex_safety_preserved, handleAppendEntries_nextIndex_preserved.\n    - auto.\n  Qed.\n\n  Lemma handleAppendEntriesReply_nextIndex :\n    forall h st st' m t es res h',\n      handleAppendEntriesReply h st h' t es res = (st', m) ->\n      type st' = Leader ->\n      type st = Leader /\\\n      ((nextIndex st' = nextIndex st \\/\n       (res = true /\\\n        currentTerm st = t /\\\n        nextIndex st' =\n        (assoc_set name_eq_dec (nextIndex st) h'\n                   (Nat.max (getNextIndex st h') (S (maxIndex es)))))) \\/\n      (res = false /\\\n       currentTerm st = t /\\\n       nextIndex st' =\n        (assoc_set name_eq_dec (nextIndex st) h'\n                   (pred (getNextIndex st h'))))).\n  Proof using. \n    unfold handleAppendEntriesReply, advanceCurrentTerm.\n    intros.\n    repeat break_match; repeat find_inversion; do_bool; simpl in *; intuition; congruence.\n  Qed.\n\n\n  Lemma nextIndex_safety_append_entries_reply :\n    raft_net_invariant_append_entries_reply nextIndex_safety.\n  Proof using si aersi. \n    unfold raft_net_invariant_append_entries_reply, nextIndex_safety, getNextIndex.\n    simpl.\n    intros.\n    repeat find_higher_order_rewrite.\n    update_destruct_simplify.\n    - erewrite handleAppendEntriesReply_log by eauto.\n      find_copy_apply_lem_hyp handleAppendEntriesReply_nextIndex; auto.\n      intuition; repeat find_rewrite.\n      + auto.\n      + destruct (name_eq_dec h' (pSrc p)).\n        * subst. rewrite get_set_same_default.\n          unfold getNextIndex.\n          apply Nat.max_case; auto.\n          { destruct es; simpl.\n            * lia.\n            * pose proof append_entries_reply_sublog_invariant _ ltac:(eauto).\n              unfold append_entries_reply_sublog in *.\n              eapply_prop_hyp pBody pBody; simpl; eauto.\n              apply maxIndex_is_max; auto.\n              apply logs_sorted_invariant; auto.\n          }\n        * rewrite get_set_diff_default by auto.\n          auto.\n      + destruct (name_eq_dec h' (pSrc p)).\n        * subst. rewrite get_set_same_default.\n          unfold getNextIndex.\n          apply NPeano.Nat.le_le_pred.\n          auto.\n        * rewrite get_set_diff_default by auto.\n          auto.\n    - auto.\n  Qed.\n\n  Lemma handleRequestVote_nextIndex_preserved :\n    forall st h h' t lli llt st' m,\n      handleRequestVote h st t h' lli llt = (st', m) ->\n      nextIndex_preserved st st'.\n  Proof using. \n    unfold handleRequestVote, nextIndex_preserved, advanceCurrentTerm.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto; try congruence.\n  Qed.\n\n  Lemma nextIndex_safety_request_vote :\n    raft_net_invariant_request_vote nextIndex_safety.\n  Proof using. \n    unfold raft_net_invariant_request_vote, nextIndex_safety.\n    simpl.\n    intros.\n    repeat find_higher_order_rewrite.\n    update_destruct_simplify.\n    - eauto using nextIndex_safety_preserved, handleRequestVote_nextIndex_preserved.\n    - auto.\n  Qed.\n\n  Lemma handleRequestVoteReply_matchIndex :\n    forall n st src t v,\n      type (handleRequestVoteReply n st src t v) = Leader ->\n      type st = Leader /\\\n      nextIndex (handleRequestVoteReply n st src t v) =\n      nextIndex st \\/\n      nextIndex (handleRequestVoteReply n st src t v) = [].\n  Proof using. \n    unfold handleRequestVoteReply.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto; try congruence.\n  Qed.\n\n  Lemma nextIndex_safety_request_vote_reply :\n    raft_net_invariant_request_vote_reply nextIndex_safety.\n  Proof using. \n    unfold raft_net_invariant_request_vote_reply, nextIndex_safety.\n    simpl.\n    intros.\n    repeat find_higher_order_rewrite.\n    update_destruct_simplify.\n    - find_copy_apply_lem_hyp handleRequestVoteReply_matchIndex.\n      unfold getNextIndex in *.\n      erewrite handleRequestVoteReply_log in * by eauto.\n      intuition; repeat find_rewrite.\n      + auto.\n      + unfold assoc_default. simpl.\n        auto using NPeano.Nat.le_le_pred.\n    - auto.\n  Qed.\n\n  Lemma doLeader_nextIndex_preserved :\n        forall st h os st' ms,\n      doLeader st h = (os, st', ms) ->\n      nextIndex_preserved st st'.\n  Proof using. \n    unfold doLeader, nextIndex_preserved.\n    intros.\n    repeat break_match; repeat find_inversion; auto; try congruence.\n  Qed.\n\n  Lemma nextIndex_safety_do_leader :\n    raft_net_invariant_do_leader nextIndex_safety.\n  Proof using. \n    unfold raft_net_invariant_do_leader, nextIndex_safety.\n    simpl.\n    intros.\n    repeat find_higher_order_rewrite.\n    update_destruct_simplify.\n    - eauto using nextIndex_safety_preserved, doLeader_nextIndex_preserved.\n    - auto.\n  Qed.\n\n  Lemma doGenericServer_nextIndex_preserved :\n    forall h st os st' ms,\n      doGenericServer h st = (os, st', ms) ->\n      nextIndex_preserved st st'.\n  Proof using. \n    unfold doGenericServer, nextIndex_preserved.\n    intros.\n    repeat break_match; repeat find_inversion; simpl in *; auto; try congruence;\n    use_applyEntries_spec; subst; simpl in *; auto.\n  Qed.\n\n  Lemma nextIndex_safety_do_generic_server :\n    raft_net_invariant_do_generic_server nextIndex_safety.\n  Proof using. \n    unfold raft_net_invariant_do_generic_server, nextIndex_safety.\n    simpl.\n    intros.\n    repeat find_higher_order_rewrite.\n    update_destruct_simplify.\n    - eauto using nextIndex_safety_preserved, doGenericServer_nextIndex_preserved.\n    - auto.\n  Qed.\n\n  Lemma nextIndex_safety_state_same_packet_subset :\n    raft_net_invariant_state_same_packet_subset nextIndex_safety.\n  Proof using. \n    unfold raft_net_invariant_state_same_packet_subset, nextIndex_safety.\n    simpl.\n    intros.\n    repeat find_reverse_higher_order_rewrite.\n    auto.\n  Qed.\n\n  Lemma nextIndex_safety_reboot :\n    raft_net_invariant_reboot nextIndex_safety.\n  Proof using. \n    unfold raft_net_invariant_reboot, nextIndex_safety, reboot.\n    simpl.\n    intros.\n    subst.\n    repeat find_higher_order_rewrite.\n    update_destruct_simplify.\n    - unfold getNextIndex, assoc_default. simpl. lia.\n    - auto.\n  Qed.\n\n  Lemma nextIndex_safety_invariant :\n    forall net,\n      raft_intermediate_reachable net ->\n      nextIndex_safety net.\n  Proof using si aersi. \n    intros.\n    apply raft_net_invariant; auto.\n    - apply nextIndex_safety_init.\n    - apply nextIndex_safety_client_request.\n    - apply nextIndex_safety_timeout.\n    - apply nextIndex_safety_append_entries.\n    - apply nextIndex_safety_append_entries_reply.\n    - apply nextIndex_safety_request_vote.\n    - apply nextIndex_safety_request_vote_reply.\n    - apply nextIndex_safety_do_leader.\n    - apply nextIndex_safety_do_generic_server.\n    - apply nextIndex_safety_state_same_packet_subset.\n    - apply nextIndex_safety_reboot.\n  Qed.\n\n  Instance nisi : nextIndex_safety_interface.\n  Proof.\n    split.\n    exact nextIndex_safety_invariant.\n  Qed.\nEnd NextIndexSafety.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft-proofs/NextIndexSafetyProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.20467695102322558}}
{"text": "From iris.proofmode Require Import proofmode.\nFrom iris.program_logic Require Import weakestpre adequacy lifting.\nFrom stdpp Require Import base.\nFrom cap_machine Require Export logrel.\nFrom cap_machine.ftlr Require Export ftlr_base.\nFrom cap_machine.rules Require Export rules_Get rules_base.\n\nSection fundamental.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ} {sealsg: sealStoreG Σ}\n          {nainv: logrel_na_invs Σ}\n          `{MachineParameters}.\n  Notation D := ((leibnizO Word) -n> iPropO Σ).\n  Notation R := ((leibnizO Reg) -n> iPropO Σ).\n  Implicit Types w : (leibnizO Word).\n  Implicit Types interp : (D).\n\n  Lemma get_case (r : leibnizO Reg) (p : Perm)\n        (b e a : Addr) (w : Word) (dst r0 : RegName) (ins: instr) (P:D) :\n    is_Get ins dst r0 →\n    ftlr_instr r p b e a w ins P.\n  Proof.\n    intros Hinstr Hp Hsome i Hbae Hi.\n    iIntros \"#IH #Hinv #Hinva #Hreg #[Hread Hwrite] Hown Ha HP Hcls HPC Hmap\".\n    rewrite delete_insert_delete.\n    rewrite <- Hi in Hinstr. clear Hi.\n    iDestruct ((big_sepM_delete _ _ PC) with \"[HPC Hmap]\") as \"Hmap /=\";\n      [apply lookup_insert|rewrite delete_insert_delete;iFrame|]. simpl.\n    iApply (wp_Get with \"[$Ha $Hmap]\"); eauto.\n    { simplify_map_eq; auto. }\n    { rewrite /subseteq /map_subseteq /set_subseteq_instance. intros rr _.\n      apply elem_of_dom. apply lookup_insert_is_Some'; eauto. }\n\n    iIntros \"!>\" (regs' retv). iDestruct 1 as (HSpec) \"[Ha Hmap]\".\n    destruct HSpec; cycle 1.\n    { iApply wp_pure_step_later; auto. iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro]. iNext.\n      iIntros \"_\".\n      iApply wp_value; auto. iIntros; discriminate. }\n    { incrementPC_inv; simplify_map_eq.\n      iApply wp_pure_step_later; auto. iMod (\"Hcls\" with \"[HP Ha]\");[iExists w;iFrame|iModIntro]. iNext.\n      assert (dst <> PC) as HdstPC by (intros ->; simplify_map_eq).\n      iIntros \"_\".\n      simplify_map_eq.\n      iApply (\"IH\" $! (<[dst := _]> (<[PC := _]> r)) with \"[%] [] [Hmap] [$Hown]\");\n        try iClear \"IH\"; eauto.\n      { intro. cbn. by repeat (rewrite lookup_insert_is_Some'; right). }\n      iIntros (ri v Hri Hsv). rewrite insert_commute // lookup_insert_ne // in Hsv; [].\n      destruct (decide (ri = dst)); simplify_map_eq.\n      { repeat rewrite fixpoint_interp1_eq; auto. }\n      { by iApply \"Hreg\". } rewrite !fixpoint_interp1_eq /=. destruct Hp as [-> | ->];iFrame \"Hinv\". }\n  Qed.\n\nEnd fundamental.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/ftlr/Get.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.20467694797408517}}
{"text": "(* Distributed under the terms of the MIT license. *)\nFrom Coq Require Import CRelationClasses.\nFrom Equations.Type Require Import Relation Relation_Properties.\nFrom MetaCoq.Template Require Import config utils BasicAst.\nFrom MetaCoq.PCUIC Require Import PCUICAst PCUICAstUtils\n     PCUICLiftSubst PCUICEquality PCUICUnivSubst\n     PCUICReduction.\n\nSet Default Goal Selector \"!\".\n\n(** * Definition of cumulativity and conversion relations *)\n\nReserved Notation \" Σ ;;; Γ |- t <=[ pb ] u\" (at level 50, Γ, t, u at next level,\n  format \"Σ  ;;;  Γ  |-  t  <=[ pb ] u\").\n\nDefinition leq_term_ext `{checker_flags} (Σ : global_env_ext) Rle t u := eq_term_upto_univ Σ (eq_universe Σ) Rle t u.\n\nNotation \" Σ ⊢ t <===[ pb ] u\" := (compare_term pb Σ Σ t u) (at level 50, t, u at next level).\n\n(** ** Cumulativity *)\n\nInductive cumulAlgo_gen `{checker_flags} (Σ : global_env_ext) (Γ : context) (pb : conv_pb) : term -> term -> Type :=\n| cumul_refl t u : Σ ⊢ t <===[ pb ] u -> Σ ;;; Γ |- t <=[pb] u\n| cumul_red_l t u v : Σ ;;; Γ |- t ⇝ v -> Σ ;;; Γ |- v <=[pb] u -> Σ ;;; Γ |- t <=[pb] u\n| cumul_red_r t u v : Σ ;;; Γ |- t <=[pb] v -> Σ ;;; Γ |- u ⇝ v -> Σ ;;; Γ |- t <=[pb] u\nwhere \" Σ ;;; Γ |- t <=[ pb ] u \" := (cumulAlgo_gen Σ Γ pb t u) : type_scope.\n\nNotation \" Σ ;;; Γ |- t = u \" := (cumulAlgo_gen Σ Γ Conv t u) (at level 50, Γ, t, u at next level) : type_scope.\nNotation \" Σ ;;; Γ |- t <= u \" := (cumulAlgo_gen Σ Γ Cumul t u) (at level 50, Γ, t, u at next level) : type_scope.\n\nNotation cumulAlgo Σ Γ := (cumulAlgo_gen Σ Γ Cumul).\nNotation convAlgo Σ Γ := (cumulAlgo_gen Σ Γ Conv).\n\n#[global]\nHint Resolve cumul_refl : pcuic.\n\nInclude PCUICConversion.\n\nModule PCUICConversionParAlgo <: EnvironmentTyping.ConversionParSig PCUICTerm PCUICEnvironment PCUICTermUtils PCUICEnvTyping.\n  Definition cumul_gen := @cumulAlgo_gen.\nEnd PCUICConversionParAlgo.\n\n#[global]\nInstance cumul_pb_decls_refl {cf:checker_flags} pb Σ Γ Γ' : Reflexive (cumul_pb_decls cumulAlgo_gen pb Σ Γ Γ').\nProof.\n  intros x. destruct x as [na [b|] ty]; constructor; auto.\n  all:constructor; reflexivity.\nQed.\n\n#[global]\nInstance conv_decls_refl {cf:checker_flags} Σ Γ Γ' : Reflexive (conv_decls cumulAlgo_gen Σ Γ Γ') := _.\n#[global]\nInstance cumul_decls_refl {cf:checker_flags} Σ Γ Γ' : Reflexive (cumul_decls cumulAlgo_gen Σ Γ Γ') := _.\n\nLemma cumul_alt `{cf : checker_flags} Σ Γ t u :\n  Σ ;;; Γ |- t <= u <~> { v & { v' & (red Σ Γ t v * red Σ Γ u v' *\n  leq_term_ext Σ (leq_universe Σ) v v')%type } }.\nProof.\n  split.\n  - induction 1.\n    + exists t, u. intuition auto.\n    + destruct IHX as (v' & v'' & (redv & redv') & leqv).\n      exists v', v''. intuition auto. now eapply red_step.\n    + destruct IHX as (v' & v'' & (redv & redv') & leqv).\n      exists v', v''. intuition auto. now eapply red_step.\n  - intros [v [v' [[redv redv'] Hleq]]].\n    apply clos_rt_rt1n in redv.\n    apply clos_rt_rt1n in redv'.\n    induction redv.\n    * induction redv'.\n    ** constructor; auto.\n    ** econstructor 3; eauto.\n    * econstructor 2; eauto.\nQed.\n\n#[global]\nInstance cumul_refl' {cf:checker_flags} Σ Γ pb : Reflexive (cumulAlgo_gen Σ Γ pb).\nProof.\n  intro; constructor; reflexivity.\nQed.\n\n#[global]\nInstance conv_refl' {cf:checker_flags} Σ Γ : Reflexive (convAlgo Σ Γ).\nProof.\n  intro; constructor. unfold leq_term_ext. reflexivity.\nQed.\n\nLemma red_cumul `{cf : checker_flags} {Σ : global_env_ext} {Γ t u} :\n  red Σ Γ t u ->\n  Σ ;;; Γ |- t <= u.\nProof.\n  intros. apply clos_rt_rt1n in X.\n  induction X.\n  - reflexivity.\n  - econstructor 2. all: eauto.\nQed.\n\nLemma red_cumul_inv `{cf : checker_flags} {Σ : global_env_ext} {Γ t u} :\n  red Σ Γ t u ->\n  Σ ;;; Γ |- u <= t.\nProof.\n  intros. apply clos_rt_rt1n in X.\n  induction X.\n  - reflexivity.\n  - econstructor 3. all: eauto.\nQed.\n\nLemma red_cumul_cumul `{cf : checker_flags} {Σ : global_env_ext} {Γ t u v} :\n  red Σ Γ t u -> Σ ;;; Γ |- u <= v -> Σ ;;; Γ |- t <= v.\nProof.\n  intros. apply clos_rt_rt1n in X.\n  induction X. 1: auto.\n  econstructor 2; eauto.\nQed.\n\nLemma red_cumul_cumul_inv `{cf : checker_flags} {Σ : global_env_ext} {Γ t u v} :\n  red Σ Γ t v -> Σ ;;; Γ |- u <= v -> Σ ;;; Γ |- u <= t.\nProof.\n  intros. apply clos_rt_rt1n in X.\n  induction X. 1: auto.\n  econstructor 3.\n  - eapply IHX. eauto.\n  - eauto.\nQed.\n\nLemma conv_cumul2 {cf:checker_flags} Σ Γ t u :\n  Σ ;;; Γ |- t = u -> (Σ ;;; Γ |- t <= u) * (Σ ;;; Γ |- u <= t).\nProof.\n  induction 1.\n  - split; constructor; now apply eq_term_leq_term.\n  - destruct IHX as [H1 H2]. split.\n    * econstructor 2; eassumption.\n    * econstructor 3; eassumption.\n  - destruct IHX as [H1 H2]. split.\n    * econstructor 3; eassumption.\n    * econstructor 2; eassumption.\nQed.\n\nLemma conv_cumul {cf:checker_flags} Σ Γ t u :\n  Σ ;;; Γ |- t = u -> Σ ;;; Γ |- t <= u.\nProof.\n  intro H; now apply conv_cumul2 in H.\nQed.\n\nLemma conv_cumul_inv {cf:checker_flags} Σ Γ t u :\n  Σ ;;; Γ |- u = t -> Σ ;;; Γ |- t <= u.\nProof.\n  intro H; now apply conv_cumul2 in H.\nQed.\n\nLemma red_conv {cf:checker_flags} (Σ : global_env_ext) Γ t u\n  : red Σ Γ t u -> Σ ;;; Γ |- t = u.\nProof.\n  intros H%clos_rt_rt1n_iff.\n  induction H.\n  - reflexivity.\n  - econstructor 2; eauto.\nQed.\n\n#[global]\nHint Resolve red_conv : core.\n\nLemma eq_term_App `{checker_flags} Σ φ f f' :\n  eq_term Σ φ f f' ->\n  isApp f = isApp f'.\nProof.\n  inversion 1; reflexivity.\nQed.\n\nLemma eq_term_eq_term_napp {cf:checker_flags} Σ ϕ napp t t' :\n  eq_term Σ ϕ t t' ->\n  eq_term_upto_univ_napp Σ (eq_universe ϕ) (eq_universe ϕ) napp t t'.\nProof.\n  intros. eapply eq_term_upto_univ_impl. 5:eauto.\n  4:auto with arith. all:typeclasses eauto.\nQed.\n\nLemma leq_term_leq_term_napp {cf:checker_flags} Σ ϕ napp t t' :\n  leq_term Σ ϕ t t' ->\n  eq_term_upto_univ_napp Σ (eq_universe ϕ) (leq_universe ϕ) napp t t'.\nProof.\n  intros. eapply eq_term_upto_univ_impl. 5:eauto.\n  4:auto with arith. all:typeclasses eauto.\nQed.\n\nLemma eq_term_mkApps `{checker_flags} Σ φ f l f' l' :\n  eq_term Σ φ f f' ->\n  All2 (eq_term Σ φ) l l' ->\n  eq_term Σ φ (mkApps f l) (mkApps f' l').\nProof.\n  induction l in l', f, f' |- *; intro e; inversion_clear 1.\n  - assumption.\n  - cbn. eapply IHl.\n    + constructor; auto. now apply eq_term_eq_term_napp.\n    + assumption.\nQed.\n\nLemma leq_term_App `{checker_flags} Σ φ f f' :\n  leq_term Σ φ f f' ->\n  isApp f = isApp f'.\nProof.\n  inversion 1; reflexivity.\nQed.\n\nLemma leq_term_mkApps `{checker_flags} Σ φ f l f' l' :\n  leq_term Σ φ f f' ->\n  All2 (eq_term Σ φ) l l' ->\n  leq_term Σ φ (mkApps f l) (mkApps f' l').\nProof.\n  induction l in l', f, f' |- *; intro e; inversion_clear 1.\n  - assumption.\n  - cbn. apply IHl.\n    + constructor; try assumption.\n      now eapply leq_term_leq_term_napp.\n    + assumption.\nQed.\n\n#[global]\nHint Resolve cumul_refl' : core.\n\nLemma red_conv_conv `{cf : checker_flags} Σ Γ t u v :\n  red (fst Σ) Γ t u -> Σ ;;; Γ |- u = v -> Σ ;;; Γ |- t = v.\nProof.\n  intros. apply clos_rt_rt1n_iff in X.\n  induction X; auto.\n  now econstructor 2.\nQed.\n\nLemma red_conv_conv_inv `{cf : checker_flags} Σ Γ t u v :\n  red (fst Σ) Γ t u -> Σ ;;; Γ |- v = u -> Σ ;;; Γ |- v = t.\nProof.\n  intros X%clos_rt_rt1n_iff.\n  induction X; auto.\n  now econstructor 3; [eapply IHX|]; eauto.\nQed.\n\n#[global]\nInstance conv_sym `{cf : checker_flags} (Σ : global_env_ext) Γ :\n  Symmetric (convAlgo Σ Γ).\nProof.\n  intros t u X. induction X.\n  - symmetry in c; now constructor.\n  - eapply red_conv_conv_inv.\n    + eapply red1_red in r. eauto.\n    + eauto.\n  - eapply red_conv_conv.\n    + eapply red1_red in r. eauto.\n    + eauto.\nQed.\n\nLemma conv_alt_red {cf : checker_flags} {Σ : global_env_ext} {Γ : context} {t u : term} :\n  Σ;;; Γ |- t = u <~> (∑ v v' : term, (red Σ Γ t v × red Σ Γ u v') ×\n    eq_term Σ (global_ext_constraints Σ) v v').\nProof.\n  split.\n  - induction 1.\n    * exists t, u; intuition auto.\n    * destruct IHX as [? [? [? ?]]].\n      exists x, x0; intuition auto. eapply red_step; eauto.\n    * destruct IHX as [? [? [? ?]]].\n      exists x, x0; intuition auto. eapply red_step; eauto.\n  - destruct 1 as [? [? [[? ?] ?]]].\n    eapply red_conv_conv; eauto.\n    eapply red_conv_conv_inv; eauto. now constructor.\nQed.\n\nDefinition eq_termp_napp {cf:checker_flags} (pb: conv_pb) (Σ : global_env_ext) napp :=\n  compare_term_napp pb Σ Σ napp.\n\nNotation eq_termp pb Σ := (compare_term pb Σ Σ).\n\nLemma eq_term_eq_termp {cf:checker_flags} pb (Σ : global_env_ext) x y :\n  eq_term Σ Σ x y ->\n  eq_termp pb Σ x y.\nProof.\n  destruct pb; [easy|].\n  cbn.\n  apply eq_term_upto_univ_leq; auto.\n  typeclasses eauto.\nQed.\n\nLemma cumul_App_l {cf:checker_flags} :\n  forall {Σ Γ f g x},\n    Σ ;;; Γ |- f <= g ->\n    Σ ;;; Γ |- tApp f x <= tApp g x.\nProof.\n  intros Σ Γ f g x h.\n  induction h.\n  - eapply cumul_refl. constructor.\n    + apply leq_term_leq_term_napp. assumption.\n    + reflexivity.\n  - eapply cumul_red_l ; try eassumption.\n    econstructor. assumption.\n  - eapply cumul_red_r ; try eassumption.\n    econstructor. assumption.\nQed.\n\nSection ContextConversion.\n  Context {cf : checker_flags}.\n  Context (Σ : global_env_ext).\n\n  Notation conv_context Γ Γ' := (All2_fold (conv_decls cumulAlgo_gen Σ) Γ Γ').\n  Notation cumul_context Γ Γ' := (All2_fold (cumul_decls cumulAlgo_gen Σ) Γ Γ').\n\n  Global Instance conv_ctx_refl : Reflexive (All2_fold (conv_decls cumulAlgo_gen Σ)).\n  Proof using Type.\n    intro Γ; induction Γ; try econstructor; auto.\n    destruct a as [na [b|] ty]; constructor; auto; pcuic; eapply conv_refl'.\n  Qed.\n\n  Global Instance cumul_ctx_refl : Reflexive (All2_fold (cumul_decls cumulAlgo_gen Σ)).\n  Proof using Type.\n    intro Γ; induction Γ; try econstructor; auto.\n    destruct a as [na [b|] ty];\n     econstructor; eauto; pcuic; try eapply conv_refl'; eapply cumul_refl'.\n  Qed.\n\n  Definition conv_ctx_refl' Γ : conv_context Γ Γ\n  := conv_ctx_refl Γ.\n\n  Definition cumul_ctx_refl' Γ : cumul_context Γ Γ\n    := cumul_ctx_refl Γ.\n\nEnd ContextConversion.\n", "meta": {"author": "SwampertX", "repo": "undergraduate-thesis", "sha": "b0c78984b94e56f1372a7195bd0babaab10fca8d", "save_path": "github-repos/coq/SwampertX-undergraduate-thesis", "path": "github-repos/coq/SwampertX-undergraduate-thesis/undergraduate-thesis-b0c78984b94e56f1372a7195bd0babaab10fca8d/final-report-new/code/v2/pcuic/theories/PCUICCumulativity.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20459025532056946}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Loc.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\n\nSet Implicit Arguments.\n\n\nModule MemoryMerge.\n  Lemma add_lower_add\n        mem0 loc from to msg1 msg2 mem1 mem2\n        (ADD1: Memory.add mem0 loc from to msg1 mem1)\n        (LOWER2: Memory.lower mem1 loc from to msg1 msg2 mem2):\n    Memory.add mem0 loc from to msg2 mem2.\n  Proof.\n    inv ADD1. inv ADD. inv LOWER2. inv LOWER.\n    rewrite LocFun.add_add_eq. econs; auto.\n    unfold Cell.add in *.\n    destruct r, r0. ss. subst.\n    unfold LocFun.add. condtac; [|congr]. s.\n    rewrite DOMap.add_add_eq. econs; auto.\n  Qed.\n\n  Lemma split_lower_split\n        mem0 loc ts1 ts2 ts3 msg2 msg2' msg3 mem1 mem2\n        (SPLIT1: Memory.split mem0 loc ts1 ts2 ts3 msg2 msg3 mem1)\n        (LOWER2: Memory.lower mem1 loc ts1 ts2 msg2 msg2' mem2):\n    Memory.split mem0 loc ts1 ts2 ts3 msg2' msg3 mem2.\n  Proof.\n    inv SPLIT1. inv SPLIT. inv LOWER2. inv LOWER.\n    rewrite LocFun.add_add_eq. econs; auto.\n    unfold Cell.split in *.\n    destruct r, r0. ss. subst.\n    unfold LocFun.add. condtac; [|congr]. s.\n    rewrite DOMap.add_add_eq. econs; auto.\n  Qed.\n\n  Lemma lower_lower_lower\n        mem0 loc from to msg0 msg1 msg2 mem1 mem2\n        (LOWER1: Memory.lower mem0 loc from to msg0 msg1 mem1)\n        (LOWER2: Memory.lower mem1 loc from to msg1 msg2 mem2):\n    Memory.lower mem0 loc from to msg0 msg2 mem2.\n  Proof.\n    inv LOWER1. inv LOWER. inv LOWER2. inv LOWER.\n    rewrite LocFun.add_add_eq. econs; auto.\n    unfold Cell.lower in *.\n    destruct r, r0. ss. subst.\n    unfold LocFun.add. condtac; [|congr]. s.\n    rewrite DOMap.add_add_eq. econs; auto.\n    etrans; eauto.\n  Qed.\n\n  Lemma promise_promise_promise\n        loc from to msg1 msg2 promises0 promises1 promises2 mem0 mem1 mem2 kind\n        (PROMISE1: Memory.promise promises0 mem0 loc from to msg1 promises1 mem1 kind)\n        (PROMISE2: Memory.promise promises1 mem1 loc from to msg2 promises2 mem2 (Memory.op_kind_lower msg1)):\n    Memory.promise promises0 mem0 loc from to msg2 promises2 mem2 kind.\n  Proof.\n    inv PROMISE2. inv PROMISE1.\n    - econs; eauto.\n      + eapply add_lower_add; eauto.\n      + eapply add_lower_add; eauto.\n      + des. subst. eauto.\n    - econs; eauto.\n      + eapply split_lower_split; eauto.\n      + eapply split_lower_split; eauto.\n      + des. subst.\n        exploit Memory.lower_get0; eauto. i. des.\n        inv MSG_LE. eauto.\n    - econs; eauto.\n      + eapply lower_lower_lower; eauto.\n      + eapply lower_lower_lower; eauto.\n    - exploit Memory.remove_get0; try exact PROMISES0. i. des.\n      exploit Memory.lower_get0; try exact PROMISES. i. des.\n      congr.\n  Qed.\n\n  Lemma promise_write_write\n        loc from to msg1 val released promises0 promises1 promises2 mem0 mem1 mem2 kind\n        (PROMISE1: Memory.promise promises0 mem0 loc from to msg1 promises1 mem1 kind)\n        (PROMISE2: Memory.write promises1 mem1 loc from to val released promises2 mem2 (Memory.op_kind_lower msg1)):\n    Memory.write promises0 mem0 loc from to val released promises2 mem2 kind.\n  Proof.\n    inv PROMISE2.\n    exploit promise_promise_promise; try exact PROMISE1; eauto.\n  Qed.\n\n  Lemma add_remove\n        loc from to msg mem0 mem1 mem2\n        (ADD1: Memory.add mem0 loc from to msg mem1)\n        (REMOVE2: Memory.remove mem1 loc from to msg mem2):\n    mem0 = mem2.\n  Proof.\n    apply Memory.ext. i. symmetry.\n    exploit Memory.add_get0; eauto. i. des.\n    erewrite Memory.remove_o; eauto. condtac; ss.\n    - des. subst. rewrite GET. ss.\n    - guardH o.\n      erewrite Memory.add_o; eauto. condtac; ss; eauto.\n  Qed.\nEnd MemoryMerge.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/prop/MemoryMerge.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20459025532056946}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.printf.\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nRequire Import VST.floyd.printf.\nRequire Import ITree.Eq.\n\n#[export] Instance nat_id : FileId := { file_id := nat; stdin := 0%nat; stdout := 1%nat }.\n#[export] Instance file_struct : FileStruct := {| FILEid := ___sFILE64; reent := __reent; f_stdin := __stdin; f_stdout := __stdout |}.\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre prog (write_list stdout\n       (string2bytes \"Hello, world!\n\");; write_list stdout (string2bytes \"This is line 2.\n\"))%itree gv\n  POST [ tint ] main_post prog gv.\n\nDefinition Gprog : funspecs :=  \n   (*ltac:(with_library prog *)(ltac:(make_printf_specs prog) ++ [ main_spec ])(*)*).\n\nLemma body_main: semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nmake_stdio.\nrepeat do_string2bytes.\nrepeat (sep_apply data_at_to_cstring; []).\nsep_apply (has_ext_ITREE(E := @IO_event file_id)).\n\nforward_printf tt (write_list stdout (string2bytes \"This is line 2.\n\")).\n{ rewrite !sepcon_assoc; apply sepcon_derives; cancel.\n  apply derives_refl. }\nforward_call.\nforward.\nforward_fprintf outp ((Ers, string2bytes \"line\", gv ___stringlit_2), (Int.repr 2, tt)) (stdout, Ret tt : @IO_itree (@IO_event file_id)).\n{ rewrite 3sepcon_assoc, sepcon_comm, sepcon_assoc; apply sepcon_derives; cancel.\n  rewrite bind_ret'; apply derives_refl. }\nforward.\nQed.\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/verif_printf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20459025532056943}}
{"text": "(** * Grothendieck Construction of a functor to Cat *)\nRequire Import Category.Core Functor.Core NaturalTransformation.Core.\nRequire Import Pseudofunctor.Core Pseudofunctor.FromFunctor.\nRequire Import Cat.Core.\nRequire Import Grothendieck.PseudofunctorToCat.\n\nSet Universe Polymorphism.\nSet Implicit Arguments.\nGeneralizable All Variables.\nSet Asymmetric Patterns.\n\nLocal Open Scope morphism_scope.\n\nSection Grothendieck.\n  Context `{Funext}.\n\n  Variable P : PreCategory -> Type.\n  (*Context `{forall C, IsHProp (P C)}.*)\n  Context `{HF : forall C D, P C -> P D -> IsHSet (Functor C D)}.\n\n  Local Notation cat := (@sub_pre_cat _ P HF).\n\n  Variable C : PreCategory.\n  Variable F : Functor C cat.\n\n  (** ** Category of elements *)\n  Definition category : PreCategory\n    := category (pseudofunctor_of_functor_to_cat F).\n\n  (** ** First projection functor *)\n  Definition pr1 : Functor category C\n    := pr1 (pseudofunctor_of_functor_to_cat F).\nEnd Grothendieck.\n", "meta": {"author": "CPP21-Universal-Algebra-in-HoTT", "repo": "Universal-Algebra-in-HoTT", "sha": "7228b5b88684abff3c26a7eed07e1222b04fd8de", "save_path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT", "path": "github-repos/coq/CPP21-Universal-Algebra-in-HoTT-Universal-Algebra-in-HoTT/Universal-Algebra-in-HoTT-7228b5b88684abff3c26a7eed07e1222b04fd8de/theories/Categories/Grothendieck/ToCat.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.31069438321455395, "lm_q1q2_score": 0.2045666233996369}}
{"text": "Require Import PeanoNat Lia List.\nRequire Import Common FMap IndexSupport.\nRequire Import Syntax Semantics SemFacts StepM Invariant.\nRequire Import Serial SerialFacts.\nRequire Import Reduction Commutativity QuasiSeq Topology.\nRequire Import RqRsTopo RqRsFacts.\nRequire Import RqRsInvMsg RqRsInvLock RqRsInvAtomic RqRsInvSep.\nRequire Import RqUpRed RsUpRed RqRsRed.\n\nSet Implicit Arguments.\n\nOpen Scope list.\nOpen Scope fmap.\n\nSection RqDownReduction.\n  Context `{dv: DecValue} `{oifc: OStateIfc}.\n  Variables (dtr: DTree)\n            (sys: System).\n\n  Hypotheses (Hiorqs: GoodORqsInit (initsOf sys))\n             (oinvs: IdxT -> ObjInv)\n             (Hrrs: RqRsSys dtr sys oinvs).\n\n  Section OnRqDown.\n    Variables (cidx: IdxT) (pobj: Object)\n              (rqDowns: list (Id Msg)).\n    Hypotheses (Hrqd: RqDownMsgs dtr sys cidx rqDowns)\n               (Hpobj: In pobj sys.(sys_objs))\n               (Hcp: parentIdxOf dtr cidx = Some (obj_idx pobj)).\n\n    Lemma rqDown_oinds:\n      forall hst inits ins outs eouts,\n        SubList rqDowns eouts ->\n        Atomic inits ins hst outs eouts ->\n        forall st1 st2,\n          Reachable (steps step_m) sys st1 ->\n          steps step_m sys st1 hst st2 ->\n          DisjList (oindsOf hst) (subtreeIndsOf dtr cidx).\n    Proof.\n      intros.\n      destruct Hrqd as [cobj [[rqDown rqdm] ?]]; dest; subst; simpl in *.\n      eapply atomic_rqDown_covers with (rqDown0:= (rqDown, rqdm)); eauto.\n      - red; auto.\n      - apply SubList_singleton_In; auto.\n    Qed.\n\n    Lemma rqDown_olast_inside_tree:\n      forall inits ins hst outs eouts,\n        DisjList rqDowns inits ->\n        Atomic inits ins hst outs eouts ->\n        forall st1 st2 loidx,\n          Reachable (steps step_m) sys st1 ->\n          Forall (InMPI st1.(st_msgs)) rqDowns ->\n          steps step_m sys st1 hst st2 ->\n          lastOIdxOf hst = Some loidx ->\n          In loidx (subtreeIndsOf dtr cidx) ->\n          SubList (oindsOf hst) (subtreeIndsOf dtr cidx).\n    Proof.\n      intros.\n      destruct Hrqd as [cobj [[rqDown rqdm] ?]]; dest; subst; simpl in *.\n      inv H2; clear H12.\n      pose proof H0.\n      eapply rqUp_start_ok in H2; eauto.\n      destruct H2 as [ruhst [nhst ?]]; dest; subst.\n      assert (~ In (rqDown, rqdm) inits).\n      { eapply DisjList_In_2; [eassumption|].\n        left; reflexivity.\n      }\n      clear H.\n\n      destruct H6; subst.\n      - rewrite app_nil_r in *.\n        eapply atomic_NonRqUp_rqDown_separation_inside\n          with (cobj0:= cobj) (pobj0:= pobj) (rqDown0:= (rqDown, rqdm)); eauto.\n        eapply lastOIdxOf_Some_oindsOf_In; eauto.\n\n      - destruct H as [roidx [rqUps [ruins [ruouts ?]]]]; dest.\n        pose proof H.\n        destruct H14 as [cidx [rqUp [? _]]]; subst.\n        destruct H13; subst.\n        + simpl in *; clear H10.\n          eapply rqUp_atomic_lastOIdxOf in H4; eauto; [|right; eauto].\n          dest; eapply rqUp_atomic_bounded; eauto.\n          right; auto.\n        + destruct H13 as [nins [nouts ?]]; dest.\n          rewrite oindsOf_app.\n          eapply steps_split in H3; [|reflexivity].\n          destruct H3 as [sti [? ?]].\n\n          assert (SubList (oindsOf nhst) (subtreeIndsOf dtr (obj_idx cobj))).\n          { eapply atomic_NonRqUp_rqDown_separation_inside\n              with (cobj0:= cobj) (pobj0:= pobj)\n                   (rqDown0:= (rqDown, rqdm)) (s1:= sti) (ioidx:= loidx); eauto.\n            { eapply atomic_messages_in_in; try eapply H6; eauto. }\n            { intro Hx; apply H12 in Hx.\n              eapply atomic_rqDown_inits_outs_disj\n                with (cidx0:= obj_idx cobj) (rqDown0:= (rqDown, rqdm))\n                     (hst:= nhst ++ ruhst); eauto.\n              eapply steps_append; eauto.\n            }\n            { eapply lastOIdxOf_Some_oindsOf_In; eauto.\n              rewrite lastOIdxOf_app in H4; [|intro Hx; subst; inv H13].\n              assumption.\n            }\n          }\n          apply SubList_app_3; [assumption|].\n          apply H16 in H14.\n          apply subtreeIndsOf_SubList in H14; [|apply Hrrs].\n          eapply SubList_trans; [|eapply H14].\n          eapply rqUp_atomic_inside_tree; eauto.\n          * discriminate.\n          * right; auto.\n    Qed.\n\n    Lemma rqDown_olast_outside_tree:\n      forall inits ins hst outs eouts,\n        DisjList rqDowns inits ->\n        Atomic inits ins hst outs eouts ->\n        forall st1 st2 loidx,\n          Reachable (steps step_m) sys st1 ->\n          Forall (InMPI st1.(st_msgs)) rqDowns ->\n          steps step_m sys st1 hst st2 ->\n          lastOIdxOf hst = Some loidx ->\n          ~ In loidx (subtreeIndsOf dtr cidx) ->\n          exists ruhst nhst,\n            hst = nhst ++ ruhst /\\\n            (ruhst = nil \\/\n             exists roidx rqUps ruins ruouts,\n               RqUpMsgsP dtr roidx rqUps /\\\n               ~ In roidx (subtreeIndsOf dtr cidx) /\\\n               Atomic inits ruins ruhst ruouts rqUps /\\\n               SubList rqUps outs /\\\n               (nhst = nil \\/\n                exists nins nouts,\n                  Atomic rqUps nins nhst nouts eouts)) /\\\n            DisjList (oindsOf nhst) (subtreeIndsOf dtr cidx).\n    Proof.\n      intros.\n      destruct Hrqd as [cobj [[rqDown rqdm] ?]]; dest; subst; simpl in *.\n      inv H2; clear H12.\n      pose proof H0.\n      eapply rqUp_start_ok in H2; eauto.\n      destruct H2 as [ruhst [nhst ?]]; dest; subst.\n      exists ruhst, nhst.\n      assert (~ In (rqDown, rqdm) inits).\n      { eapply DisjList_In_2; [eassumption|].\n        left; reflexivity.\n      }\n      clear H.\n\n      destruct H6; subst.\n      - rewrite app_nil_r in *.\n        repeat ssplit; [reflexivity|left; reflexivity|].\n        eapply atomic_NonRqUp_rqDown_separation_outside\n          with (cobj0:= cobj) (pobj0:= pobj) (rqDown0:= (rqDown, rqdm))\n               (ioidx:= loidx); eauto.\n        eapply lastOIdxOf_Some_oindsOf_In; eauto.\n\n      - destruct H as [roidx [rqUps [ruins [ruouts ?]]]]; dest.\n        pose proof H.\n        destruct H14 as [cidx [rqUp [? _]]]; subst rqUps.\n        destruct H13; subst.\n        + simpl in *; clear H10.\n          repeat ssplit; [reflexivity| |apply DisjList_nil_1].\n          right; exists roidx, [rqUp], ruins, ruouts.\n          repeat ssplit; try assumption.\n          * eapply rqUp_atomic_lastOIdxOf in H6; eauto; [|right; eauto].\n            dest; eapply outside_parent_out; try apply Hrrs; eauto.\n          * left; reflexivity.\n\n        + destruct H13 as [nins [nouts ?]]; dest.\n          assert (DisjList (oindsOf nhst) (subtreeIndsOf dtr (obj_idx cobj))).\n          { eapply steps_split in H3; [|reflexivity].\n            destruct H3 as [sti [? ?]].\n            eapply atomic_NonRqUp_rqDown_separation_outside\n              with (cobj0:= cobj) (pobj0:= pobj) (rqDown0:= (rqDown, rqdm))\n                   (ioidx:= loidx) (s1:= sti); eauto.\n            { eapply atomic_messages_in_in; try eapply H6; eauto. }\n            { intro Hx; apply H12 in Hx.\n              eapply atomic_rqDown_inits_outs_disj\n                with (cidx0:= obj_idx cobj) (rqDown0:= (rqDown, rqdm))\n                     (hst:= nhst ++ ruhst); eauto.\n              eapply steps_append; eauto.\n            }\n            { eapply lastOIdxOf_Some_oindsOf_In; eauto.\n              rewrite lastOIdxOf_app in H4; [|intro Hx; subst; inv H13].\n              assumption.\n            }\n          }\n          repeat ssplit; [reflexivity| |assumption].\n          right; exists roidx, [rqUp], ruins, ruouts.\n          repeat ssplit; try assumption.\n          { eapply DisjList_In_2; eauto. }\n          { right; eauto. }\n    Qed.\n\n    Definition RqDownP (st: State) :=\n      Forall (InMPI st.(st_msgs)) rqDowns.\n\n    Lemma rqDown_lpush_rpush_messages_disj:\n      forall rinits rins rhst routs reouts\n             linits lins lhst louts leouts,\n        DisjList rqDowns rinits ->\n        Atomic rinits rins rhst routs reouts ->\n        DisjList (oindsOf rhst) (subtreeIndsOf dtr cidx) ->\n        DisjList rqDowns linits ->\n        Atomic linits lins lhst louts leouts ->\n        SubList (oindsOf lhst) (subtreeIndsOf dtr cidx) ->\n        forall st1,\n          Reachable (steps step_m) sys st1 ->\n          RqDownP st1 ->\n          forall st2,\n            steps step_m sys st1 (lhst ++ rhst) st2 ->\n            DisjList reouts linits.\n    Proof.\n      destruct Hrrs as [? [? ?]]; intros.\n      apply (DisjList_false_spec (id_dec msg_dec)).\n      intros [midx msg] ? ?.\n      unfold RqDownP in H9.\n      destruct Hrqd as [cobj [[rqDown rqdm] ?]]; dest; subst.\n      inv H9; clear H19.\n      simpl in *.\n\n      replace midx with rqDown in *.\n      - eapply steps_split in H10; [|reflexivity].\n        destruct H10 as [sti [? ?]].\n        eapply atomic_rqDown_no_out\n          with (cobj0:= cobj) (pobj0:= pobj) (rqDown0:= (rqDown, rqdm))\n               (dmsg:= (rqDown, msg)) (st3:= st1) (outs:= routs); eauto.\n        + eapply DisjList_In_2; [eassumption|].\n          left; reflexivity.\n        + eapply atomic_eouts_in; eauto.\n      - eapply steps_split in H10; [|reflexivity].\n        destruct H10 as [sti [? ?]].\n        eapply atomic_ext_outs_in_history in H3; eauto.\n        rewrite Forall_forall in H3; specialize (H3 _ H11).\n        destruct H3 as [ofrom [? ?]].\n        eapply atomic_inits_in_history with (s1:= sti) in H6; eauto.\n        rewrite Forall_forall in H6; specialize (H6 _ H12).\n        destruct H6 as [oto [? ?]].\n        destruct H3 as [|[|]], H6 as [|[|]];\n          try (dest; exfalso; solve_midx_false; fail).\n        + exfalso; simpl in *.\n          destruct H6 as [cidx [? ?]].\n          disc_rule_conds.\n          eapply DisjList_In_2 in H13; [|eassumption].\n          apply H7 in H17.\n          elim H13.\n          eapply inside_child_in; try apply Hrrs; eauto.\n        + exfalso; simpl in *.\n          destruct H6 as [cidx [? ?]].\n          disc_rule_conds.\n          eapply DisjList_In_2 in H13; [|eassumption].\n          apply H7 in H17.\n          elim H13.\n          eapply inside_child_in; try apply Hrrs; eauto.\n        + simpl in *; destruct H3 as [cidx [? ?]].\n          disc_rule_conds.\n          eapply DisjList_In_2 in H13; [|eassumption].\n          apply H7 in H17.\n          eapply inside_child_outside_parent_case in H17;\n            try apply Hrrs; eauto; subst.\n          disc_rule_conds.\n    Qed.\n\n    Hypothesis (Hoinvs: InvReachable sys step_m (liftObjInvs oinvs)).\n\n    Lemma rqDown_lpush_rpush_unit_reducible:\n      forall rinits rins rhst routs reouts\n             linits lins lhst louts leouts,\n        Atomic rinits rins rhst routs reouts ->\n        DisjList (oindsOf rhst) (subtreeIndsOf dtr cidx) ->\n        Atomic linits lins lhst louts leouts ->\n        SubList (oindsOf lhst) (subtreeIndsOf dtr cidx) ->\n        DisjList reouts linits ->\n        Reducible sys (lhst ++ rhst) (rhst ++ lhst).\n    Proof.\n      intros.\n      eapply rqrs_reducible; try eassumption.\n      eapply DisjList_comm, DisjList_SubList; [eassumption|].\n      apply DisjList_comm; assumption.\n    Qed.\n\n    Lemma rqDown_lpush_unit_reducible:\n      forall pinits pins phst pouts peouts\n             inits ins hst outs eouts loidx,\n        PInitializing sys RqDownP phst ->\n        Atomic pinits pins phst pouts peouts ->\n        SubList rqDowns peouts ->\n        Atomic inits ins hst outs eouts ->\n        lastOIdxOf hst = Some loidx ->\n        In loidx (subtreeIndsOf dtr cidx) ->\n        DisjList peouts inits ->\n        Reducible sys (hst ++ phst) (phst ++ hst).\n    Proof.\n      intros; red; intros.\n      eapply steps_split in H6; [|reflexivity].\n      destruct H6 as [sti [? ?]].\n      eapply rqDown_lpush_rpush_unit_reducible; try eassumption.\n      - eapply rqDown_oinds; try eassumption.\n      - eapply rqDown_olast_inside_tree.\n        + eapply DisjList_SubList; [|eassumption].\n          eassumption.\n        + eassumption.\n        + eapply reachable_steps; [eassumption|].\n          eassumption.\n        + eapply H; eassumption.\n        + eassumption.\n        + eassumption.\n        + eassumption.\n      - eapply steps_append; eauto.\n    Qed.\n\n    Lemma rqDown_rpush_unit_reducible:\n      forall inits ins hst outs eouts loidx ridx routs,\n        Atomic inits ins hst outs eouts ->\n        lastOIdxOf hst = Some loidx ->\n        ~ In loidx (subtreeIndsOf dtr cidx) ->\n        DisjList rqDowns inits ->\n        ReducibleP sys RqDownP (RlblInt cidx ridx rqDowns routs :: hst)\n                   (hst ++ [RlblInt cidx ridx rqDowns routs]).\n    Proof.\n      intros; red; intros.\n      inv_steps.\n      pose proof (rqDown_olast_outside_tree H2 H Hr Hp H7 H0 H1).\n      destruct H3 as [ruhst [nhst ?]]; dest; subst.\n      eapply steps_split in H7; [|reflexivity].\n      destruct H7 as [sti [? ?]].\n\n      destruct H4; subst.\n      - rewrite app_nil_r in *; inv H3.\n        eapply rqDown_lpush_rpush_unit_reducible; try eassumption.\n        + constructor.\n        + simpl; apply SubList_cons; [|apply SubList_nil].\n          destruct Hrqd as [dobj [rqDown rqdm]]; dest; subst.\n          apply edgeDownTo_subtreeIndsOf_self_in; [apply Hrrs|].\n          congruence.\n        + red in Hp.\n          destruct Hrqd as [dobj [[rqDown rqdm] ?]]; dest; subst.\n          inv Hp; clear H12.\n          eapply DisjList_SubList; [eapply atomic_eouts_in; eassumption|].\n          apply (DisjList_singleton_2 (id_dec msg_dec)).\n          eapply atomic_rqDown_inits_outs_disj; eauto.\n          eapply DisjList_In_2; eauto.\n          left; reflexivity.\n        + simpl; econstructor; eauto.\n\n      - destruct H4 as [roidx [rqUps [ruins [ruouts ?]]]]; dest.\n        rewrite <-app_assoc.\n        eapply reducible_app_1; try assumption.\n        + instantiate (1:= RlblInt cidx ridx rqDowns routs :: ruhst).\n          red; intros.\n          eapply rqUpHistory_lpush_lbl with (rqUps0:= rqUps); try eassumption.\n          * inv_steps.\n            eapply rqUp_atomic with (rqUps0:= rqUps); eauto.\n            { red in H4; dest; subst; discriminate. }\n            { right; eauto. }\n            { apply SubList_refl. }\n          * destruct Hrrs as [? [? ?]].\n            clear -Hrqd H4 H13.\n            destruct Hrqd as [dobj [[rqDown rqdm] ?]]; dest; subst.\n            destruct H4 as [cidx [[rqUp rqum] ?]]; dest; subst.\n            apply idsOf_DisjList; simpl in *.\n            solve_midx_disj.\n        + destruct H11; subst;\n            [simpl in *; inv H6; econstructor; eauto|].\n          destruct H11 as [nins [nouts ?]].\n          change (nhst ++ RlblInt cidx ridx rqDowns routs :: ruhst)\n            with (nhst ++ [RlblInt cidx ridx rqDowns routs] ++ ruhst).\n          rewrite app_assoc.\n          eapply reducible_app_2; try assumption.\n          * instantiate (1:= RlblInt cidx ridx rqDowns routs :: nhst).\n            change (RlblInt cidx ridx rqDowns routs :: nhst)\n              with ([RlblInt cidx ridx rqDowns routs] ++ nhst).\n            eapply rqDown_lpush_rpush_unit_reducible; try eassumption.\n            { constructor. }\n            { simpl; red; intros; dest_in.\n              apply edgeDownTo_subtreeIndsOf_self_in.\n              { apply Hrrs. }\n              { destruct Hrqd; dest; congruence. }\n            }\n            { eapply DisjList_SubList.\n              { eapply atomic_eouts_in, H. }\n              { apply DisjList_comm.\n                red in Hp.\n                destruct Hrqd as [dobj [[rqDown rqdm] ?]]; dest; subst.\n                inv Hp; clear H18.\n                apply (DisjList_singleton_1 (id_dec msg_dec)).\n                eapply atomic_rqDown_inits_outs_disj; eauto.\n                { destruct (H2 (rqDown, rqdm)); [|assumption].\n                  elim H12; left; reflexivity.\n                }\n                { eapply steps_append; eassumption. }\n              }\n            }\n          * simpl; econstructor; [|eassumption].\n            eapply steps_append; eassumption.\n    Qed.\n\n    Lemma rqDown_LRPushable_unit_reducible:\n      forall rinits rins rhst routs reouts rloidx\n             linits lins lhst louts leouts lloidx,\n        Atomic rinits rins rhst routs reouts ->\n        DisjList rqDowns rinits ->\n        lastOIdxOf rhst = Some rloidx ->\n        ~ In rloidx (subtreeIndsOf dtr cidx) ->\n        Atomic linits lins lhst louts leouts ->\n        DisjList rqDowns linits ->\n        lastOIdxOf lhst = Some lloidx ->\n        In lloidx (subtreeIndsOf dtr cidx) ->\n        ReducibleP sys RqDownP (lhst ++ rhst) (rhst ++ lhst).\n    Proof.\n      intros; red; intros.\n      eapply steps_split in H7; [|reflexivity].\n      destruct H7 as [sti [? ?]].\n      eapply rqDown_olast_inside_tree in H6;\n        [|exact H4\n         |eassumption\n         |eapply reachable_steps; eassumption\n         |eapply atomic_messages_ins_ins;\n          try eapply H; try eassumption;\n          apply DisjList_comm; assumption\n         |eassumption\n         |eassumption].\n      clear H5.\n      eapply rqDown_olast_outside_tree in H2;\n        try exact H0; try eassumption.\n      clear H1.\n      destruct H2 as [ruhst [nhst ?]]; dest; subst.\n\n      destruct H2; subst.\n      - rewrite app_nil_r in *.\n        eapply rqDown_lpush_rpush_unit_reducible; try eassumption.\n        + eapply rqDown_lpush_rpush_messages_disj\n            with (rinits:= rinits) (linits:= linits); eauto.\n          eapply steps_append; eassumption.\n        + eapply steps_append; eassumption.\n\n      - destruct H1 as [roidx [rqUps [ruins [ruouts ?]]]]; dest.\n        destruct H11; subst.\n        * simpl in *.\n          eapply rqUpHistory_lpush_unit_reducible with (rqUps0:= rqUps); eauto.\n          { right; eauto. }\n          { eapply rqUp_atomic with (rqUps0:= rqUps); eauto; try apply Hiorqs.\n            { red in H1; dest; subst; discriminate. }\n            { right; auto. }\n            { apply SubList_refl. }\n          }\n          { assert (Reachable (steps step_m) sys sti)\n              by (eapply reachable_steps; eassumption).\n            clear Hr.\n            destruct H1 as [rcidx [rqUp ?]]; dest; subst.\n            eapply atomic_inside_tree_inits_disj_rqUps\n              with (rqFrom:= rcidx); eauto.\n            eapply outside_child_in; try apply Hrrs; eassumption.\n          }\n          { eapply steps_append; eauto. }\n        * destruct H11 as [nins [nouts ?]].\n          rewrite <-app_assoc.\n          eapply reducible_app_1; try assumption.\n          { instantiate (1:= lhst ++ ruhst).\n            eapply rqUpHistory_lpush_unit_reducible with (rqUps0:= rqUps); eauto.\n            { right; eauto. }\n            { eapply steps_split in H7; [|reflexivity].\n              destruct H7 as [rsti [? ?]].\n              eapply rqUp_atomic with (rqUps0:= rqUps); eauto.\n              { red in H1; dest; subst; discriminate. }\n              { right; auto. }\n              { apply SubList_refl. }\n            }\n            { assert (Reachable (steps step_m) sys sti)\n                by (eapply reachable_steps; eassumption).\n              clear Hr.\n              destruct H1 as [rcidx [rqUp ?]]; dest; subst.\n              eapply atomic_inside_tree_inits_disj_rqUps\n                with (rqFrom:= rcidx); eauto.\n              eapply outside_child_in; try apply Hrrs; eassumption.\n            }\n          }\n          { rewrite app_assoc.\n            eapply reducible_app_2; try assumption.\n            { instantiate (1:= lhst ++ nhst).\n              eapply rqDown_lpush_rpush_unit_reducible; try eassumption.\n              eapply steps_split in H7; [|reflexivity].\n              destruct H7 as [rsti [? ?]].\n              assert (DisjList rqDowns rqUps).\n              { eapply DisjList_comm, DisjList_SubList; [eassumption|].\n                apply DisjList_comm.\n                unfold RqDownP in Hp.\n                destruct Hrqd as [dobj [[rqDown rqdm] ?]]; dest; subst.\n                inv Hp.\n                apply (DisjList_singleton_1 (id_dec msg_dec)).\n                eapply atomic_rqDown_inits_outs_disj; eauto;\n                  [|eapply steps_append; eauto].\n                specialize (H0 (rqDown, rqdm)); destruct H0; auto.\n                elim H0; left; reflexivity.\n              }\n              eapply rqDown_lpush_rpush_messages_disj\n                with (rinits:= rqUps) (linits:= linits) (st1:= rsti); eauto.\n              { eapply atomic_messages_ins_ins.\n                { eapply H9. }\n                { eassumption. }\n                { eassumption. }\n                { eapply DisjList_comm, H0. }\n              }\n              { eapply steps_append; eassumption. }\n            }\n            { rewrite <-app_assoc.\n              eapply steps_append; eassumption.\n            }\n          }\n    Qed.\n\n  End OnRqDown.\n\nEnd RqDownReduction.\n\nClose Scope list.\nClose Scope fmap.\n", "meta": {"author": "mit-plv", "repo": "hemiola", "sha": "1984b4de903259ce2d7abda737e76e16e6436dee", "save_path": "github-repos/coq/mit-plv-hemiola", "path": "github-repos/coq/mit-plv-hemiola/hemiola-1984b4de903259ce2d7abda737e76e16e6436dee/src/Dsl/RqDownRed.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.20456196095000653}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Language.\n\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import PromiseConsistent.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\n\nSet Implicit Arguments.\n\n\nSection SimulationThread.\n  Variable (lang_src lang_tgt:language).\n\n  Definition SIM_TERMINAL :=\n    forall (st_src:(Language.state lang_src)) (st_tgt:(Language.state lang_tgt)), Prop.\n\n  Definition SIM_THREAD :=\n    forall (sim_terminal: SIM_TERMINAL)\n      (st1_src:(Language.state lang_src)) (lc1_src:Local.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n      (st1_tgt:(Language.state lang_tgt)) (lc1_tgt:Local.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t), Prop.\n\n  Definition _sim_thread_step\n             (sim_thread: forall (st1_src:(Language.state lang_src)) (lc1_src:Local.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n                            (st1_tgt:(Language.state lang_tgt)) (lc1_tgt:Local.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t), Prop)\n             st1_src lc1_src sc1_src mem1_src\n             st1_tgt lc1_tgt sc1_tgt mem1_tgt\n    :=\n    forall pf_tgt e_tgt st3_tgt lc3_tgt sc3_tgt mem3_tgt\n      (STEP_TGT: Thread.step pf_tgt e_tgt\n                             (Thread.mk _ st1_tgt lc1_tgt sc1_tgt mem1_tgt)\n                             (Thread.mk _ st3_tgt lc3_tgt sc3_tgt mem3_tgt)),\n      <<FAILURE: Thread.steps_failure (Thread.mk _ st1_src lc1_src sc1_src mem1_src)>> \\/\n      exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n        <<FAILURE: e_tgt <> ThreadEvent.failure>> /\\\n        <<STEPS: rtc (@Thread.tau_step _)\n                     (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                     (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n        <<STEP_SRC: Thread.opt_step e_src\n                                    (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                                    (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n        <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n        <<SC3: TimeMap.le sc3_src sc3_tgt>> /\\\n        <<MEMORY3: sim_memory mem3_src mem3_tgt>> /\\\n        <<SIM: sim_thread st3_src lc3_src sc3_src mem3_src st3_tgt lc3_tgt sc3_tgt mem3_tgt>>.\n\n  Definition _sim_thread\n             (sim_thread: SIM_THREAD)\n             (sim_terminal: SIM_TERMINAL)\n             (st1_src:(Language.state lang_src)) (lc1_src:Local.t) (sc0_src:TimeMap.t) (mem0_src:Memory.t)\n             (st1_tgt:(Language.state lang_tgt)) (lc1_tgt:Local.t) (sc0_tgt:TimeMap.t) (mem0_tgt:Memory.t): Prop :=\n    forall sc1_src mem1_src\n      sc1_tgt mem1_tgt\n      (SC: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY: sim_memory mem1_src mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc0_src sc1_src)\n      (SC_FUTURE_TGT: TimeMap.le sc0_tgt sc1_tgt)\n      (MEM_FUTURE_SRC: Memory.future_weak mem0_src mem1_src)\n      (MEM_FUTURE_TGT: Memory.future_weak mem0_tgt mem1_tgt)\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed mem1_tgt)\n      (CONS_TGT: Local.promise_consistent lc1_tgt),\n      <<TERMINAL:\n        forall (TERMINAL_TGT: (Language.is_terminal lang_tgt) st1_tgt),\n          <<FAILURE: Thread.steps_failure (Thread.mk _ st1_src lc1_src sc1_src mem1_src)>> \\/\n          exists st2_src lc2_src sc2_src mem2_src,\n            <<STEPS: rtc (@Thread.tau_step _)\n                         (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                         (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n            <<SC: TimeMap.le sc2_src sc1_tgt>> /\\\n            <<MEMORY: sim_memory mem2_src mem1_tgt>> /\\\n            <<TERMINAL_SRC: (Language.is_terminal lang_src) st2_src>> /\\\n            <<LOCAL: sim_local SimPromises.bot lc2_src lc1_tgt>> /\\\n            <<TERMINAL: sim_terminal st2_src st1_tgt>>>> /\\\n      <<PROMISES:\n        forall (PROMISES_TGT: (Local.promises lc1_tgt) = Memory.bot),\n          <<FAILURE: Thread.steps_failure (Thread.mk _ st1_src lc1_src sc1_src mem1_src)>> \\/\n          exists st2_src lc2_src sc2_src mem2_src,\n            <<STEPS: rtc (@Thread.tau_step _)\n                         (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                         (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n            <<PROMISES_SRC: (Local.promises lc2_src) = Memory.bot>>>> /\\\n      <<STEP: _sim_thread_step (sim_thread sim_terminal)\n                               st1_src lc1_src sc1_src mem1_src\n                               st1_tgt lc1_tgt sc1_tgt mem1_tgt>>.\n\n  Lemma _sim_thread_mon: monotone9 _sim_thread.\n  Proof.\n    ii. exploit IN; try apply SC; eauto. i. des.\n    splits; eauto. ii.\n    exploit STEP; eauto. i. des; eauto.\n    right. esplits; eauto.\n  Qed.\n  Hint Resolve _sim_thread_mon: paco.\n\n  Definition sim_thread: SIM_THREAD := paco9 _sim_thread bot9.\n\n  Lemma sim_thread_mon\n        sim_terminal1 sim_terminal2\n        (SIM: sim_terminal1 <2= sim_terminal2):\n    sim_thread sim_terminal1 <8= sim_thread sim_terminal2.\n  Proof.\n    pcofix CIH. i. punfold PR. pfold. ii.\n    exploit PR; try apply SC; eauto. i. des.\n    splits; auto.\n    - i. exploit TERMINAL; eauto. i. des; eauto.\n      right. esplits; eauto.\n    - ii. exploit STEP; eauto. i. des; eauto.\n      inv SIM0; [|done].\n      right. esplits; eauto.\n  Qed.\nEnd SimulationThread.\nHint Resolve _sim_thread_mon: paco.\n\n\nLemma sim_thread_step\n      lang_src lang_tgt\n      sim_terminal\n      pf_tgt e_tgt\n      st1_src lc1_src sc1_src mem1_src\n      st1_tgt lc1_tgt sc1_tgt mem1_tgt\n      st3_tgt lc3_tgt sc3_tgt mem3_tgt\n      (STEP: @Thread.step lang_tgt pf_tgt e_tgt\n                          (Thread.mk _ st1_tgt lc1_tgt sc1_tgt mem1_tgt)\n                          (Thread.mk _ st3_tgt lc3_tgt sc3_tgt mem3_tgt))\n      (SC: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY: sim_memory mem1_src mem1_tgt)\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed mem1_tgt)\n      (CONS_TGT: Local.promise_consistent lc3_tgt)\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src st1_tgt lc1_tgt sc1_tgt mem1_tgt):\n  <<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src sc1_src mem1_src)>> \\/\n  exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n    <<FAILURE: e_tgt <> ThreadEvent.failure>> /\\\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<STEP: Thread.opt_step e_src\n                            (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                            (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n    <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n    <<SC: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEMORY: sim_memory mem3_src mem3_tgt>> /\\\n    <<WF_SRC: Local.wf lc3_src mem3_src>> /\\\n    <<WF_TGT: Local.wf lc3_tgt mem3_tgt>> /\\\n    <<SC_SRC: Memory.closed_timemap sc3_src mem3_src>> /\\\n    <<SC_TGT: Memory.closed_timemap sc3_tgt mem3_tgt>> /\\\n    <<MEM_SRC: Memory.closed mem3_src>> /\\\n    <<MEM_TGT: Memory.closed mem3_tgt>> /\\\n    <<SIM: sim_thread sim_terminal st3_src lc3_src sc3_src mem3_src st3_tgt lc3_tgt sc3_tgt mem3_tgt>>.\nProof.\n  hexploit step_promise_consistent; eauto. s. i.\n  punfold SIM. exploit SIM; eauto; try refl. i. des.\n  exploit Thread.step_future; eauto. s. i. des.\n  exploit STEP0; eauto. i. des; eauto.\n  inv SIM0; [|done]. right.\n  exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n  exploit Thread.opt_step_future; eauto. s. i. des.\n  esplits; eauto.\nQed.\n\nLemma sim_thread_opt_step\n      lang_src lang_tgt\n      sim_terminal\n      e_tgt\n      st1_src lc1_src sc1_src mem1_src\n      st1_tgt lc1_tgt sc1_tgt mem1_tgt\n      st3_tgt lc3_tgt sc3_tgt mem3_tgt\n      (STEP: @Thread.opt_step lang_tgt e_tgt\n                              (Thread.mk _ st1_tgt lc1_tgt sc1_tgt mem1_tgt)\n                              (Thread.mk _ st3_tgt lc3_tgt sc3_tgt mem3_tgt))\n      (SC: TimeMap.le sc1_src sc1_tgt)\n      (MEMORY: sim_memory mem1_src mem1_tgt)\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed mem1_tgt)\n      (CONS_TGT: Local.promise_consistent lc3_tgt)\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src st1_tgt lc1_tgt sc1_tgt mem1_tgt):\n  <<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src sc1_src mem1_src)>> \\/\n  exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n    <<FAILURE: e_tgt <> ThreadEvent.failure>> /\\\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<STEP: Thread.opt_step e_src\n                            (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                            (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n    <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n    <<SC: TimeMap.le sc3_src sc3_tgt>> /\\\n    <<MEMORY: sim_memory mem3_src mem3_tgt>> /\\\n    <<WF_SRC: Local.wf lc3_src mem3_src>> /\\\n    <<WF_TGT: Local.wf lc3_tgt mem3_tgt>> /\\\n    <<SC_SRC: Memory.closed_timemap sc3_src mem3_src>> /\\\n    <<SC_TGT: Memory.closed_timemap sc3_tgt mem3_tgt>> /\\\n    <<MEM_SRC: Memory.closed mem3_src>> /\\\n    <<MEM_TGT: Memory.closed mem3_tgt>> /\\\n    <<SIM: sim_thread sim_terminal st3_src lc3_src sc3_src mem3_src st3_tgt lc3_tgt sc3_tgt mem3_tgt>>.\nProof.\n  inv STEP.\n  - right. esplits; eauto; ss. econs 1.\n  - eapply sim_thread_step; eauto.\nQed.\n\nLemma sim_thread_rtc_step\n      lang_src lang_tgt\n      sim_terminal\n      st1_src lc1_src sc1_src mem1_src\n      e1_tgt e2_tgt\n      (STEPS: rtc (@Thread.tau_step lang_tgt) e1_tgt e2_tgt)\n      (SC: TimeMap.le sc1_src (Thread.sc e1_tgt))\n      (MEMORY: sim_memory mem1_src (Thread.memory e1_tgt))\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed (Thread.memory e1_tgt))\n      (CONS_TGT: Local.promise_consistent (Thread.local e2_tgt))\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src (Thread.state e1_tgt) (Thread.local e1_tgt) (Thread.sc e1_tgt) (Thread.memory e1_tgt)):\n  <<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src sc1_src mem1_src)>> \\/\n  exists st2_src lc2_src sc2_src mem2_src,\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<SC: TimeMap.le sc2_src (Thread.sc e2_tgt)>> /\\\n    <<MEMORY: sim_memory mem2_src (Thread.memory e2_tgt)>> /\\\n    <<WF_SRC: Local.wf lc2_src mem2_src>> /\\\n    <<WF_TGT: Local.wf (Thread.local e2_tgt) (Thread.memory e2_tgt)>> /\\\n    <<SC_SRC: Memory.closed_timemap sc2_src mem2_src>> /\\\n    <<SC_TGT: Memory.closed_timemap (Thread.sc e2_tgt) (Thread.memory e2_tgt)>> /\\\n    <<MEM_SRC: Memory.closed mem2_src>> /\\\n    <<MEM_TGT: Memory.closed (Thread.memory e2_tgt)>> /\\\n    <<SIM: sim_thread sim_terminal st2_src lc2_src sc2_src mem2_src (Thread.state e2_tgt) (Thread.local e2_tgt) (Thread.sc e2_tgt) (Thread.memory e2_tgt)>>.\nProof.\n  revert SC MEMORY WF_SRC WF_TGT SC_SRC SC_TGT MEM_SRC MEM_TGT SIM.\n  revert st1_src lc1_src sc1_src mem1_src.\n  induction STEPS; i.\n  { right. esplits; eauto. }\n  inv H. inv TSTEP. destruct x, y. ss.\n  exploit Thread.step_future; eauto. s. i. des.\n  hexploit rtc_tau_step_promise_consistent; eauto. s. i.\n  exploit sim_thread_step; eauto. i. des; eauto.\n  exploit IHSTEPS; eauto. i. des.\n  - left. inv FAILURE0. des.\n    unfold Thread.steps_failure. esplits; [|eauto].\n    etrans; eauto. etrans; eauto. inv STEP0; eauto.\n    econs 2; eauto. econs.\n    + econs. eauto.\n    + destruct e, e_src; ss.\n  - right. destruct z. ss.\n    esplits; try apply MEMORY1; eauto.\n    etrans; [eauto|]. etrans; [|eauto]. inv STEP0; eauto.\n    econs 2; eauto. econs.\n    + econs. eauto.\n    + destruct e, e_src; ss.\nQed.\n\nLemma sim_thread_plus_step\n      lang_src lang_tgt\n      sim_terminal\n      pf_tgt e_tgt\n      st1_src lc1_src sc1_src mem1_src\n      e1_tgt e2_tgt e3_tgt\n      (STEPS: rtc (@Thread.tau_step lang_tgt) e1_tgt e2_tgt)\n      (STEP: @Thread.step lang_tgt pf_tgt e_tgt e2_tgt e3_tgt)\n      (SC: TimeMap.le sc1_src (Thread.sc e1_tgt))\n      (MEMORY: sim_memory mem1_src (Thread.memory e1_tgt))\n      (WF_SRC: Local.wf lc1_src mem1_src)\n      (WF_TGT: Local.wf (Thread.local e1_tgt) (Thread.memory e1_tgt))\n      (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC_TGT: Memory.closed_timemap (Thread.sc e1_tgt) (Thread.memory e1_tgt))\n      (MEM_SRC: Memory.closed mem1_src)\n      (MEM_TGT: Memory.closed (Thread.memory e1_tgt))\n      (CONS_TGT: Local.promise_consistent (Thread.local e3_tgt))\n      (SIM: sim_thread sim_terminal st1_src lc1_src sc1_src mem1_src (Thread.state e1_tgt) (Thread.local e1_tgt) (Thread.sc e1_tgt) (Thread.memory e1_tgt)):\n  <<FAILURE: Thread.steps_failure (Thread.mk lang_src st1_src lc1_src sc1_src mem1_src)>> \\/\n  exists e_src st2_src lc2_src sc2_src mem2_src st3_src lc3_src sc3_src mem3_src,\n    <<FAILURE: e_tgt <> ThreadEvent.failure>> /\\\n    <<STEPS: rtc (@Thread.tau_step lang_src)\n                 (Thread.mk _ st1_src lc1_src sc1_src mem1_src)\n                 (Thread.mk _ st2_src lc2_src sc2_src mem2_src)>> /\\\n    <<STEP: Thread.opt_step e_src\n                            (Thread.mk _ st2_src lc2_src sc2_src mem2_src)\n                            (Thread.mk _ st3_src lc3_src sc3_src mem3_src)>> /\\\n    <<EVENT: ThreadEvent.get_machine_event e_src = ThreadEvent.get_machine_event e_tgt>> /\\\n    <<SC: TimeMap.le sc3_src (Thread.sc e3_tgt)>> /\\\n    <<MEMORY: sim_memory mem3_src (Thread.memory e3_tgt)>> /\\\n    <<WF_SRC: Local.wf lc3_src mem3_src>> /\\\n    <<WF_TGT: Local.wf (Thread.local e3_tgt) (Thread.memory e3_tgt)>> /\\\n    <<SC_SRC: Memory.closed_timemap sc3_src mem3_src>> /\\\n    <<SC_TGT: Memory.closed_timemap (Thread.sc e3_tgt) (Thread.memory e3_tgt)>> /\\\n    <<MEM_SRC: Memory.closed mem3_src>> /\\\n    <<MEM_TGT: Memory.closed (Thread.memory e3_tgt)>> /\\\n    <<SIM: sim_thread sim_terminal st3_src lc3_src sc3_src mem3_src (Thread.state e3_tgt) (Thread.local e3_tgt) (Thread.sc e3_tgt) (Thread.memory e3_tgt)>>.\nProof.\n  destruct e1_tgt, e2_tgt, e3_tgt. ss.\n  exploit Thread.rtc_tau_step_future; eauto. s. i. des.\n  hexploit step_promise_consistent; eauto. s. i.\n  exploit sim_thread_rtc_step; eauto. s. i. des; eauto.\n  exploit Thread.rtc_tau_step_future; try exact STEPS0; eauto. s. i. des.\n  exploit sim_thread_step; try exact STEP; try exact SIM0; eauto. s. i. des.\n  - left. inv FAILURE. des.\n    unfold Thread.steps_failure. esplits; [|eauto].\n    etrans; eauto.\n  - right. rewrite STEPS1 in STEPS0.\n    esplits; try exact STEPS0; try exact STEP0; eauto.\nQed.\n\nLemma sim_thread_future\n      lang_src lang_tgt\n      sim_terminal\n      st_src lc_src sc1_src sc2_src mem1_src mem2_src\n      st_tgt lc_tgt sc1_tgt sc2_tgt mem1_tgt mem2_tgt\n      (SIM: @sim_thread lang_src lang_tgt sim_terminal st_src lc_src sc1_src mem1_src st_tgt lc_tgt sc1_tgt mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc1_src sc2_src)\n      (SC_FUTURE_TGT: TimeMap.le sc1_tgt sc2_tgt)\n      (MEM_FUTURE_SRC: Memory.future_weak mem1_src mem2_src)\n      (MEM_FUTURE_TGT: Memory.future_weak mem1_tgt mem2_tgt):\n  sim_thread sim_terminal st_src lc_src sc2_src mem2_src st_tgt lc_tgt sc2_tgt mem2_tgt.\nProof.\n  pfold. ii.\n  punfold SIM. exploit SIM; (try by etrans; eauto); eauto.\nQed.\n\n\nLemma cap_property\n      mem1 mem2 lc sc\n      (CAP: Memory.cap mem1 mem2)\n      (WF: Local.wf lc mem1)\n      (SC: Memory.closed_timemap sc mem1)\n      (CLOSED: Memory.closed mem1):\n  <<FUTURE: Memory.future_weak mem1 mem2>> /\\\n  <<WF: Local.wf lc mem2>> /\\\n  <<SC: Memory.closed_timemap sc mem2>> /\\\n  <<CLOSED: Memory.closed mem2>>.\nProof.\n  splits.\n  - eapply Memory.cap_future_weak; eauto.\n  - eapply Local.cap_wf; eauto.\n  - eapply Memory.cap_closed_timemap; eauto.\n  - eapply Memory.cap_closed; eauto.\nQed.\n\nLemma sc_property\n      sc1 sc2 mem\n      (MAX: Memory.max_concrete_timemap mem sc2)\n      (SC1: Memory.closed_timemap sc1 mem)\n      (MEM: Memory.closed mem):\n  <<SC2: Memory.closed_timemap sc2 mem>> /\\\n  <<LE: TimeMap.le sc1 sc2>>.\nProof.\n  splits.\n  - eapply Memory.max_concrete_timemap_closed; eauto.\n  - eapply Memory.max_concrete_timemap_spec; eauto.\nQed.\n\nLemma sim_thread_consistent\n      lang_src lang_tgt\n      sim_terminal\n      st_src lc_src sc_src mem_src\n      st_tgt lc_tgt sc_tgt mem_tgt\n      (SIM: sim_thread sim_terminal st_src lc_src sc_src mem_src st_tgt lc_tgt sc_tgt mem_tgt)\n      (SC: TimeMap.le sc_src sc_tgt)\n      (MEMORY: sim_memory mem_src mem_tgt)\n      (WF_SRC: Local.wf lc_src mem_src)\n      (WF_TGT: Local.wf lc_tgt mem_tgt)\n      (SC_SRC: Memory.closed_timemap sc_src mem_src)\n      (SC_TGT: Memory.closed_timemap sc_tgt mem_tgt)\n      (MEM_SRC: Memory.closed mem_src)\n      (MEM_TGT: Memory.closed mem_tgt)\n      (CONSISTENT: Thread.consistent (Thread.mk lang_tgt st_tgt lc_tgt sc_tgt mem_tgt)):\n  Thread.consistent (Thread.mk lang_src st_src lc_src sc_src mem_src).\nProof.\n  hexploit consistent_promise_consistent; eauto. s. i.\n  generalize SIM. intro X.\n  punfold X. exploit X; eauto; try refl. i. des.\n  ii. ss.\n  exploit Memory.cap_exists; try exact MEM_TGT. i. des.\n  exploit cap_property; try exact CAP; eauto. i. des.\n  exploit cap_property; try exact CAP0; eauto. i. des.\n  exploit sim_memory_cap; try exact MEMORY; eauto. i. des.\n  exploit Memory.max_concrete_timemap_exists; try apply CLOSED0. i. des.\n  exploit sim_memory_max_concrete_timemap; try exact x0; eauto. i. subst.\n  exploit sc_property; try exact SC_MAX; eauto. i. des.\n  exploit sc_property; try exact x0; eauto. i. des.\n  exploit CONSISTENT; eauto. s. i. des.\n  - left. inv FAILURE. des.\n    exploit sim_thread_future; try exact SIM; try exact LE; try exact LE0; eauto. i.\n    exploit sim_thread_plus_step; try exact STEPS; try exact FAILURE; try exact x3; eauto; try refl.\n    { inv FAILURE; inv STEP0. inv LOCAL. inv LOCAL0. ss. }\n    i. des; auto. ss.\n  - hexploit Local.bot_promise_consistent; eauto. i.\n    exploit sim_thread_future; try exact SIM; try exact LE; try exact LE0; eauto. i.\n    exploit sim_thread_rtc_step; try apply STEPS; try exact x2; eauto; try refl. i. des; eauto.\n    destruct e2. ss.\n    punfold SIM0. exploit SIM0; eauto; try refl. i. des.\n    exploit PROMISES1; eauto. i. des.\n    + left. unfold Thread.steps_failure in *. des.\n      esplits; [|eauto]. etrans; eauto.\n    + right. eexists (Thread.mk _ _ _ _ _). splits; [|eauto].\n      etrans; eauto.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/opt/SimThread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.20456195283676032}}
{"text": "Require Import ExtLib.Core.Any.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection functor.\n\n  Polymorphic Class CoFunctor@{d c} (F : Type@{d} -> Type@{c}) : Type :=\n  { cofmap : forall {A B : Type@{d}}, (B -> A) -> F A -> F B }.\n\n  Polymorphic Class CoPFunctor@{d c p} (F : Type@{d} -> Type@{c}) : Type :=\n  { CoFunP : Type@{d} -> Type@{p}\n  ; copfmap : forall {A B : Type@{d}} {P : CoFunP B}, (B -> A) -> F A -> F B\n  }.\n\n  Existing Class CoFunP.\n  Hint Extern 0 (@CoFunP _ _ _) => progress (simpl CoFunP) : typeclass_instances.\n\n  Polymorphic Definition CoPFunctor_From_CoFunctor@{d c p} (F : Type@{d} -> Type@{c}) (F_ : CoFunctor@{d c} F) : CoPFunctor@{d c p} F :=\n  {| CoFunP := Any@{p}\n   ; copfmap := fun _ _ _ f x => cofmap f x\n   |}.\n  Global Existing Instance CoPFunctor_From_CoFunctor.\nEnd functor.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/coq-ext-lib/theories/Structures/CoFunctor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20446893907525907}}
{"text": "(*===========================================================================\n  Wrapped allocator\n  ===========================================================================*)\nRequire Import Ssreflect.ssreflect Ssreflect.ssrbool Ssreflect.ssrnat Ssreflect.eqtype Ssreflect.seq Ssreflect.fintype Ssreflect.tuple.\nRequire Import x86proved.x86.procstate x86proved.x86.procstatemonad x86proved.bitsrep x86proved.bitsops x86proved.bitsprops x86proved.bitsopsprops.\nRequire Import x86proved.spred x86proved.septac x86proved.spec x86proved.spectac x86proved.x86.basic x86proved.x86.program.\nRequire Import x86proved.x86.call x86proved.x86.instr x86proved.x86.instrsyntax x86proved.x86.instrrules x86proved.x86.instrcodec x86proved.reader x86proved.pointsto x86proved.cursor x86proved.x86.inlinealloc\n               x86proved.x86.listspec x86proved.x86.listimp x86proved.triple x86proved.x86.macros x86proved.chargetac x86proved.basicspectac x86proved.latertac.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nImport Prenex Implicits.\n\nDefinition wrappedAlloc bytes (r1 r2:Reg) heapInfo: program :=\n  (LOCAL FAIL;\n  LOCAL SUCCEED;\n    allocImp heapInfo bytes FAIL;;\n    SUB EDI, bytes;;\n    JMP SUCCEED;;\n  FAIL:;;\n    MOV EDI, 0;;\n  SUCCEED:;)\n  %asm.\n\nLemma wrappedAlloc_correct bytes (r1 r2: Reg) heapInfo :\n  |-- Forall i j: DWORD,\n  toyfun i EDI? ((Exists p:DWORD, EDI ~= p ** memAny p (p +# bytes)) \\\\// EDI ~= #0)\n\n  @  (ESI? ** OSZCP? ** allocInv heapInfo)\n  c@ (i -- j :-> mkbody_toyfun (wrappedAlloc bytes r1 r2 heapInfo)).\nProof.\nspecintros => i j.\n\n(* First deal with the calling-convention wrapper *)\nrewrite spec_at_toyfun.\netransitivity; [|apply toyfun_mkbody]. specintro => iret.\n\n(* Now unfold the control-flow logic *)\nrewrite /wrappedAlloc/basic. specintros => i1 i2. unfold_program.\nspecintros => i3 i4 i5 i6 i7 i8 -> -> i9 -> ->.\n\n(* Deal with the allocator spec itself *)\n(*rewrite spec_at_reads. *) rewrite spec_at_swap. rewrite spec_at_at. \ninstLem (inlineAlloc_correct) => IC.\nrewrite -> spec_at_impl in IC.\nrewrite spec_at_impl. \nsuperspecapply IC.\n\n(* Now we deal with failure and success cases *)\nspecsplit.\n\n(* failure case *)\n\n(* MOV EDI, 0 *)\nunhideReg EDI => oldedi.\nsuperspecapply *. rewrite /natAsDWORD. finish_logic_with sbazooka. by apply: lorR2. \n\n(* success case *)\n(* SUB EDI, bytes *)\nspecintros => pb.\n\n(* Subtraction arithmetic *)\nelim E0:(sbbB false (pb+#bytes) (# bytes)) => [carry0 res0].\nassert (H:= subB_equiv_addB_negB (pb+#bytes) # bytes).\nrewrite E0 in H. simpl (snd _) in H. rewrite addB_negBn in H.\nrewrite H in E0.\n\nsuperspecapply *. \n\n(* JMP SUCCEED *)\nsuperspecapply *. simpllater. \n\n(* Final stuff *)\nrewrite E0. simpl snd. \nfinish_logic_with sbazooka. apply: lorR1. sbazooka. \nQed.\n", "meta": {"author": "nbenton", "repo": "x86proved", "sha": "7a58960f6456ee09dd46c990204a30c2fdd7fa1a", "save_path": "github-repos/coq/nbenton-x86proved", "path": "github-repos/coq/nbenton-x86proved/x86proved-7a58960f6456ee09dd46c990204a30c2fdd7fa1a/src/x86/wrapalloc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.20446893907525898}}
{"text": "\nRequire Import RamifyCoq.CertiGC.gc_spec.\nRequire Import RamifyCoq.msl_ext.ramification_lemmas.\n\nLemma root_valid_int_or_ptr: forall g (roots: roots_t) root outlier,\n    In root roots ->\n    roots_compatible g outlier roots ->\n    graph_rep g * outlier_rep outlier |-- !! (valid_int_or_ptr (root2val g root)).\nProof.\n  intros. destruct H0. destruct root as [[? | ?] | ?].\n  - simpl root2val. unfold odd_Z2val. replace (2 * z + 1) with (z + z + 1) by omega.\n    apply prop_right, valid_int_or_ptr_ii1.\n  - sep_apply (roots_outlier_rep_single_rep _ _ _ H H0).\n    sep_apply (single_outlier_rep_valid_int_or_ptr g0). entailer!.\n  - red in H1. rewrite Forall_forall in H1.\n    rewrite (filter_sum_right_In_iff v roots) in H.\n    apply H1 in H. simpl. sep_apply (graph_rep_valid_int_or_ptr _ _ H). entailer!.\nQed.\n\nLemma weak_derives_strong: forall (P Q: mpred),\n    P |-- Q -> P |-- (weak_derives P Q && emp) * P.\nProof.\n  intros. cancel. apply andp_right. 2: cancel.\n  assert (HS: emp |-- TT) by entailer; sep_apply HS; clear HS.\n  apply derives_weak. assumption.\nQed.\n\nLemma sapi_ptr_val: forall p m n,\n    isptr p -> Int.min_signed <= n <= Int.max_signed ->\n    (force_val\n       (sem_add_ptr_int int_or_ptr_type Signed (offset_val (WORD_SIZE * m) p)\n                        (vint n))) = offset_val (WORD_SIZE * (m + n)) p.\nProof.\n  intros. rewrite sem_add_pi_ptr_special.\n  - simpl. rewrite offset_offset_val. f_equal. rep_omega.\n  - rewrite isptr_offset_val. assumption.\n  - assumption.\nQed.\n\nLemma data_at_mfs_eq: forall g v i sh nv,\n    field_compatible int_or_ptr_type [] (offset_val (WORD_SIZE * i) nv) ->\n    0 <= i < Zlength (raw_fields (vlabel g v)) ->\n    data_at sh (tarray int_or_ptr_type i) (sublist 0 i (make_fields_vals g v)) nv *\n    field_at sh int_or_ptr_type [] (Znth i (make_fields_vals g v))\n             (offset_val (WORD_SIZE * i) nv) =\n    data_at sh (tarray int_or_ptr_type (i + 1))\n            (sublist 0 (i + 1) (make_fields_vals g v)) nv.\nProof.\n  intros. rewrite field_at_data_at. unfold field_address.\n  rewrite if_true by assumption. simpl nested_field_type.\n  simpl nested_field_offset. rewrite offset_offset_val.\n  replace (WORD_SIZE * i + 0) with (WORD_SIZE * i)%Z by omega.\n  rewrite <- (data_at_singleton_array_eq\n                sh int_or_ptr_type _ [Znth i (make_fields_vals g v)]) by reflexivity.\n  rewrite <- fields_eq_length in H0.\n  rewrite (data_at_tarray_value\n             sh (i + 1) i nv (sublist 0 (i + 1) (make_fields_vals g v))\n             (make_fields_vals g v) (sublist 0 i (make_fields_vals g v))\n             [Znth i (make_fields_vals g v)]).\n  - replace (i + 1 - i) with 1 by omega. reflexivity.\n  - omega.\n  - omega.\n  - autorewrite with sublist. reflexivity.\n  - reflexivity.\n  - rewrite sublist_one; [reflexivity | omega..].\nQed.\n\nLemma data_at__value_0_size: forall sh p,\n    data_at_ sh (tarray int_or_ptr_type 0) p |-- emp.\nProof. intros. rewrite data_at__eq. apply data_at_zero_array_inv; reflexivity. Qed.\n\nLemma data_at_minus1_address: forall sh v p,\n    data_at sh tuint v (offset_val (- WORD_SIZE) p) |--\n   !! (force_val (sem_add_ptr_int tuint Signed p (eval_unop Oneg tint (vint 1))) =\n       field_address tuint [] (offset_val (- WORD_SIZE) p)).\nProof.\n  intros. unfold eval_unop. simpl. rewrite WORD_SIZE_eq. entailer!.\n  unfold field_address. rewrite if_true by assumption. rewrite offset_offset_val.\n  simpl. reflexivity.\nQed.\n\nLemma body_forward: semax_body Vprog Gprog f_forward forward_spec.\nProof.\n  start_function.\n  destruct H as [? [? [? ?]]]. destruct H1 as [? [? [? [? ?]]]].\n  unfold limit_address, next_address, forward_p_address. destruct forward_p.\n  - unfold thread_info_rep. Intros.\n    assert (Zlength roots = Zlength (live_roots_indices f_info)) by\n        (rewrite <- (Zlength_map _ _ (flip Znth (ti_args t_info))), <- H4, Zlength_map; trivial).\n    pose proof (Znth_map _ (root2val g) _ H0). hnf in H0. rewrite H11 in H0.\n    rewrite H4, Znth_map in H12 by assumption. unfold flip in H12.\n    remember (Znth z roots) as root. rewrite <- H11 in H0.\n    pose proof (Znth_In _ _ H0).\n    rewrite <- Heqroot in H13. rewrite H11 in H0. unfold Inhabitant_val in H12.\n    assert (forall v, In (inr v) roots -> isptr (vertex_address g v)). { (**)\n      intros. destruct H5. unfold vertex_address. red in H15.\n      rewrite Forall_forall in H15.\n      rewrite (filter_sum_right_In_iff v roots) in H14. apply H15 in H14.\n      destruct H14. apply graph_has_gen_start_isptr in H14.\n      remember (gen_start g (vgeneration v)) as vv. destruct vv; try contradiction.\n      simpl. exact I. }\n    assert (is_pointer_or_integer (root2val g root)). {\n      destruct root as [[? | ?] | ?]; simpl; auto.\n      - destruct g0. simpl. exact I.\n      - specialize (H14 _ H13). apply isptr_is_pointer_or_integer. assumption. }\n    assert (0 <= Znth z (live_roots_indices f_info) < MAX_ARGS) by\n        (apply (fi_index_range f_info), Znth_In; assumption).\n    forward; rewrite H12. 1: entailer!.\n    assert_PROP (valid_int_or_ptr (root2val g root)). {\n      gather_SEP 3 2. (* no matching clauses for match *)\n      sep_apply (root_valid_int_or_ptr _ _ _ _ H13 H5). entailer!. }\n    forward_call (root2val g root).\n    remember (graph_rep g * heap_rest_rep (ti_heap t_info) * outlier_rep outlier)\n      as P. pose proof (graph_and_heap_rest_data_at_ _ _ _ H7 H).\n    unfold generation_data_at_ in H18. remember (gen_start g from) as fp.\n    remember (nth_sh g from) as fsh. remember (gen_size t_info from) as gn.\n    remember (WORD_SIZE * gn)%Z as fn.\n    assert (P |-- (weak_derives P (memory_block fsh fn fp * TT) && emp) * P). {\n      apply weak_derives_strong. subst. sep_apply H18.\n      rewrite data_at__memory_block.\n      rewrite sizeof_tarray_int_or_ptr; [Intros; cancel | unfold gen_size].\n      destruct (total_space_tight_range (nth_space t_info from)). assumption. }\n    destruct root as [[? | ?] | ?]; simpl root2val.\n    + unfold odd_Z2val. apply semax_if_seq. forward_if.\n      1: exfalso; apply H20'; reflexivity.\n      forward. Exists g t_info roots.\n      entailer!. \n      * simpl; split3; try rewrite <- Heqroot; [easy..|].\n        split3; [constructor | easy | apply tir_id].\n      * unfold thread_info_rep. entailer!.\n    + unfold GC_Pointer2val. destruct g0. apply semax_if_seq. forward_if.\n      2: exfalso; apply Int.one_not_zero in H20; assumption.\n      forward_call (Vptr b i).\n      gather_SEP (graph_rep g)\n                 (heap_rest_rep (ti_heap t_info)) (outlier_rep outlier).\n      (* gather_SEP 3 6 2. *)\n      rewrite <- HeqP. destruct H5.\n      replace_SEP 0 ((weak_derives P (memory_block fsh fn fp * TT) && emp) * P) by\n          (entailer; assumption). clear H19. Intros. simpl root2val in *.\n      assert (P |-- (weak_derives P (valid_pointer (Vptr b i) * TT) && emp) * P). {\n        subst. cancel. apply andp_right. 2: cancel.\n        assert (HS: emp |-- TT) by entailer; sep_apply HS; clear HS.\n        apply derives_weak.\n        sep_apply (roots_outlier_rep_valid_pointer _ _ _ H13 H5).\n        simpl GC_Pointer2val. cancel. }\n      replace_SEP 1 ((weak_derives P (valid_pointer (Vptr b i) * TT) && emp) * P) by\n          (entailer; assumption). Intros. clear H19.\n      forward_call (fsh, fp, fn, (Vptr b i), P). Intros v. destruct v.\n      * rewrite HeqP. Intros.\n        gather_SEP (graph_rep g) (heap_rest_rep (ti_heap t_info)).\n        sep_apply H18. rewrite Heqfn in v.\n        sep_apply (roots_outlier_rep_single_rep _ _ _ H13 H5). Intros.\n        gather_SEP (single_outlier_rep (GCPtr b i))\n                   (data_at_ fsh (tarray int_or_ptr_type gn) fp).\n        change (Vptr b i) with (GC_Pointer2val (GCPtr b i)) in v.\n        pose proof (generation_share_writable (nth_gen g from)).\n        change (generation_sh (nth_gen g from)) with (nth_sh g from) in H19.\n        rewrite <- Heqfsh in H19. unfold generation_data_at_.\n        sep_apply (single_outlier_rep_memory_block_FF (GCPtr b i) fp gn fsh H19 v).\n        assert_PROP False by entailer!. contradiction.\n      * apply semax_if_seq. forward_if. 1: exfalso; apply H19'; reflexivity.\n        forward. Exists g t_info roots.\n        entailer!.\n        -- split3; [| |split3]; simpl; try rewrite <- Heqroot;\n             [easy.. | constructor | hnf; intuition | apply tir_id].\n        -- unfold thread_info_rep. entailer!.\n    + specialize (H14 _ H13). destruct (vertex_address g v) eqn:? ; try contradiction.\n      apply semax_if_seq. forward_if.\n      2: exfalso; apply Int.one_not_zero in H20; assumption.\n      clear H20 H20'. simpl in H15, H17. forward_call (Vptr b i).\n      rewrite <- Heqv0 in *.\n      (* gather_SEP 3 6 2. *)\n      gather_SEP (graph_rep g)\n                 (heap_rest_rep _) (outlier_rep _).\n      rewrite <- HeqP.\n      replace_SEP 0 ((weak_derives P (memory_block fsh fn fp * TT) && emp) * P) by\n          (entailer; assumption). clear H19. Intros. assert (graph_has_v g v). {\n        destruct H5. red in H19. rewrite Forall_forall in H19. apply H19.\n        rewrite <- filter_sum_right_In_iff. assumption. }\n      assert (P |-- (weak_derives P (valid_pointer (Vptr b i) * TT) && emp) * P). {\n        apply weak_derives_strong. subst. sep_apply (graph_rep_vertex_rep g v H19).\n        Intros shh. unfold vertex_rep, vertex_at. remember (make_fields_vals g v).\n        sep_apply (data_at_valid_ptr shh (tarray int_or_ptr_type (Zlength l)) l\n                                     (vertex_address g v)).\n        - apply readable_nonidentity, writable_readable_share. assumption.\n        - subst l. simpl. rewrite fields_eq_length.\n          rewrite Z.max_r; pose proof (raw_fields_range (vlabel g v)); omega.\n        - rewrite Heqv0. cancel.                    \n      }\n      replace_SEP 1 (weak_derives P (valid_pointer (Vptr b i) * TT) && emp * P)\n        by (entailer; assumption). clear H20. Intros. rewrite <- Heqv0 in *.\n      forward_call (fsh, fp, fn, (vertex_address g v), P). Intros vv. rewrite HeqP.\n      sep_apply (graph_and_heap_rest_v_in_range_iff _ _ _ _ H H7 H19). Intros.\n      rewrite <- Heqfp, <- Heqgn, <- Heqfn in H20. destruct vv.\n      * Intros. rewrite H20 in v0. clear H20. apply semax_if_seq. forward_if.\n        2: exfalso; inversion H20. deadvars!. freeze [1; 2; 3; 4; 5; 6] FR.\n        clear H20 H20'. localize [vertex_rep (nth_sh g (vgeneration v)) g v].\n        unfold vertex_rep, vertex_at. Intros. rewrite v0.\n        assert (readable_share (nth_sh g from)) by\n            (unfold nth_sh; apply writable_readable, generation_share_writable).\n        sep_apply (data_at_minus1_address (nth_sh g from) (Z2val (make_header g v))\n                                          (vertex_address g v)).\n        Intros. forward. clear H21.\n        gather_SEP\n          (data_at (nth_sh g from) tuint (Z2val (make_header g v))\n                   (offset_val (- WORD_SIZE) (vertex_address g v)) )\n          (data_at (nth_sh g from)\n                   (tarray int_or_ptr_type (Zlength (make_fields_vals g v)))\n                   (make_fields_vals g v) (vertex_address g v)).\n        replace_SEP 0 (vertex_rep (nth_sh g (vgeneration v)) g v) by\n            (unfold vertex_rep, vertex_at; entailer!).\n        unlocalize [graph_rep g]. 1: apply (graph_vertex_ramif_stable _ _ H19).\n        apply semax_if_seq. forward_if; rewrite make_header_int_rep_mark_iff in H21.\n        -- deadvars!. localize [vertex_rep (nth_sh g (vgeneration v)) g v].\n           rewrite v0. unfold vertex_rep, vertex_at. Intros.\n           unfold make_fields_vals at 2. rewrite H21.\n           assert (0 <= 0 < Zlength (make_fields_vals g v)). {\n             split. 1: omega. rewrite fields_eq_length.\n             apply (proj1 (raw_fields_range (vlabel g v))). }\n           assert (is_pointer_or_integer\n                     (vertex_address g (copied_vertex (vlabel g v)))). {\n             apply isptr_is_pointer_or_integer. unfold vertex_address.\n             rewrite isptr_offset_val.\n             apply graph_has_gen_start_isptr, H9; assumption. }\n           forward. rewrite Znth_0_cons.\n           gather_SEP\n             (data_at (nth_sh g from) tuint (Z2val (make_header g v))\n                      (offset_val (- WORD_SIZE) (vertex_address g v)) )\n             (data_at (nth_sh g from)\n                      (tarray int_or_ptr_type (Zlength (make_fields_vals g v)))\n                      (vertex_address g (copied_vertex (vlabel g v))\n                                      :: tl (map (field2val g) (make_fields g v)))\n                      (vertex_address g v)).\n           replace_SEP 0 (vertex_rep (nth_sh g (vgeneration v)) g v). {\n             unfold vertex_rep, vertex_at. unfold make_fields_vals at 3.\n             rewrite H21. entailer!. }\n           unlocalize [graph_rep g]. 1: apply (graph_vertex_ramif_stable _ _ H19).\n           thaw FR. forward. forward.\n           Exists g (upd_thread_info_arg\n                       t_info\n                       (Znth z (live_roots_indices f_info))\n                       (vertex_address g (copied_vertex (vlabel g v))) H16)\n                  (upd_bunch z f_info roots (inr (copied_vertex (vlabel g v)))).\n           unfold thread_info_rep. simpl. entailer!. split; split; [| | |split].\n           ++ apply upd_fun_thread_arg_compatible. assumption.\n           ++ specialize (H9 _ H19 H21). destruct H9 as [? _].\n              apply upd_roots_compatible; assumption.\n           ++ rewrite <- Heqroot, H21.\n              now rewrite if_true by reflexivity.\n           ++ rewrite <- Heqroot. apply fr_v_in_forwarded; [reflexivity | assumption].\n           ++ easy.\n        -- forward. thaw FR. freeze [0; 1; 2; 3; 4; 5] FR.\n           apply not_true_is_false in H21. rewrite make_header_Wosize by assumption.\n           assert (0 <= Z.of_nat to < 12). {\n             clear -H H8. destruct H as [_ [_ ?]]. red in H8.\n             pose proof (spaces_size (ti_heap t_info)).\n             rewrite Zlength_correct in H0. rep_omega. } unfold heap_struct_rep.\n           destruct (gt_gs_compatible _ _ H _ H8) as [? [? ?]].\n           rewrite nth_space_Znth in *.\n           remember (Znth (Z.of_nat to) (spaces (ti_heap t_info))) as sp_to.\n           assert (isptr (space_start sp_to)) by (rewrite <- H23; apply start_isptr).\n           remember (map space_tri (spaces (ti_heap t_info))) as l.\n           assert (@Znth (val * (val * val)) (Vundef, (Vundef, Vundef))\n                         (Z.of_nat to) l = space_tri sp_to). {\n             subst l sp_to. rewrite Znth_map by (rewrite spaces_size; rep_omega).\n             reflexivity. }\n           forward; rewrite H27; unfold space_tri. 1: entailer!.\n           forward. simpl sem_binary_operation'.\n           rewrite sapi_ptr_val; [|assumption | rep_omega].\n           Opaque Znth. forward. Transparent Znth.\n           assert (Hr: Int.min_signed <= Zlength (raw_fields (vlabel g v)) <=\n                       Int.max_signed). {\n             pose proof (raw_fields_range (vlabel g v)). destruct H28. split.\n             1: rep_omega. transitivity (two_power_nat 22). 1: omega.\n             compute; intro s; inversion s. }\n           rewrite sapi_ptr_val by assumption. rewrite H27. unfold space_tri.\n           rewrite <- Z.add_assoc.\n           replace (1 + Zlength (raw_fields (vlabel g v))) with (vertex_size g v) by\n               (unfold vertex_size; omega). thaw FR. freeze [0; 2; 3; 4; 5; 6] FR.\n           assert (Hi : 0 <= Z.of_nat to < Zlength (spaces (ti_heap t_info))) by\n               (rewrite spaces_size; rep_omega).\n           assert (Hh: has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info)))\n                                 (vertex_size g v)). {\n             red. split. 1: pose proof (svs_gt_one g v); omega.\n             transitivity (unmarked_gen_size g (vgeneration v)).\n             - apply single_unmarked_le; assumption.\n             - red in H1. unfold rest_gen_size in H1. subst from.\n               rewrite nth_space_Znth in H1. assumption. }\n           assert (Hn: space_start (Znth (Z.of_nat to) (spaces (ti_heap t_info))) <>\n                       nullval). {\n             rewrite <- Heqsp_to. destruct (space_start sp_to); try contradiction.\n             intro Hn. inversion Hn. }\n           rewrite (heap_rest_rep_cut\n                      (ti_heap t_info) (Z.of_nat to) (vertex_size g v) Hi Hh Hn).\n           rewrite <- Heqsp_to. thaw FR.\n           (* gather_SEP 4 5 7. *)\n           gather_SEP (data_at sh thread_info_type _ ti) \n                      (data_at sh heap_type _ _) \n                      (heap_rest_rep _).\n           replace_SEP 0 (thread_info_rep\n                            sh (cut_thread_info t_info _ _ Hi Hh) ti). {\n             entailer. unfold thread_info_rep. simpl ti_heap. simpl ti_heap_p. cancel.\n             simpl spaces. rewrite <- upd_Znth_map. unfold cut_space.\n             unfold space_tri at 3. simpl. unfold heap_struct_rep. cancel. }\n           sep_apply (graph_vertex_ramif_stable _ _ H19). Intros.\n           freeze [1; 2; 3; 4; 5] FR. deadvars!. rewrite v0.\n           remember (nth_sh g from) as shv.\n           assert (writable_share (space_sh sp_to)) by\n               (rewrite <- H24; apply generation_share_writable).\n           remember (space_sh sp_to) as sht.\n           rewrite (data_at__tarray_value _ _ 1). 2: unfold vertex_size; rep_omega.\n           Intros.\n           remember (offset_val (WORD_SIZE * used_space sp_to) (space_start sp_to)).\n           rewrite (data_at__int_or_ptr_tuint sht v1).\n           assert_PROP\n             (force_val (sem_add_ptr_int\n                           tuint Signed\n                           (offset_val (WORD_SIZE * (used_space sp_to + 1))\n                                       (space_start sp_to))\n                           (eval_unop Oneg tint (vint 1))) =\n              field_address tuint [] v1). {\n             subst v1. rewrite WORD_SIZE_eq. entailer!. simpl. rewrite neg_repr.\n             rewrite sem_add_pi_ptr_special'; auto. simpl. unfold field_address.\n             rewrite if_true by assumption. simpl. rewrite !offset_offset_val.\n             f_equal. omega. }\n           forward. sep_apply (field_at_data_at_cancel\n                                 sht tuint (Z2val (make_header g v)) v1). clear H29.\n           subst v1. rewrite offset_offset_val.\n           replace (vertex_size g v - 1) with (Zlength (raw_fields (vlabel g v)))\n             by (unfold vertex_size; omega).\n           replace (WORD_SIZE * used_space sp_to + WORD_SIZE * 1) with\n               (WORD_SIZE * (used_space sp_to + 1))%Z by rep_omega.\n           remember (offset_val (WORD_SIZE * (used_space sp_to + 1))\n                                (space_start sp_to)) as nv.\n           thaw FR. freeze [0; 1; 2; 3; 4; 5] FR. rename i into j. deadvars!.\n           remember (Zlength (raw_fields (vlabel g v))) as n.\n           assert (isptr nv) by (subst nv; rewrite isptr_offset_val; assumption).\n           remember (field_address thread_info_type\n                                   [ArraySubsc (Znth z (live_roots_indices f_info));\n                                    StructField _args] ti) as p_addr.\n           remember (field_address heap_type\n                                   [StructField _next; ArraySubsc (Z.of_nat to);\n                                    StructField _spaces] (ti_heap_p t_info)) as n_addr.\n           forward_for_simple_bound\n             n\n             (EX i: Z,\n              PROP ( )\n              LOCAL (temp _new nv;\n                     temp _sz (vint n);\n                     temp _v (vertex_address g v);\n                     temp _from_start fp;\n                     temp _from_limit (offset_val fn fp);\n                     temp _next n_addr;\n                     temp _p p_addr;\n                     temp _depth (vint depth))\n              SEP (vertex_rep shv g v;\n                   data_at sht (tarray int_or_ptr_type i)\n                           (sublist 0 i (make_fields_vals g v)) nv;\n                   data_at_ sht (tarray int_or_ptr_type (n - i))\n                            (offset_val (WORD_SIZE * i) nv); FRZL FR))%assert.\n           ++ rewrite sublist_nil. replace (n - 0) with n by omega.\n              replace (WORD_SIZE * 0)%Z with 0 by omega.\n              rewrite isptr_offset_val_zero by assumption.\n              rewrite data_at_zero_array_eq;\n                [|reflexivity | assumption | reflexivity]. entailer!.\n           ++ unfold vertex_rep, vertex_at. Intros.\n              rewrite fields_eq_length, <- Heqn. forward.\n              ** entailer!. pose proof (mfv_all_is_ptr_or_int _ _ H9 H10 H19).\n                 rewrite Forall_forall in H45. apply H45, Znth_In.\n                 rewrite fields_eq_length. assumption.\n              ** rewrite (data_at__tarray_value _ _ 1) by omega. Intros.\n                 rewrite data_at__singleton_array_eq.\n                 assert_PROP\n                   (field_compatible int_or_ptr_type []\n                                     (offset_val (WORD_SIZE * i) nv)) by\n                     (sep_apply (data_at__local_facts\n                                   sht int_or_ptr_type\n                                   (offset_val (WORD_SIZE * i) nv)); entailer!).\n                 assert_PROP\n                   (force_val (sem_add_ptr_int int_or_ptr_type\n                                               Signed nv (vint i)) =\n                    field_address int_or_ptr_type []\n                                  (offset_val (WORD_SIZE * i) nv)). {\n                   unfold field_address. rewrite if_true by assumption.\n                   clear. entailer!. }\n                 gather_SEP\n                 (data_at shv tuint (Z2val (make_header g v))\n                           (offset_val (- WORD_SIZE) (vertex_address g v)))\n                    (data_at shv (tarray int_or_ptr_type n) (make_fields_vals g v)\n                             (vertex_address g v)). \n                  replace_SEP 0 (vertex_rep shv g v) by\n                      (unfold vertex_rep, vertex_at;\n                       rewrite fields_eq_length; entailer!). forward.\n                 rewrite offset_offset_val.\n                 replace (n - i - 1) with (n - (i + 1)) by omega.\n                 replace (WORD_SIZE * i + WORD_SIZE * 1) with\n                     (WORD_SIZE * (i + 1))%Z by rep_omega.\n                 gather_SEP 1 2.\n                 (* gather_SEP *)\n                 (*   (data_at sht *)\n                 (*            (tarray int_or_ptr_type i) *)\n                 (*            (sublist 0 i (make_fields_vals g v)) *)\n                 (*            nv) *)\n                 (*   (field_at sht int_or_ptr_type [] *)\n                 (*             (Znth i (make_fields_vals g v)) *)\n                 (*             (offset_val (WORD_SIZE * i) nv)). *)\n                 (* no matching clauses *)\n                 rewrite data_at_mfs_eq. 2: assumption.\n                 2: subst n; assumption. entailer!.\n           ++ thaw FR. rewrite v0, <- Heqshv.\n              gather_SEP 0 4.\n              (* gather_SEP (vertex_rep shv g v) (vertex_rep shv g v -* graph_rep g). *)\n              (* no matching clauses *)\n              replace_SEP 0 (graph_rep g) by (entailer!; apply wand_frame_elim).\n              rewrite sublist_all by (rewrite fields_eq_length; omega).\n              replace_SEP 2 emp. {\n                replace (n - n) with 0 by omega. clear. entailer.\n                apply data_at__value_0_size. }\n              assert (nv = vertex_address g (new_copied_v g to)). {\n                subst nv. unfold vertex_address. unfold new_copied_v. simpl. f_equal.\n                - unfold vertex_offset. simpl. rewrite H25. reflexivity.\n                - unfold gen_start. rewrite if_true by assumption.\n                  rewrite H23. reflexivity. }\n              (* gather_SEP 1 2 3. *)\n              gather_SEP\n              (data_at sht _ _ nv)\n              (emp) (data_at sht tuint _ _).\n              replace_SEP\n                0 (vertex_at (nth_sh g to)\n                             (vertex_address g (new_copied_v g to))\n                             (make_header g v) (make_fields_vals g v)). {\n                normalize. rewrite <- H24.\n                change (generation_sh (nth_gen g to)) with (nth_sh g to).\n                rewrite <- fields_eq_length in Heqn.\n                replace (offset_val (WORD_SIZE * used_space sp_to) (space_start sp_to))\n                  with (offset_val (- WORD_SIZE) nv) by\n                    (rewrite Heqnv; rewrite offset_offset_val; f_equal; rep_omega).\n                rewrite <- H30. unfold vertex_at; entailer!. }\n              gather_SEP (vertex_at (nth_sh g to) (vertex_address g (new_copied_v g to))\n            (make_header g v) (make_fields_vals g v)) (graph_rep g).\n              rewrite (copied_v_derives_new_g g v to) by assumption.\n              freeze [1; 2; 3; 4] FR. remember (lgraph_add_copied_v g v to) as g'.\n              assert (vertex_address g' v = vertex_address g v) by\n                  (subst g'; apply lacv_vertex_address_old; assumption).\n              assert (vertex_address g' (new_copied_v g to) =\n                      vertex_address g (new_copied_v g to)) by\n                  (subst g'; apply lacv_vertex_address_new; assumption).\n              rewrite <- H31. rewrite <- H32 in H30.\n              assert (writable_share (nth_sh g' (vgeneration v))) by\n                  (unfold nth_sh; apply generation_share_writable).\n              assert (graph_has_v g' (new_copied_v g to)) by\n                  (subst g'; apply lacv_graph_has_v_new; assumption).\n              sep_apply (graph_rep_valid_int_or_ptr _ _ H34). Intros.\n              rewrite <- H30 in H35. assert (graph_has_v g' v) by\n                  (subst g'; apply lacv_graph_has_v_old; assumption).\n              remember (nth_sh g' (vgeneration v)) as sh'.\n              sep_apply (graph_vertex_lmc_ramif g' v (new_copied_v g to) H36).\n              rewrite <- Heqsh'. Intros. freeze [1; 2] FR1.\n              unfold vertex_rep, vertex_at. Intros.\n              sep_apply (data_at_minus1_address\n                           sh' (Z2val (make_header g' v)) (vertex_address g' v)).\n              Intros. forward. clear H37.\n              sep_apply (field_at_data_at_cancel\n                           sh' tuint (vint 0)\n                           (offset_val (- WORD_SIZE) (vertex_address g' v))).\n              forward_call (nv). remember (make_fields_vals g' v) as l'.\n              assert (0 < Zlength l'). {\n                subst l'. rewrite fields_eq_length.\n                apply (proj1 (raw_fields_range (vlabel g' v))). }\n              rewrite data_at_tarray_value_split_1 by assumption. Intros.\n              assert_PROP (force_val (sem_add_ptr_int int_or_ptr_type Signed\n                                                      (vertex_address g' v) (vint 0)) =\n                           field_address int_or_ptr_type [] (vertex_address g' v)). {\n                clear. entailer!. unfold field_address. rewrite if_true by assumption.\n                simpl. rewrite isptr_offset_val_zero. 1: reflexivity.\n                destruct H7. assumption. } forward. clear H38.\n              sep_apply (field_at_data_at_cancel\n                           sh' int_or_ptr_type nv (vertex_address g' v)).\n              (* gather_SEP 1 0 3. *)\n              gather_SEP\n                (data_at sh' tuint (vint 0) _) \n                (data_at sh' int_or_ptr_type nv _)\n                (data_at sh' _ _ _).\n              rewrite H30. subst l'.\n              rewrite <- lmc_vertex_rep_eq.\n              thaw FR1.\n              gather_SEP 0 1.\n              (* no matching clauses *)\n              (* gather_SEP *)\n              (*   (vertex_rep sh' (lgraph_mark_copied g' v (new_copied_v g to)) v) *)\n              (*   (vertex_rep sh' (lgraph_mark_copied g' v (new_copied_v g to)) v -* *)\n              (*                graph_rep (lgraph_mark_copied g' v (new_copied_v g to))). *)\n              sep_apply\n                (wand_frame_elim\n                   (vertex_rep sh' (lgraph_mark_copied g' v (new_copied_v g to)) v)\n                   (graph_rep (lgraph_mark_copied g' v (new_copied_v g to)))).\n              rewrite <- (lmc_vertex_address g' v (new_copied_v g to)) in *. subst g'.\n              change (lgraph_mark_copied\n                        (lgraph_add_copied_v g v to) v (new_copied_v g to))\n                with (lgraph_copy_v g v to) in *.\n              remember (lgraph_copy_v g v to) as g'. rewrite <- H30 in *. thaw FR.\n              forward_call (nv). subst p_addr.\n              remember (cut_thread_info t_info (Z.of_nat to) (vertex_size g v) Hi Hh)\n                as t_info'. unfold thread_info_rep. Intros. forward.\n              remember (Znth z (live_roots_indices f_info)) as lz.\n              (* gather_SEP 1 2 3. *)\n              gather_SEP\n                (data_at sh thread_info_type _ ti)\n                (heap_struct_rep sh _ _)\n                (heap_rest_rep _ ).\n              replace_SEP 0 (thread_info_rep\n                               sh (update_thread_info_arg t_info' lz nv H16) ti). {\n                unfold thread_info_rep. simpl heap_head. simpl ti_heap_p.\n                simpl ti_args. simpl ti_heap. clear Heqt_info'. entailer!. }\n              remember (update_thread_info_arg t_info' lz nv H16) as t. subst t_info'.\n              rename t into t_info'. rewrite H30 in H32.\n              assert (forward_relation from to 0 (inl (inr v)) g g') by\n                  (subst g'; constructor; assumption).\n              assert (forward_condition g' t_info' from to). {\n                subst g' t_info' from. apply lcv_forward_condition; try assumption.\n                red. intuition. }\n              remember (upd_bunch z f_info roots (inr (new_copied_v g to))) as roots'.\n              assert (super_compatible (g', t_info', roots') f_info outlier). {\n                subst g' t_info' roots' lz. rewrite H30, H32.\n                apply lcv_super_compatible; try assumption. red. intuition. }\n              assert (thread_info_relation t_info t_info'). {\n                subst t_info'. split; [|split]; [reflexivity| |]; intros m.\n                - rewrite utiacti_gen_size. reflexivity.\n                - rewrite utiacti_space_start. reflexivity. }\n              apply semax_if_seq. forward_if.\n              ** destruct H41 as [? [? ?]]. replace fp with (gen_start g' from) by\n                     (subst fp g'; apply lcv_gen_start; assumption).\n                 replace (offset_val fn (gen_start g' from)) with\n                     (limit_address g' t_info' from) by\n                     (subst fn gn; rewrite H43; reflexivity).\n                 replace n_addr with (next_address t_info' to) by\n                     (subst n_addr; rewrite H41; reflexivity).\n                 forward_for_simple_bound\n                   n\n                   (EX i: Z, EX g3: LGraph, EX t_info3: thread_info,\n                    PROP (super_compatible (g3, t_info3, roots') f_info outlier;\n                          forward_loop\n                            from to (Z.to_nat (depth - 1))\n                            (sublist 0 i (vertex_pos_pairs g' (new_copied_v g to)))\n                            g' g3;\n                          forward_condition g3 t_info3 from to;\n                          thread_info_relation t_info' t_info3)\n                    LOCAL (temp _new nv;\n                           temp _sz (vint n);\n                           temp _from_start (gen_start g3 from);\n                           temp _from_limit (limit_address g3 t_info3 from);\n                           temp _next (next_address t_info3 to);\n                           temp _depth (vint depth))\n                    SEP (all_string_constants rsh gv;\n                         fun_info_rep rsh f_info fi;\n                         outlier_rep outlier;\n                         graph_rep g3;\n                         thread_info_rep sh t_info3 ti))%assert.\n                 --- Exists g' t_info'. autorewrite with sublist.\n                     assert (forward_loop from to (Z.to_nat (depth - 1)) [] g' g') by\n                         constructor. unfold thread_info_relation. entailer!.\n                 --- change (Tpointer tvoid {| attr_volatile := false;\n                                               attr_alignas := Some 2%N |})\n                       with (int_or_ptr_type). Intros.\n                     assert (graph_has_gen g' to) by\n                         (rewrite Heqg', <- lcv_graph_has_gen; assumption).\n                     assert (graph_has_v g' (new_copied_v g to)) by\n                         (rewrite Heqg'; apply lcv_graph_has_v_new; assumption).\n                     forward_call (rsh, sh, gv, fi, ti, g3, t_info3, f_info, roots',\n                                   outlier, from, to, depth - 1,\n                                   (@inr Z _ (new_copied_v g to, i))).\n                     +++ simpl. apply prop_right. rewrite sub_repr.\n                         do 3 split; [|easy]. f_equal. rewrite H30.\n                         rewrite sem_add_pi_ptr_special.\n                         *** simpl. f_equal. erewrite fl_vertex_address; eauto.\n                             subst g'. apply graph_has_v_in_closure. assumption.\n                         *** rewrite <- H30. assumption.\n                         *** subst n. clear -H45 Hr. rep_omega.\n                     +++ do 3 (split; [assumption |]). split.\n                         *** simpl. split; [|split; [|split]]; auto.\n                             ---- destruct H39 as [_ [_ [? _]]].\n                                  apply (fl_graph_has_v _ _ _ _ _ _ H39 H47 _ H51).\n                             ---- erewrite <- fl_raw_fields; eauto. subst g'.\n                                  unfold lgraph_copy_v. subst n.\n                                  rewrite <- lmc_raw_fields, lacv_vlabel_new.\n                                  assumption.\n                             ---- erewrite <- fl_raw_mark; eauto. subst g' from.\n                                  rewrite lcv_vlabel_new; assumption.\n                         *** split; [assumption|]. split; [omega | assumption].\n                     +++ Intros vret. destruct vret as [[g4 t_info4] roots4].\n                         simpl fst in *. simpl snd in *. Exists g4 t_info4.\n                         simpl in H53. subst roots4.\n                         assert (gen_start g3 from = gen_start g4 from). {\n                           eapply fr_gen_start; eauto.\n                           erewrite <- fl_graph_has_gen; eauto. } rewrite H53.\n                         assert (limit_address g3 t_info3 from =\n                                 limit_address g4 t_info4 from). {\n                           unfold limit_address. f_equal. 2: assumption. f_equal.\n                           destruct H56 as [? [? _]]. rewrite H57. reflexivity. }\n                         rewrite H57.\n                         assert (next_address t_info3 to = next_address t_info4 to). {\n                           unfold next_address. f_equal. destruct H56. assumption. }\n                         rewrite H58. clear H53 H57 H58.\n                         assert (thread_info_relation t_info' t_info4) by\n                             (apply tir_trans with t_info3; assumption).\n                         assert (forward_loop\n                                   from to (Z.to_nat (depth - 1))\n                                   (sublist 0 (i + 1)\n                                            (vertex_pos_pairs g' (new_copied_v g to)))\n                                   g' g4). {\n                           eapply forward_loop_add_tail_vpp; eauto. subst n g' from.\n                           rewrite lcv_vlabel_new; assumption. }\n                         entailer!.\n                 --- Intros g3 t_info3.\n                     assert (thread_info_relation t_info t_info3) by\n                         (apply tir_trans with t_info';\n                          [split; [|split]|]; assumption).\n                     rewrite sublist_all in H46. clear Heqt.\n                     2: { rewrite Z.le_lteq. right. subst n g' from.\n                          rewrite vpp_Zlength, lcv_vlabel_new; auto. }\n                     Opaque super_compatible. forward. clear H50 H51 H52 H53.\n                     remember (upd_bunch z f_info roots (inr (new_copied_v g to)))\n                       as roots'. Exists g3 t_info3 roots'. simpl. entailer!.\n                     rewrite <- Heqroot, H21, if_true by reflexivity.\n                     replace (Z.to_nat depth) with (S (Z.to_nat (depth - 1))) by\n                         (rewrite <- Z2Nat.inj_succ; [f_equal|]; omega).\n                     constructor; [|constructor]; easy.\n                     Transparent super_compatible.\n              ** assert (depth = 0) by omega. subst depth. clear H42.\n                 deadvars!. clear Heqnv. forward.\n                 remember (Znth z (live_roots_indices f_info)) as lz.\n                 remember (vertex_address (lgraph_copy_v g v to) (new_copied_v g to))\n                          as nv.\n                 remember (cut_thread_info\n                             t_info (Z.of_nat to) (vertex_size g v) Hi Hh).\n                 Exists (lgraph_copy_v g v to) (update_thread_info_arg t lz nv H16)\n                        (upd_bunch z f_info roots (inr (new_copied_v g to))).\n                 entailer!. simpl; rewrite <- Heqroot.\n                 rewrite if_true by reflexivity; rewrite H21; easy. \n      * apply semax_if_seq. forward_if. 1: exfalso; apply H21'; reflexivity.\n        rewrite H20 in n. forward.\n        Exists g t_info roots. simpl. entailer!.\n        -- rewrite <- Heqroot, if_false by assumption.\n           split3; [|simpl root2forward; constructor |]; easy. \n        -- unfold thread_info_rep. entailer!.\n  (* p is Vtype * Z, ie located in graph *)\n  - destruct p as [v n]. destruct H0 as [? [? [? ?]]]. freeze [0; 1; 2; 4] FR.\n    localize [vertex_rep (nth_sh g (vgeneration v)) g v].\n    unfold vertex_rep, vertex_at. Intros.\n    assert_PROP (offset_val (WORD_SIZE * n) (vertex_address g v) =\n                 field_address (tarray int_or_ptr_type\n                                       (Zlength (make_fields_vals g v)))\n                               [ArraySubsc n] (vertex_address g v)). {\n      entailer!. unfold field_address. rewrite if_true; [simpl; f_equal|].\n      clear -H20 H11; rewrite <- fields_eq_length in H11.\n      unfold field_compatible in *; simpl in *; intuition.\n    }\n    assert (readable_share (nth_sh g (vgeneration v))) by\n      apply writable_readable, generation_share_writable.\n    assert (is_pointer_or_integer (Znth n (make_fields_vals g v))). {\n      pose proof (mfv_all_is_ptr_or_int g v H9 H10 H0). rewrite Forall_forall in H16.\n      apply H16, Znth_In. rewrite fields_eq_length. assumption. } forward. \n    gather_SEP\n      (data_at (nth_sh g (vgeneration v)) tuint (Z2val (make_header g v))\n               (offset_val (- WORD_SIZE) (vertex_address g v)))\n      (data_at (nth_sh g (vgeneration v))\n               (tarray int_or_ptr_type (Zlength (make_fields_vals g v)))\n               (make_fields_vals g v) (vertex_address g v)).\n    replace_SEP 0 (vertex_rep (nth_sh g (vgeneration v)) g v).\n    1: unfold vertex_rep, vertex_at; entailer!.\n    unlocalize [graph_rep g]. 1: apply graph_vertex_ramif_stable; assumption. thaw FR.\n    unfold make_fields_vals.\n    rewrite H12, Znth_map; [|rewrite make_fields_eq_length; assumption].\n    assert_PROP (valid_int_or_ptr (field2val g (Znth n (make_fields g v)))). {\n      destruct (Znth n (make_fields g v)) eqn:?; [destruct s|].\n      - unfold field2val; unfold odd_Z2val.\n        replace (2 * z + 1) with (z + z + 1) by omega.\n        entailer!. apply valid_int_or_ptr_ii1.\n      - unfold field2val, outlier_rep.\n        apply in_gcptr_outlier with (gcptr:= g0) (outlier:=outlier) (n:=n) in H0;\n          try assumption.\n        apply (in_map single_outlier_rep outlier g0) in H0.\n        replace_SEP 3 (single_outlier_rep g0). {\n          clear -H0.\n          apply (list_in_map_inv single_outlier_rep) in H0; destruct H0 as [? [? ?]].\n          rewrite H.\n          apply (in_map single_outlier_rep) in H0.\n          destruct (log_normalize.fold_right_andp\n                     (map single_outlier_rep outlier)\n                     (single_outlier_rep x) H0).\n          rewrite H1. entailer!; now apply andp_left1.\n        }\n        sep_apply (single_outlier_rep_valid_int_or_ptr g0); entailer!.\n      - unfold field2val.\n        unfold no_dangling_dst in H10.\n        apply H10 with (e:=e) in H0.\n        1: sep_apply (graph_rep_valid_int_or_ptr g (dst g e) H0); entailer!.\n        unfold get_edges; rewrite <- filter_sum_right_In_iff, <- Heqf. \n        now apply Znth_In; rewrite make_fields_eq_length. }\n    forward_call (field2val g (Znth n (make_fields g v))).\n    remember (graph_rep g * heap_rest_rep (ti_heap t_info) * outlier_rep outlier) as P.\n    pose proof (graph_and_heap_rest_data_at_ _ _ _ H7 H).\n    unfold generation_data_at_ in H18. remember (gen_start g from) as fp.\n    remember (nth_sh g from) as fsh. remember (gen_size t_info from) as gn.\n    remember (WORD_SIZE * gn)%Z as fn.\n    assert (P |-- (weak_derives P (memory_block fsh fn fp * TT) && emp) * P). {\n      apply weak_derives_strong. subst. sep_apply H18.\n      rewrite data_at__memory_block.\n      rewrite sizeof_tarray_int_or_ptr; [Intros; cancel | unfold gen_size].\n      destruct (total_space_tight_range (nth_space t_info from)). assumption. }\n    destruct (Znth n (make_fields g v)) eqn:? ; [destruct s|].\n    (* Z + GC_Pointer + EType *)\n    + (* Z *)\n      unfold field2val, odd_Z2val. apply semax_if_seq. forward_if.\n      1: exfalso; apply H20'; reflexivity.\n      forward. Exists g t_info roots. entailer!. split.\n      * easy.\n      * unfold forward_condition, thread_info_relation.\n        simpl. rewrite Heqf, H12. simpl. constructor; [constructor|easy].\n    + (* GC_Pointer *)\n      destruct g0. unfold field2val, GC_Pointer2val. apply semax_if_seq. forward_if.\n      2: exfalso; apply Int.one_not_zero; assumption.\n      forward_call (Vptr b i). 1: exact I.\n      unfold thread_info_rep; Intros.\n      (* gather_SEP 0 6 3. *)\n      gather_SEP (graph_rep g)\n                 (heap_rest_rep _) (outlier_rep _).\n      rewrite <- HeqP. destruct H5.\n      replace_SEP 0 ((weak_derives P (memory_block fsh fn fp * TT) && emp) * P) by\n          (entailer; assumption). clear H19. Intros.\n      assert (P |-- (weak_derives P (valid_pointer (Vptr b i) * TT) && emp) * P). {\n        subst; cancel; apply andp_right; [|cancel].\n        assert (HS: emp |-- TT) by entailer; sep_apply HS; clear HS.\n        apply derives_weak. assert (In (GCPtr b i) outlier) by\n            (eapply in_gcptr_outlier; eauto).\n        sep_apply (outlier_rep_valid_pointer outlier (GCPtr b i) H19).\n        simpl GC_Pointer2val. cancel. }\n      replace_SEP 1 ((weak_derives P (valid_pointer (Vptr b i) * TT) && emp) * P) by\n          (entailer; assumption). Intros. clear H19.\n      forward_call (fsh, fp, fn, (Vptr b i), P).\n      Intros vret. destruct vret. (* is_from? *)\n      * (* yes *)\n        rewrite HeqP. Intros.\n        gather_SEP (graph_rep g) (heap_rest_rep (ti_heap t_info)).\n        sep_apply H18. rewrite Heqfn in v0.\n        pose proof in_gcptr_outlier g (GCPtr b i) outlier n v H0 H6 H11 Heqf.\n        sep_apply (outlier_rep_single_rep outlier (GCPtr b i)).\n        Intros.\n        gather_SEP (data_at_ fsh (tarray int_or_ptr_type gn) fp)\n                   (single_outlier_rep (GCPtr b i)).\n        change (Vptr b i) with (GC_Pointer2val (GCPtr b i)) in v0.\n        pose proof (generation_share_writable (nth_gen g from)).\n        change (generation_sh (nth_gen g from)) with (nth_sh g from) in H22.\n        rewrite <- Heqfsh in H22. unfold generation_data_at_.\n        sep_apply (single_outlier_rep_memory_block_FF (GCPtr b i) fp gn fsh H22 v0).\n        assert_PROP False by entailer!. contradiction.\n      * (* no *)\n        apply semax_if_seq. forward_if.\n        1: exfalso; apply H19'; reflexivity.\n        forward. Exists g t_info roots. entailer!.\n        -- split3.\n           ++ unfold roots_compatible. easy. \n           ++ simpl. rewrite Heqf, H12. simpl. constructor.\n           ++ easy. \n        -- unfold thread_info_rep. entailer!.\n    + (* EType *)\n      unfold field2val. remember (dst g e) as v'.\n      assert (isptr (vertex_address g v')). { (**)\n        unfold vertex_address; unfold offset_val.\n        remember (vgeneration v') as n'.\n        assert (graph_has_v g v'). {\n          unfold no_dangling_dst in H10.\n          subst. clear -H0 H10 H11 e Heqf.\n          apply (H10 v H0). \n          unfold get_edges;\n          rewrite <- filter_sum_right_In_iff, <- Heqf; apply Znth_In.\n          now rewrite make_fields_eq_length.\n        }\n        destruct H20. rewrite <- Heqn' in H20.\n        pose proof (graph_has_gen_start_isptr g n' H20).\n        destruct (gen_start g n'); try contradiction; auto.       }\n      destruct (vertex_address g v') eqn:?; try contradiction.\n      apply semax_if_seq. forward_if.\n      2: exfalso; apply Int.one_not_zero in H21; assumption.\n      clear H21 H21'. forward_call (Vptr b i).\n      unfold thread_info_rep; Intros.\n      (* gather_SEP 0 6 3. *)\n      gather_SEP (graph_rep g)\n                 (heap_rest_rep _) (outlier_rep _).\n      rewrite <- HeqP.\n      replace_SEP 0\n                  ((weak_derives P (memory_block fsh fn fp * TT) && emp) * P) by\n          (entailer; assumption).\n      clear H19. Intros. assert (graph_has_v g v'). { (**)\n        rewrite Heqv'.\n        unfold no_dangling_dst in H10.\n        clear -H10 H0 e Heqf H11. apply (H10 v H0). \n        unfold get_edges.\n        rewrite <- filter_sum_right_In_iff.\n        rewrite <- Heqf.\n        apply Znth_In.\n        rewrite make_fields_eq_length; assumption.\n      }\n      assert (P |-- (weak_derives P (valid_pointer (Vptr b i) * TT) && emp) * P). {\n        apply weak_derives_strong. subst.\n        remember (dst g e) as v'.\n        sep_apply (graph_rep_vertex_rep g v' H19).\n        Intros shh. unfold vertex_rep, vertex_at. rewrite Heqv0.\n        sep_apply (data_at_valid_ptr\n                     shh (tarray int_or_ptr_type (Zlength (make_fields_vals g v')))\n                     (make_fields_vals g v') (Vptr b i)).\n        - apply readable_nonidentity, writable_readable_share; assumption.\n        - simpl. rewrite fields_eq_length.\n          pose proof (proj1 (raw_fields_range (vlabel g v'))). rewrite Z.max_r; omega.\n        - cancel.\n      }\n      replace_SEP 1 (weak_derives P (valid_pointer (Vptr b i) * TT) && emp * P)\n        by entailer!. clear H21. Intros.\n      forward_call (fsh, fp, fn, (Vptr b i), P).\n      (* is_from *)\n      Intros vv. rewrite HeqP.\n      sep_apply (graph_and_heap_rest_v_in_range_iff _ _ _ _ H H7 H19).\n      Intros. rewrite <- Heqfp, <- Heqgn, <- Heqfn, Heqv0 in H21. destruct vv.\n      * (* yes, is_from *)\n        rewrite H21 in v0. clear H21. apply semax_if_seq. forward_if.\n        2: exfalso; inversion H21.\n        deadvars!. freeze [1; 2; 3; 4; 5; 6] FR.\n        clear H21 H21'. localize [vertex_rep (nth_sh g (vgeneration v')) g v'].\n        unfold vertex_rep, vertex_at. Intros. rewrite v0.\n        assert (readable_share (nth_sh g from)) by\n            (unfold nth_sh; apply writable_readable, generation_share_writable).\n        rewrite <- Heqv0.\n        sep_apply (data_at_minus1_address\n                     (nth_sh g from) (Z2val (make_header g v')) (vertex_address g v')).\n        Intros. forward. clear H22.\n        gather_SEP (data_at (nth_sh g from) tuint (Z2val (make_header g v'))\n            (offset_val (- WORD_SIZE) (vertex_address g v')))\n          (data_at (nth_sh g from)\n            (tarray int_or_ptr_type (Zlength (make_fields_vals g v')))\n            (make_fields_vals g v') (vertex_address g v')).\n\n        replace_SEP 0 (vertex_rep (nth_sh g (vgeneration v')) g v') by\n            (unfold vertex_rep, vertex_at; entailer!).\n        unlocalize [graph_rep g]. 1: apply (graph_vertex_ramif_stable _ _ H19).\n        apply semax_if_seq. forward_if; rewrite make_header_int_rep_mark_iff in H22.\n        -- (* yes, already forwarded *)\n          deadvars!.\n          localize [vertex_rep (nth_sh g (vgeneration v')) g v'].\n          change (Tpointer tvoid {| attr_volatile := false;\n                                    attr_alignas := Some 2%N |}) with int_or_ptr_type.\n          rewrite v0. unfold vertex_rep, vertex_at. Intros.\n          unfold make_fields_vals at 2. rewrite H22.\n          assert (0 <= 0 < Zlength (make_fields_vals g v')). {\n             split. 1: omega. rewrite fields_eq_length.\n             apply (proj1 (raw_fields_range (vlabel g v'))).\n          }\n          assert (is_pointer_or_integer\n                    (vertex_address g (copied_vertex (vlabel g v')))). {\n            apply isptr_is_pointer_or_integer. unfold vertex_address.\n            rewrite isptr_offset_val.\n            apply graph_has_gen_start_isptr, H9; assumption. }\n          forward. rewrite Znth_0_cons.\n          gather_SEP (data_at (nth_sh g from) tuint (Z2val (make_header g v'))\n            (offset_val (- WORD_SIZE) (vertex_address g v')))\n          (data_at (nth_sh g from)\n            (tarray int_or_ptr_type (Zlength (make_fields_vals g v')))\n            (vertex_address g (copied_vertex (vlabel g v'))\n             :: tl (map (field2val g) (make_fields g v'))) \n            (vertex_address g v')).\n          replace_SEP 0 (vertex_rep (nth_sh g (vgeneration v')) g v'). {\n            unfold vertex_rep, vertex_at. unfold make_fields_vals at 3.\n            rewrite H22. entailer!. }\n          unlocalize [graph_rep g]. 1: apply (graph_vertex_ramif_stable _ _ H19).\n          localize [vertex_rep (nth_sh g (vgeneration v)) g v].\n          unfold vertex_rep, vertex_at. Intros.\n          assert (writable_share (nth_sh g (vgeneration v))) by\n               (unfold nth_sh; apply generation_share_writable).\n          forward.\n          sep_apply (field_at_data_at_cancel\n                       (nth_sh g (vgeneration v))\n                       (tarray int_or_ptr_type (Zlength (make_fields_vals g v)))\n                       (upd_Znth n (make_fields_vals g v)\n                       (vertex_address g (copied_vertex (vlabel g v'))))\n                       (vertex_address g v)).\n          (* gather_SEP 1 0. *)\n          gather_SEP (data_at _ tuint _ _ ) (data_at _ _ _ _).\n          remember (copied_vertex (vlabel g v')).\n          remember (labeledgraph_gen_dst g e v1) as g'.\n          replace_SEP 0 (vertex_rep (nth_sh g' (vgeneration v)) g' v).\n          1: { unfold vertex_rep, vertex_at.\n               replace (nth_sh g' (vgeneration v)) with\n                   (nth_sh g (vgeneration v)) by (subst g'; reflexivity).\n               replace (Zlength (make_fields_vals g' v)) with\n                   (Zlength (make_fields_vals g v)) by\n                   (subst g'; repeat rewrite fields_eq_length;\n                    apply lgd_raw_fld_length_eq).\n               rewrite (lgd_mfv_change_in_one_spot g v e v1 n);\n                 [|rewrite make_fields_eq_length| | ]; try assumption.\n               entailer!. }\n          subst g'; subst v1.\n          unlocalize [graph_rep (labeledgraph_gen_dst g e\n                                                      (copied_vertex (vlabel g v')))].\n          1: apply (graph_vertex_lgd_ramif g v e (copied_vertex (vlabel g v')) n);\n            try (rewrite make_fields_eq_length); assumption.\n          forward.\n          Exists (labeledgraph_gen_dst g e (copied_vertex (vlabel g (dst g e))))\n                 t_info roots.\n          entailer!.\n          2: unfold thread_info_rep; thaw FR; entailer!.\n          pose proof (lgd_no_dangling_dst_copied_vert g e (dst g e) H9 H19 H22 H10).\n          split; [|split; [|split; [|split]]]; try reflexivity.\n          ++ now constructor.\n          ++ simpl forward_p2forward_t.\n             rewrite H12, Heqf. simpl. now constructor.\n          ++ now constructor.\n          ++ easy.\n        -- (* not yet forwarded *)\n          forward. thaw FR.  freeze [0; 1; 2; 3; 4; 5] FR.\n           apply not_true_is_false in H22. rewrite make_header_Wosize by assumption.\n           assert (0 <= Z.of_nat to < 12). {\n             clear -H H8. destruct H as [_ [_ ?]]. red in H8.\n             pose proof (spaces_size (ti_heap t_info)).\n             rewrite Zlength_correct in H0. rep_omega. } unfold heap_struct_rep.\n           destruct (gt_gs_compatible _ _ H _ H8) as [? [? ?]].\n           rewrite nth_space_Znth in *.\n           remember (Znth (Z.of_nat to) (spaces (ti_heap t_info))) as sp_to.\n           assert (isptr (space_start sp_to)) by (rewrite <- H24; apply start_isptr).\n           remember (map space_tri (spaces (ti_heap t_info))).\n           assert (@Znth (val * (val * val)) (Vundef, (Vundef, Vundef))\n                         (Z.of_nat to) l = space_tri sp_to). {\n             subst l sp_to. rewrite Znth_map by (rewrite spaces_size; rep_omega).\n             reflexivity. }\n           forward; rewrite H28; unfold space_tri. 1: entailer!.\n           forward. simpl sem_binary_operation'.\n           rewrite sapi_ptr_val; [| assumption | rep_omega].\n           Opaque Znth.  forward. Transparent Znth.\n           assert (Hr: Int.min_signed <= Zlength (raw_fields (vlabel g v')) <=\n                       Int.max_signed). {\n             pose proof (raw_fields_range (vlabel g v')). destruct H29. split.\n             - rep_omega.\n             - transitivity (two_power_nat 22). 1: omega.\n               compute; intro s; inversion s. }\n           rewrite sapi_ptr_val; [|easy|easy].\n           rewrite H28. unfold space_tri.\n           rewrite <- Z.add_assoc.\n           replace (1 + Zlength (raw_fields (vlabel g v'))) with (vertex_size g v') by\n               (unfold vertex_size; omega). thaw FR. freeze [0; 2; 3; 4; 5; 6] FR.\n           assert (Hi : 0 <= Z.of_nat to < Zlength (spaces (ti_heap t_info))) by\n               (rewrite spaces_size; rep_omega).\n           assert (Hh: has_space (Znth (Z.of_nat to) (spaces (ti_heap t_info)))\n                                 (vertex_size g v')). {\n             red. split. 1: pose proof (svs_gt_one g v'); omega.\n             transitivity (unmarked_gen_size g (vgeneration v')).\n             - apply single_unmarked_le; assumption.\n             - red in H1. unfold rest_gen_size in H1. subst from.\n               rewrite nth_space_Znth in H1. assumption. }\n           assert (Hn: space_start (Znth (Z.of_nat to) (spaces (ti_heap t_info))) <>\n                       nullval). {\n             rewrite <- Heqsp_to. destruct (space_start sp_to); try contradiction.\n             intro Hn. inversion Hn. }\n           rewrite (heap_rest_rep_cut\n                      (ti_heap t_info) (Z.of_nat to) (vertex_size g v') Hi Hh Hn).\n           rewrite <- Heqsp_to. thaw FR.\n           (* gather_SEP 4 5 7. *)\n           gather_SEP\n             (data_at sh thread_info_type _ ti)\n             (data_at sh heap_type _ _) (heap_rest_rep _).\n           replace_SEP 0 (thread_info_rep\n                            sh (cut_thread_info t_info _ _ Hi Hh) ti). {\n             entailer. unfold thread_info_rep. simpl ti_heap. simpl ti_heap_p. cancel.\n             simpl spaces. rewrite <- upd_Znth_map. unfold cut_space.\n             unfold space_tri at 3. simpl. unfold heap_struct_rep. cancel. }\n           sep_apply (graph_vertex_ramif_stable _ _ H19). Intros.\n           freeze [1; 2; 3; 4; 5] FR. deadvars!. rewrite v0.\n           remember (nth_sh g from) as shv.\n           assert (writable_share (space_sh sp_to)) by\n               (rewrite <- H25; apply generation_share_writable).\n           remember (space_sh sp_to) as sht.\n           rewrite (data_at__tarray_value _ _ 1). 2: unfold vertex_size; rep_omega.\n           Intros.\n           remember (offset_val (WORD_SIZE * used_space sp_to) (space_start sp_to)).\n           rewrite (data_at__int_or_ptr_tuint sht v1).\n           assert_PROP\n             (force_val (sem_add_ptr_int\n                           tuint Signed\n                           (offset_val (WORD_SIZE * (used_space sp_to + 1))\n                                       (space_start sp_to))\n                           (eval_unop Oneg tint (vint 1))) =\n              field_address tuint [] v1). {\n             subst v1. rewrite WORD_SIZE_eq. entailer!. unfold field_address.\n             simpl. rewrite neg_repr. rewrite sem_add_pi_ptr_special'; auto.\n             rewrite if_true by assumption. simpl. rewrite !offset_offset_val.\n             f_equal. omega. }\n           forward. sep_apply (field_at_data_at_cancel\n                                 sht tuint (Z2val (make_header g v')) v1). clear H30.\n           subst v1. rewrite offset_offset_val.\n           replace (vertex_size g v' - 1) with (Zlength (raw_fields (vlabel g v')))\n             by (unfold vertex_size; omega).\n           replace (WORD_SIZE * used_space sp_to + WORD_SIZE * 1) with\n               (WORD_SIZE * (used_space sp_to + 1))%Z by rep_omega.\n           remember (offset_val (WORD_SIZE * (used_space sp_to + 1))\n                                (space_start sp_to)) as nv.\n           thaw FR. freeze [0; 1; 2; 3; 4; 5] FR. rename i into j. deadvars!.\n           remember (Zlength (raw_fields (vlabel g v'))) as n'.\n           assert (isptr nv) by (subst nv; rewrite isptr_offset_val; assumption).\n           remember (field_address heap_type\n                                   [StructField _next; ArraySubsc (Z.of_nat to);\n                                    StructField _spaces] (ti_heap_p t_info)) as n_addr.\n           forward_for_simple_bound\n             n'\n             (EX i: Z,\n              PROP ( )\n              LOCAL (temp _new nv;\n                     temp _sz (vint n');\n                     temp _v (vertex_address g v');\n                     temp _from_start fp;\n                     temp _from_limit (offset_val fn fp);\n                     temp _next n_addr;\n                     temp _p (offset_val (WORD_SIZE * n) (vertex_address g v));\n                     temp _depth (vint depth))\n              SEP (vertex_rep shv g v';\n                   data_at sht (tarray int_or_ptr_type i)\n                           (sublist 0 i (make_fields_vals g v')) nv;\n                   data_at_ sht (tarray int_or_ptr_type (n' - i))\n                            (offset_val (WORD_SIZE * i) nv); FRZL FR))%assert.\n           ++ rewrite sublist_nil. replace (n' - 0) with n' by omega.\n              replace (WORD_SIZE * 0)%Z with 0 by omega.\n              rewrite isptr_offset_val_zero by assumption.\n              rewrite data_at_zero_array_eq;\n                [|reflexivity | assumption | reflexivity]. entailer!.\n           ++ unfold vertex_rep, vertex_at. Intros.\n              rewrite fields_eq_length, <- Heqn'. forward.\n              ** entailer!. pose proof (mfv_all_is_ptr_or_int _ _ H9 H10 H19).\n                 rewrite Forall_forall in H46. apply H46, Znth_In.\n                 rewrite fields_eq_length. assumption.\n              ** rewrite (data_at__tarray_value _ _ 1) by omega. Intros.\n                 rewrite data_at__singleton_array_eq.\n                 assert_PROP\n                   (field_compatible int_or_ptr_type []\n                                     (offset_val (WORD_SIZE * i) nv)) by\n                     (sep_apply (data_at__local_facts\n                                   sht int_or_ptr_type\n                                   (offset_val (WORD_SIZE * i) nv)); entailer!).\n                 assert_PROP\n                   (force_val (sem_add_ptr_int int_or_ptr_type\n                                               Signed nv (vint i)) =\n                    field_address int_or_ptr_type []\n                                  (offset_val (WORD_SIZE * i) nv)). {\n                   unfold field_address. rewrite if_true by assumption.\n                   clear. entailer!. }\n                 gather_SEP\n                 (data_at shv tuint (Z2val (make_header g v'))\n                          (offset_val (- WORD_SIZE) (vertex_address g v'))) (data_at shv (tarray int_or_ptr_type n') (make_fields_vals g v')\n                                                                                     (vertex_address g v')).\n                 replace_SEP 0 (vertex_rep shv g v') by\n                     (unfold vertex_rep, vertex_at;\n                      rewrite fields_eq_length; entailer!). forward.\n                 rewrite offset_offset_val.\n                 replace (n' - i - 1) with (n' - (i + 1)) by omega.\n                 replace (WORD_SIZE * i + WORD_SIZE * 1) with\n                     (WORD_SIZE * (i + 1))%Z by rep_omega.\n                 gather_SEP 1 2.\n                 (* gather_SEP *)\n                 (*   (data_at sht (tarray int_or_ptr_type i) (sublist 0 i (make_fields_vals g v')) *)\n                 (*            nv) *)\n                 (*   (field_at sht int_or_ptr_type [] (Znth i (make_fields_vals g v')) *)\n                 (*             (offset_val (WORD_SIZE * i) nv)). *)\n                 (* no matching... *)\n                 rewrite data_at_mfs_eq;\n                                   [|assumption|subst n'; assumption].\n                 entailer!.\n           ++ thaw FR. rewrite v0, <- Heqshv.\n              gather_SEP 0 4.\n              (* gather_SEP (vertex_rep shv g v') (vertex_rep shv g v' -* graph_rep g). *)\n              (* no matching clauses *)\n              replace_SEP 0 (graph_rep g) by (entailer!; apply wand_frame_elim).\n              rewrite sublist_all by (rewrite fields_eq_length; omega).\n              replace_SEP 2 emp. {\n                replace (n' - n') with 0 by omega. clear. entailer.\n                apply data_at__value_0_size. }\n              assert (nv = vertex_address g (new_copied_v g to)). {\n                subst nv. unfold vertex_address. unfold new_copied_v. simpl. f_equal.\n                - unfold vertex_offset. simpl. rewrite H26. reflexivity.\n                - unfold gen_start. rewrite if_true by assumption.\n                  rewrite H24. reflexivity. }\n              (* gather_SEP 1 2 3. *)\n              gather_SEP\n              (data_at sht _ _ nv)\n              (emp) (data_at sht tuint _ _).\n              replace_SEP\n                0 (vertex_at (nth_sh g to)\n                             (vertex_address g (new_copied_v g to))\n                             (make_header g v') (make_fields_vals g v')). {\n                normalize. rewrite <- H25.\n                change (generation_sh (nth_gen g to)) with (nth_sh g to).\n                rewrite <- fields_eq_length in Heqn'.\n                replace (offset_val (WORD_SIZE * used_space sp_to) (space_start sp_to))\n                  with (offset_val (- WORD_SIZE) nv) by\n                    (rewrite Heqnv; rewrite offset_offset_val; f_equal; rep_omega).\n                rewrite <- H31. unfold vertex_at; entailer!. }\n              gather_SEP (vertex_at (nth_sh g to) (vertex_address g (new_copied_v g to))\n            (make_header g v') (make_fields_vals g v')) (graph_rep g).\n              rewrite (copied_v_derives_new_g g v' to) by assumption.\n              freeze [1; 2; 3; 4] FR. remember (lgraph_add_copied_v g v' to) as g'.\n              assert (vertex_address g' v' = vertex_address g v') by\n                  (subst g'; apply lacv_vertex_address_old; assumption).\n              assert (vertex_address g' (new_copied_v g to) =\n                      vertex_address g (new_copied_v g to)) by\n                  (subst g'; apply lacv_vertex_address_new; assumption).\n              rewrite <- H32. rewrite <- H33 in H31.\n              assert (writable_share (nth_sh g' (vgeneration v'))) by\n                  (unfold nth_sh; apply generation_share_writable).\n              assert (graph_has_v g' (new_copied_v g to)) by\n                  (subst g'; apply lacv_graph_has_v_new; assumption).\n              sep_apply (graph_rep_valid_int_or_ptr _ _ H35). Intros.\n              rewrite <- H31 in H36. assert (graph_has_v g' v') by\n                  (subst g'; apply lacv_graph_has_v_old; assumption).\n              remember (nth_sh g' (vgeneration v')) as sh'.\n              sep_apply (graph_vertex_lmc_ramif g' v' (new_copied_v g to) H37).\n              rewrite <- Heqsh'. Intros. freeze [1; 2] FR1.\n              unfold vertex_rep, vertex_at. Intros.\n              sep_apply (data_at_minus1_address\n                           sh' (Z2val (make_header g' v')) (vertex_address g' v')).\n              Intros. forward. clear H38.\n              sep_apply (field_at_data_at_cancel\n                           sh' tuint (vint 0)\n                           (offset_val (- WORD_SIZE) (vertex_address g' v'))).\n              forward_call (nv). remember (make_fields_vals g' v') as l'.\n              assert (0 < Zlength l'). {\n                subst l'. rewrite fields_eq_length.\n                apply (proj1 (raw_fields_range (vlabel g' v'))). }\n              rewrite data_at_tarray_value_split_1 by assumption. Intros.\n              assert_PROP (force_val (sem_add_ptr_int int_or_ptr_type Signed\n                                                      (vertex_address g' v') (vint 0))\n                           =\n                           field_address int_or_ptr_type [] (vertex_address g' v')). {\n                clear. entailer!. unfold field_address. rewrite if_true by assumption.\n                simpl. rewrite isptr_offset_val_zero. 1: reflexivity.\n                destruct H7. assumption. }\n              forward. clear H39.\n              sep_apply (field_at_data_at_cancel\n                           sh' int_or_ptr_type nv (vertex_address g' v')).\n              (* gather_SEP 1 0 3. *)\n              gather_SEP\n                (data_at sh' tuint (vint 0) _)\n                (data_at sh' int_or_ptr_type nv _)\n                (data_at sh' (tarray int_or_ptr_type _) _ _).\n              rewrite H31. subst l'.\n              rewrite <- lmc_vertex_rep_eq.\n              thaw FR1.\n              gather_SEP 0 1.\n           (*    gather_SEP *)\n           (*      (vertex_rep sh' (lgraph_mark_copied g' v' (new_copied_v g to)) v') *)\n           (*      ((vertex_rep sh' (lgraph_mark_copied g' v' (new_copied_v g to)) v' -* *)\n              (* graph_rep (lgraph_mark_copied g' v' (new_copied_v g to)))). *)\n              (* no matching... *)\n              sep_apply\n                (wand_frame_elim\n                   (vertex_rep sh' (lgraph_mark_copied g' v' (new_copied_v g to)) v')\n                   (graph_rep (lgraph_mark_copied g' v' (new_copied_v g to)))).\n              rewrite <- (lmc_vertex_address g' v' (new_copied_v g to)) in *. subst g'.\n              change (lgraph_mark_copied\n                        (lgraph_add_copied_v g v' to) v' (new_copied_v g to))\n                with (lgraph_copy_v g v' to) in *.\n              remember (lgraph_copy_v g v' to) as g'.\n\n              assert (vertex_address g' v' = vertex_address g v') by\n              (subst g'; apply lcv_vertex_address_old; assumption).\n              assert (vertex_address g' (new_copied_v g to) =\n                      vertex_address g (new_copied_v g to)) by\n                  (subst g'; apply lcv_vertex_address_new; assumption).\n              assert (writable_share (nth_sh g' (vgeneration v'))) by\n                  (unfold nth_sh; apply generation_share_writable).\n              assert (graph_has_v g' (new_copied_v g to)) by\n                  (subst g'; apply lcv_graph_has_v_new; assumption).\n              forward_call (nv).\n              rewrite <- H31 in *.\n              rewrite lacv_vertex_address;\n                [|apply graph_has_v_in_closure|]; try assumption.\n              rewrite <- H32.\n              rewrite <- (lcv_vertex_address g v' to v);\n                try rewrite <- (lcv_vertex_address g v' to v) in H14;\n                try apply graph_has_v_in_closure; try assumption.\n              rewrite (lcv_mfv_Zlen_eq g v v' to H8 H0) in H14. rewrite <- Heqg' in *.\n              remember (nth_sh g' (vgeneration v)) as shh.\n              remember (make_fields_vals g' v) as mfv.\n              remember (new_copied_v g to).\n              remember (labeledgraph_gen_dst g' e v1) as g1.\n              assert (0 <= n < Zlength (make_fields_vals g' v)) by\n                  (subst g'; rewrite fields_eq_length, <- lcv_raw_fields; assumption).\n              assert (Znth n (make_fields g' v) = inr e) by\n                  (subst g'; unfold make_fields in *;\n                   rewrite <- lcv_raw_fields; assumption).\n              assert (0 <= n < Zlength (make_fields g' v)) by\n                  (rewrite make_fields_eq_length;\n                   rewrite fields_eq_length in H43; assumption).\n              assert (graph_has_v g' v) by\n                  (subst g'; apply lcv_graph_has_v_old; assumption).\n              assert (v <> v') by\n                  (intro; subst v; clear -v0 H13; omega).\n              assert (raw_mark (vlabel g' v) = false) by\n                (subst g'; rewrite <- lcv_raw_mark; assumption).\n              assert (writable_share shh) by\n                  (rewrite Heqshh; unfold nth_sh; apply generation_share_writable).\n              localize [vertex_rep (nth_sh g' (vgeneration v)) g' v].\n              unfold vertex_rep, vertex_at. Intros.\n              rewrite Heqmfv in *; rewrite <- Heqshh.\n              forward.\n              rewrite H31.\n              sep_apply (field_at_data_at_cancel\n                           shh\n                           (tarray int_or_ptr_type (Zlength (make_fields_vals g' v)))\n                           (upd_Znth n (make_fields_vals g' v) (vertex_address g' v1))\n                           (vertex_address g' v)).\n              (* gather_SEP 1 0. *)\n              gather_SEP\n                (data_at shh tuint _ _) (data_at shh _ _ _).\n              replace_SEP 0 (vertex_rep (nth_sh g1 (vgeneration v)) g1 v).\n              1: { unfold vertex_rep, vertex_at.\n                   replace (nth_sh g1 (vgeneration v)) with shh by\n                       (subst shh g1; reflexivity).\n                   replace (Zlength (make_fields_vals g1 v)) with\n                       (Zlength (make_fields_vals g' v)) by\n                       (subst g1; repeat rewrite fields_eq_length;\n                        apply lgd_raw_fld_length_eq).\n                   rewrite (lgd_mfv_change_in_one_spot g' v e v1 n);\n                     try assumption. entailer!. }\n              subst g1; subst v1.\n              unlocalize [graph_rep (labeledgraph_gen_dst g' e (new_copied_v g to))].\n              1: apply (graph_vertex_lgd_ramif g' v e (new_copied_v g to) n);\n                assumption.\n              remember (new_copied_v g to).\n              remember (labeledgraph_gen_dst g' e v1) as g1.\n              thaw FR.\n              remember (cut_thread_info t_info (Z.of_nat to) (vertex_size g v') Hi Hh)\n                as t_info'.\n              unfold thread_info_rep. Intros.\n              assert (0 <= 0 < Zlength (ti_args t_info')) by\n                  (rewrite arg_size; rep_omega).\n              (* gather_SEP 1 2 3. *)\n              gather_SEP\n                (data_at sh thread_info_type _ _)\n                (heap_struct_rep sh _ _) (heap_rest_rep _).\n              replace_SEP 0 (thread_info_rep sh t_info' ti).\n              { unfold thread_info_rep. simpl heap_head. simpl ti_heap_p.\n                simpl ti_args. simpl ti_heap. entailer!. }\n              rewrite H31 in H33.\n                assert (forward_relation from to 0 (inr e) g g1) by\n                    (subst g1 g' v1 v'; constructor; assumption).\n                assert (In e (get_edges g v)). { (**)\n                  unfold get_edges.\n                  rewrite <- filter_sum_right_In_iff.\n                  rewrite <- Heqf.\n                  apply (Znth_In n (make_fields g v)).\n                  rewrite make_fields_eq_length. assumption.\n                }\n                assert (forward_condition g1 t_info' from to). {\n                  subst g1 g' t_info' from v'.\n                  apply lgd_forward_condition; try assumption.\n                  apply lcv_forward_condition_unchanged; try assumption.\n                  red. intuition. }\n                remember roots as roots'.\n                assert (super_compatible (g1, t_info', roots') f_info outlier). {\n\n                  subst g1 g' t_info' roots'.\n                  apply lgd_super_compatible, lcv_super_compatible_unchanged;\n                    try assumption.\n                  red; intuition. }\n              assert (thread_info_relation t_info t_info'). {\n                subst t_info'. split; [|split]; [reflexivity| |]; intros m.\n                - rewrite cti_gen_size. reflexivity.\n                - rewrite cti_space_start. reflexivity. }\n                apply semax_if_seq. forward_if.\n              ** destruct H55 as [? [? ?]]. replace fp with (gen_start g1 from) by\n                     (subst fp g1 g'; apply lcv_gen_start; assumption).\n                 replace (offset_val fn (gen_start g1 from)) with\n                     (limit_address g1 t_info' from) by\n                     (subst fn gn; rewrite H57; reflexivity).\n                 replace n_addr with (next_address t_info' to) by\n                     (subst n_addr; rewrite H55; reflexivity).\n                 forward_for_simple_bound\n                   n'\n                   (EX i: Z, EX g3: LGraph, EX t_info3: thread_info,\n                    PROP (super_compatible (g3, t_info3, roots') f_info outlier;\n                          forward_loop\n                            from to (Z.to_nat (depth - 1))\n                            (sublist 0 i (vertex_pos_pairs g1 (new_copied_v g to)))\n                            g1 g3;\n                          forward_condition g3 t_info3 from to;\n                          thread_info_relation t_info' t_info3)\n                    LOCAL (temp _new nv;\n                           temp _sz (vint n');\n                           temp _from_start (gen_start g3 from);\n                           temp _from_limit (limit_address g3 t_info3 from);\n                           temp _next (next_address t_info3 to);\n                           temp _depth (vint depth))\n                    SEP (all_string_constants rsh gv;\n                         fun_info_rep rsh f_info fi;\n                         outlier_rep outlier;\n                         graph_rep g3;\n                         thread_info_rep sh t_info3 ti))%assert.\n                 --- Exists g1 t_info'. autorewrite with sublist.\n                     assert (forward_loop from to (Z.to_nat (depth - 1)) [] g1 g1) by\n                         constructor. unfold thread_info_relation.\n                     destruct H54 as [? [? [? ?]]].\n                     entailer!. easy.\n                 --- change (Tpointer tvoid {| attr_volatile := false;\n                                               attr_alignas := Some 2%N |})\n                       with (int_or_ptr_type). Intros.\n                     assert (graph_has_gen g1 to) by\n                         (rewrite Heqg1, lgd_graph_has_gen; subst g';\n                          rewrite <- lcv_graph_has_gen; assumption).\n                     assert (graph_has_v g1 (new_copied_v g to)) by\n                       (subst g1; rewrite <- lgd_graph_has_v;\n                       rewrite Heqg'; apply lcv_graph_has_v_new; assumption).\n                     forward_call (rsh, sh, gv, fi, ti, g3, t_info3, f_info, roots',\n                                   outlier, from, to, depth - 1,\n                                   (@inr Z _ (new_copied_v g to, i))).\n                     +++ simpl. apply prop_right. rewrite sub_repr.\n                         do 3 split; [|easy].\n                         f_equal. rewrite H31. rewrite sem_add_pi_ptr_special.\n                         *** simpl. f_equal.\n                             rewrite <- (lgd_vertex_address_eq g' e v1), <- Heqg1.\n                             subst v1. apply (fl_vertex_address _ _ _ _ _ _ H64 H61).\n                             apply graph_has_v_in_closure; assumption.\n                         *** rewrite <- H31. assumption.\n                         *** subst n'. clear -H59 Hr. rep_omega.\n                     +++ do 3 (split; [assumption |]). split.\n                         *** simpl. split; [|split].\n                             ---- destruct H53 as [_ [_ [? _]]].\n                                  apply (fl_graph_has_v _ _ _ _ _ _ H64 H61 _ H65).\n                             ---- erewrite <- fl_raw_fields; eauto. subst g1.\n                                  unfold lgraph_copy_v. subst n'.\n                                  rewrite <- lgd_raw_fld_length_eq.\n                                  subst g'. rewrite lcv_vlabel_new.\n                                  assumption. rewrite v0. omega.\n                             ---- erewrite <- fl_raw_mark; eauto. subst g1 from.\n                                  rewrite <- lgd_raw_mark_eq. subst g'.\n                                  rewrite lcv_vlabel_new; try assumption.\n                                  split; try assumption. omega.\n                         *** split; [assumption|]. split; [omega | assumption].\n                     +++ Intros vret. destruct vret as [[g4 t_info4] roots4].\n                         simpl fst in *. simpl snd in *. Exists g4 t_info4.\n                         simpl in H67. subst roots4.\n                         assert (gen_start g3 from = gen_start g4 from). {\n                           eapply fr_gen_start; eauto.\n                           erewrite <- fl_graph_has_gen; eauto. } rewrite H67.\n                         assert (limit_address g3 t_info3 from =\n                                 limit_address g4 t_info4 from). {\n                           unfold limit_address. f_equal. 2: assumption. f_equal.\n                           destruct H70 as [? [? _]]. rewrite H71. reflexivity. }\n                         rewrite H71.\n                         assert (next_address t_info3 to = next_address t_info4 to). {\n                           unfold next_address. f_equal. destruct H70. assumption. }\n                         rewrite H72. clear H67 H71 H72.\n                         assert (thread_info_relation t_info' t_info4) by\n                             (apply tir_trans with t_info3; assumption).\n                         assert (forward_loop\n                                   from to (Z.to_nat (depth - 1))\n                                   (sublist 0 (i + 1)\n                                            (vertex_pos_pairs g1 (new_copied_v g to)))\n                                   g1 g4). {\n                           eapply forward_loop_add_tail_vpp; eauto. subst n' g1 from.\n                           rewrite <- lgd_raw_fld_length_eq. subst g'.\n                           rewrite lcv_vlabel_new; assumption. }\n                         entailer!.\n                 --- Intros g3 t_info3.\n                     assert (thread_info_relation t_info t_info3) by\n                         (apply tir_trans with t_info';\n                          [split; [| split]|]; assumption).\n                     rewrite sublist_all in H60.\n                     2: { rewrite Z.le_lteq. right. subst n' g1 from.\n                          rewrite vpp_Zlength,  <- lgd_raw_fld_length_eq.\n                          subst g'; rewrite lcv_vlabel_new; auto. }\n                     Opaque super_compatible. forward. clear H64 H65 H66 H67.\n                     simpl.\n                     Exists g3 t_info3 roots. simpl. entailer!.\n                     replace (Z.to_nat depth) with (S (Z.to_nat (depth - 1))) by\n                         (rewrite <- Z2Nat.inj_succ; [f_equal|]; omega).\n                     rewrite Heqf, H12. simpl.\n                     constructor; [reflexivity | assumption..].\n                     Transparent super_compatible.\n              ** assert (depth = 0) by omega. subst depth. clear H56.\n                 deadvars!. clear Heqnv. forward.\n                 simpl.\n                 remember (cut_thread_info t_info (Z.of_nat to)\n                             (vertex_size g (dst g e)) Hi Hh) as t_info'.\n              remember (lgraph_copy_v g (dst g e) to) as g'.\n\n              remember (new_copied_v g to).\n              remember (labeledgraph_gen_dst g' e v0) as g1.\n              Exists g1 t_info' roots.\n              rewrite Heqf.\n              simpl field2forward. rewrite H12. simpl. entailer!.\n      * apply semax_if_seq. forward_if. 1: exfalso; apply H22'; reflexivity.\n        rewrite H21 in n0. forward.\n        simpl.\n        Exists g t_info roots. simpl. rewrite H12. entailer!.\n        -- rewrite Heqf. split; [constructor; assumption |\n                                 split; [hnf; intuition | apply tir_id]].\n        -- unfold thread_info_rep. entailer!.\nQed.\n", "meta": {"author": "johndoe20190406", "repo": "RamifyCoq", "sha": "72fb538b40ee8ea641e4bf5fe6cd232756d0929c", "save_path": "github-repos/coq/johndoe20190406-RamifyCoq", "path": "github-repos/coq/johndoe20190406-RamifyCoq/RamifyCoq-72fb538b40ee8ea641e4bf5fe6cd232756d0929c/CertiGC/verif_forward.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136564, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.20441217852006424}}
{"text": "From program_logic Require Export language.\nFrom prelude Require Export strings.\nFrom prelude Require Import gmap.\n\nModule heap_lang.\nOpen Scope Z_scope.\n\n(** Expressions and vals. *)\nDefinition loc := positive. (* Really, any countable type. *)\n\nInductive base_lit : Set :=\n  | LitInt (n : Z) | LitBool (b : bool) | LitUnit.\nInductive un_op : Set :=\n  | NegOp | MinusUnOp.\nInductive bin_op : Set :=\n  | PlusOp | MinusOp | LeOp | LtOp | EqOp.\n\nInductive binder := BAnon | BNamed : string → binder.\n\nDefinition cons_binder (mx : binder) (X : list string) : list string :=\n  match mx with BAnon => X | BNamed x => x :: X end.\nInfix \":b:\" := cons_binder (at level 60, right associativity).\nDelimit Scope binder_scope with bind.\nBind Scope binder_scope with binder.\nInstance binder_dec_eq (x1 x2 : binder) : Decision (x1 = x2).\nProof. solve_decision. Defined.\n\nInstance set_unfold_cons_binder x mx X P :\n  SetUnfold (x ∈ X) P → SetUnfold (x ∈ mx :b: X) (BNamed x = mx ∨ P).\nProof.\n  constructor. rewrite -(set_unfold (x ∈ X) P).\n  destruct mx; rewrite /= ?elem_of_cons; naive_solver.\nQed.\n\n(** A typeclass for whether a variable is bound in a given\n   context. Making this a typeclass means we can use tpeclass search\n   to program solving these constraints, so this becomes extensible.\n   Also, since typeclass search runs *after* unification, Coq has already\n   inferred the X for us; if we were to go for embedded proof terms ot\n   tactics, Coq would do things in the wrong order. *)\nClass VarBound (x : string) (X : list string) :=\n  var_bound : bool_decide (x ∈ X).\n(* There is no need to restrict this hint to terms without evars, [vm_compute]\nwill fail in case evars are arround. *)\nHint Extern 0 (VarBound _ _) => vm_compute; exact I : typeclass_instances. \n\nInstance var_bound_proof_irrel x X : ProofIrrel (VarBound x X).\nProof. rewrite /VarBound. apply _. Qed.\nInstance set_unfold_var_bound x X P :\n  SetUnfold (x ∈ X) P → SetUnfold (VarBound x X) P.\nProof.\n  constructor. by rewrite /VarBound bool_decide_spec (set_unfold (x ∈ X) P).\nQed.\n\nInductive expr (X : list string) :=\n  (* Base lambda calculus *)\n      (* Var is the only place where the terms contain a proof. The fact that they\n       contain a proof at all is suboptimal, since this means two seeminlgy\n       convertible terms could differ in their proofs. However, this also has\n       some advantages:\n       * We can make the [X] an index, so we can do non-dependent match.\n       * In expr_weaken, we can push the proof all the way into Var, making\n         sure that proofs never block computation. *)\n  | Var (x : string) `{VarBound x X}\n  | Rec (f x : binder) (e : expr (f :b: x :b: X))\n  | App (e1 e2 : expr X)\n  (* Base types and their operations *)\n  | Lit (l : base_lit)\n  | UnOp (op : un_op) (e : expr X)\n  | BinOp (op : bin_op) (e1 e2 : expr X)\n  | If (e0 e1 e2 : expr X)\n  (* Products *)\n  | Pair (e1 e2 : expr X)\n  | Fst (e : expr X)\n  | Snd (e : expr X)\n  (* Sums *)\n  | InjL (e : expr X)\n  | InjR (e : expr X)\n  | Case (e0 : expr X) (e1 : expr X) (e2 : expr X)\n  (* Concurrency *)\n  | Fork (e : expr X)\n  (* Heap *)\n  | Loc (l : loc)\n  | Alloc (e : expr X)\n  | Load (e : expr X)\n  | Store (e1 : expr X) (e2 : expr X)\n  | CAS (e0 : expr X) (e1 : expr X) (e2 : expr X).\n\nBind Scope expr_scope with expr.\nDelimit Scope expr_scope with E.\nArguments Var {_} _ {_}.\nArguments Rec {_} _ _ _%E.\nArguments App {_} _%E _%E.\nArguments Lit {_} _.\nArguments UnOp {_} _ _%E.\nArguments BinOp {_} _ _%E _%E.\nArguments If {_} _%E _%E _%E.\nArguments Pair {_} _%E _%E.\nArguments Fst {_} _%E.\nArguments Snd {_} _%E.\nArguments InjL {_} _%E.\nArguments InjR {_} _%E.\nArguments Case {_} _%E _%E _%E.\nArguments Fork {_} _%E.\nArguments Loc {_} _.\nArguments Alloc {_} _%E.\nArguments Load {_} _%E.\nArguments Store {_} _%E _%E.\nArguments CAS {_} _%E _%E _%E.\n\nInductive val :=\n  | RecV (f x : binder) (e : expr (f :b: x :b: []))\n  | LitV (l : base_lit)\n  | PairV (v1 v2 : val)\n  | InjLV (v : val)\n  | InjRV (v : val)\n  | LocV (l : loc).\n\nBind Scope val_scope with val.\nDelimit Scope val_scope with V.\nArguments PairV _%V _%V.\nArguments InjLV _%V.\nArguments InjRV _%V.\n\nDefinition signal : val := RecV BAnon (BNamed \"x\") (Store (Var \"x\") (Lit (LitInt 1))).\n\nFixpoint of_val (v : val) : expr [] :=\n  match v with\n  | RecV f x e => Rec f x e\n  | LitV l => Lit l\n  | PairV v1 v2 => Pair (of_val v1) (of_val v2)\n  | InjLV v => InjL (of_val v)\n  | InjRV v => InjR (of_val v)\n  | LocV l => Loc l\n  end.\n\nFixpoint to_val (e : expr []) : option val :=\n  match e with\n  | Rec f x e => Some (RecV f x e)\n  | Lit l => Some (LitV l)\n  | Pair e1 e2 => v1 ← to_val e1; v2 ← to_val e2; Some (PairV v1 v2)\n  | InjL e => InjLV <$> to_val e\n  | InjR e => InjRV <$> to_val e\n  | Loc l => Some (LocV l)\n  | _ => None\n  end.\n\n(** The state: heaps of vals. *)\nDefinition state := gmap loc val.\n\n(** Evaluation contexts *)\nInductive ectx_item :=\n  | AppLCtx (e2 : expr [])\n  | AppRCtx (v1 : val)\n  | UnOpCtx (op : un_op)\n  | BinOpLCtx (op : bin_op) (e2 : expr [])\n  | BinOpRCtx (op : bin_op) (v1 : val)\n  | IfCtx (e1 e2 : expr [])\n  | PairLCtx (e2 : expr [])\n  | PairRCtx (v1 : val)\n  | FstCtx\n  | SndCtx\n  | InjLCtx\n  | InjRCtx\n  | CaseCtx (e1 : expr []) (e2 : expr [])\n  | AllocCtx\n  | LoadCtx\n  | StoreLCtx (e2 : expr [])\n  | StoreRCtx (v1 : val)\n  | CasLCtx (e1 : expr [])  (e2 : expr [])\n  | CasMCtx (v0 : val) (e2 : expr [])\n  | CasRCtx (v0 : val) (v1 : val).\n\nNotation ectx := (list ectx_item).\n\nDefinition fill_item (Ki : ectx_item) (e : expr []) : expr [] :=\n  match Ki with\n  | AppLCtx e2 => App e e2\n  | AppRCtx v1 => App (of_val v1) e\n  | UnOpCtx op => UnOp op e\n  | BinOpLCtx op e2 => BinOp op e e2\n  | BinOpRCtx op v1 => BinOp op (of_val v1) e\n  | IfCtx e1 e2 => If e e1 e2\n  | PairLCtx e2 => Pair e e2\n  | PairRCtx v1 => Pair (of_val v1) e\n  | FstCtx => Fst e\n  | SndCtx => Snd e\n  | InjLCtx => InjL e\n  | InjRCtx => InjR e\n  | CaseCtx e1 e2 => Case e e1 e2\n  | AllocCtx => Alloc e\n  | LoadCtx => Load e\n  | StoreLCtx e2 => Store e e2\n  | StoreRCtx v1 => Store (of_val v1) e\n  | CasLCtx e1 e2 => CAS e e1 e2\n  | CasMCtx v0 e2 => CAS (of_val v0) e e2\n  | CasRCtx v0 v1 => CAS (of_val v0) (of_val v1) e\n  end.\nDefinition fill (K : ectx) (e : expr []) : expr [] := fold_right fill_item e K.\n\n(** Substitution *)\n(** We have [subst' e BAnon v = e] to deal with anonymous binders *)\nLemma wexpr_rec_prf {X Y} (H : X `included` Y) {f x} :\n  f :b: x :b: X `included` f :b: x :b: Y.\nProof. set_solver. Qed.\n\nProgram Fixpoint wexpr {X Y} (H : X `included` Y) (e : expr X) : expr Y :=\n  match e return expr Y with\n  | Var x _ => @Var _ x _\n  | Rec f x e => Rec f x (wexpr (wexpr_rec_prf H) e)\n  | App e1 e2 => App (wexpr H e1) (wexpr H e2)\n  | Lit l => Lit l\n  | UnOp op e => UnOp op (wexpr H e)\n  | BinOp op e1 e2 => BinOp op (wexpr H e1) (wexpr H e2)\n  | If e0 e1 e2 => If (wexpr H e0) (wexpr H e1) (wexpr H e2)\n  | Pair e1 e2 => Pair (wexpr H e1) (wexpr H e2)\n  | Fst e => Fst (wexpr H e)\n  | Snd e => Snd (wexpr H e)\n  | InjL e => InjL (wexpr H e)\n  | InjR e => InjR (wexpr H e)\n  | Case e0 e1 e2 => Case (wexpr H e0) (wexpr H e1) (wexpr H e2)\n  | Fork e => Fork (wexpr H e)\n  | Loc l => Loc l\n  | Alloc e => Alloc (wexpr H e)\n  | Load  e => Load (wexpr H e)\n  | Store e1 e2 => Store (wexpr H e1) (wexpr H e2)\n  | CAS e0 e1 e2 => CAS (wexpr H e0) (wexpr H e1) (wexpr H e2)\n  end.\nSolve Obligations with set_solver.\n\nDefinition of_val' {X} (v : val) : expr X := wexpr (included_nil _) (of_val v).\n\nLemma wsubst_rec_true_prf {X Y x} (H : X `included` x :: Y) {f y}\n    (Hfy :BNamed x ≠ f ∧ BNamed x ≠ y) :\n  f :b: y :b: X `included` x :: f :b: y :b: Y.\nProof. set_solver. Qed.\nLemma wsubst_rec_false_prf {X Y x} (H : X `included` x :: Y) {f y}\n    (Hfy : ¬(BNamed x ≠ f ∧ BNamed x ≠ y)) :\n  f :b: y :b: X `included` f :b: y :b: Y.\nProof. move: Hfy=>/not_and_l [/dec_stable|/dec_stable]; set_solver. Qed.\n\nProgram Fixpoint wsubst {X Y} (x : string) (es : expr [])\n    (H : X `included` x :: Y) (e : expr X)  : expr Y :=\n  match e return expr Y with\n  | Var y _ => if decide (x = y) then wexpr _ es else @Var _ y _\n  | Rec f y e =>\n     Rec f y $ match decide (BNamed x ≠ f ∧ BNamed x ≠ y) return _ with\n               | left Hfy => wsubst x es (wsubst_rec_true_prf H Hfy) e\n               | right Hfy => wexpr (wsubst_rec_false_prf H Hfy) e\n               end\n  | App e1 e2 => App (wsubst x es H e1) (wsubst x es H e2)\n  | Lit l => Lit l\n  | UnOp op e => UnOp op (wsubst x es H e)\n  | BinOp op e1 e2 => BinOp op (wsubst x es H e1) (wsubst x es H e2)\n  | If e0 e1 e2 => If (wsubst x es H e0) (wsubst x es H e1) (wsubst x es H e2)\n  | Pair e1 e2 => Pair (wsubst x es H e1) (wsubst x es H e2)\n  | Fst e => Fst (wsubst x es H e)\n  | Snd e => Snd (wsubst x es H e)\n  | InjL e => InjL (wsubst x es H e)\n  | InjR e => InjR (wsubst x es H e)\n  | Case e0 e1 e2 =>\n     Case (wsubst x es H e0) (wsubst x es H e1) (wsubst x es H e2)\n  | Fork e => Fork (wsubst x es H e)\n  | Loc l => Loc l\n  | Alloc e => Alloc (wsubst x es H e)\n  | Load e => Load (wsubst x es H e)\n  | Store e1 e2 => Store (wsubst x es H e1) (wsubst x es H e2)\n  | CAS e0 e1 e2 => CAS (wsubst x es H e0) (wsubst x es H e1) (wsubst x es H e2)\n  end.\nSolve Obligations with set_solver.\n\nDefinition subst {X} (x : string) (es : expr []) (e : expr (x :: X)) : expr X :=\n  wsubst x es (λ z, id) e.\nDefinition subst' {X} (mx : binder) (es : expr []) : expr (mx :b: X) → expr X :=\n  match mx with BNamed x => subst x es | BAnon => id end.\n\n(** The stepping relation *)\nDefinition un_op_eval (op : un_op) (l : base_lit) : option base_lit :=\n  match op, l with\n  | NegOp, LitBool b => Some (LitBool (negb b))\n  | MinusUnOp, LitInt n => Some (LitInt (- n))\n  | _, _ => None\n  end.\n\nDefinition bin_op_eval (op : bin_op) (l1 l2 : base_lit) : option base_lit :=\n  match op, l1, l2 with\n  | PlusOp, LitInt n1, LitInt n2 => Some $ LitInt (n1 + n2)\n  | MinusOp, LitInt n1, LitInt n2 => Some $ LitInt (n1 - n2)\n  | LeOp, LitInt n1, LitInt n2 => Some $ LitBool $ bool_decide (n1 ≤ n2)\n  | LtOp, LitInt n1, LitInt n2 => Some $ LitBool $ bool_decide (n1 < n2)\n  | EqOp, LitInt n1, LitInt n2 => Some $ LitBool $ bool_decide (n1 = n2)\n  | _, _, _ => None\n  end.\n\nInductive head_step : expr [] → state → expr [] → state → option (expr []) → Prop :=\n  | BetaS f x e1 e2 v2 e' σ :\n     to_val e2 = Some v2 →\n     e' = subst' x (of_val v2) (subst' f (Rec f x e1) e1) →\n     head_step (App (Rec f x e1) e2) σ e' σ None\n  | UnOpS op l l' σ :\n     un_op_eval op l = Some l' → \n     head_step (UnOp op (Lit l)) σ (Lit l') σ None\n  | BinOpS op l1 l2 l' σ :\n     bin_op_eval op l1 l2 = Some l' → \n     head_step (BinOp op (Lit l1) (Lit l2)) σ (Lit l') σ None\n  | IfTrueS e1 e2 σ :\n     head_step (If (Lit $ LitBool true) e1 e2) σ e1 σ None\n  | IfFalseS e1 e2 σ :\n     head_step (If (Lit $ LitBool false) e1 e2) σ e2 σ None\n  | FstS e1 v1 e2 v2 σ :\n     to_val e1 = Some v1 → to_val e2 = Some v2 →\n     head_step (Fst (Pair e1 e2)) σ e1 σ None\n  | SndS e1 v1 e2 v2 σ :\n     to_val e1 = Some v1 → to_val e2 = Some v2 →\n     head_step (Snd (Pair e1 e2)) σ e2 σ None\n  | CaseLS e0 v0 e1 e2 σ :\n     to_val e0 = Some v0 →\n     head_step (Case (InjL e0) e1 e2) σ (App e1 e0) σ None\n  | CaseRS e0 v0 e1 e2 σ :\n     to_val e0 = Some v0 →\n     head_step (Case (InjR e0) e1 e2) σ (App e2 e0) σ None\n  | ForkS e σ:\n     head_step (Fork e) σ (Lit LitUnit) σ (Some e)\n  | AllocS e v σ l :\n     to_val e = Some v → σ !! l = None →\n     head_step (Alloc e) σ (Loc l) (<[l:=v]>σ) None\n  | LoadS l v σ :\n     σ !! l = Some v →\n     head_step (Load (Loc l)) σ (of_val v) σ None\n  | StoreS l e v σ :\n     to_val e = Some v → is_Some (σ !! l) →\n     head_step (Store (Loc l) e) σ (Lit LitUnit) (<[l:=v]>σ) None\n  | CasFailS l e1 v1 e2 v2 vl σ :\n     to_val e1 = Some v1 → to_val e2 = Some v2 →\n     σ !! l = Some vl → vl ≠ v1 →\n     head_step (CAS (Loc l) e1 e2) σ (Lit $ LitBool false) σ None\n  | CasSucS l e1 v1 e2 v2 σ :\n     to_val e1 = Some v1 → to_val e2 = Some v2 →\n     σ !! l = Some v1 →\n     head_step (CAS (Loc l) e1 e2) σ (Lit $ LitBool true) (<[l:=v2]>σ) None.\n\n(** Atomic expressions *)\nDefinition atomic (e: expr []) : Prop :=\n  match e with\n  | Alloc e => is_Some (to_val e)\n  | Load e => is_Some (to_val e)\n  | Store e1 e2 => is_Some (to_val e1) ∧ is_Some (to_val e2)\n  | CAS e0 e1 e2 => is_Some (to_val e0) ∧ is_Some (to_val e1) ∧ is_Some (to_val e2)\n  (* Make \"skip\" atomic *)\n  | App (Rec _ _ (Lit _)) (Lit _) => True\n  | _ => False\n  end.\n\n(** Close reduction under evaluation contexts.\nWe could potentially make this a generic construction. *)\nInductive prim_step (e1 : expr []) (σ1 : state)\n    (e2 : expr []) (σ2: state) (ef: option (expr [])) : Prop :=\n  Ectx_step K e1' e2' :\n    e1 = fill K e1' → e2 = fill K e2' →\n    head_step e1' σ1 e2' σ2 ef → prim_step e1 σ1 e2 σ2 ef.\n\n(** Substitution *)\nLemma var_proof_irrel X x H1 H2 : @Var X x H1 = @Var X x H2.\nProof. f_equal. by apply (proof_irrel _). Qed.\n\nLemma wexpr_id X (H : X `included` X) e : wexpr H e = e.\nProof. induction e; f_equal/=; auto. by apply (proof_irrel _). Qed.\nLemma wexpr_proof_irrel X Y (H1 H2 : X `included` Y) e : wexpr H1 e = wexpr H2 e.\nProof.\n  revert Y H1 H2; induction e; simpl; auto using var_proof_irrel with f_equal.\nQed.\nLemma wexpr_wexpr X Y Z (H1 : X `included` Y) (H2 : Y `included` Z) H3 e :\n  wexpr H2 (wexpr H1 e) = wexpr H3 e.\nProof.\n  revert Y Z H1 H2 H3.\n  induction e; simpl; auto using var_proof_irrel with f_equal.\nQed.\nLemma wexpr_wexpr' X Y Z (H1 : X `included` Y) (H2 : Y `included` Z) e :\n  wexpr H2 (wexpr H1 e) = wexpr (transitivity H1 H2) e.\nProof. apply wexpr_wexpr. Qed.\n\nLemma wsubst_proof_irrel X Y x es (H1 H2 : X `included` x :: Y) e :\n  wsubst x es H1 e = wsubst x es H2 e.\nProof.\n  revert Y H1 H2; induction e; simpl; intros; repeat case_decide;\n    auto using var_proof_irrel, wexpr_proof_irrel with f_equal.\nQed.\nLemma wexpr_wsubst X Y Z x es (H1: X `included` x::Y) (H2: Y `included` Z) H3 e:\n  wexpr H2 (wsubst x es H1 e) = wsubst x es H3 e.\nProof.\n  revert Y Z H1 H2 H3.\n  induction e; intros; repeat (case_decide || simplify_eq/=);\n    auto using var_proof_irrel, wexpr_wexpr with f_equal.\nQed.\nLemma wsubst_wexpr X Y Z x es (H1: X `included` Y) (H2: Y `included` x::Z) H3 e:\n  wsubst x es H2 (wexpr H1 e) = wsubst x es H3 e.\nProof.\n  revert Y Z H1 H2 H3.\n  induction e; intros; repeat (case_decide || simplify_eq/=);\n    auto using var_proof_irrel, wexpr_wexpr with f_equal.\nQed.\nLemma wsubst_wexpr' X Y Z x es (H1: X `included` Y) (H2: Y `included` x::Z) e:\n  wsubst x es H2 (wexpr H1 e) = wsubst x es (transitivity H1 H2) e.\nProof. apply wsubst_wexpr. Qed.\n\nLemma wsubst_closed X Y x es (H1 : X `included` x :: Y) H2 (e : expr X) :\n  x ∉ X → wsubst x es H1 e = wexpr H2 e.\nProof.\n  revert Y H1 H2.\n  induction e; intros; repeat (case_decide || simplify_eq/=);\n    auto using var_proof_irrel, wexpr_proof_irrel with f_equal set_solver.\n  exfalso; set_solver.\nQed.\nLemma wsubst_closed_nil x es H (e : expr []) : wsubst x es H e = e.\nProof.\n  rewrite -{2}(wexpr_id _ (reflexivity []) e).\n  apply wsubst_closed, not_elem_of_nil.\nQed.\n\nLemma of_val'_closed (v : val) :\n  of_val' v = of_val v.\nProof. by rewrite /of_val' wexpr_id. Qed.\n\n(** to_val propagation.\n    TODO: automatically appliy in wp_tactics? *)\nLemma to_val_InjL e v : to_val e = Some v → to_val (InjL e) = Some (InjLV v).\nProof. move=>H. simpl. by rewrite H. Qed.\nLemma to_val_InjR e v : to_val e = Some v → to_val (InjR e) = Some (InjRV v).\nProof. move=>H. simpl. by rewrite H. Qed.\nLemma to_val_Pair e1 e2 v1 v2 :\n  to_val e1 = Some v1 → to_val e2 = Some v2 →\n  to_val (Pair e1 e2) = Some (PairV v1 v2).\nProof. move=>H1 H2. simpl. by rewrite H1 H2. Qed.\n\n(** Basic properties about the language *)\nLemma to_of_val v : to_val (of_val v) = Some v.\nProof. by induction v; simplify_option_eq. Qed.\n\nLemma of_to_val e v : to_val e = Some v → of_val v = e.\nProof.\n  revert e v. cut (∀ X (e : expr X) (H : X = ∅) v,\n    to_val (eq_rect _ expr e _ H) = Some v → of_val v = eq_rect _ expr e _ H).\n  { intros help e v. apply (help ∅ e eq_refl). }\n  intros X e; induction e; intros HX ??; simplify_option_eq;\n    repeat match goal with\n    | IH : ∀ _ : ∅ = ∅, _ |- _ => specialize (IH eq_refl); simpl in IH\n    end; auto with f_equal.\nQed.\n\nInstance: Inj (=) (=) of_val.\nProof. by intros ?? Hv; apply (inj Some); rewrite -!to_of_val Hv. Qed.\n\nInstance fill_item_inj Ki : Inj (=) (=) (fill_item Ki).\nProof. destruct Ki; intros ???; simplify_eq/=; auto with f_equal. Qed.\n\nInstance ectx_fill_inj K : Inj (=) (=) (fill K).\nProof. red; induction K as [|Ki K IH]; naive_solver. Qed.\n\nLemma fill_app K1 K2 e : fill (K1 ++ K2) e = fill K1 (fill K2 e).\nProof. revert e; induction K1; simpl; auto with f_equal. Qed.\n\nLemma fill_val K e : is_Some (to_val (fill K e)) → is_Some (to_val e).\nProof.\n  intros [v' Hv']; revert v' Hv'.\n  induction K as [|[]]; intros; simplify_option_eq; eauto.\nQed.\n\nLemma fill_not_val K e : to_val e = None → to_val (fill K e) = None.\nProof. rewrite !eq_None_not_Some; eauto using fill_val. Qed.\n\nLemma val_head_stuck e1 σ1 e2 σ2 ef :\n  head_step e1 σ1 e2 σ2 ef → to_val e1 = None.\nProof. destruct 1; naive_solver. Qed.\n\nLemma val_stuck e1 σ1 e2 σ2 ef : prim_step e1 σ1 e2 σ2 ef → to_val e1 = None.\nProof. intros [??? -> -> ?]; eauto using fill_not_val, val_head_stuck. Qed.\n\nLemma atomic_not_val e : atomic e → to_val e = None.\nProof. destruct e; naive_solver. Qed.\n\nLemma atomic_fill_item Ki e : atomic (fill_item Ki e) → is_Some (to_val e).\nProof.\n  intros. destruct Ki; simplify_eq/=; destruct_and?;\n    repeat (case_match || contradiction); eauto.\nQed.\n\nLemma atomic_fill K e : atomic (fill K e) → to_val e = None → K = [].\nProof.\n  destruct K as [|Ki K]; [done|].\n  rewrite eq_None_not_Some=> /= ? []; eauto using atomic_fill_item, fill_val.\nQed.\n\nLemma atomic_head_step e1 σ1 e2 σ2 ef :\n  atomic e1 → head_step e1 σ1 e2 σ2 ef → is_Some (to_val e2).\nProof.\n  destruct 2; simpl; rewrite ?to_of_val; try by eauto. subst.\n  unfold subst'; repeat (case_match || contradiction || simplify_eq/=); eauto.\nQed.\n\nLemma atomic_step e1 σ1 e2 σ2 ef :\n  atomic e1 → prim_step e1 σ1 e2 σ2 ef → is_Some (to_val e2).\nProof.\n  intros Hatomic [K e1' e2' -> -> Hstep].\n  assert (K = []) as -> by eauto 10 using atomic_fill, val_head_stuck.\n  naive_solver eauto using atomic_head_step.\nQed.\n\nLemma head_ctx_step_val Ki e σ1 e2 σ2 ef :\n  head_step (fill_item Ki e) σ1 e2 σ2 ef → is_Some (to_val e).\nProof. destruct Ki; inversion_clear 1; simplify_option_eq; eauto. Qed.\n\nLemma fill_item_no_val_inj Ki1 Ki2 e1 e2 :\n  to_val e1 = None → to_val e2 = None →\n  fill_item Ki1 e1 = fill_item Ki2 e2 → Ki1 = Ki2.\nProof.\n  destruct Ki1, Ki2; intros; try discriminate; simplify_eq/=;\n    repeat match goal with\n    | H : to_val (of_val _) = None |- _ => by rewrite to_of_val in H\n    end; auto.\nQed.\n\n(* When something does a step, and another decomposition of the same expression\nhas a non-val [e] in the hole, then [K] is a left sub-context of [K'] - in\nother words, [e] also contains the reducible expression *)\nLemma step_by_val K K' e1 e1' σ1 e2 σ2 ef :\n  fill K e1 = fill K' e1' → to_val e1 = None → head_step e1' σ1 e2 σ2 ef →\n  K `prefix_of` K'.\nProof.\n  intros Hfill Hred Hnval; revert K' Hfill.\n  induction K as [|Ki K IH]; simpl; intros K' Hfill; auto using prefix_of_nil.\n  destruct K' as [|Ki' K']; simplify_eq/=.\n  { exfalso; apply (eq_None_not_Some (to_val (fill K e1)));\n      eauto using fill_not_val, head_ctx_step_val. }\n  cut (Ki = Ki'); [naive_solver eauto using prefix_of_cons|].\n  eauto using fill_item_no_val_inj, val_head_stuck, fill_not_val.\nQed.\n\nLemma alloc_fresh e v σ :\n  let l := fresh (dom _ σ) in\n  to_val e = Some v → head_step (Alloc e) σ (Loc l) (<[l:=v]>σ) None.\nProof. by intros; apply AllocS, (not_elem_of_dom (D:=gset _)), is_fresh. Qed.\n\n(** Equality and other typeclass stuff *)\nInstance base_lit_dec_eq (l1 l2 : base_lit) : Decision (l1 = l2).\nProof. solve_decision. Defined.\nInstance un_op_dec_eq (op1 op2 : un_op) : Decision (op1 = op2).\nProof. solve_decision. Defined.\nInstance bin_op_dec_eq (op1 op2 : bin_op) : Decision (op1 = op2).\nProof. solve_decision. Defined.\n\nFixpoint expr_beq {X Y} (e : expr X) (e' : expr Y) : bool :=\n  match e, e' with\n  | Var x _, Var x' _ => bool_decide (x = x')\n  | Rec f x e, Rec f' x' e' =>\n     bool_decide (f = f') && bool_decide (x = x') && expr_beq e e'\n  | App e1 e2, App e1' e2' | Pair e1 e2, Pair e1' e2' |\n    Store e1 e2, Store e1' e2' => expr_beq e1 e1' && expr_beq e2 e2'\n  | Lit l, Lit l' => bool_decide (l = l')\n  | UnOp op e, UnOp op' e' => bool_decide (op = op') && expr_beq e e'\n  | BinOp op e1 e2, BinOp op' e1' e2' =>\n     bool_decide (op = op') && expr_beq e1 e1' && expr_beq e2 e2'\n  | If e0 e1 e2, If e0' e1' e2' | Case e0 e1 e2, Case e0' e1' e2' |\n    CAS e0 e1 e2, CAS e0' e1' e2' =>\n     expr_beq e0 e0' && expr_beq e1 e1' && expr_beq e2 e2'\n  | Fst e, Fst e' | Snd e, Snd e' | InjL e, InjL e' | InjR e, InjR e' |\n    Fork e, Fork e' | Alloc e, Alloc e' | Load e, Load e' => expr_beq e e'\n  | Loc l, Loc l' => bool_decide (l = l')\n  | _, _ => false\n  end.\nLemma expr_beq_correct {X} (e1 e2 : expr X) : expr_beq e1 e2 ↔ e1 = e2.\nProof.\n  split.\n  * revert e2; induction e1; intros [] * ?; simpl in *;\n      destruct_and?; subst; repeat f_equal/=; auto; try apply proof_irrel.\n  * intros ->. induction e2; naive_solver.\nQed.\nInstance expr_dec_eq {X} (e1 e2 : expr X) : Decision (e1 = e2).\nProof.\n refine (cast_if (decide (expr_beq e1 e2))); by rewrite -expr_beq_correct.\nDefined.\nInstance val_dec_eq (v1 v2 : val) : Decision (v1 = v2).\nProof.\n refine (cast_if (decide (of_val v1 = of_val v2))); abstract naive_solver.\nDefined.\n\nInstance expr_inhabited X : Inhabited (expr X) := populate (Lit LitUnit).\nInstance val_inhabited : Inhabited val := populate (LitV LitUnit).\nEnd heap_lang.\n\n(** Language *)\nProgram Canonical Structure heap_lang : language := {|\n  expr := heap_lang.expr []; val := heap_lang.val; state := heap_lang.state;\n  of_val := heap_lang.of_val; to_val := heap_lang.to_val;\n  atomic := heap_lang.atomic; prim_step := heap_lang.prim_step;\n|}.\nSolve Obligations with eauto using heap_lang.to_of_val, heap_lang.of_to_val,\n  heap_lang.val_stuck, heap_lang.atomic_not_val, heap_lang.atomic_step.\n\nGlobal Instance heap_lang_ctx K : LanguageCtx heap_lang (heap_lang.fill K).\nProof.\n  split.\n  - eauto using heap_lang.fill_not_val.\n  - intros ????? [K' e1' e2' Heq1 Heq2 Hstep].\n    by exists (K ++ K') e1' e2'; rewrite ?heap_lang.fill_app ?Heq1 ?Heq2.\n  - intros e1 σ1 e2 σ2 ? Hnval [K'' e1'' e2'' Heq1 -> Hstep].\n    destruct (heap_lang.step_by_val\n      K K'' e1 e1'' σ1 e2'' σ2 ef) as [K' ->]; eauto.\n    rewrite heap_lang.fill_app in Heq1; apply (inj _) in Heq1.\n    exists (heap_lang.fill K' e2''); rewrite heap_lang.fill_app; split; auto.\n    econstructor; eauto.\nQed.\n\nGlobal Instance heap_lang_ctx_item Ki :\n  LanguageCtx heap_lang (heap_lang.fill_item Ki).\nProof. change (LanguageCtx heap_lang (heap_lang.fill [Ki])). apply _. Qed.\n\n(* Prefer heap_lang names over language names. *)\nExport heap_lang.\n", "meta": {"author": "amintimany", "repo": "iris-with-logrel-backup", "sha": "9e98ff8be4b4ca516a497d328aaf31cbae186a6c", "save_path": "github-repos/coq/amintimany-iris-with-logrel-backup", "path": "github-repos/coq/amintimany-iris-with-logrel-backup/iris-with-logrel-backup-9e98ff8be4b4ca516a497d328aaf31cbae186a6c/heap_lang/lang.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2044121708914205}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Bool.\nRequire Import Sumbool.\nRequire Import Arith.\nRequire Import ZArith NArith Nnat Ndec Ndigits.\nFrom IntMap Require Import Map.\nFrom IntMap Require Import Allmaps.\nRequire Import List.\nRequire Import Wf_nat.\n\nRequire Import misc.\nRequire Import bool_fun.\nRequire Import myMap.\nRequire Import config.\nRequire Import alloc.\nRequire Import make.\nRequire Import op.\n\nSection BDDuniv_sec.\n\n\nVariable gc : BDDconfig -> list ad -> BDDconfig.\nHypothesis gc_is_OK : gc_OK gc.\n\nFixpoint BDDuniv_1 (cfg : BDDconfig) (ul : list ad) \n (node : ad) (y : BDDvar) (bound : nat) {struct bound} : \n BDDconfig * ad :=\n  match bound with\n  | O => (* Error *)  (initBDDconfig, BDDzero)\n  | S bound' =>\n      match MapGet2 _ (um_of_cfg cfg) node y with\n      | Some node' => (cfg, node')\n      | None =>\n          match MapGet _ (fst cfg) node with\n          | None => (cfg, node)\n          | Some (x, (l, r)) =>\n              match BDDcompare x y with\n              | Datatypes.Lt => (cfg, node)\n              | Datatypes.Eq => BDDand gc cfg ul l r\n              | Datatypes.Gt =>\n                  match BDDuniv_1 cfg ul l y bound' with\n                  | (cfgl, nodel) =>\n                      match BDDuniv_1 cfgl (nodel :: ul) r y bound' with\n                      | (cfgr, noder) =>\n                          match\n                            BDDmake gc cfgr x nodel noder\n                              (noder :: nodel :: ul)\n                          with\n                          | (cfg', node') =>\n                              (BDDuniv_memo_put cfg' y node node', node')\n                          end\n                      end\n                  end\n              end\n          end\n      end\n  end.\n\nLemma BDDuniv_1_lemma :\n forall (bound : nat) (cfg : BDDconfig) (ul : list ad) \n   (u : BDDvar) (node : ad),\n nat_of_N (node_height cfg node) < bound ->\n BDDconfig_OK cfg ->\n used_list_OK cfg ul ->\n used_node' cfg ul node ->\n BDDconfig_OK (fst (BDDuniv_1 cfg ul node u bound)) /\\\n config_node_OK (fst (BDDuniv_1 cfg ul node u bound))\n   (snd (BDDuniv_1 cfg ul node u bound)) /\\\n used_nodes_preserved cfg (fst (BDDuniv_1 cfg ul node u bound)) ul /\\\n Nleb\n   (node_height (fst (BDDuniv_1 cfg ul node u bound))\n      (snd (BDDuniv_1 cfg ul node u bound))) (node_height cfg node) = true /\\\n bool_fun_eq\n   (bool_fun_of_BDD (fst (BDDuniv_1 cfg ul node u bound))\n      (snd (BDDuniv_1 cfg ul node u bound)))\n   (bool_fun_forall u (bool_fun_of_BDD cfg node)).\nProof.\n  simple induction bound.  intros.  absurd (nat_of_N (node_height cfg node) < 0).\n  apply lt_n_O.  assumption.  simpl in |- *.  intros.\n  elim (option_sum _ (MapGet2 ad (um_of_cfg cfg) node u)).  intro y.\n  elim y; clear y; intros node' H4.  rewrite H4.  simpl in |- *.\n  elim (um_of_cfg_OK _ H1 u node node' H4).  intros.  split.  assumption.  \n  split.  inversion H6.  inversion H8.  assumption.  split.\n  apply used_nodes_preserved_refl.  split.  exact (proj1 (proj2 H6)).\n  exact (proj2 (proj2 H6)).  intro y.  rewrite y.\n  elim (option_sum _ (MapGet (BDDvar * (ad * ad)) (fst cfg) node)).  intro y0.\n  elim y0; clear y0.\n  intro x; elim x; clear x; intros x x0; elim x0; clear x0; intros l r H4.\n  rewrite H4.  cut (used_node' cfg ul l).  cut (used_node' cfg ul r).\n  elim (relation_sum (BDDcompare x u)).  intro y0.  elim y0; clear y0.\n  intros y0.  rewrite y0.  split.  apply BDDand_config_OK.  assumption.  \n  assumption.  assumption.  assumption.  assumption.  split.\n  apply BDDand_node_OK.  assumption.  assumption.  assumption.  assumption.  \n  assumption.  split.  apply BDDand_used_nodes_preserved.  assumption.\n  assumption.  assumption.  assumption.  assumption.  split.\n  apply\n   Nleb_trans with (b := BDDvar_max (node_height cfg l) (node_height cfg r)).\n  apply BDDand_var_le.  assumption.  assumption.  assumption.  assumption.  \n  assumption.  unfold Nleb in |- *.\n  rewrite (BDDvar_max_max (node_height cfg l) (node_height cfg r)).\n  apply leb_correct.  apply lt_le_weak.  apply\n   lt_le_trans\n    with\n      (m := max (nat_of_N (node_height cfg node))\n              (nat_of_N (node_height cfg node))).\n  apply lt_max_1_2.  apply BDDcompare_lt.  unfold node_height in |- *.\n  apply bs_node_height_left with (x := x) (r := r).  exact (proj1 H1).  assumption.\n  apply BDDcompare_lt.  unfold node_height in |- *.\n  apply bs_node_height_right with (x := x) (l := l).  exact (proj1 H1).  assumption.\n  rewrite (max_x_x_eq_x (nat_of_N (node_height cfg node))).  apply le_n.  \n  rewrite <- (BDD_EGAL_complete _ _ y0).\n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_forall u\n                (bool_fun_if x (bool_fun_of_BDD cfg r)\n                   (bool_fun_of_BDD cfg l))).\n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_and (bool_fun_of_BDD cfg r) (bool_fun_of_BDD cfg l)).\n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_and (bool_fun_of_BDD cfg l) (bool_fun_of_BDD cfg r)).\n  apply BDDand_is_and.  assumption.  assumption.  assumption.  assumption.  \n  assumption.  apply bool_fun_and_comm.  apply bool_fun_eq_sym.\n  rewrite (BDD_EGAL_complete _ _ y0).  apply bool_fun_forall_if_egal.\n  unfold bool_fun_of_BDD in |- *.  rewrite <- (BDD_EGAL_complete _ _ y0).\n  apply BDDvar_independent_high with (x := x) (l := l) (node := node).\n  exact (proj1 H1).  assumption.  unfold bool_fun_of_BDD in |- *.\n  rewrite <- (BDD_EGAL_complete _ _ y0).\n  apply BDDvar_independent_low with (x := x) (r := r) (node := node).  exact (proj1 H1).\n  assumption.  rewrite <- (BDD_EGAL_complete _ _ y0).\n  apply bool_fun_forall_preserves_eq.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_int.  assumption.  assumption.  intros y0.  rewrite y0.\n  split.  assumption.  split.  apply used_node'_OK with (ul := ul).  assumption.\n  assumption.  assumption.  split.  apply used_nodes_preserved_refl.  split.\n  apply Nleb_refl.  simpl in |- *.  apply bool_fun_eq_sym.\n  apply bool_fun_forall_independent.  unfold bool_fun_of_BDD in |- *.\n  apply BDDvar_independent_bs.  exact (proj1 H1).  \n  fold (node_OK (fst cfg) node) in |- *.  fold (config_node_OK cfg node) in |- *.\n  apply used_node'_OK with (ul := ul).  assumption.  assumption.  assumption.\n  unfold bs_node_height in |- *.  rewrite H4.  unfold Nleb in |- *.  rewrite (ad_S_is_S x).\n  apply leb_correct.  fold lt in |- *.  fold (nat_of_N x < nat_of_N u) in |- *.\n  apply BDDcompare_lt.  assumption.  intros y0 H5 H6.  rewrite y0.\n  elim (prod_sum _ _ (BDDuniv_1 cfg ul l u n)).  intros cfgl H7.\n  elim H7; clear H7.  intros nodel H7.  rewrite H7.\n  elim (prod_sum _ _ (BDDuniv_1 cfgl (nodel :: ul) r u n)).  intros cfgr H8.\n  elim H8; clear H8.  intros noder H8.  rewrite H8.  elim (prod_sum _ _ (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  intros cfg' H9.  elim H9; clear H9.  intros node' H9.  rewrite H9.  simpl in |- *.  \n  cut\n   (BDDconfig_OK cfgl /\\\n    config_node_OK cfgl nodel /\\\n    used_nodes_preserved cfg cfgl ul /\\\n    Nleb (node_height cfgl nodel) (node_height cfg l) = true /\\\n    bool_fun_eq (bool_fun_of_BDD cfgl nodel)\n      (bool_fun_forall u (bool_fun_of_BDD cfg l))).\n  intro.  elim H10; clear H10; intros.  elim H11; clear H11; intros.\n  elim H12; clear H12; intros.  elim H13; clear H13; intros.\n  cut (config_node_OK cfg l).  cut (config_node_OK cfg r).  intros.\n  cut (used_list_OK cfgl ul).  intro.  cut (used_list_OK cfgl (nodel :: ul)).\n  intro.  cut (used_node' cfgl ul r).  intro.\n  cut (used_node' cfgl (nodel :: ul) r).  intro.  \n  cut\n   (BDDconfig_OK cfgr /\\\n    config_node_OK cfgr noder /\\\n    used_nodes_preserved cfgl cfgr (nodel :: ul) /\\\n    Nleb (node_height cfgr noder) (node_height cfgl r) = true /\\\n    bool_fun_eq (bool_fun_of_BDD cfgr noder)\n      (bool_fun_forall u (bool_fun_of_BDD cfgl r))).\n  intro.  elim H21; clear H21; intros.  elim H22; clear H22; intros.\n  elim H23; clear H23; intros.  elim H24; clear H24; intros.\n  cut (used_list_OK cfgr (nodel :: ul)).  intro.\n  cut (used_list_OK cfgr (noder :: nodel :: ul)).  intro.\n  cut (used_node' cfgr (noder :: nodel :: ul) nodel).\n  cut (used_node' cfgr (noder :: nodel :: ul) noder).  intros.\n  cut\n   (forall (xl : BDDvar) (ll rl : ad),\n    MapGet _ (fst cfgr) nodel = Some (xl, (ll, rl)) ->\n    BDDcompare xl x = Datatypes.Lt).\n  cut\n   (forall (xr : BDDvar) (lr rr : ad),\n    MapGet _ (fst cfgr) noder = Some (xr, (lr, rr)) ->\n    BDDcompare xr x = Datatypes.Lt).\n  intros.  cut (BDDconfig_OK cfg').\n  cut (used_nodes_preserved cfgr cfg' (noder :: nodel :: ul)).\n  cut (config_node_OK cfg' node').\n\n  cut\n   (bool_fun_eq (bool_fun_of_BDD cfg' node')\n      (bool_fun_if x (bool_fun_of_BDD cfgr noder)\n         (bool_fun_of_BDD cfgr nodel))).\n  cut (Nleb (node_height cfg' node') (ad_S x) = true).  intros.\n  cut (config_node_OK cfg' node).  intro.\n  cut (nodes_preserved cfg' (BDDuniv_memo_put cfg' u node node')).  intro.\n  cut (BDDconfig_OK (BDDuniv_memo_put cfg' u node node')).  intro.  split.\n  assumption.  split.  apply nodes_preserved_config_node_OK with (cfg1 := cfg').\n  assumption.  assumption.  split.\n  apply used_nodes_preserved_trans with (cfg2 := cfgr).  assumption.\n  apply used_nodes_preserved_trans with (cfg2 := cfgl).  assumption.  assumption.\n  apply used_nodes_preserved_cons with (node := nodel).  assumption.\n  apply used_nodes_preserved_trans with (cfg2 := cfg').  assumption.\n  apply used_nodes_preserved_cons with (node := nodel).\n  apply used_nodes_preserved_cons with (node := noder).\n  assumption.  apply nodes_preserved_used_nodes_preserved.  assumption.\n  rewrite\n   (Neqb_complete (node_height (BDDuniv_memo_put cfg' u node node') node')\n      (node_height cfg' node')).\n  split.  apply Nleb_trans with (b := ad_S x).  assumption.\n  unfold node_height in |- *.  unfold bs_node_height in |- *.\n  rewrite H4.  apply Nleb_refl.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfg' node').\n  apply nodes_preserved_bool_fun.  assumption.  assumption.  assumption.\n  assumption.  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_if x (bool_fun_of_BDD cfgr noder)\n                (bool_fun_of_BDD cfgr nodel)).\n  assumption.\n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_if x (bool_fun_forall u (bool_fun_of_BDD cfg r))\n                (bool_fun_forall u (bool_fun_of_BDD cfg l))).\n  apply bool_fun_if_preserves_eq.  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_forall u (bool_fun_of_BDD cfgl r)).\n  assumption.  apply bool_fun_forall_preserves_eq.\n  apply used_nodes_preserved'_bool_fun with (ul := ul).\n  assumption.  assumption.  assumption.  assumption.  assumption.\n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfgl nodel).\n  apply used_nodes_preserved'_bool_fun with (ul := nodel :: ul).  assumption.\n  assumption.  assumption.  assumption.  apply used_node'_cons_node_ul.\n  assumption.  apply bool_fun_eq_sym.\n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_forall u\n                (bool_fun_if x (bool_fun_of_BDD cfg r)\n                   (bool_fun_of_BDD cfg l))).\n  apply bool_fun_forall_preserves_eq.  apply bool_fun_of_BDD_int.  assumption.\n  assumption.  apply bool_fun_forall_orthogonal.  apply not_true_is_false.\n  unfold not in |- *; intro.  rewrite (Neqb_complete _ _ H40) in y0.\n  rewrite (BDD_EGAL_correct u) in y0.  discriminate y0.  \n  apply nodes_preserved_node_height_eq.\n  assumption.  assumption.  assumption.  assumption.  apply BDDum_put_OK.\n  assumption.  assumption.  assumption.\n  rewrite (Neqb_complete (node_height cfg' node) (node_height cfg node)).\n  unfold node_height at 2 in |- *.  unfold bs_node_height in |- *.  rewrite H4.  assumption.  \n  apply used_nodes_preserved'_node_height_eq with (ul := ul).  assumption.  \n  assumption.  apply used_nodes_preserved_trans with (cfg2 := cfgl).  assumption.\n  assumption.  apply used_nodes_preserved_cons with (node := nodel).\n  apply used_nodes_preserved_trans with (cfg2 := cfgr).  assumption.  assumption.  \n  apply used_nodes_preserved_cons with (node := noder).  assumption.  assumption.  \n  assumption.  \n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_if x (bool_fun_of_BDD cfgr noder)\n                (bool_fun_of_BDD cfgr nodel)).\n  assumption.\n  apply\n   bool_fun_eq_trans\n    with (bf2 := bool_fun_forall u (bool_fun_of_BDD cfg node)).\n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_if x (bool_fun_forall u (bool_fun_of_BDD cfg r))\n                (bool_fun_forall u (bool_fun_of_BDD cfg l))).\n  apply bool_fun_if_preserves_eq.\n  apply\n   bool_fun_eq_trans with (bf2 := bool_fun_forall u (bool_fun_of_BDD cfgl r)).\n  assumption.  apply bool_fun_forall_preserves_eq.  \n  apply used_nodes_preserved'_bool_fun with (ul := ul).  assumption.  assumption.  \n  assumption.  assumption.  assumption.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_of_BDD cfgl nodel).\n  apply used_nodes_preserved'_bool_fun with (ul := nodel :: ul).  assumption.  \n  assumption.  assumption.  assumption.  apply used_node'_cons_node_ul.  \n  assumption. \n  apply\n   bool_fun_eq_trans\n    with\n      (bf2 := bool_fun_forall u\n                (bool_fun_if x (bool_fun_of_BDD cfg r)\n                   (bool_fun_of_BDD cfg l))).\n  apply bool_fun_eq_sym.  apply bool_fun_forall_orthogonal.\n  apply not_true_is_false.  unfold not in |- *; intro.\n  rewrite (Neqb_complete _ _ H39) in y0.  rewrite (BDD_EGAL_correct u) in y0.\n  discriminate y0.\n  apply bool_fun_forall_preserves_eq.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_int.  assumption.  assumption.\n  apply bool_fun_forall_preserves_eq.  apply bool_fun_eq_sym.\n  apply used_nodes_preserved'_bool_fun with (ul := ul).  assumption.  assumption.\n  apply used_nodes_preserved_trans with (cfg2 := cfgl).  assumption.  assumption.\n  apply used_nodes_preserved_trans with (cfg2 := cfgr).  assumption.\n  apply used_nodes_preserved_cons with (node := nodel).  assumption.\n  apply used_nodes_preserved_cons with (node := nodel).\n  apply used_nodes_preserved_cons with (node := noder).  assumption.  assumption.\n  assumption.  apply BDDum_put_nodes_preserved.\n  apply used_nodes_preserved_node_OK' with (ul := ul) (cfg := cfg).  assumption.\n  assumption.  assumption.  apply used_nodes_preserved_trans with (cfg2 := cfgl).\n  assumption.  assumption.  apply used_nodes_preserved_trans with (cfg2 := cfgr).\n  assumption.  apply used_nodes_preserved_cons with (node := nodel).  assumption.\n  apply used_nodes_preserved_cons with (node := nodel).\n  apply used_nodes_preserved_cons with (node := noder).  assumption.\n  replace cfg' with\n   (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  replace node' with\n   (snd (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  apply BDDmake_node_height_le.  assumption. \n  assumption.  rewrite H9; reflexivity.  rewrite H9; reflexivity.\n  replace cfg' with\n   (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  replace node' with\n   (snd (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  apply BDDmake_bool_fun.  assumption.  assumption.  assumption.  assumption.\n  assumption.  assumption.  assumption.  rewrite H9.  reflexivity.  rewrite H9.\nreflexivity.\n  replace cfg' with\n   (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  replace node' with\n   (snd (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  apply BDDmake_node_OK.  assumption.  assumption.  assumption.  assumption.\n  assumption.  assumption.  assumption.  rewrite H9.  reflexivity.  rewrite H9.\nreflexivity.\n replace cfg' with\n  (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  replace node' with\n   (snd (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  apply BDDmake_preserves_used_nodes.  assumption.  assumption.  assumption. \n\n  rewrite H9.  reflexivity.  rewrite H9.  reflexivity.\n  replace cfg' with\n   (fst (BDDmake gc cfgr x nodel noder (noder :: nodel :: ul))).\n  apply BDDmake_keeps_config_OK.  assumption.  assumption.  assumption.\n  assumption.  assumption.  assumption.   assumption.\n  rewrite H9.  reflexivity.\n  intros.  rewrite (ad_S_compare xr x).\n  replace (ad_S xr) with (node_height cfgr noder).\n  replace (ad_S x) with (node_height cfg node).   (* Unfold node_height in H24.*)\n  apply BDDlt_compare.  apply le_lt_trans with (m := nat_of_N (node_height cfgl r)).\n  apply leb_complete.  assumption.\n  rewrite (Neqb_complete (node_height cfgl r) (node_height cfg r)).\n  apply BDDcompare_lt.  unfold node_height in |- *.  apply bs_node_height_right with (x := x) (l := l).\n  exact (proj1 H1).  assumption.\n  apply used_nodes_preserved'_node_height_eq with (ul := ul).  assumption.\n  assumption.  assumption.  assumption.  assumption.\n  unfold node_height in |- *.  unfold bs_node_height in |- *.  rewrite H4.  reflexivity.\n  unfold node_height in |- *.  unfold bs_node_height in |- *.  rewrite H30.  reflexivity.\n  intros.  rewrite (ad_S_compare xl x).\n  replace (ad_S xl) with (node_height cfgr nodel).\n  replace (ad_S x) with (node_height cfg node). (*  Unfold node_height in H24.*)\n  rewrite (Neqb_complete (node_height cfgr nodel) (node_height cfgl nodel)).\n  apply BDDlt_compare.  apply le_lt_trans with (m := nat_of_N (node_height cfg l)).\n  apply leb_complete.  assumption.\n  apply BDDcompare_lt.  unfold node_height in |- *.  apply bs_node_height_left with (x := x) (r := r).\n  exact (proj1 H1).  assumption.\n  apply used_nodes_preserved'_node_height_eq with (ul := nodel :: ul).  assumption.\n  assumption.  assumption.  assumption.\n  apply used_node'_cons_node_ul.\n  unfold node_height in |- *.  unfold bs_node_height in |- *.  rewrite H4.  reflexivity.\n  unfold node_height in |- *.  unfold bs_node_height in |- *.  rewrite H30.  reflexivity.\n  apply used_node'_cons_node_ul.  apply used_node'_cons_node'_ul.\n  apply used_node'_cons_node_ul.  apply node_OK_list_OK.  assumption.\n  assumption.  apply used_nodes_preserved_list_OK with (cfg := cfgl).  assumption.\n  assumption. \n  replace cfgr with (fst (BDDuniv_1 cfgl (nodel :: ul) r u n)).\n  replace noder with (snd (BDDuniv_1 cfgl (nodel :: ul) r u n)).  apply H.\n  apply lt_trans_1 with (y := nat_of_N (node_height cfg node)).\n  rewrite (Neqb_complete (node_height cfgl r) (node_height cfg r)).  apply BDDcompare_lt.\n  unfold node_height in |- *.  apply bs_node_height_right with (x := x) (l := l).  exact (proj1 H1).\n  assumption.  apply used_nodes_preserved'_node_height_eq with (ul := ul).  assumption.\n  assumption.  assumption.  assumption.  assumption.  assumption.\n  assumption.  assumption.  assumption.  rewrite H8.  reflexivity.\n  rewrite H8.  reflexivity.  apply used_node'_cons_node'_ul.\n  apply used_nodes_preserved_used_node' with (cfg := cfg).  assumption.\n  assumption.  apply high_used' with (node := node) (x := x) (l := l).  assumption.\n  assumption.  assumption.  \n  apply used_nodes_preserved_used_node' with (cfg := cfg).  assumption.\n  assumption.  assumption.  apply node_OK_list_OK.  assumption.  assumption.\n  apply used_nodes_preserved_list_OK with (cfg := cfg).  assumption.  assumption.\n  apply used_node'_OK with (ul := ul).  assumption.  assumption.  assumption.\n  apply used_node'_OK with (ul := ul).  assumption.  assumption.  assumption.\n  replace cfgl with (fst (BDDuniv_1 cfg ul l u n)).\n  replace nodel with (snd (BDDuniv_1 cfg ul l u n)).  apply H.\n  apply lt_trans_1 with (y := nat_of_N (node_height cfg node)).\n  apply BDDcompare_lt.  unfold node_height in |- *.\n  apply bs_node_height_left with (x := x) (r := r).  exact (proj1 H1).\n  assumption.  assumption.  assumption.  assumption.  assumption.\n  rewrite H7.  reflexivity.  rewrite H7.  reflexivity.  \n  apply high_used' with (node := node) (x := x) (l := l).  assumption.  assumption.\n  assumption.  apply low_used' with (node := node) (x := x) (r := r).  assumption.\n  assumption.  assumption.  intro y0.  rewrite y0.  simpl in |- *.  split.  assumption.\n  split.  apply used_node'_OK with (ul := ul).  assumption.  assumption.  \n  assumption.  split.  apply used_nodes_preserved_refl.  split.\n  apply Nleb_refl.  cut (config_node_OK cfg node).  intro.\n  unfold config_node_OK in H4.  elim H4.  intro.  rewrite H5.\n  apply bool_fun_eq_trans with bool_fun_zero.  apply bool_fun_of_BDD_zero.\n  assumption.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_forall u bool_fun_zero).\n  apply bool_fun_eq_sym.  apply bool_fun_forall_zero.  \n  apply bool_fun_forall_preserves_eq.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_zero.  assumption.  intro.  elim H5.  intro.\n  rewrite H6.  apply bool_fun_eq_trans with bool_fun_one.\n  apply bool_fun_of_BDD_one.  assumption.  \n  apply bool_fun_eq_trans with (bf2 := bool_fun_forall u bool_fun_one).\n  apply bool_fun_eq_sym.  apply bool_fun_forall_one.  \n  apply bool_fun_forall_preserves_eq.  apply bool_fun_eq_sym.\n  apply bool_fun_of_BDD_one.  assumption.  unfold in_dom in |- *.  rewrite y0.\n  intro; discriminate.  apply used_node'_OK with (ul := ul).  assumption.  \n  assumption.  assumption.  \nQed.\n\nEnd BDDuniv_sec.\n", "meta": {"author": "coq-contribs", "repo": "smc", "sha": "e175520faa82eda0f014d300705612892fc7e778", "save_path": "github-repos/coq/coq-contribs-smc", "path": "github-repos/coq/coq-contribs-smc/smc-e175520faa82eda0f014d300705612892fc7e778/univ.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.20437304843533297}}
{"text": "From cap_machine Require Import rules_base.\nFrom iris.base_logic Require Export invariants gen_heap.\nFrom iris.program_logic Require Export weakestpre ectx_lifting.\nFrom iris.proofmode Require Import tactics.\nFrom iris.algebra Require Import frac.\n\nSection cap_lang_rules.\n  Context `{memG Σ, regG Σ}.\n  Context `{MachineParameters}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types σ : ExecConf.\n  Implicit Types c : cap_lang.expr. \n  Implicit Types a b : Addr.\n  Implicit Types r : RegName.\n  Implicit Types v : cap_lang.val. \n  Implicit Types w : Word.\n  Implicit Types reg : gmap RegName Word.\n  Implicit Types ms : gmap Addr Word.\n\n  (* TODO: Move somewhere *)\n  Ltac destruct_cap c :=\n    let p := fresh \"p\" in\n    let g := fresh \"g\" in\n    let b := fresh \"b\" in\n    let e := fresh \"e\" in\n    let a := fresh \"a\" in\n    destruct c as ((((p & g) & b) & e) & a).\n\n  Inductive Restrict_failure (regs: Reg) (dst: RegName) (src: Z + RegName) :=\n  | Restrict_fail_dst_noncap z:\n      regs !! dst = Some (inl z) →\n      Restrict_failure regs dst src\n  | Restrict_fail_pE p g b e a:\n      regs !! dst = Some (inr (p, g, b, e, a)) →\n      p = E →\n      Restrict_failure regs dst src\n  | Restrict_fail_src_nonz:\n      z_of_argument regs src = None →\n      Restrict_failure regs dst src\n  | Restrict_fail_invalid_perm p g b e a n:\n      regs !! dst = Some (inr (p, g, b, e, a)) →\n      p ≠ E →\n      z_of_argument regs src = Some n →\n      PermPairFlowsTo (decodePermPair n) (p, g) = false →\n      Restrict_failure regs dst src\n  | Restrict_fail_PC_overflow p g b e a n:\n      regs !! dst = Some (inr (p, g, b, e, a)) →\n      p ≠ E →\n      z_of_argument regs src = Some n →\n      PermPairFlowsTo (decodePermPair n) (p, g) = true →\n      incrementPC (<[ dst := inr (decodePermPair n, b, e, a) ]> regs) = None →\n      Restrict_failure regs dst src.\n\n  Inductive Restrict_spec (regs: Reg) (dst: RegName) (src: Z + RegName) (regs': Reg): cap_lang.val -> Prop :=\n  | Restrict_spec_success p g b e a n:\n      regs !! dst = Some (inr (p, g, b, e, a)) →\n      p ≠ E ->\n      z_of_argument regs src = Some n →\n      PermPairFlowsTo (decodePermPair n) (p, g) = true →\n      incrementPC (<[ dst := inr (decodePermPair n, b, e, a) ]> regs) = Some regs' →\n      Restrict_spec regs dst src regs' NextIV\n  | Restrict_spec_failure:\n      Restrict_failure regs dst src →\n      Restrict_spec regs dst src regs' FailedV.\n\n  Lemma wp_Restrict Ep pc_p pc_g pc_b pc_e pc_a w dst src regs :\n    decodeInstrW w = Restrict dst src ->\n\n    isCorrectPC (inr ((pc_p, pc_g), pc_b, pc_e, pc_a)) →\n    regs !! PC = Some (inr ((pc_p, pc_g), pc_b, pc_e, pc_a)) →\n    regs_of (Restrict dst src) ⊆ dom _ regs →\n    {{{ ▷ pc_a ↦ₐ w ∗\n        ▷ [∗ map] k↦y ∈ regs, k ↦ᵣ y }}}\n      Instr Executable @ Ep\n    {{{ regs' retv, RET retv;\n        ⌜ Restrict_spec regs dst src regs' retv ⌝ ∗\n        pc_a ↦ₐ w ∗\n        [∗ map] k↦y ∈ regs', k ↦ᵣ y }}}.\n  Proof.\n    iIntros (Hinstr Hvpc HPC Dregs φ) \"(>Hpc_a & >Hmap) Hφ\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 l1 l2 n) \"Hσ1 /=\". destruct σ1 as [r m]; simpl.\n    iDestruct \"Hσ1\" as \"[Hr Hm]\".\n    iDestruct (gen_heap_valid_inclSepM with \"Hr Hmap\") as %Hregs.\n    have HPC' := regs_lookup_eq _ _ _ HPC.\n    have ? := lookup_weaken _ _ _ _ HPC Hregs.\n    iDestruct (@gen_heap_valid with \"Hm Hpc_a\") as %Hpc_a; auto.\n    iModIntro. iSplitR. by iPureIntro; apply normal_always_head_reducible.\n    iNext. iIntros (e2 σ2 efs Hpstep).\n    apply prim_step_exec_inv in Hpstep as (-> & -> & (c & -> & Hstep)).\n    iSplitR; auto. eapply step_exec_inv in Hstep; eauto.\n\n    specialize (indom_regs_incl _ _ _ Dregs Hregs) as Hri.\n    unfold regs_of in Hri, Dregs.\n    destruct (Hri dst) as [wdst [H'dst Hdst]]. by set_solver+.\n    destruct wdst as [| cdst]; [| destruct_cap cdst].\n    { rewrite /= /RegLocate Hdst in Hstep. destruct src; inv Hstep; simplify_pair_eq.\n      all: iFailWP \"Hφ\" Restrict_fail_dst_noncap. }\n\n    destruct (z_of_argument regs src) as [wsrc|] eqn:Hwsrc;\n      pose proof Hwsrc as H'wsrc; cycle 1.\n    { destruct src as [| r0]; cbn in Hwsrc; [ congruence |].\n      destruct (Hri r0) as [r0v [Hr'0 Hr0]]. by unfold regs_of_argument; set_solver+.\n      rewrite Hr'0 in Hwsrc. destruct r0v as [| cc]; [ congruence | destruct_cap cc].\n      assert (c = Failed ∧ σ2 = (r, m)) as (-> & ->).\n      { rewrite /= /RegLocate Hdst Hr0 in Hstep. by simplify_pair_eq. }\n      iFailWP \"Hφ\" Restrict_fail_src_nonz. }\n    eapply z_of_argument_Some_inv' in Hwsrc; eauto.\n\n    destruct (decide (p = E)).\n    { subst p. cbn in Hstep. rewrite /RegLocate Hdst in Hstep.\n      repeat case_match; inv Hstep; iFailWP \"Hφ\" Restrict_fail_pE. }\n\n    destruct (PermPairFlowsTo (decodePermPair wsrc) (p, g)) eqn:Hflows; cycle 1.\n    { rewrite /= /RegLocate Hdst in Hstep.\n      destruct Hwsrc as [ -> | (r0 & -> & Hr0 & Hr0') ].\n      all: rewrite ?Hr0' Hflows in Hstep.\n      all: repeat case_match; inv Hstep; iFailWP \"Hφ\" Restrict_fail_invalid_perm. }\n\n    assert ((c, σ2) = updatePC (update_reg (r, m) dst (inr (decodePermPair wsrc, b, e, a)))) as HH.\n    { rewrite /= /RegLocate Hdst in Hstep.\n      destruct Hwsrc as [ -> | (r0 & -> & Hr0 & Hr0') ].\n      all: rewrite ?Hr0' Hflows in Hstep.\n      all: repeat case_match; inv Hstep; eauto; congruence. }\n    clear Hstep. rewrite /update_reg /= in HH.\n\n    destruct (incrementPC (<[ dst := inr (decodePermPair wsrc, b, e, a) ]> regs)) eqn:Hregs';\n      pose proof Hregs' as H'regs'; cycle 1.\n    { apply incrementPC_fail_updatePC with (m:=m) in Hregs'.\n      eapply updatePC_fail_incl with (m':=m) in Hregs'.\n      2: by apply lookup_insert_is_Some'; eauto.\n      2: by apply insert_mono; eauto.\n      simplify_pair_eq.\n      iMod ((gen_heap_update_inSepM _ _ dst) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n      iFailWP \"Hφ\" Restrict_fail_PC_overflow. }\n\n    eapply (incrementPC_success_updatePC _ m) in Hregs'\n      as (p' & g' & b' & e' & a'' & a_pc' & HPC'' & Ha_pc' & HuPC & -> & ?).\n    eapply updatePC_success_incl with (m':=m) in HuPC. 2: by eapply insert_mono; eauto.\n    simplify_pair_eq. iFrame.\n    iMod ((gen_heap_update_inSepM _ _ dst) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n    iMod ((gen_heap_update_inSepM _ _ PC) with \"Hr Hmap\") as \"[Hr Hmap]\"; eauto.\n    iFrame. iApply \"Hφ\". iFrame. iPureIntro. econstructor; eauto.\n  Qed.\n\n  (*\n  Lemma wp_restrict_success_reg_PC Ep pc_p pc_g pc_b pc_e pc_a pc_a' w rv z a'  :\n    decodeInstrW w = Restrict PC (inr rv) →\n    isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n    (pc_a + 1)%a = Some pc_a' →\n    PermPairFlowsTo (decodePermPair z) (pc_p,pc_g) = true →\n\n     {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n         ∗ ▷ pc_a ↦ₐ w\n         ∗ ▷ rv ↦ᵣ inl z }}}\n       Instr Executable @ Ep\n       {{{ RET NextIV;\n           PC ↦ᵣ inr (decodePermPair z,pc_b,pc_e,pc_a')\n           ∗ pc_a ↦ₐ w\n           ∗ rv ↦ᵣ inl z }}}.\n   Proof.\n     iIntros (Hinstr Hvpc Hpca' Hflows ϕ) \"(>HPC & >Hpc_a & >Hrv) Hφ\".\n     iDestruct (map_of_regs_2 with \"HPC Hrv\") as \"[Hmap %]\".\n     iApply (wp_Restrict with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n     by unfold regs_of; rewrite !dom_insert; set_solver+.\n     iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n     assert (pc_p ≠ E).\n     { intros ->. inversion Hvpc; subst. naive_solver. }\n\n     destruct Hspec as [| * Hfail].\n     { (* Success *)\n       iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n       destruct (decodePermPair n); simplify_eq. rewrite !insert_insert.\n       iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n     { (* Failure (contradiction) *)\n       destruct Hfail; simplify_map_eq; eauto; try congruence.\n       incrementPC_inv; simplify_map_eq; eauto. destruct e3; try congruence. }\n   Qed.*)\n\n   Lemma wp_restrict_success_reg Ep pc_p pc_g pc_b pc_e pc_a pc_a' w r1 rv p g b e a z  :\n     decodeInstrW w = Restrict r1 (inr rv) →\n     isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n     (pc_a + 1)%a = Some pc_a' →\n     PermPairFlowsTo (decodePermPair z) (p,g) = true →\n     r1 ≠ PC → p ≠ E →\n\n     {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n         ∗ ▷ pc_a ↦ₐ w\n         ∗ ▷ r1 ↦ᵣ inr ((p,g),b,e,a)\n         ∗ ▷ rv ↦ᵣ inl z }}}\n       Instr Executable @ Ep\n       {{{ RET NextIV;\n           PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e, pc_a')\n           ∗ pc_a ↦ₐ w\n           ∗ rv ↦ᵣ inl z\n           ∗ r1 ↦ᵣ inr (decodePermPair z,b,e,a) }}}.\n   Proof.\n     iIntros (Hinstr Hvpc Hpca' Hflows Hne1 Hnp ϕ) \"(>HPC & >Hpc_a & >Hr1 & >Hrv) Hφ\".\n     iDestruct (map_of_regs_3 with \"HPC Hr1 Hrv\") as \"[Hmap (%&%&%)]\".\n     iApply (wp_Restrict with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n     by unfold regs_of; rewrite !dom_insert; set_solver+.\n     iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n\n    destruct Hspec as [| * Hfail].\n    { (* Success *)\n      iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n      rewrite (insert_commute _ PC r1) // insert_insert\n              (insert_commute _ PC r1) // insert_insert.\n      iDestruct (regs_of_map_3 with \"Hmap\") as \"(?&?&?)\"; eauto; iFrame. }\n    { (* Failure (contradiction) *)\n      destruct Hfail; simplify_map_eq; eauto; try congruence.\n      incrementPC_inv; simplify_map_eq; eauto. destruct e4; try congruence.\n      inv Hvpc. naive_solver. }\n   Qed.\n\n   (*\n   Lemma wp_restrict_success_z_PC Ep pc_p pc_g pc_b pc_e pc_a pc_a' w z :\n     decodeInstrW w = Restrict PC (inl z) →\n     isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n     (pc_a + 1)%a = Some pc_a' →\n     PermPairFlowsTo (decodePermPair z) (pc_p,pc_g) = true →\n\n     {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n         ∗ ▷ pc_a ↦ₐ w }}}\n       Instr Executable @ Ep\n     {{{ RET NextIV;\n         PC ↦ᵣ inr (decodePermPair z,pc_b,pc_e,pc_a')\n         ∗ pc_a ↦ₐ w }}}.\n   Proof.\n     iIntros (Hinstr Hvpc Hpca' Hflows ϕ) \"(>HPC & >Hpc_a) Hφ\".\n     iDestruct (map_of_regs_1 with \"HPC\") as \"Hmap\".\n     iApply (wp_Restrict with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n     by rewrite !dom_insert; set_solver+.\n     iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\".\n     iDestruct \"Hspec\" as %Hspec.\n     assert (pc_p ≠ E).\n     { intros ->. inversion Hvpc; subst. naive_solver. }\n\n     destruct Hspec as [ | * Hfail ].\n     { (* Success *)\n       iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n       rewrite !insert_insert. destruct (decodePermPair n); simplify_eq.\n       iApply (regs_of_map_1 with \"Hmap\"). }\n     { (* Failure (contradiction) *)\n       destruct Hfail; simplify_map_eq; eauto. congruence.\n       incrementPC_inv; simplify_map_eq; eauto. congruence. }\n   Qed.*)\n\n   Lemma wp_restrict_success_z Ep pc_p pc_g pc_b pc_e pc_a pc_a' w r1 p g b e a z :\n     decodeInstrW w = Restrict r1 (inl z) →\n     isCorrectPC (inr ((pc_p,pc_g),pc_b,pc_e,pc_a)) →\n     (pc_a + 1)%a = Some pc_a' →\n     PermPairFlowsTo (decodePermPair z) (p,g) = true →\n     r1 ≠ PC → p ≠ E →\n\n     {{{ ▷ PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a)\n         ∗ ▷ pc_a ↦ₐ w\n         ∗ ▷ r1 ↦ᵣ inr ((p,g),b,e,a) }}}\n       Instr Executable @ Ep\n     {{{ RET NextIV;\n         PC ↦ᵣ inr ((pc_p,pc_g),pc_b,pc_e,pc_a')\n         ∗ pc_a ↦ₐ w\n         ∗ r1 ↦ᵣ inr (decodePermPair z,b,e,a) }}}.\n   Proof.\n     iIntros (Hinstr Hvpc Hpca' Hflows Hne1 HpE ϕ) \"(>HPC & >Hpc_a & >Hr1) Hφ\".\n     iDestruct (map_of_regs_2 with \"HPC Hr1\") as \"[Hmap %]\".\n     iApply (wp_Restrict with \"[$Hmap Hpc_a]\"); eauto; simplify_map_eq; eauto.\n     by unfold regs_of; rewrite !dom_insert; set_solver+.\n     iNext. iIntros (regs' retv) \"(#Hspec & Hpc_a & Hmap)\". iDestruct \"Hspec\" as %Hspec.\n     assert (pc_p ≠ E).\n     { intros ->. inversion Hvpc; subst. naive_solver. }\n\n     destruct Hspec as [| * Hfail].\n     { (* Success *)\n       iApply \"Hφ\". iFrame. incrementPC_inv; simplify_map_eq.\n       destruct (decodePermPair n); simplify_eq.\n       rewrite (insert_commute _ PC r1) // insert_insert\n               (insert_commute _ PC r1) // insert_insert.\n       iDestruct (regs_of_map_2 with \"Hmap\") as \"(?&?)\"; eauto; iFrame. }\n     { (* Failure (contradiction) *)\n       destruct Hfail; simplify_map_eq; eauto; try congruence.\n       incrementPC_inv; simplify_map_eq; eauto. \n       destruct e4; try congruence. inv Hvpc. naive_solver. }\n   Qed.\n\nEnd cap_lang_rules.\n", "meta": {"author": "logsem", "repo": "cerise-stack-monotone", "sha": "dff1909f6abc6de99c28d8f12e903b98dd76fb41", "save_path": "github-repos/coq/logsem-cerise-stack-monotone", "path": "github-repos/coq/logsem-cerise-stack-monotone/cerise-stack-monotone-dff1909f6abc6de99c28d8f12e903b98dd76fb41/theories/rules/rules_Restrict.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20422063451479072}}
{"text": "(* Copyright (c) 2017, the Dart project authors.  Please see the AUTHORS file\n * for details. All rights reserved. Use of this source code is governed by a\n * BSD-style license that can be found in the LICENSE file. *)\n\nRequire Import Utf8.\nRequire Import ClassTestTypes.\nRequire Import VoidnessPreservation.\n\n(* Works with multiple parameters, with no changes: Uncomment one of them. *)\nModule MyDynamics :=\n  Dynamics.NormalDynamics.\n\nModule MyVoidnessPreservation :=\n  VoidnessPreservation.VoidnessPreservationBase MyDynamics.\nImport MyVoidnessPreservation.\n\n(* ---------- Voidness Types ---------- *)\n\n(* B<A<1>, Object> *)\nDefinition ct_B_A1_Object :=\n  ndts_cons (B, dts_cons dt_A_void (dts_cons dt_Object dts_nil)) ct_Object.\nDefinition dt_B_A1_Object := dt_class ct_B_A1_Object.\n\n(* B<Object, Object> *)\nDefinition ct_B_ObjectObject :=\n  ndts_cons (B, dts_cons dt_Object (dts_cons dt_Object dts_nil)) ct_Object.\nDefinition dt_B_ObjectObject := dt_class ct_B_ObjectObject.\n\n(* A<A<void>> *)\nDefinition ct_A_A_void := \n  ndts_cons (A, dts_cons dt_A_void dts_nil) ct_Object.\nDefinition dt_A_A_void := dt_class ct_A_A_void.\n\nHint Unfold\n  ct_Object dt_Object ct_A_Object dt_A_Object ct_A_void dt_A_void\n  ct_A_dynamic dt_A_dynamic ct_Iterable_Object dt_Iterable_Object\n  ct_Iterable_void dt_Iterable_void ct_List_Object dt_List_Object\n  ct_List_void dt_List_void ct_A_A_void dt_A_A_void\n  ct_B_A1_Object dt_B_A1_Object ct_B_ObjectObject dt_B_ObjectObject.\n\n(* ---------- Trying out existing examples ---------- *)\n\n(* dynamic <:: dynamic *)\nGoal VoidnessPreserves dt_dynamic dt_dynamic.\n auto.\nQed.\n\n(* dynamic <:: void *)\nGoal VoidnessPreserves dt_dynamic dt_void.\n  auto.\nQed.\n\n(* dynamic <:: variable n *)\nGoal forall n, VoidnessPreserves dt_dynamic (dt_variable n).\n  auto.\nQed.\n\n(* A<Object> <:: A<void> *)\nGoal VoidnessPreserves dt_A_Object dt_A_void.\n  apply vp_class; apply vctsp_cons.\n    apply vctp_some; apply vctps_first; auto.\n  apply vctsp_cons; auto.\n  apply vctp_some. apply vctps_rest. apply vctps_first. auto.\nQed.\n\n(* A<A<void>> <:: A<void> *)\nGoal VoidnessPreserves dt_A_A_void dt_A_void.\n  apply vp_class; apply vctsp_cons; auto.\n    apply vctp_some. apply vctps_first. apply vpp_cons; auto.\n  apply vctsp_cons; auto. apply vctp_some. apply vctps_rest. apply vctps_first. auto.\nQed.\n\n(* Not A<void> <:: A<Object> *)\nGoal ~(VoidnessPreserves dt_A_void dt_A_Object).\n  unfold not. intro H. inversion H. inversion H2. inversion H5.\n    inversion H8. apply H14. reflexivity.\n  inversion H8.\n    inversion H12. inversion H19.\n  inversion H13. inversion H17.\nQed.\n", "meta": {"author": "eernstg", "repo": "coq-voidness", "sha": "727d326633a7759ed4d6f6d7ae26eae900485d01", "save_path": "github-repos/coq/eernstg-coq-voidness", "path": "github-repos/coq/eernstg-coq-voidness/coq-voidness-727d326633a7759ed4d6f6d7ae26eae900485d01/BasicTest.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20422063451479072}}
{"text": "Require Import Axioms.\n\nRequire Import VST.concurrency.sepcomp. Import SepComp.\n\nRequire Import VST.concurrency.pos.\nRequire Import VST.concurrency.stack.\n\nRequire Import ssreflect ssrbool ssrnat ssrfun eqtype seq fintype finfun.\nSet Implicit Arguments.\n\n(*NOTE: because of redefinition of [val], these imports must appear\n  after Ssreflect eqtype.*)\nRequire Import AST.    (*for typ*)\nRequire Import Values. (*for val*)\nRequire Import Globalenvs.\nRequire Import Integers.\n\nRequire Import ZArith.\n\n(* This file is a parametric version of [compcert_linking.v].  See that   *)\n(* file for more information.                                             *)\n\n(* The [CoreLinker] module gives the operational semantics of linking.    *)\n(* It is parameterized by the type of core semantics [Csem] (e.g., effect *)\n(* semantics, coop semantics, vanilla core semantics) used to the dynamic *)\n(* semantics of each translation unit.  Note that each module may still   *)\n(* have its own core type C, function definition type F, etc.             *)\n\n(* Semantics of translation units *)\n\nModule Modsem.\n\nRecord t (M : Type) := mk\n  { F   : Type\n  ; V   : Type\n  ; ge  : Genv.t F V\n  ; C   : Type\n  ; sem : @CoreSemantics (Genv.t F V) C M }.\n\nEnd Modsem.\n\n(* [Cores] are runtime execution units. *)\n\nModule Core. Section core.\n\nVariable M : Type.\nVariable N : pos.\nVariable cores : 'I_N -> Modsem.t M.\n\nImport Modsem.\n\nRecord t := mk\n  { i  : 'I_N\n  ; c  :> (cores i).(C)\n  ; sg : signature }.\n\nDefinition upd (core : t) (newC : (cores core.(i)).(C)) :=\n  {| i := core.(i)\n   ; c := newC\n   ; sg := core.(sg) |}.\n\nEnd core. End Core.\n\nArguments Core.t {M N} cores.\n\nArguments Core.i {M N cores} !t /.\n\nArguments Core.c {M N cores} !t /.\n\nArguments Core.sg {M N cores} !t /.\n\nArguments Core.upd {M N cores} !core _ /.\n\n(* Linking semantics invariants:                                          *)\n(*  -All cores except the topmost one are at_external.                    *)\n(*  -The call stack always contains at least one core.                    *)\n\nSection coreDefs.\n\nImport Modsem.\n\nVariable M : Type.\nVariable N : pos.\nVariable cores : 'I_N -> Modsem.t M.\n\nDefinition atExternal (c: Core.t cores) :=\n  let: (Core.mk i c sg) := c in\n  let: F := (cores i).(F) in\n  let: V := (cores i).(V) in\n  let: C := (cores i).(C) in\n  let: sem := (cores i).(sem) in\n  if @at_external (Genv.t F V) C M sem c is\n    Some (ef, dep_sig, args) then true\n  else false.\n\nDefinition wf_callStack (stk : Stack.t (Core.t cores)) :=\n  [&& all atExternal (STACK.pop stk) & size stk > 0].\n\nEnd coreDefs.\n\nArguments atExternal {M N} cores c.\n\n(** Call stacks are [stack]s satisfying the [wf_callStack] invariant. *)\n\nModule CallStack. Section callStack.\n\nContext {M : Type} {N : pos} (cores : 'I_N -> Modsem.t M).\n\nRecord t : Type := mk\n  { callStack :> Stack.t (Core.t cores)\n  ; _         :  wf_callStack callStack }.\n\nProgram Definition singl (core: Core.t cores) := mk [:: core] _.\n\nSection callStackDefs.\n\nContext (stack : t).\n\nDefinition callStackSize := size stack.(callStack).\n\nLemma callStack_wf : wf_callStack stack.\nProof. by case: stack. Qed.\n\nLemma callStack_ext : all (atExternal cores) (STACK.pop stack).\nProof. by move: callStack_wf; move/andP=> [H1 H2]. Qed.\n\nLemma callStack_size : callStackSize > 0.\nProof. by move: callStack_wf; move/andP=> [H1 H2]. Qed.\n\nLemma callStack_nonempty : STACK.nonempty stack.\nProof. by case: stack=> //; case. Qed.\n\nEnd callStackDefs.\n\nEnd callStack. End CallStack.\n\n(* [Linker.t]                                                             *)\n(*                                                                        *)\n(*  The first two fields of this record are static configuration data:    *)\n(*                                                                        *)\n(*    -[cores] is a function from module id's ('I_n, or integers in the   *)\n(*     range [0..n-1]) to genvs and core semantics, with existentially    *)\n(*     quantified core type [C].                                          *)\n(*                                                                        *)\n(*    -[fn_tbl] maps external function id's to module id's                *)\n(*                                                                        *)\n(*  [stack] is used to maintain a stack of cores, at runtime.             *)\n(*  Parameter [N] is the number of static modules in the program.         *)\n\nModule Linker. Section linker.\n\nVariable M : Type.\nVariable N : pos.\nVariable cores : 'I_N  -> Modsem.t M.\n\nRecord t := mkLinker\n  { fn_tbl : ident -> option 'I_N\n  ; stack  :> CallStack.t cores }.\n\nEnd linker. End Linker.\n\nImport Linker.\n\nNotation linker := Linker.t.\n\nSection linkerDefs.\n\nContext {M : Type} {N : pos} (my_cores : 'I_N -> Modsem.t M) (l : linker N my_cores).\n\nImport CallStack. (*for coercion [callStack]*)\n\nDefinition updStack (newStack : CallStack.t my_cores) :=\n  {| fn_tbl := l.(fn_tbl)\n   ; stack  := newStack |}.\n\n(* [inContext]: The top core on the call stack has a return context  *)\n\nDefinition inContext (l0 : linker N my_cores) := callStackSize l0.(stack) > 1.\n\n(* [updCore]: Replace the top core on the call stack with [newCore]  *)\n\nProgram Definition updCore (newCore: Core.t my_cores) :=\n  updStack (CallStack.mk (STACK.push (STACK.pop l.(stack)) newCore) _).\nNext Obligation. apply/andP; split=>/=; last by []; by apply: callStack_ext. Qed.\n\nLemma updCore_inj newCore newCore' :\n  updCore newCore = updCore newCore' -> newCore=newCore'.\nProof. by case. Qed.\n\nLemma updCore_inj_upd c c1 c2 :\n  updCore (Core.upd c c1) = updCore (Core.upd c c2) -> c1=c2.\nProof.\ncase=> H1; move: (EqdepFacts.eq_sigT_snd H1); move=> <-.\nby rewrite -Eqdep.Eq_rect_eq.eq_rect_eq.\nQed.\n\n(* [pushCore]: Push a new core onto the call stack.                       *)\n(* Succeeds only if all cores are currently at_external.                  *)\n\nLemma stack_push_wf newCore :\n  all (atExternal my_cores) l.(stack).(callStack) ->\n  wf_callStack (SeqStack.updStack (newCore :: l.(stack).(callStack))).\nProof.\nby rewrite/wf_callStack=> H; apply/andP; split.\nQed.\n\nDefinition pushCore\n  (newCore: Core.t my_cores)\n  (pf : all (atExternal my_cores) l.(stack).(callStack)) :=\n  updStack (CallStack.mk (STACK.push l.(stack) newCore) (stack_push_wf _ pf)).\n\n(* [popCore]: Pop the top core on the call stack.                         *)\n(* Succeeds only if the top core is running in a return context.          *)\n\nLemma inContext_wf (stk : Stack.t (Core.t my_cores)) :\n  size stk > 1 -> wf_callStack stk -> wf_callStack (STACK.pop stk).\nProof.\nrewrite/wf_callStack=> H1; move/andP=> [H2 H3]; apply/andP; split.\n- by apply: STACK.all_pop.\n- by move: H1 H2 H3; case: stk.\nQed.\n\nProgram Definition popCore : option (linker N my_cores) :=\n  (match inContext l as pf\n         return (pf = inContext l -> option (linker N my_cores)) with\n    | true => fun pf =>\n        Some (updStack (CallStack.mk (STACK.pop l.(stack))\n                                     (inContext_wf _ _ _)))\n    | false => fun pf => None\n  end) Logic.eq_refl.\nNext Obligation. by apply: callStack_wf. Qed.\n\nDefinition peekCore := STACK.head l.(stack) (callStack_nonempty l.(stack)).\n\nDefinition emptyStack := if l.(stack).(callStack) is [::] then true else false.\n\nImport Modsem.\n\nDefinition initCore (sg: signature) (ix: 'I_N) (v: val) (args: list val)\n  : option (Core.t my_cores):=\n  if @initial_core _ _ _\n       (my_cores ix).(sem)\n       (my_cores ix).(Modsem.ge)\n       v args\n  is Some c then Some (Core.mk _ my_cores ix c sg)\n  else None.\n\nEnd linkerDefs.\n\nNotation ge_ty := (Genv.t unit unit).\n\nArguments updStack {M N} {my_cores} !_ _ /.\n\nArguments updCore {M N} {my_cores} !_ _ /.\n\nArguments pushCore {M N} {my_cores} !l _ _ /.\n\nArguments peekCore {M N} {my_cores} !l /.\n\nArguments emptyStack {M N} {my_cores} !l /.\n\nLemma popCoreI M N my_cores l l' pf :\n  inContext l ->\n  l' = updStack l (CallStack.mk (STACK.pop (CallStack.callStack l)) pf) ->\n  @popCore M N my_cores l = Some l'.\nProof.\nrewrite /popCore.\nmove: (popCore_obligation_1 l); move: (popCore_obligation_2 l).\ncase: (inContext l)=> pf1 pf2 // _ ->.\nf_equal=> //.\nf_equal=> //.\nf_equal=> //.\nby apply: proof_irr.\nQed.\n\nLemma popCoreE M N my_cores l l' :\n  @popCore M N my_cores l = Some l' ->\n  exists pf,\n  [/\\ inContext l\n    & l' = updStack l (CallStack.mk (STACK.pop (CallStack.callStack l)) pf)].\nProof.\nrewrite /popCore.\nmove: (popCore_obligation_1 l); move: (popCore_obligation_2 l).\ncase: (inContext l)=> pf1 pf2 //; case=> <-.\nhave pf: wf_callStack (STACK.pop (CallStack.callStack l)).\n{ case: (andP (pf1 erefl))=> A B; apply/andP; split=> //.\n  by apply: SeqStack.all_pop.\n  by move: (pf2 erefl); clear pf1 pf2 A B; case: l=> /= ?; case; elim. }\nexists pf; split=> //.\nby f_equal; f_equal; apply: proof_irr.\nQed.\n\n(** The linking semantics *)\n\nModule LinkerSem. Section linkerSem.\n\nVariable M : Type.\nVariable N : pos.  (* Number of (compile-time) modules *)\nVariable my_cores : 'I_N  -> Modsem.t M.\nVariable my_fn_tbl: ident -> option 'I_N.\n\n(* [handle id l args] looks up function id [id] in function table         *)\n(* [l.fn_tbl], producing an optional module index [ix : 'I_N].  The index *)\n(* is used to construct a new core to handle the call to function         *)\n(* [id]. The new core is pushed onto the call stack.                      *)\n\nSection handle.\n\nVariables (sg: signature) (id: ident) (l: linker N my_cores) (args: list val).\n\nImport CallStack.\n\nDefinition handle :=\n  (match all (atExternal my_cores) l.(stack).(callStack) as pf\n        return (pf = all (atExternal my_cores) l.(stack).(callStack)\n               -> option (linker N my_cores)) with\n    | true => fun pf =>\n        if l.(fn_tbl) id is Some ix then\n        if Genv.find_symbol (my_cores ix).(Modsem.ge) id is Some bf then\n        if initCore my_cores sg ix (Vptr bf Int.zero) args is Some c\n          then Some (pushCore l c (Logic.eq_sym pf))\n        else None else None else None\n    | false => fun _ => None\n  end) erefl.\n\nEnd handle.\n\nSection handle_lems.\n\nImport CallStack.\n\nLemma handleP sg id l args l' :\n  handle sg id l args = Some l' <->\n  (exists (pf : all (atExternal my_cores) l.(stack).(callStack)) ix bf c,\n     [/\\ l.(fn_tbl) id = Some ix\n       , Genv.find_symbol (my_cores ix).(Modsem.ge) id = Some bf\n       , initCore my_cores sg ix (Vptr bf Int.zero) args = Some c\n       & l' = pushCore l c pf]).\nProof.\nrewrite/handle.\nrewrite /pushCore.\ngeneralize (stack_push_wf l).\npattern (all (atExternal my_cores) (CallStack.callStack (stack l)))\n at 1 2 3 4 5 6 7 8 9.\ncase f: (all _ _); move=> pf.\ncase g: (fn_tbl l id)=> [ix|].\ncase fnd: (Genv.find_symbol _ _)=> [bf|].\ncase h: (initCore _ _ _)=> [c|].\nsplit=> H.\nexists (erefl true),ix,bf,c; split=> //; first by case: H=> <-.\ncase: H=> pf0 []ix0 []bf0 []c0 []; case=> <-.\nrewrite fnd; case=> <-; rewrite h; case=> <- ->.\nby repeat f_equal; apply: proof_irr.\nsplit=> //; case=> pf0 []ix0 []bf0 []c0 [].\nby case=> <-; rewrite fnd; case=> <-; rewrite h.\nsplit=> //; case=> pf0 []ix0 []bf0 []c0 [].\nby case=> <-; rewrite fnd; discriminate.\nsplit=> //.\nby case=> pf0 []ix0 []bf0 []c0 []; discriminate.\nsplit=> //.\nby case=> pf0 []ix0 []bf0 []c0 []; discriminate.\nQed.\n\nEnd handle_lems.\n\nDefinition main_sig := mksignature nil (Some Tint) cc_default.\n\nDefinition initial_core (ge: ge_ty) (v: val) (args: list val)\n  : option (linker N my_cores) :=\n  if v is Vptr bf ofs then\n  if Int.eq ofs Int.zero then\n  if Genv.invert_symbol ge bf is Some id then\n  if my_fn_tbl id is Some ix then\n  if initCore my_cores main_sig ix (Vptr bf Int.zero) args is Some c\n  then Some (mkLinker my_fn_tbl (CallStack.singl c))\n  else None else None else None else None else None.\n\n(* Functions suffixed w/ 0 always operate on the running core on the (top *)\n(* of the) call stack.                                                    *)\n\nDefinition at_external0 (l: linker N my_cores) :=\n  let: c   := peekCore l in\n  let: ix  := c.(Core.i) in\n  let: sem := (my_cores ix).(Modsem.sem) in\n  let: F   := (my_cores ix).(Modsem.F) in\n  let: V   := (my_cores ix).(Modsem.V) in\n    @at_external (Genv.t F V) _ _ sem (Core.c c).\n\nArguments at_external0 !l.\n\nRequire Import VST.concurrency.val_casted. (*for val_has_type_func*)\n\nDefinition halted0 (l: linker N my_cores) :=\n  let: c   := peekCore l in\n  let: ix  := c.(Core.i) in\n  let: sg  := c.(Core.sg) in\n  let: sem := (my_cores ix).(Modsem.sem) in\n  let: F   := (my_cores ix).(Modsem.F) in\n  let: V   := (my_cores ix).(Modsem.V) in\n    if @halted (Genv.t F V) _ _ sem (Core.c c) is Some v then\n      if val_casted.val_has_type_func v (proj_sig_res sg) then Some v\n      else None\n    else None.\n\nArguments halted0 !l.\n\n(* [corestep0] lifts a corestep of the runing core to a corestep of the   *)\n(* whole program semantics.                                               *)\n\nDefinition corestep0\n  (l: linker N my_cores) (m: M) (l': linker N my_cores) (m': M) :=\n  let: c   := peekCore l in\n  let: ix  := c.(Core.i) in\n  let: sem := (my_cores ix).(Modsem.sem) in\n  let: F   := (my_cores ix).(Modsem.F) in\n  let: V   := (my_cores ix).(Modsem.V) in\n  let: ge  := (my_cores ix).(Modsem.ge) in\n    exists c',\n      @corestep (Genv.t F V) _ _ sem ge (Core.c c) m c' m'\n   /\\ l' = updCore l (Core.upd c c').\n\nArguments corestep0 !l m l' m'.\n\nDefinition fun_id (ef: external_function) : option ident :=\n  if ef is (EF_external id sig) then Some id else None.\n\n(* The linker is [at_external] whenever the top core is [at_external] and *)\n(* the [id] of the called external function isn't handleable by any       *)\n(* compilation unit.                                                      *)\n\nDefinition at_external (l: linker N my_cores) :=\n  if at_external0 l is Some (ef, dep_sig, args)\n    then if fun_id ef is Some id then\n         if fn_tbl l id is None then Some (ef, dep_sig, args) else None\n         else Some (ef, dep_sig, args)\n  else at_external0 l.\n\nDefinition after_external (mv: option val) (l: linker N my_cores) :=\n  let: c   := peekCore l in\n  let: ix  := c.(Core.i) in\n  let: sem := (my_cores ix).(Modsem.sem) in\n  let: F   := (my_cores ix).(Modsem.F) in\n  let: V   := (my_cores ix).(Modsem.V) in\n  let: ge  := (my_cores ix).(Modsem.ge) in\n    if @after_external (Genv.t F V) _ _ sem mv (Core.c c)\n      is Some c' then Some (updCore l (Core.upd c c'))\n    else None.\n\n(* The linker is [halted] when the last core on the call stack is halted. *)\n\nDefinition halted (l: linker N my_cores) :=\n  if ~~inContext l then\n  if halted0 l is Some rv then Some rv\n  else None else None.\n\n(* Corestep relation of linking semantics *)\n\nDefinition corestep\n  (l: linker N my_cores) (m: M)\n  (l': linker N my_cores) (m': M) :=\n\n  (** 1- The running core takes a step, or *)\n  corestep0 l m l' m' \\/\n\n  (** 2- We're in a function call context. In this case, the running core is either *)\n  (m=m'\n   /\\ ~corestep0 l m l' m'\n   /\\\n      (** 3- at_external, in which case we push a core onto the stack to handle\n         the external function call (or this is not possible because no module\n         handles the external function id, in which case the entire linker is\n         at_external) *)\n\n      if at_external0 l is Some (ef, dep_sig, args) then\n      if fun_id ef is Some id then\n      if handle (ef_sig ef) id l args is Some l'' then l'=l'' else False else False\n      else\n\n      (** 4- or halted, in which case we pop the halted core from the call stack\n         and inject its return value into the caller's corestate. *)\n\n      if inContext l then\n      if halted0 l is Some rv then\n      if popCore l is Some l0 then\n      if after_external (Some rv) l0 is Some l'' then l'=l''\n      else False else False else False\n\n     else False).\n\nInductive Corestep : linker N my_cores -> M\n                  -> linker N my_cores -> M -> Prop :=\n| Corestep_step :\n  forall l m c' m',\n  let: c     := peekCore l in\n  let: c_ix  := Core.i c in\n  let: c_ge  := Modsem.ge (my_cores c_ix) in\n  let: c_sem := Modsem.sem (my_cores c_ix) in\n    semantics.corestep c_sem c_ge (Core.c c) m c' m' ->\n    Corestep l m (updCore l (Core.upd (peekCore l) c')) m'\n\n| Corestep_call :\n  forall (l : linker N my_cores) m ef dep_sig args id bf d_ix d\n         (pf : all (atExternal my_cores) (CallStack.callStack l)),\n\n  let: c := peekCore l in\n  let: c_ix  := Core.i c in\n  let: c_ge  := Modsem.ge (my_cores c_ix) in\n  let: c_sem := Modsem.sem (my_cores c_ix) in\n\n  semantics.at_external c_sem (Core.c c) = Some (ef,dep_sig,args) ->\n  fun_id ef = Some id ->\n  fn_tbl l id = Some d_ix ->\n  Genv.find_symbol (my_cores d_ix).(Modsem.ge) id = Some bf ->\n\n  let: d_ge  := Modsem.ge (my_cores d_ix) in\n  let: d_sem := Modsem.sem (my_cores d_ix) in\n\n  semantics.initial_core d_sem d_ge (Vptr bf Int.zero) args = Some d ->\n  Corestep l m (pushCore l (Core.mk _ _ _ d (ef_sig ef)) pf) m\n\n| Corestep_return :\n  forall (l : linker N my_cores) l'' m rv d',\n\n  1 < CallStack.callStackSize (stack l) ->\n\n  let: c  := peekCore l in\n  let: c_ix  := Core.i c in\n  let: c_sg  := Core.sg c in\n  let: c_ge  := Modsem.ge (my_cores c_ix) in\n  let: c_sem := Modsem.sem (my_cores c_ix) in\n\n  popCore l = Some l'' ->\n\n  let: d  := peekCore l'' in\n  let: d_ix  := Core.i d in\n  let: d_ge  := Modsem.ge (my_cores d_ix) in\n  let: d_sem := Modsem.sem (my_cores d_ix) in\n\n  semantics.halted c_sem (Core.c c) = Some rv ->\n  val_has_type_func rv (proj_sig_res c_sg)=true ->\n  semantics.after_external d_sem (Some rv) (Core.c d) = Some d' ->\n  Corestep l m (updCore l'' (Core.upd d d')) m.\n\nLemma CorestepE l m l' m' :\n  Corestep l m l' m' ->\n  corestep l m l' m'.\nProof.\ninversion 1; subst; rename H0 into A; rename H into B.\nby left; exists c'; split.\nright; split=> //.\nsplit=> //.\nrewrite /corestep0=> [][]c' []step.\nby rewrite /= (corestep_not_at_external _ _ _ _ _ _ step) in A.\nrewrite /= in A.\nrewrite /inContext /at_external0 A H1.\ncase e: (handle _ _ _)=> //[l'|].\nmove: e; case/handleP=> pf' []ix' []bf' []c []C G D ->.\nmove: D; rewrite /initCore.\nrewrite H2 in C; case: C=> eq; subst ix'.\nrewrite G in H3; case: H3=> ->.\nby rewrite /= in H4; rewrite H4; case=> <-; f_equal; apply: proof_irr.\nmove: e; rewrite/handle /pushCore.\ngeneralize (stack_push_wf l).\npattern (all (atExternal my_cores) (CallStack.callStack (stack l)))\n at 1 2 3 4 5 6 7.\ncase f: (all _ _)=> pf'.\nrewrite /= in H4; rewrite H2 H3 /initCore H4; discriminate.\nby rewrite pf in f.\nright; split=> //.\nsplit=> //.\nrewrite /corestep0=> [][]c' []step.\nby rewrite /= (corestep_not_halted _ _ _ _ _ _ step) in H2.\nhave at_ext:\n  semantics.at_external\n    (Modsem.sem (my_cores (Core.i (peekCore l))))\n    (Core.c (peekCore l)) = None.\n{ case: (@at_external_halted_excl _ _ _\n         (Modsem.sem (my_cores (Core.i (peekCore l))))\n         (Core.c (peekCore l)))=> //.\n  by rewrite /= in H2; rewrite H2. }\nrewrite /= in at_ext; rewrite /inContext A /at_external0 H1 at_ext.\nby rewrite /= in H2 H4; rewrite /halted0 H2 /after_external H3 H4.\nQed.\n\nLemma CorestepI l m l' m' :\n  corestep l m l' m' ->\n  Corestep l m l' m'.\nProof.\ncase.\ncase=> c []step ->.\nby apply: Corestep_step.\ncase=> <-.\ncase=> nstep.\ncase atext: (at_external0 _)=> [[[ef dep_sig] args]|//].\ncase funid: (fun_id ef)=> [id|//].\ncase hdl:   (handle (ef_sig ef) id l args)=> [l''|//] ->.\nmove: hdl; case/handleP=> pf []ix []bf []c []fntbl genv init ->.\nmove: init; rewrite /initCore.\ncase init: (semantics.initial_core _ _ _)=> [c'|//]; case=> <-.\nby apply: (@Corestep_call _ _ ef dep_sig args id bf).\ncase inCtx: (inContext _)=> //.\ncase hlt: (halted0 _)=> [rv|//].\ncase pop: (popCore _)=> [c|//].\ncase aft: (after_external _ _)=> [l''|//] ->.\nmove: aft; rewrite /after_external.\ncase aft: (semantics.after_external _ _)=> [c''|//].\nrewrite /halted0 in hlt; move: hlt.\ncase hlt: (semantics.halted _)=> //.\ncase oval: (val_has_type_func _ _)=> //; case=> Heq. subst. case=> <-.\nby apply: (@Corestep_return _ _ _ rv c'').\nQed.\n\nLemma CorestepP l m l' m' :\n  corestep l m l' m' <-> Corestep l m l' m'.\nProof. by split; [apply: CorestepI | apply: CorestepE]. Qed.\n\nLemma corestep_not_at_external0 m c m' c' :\n  corestep0 c m c' m' -> at_external0 c = None.\nProof. by move=>[]newCore []H1 H2; apply corestep_not_at_external in H1. Qed.\n\nLemma at_external_halted_excl0 c : at_external0 c = None \\/ halted0 c = None.\nProof.\ncase: (@at_external_halted_excl _ _ _\n        (Modsem.sem (my_cores (Core.i (peekCore c))))\n        (Core.c (peekCore c))).\nby rewrite /at_external0=> ->; left.\nby rewrite /halted0=> ->; right.\nQed.\n\nLemma corestep_not_halted0 m c m' c' : corestep0 c m c' m' -> halted c = None.\nProof.\nmove=> []newCore []H1 H2; rewrite/halted.\ncase Hcx: (~~ inContext _)=>//; case Hht: (halted0 _)=>//.\nby move: Hht; rewrite/halted0; apply corestep_not_halted in H1; rewrite /= H1.\nQed.\n\nLemma corestep_not_halted0' m c m' c' : corestep0 c m c' m' -> halted0 c = None.\nProof.\nmove=> []newCore []H1 H2; rewrite/halted.\ncase Hht: (halted0 _)=>//.\nby move: Hht; rewrite/halted0; apply corestep_not_halted in H1; rewrite /= H1.\nQed.\n\nLemma corestep_not_at_external (ge : ge_ty) m c m' c' :\n  corestep c m c' m' -> at_external c = None.\nProof.\nrewrite/corestep/at_external.\nmove=> [H|[_ [_ H]]]; first by move: H; move/corestep_not_at_external0=> /= ->.\nmove: H; case Heq: (at_external0 c)=>[[[ef sig] args]|//].\nmove: Heq; case: (at_external_halted_excl0 c)=> [H|H]; first by rewrite H.\nmove=> H2; case: (fun_id ef)=>// id; case hdl: (handle _ _ _)=> [a|].\nby move: hdl; case/handleP=> ? []? []? []? []->.\nby [].\nQed.\n\nLemma at_external0_not_halted c x :\n  at_external0 c = Some x -> halted c = None.\nProof.\ncase: (at_external_halted_excl0 c); rewrite/at_external0/halted.\nby case Heq: (peekCore c)=>//[a] ->.\nmove=> H; case Heq: (peekCore c)=>//[a].\nby case Hcx: (~~ inContext _)=>//; rewrite H.\nQed.\n\nLemma corestep_not_halted (ge : ge_ty) m c m' c' :\n  corestep c m c' m' -> halted c = None.\nProof.\nrewrite/corestep.\nmove=> [H|[_ [_ H]]]; first by move: H; move/corestep_not_halted0.\nmove: H; case Hat: (at_external0 _)=> [x|//].\nby rewrite (at_external0_not_halted _ Hat).\nby rewrite /halted; case Hcx: (inContext _).\nQed.\n\nLemma at_external_halted_excl c :\n  at_external c = None \\/ halted c = None.\nProof.\nrewrite/at_external/halted; case Hat: (at_external0 c)=>//;\nfirst by right; apply: (at_external0_not_halted _ Hat).\nby left.\nQed.\n\nDefinition coresem : CoreSemantics ge_ty (linker N my_cores) M :=\n  Build_CoreSemantics ge_ty (linker N my_cores) M\n    initial_core\n    at_external\n    after_external\n    halted\n    (fun _ : ge_ty => corestep)\n    corestep_not_at_external\n    corestep_not_halted\n    at_external_halted_excl.\n\nEnd linkerSem. End LinkerSem.\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/concurrency/linking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20422063451479072}}
{"text": "\nRequire Import Coq.Setoids.Setoid Coq.Classes.Morphisms.\nDefinition f (v : option nat) := match v with\n                                 | Some k => Some k\n                                 | None => None\n                                 end.\n\nAxioms F G : (option nat -> option nat) -> Prop.\nAxiom FG : forall f, f None = None -> F f = G f.\n\nAxiom admit : forall {T}, T.\n\nExisting Instance eq_Reflexive.\n\nGlobal Instance foo (A := nat)\n  : Proper ((pointwise_relation _ eq)\n              ==> eq ==> forall_relation (fun _ => Basics.flip Basics.impl))\n           (@option_rect A (fun _ => Prop)) | 0.\nexact admit.\nQed.\n\nGlobal Instance bar (A := nat)\n  : Proper ((pointwise_relation _ eq)\n              ==> eq ==> eq ==> Basics.flip Basics.impl)\n           (@option_rect A (fun _ => Prop)) | 0.\nexact admit.\nQed.\n\nGoal forall k, option_rect (fun _ => Prop) (fun v : nat => v = v /\\ F f) True k.\nProof.\n  intro.\n  pose proof (_ : (Proper (_ ==> eq ==> _) and)).\n  setoid_rewrite (FG _ _); [ | reflexivity.. ].\n  Undo.\n  setoid_rewrite (FG _ eq_refl). (* Error: Tactic failure: setoid rewrite failed: Nothing to rewrite. in 8.5 *) Admitted.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/closed/4754.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.32423541204073586, "lm_q1q2_score": 0.20419522932456263}}
{"text": "Require Import Lia.\nRequire Import RelationClasses.\n\nFrom sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\n\nFrom PromisingLib Require Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import PromiseConsistent.\nRequire Import ReorderPromise.\nRequire Import ReorderPromises.\nRequire Import MemoryReorder.\nRequire Import MemoryFacts.\nRequire Import Pred.\nRequire Import MemoryProps.\n\nSet Implicit Arguments.\n\n\nLemma reorder_read_cancel\n      lc0 mem0\n      lc1 mem1\n      lc2\n      loc1 from1 to1 msg1\n      loc2 to2 val2 released2 ord2\n      (STEP1: Local.read_step lc0 mem0 loc2 to2 val2 released2 ord2 lc1)\n      (STEP2: Local.promise_step lc1 mem0 loc1 from1 to1 msg1 lc2 mem1 Memory.op_kind_cancel)\n  :\n    exists lc1',\n      (<<STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1' mem1 Memory.op_kind_cancel>>) /\\\n      (<<STEP2: Local.read_step lc1' mem1 loc2 to2 val2 released2 ord2 lc2>>).\nProof.\n  inv STEP1. inv STEP2.\n  hexploit MemoryFacts.promise_get1_diff; eauto.\n  { ii. clarify. ss. inv PROMISE.\n    eapply Memory.remove_get0 in MEM. des. clarify. }\n  i. des. esplits; eauto.\nQed.\n\nLemma remove_non_synch_loc loc0 prom0 loc1 from to msg prom1\n      (NONSYNCH: Memory.nonsynch_loc loc0 prom0)\n      (REMOVE: Memory.remove prom0 loc1 from to msg prom1)\n  :\n    Memory.nonsynch_loc loc0 prom1.\nProof.\n  ii. erewrite Memory.remove_o in GET; eauto.\n  des_ifs. exploit NONSYNCH; eauto.\nQed.\n\nLemma remove_non_synch prom0 loc from to msg prom1\n      (NONSYNCH: Memory.nonsynch prom0)\n      (REMOVE: Memory.remove prom0 loc from to msg prom1)\n  :\n    Memory.nonsynch prom1.\nProof.\n  ii. erewrite Memory.remove_o in GET; eauto.\n  des_ifs. exploit NONSYNCH; eauto.\nQed.\n\nLemma reorder_write_cancel\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2 mem2\n      loc1 from1 to1 msg1\n      loc2 from2 to2 val2 releasedm2 released2 ord2 kind2\n      (STEP1: Local.write_step lc0 sc0 mem0 loc2 from2 to2 val2 releasedm2 released2 ord2 lc1 sc2 mem1 kind2)\n      (STEP2: Local.promise_step lc1 mem1 loc1 from1 to1 msg1 lc2 mem2 Memory.op_kind_cancel)\n  :\n    exists lc1' mem1',\n      (<<STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1' mem1' Memory.op_kind_cancel>>) /\\\n      (<<STEP2: Local.write_step lc1' sc0 mem1' loc2 from2 to2 val2 releasedm2 released2 ord2 lc2 sc2 mem2 kind2>>).\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit MemoryReorder.write_cancel; [exact WRITE| exact PROMISE|]. i. des.\n  esplits.\n  - econs; eauto.\n    inv CANCEL1. eapply Memory.cancel_closed_message; eauto.\n  - econs; eauto.\n    i. hexploit RELEASE; eauto. i. inv CANCEL1.\n    eapply remove_non_synch_loc; eauto.\nQed.\n\nLemma reorder_write_na_cancel\n      lc0 sc0 mem0\n      lc1 mem1\n      lc2 sc2 mem2\n      loc1 from1 to1 msg1\n      loc2 from2 to2 val2 ord2 msgs2 kinds2 kind2\n      (STEP1: Local.write_na_step lc0 sc0 mem0 loc2 from2 to2 val2 ord2 lc1 sc2 mem1 msgs2 kinds2 kind2)\n      (STEP2: Local.promise_step lc1 mem1 loc1 from1 to1 msg1 lc2 mem2 Memory.op_kind_cancel)\n  :\n    exists lc1' mem1',\n      (<<STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1' mem1' Memory.op_kind_cancel>>) /\\\n      (<<STEP2: Local.write_na_step lc1' sc0 mem1' loc2 from2 to2 val2 ord2 lc2 sc2 mem2 msgs2 kinds2 kind2>>).\nProof.\n  inv STEP1. inv STEP2. ss.\n  exploit MemoryReorder.write_na_cancel; [exact WRITE|exact PROMISE|]. i. des.\n  esplits.\n  - econs; eauto.\n    inv CANCEL1. eapply Memory.cancel_closed_message; eauto.\n  - econs; eauto.\nQed.\n\nLemma reorder_fence_cancel\n      lc0 mem0\n      lc1 mem1\n      lc2\n      loc1 from1 to1 msg1\n      ord1 ord2 sc0 sc1\n      (STEP1: Local.fence_step lc0 sc0 ord1 ord2 lc1 sc1)\n      (STEP2: Local.promise_step lc1 mem0 loc1 from1 to1 msg1 lc2 mem1 Memory.op_kind_cancel)\n  :\n    exists lc1',\n      (<<STEP1: Local.promise_step lc0 mem0 loc1 from1 to1 msg1 lc1' mem1 Memory.op_kind_cancel>>) /\\\n      (<<STEP2: Local.fence_step lc1' sc0 ord1 ord2 lc2 sc1>>).\nProof.\n  inv STEP1. inv STEP2. ss. esplits.\n  - econs; eauto.\n  - econs; eauto.\n    + inv PROMISE. i. eapply remove_non_synch; eauto.\n    + i. ss. subst. erewrite PROMISES in *; auto.\n      inv PROMISE. eapply Memory.remove_get0 in PROMISES0. des.\n      erewrite Memory.bot_get in *. ss.\nQed.\n\nLemma reorder_promise_consistent_cancel\n      lc1 mem1 loc from to msg lc2 mem2\n      (CONS: Local.promise_consistent lc1)\n      (STEP: Local.promise_step lc1 mem1 loc from to msg lc2 mem2 Memory.op_kind_cancel):\n  (<<CONS: Local.promise_consistent lc2>>).\nProof.\n  inv STEP. inv PROMISE. ii. ss.\n  revert PROMISE. erewrite Memory.remove_o; eauto. condtac; ss. eauto.\nQed.\n\nLemma reorder_failure_cancel\n      lc1 mem1\n      lc2 mem2\n      loc1 from1 to1 msg1\n      (STEP1: Local.failure_step lc1)\n      (STEP2: Local.promise_step lc1 mem1 loc1 from1 to1 msg1 lc2 mem2 Memory.op_kind_cancel):\n  (<<STEP2: Local.failure_step lc2>>).\nProof.\n  inv STEP1. econs.\n  eapply reorder_promise_consistent_cancel; eauto.\nQed.\n\nLemma reorder_is_racy_cancel\n      lc1 mem1\n      lc2 mem2\n      loc2 to2 ord2\n      loc1 from1 to1 msg1\n      (RACY: Local.is_racy lc1 mem1 loc2 to2 ord2)\n      (STEP: Local.promise_step lc1 mem1 loc1 from1 to1 msg1 lc2 mem2 Memory.op_kind_cancel):\n  (<<RACY: Local.is_racy lc2 mem2 loc2 to2 ord2>>).\nProof.\n  inv RACY. inv STEP. inv PROMISE.\n  exploit Memory.remove_get1; try exact GET; eauto. i. des.\n  { subst.\n    exploit Memory.remove_get0; try exact PROMISES. i. des. congr.\n  }\n  econs; eauto. s.\n  erewrite Memory.remove_o; eauto. condtac; ss.\nQed.\n\nLemma reorder_racy_read_cancel\n      lc1 mem1\n      lc2 mem2\n      loc2 to2 val2 ord2\n      loc1 from1 to1 msg1\n      (STEP1: Local.racy_read_step lc1 mem1 loc2 to2 val2 ord2)\n      (STEP2: Local.promise_step lc1 mem1 loc1 from1 to1 msg1 lc2 mem2 Memory.op_kind_cancel):\n  (<<STEP2: Local.racy_read_step lc2 mem2 loc2 to2 val2 ord2>>).\nProof.\n  inv STEP1. econs.\n  eapply reorder_is_racy_cancel; eauto.\nQed.\n\nLemma reorder_racy_write_cancel\n      lc1 mem1\n      lc2 mem2\n      loc2 to2 ord2\n      loc1 from1 to1 msg1\n      (STEP1: Local.racy_write_step lc1 mem1 loc2 to2 ord2)\n      (STEP2: Local.promise_step lc1 mem1 loc1 from1 to1 msg1 lc2 mem2 Memory.op_kind_cancel):\n  (<<STEP2: Local.racy_write_step lc2 mem2 loc2 to2 ord2>>).\nProof.\n  inv STEP1. econs.\n  - eapply reorder_is_racy_cancel; eauto.\n  - eapply reorder_promise_consistent_cancel; eauto.\nQed.\n\nLemma reorder_racy_update_cancel\n      lc1 mem1\n      lc2 mem2\n      loc2 to2 ordr2 ordw2\n      loc1 from1 to1 msg1\n      (STEP1: Local.racy_update_step lc1 mem1 loc2 to2 ordr2 ordw2)\n      (STEP2: Local.promise_step lc1 mem1 loc1 from1 to1 msg1 lc2 mem2 Memory.op_kind_cancel):\n  (<<STEP2: Local.racy_update_step lc2 mem2 loc2 to2 ordr2 ordw2>>).\nProof.\n  inv STEP1.\n  - econs 1; eauto.\n    eapply reorder_promise_consistent_cancel; eauto.\n  - econs 2; eauto.\n    eapply reorder_promise_consistent_cancel; eauto.\n  - econs 3; eauto.\n    + eapply reorder_is_racy_cancel; eauto.\n    + eapply reorder_promise_consistent_cancel; eauto.\nQed.\n\nLemma reorder_step_cancel\n      lang\n      pf1 pf2 e1 e2 th0 th1 th2\n      (STEP1: @Thread.step lang pf1 e1 th0 th1)\n      (STEP2: Thread.step pf2 e2 th1 th2)\n      (CANCEL: ThreadEvent.is_cancel e2):\n  (exists th1',\n    (<<STEP1: Thread.step pf2 e2 th0 th1'>>) /\\\n    (<<STEP2: Thread.step pf1 e1 th1' th2>>)) \\/\n  (th2 = th0 /\\ <<RESERVE: ThreadEvent.is_reserve e1>>)\n.\nProof.\n  unfold ThreadEvent.is_cancel in *. des_ifs.\n  inv STEP2; inv STEP; [|inv LOCAL]. ss.\n  inv STEP1; ss.\n  - inv STEP. ss. exploit reorder_promise_promise_cancel; eauto.\n    i. des; clarify; eauto.\n    left. esplits.\n    + econs 1. econs; eauto.\n    + econs 1. econs; eauto.\n  - left. inv STEP. ss. inv LOCAL0; ss.\n    + esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto; ss.\n    + exploit reorder_read_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto; ss.\n    + exploit reorder_write_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto; ss.\n    + exploit reorder_write_cancel; eauto. i. des.\n      exploit reorder_read_cancel; eauto. i. des.\n      esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto; ss.\n    + exploit reorder_fence_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto; ss.\n    + exploit reorder_fence_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto; ss.\n    + exploit reorder_failure_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto.\n    + exploit reorder_write_na_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto.\n    + exploit reorder_racy_read_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto.\n    + exploit reorder_racy_write_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto.\n    + exploit reorder_racy_update_cancel; eauto. i. des. esplits.\n      * econs 1. econs; eauto.\n      * econs 2. econs; eauto.\nQed.\n\nLemma reorder_step_cancels\n      lang\n      pf e1 th0 th1 th2\n      (STEP1: Thread.step pf e1 th0 th1)\n      (STEPS2: rtc (@Thread.cancel_step lang) th1 th2)\n  :\n    (exists th1',\n        (<<STEPS1: rtc (@Thread.cancel_step lang) th0 th1'>>) /\\\n        (<<STEP2: Thread.step pf e1 th1' th2>>)) \\/\n    ((<<STEPS1: rtc (@Thread.cancel_step lang) th0 th2>>) /\\ (<<RESERVE: ThreadEvent.is_reserve e1>>))\n.\nProof.\n  ginduction STEPS2; i.\n  - esplits; eauto.\n  - inv H. exploit reorder_step_cancel.\n    { eapply STEP1. }\n    { eapply STEP. }\n    { ss. }\n    i. des.\n    { exploit IHSTEPS2; eauto. i. des.\n      - left. esplits.\n        + econs 2.\n          * splits; auto. econs; eauto.\n          * eauto.\n        + eauto.\n      - right. splits; auto. econs 2; eauto. econs; eauto.\n    }\n    { subst. right. esplits; eauto. }\nQed.\n\nLemma reorder_opt_step_cancels\n      lang\n      e1 th0 th1 th2\n      (STEP1: Thread.opt_step e1 th0 th1)\n      (STEPS2: rtc (@Thread.cancel_step lang) th1 th2)\n  :\n    (exists th1',\n        (<<STEPS1: rtc (@Thread.cancel_step lang) th0 th1'>>) /\\\n        (<<STEP2: Thread.opt_step e1 th1' th2>>)) \\/\n    ((<<STEPS1: rtc (@Thread.cancel_step lang) th0 th2>>) /\\ (<<RESERVE: ThreadEvent.is_reserve e1>>)).\nProof.\n  inv STEP1.\n  { left. esplits; eauto. econs 1. }\n  { exploit reorder_step_cancels; eauto. i. des.\n    { left. esplits; eauto. econs 2; eauto. }\n    { right. esplits; eauto. }\n  }\nQed.\n\nLemma reorder_opt_step_cancels2\n      lang\n      e1 th0 th1 th2\n      (STEP1: Thread.opt_step e1 th0 th1)\n      (STEPS2: rtc (@Thread.cancel_step lang) th1 th2)\n  :\n    exists th1' e1',\n      (<<STEPS1: rtc (@Thread.cancel_step lang) th0 th1'>>) /\\\n      (<<STEP2: Thread.opt_step e1' th1' th2>>) /\\\n      __guard__(e1' = e1 \\/ e1' = ThreadEvent.silent /\\ <<RESERVE: ThreadEvent.is_reserve e1>>).\nProof.\n  unguard. inv STEP1.\n  { esplits.\n    { eauto. }\n    { econs 1. }\n    { auto. }\n  }\n  { exploit reorder_step_cancels; eauto. i. des.\n    { esplits; eauto. econs 2; eauto. }\n    { esplits; eauto. econs 1; eauto. }\n  }\nQed.\n\nLemma steps_cancels_not_cancels\n      P lang th0 th2\n      (STEPS: rtc (tau (@pred_step P lang)) th0 th2)\n  :\n    exists th1,\n      (<<STEPS1: rtc (@Thread.cancel_step _) th0 th1>>) /\\\n      (<<STEPS2: rtc (tau (@pred_step (P /1\\ fun e => ~ ThreadEvent.is_cancel e) _)) th1 th2>>)\n.\nProof.\n  ginduction STEPS; i.\n  - esplits; eauto.\n  - inv H. inv TSTEP. inv STEP.\n    hexploit IHSTEPS; eauto. i. des.\n    destruct (classic (ThreadEvent.is_cancel e)).\n    + unfold ThreadEvent.is_cancel in H. des_ifs. esplits.\n      * econs 2.\n        { econs; eauto. }\n        { eapply STEPS1. }\n      * eapply STEPS2.\n    + exploit reorder_step_cancels.\n      { eapply STEP0. }\n      { eapply STEPS1. }\n      i. des; eauto. esplits.\n      * eauto.\n      * econs 2.\n        { econs; eauto. econs; eauto. econs; eauto. }\n        { eauto. }\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-seq-coq", "sha": "4c962f1810d6a55b19d13b1350e18c80113b146d", "save_path": "github-repos/coq/snu-sf-promising-seq-coq", "path": "github-repos/coq/snu-sf-promising-seq-coq/promising-seq-coq-4c962f1810d6a55b19d13b1350e18c80113b146d/src/prop/ReorderCancel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.35577490717496246, "lm_q1q2_score": 0.20410038215969692}}
{"text": "(** * Push-Button Synthesis of Word-By-Word Montgomery *)\nRequire Import Coq.Strings.String.\nRequire Import Coq.micromega.Lia.\nRequire Import Coq.ZArith.ZArith.\nRequire Import Coq.MSets.MSetPositive.\nRequire Import Coq.Lists.List.\nRequire Import Coq.QArith.QArith_base Coq.QArith.Qround.\nRequire Import Coq.Program.Tactics. (* For WBW Montgomery proofs *)\nRequire Import Coq.derive.Derive.\nRequire Import Crypto.Util.ErrorT.\nRequire Import Crypto.Util.ListUtil.\nRequire Import Crypto.Util.ListUtil.FoldBool.\nRequire Import Crypto.Util.Strings.Decimal.\nRequire Import Crypto.Util.ZRange.\nRequire Import Crypto.Util.ZUtil.Definitions.\nRequire Import Crypto.Util.ZUtil.Zselect.\nRequire Import Crypto.Util.ZUtil.Tactics.LtbToLt.\nRequire Import Crypto.Util.ZUtil.ModInv. (* Only needed for WBW Montgomery *)\nRequire Import Crypto.Util.ZUtil.Modulo. (* Only needed for WBW Montgomery proofs *)\nRequire Import Crypto.Util.ZUtil.Le. (* Only needed for WBW Montgomery proofs *)\nRequire Import Crypto.Util.Prod. (* For WBW Montgomery proofs *)\nRequire Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo. (* For WBW montgomery proofs *)\nRequire Import Crypto.Util.ZUtil.Tactics.RewriteModSmall. (* For WBW montgomery proofs *)\nRequire Import Crypto.Util.ZUtil.Div. (* For WBW Montgomery proofs *)\nRequire Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem. (* For WBW Montgomery proofs *)\nRequire Import Crypto.Util.ZUtil.Ones. (* For WBW montgomery proofs *)\nRequire Import Crypto.Util.ZUtil.Shift. (* For WBW montgomery proofs *)\nRequire Import Crypto.Util.ZUtil.ModExp.\nRequire Import Crypto.Util.Tactics.HasBody.\nRequire Import Crypto.Util.Tactics.Head.\nRequire Import Crypto.Util.Tactics.SpecializeBy.\nRequire Import Rewriter.Language.Wf.\nRequire Import Crypto.Language.WfExtra.\nRequire Import Rewriter.Language.Language.\nRequire Import Crypto.Language.API.\nRequire Import Crypto.AbstractInterpretation.AbstractInterpretation.\nRequire Import Crypto.Stringification.Language.\nRequire Import Crypto.Arithmetic.Core.\nRequire Import Crypto.Arithmetic.ModOps.\nRequire Import Crypto.Arithmetic.Freeze.\nRequire Import Crypto.Arithmetic.Partition.\nRequire Import Crypto.Arithmetic.WordByWordMontgomery.\nRequire Import Crypto.Arithmetic.UniformWeight.\nRequire Import Crypto.Arithmetic.BYInv.\nRequire Import Crypto.BoundsPipeline.\nRequire Import Crypto.COperationSpecifications.\nRequire Import Crypto.PushButtonSynthesis.ReificationCache.\nRequire Import Crypto.PushButtonSynthesis.Primitives.\nRequire Import Crypto.PushButtonSynthesis.WordByWordMontgomeryReificationCache.\nRequire Import Crypto.PushButtonSynthesis.BYInversionReificationCache.\nRequire Import Crypto.Assembly.Equivalence.\nImport ListNotations.\nLocal Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope list_scope. Local Open Scope bool_scope.\n\nImport\n  Language.Wf.Compilers\n  Language.WfExtra.Compilers\n  Language.Compilers\n  AbstractInterpretation.Compilers\n  Stringification.Language.Compilers.\nImport Compilers.API.\n\nImport COperationSpecifications.Primitives.\nImport COperationSpecifications.Solinas.\nImport COperationSpecifications.WordByWordMontgomery.\n\nImport Associational Positional.\nImport Arithmetic.WordByWordMontgomery.WordByWordMontgomery.\n\nImport WordByWordMontgomeryReificationCache.WordByWordMontgomery.\nImport BYInversionReificationCache.WordByWordMontgomeryInversion.\n\nLocal Coercion Z.of_nat : nat >-> Z.\nLocal Coercion QArith_base.inject_Z : Z >-> Q.\nLocal Coercion Z.pos : positive >-> Z.\n\nLocal Set Keyed Unification. (* needed for making [autorewrite] fast, c.f. COQBUG(https://github.com/coq/coq/issues/9283) *)\n\n(* needed for making [autorewrite] not take a very long time *)\nLocal Opaque\n      reified_mul_gen\n      reified_square_gen\n      reified_add_gen\n      reified_sub_gen\n      reified_opp_gen\n      reified_from_montgomery_gen\n      reified_to_montgomery_gen\n      reified_to_bytes_gen\n      reified_from_bytes_gen\n      reified_encode_gen\n      reified_zero_gen\n      reified_one_gen\n      reified_eval_gen\n      reified_bytes_eval_gen\n      reified_eval_twos_complement_gen\n      reified_msat_gen\n      reified_encode_gen\n      reified_divstep_gen\n      reified_nonzero_gen\n      expr.Interp.\n\nSection __.\n  Context {output_language_api : ToString.OutputLanguageAPI}\n          {pipeline_opts : PipelineOptions}\n          {pipeline_to_string_opts : PipelineToStringOptions}\n          {synthesis_opts : SynthesisOptions}\n          (m : Z)\n          (machine_wordsize : machine_wordsize_opt).\n\n  Definition s := 2^Z.log2_up m.\n  Definition c := s - m.\n  Definition n : nat := Z.to_nat (Qceiling (Z.log2_up s / machine_wordsize)).\n  Definition sat_limbs := (n + 1)%nat.   (* to represent m in twos complement we might need another bit *)\n  Definition r := 2^machine_wordsize.\n  Definition r' := Z.modinv r m.\n  Definition m' := Z.modinv (-m) r.\n  Definition n_bytes := bytes_n s.\n\n  Definition divstep_precompmod :=\n    let bits := (Z.log2 m) + 1 in\n    let i := if bits <? 46 then (49 * bits + 80) / 17 else (49 * bits + 57) / 17 in\n    let k := (m + 1) / 2 in\n    (Z.modexp k i m).\n\n  Definition prime_upperbound_list : list Z\n    := Partition.partition (uweight machine_wordsize) n (s-1).\n  Definition prime_bytes_upperbound_list : list Z\n    := Partition.partition (weight 8 1) n_bytes (s-1).\n  Definition upperbounds : list Z := prime_upperbound_list.\n  Definition prime_bound : ZRange.type.interp (base.type.Z)\n    := r[0~>m-1]%zrange.\n  Definition prime_word_bound : ZRange.type.interp (base.type.Z) (* a word that's guaranteed to be smaller than the prime *)\n    := r[0 ~> Z.min m (2^machine_wordsize) - 1]%zrange.\n  Definition prime_bounds : list (ZRange.type.option.interp base.type.Z)\n    := List.map (fun v => Some r[0 ~> v]%zrange) prime_upperbound_list.\n  Definition prime_bytes_bounds : list (ZRange.type.option.interp (base.type.Z))\n    := List.map (fun v => Some r[0 ~> v]%zrange) prime_bytes_upperbound_list.\n  Local Notation word_bound := (word_bound machine_wordsize).\n  Local Notation saturated_bounds := (saturated_bounds n machine_wordsize).\n  Local Notation larger_saturated_bounds := (Primitives.saturated_bounds sat_limbs machine_wordsize).\n\n\n  Definition divstep_input :=\n    (Some r[0~>2^machine_wordsize-1],\n     (Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) sat_limbs),\n      (Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) sat_limbs),\n       (Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) n),\n        (Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) n),tt)))))%zrange.\n\n  Definition divstep_output :=\n    (Some r[0~>2^machine_wordsize-1],\n     Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) sat_limbs),\n     Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) sat_limbs),\n     Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) n),\n     Some (repeat (Some r[0 ~> 2^machine_wordsize-1]) n))%zrange.\n\n  Local Notation possible_values := (possible_values_of_machine_wordsize machine_wordsize).\n  Local Notation possible_values_with_bytes := (possible_values_of_machine_wordsize_with_bytes machine_wordsize).\n\n  Definition bounds : list (ZRange.type.option.interp base.type.Z)\n    := saturated_bounds (*List.map (fun u => Some r[0~>u]%zrange) upperbounds*).\n  Definition larger_bounds : list (ZRange.type.option.interp base.type.Z)\n    := larger_saturated_bounds (*List.map (fun u => Some r[0~>u]%zrange) upperbounds*).\n  Definition montgomery_domain_bounds := saturated_bounds.\n  Definition non_montgomery_domain_bounds := saturated_bounds.\n  Typeclasses Opaque montgomery_domain_bounds.\n  Typeclasses Opaque non_montgomery_domain_bounds.\n  Global Instance montgomery_domain_bounds_typedef : typedef (t:=base.type.list base.type.Z) (Some montgomery_domain_bounds)\n    := { name := \"montgomery_domain_field_element\"\n         ; description name := (text_before_type_name ++ name ++ \" is a field element in the Montgomery domain.\")%string }.\n  Global Instance non_montgomery_domain_bounds_typedef : typedef (t:=base.type.list base.type.Z) (Some non_montgomery_domain_bounds)\n    := { name := \"non_montgomery_domain_field_element\"\n         ; description name := (text_before_type_name ++ name ++ \" is a field element NOT in the Montgomery domain.\")%string }.\n\n\n  Local Existing Instance default_translate_to_fancy.\n  Local Instance no_select_size : no_select_size_opt := no_select_size_of_no_select machine_wordsize.\n  Local Instance split_mul_to : split_mul_to_opt := split_mul_to_of_should_split_mul machine_wordsize possible_values.\n  Local Instance split_multiret_to : split_multiret_to_opt := split_multiret_to_of_should_split_multiret machine_wordsize possible_values.\n\n  (** Note: If you change the name or type signature of this\n        function, you will need to update the code in CLI.v *)\n  Definition check_args {T} (requests : list string) (res : Pipeline.ErrorT T)\n    : Pipeline.ErrorT T\n    := check_args_of_list\n         (List.map\n            (fun v => (true, v))\n            [((1 <? machine_wordsize)%Z, Pipeline.Value_not_ltZ \"machine_wordsize <= 1\" 1 machine_wordsize)\n             ; ((0 <? c)%Z, Pipeline.Value_not_ltZ \"c ≤ 0\" 0 c)\n             ; ((1 <? m)%Z, Pipeline.Value_not_ltZ \"m ≤ 1\" 1 m)\n             ; (negb (n =? 0)%nat, Pipeline.Values_not_provably_distinctZ \"n = 0\" n 0%nat)\n             ; (negb (r' =? 0)%Z, Pipeline.No_modular_inverse \"r⁻¹ mod m\" r m)\n             ; (((r * r') mod m =? 1)%Z, Pipeline.Values_not_provably_equalZ \"(r * r') mod m ≠ 1\" ((r * r') mod m) 1)\n             ; (((m * m') mod r =? (-1) mod r)%Z, Pipeline.Values_not_provably_equalZ \"(m * m') mod r ≠ (-1) mod r\" ((m * m') mod r) ((-1) mod r))\n             ; (s <=? r^n, Pipeline.Value_not_leZ \"r^n ≤ s\" s (r^n))\n             ; (s <=? uweight machine_wordsize n, Pipeline.Value_not_leZ \"weight n < s (needed for from_bytes)\" s (uweight machine_wordsize n))\n             ; (s <=? uweight 8 n_bytes, Pipeline.Value_not_leZ \"bytes_weight n_bytes < s (needed for from_bytes)\" s (uweight 8 n_bytes))\n         ])\n         res.\n\n  Local Arguments Z.mul !_ !_.\n\n  Local Ltac use_curve_good_t :=\n    repeat first [ use_requests_to_prove_curve_good_t_step\n                 | assumption\n                 | lia\n                 | progress autorewrite with distr_length\n                 | progress distr_length\n                 | solve [ auto with zarith ]\n                 | rewrite Z.log2_pow2 by use_curve_good_t ].\n\n  Context (requests : list string)\n          (curve_good : check_args requests (Success tt) = Success tt).\n\n  Lemma use_curve_good\n    : Z.pos (Z.to_pos m) = m\n      /\\ m = s - c\n      /\\ Z.pos (Z.to_pos m) <> 0\n      /\\ s - c <> 0\n      /\\ 0 < s\n      /\\ s <> 0\n      /\\ 0 < machine_wordsize\n      /\\ n <> 0%nat\n      /\\ List.length bounds = n\n      /\\ 0 < 1 <= machine_wordsize\n      /\\ 0 < c < s\n      /\\ (r * r') mod m = 1\n      /\\ (m * m') mod r = (-1) mod r\n      /\\ 0 < machine_wordsize\n      /\\ 1 < m\n      /\\ m < r^n\n      /\\ s = 2^Z.log2 s\n      /\\ s <= uweight machine_wordsize n\n      /\\ s <= uweight 8 n_bytes.\n  Proof using curve_good.\n    prepare_use_curve_good (); cbv [s c] in *.\n    { destruct m eqn:?; cbn; lia. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n    { use_curve_good_t. }\n  Qed.\n\n  Local Notation valid := (valid machine_wordsize n m).\n  Local Notation bytes_valid := (WordByWordMontgomery.valid 8 n_bytes m).\n\n  Local Notation from_montgomery_res := (from_montgomerymod machine_wordsize n m m').\n\n  Local Notation notations_for_docstring prefix\n    := ((CorrectnessStringification.dyn_context.cons\n           m \"m\"\n           (CorrectnessStringification.dyn_context.cons\n              r' (\"((2^\" ++ Decimal.Z.to_string machine_wordsize ++ \")⁻¹ mod m)\")\n              (CorrectnessStringification.dyn_context.cons\n                 from_montgomery_res \"from_montgomery\"\n                 (CorrectnessStringification.dyn_context.cons\n                    (@eval machine_wordsize n) \"eval\"\n                    (CorrectnessStringification.dyn_context.cons\n                       (@eval 8 n_bytes) \"bytes_eval\"\n                            (CorrectnessStringification.dyn_context.cons\n                               (Z.log2 m) \"⌊log2 m⌋\"\n                               (CorrectnessStringification.dyn_context.cons\n                                  (@eval_twos_complement machine_wordsize n) \"twos_complement_eval\"\n                                  CorrectnessStringification.dyn_context.nil)))))))%string)\n         (only parsing).\n  Local Notation \"'docstring_with_summary_from_lemma!' prefix summary correctness\"\n    := (docstring_with_summary_from_lemma_with_ctx!\n          (notations_for_docstring prefix)\n          summary\n          correctness)\n         (only parsing, at level 10, prefix at next level, summary at next level, correctness at next level).\n\n  Definition mul\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values\n         (reified_mul_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')\n         (Some montgomery_domain_bounds, (Some montgomery_domain_bounds, tt))\n         (Some montgomery_domain_bounds).\n\n  Definition smul (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"mul\" mul\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" multiplies two field elements in the Montgomery domain.\"]%string)\n             (mul_correct machine_wordsize n m valid from_montgomery_res)).\n\n  Definition square\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values\n         (reified_square_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')\n         (Some montgomery_domain_bounds, tt)\n         (Some montgomery_domain_bounds).\n\n  Definition ssquare (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"square\" square\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" squares a field element in the Montgomery domain.\"]%string)\n             (square_correct machine_wordsize n m valid from_montgomery_res)).\n\n  Definition add\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_add_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m)\n         (Some montgomery_domain_bounds, (Some montgomery_domain_bounds, tt))\n         (Some montgomery_domain_bounds).\n\n  Definition sadd (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"add\" add\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" adds two field elements in the Montgomery domain.\"]%string)\n             (add_correct machine_wordsize n m valid from_montgomery_res)).\n\n  Definition sub\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_sub_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m)\n         (Some montgomery_domain_bounds, (Some montgomery_domain_bounds, tt))\n         (Some montgomery_domain_bounds).\n\n  Definition ssub (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"sub\" sub\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" subtracts two field elements in the Montgomery domain.\"]%string)\n             (sub_correct machine_wordsize n m valid from_montgomery_res)).\n\n  Definition opp\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_opp_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m)\n         (Some montgomery_domain_bounds, tt)\n         (Some montgomery_domain_bounds).\n\n  Definition sopp (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"opp\" opp\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" negates a field element in the Montgomery domain.\"]%string)\n             (opp_correct machine_wordsize n m valid from_montgomery_res)).\n\n  Definition from_montgomery\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_from_montgomery_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')\n         (Some montgomery_domain_bounds, tt)\n         (Some non_montgomery_domain_bounds).\n\n  Definition sfrom_montgomery (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"from_montgomery\" from_montgomery\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" translates a field element out of the Montgomery domain.\"]%string)\n             (from_montgomery_correct machine_wordsize n m r' valid)).\n\n  Definition to_montgomery\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_to_montgomery_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')\n         (Some non_montgomery_domain_bounds, tt)\n         (Some montgomery_domain_bounds).\n\n  Definition sto_montgomery (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"to_montgomery\" to_montgomery\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" translates a field element into the Montgomery domain.\"]%string)\n             (to_montgomery_correct machine_wordsize n m valid from_montgomery_res)).\n\n  Definition nonzero\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         reified_nonzero_gen\n         (Some bounds, tt)\n         (Some r[0~>r-1]%zrange).\n\n  Definition snonzero (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"nonzero\" nonzero\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" outputs a single non-zero word if the input is non-zero and zero otherwise.\"]%string)\n             (nonzero_correct machine_wordsize n m valid from_montgomery_res)).\n\n  Definition to_bytes\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values_with_bytes\n         (reified_to_bytes_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m)\n         (Some prime_bounds, tt)\n         (Some prime_bytes_bounds).\n\n  Definition sto_bytes (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"to_bytes\" to_bytes\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" serializes a field element NOT in the Montgomery domain to bytes in little-endian order.\"]%string)\n             (to_bytes_correct machine_wordsize n n_bytes m valid)).\n\n  Definition from_bytes\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values_with_bytes\n         (reified_from_bytes_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify 1 @ GallinaReify.Reify s @ GallinaReify.Reify n)\n         (Some prime_bytes_bounds, tt)\n         (Some prime_bounds).\n\n  Definition sfrom_bytes (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"from_bytes\" from_bytes\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" deserializes a field element NOT in the Montgomery domain from bytes in little-endian order.\"]%string)\n             (from_bytes_correct machine_wordsize n n_bytes m valid bytes_valid)).\n\n  Definition encode\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_encode_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')\n         (Some prime_bound, tt)\n         (Some montgomery_domain_bounds).\n\n  Definition sencode (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"encode\" encode\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" encodes an integer as a field element in the Montgomery domain.\"]%string)\n             (encode_correct machine_wordsize n m valid from_montgomery_res)).\n\n\n  Definition encode_word\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_encode_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')\n         (Some prime_word_bound, tt)\n         (Some saturated_bounds).\n\n  Definition sencode_word (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"encode_word\" encode_word\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" encodes an integer as a field element in the Montgomery domain.\"]%string)\n             (encode_word_correct machine_wordsize n m valid from_montgomery_res)).\n\n  Definition zero\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_zero_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')\n         tt\n         (Some montgomery_domain_bounds).\n\n  Definition szero (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"zero\" zero\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname => [text_before_function_name ++ fname ++ \" returns the field element zero in the Montgomery domain.\"]%string)\n             (zero_correct machine_wordsize n m valid from_montgomery_res)).\n\n  Definition one\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_one_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m')\n         tt\n         (Some montgomery_domain_bounds).\n\n  Definition sone (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"set_one\" one (* to avoid conflict with boringSSL *)\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname => [text_before_function_name ++ fname ++ \" returns the field element one in the Montgomery domain.\"]%string)\n             (one_correct machine_wordsize n m valid from_montgomery_res)).\n\n  Definition reval (* r for reified *)\n    := Pipeline.RepeatRewriteAddAssocLeftAndFlattenThunkedRects\n         n\n         (Pipeline.PreBoundsPipeline\n            true (* subst01 *)\n            false (* let_bind_return *)\n            (reified_eval_gen\n               @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n)\n            (Some montgomery_domain_bounds, tt)).\n\n  Definition seval (arg_name : string) (* s for string *)\n    := Show.show (invert_expr.smart_App_curried (reval _) (arg_name, tt)).\n\n  Definition rbytes_eval (* r for reified *)\n    := Pipeline.RepeatRewriteAddAssocLeftAndFlattenThunkedRects\n         n_bytes\n         (Pipeline.PreBoundsPipeline\n            true (* subst01 *)\n            false (* let_bind_return *)\n            (reified_bytes_eval_gen\n               @ GallinaReify.Reify s)\n            (Some prime_bytes_bounds, tt)).\n\n  Definition sbytes_eval (arg_name : string) (* s for string *)\n    := Show.show (invert_expr.smart_App_curried (rbytes_eval _) (arg_name, tt)).\n\n  Definition reval_twos_complement (* r for reified *)\n    := Pipeline.RepeatRewriteAddAssocLeftAndFlattenThunkedRects\n         n\n         (Pipeline.PreBoundsPipeline\n            true (* subst01 *)\n            false (* let_bind_return *)\n            (reified_eval_twos_complement_gen\n               @ GallinaReify.Reify (machine_wordsize:Z)\n               @ GallinaReify.Reify n)\n            (Some bounds, tt)).\n\n  Definition seval_twos_complement (arg_name : string) (* s for string *)\n    := Show.show (invert_expr.smart_App_curried (reval_twos_complement _) (arg_name, tt)).\n\n  Definition selectznz : Pipeline.ErrorT _ := Primitives.selectznz n machine_wordsize.\n  Definition sselectznz (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Primitives.sselectznz n machine_wordsize prefix.\n\n  Definition copy : Pipeline.ErrorT _ := Primitives.copy n machine_wordsize.\n  Definition scopy (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Primitives.scopy n machine_wordsize prefix.\n\n  Definition msat\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_msat_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify sat_limbs @ GallinaReify.Reify m)\n         tt\n         (Some larger_bounds).\n\n Definition smsat (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"msat\" msat\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname => [text_before_function_name ++ fname ++ \" returns the saturated representation of the prime modulus.\"]%string)\n             (msat_correct machine_wordsize n m valid)).\n\n  Definition divstep_precomp\n    := Pipeline.BoundsPipeline\n         true (* subst01 *)\n         possible_values\n         (reified_encode_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify n @ GallinaReify.Reify m @ GallinaReify.Reify m' @ GallinaReify.Reify divstep_precompmod)\n         tt\n         (Some bounds).\n\n  Definition sdivstep_precomp (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"divstep_precomp\" divstep_precomp\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname => [text_before_function_name ++ fname ++ \" returns the precomputed value for Bernstein-Yang-inversion (in montgomery form).\"]%string)\n             (divstep_precomp_correct machine_wordsize n m valid from_montgomery_res)).\n\n  Definition divstep\n    := Pipeline.BoundsPipeline\n         false (* subst01 *)\n         possible_values\n         (reified_divstep_gen\n            @ GallinaReify.Reify (machine_wordsize:Z) @ GallinaReify.Reify sat_limbs @ GallinaReify.Reify n @ GallinaReify.Reify m)\n         (divstep_input)\n         (divstep_output).\n\n  Definition sdivstep (prefix : string)\n    : string * (Pipeline.M (Pipeline.ExtendedSynthesisResult _))\n    := Eval cbv beta in\n        FromPipelineToString!\n          machine_wordsize prefix \"divstep\" divstep\n          (docstring_with_summary_from_lemma!\n             prefix\n             (fun fname : string => [text_before_function_name ++ fname ++ \" computes a divstep.\"]%string)\n             (divstep_correct machine_wordsize n m valid from_montgomery_res)).\n\n  Lemma bounded_by_of_valid x\n        (H : valid x)\n    : ZRange.type.base.option.is_bounded_by (t:=base.type.list base.type.Z) (Some bounds) x = true.\n  Proof using curve_good.\n    pose proof use_curve_good as use_curve_good.\n    clear -H use_curve_good curve_good.\n    destruct H as [H _]; destruct_head'_and.\n    cbv [small] in H.\n    cbv [ZRange.type.base.option.is_bounded_by bounds saturated_bounds word_bound].\n    replace n with (List.length x) by now rewrite H, Partition.length_partition.\n    rewrite <- map_const, fold_andb_map_map1, fold_andb_map_iff.\n    cbv [ZRange.type.base.is_bounded_by is_bounded_by_bool lower upper type_base].\n    split; [ reflexivity | ].\n    intros *; rewrite combine_same, in_map_iff, Bool.andb_true_iff, !Z.leb_le.\n    intros; destruct_head'_ex; destruct_head'_and; subst *; cbn [fst snd].\n    match goal with\n    | [ H : In ?v x |- _ ] => revert v H\n    end.\n    rewrite H.\n    generalize (eval (n:=n) machine_wordsize x).\n    cbn [base.interp base.base_interp].\n    generalize n.\n    intro n'.\n    induction n' as [|n' IHn'].\n    { cbv [Partition.partition seq List.map In]; tauto. }\n    { intros *; rewrite Partition.partition_step, in_app_iff; cbn [List.In].\n      intros; destruct_head'_or; subst *; eauto; try tauto; [].\n      rewrite uweight_S by lia.\n      assert (0 < uweight machine_wordsize n') by now apply uwprops.\n      assert (0 < 2 ^ machine_wordsize) by auto with zarith.\n      assert (0 < 2 ^ machine_wordsize * uweight machine_wordsize n') by nia.\n      rewrite <- Z.mod_pull_div by lia.\n      rewrite Z.le_sub_1_iff.\n      auto with zarith. }\n  Qed.\n\n  (* XXX FIXME *)\n  Lemma bounded_by_prime_bounds_of_valid_gen lgr n' x\n        (Hlgr : 0 < lgr)\n        (Hs : s = 2^Z.log2 s)\n        (Hs' : s <= uweight lgr n')\n        (H : WordByWordMontgomery.valid lgr n' m x)\n    : ZRange.type.base.option.is_bounded_by (t:=base.type.list base.type.Z) (Some (List.map (fun v => Some r[0~>v]%zrange) (Partition.partition (uweight lgr) n' (s-1)))) x = true.\n  Proof using curve_good.\n    pose proof use_curve_good as use_curve_good.\n    clear -H use_curve_good curve_good Hlgr Hs Hs'.\n    destruct H as [H ?]; destruct_head'_and.\n    cbv [small] in H.\n    cbv [ZRange.type.base.option.is_bounded_by].\n    replace n' with (List.length x) by now rewrite H, Partition.length_partition.\n    rewrite fold_andb_map_map1, fold_andb_map_iff.\n    split; [ now autorewrite with distr_length | ].\n    cbv [ZRange.type.base.is_bounded_by is_bounded_by_bool lower upper].\n    rewrite H; autorewrite with distr_length.\n    intros [v1 v0]; cbn [fst snd].\n    rename x into x'.\n    generalize dependent (eval (n:=n') lgr x').\n    replace m with (s - c) in * by easy.\n    intro x; intros ??? H; subst x'.\n    eapply In_nth_error in H; destruct H as [i H].\n    rewrite nth_error_combine in H.\n    break_match_hyps; try discriminate; []; Option.inversion_option; Prod.inversion_prod; subst.\n    cbv [Partition.partition] in *.\n    apply nth_error_map_ex in Heqo; apply nth_error_map_ex in Heqo0; destruct Heqo as (?&?&?), Heqo0 as (?&?&?).\n    rewrite nth_error_seq in *.\n    break_match_hyps; try discriminate; Option.inversion_option; Prod.inversion_prod; subst.\n    rewrite ?Nat.add_0_l.\n    assert (0 <= x < s) by lia.\n    replace s with (2^Z.log2 s) by easy.\n    assert (1 < s) by lia.\n    assert (0 < Z.log2 s) by now apply Z.log2_pos.\n    assert (1 < 2^Z.log2 s) by auto with zarith.\n    generalize dependent (Z.log2 s); intro lgs; intros.\n\n    edestruct (uwprops lgr); try lia.\n    assert (forall i : nat, 0 <= uweight lgr i) by (intro z; specialize (weight_positive z); lia).\n    apply Bool.andb_true_intro; split; apply OrdersEx.Z_as_OT.leb_le;\n      [apply Z.div_nonneg | apply Z.div_le_mono_nonneg]; trivial.\n    apply Z.mod_pos_bound; trivial.\n\n    cbv [uweight].\n    cbv [weight].\n    rewrite Z.div_1_r.\n    rewrite Z.opp_involutive.\n    rewrite <-2Z.land_ones by nia.\n    rewrite Z.sub_1_r, <-Z.ones_equiv.\n    rewrite Z.land_ones_ones.\n    destruct ((lgs <? 0) || (lgr * Z.of_nat (S i) <? 0)) eqn:?.\n    { rewrite Z.land_ones, Z.ones_equiv, <-Z.sub_1_r by nia.\n      pose proof Z.le_max_r lgs (lgr*Z.of_nat (S i)).\n      etransitivity.\n      2:rewrite <- Z.sub_le_mono_r.\n      2:eapply Z.pow_le_mono_r; try lia; eassumption.\n      eapply Z.le_sub_1_iff, Z.mod_pos_bound, Z.pow_pos_nonneg; nia. }\n    rewrite (Z.ones_equiv (Z.min _ _)), <-Z.sub_1_r.\n    enough (Z.land x (Z.ones (lgr * Z.of_nat (S i))) < 2 ^ Z.min lgs (lgr * Z.of_nat (S i))) by lia.\n    eapply Testbit.Z.testbit_false_bound. nia.\n    intros j ?; assert (Z.min lgs (lgr * Z.of_nat (S i)) <= j) by lia.\n    rewrite Hs in *. revert H; intros.\n    rewrite <-(Z.mod_small x (2^lgs)) by lia.\n    rewrite OrdersEx.Z_as_OT.land_spec.\n    destruct (Zmin_irreducible lgs (lgr * Z.of_nat (S i))) as [HH|HH]; rewrite HH in *; clear HH.\n    { rewrite Z.mod_pow2_bits_high; trivial; lia. }\n    { rewrite OrdersEx.Z_as_DT.ones_spec_high, Bool.andb_false_r; trivial; nia. }\n  Qed.\n\n  Lemma length_of_valid lgr n' x\n        (H : WordByWordMontgomery.valid lgr n' m x)\n    : List.length x = n'.\n  Proof using Type.\n    destruct H as [H _]; rewrite H.\n    now autorewrite with distr_length.\n  Qed.\n\n  Lemma bounded_by_prime_bounds_of_valid x\n        (H : valid x)\n    : ZRange.type.base.option.is_bounded_by (t:=base.type.list base.type.Z) (Some prime_bounds) x = true.\n  Proof using curve_good.\n    pose proof use_curve_good as use_curve_good.\n    destruct_head'_and.\n    now apply bounded_by_prime_bounds_of_valid_gen.\n  Qed.\n\n  Lemma bounded_by_prime_bytes_bounds_of_bytes_valid x\n        (H : bytes_valid x)\n    : ZRange.type.base.option.is_bounded_by (t:=base.type.list base.type.Z) (Some prime_bytes_bounds) x = true.\n  Proof using curve_good.\n    pose proof use_curve_good as use_curve_good.\n    destruct_head'_and.\n    now apply bounded_by_prime_bounds_of_valid_gen.\n  Qed.\n\n  Lemma weight_bounded_of_bytes_valid x\n        (H : bytes_valid x)\n    : 0 <= eval 8 (n:=n_bytes) x < weight machine_wordsize 1 n.\n  Proof using curve_good.\n    cbv [bytes_valid] in H.\n    destruct H as [_ H].\n    pose proof use_curve_good.\n    cbv [uweight] in *; destruct_head'_and; lia.\n  Qed.\n\n  Local Ltac solve_extra_bounds_side_conditions :=\n    solve [ cbn [lower upper fst snd] in *; Bool.split_andb; Z.ltb_to_lt; lia\n          | cbv [valid small eval uweight n_bytes] in *; destruct_head'_and; auto\n          | now apply weight_bounded_of_bytes_valid\n          | eapply length_of_valid; eassumption ].\n\n  Hint Rewrite\n       (@eval_mulmod machine_wordsize n m r' m')\n       (@eval_squaremod machine_wordsize n m r' m')\n       (@eval_addmod machine_wordsize n m r' m')\n       (@eval_submod machine_wordsize n m r' m')\n       (@eval_oppmod machine_wordsize n m r' m')\n       (@eval_from_montgomerymod machine_wordsize n m r' m')\n       (@eval_to_montgomerymod machine_wordsize n m r' m')\n       (@eval_encodemod machine_wordsize n m r' m')\n       eval_to_bytesmod\n       eval_from_bytesmod\n       using solve [ eauto using length_of_valid | congruence | solve_extra_bounds_side_conditions ] : push_eval.\n  (* needed for making [autorewrite] fast enough *)\n  Local Opaque\n        WordByWordMontgomery.WordByWordMontgomery.onemod\n        WordByWordMontgomery.WordByWordMontgomery.from_montgomerymod\n        WordByWordMontgomery.WordByWordMontgomery.to_montgomerymod\n        WordByWordMontgomery.WordByWordMontgomery.mulmod\n        WordByWordMontgomery.WordByWordMontgomery.squaremod\n        WordByWordMontgomery.WordByWordMontgomery.encodemod\n        WordByWordMontgomery.WordByWordMontgomery.addmod\n        WordByWordMontgomery.WordByWordMontgomery.submod\n        WordByWordMontgomery.WordByWordMontgomery.oppmod\n        WordByWordMontgomery.WordByWordMontgomery.to_bytesmod.\n  Hint Unfold eval zeromod onemod : push_eval.\n\n  Local Ltac prove_correctness op_correct :=\n    let dont_clear H := first [ constr_eq H curve_good ] in\n    let Hres := match goal with H : _ = Success _ |- _ => H end in\n    let H := fresh in\n    pose proof use_curve_good as H;\n    (* I want to just use [clear -H Hres], but then I can't use any lemmas in the section because of COQBUG(https://github.com/coq/coq/issues/8153) *)\n    repeat match goal with\n           | [ H' : _ |- _ ]\n             => tryif first [ has_body H' | constr_eq H' H | constr_eq H' Hres | dont_clear H' ]\n             then fail\n             else clear H'\n           end;\n    cbv zeta in *;\n    destruct_head'_and;\n    let f := match type of Hres with ?f = _ => head f end in\n    try cbv [f] in *;\n    hnf;\n    PipelineTactics.do_unfolding;\n    try (let m := match goal with m := _ - Associational.eval _ |- _ => m end in\n         cbv [m] in * );\n    intros;\n    lazymatch goal with\n    | [ |- _ <-> _ ] => idtac\n    | [ |- _ = _ ] => idtac\n    | _ => split; [ | try split ];\n           cbv [small]\n    end;\n    PipelineTactics.use_compilers_correctness Hres;\n    repeat first [ reflexivity\n                 | now apply bounded_by_of_valid\n                 | now apply bounded_by_prime_bounds_of_valid\n                 | now apply bounded_by_prime_bytes_bounds_of_bytes_valid\n                 | now apply weight_bounded_of_bytes_valid\n                 | solve [ eapply op_correct; try eassumption; solve_extra_bounds_side_conditions ]\n                 | progress autorewrite with interp_gen_cache interp_extra\n                 | progress autorewrite with push_eval\n                 | progress autounfold with push_eval\n                 | progress autorewrite with distr_length in *\n                 | solve [ cbv [valid small eval uweight n_bytes] in *; destruct_head'_and; auto ] ].\n\n  (** TODO: DESIGN DECISION:\n\n        The correctness lemmas for most of the montgomery things are\n        parameterized over a `from_montgomery`.  When filling this in\n        for, e.g., mul-correctness, should I use `from_montgomery`\n        from arithmetic, or should I use `Interp\n        reified_from_montgomery` (the post-pipeline version), and take\n        in success of the pipeline on `from_montgomery` as well? *)\n\n  Lemma mul_correct res\n        (Hres : mul = Success res)\n    : mul_correct machine_wordsize n m valid from_montgomery_res (Interp res).\n  Proof using curve_good. prove_correctness mulmod_correct. Qed.\n\n  Lemma Wf_mul res (Hres : mul = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma square_correct res\n        (Hres : square = Success res)\n    : square_correct machine_wordsize n m valid from_montgomery_res (Interp res).\n  Proof using curve_good. prove_correctness squaremod_correct. Qed.\n\n  Lemma Wf_square res (Hres : square = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma add_correct res\n        (Hres : add = Success res)\n    : add_correct machine_wordsize n m valid from_montgomery_res (Interp res).\n  Proof using curve_good. prove_correctness addmod_correct. Qed.\n\n  Lemma Wf_add res (Hres : add = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma sub_correct res\n        (Hres : sub = Success res)\n    : sub_correct machine_wordsize n m valid from_montgomery_res (Interp res).\n  Proof using curve_good. prove_correctness submod_correct. Qed.\n\n  Lemma Wf_sub res (Hres : sub = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma opp_correct res\n        (Hres : opp = Success res)\n    : opp_correct machine_wordsize n m valid from_montgomery_res (Interp res).\n  Proof using curve_good. prove_correctness oppmod_correct. Qed.\n\n  Lemma Wf_opp res (Hres : opp = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma from_montgomery_correct res\n        (Hres : from_montgomery = Success res)\n    : from_montgomery_correct machine_wordsize n m r' valid (Interp res).\n  Proof using curve_good. prove_correctness from_montgomerymod_correct. Qed.\n\n  Lemma Wf_from_montgomery res (Hres : from_montgomery = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma to_montgomery_correct res\n        (Hres : to_montgomery = Success res)\n    : to_montgomery_correct machine_wordsize n m valid from_montgomery_res (Interp res).\n  Proof using curve_good. prove_correctness to_montgomerymod_correct. Qed.\n\n  Lemma Wf_to_montgomery res (Hres : to_montgomery = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma nonzero_correct res\n        (Hres : nonzero = Success res)\n    : nonzero_correct machine_wordsize n m valid from_montgomery_res (Interp res).\n  Proof using curve_good. prove_correctness nonzeromod_correct. Qed.\n\n  Lemma Wf_nonzero res (Hres : nonzero = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma to_bytes_correct res\n        (Hres : to_bytes = Success res)\n    : to_bytes_correct machine_wordsize n n_bytes m valid (Interp res).\n  Proof using curve_good. prove_correctness to_bytesmod_correct. Qed.\n\n  Lemma Wf_to_bytes res (Hres : to_bytes = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Lemma from_bytes_correct res\n        (Hres : from_bytes = Success res)\n    : from_bytes_correct machine_wordsize n n_bytes m valid bytes_valid (Interp res).\n  Proof using curve_good. prove_correctness eval_from_bytesmod_and_partitions. Qed.\n\n  Lemma Wf_from_bytes res (Hres : from_bytes = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Strategy -1000 [encode]. (* if we don't tell the kernel to unfold this early, then [Qed] seems to run off into the weeds *)\n  Lemma encode_correct res\n        (Hres : encode = Success res)\n    : encode_correct machine_wordsize n m valid from_montgomery_res (Interp res).\n  Proof using curve_good. prove_correctness encodemod_correct. Qed.\n\n  Lemma Wf_encode res (Hres : encode = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Strategy -1000 [encode_word]. (* if we don't tell the kernel to unfold this early, then [Qed] seems to run off into the weeds *)\n  Lemma encode_word_correct res\n        (Hres : encode_word = Success res)\n    : encode_word_correct machine_wordsize n m valid from_montgomery_res (Interp res).\n  Proof using curve_good. prove_correctness encodemod_correct. Qed.\n\n  Lemma Wf_encode_word res (Hres : encode_word = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Strategy -1000 [zero]. (* if we don't tell the kernel to unfold this early, then [Qed] seems to run off into the weeds *)\n  Lemma zero_correct res\n        (Hres : zero = Success res)\n    : zero_correct machine_wordsize n m valid from_montgomery_res (Interp res).\n  Proof using curve_good. prove_correctness encodemod_correct. Qed.\n\n  Lemma Wf_zero res (Hres : zero = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Strategy -1000 [one]. (* if we don't tell the kernel to unfold this early, then [Qed] seems to run off into the weeds *)\n  Lemma one_correct res\n        (Hres : one = Success res)\n    : one_correct machine_wordsize n m valid from_montgomery_res (Interp res).\n  Proof using curve_good. prove_correctness encodemod_correct. Qed.\n\n  Lemma Wf_one res (Hres : one = Success res) : Wf res.\n  Proof using Type. prove_pipeline_wf (). Qed.\n\n  Local Opaque Pipeline.BoundsPipeline. (* need this or else [eapply Pipeline.BoundsPipeline_correct in Hres] takes forever *)\n\n  Lemma selectznz_correct res\n        (Hres : selectznz = Success res)\n    : selectznz_correct saturated_bounds (Interp res).\n  Proof using curve_good. apply Primitives.selectznz_correct, Hres. Qed.\n\n  Lemma Wf_selectznz res (Hres : selectznz = Success res) : Wf res.\n  Proof using Type. revert Hres; cbv [selectznz]; apply Wf_selectznz. Qed.\n\n  Lemma copy_correct res\n        (Hres : copy = Success res)\n    : copy_correct saturated_bounds (Interp res).\n  Proof using curve_good. Primitives.prove_correctness use_curve_good. Qed.\n\n  Lemma Wf_copy res (Hres : copy = Success res) : Wf res.\n  Proof using Type. revert Hres; cbv [copy]; apply Wf_copy. Qed.\n\n  Section ring.\n    Context from_montgomery_res (Hfrom_montgomery : from_montgomery = Success from_montgomery_res)\n            mul_res    (Hmul    : mul    = Success mul_res)\n            add_res    (Hadd    : add    = Success add_res)\n            sub_res    (Hsub    : sub    = Success sub_res)\n            opp_res    (Hopp    : opp    = Success opp_res)\n            encode_res (Hencode : encode = Success encode_res)\n            zero_res   (Hzero   : zero   = Success zero_res)\n            one_res    (Hone    : one    = Success one_res).\n\n    Definition GoodT : Prop\n      := GoodT\n           machine_wordsize n m valid\n           (Interp from_montgomery_res)\n           (Interp mul_res)\n           (Interp add_res)\n           (Interp sub_res)\n           (Interp opp_res)\n           (Interp encode_res)\n           (Interp zero_res)\n           (Interp one_res).\n\n    Theorem Good : GoodT.\n    Proof using curve_good Hfrom_montgomery Hmul Hadd Hsub Hopp Hencode Hzero Hone.\n      pose proof use_curve_good; cbv zeta in *; destruct_head'_and.\n      eapply Good.\n      all: repeat first [ assumption\n                        | apply from_montgomery_correct\n                        | lia ].\n      all: hnf; intros.\n      all: push_Zmod; erewrite !(fun v Hv => proj1 (from_montgomery_correct _ Hfrom_montgomery v Hv)), <- !eval_from_montgomerymod; try eassumption; pull_Zmod.\n      all: repeat first [ assumption\n                        | lazymatch goal with\n                          | [ |- context[mul_res] ] => apply mul_correct\n                          | [ |- context[add_res] ] => apply add_correct\n                          | [ |- context[sub_res] ] => apply sub_correct\n                          | [ |- context[opp_res] ] => apply opp_correct\n                          | [ |- context[encode_res] ] => apply encode_correct\n                          | [ |- context[zero_res] ] => apply zero_correct\n                          | [ |- context[one_res] ] => apply one_correct\n                          end ].\n    Qed.\n  End ring.\n\n  Section for_stringification.\n    Local Open Scope string_scope.\n    Local Open Scope list_scope.\n\n    Definition known_functions\n      := [(\"mul\", wrap_s smul);\n            (\"square\", wrap_s ssquare);\n            (\"add\", wrap_s sadd);\n            (\"sub\", wrap_s ssub);\n            (\"opp\", wrap_s sopp);\n            (\"from_montgomery\", wrap_s sfrom_montgomery);\n            (\"to_montgomery\", wrap_s sto_montgomery);\n            (\"nonzero\", wrap_s snonzero);\n            (\"selectznz\", wrap_s sselectznz);\n            (\"to_bytes\", wrap_s sto_bytes);\n            (\"from_bytes\", wrap_s sfrom_bytes);\n            (\"one\", wrap_s sone);\n            (\"msat\", wrap_s smsat);\n            (\"divstep_precomp\", wrap_s sdivstep_precomp);\n            (\"divstep\", wrap_s sdivstep)].\n\n    Definition valid_names : string := Eval compute in String.concat \", \" (List.map (@fst _ _) known_functions).\n\n    (** Note: If you change the name or type signature of this\n          function, you will need to update the code in CLI.v *)\n    Definition Synthesize (comment_header : list string) (function_name_prefix : string) (requests : list string)\n      : list (synthesis_output_kind * string * Pipeline.M (list string))\n      := Primitives.Synthesize\n           machine_wordsize valid_names known_functions (fun _ => nil) all_typedefs!\n           check_args\n           (ToString.comment_file_header_block\n              (comment_header\n                 ++ [\"\"\n                     ; \"Computed values:\"]\n                 ++ (List.map\n                       (fun s => \"  \" ++ s)%string\n                       ((ToString.prefix_and_indent \"eval z = \" [seval \"z\"])\n                          ++ (ToString.prefix_and_indent \"bytes_eval z = \" [sbytes_eval \"z\"])\n                          ++ (ToString.prefix_and_indent \"twos_complement_eval z = \" [seval_twos_complement \"z\"])))))\n           function_name_prefix requests.\n  End for_stringification.\nEnd __.\n\nModule Export Hints.\n#[global]\n  Hint Opaque\n       mul\n       square\n       add\n       sub\n       opp\n       from_montgomery\n       to_montgomery\n       nonzero\n       to_bytes\n       from_bytes\n       encode\n       encode_word\n       zero\n       one\n       selectznz\n       copy\n  : wf_op_cache.\n#[global]\n  Hint Immediate\n       Wf_mul\n       Wf_square\n       Wf_add\n       Wf_sub\n       Wf_opp\n       Wf_from_montgomery\n       Wf_to_montgomery\n       Wf_nonzero\n       Wf_to_bytes\n       Wf_from_bytes\n       Wf_encode\n       Wf_encode_word\n       Wf_zero\n       Wf_one\n       Wf_selectznz\n       Wf_copy\n  : wf_op_cache.\nEnd Hints.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/PushButtonSynthesis/WordByWordMontgomery.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.20410037950882867}}
{"text": "From program_logic Require Export global_functor.\nFrom heap_lang Require Export heap.\nFrom heap_lang Require Import wp_tactics notation.\nImport uPred.\n\nDefinition spawn : val :=\n  λ: \"f\",\n    let: \"c\" := ref (InjL #0) in\n    Fork ('\"c\" <- InjR ('\"f\" #())) ;; '\"c\".\nDefinition join : val :=\n  rec: \"join\" \"c\" :=\n    match: !'\"c\" with\n      InjR \"x\" => '\"x\"\n    | InjL <>  => '\"join\" '\"c\"\n    end.\n\n(** The CMRA we need. *)\n(* Not bundling heapG, as it may be shared with other users. *)\nClass spawnG Σ := SpawnG {\n  spawn_tokG :> inG heap_lang Σ (exclR unitC);\n}.\n(** The functor we need. *)\nDefinition spawnGF : gFunctorList := [GFunctor (constRF (exclR unitC))].\n(* Show and register that they match. *)\nInstance inGF_spawnG\n  `{H : inGFs heap_lang Σ spawnGF} : spawnG Σ.\nProof. destruct H as (?&?). split. apply: inGF_inG. Qed.\n\n(** Now we come to the Iris part of the proof. *)\nSection proof.\nContext {Σ : gFunctors} `{!heapG Σ, !spawnG Σ}.\nContext (heapN N : namespace).\nLocal Notation iProp := (iPropG heap_lang Σ).\n\nDefinition spawn_inv (γ : gname) (l : loc) (Ψ : val → iProp) : iProp :=\n  (∃ lv, l ↦ lv ★ (lv = InjLV #0 ∨ ∃ v, lv = InjRV v ★ (Ψ v ∨ own γ (Excl ()))))%I.\n\nDefinition join_handle (l : loc) (Ψ : val → iProp) : iProp :=\n  (■ (heapN ⊥ N) ★ ∃ γ, heap_ctx heapN ★ own γ (Excl ()) ★\n                        inv N (spawn_inv γ l Ψ))%I.\n\nGlobal Instance spawn_inv_ne n γ l :\n  Proper (pointwise_relation val (dist n) ==> dist n) (spawn_inv γ l).\nProof. solve_proper. Qed.\nGlobal Instance join_handle_ne n l :\n  Proper (pointwise_relation val (dist n) ==> dist n) (join_handle l).\nProof. solve_proper. Qed.\n\n(** The main proofs. *)\nLemma spawn_spec (Ψ : val → iProp) e (f : val) (Φ : val → iProp) :\n  to_val e = Some f →\n  heapN ⊥ N →\n  (heap_ctx heapN ★ #> f #() {{ Ψ }} ★ ∀ l, join_handle l Ψ -★ Φ (%l))\n  ⊑ #> spawn e {{ Φ }}.\nProof.\n  intros Hval Hdisj. rewrite /spawn. ewp (by eapply wp_value). wp_let.\n  wp eapply wp_alloc; eauto with I.\n  apply forall_intro=>l. apply wand_intro_l. wp_let.\n  rewrite (forall_elim l). eapply sep_elim_True_l.\n  { by eapply (own_alloc (Excl ())). }\n  rewrite !pvs_frame_r. eapply wp_strip_pvs. rewrite !sep_exist_r.\n  apply exist_elim=>γ.\n  (* TODO: Figure out a better way to say \"I want to establish ▷ spawn_inv\". *)\n  trans (heap_ctx heapN ★ #> f #() {{ Ψ }} ★ (join_handle l Ψ -★ Φ (%l)%V) ★\n         own γ (Excl ()) ★ ▷ (spawn_inv γ l Ψ))%I.\n  { ecancel [ #> _ {{ _ }}; _ -★ _; heap_ctx _; own _ _]%I.\n    rewrite -later_intro /spawn_inv -(exist_intro (InjLV #0)).\n    cancel [l ↦ InjLV #0]%I. by apply or_intro_l', const_intro. }\n  rewrite (inv_alloc N) // !pvs_frame_l. eapply wp_strip_pvs.\n  ewp eapply wp_fork. rewrite [heap_ctx _]always_sep_dup [inv _ _]always_sep_dup.\n  sep_split left: [_ -★ _; inv _ _; own _ _; heap_ctx _]%I.\n  - wp_seq. eapply wand_apply_l; [done..|].\n    rewrite /join_handle. rewrite const_equiv // left_id -(exist_intro γ).\n    solve_sep_entails.\n  - wp_focus (f _). rewrite wp_frame_r wp_frame_l.\n    rewrite (of_to_val e) //. apply wp_mono=>v.\n    eapply (inv_fsa (wp_fsa _)) with (N0:=N); simpl;\n      (* TODO: Collect these in some Hint DB? Or add to an existing one? *)\n      eauto using to_val_InjR,to_val_InjL,to_of_val with I ndisj.\n    apply wand_intro_l. rewrite /spawn_inv {1}later_exist !sep_exist_r.\n    apply exist_elim=>lv. rewrite later_sep.\n    eapply wp_store; eauto using to_val_InjR,to_val_InjL,to_of_val with I ndisj.\n    cancel [▷ (l ↦ lv)]%I. strip_later. apply wand_intro_l.\n    rewrite right_id -later_intro -{2}[(∃ _, _ ↦ _ ★ _)%I](exist_intro (InjRV v)).\n    ecancel [l ↦ _]%I. apply or_intro_r'. rewrite sep_elim_r sep_elim_r sep_elim_l.\n    rewrite -(exist_intro v). rewrite const_equiv // left_id. apply or_intro_l.\nQed.\n\nLemma join_spec (Ψ : val → iProp) l (Φ : val → iProp) :\n  (join_handle l Ψ ★ ∀ v, Ψ v -★ Φ v)\n  ⊑ #> join (%l) {{ Φ }}.\nProof.\n  wp_rec. wp_focus (! _)%E.\n  rewrite {1}/join_handle sep_exist_l !sep_exist_r. apply exist_elim=>γ.\n  rewrite -!assoc. apply const_elim_sep_l=>Hdisj.\n  eapply (inv_fsa (wp_fsa _)) with (N0:=N); simpl; eauto with I ndisj.\n  apply wand_intro_l. rewrite /spawn_inv {1}later_exist !sep_exist_r.\n  apply exist_elim=>lv. rewrite later_sep.\n  eapply wp_load; eauto with I ndisj. cancel [▷ (l ↦ lv)]%I. strip_later.\n  apply wand_intro_l. rewrite -later_intro -[X in _ ⊑ (X ★ _)](exist_intro lv).\n  cancel [l ↦ lv]%I. rewrite sep_or_r. apply or_elim.\n  - (* Case 1 : nothing sent yet, we wait. *)\n    rewrite -or_intro_l. apply const_elim_sep_l=>-> {lv}.\n    do 2 rewrite const_equiv // left_id. wp_case.\n    wp_seq. rewrite -always_wand_impl always_elim.\n    rewrite !assoc. eapply wand_apply_r'; first done.\n    rewrite -(exist_intro γ). solve_sep_entails.\n  - rewrite [(_ ★ □ _)%I]sep_elim_l -or_intro_r !sep_exist_r. apply exist_mono=>v.\n    rewrite -!assoc. apply const_elim_sep_l=>->{lv}. rewrite const_equiv // left_id.\n    rewrite sep_or_r. apply or_elim; last first.\n    { (* contradiction: we have the token twice. *)\n      rewrite [(heap_ctx _ ★ _)%I]sep_elim_r !assoc. rewrite -own_op own_valid_l.\n      rewrite -!assoc discrete_valid. apply const_elim_sep_l=>-[]. }\n    rewrite -or_intro_r. ecancel [own _ _].\n    wp_case. wp_let. ewp (eapply wp_value; wp_done).\n    rewrite (forall_elim v). rewrite !assoc. eapply wand_apply_r'; eauto with I.\nQed.\n\nEnd proof.\n", "meta": {"author": "amintimany", "repo": "iris-with-logrel-backup", "sha": "9e98ff8be4b4ca516a497d328aaf31cbae186a6c", "save_path": "github-repos/coq/amintimany-iris-with-logrel-backup", "path": "github-repos/coq/amintimany-iris-with-logrel-backup/iris-with-logrel-backup-9e98ff8be4b4ca516a497d328aaf31cbae186a6c/heap_lang/spawn.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.20410037432248568}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import DataStructure.\nFrom PromisingLib Require Import DenseOrder.\nFrom PromisingLib Require Import Language.\nFrom PromisingLib Require Import Event.\n\nRequire Import Time.\nRequire Import View.\nRequire Import BoolMap.\nRequire Import Promises.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import Global.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import SimLocal.\nRequire Import SimMemory.\nRequire Import SimGlobal.\nRequire Import SimThread.\nRequire Import Compatibility.\n\nRequire Import ITreeLang.\nRequire Import ITreeLib.\n\nSet Implicit Arguments.\n\n\nLemma intro_load_sim_itree\n      loc ord:\n  sim_itree eq\n            (Ret tt)\n            (ITree.trigger (MemE.read loc ord);; Ret tt).\nProof.\n  unfold trigger. rewrite bind_vis.\n  pcofix CIH. ii. subst. pfold. ii. splits; i.\n  { inv TERMINAL_TGT. eapply f_equal with (f:=observe) in H; ss. }\n  { right. esplits; eauto.\n    rewrite sim_local_promises_bot; eauto.\n  }\n  ii. right.\n  inv STEP_TGT; ss.\n  - (* internal *)\n    exploit sim_local_internal; eauto. i. des.\n    esplits; try exact GL2; eauto. inv LOCAL0; ss.\n  - (* load *)\n    dependent destruction STATE.\n    esplits; [|refl|econs 1|..]; eauto.\n    + destruct e_tgt; ss.\n    + destruct e_tgt; ss.\n    + by inv LOCAL0.\n    + left. rewrite bind_ret_l. eapply paco9_mon; [apply sim_itree_ret|]; ss.\n      inv LOCAL. inv LOCAL0; ss. inv LOCAL. econs; ss.\n      etrans; eauto. apply TViewFacts.read_tview_incr.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ir-coq", "sha": "593c32a2a48b7928b67580af366e0a75c8c70bf7", "save_path": "github-repos/coq/snu-sf-promising-ir-coq", "path": "github-repos/coq/snu-sf-promising-ir-coq/promising-ir-coq-593c32a2a48b7928b67580af366e0a75c8c70bf7/src/trans/IntroLoad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.20410037432248565}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.msl.iter_sepcon.\nRequire Import malloc_lemmas.\nRequire Import malloc_sep.\nRequire Import malloc.\nRequire Import spec_malloc.\nRequire Import linking.\n\nDefinition Gprog : funspecs := user_specs_R ++ private_specs.\n\nLemma body_pre_fill:  semax_body Vprog Gprog f_pre_fill pre_fill_spec'.\nProof. \nstart_function. \nrewrite <- seq_assoc.  \nforward_call n. (*! b = size2bin(n) *)\ndestruct H as [[Hn_lo Hn_hi] Hp].\nrep_omega.\nforward.\nset (b:=size2binZ n). \nassert (Hb: 0 <= b < BINS) by (apply size2bin_range; rep_omega).\nforward_call b. (*! t2 = bin2size(b) *)\nrewrite (mem_mgr_split_R gv b rvec) by apply Hb.\nIntros bins idxs lens.\nfreeze [1; 3] Otherlists.\ndeadvars!.\ndestruct H as [[Hn_lo Hn_hi] Hp].\nforward. (*! t4 = bin[b] *)\nforward_call ((bin2sizeZ b), p, (Znth b bins), (Znth b lens), b). (*! t3 = list_from_block(t2,p,t4) *)\nIntros q.\nforward. (*! bin[b] = t3 *)\nthaw Otherlists.\n\n(* fold lists into mem_mgr_R *)\nreplace (size2binZ (bin2sizeZ b)) with b \n  by (subst b; rewrite claim3; try rep_omega).\nunfold mem_mgr_R.\nset (bins':= upd_Znth b bins q).\nset (lens':= map Z.to_nat (add_resvec rvec b (chunks_from_block b))).\nassert (Hrveclen: Zlength rvec = BINS) by\n    (subst lens; rewrite Zlength_map in H1; rep_omega). \nExists bins'. Exists idxs. Exists lens'.\nentailer!.\n{ split. unfold lens'. rewrite Zlength_map. rewrite Zlength_add_resvec; assumption.\n  apply add_resvec_no_neg; try assumption.\n  pose proof (chunks_from_block_nonneg (size2binZ n)).\n  assert (0 <= Znth (size2binZ n) rvec)\n    by (apply Forall_Znth; try rep_omega; try unfold no_neg in *; auto).\n  rep_omega.\n}\nset (idxs:= (map Z.of_nat (seq 0 (Z.to_nat BINS)))).\nset (lens:= (map Z.to_nat rvec)).\nassert (Zlength lens = BINS) by (unfold lens; rewrite Zlength_map; rep_omega).\nassert (Zlength idxs = BINS) by auto.\nrepeat (rewrite sublist_zip3; try rep_omega).  \nreplace (sublist 0 b bins) with (sublist 0 b bins') \n  by (unfold bins'; rewrite sublist_upd_Znth_l; try reflexivity; try rep_omega).\nreplace (sublist (b+1) BINS bins) with (sublist (b+1) BINS bins') \n  by (unfold bins'; rewrite sublist_upd_Znth_r; try reflexivity; try rep_omega).\nreplace (sublist 0 b lens) with (sublist 0 b lens').\n2: { unfold lens'. unfold lens.  do 2 rewrite sublist_map. f_equal.\n     unfold add_resvec. simple_if_tac''; auto.\n     rewrite sublist_upd_Znth_l; try rep_omega; reflexivity. }\nreplace (sublist (b + 1) BINS lens) with (sublist (b + 1) BINS lens').\n2: { unfold lens'. unfold lens.  do 2 rewrite sublist_map. f_equal. \n     unfold add_resvec. simple_if_tac''; auto.\n     rewrite sublist_upd_Znth_r; try rep_omega; reflexivity. }\nassert (Zlength bins' = BINS) by auto.\nassert (Zlength lens' = BINS) \n  by (unfold lens'; rewrite Zlength_map; rewrite Zlength_add_resvec; auto).\nrepeat (rewrite <- sublist_zip3; try rep_omega); try rep_omega.  \nreplace (Z.to_nat (chunks_from_block b) + Znth b lens)%nat with (Znth b lens').\n2: {unfold lens'.  rewrite Znth_map.\n    unfold add_resvec. simple_if_tac' Hcond.\n    2: { assert (Zlength rvec = BINS) by auto. \n         bdestruct(Zlength rvec =? BINS); simpl in Hcond; try contradiction.\n         bdestruct(0 <=? b); simpl in Hcond; try contradiction.\n         bdestruct(b<?BINS); simpl in Hcond; try contradiction.\n         discriminate.\n         rep_omega. \n         destruct Hb; contradiction.\n    }\n    rewrite upd_Znth_same; try rep_omega.\n    replace (Znth b lens) with (Z.to_nat (Znth b rvec)) \n      by (unfold lens; rewrite Znth_map; rep_omega).\n    rewrite <- Z2Nat.inj_add. f_equal. rep_omega.\n    apply chunks_from_block_nonneg.\n    apply Forall_Znth; try rep_omega; try unfold no_neg in *; auto.\n    rewrite Zlength_add_resvec; rep_omega.\n}\nreplace \n (mmlist (bin2sizeZ b) (Znth b lens') q nullval * TT *\n  iter_sepcon mmlist' (sublist 0 b (zip3 lens' bins' idxs)) *\n  iter_sepcon mmlist' (sublist (b + 1) BINS (zip3 lens' bins' idxs)) * TT)\nwith \n (iter_sepcon mmlist' (sublist 0 b (zip3 lens' bins' idxs)) *\n  iter_sepcon mmlist' (sublist (b + 1) BINS (zip3 lens' bins' idxs)) * \n  mmlist (bin2sizeZ b) (Znth b lens') q nullval * TT)\nby (apply pred_ext; entailer!).\nreplace q with (Znth b bins').\n2: (unfold bins'; rewrite upd_Znth_same; auto; rep_omega).\nrewrite mem_mgr_split'; try entailer!; auto.\nQed.\n\n\n\nDefinition module := [mk_body body_pre_fill].\n\n\n\n\n", "meta": {"author": "PrincetonUniversity", "repo": "DeepSpecDB", "sha": "a67d933b4288498bd04c70748b7fa28f676983c3", "save_path": "github-repos/coq/PrincetonUniversity-DeepSpecDB", "path": "github-repos/coq/PrincetonUniversity-DeepSpecDB/DeepSpecDB-a67d933b4288498bd04c70748b7fa28f676983c3/memmgr/verif_pre_fill.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.2041003716716173}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect eqtype ssrbool eqtype ssrnat seq.\nRequire Import ssrZ ZArith_ext seq_ext ssrnat_ext machine_int uniq_tac.\nRequire Import multi_int integral_type.\nImport MachineInt.\nRequire Import mips_bipl mips_seplog mips_mint mips_frame.\nImport expr_m.\nRequire Import simu.\nImport simu_m.\nRequire Import multi_add_s_s_u_prg multi_add_s_s_u_triple.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope asm_expr_scope.\nLocal Open Scope zarith_ext_scope.\nLocal Open Scope assoc_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope simu_scope.\nLocal Open Scope asm_cmd_scope.\nLocal Open Scope multi_int_scope.\n\nImport assert_m.\n\n(** z <- x + y, z signed, x signed, y unsigned *)\n\nLemma pfwd_sim_multi_add_s_s_u_wo_overflow (z x y : assoc.l) d k rk rz rx ry a0 a1 a2 a3 a4 ret X Y :\n  uniq(z, x, y) ->\n  uniq(rk, rz, rx, ry, a0, a1, a2, a3, a4, ret, X, Y, r0) ->\n  disj (mints_regs (assoc.cdom d)) (a0 :: a1 :: a2 :: a3 :: a4 :: ret :: X :: Y :: nil) ->\n  z \\notin assoc.dom d -> x \\notin assoc.dom d -> y \\notin assoc.dom d ->\n  signed k rz \\notin assoc.cdom d -> signed k rx \\notin assoc.cdom d -> unsign rk ry \\notin assoc.cdom d ->\n  (z <- (var_e x \\+ var_e y)%pseudo_expr)%pseudo_cmd\n    <=p( state_mint (z |=> signed k rz \\U+ (x |=> signed k rx \\U+ (y |=> unsign rk ry \\U+ d))),\n         (fun s st _ => [rk ]_ st <> zero32 /\\\n                       u2Z ([rk ]_ st) < 2 ^^ 31 /\\\n                       k = '|u2Z ([rk ]_ st)| /\\\n                       `| ([x ]_ s)%pseudo_expr | < \\B^(k - 1) /\\\n                       0 <= ([y ]_ s)%pseudo_expr < \\B^(k - 1))%asm_expr )\n  multi_add_s_s_u rk rz rx ry a0 a1 a2 a3 a4 ret X Y.\nProof.\nmove=> Hvars Hregs Disj z_d x_d y_d rz_d rx_d ry_d.\nrewrite /pfwd_sim => s st h [s_st_h [rk_0 [rk_231 [Hk [x_fit y_fit]]]]] s' exec_pseudo st' h' exec_asm.\n\nmove: (proj1 s_st_h z (signed k rz)).\nrewrite assoc.get_union_sing_eq.\ncase/(_ Logic.eq_refl) => lz pz Z rz_fit [Z_k lz_k lz_z z_Z] pz_fit mem_z.\n\nmove: (proj1 s_st_h x (signed k rx)).\nrewrite assoc.get_union_sing_neq; last by Uniq_neq.\nrewrite assoc.get_union_sing_eq.\ncase/(_ Logic.eq_refl) => lx px X_ rx_fit [X_k lx_k lx_x x_X] px_fit mem_x.\n\nmove: (proj1 s_st_h y (unsign rk ry)).\nrewrite assoc.get_union_sing_neq; last by Uniq_neq.\nrewrite assoc.get_union_sing_neq; last by Uniq_neq.\nrewrite assoc.get_union_sing_eq.\ncase/(_ Logic.eq_refl).\nmove=> ry_fit _ (*y_fit: superseded by y_fit*) mem_y.\nhave Htmp : 0 < Z_of_nat k < 2 ^^ 31.\n  rewrite Hk Z_of_nat_Zabs_nat; last exact: min_u2Z.\n  split => //.\n  rewrite ltZ_neqAle; split; last exact: min_u2Z.\n  contradict rk_0.\n  by apply u2Z_inj; rewrite -rk_0 Z2uK.\nmove/multi_add_s_s_u_triple : (Hregs).\nrewrite -Hk in ry_fit.\nmove/(_ k [rz]_st [rx]_st [ry]_st Htmp pz px pz_fit px_fit ry_fit Z X_\n  (Z2ints 32 '|u2Z [rk ]_ st| ([y ]_ s)%pseudo_expr) Z_k X_k) => {Htmp}.\nrewrite size_Z2ints Hk.\nmove/(_ Logic.eq_refl).\nrewrite -Hk.\nmove/( _ _ _ lx_k lz_k).\nrewrite -x_X lx_x.\nmove/(_ Logic.eq_refl) => hoare_triple.\n\nhave [st'' [h'' exec_asm_proj]] : exists st'' h'',\n  (Some (st, h |P| heap.dom (heap_mint (signed k rz) st h \\U\n    heap_mint (signed k rx) st h \\U heap_mint (unsign rk ry) st h))\n    -- multi_add_s_s_u rk rz rx ry a0 a1 a2 a3 a4 ret X Y --->\n    Some (st'', h''))%mips_cmd.\n  exists st', (h' |P| heap.dom (heap_mint (signed k rz) st h \\U\n    heap_mint (signed k rx) st h \\U heap_mint (unsign rk ry) st h)).\n  rewrite conCE in hoare_triple.\n  rewrite [in X in ({{ _ }} _ {{ X }} )%asm_hoare]conCE in hoare_triple.\n  apply (mips_syntax.triple_exec_proj _ _ _ hoare_triple) => {hoare_triple} //.\n  repeat (split; first reflexivity).\n  split.\n    rewrite Hk Z_of_nat_Zabs_nat //; exact: min_u2Z.\n  rewrite conCE.\n  rewrite -conAE.\n  rewrite heap.proj_dom_union; last first.\n    apply heap.disjUh.\n    apply (proj2 s_st_h z y); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n    apply (proj2 s_st_h x y); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n  apply con_cons.\n    apply heap.dis_disj_proj.\n    rewrite -heap.disjE.\n    apply heap.disjUh.\n    apply (proj2 s_st_h z y); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n    apply (proj2 s_st_h x y); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n  rewrite heap.proj_dom_union; last first.\n    apply (proj2 s_st_h z x); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n  apply con_cons.\n    apply heap.dis_disj_proj.\n    rewrite -heap.disjE.\n    apply (proj2 s_st_h z x); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n  move: (heap_inclu_heap_mint_signed h st k rz).\n  by move/heap.incluE => ->.\n  move: (heap_inclu_heap_mint_signed h st k rx).\n  by move/heap.incluE => ->.\n  move: (heap_inclu_heap_mint_unsign h st rk ry).\n  move/heap.incluE => ->. by rewrite Hk.\n\nset postcond := (fun s h => exists _, _)%asm_assert in hoare_triple.\nhave {hoare_triple}hoare_triple_post_cond : (postcond ** TT)%asm_assert st' h'.\n  move: {hoare_triple}(mips_frame.frame_rule_R _ _ _ hoare_triple TT (inde_TT _) (mips_frame.inde_cmd_mult_TT _)).\n    move/mips_seplog.hoare_prop_m.soundness.\n    rewrite /while.hoare_semantics.\n    move/(_ st h) => Hmulti_add_s_s_u.\n    lapply Hmulti_add_s_s_u; last first.\n      exists (heap_mint (signed k rz) st h \\U heap_mint (signed k rx) st h \\U heap_mint (unsign rk ry) st h),\n       (h \\D\\ heap.dom (heap_mint (signed k rz) st h \\U heap_mint (signed k rx) st h \\Uheap_mint (unsign rk ry) st h)).\n      split; first by apply heap.disj_difs', seq_ext.inc_refl.\n      split.\n        apply heap.union_difsK; last by [].\n        apply heap_prop_m.inclu_union.\n        apply heap_prop_m.inclu_union; by [apply heap_inclu_heap_mint_signed | apply heap.inclu_proj].\n        by apply heap_inclu_heap_mint_unsign.\n      split; last by [].\n      repeat (split=> //).\n      rewrite Hk Z_of_nat_Zabs_nat //; exact: min_u2Z.\n      rewrite -conAE.\n      apply con_cons => //.\n      + apply heap.disjUh.\n        apply (proj2 s_st_h z y); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n        apply (proj2 s_st_h x y); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n      + apply con_cons => //.\n        apply (proj2 s_st_h z x); by [Uniq_neq | assoc_get_Some | assoc_get_Some].\n        by rewrite Hk.\n    case=> _.\n    by move/(_ _ _ exec_asm).\n\nhave rz_st_st' : [ rz ]_ st = [ rz ]_ st'.\n  mips_syntax.Reg_unchanged. simpl mips_frame.modified_regs. by Uniq_not_In.\nhave rx_st_st' : [ rx ]_ st = [ rx ]_ st'.\n  mips_syntax.Reg_unchanged. simpl mips_frame.modified_regs. by Uniq_not_In.\nhave rk_st_st' : [ rk ]_ st = [ rk ]_ st'.\n  mips_syntax.Reg_unchanged. simpl mips_frame.modified_regs. by Uniq_not_In.\n\nsplit.\n- move=> x0 mx0 x0_mx0.\n  case/assoc.get_union_Some_inv : x0_mx0.\n  + case/assoc.get_sing_inv => ? ?; subst x0 mx0.\n    case: hoare_triple_post_cond => h1 [h2 [h1dh2 [h1Uh2 [Hh1 _]]]].\n    case: Hh1 => Z' [lz' [Z'_k [ry_st'_st [lz'_k [lz'_x_y [Hh1 [Ha3 Z'_x_y]]]]]]].\n        have Hk' : k <> O.\n          move=> abs.\n          rewrite Hk in abs.\n          move: abs.\n          contradict rk_0.\n          apply Zabs_nat_0_inv in rk_0.\n          rewrite (_ : 0 = u2Z zero32) in rk_0; last by rewrite Z2uK.\n          by move/u2Z_inj : rk_0.\n    apply mkVarSigned with lz' pz Z' => //.\n    * by rewrite -rz_st_st'.\n    * apply mkSignMagn => //.\n      - rewrite lz'_k Zsgn_Zmult ZsgnK.\n        have -> : sgZ (Z_of_nat k) = 1.\n          apply Z.sgn_pos.\n          rewrite Hk Z_of_nat_Zabs_nat; last exact: min_u2Z.\n          rewrite ltZ_neqAle; split; last exact: min_u2Z.\n          contradict rk_0.\n          apply u2Z_inj; by rewrite -rk_0 Z2uK.\n        rewrite mulZ1.\n        move/syntax_m.seplog_m.semop_prop_m.exec_cmd0_inv : exec_pseudo.\n        case/syntax_m.seplog_m.exec0_assign_inv => _ ->.\n        repeat syntax_m.seplog_m.assert_m.expr_m.Store_upd.\n        rewrite lz'_x_y.\n        rewrite lSum_Z2ints; last first.\n          apply/ltZ_norml; split.\n            apply: (@ltZ_leZ_trans 0); [rewrite ltZ_oppl oppZ0; exact: expZ_gt0|tauto].\n          case: y_fit => _ y_fit.\n          apply/(ltZ_leZ_trans y_fit)/leZP; rewrite ZbetaE Zpower_2_le; ssromega.\n        rewrite /= /ZIT.add geZ0_norm //; tauto.\n      - move/syntax_m.seplog_m.semop_prop_m.exec_cmd0_inv : exec_pseudo.\n        case/syntax_m.seplog_m.exec0_assign_inv => _ ->.\n        repeat syntax_m.seplog_m.assert_m.expr_m.Store_upd.\n        rewrite lSum_Z2ints geZ0_norm in Z'_x_y; last  tauto.\n        + case: (Z_zerop (s2Z lz')) => lz'_neq0.\n            by rewrite lz'_neq0 /= /ZIT.add /= -Z'_x_y lz'_neq0.\n          have {}Ha3 : u2Z [a3]_st' = 0.\n            have Htmp : `|u2Z [a3 ]_ st' * \\B^k + \\S_{ k } Z'| < \\B^k.\n              apply Zabs_Zsgn_1 in lz'_neq0.\n              rewrite -[X in X < _]mul1Z -lz'_neq0 -normZM addZC Z'_x_y.\n              apply: leZ_ltZ_trans; first exact: Z.abs_triangle.\n              apply: (@ltZ_leZ_trans (\\B^(k - 1) + \\B^(k - 1))).\n              apply Z.add_le_lt_mono => //; first exact: ltZW.\n              rewrite geZ0_norm; tauto.\n              apply/leZP; rewrite /Zbeta Zpower_plus Zpower_2_le; ssromega.\n            eapply poly_Zlt1_Zabs_inv; last by apply Htmp.\n            exact: min_lSum.\n            exact: min_u2Z.\n            by [].\n          rewrite /= /ZIT.add -Z'_x_y Ha3; ring.\n        + tauto.\n        + case: y_fit => _ y_fit; apply (ltZ_trans y_fit).\n          rewrite /Zbeta; apply expZ_2_lt; ssromega.\n    * case: Hh1 => h11 [h12 [h11dh12 [h11Uh12 [Hh11 Hh12]]]].\n       apply con_heap_mint_signed_cons with h11 => //.\n      - rewrite h1Uh2.\n        apply heap.inclu_union_L => //.\n        rewrite h11Uh12.\n        apply heap.inclu_union_L => //.\n        exact: heap.inclu_refl.\n      - by rewrite -rz_st_st'.\n      - by rewrite Z'_k.\n  + move=> x0_mx0.\n    have x0z : x0 <> z.\n      move=> ?; subst x0.\n      case/assoc.get_union_Some_inv : x0_mx0.\n        case/assoc.get_sing_inv => abs _; move: abs.\n        rewrite -/(z <> x); by Uniq_neq.\n      case/assoc.get_union_Some_inv.\n        case/assoc.get_sing_inv => abs _; move: abs.\n        rewrite -/(z <> y); by Uniq_neq.\n      move/assoc.get_Some_in_dom => abs; by rewrite abs in z_d.\n\nhave Hd_unchanged : forall v r, assoc.get v d = Some r ->\n  disj (mint_regs r) (mips_frame.modified_regs (multi_add_s_s_u rk rz rx ry a0 a1 a2 a3 a4 ret X Y)).\n  move=> v r Hvr; rewrite [mips_frame.modified_regs _]/=; Disj_remove_dup.\n  apply (disj_incl_LR Disj); last by apply incl_refl_Permutation; PermutProve.\n  apply/incP/inc_mint_regs.\n  by move/assoc.get_Some_in_cdom : Hvr.\n\n    apply var_mint_invariant with s st.\n    - move=> rx0 Hrx0.\n      mips_syntax.Reg_unchanged.\n      apply (@disj_not_In _ (mint_regs mx0)); last by [].\n      case/assoc.get_union_Some_inv : x0_mx0.\n        case/assoc.get_sing_inv => ? ?; subst x0 mx0.\n        simpl mint_regs. simpl modified_regs. Disj_remove_dup. simpl. apply uniq_disj.\n        simpl cat. by Uniq_uniq r0.\n      case/assoc.get_union_Some_inv.\n        case/assoc.get_sing_inv => ? ?; subst x0 mx0.\n        simpl mint_regs. simpl modified_regs. Disj_remove_dup. simpl. apply uniq_disj.\n        simpl cat. by Uniq_uniq r0.\n      move=> x0_mx0.\n      by apply disj_sym, (Hd_unchanged x0).\n    - Var_unchanged. rewrite /= mem_seq1; exact/negP/eqP.\n    - suff -> : heap_mint mx0 st' h' = heap_mint mx0 st h.\n        apply (proj1 s_st_h); by rewrite assoc.get_union_sing_neq.\n      symmetry.\n      case: hoare_triple_post_cond => h1 [h2 [h1dh2 [h1Uh2 [Hh1 _]]]].\n      case: Hh1 => Z' [lz' [Z'_k [ry_st'_st [lz'_k [sgn_lz' [Hh1 [Ha3 HSum]]]]]]].\n      case: Hh1 => h11 [h12 [h11dh12 [h11Uh12 [Hh11 Hh12]]]].\n      case: Hh12 => h121 [h122 [h121dh122 [h121Uh122 [Hh121 Hh122]]]].\n      case/assoc.get_union_Some_inv : (x0_mx0).\n        case/assoc.get_sing_inv => ? ?; subst x0 mx0.\n        have Htmp : (strictly_exact (var_e%asm_expr rx |--> lx :: px ::nil ** int_e px |--> X_))%asm_assert.\n          apply strictly_exact_con; by apply strictly_exact_mapstos.\n        apply: Htmp (conj mem_x _).\n        suff : (var_e%asm_expr rx |--> lx :: px :: nil ** int_e px |--> X_)%asm_assert st'\n          (heap_mint (signed k rx) st' h').\n          apply monotony => ?; by apply mapstos_ext.\n        apply con_heap_mint_signed_cons with h121 => //.\n        rewrite h1Uh2 h11Uh12 h121Uh122.\n        apply heap.inclu_union_L.\n        by map_tac_m.Disj.\n        apply heap.inclu_union_R.\n        by map_tac_m.Disj.\n        apply heap.inclu_union_L.\n        assumption.\n        by apply heap.inclu_refl.\n        by rewrite -rx_st_st'.\n        by rewrite X_k.\n      case/assoc.get_union_Some_inv.\n        case/assoc.get_sing_inv => ? ?; subst x0 mx0.\n        have Htmp : (strictly_exact (var_e%asm_expr ry |--> Z2ints 32 k ([y ]_ s)%pseudo_expr))%asm_assert.\n          by apply strictly_exact_mapstos.\n        rewrite -Hk in mem_y.\n        apply: Htmp (conj mem_y _).\n        suff : (var_e%asm_expr ry |--> Z2ints 32 k ([y ]_ s)%pseudo_expr)%asm_assert st'\n          (heap_mint (unsign rk ry) st' h').\n          by apply mapstos_ext.\n\n        apply con_heap_mint_unsign_cons with h122 => //.\n        rewrite h1Uh2 h11Uh12 h121Uh122.\n        apply heap.inclu_union_L.\n        by map_tac_m.Disj.\n        apply heap.inclu_union_R.\n        by map_tac_m.Disj.\n        apply heap.inclu_union_R.\n        assumption.\n        by apply heap.inclu_refl.\n        rewrite size_Z2ints.\n        by rewrite ry_st'_st.\n        rewrite size_Z2ints.\n        by rewrite -rk_st_st'.\n      move=> x0_d_mx0.\n\n      apply (heap_mint_state_invariant (heap_mint (signed k rz) st h \\U\n        heap_mint (signed k rx) st h \\U heap_mint (unsign rk ry) st h) x0 s) => //.\n      + move=> x1 Hx1.\n        mips_syntax.Reg_unchanged.\n        apply (@disj_not_In _ (mint_regs mx0)); last by [].\n        exact/disj_sym/(Hd_unchanged x0).\n      + apply (proj1 s_st_h).\n        rewrite assoc.get_union_sing_neq //; by auto.\n      + move: (mips_syntax.exec_deter_proj _ _ _ _ _ exec_asm _ _ _ exec_asm_proj).\n        tauto.\n      + apply heap.disjhU.\n        * apply heap.disjhU.\n          - apply (proj2 s_st_h x0 z) => //.\n            rewrite assoc.get_union_sing_neq //; by auto.\n            by assoc_get_Some.\n          - case/orP : (orbN (x0 == x)).\n            + move/eqP => ?; subst x0.\n              apply assoc.get_Some_in_dom in x0_d_mx0.\n              by rewrite x0_d_mx0 in x_d.\n            + move=> x0x.\n              apply (proj2 s_st_h x0 x) => //.\n              by apply/eqP.\n              rewrite assoc.get_union_sing_neq //; by auto.\n              by assoc_get_Some.\n        * case/orP : (orbN (x0 == y)).\n          - move/eqP => ?; subst x0.\n            apply assoc.get_Some_in_dom in x0_d_mx0.\n            by rewrite x0_d_mx0 in y_d.\n          - move=> x0y.\n            apply (proj2 s_st_h x0 y) => //.\n            by apply/eqP.\n            rewrite assoc.get_union_sing_neq //; by auto.\n            by assoc_get_Some.\n- case: hoare_triple_post_cond => h1 [h2 [h1dh2 [h1Uh2 [Hh1 _]]]].\n  case: Hh1 => Z' [lz' [Z'_k [ry_st'_st [lz'_k [sgn_lz' [Hh1 [Ha3 HSum]]]]]]].\n  case: Hh1 => h11 [h12 [h11dh12 [h11Uh12 [Hh11 Hh12]]]].\n  case: Hh12 => h121 [h122 [h121dh122 [h121Uh122 [Hh121 Hh122]]]].\n  apply state_mint_part2_three_variables with s st h => //.\n  + symmetry.\n    apply dom_heap_mint_sign_state_invariant with z s lz lz' => //.\n    move/mapstos_get1 : mem_z.\n    by apply heap_get_heap_mint_inv.\n    move/mapstos_get1 in Hh11.\n    rewrite h1Uh2 h11Uh12.\n    apply heap.get_union_L.\n    by map_tac_m.Disj.\n    by apply heap.get_union_L.\n    move/mapstos_get2 : mem_z.\n    move/heap_get_heap_mint_inv => ->.\n    symmetry.\n    move/mapstos_get2 in Hh11.\n    rewrite h1Uh2 h11Uh12.\n    apply heap.get_union_L.\n    by map_tac_m.Disj.\n    by apply heap.get_union_L.\n    apply (proj1 s_st_h z) => //.\n    by assoc_get_Some.\n    by apply (mips_syntax.dom_heap_invariant _ _ _ _ _ exec_asm).\n  + symmetry.\n    apply dom_heap_mint_sign_state_invariant with x s lx lx => //.\n    move/mapstos_get1 : mem_x.\n    by apply heap_get_heap_mint_inv.\n    move/mapstos_get1 in Hh121.\n    rewrite h1Uh2 h11Uh12 h121Uh122.\n    apply heap.get_union_L.\n    by map_tac_m.Disj.\n    apply heap.get_union_R.\n    by map_tac_m.Disj.\n    by apply heap.get_union_L.\n    move/mapstos_get2 : mem_x.\n    move/heap_get_heap_mint_inv => ->.\n    symmetry.\n    move/mapstos_get2 in Hh121.\n    rewrite h1Uh2 h11Uh12 h121Uh122.\n    apply heap.get_union_L.\n    by map_tac_m.Disj.\n    apply heap.get_union_R.\n    by map_tac_m.Disj.\n    by apply heap.get_union_L.\n    apply (proj1 s_st_h x) => //.\n    by assoc_get_Some.\n    by apply (mips_syntax.dom_heap_invariant _ _ _ _ _ exec_asm).\n  + symmetry.\n    apply dom_heap_mint_unsign_state_invariant with y s => //.\n    apply (proj1 s_st_h y) => //.\n    by assoc_get_Some.\n    by apply (mips_syntax.dom_heap_invariant _ _ _ _ _ exec_asm).\n  + move=> t Ht x0 Hx0.\n    mips_syntax.Reg_unchanged. simpl mips_frame.modified_regs.\n    case/assoc.in_cdom_union_inv : Ht.\n    * rewrite assoc.cdom_sing seq.mem_seq1.\n      move/eqP=> ?; subst t.\n      apply (@disj_not_In _ (mint_regs (signed k rz))); last by [].\n      Disj_remove_dup.\n      rewrite /=.\n      apply uniq_disj. rewrite [cat _ _]/=. by Uniq_uniq r0.\n    * case/assoc.in_cdom_union_inv.\n      - rewrite assoc.cdom_sing seq.mem_seq1.\n        move/eqP=> ?; subst t.\n        apply (@disj_not_In _ (mint_regs (signed k rx))); last by [].\n        Disj_remove_dup.\n        rewrite /=.\n        apply uniq_disj. rewrite [cat _ _]/=. by Uniq_uniq r0.\n      - case/assoc.in_cdom_union_inv.\n        * rewrite assoc.cdom_sing seq.mem_seq1.\n          move/eqP=> ?; subst t.\n          apply (@disj_not_In _ (mint_regs (unsign rk ry))); last by [].\n          Disj_remove_dup.\n          rewrite /=.\n          apply uniq_disj. rewrite [cat _ _]/=. by Uniq_uniq r0.\n        * move=> Ht; apply (@disj_not_In _ (mint_regs t)); last by [].\n          Disj_remove_dup.\n          apply disj_sym.\n          apply (disj_incl_LR Disj); last by apply incl_refl_Permutation; PermutProve.\n          exact/incP/inc_mint_regs.\n- move: (mips_syntax.exec_deter_proj _ _ _ _ _ exec_asm _ _ _ exec_asm_proj); tauto.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/begcd/multi_add_s_s_u_simu.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.20410037040388007}}
{"text": "(* Non-determinism *)\n\nFrom Coq Require Import Utf8 RelationClasses List.\nFrom PDM Require Import util structures guarded PURE GuardedPDM.\n\nImport ListNotations.\n\nSet Default Goal Selector \"!\".\nSet Printing Projections.\nSet Universe Polymorphism.\nUnset Universe Minimization ToSet.\n\n(* Computation monad *)\n\nDefinition M A :=\n  list A.\n\n#[export] Instance Monad_M : Monad M := {|\n  ret A x := [ x ] ;\n  bind A B c f := concat (map f c)\n|}.\n\n(* Effect observation *)\n\nDefinition θ : observation M pure_wp.\nProof.\n  intros A c.\n  exists (λ post, ∀ x, In x c → post x).\n  intros P Q hPQ h. intros x hx.\n  apply hPQ. apply h. apply hx.\nDefined.\n\n(* LeafPred *)\n\n#[local] Instance leafpred : LeafPred M :=\n  λ A x c, In x c.\n\nFixpoint leafine [A] (c : M A) : M { x : A | x ∈ c }.\nProof.\n  destruct c as [| x c].\n  - exact [].\n  - refine (⟨ x ⟩ :: map (λ x, ⟨ val x ⟩) (leafine _ c)).\n    + left. reflexivity.\n    + destruct x. right. assumption.\nDefined.\n\n#[local] Instance hleaf : Leafine M leafpred :=\n  leafine.\n\n(* Partial DM *)\n\nDefinition D A (w : pure_wp A) : Type :=\n  GuardedPDM.D (M := M) (θ := θ) (λ A w, w) A w.\n\nDefinition liftᵂ : spec_lift_pure pure_wp :=\n  λ A w, w.\n\n#[local] Instance LaxMorphism_θᴳ :\n  @LaxMorphism _ _ (Monad_Mᴳ _ _) _ _ (θᴳ (θ := θ) liftᵂ).\nProof.\n  constructor.\n  - intros A x. intros post h.\n    cbv - [In] in *.\n    exists I. intros y hy. destruct hy. 2: contradiction.\n    subst. apply h.\n  - intros A B c f. intros post h.\n    destruct c as [p c].\n    hnf. hnf in h.\n    destruct h as [hp h]. simpl in hp, h.\n    unshelve eexists.\n    + simpl. exists hp.\n      intros x hx. apply h. apply hx.\n    + hnf. simpl. intros y hy.\n      apply in_concat in hy. destruct hy as [l [hl hy]].\n      apply in_map_iff in hl. destruct hl as [x [e hxc]].\n      destruct x as [x hx].\n      set (h' := h x hx) in *. clearbody h'. clear h.\n      destruct h' as [hf h]. subst l.\n      apply h. assumption.\nQed.\n\n#[export] Instance DijkstraMonad_D : DijkstraMonad D :=\n  GuardedPDM.DijkstraMonad_D _ _ _ _ _.\n\n(* Lift from PURE *)\n\n#[local] Instance ReqLaxMorphism_θᴳ :\n  @ReqLaxMorphism _ _ _ (ReqMonad_Mᴳ _ _) _ _ pure_wp_ord (θᴳ (θ := θ) liftᵂ) LaxMorphism_θᴳ.\nProof.\n  constructor.\n  intro p. intros post h.\n  cbv - [In]. cbv - [In] in h. destruct h as [hp h].\n  unshelve eexists.\n  { exists hp. auto. }\n  simpl. intros ? [? | bot]. 2: contradiction.\n  subst. assumption.\nQed.\n\nDefinition liftᴾ [A w] (f : PURE A w) : D A w :=\n  liftᴾ MonoSpec_pure leafpred hleaf (λ A w, w) _ _ _ A w f.", "meta": {"author": "TheoWinterhalter", "repo": "pdm4all", "sha": "570868f2e395bada6e3dc0462d7e9af065289461", "save_path": "github-repos/coq/TheoWinterhalter-pdm4all", "path": "github-repos/coq/TheoWinterhalter-pdm4all/pdm4all-570868f2e395bada6e3dc0462d7e9af065289461/theories/ND.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.20410037040388007}}
{"text": "Require Import AutoSep Malloc Bags ThreadQueue ThreadQueues SinglyLinkedList MoreArrays.\nImport W_Bag.\nExport AutoSep Malloc W_Bag.\n\nModule Type S.\n  Parameter globalSched : W.\n\n  Parameter globalInv : bag -> HProp.\n  (* Argument is set of available file objects. *)\nEnd S.\n\nSection specs.\n  Variable globalSched : W.\n  Variables sched globalInv : bag -> HProp.\n  Variable starting : W -> nat -> HProp.\n\n  Definition initGS : spec := SPEC reserving 18\n    PRE[_] globalSched =?> 1 * mallocHeap 0\n    POST[R] sched empty * mallocHeap 0.\n\n  Definition spawnGS : spec := SPEC(\"pc\", \"ss\") reserving 26\n    Al fs,\n    PRE[V] [| V \"ss\" >= $2 |] * sched fs * starting (V \"pc\") (wordToNat (V \"ss\") - 1) * mallocHeap 0\n    POST[_] sched fs * mallocHeap 0.\n\n  Definition exitGS : spec := SPEC(\"ss\") reserving 18\n    Al fs,\n    PREexit[V] [| V \"ss\" >= $18 |] * sched fs * globalInv fs * mallocHeap 0.\n\n  Definition yieldGS : spec := SPEC reserving 28\n    Al fs,\n    PRE[_] sched fs * globalInv fs * mallocHeap 0\n    POST[_] Ex fs', [| fs %<= fs' |] * sched fs' * globalInv fs' * mallocHeap 0.\n\n  Definition listenGS : spec := SPEC(\"port\") reserving 25\n    Al fs,\n    PRE[_] sched fs * mallocHeap 0\n    POST[R] Ex fs', [| fs %<= fs' |] * sched fs' * mallocHeap 0 * [| R %in fs' |].\n\n  Definition closeGS : spec := SPEC(\"fr\") reserving 11\n    Al fs,\n    PRE[V] [| V \"fr\" %in fs |] * sched fs * mallocHeap 0\n    POST[_] sched fs * mallocHeap 0.\n\n  Definition readGS : spec := SPEC(\"fr\", \"buffer\", \"size\") reserving 32\n    Al fs,\n    PRE[V] [| V \"fr\" %in fs |] * V \"buffer\" =?>8 wordToNat (V \"size\") * sched fs * mallocHeap 0 * globalInv fs\n    POST[_] Ex fs', [| fs %<= fs' |] * V \"buffer\" =?>8 wordToNat (V \"size\") * sched fs' * mallocHeap 0 * globalInv fs'.\n\n  Definition writeGS : spec := SPEC(\"fr\", \"buffer\", \"size\") reserving 32\n    Al fs,\n    PRE[V] [| V \"fr\" %in fs |] * V \"buffer\" =?>8 wordToNat (V \"size\") * sched fs * mallocHeap 0 * globalInv fs\n    POST[_] Ex fs', [| fs %<= fs' |] * V \"buffer\" =?>8 wordToNat (V \"size\") * sched fs' * mallocHeap 0 * globalInv fs'.\n\n  Definition acceptGS : spec := SPEC(\"fr\") reserving 32\n    Al fs,\n    PRE[V] [| V \"fr\" %in fs |] * sched fs * mallocHeap 0 * globalInv fs\n    POST[R] Ex fs', Ex fs'', [| fs %<= fs' |] * [| fs' %<= fs'' |]\n    * [| R %in fs'' |] * sched fs'' * mallocHeap 0 * globalInv fs'.\nEnd specs.\n  \n\nModule Make(M : S).\nImport M.\n\nDefinition allIn (b : bag) := List.Forall (fun p => p %in b).\nDefinition allInOrZero (b : bag) := List.Forall (fun p => p = $0 \\/ p %in b).\n\nDefinition files (ts : bag) : bag -> HProp :=\n  starB (fun p => Ex fd, Ex inq, Ex outq, (p ==*> fd, inq, outq) * [| inq %in ts |] * [| outq %in ts |])%Sep.\n\nModule M''.\n  Definition world := bag.\n\n  Definition evolve : bag -> bag -> Prop := incl.\n\n  Theorem evolve_refl : forall w, evolve w w.\n    red; bags.\n  Qed.\n\n  Theorem evolve_trans : forall w1 w2 w3, evolve w1 w2 -> evolve w2 w3 -> evolve w1 w3.\n    unfold evolve in *; bags.\n  Qed.\n\n  Open Scope Sep_scope.\n\n  Definition globalInv (ts : bag) (w : world) : HProp :=\n    Ex p, Ex ready, Ex free, Ex wait, Ex waitLen, Ex freeL, Ex waitL,\n    \n    (* The scheduler entry point *)\n    globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n\n    (* The ready queue is a valid thread queue, for threads ready to run immediately. *)\n    * [| ready %in ts |]\n\n    (* The free list stores available file pointers. *)\n    * sll freeL free * [| allIn w freeL |]\n\n    (* Each available file pointer stores a record of a file descriptor and input/output thread queues. *)\n    * files ts w\n\n    (* There is an array correspoinding to outstanding declare() calls, mapping each to a queue that should be poked when its event is enabled. *)\n    * array waitL wait * [| allInOrZero ts waitL |]\n      * [| length waitL = wordToNat waitLen |]\n      * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n\n    (* Finally, the application-specific global invariant holds. *)\n    * globalInv w.\nEnd M''.\n\nModule Q' := ThreadQueues.Make(M'').\nImport M'' Q'.\nExport M'' Q'.\n\n\nDefinition files_pick (_ : W) := files.\n\nModule Type SCHED.\n  Parameter sched : bag -> HProp.\n  (* Parameter is available file pointers. *)\n\n  Axiom sched_fwd : forall fs, sched fs ===>\n    Ex ts, Ex p, globalSched =*> p\n    * Ex ready, Ex free, Ex wait, Ex waitLen, (p ==*> ready, free, wait, waitLen)\n    * [| ready %in ts |]\n    * Ex freeL, sll freeL free * [| allIn fs freeL |]\n    * files ts fs\n    * Ex waitL, array waitL wait * [| allInOrZero ts waitL |] * [| length waitL = wordToNat waitLen |]\n      * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n    * tqs ts fs.\n\n  Axiom sched_bwd : forall fs,\n    (Ex ts, Ex p, globalSched =*> p\n     * Ex ready, Ex free, Ex wait, Ex waitLen, (p ==*> ready, free, wait, waitLen)\n     * [| ready %in ts |]\n     * Ex freeL, sll freeL free * [| allIn fs freeL |]\n     * files ts fs\n     * Ex waitL, array waitL wait * [| allInOrZero ts waitL |] * [| length waitL = wordToNat waitLen |]\n       * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n     * tqs ts fs)\n    ===> sched fs.\n\n  Axiom files_empty_fwd : forall ts, files ts empty ===> Emp.\n  Axiom files_empty_bwd : forall ts, Emp ===> files ts empty.\n\n  Axiom files_pick_fwd : forall p ts fs, p %in fs\n    -> files_pick p ts fs ===> Ex fd, Ex inq, Ex outq, (p ==*> fd, inq, outq)\n      * [| inq %in ts |] * [| outq %in ts |] * files ts (fs %- p).\n  Axiom files_pick_bwd : forall p ts fs, p %in fs\n    -> (Ex fd, Ex inq, Ex outq, (p ==*> fd, inq, outq)\n      * [| inq %in ts |] * [| outq %in ts |] * files ts (fs %- p)) ===> files_pick p ts fs.\n\n  Axiom files_add_bwd : forall p ts fs,\n    (Ex fd, Ex inq, Ex outq, (p ==*> fd, inq, outq)\n      * [| inq %in ts |] * [| outq %in ts |] * files ts fs) ===> files ts (fs %+ p).\nEnd SCHED.\n\nModule Sched : SCHED.\n  Open Scope Sep_scope.\n\n  Definition sched fs :=\n    Ex ts, Ex p, globalSched =*> p\n    * Ex ready, Ex free, Ex wait, Ex waitLen, (p ==*> ready, free, wait, waitLen)\n    * [| ready %in ts |]\n    * Ex freeL, sll freeL free * [| allIn fs freeL |]\n    * files ts fs\n    * Ex waitL, array waitL wait * [| allInOrZero ts waitL |] * [| length waitL = wordToNat waitLen |]\n      * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n    * tqs ts fs.\n\n  Theorem sched_fwd : forall fs, sched fs ===>\n    Ex ts, Ex p, globalSched =*> p\n    * Ex ready, Ex free, Ex wait, Ex waitLen, (p ==*> ready, free, wait, waitLen)\n    * [| ready %in ts |]\n    * Ex freeL, sll freeL free * [| allIn fs freeL |]\n    * files ts fs\n    * Ex waitL, array waitL wait * [| allInOrZero ts waitL |] * [| length waitL = wordToNat waitLen |]\n      * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n    * tqs ts fs.\n    intros; apply Himp_refl.\n  Qed.\n\n  Theorem sched_bwd : forall fs,\n    (Ex ts, Ex p, globalSched =*> p\n     * Ex ready, Ex free, Ex wait, Ex waitLen, (p ==*> ready, free, wait, waitLen)\n     * [| ready %in ts |]\n     * Ex freeL, sll freeL free * [| allIn fs freeL |]\n     * files ts fs\n     * Ex waitL, array waitL wait * [| allInOrZero ts waitL |] * [| length waitL = wordToNat waitLen |]\n       * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n     * tqs ts fs)\n     ===> sched fs.\n    intros; apply Himp_refl.\n  Qed.\n\n  Theorem files_empty_fwd : forall ts, files ts empty ===> Emp.\n    intros; apply starB_empty_fwd.\n  Qed.\n\n  Theorem files_empty_bwd : forall ts, Emp ===> files ts empty.\n    intros; apply starB_empty_bwd.\n  Qed.\n\n  Ltac fin ts := match goal with\n                   | [ |- context[starB ?X ?Y] ] => change (starB X Y) with (files ts Y)\n                 end; sepLemma.\n\n  Theorem files_pick_fwd : forall p ts fs, p %in fs\n    -> files_pick p ts fs ===> Ex fd, Ex inq, Ex outq, (p ==*> fd, inq, outq)\n      * [| inq %in ts |] * [| outq %in ts |] * files ts (fs %- p).\n    intros; eapply Himp_trans; [ apply starB_del_fwd | ]; eauto; fin ts.\n  Qed.\n\n  Theorem files_pick_bwd : forall p ts fs, p %in fs\n    -> (Ex fd, Ex inq, Ex outq, (p ==*> fd, inq, outq)\n      * [| inq %in ts |] * [| outq %in ts |] * files ts (fs %- p)) ===> files_pick p ts fs.\n    intros; eapply Himp_trans; [ | apply starB_del_bwd ]; eauto; fin ts.\n  Qed.\n\n  Theorem files_add_bwd : forall p ts fs,\n    (Ex fd, Ex inq, Ex outq, (p ==*> fd, inq, outq)\n      * [| inq %in ts |] * [| outq %in ts |] * files ts fs) ===> files ts (fs %+ p).\n    intros; eapply Himp_trans; [ | apply starB_add_bwd ]; fin ts.\n  Qed.\nEnd Sched.\n\nImport Sched.\nExport Sched.\n\n\nDefinition exitize_me a b c d := locals a b c d.\n\nLemma exitize_locals : forall xx yy ns vs res sp,\n  exitize_me (\"rp\" :: xx :: yy :: ns) vs res sp ===> Ex vs', locals (\"rp\" :: \"sc\" :: \"ss\" :: nil) (upd (upd vs' \"ss\" (sel vs yy)) \"sc\" (sel vs xx)) (res + length ns) sp.\n  unfold exitize_me, locals; intros.\n  simpl; unfold upd; simpl.\n  apply Himp_ex_c; exists (fun x => if string_dec x \"rp\" then vs \"rp\" else vs xx).\n  eapply Himp_trans.\n  eapply Himp_star_frame.\n  eapply Himp_star_frame.\n  apply Himp_refl.\n  change (vs \"rp\" :: vs xx :: vs yy :: toArray ns vs)\n    with (toArray ((\"rp\" :: xx :: yy :: nil) ++ ns) vs).\n  apply ptsto32m_split.\n  apply Himp_refl.\n  destruct (string_dec \"rp\" \"rp\"); intuition.\n  destruct (string_dec \"sc\" \"rp\"); intuition.\n  unfold array, toArray in *.\n  simpl map in *.\n  simpl length in *.\n\n  Lemma switchedy : forall P Q R S : HProp,\n    (P * (Q * R)) * S ===> P * (Q * (R * S)).\n    sepLemma.\n  Qed.\n\n  eapply Himp_trans; [ apply switchedy | ].\n  \n  Lemma swatchedy : forall P Q R : HProp,\n    P * (Q * R) ===> P * Q * R.\n    sepLemma.\n  Qed.\n\n  eapply Himp_trans; [ | apply swatchedy ].\n  apply Himp_star_frame.\n  sepLemma; NoDup.\n  apply Himp_star_frame.\n  apply Himp_refl.\n  eapply Himp_trans; [ | apply allocated_join ].\n  apply Himp_star_frame.\n  eapply Himp_trans; [ | apply allocated_shift_base ].\n  apply ptsto32m_allocated.\n  simpl.\n  words.\n  eauto.\n  apply allocated_shift_base.\n  rewrite map_length.\n  repeat rewrite <- wplus_assoc.\n  repeat rewrite <- natToW_plus.\n  f_equal.\n  f_equal.\n  omega.\n  rewrite map_length; omega.\n  rewrite map_length; omega.\nQed.\n\nDefinition hints : TacPackage.\n  prepare (sched_fwd, SinglyLinkedList.nil_fwd, SinglyLinkedList.cons_fwd, allocate_array,\n    files_empty_fwd, files_pick_fwd, exitize_locals)\n  (sched_bwd, SinglyLinkedList.nil_bwd, SinglyLinkedList.cons_bwd, free_array, tqs_empty_bwd,\n    files_empty_bwd, files_pick_bwd, files_add_bwd).\nDefined.\n\nDefinition starting (pc : W) (ss : nat) : HProp := fun s m =>\n  (ExX (* pre *) : settings * state, Cptr pc #0\n    /\\ [| semp m |]\n    /\\ Al st : settings * state, Al vs, Al fs,\n    [| st#Sp <> 0 /\\ freeable st#Sp (1 + ss) |]\n    /\\ ![ ^[locals (\"rp\" :: nil) vs ss st#Sp * sched fs * M.globalInv fs * mallocHeap 0] ] st\n    ---> #0 st)%PropX.\n\nLemma starting_elim : forall specs pc ss P stn st,\n  interp specs (![ starting pc ss * P ] (stn, st))\n  -> (exists pre, specs pc = Some (fun x => pre x)\n    /\\ interp specs (![ P ] (stn, st))\n    /\\ forall stn_st vs fs, interp specs ([| stn_st#Sp <> 0 /\\ freeable stn_st#Sp (1 + ss) |]\n      /\\ ![ locals (\"rp\" :: nil) vs ss stn_st#Sp\n      * sched fs * M.globalInv fs * mallocHeap 0 ] stn_st\n    ---> pre stn_st)%PropX).\n  cptr.\n  generalize (split_semp _ _ _ H0 H); intros; subst; auto.\n  rewrite <- sepFormula_eq; descend; step auto_ext.\n  auto.\n  step auto_ext.\nQed.\n\nLocal Hint Resolve split_a_semp_a semp_smem_emp.\n\nLemma starting_intro : forall specs pc ss P stn st,\n  (exists pre, specs pc = Some (fun x => pre x)\n    /\\ interp specs (![ P ] (stn, st))\n    /\\ forall stn_st vs fs, interp specs ([| stn_st#Sp <> 0 /\\ freeable stn_st#Sp (1 + ss) |]\n      /\\ ![ locals (\"rp\" :: nil) vs ss stn_st#Sp\n      * sched fs * M.globalInv fs * mallocHeap 0 ] stn_st\n    ---> pre stn_st)%PropX)\n  -> interp specs (![ starting pc ss * P ] (stn, st)).\n  cptr.\nQed.\n\nLemma other_starting_intro : forall specs ts w pc ss P stn st,\n  (exists pre, specs pc = Some (fun x => pre x)\n    /\\ interp specs (![ P ] (stn, st))\n    /\\ forall stn_st vs ts' w', interp specs ([| ts %<= ts' |]\n      /\\ [| M''.evolve w w' |]\n      /\\ [| stn_st#Sp <> 0 /\\ freeable stn_st#Sp (1 + ss) |]\n      /\\ ![ locals (\"rp\" :: nil) vs ss stn_st#Sp\n      * tqs ts' w' * M''.globalInv ts' w' * mallocHeap 0 ] stn_st\n    ---> pre stn_st)%PropX)\n  -> interp specs (![ Q'.starting ts w pc ss * P ] (stn, st)).\n  cptr.\nQed.\n\n\nDefinition initS := initGS globalSched sched.\nDefinition spawnS := spawnGS sched starting.\nDefinition exitS := exitGS sched M.globalInv.\nDefinition yieldS := yieldGS sched M.globalInv.\nDefinition listenS := listenGS sched.\nDefinition closeS := closeGS sched.\nDefinition readS := readGS sched M.globalInv.\nDefinition writeS := writeGS sched M.globalInv.\nDefinition acceptS := acceptGS sched M.globalInv.\n\n(* Specs below this point are for \"private\" functions. *)\n\nDefinition pickNextS : spec := SPEC reserving 13\n  Al p, Al ready, Al free, Al wait, Al waitLen, Al ts, Al fs, Al waitL,\n  PRE[_] globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n    * tqs ts fs * [| ready %in ts |]\n    * array waitL wait * [| allInOrZero ts waitL |]\n    * [| length waitL = wordToNat waitLen |] * mallocHeap 0\n  POST[R] [| R %in ts |]\n    * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n    * tqs ts fs * [| ready %in ts |]\n    * array waitL wait * [| allInOrZero ts waitL |]\n    * [| length waitL = wordToNat waitLen |] * mallocHeap 0.\n\nDefinition newS : spec := SPEC(\"fd\") reserving 21\n  Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL,\n  PRE[V] globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n    * sll freeL free * [| allIn fs freeL |]\n    * files ts fs * tqs ts fs * mallocHeap 0\n  POST[R] Ex ts', Ex fs', Ex free', Ex freeL',\n    [| R %in fs' |] * [| ts %<= ts' |] * [| fs %<= fs' |]\n    * globalSched =*> p * (p ==*> ready, free', wait, waitLen)\n    * sll freeL' free' * [| allIn fs' freeL' |]\n    * files ts' fs' * tqs ts' fs' * mallocHeap 0.\n\nDefinition declareS : spec := SPEC(\"tq\", \"fd\", \"mode\") reserving 16\n    Al ts, Al p, Al ready, Al free, Al wait, Al waitLen, Al waitL,\n    PRE[V] [| V \"tq\" %in ts |] * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n      * array waitL wait * [| allInOrZero ts waitL |]\n      * [| length waitL = wordToNat waitLen |]\n      * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n      * mallocHeap 0\n    POST[_] Ex wait', Ex waitLen', Ex waitL',\n      globalSched =*> p * (p ==*> ready, free, wait', waitLen')\n      * array waitL' wait' * [| allInOrZero ts waitL' |]\n      * [| length waitL' = wordToNat waitLen' |]\n      * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n      * mallocHeap 0.\n\nDefinition blockS : spec := SPEC(\"tq\", \"fd\", \"mode\") reserving 26\n  Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n  PRE[V] [| V \"tq\" %in ts |]\n    * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n    * [| ready %in ts |]\n    * sll freeL free * [| allIn fs freeL |]\n    * files ts fs * tqs ts fs\n    * array waitL wait * [| allInOrZero ts waitL |]\n      * [| length waitL = wordToNat waitLen |]\n      * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n    * M.globalInv fs * mallocHeap 0\n  POST[_] Ex p', Ex ts', Ex fs', Ex ready', Ex free', Ex wait', Ex waitLen', Ex freeL', Ex waitL',\n    [| ts %<= ts' |] * [| fs %<= fs' |]\n    * globalSched =*> p' * (p' ==*> ready', free', wait', waitLen')\n    * [| ready' %in ts' |]\n    * sll freeL' free' * [| allIn fs' freeL' |]\n    * files ts' fs' * tqs ts' fs'\n    * array waitL' wait' * [| allInOrZero ts' waitL' |]\n      * [| length waitL' = wordToNat waitLen' |]\n      * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n    * M.globalInv fs' * mallocHeap 0.\n\nDefinition initSize := 2.\n\nTheorem initSize_eq : initSize = 2.\n  auto.\nQed.\n\nOpaque initSize.\n\nInductive add_a_file : Prop := AddAFile.\nInductive reveal_files_pick : Prop := RevealFilesPick.\nLocal Hint Constructors add_a_file reveal_files_pick.\n\nDefinition m := bimport [[ \"malloc\"!\"malloc\" @ [mallocS], \"malloc\"!\"free\" @ [freeS],\n                           \"threadqs\"!\"alloc\" @ [Q'.allocS], \"threadqs\"!\"spawn\" @ [Q'.spawnS],\n                           \"threadqs\"!\"exit\" @ [Q'.exitS], \"threadqs\"!\"yield\" @ [Q'.yieldS],\n                           \"threadqs\"!\"isEmpty\" @ [Q'.isEmptyS],\n\n                           \"sys\"!\"abort\" @ [abortS], \"sys\"!\"close\" @ [Sys.closeS],\n                           \"sys\"!\"listen\" @ [Sys.listenS], \"sys\"!\"accept\" @ [Sys.acceptS],\n                           \"sys\"!\"read\" @ [Sys.readS], \"sys\"!\"write\" @ [Sys.writeS],\n                           \"sys\"!\"declare\" @ [Sys.declareS], \"sys\"!\"wait\" @ [Sys.waitS] ]]\n  bmodule \"scheduler\" {{\n    bfunction \"init\"(\"root\", \"ready\", \"wait\") [initS]\n      \"root\" <-- Call \"malloc\"!\"malloc\"(0, 4)\n      [PRE[_, R] globalSched =?> 1 * R =?> 4 * mallocHeap 0\n       POST[_] sched empty * mallocHeap 0];;\n\n      globalSched *<- \"root\";;\n\n      Assert [PRE[V] globalSched =*> V \"root\" * V \"root\" =?> 4 * mallocHeap 0 * tqs empty empty\n        POST[_] sched empty * mallocHeap 0];;\n\n      \"ready\" <-- Call \"threadqs\"!\"alloc\"()\n      [PRE[V, R] globalSched =*> V \"root\" * V \"root\" =?> 4 * tqs (empty %+ R) empty * mallocHeap 0\n       POST[_] sched empty * mallocHeap 0];;\n\n      \"wait\" <-- Call \"malloc\"!\"malloc\"(0, initSize)\n      [PRE[V, R] R =?> initSize * [| R <> 0 |] * [| freeable R initSize |]\n         * globalSched =*> V \"root\" * V \"root\" =?> 4\n         * tqs (empty %+ V \"ready\") empty\n       POST[_] sched empty];;\n\n      Note [make_array];;\n\n      Assert [Al waitL,\n        PRE[V] array waitL (V \"wait\") * [| length waitL = 2 |] * [| V \"wait\" <> 0 |] * [| freeable (V \"wait\") 2 |]\n          * [| ($0 < natToW (length waitL))%word |]\n          * globalSched =*> V \"root\" * V \"root\" =?> 4 * tqs (empty %+ V \"ready\") empty\n        POST[_] sched empty];;\n\n      \"wait\"+0 *<- 0;;\n\n      Assert [Al waitL,\n        PRE[V] array waitL (V \"wait\") * [| length waitL = 2 |] * [| V \"wait\" <> 0 |] * [| freeable (V \"wait\") 2 |]\n          * [| ($1 < natToW (length waitL))%word |] * [| Array.selN waitL 0 = $0 |]\n          * globalSched =*> V \"root\" * V \"root\" =?> 4 * tqs (empty %+ V \"ready\") empty\n        POST[_] sched empty];;\n\n      \"wait\"+4 *<- 0;;\n\n      \"root\" *<- \"ready\";;\n      \"root\"+4 *<- 0;;\n      \"root\"+8 *<- \"wait\";;\n      \"root\"+12 *<- 2;;\n      Return 0\n    end with bfunction \"spawn\"(\"pc\", \"ss\", \"root\") [spawnS]\n      \"root\" <-* globalSched;;\n      \"root\" <-* \"root\";;\n\n      Call \"threadqs\"!\"spawn\"(\"root\", \"pc\", \"ss\")\n      [PRE[_] Emp\n       POST[_] Emp];;\n      Return 0\n    end with bfunctionNoRet \"exit\"(\"ss\", \"tq\", \"tmp\") [exitS]\n      \"tq\" <-- Call \"scheduler\"!\"pickNext\"()\n      [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n        PREexit[V, R] globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n          * [| ready %in ts |] * [| R %in ts |] * [| (V \"ss\" >= $18)%word |]\n          * sll freeL free * [| allIn fs freeL |]\n          * files ts fs\n          * array waitL wait * [| allInOrZero ts waitL |]\n          * [| length waitL = wordToNat waitLen |]\n          * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n          * tqs ts fs * M.globalInv fs * mallocHeap 0 ];;\n\n      \"tmp\" <- \"ss\";;\n      \"ss\" <- \"tq\";;\n      \"tq\" <- \"tmp\";;\n      Goto \"threadqs\"!\"exit\"\n    end with bfunction \"yield\"(\"root\", \"ready\", \"q\") [yieldS]\n      \"root\" <-* globalSched;;\n      \"ready\" <-* \"root\";;\n\n      \"q\" <-- Call \"scheduler\"!\"pickNext\"()\n      [Al ts, Al fs, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n        PRE[V, R] globalSched =*> V \"root\" * (V \"root\" ==*> V \"ready\", free, wait, waitLen)\n          * [| V \"ready\" %in ts |] * [| R %in ts |]\n          * sll freeL free * [| allIn fs freeL |]\n          * files ts fs\n          * array waitL wait * [| allInOrZero ts waitL |]\n          * [| length waitL = wordToNat waitLen |]\n          * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n          * tqs ts fs * M.globalInv fs * mallocHeap 0\n        POST[_] Ex ts', Ex fs', Ex p, Ex ready, Ex free, Ex wait, Ex waitLen, Ex freeL, Ex waitL,\n          [| ts %<= ts' |] * [| fs %<= fs' |]\n          * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n          * [| ready %in ts' |]\n          * sll freeL free * [| allIn fs' freeL |]\n          * files ts' fs'\n          * array waitL wait * [| allInOrZero ts' waitL |]\n          * [| length waitL = wordToNat waitLen |]\n          * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n          * tqs ts' fs' * M.globalInv fs' * mallocHeap 0 ];;\n\n      Call \"threadqs\"!\"yield\"(\"ready\", \"q\")\n      [PRE[_] Emp\n       POST[_] Emp];;\n      Return 0\n    end with bfunction \"listen\"(\"port\", \"fd\", \"fr\") [listenS]\n      \"fd\" <-- Call \"sys\"!\"listen\"(\"port\")\n      [Al fs,\n        PRE[_] sched fs * mallocHeap 0\n        POST[R] Ex fs', [| fs %<= fs' |] * sched fs' * mallocHeap 0 * [| R %in fs' |] ];;\n\n      \"fr\" <-- Call \"scheduler\"!\"new\"(\"fd\")\n      [PRE[_, R] Emp\n       POST[R'] [| R' = R |] ];;\n      Return \"fr\"\n    end with bfunction \"close\"(\"fr\", \"root\", \"free\", \"fd\", \"node\") [closeS]\n      \"root\" <-* globalSched;;\n      \"free\" <-* \"root\"+4;;\n\n      Note [reveal_files_pick];;\n\n      Assert [Al ts, Al fs, Al ready, Al wait, Al waitLen, Al freeL,\n        PRE[V] globalSched =*> V \"root\" * (V \"root\" ==*> ready, V \"free\", wait, waitLen)\n          * sll freeL (V \"free\") * [| allIn fs freeL |]\n          * files_pick (V \"fr\") ts fs * mallocHeap 0\n          * [| V \"fr\" %in fs |]\n        POST[_] Ex free', Ex freeL',\n          globalSched =*> V \"root\" * (V \"root\" ==*> ready, free', wait, waitLen)\n          * sll freeL' free' * [| allIn fs freeL' |]\n          * files_pick (V \"fr\") ts fs * mallocHeap 0];;\n\n      \"fd\" <-* \"fr\";;\n      Call \"sys\"!\"close\"(\"fd\")\n      [Al fs, Al ready, Al wait, Al waitLen, Al freeL, Al fd, Al inq, Al outq,\n        PRE[V] globalSched =*> V \"root\" * (V \"root\" ==*> ready, V \"free\", wait, waitLen)\n          * sll freeL (V \"free\") * [| allIn fs freeL |]\n          * (V \"fr\" ==*> fd, inq, outq) * mallocHeap 0\n          * [| V \"fr\" %in fs |]\n        POST[_] Ex free', Ex freeL',\n          globalSched =*> V \"root\" * (V \"root\" ==*> ready, free', wait, waitLen)\n          * sll freeL' free' * [| allIn fs freeL' |]\n          * (V \"fr\" ==*> fd, inq, outq) * mallocHeap 0];;\n\n      \"node\" <-- Call \"malloc\"!\"malloc\"(0, 2)\n      [Al fs, Al ready, Al wait, Al waitLen, Al freeL,\n        PRE[V, R] R =?> 2 * [| R <> 0 |] * [| freeable R 2 |]\n          * globalSched =*> V \"root\" * (V \"root\" ==*> ready, V \"free\", wait, waitLen)\n          * sll freeL (V \"free\") * [| allIn fs freeL |]\n          * [| V \"fr\" %in fs |]\n        POST[_] Ex free', Ex freeL',\n          globalSched =*> V \"root\" * (V \"root\" ==*> ready, free', wait, waitLen)\n          * sll freeL' free' * [| allIn fs freeL' |] ];;\n\n      \"node\" *<- \"fr\";;\n      \"node\"+4 *<- \"free\";;\n      \"root\"+4 *<- \"node\";;\n      Return 0\n    end with bfunction \"read\"(\"fr\", \"buffer\", \"size\", \"fd\", \"tq\") [readS]\n      Note [reveal_files_pick];;\n\n      Assert [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n        PRE[V] [| V \"fr\" %in fs |] * V \"buffer\" =?>8 wordToNat (V \"size\")\n          * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n          * [| ready %in ts |]\n          * sll freeL free * [| allIn fs freeL |]\n          * files_pick (V \"fr\") ts fs * tqs ts fs\n          * array waitL wait * [| allInOrZero ts waitL |]\n            * [| length waitL = wordToNat waitLen |]\n            * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n          * M.globalInv fs * mallocHeap 0\n        POST[_] Ex p', Ex ts', Ex fs', Ex ready', Ex free', Ex wait', Ex waitLen', Ex freeL', Ex waitL',\n          [| ts %<= ts' |] * [| fs %<= fs' |] * V \"buffer\" =?>8 wordToNat (V \"size\")\n          * [| V \"fr\" %in fs' |]\n          * globalSched =*> p' * (p' ==*> ready', free', wait', waitLen')\n          * [| ready' %in ts' |]\n          * sll freeL' free' * [| allIn fs' freeL' |]\n          * files ts' fs' * tqs ts' fs'\n          * array waitL' wait' * [| allInOrZero ts' waitL' |]\n            * [| length waitL' = wordToNat waitLen' |]\n            * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n          * M.globalInv fs' * mallocHeap 0];;\n\n      \"fd\" <-* \"fr\";;\n      \"tq\" <-* \"fr\"+4;;\n\n      Assert [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n        PRE[V] [| V \"tq\" %in ts |] * [| V \"fr\" %in fs |] * V \"buffer\" =?>8 wordToNat (V \"size\")\n          * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n          * [| ready %in ts |]\n          * sll freeL free * [| allIn fs freeL |]\n          * files_pick (V \"fr\") ts fs * tqs ts fs\n          * array waitL wait * [| allInOrZero ts waitL |]\n            * [| length waitL = wordToNat waitLen |]\n            * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n          * M.globalInv fs * mallocHeap 0\n        POST[_] Ex p', Ex ts', Ex fs', Ex ready', Ex free', Ex wait', Ex waitLen', Ex freeL', Ex waitL',\n          [| ts %<= ts' |] * [| fs %<= fs' |] * V \"buffer\" =?>8 wordToNat (V \"size\")\n          * [| V \"fr\" %in fs' |]\n          * globalSched =*> p' * (p' ==*> ready', free', wait', waitLen')\n          * [| ready' %in ts' |]\n          * sll freeL' free' * [| allIn fs' freeL' |]\n          * files ts' fs' * tqs ts' fs'\n          * array waitL' wait' * [| allInOrZero ts' waitL' |]\n            * [| length waitL' = wordToNat waitLen' |]\n            * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n          * M.globalInv fs' * mallocHeap 0];;\n\n      Note [reveal_files_pick];;\n\n      Call \"scheduler\"!\"block\"(\"tq\", \"fd\", 0)\n      [PRE[V] V \"buffer\" =?>8 wordToNat (V \"size\")\n       POST[_] V \"buffer\" =?>8 wordToNat (V \"size\")];;\n\n      \"size\" <-- Call \"sys\"!\"read\"(\"fd\", \"buffer\", \"size\")\n      [PRE[_] Emp\n       POST[_] Emp ];;\n      Return \"size\"\n    end with bfunction \"write\"(\"fr\", \"buffer\", \"size\", \"fd\", \"tq\") [writeS]\n      Note [reveal_files_pick];;\n\n      Assert [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n        PRE[V] [| V \"fr\" %in fs |] * V \"buffer\" =?>8 wordToNat (V \"size\")\n          * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n          * [| ready %in ts |]\n          * sll freeL free * [| allIn fs freeL |]\n          * files_pick (V \"fr\") ts fs * tqs ts fs\n          * array waitL wait * [| allInOrZero ts waitL |]\n            * [| length waitL = wordToNat waitLen |]\n            * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n          * M.globalInv fs * mallocHeap 0\n        POST[_] Ex p', Ex ts', Ex fs', Ex ready', Ex free', Ex wait', Ex waitLen', Ex freeL', Ex waitL',\n          [| ts %<= ts' |] * [| fs %<= fs' |] * V \"buffer\" =?>8 wordToNat (V \"size\")\n          * [| V \"fr\" %in fs' |]\n          * globalSched =*> p' * (p' ==*> ready', free', wait', waitLen')\n          * [| ready' %in ts' |]\n          * sll freeL' free' * [| allIn fs' freeL' |]\n          * files ts' fs' * tqs ts' fs'\n          * array waitL' wait' * [| allInOrZero ts' waitL' |]\n            * [| length waitL' = wordToNat waitLen' |]\n            * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n          * M.globalInv fs' * mallocHeap 0];;\n\n      \"fd\" <-* \"fr\";;\n      \"tq\" <-* \"fr\"+8;;\n\n      Assert [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n        PRE[V] [| V \"tq\" %in ts |] * [| V \"fr\" %in fs |] * V \"buffer\" =?>8 wordToNat (V \"size\")\n          * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n          * [| ready %in ts |]\n          * sll freeL free * [| allIn fs freeL |]\n          * files_pick (V \"fr\") ts fs * tqs ts fs\n          * array waitL wait * [| allInOrZero ts waitL |]\n            * [| length waitL = wordToNat waitLen |]\n            * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n          * M.globalInv fs * mallocHeap 0\n        POST[_] Ex p', Ex ts', Ex fs', Ex ready', Ex free', Ex wait', Ex waitLen', Ex freeL', Ex waitL',\n          [| ts %<= ts' |] * [| fs %<= fs' |] * V \"buffer\" =?>8 wordToNat (V \"size\")\n          * [| V \"fr\" %in fs' |]\n          * globalSched =*> p' * (p' ==*> ready', free', wait', waitLen')\n          * [| ready' %in ts' |]\n          * sll freeL' free' * [| allIn fs' freeL' |]\n          * files ts' fs' * tqs ts' fs'\n          * array waitL' wait' * [| allInOrZero ts' waitL' |]\n            * [| length waitL' = wordToNat waitLen' |]\n            * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n          * M.globalInv fs' * mallocHeap 0];;\n\n      Note [reveal_files_pick];;\n\n      Call \"scheduler\"!\"block\"(\"tq\", \"fd\", 1)\n      [PRE[V] V \"buffer\" =?>8 wordToNat (V \"size\")\n       POST[_] V \"buffer\" =?>8 wordToNat (V \"size\")];;\n\n      \"size\" <-- Call \"sys\"!\"write\"(\"fd\", \"buffer\", \"size\")\n      [PRE[_] Emp\n       POST[_] Emp ];;\n      Return \"size\"\n    end with bfunction \"accept\"(\"fr\", \"fd\", \"tq\") [acceptS]\n      Note [reveal_files_pick];;\n\n      Assert [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n        PRE[V] [| V \"fr\" %in fs |]\n          * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n          * [| ready %in ts |]\n          * sll freeL free * [| allIn fs freeL |]\n          * files_pick (V \"fr\") ts fs * tqs ts fs\n          * array waitL wait * [| allInOrZero ts waitL |]\n            * [| length waitL = wordToNat waitLen |]\n            * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n          * M.globalInv fs * mallocHeap 0\n        POST[R] Ex p', Ex ts', Ex fs', Ex fs'', Ex ready', Ex free', Ex wait', Ex waitLen', Ex freeL', Ex waitL',\n          [| ts %<= ts' |] * [| fs %<= fs' |] * [| fs' %<= fs'' |]\n          * [| V \"fr\" %in fs'' |] * [| R %in fs'' |]\n          * globalSched =*> p' * (p' ==*> ready', free', wait', waitLen')\n          * [| ready' %in ts' |]\n          * sll freeL' free' * [| allIn fs'' freeL' |]\n          * files ts' fs'' * tqs ts' fs''\n          * array waitL' wait' * [| allInOrZero ts' waitL' |]\n            * [| length waitL' = wordToNat waitLen' |]\n            * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n          * M.globalInv fs' * mallocHeap 0];;\n\n      \"fd\" <-* \"fr\";;\n      \"tq\" <-* \"fr\"+4;;\n\n      Assert [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n        PRE[V] [| V \"tq\" %in ts |] * [| V \"fr\" %in fs |]\n          * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n          * [| ready %in ts |]\n          * sll freeL free * [| allIn fs freeL |]\n          * files_pick (V \"fr\") ts fs * tqs ts fs\n          * array waitL wait * [| allInOrZero ts waitL |]\n            * [| length waitL = wordToNat waitLen |]\n            * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n          * M.globalInv fs * mallocHeap 0\n        POST[R] Ex p', Ex ts', Ex fs', Ex fs'', Ex ready', Ex free', Ex wait', Ex waitLen', Ex freeL', Ex waitL',\n          [| ts %<= ts' |] * [| fs %<= fs' |] * [| fs' %<= fs'' |]\n          * [| V \"fr\" %in fs'' |] * [| R %in fs'' |]\n          * globalSched =*> p' * (p' ==*> ready', free', wait', waitLen')\n          * [| ready' %in ts' |]\n          * sll freeL' free' * [| allIn fs'' freeL' |]\n          * files ts' fs'' * tqs ts' fs''\n          * array waitL' wait' * [| allInOrZero ts' waitL' |]\n            * [| length waitL' = wordToNat waitLen' |]\n            * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n          * M.globalInv fs' * mallocHeap 0];;\n\n      Note [reveal_files_pick];;\n\n      Call \"scheduler\"!\"block\"(\"tq\", \"fd\", 0)\n      [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n        PRE[V] [| V \"tq\" %in ts |] * [| V \"fr\" %in fs |]\n          * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n          * [| ready %in ts |]\n          * sll freeL free * [| allIn fs freeL |]\n          * files ts fs * tqs ts fs\n          * array waitL wait * [| allInOrZero ts waitL |]\n            * [| length waitL = wordToNat waitLen |]\n            * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n          * M.globalInv fs * mallocHeap 0\n        POST[R] Ex p', Ex ts', Ex fs', Ex fs'', Ex ready', Ex free', Ex wait', Ex waitLen', Ex freeL', Ex waitL',\n          [| ts %<= ts' |] * [| fs %<= fs' |] * [| fs' %<= fs'' |]\n          * [| V \"fr\" %in fs'' |] * [| R %in fs'' |]\n          * globalSched =*> p' * (p' ==*> ready', free', wait', waitLen')\n          * [| ready' %in ts' |]\n          * sll freeL' free' * [| allIn fs'' freeL' |]\n          * files ts' fs'' * tqs ts' fs''\n          * array waitL' wait' * [| allInOrZero ts' waitL' |]\n            * [| length waitL' = wordToNat waitLen' |]\n            * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n          * M.globalInv fs' * mallocHeap 0];;\n\n      \"fd\" <-- Call \"sys\"!\"accept\"(\"fd\")\n      [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n        PRE[V] [| V \"tq\" %in ts |] * [| V \"fr\" %in fs |]\n          * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n          * [| ready %in ts |]\n          * sll freeL free * [| allIn fs freeL |]\n          * files ts fs * tqs ts fs\n          * array waitL wait * [| allInOrZero ts waitL |]\n            * [| length waitL = wordToNat waitLen |]\n            * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n          * M.globalInv fs * mallocHeap 0\n        POST[R] Ex p', Ex ts', Ex fs', Ex fs'', Ex ready', Ex free', Ex wait', Ex waitLen', Ex freeL', Ex waitL',\n          [| ts %<= ts' |] * [| fs %<= fs' |] * [| fs' %<= fs'' |]\n          * [| V \"fr\" %in fs'' |] * [| R %in fs'' |]\n          * globalSched =*> p' * (p' ==*> ready', free', wait', waitLen')\n          * [| ready' %in ts' |]\n          * sll freeL' free' * [| allIn fs'' freeL' |]\n          * files ts' fs'' * tqs ts' fs''\n          * array waitL' wait' * [| allInOrZero ts' waitL' |]\n            * [| length waitL' = wordToNat waitLen' |]\n            * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n          * M.globalInv fs' * mallocHeap 0];;\n\n      \"fr\" <-- Call \"scheduler\"!\"new\"(\"fd\")\n      [PRE[_, R] Emp\n       POST[R'] [| R' = R |] ];;\n      Return \"fr\"\n    end with bfunction \"pickNext\"(\"root\", \"ready\", \"wait\", \"waitLen\", \"blocking\", \"n\") [pickNextS]\n      \"root\" <-* globalSched;;\n      \"ready\" <-* \"root\";;\n\n      \"blocking\" <-- Call \"threadqs\"!\"isEmpty\"(\"ready\")\n      [Al free, Al wait, Al waitLen, Al ts, Al fs, Al waitL,\n        PRE[V] globalSched =*> V \"root\" * (V \"root\" ==*> V \"ready\", free, wait, waitLen)\n          * tqs ts fs * [| V \"ready\" %in ts |]\n          * array waitL wait * [| allInOrZero ts waitL |]\n          * [| length waitL = wordToNat waitLen |]\n        POST[R] [| R %in ts |]\n          * tqs ts fs * globalSched =*> V \"root\" * (V \"root\" ==*> V \"ready\", free, wait, waitLen)\n          * array waitL wait ];;\n\n      \"n\" <-- Call \"sys\"!\"wait\"(\"blocking\")\n      [Al free, Al wait, Al waitLen, Al ts, Al waitL,\n        PRE[V] globalSched =*> V \"root\" * (V \"root\" ==*> V \"ready\", free, wait, waitLen)\n          * [| V \"ready\" %in ts |]\n          * array waitL wait * [| allInOrZero ts waitL |]\n          * [| length waitL = wordToNat waitLen |]\n        POST[R] [| R %in ts |]\n          * globalSched =*> V \"root\" * (V \"root\" ==*> V \"ready\", free, wait, waitLen)\n          * array waitL wait ];;\n\n      \"wait\" <-* \"root\"+8;;\n      \"waitLen\" <-* \"root\"+12;;\n\n      If (\"n\" < \"waitLen\") {\n        Assert [Al free, Al ts, Al waitL,\n          PRE[V] globalSched =*> V \"root\" * (V \"root\" ==*> V \"ready\", free, V \"wait\", V \"waitLen\")\n          * [| V \"ready\" %in ts |] * [| allInOrZero ts waitL |]\n          * array waitL (V \"wait\") * [| (V \"n\" < natToW (length waitL))%word |]\n        POST[R] [| R %in ts |]\n          * globalSched =*> V \"root\" * (V \"root\" ==*> V \"ready\", free, V \"wait\", V \"waitLen\")\n          * array waitL (V \"wait\") ];;\n\n        \"n\" <- 4 * \"n\";;\n        \"wait\" <-* \"wait\" + \"n\";;\n\n        If (\"wait\" = 0) {\n          Call \"sys\"!\"abort\"()\n          [PREonly[_] [| False |] ]\n        } else {\n          Return \"wait\"\n        }\n      } else {\n        Return \"ready\"\n      }\n    end with bfunction \"new\"(\"fd\", \"root\", \"free\", \"oldFree\", \"fr\", \"inq\", \"outq\") [newS]\n      \"root\" <-* globalSched;;\n      \"free\" <-* \"root\"+4;;\n\n      If (\"free\" <> 0) {\n        \"oldFree\" <- \"free\";;\n        \"fr\" <-* \"free\";;\n        \"free\" <-* \"free\"+4;;\n        \"root\"+4 *<- \"free\";;\n\n        Note [reveal_files_pick];;\n\n        Call \"malloc\"!\"free\"(0, \"oldFree\", 2)\n        [Al ts, Al fs,\n          PRE[V] [| V \"fr\" %in fs |] * files_pick (V \"fr\") ts fs\n          POST[R] [| R = V \"fr\" |] * files_pick (V \"fr\") ts fs];;\n\n        \"fr\" *<- \"fd\";;\n        Return \"fr\"\n      } else {\n        \"inq\" <-- Call \"threadqs\"!\"alloc\"()\n        [Al ts, Al fs,\n          PRE[V, R] files ts fs * tqs (ts %+ R) fs * mallocHeap 0\n          POST[R'] Ex ts', Ex fs', [| R' %in fs' |] * [| ts %+ R %<= ts' |] * [| fs %<= fs' |]\n            * files ts' fs' * tqs ts' fs' * mallocHeap 0];;\n\n        \"outq\" <-- Call \"threadqs\"!\"alloc\"()\n        [Al ts, Al fs,\n          PRE[V, R] files ts fs * tqs (ts %+ V \"inq\" %+ R) fs * mallocHeap 0\n          POST[R'] Ex ts', Ex fs', [| R' %in fs' |] * [| ts %+ V \"inq\" %+ R %<= ts' |] * [| fs %<= fs' |]\n            * files ts' fs' * tqs ts' fs' * mallocHeap 0];;\n\n        \"fr\" <-- Call \"malloc\"!\"malloc\"(0, 3)\n        [Al ts, Al fs,\n          PRE[V, R] R =?> 3 * files ts fs * tqs (ts %+ V \"inq\" %+ V \"outq\") fs\n          POST[R'] Ex fs', [| fs %<= fs' |] * [| R' %in fs' |] * files (ts %+ V \"inq\" %+ V \"outq\") fs'\n            * tqs (ts %+ V \"inq\" %+ V \"outq\") fs' ];;\n\n        Note [add_a_file];;\n\n        Assert [Al ts, Al fs,\n          PRE[V] V \"fr\" =?> 3 * files ts fs\n          POST[R] [| R = V \"fr\" |] * files (ts %+ V \"inq\" %+ V \"outq\") (fs %+ V \"fr\") ];;\n\n        \"fr\" *<- \"fd\";;\n        \"fr\"+4 *<- \"inq\";;\n        \"fr\"+8 *<- \"outq\";;\n        Return \"fr\"\n      }\n    end with bfunction \"declare\"(\"tq\", \"fd\", \"mode\", \"root\", \"wait\", \"waitLen\", \"n\", \"newWait\", \"newLen\", \"i\", \"j\", \"v\") [declareS]\n      \"root\" <-* globalSched;;\n      \"wait\" <-* \"root\"+8;;\n      \"waitLen\" <-* \"root\"+12;;\n\n      \"n\" <-- Call \"sys\"!\"declare\"(\"fd\", \"mode\")\n      [Al ts, Al ready, Al free, Al waitL,\n        PRE[V] [| V \"tq\" %in ts |] * (V \"root\" ==*> ready, free, V \"wait\", V \"waitLen\")\n          * array waitL (V \"wait\") * [| allInOrZero ts waitL |]\n          * [| length waitL = wordToNat (V \"waitLen\") |]\n          * [| V \"wait\" <> 0 |] * [| freeable (V \"wait\") (length waitL) |]\n          * mallocHeap 0\n        POST[_] Ex wait', Ex waitLen', Ex waitL',\n          (V \"root\" ==*> ready, free, wait', waitLen')\n          * array waitL' wait' * [| allInOrZero ts waitL' |]\n          * [| length waitL' = wordToNat waitLen' |]\n          * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n          * mallocHeap 0];;\n\n      If (\"n\" < \"waitLen\") {\n        Assert [Al ts, Al ready, Al free, Al waitL,\n          PRE[V] [| V \"tq\" %in ts |] * (V \"root\" ==*> ready, free, V \"wait\", V \"waitLen\")\n            * array waitL (V \"wait\") * [| allInOrZero ts waitL |]\n            * [| length waitL = wordToNat (V \"waitLen\") |]\n            * [| V \"wait\" <> 0 |] * [| freeable (V \"wait\") (length waitL) |]\n            * [| (V \"n\" < natToW (length waitL))%word |]\n            * mallocHeap 0\n          POST[_] Ex wait', Ex waitLen', Ex waitL',\n            (V \"root\" ==*> ready, free, wait', waitLen')\n            * array waitL' wait' * [| allInOrZero ts waitL' |]\n            * [| length waitL' = wordToNat waitLen' |]\n            * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n            * mallocHeap 0];;\n\n        \"n\" <- 4 * \"n\";;\n        \"wait\"+\"n\" *<- \"tq\";;\n        Return 0\n      } else {\n        \"newLen\" <- \"n\" + 1;;\n\n        If (\"newLen\" < 2) {\n          (* This case should be impossible, following the intended API usage. *)\n          Call \"sys\"!\"abort\"()\n          [PREonly[_] [| False |] ]\n        } else {\n          \"newWait\" <-- Call \"malloc\"!\"malloc\"(0, \"newLen\")\n          [Al ts, Al ready, Al free, Al waitL,\n            PRE[V, R] [| V \"tq\" %in ts |] * (V \"root\" ==*> ready, free, V \"wait\", V \"waitLen\")\n              * array waitL (V \"wait\") * [| allInOrZero ts waitL |]\n              * [| length waitL = wordToNat (V \"waitLen\") |]\n              * [| V \"wait\" <> 0 |] * [| freeable (V \"wait\") (length waitL) |]\n              * R =?> wordToNat (V \"newLen\") * [| R <> 0 |] * [| freeable R (wordToNat (V \"newLen\")) |]\n              * mallocHeap 0\n            POST[_] Ex wait', Ex waitLen', Ex waitL',\n              (V \"root\" ==*> ready, free, wait', waitLen')\n              * array waitL' wait' * [| allInOrZero ts waitL' |]\n              * [| length waitL' = wordToNat waitLen' |]\n              * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n              * mallocHeap 0];;\n\n          Note [make_array];;\n\n          Assert [Al ts, Al ready, Al free, Al waitL, Al newL,\n            PRE[V] [| V \"tq\" %in ts |] * (V \"root\" ==*> ready, free, V \"wait\", V \"waitLen\")\n              * array waitL (V \"wait\") * [| allInOrZero ts waitL |]\n              * [| length waitL = wordToNat (V \"waitLen\") |]\n              * [| V \"wait\" <> 0 |] * [| freeable (V \"wait\") (length waitL) |]\n              * array newL (V \"newWait\") * [| length newL = wordToNat (V \"newLen\") |]\n              * [| V \"newWait\" <> 0 |] * [| freeable (V \"newWait\") (wordToNat (V \"newLen\")) |]\n              * mallocHeap 0\n            POST[_] Ex wait', Ex waitLen', Ex waitL',\n              (V \"root\" ==*> ready, free, wait', waitLen')\n              * array waitL' wait' * [| allInOrZero ts waitL' |]\n              * [| length waitL' = wordToNat waitLen' |]\n              * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n              * mallocHeap 0];;\n\n          \"i\" <- 0;;\n          [Al ts, Al ready, Al free, Al waitL, Al waitL',\n            PRE[V] [| V \"tq\" %in ts |] * (V \"root\" ==*> ready, free, V \"wait\", V \"waitLen\")\n              * array waitL (V \"wait\") * [| allInOrZero ts waitL |]\n              * [| length waitL = wordToNat (V \"waitLen\") |]\n              * [| V \"wait\" <> 0 |] * [| freeable (V \"wait\") (length waitL) |]\n              * array waitL' (V \"newWait\") * [| length waitL' = wordToNat (V \"newLen\") |]\n              * [| V \"newWait\" <> 0 |] * [| freeable (V \"newWait\") (wordToNat (V \"newLen\")) |]\n              * [| allInOrZero ts (firstn (wordToNat (V \"i\")) waitL') |]\n              * mallocHeap 0 * [| (V \"i\" <= V \"newLen\")%word |]\n            POST[_] Ex wait', Ex waitLen', Ex waitL',\n              (V \"root\" ==*> ready, free, wait', waitLen')\n              * array waitL' wait' * [| allInOrZero ts waitL' |]\n              * [| length waitL' = wordToNat waitLen' |]\n              * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n              * mallocHeap 0]\n          While (\"i\" < \"newLen\") {\n            If (\"i\" = \"n\") {\n              \"v\" <- \"tq\"\n            } else {\n              If (\"i\" < \"waitLen\") {\n                Assert [Al ts, Al ready, Al free, Al waitL, Al waitL',\n                  PRE[V] [| V \"tq\" %in ts |] * (V \"root\" ==*> ready, free, V \"wait\", V \"waitLen\")\n                    * array waitL (V \"wait\") * [| allInOrZero ts waitL |]\n                    * [| length waitL = wordToNat (V \"waitLen\") |]\n                    * [| V \"wait\" <> 0 |] * [| freeable (V \"wait\") (length waitL) |]\n                    * array waitL' (V \"newWait\") * [| length waitL' = wordToNat (V \"newLen\") |]\n                    * [| V \"newWait\" <> 0 |] * [| freeable (V \"newWait\") (wordToNat (V \"newLen\")) |]\n                    * [| allInOrZero ts (firstn (wordToNat (V \"i\")) waitL') |]\n                    * [| (V \"i\" < natToW (length waitL'))%word |]\n                    * [| (V \"i\" < natToW (length waitL))%word |]\n                    * mallocHeap 0\n                  POST[_] Ex wait', Ex waitLen', Ex waitL',\n                    (V \"root\" ==*> ready, free, wait', waitLen')\n                    * array waitL' wait' * [| allInOrZero ts waitL' |]\n                    * [| length waitL' = wordToNat waitLen' |]\n                    * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n                    * mallocHeap 0];;\n                \"j\" <- 4 * \"i\";;\n                \"v\" <-* \"wait\" + \"j\"\n              } else {\n                \"v\" <- 0\n              }\n            };;\n\n            Assert [Al ts, Al ready, Al free, Al waitL, Al waitL',\n              PRE[V] [| V \"tq\" %in ts |] * (V \"root\" ==*> ready, free, V \"wait\", V \"waitLen\")\n                * array waitL (V \"wait\") * [| allInOrZero ts waitL |]\n                * [| length waitL = wordToNat (V \"waitLen\") |]\n                * [| V \"wait\" <> 0 |] * [| freeable (V \"wait\") (length waitL) |]\n                * array waitL' (V \"newWait\") * [| length waitL' = wordToNat (V \"newLen\") |]\n                * [| V \"newWait\" <> 0 |] * [| freeable (V \"newWait\") (wordToNat (V \"newLen\")) |]\n                * [| allInOrZero ts (firstn (wordToNat (V \"i\")) waitL') |]\n                * [| (V \"i\" < natToW (length waitL'))%word |]\n                * [| V \"v\" = $0 \\/ V \"v\" %in ts |]\n                * mallocHeap 0\n              POST[_] Ex wait', Ex waitLen', Ex waitL',\n                (V \"root\" ==*> ready, free, wait', waitLen')\n                * array waitL' wait' * [| allInOrZero ts waitL' |]\n                * [| length waitL' = wordToNat waitLen' |]\n                * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n                * mallocHeap 0];;\n\n            \"j\" <- 4 * \"i\";;\n            \"newWait\" + \"j\" *<- \"v\";;\n            \"i\" <- \"i\" + 1\n          };;\n\n          Note [dissolve_array];;\n\n          Assert [Al ts, Al ready, Al free, Al newL,\n            PRE[V] [| V \"tq\" %in ts |] * (V \"root\" ==*> ready, free, V \"wait\", V \"waitLen\")\n              * V \"wait\" =?> wordToNat (V \"waitLen\")\n              * [| V \"wait\" <> 0 |] * [| freeable (V \"wait\") (wordToNat (V \"waitLen\")) |]\n              * array newL (V \"newWait\") * [| length newL = wordToNat (V \"newLen\") |]\n              * [| V \"newWait\" <> 0 |] * [| freeable (V \"newWait\") (wordToNat (V \"newLen\")) |]\n              * [| allInOrZero ts newL |]\n              * mallocHeap 0\n            POST[_] Ex wait', Ex waitLen', Ex waitL',\n              (V \"root\" ==*> ready, free, wait', waitLen')\n              * array waitL' wait' * [| allInOrZero ts waitL' |]\n              * [| length waitL' = wordToNat waitLen' |]\n              * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n              * mallocHeap 0];;\n\n          Call \"malloc\"!\"free\"(0, \"wait\", \"waitLen\")\n          [Al ready, Al free,\n            PRE[V] mallocHeap 0 * (V \"root\" ==*> ready, free, V \"wait\", V \"waitLen\")\n            POST[_] mallocHeap 0 * (V \"root\" ==*> ready, free, V \"newWait\", V \"newLen\")];;\n\n          \"root\"+8 *<- \"newWait\";;\n          \"root\"+12 *<- \"newLen\";;\n          Return 0\n        }\n      }\n    end with bfunction \"block\"(\"tq\", \"fd\", \"mode\", \"tmp\") [blockS]\n       \"tmp\" <-- Call \"threadqs\"!\"isEmpty\"(\"tq\")\n       [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n         PRE[V] [| V \"tq\" %in ts |]\n           * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n           * [| ready %in ts |]\n           * sll freeL free * [| allIn fs freeL |]\n           * files ts fs * tqs ts fs\n           * array waitL wait * [| allInOrZero ts waitL |]\n             * [| length waitL = wordToNat waitLen |]\n             * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n           * M.globalInv fs * mallocHeap 0\n         POST[_] Ex p', Ex ts', Ex fs', Ex ready', Ex free', Ex wait', Ex waitLen', Ex freeL', Ex waitL',\n           [| ts %<= ts' |] * [| fs %<= fs' |]\n           * globalSched =*> p' * (p' ==*> ready', free', wait', waitLen')\n           * [| ready' %in ts' |]\n           * sll freeL' free' * [| allIn fs' freeL' |]\n           * files ts' fs' * tqs ts' fs'\n           * array waitL' wait' * [| allInOrZero ts' waitL' |]\n             * [| length waitL' = wordToNat waitLen' |]\n             * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n           * M.globalInv fs' * mallocHeap 0];;\n\n       If (\"tmp\" = 1) {\n         Call \"scheduler\"!\"declare\"(\"tq\", \"fd\", \"mode\")\n         [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n         PRE[V] [| V \"tq\" %in ts |]\n           * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n           * [| ready %in ts |]\n           * sll freeL free * [| allIn fs freeL |]\n           * files ts fs * tqs ts fs\n           * array waitL wait * [| allInOrZero ts waitL |]\n             * [| length waitL = wordToNat waitLen |]\n             * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n           * M.globalInv fs * mallocHeap 0\n         POST[_] Ex p', Ex ts', Ex fs', Ex ready', Ex free', Ex wait', Ex waitLen', Ex freeL', Ex waitL',\n           [| ts %<= ts' |] * [| fs %<= fs' |]\n           * globalSched =*> p' * (p' ==*> ready', free', wait', waitLen')\n           * [| ready' %in ts' |]\n           * sll freeL' free' * [| allIn fs' freeL' |]\n           * files ts' fs' * tqs ts' fs'\n           * array waitL' wait' * [| allInOrZero ts' waitL' |]\n             * [| length waitL' = wordToNat waitLen' |]\n             * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n           * M.globalInv fs' * mallocHeap 0]\n       } else {\n         Skip\n       };;\n\n       \"tmp\" <-- Call \"scheduler\"!\"pickNext\"()\n       [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al freeL, Al waitL,\n         PRE[V, R] [| V \"tq\" %in ts |] * [| R %in ts |]\n           * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n           * [| ready %in ts |]\n           * sll freeL free * [| allIn fs freeL |]\n           * files ts fs * tqs ts fs\n           * array waitL wait * [| allInOrZero ts waitL |]\n             * [| length waitL = wordToNat waitLen |]\n             * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n           * M.globalInv fs * mallocHeap 0\n         POST[_] Ex p', Ex ts', Ex fs', Ex ready', Ex free', Ex wait', Ex waitLen', Ex freeL', Ex waitL',\n           [| ts %<= ts' |] * [| fs %<= fs' |]\n           * globalSched =*> p' * (p' ==*> ready', free', wait', waitLen')\n           * [| ready' %in ts' |]\n           * sll freeL' free' * [| allIn fs' freeL' |]\n           * files ts' fs' * tqs ts' fs'\n           * array waitL' wait' * [| allInOrZero ts' waitL' |]\n             * [| length waitL' = wordToNat waitLen' |]\n             * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n           * M.globalInv fs' * mallocHeap 0];;\n\n       Call \"threadqs\"!\"yield\"(\"tq\", \"tmp\")\n       [Al ts, Al fs, Al p, Al ready, Al free, Al wait, Al waitLen, Al waitL,\n         PRE[V] [| V \"tq\" %in ts |]\n           * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n           * array waitL wait * [| allInOrZero ts waitL |]\n             * [| length waitL = wordToNat waitLen |]\n             * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n           * tqs ts fs * mallocHeap 0\n         POST[_] Ex wait', Ex waitLen', Ex waitL',\n           globalSched =*> p * (p ==*> ready, free, wait', waitLen')\n           * array waitL' wait' * [| allInOrZero ts waitL' |]\n             * [| length waitL' = wordToNat waitLen' |]\n             * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n           * tqs ts fs * mallocHeap 0];;\n\n       \"tmp\" <-- Call \"threadqs\"!\"isEmpty\"(\"tq\")\n       [Al ts, Al p, Al ready, Al free, Al wait, Al waitLen, Al waitL,\n         PRE[V] [| V \"tq\" %in ts |]\n           * globalSched =*> p * (p ==*> ready, free, wait, waitLen)\n           * array waitL wait * [| allInOrZero ts waitL |]\n             * [| length waitL = wordToNat waitLen |]\n             * [| wait <> 0 |] * [| freeable wait (length waitL) |]\n           * mallocHeap 0\n         POST[_] Ex wait', Ex waitLen', Ex waitL',\n           globalSched =*> p * (p ==*> ready, free, wait', waitLen')\n           * array waitL' wait' * [| allInOrZero ts waitL' |]\n             * [| length waitL' = wordToNat waitLen' |]\n             * [| wait' <> 0 |] * [| freeable wait' (length waitL') |]\n           * mallocHeap 0];;\n\n       If (\"tmp\" = 0) {\n         Call \"scheduler\"!\"declare\"(\"tq\", \"fd\", \"mode\")\n         [PRE[_] Emp POST[_] Emp]\n       } else {\n         Skip\n       };;\n\n       Return 0\n    end\n  }}.\n\nLtac finish := auto;\n  try solve [ fold (@length W) in *; try rewrite initSize_eq in *;\n    repeat match goal with\n             | [ H : length _ = _ |- _ ] => rewrite H\n           end; reflexivity || eauto 2;\n  fold (@firstn W) in *; autorewrite with sepFormula; eauto 2 ].\n\nLocal Hint Extern 1 (selN _ _ = _) => apply selN_upd_eq; solve [ finish ].\n\nLtac t' := unfold globalInv; sep hints; finish.\n\nLtac spawn := post; evaluate hints;\n  match goal with\n    | [ H : interp _ _ |- _ ] =>\n      toFront ltac:(fun P => match P with\n                               | starting _ _ => idtac\n                             end) H; apply starting_elim in H; post; descend\n  end;\n  try (toFront_conc ltac:(fun P => match P with\n                                     | Q'.starting _ _ _ _ => idtac\n                                   end); apply other_starting_intro; descend;\n  try match goal with\n        | [ |- interp _ (![ _ ] _) ] => step hints\n      end);\n  (try (repeat (apply andL; apply injL; intro);\n    match goal with\n      | [ H : forall stn_st : ST.settings * state, _ |- _ ] =>\n        eapply Imply_trans; [ | apply H ]; clear H\n    end); t').\n\nLemma tqs_weaken : forall ts fs fs',\n  fs %<= fs'\n  -> tqs ts fs ===>* tqs ts fs'.\n  rewrite tqs_eq; intros; apply tqs'_weaken; hnf; intuition.\nQed.\n\nLtac funky_nomega :=\n  simpl; pre_nomega;\n    match goal with\n      | [ H : (wordToNat (sel _ \"ss\") >= _)%nat |- _ ] =>\n        rewrite wordToNat_natToWord_idempotent in H by reflexivity\n      | [ H : (_ <= wordToNat (sel _ \"ss\"))%nat |- _ ] =>\n        rewrite wordToNat_natToWord_idempotent in H by reflexivity\n    end;\n    try match goal with\n          | [ |- (wordToNat (sel _ \"ss\") >= _)%nat ] => rewrite wordToNat_natToWord_idempotent by reflexivity\n        end; omega.\n\nLtac t := solve [\n  match goal with\n    | [ |- context[localsInvariantExit] ] =>\n      match goal with\n        | [ |- forall stn_st specs, interp specs _ -> interp specs _ ] =>\n          match goal with\n            | [ |- context[evolve] ] =>\n              unfold globalInv; post; evaluate hints;\n                match goal with\n                  | [ H : context[locals ?a ?b ?c ?d] |- _ ] =>\n                    change (locals a b c d) with (exitize_me a b c d) in H\n                end; evaluate hints;\n                match goal with\n                  | [ H : context[?ss - 4 + 1] |- _ ] =>\n                    replace (ss - 4 + 1) with (ss - 3) in H by funky_nomega\n                end;\n                repeat match goal with\n                         | [ |- Logic.ex _ ] => eexists\n                         | [ |- _ /\\ _ ] => split\n                         | [ H : context[locals _ ?vs _ _] |- context[locals _ ?vs' _ _] ] =>\n                           equate vs vs'; descend; step hints\n                       end; unfold natToW in *; descend; finish; funky_nomega\n            | _ =>\n              post; evaluate hints;\n              match goal with\n                | [ H : context[locals ?ns ?vs (?ss - 2) ?p]\n                  |- context[locals ?ns' _ (wordToNat (sel _ \"ss\") - 4) _] ] =>\n                let ns'' := peelPrefix ns ns' in\n                  let avail := constr:(ss - 2) in\n                    let avail' := constr:(ss - 4) in\n                      change (locals ns vs avail p) with (locals_in ns vs avail p ns'' ns' avail') in H;\n                        assert (ok_in ns avail ns'' ns' avail')%nat\n                          by (split; [\n                            reflexivity\n                            | split; [ funky_nomega\n                              | split; [ NoDup\n                                | simpl; omega ] ] ])\n              end; evaluate hints;\n              repeat match goal with\n                       | [ |- Logic.ex _ ] => eexists\n                       | [ |- _ /\\ _ ] => split\n                       | [ H : context[locals _ ?vs _ _] |- context[locals _ ?vs' _ _] ] =>\n                         equate vs vs'; descend; step hints\n                     end; finish\n          end\n        | [ |- forall stn st specs, interp specs _ -> forall rp : W, _ ] =>\n          post; evaluate hints;\n          match goal with\n            | [ H : context[locals ?ns ?vs (?ss - 4) ?p]\n              |- context[locals (\"rp\" :: nil) _ 13 _] ] =>\n            let avail := constr:(ss - 4) in\n              let offset := eval simpl in (4 * List.length ns)%nat in\n                change (locals ns vs avail p) with (locals_call ns vs avail p (\"rp\" :: nil) 13 offset) in H;\n                  assert (ok_call ns (\"rp\" :: nil) avail 13 offset)%nat\n                    by (split; [ funky_nomega\n                      | split; [ funky_nomega\n                        | split; [ NoDup\n                          | reflexivity ] ] ])\n          end; unfold localsInvariantExit in *; sep hints;\n          try match goal with\n                | [ |- himp _ ?pre ?post ] =>\n                  match post with\n                    | context[locals ?ns ?vs ?avail _] =>\n                      match pre with\n                        | context[excessStack _ ns ?availAlt ?ns' ?avail'] =>\n                          match pre with\n                            | context[locals ns ?vs' 0 ?sp] =>\n                              match goal with\n                                | _ => equate vs vs';\n                                  let offset := eval simpl in (4 * List.length ns)%nat in\n                                    rewrite (create_locals_return ns' avail' ns avail offset);\n                                      assert (ok_return ns ns' avail avail' offset)%nat by (split; [\n                                        funky_nomega\n                                        | reflexivity ] ); autorewrite with sepFormula;\n                                      generalize dependent vs'; intros; step hints\n                              end\n                          end\n                      end\n                  end\n              end; finish; funky_nomega\n        | _ => t'\n      end\n\n    | [ |- context[starting] ] =>\n      match goal with\n        | [ |- context[Q'.starting] ] => spawn\n      end\n    | [ |- context[add_a_file] ] =>\n      post; evaluate hints;\n      match goal with\n        | [ H : context[upd _ \"fr\" ?V] |- _ ] =>\n          match type of H with\n            | context[files _ ?B] =>\n              toFront ltac:(fun P => match P with\n                                       | tqs _ _ => idtac\n                                     end) H;\n              eapply use_HimpWeak in H; [ | apply (tqs_weaken _ _ (B %+ V)) ]; [ t | finish ]\n          end\n      end\n    | [ |- context[reveal_files_pick] ] => unfold files_pick; t'\n    | _ => t'\n  end ].\n\nLocal Hint Extern 1 (@eq W _ _) => words.\nLocal Hint Immediate evolve_refl.\n\nHint Rewrite upd_length : sepFormula.\n\nLocal Hint Extern 1 (allInOrZero _ nil) => constructor.\nLocal Hint Extern 1 (allInOrZero _ (_ :: _)) => constructor.\n\nLocal Hint Extern 1 (allIn empty _) => constructor.\n\nLocal Hint Extern 1 (allInOrZero _ (Array.upd _ (natToW 1) (natToW 0))) =>\n  hnf; rewrite upd_updN by auto;\n    repeat match goal with\n             | [ ls : list W |- _ ] =>\n               match goal with\n                 | [ _ : length ?E = _ |- _ ] =>\n                   match E with\n                     | context[ls] => destruct ls; try discriminate\n                   end\n               end\n           end; simpl in *.\n\nLocal Hint Extern 1 (freeable _ _) => congruence.\nLocal Hint Extern 1 (himp _ _ (sll nil (natToW 0))) => solve [ step hints ].\n\nLemma length_ok : forall u v n,\n  u < v\n  -> n = wordToNat v\n  -> u < natToW n.\n  intros; subst; unfold natToW; rewrite natToWord_wordToNat; auto.\nQed.\n\nLocal Hint Immediate length_ok.\n\nLemma selN_In : forall ls n,\n  (n < length ls)%nat\n  -> In (Array.selN ls n) ls.\n  induction ls; destruct n; simpl; intuition.\nQed.\n\nLemma sel_In : forall ls n,\n  n < natToW (length ls)\n  -> goodSize (length ls)\n  -> In (Array.sel ls n) ls.\n  unfold Array.sel; intros; apply selN_In; nomega.\nQed.    \n\nLemma found_queue : forall x ls i b,\n  x = Array.sel ls i\n  -> Array.sel ls i <> 0\n  -> allInOrZero b ls\n  -> i < natToW (length ls)\n  -> goodSize (length ls)\n  -> x %in b.\n  intros; subst.\n  eapply Forall_forall in H1; [ | eauto using sel_In ].\n  tauto.\nQed.\n\nLocal Hint Extern 1 (_ %in _) =>\n  eapply found_queue; [ eassumption | eassumption | eassumption | eassumption | eauto ].\n\nLemma allIn_monotone : forall b ls b',\n  allIn b ls\n  -> b %<= b'\n  -> allIn b' ls.\n  intros; eapply Forall_weaken; eauto.\n  bags.\n  specialize (H0 x); omega.\nQed.\n\nLocal Hint Immediate allIn_monotone.\n\nLemma allIn_hd : forall b x ls,\n  allIn b (x :: ls)\n  -> x %in b.\n  inversion 1; auto.\nQed.\n\nLemma allIn_tl : forall b x ls,\n  allIn b (x :: ls)\n  -> allIn b ls.\n  inversion 1; auto.\nQed.\n\nLocal Hint Immediate allIn_hd allIn_tl.\n\nLemma add_incl : forall a b x,\n  a %+ x %<= b\n  -> a %<= b.\n  bags.\n  specialize (H x0).\n  destruct (W_Key.eq_dec x0 x); auto.\nQed.\n\nLocal Hint Immediate add_incl.\n\nLocal Hint Extern 1 (himp _ (files _ _) (files _ _)) => apply starB_weaken; solve [ sepLemma ].\n\nLemma allInOrZero_monotone : forall b ls b',\n  allInOrZero b ls\n  -> b %<= b'\n  -> allInOrZero b' ls.\n  intros; eapply Forall_weaken; [ | eauto ].\n  bags.\n  specialize (H0 x); omega.\nQed.\n\nLocal Hint Immediate allInOrZero_monotone.\n\nLemma allIn_cons : forall b x ls,\n  allIn b ls\n  -> x %in b\n  -> allIn b (x :: ls).\n  constructor; auto.\nQed.\n\nLocal Hint Immediate allIn_cons.\n\nLemma allInOrZero_updN : forall b v ls,\n  allInOrZero b ls\n  -> forall i, v %in b\n    -> allInOrZero b (Array.updN ls i v).\n  induction 1; destruct i; simpl; intuition;\n    constructor; auto; apply IHForall; auto.\nQed.    \n\nLemma allInOrZero_upd : forall b ls i v,\n  allInOrZero b ls\n  -> v %in b\n  -> allInOrZero b (Array.upd ls i v).\n  intros; apply allInOrZero_updN; auto.\nQed.\n\nLocal Hint Immediate allInOrZero_upd.\n\nHint Rewrite roundTrip_0 : N.\n\nLemma zero_le : forall w : W, natToW 0 <= w.\n  intros; nomega.\nQed.\n\nLocal Hint Immediate zero_le.\n\nLemma firstn_advance' : forall v n ls,\n  (n < length ls)%nat\n  -> firstn (n + 1) (Array.updN ls n v) = firstn n ls ++ v :: nil.\n  induction n; destruct ls; simpl; intuition.\n  rewrite IHn; auto.\nQed.\n\nLemma firstn_advance : forall ls w v,\n  w < natToW (length ls)\n  -> goodSize (length ls)\n  -> firstn (wordToNat w + 1) (Array.upd ls w v) = firstn (wordToNat w) ls ++ v :: nil.\n  unfold Array.upd; intros; apply firstn_advance'; nomega.\nQed.\n\nLemma allInOrZero_advance : forall b w ls (v : W),\n  allInOrZero b (firstn (wordToNat w) ls)\n  -> v = 0 \\/ v %in b\n  -> w < natToW (length ls)\n  -> goodSize (length ls)\n  -> allInOrZero b (firstn (wordToNat (w ^+ natToW 1)) (Array.upd ls w v)).\n  intros.\n  erewrite <- next; eauto.\n  rewrite firstn_advance; auto; apply Forall_app; auto.\nQed.\n\nLocal Hint Extern 1 (allInOrZero _ (firstn (wordToNat (_ ^+ _)) _)) =>\n  solve [ apply allInOrZero_advance; auto; [ eauto 10 ] ].\n\nLocal Hint Immediate inc.\n\nHint Rewrite natToW_wordToNat : sepFormula.\n\nLemma allInOrZero_delivers : forall b ls i,\n  allInOrZero b ls\n  -> i < natToW (length ls)\n  -> goodSize (length ls)\n  -> Array.sel ls i = natToW 0 \\/ Array.sel ls i %in b.\n  intros ? ? ? H ? ?; eapply Forall_forall in H; eauto; apply sel_In; auto.\nQed.\n\nLocal Hint Extern 1 (_ \\/ _) => solve [ apply allInOrZero_delivers; auto; [ eauto 10 ] ].\n\nLemma firstn_length : forall A (ls : list A),\n  firstn (length ls) ls = ls.\n  induction ls; simpl; intuition.\nQed.\n\nLemma allInOrZero_done : forall b (i : W) ls l,\n  allInOrZero b (firstn (wordToNat i) ls)\n  -> l <= i\n  -> i <= l\n  -> length ls = wordToNat l\n  -> allInOrZero b ls.\n  intros; replace i with l in *.\n  rewrite <- H2 in *; rewrite firstn_length in *; assumption.\n  apply wordToNat_inj; nomega.\nQed.\n\nLocal Hint Immediate allInOrZero_done.\n\nLemma nonzero : forall sp sp' sp'' : W,\n  sp ^- $16 = natToW 0\n  -> sp' = sp'' ^+ natToW 16\n  -> sp'' <> 0\n  -> sp = sp'\n  -> False.\n  intros; subst; apply H1; unfold natToW in *; ring_simplify in H; auto.\nQed.\n\nLocal Hint Immediate nonzero.\n\nTheorem ok : moduleOk m.\n  vcgen; abstract t.\nQed.\n\nTransparent initSize.\n\nEnd Make.\n", "meta": {"author": "gmalecha", "repo": "bedrock-mirror-shard", "sha": "ea7e5ad56a1d6392468b6823e0457dd44524bca7", "save_path": "github-repos/coq/gmalecha-bedrock-mirror-shard", "path": "github-repos/coq/gmalecha-bedrock-mirror-shard/bedrock-mirror-shard-ea7e5ad56a1d6392468b6823e0457dd44524bca7/platform/Scheduler.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.2041003664852745}}
{"text": "Require Import floyd.proofauto.\nLocal Open Scope logic.\nRequire Import List. Import ListNotations.\nRequire Import tweetnacl20140427.tweetnaclVerifiableC.\nRequire Import tweetnacl20140427.spec_salsa.\nRequire Import sha.general_lemmas.\nRequire Import tweetnacl20140427.tweetNaclBase.\n\nLemma vn_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_vn vn_spec.\nProof.\nstart_function.\nforward.\nassert_PROP (n = Zlength (map Vint (map Int.repr (map Byte.unsigned xcont))) /\\ \n             n = Zlength (map Vint (map Int.repr (map Byte.unsigned ycont)))) as LEN by entailer!.\ndestruct LEN as [LenX LenY].\nassert (ZWS: Int.zwordsize = 32) by reflexivity. \nassert (BWS: Byte.zwordsize = 8) by reflexivity. \nforward_for_simple_bound n\n(EX i:Z, EX d:_,\n  (PROP  (Byte.eq d Byte.zero = if list_eq_dec Byte.eq_dec (sublist 0 i xcont) (sublist 0 i ycont) then true else false)\n   LOCAL (temp _d (Vint (Int.repr (Byte.unsigned d)));\n          temp _x x; temp _y y; temp _n (Vint (Int.repr n)))\n   SEP (data_at xsh (Tarray tuchar n noattr) (map Vint (map Int.repr (map Byte.unsigned xcont))) x;\n   data_at ysh (Tarray tuchar n noattr) (map Vint (map Int.repr (map Byte.unsigned ycont))) y))).\n{ Exists Byte.zero. entailer!.  }\n{ Intros. rename H0 into I. rename H1 into B. rename x0 into b.\n  forward. entailer!.\n  apply (expr_lemmas3.zero_ext_range' 8 (Int.repr (Znth i (map Byte.unsigned xcont) 0))). omega.\n  forward. entailer!.\n  apply (expr_lemmas3.zero_ext_range' 8 (Int.repr (Znth i (map Byte.unsigned ycont) 0))). omega.\n  forward. entailer!.\n  rewrite ! Zlength_map in *.\n  rewrite <- (sublist_rejoin 0 i (i+1) xcont), sublist_len_1 with (d:=Byte.zero); try omega.\n  rewrite <- (sublist_rejoin 0 i (i+1) ycont), sublist_len_1 with (d:=Byte.zero); try omega.\n  rewrite list_eq_dec_app. 2: rewrite 2 Zlength_sublist; trivial; omega. 2: rewrite 2 Zlength_cons, Zlength_nil; trivial.\n  rewrite <- B. unfold Int.xor. \n  remember (list_eq_dec Byte.eq_dec [Znth i xcont Byte.zero] [Znth i ycont Byte.zero]).  simpl.\n  rewrite or_repr. clear H0 H1 H2 H4 H5 H7 SH SH0 PNx PNy Heqs.\n  rewrite 2 Znth_map with (d':=Byte.zero) by omega.\n  rewrite 2 zero_ext_inrange by \n      (rewrite Int.unsigned_repr; [ apply Byte.unsigned_range_2 | apply byte_unsigned_range_int_unsigned_max]).\n  rewrite 2 Int.unsigned_repr by apply byte_unsigned_range_int_unsigned_max. \n  destruct (list_eq_dec Byte.eq_dec (sublist 0 i xcont) (sublist 0 i ycont)).\n  + specialize (Byte.eq_spec b Byte.zero); rewrite B; intros; subst b; clear B.\n    simpl. destruct s.\n    - inv e0. rewrite H1, Z.lxor_nilpotent, Z.lor_0_r.\n      Exists Byte.zero. entailer.\n    - destruct (Z_lxor_byte_neq (Znth i xcont Byte.zero) (Znth i ycont Byte.zero)) as [bb [BB HBB]].\n      * intros N. apply n; rewrite N; trivial.\n      * rewrite BB, Zlor_Byteor, Byte.or_zero_l.\n        Exists bb. entailer!. \n        apply Byte.eq_false; trivial.\n  + destruct s.\n    - inv e. rewrite H1, Z.lxor_nilpotent, Z.lor_0_r, andb_true_r.\n      Exists b. entailer!.\n    - destruct (Z_lxor_byte_neq (Znth i xcont Byte.zero) (Znth i ycont Byte.zero)) as [bb [BB HBB]].\n      * intros N. apply n0; rewrite N; trivial.\n      * rewrite BB, Zlor_Byteor, andb_false_r. \n        Exists (Byte.or b bb). entailer!. apply Byte.eq_false. intros N.\n        destruct (ByteOr_zero _ _ N). contradiction. }\napply extract_exists_pre; intros b.\nforward. apply prop_right.\n  rewrite ! Zlength_map in *. rewrite 2 sublist_same in H0; trivial. \n  clear H1 H4 H6 H3 H2 H5 SH SH0 PNx PNy.\n  destruct (list_eq_dec Byte.eq_dec xcont ycont).\n  + specialize (Byte.eq_spec b Byte.zero). rewrite H0; intros; subst. reflexivity.\n  + specialize (Byte.eq_spec b Byte.zero). rewrite H0; intros. clear - ZWS BWS H1.\n    f_equal. unfold Int.sub. \n    assert (Int.shru (Int.repr (Byte.unsigned b - 1)) (Int.repr 8) = Int.zero).\n    - apply Int.same_bits_eq. rewrite ZWS; intros. rewrite Int.bits_zero, Int.bits_shru; try omega.\n      rewrite (Int.unsigned_repr 8), ZWS. 2: rewrite int_max_unsigned_eq; omega.\n      if_tac; trivial. rewrite Int.testbit_repr by omega. apply isbyteZ_testbit. 2: omega.\n      destruct (Byte.unsigned_range b). replace Byte.modulus with 256 in H3 by reflexivity. split; try omega.\n      destruct (zle 0 (Byte.unsigned b - 1)); trivial. elim H1; clear H1.\n      assert (ZZ: Byte.unsigned b =0) by omega.\n      apply initialize.zero_ext_inj. rewrite ZZ; reflexivity.\n    - rewrite H, Int.and_zero; reflexivity.\nQed.\n\nLemma verify16_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_crypto_verify_16_tweet verify16_spec.\nProof.\nstart_function.\nforward_call (x,y,16,xsh,ysh,xcont,ycont).\nforward.\nQed.\n\nLemma verify32_spec_ok: semax_body SalsaVarSpecs SalsaFunSpecs\n       f_crypto_verify_32_tweet verify32_spec.\nProof.\nstart_function.\nforward_call (x,y,32,xsh,ysh,xcont,ycont).\nforward.\nQed.", "meta": {"author": "rbowden91", "repo": "cs260r-fp", "sha": "a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e", "save_path": "github-repos/coq/rbowden91-cs260r-fp", "path": "github-repos/coq/rbowden91-cs260r-fp/cs260r-fp-a1593bdcd91b5aa2e4977e67cbf0c34bc8fa561e/seplog/VST/tweetnacl20140427/verif_verify.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.2041003612989317}}
{"text": "(*\n * Copyright (c) 2020 BedRock Systems, Inc.\n * This software is distributed under the terms of the BedRock Open-Source License.\n * See the LICENSE-BedRock file in the repository root for details.\n *)\n\n(**\nAnother (incomplete) consistency proof for [PTRS], based on Krebbers' PhD thesis, and\nother formal models of C++ using structured pointers.\nThis is more complex than [SIMPLE_PTRS_IMPL], but will be necessary to justify [VALID_PTR_AXIOMS].\n\nIn this model, all valid pointers have an address pinned, but this is not meant\nto be guaranteed.\n*)\n\nFrom stdpp Require Import gmap.\nFrom bedrock.prelude Require Import base addr avl bytestring option numbers.\n\nFrom bedrock.lang.cpp Require Import ast.\nFrom bedrock.lang.cpp.semantics Require Import sub_module values.\nFrom bedrock.lang.cpp.model Require Import simple_pointers_utils inductive_pointers_utils.\n\nImplicit Types (σ : genv).\n#[local] Close Scope nat_scope.\n#[local] Open Scope Z_scope.\n\nModule PTRS_IMPL <: PTRS_INTF.\n  Import canonical_tu address_sums merge_elems.\n\n  Inductive raw_offset_seg : Set :=\n  | o_field_ (* type-name: *) (f : field)\n  | o_sub_ (ty : type) (z : Z)\n  | o_base_ (derived base : globname)\n  | o_derived_ (base derived : globname)\n  | o_invalid_.\n  #[local] Instance raw_offset_seg_eq_dec : EqDecision raw_offset_seg.\n  Proof. solve_decision. Defined.\n  #[global] Declare Instance raw_offset_seg_countable : Countable raw_offset_seg.\n\n  Definition offset_seg : Set := raw_offset_seg * Z.\n  #[local] Instance offset_seg_eq_dec : EqDecision offset_seg := _.\n  #[local] Instance offset_seg_countable : Countable offset_seg := _.\n\n  Definition eval_raw_offset_seg σ (ro : raw_offset_seg) : option Z :=\n    match ro with\n    | o_field_ f => o_field_off σ f\n    | o_sub_ ty z => o_sub_off σ ty z\n    | o_base_ derived base => o_base_off σ derived base\n    | o_derived_ base derived => o_derived_off σ base derived\n    | o_invalid_ => None\n    end.\n  Definition mk_offset_seg σ (ro : raw_offset_seg) : offset_seg :=\n    match eval_raw_offset_seg σ ro with\n    | None => (o_invalid_, 0%Z)\n    | Some off => (ro, off)\n    end.\n\n  (* This list is reversed.\n  The list of offsets in [[p; o_1; ...; o_n]] is represented as [[o_n; ... o_1]].\n  This way, we can cons new offsets to the head, and consume them at the tail. *)\n  Definition raw_offset := list offset_seg.\n  #[local] Instance raw_offset_eq_dec : EqDecision raw_offset := _.\n  #[local] Instance raw_offset_countable : Countable raw_offset := _.\n\n  Notation isnt o pattern :=\n    (match o with | pattern => False | _ => True end).\n\n  Implicit Types (z : Z).\n  (* Close Scope nat_scope. *)\n  #[local] Open Scope Z_scope.\n  Section roff_canon.\n    (* Context {σ : genv}. *)\n\n    (* We currently ensure the offsets in the destination are correct wrt the source, not that the ones in the source are consistent with each other. *)\n    Inductive roff_canon : raw_offset -> raw_offset -> Prop :=\n    | o_nil :\n      roff_canon [] []\n    | o_field_canon s d f o :\n      (* is_Some (o_field_off σ f) -> *) (* not canonicalization's problem? *)\n      roff_canon s d ->\n      roff_canon ((o_field_ f, o) :: s) ((o_field_ f, o) :: d)\n    | o_base_canon s d base derived o :\n      (* no, because (valid?) normal forms don't use [o_derived]? *)\n      (* isnt d ((o_derived_ _ _ , _) :: _) -> *)\n      roff_canon s d ->\n      roff_canon ((o_base_ derived base, o) :: s) ((o_base_ derived base, o) :: d)\n    (* should paths start from the complete object? If\n    yes, as done by Ramananandro [POPL 2012],\n    o_derived should just cancel out o_base, and this should be omitted. *)\n    (* | o_derived_wf s d derived base :\n      isnt d (o_base_ _ _ :: d) ->\n      roff_canon s d ->\n      roff_canon (o_derived_ base derived :: s) (o_derived_ base derived :: d) *)\n    | o_derived_cancel_canon s d derived base o1 o2 :\n      roff_canon s d ->\n      (* This premise is a hack, but without it, normalization might not be deterministic. Thankfully, paths can't contain o_derived step, so we're good! *)\n      (* roff_canon (o_base_ derived base :: s) (o_base_ derived base :: d) -> *)\n      roff_canon ((o_derived_ base derived, o1) :: (o_base_ derived base, o2) :: s) d\n    | o_sub_0_canon s d ty :\n      roff_canon s d ->\n      roff_canon ((o_sub_ ty 0, 0) :: s) d\n    | o_sub_canon s d ty1 z o :\n      match d with\n      | ((o_sub_ ty2 _, _) :: _) => ty1 <> ty2\n      | _ => True\n      end ->\n      (* In fact, we want [0 < z], but that's a matter of validity, not canonicalization. *)\n      z <> 0 ->\n      (* isnt o (o_sub_ _ _) *)\n      roff_canon s d ->\n      roff_canon ((o_sub_ ty1 z, o) :: s) ((o_sub_ ty1 z, o) :: d)\n    | o_sub_merge_canon s d ty z1 z2 o1 o2 :\n      (* Again, validity would require [> 0]. *)\n      z1 + z2 <> 0 ->\n      roff_canon s ((o_sub_ ty z1, o1) :: d) ->\n      roff_canon ((o_sub_ ty z2, o2) :: s) ((o_sub_ ty (z1 + z2), o1 + o2) :: d)\n    .\n  End roff_canon.\n\n  Lemma roff_canon_o_base_inv s d derived base o1 o2 :\n    roff_canon ((o_base_ derived base, o1) :: s) ((o_base_ derived base, o2) :: d) ->\n    roff_canon s d.\n  Proof. inversion 1; auto. Qed.\n\n  Lemma roff_canon_o_sub_wf s d ty z o :\n    roff_canon s ((o_sub_ ty z, o) :: d) ->\n    z <> 0.\n  Proof.\n    move E: (_ :: _) => d' Hcn.\n    elim: Hcn E; naive_solver eauto with lia.\n  Qed.\n\n  Lemma roff_canon_o_sub_no_dup s d o ty1 z ro :\n    roff_canon s ((o_sub_ ty1 z, ro) :: o :: d) ->\n    match o with\n    | (o_sub_ ty2 _, _) => ty1 <> ty2\n    | _ => True\n    end.\n  Proof.\n    move E: ((o_sub_ _ _, _) :: _) => d' Hcn.\n    elim: Hcn z ro E; naive_solver.\n  Qed.\n\n  Definition offset_seg_cons (os : offset_seg) (oss : list offset_seg) : list offset_seg :=\n    match os, oss with\n    | (o_sub_ ty1 n1, off1), _ =>\n      if decide (n1 = 0 /\\ off1 = 0)%Z then oss else\n      match oss with\n        | (o_sub_ ty2 n2, off2) :: oss' =>\n        if decide (ty1 <> ty2)\n          then os :: oss\n          else if decide (n2 + n1 = 0 /\\ off1 + off2 = 0)%Z\n          then oss'\n          else (o_sub_ ty1 (n2 + n1), (off2 + off1)%Z) :: oss'\n        | _ => os :: oss\n      end\n    | (o_derived_ base1 der1, off1), (o_base_ der2 base2, off2) :: oss' =>\n      if decide (der1 = der2 /\\ base1 = base2)\n      then oss'\n      else os :: oss\n    (* | (o_invalid_, _), _ => [(o_invalid_, 0%Z)] *)\n    | (o_invalid_, z), _ => [(o_invalid_, z)]\n    | _, _ => os :: oss\n    end.\n\n  Definition raw_offset_collapse : raw_offset -> raw_offset :=\n    foldr offset_seg_cons [].\n  Arguments raw_offset_collapse !_ /.\n\n  Definition raw_offset_wf (ro : raw_offset) : Prop :=\n    raw_offset_collapse ro = ro.\n  Arguments raw_offset_wf !_ /.\n  #[global] Instance raw_offset_wf_pi ro : ProofIrrel (raw_offset_wf ro) := _.\n  Lemma singleton_raw_offset_wf {os}\n    (Hn0 : isnt os (o_sub_ _ 0, _)) :\n    raw_offset_wf [os].\n  Proof. destruct os as [[] ?] => //=; case_decide; naive_solver. Qed.\n\n  #[local] Hint Constructors roff_canon : core.\n  Theorem canon_wf_0 src dst :\n    roff_canon src dst ->\n    roff_canon dst dst.\n  Proof.\n    intros Hrc; induction Hrc; eauto.\n    inversion IHHrc; eauto 2; last have ?: z0 = 0 by [lia]; subst.\n    (* Show that [o_sub_merge_canon] isn't applicable. *)\n    all: by efeed pose proof roff_canon_o_sub_wf.\n  Qed.\n\n  Theorem canon_wf' src dst : roff_canon src dst -> raw_offset_collapse src = dst.\n  Proof.\n    rewrite /raw_offset_wf /raw_offset_collapse => Hc;\n    induction Hc => //=; rewrite ?IHHc /offset_seg_cons //=.\n    { by [ rewrite decide_True //=; repeat (lia || f_equal)]. }\n    all: repeat ((case_decide || case_match); destruct_and?; subst => //).\n    by rewrite !right_id_L.\n  Qed.\n\n  Theorem canon_wf src dst : roff_canon src dst -> raw_offset_wf dst.\n  Proof. intros ?%canon_wf_0. exact: canon_wf'. Qed.\n\n  Definition raw_offset_merge (o1 o2 : raw_offset) : raw_offset :=\n    raw_offset_collapse (o1 ++ o2).\n  Arguments raw_offset_merge !_ _ /.\n\n  Definition offset := {ro : raw_offset | raw_offset_wf ro}.\n  #[global] Instance offset_eq_dec : EqDecision offset := _.\n\n  #[local] Definition raw_offset_to_offset (ro : raw_offset) : option offset :=\n    match decide (raw_offset_wf ro) with\n    | left Hwf => Some (exist _ ro Hwf)\n    | right _ => None\n    end.\n  #[global] Instance offset_countable : Countable offset.\n  Proof.\n    apply (inj_countable proj1_sig raw_offset_to_offset) => -[ro Hwf] /=.\n    rewrite /raw_offset_to_offset; case_match => //.\n    by rewrite (proof_irrel Hwf).\n  Qed.\n\n  Program Definition o_id : offset := [] ↾ _.\n  Next Obligation. done. Qed.\n  Program Definition mkOffset σ (ro : raw_offset_seg)\n    (Hn0 : isnt ro (o_sub_ _ 0)) : offset :=\n    [mk_offset_seg σ ro] ↾ singleton_raw_offset_wf _.\n  Next Obligation.\n    rewrite /mk_offset_seg; intros ? [] H => //=; repeat case_match => //.\n  Qed.\n  Definition o_invalid σ : offset := mkOffset σ o_invalid_ I.\n  Definition o_field σ f : offset :=\n    mkOffset σ (o_field_ f) I.\n  Definition o_base σ derived base : offset :=\n    mkOffset σ (o_base_ derived base) I.\n  Definition o_derived σ base derived : offset :=\n    mkOffset σ (o_derived_ base derived) I.\n  Program Definition o_sub σ ty z : offset :=\n    if decide (z = 0)%Z\n    then\n      match size_of σ ty with\n      | Some _ => o_id\n      | None => o_invalid σ\n      end\n    else\n    mkOffset σ (o_sub_ ty z) _.\n  Next Obligation. intros; case_match; simplify_eq/=; case_match; naive_solver. Qed.\n\n  Lemma last_last_equiv {X} d {xs : list X} : default d (stdpp.list.last xs) = List.last xs d.\n  Proof. elim: xs => // x1 xs /= <-. by case_match. Qed.\n(*\n  Section merge_elem.\n    Context {X} (f : X -> X -> list X).\n    Context (Hinv : ∀ x1 x2, merge_elems f (f x1 x2) = f x1 x2).\n\n    #[global] Instance invol_merge_elems: Involutive (merge_elems f).\n    Proof.\n    Admitted.\n\n    #[global] Instance invol_app_merge_elems: InvolApp (merge_elems f).\n    Proof.\n    Admitted.\n  End merge_elem.\n  #[local] Arguments merge_elems {X} f !_ /. *)\n\n  Definition offset_seg_append : offset_seg -> raw_offset -> raw_offset :=\n    offset_seg_cons.\n(*\n  Lemma offset_seg_cons_inv x1 x2 :\n    raw_offset_collapse (offset_seg_cons x1 x2) = offset_seg_cons x1 x2.\n  Proof.\n    move=> /= [o1 off1] [o2 off2].\n    destruct o1, o2 => //=; by repeat (case_decide; simpl).\n  Qed. *)\n\n  #[local] Definition test xs :=\n    raw_offset_collapse (raw_offset_collapse xs) = raw_offset_collapse xs.\n\n  Section tests.\n    Ltac start := intros; red; simpl.\n    Ltac step_true := rewrite ?decide_True //=.\n    Ltac step_false := rewrite ?decide_False //=.\n    Ltac res_true := start; repeat step_true.\n    Ltac res_false := start; repeat step_false.\n\n    Goal test []. Proof. res_true. Qed.\n    Goal `{n1 <> 0 -> test [(o_sub_ ty n1, o1)] }.\n    Proof. res_false; naive_solver. Qed.\n    Goal `{n1 <> 0 -> n2 <> 0 -> n2 + n1 <> 0 -> test [(o_sub_ ty n1, o1); (o_sub_ ty n2, o2)] }.\n    Proof. res_false; naive_solver. Qed.\n\n    (* Goal `{test [(o_sub_ ty n1, o1); (o_sub_ ty n2, o2); (o_field_ f, o3)] }.\n    Proof. res_true. Qed.\n\n    Goal `{test [(o_field_ f, o1); (o_sub_ ty n1, o2); (o_sub_ ty n2, o3)] }.\n    Proof. res_true. Qed.\n\n    Goal `{ty1 ≠ ty2 → test [(o_sub_ ty1 n1, o1); (o_sub_ ty2 n2, o2); (o_field_ f, o3)] }.\n    Proof. res_false. Qed.\n\n    Goal `{ty1 ≠ ty2 → test [(o_sub_ ty1 n1, o1); (o_sub_ ty1 n2, o2); (o_sub_ ty2 n3, o3); (o_field_ f, o4)] }.\n    Proof. start. step_false. step_true. step_false. Qed. *)\n  End tests.\n\n  (* This is probably sound, since it allows temporary underflows. *)\n  Definition eval_offset_seg (os : offset_seg) : option Z :=\n    match os with\n    | (o_invalid_, _) => None\n    | (_, z) => Some z\n    end.\n  Definition eval_raw_offset (o : raw_offset) : option Z :=\n    foldr (liftM2 Z.add) (Some 0) (map eval_offset_seg o).\n  Definition eval_offset (_ : genv) (o : offset) : option Z :=\n    eval_raw_offset (`o).\n  (* This is probably not generally applicable. *)\n  Local Arguments liftM2 {_ _ _ _ _ _} _ !_ !_ / : simpl nomatch.\n\n  Lemma eval_offset_nil :\n    forall {σ : genv} (wf : raw_offset_wf []),\n      eval_offset σ ([] ↾ wf) = Some 0.\n  Proof. by unfold eval_offset, eval_raw_offset; simpl. Qed.\n\n  Lemma eval_o_sub σ ty (i : Z) :\n    eval_offset _ (o_sub _ ty i) =\n      (* This order enables reducing for known ty. *)\n      (fun n => Z.of_N n * i) <$> size_of _ ty.\n  Proof.\n    rewrite /o_sub/eval_offset/eval_raw_offset/=.\n    rewrite /= /mkOffset /mk_offset_seg/=/o_sub_off/=.\n    case_decide; subst => //=;\n      case: size_of=> [sz|] //=.\n    by f_equiv; lia.\n    by rewrite (comm_L _ i) right_id_L.\n  Qed.\n\n  Lemma eval_o_field σ f n cls st :\n    f = {| f_name := n ; f_type := cls |} ->\n    glob_def σ cls = Some (Gstruct st) ->\n    st.(s_layout) = POD \\/ st.(s_layout) = Standard ->\n    eval_offset σ (o_field σ f) = offset_of σ (f_type f) (f_name f).\n  Proof.\n    move => -> _ _. cbn.\n    rewrite/mk_offset_seg /eval_raw_offset_seg /o_field_off /=.\n    case: offset_of => [off|//] /=. by rewrite right_id_L.\n  Qed.\n\n  Class InvolApp {X} (f : list X → list X) :=\n    invol_app : ∀ xs1 xs2,\n    f (xs1 ++ xs2) = f (f xs1 ++ f xs2).\n  Class Involutive {X} (f : X → X) :=\n    invol : ∀ x, f (f x) = f x.\n  #[global] Instance raw_offset_collapse_involutive : Involutive raw_offset_collapse.\n  Admitted.\n  #[global] Instance raw_offset_collapse_invol_app : InvolApp raw_offset_collapse.\n  Admitted.\n\n  Program Definition __o_dot : offset → offset → offset :=\n    λ o1 o2, (raw_offset_merge (proj1_sig o1) (proj1_sig o2)) ↾ _.\n  Next Obligation.\n    move=> o1 o2 /=.\n    exact: raw_offset_collapse_involutive.\n  Qed.\n\n  Lemma __o_dot_nil_r :\n    forall o (wf_o : raw_offset_wf o) (wf_nil : raw_offset_wf []),\n      __o_dot (o ↾ wf_o) ([] ↾ wf_nil) = o ↾ wf_o.\n  Proof.\n    intros **.\n    unfold __o_dot, raw_offset_merge, raw_offset_collapse; simpl.\n    induction o=> //=.\n    - rewrite (proof_irrel (__o_dot_obligation_1 ([] ↾ wf_o) ([] ↾ wf_nil))).\n      by rewrite (proof_irrel wf_o).\n    - rewrite (proof_irrel (__o_dot_obligation_1 ((a :: o) ↾ wf_o) ([] ↾ wf_nil))). 1: {\n        unfold raw_offset_wf, raw_offset_collapse, raw_offset_merge; simpl.\n        rewrite app_nil_r.\n        unfold raw_offset_merge, raw_offset_collapse in wf_o; simpl in wf_o.\n        rewrite wf_o.\n        done.\n      }\n      unfold raw_offset_merge, raw_offset_collapse; simpl; rewrite app_nil_r.\n      unfold raw_offset_wf, raw_offset_collapse in wf_o; simpl in wf_o.\n      rewrite wf_o; intros wf_o'.\n      by erewrite (proof_irrel wf_o).\n  Qed.\n\n  Inductive root_ptr : Set :=\n  | nullptr_\n  | global_ptr_ (tu : translation_unit_canon) (o : obj_name)\n  | alloc_ptr_ (a : alloc_id) (va : vaddr).\n\n  #[local] Instance root_ptr_eq_dec : EqDecision root_ptr.\n  Proof. solve_decision. Defined.\n  #[global] Declare Instance root_ptr_countable : Countable root_ptr.\n  #[global] Instance global_ptr__inj : Inj2 (=) (=) (=) global_ptr_.\n  Proof. by intros ???? [=]. Qed.\n\n  Definition root_ptr_alloc_id (rp : root_ptr) : option alloc_id :=\n    match rp with\n    | nullptr_ => Some null_alloc_id\n    | global_ptr_ tu o => Some (global_ptr_encode_aid o)\n    | alloc_ptr_ aid _ => Some aid\n    end.\n\n  Definition root_ptr_vaddr (rp : root_ptr) : option vaddr :=\n    match rp with\n    | nullptr_ => Some 0%N\n    | global_ptr_ tu o => Some (global_ptr_encode_vaddr o)\n    | alloc_ptr_ aid va => Some va\n    end.\n\n  Inductive ptr_ : Set :=\n  | invalid_ptr_\n  | fun_ptr_ (tu : translation_unit_canon) (o : obj_name)\n  | offset_ptr (p : root_ptr) (o : offset).\n  Definition ptr := ptr_.\n  #[global] Instance ptr_eq_dec : EqDecision ptr.\n  Proof. solve_decision. Defined.\n  #[global] Declare Instance ptr_countable : Countable ptr.\n  #[global] Instance offset_ptr_inj : Inj2 (=) (=) (=) offset_ptr.\n  Proof. by intros ???? [=]. Qed.\n\n  Definition ptr_alloc_id (p : ptr) : option alloc_id :=\n    match p with\n    | invalid_ptr_ => None\n    | fun_ptr_ tu o => Some (global_ptr_encode_aid o)\n    | offset_ptr p o => root_ptr_alloc_id p\n    end.\n\n  Definition ptr_vaddr (p : ptr) : option vaddr :=\n    match p with\n    | invalid_ptr_ => None\n    | fun_ptr_ tu o => Some (global_ptr_encode_vaddr o)\n    | offset_ptr p o =>\n      foldr\n        (λ off ova, ova ≫= offset_vaddr off)\n        (root_ptr_vaddr p)\n        (snd <$> `o)\n    end.\n\n  Definition lift_root_ptr (rp : root_ptr) : ptr := offset_ptr rp o_id.\n  Definition invalid_ptr := invalid_ptr_.\n  Definition fun_ptr tu o := fun_ptr_ (canonical_tu.tu_to_canon tu) o.\n\n  Definition null_alloc_id : alloc_id := null_alloc_id.\n  Definition nullptr := lift_root_ptr nullptr_.\n  Definition global_ptr (tu : translation_unit) o :=\n    lift_root_ptr (global_ptr_ (canonical_tu.tu_to_canon tu) o).\n  Definition alloc_ptr a oid := lift_root_ptr (alloc_ptr_ a oid).\n\n  Lemma global_ptr_nonnull tu o : global_ptr tu o <> nullptr.\n  Proof. done. Qed.\n\n  #[global] Instance global_ptr_inj tu : Inj (=) (=) (global_ptr tu) := _.\n\n  (* Some proofs using these helpers could be shortened, tactic-wise, but I find\n  them clearer this way, and they work in both models. *)\n  Lemma ptr_vaddr_global_ptr tu o :\n    ptr_vaddr (global_ptr tu o) = Some (global_ptr_encode_vaddr o).\n  Proof. done. Qed.\n  Lemma ptr_alloc_id_global_ptr tu o :\n    ptr_alloc_id (global_ptr tu o) = Some (global_ptr_encode_aid o).\n  Proof. done. Qed.\n\n  Lemma global_ptr_nonnull_addr tu o : ptr_vaddr (global_ptr tu o) <> Some 0%N.\n  Proof. rewrite ptr_vaddr_global_ptr. done. Qed.\n  Lemma global_ptr_nonnull_aid tu o : ptr_alloc_id (global_ptr tu o) <> Some null_alloc_id.\n  Proof. rewrite ptr_alloc_id_global_ptr. done. Qed.\n\n  #[global] Instance global_ptr_addr_inj tu : Inj (=) (=) (λ o, ptr_vaddr (global_ptr tu o)).\n  Proof. intros ??. rewrite !ptr_vaddr_global_ptr. by intros ?%(inj _)%(inj _). Qed.\n  #[global] Instance global_ptr_aid_inj tu : Inj (=) (=) (λ o, ptr_alloc_id (global_ptr tu o)).\n  Proof. intros ??. rewrite !ptr_alloc_id_global_ptr. by intros ?%(inj _)%(inj _). Qed.\n\n  Lemma ptr_vaddr_nullptr : ptr_vaddr nullptr = Some 0%N.\n  Proof. done. Qed.\n\n  Lemma ptr_alloc_id_nullptr : ptr_alloc_id nullptr = Some null_alloc_id.\n  Proof. done. Qed.\n\n  #[local] Instance ptr_eq_dec' : EqDecision ptr := ptr_eq_dec.\n\n  (* Instance ptr_equiv : Equiv ptr := (=).\n  Instance offset_equiv : Equiv offset := (=).\n  Instance ptr_equivalence : Equivalence (≡@{ptr}) := _.\n  Instance offset_equivalence : Equivalence (==@{offset}) := _.\n  Instance ptr_equiv_dec : RelDecision (≡@{ptr}) := _.\n  Instance offset_equiv_dec : RelDecision (==@{offset}) := _. *)\n\n  (* Instance dot_assoc : Assoc (≡) o_dot := _. *)\n  (* Instance dot_proper : Proper ((≡) ==> (≡) ==> (≡)) o_dot := _. *)\n\n  Definition __offset_ptr (p : ptr) (o : offset) : ptr :=\n    match p with\n    | offset_ptr p' o' => offset_ptr p' (__o_dot o' o)\n    | invalid_ptr_ => invalid_ptr_ (* too eager! *)\n    | fun_ptr_ _ _ =>\n      match `o with\n      | [] => p\n      | _ => invalid_ptr_\n      end\n    end.\n\n  Include PTRS_SYNTAX_MIXIN.\n  (* Duplicated. *)\n  #[global] Notation \"p ., o\" := (_dot p (o_field _ o))\n    (at level 11, left associativity, only parsing) : stdpp_scope.\n\n  #[local] Ltac UNFOLD_dot := rewrite _dot.unlock/DOT_dot/=.\n\n  (* [eval_offset] respects the monoidal structure of [offset]s *)\n  Lemma eval_offset_dot : ∀ σ (o1 o2 : offset),\n    eval_offset σ (o1 ,, o2) =\n    add_opt (eval_offset σ o1) (eval_offset σ o2).\n  Proof.\n    intros **; UNFOLD_dot.\n    destruct o1 as [[] ?]; destruct o2 as [[] ?]=> //=.\n    - unfold __o_dot, raw_offset_merge, raw_offset_collapse; simpl.\n      unfold eval_offset, eval_raw_offset; simpl.\n      unfold raw_offset_wf, raw_offset_collapse in r0; simpl in r0.\n      rewrite r0/=.\n      destruct (eval_offset_seg o);\n        destruct (foldr (liftM2 Z.add) (Some 0) (map eval_offset_seg l))=> //.\n    - rewrite __o_dot_nil_r.\n      unfold eval_offset, eval_raw_offset=> /=.\n      destruct (liftM2 Z.add (eval_offset_seg o)\n                       (foldr (liftM2 Z.add) (Some 0) (map eval_offset_seg l)))=> //.\n      unfold add_opt; simpl.\n      by rewrite Z.add_0_r.\n    - unfold __o_dot, raw_offset_merge, raw_offset_collapse, eval_offset, eval_raw_offset.\n      unfold proj1_sig; rewrite foldr_app.\n      unfold raw_offset_wf, raw_offset_collapse in *.\n      rewrite !foldr_fmap.\n      rewrite r0.\n      admit.\n  Admitted.\n\n  #[global] Instance id_dot : LeftId (=) o_id o_dot.\n  Proof. UNFOLD_dot. intros o. apply /sig_eq_pi. by case: o. Qed.\n  Lemma __o_dot_id : RightId (=) o_id __o_dot.\n  Proof.\n    intros o. apply /sig_eq_pi.\n    rewrite /= /raw_offset_merge (right_id []).\n    by case: o.\n  Qed.\n  #[global] Instance dot_id : RightId (=) o_id o_dot.\n  Proof. UNFOLD_dot. apply __o_dot_id. Qed.\n  #[global] Instance dot_assoc : Assoc (=) o_dot.\n  Proof.\n    UNFOLD_dot.\n    intros o1 o2 o3. apply /sig_eq_pi.\n    move: o1 o2 o3 => [ro1 /= wf1]\n      [ro2 /= wf2] [ro3 /= wf3].\n      rewrite /raw_offset_merge.\n      rewrite -{1}wf1 -{2}wf3.\n      rewrite -!invol_app; f_equiv.\n      apply: assoc.\n  Qed.\n\n  Implicit Types (p : ptr) (o : offset).\n\n  Lemma offset_ptr_id p : p ,, o_id = p.\n  Proof. UNFOLD_dot. case: p => // p o. by rewrite /__offset_ptr __o_dot_id. Qed.\n\n  Lemma offset_ptr_dot p o1 o2 : p ,, (o1 ,, o2) = p ,, o1 ,, o2.\n  Proof.\n    (* TO FIX: collapse function pointers with offsets less eagerly. *)\n    UNFOLD_dot.\n    destruct p; rewrite //= ?assoc //=.\n    move: o1 o2 => [o1 /= +] [o2 /= +]; rewrite /raw_offset_wf => WF1 WF2.\n    repeat (case_match; simplify_eq/= => //).\n    by rewrite H in WF2.\n  Admitted.\n\n  Lemma o_sub_0 σ ty :\n    is_Some (size_of σ ty) ->\n    o_sub σ ty 0 = o_id.\n  Proof. rewrite /o_sub; case_decide=>// -[?]; by case: size_of. Qed.\n\n  Lemma ptr_alloc_id_offset {p o} :\n    let p' := p ,, o in\n    is_Some (ptr_alloc_id p') -> ptr_alloc_id p' = ptr_alloc_id p.\n  Proof. UNFOLD_dot. by destruct p, o as [[] ?] => //= /is_Some_None []. Qed.\n\n  Axiom ptr_vaddr_o_sub_eq : forall p σ ty n1 n2 sz,\n    size_of σ ty = Some sz -> (sz > 0)%N ->\n    same_property ptr_vaddr (p ,, o_sub _ ty n1) (p ,, o_sub _ ty n2) ->\n    n1 = n2.\n\n  Arguments mk_offset_seg _ !_ /.\n  Lemma o_dot_sub σ (z1 z2 : Z) ty :\n    o_sub σ ty z1 ,, o_sub σ ty z2 = o_sub σ ty (z1 + z2).\n  Proof.\n    UNFOLD_dot.\n    intros. apply /sig_eq_pi => /=.\n    rewrite /o_sub /= /mkOffset. repeat case_decide => //=.\n    all: subst; try lia.\n    all: rewrite ?Z.add_0_r ?Z.add_0_l.\n    all: rewrite /mk_offset_seg /= /o_sub_off; case: size_of => [sz|] //=.\n    all: try by rewrite decide_False //=; lia.\n    all: repeat (case_decide; try (lia || by auto)).\n    repeat (lia || f_equiv).\n  Qed.\n\n  Lemma o_base_derived σ p base derived :\n    directly_derives σ derived base ->\n    p ,, o_base σ derived base ,, o_derived σ base derived = p.\n  Proof.\n    rewrite -offset_ptr_dot; UNFOLD_dot.\n    intros Hsome. destruct p => //=.\n    (* TODO: this model collapses invalid offsets on fun_ptr_ to invalid pointers too eagerly. *)\n    admit.\n    f_equiv.\n    apply (sig_eq_pi _) => /=.\n    move: Hsome => [?].\n    rewrite /o_base_off /o_derived_off parent_offset.unlock.\n    destruct parent_offset_tu => //= -[_] /=.\n    rewrite /raw_offset_merge/=.\n    rewrite /raw_offset_collapse /=.\n    rewrite foldr_app /=.\n    (* TODO: here we should prove that cancellation works out, but the\n    ill-behaved normalization makes this too complex. *)\n  Admitted.\n\n  Lemma o_derived_base σ p base derived :\n    directly_derives σ derived base ->\n    p ,, o_derived σ base derived ,, o_base σ derived base = p.\n  Proof.\n    rewrite -offset_ptr_dot; UNFOLD_dot.\n    intros Hsome. destruct p => //=.\n    {\n      case_match => //.\n      exfalso.\n      Fail repeat case_match; naive_solver.\n      (* TODO: this model collapses invalid offsets on fun_ptr_ to invalid\n      pointers too eagerly. *)\n      admit.\n    }\n    f_equiv.\n    case: o => o. rewrite /raw_offset_wf => Hwf.\n    apply (sig_eq_pi _) => /=.\n    move: Hsome => [?].\n    rewrite /o_base_off /o_derived_off parent_offset.unlock.\n    destruct parent_offset_tu => //= -[_] /=.\n    rewrite decide_True //=.\n    rewrite /raw_offset_merge/= app_nil_r //.\n    all: done.\n  Admitted.\n\n  Include PTRS_DERIVED_MIXIN.\n  Include PTRS_MIXIN.\nEnd PTRS_IMPL.\n", "meta": {"author": "bedrocksystems", "repo": "BRiCk", "sha": "23d7e64cc53706de608dbff0be75d1c4b8c3a7ec", "save_path": "github-repos/coq/bedrocksystems-BRiCk", "path": "github-repos/coq/bedrocksystems-BRiCk/BRiCk-23d7e64cc53706de608dbff0be75d1c4b8c3a7ec/theories/lang/cpp/model/inductive_pointers.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.36296920551961676, "lm_q1q2_score": 0.20405275788831628}}
{"text": "From mathcomp.ssreflect\nRequire Import ssreflect ssrbool ssrnat eqtype ssrfun seq.\nFrom mathcomp\nRequire Import path.\nRequire Import Eqdep.\nRequire Import Relation_Operators.\nFrom fcsl\nRequire Import pred prelude ordtype finmap pcm unionmap heap.\nFrom DiSeL\nRequire Import Freshness State EqTypeX Protocols Worlds NetworkSem Rely.\nFrom DiSeL\nRequire Import Actions Injection Process Always HoareTriples InferenceRules.\nFrom DiSeL\nRequire Import InductiveInv While.\nFrom DiSeL\nRequire Import CalculatorProtocol CalculatorInvariant.\nFrom DiSeL\nRequire Import CalculatorClientLib CalculatorServerLib.\nFrom DiSeL\nRequire Import DelegatingCalculatorServer SimpleCalculatorServers.\n\nExport CalculatorProtocol.\n\nSection CalculatorApp.\n\nDefinition l1 := 1.\nDefinition l2 := 2.\nLemma lab_dis : l2 != l1. Proof. by []. Qed.\n\nDefinition f args :=\n  match args with\n  | x::y::_ => Some (x + y)\n  | _ => None\n  end.\n\nDefinition prec (args : input) :=\n  if args is x::y::_ then true else false.\n\nLemma prec_valid :\n  forall i, prec i -> exists v, f i = Some v.\nProof. by move=>i; case: i=>//=x; case=>//y _ _; eexists _. Qed.\n\n(* Two overlapping calculator systems *)\n(* System 1: one server, one client *)\nDefinition cs1 := [::1].\nDefinition cls1 := [::2].\n\n(* System 2: one server, one client *)\nDefinition cs2 := [::3].\nDefinition cls2 := [::1].\n\nNotation nodes1 := (cs1 ++ cls1).\nNotation nodes2 := (cs2 ++ cls2).\nLemma Huniq1 : uniq nodes1. Proof. by []. Qed.\nLemma Huniq2 : uniq nodes2. Proof. by []. Qed.\n\n(* Protocol I'm a server in *)\nNotation cal1 := (cal_with_inv l1 f prec cs1 cls1).\nNotation cal2 := (cal_with_inv l2 f prec cs2 cls2).\n\nNotation W1 := (mkWorld cal1).\nNotation W2 := (mkWorld cal2).\n\n(* Composite world *)\nDefinition V := W1 \\+ W2.\nLemma validV : valid V.\nProof.\nrewrite /V; apply/andP=>/=.\nsplit; first by rewrite validPtUn/= validPt/= domPt inE/=.\nby rewrite unitR valid_unit.\nQed.\n\n(* This server node *)\nDefinition sv : nid := 1.\nDefinition cl : nid := 2.\n(* It's a server in protocol cal1 *)\nLemma  Hs1 : sv \\in cs1. Proof. by []. Qed.\n(* It's a client in protocol cal2 *)\nLemma  Hc2 : sv \\in cls2. Proof. by []. Qed.\nLemma Hc1 : cl \\in cls1. Proof. by []. Qed.\n(* Delegate server *)\nDefinition sd := 3.\nLemma Hs2 : sd \\in cs2. Proof. by []. Qed.\n\nNotation loc i k := (getLocal sv (getStatelet i k)).\nNotation loc1 i := (loc i l1).\nNotation loc2 i := (loc i l2).\n\n(****************************************************)\n(***********        Initial state     ***************)\n(****************************************************)\n\nDefinition init_loc := st :-> ([::] : reqs). \n\nDefinition init_dstate1 := sv \\\\-> init_loc \\+ cl \\\\-> init_loc.\nDefinition init_dstate2 := sv \\\\-> init_loc \\+ sd \\\\-> init_loc.\n\nLemma valid_init_dstate1 : valid init_dstate1.\nProof.\ncase: validUn=>//=;\ndo?[case: validUn=>//; do?[rewrite ?validPt/=//]|by rewrite validPt/=].\nby move=>k; rewrite !domPt !inE/==>/eqP<-/eqP.\nQed.\n\nLemma valid_init_dstate2 : valid init_dstate2.\nProof.\ncase: validUn=>//=;\ndo?[case: validUn=>//; do?[rewrite ?validPt/=//]|by rewrite validPt/=].\nby move=>k; rewrite !domPt !inE/==>/eqP<-/eqP.\nQed.\n\nNotation init_dstatelet1 := (DStatelet init_dstate1 Unit).\nNotation init_dstatelet2 := (DStatelet init_dstate2 Unit).\n\nDefinition init_state : state :=\n  l1 \\\\-> init_dstatelet1 \\+ l2 \\\\-> init_dstatelet2.\n\nLemma validI : valid init_state.\nProof.\ncase: validUn=>//=; do?[case: validUn=>//;\n  do?[rewrite ?gen_validPt/=//]|by rewrite validPt/=];\n  by move=>k; rewrite !domPt !inE/==>/eqP<-/eqP.\nQed.\n\nLemma coh1': calcoh prec cs1 cls1 init_dstatelet1 /\\\n             CalcInv l1 f prec cs1 cls1 init_dstatelet1.\nProof.\nsplit; last by move=>?????????/=/esym/empbP/=; rewrite empbPtUn.\nsplit=>//; rewrite ?valid_init_dstate1//.\n- split; first by rewrite valid_unit.\n  by move=>m ms; rewrite find0E. \n- move=>z; rewrite /=/init_dstate1 domUn !inE/= valid_init_dstate1/=.\n  by rewrite !domPt !inE !(eq_sym z). \nmove=>n/=; rewrite inE=>/orP; case=>//=. \n- move/eqP=>->/=; exists [::]=>/=.\n  rewrite /getLocal/init_dstate1/= findUnL?valid_init_dstate1//.\n  by rewrite domPt/= findPt/=.\nrewrite inE=>/eqP=>->; exists [::]=>/=.\nrewrite /getLocal/init_dstate1/= findUnL?valid_init_dstate1//.\nby rewrite domPt/= findPt.\nQed.\n\nLemma coh1 : l1 \\\\-> init_dstatelet1 \\In Coh W1.\nProof.\nsplit=>//.\n- apply/andP; split; last by rewrite valid_unit.\n  by rewrite ?validPt.\n- by rewrite validPt/=.\n- by apply: hook_complete_unit.  \n- by move=>z; rewrite !domPt !inE/=.\nmove=>k; case B: (l1==k); last first.\n- have X: (k \\notin dom W1.1).\n    by rewrite /init_state/W1/=!domPt !inE/=; move/negbT: B. \n  by rewrite /getProtocol /getStatelet/= ?findPt2 eq_sym !B/=. \nmove/eqP:B=>B; subst k; rewrite prEq/getStatelet/init_state findPt/=.\nexact: coh1'.\nQed.\n\nLemma coh2' : calcoh prec cs2 cls2 init_dstatelet2 /\\\n              CalcInv l2 f prec cs2 cls2 init_dstatelet2.\nProof.\nsplit; last by move=>?????????/=/esym/empbP/=; rewrite empbPtUn.\nsplit=>//; rewrite ?valid_init_dstate2//.\n- split; first by rewrite valid_unit.\n  by move=>m ms; rewrite find0E//. \n- move=>z; rewrite /=/init_dstate2 domUn !inE/= valid_init_dstate2//=.\n  by rewrite !domPt !inE !(eq_sym z) orbC. \nmove=>n/=; rewrite inE=>/orP; case=>//=. \n- move/eqP=>->/=; exists [::]=>/=.\n  rewrite /getLocal/init_dstate2/= findUnL?valid_init_dstate2//.\n  by rewrite domPt/= findPt/=.\nrewrite inE=>/eqP=>->; exists [::]=>/=.\nrewrite /getLocal/init_dstate2/= findUnL?valid_init_dstate2//.\nby rewrite domPt/= findPt.\nQed.\n\nLemma coh2 : l2 \\\\-> init_dstatelet2 \\In Coh W2.\nProof.\nsplit.\n- apply/andP; split; last by rewrite valid_unit.\n  by rewrite ?validPt.\n- by rewrite validPt/=.\n- by apply: hook_complete_unit.  \n- by move=>z; rewrite !domPt !inE/=.\nmove=>k; case B: (l2==k); last first.\n- have X: (k \\notin dom W2.1).\n    by rewrite /init_state/W2/=!domPt !inE/=; move/negbT: B. \n  by rewrite /getProtocol /getStatelet/= ?findPt2 eq_sym !B/=. \nmove/eqP:B=>B; subst k; rewrite prEq/getStatelet/init_state findPt/=.\nexact: coh2'.\nQed.\n\nLemma init_coh : init_state \\In Coh V.\nProof.\nsplit=>//; first by apply: validV.\n- by apply: validI.\n- rewrite /V/=/init_state/==>z.\n- by move=>???; rewrite domUn !inE/= dom0 andbC.\n- rewrite /V/init_state=>z; rewrite !domUn !inE; case/andP:validV=>->_/=.\n  by rewrite validI/= !domPt. \nmove=>k; case B: ((l1 == k) || (l2 == k)); last first.\n- have X: (k \\notin dom V.1).\n  + by rewrite /V domUn inE/= !domPt!inE/= B andbC. \n  rewrite /getProtocol /getStatelet/=.\n  case: dom_find (X)=>//->_/=; rewrite /init_state.\n  case/negbT/norP: B=>/negbTE N1/negbTE N2.\n  rewrite findUnL; rewrite ?validI// domPt inE N1.\n  rewrite findPt2 eq_sym N1/=.\n  by rewrite findPt2 eq_sym N2/=.\ncase/andP: validV=>V1 V2.\ncase/orP:B=>/eqP Z; subst k;\nrewrite /getProtocol/V findUnL/= ?V1 ?domPt ?inE/= ?findPt;\nrewrite /getStatelet ?findUnL/= ?validI// ?domPt ?inE/= ?findPt;\n[by case: coh1'|by case coh2'].\nQed.\n\n(****************************************************)\n(***********    Runnable programs     ***************)\n(****************************************************)\n\nDefinition client_input :=\n  [:: [::1; 2]; [::3; 4]; [::5; 6]; [::7; 8]; [::9; 10]].\n\nDefinition compute_input := compute_list_f l1 f prec cs1 cls1 cl Hc1 sv.\n\n(* [C] A simple client, evaluating a serives of requests *)\nProgram Definition client_run (u : unit) :\n  DHT [cl, V]\n   (fun i => network_rely V cl init_state i,\n   fun (res : seq (input * nat)) m =>\n     [/\\ all (fun e => f e.1 == Some e.2) res &\n      client_input = map fst res]) :=\n  Do (uinject (compute_input client_input)).\n\nNext Obligation.\nrewrite -(unitR V)/V.\nhave V: valid (W1 \\+ W2 \\+ Unit) by rewrite unitR validV.\napply: (injectL V); do?[apply: hook_complete_unit | apply: hooks_consistent_unit].\nby move=>??????; rewrite dom0.\nQed.\n\nNext Obligation.\nmove=>i/=R.\nhave X: injects W1 V Unit.\n- move: (@injectL W1 W2 Unit)=>/=; rewrite !unitR validV=>H.\n  apply: H=>//; do? [by apply: hook_complete0]. \n  by move=>l _=>????; rewrite dom0. \ncase: (rely_ext X coh1 R)=>i1[j1][Z]C'; subst i.\napply: inject_rule=>//.\napply: call_rule=>C1{C'}/=; last by move=>m[H1]H2 H3.\nhave E: (getStatelet i1 l1) = (getStatelet (i1 \\+ j1) l1).\n- by rewrite (locProjL (proj2 (rely_coh R)) _ C1)=>//; rewrite /W1 domPt.\nrewrite E (rely_loc' _ R)/getLocal/=/getStatelet/=.\nrewrite findUnL ?validI// domPt inE eqxx findPt/=.\nby rewrite /init_dstate1 findUnR?valid_init_dstate1// domPt/= findPt/=.\nQed.\n\n(* [S1] Delegating server, serving the client's needs *)\nDefinition delegating_server (u : unit) :=\n  delegating_server_loop l1 l2 lab_dis f prec cs1 cls1 cs2 cls2 sv\n                         Hs1 Hc2 sd Hs2.\n\nProgram Definition server1_run (u : unit) :\n  DHT [sv, V]\n   (fun i => network_rely V sv init_state i,\n   fun (res : unit) m => False) :=\n  Do (delegating_server u).\nNext Obligation.\nmove=>i/=R; apply: call_rule=>C1//=.\nrewrite (rely_loc' _ R)/getLocal/=/getStatelet/=.\nrewrite findUnL ?validI ?valid_init_dstate1//.\nrewrite domPt inE eqxx findPt/=. \nrewrite findUnR ?validI ?valid_init_dstate1//=.\nrewrite domPt inE/= findPt/=; split=>//.\nrewrite -(rely_loc _ R)/=/getStatelet findUnR ?validI ?valid_init_dstate1//=.\nrewrite domPt inE/= findPt/= /init_dstate2/=.\nrewrite findUnL ?validI ?valid_init_dstate2//.\nby rewrite domPt inE/= findPt/= /init_dstate2/=.\nQed.\n\n(* [S2] A memoizing server, serving as a delegate *)\n\nDefinition secondary_server (u : unit) :=\n  with_inv (ii l2 f prec cs2 cls2)\n           (memoizing_server l2 f prec prec_valid cs2 cls2 sd Hs2).  \n\nProgram Definition server2_run (u : unit) :\n  DHT [sd, V]\n   (fun i => network_rely V sd init_state i,\n    fun (res : unit) m => False) :=\n  Do _ (@inject sd W2 V Unit _ _ (secondary_server u);; ret _ _ tt).\n\nNext Obligation.\nrewrite -(unitR V)/V.\nhave V: valid (W1 \\+ W2 \\+ Unit) by rewrite unitR validV.\napply: (injectR V); do?[apply: hook_complete_unit | apply: hooks_consistent_unit].\nby move=>??????; rewrite dom0.\nQed.\n\nNext Obligation.\nmove=>i/=R; apply: step.\nrewrite /init_state joinC.\n\nhave X: injects W2 V Unit.\n- move: (@injectL W2 W1 Unit)=>/=; rewrite !unitR=>H. \n  rewrite /V joinC;apply: H=>//; do? [by apply: hook_complete0].\n  + by rewrite joinC validV.\n  by move=>l _=>????; rewrite dom0.\nrewrite /V joinC in R X; rewrite /init_state [l1 \\\\->_ \\+ _]joinC in R.\ncase: (rely_ext X coh2 R)=>j1[i1][Z]C'; subst i.\napply: inject_rule=>//=.\napply: with_inv_rule; apply:call_rule=>//_.\nhave E: (getStatelet j1 l2) = (getStatelet (j1 \\+ i1) l2).\n- by rewrite (locProjL (proj2 (rely_coh R)) _ C')=>//; rewrite /W1 domPt.\nrewrite E (rely_loc' _ R)/getLocal/=/getStatelet/=.\nrewrite findUnL ?validI//; last by rewrite joinC validI.\nrewrite domPt/= findPt/=.\nby rewrite /init_dstate2 findUnL ?valid_init_dstate2 ?domPt/= ?findPt.  \nQed.\n\nEnd CalculatorApp.\n\n(***************************************************)\n(* Now all three programs run in the same world!   *)\n(***************************************************)\n\nDefinition c_runner (u : unit) := client_run u.\nDefinition s_runner1 (u : unit) := server1_run u.\nDefinition s_runner2 (u : unit) := server2_run u.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/disel/Examples/Calculator/SimpleCalculatorApp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.2039926710912334}}
{"text": "(* --------------------------------------------------------------------\n * Copyright (c) - 2006--2012 - IMDEA Software Institute\n * Copyright (c) - 2006--2012 - Inria\n * Copyright (c) - 2006--2012 - Microsoft Coprporation\n *\n * Distributed under the terms of the CeCILL-B-V1 license\n * -------------------------------------------------------------------- *)\n\nRequire Import SwitchingSem.\n\nOpen Scope nat_scope.\nSet Implicit Arguments.\n\n(********************* MOVE THIS SOMEWHERE ELSE *********************)\n(********************************************************************)\n\n Lemma range_Munit: forall (A:Type) (a : A) (P : A -> Prop),\n  P a -> range  P (Munit a).\n Proof.\n  intros A a P Ha f Hf.\n  apply (Hf a Ha).\n Qed.\n\n Lemma eval_lt : forall k (m:Mem.t k)  (e1 e2: E.expr T.Nat),\n   E.eval_expr  e1 m < E.eval_expr e2 m <-> \n   E.eval_expr (e1 <! e2) m.\n Proof.\n  intros; split; intros.\n    change (is_true (leb ((E.eval_expr e1 m)+1) (E.eval_expr e2 m))).\n    apply leb_correct; rewrite plus_comm; apply gt_le_S.\n    assumption.\n    change (is_true (leb ((E.eval_expr e1 m) + 1) (E.eval_expr e2 m))) in H.\n    apply leb_complete in H; rewrite plus_comm in H; apply le_S_gt in H.\n    assumption.\n Qed.\n\n Lemma drestr_range: forall A (d:Distr A) (P:A-o>boolO),  \n    range P (drestr d  P).\n  Proof.\n   unfold range; intros.\n   rewrite mu_drestr.\n   rewrite (mu_stable_eq d _ (fzero _)).\n     rewrite <-mu_zero; trivial.\n     unfold restr; refine (ford_eq_intro _); intro a.\n     generalize (H a); case (P a); intro Heq.\n       rewrite <-Heq; trivial.\n       trivial.\n Qed.\n\n(********************************************************************)\n(********************************************************************)\n\n\n Fixpoint seq_cmd (c:cmd) (n:nat) {struct n} : cmd :=\n  match n with\n   | O => @nil I.instr\n   | S n => c ++ (seq_cmd c n)\n  end.\n\n Lemma seq_cmd_Sn_tail_unfold : forall c E n k (m:Mem.t k) f,\n  mu ([[ seq_cmd c (S n) ]] E m) f ==  \n  mu ([[ seq_cmd c n ]] E m) (fun m' => mu ([[ c ]] E m') f). \n Proof.\n  induction n; intros.\n    rewrite (deno_app_elim E c nil m), deno_nil_elim.\n    refine (mu_stable_eq _ _ _ _); refine (ford_eq_intro _). \n    intro m'; apply deno_nil_elim.\n\n    rewrite (deno_app_elim E c (seq_cmd c (S n)) m),\n      (deno_app_elim E c (seq_cmd c n) m).\n    refine (mu_stable_eq _ _ _ _); refine (ford_eq_intro _). \n    intro m'; apply IHn.\n Qed.\n\n Opaque deno.\n Opaque E.eval_expr.\n\n Lemma unroll_false_while_elim : forall (e:E.expr T.Bool) c n E k (m:Mem.t k) f,\n  E.eval_expr e m = false ->\n  mu ([[unroll_while e c n ]] E m) f == f m.\n Proof.\n  intros; case n; simpl.\n    \n    rewrite (deno_cond_elim _ _ _ _ m).  \n    case (@E.eval_expr _ T.Bool e m); rewrite deno_nil_elim; trivial.\n    intro.\n    rewrite (deno_cond_elim _ _ _ _ m), H, deno_nil_elim; trivial.\n Qed.\n\n\n Lemma false_while_elim : forall (e:E.expr T.Bool) c E k (m:Mem.t k) f,\n  E.eval_expr e m = false ->\n  mu ([[ [while e do c] ]] E m) f == f m.\n Proof.\n  intros.\n  rewrite deno_while_elim, deno_cond_elim, H.\n  apply deno_nil_elim.\n Qed.\n\n\n Section for_loop.\n\n  Close Scope U_scope.\n  Open Scope nat_scope.\n\n  Variable i : E.expr T.Nat.\n  Variable q : nat.\n  Variable c : cmd.\n  Variable E : env.\n  Variable P : forall k, (Mem.t k) -> Prop.\n  \n  Hypothesis Hran : forall k (m:Mem.t k), \n   P m ->\n   range (fun m' => E.eval_expr i m' = S (E.eval_expr i m) /\\ P m') ([[c]] E m).\n\n\n Lemma seq_cmd_range:  forall n k (m:Mem.t k), \n  P m ->\n  range (fun m' => E.eval_expr i m' = E.eval_expr i m + n /\\ P m') ([[seq_cmd c n ]] E m). \n Proof.\n  induction n; intros.\n    rewrite deno_nil, plus_0_r.\n    apply range_Munit; split; trivial.\n\n    rewrite (deno_app E c (seq_cmd c n) m) .\n    eapply range_Mlet; [ apply (Hran H) | ].\n    intros m' [Hm'1 Hm'2].\n    eapply range_weaken; [ | apply (IHn _ _ Hm'2) ].\n    intros m'' [Hm''1 Hm''2]; split.\n      rewrite Hm''1, Hm'1; apply plus_Snm_nSm.\n      assumption.\n Qed.\n  (* TODO: use this to simpify following proofs *)\n\n\n  Lemma unroll_for_loop_aux: forall n j k (m:Mem.t k) f, \n   P m ->\n   q - E.eval_expr i m < S n ->\n   mu ([[ unroll_while (i <! q) c (j + n)]] E m) f == \n   mu ([[ unroll_while (i <! q) c n ]] E m)  \n     (fun m' => mu (if negP (E.eval_expr (i <! q)) m' then Munit m' else (@distr0 _) ) f).\n Proof.\n  induction n; intros; unfold negP; intros.\n    (* case n=0 *)\n    rewrite plus_0_r.\n    assert (@E.eval_expr _ T.Bool (i <! q) m = false) by\n      (apply (leb_correct_conv q (E.eval_expr i m + 1)%nat); omega).\n    destruct j; simpl.\n      repeat (rewrite (deno_cond_elim _ _ _ _ m); case (@E.eval_expr _ T.Bool (i <! q) m); \n        rewrite deno_nil_elim); (rewrite H1; trivial).\n      repeat rewrite (deno_cond_elim  _ _ _ _ m), H1, deno_nil_elim.\n      rewrite H1; trivial.\n    (* inductive case *)\n    rewrite plus_comm, plus_Sn_m, plus_comm; simpl.\n    repeat rewrite (deno_cond_elim  _ _ _ _ m).\n    case_eq (@E.eval_expr _ T.Bool (i <! q) m); [ intros _ | intro Heq ].\n      (* case [i < q] *)\n      repeat rewrite deno_app_elim.\n      apply (range_eq (Hran H)); intros m' [Hm'1 Hm'2].\n      apply (IHn _ _ _ _ Hm'2); repeat rewrite eval_minus in *; omega.\n      (* case [i >= q ] *) \n      rewrite deno_nil_elim, deno_nil_elim, Heq; trivial.\n Qed.\n\n\n Lemma unroll_for_loop: forall k (m:Mem.t k) f n,\n   P m ->\n   q - E.eval_expr i m < S n ->\n   mu ([[ [while (i <! q) do c] ]] E m) f ==  mu ([[ unroll_while (i <! q) c n]] E m) \n     (fun m' => mu (if negP (E.eval_expr (i <! q)) m' then Munit m' else (@distr0 _) ) f).\n Proof.\n  intros.\n  rewrite deno_while_unfold_elim.\n  match goal with |- _ == ?F => rewrite <-(lub_cte F) end.\n  refine (@lub_eq_lift _ _ _ n _). \n  intros j Hj; simpl.\n  rewrite <-(plus_0_l n), (le_plus_minus _ _ Hj), plus_comm.\n  repeat rewrite (@unroll_for_loop_aux  n _ _ _ _ H H0). \n  trivial.\n Qed.\n\n\n Lemma unroll_for_loop_seq_cmd_aux: forall j n k (m:Mem.t k) f, \n   P m ->\n   (j <= q - E.eval_expr i m)%nat ->\n   mu ([[ unroll_while (i <! q) c (j + n) ]] E m) f == \n   mu ([[ seq_cmd c j ]] E m)  \n    (restr (EP k (i =?= E.eval_expr i m + j))  \n      (fun m' => mu ([[ unroll_while (i <! q) c n]] E m') f)). \n Proof.\n  induction j; intros; unfold seq_cmd.\n    (* case [j = 0] *)\n    rewrite deno_nil_elim, plus_0_r.\n    unfold restr, EP; replace \n      (@E.eval_expr _ T.Bool (i =?= E.eval_expr i m) m) with true; trivial.\n      symmetry; apply (nat_eqb_refl (E.eval_expr i m)).\n    (* inductive case *)\n    rewrite plus_Sn_m; simpl; fold (seq_cmd c j).\n    repeat rewrite (deno_cond_elim _ _ _ _ m).\n    replace (@E.eval_expr _ T.Bool (i <! q) m) with true;\n     [|symmetry; apply (leb_correct (E.eval_expr i m + 1) q); omega ].\n    repeat rewrite (deno_app_elim _ _ _ m).\n    apply (range_eq (Hran H)); intros m' [Hm'1 Hm'2].\n    rewrite <-plus_Snm_nSm, <-Hm'1.\n    apply (IHj _ _ _ _ Hm'2); omega.\n Qed.\n\n\n\nEnd for_loop.\n\n \nClose Scope U_scope.\n\n Lemma unroll_for_loop_seq_cmd: forall (i : E.expr T.Nat) c E (P:forall k, Mem.t k -> Prop) (n:nat) k (m:Mem.t k) f,\n   (forall k (m:Mem.t k), P _ m ->\n    range (fun m' => E.eval_expr i m' = S (E.eval_expr i m) /\\ P _ m') ([[c]] E m)) ->\n   P _ m ->\n   E.eval_expr (i <! n) m = true  ->\n   mu ([[ [ while (i <! n) do c ] ]] E m) f == \n   mu ([[ seq_cmd c (n - E.eval_expr i m) ]] E m) \n     (restr (EP k (i =?= n)) f).\n Proof.\n  intros.\n  rewrite (@unroll_for_loop _ _ _ _ _ H _ _ _ _  H0 (lt_n_Sn _)).    \n  rewrite <-(plus_0_r (n - E.eval_expr i m)),\n   (unroll_for_loop_seq_cmd_aux _ _ _ H _ _ _ H0 (le_refl _)), plus_0_r.\n  refine (mu_stable_eq _ _ _ _).\n  unfold restr, EP, negP; refine (ford_eq_intro _); intro m'.\n  replace (E.eval_expr i m + (n - E.eval_expr i m))%nat with n;\n   [ | apply (leb_complete  (E.eval_expr i m + 1) n) in H1; omega].\n  generalize (eval_eq m' i n); simpl;\n  case_eq (@E.eval_expr _ T.Bool (i =?= n) m'); intros ? Heq.\n    assert (@E.eval_expr _ T.Bool (i <! n) m' = false) by\n      (apply (leb_correct_conv (E.eval_expr n m') (E.eval_expr i m' + 1));\n      rewrite (nat_eqb_true (eq_sym Heq)), plus_comm; apply lt_n_Sn).\n    rewrite (deno_cond_elim _ _ _ _ m');  case (@E.eval_expr _ T.Bool (i <! n) m'); \n      rewrite deno_nil_elim; rewrite H3; trivial.\n    trivial.\n Qed.\n\n Lemma for_loop_tail_unroll: forall (i : E.expr T.Nat) (n:nat) c E (P:forall k, Mem.t k -> Prop) k (m:Mem.t k) f,\n   (forall k (m:Mem.t k), P _ m ->\n    range (fun m' => E.eval_expr i m' = S (E.eval_expr i m) /\\ P _ m') ([[c]] E m)) ->\n   P _ m ->\n   mu ([[ [ while i <! S n do c ] ]] E m) f  == \n   mu ([[ (while i <! n do c) :: [If i <! S n _then c]   ]] E m) f.\n Proof.\n  intros.\n  rewrite (deno_cons_elim _ (while i <! n do c)), Mlet_simpl.\n  destruct (lt_eq_lt_dec (E.eval_expr i m) n) as [ [H' | H'] | H'].\n    (* case [i < n] *)\n    repeat rewrite (unroll_for_loop_seq_cmd _ _ _ _ _ H H0); [ |\n      rewrite <-(eval_lt m i n); trivial |\n      rewrite <-(eval_lt m i (S n)); transitivity n; [ trivial | apply lt_n_Sn ] ].\n    rewrite <-(minus_Sn_m _ _ (lt_le_weak _ _ H')), seq_cmd_Sn_tail_unfold.\n    apply (range_eq (seq_cmd_range _ _ H _ _ H0)).\n    intros m' [Hm'1 Hm'2]; rewrite <-(le_plus_minus _ _  (lt_le_weak _ _ H')) in Hm'1.\n    unfold restr, EP; replace (@E.eval_expr _ T.Bool (i =?= n) m') with true;\n      [ | symmetry; setoid_rewrite (eval_eq m' i n); rewrite Hm'1; apply nat_eqb_refl ].\n    rewrite (deno_cond_elim _ _ _ _ m').\n    replace (@E.eval_expr _ T.Bool (i <! S n) m') with true;\n     [ | symmetry; rewrite <-(eval_lt m' i (S n)), Hm'1; apply lt_n_Sn ].\n    apply (range_eq (H _ _ Hm'2)); intros m'' [Hm''1 Hm''2].\n    replace (@E.eval_expr _ T.Bool (i =?= S n) m'') with true; trivial.\n      symmetry; setoid_rewrite (eval_eq m'' i (S n)); rewrite Hm''1, Hm'1; apply nat_eqb_refl.\n    (* case [i = n] *)\n    rewrite (unroll_for_loop_seq_cmd _ _ _ _ _ H H0); \n      [ | rewrite <-(eval_lt m i (S n)), H'; apply lt_n_Sn ].\n    rewrite  H', <-(minus_Sn_m _ _ (le_refl _)), minus_diag.\n    rewrite false_while_elim; [ |\n     apply (leb_correct_conv n (E.eval_expr i m + 1)); rewrite H', plus_comm; apply lt_n_Sn ].\n    rewrite deno_cond_elim.\n    replace (@E.eval_expr _ T.Bool (i <! S n) m) with true; [ |\n      symmetry; apply (leb_correct (E.eval_expr i m + 1) (S n)); rewrite H', plus_comm; apply le_refl ].\n    simpl; rewrite (app_nil_r c).\n    apply (range_eq (H _ _ H0)).\n    intros m' [Hm'1 Hm'2].\n    unfold restr, EP; replace (@E.eval_expr _ T.Bool (i =?= S n) m') with true; trivial.\n      symmetry; setoid_rewrite (eval_eq m' i (S n)); rewrite Hm'1, H'; apply nat_eqb_refl.\n    (* case [i > n] *)\n    rewrite (false_while_elim (i <! n));\n      [ | apply (leb_correct_conv n (E.eval_expr i m + 1)); omega ].\n    rewrite deno_while_elim, deno_cond_elim, deno_cond_elim.\n    replace (@E.eval_expr _ T.Bool (i <! S n) m) with false; trivial.\n      symmetry; apply (leb_correct_conv (S n) (E.eval_expr i m + 1)); omega.\n Qed.\n\n Lemma while_range : forall (i: E.expr T.Nat) (n:nat) c E (P:forall k, Mem.t k -> Prop) k (m:Mem.t k),\n   (forall k (m:Mem.t k), P _ m ->\n    range (fun m' => E.eval_expr i m' = S (E.eval_expr i m) /\\ P _ m') ([[c]] E m)) ->\n   P _ m ->\n   E.eval_expr (i<!n) m = true ->\n   range (EP k (i =?= n)) ([[ [ while i <! n do c ] ]] E m).\n Proof.\n  intros.\n  apply range_stable_eq with (drestr ([[seq_cmd c (n - E.eval_expr i m)]] E m) (EP k (i =?= n))).\n    apply eq_distr_intro; intro f;\n     rewrite (unroll_for_loop_seq_cmd _ _ _ _ _ H H0 H1), mu_drestr; trivial.\n    apply drestr_range.\n Qed.\n\n\n (* This is the lemma used to prove the rule for bounded loops.\n    TODO: simplify the proof *)\n Lemma init_for_loop_tail_unroll: forall (i : E.expr T.Nat) (n:nat) c E (P:forall k, Mem.t k -> Prop) k (m:Mem.t k) f,\n   (forall k (m:Mem.t k), P _ m ->\n    range (fun m' => E.eval_expr i m' = S (E.eval_expr i m) /\\ P _ m') ([[c]] E m)) ->\n   P _ m ->\n   E.eval_expr i m = 0%nat ->\n   mu ([[ [ while i <! S n do c ] ]] E m) f  == \n   mu ([[ (while i <! n do c)::c ]] E m) f.\n Proof.\n  intros.\n  rewrite (for_loop_tail_unroll _ _ _ _ _ H H0).\n  rewrite deno_cons_elim, Mlet_simpl, (deno_cons_elim _ _ c), Mlet_simpl.\n  case_eq (nat_eqb n 0); intro Hn.\n    (* case [n=0] *)\n    apply nat_eqb_true in Hn.\n    assert (Hc1: @E.eval_expr _ T.Bool (i <! n) m = false) by\n      (apply (leb_correct_conv n (E.eval_expr i m + 1)); omega).\n    repeat rewrite deno_while_elim, (deno_cond_elim _ (i <! n)), Hc1, deno_nil_elim.\n    assert (Hc: @E.eval_expr _ T.Bool (i <! S n) m = true) by\n      (apply (leb_correct (E.eval_expr i m + 1) (S n)); omega).\n    rewrite deno_cond_elim, Hc; trivial.\n    (* case [n<>0] *)\n    generalize (nat_eqb_spec n 0); rewrite Hn; clear Hn; intro Hn.  \n    assert (Hc: E.eval_expr (i <! n) m = true) by\n      (apply (leb_correct  (E.eval_expr i m + 1) n); omega).\n    refine (range_eq (while_range _ _ _ _ H H0 Hc) _ _ _).\n    unfold EP; intros m' Hm'.\n    setoid_rewrite (eval_eq m' i n) in Hm'; apply nat_eqb_true in Hm';\n      change ( E.eval_expr i m' = n) in Hm'.\n    assert (Hc' : @E.eval_expr _ T.Bool (i <! S n) m' = true) by\n      (apply (leb_correct  (E.eval_expr i m' + 1) (S n)); omega).\n    rewrite deno_cond_elim, Hc'; trivial.\n Qed.\n\n Lemma while_eq_guard_compat_elim: forall (e1 e2 : E.expr T.Bool) c E k (m:Mem.t k) f,\n   (forall (m':Mem.t k), E.eval_expr e1 m' = E.eval_expr e2 m') ->\n   mu ([[ [ while e1 do c ] ]] E m) f == mu ([[ [ while e2 do c ] ]] E m) f.\n Proof.\n  intros.\n  repeat rewrite deno_while_unfold_elim.\n  apply lub_eq_compat.\n  refine (ford_eq_intro _). \n  intro n; generalize n m H; clear H m n.\n  induction n; intros; simpl in *; unfold negP.\n    repeat rewrite (deno_cond_elim _ _ _ _ m).\n    rewrite <-H; case (@E.eval_expr _ T.Bool e1 m).\n      rewrite deno_nil_elim, deno_nil_elim, <-H; trivial.\n      rewrite deno_nil_elim, deno_nil_elim, <-H; trivial.\n\n    repeat rewrite (deno_cond_elim _ _ _ _ m).\n    rewrite <-H; case (@E.eval_expr _ T.Bool e1 m).\n      repeat rewrite deno_app_elim.\n      apply mu_stable_eq; refine (ford_eq_intro _); intros m'.\n      apply (IHn _ H). \n      rewrite deno_nil_elim, deno_nil_elim, <-H; trivial.\n Qed.\n\n\n", "meta": {"author": "EasyCrypt", "repo": "certicrypt", "sha": "7b3cd2fe4a317aec38dfff9eec902b265c575587", "save_path": "github-repos/coq/EasyCrypt-certicrypt", "path": "github-repos/coq/EasyCrypt-certicrypt/certicrypt-7b3cd2fe4a317aec38dfff9eec902b265c575587/Examples/Switching/While_stuff.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.38121955219593834, "lm_q1q2_score": 0.20398997768916488}}
{"text": "Require Import sflib.     \n\nRequire Import Axioms.\nRequire Import Basic.\nRequire Import DataStructure.\nRequire Import Loc.\nRequire Import Language.\n\nRequire Import Time.\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import NPThread.\nRequire Import Configuration.\nRequire Import MsgMapping.\nRequire Import DelaySet.\nRequire Import NPConfiguration.\n\nRequire Import LocalSim.\nRequire Import ww_RF.\n\nRequire Import LibTactics.\nRequire Import ConfigInitLemmas.\nRequire Import CompThreadSteps.\nRequire Import CompAuxDef.\nRequire Import WFConfig.\n\nRequire Import Reordering.\nRequire Import ps_to_np_thread.\nRequire Import np_to_ps_thread.\nRequire Import MsgMapping.\nRequire Import PromiseInjection.\nRequire Import ConsistentLemmas.\nRequire Import ConsistentProp.\n\nRequire Import MemoryProps.\nRequire Import Mem_at_eq_lemmas.\nRequire Import ps_to_np_thread.\nRequire Import np_to_ps_thread.\n\nRequire Import PromiseConsistent.\nRequire Import PromiseInjectionWeak.\nRequire Import promiseCertifiedAux.\n\nLemma memory_closed_addition_rsv\n      mem mem'\n      (MEM_CLOSED: Memory.closed mem)\n      (MEM_LE: Memory.le mem mem')\n      (MORE_RESERVE: \n         forall loc to from msg, Memory.get loc to mem = None ->\n                            Memory.get loc to mem' = Some (from, msg) ->\n                            msg = Message.reserve):\n  Memory.closed mem'.\nProof.\n  inv MEM_CLOSED.\n  econs; eauto. ii.\n  destruct (Memory.get loc to mem) eqn:GET.\n  destruct p.\n  exploit MEM_LE; eauto. ii.\n  rewrite MSG in x. inv x.\n  eapply CLOSED in GET; eauto. des.\n  split; eauto. split; eauto.\n  eapply message_closed_rsv_concrete_prsv; eauto.\n  exploit MORE_RESERVE; eauto. ii; subst.\n  split; eauto. econs.\nQed.\n\nLemma aux_ww_race_to_thrd_ww_race\n      lang lo pc st lc e'\n      (AUX_WW_RACE: ~ aux_ww_race lo pc)\n      (TH: IdentMap.find (Configuration.tid pc) (Configuration.threads pc) = Some (existT _ lang st, lc))\n      (STEPS: rtc (@Thread.tau_step lang lo)\n                  (@Thread.mk lang st lc (Configuration.sc pc) (Configuration.memory pc)) e')\n      (CONFIG_WF: Configuration.wf pc):\n  ~ @thrd_ww_race lang lo e'.\nProof.\n  destruct pc; ss.\n  ii.\n  contradiction AUX_WW_RACE.\n  inv H.\n  assert (STEPS': rtc (Thread.all_step lo)\n                      (Thread.mk lang st lc sc memory) (Thread.mk lang st' lc' sc' mem')).\n  {\n    eapply rtc_compose; [ | eapply STEPS0].\n    eapply Thread_tau_steps_is_all_steps; eauto.\n  }\n  eapply wf_config_rtc_thread_steps_prsv in STEPS'; eauto.\n  econs.\n  eapply TH.\n  eapply Thread_tau_steps_is_all_steps in STEPS.\n  eapply rtc_compose; [eapply STEPS | eapply STEPS0].\n  eauto.\n  split. eauto. eauto.\n  2: eauto.\n  eapply wf_config_to_local_wf with (tid := tid) in STEPS'; eauto.\n  rewrite IdentMap.gss; eauto.\nQed.\n  \nLemma thrd_ww_race_cap_prsv':\n  forall n lang lo st lc sc mem mem_c st' lc' sc' mem_c' stw loc val from to val' R' e_c'\n    (STEPS_TO_RACE: rtcn (Thread.all_step lo) n\n                         (Thread.mk lang st lc sc mem_c) (Thread.mk lang st' lc' sc' mem_c'))\n    (WRITE: Language.step lang (ProgramEvent.write loc val Ordering.plain) st' stw)\n    (RACE_MSG: Memory.get loc to mem_c' = Some (from, Message.concrete val' R'))\n    (NOT_PROM: Memory.get loc to (Local.promises lc') = None)\n    (RACE: Time.lt (View.rlx (TView.cur (Local.tview lc')) loc) to)\n    (FULFILL: rtc (@Thread.tau_step lang lo) (Thread.mk lang st' lc' sc' mem_c') e_c')\n    (BOT: Local.promises (Thread.local e_c') = Memory.bot)\n    (MEM_LE: Memory.le mem mem_c)\n    (MORE_RESERVE: \n       forall loc to from msg, Memory.get loc to mem = None ->\n                          Memory.get loc to mem_c = Some (from, msg) ->\n                          msg = Message.reserve)\n    (PRM_LE: Memory.le (Local.promises lc) mem),\n  exists mem' e',\n    rtc (Thread.all_step lo)\n        (Thread.mk lang st lc sc mem) (Thread.mk lang st' lc' sc' mem') /\\\n    Memory.get loc to mem' = Some (from, Message.concrete val' R') /\\\n    rtc (@Thread.tau_step lang lo) (Thread.mk lang st' lc' sc' mem') e' /\\\n    Local.promises (Thread.local e') = Memory.bot.\nProof.\n  induction n; ii.\n  - inv STEPS_TO_RACE.\n    eapply rtc_rtcn in FULFILL. des.\n    exploit fulfill_cap; eauto. ii; des.\n    do 2 eexists.\n    split. eauto.\n    split. eapply memory_additional_rsv_concrete_prsv; eauto.\n    split. eapply x0. eauto.\n  - inv STEPS_TO_RACE.\n    destruct a2. \n    eapply all_step_cap_prsv in A12; eauto. des.\n    eapply IHn in A23; eauto. des.\n    do 2 eexists.\n    split. eapply Relation_Operators.rt1n_trans; [eapply A12 | eapply A23].\n    split. eauto. \n    split; eauto.\nQed.\n    \nLemma thrd_ww_race_cap_prsv\n      lang lo st lc sc mem mem_c\n      (THRD_WW_RACE_CAP: @thrd_ww_race lang lo (Thread.mk lang st lc sc mem_c))\n      (MEM_LE: Memory.le mem mem_c)\n      (MORE_RESERVE: \n         forall loc to from msg, Memory.get loc to mem = None ->\n                            Memory.get loc to mem_c = Some (from, msg) ->\n                            msg = Message.reserve)\n      (PRM_LE: Memory.le (Local.promises lc) mem):\n  @thrd_ww_race lang lo (Thread.mk lang st lc sc mem).\nProof.\n  inv THRD_WW_RACE_CAP.\n  eapply rtc_rtcn in STEPS. des.\n  exploit thrd_ww_race_cap_prsv'; [eapply STEPS | eapply WRITE | eauto..]; eauto.\n  ii; des.\n  econs; eauto.\nQed.\n\n(** local sim to promise certified preserving **)\nDefinition at_CAP_MEM (mem1 mem2: Memory.t) (lo: Ordering.LocOrdMap) : Memory.t :=\n  fun loc => match (lo loc) with\n           | Ordering.atomic => mem2 loc\n           | Ordering.nonatomic => mem1 loc\n           end.\n\nLemma at_CAP_MEM_mem_le\n      mem mem1 mem2 lo\n      (LE1: Memory.le mem mem1)\n      (LE2: Memory.le mem mem2):\n  Memory.le mem (at_CAP_MEM mem1 mem2 lo).\nProof.\n  unfold Memory.le in *. ii.\n  unfold Memory.get in *. unfold at_CAP_MEM.\n  destruct (lo loc) eqn:Heqe; ss; eauto.\nQed.\n\nLemma Mem_at_eq_at_CAP_MEM\n  lo mem mem0:\n  Mem_at_eq lo mem (at_CAP_MEM mem0 mem lo).\nProof.\n  unfold at_CAP_MEM.\n  unfold Mem_at_eq. ii.\n  unfold Mem_approxEq_loc.\n  unfold Memory.get.\n  split.\n  - ii. split; ii. rewrite H; eauto.\n    des. rewrite H in H0. eauto.\n  - ii. split; ii.\n    rewrite H. eauto.\n    rewrite H in H0; eauto.\nQed.\n\nLemma Mem_at_eq_at_CAP_MEM2\n      lo mem_tgt mem_src mem\n      (MEM_AT_EQ: Mem_at_eq lo mem_tgt mem_src):\n  Mem_at_eq lo mem_tgt (at_CAP_MEM mem mem_src lo).\nProof.\n  unfold Mem_at_eq in *. ii.\n  exploit MEM_AT_EQ; eauto. ii.\n  unfold at_CAP_MEM.\n  clear MEM_AT_EQ.\n  unfold Mem_approxEq_loc in *.\n  unfold Memory.get in *.\n  rewrite H.\n  eauto.\nQed.\n\nLemma memory_concrete_le_at_CAP_MEM\n      mem mem1 mem2 lo\n      (MEM_C_LE1: memory_concrete_le mem mem1)\n      (MEM_C_LE2: memory_concrete_le mem mem2):\n  memory_concrete_le mem (at_CAP_MEM mem1 mem2 lo).\nProof.\n  unfold memory_concrete_le in *. ii.\n  unfold Memory.get in *. unfold at_CAP_MEM.\n  destruct (lo loc); eauto.\nQed.\n\nInductive rel_promises_TBOT {index: Type} (inj: Mapping) (pdset: @DelaySet index) (prm_src: Memory.t) :=\n| rel_promises_intro\n    (SOUND1: forall loc t i,\n        dset_get loc t pdset = Some i ->\n        (exists t' f' val' R',\n            inj loc t = Some t' /\\  Memory.get loc t' prm_src = Some (f', Message.concrete val' R')))\n    (COMPLETE: forall loc f' t' val' R',\n        Memory.get loc t' prm_src = Some (f', Message.concrete val' R') ->\n        (exists t, inj loc t = Some t' /\\ (exists i, dset_get loc t pdset = Some  i))). \n\nDefinition finite_dset {index: Type} (dset: @DelaySet index)\n           (ls: list (Loc.t * Time.t * index)) :=\n  forall loc t i,\n    dset_get loc t dset = Some i ->\n    List.In (loc, t, i) ls.\n\nDefinition no_Dup_ls_dset {index: Type} (dset: @DelaySet index)\n           (ls: list (Loc.t * Time.t * index)) :=\n  forall loc t i,\n    List.In (loc, t, i) ls ->\n    dset_get loc t dset = Some i.\n\nDefinition no_Dup_ls {index: Type} (ls: list (Loc.t * Time.t * index)) :=\n  forall loc t i j,\n    List.In (loc, t, i) ls -> List.In (loc, t, j) ls ->\n    i = j.\n    \nLemma finite_promises_convert_to_list'\n      promises index inj pdset\n      (FINITE_MEM: Memory.finite promises)\n      (REL_PROM_BOT: rel_promises_TBOT inj pdset promises)\n      (MONOTONIC: monotonic_inj inj):\n  exists ls, @finite_dset index pdset ls /\\ @no_Dup_ls_dset index pdset ls.\nProof.\n  unfold Memory.finite in *. des.\n  generalize dependent promises.\n  generalize dependent pdset.\n  generalize dependent inj.\n  generalize dependent index.\n  induction dom; ii.\n  - exists (@nil (Loc.t * Time.t * index)).\n    split.\n    {\n      unfold finite_dset; ii.\n      inv REL_PROM_BOT.\n      eapply SOUND1 in H; eauto; des.\n      eapply FINITE_MEM in H0; eauto.\n    }\n    {\n      unfold no_Dup_ls_dset. ii. ss.\n    }\n  - destruct a. renames t to loc0.\n    destruct (Memory.get loc0 t0 promises) eqn:H.\n    {\n      destruct p as (f0 & msg0).\n      exploit Memory.remove_exists; [eapply H | eauto..]. ii; des.\n      assert(forall loc from to msg,\n                Memory.get loc to mem2 = Some (from, msg) ->\n                List.In (loc, to) dom).\n      {\n        ii.\n        erewrite Memory.remove_o in H0; eauto.\n        des_ifH H0; ss; des; subst; ss.\n        eapply FINITE_MEM in H0; eauto.\n        des; subst; eauto. inv H0; ss.\n        eapply FINITE_MEM in H0; eauto.\n        des; subst; eauto. inv H0; ss.\n      }\n      destruct msg0.\n      {\n        (* concrete message *)\n        inv REL_PROM_BOT.\n        exploit COMPLETE; [eapply H | eauto..]. ii; des.\n        eapply IHdom with (pdset := dset_remove loc0 t pdset)\n                          (inj := inj) in H0; eauto.\n        des.\n        exists ((loc0, t, i) :: ls).\n        split.\n        {\n          unfold finite_dset in *. ii.\n          destruct (dset_get loc t1 (dset_remove loc0 t pdset)) eqn:REMOVE_GET.\n          {\n            lets REMOVE_GET': REMOVE_GET.\n            unfold dset_remove, dset_get in REMOVE_GET'.\n            des_ifH REMOVE_GET'; ss.\n            destruct (Loc.eq_dec t1 t); subst.\n            rewrite DenseOrder.DOMap.grs in REMOVE_GET'; ss.\n            rewrite DenseOrder.DOMap.gro in REMOVE_GET'; eauto.\n            unfold dset_get in H2. rewrite H2 in REMOVE_GET'. inv REMOVE_GET'.\n            eapply H0 in REMOVE_GET. eauto.\n            unfold dset_get in H2; rewrite H2 in REMOVE_GET'. inv REMOVE_GET'.\n            eapply H0 in REMOVE_GET; eauto.\n          }\n          {\n            lets REMOVE_GET': REMOVE_GET.\n            unfold dset_get, dset_remove in REMOVE_GET'.\n            des_ifH REMOVE_GET'; ss; des; subst; ss.\n            destruct (Loc.eq_dec t1 t); subst.\n            rewrite x1 in H2. inv H2; eauto.\n            rewrite DenseOrder.DOMap.gro in REMOVE_GET'; eauto.\n            unfold dset_get in H2. rewrite H2 in REMOVE_GET'. inv REMOVE_GET'.\n            unfold dset_get in H2. rewrite H2 in REMOVE_GET'. ss.\n          }\n        }\n        {\n          unfold no_Dup_ls_dset. ii; ss.\n          des; subst; ss.\n          inv H2; eauto. \n          unfold no_Dup_ls_dset in H1.\n          eapply H1 in H2.\n          clear - H2.\n          unfold dset_get, dset_remove in *.\n          des_ifH H2; subst; ss.\n          destruct (Time.eq_dec t1 t); subst.\n          rewrite DenseOrder.DOMap.grs in H2; ss.\n          rewrite DenseOrder.DOMap.gro in H2; ss.\n        }\n\n        econs; ii.\n        {\n          lets REMOVE_GET: H1.\n          unfold dset_get, dset_remove in REMOVE_GET.\n          des_ifH REMOVE_GET.\n          destruct (Loc.eq_dec t1 t); subst.\n          rewrite DenseOrder.DOMap.grs in REMOVE_GET; ss.\n          rewrite DenseOrder.DOMap.gro in REMOVE_GET; ss.\n          unfold dset_get in *.\n          eapply SOUND1 in REMOVE_GET; eauto. des.\n          exists t' f' val' R'.\n          split; eauto.\n          erewrite Memory.remove_o; eauto.\n          des_if; ss; des; subst; ss.\n          exploit monotonic_inj_implies_disj_mapping;\n            [eapply MONOTONIC | eapply REMOVE_GET | eapply x | eapply n | eauto..]; ii; ss.\n          unfold dset_get in *.\n          eapply SOUND1 in REMOVE_GET; eauto. ii; des.\n          exists t' f' val' R'.\n          split; eauto.\n          erewrite Memory.remove_o; eauto.\n          des_if; ss; des; subst; ss.\n        }\n        {\n          erewrite Memory.remove_o in H1; eauto.\n          des_ifH H1; ss; des; subst; ss.\n          exploit COMPLETE; [eapply H1 | eauto..]. ii; des.\n          eexists. split; eauto.\n          unfold dset_get, dset_remove.\n          des_if; ss; des; subst; ss; eauto.\n          exploit COMPLETE; [eapply H1 | eauto..]. ii; des.\n          eexists. split; eauto.\n          unfold dset_get, dset_remove; ss.\n          des_if; ss; subst; ss; eauto.\n          destruct (Loc.eq_dec t1 t); subst; eauto.\n          rewrite x in x2. inv x2; ss.\n          rewrite DenseOrder.DOMap.gro; eauto.\n        }\n      }\n      {\n        eapply IHdom; eauto.\n        inv REL_PROM_BOT.\n        econs; eauto; ii.\n        eapply SOUND1 in H1; eauto. des.\n        exists t' f' val' R'.\n        split; eauto.\n        erewrite Memory.remove_o; eauto.\n        des_if; ss; des; subst; ss.\n        rewrite H in H2; ss.\n        eapply COMPLETE; eauto.\n        erewrite Memory.remove_o in H1; eauto.\n        des_ifH H1; ss; des; subst; ss; eauto.\n      }\n    }\n    {\n      assert(forall loc from to msg,\n                Memory.get loc to promises = Some (from, msg) ->\n                List.In (loc, to) dom).\n      {\n        ii. exploit FINITE_MEM; [eapply H0 | eauto..]. ii; ss.\n        des; subst; ss. inv x.\n        rewrite H in H0; ss.\n      }\n      eapply IHdom in H0; eauto.\n    }\nQed.\n\nLemma finite_promises_convert_to_list\n      promises index inj pdset\n      (FINITE_MEM: Memory.finite promises)\n      (REL_PROM_BOT: rel_promises_TBOT inj pdset promises)\n      (MONOTONIC: monotonic_inj inj):\n  exists ls, @finite_dset index pdset ls /\\ @no_Dup_ls index ls.\nProof.\n  exploit finite_promises_convert_to_list'; eauto.\n  ii; des.\n  eexists. split; eauto.\n  unfold no_Dup_ls. ii.\n  unfold no_Dup_ls_dset in x1.\n  eapply x1 in H.\n  eapply x1 in H0.\n  rewrite H in H0. inv H0. eauto.\nQed.\n\nLemma dset_init_rel_promises_implies_only_reserve\n      index inj (pdset: @DelaySet index) promises\n      (REL_PROMISES_TBOT: rel_promises_TBOT inj pdset promises)\n      (DSET_SUBSET: dset_subset pdset dset_init):\n  <<RSV: forall loc to from msg,\n      Memory.get loc to promises = Some (from, msg) ->\n      msg = Message.reserve>>.\nProof.\n  ii. destruct msg; eauto.\n  inv REL_PROMISES_TBOT.\n  exploit COMPLETE; eauto. ii; des.\n  eapply DSET_SUBSET in x0.\n  clear - x0. unfold dset_get, dset_init in *.\n  rewrite DenseOrder.DOMap.gempty in x0; ss.\nQed.\n\nLemma only_reservations_fulfill\n      lang lo st lc sc mem\n      (ONLY_RSVs: forall loc to from msg,\n          Memory.get loc to (Local.promises lc) = Some (from, msg) ->\n          msg = Message.reserve)\n      (MEM_FINITE: Memory.finite (Local.promises lc))\n      (MEM_LE: Memory.le (Local.promises lc) mem):\n  exists e_src',\n    rtc (no_scfence_nprm_step lang lo) (Thread.mk lang st lc sc mem) e_src' /\\\n    Local.promises (Thread.local e_src') = Memory.bot.\nProof.\n  unfold Memory.finite in MEM_FINITE. des.\n  generalize dependent st.\n  generalize dependent lc.\n  generalize dependent sc.\n  generalize dependent mem.\n  induction dom; ss; ii.\n  - destruct (classic (exists loc to from msg,\n                          Memory.get loc to (Local.promises lc) = Some (from, msg))).\n    {\n      des. eapply MEM_FINITE in H; ss.\n    }\n    {\n      assert(Local.promises lc = Memory.bot).\n      {\n        eapply Memory.ext; ii.\n        rewrite Memory.bot_get.\n        destruct (Memory.get loc ts (Local.promises lc)) eqn:Heqe; eauto.\n        destruct p.\n        contradiction H; eauto.\n      }\n      eexists. split; eauto.\n    }\n  - destruct a. rename t into loc0.\n    destruct (Memory.get loc0 t0 (Local.promises lc)) eqn:GET.\n    {\n      destruct p.\n      exploit ONLY_RSVs; [eapply GET | eauto..]. ii; subst.\n      exploit Memory.remove_exists; [eapply GET | eauto..]. ii; des.\n      exploit MEM_LE; [eapply GET | eauto..]. ii.\n      exploit Memory.remove_exists; [eapply x | eauto..]. ii; des.\n      assert(MEM_LE': \n              Memory.le (Local.promises (Local.mk (Local.tview lc) mem2)) mem0).\n      {\n        ss. eapply memory_remove_le_rsv_prsv.\n        eapply MEM_LE. eapply x0. eapply x2.\n      }\n      eapply IHdom in MEM_LE'; eauto; ss.\n      instantiate (1 := sc) in MEM_LE'.\n      instantiate (1 := st) in MEM_LE'.\n      destruct lc; ss. des.\n      eexists. split.\n      eapply Relation_Operators.rt1n_trans.\n      eapply no_scfence_nprm_step_intro2; eauto.\n      econs. econs; ss. eapply Memory.promise_cancel; eauto. ss.\n      eapply MEM_LE'. eauto.\n      ii.\n      erewrite Memory.remove_o in H; eauto.\n      des_ifH H; ss; des; subst; ss; eauto.\n      ii.\n      erewrite Memory.remove_o in GET0; eauto.\n      des_ifH GET0; ss; des; subst; ss; eauto.\n      exploit MEM_FINITE; [eapply GET0 | eauto..].\n      ii; des; eauto.\n      inv x1; ss.\n      exploit MEM_FINITE; [eapply GET0 | eauto..].\n      ii; des; eauto.\n      inv x1; ss.\n    }\n    {\n      eapply IHdom in MEM_LE; eauto.\n      ii.\n      exploit MEM_FINITE; [eapply GET0 | eauto..].\n      ii; des; eauto.\n      inv x. rewrite GET in GET0; ss.\n    }\nQed.\n\nLemma write_not_abort_progress\n      lang loc val st st' lc sc mem lo\n      (NA_WRITE: Language.step lang (ProgramEvent.write loc val Ordering.plain) st st')\n      (ORD_MATCH: lo loc = Ordering.nonatomic)\n      (LOCAL_WF: Local.wf lc mem)\n      (MEM_CLOSED: Memory.closed mem)\n      (BOT: Local.promises lc = Memory.bot):\n  exists lc' mem' from to,\n    Local.write_step lc sc mem loc from to val None None Ordering.plain lc' sc mem' Memory.op_kind_add lo.\nProof.\n  assert (WRITE_ADD: exists mem',\n             Memory.write (Local.promises lc) mem loc\n                          (Memory.max_ts loc mem) (Time.incr (Memory.max_ts loc mem)) val\n                          None (Local.promises lc) mem' Memory.op_kind_add).\n  {\n    eapply write_succeed_valid; eauto.\n    inv LOCAL_WF; eauto.\n    ii. inv COVER. inv ITV; ss.\n    inv H; ss.\n    exploit Memory.max_ts_spec; [eapply GET | eauto..]. ii; des.\n    cut (Time.le t (Memory.max_ts loc mem)). ii.\n    clear - FROM0 H. auto_solve_time_rel.\n    clear - TO MAX. auto_solve_time_rel.\n    ss. unfold TimeMap.bot; eauto.\n    eapply Time.bot_spec; eauto.\n    auto_solve_time_rel.\n    ii. inv H. des.\n    exploit Memory.max_ts_spec; [eapply GET | eauto..]. ii; des.\n    exploit Memory.get_ts; [eapply GET | eauto..]. ii; des; subst.\n    rewrite <- x1 in MAX.\n    cut (Time.lt (Memory.max_ts loc mem) (Time.incr (Memory.max_ts loc mem))). ii.\n    clear - MAX H.\n    auto_solve_time_rel.\n    auto_solve_time_rel.\n    cut (Time.lt (Time.incr (Memory.max_ts loc mem)) (Memory.max_ts loc mem)).\n    ii. clear - H.\n    cut (Time.lt (Memory.max_ts loc mem) (Time.incr (Memory.max_ts loc mem))).\n    ii. auto_solve_time_rel.\n    ii. clear - x0. auto_solve_time_rel.\n    auto_solve_time_rel.\n    auto_solve_time_rel.\n    econs; eauto.\n  }\n  des. eexists.\n  exists mem' (Memory.max_ts loc mem) (Time.incr (Memory.max_ts loc mem)).\n  econs; eauto.\n  rewrite ORD_MATCH. ss.\n  econs; eauto.\n  inv LOCAL_WF.\n  inv TVIEW_CLOSED.\n  inv CUR.\n  unfold Memory.closed_timemap in RLX.\n  specialize (RLX loc). des.\n  exploit Memory.max_ts_spec; [eapply RLX | eauto..]. ii; des.\n  clear - MAX.\n  cut (Time.lt (Memory.max_ts loc mem) (Time.incr (Memory.max_ts loc mem))). ii.\n  auto_solve_time_rel.\n  auto_solve_time_rel.\n  ii; ss.\nQed.\n\nLemma state_in_not_abort_progress\n      lang pe st st' lo lc mem sc\n      (STATE_STEP: Language.step lang pe st st')\n      (NA_STEP_T: state_in_step pe)\n      (NOT_ABORT1: ~ (exists st' x o v,\n                         (Language.step lang (ProgramEvent.read x v o) st st' \\/\n                          Language.step lang (ProgramEvent.write x v o) st st') /\\\n                         ~ Ordering.mem_ord_match o (lo x)))\n      (NOT_ABORT2: ~ (exists st2 x vr vw or ow,\n                         Language.step lang (ProgramEvent.update x vr vw or ow)\n                                       st st2 /\\ lo x = Ordering.nonatomic))\n      (LOCAL_WF: Local.wf lc mem)\n      (MEM_CLOSED: Memory.closed mem)\n      (BOT: Local.promises lc = Memory.bot):\n  (pe = ProgramEvent.silent) \\/\n  (exists releasedr loc to val lc' st2,\n      Language.step lang (ProgramEvent.read loc val Ordering.plain) st st2 /\\ \n      Local.read_step lc mem loc to val releasedr Ordering.plain lc' lo)\n  \\/\n  (exists lc' mem' from to loc val st2,\n      Language.step lang (ProgramEvent.write loc val Ordering.plain) st st2 /\\\n      Local.write_step lc sc mem loc from to val None None Ordering.plain lc' sc mem' Memory.op_kind_add lo).\nProof.\n  destruct pe; ss; eauto.\n  - (* non-atomic read *)\n    right. left. destruct ord; ss.\n    inv LOCAL_WF. inv TVIEW_CLOSED. inv CUR.\n    unfold Memory.closed_timemap in PLN.\n    specialize (PLN loc). des.\n    assert (NA_LOC: lo loc = Ordering.nonatomic).\n    {\n      destruct (lo loc) eqn:TYPE_LOC; eauto.\n      contradiction NOT_ABORT1.\n      do 4 eexists. split. left. eauto.\n      rewrite TYPE_LOC. ii; ss. des; ss.\n    }\n    exploit (Language.read_abitrary_1 lang); [eapply STATE_STEP | eauto..].\n    instantiate (1 := val0).\n    ii; des.\n    {\n      exists released loc (View.pln (TView.cur (Local.tview lc)) loc) val0. do 2 eexists.\n      split. eapply x0.\n      econs; eauto.\n      rewrite NA_LOC. ss.\n      econs; eauto.\n      eapply Time.le_lteq; eauto.\n      ii; ss.\n    }\n    {\n      contradiction NOT_ABORT2.\n      do 6 eexists.\n      eauto.\n    }\n  - (* non atomic write *)\n    destruct ord; ss.\n    right. right.\n    assert (NA_LOC: lo loc = Ordering.nonatomic).\n    {\n      destruct (lo loc) eqn:TYPE_LOC; eauto.\n      contradiction NOT_ABORT1.\n      do 4 eexists.\n      split.\n      right. eauto.\n      rewrite TYPE_LOC. ii; ss. des; ss.\n    }\n    exploit write_not_abort_progress; eauto.\n    instantiate (1 := sc). ii; des.\n    exists lc' mem' from to loc val. exists st'.\n    split; eauto.\nQed. \n\nLemma state_in_not_abort_thread_step\n      lang pe st st' lo lc mem sc\n      (STATE_STEP: Language.step lang pe st st')\n      (NA_STEP_T: state_in_step pe)\n      (NOT_ABORT1: ~ (exists st' x o v,\n                         (Language.step lang (ProgramEvent.read x v o) st st' \\/\n                          Language.step lang (ProgramEvent.write x v o) st st') /\\\n                         ~ Ordering.mem_ord_match o (lo x)))\n      (NOT_ABORT2: ~ (exists st2 x vr vw or ow,\n                         Language.step lang (ProgramEvent.update x vr vw or ow)\n                                       st st2 /\\ lo x = Ordering.nonatomic))\n      (LOCAL_WF: Local.wf lc mem)\n      (MEM_CLOSED: Memory.closed mem)\n      (BOT: Local.promises lc = Memory.bot):\n  exists te e', Thread.step lo true te (Thread.mk lang st lc sc mem) e' /\\\n           ThreadEvent.is_na_step te /\\ (Local.promises lc) = (Local.promises (Thread.local e')).\nProof.\n  exploit state_in_not_abort_progress; eauto. ii; des; subst.\n  - do 2 eexists.\n    split.\n    eapply Thread.step_program.\n    econs.\n    Focus 2.\n    eapply Local.step_silent. ss. eauto.\n    eauto.\n  - do 2 eexists.\n    split.\n    eapply Thread.step_program.\n    econs.\n    Focus 2.\n    eapply Local.step_read. ss. eauto.\n    ss. eauto.\n    ss. split; eauto.\n    inv x1; eauto.\n  - do 2 eexists.\n    split.\n    eapply Thread.step_program.\n    econs.\n    Focus 2.\n    eapply Local.step_write. ss. eauto.\n    ss. eauto.\n    split; eauto; ss.\n    inv x1; ss. inv WRITE.\n    inv PROMISE.\n    eapply MemoryMerge.MemoryMerge.add_remove; [eapply PROMISES | eapply REMOVE].\nQed.\n    \nFixpoint cons_ols {index: Type} (pdset: @DelaySet index) (ls: list (Loc.t * Time.t * index)) :=\n  match ls with\n  | nil => nil\n  | (loc, to, i) :: ls' =>\n    match dset_get loc to pdset with\n    | None => None :: cons_ols pdset ls'\n    | Some j => Some (loc, to, j) :: cons_ols pdset ls'\n    end\n  end.\n\nLemma na_steps_promises_fulfill':\n  forall n lang e e' lo \n    (NA_STEPS: rtcn (@Thread.na_step lang lo) n e e'),\n    (forall loc to from' val R,\n        Memory.get loc to (Local.promises (Thread.local e')) = Some (from', Message.concrete val R) ->\n        exists from, Memory.get loc to (Local.promises (Thread.local e)) = Some (from, Message.concrete val R)).\nProof.\n  induction n; ii.\n  - inv NA_STEPS; eauto.\n  - inv NA_STEPS.\n    eapply IHn in A23; eauto.\n    clear - A12 A23.\n    inv A12; eauto.\n    + inv STEP; ss.\n      inv LOCAL. inv LOCAL0; ss.\n    + inv STEP; ss.\n      inv LOCAL; ss.\n      inv LOCAL0; ss.\n      inv WRITE. des.\n      inv PROMISE; ss.\n      {\n        (* add *)\n        erewrite Memory.remove_o in A23; eauto.\n        des_ifH A23; ss; eauto.\n        erewrite Memory.add_o in A23; eauto.\n        des_ifH A23; ss; eauto.\n        des; subst; ss.\n      }\n      {\n        (* split *)\n        des; subst. inv RESERVE.\n        erewrite Memory.remove_o in A23; eauto.\n        des_ifH A23; ss; eauto.\n        erewrite Memory.split_o in A23; eauto.\n        des_ifH A23; ss; eauto.\n        des; subst; ss; eauto.\n        des_ifH A23; ss; eauto.\n        des; subst; ss; eauto.\n        inv A23.\n        exploit Memory.split_get0; [eapply PROMISES | eauto..]. ii; des.\n        eauto.\n      }\n      {\n        (* lower *)\n        des; subst.\n        erewrite Memory.remove_o in A23; eauto.\n        des_ifH A23; eauto; ss.\n        erewrite Memory.lower_o in A23; eauto.\n        des_ifH A23; eauto; ss.\n        des; subst; ss.\n      }\n    + des. inv STEP; ss. inv LOCAL. eauto.\nQed.\n      \nLemma na_steps_promises_fulfill:\n  forall lang e e' lo \n    (NA_STEPS: rtc (@Thread.na_step lang lo) e e'),\n    (forall loc to from' val R,\n        Memory.get loc to (Local.promises (Thread.local e')) = Some (from', Message.concrete val R) ->\n        exists from, Memory.get loc to (Local.promises (Thread.local e)) = Some (from, Message.concrete val R)).\nProof.\n  ii.\n  eapply rtc_rtcn in NA_STEPS. des.\n  eapply na_steps_promises_fulfill'; eauto.\nQed.\n\nLemma pdset_less\n      index (index_order: index -> index -> Prop) dset dset1 dset2 dset2' pdset pdset' te\n      (DSET_SUBSET: dset_subset pdset dset)\n      (DSET_UPD: dset_after_na_step te dset dset1)\n      (DSET_SUBSET1: dset_subset dset2 dset1)\n      (REDUCE_DSET: reduce_dset index_order dset2' dset2)\n      (DSET_SUBSET': dset_subset pdset' dset2'):\n  (forall loc to j,\n      dset_get loc to pdset' = Some j ->\n      dset_get loc to pdset = None \\/\n      (exists i, dset_get loc to pdset = Some i /\\ index_order j i)).\nProof.\n  ii.\n  destruct (dset_get loc to pdset) eqn:DSET_GET; eauto.\n  unfold dset_subset in *.\n  exploit DSET_SUBSET; [eapply DSET_GET | eauto..]. ii.\n  exploit DSET_SUBSET'; [eapply H | eauto..]. ii.\n  inv REDUCE_DSET.\n  exploit REDUCE; [eapply x0 | eauto..]. ii; des.\n  right. eexists. split; eauto.\n  inv DSET_UPD.\n  - eapply DSET_SUBSET1 in x2.\n    eapply dset_get_proper in x2. des.\n    rewrite x in x2; ss.\n    rewrite x in x2. inv x2; ss.\n  - eapply DSET_SUBSET1 in x2.\n    rewrite x in x2. inv x2. eauto.\nQed.\n\nLemma remove_none_empty_all_none:\n  forall A ols (x: option A)\n    (REMOVE_NONE: remove_none ols = nil)\n    (LIST_IN: List.In x ols),\n    x = None.\nProof.\n  induction ols; ss. ii.\n  destruct a; ss; eauto.\n  des; eauto.\nQed.\n\nLemma remove_none_empty_implies_pdset_init:\n  forall index ls (pdset: @DelaySet index)\n    (REMOVE_NONE: remove_none (cons_ols pdset ls) = nil)\n    (IN: forall loc t j, dset_get loc t pdset = Some j -> exists i, List.In (loc, t, i) ls),\n    pdset = dset_init.\nProof.\n  induction ls; ii; ss.\n  - eapply functional_extensionality; eauto. ii.\n    eapply DenseOrder.DOMap.eq_leibniz.\n    unfold DenseOrder.DOMap.Equal. ii.\n    unfold dset_init.\n    rewrite DenseOrder.DOMap.gempty.\n    destruct (DenseOrder.DOMap.find y (pdset x)) eqn:GET; eauto.\n    eapply IN in GET. des. ss.\n  - destruct a. destruct p.\n    destruct (dset_get t t0 pdset) eqn:GET; ss.\n    eapply IHls in REMOVE_NONE; eauto.\n    ii.\n    exploit IN; [eapply H | eauto..]. ii; des; eauto.\n    inv x.\n    rewrite GET in H. ss.\nQed.\n\nLemma lt_dset_cons_ols':\n  forall index ls (pdset0: @DelaySet index) (index_order: index -> index -> Prop)\n    (NO_DUP_DSET: no_Dup_ls ls)\n    (PROM_LESS: forall loc t i j,\n        List.In (loc, t, i) ls -> dset_get loc t pdset0 = Some j -> index_order j i)\n    (NOT_NIL: ls <> nil),\n    lt_dset index_order (cons_ols pdset0 ls) ls.\nProof.\n  induction ls; ii; ss.\n  destruct a. destruct p.\n  destruct (dset_get t t0 pdset0) eqn:DSET_GET; ss; eauto.\n  {\n    lets PROM_LESS': PROM_LESS.\n    specialize (PROM_LESS t t0 i i0).\n    eapply PROM_LESS in DSET_GET; eauto.\n    destruct ls.\n    {\n      ss.\n      eapply lt_dset_some_nil; eauto.\n    }\n    {\n      eapply lt_dset_some.\n      eauto.\n      eapply IHls; eauto.\n      clear - NO_DUP_DSET.\n      unfold no_Dup_ls in *. ii; ss.\n      des; subst; ss.\n      inv H0; eauto.\n      specialize (NO_DUP_DSET loc t1 j i0).\n      exploit NO_DUP_DSET; eauto.\n      specialize (NO_DUP_DSET loc t1 i0 j).\n      exploit NO_DUP_DSET; eauto.\n      specialize (NO_DUP_DSET loc t1 i0 j).\n      exploit NO_DUP_DSET; eauto.\n      ii; ss.\n    }\n  }\n  {\n    destruct ls.\n    ss. eapply lt_dset_none_nil.\n    eapply lt_dset_none.\n    eapply IHls; eauto.\n    clear - NO_DUP_DSET.\n    unfold no_Dup_ls in *; ii.\n    ss. des; subst.\n    inv H0. eauto.\n    specialize (NO_DUP_DSET loc t1 j i0).\n    exploit NO_DUP_DSET; eauto.\n    specialize (NO_DUP_DSET loc t1 i0 j).\n    exploit NO_DUP_DSET; eauto.\n    specialize (NO_DUP_DSET loc t1 i0 j).\n    exploit NO_DUP_DSET; eauto.\n    ii; ss.\n  }\nQed.\n  \nLemma lt_dset_cons_ols:\n  forall index ls (pdset pdset0: @DelaySet index) (index_order: index -> index -> Prop)\n    (FINITE_DSET: finite_dset pdset ls)\n    (NO_DUP_DSET: no_Dup_ls ls)\n    (PROM_LESS: forall loc to j,\n        dset_get loc to pdset0 = Some j ->\n        (exists i, dset_get loc to pdset = Some i /\\ index_order j i))\n    (NOT_NIL: ls <> nil),\n    lt_dset index_order (cons_ols pdset0 ls) ls.\nProof.\n  ii.\n  eapply lt_dset_cons_ols'; eauto.\n  ii.\n  exploit PROM_LESS; [eapply H0 | eauto..]. ii; des.\n  unfold finite_dset in FINITE_DSET.\n  exploit FINITE_DSET; [eapply x | eauto..]. ii.\n  unfold no_Dup_ls in NO_DUP_DSET.\n  exploit NO_DUP_DSET; [eapply H | eapply x1 | eauto..]. ii; subst.\n  eauto.\nQed.\n\nLemma List_in_remove_none_cons_ols:\n  forall index ls (pdset: @DelaySet index) loc to i\n    (LIST_IN: List.In (loc, to, i) (remove_none (cons_ols pdset ls))),\n    dset_get loc to pdset = Some i.\nProof.\n  induction ls; ii; ss.\n  destruct a. destruct p.\n  destruct (dset_get t t0 pdset) eqn:GET; eauto.\n  ss. des.\n  inv LIST_IN; eauto.\n  eauto.\nQed.\n\nLemma no_Dup_ls_remove_none_cons_ols\n      index ls (pdset: @DelaySet index):\n  no_Dup_ls (remove_none (cons_ols pdset ls)).\nProof.\n  unfold no_Dup_ls. ii.\n  eapply List_in_remove_none_cons_ols in H.\n  eapply List_in_remove_none_cons_ols in H0.\n  rewrite H in H0. inv H0; eauto.\nQed.\n\nLemma finite_dset_remove_none_cons_ols':\n  forall index ls (pdset: @DelaySet index) loc to i\n    (GET: dset_get loc to pdset = Some i),\n    List.In (loc, to, i) (remove_none (cons_ols pdset ls)) \\/ ~ (exists j, List.In (loc, to, j) ls).\nProof.\n  induction ls; ii; ss.\n  right. ii. des. ss.\n  destruct a. destruct p.\n  destruct (dset_get t t0 pdset) eqn:DSET_GET; ss.\n  {\n    exploit IHls; [eapply GET | eauto..]. ii; des.\n    {\n      left. right. eauto.\n    }\n    {\n      destruct (Loc.eq_dec t loc); subst.\n      destruct (Time.eq_dec to t0); subst.\n      rewrite DSET_GET in GET. inv GET.\n      left. eauto.\n      right. ii. exploit x; eauto. des. inv H; ss.\n      eauto.\n      right.\n      ii.\n      contradiction x.\n      des. inv H; ss. eauto.\n    }\n  }\n  {\n    exploit IHls; [eapply GET | eauto..]. ii; des; eauto.\n    right. ii.\n    contradiction x. des.\n    inv H. rewrite GET in DSET_GET. ss.\n    eauto.\n  }\nQed.\n  \nLemma finite_dset_remove_none_cons_ols\n      index (pdset: @DelaySet index) ls\n      (FINITE_DSET: forall loc to i,\n          dset_get loc to pdset = Some i ->\n          exists j, List.In (loc, to, j) ls):\n  finite_dset pdset (remove_none (cons_ols pdset ls)).\nProof.\n  unfold finite_dset. ii.\n  exploit finite_dset_remove_none_cons_ols'; [eapply H | eauto..].\n  instantiate (1 := ls).\n  ii; des; eauto.\n  contradiction x0; eauto.\nQed.\n    \nLemma lsim_ensures_promise_fulfill_T_BOT'\n      index (index_order: index -> index -> Prop) pdset dset ls lang I lo\n      st_tgt lc_tgt sc_tgt mem_tgt\n      st_src lc_src sc_src mem_src sc_srcc mem_srcc\n      b inj\n      (ACC_LT_DSET: Acc_lt_dset index_order ls)\n      (REL_PROM_TBOT: rel_promises_TBOT inj pdset (Local.promises lc_src))\n      (SUBSET: dset_subset pdset dset)\n      (FINITE_DSET: finite_dset pdset ls)\n      (NO_DUP_DSET: no_Dup_ls ls)\n      (MONOTONIC_INJ: monotonic_inj inj)\n      (WELL_FOUND: well_founded index_order)\n      (T_BOT: Local.promises lc_tgt = Memory.bot)\n      (LOCAL_SIM: @local_sim_state index index_order lang I lo inj dset b\n                                   (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                                   (Thread.mk lang st_src lc_src sc_src mem_src))\n      (SAFE_S: ~ (exists e_src', rtc (@Thread.tau_step lang lo)\n                                (Thread.mk lang st_src lc_src sc_src mem_src) e_src' /\\\n                            Thread.is_abort e_src' lo))\n      (NA_SAME: forall loc, lo loc = Ordering.nonatomic -> mem_src loc = mem_srcc loc)\n      (LOCAL_WF_S: Local.wf lc_src mem_src)\n      (MEM_CLOSED_S: Memory.closed mem_src)\n      (MEM_LE_S: Memory.le mem_src mem_srcc)\n      (LOCAL_WF_T: Local.wf lc_tgt mem_tgt)\n      (MEM_CLOSED_T: Memory.closed mem_tgt):\n  exists e_srcc',\n    rtc (@Thread.nprm_step lang lo)\n        (Thread.mk lang st_src lc_src sc_srcc mem_srcc) e_srcc' /\\\n      Local.promises (Thread.local e_srcc') = Memory.bot.\nProof.\n  generalize dependent pdset.\n  generalize dependent dset.\n  generalize dependent st_tgt.\n  generalize dependent lc_tgt.\n  generalize dependent sc_tgt.\n  generalize dependent mem_tgt.\n  generalize dependent st_src.\n  generalize dependent lc_src.\n  generalize dependent sc_src.\n  generalize dependent mem_src.\n  generalize dependent mem_srcc.\n  generalize dependent sc_srcc.\n  generalize dependent b.\n  induction ACC_LT_DSET; ii.\n  assert(TGT_PROM_CONS: Local.promise_consistent lc_tgt).\n  {\n    unfold Local.promise_consistent. rewrite T_BOT. ii.\n    rewrite Memory.bot_get in PROMISE. ss.\n  }\n  assert(NOT_ABORT_T: \n          ~ Thread.is_abort (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt) lo).\n  {\n    introv NOT_ABORT_T.\n    inv LOCAL_SIM; ss.\n    contradiction SAFE_S.\n    eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n    eauto.\n    clear THRD_STEP RELY_STEP THRD_DONE.\n    exploit THRD_ABORT; eauto. ii; des.\n    contradiction SAFE_S.\n    eapply na_steps_is_tau_steps in x; eauto.\n  }\n  unfold Thread.is_abort in NOT_ABORT_T; ss.\n  eapply not_and_or in NOT_ABORT_T.\n  destruct NOT_ABORT_T as [NOT_ABORT_T | NOT_ABORT_T].\n  {\n    clear - T_BOT NOT_ABORT_T.\n    contradiction NOT_ABORT_T.\n    unfold Local.promise_consistent. ii.\n    rewrite T_BOT in PROMISE.\n    rewrite Memory.bot_get in PROMISE; ss.\n  }\n  eapply not_or_and in NOT_ABORT_T. des.\n  eapply NNPP in NOT_ABORT_T. des.\n  {\n    (* target thread takes a step *)\n    exploit state_in_or_out; eauto. instantiate (1 := e).\n    introv AT_OR_NA_STEP.\n    destruct AT_OR_NA_STEP as [AT_STEP_T | NA_STEP_T].\n    {\n      inv LOCAL_SIM; ss.\n      contradiction SAFE_S.\n      eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; eauto.\n      clear THRD_STEP RELY_STEP THRD_DONE THRD_ABORT.\n      inv STEP_INV. \n      exploit DSET_EMP; eauto. ii; subst.\n      assert(ONLY_RSVs: forall loc to from msg,\n                Memory.get loc to (Local.promises lc_src) = Some (from, msg) ->\n                msg = Message.reserve).\n      {\n        eapply dset_init_rel_promises_implies_only_reserve; eauto.\n      }\n      exploit only_reservations_fulfill; eauto.\n      Focus 3. ii. des. eexists. split. 2: eapply x1.\n      eapply no_scfence_nprm_steps_is_nprm_steps; eauto.      \n      inv LOCAL_WF_S; ss; eauto.\n      inv LOCAL_WF_S; ss; eauto.      \n      clear - MEM_LE_S PROMISES.\n      unfold Memory.le in *; ii.\n      eapply PROMISES in LHS. eauto.\n    }\n    {\n      eapply not_or_and in NOT_ABORT_T0. des.\n      exploit state_in_not_abort_thread_step; eauto.\n      instantiate (1 := sc_tgt).\n      introv TGT_THREAD_STEP.\n      destruct TGT_THREAD_STEP as (te & e_tgt & TGT_THREAD_STEP & IS_NA_STEP & PROM_EQ).\n      destruct e_tgt.\n      renames state to st_tgt', local to lc_tgt', sc to sc_tgt', memory to mem_tgt'.\n      inv LOCAL_SIM; ss.\n      (* abort *)\n      contradiction SAFE_S.\n      eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n      eexists.\n      split. eapply NP_STEPS. eauto.\n      (* not abort *)\n      clear RELY_STEP THRD_DONE THRD_ABORT.\n      assert (TGT_NA_STEP: @Thread.na_step lang lo\n                                           (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                                           (Thread.mk lang st_tgt' lc_tgt' sc_tgt' mem_tgt')).\n      {\n        clear - TGT_THREAD_STEP IS_NA_STEP.\n        destruct te; ss.\n        inv TGT_THREAD_STEP. inv STEP.\n        eapply Thread.na_tau_step_intro; eauto.\n        destruct ord; ss.\n        inv TGT_THREAD_STEP. inv STEP.\n        eapply Thread.na_plain_read_step_intro; eauto.\n        destruct ord; ss.\n        inv TGT_THREAD_STEP. inv STEP.\n        eapply Thread.na_plain_write_step_intro; eauto.\n      }\n      assert (TGT_PROM_CONS': Local.promise_consistent lc_tgt').\n      {\n        unfold Local.promise_consistent.\n        rewrite <- PROM_EQ. rewrite T_BOT.\n        ii. rewrite Memory.bot_get in PROMISE; ss.\n      }\n      exploit THRD_STEP.\n      eapply TGT_THREAD_STEP. \n      ii. clear THRD_STEP. des. clear x x1 x2.\n      exploit x0; eauto. clear x0. ii; des.\n      lets LOCAL_SIM_STATE': x2.\n      inv LOCAL_SIM_STATE'; ss.\n      contradiction SAFE_S.\n      eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss.\n      eapply na_steps_dset_to_NPThread_tau_steps in x0.\n      instantiate (1 := true) in x0. des.\n      eapply NPAuxThread_tau_steps_2_Thread_tau_steps in x0; ss.\n      exists e_src. split; eauto.\n      eapply rtc_compose; [eapply x0 | eapply NP_STEPS].\n      clear THRD_STEP RELY_STEP THRD_DONE THRD_ABORT.\n      inv STEP_INV0. des.\n      ss. rewrite <- PROM_EQ in REL_PROMISES0. rewrite T_BOT in REL_PROMISES0.\n      assert(REL_PROM_TBOT': rel_promises_TBOT inj pdset0 (Local.promises lc_src0)).\n      {\n        clear - REL_PROMISES0. inv REL_PROMISES0.\n        econs; eauto. ii.\n        eapply COMPLETE in H; eauto. des; eauto.\n        rewrite Memory.bot_get in H0; ss.\n      }\n      assert(LESS_PROMISES: forall loc from0 to val R,\n                Memory.get loc to (Local.promises lc_src0) = Some (from0, Message.concrete val R) ->\n                exists from, Memory.get loc to (Local.promises lc_src) = Some (from, Message.concrete val R)).\n      {\n        clear - x0.\n        eapply na_steps_dset_to_Thread_na_steps in x0. ii.\n        eapply na_steps_promises_fulfill in x0; ss; eauto.\n      } \n      assert(PDSET_LESS: \n               forall loc to j,\n                 dset_get loc to pdset0 = Some j ->\n                 (dset_get loc to pdset = None \\/ (exists i, dset_get loc to pdset = Some i /\\ index_order j i))).\n      {\n        ii. eapply na_steps_dset_subset in x0.\n        exploit pdset_less;\n          [eapply SUBSET | eapply x | eapply x0 | eapply x1 | eapply REL_PROMISES | eauto..]; eauto.\n      }\n      assert(PDSET_LESS0: \n               forall loc to j,\n                 dset_get loc to pdset0 = Some j -> exists i, dset_get loc to pdset = Some i /\\ index_order j i).\n      {\n        clear - REL_PROM_TBOT REL_PROM_TBOT' LESS_PROMISES PDSET_LESS MONOTONIC_INJ. ii.\n        exploit PDSET_LESS; [eapply H | eauto..]. ii; des; ss; eauto.\n        inv REL_PROM_TBOT. inv REL_PROM_TBOT'.\n        eapply SOUND0 in H. des.\n        eapply LESS_PROMISES in H0. des.\n        eapply COMPLETE in H0. des.\n        destruct (Time.eq_dec to t); subst; eauto.\n        rewrite H1 in x. ss.\n        exploit monotonic_inj_implies_disj_mapping;\n          [eapply MONOTONIC_INJ | eapply H | eapply H0 | eapply n | eauto..].\n        ii; ss.\n      }\n      eapply na_steps_dset_to_Thread_na_steps in x0.\n      lets NA_STEPS_S: x0.\n      eapply na_steps_na_loc_same_prsv in x0; eauto.\n      des.\n      exploit Thread_na_steps_is_no_scfence_nprm_steps; [eapply NA_STEP_CAP | eauto].\n      ii.\n      eapply no_scfence_nprm_steps_not_care_sc with (sc0 := sc_srcc) in x3.\n      destruct (remove_none (cons_ols pdset0 ls)) eqn: REMOVE_NONE.\n      {\n        assert(PDSET_EMPTY: pdset0 = dset_init).\n        {\n          eapply remove_none_empty_implies_pdset_init; eauto.\n          ii. clear - FINITE_DSET REL_PROM_TBOT REL_PROM_TBOT' H0 LESS_PROMISES MONOTONIC_INJ.\n          inv REL_PROM_TBOT. inv REL_PROM_TBOT'.\n          exploit SOUND0; [eapply H0 | eauto..]. ii; des.\n          exploit LESS_PROMISES; [eapply x0 | eauto..]. ii; des.\n          exploit COMPLETE; [eapply x1 | eauto..]. ii; des.\n          destruct (Time.eq_dec t t0); subst.\n          unfold finite_dset in FINITE_DSET.\n          eapply FINITE_DSET in x3; eauto.\n          exploit monotonic_inj_implies_disj_mapping;\n            [eapply MONOTONIC_INJ | eapply x | eapply x2 | eauto..]. ii; ss.\n        }\n        subst.\n        assert(ONLY_RSVs: forall loc to from msg,\n                  Memory.get loc to (Local.promises lc_src0) = Some (from, msg) ->\n                  msg = Message.reserve).\n        {\n          eapply dset_init_rel_promises_implies_only_reserve; eauto.\n          unfold dset_subset. ii; eauto.\n        }\n        assert(LOCAL_WF_T': Local.wf lc_src0 mem_src0).\n        {\n          eapply Thread_na_steps_is_no_scfence_nprm_steps in NA_STEPS_S.\n          eapply rtc_rtcn in NA_STEPS_S. des.\n          eapply no_scfence_nprm_steps_prsv_local_wf in NA_STEPS_S; eauto.\n        }\n        eapply only_reservations_fulfill in ONLY_RSVs.\n        destruct ONLY_RSVs as (e_src' & NPRM_STEPS & T_BOT').\n        instantiate (1 := mem_c') in NPRM_STEPS.\n        instantiate (1 := sc_srcc) in NPRM_STEPS.\n        instantiate (1 := st_src0) in NPRM_STEPS.\n        instantiate (1 := lo) in NPRM_STEPS.           \n        exists e_src'.\n        split; eauto.\n        eapply rtc_compose. \n        eapply no_scfence_nprm_steps_is_nprm_steps. eapply x3.\n        eapply no_scfence_nprm_steps_is_nprm_steps. eapply NPRM_STEPS.\n        inv LOCAL_WF_T'; eauto.\n        inv LOCAL_WF_T'. ii.\n        exploit PROMISES; eauto. ii.\n        destruct (lo loc) eqn: AT_NA_LOC.\n        eapply na_steps_atomic_loc_stable_rtc with (loc := loc) in NA_STEPS_S; eauto.\n        eapply na_steps_atomic_loc_stable_rtc with (loc := loc) in NA_STEP_CAP; eauto.\n        unfold Memory.get in *.\n        rewrite <- NA_STEP_CAP. rewrite <- NA_STEPS_S in x0.\n        eauto.\n        unfold Memory.get in *.\n        erewrite <- NA_SAME_PRSV; eauto.\n      }\n      {\n        specialize (H (cons_ols pdset0 ls) (remove_none (cons_ols pdset0 ls))).\n        exploit H.\n        eapply lt_dset_cons_ols; eauto.\n        ii. subst. ss.\n        eauto.\n        rewrite REMOVE_NONE. ii; ss.\n        eapply no_Dup_ls_remove_none_cons_ols.\n        eapply NA_SAME_PRSV.\n        eapply Thread_na_steps_is_no_scfence_nprm_steps in NA_STEPS_S.\n        eapply rtc_rtcn in NA_STEPS_S. des.\n        eapply no_scfence_nprm_steps_prsv_memory_closed in NA_STEPS_S; ss.\n        ii.\n        destruct (lo loc) eqn:NA_AT_LOC.\n        eapply na_steps_atomic_loc_stable_rtc with (loc := loc) in NA_STEPS_S; eauto.\n        eapply na_steps_atomic_loc_stable_rtc with (loc := loc) in NA_STEP_CAP; eauto.\n        unfold Memory.get in *.\n        rewrite <- NA_STEPS_S in LHS; eauto.\n        rewrite <- NA_STEP_CAP. eauto.\n        unfold Memory.get in *.\n        rewrite <- NA_SAME_PRSV; eauto.\n        instantiate (1 := lc_src0).\n        eapply Thread_na_steps_is_no_scfence_nprm_steps in NA_STEPS_S.\n        eapply rtc_rtcn in NA_STEPS_S. des.\n        eapply no_scfence_nprm_steps_prsv_local_wf in NA_STEPS_S; eauto.\n        instantiate (2 := st_src0).\n        instantiate (1 := sc_src0).\n        clear - SAFE_S NA_STEPS_S.\n        ii; des.\n        contradiction SAFE_S.\n        eapply Thread_na_steps_is_no_scfence_nprm_steps in NA_STEPS_S.\n        eapply no_scfence_nprm_steps_is_nprm_steps in NA_STEPS_S.\n        eapply Thread_nprm_step_is_tau_step in NA_STEPS_S.\n        exists e_src'. split; eauto.\n        eapply rtc_compose; [eapply NA_STEPS_S | eapply H].\n        instantiate (1 := mem_tgt').\n        eapply Thread_na_step_is_no_scfence_nprm_step in TGT_NA_STEP.\n        eapply no_scfence_nprm_step_prsv_memory_closed in TGT_NA_STEP; ss.\n        instantiate (1 := lc_tgt').\n        rewrite <- PROM_EQ. eauto.\n        eapply Thread_na_step_is_no_scfence_nprm_step in TGT_NA_STEP.\n        eapply no_scfence_nprm_step_prsv_local_wf in TGT_NA_STEP; ss.\n        eauto.\n        instantiate (1 := pdset0). eauto.\n        eauto.\n        eapply finite_dset_remove_none_cons_ols; eauto.\n        clear - PDSET_LESS0 FINITE_DSET.\n        ii.\n        unfold finite_dset in FINITE_DSET.\n        eapply PDSET_LESS0 in H. des.\n        eapply FINITE_DSET in H; eauto.\n        instantiate (1 := sc_srcc). ii; des.\n        exists e_srcc'.\n        split; eauto.\n        eapply no_scfence_nprm_steps_is_nprm_steps in x3.\n        eapply rtc_compose; [eapply x3 | eapply x0].\n      }\n    }\n  }\n  {\n    (* target thread is done *)\n    inv LOCAL_SIM; ss.\n    contradiction SAFE_S.\n    eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss. eauto.\n    clear THRD_STEP RELY_STEP THRD_ABORT.\n    exploit THRD_DONE; eauto. unfold Thread.is_done; simpl. eauto. ii; des. inv x0.\n    eapply na_steps_dset_to_Thread_na_steps in x.\n    destruct e_src; ss.\n    exploit na_steps_na_loc_same_prsv; [eapply x | eauto..]. ii; des.\n    exploit Thread_na_steps_is_no_scfence_nprm_steps; [eapply x | eauto..].\n    introv NO_SC_FENCE_NPRM_STEP_S.\n    exploit Thread_na_steps_is_no_scfence_nprm_steps; [eapply NA_STEP_CAP | eauto..].\n    introv NO_SC_FENCE_NPRM_STEP_S_CAP.\n    eapply no_scfence_nprm_steps_not_care_sc with (sc0 := sc_srcc) in NO_SC_FENCE_NPRM_STEP_S_CAP.\n    eexists. split.\n    eapply no_scfence_nprm_steps_is_nprm_steps. eapply NO_SC_FENCE_NPRM_STEP_S_CAP.\n    ss.\n  }\nQed.\n  \nLemma lsim_ensures_promise_fulfill_T_BOT\n      index index_order dset lang I lo\n      st_tgt lc_tgt sc_tgt mem_tgt\n      st_src lc_src sc_src mem_src sc_srcc mem_srcc\n      b inj\n      (MONOTONIC_INJ: monotonic_inj inj)\n      (WELL_FOUND: well_founded index_order)\n      (T_BOT: Local.promises lc_tgt = Memory.bot)\n      (LOCAL_WF_T: Local.wf lc_tgt mem_tgt)\n      (MEM_CLOSED_T: Memory.closed mem_tgt)\n      (LOCAL_SIM: @local_sim_state index index_order lang I lo inj dset b\n                                   (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                                   (Thread.mk lang st_src lc_src sc_src mem_src))\n      (SAFE_S: ~ (exists e_src', rtc (@Thread.tau_step lang lo)\n                                (Thread.mk lang st_src lc_src sc_src mem_src) e_src' /\\\n                            Thread.is_abort e_src' lo))\n      (NA_SAME: forall loc, lo loc = Ordering.nonatomic -> mem_src loc = mem_srcc loc)\n      (LOCAL_WF_S: Local.wf lc_src mem_src)\n      (MEM_CLOSED_S: Memory.closed mem_src)\n      (MEM_LE_SRC: Memory.le mem_src mem_srcc):\n  exists e_srcc',\n    rtc (@Thread.nprm_step lang lo)\n        (Thread.mk lang st_src lc_src sc_srcc mem_srcc) e_srcc' /\\\n    Local.promises (Thread.local e_srcc') = Memory.bot.\nProof.\n  assert (TGT_PROM_CONS: Local.promise_consistent lc_tgt).\n  {\n    unfold Local.promise_consistent.\n    rewrite T_BOT. ii. rewrite Memory.bot_get in PROMISE. ss.\n  }\n  inv LOCAL_SIM; ss.\n  (* source abort *)\n  contradiction SAFE_S.\n  eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; ss. eauto.\n  (* source not abort *)\n  assert (PSET: exists pdset, dset_subset pdset dset /\\ rel_promises_TBOT inj pdset (Local.promises lc_src)).\n  {\n    clear - STEP_INV T_BOT. inv STEP_INV. des.\n    exists pdset. split; eauto.\n    inv REL_PROMISES0. econs; eauto.\n    ii.\n    exploit COMPLETE; [eapply H | eauto..]. ii; des; eauto.\n    rewrite T_BOT in x0.\n    rewrite Memory.bot_get in x0; ss.\n  }\n  des.\n  exploit finite_promises_convert_to_list; eauto.\n  inv LOCAL_WF_S; eauto. ii; des.\n  exploit well_founded_index_implies_Acc_lt_dset; eauto.\n  instantiate (1 := ls). introv ACC_LT_DSET.\n  eapply lsim_ensures_promise_fulfill_T_BOT'; eauto.\n  eapply local_sim_state_step_intro; eauto.\nQed.\n  \nLemma lsim_ensures_promise_fulfill:\n      forall n lang index index_order I lo\n        st_tgt lc_tgt sc_tgt mem_tgt sc_tgtc mem_tgtc e_tgt'\n        st_src lc_src sc_src mem_src sc_srcc mem_srcc\n        b dset inj\n        (WELL_FOUND: well_founded index_order)\n        (MONOTONIC_INJ: monotonic_inj inj)\n        (WF_I: wf_I I)\n        (FULFILL_TGT: rtcn (@Thread.nprm_step lang lo) n\n                           (@Thread.mk lang st_tgt lc_tgt sc_tgtc mem_tgtc) e_tgt')\n        (T_BOT: Local.promises (Thread.local e_tgt') = Memory.bot)\n        (LOCAL_WF_T: Local.wf lc_tgt mem_tgt)\n        (MEM_CLOSED_T: Memory.closed mem_tgt)\n        (MEM_LE: Memory.le mem_tgt mem_tgtc)\n        (MORE_RESERVE: \n           forall loc to from msg, Memory.get loc to mem_tgt = None ->\n                              Memory.get loc to mem_tgtc = Some (from, msg) ->\n                              msg = Message.reserve)\n        (LOCAL_SIM: @local_sim_state index index_order lang I lo inj dset b\n                                     (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                                     (Thread.mk lang st_src lc_src sc_src mem_src))\n        (SAFE_S: ~ (exists e_src', rtc (@Thread.tau_step lang lo)\n                                  (Thread.mk lang st_src lc_src sc_src mem_src) e_src' /\\\n                              Thread.is_abort e_src' lo))\n        (MEM_LE_SRC: Memory.le mem_src mem_srcc)\n        (MORE_RESERVE_SRC: \n           forall loc to from msg, Memory.get loc to mem_src = None ->\n                              Memory.get loc to mem_srcc = Some (from, msg) ->\n                              msg = Message.reserve)\n        (NA_SAME: forall loc, lo loc = Ordering.nonatomic -> mem_src loc = mem_srcc loc)\n        (AT_COVER: forall loc, lo loc = Ordering.atomic ->\n                          (forall from to, Memory.get loc to mem_srcc = Some (from, Message.reserve) ->\n                                      Memory.get loc to mem_tgtc = Some (from, Message.reserve)))\n        (LOCAL_WF_S: Local.wf lc_src mem_src)\n        (MEM_CLOSED_S: Memory.closed mem_src),\n      exists e_srcc',\n        rtc (@Thread.tau_step lang lo)\n            (Thread.mk lang st_src lc_src sc_srcc mem_srcc) e_srcc' /\\\n        Local.promises (Thread.local e_srcc') = Memory.bot.\nProof.\n  induction n; ii.\n  - (* target has fulfill all its promises *)\n    inv FULFILL_TGT; ss.\n    exploit lsim_ensures_promise_fulfill_T_BOT; eauto. ii; des.\n    eapply Thread_nprm_step_is_tau_step in x0.\n    eexists. split; eauto.\n  - (* target does not fulfill all its promises *)\n    assert (LOCAL_WF_TGT_C: Local.wf lc_tgt mem_tgtc).\n    {\n      eapply memory_concrete_le_local_wf; eauto; ss.\n      inv LOCAL_WF_T. clear - PROMISES MEM_LE.\n      unfold Memory.le in *. ii.\n      eapply PROMISES in LHS. eapply MEM_LE in LHS; eauto.\n    }\n    assert (CLOSED_TGT_C: Memory.closed mem_tgtc).\n    {\n      eapply memory_closed_addition_rsv with (mem := mem_tgt); eauto.\n    }\n    \n    assert (TGT_PROMS_CONS: Local.promise_consistent lc_tgt).\n    {\n      eapply rtcn_rtc in FULFILL_TGT. \n      eapply nprm_steps_to_bot_promise_consistent in FULFILL_TGT; eauto. \n    }\n    inv FULFILL_TGT. destruct a2.\n    inv A12.\n    + (* program step *)\n      destruct (classic (exists ordr, e = ThreadEvent.fence ordr Ordering.seqcst)).\n      {\n        (* sc fence step *)\n        clear LOCAL_WF_TGT_C CLOSED_TGT_C.\n        des; subst. inv PROG. inv LOCAL. inv LOCAL0; ss.\n        exploit PROMISES; eauto. ii.\n        exploit lsim_ensures_promise_fulfill_T_BOT; eauto. ii; des.\n        eapply Thread_nprm_step_is_tau_step in x1.\n        eexists. split; eauto.\n      }\n      { \n        (* not sc fence step *)\n        assert (LOCAL_WF_T': Local.wf local memory).\n        {\n          exploit no_scfence_nprm_step_prsv_local_wf.\n          eapply no_scfence_nprm_step_intro1. eapply PROG. eauto. eauto.\n          ss. ss. ss.\n        }\n        assert (MEM_CLOSED_T': Memory.closed memory).\n        {\n          exploit no_scfence_nprm_step_prsv_memory_closed.\n          eapply no_scfence_nprm_step_intro1. eapply PROG. eauto. eauto.\n          ss. ss. ss.\n        }\n        assert (PROM_CONS_T': Local.promise_consistent local).\n        {\n          eapply rtcn_rtc in A23. \n          eapply nprm_steps_to_bot_promise_consistent in A23; eauto.\n        }\n        exploit tgt_no_scfence_program_step_cap_sim;\n          [eapply PROG | eapply TAU | eapply LOCAL_WF_T | eapply MEM_CLOSED_T | eapply H | eapply LOCAL_SIM | eauto..].\n        instantiate (1 := sc_srcc). instantiate (2 := mem_srcc).\n        ii; des.\n        exploit x0; eauto. clear x0.\n        ii; des.    \n        eapply IHn with (st_src := st_src') (lc_src := lc_src')\n                        (sc_src := sc_src) (mem_src := mem_src')\n                        (inj := inj') (mem_tgt := mem_tgt') in A23; eauto.\n        des. \n        exists e_srcc'. split; eauto.\n        eapply Thread_nprm_step_is_tau_step in S_STEPS'.\n        eapply Thread_nprm_step_is_tau_step in S_STEPS.\n        eapply rtc_compose. eapply S_STEPS. eapply A23.\n        clear - SAFE_S S_STEPS'.\n        introv ABORT. destruct ABORT as (e_src' & ABORT). des.\n        contradiction SAFE_S. \n        eapply Thread_nprm_step_is_tau_step in S_STEPS'.\n        eexists. split.\n        eapply rtc_compose; [eapply S_STEPS' | eapply ABORT | eauto..].\n        eauto.\n      }\n    + (* promise free promise step *)\n      assert (LOCAL_WF_T': Local.wf local memory).\n      {\n        exploit no_scfence_nprm_step_prsv_local_wf.\n        eapply no_scfence_nprm_step_intro2. eapply PF. eauto. eauto. ss.\n      }\n      assert (MEM_CLOSED_T': Memory.closed memory).\n      {\n        exploit no_scfence_nprm_step_prsv_memory_closed.\n        eapply no_scfence_nprm_step_intro2. eapply PF. eauto. eauto. eauto.\n      }\n      assert (PROM_CONS_T': Local.promise_consistent local).\n      {\n        eapply rtcn_rtc in A23. \n        eapply nprm_steps_to_bot_promise_consistent in A23; eauto.\n      }\n      exploit tgt_pf_promise_step_cap_sim;\n        [eapply PF | eapply LOCAL_WF_T | eapply MEM_CLOSED_T | eapply LOCAL_SIM | eauto..]; eauto.\n      ii; des.\n      exploit x0; eauto.\n      clear x0. instantiate (1 := sc_srcc). ii; des.\n      eapply IHn with (st_src := st_src') (lc_src := lc_src')\n                        (sc_src := sc_src) (mem_src := mem_src') in A23; eauto.\n      des.\n      exists e_srcc'. split; eauto.\n      eapply Thread_nprm_step_is_tau_step in S_STEPS'.\n      eapply Thread_nprm_step_is_tau_step in S_STEPS.\n      eapply rtc_compose. eapply S_STEPS. eapply A23.\n      clear - SAFE_S S_STEPS'.\n      introv ABORT. destruct ABORT as (e_src' & ABORT). des.\n      contradiction SAFE_S. \n      eapply Thread_nprm_step_is_tau_step in S_STEPS'.\n      eexists. split.\n      eapply rtc_compose; [eapply S_STEPS' | eapply ABORT | eauto..].\n      eauto.\n      Unshelve. exact lo.\n      Unshelve. exact lo.\nQed.\n      \nLemma fulfill_ww_race_free_implies_promise_certified\n      lang lo st lc sc mem sc_c mem_c e' mem_cap\n      (FULFILL: rtc (@Thread.nprm_step lang lo)\n                    (Thread.mk lang st lc sc_c mem_c) e')\n      (BOT: Local.promises (Thread.local e') = Memory.bot)\n      (NO_WW_RACE: ~ @thrd_ww_race lang lo (@Thread.mk lang st lc sc mem_c))\n      (NA_SAME: forall loc, lo loc = Ordering.nonatomic -> mem loc = mem_c loc)\n      (CAP_MEM: Memory.cap mem mem_cap)\n      (AT_COVER: forall loc, lo loc = Ordering.atomic -> mem_cap loc = mem_c loc)\n      (LOCAL_WF1: Local.wf lc mem)\n      (LOCAL_WF2: Local.wf lc mem_c)\n      (CLOSED_MEM1: Memory.closed mem)\n      (CLOSED_MEM2: Memory.closed mem_c):\n  Thread.consistent_nprm (Thread.mk lang st lc sc mem) lo. \nProof.\n  unfold Thread.consistent_nprm; ss. ii.\n  exploit Memory.cap_inj; [eapply CAP_MEM | eapply CAP | eauto..]. ii. subst mem1.\n  eapply rtc_rtcn in FULFILL. des.\n  assert(PROMISE_CONSISTENT: Local.promise_consistent lc).\n  {\n    eapply promise_consistent_prsv_thread_nprm_step in FULFILL; eauto.\n    unfold Local.promise_consistent. ii.\n    rewrite BOT in PROMISE.\n    rewrite Memory.bot_get in PROMISE. ss.\n  }\n  assert(WF_CONCRETE_PROM: forall loc from to val R,\n            Memory.get loc to (Local.promises lc) = Some (from, Message.concrete val R) ->\n            Time.lt from to).\n  {\n    ii.\n    unfold Local.promise_consistent in PROMISE_CONSISTENT.\n    exploit PROMISE_CONSISTENT; eauto.\n    introv LT.\n    exploit Memory.get_ts; eauto. ii; des; subst.\n    clear - LT. auto_solve_time_rel.\n    eauto.\n  }\n  assert(LOCAL_WF_CAP: Local.wf lc mem_cap).\n  {\n    eapply Local.cap_wf; eauto.\n  }\n  assert(MEM_CLOSED_CAP: Memory.closed mem_cap).\n  {\n    eapply Memory.cap_closed; eauto.\n  }\n  destruct e'.\n  eapply no_na_race_consistent_construction\n    with (inj := spec_inj mem_c) (mem' := mem_cap) in FULFILL; eauto; ss. \n  {\n    instantiate (1 := sc1) in FULFILL.\n    destruct FULFILL as (st' & lc' & sc' & mem' & CAP_STEPS & CAP_BOT).\n    exists (Thread.mk lang st' lc' sc' mem'). ss.\n  } \n  {\n    ii. unfold spec_inj in *.\n    destruct (Memory.get loc t mem_c); ss. destruct p. destruct t1; ss.\n    inv H0. eauto.\n  }\n  {\n    ii.\n    contradiction H0. clear H0.\n    inv H1. inv ITV; ss.\n    unfold Mem_at_eq in AT_COVER.\n    assert (Memory.get loc to mem_c = Some (from, msg)).\n    {\n      unfold Memory.get in *.\n      rewrite <- AT_COVER; eauto.\n    }\n    econs; eauto.\n    econs; eauto.\n  }\n  {\n    instantiate (2 := sc1).\n    instantiate (1 := fun loc => Memory.max_ts loc mem_cap).\n    ss. ii.\n    unfold Memory.max_concrete_timemap in SC_MAX.\n    specialize (SC_MAX loc).\n    inv MEM_CLOSED_CAP. unfold Memory.inhabited in INHABITED.\n    specialize (INHABITED loc).\n    exploit Memory.max_concrete_ts_spec; eauto. ii; des.\n    exploit Memory.cap_inv_concrete; [eapply CLOSED_MEM1 | eapply CAP | eapply GET | eauto..].\n    ii.\n    assert (GET_c: Memory.get loc (sc1 loc) mem_c = Some (from, Message.concrete val' released')).\n    {\n      unfold Memory.get in *.\n      rewrite <- NA_SAME; eauto.\n    }\n    eexists.\n    split.\n    unfold spec_inj. rewrite GET_c. eauto.\n    exploit Memory.max_ts_spec; [eapply GET | eauto..]. ii; des; eauto.\n  }\n  {\n    econs; eauto.\n    ii.\n    exists t f R.\n    split; eauto.\n    unfold spec_inj. rewrite MSG; eauto.\n    split. eapply spec_inj_optviewinj.\n    destruct (lo loc) eqn: AT_NA_LOC.\n    {\n      (* atomic loc *)\n      unfold Memory.get in *.\n      rewrite AT_COVER; eauto.\n    }\n    {\n      (* non-atomic loc *)\n      assert (GET: Memory.get loc t mem = Some (f, Message.concrete val R)).\n      {\n        unfold Memory.get in *.\n        rewrite NA_SAME; eauto.\n      }\n      inv CAP. eauto.\n    }\n    {\n      ii.\n      unfold spec_inj in INJ.\n      destruct (Memory.get loc t mem_c) eqn:GET; ss.\n      destruct p. destruct t1; eauto. ss.\n    }\n    {\n      eapply spec_inj_monotonic.\n    }\n  }\n  {\n    eapply TViewInj_spec_inj_id; eauto.\n  }\n  {\n    econs; eauto.\n    ii.\n    exists to released from.\n    inv LOCAL_WF2.\n    exploit PROMISES; eauto. introv GET_MEMC.\n    split.\n    unfold spec_inj. rewrite GET_MEMC. eauto.\n    split; eauto.\n    ii.\n    exists to' released' from'.\n    inv LOCAL_WF2.\n    exploit PROMISES; eauto. introv GET_MEMC.\n    split.\n    unfold spec_inj. rewrite GET_MEMC. eauto.\n    eauto.\n  }\n  {\n    introv NA_LOC.\n    eapply na_view_intro_le_max_ts; eauto.\n    clear - SC_MAX LOCAL_WF_CAP.\n    inv LOCAL_WF_CAP. inv TVIEW_CLOSED. inv ACQ.\n    unfold Memory.closed_timemap in RLX.\n    specialize (RLX loc). des.\n    eapply max_concrete_timemap_get in RLX; eauto.\n    ii.\n    destruct msg; eauto.\n    assert (GET_MEM: Memory.get loc ts mem = Some (from, Message.concrete val released)).\n    {\n      unfold Memory.get in *.\n      rewrite <- NA_SAME in H0; eauto.\n    }\n    inv CAP_MEM.\n    eapply SOUND in GET_MEM.\n    eapply max_concrete_timemap_get in GET_MEM; eauto.\n    clear - H GET_MEM. auto_solve_time_rel.\n    ii.\n    inv H0. inv ITV; ss.\n    eapply Memory.max_ts_spec in GET; eauto. des.\n    clear - H MAX TO.\n    cut (Time.le ts' (Memory.max_ts loc mem_cap)).\n    ii. clear - H H0. auto_solve_time_rel.\n    auto_solve_time_rel.\n  }\n  {\n    ii.\n    unfold Memory.max_concrete_timemap in SC_MAX.\n    specialize (SC_MAX loc). \n    inv MEM_CLOSED_CAP. unfold Memory.inhabited in INHABITED.\n    specialize (INHABITED loc).\n    exploit Memory.max_concrete_ts_spec; [ | eapply INHABITED | eauto..]. eauto.\n    ii; des.\n    eapply Memory.cap_inv_concrete in GET.\n    3: eapply CAP. 2: eauto.\n    unfold Memory.get in *.\n    erewrite <- NA_SAME; eauto.\n  }\n  {\n    ii.\n    inv LOCAL_WF1.\n    eapply PROMISES in H0.\n    inv CAP_MEM.\n    eapply SOUND in H0.\n    eapply max_concrete_timemap_get in H0; eauto.\n  }\nQed.\n  \nLemma promise_certified_prsv\n      lang index index_order I lo inj dset b\n      st_tgt lc_tgt sc_tgt mem_tgt st_src lc_src sc_src mem_src\n      (WELL_FOUND: well_founded index_order)\n      (CONSISTENT_T: NPAuxThread.consistent lang (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt) lo)\n      (LOCAL_SIM: @local_sim_state index index_order lang I lo inj dset b\n                                   (Thread.mk lang st_tgt lc_tgt sc_tgt mem_tgt)\n                                   (Thread.mk lang st_src lc_src sc_src mem_src))\n      (SAFE: ~ (exists e_src', rtc (@Thread.tau_step lang lo)\n                              (Thread.mk lang st_src lc_src sc_src mem_src) e_src' /\\\n                          Thread.is_abort e_src' lo))\n      (NO_WW_RACE: ~ @thrd_ww_race lang lo (@Thread.mk lang st_src lc_src sc_src mem_src))\n      (LOCAL_WF_T: Local.wf lc_tgt mem_tgt)\n      (LOCAL_WF_S: Local.wf lc_src mem_src)\n      (CLOSED_SC_T: Memory.closed_timemap sc_tgt mem_tgt)\n      (CLOSED_SC_S: Memory.closed_timemap sc_src mem_src)\n      (CLOSED_MEM_T: Memory.closed mem_tgt)\n      (CLOSED_MEM_S: Memory.closed mem_src)\n      (WF_I: wf_I I)\n      (MONOTONIC_INJ': monotonic_inj inj):\n  <<CONSISTENT_S: NPAuxThread.consistent lang (Thread.mk lang st_src lc_src sc_src mem_src) lo>>.\nProof.\n  unfold NPAuxThread.consistent in *.\n  unfold Thread.consistent_nprm in CONSISTENT_T; ss. ii.\n  exploit Memory.cap_exists; [eapply CLOSED_MEM_T | eauto..].\n  introv CAP_TGT. destruct CAP_TGT as (mem_tgt_cap & CAP_TGT). \n  exploit Memory.max_concrete_timemap_exists; eauto.\n  instantiate (1 := mem_tgt_cap).\n  eapply Memory.cap_closed in CAP_TGT; eauto.\n  inv CAP_TGT; eauto.\n  introv MAX_CONCRETE_TM_TGT. destruct MAX_CONCRETE_TM_TGT as (max_tm_tgt & MAX_CONCRETE_TM_TGT).\n  exploit CONSISTENT_T; eauto.\n  clear CONSISTENT_T. introv CONSISTENT_T. destruct CONSISTENT_T as (e_tgt & FULFILL_TGT & BOT_TGT).\n  lets FULFILL_SRC: FULFILL_TGT.\n  eapply rtc_rtcn in FULFILL_SRC. des. ss.\n  assert (TGT_PROM_CONS: Local.promise_consistent lc_tgt).\n  {\n    eapply promise_consistent_prsv_thread_nprm_step in FULFILL_SRC; eauto; ss.\n    eapply Memory.cap_closed; eauto.\n    eapply Local.cap_wf; eauto.\n    unfold Local.promise_consistent.\n    rewrite BOT_TGT. ii. rewrite Memory.bot_get in PROMISE; ss.\n  }\n  eapply lsim_ensures_promise_fulfill with\n      (sc_srcc := sc1) (mem_srcc := at_CAP_MEM mem_src mem1 lo) in FULFILL_SRC; eauto; ss.\n  {\n    destruct FULFILL_SRC as (e_srcc' & FULFILL_SRC & BOT_SRC).\n    assert(LOCAL_WF_MEM_AT_CAP: Local.wf lc_src (at_CAP_MEM mem_src mem1 lo)).\n    {\n      eapply memory_concrete_le_local_wf; eauto.\n      unfold memory_concrete_le. unfold at_CAP_MEM.\n      clear - CAP. inv CAP. clear - SOUND. unfold Memory.le in *.\n      unfold Memory.get in *. ii.\n      destruct (lo loc); eauto.\n      clear - LOCAL_WF_S CAP.\n      inv LOCAL_WF_S. inv CAP.\n      clear - SOUND PROMISES.\n      unfold Memory.le in *. unfold Memory.get in *. ii.\n      unfold at_CAP_MEM. destruct (lo loc); eauto.\n    }\n    assert(CLOSED_MEM_AT_CAP: Memory.closed (at_CAP_MEM mem_src mem1 lo)).\n    {\n      eapply memory_closed_additional_rsv; eauto.\n      eapply at_CAP_MEM_mem_le; eauto.\n      eapply Memory.Memory.le_PreOrder_obligation_1; eauto.\n      inv CAP; eauto.\n      ii. \n      unfold at_CAP_MEM in *. unfold Memory.get in *.\n      destruct (lo loc); ss.\n      destruct msg; eauto.\n      exploit Memory.cap_inv; eauto. ii; des; ss.\n      unfold Memory.get in x0.\n      rewrite H in x0; ss.\n      destruct msg; eauto. rewrite H in H0; ss.\n    }\n    eapply rtc_rtcn in FULFILL_SRC. des.\n    eapply tau_steps_fulfill_implies_nprm_steps_fulfill in FULFILL_SRC; eauto; ss. des.\n    eapply fulfill_ww_race_free_implies_promise_certified in FULFILL_SRC; eauto.\n    {\n      clear LOCAL_WF_MEM_AT_CAP CLOSED_MEM_AT_CAP.\n      introv THRD_WW_RACE_CAP.\n      contradiction NO_WW_RACE.\n      eapply thrd_ww_race_cap_prsv; eauto.\n      eapply at_CAP_MEM_mem_le; eauto.\n      eapply Memory.Memory.le_PreOrder_obligation_1; eauto.\n      inv CAP; eauto.\n      ii. unfold Memory.get in H0, H. unfold at_CAP_MEM in H0.\n      destruct (lo loc) eqn:Heqe; eauto; ss. \n      exploit Memory.cap_inv; eauto. ii; des; eauto.\n      unfold Memory.get in x0. rewrite H in x0; ss.\n      rewrite H in H0. ss.\n      inv LOCAL_WF_S; eauto.\n    } \n    {\n      ii. unfold at_CAP_MEM. rewrite H; eauto.\n    }\n    {\n      ii.\n      unfold at_CAP_MEM. rewrite H. eauto.\n    }\n  }\n  {\n    inv CAP_TGT; eauto.\n  }\n  {\n    ii. exploit Memory.cap_inv; [ | eapply CAP_TGT | eapply H0 | eauto..]; eauto.\n    ii; des; subst; ss.\n    rewrite H in x0; ss.\n  }\n  {\n    unfold Memory.le, at_CAP_MEM. ii.\n    unfold Memory.get in *.\n    destruct (lo loc); eauto.\n    inv CAP; eauto.\n  }\n  {\n    ii.\n    unfold Memory.get, at_CAP_MEM in *. destruct (lo loc); eauto.\n    destruct msg; eauto. \n    exploit Memory.cap_inv; [ | eapply CAP | eauto..]; eauto. ii; des; ss.\n    unfold Memory.get in x0.\n    rewrite H in x0. ss.\n    rewrite H in H0; ss.\n  } \n  {\n    ii.\n    unfold at_CAP_MEM. rewrite H; eauto.\n  }\n  {\n    assert(Mem_at_eq lo mem_tgt_cap (at_CAP_MEM mem_src mem1 lo)).\n    {\n      inv LOCAL_SIM; ss.\n      contradiction SAFE.\n      eapply NPAuxThread_tau_steps_2_Thread_tau_steps in NP_STEPS; eauto.\n      clear THRD_STEP RELY_STEP THRD_DONE THRD_ABORT.\n      inv STEP_INV.\n      eapply Mem_at_eq_at_CAP_MEM2; eauto.\n      eapply Mem_at_eq_cap; eauto.\n    }\n    ii.\n    unfold at_CAP_MEM in *; ss.\n    unfold Memory.get in *.\n    rewrite H0 in H1; ss.\n    unfold Mem_at_eq in *.\n    exploit H; eauto. ii. unfold Mem_approxEq_loc in x. des.\n    specialize (x0 from to). des.\n    unfold Memory.get in x1. rewrite H0 in x1. eauto.\n  }\nQed.      \n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/proofs/sim-compositionality/simPromiseCertified.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.20396019547166944}}
{"text": "From ITree Require Import ITree.\nFrom compcert Require Import Maps AST Values Memory Globalenvs Ctypes.\nFrom compcert Require Coqlib Clight Clightdefs.\nFrom Paco Require Import paco.\n\nRequire Import Arith ZArith Bool.\nRequire Import String List Lia.\n\nRequire Import sflib.\nRequire Import Axioms StdlibExt IntegersExt ITreeTac.\n\nRequire Import SysSem.\nRequire Import IPModel DiscreteTimeModel IntByteModel.\nRequire Import OSModel OSNodes.\nRequire Import ProgSem CProgEventSem.\nRequire Import ProgSim CProgSimLemmas.\nRequire Import RTSysEnv MWITree.\n\n(* Require Import SystemParams. *)\n(* Require Import SystemDefs ITreeSpec. *)\n(* Require Import SystemEventSem. *)\nRequire Import config_prm main_prm SystemProgs.\nRequire Import dev.\nRequire Import VerifProgBase.\nRequire Import VerifMainUtil.\nRequire Import PALSSystem.\n\nRequire Import AcStSystem.\nRequire Import LinkDevice.\nRequire Import SpecDevice.\n\nImport Clight Clightdefs.\nImport ITreeNotations.\nImport ActiveStandby.\n\nImport DevState.\n\nSet Nested Proofs Allowed.\n(* Arguments app : simpl nomatch. *)\nLocal Transparent Archi.ptr64.\nLocal Opaque Z.of_nat Z.to_nat.\n\n(* Arguments Nat.mul: simpl never. *)\nArguments Nat.mul: simpl never.\n\nOpaque globalenv.\n\nLocal Open Scope Z.\n\n\nDefinition dev_gvar_ids := map fst dev_gvar_ilist.\nDefinition dev_gfun_ids := map fst dev_gfun_ilist.\nDefinition dev_cenv_ids := map fst dev_cenv_ilist.\n\n\nRecord mem_dst_blk (m: mem) (st: DevState.t) (b_cst: block): Prop :=\n  MemDevState {\n      mem_dst_owner_status:\n        Mem.loadbytes m b_cst 0 1 =\n        Some [Byte (Byte.repr (owner_status_to_Z (owner_status st)))] ;\n      mem_dst_demand: Mem.loadbytes m b_cst 1 1 =\n                      Some [Byte (Byte.repr (Z.of_nat (demand st)))] ;\n\n      mem_dst_perm:\n        Mem.range_perm m b_cst 0 2 Cur Writable;\n    }.\n\n\nLemma store_set_owner_status\n      (is_owner: bool) zown m m' st b\n      (MEM_DST: mem_dst_blk m st b)\n      (ZOWN: zown = if is_owner then 1 else 2)\n      (STORE: Mem.store Mint8signed m b 0\n                        (Vint (Int.repr zown)) = Some m')\n  : mem_dst_blk m' (set_owner_status is_owner st) b.\nProof.\n  destruct st as [own dmd].\n  inv MEM_DST.\n  unfold set_owner_status. ss.\n\n  hexploit store_unchanged_on'; eauto.\n  s. unfold mem_range. i.\n\n  econs; s.\n  - eapply Mem.loadbytes_store_same in STORE. ss.\n    rewrite STORE.\n    destruct is_owner; ss.\n  - eapply Mem.loadbytes_unchanged_on; eauto.\n    ii. nia.\n  - ii. eapply Mem.perm_store_1; eauto.\nQed.\n\nLemma store_set_demand\n      (new_dmd: nat) m m' st b\n      (MEM_DST: mem_dst_blk m st b)\n      (STORE: Mem.store Mint8signed m b 1\n                        (Vint (Int.repr (Z.of_nat new_dmd))) = Some m')\n  : mem_dst_blk m' (set_demand new_dmd st) b.\nProof.\n  destruct st as [own dmd].\n  inv MEM_DST.\n  unfold set_owner_status. ss.\n\n  hexploit store_unchanged_on'; eauto.\n  s. unfold mem_range. i.\n\n  econs; s.\n  - eapply Mem.loadbytes_unchanged_on; eauto.\n    ii. nia.\n  - eapply Mem.loadbytes_store_same in STORE. ss.\n    rewrite STORE.\n    unfold inj_bytes, encode_int. s.\n    rewrite rev_if_be_single. s.\n    do 3 f_equal.\n\n    symmetry.\n    apply signed_byte_int_unsigned_repr_eq.\n  - ii. eapply Mem.perm_store_1; eauto.\nQed.\n\nLemma reduce_demand_eq\n      st\n  : reduce_demand st = set_demand (pred (demand st)) st.\nProof.\n  destruct st; ss.\nQed.\n\n\nSection MEMORY_INV.\n\n  Variable ge: genv.\n\n  Let fsymb (id: ident) (bpred: block -> Prop): Prop :=\n    forall b (FIND_SYMB: Genv.find_symbol ge id = Some b),\n      bpred b.\n\n  Definition mem_dst (m: mem) (dst: DevState.t): Prop :=\n    fsymb _state (mem_dst_blk m dst).\n\n  Definition mem_acq (m: mem): Prop :=\n    fsymb _acq_msg\n          (fun b_acq => Mem.loadbytes m b_acq 0 8 =\n                     Some (inj_bytes acq_msg)).\n\n  Definition mem_rel (m: mem): Prop :=\n    fsymb _rel_msg\n          (fun b_rel => Mem.loadbytes m b_rel 0 8 =\n                     Some (inj_bytes rel_msg)).\n\n  Definition inv_dev\n             (ast: DevState.t) (m: mem): Prop :=\n    <<DST_WF: DevState.wf ast>> /\\\n    <<MEM_DST: mem_dst m ast>> /\\\n    <<MEM_ACQ: mem_acq m>> /\\\n    <<MEM_REL: mem_rel m>>.\n\n  Lemma mem_dst_unch\n        ast m m'\n        (MEM_DST : mem_dst m ast)\n        (MEM_UNCH : Mem.unchanged_on (blocks_of ge [_state]) m m')\n    : mem_dst m' ast.\n  Proof.\n    rr. rr in MEM_DST. i.\n    hexploit MEM_DST.\n    { apply FIND_SYMB. }\n    inversion 1.\n\n    assert (forall i, blocks_of ge [_state] b i).\n    { unfold blocks_of. i.\n      exists _state.\n      split.\n      * clear. ss. eauto.\n      * apply FIND_SYMB.\n    }\n\n    econs;\n      try by eapply Mem.loadbytes_unchanged_on; eauto.\n    ii. eapply Mem.perm_unchanged_on; eauto.\n  Qed.\n\n  Lemma mem_dst_unch_diffblk\n        ast m m' b\n        (MEM_DST : mem_dst m ast)\n        (MEM_UNCH : mem_changed_block b m m')\n        (FSYMB: Genv.find_symbol ge _state <> Some b)\n    : mem_dst m' ast.\n  Proof.\n    eapply mem_dst_unch; eauto.\n    eapply Mem.unchanged_on_implies; eauto.\n    unfold blocks_of. i.\n    simpl in *. des; ss.\n    ii. subst. ss.\n  Qed.\n\n  Lemma mem_acq_unch\n        m m'\n        (MEM_ACQ : mem_acq m)\n        (MEM_UNCH : Mem.unchanged_on (blocks_of ge [_acq_msg]) m m')\n    : mem_acq m'.\n  Proof.\n    rr. rr in MEM_ACQ. i.\n    hexploit MEM_ACQ.\n    { apply FIND_SYMB. }\n    i. eapply Mem.loadbytes_unchanged_on; eauto.\n    unfold blocks_of.\n    intros _ _.\n    exists _acq_msg.\n    splits.\n    - clear. ss. eauto.\n    - apply FIND_SYMB.\n  Qed.\n\n  Lemma mem_acq_unch_diffblk\n        m m' b\n        (MEM_DST : mem_acq m)\n        (MEM_UNCH : mem_changed_block b m m')\n        (FSYMB: Genv.find_symbol ge _acq_msg <> Some b)\n    : mem_acq m'.\n  Proof.\n    eapply mem_acq_unch; eauto.\n    eapply Mem.unchanged_on_implies; eauto.\n    unfold blocks_of. i.\n    simpl in *. des; ss.\n    ii. subst. ss.\n  Qed.\n\n  Lemma mem_rel_unch\n        m m'\n        (MEM_REL : mem_rel m)\n        (MEM_UNCH : Mem.unchanged_on (blocks_of ge [_rel_msg]) m m')\n    : mem_rel m'.\n  Proof.\n    rr. rr in MEM_REL. i.\n    hexploit MEM_REL.\n    { apply FIND_SYMB. }\n    i. eapply Mem.loadbytes_unchanged_on; eauto.\n    unfold blocks_of.\n    intros _ _.\n    exists _rel_msg.\n    splits.\n    - clear. ss. eauto.\n    - apply FIND_SYMB.\n  Qed.\n\n  Lemma mem_rel_unch_diffblk\n        m m' b\n        (MEM_DST : mem_rel m)\n        (MEM_UNCH : mem_changed_block b m m')\n        (FSYMB: Genv.find_symbol ge _rel_msg <> Some b)\n    : mem_rel m'.\n  Proof.\n    eapply mem_rel_unch; eauto.\n    eapply Mem.unchanged_on_implies; eauto.\n    unfold blocks_of. i.\n    simpl in *. des; ss.\n    ii. subst. ss.\n  Qed.\n\n  Lemma inv_dev_dep_app_blocks\n    : forall (ast : DevState.t) (m m' : mem)\n        (INV: inv_dev ast m)\n        (MEM_UNCH: Mem.unchanged_on (blocks_of ge dev_gvar_ids) m m'),\n      inv_dev ast m'.\n  Proof.\n    unfold inv_dev. i. des.\n    splits.\n    - ss.\n    - eapply mem_dst_unch; eauto.\n      eapply Mem.unchanged_on_implies; eauto.\n      unfold blocks_of. ss.\n      i. des; ss.\n      clarify. esplits; eauto.\n    - eapply mem_acq_unch; eauto.\n      eapply Mem.unchanged_on_implies; eauto.\n      unfold blocks_of. ss.\n      i. des; ss.\n      clarify.\n      exists _acq_msg. esplits; eauto.\n    - eapply mem_rel_unch; eauto.\n      eapply Mem.unchanged_on_implies; eauto.\n      unfold blocks_of. ss.\n      i. des; ss.\n      clarify.\n      exists _rel_msg. esplits; eauto.\n  Qed.\n\nEnd MEMORY_INV.\n\n\nSection MEM_INIT.\n\n  Variable tid: nat.\n  Variable cprog: Clight.program.\n\n  Hypothesis CPROG_EQ: __guard__ (cprog = prog_dev (Z.of_nat tid)).\n  Notation ge := (globalenv cprog).\n\n  Let GENV_PROPS\n    : genv_props (globalenv cprog)\n                 (main_gvar_ilist tid ++ dev_gvar_ilist)\n                 (main_gfun_ilist ++ dev_gfun_ilist)\n                 (main_cenv_ilist ++ dev_cenv_ilist).\n  Proof.\n    rewrite CPROG_EQ.\n    apply (genv_props_dev tid).\n  Qed.\n\n  Lemma inv_dev_init:\n    forall (m_i : mem),\n      Genv.init_mem cprog = Some m_i ->\n      inv_dev ge DevState.init m_i.\n  Proof.\n    intros m_i INIT_MEM. r.\n    split.\n    { apply DevState.wf_init. }\n\n    assert (DEFMAP: (prog_defmap cprog) ! _state = Some (Gvar v_state) /\\\n                    (prog_defmap cprog) ! _acq_msg = Some (Gvar v_acq_msg) /\\\n                    (prog_defmap cprog) ! _rel_msg = Some (Gvar v_rel_msg)).\n    { rewrite CPROG_EQ.\n      change (prog_defmap (prog_dev (Z.of_nat tid))) with\n          (PTree.combine Linking.link_prog_merge\n                         (prog_defmap prog_mw) (prog_defmap (dev.prog (Z.of_nat tid)))).\n      do 3 rewrite PTree.gcombine by ss.\n      splits.\n      - replace ((prog_defmap prog_mw) ! _state) with\n            (@None (globdef fundef type)).\n        2: {\n          change (prog_defmap prog_mw) with\n              (PTree.combine Linking.link_prog_merge\n                             (prog_defmap config_prog)\n                             (prog_defmap main_prog)).\n          rewrite PTree.gcombine by ss.\n          ss.\n        }\n        ss.\n      - replace ((prog_defmap prog_mw) ! _acq_msg) with\n            (@None (globdef fundef type)).\n        2: {\n          change (prog_defmap prog_mw) with\n              (PTree.combine Linking.link_prog_merge\n                             (prog_defmap config_prog)\n                             (prog_defmap main_prog)).\n          rewrite PTree.gcombine by ss.\n          ss.\n        }\n        ss.\n      - replace ((prog_defmap prog_mw) ! _rel_msg) with\n            (@None (globdef fundef type)).\n        2: {\n          change (prog_defmap prog_mw) with\n              (PTree.combine Linking.link_prog_merge\n                             (prog_defmap config_prog)\n                             (prog_defmap main_prog)).\n          rewrite PTree.gcombine by ss.\n          ss.\n        }\n        ss.\n    }\n    destruct DEFMAP as (DEFMAP1 & DEFMAP2 & DEFMAP3).\n\n    splits.\n    - (* dev_state *)\n      intros b_dst FSYMB_DST.\n\n      apply Genv.find_def_symbol in DEFMAP1.\n      destruct DEFMAP1 as (b_dst' & FSYMB_DST' & FDEF_DST).\n\n      replace (Genv.globalenv cprog) with\n          (genv_genv (globalenv cprog)) in FSYMB_DST' by ss.\n      fold fundef in FSYMB_DST'.\n      rewrite FSYMB_DST in FSYMB_DST'.\n      symmetry in FSYMB_DST'. inv FSYMB_DST'.\n\n      eapply Genv.init_mem_characterization_gen in INIT_MEM.\n      r in INIT_MEM.\n      exploit INIT_MEM; eauto. s.\n      intros (RANGE_PERM & PERM & LOAD & LOADBYTES).\n\n      hexploit LOADBYTES; eauto.\n      rewrite Z.max_l by ss.\n      replace (Z.to_nat 2) with 2%nat by ss.\n      rewrite app_nil_r. s.\n      replace 2 with (1 + 1) by ss.\n\n      clear LOADBYTES. intro LOADBYTES.\n      apply Mem_loadbytes_split' in LOADBYTES; try nia.\n      des; ss.\n\n    - intros b FSYMB.\n      apply Genv.find_def_symbol in DEFMAP2.\n      destruct DEFMAP2 as (b' & FSYMB' & FDEF).\n\n      replace (Genv.globalenv cprog) with\n          (genv_genv (globalenv cprog)) in FSYMB' by ss.\n      fold fundef in FSYMB'.\n      rewrite FSYMB in FSYMB'.\n      symmetry in FSYMB'. clarify.\n\n      eapply Genv.init_mem_characterization_gen in INIT_MEM.\n      r in INIT_MEM.\n      exploit INIT_MEM; eauto. s.\n      intros (RANGE_PERM & PERM & LOAD & LOADBYTES).\n\n      rewrite LOADBYTES by ss.\n      ss.\n    - intros b FSYMB.\n      apply Genv.find_def_symbol in DEFMAP3.\n      destruct DEFMAP3 as (b' & FSYMB' & FDEF).\n\n      replace (Genv.globalenv cprog) with\n          (genv_genv (globalenv cprog)) in FSYMB' by ss.\n      fold fundef in FSYMB'.\n      rewrite FSYMB in FSYMB'.\n      symmetry in FSYMB'. clarify.\n\n      eapply Genv.init_mem_characterization_gen in INIT_MEM.\n      r in INIT_MEM.\n      exploit INIT_MEM; eauto. s.\n      intros (RANGE_PERM & PERM & LOAD & LOADBYTES).\n\n      rewrite LOADBYTES by ss.\n      ss.\n  Qed.\n\nEnd MEM_INIT.\n", "meta": {"author": "kim-yoonseung", "repo": "pals-thesis-dev", "sha": "1a165028f5461ed4d00a1e2720b3b1e4542f5dc2", "save_path": "github-repos/coq/kim-yoonseung-pals-thesis-dev", "path": "github-repos/coq/kim-yoonseung-pals-thesis-dev/pals-thesis-dev-1a165028f5461ed4d00a1e2720b3b1e4542f5dc2/src/apps/active_standby/app_verif/VerifDevice_Base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.2039601954716694}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\n(* *********************************************************************)\n(*                                                                     *)\n(*  Tactics for proving Clight code of the Compcert verified compiler  *)\n(*                                                                     *)\n(*                 Developed by Xiongnan (Newman) Wu                   *)\n(*                                                                     *)\n(*                         Yale University                             *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** This file develops the tactics for proving the Clight code using the\n    Compcert verified compiler. The main tactic vcgen is the\n    verification condition generator for special Clight code. It applies\n    the Bigstep operational semantics of the Clight 2 language to generate\n    verification condition for a loop-free clight statement where all the\n    expression can be evaluated out using the knowledge in the context,\n    i.e., if the statement contains conditional statement, appropiate\n    case analysis on the conditional expressions need to be applied before\n    the application of the vcgen tactic so that the evaluation can go through.\n    In presense of loops, the loop has to be proved separately for its\n    specification and loop termination. This can be done using a saparate\n    frameworks deleloped in LoopProof.v. We recommand to use the version\n    of the framework with while loop with no Break, Continue, or Return\n    statement in the while body, so that the proof of the loop body can\n    still be automated with the vcgen tactic.\n\nCurrently we assume:\n- We never take address of a local variable in the stack.\n- No use of C union.\n\n *)\n\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import Values.\nRequire Import MemoryExtra.\nRequire Import EventsExtra.\nRequire Import Clight.\nRequire Import Smallstep.\nRequire Import ClightBigstep.\nRequire Import Cop.\nRequire Import Ctypes.\nRequire Import DataType.\nRequire Import ZArith.\n\nHint Unfold Int.max_unsigned.\nHint Unfold Int.modulus.\nHint Unfold Int.half_modulus.\n\nGlobal Opaque PTree.get PTree.set \"!\" Z.land Z.lor.\n\n(** * Frequently used lemmas in tactics. *)\n\nLemma zadd_rm_head: forall n p q, p = q -> n + p = n + q.\nProof.\n  intros.\n  rewrite H.\n  trivial.\nQed.\n\nLemma zadd_rm_tail: forall n p q, p = q -> p + n = q + n.\nProof.\n  intros.\n  rewrite H.\n  trivial.\nQed.\n\nLemma zdiv_range_le_lt : forall a b c x: Z, a <= 0 -> b > 0 -> c > 0 -> a <= x < b -> a <= x/ c < b.\nProof.\n  intros.\n  destruct H2.\n  split.\n  apply Zdiv_le_lower_bound.\n  omega.\n  assert(a * c <= a).\n  assert(- a * c >= - a).\n  rewrite <- Zmult_1_r.\n  assert(c >= 1) by omega.\n  apply Zmult_ge_compat_l.\n  omega.\n  omega.\n  rewrite Zopp_mult_distr_l_reverse in H4.\n  omega.\n  omega.\n  apply Zdiv_lt_upper_bound.\n  omega.\n  assert(b <= b * c).\n  rewrite <- Zmult_1_r at 1.\n  assert(1 <= c) by omega.\n  apply Zmult_le_compat_l.\n  omega.\n  omega.\n  omega.\nQed.\n\nLemma zdiv_range_le_le : forall a b c x: Z, a <= 0 -> b > 0 -> c > 0 -> a <= x <= b -> a <= x/ c <= b.\nProof.\n  intros.\n  destruct H2.\n  split.\n  apply Zdiv_le_lower_bound.\n  omega.\n  assert(a * c <= a).\n  assert(- a * c >= - a).\n  rewrite <- Zmult_1_r.\n  assert(c >= 1) by omega.\n  apply Zmult_ge_compat_l.\n  omega.\n  omega.\n  rewrite Zopp_mult_distr_l_reverse in H4.\n  omega.\n  omega.\n  apply Zdiv_le_upper_bound.\n  omega.\n  assert(b <= b * c).\n  rewrite <- Zmult_1_r at 1.\n  assert(1 <= c) by omega.\n  apply Zmult_le_compat_l.\n  omega.\n  omega.\n  omega.\nQed.\n\nLemma max_unsigned_gt0: Int.max_unsigned > 0.\nProof.\n  repeat autounfold.\n  simpl.\n  omega.\nQed.\n\nLemma max_unsigned_val: Int.max_unsigned  = 4294967295.\nProof.\n  repeat autounfold; reflexivity.\nQed.\n\nLemma unsigned_inj : forall a b, Int.unsigned a = Int.unsigned b -> a = b.\nProof.\n  intros. rewrite <- (Int.repr_unsigned a).\n  rewrite <- (Int.repr_unsigned b).\n  f_equal.\n  trivial.\nQed.\n\nLemma minus1lt: forall i:Z, i - 1 < i.\nProof.\n  intro.\n  omega.\nQed.\n\nLemma Z_land_range_lo: forall x y, 0 <= x -> 0 <= Z.land x y.\nProof.\n  intros.\n  rewrite Z.land_nonneg.\n  left.\n  assumption.\nQed. \n\nLemma Z_land_range_lo_r: forall x y, 0 <= y -> 0 <= Z.land x y.\nProof.\n  intros.\n  rewrite Z.land_nonneg.\n  right.\n  assumption.\nQed.\n\nLemma Z_land_range_hi: forall x y, 0 <= x <= Int.max_unsigned -> 0 <= y <= Int.max_unsigned -> Z.land x y <= Int.max_unsigned.\nProof.\n  rewrite max_unsigned_val.\n  intros.\n  assert(Z.land x y < 4294967296).\n  apply Z.log2_lt_cancel.\n  assert(Z.log2 (Z.land x y) <= Z.min (Z.log2 x) (Z.log2 y)).\n  apply Z.log2_land.\n  omega.\n  omega.\n  rewrite Zmin_spec in H1.\n  destruct (zlt (Z.log2 x) (Z.log2 y)).\n  assert(Z.log2 x <= Z.log2 4294967295).\n  apply Z.log2_le_mono.\n  omega.\n  simpl in *.\n  omega.\n  assert(Z.log2 y <= Z.log2 4294967295).\n  apply Z.log2_le_mono.\n  omega.\n  simpl in *.\n  omega.\n  omega.\nQed.   \n\nLemma Z_land_range: forall x y, 0 <= x <= Int.max_unsigned -> 0 <= y <= Int.max_unsigned -> 0 <= Z.land x y <= Int.max_unsigned.\nProof.\n  split.\n  apply Z_land_range_lo; omega.\n  apply Z_land_range_hi; omega.\nQed.\n\nLemma Z_lor_range_lo: forall x y, 0 <= x -> 0 <= y -> 0 <= Z.lor x y.\nProof.\n  intros.\n  apply Z.lor_nonneg; auto.\nQed.\n\nLemma Z_lor_range_hi: forall x y, 0 <= x <= Int.max_unsigned -> 0 <= y <= Int.max_unsigned -> Z.lor x y <= Int.max_unsigned.\nProof.\n  rewrite max_unsigned_val; simpl.\n  intros.\n  assert(Z.lor x y < 4294967296).\n  apply Z.log2_lt_cancel.\n  assert(Z.log2 (Z.lor x y) = Z.max (Z.log2 x) (Z.log2 y)).\n  apply Z.log2_lor.\n  omega.\n  omega.\n  rewrite H1.\n  rewrite Zmax_spec in *.\n  destruct (zlt (Z.log2 y) (Z.log2 x)).\n  assert(Z.log2 x <= Z.log2 4294967295).\n  apply Z.log2_le_mono.\n  omega.\n  simpl in *.\n  omega.\n  assert(Z.log2 y <= Z.log2 4294967295).\n  apply Z.log2_le_mono.\n  omega.\n  simpl in *.\n  omega.\n  omega.\nQed.\n\nLemma Z_lor_range: forall x y, 0 <= x <= Int.max_unsigned -> 0 <= y <= Int.max_unsigned -> 0 <= Z.lor x y <= Int.max_unsigned.\nProof.\n  intros.\n  split.\n  apply Z_lor_range_lo; omega.\n  apply Z_lor_range_hi; omega.\nQed.\n\nLemma Z_lxor_range :\n  forall x y,\n    0 <= x <= Int.max_unsigned -> 0 <= y <= Int.max_unsigned ->\n    0 <= Z.lxor x y <= Int.max_unsigned.\nProof.\n  rewrite max_unsigned_val; simpl.\n  intros.\n  split.\n  rewrite Z.lxor_nonneg.\n  split; omega.\n  assert(Z.lxor x y < 4294967296).\n  apply Z.log2_lt_cancel.\n  assert(Z.log2 (Z.lxor x y) <= Z.max (Z.log2 x) (Z.log2 y)).\n  apply Z.log2_lxor.\n  omega.\n  omega.\n  apply Z.le_lt_trans with (m := Z.max (Z.log2 x) (Z.log2 y)); auto.\n  rewrite Zmax_spec in *.\n  destruct (zlt (Z.log2 y) (Z.log2 x)).\n  assert(Z.log2 x <= Z.log2 4294967295).\n  apply Z.log2_le_mono.\n  omega.\n  simpl in *.\n  omega.\n  assert(Z.log2 y <= Z.log2 4294967295).\n  apply Z.log2_le_mono.\n  omega.\n  simpl in *.\n  omega.\n  omega.\nQed.\n\nLemma Z_shiftl_16_range :\n  forall x,\n    0 <= x < 65536 -> 0 <= Z.shiftl x 16 <= Int.max_unsigned.\nProof.\n  unfold Int.max_unsigned. simpl (Int.modulus - 1).\n  intros.\n  split.\n  rewrite Z.shiftl_nonneg. omega.\n\n  assert (Z.shiftl x 16 < 4294967296).\n  case_eq (zeq x 0); intros; subst.\n\n  (* x = 0 *)\n  simpl. omega.\n\n  (* x <> 0 *)\n  apply Z.log2_lt_cancel.\n  rewrite Z.log2_shiftl; try omega.\n\n  assert (Z.log2 x <= Z.log2 65535).\n  apply Z.log2_le_mono. omega.\n  simpl in *. omega.\n\n  omega.\nQed.\n\n\n(** * Hints for autorewrite *)\n\nLemma unsigned_zero: Int.unsigned Int.zero = 0.\nProof. reflexivity. Qed.\n\nLemma unsigned_one: Int.unsigned Int.one = 1.\nProof. reflexivity. Qed.\n\nLemma eq_one_zero: Int.eq Int.one Int.zero = false.\nProof. reflexivity. Qed.\n\nLemma eq_zero_zero: Int.eq Int.zero Int.zero = true.\nProof. reflexivity. Qed.\n\nLemma negb_true: negb true = false.\nProof. reflexivity. Qed.\n\nLemma negb_false: negb false = true.\nProof. reflexivity. Qed.\n\nLemma repr_zero: Int.repr 0 = Int.zero.\nProof. reflexivity. Qed.\n\nLemma repr_one: Int.repr 1 = Int.one.\nProof. reflexivity. Qed.\n\nLemma and_zero_zero: Z.land 0 0 = 0.\nProof. reflexivity. Qed.\n\nLemma and_one_zero: Z.land 1 0 = 0.\nProof. reflexivity. Qed.\n\nLemma and_zero_one: Z.land 0 1 = 0.\nProof. reflexivity. Qed.\n\nLemma and_one_one: Z.land 1 1 = 1.\nProof. reflexivity. Qed.\n\nLemma or_zero_zero: Z.lor 0 0 = 0.\nProof. reflexivity. Qed.\n\nLemma or_one_zero: Z.lor 1 0 = 1.\nProof. reflexivity. Qed.\n\nLemma or_zero_one: Z.lor 0 1 = 1.\nProof. reflexivity. Qed.\n\nLemma or_one_one: Z.lor 1 1 = 1.\nProof. reflexivity. Qed.\n\nHint Rewrite unsigned_zero unsigned_one eq_one_zero eq_zero_zero negb_true negb_false repr_zero repr_one: arith.\nHint Rewrite and_zero_zero and_zero_one and_one_zero and_one_one or_zero_zero or_zero_one or_one_zero or_one_one : arith.\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/layerlib/MathLemma.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.32766829425520916, "lm_q1q2_score": 0.20396018729815}}
{"text": "From iris.program_logic Require Export weakestpre.\nFrom iris.program_logic Require Import ectx_lifting.\nFrom iris.base_logic Require Export invariants.\nFrom iris.algebra Require Import auth frac agree gmap.\nFrom iris.proofmode Require Import proofmode.\nFrom iris.base_logic Require Export gen_heap.\nFrom RobustSafety Require Export lang.\nFrom iris.prelude Require Import options.\n\n(** The CMRA for the heap of the implementation. This is linked to the\n    physical heap. *)\nClass heapIG Σ := HeapIG {\n  heapI_invG : invGS Σ;\n  heapI_gen_heapG :> gen_heapGS loc val Σ;\n}.\n\nClass heapPG Σ := HeapPG {\n  heapP_invG : invGpreS Σ;\n  heapP_gen_heapG :> gen_heapGpreS loc val Σ;\n}.\n\nDefinition heapΣ := #[invΣ; gen_heapΣ loc val].\n\nGlobal Instance: ∀ Σ, subG heapΣ Σ → heapPG Σ.\nProof. solve_inG. Qed.\n\nGlobal Instance heapIG_irisG `{heapIG Σ} : irisGS LambdaRS_lang Σ := {\n  iris_invGS := heapI_invG;\n  num_laters_per_step _ := 0;\n  state_interp σ  _ _ _ := (gen_heap_interp (Heap σ) ∗ ⌜Failure σ = false⌝)%I;\n  fork_post _ := True%I;\n  state_interp_mono _ _ _ _ := fupd_intro _ _\n}.\n\nNotation \"l ↦{ dq } v\" := (mapsto (L:=loc) (V:=val) l dq v)\n  (at level 20, format \"l  ↦{ dq }  v\") : bi_scope.\nNotation \"l ↦□ v\" := (mapsto (L:=loc) (V:=val) l DfracDiscarded v)\n  (at level 20, format \"l  ↦□  v\") : bi_scope.\nNotation \"l ↦{# q } v\" := (mapsto (L:=loc) (V:=val) l (DfracOwn q) v)\n  (at level 20, format \"l  ↦{# q }  v\") : bi_scope.\nNotation \"l ↦ v\" := (mapsto (L:=loc) (V:=val) l (DfracOwn 1) v)\n  (at level 20, format \"l  ↦  v\") : bi_scope.\n\nSection lang_rules.\n  Context `{heapIG Σ}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types Φ : val → iProp Σ.\n  Implicit Types σ : state.\n  Implicit Types e : expr.\n  Implicit Types v w : val.\n\n  Ltac inv_head_step :=\n  repeat match goal with\n  | _ => progress simplify_map_eq/= (* simplify memory stuff *)\n  | H : to_val _ = Some _ |- _ => apply of_to_val in H\n  | H : _ = of_val ?v |- _ =>\n     is_var v; destruct v; first[discriminate H|injection H as H]\n  | H : head_step ?e _ _ _ _ _ |- _ =>\n     try (is_var e; fail 1); (* inversion yields many goals if [e] is a variable\n     and can thus better be avoided. *)\n     inversion H; subst; clear H\n  end.\n\n  Local Hint Extern 0 (atomic _) => solve_atomic : core.\n  Local Hint Extern 0 (head_reducible _ _) => eexists _, _, _, _; simpl : core.\n\n  Local Hint Constructors head_step : core.\n  Local Hint Resolve alloc_fresh : core.\n  Local Hint Resolve to_of_val : core.\n\n  (** Base axioms for core primitives of the language: Stateful reductions. *)\n  Lemma wp_alloc E e v :\n    IntoVal e v →\n    {{{ True }}} Alloc e @ E {{{ l, RET (LocV l); l ↦ v }}}.\n  Proof.\n    iIntros (<- Φ) \"_ HΦ\". iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 ????) \"[Hh Hfl] !>\"; iSplit; first by auto.\n    iNext; iIntros (v2 σ2 efs Hstep) \"_\"; inv_head_step.\n    iMod (@gen_heap_alloc with \"Hh\") as \"(Hh & Hl & _)\"; first done.\n    iModIntro; iSplit=> //. iFrame. by iApply \"HΦ\".\n  Qed.\n\n  Lemma wp_load E l dq v :\n    {{{ ▷ l ↦{dq} v }}} Load (Loc l) @ E {{{ RET v; l ↦{dq} v }}}.\n  Proof.\n    iIntros (Φ) \">Hl HΦ\". iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 ????) \"[Hh Hfl] !>\". iDestruct (@gen_heap_valid with \"Hh Hl\") as %?.\n    iSplit; first by eauto.\n    iNext; iIntros (v2 σ2 efs Hstep) \"_\"; inv_head_step.\n    iModIntro; iSplit=> //. iFrame. by iApply \"HΦ\".\n  Qed.\n\n  Lemma wp_store E l v' e v :\n    IntoVal e v →\n    {{{ ▷ l ↦ v' }}} Store (Loc l) e @ E\n    {{{ RET UnitV; l ↦ v }}}.\n  Proof.\n    iIntros (<- Φ) \">Hl HΦ\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 ????) \"[Hh Hfl] !>\". iDestruct (@gen_heap_valid with \"Hh Hl\") as %?.\n    iSplit; first by eauto. iNext; iIntros (v2 σ2 efs Hstep) \"_\"; inv_head_step.\n    iMod (@gen_heap_update with \"Hh Hl\") as \"[$ Hl]\".\n    iModIntro. iSplit=>//. iFrame. by iApply \"HΦ\".\n  Qed.\n\n  Lemma wp_cas_fail E l dq v' e1 v1 e2 v2 :\n    IntoVal e1 v1 → IntoVal e2 v2 → v' ≠ v1 →\n    {{{ ▷ l ↦{dq} v' }}} CAS (Loc l) e1 e2 @ E\n    {{{ RET (BoolV false); l ↦{dq} v' }}}.\n  Proof.\n    iIntros (<- <- ? Φ) \">Hl HΦ\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 ????) \"[Hh Hfl] !>\". iDestruct (@gen_heap_valid with \"Hh Hl\") as %?.\n    iSplit; first by eauto.\n    iNext; iIntros (v2' σ2 efs Hstep) \"_\"; inv_head_step.\n    iModIntro; iSplit=> //. iFrame. by iApply \"HΦ\".\n  Qed.\n\n  Lemma wp_cas_suc E l e1 v1 e2 v2 :\n    IntoVal e1 v1 → IntoVal e2 v2 →\n    {{{ ▷ l ↦ v1 }}} CAS (Loc l) e1 e2 @ E\n    {{{ RET (BoolV true); l ↦ v2 }}}.\n  Proof.\n    iIntros (<- <- Φ) \">Hl HΦ\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 ????) \"[Hh Hfl] !>\". iDestruct (@gen_heap_valid with \"Hh Hl\") as %?.\n    iSplit; first by eauto. iNext; iIntros (v2' σ2 efs Hstep) \"_\"; inv_head_step.\n    iMod (@gen_heap_update with \"Hh Hl\") as \"[$ Hl]\".\n    iModIntro. iSplit=>//. iFrame. by iApply \"HΦ\".\n  Qed.\n\n  Lemma wp_FAA E l m e2 k :\n    IntoVal e2 (#nv k) →\n    {{{ ▷ l ↦ (#nv m) }}} FAA (Loc l) e2 @ E\n    {{{ RET (#nv m); l ↦ #nv (m + k) }}}.\n  Proof.\n    iIntros (<- Φ) \">Hl HΦ\".\n    iApply wp_lift_atomic_head_step_no_fork; auto.\n    iIntros (σ1 ????) \"[Hh Hfl] !>\". iDestruct (@gen_heap_valid with \"Hh Hl\") as %?.\n    iSplit; first by eauto. iNext; iIntros (v2' σ2 efs Hstep) \"_\"; inv_head_step.\n    iMod (@gen_heap_update with \"Hh Hl\") as \"[$ Hl]\".\n    iModIntro. iSplit=>//. iFrame. by iApply \"HΦ\".\n  Qed.\n\n  Lemma wp_fork E s e Φ :\n    ▷ (|={E}=> Φ UnitV) ∗ ▷ WP e @ s; ⊤ {{ _, True }} ⊢ WP Fork e @ s; E {{ Φ }}.\n  Proof.\n    iIntros \"[He HΦ]\". iApply wp_lift_atomic_head_step; [done|].\n    iIntros (σ1 ????) \"Hσ !>\"; iSplit; first by eauto.\n    iNext; iIntros (v2 σ2 efs Hstep) \"_\"; inv_head_step. by iFrame.\n  Qed.\n\n  Local Ltac solve_exec_safe := intros; subst; do 3 eexists; econstructor; eauto.\n  Local Ltac solve_exec_puredet := simpl; intros; by inv_head_step.\n  Local Ltac solve_pure_exec :=\n    unfold IntoVal in *;\n    repeat match goal with H : AsVal _ |- _ => destruct H as [??] end; subst;\n    intros ?; apply nsteps_once, pure_head_step_pure_step;\n      constructor; [solve_exec_safe | solve_exec_puredet].\n\n  Global Instance pure_rec e1 e2 `{!AsVal e2} :\n    PureExec True 1 (App (Rec e1) e2) e1.[(Rec e1), e2 /].\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_lam e1 e2 `{!AsVal e2} :\n    PureExec True 1 (App (Lam e1) e2) e1.[e2 /].\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_LetIn e1 e2 `{!AsVal e1} :\n    PureExec True 1 (LetIn e1 e2) e2.[e1 /].\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_seq e1 e2 `{!AsVal e1} :\n    PureExec True 1 (Seq e1 e2) e2.\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_fst e1 e2 `{!AsVal e1, !AsVal e2} :\n    PureExec True 1 (Fst (Pair e1 e2)) e1.\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_snd e1 e2 `{!AsVal e1, !AsVal e2} :\n    PureExec True 1 (Snd (Pair e1 e2)) e2.\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_case_inl e0 e1 e2 `{!AsVal e0}:\n    PureExec True 1 (Case (InjL e0) e1 e2) e1.[e0/].\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_case_inr e0 e1 e2 `{!AsVal e0}:\n    PureExec True 1 (Case (InjR e0) e1 e2) e2.[e0/].\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_if_true e1 e2 :\n    PureExec True 1 (If (#♭ true) e1 e2) e1.\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_if_false e1 e2 :\n    PureExec True 1 (If (#♭ false) e1 e2) e2.\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_nat_binop op a b :\n    PureExec True 1 (BinOp op (#n a) (#n b)) (of_val (binop_eval op a b)).\n  Proof. solve_pure_exec. Qed.\n\n  Global Instance pure_assert_true :\n    PureExec True 1 (Assert (#♭ true)) Unit.\n  Proof. solve_pure_exec. Qed.\n\n\n  (* stuck rules *)\n\n  Lemma var_stuck x Φ : ⊢ WP Var x ? {{v, Φ v}}.\n  Proof.\n    iApply wp_lift_pure_head_stuck; [done| |by split; [done|inversion 1]].\n    intros K ?; destruct K as [|[]] using rev_ind; simpl; try rewrite fill_app; inversion 1; done.\n  Qed.\n\n  Lemma binop_stuck op v1 v2 Φ :\n    non_nat_val v1 ∨ non_nat_val v2 →\n    ⊢ WP BinOp op (of_val v1) (of_val v2) ? {{v, Φ v}}.\n  Proof.\n    intros Hnn.\n    iApply wp_lift_pure_head_stuck; [done| |].\n    - intros K e';\n        destruct K as [|[] ? _] using rev_ind; simpl; try rewrite fill_app; try by inversion 1.\n      + inversion 1 as [[Heqop Heq]]; simplify_eq.\n        assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n        eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n      + inversion 1 as [[Heqop Heqv1 Heq]]; simplify_eq.\n        assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n        eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n    - split; first done.\n      inversion 1; simplify_eq; destruct v1; destruct v2;\n        simplify_eq/=; destruct Hnn as [Hnn|Hnn]; inversion Hnn.\n  Qed.\n\n  Lemma fst_stuck v Φ : non_pair_val v → ⊢ WP Fst (of_val v) ? {{w, Φ w}}.\n  Proof.\n    intros Hnp.\n    iApply wp_lift_pure_head_stuck; [done| |].\n    - intros K e';\n        destruct K as [|[] ? _] using rev_ind; simpl; try rewrite fill_app; try by inversion 1.\n      inversion 1 as [[Heq]]; simplify_eq.\n      assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n      eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n    - split; first done.\n      inversion 1; simplify_eq; destruct v; simplify_eq/=; inversion Hnp.\n  Qed.\n\n  Lemma snd_stuck v Φ : non_pair_val v → ⊢ WP Snd (of_val v) ? {{w, Φ w}}.\n  Proof.\n    intros Hnp.\n    iApply wp_lift_pure_head_stuck; [done| |].\n    - intros K e';\n        destruct K as [|[] ? _] using rev_ind; simpl; try rewrite fill_app; try by inversion 1.\n      inversion 1 as [[Heq]]; simplify_eq.\n      assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n      eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n    - split; first done.\n      inversion 1; simplify_eq; destruct v; simplify_eq/=; inversion Hnp.\n  Qed.\n\n  Lemma case_stuck v e1 e2 Φ : non_sum_val v → ⊢ WP Case (of_val v) e1 e2 ? {{w, Φ w}}.\n  Proof.\n    intros Hns.\n    iApply wp_lift_pure_head_stuck; [done| |].\n    - intros K e';\n        destruct K as [|[] ? _] using rev_ind; simpl; try rewrite fill_app; try by inversion 1.\n      inversion 1 as [[Heq]]; simplify_eq.\n      assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n      eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n    - split; first done.\n      inversion 1; simplify_eq; destruct v; simplify_eq/=; inversion Hns.\n  Qed.\n\n  Lemma if_stuck v e1 e2 Φ : non_bool_val v → ⊢ WP If (of_val v) e1 e2 ? {{w, Φ w}}.\n  Proof.\n    intros Hnb.\n    iApply wp_lift_pure_head_stuck; [done| |].\n    - intros K e';\n        destruct K as [|[] ? _] using rev_ind; simpl; try rewrite fill_app; try by inversion 1.\n      inversion 1 as [[Heq]]; simplify_eq.\n      assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n      eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n    - split; first done.\n      inversion 1; simplify_eq; destruct v; simplify_eq/=; inversion Hnb.\n  Qed.\n\n  Lemma app_stuck v1 v2 Φ : non_fun_val v1 → ⊢ WP App (of_val v1) (of_val v2) ? {{w, Φ w}}.\n  Proof.\n    intros Hnf.\n    iApply wp_lift_pure_head_stuck; [done| |].\n    - intros K e';\n        destruct K as [|[] ? _] using rev_ind; simpl; try rewrite fill_app; try by inversion 1.\n      + inversion 1 as [[Heq]]; simplify_eq.\n        assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n        eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n      + inversion 1 as [[z Heq]]; simplify_eq.\n        assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n        eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n    - split; first done.\n      inversion 1; simplify_eq; destruct v1; simplify_eq/=; inversion Hnf.\n  Qed.\n\n  Lemma load_stuck v Φ : non_loc_val v → ⊢ WP Load (of_val v) ? {{w, Φ w}}.\n  Proof.\n    intros Hnl.\n    iApply wp_lift_pure_head_stuck; [done| |].\n    - intros K e';\n        destruct K as [|[] ? _] using rev_ind; simpl; try rewrite fill_app; try by inversion 1.\n      inversion 1 as [[Heq]]; simplify_eq.\n      assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n      eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n    - split; first done.\n      inversion 1; simplify_eq; destruct v; simplify_eq/=; inversion Hnl.\n  Qed.\n\n  Lemma store_stuck v1 v2 Φ : non_loc_val v1 → ⊢ WP Store (of_val v1) (of_val v2) ? {{w, Φ w}}.\n  Proof.\n    intros Hnl.\n    iApply wp_lift_pure_head_stuck; [done| |].\n    - intros K e';\n        destruct K as [|[] ? _] using rev_ind; simpl; try rewrite fill_app; try by inversion 1.\n      + inversion 1 as [[Heq]]; simplify_eq.\n        assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n        eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n      + inversion 1 as [[z Heq]]; simplify_eq.\n        assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n        eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n    - split; first done.\n      inversion 1; simplify_eq; destruct v1; simplify_eq/=; inversion Hnl.\n  Qed.\n\n  Lemma cas_stuck v1 v2 v3 Φ :\n    non_loc_val v1 → ⊢ WP CAS (of_val v1) (of_val v2) (of_val v3) ? {{w, Φ w}}.\n  Proof.\n    intros Hnl.\n    iApply wp_lift_pure_head_stuck; [done| |].\n    - intros K e';\n        destruct K as [|[] ? _] using rev_ind; simpl; try rewrite fill_app; try by inversion 1.\n      + inversion 1 as [[Heq]]; simplify_eq.\n        assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n        eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n      + inversion 1 as [[z Heq]]; simplify_eq.\n        assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n        eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n      + inversion 1 as [[z1 z2 Heq]]; simplify_eq.\n        assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n        eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n    - split; first done.\n      inversion 1; simplify_eq; destruct v1; simplify_eq/=; inversion Hnl.\n  Qed.\n\n  Lemma faa_stuck_non_loc_or_non_nat v1 v2 Φ :\n    non_loc_val v1 ∨ non_nat_val v2 → ⊢ WP FAA (of_val v1) (of_val v2) ? {{w, Φ w}}.\n  Proof.\n    intros Hnln.\n    iApply wp_lift_pure_head_stuck; [done| |].\n    - intros K e';\n        destruct K as [|[] ? _] using rev_ind; simpl; try rewrite fill_app; try by inversion 1.\n      + inversion 1 as [[Heq]]; simplify_eq.\n        assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n        eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n      + inversion 1 as [[z Heq]]; simplify_eq.\n        assert (is_Some (to_val e')) as [? ?]; last by intros?; simplify_eq.\n        eapply fill_val with K; rewrite /= -Heq to_of_val; eauto.\n    - split; first done.\n      inversion 1; simplify_eq; destruct v1; destruct v2;\n        simplify_eq/=; destruct Hnln as [Hnln|Hnln]; inversion Hnln;\n        simplify_eq/=;\n          repeat match goal with\n            HX : context [to_val (of_val _)] |- _ => rewrite to_of_val /= in HX\n          end; simplify_eq.\n  Qed.\n\n  Lemma faa_stuck_non_nat_loc E l n v Φ :\n    non_nat_val v → l ↦ v ⊢ WP FAA (Loc l) (#n n) @ E ? {{w, Φ w}}.\n  Proof.\n    iIntros (Hnn) \"Hl\".\n    iApply wp_lift_head_stuck; [done| |].\n    - intros K e';\n        destruct K as [|[] ? _] using rev_ind; simpl; try rewrite fill_app; try by inversion 1.\n      + inversion 1 as [[Heq]]; simplify_eq.\n        destruct K as [|[] ? _] using rev_ind; rewrite ?fill_app in Heq; simplify_eq/=; done.\n      + inversion 1 as [[z Heq]]; simplify_eq.\n        destruct K as [|[] ? _] using rev_ind; rewrite ?fill_app in Heq; simplify_eq/=; done.\n    - iIntros (σ ns κs nt) \"[Hh Hfl]\".\n      iMod ((fupd_mask_weaken ∅ (P := True)) with \"[]\") as \"_\";\n        [set_solver|by iIntros \"?\"; iModIntro|].\n      iModIntro.\n      iDestruct (@gen_heap_valid with \"Hh Hl\") as %?.\n      iPureIntro.\n      split; first done.\n      inversion 1; simplify_eq/=; inversion Hnn.\n  Qed.\n\nEnd lang_rules.\n", "meta": {"author": "amintimany", "repo": "robustsafety", "sha": "b5a86d59d5ca033d4f4bb874de745f75a7b36690", "save_path": "github-repos/coq/amintimany-robustsafety", "path": "github-repos/coq/amintimany-robustsafety/robustsafety-b5a86d59d5ca033d4f4bb874de745f75a7b36690/theories/rules.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.20384883353157796}}
{"text": "Require Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\nRequire Import VerdiRaft.CommonTheorems.\n\nRequire Import VerdiRaft.RequestVoteMaxIndexMaxTermInterface.\nRequire Import VerdiRaft.VotedForTermSanityInterface.\n\nRequire Import VerdiRaft.VotedForMoreUpToDateInterface.\n\nSection VotedForMoreUpToDate.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n  Context {rvmimti : requestVote_maxIndex_maxTerm_interface}.\n  Context {vftsi : votedFor_term_sanity_interface}.\n\n  Lemma votedFor_moreUpToDate_append_entries :\n    refined_raft_net_invariant_append_entries votedFor_moreUpToDate.\n  Proof using. \n    red. unfold votedFor_moreUpToDate. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update_hyp; simpl in *; eauto;\n    try rewrite votesWithLog_same_append_entries; eauto.\n    - find_copy_eapply_lem_hyp handleAppendEntries_term_votedFor; eauto.\n      find_apply_lem_hyp handleAppendEntries_log_term_type.\n      intuition; try congruence. repeat find_rewrite. eauto.\n    - find_copy_eapply_lem_hyp handleAppendEntries_term_votedFor; eauto.\n      intuition; repeat find_rewrite; eauto.\n    - find_apply_lem_hyp handleAppendEntries_log_term_type.\n      intuition; try congruence. repeat find_rewrite. eauto.\n  Qed.\n\n  Lemma votedFor_moreUpToDate_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply votedFor_moreUpToDate.\n  Proof using. \n    red. unfold votedFor_moreUpToDate. intros. simpl in *.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_log_term_type.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update_hyp; simpl in *; eauto;\n    intuition; try congruence; repeat find_rewrite; eauto;\n    find_copy_eapply_lem_hyp handleAppendEntriesReply_term_votedFor; eauto;\n    intuition; repeat find_rewrite; eauto.\n  Qed.\n  \n  Lemma votedFor_moreUpToDate_request_vote :\n    refined_raft_net_invariant_request_vote votedFor_moreUpToDate.\n  Proof using rvmimti. \n    red. unfold votedFor_moreUpToDate. intros. simpl in *.\n    find_copy_apply_lem_hyp handleRequestVote_log_term_type.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update_hyp; simpl in *; eauto;\n    intuition; try congruence; repeat find_rewrite; eauto.\n    - find_eapply_lem_hyp update_elections_data_request_vote_votedFor; eauto.\n      intuition; repeat find_rewrite.\n      + eapply_prop_hyp RaftState.votedFor RaftState.votedFor; eauto.\n        break_exists_exists; intuition.\n        eauto using update_elections_data_request_vote_votesWithLog_old.\n      + simpl. eauto using moreUpToDate_refl.\n    - find_eapply_lem_hyp update_elections_data_request_vote_votedFor; eauto.\n      intuition; repeat find_rewrite.\n      + eapply_prop_hyp RaftState.votedFor RaftState.votedFor; eauto.\n        break_exists_exists; intuition.\n        eauto using update_elections_data_request_vote_votesWithLog_old.\n      + find_apply_lem_hyp requestVote_maxIndex_maxTerm_invariant.\n        subst.\n        eapply_prop_hyp requestVote_maxIndex_maxTerm pBody. conclude_using eauto.\n        all:eauto.\n        intuition; subst.\n        eexists; intuition; eauto.\n    - find_eapply_lem_hyp update_elections_data_request_vote_votedFor; eauto.\n      intuition; repeat find_rewrite.\n      + eapply_prop_hyp RaftState.votedFor RaftState.votedFor; eauto.\n        break_exists_exists; intuition.\n        eauto using update_elections_data_request_vote_votesWithLog_old.\n      + find_apply_lem_hyp requestVote_maxIndex_maxTerm_invariant.\n        subst.\n        eapply_prop_hyp requestVote_maxIndex_maxTerm pBody. conclude_using eauto.\n        all:eauto.\n        intuition; subst.\n        eexists; intuition; eauto.\n  Qed.\n\n  Lemma votedFor_moreUpToDate_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply votedFor_moreUpToDate.\n  Proof using. \n    red. unfold votedFor_moreUpToDate. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update_hyp; simpl in *;\n    try rewrite update_elections_data_request_vote_reply_votesWithLog;\n    eauto.\n    - erewrite handleRequestVoteReply_log; eauto.\n      find_copy_eapply_lem_hyp handleRequestVoteReply_log_term_type; eauto.\n      find_copy_eapply_lem_hyp handleRequestVoteReply_term_votedFor; eauto.\n      intuition. repeat find_rewrite. eauto.\n    - find_copy_eapply_lem_hyp handleRequestVoteReply_term_votedFor; eauto.\n      intuition. repeat find_rewrite. eauto.\n    - erewrite handleRequestVoteReply_log; eauto.\n      find_copy_eapply_lem_hyp handleRequestVoteReply_log_term_type; eauto.\n      intuition. repeat find_rewrite. eauto.\n  Qed.\n  \n  Lemma votedFor_moreUpToDate_timeout :\n    refined_raft_net_invariant_timeout votedFor_moreUpToDate.\n  Proof using vftsi. \n    red. unfold votedFor_moreUpToDate. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update_hyp; simpl in *; eauto.\n    - find_copy_apply_lem_hyp handleTimeout_log_same.\n      find_copy_eapply_lem_hyp update_elections_data_timeout_votedFor; eauto.\n      intuition; repeat find_rewrite; eauto.\n      simpl. eauto using moreUpToDate_refl.\n    - find_copy_eapply_lem_hyp update_elections_data_timeout_votedFor; eauto.\n      intuition; [repeat find_rewrite; eauto|].\n      subst. lia.\n    - find_copy_apply_lem_hyp handleTimeout_log_same.\n      find_apply_lem_hyp update_elections_data_timeout_votesWithLog_votesReceived.\n      intuition; try congruence.\n      find_copy_apply_lem_hyp votedFor_term_sanity_invariant.\n      eapply_prop_hyp votedFor_term_sanity RaftState.votedFor; eauto.\n      unfold raft_data in *; simpl in *; unfold raft_data in *; simpl in *.\n      lia.\n  Qed.\n\n  Lemma votedFor_moreUpToDate_client_request :\n    refined_raft_net_invariant_client_request votedFor_moreUpToDate.\n  Proof using. \n    red. unfold votedFor_moreUpToDate. intros. simpl in *.\n    subst. repeat find_higher_order_rewrite.\n    find_copy_apply_lem_hyp handleClientRequest_type; intuition.\n    find_copy_apply_lem_hyp handleClientRequest_term_votedFor; intuition.\n    destruct_update_hyp; simpl in *; eauto; repeat find_rewrite;\n    try rewrite votesWithLog_same_client_request;\n    find_apply_lem_hyp handleClientRequest_log;\n    intuition; repeat find_rewrite; eauto;\n    break_exists; intuition; congruence.\n  Qed.\n\n  Lemma votedFor_moreUpToDate_do_leader :\n    refined_raft_net_invariant_do_leader votedFor_moreUpToDate.\n  Proof using. \n    red. unfold votedFor_moreUpToDate. intros. simpl in *.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update_hyp; simpl in *; eauto;\n    try solve [find_apply_lem_hyp doLeader_candidate; subst; eauto].\n    find_apply_lem_hyp doLeader_term_votedFor.\n    intuition; repeat find_rewrite; eauto.\n  Qed.\n  \n  Lemma votedFor_moreUpToDate_do_generic_server :\n    refined_raft_net_invariant_do_generic_server votedFor_moreUpToDate.\n  Proof using. \n    red. unfold votedFor_moreUpToDate. intros. simpl in *.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update_hyp; simpl in *; eauto;\n    find_apply_lem_hyp doGenericServer_log_type_term_votesReceived;\n    intuition; repeat find_rewrite; eauto.\n  Qed.\n\n  Lemma votedFor_moreUpToDate_reboot :\n    refined_raft_net_invariant_reboot votedFor_moreUpToDate.\n  Proof using. \n    red. unfold votedFor_moreUpToDate. intros. simpl in *.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    subst. repeat find_higher_order_rewrite.\n    destruct_update_hyp; simpl in *; eauto; congruence.\n  Qed.\n\n  Lemma votedFor_moreUpToDate_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset votedFor_moreUpToDate.\n  Proof using. \n    red. unfold votedFor_moreUpToDate. intros. simpl in *.\n    subst. repeat find_reverse_higher_order_rewrite.\n    eauto.\n  Qed.\n\n  Lemma votedFor_moreUpToDate_init :\n    refined_raft_net_invariant_init votedFor_moreUpToDate.\n  Proof using. \n    red. unfold votedFor_moreUpToDate. intros. simpl in *.\n    congruence.\n  Qed.\n  \n  Instance vfmutdi : votedFor_moreUpToDate_interface.\n  split.\n  intros.\n  apply refined_raft_net_invariant; auto.\n  - apply votedFor_moreUpToDate_init.\n  - apply votedFor_moreUpToDate_client_request.\n  - apply votedFor_moreUpToDate_timeout.\n  - apply votedFor_moreUpToDate_append_entries.\n  - apply votedFor_moreUpToDate_append_entries_reply.\n  - apply votedFor_moreUpToDate_request_vote.\n  - apply votedFor_moreUpToDate_request_vote_reply.\n  - apply votedFor_moreUpToDate_do_leader.\n  - apply votedFor_moreUpToDate_do_generic_server.\n  - apply votedFor_moreUpToDate_state_same_packet_subset.\n  - apply votedFor_moreUpToDate_reboot.\n  Qed.\n  \nEnd VotedForMoreUpToDate.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft-proofs/VotedForMoreUpToDateProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.20384883353157796}}
{"text": "(*\n * Copyright (c) 2020-2021 BedRock Systems, Inc.\n * This software is distributed under the terms of the BedRock Open-Source License.\n * See the LICENSE-BedRock file in the repository root for details.\n *)\nFrom elpi Require Import locker.\nFrom bedrock.prelude Require Import base.\nFrom bedrock.lang.cpp.syntax Require Import names expr stmt types typing.\nFrom bedrock.lang.cpp.semantics Require Import genv.\n\nDefinition GlobDecl_size_of (g : GlobDecl) : option N :=\n  match g with\n  | Gstruct s => Some s.(s_size)\n  | Gunion u => Some u.(u_size)\n  | Genum t _ =>\n    match drop_qualifiers t with\n    | Tchar_ sz => Some $ char_type.bytesN sz\n    | Tnum sz _ => Some $ bytesN sz\n    | Tbool => Some 1%N\n    | _ => None\n    end\n  | _ => None\n  end.\nDefinition GlobDecl_align_of (g : GlobDecl) : option N :=\n  match g with\n  | Gstruct s => Some s.(s_alignment)\n  | Gunion u => Some u.(u_alignment)\n  | Genum t _ =>\n    match drop_qualifiers t with\n    | Tchar_ sz => Some $ char_type.bytesN sz\n    | Tnum sz _ => Some $ bytesN sz\n    | Tbool => Some 1%N\n    | _ => None\n    end\n  | _ => None\n  end.\nVariant Roption_leq {T} (R : T -> T -> Prop) : option T -> option T -> Prop :=\n| Rleq_None {x} : Roption_leq R None x\n| Rleq_Some {x y} (_ : R x y) : Roption_leq R (Some x) (Some y).\n\n\n#[global] Instance proper_GlobDecl_size_of: Proper (GlobDecl_ler ==> Roption_leq eq) GlobDecl_size_of.\nProof.\n  rewrite /GlobDecl_size_of/GlobDecl_ler/GlobDecl_le => x y Heq.\n  do 2 case_match; subst; try contradiction; try constructor.\n  case_bool_decide; subst; eauto. contradiction.\n  case_bool_decide; subst; eauto. contradiction.\n  case_bool_decide; subst; eauto. case_match; constructor; eauto. contradiction.\nQed.\n#[global] Instance proper_GlobDecl_align_of: Proper (GlobDecl_ler ==> Roption_leq eq) GlobDecl_align_of.\nProof.\n  rewrite /GlobDecl_size_of/GlobDecl_ler/GlobDecl_le => x y Heq.\n  do 2 case_match; subst; try contradiction; try constructor.\n  case_bool_decide; subst; eauto. contradiction.\n  case_bool_decide; subst; eauto. contradiction.\n  case_bool_decide; subst; eauto. simpl. case_match; constructor; eauto. contradiction.\nQed.\n\n(** * sizeof() *)\n(** this is a partial implementation of [size_of] for primitives.\n *)\nFixpoint size_of (resolve : genv) (t : type) : option N :=\n  match t with\n  | Tpointer _ => Some (pointer_size resolve)\n  | Tref _ => None\n  | Trv_ref _ => None\n  | Tnum sz _ => Some (bytesN sz)\n  | Tchar_ ct => Some (char_type.bytesN ct)\n  | Tvoid => None\n  | Tarray t n => N.mul n <$> size_of resolve t\n  | Tnamed nm => glob_def resolve nm ≫= GlobDecl_size_of\n  | Tenum nm => glob_def resolve nm ≫= GlobDecl_size_of\n  | Tfunction _ _ => None\n  | Tbool => Some 1\n  | Tmember_pointer _ _ => None (* TODO these are not well supported right now *)\n  | Tqualified _ t => size_of resolve t\n  | Tnullptr => Some (pointer_size resolve)\n  | Tfloat sz => Some (bytesN sz)\n  | Tarch sz _ => bytesN <$> sz\n  end%N.\n\n#[global] Instance Proper_size_of\n  : Proper (genv_leq ==> eq ==> Roption_leq eq) (@size_of).\nProof.\n  intros ?? Hle ? t ->; induction t; simpl; (try constructor) => //.\n  all: try exact: pointer_size_proper.\n  - by destruct IHt; constructor; subst.\n  - move: Hle => [[ /(_ g) Hle _] _ _].\n    unfold glob_def. rewrite -tu_lookup_globals in Hle.\n    destruct ((genv_tu x) !! g) as [g1| ]; last constructor.\n    move: Hle => /(_ _ eq_refl). rewrite -tu_lookup_globals.\n    move => [g2 [-> HH]] /=.\n    exact: proper_GlobDecl_size_of.\n  - move: Hle => [[ /(_ g) Hle _] _ _].\n    unfold glob_def. rewrite -tu_lookup_globals in Hle.\n    destruct ((genv_tu x) !! g) as [g1| ]; last constructor.\n    move: Hle => /(_ _ eq_refl). rewrite -tu_lookup_globals.\n    move => [g2 [-> HH]] /=.\n    exact: proper_GlobDecl_size_of.\n  - by destruct o; constructor.\nQed.\n\nTheorem size_of_int : forall {c : genv} s w,\n    @size_of c (Tnum w s) = Some (bytesN w).\nProof. reflexivity. Qed.\nTheorem size_of_char : forall {c : genv} s,\n    @size_of c (Tchar_ s) = Some (char_type.bytesN s).\nProof. reflexivity. Qed.\nTheorem size_of_bool : forall {c : genv},\n    @size_of c Tbool = Some 1%N.\nProof. reflexivity. Qed.\nTheorem size_of_pointer : forall {c : genv} t,\n    @size_of c (Tpointer t) = Some (pointer_size c).\nProof. reflexivity. Qed.\nTheorem size_of_qualified : forall {c : genv} t q,\n    @size_of c t = @size_of c (Tqualified q t).\nProof. reflexivity. Qed.\nTheorem size_of_array_0 : forall {c : genv} t sz,\n    @size_of c t = Some sz ->\n    @size_of c (Tarray t 0) = Some 0%N.\nProof. intros; simpl. by rewrite H. Qed.\n\nTheorem size_of_array_shatter : forall {c : genv} ty n sz,\n    @size_of c (Tarray ty n) = Some sz <-> exists sz', (sz = n * sz')%N /\\ @size_of c ty = Some sz' /\\ @size_of c (Tarray ty n) = Some (n * sz')%N.\nProof.\n  simpl. intros. destruct (size_of c ty) => /=; split; intros H.\n  - inversion H; subst; eauto.\n  - by destruct H as [? [? [H1 H2]]]; inversion H1; inversion H2; subst.\n  - by inversion H.\n  - by destruct H as [? [? [? ?]]]; discriminate.\nQed.\n\nTheorem size_of_array_pos : forall {c : genv} t n sz,\n    (0 < n)%N ->\n    @size_of c t = Some sz <-> @size_of c (Tarray t n) = Some (n * sz)%N.\nProof.\n  simpl. intros. destruct (size_of c t) => /=; split; try congruence.\n  inversion 1. f_equal. apply N.mul_cancel_l in H2.  auto. lia.\nQed.\n\nTheorem size_of_array : forall {c : genv} t n sz,\n    @size_of c t = Some sz -> @size_of c (Tarray t n) = Some (n * sz)%N.\nProof.\n  simpl. intros. destruct (size_of c t) => /=; try congruence.\nQed.\n\nLemma size_of_Qmut : forall {c} t,\n    @size_of c t = @size_of c (Qmut t).\nProof. reflexivity. Qed.\n\nLemma size_of_Qconst : forall {c} t ,\n    @size_of c t = @size_of c (Qconst t).\nProof. reflexivity. Qed.\n\n(* XXX: since size_of simplifies eagerly, this might be hard to apply, so you\nmight need to inline the proof. *)\nLemma size_of_genv_compat tu σ gn st\n      (Hσ : tu ⊧ σ)\n      (Hl : tu !! gn = Some (Gstruct st)) :\n  size_of σ (Tnamed gn) = GlobDecl_size_of (Gstruct st).\nProof. by rewrite /= (glob_def_genv_compat_struct st Hl). Qed.\n\nLemma size_of_erase_qualifiers σ ty :\n  size_of σ (erase_qualifiers ty) = size_of σ ty.\nProof. induction ty => //=. by rewrite IHty. Qed.\nLemma size_of_drop_qualifiers σ ty :\n  size_of σ (drop_qualifiers ty) = size_of σ ty.\nProof. by induction ty. Qed.\n\n(** [SizeOf ty n] means that C++ type [ty] has size [n] bytes *)\nClass SizeOf {σ : genv} (ty : type) (n : N) : Prop :=\n  size_of_spec : size_of σ ty = Some n.\n#[global] Hint Mode SizeOf - + - : typeclass_instances.\n\n#[global] Instance SizeOf_mono :\n  Proper (genv_leq ==> eq ==> eq ==> impl) (@SizeOf).\nProof.\n  rewrite /SizeOf=>σ1 σ2 Hσ t1 t2 Ht n ? <- ?.\n  by destruct (Proper_size_of _ _ Hσ _ _ Ht); simplify_eq.\nQed.\n\n#[global] Instance array_size_of {σ : genv} ty a n b :\n  SizeOf ty a ->\n  TCEq (n * a)%N b ->\n  SizeOf (Tarray ty n) b.\nProof.\n  rewrite /SizeOf TCEq_eq=>Hty <-.\n  cbn. by rewrite Hty.\nQed.\n\n#[global] Instance named_struct_size_of tu σ gn st n :\n  genv_compat tu σ ->\n  TCEq (tu !! gn) (Some (Gstruct st)) ->\n  TCEq st.(s_size) n ->\n  SizeOf (Tnamed gn) n.\nProof.\n  rewrite /SizeOf !TCEq_eq=>? /glob_def_genv_compat_struct Htu <-.\n  cbn. by rewrite Htu.\nQed.\n\n#[global] Instance named_union_size_of tu σ gn u n :\n  genv_compat tu σ ->\n  TCEq (tu !! gn) (Some (Gunion u)) ->\n  TCEq u.(u_size) n ->\n  SizeOf (Tnamed gn) n.\nProof.\n  rewrite /SizeOf !TCEq_eq=>? /glob_def_genv_compat_union Htu <-.\n  cbn. by rewrite Htu.\nQed.\n\n#[global] Instance bool_size_of {σ : genv} : SizeOf Tbool 1.\nProof. done. Qed.\n\n(* TODO?: consider using [SizeOf (Tnum sz sgn) (bytesN sz)]. *)\n#[global] Instance int_size_of {σ : genv} sz sgn n :\n  TCEq (bytesN sz) n -> SizeOf (Tnum sz sgn) n.\nProof. by rewrite /SizeOf TCEq_eq=><-. Qed.\n\n(* TODO?: consider using [SizeOf (Tnum sz sgn) (char_type.bytesN ct)]. *)\n#[global] Instance char_size_of {σ' : genv} ct n :\n  TCEq (char_type.bytesN ct) n -> SizeOf (Tchar_ ct) n.\nProof. by rewrite /SizeOf TCEq_eq=><-. Qed.\n\n#[global] Instance qualified_size_of {σ : genv} qual ty n :\n  SizeOf ty n -> SizeOf (Tqualified qual ty) n.\nProof. done. Qed.\n\n#[global] Instance ptr_size_of {σ : genv} ty n :\n  TCEq (pointer_size σ) n -> SizeOf (Tptr ty) n.\nProof. by rewrite /SizeOf TCEq_eq=><-. Qed.\n\n#[global] Instance arch_size_of {σ : genv} sz name n :\n  TCEq (bytesN sz) n -> SizeOf (Tarch (Some sz) name) n.\nProof. by rewrite /SizeOf TCEq_eq=><-. Qed.\n\n(** [HasSize ty] means that C++ type [ty] has a defined size *)\nClass HasSize {σ : genv} (ty : type) : Prop :=\n  has_size : is_Some (size_of σ ty).\n#[global] Hint Mode HasSize - + : typeclass_instances.\n#[global] Arguments has_size {_} _ {_} : assert.\n\n#[global] Instance HasSize_mono :\n  Proper (genv_leq ==> eq ==> impl) (@HasSize).\nProof.\n  rewrite /HasSize=>σ1 σ2 Hσ t1 t2 Ht H.\n  destruct (Proper_size_of _ _ Hσ _ _ Ht).\n  - exfalso. exact: is_Some_None.\n  - by simplify_eq.\nQed.\n\n#[global] Instance size_of_has_size {σ : genv} ty n :\n  SizeOf ty n -> HasSize ty.\nProof.\n  intros. rewrite /HasSize size_of_spec. by eexists.\nQed.\n\n(** [sizeof ty : N] is the size of C++ type [ty] (if it has a size) *)\nDefinition sizeof {σ : genv} (ty : type) `{!HasSize ty} : N :=\n  is_Some_proj (has_size ty).\n\nLemma sizeof_spec {σ : genv} ty `{Hsz : !HasSize ty} :\n  size_of σ ty = Some (sizeof ty).\nProof.\n  rewrite/sizeof/has_size. by destruct Hsz as [sz ->].\nQed.\n\n(** [offset_of] *)\n\nFixpoint find_assoc_list {T} (f : ident) (fs : list (ident * T)) : option T :=\n  match fs with\n  | nil => None\n  | (f',v) :: fs =>\n    if decide (f = f') then\n      Some v\n    else find_assoc_list f fs\n  end%list.\n\nLemma find_assoc_list_elem_of {T} base xs :\n  (∃ v, (base, v) ∈ xs) ->\n  ∃ y, find_assoc_list (T := T) base xs = Some y.\nProof.\n  move=>[v]. elim: xs => /= [/elem_of_nil //|[k w] xs IH]\n    /elem_of_cons [|] Hin; simplify_eq.\n  { rewrite decide_True; eauto. }\n  case_decide; eauto.\nQed.\n\n#[local] Close Scope nat_scope.\n#[local] Open Scope Z_scope.\n(* note: we expose the fact that reference fields are compiled to pointers,\n   so the [offset_of] a reference field is the offset of the pointer.\n *)\nDefinition offset_of (resolve : genv) (t : globname) (f : ident) : option Z :=\n  match glob_def resolve t with\n  | Some (Gstruct s) =>\n    find_assoc_list f (List.map (fun m => (m.(mem_name),m.(mem_layout).(li_offset) / 8)) s.(s_fields))\n  | Some (Gunion u) =>\n    find_assoc_list f (List.map (fun m => (m.(mem_name),m.(mem_layout).(li_offset) / 8)) u.(u_fields))\n  | _ => None\n  end.\n\nDefinition parent_offset_tu (tu : translation_unit) (derived : globname) (base : globname) : option Z :=\n  match tu !! derived with\n  | Some (Gstruct s) => find_assoc_list base (List.map (fun '(s,l) => (s,l.(li_offset) / 8)) s.(s_bases))\n  | _ => None\n  end.\n(* We hide whether [genv_tu] exists. *)\nmlock Definition parent_offset σ derived base := parent_offset_tu σ.(genv_tu) derived base.\nNotation directly_derives_tu tu derived base := (is_Some (parent_offset_tu tu derived base)).\nNotation directly_derives σ derived base := (is_Some (parent_offset σ derived base)).\n\nLemma find_assoc_list_parent_offset tu derived st base li :\n  tu !! derived = Some (Gstruct st) ->\n  (base, li) ∈ st.(s_bases) ->\n  ∃ z, parent_offset_tu tu derived base = Some z.\nProof.\n  rewrite /parent_offset_tu => -> Hin.\n  apply /find_assoc_list_elem_of.\n  eexists; apply /elem_of_list_fmap; by exists (base, li).\nQed.\n\nLemma parent_offset_genv_compat {σ tu derived base z} {Hσ : tu ⊧ σ} :\n  parent_offset_tu tu derived base = Some z ->\n  parent_offset σ derived base = Some z.\nProof.\n  rewrite parent_offset.unlock /parent_offset_tu -/(glob_def σ derived).\n  case E: (tu !! derived) => [ gd //= | // ]; destruct gd => //.\n  by erewrite glob_def_genv_compat_struct.\nQed.\n\n(** * alignof() *)\nParameter align_of : forall {resolve : genv} (t : type), option N.\nAxiom align_of_named : ∀ {σ : genv} (nm : globname),\n  align_of (Tnamed nm) =\n  glob_def σ nm ≫= GlobDecl_align_of.\n\n(** If [size_of] is defined, [align_of] must divide [size_of]. *)\nAxiom align_of_size_of' : forall {σ : genv} (t : type) sz,\n    size_of σ t = Some sz ->\n    (exists al, align_of t = Some al /\\ al <> 0 /\\ (al | sz))%N.\n\nLemma align_of_size_of {σ : genv} (t : type) sz :\n    size_of σ t = Some sz ->\n    exists al, align_of t = Some al /\\\n          (* size is a multiple of alignment *)\n          (sz mod al = 0)%N.\nProof.\n  move=>/align_of_size_of' [al [? [? /N.mod_divide ?]]].\n  eauto.\nQed.\n\nAxiom align_of_array : forall {σ : genv} (ty : type) n,\n    align_of (Tarray ty n) = align_of ty.\nAxiom align_of_qualified : ∀ σ t q,\n    align_of (resolve:=σ) (Tqualified q t) = align_of (resolve:=σ) t.\n\nAxiom Proper_align_of : Proper (genv_leq ==> eq ==> Roption_leq eq) (@align_of).\n#[global] Existing Instance Proper_align_of.\n\nLemma align_of_genv_compat tu σ gn st\n      (Hσ : tu ⊧ σ)\n      (Hl : tu !! gn = Some (Gstruct st)) :\n  align_of (Tnamed gn) = GlobDecl_align_of (Gstruct st).\nProof. by rewrite /= align_of_named (glob_def_genv_compat_struct st Hl). Qed.\n", "meta": {"author": "bedrocksystems", "repo": "BRiCk", "sha": "23d7e64cc53706de608dbff0be75d1c4b8c3a7ec", "save_path": "github-repos/coq/bedrocksystems-BRiCk", "path": "github-repos/coq/bedrocksystems-BRiCk/BRiCk-23d7e64cc53706de608dbff0be75d1c4b8c3a7ec/theories/lang/cpp/semantics/types.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.20384883353157796}}
{"text": "(* Borrowed from CompCert *)\n(* Modified to fit your screen *)\n\nRequire Import Relations.\nRequire Import Wellfounded.\nRequire Import compcert.lib.Coqlib.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.lib.Integers.\nGlobal Unset Asymmetric Patterns.\n\nRequire Import StructTact.StructTactics.\nRequire Import StructTact.Util.\n\nRequire Import oeuf.EricTact.\nRequire Import oeuf.StuartTact.\n\nRequire Import oeuf.AllValues.\nRequire Import oeuf.MatchValues.\n\nRequire oeuf.FullSemantics.\n\nSet Default Timeout 15.\nSet Implicit Arguments.\n\n\nDefinition nostep := FullSemantics.nostep.\nDefinition star := FullSemantics.star.\nDefinition plus := FullSemantics.plus.\n\nDefinition semantics := FullSemantics.semantics.\nDefinition Semantics_gen := FullSemantics.Semantics_gen.\nDefinition state := FullSemantics.state.\nDefinition genvtype := FullSemantics.genvtype.\nDefinition val_level  := FullSemantics.val_level .\nDefinition valtype  := FullSemantics.valtype .\nDefinition is_callstate  := FullSemantics.is_callstate .\nDefinition step  := FullSemantics.step .\nDefinition final_state := FullSemantics.final_state.\nDefinition globalenv := FullSemantics.globalenv.\nDefinition Semantics {state funtype vartype val_level}\n        step is_callstate final_state globalenv :=\n    @FullSemantics.Semantics state funtype vartype val_level\n        step is_callstate final_state globalenv.\n\nNotation \" 'Step' L \" := (step L (globalenv L)) (at level 1).\nNotation \" 'Star' L \" := (star (step L) (globalenv L)) (at level 1).\nNotation \" 'Plus' L \" := (plus (step L) (globalenv L)) (at level 1).\n\nDefinition forward_simulation L1 L2 :=\n    forall M, FullSemantics.forward_simulation L1 L2 M.\n\n\n\n\nSection FORWARD_SIMU_DIAGRAMS.\n\nVariable L1: semantics.\nVariable L2: semantics.\n\n(*Hypothesis public_preserved:\n  forall id, Senv.public_symbol (symbolenv L2) id = Senv.public_symbol (symbolenv L1) id. *)\n\nVariable match_states: state L1 -> state L2 -> Prop.\nVariable match_values: valtype L1 -> valtype L2 -> Prop.\n\nHypothesis match_callstate :\n      forall fv1 av1 fv2 av2 s2,\n        is_callstate L2 fv2 av2 s2 ->\n        match_values fv1 fv2 ->\n        match_values av1 av2 ->\n        exists s1,\n          match_states s1 s2 /\\\n          is_callstate L1 fv1 av1 s1.\n\n\nHypothesis match_final_states:\n  forall s1 s2 v,\n  match_states s1 s2 ->\n  final_state L1 s1 v ->\n  exists v',\n    final_state L2 s2 v' /\\ match_values v v'.\n\nHypothesis fsim_val_level_le :\n    value_level_le (val_level L1) (val_level L2).\n\nHypothesis match_val_canon :\n    forall v1 v2,\n    match_values v1 v2 <->\n    value_match (val_level L1) (val_level L2) v1 v2.\n\n\nLemma trace_value_level_le : value_level_le_indexed (val_level L1) (val_level L2).\neapply value_level_le_add_index; eauto.\nQed.\n\nLemma trace_match_val_canon : forall M v1 v2,\n    match_values v1 v2 <->\n    value_match_indexed M (val_level L1) (val_level L2) v1 v2.\nintros. rewrite <- value_match_add_index_iff; eauto.\nQed.\n\n\nSection SIMULATION_STAR_WF.\n\n(** [order] is a well-founded ordering associated with states\n  of the first semantics.  Stuttering steps must correspond\n  to states that decrease w.r.t. [order]. *)\n\nVariable order: state L1 -> state L1 -> Prop.\nHypothesis order_wf: well_founded order.\n\nHypothesis simulation:\n  forall s1 t s1', Step L1 s1 t s1' ->\n  forall s2, match_states s1 s2 ->\n  exists s2',\n  (Plus L2 s2 t s2' \\/ (Star L2 s2 t s2' /\\ order s1' s1))\n  /\\ match_states s1' s2'.\n\n\nLemma forward_simulation_star_wf: forward_simulation L1 L2.\nProof.\n  intro M. eapply FullSemantics.forward_simulation_star_wf with\n    (order := order)\n    (match_values := match_values)\n    (match_states := match_states);\n  eauto using trace_value_level_le, trace_match_val_canon.\nQed.\n\nEnd SIMULATION_STAR_WF.\n\nSection SIMULATION_STAR.\n\n(** We now consider the case where we have a nonnegative integer measure\n  associated with states of the first semantics.  It must decrease when we take\n  a stuttering step. *)\n\nVariable measure: state L1 -> nat.\n\nHypothesis simulation:\n  forall s1 t s1', Step L1 s1 t s1' ->\n  forall s2, match_states s1 s2 ->\n  (exists s2', Plus L2 s2 t s2' /\\ match_states s1' s2')\n  \\/ (measure s1' < measure s1 /\\ t = E0 /\\ match_states s1' s2)%nat.\n\nLemma forward_simulation_star: forward_simulation L1 L2.\nProof.\n  intro M. eapply FullSemantics.forward_simulation_star with\n    (measure := measure)\n    (match_values := match_values)\n    (match_states := match_states);\n  eauto using trace_value_level_le, trace_match_val_canon.\nQed.\n\nEnd SIMULATION_STAR.\n\n(** Simulation when one transition in the first program corresponds\n    to one or several transitions in the second program. *)\n\nSection SIMULATION_PLUS.\n\nHypothesis simulation:\n  forall s1 t s1', Step L1 s1 t s1' ->\n  forall s2, match_states s1 s2 ->\n  exists s2', Plus L2 s2 t s2' /\\ match_states s1' s2'.\n\nLemma forward_simulation_plus: forward_simulation L1 L2.\nProof.\n  intro M. eapply FullSemantics.forward_simulation_plus with\n    (match_values := match_values)\n    (match_states := match_states);\n  eauto using trace_value_level_le, trace_match_val_canon.\nQed.\n\nEnd SIMULATION_PLUS.\n\n(** Lock-step simulation: each transition in the first semantics\n    corresponds to exactly one transition in the second semantics. *)\n\nSection SIMULATION_STEP.\n\nHypothesis simulation:\n  forall s1 t s1', Step L1 s1 t s1' ->\n  forall s2, match_states s1 s2 ->\n  exists s2', Step L2 s2 t s2' /\\ match_states s1' s2'.\n\nLemma forward_simulation_step: forward_simulation L1 L2.\nProof.\n  intro M. eapply FullSemantics.forward_simulation_step with\n    (match_values := match_values)\n    (match_states := match_states);\n  eauto using trace_value_level_le, trace_match_val_canon.\nQed.\n\nEnd SIMULATION_STEP.\n\n(** Simulation when one transition in the first program\n    corresponds to zero or one transitions in the second program.\n    However, there is no stuttering: infinitely many transitions\n    in the source program must correspond to infinitely many\n    transitions in the second program. *)\n\nSection SIMULATION_OPT.\n\nVariable measure: state L1 -> nat.\n\nHypothesis simulation:\n  forall s1 t s1', Step L1 s1 t s1' ->\n  forall s2, match_states s1 s2 ->\n  (exists s2', Step L2 s2 t s2' /\\ match_states s1' s2')\n  \\/ (measure s1' < measure s1 /\\ t = E0 /\\ match_states s1' s2)%nat.\n\nLemma forward_simulation_opt: forward_simulation L1 L2.\nProof.\n  intro M. eapply FullSemantics.forward_simulation_opt with\n    (match_values := match_values)\n    (match_states := match_states);\n  eauto using trace_value_level_le, trace_match_val_canon.\nQed.\n\nEnd SIMULATION_OPT.\n\nEnd FORWARD_SIMU_DIAGRAMS.\n\n\n\nDefinition receptive L := FullSemantics.receptive L.\nDefinition determinate L := FullSemantics.determinate L.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/TraceSemantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.2038488318972929}}
{"text": "From mathcomp Require Import\n     all_ssreflect.\n\nFrom AUChain\n     Require Import\n     BlockTree\n     Blocks\n     Messages\n     Parameters\n     LocalState\n     StateMonad.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\n(** * Protocol\n      Execution plan for each party pr. round:\n      This consists of two parts:\n\n      1) Recieve and process messages:\n         - Recieve messages for this party and extend the blocktree with the\n           received blocks.\n  \n      2) Execute consensus algorithm:\n         - Check if leader.\n         - If leader then bake block and add return messages that has to be submitted.\n **)\n\nSection Protocol.\n\n  Definition extend_tree_l (l: LocalState) (b : Block) : LocalState  :=\n    mkLocalState (pk l) (extendTree (tree l) b). \n\n  Definition process_msg (m: Message) (l: LocalState) : LocalState :=\n    let: BlockMsg b := m in extend_tree_l l b. \n\n  Definition process_msgs (msgs: Messages) : State LocalState unit :=\n    modify (fun l => foldr process_msg l msgs).\n\n  (* Notice that if a party actually bakes a block it will be added\n     directly to the blocktree of this party. *)\n  Definition honest_bake (sl : Slot) (txs : Transactions) : State LocalState Messages :=\n    local_state <- get;\n    if Winner (pk local_state) sl\n    then let: bestChain := bestChain (sl-1) (tree local_state) in\n         let: hashPrev := HashB (head GenesisBlock bestChain) in\n         let: newBlock := MkBlock sl txs hashPrev (pk local_state) in\n         modify (fun l => extend_tree_l l newBlock);;\n         pure [:: BlockMsg newBlock]\n    else pure [::].\n\n  Definition honest_rcv (msgs : Messages) (sl : Slot) : State LocalState unit :=\n    process_msgs msgs.\n\nEnd Protocol.\n", "meta": {"author": "AU-COBRA", "repo": "PoS-NSB", "sha": "8cb62e382f17626150a4b75e44af4d270474d3e7", "save_path": "github-repos/coq/AU-COBRA-PoS-NSB", "path": "github-repos/coq/AU-COBRA-PoS-NSB/PoS-NSB-8cb62e382f17626150a4b75e44af4d270474d3e7/Protocol/Protocol.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.2038488242453192}}
{"text": "(** FreeSpec is a general-purpose framework for implementing (with a Free monad)\n    and certifying (with contracts) impure computations. In this tutorial, we\n    will use FreeSpec to implement and certify a webserver we call\n    <<MiniHTTPServer>>. Our goal is to prove our HTTP server correctly uses the\n    filesystem, that is it reads from and closes valid file descriptors, and\n    closes all its file descriptors.\n\n    The [FreeSpec.Core] module reexports the key component provided by\n    FreeSpec. *)\n\nGeneralizable All Variables.\n\nFrom Coq Require Import String.\nFrom FreeSpec Require Import Core.\n\n(** * I. Implementation *)\n\n(** FreeSpec provides the [impure] monad to implement impure computations. This\n    monad is equipped with the necessary notations to write idiomatic momadic\n    code, thanks to the same notations as the ones introduced in recent versions\n    of OCaml.\n\n    The [impure] type takes two parameters respectively of type [interface] and\n    [Type]:\n\n      - An interface is a parameterized inductive type, whose constructors\n        identify impure primitives. For an interface [i], a term of type [i a]\n        identifies a primitive which produces a term of type [a]. An impure\n        computation of type [impure i a] can leverage primitives of the\n        interface [i].\n      - The second parameter of [impure] is the type of result returned by the\n        impure computation. Therefore, an impure computation of type [impure i a]\n        is expected to produce a result of type [a]. *)\n\n(** ** I.1 Defining Interfaces *)\n\n(** An [interface] is a parameterized inductive type whose constructors identify\n    impure primitives.\n\n    For our server, we anticipate the use of three “kinds” of primitives to:\n\n      - Create and manipulate TCP sockets\n      - Interact with the filesystem\n      - Interact with the console\n\n    Since an impure computation can use _several_ interfaces, FreeSpec favors\n    defining independent primitives as part of different interfaces. In our\n    case, this means we will have three different interfaces.\n\n    In practice, FreeSpec users do not defined their interface\n    manually, but rather generate them.  To that end, we use\n    <<coqffi>>. *)\n\n(** *** The TCP Interface *)\n\nFrom MiniHTTPServerFFI Require Import TCP.\n\n(** *** The FILESYSTEM Interface *)\n\nFrom MiniHTTPServerFFI Require Import FileSystem.\n\n(** *** The CONSOLE Interface *)\n\nFrom MiniHTTPServerFFI Require Import Console.\n\n(** ** I.2. Implementing a HTTP Server *)\n\n(** With the three interfaces we have defined in the previous section, we can\n    now implement <<MiniHTTPServer>>, that is a minimal HTTP server. Our\n    objective is to write a code as idiomatic as possible.\n\n    To that end, we rely on the <<coq-ext-lib>> package, and therefore\n    import it. *)\n\nImport List.ListNotations.\nFrom ExtLib Require Import Monad Functor.\nImport MonadLetNotation FunctorNotation.\nFrom CoqFFI Require Import String.\n\n(** *** A Word on Non-Termination *)\n\n(** As Coq users know, Gallina only allows to implement strictly recursive\n    functions, which means a function in Coq will always terminate. A webserver,\n    on the other hand, is expected to run as long as incoming connections\n    arrive.  FreeSpec will eventually deal with non-termination, but this has\n    not been our priority just yet. In the context of this tutorial, we\n    compromise and <<MiniHTTPServer>> will therefore only accept a finite number\n    of connections. However, we show that it is correct for any number of finite\n    steps.\n\n    To implement this behavior, we introduce [repeatM], which repeats an impure\n    computation [n] times. *)\n\nFixpoint repeatM {m : Type -> Type} `{Monad m} {a} (n : nat) (p : m a) : m unit :=\n  match n with\n  | O => ret tt\n  | S n => p;; repeatM n p\n  end.\n\n(** *** A Generic TCP Server *)\n\n(** We first define a generic TCP Server as an impure computation parameterized\n    by a so-called handler, that is an impure computation which computes a\n    response message for each request message received from a client. *)\n\nFrom FreeSpec.FFI Require Import FFI.\n\nDefinition tcp_server `{Monad m, MonadTCP m}\n    (n : nat) (handler : string -> m string)\n  : m unit :=\n  let* server := new_tcp_socket \"127.0.0.1:8088\" in\n  listen_incoming_connection server;;\n\n  repeatM n (let* client := accept_connection server in\n\n             let* req := read_socket client in\n             let* res := handler req in\n             write_socket client res;;\n\n             close_tcp_socket client);;\n\n  close_tcp_socket server.\n\n(** *** A HTTP Handler *)\n\n(** <<MiniHTTPServer>> is a minimal server which serves static files over HTTP.\n    The main task of its handler will perform is therefore to fetch the content\n    of a file identified by a given path. To implement this behavior, we define\n    an impure computation [read_content], which performs some logging in\n    addition to interacting with the file system.\n\n    As such, [read_content] uses two interfaces. We can specify that thanks to\n    [Provide], for instance with [`{Provide ix CONSOLE, Provide ix FILESYSTEM}].\n    FreeSpec provides [Provide2], [Provide3], [Provide4], and [Provide5] to make\n    the type more readable. *)\n\nDefinition read_content `{Monad m, MonadFileSystem m, MonadConsole m}\n    (path : string)\n  : m string :=\n  echo (\"  reading <\" ++ path ++ \">... \");;\n  let* fd := open_file path in\n  let* c := read_file fd in\n  close_file fd;;\n  echo \"done.\\n\";;\n  ret c.\n\n(** Using this utility function, we can define the handler itself.\n\n    The parsing of the incoming HTTP requests, and the serialization of HTTP\n    response have been implemented in Coq, but are not relevant in this\n    tutorial. They are provided inside the <<coq-MiniHTTPServer>> and we reuse\n    them. *)\n\nFrom MiniHTTPServer Require Import URI HTTP.\n\n(** This provides the following types and functions:\n\n      - [http_req] encodes the supported HTTP requests (currently, only GET\n        requests are supported).\n      - [http_request] a parsing function of the form [bytes -> error_stack +\n        http_req]\n      - [http_res] encodes the HTTP responses used by MiniHTTPServer (in our\n        case, 200, 401, and 404)\n      - [response_to_string] to serialize a response as a valid HTTP string. *)\n\nDefinition request_handler `{Monad m, MonadFileSystem m, MonadConsole m}\n    (base : list directory_id) (req : request)\n  : m response :=\n  match req with\n  | Get uri =>\n    let path := uri_to_path (sandbox base uri) in\n    let* isf := file_exists path in\n    if (isf : bool)\n    then let* content := read_content path in\n         ret (make_response success_OK content)\n    else echo (\"  resource <\" ++ path ++\"> not found\\n\");;\n         ret (make_response client_error_NotFound \"Resource not found.\")\n  end.\n\nFrom ExtLib Require Import StateMonad.\n\nDefinition http_handler `{Monad m, MonadFileSystem m, MonadConsole m}\n    (base : list directory_id) (req : string)\n  : m string :=\n  echo \"new request received\\n\";;\n  echo (\"  request size is \" ++ StrExt.of_int (StrExt.length req) ++ \"\\n\");;\n\n  let* res := match runStateT http_request (Slice.of_string req) with\n              | inr req => request_handler base (fst req)\n              | _ => ret (make_response client_error_BadRequest \"Bad request\")\n              end in\n\n  ret (response_to_string res).\n\n(** Since [read_content] uses the [CONSOLE] interface in addition to\n    [FILESYSTEM], our [http_handler] type exposes this explicitely. However,\n    [http_handler] does not use the [TCP] interface itself, and therefore the\n    [TCP] interface does not appear inside its type even if in practice it will\n    be used in a context where [TCP] is available.\n\n    [http_server] is the final function, the [tcp_server] is specialized with\n    our [http_handler]. As a consequence, the type of [http_server] exposes the\n    three interfaces we use. *)\n\nDefinition http_server `{Monad m, MonadFileSystem m, MonadTCP m, MonadConsole m} (n : nat)\n  : m unit :=\n  echo \"hello, MiniHTTPServer!\\n\";;\n  tcp_server n (http_handler [Dirname (Slice.of_string \"tmp\")]).\n\n(** * II. Certifying *)\n\n(** As a reminder, our goal is to prove our HTTP server correctly use the\n    filesystem, that is it reads from and closes valid file descriptors, and\n    closes all its file descriptors. To that end, we need to define a contract\n    for the [FILESYSTEM] interface, then reason about [http_server] executions\n    w.r.t. this contract. *)\n\n(** ** II.1. Defining a Contract *)\n\nFrom FreeSpec.Core Require Import CoreFacts.\n\n(** Defining a contract for an interface in FreeSpec means specifying how an\n    interface shall be used, but also what to expect from the results of its\n    primitives. *)\n\n(** *** The Witness State Type and Helpers *)\n\n(** A contract in FreeSpec has a so-called witness state attached to it. It\n    allows to take into account the stateful nature of impure computations and\n    primitives implementers. More precisely, a primitive of an interface which\n    could be used at a given time may become forbidden in the future.\n\n    This is precisely the case with our use case: a valid file descriptor\n    becomes invalid once it has been used as an arguent of the [Close]\n    primitive. Witness states shall be as simple as possible, and only holds the\n    minimum amount of information about past executed primitives. In our case,\n    the witness state can be as simple as a set of open file descriptors. *)\n\nDefinition fd_set : Type := file -> bool.\n\n(** In addition, we provide the usuals helpers to manipulate (addition,\n    deletion) and reason about sets. *)\n\nAxiom fd_eq_dec : forall (fd1 fd2 : file), { fd1 = fd2 } + { ~ (fd1 = fd2) }.\n\nDefinition add_fd (ω : fd_set) (fd : file) : fd_set :=\n  fun (fd' : file) => if fd_eq_dec fd fd' then true else ω fd'.\n\nDefinition del_fd (ω : fd_set) (fd : file) : fd_set :=\n  fun (fd' : file) => if fd_eq_dec fd fd' then false else ω fd'.\n\nDefinition member (ω : fd_set) (fd : file) : Prop :=\n  ω fd = true.\n\nDefinition absent (ω : fd_set) (fd : file) : Prop :=\n  ω fd = false.\n\nLemma member_not_absent (ω : fd_set) (fd : file)\n  : member ω fd -> ~ absent ω fd.\n\nProof.\n  unfold member, absent.\n  intros m a.\n  now rewrite m in a.\nQed.\n\n#[global] Hint Resolve member_not_absent : minihttp.\n\nLemma absent_not_member (ω : fd_set) (fd : file)\n  : absent ω fd -> ~ member ω fd.\n\nProof.\n  unfold member, absent.\n  intros a m.\n  now rewrite m in a.\nQed.\n\n#[global] Hint Resolve absent_not_member : minihttp.\n\nLemma member_add_fd (ω : fd_set) (fd : file) : member (add_fd ω fd) fd.\n\nProof.\n  unfold member, add_fd.\n  destruct fd_eq_dec; auto.\nQed.\n\n#[global] Hint Resolve member_add_fd : minihttp.\n\n(** *** The Update Function *)\n\n(** In FreeSpec, a contract provides a so-called “update function” to be used to\n    reason about an interface usage over time. At any computation step requiring\n    the use of a primitive, the “current” witness state is used to determine\n    both the caller and the callee obligations. Then, the update function is\n    used to update the witness state to take into account what happened for\n    future primitives execution.\n\n    In our case, since the witness state is just a set of open file descriptors\n    and does not hold any information about e.g. file actual content, the update\n    function remains simple: we add newly open file descriptor after [Open], and\n    remove them after [Close]. *)\n\nDefinition fd_set_update (ω : fd_set) (a : Type) (e : FILESYSTEM a) (x : a) : fd_set :=\n  match e, x with\n  | Open_file _, fd =>\n    add_fd ω fd\n  | Close_file fd, _ =>\n    del_fd ω fd\n  | Read_file _, _ =>\n    ω\n  | File_exists _, _ =>\n    ω\n  end.\n\n(** *** The Caller Obligations *)\n\n(** Our experience with FreeSpec has tended to show that using inductive types\n    for obligations is the more convenient approach in practice, but this comes\n    with a tradeoff in terms of readability. *)\n\nInductive fd_set_caller_obligation (ω : fd_set)\n  : forall (a : Type), FILESYSTEM a -> Prop :=\n\n(** We do not restrict the use of [Open] or [FileExists] *)\n\n| fd_set_open_caller (p : string)\n  : fd_set_caller_obligation ω file (Open_file p)\n| fd_set_is_file_caller (p : string)\n  : fd_set_caller_obligation ω bool (File_exists p)\n\n(** In order for [Read] and [Close] to be used correctly, their\n    [file] argument has to be a member of the witness state. *)\n\n| fd_set_read_caller (fd : file)\n    (is_member : member ω fd)\n  : fd_set_caller_obligation ω string (Read_file fd)\n| fd_set_close_caller (fd : file)\n    (is_member : member ω fd)\n  : fd_set_caller_obligation ω unit (Close_file fd).\n\n#[global] Hint Constructors fd_set_caller_obligation : minihttp.\n\n(** *** The Callee Obligations *)\n\n(** The callee obligations of our contract are not as straightforward as the\n    caller obligations. It appears that we could potentially require nothing\n    special from a [FILESYSTEM] implementer for our particular use case. There\n    is, however, one scenario that we want to avoid in practice:\n\n      - The caller opens two different files\n      - The callee returns the same file descriptor for both files\n      - the caller closes one file descriptor, and uses the second one\n\n    In such a scenario, the caller misuses the interface in good faith. To avoid\n    this, we require the [Open] primitives to return _fresh_ file\n    descriptors. *)\n\nInductive fd_set_callee_obligation (ω : fd_set)\n  : forall (a : Type), FILESYSTEM a -> a -> Prop :=\n\n(** The [file] returned by the [Open] primitive shall not be a member\n    of the witness state. *)\n\n| fd_set_open_callee (p : string) (fd : file)\n    (is_absent : absent ω fd)\n  : fd_set_callee_obligation ω file (Open_file p) fd\n\n(** We do not specify any particular requirements for the results of the other\n    primitives. Therefore, we cannot use this contract to reason about the\n    result of reading twice the same file, for instance. This would require\n    another contract, which is totally fine with FreeSpec since we can compose\n    them together. *)\n\n| fd_set_read_callee (fd : file) (s : string)\n  : fd_set_callee_obligation ω string (Read_file fd) s\n| fd_set_close_callee (fd : file) (t : unit)\n  : fd_set_callee_obligation ω unit (Close_file fd) t\n| fd_set_is_file_callee (p : string) (b : bool)\n  : fd_set_callee_obligation ω bool (File_exists p) b.\n\n#[global] Hint Constructors fd_set_callee_obligation : minihttp.\n\n(** *** The Contract Definition *)\n\n(** We put everything together by defining a term of type [contract FILESYSTEM\n    fd set]. *)\n\nDefinition fd_set_contract : contract FILESYSTEM fd_set :=\n  {| witness_update := fd_set_update\n   ; caller_obligation := fd_set_caller_obligation\n   ; callee_obligation := fd_set_callee_obligation\n  |}.\n\n(** ** II.2. Problem Definition *)\n\n(** From the caller perspective, there is two concerns that we want to express.\n    First, we _always_ use correct file descriptors. Secondly, we _eventually_\n    close any file descriptor previously opened.\n\n    The first objective is a _safety_ property that we can express\n    using the [respectful_impure] predicate. The exact lemma is: *)\n\nLemma fd_set_respectful_http_server `{StrictProvide3 ix FILESYSTEM TCP CONSOLE}\n    (ω : fd_set) (n : nat)\n  : pre (to_hoare fd_set_contract (http_server n)) ω.\nAbort.\n\n(** The [StrictProvide3] typeclass is very analogous to the [Provide3] one, but\n    it requires more contrains about its arguments. The exact details about\n    the difference is out of the scope of this tutorial, especially since the\n    two typeclasses with eventually be merged together.\n\n    The second objective is a _liveness_ property that we can express agains the\n    final witness state. This can be acheived using the [respectful_run]\n    predicate provided by FreeSpec. *)\n\nLemma fd_set_preserving_http_server `{StrictProvide3 ix FILESYSTEM TCP CONSOLE}\n      (n : nat)\n  : forall (ω ω' : fd_set) (x : unit),\n    post (to_hoare fd_set_contract (http_server n)) ω x ω'\n    -> forall fd, ω fd = ω' fd.\nAbort.\n\n(** This property can be read as: any [file] which is opened during\n    the execution of [http_server] is closed before the execution ends. This\n    is a property that we generalize for any impure computations:  *)\n\nDefinition fd_set_preserving {a} `{MayProvide ix FILESYSTEM} (p : impure ix a) :=\n  forall (ω ω' : fd_set) (x : a),\n    post (to_hoare fd_set_contract p) ω x ω' -> forall fd, ω fd = ω' fd.\n\n(** And, as a consequence, the second lemma we want to prove becomes: *)\n\nLemma fd_set_preserving_http_server `{StrictProvide3 ix FILESYSTEM TCP CONSOLE}\n    (n : nat)\n  : fd_set_preserving (http_server n).\nAbort.\n\n(** ** II.3. <<MiniHTTPServer>> Proofs of Correctness *)\n\n(** We now have defined everything we need to prove the correctness of\n    <<MiniHTTPServer>>. The rest of this tutorial consists in actually write the\n    proofs. Our approach is bottom-up: we start from the leaves of our\n    computations, show they have some important properties, then reuse our\n    result to eventually conclude about the correctness of the whole program. *)\n\n(** *** Certifying [read_content] *)\n\n(** From the perspective of this tutorial, the [read_content] impure computation\n    is an interesting starting point: it uses two primitives that can be misused\n    according to the [fd_set_contract] ([Read], and [Close]), and it also uses\n    an interface which is not relevant from the perspective of [fd_set_contract]\n    ([CONSOLE]). *)\n\nLemma fd_set_respectful_read_content `{StrictProvide2 ix FILESYSTEM CONSOLE}\n    (ω : fd_set) (path : string)\n  : pre (to_hoare fd_set_contract (read_content path)) ω.\n\n(** FreeSpec provides the [prove impure] tactics to automate as much as possible\n    the construction of a proof for [respectful_impure] goals. It performs many\n    uninteresting tasks that FreeSpec users would have to do manually if they\n    decided not to use it. For the sake of demonstration, we attempt to do just that,\n    and use [repeat constructor].\n\n    This generates 5 hardly readable subgoals, for instance the 5th subgoal is:\n\n<<\n  ω : fd_set\n  path : bytes\n  x : unit\n  H4 : gen_callee_obligation fd_set_contract ω\n         (inj_p (Echo (\"  reading <\" ++ path ++ \">... \"))) x\n  x0 : file\n  H5 : gen_callee_obligation fd_set_contract\n         (gen_witness_update fd_set_contract ω\n            (inj_p (Echo (\"  reading <\" ++ path ++ \">... \"))) x)\n         (inj_p (Open path)) x0\n  x1 : bytes\n  H6 : gen_callee_obligation fd_set_contract\n         (gen_witness_update fd_set_contract\n            (gen_witness_update fd_set_contract ω\n               (inj_p (Echo (\"  reading <\" ++ path ++ \">... \"))) x)\n            (inj_p (Open path)) x0) (inj_p (Read x0)) x1\n  x2 : unit\n  H7 : gen_callee_obligation fd_set_contract\n         (gen_witness_update fd_set_contract\n            (gen_witness_update fd_set_contract\n               (gen_witness_update fd_set_contract ω\n                  (inj_p (Echo (\"  reading <\" ++ path ++ \">... \"))) x)\n               (inj_p (Open path)) x0) (inj_p (Read x0)) x1)\n         (inj_p (Close x0)) x2\n  ============================\n gen_caller_obligation fd_set_contract\n   (gen_witness_update fd_set_contract\n      (gen_witness_update fd_set_contract\n         (gen_witness_update fd_set_contract\n            (gen_witness_update fd_set_contract ω\n               (inj_p (Echo (\"  reading <\" ++ path ++ \">... \"))) x)\n            (inj_p (Open path)) x0) (inj_p (Read x0)) x1)\n      (inj_p (Close x0)) x2) (inj_p (Echo \"done.\n\"))\n>>\n\n    [prove_impure] provides a much cleaner output:\n\n<<\nsubgoal 1 is:\n  fd_set_caller_obligation ω file (Open path)\n\nsubgoal 2 is:\n fd_set_caller_obligation (add_fd ω x0) bytes (Read x0)\n\nsubgoal 3 is:\n fd_set_caller_obligation (add_fd ω x0) unit (Close x0)\n>>\n\n    In this case, we can use the [minihttp] database that we have enriched with various [Hint]\n    to conclude automatically about this. *)\n\nProof.\n  prove impure with minihttp.\nQed.\n\n#[global] Hint Resolve fd_set_respectful_read_content : minihttp.\n\n(** The second property we want to prove about [read_content] is that\n    it does not forget to close any [file]. *)\n\nLemma fd_set_preserving_read_content `{StrictProvide2 ix FILESYSTEM CONSOLE}\n    (path : string)\n  : fd_set_preserving (read_content path).\n\n(** Similarly to [prove_impure], FreeSpec provides a tactic to exploit\n    hypotheses about [respectful_run]. More precisely, it explore the different\n    execution path that could lead to the production of the run in hypothesis,\n    and clean-up as much as possible the resulting alternative goals.. We can\n    explicit the tasks performed by [respectful_run] with the following\n    command.\n\n<<\n  repeat match goal with\n         | H : respectful_run _ _ _ _ _ |- _ => inversion H; clear H; ssubst\n         end.\n>>\n\n    This produces the following goal:\n\n<<\n  path : bytes\n  ω : fd_set\n  x : bytes\n  x0 : unit\n  o_callee : gen_callee_obligation fd_set_contract ω\n               (inj_p (Echo (\"  reading <\" ++ path ++ \">... \"))) x0\n  o_caller : gen_caller_obligation fd_set_contract ω\n               (inj_p (Echo (\"  reading <\" ++ path ++ \">... \")))\n  x1 : file\n  o_callee0 : gen_callee_obligation fd_set_contract\n                (gen_witness_update fd_set_contract ω\n                   (inj_p (Echo (\"  reading <\" ++ path ++ \">... \"))) x0)\n                (inj_p (Open path)) x1\n  o_caller0 : gen_caller_obligation fd_set_contract\n                (gen_witness_update fd_set_contract ω\n                   (inj_p (Echo (\"  reading <\" ++ path ++ \">... \"))) x0)\n                (inj_p (Open path))\n\n                               [...]\n\n  o_caller3 : gen_caller_obligation fd_set_contract\n                (gen_witness_update fd_set_contract\n                   (gen_witness_update fd_set_contract\n                      (gen_witness_update fd_set_contract\n                         (gen_witness_update fd_set_contract ω\n                            (inj_p (Echo (\"  reading <\" ++ path ++ \">... \"))) x0)\n                         (inj_p (Open path)) x1) (inj_p (Read x1)) x)\n                   (inj_p (Close x1)) x3) (inj_p (Echo \"done.\n\"))\n  o_callee3 : gen_callee_obligation fd_set_contract\n                (gen_witness_update fd_set_contract\n                   (gen_witness_update fd_set_contract\n                      (gen_witness_update fd_set_contract\n                         (gen_witness_update fd_set_contract ω\n                            (inj_p (Echo (\"  reading <\" ++ path ++ \">... \"))) x0)\n                         (inj_p (Open path)) x1) (inj_p (Read x1)) x)\n                   (inj_p (Close x1)) x3) (inj_p (Echo \"done.\n\")) x4\n  ============================\n  forall fd : file,\n  ω fd =\n  gen_witness_update fd_set_contract\n    (gen_witness_update fd_set_contract\n       (gen_witness_update fd_set_contract\n          (gen_witness_update fd_set_contract\n             (gen_witness_update fd_set_contract ω\n                (inj_p (Echo (\"  reading <\" ++ path ++ \">... \"))) x0)\n             (inj_p (Open path)) x1) (inj_p (Read x1)) x)\n       (inj_p (Close x1)) x3) (inj_p (Echo \"done.\n\")) x4 fd\n>>\n\n    On the contrary, [unroll_respectful_run] keeps the goal manageable, and once called, the FreeSpec\n    internals are gone and we can write a “classical” Coq proof. *)\n\nProof.\n  intros ω x ω' run.\n  unroll_post run.\n  intros fd'.\n  unfold add_fd, del_fd.\n  destruct fd_eq_dec; subst.\n  + now inversion H4; ssubst.\n  + reflexivity.\nQed.\n\n(** The implementation details of [read_content] will not be relevant with our\n    two freshly proven lemmas. Therefore, we make the impure computation to\n    prevent [improve_impure] and [unroll_respectful_run] to unfold them. *)\n\n#[local] Opaque read_content.\n\n(** *** Certifying [file_exists] *)\n\n(** We use the exact same approach for [file_exists]. Since this computation\n    does not use any problematic primitives, the proofs are straightforward. *)\n\nLemma fd_set_respectful_file_exists `{Provide ix FILESYSTEM} (ω : fd_set) (path : string)\n  : pre (to_hoare fd_set_contract (file_exists path)) ω.\n\nProof.\n  prove impure with minihttp.\nQed.\n\n#[global] Hint Resolve fd_set_respectful_file_exists : minihttp.\n\nLemma fd_set_preserving_file_exists `{Provide ix FILESYSTEM} (path : string)\n  : fd_set_preserving (file_exists path).\n\nProof.\n  intros ω x ω' run.\n  now unroll_post run.\nQed.\n\n(** Again, we make [file_exists] opaque because its concrete implementation is\n    not relevant anymore. *)\n\n#[local] Opaque file_exists.\n\n(** *** Certifying [http_handler] *)\n\n(** The [http_handler] is interesting, because to a large extent, it does not\n    use primitives itself: it relies on other impure computations [read_content]\n    and [file_exists] to do so. Interested readers can try to remove the\n    vernacular commands which make these two computations opaque and see the\n    outputs of [prove_impure] and [unroll_respectful_run]: in a nutshell, they\n    would find themselves having to prove one more time the exact same goals, in\n    more crowded contexts. *)\n\n#[local] Opaque http_request.\n\nLemma fd_set_respectful_http_handler `{StrictProvide2 ix FILESYSTEM CONSOLE}\n    (base : list directory_id) (req : string) (ω : fd_set)\n  : pre (to_hoare  fd_set_contract (http_handler base req)) ω.\n\nProof.\n  prove impure.\n  destruct (runStateT http_request (Slice.of_string req)).\n  + prove impure.\n  + destruct (fst p).\n    prove impure.\n\n(** Here, [prove_impure] did not unfold [file_exists] and [read_content], but\n    has leveraged FreeSpec formalism to generate two clean subgoals.\n<<\nsubgoal 1 is:\n  respectful_impure fd_set_contract ω\n    (file_exists (uri_to_path (sandbox base resource)))\n\nsubgoal 2 is:\n respectful_impure fd_set_contract w\n   (read_content (uri_to_path (sandbox base resource)))\n>>\n\n    Both are straightforward to prove using the [minihttp] hint database. *)\n\n    all: eauto with minihttp.\nQed.\n\n#[global] Hint Resolve fd_set_respectful_http_handler : minihttp.\n\nLemma fd_set_preserving_http_handler `{StrictProvide2 ix FILESYSTEM CONSOLE}\n    (base : list directory_id) (req : string)\n  : fd_set_preserving (http_handler base req).\n\nProof.\n  intros ω x ω' run fd.\n  unroll_post run.\n  destruct (runStateT http_request (Slice.of_string req)).\n  + now unroll_post run.\n  + destruct p as [[res_id] req'].\n    unroll_post run.\n\n(** [unroll_respectful_run] uses a similar approach when in presence of opaque\n    terms. *)\n\n    ++ apply fd_set_preserving_file_exists in run0.\n       apply fd_set_preserving_read_content in run.\n       now transitivity (ω0 fd).\n    ++ now apply fd_set_preserving_file_exists in run0.\nQed.\n\n#[global] Hint Resolve fd_set_preserving_http_handler : minihttp.\n\n#[local] Opaque http_handler.\n#[local] Opaque response_to_string.\n\n(** *** Certifying [repeatM] *)\n\nFrom Coq Require Import FunctionalExtensionality.\n\nLemma fd_set_preserving_repeatM {a} `{Provide ix FILESYSTEM}\n    (p : impure ix a)\n    (fd_preserving : fd_set_preserving p)\n    (n : nat)\n  : fd_set_preserving (repeatM n p).\n\nProof.\n  intros ω ω' fd run.\n  induction n.\n  + now unroll_post run.\n  + unroll_post run.\n    apply IHn.\n    replace ω with ω0; auto.\n    symmetry.\n    apply functional_extensionality.\n    eauto.\nQed.\n\n#[global] Hint Resolve fd_set_preserving_repeatM : minihttp.\n\nLemma repeatM_preserving_respectful {a} `{Provide ix FILESYSTEM}\n    (p : impure ix a) (ω : fd_set)\n    (fd_trust : pre (to_hoare fd_set_contract p) ω)\n    (fd_preserving : fd_set_preserving p)\n    (n : nat)\n  : pre (to_hoare fd_set_contract (repeatM n p)) ω.\n\nProof.\n  revert ω fd_trust.\n  induction n; intros ω fd_trust.\n  + prove impure.\n  + prove impure with minihttp.\n    apply IHn.\n    replace ω0 with ω; auto.\n    apply functional_extensionality.\n    intros fd.\n    eapply fd_preserving.\n    exact hpost.\nQed.\n\n#[local] Opaque repeatM.\n\nLemma fd_set_preserving_tcp_server_repeat_routine\n   `{Provide ix TCP, MayProvide ix FILESYSTEM, Distinguish ix TCP FILESYSTEM}\n    (server : socket)\n    (handler : string -> impure ix string)\n    (preserve : forall (req : string), fd_set_preserving (handler req))\n  : fd_set_preserving (let* client := accept_connection server in\n\n                       let* req := read_socket client in\n                       let* res := handler req in\n                       write_socket client res;;\n\n                       close_tcp_socket client).\n\nProof.\n  intros ω b ω' run fd.\n  unroll_post run.\n  now apply preserve in run.\nQed.\n\n#[global] Hint Resolve fd_set_preserving_tcp_server_repeat_routine : minihttp.\n\n(** *** Certifying [http_server] *)\n\nLemma fd_set_respectful_http_server `{StrictProvide3 ix FILESYSTEM TCP CONSOLE}\n    (ω : fd_set) (n : nat)\n  : pre (to_hoare fd_set_contract (http_server n)) ω.\n\nProof.\n  prove impure.\n  apply repeatM_preserving_respectful.\n  + prove impure.\n    apply fd_set_respectful_http_handler.\n  + intros ω' ω'' [] run fd.\n    apply fd_set_preserving_tcp_server_repeat_routine in run; auto with minihttp.\n    apply fd_set_preserving_http_handler.\nQed.\n\nLemma fd_set_preserving_http_server `{StrictProvide3 ix FILESYSTEM TCP CONSOLE}\n    (n : nat)\n  : fd_set_preserving (http_server n).\n\nProof.\n  intros ω x ω' run fd.\n  unroll_post run.\n  apply fd_set_preserving_repeatM in run0; auto with minihttp.\n  apply fd_set_preserving_tcp_server_repeat_routine.\n  apply fd_set_preserving_http_handler.\nQed.\n", "meta": {"author": "lthms", "repo": "coq-MiniHTTPServer", "sha": "8b1ed9de81ec7b1770054890accb22fe4f7b692d", "save_path": "github-repos/coq/lthms-coq-MiniHTTPServer", "path": "github-repos/coq/lthms-coq-MiniHTTPServer/coq-MiniHTTPServer-8b1ed9de81ec7b1770054890accb22fe4f7b692d/theories/App.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.20382734865890992}}
{"text": "(* This program is free software; you can redistribute it and/or      *)\n(* modify it under the terms of the GNU Lesser General Public License *)\n(* as published by the Free Software Foundation; either version 2.1   *)\n(* of the License, or (at your option) any later version.             *)\n(*                                                                    *)\n(* This program is distributed in the hope that it will be useful,    *)\n(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)\n(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)\n(* GNU General Public License for more details.                       *)\n(*                                                                    *)\n(* You should have received a copy of the GNU Lesser General Public   *)\n(* License along with this program; if not, write to the Free         *)\n(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)\n(* 02110-1301 USA                                                     *)\n\n\nRequire Import Reals.\nRequire Export pi_ineq.\n\n(* Some usefull constants *)\nDefinition g : R := (322 / 10)%R.\nDefinition ConflictRange : R := 200%R.\nDefinition MinSpeed : R := 201%R.\nDefinition MaxSpeed : R := 880%R.\nDefinition MaxBank : R := (61 / 100)%R.\n\n(**********)\nRecord TypeSpeed : Type := mkTypeSpeed\n  {v :> R; v_cond1 : (MinSpeed <= v)%R; v_cond2 : (v <= MaxSpeed)%R}.\n\nDefinition tan_lb_MaxBank : R := (6 / 10)%R.\nDefinition tan_ub_MaxBank : R := (7 / 10)%R.\n\n(**********)\nLemma tanBank_def :\n forall x : R, (- MaxBank <= x)%R -> (x <= MaxBank)%R -> cos x <> 0%R.\nintros; cut (MaxBank < PI / 2)%R.\nintro H1; generalize (Ropp_lt_gt_contravar MaxBank (PI / 2) H1); intro H2;\n generalize (Rle_lt_trans x MaxBank (PI / 2) H0 H1); \n intro H3; generalize (Rlt_le_trans (- (PI / 2)) (- MaxBank) x H2 H);\n intro H4; generalize (cos_gt_0 x H4 H3); intro H5; \n red in |- *; intro H6; rewrite H6 in H5; elim (Rlt_irrefl 0 H5).\napply Rlt_trans with (PI_lb / 2)%R.\napply Rlt_trans with 1%R.\nunfold MaxBank in |- *; unfold Rdiv in |- *; apply Rmult_lt_reg_l with 100%R.\nprove_sup.\nrewrite Rmult_1_r; rewrite Rmult_comm; rewrite Rmult_assoc;\n rewrite <- Rinv_l_sym.\nprove_sup.\ndiscrR.\nunfold PI_lb in |- *; apply Rmult_lt_reg_l with 2%R.\nprove_sup.\nrewrite Rmult_1_r; unfold Rdiv in |- *; rewrite Rmult_comm;\n rewrite Rmult_assoc; rewrite <- Rinv_l_sym.\nprove_sup.\ndiscrR.\nunfold Rdiv in |- *; apply Rmult_lt_reg_l with 2%R.\nprove_sup.\ndo 2 rewrite (Rmult_comm 2); do 2 rewrite Rmult_assoc; rewrite <- Rinv_l_sym.\ndo 2 rewrite Rmult_1_r; elim PI_approx; intros; assumption.\ndiscrR.\nQed.\n\n(* Verifiable in MuPAD*)\nAxiom tan_MaxBank_approx : (tan_lb_MaxBank < tan MaxBank < tan_ub_MaxBank)%R.\n\nLemma tan_MaxBank_ub : (tan MaxBank < tan_ub_MaxBank)%R.\ngeneralize tan_MaxBank_approx; intro H; elim H; intros H0 H1; assumption.\nQed.\n\nLemma tan_MaxBank_lb : (tan_lb_MaxBank < tan MaxBank)%R.\ngeneralize tan_MaxBank_approx; intro H; elim H; intros H0 H1; assumption.\nQed.\n\n(**********)\nLemma tan_MaxBank_pos : (0 < tan MaxBank)%R.\napply Rlt_trans with tan_lb_MaxBank.\nunfold tan_lb_MaxBank in |- *; unfold Rdiv in |- *;\n apply Rmult_lt_reg_l with 10%R.\nprove_sup.\nrewrite Rmult_0_r; rewrite <- Rmult_comm; repeat rewrite Rmult_assoc;\n rewrite <- Rinv_l_sym.\nprove_sup.\ndiscrR.\napply tan_MaxBank_lb.\nQed.", "meta": {"author": "coq-contribs", "repo": "ails", "sha": "d4b1152405b772a21654f06afd3d4755d65c0275", "save_path": "github-repos/coq/coq-contribs-ails", "path": "github-repos/coq/coq-contribs-ails/ails-d4b1152405b772a21654f06afd3d4755d65c0275/trajectory_const.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.37754067580180184, "lm_q1q2_score": 0.20348808938425997}}
{"text": "(* GENERIC *)\n\nRequire Export MinBFTg.\nRequire Export ComponentSM6.\n\n\nSection MinBFTsim1.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext        }.\n  Context { minbft_context      : MinBFT_context      }.\n  Context { m_initial_keys      : MinBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys   }.\n  Context { usig_hash           : USIG_hash           }.\n  Context { minbft_auth         : MinBFT_auth         }.\n\n  Context { ti : TrustedInfo }.\n\n  Lemma wf_procs_MinBFTlocalSysP :\n    forall r subs,\n      ~In MAINname (get_names subs)\n      -> lower_head 1 subs = true\n      -> wf_procs subs\n      -> wf_procs (MinBFTlocalSysP r subs).\n  Proof.\n    introv ni.\n    unfold wf_procs, no_dup_subs; simpl; allrw andb_true.\n    autorewrite with comp.\n    dest_cases w; dands; tcsp.\n  Qed.\n  Hint Resolve wf_procs_MinBFTlocalSysP : minbft.\n\n  Lemma is_proc_n_proc_MAIN_comp :\n    forall r, is_proc_n_proc (MAIN_comp r).\n  Proof.\n    introv; eexists; introv; try reflexivity.\n  Qed.\n  Hint Resolve is_proc_n_proc_MAIN_comp : minbft.\n\n  Lemma are_procs_n_procs_MinBFTlocalSysP :\n    forall r subs,\n      are_procs_n_procs subs\n      -> are_procs_n_procs (MinBFTlocalSysP r subs).\n  Proof.\n    introv aps i; simpl in *; repndors; subst; tcsp; simpl in *; tcsp; eauto 3 with minbft comp.\n    apply are_procs_n_procs_incr_n_procs in i; auto.\n  Qed.\n  Hint Resolve are_procs_n_procs_MinBFTlocalSysP : minbft.\n\n  Lemma similar_sms_at_minbft_replica :\n    forall r (p : n_proc 2 _),\n      similar_sms p (MAIN_comp r)\n      -> exists s, p = MinBFT_replicaSM_new r s.\n  Proof.\n    introv sim; simpl in *.\n    destruct p; simpl in *; tcsp.\n    unfold similar_sms_at in sim.\n    destruct a as [upd st]; simpl in *; subst; simpl in *.\n    exists st; auto.\n  Qed.\n\n  Lemma similar_procs_MAIN :\n    forall r p,\n      similar_procs (MkPProc MAINname (MAIN_comp r)) p\n      -> exists s, p = MkPProc MAINname (MinBFT_replicaSM_new r s).\n  Proof.\n    introv sim.\n    inversion sim as [? ? ? ? sims]; clear sim; subst.\n    match goal with\n    | [ H : context[p1] |- _ ] => rename H into h1\n    end.\n    match goal with\n    | [ H : context[p2] |- _ ] => rename H into h2\n    end.\n    apply Eqdep.EqdepTheory.inj_pair2 in h1; subst; eauto 3 with comp.\n    apply Eqdep.EqdepTheory.inj_pair2 in h1; subst; eauto 3 with comp.\n    apply Eqdep.EqdepTheory.inj_pair2 in h2; subst; eauto 3 with comp.\n    apply similar_sms_sym in sims.\n    apply similar_sms_at_minbft_replica in sims; exrepnd; subst; eauto.\n  Qed.\n\n  Lemma similar_subs_MinBFTlocalSysP :\n    forall r subs ls,\n      similar_subs (MinBFTlocalSysP r subs) ls\n      -> exists (s : MAIN_state) (subs' : n_procs _),\n        ls = MinBFTlocalSys_newP r s subs'\n        /\\ similar_subs subs subs'.\n  Proof.\n    introv sim.\n    inversion sim; subst; simpl in *.\n    apply similar_procs_MAIN in simp; exrepnd; subst; simpl in *.\n    apply similar_subs_incr_n_procs_left_implies in sims; exrepnd; subst.\n    exists s j; dands; tcsp.\n  Qed.\n\n  (* MOVE to MinBFTsubs *)\n  Lemma M_run_ls_before_event_ls_is_minbftP :\n    forall {eo   : EventOrdering}\n           (e    : Event)\n           (r    : Rep)\n           (ls   : LocalSystem 2 0)\n           (subs : n_procs _),\n      ~In MAINname (get_names subs)\n      -> lower_head 1 subs = true\n      -> wf_procs subs\n      -> are_procs_n_procs subs\n      -> M_run_ls_before_event (MinBFTlocalSysP r subs) e = Some ls\n      ->\n      exists (s : MAIN_state) (subs' : n_procs _),\n        ls = MinBFTlocalSys_newP r s subs'\n        /\\ similar_subs subs subs'.\n  Proof.\n    introv ni low wf aps run.\n    applydup M_run_ls_before_event_preserves_subs in run; eauto 3 with minbft.\n    repnd.\n    apply similar_subs_MinBFTlocalSysP in run3; exrepnd; subst.\n    exists s subs'; dands; auto.\n  Qed.\n\nEnd MinBFTsim1.\n\n\nHint Resolve wf_procs_MinBFTlocalSysP : minbft.\nHint Resolve is_proc_n_proc_MAIN_comp : minbft.\nHint Resolve are_procs_n_procs_MinBFTlocalSysP : minbft.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MinBFTsim1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2034880856094067}}
{"text": "Require Import Relations.\nRequire Import EquivDec.\nRequire Import Equality.\nRequire Import List.\nRequire Import Bool.\nRequire Import Lia.\nRequire Import NArith.\nRequire Import PArith.\nRequire Import ZArith.\nRequire Import FMapPositive.\nRequire Import FSetPositive.\nRequire Import EquivDec.\nFrom sflib Require Import sflib.\n\nRequire Import PromisingArch.lib.Basic.\nRequire Import PromisingArch.lib.Order.\nRequire Import PromisingArch.lib.Time.\nRequire Import PromisingArch.lib.Lang.\nRequire Import PromisingArch.promising.Promising.\n\nSet Implicit Arguments.\n\n\nLemma rtc_state_step_state_exec\n      m1 m2\n      (WF: Machine.wf m1)\n      (STEP: rtc (Machine.step ExecUnit.state_step) m1 m2):\n  Machine.state_exec m1 m2.\nProof.\n  revert WF. induction STEP.\n  { econs; ss. ii. destruct (IdMap.find id (Machine.tpool x)); ss. econs. refl. }\n  i. exploit Machine.step_state_step_wf; eauto. i.\n  exploit IHSTEP; eauto. intro x0. inv x0.\n  destruct x as [tpool1 mem1].\n  destruct y as [tpool2 mem2].\n  inv H. inversion STEP0. inv STEP1. ss. subst. econs; ss.\n  ii. specialize (TPOOL id). revert TPOOL.\n  rewrite IdMap.add_spec. condtac; ss. i.\n  inversion e0. inv TPOOL. rewrite FIND, <- H2. econs.\n  econs; eauto.\nQed.\n\nLemma state_exec_rtc_state_step\n      m1 m2\n      (STEP: Machine.state_exec m1 m2):\n  exists m2',\n    <<EXEC: rtc (Machine.step ExecUnit.state_step) m1 m2'>> /\\\n    <<EQUIV: Machine.equiv m2 m2'>>.\nProof.\n  inv STEP.\n  assert (IN: forall tid sl1\n                (FIND1: IdMap.find tid m1.(Machine.tpool) = Some sl1),\n             exists sl2,\n               IdMap.find tid m2.(Machine.tpool) = Some sl2 /\\\n               rtc (ExecUnit.state_step tid)\n                   (ExecUnit.mk (fst sl1) (snd sl1) m1.(Machine.mem))\n                   (ExecUnit.mk (fst sl2) (snd sl2) m1.(Machine.mem))).\n  { i. specialize (TPOOL tid). rewrite FIND1 in TPOOL. inv TPOOL. esplits; ss. }\n  assert (OUT: forall tid\n                 (FIND1: IdMap.find tid m1.(Machine.tpool) = None),\n             IdMap.find tid m1.(Machine.tpool) = IdMap.find tid m2.(Machine.tpool)).\n  { i. specialize (TPOOL tid). rewrite FIND1 in TPOOL. inv TPOOL. ss. }\n  assert (P: forall tid sl1\n               (FIND1: IdMap.find tid m1.(Machine.tpool) = Some sl1),\n             IdMap.find tid m1.(Machine.tpool) = Some sl1).\n  { ss. }\n  clear TPOOL.\n  setoid_rewrite IdMap.elements_spec in IN at 1.\n  setoid_rewrite IdMap.elements_spec in OUT at 1.\n  setoid_rewrite IdMap.elements_spec in P at 1.\n  generalize (IdMap.elements_3w m1.(Machine.tpool)). intro NODUP. revert NODUP.\n  revert IN OUT P. generalize (IdMap.elements (m1.(Machine.tpool))). intro ps.\n  revert m1 MEM. induction ps; ss.\n  { i. esplits; eauto. econs; ss. ii. rewrite OUT; ss. }\n\n  i. destruct a. inv NODUP.\n  exploit (IN k).\n  { destruct (equiv_dec k k); ss. congr. }\n  exploit (P k).\n  { destruct (equiv_dec k k); ss. congr. }\n  i. des. destruct p. ss.\n\n  cut (exists m2', rtc (Machine.step ExecUnit.state_step)\n                 (Machine.mk (IdMap.add k (fst sl2, snd sl2) m1.(Machine.tpool)) m1.(Machine.mem))\n                 m2' /\\\n             Machine.equiv m2 m2').\n  { i. des. esplits; [|by eauto]. etrans; [|by eauto].\n    eapply Machine.rtc_eu_step_step; [eauto|refl|eauto].\n  }\n  assert (TID: forall tid sl (FIND: SetoidList.findA (fun id' : IdMap.key => if equiv_dec tid id' then true else false) ps = Some sl), tid <> k).\n  { ii. subst. apply H1. revert FIND. clear. induction ps; ss.\n    destruct a. destruct (equiv_dec k k0); ss.\n    - inv e. i. inv FIND. left. ss.\n    - i. right. apply IHps. ss.\n  }\n  eapply IHps; ss.\n  - i. eapply IN. destruct (equiv_dec tid k); ss.\n    inv e. exfalso. eapply TID; eauto.\n  - i. rewrite IdMap.add_spec. condtac.\n    + inversion e. subst. rewrite x1. destruct sl2. ss.\n    + eapply OUT. destruct (equiv_dec tid k); ss.\n  - i. rewrite IdMap.add_spec. condtac.\n    + inversion e. subst. exfalso. eapply TID; eauto.\n    + eapply P. destruct (equiv_dec tid k); ss.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-arm", "sha": "10291375ccd03152eadf739d280e2c59e10fa9af", "save_path": "github-repos/coq/snu-sf-promising-arm", "path": "github-repos/coq/snu-sf-promising-arm/promising-arm-10291375ccd03152eadf739d280e2c59e10fa9af/src/promising/StateExecFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.20348808560940665}}
{"text": "(** Sharpened ADT for (ab)* *)\nRequire Import Fiat.Parsers.Grammars.ABStar.\nRequire Import Fiat.Parsers.Refinement.Tactics.\nRequire Import Fiat.Parsers.Refinement.SharpenedABStar.\n\nDefinition parser : ParserInterface.Parser ab_star_grammar String.string_stringlike.\nProof.\n  let b := make_Parser (@ComputationalSplitter _ String.string_stringlike _ _) in\n  exact b.\nDefined.\n\nDefinition ab_star_parser_informative_opaque (str : Coq.Strings.String.string)\n  : option (parse_of_item ab_star_grammar str (NonTerminal (Start_symbol ab_star_grammar))).\nProof.\n  Time make_parser_informative_opaque (@ComputationalSplitter _ String.string_stringlike _ _). (* 0.82 s *)\nDefined.\n\nGoal forall b, ab_star_parser_informative_opaque \"\" = b.\nProof.\n  intro.\n  let LHS := match goal with |- ?LHS = _ => LHS end in\n  let LHS := (eval hnf in LHS) in\n  change (LHS = b).\nAbort.\n\nDefinition ab_star_parser_informative (str : Coq.Strings.String.string)\n  : option (@simple_parse_of_item Ascii.ascii).\nProof.\n  Time make_parser_informative (@ComputationalSplitter _ String.string_stringlike _ _). (* 0.124 s *)\nDefined.\n\nGoal exists s, ab_star_parser_informative \"\" = Some s.\nProof.\n  eexists.\n  compute.\n  reflexivity.\nQed.\n", "meta": {"author": "mit-plv", "repo": "fiat", "sha": "4c78284c3a88db32051bdba79202f40c645ffb7f", "save_path": "github-repos/coq/mit-plv-fiat", "path": "github-repos/coq/mit-plv-fiat/fiat-4c78284c3a88db32051bdba79202f40c645ffb7f/src/Parsers/Refinement/SharpenedABStarParseTree.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3775406617944891, "lm_q1q2_score": 0.2034880818345534}}
{"text": "Require Import ModelProperties. \nRequire Import AuxiliaryLemmas. \n \nSection chobjscIsSecure. \n \nLemma ChobjscPSS :\n forall (s t : SFSstate) (u : SUBJECT),\n FuncPre6 s -> SecureState s -> TransFunc u s Chobjsc t -> SecureState t. \nintros s t Sub FP6 SS TF; inversion TF. \ninversion H. \nunfold SecureState in |- *. \nBreakSS. \nsplit. \nauto. \n \nunfold MACSecureState in |- *; simpl in |- *; intros. \nelim (OBJeq_dec o o0). \nintro. \nrewrite <- a. \ncut (fsecmat (secmat s) o = None). \nintro. \nrewrite H6. \nelim (fOSC (objectSC s) o); elim (fOSC (chobjsc_SC s o sc) o);\n elim (fSSC (subjectSC s) u); contradiction || auto. \n \nunfold fsecmat in |- *; auto. \n \nintro. \nreplace (fOSC (chobjsc_SC s o sc) o0) with (fOSC (objectSC s) o0). \nunfold MACSecureState in MAC; apply MAC. \n \nauto. \n \nQed. \n \n \nLemma ChobjscPSP :\n forall (s t : SFSstate) (u : SUBJECT),\n FuncPre6 s -> StarProperty s -> TransFunc u s Chobjsc t -> StarProperty t. \nintros s t Sub FP6 SP TF; inversion TF. \ninversion H. \nunfold StarProperty in |- *; simpl in |- *; intros. \nelim (OBJeq_dec o o1); elim (OBJeq_dec o o2); intros EQ2 EQ1. \nrewrite <- EQ1; rewrite <- EQ2. \nreplace (fsecmat (secmat s) o) with (None (A:=ReadersWriters)). \nelim (fOSC (objectSC s) o); elim (fOSC (chobjsc_SC s o sc) o);\n contradiction || auto. \n \nsymmetry  in |- *; unfold fsecmat in |- *; auto. \n \nauto. \nrewrite <- EQ1. \nreplace (fsecmat (secmat s) o) with (None (A:=ReadersWriters)). \nreplace (fOSC (chobjsc_SC s o sc) o2) with (fOSC (objectSC s) o2). \nelim (fsecmat (secmat s) o2); elim (fOSC (chobjsc_SC s o sc) o);\n elim (fOSC (objectSC s) o); elim (fOSC (objectSC s) o2); \n intros; contradiction || auto. \n \nauto. \n \nsymmetry  in |- *; unfold fsecmat in |- *; auto. \n \nrewrite <- EQ2. \nreplace (fsecmat (secmat s) o) with (None (A:=ReadersWriters)). \nreplace (fOSC (chobjsc_SC s o sc) o1) with (fOSC (objectSC s) o1). \nelim (fsecmat (secmat s) o1); elim (fOSC (chobjsc_SC s o sc) o);\n elim (fOSC (objectSC s) o); elim (fOSC (objectSC s) o1); \n intros; contradiction || auto. \n \nauto. \n \nsymmetry  in |- *; unfold fsecmat in |- *; auto. \n \nreplace (fOSC (chobjsc_SC s o sc) o2) with (fOSC (objectSC s) o2). \nreplace (fOSC (chobjsc_SC s o sc) o1) with (fOSC (objectSC s) o1). \nunfold StarProperty in SP; apply SP. \n \nauto. \n \nauto. \n \nQed. \n \n \nLemma ChobjscPCP : forall s t : SFSstate, PreservesControlProp s Chobjsc t. \nintros; unfold PreservesControlProp in |- *; intros Sub TF; inversion TF;\n unfold ControlProperty in |- *. \ninversion H. \nsplit. \nintros. \nsplit. \nintro. \nabsurd\n (DACCtrlAttrHaveChanged s\n    (mkSFS (groups s) (primaryGrp s) (subjectSC s) \n       (AllGrp s) (RootGrp s) (SecAdmGrp s) (chobjsc_SC s o sc) \n       (acl s) (secmat s) (files s) (directories s)) o0); \n auto. \n \nauto. \n \nintros. \nabsurd\n (MACSubCtrlAttrHaveChanged s\n    (mkSFS (groups s) (primaryGrp s) (subjectSC s) \n       (AllGrp s) (RootGrp s) (SecAdmGrp s) (chobjsc_SC s o sc) \n       (acl s) (secmat s) (files s) (directories s)) u0); \n auto. \n \nQed. \n \n \nEnd chobjscIsSecure. \n \nHint Resolve ChobjscPSS ChobjscPSP ChobjscPCP.", "meta": {"author": "coq-contribs", "repo": "fssec-model", "sha": "9c1148bf33f69f2e3ca4937e2243200a10c849c0", "save_path": "github-repos/coq/coq-contribs-fssec-model", "path": "github-repos/coq/coq-contribs-fssec-model/fssec-model-9c1148bf33f69f2e3ca4937e2243200a10c849c0/chobjscIsSecure.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3593641382989649, "lm_q1q2_score": 0.20340676316198933}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom bpf.comm Require Import Regs BinrBPF State Monad.\nFrom bpf.monadicmodel Require Import Opcode rBPFInterpreter.\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory.\nImport ListNotations.\n\nFrom bpf.clightlogic Require Import Clightlogic CorrectRel CommonLemma CommonLemmaNat.\n\nFrom bpf.clight Require Import interpreter.\n\nFrom bpf.simulation Require Import MatchState InterpreterRel.\n\n(**\nCheck get_opcode_ins.\nget_opcode_ins\n     : int64 -> M nat\n\n*)\n\nSection Get_opcode_ins.\n  Context {S: special_blocks}.\n  (** The program contains our function of interest [fn] *)\n  Definition p : Clight.program := prog.\n\n  (* [Args,Res] provides the mapping between the Coq and the C types *)\n  (* Definition Args : list CompilableType := [stateCompilableType].*)\n  Definition args : list Type := [(int64:Type)].\n  Definition res : Type := (nat:Type).\n\n  (* [f] is a Coq Monadic function with the right type *)\n  Definition f : arrow_type args (M State.state res) := get_opcode_ins.\n\n  (* [fn] is the Cligth function which has the same behaviour as [f] *)\n  Definition fn: Clight.function := f_get_opcode_ins.\n\n  (* [match_arg] relates the Coq arguments and the C arguments *)\n  Definition match_arg_list : DList.t (fun x => x -> Inv _) args :=\n    (dcons (fun x => StateLess _ (int64_correct x))\n                (DList.DNil _)).\n\n  (* [match_res] relates the Coq result and the C result *)\n  Definition match_res : res -> Inv State.state := fun x  => StateLess _ (opcode_correct x).\n\n  Instance correct_function_get_opcode_ins : forall a, correct_function _ p args res f fn ModNothing true match_state match_arg_list match_res a.\n  Proof.\n    correct_function_from_body args.\n    correct_body.\n    (** how to use correct_* *)\n    unfold INV.\n    unfold f.\n    repeat intro.\n    get_invariant _ins.\n\n    unfold eval_inv, int64_correct in c0.\n    subst.\n\n    eexists. exists m, Events.E0.\n    unfold match_res, opcode_correct, BinrBPF.get_opcode.\n\n    unfold Int64.and.\n    change (Int64.unsigned (Int64.repr 255)) with 255%Z.\n    assert (Hc_le: (0 <= Z.land (Int64.unsigned c) 255 <= 255)%Z). {\n      assert (Heq: (Int64.unsigned c) = Z.of_nat (Z.to_nat(Int64.unsigned c))). {\n        rewrite Z2Nat.id.\n        reflexivity.\n        assert (Hrange: (0 <= Int64.unsigned c < Int64.modulus)%Z) by apply Int64.unsigned_range.\n        lia.\n      }\n      rewrite Heq; clear.\n      change 255%Z with (Z.of_nat (Z.to_nat 255%Z)) at 1 2.\n      rewrite LemmaNat.land_land.\n      split.\n      lia.\n      assert (H: ((Nat.land (Z.to_nat (Int64.unsigned c)) (Z.to_nat 255)) <= 255)%nat). {\n        rewrite Nat.land_comm.\n        rewrite LemmaNat.land_bound.\n        lia.\n      }\n      lia.\n    }\n    rewrite Int64.unsigned_repr; [ | change Int64.max_unsigned with 18446744073709551615%Z; lia].\n\n    rewrite Z2Nat.id; [| lia].\n\n    split; unfold step2.\n    -\n      forward_star.\n      simpl.\n      rewrite Int.zero_ext_idem; [| lia].\n      rewrite Int.zero_ext_and; [| lia].\n      change (two_p 8 - 1)%Z with 255%Z.\n\n      unfold Int64.and.\n      change (Int64.unsigned (Int64.repr 255)) with 255%Z.\n      rewrite Int64.unsigned_repr; [ | change Int64.max_unsigned with 18446744073709551615%Z; lia].\n\n      unfold Int.and.\n      rewrite Int.unsigned_repr; [| change Int.max_unsigned with 4294967295%Z; lia].\n      change (Int.unsigned (Int.repr 255)) with 255%Z.\n      rewrite <- Z.land_assoc.\n      rewrite Z.land_diag.\n\n      unfold step2; forward_star.\n    - split.\n      + unfold eval_inv.\n        split; [reflexivity|].\n        lia.\n      + split.\n        * constructor.\n          simpl.\n          rewrite Int.zero_ext_and; [| lia].\n          change (two_p 8 - 1)%Z with 255%Z.\n\n          unfold Int.and.\n          rewrite Int.unsigned_repr; [| change Int.max_unsigned with 4294967295%Z; lia].\n          change (Int.unsigned (Int.repr 255)) with 255%Z.\n          rewrite <- Z.land_assoc.\n          rewrite Z.land_diag.\n          reflexivity.\n        * split; [auto|].\n          apply unmodifies_effect_refl.\n  Qed.\n\nEnd Get_opcode_ins.\n\nExisting Instance correct_function_get_opcode_ins.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/correct_get_opcode_ins.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.2033949006695595}}
{"text": "Require Import oeuf.Common oeuf.Monads.\nRequire Import oeuf.Metadata.\nRequire String.\nRequire Import oeuf.ListLemmas.\nRequire Import oeuf.StepLib.\nRequire Import oeuf.HigherValue.\n\nRequire Import Psatz.\n\nRequire oeuf.SelfClose.\nRequire oeuf.Switched1.\n\nModule A := SelfClose.\nModule B := Switched1.\n\nSet Default Timeout 15.\n\n\n\nSection compile.\nOpen Scope option_monad.\n\nDefinition compile : A.expr -> option B.expr :=\n    let fix go e :=\n        let fix go_list es :=\n            match es with\n            | [] => Some []\n            | e :: es => @cons _ <$> go e <*> go_list es\n            end in\n        match e with\n        | A.Value v => Some (B.Value v)\n        | A.Arg => Some B.Arg\n        | A.Self => Some B.Self\n        | A.Deref e n => B.Deref <$> go e <*> Some n\n        | A.Call f a => B.Call <$> go f <*> go a\n        | A.MkConstr tag args => B.MkConstr tag <$> go_list args\n        | A.Elim A.Self cases A.Arg =>\n                go_list cases >>= fun cases' =>\n                let cases'' := map (fun case =>\n                    B.Call (B.Call case B.Self) B.Arg) cases' in\n                Some (B.Elim B.Self cases'' B.Arg)\n        | A.Elim _ _ _ => None\n        | A.MkClose f free => B.MkClose f <$> go_list free\n        | A.OpaqueOp op args => B.OpaqueOp op <$> go_list args\n        end in go.\n\nDefinition compile_list : list A.expr -> option (list B.expr) :=\n    let go := compile in\n    let fix go_list es :=\n        match es with\n        | [] => Some []\n        | e :: es => @cons _ <$> go e <*> go_list es\n        end in go_list.\n\nDefinition compile_cu (cu : list A.expr * list metadata) :\n        option (list B.expr * list metadata) :=\n    let '(exprs, metas) := cu in\n    compile_list exprs >>= fun exprs' =>\n    Some (exprs', metas).\n\nEnd compile.\n\nLtac refold_compile :=\n    fold compile_list in *.\n\n\n\nInductive I_expr vself varg : A.expr -> B.expr -> Prop :=\n| IValue : forall v, I_expr vself varg (A.Value v) (B.Value v)\n| IArg : I_expr vself varg A.Arg B.Arg\n| ISelf : I_expr vself varg A.Self B.Self\n| IDeref : forall ae be n,\n        I_expr vself varg ae be ->\n        I_expr vself varg (A.Deref ae n) (B.Deref be n)\n| ICall : forall af aa bf ba,\n        I_expr vself varg af bf ->\n        I_expr vself varg aa ba ->\n        I_expr vself varg (A.Call af aa) (B.Call bf ba)\n| IMkConstr : forall tag aargs bargs,\n        Forall2 (I_expr vself varg) aargs bargs ->\n        I_expr vself varg (A.MkConstr tag aargs) (B.MkConstr tag bargs)\n| IElim : forall aloop acases atarget bloop bcases btarget,\n        I_expr vself varg aloop bloop ->\n        Forall2 (fun acase bcase => exists bcase0,\n            I_expr vself varg acase bcase0 /\\\n            bcase = B.Call (B.Call bcase0 B.Self) B.Arg) acases bcases ->\n        I_expr vself varg atarget btarget ->\n        (aloop = A.Self \\/ aloop = A.Value vself) ->\n        (atarget = A.Arg \\/ atarget = A.Value varg) ->\n        I_expr vself varg (A.Elim aloop acases atarget) (B.Elim bloop bcases btarget)\n| IMkClose : forall fname' aargs bargs,\n        Forall2 (I_expr vself varg) aargs bargs ->\n        I_expr vself varg (A.MkClose fname' aargs) (B.MkClose fname' bargs)\n| IOpaqueOp : forall op aargs bargs,\n        Forall2 (I_expr vself varg) aargs bargs ->\n        I_expr vself varg (A.OpaqueOp op aargs) (B.OpaqueOp op bargs)\n\n| ICallSelf : forall af bf,\n        I_expr vself varg af bf ->\n        I_expr vself varg (A.Call af (A.Value vself)) (B.Call bf B.Self)\n| ICallArg : forall af bf,\n        I_expr vself varg af bf ->\n        I_expr vself varg (A.Call af (A.Value varg)) (B.Call bf B.Arg)\n.\n\nInductive I (AE : A.env) (BE : B.env) : A.state -> B.state -> Prop :=\n| IRun : forall a s ae ak be bk,\n        I_expr s a ae be ->\n        (forall v, I AE BE (ak v) (bk v)) ->\n        I AE BE (A.Run ae a s ak) (B.Run be a s bk)\n\n| IInElimLoop : forall a s ak bk,\n        I AE BE (ak s) (bk s) ->\n        I AE BE\n            (A.Run A.Self a s ak)\n            (B.Run B.Self a s bk)\n\n| IInElimTarget : forall a s ak bk,\n        I AE BE (ak a) (bk a) ->\n        I AE BE\n            (A.Run A.Arg a s ak)\n            (B.Run B.Arg a s bk)\n\n| IStop : forall v,\n        I AE BE (A.Stop v) (B.Stop v).\n\n\nLtac i_ctor := intros; econstructor; simpl; eauto.\nLtac i_lem H := intros; eapply H; simpl; eauto.\n\n\n\nLemma compile_I_expr : forall a b,\n    compile a = Some b ->\n    forall vs va,\n    I_expr vs va a b.\ninduction a using A.expr_rect_mut with\n    (Pl := fun as_ => forall bs,\n        compile_list as_ = Some bs ->\n        forall vs va,\n        Forall2 (I_expr vs va) as_ bs);\nintros0 Hcomp; simpl in *; refold_compile; break_bind_option; inject_some; intros.\nall: try solve [i_ctor].\n\ndo 2 (break_match; try discriminate).\nbreak_bind_option. inject_some. simpl.\ni_ctor.\nspecialize (IHa2 ?? *** vs va).\nfwd i_lem Forall2_length.\neapply nth_error_Forall2. { rewrite map_length. auto. }\nintros.\nfwd i_lem map_nth_error' as HH. destruct HH as (bcase & ? & ?).\nfwd i_lem Forall2_nth_error.\neexists. split; eauto.\nQed.\n\nLemma compile_list_I_expr : forall as_ bs,\n    compile_list as_ = Some bs ->\n    Forall2 (fun a b => forall vs va, I_expr vs va a b) as_ bs.\ninduction as_; destruct bs; intros0 Hcomp; simpl in *; refold_compile;\nbreak_bind_option; inject_some.\n\n- constructor.\n- i_ctor. i_lem compile_I_expr.\n- i_ctor. i_lem compile_I_expr.\nQed.\n\n\n\nLtac B_start HS :=\n    match goal with\n    | [ |- context [ ?pred ?E ?s _ ] ] =>\n            lazymatch pred with\n            | B.sstep => idtac\n            | B.sstar => idtac\n            | B.splus => idtac\n            | _ => fail \"unrecognized predicate:\" pred\n            end;\n            let S_ := fresh \"S\" in\n            let S0 := fresh \"S\" in\n            set (S0 := s);\n            change s with S0;\n            assert (HS : B.sstar E S0 S0) by (eapply B.SStarNil)\n    end.\n\nLtac B_step HS :=\n    let S_ := fresh \"S\" in\n    let S2 := fresh \"S\" in\n    let HS' := fresh HS \"'\" in\n    let go E s0 s1 Brel solver :=\n        rename HS into HS';\n        evar (S2 : B.state);\n        assert (HS : Brel E s0 S2);\n        [ solver; unfold S2\n        | clear HS' ] in\n    match type of HS with\n    | B.sstar ?E ?s0 ?s1 => go E s0 s1 B.splus\n            ltac:(eapply sstar_then_splus with (1 := HS');\n                  eapply B.SPlusOne)\n    | B.splus ?E ?s0 ?s1 => go E s0 s1 B.splus\n            ltac:(eapply splus_snoc with (1 := HS'))\n    end.\n\nLtac B_star HS :=\n    let S_ := fresh \"S\" in\n    let S2 := fresh \"S\" in\n    let HS' := fresh HS \"'\" in\n    let go E s0 s1 Brel solver :=\n        rename HS into HS';\n        evar (S2 : B.state);\n        assert (HS : Brel E s0 S2);\n        [ solver; unfold S2\n        | clear HS' ] in\n    match type of HS with\n    | B.sstar ?E ?s0 ?s1 => go E s0 s1 B.sstar\n            ltac:(eapply sstar_then_sstar with (1 := HS'))\n    | B.splus ?E ?s0 ?s1 => go E s0 s1 B.splus\n            ltac:(eapply splus_then_sstar with (1 := HS'))\n    end.\n\nLtac B_plus HS :=\n    let S_ := fresh \"S\" in\n    let S2 := fresh \"S\" in\n    let HS' := fresh HS \"'\" in\n    let go E s0 s1 Brel solver :=\n        rename HS into HS';\n        evar (S2 : B.state);\n        assert (HS : Brel E s0 S2);\n        [ solver; unfold S2\n        | clear HS' ] in\n    match type of HS with\n    | B.sstar ?E ?s0 ?s1 => go E s0 s1 B.splus\n            ltac:(eapply sstar_then_splus with (1 := HS'))\n    | B.splus ?E ?s0 ?s1 => go E s0 s1 B.splus\n            ltac:(eapply splus_then_splus with (1 := HS'))\n    end.\n\n\n\n\nLemma I_expr_value : forall vself varg a b,\n    I_expr vself varg a b ->\n    A.is_value a ->\n    B.is_value b.\nintros0 II Aval. invc Aval. invc II. constructor.\nQed.\nHint Resolve I_expr_value.\n\nLemma I_expr_value' : forall vself varg a b,\n    I_expr vself varg a b ->\n    B.is_value b ->\n    A.is_value a.\nintros0 II Bval. invc Bval. invc II. constructor.\nQed.\nHint Resolve I_expr_value'.\n\nLemma I_expr_not_value : forall vself varg a b,\n    I_expr vself varg a b ->\n    ~ A.is_value a ->\n    ~ B.is_value b.\nintros0 II Aval. contradict Aval. eauto using I_expr_value'.\nQed.\nHint Resolve I_expr_not_value.\n\nLemma I_expr_not_value' : forall vself varg a b,\n    I_expr vself varg a b ->\n    ~ B.is_value b ->\n    ~ A.is_value a.\nintros0 II Bval. contradict Bval. eauto using I_expr_value.\nQed.\nHint Resolve I_expr_not_value'.\n\nLemma I_expr_map_value : forall vself varg vs bes,\n    Forall2 (I_expr vself varg) (map A.Value vs) bes ->\n    bes = map B.Value vs.\ninduction vs; intros0 II; invc II.\n- reflexivity.\n- simpl. f_equal.\n  + on >I_expr, invc. reflexivity.\n  + apply IHvs. eauto.\nQed.\n\nTheorem I_sim : forall AE BE a a' b,\n    Forall2 (fun a b => forall vs va, I_expr vs va a b) AE BE ->\n    I AE BE a b ->\n    A.sstep AE a a' ->\n    exists b',\n        B.splus BE b b' /\\\n        I AE BE a' b'.\ndestruct a as [ae a s ak | v];\nintros0 Henv II Astep; inv Astep.\nall: invc II.\nall: try on (I_expr _ _ _ be), invc.\n\n- (* SArg *)\n  eexists. split. eapply B.SPlusOne; i_lem B.SArg.\n  auto.\n\n- (* SArg - IInElimTarget *)\n  eexists. split. eapply B.SPlusOne; i_lem B.SArg.\n  auto.\n\n- (* SSelf *)\n  eexists. split. eapply B.SPlusOne; i_lem B.SSelf.\n  auto.\n\n- (* SSelf - IInElimLoop *)\n  eexists. split. eapply B.SPlusOne; i_lem B.SSelf.\n  auto.\n\n- (* SDerefStep *)\n  eexists. split. eapply B.SPlusOne; i_lem B.SDerefStep.\n  i_ctor. i_ctor. i_ctor. i_ctor.\n\n- (* SDerefinateConstr *)\n  on (I_expr _ _ (A.Value _) _), invc.\n  eexists. split. eapply B.SPlusOne; i_lem B.SDerefinateConstr.\n  eauto.\n\n- (* SDerefinateClose *)\n  on (I_expr _ _ (A.Value _) _), invc.\n  eexists. split. eapply B.SPlusOne; i_lem B.SDerefinateClose.\n  eauto.\n\n- (* SCloseStep *)\n  destruct (Forall2_app_inv_l _ _ **) as (? & ? & ? & ? & ?).\n  on (Forall2 _ (_ :: _) _), invc.\n  rename x into b_vs. rename y into b_e. rename l' into b_es.\n\n  eexists. split. eapply B.SPlusOne; i_lem B.SCloseStep.\n  + list_magic_on (vs, (b_vs, tt)).\n  + i_ctor. i_ctor. i_ctor.\n    i_lem Forall2_app. i_ctor. i_ctor.\n\n- (* SCloseDone *)\n  fwd eapply I_expr_map_value; eauto. subst.\n  eexists. split. eapply B.SPlusOne; i_lem B.SCloseDone.\n  eauto.\n\n- (* SConstrStep *)\n  destruct (Forall2_app_inv_l _ _ **) as (? & ? & ? & ? & ?).\n  on (Forall2 _ (_ :: _) _), invc.\n  rename x into b_vs. rename y into b_e. rename l' into b_es.\n\n  eexists. split. eapply B.SPlusOne; i_lem B.SConstrStep.\n  + list_magic_on (vs, (b_vs, tt)).\n  + i_ctor. i_ctor. i_ctor.\n    i_lem Forall2_app. i_ctor. i_ctor.\n\n- (* SConstrDone *)\n  fwd eapply I_expr_map_value; eauto. subst.\n  eexists. split. eapply B.SPlusOne; i_lem B.SConstrDone.\n  eauto.\n\n- (* SOpaqueOpStep *)\n  destruct (Forall2_app_inv_l _ _ **) as (? & ? & ? & ? & ?).\n  on (Forall2 _ (_ :: _) _), invc.\n  rename x into b_vs. rename y into b_e. rename l' into b_es.\n\n  eexists. split. eapply B.SPlusOne; i_lem B.SOpaqueOpStep.\n  + list_magic_on (vs, (b_vs, tt)).\n  + i_ctor. i_ctor. i_ctor.\n    i_lem Forall2_app. i_ctor. i_ctor.\n\n- (* SOpaqueOpDone *)\n  fwd eapply I_expr_map_value; eauto. subst.\n  eexists. split. eapply B.SPlusOne; i_lem B.SOpaqueOpDone.\n  eauto.\n\n- (* SCallL *)\n  eexists. split. eapply B.SPlusOne; i_lem B.SCallL.\n  i_ctor. i_ctor. i_ctor. i_ctor.\n\n- (* SCallL - ICallSelf *)\n  eexists. split. eapply B.SPlusOne; i_lem B.SCallL.\n  i_ctor. i_ctor. i_lem ICallSelf. i_ctor.\n\n- (* SCallL - ICallArg *)\n  eexists. split. eapply B.SPlusOne; i_lem B.SCallL.\n  i_ctor. i_ctor. i_lem ICallArg. i_ctor.\n\n- (* SCallR *)\n  eexists. split. eapply B.SPlusOne; i_lem B.SCallR.\n  i_ctor. i_ctor. i_ctor. i_ctor.\n\n- (* SCallR - ICallSelf *)\n  on (~ A.is_value (A.Value _)), contradict. i_ctor.\n\n- (* SCallR - ICallArg *)\n  on (~ A.is_value (A.Value _)), contradict. i_ctor.\n\n- (* SMakeCall *)\n  on (I_expr _ _ (A.Value (Close _ _)) _), invc.\n  on (I_expr _ _ (A.Value _) _), invc.\n  fwd i_lem Forall2_nth_error_ex as HH. destruct HH as (bbody & ? & ?).\n\n  eexists. split. eapply B.SPlusOne; i_lem B.SMakeCall.\n  i_ctor.\n\n- (* SMakeCall - ICallSelf *)\n  on (I_expr _ _ (A.Value (Close _ _)) _), invc.\n  fwd i_lem Forall2_nth_error_ex as HH. destruct HH as (bbody & ? & ?).\n\n  B_start HS.\n  B_step HS. { i_lem B.SCallR. i_ctor. inversion 1. }\n  B_step HS. { i_lem B.SSelf. }\n  B_step HS. { i_lem B.SMakeCall. }\n\n  eexists. split. exact HS.\n  i_ctor.\n\n- (* SMakeCall - ICallArg *)\n  on (I_expr _ _ (A.Value (Close _ _)) _), invc.\n  fwd i_lem Forall2_nth_error_ex as HH. destruct HH as (bbody & ? & ?).\n\n  B_start HS.\n  B_step HS. { i_lem B.SCallR. i_ctor. inversion 1. }\n  B_step HS. { i_lem B.SArg. }\n  B_step HS. { i_lem B.SMakeCall. }\n\n  eexists. split. exact HS.\n  i_ctor.\n\n- (* SElimStepLoop *)\n  on (loop = _ \\/ _), invc; cycle 1. { on (~ A.is_value _), contradict. i_ctor. } \n  on (I_expr _ _ _ bloop), invc.\n  eexists. split. eapply B.SPlusOne; i_lem B.SElimStepLoop.\n    { inversion 1. }\n  i_lem IInElimLoop. i_ctor. i_ctor. i_ctor.\n\n- (* SElimStep *)\n  on (target = _ \\/ _), invc; cycle 1. { on (~ A.is_value _), contradict. i_ctor. } \n  on (I_expr _ _ _ btarget), invc.\n  eexists. split. eapply B.SPlusOne; i_lem B.SElimStep.\n    { inversion 1. }\n  i_lem IInElimTarget. i_ctor. i_ctor. i_ctor.\n\n- (* SEliminate *)\n  do 2 (on (_ \\/ _), invc); try (discriminate || on >A.is_value, invc).\n  on (A.Value _ = A.Value _), invc.\n  on (I_expr _ _ _ bloop), invc.\n  on (I_expr _ _ _ btarget), invc.\n\n  fwd i_lem Forall2_nth_error_ex as HH.  destruct HH as (bcase & ? & ?).\n    on _, fun H => destruct H as (bcase0 & ? & ?).\n\n  eexists. split. eapply B.SPlusOne; i_lem B.SEliminate.\n    { i_ctor. }\n    { i_ctor. }\n  subst bcase. i_ctor. i_lem ICallArg. i_lem ICallSelf.\nQed.\n\n\n\nTheorem compile_cu_I_expr : forall A Ameta B Bmeta,\n    compile_cu (A, Ameta) = Some (B, Bmeta) ->\n    Forall2 (fun a b => forall vs va, I_expr vs va a b) A B.\nintros. simpl in *. repeat (break_bind_option || break_match; try discriminate).\ninject_some.\ni_lem compile_list_I_expr.\nQed.\n\nTheorem compile_cu_meta_eq : forall A Ameta B Bmeta,\n    compile_cu (A, Ameta) = Some (B, Bmeta) ->\n    Bmeta = Ameta.\nintros. simpl in *. repeat (break_bind_option || break_match; try discriminate).\ninject_some.\nreflexivity.\nQed.\n\n\n\nRequire Import oeuf.Semantics.\n\nSection Preservation.\n\n    Variable aprog : A.prog_type.\n    Variable bprog : B.prog_type.\n\n    Hypothesis Hcomp : compile_cu aprog = Some bprog.\n\n    Theorem fsim : Semantics.forward_simulation (A.semantics aprog) (B.semantics bprog).\n    destruct aprog as [A Ameta], bprog as [B Bmeta].\n    fwd eapply compile_cu_I_expr; eauto.\n    fwd eapply compile_cu_meta_eq; eauto. subst Bmeta.\n\n    eapply Semantics.forward_simulation_plus with\n        (match_states := I A B)\n        (match_values := @eq value).\n\n    - simpl. intros0 Bcall Hf Ha. invc Bcall. unfold fst, snd in *.\n    (*\n      fwd eapply compile_cu_public_value with (v := Close fname free); eauto.\n      fwd eapply compile_cu_public_value with (v := av2); eauto.\n      on (public_value Ameta (Close _ _)), invc.\n      fwd i_lem compile_cu_a_length.\n      fwd eapply length_nth_error_Some with (xs := Ameta) (ys := A) as HH; eauto.\n        destruct HH as [abody Habody].\n      fwd i_lem env_ok_nth_error.\n        { erewrite map_nth_error; [ | eauto ]. eauto. }\n        break_and.\n      *)\n      fwd i_lem Forall2_nth_error_ex' as HH. destruct HH as (abody & ? & ?).\n\n      eexists. split.\n      + i_ctor. i_ctor.\n      + i_ctor.\n\n    - simpl. intros0 II Afinal. invc Afinal. invc II.\n\n      eexists. split. 2: reflexivity.\n      econstructor; eauto.\n\n    - simpl. eauto.\n    - simpl. intros. tauto.\n\n    - intros0 Astep. intros0 II.\n      eapply splus_semantics_sim, I_sim; eauto.\n\n    Qed.\n\nEnd Preservation.\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/SwitchedComp1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.20335982781826217}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*            The CertiKOS Certified Kit Operating System              *)\n(*                                                                     *)\n(*                   The FLINT Group, Yale University                  *)\n(*                                                                     *)\n(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)\n(*  This file is distributed under the terms of the Yale University    *)\n(*  Non-Commercial License Agreement.                                  *)\n(*                                                                     *)\n(* *********************************************************************)\nRequire Import Coqlib.\nRequire Import Maps.\nRequire Import ASTExtra.\nRequire Import Integers.\nRequire Import Floats.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Events.\nRequire Import Stacklayout.\nRequire Import Globalenvs.\nRequire Import AsmX.\nRequire Import Smallstep.\nRequire Import AuxStateDataType.\nRequire Import Constant.\nRequire Import GlobIdent.\nRequire Import FlatMemory.\nRequire Import CommonTactic.\nRequire Import AuxLemma.\nRequire Import RealParams.\nRequire Import PrimSemantics.\nRequire Import LAsm.\nRequire Import XOmega.\n\nRequire Import compcert.cfrontend.Ctypes.\nRequire Import Conventions.\nRequire Import liblayers.logic.PTreeModules.\nRequire Import liblayers.logic.LayerLogicImpl.\nRequire Import liblayers.compat.CompatLayers.\n\nRequire Import AbstractDataType.\nRequire Import Soundness.\nRequire Import TSysCall.\nRequire Import LoadStoreSem3.\n\nRequire Import SecurityTactic.\nRequire Import SecurityLib.\n\nSection WITHMEM.\n\n  Local Open Scope Z_scope.\n\n  Context `{real_params: RealParams}.\n\n  Context `{Hstencil: Stencil}.\n  Context `{Hmem: Mem.MemoryModel}.\n  Context `{Hmwd: UseMemWithData mem}.\n\n  Local Instance : ExternalCallsOps (mwd (cdata RData)) := CompatExternalCalls.compatlayer_extcall_ops tsyscall.\n  Local Instance : LayerConfigurationOps := compatlayer_configuration_ops tsyscall.\n\n\n  Remark inv_some2 {A B} : \n    forall (x1 x2 : A) (y1 y2 : B), Some (x1,y1) = Some (x2,y2) -> x1 = x2 /\\ y1 = y2.\n  Proof.\n    intros.\n    inversion H; auto.\n  Qed.\n\n  Ltac inv_rewrite := \n    match goal with\n      | [ H : Some (_,_) = Some (_,_) |- _ ] => apply inv_some2 in H; destruct H\n      | [ H : Some _ = Some _ |- _ ] => apply inv_some in H\n    end; subst; simpl; auto.\n\n  Section OBS_EQ.\n\n    Function vread i vadr d :=\n      if zle_lt adr_low vadr adr_high  then\n        match ZMap.get (PDX vadr) (ZMap.get i (ptpool d)) with\n          | PDEValid _ pte =>\n            match ZMap.get (PTX vadr) pte with\n              | PTEValid pi _ => Some pi\n              | _ => None\n            end\n          | _ => None\n        end\n      else None.\n\n    (* Observable equivalence of abstract data *)\n    Record obs_eq (i: Z) (d1 d2: cdata RData) :=\n      {\n        (* hidden *) obs_eq_MM: True;  \n        (* hidden *) obs_eq_MMSize: True;\n        obs_eq_vmxinfo: True;\n        (* hidden *) obs_eq_CR3: True;\n        obs_eq_ti: True;\n        obs_eq_pg: pg d1 = pg d2;\n        obs_eq_ikern: ikern d1 = ikern d2;\n        obs_eq_ihost: ihost d1 = ihost d2;\n        obs_eq_HP: forall vadr pi1 pi2, \n                     vread i vadr d1 = Some pi1 ->\n                     vread i vadr d2 = Some pi2 ->\n                     forall o, \n                       ZMap.get (PTADDR pi1 o) (HP d1) = ZMap.get (PTADDR pi2 o) (HP d2);\n        obs_eq_AC_quota: cquota (ZMap.get i (AC d1)) - cusage (ZMap.get i (AC d1)) = \n                         cquota (ZMap.get i (AC d2)) - cusage (ZMap.get i (AC d2));\n        obs_eq_AC_used: cused (ZMap.get i (AC d1)) = cused (ZMap.get i (AC d2));\n        obs_eq_AT: True;\n        obs_eq_nps: True;\n        obs_eq_init: init d1 = init d2;\n        obs_eq_pperm: True;\n        obs_eq_PT: True;\n        obs_eq_ptpool: forall vadr,\n                         (vread i vadr d1 = None <-> vread i vadr d2 = None);\n        obs_eq_idpde: True;\n        obs_eq_ipt: ipt d1 = ipt d2;\n        obs_eq_LAT: True;\n        obs_eq_pb: True;\n        obs_eq_smspool: True;\n        obs_eq_kctxt: ZMap.get i (kctxt d1) = ZMap.get i (kctxt d2);\n        (* hidden *) obs_eq_tcb: True;\n        (* hidden *) obs_eq_tdq: True;\n        obs_eq_abtcb: ZMap.get i (abtcb d1) = ZMap.get i (abtcb d2);\n        obs_eq_abq: ZMap.get i (abq d1) = ZMap.get i (abq d2);\n        obs_eq_cid: i = cid d1 <-> i = cid d2;\n        obs_eq_syncchpool: True;\n        obs_eq_uctxt: ZMap.get i (uctxt d1) = ZMap.get i (uctxt d2);\n        obs_eq_ept: True;\n        obs_eq_vmcs: True;\n        obs_eq_vmx: True\n\n        (*obs_eq_unshared: unshared d1 i <-> unshared d2 i*)\n      }.\n\n    Inductive obs_eq_st : Z -> Asm.state(mem:=mwd (cdata RData)) -> \n                          Asm.state(mem:=mwd (cdata RData)) -> Prop :=\n    | obs_eq_st_intro :\n        forall id rs1 rs2 d1 d2 m,\n          obs_eq id d1 d2 ->\n          (id = cid d1 -> rs1 = rs2) ->\n          obs_eq_st id (State rs1 (m,d1)) (State rs2 (m,d2)).\n\n    Lemma obs_eq_refl :\n      forall id d, obs_eq id d d.\n    Proof.\n      intros; constructor; intros; rewrites; auto; reflexivity.\n    Qed.\n    \n    Lemma obs_eq_sym :\n      forall id d1 d2, obs_eq id d1 d2 -> obs_eq id d2 d1.\n    Proof.\n      intros id d1 d2 Hobs; destruct Hobs; constructor; auto; try solve [symmetry; auto].\n      intros; symmetry; eapply obs_eq_HP0; eauto.\n    Qed.\n\n    Lemma obs_eq_trans : \n      forall id d1 d2 d3, \n        obs_eq id d1 d2 -> obs_eq id d2 d3 -> obs_eq id d1 d3.\n    Proof.\n      intros id d1 d2 d3 Hobs1 Hobs2.\n      destruct Hobs1, Hobs2; constructor; try congruence.\n      - intros vadr p1 p3 Harg Hp1 Hp3; assert (exists p2, vread id vadr d2 = Some p2).\n        destruct (vread id vadr d2) eqn:Hp2; eauto.\n        rewrite obs_eq_ptpool1 in Hp2; auto; rewrites.\n        destruct H; intros; erewrite obs_eq_HP0, obs_eq_HP1; eauto.\n      - intros; rewrite obs_eq_ptpool0; auto.\n      - transitivity (id = cid d2); auto.\n    Qed.\n\n    Lemma obs_eq_st_refl :\n      forall id d rs m,\n        obs_eq_st id (State rs (m,d)) (State rs (m,d)).\n    Proof.\n      intros; constructor; auto; apply obs_eq_refl.\n    Qed.\n\n    Lemma obs_eq_st_sym :\n      forall id d1 d2 rs1 rs2 m1 m2, \n        obs_eq_st id (State rs1 (m1,d1)) (State rs2 (m2,d2)) -> \n        obs_eq_st id (State rs2 (m2,d2)) (State rs1 (m1,d1)).\n    Proof.\n      intros id d1 d2 rs1 rs2 m1 m2 Hobs; inv Hobs; constructor.\n      apply obs_eq_sym; auto.\n      destruct H2; intros; subst.\n      symmetry; apply H7; apply obs_eq_cid0; auto.\n    Qed.\n\n    Lemma obs_eq_st_trans : \n      forall id d1 d2 d3 rs1 rs2 rs3 m1 m2 m3, \n        obs_eq_st id (State rs1 (m1,d1)) (State rs2 (m2,d2)) -> \n        obs_eq_st id (State rs2 (m2,d2)) (State rs3 (m3,d3)) ->\n        obs_eq_st id (State rs1 (m1,d1)) (State rs3 (m3,d3)).\n    Proof.\n      intros id d1 d2 d3 rs1 rs2 rs3 m1 m2 m3 Hobs1 Hobs2.\n      inv Hobs1; inv Hobs2; constructor.\n      apply obs_eq_trans with (d2:= d2); auto.\n      intros; subst; destruct H2.\n      transitivity rs2; auto; apply H9; apply obs_eq_cid0; auto.\n    Qed.\n\n  End OBS_EQ.\n\n  Ltac unshared_simpl_iff :=\n    match goal with\n    | [ |- unshared _ _ <-> unshared (update_LAT (?f _ _) _) _ ] => \n      let H := fresh in let Hunsh := fresh in let Hown1 := fresh in let Hown2 := fresh in\n        assert (H: forall d id v lat, unshared (update_LAT d lat) id <-> \n                                      unshared (update_LAT (f d v) lat) id) \n          by (unfold unshared; intros; split; intros Hunsh ? Hown1 ? Hown2;\n              inv Hown1; inv Hown2; simpl in *; eapply Hunsh; rewrites; econstructor; eauto);\n        rewrite <- H; clear H\n    | [ |- unshared _ _ <-> unshared (?f _ _) _ ] => \n      let H := fresh in let Hunsh := fresh in let Hown1 := fresh in let Hown2 := fresh in\n        assert (H: forall d id v, unshared d id <-> unshared (f d v) id) \n          by (unfold unshared; intros; split; intros Hunsh ? Hown1 ? Hown2;\n              inv Hown1; inv Hown2; simpl in *; eapply Hunsh; rewrites; econstructor; eauto);\n        rewrite <- H; clear H\n    end.\n\n  Ltac isOwner_rewrite :=\n    match goal with\n    | [ H: isOwner (?f _ _) _ _ |- _ ] =>\n      let H' := fresh in let Hown := fresh in\n        assert (H': forall d v id p, isOwner (f d v) id p -> isOwner d id p)\n          by (intros ? ? ? ? Hown; inv Hown; econstructor; eauto);\n        apply H' in H; clear H'\n    | [ |- isOwner (?f _ _) _ _ ] =>\n      let H' := fresh in let Hown := fresh in\n        assert (H': forall d v id p, isOwner d id p -> isOwner (f d v) id p)\n          by (intros ? ? ? ? Hown; inv Hown; econstructor; eauto);\n        apply H'; clear H'\n    end.\n\n  Ltac solve_isOwner :=\n    repeat isOwner_simpl_iff; try reflexivity; try assumption; auto.\n\n  Ltac solve_unshared :=\n    repeat unshared_simpl_iff; try reflexivity; try assumption; auto.\n\n  Ltac solve_obs_eq :=\n    match goal with\n    | [ H: obs_eq _ _ _ |- _ ] =>\n      destruct H; constructor; simpl; auto; \n          try solve [intros; isOwner_rewrite; auto\n                   | match goal with\n                     | [ Hcid: _ = cid _ <-> _ = cid _ |- _ ] =>\n                       rewrite <- (proj1 Hcid); auto;\n                         repeat rewrite ZMap.gss; subrewrite\n                     end\n                   | intro; solve_isOwner\n                   | solve_unshared]\n    end.\n\n  Ltac vread_simpl :=\n    match goal with\n    | [ H: vread _ _ (?f _ _) = _ |- _ ] =>\n      let H' := fresh in \n        assert (H': forall id vadr d v, vread id vadr (f d v) = vread id vadr d)\n          by (unfold vread, ptRead_spec, getPTE_spec; simpl; reflexivity); rewrite H' in H; clear H'\n    | [ |- context [vread _ _ (?f _ _) = _ ] ] =>\n      let H' := fresh in \n        assert (H': forall id vadr d v, vread id vadr (f d v) = vread id vadr d)\n          by (unfold vread, ptRead_spec, getPTE_spec; simpl; reflexivity); rewrite H'; clear H'\n    | [ |- vread _ _ (?f _ _) <-> vread _ _ (?f _ _)] =>\n      let H' := fresh in \n        assert (H': forall id vadr d v, vread id vadr (f d v) = vread id vadr d)\n          by (unfold vread, ptRead_spec, getPTE_spec; simpl; reflexivity); rewrite H'; clear H'\n    | [ H: vread _ _ (update_ptpool (?f _ _) _) = _ |- _ ] =>\n      let H' := fresh in \n        assert (H': forall id vadr d v p, \n                      vread id vadr (update_ptpool (f d v) p) = \n                      vread id vadr (update_ptpool d p))\n          by (unfold vread, ptRead_spec, getPTE_spec; simpl; reflexivity); rewrite H' in H; clear H'\n    | [ |- context [vread _ _ (update_ptpool (?f _ _) _) = _ ] ] =>\n      let H' := fresh in \n        assert (H': forall id vadr d v p, \n                      vread id vadr (update_ptpool (f d v) p) = \n                      vread id vadr (update_ptpool d p))\n          by (unfold vread, ptRead_spec, getPTE_spec; simpl; reflexivity); rewrite H'; clear H'\n    | [ |- vread _ _ (update_ptpool (?f _ _) _) <-> vread _ _ (update_ptpool (?f _ _) _) ] =>\n      let H' := fresh in \n        assert (H': forall id vadr d v p, \n                      vread id vadr (update_ptpool (f d v) p) = \n                      vread id vadr (update_ptpool d p))\n          by (unfold vread, ptRead_spec, getPTE_spec; simpl; reflexivity); rewrite H'; clear H'\n    end.\n    \n\n  Lemma quota_convert :\n    forall a b, (a <? b) = (0 <? b - a).\n  Proof.\n    intros.\n    destruct (a <? b) eqn:H1; destruct (0 <? b - a) eqn:H2; auto.\n    rewrite Z.ltb_lt in H1; rewrite Z.ltb_nlt in H2; omega.\n    rewrite Z.ltb_nlt in H1; rewrite Z.ltb_lt in H2; omega.\n  Qed.\n\n  Ltac obs_eq_rewrites :=\n    match goal with\n    | [H: obs_eq _ _ _ |- _ ] => destruct H\n    | _ => idtac\n    end;\n    repeat match goal with\n    | [ H: _ = cid _ <-> _ = cid _ |- _ ] => \n      rewrite <- (proj1 H) in *; auto\n    | [ H: ikern _ = ikern _ |- _ ] => rewrite <- H in *\n    | [ H: ihost _ = ihost _ |- _ ] => rewrite <- H in *\n    | [ H: pg _ = pg _ |- _ ] => rewrite <- H in *\n    | [ H: ipt _ = ipt _ |- _ ] => rewrite <- H in *\n    | [ H: PT _ = PT _ |- _ ] => rewrite <- H in *\n    | [ H: nps _ = nps _ |- _ ] => rewrite <- H in *\n    | [ H: init _ = init _ |- _ ] => rewrite <- H in *\n    | [ H: cquota _ - cusage _ = cquota _ - cusage _ |- _ ] => \n      try rewrite quota_convert in *; rewrite <- H in *\n    | [ H: cused (ZMap.get ?id (AC _)) = cused (ZMap.get ?id (AC _)) |- _ ] =>\n      rewrite <- H in *\n    | [ H: ZMap.get ?id (uctxt _) = ZMap.get ?id (uctxt _) |- _ ] => \n      rewrite <- H in *\n    | [ H: ZMap.get ?id (ptpool _) = ZMap.get ?id (ptpool _) |- _ ] => \n      rewrite <- H in *\n    | [ H: ZMap.get ?id (kctxt _) = ZMap.get ?id (kctxt _) |- _ ] => \n      rewrite <- H in *\n    end; rewrites; auto.\n\n  Section CONF_LEMMAS.\n\n    Section CONF_UCTX.\n\n      Lemma conf_uctx_set_errno :\n        forall d1 d2 d1' d2' n,\n          uctx_set_errno_spec n d1 = Some d1' ->\n          uctx_set_errno_spec n d2 = Some d2' ->\n          obs_eq (cid d1) d1 d2 -> obs_eq (cid d1) d1' d2'.\n      Proof.\n        intros d1 d2 d1' d2' n Hspec1 Hspec2 Hobs_eq.\n        inv_spec; inv Hspec1; inv Hspec2; solve_obs_eq.\n      Qed.\n\n      Lemma conf_uctx_arg1 :\n        forall d1 d2 r1 r2,\n          uctx_arg1_spec d1 = Some r1 ->\n          uctx_arg1_spec d2 = Some r2 ->\n          obs_eq (cid d1) d1 d2 -> r1 = r2.\n      Proof.\n        intros; inv_spec; obs_eq_rewrites.\n      Qed.\n\n      Lemma conf_uctx_arg2 :\n        forall d1 d2 r1 r2,\n          uctx_arg2_spec d1 = Some r1 ->\n          uctx_arg2_spec d2 = Some r2 ->\n          obs_eq (cid d1) d1 d2 -> r1 = r2.\n      Proof.\n        intros; inv_spec; obs_eq_rewrites.\n      Qed.\n\n      Lemma conf_uctx_arg3 :\n        forall d1 d2 r1 r2,\n          uctx_arg3_spec d1 = Some r1 ->\n          uctx_arg3_spec d2 = Some r2 ->\n          obs_eq (cid d1) d1 d2 -> r1 = r2.\n      Proof.\n        intros; inv_spec; obs_eq_rewrites.\n      Qed.\n\n      Lemma conf_uctx_arg4 :\n        forall d1 d2 r1 r2,\n          uctx_arg4_spec d1 = Some r1 ->\n          uctx_arg4_spec d2 = Some r2 ->\n          obs_eq (cid d1) d1 d2 -> r1 = r2.\n      Proof.\n        intros; inv_spec; obs_eq_rewrites.\n      Qed.\n\n      Lemma conf_uctx_arg5 :\n        forall d1 d2 r1 r2,\n          uctx_arg5_spec d1 = Some r1 ->\n          uctx_arg5_spec d2 = Some r2 ->\n          obs_eq (cid d1) d1 d2 -> r1 = r2.\n      Proof.\n        intros; inv_spec; obs_eq_rewrites.\n      Qed.\n\n      Lemma conf_uctx_set_retval1 :\n        forall d1 d2 d1' d2' n,\n          uctx_set_retval1_spec n d1 = Some d1' ->\n          uctx_set_retval1_spec n d2 = Some d2' ->\n          obs_eq (cid d1) d1 d2 -> obs_eq (cid d1) d1' d2'.\n      Proof.\n        intros d1 d2 d1' d2' n Hspec1 Hspec2 Hobs_eq.\n        inv_spec; inv Hspec1; inv Hspec2; solve_obs_eq.\n      Qed.\n\n      Lemma conf_uctx_set_retval2 :\n        forall d1 d2 d1' d2' n,\n          uctx_set_retval2_spec n d1 = Some d1' ->\n          uctx_set_retval2_spec n d2 = Some d2' ->\n          obs_eq (cid d1) d1 d2 -> obs_eq (cid d1) d1' d2'.\n      Proof.\n        intros d1 d2 d1' d2' n Hspec1 Hspec2 Hobs_eq.\n        inv_spec; inv Hspec1; inv Hspec2; solve_obs_eq.\n      Qed.\n\n      Lemma conf_uctx_set_retval3 :\n        forall d1 d2 d1' d2' n,\n          uctx_set_retval3_spec n d1 = Some d1' ->\n          uctx_set_retval3_spec n d2 = Some d2' ->\n          obs_eq (cid d1) d1 d2 -> obs_eq (cid d1) d1' d2'.\n      Proof.\n        intros d1 d2 d1' d2' n Hspec1 Hspec2 Hobs_eq.\n        inv_spec; inv Hspec1; inv Hspec2; solve_obs_eq.\n      Qed.\n\n      Lemma conf_uctx_set_retval4 :\n        forall d1 d2 d1' d2' n,\n          uctx_set_retval4_spec n d1 = Some d1' ->\n          uctx_set_retval4_spec n d2 = Some d2' ->\n          obs_eq (cid d1) d1 d2 -> obs_eq (cid d1) d1' d2'.\n      Proof.\n        intros d1 d2 d1' d2' n Hspec1 Hspec2 Hobs_eq.\n        inv_spec; inv Hspec1; inv Hspec2; solve_obs_eq.\n      Qed.\n\n      Lemma conf_uctx_set_retval5 :\n        forall d1 d2 d1' d2' n,\n          uctx_set_retval5_spec n d1 = Some d1' ->\n          uctx_set_retval5_spec n d2 = Some d2' ->\n          obs_eq (cid d1) d1 d2 -> obs_eq (cid d1) d1' d2'.\n      Proof.\n        intros d1 d2 d1' d2' n Hspec1 Hspec2 Hobs_eq.\n        inv_spec; inv Hspec1; inv Hspec2; solve_obs_eq.\n      Qed.\n\n    End CONF_UCTX.\n\n    Ltac rewrites :=\n      repeat (match goal with\n              | [ Heq1: ?a = _, Heq2: ?a = _ |- _ ] => rewrite Heq2 in Heq1; inv Heq1\n              | [ Heq: ?a = _ |- context [if ?a then _ else _] ] => rewrite Heq\n              | [ Heq: _ = ?a |- context [if ?a then _ else _ ] ] => rewrite <- Heq\n              | [ Heq: ?a = _ |- context [match ?a with _ => _ end ] ] => rewrite Heq\n              | [ Heq: _ = ?a |- context [match ?a with _ => _ end ] ] => rewrite <- Heq\n              end).\n\n    Ltac eqdestruct :=\n      repeat match goal with\n      | [ |- if ?a then _ else _ = if ?a then _ else _ ] => \n        let H := fresh \"Hdestruct\" in destruct a eqn:H; auto\n      | [ |- match ?a with _ => _ end = match ?a with _ => _ end ] => \n        let H := fresh \"Hdestruct\" in destruct a eqn:H; auto\n      end.\n\n    Ltac destructgoal :=\n      repeat match goal with\n      | [ |- if ?a then _ else _ = _ ] => \n        let H := fresh \"Hdestruct\" in destruct a eqn:H; auto\n      | [ |- match ?a with _ => _ end = _ ] => \n        let H := fresh \"Hdestruct\" in destruct a eqn:H; auto\n      end.\n\n    Section CONF_GET_QUOTA.\n\n      Lemma conf_trap_get_quota :\n        forall d1 d2 d1' d2',\n          trap_get_quota_spec d1 = Some d1' ->\n          trap_get_quota_spec d2 = Some d2' ->\n          obs_eq (cid d1) d1 d2 -> obs_eq (cid d1) d1' d2'.\n      Proof.\n        intros d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        repeat inv_spec; repeat inv_rewrite; simpl in *.\n        destruct Hobs_eq; constructor; simpl; auto.\n        obs_eq_rewrites; repeat rewrite ZMap.gss; reflexivity.\n      Qed.\n\n    End CONF_GET_QUOTA.\n\n    Ltac elim_stuck' H :=\n      match type of H with\n      | match ?X with | _ => _ end = Next _ _ => destruct X; try discriminate H\n      | if ?X then _ else _ = Next _ _  => destruct X; try discriminate H\n      end.\n\n    Ltac elim_stuck_eqn' H H' :=\n      match type of H with\n      | match ?X with | _ => _ end = Next _ _ => destruct X eqn:H'; try discriminate H\n      | if ?X then _ else _ = Next _ _ => destruct X eqn:H'; try discriminate H\n      end.\n\n    Section CONF_ACCESSORS.\n\n      Lemma PDEValid_usr :\n        forall id i d pti pte,\n          high_level_invariant d -> ikern d = false -> 0 <= id < num_id ->\n          ZMap.get (PDX (Int.unsigned i)) (ZMap.get id (ptpool d)) = PDEValid pti pte ->\n          adr_low <= Int.unsigned i < adr_high.\n      Proof.\n        intros id i d pti pte Hinv Hkern Hid Hpdx.\n        assert (Hrange:= Int.unsigned_range_2 i).\n        assert (Hmax:= max_unsigned_val).\n        destruct Hinv.\n        destruct (valid_PMap (valid_kern Hkern) id Hid) as [Hpmap _].\n        assert (Hcases: adr_low <= Int.unsigned i < adr_high \\/\n                (0 <= Int.unsigned i < 262144*PgSize \\/ \n                 983040*PgSize <= Int.unsigned i < 1048576*PgSize)) by omega.\n        destruct Hcases as [|Hcases]; auto.\n        assert (Hk: 0 <= Int.unsigned i / PgSize < 262144 \\/\n                983040 <= Int.unsigned i / PgSize < 1048576) \n          by  (destruct Hcases; [left|right]; split;\n               try (apply Zdiv_le_lower_bound; omega); \n               try (apply Zdiv_lt_upper_bound; omega)).\n        specialize (Hpmap _ Hk); unfold PDE_kern in Hpmap.\n        replace (PDX (Int.unsigned i / 4096 * 4096)) with (PDX (Int.unsigned i)) in Hpmap.\n        rewrites.\n        unfold PDX.\n        rewrite (Z_div_mod_eq (Int.unsigned i) PgSize); try omega.\n        repeat rewrite <- Zdiv.Zdiv_Zdiv; try omega.\n        rewrite Z.mul_comm.\n        rewrite Z_div_plus_full_l; try omega.\n        rewrite (Zdiv_small (Int.unsigned i mod PgSize) PgSize).\n        rewrite Zplus_0_r.\n        rewrite Z_div_mult_full; try omega.\n        apply Z_mod_lt; omega.\n      Qed.\n\n      Lemma conf_flatmem_load :\n        forall id d1 d2, obs_eq id d1 d2 ->\n          forall vadr p1 p2, vread id vadr d1 = Some p1 -> vread id vadr d2 = Some p2 ->\n            forall o chunk, o mod PgSize + (size_chunk chunk) <= PgSize ->\n                            FlatMem.load chunk (HP d1) (PTADDR p1 o) = FlatMem.load chunk (HP d2) (PTADDR p2 o).\n      Proof.\n        intros id d1 d2 Hobs_eq vadr p1 p2 Hrd1 Hrd2 o chunk Hchunk.\n        eapply FlatMem.load_rep'; [|eauto|eauto].\n        intros z Hz.\n        assert (Hmath: forall p, PTADDR p o + z = PTADDR p (o+z)).\n        {\n          unfold PTADDR; intro p.\n          rewrite <- Zplus_assoc; rewrite <- Zplus_mod_idemp_l.\n          rewrite (Zmod_small (o mod PgSize + z)); auto.\n          assert (Hlt: 0 < PgSize) by omega.\n          assert (Hpos := Z.mod_pos_bound o _ Hlt); omega.\n        }\n        rewrite 2 Hmath; destruct Hobs_eq.\n        eapply obs_eq_HP0; eauto.\n      Qed.\n      \n      Lemma conf_exec_loadex {F V} :\n        forall (m m1' m2' : mem) (d1 d2 d1' d2': cdata RData) rs rs1' rs2' ge chunk a rd, \n          exec_loadex(F:=F)(V:=V) ge chunk (m, d1) a rs rd = Next rs1' (m1', d1') ->\n          exec_loadex ge chunk (m, d2) a rs rd = Next rs2' (m2', d2') ->\n          high_level_invariant d1 -> high_level_invariant d2 -> \n          ikern d1 = false -> ihost d1 = true ->\n          obs_eq (cid d1) d1 d2 -> (obs_eq (cid d1) d1' d2' /\\ rs1' = rs2') /\\ m1' = m2'.\n      Proof.\n        intros m m1' m2' d1 d2 d1' d2' rs rs1' rs2' ge chunk a rd\n               Hstep1 Hstep2 Hinv1 Hinv2 Hkern Hhost Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq'.\n        unfold exec_loadex, exec_loadex3 in *; subdestruct; simpl in *; try congruence.\n        {\n          (* host mode *)\n          unfold HostAccess2.exec_host_load2, snd in *.\n          elim_stuck_eqn' Hstep1 Hpdx1; elim_stuck_eqn' Hstep2 Hpdx2.\n          rename pi into pti1, pi0 into pti2, pte into pte1, pte0 into pte2.\n          assert (Hcases1: (exists v pm, ZMap.get (PTX (Int.unsigned i)) pte1 = PTEValid v pm) \\/ \n                           ZMap.get (PTX (Int.unsigned i)) pte1 = PTEUnPresent)\n            by (clear Hstep2; subdestruct; [left|left|right]; eauto).\n          assert (Hcases2: (exists v pm, ZMap.get (PTX (Int.unsigned i)) pte2 = PTEValid v pm) \\/ \n                           ZMap.get (PTX (Int.unsigned i)) pte2 = PTEUnPresent)\n            by (clear Hstep1; subdestruct; [left|left|right]; eauto).\n          destruct Hcases1 as [[pi1 [pm1 Hvalid1]]|Hunp1].\n          {\n            assert (Hm: match ZMap.get (PTX (Int.unsigned i)) pte1 with\n                        | PTEValid v PTP =>\n                          FlatLoadStoreSem.exec_flatmem_load chunk \n                            (m, d1) (PTADDR v (Int.unsigned i)) rs rd\n                        | PTEValid v PTU =>\n                          FlatLoadStoreSem.exec_flatmem_load chunk \n                            (m, d1) (PTADDR v (Int.unsigned i)) rs rd\n                        | PTEValid v (PTK _) => Stuck\n                        | PTEUnPresent => PageFault.exec_pagefault ge (m, d1) i rs\n                        | PTEUndef => Stuck\n                         end = FlatLoadStoreSem.exec_flatmem_load chunk \n                                 (m, d1) (PTADDR pi1 (Int.unsigned i)) rs rd)\n              by (clear Hstep2; destruct pm1; rewrite Hvalid1 in Hstep1; \n                  subdestruct; rewrite Hvalid1; auto).\n            rewrite Hm in Hstep1; clear Hm.\n            assert (Husr: adr_low <= Int.unsigned i < adr_high).\n            {             \n              eapply PDEValid_usr; eauto.\n              destruct Hinv2; rewrite valid_init_PT_cid; auto.\n            }\n            destruct Hcases2 as [[pi2 [pm2 Hvalid2]]|Hunp2].\n            {\n              assert (Hm: match ZMap.get (PTX (Int.unsigned i)) pte2 with\n                        | PTEValid v PTP =>\n                          FlatLoadStoreSem.exec_flatmem_load chunk \n                            (m, d2) (PTADDR v (Int.unsigned i)) rs rd\n                        | PTEValid v PTU =>\n                          FlatLoadStoreSem.exec_flatmem_load chunk \n                            (m, d2) (PTADDR v (Int.unsigned i)) rs rd\n                        | PTEValid v (PTK _) => Stuck\n                        | PTEUnPresent => PageFault.exec_pagefault ge (m, d2) i rs\n                        | PTEUndef => Stuck\n                         end = FlatLoadStoreSem.exec_flatmem_load chunk \n                                 (m, d2) (PTADDR pi2 (Int.unsigned i)) rs rd)\n              by (clear Hstep1; destruct pm2; rewrite Hvalid2 in Hstep2; \n                  subdestruct; rewrite Hvalid2; auto).\n            rewrite Hm in Hstep2; clear Hm.\n            subdestruct.\n            unfold FlatLoadStoreSem.exec_flatmem_load in *; inv Hstep1; inv Hstep2.\n            assert (Hobs_eq': obs_eq (cid d1') d1' d2') by (constructor; auto; congruence).            \n            rewrite (conf_flatmem_load (cid d1') _ d2' Hobs_eq' (Int.unsigned i) _ pi2); auto.\n            - unfold vread; rewrite zle_lt_true; auto.\n              destruct Hinv1; rewrite <- valid_init_PT_cid; rewrites; auto.\n            - unfold vread; rewrite zle_lt_true; auto.\n              destruct Hinv2; rewrite (proj1 obs_eq_cid0); auto.\n              rewrite <- valid_init_PT_cid; rewrites; auto.\n            - clear Hdestruct6; omega.\n          }\n          {\n            assert (Hcon: vread (cid d1) (Int.unsigned i) d2 = None).\n            {\n              unfold vread; destructgoal.\n              destruct Hinv2; rewrite (proj1 obs_eq_cid0) in Hdestruct7; auto.\n              rewrite <- valid_init_PT_cid in Hdestruct7; rewrites; auto.\n            }\n            rewrite <- obs_eq_ptpool0 in Hcon; unfold vread in Hcon.\n            rewrite zle_lt_true in Hcon; auto.\n            destruct Hinv1; rewrite <- valid_init_PT_cid in Hcon; auto.\n            rewrite Hpdx1, Hvalid1 in Hcon; discriminate Hcon.\n          }\n        }\n        {\n          destruct Hcases2 as [[pi2 [pm2 Hvalid2]]|Hunp2].\n          {\n            assert (Hm: match ZMap.get (PTX (Int.unsigned i)) pte2 with\n                          | PTEValid v PTP =>\n                            FlatLoadStoreSem.exec_flatmem_load chunk \n                              (m, d2) (PTADDR v (Int.unsigned i)) rs rd\n                          | PTEValid v PTU =>\n                            FlatLoadStoreSem.exec_flatmem_load chunk \n                              (m, d2) (PTADDR v (Int.unsigned i)) rs rd\n                          | PTEValid v (PTK _) => Stuck\n                          | PTEUnPresent => PageFault.exec_pagefault ge (m, d2) i rs\n                          | PTEUndef => Stuck\n                        end = FlatLoadStoreSem.exec_flatmem_load chunk \n                                                                 (m, d2) (PTADDR pi2 (Int.unsigned i)) rs rd)\n              by (clear Hstep1; destruct pm2; rewrite Hvalid2 in Hstep2; \n                  subdestruct; rewrite Hvalid2; auto).\n            rewrite Hm in Hstep2; clear Hm.\n            assert (Hcon: vread (cid d1) (Int.unsigned i) d1 = None).\n            {\n              unfold vread; destructgoal.\n              destruct Hinv1; rewrite <- valid_init_PT_cid in Hdestruct7; rewrites; auto.\n            }\n            rewrite obs_eq_ptpool0 in Hcon; unfold vread in Hcon.\n            rewrite zle_lt_true in Hcon.\n            rewrite (proj1 obs_eq_cid0) in Hcon; auto.\n            destruct Hinv2; rewrite <- valid_init_PT_cid in Hcon; auto.\n            rewrite Hpdx2, Hvalid2 in Hcon; discriminate Hcon.\n            eapply PDEValid_usr; eauto.\n            destruct Hinv2; rewrite valid_init_PT_cid; auto.\n          }\n          {\n            unfold PageFault.exec_pagefault in *; subdestruct; inv Hstep1; inv Hstep2.\n            unfold trapinfo_set; repeat (apply conj; auto).\n            constructor; simpl; auto; congruence.\n          }\n        }\n      }\n      \n        (* guest mode *)\n       (*\n        unfold GuestAccessIntel2.exec_guest_intel_load2 in *.\n        unfold GuestAccessIntelDef2.exec_guest_intel_accessor2, GuestAccessIntel2.load_accessor2, snd in *.\n        Print RData.\n        Print VMCS.\n        subdestruct.\n        unfold FlatLoadStoreSem.exec_flatmem_load in *; inv Hstep1; inv Hstep2.\n        repeat (apply conj; auto).\n        unfold EPTADDR.\n        Eval compute in FlatLoadStoreSem.exec_flatmem_load.\n        unfold \n        Print ptRead_spec.\n        Print EPT_PML4_INDEX.\n        rewrite (conf_flatmem_load (cid d1') _ d2' Hobs_eq (Int.unsigned i) _ (hpa/PgSize)); auto.\n        unfold vread.\n        Print EPT_PDPT_INDEX.\n        Print EPT_PML4_INDEX.\n        Print EPT_PDIR_INDEX.\n        Print EPT_PTAB_INDEX.\n        clear Hdestruct4; omega.\n*)\n      (*\n      {\n        (* guest mode *)\n        (* need to add epmap_consistent invariant to prove this lemma for guest mode *)\n        \n        unfold GuestAccessIntel2.exec_guest_intel_load2 in *.\n        unfold GuestAccessIntelDef2.exec_guest_intel_accessor2, GuestAccessIntel2.load_accessor2 in *.\n        subdestruct.\n        unfold FlatLoadStoreSem.exec_flatmem_load, snd in *.\n        rewrite_fld ept; inv Hstep1; inv Hstep2.\n        rewrites; rewrite (conf_flatmem_load (cid d1') _ d2'); auto.\n        eapply pmap_owners_consistent; eauto.\n        apply valid_curid; auto.\n        apply Int.unsigned_range.\n        rewrite <- valid_init_PT_cid; eauto.\n        unfold PTADDR.\n        rewrite Z.add_1_r.\n        rewrite <- Zmult_succ_l_reverse.\n        rewrite (Zmod_small 0); try omega.\n        }*)\n      Qed.\n\n      Lemma conf_exec_storeex {F V} :\n        forall id (m m1' m2' : mem) (d1 d2 d1' d2': cdata RData) rs rs1' rs2' ge chunk a rs0 l, \n          exec_storeex(F:=F)(V:=V) ge chunk (m, d1) a rs rs0 l = Next rs1' (m1', d1') ->\n          exec_storeex ge chunk (m, d2) a rs rs0 l = Next rs2' (m2', d2') ->\n          ikern d1 = false -> obs_eq id d1 d2 -> (obs_eq id d1' d2' /\\ rs1' = rs2') /\\ m1' = m2'.\n      Proof.\n        intros id m m1' m2' d1 d2 d1' d2' rs rs1' rs2' ge chunk a s0 l\n               Hstep1 Hstep2 Hkern Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold exec_storeex, exec_storeex3 in *; subdestruct; simpl in *;\n        try solve [inv Hnh; simpl in *; congruence].\n        {\n          (* host mode *)\n          unfold HostAccess2.exec_host_store2, snd in *.\n          assert (Hpdx: ZMap.get (PDX (Int.unsigned i)) (ZMap.get (PT d1) (ptpool d1)) = \n                        ZMap.get (PDX (Int.unsigned i)) (ZMap.get (PT d2) (ptpool d2))) by (inv Hnh; auto).\n\n          rewrite <- Hpdx in Hstep2; subdestruct.\n          {\n            unfold FlatLoadStoreSem.exec_flatmem_store, flatmem_store in *.\n            assert (Hperm: pperm d1 = pperm d2) by (inv Hnh; auto).\n            unfold snd in *; rewrite <- Hperm in Hstep2; subdestruct; inv Hstep1; inv Hstep2.\n            repeat (apply conj; auto); constructor.\n            inv Hnh; constructor; auto.\n            intros p Hown o; simpl.\n            assert (Hcases: PTADDR v (Int.unsigned i) <= PTADDR p o < PTADDR v (Int.unsigned i) + \n                                                                      Z.of_nat (length (encode_val chunk (rs s0))) \\/ \n                            (PTADDR p o < PTADDR v (Int.unsigned i) \\/\n                             PTADDR p o >= PTADDR v (Int.unsigned i) + \n                                           Z.of_nat (length (encode_val chunk (rs s0))))) by omega. \n            unfold FlatMem.store; destruct Hcases as [Hcase|Hcase].\n            - rewrite 2 (get_setN_charact' _ _ _ _ Hcase); reflexivity.\n            - rewrite 2 FlatMem.setN_outside; auto.\n              apply Hhp; inv Hown; econstructor; eauto.\n          }\n          {\n            unfold FlatLoadStoreSem.exec_flatmem_store, flatmem_store in *.\n            assert (Hperm: pperm d1 = pperm d2) by (inv Hnh; auto).\n            unfold snd in *; rewrite <- Hperm in Hstep2; subdestruct; inv Hstep1; inv Hstep2.\n            repeat (apply conj; auto); constructor.\n            inv Hnh; constructor; auto.\n            intros p Hown o; simpl.\n            assert (Hcases: PTADDR v (Int.unsigned i) <= PTADDR p o < PTADDR v (Int.unsigned i) + \n                                                                      Z.of_nat (length (encode_val chunk (rs s0))) \\/ \n                            (PTADDR p o < PTADDR v (Int.unsigned i) \\/\n                             PTADDR p o >= PTADDR v (Int.unsigned i) + \n                                           Z.of_nat (length (encode_val chunk (rs s0))))) by omega. \n            unfold FlatMem.store; destruct Hcases as [Hcase|Hcase].\n            - rewrite 2 (get_setN_charact' _ _ _ _ Hcase); reflexivity.\n            - rewrite 2 FlatMem.setN_outside; auto.\n              apply Hhp; inv Hown; econstructor; eauto.\n          }\n          {\n            unfold PageFault.exec_pagefault in *; subdestruct; inv Hstep1; inv Hstep2.\n            unfold trapinfo_set; repeat (apply conj; auto); solve_obs_eq Hhp.\n          }\n        }\n        {\n          (* guest mode *)\n          unfold GuestAccessIntel2.exec_guest_intel_store2 in *.\n          unfold GuestAccessIntelDef2.exec_guest_intel_accessor2, GuestAccessIntel2.store_accessor2 in *.\n          subdestruct.\n          unfold FlatLoadStoreSem.exec_flatmem_store, flatmem_store, snd in *; inv Hstep1; inv Hstep2.\n          rewrite_fld ept; rewrite_fld pperm; rewrites.\n          subdestruct; inv H0; inv H1.\n          repeat (apply conj; auto); constructor.\n          nonHP_simpl; auto.\n          intros p Hown o; simpl.\n          assert (Hcases: EPTADDR (hpa0/PgSize) (Int.unsigned i) <= PTADDR p o \n                          < EPTADDR (hpa0/PgSize) (Int.unsigned i) + \n                            Z.of_nat (length (encode_val chunk (rs s0))) \\/ \n                          (PTADDR p o < EPTADDR (hpa0/PgSize) (Int.unsigned i) \\/\n                           PTADDR p o >= EPTADDR (hpa0/PgSize) (Int.unsigned i) + \n                                         Z.of_nat (length (encode_val chunk (rs s0))))) by omega. \n          unfold FlatMem.store; destruct Hcases as [Hcase|Hcase].\n          - rewrite 2 (get_setN_charact' _ _ _ _ Hcase); reflexivity.\n          - rewrite 2 FlatMem.setN_outside; auto.\n            apply Hhp; inv Hown; econstructor; eauto.\n        }\n      Qed.\n\n    End CONF_ACCESSORS.\n\n    End CONF_GET_QUOTA.\n\n\n    Section CONF_TSC_OFFSET.\n\n      Print vmx_get_tsc_offset_spec.\n\n      Lemma conf_vmx_get_tsc_offset :\n        \n\n      Print trap_get_tsc_offset_spec.\n\n      Lemma conf_vmx_get_tsc_off_set :\n        \n\n    End CONF_TSC_OFFSET.\n\n(* can i just turn off trap_mmap? seems needed only for virtualization *)\n    Section CONF_MMAP.\n\n      Lemma ptAllocPDE0_vread_gso :\n        forall id v vadr p d,\n          PDX v <> PDX vadr ->\n          vread id v d{ptpool: ZMap.set id (ZMap.set (PDX vadr) \n                                       (PDEValid p CalRealInitPTE.real_init_PTE) \n                                       (ZMap.get id (ptpool d))) (ptpool d)} = vread id v d.\n      Proof.\n        unfold vread, ptRead_spec, getPTE_spec; intros; subdestruct; simpl in *.        \n        rewrite ZMap.gss; rewrite ZMap.gso; auto.\n      Qed.\n\n      Lemma ptAllocPDE0_vread_gss :\n        forall id v vadr p d,          \n          PDX v = PDX vadr ->\n          vread id v d{ptpool: ZMap.set id (ZMap.set (PDX vadr) \n                                       (PDEValid p CalRealInitPTE.real_init_PTE) \n                                       (ZMap.get id (ptpool d))) (ptpool d)} = None.\n      Proof.\n        unfold vread, ptRead_spec, getPTE_spec; intros; subdestruct; simpl in *; rewrites.\n        destructgoal; subdestruct.\n        rewrite H in Hdestruct7; rewrite 2 ZMap.gss in Hdestruct7; inv Hdestruct7.\n        rewrite CalRealInitPTE.real_init_PTE_unp in Hdestruct8; inv Hdestruct8.\n        unfold PTX; apply Z.mod_pos_bound; omega.\n        inv_rewrite; contradiction n; auto.\n      Qed.\n\n      Lemma vread_owner :\n        forall v p d,\n          high_level_invariant d -> \n          vread (cid d) v d = Some p -> isOwner d (cid d) p.\n      Proof.\n        intros v p d Hinv Hrd.\n        assert (Hinv':= Hinv); destruct Hinv'.\n        unfold_specs; subdestruct.\n        unfold_specs; subdestruct; repeat inv_rewrite; try omega.\n        eapply pmap_owners_consistent; eauto; try omega.\n        unfold PageI; replace ((v0 * 4096 + PermtoZ p0) / 4096) with v0; eauto.\n        symmetry; eapply Zdiv_unique; eauto.\n        destruct p0; simpl; try omega.\n        destruct b; omega.\n      Qed.\n\n      Lemma conf_ptAllocPDE0 : \n        forall d1 d2 d1' d2' vadr r1' r2',          \n          ptAllocPDE0_spec (cid d1) vadr d1 = Some (d1', r1') ->\n          ptAllocPDE0_spec (cid d1) vadr d2 = Some (d2', r2') ->\n          init d1 = true -> high_level_invariant d1 -> high_level_invariant d2 ->\n          obs_eq (cid d1) d1 d2 -> obs_eq (cid d1) d1' d2'.\n      Proof.\n        intros d1 d2 d1' d2' vadr r1' r2' Hspec1 Hspec2 Hinit Hinv1 Hinv2 Hobs_eq.\n        unfold_specs; obs_eq_rewrites; subdestruct; repeat inv_rewrite.\n        {\n          constructor; simpl; try assumption; try congruence.\n          {\n            intros v p1 p2 Hrd1 Hrd2; repeat vread_simpl.\n            destruct (zeq (PDX v) (PDX vadr)).\n            - rewrite ptAllocPDE0_vread_gss in Hrd1, Hrd2; try assumption; try congruence.\n            - rewrite ptAllocPDE0_vread_gso in Hrd1, Hrd2; try assumption.\n              intro o; rewrite 2 FlatMem.free_page_gso.\n              eapply obs_eq_HP0; eauto.\n              rewrite (proj1 obs_eq_cid0) in Hrd2; try reflexivity.\n              apply vread_owner in Hrd2; try assumption.\n              rewrite pagei_ptaddr; intro Hcon; subst.\n              destruct a as [a [Hcon a']]; inv Hrd2; rewrites; contradiction.\n              apply vread_owner in Hrd1; try assumption.\n              rewrite pagei_ptaddr; intro Hcon; subst.\n              destruct a0 as [a0 [Hcon a0']]; inv Hrd1; rewrites; contradiction.\n          }\n          {\n            repeat rewrite ZMap.gss; simpl; omega.\n          }\n          {\n            repeat rewrite ZMap.gss; auto.\n          }\n          {\n            intro v; repeat vread_simpl.\n            destruct (zeq (PDX v) (PDX vadr)).\n            - rewrite 2 ptAllocPDE0_vread_gss; auto; reflexivity.\n            - rewrite 2 ptAllocPDE0_vread_gso; auto.\n          }\n        }\n        {\n          Print trap_mmap_spec.\n          Print vmx_set_mmap_spec.\n          Print ept_add_mapping_spec.\n          Print getPTE_spec.\nPrint ptfault_resv_spec.\n\n          Print high_level_invariant.\n          Print PMap_usr.\n          Print PDE_usr.\n          Print ptResv_spec.\nPrint ptInsert0_spec.\n          Print palloc_spec.\n          {\n            repeat unshared_simpl_iff.\n            unfold unshared; split; intros Hunsh p Hown1 id Hown2.\n            inv Hown1; inv Hown2; simpl in *.\n            destruct (zeq p r2'); subst.\n            - rewrite ZMap.gss in *.\n              inv H; contradiction.              \n            - rewrite ZMap.gso in *; auto; rewrites.\n              eapply Hunsh; econstructor; simpl; eauto.\n              rewrite ZMap.gso; eauto.\n            vread_simpl.\n            auto.\n              inv H1.\nPrint ptRead_spec.\nPrint getPTE_spec.\nCheck pmap_owners_consistent.\n\n\n\n              intro o; rewrite 2 FlatMem.free_page_gso.\n\n            try solve [unfold PageI, PTADDR; simpl; rewrite Zdiv.Zdiv_small; try omega;\n                       apply Z.mod_pos_bound; omega].\n            apply (obs_eq_HP0 vadr).\n            unfold ptRead_spec, getPTE_spec.\n; rewrites.\n          erewrite Hdestruct14.\n          \n          inv_rewrite.\n          simpl.\nPrint ptAllocPDE0_spec.\nPrint trap_mmap_spec.\nPrint ptRead_spec.\nPrint getPTE_spec.\nPrint ptResv_spec.\nPrint ptInsert0_spec.\nPrint palloc_spec.\nPrint vmx_set_mmap_spec.\nPrint ept_add_mapping_spec.\n          subdestruct.\n          rewrites.\n; obs_eq_rewrites.\n          unfold ptRead_spec, getPTE_spec; simpl.\n          intros.\n          \n auto.\n        rewrite quota_convert in *.\n        rewrite <- obs_eq_AC_quota0 in *.\n        unfold ptAllocPDE0_spec in *.\n        rewrite_fld LAT; rewrite_fld nps; rewrite_fld pperm; rewrite_fld ptpool; rewrite_fld AC.\n        subdestruct; inv Hspec1; inv Hspec2; auto.\n        split; constructor.\n        repeat nonHP_simpl; auto.\n        simpl; intros p Hown o; inv Hown.\n        simpl in H.\n        destruct (zeq p r2'); subst.\n        rewrite ZMap.gss in H; inv H; inv H0.\n        rewrite 2 FlatMem.free_page_gso; try (rewrite pagei_ptaddr; auto).\n        rewrite ZMap.gso in H; auto; apply Hhp; econstructor; eauto.\n      Qed.\n\n      Lemma conf_palloc : \n        forall id (d1 d2 d1' d2' : cdata RData) i r1 r2,\n          palloc_spec i d1 = Some (d1', r1) ->\n          palloc_spec i d2 = Some (d2', r2) ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2' /\\ r1 = r2.\n      Proof.\n        intros id d1 d2 d1' d2' i r1 r2 Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold palloc_spec in *.\n        rewrite_fld LAT; rewrite_fld nps; rewrite_fld pperm; rewrite_fld AC.\n        inv_spec; inv Hspec1; inv Hspec2; auto.\n        split; constructor.\n        repeat nonHP_simpl; assumption.\n        simpl; intros p Hown o; inv Hown.\n        simpl in H.\n        destruct (zeq p r2); subst.\n        rewrite ZMap.gss in H; inv H; inv H0.\n        rewrite ZMap.gso in H; auto; apply Hhp; econstructor; eauto.\n      Qed.\n\n      (* ptResv is a special case for confidentiality - it is composed of a sequence of specs, some\n         of which (ptInsert0_spec in particular) violate noninterference. However, it is possible to\n         use high level invariants to prove that ptResv as a whole is nevertheless noninterfering. *)\n      Lemma conf_ptResv : \n        forall id (d1 d2 d1' d2' : cdata RData) n vadr pm r1 r2,      \n          ptResv_spec n vadr pm d1 = Some (d1', r1) ->\n          ptResv_spec n vadr pm d2 = Some (d2', r2) ->\n          high_level_invariant d1 -> high_level_invariant d2 ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2' /\\ r1 = r2.\n      Proof.\n        intros id d1 d2 d1' d2' n vadr pm r1 r2 Hspec1 Hspec2 Hinv1 Hinv2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold ptResv_spec in *.\n        conf_simpl id conf_palloc d1'' d2'' r.\n        subdestruct; inv Hspec1; inv Hspec2; auto.\n        split.\n        constructor.\n        {\n          unfold ptInsert0_spec in *.\n          clear Hnh; rewrite_fld ptpool; rewrite_fld nps.\n          subdestruct; inv H0; inv H1.\n          {\n            unfold ptInsertPTE0_spec in *.\n            rewrite_fld LAT; rewrite_fld pperm; rewrite_fld ptpool; rewrite_fld nps.\n            subdestruct; repeat inv_rewrite'; repeat nonHP_simpl; assumption.\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct14 Hdestruct11 Hobs_eq0) as [Hobs _].\n            inv Hobs; auto.\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct14 Hdestruct11 Hobs_eq0) as [_ Heq]; subst.\n            contradiction n1; auto.\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct15 Hdestruct11 Hobs_eq0) as [_ Heq]; subst.\n            contradiction n1; auto. \n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct15 Hdestruct11 Hobs_eq0) as [Hobs Heq]; subst.\n            inv Hobs.\n            unfold ptInsertPTE0_spec in *.\n            rewrite_fld LAT; rewrite_fld pperm; rewrite_fld ptpool; rewrite_fld nps.\n            subdestruct; repeat inv_rewrite'; repeat nonHP_simpl; assumption.\n          }\n        }\n        {\n          unfold ptInsert0_spec in *.\n          clear Hnh; rewrite_fld ptpool; rewrite_fld nps.\n          subdestruct; inv H0; inv H1.\n          {\n            unfold ptInsertPTE0_spec in *.\n            rewrite_fld LAT; rewrite_fld pperm; rewrite_fld ptpool; rewrite_fld nps.\n            subdestruct; repeat inv_rewrite'.\n            {\n              intros p' Hown o; inv Hown.\n              simpl in H.\n              destruct (zeq p' r); subst.\n              {\n                rewrite ZMap.gss in H; inv H.\n                destruct H0.\n                inv H.\n                unfold palloc_spec in *.\n                inv Hobs_eq; rewrite_fld nps; rewrite_fld LAT; rewrite_fld AC.\n                subdestruct; inv Hspec; inv Hspec0; simpl in *.\n                assert (Hneq: ZMap.get r (pperm d1) <> PGAlloc).\n                {\n                  intro Hcon.\n                  assert (Hneq: ZMap.get r (pperm d1) <> PGUndef) by \n                      (destruct (ZMap.get r (pperm d1)); inv Hcon; discriminate).\n                  destruct a0 as [Hrange [Hlat Hx]].\n                  assert (Hrange' : 0 <= r < nps d1) by omega.\n                  destruct (valid_pperm_ppage _ Hinv1 _ Hrange') as [Hperm _].\n                  destruct (Hperm Hneq) as [n Hlat'].\n                  rewrite Hlat in Hlat'; inv Hlat'.\n                }\n                rewrite (valid_dirty _ Hinv1 _ Hneq).\n                rewrite_fld_rev pperm.\n                rewrite (valid_dirty _ Hinv2 _ Hneq).\n                rewrite <- (pagei_ptaddr r o) at 2 4.\n                rewrite 2 FlatMem.free_page_gss; auto.\n                contradiction n0; auto.\n                contradiction n0; auto.\n                apply Hhp0; econstructor; eauto.\n              }\n              {\n                rewrite ZMap.gso in H; auto.\n                apply Hhp0; econstructor; eauto.\n              }\n            }\n            {\n              intros p' Hown o; inv Hown.\n              simpl in H.\n              destruct (zeq p' r); subst.\n              {\n                rewrite ZMap.gss in H; inv H.\n                destruct H0.\n                inv H.\n                unfold palloc_spec in *.\n                inv Hobs_eq; rewrite_fld nps; rewrite_fld LAT; rewrite_fld AC.\n                subdestruct; inv Hspec; inv Hspec0; simpl in *.\n                assert (Hneq: ZMap.get r (pperm d1) <> PGAlloc).\n                {\n                  intro Hcon.\n                  assert (Hneq: ZMap.get r (pperm d1) <> PGUndef) by \n                      (destruct (ZMap.get r (pperm d1)); inv Hcon; discriminate).\n                  destruct a0 as [Hrange [Hlat Hx]].\n                  assert (Hrange' : 0 <= r < nps d1) by omega.\n                  destruct (valid_pperm_ppage _ Hinv1 _ Hrange') as [Hperm _].\n                  destruct (Hperm Hneq) as [n Hlat'].\n                  rewrite Hlat in Hlat'; inv Hlat'.\n                }\n                rewrite (valid_dirty _ Hinv1 _ Hneq).\n                rewrite_fld_rev pperm.\n                rewrite (valid_dirty _ Hinv2 _ Hneq).\n                rewrite <- (pagei_ptaddr r o) at 2 4.\n                rewrite 2 FlatMem.free_page_gss; auto.\n                contradiction n0; auto.\n                contradiction n0; auto.\n                apply Hhp0; econstructor; eauto.\n              }\n              {\n                rewrite ZMap.gso in H; auto.\n                apply Hhp0; econstructor; eauto.\n              }\n            }\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct14 Hdestruct11 Hobs_eq0) as [Hobs _].\n            inv Hobs; auto.\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct14 Hdestruct11 Hobs_eq0) as [_ Heq]; subst.\n            contradiction n1; auto.\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct15 Hdestruct11 Hobs_eq0) as [_ Heq]; subst.\n            contradiction n1; auto.\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct15 Hdestruct11 Hobs_eq0) as [Hobs Heq]; subst.\n            rename r4 into d1''', r0 into d2'''.\n            unfold ptAllocPDE0_spec in *.\n            rewrite_fld LAT; rewrite_fld pperm; rewrite_fld ptpool; rewrite_fld nps; rewrite_fld AC.\n            subdestruct.\n            unfold ptInsertPTE0_spec in *.\n            inv Hobs; rewrite_fld LAT; rewrite_fld pperm; rewrite_fld ptpool; rewrite_fld nps.\n            subdestruct; simpl in *.\n            {\n              inv Hdestruct11; inv Hdestruct14; inv Hdestruct15; inv Hdestruct18; simpl in *.\n              intros p' Hown o; inv Hown.\n              simpl in H1.\n              destruct (zeq p' r); subst.\n              {\n                destruct (zeq r2 r); subst.\n                rewrite <- (pagei_ptaddr r o) at 2 4.\n                rewrite 2 FlatMem.free_page_gss; auto.\n                rewrite ZMap.gss in H1; inv H1.\n                destruct H2.\n                inv H1.\n                unfold palloc_spec in *.\n                inv Hobs_eq; rewrite_fld nps; rewrite_fld LAT; rewrite_fld AC.\n                subdestruct; inv Hspec; inv Hspec0; simpl in *.\n                assert (Hneq: ZMap.get r (pperm d1) <> PGAlloc).\n                {\n                  intro Hcon.\n                  assert (Hneq: ZMap.get r (pperm d1) <> PGUndef) by \n                      (destruct (ZMap.get r (pperm d1)); inv Hcon; discriminate).\n                  destruct a1 as [Hrange [Hlat Hx]].\n                  assert (Hrange' : 0 <= r < nps d1) by omega.\n                  destruct (valid_pperm_ppage _ Hinv1 _ Hrange') as [Hperm _].\n                  destruct (Hperm Hneq) as [n Hlat'].\n                  rewrite Hlat in Hlat'; inv Hlat'.\n                }\n                rewrite 2 FlatMem.free_page_gso; try solve [rewrite pagei_ptaddr; auto].\n                rewrite (valid_dirty _ Hinv1 _ Hneq).\n                rewrite_fld_rev' pperm H1.\n                rewrite (valid_dirty _ Hinv2 _ Hneq).\n                rewrite <- (pagei_ptaddr r o) at 2 4.\n                rewrite 2 FlatMem.free_page_gss; auto.\n                contradiction n0; auto.\n                contradiction n0; auto.\n                apply H0; econstructor; eauto.\n              }\n              {\n                rewrite ZMap.gso in H1; [|auto].\n                apply H0; econstructor; eauto.\n              }\n            }\n            {\n              inv Hdestruct11; inv Hdestruct14; inv Hdestruct15; inv Hdestruct18; simpl in *.\n              intros p' Hown o; inv Hown.\n              simpl in H1.\n              destruct (zeq p' r); subst.\n              {\n                destruct (zeq r2 r); subst.\n                rewrite <- (pagei_ptaddr r o) at 2 4.\n                rewrite 2 FlatMem.free_page_gss; auto.\n                rewrite ZMap.gss in H1; inv H1.\n                destruct H2.\n                inv H1.\n                unfold palloc_spec in *.\n                inv Hobs_eq; rewrite_fld nps; rewrite_fld LAT; rewrite_fld AC.\n                subdestruct; inv Hspec; inv Hspec0; simpl in *.\n                assert (Hneq: ZMap.get r (pperm d1) <> PGAlloc).\n                {\n                  intro Hcon.\n                  assert (Hneq: ZMap.get r (pperm d1) <> PGUndef) by \n                      (destruct (ZMap.get r (pperm d1)); inv Hcon; discriminate).\n                  destruct a1 as [Hrange [Hlat Hx]].\n                  assert (Hrange' : 0 <= r < nps d1) by omega.\n                  destruct (valid_pperm_ppage _ Hinv1 _ Hrange') as [Hperm _].\n                  destruct (Hperm Hneq) as [n Hlat'].\n                  rewrite Hlat in Hlat'; inv Hlat'.\n                }\n                rewrite 2 FlatMem.free_page_gso; try solve [rewrite pagei_ptaddr; auto].\n                rewrite (valid_dirty _ Hinv1 _ Hneq).\n                rewrite_fld_rev' pperm H1.\n                rewrite (valid_dirty _ Hinv2 _ Hneq).\n                rewrite <- (pagei_ptaddr r o) at 2 4.\n                rewrite 2 FlatMem.free_page_gss; auto.\n                contradiction n0; auto.\n                contradiction n0; auto.\n                apply H0; econstructor; eauto.\n              }\n              {\n                rewrite ZMap.gso in H1; [|auto].\n                apply H0; econstructor; eauto.\n              }\n            }\n            inv Hdestruct11; contradiction n1; auto.\n            inv Hdestruct11; contradiction n1; auto.\n          }\n        }\n        {\n          unfold ptInsert0_spec in *.\n          rewrite_fld nps; rewrite_fld ptpool.\n          subdestruct; inv H0; inv H1; auto.\n          destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                     Hdestruct14 Hdestruct11 Hobs_eq0) as [_ Heq]; subst.\n          contradiction n1; auto.\n          destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                     Hdestruct15 Hdestruct11 Hobs_eq0) as [_ Heq]; subst.\n          contradiction n1; auto.\n          destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                     Hdestruct15 Hdestruct11 Hobs_eq0) as [_ Heq]; subst; auto.\n        }\n      Qed.\n\n    End CONF_PTRESV.\n\n    \n\n    Section CONF_MMAP.\n\n      Lemma conf_vmx_set_mmap : \n        forall id (d1 d2 d1' d2' : cdata RData) gpa hpa ty r1' r2',\n          vmx_set_mmap_spec gpa hpa ty d1 = Some (d1', r1') ->\n          vmx_set_mmap_spec gpa hpa ty d2 = Some (d2', r2') ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2' /\\ r1' = r2'.\n      Proof.\n        intros id d1 d2 d1' d2' gpa hpa ty r1' r2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold vmx_set_mmap_spec, ept_add_mapping_spec in *.\n        rewrite_fld ept; subdestruct; inv Hspec1; inv Hspec2;\n        solve [split; try solve_obs_eq Hhp; inv_spec; repeat inv_rewrite'].\n      Qed.\n\n      Lemma conf_trap_mmap : \n        forall id (d1 d2 d1' d2' : cdata RData),      \n          trap_mmap_spec d1 = Some d1' ->\n          trap_mmap_spec d2 = Some d2' ->\n          high_level_invariant d1 -> high_level_invariant d2 ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hinv1 Hinv2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold trap_mmap_spec in *.\n        rewrite_fld cid.\n        repeat conf_arg_simpl.\n        elim_none.\n        {\n          conf_goal; [rewrite_fld ptpool; subdestruct; rewrites; auto|].\n          clear H H0; subst; elim_none; elim_none.\n          {\n            conf_simpl id conf_ptResv d1'' d2'' r.\n            conf_goal; [rewrite_fld ptpool; subdestruct; rewrites; auto|].\n            clear H H0; subst; elim_none.\n            conf_simpl id conf_vmx_set_mmap d1''' d2''' r'.\n            eapply conf_uctx_set_errno; eauto.\n          }\n          {\n            conf_simpl id conf_vmx_set_mmap d1'' d2'' r.\n            eapply conf_uctx_set_errno; eauto.\n          }\n        }\n        {\n          eapply conf_uctx_set_errno; eauto.\n        }\n      Qed.\n\n    End CONF_MMAP.\n\n    Section CONF_PROC_CREATE.\n\n      Lemma conf_proc_create :\n        forall id (d1 d2 d1' d2' : cdata RData) b b' buc ofs q r1 r2,\n          proc_create_spec d1 b b' buc ofs q = Some (d1',r1) ->\n          proc_create_spec d2 b b' buc ofs q = Some (d2',r2) ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2' /\\ r1 = r2.\n      Proof.\n        intros id d1 d2 d1' d2' b b' buc ofs q r1 r2 Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld pb; rewrite_fld kctxt; rewrite_fld abq.\n        rewrite_fld abtcb; rewrite_fld uctxt; rewrite_fld AC; rewrite_fld cid.\n        subdestruct; inv Hspec1; inv Hspec2.\n        split; auto; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_trap_proc_create : \n        forall id (d1 d2 d1' d2' : cdata RData) s m,\n          trap_proc_create_spec s m d1 = Some d1' ->\n          trap_proc_create_spec s m d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' s m Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl.\n        rewrite_fld cid; rewrite_fld AC.\n        destruct (zle_le 0 z0\n                         (cquota (ZMap.get (cid d1) (AC d1)) -\n                          cusage (ZMap.get (cid d1) (AC d1)))).\n        conf_arg_simpl.\n        elim_none; elim_none; elim_none; elim_none; elim_none; elim_none.\n        elim_none; elim_none; elim_none; elim_none; elim_none.\n        conf_simpl' id conf_proc_create d1'' d2'' r.\n        conf_simpl_noret id conf_uctx_set_retval1 d1''' d2'''.\n        eapply conf_uctx_set_errno; eauto.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_PROC_CREATE.\n\n    Section CONF_TSC.\n\n      Lemma conf_vmx_set_tsc_offset : \n        forall id (d1 d2 d1' d2' : cdata RData) ofs,\n          vmx_set_tsc_offset_spec ofs d1 = Some d1' ->\n          vmx_set_tsc_offset_spec ofs d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' ofs Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; subdestruct; inv Hspec1; inv Hspec2; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_trap_get_tsc_offset : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_get_tsc_offset_spec d1 = Some d1' ->\n          trap_get_tsc_offset_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        unfold vmx_get_tsc_offset_spec in *.\n        rewrite_fld vmcs.\n        subdestruct.\n        eapply conf_uctx_set_errno; eauto.\n        eapply conf_uctx_set_retval2; eauto.\n        eapply conf_uctx_set_retval1; eauto.\n      Qed.\n\n      Lemma conf_trap_set_tsc_offset : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_set_tsc_offset_spec d1 = Some d1' ->\n          trap_set_tsc_offset_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl; conf_arg_simpl.\n        conf_simpl_noret id conf_vmx_set_tsc_offset d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_TSC.\n\n    Section CONF_EXITINFO.\n\n      Hint Unfold vmx_get_exit_reason_spec vmx_get_exit_io_port_spec vmx_get_io_width_spec \n           vmx_get_io_write_spec vmx_get_exit_io_rep_spec vmx_get_exit_io_str_spec\n           vmx_get_exit_fault_addr_spec.\n\n      Lemma conf_trap_get_exitinfo : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_get_exitinfo_spec d1 = Some d1' ->\n          trap_get_exitinfo_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs; autounfold in *. \n        rewrite_fld vmcs; rewrite_fld vmx; rewrite_fld ikern; rewrite_fld pg; rewrite_fld ihost.\n        elim_none; elim_none; elim_none; elim_none; elim_none; elim_none; elim_none.\n        conf_simpl_noret id conf_uctx_set_retval1 dr1 dr1'.\n        elim_none.\n        {\n          conf_simpl_noret id conf_uctx_set_retval2 dr2 dr2'.\n          conf_simpl_noret id conf_uctx_set_retval3 dr3 dr3'.\n          conf_simpl_noret id conf_uctx_set_retval4 dr4 dr4'.\n          eapply conf_uctx_set_errno; eauto.\n        }\n        {\n          elim_none.\n          conf_simpl_noret id conf_uctx_set_retval2 dr2 dr2'.\n          eapply conf_uctx_set_errno; eauto.\n          eapply conf_uctx_set_errno; eauto.\n        }\n      Qed.\n\n    End CONF_EXITINFO.\n\n    Section CONF_REG.\n\n      Lemma conf_vmx_get_reg : \n        forall id (d1 d2 : cdata RData) reg r1 r2,\n          vmx_get_reg_spec reg d1 = Some r1 ->\n          vmx_get_reg_spec reg d2 = Some r2 ->\n          obs_eq id d1 d2 -> r1 = r2.\n      Proof.\n        intros id d1 d2 reg r1 r2 Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; rewrite_fld vmx; subdestruct; inv Hspec1; inv Hspec2; auto.\n      Qed.\n\n      Lemma conf_vmx_set_reg : \n        forall id (d1 d2 d1' d2' : cdata RData) reg v,\n          vmx_set_reg_spec reg v d1 = Some d1' ->\n          vmx_set_reg_spec reg v d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' reg v Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; rewrite_fld vmx; subdestruct; inv Hspec1; inv Hspec2; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_trap_get_reg : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_get_reg_spec d1 = Some d1' ->\n          trap_get_reg_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl; elim_none.\n        elim_none_eqn' Hspec1 Hget1; elim_none_eqn' Hspec2 Hget2.\n        assert (z = z1) by (eapply conf_vmx_get_reg; eauto); subst.\n        conf_simpl_noret id conf_uctx_set_retval1 d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n      Lemma conf_trap_set_reg : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_set_reg_spec d1 = Some d1' ->\n          trap_set_reg_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl; conf_arg_simpl; elim_none.    \n        conf_simpl_noret id conf_vmx_set_reg d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_REG.\n\n    Section CONF_SEG.\n\n      Lemma conf_vmx_set_desc : \n        forall id (d1 d2 d1' d2' : cdata RData) seg sel base lim ar,\n          vmx_set_desc_spec seg sel base lim ar d1 = Some d1' ->\n          vmx_set_desc_spec seg sel base lim ar d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' seg sel base lim ar Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; subdestruct; inv Hspec1; inv Hspec2; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_trap_set_seg : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_set_seg_spec d1 = Some d1' ->\n          trap_set_seg_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl; conf_arg_simpl; conf_arg_simpl; conf_arg_simpl; conf_arg_simpl; elim_none.    \n        conf_simpl_noret id conf_vmx_set_desc d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_SEG.\n\n    Section CONF_EIP.\n\n      Lemma conf_vmx_get_next_eip : \n        forall id (d1 d2 : cdata RData) r1 r2,\n          vmx_get_next_eip_spec d1 = Some r1 ->\n          vmx_get_next_eip_spec d2 = Some r2 ->\n          obs_eq id d1 d2 -> r1 = r2.\n      Proof.\n        intros id d1 d2 r1 r2 Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; rewrite_fld vmx; subdestruct; inv Hspec1; inv Hspec2; auto.\n      Qed.\n\n      Lemma conf_trap_get_next_eip : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_get_next_eip_spec d1 = Some d1' ->\n          trap_get_next_eip_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        elim_none_eqn' Hspec1 Hget1; elim_none_eqn' Hspec2 Hget2.\n        assert (z = z0) by (eapply conf_vmx_get_next_eip; eauto); subst; elim_none.\n        conf_simpl_noret id conf_uctx_set_retval1 d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_EIP.\n\n    Section CONF_EVENT.\n\n      Lemma conf_vmx_inject_event : \n        forall id (d1 d2 d1' d2' : cdata RData) ty vec err ev,\n          vmx_inject_event_spec ty vec err ev d1 = Some d1' ->\n          vmx_inject_event_spec ty vec err ev d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' ty vec err ev Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; subdestruct'; apply inv_some in Hspec1; \n        apply inv_some in Hspec2; subst; auto; solve_obs_eq Hhp.\n      Qed.\n      \n      Lemma conf_trap_inject_event : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_inject_event_spec d1 = Some d1' ->\n          trap_inject_event_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl; conf_arg_simpl; conf_arg_simpl; conf_arg_simpl.\n        conf_simpl_noret id conf_vmx_inject_event d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n      Lemma conf_vmx_check_pending_event : \n        forall id (d1 d2 : cdata RData) r1 r2,\n          vmx_check_pending_event_spec d1 = Some r1 ->\n          vmx_check_pending_event_spec d2 = Some r2 ->\n          obs_eq id d1 d2 -> r1 = r2.\n      Proof.\n        intros id d1 d2 r1 r2 Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; subdestruct; inv Hspec1; inv Hspec2; auto.\n      Qed.\n\n      Lemma conf_trap_check_pending_event : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_check_pending_event_spec d1 = Some d1' ->\n          trap_check_pending_event_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        elim_none_eqn' Hspec1 Hget1; elim_none_eqn' Hspec2 Hget2.\n        assert (z = z0) by (eapply conf_vmx_check_pending_event; eauto); subst.\n        conf_simpl_noret id conf_uctx_set_retval1 d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_EVENT.\n\n    Section CONF_INT.\n\n      Lemma conf_vmx_check_int_shadow : \n        forall id (d1 d2 : cdata RData) r1 r2,\n          vmx_check_int_shadow_spec d1 = Some r1 ->\n          vmx_check_int_shadow_spec d2 = Some r2 ->\n          obs_eq id d1 d2 -> r1 = r2.\n      Proof.\n        intros id d1 d2 r1 r2 Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; subdestruct; inv Hspec1; inv Hspec2; auto.\n      Qed.\n\n      Lemma conf_vmx_set_intercept_intwin : \n        forall id (d1 d2 d1' d2' : cdata RData) en,\n          vmx_set_intercept_intwin_spec en d1 = Some d1' ->\n          vmx_set_intercept_intwin_spec en d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' en Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; subdestruct; inv Hspec1; inv Hspec2; solve_obs_eq Hhp.\n      Qed.\n      \n      Lemma conf_trap_check_int_shadow : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_check_int_shadow_spec d1 = Some d1' ->\n          trap_check_int_shadow_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        elim_none_eqn' Hspec1 Hget1; elim_none_eqn' Hspec2 Hget2.\n        assert (z = z0) by (eapply conf_vmx_check_int_shadow; eauto); subst.\n        conf_simpl_noret id conf_uctx_set_retval1 d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n      Lemma conf_trap_intercept_int_window : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_intercept_int_window_spec d1 = Some d1' ->\n          trap_intercept_int_window_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl. \n        conf_simpl_noret id conf_vmx_set_intercept_intwin d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_INT.\n\n    Section CONF_MSR.\n\n      Lemma conf_rdmsr : \n        forall id (d1 d2 : cdata RData) z r1 r2,\n          rdmsr_spec z d1 = Some r1 ->\n          rdmsr_spec z d2 = Some r2 ->\n          obs_eq id d1 d2 -> r1 = r2.\n      Proof.\n        intros; inv_spec; rewrites; auto.\n      Qed.\n      \n      Lemma conf_wrmsr : \n        forall id (d1 d2 : cdata RData) z1 z2 r1 r2,\n          wrmsr_spec z1 z2 d1 = Some r1 ->\n          wrmsr_spec z1 z2 d2 = Some r2 ->\n          obs_eq id d1 d2 -> r1 = r2.\n      Proof.\n        intros; inv_spec; rewrites; auto.\n      Qed.\n\n      Lemma conf_trap_handle_rdmsr : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_handle_rdmsr_spec d1 = Some d1' ->\n          trap_handle_rdmsr_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        elim_none_eqn' Hspec1 Hget1; elim_none_eqn' Hspec2 Hget2.\n        assert (z = z0) by (eapply conf_vmx_get_reg; eauto); subst.\n        elim_none_eqn' Hspec1 Hget1'; elim_none_eqn' Hspec2 Hget2'.\n        assert (z = z1) by (eapply conf_rdmsr; eauto); subst; elim_none.\n        conf_simpl_noret id conf_vmx_set_reg dr1 dr1'.\n        conf_simpl_noret id conf_vmx_set_reg dr2 dr2'.\n        elim_none_eqn' Hspec1 Hget1''; elim_none_eqn' Hspec2 Hget2''.\n        assert (z1 = z2) by (eapply conf_vmx_get_next_eip; eauto); subst; elim_none.\n        conf_simpl_noret id conf_vmx_set_reg dr3 dr3'.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n      Lemma conf_trap_handle_wrmsr : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_handle_wrmsr_spec d1 = Some d1' ->\n          trap_handle_wrmsr_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        elim_none_eqn' Hspec1 Hget1; elim_none_eqn' Hspec2 Hget2.\n        assert (z = z0) by (eapply conf_vmx_get_reg; eauto); subst.\n        elim_none_eqn' Hspec1 Hget1'; elim_none_eqn' Hspec2 Hget2'.\n        assert (z = z1) by (eapply conf_vmx_get_reg; eauto); subst.\n        elim_none_eqn' Hspec1 Hget1''; elim_none_eqn' Hspec2 Hget2''.\n        assert (z = z2) by (eapply conf_vmx_get_reg; eauto); subst.\n        elim_none' Hspec1; elim_none' Hspec2.\n        elim_none_eqn' Hspec1 Hget1''''; elim_none_eqn' Hspec2 Hget2''''.\n        assert (z4 = z5) by (eapply conf_vmx_get_next_eip; eauto); subst; elim_none.    \n        conf_simpl_noret id conf_vmx_set_reg d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_MSR.\n\n  End CONF_LEMMAS.\n\n\n  Section INTEG_LEMMAS.\n\n    Variable (id : Z).\n\n    Section INTEG_UCTX_SET_ERRNO.\n\n      Lemma integ_uctx_set_errno :\n        forall d d' n,\n          uctx_set_errno_spec n d = Some d' ->\n          obs_eq id d d'.\n      Proof.\n        intros; inv_spec; inv_rewrite; constructor; auto.\n        intro; isOwner_simpl_iff; reflexivity.\n        unshared_simpl_iff; reflexivity.\n      Qed.      \n\n    End INTEG_UCTX_SET_ERRNO.\n\n    Section INTEG_MMAP.\n\n      Lemma integ_ptAllocPDE0 : \n        forall d d' vadr r,\n          ptAllocPDE0_spec (cid d) vadr d = Some (d',r) -> \n          id <> cid d -> obs_eq id d d'.\n      Proof.\n        intros d d' vadr r Hspec Hid.\n        inv_spec; inv_rewrite; try apply obs_eq_refl.\n        constructor; simpl in *; auto; try solve [rewrite ZMap.gso; auto].\n        {\n          (* obs_eq_HP *)\n          intros p Hown o.\n          destruct (zeq p r); subst.\n          decompose [and] a; inv Hown; rewrites; contradiction.\n          rewrite FlatMem.free_page_gso; auto.\n          rewrite pagei_ptaddr; auto.\n        }\n        {\n          (* obs_eq_pperm *)\n          intros p Hown.\n          destruct (zeq p r); subst.\n          decompose [and] a; inv Hown; rewrites; contradiction.\n          rewrite ZMap.gso; auto.\n        }\n        {\n          (* obs_eq_LAT *)\n          intros p Hown.\n          destruct (zeq p r); subst.\n          decompose [and] a; inv Hown; rewrites; contradiction.\n          rewrite ZMap.gso; auto.\n        }\n        {\n          (* obs_eq_owner *)\n          intro p.\n          destruct (zeq p r); subst.\n          - decompose [and] a; split; intro Hown; inv Hown.\n            rewrites; contradiction.\n            simpl in *; rewrite ZMap.gss in *; rewrites; inv H0; contradiction.\n          - solve_isOwner_iff.\n        }\n        {\n          (* obs_eq_unshared *)\n          repeat unshared_simpl_iff.\n          unfold unshared; split; intros Hunsh p Hown1 ? Hown2.\n          - destruct (zeq p r); subst.\n            + inv Hown1.\n              simpl in *; rewrite ZMap.gss in *; inv H; inv H0.\n            + inv Hown1; inv Hown2; rewrites; simpl in *; rewrite ZMap.gso in *; auto.\n              eapply Hunsh; econstructor; eauto.\n          - destruct (zeq p r); subst.\n            + decompose [and] a; inv Hown1; rewrites; contradiction.\n            + inv Hown1; inv Hown2; rewrites.\n              eapply Hunsh; econstructor; simpl; eauto; rewrite ZMap.gso; eauto.\n        }\n      Qed.\n      \n      Lemma integ_palloc : \n        forall d d' r,\n          palloc_spec (cid d) d = Some (d',r) -> \n          id <> cid d -> obs_eq id d d'.\n      Proof.\n        intros d d' r Hspec Hid.\n        inv_spec; inv_rewrite; try apply obs_eq_refl.\n        constructor; simpl in *; auto; try solve [rewrite ZMap.gso; auto].\n        {\n          (* obs_eq_pperm *)\n          intros p Hown.\n          destruct (zeq p r); subst.\n          decompose [and] a; inv Hown; rewrites; contradiction.\n          rewrite ZMap.gso; auto.\n        }\n        {\n          (* obs_eq_LAT *)\n          intros p Hown.\n          destruct (zeq p r); subst.\n          decompose [and] a; inv Hown; rewrites; contradiction.\n          rewrite ZMap.gso; auto.\n        }\n        {\n          (* obs_eq_owner *)\n          intro p.\n          destruct (zeq p r); subst; [|solve_isOwner_iff].\n          decompose [and] a.\n          split; intro Hown; inv Hown.\n          rewrites; contradiction.\n          simpl in *; rewrite ZMap.gss in *; rewrites; inv H0; contradiction.\n        }\n        {\n          (* obs_eq_unshared *)\n          repeat unshared_simpl_iff.\n          unfold unshared; split; intros Hunsh p Hown1 ? Hown2.\n          - destruct (zeq p r); subst.\n            + inv Hown1.\n              simpl in *; rewrite ZMap.gss in *; inv H; inv H0.\n            + inv Hown1; inv Hown2; rewrites; simpl in *; rewrite ZMap.gso in *; auto.\n              eapply Hunsh; econstructor; eauto.\n          - destruct (zeq p r); subst.\n            + decompose [and] a; inv Hown1; rewrites; contradiction.\n            + inv Hown1; inv Hown2; rewrites.\n              eapply Hunsh; econstructor; simpl; eauto; rewrite ZMap.gso; eauto.\n        }\n      Qed.\n\n      Lemma integ_ptInsertPTE0 :\n        forall d d' vadr padr pm,\n          ptInsertPTE0_spec (cid d) vadr padr pm d = Some d' -> \n          ~ isOwner d id padr -> id <> cid d -> obs_eq id d d'.\n      Proof.\n        intros d d' vadr padr pm Hspec Hnown Hid.\n        inv_spec; inv_rewrite.\n        {\n          constructor; simpl; auto; try solve [rewrite ZMap.gso; auto].\n          {\n            (* obs_eq_LAT *)\n            intros p Hown.\n            destruct (zeq p padr); subst; try contradiction.\n            rewrite ZMap.gso; auto.\n          }\n          {\n            (* obs_eq_owner *)\n            intro p.\n            destruct (zeq p padr); subst; [|solve_isOwner_iff].\n            isOwner_simpl_iff; split; intro Hown; inv Hown; rewrites.\n            - econstructor; simpl.\n              rewrite ZMap.gss; eauto.\n              right; eauto.\n            - simpl in *; rewrite ZMap.gss in *; inv H.\n              destruct H0.\n              inv H; contradict Hid; auto.\n              econstructor; eauto.\n          }\n          {\n            (* obs_eq_unshared *)\n            repeat unshared_simpl_iff.\n            unfold unshared; split; intros Hunsh p Hown1 ? Hown2.\n            - destruct (zeq p padr); subst.\n              + inv Hown1.\n                simpl in *; rewrite ZMap.gss in *; inv H; inv H0.\n                contradict Hid; inv H; auto.\n                contradict Hnown; econstructor; eauto.\n              + inv Hown1; inv Hown2; simpl in *; rewrites.\n                rewrite ZMap.gso in *; auto; eapply Hunsh; econstructor; eauto.\n            - destruct (zeq p padr); subst; try contradiction.\n              inv Hown1; inv Hown2; rewrites.\n              eapply Hunsh; econstructor; simpl; eauto; rewrite ZMap.gso; eauto.\n          }\n        }\n        {\n          constructor; simpl; auto; try solve [rewrite ZMap.gso; auto].\n          {\n            (* obs_eq_LAT *)\n            intros p Hown.\n            destruct (zeq p padr); subst; try contradiction.\n            rewrite ZMap.gso; auto.\n          }\n          {\n            (* obs_eq_owner *)\n            intro p.\n            destruct (zeq p padr); subst; [|solve_isOwner_iff].\n            isOwner_simpl_iff; split; intro Hown; inv Hown; rewrites.\n            - econstructor; simpl.\n              rewrite ZMap.gss; eauto.\n              right; eauto.\n            - simpl in *; rewrite ZMap.gss in *; inv H.\n              destruct H0.\n              inv H; contradict Hid; auto.\n              econstructor; eauto.\n          }\n          {\n            (* obs_eq_unshared *)\n            repeat unshared_simpl_iff.\n            unfold unshared; split; intros Hunsh p Hown1 ? Hown2.\n            - destruct (zeq p padr); subst.\n              + inv Hown1.\n                simpl in *; rewrite ZMap.gss in *; inv H; inv H0.\n                contradict Hid; inv H; auto.\n                contradict Hnown; econstructor; eauto.\n              + inv Hown1; inv Hown2; simpl in *; rewrites.\n                rewrite ZMap.gso in *; auto; eapply Hunsh; econstructor; eauto.\n            - destruct (zeq p padr); subst; try contradiction.\n              inv Hown1; inv Hown2; rewrites.\n              eapply Hunsh; econstructor; simpl; eauto; rewrite ZMap.gso; eauto.\n          }\n        }\n      Qed.\n\n      Lemma integ_ptInsert0 :\n        forall d d' vadr padr pm r,\n          ptInsert0_spec (cid d) vadr padr pm d = Some (d',r) -> \n          ~ isOwner d id padr -> id <> cid d -> obs_eq id d d'.\n      Proof.\n        intros d d' vadr padr pm r Hspec Hnown Hid.\n        inv_spec; inv Hspec.\n        eapply integ_ptInsertPTE0; eauto.\n        eapply integ_ptAllocPDE0; eauto.\n        apply integ_ptAllocPDE0 in Hdestruct6; auto.\n        eapply obs_eq_trans; eauto.\n        destruct Hdestruct6.\n        eapply integ_ptInsertPTE0; eauto.\n        rewrite <- obs_eq_cid0; eauto.\n        rewrite <- obs_eq_owner0; auto.\n        rewrite <- obs_eq_cid0; auto.\n      Qed.\n\n      Lemma integ_ptResv :\n        forall d d' vadr pm r,\n          ptResv_spec (cid d) vadr pm d = Some (d',r) -> \n          id <> cid d -> obs_eq id d d'.\n      Proof.\n        intros d d' vadr pm r Hspec Hid.\n        inv_spec; inv Hspec; try apply obs_eq_refl.\n        assert (Hpalloc:= Hdestruct); apply integ_palloc in Hdestruct; auto.\n        eapply obs_eq_trans; eauto.\n        destruct Hdestruct.\n        rewrite obs_eq_cid0 in H0; eapply integ_ptInsert0; eauto; try congruence.\n        clear H0; inv_spec; inv_rewrite.\n        intro Hcon; inv Hcon; simpl in *.\n        rewrite ZMap.gss in *; inv H; inv H0.\n      Qed.\n\n      Print trap_mmap_spec.\n      \n      Print uctx_arg2_spec.\n      Print ptRead_spec.\n      Print getPTE_spec.\n\n    End INTEG_PTRESV.\n\n    Section INTEG_MMAP.\n(*\n      Lemma conf_vmx_set_mmap : \n        forall id (d1 d2 d1' d2' : cdata RData) gpa hpa ty r1' r2',\n          vmx_set_mmap_spec gpa hpa ty d1 = Some (d1', r1') ->\n          vmx_set_mmap_spec gpa hpa ty d2 = Some (d2', r2') ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2' /\\ r1' = r2'.\n      Proof.\n        intros id d1 d2 d1' d2' gpa hpa ty r1' r2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold vmx_set_mmap_spec, ept_add_mapping_spec in *.\n        rewrite_fld ept; subdestruct; inv Hspec1; inv Hspec2;\n        solve [split; try solve_obs_eq Hhp; inv_spec; repeat inv_rewrite'].\n      Qed.\n*)\n      Lemma integ_trap_mmap : \n        forall id (d d' : cdata RData),      \n          trap_mmap_spec d = Some d' ->\n          high_level_invariant d ->\n          id <> cid d -> obs_eq id d d'.\n      Proof.\n        intros id d d' Hspec Hinv Hid.\n        unfold trap_mmap_spec in Hspec.\n      Qed.\n\n    End CONF_MMAP.\n\n      (* ptResv is a special case for confidentiality - it is composed of a sequence of specs, some\n     of which (ptInsert0_spec in particular) violate noninterference. However, it is possible to\n     use high level invariants to prove that ptResv as a whole is nevertheless noninterfering. *)\n      Lemma conf_ptResv : \n        forall id (d1 d2 d1' d2' : cdata RData) n vadr pm r1 r2,      \n          ptResv_spec n vadr pm d1 = Some (d1', r1) ->\n          ptResv_spec n vadr pm d2 = Some (d2', r2) ->\n          high_level_invariant d1 -> high_level_invariant d2 ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2' /\\ r1 = r2.\n      Proof.\n        intros id d1 d2 d1' d2' n vadr pm r1 r2 Hspec1 Hspec2 Hinv1 Hinv2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold ptResv_spec in *.\n        conf_simpl id conf_palloc d1'' d2'' r.\n        subdestruct; inv Hspec1; inv Hspec2; auto.\n        split.\n        constructor.\n        {\n          unfold ptInsert0_spec in *.\n          clear Hnh; rewrite_fld ptpool; rewrite_fld nps.\n          subdestruct; inv H0; inv H1.\n          {\n            unfold ptInsertPTE0_spec in *.\n            rewrite_fld LAT; rewrite_fld pperm; rewrite_fld ptpool; rewrite_fld nps.\n            subdestruct; repeat inv_rewrite'; repeat nonHP_simpl; assumption.\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct14 Hdestruct11 Hobs_eq0) as [Hobs _].\n            inv Hobs; auto.\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct14 Hdestruct11 Hobs_eq0) as [_ Heq]; subst.\n            contradiction n1; auto.\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct15 Hdestruct11 Hobs_eq0) as [_ Heq]; subst.\n            contradiction n1; auto. \n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct15 Hdestruct11 Hobs_eq0) as [Hobs Heq]; subst.\n            inv Hobs.\n            unfold ptInsertPTE0_spec in *.\n            rewrite_fld LAT; rewrite_fld pperm; rewrite_fld ptpool; rewrite_fld nps.\n            subdestruct; repeat inv_rewrite'; repeat nonHP_simpl; assumption.\n          }\n        }\n        {\n          unfold ptInsert0_spec in *.\n          clear Hnh; rewrite_fld ptpool; rewrite_fld nps.\n          subdestruct; inv H0; inv H1.\n          {\n            unfold ptInsertPTE0_spec in *.\n            rewrite_fld LAT; rewrite_fld pperm; rewrite_fld ptpool; rewrite_fld nps.\n            subdestruct; repeat inv_rewrite'.\n            {\n              intros p' Hown o; inv Hown.\n              simpl in H.\n              destruct (zeq p' r); subst.\n              {\n                rewrite ZMap.gss in H; inv H.\n                destruct H0.\n                inv H.\n                unfold palloc_spec in *.\n                inv Hobs_eq; rewrite_fld nps; rewrite_fld LAT; rewrite_fld AC.\n                subdestruct; inv Hspec; inv Hspec0; simpl in *.\n                assert (Hneq: ZMap.get r (pperm d1) <> PGAlloc).\n                {\n                  intro Hcon.\n                  assert (Hneq: ZMap.get r (pperm d1) <> PGUndef) by \n                      (destruct (ZMap.get r (pperm d1)); inv Hcon; discriminate).\n                  destruct a0 as [Hrange [Hlat Hx]].\n                  assert (Hrange' : 0 <= r < nps d1) by omega.\n                  destruct (valid_pperm_ppage _ Hinv1 _ Hrange') as [Hperm _].\n                  destruct (Hperm Hneq) as [n Hlat'].\n                  rewrite Hlat in Hlat'; inv Hlat'.\n                }\n                rewrite (valid_dirty _ Hinv1 _ Hneq).\n                rewrite_fld_rev pperm.\n                rewrite (valid_dirty _ Hinv2 _ Hneq).\n                rewrite <- (pagei_ptaddr r o) at 2 4.\n                rewrite 2 FlatMem.free_page_gss; auto.\n                contradiction n0; auto.\n                contradiction n0; auto.\n                apply Hhp0; econstructor; eauto.\n              }\n              {\n                rewrite ZMap.gso in H; auto.\n                apply Hhp0; econstructor; eauto.\n              }\n            }\n            {\n              intros p' Hown o; inv Hown.\n              simpl in H.\n              destruct (zeq p' r); subst.\n              {\n                rewrite ZMap.gss in H; inv H.\n                destruct H0.\n                inv H.\n                unfold palloc_spec in *.\n                inv Hobs_eq; rewrite_fld nps; rewrite_fld LAT; rewrite_fld AC.\n                subdestruct; inv Hspec; inv Hspec0; simpl in *.\n                assert (Hneq: ZMap.get r (pperm d1) <> PGAlloc).\n                {\n                  intro Hcon.\n                  assert (Hneq: ZMap.get r (pperm d1) <> PGUndef) by \n                      (destruct (ZMap.get r (pperm d1)); inv Hcon; discriminate).\n                  destruct a0 as [Hrange [Hlat Hx]].\n                  assert (Hrange' : 0 <= r < nps d1) by omega.\n                  destruct (valid_pperm_ppage _ Hinv1 _ Hrange') as [Hperm _].\n                  destruct (Hperm Hneq) as [n Hlat'].\n                  rewrite Hlat in Hlat'; inv Hlat'.\n                }\n                rewrite (valid_dirty _ Hinv1 _ Hneq).\n                rewrite_fld_rev pperm.\n                rewrite (valid_dirty _ Hinv2 _ Hneq).\n                rewrite <- (pagei_ptaddr r o) at 2 4.\n                rewrite 2 FlatMem.free_page_gss; auto.\n                contradiction n0; auto.\n                contradiction n0; auto.\n                apply Hhp0; econstructor; eauto.\n              }\n              {\n                rewrite ZMap.gso in H; auto.\n                apply Hhp0; econstructor; eauto.\n              }\n            }\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct14 Hdestruct11 Hobs_eq0) as [Hobs _].\n            inv Hobs; auto.\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct14 Hdestruct11 Hobs_eq0) as [_ Heq]; subst.\n            contradiction n1; auto.\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct15 Hdestruct11 Hobs_eq0) as [_ Heq]; subst.\n            contradiction n1; auto.\n          }\n          {\n            destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                       Hdestruct15 Hdestruct11 Hobs_eq0) as [Hobs Heq]; subst.\n            rename r4 into d1''', r0 into d2'''.\n            unfold ptAllocPDE0_spec in *.\n            rewrite_fld LAT; rewrite_fld pperm; rewrite_fld ptpool; rewrite_fld nps; rewrite_fld AC.\n            subdestruct.\n            unfold ptInsertPTE0_spec in *.\n            inv Hobs; rewrite_fld LAT; rewrite_fld pperm; rewrite_fld ptpool; rewrite_fld nps.\n            subdestruct; simpl in *.\n            {\n              inv Hdestruct11; inv Hdestruct14; inv Hdestruct15; inv Hdestruct18; simpl in *.\n              intros p' Hown o; inv Hown.\n              simpl in H1.\n              destruct (zeq p' r); subst.\n              {\n                destruct (zeq r2 r); subst.\n                rewrite <- (pagei_ptaddr r o) at 2 4.\n                rewrite 2 FlatMem.free_page_gss; auto.\n                rewrite ZMap.gss in H1; inv H1.\n                destruct H2.\n                inv H1.\n                unfold palloc_spec in *.\n                inv Hobs_eq; rewrite_fld nps; rewrite_fld LAT; rewrite_fld AC.\n                subdestruct; inv Hspec; inv Hspec0; simpl in *.\n                assert (Hneq: ZMap.get r (pperm d1) <> PGAlloc).\n                {\n                  intro Hcon.\n                  assert (Hneq: ZMap.get r (pperm d1) <> PGUndef) by \n                      (destruct (ZMap.get r (pperm d1)); inv Hcon; discriminate).\n                  destruct a1 as [Hrange [Hlat Hx]].\n                  assert (Hrange' : 0 <= r < nps d1) by omega.\n                  destruct (valid_pperm_ppage _ Hinv1 _ Hrange') as [Hperm _].\n                  destruct (Hperm Hneq) as [n Hlat'].\n                  rewrite Hlat in Hlat'; inv Hlat'.\n                }\n                rewrite 2 FlatMem.free_page_gso; try solve [rewrite pagei_ptaddr; auto].\n                rewrite (valid_dirty _ Hinv1 _ Hneq).\n                rewrite_fld_rev' pperm H1.\n                rewrite (valid_dirty _ Hinv2 _ Hneq).\n                rewrite <- (pagei_ptaddr r o) at 2 4.\n                rewrite 2 FlatMem.free_page_gss; auto.\n                contradiction n0; auto.\n                contradiction n0; auto.\n                apply H0; econstructor; eauto.\n              }\n              {\n                rewrite ZMap.gso in H1; [|auto].\n                apply H0; econstructor; eauto.\n              }\n            }\n            {\n              inv Hdestruct11; inv Hdestruct14; inv Hdestruct15; inv Hdestruct18; simpl in *.\n              intros p' Hown o; inv Hown.\n              simpl in H1.\n              destruct (zeq p' r); subst.\n              {\n                destruct (zeq r2 r); subst.\n                rewrite <- (pagei_ptaddr r o) at 2 4.\n                rewrite 2 FlatMem.free_page_gss; auto.\n                rewrite ZMap.gss in H1; inv H1.\n                destruct H2.\n                inv H1.\n                unfold palloc_spec in *.\n                inv Hobs_eq; rewrite_fld nps; rewrite_fld LAT; rewrite_fld AC.\n                subdestruct; inv Hspec; inv Hspec0; simpl in *.\n                assert (Hneq: ZMap.get r (pperm d1) <> PGAlloc).\n                {\n                  intro Hcon.\n                  assert (Hneq: ZMap.get r (pperm d1) <> PGUndef) by \n                      (destruct (ZMap.get r (pperm d1)); inv Hcon; discriminate).\n                  destruct a1 as [Hrange [Hlat Hx]].\n                  assert (Hrange' : 0 <= r < nps d1) by omega.\n                  destruct (valid_pperm_ppage _ Hinv1 _ Hrange') as [Hperm _].\n                  destruct (Hperm Hneq) as [n Hlat'].\n                  rewrite Hlat in Hlat'; inv Hlat'.\n                }\n                rewrite 2 FlatMem.free_page_gso; try solve [rewrite pagei_ptaddr; auto].\n                rewrite (valid_dirty _ Hinv1 _ Hneq).\n                rewrite_fld_rev' pperm H1.\n                rewrite (valid_dirty _ Hinv2 _ Hneq).\n                rewrite <- (pagei_ptaddr r o) at 2 4.\n                rewrite 2 FlatMem.free_page_gss; auto.\n                contradiction n0; auto.\n                contradiction n0; auto.\n                apply H0; econstructor; eauto.\n              }\n              {\n                rewrite ZMap.gso in H1; [|auto].\n                apply H0; econstructor; eauto.\n              }\n            }\n            inv Hdestruct11; contradiction n1; auto.\n            inv Hdestruct11; contradiction n1; auto.\n          }\n        }\n        {\n          unfold ptInsert0_spec in *.\n          rewrite_fld nps; rewrite_fld ptpool.\n          subdestruct; inv H0; inv H1; auto.\n          destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                     Hdestruct14 Hdestruct11 Hobs_eq0) as [_ Heq]; subst.\n          contradiction n1; auto.\n          destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                     Hdestruct15 Hdestruct11 Hobs_eq0) as [_ Heq]; subst.\n          contradiction n1; auto.\n          destruct (conf_ptAllocPDE0 id _ _ _ _ _ _ _ _ \n                                     Hdestruct15 Hdestruct11 Hobs_eq0) as [_ Heq]; subst; auto.\n        }\n      Qed.\n\n    End CONF_PTRESV.\n*)\n(*\n    Section CONF_UCTX_ARG.\n\n      Lemma conf_uctx_set_errno :\n        forall id (d1 d2 d1' d2' : cdata RData) n,\n          uctx_set_errno_spec n d1 = Some d1' ->\n          uctx_set_errno_spec n d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' n Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        inv_spec; inv Hspec1; inv Hspec2.\n        rewrite_fld cid; rewrite_fld uctxt; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_uctx_set_retval1 :\n        forall id (d1 d2 d1' d2' : cdata RData) n,\n          uctx_set_retval1_spec n d1 = Some d1' ->\n          uctx_set_retval1_spec n d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' n Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        inv_spec; inv Hspec1; inv Hspec2.\n        rewrite_fld cid; rewrite_fld uctxt; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_uctx_set_retval2 :\n        forall id (d1 d2 d1' d2' : cdata RData) n,\n          uctx_set_retval2_spec n d1 = Some d1' ->\n          uctx_set_retval2_spec n d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' n Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        inv_spec; inv Hspec1; inv Hspec2.\n        rewrite_fld cid; rewrite_fld uctxt; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_uctx_set_retval3 :\n        forall id (d1 d2 d1' d2' : cdata RData) n,\n          uctx_set_retval3_spec n d1 = Some d1' ->\n          uctx_set_retval3_spec n d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' n Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        inv_spec; inv Hspec1; inv Hspec2.\n        rewrite_fld cid; rewrite_fld uctxt; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_uctx_set_retval4 :\n        forall id (d1 d2 d1' d2' : cdata RData) n,\n          uctx_set_retval4_spec n d1 = Some d1' ->\n          uctx_set_retval4_spec n d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' n Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        inv_spec; inv Hspec1; inv Hspec2.\n        rewrite_fld cid; rewrite_fld uctxt; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_uctx_set_retval5 :\n        forall id (d1 d2 d1' d2' : cdata RData) n,\n          uctx_set_retval5_spec n d1 = Some d1' ->\n          uctx_set_retval5_spec n d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' n Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        inv_spec; inv Hspec1; inv Hspec2.\n        rewrite_fld cid; rewrite_fld uctxt; solve_obs_eq Hhp.\n      Qed.\n\n    End CONF_UCTX_ARG.\n*)\n    Section INTEG_MMAP.\n(*\n      Lemma conf_vmx_set_mmap : \n        forall id (d1 d2 d1' d2' : cdata RData) gpa hpa ty r1' r2',\n          vmx_set_mmap_spec gpa hpa ty d1 = Some (d1', r1') ->\n          vmx_set_mmap_spec gpa hpa ty d2 = Some (d2', r2') ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2' /\\ r1' = r2'.\n      Proof.\n        intros id d1 d2 d1' d2' gpa hpa ty r1' r2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold vmx_set_mmap_spec, ept_add_mapping_spec in *.\n        rewrite_fld ept; subdestruct; inv Hspec1; inv Hspec2;\n        solve [split; try solve_obs_eq Hhp; inv_spec; repeat inv_rewrite'].\n      Qed.\n*)\n      Lemma integ_trap_mmap : \n        forall id (d d' : cdata RData),      \n          trap_mmap_spec d = Some d' ->\n          high_level_invariant d ->\n          id <> cid d -> obs_eq id d d'.\n      Proof.\n        intros id d d' Hspec Hinv Hid.\n        unfold trap_mmap_spec in Hspec.\n      Qed.\n\n    End CONF_MMAP.\n\n    Section CONF_PROC_CREATE.\n\n      Lemma conf_proc_create :\n        forall id (d1 d2 d1' d2' : cdata RData) b b' buc ofs q r1 r2,\n          proc_create_spec d1 b b' buc ofs q = Some (d1',r1) ->\n          proc_create_spec d2 b b' buc ofs q = Some (d2',r2) ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2' /\\ r1 = r2.\n      Proof.\n        intros id d1 d2 d1' d2' b b' buc ofs q r1 r2 Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld pb; rewrite_fld kctxt; rewrite_fld abq.\n        rewrite_fld abtcb; rewrite_fld uctxt; rewrite_fld AC; rewrite_fld cid.\n        subdestruct; inv Hspec1; inv Hspec2.\n        split; auto; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_trap_proc_create : \n        forall id (d1 d2 d1' d2' : cdata RData) s m,\n          trap_proc_create_spec s m d1 = Some d1' ->\n          trap_proc_create_spec s m d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' s m Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl.\n        rewrite_fld cid; rewrite_fld AC.\n        destruct (zle_le 0 z0\n                         (cquota (ZMap.get (cid d1) (AC d1)) -\n                          cusage (ZMap.get (cid d1) (AC d1)))).\n        conf_arg_simpl.\n        elim_none; elim_none; elim_none; elim_none; elim_none; elim_none.\n        elim_none; elim_none; elim_none; elim_none; elim_none.\n        conf_simpl' id conf_proc_create d1'' d2'' r.\n        conf_simpl_noret id conf_uctx_set_retval1 d1''' d2'''.\n        eapply conf_uctx_set_errno; eauto.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_PROC_CREATE.\n\n    Section CONF_TSC.\n\n      Lemma conf_vmx_set_tsc_offset : \n        forall id (d1 d2 d1' d2' : cdata RData) ofs,\n          vmx_set_tsc_offset_spec ofs d1 = Some d1' ->\n          vmx_set_tsc_offset_spec ofs d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' ofs Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; subdestruct; inv Hspec1; inv Hspec2; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_trap_get_tsc_offset : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_get_tsc_offset_spec d1 = Some d1' ->\n          trap_get_tsc_offset_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        unfold vmx_get_tsc_offset_spec in *.\n        rewrite_fld vmcs.\n        subdestruct.\n        eapply conf_uctx_set_errno; eauto.\n        eapply conf_uctx_set_retval2; eauto.\n        eapply conf_uctx_set_retval1; eauto.\n      Qed.\n\n      Lemma conf_trap_set_tsc_offset : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_set_tsc_offset_spec d1 = Some d1' ->\n          trap_set_tsc_offset_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl; conf_arg_simpl.\n        conf_simpl_noret id conf_vmx_set_tsc_offset d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_TSC.\n\n    Section CONF_EXITINFO.\n\n      Hint Unfold vmx_get_exit_reason_spec vmx_get_exit_io_port_spec vmx_get_io_width_spec \n           vmx_get_io_write_spec vmx_get_exit_io_rep_spec vmx_get_exit_io_str_spec\n           vmx_get_exit_fault_addr_spec.\n\n      Lemma conf_trap_get_exitinfo : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_get_exitinfo_spec d1 = Some d1' ->\n          trap_get_exitinfo_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs; autounfold in *. \n        rewrite_fld vmcs; rewrite_fld vmx; rewrite_fld ikern; rewrite_fld pg; rewrite_fld ihost.\n        elim_none; elim_none; elim_none; elim_none; elim_none; elim_none; elim_none.\n        conf_simpl_noret id conf_uctx_set_retval1 dr1 dr1'.\n        elim_none.\n        {\n          conf_simpl_noret id conf_uctx_set_retval2 dr2 dr2'.\n          conf_simpl_noret id conf_uctx_set_retval3 dr3 dr3'.\n          conf_simpl_noret id conf_uctx_set_retval4 dr4 dr4'.\n          eapply conf_uctx_set_errno; eauto.\n        }\n        {\n          elim_none.\n          conf_simpl_noret id conf_uctx_set_retval2 dr2 dr2'.\n          eapply conf_uctx_set_errno; eauto.\n          eapply conf_uctx_set_errno; eauto.\n        }\n      Qed.\n\n    End CONF_EXITINFO.\n\n    Section CONF_REG.\n\n      Lemma conf_vmx_get_reg : \n        forall id (d1 d2 : cdata RData) reg r1 r2,\n          vmx_get_reg_spec reg d1 = Some r1 ->\n          vmx_get_reg_spec reg d2 = Some r2 ->\n          obs_eq id d1 d2 -> r1 = r2.\n      Proof.\n        intros id d1 d2 reg r1 r2 Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; rewrite_fld vmx; subdestruct; inv Hspec1; inv Hspec2; auto.\n      Qed.\n\n      Lemma conf_vmx_set_reg : \n        forall id (d1 d2 d1' d2' : cdata RData) reg v,\n          vmx_set_reg_spec reg v d1 = Some d1' ->\n          vmx_set_reg_spec reg v d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' reg v Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; rewrite_fld vmx; subdestruct; inv Hspec1; inv Hspec2; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_trap_get_reg : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_get_reg_spec d1 = Some d1' ->\n          trap_get_reg_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl; elim_none.\n        elim_none_eqn' Hspec1 Hget1; elim_none_eqn' Hspec2 Hget2.\n        assert (z = z1) by (eapply conf_vmx_get_reg; eauto); subst.\n        conf_simpl_noret id conf_uctx_set_retval1 d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n      Lemma conf_trap_set_reg : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_set_reg_spec d1 = Some d1' ->\n          trap_set_reg_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl; conf_arg_simpl; elim_none.    \n        conf_simpl_noret id conf_vmx_set_reg d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_REG.\n\n    Section CONF_SEG.\n\n      Lemma conf_vmx_set_desc : \n        forall id (d1 d2 d1' d2' : cdata RData) seg sel base lim ar,\n          vmx_set_desc_spec seg sel base lim ar d1 = Some d1' ->\n          vmx_set_desc_spec seg sel base lim ar d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' seg sel base lim ar Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; subdestruct; inv Hspec1; inv Hspec2; solve_obs_eq Hhp.\n      Qed.\n\n      Lemma conf_trap_set_seg : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_set_seg_spec d1 = Some d1' ->\n          trap_set_seg_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl; conf_arg_simpl; conf_arg_simpl; conf_arg_simpl; conf_arg_simpl; elim_none.    \n        conf_simpl_noret id conf_vmx_set_desc d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_SEG.\n\n    Section CONF_EIP.\n\n      Lemma conf_vmx_get_next_eip : \n        forall id (d1 d2 : cdata RData) r1 r2,\n          vmx_get_next_eip_spec d1 = Some r1 ->\n          vmx_get_next_eip_spec d2 = Some r2 ->\n          obs_eq id d1 d2 -> r1 = r2.\n      Proof.\n        intros id d1 d2 r1 r2 Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; rewrite_fld vmx; subdestruct; inv Hspec1; inv Hspec2; auto.\n      Qed.\n\n      Lemma conf_trap_get_next_eip : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_get_next_eip_spec d1 = Some d1' ->\n          trap_get_next_eip_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        elim_none_eqn' Hspec1 Hget1; elim_none_eqn' Hspec2 Hget2.\n        assert (z = z0) by (eapply conf_vmx_get_next_eip; eauto); subst; elim_none.\n        conf_simpl_noret id conf_uctx_set_retval1 d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_EIP.\n\n    Section CONF_EVENT.\n\n      Lemma conf_vmx_inject_event : \n        forall id (d1 d2 d1' d2' : cdata RData) ty vec err ev,\n          vmx_inject_event_spec ty vec err ev d1 = Some d1' ->\n          vmx_inject_event_spec ty vec err ev d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' ty vec err ev Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; subdestruct'; apply inv_some in Hspec1; \n        apply inv_some in Hspec2; subst; auto; solve_obs_eq Hhp.\n      Qed.\n      \n      Lemma conf_trap_inject_event : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_inject_event_spec d1 = Some d1' ->\n          trap_inject_event_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl; conf_arg_simpl; conf_arg_simpl; conf_arg_simpl.\n        conf_simpl_noret id conf_vmx_inject_event d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n      Lemma conf_vmx_check_pending_event : \n        forall id (d1 d2 : cdata RData) r1 r2,\n          vmx_check_pending_event_spec d1 = Some r1 ->\n          vmx_check_pending_event_spec d2 = Some r2 ->\n          obs_eq id d1 d2 -> r1 = r2.\n      Proof.\n        intros id d1 d2 r1 r2 Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; subdestruct; inv Hspec1; inv Hspec2; auto.\n      Qed.\n\n      Lemma conf_trap_check_pending_event : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_check_pending_event_spec d1 = Some d1' ->\n          trap_check_pending_event_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        elim_none_eqn' Hspec1 Hget1; elim_none_eqn' Hspec2 Hget2.\n        assert (z = z0) by (eapply conf_vmx_check_pending_event; eauto); subst.\n        conf_simpl_noret id conf_uctx_set_retval1 d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_EVENT.\n\n    Section CONF_INT.\n\n      Lemma conf_vmx_check_int_shadow : \n        forall id (d1 d2 : cdata RData) r1 r2,\n          vmx_check_int_shadow_spec d1 = Some r1 ->\n          vmx_check_int_shadow_spec d2 = Some r2 ->\n          obs_eq id d1 d2 -> r1 = r2.\n      Proof.\n        intros id d1 d2 r1 r2 Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; subdestruct; inv Hspec1; inv Hspec2; auto.\n      Qed.\n\n      Lemma conf_vmx_set_intercept_intwin : \n        forall id (d1 d2 d1' d2' : cdata RData) en,\n          vmx_set_intercept_intwin_spec en d1 = Some d1' ->\n          vmx_set_intercept_intwin_spec en d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' en Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        rewrite_fld vmcs; subdestruct; inv Hspec1; inv Hspec2; solve_obs_eq Hhp.\n      Qed.\n      \n      Lemma conf_trap_check_int_shadow : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_check_int_shadow_spec d1 = Some d1' ->\n          trap_check_int_shadow_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        elim_none_eqn' Hspec1 Hget1; elim_none_eqn' Hspec2 Hget2.\n        assert (z = z0) by (eapply conf_vmx_check_int_shadow; eauto); subst.\n        conf_simpl_noret id conf_uctx_set_retval1 d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n      Lemma conf_trap_intercept_int_window : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_intercept_int_window_spec d1 = Some d1' ->\n          trap_intercept_int_window_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        conf_arg_simpl. \n        conf_simpl_noret id conf_vmx_set_intercept_intwin d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_INT.\n\n    Section CONF_MSR.\n\n      Lemma conf_rdmsr : \n        forall id (d1 d2 : cdata RData) z r1 r2,\n          rdmsr_spec z d1 = Some r1 ->\n          rdmsr_spec z d2 = Some r2 ->\n          obs_eq id d1 d2 -> r1 = r2.\n      Proof.\n        intros; inv_spec; rewrites; auto.\n      Qed.\n      \n      Lemma conf_wrmsr : \n        forall id (d1 d2 : cdata RData) z1 z2 r1 r2,\n          wrmsr_spec z1 z2 d1 = Some r1 ->\n          wrmsr_spec z1 z2 d2 = Some r2 ->\n          obs_eq id d1 d2 -> r1 = r2.\n      Proof.\n        intros; inv_spec; rewrites; auto.\n      Qed.\n\n      Lemma conf_trap_handle_rdmsr : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_handle_rdmsr_spec d1 = Some d1' ->\n          trap_handle_rdmsr_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        elim_none_eqn' Hspec1 Hget1; elim_none_eqn' Hspec2 Hget2.\n        assert (z = z0) by (eapply conf_vmx_get_reg; eauto); subst.\n        elim_none_eqn' Hspec1 Hget1'; elim_none_eqn' Hspec2 Hget2'.\n        assert (z = z1) by (eapply conf_rdmsr; eauto); subst; elim_none.\n        conf_simpl_noret id conf_vmx_set_reg dr1 dr1'.\n        conf_simpl_noret id conf_vmx_set_reg dr2 dr2'.\n        elim_none_eqn' Hspec1 Hget1''; elim_none_eqn' Hspec2 Hget2''.\n        assert (z1 = z2) by (eapply conf_vmx_get_next_eip; eauto); subst; elim_none.\n        conf_simpl_noret id conf_vmx_set_reg dr3 dr3'.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n      Lemma conf_trap_handle_wrmsr : \n        forall id (d1 d2 d1' d2' : cdata RData),\n          trap_handle_wrmsr_spec d1 = Some d1' ->\n          trap_handle_wrmsr_spec d2 = Some d2' ->\n          obs_eq id d1 d2 -> obs_eq id d1' d2'.\n      Proof.\n        intros id d1 d2 d1' d2' Hspec1 Hspec2 Hobs_eq.\n        assert (Hobs_eq':= Hobs_eq); destruct Hobs_eq' as [Hnh Hhp].\n        unfold_specs.\n        elim_none_eqn' Hspec1 Hget1; elim_none_eqn' Hspec2 Hget2.\n        assert (z = z0) by (eapply conf_vmx_get_reg; eauto); subst.\n        elim_none_eqn' Hspec1 Hget1'; elim_none_eqn' Hspec2 Hget2'.\n        assert (z = z1) by (eapply conf_vmx_get_reg; eauto); subst.\n        elim_none_eqn' Hspec1 Hget1''; elim_none_eqn' Hspec2 Hget2''.\n        assert (z = z2) by (eapply conf_vmx_get_reg; eauto); subst.\n        elim_none' Hspec1; elim_none' Hspec2.\n        elim_none_eqn' Hspec1 Hget1''''; elim_none_eqn' Hspec2 Hget2''''.\n        assert (z4 = z5) by (eapply conf_vmx_get_next_eip; eauto); subst; elim_none.    \n        conf_simpl_noret id conf_vmx_set_reg d1'' d2''.\n        eapply conf_uctx_set_errno; eauto.\n      Qed.\n\n    End CONF_MSR.\n\n\n  End INTEG_LEMMAS.\n\n\n\nEnd WITHMEM.\n\n  Ltac rewrites :=\n    repeat (match goal with\n            | [ Heq1: ?a = _, Heq2: ?a = _ |- _ ] => rewrite Heq2 in Heq1; inv Heq1\n            end).\n\n  Ltac rewrite_fld f := \n    match goal with\n    | [ Hnh : nonHP_eq ?d1 ?d2 |- _ ] => \n        let H := fresh in (assert (H: f d1 = f d2) by (inv Hnh; auto); rewrite <- H in *; clear H)\n    end.\n\n  Ltac rewrite_fld_rev f := \n    match goal with\n    | [ Hnh : nonHP_eq ?d1 ?d2 |- _ ] => \n        let H := fresh in (assert (H: f d2 = f d1) by (inv Hnh; auto); rewrite <- H in *; clear H)\n    end.\n\n  Ltac rewrite_fld' f Hnh:= \n    match type of Hnh with\n    | nonHP_eq ?d1 ?d2 => \n        let H := fresh in (assert (H: f d1 = f d2) by (inv Hnh; auto); rewrite <- H in *; clear H)\n    end.\n\n  Ltac rewrite_fld_rev' f Hnh := \n    match type of Hnh with\n    | nonHP_eq ?d1 ?d2 => \n        let H := fresh in (assert (H: f d2 = f d1) by (inv Hnh; auto); rewrite <- H in *; clear H)\n    end.\n\n  Ltac nonHP_simpl :=\n    match goal with\n    | [ |- nonHP_eq (update_HP _ _) (update_HP _ _) ] =>\n      let H := fresh in let Hnh := fresh in \n        assert (H: forall d1 d2 h1 h2, nonHP_eq d1 d2 -> nonHP_eq (update_HP d1 h1) (update_HP d2 h2)) \n          by (intros ? ? ? ? Hnh; inv Hnh; constructor; auto); apply H; clear H\n    | [ |- nonHP_eq (?f _ ?v) (?f _ ?v) ] => \n      let H := fresh in let Hnh := fresh in \n        assert (H: forall d1 d2 x, nonHP_eq d1 d2 -> nonHP_eq (f d1 x) (f d2 x)) \n          by (intros ? ? ? Hnh; inv Hnh; constructor; auto); apply H; clear H\n    end.\n\n  Ltac conf_simpl id conf_spec d1' d2' r2 :=\n    match goal with\n    | [ Hs1: match ?spec ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec d1'') as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec d2'') as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?a1 ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?a1 ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec a1 d1'') as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec a1 d2'') as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?a1 ?a2 ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?a1 ?a2 ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec a1 a2 d1'') as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec a1 a2 d2'') as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?a1 ?a2 ?a3 ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?a1 ?a2 ?a3 ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec a1 a2 a3 d1'') as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec a1 a2 a3 d2'') as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?a1 ?a2 ?a3 ?a4 ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?a1 ?a2 ?a3 ?a4 ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec a1 a2 a3 a4 d1'') as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec a1 a2 a3 a4 d2'') as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?a1 ?a2 ?a3 ?a4 ?a5 ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?a1 ?a2 ?a3 ?a4 ?a5 ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec a1 a2 a3 a4 a5 d1'') as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec a1 a2 a3 a4 a5 d2'') as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec a1 a2 a3 a4 a5 a6 d1'') as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec a1 a2 a3 a4 a5 a6 d2'') as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    end.\n\n  Ltac conf_simpl' id conf_spec d1' d2' r2 :=\n    match goal with\n    | [ Hs1: match ?spec ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec d1'') as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec d2'') as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?d1'' ?a1 with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?d2'' ?a1 with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec d1'' a1) as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec d2'' a1) as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?d1'' ?a1 ?a2 with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?d2'' ?a1 ?a2 with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec d1'' a1 a2) as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec d2'' a1 a2) as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?d1'' ?a1 ?a2 ?a3 with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?d2'' ?a1 ?a2 ?a3 with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec d1'' a1 a2 a3) as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec d2'' a1 a2 a3) as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?d1'' ?a1 ?a2 ?a3 ?a4 with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?d2'' ?a1 ?a2 ?a3 ?a4 with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec d1'' a1 a2 a3 a4) as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec d2'' a1 a2 a3 a4) as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?d1'' ?a1 ?a2 ?a3 ?a4 ?a5 with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?d2'' ?a1 ?a2 ?a3 ?a4 ?a5 with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec d1'' a1 a2 a3 a4 a5) as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec d2'' a1 a2 a3 a4 a5) as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?d1'' ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?d2'' ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in let Hret := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in let r1 := fresh in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec d1'' a1 a2 a3 a4 a5 a6) as [[d1' r1]|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec d2'' a1 a2 a3 a4 a5 a6) as [[d2' r2]|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2' /\\ r1 = r2) by (eapply conf_spec; eauto);\n           destruct H as [H Hret]; subst;\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    end.\n\n  Ltac conf_simpl_noret id conf_spec d1' d2' :=\n    match goal with\n    | [ Hs1: match ?spec ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec d1'') as [d1'|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec d2'') as [d2'|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2') by (eapply conf_spec; eauto);\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?a1 ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?a1 ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec a1 d1'') as [d1'|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec a1 d2'') as [d2'|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2') by (eapply conf_spec; eauto);\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?a1 ?a2 ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?a1 ?a2 ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec a1 a2 d1'') as [d1'|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec a1 a2 d2'') as [d2'|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2') by (eapply conf_spec; eauto);\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?a1 ?a2 ?a3 ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?a1 ?a2 ?a3 ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec a1 a2 a3 d1'') as [d1'|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec a1 a2 a3 d2'') as [d2'|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2') by (eapply conf_spec; eauto);\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?a1 ?a2 ?a3 ?a4 ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?a1 ?a2 ?a3 ?a4 ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec a1 a2 a3 a4 d1'') as [d1'|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec a1 a2 a3 a4 d2'') as [d2'|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2') by (eapply conf_spec; eauto);\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?a1 ?a2 ?a3 ?a4 ?a5 ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?a1 ?a2 ?a3 ?a4 ?a5 ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec a1 a2 a3 a4 a5 d1'') as [d1'|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec a1 a2 a3 a4 a5 d2'') as [d2'|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2') by (eapply conf_spec; eauto);\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    | [ Hs1: match ?spec ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?d1'' with Some _ => _ | None => _ end = _,\n        Hs2: match ?spec ?a1 ?a2 ?a3 ?a4 ?a5 ?a6 ?d2'' with Some _ => _ | None => _ end = _ |- _ ] =>\n        let Hobs_eq := fresh \"Hobs_eq\" in let H := fresh in\n        let Hnh := fresh \"Hnh\" in let Hhp := fresh \"Hhp\" in\n        let Hspec1 := fresh \"Hspec\" in let Hspec2 := fresh \"Hspec\" in \n          (destruct (spec a1 a2 a3 a4 a5 a6 d1'') as [d1'|] eqn:Hspec1; [|inv Hs1];\n           destruct (spec a1 a2 a3 a4 a5 a6 d2'') as [d2'|] eqn:Hspec2; [|inv Hs2];\n           assert (H: obs_eq id d1' d2') by (eapply conf_spec; eauto);\n           assert (Hobs_eq:= H); destruct H as [Hnh Hhp])\n    end.\n\n  Ltac conf_arg_simpl :=\n      let Harg1 := fresh in let Harg2 := fresh in\n      match goal with\n      | [ Hs1: match _ _ with Some _ => _ | None => _ end = _,\n          Hs2: match _ _ with Some _ => _ | None => _ end = _ |- _ ] =>\n        elim_none_eqn' Hs1 Harg1; elim_none_eqn' Hs2 Harg2;\n        match type of Harg1 with\n        | _ _ = Some ?r => \n        match type of Harg2 with\n        | _ _ = Some ?r' =>                           \n          assert (r = r') by\n              (clear Hs1 Hs2; inv_spec; rewrite_fld uctxt; rewrite_fld cid; rewrites; auto); \n          subst; clear Harg1 Harg2\n        end end end.\n\n  Ltac conf_goal :=\n    let Harg1 := fresh in let Harg2 := fresh in\n      match goal with\n      | [ Hs1: match _ _ with Some _ => _ | None => _ end = _,\n          Hs2: match _ _ with Some _ => _ | None => _ end = _ |- _ ] => \n        elim_none_eqn' Hs1 Harg1; elim_none_eqn' Hs2 Harg2;\n        match type of Harg1 with\n        | _ _ = Some ?r => \n        match type of Harg2 with\n        | _ _ = Some ?r' =>                           \n          assert (r = r'); [clear Hs1 Hs2; unfold_specs|] end end\n      | [ Hs1: match _ _ _ with Some _ => _ | None => _ end = _,\n          Hs2: match _ _ _ with Some _ => _ | None => _ end = _ |- _ ] => \n        elim_none_eqn' Hs1 Harg1; elim_none_eqn' Hs2 Harg2;\n        match type of Harg1 with\n        | _ _ _ = Some ?r => \n        match type of Harg2 with\n        | _ _ _ = Some ?r' =>                           \n          assert (r = r'); [clear Hs1 Hs2; unfold_specs|] end end\n      | [ Hs1: match _ _ _ _ with Some _ => _ | None => _ end = _,\n          Hs2: match _ _ _ _ with Some _ => _ | None => _ end = _ |- _ ] => \n        elim_none_eqn' Hs1 Harg1; elim_none_eqn' Hs2 Harg2;\n        match type of Harg1 with\n        | _ _ _ _ = Some ?r => \n        match type of Harg2 with\n        | _ _ _ _ = Some ?r' =>                           \n          assert (r = r'); [clear Hs1 Hs2; unfold_specs|] end end\n      | [ Hs1: match _ _ _ _ _ with Some _ => _ | None => _ end = _,\n          Hs2: match _ _ _ _ _ with Some _ => _ | None => _ end = _ |- _ ] => \n        elim_none_eqn' Hs1 Harg1; elim_none_eqn' Hs2 Harg2;\n        match type of Harg1 with\n        | _ _ _ _ _ = Some ?r => \n        match type of Harg2 with\n        | _ _ _ _ _ = Some ?r' =>                           \n          assert (r = r'); [clear Hs1 Hs2; unfold_specs|] end end\n      | [ Hs1: match _ _ _ _ _ _ with Some _ => _ | None => _ end = _,\n          Hs2: match _ _ _ _ _ _ with Some _ => _ | None => _ end = _ |- _ ] => \n        elim_none_eqn' Hs1 Harg1; elim_none_eqn' Hs2 Harg2;\n        match type of Harg1 with\n        | _ _ _ _ _ _ = Some ?r => \n        match type of Harg2 with\n        | _ _ _ _ _ _ = Some ?r' =>                           \n          assert (r = r'); [clear Hs1 Hs2; unfold_specs|] end end\n      | [ Hs1: match _ _ _ _ _ _ _ with Some _ => _ | None => _ end = _,\n          Hs2: match _ _ _ _ _ _ _ with Some _ => _ | None => _ end = _ |- _ ] => \n        elim_none_eqn' Hs1 Harg1; elim_none_eqn' Hs2 Harg2;\n        match type of Harg1 with\n        | _ _ _ _ _ _ _ = Some ?r => \n        match type of Harg2 with\n        | _ _ _ _ _ _ _ = Some ?r' =>                           \n          assert (r = r'); [clear Hs1 Hs2; unfold_specs|] end end\n      end.\n\n  Ltac solve_obs_eq Hhp :=\n    let p := fresh in let Hown := fresh in let o := fresh in\n      constructor; [repeat nonHP_simpl; auto |\n                    intros p Hown o; inv Hown; apply Hhp; econstructor; eauto].\n", "meta": {"author": "npe9", "repo": "certikos", "sha": "dd2631a096523a29a2e8a3101d8a224b754ea56a", "save_path": "github-repos/coq/npe9-certikos", "path": "github-repos/coq/npe9-certikos/certikos-dd2631a096523a29a2e8a3101d8a224b754ea56a/mcertikos/security/ConfidentialityCommon.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.2033546511400949}}
{"text": "Require Import Rel.Definitions.\nRequire Import Rel.BasicFacts.\nRequire Import Rel.Compat_sub.\nRequire Import Rel.Compat_map.\nRequire Import Util.Subset.\nRequire Import Lang.Static.\nRequire Import Lang.BindingsFacts.\nRequire Import Lang.StaticFacts.\nSet Implicit Arguments.\n\nSection section_compat_val_up.\n\nContext (EV HV V : Set).\nContext (Ξ : XEnv EV HV).\nContext (P : HV → F).\nContext (Γ : V → ty EV HV ∅).\nContext (𝔽 : F).\nContext (h₁ h₂ : hd EV HV V ∅).\nContext (ℓ : lbl HV ∅).\nContext (H_lbl₁ : lbl_hd h₁ = ℓ).\nContext (H_lbl₂ : lbl_hd h₂ = ℓ).\nContext (𝓔 : eff EV HV ∅).\nContext (H𝓔 : 𝓔 = [ef_lbl ℓ]).\nContext (Wf_Ξ : wf_XEnv Ξ).\nHint Resolve st_reflexive.\n\nLemma compat_val_up n :\nn ⊨ ⟦ Ξ P Γ ⊢ h₁ ≼ˡᵒᵍₕ h₂ : 𝔽 # ℓ ⟧ →\nn ⊨ ⟦ Ξ P Γ ⊢ (⇧ h₁) ≼ˡᵒᵍᵥ (⇧ h₂) :\n      ty_fun\n      (HV_open_ty (EV_open_ty (fst (Σ 𝔽))))\n      (HV_open_ty (EV_open_ty (snd (Σ 𝔽))))\n      𝓔 ⟧.\nProof.\nspecialize (Wf_Σ 𝔽) as Wf_Σ.\nintro Hh.\niintro ξ₁ ; iintro ξ₂ ; iintro δ₁ ; iintro δ₂ ; iintro δ ;\niintro ρ₁ ; iintro ρ₂ ; iintro ρ ; iintro γ₁ ; iintro γ₂.\niintro Hξ ; iintro cl_δ ; iintro cl_ρ₁ρ₂ ; iintro Hρ ; iintro Hγ.\nsimpl.\niintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂' ;\niintro v₁ ; iintro v₂ ; iintro Hv.\n\niespecialize Hh.\nrepeat (ispecialize Hh ; [ eassumption | ]).\n\nbind_hole.\neapply 𝓦_in_𝓣.\ndestruct ℓ as [ p | [ | X ] ] ; [ | auto | ] ; simpl in Hh |- *.\n+ idestruct Hh as r₁ Hh ; idestruct Hh as r₂ Hh ;\n  idestruct Hh as X₁ Hh ; idestruct Hh as X₂ Hh ;\n  idestruct Hh as Hh₁h₂ Hh ; idestruct Hh as Hρ₁ρ₂ Hr.\n  iexists (λ ξ₁'' ξ₂'' t₁ t₂,\n    match t₁, t₂ with\n    | tm_val v₁, tm_val v₂ =>\n      ▷ 𝓥⟦ Ξ ⊢ HV_open_ty (EV_open_ty (snd (Σ 𝔽))) ⟧\n        δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁'' ξ₂'' v₁ v₂\n    | _, _ => (False)ᵢ\n    end\n  ).\n  repeat ieexists ; repeat isplit.\n  - subst 𝓔 ; simpl.\n    ileft ; repeat ieexists ; repeat isplit.\n    * eassumption.\n    * auto.\n    * auto 9.\n    * repeat ieexists ; repeat isplit ; [ eassumption | eassumption | ].\n      later_shift.\n      eapply 𝓗_Fun'_monotone ; eauto.\n    * clear - Hv Wf_Ξ Wf_Σ.\n      iintro_later ; apply 𝓥_roll.\n      erewrite I_iff_elim_M ; [ | apply closed_weaken_𝓥 ; crush ] ; eauto.\n    * clear - Wf_Ξ Wf_Σ.\n      iintro ξ₁ ; iintro ξ₂ ; iintro t₁ ; iintro t₂.\n      isplit ; iintro H ; later_shift.\n      { idestruct H as v₁ H ; idestruct H as v₂ H ; idestruct H as Ht₁t₂ Hv.\n        ielim_prop Ht₁t₂ ; destruct Ht₁t₂ ; subst.\n        apply 𝓥_unroll in Hv.\n        erewrite <- I_iff_elim_M ; [ | apply closed_weaken_𝓥 ] ; crush.\n      }\n      { repeat ieexists ; isplit ; [ crush | ].\n        apply 𝓥_roll.\n        erewrite I_iff_elim_M ; [ | apply closed_weaken_𝓥 ; crush ] ; eauto.\n      }\n  - iintro_prop ; crush.\n  - clear.\n    iintro ξ₁'' ; iintro ξ₂'' ; iintro t₁ ; iintro t₂ ; iintro Hξ₁'' ; iintro Hξ₂''.\n    iintro H ; destruct t₁, t₂ ; try icontradict H.\n    later_shift.\n    eapply 𝓥_in_𝓣 in H.\n    apply 𝓣_roll ; exact H.\n\n+ idestruct Hh as r₁ Hh ; idestruct Hh as r₂ Hh ; idestruct Hh as Hh₁h₂ Hh ;\n  idestruct Hh as T Hh ; idestruct Hh as 𝓕 Hh ; idestruct Hh as BindsX Hr.\n  iexists (λ ξ₁'' ξ₂'' t₁ t₂,\n    match t₁, t₂ with\n    | tm_val v₁, tm_val v₂ =>\n      ▷ 𝓥⟦ Ξ ⊢ HV_open_ty (EV_open_ty (snd (Σ 𝔽))) ⟧\n        δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁'' ξ₂'' v₁ v₂\n    | _, _ => (False)ᵢ\n    end\n  ).\n  repeat ieexists ; repeat isplit.\n  - subst 𝓔 ; simpl.\n    ileft ; repeat ieexists ; repeat isplit.\n    * auto 9.\n    * auto.\n    * auto 9.\n    * repeat ieexists ; repeat isplit ; [ eassumption | ].\n      repeat ieexists ; isplit ; [ eassumption | ].\n      later_shift.\n      eapply 𝓗_Fun'_monotone ; eauto.\n    * clear - Hv Wf_Ξ Wf_Σ.\n      iintro_later ; apply 𝓥_roll.\n      erewrite I_iff_elim_M ; [ | apply closed_weaken_𝓥 ; crush ] ; eauto.\n    * clear - Wf_Ξ Wf_Σ.\n      iintro ξ₁ ; iintro ξ₂ ; iintro t₁ ; iintro t₂.\n      isplit ; iintro H ; later_shift.\n      { idestruct H as v₁ H ; idestruct H as v₂ H ; idestruct H as Ht₁t₂ Hv.\n        ielim_prop Ht₁t₂ ; destruct Ht₁t₂ ; subst.\n        apply 𝓥_unroll in Hv.\n        erewrite <- I_iff_elim_M ; [ | apply closed_weaken_𝓥 ] ; crush.\n      }\n      { repeat ieexists ; isplit ; [ crush | ].\n        apply 𝓥_roll.\n        erewrite I_iff_elim_M ; [ | apply closed_weaken_𝓥 ; crush ] ; eauto.\n      }\n  - iintro_prop ; crush.\n  - clear.\n    iintro ξ₁'' ; iintro ξ₂'' ; iintro t₁ ; iintro t₂ ; iintro Hξ₁'' ; iintro Hξ₂''.\n    iintro H ; destruct t₁, t₂ ; try icontradict H.\n    later_shift.\n    eapply 𝓥_in_𝓣 in H.\n    apply 𝓣_roll ; exact H.\nQed.\n\nEnd section_compat_val_up.\n", "meta": {"author": "yizhouzhang", "repo": "abseff-coq", "sha": "129c08fde2b4e41b5348db397c8a8f0e30f14cb5", "save_path": "github-repos/coq/yizhouzhang-abseff-coq", "path": "github-repos/coq/yizhouzhang-abseff-coq/abseff-coq-129c08fde2b4e41b5348db397c8a8f0e30f14cb5/coq-src/ABS/Rel/Compat_val_up.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.3174262591305011, "lm_q1q2_score": 0.2033546385108894}}
{"text": "Require Import Classical Peano_dec Setoid PeanoNat.\nFrom hahn Require Import Hahn.\nRequire Import Lia.\n\nRequire Import Events.\nRequire Import Execution.\nRequire Import Execution_eco.\nRequire Import imm_bob.\nRequire Import imm_s.\nRequire Import imm_s_ppo.\nRequire Import imm_s_rfppo.\nRequire Import AuxDef.\nRequire Import SetSize.\nRequire Import FairExecution.\nRequire Import ImmFair.\nRequire Import AuxRel2.\nRequire Import CountabilityHelpers.\nRequire Import CombRelations.\nImport ListNotations.\nFrom imm Require Import imm_s.\nFrom imm Require Import imm_s_hb.\nRequire Import FairExecution. \nRequire Import AuxRel2.\nRequire Import FinThreads.\n\nSection HbFsupp.\n  Variable (G: execution) (sc: relation actid). \n  Hypothesis (WF: Wf G) (IMMCON: imm_consistent G sc).\n  Hypothesis (FAIR: mem_fair G) (FSUPP_SC: fsupp sc).\n  Hypothesis (TB: fin_threads G). \n  \n  Lemma fsupp_rs : fsupp (⦗set_compl is_init⦘ ⨾ rs G).\n  Proof using WF IMMCON FAIR.\n    assert (sc_per_loc G) as SCPL.\n    { apply coherence_sc_per_loc, IMMCON. }\n    unfold imm_s_hb.rs.\n    rewrite <- !seqA.\n    apply fsupp_seq.\n    2: { rewrite rf_rmw_in_co; auto.\n         rewrite rt_of_trans; [| apply co_trans; auto].\n         apply fsupp_cr. apply FAIR. }\n    rewrite inclusion_seq_eqv_r, seqA, inclusion_seq_eqv_l with (dom := is_w _).\n    rewrite inclusion_inter_l1. rewrite crE. relsf.\n    apply fsupp_union; auto using fsupp_eqv, fsupp_sb. \n  Qed.\n\n  Lemma fsupp_release : fsupp (release G).\n  Proof using WF IMMCON FAIR. \n    rewrite no_release_from_init; auto. \n    unfold imm_s_hb.release.\n    rewrite inclusion_seq_eqv_l with (dom := is_rel _).\n    eapply fsupp_mori.\n    2: { apply fsupp_seq with (r1 := ⦗set_compl is_init⦘ ⨾ (sb G)^?).\n         2: { apply fsupp_rs. }\n         rewrite crE. relsf. apply fsupp_union; auto using fsupp_sb, fsupp_eqv. }\n    red. rewrite no_sb_to_init at 1. basic_solver 10. \n  Qed. \n    \n  Lemma fsupp_sw : fsupp (sw G).\n  Proof using WF IMMCON FAIR.\n    unfold imm_s_hb.sw.\n    rewrite (no_rf_to_init WF).\n    rewrite !seqA. rewrite <- seqA with (r2 := rf G). \n    apply fsupp_seq.\n    2: { rewrite !inclusion_seq_eqv_r.\n         rewrite crE. relsf. apply fsupp_union; auto using fsupp_sb, fsupp_eqv. }\n    apply fsupp_seq; auto using fsupp_rf, fsupp_release.\n  Qed.  \n\n  Lemma fsupp_hb : fsupp (⦗set_compl is_init⦘ ⨾ hb G).\n  Proof using TB WF IMMCON FAIR.\n    rewrite (dom_l (wf_hbE WF)), <- !seqA.\n    rewrite <- id_inter, set_interC, <- set_minusE.\n    unfold imm_s_hb.hb.\n    rewrite clos_trans_domb_l_strong.\n    2: { rewrite no_sb_to_init, no_sw_to_init, wf_sbE, wf_swE; basic_solver. }\n    rewrite inclusion_seq_eqv_r. \n    arewrite (acts_set G \\₁ is_init ⊆₁ set_compl is_init); [basic_solver| ]. \n    rewrite seq_union_r.\n    eapply fsupp_ct with (s := acts_set G \\₁ is_init), fsupp_union; ins; eauto. \n    { rewrite 2!inclusion_seq_eqv_l.\n      cdes IMMCON. red in Cint. \n      generalize Cint. unfold acyclic, hb. basic_solver 10. }\n    { rewrite (dom_l (@wf_sbE G)), (dom_l (wf_swE WF)); basic_solver 10. }\n    { rewrite <- inclusion_union_r1.\n      eapply (@has_finite_antichains_sb G); eauto. }\n    { apply fsupp_sb; auto. }\n    eapply fsupp_mori; [| apply fsupp_sw]. red. basic_solver 10. \n  Qed.\n\n  Lemma fsupp_furr:\n    fsupp (⦗set_compl is_init⦘ ⨾ furr G sc).\n  Proof using WF IMMCON FSUPP_SC TB FAIR.\n    assert (wf_sc G sc) as WFSC by (apply IMMCON). \n    rewrite furr_alt; auto.\n    rewrite !crE, !seq_union_l, !seq_union_r.\n    rewrite !seq_id_l, !seq_id_r.\n    arewrite (hb G ⨾ hb G ⊆ hb G).\n    rewrite <- !seqA.\n    arewrite ((⦗set_compl (is_init)⦘ ;; ⦗is_w (lab G)⦘) ⨾ rf G ⊆ rf G) by basic_solver 10.\n    assert (⦗is_w (lab G)⦘ ⨾ sc ⊆ ∅₂) as AA.\n    { rewrite (wf_scD WFSC); type_solver. }\n    arewrite (⦗is_w (lab G)⦘ ⨾ sc ⊆ ∅₂); auto.\n    arewrite (⦗set_compl (is_init)⦘ ;; ⦗is_w (lab G)⦘ ⨾ sc ⊆ ∅₂).\n    { rewrite AA. basic_solver. }\n    rewrite <- !seqA.\n    arewrite (rf G ⨾ sc ⊆ ∅₂).\n    { rewrite (wf_scD WFSC), wf_rfD; auto. type_solver. }\n    rewrite seq_false_r, seq_false_l, union_false_l, union_false_r.\n    rewrite <- !seqA.\n    arewrite ((⦗set_compl is_init⦘ ⨾ ⦗is_w (lab G)⦘) ⨾ hb G ⊆ ⦗set_compl (is_init)⦘ ;; hb G)\n      by basic_solver 10.\n    assert (fsupp (rf G ⨾ hb G)) as CC.\n    { rewrite no_rf_to_init, seqA; auto.\n      apply fsupp_seq; auto using fsupp_hb, fsupp_rf. }\n    assert (fsupp (sc ⨾ hb G)) as DD.\n    { rewrite (no_sc_to_init WF WFSC). rewrite seqA; auto.      \n      apply fsupp_seq; auto using fsupp_hb. }\n    rewrite <- id_inter.\n    repeat apply fsupp_union; try by auto using fsupp_rf, fsupp_hb, fsupp_eqv. \n    all: try rewrite <- seqA.\n    all: apply fsupp_seq; auto using fsupp_rf, fsupp_hb, fsupp_eqv.\n  Qed.\n  \nEnd HbFsupp. \n", "meta": {"author": "weakmemory", "repo": "imm", "sha": "7942cc3f204cabca065b8fbf749323c398bc0973", "save_path": "github-repos/coq/weakmemory-imm", "path": "github-repos/coq/weakmemory-imm/imm-7942cc3f204cabca065b8fbf749323c398bc0973/src/imm/HbFsupp.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.334589441253186, "lm_q1q2_score": 0.2033176804645271}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import malloc.\nRequire Import malloc_lemmas.\nRequire Import malloc_sep.\nRequire Import VSU_malloc_definitions.\nLocal Open Scope logic.\n(*\nDefinition Gprog : funspecs := external_specs ++ private_specs.\n*)\n\nLemma body_fill_bin: semax_body MF_Vprog MF_Gprog f_fill_bin fill_bin_spec.\nProof. \nstart_function. \nforward_call b.  (*! s = bin2size(b) !*)\nset (s:=bin2sizeZ b).\nassert (WORD <= s <= bin2sizeZ(BINS-1)) by (pose proof (bin2size_range b); rep_lia).\nforward_call BIGBLOCK.  (*! *p = mmap0(BIGBLOCK ...) !*)  \n(*{ rep_lia. }*)\nIntros p.  \nif_tac in H1. (* split cases on mmap post *)\n- (* case p = nullval *)\n  forward_if. (*! if p == NULL, case true  !*)\n  forward. (*! return NULL !*)\n  Exists nullval. Exists 1. \n  entailer!. contradiction.\n- (* case p <> nullval *)\n  assert_PROP (isptr p) by entailer!.\n  destruct p; try contradiction. \n  rename b0 into pblk; rename i into poff. (* p as blk+ofs *)\n  assert_PROP (Ptrofs.unsigned poff + BIGBLOCK < Ptrofs.modulus) by entailer!.\n  forward_if; try contradiction. (*! if p == NULL, case false *)\n  forward_call((s,(Vptr pblk poff),nullval,0%nat,b)).  (*! t3 = list_from_block(s,p,null) *)\n  { unfold mmlist. entailer!. }\n  Intro q.\n  forward. (*! return t3 *) \n  Exists q. Exists (chunks_from_block (size2binZ s)).\n  if_tac.\n  { (* q = null - contradiction *)\n    pose proof (chunks_from_block_pos b H).\n    assert (q<>nullval).\n    { apply (proj1 H7) in H8.\n      rewrite Nat.add_0_r in H8.\n      rewrite <- Z2Nat.inj_0 in H8.\n      apply Z2Nat.inj in H8; try rep_lia.\n      subst s.\n      rewrite bin2size2bin_id in *; try rep_lia.\n      apply chunks_from_block_nonneg.\n    }\n    contradiction.\n  }\n  entailer!.\n  assert (Hbs: 0 <= s <= bin2sizeZ(BINS-1)) by rep_lia.\n  pose proof (size2bin_range s Hbs) as Hs.\n  pose proof (chunks_from_block_pos (size2binZ s) Hs).\n  rep_lia.\n  rewrite Nat.add_0_r. (* ugh *)\n  subst s.\n  cancel.\nQed.\n\n(*Definition module := [mk_body body_fill_bin].*)\n", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs/memmgr/verif_fill_bin.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.20326319462008793}}
{"text": "Require Import SpecCert.Address.\nRequire Import SpecCert.Cache.\nRequire Import SpecCert.Formalism.\nRequire Import SpecCert.Memory.\nRequire Import SpecCert.Smm.Delta.Behavior.\nRequire Import SpecCert.Smm.Software.\nRequire Import SpecCert.x86.\n\nDefinition invariant := Architecture Software -> Prop.\n\nDefinition smramc_inv\n           (a: Architecture Software) :=\n  smramc_is_locked (memory_controller a).\n\nDefinition smram_code_inv\n           (a:    Architecture Software) :=\n  forall (addr: PhysicalAddress),\n  forall (val:  Value),\n  forall (s:    Software),\n    is_inside_smram addr\n    -> find_memory_content a (dram addr) = (val, s)\n    -> s = smm.\n\nDefinition smrr_inv\n           (a: Architecture Software) :=\n  forall (pa: PhysicalAddress),\n  is_inside_smram pa\n  -> is_inside_smrr (proc a) pa.\n\nDefinition cache_clean_inv\n           (a:   Architecture Software) :=\n  forall (pa:  PhysicalAddress),\n  forall (val: Value),\n  forall (s:    Software),\n    is_inside_smram pa\n    -> cache_hit (cache a) pa\n    -> find_cache_content a pa = Some (val, s)\n    -> s = smm.\n\nDefinition ip_inv\n           (a: Architecture Software) :=\n  smm_context a = smm\n  -> is_inside_smram (ip (proc a)).\n\nDefinition smbase_inv\n           (a: Architecture Software) :=\n  is_inside_smram (smbase (proc a)).\n\nDefinition inv :=\n  fun (a: Architecture Software) =>\n    smramc_inv a\n    /\\ smram_code_inv a\n    /\\ smrr_inv a\n    /\\ cache_clean_inv a\n    /\\ ip_inv a\n    /\\ smbase_inv a.\n\nDefinition partial_preserve\n           (ev:   x86Event)\n           (prop: Architecture Software -> Prop)\n           (i:    Architecture Software -> Prop) :=\n  forall h h': Architecture Software,\n    inv h\n    -> prop h\n    -> x86_precondition h ev\n    -> x86_postcondition smm_context h ev h'\n    -> i h'.\n\nProgram Definition software_partial_preserve\n        (ev:   { e: x86Event | x86_software e})\n        (prop: Architecture Software -> Prop)\n        (i:    Architecture Software -> Prop) :=\n  forall h h': Architecture Software,\n    inv h\n    -> prop h\n    -> smm_behavior h ev\n    -> x86_precondition h ev\n    -> x86_postcondition smm_context h ev h'\n    -> i h'.\n\nDefinition preserve\n           (ev: x86Event)\n           (i:  Architecture Software -> Prop) :=\n  forall h h': Architecture Software,\n    inv h\n    -> x86_precondition h ev\n    -> x86_postcondition smm_context h ev h'\n    -> i h'.\n\nProgram Definition software_preserve\n        (ev: { e: x86Event | x86_software e})\n        (i:  Architecture Software -> Prop) :=\n  forall h h': Architecture Software,\n    inv h\n    -> smm_behavior h ev\n    -> x86_precondition h ev\n    -> x86_postcondition smm_context h ev h'\n    -> i h'.\n\nDefinition preserve_inv\n           (ev: x86Event) :=\n  forall h h': Architecture Software,\n    inv h\n    -> x86_precondition h ev\n    -> x86_postcondition smm_context h ev h'\n    -> inv h'.\n\nProgram Definition software_preserve_inv\n        (ev: { e: x86Event | x86_software e}) :=\n  forall h h': Architecture Software,\n    inv h\n    -> smm_behavior h ev\n    -> x86_precondition h ev\n    -> x86_postcondition smm_context h ev h'\n    -> inv h'.\n\nDefinition partial_preserve_inv\n           (ev:    x86Event)\n           (prop:  Architecture Software -> Prop)\n  := forall h h': Architecture Software,\n    inv h\n    -> prop h\n    -> x86_precondition h ev\n    -> x86_postcondition smm_context h ev h'\n    -> inv h'.\n\nProgram Definition software_partial_preserve_inv\n        (ev:   { e: x86Event | x86_software e})\n        (prop: Architecture Software -> Prop)\n  := forall h h',\n    inv h\n    -> prop h\n    -> smm_behavior h ev\n    -> x86_precondition h ev\n    -> x86_postcondition smm_context h ev h'\n    -> inv h'.\n\nLtac intros_preserve :=\n  let a := fresh \"a\" in\n  let a' := fresh \"a'\" in\n  let Hsmramc := fresh \"Hsmramc\" in\n  let Hsmram := fresh \"Hsmram\" in\n  let Hsmrr := fresh \"Hsmrr\" in\n  let Hclean := fresh \"Hclean\" in\n  let Hip := fresh \"Hip\" in\n  let Hsmbase := fresh \"Hsmbase\" in\n  let Hpre := fresh \"Hpre\" in\n  let Hpost := fresh \"Hpost\" in\n  intros a a' [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]] Hpre Hpost.\n\nLtac intros_soft_preserve :=\n  let a := fresh \"a\" in\n  let a' := fresh \"a'\" in\n  let Hsmramc := fresh \"Hsmramc\" in\n  let Hsmram := fresh \"Hsmram\" in\n  let Hsmrr := fresh \"Hsmrr\" in\n  let Hclean := fresh \"Hclean\" in\n  let Hip := fresh \"Hip\" in\n  let Hsmbase := fresh \"Hsmbase\" in\n  let Hsmm := fresh \"Hsmm\" in\n  let Hpre := fresh \"Hpre\" in\n  let Hpost := fresh \"Hpost\" in\n  intros a a' [Hsmramc [Hsmram [Hsmrr [Hclean [Hip Hsmbase]]]]] Hsmm Hpre Hpost.\n\nLtac unfold_inv :=\n  unfold inv;\n  unfold smramc_inv, smram_code_inv, smrr_inv, cache_clean_inv.\n\nLtac bully_preserve f1 f2 :=\n  unfold preserve_inv;\n  unfold_inv;\n  intros a a' [Hsmramc [Hsmram [Hsmrr Hclean]]] Hpre Hpost;\n  unfold x86_postcondition in Hpost;\n  unfold f1 in Hpost;\n  unfold f2 in Hpost;\n  rewrite Hpost;\n  simpl;\n  do 3 (try split); trivial.\n", "meta": {"author": "lthms", "repo": "speccert", "sha": "8c1edfb173548af0e9ca3c4e24d43726401fdb71", "save_path": "github-repos/coq/lthms-speccert", "path": "github-repos/coq/lthms-speccert/speccert-8c1edfb173548af0e9ca3c4e24d43726401fdb71/src/Smm/Delta/Invariant.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3665897432423098, "lm_q1q2_score": 0.20326318538528718}}
{"text": "Require Import Poulet4.P4light.Syntax.P4defs.\nRequire Import Poulet4.P4light.Semantics.Semantics.\nRequire Import ProD3.core.Core.\nRequire Import ProD3.core.Tofino.\nRequire Import ProD3.examples.sbf.p4ast.\nRequire Import ProD3.examples.sbf.ConFilter.\nRequire Import ProD3.examples.sbf.common.\nRequire Import ProD3.examples.sbf.FilterRepr.\nRequire Import ProD3.examples.sbf.verif_Win1.\nRequire Import ProD3.examples.sbf.verif_Win2.\nRequire Import ProD3.examples.sbf.verif_Win3.\nRequire Import ProD3.examples.sbf.verif_Win4.\nRequire Import ProD3.examples.sbf.verif_Filter.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_1_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_2_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_hash_index_3_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_clear_index_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_clear_window_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_1_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_2_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_3_body) : func_specs.\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply act_set_clear_win_4_body) : func_specs.\n\nDefinition P4_bf2_win_md_t_insert (f cf if' : Z) (new_clear_index : Sval) (is : list Sval) :=\n  if f=? cf then\n    P4_bf2_win_md_t (P4Bit 8 CLEAR) (Zrepeat new_clear_index 3)\n  else if f=? if' then\n    P4_bf2_win_md_t (P4Bit 8 INSERT) is\n  else\n    P4_bf2_win_md_t (P4Bit 8 NOOP) is.\n\nDefinition tbl_set_win_insert_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD (Some [[\"ds_md\"];\n               [\"act_set_clear_win_1\"; \"api_1\"];\n               [\"act_set_clear_win_1\"; \"api_2\"];\n               [\"act_set_clear_win_1\"; \"api_3\"];\n               [\"act_set_clear_win_1\"; \"api_4\"];\n               [\"act_set_clear_win_2\"; \"api_1\"];\n               [\"act_set_clear_win_2\"; \"api_2\"];\n               [\"act_set_clear_win_2\"; \"api_3\"];\n               [\"act_set_clear_win_2\"; \"api_4\"];\n               [\"act_set_clear_win_3\"; \"api_1\"];\n               [\"act_set_clear_win_3\"; \"api_2\"];\n               [\"act_set_clear_win_3\"; \"api_3\"];\n               [\"act_set_clear_win_3\"; \"api_4\"];\n               [\"act_set_clear_win_2\"; \"api_1\"];\n               [\"act_set_clear_win_4\"; \"api_1\"];\n               [\"act_set_clear_win_4\"; \"api_2\"];\n               [\"act_set_clear_win_4\"; \"api_3\"];\n               [\"act_set_clear_win_4\"; \"api_4\"]]) []\n    WITH (timer : Z * bool) (clear_index_1 hash_index_1 hash_index_2 hash_index_3: Sval)\n      (H_timer : 0 <= fst timer < frame_tick_tocks * num_frames),\n      PRE\n        (ARG []\n        (MEM [([\"api\"], P4Bit 8 INSERT);\n              ([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", P4Bit 16 (fst timer));\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"win_1\", P4_bf2_win_md_t_);\n                  (\"win_2\", P4_bf2_win_md_t_);\n                  (\"win_3\", P4_bf2_win_md_t_);\n                  (\"win_4\", P4_bf2_win_md_t_)])]\n        (EXT [])))\n      POST\n        (EX retv,\n        (ARG_RET [] retv\n        (let cf := get_clear_frame timer in\n        let if' := get_insert_frame cf in\n        (MEM [([\"ds_md\"], ValBaseStruct\n                 [(\"clear_window\", P4Bit 16 (fst timer));\n                  (\"clear_index_1\", clear_index_1);\n                  (\"hash_index_1\", hash_index_1);\n                  (\"hash_index_2\", hash_index_2);\n                  (\"hash_index_3\", hash_index_3);\n                  (\"win_1\", P4_bf2_win_md_t_insert 0 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_2\", P4_bf2_win_md_t_insert 1 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_3\", P4_bf2_win_md_t_insert 2 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3]);\n                  (\"win_4\", P4_bf2_win_md_t_insert 3 cf if' clear_index_1\n                        [hash_index_1; hash_index_2; hash_index_3])])]\n        (EXT [])))))%arg_ret_assr.\n\nLemma tbl_set_win_insert_body :\n  func_sound ge tbl_set_win_fd nil tbl_set_win_insert_spec.\nProof.\n  start_function; elim_trivial_cases.\n  - replace (get_clear_frame timer) with 0. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_1_body.\n    { entailer. }\n    { entailer. }\n  - replace (get_clear_frame timer) with 1. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_2_body.\n    { entailer. }\n    { entailer. }\n  - replace (get_clear_frame timer) with 2. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_3_body.\n    { entailer. }\n    { entailer. }\n  - replace (get_clear_frame timer) with 3. 2 : {\n      symmetry; eapply Z_div_squeeze'; eauto.\n    }\n    table_action act_set_clear_win_4_body.\n    { entailer. }\n    { entailer. }\n  - lia.\nQed.\n\n#[local] Hint Extern 5 (func_modifies _ _ _ _ _) => (apply tbl_set_win_insert_body) : func_specs.\n\nDefinition filter_insert := @filter_insert num_frames num_rows num_slots H_num_frames H_num_rows H_num_slots\n  frame_tick_tocks.\n\nDefinition Filter_insert_spec : func_spec :=\n  WITH (* p *),\n    PATH p\n    MOD None [p]\n    WITH (key : Val) (tstamp : Z) (cf : filter num_frames num_rows num_slots),\n      PRE\n        (ARG [eval_val_to_sval key; P4Bit 8 INSERT; P4Bit 48 tstamp; P4Bit 8 1]\n        (MEM []\n        (EXT [filter_repr p index_w panes rows cf])))\n      POST\n        (ARG_RET [P4Bit 8 1] ValBaseNull\n        (MEM []\n        (EXT [filter_repr p index_w panes rows (filter_insert cf (Z.odd (tstamp/2097152)) (hashes key))]))).\n\nLemma Filter_insert_body :\n  func_sound ge Filter_fd nil Filter_insert_spec.\nProof.\n  Time start_function.\n  destruct cf as [[ps ?H] ? ?].\n  unfold filter_repr.\n  cbn [proj1_sig] in *.\n  destruct_list ps.\n  normalize_EXT.\n  Time step.\n  Time step_call tbl_hash_index_1_body.\n  { entailer. }\n  Intros _.\n  step_call tbl_hash_index_2_body.\n  { entailer. }\n  Time simpl_assertion.\n  Intros _.\n  step_call tbl_hash_index_3_body.\n  { entailer. }\n  Time simpl_assertion.\n  Intros _.\n  set (is := (exist _ [hash1 key; hash2 key; hash3 key] eq_refl : listn Z 3)).\n  set (clear_is := (exist _ (Zrepeat fil_clear_index 3) eq_refl : listn Z 3)).\n  assert (Forall (fun i : Z => 0 <= i < num_slots) (`is)). {\n    repeat first [apply Forall_cons | apply Forall_nil].\n    all : unfold hash1, hash2, hash3;\n      apply Z.mod_pos_bound; lia.\n  }\n  P4assert (0 <= fil_clear_index < num_slots). {\n    unfold fil_clear_index_repr.\n    Intros i'.\n    normalize_EXT.\n    Intros_prop.\n    apply ext_implies_prop_intro.\n    subst.\n    apply Z.mod_pos_bound.\n    lia.\n  }\n  assert (Forall (fun i : Z => 0 <= i < num_slots) (`clear_is)). {\n    repeat first [\n      assumption\n    | constructor\n    ].\n  }\n  step_call tbl_clear_index_body.\n  { entailer. }\n  Time simpl_assertion.\n  Intros _.\n  step_call tbl_clear_window_body.\n  { entailer. }\n  Intros _.\n  set (new_timer := update_timer fil_timer (Z.odd (tstamp / 2097152))).\n  (* We need assert_Prop. *)\n  P4assert (0 <= fst new_timer < num_frames * frame_tick_tocks).\n  { unfold timer_repr.\n    normalize_EXT.\n    Intros_prop.\n    apply ext_implies_prop_intro.\n    auto.\n  }\n  step_call tbl_set_win_insert_body.\n  { entailer. }\n  { auto. }\n  Intros _.\n  (* unfold and fold in the post condition *)\n  unfold filter_insert, ConFilter.filter_insert.\n  unfold proj1_sig.\n  fold new_timer.\n  replace (exist (fun i : list Z => Zlength i = num_rows) (Zrepeat fil_clear_index num_rows) _) with clear_is. 2 : {\n    apply subset_eq_compat. auto.\n  }\n  assert (0 <= get_clear_frame new_timer < num_frames). {\n    unfold ConFilter.get_clear_frame.\n    split.\n    - apply Z.div_le_lower_bound; lia.\n    - apply Z.div_lt_upper_bound; lia.\n  }\n  destruct (get_clear_frame new_timer =? 0) eqn:?.\n  { replace (get_clear_frame new_timer) with 0 by lia.\n    step_call verif_Win1.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win4.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_into.\n    { hoare_func_table_nondet; elim_trivial_cases.\n      table_action NoAction_body.\n      { entailer. }\n      { apply arg_ret_implies_refl. }\n    }\n    { reflexivity. }\n    { reflexivity. }\n    simpl_assertion.\n    entailer.\n  }\n  destruct (get_clear_frame new_timer =? 1) eqn:?.\n  { replace (get_clear_frame new_timer) with 1 by lia.\n    step_call verif_Win1.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win4.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_into.\n    { hoare_func_table_nondet; elim_trivial_cases.\n      table_action NoAction_body.\n      { entailer. }\n      { apply arg_ret_implies_refl. }\n    }\n    { reflexivity. }\n    { reflexivity. }\n    simpl_assertion.\n    entailer.\n  }\n  destruct (get_clear_frame new_timer =? 2) eqn:?.\n  { replace (get_clear_frame new_timer) with 2 by lia.\n    step_call verif_Win1.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win4.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_into.\n    { hoare_func_table_nondet; elim_trivial_cases.\n      table_action NoAction_body.\n      { entailer. }\n      { apply arg_ret_implies_refl. }\n    }\n    { reflexivity. }\n    { reflexivity. }\n    simpl_assertion.\n    entailer.\n  }\n  destruct (get_clear_frame new_timer =? 3) eqn:?.\n  { replace (get_clear_frame new_timer) with 3 by lia.\n    step_call verif_Win1.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win2.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win3.Win_body _ _ is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    step_call verif_Win4.Win_body _ _ clear_is.\n    { entailer. }\n    { solve [repeat constructor]. }\n    { auto. }\n    simpl Z.eqb. cbn match.\n    step_into.\n    { hoare_func_table_nondet; elim_trivial_cases.\n      table_action NoAction_body.\n      { entailer. }\n      { apply arg_ret_implies_refl. }\n    }\n    { reflexivity. }\n    { reflexivity. }\n    simpl_assertion.\n    entailer.\n  }\n  lia.\nTime Qed.\n", "meta": {"author": "verified-network-toolchain", "repo": "VerifiableP4", "sha": "87afa7bef7d88da2e9a642e37c0ddb2412b57509", "save_path": "github-repos/coq/verified-network-toolchain-VerifiableP4", "path": "github-repos/coq/verified-network-toolchain-VerifiableP4/VerifiableP4-87afa7bef7d88da2e9a642e37c0ddb2412b57509/examples/sbf/verif_Filter_insert.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.3665897363221598, "lm_q1q2_score": 0.20326318154826842}}
{"text": "Require Import MetaProp.\nRequire Import SyntaxProp.\nRequire Import DynamicProp.\nRequire Import TypesProp.\nRequire Import WellFormednessProp.\nRequire Import Shared.\nRequire Import Locking.\n\nHint Constructors is_econtext.\nHint Constructors cfg_blocked.\n\nTactic Notation \"preservation_context_tactic\" integer(n) :=\n  solve[\n      intuition;\n         match goal with\n           | [IH : forall cfg', _ / ?cfg ==> cfg' -> ?P,\n                Hstep : _ / ?cfg ==> _ |- _] =>\n             eapply IH in Hstep as (Gamma' & wfCfg' & Hsub);\n               eauto;\n               inverts wfCfg' as Hfresh' wfH' wfV' wfT';\n               inversion wfT'; inversion Hsub;\n               exists Gamma'; split; try(eassumption)\n         end;\n         repeat (econstructor;\n                 simpl;\n                 eauto n using hasType_subsumption,\n                               hasType_subsumption_extend\n                          with env); try(omega)\n    | eexists; split; eauto with env].\n\nHint Immediate lt_0_Sn.\n\nLemma single_threaded_preservation :\n  forall P t' Gamma H V n Ls e cfg' t,\n    wfProgram P t' ->\n    wfConfiguration P Gamma (H, V, n, T_Thread Ls e) t ->\n    P / (H, V, n, T_Thread Ls e) ==> cfg' ->\n    exists Gamma',\n      wfConfiguration P Gamma' cfg' t /\\\n      wfSubsumption Gamma Gamma'.\nProof with eauto using subtypeOf with env.\n  introv wfP wfCfg Hstep.\n  inverts wfCfg as Hfresh wfH wfV wfT wfL.\n  inverts wfT as Hfree hasType.\n  gen cfg'.\n  hasType_cases(induction hasType) Case; intros;\n  (* Some trivial cases can be discarded*)\n  try(inv Hstep; malformed_context);\n\n  (* All variables must be dynamic *)\n  match goal with\n    | [Hfree : freeVars _ = nil |- _] =>\n      simpl in Hfree;\n        repeat\n        match goal with\n          | [Hfree : freeVars _ ++ _ ++ _ = nil |- _] =>\n            simpl in Hfree;\n              apply app_eq_nil in Hfree as (Hfree1 & Hfree2);\n              apply app_eq_nil in Hfree2 as (Hfree2 & Hfree3)\n          | [Hfree : freeVars _ ++ _ = nil |- _] =>\n            simpl in Hfree;\n              apply app_eq_nil in Hfree as (Hfree1 & Hfree2)\n          | [x : var |- _] =>\n            destruct x; try(congruence)\n        end\n    | _ => idtac\n  end;\n\n  (* Unfold the resulting configuation *)\n  destruct cfg' as [[[H' V'] n'] T'];\n\n  (* Assert that the fresh symbols grow monotonically *)\n  assert (Hmono: n <= n')\n    by eauto using step_n_monotonic;\n  try(\n  assert (wfL': wfLocking H' T')\n    by (eapply wfLocking_preservation in Hstep; eauto)\n    ).\n  + Case \"T_Var\".\n    inverts Hstep; try malformed_context...\n    wfEnvLookup. rewrite_and_invert.\n    eexists...\n  + Case \"T_New\".\n    inv Hstep; try malformed_context.\n    exists (extend Gamma (env_loc (length H)) (TClass c)).\n    assert (wfEnv P (extend Gamma (env_loc (length H)) (TClass c)))...\n    assert (fresh Gamma (env_loc (length H)))...\n    split...\n    apply wfConfiguration_substitution\n    with (ENew c); eauto using subtypeOf, wfLocking_heapExtend.\n    eapply wfConfiguration_heapExtend;\n      eauto using wfFields_declsToFields.\n  + Case \"T_Call\".\n    assert (wfL'': wfLocking H (T_Thread Ls e))\n      by eauto 3 using wfLocking_econtext.\n    inv Hstep;\n      try(malformed_context); try(inv_eq);\n      try(preservation_context_tactic 2).\n    - SCase \"EvalCall\". clear IHhasType2.\n      inv hasType1.\n      assert(Hsub: subtypeOf P (TClass c) t1)\n      by (wfEnvLookup; rewrite_and_invert;\n          inv hasType; wfEnvLookup;\n          assert (c0 = c) by crush; subst; eauto).\n      assert (wfC: wfType P (TClass c))...\n      assert (cLookup: classLookup P c <> None)\n        by (inv wfC; assumption).\n      apply classLookup_not_none in cLookup as (i & fs & ms & cLookup).\n      assert (wfCls: wfClassDecl P (Cls c i fs ms))\n        by (inv wfP; lookup_forall as wfCls; eauto)...\n      assert (mtds = ms)\n        by (simpls; destruct classLookup; eauto; inv_eq; inv_eq).\n      subst.\n      inverts wfCls as Hsigs wfFlds wfMtds.\n\n      assert (wfT2: wfType P t2)...\n      assert (sigLookup: methodSigLookup (extractSigs ms) m = Some (MethodSig m (y, t2) t))\n        by eauto using methodSigs_sub.\n      apply extractSigs_sound in sigLookup as [e mLookup].\n      rewrite_and_invert.\n      exists (extend\n                (extend\n                   Gamma (env_var (DV (DVar n))) (TClass c))\n                (env_var (DV (DVar (S n)))) t2).\n      assert (fresh Gamma (env_var (DV (DVar n))))...\n      assert (n <= S n)...\n      assert (fresh Gamma (env_var (DV (DVar (S n)))))...\n      split...\n      * { econstructor; auto.\n          + eapply wfHeap_invariance\n            with (Gamma := Gamma); eauto 3 with env.\n          + eapply wfVars_extend; eauto 2 with env.\n            - eapply wfVars_extend...\n              apply wfVars_ge with n...\n            - eapply hasType_subsumption\n              with (Gamma := Gamma);\n              eauto 2 using wfSubsumption_fresh with env.\n          + lookup_forall as wfMtd.\n            inv wfMtd. simpls.\n            econstructor...\n            - autorewrite with freeVars...\n            - eapply hasType_subst; eauto 3 with env.\n              eapply hasType_flip...\n              eapply hasType_subst; eauto 3 with env.\n              eapply hasType_subsumption\n              with (Gamma := (extend\n                                (extend empty (env_var (SV y)) t2)\n                                 (env_var (SV this)) (TClass c)));\n                eauto 3 using wfSubsumption_extend with env.\n              unfold fresh. case_extend. inv_eq. omega.\n        }\n  + Case \"T_Select\".\n    inv hasType.\n    assert (wfType P t)\n      by eauto using fieldLookup_wfType.\n    inv Hstep;\n      try(malformed_context); try(inv_eq);\n      try(preservation_context_tactic 2).\n    - SCase \"EvalSelect\". clear IHhasType.\n      wfEnvLookup. rewrite_and_invert.\n      inverts hasType as Vlookup envLookup Hsub.\n      assert (t2 = TClass c); subst...\n      assert (c0 = c)\n        by (wfEnvLookup; rewrite_and_invert); subst.\n      assert (wfF: exists v, F f = Some v /\\\n                             P; Gamma |- EVal v \\in t)\n        by eauto using dyn_wfFieldLookup, wfHeap_wfFields.\n      inv wfF as (v' & Flookup & hasType).\n      rewrite_and_invert.\n      inv wfL.\n      eexists. split...\n  + Case \"T_Update\".\n    assert (wfL'': wfLocking H (T_Thread Ls e))\n      by eauto 3 using wfLocking_econtext.\n    inv Hstep;\n      try(malformed_context); try(inv_eq);\n      try(preservation_context_tactic 2).\n    - SCase \"EvalUpdate\". clear IHhasType1. clear IHhasType2.\n      inv hasType1. wfEnvLookup. rewrite_and_invert.\n      inv hasType. wfEnvLookup.\n      assert (Heq: TClass c1 = TClass c)... inv Heq.\n      rewrite_and_invert.\n      exists Gamma. split...\n      inverts wfL as ? ? wfL.\n      inv wfL...\n      eapply wfConfiguration_heapUpdate;\n        eauto using wfFields_extend, wfHeldLocks_taken;\n        crush.\n  + Case \"T_Let\".\n    assert (wfL': wfLocking H' T').\n      eapply wfLocking_preservation in Hstep...\n      econstructor...\n      econstructor...\n      simpl...\n    assert (wfLocking H (T_Thread Ls e))\n      by (apply wfLocking_econtext with (ctx := ctx_let x body); eauto).\n    inv Hstep;\n      try(malformed_context); try(inv_eq);\n      try(preservation_context_tactic 2).\n    - SCase \"EvalLet\". clear IHhasType1. clear IHhasType2.\n      exists (extend Gamma (env_var (DV (DVar n))) t).\n      split...\n      * { econstructor; auto.\n          + eapply wfHeap_invariance\n            with (Gamma := Gamma);\n            eauto 2 with env.\n          + eapply wfVars_extend...\n            eapply wfVars_ge...\n          + econstructor;\n            eauto using hasType_subst with env;\n            autorewrite with freeVars...\n        }\n      * apply wfSubsumption_fresh...\n  + Case \"T_Cast\".\n    assert (wfL'': wfLocking H (T_Thread Ls e))\n      by eauto 3 using wfLocking_econtext.\n    inv Hstep;\n      try(malformed_context); try(inv_eq);\n      try(preservation_context_tactic 2).\n    - SCase \"EvalCast\". clear IHhasType.\n      exists Gamma. split...\n      econstructor...\n      econstructor...\n      inv hasType...\n  + Case \"T_Par\".\n    assert (wfL': wfLocking H' T').\n      eapply wfLocking_preservation in Hstep...\n      econstructor...\n      econstructor...\n      simpl... crush.\n    inv Hstep; try(malformed_context).\n    exists Gamma.\n    split...\n    econstructor...\n    apply wfSubsumption_frame in H0 as []...\n    econstructor...\n    - econstructor...\n      eapply hasType_subsumption with (Gamma := Gamma1)...\n    - econstructor...\n      eapply hasType_subsumption with (Gamma := Gamma2)...\n  + Case \"T_Lock\".\n    inv hasType1.\n    wfEnvLookup.\n    inv hasType.\n    - SCase \"V x = l\".\n      inv Hstep;\n      try(malformed_context); try(inv_eq);\n      try(preservation_context_tactic 2);\n      rewrite_and_invert.\n      exists Gamma. split...\n      econstructor...\n      eapply wfHeap_update...\n      eapply wfHeap_wfFields...\n    - inv Hstep;\n      try(malformed_context); try(inv_eq);\n      try(preservation_context_tactic 2);\n      rewrite_and_invert.\n  + Case \"T_Locked\".\n    inv hasType1.\n    assert (wfL'': wfLocking H (T_Thread Ls e))\n      by eauto 3 using wfLocking_econtext.\n    inv Hstep;\n      try(malformed_context); try(inv_eq);\n      try(preservation_context_tactic 2).\n    - SCase \"EvalLock_Release\". clear IHhasType1. clear IHhasType2.\n      exists Gamma. split...\n      econstructor...\n      eapply wfHeap_update...\n      eapply wfHeap_wfFields...\nQed.\n\nTheorem preservation :\n  forall P t' Gamma cfg cfg' t,\n    wfProgram P t' ->\n    wfConfiguration P Gamma cfg t ->\n    P / cfg ==> cfg' ->\n    exists Gamma',\n      wfConfiguration P Gamma' cfg' t /\\\n      wfSubsumption Gamma Gamma'.\nProof with eauto using wfConfiguration.\n  introv wfP wfCfg Hstep.\n  inverts wfCfg as Hfresh wfH wfV wfT wfL.\n  gen t cfg' wfL wfT.\n  induction T; intros...\n  + Case \"T = EXN\".\n    (* EXN does not step *)\n    inv Hstep.\n  + Case \"T = T_Thread e\".\n    eapply single_threaded_preservation...\n  + Case \"T = T_Async T1 T2 e\".\n    inverts wfT as Hfree hasType wfT1 wfT2.\n    inverts wfL as wfWl wfRl Hdisj wfL1 wfL2.\n    destruct cfg' as [[[H' V'] n'] T'].\n    assert (Hmono: n <= n')\n      by eauto using step_n_monotonic.\n    assert(wfLocking H' T')\n      by eauto using wfLocking_preservation.\n    inv Hstep;\n    try(\n        solve\n          [\n            (* When no thread steps, Gamma still types the cfg *)\n            exists Gamma; split; eauto with env\n          |\n            (* When one of the threads step, IH applies *)\n            match goal with\n              | [IH: forall t cfg', _ / (_, _, _, ?T) ==> cfg' -> _,\n                   Hstep: _ / (_, _, _, ?T) ==> _ |- _]\n                => eapply IH in Hstep as [Gamma' [wfCfg' wfSub]];\n                  eauto; inverts wfCfg'; exists Gamma'\n            end;\n            split; eauto;\n            econstructor; eauto with arith;\n            econstructor;\n            eauto using hasType_subsumption,\n                        wfThreads_subsumption\n          ]).\nQed.\n", "meta": {"author": "EliasC", "repo": "oolong", "sha": "f449d42f70da1c404883860296ec4f2c5ed088b7", "save_path": "github-repos/coq/EliasC-oolong", "path": "github-repos/coq/EliasC-oolong/oolong-f449d42f70da1c404883860296ec4f2c5ed088b7/coq/vanilla/Preservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.20326318154826842}}
{"text": "(* ** Imports and settings *)\nFrom mathcomp Require Import all_ssreflect all_algebra.\nFrom mathcomp Require Import word_ssrZ.\nRequire Import strings word utils type var expr.\nRequire Import compiler_util byteset.\nRequire Import ZArith.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nLocal Open Scope vmap.\nLocal Open Scope seq_scope.\n\nModule Import E.\n\n  Definition pass : string := \"stack allocation\".\n\n  Definition stk_error_gen (internal:bool) (x:var_i) msg := {|\n    pel_msg := msg;\n    pel_fn := None;\n    pel_fi := None;\n    pel_ii := None;\n    pel_vi := Some x.(v_info);\n    pel_pass := Some pass;\n    pel_internal := internal\n  |}.\n\n  Definition stk_error  := stk_error_gen false.\n  Definition stk_ierror := stk_error_gen true.\n\n  Definition stk_ierror_basic x msg :=\n    stk_ierror x (pp_box [:: pp_s msg; pp_nobox [:: pp_s \"(\"; pp_var x; pp_s \")\"]]).\n\n  Definition stk_error_no_var_gen (internal:bool) msg := {|\n    pel_msg := pp_s msg;\n    pel_fn := None;\n    pel_fi := None;\n    pel_ii := None;\n    pel_vi := None;\n    pel_pass := Some pass;\n    pel_internal := internal\n  |}.\n\n  Definition stk_error_no_var  := stk_error_no_var_gen false.\n  Definition stk_ierror_no_var := stk_error_no_var_gen true.\n\nEnd E.\n\n(* TODO: could [wsize_size] return a [positive] rather than a [Z]?\n   If so, [size_of] could return a positive too.\n*)\nDefinition size_of (t:stype) :=\n  match t with\n  | sword sz => wsize_size sz\n  | sarr n   => Zpos n\n  | sbool | sint => 1%Z\n  end.\n\nDefinition slot := var.\n\nNotation size_slot s := (size_of s.(vtype)).\n\nRecord region :=\n  { r_slot : slot;        (* the name of the region        *)\n      (* the size of the region is encoded in the type of [r_slot] *)\n    r_align : wsize;      (* the alignment of the region   *)\n    r_writable : bool;    (* the region is writable or not *)\n  }.\n\nDefinition region_beq (r1 r2:region) :=\n  [&& r1.(r_slot)     == r2.(r_slot), \n      r1.(r_align)    == r2.(r_align) &\n      r1.(r_writable) == r2.(r_writable)].\n\nDefinition region_same (r1 r2:region) :=\n  (r1.(r_slot) == r2.(r_slot)).\n\nLemma region_axiom : Equality.axiom region_beq.\nProof.\n  rewrite /region_beq => -[xs1 xa1 xw1] [xs2 xa2 xw2].\n  by apply:(iffP and3P) => /= [[/eqP -> /eqP -> /eqP ->] | [-> -> ->]].\nQed.\n\nDefinition region_eqMixin := Equality.Mixin region_axiom.\nCanonical  region_eqType  := Eval hnf in EqType region region_eqMixin.\n\nModule CmpR.\n\n  Definition t := [eqType of region].\n\n  Definition cmp (r1 r2: t) := \n    Lex (bool_cmp r1.(r_writable) r2.(r_writable))\n     (Lex (wsize_cmp r1.(r_align) r2.(r_align))\n          (var_cmp r1.(r_slot) r2.(r_slot))).\n\n#[global]\n  Instance cmpO : Cmp cmp.\n  Proof.\n    constructor => [x y | y x z c | [???] [???]]; rewrite /cmp !Lex_lex.\n    + by repeat (apply lex_sym; first by apply cmp_sym); apply cmp_sym.\n    + by repeat (apply lex_trans=> /=; first by apply cmp_ctrans); apply cmp_ctrans.\n    move=> /lex_eq [] /= h1 /lex_eq [] /= h2 h3.\n    by rewrite (cmp_eq h1) (cmp_eq h2) (cmp_eq h3).\n  Qed.\n\nEnd CmpR.\n\nModule Mr := Mmake CmpR.\n\n(* ------------------------------------------------------------------ *)\nRecord zone := {\n  z_ofs : Z;\n  z_len : Z;\n}.\n\nScheme Equality for zone.\n\nLemma zone_eq_axiom : Equality.axiom zone_beq.\nProof.\n  move=> x y;apply:(iffP idP).\n  + by apply: internal_zone_dec_bl.\n  by apply: internal_zone_dec_lb.\nQed.\n\nDefinition zone_eqMixin := Equality.Mixin zone_eq_axiom.\nCanonical  zone_eqType  := EqType zone zone_eqMixin.\n\nDefinition disjoint_zones z1 z2 := \n  (((z1.(z_ofs) + z1.(z_len))%Z <= z2.(z_ofs)) || \n   ((z2.(z_ofs) + z2.(z_len))%Z <= z1.(z_ofs)))%CMP.\n\n(* ------------------------------------------------------------------ *)\n(* A zone inside a region. *)\nRecord sub_region := {\n    sr_region : region;\n    sr_zone  : zone;\n  }.\n\nDefinition sub_region_beq sr1 sr2 := \n  (sr1.(sr_region) == sr2.(sr_region)) && (sr1.(sr_zone) == sr2.(sr_zone)).\n\nLemma sub_region_eq_axiom : Equality.axiom sub_region_beq.\nProof.\n  rewrite /sub_region_beq => -[mp1 sub1] [mp2 sub2].\n  by apply:(iffP andP) => /= [[/eqP -> /eqP ->] | [-> ->]].\nQed.\n\nDefinition sub_region_eqMixin := Equality.Mixin sub_region_eq_axiom.\nCanonical sub_region_eqType := EqType sub_region sub_region_eqMixin.\n\n(* ------------------------------------------------------------------ *)\n(* idea: could we use a gvar instead of var & v_scope? *)\nVariant ptr_kind_init :=\n| PIdirect of var & zone & v_scope\n| PIregptr of var\n| PIstkptr of var & zone & var.\n\nVariant ptr_kind :=\n| Pdirect of var & Z & wsize & zone & v_scope\n| Pregptr of var\n| Pstkptr of var & Z & wsize & zone & var.\n\nRecord param_info := { \n  pp_ptr      : var;\n  pp_writable : bool;\n  pp_align    : wsize;\n}.\n\nRecord pos_map := {\n  vrip    : var;\n  vrsp    : var;\n  vxlen   : var;\n  globals : Mvar.t (Z * wsize);\n  locals  : Mvar.t ptr_kind;\n  vnew    : Sv.t;\n}.\n\n(* TODO: Z.land or is_align ?\n   Could be just is_align (sub_region_addr sr) ws ? *)\nDefinition check_align x (sr:sub_region) ws :=\n  Let _ := assert (ws <= sr.(sr_region).(r_align))%CMP\n                  (stk_ierror_basic x \"unaligned offset\") in\n  assert (Z.land sr.(sr_zone).(z_ofs) (wsize_size ws - 1) == 0)%Z\n         (stk_ierror_basic x \"unaligned sub offset\").\n\nDefinition writable (x:var_i) (r:region) :=\n  assert r.(r_writable)\n    (stk_error x (pp_box [:: pp_s \"cannot write to the constant pointer\"; pp_var x; pp_s \"targetting\"; pp_var r.(r_slot) ])).\n\nModule Region.\n\nDefinition bytes_map := Mvar.t ByteSet.t.\n\nRecord region_map := {\n  var_region : Mvar.t sub_region; (* The region where the value is initialy stored            *)\n  region_var :> Mr.t bytes_map;     (* The set of source variables whose value is in the region *)\n    (* region -> var -> ByteSet.t *)\n}.\n\nDefinition empty_bytes_map := Mvar.empty ByteSet.t.\n\nDefinition empty := {|\n  var_region := Mvar.empty _;\n  region_var := Mr.empty bytes_map;\n|}.\n\nDefinition get_sub_region (rmap:region_map) (x:var_i) :=\n  match Mvar.get rmap.(var_region) x with\n  | Some sr => ok sr\n  | None => Error (stk_error x (pp_box [:: pp_s \"no region associated to variable\"; pp_var x]))\n  end.\n\nDefinition get_bytes_map (r:region) rv : bytes_map :=\n  odflt empty_bytes_map (Mr.get rv r).\n\nDefinition get_bytes (x:var) (bytes_map:bytes_map) :=\n  odflt ByteSet.empty (Mvar.get bytes_map x).\n\nDefinition interval_of_zone z := \n  {| imin := z.(z_ofs); imax := z.(z_ofs) + z.(z_len) |}.\n\nDefinition get_var_bytes rv r x :=\n  let bm := get_bytes_map r rv in\n  let bytes := get_bytes x bm in\n  bytes.\n\n(* Returns the sub-zone of [z] starting at offset [ofs] and of length [len].\n   The offset [z] can be None, meaning its exact value is not known. In this\n   case, the full zone [z] is returned. This is a safe approximation.\n*)\nDefinition sub_zone_at_ofs z ofs len := \n  match ofs with\n  | None => z\n  | Some ofs => {| z_ofs := z.(z_ofs) + ofs; z_len := len |}\n  end.\n\nDefinition sub_region_at_ofs sr ofs len :=\n  {| sr_region := sr.(sr_region);\n     sr_zone   := sub_zone_at_ofs sr.(sr_zone) ofs len\n  |}.\n\nDefinition check_valid (rmap:region_map) (x:var_i) ofs len :=\n  (* we get the bytes associated to variable [x] *)\n  Let sr := get_sub_region rmap x in\n  let bytes := get_var_bytes rmap sr.(sr_region) x in\n  let sr' := sub_region_at_ofs sr ofs len in\n  let isub_ofs := interval_of_zone sr'.(sr_zone) in\n  (* we check if [isub_ofs] is a subset of one of the intervals of [bytes] *)\n  Let _   := assert (ByteSet.mem bytes isub_ofs)\n                    (stk_error x (pp_box [:: pp_s \"the region associated to variable\"; pp_var x; pp_s \"is partial\"])) in\n  ok (sr, sr').\n\nDefinition clear_bytes i bytes := ByteSet.remove bytes i.\n(* TODO: check optim\n  let bytes := ByteSet.remove bytes i in\n  if ByteSet.is_empty bytes then None else Some bytes.\n*)\n\nDefinition clear_bytes_map i (bm:bytes_map) :=\n  Mvar.map (clear_bytes i) bm.\n(* TODO: if optim above, optim below\n  let bm := Mvar.filter_map (clear_bytes i) bm in\n  if Mvar.is_empty bm then None else Some bm.\n*)\n\n(* TODO: take [bytes] as an argument ? *)\nDefinition set_pure_bytes rv (x:var) sr ofs len :=\n  let z     := sr.(sr_zone) in\n  let z1    := sub_zone_at_ofs z ofs len in\n  let i     := interval_of_zone z1 in\n  let bm    := get_bytes_map sr.(sr_region) rv in\n  let bytes := if ofs is Some _ then ByteSet.add i (get_bytes x bm)\n               else get_bytes x bm\n  in\n  (* clear all bytes corresponding to z1 *)\n  let bm := clear_bytes_map i bm in\n  (* set the bytes *)\n  let bm := Mvar.set bm x bytes in\n  Mr.set rv sr.(sr_region) bm.\n\nDefinition set_bytes rv (x:var_i) sr (ofs : option Z) (len : Z) :=\n  Let _     := writable x sr.(sr_region) in\n  ok (set_pure_bytes rv x sr ofs len).\n\n(* TODO: as many functions are similar, maybe we could have one big function\n   taking flags as arguments that tell whether we have to check align/check valid... *)\nDefinition set_sub_region rmap (x:var_i) sr (ofs : option Z) (len : Z) :=\n  Let rv := set_bytes rmap x sr ofs len in\n  ok {| var_region := Mvar.set rmap.(var_region) x sr;\n        region_var := rv |}.\n\nDefinition sub_region_stkptr s ws z :=\n  let r := {| r_slot := s; r_align := ws; r_writable := true |} in\n  {| sr_region := r; sr_zone := z |}.\n\nSection WITH_POINTER_DATA.\nContext {pd: PointerData}.\n\nDefinition set_stack_ptr (rmap:region_map) s ws z (x':var) :=\n  let sr := sub_region_stkptr s ws z in\n  let rv := set_pure_bytes rmap x' sr (Some 0)%Z (wsize_size Uptr) in\n  {| var_region := rmap.(var_region);\n     region_var := rv |}.\n\n(* TODO: fusion with check_valid ? *)\nDefinition check_stack_ptr rmap s ws z x' :=\n  let sr := sub_region_stkptr s ws z in\n  let z := sub_zone_at_ofs z (Some 0)%Z (wsize_size Uptr) in\n  let i := interval_of_zone z in\n  let bytes := get_var_bytes rmap sr.(sr_region) x' in\n  ByteSet.mem bytes i.\n\nEnd WITH_POINTER_DATA.\n\n(* Precondition size_of x = ws && length sr.sr_zone = wsize_size ws *)\nDefinition set_word rmap (x:var_i) sr ws :=\n  Let _ := check_align x sr ws in\n  set_sub_region rmap x sr (Some 0)%Z (size_slot x).\n\n(* If we write to array [x] at offset [ofs], we invalidate the corresponding\n   memory zone for the other variables, and mark it as valid for [x].\n   The offset [ofs] can be None, meaning its exact value is not known. In this\n   case, the full zone [z] associated to array [x] is invalidated for the\n   other variables, and remains the zone associated to [x]. It is a safe\n   approximation.\n*)\n(* [set_word], [set_stack_ptr] and [set_arr_word] could be factorized? -> think more about it *)\nDefinition set_arr_word (rmap:region_map) (x:var_i) ofs ws :=\n  Let sr := get_sub_region rmap x in\n  Let _ := check_align x sr ws in\n  set_sub_region rmap x sr ofs (wsize_size ws).\n\nDefinition set_arr_call rmap x sr := set_sub_region rmap x sr (Some 0)%Z (size_slot x).\n\nDefinition set_move_bytes rv x sr :=\n  let bm := get_bytes_map sr.(sr_region) rv in\n  let bytes := get_bytes x bm in\n  let bm := Mvar.set bm x (ByteSet.add (interval_of_zone sr.(sr_zone)) bytes) in\n  Mr.set rv sr.(sr_region) bm.\n\nDefinition set_move_sub (rmap:region_map) x sr :=\n  let rv := set_move_bytes rmap x sr in\n  {| var_region := rmap.(var_region);\n     region_var := rv |}.\n\nDefinition set_arr_sub (rmap:region_map) (x:var_i) ofs len sr_from :=\n  Let sr := get_sub_region rmap x in\n  let sr' := sub_region_at_ofs sr (Some ofs) len in\n  Let _ := assert (sr' == sr_from)\n                  (stk_ierror x\n                    (pp_box [::\n                      pp_s \"the assignment to sub-array\"; pp_var x;\n                      pp_s \"cannot be turned into a nop: source and destination regions are not equal\"]))\n  in\n  ok (set_move_sub rmap x sr').\n\n(* identical to [set_sub_region], except clearing\n   TODO: fusion with set_arr_sub ? not sure its worth\n*)\nDefinition set_move (rmap:region_map) (x:var) sr :=\n  let rv := set_move_bytes rmap x sr in\n  {| var_region := Mvar.set rmap.(var_region) x sr;\n     region_var := rv |}.\n\nDefinition set_arr_init rmap x sr := set_move rmap x sr.\n\nDefinition incl_bytes_map (_r: region) (bm1 bm2: bytes_map) := \n  Mvar.incl (fun x => ByteSet.subset) bm1 bm2.\n\nDefinition incl (rmap1 rmap2:region_map) :=\n  Mvar.incl (fun x r1 r2 => r1 == r2) rmap1.(var_region) rmap2.(var_region) &&\n  Mr.incl incl_bytes_map rmap1.(region_var) rmap2.(region_var).\n\nDefinition merge_bytes (x:var) (bytes1 bytes2: option ByteSet.t) := \n  match bytes1, bytes2 with\n  | Some bytes1, Some bytes2 => \n    let bytes := ByteSet.inter bytes1 bytes2 in\n    if ByteSet.is_empty bytes then None\n    else Some bytes\n  | _, _ => None\n  end.\n\nDefinition merge_bytes_map (_r:region) (bm1 bm2: option bytes_map) :=\n  match bm1, bm2 with\n  | Some bm1, Some bm2 => \n    let bm := Mvar.map2 merge_bytes bm1 bm2 in\n    if Mvar.is_empty bm then None\n    else Some bm\n  | _, _ => None\n  end.\n\nDefinition merge (rmap1 rmap2:region_map) := \n  {| var_region := \n       Mvar.map2 (fun _ osr1 osr2 =>\n        match osr1, osr2 with\n        | Some sr1, Some sr2 => if sr1 == sr2 then osr1 else None\n        | _, _ => None\n        end) rmap1.(var_region) rmap2.(var_region);\n     region_var := Mr.map2 merge_bytes_map rmap1.(region_var) rmap2.(region_var) |}.\n\nEnd Region.\n\nImport Region.\n\nSection ASM_OP.\nContext {pd: PointerData}.\nContext `{asmop:asmOp}.\n\nDefinition mul := Papp2 (Omul (Op_w Uptr)).\nDefinition add := Papp2 (Oadd (Op_w Uptr)).\n\nDefinition mk_ofs aa ws e1 ofs := \n  let sz := mk_scale aa ws in\n  if is_const e1 is Some i then \n    cast_const (i * sz + ofs)%Z\n  else \n    add (mul (cast_const sz) (cast_ptr e1)) (cast_const ofs).\n\nDefinition mk_ofsi aa ws e1 := \n  if is_const e1 is Some i then Some (i * (mk_scale aa ws))%Z\n  else None.\n\nSection CHECK.\n\n(* The code in this file is called twice.\n   - First, it is called from the stack alloc OCaml oracle. Indeed, the oracle\n     returns initial results, and performs stack and reg allocation using\n     these results. Based on the program that it obtains,\n     it fixes some of the results and returns them.\n   - Second, it is called as a normal compilation pass on the results returned\n     by the oracle.\n\n   When the code is called from the OCaml oracle, all the checks\n   that are performed so that the pass can be proved correct are actually not\n   needed. We introduce this boolen [check] to deactivate some of the tests\n   when the code is called from the oracle.\n\n   TODO: deactivate more tests (or even do not use rmap) when [check] is [false]\n*)\nVariable (check : bool).\n\nDefinition assert_check E b (e:E) :=\n  if check then assert b e\n  else ok tt.\n\nVariant vptr_kind :=\n  | VKglob of Z * wsize\n  | VKptr  of ptr_kind.\n\nDefinition var_kind := option vptr_kind.\n\nRecord stack_alloc_params :=\n  {\n    (* Return an instruction that computes an address from an base address and\n     an offset. *)\n    sap_mov_ofs :\n      lval            (* The variable to save the address to. *)\n      -> assgn_tag    (* The tag present in the source. *)\n      -> vptr_kind    (* The kind of address to compute. *)\n      -> pexpr        (* Variable with base address. *)\n      -> Z            (* Offset. *)\n      -> option instr_r;\n  }.\n\nContext\n  (saparams : stack_alloc_params).\n\nSection Section.\n\nVariables (pmap:pos_map).\n\nSection ALLOC_E.\n\nVariables (rmap: region_map).\n\nDefinition get_global (x:var_i) := \n  match Mvar.get pmap.(globals) x with\n  | None => Error (stk_ierror_basic x \"unallocated global variable\")\n  | Some z => ok z\n  end.\n\nDefinition get_local (x:var) := Mvar.get pmap.(locals) x.\n\nDefinition check_diff (x:var_i) :=\n  if Sv.mem x pmap.(vnew) then\n    Error (stk_ierror_basic x \"the code writes to one of the new variables\")\n  else ok tt.\n\nDefinition check_var (x:var_i) := \n  match get_local x with\n  | None => ok tt\n  | Some _ =>\n    Error (stk_error x (pp_box [::\n      pp_var x; pp_s \"is a stack variable, but a reg variable is expected\"]))\n  end.\n\nDefinition with_var xi x := \n  {| v_var := x; v_info := xi.(v_info) |}.\n\nDefinition base_ptr sc :=\n  match sc with\n  | Slocal => pmap.(vrsp)\n  | Sglobal => pmap.(vrip)\n  end.\n\nDefinition addr_from_pk (x:var_i) (pk:ptr_kind) :=\n  match pk with\n  | Pdirect _ ofs _ z sc => ok (with_var x (base_ptr sc), ofs + z.(z_ofs))\n  | Pregptr p            => ok (with_var x p,             0)\n  | Pstkptr _ _ _ _ _    =>\n    Error (stk_error x (pp_box [::\n      pp_var x; pp_s \"is a stack pointer, it should not appear in an expression\"]))\n  end%Z.\n\nDefinition addr_from_vpk x (vpk:vptr_kind) :=\n  match vpk with\n  | VKglob zws => ok (with_var x pmap.(vrip), zws.1)\n  | VKptr pk => addr_from_pk x pk\n  end.\n\nDefinition mk_addr_ptr x aa ws (pk:ptr_kind) (e1:pexpr) :=\n  Let xofs := addr_from_pk x pk in\n  ok (xofs.1, mk_ofs aa ws e1 xofs.2).\n\nDefinition mk_addr x aa ws (vpk:vptr_kind) (e1:pexpr) :=\n  Let xofs := addr_from_vpk x vpk in\n  ok (xofs.1, mk_ofs aa ws e1 xofs.2).\n\nDefinition get_var_kind x :=\n  let xv := x.(gv) in\n  if is_glob x then\n    Let z := get_global xv in\n    ok (Some (VKglob z))\n  else \n    ok (omap VKptr (get_local xv)).\n\nDefinition sub_region_full x r :=\n  let z := {| z_ofs := 0; z_len := size_slot x |} in\n  {| sr_region := r; sr_zone := z |}.\n\nDefinition sub_region_glob x ws :=\n  let r := {| r_slot := x; r_align := ws; r_writable := false |} in\n  sub_region_full x r.\n\nDefinition check_vpk rmap (x:var_i) vpk ofs len :=\n  match vpk with\n  | VKglob (_, ws) =>\n    let sr := sub_region_glob x ws in\n    ok (sr, sub_region_at_ofs sr ofs len)\n  | VKptr _pk => \n    check_valid rmap x ofs len\n  end.\n\n(* We could write [check_vpk] as follows.\n  Definition check_vpk' rmap (x : gvar) ofs len :=\n    let (sr, bytes) := check_gvalid rmap x in\n    let sr' := sub_region_at_ofs sr.(sr_zone) ofs len in\n    let isub_ofs := interval_of_zone sr'.(sr_zone) in\n    (* we check if [isub_ofs] is a subset of one of the intervals of [bytes] *)\n    (* useless test when [x] is glob, but factorizes call to [sub_region_at_ofs] *)\n    Let _   := assert (ByteSet.mem bytes isub_ofs)\n                      (Cerr_stk_alloc \"check_valid: the region is partial\") in\n    ok sr'.\n*)\n\nDefinition check_vpk_word rmap x vpk ofs ws :=\n  Let srs := check_vpk rmap x vpk ofs (wsize_size ws) in\n  check_align x srs.1 ws.\n\nFixpoint alloc_e (e:pexpr) := \n  match e with\n  | Pconst _ | Pbool _ | Parr_init _ => ok e\n  | Pvar   x =>\n    let xv := x.(gv) in\n    Let vk := get_var_kind x in\n    match vk with\n    | None => Let _ := check_diff xv in ok e\n    | Some vpk => \n      if is_word_type (vtype xv) is Some ws then\n        Let _ := check_vpk_word rmap xv vpk (Some 0%Z) ws in\n        Let pofs := mk_addr xv AAdirect ws vpk (Pconst 0) in\n        ok (Pload ws pofs.1 pofs.2)\n      else Error (stk_ierror_basic xv \"not a word variable in expression\")\n    end\n\n  | Pget aa ws x e1 =>\n    let xv := x.(gv) in\n    Let e1 := alloc_e e1 in\n    Let vk := get_var_kind x in\n    match vk with\n    | None => Let _ := check_diff xv in ok (Pget aa ws x e1)\n    | Some vpk =>\n      let ofs := mk_ofsi aa ws e1 in\n      Let _ := check_vpk_word rmap xv vpk ofs ws in\n      Let pofs := mk_addr xv aa ws vpk e1 in\n      ok (Pload ws pofs.1 pofs.2)\n    end\n\n  | Psub aa ws len x e1 =>\n    Error (stk_ierror_basic x.(gv) \"Psub\")\n\n  | Pload ws x e1 =>\n    Let _ := check_var x in\n    Let _ := check_diff x in\n    Let e1 := alloc_e e1 in\n    ok (Pload ws x e1)\n\n  | Papp1 o e1 =>\n    Let e1 := alloc_e e1 in\n    ok (Papp1 o e1)\n\n  | Papp2 o e1 e2 =>\n    Let e1 := alloc_e e1 in\n    Let e2 := alloc_e e2 in\n    ok (Papp2 o e1 e2)\n\n  | PappN o es => \n    Let es := mapM alloc_e es in\n    ok (PappN o es)\n\n  | Pif t e e1 e2 =>\n    Let e := alloc_e e in\n    Let e1 := alloc_e e1 in\n    Let e2 := alloc_e e2 in\n    ok (Pif t e e1 e2)\n  end.\n\n  Definition alloc_es := mapM alloc_e.\n\nEnd ALLOC_E.\n\nDefinition sub_region_direct x align sc z :=\n  let r := {| r_slot := x; r_align := align; r_writable := sc != Sglob |} in\n  {| sr_region := r; sr_zone := z |}.\n\nDefinition sub_region_stack x align z :=\n  sub_region_direct x align Slocal z.\n\nDefinition sub_region_pk x pk :=\n  match pk with\n  | Pdirect x ofs align sub Slocal => ok (sub_region_stack x align sub)\n  | _ => Error (stk_ierror x (pp_box [:: pp_var x; pp_s \"is not in the stack\"]))\n  end.\n\nDefinition alloc_lval (rmap: region_map) (r:lval) (ty:stype) :=\n  match r with\n  | Lnone _ _ => ok (rmap, r)\n\n  | Lvar x =>\n    (* TODO: could we remove this [check_diff] and use an invariant in the proof instead? *)\n    match get_local x with\n    | None => Let _ := check_diff x in ok (rmap, r)\n    | Some pk => \n      if is_word_type (vtype x) is Some ws then \n        if subtype (sword ws) ty then \n          Let pofs := mk_addr_ptr x AAdirect ws pk (Pconst 0) in\n          Let sr   := sub_region_pk x pk in\n          let r := Lmem ws pofs.1 pofs.2 in\n          Let rmap := Region.set_word rmap x sr ws in\n          ok (rmap, r)\n        else Error (stk_ierror_basic x \"invalid type for assignment\")\n      else Error (stk_ierror_basic x \"not a word variable in assignment\")\n    end\n\n  | Laset aa ws x e1 =>\n    (* TODO: could we remove this [check_diff] and use an invariant in the proof instead? *)\n    Let e1 := alloc_e rmap e1 in\n    match get_local x with\n    | None => Let _ := check_diff x in ok (rmap, Laset aa ws x e1)\n    | Some pk => \n      let ofs := mk_ofsi aa ws e1 in \n      Let rmap := set_arr_word rmap x ofs ws in\n      Let pofs := mk_addr_ptr x aa ws pk e1 in\n      let r := Lmem ws pofs.1 pofs.2 in\n      ok (rmap, r)\n    end\n\n  | Lasub aa ws len x e1 =>\n    Error (stk_ierror_basic x \"Lasub\")\n\n  | Lmem ws x e1 =>\n    Let _ := check_var x in\n    Let _ := check_diff x in\n    Let e1 := alloc_e rmap e1 in\n    ok (rmap, Lmem ws x e1)\n  end.\n\nDefinition nop := Copn [::] AT_none Onop [::]. \n\n(* [is_spilling] is used for stack pointers. *)\nDefinition is_nop is_spilling rmap (x:var) (sry:sub_region) : bool :=\n  if is_spilling is Some (s, ws, z, f) then\n    if Mvar.get rmap.(var_region) x is Some srx then\n      (srx == sry) && check_stack_ptr rmap s ws z f\n    else false\n  else false.\n\n(* TODO: better error message *)\nDefinition get_addr is_spilling rmap x dx tag sry vpk y ofs :=\n  let ir := if is_nop is_spilling rmap x sry\n            then Some nop\n            else sap_mov_ofs saparams dx tag vpk y ofs in\n  let rmap := Region.set_move rmap x sry in\n  (rmap, ir).\n\nDefinition get_ofs_sub aa ws x e1 := \n  match mk_ofsi aa ws e1 with\n  | None     => Error (stk_ierror_basic x \"cannot take/set a subarray on a unknown starting position\")\n  | Some ofs => ok ofs\n  end.\n\nDefinition get_Lvar_sub lv := \n  match lv with\n  | Lvar x => ok (x, None)\n  | Lasub aa ws len x e1 =>\n    Let ofs := get_ofs_sub aa ws x e1 in\n    ok (x, Some (ofs, arr_size ws len))\n  | _      => Error (stk_ierror_no_var \"get_Lvar_sub: variable/subarray expected\")\n  end.\n\nDefinition get_Pvar_sub e := \n  match e with\n  | Pvar x => ok (x, None)\n  | Psub aa ws len x e1 =>\n    Let ofs := get_ofs_sub aa ws x.(gv) e1 in\n    ok (x, Some (ofs, arr_size ws len))\n  | _      => Error (stk_ierror_no_var \"get_Pvar_sub: variable/subarray expected\")\n  end.\n\nDefinition is_stack_ptr vpk :=\n  match vpk with\n  | VKptr (Pstkptr s ofs ws z f) => Some (s, ofs, ws, z, f)\n  | _ => None\n  end.\n\n(* Not so elegant: function [addr_from_vpk] can fail, but it\n   actually fails only on the [Pstkptr] case, that is treated apart.\n   Thus function [mk_addr_pexpr] never fails, but this is not checked statically.\n*)\nDefinition mk_addr_pexpr rmap x vpk :=\n  if is_stack_ptr vpk is Some (s, ofs, ws, z, f) then\n    Let _   := assert (check_stack_ptr rmap s ws z f)\n                      (stk_error x (pp_box [:: pp_s \"the stack pointer\"; pp_var x; pp_s \"is no longer valid\"])) in\n    ok (Pload Uptr (with_var x pmap.(vrsp)) (cast_const (ofs + z.(z_ofs))), 0%Z)\n  else\n    Let xofs := addr_from_vpk x vpk in\n    ok (Plvar xofs.1, xofs.2).\n\n(* TODO: the check [is_lvar] was removed, was it really on purpose? *)\n(* TODO : currently, we check that the source array is valid and set the target\n   array as valid too. We could, instead, give the same validity to the target\n   array as the source one.\n   [check_vpk] should be replaced with some function returning the valid bytes\n   of y...\n*)\n(* Precondition is_sarr ty *)\nDefinition alloc_array_move rmap r tag e :=\n  Let xsub := get_Lvar_sub r in\n  Let ysub := get_Pvar_sub e in\n  let '(x,subx) := xsub in\n  let '(y,suby) := ysub in\n\n  Let sryl := \n    let vy := y.(gv) in\n    Let vk := get_var_kind y in\n    let (ofs, len) := \n      match suby with\n      | None => (0%Z, size_slot vy)\n      | Some p => p\n      end\n    in\n    match vk with\n    | None => Error (stk_ierror_basic vy \"register array remains\")\n    | Some vpk =>\n      Let srs := check_vpk rmap vy vpk (Some ofs) len in\n      let sry := srs.2 in\n      Let eofs := mk_addr_pexpr rmap vy vpk in\n      ok (sry, vpk, eofs.1, (eofs.2 + ofs)%Z)\n    end\n  in\n  let '(sry, vpk, ey, ofs) := sryl in\n  match subx with\n  | None =>\n    match get_local (v_var x) with\n    | None    => Error (stk_ierror_basic x \"register array remains\")\n    | Some pk => \n      match pk with\n      | Pdirect s _ ws zx sc =>\n        let sr := sub_region_direct s ws sc zx in\n        Let _  :=\n          assert (sr == sry)\n                 (stk_ierror x\n                    (pp_box [::\n                      pp_s \"the assignment to array\"; pp_var x;\n                      pp_s \"cannot be turned into a nop: source and destination regions are not equal\"]))\n        in\n        let rmap := Region.set_move rmap x sry in\n        ok (rmap, nop)\n      | Pregptr p =>\n        let (rmap, oir) :=\n            get_addr None rmap x (Lvar (with_var x p)) tag sry vpk ey ofs in\n        match oir with\n        | None =>\n          let err_pp := pp_box [:: pp_s \"cannot compute address\"; pp_var x] in\n          Error (stk_error x err_pp)\n        | Some ir =>\n          ok (rmap, ir)\n        end\n      | Pstkptr slot ofsx ws z x' =>\n        let is_spilling := Some (slot, ws, z, x') in\n        let dx_ofs := cast_const (ofsx + z.(z_ofs)) in\n        let dx := Lmem Uptr (with_var x pmap.(vrsp)) dx_ofs in\n        let (rmap, oir) := get_addr is_spilling rmap x dx tag sry vpk ey ofs in\n        match oir with\n        | None =>\n          let err_pp := pp_box [:: pp_s \"cannot compute address\"; pp_var x] in\n          Error (stk_error x err_pp)\n        | Some ir =>\n          ok (Region.set_stack_ptr rmap slot ws z x', ir)\n        end\n      end\n    end\n  | Some (ofs, len) =>\n    match get_local (v_var x) with\n    | None   => Error (stk_ierror_basic x \"register array remains\")\n    | Some _ => \n      Let rmap := Region.set_arr_sub rmap x ofs len sry in\n      ok (rmap, nop)\n    end\n  end.\n\n(* This function is also defined in array_init.v *)\n(* TODO: clean *)\nDefinition is_array_init e := \n  match e with\n  | Parr_init _ => true\n  | _ => false\n  end.\n\n(* We do not update the [var_region] part *)\n(* there seems to be an invariant: all Pdirect are in the rmap *)\n(* long-term TODO: we can avoid putting PDirect in the rmap (look in pmap instead) *)\nDefinition alloc_array_move_init rmap r tag e :=\n  if is_array_init e then\n    Let xsub := get_Lvar_sub r in\n    let '(x,subx) := xsub in\n    let (ofs, len) := \n      match subx with\n      | None => (0%Z, size_slot (v_var x))\n      | Some p => p\n      end in\n    Let sr := \n      match get_local (v_var x) with\n      | None    => Error (stk_ierror_basic x \"register array remains\")\n      | Some pk =>\n        match pk with\n        | Pdirect x' _ ws z sc =>\n          if sc is Slocal then\n            ok (sub_region_stack x' ws z)\n          else\n            Error (stk_error x (pp_box [:: pp_s \"cannot initialize glob array\"; pp_var x]))\n        | _ => \n          get_sub_region rmap x\n        end\n      end in\n    let sr := sub_region_at_ofs sr (Some ofs) len in\n    let rmap := Region.set_move_sub rmap x sr in\n    ok (rmap, nop)\n  else alloc_array_move rmap r tag e.\n\nDefinition bad_lval_number := stk_ierror_no_var \"invalid number of lval\".\n\nDefinition alloc_lvals rmap rs tys := \n  fmapM2 bad_lval_number alloc_lval rmap rs tys.\n\nSection LOOP.\n\n Variable ii:instr_info.\n\n Variable check_c2 : region_map -> cexec ((region_map * region_map) * (pexpr * (seq cmd * seq cmd)) ).\n\n Fixpoint loop2 (n:nat) (m:region_map) := \n    match n with\n    | O => Error (pp_at_ii ii (stk_ierror_no_var \"loop2\"))\n    | S n =>\n      Let m' := check_c2 m in\n      if incl m m'.1.2 then ok (m'.1.1, m'.2)\n      else loop2 n (merge m m'.1.2)\n    end.\n\nEnd LOOP.\n\nRecord stk_alloc_oracle_t :=\n  { sao_align : wsize \n  ; sao_size: Z\n  ; sao_ioff: Z\n  ; sao_extra_size: Z\n  ; sao_max_size : Z\n  ; sao_max_call_depth : Z\n  ; sao_params : seq (option param_info)  (* Allocation of pointer params *)\n  ; sao_return : seq (option nat)         (* Where to find the param input region *)\n  ; sao_slots : seq (var * wsize * Z)  \n  ; sao_alloc: seq (var * ptr_kind_init)   (* Allocation of local variables without params, and stk ptr *)\n  ; sao_to_save: seq (var * Z)\n  ; sao_rsp: saved_stack\n  ; sao_return_address: return_address_location\n  }.\n\nSection PROG.\n\nContext (local_alloc: funname -> stk_alloc_oracle_t).\n\nDefinition get_Pvar e := \n  match e with\n  | Pvar x => ok x\n  | _      => Error (stk_ierror_no_var \"get_Pvar: variable expected\")\n  end.\n\n(* The name is chosen to be similar to [set_pure_bytes] and [set_move_bytes],\n   but there are probably better ideas.\n   TODO: factorize [set_clear_bytes] and [set_pure_bytes] ?\n*)\nDefinition set_clear_bytes rv sr ofs len :=\n  let z     := sr.(sr_zone) in\n  let z1    := sub_zone_at_ofs z ofs len in\n  let i     := interval_of_zone z1 in\n  let bm    := get_bytes_map sr.(sr_region) rv in\n  (* clear all bytes corresponding to z1 *)\n  let bm := clear_bytes_map i bm in\n  Mr.set rv sr.(sr_region) bm.\n\nDefinition set_clear_pure rmap sr ofs len :=\n  {| var_region := rmap.(var_region);\n     region_var := set_clear_bytes rmap sr ofs len |}.\n\nDefinition set_clear rmap x sr ofs len :=\n  Let _ := writable x sr.(sr_region) in\n  ok (set_clear_pure rmap sr ofs len).\n\n(* We clear the arguments. This is not necessary in the classic case, because\n   we also clear them when assigning the results in alloc_call_res\n   (this works if each writable reg ptr is returned (which is currently\n   checked by the pretyper) and if each result variable has the same size\n   as the corresponding input variable).\n   But this complexifies the proof and needs a few more\n   checks in stack_alloc to be valid. Thus, for the sake of simplicity, it was\n   decided to make the clearing of the arguments twice : here and in\n   alloc_call_res.\n\n   We use two rmaps:\n   - the initial rmap [rmap0] is used to check the validity of the sub-regions;\n   - the current rmap [rmap] is [rmap0] with all the previous writable sub-regions cleared.\n   Actually, we could use [rmap] to check the validity, and that would partially\n   enforce that the arguments correspond to disjoint regions (in particular,\n   writable sub-regions are pairwise disjoint), so with this version we could\n   simplify check_all_disj. If we first check the validity and clear the writable regions,\n   and then check the validity of the non-writable ones, we can even remove [check_all_disj].\n   But the error message (disjoint regions) is much clearer when we have [check_all_disj],\n   so I leave it as it is now.\n*)\nDefinition alloc_call_arg_aux rmap0 rmap (sao_param: option param_info) (e:pexpr) := \n  Let x := get_Pvar e in\n  Let _ := assert (~~is_glob x)\n                  (stk_ierror_basic x.(gv) \"global variable in argument of a call\") in\n  let xv := gv x in\n  match sao_param, get_local xv with\n  | None, None =>\n    Let _ := check_diff xv in\n    ok (rmap, (None, Pvar x))\n  | None, Some _ => Error (stk_ierror_basic xv \"argument not a reg\")\n  | Some pi, Some (Pregptr p) => \n    Let srs := Region.check_valid rmap0 xv (Some 0%Z) (size_slot xv) in\n    let sr := srs.1 in\n    Let rmap := if pi.(pp_writable) then set_clear rmap xv sr (Some 0%Z) (size_slot xv) else ok rmap in\n    Let _  := check_align xv sr pi.(pp_align) in\n    ok (rmap, (Some (pi.(pp_writable),sr), Pvar (mk_lvar (with_var xv p))))\n  | Some _, _ => Error (stk_ierror_basic xv \"the argument should be a reg ptr\")\n  end.\n\nDefinition alloc_call_args_aux rmap sao_params es :=\n  fmapM2 (stk_ierror_no_var \"bad params info\") (alloc_call_arg_aux rmap) rmap sao_params es.\n\nDefinition disj_sub_regions sr1 sr2 :=\n  ~~(region_same sr1.(sr_region) sr2.(sr_region)) || \n  disjoint_zones sr1.(sr_zone) sr2.(sr_zone).\n\nFixpoint check_all_disj (notwritables writables:seq sub_region) (srs:seq (option (bool * sub_region) * pexpr)) := \n  match srs with\n  | [::] => true\n  | (None, _) :: srs => check_all_disj notwritables writables srs\n  | (Some (writable, sr), _) :: srs => \n    if all (disj_sub_regions sr) writables then \n      if writable then \n        if all (disj_sub_regions sr) notwritables then \n          check_all_disj notwritables (sr::writables) srs\n        else false \n      else check_all_disj (sr::notwritables) writables srs\n    else false \n  end.\n\nDefinition alloc_call_args rmap (sao_params: seq (option param_info)) (es:seq pexpr) := \n  Let es := alloc_call_args_aux rmap sao_params es in\n  Let _  := assert (check_all_disj [::] [::] es.2)\n                   (stk_error_no_var \"some writable reg ptr are not disjoints\") in\n  ok es.\n\nDefinition check_lval_reg_call (r:lval) := \n  match r with\n  | Lnone _ _ => ok tt\n  | Lvar x =>\n    match get_local x with\n    | None   => Let _ := check_diff x in ok tt\n    | Some _ => Error (stk_ierror_basic x \"call result should be stored in reg\")\n    end\n  | Laset aa ws x e1 => Error (stk_ierror_basic x \"array assignement in lval of a call\")\n  | Lasub aa ws len x e1 => Error (stk_ierror_basic x \"sub-array assignement in lval of a call\")\n  | Lmem ws x e1     => Error (stk_ierror_basic x \"call result should be stored in reg\")\n  end.\n\nDefinition check_is_Lvar r (x:var) :=\n  match r with\n  | Lvar x' => x == x' \n  | _       => false \n  end.\n\nDefinition get_regptr (x:var_i) := \n  match get_local x with\n  | Some (Pregptr p) => ok (with_var x p)\n  | _ => Error (stk_ierror x (pp_box [:: pp_s \"variable\"; pp_var x; pp_s \"should be a reg ptr\"]))\n  end.\n\nDefinition alloc_lval_call (srs:seq (option (bool * sub_region) * pexpr)) rmap (r: lval) (i:option nat) :=\n  match i with\n  | None => \n    Let _ := check_lval_reg_call r in\n    ok (rmap, r)\n  | Some i => \n    match nth (None, Pconst 0) srs i with\n    | (Some (_,sr), _) =>\n      match r with\n      | Lnone i _ => ok (rmap, Lnone i (sword Uptr))\n      | Lvar x =>\n        Let p := get_regptr x in\n        Let rmap := Region.set_arr_call rmap x sr in\n        (* TODO: Lvar p or Lvar (with_var x p) like in alloc_call_arg? *)\n        ok (rmap, Lvar p)\n      | Laset aa ws x e1 => Error (stk_ierror_basic x \"array assignement in lval of a call\")\n      | Lasub aa ws len x e1 => Error (stk_ierror_basic x \"sub-array assignement in lval of a call\")\n      | Lmem ws x e1     => Error (stk_ierror_basic x \"call result should be stored in reg ptr\")\n      end\n    | (None, _) => Error (stk_ierror_no_var \"alloc_lval_call\")\n    end\n  end.\n\nDefinition alloc_call_res rmap srs ret_pos rs := \n  fmapM2 bad_lval_number (alloc_lval_call srs) rmap rs ret_pos.\n\nDefinition is_RAnone ral :=\n  if ral is RAnone then true else false.\n\nDefinition alloc_call (sao_caller:stk_alloc_oracle_t) rmap ini rs fn es := \n  let sao_callee := local_alloc fn in\n  Let es  := alloc_call_args rmap sao_callee.(sao_params) es in\n  let '(rmap, es) := es in\n  Let rs  := alloc_call_res rmap es sao_callee.(sao_return) rs in (*\n  Let _   := assert_check (~~ is_RAnone sao_callee.(sao_return_address))\n               (Cerr_stk_alloc \"cannot call export function\")\n  in *)\n  Let _   :=\n    let local_size :=\n      if is_RAnone sao_caller.(sao_return_address) then\n        (sao_caller.(sao_size) + sao_caller.(sao_extra_size) + wsize_size sao_caller.(sao_align) - 1)%Z\n      else\n        (round_ws sao_caller.(sao_align) (sao_caller.(sao_size) + sao_caller.(sao_extra_size)))%Z\n    in\n    assert_check (local_size + sao_callee.(sao_max_size) <=? sao_caller.(sao_max_size))%Z\n                 (stk_ierror_no_var \"error in max size computation\")\n  in\n  Let _   := assert_check (sao_callee.(sao_align) <= sao_caller.(sao_align))%CMP\n                          (stk_ierror_no_var \"non aligned function call\")\n  in\n  let es  := map snd es in\n  ok (rs.1, Ccall ini rs.2 fn es).\n\n(* Before stack_alloc :\n     Csyscall [::x] (getrandom len) [::t] \n     t : arr n & len <= n.\n     return arr len.\n   After: \n     xlen: Uptr \n     xlen := len;\n     Csyscall [::xp] (getrandom len) [::p, xlen] \n*)\nDefinition alloc_syscall ii rmap rs o es := \n  add_iinfo ii\n  match o with\n  | RandomBytes len =>\n    (* per the semantics, we have [len <= wbase Uptr], but we need [<] *)\n    Let _ := assert (len <? wbase Uptr)%Z\n                    (stk_error_no_var \"randombytes: the requested size is too large\")\n    in\n    match rs, es with\n    | [::Lvar x], [::Pvar xe] =>\n      let xe := xe.(gv) in\n      let xlen := with_var xe (vxlen pmap) in\n      Let p  := get_regptr xe in\n      Let xp := get_regptr x in\n      Let sr := get_sub_region rmap xe in\n      Let rmap := set_sub_region rmap x sr (Some 0%Z) (Zpos len) in\n      ok (rmap,\n          [:: MkI ii (Cassgn (Lvar xlen) AT_none (sword Uptr) (cast_const (Zpos len)));\n              MkI ii (Csyscall [::Lvar xp] o [:: Plvar p; Plvar xlen])])\n    | _, _ =>\n      Error (stk_ierror_no_var \"randombytes: invalid args or result\")\n    end\n  end.\n\nFixpoint alloc_i sao (rmap:region_map) (i: instr) : cexec (region_map * cmd) :=\n  let (ii, ir) := i in\n\n    match ir with\n    | Cassgn r t ty e => \n      if is_sarr ty then \n        Let ri := add_iinfo ii (alloc_array_move_init rmap r t e) in\n        ok (ri.1, [:: MkI ii ri.2]) \n      else\n        Let e := add_iinfo ii (alloc_e rmap e) in\n        Let r := add_iinfo ii (alloc_lval rmap r ty) in\n        ok (r.1, [:: MkI ii (Cassgn r.2 t ty e)])\n\n    | Copn rs t o e => \n      Let e  := add_iinfo ii (alloc_es rmap e) in\n      Let rs := add_iinfo ii (alloc_lvals rmap rs (sopn_tout o)) in\n      ok (rs.1, [:: MkI ii (Copn rs.2 t o e)])\n\n    | Csyscall rs o es =>\n      alloc_syscall ii rmap rs o es \n\n    | Cif e c1 c2 => \n      Let e := add_iinfo ii (alloc_e rmap e) in\n      Let c1 := fmapM (alloc_i sao) rmap c1 in\n      Let c2 := fmapM (alloc_i sao) rmap c2 in\n      let rmap:= merge c1.1 c2.1 in\n      ok (rmap, [:: MkI ii (Cif e (flatten c1.2) (flatten c2.2))])\n\n    | Cwhile a c1 e c2 => \n      let check_c rmap := \n        Let c1 := fmapM (alloc_i sao) rmap c1 in\n        let rmap1 := c1.1 in\n        Let e := add_iinfo ii (alloc_e rmap1 e) in\n        Let c2 := fmapM (alloc_i sao) rmap1 c2 in\n        ok ((rmap1, c2.1), (e, (c1.2, c2.2))) in\n      Let r := loop2 ii check_c Loop.nb rmap in\n      ok (r.1, [:: MkI ii (Cwhile a (flatten r.2.2.1) r.2.1 (flatten r.2.2.2))])\n\n    | Ccall ini rs fn es =>\n      Let ri := add_iinfo ii (alloc_call sao rmap ini rs fn es) in\n      ok (ri.1, [::MkI ii ri.2])                            \n\n    | Cfor _ _ _  => Error (pp_at_ii ii (stk_ierror_no_var \"don't deal with for loop\"))\n\n    end.\n\n\nEnd PROG.\n\nEnd Section.\n\nDefinition init_stack_layout (mglob : Mvar.t (Z * wsize)) sao := \n  let add (xsr: var * wsize * Z) \n          (slp:  Mvar.t (Z * wsize) * Z) :=\n    let '(stack, p) := slp in\n    let '(x,ws,ofs) := xsr in\n    if Mvar.get stack x is Some _ then Error (stk_ierror_no_var \"duplicate stack region\")\n    else if Mvar.get mglob x is Some _ then Error (stk_ierror_no_var \"a region is both glob and stack\")\n    else\n      if (p <= ofs)%CMP then\n        let len := size_slot x in\n        if (ws <= sao.(sao_align))%CMP then\n          if (Z.land ofs (wsize_size ws - 1) == 0)%Z then\n            let stack := Mvar.set stack x (ofs, ws) in\n            ok (stack, (ofs + len)%Z)\n          else Error (stk_ierror_no_var \"bad stack region alignment\")\n        else Error (stk_ierror_no_var \"bad stack alignment\")\n      else Error (stk_ierror_no_var \"stack region overlap\") in\n  Let _ := assert (0 <=? sao.(sao_ioff))%Z (stk_ierror_no_var \"negative initial stack offset\") in\n  Let sp := foldM add (Mvar.empty _, sao.(sao_ioff)) sao.(sao_slots) in\n  let '(stack, size) := sp in\n  if (size <= sao.(sao_size))%CMP then ok stack\n  else Error (stk_ierror_no_var \"stack size\").\n\nDefinition add_alloc globals stack (xpk:var * ptr_kind_init) (lrx: Mvar.t ptr_kind * region_map * Sv.t) :=\n  let '(locals, rmap, sv) := lrx in\n  let '(x, pk) := xpk in\n  if Sv.mem x sv then Error (stk_ierror_no_var \"invalid reg pointer\")\n  else if Mvar.get locals x is Some _ then\n    Error (stk_ierror_no_var \"the oracle returned two results for the same var\")\n  else\n    Let svrmap := \n      match pk with\n      | PIdirect x' z sc =>\n        let vars := if sc is Slocal then stack else globals in\n        match Mvar.get vars x' with\n        | None => Error (stk_ierror_no_var \"unknown region\")\n        | Some (ofs', ws') =>\n          if [&& (size_slot x <= z.(z_len))%CMP, (0%Z <= z.(z_ofs))%CMP &\n                 ((z.(z_ofs) + z.(z_len))%Z <= size_slot x')%CMP] then\n            let rmap :=\n              if sc is Slocal then\n                let sr := sub_region_stack x' ws' z in\n                Region.set_arr_init rmap x sr\n              else\n                rmap\n            in\n            ok (sv, Pdirect x' ofs' ws' z sc, rmap)\n          else Error (stk_ierror_no_var \"invalid slot\")\n        end\n      | PIstkptr x' z xp =>\n        if ~~ is_sarr x.(vtype) then\n          Error (stk_ierror_no_var \"a stk ptr variable must be an array\")\n        else\n        match Mvar.get stack x' with\n        | None => Error (stk_ierror_no_var \"unknown stack region\")\n        | Some (ofs', ws') =>\n          if Sv.mem xp sv then Error (stk_ierror_no_var \"invalid stk ptr (not unique)\")\n          else if xp == x then Error (stk_ierror_no_var \"a pseudo-var is equal to a program var\")\n          else if Mvar.get locals xp is Some _ then Error (stk_ierror_no_var \"a pseudo-var is equal to a program var\")\n          else\n            if [&& (Uptr <= ws')%CMP,\n                (0%Z <= z.(z_ofs))%CMP,\n                (Z.land z.(z_ofs) (wsize_size Uptr - 1) == 0)%Z,\n                (wsize_size Uptr <= z.(z_len))%CMP &\n                ((z.(z_ofs) + z.(z_len))%Z <= size_slot x')%CMP] then\n              ok (Sv.add xp sv, Pstkptr x' ofs' ws' z xp, rmap)\n          else Error (stk_ierror_no_var \"invalid ptr kind\")\n        end\n      | PIregptr p => \n        if ~~ is_sarr x.(vtype) then\n          Error (stk_ierror_no_var \"a reg ptr variable must be an array\")\n        else\n        if Sv.mem p sv then Error (stk_ierror_no_var \"invalid reg pointer already exists\")\n        else if Mvar.get locals p is Some _ then Error (stk_ierror_no_var \"a pointer is equal to a program var\")\n        else if vtype p != sword Uptr then Error (stk_ierror_no_var \"invalid pointer type\")\n        else ok (Sv.add p sv, Pregptr p, rmap) \n      end in\n    let '(sv,pk, rmap) := svrmap in\n    let locals := Mvar.set locals x pk in\n    ok (locals, rmap, sv).\n\nDefinition init_local_map vrip vrsp vxlen globals stack sao :=\n  Let _ := assert (vxlen != vrip) (stk_ierror_no_var \"two fresh variables are equal\") in\n  Let _ := assert (vxlen != vrsp) (stk_ierror_no_var \"two fresh variables are equal\") in\n  let sv := Sv.add vxlen (Sv.add vrip (Sv.add vrsp Sv.empty)) in\n  Let aux := foldM (add_alloc globals stack) (Mvar.empty _, Region.empty, sv) sao.(sao_alloc) in\n  let '(locals, rmap, sv) := aux in\n  ok (locals, rmap, sv).\n\n(** For each function, the oracle returns:\n  - the size of the stack block;\n  - an allocation for local variables;\n  - an allocation for the variables to save;\n  - where to save the stack pointer (of the caller); (* TODO: merge with above? *)\n  - how to pass the return address (non-export functions only)\n\n  It can call back the partial stack-alloc transformation that given an oracle (size of the stack block and allocation of stack variables)\n  will transform the body of the current function.\n\n  The oracle is implemented as follows:\n   1/ stack allocation\n   2/ Reg allocation\n   3/ if we have remaining register to save the stack pointer we use on those register\n      else\n        4/ we restart stack allocation and we keep one position in the stack to save the stack pointer\n        5/ Reg allocation\n*)\n\nDefinition check_result pmap rmap paramsi params oi (x:var_i) :=\n  match oi with\n  | Some i =>\n    match nth None paramsi i with\n    | Some sr =>\n      Let _ := assert (x.(vtype) == (nth x params i).(vtype))\n                      (stk_ierror_no_var \"reg ptr in result not corresponding to a parameter\") in\n      Let srs := check_valid rmap x (Some 0%Z) (size_slot x) in\n      let sr' := srs.1 in\n      Let _  := assert (sr == sr') (stk_ierror_no_var \"invalid reg ptr in result\") in\n      Let p  := get_regptr pmap x in\n      ok p\n    | None => Error (stk_ierror_no_var \"invalid function info\")\n    end\n  | None => \n    Let _ := check_var pmap x in\n    Let _ := check_diff pmap x in\n    ok x\n  end.\n\n(* TODO: clean the 3 [all2] functions *)\nDefinition check_all_writable_regions_returned paramsi (ret_pos:seq (option nat)) :=\n  all2 (fun i osr =>\n    match osr with\n    | Some sr => if sr.(sr_region).(r_writable) then Some i \\in ret_pos else true\n    | None => true\n    end) (iota 0 (size paramsi)) paramsi.\n\nDefinition check_results pmap rmap paramsi params ret_pos res := \n  Let _ := assert (check_all_writable_regions_returned paramsi ret_pos)\n                  (stk_ierror_no_var \"a writable region is not returned\")\n  in\n  mapM2 (stk_ierror_no_var \"invalid function info\")\n        (check_result pmap rmap paramsi params) ret_pos res.\n\n(* TODO: is duplicate region the best error msg ? *)\nDefinition init_param (mglob stack : Mvar.t (Z * wsize)) accu pi (x:var_i) := \n  let: (disj, lmap, rmap) := accu in\n  Let _ := assert (~~ Sv.mem x disj) (stk_ierror_no_var \"a parameter already exists\") in\n  if Mvar.get lmap x is Some _ then Error (stk_ierror_no_var \"a stack variable also occurs as a parameter\")\n  else\n  match pi with\n  | None => ok (accu, (None, x))\n  | Some pi => \n    Let _ := assert (vtype pi.(pp_ptr) == sword Uptr) (stk_ierror_no_var \"bad ptr type\") in\n    Let _ := assert (~~Sv.mem pi.(pp_ptr) disj) (stk_ierror_no_var \"duplicate region\") in\n    Let _ := assert (is_sarr x.(vtype)) (stk_ierror_no_var \"bad reg ptr type\") in\n    if Mvar.get lmap pi.(pp_ptr) is Some _ then Error (stk_ierror_no_var \"a pointer is equal to a local var\")\n    else if Mvar.get mglob x is Some _ then Error (stk_ierror_no_var \"a region is both glob and param\")\n    else if Mvar.get stack x is Some _ then Error (stk_ierror_no_var \"a region is both stack and param\")\n    else\n    let r :=\n      {| r_slot := x;\n         r_align := pi.(pp_align); r_writable := pi.(pp_writable) |} in\n    let sr := sub_region_full x r in\n    ok (Sv.add pi.(pp_ptr) disj,\n        Mvar.set lmap x (Pregptr pi.(pp_ptr)),\n        set_move rmap x sr,\n        (Some sr, with_var x pi.(pp_ptr)))\n  end.\n\nDefinition init_params mglob stack disj lmap rmap sao_params params :=\n  fmapM2 (stk_ierror_no_var \"invalid function info\")\n    (init_param mglob stack) (disj, lmap, rmap) sao_params params.\n\nDefinition alloc_fd_aux p_extra mglob (fresh_reg : string -> stype -> string) (local_alloc: funname -> stk_alloc_oracle_t) sao fd : cexec _ufundef :=\n  let vrip := {| vtype := sword Uptr; vname := p_extra.(sp_rip) |} in\n  let vrsp := {| vtype := sword Uptr; vname := p_extra.(sp_rsp) |} in\n  let vxlen := {| vtype := sword Uptr; vname := fresh_reg \"__len__\"%string (sword Uptr) |} in\n  let ra := sao.(sao_return_address) in\n  Let stack := init_stack_layout mglob sao in\n  Let mstk := init_local_map vrip vrsp vxlen mglob stack sao in\n  let '(locals, rmap, disj) := mstk in\n  (* adding params to the map *)\n  Let rparams :=\n    init_params mglob stack disj locals rmap sao.(sao_params) fd.(f_params) in\n  let: (sv, lmap, rmap, alloc_params) := rparams in\n  let paramsi := map fst alloc_params in\n  let params : seq var_i := map snd alloc_params in\n  let pmap := {|\n        vrip    := vrip;\n        vrsp    := vrsp;\n        vxlen   := vxlen;\n        globals := mglob;\n        locals  := lmap;\n        vnew    := sv;\n      |} in\n  Let _ := assert (0 <=? sao.(sao_extra_size))%Z\n                  (stk_ierror_no_var \"negative extra size\")\n  in\n  Let _ :=\n    let local_size :=\n      if is_RAnone sao.(sao_return_address) then\n        (sao.(sao_size) + sao.(sao_extra_size) + wsize_size sao.(sao_align) - 1)%Z\n      else\n        (round_ws sao.(sao_align) (sao.(sao_size) + sao.(sao_extra_size)))%Z\n    in\n    assert_check (local_size <=? sao.(sao_max_size))%Z\n                 (stk_ierror_no_var \"sao_max_size too small\")\n  in\n  Let rbody := fmapM (alloc_i pmap local_alloc sao) rmap fd.(f_body) in\n  let: (rmap, body) := rbody in\n  Let res :=\n      check_results pmap rmap paramsi fd.(f_params) sao.(sao_return) fd.(f_res) in\n  ok {|\n    f_info := f_info fd;\n    f_tyin := map2 (fun o ty => if o is Some _ then sword Uptr else ty) sao.(sao_params) fd.(f_tyin); \n    f_params := params;\n    f_body := flatten body;\n    f_tyout := map2 (fun o ty => if o is Some _ then sword Uptr else ty) sao.(sao_return) fd.(f_tyout);\n    f_res := res;\n    f_extra := f_extra fd |}.\n\nDefinition alloc_fd p_extra mglob (fresh_reg : string -> stype -> string) (local_alloc: funname -> stk_alloc_oracle_t) fn fd :=\n  let: sao := local_alloc fn in\n  Let fd := alloc_fd_aux p_extra mglob fresh_reg local_alloc sao fd in\n  let f_extra := {|\n        sf_align  := sao.(sao_align);\n        sf_stk_sz := sao.(sao_size);\n        sf_stk_ioff := sao.(sao_ioff);\n        sf_stk_extra_sz := sao.(sao_extra_size);\n        sf_stk_max := sao.(sao_max_size);\n        sf_max_call_depth := sao.(sao_max_call_depth);\n        sf_to_save := sao.(sao_to_save);\n        sf_save_stack := sao.(sao_rsp);\n        sf_return_address := sao.(sao_return_address);\n      |} in\n  ok (swith_extra fd f_extra).\n\nDefinition check_glob (m: Mvar.t (Z*wsize)) (data:seq u8) (gd:glob_decl) := \n  let x := gd.1 in\n  match Mvar.get m x with\n  | None => false \n  | Some (z, _) =>\n    let n := Z.to_nat z in\n    let data := drop n data in\n    match gd.2 with\n    | @Gword ws w =>\n      let s := Z.to_nat (wsize_size ws) in \n      (s <= size data) &&\n      (LE.decode ws (take s data) == w)\n    | @Garr p t =>\n      let s := Z.to_nat p in\n      (s <= size data) &&\n      all (fun i => \n             match read t (Z.of_nat i) U8 with\n             | Ok w => nth 0%R data i == w\n             | _    => false\n             end) (iota 0 s)\n    end\n  end.\n\nDefinition check_globs (gd:glob_decls) (m:Mvar.t (Z*wsize)) (data:seq u8) := \n  all (check_glob m data) gd.\n\nDefinition init_map (sz:Z) (l:list (var * wsize * Z)) : cexec (Mvar.t (Z*wsize)) :=\n  let add (vp:var * wsize * Z) (globals:Mvar.t (Z*wsize) * Z) :=\n    let '(v, ws, p) := vp in\n    if (globals.2 <=? p)%Z then\n      if Z.land p (wsize_size ws - 1) == 0%Z then\n        let s := size_slot v in\n        ok (Mvar.set globals.1 v (p,ws), p + s)%Z\n      else Error (stk_ierror_no_var \"bad global alignment\")\n    else Error (stk_ierror_no_var \"global overlap\") in\n  Let globals := foldM add (Mvar.empty (Z*wsize), 0%Z) l in\n  if (globals.2 <=? sz)%Z then ok globals.1\n  else Error (stk_ierror_no_var \"global size\").\n\nDefinition alloc_prog (fresh_reg:string -> stype -> Ident.ident) \n    rip rsp global_data global_alloc local_alloc (P:_uprog) : cexec _sprog :=\n  Let mglob := init_map (Z.of_nat (size global_data)) global_alloc in\n  let p_extra :=  {|\n    sp_rip   := rip;\n    sp_rsp   := rsp;\n    sp_globs := global_data;\n  |} in\n  if rip == rsp then Error (stk_ierror_no_var \"rip and rsp clash\")\n  else if check_globs P.(p_globs) mglob global_data then\n    Let p_funs := map_cfprog_name (alloc_fd  p_extra mglob fresh_reg local_alloc) P.(p_funcs) in\n    ok  {| p_funcs  := p_funs;\n           p_globs := [::];\n           p_extra := p_extra;\n        |}\n  else \n     Error (stk_ierror_no_var \"invalid data\").\n\nEnd CHECK.\n\nEnd ASM_OP.\n", "meta": {"author": "jasmin-lang", "repo": "jasmin", "sha": "3c783b662000c371ba924a953d444fd80b860d9f", "save_path": "github-repos/coq/jasmin-lang-jasmin", "path": "github-repos/coq/jasmin-lang-jasmin/jasmin-3c783b662000c371ba924a953d444fd80b860d9f/proofs/compiler/stack_alloc.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.20326317387423093}}
{"text": "Require Import SpecDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import AbsAccessor.Spec.\nRequire Import PSCIAux.Spec.\n\nLocal Open Scope Z_scope.\n\nSection Spec.\n\n Definition find_lock_map_target_rec_spec (rec: Pointer) (target: Z64) (adt: RData) : option RData :=\n   match target with\n   | VZ64 target =>\n     rely is_int64 target;\n     rely (peq (base rec) buffer_loc);\n     when gidx == ((buffer (priv adt)) @ (offset rec));\n     rely is_gidx gidx;\n     let gn := (gs (share adt)) @ gidx in\n     rely gtype gn =? GRANULE_STATE_REC;\n     rely g_inited (gro gn);\n     let idx1 := __mpidr_to_rec_idx target in\n     let idx2 := g_rec_idx (gro gn) in\n     rely is_int64 idx1; rely is_int64 idx2;\n     if idx1 =? idx2 then\n       rely (g_rec (gro gn) =? gidx);\n       when adt == query_oracle adt;\n       let gn := (gs (share adt)) @ gidx in\n       rely prop_dec (glock gn = None);\n       let g' := gn {glock: Some CPU_ID} in\n       Some adt {log: (EVT CPU_ID (ACQ gidx)) :: log adt} {share: (share adt) {gs: (gs (share adt)) # gidx == g'}}\n            {priv: (priv adt) {buffer: (buffer (priv adt)) # SLOT_REC_TARGET == (Some gidx)} {target_rec: SLOT_REC_TARGET}}\n     else\n       rely (g_tag (ginfo gn) =? GRANULE_STATE_REC);\n       rely (ref_accessible gn CPU_ID);\n       let rd_gidx := g_rec_rd (grec gn) in\n       let recl_gidx := g_rec_rec_list (grec gn) in\n       rely is_gidx rd_gidx; rely is_gidx recl_gidx;\n       rely prop_dec ((buffer (priv adt)) @ SLOT_REC_LIST = None);\n        when adt == (query_oracle adt);\n        let adt := adt {log: EVT CPU_ID (RECL recl_gidx idx1 GET_RECL) :: log adt} in\n        let grecl := (gs (share adt)) @ recl_gidx in\n        rely (gtype grecl =? GRANULE_STATE_REC_LIST);\n        let g_rec_gidx := (g_data (gnorm grecl)) @ idx1 in\n        if g_rec_gidx =? 0 then\n          Some adt {priv: (priv adt) {target_rec: 0}}\n        else\n          rely is_gidx g_rec_gidx;\n          when adt == query_oracle adt;\n          let e := EVT CPU_ID (ACQ g_rec_gidx) in\n          let adt := adt {log: e :: log adt} in\n          let gn_target := (gs (share adt)) @ g_rec_gidx in\n          rely prop_dec (glock gn_target = None);\n          let gn_target := gn_target {glock: Some CPU_ID} in\n          rely is_int (g_tag (ginfo gn_target));\n          rely is_gidx (g_rd (ginfo gn_target));\n          if g_tag (ginfo gn_target) =? GRANULE_STATE_REC then\n            if g_rd (ginfo gn_target) =? rd_gidx then\n              let adt := adt {share: (share adt) {gs: (gs (share adt)) # g_rec_gidx == gn_target}} in\n              when adt == query_oracle adt;\n              let gn_target := (gs (share adt)) @ g_rec_gidx in\n              rely (gtype gn_target =? g_tag (ginfo gn_target));\n              let e := EVT CPU_ID (RECL recl_gidx idx1 GET_RECL) in\n              rely (gtype ((gs (share adt)) @ recl_gidx) =? GRANULE_STATE_REC_LIST);\n              let g_rec_gidx' := (g_data (gnorm ((gs (share adt)) @ recl_gidx))) @ idx1 in\n              rely is_int g_rec_gidx';\n              if g_rec_gidx =? g_rec_gidx' then\n                Some adt {log: e :: log adt}\n                     {priv: (priv adt) {buffer: (buffer (priv adt)) # SLOT_REC_TARGET == (Some g_rec_gidx)} {target_rec: SLOT_REC_TARGET}}\n              else\n                let e' := EVT CPU_ID (REL g_rec_gidx gn_target) in\n                Some adt {share: (share adt) {gs: (gs (share adt)) # g_rec_gidx == (gn_target {glock: None})}}\n                     {log: e' :: e :: log adt} {priv: (priv adt) {target_rec: 0}}\n            else\n              rely (gtype gn_target =? g_tag (ginfo gn_target));\n              Some adt {log: EVT CPU_ID (REL g_rec_gidx gn_target) :: log adt}\n                  {priv: (priv adt) {target_rec: 0}}\n          else\n            rely (gtype gn_target =? g_tag (ginfo gn_target));\n            Some adt {log: EVT CPU_ID (REL g_rec_gidx gn_target) :: log adt}\n                 {priv: (priv adt) {target_rec: 0}}\n   end.\n\nEnd Spec.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RVIC2/Specs/find_lock_map_target_rec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891307678321, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.20322873907128533}}
{"text": "(** Verification of lock coupling template algorithm *)\n\nRequire Import lock.\nFrom iris.algebra Require Import excl auth gmap agree gset.\nFrom iris.heap_lang Require Export notation locations lang.\nFrom iris.base_logic.lib Require Export invariants.\nFrom iris.program_logic Require Export atomic.\nFrom iris.proofmode Require Import tactics.\nFrom iris.heap_lang Require Import proofmode notation par.\nFrom iris.bi.lib Require Import fractional.\nSet Default Proof Using \"All\".\nRequire Export inset_flows.\nRequire Import auth_ext.\n\n(** We use integers as keys. *)\nDefinition K := Z.\n\n(** Definitions of cameras used in the template verification *)\nSection Coupling_Cameras.\n\n  (* RA for authoritative flow interfaces over multisets of keys *)\n  Class flowintG Σ :=\n    FlowintG { flowint_inG :> inG Σ (authR (multiset_flowint_ur K)) }.\n  Definition flowintΣ : gFunctors := #[GFunctor (authR (multiset_flowint_ur K))].\n\n  Instance subG_flowintΣ {Σ} : subG flowintΣ Σ → flowintG Σ.\n  Proof. solve_inG. Qed.\n\n  (* RA for authoritative set of nodes *)\n  Class nodesetG Σ := NodesetG { nodeset_inG :> inG Σ (authR (gsetUR Node)) }.\n  Definition nodesetΣ : gFunctors := #[GFunctor (authR (gsetUR Node))].\n\n  Instance subG_nodesetΣ {Σ} : subG nodesetΣ Σ → nodesetG Σ.\n  Proof. solve_inG. Qed.\n\n  (* RA for pair of keysets and contents *)\n  Instance subG_keysetΣ {Σ} : subG (@keysetΣ K _ _) Σ → (@keysetG K _ _) Σ.\n  Proof. solve_inG. Qed.\n\n  (* RA for set of contents *)\n  Class contentG Σ :=\n    ContentG { content_inG :> inG Σ (authR (optionUR (exclR (gsetR K)))) }.\n  Definition contentΣ : gFunctors :=\n    #[GFunctor (authR (optionUR (exclR (gsetR K))))].\n\nEnd Coupling_Cameras.\n\n(** Verification of the template *)\nSection Coupling_Template.\n\n  Context `{!heapG Σ, !flowintG Σ, !nodesetG Σ, !(@keysetG K _ _) Σ, !contentG Σ} (N : namespace).\n  Notation iProp := (iProp Σ).\n\n  (** The code of the coupling template. *)\n\n  (* The following parameters are the implementation-specific helper functions\n   * assumed by the template. See GRASShopper files b+-tree.spl and\n   * hashtbl-give-up.spl for the concrete implementations. *)\n\n  Parameter allocRoot : val.\n  Parameter findNext : val.\n  Parameter decisiveOp : (dOp → val).\n  Parameter alloc : val.\n\n  Definition create : val :=\n    λ: <>,\n      let: \"r\" := allocRoot #() in\n      \"r\".\n\n  Definition traverse : val :=\n    rec: \"tr\" \"p\" \"n\" \"k\" :=\n      match: Fst (findNext \"n\" \"k\") with\n        NONE => ((\"p\", \"n\"), Snd (findNext \"n\" \"k\"))\n      | SOME \"n'\" =>\n        lockNode \"n'\";; unlockNode \"p\";; \"tr\" \"n\" \"n'\" \"k\"\n      end.\n\n  Definition CSS_insertOp (root: Node) : val :=\n    λ: \"k\",\n    lockNode #root;;\n    let: \"n0\" := Fst (findNext #root \"k\") in\n    match: \"n0\" with\n      NONE => \"\"\n    | SOME \"n0\" =>\n      lockNode \"n0\";;\n      let: \"tr_res\" := traverse #root \"n0\" \"k\" in\n      let: \"b\" := Snd \"tr_res\" in\n      if: \"b\" then\n        #false\n      else\n        let: \"pn\" := Fst \"tr_res\" in\n        let: \"p\" := Fst \"pn\" in\n        let: \"n\" := Snd \"pn\" in\n        let: \"m\" := alloc #() in\n        let: \"res\" := (decisiveOp insertOp) \"p\" \"n\" \"k\" in\n        unlockNode \"p\";; unlockNode \"n\";; \"res\" end.\n\n  (** Assumptions on the implementation made by the template proofs.\n   * Matching definitions can be found in GRASShopper file list-coupling.spl *)\n\n  (* The node predicate is specific to each template implementation. *)\n  Parameter node : Node → Node → multiset_flowint_ur K → gset K → iProp.\n\n  (* The following assumption is justified by the fact that GRASShopper uses a\n   * root-order separation logic. *)\n  Parameter node_timeless_proof : ∀ root n I C, Timeless (node root n I C).\n  Instance node_timeless root n I C: Timeless (node root n I C).\n  Proof. apply node_timeless_proof. Qed.\n\n  (* Spatial part of node predicate. *)\n  Parameter hrepSpatial : Node → iProp.\n\n  (* The node-local invariant.\n   * See list-coupling.spl for the corresponding GRASShopper definition.*)\n  (* TODO there's a slight discrepancy between this and grasshopper. *)\n  Definition nodeinv root n (In : multiset_flowint_ur K) Cn : Prop :=\n    domm In = {[n]}\n    ∧ Cn ⊆ keyset K In n\n    ∧ (∀ k : K, default 0 (inf In n !! k) ≤ 1)\n    ∧ (n = root → ∀ k1 : K, k1 ∈ KS → in_outsets K k1 In).\n\n  (* The following hypotheses are proved as GRASShopper lemmas in\n   * list-coupling.spl *)\n  Hypothesis node_implies_nodeinv : ∀ root n In C,\n    ⌜✓In⌝ -∗ node root n In C -∗ ⌜nodeinv root n In C⌝.\n\n  Hypothesis node_sep_star: ∀ root n In In' C C',\n    node root n In C -∗ node root n In' C' -∗ False.\n\n  Lemma successor_not_root : ∀ (I I1 I2 I3 : flowintT) C root n k,\n      globalinv K root I →\n      I = I1 ⋅ I2 ⋅ I3 →\n      k ∈ outset K I1 n →\n      k ∈ KS →\n      nodeinv root n I2 C →\n      n ≠ root.\n  Proof.\n    intros ? ? ? ? ? ? ? ? GI IDef k_in_out1 k_in_KS NI.\n    destruct (decide (n = root)).\n    destruct GI as (VI & root_in_I & I_closed & I_inf_out).\n    rewrite <- cmra_assoc in IDef.\n    (*unfold op, cmra_op, ucmra_cmraR, multiset_flowint_ur, flowintUR, ucmra_op in IDef.*)\n    rewrite IDef in VI.\n    pose proof (intComp_valid_proj1 _ _ VI) as V1.\n    pose proof (intComp_valid_proj2 _ _ VI) as V23.\n    pose proof (intComp_unfold_inf_1 _ _ VI n) as inf_I1.\n    pose proof (intComp_unfold_inf_1 _ _ V23) as inf_I2.\n    destruct NI as (domm_I2 & _ & inf_bound & _).\n    assert (n ∈ domm I2 ∪ domm I3) as n_in_I23 by set_solver.\n    pose proof (intComp_unfold_inf_2 _ _ VI n) as inf_I23.\n    rewrite intComp_dom in inf_I23.\n    apply inf_I23 in n_in_I23 as n_inf_I23.\n    unfold cmra_op, flowintRA, cmra_car, K_multiset at 5, K_multiset at 5 in n_inf_I23.\n    pose proof (I_inf_out k k_in_KS) as root_out_k.\n    assert (default 0 (inf I n !! k) ≠ 0).\n    rewrite e.\n    unfold inset, dom_ms in root_out_k.\n    apply nzmap_elem_of_dom in root_out_k.\n    unfold lookup, nzmap_lookup.\n    pose proof (nzmap_is_wf (inf I root)) as inf_root_wf.\n    pose proof (nzmap_lookup_wf _ k inf_root_wf).\n    destruct (inf I root).\n    simpl in root_out_k.\n    unfold is_Some in root_out_k.\n    destruct root_out_k as [x root_out_k].\n    unfold lookup, nzmap_lookup in root_out_k.\n    rewrite root_out_k.\n    simpl in H0.\n    simpl.\n    naive_solver.\n    pose proof (lookup_op _ _ (inf I n) (out I1 n) k) as inf_I23_def.\n\n    rewrite IDef in inf_I23_def.\n    unfold cmra_op, flowintRA, cmra_car, nzmap_total_lookup in inf_I23_def.\n    unfold ccm_op, lift_ccm in n_inf_I23.\n\n    unfold K_multiset_ccm at 4, lift_ccm in n_inf_I23.\n    rewrite <- n_inf_I23 in inf_I23_def.\n    unfold cmra_op, flowintRA, cmra_car in IDef.\n    rewrite <- IDef in inf_I23_def.\n\n    assert (n ∈ domm I2) as n_in_I2 by set_solver.\n    pose proof (inf_I2 n n_in_I2) as n_inf_I2.\n    pose proof (lookup_op _ _ (inf (I2 ⋅ I3) n) (out I3 n) k) as inf_I2_def.\n    unfold cmra_op, flowintRA, cmra_car, nzmap_total_lookup in inf_I2_def.\n    unfold K_multiset_ccm, ccmop, ccm_op, lift_ccm in n_inf_I2.\n    setoid_rewrite <- n_inf_I2 in inf_I2_def.\n    setoid_rewrite inf_I23_def in inf_I2_def.\n\n    assert (default 0 (out I1 n !! k) ≠ 0).\n    unfold outset, dom_ms in k_in_out1.\n    apply nzmap_elem_of_dom in k_in_out1.\n    pose proof (nzmap_is_wf (out I1 n)) as out_n_wf.\n    pose proof (nzmap_lookup_wf _ k out_n_wf).\n    destruct (out I1 n).\n    simpl in k_in_out1.\n    unfold is_Some in k_in_out1.\n    destruct k_in_out1 as [x k_in_out1].\n    rewrite k_in_out1.\n    simpl in H0.\n    simpl.\n    naive_solver.\n    unfold ccmunit, ccmop, ccm_unit, ccm_op, nat_ccm, nat_unit, nat_op in inf_I23_def.\n    unfold ccmunit, ccmop, ccm_unit, ccm_op, nat_ccm, nat_unit, nat_op in inf_I2_def.\n    pose proof (inf_bound k).\n    remember (inf I2 n !! k) as x2.\n    unfold K_multiset at 1, nat_ccm, nat_unit, nat_op in Heqx2.\n    setoid_rewrite <- Heqx2 in inf_I2_def.\n    remember (inf I n !! k) as x.\n    unfold K_multiset at 1, nat_ccm, nat_unit, nat_op in Heqx.\n    rewrite <- Heqx in inf_I2_def.\n    remember (out I1 n !! k) as x1.\n    unfold K_multiset at 1, nat_ccm, nat_unit, nat_op in Heqx1.\n    rewrite <- Heqx1 in inf_I2_def.\n    lia.\n    all: trivial.\n  Qed.\n\n\n  (** Helper functions specs *)\n\n  (* The following functions are proved for each implementation in GRASShopper\n   * (see list-coupling.spl) *)\n\n  Parameter allocRoot_spec :\n      ⊢ ({{{ True }}}\n           allocRoot #()\n         {{{ (r: Node) (Ir: multiset_flowint_ur K) (ks: nzmap K nat),\n             RET #r; node r r Ir ∅ ∗ (lockLoc r) ↦ #false \n                     ∗ ⌜Ir = int {| infR := {[r := ks]}; outR := ∅ |}⌝\n                     ∗ ⌜dom (gset K) ks = KS⌝\n                     }}})%I.\n\n  (* TODO ghp spec doesn't match *)\n  Parameter findNext_spec : ∀ (n: Node) (k: K) (In : multiset_flowint_ur K) (C: gset K) root,\n     ⊢ ({{{ node root n In C ∗ ⌜in_inset K k In n⌝ }}}\n           findNext #n #k\n       {{{ (succ: bool) (np: Node) (res: bool),\n              RET (match succ with true => ((SOMEV #np), #res) | false => (NONEV, #res) end);\n                  node root n In C ∗ ⌜res ↔ k ∈ C⌝\n               ∗ (match succ with true  => ⌜in_outset K k In np⌝\n                                | false => ⌜¬in_outsets K k In⌝ ∗ ⌜n ≠ root⌝ end) }}})%I.\n\n  Parameter decisiveOp_insert_spec : ∀ root (p n m: Node) (k: K) (Ip In: multiset_flowint_ur K) (Cp Cn: gset K),\n     ⊢ ({{{       ⌜k ∈ KS⌝\n                ∗ ⌜keyset K Ip p ## keyset K In n⌝\n                ∗ node root p Ip Cp\n                ∗ node root n In Cn\n                ∗ hrepSpatial m\n                ∗ ⌜✓ (Ip ⋅ In)⌝\n                ∗ ⌜out (Ip ⋅ In) m = 0%CCM⌝\n                ∗ ⌜m ≠ root⌝\n                ∗ ⌜n ≠ root⌝\n                ∗ ⌜k ∉ Cn⌝\n                ∗ ⌜in_outset K k Ip n⌝\n                ∗ ⌜in_inset K k Ip p⌝\n                ∗ ⌜¬in_outsets K k In⌝ }}}\n\n           decisiveOp insertOp #p #n #k\n\n       {{{ (Cp1 Cn1 Cm1: gset K) (Ip1 In1 Im1: flowintUR K_multiset) (res: bool), RET  #res;\n                  node root p Ip1 Cp1\n                ∗ node root n In1 Cn1\n                ∗ node root m Im1 Cm1\n                ∗ ⌜Ψ insertOp k (Cp ∪ Cn) (Cp1 ∪ Cn1 ∪ Cm1) res⌝\n                ∗ ⌜contextualLeq _ (Ip ⋅ In) (Ip1 ⋅ In1 ⋅ Im1)⌝\n                ∗ ⌜inf (Ip1 ⋅ In1 ⋅ Im1) m = 0%CCM⌝\n                ∗ ⌜keyset K Ip1 p ## keyset K In1 n⌝\n                ∗ ⌜keyset K Ip1 p ## keyset K Im1 m⌝\n                ∗ ⌜keyset K Im1 m ## keyset K In1 n⌝\n                ∗ ⌜keyset K Ip1 p ∪ keyset K In1 n ∪ keyset K Im1 m = keyset K Ip p ∪ keyset K In n⌝ }}})%I.\n\n  (*TODO changed back to original spec*)\n  Parameter alloc_spec :\n     ⊢ ({{{ True }}}\n           alloc #()\n       {{{ (m: Node) (l:loc), RET #m; hrepSpatial m ∗ ⌜lockLoc m = l⌝ ∗ l ↦ #false }}})%I.\n\n\n  (** The concurrent search structure invariant *)\n\n  Definition inFP γ_f n : iProp := ∃ (N: gset Node), own γ_f (◯ N) ∗ ⌜n ∈ N⌝.\n\n  Definition nodePred γ_I γ_k root n In Cn  :iProp :=\n                      node root n In Cn\n                    ∗ own γ_k (◯ prod (keyset K In n, Cn))\n                    ∗ own γ_I (◯ In)\n                    ∗ ⌜domm In = {[n]}⌝.\n\n  Definition nodeFull γ_I γ_k root n : iProp :=\n    (∃ (b: bool) In Cn,\n        (lockR b n (nodePred γ_I γ_k root n In Cn))).\n\n  Definition globalGhost γ_I γ_f γ_k γ_c root I C : iProp :=\n                    own γ_I (● I)\n                  ∗ ⌜globalinv K root I⌝\n                  ∗ own γ_k (● prod (KS, C))\n                  ∗ own γ_f (● domm I)\n                  ∗ own γ_c (● (Some (Excl C))).\n\n  Definition CSSi γ_I γ_f γ_k γ_c root I C : iProp :=\n                    globalGhost γ_I γ_f γ_k γ_c root I C\n                  ∗ ([∗ set] n ∈ (domm I), nodeFull γ_I γ_k root n).\n\n  Definition CSS γ_I γ_f γ_k γ_c root : iProp := ∃ I C, CSSi γ_I γ_f γ_k γ_c root I C.\n\n  Definition css_inv γ_I γ_f γ_k γ_c root : iProp := inv N (CSS γ_I γ_f γ_k γ_c root).\n\n  Definition css_cont (γ_c: gname) (C: gset K) : iProp := own γ_c (◯ (Excl' C)).\n\n  Instance CSS_timeless  γ_I γ_f γ_k γ_c root :\n    Timeless (CSS γ_I γ_f γ_k γ_c root).\n  Proof.\n    rewrite /CSS. apply bi.exist_timeless; intros.\n    apply bi.exist_timeless; intros.\n    repeat apply bi.sep_timeless; try apply _.\n    apply big_sepS_timeless.\n    intros. apply bi.exist_timeless. intros.\n    apply bi.exist_timeless. intros.\n    apply bi.exist_timeless. intros.\n    apply bi.sep_timeless; try apply _.\n    destruct x2; try apply _.\n  Qed.\n\n  (** Some useful lemmas *)\n\n  Lemma auth_agree γ xs ys :\n  own γ (● (Excl' xs)) -∗ own γ (◯ (Excl' ys)) -∗ ⌜xs = ys⌝.\n  Proof.\n    iIntros \"Hγ● Hγ◯\". by iDestruct (own_valid_2 with \"Hγ● Hγ◯\")\n      as %[<-%Excl_included%leibniz_equiv _]%auth_both_valid_discrete.\n  Qed.\n\n\n  Lemma flowint_update_result γ I I_n I_n' x :\n    ⌜flowint_update_P K_multiset I I_n I_n' x⌝ ∗ own γ x -∗\n    ∃ I', ⌜contextualLeq K_multiset I I'⌝\n          ∗ ⌜∃ I_o, I = I_n ⋅ I_o ∧ I' = I_n' ⋅ I_o⌝\n          ∗ own γ (● I' ⋅ ◯ I_n').\n  Proof.\n    unfold flowint_update_P.\n    case_eq (view_auth_proj x); last first.\n    - intros Hx. iIntros \"(% & ?)\". iExFalso. done.\n    - intros [q a] Hx.\n      iIntros \"[HI' Hown]\". iDestruct \"HI'\" as %HI'.\n      destruct HI' as [I' HI'].\n      destruct HI' as [Hagree [Hq [HIn [Hcontxl HIo]]]].\n      iExists I'.\n      iSplit. by iPureIntro.\n      iSplit. by iPureIntro. destruct x.\n      simpl in Hx. simpl in HIn.\n      rewrite Hx. rewrite <-HIn.\n      rewrite Hq Hagree.\n      assert (● I' ⋅ ◯ I_n' = View (Some (1%Qp, to_agree I')) I_n') as H'.\n      { rewrite /(● I' ⋅ ◯ I_n'). unfold cmra_op.\n        simpl. unfold view_op_instance. simpl.\n        assert (ε ⋅ I_n' = I_n') as H'. by rewrite left_id.\n        rewrite H'. unfold op, cmra_op. by simpl. }   \n      by iEval (rewrite H').\n  Qed.\n\n  Lemma inFP_domm γ_I γ_f γ_k γ_c root I C n  :\n    inFP γ_f n -∗ CSSi γ_I γ_f γ_k γ_c root I C -∗ ⌜n ∈ domm I⌝.\n  Proof.\n    iIntros \"#Hfp Hcss\".\n    iDestruct \"Hcss\" as \"((HI & Hglob & Hks & Hdom & Hcont) & Hbigstar)\".\n    iDestruct \"Hfp\" as (N0) \"(#Hdom' & n_in_N)\". iDestruct \"n_in_N\" as %n_in_N.\n    iPoseProof ((auth_own_incl γ_f (domm I) N0) with \"[$]\") as \"#N_incl\".\n    iDestruct \"N_incl\" as %N_incl.\n    apply gset_included in N_incl.\n    iPureIntro. set_solver.\n  Qed.\n\n  Lemma int_domm γ_I γ_f γ_k γ_c root I C n In :\n    own γ_I (◯ In) -∗ ⌜domm In = {[n]}⌝ -∗ CSSi γ_I γ_f γ_k γ_c root I C -∗ ⌜n ∈ domm I⌝.\n  Proof.\n    iIntros \"Hi Dom_In Hcss\".\n    iDestruct \"Dom_In\" as %Dom_In.\n    iDestruct \"Hcss\" as \"((HI & Hglob & Hks & Hdom) & Hbigstar)\".\n    iPoseProof ((auth_own_incl γ_I (I) (In)) with \"[$]\") as \"%\".\n    rename H0 into I_incl. destruct I_incl as [Io I_incl].\n    iPoseProof (own_valid with \"HI\") as \"%\". rename H0 into Valid_I.\n    iPureIntro. rewrite I_incl. rewrite flowint_comp_fp.\n    rewrite Dom_In. set_solver. rewrite <- I_incl.\n    by apply auth_auth_valid.\n  Qed.\n\n  Lemma node_nodeFull_equal γ_I γ_k root n In Cn :\n    node root n In Cn -∗ nodeFull γ_I γ_k root n\n    -∗ ((lockR true n (∃ In Cn, nodePred γ_I γ_k root n In Cn))∗ (node root n In Cn)).\n  Proof.\n    iIntros \"Hn Hnf\".\n    iDestruct \"Hnf\" as (b In' Cn') \"(Hlock & Hnp)\". destruct b.\n    - (* Case n locked *)\n      iFrame \"∗\".\n    - (* Case n unlocked: impossible *)\n      iDestruct \"Hnp\" as \"(Hn' & _)\".\n      iExFalso. iApply (node_sep_star root n In In' with \"[$] [$]\").\n  Qed.\n\n  Lemma CSS_unfold γ_I γ_f γ_k γ_c root I C n :\n    CSSi γ_I γ_f γ_k γ_c root I C -∗ ⌜n ∈ domm I⌝\n    -∗ (globalGhost γ_I γ_f γ_k γ_c root I C ∗ nodeFull γ_I γ_k root n\n        ∗ (∀ C',\n           globalGhost γ_I γ_f γ_k γ_c root I C' ∗ nodeFull γ_I γ_k root n\n           -∗ CSSi γ_I γ_f γ_k γ_c root I C')).\n  Proof.\n    iIntros \"Hcss %\".\n    iDestruct \"Hcss\" as \"((HI & Hglob & Hks & Hdom) & Hbigstar)\".\n    rewrite (big_sepS_elem_of_acc _ (domm I) n); last by eauto.\n    iDestruct \"Hbigstar\" as \"(Hn & Hbigstar)\". iFrame \"∗\".\n    iIntros (C') \"((HI & Hglob & Hks & Hdom) & H)\".\n    iFrame \"∗\". by iApply \"Hbigstar\".\n  Qed.\n\n  Lemma ghost_snapshot_fp γ_f (Ns: gset Node) n:\n    ⊢ own γ_f (● Ns) -∗ ⌜n ∈ Ns⌝ ==∗ own γ_f (● Ns) ∗ inFP γ_f n.\n  Proof.\n    iIntros.\n    iMod (own_update γ_f (● Ns) (● Ns ⋅ ◯ Ns) with \"[$]\")\n      as \"H\".\n    { apply auth_update_frac_alloc. apply gset_core_id. done. }\n    iDestruct \"H\" as \"(Haa & Haf)\". iFrame. iModIntro.\n    iExists Ns. by iFrame.\n  Qed.\n\n  (* root is in footprint *)\n  Lemma ghost_update_root γ_I γ_f γ_k γ_c root :\n    ⊢ CSS γ_I γ_f γ_k γ_c root\n      ==∗ CSS γ_I γ_f γ_k γ_c root ∗ inFP γ_f root.\n  Proof.\n    iIntros \"Hcss\".\n    (* Open CSS to get r ∈ domm I *)\n    iDestruct \"Hcss\" as (I C) \"((HI & #Hglob & Hks & Hdom & Hcont) & Hbigstar)\".\n    iDestruct \"Hglob\" as %Hglob.\n    assert (root ∈ domm I)%I as Hroot.\n    { apply globalinv_root_fp. done. }\n    (* Snapshot FP for inFP: *)\n    iMod (ghost_snapshot_fp γ_f (domm I) root with \"[$Hdom] [% //]\")\n        as \"(Hdom & #Hinfp)\".\n    iModIntro. iFrame \"Hinfp\".\n    iExists I, C. iFrame \"∗ %\".\n  Qed.\n\n  Lemma Ψ_key_present γ_k k n In (Cn C: gset K) :\n        ⌜true ↔ k ∈ Cn⌝ -∗ own γ_k (● prod (KS, C))\n                        -∗ own γ_k (◯ prod (keyset K In n, Cn))\n                        -∗ own γ_k (● prod (KS, C)) ∗ own γ_k (◯ prod (keyset K In n, Cn))\n                                                    ∗ ⌜Ψ insertOp k C C false⌝.\n  Proof.\n    iIntros \"H Hks Hkn\". iDestruct \"H\" as %Hres.\n    iPoseProof (own_valid with \"Hks\") as \"%\". rename H0 into Valid_ks_auth.\n    iPoseProof (own_valid with \"Hkn\") as \"%\". rename H0 into Valid_ks_frag.\n    iPoseProof ((auth_own_incl γ_k (prod (KS, C)) _) with \"[Hks Hkn]\") as \"%\".\n    iFrame. rename H0 into ks_incl.\n    rewrite auth_auth_valid in Valid_ks_auth *; intros Valid_ks_auth.\n    rewrite auth_frag_valid in Valid_ks_frag *; intros Valid_ks_frag.\n    pose proof (auth_ks_included (keyset K In n) KS Cn C Valid_ks_frag Valid_ks_auth ks_incl)\n                               as ks_incl_lemma.\n    iFrame. unfold Ψ. iPureIntro.\n    assert (k ∈ Cn). by apply Hres.\n    destruct ks_incl_lemma.\n    - destruct H1. subst C.\n      split; set_solver.\n    - destruct H1 as [a [b [_ [H1 _]]]].\n      split; set_solver.\n  Qed.\n\n (* TODO had to change to original implementation using lockLoc for now *)\n  Lemma node_lock_not_in_FP γ_I γ_f γ_k γ_c root I C n b :\n  lockLoc n ↦ #b -∗ CSSi γ_I γ_f γ_k γ_c root I C -∗ ⌜n ∉ domm I⌝.\n  Proof.\n    iIntros \"Hl Hcss\". iDestruct \"Hcss\" as \"(Hg & Hbigstar)\".\n    destruct (decide (n ∈ domm I)).\n    rewrite (big_sepS_elem_of_acc _ (domm I) n); last by eauto.\n    iDestruct \"Hbigstar\" as \"(Hn & Hbigstar)\". \n    iDestruct \"Hn\" as (b0 In Cn) \"(Hlockn & Hb)\".\n    iDestruct (mapsto_valid_2 with \"Hl Hlockn\") as \"%\". \n    exfalso. destruct H0. by compute in H0.\n    by iPureIntro.\n  Qed.\n\n  Lemma CSS_unfold_node_wand γ_I γ_f γ_k γ_c root I C n In Cn :\n    CSSi γ_I γ_f γ_k γ_c root I C\n    -∗ node root n In Cn -∗ ⌜n ∈ domm I⌝\n    -∗ (node root n In Cn\n        ∗ globalGhost γ_I γ_f γ_k γ_c root I C\n        ∗ (lockR true n (nodePred γ_I γ_k root n In Cn))\n        ∗ (∀ C',\n           globalGhost γ_I γ_f γ_k γ_c root I C' ∗ nodeFull γ_I γ_k root n\n           -∗ CSSi γ_I γ_f γ_k γ_c root I C')).\n  Proof.\n    iIntros \"Hcssi Hn %\".\n    iPoseProof (CSS_unfold with \"[$] [%]\") as \"(Hg & Hnf & Hcss')\"; try done.\n    iPoseProof (node_nodeFull_equal with \"[$] [$]\")\n      as \"(Hlock & Hn)\".\n    iFrame.\n  Qed.\n\n\n  (* ghost update for traverse inductive case *)\n  Lemma ghost_update_step γ_I γ_f γ_k γ_c root n In Cn k n' :\n    ⊢ CSS γ_I γ_f γ_k γ_c root\n      -∗ nodePred γ_I γ_k root n In Cn\n      -∗ ⌜in_inset K k In n⌝\n      -∗ ⌜in_outset K k In n'⌝\n      ==∗ CSS γ_I γ_f γ_k γ_c root ∗ nodePred γ_I γ_k root n In Cn\n      ∗ inFP γ_f n'.\n  Proof.\n    iIntros \"Hcss Hnp % %\".\n    iDestruct \"Hnp\" as \"(Hn & HkIn & HIn & %)\".\n    iDestruct \"Hcss\" as (I C) \"Hcssi\".\n    iPoseProof (int_domm with \"[$] [% //] [$]\") as \"%\".\n    iPoseProof (CSS_unfold with \"[$] [%]\") as \"(Hg & Hnf & Hcss')\"; try done.\n    iDestruct \"Hg\" as \"(HI & Hglob & Hks & Hdom & Hc)\".\n    (* In ≼ I *)\n    iPoseProof ((auth_own_incl γ_I I In) with \"[$]\")\n      as (Io) \"#incl\".\n    iDestruct \"incl\" as %incl. iDestruct \"Hglob\" as %Hglob.\n    (* Some validities we'll use later *)\n    iPoseProof (own_valid with \"HI\") as \"%\".\n    iPoseProof (own_valid with \"HIn\") as \"%\".\n    (* Prove the preconditions of ghost_snapshot_fp *)\n    assert (n' ∈ domm Io).\n    { apply (flowint_step I In Io k n'); try done.\n      rewrite auth_auth_valid in H4 *. done.\n      unfold globalinv in Hglob.\n      destruct Hglob as (_ & _ & cI & _). done.\n    }\n    assert (domm I = domm In ∪ domm Io). {\n      rewrite incl. rewrite flowint_comp_fp. done.\n      rewrite <- incl. by apply auth_auth_valid.\n    }\n    assert (n ∈ domm I). by set_solver.\n    assert (n' ∈ domm I). by set_solver.\n    (* Take snapshot of fp to get inFP n' *)\n    iMod (ghost_snapshot_fp γ_f (domm I) n' with \"[$Hdom] [% //]\")\n        as \"(Hdom & #Hinfp')\".\n    iModIntro. iFrame \"Hinfp'\".\n    iSplitL \"Hcss' Hnf HI Hks Hdom Hc\". iExists I, C.\n    iApply \"Hcss'\". iFrame \"∗ %\".\n    iFrame. iFrame \"∗ %\".\n  Qed.\n\n\n  Lemma extract_from_nodeinv root p Ip Cp :\n        ⌜✓ Ip⌝ -∗ node root p Ip Cp -∗ ⌜Cp ⊆ keyset K Ip p ∧ domm Ip = {[p]}⌝.\n  Proof.\n    iIntros \"% Hnode\".\n    iPoseProof (node_implies_nodeinv with \"[//] [$]\") as \"H\".\n    iDestruct \"H\" as %nodeinv_p.\n    unfold nodeinv in nodeinv_p. destruct nodeinv_p as [Hdom [nodeinv_p ]]. by iPureIntro.\n  Qed.\n\n  Lemma ghost_update_cssOp_keyset γ_k root p n m Ip In Ip' In' Im' Cp Cn Cp' Cn' Cm' C k res :\n      ⊢  ⌜contextualLeq K_multiset (Ip ⋅ In) (Ip' ⋅ In' ⋅ Im')⌝\n      ∗ ⌜Cp ## Cn⌝\n      ∗ ⌜keyset K Ip p ## keyset K In n⌝\n      ∗ ⌜Cp ⊆ keyset K Ip p⌝\n      ∗ ⌜Cn ⊆ keyset K In n⌝\n      ∗ ⌜keyset K Ip' p ## keyset K In' n⌝\n      ∗ ⌜keyset K Ip' p ## keyset K Im' m⌝\n      ∗ ⌜keyset K Im' m ## keyset K In' n⌝\n      ∗ ⌜keyset K Ip' p ∪ keyset K In' n ∪ keyset K Im' m = keyset K Ip p ∪ keyset K In n⌝\n      ∗ ⌜k ∈ keyset K In n⌝\n      ∗ ⌜k ∈ KS⌝\n      ∗ node root p Ip' Cp'\n      ∗ node root n In' Cn'\n      ∗ node root m Im' Cm'\n      ∗ own γ_k (◯ prod (keyset K In n, Cn) ⋅ ◯ prod (keyset K Ip p, Cp))\n      ∗ own γ_k (● prod (KS, C))\n      ∗ ⌜Ψ insertOp k (Cp ∪ Cn) (Cp' ∪ Cn' ∪ Cm') res⌝\n      ==∗ ∃ C', ⌜Ψ insertOp k C C' res⌝\n              ∗ node root p Ip' Cp'\n              ∗ node root n In' Cn'\n              ∗ node root m Im' Cm'\n              ∗ own γ_k (◯ prod (keyset K Ip' p, Cp'))\n              ∗ own γ_k (◯ prod (keyset K In' n, Cn'))\n              ∗ own γ_k (◯ prod (keyset K Im' m, Cm'))\n              ∗ own γ_k (● prod (KS, C'))\n              ∗ ⌜domm Ip' = {[p]}⌝\n              ∗ ⌜domm In' = {[n]}⌝\n              ∗ ⌜domm Im' = {[m]}⌝.\n  Proof.\n    iIntros \"(ContLeq & Disj_pn & Disj_ks_pn & Sub_p & Sub_n & Disj_ks_pn' & Disj_ks_pm'\n               & Disj_ks_mn' & ks_eq & k_in_ks & k_in_KS & Hnodep & Hnoden & Hnodem & Hkspn' & HKS & #HΨ)\".\n    iDestruct \"ContLeq\" as %ContLeq.\n    iDestruct \"Disj_pn\" as %Disj_pn.\n    iDestruct \"Disj_ks_pn\" as %Disj_ks_pn.\n    iDestruct \"Sub_p\" as %Sub_p.\n    iDestruct \"Sub_n\" as %Sub_n.\n    iDestruct \"Disj_ks_pn'\" as %Disj_ks_pn'.\n    iDestruct \"Disj_ks_pm'\" as %Disj_ks_pm'.\n    iDestruct \"Disj_ks_mn'\" as %Disj_ks_mn'.\n    iDestruct \"ks_eq\" as %ks_eq.\n    iDestruct \"k_in_ks\" as %k_in_ks.\n    iDestruct \"k_in_KS\" as %k_in_KS.\n    unfold contextualLeq in ContLeq. destruct ContLeq as [Valid_Ipn [Valid_Ipnm' ContLeq]].\n    iPoseProof (extract_from_nodeinv with \"[] [$Hnodep]\") as \"%\".\n    { iPureIntro. by repeat apply cmra_valid_op_l in Valid_Ipnm'. }\n    destruct H0 as [Sub_p' Dom_Ip'].\n    iPoseProof (extract_from_nodeinv with \"[] [$Hnoden]\") as \"%\".\n    { iPureIntro. by apply cmra_valid_op_l, cmra_valid_op_r in Valid_Ipnm'. }\n    destruct H0 as [Sub_n' Dom_In'].\n    iPoseProof (extract_from_nodeinv with \"[] [$Hnodem]\") as \"%\".\n    { iPureIntro. by apply cmra_valid_op_r in Valid_Ipnm'. }\n    destruct H0 as [Sub_m' Dom_Im'].\n    assert (Cp' ## Cn') as Disj_pn'. { clear -Sub_p' Sub_n' Disj_ks_pn'. set_solver. }\n    assert (Cn' ## Cm') as Disj_nm'. { clear -Sub_m' Sub_n' Disj_ks_mn'. set_solver. }\n    assert (Cm' ## Cp') as Disj_pm'. { clear -Sub_p' Sub_m' Disj_ks_pm'. set_solver. }\n    iEval (rewrite -auth_frag_op) in \"Hkspn'\".\n    assert (prod (keyset K Ip' p, Cp') ⋅ prod (keyset K In' n, Cn') ⋅ prod (keyset K Im' m, Cm')\n                   = prod (keyset K Ip' p ∪ keyset K In' n ∪ keyset K Im' m, Cp' ∪ Cn' ∪ Cm')).\n    { unfold op, prodOp. repeat case_decide; try done. exfalso. try apply H7. set_solver by eauto.\n      exfalso. apply H6. clear - Disj_ks_pn' Disj_ks_pm' Disj_ks_mn'. set_solver by eauto.\n      exfalso. apply H4. set_solver by eauto. }\n    assert (◯ (prod (keyset K Ip' p, Cp') ⋅ prod (keyset K In' n, Cn') ⋅ prod (keyset K Im' m, Cm'))\n                   = ◯ (prod (keyset K Ip' p ∪ keyset K In' n ∪ keyset K Im' m, Cp' ∪ Cn' ∪ Cm'))).\n    { rewrite H0. reflexivity. }\n    assert ((prod (keyset K Ip p, Cp) ⋅ prod (keyset K In n, Cn))\n                    = prod (keyset K Ip p ∪ keyset K In n, Cp ∪ Cn)).\n    { unfold op, prodOp. repeat case_decide; try done. }\n    iMod ((ghost_update_keyset γ_k insertOp k (Cp ∪ Cn) (Cp' ∪ Cn' ∪ Cm') res\n                   (keyset K Ip p ∪ keyset K In n) C) with \"[HKS Hkspn']\") as \"Hgks\".\n    { iEval (rewrite comm) in \"Hkspn'\". iEval (rewrite H2) in \"Hkspn'\".\n      iFrame \"∗ # %\". iPureIntro. split.\n      rewrite <-ks_eq. clear -Sub_p' Sub_n' Sub_m'. set_solver.\n      clear -k_in_ks. set_solver. }\n    iDestruct \"Hgks\" as (C') \"(#HΨ' & HKS & H)\". iEval (rewrite <-ks_eq) in \"H\".\n    iAssert (own γ_k (◯ (prod (keyset K Ip' p, Cp') ⋅ prod (keyset K In' n, Cn')\n                                                    ⋅ prod (keyset K Im' m, Cm'))))\n            with \"[H]\" as \"Hv\". { iEval (rewrite H1). done. }\n    iDestruct \"Hv\" as \"((Hksp' & Hksn') & Hksm')\".\n    iModIntro. iExists C'. iFrame \"∗ # %\".\n  Qed.\n\n  Lemma ghost_update_cssOp_interface γ_I γ_f root p n m (I Ip In Ip' In' Im': multiset_flowint_ur K) :\n      ⊢ ⌜m ∉ domm I⌝\n      ∗ ⌜globalinv K root I⌝\n      ∗ ⌜contextualLeq K_multiset (Ip ⋅ In) (Ip' ⋅ In' ⋅ Im')⌝\n      ∗ own γ_I (● I)\n      ∗ own γ_I (◯ (Ip ⋅ In))\n      ∗ own γ_f (● domm I)\n      ∗ ⌜domm Ip = {[p]}⌝\n      ∗ ⌜domm In = {[n]}⌝\n      ∗ ⌜domm Ip' = {[p]}⌝\n      ∗ ⌜domm In' = {[n]}⌝\n      ∗ ⌜domm Im' = {[m]}⌝\n      ∗ ⌜inf (Ip' ⋅ In' ⋅ Im') m = 0%CCM⌝\n      ==∗ ∃ I', ⌜contextualLeq K_multiset I I'⌝\n              ∗ ⌜globalinv K root I'⌝\n              ∗ own γ_I (● I')\n              ∗ own γ_I (◯ Ip')\n              ∗ own γ_I (◯ In')\n              ∗ own γ_I (◯ Im')\n              ∗ own γ_f (● domm I')\n              ∗ ⌜domm I' = domm I ∪ {[m]}⌝\n              ∗ ⌜domm I' ∖ {[m]} = domm I⌝.\n  Proof.\n    iIntros \"(m_not_in_I & Hglob & ContLeq & HI & HIpn &\n                          Hdomm & Dom_Ip & Dom_In & Dom_Ip' & Dom_In' & Dom_Im' & Hinf)\".\n    iDestruct \"m_not_in_I\" as %m_not_in_I.\n    iDestruct \"Hglob\" as %Hglob.\n    iDestruct \"ContLeq\" as %ContLeq.\n    iDestruct \"Dom_Ip\" as %Dom_Ip.\n    iDestruct \"Dom_In\" as %Dom_In.\n    iDestruct \"Dom_Ip'\" as %Dom_Ip'.\n    iDestruct \"Dom_In'\" as %Dom_In'.\n    iDestruct \"Dom_Im'\" as %Dom_Im'.\n    iDestruct \"Hinf\" as %m_inf.\n    iCombine \"HI\" \"HIpn\" as \"Hownint\".\n    iPoseProof (own_valid with \"Hownint\") as \"%\". rename H0 into Valid_I_pn.\n    apply auth_both_valid_discrete in Valid_I_pn. destruct Valid_I_pn as [Ipn_incl_I Valid_I].\n    destruct Ipn_incl_I as [Iz Ipn_incl_I].\n    iDestruct \"Hownint\" as \"[HI H']\".\n    destruct ContLeq as (Valid_Ipn & Valid_Ipnm & Hsub & Hinf_pn & Hout).\n    assert (domm (Ip' ⋅ In' ⋅ Im') = domm Ip' ∪ domm In' ∪ domm Im') as Dom_eq.\n    { repeat rewrite (flowint_comp_fp); try done. by apply cmra_valid_op_l in Valid_Ipnm. }\n    rewrite Dom_Ip' Dom_In' Dom_Im' in Dom_eq.\n    assert (m ∉ domm Iz) as m_not_in_Iz.\n    { apply leibniz_equiv in Ipn_incl_I.\n      rewrite Ipn_incl_I in m_not_in_I.\n      rewrite (flowint_comp_fp) in m_not_in_I.\n      clear - m_not_in_I. set_solver.\n      apply leibniz_equiv_iff in Ipn_incl_I.\n      rewrite <-Ipn_incl_I. done. }\n    unfold globalinv in Hglob. destruct Hglob as (_ & Hgroot & Hgout & Hgin).\n    assert (out Iz m = 0%CCM) as out_Iz_zero.\n    {\n      apply (intComp_out_zero (Ip⋅In) Iz m). by rewrite <-Ipn_incl_I.\n      rewrite <-Ipn_incl_I. done. rewrite <-Ipn_incl_I. apply nzmap_eq.\n      intros km. pose proof (Hgout km m) as km_out.\n      unfold outset, dom_ms in km_out.\n      rewrite (nzmap_elem_of_dom_total) in km_out *; intros km_out.\n      apply dec_stable in km_out. rewrite km_out.\n      by rewrite nzmap_lookup_empty.\n    }\n    iMod (own_updateP (flowint_update_P K_multiset I (Ip ⋅ In) (Ip' ⋅ In' ⋅ Im')) γ_I\n                            (● I ⋅ ◯ (Ip ⋅ In)) with \"[HI H']\") as (Io) \"H0\".\n    {\n      rewrite Ipn_incl_I.\n      apply (flowint_update K_multiset (Iz) (Ip ⋅ In) (Ip' ⋅ In' ⋅ Im')).\n      repeat split; try done. apply leibniz_equiv in Ipn_incl_I.\n      assert (Valid2_I := Valid_I). rewrite Ipn_incl_I in Valid_I.\n      apply intComposable_valid in Valid_I. unfold intComposable in Valid_I.\n      destruct Valid_I as (_ & _ & Hdisj & _). rewrite flowint_comp_fp in Hdisj; last first.\n      done. rewrite Dom_Ip Dom_In in Hdisj. rewrite Dom_eq.\n      clear -Hdisj m_not_in_Iz. set_solver.\n      intros nf Hnf. assert (nf = m). rewrite Dom_eq in Hnf.\n      rewrite flowint_comp_fp in Hnf; try done. rewrite Dom_Ip Dom_In in Hnf.\n      clear -Hnf. set_solver. replace nf.\n      unfold out in out_Iz_zero. done.\n    }\n    { try repeat rewrite own_op; iFrame. }\n    iPoseProof ((flowint_update_result γ_I I (Ip ⋅ In) (Ip' ⋅ In' ⋅ Im'))\n                        with \"H0\") as (I'') \"(% & % & HIIpnm)\".\n    rename H0 into ContLeq_I. destruct H1 as [Io' [I_eq I''_eq]].\n    assert (Io' = Iz).\n    { rewrite Ipn_incl_I in I_eq *; intros I_eq.\n      apply intComp_cancelable in I_eq. done.\n      by rewrite <-Ipn_incl_I. }\n    subst Io'.\n    iMod (own_update γ_f (● domm I) (● (domm I ∪ {[m]}) ⋅ ◯ (domm I ∪ {[m]}))\n                         with \"[Hdomm]\") as \"H\"; try done.\n    { apply (auth_update_alloc (domm I) (domm I ∪ {[m]}) (domm I ∪ {[m]})).\n      apply gset_local_update. set_solver. }\n    assert (domm I'' = domm I ∪ {[m]}) as domm_I''.\n    {\n      assert (domm I'' = {[p]} ∪ {[n]} ∪ {[m]} ∪ domm Iz) as Dom_I''.\n      {\n        rewrite I''_eq. repeat rewrite flowint_comp_fp; try congruence; try done.\n        by apply cmra_valid_op_l in Valid_Ipnm.\n        apply leibniz_equiv_iff in I''_eq.\n        rewrite <-I''_eq. unfold contextualLeq in ContLeq_I.\n        by destruct ContLeq_I as [_ [? _]].\n      }\n      assert (domm I = {[p]} ∪ {[n]} ∪ domm Iz) as Dom_I.\n      {\n        rewrite I_eq. repeat rewrite flowint_comp_fp; try congruence; try done.\n        apply leibniz_equiv_iff in I_eq. by rewrite <-I_eq.\n      }\n      rewrite Dom_I'' Dom_I. clear. set_solver.\n    }\n    assert (globalinv K root I'').\n    {\n      apply (contextualLeq_impl_globalinv I I'').\n      all : trivial.\n      unfold globalinv. repeat split; try done.\n      intros n0 Hn0. assert (n0 = m).\n      { clear - Hn0 domm_I'' m_not_in_I. set_solver. } subst n0.\n      unfold inset. unfold dom_ms. unfold inf. case_eq (inf_map I'' !! m); last first.\n      - intros Hm. unfold ccmunit, ccm_unit. simpl. unfold nzmap_dom. simpl. set_solver.\n      - intros k0 Hk0. simpl.\n        assert (inf (Ip' ⋅ In' ⋅ Im' ⋅ Iz) m = (inf (Ip' ⋅ In'⋅ Im') m) - (out Iz m))%CCM as inf_def.\n        { apply intComp_inf_1. apply leibniz_equiv_iff in I''_eq. rewrite <-I''_eq.\n          unfold contextualLeq in ContLeq_I. by destruct ContLeq_I as [_ [? _]].\n          rewrite Dom_eq. clear. set_solver. }\n        rewrite m_inf in inf_def. rewrite out_Iz_zero in inf_def.\n        rewrite ccm_pinv_unit in inf_def. unfold inf in inf_def.\n        apply leibniz_equiv_iff in I''_eq.\n        rewrite <-I''_eq in inf_def. rewrite Hk0 in inf_def.\n        simpl in inf_def. rewrite inf_def. unfold ccmunit, lift_unit, nzmap_unit.\n        simpl. unfold nzmap_dom. simpl. set_solver.\n      }\n    iModIntro. iExists I''.\n    iEval (rewrite own_op) in \"HIIpnm\". iDestruct \"HIIpnm\" as \"(HI' & HIpnm'')\".\n    iEval (rewrite auth_frag_op) in \"HIpnm''\". iDestruct \"HIpnm''\" as \"(HIpn' & HIm')\".\n    iEval (rewrite auth_frag_op) in \"HIpn'\". iDestruct \"HIpn'\" as \"(HIp' & HIn')\".\n    iDestruct \"H\" as \"(Hdomm & _)\". iEval (rewrite <-domm_I'') in \"Hdomm\".\n    iFrame \"∗ # %\". iPureIntro. clear - domm_I'' m_not_in_I. set_solver.\n  Qed.\n  \n  (** High-level lock specs **)\n\n  Lemma lockNode_spec_high γ_I γ_f γ_k γ_c root n :\n    ⊢ inFP γ_f n -∗ css_inv γ_I γ_f γ_k γ_c root\n      -∗ <<< True >>>\n           lockNode #n @ ⊤ ∖ ↑N\n         <<< ∃ In Cn, nodePred γ_I γ_k root n In Cn,\n             RET #() >>>.\n  Proof.\n    iIntros \"#HFp #HInv\".\n    iIntros (Φ) \"AU\".\n    awp_apply (lockNode_spec n).\n    iInv \"HInv\" as \">Hcss\". iDestruct \"Hcss\" as (I C) \"Hcssi\".\n    iPoseProof (inFP_domm with \"[$] [$]\") as \"%\". rename H0 into n_in_I.\n    iPoseProof (CSS_unfold with \"[$] [%]\") as \"(Hg & Hnf & Hcss')\"; try done.\n    iSpecialize (\"Hcss'\" $! C).\n    iDestruct \"Hnf\" as (b In Cn) \"Hlock\". iFrame.\n    iAaccIntro with \"Hlock\".\n    { iIntros \"Hlockn\". iModIntro.\n      iPoseProof (\"Hcss'\" with \"[-AU]\") as \"Hcss\".\n      { iFrame. iExists b, In, Cn. iFrame. }\n      iSplitL \"Hcss\"; try done. iNext. iExists I, C. iFrame.\n    }\n    iIntros \"(Hlockn & H)\". \n    iMod \"AU\" as \"[_ [_ Hclose]]\".\n    iDestruct \"Hlockn\" as \"(Hlockn & _)\".\n    iMod (\"Hclose\" with \"[H]\") as \"HΦ\"; try done. iModIntro.\n    iPoseProof (\"Hcss'\" with \"[-HΦ]\") as \"Hcss\".\n    { iFrame. iExists true, In, Cn. iFrame. }\n    iFrame. iNext. iExists I, C. eauto with iFrame.\n  Qed.\n\n  Lemma unlockNode_spec_high γ_I γ_f γ_k γ_c root (n: Node) In Cn :\n    ⊢ css_inv γ_I γ_f γ_k γ_c root ∗ nodePred γ_I γ_k root n In Cn\n      -∗  <<< True  >>>\n           unlockNode #n @ ⊤ ∖ ↑N\n          <<< True, RET #() >>>.\n  Proof.\n    iIntros \"(#HInv & Hnp)\". iIntros (Φ) \"AU\".\n    awp_apply (unlockNode_spec n).\n    iInv \"HInv\" as \">Hcss\". iDestruct \"Hcss\" as (I C) \"Hcssi\".\n    iDestruct \"Hnp\" as \"(node & Hnpks & HnpI & Dom_In)\".\n    iPoseProof (int_domm with \"[$] [$] [$]\") as \"%\". rename H0 into n_in_I.\n    iPoseProof (CSS_unfold_node_wand with \"[$] [$] [%]\")\n      as \"(Hn & Hg & Hlock & Hcss')\"; try done.\n    iAssert (nodePred γ_I γ_k root n In Cn)%I \n      with \"[Hnpks HnpI Dom_In Hn]\" as \"Hnp\".\n    { iFrame. }\n    iCombine \"Hlock\" \"Hnp\" as \"HPre\".      \n    iAaccIntro with \"HPre\".\n    { iIntros \"(Hlock & Hnp)\". iModIntro. iFrame. iNext. \n      iExists I, C. iApply \"Hcss'\". iFrame. iExists true, In, Cn. iFrame. }\n    iIntros \"Hlock\".\n    iMod \"AU\" as \"[_ [_ Hclose]]\".\n    iMod (\"Hclose\" with \"[]\") as \"HΦ\"; try done.\n    iModIntro. iFrame. iNext. iExists I, C.\n    iApply \"Hcss'\". iFrame. iExists false, In, Cn. iFrame.\n  Qed.\n\n  (** Proof of the lock-coupling template *)\n\n  Theorem create_spec :\n   ⊢ {{{ True }}}\n        create #()\n     {{{ γ_I γ_f γ_k γ_c (root: Node), RET #root; \n          css_inv γ_I γ_f γ_k γ_c root ∗ css_cont γ_c ∅ }}}.\n  Proof.\n    iIntros (Φ). iModIntro.\n    iIntros \"_ HΦ\".\n    wp_lam. wp_apply allocRoot_spec; try done.\n    iIntros (root Ir ks) \"(node & Hl & HIr & Hks)\".\n    iDestruct \"HIr\" as %HIr. iDestruct \"Hks\" as %Hks.\n    iApply fupd_wp.\n    iMod (own_alloc ( (● Ir) ⋅ (◯ Ir))) as (γ_I)\"(HIr● & HIr◯)\".\n    { apply auth_both_valid_discrete. split; try done.\n      unfold valid, cmra_valid. simpl. unfold ucmra_valid.\n      simpl. unfold flowint_valid. subst Ir.\n      split; try done. apply map_disjoint_dom. set_solver. }\n    iMod (own_alloc ((● prod (KS, ∅)) ⋅ (◯ (prod (KS, ∅))))) \n          as (γ_k)\"(Hks● & Hks◯)\".\n    { apply auth_both_valid_discrete. split; try done. }\n    iMod (own_alloc (● (domm Ir))) \n          as (γ_f)\"Hf\". { apply auth_auth_valid. try done. }\n    iMod (own_alloc (● (Some (Excl ∅)) ⋅ ◯ (Some (Excl ∅)))) \n      as (γ_c)\"(Hc● & Hc◯)\".\n    { apply auth_both_valid_discrete. split; try done. }\n    iModIntro. wp_pures.\n    iMod (inv_alloc N _ (CSS γ_I γ_f γ_k γ_c root) with \"[-HΦ Hc◯]\") as \"#css_inv\".\n    { iNext. iExists Ir, ∅. iFrame. iSplitR.\n      - iPureIntro. repeat split; try done.\n        unfold valid, cmra_valid, flowint_valid.\n        subst Ir; split; try done.\n        apply map_disjoint_dom; set_solver.\n        subst Ir. unfold domm, dom, flowint_dom. simpl.\n        rewrite dom_singleton. set_solver.\n        unfold closed, outset, dom_ms, out, out_map.\n        subst Ir; simpl. try done.\n        unfold inset, dom_ms, inf.\n        subst Ir; simpl. rewrite lookup_singleton; simpl.\n        intros k Hk; rewrite Hks; try done.\n      - assert (domm Ir = {[root]}) as Domm_Ir.\n        { subst Ir; unfold domm, dom, flowint_dom, inf_map; simpl.\n          apply leibniz_equiv. by rewrite dom_singleton. }\n        rewrite Domm_Ir. rewrite big_opS_singleton.\n        iExists false, Ir, ∅. iFrame \"∗%\".\n        assert (keyset K Ir root = KS) as Hkeyset.\n        { unfold keyset. unfold dom_ms, inf, out; subst Ir; simpl.\n          rewrite nzmap_lookup_empty. rewrite lookup_singleton.\n          unfold ccmunit at 2. unfold ccm_unit. simpl.\n          unfold nzmap_dom. simpl.\n          assert (dom (gset K) (∅: gmap K nat) = ∅) as H'.\n          { apply leibniz_equiv. by rewrite dom_empty. }\n          rewrite H' Hks. set_solver. }\n        by rewrite Hkeyset. }\n      iModIntro. \n      iApply (\"HΦ\" $! γ_I γ_f γ_k γ_c root); try iFrame \"∗#\".    \n  Qed.    \n\n  Lemma traverse_spec γ_I γ_f γ_k γ_c root k p n Ip Cp In Cn:\n    ⊢ ⌜k ∈ KS⌝ ∗ css_inv γ_I γ_f γ_k γ_c root -∗\n    {{{   inFP γ_f n ∗ inFP γ_f p ∗ inFP γ_f root ∗ ⌜n ≠ root⌝\n        ∗ nodePred γ_I γ_k root n In Cn ∗ nodePred γ_I γ_k root p Ip Cp\n        ∗ ⌜in_inset K k Ip p⌝ ∗ ⌜in_outset K k Ip n⌝\n    }}}\n      traverse #p #n #k @ ⊤\n    {{{ p' n' Ip' In' Cp' Cn' (res: bool), RET ((#p', #n'), #res);\n          inFP γ_f n' ∗ inFP γ_f p'\n        ∗ nodePred γ_I γ_k root n' In' Cn' ∗ nodePred γ_I γ_k root p' Ip' Cp'\n        ∗ ⌜in_inset K k Ip' p'⌝\n        ∗ ⌜in_outset K k Ip' n'⌝\n        ∗ ⌜¬in_outsets K k In'⌝\n        ∗ ⌜res ↔ k ∈ Cn'⌝\n    }}}.\n  Proof.\n    iIntros \"(% & #HInv)\". iIntros (Φ) \"!# H HCont\".\n    iLöb as \"IH\" forall (p n Ip In Cp Cn).\n    iDestruct \"H\" as \"(#Hfpn & #Hfpp & #Hfpr & % & Hnp_n & Hnp_p & % & %)\".\n    rename H0 into k_in_KS. rename H1 into n_neq_root.\n    rename H2 into in_inset_Ip. rename H3 into in_outset_Ip.\n    wp_lam. wp_pures. wp_bind (findNext _ _)%E.\n    (* Preparing pre-condition of findNext *)\n    iDestruct \"Hnp_n\" as \"(noden & Hkn & Hin & Dom_In)\".\n    iDestruct \"Hnp_p\" as \"(nodep & Hkp & Hip & Dom_Ip)\".\n    iDestruct \"Dom_In\" as %Dom_In.\n    iDestruct \"Dom_Ip\" as %Dom_Ip.\n    iCombine \"Hip\" \"Hin\" as \"H\".\n    iPoseProof (own_valid with \"[$]\") as \"%\". rename H0 into Valid_Inp.\n    assert (in_inset K k In n) as in_inset_In.\n    { apply (flowint_inset_step Ip In k n); try done. apply auth_frag_valid. done. set_solver. }\n    wp_apply ((findNext_spec n k In Cn root) with \"[noden]\").\n    { iFrame \"∗ %\". } iDestruct \"H\" as \"(Hip & Hin)\".\n    iIntros (b n' res) \"(noden & % & Hb)\". rename H0 into Hres. destruct b.\n    - (* findNext returns Some n' *)\n      iDestruct \"Hb\" as %in_outset_In. wp_pures.\n      wp_bind (lockNode _)%E. iApply fupd_wp.\n      (* Open invariant to get pre for lockNode_spec *)\n      iInv \"HInv\" as \">Hcss\".\n      iAssert (nodePred γ_I γ_k root n In Cn)%I with \"[noden Hkn Hin]\"\n                        as \"Hnp_n\". { iFrame \"∗ %\". }\n      (* ghost update to step to n' *)\n      iMod (ghost_update_step with \"[$] [$] [% //] [% //]\") as \"(Hcss & Hnp_n & #Hfpn')\".\n      iModIntro. iSplitL \"Hcss\". by iNext. iModIntro.\n      (* Lock node n' *)\n      awp_apply (lockNode_spec_high) without \"HCont\".\n      iFrame \"Hfpn'\". iFrame \"HInv\".\n      iAaccIntro with \"[]\"; first done. { eauto with iFrame. }\n      (* Receive post of lock_spec_high *)\n      iIntros (In' Cn') \"Hnp_n'\".\n      iModIntro. iIntros \"HCont\". wp_pures.\n      iAssert (nodePred γ_I γ_k root p Ip Cp)%I with \"[nodep Hkp Hip]\"\n                        as \"Hnp_p\". { iFrame \"∗ %\". }\n      (* Unlock node p *)\n      awp_apply (unlockNode_spec_high with \"[Hnp_p]\") without \"HCont\".\n      { iFrame \"Hnp_p HInv\". }\n      iAaccIntro with \"[]\"; first done. { eauto with iFrame. }\n      iIntros \"_\"; iModIntro. iIntros \"HCont\". wp_pures.\n      (* Open invariant and prepare pre for induction hypothesis *)\n      iApply fupd_wp. iInv \"HInv\" as \">Hcss\".\n      iDestruct \"Hcss\" as (I C) \"((HI & Hglob & Hks & Hdom & Hcont) & Hbigstar)\".\n      iDestruct \"Hnp_n\" as \"(noden & Hkn & Hin & Dom_In)\".\n      iDestruct \"Hnp_n'\" as \"(noden' & Hkn' & Hin' & Dom_In')\".\n      iDestruct \"Hglob\" as %Hglob.\n      iDestruct \"Dom_In'\" as %Dom_In'.\n      iPoseProof ((own_op γ_I (◯ In) (◯ In')) with \"[Hin Hin']\") as \"H\";\n                     first by eauto with iFrame.\n      iEval (rewrite -auth_frag_op) in \"H\".\n      iPoseProof ((auth_own_incl _ I) with \"[$HI $H]\") as (Io)\"%\".\n      rename H0 into I_incl.\n      iPoseProof (own_valid with \"H\") as \"%\". rename H0 into Valid_Inn'.\n      iPoseProof (node_implies_nodeinv with \"[] [$noden']\") as \"%\".\n      { iPureIntro. rewrite auth_frag_valid in Valid_Inn' *; intros Valid_Inn'.\n        by apply cmra_valid_op_r in Valid_Inn'. } rename H0 into nodeinv_n'.\n      assert (n' ≠ root) as n'_neq_root.\n      { apply (successor_not_root I In In' Io Cn' root n' k); try done. }\n      (* Close invariant *)\n      iModIntro. iSplitL \"HI Hks Hcont Hbigstar Hdom\".\n      iNext. iExists I, C. iFrame \"∗ # %\". iModIntro.\n      iDestruct \"H\" as \"(Hin & Hin')\".\n      iAssert (nodePred γ_I γ_k root n In Cn)%I with \"[noden Hkn Hin]\"\n                        as \"Hnp_n\". { iFrame \"∗ %\". }\n      iAssert (nodePred γ_I γ_k root n' In' Cn')%I with \"[noden' Hkn' Hin']\"\n                        as \"Hnp_n'\". { iFrame \"∗ %\". }\n      (* Apply induction hypothesis *)\n      iSpecialize (\"IH\" $! n n' In In' Cn Cn').\n      iApply (\"IH\" with \"[Hnp_n Hnp_n']\"). iFrame \"∗ # %\".\n      iNext. done.\n    - (* findNext returns None *)\n      wp_pures. wp_bind (findNext _ _)%E.\n      wp_apply (findNext_spec with \"[noden]\"). iFrame \"∗ %\".\n      iIntros (suc n0 res0)\"(Hnoden & Hres & Hsuc)\". iDestruct \"Hb\" as \"(% & %)\".\n      iDestruct \"Hres\" as \"%\".\n      (* Apply continuation *)\n      iSpecialize (\"HCont\" $! p n Ip In Cp Cn).\n      destruct suc; wp_pures; iApply \"HCont\"; \n      iFrame \"∗ # %\"; iModIntro; try done.\n  Qed.\n\n  \n\n  (* TODO uses old version of node_lock_not_in_FP *)\n  Theorem searchStrOp_spec γ_I γ_f γ_k γ_c root (k: K) :\n    ⊢ ⌜k ∈ KS⌝ ∗ css_inv γ_I γ_f γ_k γ_c root -∗\n    <<< ∀ (C: gset K), css_cont γ_c C >>>\n      CSS_insertOp root #k @ ⊤ ∖ ↑N\n    <<< ∃ (C' : gset K) (res: bool), css_cont γ_c C'\n                        ∗ ⌜Ψ insertOp k C C' res⌝, RET #res >>>.\n  Proof.\n    iIntros \"(k_in_KS & #HInv)\". iIntros (Φ) \"AU\".\n    iDestruct \"k_in_KS\" as %k_in_KS.\n    wp_lam. wp_bind (lockNode _)%E.\n    iApply fupd_wp. iInv \"HInv\" as \">Hcss\".\n    iMod (ghost_update_root with \"[$]\") as \"(Hcss & #HinFPr)\".\n    iModIntro. iSplitR \"AU\". by iNext. iModIntro.\n    (* Lock root *)\n    awp_apply (lockNode_spec_high γ_I γ_f γ_k γ_c root root); try done.\n    iAaccIntro with \"[]\"; try eauto with iFrame.\n    iIntros (Ir Cr) \"Hnp\". iModIntro. wp_pures.\n    wp_bind (findNext _ _)%E.\n    (* Preparing pre-condition of findNext *)\n    iApply fupd_wp. iInv \"HInv\" as \">Hcss\".\n    iDestruct \"Hcss\" as (I1 C1) \"((HI & Hglob & Hks & Hdom & Hcont) & Hbigstar)\".\n    iDestruct \"Hglob\" as %Hglob1.\n    iDestruct \"Hnp\" as \"(Hnode & Hk & Hi & Dom_In)\".\n    iDestruct \"Dom_In\" as %Dom_In.\n    iPoseProof ((auth_own_incl _ I1) with \"[$HI $Hi]\") as (Io')\"%\".\n    rename H0 into Ir_incl_I1.\n    iPoseProof (own_valid with \"HI\") as \"%\". rename H0 into Valid_I1.\n    assert (in_inset K k Ir root) as k_inset_root.\n    { unfold globalinv in Hglob1. destruct Hglob1 as [_ [_ [_ Hglob1_inset]]].\n      pose proof (Hglob1_inset k k_in_KS).\n      apply (inset_monotone I1 Ir Io' k root); try done.\n      by apply auth_auth_valid. set_solver. }\n    iModIntro. iSplitL \"Hbigstar Hcont Hdom Hks HI\".\n    iNext. iExists I1, C1. iFrame \"∗ %\". iModIntro.\n    wp_apply ((findNext_spec root k Ir Cr root) with \"[Hnode]\").\n    { iFrame \"∗ %\". } iIntros (b n res0) \"(Hnode & Hres & Hb)\".\n    iDestruct \"Hres\" as %Hres.\n    destruct b; last first.\n    { (* (findNext root) returns None; contradiction *)\n      iDestruct \"Hb\" as \"(_ & root_neq)\".\n      iDestruct \"root_neq\" as %root_neq.\n      contradiction. }\n    (* (findNext root) return Some n *)\n    iDestruct \"Hb\" as %in_outset_r.\n    wp_pures. wp_bind (lockNode _)%E.\n    (* Open invariant to show n in the footprint *)\n    iApply fupd_wp. iInv \"HInv\" as \">Hcss\".\n    iDestruct \"Hcss\" as (I2 C2) \"Hcssi\".\n    iDestruct \"Hcssi\" as \"((HI & Hglob & Hks & Hdom & Hcont) & Hbigstar)\".\n    iDestruct \"Hglob\" as %Hglob2.\n    iPoseProof (own_valid with \"HI\") as \"%\". rename H0 into Valid_I2.\n    iPoseProof ((auth_own_incl _ I2) with \"[$HI $Hi]\") as (Io'')\"%\".\n    rename H0 into Ir_incl_I2.\n    assert (n ∈ domm I2) as n_in_I2.\n    { assert (n ∈ domm Io'').\n      { apply (flowint_step I2 Ir Io'' k n); try done.\n        rewrite auth_auth_valid in Valid_I2*. done.\n        unfold globalinv in Hglob2.\n        destruct Hglob2 as (_ & _ & cI & _). done.\n      }\n      rewrite Ir_incl_I2. rewrite flowint_comp_fp. set_solver.\n      rewrite <-Ir_incl_I2. by apply auth_auth_valid. }\n    iMod (ghost_snapshot_fp γ_f (domm I2) n with \"[$Hdom] [% //]\")\n        as \"(Hdom & #Hinfpn)\".\n    iModIntro. iSplitL \"HI Hks Hcont Hbigstar Hdom\".\n    iNext. iExists I2, C2. iFrame \"∗ %\". iModIntro.\n    (* Lock n *)\n    awp_apply (lockNode_spec_high γ_I γ_f γ_k γ_c root n); try done.\n    iAaccIntro with \"[]\"; try eauto with iFrame.\n    iIntros (In Cn) \"Hnpn\".\n    iModIntro. wp_pures. wp_bind (traverse _ _ _)%E.\n    (* Open invariant for pre of traverse *)\n    iApply fupd_wp. iInv \"HInv\" as \">Hcss\".\n    iDestruct \"Hcss\" as (I3 C3) \"((HI & Hglob & Hks & Hdom & Hcont) & Hbigstar)\".\n    iDestruct \"Hglob\" as %Hglob3.\n    iDestruct \"Hnpn\" as \"(Hnoden & Hkn & Hin & Dom_Inn)\".\n    iPoseProof ((own_op γ_I (◯ Ir) (◯ In)) with \"[Hi Hin]\") as \"H\";\n                     first by eauto with iFrame.\n    iEval (rewrite -auth_frag_op) in \"H\".\n    clear Io' Ir_incl_I1 Io'' Ir_incl_I2.\n    iPoseProof ((auth_own_incl _ I3) with \"[$HI $H]\") as (Io)\"%\".\n    rename H0 into Irn_incl_I3.\n    iPoseProof (own_valid with \"H\") as \"%\". rename H0 into Valid_Irn.\n    iPoseProof (node_implies_nodeinv with \"[] [$Hnoden]\") as \"%\".\n    { iPureIntro. rewrite auth_frag_valid in Valid_Irn *; intros Valid_Irn.\n      by apply cmra_valid_op_r in Valid_Irn. } rename H0 into nodeinv_n.\n    assert (n ≠ root) as n_neq_root.\n    { apply (successor_not_root I3 Ir In Io Cn root n k); try done. }\n    (* Close invariant *)\n    iModIntro. iSplitL \"HI Hks Hcont Hbigstar Hdom\".\n    iNext. iExists I3, C3. iFrame \"∗ # %\". iModIntro.\n    iDestruct \"H\" as \"(Hi & Hin)\".\n    iDestruct \"Dom_Inn\" as %Dom_Inn.\n    (* Apply traverse_spec *)\n    wp_apply ((traverse_spec γ_I γ_f γ_k γ_c root k root n Ir Cr In Cn)\n                 with \"[] [-AU]\"); try iFrame \"∗ % #\".\n    iIntros (p' n' Ip' In' Cp' Cn' res) \"(#HinFPn' & # HinFPp'\n                            & Hnpn' & Hnpp' & H1 & H2 & H3 & H4)\".\n    iDestruct \"H1\" as %inset_p'. iDestruct \"H2\" as %outset_pn'.\n    iDestruct \"H3\" as %not_outset_n'. clear Hres. iDestruct \"H4\" as %Hres.\n    wp_pures. destruct res.\n    - (* The traverse spec returns the operation key is already present.\n         In this case, we do not need to add a new node.\n         So, we open AU and show post-condition *)\n      iInv \"HInv\" as \">Hcss\".\n      iDestruct \"Hcss\" as (I4 C4) \"((HI & Hglob & Hks & Hdom & Hcont) & Hbigstar)\".\n      iDestruct \"Hnpn'\" as \"(Hnoden & Hkn & Hin & Dom_Inn)\".\n      iPoseProof (Ψ_key_present with \"[% //] [$Hks] [$Hkn]\") as \"(Hks & Hkn & #HΨ)\".\n      (* Open AU *)\n      iMod \"AU\" as (C') \"[Hc [_ Hclose]]\". iEval (rewrite /css_cont) in \"Hc\".\n      iDestruct (auth_agree with \"Hcont Hc\") as %<-.\n      wp_pures. iSpecialize (\"Hclose\" $! C4 false).\n      (* Close AU *)\n      iMod (\"Hclose\" with \"[Hc]\") as \"HΦ\". iFrame \"∗ #\".\n      iModIntro. iModIntro. iSplitR \"HΦ\". iNext.\n      iExists I4, C4. iFrame \"∗ %\". done.\n    - (* The traverse spec returns the operation key is not present.\n         Here, we create a new node m *)\n      wp_pures.\n      (* alloc m *)\n      wp_apply (alloc_spec); first done.\n      iIntros (m lm) \"(Hrepm & % & Hlm)\". wp_pures. wp_bind (decisiveOp _ _ _ _)%E.\n      rename H0 into Lock_m. iEval (rewrite <-Lock_m) in \"Hlm\".\n      (* Open invariant for pre of decisiveOp *)\n      iApply fupd_wp. iInv \"HInv\" as \">Hcss\". iDestruct \"Hcss\" as (I4 C4) \"Hcss\".\n      iPoseProof (node_lock_not_in_FP with \"[$] [$]\") as \"%\". rename H0 into m_not_in_I4.\n      iPoseProof (inFP_domm with \"[$HinFPr] [$]\") as \"%\". rename H0 into n_in_I.\n      assert (m ≠ root) as m_neq_root. { set_solver. }\n      iDestruct \"Hnpn'\" as \"(Hnoden & Hkn & Hin & Dom_Inn)\". iDestruct \"Dom_Inn\" as %Dom_In'.\n      iDestruct \"Hnpp'\" as \"(Hnodep & Hkp & Hip & Dom_Inp)\". iDestruct \"Dom_Inp\" as %Dom_Ip'.\n      iPoseProof ((own_op γ_I (◯ Ip') (◯ In')) with \"[Hip Hin]\") as \"HIpn'\"; first by eauto with iFrame.\n      iPoseProof (own_valid with \"HIpn'\") as \"%\". rename H0 into Valid_Ipn'.\n      rewrite -auth_frag_op in Valid_Ipn'. rewrite auth_frag_valid in Valid_Ipn' *; intros Valid_Ipn'.\n      iPoseProof ((own_op γ_k _ _) with \"[Hkp Hkn]\") as \"Hkspn'\"; first by eauto with iFrame.\n      iPoseProof (own_valid with \"Hkspn'\") as \"%\". rename H0 into Valid_kspn'.\n      rewrite -auth_frag_op in Valid_kspn'. rewrite auth_frag_valid in Valid_kspn' *; intros Valid_kspn'.\n      unfold op, cmra_op in Valid_kspn'. simpl in Valid_kspn'.\n      unfold ucmra_op in Valid_kspn'. simpl in Valid_kspn'. repeat case_decide; try done .\n      rename H0 into c_sub_ks_n. rename H1 into c_sub_ks_p.\n      rename H2 into Disj_ks_pn. rename H3 into Disj_c_pn.\n      iEval (rewrite -auth_frag_op) in \"HIpn'\".\n      iDestruct \"Hcss\" as \"((HI & Hglob & Hks & Hdom & Hcont) & Hbigstar)\".\n      iDestruct \"Hglob\" as %Hglob4.\n      iPoseProof ((auth_own_incl _ I4) with \"[$HI $HIpn']\") as (Iw)\"%\".\n      rename H0 into Ipn_incl_I4.\n      iPoseProof (own_valid with \"HI\") as \"%\". rename H0 into Valid_I4.\n      iPoseProof (own_valid with \"HIpn'\") as \"%\". rename H0 into Valid_Ipn.\n      assert (out (Ip'⋅In') m = 0%CCM) as Out_zero_pn'.\n      {\n        apply (intComp_out_zero Iw (Ip'⋅In') m).\n        rewrite intComp_comm. rewrite <-Ipn_incl_I4.\n        by apply auth_auth_valid.\n        rewrite intComp_comm. by rewrite <-Ipn_incl_I4.\n        rewrite intComp_comm. rewrite <-Ipn_incl_I4.\n        unfold globalinv in Hglob4. destruct Hglob4 as (_ & _ & Hglob4 & _).\n        apply nzmap_eq. intros k0. pose proof (Hglob4 k0 m) as k_not_out.\n        unfold outset, dom_ms in k_not_out.\n        rewrite (nzmap_elem_of_dom_total) in k_not_out *; intros k_not_out.\n        apply dec_stable in k_not_out. by rewrite nzmap_lookup_empty.\n      }\n      clear n_neq_root nodeinv_n.\n      iPoseProof (node_implies_nodeinv with \"[] [$Hnoden]\") as \"%\".\n      { iPureIntro. rewrite auth_frag_valid in Valid_Ipn *; intros Valid_Ipn.\n        by apply cmra_valid_op_r in Valid_Ipn. } rename H0 into nodeinv_n.\n      assert (n' ≠ root) as n_neq_root.\n      { apply (successor_not_root I4 Ip' In' Iw Cn' root n' k); try done. }\n      (* Close invariant *)\n      iModIntro. iSplitL \"HI Hks Hcont Hbigstar Hdom\". iNext.\n      iExists I4, C4. iFrame \"∗ # %\". iModIntro.\n      destruct Hres as [Hres Hk_not0].\n      assert (k ∉ Cn') as Hk_not1. { unfold not. apply Hk_not0. }\n      (* Apply decisiveOp_spec *)\n      wp_apply ((decisiveOp_insert_spec root p' n' m k Ip' In' Cp' Cn')\n            with \"[Hnodep Hnoden Hrepm]\"). { iFrame \"∗ % #\". iPureIntro. set_solver. }\n      iIntros (Cp'' Cn'' Cm'' Ip'' In'' Im'' res) \"(Hnodep' & Hnoden' & Hnodem' & #HΨ & HcontLeq & Hminf & H)\".\n      iDestruct \"H\" as \"(Disj_ks_pn & Disj_ks_pm & Disj_ks_mn & ks_eq)\".\n      iDestruct \"Hminf\" as %Hinf.\n      iDestruct \"HcontLeq\" as %HcontLeq.\n      iDestruct \"Disj_ks_pn\" as %Disj_ks_pn'.\n      iDestruct \"Disj_ks_pm\" as %Disj_ks_pm'.\n      iDestruct \"Disj_ks_mn\" as %Disj_ks_mn'.\n      iDestruct \"ks_eq\" as %ks_eq.\n\n      (* Linearization starts *)\n      iApply fupd_wp. iInv \"HInv\" as \">Hcss\".\n      iDestruct \"Hcss\" as (I5 C5) \"((HI & Hglob & Hks & Hdom & Hcont) & Hbigstar)\".\n      (* Open AU *)\n      iMod \"AU\" as (C') \"[Hc [_ Hclose]]\". iEval (rewrite /css_cont) in \"Hc\".\n      iDestruct (auth_agree with \"Hcont Hc\") as %<-.\n\n      (* ------ update keyset ghost resources -------*)\n\n      assert (in_inset K k In' n') as in_inset_n.\n      { apply (flowint_inset_step Ip' In' k n'); try done.\n        rewrite Dom_In'. clear. set_solver. }\n      assert (k ∈ keyset K In' n') as in_keyset_n.\n      { apply keyset_def; try done. }\n      iMod (ghost_update_cssOp_keyset with \"[Hnodep' Hnoden' Hnodem' Hks Hkspn']\") as \"Hgks\".\n      { iFrame \"HΨ\". iFrame \"∗\". iFrame \"%\".\n        iPureIntro. split; try set_solver. }\n      iDestruct \"Hgks\" as (C5') \"(#HΨ' & Hnodep' & Hnoden' & Hnodem' & Hksp'\n                                       & Hksn' & Hksm' & HKS & % & % & %)\".\n      rename H0 into Dom_Ip''.\n      rename H1 into Dom_In''.\n      rename H2 into Dom_Im''.\n      iMod (auth_excl_update γ_c (C5') with \"Hcont Hc\") as \"[Hcont Hc]\".\n\n      (* ------ update interface ghost resources -------*)\n\n      iPoseProof (node_lock_not_in_FP with \"[$Hlm] [$]\") as \"%\". rename H0 into m_not_in_I5.\n      iDestruct \"Hglob\" as %Hglob5.\n      iMod (ghost_update_cssOp_interface with \"[HIpn' HI Hdom]\") as \"Hgi\".\n      { iFrame \"∗\". iPureIntro. split. apply m_not_in_I5.\n        split; try apply Hglob5. split; try apply HcontLeq.\n        repeat split; try done. }\n      iDestruct \"Hgi\" as (I') \"(ContLeq_I & Hglob_I' & HI & HIp' & HIn'\n                                & HIm' & Hdomm & Dom_I' & Dom2_I')\".\n      iDestruct \"ContLeq_I\" as %ContLeq_I.\n      iDestruct \"Hglob_I'\" as %Hglob_I'.\n      iDestruct \"Dom_I'\" as %Dom_I'.\n      iDestruct \"Dom2_I'\" as %Dom2_I'.\n\n      (* ------ updates over, close AU -------*)\n\n      iSpecialize (\"Hclose\" $! C5' res).\n      iMod (\"Hclose\" with \"[Hc]\") as \"HΦ\". iFrame \"∗ % #\".\n      iModIntro. iSplitL \"Hbigstar HKS Hcont HI Hdomm Hnodem' Hksm' HIm' Hlm\".\n      iNext. iExists I', C5'. iFrame \"∗ # %\".\n      { rewrite (big_sepS_delete _ (domm I') m); last first.\n      clear -Dom_I'. set_solver. iEval (rewrite Dom2_I').\n      iFrame. iExists false. iFrame \"∗ %\". iExists Im'', Cm''. iFrame \"∗ %\". }\n      iModIntro. wp_pures. wp_bind (unlockNode _)%E.\n\n      (* ------ linearization over -------*)\n\n      iAssert (nodePred γ_I γ_k root p' Ip'' Cp'')%I with \"[Hnodep' Hksp' HIp']\"\n                        as \"Hnp_p\". { iFrame \"∗ %\". }\n      (* Unlock node p *)\n      awp_apply (unlockNode_spec_high with \"[Hnp_p]\") without \"HΦ\".\n      iFrame \"Hnp_p HInv\".\n      iAaccIntro with \"[]\"; first done.\n      { iIntros \"_\". iModIntro.\n        iFrame \"∗ %\". }\n      iIntros \"_\". iModIntro. iIntros \"HΦ\". wp_pures.\n      iAssert (nodePred γ_I γ_k root n' In'' Cn'')%I with \"[Hnoden' Hksn' HIn']\"\n                        as \"Hnp_n\". { iFrame \"∗ %\". }\n      (* Unlock node n *)\n      awp_apply (unlockNode_spec_high with \"[Hnp_n]\") without \"HΦ\".\n      iFrame \"Hnp_n HInv\".\n      iAaccIntro with \"[]\"; first done.\n      { eauto with iFrame. }\n      iIntros \"_\". iModIntro. iIntros \"HΦ\". wp_pures. done.\n  Qed.\n\nEnd Coupling_Template.\n", "meta": {"author": "nyu-acsys", "repo": "template-proofs", "sha": "3911d3f9c25f3fffdd95d6aa052fae606f4d52c2", "save_path": "github-repos/coq/nyu-acsys-template-proofs", "path": "github-repos/coq/nyu-acsys-template-proofs/template-proofs-3911d3f9c25f3fffdd95d6aa052fae606f4d52c2/templates/single_copy/coupling.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.63341026367784, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.20321150474878197}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs64.printf.\n#[export] Instance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nRequire Import VST.floyd.printf.\nRequire Import ITree.Eq.\n\n#[export] Instance nat_id : FileId := { file_id := nat; stdin := 0%nat; stdout := 1%nat }.\n#[export] Instance file_struct : FileStruct := {| FILEid := ___sFILE64; reent := __reent; f_stdin := __stdin; f_stdout := __stdout |}.\n\nDefinition main_spec :=\n DECLARE _main\n  WITH gv : globals\n  PRE  [] main_pre prog (write_list stdout (string2bytes \"Hello, world!\n\");; write_list stdout (string2bytes \"This is line 2.\n\"))%itree gv\n  POST [ tint ] main_post prog gv.\n\nDefinition Gprog : funspecs :=  \n   (*ltac:(with_library prog *)(ltac:(make_printf_specs prog) ++ [ main_spec ])(*)*).\n\nLemma body_main: semax_body Vprog Gprog f_main main_spec.\nProof.\nstart_function.\nmake_stdio.\nrepeat do_string2bytes.\nrepeat (sep_apply data_at_to_cstring; []).\nsep_apply (has_ext_ITREE(E := @IO_event file_id)).\n\nforward_printf tt (write_list stdout (string2bytes \"This is line 2.\n\")).\n{ rewrite !sepcon_assoc; apply sepcon_derives; cancel.\n  apply derives_refl. }\nforward_call.\nforward.\nforward_fprintf outp ((Ers, string2bytes \"line\", gv ___stringlit_2), (Int.repr 2, tt)) (stdout, Ret tt : @IO_itree (@IO_event file_id)).\n{ rewrite 3sepcon_assoc, sepcon_comm, sepcon_assoc; apply sepcon_derives; cancel.\n  rewrite bind_ret'; apply derives_refl. }\nforward.\nQed.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/progs64/verif_printf.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20302909464460284}}
{"text": "Require Export Fiat.Parsers.ContextFreeGrammar.Core.\nRequire Export Fiat.Parsers.ContextFreeGrammar.PreNotations.\nRequire Export Fiat.Parsers.StringLike.FirstCharSuchThat.\nRequire Export Coq.Strings.String.\nRequire Export Fiat.Computation.Core.\nRequire Export Coq.Program.Program.\nRequire Export Fiat.Computation.ApplyMonad.\nRequire Export Fiat.Computation.SetoidMorphisms.\nRequire Export Fiat.Common.\nRequire Export Fiat.Parsers.StringLike.Core.\n\nRequire Import Fiat.Parsers.ContextFreeGrammar.Equality.\nRequire Import Fiat.Parsers.ContextFreeGrammar.Carriers.\nRequire Import Fiat.Common.Equality.\nRequire Import Fiat.Common.BoolFacts.\nRequire Import Fiat.Common.NatFacts.\nRequire Import Fiat.Computation.Refinements.General.\n\nExport Common.opt2.Notations.\n\nGlobal Open Scope string_scope.\nGlobal Open Scope list_scope.\nGlobal Arguments string_beq : simpl never.\nGlobal Arguments ascii_beq : simpl never.\nGlobal Arguments item_beq : simpl never.\nGlobal Arguments production_beq : simpl never.\nGlobal Arguments productions_beq : simpl never.\nDelimit Scope char_scope with char.\nInfix \"=p\" := (production_beq _) (at level 70, no associativity).\n\n(** Unfolding rules for enumerated ascii *)\nGlobal Arguments Ascii.one / .\nGlobal Arguments Ascii.shift _ !_ / .\nGlobal Arguments Ascii.ascii_of_pos !_ / .\nGlobal Arguments Ascii.ascii_of_nat !_ / .\nGlobal Arguments Carriers.default_nonterminal_carrierT / .\n\nSection tac_helpers.\n  Lemma pull_match_list {A R R' rn rc} {ls : list A} (f : R -> R')\n  : match ls with\n      | nil => f rn\n      | cons x xs => f (rc x xs)\n    end = f (match ls with\n               | nil => rn\n               | cons x xs => rc x xs\n             end).\n  Proof.\n    destruct ls; reflexivity.\n  Qed.\n\n  Lemma pull_match_item {A R R' rn rc} {ls : item A} (f : R -> R')\n  : match ls with\n      | NonTerminal x => f (rn x)\n      | Terminal x => f (rc x)\n    end = f (match ls with\n               | NonTerminal x => rn x\n               | Terminal x => rc x\n             end).\n  Proof.\n    destruct ls; reflexivity.\n  Qed.\n\n  Lemma pull_match_bool {R R' rn rc} {b : bool} (f : R -> R')\n  : (if b then f rn else f rc)\n    = f (if b then rn else rc).\n  Proof.\n    destruct b; reflexivity.\n  Qed.\n\n  Lemma pull_If_bool {R R' rn rc} {b : bool} (f : R -> R')\n  : (If b Then f rn Else f rc)\n    = f (If b Then rn Else rc).\n  Proof.\n    destruct b; reflexivity.\n  Qed.\nEnd tac_helpers.\n\nLemma unguard {T} (x : T)\n: refine { x' : T | True }\n         (ret x).\nProof.\n  repeat intro; computes_to_inv; subst.\n  apply PickComputes; constructor.\nQed.\n\nGlobal Arguments unguard {_} _ [_] _.\n\nLtac parser_pull_tac :=\n  repeat match goal with\n           | [ |- context G[match ?ls with\n                              | nil => [?x]\n                              | (_::_) => [?y]\n                            end] ]\n             => rewrite (@pull_match_list _ _ _ x (fun _ _ => y) ls (fun k => [k]))\n           | [ |- context G[match ?it with\n                              | NonTerminal _ => [?x]\n                              | Terminal _ => [?y]\n                            end] ]\n             => rewrite (@pull_match_item _ _ _ (fun _ => x) (fun _ => y) it (fun k => [k]))\n           | [ |- context G[match ?b with\n                              | true => [?x]\n                              | false => [?y]\n                            end] ]\n             => rewrite (@pull_match_bool _ _ x y b (fun k => [k]))\n           | [ |- context G[match ?b with\n                              | true => ret ?x\n                              | false => ret ?y\n                            end] ]\n             => rewrite (@pull_match_bool _ _ x y b (fun k => ret k))\n           | [ |- context G[If ?b Then [?x] Else [?y] ] ]\n             => rewrite (@pull_If_bool _ _ x y b (fun k => [k]))\n           | [ |- context G[If ?b Then ret ?x Else ret ?y] ]\n             => rewrite (@pull_If_bool _ _ x y b (fun k => ret k))\n         end.\n\nLtac unguard :=\n  rewrite ?(unguard [0]).\n\nLtac solve_prod_beq :=\n  clear;\n  repeat match goal with\n           | [ |- context[true = false] ] => congruence\n           | [ |- context[false = true] ] => congruence\n           | [ |- context[EqNat.beq_nat ?x ?y] ]\n             => is_var x;\n               let H := fresh in\n               destruct (EqNat.beq_nat x y) eqn:H;\n                 [ apply EqNat.beq_nat_true in H; subst x\n                 | ];\n                 simpl\n           | [ |- context[EqNat.beq_nat ?x ?y] ]\n             => first [ is_var x; fail 1\n                      | generalize x; intro ]\n         end.\n\nDefinition if_aggregate {A} (b1 b2 : bool) (x y : A)\n: (If b1 Then x Else If b2 Then x Else y) = (If (b1 || b2)%opt2_bool Then x Else y)\n  := if_aggregate b1 b2 x y.\nDefinition if_aggregate2 {A} (b1 b2 b3 : bool) (x y z : A) (H : b1 = false -> b2 = true -> b3 = true -> False)\n: (If b1 Then x Else If b2 Then y Else If b3 Then x Else z) = (If (b1 || b3)%opt2_bool Then x Else If b2 Then y Else z)\n  := if_aggregate2 x y z H.\nDefinition if_aggregate3 {A} (b1 b2 b3 b4 : bool) (x y z w : A) (H : b1 = false -> (b2 || b3)%bool = true -> b4 = true -> False)\n: (If b1 Then x Else If b2 Then y Else If b3 Then z Else If b4 Then x Else w) = (If (b1 || b4)%opt2_bool Then x Else If b2 Then y Else If b3 Then z Else w)\n  := if_aggregate3 _ _ x y z w H.\n\nModule opt2.\n  Definition orb_false_r : forall b, (b || false)%opt2_bool = b\n    := Bool.orb_false_r.\n  Definition andb_orb_distrib_r : forall b1 b2 b3 : bool,\n      (b1 && (b2 || b3))%opt2_bool = (b1 && b2 || b1 && b3)%opt2_bool\n    := Bool.andb_orb_distrib_r.\n  Definition andb_orb_distrib_l : forall b1 b2 b3 : bool,\n      ((b1 || b2) && b3)%opt2_bool = (b1 && b3 || b2 && b3)%opt2_bool\n    := Bool.andb_orb_distrib_l.\n  Definition orb_andb_distrib_r\n    : forall b1 b2 b3 : bool,\n      (b1 || b2 && b3)%opt2_bool = ((b1 || b2) && (b1 || b3))%opt2_bool\n    := Bool.orb_andb_distrib_r.\n  Definition orb_andb_distrib_l\n    : forall b1 b2 b3 : bool,\n      (b1 && b2 || b3)%opt2_bool = ((b1 || b3) && (b2 || b3))%opt2_bool\n    := Bool.orb_andb_distrib_l.\n  Definition andb_assoc\n    : forall b1 b2 b3 : bool, (b1 && (b2 && b3))%opt2_bool = (b1 && b2 && b3)%opt2_bool\n    := Bool.andb_assoc.\n  Definition orb_assoc\n    : forall b1 b2 b3 : bool, (b1 || (b2 || b3))%opt2_bool = (b1 || b2 || b3)%opt2_bool\n    := Bool.orb_assoc.\n  Definition andb_orb_distrib_r_assoc\n    : forall b1 b2 b3 b4 : bool,\n      (b1 && (b2 || b3) || b4)%opt2_bool = (b1 && b2 || (b1 && b3 || b4))%opt2_bool\n    := andb_orb_distrib_r_assoc.\n  Definition beq_0_1_leb\n    : forall x : nat,\n      (opt2.beq_nat x 1 || opt2.beq_nat x 0)%opt2_bool = opt2.leb x 1\n    := beq_0_1_leb.\n  Definition beq_S_leb\n    : forall x n : nat,\n      (opt2.beq_nat x (S n) || opt2.leb x n)%opt2_bool = opt2.leb x (S n)\n    := beq_S_leb.\nEnd opt2.\n", "meta": {"author": "JasonGross", "repo": "slow-coq-examples", "sha": "45c90a0447be39dfebbb787029528ad0dd32b090", "save_path": "github-repos/coq/JasonGross-slow-coq-examples", "path": "github-repos/coq/JasonGross-slow-coq-examples/slow-coq-examples-45c90a0447be39dfebbb787029528ad0dd32b090/slow_fiat_eapply_example/src/Parsers/Refinement/PreTactics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20302909464460284}}
{"text": "(*\n * Copyright (c) 2020 BedRock Systems, Inc.\n * This software is distributed under the terms of the BedRock Open-Source License.\n * See the LICENSE-BedRock file in the repository root for details.\n *)\n(** This file defines the core logic (called [mpred]) that we use\n    for C++.\n\n    Known issues:\n    - currently the logic is sequentially consistent\n    - the memory model is simplified from the standard C++ memory\n      model.\n *)\nRequire Export bedrock.prelude.addr.\n\nFrom bedrock.lang.bi Require Export prelude observe.\nFrom bedrock.lang.cpp.logic Require Export mpred rep.\n(** ^^ Delicate; export types and canonical structures (CS) for [monPred], [mpred] and [Rep].\nExport order can affect CS inference. *)\n\nFrom bedrock.lang.cpp.algebra Require Export cfrac.\nRequire Export bedrock.lang.cpp.bi.cfractional.\n\nFrom iris.base_logic.lib Require Export iprop.\n(* TODO: ^^ only needed to export uPredI, should be removed. *)\nFrom iris.bi.lib Require Import fractional.\nFrom iris.proofmode Require Import proofmode.\n\nRequire Import bedrock.lang.bi.na_invariants.\nRequire Import bedrock.lang.bi.cancelable_invariants.\nExport ChargeNotation.\n\nFrom bedrock.lang.cpp.syntax Require Import\n     names\n     types\n     translation_unit.\nFrom bedrock.lang.cpp.semantics Require Import values subtyping.\n\n#[local] Set Printing Coercions.\n\nVariant validity_type : Set := Strict | Relaxed.\n\nImplicit Types (vt : validity_type) (σ resolve : genv).\nImplicit Types (n : N) (z : Z).\n\n(* Namespace for the invariants of the C++ abstraction's ghost state. *)\nDefinition pred_ns : namespace := nroot .@@ \"bedrock\" .@@ \"lang\" .@@ \"cpp_logic\".\n\nModule Type CPP_LOGIC\n  (Import P : PTRS_INTF)\n  (Import INTF : VALUES_INTF_FUNCTOR P)\n  (Import CC : CPP_LOGIC_CLASS).\n\n  Implicit Types (p : ptr).\n\n  Section with_cpp.\n    Context `{Σ : cpp_logic}.\n\n    (**\n      [_valid_ptr vt p] is a persistent assertion that [p] is a _valid pointer_, that is:\n      - [p] can point to a function or a (possibly dead) object [o]\n      - if [vt = Relaxed], [p] can be nullptr, or past-the-end of a (possibly dead) object [o].\n      In particular, [_valid_ptr vt p] prevents producing [p] by incrementing\n      past-the-end pointers into overflow territory.\n\n      Our definition of validity includes all cases in which a pointer is not\n      an _invalid pointer value_ in the sense of the standard\n      (https://eel.is/c++draft/basic.compound#3.1), except that our concept\n      of validity survives deallocation; a pointer is only valid according to\n      the standard (or \"standard-valid\") if it is _both_ valid ([_valid_ptr\n      vt p]) and live ([live_ptr p]); we require both where needed (e.g.\n      [eval_ptr_eq]).\n\n      When the duration of a region of storage ends [note 1], contained objects [o] go\n      from live to dead, and pointers to such objects become _dangling_, or\n      _invalid pointer values_ (https://eel.is/c++draft/basic.compound#3.1);\n      this is called _pointer zapping_ [note 1].\n      In our semantics, that only consumes the non-persistent predicate\n      [live_ptr p], not the persistent predicate [_valid_ptr vt p].\n\n      Following Cerberus, [live_alloc_id] tracks liveness per allocation\n      ID (see comments for [ptr]), and [live_ptr] is derived from it. Hence,\n      a pointer [p] past-the-end of [o] also becomes dangling when [o] is\n      deallocated.\n\n      It's implementation-defined whether invalid pointer values are\n      (non-copyable) trap representations. Instead, we restrict to\n      implementations where dangling pointers are not trap representations\n      (which is allowed, since this choice is implementation-defined) and\n      pointer zapping does not actually clear pointers.\n\n      [Note 1]. See https://eel.is/c++draft/basic.stc.general#4 and\n      https://eel.is/c++draft/basic.compound#3.1 for C++, and\n      http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2369.pdf for\n      discussion in the context of the C standard.\n    *)\n    Parameter _valid_ptr : forall (vt : validity_type), ptr -> mpred.\n    (* strict validity (not past-the-end) *)\n    Notation strict_valid_ptr := (_valid_ptr Strict).\n    (* validity (past-the-end allowed) *)\n    Notation valid_ptr := (_valid_ptr Relaxed).\n\n    Axiom _valid_ptr_persistent : forall b p, Persistent (_valid_ptr b p).\n    Axiom _valid_ptr_affine : forall b p, Affine (_valid_ptr b p).\n    Axiom _valid_ptr_timeless : forall b p, Timeless (_valid_ptr b p).\n    #[global] Existing Instances _valid_ptr_persistent _valid_ptr_affine _valid_ptr_timeless.\n\n    Axiom valid_ptr_nullptr : |-- valid_ptr nullptr.\n    Axiom not_strictly_valid_ptr_nullptr : strict_valid_ptr nullptr |-- False.\n    Axiom strict_valid_valid : forall p,\n      strict_valid_ptr p |-- valid_ptr p.\n\n    (** Formalizes the notion of \"provides storage\",\n    http://eel.is/c++draft/intro.object#def:provides_storage *)\n    Parameter provides_storage :\n      forall (storage : ptr) (object : ptr) (object_type : type), mpred.\n\n    Axiom provides_storage_persistent :\n      forall storage_ptr obj_ptr ty,\n      Persistent (provides_storage storage_ptr obj_ptr ty).\n    Axiom provides_storage_affine :\n      forall storage_ptr obj_ptr ty,\n      Affine (provides_storage storage_ptr obj_ptr ty).\n    Axiom provides_storage_timeless :\n      forall storage_ptr obj_ptr ty,\n      Timeless (provides_storage storage_ptr obj_ptr ty).\n    #[global] Existing Instances provides_storage_persistent provides_storage_affine provides_storage_timeless.\n\n    (**\n    Typed points-to predicate. Fact [tptsto t q p v] asserts the following things:\n    1. Pointer [p] points to value [v].\n    2. We have fractional ownership [q] (in the separation logic sense).\n    3. Pointer [p] points to a memory location with C++ type [t].\n    However:\n    1. Value [v] need not be initialized.\n    2. Hence, [v] might not satisfy [has_type t v].\n\n    We use this predicate both for pointers to actual memory and for pointers to\n    C++ locations that are not stored in memory (as an optimization).\n    *)\n    Parameter tptsto : forall {σ:genv} (t : type) (q : cQp.t) (a : ptr) (v : val), mpred.\n\n    Axiom tptsto_nonnull : forall {σ} ty q a,\n      @tptsto σ ty q nullptr a |-- False.\n\n    Axiom tptsto_proper :\n      Proper (genv_eq ==> eq ==> eq ==> eq ==> eq ==> (≡)) (@tptsto).\n    Axiom tptsto_mono :\n      Proper (genv_leq ==> eq ==> eq ==> eq ==> eq ==> (⊢)) (@tptsto).\n    #[global] Existing Instances tptsto_proper tptsto_mono.\n\n    #[global] Declare Instance tptsto_timeless : Timeless5 (@tptsto).\n    #[global] Declare Instance tptsto_cfractional {σ} ty : CFractional2 (tptsto ty).\n\n    #[global] Declare Instance tptsto_cfrac_valid {σ} t : CFracValid2 (tptsto t).\n\n    Axiom tptsto_agree : forall {σ} ty q1 q2 p v1 v2,\n      Observe2 [| val_related σ ty v1 v2 |]\n               (@tptsto σ ty q1 p v1)\n               (@tptsto σ ty q2 p v2).\n    #[global] Existing Instances tptsto_agree.\n\n    (* TODO (JH/PG): Add in a proper instance using this which allows us to rewrite\n         `val_related` values within `tptsto`s.\n\n         <https://gitlab.com/bedrocksystems/cpp2v-core/-/merge_requests/377#note_530611061> *)\n    Axiom tptsto_val_related_transport : forall {σ} ty q p v1 v2,\n        [| val_related σ ty v1 v2 |] |-- @tptsto σ ty q p v1 -* @tptsto σ ty q p v2.\n\n    (** The allocation is alive. Neither persistent nor fractional.\n      See https://eel.is/c++draft/basic.stc.general#4 and\n      https://eel.is/c++draft/basic.compound#3.1.\n    *)\n    Parameter live_alloc_id : alloc_id -> mpred.\n    Axiom live_alloc_id_timeless : forall aid, Timeless (live_alloc_id aid).\n    #[global] Existing Instance live_alloc_id_timeless.\n\n    Axiom valid_ptr_alloc_id : forall p,\n      valid_ptr p |-- [| is_Some (ptr_alloc_id p) |].\n\n    (** This pointer is from a live allocation; this does not imply\n    [_valid_ptr], because even overflowing offsets preserve the allocation ID.\n    *)\n    Definition live_ptr (p : ptr) :=\n      default False%I (live_alloc_id <$> ptr_alloc_id p).\n\n    (** We consider [nullptr] as live, following Krebbers, as a way to\n    simplify stating rules for pointer comparison. *)\n    Axiom nullptr_live : |-- live_ptr nullptr.\n\n    Axiom tptsto_live : forall {σ} ty (q : cQp.t) p v,\n      @tptsto σ ty q p v |-- live_ptr p ** True.\n\n    (** [identity σ this mdc q p] state that [p] is a pointer to a (live)\n        object of type [this] that is part of an object that can be reached\n        using the *path* [mdc].\n        - if [mdc = []] then this object identity is not initialized yet,\n          e.g. because its base classes are still being constructed.\n        - otherwise, [mdc] is the *path* from the most derived class to this\n          object. For example, suppose you have:\n          ```c++\n          struct A { virtual int f() { return 0; } };\n          struct B : public A { virtual int f() { return 1; } };\n          struct C : public A { };\n          struct D : public B, public C {};\n\n          int doA(A* a) { return a->f(); }\n          int test() {\n              D d;\n              return doA(static_cast<B*>(&d)) /* = 1 */\n                   + doA(static_cast<C*>(&d)) /* = 0 */;\n          }\n          ```\n          for a fully constructed object of type `D` (at pointer [d]), you would\n          have:\n          [[\n          identity \"::D\" [\"::D\"]           1  d **\n          identity \"::B\" [\"::D\",\"::B\"]      1 (d ., _base \"::B\") **\n          identity \"::A\" [\"::D\",\"::B\",\"::A\"] 1 (d ,, _base \"::B\" ,, _base \"::A\") **\n          identity \"::C\" [\"::D\",\"::C\"]      1 (d ,, _base \"::C\") **\n          idenitty \"::A\" [\"::D\",\"::C\",\"::A\"] 1 (d ,, _base \"::C\" ,, _base \"::A\")\n          ]]\n          in the partially constructed state, where \"::D\" has not yet been constructed\n          but the base classes have been, you have the following:\n          [[\n          identity \"::B\" [\"::B\"]      1 (d ., _base \"::B\") **\n          identity \"::A\" [\"::B\",\"::A\"] 1 (d ,, _base \"::B\" ,, _base \"::A\") **\n          identity \"::C\" [\"::C\"]      1 (d ,, _base \"::C\") **\n          idenitty \"::A\" [\"::C\",\"::A\"] 1 (d ,, _base \"::C\" ,, _base \"::A\")\n          ]]\n          note that you do not get [identity \"::D\" [] 1 d] at this point, you\n          get [identity \"::D\" [\"::D\"] 1 d] when you update all the other identities\n          (but not atomically)\n\n        [identity] is primarily used to dispatch virtual function calls.\n\n        compilers can use the ownership here to represent dynamic dispatch\n        tables.\n     *)\n    Parameter identity : forall {σ : genv}\n        (this : globname) (most_derived : list globname),\n        cQp.t -> ptr -> mpred.\n    #[global] Declare Instance identity_cfractional σ this mdc : CFractional1 (identity this mdc).\n    #[global] Declare Instance identity_cfrac_valid {σ} cls path : CFracValid1 (identity cls path).\n    #[global] Declare Instance identity_timeless : Timeless5 (@identity).\n    #[global] Declare Instance identity_strict_valid σ this mdc q p : Observe (strict_valid_ptr p) (identity this mdc q p).\n\n    (** cpp2v-core#194: Agreement? *)\n\n    (** this allows you to forget an object identity, necessary for doing\n        placement [new] over an existing object.\n     *)\n    Axiom identity_forget : forall σ mdc this p,\n        @identity σ this mdc (cQp.m 1) p |-- |={↑pred_ns}=> @identity σ this nil (cQp.m 1) p.\n\n    (** the pointer points to the code\n\n      note that in the presence of code-loading, function calls will\n      require an extra side-condition that the code is loaded.\n     *)\n    Parameter code_at : genv -> translation_unit -> Func -> ptr -> mpred.\n    Parameter method_at : genv -> translation_unit -> Method -> ptr -> mpred.\n    Parameter ctor_at : genv -> translation_unit -> Ctor -> ptr -> mpred.\n    Parameter dtor_at : genv -> translation_unit -> Dtor -> ptr -> mpred.\n\n    Section with_genv.\n      Context {σ : genv} (tu : translation_unit).\n      #[local] Notation code_at := (code_at σ tu) (only parsing).\n      #[local] Notation method_at := (method_at σ tu) (only parsing).\n      #[local] Notation ctor_at := (ctor_at σ tu) (only parsing).\n      #[local] Notation dtor_at := (dtor_at σ tu) (only parsing).\n\n      Axiom code_at_persistent : forall f p, Persistent (code_at f p).\n      Axiom code_at_affine : forall f p, Affine (code_at f p).\n      Axiom code_at_timeless : forall f p, Timeless (code_at f p).\n\n      Axiom method_at_persistent : forall f p, Persistent (method_at f p).\n      Axiom method_at_affine : forall f p, Affine (method_at f p).\n      Axiom method_at_timeless : forall f p, Timeless (method_at f p).\n\n      Axiom ctor_at_persistent : forall f p, Persistent (ctor_at f p).\n      Axiom ctor_at_affine : forall f p, Affine (ctor_at f p).\n      Axiom ctor_at_timeless : forall f p, Timeless (ctor_at f p).\n\n      Axiom dtor_at_persistent : forall f p, Persistent (dtor_at f p).\n      Axiom dtor_at_affine : forall f p, Affine (dtor_at f p).\n      Axiom dtor_at_timeless : forall f p, Timeless (dtor_at f p).\n\n      #[global] Existing Instances\n        code_at_persistent code_at_affine code_at_timeless\n        method_at_persistent method_at_affine method_at_timeless\n        ctor_at_persistent ctor_at_affine ctor_at_timeless\n        dtor_at_persistent dtor_at_affine dtor_at_timeless.\n\n      Axiom code_at_live   : forall f p,   code_at f p |-- live_ptr p.\n      Axiom method_at_live : forall f p, method_at f p |-- live_ptr p.\n      Axiom ctor_at_live   : forall f p,   ctor_at f p |-- live_ptr p.\n      Axiom dtor_at_live   : forall f p,   dtor_at f p |-- live_ptr p.\n\n      Axiom code_at_strict_valid   : forall f p,   code_at f p |-- strict_valid_ptr p.\n      Axiom method_at_strict_valid : forall f p, method_at f p |-- strict_valid_ptr p.\n      Axiom ctor_at_strict_valid   : forall f p,   ctor_at f p |-- strict_valid_ptr p.\n      Axiom dtor_at_strict_valid   : forall f p,   dtor_at f p |-- strict_valid_ptr p.\n\n    End with_genv.\n\n    Axiom offset_pinned_ptr_pure : forall σ o z va p,\n      eval_offset σ o = Some z ->\n      ptr_vaddr p = Some va ->\n      valid_ptr (p ,, o) |--\n      [| ptr_vaddr (p ,, o) = Some (Z.to_N (Z.of_N va + z)) |].\n\n    Axiom offset_inv_pinned_ptr_pure : forall σ o z va p,\n      eval_offset σ o = Some z ->\n      ptr_vaddr (p ,, o) = Some va ->\n      valid_ptr (p ,, o) |--\n      [| 0 <= Z.of_N va - z |]%Z **\n      [| ptr_vaddr p = Some (Z.to_N (Z.of_N va - z)) |].\n\n    Axiom provides_storage_same_address : forall storage_ptr obj_ptr ty,\n      Observe [| same_address storage_ptr obj_ptr |] (provides_storage storage_ptr obj_ptr ty).\n\n    Axiom provides_storage_valid_storage_ptr : forall storage_ptr obj_ptr aty,\n      Observe (valid_ptr storage_ptr) (provides_storage storage_ptr obj_ptr aty).\n    Axiom provides_storage_valid_obj_ptr : forall storage_ptr obj_ptr aty,\n      Observe (valid_ptr obj_ptr) (provides_storage storage_ptr obj_ptr aty).\n\n    #[global] Existing Instances provides_storage_same_address\n      provides_storage_valid_storage_ptr provides_storage_valid_obj_ptr.\n\n    (**\n    [exposed_aid aid] states that the storage instance identified by [aid] is\n    \"exposed\" [1]. This enables int2ptr casts to produce pointers into this\n    storage instance.\n\n    [1] We use \"exposed\" in the sense defined by the N2577 draft C standard\n    (http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2577.pdf).\n    See https://dl.acm.org/doi/10.1145/3290380 for an introduction.\n    *)\n    Parameter exposed_aid : alloc_id -> mpred.\n    Axiom exposed_aid_persistent : forall aid, Persistent (exposed_aid aid).\n    Axiom exposed_aid_affine : forall aid, Affine (exposed_aid aid).\n    Axiom exposed_aid_timeless : forall aid, Timeless (exposed_aid aid).\n\n    Axiom exposed_aid_null_alloc_id : |-- exposed_aid null_alloc_id.\n\n    #[global] Existing Instances\n      exposed_aid_persistent exposed_aid_affine exposed_aid_timeless.\n\n    (**\n      [type_ptr {resolve := resolve} ty p] asserts that [p] points to\n      a (possibly dead) object of type [ty] (in environment\n      [resolve]), as defined by https://eel.is/c++draft/basic.compound#3.1.\n\n      This implies:\n      - the pointer is strictly valid [type_ptr_strict_valid], and\n        \"p + 1\" is also valid (while possibly past-the-end) [type_ptr_valid_plus_one].\n      - the pointer is not (an offset of) null pointers [type_ptr_off_nonnull, type_ptr_nonnull]\n      - the pointer is properly aligned [type_ptr_aligned_pure]\n\n      [type_ptr] is persistent and survives deallocation of the pointed-to\n      object, like [_valid_ptr].\n\n      TODO: before a complete object is fully initialized,\n      what [type_ptr] facts are available? For now, we only use [type_ptr]\n      for fully initialized objects.\n      Consider http://eel.is/c++draft/basic.memobj#basic.life, especially\n      from http://eel.is/c++draft/basic.memobj#basic.life-1 to\n      http://eel.is/c++draft/basic.memobj#basic.life-4.\n     *)\n    Parameter type_ptr : forall {resolve : genv} (c: type), ptr -> mpred.\n    Axiom type_ptr_persistent : forall σ p ty,\n      Persistent (type_ptr ty p).\n    Axiom type_ptr_affine : forall σ p ty,\n      Affine (type_ptr ty p).\n    Axiom type_ptr_timeless : forall σ p ty,\n      Timeless (type_ptr ty p).\n    #[global] Existing Instances type_ptr_persistent type_ptr_affine type_ptr_timeless.\n\n    Axiom type_ptr_aligned_pure : forall σ ty p,\n      type_ptr ty p |-- [| aligned_ptr_ty ty p |].\n\n    Axiom type_ptr_off_nonnull : forall {σ ty p o},\n      type_ptr ty (p ,, o) |-- [| p <> nullptr |].\n\n    Axiom tptsto_type_ptr : forall (σ : genv) ty q p v,\n      Observe (type_ptr ty p) (tptsto ty q p v).\n    #[global] Existing Instance tptsto_type_ptr.\n\n    (* All objects in the C++ abstract machine have a size\n\n       NOTE to support un-sized objects, we can simply say that the [sizeof] operator\n            in C++ is only a conservative approximation of the true size of an object.\n     *)\n    Axiom type_ptr_size : forall σ ty p,\n        type_ptr ty p |-- [| is_Some (size_of σ ty) |].\n\n    (**\n    Recall that [type_ptr] and [strict_valid_ptr] don't include\n    past-the-end pointers... *)\n    Axiom type_ptr_strict_valid : forall resolve ty p,\n      type_ptr ty p |-- strict_valid_ptr p.\n    (** Hence they can be incremented into (possibly past-the-end) valid pointers. *)\n    Axiom type_ptr_valid_plus_one : forall resolve ty p,\n      type_ptr ty p |-- valid_ptr (p ,, o_sub resolve ty 1).\n\n    (* When [p] is a [ptr] to a C++ object of type [ty], [p] is /also/ a pointer\n       to the \"object representation\" of [ty] - which consists of \"the sequence\n       of [sizeof(ty)] unsigned char objects taken up by the object of\n       type [ty]\" [1].\n\n       Detailed Justification:\n       a) From the comment above the axiomatization of [type_ptr]:\n          | [type_ptr ty p] asserts that [p] points to a (possibly dead) object of type [ty].\n       b) In [basic.types.general#4] [1] the C++ Standard states that:\n          | The object representation of an object of type T is the sequence of N unsigned\n          | char objects taken up by the object of type T, where N equals sizeof(T).\n       d) (NOTE: the C++ Standard lacks language regarding this point) the \"object representation\"\n          for an object pointed to by [ptr] [p] is /also/ accessible via [p].\n       e) (a)+(b)+(d) implies that a (potentially dead) object representation for type [ty]\n          exists at [ptr] [p]\n       f) (a)+(c)+(e) implies that [type_ptr Tu8 (p .[ Tu8 ! i ])] holds (regardless of whether\n          not the object/\"object representation\" is alive)\n\n       NOTE: There is no need to deal with past-the-end pointers explicitly since\n       [type_ptr] explicitly excludes them; validity of past-the-end pointers\n       can be established using [type_ptr_valid_plus_one].\n\n       [1] <https://eel.is/c++draft/basic.types.general#4>\n     *)\n    Section type_ptr_object_representation.\n      (* This section is intended to axiomatize a /sufficient/ and /sound/\n         set of transport rules for [type_ptr] facts which can be used to\n         satisfy the preconditions required when using [ptr_congP] to\n         transport other resources.\n       *)\n\n      (* The following [Axiom] reflects a trivially faithful encoding of\n         the quote from the C++ standard above [Section type_ptr_object_representation].\n\n         NOTE: To practically use this [Axiom], [type_ptr] must be [Persistent];\n         a reasonable alternative axiomatization which sidestepts this issue\n         could produce /all/ of the [type_ptr] facts for the \"object representation\"\n         at once:\n         | ... ->\n         |     type_ptr ty p\n         | |-- [∗list] i ∈ seqN 0 (sizeof ty), type_ptr Tu8 (p .[ Tu8 ! i ])\n       *)\n      Section conservative.\n        Axiom type_ptr_obj_repr_byte :\n          forall (σ : genv) (ty : type) (p : ptr) (i sz : N),\n            size_of σ ty = Some sz -> (* 1) [ty] has some byte-size [sz] *)\n            (i < sz)%N ->             (* 2) by (1), [sz] is nonzero and [i] is a\n                                            byte-offset into the object rooted at [p ,, o]\n\n                                         NOTE: [forall ty, size_of (Tarray ty 0) = Some 0],\n                                         but zero-length arrays are not permitted by the Standard\n                                         (cf. <https://eel.is/c++draft/dcl.array#def:array,bound>).\n                                         NOTE: if support for flexible array members is ever added,\n                                         it will need to be carefully coordinated with these sorts\n                                         of transport lemmas.\n                                       *)\n            (* 4) The existence of the \"object representation\" of an object of type [ty] -\n               |  in conjunction with the premises - justifies \"lowering\" any\n               |  [type_ptr ty p] fact to a collection of [type_ptr Tu8 (p ,, .[Tu8 ! i])]\n               |  facts - where [i] is a byte-offset within the [ty] ([0 <= i < sizeof(ty)]).\n               v *)\n            type_ptr ty p |-- type_ptr Tu8 (p ,, .[ Tu8 ! i ]).\n      End conservative.\n\n      (* NOTE: This might be reasonable to axiomatize directly; cf. the [NOTE] above\n         [Section conservative].\n       *)\n      Section all_at_once.\n        Lemma type_ptr_obj_repr :\n          forall (σ : genv) (ty : type) (p : ptr) (sz : N),\n            size_of σ ty = Some sz ->\n            type_ptr ty p |-- [∗list] i ∈ seqN 0 sz, type_ptr Tu8 (p .[ Tu8 ! Z.of_N i ]).\n        Proof.\n          intros * Hsz; iIntros \"#tptr\".\n          iApply big_sepL_intro; iIntros \"!>\" (k n) \"%Hn'\".\n          assert (lookup (K:=N) (N.of_nat k) (seqN 0%N sz) = Some n)\n            as Hn\n            by (unfold lookupN, list_lookupN; rewrite Nat2N.id //);\n            clear Hn'.\n          apply lookupN_seqN in Hn as [? ?].\n          iDestruct (type_ptr_obj_repr_byte σ ty p n sz Hsz ltac:(lia) with \"tptr\") as \"$\".\n        Qed.\n      End all_at_once.\n    End type_ptr_object_representation.\n\n    (* [offset_congP] hoists [offset_cong] to [mpred] *)\n    Definition offset_congP (σ : genv) (o1 o2 : offset) : mpred :=\n      [| offset_cong σ o1 o2 |].\n\n    (* [ptr_congP σ p1 p2] is an [mpred] which quotients [ptr_cong σ p1 p2]\n       by requiring that [type_ptr Tu8] holds for both [p1] /and/ [p2]. This property\n       is intended to be sound and sufficient for transporting certain physical\n       resources between [p1] and [p2] - and we hypothesize that it is also\n       necessary.\n     *)\n    Definition ptr_congP (σ : genv) (p1 p2 : ptr) : mpred :=\n      [| ptr_cong σ p1 p2 |] ** type_ptr Tu8 p1 ** type_ptr Tu8 p2.\n\n    (* All [tptsto Tu8] facts can be transported over [ptr_congP] [ptr]s.\n\n       High level meaning:\n       In the C++ object model, a single byte of storage can be accessed through different pointers,\n       e.g. consider [struct C { int x; int y; } c;]. The first byte of the struct can be read through\n       [static_cast<byte*>(&c)] (with pointer representation [c]) as well as [static_cast<byte*>(&c.x)]\n       (with pointer representation [c ,, _field \"::C\" \"x\"]). To put an ownership discipline on this\n       single byte, we build an equivalence relation on pointers that allows us to transport ownership\n       of the byte between these different pointers. For example, half of the ownership could live at [c]\n       and the other half of the ownership can live at [c ,, _field \"::C\" \"x\"].\n\n       The standard justifies this as follows:\n       1) (cf. [tptsto] comment) [tptsto ty q p v] ensures that [p] points to a memory\n          location with C++ type [ty] and which has some value [v].\n       2) (cf. [Section type_ptr_object_representation]) [type_ptr Tu8] holds for all of the\n          bytes (i.e. the \"object reprsentation\") constituting well-typed C++ objects.\n       3) NOTE (JH): the following isn't quite true yet, but we'll want this when we flesh\n          out [rawR]/[RAW_BYTES]:\n          a) all values [v] can be converted into (potentially many) [raw_byte]s -\n             which capture its \"object representation\"\n          b) all [tptsto ty] facts can be shattered into (potentially many)\n             [tptsto Tu8 _ _ (Vraw _)] facts corresponding to its \"object representation\"\n       4) [tptsto Tu8 _ _ (Vraw _)] can be transported over [ptr_congP] [ptr]s:\n          a) [tptso Tu8 _ _ (Vraw _)] facts deal with the \"object representation\" directly\n             and thus permit erasing the structure of pointers in favor of reasoning about\n             relative byte offsets from a shared [ptr]-prefix.\n          b) the [ptr]s are [ptr_congP] so we know that:\n             i) they share a common base pointer [p_base]\n             ii) the byte-offset values of the C++ offsets which reconstitute the src/dst from\n                 [p_base] are equal\n             iii) NOTE: (cf. [valid_ptr_nonnull_nonzero]/[type_ptr_valid_ptr]/[type_ptr_nonnull] below)\n                  [p_base] has some [vaddr], but we don't currently rely on this fact.\n     *)\n    (* TODO: improve our axiomatic support for raw values - including \"shattering\"\n       non-raw values into their constituent raw pieces - to enable deriving\n       [tptsto_ptr_congP_transport] from [tptsto_raw_ptr_congP_transport].\n     *)\n    Axiom tptsto_ptr_congP_transport : forall {σ} q p1 p2 v,\n      ptr_congP σ p1 p2 |-- @tptsto σ Tu8 q p1 v -* @tptsto σ Tu8 q p2 v.\n\n    (**\n     ** Deducing pointer equalities\n     The following axioms, together with [same_address_o_sub_eq], enable going\n     from [same_address] (produced by C++ pointer equality) to actual pointer\n     equalities.\n     *)\n\n    (** Pointer equality with [nullptr] is easy, as long as your pointer is valid.\n     Validity is necessary: the C++ expression [(char * )p - (uintptr_t) p]\n     produces an invalid pointer with address 0, which is not [nullptr] because\n     it preserves the provenance of [p]. *)\n    Axiom same_address_eq_null : forall p tv,\n      _valid_ptr tv p |--\n      [| same_address p nullptr <-> p = nullptr |].\n\n    (**\n    [same_address_eq_type_ptr] concludes that two pointers [p1] and [p2] are\n    equal if they have the same address, point to live objects [o1] and [o2],\n    and have the same (non-uchar) type [ty] with nonzero size.\n\n    Justifying this from the standard is tricky; here's a proof sketch.\n    - Because [ty] has \"nonzero size\" (https://eel.is/c++draft/intro.object#8),\n      and we don't support bitfields, we apply the standard:\n\n      > Unless it is a bit-field, an object with nonzero size shall occupy one\n        or more bytes of storage, including every byte that is occupied in full\n        or in part by any of its subobjects.\n\n    - Because [o1] and [o2] are live, these objects share storage, hence they\n      must coincide or one must be nested inside the other\n      (https://eel.is/c++draft/intro.object#4); if they coincide, our proof\n      is done.\n    - Because [ty] is not [unsigned char], neither pointer can provide storage\n      for the other (https://eel.is/c++draft/intro.object#3); so one must be a\n      subobject of the other.\n    - Since [o1] and [o2] have type [ty], and type [ty] has \"nonzero size\",\n      neither of [o1] and [o2] can be a subobject of the other;\n      we conjecture is provable from the C++ type system.\n\n    NOTE: we check \"nonzero size\"\n    (https://eel.is/c++draft/basic.memobj#intro.object-8) using [size_of],\n    which might incorporate implementation-specific compiler decisions.\n    TODO: handle [std::byte] like [unsigned char].\n    *)\n    Axiom same_address_eq_type_ptr : forall resolve ty p1 p2 n,\n      same_address p1 p2 ->\n      size_of resolve ty = Some n ->\n      (* if [ty = Tuchar], one of these pointer could provide storage for the other. *)\n      ty <> Tuchar ->\n      (n > 0)%N ->\n      type_ptr ty p1 ∧ type_ptr ty p2 ∧ live_ptr p1 ∧ live_ptr p2 ⊢\n        |={↑pred_ns}=> [| p1 = p2 |].\n  End with_cpp.\n\n  (* strict validity (not past-the-end) *)\n  Notation strict_valid_ptr := (_valid_ptr Strict).\n  (* validity (past-the-end allowed) *)\n  Notation valid_ptr := (_valid_ptr Relaxed).\nEnd CPP_LOGIC.\n\n(* Pointer axioms. XXX Not modeled for now. *)\nModule Type VALID_PTR_AXIOMS\n  (Import P : PTRS_INTF)\n  (Import INTF : VALUES_INTF_FUNCTOR P)\n  (Import CC : CPP_LOGIC_CLASS)\n  (Import CPP : CPP_LOGIC P INTF CC).\n\n  Implicit Types (p : ptr).\n\n  Section with_cpp.\n    Context `{cpp_logic} {σ : genv}.\n\n    Axiom invalid_ptr_invalid : forall vt,\n      _valid_ptr vt invalid_ptr |-- False.\n\n    (** Justified by [https://eel.is/c++draft/expr.add#4.1]. *)\n    Axiom _valid_ptr_nullptr_sub_false : forall vt ty (i : Z) (_ : i <> 0),\n      _valid_ptr vt (nullptr ,, o_sub σ ty i) |-- False.\n    (*\n    TODO Controversial; if [f] is the first field, [nullptr->f] or casts relying on\n    https://eel.is/c++draft/basic.compound#4 might invalidate this.\n    To make this valid, we could ensure our axiomatic semantics produces\n    [nullptr] instead of [nullptr ., o_field]. *)\n    (* Axiom _valid_ptr_nullptr_field_false : forall vt f,\n      _valid_ptr vt (nullptr ,, o_field σ f) |-- False. *)\n\n    (** These axioms are named after the predicate in the conclusion. *)\n\n    (**\n    TODO: The intended proof of [strict_valid_ptr_sub] assumes that, if [p']\n    normalizes to [p ., [ ty ! i ]], then [valid_ptr p'] is defined to imply\n    validity of all pointers from [p] to [p'].\n\n    Note that `arrR` exposes stronger reasoning principles, but this might still be useful.\n    *)\n    Axiom strict_valid_ptr_sub : ∀ (i j k : Z) p ty vt1 vt2,\n      (i <= j < k)%Z ->\n      _valid_ptr vt1 (p ,, o_sub σ ty i) |--\n      _valid_ptr vt2 (p ,, o_sub σ ty k) -* strict_valid_ptr (p ,, o_sub σ ty j).\n\n    (** XXX: this axiom is convoluted but\n    TODO: The intended proof of [strict_valid_ptr_field_sub] (and friends) is that\n    (1) if [p'] normalizes to [p'' ., [ ty ! i ]], then [valid_ptr p'] implies\n    [valid_ptr p''].\n    (2) [p ,, o_field σ f ,, o_sub σ ty i] will normalize to [p ,, o_field\n    σ f ,, o_sub σ ty i], without cancellation.\n    *)\n    Axiom strict_valid_ptr_field_sub : ∀ (p : ptr) ty (i : Z) f vt,\n      (0 < i)%Z ->\n      _valid_ptr vt (p ,, o_field σ f ,, o_sub σ ty i) |-- strict_valid_ptr (p ,, o_field σ f).\n\n    (* TODO: can we deduce that [p] is strictly valid? *)\n    Axiom _valid_ptr_field : ∀ p f vt,\n      _valid_ptr vt (p ,, o_field σ f) |-- _valid_ptr vt p.\n    (* TODO: Pointers to fields can't be past-the-end, right?\n    Except 0-size arrays. *)\n    (* Axiom strict_valid_ptr_field : ∀ p f,\n      valid_ptr (p ,, o_field σ f) |--\n      strict_valid_ptr (p ,, o_field σ f). *)\n    (* TODO: if we add [strict_valid_ptr_field], we can derive\n    [_valid_ptr_field] from just [strict_valid_ptr_field] *)\n    (* Axiom strict_valid_ptr_field : ∀ p f,\n      strict_valid_ptr (p ,, o_field σ f) |-- strict_valid_ptr p. *)\n\n    (* We're ignoring virtual inheritance here, since we have no plans to\n    support it for now, but this might hold there too. *)\n\n    (* We're ignoring virtual inheritance here, since we have no plans to\n    support it for now, but this might hold there too. *)\n    Axiom o_base_directly_derives : forall p base derived,\n      strict_valid_ptr (p ,, o_base σ derived base) |--\n      [| directly_derives σ derived base |].\n\n    Axiom o_derived_directly_derives : forall p base derived,\n      strict_valid_ptr (p ,, o_derived σ base derived) |--\n      [| directly_derives σ derived base |].\n\n    (* TODO: maybe add a validity of offsets to allow stating this more generally. *)\n    Axiom valid_o_sub_size : forall p ty i vt,\n      _valid_ptr vt (p ,, o_sub σ ty i) |-- [| is_Some (size_of σ ty) |].\n\n    Axiom type_ptr_o_base : forall derived base p,\n      class_derives derived [base] ->\n      type_ptr (Tnamed derived) p ⊢ type_ptr (Tnamed base) (p ,, _base derived base).\n\n    Axiom type_ptr_o_field_type_ptr : forall p fld cls (st : Struct),\n      glob_def σ cls = Some (Gstruct st) ->\n      fld ∈ s_fields st →\n      type_ptr (Tnamed cls) p ⊢ type_ptr fld.(mem_type) (p .,\n        {| f_name := fld.(mem_name) ; f_type := cls |}).\n\n    Axiom type_ptr_o_sub : forall p (m n : N) ty,\n      (m < n)%N ->\n      type_ptr (Tarray ty n) p ⊢ type_ptr ty (p ,, _sub ty m).\n  End with_cpp.\nEnd VALID_PTR_AXIOMS.\n\nDeclare Module L : CPP_LOGIC PTRS_INTF_AXIOM VALUES_INTF_AXIOM LC.\nExport L.\n\nDeclare Module Export VALID_PTR : VALID_PTR_AXIOMS PTRS_INTF_AXIOM VALUES_INTF_AXIOM LC L.\n\nSection valid_ptr_code.\n  Context `{Σ : cpp_logic} {σ : genv} (tu : translation_unit).\n\n  Lemma code_at_valid   : forall f p,   code_at _ tu f p |-- valid_ptr p.\n  Proof. intros. rewrite code_at_strict_valid; apply strict_valid_valid. Qed.\n  Lemma method_at_valid : forall f p, method_at _ tu f p |-- valid_ptr p.\n  Proof. intros. rewrite method_at_strict_valid; apply strict_valid_valid. Qed.\n  Lemma ctor_at_valid   : forall f p,   ctor_at _ tu f p |-- valid_ptr p.\n  Proof. intros. rewrite ctor_at_strict_valid; apply strict_valid_valid. Qed.\n  Lemma dtor_at_valid   : forall f p,   dtor_at _ tu f p |-- valid_ptr p.\n  Proof. intros. rewrite dtor_at_strict_valid; apply strict_valid_valid. Qed.\nEnd valid_ptr_code.\n\nSection pinned_ptr_def.\n  Context `{Σ : cpp_logic}.\n\n  Definition exposed_ptr_def p : mpred :=\n    valid_ptr p ** ∃ aid, [| ptr_alloc_id p = Some aid |] ** exposed_aid aid.\n  Definition exposed_ptr_aux : seal exposed_ptr_def. Proof. by eexists. Qed.\n  Definition exposed_ptr := exposed_ptr_aux.(unseal).\n  Definition exposed_ptr_eq : exposed_ptr = _ := exposed_ptr_aux.(seal_eq).\n\n  #[global] Hint Opaque exposed_ptr : typeclass_instances.\n\n  #[global] Instance exposed_ptr_persistent p : Persistent (exposed_ptr p).\n  Proof. rewrite exposed_ptr_eq. apply _. Qed.\n  #[global] Instance exposed_ptr_affine p : Affine (exposed_ptr p).\n  Proof. rewrite exposed_ptr_eq. apply _. Qed.\n  #[global] Instance exposed_ptr_timeless p : Timeless (exposed_ptr p).\n  Proof. rewrite exposed_ptr_eq. apply _. Qed.\n  #[global] Instance exposed_ptr_valid p :\n    Observe (valid_ptr p) (exposed_ptr p).\n  Proof. rewrite exposed_ptr_eq. apply _. Qed.\n\n  Lemma exposed_ptr_nullptr : |-- exposed_ptr nullptr.\n  Proof.\n    rewrite exposed_ptr_eq /exposed_ptr_def ptr_alloc_id_nullptr.\n    iDestruct valid_ptr_nullptr as \"$\". iExists _.\n    by iDestruct exposed_aid_null_alloc_id as \"$\".\n  Qed.\n\n  Lemma offset_exposed_ptr p o :\n    valid_ptr (p ,, o) |-- exposed_ptr p -* exposed_ptr (p ,, o).\n  Proof.\n    rewrite exposed_ptr_eq /exposed_ptr_def.\n    iIntros \"#V' #[V E]\". iDestruct (valid_ptr_alloc_id with \"V'\") as %?.\n    iFrame \"V'\". by rewrite ptr_alloc_id_offset.\n  Qed.\n\n  Lemma offset2_exposed_ptr p o1 o2 :\n    valid_ptr (p ,, o2) |-- exposed_ptr (p ,, o1) -* exposed_ptr (p ,, o2).\n  Proof.\n    rewrite exposed_ptr_eq /exposed_ptr_def.\n    iIntros \"#V2 #[V1 E]\"; iFrame \"V2\".\n    iDestruct (valid_ptr_alloc_id with \"V1\") as %?.\n    iDestruct (valid_ptr_alloc_id with \"V2\") as %?.\n    by rewrite ptr_alloc_id_offset // ptr_alloc_id_offset.\n  Qed.\n\n  Lemma offset_inv_exposed_ptr p o :\n    valid_ptr p |-- exposed_ptr (p ,, o) -* exposed_ptr p.\n  Proof. rewrite -{1 3}(offset_ptr_id p). apply offset2_exposed_ptr. Qed.\n\n  (** Physical representation of pointers. *)\n  (** [pinned_ptr va p] states that the abstract pointer [p] is tied to a\n    virtual address [va].\n    [pinned_ptr] will only hold on pointers that are associated to addresses,\n    but other pointers exist. *)\n  Definition pinned_ptr_def (va : vaddr) (p : ptr) : mpred :=\n    [| ptr_vaddr p = Some va |] ** exposed_ptr p.\n  Definition pinned_ptr_aux : seal pinned_ptr_def. Proof. by eexists. Qed.\n  Definition pinned_ptr := pinned_ptr_aux.(unseal).\n  Definition pinned_ptr_eq : pinned_ptr = _ := pinned_ptr_aux.(seal_eq).\n\n  #[global] Hint Opaque pinned_ptr : typeclass_instances.\n\n  #[global] Instance pinned_ptr_persistent va p : Persistent (pinned_ptr va p).\n  Proof. rewrite pinned_ptr_eq. apply _. Qed.\n  #[global] Instance pinned_ptr_affine va p : Affine (pinned_ptr va p).\n  Proof. rewrite pinned_ptr_eq. apply _. Qed.\n  #[global] Instance pinned_ptr_timeless va p : Timeless (pinned_ptr va p).\n  Proof. rewrite pinned_ptr_eq. apply _. Qed.\n\n  Lemma pinned_ptr_intro p va :\n    ptr_vaddr p = Some va -> exposed_ptr p |-- pinned_ptr va p.\n  Proof. rewrite pinned_ptr_eq /pinned_ptr_def. by iIntros (?) \"$\". Qed.\n\n  #[global] Instance pinned_ptr_ptr_vaddr va p :\n    Observe [| ptr_vaddr p = Some va |] (pinned_ptr va p).\n  Proof. rewrite pinned_ptr_eq. apply _. Qed.\n\n  Lemma pinned_ptr_change_va_eq (p : ptr) (va va' : vaddr)\n    (Heq : ptr_vaddr p = Some va) :\n    pinned_ptr va' p |--  [| va' = va |] ** pinned_ptr va p.\n  Proof.\n    iIntros \"#P\".\n    iDestruct (observe_elim_pure (ptr_vaddr p = Some va') with \"P\") as %?.\n    simplify_eq. auto.\n  Qed.\n\n  Lemma pinned_ptr_change_va p va va'\n    (Heq : ptr_vaddr p = Some va) :\n    pinned_ptr va' p |-- pinned_ptr va p.\n  Proof. rewrite pinned_ptr_change_va_eq //. by iIntros \"[_ $]\". Qed.\n\n  #[global] Instance pinned_ptr_agree va1 va2 p :\n    Observe2 [| va1 = va2 |] (pinned_ptr va1 p) (pinned_ptr va2 p).\n  Proof.\n    iIntros \"#P1 #P2 !>\".\n    iDestruct (observe_elim_pure (_ = _) with \"P1\") as %?.\n    iDestruct (observe_elim_pure (_ = _) with \"P2\") as %?; simplify_eq.\n    by [].\n  Qed.\n\n  #[global] Instance pinned_ptr_valid va p :\n    Observe (valid_ptr p) (pinned_ptr va p).\n  Proof. rewrite pinned_ptr_eq. apply _. Qed.\n\n  (** Just a corollary of [provides_storage_same_address] in the style of\n  [provides_storage_pinned_ptr]. *)\n  Lemma provides_storage_pinned_ptr_pure {storage_ptr obj_ptr aty va} :\n    ptr_vaddr storage_ptr = Some va ->\n    provides_storage storage_ptr obj_ptr aty |-- [| ptr_vaddr obj_ptr = Some va |].\n  Proof. rewrite provides_storage_same_address. by iIntros (HP <-). Qed.\nEnd pinned_ptr_def.\n\n#[deprecated(note=\"Use pinned_ptr_ptr_vaddr\", since=\"2022-01-18\")]\nNotation pinned_ptr_pinned_ptr_pure := pinned_ptr_ptr_vaddr (only parsing).\n\nSection with_cpp.\n  Context `{Σ : cpp_logic} {σ : genv}.\n\n  Lemma same_address_bool_null p tv :\n    _valid_ptr tv p |--\n    [| same_address_bool p nullptr = bool_decide (p = nullptr) |].\n  Proof. rewrite same_address_eq_null; iIntros \"!%\". apply bool_decide_ext. Qed.\n\n  Lemma valid_ptr_zero_null p :\n    ptr_vaddr p = Some 0%N ->\n    valid_ptr p |-- [| p = nullptr |].\n  Proof.\n    rewrite same_address_eq_null.\n    iIntros (Haddr [Hsuff _]) \"!%\". apply: Hsuff.\n    rewrite same_address_iff ptr_vaddr_nullptr; naive_solver.\n  Qed.\n\n  Lemma valid_ptr_nonnull_nonzero p :\n    p <> nullptr ->\n    valid_ptr p |-- [| ptr_vaddr p <> Some 0%N |].\n  Proof.\n    destruct (decide (ptr_vaddr p = Some 0%N)); last naive_solver.\n    rewrite valid_ptr_zero_null; naive_solver.\n  Qed.\n\n  Lemma type_ptr_nonnull ty p :\n    type_ptr ty p |-- [| p <> nullptr |].\n  Proof. rewrite -{1}(offset_ptr_id p). apply type_ptr_off_nonnull. Qed.\n\n  #[global] Instance type_ptr_observe_nonnull ty p :\n    Observe [| p <> nullptr |] (type_ptr ty p).\n  Proof. rewrite type_ptr_nonnull. refine _. Qed.\n\n  #[global] Instance provides_storage_preserves_nullptr {storage_ptr obj_ptr aty} :\n    Observe [| storage_ptr = nullptr <-> obj_ptr = nullptr |] (provides_storage storage_ptr obj_ptr aty).\n  Proof.\n    apply observe_intro_only_provable; iIntros \"PS\".\n    iDestruct (provides_storage_same_address with \"PS\") as %Hsm.\n    iDestruct (provides_storage_valid_obj_ptr with \"PS\") as \"#VO\".\n    iDestruct (provides_storage_valid_storage_ptr with \"PS\") as \"#VS {PS}\".\n    iDestruct (same_address_eq_null with \"VO\") as %[HeqO _].\n    iDestruct (same_address_eq_null with \"VS\") as %[HeqS _].\n    iIntros \"!%\"; split; intros ->.\n    - apply HeqO, symmetry, Hsm.\n    - apply HeqS, Hsm.\n  Qed.\n\n  #[global] Instance provides_storage_preserves_nonnull {storage_ptr obj_ptr aty} :\n    Observe [| storage_ptr <> nullptr <-> obj_ptr <> nullptr |] (provides_storage storage_ptr obj_ptr aty).\n  Proof.\n    apply observe_intro_only_provable. iIntros \"PS\".\n    by iDestruct (provides_storage_preserves_nullptr with \"PS\") as \"#-> {PS}\".\n  Qed.\n\n  #[global] Instance pinned_ptr_unique va va' p :\n    Observe2 [| va = va' |] (pinned_ptr va p) (pinned_ptr va' p).\n  Proof.\n    rewrite pinned_ptr_eq.\n    iIntros \"[%H1 _] [%H2 _] !> !%\". congruence.\n  Qed.\n\n  Lemma offset_2_pinned_ptr_pure o1 o2 z1 z2 va p :\n    eval_offset σ o1 = Some z1 ->\n    eval_offset σ o2 = Some z2 ->\n    ptr_vaddr (p ,, o1) = Some va ->\n    valid_ptr p |-- valid_ptr (p ,, o1) -* valid_ptr (p ,, o2) -*\n    [| ptr_vaddr (p ,, o2) = Some (Z.to_N (Z.of_N va - z1 + z2)) |].\n  Proof.\n    iIntros (He1 He2 Hpin1) \"V V1 V2\".\n    iDestruct (offset_inv_pinned_ptr_pure with \"V1\") as %[??]; [done..|].\n    iDestruct (offset_pinned_ptr_pure with \"V2\") as %Hgoal; [done..|].\n    iIntros \"!%\". by rewrite Z2N.id in Hgoal.\n  Qed.\n\n  Lemma pinned_ptr_null : |-- pinned_ptr 0 nullptr.\n  Proof.\n    rewrite pinned_ptr_eq /pinned_ptr_def.\n    iFrame (ptr_vaddr_nullptr).\n    iApply exposed_ptr_nullptr.\n  Qed.\n\n  #[global] Instance pinned_ptr_zero_is_null (p : ptr) :\n    Observe [| p = nullptr |] (pinned_ptr 0 p).\n  Proof.\n    rewrite pinned_ptr_eq /pinned_ptr_def.\n    iIntros \"[%Heq #E]\".\n    rewrite -valid_ptr_zero_null //.\n    by iApply (exposed_ptr_valid with \"E\").\n  Qed.\n\n  #[global] Instance pinned_ptr_null_is_zero addr :\n    Observe [| addr = 0 |]%N (pinned_ptr addr nullptr).\n  Proof.\n    rewrite pinned_ptr_eq /pinned_ptr_def ptr_vaddr_nullptr.\n    apply: (observe_derive_only_provable (Some 0%N = Some addr)); naive_solver.\n  Qed.\n\n  Lemma pinned_ptr_same_address pp1 pp2 v :\n    same_address pp1 pp2 ->\n    exposed_ptr pp2 |-- pinned_ptr v pp1 -* pinned_ptr v pp2.\n  Proof.\n    rewrite pinned_ptr_eq/pinned_ptr_def.\n    by iIntros ((? & -> & ->)%same_address_iff) \"$ [%Hp _] !%\".\n  Qed.\n\n  Lemma offset_pinned_ptr o z va p :\n    eval_offset _ o = Some z ->\n    valid_ptr (p ,, o) |--\n    pinned_ptr va p -* pinned_ptr (Z.to_N (Z.of_N va + z)) (p ,, o).\n  Proof.\n    rewrite pinned_ptr_eq /pinned_ptr_def.\n    iIntros (He) \"#V' #(%P & E)\".\n    iDestruct (offset_pinned_ptr_pure with \"V'\") as \"$\"; [done..|].\n    by iApply offset_exposed_ptr.\n  Qed.\n\n  Lemma offset_inv_pinned_ptr o z va p :\n    eval_offset _ o = Some z ->\n    valid_ptr p |-- pinned_ptr va (p ,, o) -*\n    [| 0 <= Z.of_N va - z |]%Z ** pinned_ptr (Z.to_N (Z.of_N va - z)) p.\n  Proof.\n    rewrite pinned_ptr_eq /pinned_ptr_def.\n    iIntros (He) \"#V #(%P & E)\".\n    iDestruct (offset_inv_pinned_ptr_pure with \"[]\") as \"-#[$$]\"; [done..| |].\n    { by iApply (observe with \"E\"). }\n    by iApply offset_inv_exposed_ptr.\n  Qed.\n\n  Lemma offset2_pinned_ptr o1 o2 z1 z2 va p :\n    eval_offset σ o1 = Some z1 ->\n    eval_offset σ o2 = Some z2 ->\n    valid_ptr p |-- valid_ptr (p ,, o1) -* valid_ptr (p ,, o2) -*\n    pinned_ptr va (p ,, o1) -*\n    pinned_ptr (Z.to_N (Z.of_N va - z1 + z2)) (p ,, o2).\n  Proof.\n    rewrite pinned_ptr_eq /pinned_ptr_def.\n    iIntros (He1 He2) \"V V1 #V2 #(%P & E)\".\n    iDestruct (offset_2_pinned_ptr_pure with \"V V1 V2\") as \"$\"; [done..|].\n    by iApply offset2_exposed_ptr.\n  Qed.\n\n  Lemma pinned_ptr_aligned_divide va n p :\n    pinned_ptr va p ⊢\n    [| aligned_ptr n p <-> (n | va)%N |].\n  Proof.\n    rewrite pinned_ptr_eq /pinned_ptr_def; iIntros \"(%P & _) !%\".\n    exact: pinned_ptr_pure_aligned_divide.\n  Qed.\n\n  Lemma pinned_ptr_pure_type_divide_1 va n p ty\n    (Hal : align_of ty = Some n) :\n    type_ptr ty p ⊢ [| ptr_vaddr p = Some va |] -∗ [| (n | va)%N |].\n  Proof.\n    rewrite type_ptr_aligned_pure. iIntros \"!%\".\n    exact: pinned_ptr_pure_divide_1.\n  Qed.\n\n  Lemma pinned_ptr_type_divide_1 va n p ty\n    (Hal : align_of ty = Some n) :\n    type_ptr ty p ⊢ pinned_ptr va p -∗ [| (n | va)%N |].\n  Proof.\n    rewrite pinned_ptr_eq /pinned_ptr_def.\n    iIntros \"#? #(? & _)\". by iApply pinned_ptr_pure_type_divide_1.\n  Qed.\n\n  Lemma shift_pinned_ptr_sub ty z va (p1 p2 : ptr) o:\n    size_of σ ty = Some o ->\n    p1 ,, o_sub _ ty z = p2 ->\n        valid_ptr p2 ** pinned_ptr va p1\n    |-- pinned_ptr (Z.to_N (Z.of_N va + z * Z.of_N o)) p2.\n  Proof.\n    move => o_eq <-.\n    iIntros \"[val pin1]\".\n    iApply (offset_pinned_ptr _ with \"val\") => //.\n    rewrite eval_o_sub o_eq /= Z.mul_comm //.\n  Qed.\n\n  Lemma _valid_valid p vt : _valid_ptr vt p |-- valid_ptr p.\n  Proof. case: vt => [|//]. exact: strict_valid_valid. Qed.\n\n  Lemma valid_ptr_sub (i j k : Z) p ty vt\n    (Hj : (i <= j <= k)%Z) :\n    _valid_ptr vt (p ,, o_sub σ ty i) |--\n    _valid_ptr vt (p ,, o_sub σ ty k) -* valid_ptr (p ,, o_sub σ ty j).\n  Proof.\n    destruct (decide (j = k)) as [->|Hne].\n    { rewrite -_valid_valid. by iIntros \"_ $\". }\n    rewrite -strict_valid_valid. apply strict_valid_ptr_sub. lia.\n  Qed.\n\n  Lemma _valid_ptr_field_sub (i : Z) (p : ptr) ty f vt (Hle : (0 <= i)%Z) :\n    _valid_ptr vt (p ,, o_field σ f ,, o_sub σ ty i) |-- _valid_ptr vt (p ,, o_field σ f).\n  Proof.\n    iIntros \"V\". case: (decide (i = 0)%Z) Hle => [-> _|Hne Hle].\n    - iDestruct (valid_o_sub_size with \"V\") as %?.\n      by rewrite offset_ptr_sub_0.\n    - rewrite strict_valid_ptr_field_sub; last by lia.\n      case: vt => //. by rewrite strict_valid_valid.\n  Qed.\n\n  Lemma o_base_derived_strict p base derived :\n    strict_valid_ptr (p ,, o_base σ derived base) |--\n    [| p ,, o_base σ derived base ,, o_derived σ base derived = p |].\n  Proof.\n    rewrite o_base_directly_derives. f_equiv => ?. exact: o_base_derived.\n  Qed.\n\n  Lemma o_derived_base_strict p base derived :\n    strict_valid_ptr (p ,, o_derived σ base derived) |--\n    [| p ,, o_derived σ base derived ,, o_base σ derived base = p |].\n  Proof.\n    rewrite o_derived_directly_derives. f_equiv => ?. exact: o_derived_base.\n  Qed.\n\n  Lemma o_derived_base_type p base derived ty :\n    type_ptr ty (p ,, o_derived σ base derived) |--\n    [| p ,, o_derived σ base derived ,, o_base σ derived base = p |].\n  Proof. rewrite type_ptr_strict_valid. apply (o_derived_base_strict p). Qed.\n\n  (** [_inv] because unlike [type_ptr_o_base] and [type_ptr_o_field_type_ptr],\n  this lemma fits the [type_ptr _ (p ,, o) ⊢ type_ptr _ p] schema instead of the\n  converse. *)\n  Lemma type_ptr_o_derived_inv derived base p :\n    class_derives derived [base] ->\n    type_ptr (Tnamed derived) (p ,, _derived base derived) |--\n    type_ptr (Tnamed base) p.\n  Proof.\n    iIntros (Hcd) \"T\".\n    iDestruct (o_derived_base_type with \"T\") as %Hp.\n    by rewrite (type_ptr_o_base _ _ _ Hcd) Hp.\n  Qed.\n\n  (** [p] is a valid pointer value in the sense of the standard, or\n  \"standard-valid\" (https://eel.is/c++draft/basic.compound#3.1), that is both\n  valid (in our sense) and live.\n\n  In particular, [p] is a valid pointer value even when accounting for\n  pointer zapping.\n  *)\n  Definition _valid_live_ptr vt (p : ptr) : mpred :=\n    _valid_ptr vt p ∗ live_ptr p.\n  Definition valid_live_ptr p : mpred := _valid_live_ptr Relaxed p.\n  Definition strict_valid_live_ptr p : mpred := _valid_live_ptr Strict p.\n\n  #[global] Instance tptsto_flip_mono :\n    Proper (flip genv_leq ==> eq ==> eq ==> eq ==> eq ==> flip (⊢))\n      (@tptsto _ Σ).\n  Proof. repeat intro. exact: tptsto_mono. Qed.\n\n  #[global] Instance tptsto_as_cfractional ty : AsCFractional2 (tptsto ty).\n  Proof. solve_as_cfrac. Qed.\n\n  #[global] Instance identity_as_cfractional this mdc :\n    AsCFractional1 (identity this mdc).\n  Proof. solve_as_cfrac. Qed.\n\n  #[global] Instance tptsto_observe_nonnull t q p v :\n    Observe [| p <> nullptr |] (tptsto t q p v).\n  Proof.\n    apply: observe_intro.\n    destruct (ptr_eq_dec p nullptr); subst; last by eauto.\n    rewrite {1}tptsto_nonnull. exact: bi.False_elim.\n  Qed.\n\n  Lemma tptsto_disjoint ty c1 c2 q p v1 v2 :\n    tptsto ty (cQp.mk c1 1) p v1 ** tptsto ty (cQp.mk c2 q) p v2 |-- False.\n  Proof.\n    iIntros \"[T1 T2]\".\n    iDestruct (tptsto_agree with \"T1 T2\") as %Hvs.\n    iDestruct (tptsto_val_related_transport $! Hvs with \"T1\") as \"T1\".\n    iCombine \"T1 T2\" as \"T\".\n    by iDestruct (cfrac_valid_2 with \"T\") as %?%Qp.not_add_le_l.\n  Qed.\n\n  (** *** Just wrappers. *)\n  (** We can lift validity entailments through [Observe] (using\n  [Observe_mono]. These are not instances, to avoid causing slowdowns in\n  proof search. *)\n  Lemma observe_strict_valid_valid\n    `(Hobs : !Observe (strict_valid_ptr p) P) : Observe (valid_ptr p) P.\n  Proof. by rewrite -strict_valid_valid. Qed.\n\n  Lemma observe_type_ptr_strict_valid\n    `(Hobs : !Observe (type_ptr ty p) P) : Observe (strict_valid_ptr p) P.\n  Proof. by rewrite -type_ptr_strict_valid. Qed.\n\n  Lemma observe_type_ptr_valid_plus_one\n    `(Hobs : !Observe (type_ptr ty p) P) : Observe (valid_ptr (p ,, o_sub σ ty 1)) P.\n  Proof. by rewrite -type_ptr_valid_plus_one. Qed.\n\n  Lemma type_ptr_valid ty p : type_ptr ty p |-- valid_ptr p.\n  Proof. by rewrite type_ptr_strict_valid strict_valid_valid. Qed.\n\n  #[global] Instance type_ptr_size_observe ty p :\n    Observe [| is_Some (size_of σ ty) |] (type_ptr ty p).\n  Proof. rewrite type_ptr_size. apply _. Qed.\n\n  #[global] Instance valid_ptr_sub_0 (p : ptr) (ty : type) :\n    HasSize ty ->\n    Observe (valid_ptr (p ,, o_sub σ ty 0)) (valid_ptr p).\n  Proof. intros. rewrite o_sub_0 // offset_ptr_id. refine _. Qed.\n  #[global] Instance type_ptr_sub_0 (p : ptr) (ty : type) :\n    HasSize ty ->\n    Observe (valid_ptr (p ,, o_sub σ ty 0)) (type_ptr ty p).\n  Proof.\n    intros. by rewrite type_ptr_valid; apply valid_ptr_sub_0.\n  Qed.\n  #[global] Instance type_ptr_valid_ptr_next (p : ptr) (ty : type) (m n : Z) :\n    (m = n + 1)%Z ->\n    Observe (valid_ptr (p ,, o_sub σ ty m)) (type_ptr ty (p ,, o_sub σ ty n)).\n  Proof.\n    intros; subst.\n    iIntros \"X\".\n    iDestruct (observe (valid_ptr (p ,, o_sub _ _ _ ,, o_sub _ _ _)) with \"X\") as \"z\".\n    apply observe_type_ptr_valid_plus_one. refine _.\n    by rewrite o_sub_sub.\n  Qed.\n\n  Lemma same_alloc_refl p : valid_ptr p ⊢ [| same_alloc p p |].\n  Proof.\n    rewrite valid_ptr_alloc_id same_alloc_iff. iIntros \"!%\". case; naive_solver.\n  Qed.\n\n  Lemma live_has_alloc_id p :\n    live_ptr p ⊢ ∃ aid, [| ptr_alloc_id p = Some aid |] ∗ live_alloc_id aid.\n  Proof. rewrite /live_ptr; iIntros. case: (ptr_alloc_id p) => /= [aid|]; eauto. Qed.\nEnd with_cpp.\n", "meta": {"author": "bedrocksystems", "repo": "BRiCk", "sha": "23d7e64cc53706de608dbff0be75d1c4b8c3a7ec", "save_path": "github-repos/coq/bedrocksystems-BRiCk", "path": "github-repos/coq/bedrocksystems-BRiCk/BRiCk-23d7e64cc53706de608dbff0be75d1c4b8c3a7ec/theories/lang/cpp/logic/pred.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2029705395543598}}
{"text": "(* -------------------------------------------------------------------------- *\n *                     Vellvm - the Verified LLVM project                     *\n *                                                                            *\n *     Copyright (c) 2018 Steve Zdancewic <stevez@cis.upenn.edu>              *\n *                                                                            *\n *   This file is distributed under the terms of the GNU General Public       *\n *   License as published by the Free Software Foundation, either version     *\n *   3 of the License, or (at your option) any later version.                 *\n ---------------------------------------------------------------------------- *)\n\n\nFrom Coq Require Import\n     ZArith List String Omega\n     FSets.FMapAVL\n     Structures.OrderedTypeEx\n     ZMicromega.\n\nFrom ITree Require Import\n     ITree\n     Basics.Basics\n     Events.Exception\n     Events.State.\n\nImport Basics.Basics.Monads.\n\nFrom ExtLib Require Import\n     Structures.Monads\n     Programming.Eqv\n     Programming.Show\n     Data.String.\n\nFrom Vellvm Require Import\n     LLVMAst\n     Util\n     DynamicTypes\n     Denotation\n     MemoryAddress\n     LLVMEvents\n     Error\n     Coqlib\n     Numeric.Integers\n     Numeric.Floats.\n\nImport MonadNotation.\nImport EqvNotation.\nImport ListNotations.\n\nSet Implicit Arguments.\nSet Contextual Implicit.\n\nModule A : MemoryAddress.ADDRESS with Definition addr := (Z * Z) % type.\n  Definition addr := (Z * Z) % type.\n  Definition null := (0, 0).\n  Definition t := addr.\n  Lemma eq_dec : forall (a b : addr), {a = b} + {a <> b}.\n  Proof.\n    intros [a1 a2] [b1 b2].\n    destruct (a1 ~=? b1);\n      destruct (a2 ~=? b2); unfold eqv in *; unfold AstLib.eqv_int in *; subst.\n    - left; reflexivity.\n    - right. intros H. inversion H; subst. apply n. reflexivity.\n    - right. intros H. inversion H; subst. apply n. reflexivity.\n    - right. intros H. inversion H; subst. apply n. reflexivity.\n  Qed.\nEnd A.\n\n\nModule Make(LLVMEvents: LLVM_INTERACTIONS(A)).\n  Import LLVMEvents.\n  Import DV.\n\n  Definition addr := A.addr.\n\n  Module IM := FMapAVL.Make(Coq.Structures.OrderedTypeEx.Z_as_OT).\n  Definition IntMap := IM.t.\n\n  Definition add {a} k (v:a) := IM.add k v.\n  Definition delete {a} k (m:IntMap a) := IM.remove k m.\n  Definition member {a} k (m:IntMap a) := IM.mem k m.\n  Definition lookup {a} k (m:IntMap a) := IM.find k m.\n  Definition empty {a} := @IM.empty a.\n\n  Fixpoint add_all {a} ks (m:IntMap a) :=\n    match ks with\n    | [] => m\n    | (k,v) :: tl => add k v (add_all tl m)\n    end.\n\n  Fixpoint add_all_index {a} vs (i:Z) (m:IntMap a) :=\n    match vs with\n    | [] => m\n    | v :: tl => add i v (add_all_index tl (i+1) m)\n    end.\n\n  (* Give back a list of values from i to (i + sz) - 1 in m. *)\n  (* Uses def as the default value if a lookup failed. *)\n  Definition lookup_all_index {a} (i:Z) (sz:Z) (m:IntMap a) (def:a) : list a :=\n    List.map (fun x =>\n                let x' := lookup (Z.of_nat x) m in\n                match x' with\n                | None => def\n                | Some val => val\n                end) (seq (Z.to_nat i) (Z.to_nat sz)).\n\n  Definition union {a} (m1 : IntMap a) (m2 : IntMap a)\n    := IM.map2 (fun mx my =>\n                  match mx with | Some x => Some x | None => my end) m1 m2.\n\n  Definition maximumBy {A} (leq : A -> A -> bool) (def : A) (l : list A) : A :=\n    fold_left (fun a b => if leq a b then b else a) l def.\n\n  (* Get a fresh key for use in memory map *)\n  Definition next_key {a} (m : IM.t a) : Z\n    := let keys := map fst (IM.elements m) in\n       1 + maximumBy Z.leb (-1) keys.\n\n  Inductive SByte :=\n  | Byte : byte -> SByte\n  | Ptr : addr -> SByte\n  | PtrFrag : SByte\n  | SUndef : SByte.\n\n  (* TODO SAZ: mem_block should keep track of its allocation size so\n    that operations can fail if they are out of range\n\n    CB: I think this might happen implicitly with make_empty_block --\n    it initializes the IntMap with only the valid indices. As long as the\n    lookup functions handle this properly, anyway.\n   *)\n\n  (* Simple view of memory *)\n  Definition mem_block := IntMap SByte.\n  Definition memory    := IntMap mem_block.\n\n  (* Allocation stacks *)\n  Definition mem_frame := list Z.  (* A list of block ids that need to be freed when popped *)\n  Definition mem_stack := list mem_frame.\n\n  (* Memory + stack for freeing *)\n  Definition memory_stack : Type := memory * mem_stack.\n\n  (* Definition undef := DVALUE_Undef. (* TODO: should this be an empty block? *) *)\n\n  Fixpoint max_default (l:list Z) (x:Z) :=\n    match l with\n    | [] => x\n    | h :: tl =>\n      max_default tl (if h >? x then h else x)\n    end.\n\n  Definition oracle (m:memory) : Z :=\n    let keys := List.map fst (IM.elements m) in\n    let max := max_default keys 0 in\n    let offset := 1 in (* TODO: This should be \"random\" *)\n    max + offset.\n\n\n  (* Computes the byte size of this type. *)\n  Fixpoint sizeof_dtyp (ty:dtyp) : Z :=\n    match ty with\n    | DTYPE_I sz => 8 (* All integers are padded to 8 bytes. *)\n    | DTYPE_Pointer => 8\n    | DTYPE_Struct l => fold_left (fun x acc => x + sizeof_dtyp acc) l 0\n    | DTYPE_Array sz ty' => sz * sizeof_dtyp ty'\n    | DTYPE_Float => 4\n    | DTYPE_Double => 8\n    | _ => 0 (* TODO: add support for more types as necessary *)\n    end.\n\n  (* Convert integer to its byte representation. *)\n  Fixpoint bytes_of_int (n: nat) (x: Z) {struct n}: list byte :=\n    match n with\n    | O => nil\n    | S m => Byte.repr x :: bytes_of_int m (x / 256)\n    end.\n\n  Fixpoint int_of_bytes (l: list byte): Z :=\n    match l with\n    | nil => 0\n    | b :: l' => Byte.unsigned b + int_of_bytes l' * 256\n    end.\n\n  (* CB TODO: Is interpreting everything except for bytes as undef reasonable? *)\n  Definition Sbyte_to_byte (sb:SByte) : option byte :=\n    match sb with\n    | Byte b => ret b\n    | Ptr _ | PtrFrag | SUndef => None\n    end.\n\n  Definition Z_to_sbyte_list (count:nat) (z:Z) : list SByte :=\n    List.map Byte (bytes_of_int count z).\n\n  Definition Sbyte_to_byte_list (sb:SByte) : list byte :=\n    match sb with\n    | Byte b => [b]\n    | Ptr _ | PtrFrag | SUndef => []\n    end.\n\n  Definition sbyte_list_to_byte_list (bytes:list SByte) : list byte :=\n    List.flat_map Sbyte_to_byte_list bytes.\n\n  Definition sbyte_list_to_Z (bytes:list SByte) : Z :=\n    int_of_bytes (sbyte_list_to_byte_list bytes).\n\n\n  (** Length properties *)\n\n  Lemma length_bytes_of_int:\n    forall n x, List.length (bytes_of_int n x) = n.\n  Proof.\n    induction n; simpl; intros. auto. decEq. auto.\n  Qed.\n\n  Lemma int_of_bytes_of_int:\n    forall n x,\n      int_of_bytes (bytes_of_int n x) = x mod (two_p (Z.of_nat n * 8)).\n  Proof.\n    induction n; intros.\n    simpl. rewrite Zmod_1_r. auto.\n    Opaque Byte.wordsize.\n    rewrite Nat2Z.inj_succ. simpl.\n    replace (Z.succ (Z.of_nat n) * 8) with (Z.of_nat n * 8 + 8) by omega.\n    rewrite two_p_is_exp; try omega.\n    rewrite Zmod_recombine. rewrite IHn. rewrite Z.add_comm.\n    change (Byte.unsigned (Byte.repr x)) with (Byte.Z_mod_modulus x).\n    rewrite Byte.Z_mod_modulus_eq. reflexivity.\n    apply two_p_gt_ZERO. omega. apply two_p_gt_ZERO. omega.\n  Qed.\n\n\n\n  (* Serializes a dvalue into its SByte-sensitive form. *)\n  Fixpoint serialize_dvalue (dval:dvalue) : list SByte :=\n    match dval with\n    | DVALUE_Addr addr => (Ptr addr) :: (repeat PtrFrag 7)\n    | DVALUE_I1 i => Z_to_sbyte_list 8 (unsigned i)\n    | DVALUE_I8 i => Z_to_sbyte_list 8 (unsigned i)\n    | DVALUE_I32 i => Z_to_sbyte_list 8 (unsigned i)\n    | DVALUE_I64 i => Z_to_sbyte_list 8 (unsigned i)\n    | DVALUE_Float f => Z_to_sbyte_list 4 (unsigned (Float32.to_bits f))\n    | DVALUE_Double d => Z_to_sbyte_list 8 (unsigned (Float.to_bits d))\n    | DVALUE_Struct fields | DVALUE_Array fields =>\n                             (* note the _right_ fold is necessary for byte ordering. *)\n                             fold_right (fun 'dv acc => ((serialize_dvalue dv) ++ acc) % list) [] fields\n    | _ => [] (* TODO add more dvalues as necessary *)\n    end.\n\n  (* CB TODO: does this really not exist somewhere? *)\n  Definition is_some {A} (o : option A) :=\n    match o with\n    | Some x => true\n    | None => false\n    end.\n\n  Definition all_not_sundef (bytes : list SByte) : bool :=\n    forallb is_some (map Sbyte_to_byte bytes).\n\n  (* Deserialize a list of SBytes into a uvalue, assuming that none of the bytes are undef *)\n  Fixpoint deserialize_sbytes_defined (bytes:list SByte) (t:dtyp) : uvalue :=\n    match t with\n    | DTYPE_I sz =>\n      let des_int := sbyte_list_to_Z bytes in\n      match sz with\n      | 1  => UVALUE_I1 (repr des_int)\n      | 8  => UVALUE_I8 (repr des_int)\n      | 32 => UVALUE_I32 (repr des_int)\n      | 64 => UVALUE_I64 (repr des_int)\n      | _  => UVALUE_None (* invalid size. *)\n      end\n    | DTYPE_Float => UVALUE_Float (Float32.of_bits (repr (sbyte_list_to_Z bytes)))\n    | DTYPE_Double => UVALUE_Double (Float.of_bits (repr (sbyte_list_to_Z bytes)))\n\n    | DTYPE_Pointer =>\n      match bytes with\n      | Ptr addr :: tl => UVALUE_Addr addr\n      | _ => UVALUE_None (* invalid pointer. *)\n      end\n    | DTYPE_Array sz t' =>\n      let fix array_parse count byte_sz bytes :=\n          match count with\n          | O => []\n          | S n => (deserialize_sbytes_defined (firstn byte_sz bytes) t')\n                     :: array_parse n byte_sz (skipn byte_sz bytes)\n          end in\n      UVALUE_Array (array_parse (Z.to_nat sz) (Z.to_nat (sizeof_dtyp t')) bytes)\n    | DTYPE_Struct fields =>\n      let fix struct_parse typ_list bytes :=\n          match typ_list with\n          | [] => []\n          | t :: tl =>\n            let size_ty := Z.to_nat (sizeof_dtyp t) in\n            (deserialize_sbytes_defined (firstn size_ty bytes) t)\n              :: struct_parse tl (skipn size_ty bytes)\n          end in\n      UVALUE_Struct (struct_parse fields bytes)\n    | _ => UVALUE_None (* TODO add more as serialization support increases *)\n    end.\n\n  Definition deserialize_sbytes (bytes : list SByte) (t : dtyp) : uvalue :=\n    if all_not_sundef bytes\n    then deserialize_sbytes_defined bytes t\n    else UVALUE_Undef t.\n\n  (* Todo - complete proofs, and think about moving to MemoryProp module. *)\n  (* The relation defining serializable dvalues. *)\n  Inductive serialize_defined : dvalue -> Prop :=\n  | d_addr: forall addr,\n      serialize_defined (DVALUE_Addr addr)\n  | d_i1: forall i1,\n      serialize_defined (DVALUE_I1 i1)\n  | d_i8: forall i1,\n      serialize_defined (DVALUE_I8 i1)\n  | d_i32: forall i32,\n      serialize_defined (DVALUE_I32 i32)\n  | d_i64: forall i64,\n      serialize_defined (DVALUE_I64 i64)\n  | d_struct_empty:\n      serialize_defined (DVALUE_Struct [])\n  | d_struct_nonempty: forall dval fields_list,\n      serialize_defined dval ->\n      serialize_defined (DVALUE_Struct fields_list) ->\n      serialize_defined (DVALUE_Struct (dval :: fields_list))\n  | d_array_empty:\n      serialize_defined (DVALUE_Array [])\n  | d_array_nonempty: forall dval fields_list,\n      serialize_defined dval ->\n      serialize_defined (DVALUE_Array fields_list) ->\n      serialize_defined (DVALUE_Array (dval :: fields_list)).\n\n  (* Lemma assumes all integers encoded with 8 bytes. *)\n\n  Inductive sbyte_list_wf : list SByte -> Prop :=\n  | wf_nil : sbyte_list_wf []\n  | wf_cons : forall b l, sbyte_list_wf l -> sbyte_list_wf (Byte b :: l)\n  .\n\n  (*\nLemma sbyte_list_to_Z_inverse:\n  forall i1 : int1, (sbyte_list_to_Z (Z_to_sbyte_list 8 (Int1.unsigned i1))) =\n               (Int1.unsigned i1).\nProof.\n  intros i1.\n  destruct i1. simpl.\nAdmitted. *)\n\n\n  (*\nLemma serialize_inverses : forall dval,\n    serialize_defined dval -> exists typ, deserialize_sbytes (serialize_dvalue dval) typ = dval.\nProof.\n  intros. destruct H.\n  (* DVALUE_Addr. Type of pointer is not important. *)\n  - exists (TYPE_Pointer TYPE_Void). reflexivity.\n  (* DVALUE_I1. Todo: subversion lemma for integers. *)\n  - exists (TYPE_I 1).\n    simpl.\n\n\n    admit.\n  (* DVALUE_I32. Todo: subversion lemma for integers. *)\n  - exists (TYPE_I 32). admit.\n  (* DVALUE_I64. Todo: subversion lemma for integers. *)\n  - exists (TYPE_I 64). admit.\n  (* DVALUE_Struct [] *)\n  - exists (TYPE_Struct []). reflexivity.\n  (* DVALUE_Struct fields *)\n  - admit.\n  (* DVALUE_Array [] *)\n  - exists (TYPE_Array 0 TYPE_Void). reflexivity.\n  (* DVALUE_Array fields *)\n  - admit.\nAdmitted.\n   *)\n\n  (* Construct block indexed from 0 to n. *)\n  Fixpoint init_block_h (n:nat) (m:mem_block) : mem_block :=\n    match n with\n    | O => add 0 SUndef m\n    | S n' => add (Z.of_nat n) SUndef (init_block_h n' m)\n    end.\n\n  (* Initializes a block of n 0-bytes. *)\n  Definition init_block (n:Z) : mem_block :=\n    match n with\n    | 0 => empty\n    | Z.pos n' => init_block_h (BinPosDef.Pos.to_nat (n' - 1)) empty\n    | Z.neg _ => empty (* invalid argument *)\n    end.\n\n  (* Makes a block appropriately sized for the given type. *)\n  Definition make_empty_block (ty:dtyp) : mem_block :=\n    init_block (sizeof_dtyp ty).\n\n  Fixpoint handle_gep_h (t:dtyp) (b:Z) (off:Z) (vs:list dvalue) (m:memory) : err (memory * dvalue):=\n    match vs with\n    | v :: vs' =>\n      match v with\n      | DVALUE_I32 i =>\n        let k := unsigned i in\n        let n := BinIntDef.Z.to_nat k in\n        match t with\n        | DTYPE_Vector _ ta | DTYPE_Array _ ta =>\n                              handle_gep_h ta b (off + k * (sizeof_dtyp ta)) vs' m\n        | DTYPE_Struct ts | DTYPE_Packed_struct ts => (* Handle these differently in future *)\n                            let offset := fold_left (fun acc t => acc + sizeof_dtyp t)\n                                                    (firstn n ts) 0 in\n                            match nth_error ts n with\n                            | None => failwith \"overflow\"\n                            | Some t' =>\n                              handle_gep_h t' b (off + offset) vs' m\n                            end\n        | _ => failwith (\"non-i32-indexable type\")\n        end\n      | DVALUE_I8 i =>\n        let k := unsigned i in\n        let n := BinIntDef.Z.to_nat k in\n        match t with\n        | DTYPE_Vector _ ta | DTYPE_Array _ ta =>\n                              handle_gep_h ta b (off + k * (sizeof_dtyp ta)) vs' m\n        | _ => failwith (\"non-i8-indexable type\")\n        end\n      | DVALUE_I64 i =>\n        let k := unsigned i in\n        let n := BinIntDef.Z.to_nat k in\n        match t with\n        | DTYPE_Vector _ ta | DTYPE_Array _ ta =>\n                              handle_gep_h ta b (off + k * (sizeof_dtyp ta)) vs' m\n        | _ => failwith (\"non-i64-indexable type\")\n        end\n      | _ => failwith \"non-I32 index\"\n      end\n    | [] => ret (m, DVALUE_Addr (b, off))\n    end.\n\n  Definition concretize_block (b:Z) (m:memory) : Z * memory :=\n    match lookup b m with\n    | None => (b, m)\n    | Some block =>\n      let i := oracle m in\n      let fix loop es k block : mem_block :=\n          match es with\n          | [] => block\n          | (i, e) :: tl => loop tl (k+1) (add (k + i) e block)\n          end in\n      (* TODO change source block SBYTES to associate abstract pointers with concrete memory. *)\n      (i, add b (loop (IM.elements block) i block) m)\n    end.\n\n  Definition handle_gep (t:dtyp) (dv:dvalue) (vs:list dvalue) (m:memory) : err (memory * dvalue):=\n    match vs with\n    | DVALUE_I32 i :: vs' => (* TODO: Handle non i32 indices *)\n      match dv with\n      | DVALUE_Addr (b, o) =>\n        handle_gep_h t b (o + (sizeof_dtyp t) * (unsigned i)) vs' m\n      | _ => failwith \"non-address\"\n      end\n    | _ => failwith \"non-I32 index\"\n    end.\n\n  (* LLVM 5.0 memcpy\n   According to the documentation: http://releases.llvm.org/5.0.0/docs/LangRef.html#llvm-memcpy-intrinsic\n   this operation can never fail?  It doesn't return any status code...\n   *)\n\n  Definition handle_memcpy (args : List.list dvalue) (m:memory) : err memory :=\n    match args with\n    | DVALUE_Addr (dst_b, dst_o) ::\n                  DVALUE_Addr (src_b, src_o) ::\n                  DVALUE_I32 len ::\n                  DVALUE_I32 align :: (* alignment ignored *)\n                  DVALUE_I1 volatile :: [] (* volatile ignored *)  =>\n      src_block <- trywith \"memcpy src block not found\" (lookup src_b m) ;;\n                dst_block <- trywith \"memcpy dst block not found\" (lookup dst_b m) ;;\n                let sdata := lookup_all_index src_o (unsigned len) src_block SUndef in\n                let dst_block' := add_all_index sdata dst_o dst_block in\n                let m' := add dst_b dst_block' m in\n                (ret m' : err memory)\n\n    | _ => failwith \"memcpy got incorrect arguments\"\n    end.\n\n  (* TODO:\n   - we can use the handler combinators to make these more modular\n\n   - these operations are too defined: load and store should fail if the\n     address isn't in range\n   *)\n\n  Definition free_frame (f : mem_frame) (m : memory) : memory\n    := fold_left (fun m key => delete key m) f m.\n\n  Definition handle_memory {E} `{FailureE -< E} `{UBE -< E}: MemoryE ~> stateT memory_stack (itree E) :=\n    fun _ e '(m, s) =>\n      match e with\n      | MemPush => ret ((m, [] :: s), tt)\n\n      | MemPop =>\n        match s with\n        | [] => raise \"Tried to pop memory stack, but there's nothing to pop.\"\n        | frame :: stack_rest =>\n          let m' := free_frame frame m in\n          ret ((m', stack_rest), tt)\n        end\n\n      | Alloca t =>\n        let new_block := make_empty_block t in\n        let key := next_key m in\n        let new_mem := add key new_block m in\n\n        match s with\n        | [] => raise \"No stack frame for alloca.\"\n        | frame :: stack_rest =>\n          let new_stack := (key :: frame) :: stack_rest in\n          ret ((new_mem, new_stack), DVALUE_Addr (key, 0))\n        end\n\n      | Load t dv =>\n        match dv with\n        | DVALUE_Addr (b, i) =>\n          match lookup b m with\n          | Some block =>\n            ret ((m, s), deserialize_sbytes (lookup_all_index i (sizeof_dtyp t) block SUndef) t)\n          (* Asking for a non-allocated block is undefined behaviour. *)\n          | None => raiseUB \"Loading from block that has never been allocated.\"\n          end\n        | _ => raise \"Load got non-address dvalue\"\n        end\n\n      | Store dv v =>\n        match dv with\n        | DVALUE_Addr (b, i) =>\n          match lookup b m with\n          | Some m' =>\n            ret ((add b (add_all_index (serialize_dvalue v) i m') m, s), tt)\n          | None => raise \"stored to unallocated address\"\n          end\n        | _ => raise (\"Store got non-address dvalue: \" ++ (to_string dv))\n        end\n\n      | GEP t dv vs =>\n        match handle_gep t dv vs m with\n        | inl err => raise err\n        | inr (m, dv) => ret ((m, s), dv)\n        end\n\n      | ItoP i =>\n        match i with\n        | DVALUE_I64 i => ret ((m, s), DVALUE_Addr (0, unsigned i))\n        | DVALUE_I32 i => ret ((m, s), DVALUE_Addr (0, unsigned i))\n        | DVALUE_I8 i  => ret ((m, s), DVALUE_Addr (0, unsigned i))\n        | DVALUE_I1 i  => ret ((m, s), DVALUE_Addr (0, unsigned i))\n        | _            => raise \"Non integer passed to ItoP\"\n        end\n\n      | PtoI a =>\n        match a with\n        | DVALUE_Addr (b, i) =>\n          if Z.eqb b 0 then ret ((m, s), DVALUE_Addr(0, i))\n          else let (k, m) := concretize_block b m in\n               ret ((m, s), DVALUE_Addr (0, (k + i)))\n        | _ => raise \"PtoI got non-address dvalue\"\n        end\n      end.\n\n  Definition handle_intrinsic {E} `{FailureE -< E}: IntrinsicE ~> stateT memory_stack (itree E) :=\n    fun _ e '(m, s) =>\n      match e with\n      | Intrinsic t name args =>\n        if string_dec name \"llvm.memcpy.p0i8.p0i8.i32\" then  (* FIXME: use reldec typeclass? *)\n          match handle_memcpy args m with\n          | inl err => raise err\n          | inr m' => ret ((m', s), DVALUE_None)\n          end\n        else\n            raise (\"Unknown intrinsic: \" ++ name)\n      end.\n\n\n  (* TODO: clean this up *)\n  (* {E} `{failureE -< E} : IO ~> stateT memory (itree E)  *)\n  (* Won't need to be case analysis, just passes through failure + debug *)\n  (* Might get rid of this one *)\n  (* This can't show that IO ∉ E :( *)\n  (* Alternative 2: Fix order of effects\n\n   Layer interpretors so that they each chain into the next. Have to\n   do ugly matches everywhere :(.\n\n   Split the difference:\n\n   `{IO -< IO +' failureE +' debugE}\n\n   Alternative 3: follow 2, and then use notations to make things better.\n\n   Alternative 4: Extend itrees mechanisms with some kind of set operations.\n\n   If you want to allow sums on the left of your handlers, you want\n   this notion of an atomic handler / event, which is different from a\n   variable or a sum...\n\n   `{E +' F -< G}\n\n   This seems too experimental to try to work out now --- chat with Li-yao about it.\n\n   Alternative 2 might be the most straightforward way to get things working in the short term.\n\n   We just want to get everything hooked together to build and test\n   it. Then think about making the interfaces nicer. The steps to alt\n   2, start with LLVM1 ordering as the basic default. Then each stage\n   of interpretation peels off one, or reintroduces the same kind of\n   events / changes it.\n\n\n   *)\n  Section PARAMS.\n  Variable (E F : Type -> Type).\n    Definition E_trigger {M} : forall R, E R -> (stateT M (itree (E +' F)) R) :=\n      fun R e m => r <- trigger e ;; ret (m, r).\n\n  Definition F_trigger {M} : forall R, F R -> (stateT M (itree (E +' F)) R) :=\n      fun R e m => r <- trigger e ;; ret (m, r).\n\n  Definition interp_memory `{FailureE -< E +' F} `{UBE -< E +' F}:\n    itree (E +'  IntrinsicE +' MemoryE +' F) ~> stateT memory_stack (itree (E +' F)) :=\n    interp_state (case_ E_trigger (case_ handle_intrinsic (case_ handle_memory F_trigger))).\n\n  End PARAMS.\n\nEnd Make.\n", "meta": {"author": "amuppal18", "repo": "test", "sha": "4f6663f47786843480790e1b754ea117de435ff3", "save_path": "github-repos/coq/amuppal18-test", "path": "github-repos/coq/amuppal18-test/test-4f6663f47786843480790e1b754ea117de435ff3/src/coq/Handlers/Memory.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.20297053955435979}}
{"text": "Require Import ExtLib.Core.RelDec.\n\nRequire Import MirrorCore.Lambda.Expr.\nRequire Import MirrorCore.RTac.RTac.\nRequire Import MirrorCore.Lambda.ExprSubst.\nRequire Import MirrorCore.Lambda.ExprUnify_simul.\nRequire Import MirrorCore.Lambda.ExprVariables.\nRequire MirrorCore.syms.SymEnv.\nRequire MirrorCore.syms.SymSum.\nRequire Import MirrorCore.VariablesI.\n\nRequire Import Charge.Tactics.OrderedCanceller.\nRequire Import Charge.Tactics.BILNormalize.\nRequire Import Charge.Tactics.SynSepLog.\nRequire Import Charge.Tactics.SepLogFoldWithAnd.\nRequire Import Charge.ModularFunc.ILogicFunc.\nRequire Import Charge.ModularFunc.BILogicFunc.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nSection Canceller.\n  Context (typ func subst : Type) (tyLogic : typ).\n  Context {HIL : ILogicFunc typ func} {HBIL : BILogicFunc typ func}.\n  Context {RType_typ : RType typ} {RelDec_typ : RelDec (@eq typ)}.\n  Context {Typ2_typ : Typ2 RType_typ Fun}.\n  Context {RSym_func : @RSym _ RType_typ func}.\n  Existing Instance Expr_expr.\n  Context {SS : Subst subst (expr typ func)}.\n  Context {SU : SubstUpdate subst (expr typ func)}.\n  Context {SO : SubstOk SS}.\n  Context {MA : MentionsAny (expr typ func)}.\n  Context {uis_pure : expr typ func -> bool}.\n\n  Definition sls : SepLogAndSpec typ func :=\n  {| is_pure := fun e : expr typ func =>\n                  match ilogicS e with\n\t\t    | Some (ilf_true _)\n\t\t    | Some (ilf_false _) => true\n\t\t    | _ => uis_pure e\n\t\t  end\n   ; is_emp := fun e => false\n   ; is_star := fun e : expr typ func =>\n \t\t  match bilogicS e with\n \t\t    | Some (bilf_star _) => true\n \t\t    | _ => false\n \t\t  end\n   ; is_and := fun e : expr typ func =>\n \t\t  match ilogicS e with\n \t\t    | Some (ilf_and _) => true\n \t\t    | _ => false\n \t\t  end\n   |}.\n\n  Let doUnifySepLog c (tus tvs : EnvI.tenv typ) (s : ctx_subst (typ := typ) (expr := expr typ func) c) (e1 e2 : expr typ func)\n  : option (ctx_subst c) :=\n    @exprUnify (ctx_subst c) typ func RType_typ RSym_func Typ2_typ _ _ 10 tus tvs 0 e1 e2 tyLogic s.\n\n  Let ssl : SynSepLog typ func :=\n  {| e_star := fun l r =>\n                 match bilogicS l with\n                   | Some (bilf_emp _) => r\n                   | _ => match bilogicS r with\n                            | Some (bilf_emp _) => l\n                            | _ => mkStar tyLogic l r\n                          end\n                 end\n   ; e_emp := mkEmp tyLogic\n   ; e_and := fun l r =>\n                match ilogicS l with\n                  | Some (ilf_true _) => r\n                  | _ => match ilogicS r with\n                           | Some (ilf_true _) => l\n                           | _ => mkAnd tyLogic l r\n                         end\n                end\n   ; e_true := mkTrue tyLogic\n   |}.\n\n  Definition eproveTrue c (s : ctx_subst (typ := typ) (expr := expr typ func) c) (e : expr typ func) : option (ctx_subst c) :=\n    match ilogicS e with\n      | Some (ilf_true _) => Some s\n      | _ => None\n    end.\n\n  Definition is_solved (e1 e2 : conjunctives typ func) : bool :=\n    match e1 , e2 with\n      | {| spatial := e1s ; star_true := t ; pure := _ |}\n        , {| spatial := nil ; star_true := t' ; pure := nil |} =>\n        if t' then\n          (** ... |- true **)\n          true\n        else\n          (** ... |- emp **)\n          if t then false else match e1s with\n                                 | nil => true\n                                 | _ => false\n                               end\n      | _ , _ => false\n    end.\nCheck @OrderedCanceller.ordered_cancel.\n\n  Definition the_canceller tus tvs (lhs rhs : expr typ func) c\n             (s : ctx_subst c)\n  : (expr typ func * expr typ func * (ctx_subst c)) + (ctx_subst c) :=\n    match @normalize_and typ _ _ func _ ssl sls tus tvs tyLogic lhs\n        , @normalize_and typ _ _ func _ ssl sls tus tvs tyLogic rhs\n    with\n      | Some lhs_norm , Some rhs_norm =>\n        match lhs_norm tt , rhs_norm tt with\n          | Some lhs_norm , Some rhs_norm =>\n            let '(lhs',rhs',s') :=\n                OrderedCanceller.ordered_cancel (subst := ctx_subst c)\n                  (doUnifySepLog (c := c) tus tvs) (eproveTrue (c := c))\n                  ssl\n                  (simple_order (func:=func)) lhs_norm rhs_norm s\n            in\n            if is_solved lhs' rhs' then\n              inr s'\n            else\n              inl (conjunctives_to_expr ssl lhs',\n                   conjunctives_to_expr ssl rhs',\n                   s')\n          | _ , _ => inl (lhs, rhs, s)\n        end\n      | _ , _ => inl (lhs, rhs, s)\n    end.\n\n  Let tyArr : typ -> typ -> typ := @typ2 _ _ _ _.\n\n  Definition CANCELLATION : rtac typ (expr typ func) :=\n    fun tus tvs nus nvs c s e =>\n      match e with\n        | App (App f L) R =>\n          match ilogicS f with\n\t    | Some (ilf_entails t) =>\n\t      match t ?[ eq ] tyLogic with\n\t     \t| true =>\n\t\t  match the_canceller tus tvs L R s with\n\t\t    | inl (l,r,s') =>\n\t\t      match bilogicS r with (* This is for intuitionistic logics only *)\n\t\t        | Some (bilf_emp _) => Solved s'\n\t\t        | _ => let e' := mkEntails tyLogic l r in\n\t\t\t       More s (GGoal e')\n\t\t      end\n\t\t    | inr s' => Solved s'\n\t\t  end\n\t\t| false => More s (GGoal e)\n\t      end\n\t    | _ => More s (GGoal e)\n\t  end\n        | _ => More s (GGoal e)\n      end.  \n      \n      \nDefinition the_canceller2 tus tvs (lhs rhs : expr typ func) :=\n    match @normalize_and typ _ _ func _ ssl sls tus tvs tyLogic lhs\n        , @normalize_and typ _ _ func _ ssl sls tus tvs tyLogic rhs\n    with\n      | Some lhs_norm , Some rhs_norm =>\n        match lhs_norm tt , rhs_norm tt with\n          | Some lhs_norm , Some rhs_norm =>\n            Some (simple_order (func := func) lhs_norm,\n                  simple_order (func := func) rhs_norm)\n          | _ , _ => None\n        end\n      | _ , _ => None\n    end.\n\n  Definition CANCELLATION2 tus tvs e :=\n      match e with\n        | App (App f L) R =>\n          match ilogicS f with\n\t    | Some (ilf_entails t) =>\n\t      match t ?[ eq ] tyLogic with\n\t     \t| true => the_canceller2 tus tvs L R\n\t\t    | false => None\n\t      end\n\t    | _ => None\n\t  end\n        | _ => None\n      end.\n\nEnd Canceller.\n\nImplicit Arguments CANCELLATION [[HIL] [HBIL] [RType_typ] [RelDec_typ]\n                                [Typ2_typ] [RSym_func] [MA]].\n", "meta": {"author": "jesper-bengtson", "repo": "Charge", "sha": "e58efc35e9f68a50cec6fcb40e83562133a84a21", "save_path": "github-repos/coq/jesper-bengtson-Charge", "path": "github-repos/coq/jesper-bengtson-Charge/Charge-e58efc35e9f68a50cec6fcb40e83562133a84a21/Charge!/src/Charge/Tactics/Rtac/Cancellation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20297053383584146}}
{"text": "Require Import String.\n\n(* Require Import Setoid. *)\n(* Require Import Coq.Arith.PeanoNat. *)\n(* Require Import Coq.Logic.Decidable. *)\n\n\nFrom networks Require Import listidx.\nFrom networks Require Import sequences.\n\nSet Implicit Arguments.\n\n\nVariable nodeCount : nat.\nDefinition node := { n:nat | n < nodeCount}.\nDefinition label := nat.\n\nSection modules.\n\n    \n\n\nVariant module_io_t ( I O : Type) :=\n    | m_evt_in : label -> node -> I -> module_io_t I O \n    | m_evt_out : label -> node -> O -> module_io_t I O\n.\n\n#[global]Arguments m_evt_in [I O]%type_scope _ _ _.\n#[global]Arguments m_evt_out [I O]%type_scope _ _ _.\n\nInductive corruption_evt   :=\n    | corruption : node -> corruption_evt\n.\n\n\nRecord module : Type :=  {\n    l : label;\n    I : Type;\n    O : Type;\n    module_io : Type := module_io_t I O;\n    module_xioc : Type := unit + module_io + corruption_evt;\n    A : seq module_xioc -> Prop\n}.\n\n\nEnd modules.\n\nSection StateMachines.\n\nOpen Scope type_scope.\n\n\nRecord stateMachine (I O : Type) :Type := {\n    State : Type;\n    S0 : State;\n    transition : State -> I -> ( O * State )\n}.\n\n\nEnd StateMachines.\n\nSection Protocols.\n\n\nVariant protocol_io_t (I O : Type) :=\n    | p_evt_in : node -> I -> protocol_io_t I O \n    | p_evt_out : node -> O -> protocol_io_t I O\n.\n\n#[global]Arguments p_evt_in [I]%type_scope [O]%type_scope _ _.\n#[global]Arguments p_evt_out [I]%type_scope [O]%type_scope _ _.\n\n\n\nVariant exec_evt_t  (I O : Type) (M: list module)  :=\n    | prot : protocol_io_t I O -> exec_evt_t I O M\n    | mod (m : listidx.indexOf M) : module_io (nth_checked m) -> exec_evt_t I O M\n    | corr : corruption_evt -> exec_evt_t I O M\n.\n\n\n#[global]Arguments prot [I O]%type_scope [M]%list_scope _.\n#[global]Arguments mod [I O]%type_scope [M]%list_scope m _.\n#[global]Arguments corr [I O]%type_scope [M]%list_scope _.\n(*\n Definition in_SMI_t (I O : Type) (M: list module) (e:exec_evt_t I O M) : Prop := \n    match e with\n        | prot (p_evt_in _ _) | mod _ (m_evt_out _ _ _) => True\n        | _ => False\n    end.\n\nDefinition in_SMO_t (I O : Type) (M: list module) (e:exec_evt_t I O M) : Prop := \n    match e with\n        | prot (p_evt_out _ _) | mod _ (m_evt_in _ _ _) => True\n        | _ => False\n    end. *)\n\n\nRecord Protocol := {\n    Ip : Type;\n    Op : Type;\n    M : list module;\n    protocol_io := protocol_io_t Ip Op;\n    exec_evt := exec_evt_t Ip Op M; \n    prot_p := prot (I:=Ip) (O:=Op) (M:=M);\n    module_p := mod (I:=Ip) (O:=Op) (M:=M);\n    corr_p := corr (I:=Ip) (O:=Op) (M:=M);\n    (* inSMI := in_SMI_t (I:=Ip) (O:=Op) (M:=M);\n    inSMO := in_SMO_t (I:=Ip) (O:=Op) (M:=M); *)\n\n    (* all definitions required to define the state machine I/O types needs to be inlined within the record def*)\n    inSMI := fun (e:exec_evt) => match e with\n                | prot (p_evt_in _ _) | mod _ (m_evt_out _ _ _) => True\n                | _ => False\n            end;\n    inSMO := fun (e : exec_evt) =>  match e with\n                | prot (p_evt_out _ _) | mod _ (m_evt_in _ _ _) => True\n                | _ => False\n              end;\n    SMI := {e:exec_evt | inSMI e};\n    SMO := list {e:exec_evt | inSMO e};\n    SM : stateMachine SMI SMO;\n}. \n\n\n\n(* in view of p means it's an input/output of p  *)\nDefinition isInNodeView (P:Protocol) (e:exec_evt P) (p:node) : Prop :=\n    match e with \n        | prot (p_evt_in p _)  | mod _ (m_evt_out _ p _)\n        | prot (p_evt_out p _) | mod _ (m_evt_in _ p _)  => True\n        | _ => False\nend.\n\n\n\n\nLemma view_subset_SMIO (P:Protocol) (e:exec_evt P) (p:node) : isInNodeView e p -> {inSMI e} + {inSMO e} .\nProof.\n    intros. unfold isInNodeView in H. \n    repeat match goal with \n    | s : match ?a with _ => _ end |- _ =>  destruct a \n    end.\n    all: simpl;auto.\nQed.\n\nLemma isInNodeView_dec (P:Protocol) (e:exec_evt P) (p:node) : {isInNodeView e p} + {~isInNodeView e p}.\nProof.\n    unfold isInNodeView. destruct e.\n    - destruct p0. all: auto.\n    - destruct m0. all: auto.\n    - auto.\nQed.\n\nLemma in_SMI_dec (P:Protocol) (e:exec_evt P) :  {inSMI e} + {~inSMI e}.\nProof. \n    unfold inSMI. destruct e. \n    - destruct p. all: simpl;auto. \n    - destruct m0. all: simpl;auto. \n    - auto.\nQed.\n\n\n\nDefinition execs (P:Protocol) := seq (exec_evt P).\n\nDefinition compatible_spec (P:Protocol) (s:module) : Prop :=\n    Ip P = I s /\\ Op P = O s.\n    \nDefinition spec_of (P:Protocol) := { s:module | compatible_spec P s}.\n\nDefinition convert_type (I I' : Type) (p_eq : I = I') (i : I ) : I' := eq_rect I (fun X => X) i I' p_eq.\nDefinition convert_set (I I' : Set) (p_eq : I = I') (i : I ) : I' := eq_rect I (fun X => X) i I' p_eq.\n\n    \n(* convert protocol io events into its spec io events  *)\nDefinition convert_io {P:Protocol} (io : protocol_io P) (s: module) (comp_proof : compatible_spec P s) : module_io s :=\n    match io with\n        | p_evt_in  n in' => m_evt_in (l s) n (convert_type (proj1 comp_proof) in')\n        | p_evt_out  n out' => m_evt_out (l s) n (convert_type (proj2 comp_proof) out')\n    end.\n\n\n(* convert protocol execs into sequences that can be fed to its specification admissibility predicate.  *)\nCoFixpoint strip_exec (P:Protocol) (s: module) (comp_proof : compatible_spec P s) (E: execs P) : seq (module_xioc s) :=\n    match E  with\n        | cons  e tl => let e' := match e with\n                | mod m io => inl (inl tt)\n                | prot io       => inl (inr (convert_io io comp_proof))\n                | corr c    => inr c\n            end in cons e' (strip_exec comp_proof tl)\n        | nil _     => nil (module_xioc s)\n    end.\n\nRequire Import Coq.Program.Wf.\n\n\n(* the sate at the nth event is the state right *before* the nth event is processed by the SM*)\n(* the recursive call is bascally a destruct on (rangeproof i) *)\n(* You may notice that \"index i = n\" is unused. It is present to make it appear as an hypothesis of the proof of well-foundedness *)\nProgram Fixpoint state_at (P:Protocol) (E : execs P) (i: indexOf E) (p:node) {measure (index i)} : State (SM P) :=\n    match index i as n return isinIndex E n -> index i = n -> State (SM P) with\n        | 0     => fun _ _ => S0 (SM P) \n        | S n'  => fun (p_in : isinIndex E (S n')) (_ : index i = (S n') ) => let prev_state := (state_at (mkIndex (skip_one p_in)) p) in \n            match (in_SMI_dec (elem i)), (isInNodeView_dec (elem i) p) with  (* only process input in view *)\n                | left pSMI, left pNodeView => snd (transition (SM P) prev_state (exist _ _ pSMI))\n                | _, _                      => prev_state\n            end\n    end (rangeproof i) (eq_refl (index i)).\nNext Obligation. rewrite H. auto. Defined.\n\n\n\n\nDefinition isNodeOut (P:Protocol) (e:exec_evt P) (p:node) : Prop := \n    match e with \n    | prot (p_evt_out p _) | mod _ (m_evt_in _ p _)  => True\n    | _ => False\nend.\n\nDefinition isNodeIn  (P:Protocol) (e:exec_evt P) (p:node) : Prop := \n    match e with \n        | prot (p_evt_in p _)  | mod _ (m_evt_out _ p _) => True\n        | _ => False\nend.\n\nLemma NodeOutEquivSMOView  (P:Protocol) (e:exec_evt P) (p:node) : isInNodeView e p /\\ inSMO e <-> isNodeOut e p.\nProof.\n    split. all:intros.\n    - unfold isNodeOut. destruct H. unfold isInNodeView in H. unfold inSMO in H0.  \n        repeat match goal with \n        | s : match ?a with _ => _ end |- _ =>  destruct a\n        end. all: auto.\n    - split. unfold isInNodeView. unfold isNodeOut in H. \n        repeat match goal with \n        | s : match ?a with _ => _ end |- _ =>  destruct a\n        end. all:auto.\nQed.\n\nDefinition NodeOutConj (P:Protocol) {e:exec_evt P} {p:node}  (proof: isNodeOut e p) : isInNodeView e p /\\ inSMO e :=  proj2 (NodeOutEquivSMOView e p) proof.\n\n\nLemma NodeInEquivSMIView  (P:Protocol) (e:exec_evt P) (p:node) : isInNodeView e p /\\ inSMI e <-> isNodeIn e p.\nsplit. all:intros.\n- unfold isNodeIn. destruct H. unfold isInNodeView in H. unfold inSMI in H0.  \n    repeat match goal with \n    | s : match ?a with _ => _ end |- _ =>  destruct a\n    end. all: auto.\n- split. unfold isInNodeView. unfold isNodeIn in H. \n    repeat match goal with \n    | s : match ?a with _ => _ end |- _ =>  destruct a\n    end. all:auto.\nQed.\nDefinition NodeInConj (P:Protocol) {e:exec_evt P} {p:node}  (proof: isNodeIn e p) : isInNodeView e p /\\ inSMI e :=  proj2 (NodeInEquivSMIView e p) proof.\n\n\n(*The SM output of node p' SM at event i, **before** (elem i) is processed *)\nDefinition process_at (P:Protocol) (E : execs P) (i: indexOf E) (p:node) (pIn : isNodeIn (elem i) p)  : list {e: exec_evt P | isNodeOut e p} :=\n    fst (transition (SM P) (state_at i p) (makeSig (proj2 (NodeInConj pIn)))).\n\nDefinition process_at_asSMO (P:Protocol) (E : execs P) (i: indexOf E) (p:node) (pIn : isNodeIn (elem i) p) : SMO P :=\n    (process_at i p pIn) (*? is there some implicit coercions i'm not aware of? *)\n.\n\n\nEnd Protocols.\n\nSection Models.\n    \n\nDefinition leibniz {T:Type} (x y : T) (p_eq: x = y) (P: T -> Type) : P y -> P x.\n    intros. subst y. exact X. \nDefined.\n\n\n\n(* downcast protocol execs event into events that can be fed to mod m' admissibility predicate. All events that m cannot process is replaced by unit *)\nDefinition clamped_evt (P:Protocol) (m: listidx.indexOf (M P)) (e: exec_evt P)  : module_xioc (nth_checked m)  := \n    match e with\n        | mod  m' mio =>  match (PeanoNat.Nat.eq_dec (listidx.index m) (listidx.index m')) with\n            | left eq_proof => inl (inr  (leibniz (rangeproof_irreverant m m' eq_proof) module_io mio))\n            | right _       => inl (inl tt)\n        end\n        | corr c => inr c\n        | _        =>  inl (inl tt)\n    end. \n\nDefinition  module_admissible (P:Protocol) (E:execs P) : Prop := \n    forall m: (listidx.indexOf (M P)), A (map E (clamped_evt m) ).\n\n Definition DelayPred := forall (P:Protocol) (E:execs P) (i:indexOf E) (p:node),  Prop. \n\nDefinition staticAdv := fun (P:Protocol) (E:execs P) (i : indexOf E)  (p:node) => True.\nDefinition staticAdv' : DelayPred := fun _ _ _ _ => True.\n\nDefinition  corrupt_at (P:Protocol) (E:execs P) (D: DelayPred) (i : indexOf E)  (p:node)  : Prop :=\n    exists (j:indexOf E), match elem j with\n        | corr (corruption p) => index j < index i /\\ D P E i p\n        | _ => False \n        end.\n\nDefinition corrupt (P:Protocol) (E:execs P) (D: DelayPred) (p:node) : Prop :=\n    exists (i : indexOf E), corrupt_at D i p.\n\nDefinition honest_at (P:Protocol) (E:execs P) (D: DelayPred) (i : indexOf E)  (p:node)  : Prop :=\n    ~ corrupt_at D i p.\n\nDefinition honest (P:Protocol) (E:execs P) (D: DelayPred) (p:node)  : Prop :=\n    ~ corrupt E D p.\n\n\n(* honest node admissibility : when an honest node receives input, all the following events are the node output. I.e., honest nodes follows the protocol *)\nDefinition honest_admissible (P:Protocol) (D: DelayPred) (E:execs P) : Prop := \n    forall (i : indexOf E), exists (p:node), forall pIn : (isNodeIn (elem i) p), honest_at D i p ->\n    isPrefixOf (List.map (proj1_sig (P:=fun x=> isNodeOut x p)) (process_at i p pIn) )\n               (tail i)\n.\n(* note to self: in this version, the adversary is NOT authorized to reorder outputs ! may need to fix *)\n    \n\n\n\nDefinition corruption_struct := (node -> Prop) -> Prop.\n\nDefinition k_cover (C:corruption_struct) (k:nat) := \n    exists (pi: {n:nat | n<k} -> (node->Prop)),\n    forall (p: node) (pi_n: {n:nat | n<k}),\n    pi pi_n p\n.\n\nRecord adversary_struct : Type := {\n    C : corruption_struct;\n    D : DelayPred;\n}.\n\n(* respects a given corruption structure*)\nDefinition structure_admissible (P:Protocol) (Adv:adversary_struct) (E:execs P)  : Prop := \n    forall (i:indexOf E), (C Adv) (corrupt_at (D Adv) i)\n.\n\n(* E is part of the model of P iff all admissibility requirements are met*)\nDefinition model (P:Protocol) (Adv:adversary_struct) (E:execs P) : Prop := \n    module_admissible E   /\\\n    honest_admissible (D Adv) E /\\\n    structure_admissible Adv E.\n\n\nDefinition satisfies (P: Protocol) (Adv:adversary_struct)  (s:spec_of P) (s: module ) (comp_proof : compatible_spec P s) : Prop  :=\n    forall E:execs P, model Adv E -> A (strip_exec comp_proof E)\n.\n\nEnd Models.\n\n", "meta": {"author": "Maschmalow", "repo": "network_models", "sha": "2bd84a80b9f32b26fe7b10ffbe05ab6cc70dc7b6", "save_path": "github-repos/coq/Maschmalow-network_models", "path": "github-repos/coq/Maschmalow-network_models/network_models-2bd84a80b9f32b26fe7b10ffbe05ab6cc70dc7b6/network.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.20296346422324274}}
{"text": "From iris Require Import base.\nFrom iris.program_logic Require Import language ectx_language ectxi_language.\nFrom stdpp Require Import gmap fin_maps fin_sets.\nFrom cap_machine Require Import addr_reg.\n\nSection Linking.\n  \n  Variable Symbols: Type.\n  Variable Symbols_eq_dec: EqDecision Symbols.\n  Variable Symbols_countable: Countable Symbols.\n\n  Variable Word: Type.\n  Variable can_address_only: Word -> (gset Addr) -> Prop.\n  Variable is_main: Word -> Prop.\n  \n  Definition imports: Type := gset (Symbols * Addr).\n  Definition exports: Type := gmap Symbols Word.\n  Definition segment: Type := gmap Addr Word.\n\n  Definition pre_component: Type := (segment * imports * exports).\n  Inductive component: Type :=\n  | Lib: pre_component -> component\n  | Main: pre_component -> Word -> component.\n\n  Inductive well_formed_pre_comp: pre_component -> Prop :=\n  | wf_pre_intro:\n      forall (ms : gmap Addr Word) imp (exp : gmap Symbols Word)\n        (Hdisj: forall s, is_Some (exp !! s) -> ~ exists a, (s, a) ∈ imp)\n        (Hexp: forall (s : Symbols) (w : Word), exp !! s = Some w -> can_address_only w (dom ms))\n        (Himp: forall s a, (s, a) ∈ imp -> is_Some (ms !! a))\n        (Himpdisj: forall s1 s2 a, (s1, a) ∈ imp -> (s2, a) ∈ imp -> s1 = s2)\n        (Hnpwl: forall (a : Addr) (w : Word), ms !! a = Some w -> can_address_only w (dom ms)),\n        well_formed_pre_comp (ms, imp, exp).\n\n  Inductive well_formed_comp: component -> Prop :=\n  | wf_lib:\n      forall comp\n        (Hwf_pre: well_formed_pre_comp comp),\n        well_formed_comp (Lib comp)\n  | wf_main:\n      forall comp w_main\n        (Hwf_pre: well_formed_pre_comp comp)\n        (Hw_main_addr: can_address_only w_main (dom (comp.1.1)))\n        (Hw_main: is_main w_main),\n        well_formed_comp (Main comp w_main).\n\n  Inductive is_program: component -> Prop :=\n  | is_program_intro:\n      forall ms imp exp w_main\n        (Hnoimports: imp = ∅)\n        (Hwfcomp: well_formed_comp (Main (ms, imp, exp) w_main)),\n        is_program (Main (ms,imp, exp) w_main).\n\n  Definition resolve_imports (imp: imports) (exp: exports) (ms: segment) :=\n    set_fold (fun '(s, a) m => match exp !! s with Some w => <[a:=w]> m | None => m end) ms imp.\n\n  Lemma resolve_imports_spec:\n    forall imp exp ms a\n      (Himpdisj: forall s1 s2 a, (s1, a) ∈ imp -> (s2, a) ∈ imp -> s1 = s2),\n      ((~ exists s, (s, a) ∈ imp) ->\n       (resolve_imports imp exp ms) !! a = ms !! a) /\\\n      (forall s, (s, a) ∈ imp ->\n       (exp !! s = None /\\ (resolve_imports imp exp ms) !! a = ms !! a) \\/ (exists wexp, exp !! s = Some wexp /\\ (resolve_imports imp exp ms) !! a = Some wexp)).\n  Proof.\n    intros imp exp ms a. eapply (set_fold_ind_L (fun m imp => (forall s1 s2 a, (s1, a) ∈ imp -> (s2, a) ∈ imp -> s1 = s2) -> ((~ exists s, (s, a) ∈ imp) -> m !! a = ms !! a) /\\ (forall s, (s, a) ∈ imp -> (exp !! s = None /\\ m !! a = ms !! a) \\/ (exists wexp, exp !! s = Some wexp /\\ m !! a = Some wexp))) (fun '(s, a) m => match exp !! s with Some w => <[a:=w]> m | None => m end)); eauto.\n    { intros. split; auto. intros.\n      eapply elem_of_empty in H0; elim H0; auto. }\n    intros. destruct x. split.\n    { intros. destruct (exp !! s).\n      - rewrite lookup_insert_ne; auto.\n        + apply H0.\n          * intros. eapply H1; eapply elem_of_union; right; eauto.\n          * intro Y. destruct Y as [sy Hiny].\n            eapply H2. exists sy. eapply elem_of_union. right; eauto.\n        + intro; subst a. eapply H2. exists s.\n          eapply elem_of_union. left. eapply elem_of_singleton. reflexivity.\n      - apply H0.\n        + intros. eapply H1; eapply elem_of_union; right; eauto.\n        + intro Y. destruct Y as [sy Hiny].\n          eapply H2. exists sy. eapply elem_of_union. right; auto. }\n    { intros; destruct (exp !! s) eqn:Hexp.\n      - destruct (decide (f = a)).\n        + subst f; rewrite lookup_insert.\n          right. assert (s0 = s) as ->; eauto.\n          eapply elem_of_union in H2. destruct H2.\n          * generalize (proj1 (elem_of_singleton _ _) H2). inversion 1; subst; auto.\n          * eapply (H1 s0 s a); [eapply elem_of_union_r; auto|eapply elem_of_union_l; eapply elem_of_singleton; eauto].\n        + rewrite lookup_insert_ne; auto.\n          eapply elem_of_union in H2; destruct H2.\n          * erewrite elem_of_singleton in H2. inversion H2; congruence.\n          * eapply H0; auto.\n            intros; eapply H1; eapply elem_of_union; right; eauto.\n      - eapply elem_of_union in H2. destruct H2.\n        + erewrite elem_of_singleton in H2. inversion H2; subst; clear H2.\n          left; split; auto. eapply (proj1 (H0 ltac:(intros; eapply H1; eapply elem_of_union; right; eauto))).\n          intro Y. destruct Y as [sy Hsy].\n          eapply H. replace s with sy; auto.\n          eapply H1; [eapply elem_of_union_r; eauto| eapply elem_of_union_l; eapply elem_of_singleton; eauto].\n        + eapply H0; auto.\n          intros; eapply H1; eapply elem_of_union_r; eauto. }\n  Qed.\n\n  Lemma resolve_imports_spec_in:\n    forall imp exp ms a s\n      (Himpdisj: forall s1 s2 a, (s1, a) ∈ imp -> (s2, a) ∈ imp -> s1 = s2),\n      (s, a) ∈ imp ->\n      (exp !! s = None /\\ (resolve_imports imp exp ms) !! a = ms !! a) \\/ (exists wexp, exp !! s = Some wexp /\\ (resolve_imports imp exp ms) !! a = Some wexp).\n  Proof.\n    intros. eapply resolve_imports_spec; eauto.\n  Qed.\n\n  Lemma resolve_imports_spec_not_in:\n    forall imp exp ms a\n      (Himpdisj: forall s1 s2 a, (s1, a) ∈ imp -> (s2, a) ∈ imp -> s1 = s2),\n      ((~ exists s, (s, a) ∈ imp) ->\n       (resolve_imports imp exp ms) !! a = ms !! a).\n  Proof.\n    intros. eapply resolve_imports_spec; eauto.\n  Qed.\n\n  Inductive link_pre_comp: pre_component -> pre_component -> pre_component -> Prop :=\n  | link_pre_comp_intro:\n      forall ms1 ms2 ms imp1 imp2 imp exp1 exp2 exp\n        (Hms_disj: forall a, is_Some (ms1 !! a) -> is_Some (ms2 !! a) -> False)\n        (Hexp: exp = merge (fun o1 o2 => match o1 with | Some _ => o1 | None => o2 end) exp1 exp2)\n        (Himp: forall s a, (s, a) ∈ imp <-> (((s, a) ∈ imp1 \\/ (s, a) ∈ imp2) /\\ exp !! s = None))\n        (Hms: ms = resolve_imports imp2 exp (resolve_imports imp1 exp (map_union ms1 ms2))),\n        link_pre_comp (ms1, imp1, exp1) (ms2, imp2, exp2) (ms, imp, exp).\n\n  Inductive link: component -> component -> component -> Prop :=\n  | link_lib_lib:\n      forall comp1 comp2 comp\n        (Hlink: link_pre_comp comp1 comp2 comp)\n        (Hwf_l: well_formed_comp (Lib comp1))\n        (Hwf_r: well_formed_comp (Lib comp2)),\n        link (Lib comp1) (Lib comp2) (Lib comp)\n  | link_lib_main:\n      forall comp1 comp2 comp w_main\n        (Hlink: link_pre_comp comp1 comp2 comp)\n        (Hwf_l: well_formed_comp (Lib comp1))\n        (Hwf_r: well_formed_comp (Main comp2 w_main)),\n        link (Lib comp1) (Main comp2 w_main) (Main comp w_main)\n  | link_main_lib:\n      forall comp1 comp2 comp w_main\n        (Hlink: link_pre_comp comp1 comp2 comp)\n        (Hwf_l: well_formed_comp (Main comp1 w_main))\n        (Hwf_r: well_formed_comp (Lib comp2)),\n        link (Main comp1 w_main) (Lib comp2) (Main comp w_main).\n\n  Inductive is_context (c comp p: component): Prop :=\n  | is_context_intro:\n      forall (His_program: link c comp p /\\ is_program p),\n      is_context c comp p.\n\nEnd Linking.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/linking.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.20296345490571263}}
{"text": "Require Import vellvm.\nRequire Import opsem_props.\nRequire Import memory_sim.\nRequire Import memory_props.\n\n(***********************************************************************)\n(* Properties of program initialization *)\nAxiom genGlobalAndInitMem__wf_global: forall initGlobal initFunTable initMem\n  CurLayouts CurNamedts CurProducts S,\n  OpsemAux.genGlobalAndInitMem\n    (OpsemAux.initTargetData CurLayouts CurNamedts Mem.empty) CurProducts\n      nil nil Mem.empty = ret (initGlobal, initFunTable, initMem) ->\n  wf_global (CurLayouts, CurNamedts) S initGlobal.\n\n(* OpsemPP.initLocals__wf_lc needs wf_params that is for params.\n   At initialization, we only have args...\n   Actually OpsemPP.initLocals__wf_lc only needs types in params.\n   So, we use the function to create a param from arg.\n   We should simplify the proofs of OpsemPP.initLocals__wf_lc, and\n   use only types. *)\nDefinition args_to_params (la: args) : params :=\nList.map (fun a0 => let '(t0,attr0,id0) := a0 in (t0,attr0,value_id id0)) la.\n\nAxiom main_wf_params: forall f t i0 a v b S CurLayouts CurNamedts CurProducts\n  VarArgs,\n  getParentOfFdefFromSystem (fdef_intro (fheader_intro f t i0 a v) b) S =\n    ret module_intro CurLayouts CurNamedts CurProducts ->\n  OpsemPP.wf_params\n    (OpsemAux.initTargetData CurLayouts CurNamedts Mem.empty)\n    VarArgs (args_to_params a).\n\nLemma s_genInitState__opsem_wf: forall S main VarArgs cfg IS\n  (HwfS : wf_system S)\n  (Hinit : Opsem.s_genInitState S main VarArgs Mem.empty = ret (cfg, IS)),\n  OpsemPP.wf_Config cfg /\\ OpsemPP.wf_State cfg IS.\nProof.\n  intros.\n  simpl_s_genInitState.\n  assert (HeqR0':=HeqR0).\n  apply getParentOfFdefFromSystem__moduleInProductsInSystemB in HeqR0'.\n  destruct HeqR0' as [HMinS HinPs].\n  assert (wf_namedts S (CurLayouts, CurNamedts)) as Hwfnts.\n    inv HwfS.\n    eapply wf_modules__wf_module in HMinS; eauto.\n    inv HMinS; auto.\n  split.\n  split; auto.\n  split.\n    eapply genGlobalAndInitMem__wf_global in HeqR1; eauto.\n  split; auto.\n  (* split; auto. *)\n  (*   intro J. congruence. *)\n  split.\n    eapply main_wf_params in HeqR0; eauto.\n    eapply OpsemPP.wf_ExecutionContext__at_beginning_of_function; eauto.\n    simpl.\n    split; auto.\n      intros. destruct b0 as [? [? ? t0]]. destruct t0; auto.\nQed.\n\nAxiom genGlobalAndInitMem__wf_globals_Mem: forall \n  (initGlobal initFunTable : GVMap) (initMem : mem)\n  (CurLayouts : layouts) (CurNamedts : namedts)\n  (CurProducts : list product) (la : args) (lc : Opsem.GVsMap)\n  (VarArgs : list GenericValue),\n  OpsemAux.genGlobalAndInitMem\n         (OpsemAux.initTargetData CurLayouts CurNamedts Mem.empty)\n         CurProducts nil nil Mem.empty =\n    ret (initGlobal, initFunTable, initMem) ->\n  Opsem.initLocals\n    (OpsemAux.initTargetData CurLayouts CurNamedts Mem.empty) la VarArgs =\n    ret lc ->\n  MemProps.wf_lc initMem lc /\\\n  (MemProps.wf_globals (Mem.nextblock initMem - 1) initGlobal /\\\n   MemProps.wf_Mem (Mem.nextblock initMem - 1)\n     (OpsemAux.initTargetData CurLayouts CurNamedts Mem.empty) initMem) /\\\n  MoreMem.mem_inj (MemProps.inject_init (Mem.nextblock initMem - 1)) \n    initMem initMem /\\\n  genericvalues_inject.wf_sb_mi (Mem.nextblock initMem - 1) \n    (MemProps.inject_init (Mem.nextblock initMem - 1)) initMem initMem /\\\n  OpsemAux.ftable_simulation (MemProps.inject_init (Mem.nextblock initMem - 1))\n    initFunTable initFunTable /\\\n  (forall i0 gv, \n     lookupAL GenericValue lc i0 = ret gv ->\n     genericvalues_inject.gv_inject \n       (MemProps.inject_init (Mem.nextblock initMem - 1)) gv gv) /\\\n  MoreMem.mem_inj inject_id initMem initMem /\\\n  OpsemAux.ftable_simulation inject_id initFunTable initFunTable.\n\n(***********************************************************************)\n(* A measure function used by refinement proofs, which is the number of \n   commands to execute. *)\nDefinition measure (st:Opsem.State) : nat :=\nmatch st with \n| {| Opsem.ECS := {| Opsem.CurCmds := cs |} :: _ |} => List.length cs\n| _ => 0%nat\nend.\n", "meta": {"author": "snu-sf", "repo": "crellvm-vellvm", "sha": "54c7cc88ab5b4aec4c327f501cac4d9a667ca057", "save_path": "github-repos/coq/snu-sf-crellvm-vellvm", "path": "github-repos/coq/snu-sf-crellvm-vellvm/crellvm-vellvm-54c7cc88ab5b4aec4c327f501cac4d9a667ca057/src/Vellvm/program_sim.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.2029099584497726}}
{"text": "Require Import Metatheory.\nRequire Import alist.\nRequire Import monad.\nRequire Import targetdata.\nRequire Import genericvalues.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Integers.\nRequire Import Coqlib.\nRequire Import syntax.\nRequire Import typings.\nRequire Import static.\nRequire Import opsem.\nRequire Import opsem_props.\nRequire Import opsem_wf.\nRequire Import vellvm_tactics.\nRequire Import infrastructure.\nRequire Import infrastructure_props.\n\nImport LLVMsyntax.\nImport LLVMgv.\nImport LLVMtd.\nImport LLVMtypings.\nImport LLVMinfra.\n\n(* This file defines the deterministic instance of Vellvm's operational \n   semantics. *)\n\n(* DGVs implements the signature of GenericValues. *)\nModule MDGVs.\n\nDefinition t := GenericValue.\nDefinition instantiate_gvs (gv : GenericValue) (gvs : t) : Prop := gvs = gv.\nDefinition inhabited (gvs : t) : Prop := True.\nDefinition cundef_gvs := LLVMgv.cundef_gv.\nDefinition undef_gvs gv (ty:typ) : t := gv.\nDefinition cgv2gvs := LLVMgv.cgv2gv.\nDefinition gv2gvs (gv:GenericValue) (ty:typ) : t := gv.\n\nNotation \"gv @ gvs\" :=\n  (instantiate_gvs gv gvs) (at level 43, right associativity).\nNotation \"$ gv # t $\" := (gv2gvs gv t) (at level 41).\nHint Unfold inhabited instantiate_gvs.\n\nLemma cundef_gvs__getTypeSizeInBits : forall S los nts gv ty sz al gv',\n  wf_typ S (los,nts) ty ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true ty =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  gv' @ (cundef_gvs gv ty) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) =\n    sizeGenericValue gv'.\nProof.\n  unfold instantiate_gvs.\n  intros. inv H2.\n  eapply cundef_gv__getTypeSizeInBits; eauto.\nQed.\n\nLemma cundef_gvs__matches_chunks : forall S los nts gv ty gv',\n  wf_typ S (los,nts) ty ->\n  gv_chunks_match_typ (los, nts) gv ty ->\n  gv' @ (cundef_gvs gv ty) ->\n  gv_chunks_match_typ (los, nts) gv' ty.\nProof.\n  unfold instantiate_gvs.\n  intros. subst.\n  eapply cundef_gv__matches_chunks; eauto.\nQed.\n\nLemma cundef_gvs__inhabited : forall gv ty, inhabited (cundef_gvs gv ty).\nProof. auto. Qed.\n\nLemma undef_gvs__getTypeSizeInBits : forall S los nts gv t sz al gv',\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  gv' @ (undef_gvs gv t) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) =\n    sizeGenericValue gv'.\nProof.\n  unfold instantiate_gvs.\n  intros. inv H2. auto.\nQed.\n\nLemma undef_gvs__matches_chunks : forall S los nts gv ty gv',\n  wf_typ S (los,nts) ty ->\n  gv_chunks_match_typ (los, nts) gv ty ->\n  gv' @ (undef_gvs gv ty) ->\n  gv_chunks_match_typ (los, nts) gv' ty.\nProof.\n  unfold instantiate_gvs.\n  intros. subst. auto.\nQed.\n\nLemma undef_gvs__inhabited : forall gv ty, inhabited (undef_gvs gv ty).\nProof. auto. Qed.\n\nLemma cgv2gvs__getTypeSizeInBits : forall S los nts gv t sz al gv',\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  gv' @ (cgv2gvs gv t) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) =\n    sizeGenericValue gv'.\nProof.\n  unfold instantiate_gvs.\n  intros. inv H2.\n  eapply cgv2gv__getTypeSizeInBits; eauto.\nQed.\n\nLemma cgv2gvs__matches_chunks : forall S los nts gv t gv',\n  wf_typ S (los,nts) t ->\n  gv_chunks_match_typ (los, nts) gv t ->\n  gv' @ (cgv2gvs gv t) ->\n  gv_chunks_match_typ (los, nts) gv' t.\nProof.\n  unfold instantiate_gvs.\n  intros. subst. unfold cgv2gvs.\n  destruct gv; auto.\n  destruct p as [[]]; auto. \n  destruct gv; auto.\n  eapply cundef_gvs__matches_chunks; eauto.\nQed.\n\nLemma cgv2gvs__inhabited : forall gv t, inhabited (cgv2gvs gv t).\nProof. auto. Qed.\n\nLemma gv2gvs__getTypeSizeInBits : forall S los nts gv t sz al,\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  forall gv', gv' @ (gv2gvs gv t) ->\n  sizeGenericValue gv' = Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8).\nProof.\n  unfold instantiate_gvs.\n  intros. inv H2. auto.\nQed.\n\nLemma gv2gvs__matches_chunks : forall S los nts gv t,\n  wf_typ S (los,nts) t ->\n  gv_chunks_match_typ (los, nts) gv t ->\n  forall gv', gv' @ (gv2gvs gv t) ->\n  gv_chunks_match_typ (los, nts) gv' t.\nProof.\n  unfold instantiate_gvs.\n  intros. subst. auto.\nQed.\n\nLemma gv2gvs__inhabited : forall gv t, inhabited ($ gv # t $).\nProof. auto. Qed.\n\nDefinition lift_op1 (f: GenericValue -> option GenericValue) (gvs1:t) (ty:typ) :\n  option t := f gvs1.\n\nDefinition lift_op2 (f: GenericValue -> GenericValue -> option GenericValue)\n  (gvs1 gvs2:t) (ty: typ) : option t := f gvs1 gvs2.\n\nLemma lift_op1__inhabited : forall f gvs1 ty gvs2\n  (H:forall x, exists z, f x = Some z),\n  inhabited gvs1 ->\n  lift_op1 f gvs1 ty = Some gvs2 ->\n  inhabited gvs2.\nProof. auto. Qed.\n\nLemma lift_op2__inhabited : forall f gvs1 gvs2 t gvs3\n  (H:forall x y, exists z, f x y = Some z),\n  inhabited gvs1 -> inhabited gvs2 ->\n  lift_op2 f gvs1 gvs2 t = Some gvs3 ->\n  inhabited gvs3.\nProof. auto. Qed.\n\nLemma lift_op1__isnt_stuck : forall f gvs1 ty\n  (H:forall x, exists z, f x = Some z),\n  exists gvs2, lift_op1 f gvs1 ty = Some gvs2.\nProof. unfold lift_op1. auto. Qed.\n\nLemma lift_op2__isnt_stuck : forall f gvs1 gvs2 t\n  (H:forall x y, exists z, f x y = Some z),\n  exists gvs3, lift_op2 f gvs1 gvs2 t = Some gvs3.\nProof. unfold lift_op2. auto. Qed.\n\nLemma lift_op1__getTypeSizeInBits : forall S los nts f g t sz al gvs,\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  (forall x y, x @ g -> f x = Some y ->\n   sizeGenericValue y = nat_of_Z (ZRdiv (Z_of_nat sz) 8)) ->\n  lift_op1 f g t = Some gvs ->\n  forall gv : GenericValue,\n  gv @ gvs ->\n  sizeGenericValue gv = nat_of_Z (ZRdiv (Z_of_nat sz) 8).\nProof. intros. unfold lift_op1 in H2. inv H3. eauto. Qed.\n\nLemma lift_op1__matches_chunks : forall S los nts f g t gvs,\n  wf_typ S (los,nts) t ->\n  (forall x y, instantiate_gvs x g -> f x = Some y ->\n    gv_chunks_match_typ (los, nts) y t) ->\n  lift_op1 f g t = Some gvs ->\n  forall gv : GenericValue,\n  instantiate_gvs gv gvs ->\n  gv_chunks_match_typ (los, nts) gv t.\nProof. intros. unfold lift_op1 in H1. inv H2. eauto. Qed.\n\nLemma lift_op2__getTypeSizeInBits : forall S los nts f g1 g2 t sz al gvs,\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  (forall x y z, x @ g1 -> y @ g2 -> f x y = Some z ->\n   sizeGenericValue z = nat_of_Z (ZRdiv (Z_of_nat sz) 8)) ->\n  lift_op2 f g1 g2 t = Some gvs ->\n  forall gv : GenericValue,\n  gv @ gvs ->\n  sizeGenericValue gv = nat_of_Z (ZRdiv (Z_of_nat sz) 8).\nProof. intros. unfold lift_op2 in H2. inv H3. eauto. Qed.\n\nLemma lift_op2__matches_chunks : forall S los nts f g1 g2 t gvs,\n  wf_typ S (los,nts) t ->\n  (forall x y z,\n   instantiate_gvs x g1 -> instantiate_gvs y g2 -> f x y = Some z ->\n   gv_chunks_match_typ (los, nts) z t) ->\n  lift_op2 f g1 g2 t = Some gvs ->\n  forall gv : GenericValue,\n  instantiate_gvs gv gvs ->\n  gv_chunks_match_typ (los, nts) gv t.\nProof. intros. unfold lift_op2 in H1. inv H2. eauto. Qed.\n\nLemma inhabited_inv : forall gvs, inhabited gvs -> exists gv, gv @ gvs.\nProof. eauto. Qed.\n\nLemma instantiate_undef__undef_gvs : forall gv t, gv @ (undef_gvs gv t).\nProof. auto. Qed.\n\nLemma instantiate_gv__gv2gvs : forall gv t, gv @ ($ gv # t $).\nProof. auto. Qed.\n\nLemma none_undef2gvs_inv : forall gv gv' t,\n  gv @ $ gv' # t $ -> (forall mc, (Vundef, mc)::nil <> gv') -> gv = gv'.\nProof.\n  intros.\n  destruct gv'; try solve [inv H; auto].\nQed.\n\nEnd MDGVs.\n\nDefinition DGVs : GenericValues := mkGVs\nMDGVs.t\nMDGVs.instantiate_gvs\nMDGVs.inhabited\nMDGVs.cgv2gvs\nMDGVs.gv2gvs\nMDGVs.lift_op1\nMDGVs.lift_op2\nMDGVs.cgv2gvs__getTypeSizeInBits\nMDGVs.cgv2gvs__matches_chunks\nMDGVs.cgv2gvs__inhabited\nMDGVs.gv2gvs__getTypeSizeInBits\nMDGVs.gv2gvs__matches_chunks\nMDGVs.gv2gvs__inhabited\nMDGVs.lift_op1__inhabited\nMDGVs.lift_op2__inhabited\nMDGVs.lift_op1__isnt_stuck\nMDGVs.lift_op2__isnt_stuck\nMDGVs.lift_op1__getTypeSizeInBits\nMDGVs.lift_op2__getTypeSizeInBits\nMDGVs.lift_op1__matches_chunks\nMDGVs.lift_op2__matches_chunks\nMDGVs.inhabited_inv\nMDGVs.instantiate_gv__gv2gvs\nMDGVs.none_undef2gvs_inv.\n\nNotation \"gv @ gvs\" :=\n  (DGVs.(instantiate_gvs) gv gvs) (at level 43, right associativity).\nNotation \"$ gv # t $\" := (DGVs.(gv2gvs) gv t) (at level 41).\nNotation \"vidxs @@ vidxss\" := (@Opsem.in_list_gvs DGVs vidxs vidxss)\n  (at level 43, right associativity).\n\n(* Properties of deterministic operational semantics. *)\nLemma dos_in_list_gvs_inv : forall gvs gvss, gvs @@ gvss -> gvs = gvss.\nProof.\n  induction 1; subst; auto.\n    inv H; auto.\nQed.\n\nLemma dos_in_gvs_inv : forall gvs gvss, gvs @ gvss -> gvs = gvss.\nProof.\n  intros. inv H; auto.\nQed.\n\nLtac dgvs_instantiate_inv :=\n  match goal with\n  | [ H : DGVs.(instantiate_gvs) _ _ |- _ ] => inv H\n  | [ H : _ @@ _ |- _ ] => apply dos_in_list_gvs_inv in H; subst\n  end.\n\nLemma dos_instantiate_gvs_intro : forall gv, gv @ gv.\nProof.\nLocal Transparent instantiate_gvs.\n  unfold instantiate_gvs. simpl. auto.\nGlobal Opaque instantiate_gvs.\nQed.\n\nHint Resolve dos_instantiate_gvs_intro.\n\nLemma dos_in_list_gvs_intro : forall gvs, gvs @@ gvs.\nProof.\n  induction gvs; simpl; auto.\nQed.\n\nHint Resolve dos_in_list_gvs_intro.\n\n(*************************************)\nDefinition DGVMap := @Opsem.GVsMap DGVs.\n\n(*************************************)\n(* Aux invariants of wf ECs *)\n\nDefinition wfEC_inv s m (EC: @Opsem.ExecutionContext DGVs) : Prop :=\nuniqFdef (Opsem.CurFunction EC) /\\ \nblockInFdefB (Opsem.CurBB EC) (Opsem.CurFunction EC) = true /\\\nmatch Opsem.CurCmds EC with\n| nil => wf_insn s m (Opsem.CurFunction EC) (Opsem.CurBB EC) \n           (insn_terminator (Opsem.Terminator EC))\n| c::_ => wf_insn s m (Opsem.CurFunction EC) (Opsem.CurBB EC) \n           (insn_cmd c)\nend /\\\nexists l0, exists ps0, exists cs0,\n  Opsem.CurBB EC = (l0, stmts_intro ps0 (cs0 ++ Opsem.CurCmds EC)\n    (Opsem.Terminator EC)).\n\nDefinition wfECs_inv s m (ECs: list (@Opsem.ExecutionContext DGVs)) : Prop :=\nList.Forall (wfEC_inv s m) ECs.\n\nLemma wf_EC__wfEC_inv: forall S los nts Ps EC\n  (HwfS : wf_system S) \n  (HMinS : moduleInSystemB (module_intro los nts Ps) S = true)\n  (Hwfec : OpsemPP.wf_ExecutionContext (los, nts) Ps EC),\n  wfEC_inv S (module_intro los nts Ps) EC.\nProof.\n  destruct EC; simpl.\n  intros.\n  destruct Hwfec as [J1 [J2 [J3 [J4 [J5 J6]]]]].\n  unfold wfEC_inv. simpl.\n  split; eauto 2 using wf_system__uniqFdef.\n  split; auto.\n  split; auto.\n    destruct J6 as [l1 [ps1 [cs1 J6]]]; subst.\n    destruct CurCmds.\n      eapply wf_system__wf_tmn in J2; eauto.\n      eapply wf_system__wf_cmd in J2; eauto using in_middle.\nQed.\n\nLemma wf_ECStack__wfECs_inv: forall S los nts Ps ECs\n  (HwfS : wf_system S) \n  (HMinS : moduleInSystemB (module_intro los nts Ps) S = true)\n  (Hwf : OpsemPP.wf_ECStack (los, nts) Ps ECs),\n  wfECs_inv S (module_intro los nts Ps) ECs.\nProof.\n  unfold wfECs_inv.\n  induction ECs as [|]; simpl; intros; auto.\n    destruct Hwf as [J1 [J2 J3]].\n    constructor; eauto using wf_EC__wfEC_inv.\nQed.\n\nLemma wf_State__wfECs_inv: forall cfg St (Hwfc: OpsemPP.wf_Config cfg) \n  (Hwfst: OpsemPP.wf_State cfg St), \n  wfECs_inv (OpsemAux.CurSystem cfg) \n    (module_intro (fst (OpsemAux.CurTargetData cfg))\n                  (snd (OpsemAux.CurTargetData cfg))\n                  (OpsemAux.CurProducts cfg) )\n    (Opsem.ECS St).\nProof.\n  intros.\n  destruct cfg as [? [? ?] ? ?].\n  destruct St.\n  destruct Hwfc as [? [? [? ?]]].\n  destruct Hwfst. simpl.\n  eapply wf_ECStack__wfECs_inv; eauto.\nQed.\n\nDefinition uniqEC (EC: @Opsem.ExecutionContext DGVs) : Prop :=\nuniqFdef (Opsem.CurFunction EC) /\\ \nblockInFdefB (Opsem.CurBB EC) (Opsem.CurFunction EC) = true /\\\nexists l0, exists ps0, exists cs0,\n  Opsem.CurBB EC = (l0, stmts_intro ps0 (cs0 ++ Opsem.CurCmds EC)\n    (Opsem.Terminator EC)).\n\nDefinition uniqECs (ECs: list (@Opsem.ExecutionContext DGVs)) : Prop :=\nList.Forall uniqEC ECs.\n\nLemma wfEC_inv__uniqEC: forall s m EC (Hwf: wfEC_inv s m EC), uniqEC EC.\nProof.\n  intros.\n  destruct Hwf as [J1 [J3 [_ J2]]]. split; auto.\nQed.\n\nLemma wfECs_inv__uniqECs: forall s m ECs (Hwf: wfECs_inv s m ECs), uniqECs ECs.\nProof.\n  unfold wfECs_inv, uniqECs.\n  intros.\n  induction Hwf; auto.\n    constructor; auto.\n      apply wfEC_inv__uniqEC in H; auto.\nQed.\n\nLemma wf_State__uniqECs: forall cfg St (Hwfc: OpsemPP.wf_Config cfg) \n  (Hwfst: OpsemPP.wf_State cfg St), uniqECs (Opsem.ECS St).\nProof.\n  intros.\n  destruct cfg as [? [? ?] ? ?].\n  destruct St.\n  destruct Hwfc as [? [? [? ?]]].\n  destruct Hwfst. simpl.\n  eapply wf_ECStack__wfECs_inv in H4; eauto.\n  eapply wfECs_inv__uniqECs; eauto.\nQed.\n\nLtac find_uniqEC :=\nrepeat match goal with\n| H: uniqECs (Opsem.ECS {|Opsem.ECS := _; Opsem.Mem := _ |}) |- uniqEC _ => \n  simpl in H\n| H: uniqECs (?EC::_) |- uniqEC ?EC => inv H; auto\n| H: uniqECs (_::?EC::_) |- uniqEC ?EC => inv H; auto\n| H: Forall uniqEC (?EC::_) |- uniqEC ?EC => inv H; auto\n| H: Forall uniqEC (_::?EC::_) |- uniqEC ?EC => inv H; auto\nend.\n\n(*************************************)\n(* More dynamic properties *)\n\nLemma GEP_inv: forall TD t (mp1 : GVsT DGVs) inbounds0 vidxs mp2 t'\n  (H1 : Opsem.GEP TD t mp1 vidxs inbounds0 t' = ret mp2),\n  gundef TD (typ_pointer t') = ret mp2 \\/\n  exists blk, exists ofs1, exists ofs2 : int32, exists m1, exists m2,\n    mp1 = (Vptr blk ofs1, m1) :: nil /\\ mp2 = (Vptr blk ofs2, m2) :: nil.\nProof.\nLocal Transparent lift_op1.\n  intros.\n  unfold Opsem.GEP in H1. unfold lift_op1 in H1. simpl in H1.\n  unfold MDGVs.lift_op1 in H1.\n  unfold gep in H1. unfold GEP in H1.\n  remember (GV2ptr TD (getPointerSize TD) mp1) as R1.\n  destruct R1; auto.\n  destruct (GVs2Nats TD vidxs); auto.\n  remember (mgep TD t v l0) as R2.\n  destruct R2; auto.\n  inv H1.\n  unfold mgep in HeqR2.\n  destruct v; tinv HeqR2.\n  destruct l0; tinv HeqR2.\n  destruct (mgetoffset TD (typ_array 0%nat t) (z :: l0)) as [[]|];\n    inv HeqR2.\n  unfold GV2ptr in HeqR1.\n  destruct mp1 as [|[]]; tinv HeqR1.\n  destruct v; tinv HeqR1.\n  destruct mp1; inv HeqR1.\n  unfold ptr2GV. unfold val2GV. right. exists b0. exists i1.\n  exists (Int.add 31 i1 (Int.repr 31 z0)). exists m.\n  exists (AST.Mint (Size.mul Size.Eight (getPointerSize TD) - 1)).\n  eauto.\nOpaque lift_op1.\nQed.\n\nLemma wf__getTypeStoreSize_eq_sizeGenericValue: forall (gl2 : GVMap)\n  (lc2 : Opsem.GVsMap) (S : system) (los : layouts) (nts : namedts)\n  (Ps : list product) (v1 : value) (gv1 : GenericValue)\n  (Hwfg : LLVMgv.wf_global (los, nts) S gl2) (n : nat) t\n  (HeqR : ret n = getTypeStoreSize (los, nts) t) F\n  (H24 : @Opsem.getOperandValue DGVs (los, nts) v1 lc2 gl2 = ret gv1)\n  (Hwflc1 : OpsemPP.wf_lc (los, nts) F lc2)\n  (Hwfv : wf_value S (module_intro los nts Ps) F v1 t),\n  n = sizeGenericValue gv1.\nProof.\n  intros.\n  eapply OpsemPP.getOperandValue__wf_gvs in Hwflc1; eauto.\n  inv Hwflc1.\n  assert (gv1 @ gv1) as Hinst. auto.\n  apply H2 in Hinst.\n  unfold gv_chunks_match_typ in Hinst.\n  clear - Hinst HeqR Hwfv. inv_mbind.\n  apply wf_value__wf_typ in Hwfv. destruct Hwfv as [J1 J2].\n  symmetry in HeqR0.\n  eapply flatten_typ__getTypeSizeInBits in HeqR0; eauto.\n  destruct HeqR0 as [sz [al [A B]]].          \n  unfold getTypeAllocSize, getTypeStoreSize, getABITypeAlignment,\n         getTypeSizeInBits, getAlignment, \n         getTypeSizeInBits_and_Alignment in HeqR.\n  rewrite A in HeqR.\n  inv HeqR. rewrite B.\n  eapply vm_matches_typ__sizeMC_eq_sizeGenericValue; eauto.\nQed.\n", "meta": {"author": "vellvm", "repo": "vellvm-legacy", "sha": "e4c22d795974ba7c768c18b74fa098b0be2f86f7", "save_path": "github-repos/coq/vellvm-vellvm-legacy", "path": "github-repos/coq/vellvm-vellvm-legacy/vellvm-legacy-e4c22d795974ba7c768c18b74fa098b0be2f86f7/src/Vellvm/dopsem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20267465727715742}}
{"text": "(*\n * Copyright (c) 2009-2016, Andrew Appel, Robert Dockins,\n    Aquinas Hobor and Le Xuan Bach\n *\n *)\n\nRequire Import VST.msl.base.\nRequire Import VST.msl.sepalg.\nRequire Import VST.msl.psepalg.\nRequire Import VST.msl.sepalg_generators.\nRequire Import VST.msl.boolean_alg.\nRequire Import VST.msl.eq_dec.\n\nRequire VST.msl.tree_shares.\n\nModule Share : SHARE_MODEL := tree_shares.Share.\nImport Share.\n\nDefinition share : Type := Share.t.\n\nInstance pa_share : Perm_alg share := Share.pa.\nInstance sa_share : Sep_alg share := Share.sa.\nInstance ca_share : Canc_alg share := Share.ca.\nDefinition emptyshare : share := Share.bot.\nDefinition fullshare : share := Share.top.\n\nTheorem leq_join_sub : forall s1 s2:Share.t,\n  s1 <= s2 <-> join_sub s1 s2.\nProof.\n  split; intros.\n  pose (s' := glb s2 (comp s1)).\n  exists s'.\n  simpl; split.\n  subst s'.\n  rewrite glb_commute.\n  rewrite glb_assoc.\n  rewrite (glb_commute (comp s1) s1).\n  rewrite comp2.\n  apply glb_bot.\n  subst s'.\n  rewrite distrib2.\n  rewrite comp1.\n  rewrite glb_top.\n  rewrite <- ord_spec2; auto.\n\n  destruct H as [s' H].\n  destruct H.\n  rewrite ord_spec2.\n  rewrite <- H0.\n  rewrite <- lub_assoc.\n  rewrite lub_idem; auto.\nQed.\n\nLemma top_correct' : forall x:t, join_sub x top.\nProof.\n  intros; rewrite <- leq_join_sub; auto with ba.\nQed.\n\nLemma bot_identity : identity bot.\nProof.\n  hnf; intros.\n  destruct H.\n  rewrite lub_commute in H0.\n  rewrite lub_bot in H0.\n  auto.\nQed.\n\nHint Resolve bot_identity : core.\n\nLemma identity_share_bot : forall s,\n  identity s -> s = bot.\nProof.\n  intros.\n  apply identities_unique; auto.\n  exists s.\n  apply join_comm.\n\n  destruct (top_correct' s).\n  assert (x = top).\n  apply H; auto.\n  subst x; auto.\n  destruct (top_correct' bot).\n  assert (x = top).\n  apply bot_identity; auto.\n  subst x; auto.\n  apply join_comm in H1.\n  destruct (join_assoc H0 H1); intuition.\n  assert (x = top).\n  apply H; auto.\n  subst x.\n  replace bot with s.\n  rewrite identity_unit_equiv in H.\n  trivial.\n  eapply joins_units_eq; try apply H0. exists top; eauto.\n  simpl. split. apply glb_bot. apply lub_bot.\nQed.\n\nLemma factoryOverlap' : forall f1 f2 n1 n2,\n  isTokenFactory f1 n1 -> isTokenFactory f2 n2 -> joins f1 f2 -> False.\nProof.\n  intros.\n  destruct H1.\n  destruct H1.\n  apply (factoryOverlap f1 f2 n1 n2 H H0 H1).\nQed.\n\nLemma identityToken' : forall x, isToken x 0 <-> identity x.\nProof.\n  intro x; destruct (identityToken x); split; intros.\n  hnf; intros.\n  rewrite H in H2; auto.\n  apply H0.\n  apply identity_share_bot; auto.\nQed.\n\nLemma nonidentityToken' : forall x n, (n > 0)%nat -> isToken x n -> nonidentity x.\nProof.\n  intros.\n  generalize (nonidentityToken x n H H0).\n  repeat intro.\n  apply H1.\n  apply identity_share_bot; auto.\nQed.\n\nLemma nonidentityFactory' : forall x n, isTokenFactory x n -> nonidentity x.\nProof.\n  intros.\n  generalize (nonidentityFactory x n H); repeat intro.\n  apply H0.\n  apply identity_share_bot; auto.\nQed.\n\nLemma split_join : forall x1 x2 x,\n  split x = (x1,x2) -> join x1 x2 x.\nProof.\n  intros; split.\n  apply split_disjoint with x; auto.\n  apply split_together; auto.\nQed.\n\nLemma split_nontrivial' : forall x1 x2 x,\n  split x = (x1, x2) ->\n    (identity x1 \\/ identity x2) ->\n    identity x.\nProof.\n  intros.\n  rewrite (split_nontrivial x1 x2 x H).\n  apply bot_identity.\n  destruct H0.\n  left; apply identity_share_bot; auto.\n  right; apply identity_share_bot; auto.\nQed.\n\nLemma rel_leq : forall a x, join_sub (rel a x) a.\nProof.\n  intros.\n  rewrite <- leq_join_sub.\n\n  intros.\n  rewrite ord_spec1.\n  pattern a at 3.\n  replace a with (rel a top).\n  rewrite <- rel_preserves_glb.\n  rewrite glb_top.\n  auto.\n  apply rel_top1.\nQed.\n\nLemma rel_join : forall a x y z,\n  join x y z ->\n  join (rel a x) (rel a y) (rel a z).\nProof.\n  simpl; intuition. inv H.\n  constructor.\n  rewrite <- rel_preserves_glb.\n  replace bot with (rel a bot).\n  replace (glb x y) with bot; auto.\n  apply rel_bot1.\n  rewrite <- rel_preserves_lub. auto.\nQed.\n\nLemma rel_join2 : forall a x y s,\n  nonidentity a ->\n  join (rel a x) (rel a y) s ->\n  exists z, s = rel a z /\\ join x y z.\nProof.\n  simpl; intros.\n  destruct H0.\n  exists (lub x y).\n  split.\n  rewrite <- H1.\n  symmetry.\n  apply rel_preserves_lub.\n  split; auto.\n  rewrite <- rel_preserves_glb in H0.\n  replace bot with (rel a bot) in H0.\n  apply rel_inj_l with a; auto.\n  hnf; intros; apply H.\n  subst a; apply bot_identity.\n  apply rel_bot1.\nQed.\n\nLemma rel_nontrivial : forall a x,\n  identity (rel a x) ->\n  (identity a \\/ identity x).\nProof.\n  intros a x H.\n  destruct (eq_dec a bot); auto.\n  subst a.\n  left. apply bot_identity.\n\n  right.\n  assert (rel a x = bot).\n  apply identity_share_bot; auto.\n  assert (x = bot).\n  replace bot with (rel a bot) in H0.\n  apply rel_inj_l with a; auto.\n  apply rel_bot1.\n  subst x; apply bot_identity.\nQed.\n\nInstance share_cross_split : Cross_alg t.\nProof.\n  hnf; simpl; intuition. destruct H as [H1 H2]. destruct H0 as [H H3].\n  exists (glb a c, glb a d, glb b c, glb b d); intuition; constructor.\n  rewrite (glb_commute a d).\n  rewrite glb_assoc.\n  rewrite <- (glb_assoc c d a).\n  rewrite H.\n  rewrite (glb_commute bot a).\n  rewrite glb_bot.\n  rewrite glb_bot.\n  auto.\n  rewrite <- distrib1;  rewrite H3; rewrite <- H2; auto with ba.\n  rewrite (glb_commute b d).\n  rewrite glb_assoc.\n  rewrite <- (glb_assoc c d b).\n  rewrite H.\n  rewrite (glb_commute bot b).\n  rewrite glb_bot.\n  rewrite glb_bot.\n  auto.\n  rewrite <- distrib1;  rewrite H3; rewrite <- H2; auto with ba.\n  rewrite (glb_commute a c).\n  rewrite glb_assoc.\n  rewrite <- (glb_assoc a b c).\n  rewrite H1.\n  rewrite (glb_commute bot c).\n  rewrite glb_bot.\n  rewrite glb_bot.\n  auto.\n  rewrite (glb_commute a c).\n  rewrite (glb_commute b c).\n  rewrite <- distrib1; rewrite H2; rewrite <- H3; auto with ba.\n  rewrite (glb_commute a d).\n  rewrite glb_assoc.\n  rewrite <- (glb_assoc a b d).\n  rewrite H1.\n  rewrite (glb_commute bot d).\n  rewrite glb_bot.\n  rewrite glb_bot.\n  auto.\n  rewrite (glb_commute a d).\n  rewrite (glb_commute b d).\n  rewrite <- distrib1; rewrite H2; rewrite <- H3; auto with ba.\nQed.\n\nLemma bot_correct' : forall x, join_sub bot x.\nProof.\n  intros s.\n  destruct (top_correct' s).\n  exists s.\n  destruct (top_correct' bot).\n  assert (x0 = top).\n  apply bot_identity; auto.\n  subst x0.\n  apply join_comm in H0.\n  destruct (join_assoc H H0); intuition.\n  apply join_comm in H2.\n  destruct (join_assoc H1 H2); intuition.\n  assert (s = x1).\n  apply bot_identity; auto.\n  subst x1; auto.\nQed.\n\nLemma top_share_nonidentity : nonidentity top.\nProof.\n  hnf; intros.\n  assert (top = bot).\n  apply identity_share_bot; auto.\n  apply nontrivial; auto.\nQed.\n\nLemma top_share_nonunit: nonunit top.\nProof.\n  repeat intro. unfold unit_for in H.\n  destruct H. rewrite glb_commute in H. rewrite glb_top in H. subst.\n  rewrite lub_bot in H0. apply nontrivial; auto.\nQed.\n\nLemma bot_join_eq : forall x, join bot x x.\nProof.\n  intros.\n  destruct (join_ex_identities x); intuition.\n  destruct H0.\n  generalize (H _ _ H0).\n  intros; subst; auto.\n  replace bot with x0; auto.\n  apply identity_share_bot; auto.\nQed.\n\nLemma join_bot_eq : forall x, join x bot x.\nProof.\n  intros.\n  apply join_comm, bot_join_eq.\nQed.\n\nLemma bot_joins : forall x, joins bot x.\nProof.\n  intro x; exists x; apply bot_join_eq.\nQed.\n\nLemma dec_share_identity : forall x:t, { identity x } + { ~identity x }.\nProof.\n  intro x.\n  destruct (eq_dec x bot); subst.\n  left; apply bot_identity.\n  right; intro; elim n.\n  apply identity_share_bot; auto.\nQed.\n\nLemma dec_share_nonunit : forall x:t, { nonunit x } + { ~ nonunit x }.\nProof.\n  intro x.\n  destruct (dec_share_identity x) as [H | H]; [right | left].\n  + intro; revert H. apply nonunit_nonidentity; auto.\n  + apply nonidentity_nonunit; auto.\nQed.\n\nLemma fullshare_full : full fullshare.\nProof.\n  unfold full.\n  intros.\n  generalize (Share.top_correct);intros.\n  destruct H as [sigma'' ?].\n  specialize (H0 sigma'').\n  rewrite leq_join_sub in H0.\n  destruct H0.\n  destruct (join_assoc H H0) as [s [H1 H2]].\n  apply join_comm in H2. apply unit_identity in H2.\n  eapply split_identity; eauto.\nQed.\n\nLemma join_sub_fullshare : forall sh,\n  join_sub fullshare sh -> sh = fullshare.\nProof.\n  intros.\n  generalize fullshare_full; intro.\n  apply full_maximal in H0.\n  specialize ( H0 sh H).\n  auto.\nQed.\n\nLemma dec_share_full : forall (sh : Share.t),\n  {full sh} + {~full sh}.\nProof with auto.\n  intro sh.\n  destruct (eq_dec sh top); subst.\n  left. apply fullshare_full.\n  right. intro. apply n.\n  generalize (Share.top_correct sh);intro.\n  apply leq_join_sub in H0.\n  destruct H0.\n  specialize ( H x). spec H. exists top...\n  specialize ( H sh top (join_comm H0))...\nQed.\n\nLemma rel_congruence : forall a x1 x2,\n  join_sub x1 x2 ->\n  join_sub (rel a x1) (rel a x2).\nProof.\n  intros.\n  destruct H.\n  exists (rel a x).\n  apply rel_join; auto.\nQed.\n\nLemma share_split_injective:\n  forall sh1 sh2, Share.split sh1 = Share.split sh2 -> sh1=sh2.\nProof.\n  intros sh1 sh2;\n    case_eq (Share.split sh1); case_eq (Share.split sh2); intros.\n  generalize (split_join _ _ _ H); intro.\n  generalize (split_join _ _ _ H0); intro.\n  inv H1.\n  eapply join_eq; eauto.\nQed.\n\nLemma share_joins_constructive:\n  forall sh1 sh2 : t , joins sh1 sh2 ->  {sh3 | join sh1 sh2 sh3}.\nProof.\n  intros.\n  exists (lub sh1 sh2).\n  destruct H.\n  destruct H; split; auto.\nQed.\n\nLemma share_join_sub_constructive:\n  forall sh1 sh3 : t , join_sub sh1 sh3 ->  {sh2 | join sh1 sh2 sh3}.\nProof.\n  intros.\n  exists (glb sh3 (comp sh1)).\n  destruct H.\n  destruct H.\n  split.\n  rewrite (glb_commute sh3 (comp sh1)).\n  rewrite <- glb_assoc.\n  rewrite comp2.\n  rewrite glb_commute.\n  rewrite glb_bot.\n  auto.\n  rewrite distrib2.\n  rewrite comp1.\n  rewrite glb_top.\n  rewrite <- ord_spec2.\n  rewrite <- H0.\n  apply lub_upper1.\nQed.\n\nLemma triple_join_exists_share : Trip_alg t.\nProof.\n  repeat intro.\n  destruct H; destruct H0; destruct H1.\n  exists (lub a (lub b c)).\n  split.\n  rewrite <- H2.\n  rewrite glb_commute.\n  rewrite distrib1.\n  rewrite glb_commute.\n  rewrite H1.\n  rewrite glb_commute.\n  rewrite H0.\n  rewrite lub_bot; auto.\n  rewrite <- H2.\n  apply lub_assoc.\nQed.\n\nLemma nonemp_split_neq1: forall sh sh1 sh2, nonidentity sh -> split sh = (sh1, sh2) -> sh1 <> sh.\nProof with auto.\n  intros until sh2; intros H H0.\n  destruct (dec_share_identity sh2).\n  generalize (split_nontrivial' _ _ _ H0); intro.\n  spec H1...\n  destruct (eq_dec sh1 sh)...\n  subst sh1.\n  generalize (split_join _ _ _ H0); intro.\n  apply join_comm in H1.\n  apply unit_identity in H1...\nQed.\n\nLemma nonemp_split_neq2: forall sh sh1 sh2, nonidentity sh -> split sh = (sh1, sh2) -> sh2 <> sh.\nProof with auto.\n  intros until sh2; intros H H0.\n  destruct (dec_share_identity sh1).\n  generalize (split_nontrivial' _ _ _ H0); intro.\n  spec H1...\n  destruct (eq_dec sh2 sh)...\n  subst sh2.\n  generalize (split_join _ _ _ H0); intro.\n  apply unit_identity in H1...\nQed.\n\nLemma bot_unit: forall sh,\n  join emptyshare sh sh.\nProof.\n  intro sh.\n  generalize (bot_joins sh); generalize bot_identity; intros.\n  destruct H0.\n  specialize ( H sh x H0). subst.\n  trivial.\nQed.\n\nHint Resolve bot_unit : core.\n\nLemma join_bot: join emptyshare emptyshare emptyshare.\nProof.\n  apply bot_unit.\nQed.\n\n\nLemma share_rel_nonidentity:\n  forall {sh1 sh2}, nonidentity sh1 -> nonidentity sh2 -> nonidentity (Share.rel sh1 sh2).\nProof.\nintros.\nunfold nonidentity in *.\ngeneralize (rel_nontrivial sh1 sh2); intro. intuition.\nQed.\n\nLemma share_rel_nonunit: forall {sh1 sh2: Share.t},\n       nonunit sh1 -> nonunit sh2 -> nonunit (Share.rel sh1 sh2).\nProof. intros. apply nonidentity_nonunit. apply share_rel_nonidentity.\nintro. apply (@identity_unit _ _ _ sh1 Share.bot) in H1. apply H in H1; auto.\napply joins_comm. apply bot_joins.\nintro. apply (@identity_unit _ _ _ sh2 Share.bot) in H1. apply H0 in H1; auto.\napply joins_comm. apply bot_joins.\nQed.\n\n\nLemma decompose_bijection: forall sh1 sh2,\n sh1 = sh2 <-> decompose sh1 = decompose sh2.\nProof.\n intros.\n split;intros. subst;trivial.\n generalize (recompose_decompose sh1);intro.\n generalize (recompose_decompose sh2);intro.\n congruence.\nQed.\n\nModule ShareMap.\nSection SM.\n  Variable A:Type.\n  Variable EqDec_A : EqDec A.\n\n  Variable B:Type.\n  Variable JB: Join B.\n  Variable paB : Perm_alg B.\n  Variable saB : Sep_alg B.\n\n  Definition map := fpm A (lifted Share.Join_ba * B).\n  Instance Join_map : Join map := Join_fpm _.\n  Instance pa_map : Perm_alg map := Perm_fpm _ _.\n  Instance sa_map : Sep_alg map := Sep_fpm _ _.\n  Instance ca_map {CA: Canc_alg B} : Canc_alg map := Canc_fpm _.\n  Instance da_map {DA: Disj_alg B} : Disj_alg map := @Disj_fpm _ _ _ _ _ _.\n\n  Definition map_share (a:A) (m:map) : share :=\n    match lookup_fpm m a with\n    | Some (sh,_) => lifted_obj sh\n    | None => Share.bot\n    end.\n\n  Definition map_val (a:A) (m:map) : option B :=\n    match lookup_fpm m a with\n    | Some (_,b) => Some b\n    | None => None\n    end.\n\n  Definition empty_map : map := empty_fpm _ _.\n\n  Definition map_upd (a:A) (b:B) (m:map) : option map :=\n    match lookup_fpm m a with\n    | Some (sh,_) =>\n        if eq_dec (lifted_obj sh) fullshare\n           then Some (insert_fpm _ a (sh,b) m)\n           else None\n    | None => None\n    end.\n\nLemma join_lifted {t} {J: Join t}:\n    forall (a b c: lifted J), join a b c -> join (lifted_obj a) (lifted_obj b) (lifted_obj c).\nProof. destruct a; destruct b; destruct c; simpl; intros. apply H.\nQed.\n\n  Lemma map_join_char : forall m1 m2 m3,\n    join m1 m2 m3 <->\n    (forall a,\n       join (map_share a m1) (map_share a m2) (map_share a m3) /\\\n       join (map_val a m1) (map_val a m2) (map_val a m3)).\n  Proof with auto.\n    split; intros.\n    hnf in H. specialize ( H a).\n    unfold map_val, map_share, lookup_fpm.\n    destruct (proj1_sig m1 a) as [[sh1 a1] | ];\n    destruct (proj1_sig m2 a) as [[sh2 a2] | ];\n    destruct (proj1_sig m3 a) as [[sh3 a3] | ]; inv H; try solve [inv H0]; simpl; auto.\n    destruct H3; simpl in *; auto.\n    split. apply join_lifted; auto. constructor; auto.\n    split; apply join_unit2; auto.\n    split; apply join_unit1; auto.\n    split; apply join_unit1; auto.\n    split; apply join_unit1; auto.\n\n    intro a. specialize ( H a). destruct H.\n        unfold map_val, map_share, lookup_fpm in *.\n    destruct (proj1_sig m1 a) as [[sh1 a1] | ];\n    destruct (proj1_sig m2 a) as [[sh2 a2] | ];\n    destruct (proj1_sig m3 a) as [[sh3 a3] | ]; inv H0; try solve [inv H1]; auto.\n    constructor. split; auto.\n    apply join_unit2_e in H; auto. apply join_unit2; auto.\n    repeat f_equal. destruct sh1; destruct sh3; simpl in *; subst.\n    rewrite (proof_irr n n0); auto.\n    apply join_unit1_e in H; auto. apply join_unit1; auto.\n    repeat f_equal. destruct sh2; destruct sh3; simpl in *; subst.\n    rewrite (proof_irr n n0); auto.\n    constructor. constructor.\n Qed.\n\n  Lemma empty_map_identity {CAB: Disj_alg B}: identity empty_map.\n  Proof.\n    rewrite identity_unit_equiv.\n    intro x. simpl. auto. constructor.\n  Qed.\n\n  Lemma map_identity_unique {CAB: Disj_alg B}: forall m1 m2:map,\n    identity m1 -> identity m2 -> m1 = m2.\n  Proof.\n    intros.\n    destruct m1; destruct m2; simpl in *.\n    cut (x = x0). intros. subst x0.\n    replace f0 with f; auto.\n    apply proof_irr; auto.\n    rewrite identity_unit_equiv in H, H0.\n    extensionality a.\n    specialize ( H a); specialize ( H0 a).\n    apply lower_inv in H.\n    apply lower_inv in H0.\n    destruct H; destruct H0; simpl in *.\n    intuition; congruence.\n    destruct s0 as [? [? [? [? [? [? ?]]]]]].\n    rewrite H in H1. inv H1. rewrite H0 in H; inv H.\n    destruct x3. destruct H2. simpl in *. apply no_units in H. contradiction.\n    destruct s as [? [? [? [? [? [? ?]]]]]].\n    rewrite H in H0; inv H0. rewrite H1 in H; inv H.\n    destruct x2. destruct H2. simpl in *. apply no_units in H. contradiction.\n    destruct s as [? [? [? [? [? [? ?]]]]]].\n    rewrite H in H0; inv H0. rewrite H1 in H; inv H.\n    destruct x2. destruct H2. simpl in *. apply no_units in H. contradiction.\n  Qed.\n\n  Lemma map_identity_is_empty  {CAB: Disj_alg B} : forall m,\n    identity m -> m = empty_map.\n  Proof.\n    intros; apply map_identity_unique; auto.\n    apply empty_map_identity.\n  Qed.\n\n  Lemma empty_map_join {CAB: Disj_alg B} : forall m,\n    join empty_map m m.\n  Proof.\n    intro m. destruct (join_ex_units m).\n    replace empty_map with x; auto.\n    apply map_identity_is_empty.\n    eapply unit_identity; eauto.\n  Qed.\n\n  Lemma map_val_bot  : forall a m,\n    map_val a m = None <-> map_share a m = Share.bot.\n  Proof.\n    do 2 intro.\n    unfold map_val, map_share, lookup_fpm.\n    destruct (proj1_sig m a); intuition.\n    disc.\n    contradiction (no_units a0 a0). destruct a0. simpl in *. subst.\n    contradiction (n bot). auto.\n  Qed.\n\n  Lemma map_upd_success : forall a v m,\n    map_share a m = Share.top ->\n    exists m', map_upd a v m = Some m'.\n  Proof.\n    intros.\n    unfold map_upd. simpl.\n    unfold map_share, lookup_fpm in*.\n    destruct (proj1_sig  m a).\n    destruct p.\n    rewrite H.\n    unfold fullshare.\n    destruct (eq_dec top top).\n    eauto.\n    elim n; auto.\n    elim Share.nontrivial; auto.\n  Qed.\n\n  Lemma map_set_share1 : forall a v m m',\n    map_upd a v m = Some m' ->\n    map_share a m = Share.top.\n  Proof.\n    unfold map_upd, map_share.\n    intros.\n    destruct (lookup_fpm m a); disc.\n    destruct p.\n    destruct (eq_dec (lifted_obj l) fullshare); disc; auto.\n  Qed.\n\n  Lemma map_set_share2 : forall a v m m',\n    map_upd a v m = Some m' ->\n    map_share a m' = Share.top.\n  Proof.\n    unfold map_upd, map_share.\n    intros. destruct (lookup_fpm m a); disc.\n    destruct p. destruct (eq_dec (lifted_obj l) fullshare); disc.\n    inv H.\n    rewrite fpm_gss. auto.\n  Qed.\n\n  Lemma map_set_share3 : forall a v m m',\n    map_upd a v m = Some m' ->\n    forall a',\n      map_share a' m = map_share a' m'.\n  Proof.\n    unfold map_upd, map_share.\n    intros a v m m'.\n    case_eq (lookup_fpm m a); intros; disc.\n    destruct p.\n    destruct (eq_dec (lifted_obj l) fullshare); disc.\n    inv H0.\n    destruct (eq_dec a a'). subst.\n    rewrite H.\n    rewrite fpm_gss. auto.\n    rewrite fpm_gso; auto.\n  Qed.\n\n  Lemma map_gss_val: forall a v m m',\n        map_upd a v m = Some m' ->\n        map_val a m' = Some v.\n  Proof.\n    unfold map_upd, map_val.\n    intros a v m m'.\n    case_eq (lookup_fpm m a); intros; disc.\n    destruct p.\n    destruct (eq_dec (lifted_obj l) fullshare); disc.\n    inv H0.\n    rewrite fpm_gss. auto.\n  Qed.\n\n  Lemma map_gso_val : forall i j v m m',\n       i <> j ->\n       map_upd j v m = Some m' ->\n       map_val i m = map_val i m'.\n  Proof.\n    unfold map_upd, map_val.\n    intros i j v m m'.\n    case_eq (lookup_fpm m j); intros; disc.\n    destruct p.\n    destruct (eq_dec (lifted_obj l) fullshare); disc.\n    inv H1.\n    rewrite fpm_gso; auto.\n  Qed.\n\n  Lemma map_gso_share : forall i j v m m',\n    i <> j ->\n    map_upd j v m = Some m' ->\n    map_share i m = map_share i m'.\n  Proof.\n    unfold map_upd, map_share.\n    intros i j v m m'.\n    case_eq (lookup_fpm m j); intros; disc.\n    destruct p.\n    destruct (eq_dec (lifted_obj l) fullshare); disc.\n    inv H1.\n    rewrite fpm_gso; auto.\n  Qed.\n\n  Lemma map_upd_join : forall m1 m2 m3 a v m1',\n    map_upd a v m1 = Some m1' ->\n    join m1 m2 m3 ->\n    exists m3', map_upd a v m3 = Some m3' /\\\n      join m1' m2 m3'.\n  Proof.\n    intros.\n    rewrite map_join_char in H0.\n    destruct (H0 a).\n    generalize H; intros.\n    apply map_set_share1 in H.\n    rewrite H in H1.\n    destruct H1.\n    rewrite glb_commute in H1.\n    rewrite glb_top in H1.\n    rewrite H1 in H4.\n    rewrite lub_bot in H4.\n    symmetry in H4.\n    destruct (map_upd_success a v _ H4).\n    exists x; split; auto.\n    clear H2.\n    rewrite map_join_char.\n    intro a'.\n    destruct (eq_dec a a').\n    subst a'. split.\n    apply map_set_share2 in H3. rewrite H3.\n    apply map_set_share2 in H5. rewrite H5.\n    rewrite H1. apply join_unit2; auto.\n    erewrite map_gss_val; eauto.\n    apply map_val_bot in H1. rewrite H1.\n    erewrite map_gss_val; eauto. constructor.\n    destruct (H0 a'). split.\n    rewrite <- (map_gso_share a' a v m1 m1'); auto.\n    rewrite <- (map_gso_share a' a v m3 x); auto.\n    rewrite <- (map_gso_val a' a v m1 m1'); auto.\n    rewrite <- (map_gso_val a' a v m3 x); auto.\n  Qed.\n\n  Definition build_map (l:list (A * B)) : map :=\n     fold_right\n      (fun (ab:A * B) m =>\n        insert_fpm EqDec_A\n           (fst ab)\n           (mk_lifted fullshare top_share_nonunit,snd ab) m)\n      empty_map l.\n\n  Lemma build_map_results : forall (l:list (A*B)) a b,\n    NoDup (List.map (@fst _ _) l) ->\n    (In (a,b) l <->\n    (map_val a (build_map l) = Some b /\\\n     map_share a (build_map l) = Share.top)).\n  Proof.\n    induction l; simpl.\n    split; intros. elim H0.\n    destruct H0.\n    unfold build_map in H0. simpl in H0.\n    unfold map_val in H0.\n    simpl in H0. discriminate.\n    intros. split; intros.\n    destruct H0; subst.\n    unfold build_map.\n    simpl fold_right.\n    split.\n    unfold map_val.\n    rewrite fpm_gss. simpl; auto.\n    unfold map_share.\n    rewrite fpm_gss. simpl; auto.\n    generalize H0; intro H1.\n    rewrite IHl in H0.\n    inv H.\n    assert (fst a <> a0).\n    intro. subst a0.\n    elim H4.\n    clear -H1. induction l; simpl in *; intuition; subst; auto.\n    destruct H0.\n    unfold build_map. simpl fold_right.\n    split.\n    unfold map_val.\n    rewrite fpm_gso; auto.\n    unfold map_share.\n    rewrite fpm_gso; auto.\n    inv H. auto.\n    inv H.\n    destruct H0.\n    destruct a.\n    destruct (eq_dec a a0).\n    subst a0.\n    left. f_equal.\n    unfold build_map in H.\n    unfold map_val in H.\n    simpl fold_right in H.\n    rewrite fpm_gss in H.\n    inv H. auto.\n    right.\n    rewrite IHl; auto.\n    split.\n    revert H.\n    unfold build_map, map_val.\n    simpl fold_right.\n    rewrite fpm_gso; auto.\n    revert H0.\n    unfold build_map, map_share.\n    simpl fold_right.\n    rewrite fpm_gso; auto.\n  Qed.\n\n  Lemma build_map_join : forall (l1 l2:list (A * B)),\n    NoDup (List.map (@fst _ _) (l1++l2)) ->\n    join  (build_map l1)\n          (build_map l2)\n          (build_map (l1++l2)).\n  Proof.\n    induction l1; intros.\n    simpl app.\n    unfold build_map at 1.\n    simpl fold_right.\n    apply empty_fpm_join; auto with typeclass_instances.\n    inv H.\n    simpl app.\n    unfold build_map.\n    simpl fold_right.\n    apply insert_fpm_join. auto with typeclass_instances.\n    2: apply (IHl1 l2); auto.\n    assert (~In (fst a) (List.map (@fst _ _) l2)).\n    intro.\n    elim H2.\n    rewrite map_app.\n    apply in_or_app.\n    auto.\n    clear -H.\n    induction l2; simpl in *.\n    auto.\n    rewrite fpm_gso; auto.\n  Qed.\n\nEnd SM.\nEnd ShareMap.\n\n", "meta": {"author": "Ereboas", "repo": "PL-Final-Project", "sha": "442d296ce43a3728e7a8c2b373db2d331a4a4bbf", "save_path": "github-repos/coq/Ereboas-PL-Final-Project", "path": "github-repos/coq/Ereboas-PL-Final-Project/PL-Final-Project-442d296ce43a3728e7a8c2b373db2d331a4a4bbf/code/VST/msl/shares.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.2026746572771574}}
{"text": "Require Import Verdi.GhostSimulations.\n\nRequire Import VerdiRaft.Raft.\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.CommonTheorems.\n\nRequire Import VerdiRaft.SpecLemmas.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\n\nRequire Import VerdiRaft.LogsLeaderLogsInterface.\nRequire Import VerdiRaft.LeaderLogsSortedInterface.\nRequire Import VerdiRaft.LeaderLogsContiguousInterface.\nRequire Import VerdiRaft.LeaderLogsLogMatchingInterface.\nRequire Import VerdiRaft.RefinedLogMatchingLemmasInterface.\nRequire Import VerdiRaft.LeadersHaveLeaderLogsStrongInterface.\nRequire Import VerdiRaft.NextIndexSafetyInterface.\nRequire Import VerdiRaft.SortedInterface.\nRequire Import VerdiRaft.LeaderLogsLogPropertiesInterface.\n\nSection LogsLeaderLogs.\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {rri : raft_refinement_interface}.\n  Context {llsi : leaderLogs_sorted_interface}.\n  Context {rlmli : refined_log_matching_lemmas_interface}.\n  Context {llci : leaderLogs_contiguous_interface}.\n  Context {lllmi : leaderLogs_entries_match_interface}.\n  Context {lhllsi : leaders_have_leaderLogs_strong_interface}.\n  Context {nisi : nextIndex_safety_interface}.\n  Context {si : sorted_interface}.\n  Context {lpholli : log_properties_hold_on_leader_logs_interface}.\n\n  Definition weak_sanity pli ll ll' :=\n    pli = 0 ->\n    (exists e, eIndex e = 0 /\\ In e ll) \\/\n    ll = ll'.\n  \n  Definition logs_leaderLogs_nw_weak net :=\n    forall p t n pli plt es ci e,\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      In e es ->\n      exists leader ll es' ll',\n        In (eTerm e, ll) (leaderLogs (fst (nwState net leader))) /\\\n        Prefix ll' ll /\\\n        removeAfterIndex es (eIndex e) = es' ++ ll' /\\\n        (forall e', In e' es' -> eTerm e' = eTerm e) /\\\n        weak_sanity pli ll ll'.\n\n  Lemma logs_leaderLogs_nw_weaken :\n    forall net,\n      logs_leaderLogs_nw net ->\n      logs_leaderLogs_nw_weak net.\n  Proof using. \n    intros. unfold logs_leaderLogs_nw, logs_leaderLogs_nw_weak, weak_sanity in *.\n    intros.\n    eapply_prop_hyp In In; eauto.\n    break_exists_exists; intuition; subst; try lia.\n    break_exists; intuition; eauto.\n  Qed.\n    \n  Definition logs_leaderLogs_inductive net :=\n    logs_leaderLogs net /\\\n    logs_leaderLogs_nw net.\n\n  Theorem lift_sorted :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      logs_sorted (deghost net).\n  Proof using si rri. \n    intros.\n    eapply lift_prop; eauto using logs_sorted_invariant.\n  Qed.\n  \n  Theorem lift_logs_sorted :\n    forall net h,\n      refined_raft_intermediate_reachable net ->\n      sorted (log (snd (nwState net h))).\n  Proof using si rri. \n    intros.\n    find_apply_lem_hyp lift_sorted.\n    unfold logs_sorted, logs_sorted_host in *.\n    intuition.\n    unfold deghost in *. simpl in *. break_match; eauto.\n  Qed.\n\n  Lemma lift_nextIndex_safety :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      nextIndex_safety (deghost net).\n  Proof using nisi rri. \n    intros.\n    eapply lift_prop; eauto using nextIndex_safety_invariant.\n  Qed.\n\n  \n  Lemma nextIndex_sanity :\n    forall net h h',\n      refined_raft_intermediate_reachable net ->\n      type (snd (nwState net h)) = Leader ->\n      pred (getNextIndex (snd (nwState net h)) h') <> 0 ->\n      exists e,\n        findAtIndex (log (snd (nwState net h))) (pred (getNextIndex (snd (nwState net h)) h')) = Some e.\n  Proof using si nisi rlmli rri. \n    intros.\n    find_copy_apply_lem_hyp entries_contiguous_invariant.\n    find_copy_apply_lem_hyp lift_nextIndex_safety.\n    assert (pred (getNextIndex (snd (nwState net h)) h') > 0) by lia.\n    unfold nextIndex_safety in *.\n    match goal with\n      | H : forall _ _, type _ = _ -> _ |- _ => specialize (H h h')\n    end. \n    intuition.\n    unfold entries_contiguous in *. specialize (H2 h).\n    unfold contiguous_range_exact_lo in *. intuition.\n    match goal with\n      | H : forall _, _ < _ <= _ -> _ |- _ =>\n        specialize (H (pred (getNextIndex (snd (nwState net h)) h')))\n    end.\n    unfold raft_refined_base_params in *.\n    repeat find_rewrite_lem deghost_spec. intuition.\n    break_exists_exists. intuition.\n    apply findAtIndex_intro; eauto using lift_logs_sorted, sorted_uniqueIndices.\n  Qed.\n\n  \n  Lemma update_elections_data_client_request_leaderLogs :\n    forall h st client id c,\n      leaderLogs (update_elections_data_client_request h st client id c) =\n      leaderLogs (fst st).\n  Proof using. \n    unfold update_elections_data_client_request in *.\n    intros. repeat break_match; repeat find_inversion; auto.\n  Qed.\n\n  Lemma update_elections_data_timeout_leaderLogs :\n    forall h st,\n      leaderLogs (update_elections_data_timeout h st) =\n      leaderLogs (fst st).\n  Proof using. \n    unfold update_elections_data_timeout.\n    intros.\n    repeat break_match; simpl in *; auto.\n  Qed.\n\n  Lemma update_elections_data_appendEntries_leaderLogs :\n    forall h st t h' pli plt es ci,\n      leaderLogs (update_elections_data_appendEntries h st t h' pli plt es ci) =\n      leaderLogs (fst st).\n  Proof using. \n    intros.\n    unfold update_elections_data_appendEntries.\n    repeat break_match; subst; simpl in *; auto.\n  Qed.\n  \n  Lemma update_elections_data_requestVote_leaderLogs :\n    forall h h' t lli llt st,\n      leaderLogs (update_elections_data_requestVote h h' t h' lli llt st) =\n      leaderLogs (fst st).\n  Proof using. \n    unfold update_elections_data_requestVote.\n    intros.\n    repeat break_match; auto.\n  Qed.\n\n  Lemma update_elections_data_requestVoteReply_leaderLogs :\n    forall h h' t  st t' ll' r,\n      In (t', ll') (leaderLogs (fst st)) ->\n      In (t', ll') (leaderLogs (update_elections_data_requestVoteReply h h' t r st)).\n  Proof using. \n    unfold update_elections_data_requestVoteReply.\n    intros.\n    repeat break_match; auto.\n    simpl in *. intuition.\n  Qed.\n  \n\n  Ltac prove_in :=\n    match goal with\n      | [ _ : nwPackets ?net = _,\n              _ : In ?p _ |- _] =>\n        assert (In p (nwPackets net)) by (repeat find_rewrite; do_in_app; intuition)\n      | [ _ : nwPackets ?net = _,\n              _ : pBody ?p = _ |- _] =>\n        assert (In p (nwPackets net)) by (repeat find_rewrite; intuition)\n    end.\n\n  Lemma contiguous_log_property :\n    log_property (fun l => contiguous_range_exact_lo l 0).\n  Proof using rlmli. \n    red. intros.\n    apply entries_contiguous_invariant; auto.\n  Qed.\n\n  Lemma leaderLogs_contiguous :\n    forall net h t ll,\n      refined_raft_intermediate_reachable net ->\n      In (t, ll) (leaderLogs (fst (nwState net h))) ->\n      contiguous_range_exact_lo ll 0.\n  Proof using lpholli rlmli. \n    intros. pattern ll.\n    eapply log_properties_hold_on_leader_logs_invariant; eauto using contiguous_log_property.\n  Qed.\n  \n  Lemma logs_leaderLogs_inductive_appendEntries :\n    refined_raft_net_invariant_append_entries logs_leaderLogs_inductive.\n  Proof using lpholli si lllmi llci rlmli llsi rri. \n    red. unfold logs_leaderLogs_inductive. intros.\n    subst. simpl in *. intuition.\n    - unfold logs_leaderLogs in *. intros.\n      simpl in *. repeat find_higher_order_rewrite.\n      update_destruct; subst; rewrite_update; eauto.\n      + simpl in *. find_apply_lem_hyp handleAppendEntries_log.\n        intuition; repeat find_rewrite; eauto.\n        * find_apply_hyp_hyp. break_exists_exists; intuition.\n          find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto.\n          simpl in *.\n          rewrite update_elections_data_appendEntries_leaderLogs. auto.\n        * { subst.\n            find_apply_lem_hyp logs_leaderLogs_nw_weaken.\n            unfold logs_leaderLogs_nw_weak in *.\n            copy_eapply_prop_hyp pBody pBody; eauto.\n            break_exists_exists.\n            break_exists. intuition.\n            - repeat find_higher_order_rewrite.\n              update_destruct; subst; rewrite_update; eauto.\n              simpl.\n              rewrite update_elections_data_appendEntries_leaderLogs.\n              auto.\n            - repeat find_rewrite. f_equal.\n              find_copy_apply_lem_hyp leaderLogs_sorted_invariant; eauto.\n              eapply sorted_Prefix_in_eq; eauto.\n              intros.\n              eapply prefix_contiguous with (i := 0); eauto.\n              + unfold weak_sanity in *. concludes.\n                intuition; subst; simpl in *; intuition.\n                break_exists. intuition.\n                find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto.\n                lia.\n              + eapply leaderLogs_contiguous_invariant; eauto.\n              + assert (sorted (log d)) by (eapply entries_sorted_nw_invariant; eauto).\n                eapply contiguous_app with (l1 := x1).\n                * repeat find_reverse_rewrite.\n                  apply removeAfterIndex_sorted. auto.\n                * repeat find_reverse_rewrite.\n                  eapply removeAfterIndex_contiguous; eauto.\n                  eapply entries_contiguous_nw_invariant; eauto.\n          }\n        * { break_exists. intuition. subst.\n            do_in_app. intuition.\n            - (* new entry *)\n              unfold logs_leaderLogs_nw in *.\n              prove_in.\n              copy_eapply_prop_hyp In In; eauto.\n              match goal with\n                | H:exists _, _ |- _ => destruct H as [leader]\n              end.\n              break_exists; intuition.\n              + (* all of the new entries, as well as x, are in the\n                new term. This means we can apply the host invariant\n                to x and get our leader. *)\n                assert (x2 = []).\n                {\n                  destruct x2; intuition. exfalso.\n                  simpl in *. break_match; intuition.\n                  simpl in *. subst.\n                  find_copy_apply_lem_hyp entries_contiguous_nw_invariant.\n                  eapply_prop_hyp entries_contiguous_nw pBody; eauto.\n                  unfold contiguous_range_exact_lo in *. intuition.\n                  match goal with\n                    | _ : removeAfterIndex _ ?index = _ ++ ?e :: _ |- _ =>\n                      assert (In e es) by\n                          (apply removeAfterIndex_in with (i := index);\n                           repeat find_rewrite; intuition)\n                  end.\n                  eapply_prop_hyp In In. lia.\n                } subst. rewrite app_nil_r in *.\n                match goal with\n                  | H : forall _ _, In _ _ -> _ |- _ =>\n                    specialize (H0 (pDst p) x)\n                end. intuition.\n                break_exists. intuition.\n                match goal with\n                  | _ : In (_, ?ll) (leaderLogs (_ (_ _ ?h))),\n                        _ : removeAfterIndex _ _ = ?es' ++ ?ll |- _ =>\n                    exists h, ll, (removeAfterIndex es (eIndex e) ++ es')\n                end. intuition.\n                * repeat find_rewrite.\n                  match goal with\n                    | H : forall _, st' _ = _ |- _ =>\n                      rewrite H\n                  end.\n                  update_destruct; subst; rewrite_update; eauto.\n                  simpl in *.\n                  rewrite update_elections_data_appendEntries_leaderLogs. auto.\n                * rewrite removeAfterIndex_in_app; auto.\n                  rewrite app_ass. repeat find_rewrite. auto.\n                * repeat find_rewrite. do_in_app. intuition; eauto.\n              + (* we share an entry with the leader, so we can use\n                log matching to make sure our old entries match. we'll\n                get the new entries for free from the nw invariant. *)\n                break_exists; intuition;\n                match goal with\n                  | [ _ : In (_, ?ll) (leaderLogs (_ (_ _ ?leader))),\n                      _ : removeAfterIndex _ _ = ?es' ++ _ |- _ ] =>\n                    exists leader, ll, es'\n                end; intuition.\n                * repeat find_rewrite.\n                  match goal with\n                    | H : forall _, st' _ = _ |- _ =>\n                      rewrite H\n                  end.\n                  update_destruct; subst; rewrite_update; eauto.\n                  simpl in *.\n                  rewrite update_elections_data_appendEntries_leaderLogs. auto.\n                * rewrite removeAfterIndex_in_app; auto.\n                  repeat find_rewrite. rewrite app_ass.\n                  find_copy_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                  f_equal.\n                  eapply thing; eauto using lift_logs_sorted;\n                  [eauto using leaderLogs_contiguous|eapply leaderLogs_entries_match_invariant; eauto|].\n                  assert (sorted es) by (eapply entries_sorted_nw_invariant; eauto).\n                  find_copy_apply_lem_hyp entries_contiguous_nw_invariant.\n                  unfold entries_contiguous_nw in *.\n                  copy_eapply_prop_hyp contiguous_range_exact_lo pBody; eauto.\n                  find_eapply_lem_hyp removeAfterIndex_contiguous; eauto.\n                  match goal with\n                    | H : removeAfterIndex _ _ = _ |- _ =>\n                      find_erewrite_lem H\n                  end.\n                  eapply contiguous_app; eauto.\n                  repeat find_reverse_rewrite. eauto using removeAfterIndex_sorted.\n                * repeat find_rewrite.\n                  match goal with\n                    | H : forall _, st' _ = _ |- _ =>\n                      rewrite H\n                  end.\n                  update_destruct; subst; rewrite_update; eauto.\n                  simpl in *.\n                  rewrite update_elections_data_appendEntries_leaderLogs. auto.\n                * rewrite removeAfterIndex_in_app; auto.\n                  repeat find_rewrite. rewrite app_ass.\n                  f_equal.\n                  assert (x2 = []).\n                  {\n                    destruct x2; intuition. exfalso.\n                    simpl in *. break_match; intuition.\n                    simpl in *. subst.\n                    find_copy_apply_lem_hyp entries_contiguous_nw_invariant.\n                    eapply_prop_hyp entries_contiguous_nw pBody; eauto.\n                    unfold contiguous_range_exact_lo in *. break_and.\n                    match goal with\n                      | _ : removeAfterIndex _ ?index = _ ++ ?e :: _ |- _ =>\n                        assert (In e es) by\n                            (apply removeAfterIndex_in with (i := index);\n                             repeat find_rewrite; intuition)\n                    end.\n                    clear H0 H7.\n                    eapply_prop_hyp In In. lia.\n                  } subst. simpl.\n                  find_copy_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                  match goal with\n                    | |- _ = ?ll =>\n                      rewrite removeAfterIndex_maxIndex_sorted with (l := ll) at 2\n                  end; eauto.\n                  eapply removeAfterIndex_same_sufficient; eauto using lift_logs_sorted;\n                  intros;\n                  match goal with\n                    | _ : eIndex ?e = maxIndex _,\n                          _ : In ?e (log _),\n                              _ : eIndex ?e' = maxIndex _ |- In ?e'' _ =>\n                      assert (eIndex e = eIndex e') as Heq by (repeat find_rewrite; auto);\n                        assert (eIndex e'' <= eIndex e) by lia;\n                        eapply leaderLogs_entries_match_invariant in Heq; eauto;\n                        repeat conclude Heq ltac:(eauto; intuition)\n                  end; intuition.\n            - (* old entry *)\n              (* can use host invariant, since we don't change removeAfterIndex *)\n              find_copy_apply_lem_hyp removeAfterIndex_in.\n              find_copy_apply_lem_hyp removeAfterIndex_In_le; eauto using lift_logs_sorted.\n              find_apply_hyp_hyp. break_exists_exists; intuition.\n              + find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto.\n                simpl in *.\n                rewrite update_elections_data_appendEntries_leaderLogs. auto.\n              + rewrite removeAfterIndex_in_app_l'; eauto;\n                [rewrite <- removeAfterIndex_le; auto|].\n                intros.\n                apply (Nat.le_lt_trans _ (eIndex x)); [auto|].\n                eapply entries_contiguous_nw_invariant; eauto.\n          }\n      + find_apply_hyp_hyp. break_exists_exists; intuition.\n        find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto.\n        simpl in *.\n        rewrite update_elections_data_appendEntries_leaderLogs. auto.\n    - unfold logs_leaderLogs_nw in *.\n      intros. simpl in *. find_apply_hyp_hyp.\n      intuition.\n      + prove_in.\n        copy_eapply_prop_hyp In In; eauto.\n        break_exists_exists; intuition;\n        repeat find_higher_order_rewrite;\n        update_destruct; subst; rewrite_update; eauto;\n        simpl in *;\n        rewrite update_elections_data_appendEntries_leaderLogs; auto.\n      + exfalso. subst. simpl in *.\n        unfold handleAppendEntries in *; repeat break_match; find_inversion; congruence.\n  Qed.\n  \n  Lemma logs_leaderLogs_inductive_appendEntriesReply :\n    refined_raft_net_invariant_append_entries_reply logs_leaderLogs_inductive.\n  Proof using. \n    red. unfold logs_leaderLogs_inductive. intros. intuition.\n    - find_apply_lem_hyp handleAppendEntriesReply_log. subst.\n      unfold logs_leaderLogs in *. intros.\n      simpl in *.\n      find_higher_order_rewrite; update_destruct; subst; rewrite_update; simpl in *;\n      repeat find_rewrite;\n      find_apply_hyp_hyp; break_exists_exists; intuition;\n      find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto.\n    - find_eapply_lem_hyp handleAppendEntriesReply_packets. subst.\n      intuition. unfold logs_leaderLogs_nw in *. intros.\n      simpl in *. find_apply_hyp_hyp. intuition.\n      prove_in. copy_eapply_prop_hyp In In; eauto.\n      break_exists_exists; intuition;\n      repeat find_higher_order_rewrite;\n      update_destruct; subst; rewrite_update; eauto.\n  Qed.\n\n\n  Lemma logs_leaderLogs_inductive_requestVote :\n    refined_raft_net_invariant_request_vote logs_leaderLogs_inductive.\n  Proof using. \n    red. unfold logs_leaderLogs_inductive. intros. intuition.\n    - find_apply_lem_hyp handleRequestVote_log. subst.\n      unfold logs_leaderLogs in *. intros.\n      simpl in *.\n      find_higher_order_rewrite; update_destruct; subst; rewrite_update; simpl in *;\n      repeat find_rewrite;\n      find_apply_hyp_hyp; break_exists_exists; intuition;\n      find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto;\n      simpl in *; rewrite update_elections_data_requestVote_leaderLogs; eauto.\n    - find_eapply_lem_hyp handleRequestVote_no_append_entries. subst.\n      intuition. unfold logs_leaderLogs_nw in *. intros.\n      simpl in *. find_apply_hyp_hyp. intuition.\n      + prove_in. copy_eapply_prop_hyp In In; eauto.\n        break_exists_exists; intuition;\n        repeat find_higher_order_rewrite;\n        update_destruct; subst; rewrite_update; eauto;\n        simpl in *; rewrite update_elections_data_requestVote_leaderLogs; eauto.\n      + find_false. subst. simpl in *. subst.\n        repeat eexists; eauto.\n  Qed.\n  \n  Lemma logs_leaderLogs_inductive_requestVoteReply :\n    refined_raft_net_invariant_request_vote_reply logs_leaderLogs_inductive.\n  Proof using. \n    red. unfold logs_leaderLogs_inductive. intros. intuition.\n    - subst.\n      unfold logs_leaderLogs in *. intros.\n      simpl in *.\n      find_higher_order_rewrite; update_destruct; subst; rewrite_update; simpl in *;\n      repeat find_rewrite;\n      [match goal with\n        | H : In _ (log _ ) |- _ =>\n          erewrite handleRequestVoteReply_log; eauto;\n          erewrite handleRequestVoteReply_log in H; eauto\n      end|];\n      find_apply_hyp_hyp; break_exists_exists; intuition;\n      find_higher_order_rewrite ; update_destruct; subst; rewrite_update; eauto;\n      simpl in *; apply update_elections_data_requestVoteReply_leaderLogs; eauto.\n    - unfold logs_leaderLogs_nw in *. intros.\n      simpl in *. find_apply_hyp_hyp. intuition.\n      prove_in. copy_eapply_prop_hyp In In; eauto.\n      break_exists_exists; intuition;\n      repeat find_higher_order_rewrite;\n      update_destruct; subst; rewrite_update; eauto;\n      simpl in *; apply update_elections_data_requestVoteReply_leaderLogs; eauto.\n  Qed.\n\n  Lemma logs_leaderLogs_inductive_clientRequest :\n    refined_raft_net_invariant_client_request logs_leaderLogs_inductive.\n  Proof using si lhllsi rri. \n    red. unfold logs_leaderLogs_inductive. intros. intuition.\n    - subst.\n      unfold logs_leaderLogs in *. intros.\n      simpl in *.\n      find_higher_order_rewrite; update_destruct; subst; rewrite_update; simpl in *.\n      + find_apply_lem_hyp handleClientRequest_log. intuition; subst; repeat find_rewrite.\n        * find_apply_hyp_hyp; break_exists_exists; intuition;\n          find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto;\n          simpl in *; rewrite update_elections_data_client_request_leaderLogs; eauto.\n        * {break_exists. intuition. repeat find_rewrite. simpl in *.\n           intuition; subst.\n           - find_apply_lem_hyp leaders_have_leaderLogs_strong_invariant; eauto.\n             break_exists. intuition.\n             unfold ghost_data in *. simpl in *. repeat find_rewrite.\n             match goal with\n               | h : name, _ : _ = ?e :: ?es ++ ?ll |- _ =>\n                 exists h, ll, (e :: x0)\n             end; intuition.\n             + find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto;\n               simpl in *; rewrite update_elections_data_client_request_leaderLogs; eauto.\n             + break_if; eauto using app_ass; do_bool; lia.\n             + simpl in *. intuition; subst; eauto.\n           - find_copy_apply_lem_hyp maxIndex_is_max; eauto using lift_logs_sorted.\n             find_apply_hyp_hyp. break_exists_exists; intuition;\n             [find_higher_order_rewrite ; update_destruct; subst; rewrite_update; eauto;\n              simpl in *; rewrite update_elections_data_client_request_leaderLogs; eauto|].\n             break_if; do_bool; intuition; lia.\n          }\n      + find_apply_hyp_hyp; break_exists_exists; intuition;\n        find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto;\n        simpl in *; rewrite update_elections_data_client_request_leaderLogs; eauto.\n    - unfold logs_leaderLogs_nw in *.\n      intros. simpl in *. find_apply_hyp_hyp. intuition.\n      + eapply_prop_hyp In pBody; eauto; break_exists_exists; intuition; subst;\n        repeat find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto;\n        simpl in *; rewrite update_elections_data_client_request_leaderLogs; eauto.\n      + do_in_map. subst. simpl in *. find_eapply_lem_hyp handleClientRequest_no_append_entries;\n          eauto. intuition. find_false. repeat find_rewrite. repeat eexists; eauto.\n  Qed.\n  \n  Lemma logs_leaderLogs_inductive_timeout :\n    refined_raft_net_invariant_timeout logs_leaderLogs_inductive.\n  Proof using. \n    red. unfold logs_leaderLogs_inductive. intros. intuition.\n    - find_apply_lem_hyp handleTimeout_log_same. subst.\n      unfold logs_leaderLogs in *. intros.\n      simpl in *.\n      find_higher_order_rewrite; update_destruct; subst; rewrite_update; simpl in *;\n      repeat find_rewrite;\n      find_apply_hyp_hyp; break_exists_exists; intuition;\n      find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto;\n      simpl in *; rewrite update_elections_data_timeout_leaderLogs; eauto.\n    - intuition. unfold logs_leaderLogs_nw in *. intros.\n      simpl in *. find_apply_hyp_hyp. intuition.\n      + copy_eapply_prop_hyp In In; eauto.\n        break_exists_exists; intuition;\n        repeat find_higher_order_rewrite;\n        update_destruct; subst; rewrite_update; eauto;\n        simpl in *; rewrite update_elections_data_timeout_leaderLogs; eauto.\n      + do_in_map. subst. simpl in *.\n        find_eapply_lem_hyp handleTimeout_packets; eauto. intuition.\n        find_false. repeat find_rewrite.\n        repeat eexists; eauto.\n  Qed.\n\n  Lemma logs_leaderLogs_inductive_doGenericServer :\n    refined_raft_net_invariant_do_generic_server logs_leaderLogs_inductive.\n  Proof using. \n    red. unfold logs_leaderLogs_inductive. intros.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    intuition.\n    - find_apply_lem_hyp doGenericServer_log.\n      unfold logs_leaderLogs in *. intros.\n      simpl in *.\n      find_higher_order_rewrite; update_destruct; subst; rewrite_update; simpl in *;\n      repeat find_rewrite;\n      find_apply_hyp_hyp; break_exists_exists; intuition;\n      find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto.\n    - find_apply_lem_hyp doGenericServer_packets. subst.\n      unfold logs_leaderLogs_nw in *. intros. simpl in *.\n      find_apply_hyp_hyp. intuition.\n      eapply_prop_hyp In In; eauto.\n      break_exists_exists; intuition;\n      repeat find_higher_order_rewrite;\n      update_destruct; subst; rewrite_update; eauto.\n  Qed.\n\n  Lemma doLeader_spec :\n    forall st h os st' ms m t n pli plt es ci,\n      doLeader st h = (os, st', ms) ->\n      In m ms ->\n      snd m = AppendEntries t n pli plt es ci ->\n      t = currentTerm st /\\\n      log st' = log st /\\\n      type st = Leader /\\\n      ((pli = 0 /\\ plt = 0 /\\ es = findGtIndex (log st) 0) \\/\n       ((exists e, findAtIndex (log st) pli = Some e /\\\n              eTerm e = plt) /\\\n        es = findGtIndex (log st) pli) \\/\n       exists h', pred (getNextIndex st h') <> 0 /\\ findAtIndex (log st) (pred (getNextIndex st h')) = None).\n  Proof using. \n    intros. unfold doLeader, advanceCommitIndex in *.\n    break_match; try solve [find_inversion; simpl in *; intuition].\n    break_if; try solve [find_inversion; simpl in *; intuition].\n    find_inversion. simpl. do_in_map. subst.\n    simpl in *. find_inversion. intuition.\n    match goal with\n      | |- context [pred ?x] =>\n        remember (pred x) as index\n    end. break_match; simpl in *.\n    - right. left. eauto.\n    -  destruct index; intuition.\n       right. right. exists x.\n       match goal with\n         | _ : S _ = pred ?x |- context [pred ?y] =>\n           assert (pred x = pred y) by auto\n       end.\n       repeat find_rewrite. intuition.\n  Qed.\n\n  Lemma logs_leaderLogs_inductive_doLeader :\n    refined_raft_net_invariant_do_leader logs_leaderLogs_inductive.\n  Proof using si nisi rlmli llsi rri. \n    red. unfold logs_leaderLogs_inductive. intros.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    intuition.\n    - unfold logs_leaderLogs in *.\n      intros.\n      simpl in *.\n      find_apply_lem_hyp doLeader_log.\n      find_higher_order_rewrite. simpl in *.\n      update_destruct; subst; rewrite_update; simpl in *; repeat find_rewrite;\n      find_apply_hyp_hyp; break_exists_exists; intuition;\n      find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto.\n    - unfold logs_leaderLogs_nw.\n      intros. simpl in *. find_apply_hyp_hyp.\n      break_or_hyp.\n      + unfold logs_leaderLogs_nw in *.\n        eapply_prop_hyp pBody pBody; eauto.\n        break_exists_exists; intuition; subst;\n        find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto.\n      + { do_in_map. subst. simpl in *.\n          find_eapply_lem_hyp doLeader_spec; eauto. intuition.\n          - subst. (* just use host invariant *)\n            unfold logs_leaderLogs in *.\n            find_apply_lem_hyp findGtIndex_necessary.\n            intuition.\n            eapply_prop_hyp In In.\n            break_exists_exists. intuition.\n            match goal with\n              | _ : In (_, ?ll) _ |- _ =>\n                exists ll\n            end.\n            intuition; eauto using Prefix_refl;\n            [find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto|].\n            rewrite sorted_findGtIndex_0; eauto using lift_logs_sorted.\n            intros. eapply entries_gt_0_invariant; eauto.\n          - break_exists. break_and.\n            subst.\n            unfold logs_leaderLogs in *.\n            find_apply_lem_hyp findGtIndex_necessary.\n            break_and. find_apply_hyp_hyp.\n            match goal with\n              | H : exists _ _ _, _ |- _ =>\n                destruct H as [leader];\n                  destruct H as [ll];\n                  destruct H as [es]\n            end.\n            break_and.\n            destruct (lt_eq_lt_dec (maxIndex ll) pli); intuition.\n            + exists leader, ll, (findGtIndex es pli), []. intuition.\n              * find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto.\n              * simpl; auto.\n              * rewrite app_nil_r.\n                rewrite findGtIndex_removeAfterIndex_commute; eauto using lift_logs_sorted.\n                unfold ghost_data in *. simpl in *.\n                find_rewrite.\n                eapply findGtIndex_app_1; lia.\n              * eauto using findGtIndex_in.\n              * left. intuition.\n                match goal with\n                  | H : forall _, In _ _ -> _ |- _ =>\n                    apply H\n                end.\n                find_apply_lem_hyp findAtIndex_elim. intuition.\n                subst.\n                match goal with\n                  | _ : In ?x ?l, _ : eIndex ?e > eIndex ?x |- _ =>\n                    assert (In x (removeAfterIndex l (eIndex e))) by\n                        (apply removeAfterIndex_le_In; eauto; lia)\n                end.\n                unfold ghost_data in *. simpl in *.\n                find_rewrite.\n                do_in_app; intuition.\n                find_copy_apply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                find_apply_lem_hyp maxIndex_is_max; eauto; lia.\n            + exists leader, ll, (findGtIndex es pli), []. intuition.\n              * find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto.\n              * simpl; auto.\n              * rewrite app_nil_r.\n                rewrite findGtIndex_removeAfterIndex_commute; eauto using lift_logs_sorted.\n                unfold ghost_data in *. simpl in *.\n                find_rewrite.\n                apply findGtIndex_app_1. lia.\n              * eauto using findGtIndex_in.\n              * right. find_apply_lem_hyp findAtIndex_elim.\n                left. exists x0. intuition. subst.\n                match goal with\n                  | _ : In ?x ?l, _ : eIndex ?e > _ |- _ =>\n                    assert (In x (removeAfterIndex l (eIndex e))) by\n                        (apply removeAfterIndex_le_In; eauto; lia)\n                end.\n                unfold ghost_data in *. simpl in *.\n                find_rewrite.\n                assert (sorted (es ++ ll)) by (repeat find_reverse_rewrite;\n                                               apply removeAfterIndex_sorted;\n                                               repeat find_rewrite; eauto using lift_logs_sorted).\n                eapply thing3; eauto; try lia. intros.\n                match goal with\n                  | |- eIndex ?e > _ =>\n                    assert (In e (log (snd (nwState net h)))) by\n                        (unfold ghost_data in *; simpl in *;\n                         eapply removeAfterIndex_in; repeat find_reverse_rewrite; eauto)\n                end. \n                eapply entries_gt_0_invariant; eauto.\n            + exists leader, ll, es, (findGtIndex ll pli). intuition.\n              * find_higher_order_rewrite; update_destruct; subst; rewrite_update; eauto.\n              * (* prefix_findGtIndex *)\n                apply findGtIndex_Prefix.\n              * rewrite findGtIndex_removeAfterIndex_commute; eauto using lift_logs_sorted.\n                unfold ghost_data in *. simpl in *.\n                find_rewrite.\n                assert (sorted (es ++ ll)) by (repeat find_reverse_rewrite;\n                                               apply removeAfterIndex_sorted;\n                                               repeat find_rewrite; eauto using lift_logs_sorted).\n                apply findGtIndex_app_2; auto.\n              * { right. left.\n                  find_apply_lem_hyp findAtIndex_elim. \n                  exists x0.  intuition.\n                  - subst.\n                    match goal with\n                      | H : removeAfterIndex _ _ = _ |- _ =>\n                        find_eapply_lem_hyp removeAfterIndex_le_In;\n                          [unfold ghost_data in *; simpl in *; find_rewrite_lem H|lia]\n                    end.\n                    assert (sorted (es ++ ll)) by (repeat find_reverse_rewrite;\n                                                   apply removeAfterIndex_sorted;\n                                                   repeat find_rewrite; eauto using lift_logs_sorted).\n                    eapply thing3; eauto; try lia. intros.\n                     match goal with\n                       | |- eIndex ?e > _ =>\n                         assert (In e (log (snd (nwState net h)))) by\n                             (unfold ghost_data in *; simpl in *;\n                              eapply removeAfterIndex_in; repeat find_reverse_rewrite; eauto)\n                     end. \n                     eapply entries_gt_0_invariant; eauto.\n                  - left. intros.\n                    eapply findGtIndex_non_empty; eauto.\n                }\n          - exfalso. (* use nextIndex_sanity *)\n            break_exists. intuition.\n            find_eapply_lem_hyp nextIndex_sanity; eauto. break_exists.\n            unfold ghost_data in *. simpl in *. congruence.\n        }\n  Qed.\n\n  Lemma logs_leaderLogs_inductive_init :\n    refined_raft_net_invariant_init logs_leaderLogs_inductive.\n  Proof using. \n    unfold logs_leaderLogs_inductive. red. intuition.\n    - unfold logs_leaderLogs. intros. simpl in *. intuition.\n    - unfold logs_leaderLogs_nw. intros. simpl in *. intuition.\n  Qed.\n\n  Lemma logs_leaderLogs_inductive_state_same_packets_subset :\n    refined_raft_net_invariant_state_same_packet_subset logs_leaderLogs_inductive.\n  Proof using. \n    red. unfold logs_leaderLogs_inductive. intuition.\n    - unfold logs_leaderLogs in *. intros.\n      repeat find_reverse_higher_order_rewrite.\n      find_apply_hyp_hyp. break_exists_exists; intuition.\n      find_reverse_higher_order_rewrite. auto.\n    - unfold logs_leaderLogs_nw in *. intros.\n      find_apply_hyp_hyp. eapply_prop_hyp pBody pBody; eauto.\n      break_exists_exists; intuition; subst;\n      repeat find_reverse_higher_order_rewrite; auto.\n  Qed.\n\n  Lemma logs_leaderLogs_inductive_reboot :\n    refined_raft_net_invariant_reboot logs_leaderLogs_inductive.\n  Proof using. \n    red. unfold logs_leaderLogs_inductive. intros.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    intuition.\n    - subst. unfold logs_leaderLogs in *. intros.\n      repeat find_reverse_higher_order_rewrite.\n      find_higher_order_rewrite.\n      update_destruct; subst; rewrite_update; unfold reboot in *; simpl in *;\n      find_apply_hyp_hyp; break_exists_exists; intuition;\n      find_higher_order_rewrite; simpl in *; auto;\n      update_destruct; subst; rewrite_update; simpl in *; auto.\n    - unfold logs_leaderLogs_nw in *. intros.\n      find_reverse_rewrite.\n      eapply_prop_hyp pBody pBody; eauto.\n      break_exists_exists; intuition; subst;\n      repeat find_reverse_higher_order_rewrite; auto;\n      repeat find_higher_order_rewrite; simpl in *; auto;\n      update_destruct; subst; rewrite_update; simpl in *; auto.\n  Qed.\n\n  Theorem logs_leaderLogs_inductive_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      logs_leaderLogs_inductive net.\n  Proof using lpholli si nisi lhllsi lllmi llci rlmli llsi rri. \n    intros.\n    apply refined_raft_net_invariant; auto.\n    - apply logs_leaderLogs_inductive_init.\n    - apply logs_leaderLogs_inductive_clientRequest.\n    - apply logs_leaderLogs_inductive_timeout.\n    - apply logs_leaderLogs_inductive_appendEntries.\n    - apply logs_leaderLogs_inductive_appendEntriesReply.\n    - apply logs_leaderLogs_inductive_requestVote.\n    - apply logs_leaderLogs_inductive_requestVoteReply.\n    - apply logs_leaderLogs_inductive_doLeader.\n    - apply logs_leaderLogs_inductive_doGenericServer.\n    - apply logs_leaderLogs_inductive_state_same_packets_subset.\n    - apply logs_leaderLogs_inductive_reboot.\n  Qed.\n  \n  Theorem logs_leaderLogs_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      logs_leaderLogs net.\n  Proof using lpholli si nisi lhllsi lllmi llci rlmli llsi rri. \n    intros. apply logs_leaderLogs_inductive_invariant. auto.\n  Qed.\n\n  Theorem logs_leaderLogs_nw_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      logs_leaderLogs_nw net.\n  Proof using lpholli si nisi lhllsi lllmi llci rlmli llsi rri. \n    intros. apply logs_leaderLogs_inductive_invariant. auto.\n  Qed.\n\n  Instance llli : logs_leaderLogs_interface.\n  Proof.\n    split; eauto using logs_leaderLogs_invariant, logs_leaderLogs_nw_invariant.\n  Qed.\n\nEnd LogsLeaderLogs.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft-proofs/LogsLeaderLogsProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.36296921930155557, "lm_q1q2_score": 0.2026555185839558}}
{"text": "Require Import Rupicola.Lib.Api.\nRequire Import Crypto.Arithmetic.PrimeFieldTheorems.\nRequire Import Crypto.Bedrock.Specs.Field.\n\nSection Gallina.\n  Definition point {field_parameters : FieldParameters} : Type\n    := (F M_pos * F M_pos).\nEnd Gallina.\n\nSection Compile.\n  Context {semantics : Semantics.parameters}\n          {semantics_ok : Semantics.parameters_ok semantics}.\n  Context {field_parameters : FieldParameters}\n          {field_representation : FieldRepresentation}.\n\n  Lemma compile_point_assign :\n    forall (locals: Semantics.locals) (mem: Semantics.mem)\n           (locals_ok : Semantics.locals -> Prop)\n      tr retvars R functions T (pred: T -> _ -> _ -> Prop)\n      (x y : F M_pos) k k_impl,\n      let v := (x, y) in\n      (let __ := 0 in (* placeholder *)\n       find k_impl\n       implementing (pred (dlet x\n                                (fun x => dlet y\n                                               (fun y => k (x, y)))))\n       and-returning retvars\n       and-locals-post locals_ok\n       with-locals locals and-memory mem and-trace tr and-rest R\n       and-functions functions) ->\n      (let head := v in\n       find k_impl\n       implementing (pred (dlet head k))\n       and-returning retvars\n       and-locals-post locals_ok\n       with-locals locals and-memory mem and-trace tr and-rest R\n       and-functions functions).\n  Proof.\n    repeat straightline'. eauto.\n  Qed.\nEnd Compile.\n", "meta": {"author": "dip-proto", "repo": "fiat-crypto", "sha": "fc3a9280c51f413943c167cc9292e953b8e42c02", "save_path": "github-repos/coq/dip-proto-fiat-crypto", "path": "github-repos/coq/dip-proto-fiat-crypto/fiat-crypto-fc3a9280c51f413943c167cc9292e953b8e42c02/src/Bedrock/Group/Point.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.20265551088912714}}
{"text": "(* This file defines a simple escrow contract based on the \"safe remote\npurchase\" example in Solidity's docs. This contract allows a seller to sell an\nitem in a trustless setting assuming economically rational actors. With the\npremise that the seller wants to sell an item for 1 ETH, the contract works in\nthe following way:\n\n1. The seller deploys the contract and commits 2 ETH.\n2. The buyer commits 2 ETH before the deadline.\n3. The seller hands over the item (outside of the smart contract).\n4. The buyer confirms he has received the item. He gets 1 ETH back\nwhile the seller gets 3 ETH back.\n\nIf the buyer does not commit the funds, the seller gets his money back after the\ndeadline. The economic rationality shows up in our assumption that the seller\nwill confirm he has received the item to get his own funds back. *)\n\nFrom Coq Require Import Bool.\nFrom Coq Require Import ZArith_base.\nFrom Coq Require Import List. Import ListNotations.\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import Monad.\nFrom ConCert.Execution Require Import ResultMonad.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Utils Require Import RecordUpdate.\n\n\n\nSection Escrow.\n  Context `{Base : ChainBase}.\n\n  Set Nonrecursive Elimination Schemes.\n\n  Record Setup :=\n    build_setup {\n      setup_buyer : Address;\n    }.\n\n  Inductive NextStep :=\n  (* Waiting for buyer to commit itemvalue * 2 *)\n  | buyer_commit\n  (* Waiting for buyer to confirm item received *)\n  | buyer_confirm\n  (* Waiting for buyer and seller to withdraw their funds. *)\n  | withdrawals\n  (* No next step, sale is done. *)\n  | no_next_step.\n\n  Record State :=\n    build_state {\n      last_action : nat;\n      next_step : NextStep;\n      seller : Address;\n      buyer : Address;\n      seller_withdrawable : Amount;\n      buyer_withdrawable : Amount;\n    }.\n\n  Definition Error : Type := nat.\n  Definition default_error : Error := 1%nat.\n\n  Inductive Msg :=\n  | commit_money\n  | confirm_item_received\n  | withdraw.\n\n  (* begin hide *)\n  MetaCoq Run (make_setters State).\n  (* end hide *)\n\n  Section Serialization.\n    Global Instance Setup_serializable : Serializable Setup :=\n      Derive Serializable Setup_rect<build_setup>.\n\n    Global Instance NextStep_serializable : Serializable NextStep :=\n      Derive Serializable NextStep_rect<buyer_commit, buyer_confirm, withdrawals, no_next_step>.\n\n    Global Instance State_serializable : Serializable State :=\n      Derive Serializable State_rect<build_state>.\n\n    Global Instance Msg_serializable : Serializable Msg :=\n      Derive Serializable Msg_rect<commit_money, confirm_item_received, withdraw>.\n  End Serialization.\n\n  Open Scope Z.\n  Definition init (chain : Chain)\n                  (ctx : ContractCallContext)\n                  (setup : Setup)\n                  : result State Error :=\n    let seller := ctx_from ctx in\n    let buyer := setup_buyer setup in\n    do if (buyer =? seller)%address then Err default_error else Ok tt;\n    do if ctx_amount ctx =? 0 then Err default_error else Ok tt;\n    do if Z.even (ctx_amount ctx) then Ok tt else Err default_error;\n    Ok (build_state (current_slot chain) buyer_commit seller buyer 0 0).\n\n  Definition subAmountOption (n m : Amount) : option Amount :=\n    if n <? m then None else Some (n - m).\n\n  Definition receive (chain : Chain)\n                     (ctx : ContractCallContext)\n                     (state : State)\n                     (msg : option Msg)\n                     : result (State * list ActionBody) Error :=\n    match msg, next_step state with\n    | Some commit_money, buyer_commit =>\n      do diff_ <- result_of_option (subAmountOption (ctx_contract_balance ctx) (ctx_amount ctx)) default_error;\n      let item_price := diff_ / 2 in\n      let expected := item_price * 2 in\n      do if (ctx_from ctx =? buyer state)%address then Ok tt else Err default_error;\n      do if ctx_amount ctx =? expected then Ok tt else Err default_error;\n      Ok (state<|next_step := buyer_confirm|>\n              <|last_action := current_slot chain|>, [])\n\n    | Some confirm_item_received, buyer_confirm =>\n      let item_price := ctx_contract_balance ctx / 4 in\n      do if (ctx_from ctx =? buyer state)%address then Ok tt else Err default_error;\n      do if ctx_amount ctx =? 0 then Ok tt else Err default_error;\n      let new_state :=\n          state<|next_step := withdrawals|>\n              <|buyer_withdrawable := item_price|>\n              <|seller_withdrawable := item_price * 3|> in\n      Ok (new_state, [])\n\n    | Some withdraw, withdrawals =>\n      do if ctx_amount ctx =? 0 then Ok tt else Err default_error;\n      let from := ctx_from ctx in\n      do '(to_pay, new_state) <-\n        match from =? buyer state, from =? seller state with\n        | true, _ => Ok (buyer_withdrawable state, state<|buyer_withdrawable := 0|>)\n        | _, true => Ok (seller_withdrawable state, state<|seller_withdrawable := 0|>)\n        | _, _ => Err default_error\n        end%address;\n      do if to_pay >? 0 then Ok tt else Err default_error;\n      let new_state :=\n          if (buyer_withdrawable new_state =? 0) && (seller_withdrawable new_state =? 0)\n          then new_state<|next_step := no_next_step|>\n          else new_state in\n      Ok (new_state, [act_transfer (ctx_from ctx) to_pay])\n    | Some withdraw, buyer_commit =>\n      do if ctx_amount ctx =? 0 then Ok tt else Err default_error;\n      do if (last_action state + 50 <? current_slot chain)%nat then Err default_error else Ok tt;\n      do if (ctx_from ctx =? seller state)%address then Ok tt else Err default_error;\n      let balance := ctx_contract_balance ctx in\n      Ok (state<|next_step := no_next_step|>, [act_transfer (seller state) balance])\n\n    | _, _ => Err default_error\n    end.\n\n  Definition contract : Contract Setup Msg State Error :=\n    build_contract init receive.\n\nEnd Escrow.\n", "meta": {"author": "AU-COBRA", "repo": "ConCert", "sha": "55ffd996fe89d41677a2ff368d3a5e4be1e997b7", "save_path": "github-repos/coq/AU-COBRA-ConCert", "path": "github-repos/coq/AU-COBRA-ConCert/ConCert-55ffd996fe89d41677a2ff368d3a5e4be1e997b7/examples/escrow/Escrow.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.2026555055540665}}
{"text": "Require Import Assertions.\nRequire Import HahnBase.\nRequire Import Heaps.\nRequire Import List.\nRequire Import Models.\nRequire Import Permissions.\nRequire Import Permutation.\nRequire Import Prelude.\nRequire Import Processes.\nRequire Import Programs.\nRequire Import QArith.\nRequire Import Qcanon.\nRequire Import Utf8.\n\nImport ListNotations.\n\nSet Implicit Arguments.\n\n(** * Soundness *)\n\nModule Type Soundness\n  (doms: Domains)\n  (procs: Processes doms)\n  (heaps: Heaps doms)\n  (progs: Programs doms procs heaps)\n  (models: Models doms procs heaps progs)\n  (assns: Assertions doms procs heaps progs models).\n\nExport doms procs heaps progs models assns.\n\n(** ** Instrumented semantics *)\n\n(** The instrumented semantics [istep] defines the _lock-step execution_\n    of [step] and [pstep]. The instrumented semantics is defined \n    up to bisimulation equivalence of permission processes. This is not\n    strictly necessary (one may do without all [pbisim] conditions and handle\n    bisimulation inside [safe]), but gives some very nice\n    properties (e.g. [istep_bisim_l] and [istep_bisim_r]). *)\n\nInductive istep : Cmd -> Proc -> Heap -> Store -> Label -> Cmd -> Proc -> Heap -> Store -> Prop :=\n  (* internal computation *)\n  | istep_comp C P Q h s C' h' s' :\n    step C h s Lcomp C' h' s' ->\n    bisim P Q ->\n    istep C P h s Lcomp C' Q h' s'\n  (* explicit send *)\n  | istep_send C P Q h s C' P' Q' h' s' v tag :\n    step C h s (Lsend v tag) C' h' s' ->\n    bisim P P' ->\n    pstep P' (PLsend v tag) Q' ->\n    bisim Q' Q ->\n    istep C P h s (Lsend v tag) C' Q h' s'\n  (* explicit receive *)\n  | istep_recv C P Q h s C' P' Q' h' s' v tag :\n    step C h s (Lrecv v tag) C' h' s' ->\n    bisim P P' ->\n    pstep P' (PLrecv v tag) Q' ->\n    bisim Q' Q ->\n    istep C P h s (Lrecv v tag) C' Q h' s'\n  (* explicit communication *)\n  | istep_comm C P Q h s C' P' Q' h' s' v tag :\n    step C h s (Lcomm v tag) C' h' s' ->\n    bisim P P' ->\n    pstep P' (PLcomm v tag) Q' ->\n    bisim Q' Q ->\n    istep C P h s (Lcomm v tag) C' Q h' s'\n  (* explicit querying *)\n  | istep_query C P Q h s C' P' Q' h' s' b :\n    step C h s (Lquery b) C' h' s' ->\n    bisim P P' ->\n    pstep P' (PLassn b) Q' ->\n    bisim Q' Q ->\n    istep C P h s (Lquery b) C' Q h' s'.\n\nLemma istep_comp_proc_pres :\n  forall C P h s C' P' h' s',\n  istep C P h s Lcomp C' P' h' s' -> bisim P P'.\nProof.\n  induction C; intros P h s C' P' h' s' H1; inv H1.\nQed.\n\nLemma istep_seq_l :\n  forall C1 C2 P h s l C1' P' h' s',\n  istep C1 P h s l C1' P' h' s' <->\n  istep (Cseq C1 C2) P h s l (Cseq C1' C2) P' h' s'.\nProof.\n  intros C1 C2 P h s l C1' P' h' s'.\n  split; intro STEP.\n  (* left to right *)\n  - inv STEP; clear STEP.\n    + apply istep_comp; vauto.\n    + rename P'0 into Q.\n      apply istep_send with Q Q'; vauto.\n    + rename P'0 into Q.\n      apply istep_recv with Q Q'; vauto.\n    + rename P'0 into Q.\n      apply istep_comm with Q Q'; vauto.\n    + rename P'0 into Q.\n      apply istep_query with Q Q'; vauto.\n  (* right to left *)\n  - inv STEP; clear STEP.\n    + inv H; vauto. by apply cmd_neg_seq in H5.\n    + inv H; vauto.\n    + inv H; vauto.\n    + inv H; vauto.\n    + inv H; vauto.\nQed.\n\nLemma istep_seq_r :\n  forall C P h s l h' s',\n  step (Cseq Cskip C) h s l C h' s' <->\n  istep (Cseq Cskip C) P h s l C P h' s'.\nProof.\n  intros C P h s l h' s'. split; intro H1.\n  (* left to right *)\n  - induction l; vauto.\n    + inv H1. inv H8.\n    + inv H1. inv H8.\n    + inv H1. inv H8.\n    + inv H1. inv H8.\n  (* right to left *)\n  - induction l; vauto.\n    + inv H1.\n    + inv H1.\n    + inv H1.\n    + inv H1.\n    + inv H1.\nQed.\n\nLemma istep_par_l :\n  forall C1 C2 P h s l C1' P' h' s',\n  istep C1 P h s l C1' P' h' s' <->\n  istep (Cpar C1 C2) P h s l (Cpar C1' C2) P' h' s'.\nProof.\n  intros C1 C2 P h s l C1' P' h' s'.\n  split; intro H; inv H; clear H.\n  - constructor; vauto.\n  - apply istep_send with P'0 Q'; vauto.\n  - apply istep_recv with P'0 Q'; vauto.\n  - apply istep_comm with P'0 Q'; vauto.\n  - apply istep_query with P'0 Q'; vauto.\n  - inv H0; clear H0.\n    + constructor; vauto.\n    + apply prog_sos_neg_C in H10. vauto.\n  - apply istep_send with P'0 Q'; vauto.\n    inv H0; clear H0. by apply prog_sos_neg_C in H12.\n  - apply istep_recv with P'0 Q'; vauto.\n    inv H0; clear H0. by apply prog_sos_neg_C in H12.\n  - apply istep_comm with P'0 Q'; vauto.\n    inv H0; clear H0.\n    + by apply prog_sos_neg_C in H12.\n    + by apply prog_sos_neg_C in H14.\n    + by apply prog_sos_neg_C in H14.\n  - apply istep_query with P'0 Q'; vauto.\n    inv H0; clear H0. by apply prog_sos_neg_C in H12.\nQed.\n\nLemma istep_par_r :\n  forall C1 C2 P h s l C2' P' h' s',\n  istep C2 P h s l C2' P' h' s' <->\n  istep (Cpar C1 C2) P h s l (Cpar C1 C2') P' h' s'.\nProof.\n  intros C1 C2 P h s l C2' P' h' s'.\n  split; intro H; inv H; clear H.\n  - constructor; vauto.\n  - apply istep_send with P'0 Q'; vauto.\n  - apply istep_recv with P'0 Q'; vauto.\n  - apply istep_comm with P'0 Q'; vauto.\n  - apply istep_query with P'0 Q'; vauto.\n  - inv H0; clear H0.\n    + by apply prog_sos_neg_C in H10.\n    + constructor; vauto.\n  - apply istep_send with P'0 Q'; vauto.\n    inv H0; clear H0. by apply prog_sos_neg_C in H12.\n  - apply istep_recv with P'0 Q'; vauto.\n    inv H0; clear H0. by apply prog_sos_neg_C in H12.\n  - apply istep_comm with P'0 Q'; vauto.\n    inv H0; clear H0.\n    + by apply prog_sos_neg_C in H12.\n    + by apply prog_sos_neg_C in H13.\n    + by apply prog_sos_neg_C in H13.\n  - apply istep_query with P'0 Q'; vauto.\n    inv H0; clear H0. by apply prog_sos_neg_C in H12.\nQed.\n\nLemma istep_bisim_l :\n  forall C P1 P2 h s l C' Q h' s',\n  bisim P1 P2 ->\n  istep C P1 h s l C' Q h' s' ->\n  istep C P2 h s l C' Q h' s'.\nProof.\n  intros C P1 P2 h s l C' Q h' s' H1 H2.\n  inv H2; vauto.\n  - apply istep_comp; auto. by rewrite <- H1.\n  - apply istep_send with P' Q'; auto. by rewrite <- H1.\n  - apply istep_recv with P' Q'; auto. by rewrite <- H1.\n  - apply istep_comm with P' Q'; auto. by rewrite <- H1.\n  - apply istep_query with P' Q'; auto. by rewrite <- H1.\nQed.\n\nLemma istep_bisim_r :\n  forall C P h s l C' Q1 Q2 h' s',\n  bisim Q1 Q2 ->\n  istep C P h s l C' Q1 h' s' ->\n  istep C P h s l C' Q2 h' s'.\nProof.\n  intros C P h s l C' Q1 Q2 h' s' H1 H2.\n  inv H2; vauto.\n  - apply istep_comp; auto. by rewrite <- H1.\n  - apply istep_send with P' Q'; auto. by rewrite <- H1.\n  - apply istep_recv with P' Q'; auto. by rewrite <- H1.\n  - apply istep_comm with P' Q'; auto. by rewrite <- H1.\n  - apply istep_query with P' Q'; auto. by rewrite <- H1.\nQed.\n\nAdd Parametric Morphism : istep\n  with signature eq ==> bisim ==> eq ==> eq ==> eq ==> eq ==> bisim ==> eq ==> eq ==> iff as istep_bisim_mor.\nProof.\n  intros C P1 P2 H1 h s l C' Q1 Q2 H2 h' s'. split; intro H3.\n  - apply istep_bisim_l with P1; auto.\n    apply istep_bisim_r with Q1; auto.\n  - apply istep_bisim_l with P2; auto.\n    apply istep_bisim_r with Q2; auto.\nQed.\n\nLemma istep_proc_frame :\n  forall C P Q h s l C' P' h' s',\n  istep C P h s l C' P' h' s' ->\n  istep C (Ppar P Q) h s l C' (Ppar P' Q) h' s'.\nProof.\n  intros C P1 Q h s l C' P1' h' s' H. inv H; vauto.\n  - apply istep_comp; auto. by rewrite H1.\n  - apply istep_send with (Ppar P' Q)(Ppar Q' Q); auto.\n    + by rewrite H1.\n    + by apply pstep_par_frame_l.\n    + by rewrite H3.\n  - apply istep_recv with (Ppar P' Q)(Ppar Q' Q); auto.\n    + by rewrite H1.\n    + by apply pstep_par_frame_l.\n    + by rewrite H3.\n  - apply istep_comm with (Ppar P' Q)(Ppar Q' Q); auto.\n    + by rewrite H1.\n    + by apply pstep_par_frame_l.\n    + by rewrite H3.\n  - apply istep_query with (Ppar P' Q)(Ppar Q' Q); auto.\n    + by rewrite H1.\n    + by apply pstep_par_frame_l.\n    + by rewrite H3.\nQed.\n\nLemma istep_fv_mod :\n  forall l C h P s C' h' P' s',\n  istep C P h s l C' P' h' s' ->\n    (forall x, In x (cmd_fv C') -> In x (cmd_fv C)) /\\\n    (forall x, In x (cmd_mod C') -> In x (cmd_mod C)) /\\\n    (forall x, ~ In x (cmd_mod C) -> s x = s' x).\nProof.\n  induction l; intros C h P s C' h' P' s'; intros STEP.\n  - inv STEP. repeat split; vauto.\n    + intros x H3. apply step_fv_mod in H0.\n      destruct H0 as (M1 & M2 & M3). by apply M1.\n    + intros x H3. apply step_fv_mod in H0.\n      destruct H0 as (M1 & M2 & M3). by apply M2.\n    + intros x H3. apply step_fv_mod in H0.\n      destruct H0 as (M1 & M2 & M3). by apply M3.\n  - inv STEP. repeat split; vauto.\n    + intros x H3. apply step_fv_mod in H1.\n      destruct H1 as (M1 & M2 & M3). by apply M1.\n    + intros x H3. apply step_fv_mod in H1.\n      destruct H1 as (M1 & M2 & M3). by apply M2.\n    + intros x H3. apply step_fv_mod in H1.\n      destruct H1 as (M1 & M2 & M3). by apply M3.\n  - inv STEP. repeat split; vauto.\n    + intros x H3. apply step_fv_mod in H1.\n      destruct H1 as (M1 & M2 & M3). by apply M1.\n    + intros x H3. apply step_fv_mod in H1.\n      destruct H1 as (M1 & M2 & M3). by apply M2.\n    + intros x H3. apply step_fv_mod in H1.\n      destruct H1 as (M1 & M2 & M3). by apply M3.\n  - inv STEP. repeat split; vauto.\n    + intros x H3. apply step_fv_mod in H1.\n      destruct H1 as (M1 & M2 & M3). by apply M1.\n    + intros x H3. apply step_fv_mod in H1.\n      destruct H1 as (M1 & M2 & M3). by apply M2.\n    + intros x H3. apply step_fv_mod in H1.\n      destruct H1 as (M1 & M2 & M3). by apply M3.\n  - inv STEP. repeat split; vauto.\n    + intros x H3. apply step_fv_mod in H.\n      destruct H as (M1 & M2 & M3). by apply M1.\n    + intros x H3. apply step_fv_mod in H.\n      destruct H as (M1 & M2 & M3). by apply M2.\n    + intros x H3. apply step_fv_mod in H.\n      destruct H as (M1 & M2 & M3). by apply M3.\nQed.\n\nLemma istep_agree :\n  forall l C h P s1 s2 C' h' P' s1' (phi : Var -> Prop),\n    (forall x, In x (cmd_fv C) -> phi x) ->\n    (forall x, phi x -> s1 x = s2 x) ->\n    istep C P h s1 l C' P' h' s1' ->\n  exists s2',\n    (forall x, phi x -> s1' x = s2' x) /\\\n    istep C P h s2 l C' P' h' s2'.\nProof.\n  induction l; intros C h P1 s1 s2 C' h' P1' s1' phi H1 H2 STEP.\n  - inv STEP. apply step_agree with (s2 := s2)(phi := phi) in H0; auto.\n    destruct H0 as (s2' & H5 & H6). exists s2'. intuition.\n    apply istep_query with (P' := P')(Q' := Q'); auto.\n  - inv STEP. apply step_agree with (s2 := s2)(phi := phi) in H3; auto.\n    destruct H3 as (s2' & H5 & H6). exists s2'. intuition.\n    apply istep_send with (P' := P')(Q' := Q'); auto.\n  - inv STEP. apply step_agree with (s2 := s2)(phi := phi) in H3; auto.\n    destruct H3 as (s2' & H5 & H6). exists s2'. intuition.\n    apply istep_recv with (P' := P')(Q' := Q'); auto.\n  - inv STEP. apply step_agree with (s2 := s2)(phi := phi) in H3; auto.\n    destruct H3 as (s2' & H5 & H6). exists s2'. intuition.\n    apply istep_comm with (P' := P')(Q' := Q'); auto.\n  - inv STEP. apply step_agree with (s2 := s2)(phi := phi) in H; auto.\n    destruct H as (s2' & H5 & H6). exists s2'. intuition vauto.\nQed.\n\nLemma istep_agree_sim :\n  forall C h P s1 s2 l C' h' P' s1' s2',\n    (forall x, In x (cmd_fv C) -> s1 x = s2 x) ->\n    (forall x, In x (cmd_fv C) -> s1' x = s2' x) ->\n  step C h s1 l C' h' s1' ->\n  istep C P h s2 l C' P' h' s2' ->\n  istep C P h s1 l C' P' h' s1'.\nProof.\n  induction C; intros h P s1 s2 l C' h' P' s1' s2' H1 H2 H3 H4.\n  (* skip *)\n  - inv H3.\n  (* sequential composition *)\n  - inv H3; clear H3.\n    + rewrite <- istep_seq_l. apply IHC1 with s2 s2'; vauto.\n      * intros x D1. apply H1. simpl.\n        apply in_or_app. by left.\n      * intros x D1. apply H2. simpl.\n        apply in_or_app. by left.\n      * by rewrite <- istep_seq_l in H4.\n    + apply istep_comp_proc_pres in H4. rewrite <- H4.\n      rewrite <- istep_seq_r. constructor.\n  (* assignment *)\n  - inv H3. constructor; vauto.\n    by apply istep_comp_proc_pres in H4.\n  (* heap reading *)\n  - inv H3. constructor; vauto.\n    by apply istep_comp_proc_pres in H4.\n  (* heap writing *)\n  - inv H3. constructor; vauto.\n    by apply istep_comp_proc_pres in H4.\n  (* if-then-else *)\n  - inv H3; clear H3.\n    + inv H4. clear H4. constructor; vauto.\n    + inv H4. clear H4. constructor; vauto.\n  (* while loops *)\n  - inv H3. clear H3. inv H4. clear H4.\n    constructor; vauto.\n  (* parallel composition *)\n  - inv H3; clear H3.\n    + apply istep_par_l. apply IHC1 with s2 s2'; vauto.\n      * intros x D1. apply H1. simpl.\n        apply in_or_app. by left.\n      * intros x D1. apply H2. simpl.\n        apply in_or_app. by left.\n      * by apply istep_par_l in H4.\n    + apply istep_par_r. apply IHC2 with s2 s2'; vauto.\n      * intros x D1. apply H1. simpl.\n        apply in_or_app. by right.\n      * intros x D1. apply H2. simpl.\n        apply in_or_app. by right.\n      * by apply istep_par_r in H4.\n    + constructor; vauto. inv H4.\n    + inv H4. clear H4.\n      apply istep_comm with P'0 Q'; vauto.\n    + inv H4. clear H4.\n      apply istep_comm with P'0 Q'; vauto.\n  (* heap allocation *)\n  - inv H3. clear H3. constructor; vauto. inv H4.\n  (* heap disposal *)\n  - inv H3. clear H3. constructor; vauto. inv H4.\n  (* sending *)\n  - inv H3. clear H3. inv H4. clear H4.\n    apply istep_send with P'0 Q'; vauto.\n  (* receiving *)\n  - inv H3. clear H3. inv H4. clear H4.\n    apply istep_recv with P'0 Q'; vauto.\n  - inv H3. clear H3. inv H4. clear H4.\n    apply istep_recv with P'0 Q'; vauto.\n  (* querying *)\n  - inv H3. clear H3. inv H4. clear H4.\n    apply istep_query with P'0 Q'; vauto.\nQed.\n\n(** ** Adequacy *)\n\nDefinition heap_preserve (l: Label)(ph1 ph2: PermHeap): Prop :=\n  match l with\n    | Lsend _ _ => ph1 = ph2\n    | _ => True\n  end.\n\nCoInductive safe (C: Cmd)(ph: PermHeap)(P: Proc)(s: Store)(A: Assn): Prop :=\n  | safe_prog :\n      (* terminating programs satisfy the postcondition *)\n      (C = Cskip -> sat ph P s A) /\\\n      (* computation preserves safety *)\n      (forall phF C' h' s' l,\n        permheap_disj ph phF ->\n        let h := permheap_concr (permheap_add ph phF) in\n        heap_finite h ->\n        psafe P ->\n        step C h s l C' h' s' ->\n      exists ph',\n        heap_preserve l ph ph' /\\\n        permheap_disj ph' phF /\\\n        permheap_concr (permheap_add ph' phF) = h' /\\\n        heap_finite h' /\\\n      exists P',\n        psafe P' /\\\n        istep C P h s l C' P' h' s' /\\\n        safe C' ph' P' s' A) ->\n    safe C ph P s A.\n\nLemma safe_skip :\n  forall ph P s A, sat ph P s A <-> safe Cskip ph P s A.\nProof.\n  intros ph P s A. split; intro H1.\n  - constructor. split; vauto.\n    intros ????????? STEP. inv STEP.\n  - inv H1. clear H1.\n    destruct H as (H & _). by apply H.\nQed.\n\nLemma safe_agree :\n  forall C ph P s1 s2 A,\n    (forall x, assn_fv A x -> s1 x = s2 x) ->\n    (forall x, In x (cmd_fv C) -> s1 x = s2 x) ->\n  safe C ph P s1 A ->\n  safe C ph P s2 A.\nProof.\n  cofix CH.\n  intros C ph P s1 s2 A H1 H2 H3.\n  repeat split.\n  (* termination *)\n  - intro H4. clarify.\n    apply sat_agree with s1; auto.\n    by apply safe_skip in H3.\n  (* computation *)\n  - simpl. intros phF C' h' s' l H4 H5 H6 STEP.\n    generalize STEP. intro STEP'.\n    apply step_agree with (s2 := s1)(phi := fun x => In x (cmd_fv C) \\/ assn_fv A x) in STEP; vauto.\n    2 : { intros x [H7 | H7].\n      + symmetry. by apply H2.\n      + symmetry. by apply H1. }\n    destruct STEP as (s2' & H7 & H8).\n    inv H3. clear H3. destruct H as (_ & H).\n    simpl in H. apply H in H8; vauto. clear H.\n    destruct H8 as (ph' & D1 & D2 & D3 & D4 & P' & D5 & D6 & D7).\n    exists ph'. intuition.\n    exists P'. intuition.\n    + apply istep_agree with (s2 := s2)(phi := fun x => In x (cmd_fv C) \\/ assn_fv A x) in D6; vauto.\n      destruct D6 as (s3 & D6 & D8).\n      apply istep_agree_sim with s2 s3; vauto.\n      * intros x S1. rewrite H7; vauto.\n        apply D6. by left.\n      * intros x [S1 | S1].\n        ** apply H2. vauto.\n        ** apply H1. vauto.\n    + apply CH with s2'; vauto.\n      * intros x S1. symmetry. apply H7. vauto.\n      * intros x S1. symmetry. apply H7. vauto.\n        left. apply step_fv_mod in STEP'.\n        destruct STEP' as (STEP' & _).\n        by apply STEP'.\nQed.\n\nLemma safe_bisim :\n  forall C ph P1 P2 s A,\n  bisim P1 P2 -> safe C ph P1 s A -> safe C ph P2 s A.\nProof.\n  intros C ph P1 P2 s A H1 H2.\n  repeat split.\n  (* termination *)\n  - intro H3. clarify. rewrite <- safe_skip in H2.\n    by rewrite <- H1.\n  (* computation *)\n  - simpl. intros phF C' h' s' l H3 H4 H5 H6.\n    inv H2. clear H2. destruct H as (_ & H2).\n    apply H2 in H6; clear H2; vauto.\n    2 : { by rewrite H1. }\n    destruct H6 as (ph' & D1 & D2 & D3 & D4 & P' & D5 & D6 & D7).\n    exists ph'. intuition.\n    exists P'. intuition.\n    by rewrite <- H1.\nQed.\n\nAdd Parametric Morphism : safe\n  with signature eq ==> eq ==> bisim ==> eq ==> eq ==> iff as safe_mor.\nProof.\n  intros C ph P1 P2 H1 s A. split; intro H2.\n  - apply safe_bisim with P1; auto.\n  - apply safe_bisim with P2; auto.\nQed.\n\n(** ** Proof rules *)\n\nDefinition csl (A1: Assn)(C: Cmd)(A2: Assn): Prop :=\n  forall ph P s, permheap_valid ph -> sat ph P s A1 -> safe C ph P s A2.\n\n(** *** Skip *)\n\nTheorem rule_skip :\n  forall A, csl A Cskip A.\nProof.\n  intros A ph P s H1 H2. by apply safe_skip.\nQed.\n\n(** *** Sequential composition *)\n\nLemma safe_seq :\n  forall C1 C2 A1 A2 ph P s,\n  permheap_valid ph ->\n  safe C1 ph P s A1 ->\n  (forall ph' P' s',\n    permheap_valid ph' ->\n    sat ph' P' s' A1 ->\n    safe C2 ph' P' s' A2) ->\n  safe (Cseq C1 C2) ph P s A2.\nProof.\n  cofix CH.\n  intros C1 C2 A1 A2 ph P s H1 H2 H3.\n  constructor. split.\n  (* termination *)\n  - intro H4. vauto.\n  (* computation *)\n  - simpl. intros phF C' h' s' l H4 H5 H6 STEP.\n    inv STEP; clear STEP.\n    (* step in [C1] *)\n    + apply H2 in H13; auto. clear H2.\n      destruct H13 as (ph'&D1&D2&D3&D4&P'&D5&D6&D7).\n      exists ph'. intuition.\n      exists P'. intuition.\n      * rewrite <- istep_seq_l; auto.\n      * apply CH with A1; auto.\n        by apply permheap_disj_valid_l in D2.\n    (* [C1] terminated *)\n    + exists ph. intuition.\n      exists P. intuition.\n      * rewrite <- istep_seq_r; vauto.\n      * apply H3; auto.\n        by apply safe_skip in H2.\nQed.\n\nTheorem rule_seq :\n  forall A1 A2 A3 C1 C2,\n  csl A1 C1 A2 ->\n  csl A2 C2 A3 ->\n  csl A1 (Cseq C1 C2) A3.\nProof.\n  cofix CH.\n  intros A1 A2 A3 C1 C2 H1 H2. red.\n  intros ph P s H3 H4.\n  apply safe_seq with A2; auto.\nQed.\n\n(** *** If-then-else *)\n\nLemma safe_ite :\n  forall A1 A2 B C1 C2 ph P s,\n  sat ph P s A1 ->\n  (sat ph P s (Astar A1 (Aplain B)) -> safe C1 ph P s A2) ->\n  (sat ph P s (Astar A1 (Aplain (Bnot B))) -> safe C2 ph P s A2) ->\n  safe (Cite B C1 C2) ph P s A2.\nProof.\n  intros A1 A2 B C1 C2 ph P s H1 H2 H3.\n  constructor. split; vauto. simpl.\n  intros phF C' h' s' l H4 H5 H6 STEP.\n  inv STEP; clear STEP; vauto.\n  (* [B] evaluates positively *)\n  - exists ph. intuition.\n    exists P. intuition vauto.\n    apply H2. simpl.\n    exists ph, permheap_iden. intuition auto.\n    { apply permheap_disj_iden_l.\n      by apply permheap_disj_valid_l in H4. }\n    { by rewrite permheap_add_iden_l. }\n    exists P, Pepsilon. intuition.\n    rewrite par_epsilon_r. auto.\n  (* [B] evaluates negatively *)\n  - exists ph. intuition.\n    exists P. intuition vauto.\n    apply H3. simpl.\n    exists ph, permheap_iden. intuition vauto.\n    { apply permheap_disj_iden_l.\n      by apply permheap_disj_valid_l in H4. }\n    { by rewrite permheap_add_iden_l. }\n    exists P, Pepsilon. intuition.\n    rewrite par_epsilon_r. auto.\nQed.\n\nTheorem rule_ite :\n  forall A1 A2 B C1 C2,\n  csl (Astar A1 (Aplain B)) C1 A2 ->\n  csl (Astar A1 (Aplain (Bnot B))) C2 A2 ->\n  csl A1 (Cite B C1 C2) A2.\nProof.\n  intros A1 A2 B C1 C2 H1 H2. red.\n  intros ph P s H3 H4. apply safe_ite with A1; auto.\nQed.\n\n(** *** While loops *)\n\nLemma safe_while1 :\n  forall B C1 C2 ph P s A,\n  safe C1 ph P s A ->\n  csl (Astar A (Aplain B)) C2 A ->\n  safe (Cseq C1 (Cwhile B C2)) ph P s (Astar A (Aplain (Bnot B))).\nProof.\n  cofix CH.\n  intros B C1 C2 ph P s A H1 H2.\n  constructor. split; vauto. simpl.\n  intros phF C' h' s' l H3 H4 H5 STEP.\n  inv STEP; clear STEP.\n  (* step in [C1] *)\n  - apply H1 in H12; auto.\n    destruct H12 as (ph'&D1&D2&D3&D4&P'&D5&D6&D7).\n    exists ph'. intuition.\n    exists P'. intuition.\n    by apply istep_seq_l.\n  (* [C1] terminated *)\n  - exists ph. intuition.\n    exists P. intuition vauto.\n    apply safe_skip in H1.\n    constructor. split; vauto. simpl.\n    intros phF' C' h' s'' l D1 D2 D3 STEP.\n    inv STEP; clear STEP.\n    exists ph. intuition.\n    exists P. intuition vauto.\n    constructor. split; vauto. simpl.\n    intros phF'' C' h' s' l F1 F2 F3 STEP.\n    inv STEP; clear STEP.\n    (* step in [C2] *)\n    + exists ph. intuition.\n      exists P. intuition vauto.\n      apply CH; auto. apply H2; auto.\n      { by apply permheap_disj_valid_l in F1. }\n      exists ph, permheap_iden. intuition.\n      { apply permheap_disj_iden_l.\n        by apply permheap_disj_valid_l in F1. }\n      { by rewrite permheap_add_iden_l. }\n      exists P, Pepsilon. intuition.\n      by apply par_epsilon_r.\n    (* termination of the loop *)\n    + exists ph. intuition.\n      exists P. intuition vauto.\n      apply safe_skip.\n      exists ph, permheap_iden. intuition.\n      { apply permheap_disj_iden_l.\n        by apply permheap_disj_valid_l in F1. }\n      { by rewrite permheap_add_iden_l. }\n      exists P, Pepsilon. intuition vauto.\n      { by apply par_epsilon_r. }\n      simpl. apply eq_true_not_negb. vauto.\nQed.\n\nLemma safe_while2 :\n  forall B C ph P s A,\n  csl (Astar A (Aplain B)) C A ->\n  sat ph P s A ->\n  safe (Cwhile B C) ph P s (Astar A (Aplain (Bnot B))).\nProof.\n  intros B C ph P s A H1 H2. constructor.\n  split; vauto. simpl.\n  intros phF C' h' s' l H3 H4 H5 STEP.\n  inv STEP. clear STEP. exists ph. intuition.\n  exists P. intuition vauto.\n  apply safe_ite with A; auto.\n  (* any loop iteration must be safe *)\n  - intro H6. apply safe_while1; auto.\n    apply H1; auto.\n    by apply permheap_disj_valid_l in H3.\n  (* safety must be preserved after termination of the loop *)\n  - intro H6. by apply safe_skip.\nQed.\n\nTheorem rule_while :\n  forall A B C,\n  csl (Astar A (Aplain B)) C A ->\n  csl A (Cwhile B C) (Astar A (Aplain (Bnot B))).\nProof.\n  intros A B C CSL. red. intros ph P s H1 H2.\n  apply safe_while2; auto.\nQed.\n\n(** *** Assignment *)\n\nLemma safe_assign :\n  forall A x E ph P s,\n  sat ph P s (assn_subst x E A) -> safe (Cass x E) ph P s A.\nProof.\n  cofix CH. intros A x E ph P s H1.\n  repeat split; vauto. simpl.\n  intros phF C' h' s' l H2 H3 H4 STEP. inv STEP.\n  exists ph. intuition.\n  exists P. intuition vauto.\n  apply safe_skip. rewrite sat_subst in H1. vauto.\nQed.\n\nTheorem rule_assign :\n  forall A x E,\n  csl (assn_subst x E A) (Cass x E) A.\nProof.\n  ins. red. split; vauto. ins. by apply safe_assign.\nQed.\n\n(** *** Framing *)\n\nLemma safe_frame :\n  forall C ph1 ph2 P1 P2 s A1 A2,\n  permheap_disj ph1 ph2 ->\n  disjoint (assn_fv A2) (cmd_mod C) ->\n  sat ph2 P2 s A2 ->\n  safe C ph1 P1 s A1 ->\n  safe C (permheap_add ph1 ph2) (Ppar P1 P2) s (Astar A1 A2).\nProof.\n  cofix CH.\n  intros C ph1 ph2 P1 P2 s A1 A2 H1 FV1 SAT1 SAFE1.\n  repeat split.\n  (* termination *)\n  - intros ?. clarify. apply safe_skip in SAFE1.\n    exists ph1, ph2. intuition.\n    exists P1, P2. intuition.\n  (* computation *)\n  - simpl. intros phF C' h' s' l H2 H3 SAFE2 STEP.\n    inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1).\n    rewrite permheap_add_swap_r with (ph2 := ph2) in STEP.\n    rewrite permheap_add_assoc in STEP.\n    rewrite permheap_add_comm with phF ph2 in STEP.\n    apply SAFE1 in STEP; clear SAFE1; vauto.\n    + destruct STEP as (ph' & D1 & D2 & D3 & D4 & P' & D5 & D6 & D7).\n      clarify. exists (permheap_add ph' ph2). intuition.\n      { red in D1. desf. }\n      { apply permheap_disj_assoc_r; auto.\n        apply permheap_disj_add_l with ph1; auto. }\n      { rewrite permheap_add_swap_r with (ph2 := ph2).\n        rewrite permheap_add_assoc.\n        by rewrite permheap_add_comm with phF ph2. }\n      exists (Ppar P' P2). intuition.\n      { apply psafe_par_rev in SAFE2.\n        destruct SAFE2 as (_ & SAFE2).\n        by apply psafe_par. }\n      { rewrite permheap_add_swap_r with (ph2 := ph2).\n        rewrite permheap_add_assoc.\n        rewrite permheap_add_comm with phF ph2.\n        by apply istep_proc_frame. }\n      apply CH; vauto.\n      { apply permheap_disj_add_r with phF; auto.\n        apply permheap_disj_add_l with ph1; auto. }\n      { red. intros x H7 H8. apply istep_fv_mod in D6.\n        destruct D6 as (FV2 & FV3 & FV4).\n        apply FV1 in H7. by apply FV3 in H8. }\n      { apply istep_fv_mod in D6.\n        destruct D6 as (FV2 & FV3 & FV4).\n        apply sat_agree with s; auto.\n        intros x ?. apply FV4. intro. by apply FV1 with x. }\n    + apply permheap_disj_assoc_l; auto.\n    + by rewrite <- permheap_add_assoc.\n    + apply psafe_par_rev in SAFE2. desf.\nQed.\n\nTheorem rule_frame :\n  forall A1 A2 A3 C,\n  disjoint (assn_fv A3) (cmd_mod C) ->\n  csl A1 C A2 ->\n  csl(Astar A1 A3) C (Astar A2 A3).\nProof.\n  intros A1 A2 A3 C H1 H2. red.\n  intros ph P s H3 H4. simpl in H4.\n  destruct H4 as (ph1&ph2&H4&H5&P1&P2&H6&H7&H8).\n  rewrite <- H5, <- H6. apply safe_frame; vauto.\n  apply H2; vauto. by apply permheap_disj_valid_l in H4.\nQed.\n\n(** *** Parallel composition *)\n\nLemma safe_par :\n  forall C1 C2 ph1 ph2 P1 P2 s A1 A2,\n  permheap_disj ph1 ph2 ->\n  disjoint (cmd_fv C1) (cmd_mod C2) ->\n  disjoint (assn_fv A1) (cmd_mod C2) ->\n  disjoint (cmd_fv C2) (cmd_mod C1) ->\n  disjoint (assn_fv A2) (cmd_mod C1) ->\n  safe C1 ph1 P1 s A1 ->\n  safe C2 ph2 P2 s A2 ->\n  safe (Cpar C1 C2) (permheap_add ph1 ph2) (Ppar P1 P2) s (Astar A1 A2).\nProof.\n  cofix CH.\n  intros C1 C2 ph1 ph2 P1 P2 s A1 A2 H1 H2 H3 H4 H5 SAFE1 SAFE2.\n  repeat split.\n  (* termination *)\n  - intro H8. clarify.\n  (* computation *)\n  - simpl. intros phF C' h' s' l H6 H7 SAFE3 STEP.\n    inv STEP; clear STEP.\n    (* step in left program *)\n    + inv SAFE1. clear SAFE1. destruct H as (_ & H).\n      simpl in H. specialize H with (permheap_add ph2 phF) C1' h' s' l.\n      rewrite permheap_add_assoc in H14.\n      apply H in H14; clear H.\n\n      2:{ apply permheap_disj_assoc_l; auto. }\n      2:{ rewrite <- permheap_add_assoc. auto. }\n      2:{ apply psafe_par_rev in SAFE3. desf. }\n\n      destruct H14 as (ph' & D1 & D2 & D3 & D4 & P' & D5 & D6 & D7).\n      exists (permheap_add ph' ph2). intuition.\n\n      { red in D1. desf. }\n      { apply permheap_disj_assoc_r; auto.\n        apply permheap_disj_add_l with ph1; auto. }\n      { by rewrite permheap_add_assoc. }\n\n      exists (Ppar P' P2). intuition.\n\n      { apply psafe_par_rev in SAFE3.\n        destruct SAFE3 as (_ & SAFE3).\n        apply psafe_par; auto. }\n      { clarify. rewrite permheap_add_assoc with ph1 ph2 phF.\n        apply istep_par_l.\n        apply istep_proc_frame. auto. }\n\n      apply CH; auto.\n\n      { apply permheap_disj_add_r with phF; auto.\n        apply permheap_disj_add_l with ph1; auto. }\n      { red. intros x FV1 FV2. apply istep_fv_mod in D6.\n        destruct D6 as (D6 & _).\n        apply D6 in FV1. by apply H2 with x. }\n      { red. intros x FV1 FV2. apply istep_fv_mod in D6.\n        destruct D6 as (_ & D6 & _).\n        apply D6 in FV2. by apply H4 with x. }\n      { red. intros x FV1 FV2. apply istep_fv_mod in D6.\n        destruct D6 as (_ & D6 & _).\n        apply D6 in FV2. by apply H5 with x. }\n\n      apply safe_agree with s; vauto.\n\n      { intros x S1. apply istep_fv_mod in D6.\n        destruct D6 as (_ & _ & D6). apply D6.\n        intro S2. red in H5. apply H5 with x; vauto. }\n      { intros x S1. apply istep_fv_mod in D6.\n        destruct D6 as (_ & _ & D6). apply D6.\n        intro S2. red in H4. apply H4 with x; vauto. }\n\n    (* step in right program *)\n    + inv SAFE2. clear SAFE2. destruct H as (_ & H).\n      simpl in H. specialize H with (permheap_add ph1 phF) C2' h' s' l.\n      rewrite permheap_add_comm with ph1 ph2 in H14.\n      rewrite permheap_add_assoc in H14.\n      apply H in H14; clear H.\n\n      2:{ apply permheap_disj_assoc_l; auto.\n          by rewrite permheap_add_comm. }\n      2:{ rewrite <- permheap_add_assoc.\n          by rewrite permheap_add_comm with ph2 ph1. }\n      2:{ apply psafe_par_rev in SAFE3. desf. }\n\n      destruct H14 as (ph' & D1 & D2 & D3 & D4 & P' & D5 & D6 & D7).\n\n      exists (permheap_add ph1 ph'). intuition.\n\n      { red in D1. desf. }\n      { rewrite permheap_add_comm.\n        apply permheap_disj_assoc_r; auto.\n        apply permheap_disj_add_l with ph2; auto.\n        by rewrite permheap_add_comm. }\n      { rewrite permheap_add_comm with ph1 ph'.\n        by rewrite permheap_add_assoc. }\n      exists (Ppar P1 P'). intuition.\n      { apply psafe_par_rev in SAFE3.\n        destruct SAFE3 as (SAFE3 & _).\n        apply psafe_par; auto. }\n      { clarify. rewrite permheap_add_comm with ph1 ph2.\n        rewrite permheap_add_assoc with ph2 ph1 phF.\n        apply istep_par_r.\n        rewrite par_comm with (P := P1)(Q := P2).\n        rewrite par_comm with (P := P1)(Q := P').\n        apply istep_proc_frame. auto. }\n\n      apply CH; auto.\n\n      { symmetry.\n        apply permheap_disj_add_r with phF; auto.\n        apply permheap_disj_add_l with ph2; auto.\n        by rewrite permheap_add_comm. }\n      { red. intros x FV1 FV2. apply istep_fv_mod in D6.\n        destruct D6 as (_ & D6 & _).\n        apply D6 in FV2. by apply H2 with x. }\n      { red. intros x FV1 FV2. apply istep_fv_mod in D6.\n        destruct D6 as (_ & D6 & _).\n        apply D6 in FV2. by apply H3 with x. }\n      { red. intros x FV1 FV2. apply istep_fv_mod in D6.\n        destruct D6 as (D6 & _ & _).\n        apply D6 in FV1. by apply H4 with x. }\n\n      apply safe_agree with s; vauto.\n\n      { intros x S1. apply istep_fv_mod in D6.\n        destruct D6 as (_ & _ & D6). apply D6.\n        intro S2. red in H3. apply H3 with x; vauto. }\n      { intros x S1. apply istep_fv_mod in D6.\n        destruct D6 as (_ & _ & D6). apply D6.\n        intro S2. red in H2. apply H2 with x; vauto. }\n\n    (* both programs are empty *)\n    + exists (permheap_add ph1 ph2). intuition.\n      exists (Ppar P1 P2). intuition.\n      * constructor; vauto.\n      * apply safe_skip. simpl.\n        exists ph1, ph2. intuition.\n        exists P1, P2. intuition.\n        ** inv SAFE1. clear SAFE1.\n           destruct H as (H & _). by apply H.\n        ** inv SAFE2. clear SAFE2.\n           destruct H as (H & _). by apply H.\n\n    (* communication: left program sends, right program receives *)\n    + inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1).\n      simpl in SAFE1. repeat rewrite permheap_add_assoc in H8.\n      apply SAFE1 in H8; clear SAFE1; vauto.\n\n      2:{ apply permheap_disj_assoc_l; vauto. }\n      2:{ by rewrite <- permheap_add_assoc. }\n      2:{ apply psafe_par_rev in SAFE3. desf. }\n\n      destruct H8 as (ph1' & D1 & D2 & D3 & D4 & P1' & D5 & D6 & D7).\n      simpl in D1. clarify. rename ph1' into ph1. clear D3.\n\n      inv SAFE2. clear SAFE2. destruct H as (_ & SAFE2).\n      simpl in SAFE2. repeat rewrite permheap_add_comm with ph1 ph2 in H15.\n      repeat rewrite permheap_add_assoc in H15.\n      apply SAFE2 in H15; clear SAFE2.\n\n      2:{ apply permheap_disj_assoc_l.\n          - by symmetry.\n          - by rewrite permheap_add_comm with ph2 ph1. }\n      2:{ rewrite <- permheap_add_assoc.\n          by rewrite permheap_add_comm with ph2 ph1. }\n      2:{ apply psafe_par_rev in SAFE3. desf. }\n\n      destruct H15 as (ph2' & F1 & F2 & F3 & F4 & P2' & F5 & F6 & F7).\n      simpl in F1. clear F1.\n\n      exists (permheap_add ph1 ph2'). intuition.\n\n      { red. vauto. }\n      { rewrite permheap_add_comm.\n        apply permheap_disj_assoc_r; auto.\n        apply permheap_disj_add_l with ph2; auto.\n        by rewrite permheap_add_comm. }\n      { rewrite permheap_add_comm with ph1 ph2'.\n        rewrite permheap_add_assoc.\n        rewrite F3.\n        rewrite <- permheap_add_assoc.\n        by rewrite permheap_add_comm with ph2 ph1. }\n\n      exists (Ppar P1' P2'). intuition.\n\n      { apply psafe_par; vauto. }\n      { inv D6. clear D6. inv F6. clear F6.\n        rename P'0 into Q2, Q'0 into Q2'.\n        rename P' into Q1, Q' into Q1'.\n        apply istep_comm with (Ppar Q1 Q2) (Ppar Q1' Q2'); vauto.\n        - apply step_comm_l; vauto.\n          + by repeat rewrite permheap_add_assoc.\n          + repeat rewrite permheap_add_comm with ph1 ph2.\n            by repeat rewrite permheap_add_assoc.\n        - apply bisim_par; vauto.\n        - apply bisim_par; vauto. }\n\n      apply CH; vauto.\n\n      { symmetry. apply permheap_disj_add_r with phF; auto.\n        apply permheap_disj_add_l with ph2; auto.\n        by rewrite permheap_add_comm. }\n      { red. intros x FV1 FV2.\n        apply istep_fv_mod in D6. destruct D6 as (D6 & _).\n        apply istep_fv_mod in F6. destruct F6 as (_ & F6 & _).\n        apply D6 in FV1. apply F6 in FV2. by apply H2 with x. }\n      { red. intros x FV1 FV2.\n        apply istep_fv_mod in F6. destruct F6 as (_ & F6 & _).\n        apply F6 in FV2. by apply H3 with x. }\n      { red. intros x FV1 FV2.\n        apply istep_fv_mod in D6. destruct D6 as (_ & D6 & _).\n        apply istep_fv_mod in F6. destruct F6 as (F6 & _).\n        apply D6 in FV2. apply F6 in FV1.\n        by apply H4 with x. }\n      { red. intros x FV1 FV2.\n        apply istep_fv_mod in D6. destruct D6 as (_ & D6 & _).\n        apply D6 in FV2. by apply H5 with x. }\n\n      apply safe_agree with s; vauto.\n\n      { intros x FV1. apply istep_fv_mod in F6.\n        destruct F6 as (_ & _ & F6). apply F6.\n        intro FV2. by apply H3 with x. }\n      { intros x FV1. apply istep_fv_mod in F6.\n        destruct F6 as (_ & _ & F6). apply F6.\n        intro FV2. apply istep_fv_mod in D6.\n        destruct D6 as (D6 & _). apply D6 in FV1.\n        by apply H2 with x. }\n\n    (* communication: right program sends, left program receives *)\n    + inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1).\n      simpl in SAFE1. repeat rewrite permheap_add_assoc in H8.\n      apply SAFE1 in H8; clear SAFE1; vauto.\n\n      2:{ apply permheap_disj_assoc_l; vauto. }\n      2:{ by rewrite <- permheap_add_assoc. }\n      2:{ apply psafe_par_rev in SAFE3. desf. }\n\n      destruct H8 as (ph1' & D1 & D2 & D3 & D4 & P1' & D5 & D6 & D7).\n      simpl in D1. clear D1.\n\n      inv SAFE2. clear SAFE2. destruct H as (_ & SAFE2).\n      simpl in SAFE2. repeat rewrite permheap_add_comm with ph1 ph2 in H15.\n      repeat rewrite permheap_add_assoc in H15.\n      apply SAFE2 in H15; clear SAFE2.\n\n      2:{ apply permheap_disj_assoc_l.\n          - by symmetry.\n          - by rewrite permheap_add_comm with ph2 ph1. }\n      2:{ rewrite <- permheap_add_assoc.\n          by rewrite permheap_add_comm with ph2 ph1. }\n      2:{ apply psafe_par_rev in SAFE3. desf. }\n\n      destruct H15 as (ph2' & F1 & F2 & F3 & F4 & P2' & F5 & F6 & F7).\n      simpl in F1. clarify. rename ph2' into ph2. clear F3.\n\n      exists (permheap_add ph1' ph2). intuition.\n\n      { red. vauto. }\n      { apply permheap_disj_assoc_r; auto.\n        by apply permheap_disj_add_l with ph1. }\n      { by repeat rewrite permheap_add_assoc. }\n\n      exists (Ppar P1' P2'). intuition.\n\n      { apply psafe_par; vauto. }\n      { inv D6. clear D6. inv F6. clear F6.\n        rename P'0 into Q2, Q'0 into Q2'.\n        rename P' into Q1, Q' into Q1'.\n        apply istep_comm with (Ppar Q1 Q2) (Ppar Q1' Q2'); vauto.\n        - apply step_comm_r; vauto.\n          + by repeat rewrite permheap_add_assoc.\n          + repeat rewrite permheap_add_comm with ph1 ph2.\n            by repeat rewrite permheap_add_assoc.\n        - apply bisim_par; vauto.\n        - apply bisim_par; vauto. }\n\n      apply CH; vauto.\n\n      { apply permheap_disj_add_r with phF; auto.\n        apply permheap_disj_add_l with ph1; auto. }\n\n      { red. intros x FV1 FV2.\n        apply istep_fv_mod in D6. destruct D6 as (D6 & _).\n        apply istep_fv_mod in F6. destruct F6 as (_ & F6 & _).\n        apply D6 in FV1. apply F6 in FV2. by apply H2 with x. }\n      { red. intros x FV1 FV2.\n        apply istep_fv_mod in F6. destruct F6 as (_ & F6 & _).\n        apply F6 in FV2. by apply H3 with x. }\n      { red. intros x FV1 FV2.\n        apply istep_fv_mod in D6. destruct D6 as (_ & D6 & _).\n        apply istep_fv_mod in F6. destruct F6 as (F6 & _).\n        apply D6 in FV2. apply F6 in FV1.\n        by apply H4 with x. }\n      { red. intros x FV1 FV2.\n        apply istep_fv_mod in D6. destruct D6 as (_ & D6 & _).\n        apply D6 in FV2. by apply H5 with x. }\n\n      apply safe_agree with s; vauto.\n\n      { intros x FV1. apply istep_fv_mod in D6.\n        destruct D6 as (_ & _ & D6). apply D6.\n        intro FV2. by apply H5 with x. }\n      { intros x FV1. apply istep_fv_mod in D6.\n        destruct D6 as (_ & _ & D6). apply D6.\n        intro FV2. apply istep_fv_mod in F6.\n        destruct F6 as (F6 & _). apply F6 in FV1.\n        by apply H4 with x. }\nQed.\n\nTheorem rule_par :\n  forall C1 C2 A1 A2 A1' A2',\n  disjoint (cmd_fv C1) (cmd_mod C2) ->\n  disjoint (assn_fv A1') (cmd_mod C2) ->\n  disjoint (cmd_fv C2) (cmd_mod C1) ->\n  disjoint (assn_fv A2') (cmd_mod C1) ->\n  csl A1 C1 A1' ->\n  csl A2 C2 A2' ->\n  csl (Astar A1 A2) (Cpar C1 C2) (Astar A1' A2').\nProof.\n  intros C1 C2 A1 A2 A1' A2' FV1 FV2 FV3 FV4 CSL1 CSL2.\n  red. intros ph P s H1 H2. simpl in H2.\n  destruct H2 as (ph1 & ph2 & H2 & H3 & P1 & P2 & H4 & H5 & H6).\n  clarify. rewrite <- H4.\n  apply safe_par; vauto.\n  - red in CSL1. apply CSL1 in H5; vauto.\n    by apply permheap_disj_valid_l in H2.\n  - red in CSL2. apply CSL2 in H6; vauto.\n    by apply permheap_disj_valid_r in H2.\nQed.\n\n(** *** Sending *)\n\nTheorem rule_send :\n  forall E T AP,\n  csl (Aproc (APseq (APsend E T) AP)) (Csend E T) (Aproc AP).\nProof.\n  intros E T AP ph P s H1 SAT1.\n  constructor. split.\n  (* termination *)\n  - intros ?. vauto.\n  (* computation *)\n  - simpl. intros phF C' h' s' l H2 FIN1 SAFE1 STEP.\n    inv STEP. rename v0 into v', s' into s.\n    exists ph. intuition. destruct SAT1 as (P'' & H3).\n    set (P' := Ppar (aproc_conv AP s) P'').\n    exists P'. intuition.\n    { rewrite H3 in SAFE1.\n      apply psafe_par_rev in SAFE1. destruct SAFE1 as (SAFE1 & SAFE2).\n      simpl in SAFE1. inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1).\n      subst P'. apply psafe_par; auto.\n      assert (H4: pstep (Pseq (Psend (expr_conv E s) (expr_conv T s)) (aproc_conv AP s)) (PLsend (pexpr_eval (expr_conv E s)) (pexpr_eval (expr_conv T s))) (Pseq Pepsilon (aproc_conv AP s))) by vauto.\n      apply SAFE1 in H4. clear SAFE1. rewrite pseq_epsilon_r in H4. simpls. }\n    { inv STEP. clear H8. rewrite H3. subst P'.\n      apply istep_proc_frame.\n      apply istep_send with\n        (P' := aproc_conv (APseq (APsend E T) AP) s)\n        (Q' := aproc_conv (APseq APepsilon AP) s); auto.\n      - repeat constructor. subst v'.\n        rewrite expr_conv_eval. subst tag0.\n        rewrite expr_conv_eval. constructor.\n      - simpl. by rewrite pseq_epsilon_r. }\n    inv STEP. clear H8. apply safe_skip.\n    subst P'. exists P''. intuition.\nQed.\n\n(** *** Receiving *)\n\nTheorem rule_recv1 :\n  forall x1 x2 y1 y2 AP,\n  ~ aproc_fv AP x1 ->\n  ~ aproc_fv AP x2 ->\n  ~ y1 = y2 ->\n  ~ x1 = y2 ->\n  ~ x2 = y1 ->\n  ~ x1 = x2 ->\n  csl (Aproc (APsigma y1 (APsigma y2 (APseq (APrecv (Evar y1) (Evar y2)) AP)))) (Crecv1 x1 x2) (Aproc (aproc_subst y2 (Evar x2) (aproc_subst y1 (Evar x1) AP))).\nProof.\n  intros x1 x2 y1 y2 AP H1 H2 V1 V2 V3 V4 ph P s H3 SAT1.\n  constructor. split.\n  (* termination *)\n  - intros ?. vauto.\n  (* computation *)\n  - simpl. intros phF C' h' s' l H4 FIN1 SAFE1 STEP.\n    inv STEP. exists ph. intuition. destruct SAT1 as (P'' & H5).\n    assert (H6: pstep\n\t    (aproc_conv (APsigma y1 (APsigma y2 (APseq (APrecv (Evar y1) (Evar y2)) AP))) s)\n\t    (PLrecv v1 v2)\n\t    (aproc_conv (aproc_subst y1 (Econst v1) (aproc_subst y2 (Econst v2) (APseq APepsilon AP))) s)). {\n      simpl. desf. apply pstep_sum with v1, pstep_sum with v2.\n      apply pstep_seq_l. simpl. desf. vauto. }\n    assert (H7:\n      aproc_conv (aproc_subst y2 (Evar x2) (aproc_subst y1 (Evar x1) AP)) (updatestore (updatestore s x1 v1) x2 v2) =\n      aproc_conv (aproc_subst y1 (Econst v1) (aproc_subst y2 (Econst v2) AP)) s). {\n      rewrite aproc_conv_subst_upd, aproc_conv_subst_upd_swap, aproc_conv_subst_upd; vauto.\n      + intro H8. apply aproc_fv_subst_in in H8; vauto.\n      + intro H7. apply V1. by symmetry.\n      + intro H7. apply V2. by symmetry.\n      + intro H8. apply aproc_fv_subst_in in H8; vauto. simpls.\n        apply and_not_or. intuition. }\n    set (P' := Ppar (aproc_conv (aproc_subst y2 (Evar x2) (aproc_subst y1 (Evar x1) AP)) (updatestore (updatestore s x1 v1) x2 v2)) P'').\n    exists P'. intuition.\n    { rewrite H5 in SAFE1. apply psafe_par_rev in SAFE1.\n      destruct SAFE1 as (SAFE1 & SAFE2).\n      inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1).\n      apply SAFE1 in H6. clear SAFE1. simpl in H6.\n      rewrite pseq_epsilon_r in H6. subst P'.\n      apply psafe_par; auto. rewrite H7; vauto. }\n    { rewrite H5. subst P'. apply istep_proc_frame.\n      apply istep_recv with\n        (P' := aproc_conv (APsigma y1 (APsigma y2 (APseq (APrecv (Evar y1) (Evar y2)) AP))) s)\n        (Q' := aproc_conv (APseq APepsilon (aproc_subst y2 (Evar x2) (aproc_subst y1 (Evar x1) AP))) (updatestore (updatestore s x1 v1) x2 v2)); auto.\n      - rewrite aproc_conv_sigma.\n        apply pstep_sum with v1. simpl. desf. clear e.\n        apply pstep_sum with v2. simpl. desf. clear e.\n        rewrite <- H7. vauto.\n      - simpls. intuition. by rewrite pseq_epsilon_r. }\n    apply safe_skip. subst P'. exists P''.\n    apply bisim_par; intuition.\nQed.\n\nTheorem rule_recv2 :\n  forall x y T AP,\n  ~ aproc_fv AP x ->\n  ~ In y (expr_fv T) ->\n  csl (Aproc (APsigma y (APseq (APrecv (Evar y) T) AP))) (Crecv2 x T) (Aproc (aproc_subst y (Evar x) AP)).\nProof.\n  intros x y T AP H1 H2 ph P s H3 SAT1.\n  constructor. split.\n  (* termination *)\n  - intros ?. vauto.\n  (* computation *)\n  - simpl. intros phF C' h' s' l H4 FIN1 SAFE1 STEP.\n    inv STEP. exists ph. intuition. destruct SAT1 as (P'' & H5).\n    set (P' := Ppar (aproc_conv (aproc_subst y (Evar x) AP) (updatestore s x v)) P'').\n    exists P'. intuition.\n    { rewrite H5 in SAFE1.\n      apply psafe_par_rev in SAFE1. destruct SAFE1 as (SAFE1 & SAFE2).\n      inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1).\n      subst P'. repeat apply ppsafe_add; auto.\n      rewrite aproc_conv_subst_upd; auto.\n      assert (H6: pstep (aproc_conv (APsigma y (APseq (APrecv (Evar y) T) AP)) s) (PLrecv v tag) (aproc_conv (aproc_subst y (Econst v) (APseq APepsilon AP)) s)). {\n        simpl. desf. apply pstep_sum with v.\n        constructor. subst tag. rewrite expr_subst_pres.\n        + rewrite expr_conv_eval. vauto.\n        + intro H6. by apply H2. }\n      apply SAFE1 in H6. clear SAFE1. simpl in H6.\n      rewrite pseq_epsilon_r in H6. simpls.\n      apply psafe_par; auto. }\n    { rewrite H5. subst P'. apply istep_proc_frame.\n      apply istep_recv with\n        (P' := aproc_conv (APsigma y (APseq (APrecv (Evar y) T) AP)) s)\n        (Q' := aproc_conv (APseq APepsilon (aproc_subst y (Evar x) AP)) (updatestore s x v)); auto.\n      - rewrite aproc_conv_sigma.\n        apply pstep_sum with v. simpl. desf. clear e.\n        simpl. rewrite aproc_conv_subst_upd; auto.\n        apply pstep_seq_l. rewrite expr_subst_pres.\n        + subst tag. rewrite expr_conv_eval. vauto.\n        + intro H6. by apply H2.\n      - simpls. intuition. by rewrite pseq_epsilon_r. }\n      apply safe_skip. subst P'. exists P''. intuition.\nQed.\n\n(** *** Querying *)\n\nTheorem rule_query :\n  forall B AP,\n  csl (Aproc (APseq (APassn B) AP)) (Cquery B) (Astar (Aproc AP) (Aplain B)).\nProof.\n  intros B AP ph P s H1 SAT1.\n  constructor. split.\n  (* termination *)\n  - intros H. inv H.\n  (* computation *)\n  - simpl. intros phF C' h' s' l H2 FIN1 SAFE1 STEP.\n    inv STEP. rename s' into s. exists ph.\n    intuition. destruct SAT1 as (P'' & H3).\n    assert (H5: cond_eval B s). {\n      rewrite cond_conv_eval. rewrite H3 in SAFE1.\n      apply psafe_par_rev in SAFE1. destruct SAFE1 as (SAFE1 & _).\n      simpl in SAFE1.\n      apply psafe_seq_left in SAFE1. inv SAFE1. clear SAFE1.\n      destruct H as (SAFE1 & _). by apply passn_nfault. }\n    set (P' := Ppar (aproc_conv AP s) P'').\n    exists P'. intuition.\n    { rewrite H3 in SAFE1.\n      apply psafe_par_rev in SAFE1. destruct SAFE1 as (SAFE1 & SAFE2).\n      simpl in SAFE1. inv SAFE1. clear SAFE1. destruct H as (_ & SAFE1).\n      subst P'. repeat apply ppsafe_add; auto.\n      assert (H6: pstep (Pseq (Passn (cond_conv B s)) (aproc_conv AP s)) (PLassn (pcond_eval (cond_conv B s))) (Pseq Pepsilon (aproc_conv AP s))). {\n        repeat constructor. by rewrite <- cond_conv_eval. }\n      apply SAFE1 in H6. clear SAFE1. rewrite pseq_epsilon_r in H6.\n      apply psafe_par; auto. }\n    { subst P'. rewrite H3. apply istep_proc_frame.\n      apply istep_query with\n        (P' := aproc_conv (APseq (APassn B) AP) s)\n        (Q' := aproc_conv (APseq APepsilon AP) s); auto.\n      - apply pstep_seq_l. rewrite cond_conv_eval at 1. constructor.\n        by rewrite <- cond_conv_eval.\n      - simpl. intuition. by rewrite pseq_epsilon_r. }\n    apply safe_skip. subst P'.\n    exists ph, permheap_iden. intuition.\n    { by rewrite permheap_add_iden_l. }\n    exists (aproc_conv AP s), P''. intuition. simpl.\n    exists Pepsilon. by rewrite par_epsilon_r.\nQed.\n\nEnd Soundness.\n", "meta": {"author": "utwente-fmt", "repo": "iFM19-MessagePassingAbstr", "sha": "4134d106e3a2110bca1ca35f4462914db0efb58f", "save_path": "github-repos/coq/utwente-fmt-iFM19-MessagePassingAbstr", "path": "github-repos/coq/utwente-fmt-iFM19-MessagePassingAbstr/iFM19-MessagePassingAbstr-4134d106e3a2110bca1ca35f4462914db0efb58f/coq/Soundness.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.20265550555406647}}
{"text": "Require Import Platform.AutoSep Platform.Malloc Platform.Bootstrap Platform.Cito.examples.FactorialRecur.\n\n\nModule Type S.\n  Variable heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"top\"!\"top\" @ [topS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Call \"top\"!\"top\"()\n        [PREonly[_] [| False |] ]\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Definition m0 := link Malloc.m boot.\n  Definition m1 := link all m0.\n\n  Lemma ok0 : moduleOk m0.\n    link Malloc.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link all_ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n\n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, ($ (size * 4) <= w)%word -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "JasonGross", "repo": "bedrock2-old", "sha": "215299d1a048410ebdab642208fe7d51d9ee1555", "save_path": "github-repos/coq/JasonGross-bedrock2-old", "path": "github-repos/coq/JasonGross-bedrock2-old/bedrock2-old-215299d1a048410ebdab642208fe7d51d9ee1555/platform/Cito/examples/FactorialRecurDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20250740690874458}}
{"text": "(* \n * SPDX-License-Identifier: MIT\n * \n *)\nFrom Coq Require Import\n     String\n     Sumbool\n     Morphisms.\n\nFrom SPICY Require Import\n     MyPrelude\n     Maps\n     Keys\n     Messages.\n\nSet Implicit Arguments.\n\nModule RW_message <: GRANT_ACCESS.\n  Definition access := key_permission.\nEnd RW_message.\n\nModule message := Messages(RW_message).\nImport message.\nExport message.\n\nDefinition cipher_id := nat.\n\nInductive crypto : type -> Type :=\n| Content {t} (c : message t) : crypto t\n| SignedCiphertext {t} (c_id : cipher_id) : crypto t\n.\n\n(* We need to handle non-deterministic message  -- external choice on ordering *)\nInductive msg_pat :=\n| Accept\n| Signed (k : key_identifier) (chk_replay : bool)\n| SignedEncrypted (k__sign k__enc : key_identifier) (chk_replay : bool)\n.\n\nDefinition msg_seq : Set := (option user_id) * nat.\n\nDefinition msg_seq_eq (s1 s2 : msg_seq) : {s1 = s2} + {s1 <> s2}.\n  repeat (decide equality).\nDefined.\n\nInductive cipher : Type :=\n| SigCipher {t} (k__sign : key_identifier) (msg_to : user_id) (c_nonce : msg_seq) (msg : message t) : cipher\n| SigEncCipher {t} (k__sign k__enc : key_identifier) (msg_to : user_id) (c_nonce : msg_seq) (msg : message t) : cipher\n.\n\nDefinition cipher_signing_key (c : cipher) :=\n  match c with\n  | SigCipher k _ _ _      => k\n  | SigEncCipher k _ _ _ _ => k\n  end.\n\nDefinition cipher_to_user (c : cipher) :=\n  match c with\n  | SigCipher _ to _ _      => to\n  | SigEncCipher _ _ to _ _ => to\n  end.\n\nDefinition cipher_nonce (c : cipher) :=\n  match c with\n  | SigCipher _ _ n _      => n\n  | SigEncCipher _ _ _ n _ => n\n  end.\n\nDefinition queued_messages := list (sigT crypto).\nDefinition ciphers         := NatMap.t cipher.\nDefinition my_ciphers      := list cipher_id.\nDefinition recv_nonces     := list msg_seq.\nDefinition sent_nonces     := list msg_seq.\n\nInductive msg_accepted_by_pattern (cs : ciphers) (opt_uid_to : option user_id) (froms : recv_nonces)\n  : forall {t : type}, msg_pat -> crypto t -> Prop :=\n| MsgAccept : forall {t} (m : crypto t),\n    msg_accepted_by_pattern cs opt_uid_to froms Accept m\n| ProperlySigned : forall {t t'} c_id k (m : message t) msg_to nonce (chk : bool),\n    cs $? c_id = Some (SigCipher k msg_to nonce m)\n    -> (if chk then (count_occ msg_seq_eq froms nonce = 0) else True)\n    -> opt_uid_to = Some msg_to\n    -> msg_accepted_by_pattern cs opt_uid_to froms (Signed k chk) (@SignedCiphertext t' c_id)\n| ProperlyEncrypted : forall {t t'} c_id k__sign k__enc (m : message t) msg_to nonce (chk : bool),\n    cs $? c_id = Some (SigEncCipher k__sign k__enc msg_to nonce m)\n    -> (if chk then (count_occ msg_seq_eq froms nonce = 0) else True)\n    -> opt_uid_to = Some msg_to\n    -> msg_accepted_by_pattern cs opt_uid_to froms (SignedEncrypted k__sign k__enc chk) (@SignedCiphertext t' c_id).\n\n#[export] Hint Extern 1 (~ In _ _) => rewrite not_find_in_iff : core.\n\nNotation honest_key honk kid := (honk $? kid = Some true).\n\nSection SafeMessages.\n  Variable all_keys : keys.\n  Variable honestk advk : key_perms.\n\n  Definition honest_keyb (k_id : key_identifier) : bool :=\n    match honestk $? k_id with\n    | Some true => true\n    | _ => false\n    end.\n\n  Definition msg_cipher_id {t} (msg : crypto t) : option cipher_id :=\n    match msg with\n    | SignedCiphertext c_id => Some c_id\n    | _ => None\n    end.\n\n  Definition msg_signing_key {t} (cs : ciphers) (msg : crypto t) : option key_identifier :=\n    match msg with\n    | Content _ => None\n    | SignedCiphertext c_id =>\n      match cs $? c_id with\n      | Some c => Some (cipher_signing_key c)\n      | None   => None\n      end\n    end.\n\n  Definition msg_destination_user {t} (cs : ciphers) (msg : crypto t) : option user_id :=\n    match msg with\n    | Content _ => None\n    | SignedCiphertext c_id =>\n      match cs $? c_id with\n      | Some c => Some (cipher_to_user c)\n      | None   => None\n      end\n    end.\n\n  Definition msg_honestly_signed {t} (cs : ciphers) (msg : crypto t) : bool :=\n    match msg_signing_key cs msg with\n    | Some k => honest_keyb k\n    | _ => false\n    end.\n\n  Definition msg_to_this_user {t} (cs : ciphers) (to_usr : option user_id) (msg : crypto t) : bool :=\n    match msg_destination_user cs msg with\n    | Some to_usr' => match to_usr with\n                     | None => true\n                     | Some to_hon_user => if to_usr' ==n to_hon_user then true else false\n                     end\n    | _ => false\n    end.\n\n  Definition msg_signed_addressed (cs : ciphers) (to_user_id : option user_id) {t} (msg : crypto t) :=\n    msg_honestly_signed cs msg && msg_to_this_user cs to_user_id msg.\n\n  Definition keys_mine (my_perms key_perms: key_perms) : Prop :=\n    forall k_id kp,\n      key_perms $? k_id = Some kp\n    ->  my_perms $? k_id = Some kp\n    \\/ (my_perms $? k_id = Some true /\\ kp = false).\n\n  Definition cipher_honestly_signed (c : cipher) : bool :=\n    match c with\n    | SigCipher k_id _ _ _              => honest_keyb k_id\n    | SigEncCipher k__signid k__encid _ _ _ => honest_keyb k__signid\n    end.\n\n  Definition ciphers_honestly_signed :=\n    Forall_natmap (fun c => cipher_honestly_signed c = true).\n\n  Inductive msg_pattern_safe : msg_pat -> Prop :=\n  | HonestlySignedSafe : forall k,\n        honest_key honestk k\n      -> msg_pattern_safe (Signed k true)\n  | HonestlySignedEncryptedSafe : forall k__sign k__enc,\n        honest_key honestk k__sign\n      -> msg_pattern_safe (SignedEncrypted k__sign k__enc true)\n  .\n\nEnd SafeMessages.\n\nInductive user_cmd_type :=\n| Base (t : type)\n| Message (t : type)\n| Crypto (t : type)\n| UPair (t1 t2 : user_cmd_type)\n.\n\nFixpoint denote (t : user_cmd_type) :=\n  match t with\n  | Base t' => message.typeDenote t'\n  | Message t' => message t'\n  | Crypto t' => crypto t'\n  | UPair t1 t2 => (denote t1 * denote t2)%type\n  end\n.\n\nDeclare Scope realworld_scope.\nNotation \"<< t >>\" := (denote t) (at level 75) : realworld_scope.\nDelimit Scope realworld_scope with realworld.\nOpen Scope realworld_scope.\n\nInductive user_cmd : user_cmd_type -> Type :=\n(* Plumbing *)\n| Return {A} (res : <<A>>%realworld) : user_cmd A\n| Bind {A A'} (cmd1 : user_cmd A') (cmd2 : <<A'>>%realworld -> user_cmd A) : user_cmd A\n\n| Gen : user_cmd (Base Nat)\n\n(* Messaging *)\n| Send {t} (uid : user_id) (msg : crypto t) : user_cmd (Base Unit)\n| Recv {t} (pat : msg_pat) : user_cmd (Crypto t)\n\n(* Crypto!! *)\n| SignEncrypt {t} (k__sign k__enc : key_identifier) (msg_to : user_id) (msg : message t) : user_cmd (Crypto t)\n| Decrypt {t} (c : crypto t) : user_cmd (Message t)\n\n| Sign    {t} (k : key_identifier) (msg_to : user_id) (msg : message t) : user_cmd (Crypto t)\n| Verify  {t} (k : key_identifier) (c : crypto t) : user_cmd (UPair (Base Bool) (Message t))\n\n| GenerateKey (kt : key_type) (usage : key_usage) : user_cmd (Base Access)\n.\n\nModule RealWorldNotations.\n  Ltac denoteInvert T :=\n    match T with\n      | key_permission => exact (Base Access)\n      | bool => exact (Base Bool)\n      | nat => exact (Base Nat)\n      | unit => exact (Base Unit)\n      | (?T1 * ?T2)%type =>\n        exact (UPair ltac:(denoteInvert T1) ltac:(denoteInvert T2))\n      end\n  .\n  Ltac typeOf x :=\n    match type of x with\n    | ?T => denoteInvert T\n    end\n  .\n  Notation \"x <- c1 ; c2\" := (Bind c1 (fun x => c2)) (right associativity, at level 75) : realworld_scope.\n  Notation \"'ret' x\" := (@Return ltac:(typeOf x) x) (at level 75, only parsing) : realworld_scope.\nEnd RealWorldNotations.\nImport  RealWorldNotations.\n\nRecord user_data (A : type) :=\n  mkUserData {\n      key_heap  : key_perms\n    ; protocol  : user_cmd (Base A)\n    ; msg_heap  : queued_messages\n    ; c_heap    : my_ciphers\n    ; from_nons : recv_nonces\n    ; sent_nons : sent_nonces\n    ; cur_nonce : nat\n    }.\n\nDefinition honest_users A := NatMap.t (user_data A).\n\nRecord simpl_universe A :=\n  mkSimplUniverse {\n      s_users       : honest_users A\n    ; s_all_ciphers : ciphers\n    ; s_all_keys    : keys\n    }.\n\nRecord universe A B :=\n  mkUniverse {\n      users       : honest_users A\n    ; adversary   : user_data B\n    ; all_ciphers : ciphers\n    ; all_keys    : keys\n    }.\n\nDefinition peel_adv {A B} (U : universe A B) : simpl_universe A :=\n   {| s_users       := U.(users)\n    ; s_all_ciphers := U.(all_ciphers)\n    ; s_all_keys    := U.(all_keys) |}.\n\nDefinition findUserKeys {A} (us : NatMap.t (user_data A)) : key_perms :=\n  fold (fun u_id u ks => ks $k++ u.(key_heap)) us $0.\n\nDefinition addUserKeys {A} (ks : key_perms) (u : user_data A) : user_data A :=\n  {| key_heap  := u.(key_heap) $k++ ks\n   ; protocol  := u.(protocol)\n   ; msg_heap  := u.(msg_heap)\n   ; c_heap    := u.(c_heap)\n   ; from_nons := u.(from_nons)\n   ; sent_nons := u.(sent_nons)\n   ; cur_nonce := u.(cur_nonce)\n  |}.\n\nDefinition addUsersKeys {A} (us : NatMap.t (user_data A)) (ks : key_perms) :=\n  map (addUserKeys ks) us.\n\nFixpoint findKeysMessage {t} (msg : message t) : key_perms :=\n  match msg with\n  | message.Permission k => $0 $+ (fst k, snd k) \n  | message.Content _ => $0\n  | message.MsgPair m1 m2 => findKeysMessage m1 $k++ findKeysMessage m2\n  end.\n\nDefinition findKeysCrypto {t} (cs : ciphers) (msg : crypto t) : key_perms :=\n  match msg with\n  | Content  m          => findKeysMessage m\n  | SignedCiphertext c_id  =>\n    match cs $? c_id with\n    | Some (SigCipher _ _ _ m) => findKeysMessage m\n    | _ => $0\n    end\n  end.\n\nDefinition findCiphers {t} (msg : crypto t) : my_ciphers :=\n  match msg with\n  | Content _          => []\n  | SignedCiphertext c => [c]\n  end.\n\nDefinition findMsgCiphers {t} (msg : crypto t) : queued_messages :=\n  match msg with\n  | Content _          => []\n  | SignedCiphertext _ => [existT _ _ msg]\n  end.\n\nDefinition user_keys {A} (usrs : honest_users A) (u_id : user_id) : option key_perms :=\n  match usrs $? u_id with\n  | Some u_d => Some u_d.(key_heap)\n  | None     => None\n  end.\n\nDefinition user_queue {A} (usrs : honest_users A) (u_id : user_id) : option queued_messages :=\n  match usrs $? u_id with\n  | Some u_d => Some u_d.(msg_heap)\n  | None     => None\n  end.\n\nDefinition user_cipher_queue {A} (usrs : honest_users A) (u_id : user_id) : option my_ciphers :=\n  match usrs $? u_id with\n  | Some u_d => Some u_d.(c_heap)\n  | None     => None\n  end.\n\nDefinition buildUniverse {A B}\n           (usrs : honest_users A) (adv : user_data B) (cs : ciphers) (ks : keys)\n           (u_id : user_id) (userData : user_data A) : universe A B :=\n  {| users        := usrs $+ (u_id, userData)\n   ; adversary    := adv\n   ; all_ciphers  := cs\n   ; all_keys     := ks\n   |}.\n\nDefinition buildUniverseAdv {A B}\n           (usrs : honest_users A) (cs : ciphers) (ks : keys)\n           (userData : user_data B) : universe A B :=\n  {| users        := usrs\n   ; adversary    := userData\n   ; all_ciphers  := cs\n   ; all_keys     := ks\n   |}.\n\nDefinition updateTrackedNonce {t} (to_usr : option user_id) (froms : recv_nonces) (cs : ciphers) (msg : crypto t) :=\n  match msg with\n  | Content _ => froms\n  | SignedCiphertext c_id =>\n    match cs $? c_id with\n    | None => froms\n    | Some c =>\n      match to_usr with\n      | None => froms\n      | Some to_uid =>\n        if to_uid ==n cipher_to_user c\n        then match count_occ msg_seq_eq froms (cipher_nonce c) with\n             | 0 => cipher_nonce c :: froms\n             | _ => froms\n             end\n        else froms\n      end                \n    end\n  end.\n\nDefinition updateSentNonce {t} (to_usr : option user_id) (sents : sent_nonces) (cs : ciphers) (msg : crypto t) :=\n  match msg with\n  | Content _ => sents\n  | SignedCiphertext c_id =>\n    match cs $? c_id with\n    | None => sents\n    | Some c =>\n      match to_usr with\n      | None => sents\n      | Some to_uid =>\n        if to_uid ==n cipher_to_user c\n        then cipher_nonce c :: sents\n        else sents\n      end                \n    end\n  end.\n\n\nDefinition msg_nonce_not_same (new_cipher : cipher) (cs : ciphers) {t} (msg : crypto t) : Prop :=\n  forall c_id c,\n    msg = SignedCiphertext c_id\n    -> cs $? c_id = Some c\n    -> cipher_nonce new_cipher <> cipher_nonce c.\n\nDefinition msg_nonce_same (new_cipher : cipher) (cs : ciphers) {t} (msg : crypto t) : Prop :=\n  forall c_id c,\n      msg = SignedCiphertext c_id\n    -> cs $? c_id = Some c\n    -> cipher_nonce new_cipher = cipher_nonce c.\n\nDefinition msg_not_replayed {t} (to_usr : option user_id) (cs : ciphers) (froms : recv_nonces) (msg : crypto t) (msgs : queued_messages) : Prop :=\n  exists c_id c,\n      msg = SignedCiphertext c_id\n    /\\ cs $? c_id = Some c\n    /\\ ~ List.In (cipher_nonce c) froms\n    /\\ Forall (fun sigM => match sigM with\n                       | (existT _ _ m) => msg_to_this_user cs to_usr m = true\n                                        -> msg_nonce_not_same c cs m\n                       end) msgs.\n\nInductive action : Type :=\n| Input  t (msg : crypto t) (pat : msg_pat) (froms : recv_nonces)\n| Output t (msg : crypto t) (from_user : option user_id) (to_user : option user_id) (sents : sent_nonces)\n.\n\nDefinition rlabel := @label action.\nDefinition uaction := (user_id * action)%type.\nDefinition ulabel := @label uaction.\nDefinition mkULbl (lbl : rlabel) (uid : user_id) : ulabel :=\n  match lbl with\n  | Silent => Silent\n  | Action a => Action (uid, a)\n  end.\n\nDefinition data_step0 A B C : Type :=\n  honest_users A * user_data B * ciphers * keys * key_perms * queued_messages * my_ciphers * recv_nonces * sent_nonces * nat * user_cmd C.\n\nDefinition build_data_step {A B C} (U : universe A B) (u_data : user_data C) : data_step0 A B (Base C) :=\n  (U.(users), U.(adversary), U.(all_ciphers), U.(all_keys),\n   u_data.(key_heap), u_data.(msg_heap), u_data.(c_heap), u_data.(from_nons), u_data.(sent_nons), u_data.(cur_nonce), u_data.(protocol)).\n\nInductive step_user : forall A B C, rlabel -> option user_id -> data_step0 A B C -> data_step0 A B C -> Prop :=\n\n(* Plumbing *)\n| StepBindRecur : forall {A B r r'} (usrs usrs' : honest_users A) (adv adv' : user_data B)\n                    lbl u_id cs cs' qmsgs qmsgs' gks gks' ks ks' mycs mycs' froms froms' sents sents' cur_n cur_n'\n                    (cmd1 cmd1' : user_cmd r) (cmd2 : <<r>> -> user_cmd r'),\n    step_user lbl u_id (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd1)\n                       (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', cmd1')\n    -> step_user lbl u_id (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, Bind cmd1 cmd2)\n                         (usrs', adv', cs', gks', ks', qmsgs', mycs', froms', sents', cur_n', Bind cmd1' cmd2)\n| StepBindProceed : forall {A B r r'} (usrs : honest_users A) (adv : user_data B) cs u_id gks ks qmsgs mycs froms sents cur_n\n                      (v : <<r'>>) (cmd : <<r'>> -> user_cmd r),\n    step_user Silent u_id\n              (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, Bind (@Return r' v) cmd)\n              (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd v)\n\n| StepGen : forall {A B} (usrs : honest_users A) (adv : user_data B) cs u_id gks ks qmsgs mycs froms sents cur_n n,\n    step_user Silent u_id (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, Gen)\n              (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, Return n)\n\n(* Comms  *)\n| StepRecv : forall {A B} {t} (usrs : honest_users A) (adv : user_data B) cs u_id gks ks ks' qmsgs qmsgs' mycs mycs' froms froms'\n               sents cur_n (msg : crypto t) msgs__front msgs__back pat newkeys newcs,\n      qmsgs = msgs__front ++ (existT _ _ msg) :: msgs__back (* we have a message waiting for us! *)\n    -> qmsgs' = msgs__front ++ msgs__back\n    -> findKeysCrypto cs msg = newkeys\n    -> newcs = findCiphers msg\n    -> ks' = ks $k++ newkeys\n    -> mycs' = newcs ++ mycs\n    -> froms' = updateTrackedNonce u_id froms cs msg\n    -> msg_accepted_by_pattern cs u_id froms pat msg\n    -> Forall (fun '(existT _ _ msg')  => ~ msg_accepted_by_pattern cs u_id froms pat msg') msgs__front\n    -> step_user (Action (Input msg pat froms)) u_id\n                (usrs, adv, cs, gks, ks , qmsgs , mycs, froms, sents, cur_n,  Recv pat)\n                (usrs, adv, cs, gks, ks', qmsgs', mycs', froms', sents, cur_n, @Return (Crypto t) msg)\n\n\n(* Augment attacker's keys with those available through messages sent, *)\n(*  * including traversing through ciphers already known by attacker, etc. *)\n(*  *)\n| StepSend : forall {A B} {t} (usrs usrs' : honest_users A) (adv adv' : user_data B)\n               cs suid gks ks qmsgs mycs froms sents sents' cur_n rec_u_id rec_u newkeys (msg : crypto t),\n    findKeysCrypto cs msg = newkeys\n    -> keys_mine ks newkeys\n    -> incl (findCiphers msg) mycs\n    -> usrs $? rec_u_id = Some rec_u\n    -> Some rec_u_id <> suid\n    -> sents' = updateSentNonce (Some rec_u_id) sents cs msg\n    -> usrs' = usrs $+ (rec_u_id, {| key_heap  := rec_u.(key_heap)\n                                  ; protocol  := rec_u.(protocol)\n                                  ; msg_heap  := rec_u.(msg_heap) ++ [existT _ _ msg]\n                                  ; c_heap    := rec_u.(c_heap)\n                                  ; from_nons := rec_u.(from_nons)\n                                  ; sent_nons := rec_u.(sent_nons)\n                                  ; cur_nonce := rec_u.(cur_nonce) |})\n    -> adv' = \n      {| key_heap  := adv.(key_heap) $k++ newkeys\n       ; protocol  := adv.(protocol)\n       ; msg_heap  := adv.(msg_heap) ++ [existT _ _ msg]\n       ; c_heap    := adv.(c_heap)\n       ; from_nons := adv.(from_nons)\n       ; sent_nons := adv.(sent_nons)\n       ; cur_nonce := adv.(cur_nonce) |}\n    -> step_user (Action (Output msg suid (Some rec_u_id) sents)) suid\n                (usrs , adv , cs, gks, ks, qmsgs, mycs, froms, sents,  cur_n, Send rec_u_id msg)\n                (usrs', adv', cs, gks, ks, qmsgs, mycs, froms, sents', cur_n, @Return (Base Unit) tt)\n\n(* Encryption / Decryption *)\n| StepEncrypt : forall {A B} {t} (usrs : honest_users A) (adv : user_data B) cs cs' u_id gks ks qmsgs mycs mycs' froms sents\n                  cur_n cur_n' (msg : message t) k__signid k__encid kp__enc kt__enc kt__sign c_id cipherMsg msg_to msg_nonce,\n      gks $? k__encid  = Some (MkCryptoKey k__encid Encryption kt__enc)\n    -> gks $? k__signid = Some (MkCryptoKey k__signid Signing kt__sign)\n    -> ks $? k__encid   = Some kp__enc\n    -> ks $? k__signid  = Some true\n    -> ~ In c_id cs\n    -> keys_mine ks (findKeysMessage msg)\n    -> cur_n' = 1 + cur_n\n    -> (u_id <> None -> msg_nonce = (u_id, cur_n))\n    -> cipherMsg = SigEncCipher k__signid k__encid msg_to msg_nonce msg\n    -> cs' = cs $+ (c_id, cipherMsg)\n    -> mycs' = c_id :: mycs\n    -> step_user Silent u_id\n                (usrs, adv, cs , gks, ks, qmsgs, mycs,  froms, sents, cur_n,  SignEncrypt k__signid k__encid msg_to msg)\n                (usrs, adv, cs', gks, ks, qmsgs, mycs', froms, sents, cur_n', @Return (Crypto t) (SignedCiphertext c_id))\n\n| StepDecrypt : forall {A B} {t} (usrs : honest_users A) (adv : user_data B) cs u_id gks ks ks' qmsgs mycs mycs'\n                  (msg : message t) k__signid kp__sign k__encid c_id nonce newkeys kt__sign kt__enc msg_to froms sents cur_n,\n      cs $? c_id     = Some (SigEncCipher k__signid k__encid msg_to nonce msg)\n    -> gks $? k__encid  = Some (MkCryptoKey k__encid Encryption kt__enc)\n    -> gks $? k__signid = Some (MkCryptoKey k__signid Signing kt__sign)\n    -> ks  $? k__encid  = Some true\n    -> ks  $? k__signid = Some kp__sign\n    -> findKeysMessage msg = newkeys\n    -> ks' = ks $k++ newkeys\n    -> mycs' = (* newcs ++  *)mycs\n    -> List.In c_id mycs\n    -> step_user Silent u_id\n                (usrs, adv, cs, gks, ks , qmsgs, mycs,  froms, sents, cur_n, Decrypt (SignedCiphertext c_id))\n                (usrs, adv, cs, gks, ks', qmsgs, mycs', froms, sents, cur_n, @Return (Message t) msg)\n\n(* Signing / Verification *)\n| StepSign : forall {A B} {t} (usrs : honest_users A) (adv : user_data B) cs cs' u_id gks ks qmsgs mycs mycs'\n               froms sents cur_n cur_n' msg_nonce (msg : message t) k_id kt c_id cipherMsg msg_to,\n      gks $? k_id = Some (MkCryptoKey k_id Signing kt)\n    -> ks  $? k_id = Some true\n    -> ~ In c_id cs\n    -> keys_mine ks (findKeysMessage msg)\n    -> cur_n' = 1 + cur_n\n    -> (u_id <> None -> msg_nonce = (u_id, cur_n))\n    -> cipherMsg = SigCipher k_id msg_to msg_nonce msg\n    -> cs' = cs $+ (c_id, cipherMsg)\n    -> mycs' = c_id :: mycs\n    -> step_user Silent u_id\n                (usrs, adv, cs , gks, ks, qmsgs, mycs,  froms, sents, cur_n,  Sign k_id msg_to msg)\n                (usrs, adv, cs', gks, ks, qmsgs, mycs', froms, sents, cur_n', @Return (Crypto t) (SignedCiphertext c_id))\n\n| StepVerify : forall {A B} {t} (usrs : honest_users A) (adv : user_data B) cs u_id gks ks qmsgs mycs froms sents cur_n\n                 (msg : message t) k_id kp kt c_id nonce msg_to,\n      gks $? k_id = Some (MkCryptoKey k_id Signing kt)\n    -> ks  $? k_id = Some kp\n    -> cs $? c_id = Some (SigCipher k_id msg_to nonce msg)\n    -> List.In c_id mycs\n    -> step_user Silent u_id\n                (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, Verify k_id (SignedCiphertext c_id))\n                (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, @Return (UPair (Base Bool) (Message t))(true, msg))\n\n| StepGenerateKey: forall {A B} (usrs : honest_users A) (adv : user_data B)\n                     cs u_id gks gks' ks ks' qmsgs mycs froms sents cur_n\n                     (k_id : key_identifier) k kt usage,\n    gks $? k_id = None\n    -> k = MkCryptoKey k_id usage kt\n    -> gks' = gks $+ (k_id, k)\n    -> ks' = add_key_perm k_id true ks\n    -> step_user Silent u_id\n                (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, GenerateKey kt usage)\n                (usrs, adv, cs, gks', ks', qmsgs, mycs, froms, sents, cur_n, @Return (Base Access) (k_id, true))\n\n.\n\nInductive step_universe {A B} : option user_id -> universe A B -> ulabel -> universe A B -> Prop :=\n| StepUser : forall U U' (u_id : user_id) userData usrs adv cs gks ks qmsgs mycs froms sents cur_n lbl lbl' (cmd : user_cmd (Base A)),\n    U.(users) $? u_id = Some userData\n    -> step_user lbl (Some u_id)\n                (build_data_step U userData)\n                (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n    -> U' = buildUniverse usrs adv cs gks u_id {| key_heap  := ks\n                                               ; msg_heap  := qmsgs\n                                               ; protocol  := cmd\n                                               ; c_heap    := mycs\n                                               ; from_nons := froms\n                                               ; sent_nons := sents\n                                               ; cur_nonce := cur_n |}\n    -> lbl' = mkULbl lbl u_id\n    -> step_universe (Some u_id) U lbl' U'\n| StepAdversary : forall U U' usrs adv cs gks ks qmsgs mycs froms sents cur_n lbl (cmd : user_cmd (Base B)),\n    step_user lbl None\n              (build_data_step U U.(adversary))\n              (usrs, adv, cs, gks, ks, qmsgs, mycs, froms, sents, cur_n, cmd)\n    -> U' = buildUniverseAdv usrs cs gks {| key_heap  := ks\n                                         ; msg_heap  := qmsgs\n                                         ; protocol  := cmd\n                                         ; c_heap    := mycs\n                                         ; from_nons := froms\n                                         ; sent_nons := sents\n                                         ; cur_nonce := cur_n |}\n    -> step_universe None U Silent U'\n.\n", "meta": {"author": "spicy-paper", "repo": "spicy", "sha": "14b766c24bb546861e623b6681b2e71653234681", "save_path": "github-repos/coq/spicy-paper-spicy", "path": "github-repos/coq/spicy-paper-spicy/spicy-14b766c24bb546861e623b6681b2e71653234681/src/RealWorld.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20250740690874458}}
{"text": "From iris.algebra Require Import gmap agree auth.\nFrom iris.proofmode Require Import tactics.\nFrom cap_machine Require Export region_invariants region_invariants_uninitialized.\nImport uPred.\n\nSection region_alloc.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n          {stsg : STSG Addr region_type Σ} {heapg : heapG Σ}\n          `{MonRef: MonRefG (leibnizO _) CapR_rtc Σ}\n          `{MachineParameters}.\n\n  Notation STS := (leibnizO (STS_states * STS_rels)).\n  Notation STS_STD := (leibnizO (STS_std_states Addr region_type)).\n  Notation WORLD := (prodO STS_STD STS).\n  Implicit Types W : WORLD.\n\n  (* Lemmas for extending the region map *)\n\n  Lemma static_extend_preserve W (M : relT) (Mρ : gmap Addr region_type) (l : Addr) g ρ :\n    l ∉ dom (gset Addr) (std W) ->\n    dom (gset Addr) (std W) = dom (gset Addr) M ->\n    dom (gset Addr) Mρ = dom (gset Addr) M ->\n    (∀ a' : Addr, a' ∈ dom (gset Addr) g → Mρ !! a' = Some (Static g)) ->\n    ∀ a' : Addr, a' ∈ dom (gset Addr) g → <[l:=ρ]> Mρ !! a' = Some (Static g).\n  Proof.\n    intros Hl Hdom1 Hdom2 Hall.\n    intros a' Hin. pose proof (Hall _ Hin) as Hcontr.\n    assert (a' ∈ dom (gset Addr) Mρ) as Hincontr;[apply elem_of_gmap_dom;eauto|].\n    rewrite Hdom2 in Hincontr. apply elem_of_gmap_dom in Hincontr. clear Hcontr.\n    assert (is_Some (std W !! a')) as Hcontr.\n    { apply elem_of_gmap_dom. rewrite Hdom1. apply elem_of_gmap_dom. eauto. }\n    apply elem_of_gmap_dom in Hcontr.\n    assert (a' ≠ l) as Hne';[intros Heq;subst;contradiction|].\n    rewrite lookup_insert_ne;auto.\n  Qed.\n\n  Lemma extend_region_temp_pwl E W l p v φ `{∀ Wv, Persistent (φ Wv)}:\n     p ≠ O →\n     l ∉ dom (gset Addr) (std W) →\n     (pwl p) = true →\n     (future_pub_mono φ v →\n     sts_full_world W -∗ region W -∗ l ↦ₐ[p] v -∗ φ (W,v) ={E}=∗ region (<s[l := Temporary ]s>W)\n                                                              ∗ rel l p φ\n                                                              ∗ sts_full_world (<s[l := Temporary ]s>W))%I.\n  Proof.\n    iIntros (Hpne Hnone1 Hpwl) \"#Hmono Hfull Hreg Hl #Hφ\".\n    rewrite region_eq rel_eq /region_def /rel_def.\n    iDestruct \"Hreg\" as (M Mρ) \"(Hγrel & HMW & HMρ & Hpreds)\".\n    iDestruct \"HMW\" as %HMW. iDestruct \"HMρ\" as %HMρ.\n    rewrite RELS_eq /RELS_def.\n    (* destruct on M !! l *)\n    destruct (M !! l) eqn:HRl.\n    { (* The location is not in the map *)\n      iDestruct (big_sepM_delete _ _ _ _ HRl with \"Hpreds\") as \"[Hl' _]\".\n      iDestruct \"Hl'\" as (ρ' Hl) \"[Hstate Hl']\".\n      iDestruct (sts_full_state_std with \"Hfull Hstate\") as %Hcontr.\n      apply (not_elem_of_dom W.1 l) in Hnone1.\n      rewrite Hcontr in Hnone1. done.\n    }\n    (* if not, we need to allocate a new saved pred using φ,\n       and extend R with l := pred *)\n    iMod (saved_pred_alloc φ) as (γpred) \"#Hφ'\".\n    iMod (own_update _ _ (● (<[l:=to_agree (γpred,_)]> (to_agree <$> M : relUR)) ⋅ ◯ ({[l:=to_agree (γpred,_)]}))\n            with \"Hγrel\") as \"[HR #Hγrel]\".\n    { apply auth_update_alloc.\n      apply (alloc_singleton_local_update (to_agree <$> M)); last done.\n      rewrite lookup_fmap. rewrite HRl. done.\n    }\n    (* we also need to extend the World with a new temporary region *)\n    iMod (sts_alloc_std_i W l Temporary\n            with \"[] Hfull\") as \"(Hfull & Hstate)\"; auto.\n    apply (related_sts_pub_world_fresh W l Temporary) in Hnone1 as Hrelated; auto.\n    iDestruct (region_map_monotone $! Hrelated with \"Hpreds\") as \"Hpreds'\".\n    iModIntro. rewrite bi.sep_exist_r. iExists _.\n    rewrite -fmap_insert.\n    iFrame \"HR\". iFrame \"∗ #\".\n    iSplitL;[iExists (<[l:=_]> Mρ);iSplitR;[|iSplitR]|].\n    - iPureIntro. repeat rewrite dom_insert_L. rewrite HMW. auto.\n    - iPureIntro. repeat rewrite dom_insert_L. rewrite HMρ. auto.\n    - iApply big_sepM_insert; auto.\n      iSplitR \"Hpreds'\".\n      { iExists Temporary. iFrame.\n        iSplitR;[iPureIntro;apply lookup_insert|].\n        iExists γpred,_,φ. iSplitR;[auto|]. iFrame \"∗ #\".\n        iSplitR;[auto|]. iExists v. iFrame.\n        rewrite Hpwl. iFrame \"#\". iSplitR;[auto|].\n        iNext. iApply \"Hmono\"; eauto.\n      }\n      iApply (big_sepM_mono with \"Hpreds'\").\n      iIntros (a x Ha) \"Hρ\".\n      iDestruct \"Hρ\" as (ρ Hρ) \"[Hstate Hρ]\".\n      iExists ρ.\n      assert (a ≠ l) as Hne;[intros Hcontr;subst a;rewrite HRl in Ha; inversion Ha|].\n      rewrite lookup_insert_ne;auto. iSplitR;[auto|]. iFrame.\n      destruct ρ; iFrame.\n      iDestruct \"Hρ\" as (γpred0 p0 φ0 Heq Hpers) \"[Hsaved Hl]\".\n      iDestruct \"Hl\" as (v0 Hg Hne') \"[Ha #Hall]\". iDestruct \"Hall\" as %Hall.\n      iExists _,_,_. repeat iSplit;eauto. iExists v0. iFrame. iSplit;auto. iPureIntro. split;auto.\n      eapply static_extend_preserve; eauto.\n    - iExists γpred. iFrame \"#\".\n      rewrite REL_eq /REL_def.\n      done.\n  Qed.\n\n  Lemma extend_region_temp_nwl E W l p v φ `{∀ Wv, Persistent (φ Wv)}:\n     p ≠ O →\n     l ∉ dom (gset Addr) (std W) →\n     (pwl p) = false →\n     (future_priv_mono φ v →\n     sts_full_world W -∗ region W -∗ l ↦ₐ[p] v -∗ φ (W,v) ={E}=∗ region (<s[l := Temporary ]s>W)\n                                                              ∗ rel l p φ\n                                                              ∗ sts_full_world (<s[l := Temporary ]s>W))%I.\n  Proof.\n    iIntros (Hpne Hnone1 Hpwl) \"#Hmono Hfull Hreg Hl #Hφ\".\n    rewrite region_eq rel_eq /region_def /rel_def.\n    iDestruct \"Hreg\" as (M Mρ) \"(Hγrel & HMW & HMρ & Hpreds)\".\n    iDestruct \"HMW\" as %HMW. iDestruct \"HMρ\" as %HMρ.\n    rewrite RELS_eq /RELS_def.\n    (* destruct on M !! l *)\n    destruct (M !! l) eqn:HRl.\n    { (* The location is not in the map *)\n      iDestruct (big_sepM_delete _ _ _ _ HRl with \"Hpreds\") as \"[Hl' _]\".\n      iDestruct \"Hl'\" as (ρ' Hl) \"[Hstate Hl']\".\n      iDestruct (sts_full_state_std with \"Hfull Hstate\") as %Hcontr.\n      apply (not_elem_of_dom W.1 l) in Hnone1.\n      rewrite Hcontr in Hnone1. done.\n    }\n    (* if not, we need to allocate a new saved pred using φ,\n       and extend R with l := pred *)\n    iMod (saved_pred_alloc φ) as (γpred) \"#Hφ'\".\n    iMod (own_update _ _ (● (<[l:=to_agree (γpred,_)]> (to_agree <$> M : relUR)) ⋅ ◯ ({[l:=to_agree (γpred,_)]}))\n            with \"Hγrel\") as \"[HR #Hγrel]\".\n    { apply auth_update_alloc.\n      apply (alloc_singleton_local_update (to_agree <$> M)); last done.\n      rewrite lookup_fmap. rewrite HRl. done.\n    }\n    (* we also need to extend the World with a new temporary region *)\n    iMod (sts_alloc_std_i W l Temporary\n            with \"[] Hfull\") as \"(Hfull & Hstate)\"; auto.\n    apply (related_sts_pub_world_fresh W l Temporary) in Hnone1 as Hrelated; auto.\n    iDestruct (region_map_monotone $! Hrelated with \"Hpreds\") as \"Hpreds'\".\n    iModIntro. rewrite bi.sep_exist_r. iExists _.\n    rewrite -fmap_insert.\n    iFrame \"HR\". iFrame.\n     iSplitL;[iExists (<[l:=_]> Mρ);iSplitR;[|iSplitR]|].\n    - iPureIntro. repeat rewrite dom_insert_L. rewrite HMW. auto.\n    - iPureIntro. repeat rewrite dom_insert_L. rewrite HMρ. auto.\n    - iApply big_sepM_insert; auto.\n      iSplitR \"Hpreds'\".\n      { iExists Temporary. iFrame.\n        iSplitR;[iPureIntro;apply lookup_insert|].\n        iExists γpred,_,φ. iSplitR;[auto|]. iFrame \"∗ #\".\n        iSplitR;[done|]. iExists _. iFrame.\n        rewrite Hpwl. iFrame \"#\". repeat iSplit;auto.\n        iNext. iApply \"Hmono\"; eauto.\n        iPureIntro. by apply related_sts_pub_priv_world.\n      }\n      iApply (big_sepM_mono with \"Hpreds'\").\n      iIntros (a x Ha) \"Hρ\".\n      iDestruct \"Hρ\" as (ρ Hρ) \"[Hstate Hρ]\".\n      iExists ρ.\n      assert (a ≠ l) as Hne;[intros Hcontr;subst a;rewrite HRl in Ha; inversion Ha|].\n      rewrite lookup_insert_ne;auto. iSplitR;[auto|]. iFrame.\n      destruct ρ; iFrame.\n      iDestruct \"Hρ\" as (γpred0 p0 φ0 Heq Hpers) \"[Hsaved Hl]\".\n      iDestruct \"Hl\" as (v0 Hg Hne') \"[Ha #Hall]\". iDestruct \"Hall\" as %Hall.\n      iExists _,_,_. repeat iSplit;eauto. iExists v0. iFrame. iSplit;auto. iPureIntro. split;auto.\n      eapply static_extend_preserve; eauto.\n    - iExists γpred. iFrame \"#\".\n      rewrite REL_eq /REL_def.\n      done.\n  Qed.\n\n  Lemma extend_region_perm E W l p v φ `{∀ Wv, Persistent (φ Wv)}:\n     p ≠ O →\n     l ∉ dom (gset Addr) (std W) →\n     (future_priv_mono φ v →\n     sts_full_world W -∗ region W -∗ l ↦ₐ[p] v -∗ φ (W,v) ={E}=∗ region (<s[l := Permanent ]s>W)\n                                                              ∗ rel l p φ\n                                                              ∗ sts_full_world (<s[l := Permanent ]s>W))%I.\n  Proof.\n    iIntros (Hpne Hnone1) \"#Hmono Hfull Hreg Hl #Hφ\".\n    rewrite region_eq rel_eq /region_def /rel_def.\n    iDestruct \"Hreg\" as (M Mρ) \"(Hγrel & HMW & HMρ & Hpreds)\".\n    iDestruct \"HMW\" as %HMW. iDestruct \"HMρ\" as %HMρ.\n    rewrite RELS_eq /RELS_def.\n    (* destruct on M !! l *)\n    destruct (M !! l) eqn:HRl.\n    { (* The location is not in the map *)\n      iDestruct (big_sepM_delete _ _ _ _ HRl with \"Hpreds\") as \"[Hl' _]\".\n      iDestruct \"Hl'\" as (ρ' Hl) \"[Hstate Hl']\".\n      iDestruct (sts_full_state_std with \"Hfull Hstate\") as %Hcontr.\n      apply (not_elem_of_dom W.1 l) in Hnone1.\n      rewrite Hcontr in Hnone1. done.\n    }\n    (* if not, we need to allocate a new saved pred using φ,\n       and extend R with l := pred *)\n    iMod (saved_pred_alloc φ) as (γpred) \"#Hφ'\".\n    iMod (own_update _ _ (● (<[l:=to_agree (γpred,_)]> (to_agree <$> M : relUR)) ⋅ ◯ ({[l:=to_agree (γpred,_)]}))\n            with \"Hγrel\") as \"[HR #Hγrel]\".\n    { apply auth_update_alloc.\n      apply (alloc_singleton_local_update (to_agree <$> M)); last done.\n      rewrite lookup_fmap. rewrite HRl. done.\n    }\n    (* we also need to extend the World with a new temporary region *)\n    iMod (sts_alloc_std_i W l Permanent\n            with \"[] Hfull\") as \"(Hfull & Hstate)\"; auto.\n    apply (related_sts_pub_world_fresh W l Permanent) in Hnone1 as Hrelated; auto.\n    iDestruct (region_map_monotone $! Hrelated with \"Hpreds\") as \"Hpreds'\".\n    iModIntro. rewrite bi.sep_exist_r. iExists _.\n    rewrite -fmap_insert.\n    iFrame \"HR\". iFrame.\n    iSplitL;[iExists (<[l:=_]> Mρ);iSplitR;[|iSplitR]|].\n    - iPureIntro. repeat rewrite dom_insert_L. rewrite HMW. auto.\n    - iPureIntro. repeat rewrite dom_insert_L. rewrite HMρ. auto.\n    - iApply big_sepM_insert; auto.\n      iSplitR \"Hpreds'\".\n      { iExists Permanent. iFrame.\n        iSplitR;[iPureIntro;apply lookup_insert|].\n        iExists γpred,_,φ. iSplitR;[auto|]. iFrame \"∗ #\".\n        iSplitR;[done|]. iExists _. iFrame. repeat iSplit;auto.\n        iNext. iApply \"Hmono\"; eauto.\n        iPureIntro. by apply related_sts_pub_priv_world.\n      }\n      iApply (big_sepM_mono with \"Hpreds'\").\n      iIntros (a x Ha) \"Hρ\".\n      iDestruct \"Hρ\" as (ρ Hρ) \"[Hstate Hρ]\".\n      iExists ρ.\n      assert (a ≠ l) as Hne;[intros Hcontr;subst a;rewrite HRl in Ha; inversion Ha|].\n      rewrite lookup_insert_ne;auto. iSplitR;[auto|]. iFrame.\n      destruct ρ; iFrame.\n      iDestruct \"Hρ\" as (γpred0 p0 φ0 Heq Hpers) \"[Hsaved Hl]\".\n      iDestruct \"Hl\" as (v0 Hg Hne') \"[Ha #Hall]\". iDestruct \"Hall\" as %Hall.\n      iExists _,_,_. repeat iSplit;eauto. iExists v0. iFrame. iSplit;auto. iPureIntro. split;auto.\n      eapply static_extend_preserve; eauto.\n    - iExists γpred. iFrame \"#\".\n      rewrite REL_eq /REL_def.\n      done.\n  Qed.\n\n  (* The following allocates a Revoked region. This allocates the saved predicate and the region state, *)\n  (* but since a revoked region is empty, there is no need to assume any resources for that region *)\n\n  Lemma extend_region_revoked E W l p φ `{∀ Wv, Persistent (φ Wv)} :\n     l ∉ dom (gset Addr) (std W) →\n     (sts_full_world W -∗ region W ={E}=∗ region (<s[l := Revoked ]s>W)\n                                               ∗ rel l p φ\n                                               ∗ sts_full_world (<s[l := Revoked ]s>W))%I.\n  Proof.\n    iIntros (Hnone1) \"Hfull Hreg\".\n    rewrite region_eq rel_eq /region_def /rel_def.\n    iDestruct \"Hreg\" as (M Mρ) \"(Hγrel & HMW & HMρ & Hpreds)\".\n    iDestruct \"HMW\" as %HMW. iDestruct \"HMρ\" as %HMρ.\n    rewrite RELS_eq /RELS_def.\n    (* destruct on M !! l *)\n    destruct (M !! l) eqn:HRl.\n    { (* The location is not in the map *)\n      iDestruct (big_sepM_delete _ _ _ _ HRl with \"Hpreds\") as \"[Hl' _]\".\n      iDestruct \"Hl'\" as (ρ' Hl) \"[Hstate Hl']\".\n      iDestruct (sts_full_state_std with \"Hfull Hstate\") as %Hcontr.\n      apply (not_elem_of_dom W.1 l) in Hnone1.\n      rewrite Hcontr in Hnone1. done.\n    }\n    (* if not, we need to allocate a new saved pred using φ,\n       and extend R with l := pred *)\n    iMod (saved_pred_alloc φ) as (γpred) \"#Hφ'\".\n    iMod (own_update _ _ (● (<[l:=to_agree (γpred,p)]> (to_agree <$> M : relUR)) ⋅ ◯ ({[l:=to_agree (γpred,p)]}))\n            with \"Hγrel\") as \"[HR #Hγrel]\".\n    { apply auth_update_alloc.\n      apply (alloc_singleton_local_update (to_agree <$> M)); last done.\n      rewrite lookup_fmap. rewrite HRl. done.\n    }\n    (* we also need to extend the World with a new temporary region *)\n    iMod (sts_alloc_std_i W l Revoked\n            with \"[] Hfull\") as \"(Hfull & Hstate)\"; auto.\n    apply (related_sts_pub_world_fresh W l Revoked) in Hnone1 as Hrelated; auto.\n    iDestruct (region_map_monotone $! Hrelated with \"Hpreds\") as \"Hpreds'\".\n    iModIntro. rewrite bi.sep_exist_r. iExists _.\n    rewrite -fmap_insert.\n    iFrame \"HR\". iFrame.\n    iSplitL;[iExists (<[l:=_]> Mρ);iSplitR;[|iSplitR]|].\n    - iPureIntro. repeat rewrite dom_insert_L. rewrite HMW. auto.\n    - iPureIntro. repeat rewrite dom_insert_L. rewrite HMρ. auto.\n    - iApply big_sepM_insert; auto.\n      iSplitR \"Hpreds'\".\n      { iExists Revoked. iFrame. iSplitR.\n        iPureIntro;apply lookup_insert.\n        iExists _,_,_. iFrame \"#\". iSplit;eauto.\n      }\n      iApply (big_sepM_mono with \"Hpreds'\").\n      iIntros (a x Ha) \"Hρ\".\n      iDestruct \"Hρ\" as (ρ Hρ) \"[Hstate Hρ]\".\n      iExists ρ.\n      assert (a ≠ l) as Hne;[intros Hcontr;subst a;rewrite HRl in Ha; inversion Ha|].\n      rewrite lookup_insert_ne;auto. iSplitR;[auto|]. iFrame.\n      destruct ρ; iFrame.\n      iDestruct \"Hρ\" as (γpred0 p0 φ0 Heq Hpers) \"[Hsaved Hl]\".\n      iDestruct \"Hl\" as (v0 Hg Hne') \"[Ha #Hall]\". iDestruct \"Hall\" as %Hall.\n      iExists _,_,_. repeat iSplit;eauto. iExists v0. iFrame. iSplit;auto. iPureIntro. split;auto.\n      eapply static_extend_preserve; eauto.\n    - iExists γpred. iFrame \"#\".\n      rewrite REL_eq /REL_def.\n      done.\n  Qed.\n\n  Lemma extend_region_perm_sepL2 E W l1 l2 p φ `{∀ Wv, Persistent (φ Wv)}:\n     p ≠ O →\n     Forall (λ k, std W !! k = None) l1 →\n     (sts_full_world W -∗ region W -∗\n     ([∗ list] k;v ∈ l1;l2, k ↦ₐ[p] v ∗ φ (W, v) ∗ future_priv_mono φ v)\n\n     ={E}=∗\n\n     region (std_update_multiple W l1 Permanent)\n     ∗ ([∗ list] k ∈ l1, rel k p φ)\n     ∗ sts_full_world (std_update_multiple W l1 Permanent))%I.\n  Proof.\n    revert l2. induction l1.\n    { cbn. intros. iIntros \"? ? ?\". iFrame. eauto. }\n    { intros * ? [? ?]%Forall_cons_1. iIntros \"Hsts Hr Hl\".\n      iDestruct (big_sepL2_length with \"Hl\") as %Hlen.\n      iDestruct (NoDup_of_sepL2_exclusive with \"[] Hl\") as %[Hal1 ND]%NoDup_cons.\n      { iIntros (? ? ?) \"(H1 & ? & ?) (H2 & ? & ?)\".\n        iApply (cap_duplicate_false with \"[$H1 $H2]\"). auto. }\n      destruct l2; [ by inversion Hlen |].\n      iDestruct (big_sepL2_cons with \"Hl\") as \"[(Ha & Hφ & #Hf) Hl]\".\n      iMod (IHl1 with \"Hsts Hr Hl\") as \"(Hr & ? & Hsts)\"; auto.\n      iDestruct (extend_region_perm with \"Hf Hsts Hr Ha [Hφ]\") as \">(? & ? & ?)\"; auto.\n      { rewrite -std_update_multiple_not_in_sta; auto.\n        rewrite not_elem_of_dom //. }\n      { iApply (\"Hf\" with \"[] Hφ\"). iPureIntro.\n        apply related_sts_pub_priv_world, related_sts_pub_update_multiple.\n        eapply Forall_impl; eauto.\n        intros. by rewrite not_elem_of_dom. }\n      iModIntro. cbn. iFrame. }\n  Qed.\n\n  Lemma extend_region_static_single E W l p v φ `{∀ Wv, Persistent (φ Wv)}:\n     p ≠ O →\n     l ∉ dom (gset Addr) (std W) →\n     (sts_full_world W -∗ region W -∗ l ↦ₐ[p] v\n     ={E}=∗\n     region (<s[l := Static {[l := v]}]s>W)\n     ∗ rel l p φ\n     ∗ sts_full_world (<s[l := Static {[l := v]} ]s>W))%I.\n  Proof.\n    iIntros (Hpne Hnone1) \"Hfull Hreg Hl\".\n    rewrite region_eq rel_eq /region_def /rel_def.\n    iDestruct \"Hreg\" as (M Mρ) \"(Hγrel & HdomM & HdomMρ & Hpreds)\".\n    iDestruct \"HdomM\" as %HdomM. iDestruct \"HdomMρ\" as %HdomMρ.\n    rewrite RELS_eq /RELS_def.\n    (* destruct on M !! l *)\n    destruct (M !! l) eqn:HRl.\n    { (* The location is not in the map *)\n      iDestruct (big_sepM_delete _ _ _ _ HRl with \"Hpreds\") as \"[Hl' _]\".\n      iDestruct \"Hl'\" as (ρ' Hl) \"[Hstate Hl']\".\n      iDestruct (sts_full_state_std with \"Hfull Hstate\") as %Hcontr.\n      apply (not_elem_of_dom W.1 l) in Hnone1.\n      rewrite Hcontr in Hnone1. done.\n    }\n    (* if not, we need to allocate a new saved pred using φ,\n       and extend R with l := pred *)\n    iMod (saved_pred_alloc φ) as (γpred) \"#Hφ'\".\n    iMod (own_update _ _ (● (<[l:=to_agree (γpred,_)]> (to_agree <$> M : relUR)) ⋅ ◯ ({[l:=to_agree (γpred,_)]}))\n            with \"Hγrel\") as \"[HR #Hγrel]\".\n    { apply auth_update_alloc.\n      apply (alloc_singleton_local_update (to_agree <$> M)); last done.\n      rewrite lookup_fmap. rewrite HRl. done.\n    }\n    (* we also need to extend the World with a new temporary region *)\n    iMod (sts_alloc_std_i W l (Static {[l:=v]})\n            with \"[] Hfull\") as \"(Hfull & Hstate)\"; auto.\n    eapply (related_sts_pub_world_fresh W l (Static {[l:=v]})) in Hnone1 as Hrelated; auto.\n    iDestruct (region_map_monotone $! Hrelated with \"Hpreds\") as \"Hpreds'\".\n    iModIntro. rewrite bi.sep_exist_r. iExists _.\n    rewrite -fmap_insert.\n    iFrame \"HR\". iFrame.\n    iSplitL;[iExists (<[l:=_]> Mρ);iSplitR;[|iSplitR]|].\n    - iPureIntro. repeat rewrite dom_insert_L. rewrite HdomM. auto.\n    - iPureIntro. repeat rewrite dom_insert_L. rewrite HdomMρ. auto.\n    - iApply big_sepM_insert; auto.\n      iSplitR \"Hpreds'\".\n      { iExists (Static {[l:=v]}). iFrame.\n        iSplitR;[iPureIntro;apply lookup_insert|].\n        iExists γpred,_,φ. iSplitR;[auto|]. iFrame \"∗ #\".\n        iSplitR;[done|]. iExists _. iFrame. repeat iSplit;auto.\n        iPureIntro. apply lookup_singleton.\n        iPureIntro. intro. rewrite dom_singleton elem_of_singleton.\n        intros ->. apply lookup_insert. }\n      iApply (big_sepM_mono with \"Hpreds'\").\n      iIntros (a x Ha) \"Hρ\".\n      iDestruct \"Hρ\" as (ρ Hρ) \"[Hstate Hρ]\".\n      iExists ρ.\n      assert (a ≠ l) as Hne;[intros Hcontr;subst a;rewrite HRl in Ha; inversion Ha|].\n      rewrite lookup_insert_ne;auto. iSplitR;[auto|]. iFrame.\n      destruct ρ; iFrame.\n      iDestruct \"Hρ\" as (γpred0 p0 φ0 Heq Hpers) \"[Hsaved Hl]\".\n      iDestruct \"Hl\" as (v0 Hg Hne') \"[Ha #Hall]\". iDestruct \"Hall\" as %Hall.\n      iExists _,_,_. repeat iSplit;eauto. iExists v0. iFrame. iSplit;auto. iPureIntro. split;auto.\n      eapply static_extend_preserve; eauto.\n    - iExists γpred. iFrame \"#\".\n      rewrite REL_eq /REL_def.\n      done.\n  Qed.\n\n  Lemma extend_region_static_single_sepM E W (m: gmap Addr Word) p φ `{∀ Wv, Persistent (φ Wv)}:\n     p ≠ O →\n     (∀ k, is_Some (m !! k) → std W !! k = None) →\n     (sts_full_world W -∗ region W -∗\n     ([∗ map] k↦v ∈ m, k ↦ₐ[p] v)\n\n     ={E}=∗\n\n     region (override_uninitializedW m W)\n     ∗ ([∗ map] k↦_ ∈ m, rel k p φ)\n     ∗ sts_full_world (override_uninitializedW m W))%I.\n  Proof.\n    induction m using map_ind.\n    { intros. rewrite !override_uninitializedW_empty !big_sepM_empty.\n      iIntros. by iFrame. }\n    { iIntros (? HnW) \"Hsts Hr H\". rewrite big_sepM_insert //.\n      iDestruct \"H\" as \"(Hk & Hm)\".\n      rewrite !override_uninitializedW_insert.\n      iMod (IHm with \"Hsts Hr Hm\") as \"(Hr & Hm & Hsts)\"; auto.\n      { intros. apply HnW. rewrite lookup_insert_is_Some.\n        destruct (decide (i = k)); auto. }\n      iDestruct (extend_region_static_single with \"Hsts Hr Hk\")\n        as \">(Hr & Hrel & Hsts)\"; auto.\n      { rewrite override_uninitializedW_dom'.\n        rewrite not_elem_of_union !not_elem_of_dom. split; auto.\n        apply HnW. rewrite lookup_insert //. eauto. }\n      iFrame. iModIntro. iApply big_sepM_insert; eauto. }\n  Qed.\n\nEnd region_alloc.\n", "meta": {"author": "logsem", "repo": "cerise-stack", "sha": "f68111362730aff998798d63c7d6a0a7176eff44", "save_path": "github-repos/coq/logsem-cerise-stack", "path": "github-repos/coq/logsem-cerise-stack/cerise-stack-f68111362730aff998798d63c7d6a0a7176eff44/theories/region_invariants_allocation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2025074012502626}}
{"text": "Require Import ucos_include.\nRequire Import OSMutex_common.\nRequire Import os_ucos_h.\nRequire Import mutex_absop_rules.\nRequire Import sep_lemmas_ext.\nRequire Import symbolic_lemmas.\nRequire Import OSTimeDlyPure.\nRequire Import OSQPostPure.\nRequire Import tcblist_setnode_lemmas.\nRequire Import OSMutexPostPure.\n\nLocal Open Scope code_scope.\nLocal Open Scope nat_scope.\nLocal Open Scope Z_scope.\nLocal Open Scope int_scope.\nLocal Open Scope list_scope.\n\nLemma tcbjoin_get_exists :\n  forall (tcbls:TcbMod.map) a x,\n    get tcbls a = Some x ->\n    exists tcbls',\n      TcbJoin a x tcbls' tcbls.\nProof.\n  intros.\n  unfold TcbJoin.\n  exists (minus tcbls (sig a x)).\n  unfold join, minus, sig; simpl.\n  unfold get in H; simpl in H.\n  unfold TcbMod.join; intro.\n  destruct (tidspec.beq a a0) eqn : eq1.\n  lets Hx: tidspec.beq_true_eq eq1; substs.\n  rewrite TcbMod.get_sig_some.\n  rewrite TcbMod.minus_sem.\n  rewrite TcbMod.get_sig_some.\n  rewrite H; auto.\n  lets Hx: tidspec.beq_false_neq eq1.\n  rewrite TcbMod.minus_sem.\n  rewrite TcbMod.get_sig_none; auto.\n  destruct (TcbMod.get tcbls a0); auto.\nQed.\n\nLemma OSMapVallist_bound :\n  forall n (i:int32),\n    (n < 8)%nat -> exists i, nth_val' n OSMapVallist = Vint32 i /\\ (Int.unsigned i) <= 128. \nProof.\n  intros.\n  destruct n.\n  simpl; exists ($1); split; mauto.\n  destruct n.\n  simpl; exists ($2); split; mauto.\n  destruct n.\n  simpl; exists ($4); split; mauto.\n  destruct n.\n  simpl; exists ($8); split; mauto.\n  destruct n.\n  simpl; exists ($16); split; mauto.\n  destruct n.\n  simpl; exists ($32); split; mauto.\n  destruct n.\n  simpl; exists ($64); split; mauto.\n  destruct n.\n  simpl; exists ($128); split; mauto.\n  omega.\nQed.\n\n\nLemma mutex_post_no_pi_part1 :\n  forall \n   ( v'  v'0  v'1  v'2 : val)\n(v'3  v'4  v'5 : list vallist )\n(  v'6 : list EventData)\n(  v'7 : list os_inv.EventCtr)\n(  v'8 : vallist)\n(  v'9  v'10 : val)\n(  v'11 : list vallist)\n(  v'12 : vallist)\n(  v'13 : list vallist)\n(  v'14 : vallist)\n(  v'15 : val)\n(  v'16 : EcbMod.map)\n(  v'17 : TcbMod.map)\n(  v'18 : int32)\n(  v'19 : addrval)\n(  v'21 : val)\n(  v'22 : list vallist)\n(  v'25  v'26 : list os_inv.EventCtr)\n(  v'27  v'28 : list EventData)\n(  v'33  v'35 : list vallist)\n(  v'38 : EcbMod.map)\n(  v'42  v'46 : val)\n(  v'47  v'48  v'49 : EcbMod.map)\n(  w : waitset)\n(  H17 : EcbMod.join v'47 v'49 v'38)\n(  H12 : length v'25 = length v'27)\n(  H16 : isptr v'46)\n(  v'23 : addrval)\n(  x3 : val)\n(  H24 : isptr v'46)\n(  H20 : Int.unsigned ($ OS_EVENT_TYPE_MUTEX) <= 255)\n(  x : int32)\n(  H10 : Int.unsigned x <= 65535)\n(  H15 : Int.unsigned (x >>ᵢ $ 8) < 64)\n(  H22 : Int.unsigned x <= 65535)\n(  v'24 : val)\n(  v'43  v'45 : TcbMod.map)\n(  v'52 : block)\n(  H30 : Vptr (v'52, Int.zero) <> Vnull)\n(  H36 : isptr v'24)\n(  x7 : val)\n(  x10 : TcbMod.map)\n(  m : msg)\n(  H : RH_TCBList_ECBList_P v'16 v'17 (v'52, Int.zero))\n(  H0 : RH_CurTCB (v'52, Int.zero) v'17)\n(  H23 : isptr (Vptr (v'52, $ 0)))\n(  H29 : x&ᵢ$ OS_MUTEX_KEEP_LOWER_8 = $ OS_MUTEX_AVAILABLE \\/\n        x&ᵢ$ OS_MUTEX_KEEP_LOWER_8 <> $ OS_MUTEX_AVAILABLE ) \n(  H35 : x&ᵢ$ OS_MUTEX_KEEP_LOWER_8 <> $ OS_MUTEX_AVAILABLE)\n(  H47 : Int.ltu (x >>ᵢ $ 8) (x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) = true)\n(  H48 : Int.unsigned (x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) < 64)\n(  H4 : Some (v'52, $ 0, x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) = None -> w = nil)\n(  H9 : forall (tid0 : tid) (opr : int32),\n       Some (v'52, $ 0, x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) = Some (tid0, opr) ->\n       Int.ltu (x >>ᵢ $ 8) opr = true /\\ Int.unsigned opr < 64 )\n(  H13 : w <> nil -> Some (v'52, $ 0, x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) <> None )\n(  H25 : x&ᵢ$ OS_MUTEX_KEEP_LOWER_8 = $ OS_MUTEX_AVAILABLE ->\n        Some (v'52, $ 0, x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) = None /\\\n        Vptr (v'52, $ 0) = Vnull )\n(  H26 : x&ᵢ$ OS_MUTEX_KEEP_LOWER_8 <> $ OS_MUTEX_AVAILABLE ->\n        exists tid,\n        Vptr (v'52, $ 0) = Vptr tid /\\\n        Some (v'52, $ 0, x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) =\n        Some (tid, x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) )\n(  backup : RLH_ECBData_P (DMutex (Vint32 x) (Vptr (v'52, $ 0)))\n             (absmutexsem (x >>ᵢ $ 8)\n                (Some (v'52, $ 0, x&ᵢ$ OS_MUTEX_KEEP_LOWER_8)), w) )\n(  v'32  x1  x0 : val )\n(  i7 : int32)\n(  H55 : Int.unsigned i7 <= 255)\n(  x2 : int32)\n(  H59 : length OSUnMapVallist = 256%nat)\n(  H62 : true = rule_type_val_match Int8u (Vint32 x2))\n(  fffbb : Int.unsigned x2 < 8)\n(  x4 : int32)\n(  H64 : Int.unsigned x4 <= 255)\n(  H65 : (Z.to_nat (Int.unsigned x4) < length OSUnMapVallist)%nat)\n(  x5 : int32)\n(  H66 : nth_val' (Z.to_nat (Int.unsigned x4)) OSUnMapVallist = Vint32 x5)\n(  H67 : Int.unsigned x5 <= 255)\n(  ttfasd : Int.unsigned x5 < 8)\n(  H27 : isptr x7)\n(  H38 : isptr m)\n(  x6 : int32)\n(  H77 : 0 <= Int.unsigned x6)\n(  H85 : Int.unsigned x6 < 64)\n(  x15 : val)\n(  H43 : Int.unsigned (x6 >>ᵢ $ 3) <= 255)\n(  H45 : Int.unsigned ($ 1<<ᵢ(x6 >>ᵢ $ 3)) <= 255)\n(  H44 : Int.unsigned ($ 1<<ᵢ(x6&ᵢ$ 7)) <= 255)\n(  H42 : Int.unsigned (x6&ᵢ$ 7) <= 255)\n(  H41 : Int.unsigned x6 <= 255)\n(  H28 : Int.ltu x6 (x >>ᵢ $ 8) = false)\n(  H37 : isptr x15)\n(  r1 : Int.unsigned ((x >>ᵢ $ 8) >>ᵢ $ 3) < 8)\n(  r2 : Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8)&ᵢ$ 7) < 8)\n(  r3 : Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) >>ᵢ $ 3) < 8)\n(  r4 : Int.unsigned ((x >>ᵢ $ 8)&ᵢ$ 7) < 8)\n(  H34 : array_type_vallist_match Int8u OSMapVallist)\n(  H69 : length OSMapVallist = 8%nat)\n(  H71 : (Z.to_nat (Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) >>ᵢ $ 3)) <\n         8)%nat )\n(  x8 : int32 )\n(  H74 : nth_val'\n          (Z.to_nat\n             (Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) >>ᵢ $ 3)))\n          OSMapVallist = Vint32 x8 )\n(  H75 : true = rule_type_val_match Int8u (Vint32 x8))\n(  H76 : (Z.to_nat (Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8)&ᵢ$ 7)) < 8)%nat)\n(  x9 : int32)\n(  H78 : nth_val'\n          (Z.to_nat (Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8)&ᵢ$ 7)))\n          OSMapVallist = Vint32 x9 )\n(  H79 : true = rule_type_val_match Int8u (Vint32 x9))\n(  H80 : (Z.to_nat (Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8)&ᵢ$ 7)) < 8)%nat)\n(  x11 : int32)\n(  H81 : nth_val'\n          (Z.to_nat (Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8)&ᵢ$ 7)))\n          OSMapVallist = Vint32 x11)\n(  H83 : true = rule_type_val_match Int8u (Vint32 x11))\n(  r5 : Int.unsigned (x6 >>ᵢ $ 3) < 8)\n(  r6 : Int.unsigned (x6&ᵢ$ 7) < 8)\n(  x16 : int32)\n(  H91 : Int.unsigned x16 <= 255)\n(  x13 : int32)\n(  H90 : Int.unsigned x13 <= 255)\n(  x12 : int32)\n(  H89 : Int.unsigned x12 <= 255)\n(  H92 : Int.unsigned (x >>ᵢ $ 8) < Int.unsigned ($ Byte.modulus))\n(  H70 : TcbJoin (v'52, Int.zero) (x6, rdy, m) x10 v'45)\n(  H82 : $ OS_STAT_RDY = $ OS_STAT_RDY \\/\n        $ OS_STAT_RDY = $ OS_STAT_SEM \\/\n        $ OS_STAT_RDY = $ OS_STAT_Q \\/\n        $ OS_STAT_RDY = $ OS_STAT_MBOX \\/\n        $ OS_STAT_RDY = $ OS_STAT_MUTEX )\n(  H84 : $ OS_STAT_RDY = $ OS_STAT_RDY -> x15 = Vnull)\n(  H40 : Int.unsigned ($ OS_STAT_RDY) <= 255)\n(  H39 : Int.unsigned ($ 0) <= 65535)\n(  H93 : val_inj\n          (if Int.eq x6 (x >>ᵢ $ 8)\n           then Some (Vint32 Int.one)\n           else Some (Vint32 Int.zero)) = Vint32 Int.zero \\/\n        val_inj\n          (if Int.eq x6 (x >>ᵢ $ 8)\n           then Some (Vint32 Int.one)\n           else Some (Vint32 Int.zero)) = Vnull )\n(  v'34 : addrval)\n(  v'37 : TcbMod.map)\n(  v'53 : list val)\n(  v'54 : vallist)\n(  v'57 : val)\n(  v'58  v'59 : int32)\n(  v'60 : vallist)\n(  v'67  v'69 : val)\n(  v'73  v'74  v'75  v'76  v'77 : int32)\n(  v'80  v'81  v'82  v'83  v'84 : val)\n(  v'85 : int32)\n(  v'86  v'87  v'88  v'89  v'90 : val)\n(  v'91 : block)\n(  v'92 : int32)\n(  H95 : nth_val' (Z.to_nat (Int.unsigned v'74)) v'54 = Vint32 v'92)\n(  H97 : nth_val' (Z.to_nat (Int.unsigned ((v'74<<ᵢ$ 3) +ᵢ  v'73))) v'53 =\n        Vptr (v'91, Int.zero) /\\ (v'91, Int.zero) <> v'34 )\n(  H103 : nth_val' (Z.to_nat (Int.unsigned v'58)) OSUnMapVallist =\n         Vint32 v'74 )\n(  H104 : nth_val' (Z.to_nat (Int.unsigned v'74)) v'60 = Vint32 v'75 )\n(  H105 : nth_val' (Z.to_nat (Int.unsigned v'75)) OSUnMapVallist =\n         Vint32 v'73 )\n(  H106 : nth_val' (Z.to_nat (Int.unsigned v'74)) OSMapVallist =\n         Vint32 v'77 )\n(  H107 : nth_val' (Z.to_nat (Int.unsigned v'73)) OSMapVallist =\n         Vint32 v'76 )\n(  H112 : array_type_vallist_match Int8u v'54 /\\\n         length v'54 = ∘ OS_RDY_TBL_SIZE )\n(  H114 : RL_Tbl_Grp_P v'60 (Vint32 v'58))\n(  H115 : array_type_vallist_match Int8u v'60)\n(  H120 : array_type_vallist_match OS_TCB ∗ v'53 /\\ length v'53 = 64%nat)\n(  H122 : R_PrioTbl_P v'53 v'37 v'34)\n(  H31 : v'67 <> Vnull)\n(  H46 : array_type_vallist_match OS_TCB ∗ v'53)\n(  H51 : length v'53 = 64%nat)\n(  H52 : nth_val (Z.to_nat (Int.unsigned (x&ᵢ$ OS_MUTEX_KEEP_LOWER_8)))\n          v'53 = Some x1 )\n(  H53 : nth_val (Z.to_nat (Int.unsigned (x >>ᵢ $ 8))) v'53 = Some x0)\n(  H72 : TCBList_P x7 v'35 v'54 x10)\n(  H54 : array_type_vallist_match Int8u v'54)\n(  H58 : length v'54 = ∘ OS_RDY_TBL_SIZE)\n(  H57 : prio_in_tbl ($ OS_IDLE_PRIO) v'54)\n(  H56 : RL_Tbl_Grp_P v'54 (Vint32 i7))\n(  rr1 : (Z.to_nat (Int.unsigned ((x >>ᵢ $ 8) >>ᵢ $ 3)) < length v'54)%nat)\n(  rr2 : (Z.to_nat (Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8)&ᵢ$ 7)) <\n         length v'54)%nat )\n(  rr3 : (Z.to_nat (Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) >>ᵢ $ 3)) <\n         length v'54)%nat )\n(  rr4 : (Z.to_nat (Int.unsigned ((x >>ᵢ $ 8)&ᵢ$ 7)) < length v'54)%nat)\n(  rr5 : (Z.to_nat (Int.unsigned (x6 >>ᵢ $ 3)) < length v'54)%nat)\n(  rr6 : (Z.to_nat (Int.unsigned (x6&ᵢ$ 7)) < length v'54)%nat)\n(  rrr1 : Int.unsigned ((x >>ᵢ $ 8) >>ᵢ $ 3) < Z.of_nat (length v'54))\n(  rrr2 : Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8)&ᵢ$ 7) <\n         Z.of_nat (length v'54) )\n(  rrr3 : Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) >>ᵢ $ 3) <\n         Z.of_nat (length v'54) )\n(  rrr4 : Int.unsigned ((x >>ᵢ $ 8)&ᵢ$ 7) < Z.of_nat (length v'54))\n(  rrr5 : Int.unsigned (x6 >>ᵢ $ 3) < Z.of_nat (length v'54))\n(  rrr6 : Int.unsigned (x6&ᵢ$ 7) < Z.of_nat (length v'54))\n(  HH58 : length v'54 = Z.to_nat 8)\n(  aa : rule_type_val_match Int8u\n         (nth_val' (Z.to_nat (Int.unsigned ((x >>ᵢ $ 8) >>ᵢ $ 3))) v'54) =\n       true )\n(  aa2 : rule_type_val_match Int8u\n          (nth_val'\n             (Z.to_nat\n                (Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) >>ᵢ $ 3)))\n             v'54) = true )\n(  aa3 : rule_type_val_match Int8u\n          (nth_val' (Z.to_nat (Int.unsigned (x6 >>ᵢ $ 3))) v'54) = true )\n(  H88 : nth_val' (Z.to_nat (Int.unsigned ((x >>ᵢ $ 8) >>ᵢ $ 3))) v'54 =\n        Vint32 x16 )\n(  H87 : nth_val'\n          (Z.to_nat\n             (Int.unsigned ((x&ᵢ$ OS_MUTEX_KEEP_LOWER_8) >>ᵢ $ 3))) v'54 =\n        Vint32 x13 )\n(  H86 : nth_val' (Z.to_nat (Int.unsigned (x6 >>ᵢ $ 3))) v'54 =\n        Vint32 x12 )\n(  backup2 : TCBList_P (Vptr (v'52, Int.zero))\n              ((x7\n                :: v'24\n                   :: x15\n                      :: m\n                         :: V$ 0\n                            :: V$ OS_STAT_RDY\n                               :: Vint32 x6\n                                  :: Vint32 (x6&ᵢ$ 7)\n                                     :: Vint32 (x6 >>ᵢ $ 3)\n                                        :: Vint32 ($ 1<<ᵢ(x6&ᵢ$ 7))\n                                           :: Vint32\n                                              ($ 1<<ᵢ(x6 >>ᵢ $ 3))\n                                              :: nil) :: v'35) v'54 v'45 )\n(  H73 : R_TCB_Status_P\n          (x7\n           :: v'24\n              :: x15\n                 :: m\n                    :: V$ 0\n                       :: V$ OS_STAT_RDY\n                          :: Vint32 x6\n                             :: Vint32 (x6&ᵢ$ 7)\n                                :: Vint32 (x6 >>ᵢ $ 3)\n                                   :: Vint32 ($ 1<<ᵢ(x6&ᵢ$ 7))\n                                      :: Vint32 ($ 1<<ᵢ(x6 >>ᵢ $ 3))\n                                         :: nil) v'54 \n          (x6, rdy, m) )\n(  H33 : TCBList_P v'67 v'33 v'54 v'43)\n(  H49 : RL_RTbl_PrioTbl_P v'54 v'53 v'34)\n(  H111 : RL_Tbl_Grp_P v'54 (Vint32 i7) /\\\n         prio_in_tbl ($ OS_IDLE_PRIO) v'54 )\n(  H113 : rule_type_val_match Int8u (Vint32 i7) = true)\n(  H11 : array_type_vallist_match Int8u v'60)\n(  H19 : length v'60 = ∘ OS_EVENT_TBL_SIZE)\n(  fffbb2 : (Z.to_nat (Int.unsigned x2) < length v'60)%nat)\n(  H19'' : length v'60 = Z.to_nat 8)\n(  H63 : nth_val' (Z.to_nat (Int.unsigned x2)) v'60 = Vint32 x4)\n(  H102 : rel_edata_tcbstat (DMutex (Vint32 x) (Vptr (v'52, $ 0))) v'85)\n(  H3 : ECBList_P v'46 Vnull v'26 v'28 v'48 v'37)\n(  H32 : join v'43 v'45 v'37)\n(  H7 : RH_TCBList_ECBList_P v'38 v'37 (v'52, Int.zero))\n(  H8 : RH_CurTCB (v'52, Int.zero) v'37)\n(  H50 : R_PrioTbl_P v'53 v'37 v'34)\n(  H124 : TCBList_P v'67\n           (v'33 ++\n            (x7\n             :: v'24\n                :: x15\n                   :: m\n                      :: V$ 0\n                         :: V$ OS_STAT_RDY\n                            :: Vint32 x6\n                               :: Vint32 (x6&ᵢ$ 7)\n                                  :: Vint32 (x6 >>ᵢ $ 3)\n                                     :: Vint32 ($ 1<<ᵢ(x6&ᵢ$ 7))\n                                        :: Vint32 ($ 1<<ᵢ(x6 >>ᵢ $ 3))\n                                           :: nil) :: v'35) v'54 v'37 )\n(  H21 : Int.unsigned v'58 <= 255 )\n(  fffa : length OSUnMapVallist = 256%nat ->\n         (Z.to_nat (Int.unsigned v'58) < 256)%nat ->\n         exists x,\n         Vint32 x2 = Vint32 x /\\\n         true = rule_type_val_match Int8u (Vint32 x) )\n(  H60 : (Z.to_nat (Int.unsigned v'58) < 256)%nat )\n(  H61 : nth_val' (Z.to_nat (Int.unsigned v'58)) OSUnMapVallist =\n        Vint32 x2 )\n(  H68 : val_inj\n          (bool_and\n             (val_inj\n                (notint\n                   (val_inj\n                      (if Int.eq v'58 ($ 0)\n                       then Some (Vint32 Int.one)\n                       else Some (Vint32 Int.zero)))))\n             (val_inj\n                (bool_or\n                   (val_inj\n                      (if Int.ltu ((x2<<ᵢ$ 3) +ᵢ  x5) (x >>ᵢ $ 8)\n                       then Some (Vint32 Int.one)\n                       else Some (Vint32 Int.zero)))\n                   (val_inj\n                      (if Int.eq ((x2<<ᵢ$ 3) +ᵢ  x5) (x >>ᵢ $ 8)\n                       then Some (Vint32 Int.one)\n                       else Some (Vint32 Int.zero)))))) =\n        Vint32 Int.zero \\/\n        val_inj\n          (bool_and\n             (val_inj\n                (notint\n                   (val_inj\n                      (if Int.eq v'58 ($ 0)\n                       then Some (Vint32 Int.one)\n                       else Some (Vint32 Int.zero)))))\n             (val_inj\n                (bool_or\n                   (val_inj\n                      (if Int.ltu ((x2<<ᵢ$ 3) +ᵢ  x5) (x >>ᵢ $ 8)\n                       then Some (Vint32 Int.one)\n                       else Some (Vint32 Int.zero)))\n                   (val_inj\n                      (if Int.eq ((x2<<ᵢ$ 3) +ᵢ  x5) (x >>ᵢ $ 8)\n                       then Some (Vint32 Int.one)\n                       else Some (Vint32 Int.zero)))))) = Vnull )\n(  H94 : val_inj\n          (notint\n             (val_inj\n                (if Int.eq v'58 ($ 0)\n                 then Some (Vint32 Int.one)\n                 else Some (Vint32 Int.zero)))) <> \n        Vint32 Int.zero /\\\n        val_inj\n          (notint\n             (val_inj\n                (if Int.eq v'58 ($ 0)\n                 then Some (Vint32 Int.one)\n                 else Some (Vint32 Int.zero)))) <> Vnull /\\\n        val_inj\n          (notint\n             (val_inj\n                (if Int.eq v'58 ($ 0)\n                 then Some (Vint32 Int.one)\n                 else Some (Vint32 Int.zero)))) <> Vundef )\n(  i_neq_zero : v'58 <> Int.zero )\n(  H18 : RL_Tbl_Grp_P v'60 (Vint32 v'58) )\n(  H1 : ECBList_P v'42 Vnull\n         (v'25 ++\n          ((V$ OS_EVENT_TYPE_MUTEX\n            :: Vint32 v'58\n               :: Vint32 x :: Vptr (v'52, $ 0) :: x3 :: v'46 :: nil,\n           v'60) :: nil) ++ v'26)\n         (v'27 ++ (DMutex (Vint32 x) (Vptr (v'52, $ 0)) :: nil) ++ v'28)\n         v'38 v'37 )\n(  H98 : tcblist_get (Vptr (v'91, Int.zero)) v'67\n          (v'33 ++\n           (x7\n            :: v'24\n               :: x15\n                  :: m\n                     :: V$ 0\n                        :: V$ OS_STAT_RDY\n                           :: Vint32 x6\n                              :: Vint32 (x6&ᵢ$ 7)\n                                 :: Vint32 (x6 >>ᵢ $ 3)\n                                    :: Vint32 ($ 1<<ᵢ(x6&ᵢ$ 7))\n                                       :: Vint32 ($ 1<<ᵢ(x6 >>ᵢ $ 3))\n                                          :: nil) :: v'35) =\n        Some\n          (v'80\n           :: v'81\n              :: v'82\n                 :: v'83\n                    :: v'84\n                       :: Vint32 v'85\n                          :: v'86 :: v'87 :: v'88 :: v'89 :: v'90 :: nil) /\\\n        struct_type_vallist_match OS_TCB_flag\n          (v'80\n           :: v'81\n              :: v'82\n                 :: v'83\n                    :: v'84\n                       :: Vint32 v'85\n                          :: v'86 :: v'87 :: v'88 :: v'89 :: v'90 :: nil) )\n(  H121 : RL_RTbl_PrioTbl_P\n           (update_nth_val (Z.to_nat (Int.unsigned v'74)) v'54\n              (Vint32 (Int.or v'92 v'76))) v'53 v'34 )\n(  v'30 : addrval)\n(  v'31 : val)\n(  v'36 : block)\n(  H118 : struct_type_vallist_match OS_EVENT\n           (V$ OS_EVENT_TYPE_MUTEX\n            :: Vint32 v'59\n               :: Vint32 x :: Vptr (v'52, $ 0) :: x3 :: v'46 :: nil) )\n(  H99 : array_type_vallist_match Int8u\n          (update_nth_val (Z.to_nat (Int.unsigned v'74)) v'60\n             (Vint32 (v'75&ᵢInt.not v'76))) )\n(  H101 : Some (Vint32 v'59) = Some v'31 )\n(  H108 : RL_Tbl_Grp_P\n           (update_nth_val (Z.to_nat (Int.unsigned v'74)) v'60\n              (Vint32 (v'75&ᵢInt.not v'76))) v'31)\n(  H109 : Some (V$ OS_EVENT_TYPE_MUTEX) = Some (V$ OS_EVENT_TYPE_MUTEX))\n(  H116 : Some (Vint32 x) = Some (Vint32 x))\n(  H117 : Some (Vptr (v'52, $ 0)) = Some (Vptr (v'52, $ 0)))\n(  H14 : id_addrval' (Vptr (v'36, Int.zero)) OSEventTbl OS_EVENT =\n        Some v'23 )\n(  H6 : EcbMod.joinsig (v'36, Int.zero)\n         (absmutexsem (x >>ᵢ $ 8)\n            (Some (v'52, $ 0, x&ᵢ$ OS_MUTEX_KEEP_LOWER_8)), w) v'48 v'49 )\n(  H2 : ECBList_P v'42 (Vptr (v'36, Int.zero)) v'25 v'27 v'47 v'37 )\n(  H5 : R_ECB_ETbl_P (v'36, Int.zero)\n         (V$ OS_EVENT_TYPE_MUTEX\n          :: Vint32 v'58\n             :: Vint32 x :: Vptr (v'52, $ 0) :: x3 :: v'46 :: nil, v'60)\n         v'37 )\n(  H123 : R_ECB_ETbl_P (v'36, Int.zero)\n           (V$ OS_EVENT_TYPE_MUTEX\n            :: Vint32 v'58\n               :: Vint32 x :: Vptr (v'52, $ 0) :: x3 :: v'46 :: nil,\n           v'60) v'37 )\n(  H119 : ptr_in_tcblist (Vptr (v'52, Int.zero)) v'67\n           (set_node (Vptr (v'91, Int.zero))\n              (v'80\n               :: v'81\n                  :: Vnull\n                     :: Vptr (v'36, Int.zero)\n                        :: Vint32 Int.zero\n                           :: Vint32 (v'85&ᵢInt.not ($ OS_STAT_MUTEX))\n                              :: v'86\n                                 :: v'87 :: v'88 :: v'89 :: v'90 :: nil)\n              v'67\n              (v'33 ++\n               (x7\n                :: v'24\n                   :: x15\n                      :: m\n                         :: V$ 0\n                            :: V$ OS_STAT_RDY\n                               :: Vint32 x6\n                                  :: Vint32 (x6&ᵢ$ 7)\n                                     :: Vint32 (x6 >>ᵢ $ 3)\n                                        :: Vint32 ($ 1<<ᵢ(x6&ᵢ$ 7))\n                                           :: Vint32\n                                              ($ 1<<ᵢ(x6 >>ᵢ $ 3))\n                                              :: nil) :: v'35)) )\n(  H100 : id_addrval' (Vptr (v'36, Int.zero)) OSEventTbl OS_EVENT =\n         Some v'30 )\n(  H_rgrp_le7 : Int.unsigned v'74 <= 7)\n( H_row_le7 : Int.unsigned v'73 <= 7 ),\n {|OS_spec, GetHPrio, OSLInv, I,\n   fun v : option val =>\n   ( <|| END v ||>  **\n    p_local OSLInv (v'52, Int.zero) init_lg **\n    ((EX v0 : val, LV pevent @ OS_EVENT ∗ |-> v0) **\n     (EX v0 : val, LV os_code_defs.x @ Int8u |-> v0) **\n     (EX v0 : val, LV pip @ Int8u |-> v0) **\n     (EX v0 : val, LV prio @ Int8u |-> v0) **\n     (EX v0 : val, LV legal @ Int8u |-> v0) ** Aemp) **\n    Aie true ** Ais nil ** Acs nil ** Aisr empisr) **\n   A_dom_lenv\n     ((pevent, OS_EVENT ∗)\n      :: (os_code_defs.x, Int8u)\n         :: (pip, Int8u) :: (prio, Int8u) :: (legal, Int8u) :: nil),\n   Afalse|}|- (v'52, Int.zero)\n   {{ <|| mutexpost (Vptr (v'36, Int.zero) :: nil) ||>  **\n     LV pevent @ OS_EVENT ∗ |-> Vptr (v'36, Int.zero) **\n     Astruct (v'36, Int.zero) OS_EVENT\n       (V$ OS_EVENT_TYPE_MUTEX\n        :: Vint32 v'59\n           :: Vint32\n                (Int.or (x&ᵢ$ OS_MUTEX_KEEP_UPPER_8) ((v'74<<ᵢ$ 3) +ᵢ  v'73))\n              :: nth_val' (Z.to_nat (Int.unsigned ((v'74<<ᵢ$ 3) +ᵢ  v'73)))\n                   v'53 :: x3 :: v'46 :: nil) **\n     Aarray v'30 (Tarray Int8u ∘ OS_EVENT_TBL_SIZE)\n       (update_nth_val (Z.to_nat (Int.unsigned v'74)) v'60\n          (Vint32 (v'75&ᵢInt.not v'76))) **\n     p_local OSLInv (v'52, Int.zero) init_lg **\n     Aie false **\n     Ais nil **\n     Acs (true :: nil) **\n     Aisr empisr **\n     A_isr_is_prop **\n     AOSUnMapTbl **\n     AOSMapTbl **\n     AOSRdyTblGrp\n       (update_nth_val (Z.to_nat (Int.unsigned v'74)) v'54\n          (Vint32 (Int.or v'92 v'76))) v'57 **\n     GAarray OSTCBPrioTbl (Tarray OS_TCB ∗ 64) v'53 **\n     tcbdllseg v'67 Vnull v'69 Vnull\n       (set_node (Vptr (v'91, Int.zero))\n          (v'80\n           :: v'81\n              :: Vnull\n                 :: Vptr (v'36, Int.zero)\n                    :: Vint32 Int.zero\n                       :: Vint32 (v'85&ᵢInt.not ($ OS_STAT_MUTEX))\n                          :: v'86 :: v'87 :: v'88 :: v'89 :: v'90 :: nil)\n          v'67\n          (v'33 ++\n           (x7\n            :: v'24\n               :: x15\n                  :: m\n                     :: V$ 0\n                        :: V$ OS_STAT_RDY\n                           :: Vint32 x6\n                              :: Vint32 (x6&ᵢ$ 7)\n                                 :: Vint32 (x6 >>ᵢ $ 3)\n                                    :: Vint32 ($ 1<<ᵢ(x6&ᵢ$ 7))\n                                       :: Vint32 ($ 1<<ᵢ(x6 >>ᵢ $ 3)) :: nil)\n           :: v'35)) **\n     LV prio @ Int8u |-> Vint32 ((v'74<<ᵢ$ 3) +ᵢ  v'73) **\n     LV os_code_defs.x @ Int8u |-> (V$ OS_STAT_MUTEX) **\n     LV legal @ Int8u |-> Vint32 x2 **\n     PV v'34 @ Int8u |-> v'32 **\n     GV OSTCBList @ OS_TCB ∗ |-> v'67 **\n     GV OSTCBCur @ OS_TCB ∗ |-r-> Vptr (v'52, Int.zero) **\n     LV pip @ Int8u |-> Vint32 (x >>ᵢ $ 8) **\n     GV OSEventList @ OS_EVENT ∗ |-> v'42 **\n     evsllseg v'42 (Vptr (v'36, Int.zero)) v'25 v'27 **\n     evsllseg v'46 Vnull v'26 v'28 **\n     tcbdllflag v'67\n       (v'33 ++\n        (x7\n         :: v'24\n            :: x15\n               :: m\n                  :: V$ 0\n                     :: V$ OS_STAT_RDY\n                        :: Vint32 x6\n                           :: Vint32 (x6&ᵢ$ 7)\n                              :: Vint32 (x6 >>ᵢ $ 3)\n                                 :: Vint32 ($ 1<<ᵢ(x6&ᵢ$ 7))\n                                    :: Vint32 ($ 1<<ᵢ(x6 >>ᵢ $ 3)) :: nil)\n        :: v'35) **\n     G& OSPlaceHolder @ Int8u == v'34 **\n     HECBList v'38 **\n     HTCBList v'37 **\n     HCurTCB (v'52, Int.zero) **\n     AOSEventFreeList v'3 **\n     AOSQFreeList v'4 **\n     AOSQFreeBlk v'5 **\n     AOSIntNesting **\n     AOSTCBFreeList v'21 v'22 **\n     AOSTime (Vint32 v'18) **\n     HTime v'18 **\n     AGVars **\n     atoy_inv' **\n     A_dom_lenv\n       ((pevent, OS_EVENT ∗)\n        :: (os_code_defs.x, Int8u)\n           :: (pip, Int8u) :: (prio, Int8u) :: (legal, Int8u) :: nil)}} \n   EXIT_CRITICAL;ₛ\n   OS_Sched (­);ₛ\n  RETURN ′ OS_NO_ERR {{Afalse}}.\nProof.\n  Set Printing Depth 999.\n  intros.\n\n  (*high level step*)\n  destruct H97.\n  unfolds in H50.\n  destruct H50.\n  assert (0 <= Int.unsigned ((v'74<<ᵢ$ 3) +ᵢ  v'73) < 64) as H_prio_range.\n  clear - H_rgrp_le7 H_row_le7.\n  mauto.\n\n  assert (nth_val ∘ (Int.unsigned ((v'74<<ᵢ$ 3) +ᵢ  v'73)) v'53 = Some (Vptr (v'91, Int.zero))).\n  eapply oscore_common.nth_val'2nth_val'; auto.\n\n  lets Hx: H50 H_prio_range H125 H97.\n  destruct Hx.\n  destruct H126.\n\n  lets Hx: tcbjoin_get_exists H126; destruct Hx.\n  lets Hx: post_exwt_succ_pre_mutex'' i_neq_zero H103 H104 H105 H96; eauto.\n  clear - H104 H115 H_rgrp_le7 H19.\n  assert (Z.to_nat (Int.unsigned v'74) < length v'60)%nat.\n  rewrite H19.\n  unfold OS_EVENT_TBL_SIZE.\n  mauto.\n  lets Hx: array_int8u_nth_lt_len H115 H; simpljoin1.\n  rewrite H104 in H0; inverts H0; auto.\n  lets Hx1: Hx H127; clear Hx.\n  simpljoin1.\n\n  assert (Int.eq x6 (x >>ᵢ $ 8) = false).\n  clear - H93.\n  destruct H93.\n  destruct (Int.eq x6 (x >>ᵢ $ 8)) eqn : eq1; tryfalse; auto.\n  destruct (Int.eq x6 (x >>ᵢ $ 8)) eqn : eq1; tryfalse; auto.\n  \n  hoare abscsq.\n  apply noabs_oslinv.\n  eapply absinfer_mutexpost_noreturn_exwt_succ; eauto.\n  go.\n  eapply EcbMod.join_get_r; eauto.\n  eapply EcbMod.join_get_l; eauto.\n  eapply EcbMod.get_sig_some.\n\n  eapply join_get_r.\n  auto.\n  eapply H32.\n  unfold TcbJoin in H70.\n  eapply join_get_l; eauto.\n  eapply get_sig_some.\n\n(*change the tcbdllseg in the post cond of OS_EventTaskRdy *)\n  assert ((((v'74<<ᵢ$ 3) +ᵢ  v'73) >>ᵢ $ 3) = v'74) as H_prio_shr3.\n  clear - H_rgrp_le7 H_row_le7.\n  mauto.\n  assert ((((v'74<<ᵢ$ 3) +ᵢ  v'73) &ᵢ$ 7) = v'73) as H_prio_and7.\n  clear - H_rgrp_le7 H_row_le7.\n  mauto.\n  assert (v'76 = ($ 1<<ᵢv'73)) as H_bitx_prop.\n  clear - H107 H_row_le7.\n  eapply math_mapval_core_prop; auto.\n  mauto.\n\n  hoare lift 19%nat pre.\n  eapply set_node_elim_hoare; eauto.\n  eapply TCBNode_P_set_rdy with (row := v'92); eauto.\n  rewrite H_prio_shr3.\n  eapply nth_val'2nth_val; eauto.\n  3: eapply TCBList_P_tcblist_get_TCBNode_P; eauto. \n  clear - H95 H112 H_rgrp_le7 H141.\n  assert (Z.to_nat (Int.unsigned v'74) < length v'54)%nat.\n  rewrite H141.\n  unfold OS_RDY_TBL_SIZE.\n  mauto.\n  lets Hx: array_int8u_nth_lt_len H112 H; simpljoin1.\n  rewrite H95 in H0; inverts H0; auto.\n\n  clear - H102.\n  simpl in H102; substs.\n  unfold OS_STAT_MUTEX, OS_STAT_MUTEX.\n  apply Int.and_not_self.\n  unfolds.\n  rewrite H_prio_shr3; rewrite H_prio_and7.\n  do 2 eexists.\n  splits; eauto.\n  rewrite H_bitx_prop; auto.\n  unfolds; simpl; auto.\n  (**)\n\n  (*EXIT_CRITICAL;ₛ*)\n  hoare forward prim.\n  remember (A_dom_lenv\n              ((pevent, OS_EVENT ∗)\n               :: (os_code_defs.x, Int8u) :: (pip, Int8u) :: (prio, Int8u) :: (legal, Int8u) :: nil)) in H116.\n  sep split in H116.\n  unfold AOSTCBList.\n  sep normal.\n  do 23 eexists.\n  sep cancel 1%nat 2%nat.\n  sep cancel 1%nat 3%nat.\n  do 2 sep cancel 18%nat 1%nat.\n  sep split.\n  6: eapply H128.\n  sep cancel AOSEventFreeList.\n  do 2 sep cancel 24%nat 1%nat.\n  sep cancel AOSMapTbl; sep cancel AOSUnMapTbl; sep cancel AOSIntNesting.\n  sep cancel AOSTCBFreeList; sep cancel AOSRdyTblGrp.\n  sep cancel AOSTime.\n  do 2 sep cancel 3%nat 5%nat.\n  sep cancel AGVars.\n  sep cancel p_local.\n  sep cancel A_isr_is_prop.\n  sep cancel atoy_inv'.\n  do 2 sep cancel 1%nat 3%nat.\n  unfold AOSTCBPrioTbl.\n  sep split; eauto.\n  sep cancel OSTCBPrioTbl.\n  sep cancel OSPlaceHolder.\n  sep normal.\n  eexists.\n  sep cancel 7%nat 1%nat.\n  sep lift 11%nat in H116.\n  sep lift 2%nat.\n  eapply tcbdllflag_set_node; eauto.\n  sep cancel 1%nat 1%nat.\n  unfold AECBList.\n  sep normal.\n  eexists.\n  sep cancel OSEventList.\n  sep split; eauto.\n  eapply evsllseg_compose; eauto.\n  instantiate (2 :=\n                 (V$ OS_EVENT_TYPE_MUTEX\n                   :: Vint32 v'59\n                   :: Vint32 (Int.or (x&ᵢ$ OS_MUTEX_KEEP_UPPER_8) ((v'74<<ᵢ$ 3) +ᵢ  v'73))\n                   :: nth_val' (Z.to_nat (Int.unsigned ((v'74<<ᵢ$ 3) +ᵢ  v'73))) v'53\n                   :: x3 :: v'46 :: nil)).\n  unfold V_OSEventListPtr; simpl; eauto.\n  sep cancel 8%nat 2%nat.\n  sep cancel 8%nat 2%nat.\n  instantiate (2 := DMutex (Vint32 (Int.or (x&ᵢ$ OS_MUTEX_KEEP_UPPER_8) ((v'74<<ᵢ$ 3) +ᵢ  v'73))) (Vptr (v'91, Int.zero)) ).\n  unfold AEventNode; unfold AOSEvent; unfold AEventData; unfold AOSEventTbl.\n  unfold node.\n  sep normal.\n  do 3 eexists.\n  sep split; eauto.\n  sep cancel 2%nat 1%nat.\n  sep cancel 2%nat 1%nat.\n  rewrite Heqa in H116.\n  exact H116.\n  unfolds; simpl.\n  rewrite H96; auto.\n  split; auto.\n  rewrite H96.\n  clear - H118 H_rgrp_le7 H_row_le7 H133 H134 H10.\n  simpl in H118.\n  simpl.\n  simpljoin1; splits; auto.\n  remember ((v'74<<ᵢ$ 3) +ᵢ  v'73).\n  clear Heqi.\n  clear - H134 H10.\n  lets Hx: mund_int_c1 H134 H10.\n  rewrite Zle_imp_le_bool; auto.\n\n  rewrite H96.\n  eapply ecblist_p_post_exwt_hold_mutex_new; eauto.\n  rewrite H61 in H103.\n  inverts H103.\n  rewrite H63 in H104.\n  inverts H104.\n  rewrite H66 in H105.\n  inverts H105.\n  eapply zh_asdf.\n  clear - H68 i_neq_zero.\n  assert (Int.eq v'58 ($ 0) = false).\n  eapply Int.eq_false; auto.\n  rewrite H in H68.\n  auto.\n  clear - H104 H115 H_rgrp_le7 H19.\n  assert (Z.to_nat (Int.unsigned v'74) < length v'60)%nat.\n  rewrite H19.\n  unfold OS_EVENT_TBL_SIZE.\n  mauto.\n  lets Hx: array_int8u_nth_lt_len H115 H; simpljoin1.\n  rewrite H104 in H0; inverts H0; auto.\n\n  clear - H107 H_row_le7.\n  assert (Z.to_nat (Int.unsigned v'73) < 8)%nat.\n  mauto.\n  lets Hx: OSMapVallist_bound H; auto.\n  simpljoin1.\n  rewrite H107 in H0; inverts H0; auto.\n  unfolds; simpl; auto.\n  clear - H50 H96 H97 H122 H133 H134.\n  assert (nth_val (Z.to_nat (Int.unsigned ((v'74<<ᵢ$ 3) +ᵢ  v'73))) v'53 = Some (Vptr (v'91, Int.zero))).\n  eapply oscore_common.nth_val'2nth_val'; auto.\n  apply H50 in H; auto.\n  do 2 destruct H.\n  eapply r_priotbl_p_set_hold; eauto.\n  lets Hx: Pos.eq_dec v'52 v'91.\n  destruct Hx.\n  substs.\n  eapply OSMutex_common.return_rh_ctcb.\n  eapply rh_curtcb_set_nct; auto.\n  intro; apply n; inverts H144; auto.\n  unfolds in H131; simpljoin1.\n  lets Hx: rh_tcblist_ecblist_p_post_exwt_aux_mbox H7 H17 H6 H131 H126.\n  auto.\n  destruct Hx; substs.\n  eapply rh_tcblist_ecblist_p_post_exwt_mutex; eauto.\n  rewrite H_prio_shr3 in H143.\n  rewrite H_prio_and7 in H143.\n  rewrite H_bitx_prop.\n  auto.\n  rewrite H_prio_shr3 in H142.\n  rewrite H_prio_and7 in H142.\n  rewrite H_bitx_prop.\n  auto.\n  auto.\n  go.\n\n  (*OS_Sched (­);ₛ*)\n  hoare forward.\n  sep normal.\n  do 2 eexists.\n  remember (A_dom_lenv\n              ((pevent, OS_EVENT ∗)\n               :: (os_code_defs.x, Int8u) :: (pip, Int8u) :: (prio, Int8u) :: (legal, Int8u) :: nil)) in H116.\n  sep split in H116.\n  sep split; eauto.\n  sep cancel p_local.\n  rewrite Heqa in H116.\n  exact H116.\n  unfolds; auto.\n  go.\n  intros.\n  do 2 destruct H116.\n  exists init_lg.\n  sep cancel p_local.\n  sep auto.\n  intros.\n  do 2 destruct H116.\n  exists (logic_val x20 :: nil).\n  sep cancel p_local.\n  sep auto.\n\n  (*RETURN ′ OS_NO_ERR*)\n  unfold OS_SchedPost.\n  simpl getasrt.\n  unfold OS_SchedPost'.\n  hoare forward.\n  sep normal.\n  do 5 eexists.\n  sep split in H116.\n  sep split; eauto.\n  sep cancel pevent.\n  sep cancel p_local.\n  sep cancel legal.\n  sep cancel prio.\n  sep cancel pip.\n  eapply H116.\n  inverts H117.\n  auto.\nQed.\n", "meta": {"author": "brightfu", "repo": "CertiuCOS2", "sha": "1b7e588056a23bc32a9e442a240de3002b16eefb", "save_path": "github-repos/coq/brightfu-CertiuCOS2", "path": "github-repos/coq/brightfu-CertiuCOS2/CertiuCOS2-1b7e588056a23bc32a9e442a240de3002b16eefb/coqimp/certiucos/proofs/mutex/OSMutexPost_tozh_1.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.34158250614097546, "lm_q1q2_score": 0.20244454251836208}}
{"text": "Require Import Bool List String PeanoNat.\nRequire Import Common FMap ListSupport Syntax Semantics StepM SemFacts.\nRequire Import Invariant Serial SerialFacts.\n\nRequire Import Lia.\n\nSet Implicit Arguments.\n\nSection TrsInv.\n  Context `{dv: DecValue} `{oifc: OStateIfc}.\n\n  Variables (impl: System)\n            (ginv: State -> Prop).\n\n  Definition Invariant := @Invariant (State).\n  Definition InvInit := @InvInit (System) (State) _ impl ginv.\n\n  Definition InvTrs :=\n    forall ist1,\n      Reachable (steps step_m) impl ist1 ->\n      ginv ist1 ->\n      forall hst ist2,\n        trsSteps impl ist1 hst ist2 ->\n        ginv ist2.\n\n  Definition InvSeq :=\n    forall ist1,\n      Reachable (steps step_m) impl ist1 ->\n      ginv ist1 ->\n      forall hst ist2,\n        seqSteps impl ist1 hst ist2 ->\n        ginv ist2.\n\n  Hypotheses (Hinvi: InvInit)\n             (Hinvt: InvTrs).\n\n  Lemma inv_trs_seqSteps':\n    forall ist1,\n      Reachable (steps step_m) impl ist1 ->\n      ginv ist1 ->\n      forall ihst ist2,\n        seqSteps impl ist1 ihst ist2 ->\n        ginv ist2.\n  Proof.\n    intros.\n    destruct H1; destruct H2 as [trss ?].\n    destruct H2; subst.\n\n    generalize dependent ist2; generalize dependent ist1.\n    induction trss; simpl; intros.\n    - inv H1; assumption.\n    - eapply steps_split in H1; [|reflexivity].\n      destruct H1 as [sti [? ?]].\n      inv H2.\n      eapply Hinvt with (ist1:= sti); eauto.\n      + eapply reachable_steps; eauto.\n      + split; eauto.\n  Qed.\n\n  Lemma inv_trs_seqSteps: InvSeq.\n  Proof.\n    unfold InvSeq; intros.\n    eapply inv_trs_seqSteps'; eauto.\n  Qed.\n\nEnd TrsInv.\n\nSection AtomicInv.\n  Context `{dv: DecValue} `{oifc: OStateIfc}.\n\n  Variables (impl: System)\n            (ginv: State -> Prop)\n            (ainv: list (Id Msg) (* inits *) ->\n                   State (* starting state *) ->\n                   History (* atomic history *) ->\n                   list (Id Msg) (* eouts *) ->\n                   State (* ending state *) -> Prop).\n\n  Definition InvTrsIns :=\n    forall ist1,\n      Reachable (steps step_m) impl ist1 ->\n      ginv ist1 ->\n      forall eins ist2,\n        step_m impl ist1 (RlblIns eins) ist2 ->\n        ginv ist2.\n\n  Definition InvTrsOuts :=\n    forall ist1,\n      Reachable (steps step_m) impl ist1 ->\n      ginv ist1 ->\n      forall eouts ist2,\n        step_m impl ist1 (RlblOuts eouts) ist2 ->\n        ginv ist2.\n\n  Definition InvTrsAtomic :=\n    forall ist1,\n      Reachable (steps step_m) impl ist1 ->\n      ginv ist1 ->\n      forall inits hst eouts ist2,\n        ExtAtomic impl inits hst eouts ->\n        steps step_m impl ist1 hst ist2 ->\n        ainv inits ist1 hst eouts ist2 /\\ ginv ist2.\n\n  Hypotheses (Hinvi: InvInit impl ginv)\n             (Hinvti: InvTrsIns)\n             (Hinvto: InvTrsOuts)\n             (Hinvta: InvTrsAtomic).\n\n  Lemma inv_atomic_InvTrs:\n    InvTrs impl ginv.\n  Proof.\n    red; intros.\n    destruct H1.\n    inv H2.\n    - inv_steps; inv_step; assumption.\n    - inv_steps; eapply Hinvti; eauto.\n    - inv_steps; eapply Hinvto; eauto.\n    - eapply Hinvta; eauto.\n  Qed.\n\nEnd AtomicInv.\n\nTheorem invSeq_serializable_invStep:\n  forall `{dv: DecValue} `{oifc: OStateIfc} (impl: System) ginv,\n    InvInit impl ginv ->\n    InvSeq impl ginv ->\n    SerializableSys impl ->\n    InvStep impl step_m ginv.\nProof.\n  unfold InvInit, InvSeq, SerializableSys, InvStep, Invariant.InvStep.\n  intros.\n  assert (Reachable (steps step_m) impl ist2).\n  { eapply reachable_steps; [eassumption|].\n    apply steps_singleton; eassumption.\n  }\n  specialize (H1 _ H5).\n  red in H1; destruct H1 as [sll ?].\n  eapply H0; [| |eassumption]; auto.\n  apply reachable_init.\nQed.\n", "meta": {"author": "mit-plv", "repo": "hemiola", "sha": "1984b4de903259ce2d7abda737e76e16e6436dee", "save_path": "github-repos/coq/mit-plv-hemiola", "path": "github-repos/coq/mit-plv-hemiola/hemiola-1984b4de903259ce2d7abda737e76e16e6436dee/src/System/TrsInv.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.20244453060103684}}
{"text": "From isla Require Import opsem.\n\nDefinition instr_ldr : isla_trace :=\n  AssumeReg \"HCR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x80000000%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL3\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL2\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL1\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"CFG_ID_AA64PFR0_EL1_EL0\" [] (RegVal_Base (Val_Bits (BV 4%N 0x1%Z))) Mk_annot :t:\n  AssumeReg \"TCR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"EDSCR\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"OSDLR_EL1\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"OSLSR_EL1\" [] (RegVal_Base (Val_Bits (BV 32%N 0x0%Z))) Mk_annot :t:\n  Smt (DeclareConst 6%Z (Ty_BitVec 1%N)) Mk_annot :t:\n  AssumeReg \"PSTATE\" [Field \"EL\"] (RegVal_Base (Val_Bits (BV 2%N 0x2%Z))) Mk_annot :t:\n  AssumeReg \"PSTATE\" [Field \"nRW\"] (RegVal_Base (Val_Bits (BV 1%N 0x0%Z))) Mk_annot :t:\n  AssumeReg \"SCR_EL3\" [] (RegVal_Base (Val_Bits (BV 32%N 0x501%Z))) Mk_annot :t:\n  AssumeReg \"SCTLR_EL2\" [] (RegVal_Base (Val_Bits (BV 64%N 0x4000002%Z))) Mk_annot :t:\n  Smt (DeclareConst 29%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  Assume (AExp_Binop (Eq) (AExp_Manyop (Bvmanyarith Bvand) [AExp_Val (AVal_Var \"R1\" []) Mk_annot; AExp_Val (AVal_Bits (BV 64%N 0xfff0000000000007%Z)) Mk_annot] Mk_annot) (AExp_Val (AVal_Bits (BV 64%N 0x0%Z)) Mk_annot) Mk_annot) Mk_annot :t:\n  ReadReg \"R1\" [] (RegVal_Base (Val_Symbolic 29%Z)) Mk_annot :t:\n  Smt (DefineConst 118%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 29%Z) Mk_annot; Val (Val_Bits (BV 64%N 0x0%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n  Smt (DefineConst 122%Z (Binop (Eq) (Val (Val_Symbolic 118%Z) Mk_annot) (Manyop (Bvmanyarith Bvand) [Val (Val_Symbolic 118%Z) Mk_annot; Val (Val_Bits (BV 64%N 0xfffffffffffffff8%Z)) Mk_annot] Mk_annot) Mk_annot)) Mk_annot :t:\n  ReadReg \"PSTATE\" [Field \"D\"] (RegVal_Struct [(\"D\", RegVal_Base (Val_Symbolic 6%Z))]) Mk_annot :t:\n  Smt (DeclareConst 2317%Z (Ty_BitVec 56%N)) Mk_annot :t:\n  Smt (DefineConst 2326%Z (Unop (ZeroExtend 8%N) (Manyop Concat [Val (Val_Bits (BV 4%N 0x0%Z)) Mk_annot; Unop (Extract 51%N 0%N) (Val (Val_Symbolic 118%Z) Mk_annot) Mk_annot] Mk_annot) Mk_annot)) Mk_annot :t:\n  Smt (DeclareConst 2327%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadMem (RegVal_Base (Val_Symbolic 2327%Z)) (RegVal_Base (Val_Enum ((Mk_enum_id 6%nat), Mk_enum_ctor 0%nat))) (RegVal_Base (Val_Symbolic 2326%Z)) 8%N None Mk_annot :t:\n  Smt (DefineConst 2331%Z (Val (Val_Symbolic 2327%Z) Mk_annot)) Mk_annot :t:\n  WriteReg \"R0\" [] (RegVal_Base (Val_Symbolic 2331%Z)) Mk_annot :t:\n  Smt (DeclareConst 2332%Z (Ty_BitVec 64%N)) Mk_annot :t:\n  ReadReg \"_PC\" [] (RegVal_Base (Val_Symbolic 2332%Z)) Mk_annot :t:\n  Smt (DefineConst 2333%Z (Manyop (Bvmanyarith Bvadd) [Val (Val_Symbolic 2332%Z) Mk_annot; Val (Val_Bits (BV 64%N 0x4%Z)) Mk_annot] Mk_annot)) Mk_annot :t:\n  WriteReg \"_PC\" [] (RegVal_Base (Val_Symbolic 2333%Z)) Mk_annot :t:\n  tnil\n.\n", "meta": {"author": "rems-project", "repo": "islaris", "sha": "fcc5791c74a2f791dee9080263cd64e42e73bc39", "save_path": "github-repos/coq/rems-project-islaris", "path": "github-repos/coq/rems-project-islaris/islaris-fcc5791c74a2f791dee9080263cd64e42e73bc39/instructions/instr_ldr.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.20241634696548919}}
{"text": "From RecordUpdate Require Import RecordSet.\nFrom aneris.aneris_lang Require Import network resources.\nFrom aneris.aneris_lang.lib.serialization Require Import serialization_proof.\n\nDefinition Key := string.\n\n(** Arguments that user supplies to the interface *)\n\nClass DB_params := {\n  DB_addresses : list socket_address; (* can we remove it ? *)\n  DB_addresses_NoDup : NoDup DB_addresses;\n  DB_keys : gset Key;\n  DB_InvName : namespace; (* Global Invariant *)\n  DB_serialization : serialization;\n}.\n\nNotation DB_Serializable v := (Serializable DB_serialization v).\n\nRecord SerializableVal `{!DB_params} :=\n  SerVal {SV_val : val;\n          SV_ser : DB_Serializable SV_val }.\n\nCoercion SV_val : SerializableVal >-> val.\n\nExisting Instance SV_ser.\n\nArguments SerVal {_} _ {_}.\n", "meta": {"author": "logsem", "repo": "aneris", "sha": "9783addaeff0d32fbb0ded945bfb98cdc6ef21d1", "save_path": "github-repos/coq/logsem-aneris", "path": "github-repos/coq/logsem-aneris/aneris-9783addaeff0d32fbb0ded945bfb98cdc6ef21d1/aneris/examples/dscm/spec/base.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.20229668914636834}}
{"text": "Set Implicit Arguments.\nRequire Import HJ.Tid.\nRequire Import HJ.Vars.\nRequire Import HJ.Phasers.Regmode.\nRequire Import HJ.Phasers.Phaser.\nRequire Import Coq.Lists.SetoidList.\n\n(** This chapter defines a deadlock-free phaser language. A [phasermap] represents\nall phasers available for a set of tasks. A phasermap is a map from phaser handles [phid]\ninto phasers. *)\n\nDefinition phasermap := Map_PHID.t phaser.\n\n(** Function [make] creates an empty phasermap. *)\n\nDefinition make : phasermap := Map_PHID.empty phaser.\n\n(**\n  We now define phasermap operations, first with a pre-condition and\n  then a function that executes the operation.\n  *)\n\nRecord Op := mk_op {\n  can_run: tid -> phasermap -> Prop;\n  run: tid -> phasermap -> phasermap\n}.\n\n(**\n  Function [new_phaser] places a new empty phaser in the phasermap.\n  The pre-condition is that [p] is not in phasermap [m]. *)\n\nInductive PhNewPre p (t:tid) (m:phasermap) : Prop :=\n  ph_new_pre:\n    ~ Map_PHID.In p m ->\n    PhNewPre p t m.\n\nDefinition ph_new (p:phid) (t:tid) : phasermap -> phasermap := Map_PHID.add p (Phaser.make t).\n\nDefinition ph_new_op p := mk_op (PhNewPre p) (ph_new p).\n\n(**\n  Function [update] mutates the phaser associated to [p] by applying\n  parameter [f] to the phaser.\n *)\n\nDefinition update p (f:phaser -> phaser) m : phasermap := \nmatch Map_PHID.find p m with\n| Some ph => Map_PHID.add p (f ph) m\n| None => m\nend.\n\n(**\n  Signal applies the phaser-signal to the phaser associated with [p].\n  The pre-condition is that [p] must be in the phasermap and\n  we must meet the pre-conditions of the phaser-signal.\n  *)\n\nInductive PhSignalPre p t m : Prop :=\n  ph_signal_pre:\n    forall ph,\n    Map_PHID.MapsTo p ph m ->\n    SignalPre t ph ->\n    PhSignalPre p t m.\n\nDefinition ph_signal p t := update p (Phaser.signal t).\n\nDefinition ph_signal_op p := mk_op (PhSignalPre p) (ph_signal p).\n\n(** Droping a phaser has a similar implementation and pre-conditions. *)\n\nInductive PhDropPre p t m : Prop :=\n  ph_drop_pre:\n    forall ph,\n    Map_PHID.MapsTo p ph m ->\n    DropPre t ph ->\n    PhDropPre p t m.\n\nDefinition ph_drop p t := update p (Phaser.drop t).\n\nDefinition ph_drop_op p := mk_op (PhDropPre p) (ph_drop p).\n\n(**\n  We now introduce functions that act on all phasers the task is regitered  with.\n  Function [foreach] updates all phasers in the phasermap by applying function [f].\n  *)\n\nDefinition foreach (f:phaser -> phaser) : phasermap -> phasermap :=\nMap_PHID.mapi (fun _ ph => f ph).\n\n(** Function [signal_all] lets task [t] perform a [Phaser.signal] on all phasers\n    it is registered with. There are no pre-conditions to this operation. *)\n\nDefinition signal_all (t:tid) := foreach (Phaser.try_signal t).\n\nDefinition signal_all_op := mk_op (fun _ _ => True) signal_all.\n\n(**\n  Wait-all invokes a wait on every phaser the task is registered with.\n  The pre-condition of wait-all is the pre-condition of each phaser the\n  task is registered with. *)\n\nInductive WaitAllPre t m : Prop :=\n  wait_all_pre:\n    (forall p ph, Map_PHID.MapsTo p ph m -> Map_TID.In t ph -> TryWaitPre t ph) ->\n    WaitAllPre t m.\n\nDefinition wait_all (t:tid) := foreach (Phaser.wait t).\n\nDefinition wait_all_op := mk_op WaitAllPre wait_all.\n\n(**\n  Function [drop_all] deregisters task [t] from all phasers in the phasermap; it\n  has no pre-conditions.\n  *)\n\nDefinition drop_all (t:tid) := foreach (Phaser.drop t).\n\nDefinition drop_all_op := mk_op (fun _ _ => True) drop_all.\n\n(**\n  Finally, we define async. To be able to spawn a task we must ensure\n  that the spawned task name is unknown in all phasers, so we need to\n  define a task membership for phasermaps.\n  Predicate [In t m] holds when task [t] is registered in a phaser of [m]. *)\n\nInductive In (t:tid) (pm:phasermap) : Prop :=\n  in_def:\n    forall p ph,\n    Map_PHID.MapsTo p ph pm ->\n    Map_TID.In t ph ->\n    In t pm.\n\nInductive Nonempty (pm:phasermap) : Prop :=\n| nonempty_def:\n  forall x,\n  In x pm ->\n  Nonempty pm.\n\nDefinition Empty (pm:phasermap) : Prop := forall x, ~ In x pm.\n\n(** The parameter of a phased async is list of pairs, each of which\n  consists of a phaser name and a registration  mode. *)\n\nRecord phased := mk_phased {\n  get_args : Map_PHID.t regmode;\n  get_new_task : tid\n}.\n\n(** \n  Async phased register a new task in a list of [phased].\n  Function [async_1] registers task [t] with phaser named by [p] according\n  to mode [r].\n  *)\n\nDefinition async_1 (ps:phased) t p ph : phaser :=\nmatch Map_PHID.find p (get_args ps) with\n| Some r => register (mk_registry (get_new_task ps) r) t ph\n| _ => ph\nend.\n\nDefinition async ps t : phasermap -> phasermap := Map_PHID.mapi (async_1 ps t).\n\n(**\n  Predicate [PhasedPre] ensures that task [t] can register task [t']\n  using the phased object [ps].\n   *)\n\nInductive PhasedPre (ps:phased) (t:tid) pm : Prop := \n  phased_pre_def:\n    (forall p m,\n      Map_PHID.MapsTo p m (get_args ps) -> \n      exists ph, Map_PHID.MapsTo p ph pm /\\ RegisterPre (mk_registry (get_new_task ps) m) t ph) ->\n    PhasedPre ps t pm.\n\n(**\n  The pre-condition of executing an async are three:\n  (i) all phased pairs in [ps] must meet the preconditions of [PhasedPre],\n  (ii) the spawned task [t'] cannot be known in the phasermap.\n  *)\n\nInductive AsyncPre (ps:phased) t m : Prop :=\n  async_pre:\n    PhasedPre ps t m ->\n    ~ In (get_new_task ps) m -> \n    AsyncPre ps t m.\n\nDefinition async_op (ps:phased) := mk_op (AsyncPre ps) (async ps).\n\n(**\n  We are now ready to define the closed set of operations on phasermaps.\n *)\n\nInductive op : Type :=\n| PH_NEW : phid -> op\n| PH_SIGNAL : phid -> op\n| PH_DROP : phid -> op\n| SIGNAL_ALL\n| WAIT_ALL\n| DROP_ALL\n| ASYNC : phased -> op.\n  \n(** Function [get_impl] yields the [Op] object. *)\n\nDefinition get_impl o :=\nmatch o with\n| PH_NEW p => ph_new_op p\n| PH_SIGNAL p => ph_signal_op p\n| PH_DROP p => ph_drop_op p\n| SIGNAL_ALL => signal_all_op\n| WAIT_ALL => wait_all_op\n| DROP_ALL => drop_all_op\n| ASYNC ps => async_op ps\nend.\n\n(** In closing, we define the [Reduces] relation. *)\n\nInductive Reduces m t o : phasermap -> Prop :=\n  reduces:\n    can_run (get_impl o) t m ->\n    Reduces m t o (run (get_impl o) t m).\n\nModule Trace.\n  Definition t := (list (tid * op)) % type.\n\n  Inductive ReducesN: phasermap -> t -> Prop :=\n  | reduces_n_nil:\n    ReducesN make nil\n  | reduces_n_cons:\n    forall t l o pm pm',\n    ReducesN pm l ->\n    Reduces pm t o pm' ->\n    ReducesN pm' ((t,o)::l).\nEnd Trace.\n\nSection Facts.\n\n  Let update_rw:\n    forall p f ph m,\n    Map_PHID.MapsTo p ph m ->\n    update p f m = Map_PHID.add p (f ph) m.\n  Proof.\n    intros.\n    unfold update.\n    remember (Map_PHID.find _ _) as o.\n    symmetry in Heqo.\n    destruct o.\n    - rewrite <- Map_PHID_Facts.find_mapsto_iff in Heqo.\n      assert (p0 = ph) by eauto using Map_PHID_Facts.MapsTo_fun.\n      subst.\n      trivial.\n    - rewrite <- Map_PHID_Facts.not_find_in_iff in Heqo.\n      contradiction Heqo.\n      eauto using Map_PHID_Extra.mapsto_to_in.\n  Qed.\n\n  Lemma ph_signal_rw:\n    forall p t ph m,\n    Map_PHID.MapsTo p ph m ->\n    ph_signal p t m = Map_PHID.add p (Phaser.signal t ph) m.\n  Proof.\n    intros.\n    unfold ph_signal.\n    rewrite update_rw with (ph:=ph); auto.\n  Qed.\n\n  Lemma ph_drop_rw:\n    forall p t ph m,\n    Map_PHID.MapsTo p ph m ->\n    ph_drop p t m = Map_PHID.add p (Phaser.drop t ph) m.\n  Proof.\n    intros.\n    unfold ph_drop.\n    rewrite update_rw with (ph:=ph); auto.\n  Qed.\n\n  Lemma foreach_mapsto_rw:\n    forall p ph f m,\n    Map_PHID.MapsTo p ph (foreach f m) <->\n    exists ph', ph = f ph' /\\ Map_PHID.MapsTo p ph' m.\n  Proof.\n    intros.\n    unfold foreach in *.\n    rewrite Map_PHID_Facts.mapi_mapsto_iff; auto.\n    split; eauto.\n  Qed.\n\n  Lemma async_simpl_notin:\n    forall p (ps:phased) ph t,\n    ~ Map_PHID.In p (get_args ps) ->\n    async_1 ps t p ph = ph.\n  Proof.\n    intros.\n    unfold async_1.\n    destruct (Map_PHID_Extra.find_rw p (get_args ps)) as [(R,?)|(r,(R,?))].\n    - rewrite R; clear R.\n      trivial.\n    - contradiction H.\n      eauto using Map_PHID_Extra.mapsto_to_in.\n  Qed.\n\n  Lemma async_1_rw:\n    forall ps t p ph,\n      { exists r, Map_PHID.MapsTo p r (get_args ps) /\\ async_1 ps t p ph = register (mk_registry (get_new_task ps) r) t ph }\n      +\n      { async_1 ps t p ph = ph /\\ ~ Map_PHID.In p (get_args ps)}.\n  Proof.\n    intros.\n    unfold async_1.\n    destruct (Map_PHID_Extra.find_rw p (get_args ps)).\n    - right.\n      destruct a as (R,?).\n      rewrite R.\n      intuition.\n    - left.\n      destruct e as (r,(R,?)).\n      rewrite R.\n      eauto.\n  Qed.\n\n  Lemma async_1_mapsto_neq:\n    forall t' v ps t p ph,\n    t' <> (get_new_task ps) ->\n    Map_TID.MapsTo t' v (async_1 ps t p ph) ->\n    Map_TID.MapsTo t' v ph.\n  Proof.\n    intros.\n    unfold async_1 in *.\n    destruct (Map_PHID_Extra.find_rw p (get_args ps)) as [(R,?)|(r,(R,?))]. {\n      rewrite R in *; clear R.\n      assumption.\n    }\n    rewrite R in *; clear R.\n    eauto using register_mapsto_neq.\n  Qed.\n\n  Lemma async_1_mapsto_eq:\n    forall v ps t p ph r,\n    Map_TID.In t ph ->\n    Map_PHID.MapsTo p r (get_args ps) ->\n    Map_TID.MapsTo (get_new_task ps) v (async_1 ps t p ph) ->\n    exists v', Map_TID.MapsTo t v' ph /\\ v = Taskview.set_mode v' r.\n  Proof.\n    intros.\n    unfold async_1 in *.\n    destruct (Map_PHID_Extra.find_rw p (get_args ps)) as [(R,?)|(r',(R,?))]. {\n      (* absurd *)\n      rewrite R in *; clear R.\n      contradiction H2.\n      eauto using Map_PHID_Extra.mapsto_to_in.\n    }\n    rewrite R in *; clear R.\n    assert (r' = r) by eauto using Map_PHID_Facts.MapsTo_fun; subst; clear H2.\n    eauto using register_mapsto_eq.\n  Qed.\n\n  Lemma async_1_mapsto:\n    forall p ph ps t' t v,\n    Map_TID.MapsTo t' v (async_1 ps t p ph) ->\n    Map_TID.MapsTo t' v ph \\/\n    (exists v' r, Map_TID.MapsTo t v' ph /\\ Map_PHID.MapsTo p r (get_args ps) /\\\n    v = Taskview.set_mode v' r).\n  Proof.\n    intros.\n    destruct (async_1_rw ps t p ph) as [(r,(i,R))|(R1,R2)]. {\n      rewrite R in *; clear R.\n      apply register_inv_mapsto in H.\n      destruct H; auto.\n      destruct H as (?, (v', (mt2, ?))).\n      subst.\n      right.\n      eauto.\n    }\n    left.\n    rewrite R1 in *; clear R1.\n    auto.\n  Qed.\n\n  Lemma async_mapsto_rw:\n    forall p ph ps t m,\n    Map_PHID.MapsTo p ph (async ps t m) <->\n    exists ph', ph = async_1 ps t p ph' /\\ Map_PHID.MapsTo p ph' m.\n  Proof.\n    intros.\n    unfold async in *.\n    rewrite Map_PHID_Facts.mapi_mapsto_iff; auto.\n    split; eauto.\n    intros.\n    subst.\n    trivial.\n  Qed.\n\n  Lemma async_notina_mapsto:\n    forall p ps m t ph,\n    ~ Map_PHID.In p (get_args ps) ->\n    Map_PHID.MapsTo p ph m ->\n    Map_PHID.MapsTo p ph (async ps t m).\n  Proof.\n    intros.\n    apply async_mapsto_rw.\n    exists ph.\n    intuition.\n    symmetry.\n    eauto using async_simpl_notin.\n  Qed.\n\n  Lemma async_notina_mapsto_rtl:\n    forall p ps m t ph,\n    ~ Map_PHID.In p (get_args ps) ->\n    Map_PHID.MapsTo p ph (async ps t m) ->\n    Map_PHID.MapsTo p ph m.\n  Proof.\n    intros.\n    apply async_mapsto_rw in H0.\n    destruct H0 as (ph', (R, mt)).\n    rewrite R in *.\n    apply async_simpl_notin with (ph:=ph') (t:=t) in H.\n    rewrite H.\n    assumption.\n  Qed.\n\n  Lemma ph_new_impl_mapsto:\n    forall p t pm,\n    Map_PHID.MapsTo p (Phaser.make t) (ph_new p t pm).\n  Proof.\n    intros.\n    unfold ph_new.\n    auto using Map_PHID.add_1.\n  Qed.\n\n  Lemma async_pre_to_in_ph:\n    forall ps t pm r ph p,\n    AsyncPre ps t pm ->\n    Map_PHID.MapsTo p r (get_args ps) ->\n    Map_PHID.MapsTo p ph pm ->\n    Map_TID.In t ph.\n  Proof.\n    intros.\n    inversion H as [Hx].\n    inversion Hx.\n    specialize (H3 _ _ H0).\n    destruct H3 as (ph', (?, Hr)).\n    assert (ph' = ph) by eauto using Map_PHID_Facts.MapsTo_fun; subst.\n    eauto using Phaser.register_pre_to_in.\n  Qed.\nEnd Facts.\n\nSection Decidability.\n  Ltac handle_not := right; unfold not; intros N; inversion N; contradiction; fail.\n  Lemma ph_new_pre_dec p t pm:\n    { PhNewPre p t pm } + { ~ PhNewPre p t pm }.\n  Proof.\n    destruct (Map_PHID_Facts.In_dec pm p); try handle_not.\n    auto using ph_new_pre.\n  Defined.\n  \n  Lemma ph_signal_pre_dec p t pm:\n    { PhSignalPre p t pm } + { ~ PhSignalPre p t pm }.\n  Proof.\n    destruct (Map_PHID_Extra.lookup_dec phid_eq_rw p pm) as [(ph,mt)|(_,?)]. {\n      destruct (signal_pre t ph). {\n        eauto using ph_signal_pre.\n      }\n      right.\n      unfold not; intros N.\n      inversion N.\n      assert (ph0 = ph) by eauto using Map_PHID_Facts.MapsTo_fun; subst.\n      contradiction.\n    }\n    right.\n    unfold not; intros N.\n    inversion N.\n    apply Map_PHID_Extra.mapsto_to_in in H.\n    contradiction.\n  Defined.\n\n  Lemma ph_drop_pre_dec p t pm:\n    { PhDropPre p t pm } + { ~ PhDropPre p t pm }.\n  Proof.\n    destruct (Map_PHID_Extra.lookup_dec phid_eq_rw p pm) as [(ph,mt)|(_,?)]. {\n      destruct (drop_pre t ph). {\n        eauto using ph_drop_pre.\n      }\n      right.\n      unfold not; intros N.\n      inversion N.\n      assert (ph0 = ph) by eauto using Map_PHID_Facts.MapsTo_fun; subst.\n      contradiction.\n    }\n    right.\n    unfold not; intros N.\n    inversion N.\n    apply Map_PHID_Extra.mapsto_to_in in H.\n    contradiction.\n  Defined.\n\n  Definition phased_pre_dec ps t (pm:phasermap):\n    { PhasedPre ps t pm } + { ~ PhasedPre ps t pm }.\n  Proof.\n    remember (forallb (fun kv => \n      match Map_PHID.find (fst kv) pm with\n      | Some ph =>\n        if register_pre {| get_task := get_new_task ps; get_mode := (snd kv) |} t ph\n        then true else false\n      | _ => false\n      end\n    ) (Map_PHID.elements (get_args ps))).\n    symmetry in Heqb.\n    destruct b. {\n      left.\n      apply phased_pre_def.\n      intros.\n      rewrite forallb_forall in *.\n      specialize Heqb with (p, m).\n      rewrite <- Map_PHID_Extra.maps_to_iff_in_elements in Heqb; auto using phid_eq_rw.\n      specialize (Heqb H).\n      simpl in *.\n      destruct (Map_PHID_Extra.find_rw p pm) as [(R,N)|(ph,(R,?))]; rewrite R in *; clear R. {\n        inversion Heqb.\n      }\n      destruct (register_pre {| get_task := get_new_task ps; get_mode := m |} t ph). {\n        eauto.\n      }\n      inversion Heqb.\n    }\n    right.\n    rewrite List.forallb_existsb in Heqb.\n    rewrite Bool.negb_false_iff in *.\n    apply existsb_exists in Heqb.\n    unfold not; intros N.\n    destruct Heqb as ((p,m),(Hi,Hx)).\n    apply Map_PHID_Extra.maps_to_iff_in_elements in Hi; auto using phid_eq_rw.\n    rewrite Bool.negb_true_iff in *.\n    simpl in *.\n    inversion N.\n    specialize (H _ _ Hi).\n    destruct H as (ph, (mt, Hr)).\n    destruct (Map_PHID_Extra.find_rw p pm) as [(R,N1)|(ph',(R,?))]; rewrite R in *; clear R. {\n      contradiction N1.\n      eauto using Map_PHID_Extra.mapsto_to_in.\n    }\n    destruct (register_pre {| get_task := get_new_task ps; get_mode := m |} t ph'). {\n      inversion Hx.\n    }\n    assert (ph' = ph) by eauto using Map_PHID_Facts.MapsTo_fun; subst.\n    contradiction.\n  Defined.\n\n  Definition in_dec t pm:\n    { In t pm } + { ~ In t pm }.\n  Proof.\n    destruct (Map_PHID_Extra.pred_choice pm (fun p ph =>\n      if Map_TID_Extra.in_dec tid_eq_rw t ph then true else false\n    )); auto with *. {\n      left.\n      destruct e as (p,(ph, (?,Hx))).\n      destruct (Map_TID_Extra.in_dec tid_eq_rw t ph). {\n        eauto using in_def.\n      }\n      inversion Hx.\n    }\n    right.\n    unfold not; intros N.\n    inversion N; subst; clear N.\n    specialize (e _ _ H).\n    destruct (Map_TID_Extra.in_dec tid_eq_rw t ph). {\n      inversion e.\n    }\n    contradiction.\n  Defined.\n\n  Lemma async_pre_dec ps t pm: \n    { AsyncPre ps t pm } + { ~ AsyncPre ps t pm }.\n  Proof.\n    destruct (in_dec (get_new_task ps) pm). {\n      right.\n      unfold not; intros N.\n      inversion N.\n      contradiction.\n    }\n    destruct (phased_pre_dec ps t pm). {\n      auto using async_pre.\n    }\n    right.\n    unfold not; intros N.\n    inversion N.\n    contradiction.\n  Defined.\nEnd Decidability.\n\nSection InInv.\n  Let in_add_inv:\n    forall x p ph s,\n    In x (Map_PHID.add p ph s) ->\n    Map_TID.In x ph \\/ In x s.\n  Proof.\n    intros.\n    inversion H; subst; clear H.\n    apply Map_PHID_Facts.add_mapsto_iff in H0.\n    destruct H0 as [(?,?)|(?,?)]. {\n      subst.\n      auto.\n    }\n    eauto using in_def.\n  Qed.\n\n  Let in_make_inv:\n    forall x y,\n    Map_TID.In y (Phaser.make x) ->\n    y = x.\n  Proof.\n    intros.\n    apply Map_TID_Extra.in_to_mapsto in H.\n    destruct H as (?, mt).\n    apply make_mapsto in mt.\n    destruct mt; auto.\n  Qed.\n\n  Let ph_in_signal_inv:\n    forall x y ph,\n    Map_TID.In x (signal y ph) ->\n    Map_TID.In x ph.\n  Proof.\n    unfold signal, Phaser.update; intros.\n    destruct (Map_TID_Extra.find_rw y ph) as [(R,?)|(?,(R,?))];\n    rewrite R in *; clear R. {\n      assumption.\n    }\n    apply Map_TID_Extra.F.add_in_iff in H.\n    destruct H. {\n      subst.\n      eauto using Map_TID_Extra.mapsto_to_in.\n    }\n    assumption.\n  Qed.\n\n  Let ph_in_try_signal_inv:\n    forall x y ph,\n    Map_TID.In x (try_signal y ph) ->\n    Map_TID.In x ph.\n  Proof.\n    unfold try_signal, Phaser.update; intros.\n    destruct (Map_TID_Extra.find_rw y ph) as [(R,?)|(?,(R,?))];\n    rewrite R in *; clear R. {\n      assumption.\n    }\n    apply Map_TID_Extra.F.add_in_iff in H.\n    destruct H. {\n      subst.\n      eauto using Map_TID_Extra.mapsto_to_in.\n    }\n    assumption.\n  Qed.\n\n  Let ph_in_wait_inv:\n    forall x y ph,\n    Map_TID.In x (wait y ph) ->\n    Map_TID.In x ph.\n  Proof.\n    unfold wait, Phaser.update; intros.\n    destruct (Map_TID_Extra.find_rw y ph) as [(R,?)|(?,(R,?))];\n    rewrite R in *; clear R. {\n      assumption.\n    }\n    apply Map_TID_Facts.add_in_iff in H.\n    destruct H. {\n      subst.\n      eauto using Map_TID_Extra.mapsto_to_in.\n    }\n    assumption.\n  Qed.\n\n  Let ph_in_drop_inv:\n    forall x y ph,\n    Map_TID.In x (drop y ph) ->\n    y <> x /\\ Map_TID.In x ph.\n  Proof.\n    unfold drop, Phaser.update; intros.\n    apply Map_TID_Facts.remove_in_iff in H.\n    assumption.\n  Qed.\n\n  Let ph_in_async_1_inv:\n    forall x y p ph h,\n    Map_TID.In y (async_1 p x h ph) ->\n    get_new_task p = y \\/ Map_TID.In y ph.\n  Proof.\n    unfold async_1; intros.\n    destruct (Map_PHID_Extra.find_rw h (get_args p)) as [(R,?)|(?,(R,?))];\n    rewrite R in *; clear R. {\n      auto.\n    }\n    unfold register in *.\n    destruct (Map_TID_Extra.find_rw x ph) as [(R,?)|(?,(R,?))];\n    rewrite R in *; clear R. {\n      auto.\n    }\n    simpl in *.\n    apply Map_TID_Facts.add_in_iff in H.\n    auto.\n  Qed.\n\n  Let in_signal_inv:\n    forall x y p s,\n    In x (ph_signal p y s) ->\n    In x s.\n  Proof.\n    unfold ph_signal, update.\n    intros.\n    destruct (Map_PHID_Extra.find_rw p s) as [(R,?)|(?,(R,?))];\n    rewrite R in *; clear R. {\n      assumption.\n    }\n    apply in_add_inv in H.\n    destruct H; eauto using in_def, ph_in_signal_inv.\n  Qed.\n\n  Let in_drop_inv:\n    forall x y p s,\n    In x (ph_drop p y s) ->\n    In x s.\n  Proof.\n    unfold ph_drop, update.\n    intros.\n    destruct (Map_PHID_Extra.find_rw p s) as [(R,?)|(?,(R,?))];\n    rewrite R in *; clear R. {\n      assumption.\n    }\n    apply in_add_inv in H.\n    destruct H; auto.\n    apply ph_in_drop_inv in H.\n    destruct H; eauto using in_def.\n  Qed.\n\n  Let in_signal_all_inv:\n    forall x y s,\n    In x (signal_all y s) ->\n    In x s.\n  Proof.\n    unfold signal_all, foreach.\n    intros.\n    inversion H; subst; clear H.\n    rewrite Map_PHID_Facts.mapi_mapsto_iff in *; auto.\n    destruct H0 as (ph', (?,mt)).\n    subst.\n    eauto using in_def, ph_in_try_signal_inv.\n  Qed.\n\n  Let in_wait_all_inv:\n    forall x y s,\n    In x (wait_all y s) ->\n    In x s.\n  Proof.\n    unfold wait_all, foreach.\n    intros.\n    inversion H; subst; clear H.\n    rewrite Map_PHID_Facts.mapi_mapsto_iff in *; auto.\n    destruct H0 as (ph', (?,mt)).\n    subst.\n    eauto using in_def, ph_in_wait_inv.\n  Qed.\n\n  Let in_drop_all_inv:\n    forall x y s,\n    In x (drop_all y s) ->\n    y <> x /\\ In x s.\n  Proof.\n    unfold drop_all, foreach.\n    intros.\n    inversion H; subst; clear H.\n    rewrite Map_PHID_Facts.mapi_mapsto_iff in *; auto.\n    destruct H0 as (ph', (?,mt)).\n    subst.\n    apply ph_in_drop_inv in H1.\n    destruct H1.\n    eauto using in_def.\n  Qed.\n\n  Let in_async_inv:\n    forall x y s p,\n    In x (async p y s) ->\n    get_new_task p = x \\/ In x s.\n  Proof.\n    unfold async, foreach.\n    intros.\n    inversion H; subst; clear H.\n    rewrite Map_PHID_Facts.mapi_mapsto_iff in *. {\n      destruct H0 as (ph', (?,mt)).\n      subst.\n      apply ph_in_async_1_inv in H1.\n      destruct H1;\n      eauto using in_def.\n    }\n    intros.\n    subst.\n    auto.\n  Qed.\n\n  Lemma reduces_in_inv:\n    forall x y o s s',\n    In y s' ->\n    Reduces s x o s' ->\n    (y = x /\\ exists p, o = PH_NEW p) \\/\n    (exists p, get_new_task p = y /\\ o = ASYNC p) \\/\n    In y s.\n  Proof.\n    intros.\n    destruct o; inversion H0; subst; clear H0; simpl in *;\n    inversion H1; subst; clear H1.\n    - unfold ph_new in *.\n      apply in_add_inv in H.\n      destruct H; auto.\n      apply in_make_inv in H.\n      eauto 4.\n    - eauto using in_signal_inv.\n    - eauto using in_drop_inv.\n    - eauto using in_signal_all_inv.\n    - eauto using in_wait_all_inv.\n    - apply in_drop_all_inv in H.\n      destruct H; auto.\n    - apply in_async_inv in H.\n      destruct H; eauto.\n  Qed.\n\n  Lemma reduces_drop_all_not_in:\n    forall pm x pm',\n    Reduces pm x DROP_ALL pm' ->\n    ~ In x pm'.\n  Proof.\n    intros.\n    unfold not; intros N.\n    inversion H; subst; clear H.\n    simpl in *.\n    apply in_drop_all_inv in N.\n    destruct N.\n    contradiction.\n  Qed.\n\n  Lemma not_in_make:\n    forall x,\n    ~ In x make.\n  Proof.\n    intros.\n    unfold not, make in *; intros N.\n    inversion N; subst; clear N.\n    rewrite Map_PHID_Facts.empty_mapsto_iff in *.\n    assumption.\n  Qed.\nEnd InInv.", "meta": {"author": "cogumbreiro", "repo": "habanero-coq", "sha": "2e7b1be0e25e53b4c6aba20a45700d6c743d7ce2", "save_path": "github-repos/coq/cogumbreiro-habanero-coq", "path": "github-repos/coq/cogumbreiro-habanero-coq/habanero-coq-2e7b1be0e25e53b4c6aba20a45700d6c743d7ce2/src/Phasers/Phasermap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.20229668330579953}}
{"text": "Require Import Coqlib.                                                                  \nRequire Import Maps.            \nRequire Import LibTactics.   \n        \nRequire Import Integers.  \nOpen Scope Z_scope.        \nImport ListNotations.  \n   \nSet Asymmetric Patterns.  \n        \nRequire Import state.    \nRequire Import language.  \n \nSet Implicit Arguments.    \nUnset Strict Implicit. \n               \nRequire Import logic.\n    \nRequire Import lemmas.\nRequire Import lemmas_ins.\n\nRequire Import Coq.Logic.FunctionalExtensionality.\n\nRequire Import integer_lemma.\n\nRequire Import sep_lemma.\nRequire Import reg_lemma.\nRequire Import derived_rule.\n\nRequire Import tm_dly_lemma.\n\nRequire Import code.\nRequire Import ctxswitch_spec.\n\nRequire Import lemma1.\n\nOpen Scope nat.\nOpen Scope code_scope.\nOpen Scope mem_scope.\n\nTheorem RegRestoreProof :\n  forall vl,\n    spec |- {{ reg_restore_pre vl }}\n             regstore\n           {{ reg_restore_post vl }}.\nProof.\n  intros.\n  unfold reg_restore_pre.\n  unfold reg_restore_post.\n  hoare_ex_intro_pre.\n  renames x' to fmg, x'0 to fmo, x'1 to fml, x'2 to fmi.\n  renames x'3 to nctx, x'5 to vy, x'7 to id, x'8 to vi, x'9 to F.\n  renames x'4 to l, x'6 to retl.\n  eapply Pure_intro_rule.\n  introv Hlgvl.\n  destruct nctx as [nl nctx].\n  destruct nctx as [ [ [rl ri] rg] ry].\n  hoare_lift_pre 5.\n  eapply Pure_intro_rule.\n  introv Hpure.\n  destruct Hpure as [Hsp [Hctx_addr Hretf] ].\n  simpl in Hctx_addr.\n  inversion Hctx_addr; subst.\n  unfold regstore.\n  hoare_lift_pre 2.\n  unfold context at 1.\n  unfold context'.\n  eapply backward_rule.\n  introv Hs.\n  asrt_to_line_in Hs 3.\n  eauto.\n \n  save_reg_unfold.\n  hoare_lift_pre 2.\n  save_reg_unfold.\n  hoare_lift_pre 3.\n  save_reg_unfold.\n  eapply backward_rule.\n  introv Hs.\n  unfold save_reg at 1 in Hs.\n  asrt_to_line_in Hs 8.\n  simpl_sep_liftn_in Hs 9.\n  simpl_sep_liftn_in Hs 9.\n  unfold save_reg at 1 in Hs.\n  asrt_to_line_in Hs 8.\n  simpl_sep_liftn_in Hs 9.\n  simpl_sep_liftn_in Hs 17.\n  unfold save_reg at 1 in Hs.\n  asrt_to_line_in Hs 4.\n  simpl_sep_liftn_in Hs 5.\n  simpl_sep_liftn_in Hs 22.\n  eauto.\n\n  Ltac solve_ld_ctx :=\n    eapply seq_rule;\n    [TimReduce_simpl; eapply ld_rule_reg; eauto;\n    try solve [simpl; repeat (rewrite Int.add_assoc); eauto] | simpl upd_genreg].\n\n  destruct fmg, fmo, fml, fmi.\n  simpl in Hsp.\n  inversion Hsp; subst.\n  \n  (** ld (l5 + OS_L0_OFFSET) l0 *)\n  solve_ld_ctx.\n  simpl.\n  unfold OS_L0_OFFSET.\n  rewrite in_range0; eauto.\n  rewrite Int.add_zero; eauto.\n \n  (** ld (l5 + OS_L1_OFFSET) l1 *)\n  hoare_lift_pre 3.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_L2_OFFSET) l2 *)\n  hoare_lift_pre 4.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_L3_OFFSET) l3 *)\n  hoare_lift_pre 5.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_I0_OFFSET) i0 *)\n  hoare_lift_pre 6.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_I1_OFFSET) i1 *)\n  hoare_lift_pre 7.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_I2_OFFSET) i2 *)\n  hoare_lift_pre 8.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_I3_OFFSET) i3 *)\n  hoare_lift_pre 9.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_I4_OFFSET) i4 *)\n  hoare_lift_pre 10.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_I5_OFFSET) i5 *)\n  hoare_lift_pre 11.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_I6_OFFSET) i6 *)\n  hoare_lift_pre 12.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_I7_OFFSET) i7 *)\n  hoare_lift_pre 13.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_Y_OFFSET) l6 *)\n  hoare_lift_pre 22.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** wr l6 0 Ry *)\n  hoare_lift_pre 23.\n  hoare_lift_pre 2.\n  eapply seq_rule.\n  TimReduce_simpl.\n  eapply wr_rule_reg; eauto.\n  simpl; eauto.\n  rewrite in_range0; eauto.\n  simpl set_spec_reg.\n  rewrite Int.xor_zero.\n\n  (** ld (l5 + OS_G1_OFFSET) g1 *)\n  hoare_lift_pre 17.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_G2_OFFSET) g2 *)\n  hoare_lift_pre 18.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_G3_OFFSET) g3 *)\n  hoare_lift_pre 19.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_G4_OFFSET) g4 *)\n  hoare_lift_pre 20.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_G5_OFFSET) g5 *)\n  hoare_lift_pre 21.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_G6_OFFSET) g6 *)\n  hoare_lift_pre 22.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** ld (l5 + OS_G7_OFFSET) g7 *)\n  hoare_lift_pre 23.\n  hoare_lift_pre 2.\n  solve_ld_ctx.\n\n  (** retl; nop *)\n  eapply retl_rule; eauto.\n  TimReduce_simpl.\n  eapply nop_rule; eauto.\n  introv Hs.\n  sep_ex_intro.\n  eapply sep_pure_l_intro; eauto.\n  sep_cancel1 1 1.\n  sep_cancel1 8 2.\n  unfold context, context'.\n  asrt_to_line 4.\n  unfold save_reg.\n  asrt_to_line 4.\n  simpl_sep_liftn 5.\n  simpl_sep_liftn 5.\n  asrt_to_line 8.\n  simpl_sep_liftn 9.\n  simpl_sep_liftn 13.\n  asrt_to_line 8.\n  simpl_sep_liftn 9.\n\n  sep_cancel1 1 8.\n  sep_cancel1 1 7.\n  sep_cancel1 1 6.\n  sep_cancel1 1 5.\n  sep_cancel1 1 4.\n  sep_cancel1 1 3.\n  sep_cancel1 1 2.\n  sep_cancel1 1 14.\n  sep_cancel1 13 1.\n  sep_cancel1 1 8.\n  sep_cancel1 1 7.\n  sep_cancel1 1 6.\n  sep_cancel1 1 5.\n  sep_cancel1 1 4.\n  sep_cancel1 1 3.\n  sep_cancel1 1 2.\n  sep_cancel1 1 1.\n  sep_cancel1 1 4.\n  sep_cancel1 1 3.\n  sep_cancel1 1 2.\n  sep_cancel1 1 1.\n  sep_cancel1 1 1.\n  instantiate (1 := Aemp).\n  eapply astar_emp_intro_r; eauto.\n  eapply astar_emp_elim_r.\n  eapply sep_pure_l_intro; eauto.\n  simpls.\n  repeat (split; eauto).\n\n  unfold fretSta.\n  TimReduce_simpl.\n  introv Hs Hs'.\n  simpl in Hretf.\n  inversion Hretf; subst.\n  sep_ex_elim_in Hs'.\n  eapply sep_pure_l_elim in Hs'.\n  destruct Hs' as [Hlgvl1 Hs'].\n  inversion Hlgvl1; subst.\n  destruct x, x0, x1, x2.\n  simpl_sep_liftn_in Hs' 5.\n  eapply sep_pure_l_elim in Hs'.\n  destruct Hs' as [Hctx_win_restore Hs'].\n  destruct_state s.\n  destruct_state s'.\n  eapply getR_eq_get_genreg_val1 with (rr := r15) in Hs; eauto.\n  eapply getR_eq_get_genreg_val1 with (rr := r15) in Hs'; eauto.\n  clear - Hs Hctx_win_restore Hs'.\n  simpls.\n  simpljoin1.\n  unfolds get_R.\n  destruct (r r15); tryfalse.\n  destruct (r0 r15); tryfalse.\n  inversion H0; subst.\n  eauto.\nQed.\n\n  \n", "meta": {"author": "luckywangwang", "repo": "CertiSparc", "sha": "b5c4ff0d1b723537a645b6c5578b8749ed1c813e", "save_path": "github-repos/coq/luckywangwang-CertiSparc", "path": "github-repos/coq/luckywangwang-CertiSparc/CertiSparc-b5c4ff0d1b723537a645b6c5578b8749ed1c813e/coqimp/contextswitch/proof/RegRestoreProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.20229668330579953}}
{"text": "Require Export MicroBFTprops2.\n\n\nSection MicroBFTass_new.\n\n  Local Open Scope eo.\n  Local Open Scope proc.\n\n  Context { dtc                 : DTimeContext          }.\n  Context { microbft_context    : MicroBFT_context      }.\n  Context { m_initial_keys      : MicroBFT_initial_keys }.\n  Context { u_initial_keys      : USIG_initial_keys     }.\n  Context { usig_hash           : USIG_hash             }.\n  Context { microbft_auth       : MicroBFT_auth         }.\n\n\n  Opaque KE_TOWNS.\n  Opaque KE_ID_BEFORE.\n\n\n  Lemma ASSUMPTION_generates_new_true :\n    forall (eo : EventOrdering), assume_eo eo ASSUMPTION_generates_new_ex.\n  Proof.\n    introv h; simpl in *.\n    allrw interp_KE_ID_BEFORE.\n    exrepnd; GC; subst.\n\n    unfold id_before, id_after in *; simpl; exrepnd; subst.\n    rename mem0 into mem1.\n    rename mem into mem2.\n    simpl in *.\n    unfold trusted_state_before, trusted_state_after in *; simpl in *.\n    exrepnd.\n    rewrite h2 in *; unfold MicroBFTheader.node2name in *; ginv; subst.\n    unfold disseminate_data in *; exrepnd.\n    unfold M_byz_output_sys_on_event in *.\n    unfold M_byz_output_ls_on_event in *; simpl in *.\n    unfold M_byz_state_sys_on_event in *; simpl in *.\n    unfold M_byz_state_sys_before_event in *; simpl in *.\n\n    applydup preserves_usig_id in h5 as eqid; auto;[].\n\n    apply map_option_Some in h5; exrepnd; rev_Some; simpl in *; microbft_simp.\n    apply map_option_Some in h6; exrepnd; rev_Some; simpl in *; microbft_simp.\n    rewrite M_byz_run_ls_on_event_unroll2 in h3; simpl in *.\n\n    remember (M_byz_run_ls_before_event (MicroBFTsys (loc e)) e) as ls; symmetry in Heqls.\n    simpl in *.\n    rewrite Heqls in *.\n    unfold MicroBFTsys in *; simpl in *.\n\n    apply M_byz_run_ls_before_event_ls_is_microbft in Heqls.\n    repndors; exrepnd; subst; simpl in *; microbft_simp.\n\n    { unfold M_byz_run_ls_on_this_one_event in *; simpl in *.\n      unfold M_byz_run_ls_on_one_event in *; simpl in *.\n      revert dependent o.\n      unfold data_is_in_out, event2out in *.\n      remember (trigger e) as trig; symmetry in Heqtrig.\n      destruct trig; simpl in *; ginv; tcsp; introv run j.\n\n      { allrw in_flat_map; exrepnd.\n        unfold M_run_ls_on_input in *.\n        autorewrite with microbft in *.\n        Time microbft_dest_msg Case;\n          repeat (simpl in *; autorewrite with microbft in *; smash_microbft2);\n          try (complete (repndors; ginv; simpl in *;\n                           unfold ui_has_counter, ui2counter, state_of_trusted in *; simpl in *;\n                             eexists; dands; try reflexivity; try omega; tcsp)). }\n\n      { unfold M_run_ls_on_trusted, M_run_ls_on_input in *; simpl in *.\n        autorewrite with microbft in *.\n        rewrite @on_comp_sing_eq in run.\n        rewrite @on_comp_sing_eq in h3.\n        dest_cases w; simpl in *;[].\n        destruct i, o; simpl in *; repndors; ginv; tcsp;[].\n        inversion w; subst; simpl in *.\n        rewrite (UIP_refl_CompName _ w) in *; auto; simpl in *.\n        destruct it_input; simpl in *; repnd; simpl in *; tcsp; microbft_simp; ginv;\n          unfold ui_has_counter, ui2counter, state_of_trusted in *; simpl in *;\n            eexists; dands; try reflexivity; try omega; tcsp. } }\n\n    { unfold M_byz_run_ls_on_this_one_event in *; simpl in *.\n      unfold M_byz_run_ls_on_one_event in *; simpl in *.\n      revert dependent o.\n      unfold data_is_in_out, event2out in *.\n      remember (trigger e) as trig; symmetry in Heqtrig.\n      destruct trig; simpl in *; ginv; tcsp; introv run j.\n\n      unfold M_run_ls_on_trusted, M_run_ls_on_input in *; simpl in *.\n      autorewrite with microbft in *.\n      rewrite @on_comp_sing_eq in run.\n      rewrite @on_comp_sing_eq in h3.\n      dest_cases w; simpl in *;[].\n      destruct i, o; simpl in *; repndors; ginv; tcsp;[].\n      inversion w; subst; simpl in *.\n      rewrite (UIP_refl_CompName _ w) in *; auto; simpl in *.\n      destruct it_input; simpl in *; repnd; simpl in *; tcsp; microbft_simp; ginv;\n        unfold ui_has_counter, ui2counter, state_of_trusted in *; simpl in *;\n          eexists; dands; try reflexivity; try omega; tcsp. }\n  Qed.\n  Hint Resolve ASSUMPTION_generates_new_true : microbft.\n\nEnd MicroBFTass_new.\n\n\nHint Resolve ASSUMPTION_generates_new_true : microbft.\n", "meta": {"author": "veri-fit", "repo": "Asphalion", "sha": "fbf9c82e75dc7b5c98774e4ab07c642eb3856105", "save_path": "github-repos/coq/veri-fit-Asphalion", "path": "github-repos/coq/veri-fit-Asphalion/Asphalion-fbf9c82e75dc7b5c98774e4ab07c642eb3856105/MinBFT/MicroBFTass_new.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.20229668330579947}}
{"text": "Require Import Lia IndefiniteDescription Arith.\nFrom hahn Require Import Hahn.\nRequire Import AuxRel.\nRequire Import Labels.\nRequire Import Events.\nRequire Import Execution.\nRequire Import View.\n\nSet Implicit Arguments.\n\nRecord Message :=\n  Msg {\n      mloc : Loc ;\n      mval : Val ;\n      mts  : Timestamp ;\n      mview : View }.\n\nDefinition Memory := (Message -> Prop).\nDefinition State := (Memory * (Tid -> View))%type.\n\nDefinition Minit : Memory :=\n  fun m => mval m = 0 /\\ mts m = 0 /\\\n           mview m = fun _ => 0.\n\nDefinition Vinit : View := fun x => 0.\nDefinition Sinit : State := (Minit, fun tid => Vinit).\n\nInductive RA_label :=\n  | RA_event (e : Event) (tstamp : Timestamp) (view : View)\n  | RA_internal (t : Tid) (x : Loc) (tstamp : Timestamp).\n\nDefinition deflabel : RA_label := RA_internal 0 0 0.\n\nDefinition read_ts x :=\n  match x with\n  | RA_event _ ts _ => ts\n  | RA_internal _ _ _ => 0\n  end.\n\nDefinition write_ts x :=\n  match x with\n  | RA_event _ ts _ => S ts\n  | RA_internal _ _ _ => 0\n  end.\n\nDefinition tid_of x :=\n  match x with\n  | RA_event e _ _ => tid e\n  | RA_internal tid x _ => tid\n  end.\n\nDefinition is_external x :=\n  match x with\n  | RA_event (ThreadEvent _ _ _) _ _ => True\n  | _ => False\n  end.\n\nDefinition proj_ev x :=\n  match x with\n  | RA_event e _ _ => e\n  | RA_internal _ _ _ => InitEvent 0\n  end.\n\nDefinition trproj t :=\n  trace_map proj_ev (trace_filter is_external t).\n\nDefinition fresh_tstamp (m : Memory) x ts :=\n  ~ exists v view, m (Msg x v ts view).\n\n(*\n  Note that we use 'S tstamp` value in write transitions.  \n  This allows to compute both read and write timestamps \n  from single 'tstamp' field of RA_label. \n  This is useful for working with RMW labels \n  for which both kinds of timestamps make sense. \n  By accessing these timestamps with write_ts and read_ts helpers defined above,\n  we obtain actual timestamps being written to memory. \n*)\nInductive RA_step (MV : State) (e: RA_label) (MV' : State) : Prop :=\n| RAstep_read t i x v tstamp view view'\n              (EQ: e = RA_event (ThreadEvent t i (Aload x v)) tstamp view')\n\t      (MSG: fst MV (Msg x v tstamp view))\n              (LEV: snd MV t x <= tstamp)\n              (MEM: fst MV' = fst MV)\n              (EQ': view' = view_join (upd (snd MV t) x tstamp) view)\n\t      (VIEW: snd MV' = upd (snd MV) t view')\n| RAstep_write t i x v tstamp view'\n               (EQ: e = RA_event (ThreadEvent t i (Astore x v)) tstamp view')\n               (EQ': view' = upd (snd MV t) x (S tstamp))\n               (LTV: snd MV t x < S tstamp)\n               (MEM: fst MV' = fst MV ∪₁ eq (Msg x v (S tstamp) view'))\n               (FRESH: fresh_tstamp (fst MV) x (S tstamp))\n\t       (VIEW: snd MV' = upd (snd MV) t view')\n| RAstep_rmw t i x vr vw tstamp view view'\n             (EQ: e = RA_event (ThreadEvent t i (Armw x vr vw)) tstamp view')\n\t     (MSG: fst MV (Msg x vr tstamp view))\n             (LEV: snd MV t x <= tstamp)\n             (EQ' : view' = view_join (upd (snd MV t) x (S tstamp)) view)\n             (MEM: fst MV' = fst MV ∪₁ eq (Msg x vw (S tstamp) view'))\n             (FRESH: fresh_tstamp (fst MV) x (S tstamp))\n             (VIEW: snd MV' = upd (snd MV) t view')\n| RAstep_internal t x v tstamp view view'\n                  (EQ: e = RA_internal t x tstamp)\n\t\t  (MSG: fst MV (Msg x v tstamp view))\n                  (LEV: snd MV t x < tstamp)\n                  (MEM: fst MV' = fst MV)\n                  (EQ': view' = upd (snd MV t) x tstamp)\n\t\t  (VIEW: snd MV' = upd (snd MV) t view').\n\nDefinition ra_lts :=\n  {| LTS_init := eq Sinit ;\n     LTS_step := RA_step ;\n     LTS_final := ∅ |}.\n\nDefinition run_fair (states : nat -> State) t : Prop :=\n  match t with\n  | trace_fin _ => True\n  | trace_inf fl =>\n    exists (threads : Tid -> Prop),\n    set_finite threads /\\\n    trace_elems t ⊆₁ tid_of ↓₁ threads /\\\n    forall i (tid : Tid) (TID: threads tid) x tstamp,\n    exists j,\n      i <= j /\\\n      (fl j = RA_internal tid x tstamp \\/\n       forall st'\n              (STEP: RA_step (states j) (RA_internal tid x tstamp) st'),\n         False)\n  end.\n\nDefinition RA_is_w lab :=\n  match lab with\n  | RA_event (ThreadEvent _ _ (Astore _ _)) ts view => True\n  | RA_event (ThreadEvent _ _ (Armw _ _ _)) ts view => True\n  | _ => False\n  end.\n\nDefinition RA_wmsg lab :=\n  match lab with\n  | RA_event (ThreadEvent t i (Astore x v)) ts view => Msg x v (S ts) view\n  | RA_event (ThreadEvent t i (Armw x vr vw)) ts view => Msg x vw (S ts) view\n  | _ => Msg 0 0 0 (fun _ => 0)\n  end.\n\nDefinition view_of x :=\n  match x with\n  | RA_event _ _ view => view\n  | RA_internal _ _ _ => fun _ => 0\n  end.\n\nInductive match_ev (e : Event) (l : RA_label) : Prop :=\n| ME_case t i lab tstamp view (EQe : e = ThreadEvent t i lab)\n          (EQl : l = RA_event e tstamp view).\n\nDefinition view_of' t x :=\n  match excluded_middle_informative\n          (exists xl, match_ev x xl /\\ trace_elems t xl) with\n  | left IN =>\n    view_of (proj1_sig\n               (IndefiniteDescription.constructive_indefinite_description\n                  _ IN))\n  | right _ => fun _ => 0\n  end.\n\nLemma view_of_init t x :\n  view_of' t (InitEvent x) = fun _ => 0.\nProof using.\n  unfold view_of'; desf.\n  exfalso; desf; destruct e; desf.\nQed.\n\nLemma RA_step_view_mono mem lab mem'\n      (STEP : RA_step mem lab mem') t :\n  view_le (snd mem t) (snd mem' t).\nProof using.\n  destruct STEP; ins; desf; ins.\n  all: rewrite VIEW; clear VIEW; unfold upd; desf.\n  all: try apply view_le_join_l.\n  all: red; unfold upd; ins; desf; lia.\nQed.\n\nLemma RA_step_view_ext mem lab mem'\n      (STEP : RA_step mem lab mem')\n      (EXT : is_external lab) :\n  view_le (snd mem (tid_of lab))\n          (view_of lab) /\\\n  view_of lab = snd mem' (tid_of lab).\nProof using.\n  destruct STEP; ins; desf; ins.\n  all: rewrite VIEW, upds; split; ins.\n  all: try apply view_le_join_l.\n  all: red; unfold upd; ins; desf; lia.\nQed.\n\nLemma RA_view_mono mem lab\n      (STEP : forall i, RA_step (mem i) (lab i) (mem (S i)))\n      i j (LE : i <= j) mytid x :\n  snd (mem i) mytid x <= snd (mem j) mytid x.\nProof using.\n  induction j; rewrite Nat.le_lteq in LE; desf; try lia.\n  rewrite Nat.lt_succ_r in *; intuition.\n  eapply Nat.le_trans, RA_step_view_mono; eauto.\nQed.\n\nSection RADeclarative.\n\nVariable G: execution. \n\nDefinition ra_consistent :=\n  irreflexive (hb G ⨾ (co G ∪ fr G)^?) /\\\n  irreflexive ((rf G)⁻¹ ⨾ (co G ⨾ (co G))).\n\nLemma hb_irr (CONS : ra_consistent) : irreflexive (hb G).\nProof using.\n  cdes CONS. eapply irreflexive_mori; [|by apply CONS0]. red. basic_solver.\nQed.\n\nLemma ra_rmw_atomicity (WF: Wf G) (CONS : ra_consistent) :\n  rmw_atomicity G.\nProof using.\n  unfold ra_consistent, rmw_atomicity in *; desc.\n  rewrite wf_rfE, wf_rfD; ins; unfolder in *; ins; desf.\n  destruct (classic (x = y)) as [|NEQ]; desf.\n    by edestruct (CONS y); exists y; split; vauto.\n  eapply (wf_co_total WF) in NEQ; ins; desf; ins.    \n    splits; ins; intro; desf; eauto 10.  \n  edestruct (CONS x); exists y; split; vauto.    \n  apply wf_rfl in H0; ins.\nQed.\n\n \nLemma ra_rf_irr (CONS : ra_consistent) : irreflexive (rf G).\nProof using. rewrite rf_in_hb. by apply hb_irr. Qed.\n\nLemma rf_w_in_co (WF: Wf G) (CONS : ra_consistent) :\n  (rf G) ⨾ ⦗is_w⦘ ⊆ (co G).\nProof using.\n  unfolder. intros x y [RF WY].\n  destruct (classic (x = y)) as [|NEQ]; subst.\n  { exfalso. eapply ra_rf_irr; eauto. }\n  apply (wf_rfE WF) in RF. unfolder in RF. desf.\n  apply (wf_rfD WF) in RF0. unfolder in RF0. desf.\n  edestruct (wf_co_total WF) with (a:=x) (b:=y) as [|HH]; eauto.\n  1,2: unfolder; splits; eauto.\n  { symmetry. by apply (wf_rfl WF). }\n  exfalso.\n  cdes CONS.\n  eapply CONS0. eexists. split.\n  2: { generalize HH. basic_solver. }\n    by apply rf_in_hb.\nQed.\n\nLemma co_init_r (WF: Wf G) (CONS : ra_consistent) x y : (co G) x y -> is_init y -> False.\nProof.\n  ins.\n  eapply (proj1 CONS y); eexists x; split; vauto.\n  apply (wf_coE WF) in H.\n  apply t_step; left; unfold sb, ext_sb; unfolder in *; desf.\n  assert (SL := wf_col WF _ _ H1); unfold same_loc, loc in *; ins; desf.\n  edestruct (co_irr WF); eauto.\nQed.\n\nEnd RADeclarative.\n", "meta": {"author": "weakmemory", "repo": "fairness", "sha": "537609d3c23490a82f11f13125d1f0ce4ce3fef8", "save_path": "github-repos/coq/weakmemory-fairness", "path": "github-repos/coq/weakmemory-fairness/fairness-537609d3c23490a82f11f13125d1f0ce4ce3fef8/src/equivalence/ra/RAop.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.31742627204485063, "lm_q1q2_score": 0.20221031464442682}}
{"text": "(**************************************************************************)\n(*  This file is part of CertrBPF,                                        *)\n(*  a formally verified rBPF verifier + interpreter + JIT in Coq.         *)\n(*                                                                        *)\n(*  Copyright (C) 2022 Inria                                              *)\n(*                                                                        *)\n(*  This program is free software; you can redistribute it and/or modify  *)\n(*  it under the terms of the GNU General Public License as published by  *)\n(*  the Free Software Foundation; either version 2 of the License, or     *)\n(*  (at your option) any later version.                                   *)\n(*                                                                        *)\n(*  This program is distributed in the hope that it will be useful,       *)\n(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)\n(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)\n(*  GNU General Public License for more details.                          *)\n(*                                                                        *)\n(**************************************************************************)\n\nFrom bpf.comm Require Import rBPFAST ListAsArray MemRegion Regs Flag State.\n\nFrom bpf.monadicmodel Require Import Opcode.\n\nFrom Coq Require Import List Lia ZArith.\nFrom compcert Require Import Integers Values Clight Memory AST.\nImport ListNotations.\n\nFrom bpf.clightlogic Require Import Clightlogic CommonLib.\nFrom bpf.simulation Require Import MatchState.\n\nDefinition val_ptr_correct {S:special_blocks} (x:val) (v: val) (st: State.state) (m:Memory.Mem.mem) :=\n  x = v /\\\n  match_state st m.\n\nOpen Scope nat_scope.\nDefinition is_state_handle {S: special_blocks} (v: val) := v = Vptr st_blk Ptrofs.zero.\n\nDefinition is_illegal_alu64_ins (i:nat): Prop :=\n  ((Nat.land i 240) <> 0x00) /\\\n  ((Nat.land i 240) <> 0x10) /\\\n  ((Nat.land i 240) <> 0x20) /\\\n  ((Nat.land i 240) <> 0x30) /\\\n  ((Nat.land i 240) <> 0x40) /\\\n  ((Nat.land i 240) <> 0x50) /\\\n  ((Nat.land i 240) <> 0x60) /\\\n  ((Nat.land i 240) <> 0x70) /\\\n  ((Nat.land i 240) <> 0x80) /\\\n  ((Nat.land i 240) <> 0x90) /\\\n  ((Nat.land i 240) <> 0xa0) /\\\n  ((Nat.land i 240) <> 0xb0) /\\\n  ((Nat.land i 240) <> 0xc0).\n\nDefinition opcode_alu64_correct (opcode: opcode_alu64) (v: val) :=\n  match opcode with\n  | op_BPF_ADD64 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x07 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x0f 240)))\n  | op_BPF_SUB64 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x17 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x1f 240)))\n  | op_BPF_MUL64 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x27 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x2f 240)))\n  | op_BPF_DIV64 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x37 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x3f 240)))\n  | op_BPF_OR64  => v = Vint (Int.repr (Z.of_nat (Nat.land 0x47 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x4f 240)))\n  | op_BPF_AND64 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x57 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x5f 240)))\n  | op_BPF_LSH64 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x67 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x6f 240)))\n  | op_BPF_RSH64 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x77 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x7f 240)))\n  | op_BPF_NEG64 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x87 240)))\n  | op_BPF_MOD64 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x97 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x9f 240)))\n  | op_BPF_XOR64 => v = Vint (Int.repr (Z.of_nat (Nat.land 0xa7 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0xaf 240)))\n  | op_BPF_MOV64 => v = Vint (Int.repr (Z.of_nat (Nat.land 0xb7 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0xbf 240)))\n  | op_BPF_ARSH64=> v = Vint (Int.repr (Z.of_nat (Nat.land 0xc7 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0xcf 240)))\n  | op_BPF_ALU64_ILLEGAL_INS => exists i, v = Vint (Int.repr (Z.of_nat (Nat.land i 240))) /\\ is_illegal_alu64_ins i\n  end.\n\nDefinition is_illegal_alu32_ins (i:nat): Prop :=\n  ((Nat.land i 240) <> 0x00) /\\\n  ((Nat.land i 240) <> 0x10) /\\\n  ((Nat.land i 240) <> 0x20) /\\\n  ((Nat.land i 240) <> 0x30) /\\\n  ((Nat.land i 240) <> 0x40) /\\\n  ((Nat.land i 240) <> 0x50) /\\\n  ((Nat.land i 240) <> 0x60) /\\\n  ((Nat.land i 240) <> 0x70) /\\\n  ((Nat.land i 240) <> 0x80) /\\\n  ((Nat.land i 240) <> 0x90) /\\\n  ((Nat.land i 240) <> 0xa0) /\\\n  ((Nat.land i 240) <> 0xb0) /\\\n  ((Nat.land i 240) <> 0xc0).\n\nDefinition opcode_alu32_correct (opcode: opcode_alu32) (v: val) :=\n  match opcode with\n  | op_BPF_ADD32 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x04 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x0c 240)))\n  | op_BPF_SUB32 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x14 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x1c 240)))\n  | op_BPF_MUL32 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x24 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x2c 240)))\n  | op_BPF_DIV32 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x34 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x3c 240)))\n  | op_BPF_OR32  => v = Vint (Int.repr (Z.of_nat (Nat.land 0x44 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x4c 240)))\n  | op_BPF_AND32 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x54 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x5c 240)))\n  | op_BPF_LSH32 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x64 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x6c 240)))\n  | op_BPF_RSH32 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x74 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x7c 240)))\n  | op_BPF_NEG32 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x84 240)))\n  | op_BPF_MOD32 => v = Vint (Int.repr (Z.of_nat (Nat.land 0x94 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x9c 240)))\n  | op_BPF_XOR32 => v = Vint (Int.repr (Z.of_nat (Nat.land 0xa4 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0xac 240)))\n  | op_BPF_MOV32 => v = Vint (Int.repr (Z.of_nat (Nat.land 0xb4 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0xbc 240)))\n  | op_BPF_ARSH32=> v = Vint (Int.repr (Z.of_nat (Nat.land 0xc4 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0xcc 240)))\n  | op_BPF_ALU32_ILLEGAL_INS => exists i, v = Vint (Int.repr (Z.of_nat (Nat.land i 240))) /\\ is_illegal_alu32_ins i\n  end.\n\nDefinition is_illegal_jmp_ins (i:nat): Prop :=\n  ((Nat.land i 240) <> 0x00) /\\\n  ((Nat.land i 240) <> 0x10) /\\\n  ((Nat.land i 240) <> 0x20) /\\\n  ((Nat.land i 240) <> 0x30) /\\\n  ((Nat.land i 240) <> 0x40) /\\\n  ((Nat.land i 240) <> 0x50) /\\\n  ((Nat.land i 240) <> 0x60) /\\\n  ((Nat.land i 240) <> 0x70) /\\\n  ((Nat.land i 240) <> 0x80) /\\\n  ((Nat.land i 240) <> 0x90) /\\\n  ((Nat.land i 240) <> 0xa0) /\\\n  ((Nat.land i 240) <> 0xb0) /\\\n  ((Nat.land i 240) <> 0xc0) /\\\n  ((Nat.land i 240) <> 0xd0).\n\nDefinition opcode_branch_correct (opcode: opcode_branch) (v: val) :=\n  match opcode with\n  | op_BPF_JA    => v = Vint (Int.repr (Z.of_nat (Nat.land 0x05 240)))\n  | op_BPF_JEQ   => v = Vint (Int.repr (Z.of_nat (Nat.land 0x15 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x1d 240)))\n  | op_BPF_JGT   => v = Vint (Int.repr (Z.of_nat (Nat.land 0x25 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x2d 240)))\n  | op_BPF_JGE   => v = Vint (Int.repr (Z.of_nat (Nat.land 0x35 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x3d 240)))\n  | op_BPF_JLT   => v = Vint (Int.repr (Z.of_nat (Nat.land 0xa5 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0xad 240)))\n  | op_BPF_JLE   => v = Vint (Int.repr (Z.of_nat (Nat.land 0xb5 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0xbd 240)))\n  | op_BPF_JSET  => v = Vint (Int.repr (Z.of_nat (Nat.land 0x45 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x4d 240)))\n  | op_BPF_JNE   => v = Vint (Int.repr (Z.of_nat (Nat.land 0x55 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x5d 240)))\n  | op_BPF_JSGT  => v = Vint (Int.repr (Z.of_nat (Nat.land 0x65 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x6d 240)))\n  | op_BPF_JSGE  => v = Vint (Int.repr (Z.of_nat (Nat.land 0x75 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0x7d 240)))\n  | op_BPF_JSLT  => v = Vint (Int.repr (Z.of_nat (Nat.land 0xc5 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0xcd 240)))\n  | op_BPF_JSLE  => v = Vint (Int.repr (Z.of_nat (Nat.land 0xd5 240))) \\/ v = Vint (Int.repr (Z.of_nat (Nat.land 0xdd 240)))\n  | op_BPF_CALL  => v = Vint (Int.repr (Z.of_nat (Nat.land 0x85 240)))\n  | op_BPF_RET   => v = Vint (Int.repr (Z.of_nat (Nat.land 0x95 240)))\n  | op_BPF_JMP_ILLEGAL_INS => exists i, v = Vint (Int.repr (Z.of_nat (Nat.land i 240))) /\\ is_illegal_jmp_ins i\n  end.\n\nDefinition opcode_mem_ld_imm_correct (opcode: opcode_mem_ld_imm) (v: val) :=\n  match opcode with\n  | op_BPF_LDDW_low  => v = Vint (Int.repr (Z.of_nat 0x18))\n  | op_BPF_LDDW_high => v = Vint (Int.repr (Z.of_nat 0x10))\n  | op_BPF_LDX_IMM_ILLEGAL_INS =>\n    exists i,\n      v = Vint (Int.repr (Z.of_nat i)) /\\\n      (i <> 0x18 /\\ i <> 0x10) /\\\n      i <= 255\n  end.\n\nDefinition opcode_mem_ld_reg_correct (opcode: opcode_mem_ld_reg) (v: val) :=\n  match opcode with\n  | op_BPF_LDXW  => v = Vint (Int.repr (Z.of_nat 0x61))\n  | op_BPF_LDXH  => v = Vint (Int.repr (Z.of_nat 0x69))\n  | op_BPF_LDXB  => v = Vint (Int.repr (Z.of_nat 0x71))\n  | op_BPF_LDXDW => v = Vint (Int.repr (Z.of_nat 0x79))\n  | op_BPF_LDX_REG_ILLEGAL_INS =>\n    exists i,\n      v = Vint (Int.repr (Z.of_nat i)) /\\\n      (i <> 0x61 /\\ i <> 0x69 /\\ i <> 0x71 /\\ i <> 0x79) /\\\n      i <= 255\n  end.\n\nDefinition opcode_mem_st_imm_correct (opcode: opcode_mem_st_imm) (v: val) :=\n  match opcode with\n  | op_BPF_STW  => v = Vint (Int.repr (Z.of_nat 0x62))\n  | op_BPF_STH  => v = Vint (Int.repr (Z.of_nat 0x6a))\n  | op_BPF_STB  => v = Vint (Int.repr (Z.of_nat 0x72))\n  | op_BPF_STDW => v = Vint (Int.repr (Z.of_nat 0x7a))\n  | op_BPF_ST_ILLEGAL_INS =>\n    exists i,\n      v = Vint (Int.repr (Z.of_nat i)) /\\\n      (i <> 0x62 /\\ i <> 0x6a /\\ i <> 0x72 /\\ i <> 0x7a) /\\\n      i <= 255\n  end.\n\nDefinition opcode_mem_st_reg_correct (opcode: opcode_mem_st_reg) (v: val) :=\n  match opcode with\n  | op_BPF_STXW  => v = Vint (Int.repr (Z.of_nat 0x63))\n  | op_BPF_STXH  => v = Vint (Int.repr (Z.of_nat 0x6b))\n  | op_BPF_STXB  => v = Vint (Int.repr (Z.of_nat 0x73))\n  | op_BPF_STXDW => v = Vint (Int.repr (Z.of_nat 0x7b))\n  | op_BPF_STX_ILLEGAL_INS =>\n    exists i,\n      v = Vint (Int.repr (Z.of_nat i)) /\\\n      (i <> 0x63 /\\ i <> 0x6b /\\ i <> 0x73 /\\ i <> 0x7b) /\\\n      i <= 255\n  end.\n\nDefinition opcode_step_correct (op: opcode) (v: val) :=\n  match op with\n  | op_BPF_ALU64   (**r 0xX7 / 0xXf *) => v = Vint (Int.repr (Z.of_nat 0x07))\n  | op_BPF_ALU32   (**r 0xX4 / 0xXc *) => v = Vint (Int.repr (Z.of_nat 0x04))\n  | op_BPF_Branch  (**r 0xX5 / 0xXd *) => v = Vint (Int.repr (Z.of_nat 0x05))\n  | op_BPF_Mem_ld_imm  (**r 0xX8 *)    => v = Vint (Int.repr (Z.of_nat 0x00))\n  | op_BPF_Mem_ld_reg  (**r 0xX1/0xX9 *) => v = Vint (Int.repr (Z.of_nat 0x01))\n  | op_BPF_Mem_st_imm  (**r 0xX2/0xXa *) => v = Vint (Int.repr (Z.of_nat 0x02))\n  | op_BPF_Mem_st_reg  (**r 0xX3/0xXb *) => v = Vint (Int.repr (Z.of_nat 0x03))\n\n  | op_BPF_ILLEGAL_INS =>\n    exists i,\n      v = Vint (Int.repr (Z.of_nat i)) /\\\n      (i <> 0x00 /\\ i <> 0x01 /\\ i <> 0x02 /\\ i <> 0x03 /\\ i <> 0x04 /\\ i <> 0x05 /\\ i <> 0x07) /\\\n      i <= 255\n  end.\n\nClose Scope nat_scope.\n\n\nDefinition mr_correct {S:special_blocks} (mr: memory_region) (v: val) (st: State.state) (m:Memory.Mem.mem) :=\n  List.In mr (bpf_mrs st) /\\\n  match_region st_blk mrs_blk ins_blk mr v st m /\\\n  match_state  st m.\n\nDefinition mrs_correct (S: special_blocks) (mrs: list memory_region) (v: val) (st: State.state) (m:Memory.Mem.mem) :=\n  v = Vptr mrs_blk Ptrofs.zero /\\\n  mrs = (bpf_mrs st) /\\\n  match_regions st_blk mrs_blk ins_blk st m /\\\n  match_state  st m.\n", "meta": {"author": "future-proof-iot", "repo": "CertFC", "sha": "75690097c946c555cc4ce1e69d13ef86dc738180", "save_path": "github-repos/coq/future-proof-iot-CertFC", "path": "github-repos/coq/future-proof-iot-CertFC/CertFC-75690097c946c555cc4ce1e69d13ef86dc738180/simulation/InterpreterRel.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300698514778, "lm_q2_score": 0.28776780354463427, "lm_q1q2_score": 0.20216553512521826}}
{"text": "Require Import sflib.\nRequire Import Ensembles.\nRequire Import syntax.\nRequire Import infrastructure.\nRequire Import List.\nRequire Import Arith.\nRequire Import monad.\nRequire Import Metatheory.\nRequire Import genericvalues.\nRequire Import alist.\nRequire Import Values.\nRequire Import Memory.\nRequire Import Integers.\nRequire Import Coqlib.\nRequire Import targetdata.\nRequire Import infrastructure_props.\nRequire Import typings.\nRequire Import events.\nRequire Import external_intrinsics.\nRequire Import genericvalues_inject.\nRequire Import static.\n\n(*************************************************************)\n(* The operational semantics of Vellvm                       *)\n\nImport LLVMsyntax.\nImport LLVMtd.\nImport LLVMinfra.\nImport LLVMgv.\nImport LLVMtypings.\n\nLemma cgv2gvs__getTypeSizeInBits : forall S los nts gv t sz al,\n  wf_typ S (los,nts) t ->\n  _getTypeSizeInBits_and_Alignment los\n    (getTypeSizeInBits_and_Alignment_for_namedts (los,nts) true) true t =\n      Some (sz, al) ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) = sizeGenericValue gv ->\n  Coqlib.nat_of_Z (Coqlib.ZRdiv (Z_of_nat sz) 8) =\n    sizeGenericValue (LLVMgv.cgv2gv gv t).\nProof.\n  intros.\n  eapply cgv2gv__getTypeSizeInBits; eauto.\nQed.\n\nLemma cundef_gvs__matches_chunks : forall S los nts gv ty,\n  wf_typ S (los,nts) ty ->\n  gv_chunks_match_typ (los, nts) gv ty ->\n  gv_chunks_match_typ (los, nts) (LLVMgv.cundef_gv gv ty) ty.\nProof.\n  intros. subst.\n  eapply cundef_gv__matches_chunks; eauto.\nQed.\n\nLemma cgv2gvs__matches_chunks : forall S los nts gv t,\n  wf_typ S (los,nts) t ->\n  gv_chunks_match_typ (los, nts) gv t ->\n  gv_chunks_match_typ (los, nts) (LLVMgv.cgv2gv gv t) t.\nProof.\n  intros. subst. unfold LLVMgv.cgv2gv.\n  destruct gv; auto.\nQed.\n\nModule OpsemAux.\n\n(**************************************)\n(* This module defines configuration of semantics. A configuration includes\n   the invariants and parameters of semantics. *)\n\n(* The configuration for small-step semantics. *)\nRecord Config : Type := mkCfg {\nCurSystem          : system;        (* programs *)\nCurTargetData      : TargetData;    (* data layouts of the current program *)\nCurProducts        : list product;  (* the currenr program *)\nGlobals            : GVMap;         (* globals *)\n(* FunTable maps function names to their addresses that are taken as function\n   pointers. When we are calling a function via an id, we first search in Globals\n   via the value id to get its address, and then search in FunTable to get its\n   name, via the name, we search in CurProducts to get its definition.\n\n   We assume that there is an 'initFunTable' that returns function addresses to\n   initialize FunTable\n*)\nFunTable           : GVMap \n}.\n\n(* The configuration for big-step semantics. *)\nRecord bConfig : Type := mkbCfg {\nbCurSystem          : system;\nbCurTargetData      : TargetData;\nbCurProducts        : list product;\nbGlobals            : GVMap;\nbFunTable           : GVMap;\nbCurFunction        : fdef\n}.\n\n(* Find the name mapped to fptr from the function table fs. \n\n   To realize it in LLVM, we can try to dynamically cast fptr to Function*,\n   if failed, return None\n   if successeful, we can return this function's name *)\nFixpoint lookupFdefViaGVFromFunTable (fs:GVMap)(fptr:GenericValue): option id :=\nmatch fs with\n| nil => None\n| (id0,gv0)::fs' =>\n  if eq_gv gv0 fptr\n  then Some id0\n  else lookupFdefViaGVFromFunTable fs' fptr\nend.\n\n(* Find the function definition. *)\nDefinition lookupFdefViaPtr (Ps:products) (fs:GVMap) fptr : option fdef :=\n  do fn <- lookupFdefViaGVFromFunTable fs fptr;\n     lookupFdefViaIDFromProducts Ps fn.\n\n(* Find the function declaration of external functions. *)\nDefinition lookupExFdecViaPtr (Ps:products) (fs:GVMap) fptr : option fdec :=\ndo fn <- lookupFdefViaGVFromFunTable fs fptr;\n    match lookupFdefViaIDFromProducts Ps fn with\n    | Some _ => None\n    | None => lookupFdecViaIDFromProducts Ps fn\n    end\n.\n\n(* Initalize a global with name id0, type t, initial value c, and alignment \n   align0. *)\nDefinition initGlobal (TD:TargetData)(gl:GVMap)(Mem:mem)(id0:id)(t:typ)(c:const)\n  (align0:align) : option (GenericValue*mem) :=\n  do tsz <- getTypeAllocSize TD t;\n  do gv <- LLVMgv.const2GV TD gl c;\n     match (malloc_one TD Mem (Size.from_nat tsz) align0) with\n     | Some (Mem', mb) =>\n       do Mem'' <- mstore TD Mem' (blk2GV TD mb) t gv align0;\n       ret (blk2GV TD mb,  Mem'')\n     | None => None\n     end.\n\n(* Initialize targetdata. Mem is used when extraction. *)\nDefinition initTargetData (los:layouts)(nts:namedts)(Mem:mem) : TargetData :=\n  (los, nts).\n\n(* Return the memory location of external functions. *)\nAxiom getExternalGlobal : mem -> id -> option GenericValue.\n\n(* For each function id, the runtime emits an address as a function pointer.\n   It can be realized by taking Function* in LLVM as the address. *)\nAxiom initFunTable : mem -> id -> option GenericValue.\n\n(* Initialized globals and function tables in terms of the definitions in the \n   program Ps. *)\nFixpoint genGlobalAndInitMem (TD:TargetData)(Ps:list product)(gl:GVMap)(fs:GVMap)\n  (Mem:mem) : option (GVMap*GVMap*mem) :=\nmatch Ps with\n| nil => Some (gl, fs, Mem)\n| (product_gvar (gvar_intro id0 _ spec t c align))::Ps' =>\n  match (initGlobal TD gl Mem id0 t c align) with\n  | Some (gv, Mem') =>\n      genGlobalAndInitMem TD Ps' (updateAddAL _ gl id0 gv) fs Mem'\n  | None => None\n  end\n| (product_gvar (gvar_external id0 spec t))::Ps' =>\n  match (getExternalGlobal Mem id0) with\n  | Some gv => genGlobalAndInitMem TD Ps' (updateAddAL _ gl id0 gv) fs Mem\n  | None => None\n  end\n| (product_fdef (fdef_intro (fheader_intro _ _ id0 _ _) _))::Ps' =>\n  match initFunTable Mem id0 with\n  | Some gv => genGlobalAndInitMem TD Ps' (updateAddAL _ gl id0 gv)\n      (updateAddAL _ fs id0 gv) Mem\n  | None => None\n  end\n| (product_fdec (fdec_intro (fheader_intro _ _ id0 _ _) _))::Ps' =>\n  match initFunTable Mem id0 with\n  | Some gv => genGlobalAndInitMem TD Ps' (updateAddAL _ gl id0 gv)\n      (updateAddAL _ fs id0 gv) Mem\n  | None => None\n  end\nend.\n\n(* Properties of lookupFdefViaPtr. *)\nLemma lookupFdefViaPtr_inversion : forall Ps fs fptr f,\n  lookupFdefViaPtr Ps fs fptr = Some f ->\n  exists fn,\n    lookupFdefViaGVFromFunTable fs fptr = Some fn /\\\n    lookupFdefViaIDFromProducts Ps fn = Some f.\nProof.\n  intros.\n  unfold lookupFdefViaPtr in H.\n  destruct (lookupFdefViaGVFromFunTable fs fptr); tinv H.\n  simpl in H. exists i0. eauto.\nQed.\n\nLemma lookupFdefViaPtr_inv : forall Ps fs fv F,\n  lookupFdefViaPtr Ps fs fv = Some F ->\n  InProductsB (product_fdef F) Ps.\nProof.\n  intros.\n  unfold lookupFdefViaPtr in H.\n  destruct (lookupFdefViaGVFromFunTable fs fv); try solve [inversion H].\n  apply lookupFdefViaIDFromProducts_inv in H; auto.\nQed.\n\nLemma lookupFdefViaPtr_uniq : forall los nts Ps fs S fptr F,\n  uniqSystem S ->\n  moduleInSystem (module_intro los nts Ps) S ->\n  lookupFdefViaPtr Ps fs fptr = Some F ->\n  uniqFdef F.\nProof.\n  intros.\n  apply lookupFdefViaPtr_inversion in H1.\n  destruct H1 as [fn [J1 J2]].\n  apply lookupFdefViaIDFromProducts_inv in J2; auto.\n  apply uniqSystem__uniqProducts in H0; auto.\n  eapply uniqProducts__uniqFdef; simpl; eauto.\nQed.\n\nLemma lookupFdefViaPtrInSystem : forall los nts Ps fs S fv F,\n  moduleInSystem (module_intro los nts Ps) S ->\n  lookupFdefViaPtr Ps fs fv = Some F ->\n  productInSystemModuleB (product_fdef F) S (module_intro los nts Ps).\nProof.\n  intros.\n  apply lookupFdefViaPtr_inversion in H0.\n  destruct H0 as [fn [J1 J2]].\n  apply lookupFdefViaIDFromProducts_inv in J2.\n  apply productInSystemModuleB_intro; auto.\nQed.\n\nLemma entryBlockInSystemBlockFdef'' : forall los nts Ps fs fv F S B,\n  moduleInSystem (module_intro los nts Ps) S ->\n  lookupFdefViaPtr Ps fs fv = Some F ->\n  getEntryBlock F = Some B ->\n  blockInSystemModuleFdef B S (module_intro los nts Ps) F.\nProof.\n  intros.\n  apply lookupFdefViaPtr_inversion in H0.\n  destruct H0 as [fn [J1 J2]].\n  apply lookupFdefViaIDFromProducts_inv in J2.\n  apply entryBlockInFdef in H1.\n  apply blockInSystemModuleFdef_intro; auto.\nQed.\n\n(* Properties of lookupExFdecViaPtr. *)\nLemma lookupExFdecViaPtr_inversion : forall Ps fs fptr f,\n  lookupExFdecViaPtr Ps fs fptr = Some f ->\n  exists fn,\n    lookupFdefViaGVFromFunTable fs fptr = Some fn /\\\n    lookupFdefViaIDFromProducts Ps fn = None /\\\n    lookupFdecViaIDFromProducts Ps fn = Some f.\nProof.\n  intros.\n  unfold lookupExFdecViaPtr in H.\n  destruct (lookupFdefViaGVFromFunTable fs fptr); tinv H.\n  simpl in H. exists i0.\n  destruct (lookupFdefViaIDFromProducts Ps i0); inv H; auto.\nQed.\n\n(* Simulation of function tables. *)\nDefinition ftable_simulation mi fs1 fs2 : Prop :=\n  forall fv1 fv2, gv_inject mi fv1 fv2 ->\n    lookupFdefViaGVFromFunTable fs1 fv1 =\n    lookupFdefViaGVFromFunTable fs2 fv2.\n\n(* Assume memory extension preserves function table simulation. *)\nAxiom inject_incr__preserves__ftable_simulation: forall mi mi' fs1 fs2,\n  ftable_simulation mi fs1 fs2 ->\n  inject_incr mi mi' ->\n  ftable_simulation mi' fs1 fs2.\n\nEnd OpsemAux.\n\n(************** Operational semantics *************************************** ***)\n\nModule Opsem.\n\nExport LLVMsyntax.\nExport LLVMtd.\nExport LLVMinfra.\nExport LLVMgv.\nExport LLVMtypings.\nExport OpsemAux.\n\nSection Opsem.\n\nDefinition GVsMap := list (id * GenericValue).\n\n(* Compute the semantic value of a constant. *)\nDefinition const2GV (TD:TargetData) (gl:GVMap) (c:const) : option GenericValue :=\nmatch (_const2GV TD gl c) with\n| None => None\n| Some (gv, ty) => Some (LLVMgv.cgv2gv gv ty)\nend.\n\n(* Compute the semantic value of a program value. *)\nDefinition getOperandValue (TD:TargetData) (v:value) (locals:GVsMap)\n  (globals:GVMap) : option GenericValue :=\nmatch v with\n| value_id id => lookupAL _ locals id\n| value_const c => const2GV TD globals c\nend.\n\n(**************************************)\n(** Execution contexts *)\n\n(* Frames *)\nRecord ExecutionContext : Type := mkEC {\nCurFunction : fdef;                  (* the current function *)\nCurBB       : block;                 (* the current block in CurFunction *)\nCurCmds     : cmds;                  (* cmds to run within CurBB *)\nTerminator  : terminator;            (* the terminator of CurBB *)\nLocals      : GVsMap;                (* LLVM values used in this invocation *)\nAllocas     : list mblock            (* Track memory allocated by alloca *)\n}.\n(* Stacks *)\nDefinition ECStack := list ExecutionContext.\n(* Program states *)\nRecord State : Type := mkState {\nEC                 : ExecutionContext;\nECS                : ECStack;\nMem                : mem\n}.\n\n(* When a program jumps from the block b to a block with phinodes PNs, the\n  function computes the definitions of PNs. *)\nFixpoint getIncomingValuesForBlockFromPHINodes (TD:TargetData)\n  (PNs:list phinode) (b:block) (globals:GVMap) (locals:GVsMap) :\n  option (list (id*GenericValue)) :=\nmatch PNs with\n| nil => Some nil\n| (insn_phi id0 t vls)::PNs =>\n  match (getValueViaBlockFromPHINode (insn_phi id0 t vls) b) with\n  | None => None\n  | Some v =>\n    match (getOperandValue TD v locals globals,\n           getIncomingValuesForBlockFromPHINodes TD PNs b globals locals)\n    with\n    | (Some gv1, Some idgvs) =>\n      if (gv_chunks_match_typb TD gv1 t)\n      then Some ((id0,gv1)::idgvs)\n      else None\n    | _ => None\n    end\n  end\nend.\n\n(* Update locals in terms of the mapping ResultValues. *)\nFixpoint updateValuesForNewBlock (ResultValues:list (id*GenericValue)) (locals:GVsMap)\n  : GVsMap :=\nmatch ResultValues with\n| nil => locals\n| (id, v)::ResultValues' =>\n    updateAddAL _ (updateValuesForNewBlock ResultValues' locals) id v\nend.\n\n(* When a program jumps from the block PrevBB to the block Dest, the function \n   updates locals. *)\nDefinition switchToNewBasicBlock(TD:TargetData) (Dest:block)\n  (PrevBB:block) (globals: GVMap) (locals:GVsMap): option GVsMap :=\n  let PNs := getPHINodesFromBlock Dest in\n  match getIncomingValuesForBlockFromPHINodes TD PNs PrevBB globals locals with\n  | Some ResultValues => Some (updateValuesForNewBlock ResultValues locals)\n  | None => None\n  end.\n\n(* When a program calls a function with parameters lp, the following computes the\n   runtime values of lp. *)\nFixpoint params2GVs (TD:TargetData) (lp:params) (locals:GVsMap) (globals:GVMap) :\n option (list GenericValue) :=\nmatch lp with\n| nil => Some nil\n| (_, v)::lp' =>\n    match (getOperandValue TD v locals globals,\n           params2GVs TD lp' locals globals) with\n    | (Some gv, Some gvs) => Some (gv::gvs)\n    | _ => None\n    end\nend.\n\n(* oResult is the value returned by a external function. rid is the variable\n   that stores the return value. The following updates locals in terms of the\n   type rt of the return value, and noret (whether the function returns). *)\nDefinition exCallUpdateLocals TD (rt:typ) (noret:bool) (rid:id)\n  (oResult:option GenericValue) (lc :GVsMap) : option GVsMap :=\n  match noret with\n  | false =>\n      match oResult with\n      | None => None\n      | Some Result =>\n            match fit_gv TD rt Result with\n            | Some gr => Some (updateAddAL _ lc rid gr)\n            | _ => None\n            end\n      end\n  | true => Some lc\n  end.\n\n(* c' must be a call of a function that returns Result.\n   lc is the local of the callee's function, and lc' is the local of\n   the caller's function. The following updates lc'. *)\nDefinition returnUpdateLocals (TD:TargetData) (c':cmd) (Result:value)\n  (lc lc':GVsMap) (gl:GVMap) : option GVsMap :=\n  match (getOperandValue TD Result lc gl) with\n  | Some gr =>\n      match c' with\n      | insn_call id0 false _ ct _ _ _ =>\n           match (fit_gv TD ct) gr with\n           | Some gr' => Some (updateAddAL _ lc' id0 gr')\n           | _ => None\n           end\n      | insn_call _ _ _ _ _ _ _ => Some lc'\n      | _=> None\n      end\n  | None => None\n  end.\n\n(* Convert the list of values of GEP into runtime values. *)\nFixpoint values2GVs (TD:TargetData) (lv:list (sz * value)) (locals:GVsMap)\n  (globals:GVMap) : option (list GenericValue):=\nmatch lv with\n| nil => Some nil\n| (_, v) :: lv' =>\n  match (getOperandValue TD v locals globals) with\n  | Some GV =>\n    match (values2GVs TD lv' locals globals) with\n    | Some GVs => Some (GV::GVs)\n    | None => None\n    end\n  | None => None\n  end\nend.\n\n(* When a program calls a function with arguments la and the correponding runtime\n   values lg, the following computes the initial locals of the function. \n   When la and lg do not match, for example, calling a function with the wrong\n   signature, it returns none.\n*)\nFixpoint _initializeFrameValues TD (la:args) (lg:list GenericValue) (locals:GVsMap)\n  : option GVsMap :=\nmatch (la, lg) with\n| (((t, _), id)::la', g::lg') =>\n  match _initializeFrameValues TD la' lg' locals,\n        (fit_gv TD t) g with\n  | Some lc', Some gv => Some (updateAddAL _ lc' id gv)\n  | _, _ => None\n  end\n| (((t, _), id)::la', nil) =>\n  (* FIXME: We should initalize them w.r.t their type size. *)\n  match _initializeFrameValues TD la' nil locals, gundef TD t with\n  | Some lc', Some gv => Some (updateAddAL _ lc' id gv)\n  | _, _ => None\n  end\n| _ => Some locals\nend.\n\nDefinition initLocals TD (la:args) (lg:list GenericValue): option GVsMap :=\n_initializeFrameValues TD la lg nil.\n\n(* Operations *)\nDefinition BOP (TD:TargetData) (lc:GVsMap) (gl:GVMap) (op:bop) (bsz:sz)\n  (v1 v2:value) : option GenericValue :=\nmatch (getOperandValue TD v1 lc gl, getOperandValue TD v2 lc gl) with\n| (Some gvs1, Some gvs2) =>\n    (mbop TD op bsz) gvs1 gvs2\n| _ => None\nend\n.\n\nDefinition FBOP (TD:TargetData) (lc:GVsMap) (gl:GVMap) (op:fbop) fp\n  (v1 v2:value) : option GenericValue :=\nmatch (getOperandValue TD v1 lc gl, getOperandValue TD v2 lc gl) with\n| (Some gvs1, Some gvs2) =>\n    (mfbop TD op fp) gvs1 gvs2\n| _ => None\nend\n.\n\nDefinition ICMP (TD:TargetData) (lc:GVsMap) (gl:GVMap) c t (v1 v2:value)\n  : option GenericValue :=\nmatch (getOperandValue TD v1 lc gl, getOperandValue TD v2 lc gl) with\n| (Some gvs1, Some gvs2) =>\n    (micmp TD c t) gvs1 gvs2\n| _ => None\nend\n.\n\nDefinition FCMP (TD:TargetData) (lc:GVsMap) (gl:GVMap) c fp (v1 v2:value)\n  : option GenericValue :=\nmatch (getOperandValue TD v1 lc gl, getOperandValue TD v2 lc gl) with\n| (Some gvs1, Some gvs2) =>\n    (mfcmp TD c fp) gvs1 gvs2\n| _ => None\nend\n.\n\nDefinition SELECT (TD:TargetData) (lc gl:GVMap) (v0 v1 v2:value) (t: typ): option GenericValue :=\n  match (getOperandValue TD v0 lc gl, getOperandValue TD v1 lc gl, getOperandValue TD v2 lc gl) with\n  | (Some gv0, Some gv1, Some gv2) => mselect TD t gv0 gv1 gv2\n  | _ => None (* gundef TD t *)\n           (* for unity *)\n  end\n.\n\nDefinition CAST (TD:TargetData) (lc:GVsMap) (gl:GVMap) (op:castop)\n  (t1:typ) (v1:value) (t2:typ) : option GenericValue:=\nmatch (getOperandValue TD v1 lc gl) with\n| (Some gvs1) => (mcast TD op t1 t2) gvs1\n| _ => None\nend\n.\n\nDefinition TRUNC (TD:TargetData) (lc:GVsMap) (gl:GVMap) (op:truncop)\n  (t1:typ) (v1:value) (t2:typ) : option GenericValue:=\nmatch (getOperandValue TD v1 lc gl) with\n| (Some gvs1) => (mtrunc TD op t1 t2) gvs1\n| _ => None\nend\n.\n\nDefinition EXT (TD:TargetData) (lc:GVsMap) (gl:GVMap) (op:extop)\n  (t1:typ) (v1:value) (t2:typ) : option GenericValue:=\nmatch (getOperandValue TD v1 lc gl) with\n| (Some gvs1) => (mext TD op t1 t2) gvs1\n| _ => None\nend\n.\n\nDefinition GEP (TD:TargetData) (ty:typ) (mas:GenericValue) (vidxs:list GenericValue)\n  (inbounds:bool) ty' : option GenericValue :=\n  (gep TD ty vidxs inbounds ty') mas.\n\nDefinition extractGenericValue (TD:TargetData) (t:typ) (gvs : GenericValue)\n  (cidxs : list const) : option GenericValue :=\nmatch (intConsts2Nats TD cidxs) with\n| None => None\n| Some idxs =>\n  match (mgetoffset TD t idxs) with\n  | Some (o, t') => (mget' TD o t') gvs\n  | None => None\n  end\nend.\n\nDefinition insertGenericValue (TD:TargetData) (t:typ) (gvs:GenericValue)\n  (cidxs:list const) (t0:typ) (gvs0:GenericValue) : option GenericValue :=\nmatch (intConsts2Nats TD cidxs) with\n| None => None\n| Some idxs =>\n  match (mgetoffset TD t idxs) with\n  | Some (o, _) => (mset' TD o t t0) gvs gvs0\n  | None => None\n  end\nend.\n\n(* TODO: position *)\nInductive decide_nonzero (TD:TargetData) (gv:GenericValue) (decision:bool): Prop :=\n| decide_nonzero_intro\n    z \n    (INT: GV2int TD Size.One gv = Some z)\n    (DECISION: decision = negb (zeq z 0))\n.\n\nLemma decide_nonzero_implies_gvzero \n      TD gv decision (IS_ZERO : decide_nonzero TD gv decision) :\n  negb decision = (isGVZero TD gv).\nProof.\n  inversion IS_ZERO.\n  unfold isGVZero. rewrite INT.\n  destruct (zeq z 0); simpl in DECISION; rewrite DECISION; auto.\nQed.\n\nDefinition intConst2Z c :=\n  match c with\n  | const_int sz i =>\n    ret INTEGER.to_Z i\n  | _ => merror\n  end.\n\nDefinition get_switch_branch_aux ValZ cases dflt :=\n  let tgt_: monad (const * l) :=\n      List.find (fun x =>\n                   match intConst2Z (fst x) with\n                   | Some y => Zeq_bool y ValZ\n                   | None => false\n                   end) cases\n  in\n  match tgt_ with\n  | Some (_, tgt) => tgt\n  | None => dflt\n  end.\n\nDefinition get_switch_branch TD ty ValGV cases dflt :=\n  match ty with\n  | typ_int sz =>\n    match GV2int TD sz ValGV with\n    | Some ValZ => Some (get_switch_branch_aux ValZ cases dflt)\n    | None => None\n    end\n  | _ => None\n  end.\n\nLemma get_switch_branch_aux_in_successors\n      id typ val ValGV cases dflt:\n  In (get_switch_branch_aux ValGV cases dflt)\n     (successors_terminator (insn_switch id typ val dflt cases)).\nProof.\n  s. unfold get_switch_branch_aux.\n  match goal with\n  | [|- context[match ?f with | Some _ => _ | None => _ end]] =>\n    destruct f as [[]|] eqn:X\n  end; cycle 1.\n  { destruct (in_dec eq_atom_dec dflt (list_prj2 const l cases)); [|by left].\n    apply nodup_In; eauto.\n  }\n  cut (In l0 (list_prj2 const l cases)).\n  { i. destruct (in_dec eq_atom_dec dflt (list_prj2 const l cases)); ss.\n    - apply nodup_In. ss.\n    - right. apply nodup_In. ss.\n  }\n  exploit find_some; eauto. i. des.\n  revert H. clear. induction cases as [|[]]; ss.\n  i. des.\n  - inv H. left. ss.\n  - right. eauto.\nQed.\n\nLemma get_switch_branch_in_successors\n      id TD typ val ValGV cases dflt l\n      (SWITCH: get_switch_branch TD typ ValGV cases dflt = Some l):\n  In l (successors_terminator (insn_switch id typ val dflt cases)).\nProof.\n  destruct typ; ss. destruct (GV2int TD sz5 ValGV); ss. inv SWITCH.\n  apply get_switch_branch_aux_in_successors; ss. exact (typ_int (sz5)).\nQed.\n\n(***************************************************************)\n(* small-step *)\n\nInductive sInsn : Config -> State -> State -> trace -> Prop :=\n| sReturn : forall S TD Ps F B rid RetTy Result lc gl fs\n                            F' B' c' cs' tmn' lc' ECS\n                            Mem Mem' als als' lc'',\n  Instruction.isCallInst c' = true ->\n  (* FIXME: we should get Result before free?! *)\n  free_allocas TD Mem als = Some Mem' ->\n  returnUpdateLocals TD c' Result lc lc' gl = Some lc'' ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B nil (insn_return rid RetTy Result) lc als)\n              ((mkEC F' B' (c'::cs') tmn' lc' als')::ECS) Mem)\n    (mkState (mkEC F' B' cs' tmn' lc'' als') (ECS) Mem')\n    E0\n\n| sReturnVoid : forall S TD Ps F B rid lc gl fs\n                            F' B' c' tmn' lc' ECS \n                            cs' Mem Mem' als als',\n  Instruction.isCallInst c' = true ->\n  free_allocas TD Mem als = Some Mem' ->\n  getCallerReturnID c' = None ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B nil (insn_return_void rid) lc als)\n              ((mkEC F' B' (c'::cs') tmn' lc' als')::ECS) Mem)\n    (mkState (mkEC F' B' cs' tmn' lc' als') (ECS) Mem')\n    E0 \n\n| sBranch : forall S TD Ps F B lc gl fs bid Cond l1 l2 conds decision\n                              ps' cs' tmn' lc' ECS Mem als,\n  getOperandValue TD Cond lc gl = Some conds ->\n  decide_nonzero TD conds decision ->\n  Some (stmts_intro ps' cs' tmn') =\n  (lookupBlockViaLabelFromFdef F (if decision then l1 else l2)) ->\n  switchToNewBasicBlock TD (if decision then l1 else l2, \n                            stmts_intro ps' cs' tmn') B gl lc = Some lc'->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B nil (insn_br bid Cond l1 l2) lc als) (ECS) Mem)\n    (mkState (mkEC F (if decision then l1 else l2, \n                       stmts_intro ps' cs' tmn') cs' tmn' lc' als) (ECS) Mem)\n    E0 \n\n| sSwitch :\n    forall S TD Ps gl fs\n           ECS Mem\n           F B lc als\n           id ty Val (dflt: l) cases\n           (ValGV: GenericValue)\n           ps' cs' tmn' lc' tgt\n    ,\n      getOperandValue TD Val lc gl = Some ValGV ->\n      get_switch_branch TD ty ValGV cases dflt = Some tgt ->\n      Some (stmts_intro ps' cs' tmn') = lookupBlockViaLabelFromFdef F tgt ->\n      switchToNewBasicBlock TD (tgt, stmts_intro ps' cs' tmn') B gl lc = Some lc'->\n      sInsn (mkCfg S TD Ps gl fs)\n            (mkState (mkEC F B nil (insn_switch id ty Val dflt cases) lc als) (ECS) Mem)\n            (mkState (mkEC F (tgt, stmts_intro ps' cs' tmn') cs' tmn' lc' als) (ECS) Mem)\n            E0\n\n| sBranch_uncond : forall S TD Ps F B lc gl fs bid l\n                           ps' cs' tmn' lc' ECS Mem als,\n  Some (stmts_intro ps' cs' tmn') = (lookupBlockViaLabelFromFdef F l) ->\n  switchToNewBasicBlock TD (l, stmts_intro ps' cs' tmn') B gl lc = Some lc'->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B nil (insn_br_uncond bid l) lc als) (ECS) Mem)\n    (mkState (mkEC F (l, stmts_intro ps' cs' tmn') cs' tmn' lc' als) (ECS) Mem)\n    E0 \n\n| sNop: forall S TD Ps F B lc gl fs id ECS cs tmn Mem als,\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_nop id)::cs) tmn lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn lc als) (ECS) Mem)\n    E0\n\n| sBop: forall S TD Ps F B lc gl fs id bop sz v1 v2 gvs3 ECS cs tmn Mem als,\n  BOP TD lc gl bop sz v1 v2 = Some gvs3 ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_bop id bop sz v1 v2)::cs) tmn lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn (updateAddAL _ lc id gvs3) als) (ECS) Mem)\n    E0 \n\n| sFBop: forall S TD Ps F B lc gl fs id fbop fp v1 v2 gvs3 ECS cs tmn Mem als,\n  FBOP TD lc gl fbop fp v1 v2 = Some gvs3 ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_fbop id fbop fp v1 v2)::cs) tmn lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn (updateAddAL _ lc id gvs3) als) (ECS) Mem)\n    E0 \n\n| sExtractValue : forall S TD Ps F B lc gl fs id t v gvs gvs' idxs ECS cs tmn\n                          Mem als t',\n  getOperandValue TD v lc gl = Some gvs ->\n  extractGenericValue TD t gvs idxs = Some gvs' ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_extractvalue id t v idxs t')::cs) tmn lc als) (ECS)\n               Mem)\n    (mkState (mkEC F B cs tmn (updateAddAL _ lc id gvs') als) (ECS) Mem)\n    E0\n\n| sInsertValue : forall S TD Ps F B lc gl fs id t v t' v' gvs gvs' gvs'' idxs\n                         ECS cs tmn Mem als,\n  getOperandValue TD v lc gl = Some gvs ->\n  getOperandValue TD v' lc gl = Some gvs' ->\n  insertGenericValue TD t gvs idxs t' gvs' = Some gvs'' ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_insertvalue id t v t' v' idxs)::cs) tmn\n                    lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn (updateAddAL _ lc id gvs'') als) (ECS) Mem)\n    E0 \n\n| sMalloc : forall S TD Ps F B lc gl fs id t v gn align ECS cs tmn Mem als\n                    Mem' tsz mb,\n  getTypeAllocSize TD t = Some tsz ->\n  getOperandValue TD v lc gl = Some gn ->\n  malloc TD Mem tsz gn align = Some (Mem', mb) ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_malloc id t v align)::cs) tmn lc als)  (ECS) Mem)\n    (mkState (mkEC F B cs tmn\n                (updateAddAL _ lc id (blk2GV TD mb))\n                als) (ECS) Mem')\n    E0\n\n| sFree : forall S TD Ps F B lc gl fs fid t v ECS cs tmn Mem als Mem' mptr,\n  getOperandValue TD v lc gl = Some mptr ->\n  free TD Mem mptr = Some Mem'->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_free fid t v)::cs) tmn lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn lc als) (ECS) Mem')\n    E0\n\n| sAlloca : forall S TD Ps F B lc gl fs id t v gn align ECS cs tmn Mem als\n                    Mem' tsz mb,\n  getTypeAllocSize TD t = Some tsz ->\n  getOperandValue TD v lc gl = Some gn ->\n  alloca TD Mem tsz gn align = Some (Mem', mb) ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_alloca id t v align)::cs) tmn lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn\n                   (updateAddAL _ lc id (blk2GV TD mb))\n                   (mb::als)) (ECS) Mem')\n    E0\n\n| sLoad : forall S TD Ps F B lc gl fs id t align v ECS cs tmn Mem als mp gv,\n  getOperandValue TD v lc gl = Some mp ->\n  mload TD Mem mp t align = Some gv ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_load id t v align)::cs) tmn lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn (updateAddAL _ lc id gv) als) (ECS) Mem)\n    E0\n\n| sStore : forall S TD Ps F B lc gl fs sid t align v1 v2 ECS cs tmn Mem als\n                   mp2 gv1 Mem',\n  getOperandValue TD v1 lc gl = Some gv1 ->\n  getOperandValue TD v2 lc gl = Some mp2 ->\n  mstore TD Mem mp2 t gv1 align = Some Mem' ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_store sid t v1 v2 align)::cs) tmn lc als) (ECS)\n               Mem)\n    (mkState (mkEC F B cs tmn lc als) (ECS) Mem')\n    E0\n\n| sGEP : forall S TD Ps F B lc gl fs id inbounds t v idxs vidxs ECS mp mp'\n                 cs tmn Mem als t',\n  getOperandValue TD v lc gl = Some mp ->\n  values2GVs TD idxs lc gl = Some vidxs ->\n  GEP TD t mp vidxs inbounds t' = Some mp' ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_gep id inbounds t v idxs t')::cs) \n                 tmn lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn (updateAddAL _ lc id mp') als) (ECS) Mem)\n    E0 \n\n| sTrunc : forall S TD Ps F B lc gl fs id truncop t1 v1 t2 gvs2 ECS cs tmn\n                   Mem als,\n  TRUNC TD lc gl truncop t1 v1 t2 = Some gvs2 ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_trunc id truncop t1 v1 t2)::cs) tmn lc als) (ECS)\n               Mem)\n    (mkState (mkEC F B cs tmn (updateAddAL _ lc id gvs2) als) (ECS) Mem)\n    E0\n\n| sExt : forall S TD Ps F B lc gl fs id extop t1 v1 t2 gvs2 ECS cs tmn Mem\n                 als,\n  EXT TD lc gl extop t1 v1 t2 = Some gvs2 ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_ext id extop t1 v1 t2)::cs) tmn lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn (updateAddAL _ lc id gvs2) als) (ECS) Mem)\n    E0\n\n| sCast : forall S TD Ps F B lc gl fs id castop t1 v1 t2 gvs2 ECS cs tmn Mem\n                  als,\n  CAST TD lc gl castop t1 v1 t2 = Some gvs2 ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_cast id castop t1 v1 t2)::cs) tmn lc als) (ECS)\n               Mem)\n    (mkState (mkEC F B cs tmn (updateAddAL _ lc id gvs2) als) (ECS) Mem)\n    E0\n\n| sIcmp : forall S TD Ps F B lc gl fs id cond t v1 v2 gvs3 ECS cs tmn Mem als,\n  ICMP TD lc gl cond t v1 v2 = Some gvs3 ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_icmp id cond t v1 v2)::cs) tmn lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn (updateAddAL _ lc id gvs3) als) (ECS) Mem)\n    E0\n\n| sFcmp : forall S TD Ps F B lc gl fs id fcond fp v1 v2 gvs3 ECS cs tmn Mem\n                  als,\n  FCMP TD lc gl fcond fp v1 v2 = Some gvs3 ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_fcmp id fcond fp v1 v2)::cs) tmn lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn (updateAddAL _ lc id gvs3) als) (ECS) Mem)\n    E0\n\n| sSelect : forall S TD Ps F B lc gl fs id v0 t v1 v2 ECS cs tmn Mem als gvresult,\n    SELECT TD lc gl v0 v1 v2 t = Some gvresult ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_select id v0 t v1 v2)::cs) tmn lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn (updateAddAL _ lc id gvresult) als) (ECS) Mem)\n    E0\n\n| sCall : forall S TD Ps F B lc gl fs rid noret ca fid fv lp cs tmn fptr\n                 lc' l' ps' cs' tmn' ECS rt la va lb Mem als rt1 va1 fa gvs,\n  (* only look up the current module for the time being,\n     do not support linkage. *)\n  getOperandValue TD fv lc gl = Some fptr ->\n  lookupFdefViaPtr Ps fs fptr =\n    Some (fdef_intro (fheader_intro fa rt fid la va) lb) ->\n  getEntryBlock (fdef_intro (fheader_intro fa rt fid la va) lb) =\n    Some (l', stmts_intro ps' cs' tmn') ->\n  params2GVs TD lp lc gl = Some gvs ->\n  initLocals TD la gvs = Some lc' ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_call rid noret ca rt1 va1 fv lp)::cs) tmn\n                       lc als) ECS Mem)\n    (mkState (mkEC (fdef_intro (fheader_intro fa rt fid la va) lb)\n                       (l', stmts_intro ps' cs' tmn') cs' tmn' lc' nil)\n              ((mkEC F B ((insn_call rid noret ca rt1 va1 fv lp)::cs) tmn\n                       lc als)::ECS) Mem)\n    E0 \n\n| sExCall : forall S TD Ps F B lc gl fs rid noret ca fid fv lp cs tmn ECS dck\n       rt la Mem als oresult Mem' lc' va rt1 va1 fa gvs fptr tr,\n  (* only look up the current module for the time being,\n     do not support linkage.\n     FIXME: should add excall to trace\n  *)\n  getOperandValue TD fv lc gl = Some fptr ->\n  lookupExFdecViaPtr Ps fs fptr =\n    Some (fdec_intro (fheader_intro fa rt fid la va) dck) ->\n  params2GVs TD lp lc gl = Some gvs ->\n  callExternalOrIntrinsics TD gl Mem fid rt (args2Typs la) dck gvs = \n    Some (oresult, tr, Mem') ->\n  exCallUpdateLocals TD rt1 noret rid oresult lc = Some lc' ->\n  sInsn (mkCfg S TD Ps gl fs)\n    (mkState (mkEC F B ((insn_call rid noret ca rt1 va1 fv lp)::cs) tmn\n                       lc als) (ECS) Mem)\n    (mkState (mkEC F B cs tmn lc' als) (ECS) Mem')\n    tr\n.\n\n(* Given the entry of main with input Args, the following initializes the \n   program S. *)\nDefinition s_genInitState (S:system) (main:id) (Args:list GenericValue) (initmem:mem)\n  : option (Config * State) :=\nmatch (lookupFdefViaIDFromSystem S main) with\n| None => None\n| Some CurFunction =>\n  match (getParentOfFdefFromSystem CurFunction S) with\n  | None => None\n  | Some (module_intro CurLayouts CurNamedts CurProducts) =>\n    let initargetdata :=\n      initTargetData CurLayouts CurNamedts initmem in\n    match (genGlobalAndInitMem initargetdata CurProducts nil nil\n      initmem) with\n    | None => None\n    | Some (initGlobal, initFunTable, initMem) =>\n      match (getEntryBlock CurFunction) with\n      | None => None\n      | Some (l, stmts_intro ps cs tmn) =>\n          match CurFunction with\n          | fdef_intro (fheader_intro _ rt _ la _) _ =>\n            match initLocals initargetdata la Args with\n            | Some Values =>\n              Some\n              (mkCfg\n                S\n                initargetdata\n                CurProducts\n                initGlobal\n                initFunTable,\n               mkState\n                (mkEC\n                  CurFunction\n                  (l, stmts_intro ps cs tmn)\n                  cs\n                  tmn\n                  Values\n                  nil\n                )\n                nil \n                initMem\n              )\n            | None => None\n            end\n        end\n      end\n    end\n  end\nend.\n\nDefinition GV2Vint (gv: GenericValue): option val :=\n  match gv with\n  | (Vint wz i, _) :: nil => Some (Vint wz i)\n  | _ => None\n  end\n.\n\nDefinition s_isFinalState (cfg: Config) (state: State): option val :=\n  match (match state with\n   | (mkState (mkEC _ _ nil (insn_return_void _) _ _) nil Mem ) => \n     (* This case cannot be None at any context. *)\n     const2GV (OpsemAux.CurTargetData cfg) (OpsemAux.Globals cfg) \n              (const_int Size.One (INTEGER.of_Z 1%Z 1%Z false))\n   | (mkState (mkEC _ _ nil (insn_return _ _ v) lc _) nil Mem ) => \n     (* This case cannot be None at well-formed context. \n       In other words, if a program reaches here, but returns None, \n       the program is stuck. *)\n     getOperandValue (OpsemAux.CurTargetData cfg) v lc \n                     (OpsemAux.Globals cfg)\n   | _ => None\n   end) with\n  | Some gv => GV2Vint gv\n  | None => None\n  end\n.\n\n(* >=0 small steps *)\nInductive sop_star (cfg:Config) : State -> State -> trace -> Prop :=\n| sop_star_nil : forall state, sop_star cfg state state E0\n| sop_star_cons : forall state1 state2 state3 tr1 tr2,\n    sInsn cfg state1 state2 tr1 ->\n    sop_star cfg state2 state3 tr2 ->\n    sop_star cfg state1 state3 (Eapp tr1 tr2)\n.\n\n(* >=1 small steps *)\nInductive sop_plus (cfg:Config) : State -> State -> trace -> Prop :=\n| sop_plus_cons : forall state1 state2 state3 tr1 tr2,\n    sInsn cfg state1 state2 tr1 ->\n    sop_star cfg state2 state3 tr2 ->\n    sop_plus cfg state1 state3 (Eapp tr1 tr2)\n.\n\n(* Three definitions of divergence. They are used for different proofs.\n   We prove that they are equivalent. *)\nCoInductive sop_diverges (cfg:Config) : State -> traceinf -> Prop :=\n| sop_diverges_intro : forall state1 state2 tr1 tr2,\n    sop_plus cfg state1 state2 tr1 ->\n    sop_diverges cfg state2 tr2 ->\n    sop_diverges cfg state1 (Eappinf tr1 tr2)\n.\n\nCoInductive sop_diverges' (cfg:Config): State -> traceinf -> Prop :=\n| sop_diverges_intro' : forall state1 state2 tr1 tr2,\n    Opsem.sInsn cfg state1 state2 tr1 ->\n    sop_diverges' cfg state2 tr2 ->\n    sop_diverges' cfg state1 (Eappinf tr1 tr2).\n\nSection SOP_WF_DIVERGES.\n\nVariable Measure: Type.\nVariable R:Measure -> Measure -> Prop.\nHypothesis Hwf_founded_R: well_founded R.\n\nCoInductive sop_wf_diverges (cfg:Config): Measure -> State -> traceinf -> Prop:=\n| sop_wf_diverges_plus : forall m1 m2 state1 state2 tr1 tr2,\n    Opsem.sop_plus cfg state1 state2 tr1 ->\n    sop_wf_diverges cfg m2 state2 tr2 ->\n    sop_wf_diverges cfg m1 state1 (Eappinf tr1 tr2)\n| sop_wf_diverges_star : forall m1 m2 state1 state2 tr1 tr2,\n    R m2 m1 ->\n    Opsem.sop_star cfg state1 state2 tr1 ->\n    sop_wf_diverges cfg m2 state2 tr2 ->\n    sop_wf_diverges cfg m1 state1 (Eappinf tr1 tr2)\n.\n\nEnd SOP_WF_DIVERGES.\n\n(* A program terminates if its initial state reaches a final state. *)\nInductive s_converges : system -> id -> list GenericValue -> trace -> val -> Prop :=\n| s_converges_intro : forall (s:system) (main:id) (VarArgs:list GenericValue)    \n                              cfg (IS FS:Opsem.State) r tr,\n  s_genInitState s main VarArgs Mem.empty = Some (cfg, IS) ->\n  sop_star cfg IS FS tr ->\n  s_isFinalState cfg FS = Some r ->\n  s_converges s main VarArgs tr r\n.\n\n(* A program non-terminates if its initial state diverges. *)\nInductive s_diverges : system -> id -> list GenericValue -> traceinf -> Prop :=\n| s_diverges_intro : forall (s:system) (main:id) (VarArgs:list GenericValue)\n                             cfg (IS:State) tr,\n  s_genInitState s main VarArgs Mem.empty = Some (cfg, IS) ->\n  sop_diverges cfg IS tr ->\n  s_diverges s main VarArgs tr\n.\n\n(* A state is stuck if it cannot step. *)\nDefinition stuck_state (cfg:OpsemAux.Config) (st:State) : Prop :=\n~ exists st', exists tr, sInsn cfg st st' tr.\n\n(* A program terminates if its initial state reaches a non-final stuck state. *)\nInductive s_goeswrong : system -> id -> list GenericValue -> trace -> State -> Prop :=\n| s_goeswrong_intro : forall (s:system) (main:id) (VarArgs:list GenericValue)\n                              cfg (IS FS:State) tr,\n  s_genInitState s main VarArgs Mem.empty = Some (cfg, IS) ->\n  sop_star cfg IS FS tr ->\n  stuck_state cfg FS ->\n  s_isFinalState cfg FS = None ->\n  s_goeswrong s main VarArgs tr FS\n.\n\nEnd Opsem.\n\nHint Constructors sInsn sop_star sop_diverges sop_plus.\n\nEnd Opsem.\n\nTactic Notation \"sInsn_cases\" tactic(first) tactic(c) :=\n  first;\n  [ c \"sReturn\" | c \"sReturnVoid\" | c \"sBranch\" | c \"sSwitch\" | c \"sBranch_uncond\" |\n    c \"sNop\" |\n    c \"sBop\" | c \"sFBop\" | c \"sExtractValue\" | c \"sInsertValue\" |\n    c \"sMalloc\" | c \"sFree\" |\n    c \"sAlloca\" | c \"sLoad\" | c \"sStore\" | c \"sGEP\" |\n    c \"sTrunc\" | c \"sExt\" |\n    c \"sCast\" |\n    c \"sIcmp\" | c \"sFcmp\" | c \"sSelect\" |\n    c \"sCall\" | c \"sExCall\" ].\n\nTactic Notation \"b_mutind_cases\" tactic(first) tactic(c) :=\n  first;\n  [ c \"bBranch\" | c \"bBranch_uncond\" |\n    c \"bBop\" | c \"bFBop\" | c \"bExtractValue\" | c \"bInsertValue\" |\n    c \"bMalloc\" | c \"bFree\" |\n    c \"bAlloca\" | c \"bLoad\" | c \"bStore\" | c \"bGEP\" |\n    c \"bTrunc\" | c \"bExt\" | c \"bCast\" | c \"bIcmp\" | c \"bFcmp\" |  c \"bSelect\" |\n    c \"bCall\" | c \"bExCall\" |\n    c \"bops_nil\" | c \"bops_cons\" | c \"bFdef_func\" | c \"bFdef_proc\" ].\n\nTactic Notation \"sop_star_cases\" tactic(first) tactic(c) :=\n  first;\n  [ c \"sop_star_nil\" | c \"sop_star_cons\" ].\n\nLtac simpl_s_genInitState :=\n  match goal with\n  | Hinit: Opsem.s_genInitState _ _ _ _ = _ |- _ =>\n    unfold Opsem.s_genInitState in Hinit;\n    inv_mbind'\n  end;\n  match goal with\n  | m : module |- _ =>\n    destruct m as [CurLayouts CurNamedts CurProducts];\n    inv_mbind'\n  end;\n  match goal with\n  | H: ret (_, ?s0) = getEntryBlock ?f |- _ =>\n    destruct s0 as [ps0 cs0 tmn0];\n    destruct f as [[f t i0 a v] b];\n    inv_mbind'\n  end;\n  try repeat match goal with\n  | H: ret _ = ret _ |- _ => inv H\n  end;\n  symmetry_ctx.\n", "meta": {"author": "snu-sf", "repo": "crellvm-vellvm", "sha": "54c7cc88ab5b4aec4c327f501cac4d9a667ca057", "save_path": "github-repos/coq/snu-sf-crellvm-vellvm", "path": "github-repos/coq/snu-sf-crellvm-vellvm/crellvm-vellvm-54c7cc88ab5b4aec4c327f501cac4d9a667ca057/src/Vellvm/opsem.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.202069214038221}}
{"text": "Require Import Coq.Lists.ListSet.\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.lib.Maps.\n\n(** External function specifications and linking *)\n\nDefinition PTree_injective {A} (t: PTree.t A) : Prop :=\n  forall id1 id2 b, t ! id1 = Some b -> t ! id2 = Some b -> id1 = id2.\n\nDefinition injective_PTree A := sig (@PTree_injective A).\n\nStructure external_specification (M E Z : Type) :=\n  { ext_spec_type : E -> Type\n  ; ext_spec_pre: forall e: E,\n    ext_spec_type e -> injective_PTree block -> list typ -> list val -> Z -> M -> Prop\n  ; ext_spec_post: forall e: E,\n    ext_spec_type e -> injective_PTree block -> option typ -> option val -> Z -> M ->  Prop\n  ; ext_spec_exit: option val -> Z -> M ->  Prop }.\n\nArguments ext_spec_type {M E Z} _ _.\nArguments ext_spec_pre {M E Z} _ _ _ _ _ _ _ _.\nArguments ext_spec_post {M E Z} _ _ _ _ _ _ _ _.\nArguments ext_spec_exit {M E Z} _ _ _ _.\n\nDefinition ext_spec := external_specification mem external_function.\n\nLemma extfunct_eqdec (ef1 ef2 : external_function) : {ef1=ef2} + {~ef1=ef2}.\nProof.\nrepeat decide equality; try apply Integers.Int.eq_dec.\nDefined.\n\nSet Implicit Arguments.\n\nDefinition ef_ext_spec (M Z : Type) :=\n  external_specification M AST.external_function Z.\n\nDefinition spec_of\n  (M Z : Type) (ef : AST.external_function) (spec : ef_ext_spec M Z) :=\n  (ext_spec_pre spec ef, ext_spec_post spec ef).\n\nDefinition oval_inject j (v tv : option val) :=\n  match v, tv with\n    | None, None => True\n    | Some v', Some tv' => Val.inject j v' tv'\n    | _, _ => False\n  end.\n\nModule ExtSpecProperties.\n\nDefinition det (M E Z : Type) (spec : external_specification M E Z) :=\n  forall ef (x x' : ext_spec_type spec ef) ge tys z vals m\n         oty' ov' z' m' oty'' ov'' z'' m'',\n  ext_spec_pre spec ef x ge tys vals z m ->\n  ext_spec_post spec ef x ge oty' ov' z' m' ->\n  ext_spec_pre spec ef x' ge tys vals z m ->\n  ext_spec_post spec ef x' ge oty'' ov'' z'' m'' ->\n  oty'=oty'' /\\ ov'=ov'' /\\ z'=z'' /\\ m'=m''.\n\nRecord closed (Z : Type) (spec : ext_spec Z) :=\n  { P_closed :\n      forall ef (x : ext_spec_type spec ef) ge j tys vals z m tvals tm,\n      ext_spec_pre spec ef x ge tys vals z m ->\n      Val.inject_list j vals tvals ->\n      Mem.inject j m tm ->\n      ext_spec_pre spec ef x ge tys tvals z tm\n  ; Q_closed :\n      forall ef (x : ext_spec_type spec ef) ge j oty ov z m otv tm,\n      ext_spec_post spec ef x ge oty ov z m ->\n      oval_inject j ov otv ->\n      Mem.inject j m tm ->\n      ext_spec_post spec ef x ge oty otv z tm\n  ; exit_closed :\n      forall j ov z m otv tm,\n      ext_spec_exit spec ov z m ->\n      oval_inject j ov otv ->\n      Mem.inject j m tm ->\n      ext_spec_exit spec otv z tm }.\n\nEnd ExtSpecProperties.\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq_projects/VST/sepcomp/extspec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.20205056132793536}}
{"text": "(*CompCert imports*)\nRequire Import Events.\nRequire Import Memory.\nRequire Import Coqlib.\nRequire Import Values.\nRequire Import Maps.\nRequire Import Integers.\nRequire Import AST.\nRequire Import Globalenvs.\nRequire Import Axioms.\n\nRequire Import mem_lemmas. (*needed for definition of mem_forward etc*)\nRequire Import semantics.\nRequire Import semantics_lemmas.\nRequire Import closed_simulations.\nRequire Import closed_safety.\nRequire Import effect_semantics.\n\nImport Wholeprog_sim.\n\nArguments match_state : default implicits.\nArguments core_halted : default implicits.\nArguments core_data : default implicits.\nArguments core_ord : default implicits.\nArguments core_ord_wf : default implicits.\nArguments core_diagram : default implicits.\n\n(** * Closed Simulations Lemmas *)\n\nSection closed_simulations_lemmas.\nContext  {G TG C D M TM Z data : Type}\n         {source : @CoreSemantics G C M}\n         {target : @CoreSemantics TG D TM}\n         {geS : G}\n         {geT : TG}\n         {ge_inv : G -> TG -> Prop}\n         {init_inv : meminj -> G -> list val -> M -> TG -> list val -> TM -> Prop}\n         {halt_inv : structured_injections.SM_Injection ->\n                     G -> val -> M -> TG -> val -> TM -> Prop}\n         (main : val)\n\n  (sim : Wholeprog_sim source target geS geT main ge_inv init_inv halt_inv)\n  (c : C)\n  (d : D)\n  (m : M)\n  (tm: TM)\n\n  (TGT_DET : corestep_fun target)\n  \n  (source_safe : forall n, safeN source geS n c m).\n\nDefinition my_P := fun (x: core_data sim) => \n   forall j (c : C) (d : D) (m : M) (tm : TM),\n   (forall n : nat, safeN source geS n c m) ->\n   match_state sim x j c m d tm ->\n   (exists rv : val, halted source c = Some rv) \\/\n   (exists (cd' : core_data sim) j' (c' : C) (m' : M),\n      corestep_plus source geS c m c' m' /\\\n      ((exists (d' : D) (tm' : TM),\n          corestep_plus target geT d tm d' tm' /\\\n          match_state sim cd' j' c' m' d' tm') \\/\n       (exists rv : val,\n        halted source c' = Some rv \n        /\\ match_state sim cd' j' c' m' d tm))).\n\nLemma corestep_ord:\n  forall cd j,\n  match_state sim cd j c m d tm -> \n  (exists rv, halted source c = Some rv) \\/\n  (exists cd' j' c' m',\n      corestep_plus source geS c m c' m'\n   /\\ ((exists d' tm', corestep_plus target geT d tm d' tm'\n                   /\\ match_state sim cd' j' c' m' d' tm')\n    \\/ (exists rv, halted source c' = Some rv \n                   /\\ match_state sim cd' j' c' m' d tm))).\nProof.\nintros.\nrevert j c d m tm source_safe H.\nassert (my_well_founded_induction\n     : (forall x, (forall y, core_ord sim y x -> my_P y) -> my_P x) ->\n       forall a, my_P a).\n{ apply well_founded_induction; auto. apply (core_ord_wf sim). }\nunfold my_P in my_well_founded_induction.\napply my_well_founded_induction; auto.\nintros.\ncase_eq (halted source c).\nintros.\nsolve[left; exists v; auto].\nintros HALTED_NONE.\nright.\ngeneralize H0 as SAFE; intro.\nspecialize (H0 (S O)); simpl in H0.\nrewrite HALTED_NONE in H0.\ndestruct H0 as [H0 HALL].\ndestruct H0 as [c2 [m2 STEP]].\ngeneralize STEP as STEP'; intro.\neapply core_diagram in STEP; eauto.\ndestruct STEP as [d2 [tm2 [cd2 [j2 [? H2]]]]].\ndestruct H2 as [H2|H2]. exists cd2, j2, c2, m2. split; auto.\nexists O; simpl; exists c2, m2; split; auto.\nsolve[left; exists d2, tm2; split; auto].\ndestruct H2 as [H2 ORD].\nspecialize (H _ ORD j2 c2 d2 m2 tm2).\nassert (SAFE': forall n, safeN source geS n c2 m2).\n  solve[intros n; eapply safe_corestep_forward; eauto].\nspecialize (H SAFE' H0).\ndestruct H2 as [n H2].\ndestruct n. inv H2.\ndestruct H.\ndestruct H as [rv HALTED].\nexists cd2, j2, c2, m2.\nsplit; auto.\nsolve[exists O; simpl; exists c2, m2; split; auto].\nsolve[right; exists rv; split; auto].\ndestruct H as [cd' [j' [c' [m' [STEPN H]]]]].\ndestruct H as [H|H].\ndestruct H as [d' [tm' [TSTEP' MATCH']]].\nexists cd', j', c', m'.\nsplit; auto. \ndestruct STEPN as [n STEPN].\nexists (S n).\nsimpl.\nexists c2, m2.\nsplit; auto.\nsolve[left; exists d', tm'; split; auto].\ndestruct H as [rv [HALT MATCH']].\nexists cd', j', c', m'.\nsplit; auto. \ndestruct STEPN as [n STEPN].\nexists (S n).\nsimpl.\nexists c2, m2.\nsplit; auto.\nsolve[right; exists rv; split; auto].\nexists cd2, j2, c2, m2.\nsplit; auto. \nsolve[exists O; simpl; exists c2, m2; split; auto].\nleft. \nexists d2, tm2.\nsplit; auto.\nexists n; auto.\nQed.\n\nDefinition halt_match c d := \n  exists rv trv, \n    halted source c = Some rv \n    /\\ halted target d = Some trv.\n\nLemma corestep_ord':\n  forall cd j,\n  match_state sim cd j c m d tm -> \n  halt_match c d\n  \\/ (exists cd' j' c' m', \n         corestep_plus source geS c m c' m' \n         /\\ ((match_state sim cd' j' c' m' d tm /\\ halt_match c' d)\n            \\/ (exists d' tm', \n                  corestep_plus target geT d tm d' tm'\n                  /\\ match_state sim cd' j' c' m' d' tm'))).\nProof.\nintros.\ngeneralize H as MATCH; intro.\napply corestep_ord in H.\ndestruct H.\n{\ndestruct H as [rv HALT].\nleft.\nunfold halt_match.\ngeneralize HALT as HALT'; intro.\napply (core_halted sim cd j c m d tm) in HALT; auto.\ndestruct HALT as [j' [rv' [INJ HALT]]].\nexists rv, rv'.\nsplit; auto.\n}\n{\ndestruct H as [cd' [j' [c' [m' [STEPN ?]]]]].\ndestruct H as [H|H].\ndestruct H as [d' [tm' [TSTEPN MATCH']]].\nright.\nexists cd', j', c', m'.\nsplit; auto.\nright.\nexists d', tm'.\nsolve[split; auto].\ndestruct H as [rv [HALT MATCH']].\nright.\nexists cd', j', c', m'.\nsplit; auto.\nleft.\nsplit; auto.\nunfold halt_match.\ngeneralize HALT as HALT'; intro.\napply (core_halted sim cd' j' c' m' d tm) in HALT; auto.\ndestruct HALT as [j'' [rv' [INJ HALT]]].\nexists rv, rv'.\nsplit; auto.\n}\nQed.\n\nEnd closed_simulations_lemmas.\n\nLemma corestepN_splits_lt \n       {G C M} (csem : CoreSemantics G C M) (ge : G)\n       c m c' m' c'' m'' n1 n2 :\n  corestep_fun csem -> \n  corestepN csem ge (S n1) c m c' m' -> \n  corestepN csem ge n2 c m c'' m'' -> \n  (S n1 <= n2)%nat -> \n  exists a b,\n    a = S n1\n    /\\ (b=0 -> a=n2)%nat\n    /\\ n2 = plus a b \n    /\\ corestepN csem ge a c m c' m'\n    /\\ corestepN csem ge b c' m' c'' m''.\nProof.\nintros FN H1 H2 LT.\nrevert c m n1 H1 H2 LT.\ninduction n2; intros.\ndestruct n1; try inv LT.\ndestruct n1.\ndestruct H1 as [c2' [m2' [STEP STEPN]]].\ninv STEPN.\nexists (S O), n2.\nsplit; try omega.\nsplit; try omega.\ndestruct H2 as [c2'' [m2'' [STEP' STEPN']]].\ndestruct (FN _ _ _ _ _ _ _ STEP STEP').\nsubst c2'' m2''.\nsplit; auto.\nsplit; auto.\nexists c',m'. \nsplit; simpl; auto.\nassert (n1 < n2)%nat by omega.\ndestruct H1 as [c2 [m2 [STEP STEPN]]].\ndestruct H2 as [c2' [m2' [STEP' STEPN']]].\nassert (c2'=c2 /\\ m2=m2') as [? ?].\n  { destruct (FN _ _ _ _ _ _ _ STEP STEP').\n    subst c2 m2; split; auto. }\nsubst c2' m2; auto.\ndestruct (IHn2 c2 m2' n1); auto.\ndestruct H0 as [n1' [H0 [H1 [H2 [H3 H4]]]]].\nexists (S x), n1'.\nsplit; auto.\nsplit. omega.\nsplit; auto. omega.\nsplit; auto.\nexists c2,m2'.\nsplit; auto.\nQed.\n\nLemma corestepN_splits_lt' \n       {G C M} (csem : CoreSemantics G C M) (ge : G)\n       c m c' m' c'' m'' n1 n2 :\n  corestep_fun csem -> \n  corestepN csem ge n1 c m c' m' -> \n  corestepN csem ge n2 c m c'' m'' -> \n  (n1 <= n2)%nat -> \n  exists q,\n       n2 = plus n1 q \n    /\\ corestepN csem ge n1 c m c' m'\n    /\\ corestepN csem ge q c' m' c'' m''.\nProof.\nintros.\ndestruct n1.\nsimpl. exists n2. split; auto. simpl in H0. split; auto. inv H0; auto.\ndestruct (corestepN_splits_lt csem ge c m c' m' c'' m'' n1 n2 H H0 H1 H2) \n as (a&b&H3&H4&H5&H6&H7).\nexists b; split; auto. omega.\nQed.\n\n(** ** Closed Simulation Implies Equitermination *)\n\nSection termination_preservation.\nContext  {G TG C D M TM Z data : Type}\n         {source : @CoreSemantics G C M}\n         {target : @CoreSemantics TG D TM}\n         {geS : G}\n         {geT : TG}\n         {ge_inv : G -> TG -> Prop}\n         {init_inv : meminj -> G -> list val -> M -> TG -> list val -> TM -> Prop}\n         {halt_inv : structured_injections.SM_Injection ->\n                     G -> val -> M -> TG -> val -> TM -> Prop}\n         (main : val)\n\n  (sim : Wholeprog_sim source target geS geT main ge_inv init_inv halt_inv).\n\nLemma termination_preservation:\n  forall cd c m d tm j c' m' rv1,\n  match_state sim cd j c m d tm -> \n  corestep_star source geS c m c' m' -> \n  halted source c' = Some rv1 -> \n  terminates target geT d tm.\nProof.\nintros.\ndestruct H0 as [n H0].\nrevert cd j c m d tm H H0.\ninduction n; intros.\nsimpl in H0. symmetry in H0; inv H0.\ncut (@halt_match G _ C D _ _ source target c d). intro.\nunfold halt_match in H0.\ndestruct H0 as [rv [trv [? ?]]].\nexists d, tm; split; auto. \nsolve[exists O; simpl; auto].\nsolve[exists trv; auto].\ngeneralize H1 as H1'; intro.\neapply core_halted in H1; eauto. \ndestruct H1 as [? [rv2 [? ?]]].\nexists rv1, rv2; split; auto.\nsimpl in H0.\ndestruct H0 as [c2 [m2 [STEP STEPN]]].\ngeneralize STEP as STEP'; intro.\napply corestep_not_halted in STEP.\neapply core_diagram in STEP'; eauto.\ndestruct STEP' as [? [? [cd' [j' [MATCH ?]]]]].\nclear H.\ndestruct H0 as [X|[X Y]].\neapply IHn in MATCH; eauto.\nunfold terminates in MATCH|-*.\ndestruct MATCH as [x' [tm' [Y [v W]]]].\nexists x', tm'; split; eauto.\neapply corestep_star_trans; eauto.\nsolve[eapply corestep_plus_star; eauto].\neapply IHn in MATCH; eauto.\nunfold terminates in MATCH|-*.\ndestruct MATCH as [x' [tm' [U [v W]]]].\nexists x', tm'; split; eauto.\nsolve[eapply corestep_star_trans; eauto].\nQed.\n\nEnd termination_preservation.\n\nSection equitermination.\nContext  {G TG C D M TM Z data : Type}\n         {source : @CoreSemantics G C M}\n         {target : @CoreSemantics TG D TM}\n         {geS : G}\n         {geT : TG}\n         {ge_inv : G -> TG -> Prop}\n         {init_inv : meminj -> G -> list val -> M -> TG -> list val -> TM -> Prop}\n         {halt_inv : structured_injections.SM_Injection ->\n                     G -> val -> M -> TG -> val -> TM -> Prop}\n         (main : val)\n\n  (sim : Wholeprog_sim source target geS geT main ge_inv init_inv halt_inv)\n  (TGT_DET : corestep_fun target).\n\nLemma termination_reflection:\n  forall n c m d tm cd j d' tm' hv'\n    (source_safe : forall n, safeN source geS n c m),\n    match_state sim cd j c m d tm -> \n    corestepN target geT n d tm d' tm' ->\n    halted target d' = Some hv' -> \n    terminates source geS c m.\nProof.\nset (my_P := fun (n : nat) => \n   forall (c : C) (m : M) (d : D) (tm : TM) \n     (cd : core_data sim) (j : structured_injections.SM_Injection) \n     (d' : D) (tm' : TM) (hv' : val),\n   (forall n0 : nat, safeN source geS n0 c m) ->\n   match_state sim cd j c m d tm ->\n   corestepN target geT n d tm d' tm' ->\n   halted target d' = Some hv' -> terminates source geS c m).\napply (@well_founded_induction _ _ lt_wf my_P); auto.\nunfold my_P; clear my_P; intros n IH.\n\nintros c m d tm cd j d' tm' hv' safe MATCH TSTEPN HLT2. \napply (corestep_ord' main sim c d m tm) in MATCH; auto. \ndestruct MATCH as [HLT|H]. \ndestruct HLT as [rv [_ [HLT _]]]; exists c,m. split. \nexists O; simpl; auto. solve[exists rv; auto].\ndestruct H as [cd' [j' [c2 [m2 [STEPN H]]]]]. destruct H as [[H H2]|H].\ndestruct H2 as [rv [_ [HLT _]]].\ndestruct STEPN as [n2 STEPN]. \nexists c2,m2. split; auto. exists (S n2); simpl; auto. solve[exists rv; auto].\n\ndestruct H as [d2 [tm2 [[n2 TSTEPN2] MTCH2]]].\ndestruct (lt_dec n2 n) as [pf|pf].\n{ assert (TSTEPN': exists n2', (n2' < n)%nat \n    /\\ corestepN target geT n2' d2 tm2 d' tm').\n  { destruct (corestepN_splits_lt target geT d tm d2 tm2 d' tm' n2 n TGT_DET\n              TSTEPN2 TSTEPN pf)\n      as [a [b [alt [neq [X [Y U]]]]]].\n    exists b; split; auto. omega. }\n  destruct TSTEPN' as [n2' [ltpf TSTEPN']].\n  assert (safe': forall n, safeN source geS n c2 m2). \n  { destruct STEPN as [q STEPN].\n    intros n0; eapply safe_corestepN_forward; eauto. }\n  destruct (IH n2' ltpf c2 m2 d2 tm2 cd' j' d' tm' hv' safe' MTCH2 TSTEPN' HLT2)\n    as [c0 [m0 [[q STEPN1] [hv0 HLT1]]]].\n  destruct STEPN as [q' STEPN]. exists c0,m0; split; auto. \n  eapply corestep_star_trans. exists (S q'); eauto. exists q; auto.\n  exists hv0; auto. }\n{ assert (lt: (n < S n2)%nat) by omega. clear pf.\n  destruct n. inv TSTEPN. simpl in TSTEPN2. \n  destruct TSTEPN2 as [? [? [X _]]]; apply corestep_not_halted in X.\n  rewrite X in HLT2; congruence.\n  destruct (corestepN_splits_lt target geT d tm d' tm' d2 tm2 n (S n2) TGT_DET\n              TSTEPN TSTEPN2)\n      as [a [b [alt [neq [X [Y W]]]]]]. omega.\n  destruct b. subst. rewrite neq in lt; auto. omega. \n  simpl in W. destruct W as [? [? [W _]]].\n  apply corestep_not_halted in W; rewrite W in HLT2; congruence. }\nQed.\n\nLemma equitermination:\n  forall cd c m d tm j\n  (source_safe : forall n, safeN source geS n c m),\n  match_state sim cd j c m d tm -> \n  (terminates source geS c m <-> terminates target geT d tm).\nProof.\nintros; split; intros [? [? [A [? B]]]].\neapply termination_preservation; eauto.\ndestruct A as [n A]; eapply termination_reflection; eauto.\nQed.\n\nEnd equitermination.\n\nSection safety_preservation.\nContext  {F V TF TV C D Z data : Type}.\nLet G := Genv.t F V.\nLet TG := Genv.t TF TV.\nContext  {source : @CoreSemantics G C mem}\n         {target : @CoreSemantics TG D mem}\n         {geS : G}\n         {geT : TG}\n         {ge_inv : G -> TG -> Prop}\n         {init_inv : meminj -> G -> list val -> mem -> TG -> list val -> mem -> Prop}\n         {halt_inv : structured_injections.SM_Injection ->\n                     G -> val -> mem -> TG -> val -> mem -> Prop}\n         (main : val)\n\n  (sim : Wholeprog_sim source target geS geT main ge_inv init_inv halt_inv)\n  (TGT_DET : corestep_fun target).\n\nLemma safety_preservation:\n  forall\n  (c : C)\n  (d : D)\n  (m : mem)\n  (tm: mem)\n  (MATCH : exists cd j, match_state sim cd j c m d tm)\n  (source_safe : forall n, safeN source geS n c m),\n\n  (forall n, safeN target geT n d tm).\nProof.\nintros until n.\ndestruct MATCH as [cd [j MATCH2]].\nrevert cd j c m d tm MATCH2 source_safe.\ninduction n; simpl; auto.\nintros.\napply (corestep_ord' main sim c d m tm) in MATCH2; auto.\ndestruct MATCH2 as [H|H].\ndestruct H as [rv [rv' [H1 H2]]].\nrewrite H2; auto.\ndestruct H as [cd' [j' [c' [m' [STEPN [[H1 H2]|H]]]]]].\ndestruct H2 as [rv [rv' [A1 A2]]].\nrewrite A2; auto.\ndestruct H as [d' [tm' [TSTEPN MATCH']]].\ndestruct TSTEPN as [n0 TSTEPN].\ncut (halted target d = None). intros ->.\nsimpl in TSTEPN.\ndestruct TSTEPN as [d2 [tm2 [TSTEP TSTEPN]]].\nsplit.\nexists d2, tm2; auto.\ncut (safeN target geT (n - n0) d' tm'). intros SAFE d'' tm'' TSTEP'.\ndestruct (TGT_DET _ _ _ _ _ _ _ TSTEP TSTEP').\nsubst d''; subst tm''.\napply (@safe_corestepN_backward _ _ _ _ _ _ _ _ _ _ _ TGT_DET TSTEPN SAFE).\ncut (safeN target geT n d' tm'). intro.\napply safe_downward with (n' := (n - n0)%nat) in H.\napply H. omega.\napply (IHn _ _ _ _ _ _ MATCH').\nintros n1.\ndestruct STEPN as [n2 STEPN].\nspecialize (source_safe (n1 + (S (S n2)))%nat).\ngeneralize @safe_corestepN_forward. intro FORW.\nsolve[apply (FORW _ _ _ _ _ _ _ _ _ _ _ STEPN source_safe)].\nsimpl in TSTEPN.\ndestruct TSTEPN as [d2 [tm2 [STEP ?]]].\nsolve[apply corestep_not_halted in STEP; auto].\nQed.\n\nLemma halted_safe (SRC_DET : corestep_fun source): \n  forall c m c' m' (P: val -> mem -> Prop) rv, \n  corestep_star source geS c m c' m' -> \n  halted source c' = Some rv -> \n  (forall n, safeN source geS n c m).\nProof.\nintros.\ndestruct H as [n0 H].\nrevert c m H H0.\ninduction n0.\nsimpl. intros. inv H.\ndestruct n; simpl; auto.\nsolve[rewrite H0; auto].\nsimpl.\nintros c0 m0 [c2 [m2 [STEP STEPN]]] HALTED.\neapply (safe_corestep_backward SRC_DET); eauto.\ngeneralize (IHn0 _ _ STEPN HALTED); intros SAFEN.\neapply safe_downward with (n := n); auto; omega.\nQed.\n\nLemma halted_same_num_steps d tm d' tm' d'' tm'' rv rv' n n' :\n  corestepN target geT n d tm d' tm' -> \n  corestepN target geT n' d tm d'' tm'' -> \n  halted target d' = Some rv -> \n  halted target d'' = Some rv' -> \n  n=n'.\nProof.\nrevert d tm n'; induction n.\nintros d tm. simpl. inversion 1; subst. \ndestruct n'. simpl. inversion 1; subst; auto.\nsimpl. intros [d2 [m2 [STEP STEP']]] HALT HALT'.\napply corestep_not_halted in STEP.\nrewrite HALT in STEP; congruence.\nintros.\ndestruct H as [d2 [tm2 [H H']]].\ndestruct n'.\nsimpl in H0. inv H0. \napply corestep_not_halted in H.\nrewrite H2 in H; congruence.\nerewrite IHn; eauto.\ndestruct H0 as [d2' [tm2' [? ?]]].\ngeneralize (TGT_DET _ _ _ _ _ _ _ H H0).\ninversion 1; subst; auto.\nQed.\n\nEnd safety_preservation.\n\nSection behavior_refinement.\nContext  {F V TF TV C D Z data : Type}.\nLet G := Genv.t F V.\nLet TG := Genv.t TF TV.\nContext  {source : @CoreSemantics G C mem}\n         {target : @CoreSemantics TG D mem}\n         {geS : G}\n         {geT : TG}\n         {ge_inv : G -> TG -> Prop}\n         {init_inv : meminj -> G -> list val -> mem -> TG -> list val -> mem -> Prop}\n         {halt_inv : structured_injections.SM_Injection ->\n                     G -> val -> mem -> TG -> val -> mem -> Prop}\n         (main : val)\n\n  (sim : Wholeprog_sim source target geS geT main ge_inv init_inv halt_inv)\n  (TGT_DET : corestep_fun target).\n\nLemma behavior_refinement:\n  forall em : ClassicalFacts.excluded_middle, (* proof can probably be done without EM *)\n  forall c d m tm tbeh (MATCH : exists cd j, match_state sim cd j c m d tm),\n  has_behavior target geT d tm tbeh -> \n  exists beh, has_behavior source geS c m beh /\\ behavior_refines tbeh beh.\nProof.\nintros until tbeh; intros [cd [j MATCH]].\ncut (safe source geS c m \\/ ~safe source geS c m).\n{ intros [Safe|Nsafe].\n  { (*safe*) inversion 1; subst.\n    exists Termination; split; try constructor.\n    solve[erewrite equitermination; eauto].\n    assert (~terminates source geS c m). \n    { intros nterm. erewrite equitermination in nterm; eauto. }\n    exists Divergence; split; try constructor; auto.\n    solve[apply safe_forever_steps_or_halted; auto].\n    elimtype False; apply H0.\n    solve[intros n; eapply safety_preservation in Safe; eauto]. }\n  { (*not safe*) intros. exists Going_wrong. split; try constructor; auto. }}\n{ apply em. }\nQed.    \n\nLemma behavior_equiv:\n  forall em : ClassicalFacts.excluded_middle, (* proof can probably be done without EM *)\n  forall c d m tm tbeh (MATCH : exists cd j, match_state sim cd j c m d tm),\n  safe source geS c m -> \n  (has_behavior target geT d tm tbeh <-> \n   has_behavior source geS c m tbeh).\nProof.\nintros; split; intros. \n{ \neapply behavior_refinement in H0; eauto.\ndestruct H0 as [beh [Hhas Href]]; inv Href; eauto.\ninv Hhas; contradiction.\n}\n{\ndestruct MATCH as [cd [j Hmatch]].\ninv H0; constructor. \nerewrite <-equitermination; eauto.\nintros n. \neapply safety_preservation with (d0:=d)(tm0:=tm)(n0:=n) in H; eauto.\nsolve[apply safeN_safeN_det; auto].\nintros Hterm; apply H2.\nerewrite equitermination; eauto.\ncontradiction.\n}\nQed.    \n\nEnd behavior_refinement.\n", "meta": {"author": "PrincetonUniversity", "repo": "compcomp", "sha": "eebb7d5a95fed97775cef7f014399be78abbe7bf", "save_path": "github-repos/coq/PrincetonUniversity-compcomp", "path": "github-repos/coq/PrincetonUniversity-compcomp/compcomp-eebb7d5a95fed97775cef7f014399be78abbe7bf/core/closed_simulations_lemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.20205055742716926}}
{"text": "(* SPDX-License-Identifier: GPL-2.0 *)\nRequire Import List.\nImport ListNotations.\n(* From RecordUpdate Require Import RecordSet.\n)Import RecordSetNotations. *)\n(* Require Import PeanoNat. *)\n\nRequire Import Psatz.\n\nRequire Import weakenedWDRF.Base weakenedWDRF.Promising weakenedWDRF.DRF weakenedWDRF.SC.\n\nDefinition get_view (e : Event) : option View :=\n    match e with\n    | LOAD _ v _ => Some v\n    | ACQ v _ => Some v\n    | STORE _ v _ => Some v\n    | REL v _ => Some v\n    | _ => None\n    end.\n\n(* construct sc trace from promising trace *)\nInductive rel_global_trace : Trace -> list GlobalEvent -> Prop :=\n| GT_EMPTY : forall n lp\n                (Hempty : forall p, p <= n -> lp p = None), \n                rel_global_trace (mkTrace n lp (fun _ => [])) []\n| GT_INTERNAL : forall t gt i tid\n                    (Hgt : rel_global_trace t gt),\n                    rel_global_trace \n                        (t\n                            <|executions := update (executions t) tid (INTERNAL i :: (executions t tid)) |> \n                        )\n                        (GE tid (INTERNAL i) :: gt)\n| GT_ORACLE : forall t gt reg val tid\n                    (Hgt : rel_global_trace t gt),\n                    rel_global_trace\n                        (t\n                            <|executions := update (executions t) tid (ORACLE reg val :: (executions t tid)) |>\n                        )\n                        (GE tid (ORACLE reg val) :: gt)\n| GT_LOAD : forall t gt addr view reg tid\n                    (Hgt : rel_global_trace t gt)\n                    (Hlast : forall ms, rel_replay_mem (promiselen t) (promiselist t) ms -> Some (ms addr) = get_value view (promiselist t)),\n                    rel_global_trace \n                        (t\n                            <|executions := update (executions t) tid (LOAD addr view reg :: (executions t tid)) |> \n                        )\n                        (GE tid (LOAD addr view reg) :: gt)\n| GT_STORE : forall t gt addr view reg tid val\n                    (Hgt : rel_global_trace t gt)\n                    (Hmask : promiselist t view = None)\n                    (Hlast : forall ms, rel_replay_mem (promiselen t) (promiselist t) ms ->\n                        rel_replay_mem (promiselen t) (update (promiselist t) view (Some (WRITE tid val addr))) \n                            (update ms addr val)    \n                    )\n                    (Hunused : forall e tid, In e (executions t tid) -> get_view e <> Some view),\n                    rel_global_trace \n                        (t\n                            <|promiselist := update (promiselist t) view (Some (WRITE tid val addr)) |>\n                            <|executions := update (executions t) tid (STORE addr view reg :: (executions t tid)) |> \n                        )\n                        (GE tid (STORE addr view reg) :: gt)\n(* ACQs and RELs are ignored in the global trace *)\n| GT_ACQUIRE : forall t gt view addr tid\n                    (Hgt : rel_global_trace t gt)\n                    (Hmask : promiselist t view = None)\n                    (Hlast : forall om n, rel_global_ownership n om (update (promiselist t) view (Some (PULL tid addr))) (fun _ => None) ->\n                        exists om', rel_global_ownership n om' (promiselist t) (fun _ => None))\n                    (Hunused : forall e tid, In e (executions t tid) -> get_view e <> Some view),\n                    rel_global_trace\n                        (t\n                            <|promiselist := update (promiselist t) view (Some (PULL tid addr)) |>\n                            <|executions := update (executions t) tid (ACQ view addr :: (executions t tid)) |> \n                        )\n                        gt\n| GT_RELEASE : forall t gt view addr tid\n                    (Hgt : rel_global_trace t gt)\n                    (Hmask : promiselist t view = None)\n                    (Hlast : forall om n, rel_global_ownership n om (update (promiselist t) view (Some (PUSH tid addr))) (fun _ => None) ->\n                        exists om', rel_global_ownership n om' (promiselist t) (fun _ => None))\n                    (Hunused : forall e tid, In e (executions t tid) -> get_view e <> Some view),\n                    rel_global_trace\n                        (t\n                            <|promiselist := update (promiselist t) view (Some (PUSH tid addr)) |>\n                            <|executions := update (executions t) tid (REL view addr :: (executions t tid)) |> \n                        )\n                        gt.\n\n\n\nInductive same_result : Trace -> list GlobalEvent -> Prop :=\n| SAME_RESULT : forall t gt ms gs rs\n                    (Hpamem : rel_replay_mem (promiselen t) (promiselist t) ms)\n                    (Hpareg : forall tid, rel_replay_reg (promiselist t) (executions t tid) (rs tid))\n                    (Hsc : rel_replay_sc gt gs)\n                    (Hms : memstate gs = ms)\n                    (Hreg : forall tid, regstates gs tid = rs tid)\n                    ,\n                    same_result t gt.\n\nLemma replay_mem_exists : forall lp n, exists ms, rel_replay_mem n lp ms.\nProof.\n    intro. induction n.\n    -   esplit. constructor.\n    -   destruct IHn as (ms & Hms). destruct (lp (S n)) eqn:Hsn.\n        +   destruct p.\n            *   esplit.\n                eapply REPLAY_MEM_WRITE. apply Hms. apply Hsn.\n            *   esplit.  \n                eapply REPLAY_MEM_OTHER. apply Hms. rewrite Hsn. easy.\n            *   esplit.  \n                eapply REPLAY_MEM_OTHER. apply Hms. rewrite Hsn. easy.\n        +   esplit. eapply REPLAY_MEM_OTHER. apply Hms. rewrite Hsn. easy.\nQed.\n\n\nLemma replay_sc_exists : forall gt, exists gs, rel_replay_sc gt gs.\nProof.\n    intro. induction gt.\n    -   esplit. constructor.\n    -   destruct a.\n        destruct e; destruct IHgt as (gs & Hgs).\n        {\n            specialize (execute_internal_exists i (regstates gs tid)). intro. destruct H  as (rs & Hrs).\n            esplit. constructor. apply Hgs. apply Hrs.\n        }\n        esplit; constructor; try apply Hgs.\n        esplit; constructor; try apply Hgs.\n        esplit; constructor; try apply Hgs.\n        esplit; constructor; try apply Hgs.\n        esplit; constructor; try apply Hgs.\nQed.\n\nLemma empty_replay_mem :\n        forall n lp\n            (Hempty : forall p : nat, p <= n -> lp p = None),\n            rel_replay_mem n lp (fun addr => 0).\nProof.\n    induction n; intros.\n    -   constructor.\n    -   apply REPLAY_MEM_OTHER. apply IHn.\n        intros. apply Hempty. lia.\n        rewrite Hempty. easy. easy.\nQed.\n\nLemma nth_error_inv :\n        forall {T} (l : list T) n a b, nth_error (a :: l) n = Some b ->\n            (n = 0 /\\ a = b) \\/ (exists n', n = S n' /\\ nth_error l n' = Some b).\nProof.\n    intros.\n    destruct n.\n    left. simpl in *. inversion H. easy.\n    right. simpl in *. exists n. split. easy.\n    assumption.\nQed.\n\n\n\nLemma localstate_promise_unused_write : \n    forall tid pl ex ls view val addr tid'\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hls : rel_promising tid (update pl view (Some (WRITE tid' val addr))) ex ls),\n        rel_promising tid pl ex ls.\nProof.\n    induction ex; intros.\n    -   inversion Hls. constructor.\n    -   inversion Hls.\n        +   econstructor.\n            eapply IHex.\n            *   apply Hmask.\n            *   intros. apply Hunused. simpl. auto.\n            *   apply Hls0.\n            *   apply Hexec. \n        +   econstructor. \n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto. apply Hls0.\n        +   econstructor. \n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. eapply Le.le_trans. apply previous_promise_incr.\n            apply Hmask. apply Hbarrier. \n            apply Hcoh.\n            rewrite update_not_same in Hpromise. easy.\n            specialize Hunused with a. intro. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   econstructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   constructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. apply Hbarrier. apply Hcoh.\n            rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   econstructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n            apply Hbarrier.\nQed.\n\nLemma global_ownership_unused_write_aux :\n    forall n omr pl view tid val addr om\n        (Hmask : pl view = None)\n        (Hom : rel_global_ownership n om (update pl view (Some (WRITE tid val addr))) omr),\n        rel_global_ownership n om pl omr.\nProof.\n    induction n; intros.\n    -   inversion Hom. constructor.\n    -   inversion Hom.\n        +   constructor. eapply IHn.\n            apply Hmask. apply Hlp. apply Hown.\n            rewrite <- Hlp0. rewrite update_not_same. easy.\n            intro. subst. rewrite update_same in Hlp0. discriminate.\n        +   econstructor. eapply IHn.\n            apply Hmask. apply Hlp. apply Hown.\n            rewrite <- Hlp0. rewrite update_not_same. easy.\n            intro. subst. rewrite update_same in Hlp0. discriminate.\n        +   destruct (Peano_dec.eq_nat_dec view (S n)).\n            *   apply GO_NONE. eapply IHn. apply Hmask. apply Hlp.\n                subst. apply Hmask.\n            *   eapply GO_WRITE. eapply IHn.\n            apply Hmask. apply Hlp. apply Hown.\n            rewrite update_not_same in Hlp0 by easy.\n            apply Hlp0.\n        +   destruct (Peano_dec.eq_nat_dec view (S n)).\n            *   apply GO_NONE. eapply IHn. apply Hmask. apply Hlp.\n                subst. apply Hmask.\n            *   eapply GO_NONE. eapply IHn.\n            apply Hmask. apply Hlp.\n            rewrite update_not_same in Hlp0 by easy.\n            apply Hlp0.\nQed. \n\nLemma global_ownership_unused_write :\n    forall n pl view tid val addr om\n        (Hmask : pl view = None)\n        (Hom : rel_global_ownership n om (update pl view (Some (WRITE tid val addr))) (fun _ => None)),\n        rel_global_ownership n om pl (fun _ => None).\nProof.\n    intros. eapply global_ownership_unused_write_aux.\n    apply Hmask. apply Hom.\nQed.\n\nLemma local_ownership_unused_write :\n    forall pl ex lo view val addr tid'\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hlo : rel_local_ownership (update pl view (Some (WRITE tid' val addr))) ex lo),\n        rel_local_ownership pl ex lo.\nProof.\n    induction ex; intros.\n    -   inversion Hlo. constructor.\n    -   inversion Hlo.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown. apply Hview.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown. apply Hview.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0.\nQed.\n\n\nLemma regstate_write_unchanged :\n    forall pl ex view tid addr rs val\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hrs : rel_replay_reg pl ex rs),\n        rel_replay_reg (update pl view (Some (WRITE tid val addr))) ex rs.\nProof.\n    induction ex; intros.\n    -   inversion Hrs. constructor.\n    -   inversion Hrs.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. apply Hinternal.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. unfold get_value in *.\n            rewrite update_not_same. apply Hval.\n            intro. edestruct Hunused.\n            simpl. left. reflexivity.\n            subst a. simpl. subst. reflexivity.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. unfold get_value in *.\n            rewrite update_not_same. apply Hval.\n            intro. edestruct Hunused.\n            simpl. left. reflexivity.\n            subst a. simpl. subst. reflexivity.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. \n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs.  \nQed.\n\nLemma localstate_promise_unused_pull : \n    forall tid pl ex ls view addr tid'\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hls : rel_promising tid (update pl view (Some (PULL tid' addr))) ex ls),\n        rel_promising tid pl ex ls.\nProof.\n    induction ex; intros.\n    -   inversion Hls. constructor.\n    -   inversion Hls.\n        +   econstructor.\n            eapply IHex.\n            *   apply Hmask.\n            *   intros. apply Hunused. simpl. auto.\n            *   apply Hls0.\n            *   apply Hexec. \n        +   econstructor. \n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto. apply Hls0.\n        +   econstructor. \n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. eapply Le.le_trans. apply previous_promise_incr.\n            apply Hmask. apply Hbarrier. \n            apply Hcoh.\n            rewrite update_not_same in Hpromise. easy.\n            specialize Hunused with a. intro. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   econstructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   constructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. apply Hbarrier. apply Hcoh.\n            rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   econstructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n            apply Hbarrier.\nQed.\n\nLemma local_ownership_unused_pull :\n    forall pl ex lo view addr tid'\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hlo : rel_local_ownership (update pl view (Some (PULL tid' addr))) ex lo),\n        rel_local_ownership pl ex lo.\nProof.\n    induction ex; intros.\n    -   inversion Hlo. constructor.\n    -   inversion Hlo.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown. apply Hview.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown. apply Hview.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0.\nQed.\n\nLemma memstate_pull_unchanged :\n    forall n pl view ms tid addr\n        (Hmask : pl view = None)\n        (Hms : rel_replay_mem n pl ms),\n        rel_replay_mem n (update pl view (Some (PULL tid addr))) ms.\nProof.\n    induction n; intros.\n    -   inversion Hms. constructor.\n    -   inversion Hms.\n        +   econstructor. apply IHn.\n            apply Hmask. apply Hlp.\n            rewrite update_not_same. apply Hwrite.\n            intro. contradict Hwrite. subst. rewrite Hmask. easy.\n        +   econstructor. apply IHn.\n            apply Hmask. apply Hlp.\n            destruct (Peano_dec.eq_nat_dec view (S n)).\n            *   subst. rewrite update_same. easy.\n            *   rewrite update_not_same by easy. apply Hnotwrite.\nQed.   \n\nLemma regstate_pull_unchanged :\n    forall pl ex view tid addr rs\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hrs : rel_replay_reg pl ex rs),\n        rel_replay_reg (update pl view (Some (PULL tid addr))) ex rs.\nProof.\n    induction ex; intros.\n    -   inversion Hrs. constructor.\n    -   inversion Hrs.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. apply Hinternal.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. \n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. unfold get_value in *.\n            rewrite update_not_same. apply Hval.\n            intro. edestruct Hunused.\n            simpl. left. reflexivity.\n            subst a. simpl. subst. reflexivity.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. unfold get_value in *.\n            rewrite update_not_same. apply Hval.\n            intro. edestruct Hunused.\n            simpl. left. reflexivity.\n            subst a. simpl. subst. reflexivity.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. \n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs.  \nQed.\n\nLemma localstate_promise_unused_push : \n    forall tid pl ex ls view addr tid'\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hls : rel_promising tid (update pl view (Some (PUSH tid' addr))) ex ls),\n        rel_promising tid pl ex ls.\nProof.\n    induction ex; intros.\n    -   inversion Hls. constructor.\n    -   inversion Hls.\n        +   econstructor.\n            eapply IHex.\n            *   apply Hmask.\n            *   intros. apply Hunused. simpl. auto.\n            *   apply Hls0.\n            *   apply Hexec. \n        +   econstructor. \n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto. apply Hls0.\n        +   econstructor. \n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. eapply Le.le_trans. apply previous_promise_incr.\n            apply Hmask. apply Hbarrier. \n            apply Hcoh.\n            rewrite update_not_same in Hpromise. easy.\n            specialize Hunused with a. intro. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   econstructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   constructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. apply Hbarrier. apply Hcoh.\n            rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n        +   econstructor.\n            eapply IHex. apply Hmask.\n            intros. apply Hunused. simpl. auto.\n            apply Hls0. rewrite update_not_same in Hpromise. apply Hpromise.\n            intro. specialize Hunused with a. destruct Hunused.\n            simpl. auto. unfold get_view. subst a. rewrite H4. easy.\n            apply Hbarrier.\nQed.\n\nLemma local_ownership_unused_push :\n    forall pl ex lo view addr tid'\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hlo : rel_local_ownership (update pl view (Some (PUSH tid' addr))) ex lo),\n        rel_local_ownership pl ex lo.\nProof.\n    induction ex; intros.\n    -   inversion Hlo. constructor.\n    -   inversion Hlo.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown. apply Hview.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0. apply Hown. apply Hview.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0.\n        +   constructor. eapply IHex.\n            apply Hmask. intros. apply Hunused.\n            simpl. right. easy.\n            apply Hlo0.\nQed.\n\nLemma regstate_push_unchanged :\n    forall pl ex view tid addr rs\n        (Hmask : pl view = None)\n        (Hunused : forall e, In e ex -> get_view e <> Some view)\n        (Hrs : rel_replay_reg pl ex rs),\n        rel_replay_reg (update pl view (Some (PUSH tid addr))) ex rs.\nProof.\n    induction ex; intros.\n    -   inversion Hrs. constructor.\n    -   inversion Hrs.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. apply Hinternal.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. \n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. unfold get_value in *.\n            rewrite update_not_same. apply Hval.\n            intro. edestruct Hunused.\n            simpl. left. reflexivity.\n            subst a. simpl. subst. reflexivity.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. unfold get_value in *.\n            rewrite update_not_same. apply Hval.\n            intro. edestruct Hunused.\n            simpl. left. reflexivity.\n            subst a. simpl. subst. reflexivity.\n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs. \n        +   econstructor. apply IHex.\n            apply Hmask. intros. apply Hunused. simpl. right. easy.\n            apply Hs.  \nQed.\n\nLemma memstate_push_unchanged :\n    forall n pl view ms tid addr\n        (Hmask : pl view = None)\n        (Hms : rel_replay_mem n pl ms),\n        rel_replay_mem n (update pl view (Some (PUSH tid addr))) ms.\nProof.\n    induction n; intros.\n    -   inversion Hms. constructor.\n    -   inversion Hms.\n        +   econstructor. apply IHn.\n            apply Hmask. apply Hlp.\n            rewrite update_not_same. apply Hwrite.\n            intro. contradict Hwrite. subst. rewrite Hmask. easy.\n        +   econstructor. apply IHn.\n            apply Hmask. apply Hlp.\n            destruct (Peano_dec.eq_nat_dec view (S n)).\n            *   subst. rewrite update_same. easy.\n            *   rewrite update_not_same by easy. apply Hnotwrite.\nQed.   \n\nTheorem same_mem :\n    forall (t : Trace) (gt : list GlobalEvent)\n        (Hsc : rel_global_trace t gt)\n        (Hvalid : valid_trace t)\n        (Hdrf : DRF t)\n        ,\n        same_result t gt.\nProof.\n    intros. induction Hsc.\n    -   (* empty *)\n        esplit; simpl in *.\n        +   apply empty_replay_mem. easy.\n        +   intro. apply REPLAY_REG_EMPTY.\n        +   apply SC_EMPTY.\n        +   simpl. reflexivity.\n        +   simpl. easy.\n    -   (* internal *)\n        assert (same_result t gt) as IHsame.\n        {\n            apply IHHsc.\n            inversion Hvalid. simpl in *.\n            -   constructor.\n                +   unfold fulfilled in *. simpl in *. intros v Hp.\n                    specialize Hfulfilled with v. apply Hfulfilled in Hp.\n                    destruct Hp as (tid0 & e & n & Hp1 & Hp2 & Hp3).\n                    destruct (promiselist t v) eqn: Heqp; try easy.                \n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                    *   subst. rewrite update_same in Hp1.\n                        apply nth_error_inv in Hp1 as [|]. \n                        {   destruct H. subst.\n                            destruct p; destruct Hp2; try easy.\n                            destruct H0. easy.\n                        }\n                        {exists tid0, e.\n                            destruct H as (n0 & Hn01 & Hn02).\n                            exists n0.\n                            split. easy. split. easy.\n                            intros.\n                            destruct (Peano_dec.eq_nat_dec tid0 tid').\n                             rewrite e0 in *.\n                                specialize Hp3 with tid' (S n') e'.\n                                rewrite update_same in Hp3. rewrite Hn01 in Hp3.\n                                split; auto.\n                                assert (S n0 = S n') by now apply Hp3.\n                                inversion H. easy.\n                             specialize Hp3 with tid' n' e'.\n                                rewrite update_not_same in Hp3 by lia.\n                                apply Hp3  in He'; easy.\n                        }\n                    *   rewrite update_not_same in Hp1 by easy.\n                        exists tid0, e, n. split. easy.\n                        split. easy. intros.\n                        destruct (Peano_dec.eq_nat_dec tid tid').\n                        {   rewrite <- e0 in *.\n                            specialize Hp3 with tid (S n') e'.\n                            rewrite update_same in Hp3.\n                            contradict n0. symmetry. apply Hp3.\n                            simpl. easy. easy.\n                        }\n                        {   apply Hp3 with e'.\n                            rewrite update_not_same by easy. easy. easy.\n\n                        }\n                +   intro. specialize Hconsistent with tid0. destruct Hconsistent as (ls1 & Hls1).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                    *   subst. rewrite update_same in Hls1.\n                        inversion Hls1; exists ls; easy.\n                    *   rewrite update_not_same in Hls1 by easy.\n                        exists ls1. easy.\n            -   (* DRF *)\n                inversion Hdrf. simpl in *.\n                esplit. apply Hglobal.\n                intro. specialize Hlocal with tid0. destruct Hlocal as (lo & Hlo).\n                destruct (Peano_dec.eq_nat_dec tid tid0).\n                  subst. rewrite update_same in Hlo.\n                    inversion Hlo. exists lo. easy.\n                  rewrite update_not_same in Hlo by easy.\n                    exists lo. easy.               \n        }\n        clear IHHsc. inversion IHsame.\n        destruct (execute_internal_exists i (rs tid)) as (r0 & Hr0).\n        set (rs0 := update rs tid r0).\n        replace r0 with (rs0 tid) in Hr0 by now unfold rs0; rewrite update_same.\n        esplit; simpl in *.\n        +   apply Hpamem.\n        +   intro. specialize Hpareg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst tid0. rewrite update_same.\n                econstructor. apply Hpareg.\n                apply Hr0.\n            *   rewrite update_not_same by easy.\n                replace (rs0 tid0) with (rs tid0).\n                apply Hpareg. unfold rs0. rewrite update_not_same by easy.\n                reflexivity.\n        +   constructor. apply Hsc0.\n            rewrite Hreg. apply Hr0.\n        +   simpl. apply Hms.\n        +   simpl. intro. specialize Hreg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst tid0. rewrite update_same. reflexivity.\n            *   unfold rs0.\n                rewrite update_not_same by easy.\n                rewrite update_not_same by easy.\n                apply Hreg.\n    -   (* oracle *)\n        assert (same_result t gt) as IHsame.\n        {\n            apply IHHsc.\n            inversion Hvalid. simpl in *.\n            -   constructor.\n                +   unfold fulfilled in *. simpl in *. intros v Hp.\n                    specialize Hfulfilled with v. apply Hfulfilled in Hp.\n                    destruct Hp as (tid0 & e & n & Hp1 & Hp2 & Hp3).\n                    destruct (promiselist t v) eqn: Heqp; try easy.                \n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                    *   subst. rewrite update_same in Hp1.\n                        apply nth_error_inv in Hp1 as [|]. \n                        {   destruct H. subst.\n                            destruct p; destruct Hp2; try easy.\n                            destruct H0. easy.\n                        }\n                        {exists tid0, e.\n                            destruct H as (n0 & Hn01 & Hn02).\n                            exists n0.\n                            split. easy. split. easy.\n                            intros.\n                            destruct (Peano_dec.eq_nat_dec tid0 tid').\n                             rewrite e0 in *.\n                                specialize Hp3 with tid' (S n') e'.\n                                rewrite update_same in Hp3. rewrite Hn01 in Hp3.\n                                split; auto.\n                                assert (S n0 = S n') by now apply Hp3.\n                                inversion H. easy.\n                             specialize Hp3 with tid' n' e'.\n                                rewrite update_not_same in Hp3 by lia.\n                                apply Hp3  in He'; easy.\n                        }\n                    *   rewrite update_not_same in Hp1 by easy.\n                        exists tid0, e, n. split. easy.\n                        split. easy. intros.\n                        destruct (Peano_dec.eq_nat_dec tid tid').\n                        {   rewrite <- e0 in *.\n                            specialize Hp3 with tid (S n') e'.\n                            rewrite update_same in Hp3.\n                            contradict n0. symmetry. apply Hp3.\n                            simpl. easy. easy.\n                        }\n                        {   apply Hp3 with e'.\n                            rewrite update_not_same by easy. easy. easy.\n\n                        }\n                +   intro. specialize Hconsistent with tid0. destruct Hconsistent as (ls1 & Hls1).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                    *   subst. rewrite update_same in Hls1.\n                        inversion Hls1; exists ls; easy.\n                    *   rewrite update_not_same in Hls1 by easy.\n                        exists ls1. easy.\n            -   (* DRF *)\n                inversion Hdrf. simpl in *.\n                esplit. apply Hglobal.\n                intro. specialize Hlocal with tid0. destruct Hlocal as (lo & Hlo).\n                destruct (Peano_dec.eq_nat_dec tid tid0).\n                  subst. rewrite update_same in Hlo.\n                    inversion Hlo. exists lo. easy.\n                  rewrite update_not_same in Hlo by easy.\n                    exists lo. easy.               \n        }\n        clear IHHsc. inversion IHsame.\n        set (r0 := update (rs tid) reg val).\n        set (rs0 := update rs tid r0).\n        esplit; simpl in *.\n        +   apply Hpamem.\n        +   instantiate (1:=rs0).\n            intro. specialize Hpareg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst tid0. rewrite update_same.\n                unfold rs0. rewrite update_same.\n                econstructor. apply Hpareg.\n            *   rewrite update_not_same by easy.\n                replace (rs0 tid0) with (rs tid0).\n                apply Hpareg. unfold rs0. rewrite update_not_same by easy.\n                reflexivity.\n        +   constructor. apply Hsc0.\n        +   simpl. apply Hms.\n        +   simpl. intro. specialize Hreg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst tid0. rewrite update_same. rewrite Hreg.\n                unfold rs0. rewrite update_same. easy.\n            *   unfold rs0.\n                rewrite update_not_same by easy.\n                rewrite update_not_same by easy.\n                apply Hreg.\n    -   (* LOAD *)\n        assert (same_result t gt) as IHsame.\n        {\n            apply IHHsc.\n            -   inversion Hvalid. constructor.\n                +   unfold fulfilled in *. simpl in *. intros v Hp.\n                    specialize Hfulfilled with v. apply Hfulfilled in Hp.\n                    destruct Hp as (tid0 & e & n & Hp1 & Hp2 & Hp3).\n                    destruct (promiselist t v) eqn: Heqp; try easy.                \n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                    *   subst. rewrite update_same in Hp1.\n                        apply nth_error_inv in Hp1 as [|]. \n                          destruct H. subst.\n                            destruct p; destruct Hp2; try easy.\n                            destruct H0. easy.\n                          exists tid0, e.\n                            destruct H as (n0 & Hn01 & Hn02).\n                            exists n0.\n                            split. easy. split. easy.\n                            intros.\n                            destruct (Peano_dec.eq_nat_dec tid0 tid').\n                             rewrite e0 in *.\n                                specialize Hp3 with tid' (S n') e'.\n                                rewrite update_same in Hp3. rewrite Hn01 in Hp3.\n                                split; auto.\n                                assert (S n0 = S n') by now apply Hp3.\n                                inversion H. easy.\n                             specialize Hp3 with tid' n' e'.\n                                rewrite update_not_same in Hp3 by lia.\n                                apply Hp3  in He'; easy.\n                    *   rewrite update_not_same in Hp1 by easy.\n                        exists tid0, e, n. split. easy.\n                        split. easy. intros.\n                        destruct (Peano_dec.eq_nat_dec tid tid').\n                          rewrite <- e0 in *.\n                            specialize Hp3 with tid (S n') e'.\n                            rewrite update_same in Hp3.\n                            contradict n0. symmetry. apply Hp3.\n                            simpl. easy. easy.\n                          apply Hp3 with e'.\n                            rewrite update_not_same by easy. easy. easy.  \n                +   intro. simpl in *.\n                    specialize Hconsistent with tid0. destruct Hconsistent as (ls & Hls).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                    *   subst. rewrite update_same in Hls.\n                        inversion Hls. exists ls0. easy.\n                    *   rewrite update_not_same in Hls by easy.\n                        exists ls. easy.\n            -   inversion Hdrf. simpl in *. esplit.\n                apply Hglobal.\n                intro. specialize Hlocal with tid0.\n                destruct (Peano_dec.eq_nat_dec tid tid0).\n                +   subst. rewrite update_same in Hlocal.\n                    destruct Hlocal as (lo & Hlo).\n                    inversion Hlo. exists lo. apply Hlo0.\n                +   rewrite update_not_same in Hlocal by easy.\n                    apply Hlocal.\n        }\n        clear IHHsc. inversion IHsame.\n        inversion Hvalid.\n        destruct (Hconsistent tid) as (ls & Hls). simpl in *.\n        rewrite update_same in Hls.\n        inversion Hls.\n        set (rs0 := update rs tid (update (rs tid) reg val)).\n        esplit; simpl in *.\n        +   apply Hpamem.\n        +   subst.\n            instantiate (1:= update rs tid (update (rs tid) reg val)).\n            intro. specialize Hpareg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst. simpl in *. rewrite update_same.\n                unfold rs0. rewrite update_same.\n                constructor. assumption.\n                unfold get_value. rewrite Hpromise. easy.\n            *   unfold rs0.\n                repeat rewrite update_not_same by easy.\n                easy.\n        +   constructor. apply Hsc0.\n        +   easy.\n        +   simpl. intro.\n            destruct (Peano_dec.eq_nat_dec tid tid1).\n            *   rewrite Hreg. rewrite Hms.\n                rewrite e.\n                repeat rewrite update_same.\n                assert (ms addr = val). (* last read *)\n                {\n                    apply Hlast in Hpamem.\n                    unfold get_value in *. rewrite Hpromise in Hpamem.\n                    inversion Hpamem. reflexivity.\n                }\n                subst. easy.\n            *   subst.\n                repeat rewrite update_not_same by easy. rewrite Hreg. easy.     \n    -   (* STORE *)   \n        assert (same_result t gt) as IHsame.\n        {\n            apply IHHsc.\n            inversion Hvalid. simpl in *.\n            -   constructor.\n                +   unfold fulfilled in *. simpl in *. intros v Hp.\n                    specialize Hfulfilled with v.\n                    destruct (Peano_dec.eq_nat_dec v view).\n                    *   rewrite e in *.\n                        rewrite Hmask in *. destruct Hp. easy.\n                    *   rewrite update_not_same in Hfulfilled by lia.\n                        apply Hfulfilled in Hp.\n                        destruct Hp as (tid0 & e & n0 & He & Hp1 & Hp2).\n                        exists tid0, e.\n                        destruct (Peano_dec.eq_nat_dec tid tid0).\n                          rewrite <- e0 in *. rewrite update_same in He.\n                            apply nth_error_inv in He as [|].\n                              destruct H0. subst.\n                                destruct (promiselist t v); try easy.\n                                destruct p. destruct Hp1 as (_ & reg0 & Hreg).\n                                inversion Hreg. contradict n. easy. easy.\n                                destruct Hp1. discriminate.\n                              destruct H0 as (n' & Hn'1 & Hn'2).\n                                exists n'. split. easy. split. easy.\n                                intros.\n                                destruct (Peano_dec.eq_nat_dec tid tid').\n                                  rewrite <- e1 in *.\n                                    specialize Hp2 with tid (S n'0) e'.\n                                    rewrite update_same in Hp2.\n                                    rewrite Hn'1 in *.\n                                    assert (S n' = S n'0) by now apply Hp2.\n                                    auto.\n                                  specialize Hp2 with tid' n'0 e'.\n                                    rewrite update_not_same in Hp2 by lia.\n                                    contradict n1. apply Hp2. easy. easy.\n                          rewrite update_not_same in He by easy.\n                            exists n0. split. easy. split. easy.\n                            intros. destruct (Peano_dec.eq_nat_dec tid tid').\n                              specialize Hp2 with tid (S n') e'. rewrite <- e0 in *.\n                                rewrite update_same in Hp2.\n                                contradict n1. symmetry. apply Hp2.\n                                simpl. easy. easy.\n                              specialize Hp2 with tid' n' e'.\n                                rewrite update_not_same in Hp2 by easy.\n                                apply Hp2. easy. easy.\n                +   intro. specialize Hconsistent with tid0. destruct Hconsistent as (ls1 & Hls1).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                      subst. rewrite update_same in Hls1.\n                        inversion Hls1. exists ls.\n                        eapply localstate_promise_unused_write.\n                          apply Hmask.\n                          intros. eapply Hunused. apply H6.\n                          apply Hls.\n                      rewrite update_not_same in Hls1 by easy.\n                        exists ls1.\n                        eapply localstate_promise_unused_write.\n                        apply Hmask. intros. eapply Hunused. apply H0. apply Hls1.\n            -   (* DRF *)\n                inversion Hdrf. simpl in *.\n                esplit. \n                +   inversion Hglobal. eexists. eapply global_ownership_unused_write.\n                    apply Hmask. apply H0. (* last write *)\n                +   intro. specialize Hlocal with tid0. destruct Hlocal  as (lo & Hlo).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                      subst. rewrite update_same in Hlo.\n                        inversion Hlo. exists lo0.\n                        eapply local_ownership_unused_write. apply Hmask.\n                        intros. eapply Hunused. apply H5. subst. apply Hlo0.\n                      rewrite update_not_same in Hlo by easy.\n                        exists lo.\n                        eapply local_ownership_unused_write. apply Hmask.\n                        intros. eapply Hunused. apply H0. subst. apply Hlo.        \n        }\n        clear IHHsc. inversion IHsame.\n        esplit; simpl in *.\n        +   apply Hlast. apply Hpamem. \n        +   intro. specialize Hpareg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst. rewrite update_same.\n                apply REPLAY_REG_STORE. \n                eapply regstate_write_unchanged. apply Hmask.\n                intros. eapply Hunused. apply H. apply Hpareg.\n                unfold get_value. rewrite update_same.\n                inversion Hvalid.\n                specialize Hconsistent with tid0. destruct Hconsistent.\n                simpl in *. rewrite update_same in H0. inversion H0.\n                rewrite update_same in Hpromise. inversion Hpromise.\n                erewrite rel_promising_localstate. reflexivity.\n                apply Hls. apply regstate_write_unchanged.\n                apply Hmask. intro. apply Hunused. easy. \n            *   rewrite update_not_same by easy.\n                eapply regstate_write_unchanged. apply Hmask.\n                intros. eapply Hunused. apply H1. apply Hpareg.\n        +   constructor. apply Hsc0. \n        +   simpl. rewrite Hreg. rewrite Hms.\n            replace (rs tid reg) with val. easy.\n            inversion Hvalid. specialize Hconsistent with tid.\n            destruct Hconsistent. simpl in *. rewrite update_same in H2.\n            inversion H2. rewrite update_same in Hpromise. inversion Hpromise.\n            erewrite rel_promising_localstate. reflexivity.\n            apply Hls. apply regstate_write_unchanged. apply Hmask.\n            intro. eapply Hunused. easy.\n        +   simpl. intro. specialize Hreg with tid0.\n            apply Hreg.\n    -   (* ACQ *)\n        assert (same_result t gt) as IHsame.\n        {\n            apply IHHsc.\n            inversion Hvalid. simpl in *.\n            -   constructor.\n                +   unfold fulfilled in *. simpl in *. intros v Hp.\n                    specialize Hfulfilled with v.\n                    destruct (Peano_dec.eq_nat_dec v view).\n                    *   rewrite e in *.\n                        rewrite Hmask in *. destruct Hp. easy.\n                    *   rewrite update_not_same in Hfulfilled by lia.\n                        apply Hfulfilled in Hp.\n                        destruct Hp as (tid0 & e & n0 & He & Hp1 & Hp2).\n                        exists tid0, e.\n                        destruct (Peano_dec.eq_nat_dec tid tid0).\n                          rewrite <- e0 in *. rewrite update_same in He.\n                            apply nth_error_inv in He as [|].\n                              destruct H0. subst.\n                                destruct (promiselist t v); try easy.\n                                destruct p. destruct Hp1 as (_ & reg & Hreg). discriminate.\n                                destruct Hp1. inversion H0. contradict n. easy. easy.\n                              destruct H0 as (n' & Hn'1 & Hn'2).\n                                exists n'. split. easy. split. easy.\n                                intros.\n                                destruct (Peano_dec.eq_nat_dec tid tid').\n                                  rewrite <- e1 in *.\n                                    specialize Hp2 with tid (S n'0) e'.\n                                    rewrite update_same in Hp2.\n                                    rewrite Hn'1 in *.\n                                    assert (S n' = S n'0) by now apply Hp2.\n                                    auto.\n                                  specialize Hp2 with tid' n'0 e'.\n                                    rewrite update_not_same in Hp2 by lia.\n                                    contradict n1. apply Hp2. easy. easy.\n                          rewrite update_not_same in He by easy.\n                            exists n0. split. easy. split. easy.\n                            intros. destruct (Peano_dec.eq_nat_dec tid tid').\n                              specialize Hp2 with tid (S n') e'. rewrite <- e0 in *.\n                                rewrite update_same in Hp2.\n                                contradict n1. symmetry. apply Hp2.\n                                simpl. easy. easy.\n                              specialize Hp2 with tid' n' e'.\n                                rewrite update_not_same in Hp2 by easy.\n                                apply Hp2. easy. easy.\n                +   intro. specialize Hconsistent with tid0. destruct Hconsistent as (ls1 & Hls1).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                      subst. rewrite update_same in Hls1.\n                        inversion Hls1. exists ls. \n                        eapply localstate_promise_unused_pull.\n                        apply Hmask. intros. eapply Hunused. apply H5. apply Hls.\n                      rewrite update_not_same in Hls1 by easy.\n                        exists ls1. eapply localstate_promise_unused_pull.\n                        apply Hmask. intros. eapply Hunused. apply H0. apply Hls1.\n            -   (* DRF *)\n                inversion Hdrf. simpl in *.\n                esplit. \n                +   inversion Hglobal. eapply Hlast. apply H0.\n                +   intro. specialize Hlocal with tid0. destruct Hlocal as (lo & Hlo).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                      subst. rewrite update_same in Hlo.\n                        inversion Hlo. exists lo0.\n                        eapply local_ownership_unused_pull.\n                        apply Hmask. intros. eapply Hunused. apply H4.\n                        apply Hlo0.\n                      rewrite update_not_same in Hlo by easy.\n                        exists lo. eapply local_ownership_unused_pull.\n                        apply Hmask. intros. eapply Hunused. apply H0. subst. apply Hlo.             \n        }\n        clear IHHsc. inversion IHsame.\n        esplit; simpl in *.\n        +   apply memstate_pull_unchanged. apply Hmask. apply Hpamem.\n        +   instantiate (1:= rs).\n            intro. specialize Hpareg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst. rewrite update_same.\n                constructor.\n                apply regstate_pull_unchanged. apply Hmask.\n                intros. eapply Hunused. apply H. apply Hpareg.\n            *   rewrite update_not_same by easy.\n                apply regstate_pull_unchanged. apply Hmask.\n                intros. eapply Hunused. apply H1. apply Hpareg.\n        +   apply Hsc0. \n        +   simpl. apply Hms.\n        +   simpl. intro. specialize Hreg with tid0.\n            apply Hreg.\n    -   (* REL *)\n        assert (same_result t gt) as IHsame.\n        {\n            apply IHHsc.\n            inversion Hvalid. simpl in *.\n            -   constructor.\n                +   unfold fulfilled in *. simpl in *. intros v Hp.\n                    specialize Hfulfilled with v.\n                    destruct (Peano_dec.eq_nat_dec v view).\n                    *   rewrite e in *.\n                        rewrite Hmask in *. destruct Hp. easy.\n                    *   rewrite update_not_same in Hfulfilled by lia.\n                        apply Hfulfilled in Hp.\n                        destruct Hp as (tid0 & e & n0 & He & Hp1 & Hp2).\n                        exists tid0, e.\n                        destruct (Peano_dec.eq_nat_dec tid tid0).\n                          rewrite <- e0 in *. rewrite update_same in He.\n                            apply nth_error_inv in He as [|].\n                              destruct H0. subst.\n                                destruct (promiselist t v); try easy.\n                                destruct p. destruct Hp1 as (_ & reg & Hreg). discriminate.\n                                easy.\n                                destruct Hp1. inversion H0. contradict n. easy.\n                              destruct H0 as (n' & Hn'1 & Hn'2).\n                                exists n'. split. easy. split. easy.\n                                intros.\n                                destruct (Peano_dec.eq_nat_dec tid tid').\n                                  rewrite <- e1 in *.\n                                    specialize Hp2 with tid (S n'0) e'.\n                                    rewrite update_same in Hp2.\n                                    rewrite Hn'1 in *.\n                                    assert (S n' = S n'0) by now apply Hp2.\n                                    auto.\n                                  specialize Hp2 with tid' n'0 e'.\n                                    rewrite update_not_same in Hp2 by lia.\n                                    contradict n1. apply Hp2. easy. easy.\n                          rewrite update_not_same in He by easy.\n                            exists n0. split. easy. split. easy.\n                            intros. destruct (Peano_dec.eq_nat_dec tid tid').\n                              specialize Hp2 with tid (S n') e'. rewrite <- e0 in *.\n                                rewrite update_same in Hp2.\n                                contradict n1. symmetry. apply Hp2.\n                                simpl. easy. easy.\n                              specialize Hp2 with tid' n' e'.\n                                rewrite update_not_same in Hp2 by easy.\n                                apply Hp2. easy. easy.\n                +   intro. specialize Hconsistent with tid0. destruct Hconsistent as (ls1 & Hls1).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                      subst. rewrite update_same in Hls1.\n                        inversion Hls1. exists ls.\n                        eapply localstate_promise_unused_push.\n                        apply Hmask. intros. eapply Hunused. apply H5. rewrite H1. apply Hls.\n                      rewrite update_not_same in Hls1 by easy.\n                        exists ls1. eapply localstate_promise_unused_push.\n                        apply Hmask. intros. eapply Hunused. apply H0. apply Hls1.\n            -   (* DRF *)\n                inversion Hdrf. simpl in *.\n                esplit. \n                +   inversion Hglobal. eapply Hlast. apply H0.\n                +   intro. specialize Hlocal with tid0. destruct Hlocal as (lo & Hlo).\n                    destruct (Peano_dec.eq_nat_dec tid tid0).\n                      subst. rewrite update_same in Hlo.\n                        inversion Hlo. exists lo0.\n                        eapply local_ownership_unused_push.\n                        apply Hmask. intros. eapply Hunused. apply H4.\n                        apply Hlo0.\n                      rewrite update_not_same in Hlo by easy.\n                        exists lo. eapply local_ownership_unused_push.\n                        apply Hmask. intros. eapply Hunused. apply H0. subst. apply Hlo.              \n        }\n        clear IHHsc. inversion IHsame.\n        esplit; simpl in *.\n        +   apply memstate_push_unchanged. apply Hmask. apply Hpamem.\n        +   instantiate (1:=rs).\n            intro. specialize Hpareg with tid0.\n            destruct (Peano_dec.eq_nat_dec tid tid0).\n            *   subst. rewrite update_same.\n                constructor.\n                apply regstate_push_unchanged. apply Hmask.\n                intros. eapply Hunused. apply H. apply Hpareg.\n            *   rewrite update_not_same by easy.\n                apply regstate_push_unchanged. apply Hmask.\n                intros. eapply Hunused. apply H1. apply Hpareg.\n        +   apply Hsc0. \n        +   simpl. apply Hms.\n        +   simpl. intro. specialize Hreg with tid0.\n            apply Hreg.\nQed.\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/RelaxedMemory/weakenedWDRF/Proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.35220177524832036, "lm_q1q2_score": 0.20205054839214764}}
{"text": "Require Import sflib. \n\nRequire Import Axioms.\nRequire Import Basic.\nRequire Import DataStructure.\nRequire Import Loc.\nRequire Import Language.\n\nRequire Import Time.\nRequire Import Event.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\nRequire Import NPConfiguration.\nRequire Import ww_RF.\nRequire Import Behavior.\nRequire Import LocalSim.\n\nRequire Import LibTactics.\n\nRequire Import SemaEq.\nRequire Import wwRFEq.\nRequire Import Compositionality.\nRequire Import GlobSim.\nRequire Import NPBehavior.\nRequire Import wwRFPrsv.\n\nSet Implicit Arguments.\n\n(** * Framework Final Theorem *)\n\n(** This file defines the final theorem of our framework. *)\n\n(** The main result (theorem [Verif_implies_Correctness] in this file) is that:\n    a verified optimizer is a correct optimizer. *)\n\n(** * Correctness of Optimizer *)\nSection Correct_Optimizer.\n  Variable lang: language.\n\n  (** ** Type of Optimizer *)\n  Definition Optimizer :=\n    forall (lo: Ordering.LocOrdMap) (code: Language.syntax lang), option (Language.syntax lang).\n\n  (** ** Correctness of Optimizer *)\n  (** An optimizer is correct if,\n\n      for any optimization,\n      if the source program is write-write race freedom [ww_rf] and safe [Configuration.safe],\n      we have the refinement between the target program optimized and the source program,\n      and the write-write race freedom and safety properties are preserved during optimization. *)\n  Definition Correct (optimizer: Optimizer) :=\n    forall (code_s code_t: Language.syntax lang) fs lo ctid\n           (OPTIMIZE: optimizer lo code_s = Some code_t)\n           (WWRF_S: ww_rf lo fs code_s ctid)\n           (SAFE_S: Configuration.safe lo fs code_s ctid),\n      <<REFINE: forall behs, prog_behaviors fs code_t ctid lo behs -> prog_behaviors fs code_s ctid lo behs>> /\\\n      <<WWRF_T: ww_rf lo fs code_t ctid>> /\\ <<SAFE_T: Configuration.safe lo fs code_t ctid>>.\n\n  \n  (** ** Optimizers Linking *)\n  (** It contructs an optimizer with two optimization phases. *)\n  (** opt_link (optimizer1, optimizer) (code_s) =\n       let code_m := optimizer2(code_s) in optimizer1(code_m)   *)\n  Definition opt_link (optimizer1 optimizer2: Optimizer) : Optimizer :=\n    fun (lo: Ordering.LocOrdMap) (code_s: Language.syntax lang) =>\n      match (optimizer2 lo code_s) with\n      | Some code_m => optimizer1 lo code_m\n      | None => None\n      end.\n\n  (** ** Correctness of Optimizers Linking *)\n  Lemma correct_optimizer_transitive:\n    forall (optimizer1 optimizer2: Optimizer)\n      (CORRECT1: Correct(optimizer1))\n      (CORRECT2: Correct(optimizer2)),\n      Correct(opt_link optimizer1 optimizer2).\n  Proof.\n    intros; unfolds Correct; intros.\n    unfold opt_link in OPTIMIZE. destruct (optimizer2 lo code_s) eqn:H_OPTIMIZER2; simpls; tryfalse.\n    eapply CORRECT2 in H_OPTIMIZER2; eauto.\n    destruct H_OPTIMIZER2 as (Hrefine2 & Hww_rf2 & Hsafe2).\n    eapply CORRECT1 in OPTIMIZE; eauto.\n    destruct OPTIMIZE as (Hrefine1 & Hww_rf1 & Hsafe1).\n    split; eauto.\n  Qed.\n\n  (** ** Verified Optimizer *)\n  (** An optimizer is verified if we can establish the thread-local simulation [local_sim]\n      between the target and source programs *)\n  Definition Verif (optimizer: Optimizer): Prop := \n    forall (code_s code_t: Language.syntax lang) (lo: Ordering.LocOrdMap),\n        optimizer lo code_s = Some code_t -> \n          exists invariant index ord, \n            @local_sim index ord lang invariant lo code_t code_s.\n\n  (** The following lemma [Verif_opt_implies_localsim]\n      shows that for a verified optimizer,\n      the source program and the target program optimized\n      are simulated by the thread-local simulation.\n\n      Lemma [Verif_opt_implies_localsim] corresponds to\n      the step 2 in Figure 6 (Our proof path) in our paper *)\n  Lemma Verif_opt_implies_localsim\n        optimizer code_s code_t lo\n        (VERIF: Verif optimizer)\n        (OPT: optimizer lo code_s = Some code_t):\n    exists invariant index ord,\n      @local_sim index ord lang invariant lo code_t code_s.\n  Proof.\n    eauto.\n  Qed.\n\n  (** ** A verified optimizer is correct *)\n  Theorem Verif_implies_Correctness: \n    forall (optimizer: Optimizer),\n      Verif optimizer -> Correct optimizer.\n  Proof.\n    ii. renames H to WF_OPT.\n    eapply Verif_opt_implies_localsim in WF_OPT; eauto.\n    renames WF_OPT to LOCAL_SIM. des.\n    lets GLOB_SIM: LOCAL_SIM.\n    eapply compositionality in GLOB_SIM; eauto.\n    Focus 2. eapply config_safe_eq; eauto.\n    Focus 2. eapply ww_RF_eq; eauto.\n    split.\n    {\n      ii. eapply sema_eq_ps_nps in H.\n      eapply sema_eq_ps_nps.\n      eapply glob_sim_implies_refinement; eauto.\n    }\n    split.\n    {\n      lets WW_RF: LOCAL_SIM.\n      eapply ww_RF_preservation in WW_RF.\n      eapply ww_RF_eq; eauto.\n      eapply config_safe_eq; eauto.\n      eapply ww_RF_eq; eauto.\n    }\n    {\n      lets SAFE_S': SAFE_S.\n      eapply safe_implies_not_abort_tr in SAFE_S'.\n      eapply not_abort_tr_implies_safe. ii; des.\n      contradiction SAFE_S'.\n      eapply sema_eq_ps_nps in H.\n      eapply glob_sim_implies_refinement in GLOB_SIM; eauto.\n      eapply sema_eq_ps_nps in GLOB_SIM; eauto.\n    }\n  Qed.\n\nEnd Correct_Optimizer.\n", "meta": {"author": "Hughshine", "repo": "promising-comp", "sha": "bd8e0f0463c8cdec1efa69320b1e137f6450f373", "save_path": "github-repos/coq/Hughshine-promising-comp", "path": "github-repos/coq/Hughshine-promising-comp/promising-comp-bd8e0f0463c8cdec1efa69320b1e137f6450f373/src/result/CorrectOpt.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6297746074044135, "lm_q2_score": 0.3208212943308302, "lm_q1q2_score": 0.20204510468417436}}
{"text": "Require Import Coq.ZArith.ZArith.\nRequire Import Coq.Lists.List.\nRequire Import Crypto.AbstractInterpretation.AbstractInterpretation.\nRequire Import Crypto.Bedrock.Field.Common.Types.\nRequire Import Crypto.Language.API.\nRequire Import Crypto.Util.Option.\n\nImport Language.API.Compilers AbstractInterpretation.Compilers.\nImport Types.Notations.\n#[global]\nExisting Instances rep.Z rep.listZ_mem.\n\nSection with_parameters.\n  Context \n    {width BW word mem locals env ext_spec varname_gen error}\n   `{parameters_sentinel : @parameters width BW word mem locals env ext_spec varname_gen error}.\n\n  Fixpoint list_lengths_repeat_base (n : nat) t : base_listonly nat t :=\n    match t as t0 return base_listonly nat t0 with\n    | base.type.prod a b =>\n      (list_lengths_repeat_base n a, list_lengths_repeat_base n b)\n    | base_listZ => n\n    | _ => tt\n    end.\n  Fixpoint list_lengths_repeat_args (n : nat) t\n    : type.for_each_lhs_of_arrow list_lengths t :=\n    match t as t0 return type.for_each_lhs_of_arrow list_lengths t0 with\n    | type.base b => tt\n    | type.arrow (type.base s) d =>\n      (list_lengths_repeat_base n s, list_lengths_repeat_args n d)\n    | type.arrow s d => (tt, list_lengths_repeat_args n d)\n    end.\n\n  (* mostly a duplicate of list_lengths_from_value, just with ZRange interp *)\n  Fixpoint list_lengths_from_bounds {t}\n    : ZRange.type.base.option.interp t -> option (base_listonly nat t) :=\n    match t as t0 return\n          ZRange.type.base.option.interp t0 -> option (base_listonly nat t0) with\n    | base.type.prod a b =>\n      fun x =>\n        (x1 <- list_lengths_from_bounds (fst x);\n           x2 <- list_lengths_from_bounds (snd x);\n           Some (x1, x2))%option\n    | base_listZ =>\n      fun x : option (list _) => option_map (@List.length _) x\n    | _ => fun _ => Some tt\n    end.\n  Fixpoint list_lengths_from_argbounds {t}\n    : type.for_each_lhs_of_arrow ZRange.type.option.interp t ->\n      option (type.for_each_lhs_of_arrow list_lengths t) :=\n    match t as t0 return\n          type.for_each_lhs_of_arrow _ t0 ->\n          option (type.for_each_lhs_of_arrow _ t0) with\n    | type.base b => fun _ => Some tt\n    | type.arrow (type.base a) b =>\n      fun x =>\n        (x1 <- list_lengths_from_bounds (fst x);\n           x2 <- list_lengths_from_argbounds (snd x);\n           Some (x1, x2))%option\n    | type.arrow a b => fun _ => None\n    end.\nEnd with_parameters.\n", "meta": {"author": "mit-plv", "repo": "fiat-crypto", "sha": "750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579", "save_path": "github-repos/coq/mit-plv-fiat-crypto", "path": "github-repos/coq/mit-plv-fiat-crypto/fiat-crypto-750f7b69e0ef4ad6841fc0cbef3f7f65c2f80579/src/Bedrock/Field/Common/Arrays/MakeListLengths.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.20202608152709217}}
{"text": "From PCC Require Import list_utils java_basic_defs expressions_assertions.\nFrom Coq Require Import List Bool ZArith.\nFrom PCC Require Import ssrexport.\n\nSection ProgramModel.\n  \nOpen Scope type_scope.\n\nDefinition ghost_update := ghostid * expr.\n\nInductive instr : Set :=\n| aload (_: nat)\n| astore (_: nat)\n| athrow\n| dup\n| getfield (_: fieldid)\n| getstatic (_: classid) (_: fieldid)\n| goto (_: label)\n| iadd\n| iconst (_: Z)\n| ifeq (_: label)\n| invoke (_: classid) (_: methid)\n| putstatic (_: classid) (_: fieldid)\n| ldc (_: jvalue)\n| exit\n| ret\n| nop\n| ghost_instr (_: ghost_update).\n\n(* Exception handler records (rows in the exception handler table) *)\nRecord eh_record : Set := {\n  start_label  : label;\n  end_label    : label;\n  target_label : label;\n  handled_classes : classid\n}.\n\nDefinition eh_table := list eh_record.\n\n(* \n   A label function is used to look up successor-labels. It used to \n   be 'S' (the nat successor-funciotn) but that quickly became insufficient \n   when inserting ghost-instructions.\n*)\nDefinition label_function := label -> label.\n\n(* \n   We're skipping the regular method definition and jump straight to the\n   extended version which includes assertions. \n*)\nRecord method := {\n  code_of: label -> instr;\n  annotations_of : label -> ast;\n  eh_table_of: eh_table;\n  label_function_of: label_function\n}.\n\n(* \n   No field declarations at this point. Wi simply assume that all fields \n   accessed by the program has been properly declared. \n *)\nDefinition class := methid -> method.\n\n(* Local variables store. *)\nDefinition lstore := nat -> jvalue.\n\nDefinition emptylstore : lstore := fun x => undefval.\n\nDefinition upd (ls:lstore) (n:nat) (v:jvalue) : lstore :=\n  fun x => if beq_nat x n then v else ls x.\n\n(* A heap consists of a dynamic part (dheap) and static part (sheap). *)\nDefinition dheap := loc -> option object.\n\nDefinition sheap := classid -> fieldid -> option jvalue.\n\nDefinition heap := dheap * sheap.\n\nDefinition empty_heap : heap := (fun l => None, fun c f => None).\n\nDefinition upd_sheap (h:heap) (cid:classid) (fid:fieldid) (v:jvalue) : heap :=\n  (fst h, fun c f => if beq_nat c cid && beq_nat f fid then Some v else (snd h) c f).\n\nNotation \"ls '[[' n '⟼' v ']]'\" := (upd ls n v) (at level 90).\n\n(* Activation records. *)\nInductive act_record : Set :=\n| normal (_: classid) (_: methid) (_: label) (_: stack) (_: lstore)\n| exceptional (_: loc).\n\nRecord program := {\n  classes: classid -> class;\n  inv: ast\n}.\n\n(* Main class and main method are assumed to be these constants. *)\nDefinition maincid : classid := O.\n\nDefinition mainmid : methid := O.\n\nDefinition ghost_valuation := ghostid -> value.\n\n(* We assume that the default value for ghost variables is 0. (Since the undefval is\n   reserved for the notion of \"going wrong\".) *)\nDefinition initial_gv : ghost_valuation := fun l => intval 0. \n\nDefinition upd_gv (gv: ghost_valuation) (var: ghostid) (val: value) : ghost_valuation :=\n  (fun v => if beq_nat v var then val else gv v).\n\n(* We go straight to extended configurations. *)\nDefinition conf := ghost_valuation * heap * (list act_record).\n\nDefinition execution := list conf.\n\n(* Convenience access methods  *)\nDefinition instr_at (p: program) c m l : instr := code_of (classes p c m) l.\n\nDefinition minstr_at (m: method) l : instr := code_of m l.\n\nDefinition ast_at   (p: program) c m l : ast   := annotations_of (classes p c m) l.\n\nDefinition successor (p: program) c m l := label_function_of (classes p c m) l.\n\nDefinition stack_of (c: conf) : option stack :=\n  match c with (_, _, (normal _ _ _ s _)::_) => Some s | _ => None end.\n\nDefinition lstore_of (c: conf) : option lstore :=\n  match c with (_, _, (normal _ _ _ _ ls)::_) => Some ls | _ => None end.\n\nDefinition class_of (c: conf) : option classid :=\n  match c with (_, _, (normal c _ _ _ _)::_) => Some c | _ => None end.\n\nDefinition meth_of (c: conf) : option methid :=\n  match c with (_, _, (normal _ m _ _ _)::_) => Some m | _ => None end.\n\nDefinition heap_of (c: conf) : heap := snd (fst c).\n\nDefinition ars_of (c: conf) : (list act_record) := snd c.\n\nDefinition ghost_valuation_of (c: conf) : ghost_valuation := fst (fst c).\n\nDefinition current_instr (p: program) (cnf: conf) : option instr :=\n  match cnf with (_, _, (normal c m pc _ _)::_) => \n    Some (instr_at p c m pc) | _ => None end.\n\nDefinition current_ast (p: program) (cnf: conf) : option ast :=\n  match cnf with (_, _, (normal c m pc _ _)::_) => \n    Some (ast_at p c m pc) | _ => None end.\n\nDefinition current_label (cnf: conf) : option label :=\n  match cnf with (_, _, (normal _ _ pc _ _)::_) => Some pc | _ => None end.\n\nLemma current_to_instr_at : forall pg p c m pc s l1 l i, \n  current_instr pg (p, normal c m pc s l1 :: l) = Some i ->\n  instr_at pg c m pc = i.\nProof.\nmove => pg p c m pc s l1 l i H.\ninversion H as [H0].\nmove: p H H0; case => g h H H0.\nby inversion H0.\nQed.\n\nLemma instr_at_to_current : forall pg p c m pc s l1 l i, \n  instr_at pg c m pc = i -> current_instr pg (p, normal c m pc s l1 :: l) = Some i.\nProof.\nmove => pg p c m pc s l1 l i H.\nrewrite /current_instr.\ncase: p => g h.\nby rewrite H.\nQed.\n\n(*\n  To  show ∥wp(A)∥ C <-> ∥A∥ C' later on, we need a lemma (in the neg case) \n  relating aeval and aeval_f in the following way:\n\n  (aeval a c <-> aeval a' c') -> (aeval_f a c <-> aeval_f a' c')       (1)\n\n  This fact requires more than just [aeval a c -> ~aeval_f a c] and vice versa,\n  since if there is an undefined expression (s.t. [~aeval undef c] and \n  [~ aeval_f undef c]) we get the following counter example:\n\n  (aeval ff c <-> aeval undef c') -> (aeval_f ff c <-> aeval_f undef c')\n\n  Fact (1) relies on a stronger fact that\n\n  ~ (aeval a c <-> aeval_f a c)      (2)\n\n  Showing (2) requires that aeval_f is true/defined for all cases in which\n  aeval is not true/defined. For example, if the heap is ill-typed, this has \n  to be taken into account in aeval_f.\n\n  This in turn requires that all expressions can be evaluated to a value, no\n  matter the context.\n*)\n\nDefinition is_intval (v: value) : Prop := exists i, v = intval i.\n\nInductive eeval : expr -> conf -> value -> Prop :=\n| e_val : forall c v, eeval (valexp v) c v\n| e_nsfield : forall gv c e dh sh ars f l obj, c = (gv, (dh, sh), ars) -> \n    eeval e c (refval l) -> dh l = Some obj -> eeval (nsfield e f) c (obj f)\n| e_sfield : forall gv c dh sh ars cid f v, c = (gv, (dh, sh), ars) -> \n    sh cid f = Some v -> eeval (sfield cid f) c v\n| e_ghosterr : forall c, eeval ghost_errval c ghost_errval\n| e_plus : forall c e1 e2 i j, eeval e1 c (intval i) -> \n    eeval e2 c (intval j) -> eeval (plus e1 e2) c (intval (i + j))\n| e_guard_true : forall c eg et ef v, eeval eg c (boolval true ) -> \n    eeval et c v -> eeval (guarded eg et ef) c v\n| e_guard_other : forall c eg et ef v, eeval eg c (boolval false) -> \n    eeval ef c v -> eeval (guarded eg et ef) c v\n| e_stack : forall c n s, stack_of c = Some s -> eeval (stackexp n) c (s[[n]])\n| e_local : forall c n ls, lstore_of c = Some ls -> eeval (local n) c (ls n)\n| e_ghostvar : forall c gvarid, eeval (ghost_var gvarid) c ((ghost_valuation_of c) gvarid)\n| e_nsfield_err1 : forall c e v f, eeval e c v -> (forall l, v <> refval l) -> \n    eeval (nsfield e f) c undefval\n| e_nsfield_err2 : forall gv c e dh sh ars f l, c = (gv, (dh, sh), ars) -> \n    eeval e c (refval l) -> dh l = None -> eeval (nsfield e f) c undefval\n| e_sfield_err : forall gv c dh sh ars cid f, c = (gv, (dh, sh), ars) -> \n    sh cid f = None -> eeval (sfield cid f) c undefval\n| e_plus_err : forall c e1 e2 v1 v2, eeval e1 c v1 -> eeval e2 c v2 -> \n    ~ is_intval v1 \\/ ~ is_intval v2 -> eeval (plus e1 e2) c undefval\n| e_guard_err : forall c eg et ef v, eeval eg c v -> (forall b, v <> boolval b) -> \n    eeval (guarded eg et ef) c undefval.\n\n(* Transitions (activation record related) *)\nInductive artrans : program -> act_record -> act_record -> Prop :=\n| tr_aload : forall p c m pc n s ls ar1 ar2,\n    instr_at p c m pc = aload n ->\n    ar1 = normal c m pc s ls ->\n    ar2 = normal c m (successor p c m pc) (ls n::s) ls ->\n    artrans p ar1 ar2\n| tr_astore : forall p c m pc s n ls v ar1 ar2,\n    instr_at p c m pc = astore n ->\n    ar1 = normal c m pc (v::s) ls ->\n    ar2 = normal c m (successor p c m pc) s (ls[[n ⟼ v]]) ->\n    artrans p ar1 ar2\n| tr_dup : forall p c m pc s ls v ar1 ar2,\n    instr_at p c m pc = dup ->\n    ar1 = normal c m pc (v::s) ls ->\n    ar2 = normal c m (successor p c m pc) (v::v::s) ls ->\n    artrans p ar1 ar2\n| tr_goto : forall p c m l pc s ls ar1 ar2,\n    instr_at p c m pc = goto l ->\n    ar1 = normal c m pc s ls ->\n    ar2 = normal c m l  s ls ->\n    artrans p ar1 ar2\n| tr_iconst : forall p c m pc n ls s ar1 ar2,\n    instr_at p c m pc = iconst n ->\n    ar1 = normal c m pc s ls ->\n    ar2 = normal c m (successor p c m pc) ((intval n)::s) ls ->\n    artrans p ar1 ar2\n| tr_ldc : forall p c m pc s ls v ar1 ar2,\n    instr_at p c m pc = ldc v ->\n    ar1 = normal c m pc s ls ->\n    ar2 = normal c m (successor p c m pc) (v::s) ls ->\n    artrans p ar1 ar2\n| tr_ifeq_true : forall p c m pc s ls l v ar1 ar2,\n    instr_at p c m pc = ifeq l ->\n    v = boolval true ->\n    ar1 = normal c m pc (v::s) ls ->\n    ar2 = normal c m l s ls ->\n    artrans p ar1 ar2\n| tr_ifeq_false : forall p c m pc s ls l v ar1 ar2,\n    instr_at p c m pc = ifeq l ->\n    v = boolval false ->\n    ar1 = normal c m pc (v::s) ls ->\n    ar2 = normal c m l s ls ->\n    artrans p ar1 ar2.\n    \n(* Transitions (heap releated) *)\nInductive htrans : program -> conf -> conf -> Prop :=\n| tr_putstatic : forall p c cid fid ars m pc v s ls h c1 c2 ar1 ar2 gv,\n    instr_at p c m pc = putstatic cid fid ->\n    ar1 = normal c m pc (v::s) ls ->\n    ar2 = normal c m (successor p c m pc) (v::s) ls ->\n    c1 = (gv, h, ar1::ars) ->\n    c2 = (gv, upd_sheap h cid fid v, ar2::ars) ->\n    htrans p c1 c2\n| tr_getstatic : forall p c cid fid ars m pc v s ls h c1 c2 ar1 ar2 gv,\n    instr_at p c m pc = getstatic cid fid ->\n    ar1 = normal c m pc s ls ->\n    ar2 = normal c m (successor p c m pc) (v::s) ls ->\n    c1 = (gv, h, ar1::ars) ->\n    c2 = (gv, h, ar2::ars) ->\n    htrans p c1 c2.\n  \n(* Ghost instruction transitions *)\n(* Just a stub as of now. *)\nInductive g_eeval : expr -> ghost_valuation -> value -> Prop :=\n| ge_val : forall s v, g_eeval (valexp v) s v\n| ge_gv : forall gv gid, g_eeval (ghost_var gid) gv (gv gid)\n| ge_nsfield : forall e f gv, g_eeval (nsfield e f) gv undefval\n| ge_sfield : forall gv cid f, g_eeval (sfield cid f) gv undefval\n| ge_stackexp : forall gv n, g_eeval (stackexp n) gv undefval\n| ge_local : forall gv l, g_eeval (local l) gv undefval\n| ge_plus : forall gv e1 e2, g_eeval (plus e1 e2) gv undefval\n| ge_guarded : forall gv e1 e2 e3, g_eeval (guarded e1 e2 e3) gv undefval.\n    \nInductive ghosttrans : program -> conf -> conf -> Prop :=\n| tr_ghost_upd :\n    forall h ars s ls p c m pc gvar e gv v,\n      instr_at p c m pc = ghost_instr (gvar, e) -> g_eeval e gv v ->\n    ghosttrans p (gv, h, (normal c m pc s ls) :: ars)\n      (upd_gv gv gvar v, h, (normal c m (successor p c m pc) s ls) :: ars).\n    \n(* Transitions (invoke-related) *)\nInductive invtrans : program -> conf -> conf -> Prop :=\n| tr_invoke : forall p c m pc cid mid s ls c1 c2 h ar1 ar2 ars gv,\n    instr_at p c m pc = invoke cid mid ->\n    ar1 = normal c m pc s ls ->\n    ar2 = normal c m (successor p c m pc) s ls ->\n    c1 = (gv, h, ar1::ars) ->\n    c2 = (gv, h, (normal cid mid O emptystack emptylstore)::ar2::ars) ->\n    invtrans p c1 c2.\n    \n(* Transitions (exceptional) *)\n(* Not implemented as of now. *)  \n  \n(* Transitions Combined (Only activation record related as of now.) *)\nInductive trans : program -> conf -> conf -> Prop :=\n| tr_ar : forall prog ar1 ar2 ars h c1 c2 gv,\n    c1 = (gv, h, ar1::ars) ->\n    c2 = (gv, h, ar2::ars) ->\n    artrans prog ar1 ar2 ->\n    trans prog c1 c2\n| tr_ghost : forall p c c', ghosttrans p c c' -> trans p c c'.\n  \nInductive trans_star : program -> execution -> Prop :=\n| tr_star_nil : forall p, trans_star p nil\n| tr_star_sing : forall p c, trans_star p (c :: nil)\n| tr_star_step : forall p c c' e, trans p c c' ->\n    trans_star p (c' :: e) ->\n    trans_star p (c :: c' :: e).\n  \nLemma trans_star_seq : forall p c e1 e2,\n  trans_star p (e1 ++ c :: nil) -> trans_star p (c :: e2) ->\n  trans_star p (e1 ++ c :: e2).\nProof.\nmove => p c.\nelim => [|c']; first by [].\ncase => [|c0 l] IH e2 H0 H1; rewrite -app_comm_cons /=.\n- by apply tr_star_step; inversion H0.\n- apply tr_star_step; first by inversion H0.\n  rewrite /= in IH; apply IH; last by [].\n  by inversion H0.\nQed.\n\nLemma trans_star_suff : forall p e e', trans_star p (e ++ e') -> trans_star p e'.\nProof.\nmove => p.\nelim => [|c e IH e' H]; first by [].\nby apply IH; inversion H; first by apply tr_star_nil.\nQed.\n\nDefinition initial_conf (c: conf) : Prop := \n  c = (initial_gv, empty_heap, \n    (normal maincid mainmid O emptystack (fun n => undefval))::nil).\n\nInductive execution_of p : execution -> Prop :=\n| exec_intros : forall exec,\n    (forall c, head exec = Some c -> initial_conf c) ->\n    (forall pref c c' suff, exec = pref ++ c :: c' :: suff -> trans p c c') ->\n    execution_of p exec.\n\n(* \n   An alternative approach would have been to define execution as a dependent\n   inductive type directly based on initial_conf and trans. Such approach,\n   would be cleaner in many ways, but would unfortunately prevent us from\n   using all the nice list lemmas and induction principles in the coq\n   library.\n   \n   Same goes for the approach { ex : list conf | execution_of p ex } since\n   elements of this type are not lists either. \n*)\n\nDefinition max_execution_of p e : Prop :=\n  execution_of p e /\\ ~ exists c, execution_of p (e ++ c :: nil).\n\nLemma exec_nil : forall p, execution_of p nil.\nProof.\nmove => p.\napply exec_intros; first by [].\nmove => pref c c' suffx H.\nby contradict H; auto with datatypes.\nQed.\n\nLemma exec_sing_impl_initial : forall p c, execution_of p (c :: nil) -> initial_conf c.\nProof.\nmove => p c H_exec.\ninversion H_exec as [exec H_init H_trans H_eq].\nby apply H_init.\nQed.\n\nLemma exec_append : forall p e c c', execution_of p (e ++ c :: nil) -> trans p c c' ->\n  execution_of p (e ++ c :: c' :: nil).\nProof.\nmove => p e c c' H_exec H_trans.\ninversion H_exec as [e' H_init H_suff H_eq].\napply exec_intros.\n- pose proof (list_same_head e c c') as H_head.\n  move => c0 H_some.\n  rewrite -H_head in H_some.\n  by apply H_init.\n- move => pref c0 c1.\n  case => [|c2 suffx] H_pref.\n  * rewrite list_rearrange in H_pref.\n    have H_re: pref ++ c0 :: c1 :: nil = (pref ++ c0 :: nil) ++ c1 :: nil.\n      by rewrite list_rearrange.\n    rewrite H_re {H_re} in H_pref.\n    apply app_inj_tail in H_pref.\n    move: H_pref => [H_pref H_cc'].\n    apply app_inj_tail in H_pref.\n    move: H_pref => [H_e H_c].\n    by rewrite -H_cc' -H_c.\n  * apply (H_suff pref c0 c1 (removelast (c2 :: suffx))).\n    have H_rl : removelast (e ++ c :: c' :: nil) = removelast (pref ++ c0 :: c1 :: c2 :: suffx).\n      by rewrite H_pref.\n    have H_neq : c :: c' :: nil <> nil by [].    \n    rewrite (removelast_app e H_neq) /= {H_neq} in H_rl.\n    have H_re: pref ++ c0 :: c1 :: c2 :: suffx = (pref ++ c0 :: c1 :: nil) ++ c2 :: suffx.\n      by rewrite app_ass -app_comm_cons.\n    rewrite H_re {H_re} in H_rl.\n    have H_nnil: c2 :: suffx <> nil by [].\n    rewrite (removelast_app (pref ++ c0 :: c1 :: nil) H_nnil) {H_nnil} in H_rl.\n    by rewrite H_rl app_ass -app_comm_cons.\nQed.\n  \nLemma exec_impl_trans_star : forall p e, execution_of p e -> trans_star p e.\nProof.\nmove => p e H_exec.\ninversion H_exec as [e' H_init H_suff H_eq].\nmove: e H_suff {H_exec H_init H_eq e'}. \nelim => [H_suff|c]; first by apply tr_star_nil.\ncase => [|c' l] H_suff H_pref; first by apply tr_star_sing.\napply tr_star_step; first by apply (H_pref nil c c' l). \napply H_suff => pref c0 c1 suffx H_eq.\napply H_pref with (pref := c :: pref) (suff := suffx).\nby rewrite H_eq.\nQed.\n\nDefinition complete_execution_of p ex : Prop :=\n  execution_of p ex /\\ ~exists c', execution_of p (ex ++ c' :: nil).\n\nInductive normal_conf : conf -> Prop :=\n| is_norm_conf : forall h c m pc s ls ars gv, \n    normal_conf (gv, h, (normal c m pc s ls)::ars).\n\nInductive exceptional_conf : conf -> Prop :=\n| is_exc_conf : forall h o ars gv, exceptional_conf (gv, h, (exceptional o)::ars).\n\nInductive calling_conf p : conf -> Prop :=\n| call_conf : forall gv h c m pc l ls ars,\n  trans p (gv, h, ars) (gv, h, (normal c m pc l ls)::ars) ->\n  calling_conf p (gv, h, ars).\n\nInductive returning_conf p : conf -> Prop :=\n| ret_norm_conf : forall h ar ars,\n  trans p (h, ar::ars) (h, ars) ->\n  returning_conf p (h, ar::ars).\n\nDefinition visible_conf p c : Prop :=\n  calling_conf p c \\/ returning_conf p c.\n\nEnd ProgramModel.\n", "meta": {"author": "palmskog", "repo": "pcc", "sha": "2b16af3e282268e4f4adc9f6b7d3fda082b4a101", "save_path": "github-repos/coq/palmskog-pcc", "path": "github-repos/coq/palmskog-pcc/pcc-2b16af3e282268e4f4adc9f6b7d3fda082b4a101/theories/program_model.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.20202608152709214}}
{"text": "Require Import Recdef.\nRequire Import VST.floyd.proofauto.\nLocal Open Scope logic.\nRequire Import List. Import ListNotations.\nRequire Import sha.general_lemmas.\n\n(* TODO remove this line and update proof (should become simpler) *)\nLtac canon_load_result ::= idtac.\n\nRequire Import tweetnacl20140427.split_array_lemmas.\nRequire Import ZArith.\nRequire Import tweetnacl20140427.tweetNaclBase.\nRequire Import tweetnacl20140427.Salsa20.\nRequire Import tweetnacl20140427.verif_salsa_base.\nRequire Import tweetnacl20140427.tweetnaclVerifiableC.\nRequire Import tweetnacl20140427.spec_salsa. Opaque Snuffle.Snuffle.\nRequire Import VST.floyd.library.\n\nOpaque littleendian.\n    Opaque littleendian_invert. Opaque Snuffle20. Opaque prepare_data.\n    Opaque QuadByte2ValList. Opaque fcore_result.\n\nDefinition wlistJ' (wlist:list val) (j: Z) (t0 t1 t2 t3:int) (l: list val): Prop :=\n  Zlength l = 16 /\\\n  l = upd_Znth (4 * j + (j + 3) mod 4)\n       (upd_Znth (4 * j + (j + 2) mod 4)\n         (upd_Znth (4 * j + (j + 1) mod 4)\n          (upd_Znth (4 * j + (j + 0) mod 4) wlist (Vint t0))\n          (Vint t1)) (Vint t2)) (Vint t3).\n\nFixpoint WLIST' (wlist : list val) (tlist: list int) (j:Z) m l :=\n  match m with\n    O => l=wlist\n  | S m' => exists l' tm,\n            Zlength l = Zlength wlist /\\\n            WLIST' wlist tlist j m' l' /\\\n            Znth (Z.of_nat m') (map Vint tlist) Vundef = Vint tm /\\\n            l = upd_Znth (4*j+ ((j+Z.of_nat m') mod 4)) l' (Vint tm)\n  end.\n\nLemma WLIST'_length wlist tlist j : forall m l, WLIST' wlist tlist j m l -> Zlength l=Zlength wlist.\nProof. induction m; simpl; intros; subst; trivial.\n  destruct H as [l' [tm [ L [W [ZZ LL]]]]]. subst. apply IHm in W; trivial.\nQed.\n\nDefinition Wcopyspec (t0 t1 t2 t3: int):=\n(Int.xor t0\n        (Int.rol\n           (Int.add\n              (Int.xor t3\n                 (Int.rol\n                    (Int.add\n                       (Int.xor t2\n                          (Int.rol\n                             (Int.add\n                                (Int.xor t1\n                                   (Int.rol (Int.add t0 t3) (Int.repr 7))) t0)\n                             (Int.repr 9)))\n                       (Int.xor t1 (Int.rol (Int.add t0 t3) (Int.repr 7))))\n                    (Int.repr 13)))\n              (Int.xor t2\n                 (Int.rol\n                    (Int.add\n                       (Int.xor t1 (Int.rol (Int.add t0 t3) (Int.repr 7))) t0)\n                    (Int.repr 9)))) (Int.repr 18)),\n  Int.xor t1 (Int.rol (Int.add t0 t3) (Int.repr 7)),\n  Int.xor t2\n       (Int.rol\n          (Int.add (Int.xor t1 (Int.rol (Int.add t0 t3) (Int.repr 7))) t0)\n          (Int.repr 9)),\n  Int.xor t3\n       (Int.rol\n          (Int.add\n             (Int.xor t2\n                (Int.rol\n                   (Int.add\n                      (Int.xor t1 (Int.rol (Int.add t0 t3) (Int.repr 7))) t0)\n                   (Int.repr 9)))\n             (Int.xor t1 (Int.rol (Int.add t0 t3) (Int.repr 7))))\n          (Int.repr 13))).\n\nLemma SixteenWR_Znth_int' s i:\n  0 <= i < 16 -> exists ii : int, Znth i (SixteenWordRep s) Vundef = Vint ii.\nProof. apply SixteenWR_Znth_int. Qed.\n\nDefinition array_copy1_statement :=\n  (Sfor (Sset _m (Econst_int (Int.repr 0) tint))\n     (Ebinop Olt (Etempvar _m tint) (Econst_int (Int.repr 4) tint) tint)\n     (Ssequence\n        (Sset _t'33\n           (Ederef\n              (Ebinop Oadd (Evar _x (tarray tuint 16))\n                 (Ebinop Omod\n                    (Ebinop Oadd\n                       (Ebinop Omul (Econst_int (Int.repr 5) tint)\n                          (Etempvar _j tint) tint)\n                       (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                          (Etempvar _m tint) tint) tint)\n                    (Econst_int (Int.repr 16) tint) tint) (tptr tuint)) tuint))\n        (Sassign\n           (Ederef\n              (Ebinop Oadd (Evar _t (tarray tuint 4)) (Etempvar _m tint)\n                 (tptr tuint)) tuint) (Etempvar _t'33 tuint)))\n     (Sset _m\n        (Ebinop Oadd (Etempvar _m tint) (Econst_int (Int.repr 1) tint) tint))).\nLemma array_copy1: forall (Espec: OracleKind) j t x (xs:list int)\n  (J:0<=j<4),\n semax (initialized_list [_i; _j]\n     (func_tycontext f_core SalsaVarSpecs SalsaFunSpecs))\n  (PROP  ()\n   LOCAL  (temp _j (Vint (Int.repr j));\n   lvar _t (tarray tuint 4) t;\n   lvar _x (tarray tuint 16) x)\n   SEP  (data_at_ Tsh (tarray tuint 4) t;\n           data_at Tsh (tarray tuint 16) (@map int val Vint xs) x))\n   array_copy1_statement\n  (normal_ret_assert\n  (PROP  ()\n   LOCAL  (temp _m (Vint (Int.repr 4)); temp _j (Vint (Int.repr j));\n   lvar _t (tarray tuint 4) t;\n   lvar _x (tarray tuint 16) x)\n   SEP  (data_at Tsh (tarray tuint 16) (map Vint xs) x;\n     EX  l : list val,\n     !!(forall mm : Z,\n         0 <= mm < 4 ->\n         Znth mm l Vundef =\n         Znth ((5 * j + 4 * mm) mod 16) (map Vint xs) Vundef)\n        && data_at Tsh (tarray tuint 4) l t))).\nProof. intros. unfold array_copy1_statement. abbreviate_semax.\n  assert_PROP (Zlength (map Vint xs) = 16) as XL by entailer!. (*1*)\n  forward_for_simple_bound 4\n (EX m:Z,\n  (PROP  ()\n   LOCAL  (temp _j (Vint (Int.repr j)); lvar _t (tarray tuint 4) t;\n   lvar _x (tarray tuint 16) x)\n   SEP  (EX l:_, !!(forall mm, 0<=mm<m -> Znth mm l Vundef =\n                  Znth ((5*j+4*mm) mod 16) (map Vint xs) Vundef)\n            && data_at Tsh (tarray tuint 4) l t;\n       data_at Tsh (tarray tuint 16) (map Vint xs) x))).\n  (*1.3*)\n  { Exists (list_repeat 4 Vundef). (*Time*) entailer!. (*2.2*)  intros; omega. }\n  { rename i into m. rename H into M. Intros T.\n    rename H into HT.\n    (*Time*) assert_PROP (Zlength T = 4) as TL by entailer!. (*2.2 versus 5.7*)\n    destruct (Z_mod_lt (5 * j + 4 * m) 16) as [M1 M2]. omega.\n    destruct (Znth_mapVint xs ((5 * j + 4 * m) mod 16) Vundef) as [v NV].\n       simpl in XL. rewrite <- (Zlength_map _ _ Vint xs), XL. split; assumption.\n    forward.\n    { apply prop_right. unfold Int.mods. (* rewrite ! mul_repr, add_repr.*)\n      rewrite ! Int.signed_repr.\n      2: rewrite int_max_signed_eq, int_min_signed_eq; omega.\n      2: rewrite int_max_signed_eq, int_min_signed_eq; omega.\n      rewrite Z.rem_mod_nonneg; try omega.\n      rewrite Int.unsigned_repr. omega. \n      rewrite int_max_unsigned_eq; omega. }\n    { unfold Int.mods. \n      rewrite ! Int.signed_repr.\n      2: rewrite int_max_signed_eq, int_min_signed_eq; omega.\n      2: rewrite int_max_signed_eq, int_min_signed_eq; omega.\n      rewrite Z.rem_mod_nonneg; try omega.\n      rewrite Int.unsigned_repr, NV. 2: rewrite int_max_unsigned_eq; omega. \n      entailer!. \n      rewrite andb_false_intro2. simpl; trivial. cbv; trivial. }\n    unfold Int.mods. \n    rewrite ! Int.signed_repr.\n    2: rewrite int_max_signed_eq, int_min_signed_eq; omega.\n    2: rewrite int_max_signed_eq, int_min_signed_eq; omega.\n    rewrite Z.rem_mod_nonneg; try omega.\n    forward.\n    { entailer!. rewrite NV. simpl. Exists (upd_Znth m T (Vint v)). entailer!.\n      intros mm ?.\n      destruct (zeq mm m); subst.\n      + rewrite upd_Znth_same; try omega. rewrite NV; trivial.\n      + rewrite upd_Znth_diff; try omega. apply HT; omega. }\n  }\n  entailer!.\nQed. \n\nDefinition Jbody_statement :=\n  (Ssequence\n     (Sfor (Sset _m (Econst_int (Int.repr 0) tint))\n        (Ebinop Olt (Etempvar _m tint) (Econst_int (Int.repr 4) tint) tint)\n        (Ssequence\n           (Sset _t'33\n              (Ederef\n                 (Ebinop Oadd (Evar _x (tarray tuint 16))\n                    (Ebinop Omod\n                       (Ebinop Oadd\n                          (Ebinop Omul (Econst_int (Int.repr 5) tint)\n                             (Etempvar _j tint) tint)\n                          (Ebinop Omul (Econst_int (Int.repr 4) tint)\n                             (Etempvar _m tint) tint) tint)\n                       (Econst_int (Int.repr 16) tint) tint) (tptr tuint))\n                 tuint))\n           (Sassign\n              (Ederef\n                 (Ebinop Oadd (Evar _t (tarray tuint 4)) (Etempvar _m tint)\n                    (tptr tuint)) tuint) (Etempvar _t'33 tuint)))\n        (Sset _m\n           (Ebinop Oadd (Etempvar _m tint) (Econst_int (Int.repr 1) tint)\n              tint)))\n     (Ssequence\n        (Ssequence\n           (Ssequence\n              (Sset _t'31\n                 (Ederef\n                    (Ebinop Oadd (Evar _t (tarray tuint 4))\n                       (Econst_int (Int.repr 0) tint) (tptr tuint)) tuint))\n              (Ssequence\n                 (Sset _t'32\n                    (Ederef\n                       (Ebinop Oadd (Evar _t (tarray tuint 4))\n                          (Econst_int (Int.repr 3) tint) (tptr tuint)) tuint))\n                 (Scall (Some _t'5)\n                    (Evar _L32\n                       (Tfunction (Tcons tuint (Tcons tint Tnil)) tuint\n                          cc_default))\n                    [Ebinop Oadd (Etempvar _t'31 tuint)\n                       (Etempvar _t'32 tuint) tuint;\n                    Econst_int (Int.repr 7) tint])))\n           (Ssequence\n              (Sset _t'30\n                 (Ederef\n                    (Ebinop Oadd (Evar _t (tarray tuint 4))\n                       (Econst_int (Int.repr 1) tint) (tptr tuint)) tuint))\n              (Sassign\n                 (Ederef\n                    (Ebinop Oadd (Evar _t (tarray tuint 4))\n                       (Econst_int (Int.repr 1) tint) (tptr tuint)) tuint)\n                 (Ebinop Oxor (Etempvar _t'30 tuint) (Etempvar _t'5 tuint)\n                    tuint))))\n        (Ssequence\n           (Ssequence\n              (Ssequence\n                 (Sset _t'28\n                    (Ederef\n                       (Ebinop Oadd (Evar _t (tarray tuint 4))\n                          (Econst_int (Int.repr 1) tint) (tptr tuint)) tuint))\n                 (Ssequence\n                    (Sset _t'29\n                       (Ederef\n                          (Ebinop Oadd (Evar _t (tarray tuint 4))\n                             (Econst_int (Int.repr 0) tint) (tptr tuint))\n                          tuint))\n                    (Scall (Some _t'6)\n                       (Evar _L32\n                          (Tfunction (Tcons tuint (Tcons tint Tnil)) tuint\n                             cc_default))\n                       [Ebinop Oadd (Etempvar _t'28 tuint)\n                          (Etempvar _t'29 tuint) tuint;\n                       Econst_int (Int.repr 9) tint])))\n              (Ssequence\n                 (Sset _t'27\n                    (Ederef\n                       (Ebinop Oadd (Evar _t (tarray tuint 4))\n                          (Econst_int (Int.repr 2) tint) (tptr tuint)) tuint))\n                 (Sassign\n                    (Ederef\n                       (Ebinop Oadd (Evar _t (tarray tuint 4))\n                          (Econst_int (Int.repr 2) tint) (tptr tuint)) tuint)\n                    (Ebinop Oxor (Etempvar _t'27 tuint) (Etempvar _t'6 tuint)\n                       tuint))))\n           (Ssequence\n              (Ssequence\n                 (Ssequence\n                    (Sset _t'25\n                       (Ederef\n                          (Ebinop Oadd (Evar _t (tarray tuint 4))\n                             (Econst_int (Int.repr 2) tint) (tptr tuint))\n                          tuint))\n                    (Ssequence\n                       (Sset _t'26\n                          (Ederef\n                             (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                (Econst_int (Int.repr 1) tint) (tptr tuint))\n                             tuint))\n                       (Scall (Some _t'7)\n                          (Evar _L32\n                             (Tfunction (Tcons tuint (Tcons tint Tnil)) tuint\n                                cc_default))\n                          [Ebinop Oadd (Etempvar _t'25 tuint)\n                             (Etempvar _t'26 tuint) tuint;\n                          Econst_int (Int.repr 13) tint])))\n                 (Ssequence\n                    (Sset _t'24\n                       (Ederef\n                          (Ebinop Oadd (Evar _t (tarray tuint 4))\n                             (Econst_int (Int.repr 3) tint) (tptr tuint))\n                          tuint))\n                    (Sassign\n                       (Ederef\n                          (Ebinop Oadd (Evar _t (tarray tuint 4))\n                             (Econst_int (Int.repr 3) tint) (tptr tuint))\n                          tuint)\n                       (Ebinop Oxor (Etempvar _t'24 tuint)\n                          (Etempvar _t'7 tuint) tuint))))\n              (Ssequence\n                 (Ssequence\n                    (Ssequence\n                       (Sset _t'22\n                          (Ederef\n                             (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                (Econst_int (Int.repr 3) tint) (tptr tuint))\n                             tuint))\n                       (Ssequence\n                          (Sset _t'23\n                             (Ederef\n                                (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                   (Econst_int (Int.repr 2) tint)\n                                   (tptr tuint)) tuint))\n                          (Scall (Some _t'8)\n                             (Evar _L32\n                                (Tfunction (Tcons tuint (Tcons tint Tnil))\n                                   tuint cc_default))\n                             [Ebinop Oadd (Etempvar _t'22 tuint)\n                                (Etempvar _t'23 tuint) tuint;\n                             Econst_int (Int.repr 18) tint])))\n                    (Ssequence\n                       (Sset _t'21\n                          (Ederef\n                             (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                (Econst_int (Int.repr 0) tint) (tptr tuint))\n                             tuint))\n                       (Sassign\n                          (Ederef\n                             (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                (Econst_int (Int.repr 0) tint) (tptr tuint))\n                             tuint)\n                          (Ebinop Oxor (Etempvar _t'21 tuint)\n                             (Etempvar _t'8 tuint) tuint))))\n                 (Sfor (Sset _m (Econst_int (Int.repr 0) tint))\n                    (Ebinop Olt (Etempvar _m tint)\n                       (Econst_int (Int.repr 4) tint) tint)\n                    (Ssequence\n                       (Sset _t'20\n                          (Ederef\n                             (Ebinop Oadd (Evar _t (tarray tuint 4))\n                                (Etempvar _m tint) (tptr tuint)) tuint))\n                       (Sassign\n                          (Ederef\n                             (Ebinop Oadd (Evar _w (tarray tuint 16))\n                                (Ebinop Oadd\n                                   (Ebinop Omul\n                                      (Econst_int (Int.repr 4) tint)\n                                      (Etempvar _j tint) tint)\n                                   (Ebinop Omod\n                                      (Ebinop Oadd (Etempvar _j tint)\n                                         (Etempvar _m tint) tint)\n                                      (Econst_int (Int.repr 4) tint) tint)\n                                   tint) (tptr tuint)) tuint)\n                          (Etempvar _t'20 tuint)))\n                    (Sset _m\n                       (Ebinop Oadd (Etempvar _m tint)\n                          (Econst_int (Int.repr 1) tint) tint)))))))).\n\nLemma Jbody (Espec : OracleKind) FR c k h nonce out w x y t i j xs\n  (I : 0 <= i < 20)\n  (J : 0 <= j < 4)\n  wlist\n  t0 t1 t2 t3\n  (T0: Znth ((5*j+4*0) mod 16) (map Vint xs) Vundef = Vint t0)\n  (T1: Znth ((5*j+4*1) mod 16) (map Vint  xs) Vundef = Vint t1)\n  (T2: Znth ((5*j+4*2) mod 16) (map Vint xs) Vundef = Vint t2)\n  (T3: Znth ((5*j+4*3) mod 16) (map Vint xs) Vundef = Vint t3):\n@semax CompSpecs Espec\n  (initialized_list [_i; _j]\n     (func_tycontext f_core SalsaVarSpecs SalsaFunSpecs))\n  (PROP  ()\n   LOCAL  (temp _j (Vint (Int.repr j)); temp _i (Vint (Int.repr i));\n   lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n   lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w; temp _in nonce;\n   temp _out out; temp _c c; temp _k k; temp _h (Vint (Int.repr h)))\n   SEP  (FR; data_at_ Tsh (tarray tuint 4) t;\n         data_at Tsh (tarray tuint 16) (*(map Vint wlist)*) wlist w;\n         data_at Tsh (tarray tuint 16) (map Vint xs) x))\n  Jbody_statement\n  (normal_ret_assert\n     (PROP  (0 <= j + 1 <= 4)\n      LOCAL  (temp _j (Vint (Int.repr j)); temp _i (Vint (Int.repr i));\n      lvar _t (tarray tuint 4) t; lvar _y (tarray tuint 16) y;\n      lvar _x (tarray tuint 16) x; lvar _w (tarray tuint 16) w;\n      temp _in nonce; temp _out out; temp _c c; temp _k k;\n      temp _h (Vint (Int.repr h)))\n      SEP  (FR; data_at Tsh (tarray tuint 16) (map Vint xs) x;\n          data_at_ Tsh (tarray tuint 4) t;\n          EX W:_,\n             !!(match Wcopyspec t0 t1 t2 t3 with\n                 (s0,s1,s2,s3) => wlistJ' wlist j s0 s1 s2 s3 W\n                end)\n             && data_at Tsh (tarray tuint 16) (*(map Vint W)*)W w))).\nProof. intros. abbreviate_semax.\n  semax_frame [ ] [ FR ].\n  forward_seq.\n {\n  semax_frame [   temp _i (Vint (Int.repr i));  lvar _y (tarray tuint 16) y;\n     lvar _w (tarray tuint 16) w; temp _in nonce;\n     temp _out out; temp _c c; temp _k k; temp _h (Vint (Int.repr h))]\n    [ data_at Tsh (tarray tuint 16) wlist w ].\n  apply array_copy1; trivial. }\n  abbreviate_semax. simpl app.\n  Intros tlist.\n  rename H into HT.\n\n  assert_PROP (tlist = map Vint [t0; t1;t2;t3]) as TLI. {\n   entailer!.\n   clear - HT H3 T0 T1 T2 T3. rename H3 into TL.\n   rewrite Zlength_correct in TL. change 4 with (Z.of_nat 4) in TL.\n   apply Nat2Z.inj in TL.\n   destruct tlist as [ | x0 [ | x1 [ | x2 [ | x3 [ | ]]]]]; inv TL.\n   rewrite <- HT in T0,T1,T2,T3 by omega.\n   rewrite <- T0, <- T1, <- T2, <- T3. reflexivity.\n }\n  subst tlist.\n  clear T0 T1 T2 T3 HT.\n\nLtac compute_Znth :=\n let xx := fresh in\n   set (xx := (Znth _ (map Vint (_::_)) _));\n   compute in xx;\n   subst xx.\n\nLtac compute_upd_Znth :=\n let xx := fresh \"xx\" in\n   set (xx := (upd_Znth _ (map Vint (_::_)) (Vint _)));\n   pattern xx;\n  match goal with |- ?G xx =>\n  let g := fresh \"G\" in set (g:=G);\n  revert xx;\n  unfold upd_Znth, Zlength, sublist;\n  simpl; rewrite <- (map_nil Vint), <- ?map_cons;\n  subst g; cbv beta\n end.\n\ndeadvars!.\n  (*pattern1*)\n  forward. compute_Znth.\n  forward. compute_Znth. \n  forward_call (Int.add t0 t3, Int.repr 7).\n  forward. compute_Znth.\n  forward.\n  remember (Int.xor t1 (Int.rol (Int.add t0 t3) (Int.repr 7))) as tt0.\n  forward. compute_upd_Znth.\n\ndeadvars!.\n  (*VST Issue: mkConciseDelta SalsaVarSpecs SalsaFunSpecs f_core Delta. doesn't work any longer*)\n  (*pattern2*)\n  forward. compute_Znth.\n  forward_call (Int.add tt0 t0, Int.repr 9).\n  forward. compute_Znth.\n  forward.\n  remember (Int.xor t2 (Int.rol (Int.add tt0 t0) (Int.repr 9))) as tt1.\n  forward. compute_upd_Znth.\n\ndeadvars!.\n  (*pattern3*)\n  forward. compute_Znth.\n  forward_call (Int.add tt1 tt0, Int.repr 13).\n  forward. compute_Znth.\n  forward.\n  remember (Int.xor t3 (Int.rol (Int.add tt1 tt0) (Int.repr 13))) as tt2.\n  forward. compute_upd_Znth.\n\ndeadvars!.\n  (*pattern4*)\n  forward. compute_Znth.\n  forward_call (Int.add tt2 tt1, Int.repr 18).\n  forward. compute_Znth.\n  forward.\n  remember (Int.xor t0 (Int.rol (Int.add tt2 tt1) (Int.repr 18))) as tt3.\n\ndeadvars!.\n(*  forward. compute_upd_Znth.\n\n(* delete _aux1*) drop_LOCAL 0%nat.\n(* delete _aux*) drop_LOCAL 0%nat.\n(* delete old m*) drop_LOCAL 0%nat.*)\n(*Time*) assert_PROP (Zlength wlist=16) as WL by entailer!. (*1.6 versus 4.4*)\n\n  subst POSTCONDITION; unfold abbreviate.\n\n  semax_frame [\n   lvar _x (tarray tuint 16) x;\n   temp _i (Vint (Int.repr i));\n   lvar _y (tarray tuint 16) y; temp _in nonce;\n   temp _out out; temp _c c; temp _k k;\n   temp _h (Vint (Int.repr h))]\n    [ data_at Tsh (tarray tuint 16) (map Vint xs) x ].\n\n forward_for_simple_bound 4 (EX m:Z, EX l: list val,\n  (PROP  (WLIST' wlist [tt3; tt0; tt1; tt2] j (Z.to_nat m) l)\n   LOCAL  (temp _j (Vint (Int.repr j)); lvar _t (tarray tuint 4) t; lvar _w (tarray tuint 16) w )\n   SEP  (data_at Tsh (tarray tuint 4) (map Vint [tt3; tt0; tt1; tt2]) t;\n           data_at Tsh (tarray tuint 16) l w))).\n   (*1.2 versus 6.3*)\n{ Exists wlist. (*Time*) entailer!. (*2.4 versus 6.3*) }\n{ rename H into M; rename i0 into m.\n  rename x0 into wlist1. Intros. rename H into WLIST1.\n  assert (TM: exists tm, Znth m [Vint tt3; Vint tt0; Vint tt1; Vint tt2] Vundef = Vint tm).\n    destruct (zeq m 0); subst; simpl. eexists; reflexivity.\n    destruct (zeq m 1); subst; simpl. eexists; reflexivity.\n    destruct (zeq m 2); subst; simpl. eexists; reflexivity.\n    destruct (zeq m 3); subst; simpl. eexists; reflexivity. omega.\n  destruct TM as [tm TM].\n  forward.\n  { entailer!. rewrite TM; simpl; trivial. }\n  assert (JM: 0 <= Z.rem (j + m) 4 < 4) by (apply Zquot.Zrem_lt_pos_pos; omega).\n  assert (JM2: 0<= (j + m) mod 4 < 4) by (apply Z_mod_lt; omega).\n  deadvars!.\n  forward.\n  { entailer!. rewrite andb_false_r; simpl; trivial.\n   clear H1. clear WLIST1. clear TM. clear H.\n   rewrite and_True.\n   unfold Int.mods. rewrite (Int.signed_repr (j+m)) by rep_omega.\n   change (Int.signed (Int.repr 4)) with 4. \n   rewrite Int.signed_repr by rep_omega. rep_omega.  }\n  { apply prop_right.\n    unfold Int.mods. (*rewrite ! mul_repr, add_repr.*)\n    rewrite ! Int.signed_repr(*, add_repr, Int.signed_repr*).\n      2: rewrite int_max_signed_eq, int_min_signed_eq; omega.\n      2: rewrite int_max_signed_eq, int_min_signed_eq; omega.\n    rewrite Int.unsigned_repr. 2: rewrite int_max_unsigned_eq; omega.\n    rewrite Int.unsigned_repr. 2: rewrite int_max_unsigned_eq; omega.\n    omega. }\n  { Exists (upd_Znth (4 * j + (j + m) mod 4) wlist1 (Vint tm)). (*_id0)). *)\n    go_lower. rewrite TM. simpl. \n    apply andp_right.  \n    + apply prop_right. split. omega. split; trivial.\n      assert (AP: 0 <= (j + m) mod 4 < 4) by (apply Z_mod_lt; omega).\n      rewrite Z.add_comm. rewrite Z2Nat.inj_add; try omega.\n      assert (SS: (Z.to_nat 1 + Z.to_nat m)%nat = S (Z.to_nat m)) by reflexivity.\n      rewrite SS; simpl.\n      exists wlist1, tm.\n      assert (WL1: Zlength wlist1 = 16). erewrite WLIST'_length. 2: eassumption. assumption.\n      split. rewrite upd_Znth_Zlength. eapply WLIST'_length; eassumption.\n             rewrite WL1. omega.\n             split. trivial.\n             rewrite Z2Nat.id. split; trivial. omega. \n    + unfold Int.mods. (*rewrite ! mul_repr, add_repr.*)\n      rewrite ! Int.signed_repr(*, add_repr, Int.signed_repr*).\n        2: rewrite int_max_signed_eq, int_min_signed_eq; omega.\n        2: rewrite int_max_signed_eq, int_min_signed_eq; omega.\n      rewrite Int.unsigned_repr. 2: rewrite int_max_unsigned_eq; omega.\n      rewrite Int.unsigned_repr. 2: rewrite int_max_unsigned_eq; omega. \n      rewrite Z.rem_mod_nonneg; try omega. entailer!. }\n  } \n\nIntros l. Exists l.\nentailer!.\nsplit. assumption.\ndestruct H as [l1 [tm1 [ZL1 [XX1 [Z3 HL1]]]]].\ndestruct XX1 as [l2 [tm2 [ZL2 [XX2 [Z2 HL2]]]]].\ndestruct XX2 as [l3 [tm3 [ZL3 [XX3 [Z1 HL3]]]]].\ndestruct XX3 as [l4 [tm4 [ZL4 [XX4 [Z0 HL4]]]]].\nsimpl in *.\nsubst.\nrewrite <- Z0, <- Z1, <- Z2, <- Z3.\nreflexivity.\nTime Qed. (*June 4th,2017 (laptop):Finished transaction in 9.528 secs (8.024u,0.02s) (successful)*)\n\n", "meta": {"author": "ildyria", "repo": "coq-verif-tweetnacl", "sha": "8181ab4406cefd03ab0bd53d4063eb1644a2673d", "save_path": "github-repos/coq/ildyria-coq-verif-tweetnacl", "path": "github-repos/coq/ildyria-coq-verif-tweetnacl/coq-verif-tweetnacl-8181ab4406cefd03ab0bd53d4063eb1644a2673d/packages/coq-vst/coq-vst.2.0/tweetnacl20140427/verif_fcore_jbody.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2020214186165276}}
{"text": "Require Import ExtLib.Structures.Monads.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nImport MonadNotation.\nLocal Open Scope monad_scope.\n\nGlobal Instance Monad_option : Monad option :=\n{ ret  := @Some\n; bind := fun _ _ c1 c2 => match c1 with\n                             | None => None\n                             | Some v => c2 v\n                           end\n}.\n\nGlobal Instance Zero_option : MonadZero option :=\n{ mzero := @None }.\n\nGlobal Instance Plus_option : MonadPlus option :=\n{ mplus _A _B aM bM :=\n    match aM with\n    | None => liftM inr bM\n    | Some a => Some (inl a)\n    end\n}.\n\nSection Trans.\n  Variable m : Type -> Type.\n\n  Inductive optionT a := mkOptionT { unOptionT : m (option a) }.\n\n  Context {M : Monad m}.\n\n  Global Instance Monad_optionT : Monad optionT :=\n  { ret _A := fun x => mkOptionT (ret (Some x))\n  ; bind _A _B aMM f := mkOptionT\n      (aM <- unOptionT aMM ;;\n       match aM with\n       | None => ret None\n       | Some a => unOptionT (f a)\n       end)\n  }.\n\n  Global Instance Zero_optionT : MonadZero optionT :=\n  { mzero _A := mkOptionT (ret None) }.\n\n  Global Instance MonadT_optionT : MonadT optionT m :=\n  { lift _A aM := mkOptionT (liftM ret aM) }.\n\n  Global Instance State_optionT {T} (SM : MonadState T m) : MonadState T optionT :=\n  { get := lift get\n  ; put v := lift (put v)\n  }.\n\n  Instance Plus_optionT_right : MonadPlus optionT :=\n  { mplus _A _B a b :=\n      mkOptionT (bind (unOptionT b) (fun b =>\n        match b with\n          | None =>\n            bind (unOptionT a) (fun a =>\n                                  match a with\n                                    | None => ret None\n                                    | Some a => ret (Some (inl a))\n                                  end)\n          | Some b => ret (Some (inr b))\n        end))\n  }.\n\n  Instance Plus_optionT_left : MonadPlus optionT :=\n  { mplus _A _B a b :=\n      mkOptionT (bind (unOptionT a) (fun a =>\n        match a with\n          | None =>\n            bind (unOptionT b) (fun b =>\n                                  match b with\n                                    | None => ret None\n                                    | Some b => ret (Some (inr b))\n                                  end)\n          | Some a => ret (Some (inl a))\n        end))\n  }.\n\n  Global Instance Plus_optionT : MonadPlus optionT := Plus_optionT_left.\n\n  Global Instance Reader_optionT {T} (SM : MonadReader T m) : MonadReader T optionT :=\n  { ask := lift ask\n  ; local _T v cmd := mkOptionT (local v (unOptionT cmd))\n  }.\n\n  Instance OptionTError : MonadExc unit optionT :=\n  { raise _u _A := mzero\n  ; catch _A aMM f := mkOptionT\n      (aM <- unOptionT aMM ;;\n       match aM with\n       | None => unOptionT (f tt)\n       | Some x => ret (Some x)\n       end)\n  }.\n\nEnd Trans.\n", "meta": {"author": "UCSD-PL", "repo": "proverbot9001", "sha": "3c1f03acf2e31bca5096368f9a30d7572f81cf73", "save_path": "github-repos/coq/UCSD-PL-proverbot9001", "path": "github-repos/coq/UCSD-PL-proverbot9001/proverbot9001-3c1f03acf2e31bca5096368f9a30d7572f81cf73/coq-projects/coq-ext-lib/theories/Data/Monads/OptionMonad.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.37754065479083276, "lm_q1q2_score": 0.2020214167193091}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import ssrZ ZArith_ext seq_ext machine_int uniq_tac.\nImport MachineInt.\nRequire Import mips_cmd mips_tactics mips_contrib.\nImport expr_m.\nRequire Import copy_u_u_prg.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope mips_expr_scope.\nLocal Open Scope mips_cmd_scope.\nLocal Open Scope uniq_scope.\n\nLemma copy_u_u_termination st h rk ru rx a0 a1 a2 :\n  uniq(rk, ru, rx, a0, a1, a2, r0) ->\n  {si | Some (st, h) -- copy_u_u rk ru rx a0 a1 a2 ---> si}%mips_cmd.\nProof.\nmove=> Hset.\nrewrite /copy_u_u.\napply exists_addiu_seq.\nrewrite sext_Z2u // addi0.\napply exists_addiu_seq.\nrewrite sext_Z2u // addi0.\nrepeat Reg_upd.\nset s0 := store.upd _ _ _.\nhave [na2 Ha2] : { na2 | u2Z [rk]_s0 - u2Z [a2]_s0 = Z_of_nat na2 }%mips_expr.\n  have [va2 Hva2] : { va2 | u2Z [rk]_s0 - u2Z [a2]_s0 = va2}%mips_expr by eapply exist; reflexivity.\n  have : 0 <= va2.\n    move: Hva2.\n    rewrite /s0.\n    repeat Reg_upd.\n    rewrite Z2uK // subZ0 => <-.\n    by apply min_u2Z.\n  case/Z_of_nat_complete_inf => na2 va2_na2.\n  by exists na2; rewrite Hva2.\nmove: na2 s0 Ha2 h; elim.\n- move=> s0 Ha2 h.\n  exists (Some (s0, h)).\n  apply while.exec_while_false => /=.\n  rewrite negbK.\n  rewrite /= in Ha2.\n  apply/eqP.\n  lia.\n- move=> na2 IH s0 Hna2 h.\n  apply exists_while.\n  + rewrite /=.\n    apply/eqP => abs.\n    rewrite abs Z_S subZZ in Hna2;lia.\n  + apply exists_seq_P2 with (fun st => u2Z [rk]_(fst st) - u2Z [a2]_(fst st) = Z_of_nat na2)%mips_expr.\n    * exists_lwxs l_idx H_l_idx z_idx H_z_idx.\n      exists_sw_P l_idx2 H_l_idx2 z_idx2 H_z_idx2.\n      repeat Reg_upd.\n      apply exists_addiu_seq_P.\n      repeat Reg_upd.\n      apply exists_addiu_P.\n      rewrite /=.\n      repeat Reg_upd.\n      rewrite Z_S in Hna2.\n      rewrite sext_Z2u // u2Z_add_Z2u //.\n      lia.\n      move: (min_u2Z ([rk ]_ s0)%mips_expr) => ?.\n      move: (min_u2Z ([a2 ]_ s0)%mips_expr) => ?.\n      move: (max_u2Z ([rk ]_ s0)%mips_expr) => ?.\n      move: (max_u2Z ([a2 ]_ s0)%mips_expr) => ?.\n      lia.\n    * move=> [si hi] Hna2'.\n      by apply IH.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/cryptoasm/copy_u_u_termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.37754066179448903, "lm_q1q2_score": 0.20202141486888206}}
{"text": "\nRequire Import ZArith.\nRequire Import Coq.Strings.String.\nRequire Import List. Import ListNotations.\n\nSet Warnings \"-extraction-reserved-identifier\".\n\nFrom QuickChick Require Import QuickChick.\n\nRequire Import IFC.Rules.\nRequire Import IFC.TestingCommon.\nRequire Import IFC.Generation.\nRequire Import IFC.Shrinking.\nRequire Import IFC.SSNI.\nRequire Import IFC.Reachability.\nRequire Import IFC.SingleStateArb.\n\nRequire Import IFC.SanityChecks.\n\n(* Testing well-formedness first *)\n\nQuickCheck prop_stamp_generation.\n\nQuickCheck prop_generate_indist.\n\nQuickCheck (prop_fstep_preserves_well_formed default_table).\n\n(* Testing non-interference second (default table) *)\n\nDefinition testSSNI t := quickCheck (propSSNI_smart exp_result_normal t).\n\nQuickCheck (propSSNI_smart exp_result_normal default_table).\n\n(* Testing mutants third *)\n\nRequire Import Mutate.\nFrom QuickChick Require Import MutateCheck.\n\nInstance mutateable_table : Mutateable table :=\n{|\n  mutate := mutate_table\n|}.\n\nDefinition testMutantX_  n :Checker :=\n  propSSNI_smart  exp_result_normal (nth n (mutate_table default_table) default_table).\n\nQuickChick (testMutantX_ 0).\n(* FuzzChick (testMutantX_ 0).*)\n(*\nEval simpl in (nth 24 (mutate_table default_table) default_table).\n*)\nMutateCheckMany default_table (fun t => [propSSNI_smart exp_result_normal t;\n    prop_fstep_preserves_well_formed t]).\n\n(* The rest of this file is mostly garbage *)\n\n(*\nEval lazy -[labelCount helper] in\n  nth 26 (mutate_table default_table) default_table.\n*)\n\nDefinition testMutantX x y :=\n  let mutant := fun o' =>\n    (helper x y o' (default_table o'))  in\n  testSSNI mutant.\n\nFuzzChick\n\nDefinition testMutant7 := testMutantX\n  OpBCall (≪TRUE, JOIN Lab2 LabPC, Lab1 ≫).\n(* CH: most often we catch this one; but sometimes it escapes *)\n\nDefinition testMutant9 := testMutantX\n  OpBRet (≪LE Lab1 (JOIN Lab2 Lab3), Lab2, Lab3 ≫).\n(* Problem: we weren't generating _any_ HIGH -> LOW cases;\n            doing a very bad job at generating stacks!\n(\"Some OpBRet, Failed\",484),\n(\"Some OpBRet, HIGH -> HIGH\",206),\n(\"Some OpBRet, LOW -> *\",224),\n(\"Some OpBRet, Second failed H\",28),\n(\"Some OpBRet, Second not low\",83),\n   After expedient fix this finds the bug and looks like this:\n(\"Some OpBRet, Failed\",85),\n(\"Some OpBRet, HIGH -> HIGH\",23),\n(\"Some OpBRet, LOW -> *\",40),\n(\"Some OpBRet, Second failed H\",6),\n(\"Some OpBRet, HIGH -> LOW\",7), <---- this case was missing\n*)\n\nDefinition testMutant26 := testMutantX\n  OpBNZ (≪TRUE, __ , LabPC ≫).\n(* This was found, just not often enough (once in 20000-30000 tests)\n   We weren't generating zeroes often enough (1 in 200)\n   Changed to 1 in 10 and we're finding this just fine. *)\n\nDefinition testMutant29 := testMutantX\n  OpLoad (≪TRUE, Lab3, JOIN Lab1 Lab2 ≫).\n(* CH: this one is at the limit (with 10000 tests sometimes we catch\n       it and sometimes we don't)*)\n\nDefinition testMutant36 := testMutantX\n  OpAlloc (≪TRUE, Lab2, LabPC ≫).\n(* XXX: this and the next mutants break well-formedness;\n   but we don't test that as a precondition to SSNI\n   DONE: for each mutant we should also test well-formedness\n   and if that fails the mutant is also killed *)\n\nDefinition testMutantWF x y :=\n  let mutant := fun o' =>\n    (helper x y o' (default_table o'))  in\n  quickCheck (prop_fstep_preserves_well_formed mutant).\n\nDefinition testMutant36wf := testMutantWF\n  OpAlloc (≪TRUE, Lab2, LabPC ≫).\n(* XXX: this sometimes fails, and otherwise gives stack overflow\n   during shrinking (probably an infinite loop of some sort) *)\n\nDefinition testMutant37 := testMutantX\n  OpAlloc (≪TRUE, Lab1, LabPC ≫).\n\nDefinition testMutant37wf := testMutantWF\n  OpAlloc (≪TRUE, Lab1, LabPC ≫).\n(* XXX: this sometimes fails, and otherwise gives stack overflow\n   during shrinking (probably an infinite loop of some sort) *)\n\n(* Definition testNI := testMutant37wf. *)\n\n(* QuickCheck testMutants.*)\n(* Definition testNI := testMutant9.*)\n(* Definition testNI := testSSNI default_table. *)\n(* Definition testNI := quickCheck prop_stamp_generation. *)\n(* Definition testNI :=\n  quickCheck (prop_preserves_well_formed default_table). *)\n(* Definition testNI := quickCheck prop_generate_indist. *)\n(*(forAllShrink (fun _ => \"implement me!\")\n                           genSingleExecState\n                           (fun _ => nil)\n                           (propWellFormednessPreserved default_table)).*)\n\n(*Definition testNI :=\n  let l := lab_of_list [Pos.of_nat 1] in\n  let h := lab_of_list [Pos.of_nat 1; Pos.of_nat 2] in\n  match alloc 2%Z l bot (Vint Z0 @ bot) (Mem.empty Atom Label) with\n    | Some (mf, m') =>\n      map (Mem.get_frame m') (Mem.get_all_blocks h m')\n    | _ => []\n  end.\n*)\n", "meta": {"author": "jwshi21", "repo": "etna", "sha": "master", "save_path": "github-repos/coq/jwshi21-etna", "path": "github-repos/coq/jwshi21-etna/etna-main/workloads/Coq/IFC/Src/Driver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.20192149341158863}}
{"text": "Set Implicit Arguments.\n\nRequire Import Bedrock.Platform.Cito.ADT.\n\nModule Make (Import E : ADT).\n\n  Require Import Bedrock.Platform.Cito.Semantics.\n  Module Import SemanticsMake := Make E.\n\n  Section TopSection.\n\n    Require Import Bedrock.Platform.Cito.GoodModule.\n    Require Import Bedrock.Platform.Cito.GLabelMap.\n    Import GLabelMap.\n\n    Open Scope bool_scope.\n    Notation \"! b\" := (negb b) (at level 35).\n\n    Require Import Coq.Arith.Compare_dec.\n\n    Definition to_bool A B (b : {A} + {B}) := if b then true else false.\n\n    Notation fst2 := (fun x => @fst _ _ (@fst _ _ x)).\n\n    Require Import Bedrock.Platform.Cito.ListFacts3.\n    Require Import Bedrock.Platform.Cito.NameDecoration.\n\n    Definition GoodToLink_bool (modules : list GoodModule) (imports : t ForeignFuncSpec) :=\n      let imported_module_names := List.map fst2 (elements imports) in\n      let module_names := List.map Name modules in\n      ! sumbool_to_bool (zerop (length modules)) &&\n        is_no_dup module_names &&\n        forallb (fun s => ! sumbool_to_bool (in_dec string_dec s module_names)) imported_module_names &&\n        forallb is_good_module_name imported_module_names.\n\n    Require Import Bedrock.Platform.Cito.GeneralTactics.\n    Require Import Bedrock.Platform.Cito.ListFacts1.\n    Require Import Bedrock.Platform.Cito.GeneralTactics.\n    Require Import Coq.Bool.Bool.\n    Require Import Bedrock.Platform.Cito.GLabelMapFacts.\n\n    Lemma GoodToLink_bool_sound :\n      forall modules imports,\n        GoodToLink_bool modules imports = true ->\n        modules <> nil /\\\n        List.NoDup (List.map Name modules) /\\\n        ListFacts1.Disjoint (List.map Name modules) (List.map fst2 (elements imports)) /\\\n        forall l, In l imports -> IsGoodModuleName (fst l).\n    Proof.\n      intros.\n      unfold GoodToLink_bool in *; simpl in *.\n      repeat (eapply andb_true_iff in H; openhyp).\n      split.\n      eapply negb_true_iff in H.\n      unfold sumbool_to_bool in *.\n      destruct (zerop _); intuition.\n      subst; simpl in *; intuition.\n      split.\n      eapply is_no_dup_sound; eauto.\n      split.\n      unfold ListFacts1.Disjoint; intuition.\n      eapply forallb_forall in H1; eauto.\n      eapply negb_true_iff in H1.\n      unfold sumbool_to_bool in *.\n      destruct (in_dec _ _ _); intuition.\n      intros.\n      eapply forallb_forall in H0; eauto.\n      rewrite <- map_map.\n      eapply in_map.\n      eapply In_fst_elements_In; eauto.\n    Qed.\n\n  End TopSection.\n(*\n  Require Import RepInv.\n\n  Module Make (Import M : RepInv E).\n\n    Require Import Link.\n    Module Import LinkMake := Make E M.\n    Require Import GoodOptimizer.\n    Module Import GoodOptimizerMake := Make E.\n    Require Import AutoSep.\n\n    Lemma result_ok_2 :\n      forall modules imports,\n        GoodToLink_bool modules imports = true ->\n        forall opt (opt_g: GoodOptimizer opt),\n          moduleOk (result modules imports opt_g).\n    Proof.\n      intros.\n      eapply GoodToLink_bool_sound in H.\n      Require Import GeneralTactics.\n      openhyp.\n      eapply result_ok; eauto.\n    Qed.\n\n  End Make.\n*)\nEnd Make.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Platform/Cito/LinkFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.2019214844771115}}
{"text": "Require Import String.\nRequire Import Relations Decidable.\nRequire Import FFJ.Base.\nRequire Import FFJ.Syntax.\nRequire Import FFJ.ClassTable.\n\nFixpoint subst (e: Exp) (ds: [Exp]) (xs: [Var]): Exp := \n  match e with\n  | ExpVar var => match find_where var xs with\n                  | Some i => match nth_error ds i with\n                                   | None => e | Some di => di end\n                  | None => e end\n  | ExpFieldAccess exp i => ExpFieldAccess (subst exp ds xs) i\n  | ExpMethodInvoc exp i exps => \n      ExpMethodInvoc (subst exp ds xs) i (map (fun x => subst x ds xs) exps)\n  | ExpCast cname exp => ExpCast cname (subst exp ds xs)\n  | ExpNew cname exps => ExpNew cname (map (fun x => subst x ds xs) exps)\n  end.\nNotation \" [; ds '\\' xs ;] e \" := (subst e ds xs) (at level 30).\n\n\nInductive Warning (s: string) : Prop :=\n  | w_str : Warning s.\nNotation stupid_warning := (Warning \"stupid warning\").\n\n(* We can make a stupid cast at anytime, but that rule must be flagged. *)\nAxiom STUPID_STEP : stupid_warning.\n\nReserved Notation \"Gamma '|--' x ':' C\" (at level 60, x at next level).\nInductive ExpTyping (Gamma: env ClassName) : Exp -> ClassName -> Prop :=\n  | T_Var : forall x C, get Gamma x = Some C -> \n                Gamma |-- ExpVar x : C\n  | T_Field: forall e0 C0 fs i Fi Ci fi,\n                Gamma |-- e0 : C0 ->\n                fields C0 fs ->\n                nth_error fs i = Some Fi ->\n                Ci = fieldType Fi ->\n                fi = ref Fi ->\n                Gamma |-- ExpFieldAccess e0 fi : Ci\n  | T_Invk : forall e0 C Cs C0 Ds m es,\n                Gamma |-- e0 : C0 ->\n                mtype(m, C0) = Ds ~> C ->\n                Forall2 (ExpTyping Gamma) es Cs ->\n                Forall2 Subtype Cs Ds ->\n                Gamma |-- ExpMethodInvoc e0 m es : C\n  | T_New : forall C Ds Cs fs es,\n                fields C fs ->\n                Ds = map fieldType fs ->\n                Forall2 (ExpTyping Gamma) es Cs ->\n                Forall2 Subtype Cs Ds ->\n                Gamma |-- ExpNew C es : C\n  | T_UCast : forall e0 D C,\n                Gamma |-- e0 : D ->\n                D <: C ->\n                Gamma |-- ExpCast C e0 : C\n  | T_DCast : forall e0 C D,\n                Gamma |-- e0 : D ->\n                C <: D ->\n                C <> D ->\n                Gamma |-- ExpCast C e0 : C\n  | T_SCast : forall e0 D C,\n                Gamma |-- e0 : D ->\n                ~ D <: C ->\n                ~ C <: D ->\n                stupid_warning ->\n                Gamma |-- ExpCast C e0 : C\n  where \" Gamma '|--' e ':' C \" := (ExpTyping Gamma e C).\n\nTactic Notation \"typing_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"T_Var\" | Case_aux c \"T_Field\" \n  | Case_aux c \"T_Invk\" | Case_aux c \"T_New\"\n  | Case_aux c \"T_UCast\" | Case_aux c \"T_DCast\" \n  | Case_aux c \"T_SCast\"].\n\nReserved Notation \"e '~>!' e1\" (at level 59).\nInductive Computation_step : Exp -> Exp -> Prop :=\n  | R_Field : forall C Fs es fi ei i,\n            fields C Fs ->\n            nth_error Fs i = Some fi ->\n            nth_error es i = Some ei-> \n            ExpFieldAccess (ExpNew C es) (ref fi) ~>! ei\n  | R_Invk : forall C m xs ds es e0,\n            mbody(m, C) = xs o e0 ->\n            NoDup (this :: xs) ->\n            List.length ds = List.length xs ->\n            ExpMethodInvoc (ExpNew C es) m ds ~>! [; ExpNew C es :: ds \\ this :: xs;] e0\n  | R_Cast : forall C D es,\n            C <: D ->\n            ExpCast D (ExpNew C es) ~>! ExpNew C es\n  where \"e '~>!' e1\" := (Computation_step e e1).\nTactic Notation \"computation_step_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"R_Field\" | Case_aux c \"R_Invk\" \n  | Case_aux c \"R_Cast\" ].\n\nReserved Notation \"e '~>' e1\" (at level 60).\nInductive Computation : Exp -> Exp -> Prop :=\n  | R_Step : forall e e1, e ~>! e1 -> e ~> e1\n  | RC_Field : forall e0 e0' f,\n            e0 ~> e0' ->\n            ExpFieldAccess e0 f ~> ExpFieldAccess e0' f\n  | RC_Invk_Recv : forall e0 e0' m es,\n            e0 ~> e0' ->\n            ExpMethodInvoc e0 m es ~> ExpMethodInvoc e0' m es\n  | RC_Invk_Arg : forall e0 ei' m es es' ei i,\n            ei ~> ei' ->\n            nth_error es i = Some ei ->\n            nth_error es' i = Some ei' ->\n            (forall j, j <> i -> nth_error es j = nth_error es' j) ->\n            length es = length es' ->\n            ExpMethodInvoc e0 m es ~> ExpMethodInvoc e0 m es'\n  | RC_New_Arg : forall C ei' es es' ei i,\n            ei ~> ei' ->\n            nth_error es i = Some ei ->\n            nth_error es' i = Some ei' ->\n            (forall j, j <> i -> nth_error es j = nth_error es' j) ->\n            length es = length es' ->\n            ExpNew C es ~> ExpNew C es'\n  | RC_Cast : forall C e0 e0',\n            e0 ~> e0' ->\n            ExpCast C e0 ~> ExpCast C e0'\n  where \"e '~>' e1\" := (Computation e e1).\n\nTactic Notation \"computation_cases\" tactic(first) ident(c) :=\n  first;\n  [ Case_aux c \"R_Step\" | Case_aux c \"RC_Field\"\n  | Case_aux c \"RC_Invk_Recv\" | Case_aux c \"RC_Invk_Arg\" \n  | Case_aux c \"RC_New_Arg\" | Case_aux c \"RC_Cast\"].\n\nInductive Value : Exp -> Prop :=\n  v_new: forall C es, Value (ExpNew C es).\n\n\nReserved Notation \"e '~>*' e1\" (at level 59).\nInductive ComputationStar : Exp -> Exp -> Prop := \n  | Comp_Refl : forall e,\n    e ~>* e\n  | Comp_Trans: forall e1 e2 e3,\n    e1 ~>* e2 ->\n    e2 ~>* e3 ->\n    e1 ~>* e3\n  where \"e '~>*' e1\" := (ComputationStar e e1).\nHint Constructors Computation ExpTyping Value ComputationStar.\nDefinition normal_form {X:Type} (R: relation X) (t: X) :=\n  ~exists t', R t t'.\n\n\nDefinition override (m: id) (D: ClassName) (Cs: [ClassName]) (C0: ClassName) :=\n    (forall Ds D0, mtype(m, D) = Ds ~> D0 -> (Ds = Cs /\\ C0 = D0)).\n\n(* We cut off introduce in this rule, because our definition of introduce only checks backwards,\n  hence no need to check on a Class Declaration *)\nInductive MType_OK : ClassName -> MethodDecl -> Prop :=\n  | T_Method : forall C D C0 E0 xs Cs e0 Fs noDupfs K Ms noDupMds fargs m noDupFargs,\n            nil extds (this :: xs) : (C :: Cs) |-- e0 : E0 ->\n            E0 <: C0 ->\n            find C CT = Some (CDecl C D Fs noDupfs K Ms noDupMds) ->\n            override m D Cs C0 ->\n            map fargType fargs = Cs ->\n            refs fargs = xs ->\n            find m Ms = Some (MDecl C0 m fargs noDupFargs e0) ->\n            MType_OK C (MDecl C0 m fargs noDupFargs e0).\n\n(*In the paper there is no override in this rule, but if you don't need it here\nthen you wouldn't need it in MType_OK also *)\nInductive MType_r_OK : RefinementName -> MethodDecl -> Prop :=\n  | TCR_Method : forall R C D C0 E0 xs Cs e0 feat fs noDupfDecls K Ms noDupmDecls mRefines noDupmRefines m fargs noDupFargs fs' noDupfDecls' K' Ms' noDupMds',\n            nil extds (this :: xs) : (C :: Cs) |-- e0 : E0 ->\n            E0 <: C0 ->\n            R = C @ feat ->\n            find C CT = Some (CDecl C D fs' noDupfDecls' K' Ms' noDupMds') ->\n            find_refinement R (CRefine R fs noDupfDecls K Ms noDupmDecls mRefines noDupmRefines) ->\n            override m D Cs C0 ->\n            map fargType fargs = Cs ->\n            refs fargs = xs ->\n            find m Ms = Some (MDecl C0 m fargs noDupFargs e0) ->\n            introduce m R ->\n            MType_r_OK R (MDecl C0 m fargs noDupFargs e0).\n\nInductive MRType_r_OK: RefinementName -> MethodRefinement -> Prop :=\n  | TR_Method : forall R C C0 E0 xs Cs e0 feat fs noDupfDecls K Ms noDupmDecls mRefines noDupmRefines m fargs noDupFargs,\n            nil extds (this :: xs) : (C :: Cs) |-- e0 : E0 ->\n            E0 <: C0 ->\n            R = C @ feat ->\n            find_refinement R (CRefine R fs noDupfDecls K Ms noDupmDecls mRefines noDupmRefines) ->\n            map fargType fargs = Cs ->\n            refs fargs = xs ->\n            find m mRefines = Some (MRefine C0 m fargs noDupFargs e0) ->\n            find m Ms = None ->\n            override_r m R Cs C0 ->\n            MRType_r_OK R (MRefine C0 m fargs noDupFargs e0).\n\nInductive CType_OK: ClassDecl -> Prop :=\n  | T_Class : forall C D Fs noDupfs K Ms noDupMds Cfargs Dfargs fdecl,\n            K = KDecl C (Cfargs ++ Dfargs) (map Arg (refs Cfargs)) (zipWith Assgnmt (map (ExpFieldAccess (ExpVar this)) (refs Fs)) (map ExpVar (refs Fs))) ->\n            fields D fdecl ->\n            NoDup (refs (fdecl ++ Fs)) ->\n            Forall (MType_OK C) (Ms) ->\n            find C CT = Some (CDecl C D Fs noDupfs K Ms noDupMds) ->\n            (forall R fs',  last_refinement C = Some R -> \n                            fields_r R fs' ->\n                            NoDup (refs (fdecl ++ Fs ++ fs'))) ->\n            NoDup (refs (fdecl ++ Fs)) ->\n            CType_OK (CDecl C D Fs noDupfs K Ms noDupMds).\n\nInductive NoDup_fields: RefinementName -> Prop :=\n  | NoDup_Pred: forall R fs noDupfs K Ms noDupMds mRefines noDupmRefines P fs',\n    find_refinement R (CRefine R fs noDupfs K Ms noDupMds mRefines noDupmRefines) ->\n    pred R P ->\n    fields_r P fs' ->\n    NoDup (refs (fs' ++ fs))->\n    NoDup_fields R\n  | NoDup_First: forall R fs noDupfs K Ms noDupMds mRefines noDupmRefines fs',\n    find_refinement R (CRefine R fs noDupfs K Ms noDupMds mRefines noDupmRefines) ->\n    first_refinement R ->\n    fields (class_name R) fs' ->\n    NoDup (refs (fs' ++ fs))->\n    NoDup_fields R.\n\nInductive CRType_OK: ClassRefinement -> Prop :=\n  | TR_Refinement : forall R fs noDupfs K Ms noDupMds mRefines noDupmRefines,\n      find_refinement R (CRefine R fs noDupfs K Ms noDupMds mRefines noDupmRefines) ->\n      NoDup_fields R ->\n      Forall (MType_r_OK R) Ms ->\n      Forall (MRType_r_OK R) (mRefines) ->\n      CRType_OK (CRefine R fs noDupfs K Ms noDupMds mRefines noDupmRefines).\n\n(* Hypothesis for ClassTable sanity *)\nModule CTSanity.\n\nHypothesis obj_notin_dom: find Object CT = None.\nHint Rewrite obj_notin_dom.\n\nHypothesis dec_subtype: forall C D,\n  decidable (Subtype C D).\n\nHypothesis antisym_subtype:\n  antisymmetric _ Subtype.\n\n\nHypothesis superClass_in_dom: forall C D Fs noDupfs K Ms noDupMds,\n  find C CT = Some (CDecl C D Fs noDupfs K Ms noDupMds) ->\n  D <> Object ->\n  exists D0 Fs0 noDupfs0 K0 Ms0 noDupMds0, find D CT = Some (CDecl D D0 Fs0 noDupfs0 K0 Ms0 noDupMds0).\n\nHypothesis RT_wellformed:\n  Forall (fun CR => CRType_OK CR) RT.\n\n(*TODO: Not use Excluded middle *)\nHypothesis em : forall A:Prop, A \\/ ~ A.\n\nLemma ClassesRefinementOK': forall R, \n  In R RT -> \n  CRType_OK R.\nProof.\n  apply Forall_forall.\n  exact RT_wellformed.\nQed.\n\nLemma pred_in_dom': forall Cl S,\n  pred S Cl ->\n  exists CD, find_refinement Cl CD.\nProof.\n  intros. destruct S. destruct Cl. inversion H. destruct CR. destruct r. subst.\n  unfold refinements_of in *.\n  apply nth_error_In in H6. apply filter_In in H6. destruct H6.\n  apply ClassesRefinementOK' in H0. inversion H0; eauto.\nQed.\n\nLemma ClassesRefinementOK: forall R RD, \n  find_refinement R RD ->\n  CRType_OK RD.\nProof.\n  intros. inversion H. subst.\n  apply find_in in H2.\n  unfold refinements_of in H2.\n  apply filter_In in H2. destruct H2.\n  eapply ClassesRefinementOK'; eauto.\nQed.\nHint Resolve ClassesRefinementOK  ClassesRefinementOK' pred_in_dom'.\n\n\nHypothesis ClassesOK: forall C CD, \n  find C CT = Some CD->\n  CType_OK CD.\nHint Resolve ClassesOK.\n\nLemma subtype_obj_obj: forall C,\n  Object <: C ->\n  Object = C.\nProof.\n  intros_all. remember Object as Obj.\n  induction H; crush.\nQed.\n\nLemma sub_not_obj: forall C,\n  Object <> C ->\n  ~ Object <: C.\nProof.\n  Hint Resolve subtype_obj_obj.\n  intros_all. remember Object as Obj.\n  induction H; crush.\nQed.\n\n\nEnd CTSanity.\n\nDefinition ExpTyping_ind' := \n  fun (Gamma : env ClassName) (P : Exp -> ClassName -> Prop)\n  (f : forall (x : id) (C : ClassName), get Gamma x = Some C -> P (ExpVar x) C)\n  (f0 : forall (e0 : Exp) (C0 : ClassName) (fs : [FieldDecl]) (i : nat) (Fi : FieldDecl)\n          (Ci : ClassName) (fi : id),\n        Gamma |-- e0 : C0 ->\n        P e0 C0 ->\n        fields C0 fs ->\n        nth_error fs i = Some Fi -> Ci = fieldType Fi -> fi = ref Fi -> P (ExpFieldAccess e0 fi) Ci)\n  (f1 : forall (e0 : Exp) (C : ClassName) (Cs : [ClassName]) (C0 : ClassName) (Ds : [ClassName]) \n          (m : id) (es : [Exp]),\n        Gamma |-- e0 : C0 ->\n        P e0 C0 ->\n        mtype( m, C0)= Ds ~> C ->\n        Forall2 (ExpTyping Gamma) es Cs ->\n        Forall2 Subtype Cs Ds -> \n        Forall2 P es Cs ->\n        P (ExpMethodInvoc e0 m es) C)\n  (f2 : forall (C : id) (Ds Cs : [ClassName]) (fs : [FieldDecl]) (es : [Exp]),\n        fields C fs ->\n        Ds = map fieldType fs ->\n        Forall2 (ExpTyping Gamma) es Cs ->\n        Forall2 Subtype Cs Ds -> \n        Forall2 P es Cs ->\n        P (ExpNew C es) C)\n  (f3 : forall (e0 : Exp) (D C : ClassName), Gamma |-- e0 : D -> P e0 D -> D <: C -> P (ExpCast C e0) C)\n  (f4 : forall (e0 : Exp) (C : id) (D : ClassName),\n        Gamma |-- e0 : D -> P e0 D -> C <: D -> C <> D -> P (ExpCast C e0) C)\n  (f5 : forall (e0 : Exp) (D C : ClassName),\n        Gamma |-- e0 : D -> P e0 D -> ~ D <: C -> ~ C <: D -> stupid_warning -> P (ExpCast C e0) C) =>\nfix F (e : Exp) (c : ClassName) (e0 : Gamma |-- e : c) {struct e0} : P e c :=\n  match e0 in (_ |-- e1 : c0) return (P e1 c0) with\n  | T_Var _ x C e1 => f x C e1\n  | T_Field _ e1 C0 fs i Fi Ci fi e2 f6 e3 e4 e5 => f0 e1 C0 fs i Fi Ci fi e2 (F e1 C0 e2) f6 e3 e4 e5\n  | T_Invk _ e1 C Cs C0 Ds m es e2 m0 f6 f7 => f1 e1 C Cs C0 Ds m es e2 (F e1 C0 e2) m0 f6 f7 \n          ((fix list_Forall_ind (es' : [Exp]) (Cs' : [ClassName]) \n            (map : Forall2 (ExpTyping Gamma) es' Cs'): \n               Forall2 P es' Cs' :=\n            match map with\n            | Forall2_nil _ => Forall2_nil P\n            | (@Forall2_cons _ _ _ ex cx ees ccs H1 H2) => Forall2_cons ex cx (F ex cx H1) (list_Forall_ind ees ccs H2)\n          end) es Cs f6)\n  | T_New _ C Ds Cs fs es f6 e1 f7 f8 => f2 C Ds Cs fs es f6 e1 f7 f8\n          ((fix list_Forall_ind (es' : [Exp]) (Cs' : [ClassName]) \n            (map : Forall2 (ExpTyping Gamma) es' Cs'): \n               Forall2 P es' Cs' :=\n            match map with\n            | Forall2_nil _ => Forall2_nil P\n            | (@Forall2_cons _ _ _ ex cx ees ccs H1 H2) => Forall2_cons ex cx (F ex cx H1) (list_Forall_ind ees ccs H2)\n          end) es Cs f7)\n  | T_UCast _ e1 D C e2 s => f3 e1 D C e2 (F e1 D e2) s\n  | T_DCast _ e1 C D e2 s n => f4 e1 C D e2 (F e1 D e2) s n\n  | T_SCast _ e1 D C e2 s s0 w => f5 e1 D C e2 (F e1 D e2) s s0 w\n  end.", "meta": {"author": "hephaestus-pl", "repo": "coqffj", "sha": "2e73b3908c4909cb48f7938a610e2e8f1629b4fe", "save_path": "github-repos/coq/hephaestus-pl-coqffj", "path": "github-repos/coq/hephaestus-pl-coqffj/coqffj-2e73b3908c4909cb48f7938a610e2e8f1629b4fe/src/FFJ/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.20184701656917398}}
{"text": "Require Import Coq.Strings.String.\nRequire Import Coq.ZArith.BinInt.\nRequire Import coqutil.Map.Interface.\nRequire Import coqutil.Word.Interface.\nRequire Import coqutil.Word.LittleEndian.\nRequire Import riscv.Spec.Decode.\nRequire Import riscv.Platform.Memory.\nRequire Import riscv.Utility.Utility.\n\n\nSection Machine.\n\n  Context {width: Z} {word: word width} {word_ok: word.ok word}.\n  Context {Registers: map.map Register word}.\n  Context {Mem: map.map word byte}.\n\n  (* (memory before call, call name, arg values) and (memory after call, return values) *)\n  Definition LogItem{_: Bitwidth width}: Type := (Mem * string * list word) * (Mem * list word).\n\n  (* set of executable addresses. On some processors, this could be the whole address range,\n     while on others, only a specific range. And when an address is written, we might\n     conservatively remove it from that set if we want to prove that our software does not\n     depend on self-modifying code being possible.\n     The ifence instruction will flush the instruction cache and therefore put back the\n     set of executable addresses to the whole range. *)\n  Definition XAddrs: Type := list word.\n\n  Definition isXAddr1B(a: word)(xAddrs: XAddrs): bool :=\n    match List.find (word.eqb a) xAddrs with\n    | Some _ => true\n    | None => false\n    end.\n\n  Definition isXAddr4B(a: word)(xAddrs: XAddrs): bool :=\n    isXAddr1B a xAddrs &&\n    isXAddr1B (word.add a (word.of_Z 1)) xAddrs &&\n    isXAddr1B (word.add a (word.of_Z 2)) xAddrs &&\n    isXAddr1B (word.add a (word.of_Z 3)) xAddrs.\n\n  Definition isXAddr1: word -> XAddrs -> Prop := @List.In word.\n\n  Definition isXAddr4(a: word)(xAddrs: XAddrs): Prop :=\n    isXAddr1 a xAddrs /\\\n    isXAddr1 (word.add a (word.of_Z 1)) xAddrs /\\\n    isXAddr1 (word.add a (word.of_Z 2)) xAddrs /\\\n    isXAddr1 (word.add a (word.of_Z 3)) xAddrs.\n\n  Lemma isXAddr1B_holds: forall a xAddrs,\n      isXAddr1B a xAddrs = true -> isXAddr1 a xAddrs.\n  Proof.\n    unfold isXAddr1B, isXAddr1. intros.\n    destruct (List.find (word.eqb a) xAddrs) eqn: E; [|discriminate].\n    apply List.find_some in E. destruct E.\n    apply Word.Properties.word.eqb_true in H1.\n    subst. assumption.\n  Qed.\n\n  Lemma isXAddr1B_not: forall a xAddrs,\n      isXAddr1B a xAddrs = false -> ~ isXAddr1 a xAddrs.\n  Proof.\n    unfold isXAddr1B, isXAddr1. intros.\n    destruct (List.find (word.eqb a) xAddrs) eqn: E; [discriminate|].\n    intro C.\n    pose proof (List.find_none _ _ E _ C) as P.\n    rewrite Word.Properties.word.eqb_eq in P by reflexivity.\n    discriminate.\n  Qed.\n\n  Lemma isXAddr1B_true: forall a xAddrs,\n      isXAddr1 a xAddrs -> isXAddr1B a xAddrs = true.\n  Proof.\n    intros. destruct (isXAddr1B a xAddrs) eqn: E; [reflexivity|exfalso].\n    eapply isXAddr1B_not; eassumption.\n  Qed.\n\n  Lemma isXAddr1B_false: forall a xAddrs,\n      ~ isXAddr1 a xAddrs -> isXAddr1B a xAddrs = false.\n  Proof.\n    intros. destruct (isXAddr1B a xAddrs) eqn: E; [exfalso|reflexivity].\n    apply isXAddr1B_holds in E. contradiction.\n  Qed.\n\n  Lemma isXAddr4B_holds: forall a xAddrs,\n      isXAddr4B a xAddrs = true -> isXAddr4 a xAddrs.\n  Proof.\n    unfold isXAddr4B, isXAddr4. intros.\n    apply andb_prop in H. destruct H as [H ?].\n    apply andb_prop in H. destruct H as [H ?].\n    apply andb_prop in H. destruct H as [H ?].\n    apply isXAddr1B_holds in H.\n    apply isXAddr1B_holds in H0.\n    apply isXAddr1B_holds in H1.\n    apply isXAddr1B_holds in H2.\n    auto.\n  Qed.\n\n  Lemma isXAddr4B_not: forall a xAddrs,\n      isXAddr4B a xAddrs = false -> ~ isXAddr4 a xAddrs.\n  Proof.\n    unfold isXAddr4B, isXAddr4. intros.\n    intros [C0 [C1 [C2 C3]]].\n    apply isXAddr1B_true in C0. rewrite C0 in H.\n    apply isXAddr1B_true in C1. rewrite C1 in H.\n    apply isXAddr1B_true in C2. rewrite C2 in H.\n    apply isXAddr1B_true in C3. rewrite C3 in H.\n    discriminate H.\n  Qed.\n\n  Lemma isXAddr4B_true: forall a xAddrs,\n      isXAddr4 a xAddrs -> isXAddr4B a xAddrs = true.\n  Proof.\n    intros. destruct (isXAddr4B a xAddrs) eqn: E; [reflexivity|exfalso].\n    eapply isXAddr4B_not; eassumption.\n  Qed.\n\n  Lemma isXAddr4B_false: forall a xAddrs,\n      ~ isXAddr4 a xAddrs -> isXAddr4B a xAddrs = false.\n  Proof.\n    intros. destruct (isXAddr4B a xAddrs) eqn: E; [exfalso|reflexivity].\n    apply isXAddr4B_holds in E. contradiction.\n  Qed.\n\n  Definition removeXAddr(a: word): XAddrs -> XAddrs :=\n    List.filter (fun a' => negb (word.eqb a a')).\n\n  Definition addXAddr: word -> XAddrs -> XAddrs := List.cons.\n\n  Fixpoint addXAddrRange(a: word)(nBytes: nat)(xAddrs: XAddrs): XAddrs :=\n    match nBytes with\n    | O => xAddrs\n    | S n => addXAddr a (addXAddrRange (word.add a (word.of_Z 1)) n xAddrs)\n    end.\n\n  Section WithBitwidth.\n    Context {BW: Bitwidth width}.\n\n    Record RiscvMachine := mkRiscvMachine {\n      getRegs: Registers;\n      getPc: word;\n      getNextPc: word;\n      getMem: Mem;\n      getXAddrs: XAddrs;\n      getLog: list LogItem;\n    }.\n\n    Definition withRegs: Registers -> RiscvMachine -> RiscvMachine :=\n      fun regs2 '(mkRiscvMachine regs1 pc nextPC mem xAddrs log) =>\n                  mkRiscvMachine regs2 pc nextPC mem xAddrs log.\n\n    Definition withPc: word -> RiscvMachine -> RiscvMachine :=\n      fun pc2 '(mkRiscvMachine regs pc1 nextPC mem xAddrs log) =>\n                mkRiscvMachine regs pc2 nextPC mem xAddrs log.\n\n    Definition withNextPc: word -> RiscvMachine -> RiscvMachine :=\n      fun nextPC2 '(mkRiscvMachine regs pc nextPC1 mem xAddrs log) =>\n                    mkRiscvMachine regs pc nextPC2 mem xAddrs log.\n\n    Definition withMem: Mem -> RiscvMachine -> RiscvMachine :=\n      fun mem2 '(mkRiscvMachine regs pc nextPC mem1 xAddrs log)  =>\n                 mkRiscvMachine regs pc nextPC mem2 xAddrs log.\n\n    Definition withXAddrs: XAddrs -> RiscvMachine -> RiscvMachine :=\n      fun xAddrs2 '(mkRiscvMachine regs pc nextPC mem xAddrs1 log)  =>\n                    mkRiscvMachine regs pc nextPC mem xAddrs2 log.\n\n    Definition withLog: list LogItem -> RiscvMachine -> RiscvMachine :=\n      fun log2 '(mkRiscvMachine regs pc nextPC mem xAddrs log1) =>\n                 mkRiscvMachine regs pc nextPC mem xAddrs log2.\n\n    Definition withLogItem: LogItem -> RiscvMachine -> RiscvMachine :=\n      fun item '(mkRiscvMachine regs pc nextPC mem xAddrs log) =>\n                 mkRiscvMachine regs pc nextPC mem xAddrs (item :: log).\n\n    Definition withLogItems: list LogItem -> RiscvMachine -> RiscvMachine :=\n      fun items '(mkRiscvMachine regs pc nextPC mem xAddrs log) =>\n                  mkRiscvMachine regs pc nextPC mem xAddrs (items ++ log).\n\n    Definition Z32s_to_bytes(l: list Z): list byte :=\n      List.flat_map (fun z => HList.tuple.to_list (LittleEndian.split 4 z)) l.\n\n    Definition putProgram(prog: list MachineInt)(addr: word)(ma: RiscvMachine): RiscvMachine :=\n      (withPc addr\n      (withNextPc (word.add addr (word.of_Z 4))\n      (withXAddrs (addXAddrRange addr (4 * List.length prog) ma.(getXAddrs))\n      (withMem (unchecked_store_byte_list addr (Z32s_to_bytes prog) ma.(getMem)) ma)))).\n\n  End WithBitwidth.\nEnd Machine.\n", "meta": {"author": "mit-plv", "repo": "riscv-coq", "sha": "55c9cc88a6734550bdd913bfdf482d498c6354e6", "save_path": "github-repos/coq/mit-plv-riscv-coq", "path": "github-repos/coq/mit-plv-riscv-coq/riscv-coq-55c9cc88a6734550bdd913bfdf482d498c6354e6/src/riscv/Platform/RiscvMachine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.20184700894860286}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Axioms.\nFrom PromisingLib Require Import Basic.\nRequire Import Event.\nFrom PromisingLib Require Import Language.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimThread.\nRequire Import Simulation.\n\nSet Implicit Arguments.\n\n\nLemma singleton_consistent\n      tid lang st lc sc mem\n      (WF: Local.wf lc mem)\n      (SC: Memory.closed_timemap sc mem)\n      (MEM: Memory.closed mem)\n      (CONSISTENT: Thread.consistent (Thread.mk lang st lc sc mem)):\n  <<WF: Configuration.wf (Configuration.mk (IdentMap.singleton tid (existT _ _ st, lc)) sc mem)>> /\\\n  <<CONSISTENT: Configuration.consistent (Configuration.mk (IdentMap.singleton tid (existT _ _ st, lc)) sc mem)>>.\nProof.\n  econs; ss.\n  - econs; ss. econs.\n    + i.\n      apply IdentMap.singleton_find_inv in TH1.\n      apply IdentMap.singleton_find_inv in TH2.\n      des. Configuration.simplify.\n    + i. apply IdentMap.singleton_find_inv in TH. des.\n      Configuration.simplify.\n  - ii. apply IdentMap.singleton_find_inv in TH. des.\n    Configuration.simplify.\n    apply CONSISTENT; eauto.\nQed.\n\nLemma singleton_consistent_inv\n      tid lang st lc sc mem\n      (WF: Configuration.wf (Configuration.mk (IdentMap.singleton tid (existT _ _ st, lc)) sc mem))\n      (CONSISTENT: Configuration.consistent (Configuration.mk (IdentMap.singleton tid (existT _ _ st, lc)) sc mem)):\n  <<WF: Local.wf lc mem>> /\\\n  <<SC: Memory.closed_timemap sc mem>> /\\\n  <<MEM: Memory.closed mem>> /\\\n  <<CONSISTENT: Thread.consistent (Thread.mk lang st lc sc mem)>>.\nProof.\n  inv WF. inv WF0. exploit THREADS; eauto.\n  { apply IdentMap.singleton_eq. }\n  i. splits; eauto.\n  eapply CONSISTENT. apply IdentMap.singleton_eq.\nQed.\n\nLemma singleton_is_terminal\n      tid lang st lc:\n  Threads.is_terminal (IdentMap.singleton tid (existT _ _ st, lc)) <->\n  <<STATE: lang.(Language.is_terminal) st>> /\\\n  <<THREAD: Local.is_terminal lc>>.\nProof.\n  econs; intro X.\n  - eapply X. apply IdentMap.singleton_eq.\n  - ii. apply IdentMap.singleton_find_inv in FIND. i. des.\n    Configuration.simplify.\nQed.\n\nLemma sim_thread_sim\n      lang_src lang_tgt\n      sim_terminal\n      st1_src lc1_src sc0_src mem0_src\n      st1_tgt lc1_tgt sc0_tgt mem0_tgt\n      tid\n      (SIM: @sim_thread lang_src lang_tgt sim_terminal\n                        st1_src lc1_src sc0_src mem0_src\n                        st1_tgt lc1_tgt sc0_tgt mem0_tgt):\n  sim\n    (IdentMap.singleton tid (existT _ _ st1_src, lc1_src)) sc0_src mem0_src\n    (IdentMap.singleton tid (existT _ _ st1_tgt, lc1_tgt)) sc0_tgt mem0_tgt.\nProof.\n  revert st1_src lc1_src sc0_src mem0_src st1_tgt lc1_tgt sc0_tgt mem0_tgt SIM. pcofix CIH. i. pfold. ii.\n  exploit singleton_consistent_inv; try apply WF_SRC; eauto. i. des.\n  exploit singleton_consistent_inv; try apply WF_TGT; eauto. i. des.\n  splits.\n  - i. apply (singleton_is_terminal tid) in TERMINAL_TGT. des.\n    punfold SIM. exploit SIM; try apply SC1; eauto. i. des.\n    exploit TERMINAL; eauto. i. des.\n    esplits; [|eauto|eauto|].\n    + generalize (rtc_tail STEPS). intro X. des.\n      * inv X0. inv TSTEP. destruct a2. econs 2; [|econs 1].\n        econs. rewrite <- EVENT. econs; ss; eauto.\n        { eapply IdentMap.singleton_eq. }\n        { ii. eexists. splits; eauto. ss.\n          eapply SimPromises.sem_bot_inv.\n          inv THREAD. rewrite <- PROMISES0. apply LOCAL.\n        }\n      * inv X. s. erewrite IdentMap.singleton_add. econs.\n    + ii. ss. rewrite IdentMap.singleton_add in *.\n      apply IdentMap.singleton_find_inv in FIND. des. subst.\n      splits; Configuration.simplify. econs; eauto.\n      eapply SimPromises.sem_bot_inv.\n      inv THREAD. rewrite <- PROMISES0. apply LOCAL.\n  - i. inv STEP_TGT. ss.\n    apply IdentMap.singleton_find_inv in TID. des.\n    Configuration.simplify.\n    exploit sim_thread_rtc_step; try apply STEPS; try apply SC1; eauto.\n    { eapply sim_thread_future; eauto. }\n    i. des. destruct e2. ss.\n    exploit sim_thread_opt_step; try apply MEMORY; eauto.\n    { econs 2. eauto. }\n    i. des. rewrite STEPS1 in STEPS0. inv STEP0.\n    { generalize (rtc_tail STEPS0). intro X. des.\n      - inv X0. inv TSTEP. esplits; eauto.\n        + rewrite <- EVENT. s. rewrite <- EVENT0.\n          econs 2. econs; s.\n          * apply IdentMap.singleton_eq.\n          * etrans; eauto.\n          * eauto.\n          * eapply sim_thread_consistent; eauto.\n        + right. s. rewrite ? IdentMap.singleton_add.\n          apply CIH. ss.\n      - inv X. esplits; eauto.\n        + rewrite <- EVENT. s. instantiate (2 := tid). econs 1.\n        + right. s. rewrite ? IdentMap.singleton_add.\n          apply CIH. eauto.\n    }\n    esplits; eauto.\n    + rewrite <- EVENT.\n      econs 2. econs; s.\n      * apply IdentMap.singleton_eq.\n      * etrans; eauto.\n      * eauto.\n      * eapply sim_thread_consistent; eauto.\n    + right. s. rewrite ? IdentMap.singleton_add.\n      apply CIH. ss.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-coq", "sha": "bff53239c51681ea653745cebf3b30ddd38f97ba", "save_path": "github-repos/coq/snu-sf-promising-coq", "path": "github-repos/coq/snu-sf-promising-coq/promising-coq-bff53239c51681ea653745cebf3b30ddd38f97ba/src/opt/AdequacyThread.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.33807711748081287, "lm_q1q2_score": 0.2016403940088059}}
{"text": "Fail Fixpoint F (u : unit) : Prop :=\n  (fun p : {P : Prop & _} => match p with existT _ _ P => P end)\n  (existT (fun P => False -> P) (F tt) _).\n(* Anomaly: A universe comparison can only happen between variables.\nPlease report. *)\n\n\n\nDefinition g (x : Prop) := x.\n\nDefinition h (y : Type) := y.\n\nDefinition eq_hf : h = g :> (Prop -> Type) :=\n  @eq_refl (Prop -> Type) g.\n\nSet Printing All.\nSet Printing Universes.\nFail Definition eq_hf : h = g :> (Prop -> Type) :=\n  eq_refl g.\n(* Originally an anomaly, now says\nToplevel input, characters 48-57:\nError:\nThe term \"@eq_refl (forall _ : Prop, Prop) g\" has type\n \"@eq (forall _ : Prop, Prop) g g\" while it is expected to have type\n \"@eq (forall _ : Prop, Type (* Top.16 *)) (fun y : Prop => h y) g\"\n(Universe inconsistency: Cannot enforce Prop = Top.16)). *)\n", "meta": {"author": "princeton-vl", "repo": "CoqGym", "sha": "0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e", "save_path": "github-repos/coq/princeton-vl-CoqGym", "path": "github-repos/coq/princeton-vl-CoqGym/CoqGym-0c03a6fba3a3ea7e2aecedc1c624ff3885f7267e/coq/test-suite/bugs/closed/3205.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.32766831395172374, "lm_q1q2_score": 0.20154480054913096}}
{"text": "From sflib Require Import sflib.\nFrom Paco Require Import paco.\n\nFrom PromisingLib Require Import Basic.\nFrom PromisingLib Require Import Loc.\nFrom PromisingLib Require Import Language.\n\nRequire Import Event.\nRequire Import Time.\nRequire Import View.\nRequire Import Cell.\nRequire Import Memory.\nRequire Import TView.\nRequire Import Local.\nRequire Import Thread.\nRequire Import Configuration.\n\nRequire Import FulfillStep.\n\nRequire Import SimMemory.\nRequire Import SimPromises.\nRequire Import SimLocal.\nRequire Import SimThread.\nRequire Import Compatibility.\n\nRequire Import Syntax.\nRequire Import Semantics.\n\nSet Implicit Arguments.\n\n\nDefinition local_acquired (lc:Local.t) :=\n  (Local.mk (TView.read_fence_tview (Local.tview lc) Ordering.acqrel) (Local.promises lc)).\n\nLemma sim_local_promise_acquired\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt mem2_tgt\n      loc from to msg kind\n      (STEP_TGT: Local.promise_step lc1_tgt mem1_tgt loc from to msg lc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src (local_acquired lc1_tgt))\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src mem2_src,\n    <<STEP_SRC: Local.promise_step lc1_src mem1_src loc from to msg lc2_src mem2_src kind>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acquired lc2_tgt)>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit SimPromises.promise_bot; eauto.\n  { apply WF1_SRC. }\n  { apply WF1_TGT. }\n  i. des.\n  exploit Memory.promise_future; try apply PROMISE_SRC; try apply WF1_SRC; eauto.\n  { destruct msg; ss. inv CLOSED. econs.\n    eapply sim_memory_closed_opt_view; eauto. }\n  i. des.\n  esplits; eauto.\n  - econs; eauto.\n    destruct msg; ss. inv CLOSED. econs.\n    eapply sim_memory_closed_opt_view; eauto.\n  - econs; eauto.\nQed.\n\nLemma sim_local_fulfill_acquired\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt\n      loc from to val releasedm_src releasedm_tgt released ord_src ord_tgt\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_WF: View.opt_wf releasedm_src)\n      (RELM_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT: Time.le (View.rlx (View.unwrap releasedm_tgt) loc) from)\n      (WF_RELM_TGT: View.opt_wf releasedm_tgt)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (ORD_TGT: Ordering.le ord_tgt Ordering.strong_relaxed)\n      (STEP_TGT: fulfill_step lc1_tgt sc1_tgt loc from to val releasedm_tgt released ord_tgt lc2_tgt sc2_tgt)\n      (LOCAL1: sim_local SimPromises.bot lc1_src (local_acquired lc1_tgt))\n      (ACQUIRED1: View.le (TView.cur (Local.tview lc1_src))\n                          (View.join (TView.cur (Local.tview lc1_tgt)) (View.unwrap releasedm_tgt)))\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists lc2_src sc2_src,\n    <<STEP_SRC: fulfill_step lc1_src sc1_src loc from to val releasedm_src released ord_src lc2_src sc2_src>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acquired lc2_tgt)>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>>.\nProof.\n  inv STEP_TGT.\n  assert (RELT_LE:\n   View.opt_le\n     (TView.write_released (Local.tview lc1_src) sc1_src loc to releasedm_src ord_src)\n     (TView.write_released (Local.tview lc1_tgt) sc2_tgt loc to releasedm_tgt ord_tgt)).\n  { unfold TView.write_released, TView.write_tview. ss. viewtac.\n    repeat (condtac; aggrtac;\n            try match goal with\n                | [|- View.opt_le _ _] => econs\n                end);\n      try apply WF1_TGT.\n    - etrans; eauto. aggrtac.\n    - etrans; [apply WF1_SRC|]. etrans; eauto. aggrtac.\n    - etrans; [apply LOCAL1|]. aggrtac.\n  }\n  assert (RELT_WF:\n   View.opt_wf (TView.write_released (Local.tview lc1_src) sc1_src loc to releasedm_src ord_src)).\n  { unfold TView.write_released. condtac; econs.\n    repeat (try condtac; viewtac; try apply WF1_SRC).\n  }\n  exploit SimPromises.remove_bot; try exact REMOVE;\n    try exact MEM1; try apply LOCAL1; eauto.\n  { econs. ss. }\n  { apply WF1_SRC. }\n  { apply WF1_TGT. }\n  { apply WF1_TGT. }\n  i. des. esplits.\n  - econs; eauto.\n    inv WRITABLE. econs.\n    eapply TimeFacts.le_lt_lt; [apply ACQUIRED1|]. viewtac.\n    eapply TimeFacts.le_lt_lt; eauto.\n  - econs; eauto. s. unfold TView.write_tview, TView.read_fence_tview. ss.\n    econs; ss; repeat (try condtac; aggrtac).\n    all: try by destruct ord_src, ord_tgt.\n    all: try by apply WF1_TGT.\n    + etrans; [apply LOCAL1|]. aggrtac.\n    + etrans; [apply LOCAL1|]. aggrtac.\n    + etrans; [apply WF1_SRC|]. etrans; [apply LOCAL1|]. aggrtac.\n    + etrans; [apply LOCAL1|]. aggrtac.\n  - ss.\nQed.\n\nLemma sim_local_write_acquired\n      lc1_src sc1_src mem1_src\n      lc1_tgt sc1_tgt mem1_tgt\n      lc2_tgt sc2_tgt mem2_tgt\n      loc from to val releasedm_src releasedm_tgt released_tgt ord_src ord_tgt kind\n      (RELM_LE: View.opt_le releasedm_src releasedm_tgt)\n      (RELM_SRC_WF: View.opt_wf releasedm_src)\n      (RELM_SRC_CLOSED: Memory.closed_opt_view releasedm_src mem1_src)\n      (RELM_TGT_WF: View.opt_wf releasedm_tgt)\n      (RELM_TGT_CLOSED: Memory.closed_opt_view releasedm_tgt mem1_tgt)\n      (RELM_TGT: Time.le (View.rlx (View.unwrap releasedm_tgt) loc) from)\n      (ORD: Ordering.le ord_src ord_tgt)\n      (ORD_TGT: Ordering.le ord_tgt Ordering.strong_relaxed)\n      (STEP_TGT: Local.write_step lc1_tgt sc1_tgt mem1_tgt loc from to val releasedm_tgt released_tgt ord_tgt lc2_tgt sc2_tgt mem2_tgt kind)\n      (LOCAL1: sim_local SimPromises.bot lc1_src (local_acquired lc1_tgt))\n      (ACQUIRED1: View.le (TView.cur (Local.tview lc1_src))\n                          (View.join (TView.cur (Local.tview lc1_tgt)) (View.unwrap releasedm_tgt)))\n      (SC1: TimeMap.le sc1_src sc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (SC1_SRC: Memory.closed_timemap sc1_src mem1_src)\n      (SC1_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists released_src lc2_src sc2_src mem2_src,\n    <<STEP_SRC: Local.write_step lc1_src sc1_src mem1_src loc from to val releasedm_src released_src ord_src lc2_src sc2_src mem2_src kind>> /\\\n    <<REL2: View.opt_le released_src released_tgt>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acquired lc2_tgt)>> /\\\n    <<SC2: TimeMap.le sc2_src sc2_tgt>> /\\\n    <<MEM2: sim_memory mem2_src mem2_tgt>>.\nProof.\n  exploit write_promise_fulfill; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  exploit sim_local_promise_acquired; eauto. i. des.\n  exploit Local.promise_step_future; eauto. i. des.\n  hexploit sim_local_fulfill_acquired; try apply STEP2;\n    try apply LOCAL2; try apply MEM2; eauto.\n  { eapply Memory.future_closed_opt_view; eauto. }\n  { inv STEP_SRC. inv STEP1. ss. }\n  i. des.\n  exploit promise_fulfill_write_sim_memory; try exact STEP_SRC; try exact STEP_SRC0; eauto.\n  { i. hexploit ORD0; eauto.\n    i. des. splits; auto. eapply sim_local_nonsynch_loc; eauto.\n  }\n  i. des. esplits; eauto. etrans; eauto.\nQed.\n\n\nInductive split_acquire: forall (i1 i2:Instr.t), Prop :=\n| split_acquire_load\n    r l:\n    split_acquire (Instr.load r l Ordering.acqrel) (Instr.load r l Ordering.relaxed)\n| split_acquire_update\n    r l rmw ow\n    (OW: Ordering.le ow Ordering.strong_relaxed):\n    split_acquire (Instr.update r l rmw Ordering.acqrel ow) (Instr.update r l rmw Ordering.relaxed ow)\n.\n\nInductive sim_acquired: forall (st_src:(Language.state lang)) (lc_src:Local.t) (sc1_src:TimeMap.t) (mem1_src:Memory.t)\n                          (st_tgt:(Language.state lang)) (lc_tgt:Local.t) (sc1_tgt:TimeMap.t) (mem1_tgt:Memory.t), Prop :=\n| sim_acquired_intro\n    rs\n    lc1_src sc1_src mem1_src\n    lc1_tgt sc1_tgt mem1_tgt\n    (LOCAL: sim_local SimPromises.bot lc1_src (local_acquired lc1_tgt))\n    (SC: TimeMap.le sc1_src sc1_tgt)\n    (MEMORY: sim_memory mem1_src mem1_tgt)\n    (WF_SRC: Local.wf lc1_src mem1_src)\n    (WF_TGT: Local.wf lc1_tgt mem1_tgt)\n    (SC_SRC: Memory.closed_timemap sc1_src mem1_src)\n    (SC_TGT: Memory.closed_timemap sc1_tgt mem1_tgt)\n    (MEM_SRC: Memory.closed mem1_src)\n    (MEM_TGT: Memory.closed mem1_tgt):\n    sim_acquired\n      (State.mk rs []) lc1_src sc1_src mem1_src\n      (State.mk rs [Stmt.instr (Instr.fence Ordering.acqrel Ordering.plain)]) lc1_tgt sc1_tgt mem1_tgt\n.\n\nLemma sim_acquired_mon\n      st_src lc_src sc1_src mem1_src\n      st_tgt lc_tgt sc1_tgt mem1_tgt\n      sc2_src mem2_src\n      sc2_tgt mem2_tgt\n      (SIM1: sim_acquired st_src lc_src sc1_src mem1_src\n                          st_tgt lc_tgt sc1_tgt mem1_tgt)\n      (SC_FUTURE_SRC: TimeMap.le sc1_src sc2_src)\n      (SC_FUTURE_TGT: TimeMap.le sc1_tgt sc2_tgt)\n      (MEM_FUTURE_SRC: Memory.future_weak mem1_src mem2_src)\n      (MEM_FUTURE_TGT: Memory.future_weak mem1_tgt mem2_tgt)\n      (SC1: TimeMap.le sc2_src sc2_tgt)\n      (MEM1: sim_memory mem2_src mem2_tgt)\n      (WF_SRC: Local.wf lc_src mem2_src)\n      (WF_TGT: Local.wf lc_tgt mem2_tgt)\n      (SC_SRC: Memory.closed_timemap sc2_src mem2_src)\n      (SC_TGT: Memory.closed_timemap sc2_tgt mem2_tgt)\n      (MEM_SRC: Memory.closed mem2_src)\n      (MEM_TGT: Memory.closed mem2_tgt):\n  sim_acquired st_src lc_src sc2_src mem2_src\n               st_tgt lc_tgt sc2_tgt mem2_tgt.\nProof.\n  inv SIM1. econs; eauto.\nQed.\n\nLemma sim_acquired_step\n      st1_src lc1_src sc1_src mem1_src\n      st1_tgt lc1_tgt sc1_tgt mem1_tgt\n      (SIM: sim_acquired st1_src lc1_src sc1_src mem1_src\n                         st1_tgt lc1_tgt sc1_tgt mem1_tgt):\n  _sim_thread_step lang lang ((sim_thread (sim_terminal eq)) \\8/ sim_acquired)\n                   st1_src lc1_src sc1_src mem1_src\n                   st1_tgt lc1_tgt sc1_tgt mem1_tgt.\nProof.\n  inv SIM. ii.\n  inv STEP_TGT; [inv STEP|inv STEP; inv LOCAL0];\n    try (inv STATE; inv INSTR; inv SPLIT); ss.\n  - (* promise *)\n    right.\n    exploit Local.promise_step_future; eauto. i. des.\n    exploit sim_local_promise_acquired; try exact LOCAL; eauto. i. des.\n    exploit Local.promise_step_future; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs. econs; eauto.\n    + eauto.\n    + right. econs; eauto.\n  - (* fence *)\n    right.\n    exploit Local.fence_step_future; eauto. i. des.\n    inv STATE. inv INSTR. inv LOCAL1. ss.\n    esplits; (try by econs 1); eauto; ss.\n    left. eapply paco9_mon; [apply sim_stmts_nil|]; ss. econs; ss.\n    + rewrite TViewFacts.write_fence_tview_strong_relaxed; ss. apply LOCAL.\n    + apply LOCAL.\nQed.\n\nLemma sim_acquired_sim_thread:\n  sim_acquired <8= (sim_thread (sim_terminal eq)).\nProof.\n  pcofix CIH. i. pfold. ii. ss. splits; ss; ii.\n  - inv TERMINAL_TGT. inv PR; ss.\n  - right. esplits; eauto.\n    inv PR. eapply sim_local_memory_bot; eauto.\n  - exploit sim_acquired_mon; eauto. i.\n    exploit sim_acquired_step; eauto. i. des; eauto.\n    + right. esplits; eauto.\n      left. eapply paco9_mon; eauto. ss.\n    + right. esplits; eauto.\nQed.\n\nLemma sim_local_read_acquired\n      lc1_src mem1_src\n      lc1_tgt mem1_tgt\n      lc2_tgt\n      loc ts val released_tgt\n      (STEP_TGT: Local.read_step lc1_tgt mem1_tgt loc ts val released_tgt Ordering.relaxed lc2_tgt)\n      (LOCAL1: sim_local SimPromises.bot lc1_src lc1_tgt)\n      (MEM1: sim_memory mem1_src mem1_tgt)\n      (WF1_SRC: Local.wf lc1_src mem1_src)\n      (WF1_TGT: Local.wf lc1_tgt mem1_tgt)\n      (MEM1_SRC: Memory.closed mem1_src)\n      (MEM1_TGT: Memory.closed mem1_tgt):\n  exists released_src lc2_src,\n    <<REL: View.opt_le released_src released_tgt>> /\\\n    <<STEP_SRC: Local.read_step lc1_src mem1_src loc ts val released_src Ordering.acqrel lc2_src>> /\\\n    <<LOCAL2: sim_local SimPromises.bot lc2_src (local_acquired lc2_tgt)>>.\nProof.\n  inv LOCAL1. inv STEP_TGT.\n  exploit sim_memory_get; try apply GET; try apply MEM1. i. des. inv MSG.\n  esplits; eauto.\n  - econs; eauto. inv READABLE. econs; ss; i.\n    + rewrite <- PLN. apply TVIEW.\n    + rewrite <- RLX; ss. apply TVIEW.\n  - econs; eauto. s.\n    unfold TView.read_tview, TView.read_fence_tview. ss.\n    econs; repeat (condtac; aggrtac).\n    all: try by apply TVIEW.\n    all: try by apply WF1_TGT.\n    + rewrite <- ? View.join_l. etrans; [apply TVIEW|]. apply WF1_TGT.\n    + inv MEM1_TGT. exploit CLOSED; eauto. i. des.\n      apply View.unwrap_opt_wf. inv MSG_WF. ss.\n    + rewrite <- ? View.join_l. apply TVIEW.\n    + inv MEM1_TGT. exploit CLOSED; eauto. i. des.\n      apply View.unwrap_opt_wf. inv MSG_WF. ss.\nQed.\n\nLemma split_acquire_sim_stmts\n      i_src i_tgt\n      (SPLIT: split_acquire i_src i_tgt):\n  sim_stmts eq\n            [Stmt.instr i_src]\n            [Stmt.instr i_tgt; Stmt.instr (Instr.fence Ordering.acqrel Ordering.plain)]\n            eq.\nProof.\n  pcofix CIH. ii. subst. pfold. ii. splits; ii.\n  { inv TERMINAL_TGT. }\n  { right. esplits; eauto.\n    inv LOCAL. apply SimPromises.sem_bot_inv in PROMISES; auto. rewrite PROMISES. auto.\n  }\n  right.\n  inv STEP_TGT; [inv STEP|inv STEP; inv LOCAL0];\n    try (inv STATE; inv INSTR; inv SPLIT); ss.\n  - (* promise *)\n    exploit sim_local_promise; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    econs 2. econs 1; eauto. econs; eauto. eauto.\n  - (* load *)\n    exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read_acquired; eauto. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs 2. econs; cycle 1.\n      * econs 2. eauto.\n      * econs. econs.\n    + auto.\n    + left. eapply paco9_mon; [apply sim_acquired_sim_thread|]; ss.\n  - (* update-load *)\n    exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read_acquired; eauto. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs 2. econs; cycle 1.\n      * econs 2. eauto.\n      * econs. econs. eauto.\n    + auto.\n    + left. eapply paco9_mon; [apply sim_acquired_sim_thread|]; ss.\n  - (* update *)\n    exploit Local.read_step_future; eauto. i. des.\n    exploit sim_local_read_acquired; eauto. i. des.\n    exploit Local.read_step_future; eauto. i. des.\n    exploit Local.write_step_future; eauto. i. des.\n    hexploit sim_local_write_acquired; try exact LOCAL2; try exact SC; eauto; try refl.\n    { inv LOCAL1. inv MEM_TGT. exploit CLOSED; eauto. i. des.\n      inv MSG_TS. ss. }\n    { inv STEP_SRC. inv LOCAL1. ss. repeat (condtac; aggrtac).\n      - rewrite <- ? View.join_l. apply LOCAL.\n      - apply WF_TGT.\n      - unfold TimeMap.join. rewrite <- Time.join_l. rewrite <- Time.join_l. rewrite <- Time.join_r.\n        unfold View.singleton_ur_if. condtac; ss. unfold TimeMap.singleton, LocFun.add.\n        condtac; ss. refl.\n    }\n    i. des.\n    exploit Local.write_step_future; eauto. i. des.\n    esplits; try apply SC; eauto; ss.\n    + econs 2. econs 2. econs; cycle 1.\n      * econs 4; eauto.\n      * econs. econs. eauto.\n    + auto.\n    + left. eapply paco9_mon; [apply sim_acquired_sim_thread|]; ss.\nQed.\n", "meta": {"author": "snu-sf", "repo": "promising-ldrf-coq", "sha": "715c88b11394e04a575ab780d7b176893a873d09", "save_path": "github-repos/coq/snu-sf-promising-ldrf-coq", "path": "github-repos/coq/snu-sf-promising-ldrf-coq/promising-ldrf-coq-715c88b11394e04a575ab780d7b176893a873d09/src/opt/SplitAcq.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.37387582974820255, "lm_q1q2_score": 0.20151280439228456}}
{"text": "Require Import List.\nRequire Import Arith.\nRequire Import Omega.\nImport ListNotations.\nRequire Import Sorting.Permutation.\nRequire Import FunctionalExtensionality.\nRequire Import Relations.Relation_Operators.\nRequire Import Relations.Operators_Properties.\nRequire Import Util.\nRequire Import VerdiTactics.\n\nRequire Import String.\n\nSet Implicit Arguments.\n\nClass BaseParams :=\n  {\n    data : Type;\n    input : Type;\n    output : Type;\n\n    sigPK : string -> string\n  }.\n\n\nClass OneNodeParams (P : BaseParams) :=\n  {\n    init : data;\n    handler : input -> data -> (list output * data)\n  }.\n\nInductive cryptoEvent {name : Type} :=\n| Sign : string -> string -> cryptoEvent\n| Verify : string -> string -> cryptoEvent\n| Leak : string -> cryptoEvent\n| LeakEncrytped : string -> string -> cryptoEvent\n| Random : string -> cryptoEvent\n.\n\nClass MultiParams (P : BaseParams) :=\n  {\n    name : Type ;\n    msg : Type ;\n    msg_eq_dec : forall x y : msg, {x = y} + {x <> y} ;\n    name_eq_dec : forall x y : name, {x = y} + {x <> y} ;\n    nodes : list name ;\n    all_names_nodes : forall n, In n nodes ;\n    no_dup_nodes : NoDup nodes ;\n    init_handlers : name -> data;\n    net_handlers : name -> name -> msg -> data -> (list output) * data * list\n    (name * msg) * (list (@cryptoEvent name)) ;\n    input_handlers : name -> input -> data -> (list output) * data * list (name\n    * msg) * (list (@cryptoEvent name))\n  }.\n\nClass FailureParams `(P : MultiParams) :=\n  {\n    reboot : data -> data\n  }.\n\nSection StepRelations.\n  Variable A : Type.\n  Variable trace : Type.\n\n  Definition step_relation := A -> A -> list trace -> Prop.\n\n  Inductive refl_trans_1n_trace (step : step_relation) : step_relation :=\n  | RT1nTBase : forall x, refl_trans_1n_trace step x x []\n  | RT1nTStep : forall x x' x'' cs cs',\n                   step x x' cs ->\n                   refl_trans_1n_trace step x' x'' cs' ->\n                   refl_trans_1n_trace step x x'' (cs ++ cs').\n\n  Theorem refl_trans_1n_trace_trans : forall step (a b c : A) (os os' : list trace),\n                                        refl_trans_1n_trace step a b os ->\n                                        refl_trans_1n_trace step b c os' ->\n                                        refl_trans_1n_trace step a c (os ++ os').\n  Proof.\n    intros.\n    induction H; simpl; auto.\n    concludes.\n    rewrite app_ass.\n    constructor 2 with x'; auto.\n  Qed.\n\n  Definition inductive (step : step_relation) (P : A -> Prop)  :=\n    forall (a a': A) (os : list trace),\n      P a ->\n      step a a' os ->\n      P a'.\n\n  Theorem step_star_inductive :\n    forall step P,\n      inductive step P ->\n      forall (a : A) a' os,\n        P a ->\n        (refl_trans_1n_trace step) a a' os ->\n        P a'.\n  Proof.\n    unfold inductive. intros.\n    induction H1; auto.\n    forwards; eauto.\n  Qed.\n\n  Definition inductive_invariant (step : step_relation) (init : A) (P : A -> Prop) :=\n    P init /\\ inductive step P.\n\n  Definition reachable step init a :=\n    exists out, refl_trans_1n_trace step init a out.\n\n  Definition true_in_reachable step init (P : A -> Prop) :=\n    forall a,\n      reachable step init a ->\n      P a.\n\n  Theorem true_in_reachable_reqs :\n    forall (step : step_relation) init (P : A -> Prop),\n      (P init) ->\n      (forall a a' out,\n         step a a' out ->\n         reachable step init a ->\n         P a ->\n         P a') ->\n      true_in_reachable step init P.\n  Proof.\n    intros. unfold true_in_reachable, reachable in *.\n    intros. break_exists.\n    match goal with H : refl_trans_1n_trace _ _ _ _ |- _ => induction H end;\n      intuition eauto.\n    match goal with H : P _ -> _ |- _ => apply H end;\n      intros; break_exists;\n      match goal with H : forall _ _ _, step _ _ _ -> _ |- _ => eapply H end;\n      eauto; eexists; econstructor; eauto.\n  Qed.\n\n  Theorem inductive_invariant_true_in_reachable :\n    forall step init P,\n      inductive_invariant step init P ->\n      true_in_reachable step init P.\n  Proof.\n    unfold inductive_invariant, true_in_reachable, reachable, inductive in *. intros.\n    break_exists.\n    match goal with H : refl_trans_1n_trace _ _ _ _ |- _ => induction H end;\n      intuition eauto.\n  Qed.\n\n  Inductive refl_trans_n1_trace (step : step_relation) : step_relation :=\n  | RTn1TBase : forall x, refl_trans_n1_trace step x x []\n  | RTn1TStep : forall x x' x'' cs cs',\n                  refl_trans_n1_trace step x x' cs ->\n                  step x' x'' cs' ->\n                  refl_trans_n1_trace step x x'' (cs ++ cs').\n\n  Lemma RTn1_step :\n    forall (step : step_relation) x y z l l',\n      step x y l ->\n      refl_trans_n1_trace step y z l' ->\n      refl_trans_n1_trace step x z (l ++ l').\n  Proof.\n    intros.\n    induction H0.\n    - rewrite app_nil_r. rewrite <- app_nil_l.\n      econstructor.\n      constructor.\n      auto.\n    - concludes.\n      rewrite <- app_ass.\n      econstructor; eauto.\n  Qed.\n\n  Lemma refl_trans_1n_n1_trace :\n    forall step x y l,\n      refl_trans_1n_trace step x y l ->\n      refl_trans_n1_trace step x y l.\n  Proof.\n    intros.\n    induction H.\n    - constructor.\n    - eapply RTn1_step; eauto.\n  Qed.\n\n  Lemma RT1n_step :\n    forall (step : step_relation) x y z l l',\n      refl_trans_1n_trace step x y l ->\n      step y z l' ->\n      refl_trans_1n_trace step x z (l ++ l').\n  Proof.\n    intros.\n    induction H.\n    - simpl. rewrite <- app_nil_r. econstructor; eauto. constructor.\n    - concludes. rewrite app_ass.\n      econstructor; eauto.\n  Qed.\n\n  Lemma refl_trans_n1_1n_trace :\n    forall step x y l,\n      refl_trans_n1_trace step x y l ->\n      refl_trans_1n_trace step x y l.\n  Proof.\n    intros.\n    induction H.\n    - constructor.\n    - eapply RT1n_step; eauto.\n  Qed.\n\n  Lemma refl_trans_1n_trace_n1_ind :\n    forall (step : step_relation) (P : A -> A -> list trace -> Prop),\n      (forall x, P x x []) ->\n      (forall x x' x'' tr1 tr2,\n         refl_trans_1n_trace step x x' tr1 ->\n         step x' x'' tr2 ->\n         P x x' tr1 ->\n         refl_trans_1n_trace step x x'' (tr1 ++ tr2) ->\n         P x x'' (tr1 ++ tr2)) ->\n      forall x y l,\n        refl_trans_1n_trace step x y l -> P x y l.\n  Proof.\n    intros.\n    find_apply_lem_hyp refl_trans_1n_n1_trace.\n    eapply refl_trans_n1_trace_ind; eauto.\n    intros. eapply H0; eauto using refl_trans_n1_1n_trace, RT1n_step.\n  Qed.\n\n  Theorem true_in_reachable_elim :\n    forall (step : step_relation) init (P : A -> Prop),\n      true_in_reachable step init P ->\n      (P init) /\\\n      (forall a a' out,\n         step a a' out ->\n         reachable step init a ->\n         P a ->\n         P a').\n  Proof.\n    intros. unfold true_in_reachable, reachable in *.\n    intros. intuition.\n    - apply H; eexists; econstructor.\n    - apply H.\n      break_exists.\n      eexists. apply refl_trans_n1_1n_trace.\n      find_apply_lem_hyp refl_trans_1n_n1_trace.\n      econstructor; eauto.\n  Qed.\nEnd StepRelations.\n\nSection Step1.\n  Context `{params : OneNodeParams}.\n\n  Inductive step_1 : (step_relation data (input * list output)) :=\n  | S1T_deliver : forall (i : input) s s' (out : list output),\n                    handler i s = (out, s') ->\n                    step_1 s s' [(i, out)].\n\n  Definition step_1_star := refl_trans_1n_trace step_1.\nEnd Step1.\n\nSection StepAsync.\n\n  Context `{params : MultiParams}.\n\n  Definition update {A : Type} st h (v : A) := (fun nm => if name_eq_dec nm h then v else st nm).\n\n  Record packet := mkPacket { pSrc  : name;\n                              pDst  : name;\n                              pBody : msg }.\n\n  Definition send_packets src ps := (map (fun m => mkPacket src (fst m) (snd m)) ps).\n\n  Definition mark_cevents_src (src : name) := (map (fun (m : (@cryptoEvent name)) => (src, m) )).\n\n  Record network := mkNetwork {\n                                nwState   : name -> data;\n                                nwCrypto  : list (name * (@cryptoEvent name)) }.\n\n  Definition step_m_init : network :=\n    mkNetwork init_handlers [].\n\n  Inductive secret : string -> network -> Prop :=\n  | Secret : forall (v:string) (net:network), \n    (~ exists them, In (them, Leak v) (nwCrypto net))\n    -> (forall them sk, In (them, LeakEncrytped v sk) (nwCrypto net) -> secret sk net)\n    -> secret v net.\n\n  Inductive step_m : step_relation network (name * (input + list output)) :=\n  (* just like step_m *)\n  | SM_deliver : forall net net' p out d l cEvents,\n                     net_handlers (pDst p) (pSrc p) (pBody p) (nwState net (pDst\n                     p)) = (out, d, l, cEvents) ->\n                     net' = mkNetwork (update (nwState net) (pDst p) d)\n                                      ((mark_cevents_src (pDst p) cEvents) ++\n                                      (nwCrypto net))\n                                      ->\n                     (forall sk msg, (In (Verify (sigPK sk) msg) cEvents) ->\n                       secret sk net' ->\n                       (exists them, In (them, Random sk) (nwCrypto net')) ->\n                       (exists them, In (them, Sign sk msg) (nwCrypto net'))) ->\n                     step_m net net' [(pDst p, inr out)]\n  (* inject a message (f inp) into host h *)\n  | SM_input : forall h net net' out inp d l cEvents,\n                   input_handlers h inp (nwState net h) = (out, d, l, cEvents) ->\n                   net' = mkNetwork (update (nwState net) h d)\n                                    (nwCrypto net) ->\n                   step_m net net' [(h, inl inp)]. (* note: we throw away the immediate output!*)\n\n  Definition step_m_star := refl_trans_1n_trace step_m.\nEnd StepAsync.\n\nArguments update _ _ _ _ _ _ / _.\nArguments send_packets _ _ _ _ /.\n\nSection packet_eta.\n  Context {P : BaseParams}.\n  Context {M : @MultiParams P}.\n\n  Lemma packet_eta :\n    forall p : @packet P M,\n      {| pSrc := pSrc p; pDst := pDst p; pBody := pBody p |} = p.\n  Proof.\n    destruct p; auto.\n  Qed.\nEnd packet_eta.\n\nLtac map_id :=\n  rewrite map_ext with (g := (fun x => x)); [eauto using map_id|simpl; intros; apply packet_eta].\n", "meta": {"author": "andres-erbsen", "repo": "notary", "sha": "a2bd24db19a19642480fe17d3ee83e75ae8df61f", "save_path": "github-repos/coq/andres-erbsen-notary", "path": "github-repos/coq/andres-erbsen-notary/notary-a2bd24db19a19642480fe17d3ee83e75ae8df61f/Net.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3738758297482025, "lm_q1q2_score": 0.20151279885496645}}
{"text": "From iris.proofmode Require Import proofmode.\nFrom lrust.typing Require Export type.\nFrom iris.prelude Require Import options.\n\nSection util.\n  Context `{!typeGS Σ}.\n\n  (* Delayed sharing is used by various types; in particular own and uniq.\n     It comes in two flavors: Borrows of \"later something\" and borrows of\n     \"borrowed something\".\n     TODO: Figure out a nice way to generalize that; the two proofs below are too\n     similar. *)\n\n  (* This is somewhat the general pattern here... but it doesn't seem\n     easy to make this usable in Coq, with the arbitrary quantifiers\n     and things.  Also, it actually works not just for borrows but for\n     anything that you can split into a timeless and a persistent\n     part.\n\n  Lemma delay_borrow_step :\n    lfeE ⊆ N → (∀ x, Persistent (Post x)) →\n    lft_ctx -∗ &{κ} P -∗\n      □ (∀ x, &{κ} P -∗ Pre x -∗ Frame x ={F1 x}[F2 x]▷=∗ Post x ∗ Frame x) ={N}=∗ \n      □ (∀ x, Pre x -∗ Frame x ={F1 x}[F2 x]▷=∗ Post x ∗ Frame x).\n   *)\n\n  Lemma delay_sharing_later N κ l ty tid :\n    ↑lftN ⊆ N →\n    lft_ctx -∗ &{κ}(▷ l ↦∗: ty_own ty tid) ={N}=∗\n       □ ∀ (F : coPset) (q : Qp),\n       ⌜↑shrN ∪ ↑lftN ⊆ F⌝ -∗ (q).[κ] ={F}[F ∖ ↑shrN]▷=∗ ty.(ty_shr) κ tid l ∗ (q).[κ].\n  Proof.\n    iIntros (?) \"#LFT Hbor\". rewrite bor_unfold_idx.\n    iDestruct \"Hbor\" as (i) \"(#Hpb&Hpbown)\".\n    iMod (inv_alloc shrN _ (idx_bor_own 1 i ∨ ty_shr ty κ tid l)%I\n          with \"[Hpbown]\") as \"#Hinv\"; first by eauto.\n    iIntros \"!> !> * % Htok\".\n    iMod (inv_acc with \"Hinv\") as \"[INV Hclose]\"; first solve_ndisj.\n    iDestruct \"INV\" as \"[>Hbtok|#Hshr]\".\n    - iMod (bor_later_tok with \"LFT [Hbtok] Htok\") as \"Hdelay\"; first solve_ndisj.\n      { rewrite bor_unfold_idx. eauto. }\n      iModIntro. iNext. iMod \"Hdelay\" as \"[Hb Htok]\".\n      iMod (ty.(ty_share) with \"LFT Hb Htok\") as \"[#$ $]\"; first solve_ndisj.\n      iApply \"Hclose\". auto.\n    - iMod fupd_mask_subseteq as \"Hclose'\"; first solve_ndisj. iModIntro.\n      iNext. iMod \"Hclose'\" as \"_\". iMod (\"Hclose\" with \"[]\") as \"_\"; by eauto.\n  Qed.\n\n  Lemma delay_sharing_nested N κ κ' κ'' l ty tid :\n    ↑lftN ⊆ N →\n    lft_ctx -∗ ▷ (κ'' ⊑ κ ⊓ κ') -∗ &{κ'}(&{κ}(l ↦∗: ty_own ty tid)) ={N}=∗\n       □ ∀ (F : coPset) (q : Qp),\n       ⌜↑shrN ∪ ↑lftN ⊆ F⌝ -∗ (q).[κ''] ={F}[F ∖ ↑shrN]▷=∗ ty.(ty_shr) κ'' tid l ∗ (q).[κ''].\n  Proof.\n    iIntros (?) \"#LFT #Hincl Hbor\". rewrite bor_unfold_idx.\n    iDestruct \"Hbor\" as (i) \"(#Hpb&Hpbown)\".\n    iMod (inv_alloc shrN _ (idx_bor_own 1 i ∨ ty_shr ty κ'' tid l)%I\n          with \"[Hpbown]\") as \"#Hinv\"; first by eauto.\n    iIntros \"!> !> * % Htok\".\n    iMod (inv_acc with \"Hinv\") as \"[INV Hclose]\"; first solve_ndisj.\n    iDestruct \"INV\" as \"[>Hbtok|#Hshr]\".\n    - iMod (bor_unnest with \"LFT [Hbtok]\") as \"Hb\"; first solve_ndisj.\n      { iApply bor_unfold_idx. eauto. }\n      iModIntro. iNext. iMod \"Hb\".\n      iMod (ty.(ty_share) with \"LFT [Hb] Htok\") as \"[#Hshr $]\"; first solve_ndisj.\n      { iApply bor_shorten; done. }\n      iMod (\"Hclose\" with \"[]\") as \"_\"; auto.\n    - iMod fupd_mask_subseteq as \"Hclose'\"; last iModIntro; first solve_ndisj.\n      iNext. iMod \"Hclose'\" as \"_\". iMod (\"Hclose\" with \"[]\") as \"_\"; by eauto.\n  Qed.\nEnd util.\n", "meta": {"author": "lambdaxymox", "repo": "LambdaRust-coq", "sha": "4b96b6dece1564263d7620f1d5df80ead3b9cdc3", "save_path": "github-repos/coq/lambdaxymox-LambdaRust-coq", "path": "github-repos/coq/lambdaxymox-LambdaRust-coq/LambdaRust-coq-4b96b6dece1564263d7620f1d5df80ead3b9cdc3/theories/typing/util.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.20151279509474682}}
{"text": "(* \n This is the definition of formal syntax for Dan Grossman's Thesis, \n  \"SAFE PROGRAMMING AT THE C LEVEL OF ABSTRACTION\". \n\n   Lemmas about static semantics kinding.\n\n*)\n\nRequire Import List.\nExport ListNotations.\nRequire Import ZArith.\nRequire Import Init.Datatypes.\nRequire Import Coq.Init.Logic.\n\nRequire Export FormalSyntax.\nRequire Export DynamicSemanticsTypeSubstitution.\nRequire Export DynamicSemanticsHeapObjects.\nRequire Export DynamicSemantics.\nRequire Export DynamicSemanticsTypeSubstitution.\nRequire Export StaticSemanticsKindingAndContextWellFormedness.\nRequire Export StaticSemantics.\nRequire Export TypeSafety.\nRequire Export CpdtTactics.\nRequire Export TacticNotations.\nRequire Export GetLemmasRelation.\nRequire Export ContextExtensionRelation.\nRequire Export ContextExtensionLemmas.\n\nLemma K_weakening:\n  forall (d : Delta) (tau : Tau) (k : Kappa),\n      WFD d ->\n      K d tau k -> \n      forall (d' : Delta),\n        WFD d' ->\n        ExtendedByD d d' ->\n        K d' tau k.\nProof.\n intros d tau k WFDder Kder.\n K_ind_cases (induction Kder) Case.\n \n Case \"K d cint B\".\n  intros.\n  constructor.\n Case \"K d (tv_t alpha) B\".\n  intros.\n  apply getD_extension_agreement with (d:= d) (d':=d') (alpha:= alpha) (k:= B) \n    in WFDder; \n    try assumption.\n  apply K_B; try assumption.\n Case \"K d (ptype (tv_t alpha)) B\".\n  intros.\n  constructor.\n  apply getD_extension_agreement with (d':= d') in H; try assumption.\n Case \"K d tau A\".\n  intros.\n  apply IHKder with (d':= d') in WFDder; try assumption.\n  constructor; try assumption.\n Case \"K d (cross t0 t1) A\".\n  intros.\n  pose proof WFDder as WFDder2.\n  apply IHKder1 with (d':= d') in WFDder; try assumption.\n  apply IHKder2 with (d':= d') in WFDder2; try assumption.\n  apply K_cross; try assumption.\n Case \"K d (arrow t0 t1) A\".\n  intros.\n  pose proof WFDder as WFDder2.\n  apply IHKder1 with (d':= d') in WFDder; try assumption.\n  apply IHKder2 with (d':= d') in WFDder2; try assumption.\n  apply K_arrow; try assumption.\n Case \"K d (ptype tau) B\".\n  intros.\n  apply IHKder with (d':= d') in WFDder; try assumption.\n  constructor.\n  assumption.\n Case \"K d (utype alpha k tau) A\".\n  intros.\n  assert (Z: getD d' alpha = None).\n  AdmitAlphaConversion.\n  apply IHKder with (d':= ([(alpha, k)] ++ d')) in H; try assumption.\n  apply K_utype; try assumption.\n  constructor; try  assumption.\n  constructor; try assumption.\n  apply ExtendedByD_preserved_under_add_alpha_k; try assumption.\n Case \"K d (etype p alpha k tau) A)\".\n  intros.\n  assert (Z: getD d' alpha = None).\n  AdmitAlphaConversion.\n  apply IHKder with (d':= ([(alpha, k)] ++ d')) in H; try assumption.\n  apply K_etype; try assumption.\n  constructor; try  assumption.\n  constructor; try assumption.\n  apply ExtendedByD_preserved_under_add_alpha_k; try assumption.\nQed.\n\nLemma AK_weakening:\n  forall (d : Delta) (tau : Tau) (k : Kappa),\n      WFD d ->\n      AK d tau k -> \n      forall (d' : Delta),\n        WFD d' ->\n        ExtendedByD d d' ->\n        AK d' tau k.\nProof.\n intros d tau k WFDder AKder.\n inversion AKder.\n intros.\n constructor.\n apply K_weakening with (d:= d); try assumption.\n intros.\n rewrite <- H2 in *.\n rewrite <- H1 in *.\n assert (Z: getD d' alpha = Some A).\n apply getD_extension_agreement with (d':= d') in H; try assumption.\n apply AK_A; try assumption.\nQed.\n", "meta": {"author": "briangmilnes", "repo": "CycloneCoqSemantics", "sha": "190c0fc57d5aebfde244efb06a119f108de7a150", "save_path": "github-repos/coq/briangmilnes-CycloneCoqSemantics", "path": "github-repos/coq/briangmilnes-CycloneCoqSemantics/CycloneCoqSemantics-190c0fc57d5aebfde244efb06a119f108de7a150/3/StaticSemanticsKindingLemmas.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3738758157951908, "lm_q1q2_score": 0.2015127913345272}}
{"text": "Require Import coqutil.sanity coqutil.Macros.subst coqutil.Macros.unique coqutil.Byte.\nRequire Import coqutil.Datatypes.PrimitivePair coqutil.Datatypes.HList.\nRequire Import coqutil.Decidable.\nRequire Import bedrock2.Notations bedrock2.Syntax coqutil.Map.Interface coqutil.Map.OfListWord.\nRequire Import BinIntDef coqutil.Word.Interface coqutil.Word.Bitwidth.\nRequire Import bedrock2.MetricLogging.\nRequire Export bedrock2.Memory.\n\nRequire Import Coq.Lists.List.\n\n(* BW is not needed on the rhs, but helps infer width *)\nDefinition trace{width: Z}{BW: Bitwidth width}{word: word.word width}{mem: map.map word byte} :=\n  list ((mem * String.string * list word) * (mem * list word)).\n\nDefinition ExtSpec{width: Z}{BW: Bitwidth width}{word: word.word width}{mem: map.map word byte} :=\n  (* Given a trace of what happened so far,\n     the given-away memory, an action label and a list of function call arguments, *)\n  trace -> mem -> String.string -> list word ->\n  (* and a postcondition on the received memory and function call results, *)\n  (mem -> list word -> Prop) ->\n  (* tells if this postcondition will hold *)\n  Prop.\n\nExisting Class ExtSpec.\n\nModule ext_spec.\n  Class ok{width: Z}{BW: Bitwidth width}{word: word.word width}{mem: map.map word byte}\n          {ext_spec: ExtSpec}: Prop :=\n  {\n    (* The action name and arguments uniquely determine the footprint of the given-away memory. *)\n    unique_mGive_footprint: forall t1 t2 mGive1 mGive2 a args\n                                            (post1 post2: mem -> list word -> Prop),\n        ext_spec t1 mGive1 a args post1 ->\n        ext_spec t2 mGive2 a args post2 ->\n        map.same_domain mGive1 mGive2;\n\n    weaken :> forall t mGive act args,\n        Morphisms.Proper\n          (Morphisms.respectful\n             (Morphisms.pointwise_relation Interface.map.rep\n               (Morphisms.pointwise_relation (list word) Basics.impl)) Basics.impl)\n          (ext_spec t mGive act args);\n\n    intersect: forall t mGive a args\n                      (post1 post2: mem -> list word -> Prop),\n        ext_spec t mGive a args post1 ->\n        ext_spec t mGive a args post2 ->\n        ext_spec t mGive a args (fun mReceive resvals =>\n                                   post1 mReceive resvals /\\ post2 mReceive resvals);\n  }.\nEnd ext_spec.\nArguments ext_spec.ok {_ _ _ _} _.\n\nSection binops.\n  Context {width : Z} {word : Word.Interface.word width}.\n  Definition interp_binop (bop : bopname) : word -> word -> word :=\n    match bop with\n    | bopname.add => word.add\n    | bopname.sub => word.sub\n    | bopname.mul => word.mul\n    | bopname.mulhuu => word.mulhuu\n    | bopname.divu => word.divu\n    | bopname.remu => word.modu\n    | bopname.and => word.and\n    | bopname.or => word.or\n    | bopname.xor => word.xor\n    | bopname.sru => word.sru\n    | bopname.slu => word.slu\n    | bopname.srs => word.srs\n    | bopname.lts => fun a b =>\n      if word.lts a b then word.of_Z 1 else word.of_Z 0\n    | bopname.ltu => fun a b =>\n      if word.ltu a b then word.of_Z 1 else word.of_Z 0\n    | bopname.eq => fun a b =>\n      if word.eqb a b then word.of_Z 1 else word.of_Z 0\n    end.\nEnd binops.\n\nSection semantics.\n  Context {width: Z} {BW: Bitwidth width} {word: word.word width} {mem: map.map word byte}.\n  Context {locals: map.map String.string word}.\n  Context {env: map.map String.string (list String.string * list String.string * cmd)}.\n  Context {ext_spec: ExtSpec}.\n\n  Local Notation metrics := MetricLog.\n\n  (* this is the expr evaluator that is used to verify execution time, the just-correctness-oriented version is below *)\n  Section WithMemAndLocals.\n    Context (m : mem) (l : locals).\n    Fixpoint eval_expr (e : expr) (mc : metrics) : option (word * metrics) :=\n      match e with\n      | expr.literal v => Some (word.of_Z v, addMetricInstructions 8\n                                             (addMetricLoads 8 mc))\n      | expr.var x => match map.get l x with\n                      | Some v => Some (v, addMetricInstructions 1\n                                           (addMetricLoads 2 mc))\n                      | None => None\n                      end\n      | expr.inlinetable aSize t index =>\n          'Some (index', mc') <- eval_expr index mc | None;\n          'Some v <- load aSize (map.of_list_word t) index' | None;\n          Some (v, (addMetricInstructions 3\n                   (addMetricLoads 4\n                   (addMetricJumps 1 mc'))))\n      | expr.load aSize a =>\n          'Some (a', mc') <- eval_expr a mc | None;\n          'Some v <- load aSize m a' | None;\n          Some (v, addMetricInstructions 1\n                   (addMetricLoads 2 mc'))\n      | expr.op op e1 e2 =>\n          'Some (v1, mc') <- eval_expr e1 mc | None;\n          'Some (v2, mc'') <- eval_expr e2 mc' | None;\n          Some (interp_binop op v1 v2, addMetricInstructions 2\n                                       (addMetricLoads 2 mc''))\n      | expr.ite c e1 e2 =>\n          'Some (vc, mc') <- eval_expr c mc | None;\n          eval_expr (if word.eqb vc (word.of_Z 0) then e2 else e1)\n                    (addMetricInstructions 2\n                       (addMetricLoads 2\n                       (addMetricJumps 1 mc')))\n      end.\n\n    Fixpoint eval_expr_old (e : expr) : option word :=\n      match e with\n      | expr.literal v => Some (word.of_Z v)\n      | expr.var x => map.get l x\n      | expr.inlinetable aSize t index =>\n          'Some index' <- eval_expr_old index | None;\n          load aSize (map.of_list_word t) index'\n      | expr.load aSize a =>\n          'Some a' <- eval_expr_old a | None;\n          load aSize m a'\n      | expr.op op e1 e2 =>\n          'Some v1 <- eval_expr_old e1 | None;\n          'Some v2 <- eval_expr_old e2 | None;\n          Some (interp_binop op v1 v2)\n      | expr.ite c e1 e2 =>\n          'Some vc <- eval_expr_old c | None;\n          eval_expr_old (if word.eqb vc (word.of_Z 0) then e2 else e1)\n      end.\n\n    Fixpoint evaluate_call_args_log (arges : list expr) (mc : metrics) :=\n      match arges with\n      | e :: tl =>\n        'Some (v, mc') <- eval_expr e mc | None;\n        'Some (args, mc'') <- evaluate_call_args_log tl mc' | None;\n        Some (v :: args, mc'')\n      | _ => Some (nil, mc)\n      end.\n\n  End WithMemAndLocals.\nEnd semantics.\n\nModule exec. Section WithEnv.\n  Context {width: Z} {BW: Bitwidth width} {word: word.word width} {mem: map.map word byte}.\n  Context {locals: map.map String.string word}.\n  Context {env: map.map String.string (list String.string * list String.string * cmd)}.\n  Context {ext_spec: ExtSpec}.\n  Context (e: env).\n\n  Local Notation metrics := MetricLog.\n\n  Implicit Types post : trace -> mem -> locals -> metrics -> Prop. (* COQBUG(unification finds Type instead of Prop and fails to downgrade *)\n  Inductive exec :\n    cmd -> trace -> mem -> locals -> metrics ->\n    (trace -> mem -> locals -> metrics -> Prop) -> Prop :=\n  | skip\n    t m l mc post\n    (_ : post t m l mc)\n    : exec cmd.skip t m l mc post\n  | set x e\n    t m l mc post\n    v mc' (_ : eval_expr m l e mc = Some (v, mc'))\n    (_ : post t m (map.put l x v) (addMetricInstructions 1\n                                  (addMetricLoads 1 mc')))\n    : exec (cmd.set x e) t m l mc post\n  | unset x\n    t m l mc post\n    (_ : post t m (map.remove l x) mc)\n    : exec (cmd.unset x) t m l mc post\n  | store sz ea ev\n    t m l mc post\n    a mc' (_ : eval_expr m l ea mc = Some (a, mc'))\n    v mc'' (_ : eval_expr m l ev mc' = Some (v, mc''))\n    m' (_ : store sz m a v = Some m')\n    (_ : post t m' l (addMetricInstructions 1\n                     (addMetricLoads 1\n                     (addMetricStores 1 mc''))))\n    : exec (cmd.store sz ea ev) t m l mc post\n  | stackalloc x n body\n    t mSmall l mc post\n    (_ : Z.modulo n (bytes_per_word width) = 0)\n    (_ : forall a mStack mCombined,\n        anybytes a n mStack ->\n        map.split mCombined mSmall mStack ->\n        exec body t mCombined (map.put l x a) (addMetricInstructions 1 (addMetricLoads 1 mc))\n          (fun t' mCombined' l' mc' =>\n            exists mSmall' mStack',\n              anybytes a n mStack' /\\\n              map.split mCombined' mSmall' mStack' /\\\n              post t' mSmall' l' mc'))\n     : exec (cmd.stackalloc x n body) t mSmall l mc post\n  | if_true t m l mc e c1 c2 post\n    v mc' (_ : eval_expr m l e mc = Some (v, mc'))\n    (_ : word.unsigned v <> 0)\n    (_ : exec c1 t m l (addMetricInstructions 2\n                       (addMetricLoads 2\n                       (addMetricJumps 1 mc'))) post)\n    : exec (cmd.cond e c1 c2) t m l mc post\n  | if_false e c1 c2\n    t m l mc post\n    v mc' (_ : eval_expr m l e mc = Some (v, mc'))\n    (_ : word.unsigned v = 0)\n    (_ : exec c2 t m l (addMetricInstructions 2\n                       (addMetricLoads 2\n                       (addMetricJumps 1 mc'))) post)\n    : exec (cmd.cond e c1 c2) t m l mc post\n  | seq c1 c2\n    t m l mc post\n    mid (_ : exec c1 t m l mc mid)\n    (_ : forall t' m' l' mc', mid t' m' l' mc' -> exec c2 t' m' l' mc' post)\n    : exec (cmd.seq c1 c2) t m l mc post\n  | while_false e c\n    t m l mc post\n    v mc' (_ : eval_expr m l e mc = Some (v, mc'))\n    (_ : word.unsigned v = 0)\n    (_ : post t m l (addMetricInstructions 1\n                    (addMetricLoads 1\n                    (addMetricJumps 1 mc'))))\n    : exec (cmd.while e c) t m l mc post\n  | while_true e c\n      t m l mc post\n      v mc' (_ : eval_expr m l e mc = Some (v, mc'))\n      (_ : word.unsigned v <> 0)\n      mid (_ : exec c t m l mc' mid)\n      (_ : forall t' m' l' mc'', mid t' m' l' mc'' ->\n                                 exec (cmd.while e c) t' m' l' (addMetricInstructions 2\n                                                               (addMetricLoads 2\n                                                               (addMetricJumps 1 mc''))) post)\n    : exec (cmd.while e c) t m l mc post\n  | call binds fname arges\n      t m l mc post\n      params rets fbody (_ : map.get e fname = Some (params, rets, fbody))\n      args mc' (_ : evaluate_call_args_log m l arges mc = Some (args, mc'))\n      lf (_ : map.of_list_zip params args = Some lf)\n      mid (_ : exec fbody t m lf (addMetricInstructions 100 (addMetricJumps 100 (addMetricLoads 100 (addMetricStores 100 mc')))) mid)\n      (_ : forall t' m' st1 mc'', mid t' m' st1 mc'' ->\n          exists retvs, map.getmany_of_list st1 rets = Some retvs /\\\n          exists l', map.putmany_of_list_zip binds retvs l = Some l' /\\\n          post t' m' l'  (addMetricInstructions 100 (addMetricJumps 100 (addMetricLoads 100 (addMetricStores 100 mc'')))))\n    : exec (cmd.call binds fname arges) t m l mc post\n  | interact binds action arges\n      t m l mc post\n      mKeep mGive (_: map.split m mKeep mGive)\n      args mc' (_ :  evaluate_call_args_log m l arges mc = Some (args, mc'))\n      mid (_ : ext_spec t mGive action args mid)\n      (_ : forall mReceive resvals, mid mReceive resvals ->\n          exists l', map.putmany_of_list_zip binds resvals l = Some l' /\\\n          forall m', map.split m' mKeep mReceive ->\n          post (cons ((mGive, action, args), (mReceive, resvals)) t) m' l'\n            (addMetricInstructions 1\n            (addMetricStores 1\n            (addMetricLoads 2 mc'))))\n    : exec (cmd.interact binds action arges) t m l mc post\n  .\n  End WithEnv.\nEnd exec. Notation exec := exec.exec.\n", "meta": {"author": "dderjoel", "repo": "base", "sha": "2aa122fb618100b7fed3119ea3cef73cec5bf4a5", "save_path": "github-repos/coq/dderjoel-base", "path": "github-repos/coq/dderjoel-base/base-2aa122fb618100b7fed3119ea3cef73cec5bf4a5/fiat-crypto/rupicola/bedrock2/bedrock2/src/bedrock2/Semantics.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3738758157951908, "lm_q1q2_score": 0.2015127913345272}}
{"text": "Require Import Asm.\nRequire Import SMTC.Coqlib.\nRequire Import SMTC.Integers.\nRequire Import Maps.\nRequire Import LibTactics.\nRequire Import Coq.omega.Omega.\nRequire Import MathSol.\nRequire Import IntAuto.\nRequire Import Coq.Logic.FunctionalExtensionality.\nLocal Open Scope sparc_scope.\nLocal Open Scope Z_scope.\nImport ListNotations.\n\nDefinition some_reg_eq: RegFile -> RegFile -> Prop :=\n  fun R R' =>\n    R#wim = R'#wim /\\ R#trap = R'#trap /\\ R#s = R'#s /\\ R#annul = R'#annul /\\ R#et = R'#et /\\ R#pc = R'#pc /\\ R#npc = R'#npc /\\ R#r1 = R'#r1.\n\n\nLemma Hold_Sth_Replace:\n   forall l R R',\n      R' = replace l R ->\n      some_reg_eq R R'.\nProof.\n  intros.\n  unfolds.\n  splits;\n  unfolds in H;\n  rewrite H; clear H;\n  destruct l; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct l; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct l; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct f; auto;\n  destruct l; auto;\n  destruct f; auto;\n  auto;\n  destruct f; auto;\n  auto; auto; auto.\nQed.\n\nLemma UserMode_Replace:\n    forall l R R',\n      usr_mode_R R ->\n      R' = replace l R ->\n      usr_mode_R R'.\nProof.\n  intros.\n  assert (R#s = R'#s).\n  apply (Hold_Sth_Replace l R R'); auto.\n  unfolds. unfolds in H.\n  unfolds. unfolds in H.\n  rewrite H1 in H. auto.\nQed.\n\nLemma Hold_Sth_LeftWin:\n   forall R R' F F' k,\n      left_win k (R,F) = (R',F') ->\n      some_reg_eq R R'.\nProof.\n  intros.\n\n  unfolds in H.\n  remember (left_iter (Z.to_nat k) F (fench R)).\n  destruct p.\n  inverts H.\n\n  unfolds. splits; unfolds; unfolds; simpl;\n  apply (Hold_Sth_Replace f0 R (replace f0 R)); auto.\n\nQed.\n\n\nLemma Hold_Sth_RightWin:\n   forall R R' F F' k,\n      right_win k (R,F) = (R',F') ->\n      some_reg_eq R R'.\nProof.\n  intros.\n\n  unfolds in H.\n  remember (right_iter (Z.to_nat k) F (fench R)).\n  destruct p.\n  inverts H.\n\n  unfolds. splits; unfolds; unfolds; simpl;\n  apply (Hold_Sth_Replace f0 R (replace f0 R)); auto.\n\nQed.\n\n\nLemma Hold_Sth_SetWin:\n   forall R R' F F' k,\n      set_win k (R,F) = (R',F') ->\n      some_reg_eq R R'.\nProof.\n  intros.\n  unfolds in H.\n\n  destruct (Int.unsigned k >? Int.unsigned (get_R cwp R)).\n\n  apply (Hold_Sth_LeftWin R R' F F' (Int.unsigned k -ᵢ (get_R cwp R))); iauto.\n\n  destruct (Int.unsigned k <? Int.unsigned (get_R cwp R)).\n\n  apply (Hold_Sth_RightWin R R' F F' (Int.unsigned (get_R cwp R) -ᵢ k)); iauto.\n\n  inverts H. unfolds. splits; auto.\nQed.\n\nLemma UserMode_LeftWin:\n  forall R R' F F' k,\n    usr_mode_R R ->\n    left_win k (R,F) = (R',F') ->\n    usr_mode_R R'.\nProof.\n  intros.\n  unfolds in H0.\n  remember (left_iter (Z.to_nat k) F (fench R)).\n  destruct p.\n  inverts H0.\n\n  unfolds. unfolds.\n\n  asserts_rewrite (get_R s (RegMap.set cwp (post_cwp k R) (replace f0 R)) = get_R s  (replace f0 R)).\n  auto.\n  asserts_rewrite (usr_mode_R (replace f0 R)). {\n    apply (UserMode_Replace f0 R).\n    apply H. auto.\n  }\n  auto.\nQed.\n\n\nLemma UserMode_RightWin:\n  forall R R' F F' k,\n    usr_mode_R R ->\n    right_win k (R,F) = (R',F') ->\n    usr_mode_R R'.\nProof.\n  intros.\n  unfolds in H0.\n  remember (right_iter (Z.to_nat k) F (fench R)).\n  destruct p.\n  inverts H0.\n\n  unfolds. unfolds.\n\n  asserts_rewrite (get_R s (RegMap.set cwp (pre_cwp k R) (replace f0 R)) = get_R s  (replace f0 R)).\n  auto.\n  asserts_rewrite (usr_mode_R (replace f0 R)). {\n    apply (UserMode_Replace f0 R).\n    apply H. auto.\n  }\n  auto.\nQed.\n\nLemma UserMode_SetWin:\n  forall R R' F F' w,\n    usr_mode_R R ->\n    set_win w (R,F) = (R',F') ->\n    usr_mode_R R'.\nProof.\n  intros.\n  unfolds in H0.\n  destruct (Int.unsigned w >? Int.unsigned (get_R cwp R)).\n\n  remember (left_win (Int.unsigned w -ᵢ (get_R cwp R)) (R, F)).\n  destruct r.\n  inverts H0.\n  symmetry in Heqr.\n  apply (UserMode_LeftWin R R' F F'(Int.unsigned w -ᵢ (get_R cwp R)) H Heqr).\n\n  destruct (Int.unsigned w <? Int.unsigned (get_R cwp R)).\n  remember (right_win (Int.unsigned (get_R cwp R) -ᵢ w) (R, F)).\n  destruct r.\n  inverts H0.\n  symmetry in Heqr.\n  apply (UserMode_RightWin R R' F F'(Int.unsigned (get_R cwp R) -ᵢ w) H Heqr).\n\n  inverts H0. auto.\n\nQed.\n\nLemma Hold_Sth_IncWin:\n   forall R R' F F',\n      inc_win (R,F) = Some (R',F') ->\n      some_reg_eq R R'.\nProof.\n  intros.\n  unfolds in H.\n  destruct (negb (win_masked (post_cwp 1 R) R)).\n\n  remember (left_win 1 (R, F)).\n  destruct r.\n  inverts H.\n  symmetry in Heqr.\n  apply (Hold_Sth_LeftWin R R' F F' 1); auto.\n\n  inverts H.\nQed.\n\n\nLemma Hold_Sth_DecWin:\n   forall R R' F F',\n      dec_win (R,F) = Some (R',F') ->\n      some_reg_eq R R'.\nProof.\n  intros.\n  unfolds in H.\n  destruct (negb (win_masked (pre_cwp 1 R) R)).\n\n  remember (right_win 1 (R, F)).\n  destruct r.\n  inverts H.\n  symmetry in Heqr.\n  apply (Hold_Sth_RightWin R R' F F' 1); auto.\n\n  inverts H.\nQed.\n\n\nLemma UserMode_IncWin:\n  forall R R' F F',\n    usr_mode_R R ->\n    inc_win (R,F) = Some (R',F') ->\n    usr_mode_R R'.\nProof.\n  intros.\n  unfolds in H0.\n  destruct (negb (win_masked (post_cwp 1 R) R)).\n\n  remember (left_win 1 (R, F)).\n  destruct r.\n  inverts H0.\n  symmetry in Heqr.\n  apply (UserMode_LeftWin R R' F F' 1); auto.\n\n  inverts H0.\nQed.\n\nLemma UserMode_DecWin:\n  forall R R' F F',\n    usr_mode_R R ->\n    dec_win (R,F) = Some (R',F') ->\n    usr_mode_R R'.\nProof.\n  intros.\n  unfolds in H0.\n  destruct (negb (win_masked (pre_cwp 1 R) R)).\n\n  remember (right_win 1 (R, F)).\n  destruct r.\n  inverts H0.\n  symmetry in Heqr.\n  apply (UserMode_RightWin R R' F F' 1); auto.\n\n  inverts H0.\nQed.\n\nLemma usr_mode_prop:\n    forall R,\n    usr_mode_R R ->\n    R#s = $0.\nProof.\n  intros.\n  unfolds in H.\n  unfolds in H.\n  remember ((get_R s R) =ᵢ ($ 0)).\n  destruct b.\n  symmetry in Heqb.\n  assert (if (get_R s R) =ᵢ ($ 0) then (get_R s R) = ($0) else (get_R s R) <> ($0) ). {\n    apply Int.eq_spec.\n  }\n  rewrite Heqb in H0.\n  auto.\n  inverts H.\nQed.\n\nLemma UsrMode_R:\n    forall i M M' R R',\n    usr_mode_R R ->\n    R__ (M,R) i (M',R') ->\n    usr_mode_R R'.\nProof.\n  intros.\n  apply usr_mode_prop in H.\n  inverts H0;\n  unfolds; unfolds.\n\n  asserts_rewrite (get_R s (next R) = get_R s R ). auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (djmp w R) = get_R s R ). auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (set_annul (next R)) = get_R s R ). auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (set_annul (djmp w R)) = get_R s R ). auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (djmp w R) = get_R s R ). auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (djmp w (save_pc ri R)) = get_R s R ).\n  destruct ri; auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (next R # ri <- v) = get_R s R ).\n  destruct ri; auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (next R) = get_R s R ). auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (next R) = get_R s R ). auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (next R) = get_R s R ). auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (set_user_trap (get_range 0 6 a) R) = get_R s R ). auto.\n  rewrite H. auto.\n\n  inverts H7. unfolds in H1.\n  rewrite H in H1. inverts H1.\n\n  asserts_rewrite (get_R s (next R # ri <- (get_R syb R)) = get_R s R).\n  destruct ri; auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (next R # rj <- ((get_R ri R) &ᵢ a)) = get_R s R ). \n  destruct rj; auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (next R # rj <- ((get_R ri R) |ᵢ a)) = get_R s R ). \n  destruct rj; auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (next R # rj <- ((get_R ri R) <<ᵢ (get_range 0 4 a))) = get_R s R ). \n  destruct rj; auto.\n  rewrite H. auto.\n\n  asserts_rewrite (get_R s (next R # rj <- ((get_R ri R) >>ᵢ (get_range 0 4 a))) = get_R s R ). \n  destruct rj; auto.\n  rewrite H. auto.\n\nQed.\n\nLemma Determinacy_R:\n    forall i M M1 M2 R R1 R2,\n    R__ (M,R) i (M1,R1) ->\n    R__ (M,R) i (M2,R2) ->\n    M1 = M2 /\\ R1 = R2.\nProof.\n  intros.\n  inverts H; inverts H0; fequals; try auto;\n  try (inverts H4; fequals; auto);\n  try (inverts H5; fequals; auto);\n  try solve [rewrite H7 in H6; try inverts H6; fequals; auto];\n  try solve [inverts H9; inverts H10; auto];\n  try (rewrite H0 in H6; try inverts H6; fequals; auto);\n  try solve [rewrite H9 in H11; try inverts H11; fequals; auto];\n  try solve [try rewrite H9 in H8; try inverts H8; fequals; auto];\n  try solve [inverts H7;fequals; auto].\nQed.\n\nLemma trap_has_trap:\n  forall i Q Q',\n    unexpected_trap i Q = Some Q' ->\n    no_trap_Q Q' ->\n    False.\nProof.\n  intros.\n  unfolds in H.\n  destruct (trap_type i Q).\n  destruct Q.\n  inverts H.\n  unfolds in H0.\n  unfolds in H0.\n  unfolds in H0.\n  unfold set_trap in H0.\n  unfold get_R in H0.\n\n  assert ((RegMap.set tt w r) # trap <- ($ 1) trap = ($ 1)). {\n    apply RegMap.gss.\n  }\n  rewrite H in H0.\n  rewrite Int.eq_true in H0.\n  inverts H0.\n\n  destruct Q.\n  inverts H.\nQed.\n\n\nLemma ModeDeq:\n  forall Q,\n    sup_mode_Q Q ->\n    usr_mode_Q Q ->\n    False.\nProof.\n  intros.\n  unfolds in H.\n  unfolds in H0.\n  destruct Q.\n  unfolds in H.\n  unfolds in H0.\n  rewrite H in H0.\n  inverts H0.\nQed.\n\nFixpoint no_psr(D: DelayList) : Prop :=\n  match D with\n  | (_,syb,_)::D' => syb<>psr /\\ no_psr D'\n  | _ => True\n  end.\n\nLemma UserMode_Q:\n  forall i M M' Q Q' D D',\n  usr_mode_Q Q /\\ no_psr D->\n  Q__ (M,Q,D) i (M',Q',D') ->\n  usr_mode_Q Q' /\\ no_psr D'.\nProof.\n  intros.\n\n  inverts H0;\n  try unfold usr_mode_Q;\n  try unfold usr_mode_R;\n  try unfold usr_mode;\n  try iauto;\n  split; try apply H.\n\n  {\n  apply (UsrMode_R i M M' R R'); iauto.\n  }\n\n  {\n  asserts_rewrite (get_R s (next R' # rj <- ((get_R ri R) +ᵢ a)) = get_R s R').\n  destruct rj; auto.\n  assert (usr_mode_R R').\n    apply (UserMode_DecWin R R' F F'); iauto.\n  apply H0.\n  }\n\n  {\n  asserts_rewrite (get_R s (next R' # rj <- ((get_R ri R) +ᵢ a)) = get_R s R').\n  destruct rj; auto.\n  assert (usr_mode_R R').\n    apply (UserMode_IncWin R R' F F'); iauto.\n  apply H0.\n  }\n\n  {\n  destruct H.\n  false.\n  }\n\n  {\n  destruct syb; simpl; iauto.\n  }\n\n  {\n  destruct syb; simpl; iauto.\n  }\n\n  {\n  destruct H.\n  false.\n  }\n\n  {\n  unfolds in H5.\n  destruct Q.\n  destruct (trap_type i (r, f)); iauto.\n  inverts H5.\n  asserts_rewrite (get_R s (set_trap (RegMap.set tt w r)) = get_R s r); iauto.\n  inverts H5.\n  }\nQed.\n\n\nLemma Determinacy_Trap:\n  forall i Q Q1 Q2,\n  unexpected_trap i Q = Some Q1 ->\n  unexpected_trap i Q = Some Q2 ->\n  Q1 = Q2.\nProof.\n  intros.\n  destruct i;\n  unfolds in H;\n  unfold trap_type in H;\n  unfolds in H0;\n  unfold trap_type in H0;\n  destruct Q;\n  try solve [inverts H];\n  try destruct (eval_AddrExp a r);\n  try destruct (negb (word_aligned w));\n  fequals.\nQed.\n\n\n\n\nLemma Determinacy_Deq:\n    forall i M R M' R' F Q,\n    R__ (M, R) i (M', R') ->\n    unexpected_trap i (R,F) = Some Q -> False.\nProof.\n  intros.\n  inverts H;\n  unfold unexpected_trap in H0;\n  unfold trap_type in H0;\n\n  try solve [\n\n  try rewrite H7 in H0;\n  try rewrite H6 in H0;\n  try rewrite H9 in H0;\n\n\n  try (unfold word_aligned_R in H8;\n       rewrite H8 in H0;\n       simpl in H0);\n       try inverts H0\n  ];\n\n\n  try solve [\n  try (unfold sup_mode_R in H7;\n       rewrite H7 in H0);\n       destruct syb; inverts H0\n  ];\n\n  try (unfold sup_mode_R in H6;\n       rewrite H6 in H0);\n\n\n  try solve [\n    destruct syb;\n    destruct H8;\n    destruct H1;\n    eauto;\n    inverts H0\n  ].\n\nQed.\n\nLemma Determinacy_Q:\n    forall i M M1 M2 Q Q1 Q2 F F1 F2,\n    Q__ (M,Q,F) i (M1,Q1,F1) ->\n    Q__ (M,Q,F) i (M2,Q2,F2) ->\n    M1 = M2 /\\ Q1 = Q2 /\\ F1 = F2.\nProof.\n  intros.\n\n  inverts H; inverts H0; fequals; try auto;\n  try rename R' into R1;\n  try rename R'0 into R2;\n  try rename F0 into F;\n  try rename F' into F1;\n  try rename F'0 into F2;\n\n try solve [inverts H5; false].\n\n  {\n  assert(M1 = M2 /\\ R1 = R2).\n  apply (Determinacy_R i M M1 M2 R R1 R2); iauto.\n  inverts H. auto.\n  }\n\n  {\n  false. apply (Determinacy_Deq i M2 R M1 R1 F Q2); iauto.\n  }\n\n  {\n  rewrite H9 in H11. clear H9.\n  inverts H11.\n  inverts H6.\n  rewrite H10 in H12. clear H10.\n  inverts H12. auto.\n  }\n\n  {\n  unfold unexpected_trap in H4.\n  unfold trap_type in H4.\n  rewrite H9 in H4.\n  inverts H4.\n  }\n\n  {\n  rewrite H9 in H11. clear H9.\n  inverts H11.\n  inverts H6.\n  rewrite H10 in H12. clear H10.\n  inverts H12. auto.\n  }\n\n  {\n  unfold unexpected_trap in H4.\n  unfold trap_type in H4.\n  rewrite H9 in H4.\n  inverts H4.\n  }\n\n  {\n  rewrite H13 in H18. clear H13.\n  inverts H18.\n  inverts H8.\n  rewrite H11 in H16. clear H11.\n  inverts H16.\n  auto.\n  }\n\n  {\n  unfold unexpected_trap in H4.\n  unfold trap_type in H4.\n  rewrite H9 in H4.\n  false.\n  }\n\n  {\n  inverts H8.\n  rewrite H11 in H14. clear H11.\n  inverts H14.\n  auto.\n  }\n\n  {\n  unfold unexpected_trap in H4.\n  unfold trap_type in H4.\n  destruct H10 as (TBR & WIM & PSR).\n  destruct syb; false.\n  }\n\n  {\n  inverts H8.\n  rewrite H11 in H14. clear H11.\n  inverts H14.\n  auto.\n  }\n\n  {\n  unfold unexpected_trap in H4.\n  unfold trap_type in H4.\n  destruct syb; try false; rewrite H9 in H4; false.\n  }\n\n  {\n  inverts H7.\n  rewrite H10 in H13.\n  inverts H13. auto.\n  }\n\n  {\n  unfold unexpected_trap in H4.\n  unfold trap_type in H4.\n  rewrite H8 in H4. clear H8.\n  rewrite H10 in H4. clear H10.\n  rewrite H12 in H4. clear H12.\n  false.\n  }\n\n  {\n  false. apply (Determinacy_Deq i M1 R M2 R1 F Q1); iauto.\n  }\n\n  {\n  unfold unexpected_trap in H5.\n  unfold trap_type in H5.\n  rewrite H9 in H5.\n  false.\n  }\n\n  {\n  unfold unexpected_trap in H5.\n  unfold trap_type in H5.\n  rewrite H9 in H5.\n  false.\n  }\n\n  {\n  unfold unexpected_trap in H5.\n  unfold trap_type in H5.\n  rewrite H9 in H5.\n  false.\n  }\n\n  {\n  unfold unexpected_trap in H5.\n  unfold trap_type in H5.\n  destruct H10 as (TBR & WIM & PSR).\n  destruct syb; false.\n  }\n\n  {\n  unfold unexpected_trap in H5.\n  unfold trap_type in H5.\n  destruct syb; try false; rewrite H9 in H5; false.\n  }\n\n  {\n  unfold unexpected_trap in H5.\n  unfold trap_type in H5.\n  rewrite H8 in H5.\n  rewrite H10 in *.\n  rewrite H12 in *.\n  false.\n  }\n\n  {\n  asserts_rewrite(Q1 = Q2).\n  apply (Determinacy_Trap i Q Q1 Q2); iauto.\n  auto.\n  }\n\nQed.\n\n\n\nLemma No_PSR_in_D:\n  forall Q D Q' D',\n    usr_mode_Q Q ->\n    no_psr D ->\n    exe_delay Q D = (Q',D') ->\n    usr_mode_Q Q' /\\ no_psr D'.\nProof.\n  induction D as [|d].\n  - intros.\n    unfolds in H1.\n    inverts H1. auto.\n  - intros.\n    destruct d.\n    destruct p.\n\n    inverts H0.\n    destruct s; try solve [false].\n    {\n      inverts H1.\n      destruct d.\n      remember (exe_delay Q D).\n      destruct p as (Q'' & D'').\n      assert (usr_mode_Q Q'' /\\ no_psr D''). {\n        apply (IHD Q'' D''); iauto.\n      }\n      clear IHD H2 Heqp.\n      destruct Q'' as (R'' & F'').\n      inverts H4.\n      apply H0.\n      remember (exe_delay Q D).\n      destruct p as (Q'' & D'').\n      assert (usr_mode_Q Q'' /\\ no_psr D''). {\n        apply (IHD Q'' D''); iauto.\n      }\n      clear IHD H2 Heqp.\n      destruct Q'' as (R'' & F'').\n      inverts H4.\n      split.\n      apply H0.\n      unfolds.\n      split.\n      unfolds.\n      intros.\n      false.\n      apply H0.\n    }\n    {\n      inverts H1.\n      destruct d.\n      remember (exe_delay Q D).\n      destruct p as (Q'' & D'').\n      assert (usr_mode_Q Q'' /\\ no_psr D''). {\n        apply (IHD Q'' D''); iauto.\n      }\n      clear IHD H2 Heqp.\n      destruct Q'' as (R'' & F'').\n      inverts H4.\n      apply H0.\n      remember (exe_delay Q D).\n      destruct p as (Q'' & D'').\n      assert (usr_mode_Q Q'' /\\ no_psr D''). {\n        apply (IHD Q'' D''); iauto.\n      }\n      clear IHD H2 Heqp.\n      destruct Q'' as (R'' & F'').\n      inverts H4.\n      split.\n      apply H0.\n      unfolds.\n      split.\n      unfolds.\n      intros.\n      false.\n      apply H0.\n    }\n    {\n      inverts H1.\n      destruct d.\n      remember (exe_delay Q D).\n      destruct p as (Q'' & D'').\n      assert (usr_mode_Q Q'' /\\ no_psr D''). {\n        apply (IHD Q'' D''); iauto.\n      }\n      clear IHD H2 Heqp.\n      destruct Q'' as (R'' & F'').\n      inverts H4.\n      apply H0.\n      remember (exe_delay Q D).\n      destruct p as (Q'' & D'').\n      assert (usr_mode_Q Q'' /\\ no_psr D''). {\n        apply (IHD Q'' D''); iauto.\n      }\n      clear IHD H2 Heqp.\n      destruct Q'' as (R'' & F'').\n      inverts H4.\n      split.\n      apply H0.\n      unfolds.\n      split.\n      unfolds.\n      intros.\n      false.\n      apply H0.\n    }\n    {\n      inverts H1.\n      destruct d.\n      remember (exe_delay Q D).\n      destruct p as (Q'' & D'').\n      assert (usr_mode_Q Q'' /\\ no_psr D''). {\n        apply (IHD Q'' D''); iauto.\n      }\n      clear IHD H2 Heqp.\n      destruct Q'' as (R'' & F'').\n      inverts H4.\n      apply H0.\n      remember (exe_delay Q D).\n      destruct p as (Q'' & D'').\n      assert (usr_mode_Q Q'' /\\ no_psr D''). {\n        apply (IHD Q'' D''); iauto.\n      }\n      clear IHD H2 Heqp.\n      destruct Q'' as (R'' & F'').\n      inverts H4.\n      split.\n      apply H0.\n      unfolds.\n      split.\n      unfolds.\n      intros.\n      false.\n      apply H0.\n    }\nQed.\n\nLemma UserMode_H:\n  forall C M Q D M' Q' D',\n  usr_mode_Q Q /\\ no_psr D ->\n  H__ C (M,Q,D) (M',Q',D') ->\n  usr_mode_Q Q' /\\ no_psr D'.\nProof.\n  intros.\n  inverts H0;\n  try rename Q'0 into Q'';\n  try rename D'0 into D''.\n\n  assert(usr_mode_Q Q'' /\\ no_psr D'').\n  apply (No_PSR_in_D Q D Q'' D''); iauto.\n  apply (UserMode_Q i M M' Q'' Q' D'' D'); iauto.\n\n  assert(usr_mode_Q Q'' /\\ no_psr D').\n  apply (No_PSR_in_D Q D Q'' D'); iauto.\n\n  destruct Q'' as (R'' & F'').\n  unfold clear_annul_Q.\n  apply H0.\n\nQed.\n\n\nLemma Determinacy_H:\n    forall C M M1 M2 Q Q1 Q2 F F1 F2,\n    H__ C (M,Q,F) (M1,Q1,F1) ->\n    H__ C (M,Q,F) (M2,Q2,F2) ->\n    M1 = M2 /\\ Q1 = Q2 /\\ F1 = F2.\nProof.\n  intros.\n  inverts H;\n  inverts H0; auto.\n\n  {\n  rewrite H6 in H7. clear H6.\n  inverts H7.\n\n  rewrite H10 in H13. clear H10.\n  inverts H13.\n\n  apply (Determinacy_Q i0 M M1 M2 Q' Q1 Q2 D' F1 F2); iauto.\n  }\n\n  {\n  rewrite H7 in H5. clear H7.\n  inverts H5.\n  destruct Q'0 as (R' & F').\n  false.\n  }\n\n  {\n  rewrite H7 in H6. clear H7.\n  inverts H6.\n  destruct Q' as (R' & F').\n  false.\n  }\n\n  {\n  rewrite H5 in H6. clear H5.\n  inverts H6.\n  auto.\n  }\nQed.\n\n\nLemma UserMode_P:\n  forall Cu Cs Mu Mu' Ms Ms' Q Q' D D',\n  usr_mode_S ((Mu,Ms),Q,D) /\\ no_psr D ->\n  P__ (Cu,Cs) ((Mu,Ms),Q,D) ((Mu',Ms'),Q',D') ->\n  usr_mode_S ((Mu',Ms'),Q',D') /\\ Ms = Ms' /\\ no_psr D'.\nProof.\n  intros.\n  inverts H0.\n  assert (usr_mode_Q Q' /\\ no_psr D'). {\n    apply (UserMode_H Cu Mu Q D Mu' Q' D'); iauto.\n  }\n  splits;\n  try apply H0;\n  iauto.\n\n  {\n  assert (usr_mode_Q Q); iauto.\n  destruct Q as (R & F).\n  false.\n  }\n\nQed.\n\nLemma Determinacy_P:\n    forall CP S S1 S2,\n    P__ CP S S1 ->\n    P__ CP S S2 ->\n    S1 = S2.\nProof.\n  intros.\n  inverts H; inverts H0; auto.\n  assert (Mu' = Mu'0 /\\ Q' = Q'0 /\\ D' = D'0). {\n    apply (Determinacy_H Cu Mu Mu' Mu'0 Q Q' Q'0 D D' D'0); iauto.\n  }\n  inverts H.\n  inverts H4. auto.\n\n  {\n  destruct Q as (R' & F').\n  false.\n  }\n\n  {\n  destruct Q as (R' & F').\n  false.\n  }\n\n  assert (Ms' = Ms'0 /\\ Q' = Q'0 /\\ D' = D'0). {\n    apply (Determinacy_H Cs Ms Ms' Ms'0 Q Q' Q'0 D D' D'0); iauto.\n  }\n  inverts H.\n  inverts H4. auto.\nQed.\n\n\nDefinition usr_mem_eq: MemPair -> MemPair -> Prop :=\n  fun MP MP' =>\n    let (Mu,Ms) := MP in\n    let (Mu',Ms') := MP' in\n    Mu = Mu'.\n\n\nDefinition sup_mem_eq: State -> State -> Prop :=\n  fun S S' =>\n    let '(MP,_,_) := S in\n    let '(MP',_,_) := S' in\n    let (Mu,Ms) := MP in\n    let (Mu',Ms') := MP' in\n    Ms = Ms'.\n\nDefinition interrupt_e: Event -> bool :=\n  fun e => andb (17%Z <=? Int.signed e) (Int.signed e <=? 31%Z).\n\nFixpoint no_trap(E: EventList): Prop :=\n    match E with\n    | e::E' =>\n      match e with\n      | Some _ => False\n      | None => no_trap E'\n      end\n    | Nil => True\n    end.\n\nDefinition usr_code_eq: CodePair -> CodePair -> Prop :=\n  fun CP CP' =>\n    let (Cu,Cs) := CP in\n    let (Cu',Cs') := CP' in\n    Cu = Cu'.\n\n\nFixpoint no_interrupt(E: EventList):Prop :=\n  match E with\n  | e::E' =>\n    no_interrupt E'/\\\n    match e with\n    | Some w => interrupt_e(w) = false\n    | None => True\n    end\n  | nil => True\n  end.\n\n\nDefinition low_eq: State -> State -> Prop :=\n  fun S S' =>\n    let '(MP,Q,F) := S in\n    let '(MP',Q',F') := S' in\n    let (Mu,Ms) := MP in\n    let (Mu',Ms') := MP' in\n    Q = Q' /\\ Mu = Mu' /\\ F = F'.\n\nDefinition no_psr_S: State -> Prop :=\n  fun S =>\n    let '(MP,Q,F) := S in\n      no_psr F.\n\nLemma LowEq_P:\n  forall Cu1 Cu2 Cs1 Cs2 S1 S2 S1' S2',\n    usr_mode_S S1 /\\ no_psr_S S1 ->\n    usr_mode_S S2 /\\ no_psr_S S2 ->\n    Cu1 = Cu2 /\\ low_eq S1 S2 ->\n    P__ (Cu1,Cs1) S1 S1' ->\n    P__ (Cu2,Cs2) S2 S2' ->\n    low_eq S1' S2'.\nProof.\n  intros.\n\n  destruct S1 as (MPQ1 & D1).\n  destruct MPQ1 as (MP1 & Q1).\n  destruct S2 as (MPQ2 & D2).\n  destruct MPQ2 as (MP2 & Q2).\n  destruct MP1 as (Mu1 & Ms1).\n  destruct MP2 as (Mu2 & Ms2).\n  simpl in H.\n  simpl in H0.\n  simpl in H1.\n\n  inverts H1.\n  inverts H5.\n  inverts H4.\n\n  rename Cu2 into Cu.\n  rename D2 into D.\n  rename Q2 into Q.\n  rename Mu2 into Mu.\n\n  inverts H2; inverts H3; iauto;\n  try rename Mu' into Mu1;\n  try rename Mu'0 into Mu2;\n  try rename Q' into Q1;\n  try rename Q'0 into Q2;\n  try rename D' into D1;\n  try rename D'0 into D2.\n\n  {\n  assert (Mu1 = Mu2 /\\ Q1 = Q2 /\\ D1 = D2).\n  apply (Determinacy_H Cu Mu Mu1 Mu2 Q Q1 Q2 D D1 D2); iauto.\n  unfolds.\n  iauto.\n  }\n\n  {\n  destruct Q as (R & F).\n  false.\n  }\n\n  {\n  destruct Q as (R & F).\n  false.\n  }\n\n  {\n  destruct Q as (R & F).\n  destruct H.\n  false.\n  }\nQed.\n\n\nLemma and_true_true: forall m n,\n    andb m n = true ->\n    m = true /\\ n = true.\nProof.\n  intros.\n  unfolds in H.\n  destruct m.\n  auto. \n  inverts H.\nQed.\n\nLemma and_false_false: forall m n,\n    andb m n = false ->\n    m = false \\/ n = false.\nProof.\n  intros.\n  unfolds in H.\n  destruct m; auto.\nQed.\n\nLemma Determinacy_Inturrupt_Eq:\n  forall w1 w2 O O1 O2 ,\n  interrupt w1 O = Some O1 ->\n  interrupt w2 O = Some O2 ->\n  get_tt O1 = get_tt O2 -> w1 = w2.\nProof.\n  intros.\n  unfolds in H.\n  unfolds in H0.\n\n  remember ((1 <=? Int.signed w1) && (Int.signed w1 <=? 15)).\n  destruct b.\n  remember ((1 <=? Int.signed w2) && (Int.signed w2 <=? 15)).\n  destruct b.\n  destruct O.\n  destruct (negb (has_trap r) && trap_enabled r &&\n      ((Int.signed w1 =? 15) || (Int.signed (get_R pil r) <? Int.signed w1))).\n  destruct (negb (has_trap r) && trap_enabled r &&\n      ((Int.signed w2 =? 15) || (Int.signed (get_R pil r) <? Int.signed w2))).\n  remember (set_trap r # tt <- ($ (16 + Int.signed w1)), f).\n  remember (set_trap r # tt <- ($ (16 + Int.signed w2)), f).\n  inverts H0.\n  inverts H.\n  substs.\n\n  unfolds in H1.\n  unfolds in H1.\n  assert (set_trap r # tt <- ($ (16 + Int.signed w1)) tt = r # tt <- ($ (16 + Int.signed w1)) tt).\n  auto.\n  assert (set_trap r # tt <- ($ (16 + Int.signed w2)) tt = r # tt <- ($ (16 + Int.signed w2)) tt).\n  auto.\n\n  rewrite H in H1.\n  rewrite H0 in H1.\n  clear H H0.\n\n  assert (r # tt <- ($ (16 + Int.signed w1)) tt = $ (16 + Int.signed w1)).\n  apply RegMap.gss.\n  assert (r # tt <- ($ (16 + Int.signed w2)) tt = $ (16 + Int.signed w2)).\n  apply RegMap.gss.\n  rewrite H in H1.\n  rewrite H0 in H1.\n  clear H H0.\n\n  symmetry in Heqb.\n  apply and_true_true in Heqb.\n  destruct Heqb as (A1 & A2).\n  apply Z.leb_le in A1.\n  apply Z.leb_le in A2.\n  symmetry in Heqb0.\n  apply and_true_true in Heqb0.\n  destruct Heqb0 as (B1 & B2).\n  apply Z.leb_le in B1.\n  apply Z.leb_le in B2.\n\n  remember (Int.signed w1) as n1.\n  remember (Int.signed w2) as n2.\n\n  assert (Int.signed ($ (16 + n1)) = Int.signed ($ (16 + n2))).\n  rewrite H1. auto.\n  clear H1.\n\n  assert (17 <= (16 + n1) <= 31).  omega.\n  assert (17 <= (16 + n2) <= 31).  omega.\n\n  assert ( Int.min_signed <= (16 + n1) <= Int.max_signed ).\n  {\n    remember (16+n1) as n1'.\n    intros.\n    unfolds Int.max_signed.\n    unfolds Int.min_signed.\n    unfolds Int.half_modulus.\n    unfolds Int.modulus.\n    unfolds Int.wordsize.\n    unfolds Wordsize_32.wordsize.\n    unfolds two_power_nat.\n    unfolds shift_nat.\n    unfolds nat_rect.\n    simpl.\n    omega.\n  }\n  assert (Int.signed ($(16 + n1)) = 16 + n1). {\n    apply Int.signed_repr. apply H2.\n  }\n  clear H2. rewrite H3 in H. clear H3.\n\n  assert ( Int.min_signed <= (16 + n2) <= Int.max_signed ).\n  {\n    remember (16+n2) as n2'.\n    intros.\n    unfolds Int.max_signed.\n    unfolds Int.min_signed.\n    unfolds Int.half_modulus.\n    unfolds Int.modulus.\n    unfolds Int.wordsize.\n    unfolds Wordsize_32.wordsize.\n    unfolds two_power_nat.\n    unfolds shift_nat.\n    unfolds nat_rect.\n    simpl.\n    omega.\n  }\n  assert (Int.signed ($(16 + n2)) = 16 + n2). {\n    apply Int.signed_repr. apply H2.\n  }\n  clear H2. rewrite H3 in H. clear H3.\n\n  assert (n1 = n2). omega.\n\n  assert (w1 = $n1). rewrite Heqn1.\n  symmetry.\n  apply Int.repr_signed.\n\n  assert (w2 = $n2). rewrite Heqn2.\n  symmetry.\n  apply Int.repr_signed.\n\n  substs. auto.\n\n  inverts H0.\n  inverts H.\n  destruct O.\n  inverts H0.\n  destruct O.\n  inverts H.\nQed.\n\n\nLemma Determinacy_Inturrupt_Trap:\n  forall w Q Q',\n  has_trap_Q Q ->\n  interrupt w Q = Some Q' ->\n  False.\nProof.\n  intros.\n  unfolds in H0.\n  unfolds in H.\n  destruct Q.\n  unfolds in H.\n  destruct ((1 <=? Int.signed w) && (Int.signed w <=? 15)).\n  rewrite H in H0.\n  simpl in H0.\n  inverts H0.\n  inverts H0.\nQed.\n\nLemma Determinacy_Inturrupt_Deq:\n  forall w Q Q' e,\n  interrupt w Q = Some Q' ->\n  get_tt Q' = e ->\n  interrupt_e e = false ->\n  False.\nProof.\n  intros.\n  unfolds in H.\n  unfolds in H1.\n  unfolds in H0.\n  destruct Q.\n  remember ((1 <=? Int.signed w) && (Int.signed w <=? 15)).\n  destruct b.\n  destruct (negb (has_trap r) && trap_enabled r &&\n      ((Int.signed w =? 15) || (Int.signed (get_R pil r) <? Int.signed w))).\n  destruct Q'.\n  remember (set_trap r # tt <- ($ (16 + Int.signed w))).\n  inverts H.\n  rewrite <- H2 in H0. clear H2.\n\n  unfold get_R in H0.\n\n  assert (forall R,set_trap R tt = R tt). {\n    intros.\n    unfolds.\n    reflexivity.\n  }\n  rewrite H in H0. clear H.\n\n\n  assert (r # tt <- ($ (16 + Int.signed w)) tt = ($ (16 + Int.signed w))). {\n  apply RegMap.gss.\n  }\n  rewrite H in H0. clear H.\n\n  remember (Int.signed w) as n.\n\n  assert ( 1 <= n <= 15).\n  {\n    unfolds in Heqb.\n    remember (1 <=? n).\n    destruct b.\n    - symmetry in Heqb0.\n      apply Z.leb_le in Heqb0.\n      symmetry in Heqb.\n      apply Z.leb_le in Heqb.\n      auto.\n    - inverts Heqb.\n  }\n\n  assert ( 17 <= (16 + n) <= 31).\n  {\n    omega.\n  }\n\n  assert ( Int.min_signed <= (16 + n) <= Int.max_signed ).\n  {\n    remember (16+n) as n'.\n    intros.\n    unfolds Int.max_signed.\n    unfolds Int.min_signed.\n    unfolds Int.half_modulus.\n    unfolds Int.modulus.\n    unfolds Int.wordsize.\n    unfolds Wordsize_32.wordsize.\n    unfolds two_power_nat.\n    unfolds shift_nat.\n    unfolds nat_rect.\n    simpl.\n    omega.\n  }\n\n  assert (Int.signed ($(16 + n)) = 16 + n). {\n    apply Int.signed_repr. apply H3.\n  }\n\n  rewrite <- H0 in H1.\n  rewrite H4 in H1.\n\n  clear H Heqn H2 H0 H3 H4.\n\n\n  symmetry in Heqb.\n  apply and_true_true in Heqb.\n  destruct Heqb.\n  apply Z.leb_le in H.\n  apply Z.leb_le in H0.\n\n  apply and_false_false in H1.\n  destruct H1.\n\n  assert ((17 <=? 16 + n) = true).\n  {\n    apply Z.leb_le.\n    omega.\n  }\n  rewrite H1 in H2. inverts H2.\n\n  assert ((16 + n <=? 31) = true).\n  {\n    apply Z.leb_le.\n    omega.\n  }\n  rewrite H1 in H2. inverts H2.\n\n  inverts H.\n  inverts H.\n\nQed.\n\nLemma Determinacy_E:\n    forall CP S e S1 S2,\n    E__ CP S e S1 ->\n    E__ CP S e S2 ->\n    S1 = S2.\nProof.\n  intros.\n  inverts H; inverts H0; auto;\n  try rename w into w1;\n  try rename w0 into w2;\n  try rename Q' into Q1;\n  try rename Q'0 into Q2;\n  try rename Q'' into Q1';\n  try rename Q''0 into Q2';\n  try rename Q''' into Q1'';\n  try rename Q'''0 into Q2'';\n  try rename D' into D1;\n  try rename D'0 into D2;\n  try rename Ms' into Ms1;\n  try rename Ms'0 into Ms2.\n\n  - symmetry in H11.\n    assert (w1 = w2). apply (Determinacy_Inturrupt_Eq w1 w2 Q Q1 Q2); iauto.\n    substs.\n    rewrite H1 in H11. clear H1.\n    inverts H11.\n    rewrite H3 in H13. clear H3.\n    inverts H13.\n    assert ( Ms1 = Ms2 /\\ Q1'' = Q2'' /\\ D1 = D2). {\n      apply (Determinacy_H Cs Ms Ms1 Ms2 Q2' Q1'' Q2'' D D1 D2); iauto.\n    }\n    inverts H.\n    inverts H1.\n    auto.\n  - false. apply (Determinacy_Inturrupt_Trap w1 Q Q1); iauto.\n  - false. apply (Determinacy_Inturrupt_Trap w1 Q Q2); iauto.\n  - rewrite H3 in H13. clear H3.\n    inverts H13.\n    assert ( Ms1 = Ms2 /\\ Q1' = Q2' /\\ D1 = D2). {\n    apply (Determinacy_H Cs Ms Ms1 Ms2 Q2 Q1' Q2' D D1 D2); iauto.\n    }\n    inverts H.\n    inverts H2.\n    auto.\nQed.\n\nLemma Determinacy_PE_Deq:\n    forall CP S S1 S2 e,\n    P__ CP S S1 ->\n    interrupt_e e = false ->\n    E__ CP S e S2 ->\n    False.\nProof.\n  intros.\n  inverts H; inverts H0; auto;\n  inverts H1; auto;\n  try (apply (Determinacy_Inturrupt_Deq w Q Q'0 ((get_tt Q'0))); iauto);\n  try (destruct Q as (R & F); false).\nQed.\n\nTheorem Determinacy:\n    forall n E CP S S1 S2,\n    Z__ CP S E n S1 ->\n    Z__ CP S E n S2 ->\n    S1 = S2.\nProof.\n  induction n as [|n'].\n  - intros.\n    inverts H; inverts H0; auto.\n  - intros.\n    assert (Z__ CP S E (Datatypes.S n') S1) as I1. apply H.\n    assert (Z__ CP S E (Datatypes.S n') S2) as I2. apply H0.\n    inverts H; inverts H0; auto.\n    + assert (S'' = S''0).\n      apply (IHn' E0 CP S S'' S''0); auto.\n      substs.\n      apply (Determinacy_P CP S''0); auto.\n    + assert (S'' = S''0).\n      apply (IHn' E0 CP S S'' S''0); auto.\n      substs.\n      apply (Determinacy_E CP S''0 e); auto.\nQed.\n\nDefinition empty_DL: State -> Prop :=\n  fun S =>\n    let '(_,_,D) := S in D = nil.\n\nTheorem Non_Exfiltration_Iter:\n    forall CP S S' n E,\n    usr_mode_S S ->\n    no_psr_S S ->\n    Z__ CP S E n S' ->\n    no_trap E ->\n    sup_mem_eq S S' /\\ usr_mode_S S' /\\ no_psr_S S'.\nProof.\n  intros.\n  gen S S' E.\n  induction n as [|n'].\n  - intros.\n    inverts H1.\n    unfolds sup_mem_eq.\n    split; auto.\n    destruct S'.\n    destruct p.\n    destruct m.\n    auto.\n  - intros.\n    inverts H1.\n    assert (sup_mem_eq S S'' /\\ usr_mode_S S'' /\\ no_psr_S S''). {\n    apply (IHn' S H H0 S'' E0); iauto.\n    }\n    clear IHn' H4.\n\n    destruct S'' as (MPQ'' & D'').\n    destruct MPQ'' as (MP'' & Q'').\n    destruct MP'' as (Mu'' & Ms'').\n    destruct S as (MPQ & D).\n    destruct MPQ as (MP & Q).\n    destruct MP as (Mu & Ms).\n    destruct S' as (MPQ' & D').\n    destruct MPQ' as (MP' & Q').\n    destruct MP' as (Mu' & Ms').\n    destruct CP as (Cu & Cs).\n\n    simpl in H1.\n    simpl.\n\n    assert (usr_mode_Q Q' /\\ Ms'' = Ms' /\\ no_psr D'). {\n      apply (UserMode_P Cu Cs Mu'' Mu' Ms'' Ms' Q'' Q' D'' D'); iauto.\n    }\n    inverts H1.\n    inverts H3.\n    inverts H4.\n    iauto.\n\n\n  false.\nQed.\n\nDefinition ArrorWR: CodePair -> State -> nat -> State -> Prop:=\n    fun CP S n S' =>\n    exists E,usr_mode_S S /\\ empty_DL S /\\ Z__ CP S E n S' /\\ no_trap E.\n\nTheorem ModeControl:\n    forall CP S n S',\n      ArrorWR CP S n S' ->\n      usr_mode_S S'.\nProof.\n  intros.\n  unfolds in H.\n  destruct H as (E & H).\n  destruct H as (H0 & H1 & H2 & H3).\n  apply (Non_Exfiltration_Iter CP S S' n E); iauto.\n  unfolds.\n  destruct S.\n  destruct p.\n  unfolds in H1.\n  substs. unfolds. auto.\nQed.\n\n\nTheorem Non_Exfiltration:\n    forall CP S n S',\n      ArrorWR CP S n S' ->\n      sup_mem_eq S S'.\nProof.\n  intros.\n  unfolds in H.\n  destruct H as (E & H).\n  destruct H as (H0 & H1 & H2 & H3).\n  apply (Non_Exfiltration_Iter CP S S' n E); iauto.\n  unfolds.\n  destruct S.\n  destruct p.\n  unfolds in H1.\n  substs. unfolds. auto.\nQed.\n\n\n\nLemma Non_Infiltration_Iter:\n    forall n CP1 CP2 S1 S1' S2 S2' E1 E2,\n    usr_mode_S S1 /\\ no_psr_S S1 ->\n    usr_mode_S S2 /\\ no_psr_S S2 ->\n    usr_code_eq CP1 CP2 /\\ low_eq S1 S2 ->\n    Z__ CP1 S1 E1 n S1' /\\ Z__ CP2 S2 E2 n S2' ->\n    no_trap E1 /\\ no_trap E2 ->\n    low_eq S1' S2' /\\ usr_mode_S S1' /\\ usr_mode_S S2' /\\ no_psr_S S1' /\\ no_psr_S S2'.\nProof.\n  induction n.\n  - intros.\n    destruct H2 as (I1 & I2).\n    inverts I1; inverts I2; auto.\n    splits; iauto.\n  - intros.\n    destruct H2 as (I1 & I2).\n    inverts I1; inverts I2; auto.\n\n    rename S'' into S1''.\n    rename S''0 into S2''.\n    assert (low_eq S1'' S2'' /\\ usr_mode_S S1'' /\\ usr_mode_S S2'' /\\ no_psr_S S1'' /\\ no_psr_S S2''). {\n    apply (IHn CP1 CP2 S1 S1'' S2 S2'' E E0);\n    try split; iauto.\n    }\n\n    clear IHn H4 H5.\n\n    destruct CP1 as (Cu1 & Cs1).\n    destruct CP2 as (Cu2 & Cs2).\n\n    split.\n    apply (LowEq_P Cu1 Cu2 Cs1 Cs2 S1'' S2'' S1' S2'); iauto.\n    destruct S1'' as (MPQ1'' & D1'').\n    destruct MPQ1'' as (MP1'' & Q1'').\n    destruct MP1'' as (Mu1'' & Ms1'').\n    destruct S2'' as (MPQ2'' & D2'').\n    destruct MPQ2'' as (MP2'' & Q2'').\n    destruct MP2'' as (Mu2'' & Ms2'').\n    destruct S1' as (MPQ1' & D1').\n    destruct MPQ1' as (MP1' & Q1').\n    destruct MP1' as (Mu1' & Ms1').\n    destruct S2' as (MPQ2' & D2').\n    destruct MPQ2' as (MP2' & Q2').\n    destruct MP2' as (Mu2' & Ms2').\n\n\n    assert (usr_mode_S (Mu1', Ms1', Q1', D1') /\\ Ms1'' = Ms1' /\\ no_psr D1'). {\n    apply (UserMode_P Cu1 Cs1 Mu1'' Mu1' Ms1'' Ms1' Q1'' Q1' D1'' D1'); iauto.\n    }\n\n    assert (usr_mode_S (Mu2', Ms2', Q2', D2') /\\ Ms2'' = Ms2' /\\ no_psr D2'). {\n    apply (UserMode_P Cu2 Cs2 Mu2'' Mu2' Ms2'' Ms2' Q2'' Q2' D2'' D2'); iauto.\n    }\n\n    simpl in H4.\n    simpl in H5.\n    simpl.\n    splits; iauto.\n\n    inverts H3.\n    inverts H6.\n\n    inverts H3.\n    inverts H2.\n\n    inverts H3.\n    inverts H2.\n\nQed.\n\nTheorem Non_Infiltration:\n  forall n CP1 CP2 S1 S1' S2 S2',\n    usr_code_eq CP1 CP2 /\\ low_eq S1 S2 ->\n    ArrorWR CP1 S1 n S1' /\\ ArrorWR CP2 S2 n S2' ->\n    low_eq S1' S2'.\nProof.\n  intros.\n  destruct H.\n  destruct H0.\n  destruct H0 as (E1 & Hx).\n  destruct H2 as (E2 & Hy).\n  destruct Hx as (Hx0 & Hx1 & Hx2 & Hx3).\n  destruct Hy as (Hy0 & Hy1 & Hy2 & Hy3).\n  apply (Non_Infiltration_Iter n CP1 CP2 S1 S1' S2 S2' E1 E2); iauto;\n  splits; iauto.\n  unfolds.\n  destruct S1.\n  destruct p.\n  unfolds in Hx1.\n  substs. unfolds. auto.\n  unfolds.\n  destruct S2.\n  destruct p.\n  unfolds in Hy1.\n  substs. unfolds. auto.\nQed.\n\nLemma Exsits_Q:\n  forall i M R F D,\n    abort_ins i (R,F) M = false ->\n    unexpected_trap i (R,F) = None ->\n    exists M' R' F' D', Q__ (M,(R,F),D) i (M',(R',F'),D').\nProof.\n  intros.\n  destruct i;\n  unfolds in H;\n  unfolds in H0;\n  unfold trap_type in H0.\n\n  - (* bicc *)\n    remember (eval_AddrExp a R) as W.\n    destruct W; try solve [inverts H].\n    clear H.\n    remember (negb (word_aligned w)) as B.\n    destruct B; try solve [inverts H0].\n    assert (word_aligned_R w). {\n      unfolds in HeqB.\n      remember (word_aligned w).\n      destruct b.\n      unfolds. auto.\n      inverts HeqB.\n    }\n    clear H0.\n\n    remember (eval_TestCond t R).\n    destruct b; symmetry in Heqb.\n    assert (Q__ (M, (R,F),D) (bicc t a) (M, (djmp w R,F),D)).\n    {\n      apply MR.\n      apply (Bicc_true t a (bicc t a) w M R); auto.\n    }\n    exists M (djmp w R) F D. auto.\n\n    assert (Q__ (M, (R,F),D) (bicc t a) (M, (next R,F),D)). {\n      apply MR.\n      apply (Bicc_false t a (bicc t a) w M R); auto.\n    }\n    exists M (next R) F D. auto.\n\n  - (* bicca *)\n    remember (eval_AddrExp a R) as W.\n    destruct W; try solve [inverts H].\n    clear H.\n    remember (negb (word_aligned w)) as B.\n    destruct B; try solve [inverts H0].\n    assert (word_aligned_R w). {\n      unfolds in HeqB.\n      remember (word_aligned w).\n      destruct b.\n      unfolds. auto.\n      inverts HeqB.\n    }\n    clear H0.\n\n    destruct t.\n    assert (Q__ (M, (R,F),D) (bicca al a) (M,(set_annul(djmp w R),F),D)). {\n      apply MR.\n      apply (Bicca_always a (bicca al a) w M R); auto.\n    }\n    exists M (set_annul(djmp w R)) F D. auto.\n\n    assert (Q__ (M, (R,F),D) (bicca nv a) (M,(set_annul(next R),F),D)). {\n      apply MR.\n      apply (Bicca_false nv a (bicca nv a) w M R); auto.\n    }\n    exists M (set_annul(next R)) F D. auto.\n\n    remember (eval_TestCond ne R).\n    destruct b.\n    assert (Q__ (M, (R,F),D) (bicca ne a) (M,(djmp w R,F),D)). {\n      apply MR.\n      apply (Bicca ne a (bicca ne a) w M R); auto.\n      unfolds. intros I. inverts I.\n    }\n    exists M (djmp w R) F D. auto.\n    assert (Q__ (M, (R,F),D) (bicca ne a) (M,(set_annul(next R),F),D)). {\n      apply MR.\n      apply (Bicca_false ne a (bicca ne a) w M R); auto.\n    }\n    exists M (set_annul(next R)) F D. auto.\n\n    remember (eval_TestCond eq R).\n    destruct b.\n    assert (Q__ (M, (R,F),D) (bicca eq a) (M,(djmp w R,F),D)). {\n      apply MR.\n      apply (Bicca eq a (bicca eq a) w M R); auto.\n      unfolds. intros I. inverts I.\n    }\n    exists M (djmp w R) F D. auto.\n    assert (Q__ (M, (R,F),D) (bicca eq a) (M,(set_annul(next R),F),D)). {\n      apply MR.\n      apply (Bicca_false eq a (bicca eq a) w M R); auto.\n    }\n    exists M (set_annul(next R)) F D. auto.\n\n  - (* jmpl *)\n    remember (eval_AddrExp a R) as W.\n    destruct W; try solve [inverts H]. clear H.\n    remember (negb (word_aligned w)) as B.\n    destruct B; try solve [inverts H0].\n    assert (word_aligned_R w). {\n      unfolds in HeqB.\n      remember (word_aligned w).\n      destruct b.\n      unfolds. auto.\n      inverts HeqB.\n    }\n\n    remember (save_pc g R) as R'.\n\n    assert (Q__ (M, (R,F),D) (jmpl a g) (M,(djmp w R',F),D)). {\n      apply MR.\n      apply (Jmpl g a (jmpl a g) w M R R'); auto.\n    }\n    exists M (djmp w R') F D. auto.\n\n  - (* ld *)\n    remember (eval_AddrExp a R) as W.\n    destruct W; try solve [inverts H].\n    remember (M w) as A;\n    destruct A; try solve [inverts H].\n    clear H.\n    remember (negb (word_aligned w)) as B.\n    destruct B; try solve [inverts H0].\n    assert (word_aligned_R w). {\n      unfolds in HeqB.\n      remember (word_aligned w).\n      destruct b.\n      unfolds. auto.\n      inverts HeqB.\n    }\n    clear H0.\n\n    remember (R#g <- w0) as R'.\n    assert (Q__ (M, (R,F),D) (ld a g)  (M,(next R',F),D)). {\n      apply MR.\n      apply (Ld g a (ld a g) w w0 M R R'); auto.\n    }\n    exists M (next R') F D. auto.\n\n  - (* st *)\n    remember (eval_AddrExp a R) as W.\n    destruct W; try solve [inverts H].\n    clear H.\n    remember (negb (word_aligned w)) as B.\n    destruct B; try solve [inverts H0].\n    assert (word_aligned_R w). {\n      unfolds in HeqB.\n      remember (word_aligned w).\n      destruct b.\n      unfolds. auto.\n      inverts HeqB.\n    }\n    clear H0.\n\n    remember (WordMap.set w (Some(R#g)) M) as M'.\n    assert (Q__ (M, (R,F),D) (st g a) (M',(next R,F),D)). {\n      apply MR.\n      apply (St g a (st g a) w M M' R); auto.\n    }\n    exists M' (next R) F D. auto.\n\n  - remember (eval_TrapExp t0 R) as W.\n    destruct W; try solve [inverts H].\n    clear H.\n\n    remember (eval_TestCond t R).\n    destruct b.\n\n    assert (Q__ (M, (R,F),D)  (ticc t t0) (M,(set_user_trap (get_range 0 6 w) R,F),D)). {\n      apply MR.\n      apply (Ticc_true t t0 (ticc t t0) w M R); auto.\n    }\n    exists M (set_user_trap (get_range 0 6 w) R) F D. auto.\n\n    assert (Q__ (M, (R,F),D)  (ticc t t0) (M,(next R,F),D)). {\n      apply MR.\n      apply (Ticc_false t t0 (ticc t t0) w M R); auto.\n    }\n    exists M (next R) F D. auto.\n\n  - (* save *)\n    remember (eval_OpExp o R) as W.\n    destruct W; try solve [inverts H].\n    remember (dec_win (R, F)) as I.\n    destruct I; try solve [inverts H0].\n    destruct r as (R' & F').\n    remember (R'#g0 <- ((R#g) +ᵢ w)) as R''.\n    assert (Q__ (M,(R,F),D) (save g o g0) (M,(next R'',F'),D)). {\n      apply (Save g o g0 (save g o g0) w M R R' R'' F F'); auto.\n    }\n    exists M (next R'') F' D. auto.\n\n  - (* restore *)\n    remember (eval_OpExp o R) as W.\n    destruct W; try solve [inverts H].\n    remember (inc_win (R, F)) as I.\n    destruct I; try solve [inverts H0].\n    destruct r as (R' & F').\n    remember (R'#g0 <- ((R#g) +ᵢ w)) as R''.\n    assert (Q__ (M,(R,F),D) (restore g o g0) (M,(next R'',F'),D)). {\n      apply (Restore g o g0 (restore g o g0) w M R R' R'' F F'); auto.\n    }\n    exists M (next R'') F' D. auto.\n\n  - (* rett *)\n    remember (eval_AddrExp a R) as W.\n    destruct W; try solve [inverts H].\n    remember (word_aligned w) as B.\n    destruct B; try solve [inverts H].\n    remember (usr_mode R).\n    destruct b; try solve [inverts H].\n    remember (inc_win (R, F)) as I.\n    destruct I; try solve [inverts H].\n    destruct r as (R' & F').\n    clear H.\n    remember (trap_enabled R) as T.\n    destruct T; try solve [inverts H0].\n    clear H0.\n\n    remember (rett_f (R,F)) as K.\n    unfolds in HeqK.\n    rewrite <- HeqI in HeqK.\n    remember (restore_mode (enable_trap R')) as R''.\n \n    assert (Q__ (M,(R,F),D) (rett a) (M,(djmp w R'',F'),D)). {\n      apply (Rett a (rett a) w M R R'' F F'); try solve [unfolds; auto]; auto.\n      unfolds. rewrite <- HeqI. rewrite HeqR''. auto.\n    }\n    exists M (djmp w R'') F' D. auto.\n\n  - (* rd *)\n    destruct s;\n    remember (usr_mode R);\n    destruct b; try solve [inverts H0].\n\n    remember (R#g <- (R#psr)) as R'.\n    assert (Q__ (M,(R,F),D) (rd psr g) (M,(next R',F),D)). {\n      apply MR.\n      apply (Rd_sup psr g (rd psr g) M R R'); auto.\n      unfolds. auto.\n    }\n    exists M (next R') F D. auto.\n\n    remember (R#g <- (R#wim)) as R'.\n    assert (Q__ (M,(R,F),D) (rd wim g) (M,(next R',F),D)). {\n      apply MR.\n      apply (Rd_sup wim g (rd wim g) M R R'); auto.\n      unfolds. auto.\n    }\n    exists M (next R') F D. auto.\n\n    remember (R#g <- (R#tbr)) as R'.\n    assert (Q__ (M,(R,F),D) (rd tbr g) (M,(next R',F),D)). {\n      apply MR.\n      apply (Rd_sup tbr g (rd tbr g) M R R'); auto.\n      unfolds. auto.\n    }\n    exists M (next R') F D. auto.\n\n    remember (R#g <- (R#y)) as R'.\n    assert (Q__ (M,(R,F),D) (rd y g) (M,(next R',F),D)). {\n      apply MR.\n      apply (Rd_usr y g (rd y g) M R R'); auto.\n      unfolds. auto.\n      split; try split; try unfolds; intros; inverts H1.\n    }\n    exists M (next R') F D. auto.\n\n    remember (R#g <- (R#y)) as R'.\n    assert (Q__ (M,(R,F),D) (rd y g) (M,(next R',F),D)). {\n      apply MR.\n      apply (Rd_sup y g (rd y g) M R R'); auto.\n      unfolds. auto.\n    }\n    exists M (next R') F D. auto.\n\n    remember (R#g <- (R#a)) as R'.\n    assert (Q__ (M,(R,F),D) (rd a g) (M,(next R',F),D)). {\n      apply MR.\n      apply (Rd_usr a g (rd a g) M R R'); auto.\n      unfolds. auto.\n      split; try split; try unfolds; intros; inverts H1.\n    }\n    exists M (next R') F D. auto.\n\n    remember (R#g <- (R#a)) as R'.\n    assert (Q__ (M,(R,F),D) (rd a g) (M,(next R',F),D)). {\n      apply MR.\n      apply (Rd_sup a g (rd a g) M R R'); auto.\n      unfolds. auto.\n    }\n    exists M (next R') F D. auto.\n\n - (* wr *)\n    remember (eval_OpExp o R) as W.\n    destruct W; try solve [inverts H];\n    clear H;\n    remember ((R#g) xor w) as k;\n    destruct s;\n    remember (usr_mode R);\n    destruct b; try solve [inverts H0].\n\n    remember ((get_range 0 4 k) >=ᵢ Asm.N);\n    destruct b; try solve [inverts H0];\n    clear H0.\n\n    remember (set_delay psr k D) as D'.\n    remember (R#et <- (get_bit 5 k)\n              #pil <- (get_range 8 11 k)) as R'.\n    assert (Q__ (M,(R,F),D) (wr g o psr) (M,(next R',F),D')).\n    {\n      apply (Wr_psr g o (wr g o psr) w k M R R'); iauto.\n      unfolds. auto.\n    }\n    exists M (next R') F D'. auto.\n\n    remember (set_delay wim k D) as D'.\n    assert (Q__ (M,(R,F),D) (wr g o wim) (M,(next R,F),D')).\n    {\n      apply (Wr_sup g o wim (wr g o wim) w k M R F D D'); iauto.\n      unfolds. auto.\n      unfolds. intros. inverts H.\n    }\n    exists M (next R) F D'. auto.\n\n    remember (set_delay tbr k D) as D'.\n    assert (Q__ (M,(R,F),D) (wr g o tbr) (M,(next R,F),D')).\n    {\n      apply (Wr_sup g o tbr (wr g o tbr) w k M R F D D'); iauto.\n      unfolds. auto.\n      unfolds. intros. inverts H.\n    }\n    exists M (next R) F D'. auto.\n\n    remember (set_delay y k D) as D'.\n    assert (Q__ (M,(R,F),D) (wr g o y) (M,(next R,F),D')).\n    {\n      apply (Wr_usr g o y (wr g o y) w k M R F D D'); iauto.\n      unfolds. auto.\n      splits; unfolds; intros; inverts H.\n    }\n    exists M (next R) F D'. auto.\n\n    remember (set_delay y k D) as D'.\n    assert (Q__ (M,(R,F),D) (wr g o y) (M,(next R,F),D')).\n    {\n      apply (Wr_sup g o y (wr g o y) w k M R F D D'); iauto.\n      unfolds. auto.\n      unfolds. intros. inverts H.\n    }\n    exists M (next R) F D'. auto.\n\n    remember (set_delay a k D) as D'.\n    assert (Q__ (M,(R,F),D) (wr g o a) (M,(next R,F),D')).\n    {\n      apply (Wr_usr g o a (wr g o a) w k M R F D D'); iauto.\n      unfolds. auto.\n      splits; unfolds; intros; inverts H.\n    }\n    exists M (next R) F D'. auto.\n\n    remember (set_delay a k D) as D'.\n    assert (Q__ (M,(R,F),D) (wr g o a) (M,(next R,F),D')).\n    {\n      apply (Wr_sup g o a (wr g o a) w k M R F D D'); iauto.\n      unfolds. auto.\n      unfolds. intros. inverts H.\n    }\n    exists M (next R) F D'. auto.\n\n\n  - (* sll *)\n    remember (eval_OpExp o R) as W.\n    destruct W; try solve [inverts H].\n    clear H. clear H0.\n    remember ((R#g) <<ᵢ (get_range 0 4 w)) as k.\n    remember (R#g0 <- k) as R'.\n    assert (Q__ (M,(R,F),D) (sll g o g0) (M,(next R',F),D)). {\n    apply MR.\n    apply (Sll g o g0 (sll g o g0) w k M R R'); auto.\n    }\n    exists M (next R') F D. auto.\n\n  - (* srl *)\n    remember (eval_OpExp o R) as W.\n    destruct W; try solve [inverts H].\n    clear H. clear H0.\n    remember ((R#g) >>ᵢ (get_range 0 4 w)) as k.\n    remember (R#g0 <- k) as R'.\n    assert (Q__ (M,(R,F),D) (srl g o g0) (M,(next R',F),D)). {\n    apply MR.\n    apply (Srl g o g0 (srl g o g0) w k M R R'); auto.\n    }\n    exists M (next R') F D. auto.\n\n  - (* or *)\n    remember (eval_OpExp o R) as W.\n    destruct W; try solve [inverts H].\n    clear H. clear H0.\n    remember ((R#g) |ᵢ w) as k.\n    remember (R#g0 <- k) as R'.\n    assert (Q__ (M,(R,F),D) (or g o g0) (M,(next R',F),D)). {\n    apply MR.\n    apply (Or_ g o g0 (or g o g0) w k M R R'); auto.\n    }\n    exists M (next R') F D. auto.\n\n  - (* and *)\n    remember (eval_OpExp o R) as W.\n    destruct W; try solve [inverts H].\n    clear H. clear H0.\n    remember ((R#g) &ᵢ w) as k.\n    remember (R#g0 <- k) as R'.\n    assert (Q__ (M,(R,F),D) (and g o g0) (M,(next R',F),D)). {\n    apply MR.\n    apply (And_ g o g0 (and g o g0) w k M R R'); auto.\n    }\n    exists M (next R') F D. auto.\n\n  - (* nop *)\n    assert (Q__ (M,(R,F),D) nop (M,(next R,F),D)). {\n    apply MR.\n    apply (Nop nop M R). auto.\n    }\n    exists M (next R) F D. auto.\nQed.\n\n\n\nLemma Exsits_Ins:\n  forall i M Q D,\n    abort_ins i Q M = false ->\n    exists M' Q' D', Q__ (M,Q,D) i (M',Q',D').\nProof.\n  intros.\n  remember (unexpected_trap i Q).\n  destruct o.\n  assert (Q__ (M,Q,D) i (M,r,D)). {\n    apply (Trap_ins i M Q r); auto.\n  }\n  exists M r D. auto.\n\n  destruct Q as (R & F).\n  assert (exists M' R' F' D', Q__ (M,(R,F),D) i (M',(R',F'),D')). {\n    apply (Exsits_Q i M R F D); auto.\n  }\n\n  destruct H0 as (M' & R' & F' & D' & Hl).\n  exists M' (R',F') D'. auto.\nQed.\n\n\nLemma Hold_Annul:\n   forall D D' Q Q',\n      annuled_Q Q ->\n      exe_delay Q D = (Q',D') ->\n      annuled_Q Q'.\nProof.\n  induction D.\n  - intros.\n    inverts H0; auto.\n  - intros.\n    unfolds in H0.\n\n    asserts_rewrite (\n      (fix exe_delay (Q : RState) (D : DelayList) {struct D} :\n               RState * DelayList :=\n               match D with\n               | [] => (Q, D)\n               | (0%nat, syb0, w0) :: D' =>\n                   let (Q', D'') := exe_delay Q D' in\n                   let (R', F') := Q' in\n                   match syb0 with\n                   | psr =>\n                       (set_win (get_range 0 4 w0) (R' # syb0 <- w0, F'),\n                       D'')\n                   | wim => (R' # syb0 <- w0, F', D'')\n                   | tbr => (R' # syb0 <- w0, F', D'')\n                   | y => (R' # syb0 <- w0, F', D'')\n                   | Sasr _ => (R' # syb0 <- w0, F', D'')\n                   end\n               | (S k, syb0, w0) :: D' =>\n                   let (Q', D'') := exe_delay Q D' in\n                   (Q', (k, syb0, w0) :: D'')\n               end) Q D\n      = exe_delay Q D) in H0.\n    { unfolds. auto. }\n\n    remember (exe_delay Q D).\n    destruct p as (Q'' & D'').\n    assert (annuled_Q Q''). {\n      apply (IHD D'' Q Q''); iauto.\n    }\n    clear IHD Heqp.\n\n    {\n    destruct a.\n    destruct p.\n    destruct Q'' as (R'' & F'').\n    destruct Q' as (R' & F').\n    unfolds.\n    unfolds in H1.\n    unfolds in H1.\n    unfolds in H1.\n    assert ((get_R annul R'') =ᵢ ($ 1) = true). {\n      destruct ((get_R annul R'') =ᵢ ($ 1)); iauto.\n    } clear H1. rename H2 into H1.\n    unfolds.\n    unfolds.\n    assert ((get_R annul R') =ᵢ ($ 1) = true -> ((if (get_R annul R') =ᵢ ($ 1) then true else false) = true)).\n    {\n      intros.\n      destruct ((get_R annul R') =ᵢ ($ 1)); iauto.\n    }\n    apply H2.\n    clear H2.\n    destruct d;\n    destruct s;\n    try solve [inverts H0; auto].\n\n    {\n    remember (set_win (get_range 0 4 w) (R'' # psr <- w, F'')).\n    destruct r as (R''' & F''').\n\n    assert ((R'' # psr <- w)#annul = R'''#annul). {\n      apply (Hold_Sth_SetWin (R'' # psr <- w) R''' F'' F''' (get_range 0 4 w)); iauto.\n    }\n    assert (get_R annul R'' # psr <- w = get_R annul R''). iauto.\n    rewrite H3 in H2.\n    clear H3 Heqr.\n    inverts H0.\n    rewrite <- H2. auto.\n    }\n\n    }\nQed.\n\n\nLemma Hold_Annul2:\n   forall D D' Q Q',\n      not_annuled_Q Q ->\n      exe_delay Q D = (Q',D') ->\n      not_annuled_Q Q'.\nProof.\n  induction D.\n  - intros.\n    inverts H0; auto.\n  - intros.\n    unfolds in H0.\n\n    asserts_rewrite (\n      (fix exe_delay (Q : RState) (D : DelayList) {struct D} :\n               RState * DelayList :=\n               match D with\n               | [] => (Q, D)\n               | (0%nat, syb0, w0) :: D' =>\n                   let (Q', D'') := exe_delay Q D' in\n                   let (R', F') := Q' in\n                   match syb0 with\n                   | psr =>\n                       (set_win (get_range 0 4 w0) (R' # syb0 <- w0, F'),\n                       D'')\n                   | wim => (R' # syb0 <- w0, F', D'')\n                   | tbr => (R' # syb0 <- w0, F', D'')\n                   | y => (R' # syb0 <- w0, F', D'')\n                   | Sasr _ => (R' # syb0 <- w0, F', D'')\n                   end\n               | (S k, syb0, w0) :: D' =>\n                   let (Q', D'') := exe_delay Q D' in\n                   (Q', (k, syb0, w0) :: D'')\n               end) Q D\n      = exe_delay Q D) in H0.\n    { unfolds. auto. }\n\n    remember (exe_delay Q D).\n    destruct p as (Q'' & D'').\n    assert (not_annuled_Q Q''). {\n      apply (IHD D'' Q Q''); iauto.\n    }\n    clear IHD Heqp.\n\n    {\n    destruct a.\n    destruct p.\n    destruct Q'' as (R'' & F'').\n    destruct Q' as (R' & F').\n    unfolds.\n    unfolds in H1.\n    unfolds in H1.\n    unfolds in H1.\n    assert ((get_R annul R'') =ᵢ ($ 1) = false). {\n      destruct ((get_R annul R'') =ᵢ ($ 1)); iauto.\n    } clear H1. rename H2 into H1.\n    unfolds.\n    unfolds.\n    assert ((get_R annul R') =ᵢ ($ 1) = false -> ((if (get_R annul R') =ᵢ ($ 1) then true else false) = false)).\n    {\n      intros.\n      destruct ((get_R annul R') =ᵢ ($ 1)); iauto.\n    }\n    apply H2.\n    clear H2.\n    destruct d;\n    destruct s;\n    try solve [inverts H0; auto].\n\n    {\n    remember (set_win (get_range 0 4 w) (R'' # psr <- w, F'')).\n    destruct r as (R''' & F''').\n\n    assert ((R'' # psr <- w)#annul = R'''#annul). {\n      apply (Hold_Sth_SetWin (R'' # psr <- w) R''' F'' F''' (get_range 0 4 w)); iauto.\n    }\n    assert (get_R annul R'' # psr <- w = get_R annul R''). iauto.\n    rewrite H3 in H2.\n    clear H3 Heqr.\n    inverts H0.\n    rewrite <- H2. auto.\n    }\n\n    }\nQed.\n\n\nLemma Exsits_H:\n  forall C M Q Q' D D' i,\n    exe_delay Q D = (Q',D') ->\n    C (cursor_Q Q') = Some i ->\n    abort_ins i Q' M = false ->\n    exists M'' Q'' D'', H__ C (M,Q,D) (M'',Q'',D'').\nProof.\n  intros.\n  remember (exe_delay Q D).\n  destruct p as (Q'' & D'').\n  inverts H.\n  destruct Q as (R & F).\n  remember (annuled R).\n  destruct b.\n\n  remember (clear_annul_Q Q') as Q''.\n\n  assert (H__ C (M,(R,F),D) (M,next_Q Q'',D')). {\n    apply (Annul C M (R,F) Q' Q'' D D'); iauto.\n    apply (Hold_Annul D D' ((R, F)) Q'); iauto.\n    unfolds. unfolds. iauto.\n  }\n\n  exists M (next_Q Q'') D'. auto.\n\n  remember (R,F) as Q.\n  assert (exists M'' Q'' D'', Q__ (M,Q',D') i (M'',Q'',D'')). {\n    apply (Exsits_Ins i M Q'); auto.\n  }\n\n  destruct H as (M'' & Q'' & D'' & Hl).\n  destruct Q'' as (R'' & F'').\n\n  remember (R'', F'') as Q''.\n\n  assert (not_annuled_Q Q'). {\n    apply (Hold_Annul2 D D' Q Q'); iauto.\n    rewrite HeqQ.\n    unfolds. unfolds. iauto.\n  }\n\n  assert (H__ C (M,Q,D) (M'',Q'',D'')). {\n    apply (Normal i C M M'' Q Q' Q'' D D' D''); iauto.\n  }\n\n  exists M'' Q'' D''. auto.\nQed.\n\n\n\nDefinition not_abort(C: CodeHeap)(M: Memory)(Q: RState)(D: DelayList) :Prop :=\n  exists Q' D' i,\n    exe_delay Q D = (Q',D') /\\\n    C (cursor_Q Q') = Some i /\\\n    abort_ins i Q' M = false.\n\n\nLemma Exsits_H2:\n  forall C M Q D,\n    not_abort C M Q D ->\n    exists M'' Q'' D'', H__ C (M,Q,D) (M'',Q'',D'').\nProof.\n  intros.\n\n  unfolds in H.\n  destruct H as (Q' & D' & i & H & H1 & H2).\n\n  apply (Exsits_H C M Q Q' D D' i); iauto.\nQed.\n\n\nLemma Exists_P_Sup:\n  forall Cu Cs Mu Ms Q D,\n    no_trap_Q Q ->\n    sup_mode_Q Q ->\n    not_abort Cs Ms Q D ->\n    exists Ms' Q' D', P__ (Cu,Cs) ((Mu,Ms),Q,D) ((Mu,Ms'),Q',D').\nProof.\n  intros.\n\n  assert (exists Ms'' Q'' D'', H__ Cs (Ms,Q,D) (Ms'',Q'',D'')). {\n    apply (Exsits_H2 Cs Ms Q ); auto.\n  }\n  destruct H2 as (Ms'' & Q'' & D'' & Hl).\n  assert (P__ (Cu,Cs) ((Mu,Ms),Q,D) ((Mu,Ms''),Q'',D'')). {\n    apply (Nor_sup Q Q'' Cs Cu Ms Ms'' Mu D D''); iauto.\n  }\n  exists Ms'' Q'' D''. auto.\nQed.\n\nDefinition f_context(F: FrameList) :=\n  exists\n    P_w00 P_w01 P_w02 P_w03 P_w04 P_w05 P_w06 P_w07 \n    P_w10 P_w11 P_w12 P_w13 P_w14 P_w15 P_w16 P_w17 \n    P_w20 P_w21 P_w22 P_w23 P_w24 P_w25 P_w26 P_w27 \n    P_w30 P_w31 P_w32 P_w33 P_w34 P_w35 P_w36 P_w37 \n    P_w40 P_w41 P_w42 P_w43 P_w44 P_w45 P_w46 P_w47 \n    P_w50 P_w51 P_w52 P_w53 P_w54 P_w55 P_w56 P_w57 \n    P_w60 P_w61 P_w62 P_w63 P_w64 P_w65 P_w66 P_w67 \n    P_w70 P_w71 P_w72 P_w73 P_w74 P_w75 P_w76 P_w77 \n    P_w80 P_w81 P_w82 P_w83 P_w84 P_w85 P_w86 P_w87 \n    P_w90 P_w91 P_w92 P_w93 P_w94 P_w95 P_w96 P_w97 \n    P_wa0 P_wa1 P_wa2 P_wa3 P_wa4 P_wa5 P_wa6 P_wa7 \n    P_wb0 P_wb1 P_wb2 P_wb3 P_wb4 P_wb5 P_wb6 P_wb7 \n    P_wc0 P_wc1 P_wc2 P_wc3 P_wc4 P_wc5 P_wc6 P_wc7,\n  F =\n   [[P_w00;P_w01;P_w02;P_w03;P_w04;P_w05;P_w06;P_w07];\n    [P_w10;P_w11;P_w12;P_w13;P_w14;P_w15;P_w16;P_w17];\n    [P_w20;P_w21;P_w22;P_w23;P_w24;P_w25;P_w26;P_w27];\n    [P_w30;P_w31;P_w32;P_w33;P_w34;P_w35;P_w36;P_w37];\n    [P_w40;P_w41;P_w42;P_w43;P_w44;P_w45;P_w46;P_w47];\n    [P_w50;P_w51;P_w52;P_w53;P_w54;P_w55;P_w56;P_w57];\n    [P_w60;P_w61;P_w62;P_w63;P_w64;P_w65;P_w66;P_w67];\n    [P_w70;P_w71;P_w72;P_w73;P_w74;P_w75;P_w76;P_w77];\n    [P_w80;P_w81;P_w82;P_w83;P_w84;P_w85;P_w86;P_w87];\n    [P_w90;P_w91;P_w92;P_w93;P_w94;P_w95;P_w96;P_w97];\n    [P_wa0;P_wa1;P_wa2;P_wa3;P_wa4;P_wa5;P_wa6;P_wa7];\n    [P_wb0;P_wb1;P_wb2;P_wb3;P_wb4;P_wb5;P_wb6;P_wb7];\n    [P_wc0;P_wc1;P_wc2;P_wc3;P_wc4;P_wc5;P_wc6;P_wc7]].\n\n\n\nLemma left_then_right1 :\n  forall (i:RegNameEq.t) R F R' F' R'' F'',\n      f_context F ->\n      left_win 1 (R,F) = (R',F') ->\n      right_win 1 (R',F') = (R'',F'') ->\n      i <> cwp ->\n      R i = R'' i.\nProof.\n  intros.\n  rewrite <- H0 in H1.\n  clear H0.\n  unfold right_win in H1.\n  unfold left_win in H1.\n  asserts_rewrite ((Z.to_nat 1) = 1%nat) in H1. compute. auto.\n  unfold left_iter in H1.\n  unfold right_iter in H1.\n  unfolds in H.\n  destruct H as (\n    P_w00 & P_w01 & P_w02 & P_w03 & P_w04 & P_w05 & P_w06 & P_w07 &\n    P_w10 & P_w11 & P_w12 & P_w13 & P_w14 & P_w15 & P_w16 & P_w17 &\n    P_w20 & P_w21 & P_w22 & P_w23 & P_w24 & P_w25 & P_w26 & P_w27 &\n    P_w30 & P_w31 & P_w32 & P_w33 & P_w34 & P_w35 & P_w36 & P_w37 & \n    P_w40 & P_w41 & P_w42 & P_w43 & P_w44 & P_w45 & P_w46 & P_w47 & \n    P_w50 & P_w51 & P_w52 & P_w53 & P_w54 & P_w55 & P_w56 & P_w57 & \n    P_w60 & P_w61 & P_w62 & P_w63 & P_w64 & P_w65 & P_w66 & P_w67 & \n    P_w70 & P_w71 & P_w72 & P_w73 & P_w74 & P_w75 & P_w76 & P_w77 & \n    P_w80 & P_w81 & P_w82 & P_w83 & P_w84 & P_w85 & P_w86 & P_w87 & \n    P_w90 & P_w91 & P_w92 & P_w93 & P_w94 & P_w95 & P_w96 & P_w97 & \n    P_wa0 & P_wa1 & P_wa2 & P_wa3 & P_wa4 & P_wa5 & P_wa6 & P_wa7 & \n    P_wb0 & P_wb1 & P_wb2 & P_wb3 & P_wb4 & P_wb5 & P_wb6 & P_wb7 & \n    P_wc0 & P_wc1 & P_wc2 & P_wc3 & P_wc4 & P_wc5 & P_wc6 & P_wc7 & H).\n  substs.\n  unfold left in H1.\n  unfold right in H1.\n  unfold fench in H1.\n  unfold replace in H1.\n  simpl in H1.\n  inverts H1.\n\n  destruct i;\n  simpl; auto.\n  destruct g;\n  simpl; auto.\n  destruct p;\n  simpl; auto.\n  unfolds in H2.\n  false.\nQed.\n\n\nLemma right_cwp:\n  forall R R' F F',\n  f_context F ->\n  right_win 1 (R,F) = (R',F') ->\n  R'#cwp = pre_cwp 1 R.\nProof.\n  intros.\n  unfold right_win in *.\n  asserts_rewrite ((Z.to_nat 1) = 1%nat) in *. compute. auto.\n  unfold right_iter in *.\n  unfolds in H.\n  destruct H as (\n    P_w00 & P_w01 & P_w02 & P_w03 & P_w04 & P_w05 & P_w06 & P_w07 &\n    P_w10 & P_w11 & P_w12 & P_w13 & P_w14 & P_w15 & P_w16 & P_w17 &\n    P_w20 & P_w21 & P_w22 & P_w23 & P_w24 & P_w25 & P_w26 & P_w27 &\n    P_w30 & P_w31 & P_w32 & P_w33 & P_w34 & P_w35 & P_w36 & P_w37 & \n    P_w40 & P_w41 & P_w42 & P_w43 & P_w44 & P_w45 & P_w46 & P_w47 & \n    P_w50 & P_w51 & P_w52 & P_w53 & P_w54 & P_w55 & P_w56 & P_w57 & \n    P_w60 & P_w61 & P_w62 & P_w63 & P_w64 & P_w65 & P_w66 & P_w67 & \n    P_w70 & P_w71 & P_w72 & P_w73 & P_w74 & P_w75 & P_w76 & P_w77 & \n    P_w80 & P_w81 & P_w82 & P_w83 & P_w84 & P_w85 & P_w86 & P_w87 & \n    P_w90 & P_w91 & P_w92 & P_w93 & P_w94 & P_w95 & P_w96 & P_w97 & \n    P_wa0 & P_wa1 & P_wa2 & P_wa3 & P_wa4 & P_wa5 & P_wa6 & P_wa7 & \n    P_wb0 & P_wb1 & P_wb2 & P_wb3 & P_wb4 & P_wb5 & P_wb6 & P_wb7 & \n    P_wc0 & P_wc1 & P_wc2 & P_wc3 & P_wc4 & P_wc5 & P_wc6 & P_wc7 & H).\n  substs.\n  unfold right in *.\n  unfold left in *.\n  unfold fench in *.\n  unfold replace in *.\n  inverts H0.\n  simpl. auto.\nQed.\n\n\n\nLemma left_cwp:\n  forall R R' F F',\n  f_context F ->\n  left_win 1 (R,F) = (R',F') ->\n  R'#cwp = post_cwp 1 R.\nProof.\n  intros.\n  unfold left_win in *.\n  asserts_rewrite ((Z.to_nat 1) = 1%nat) in *. compute. auto.\n  unfold left_iter in *.\n  unfolds in H.\n  destruct H as (\n    P_w00 & P_w01 & P_w02 & P_w03 & P_w04 & P_w05 & P_w06 & P_w07 &\n    P_w10 & P_w11 & P_w12 & P_w13 & P_w14 & P_w15 & P_w16 & P_w17 &\n    P_w20 & P_w21 & P_w22 & P_w23 & P_w24 & P_w25 & P_w26 & P_w27 &\n    P_w30 & P_w31 & P_w32 & P_w33 & P_w34 & P_w35 & P_w36 & P_w37 & \n    P_w40 & P_w41 & P_w42 & P_w43 & P_w44 & P_w45 & P_w46 & P_w47 & \n    P_w50 & P_w51 & P_w52 & P_w53 & P_w54 & P_w55 & P_w56 & P_w57 & \n    P_w60 & P_w61 & P_w62 & P_w63 & P_w64 & P_w65 & P_w66 & P_w67 & \n    P_w70 & P_w71 & P_w72 & P_w73 & P_w74 & P_w75 & P_w76 & P_w77 & \n    P_w80 & P_w81 & P_w82 & P_w83 & P_w84 & P_w85 & P_w86 & P_w87 & \n    P_w90 & P_w91 & P_w92 & P_w93 & P_w94 & P_w95 & P_w96 & P_w97 & \n    P_wa0 & P_wa1 & P_wa2 & P_wa3 & P_wa4 & P_wa5 & P_wa6 & P_wa7 & \n    P_wb0 & P_wb1 & P_wb2 & P_wb3 & P_wb4 & P_wb5 & P_wb6 & P_wb7 & \n    P_wc0 & P_wc1 & P_wc2 & P_wc3 & P_wc4 & P_wc5 & P_wc6 & P_wc7 & H).\n  substs.\n  unfold left in *.\n  unfold fench in *.\n  unfold replace in *.\n  inverts H0.\n  simpl. auto.\nQed.\n\n\nLemma left_then_right2 :\n  forall R F R' F' R'' F'',\n      0 <= Int.unsigned (R#cwp) <= Int.unsigned(Asm.N)-1 ->\n      f_context F ->\n      left_win 1 (R,F) = (R',F') ->\n      right_win 1 (R',F') = (R'',F'') ->\n      R#cwp = R''#cwp.\nProof.\n  intros.\n\n  assert (f_context F' /\\ R'#cwp = post_cwp 1 R). {\n  unfold left_win in *.\n  asserts_rewrite ((Z.to_nat 1) = 1%nat) in *. compute. auto.\n  unfold left_iter in *.\n  destruct H0 as (\n    P_w00 & P_w01 & P_w02 & P_w03 & P_w04 & P_w05 & P_w06 & P_w07 &\n    P_w10 & P_w11 & P_w12 & P_w13 & P_w14 & P_w15 & P_w16 & P_w17 &\n    P_w20 & P_w21 & P_w22 & P_w23 & P_w24 & P_w25 & P_w26 & P_w27 &\n    P_w30 & P_w31 & P_w32 & P_w33 & P_w34 & P_w35 & P_w36 & P_w37 & \n    P_w40 & P_w41 & P_w42 & P_w43 & P_w44 & P_w45 & P_w46 & P_w47 & \n    P_w50 & P_w51 & P_w52 & P_w53 & P_w54 & P_w55 & P_w56 & P_w57 & \n    P_w60 & P_w61 & P_w62 & P_w63 & P_w64 & P_w65 & P_w66 & P_w67 & \n    P_w70 & P_w71 & P_w72 & P_w73 & P_w74 & P_w75 & P_w76 & P_w77 & \n    P_w80 & P_w81 & P_w82 & P_w83 & P_w84 & P_w85 & P_w86 & P_w87 & \n    P_w90 & P_w91 & P_w92 & P_w93 & P_w94 & P_w95 & P_w96 & P_w97 & \n    P_wa0 & P_wa1 & P_wa2 & P_wa3 & P_wa4 & P_wa5 & P_wa6 & P_wa7 & \n    P_wb0 & P_wb1 & P_wb2 & P_wb3 & P_wb4 & P_wb5 & P_wb6 & P_wb7 & \n    P_wc0 & P_wc1 & P_wc2 & P_wc3 & P_wc4 & P_wc5 & P_wc6 & P_wc7 & H0).\n  substs.\n  unfold left in *.\n  unfold fench in *.\n  unfold replace in *.\n\n  split.\n\n  inverts H1.\n  unfolds.\n  exists P_w20 P_w21 P_w22 P_w23 P_w24 P_w25.\n  exists P_w26 P_w27 P_w30 P_w31 P_w32 P_w33.\n  exists P_w34 P_w35 P_w36 P_w37 P_w40 P_w41.\n  exists P_w42 P_w43 P_w44 P_w45 P_w46 P_w47.\n  exists P_w50 P_w51 P_w52 P_w53 P_w54 P_w55.\n  exists P_w56 P_w57 P_w60 P_w61 P_w62 P_w63.\n  exists P_w64 P_w65 P_w66 P_w67 P_w70 P_w71.\n  exists P_w72 P_w73 P_w74 P_w75 P_w76 P_w77.\n  exists P_w80 P_w81 P_w82 P_w83 P_w84 P_w85.\n  exists P_w86 P_w87 P_w90 P_w91 P_w92 P_w93.\n  exists P_w94 P_w95 P_w96 P_w97 P_wa0 P_wa1.\n  exists P_wa2 P_wa3 P_wa4 P_wa5 P_wa6 P_wa7.\n  exists P_wb0 P_wb1 P_wb2 P_wb3 P_wb4 P_wb5.\n  exists P_wb6 P_wb7 P_wc0 P_wc1 P_wc2 P_wc3.\n  exists P_wc4 P_wc5 P_wc6 P_wc7 (R r8) (R r9).\n  exists (R r10) (R r11) (R r12) (R r13) (R r14) (R r15).\n  exists (R r16) (R r17) (R r18) (R r19) (R r20) (R r21).\n  exists (R r22) (R r23). auto.\n\n  inverts H1. simpl. auto.\n  }\n  clear H0 H1.\n\n\n  destruct H3 as (H0 & G).\n  assert (R''#cwp = pre_cwp 1 R'). {\n  unfold right_win in *.\n  asserts_rewrite ((Z.to_nat 1) = 1%nat) in *. compute. auto.\n  unfold right_iter in *.\n  destruct H0 as (\n    P_w00 & P_w01 & P_w02 & P_w03 & P_w04 & P_w05 & P_w06 & P_w07 &\n    P_w10 & P_w11 & P_w12 & P_w13 & P_w14 & P_w15 & P_w16 & P_w17 &\n    P_w20 & P_w21 & P_w22 & P_w23 & P_w24 & P_w25 & P_w26 & P_w27 &\n    P_w30 & P_w31 & P_w32 & P_w33 & P_w34 & P_w35 & P_w36 & P_w37 & \n    P_w40 & P_w41 & P_w42 & P_w43 & P_w44 & P_w45 & P_w46 & P_w47 & \n    P_w50 & P_w51 & P_w52 & P_w53 & P_w54 & P_w55 & P_w56 & P_w57 & \n    P_w60 & P_w61 & P_w62 & P_w63 & P_w64 & P_w65 & P_w66 & P_w67 & \n    P_w70 & P_w71 & P_w72 & P_w73 & P_w74 & P_w75 & P_w76 & P_w77 & \n    P_w80 & P_w81 & P_w82 & P_w83 & P_w84 & P_w85 & P_w86 & P_w87 & \n    P_w90 & P_w91 & P_w92 & P_w93 & P_w94 & P_w95 & P_w96 & P_w97 & \n    P_wa0 & P_wa1 & P_wa2 & P_wa3 & P_wa4 & P_wa5 & P_wa6 & P_wa7 & \n    P_wb0 & P_wb1 & P_wb2 & P_wb3 & P_wb4 & P_wb5 & P_wb6 & P_wb7 & \n    P_wc0 & P_wc1 & P_wc2 & P_wc3 & P_wc4 & P_wc5 & P_wc6 & P_wc7 & H0).\n  substs.\n  unfold right in *.\n  unfold left in *.\n  unfold fench in *.\n  unfold replace in *.\n  inverts H2.\n  simpl. auto.\n  }\n  clear H0 H2.\n\n  unfold post_cwp in G.\n  unfold pre_cwp in H1.\n  rewrite G in H1. clear G.\n  unfold Asm.N in H1.\n\n  remember (get_R cwp R) as c.\n  remember (get_R cwp R'') as c'.\n  remember (Int.unsigned c) as n.\n\n  unfold Asm.N in H.\n  asserts_rewrite (Int.unsigned $ 8 - 1 = 7) in H. {\n    clear Heqc Heqn H H1.\n    int auto.\n  }\n\n  assert (n = 0 \\/ n = 1 \\/ n = 2 \\/ n = 3 \\/ n = 4 \\/ n = 5\n   \\/ n = 6 \\/ n = 7). {\n    clear Heqc Heqn H1.\n    int auto.\n  }\n  clear H Heqc Heqc'.\n\n  destruct H0.\n  {\n    substs.\n    int auto;\n    rewrite H;\n    simpl;\n    int auto;\n    int auto;\n    mauto.\n    compute.\n    rewrite <- H.\n    symmetry.\n    apply Int.repr_unsigned.\n  }\n  destruct H.\n  {\n    substs.\n    int auto;\n    rewrite H;\n    simpl;\n    int auto;\n    int auto;\n    mauto.\n    compute.\n    rewrite <- H.\n    symmetry.\n    apply Int.repr_unsigned.\n  }\n  destruct H.\n  {\n    substs.\n    int auto;\n    rewrite H;\n    simpl;\n    int auto;\n    int auto;\n    mauto.\n    compute.\n    rewrite <- H.\n    symmetry.\n    apply Int.repr_unsigned.\n  }\n  destruct H.\n  {\n    substs.\n    int auto;\n    rewrite H;\n    simpl;\n    int auto;\n    int auto;\n    mauto.\n    compute.\n    rewrite <- H.\n    symmetry.\n    apply Int.repr_unsigned.\n  }\n  destruct H.\n  {\n    substs.\n    int auto;\n    rewrite H;\n    simpl;\n    int auto;\n    int auto;\n    mauto.\n    compute.\n    rewrite <- H.\n    symmetry.\n    apply Int.repr_unsigned.\n  }\n  destruct H.\n  {\n    substs.\n    int auto;\n    rewrite H;\n    simpl;\n    int auto;\n    int auto;\n    mauto.\n    compute.\n    rewrite <- H.\n    symmetry.\n    apply Int.repr_unsigned.\n  }\n  destruct H.\n  {\n    substs.\n    int auto;\n    rewrite H;\n    simpl;\n    int auto;\n    int auto;\n    mauto.\n    compute.\n    rewrite <- H.\n    symmetry.\n    apply Int.repr_unsigned.\n  }\n  {\n    substs.\n    int auto;\n    rewrite H;\n    simpl;\n    int auto;\n    int auto;\n    mauto.\n    compute.\n    rewrite <- H.\n    symmetry.\n    apply Int.repr_unsigned.\n  }\nQed.\n\n\nLemma left_then_right_R :\n  forall R F R' F' R'' F'',\n      0 <= Int.unsigned (R#cwp) <= Int.unsigned(Asm.N)-1 ->\n      f_context F ->\n      left_win 1 (R,F) = (R',F') ->\n      right_win 1 (R',F') = (R'',F'') ->\n      R = R''.\nProof.\n  intros.\n  apply functional_extensionality.\n  intros.\n  assert ({x = cwp} + {x <> cwp}). repeat decide equality.\n  destruct H3.\n  assert (get_R cwp R = get_R cwp R'').\n  apply (left_then_right2 R F R' F' R'' F''); iauto.\n  substs. iauto.\n\n  apply (left_then_right1 x R F R' F' R'' F''); iauto.\nQed.\n\n\nLemma left_then_right_F :\n  forall R F R' F' R'' F'',\n      f_context F ->\n      left_win 1 (R,F) = (R',F') ->\n      right_win 1 (R',F') = (R'',F'') ->\n      F = F''.\nProof.\n  intros.\n  rewrite <- H0 in H1.\n  clear H0.\n  unfold right_win in H1.\n  unfold left_win in H1.\n  asserts_rewrite ((Z.to_nat 1) = 1%nat) in H1. compute. auto.\n  unfold left_iter in H1.\n  unfold right_iter in H1.\n  unfolds in H.\n  destruct H as (\n    P_w00 & P_w01 & P_w02 & P_w03 & P_w04 & P_w05 & P_w06 & P_w07 &\n    P_w10 & P_w11 & P_w12 & P_w13 & P_w14 & P_w15 & P_w16 & P_w17 &\n    P_w20 & P_w21 & P_w22 & P_w23 & P_w24 & P_w25 & P_w26 & P_w27 &\n    P_w30 & P_w31 & P_w32 & P_w33 & P_w34 & P_w35 & P_w36 & P_w37 & \n    P_w40 & P_w41 & P_w42 & P_w43 & P_w44 & P_w45 & P_w46 & P_w47 & \n    P_w50 & P_w51 & P_w52 & P_w53 & P_w54 & P_w55 & P_w56 & P_w57 & \n    P_w60 & P_w61 & P_w62 & P_w63 & P_w64 & P_w65 & P_w66 & P_w67 & \n    P_w70 & P_w71 & P_w72 & P_w73 & P_w74 & P_w75 & P_w76 & P_w77 & \n    P_w80 & P_w81 & P_w82 & P_w83 & P_w84 & P_w85 & P_w86 & P_w87 & \n    P_w90 & P_w91 & P_w92 & P_w93 & P_w94 & P_w95 & P_w96 & P_w97 & \n    P_wa0 & P_wa1 & P_wa2 & P_wa3 & P_wa4 & P_wa5 & P_wa6 & P_wa7 & \n    P_wb0 & P_wb1 & P_wb2 & P_wb3 & P_wb4 & P_wb5 & P_wb6 & P_wb7 & \n    P_wc0 & P_wc1 & P_wc2 & P_wc3 & P_wc4 & P_wc5 & P_wc6 & P_wc7 & H).\n  substs.\n  unfold left in *.\n  unfold fench in *.\n  unfold replace in *.\n  inverts H1.\n  simpl. auto.\nQed.\n\n\nLemma right_stack_p :\n  forall R R' F F',\n      f_context F ->\n      right_win 1 (R,F) = (R',F') ->\n      R'#r30 = R#r14.\nProof.\n  intros.\n  unfolds in H.\n  destruct H as (\n    P_w00 & P_w01 & P_w02 & P_w03 & P_w04 & P_w05 & P_w06 & P_w07 &\n    P_w10 & P_w11 & P_w12 & P_w13 & P_w14 & P_w15 & P_w16 & P_w17 &\n    P_w20 & P_w21 & P_w22 & P_w23 & P_w24 & P_w25 & P_w26 & P_w27 &\n    P_w30 & P_w31 & P_w32 & P_w33 & P_w34 & P_w35 & P_w36 & P_w37 & \n    P_w40 & P_w41 & P_w42 & P_w43 & P_w44 & P_w45 & P_w46 & P_w47 & \n    P_w50 & P_w51 & P_w52 & P_w53 & P_w54 & P_w55 & P_w56 & P_w57 & \n    P_w60 & P_w61 & P_w62 & P_w63 & P_w64 & P_w65 & P_w66 & P_w67 & \n    P_w70 & P_w71 & P_w72 & P_w73 & P_w74 & P_w75 & P_w76 & P_w77 & \n    P_w80 & P_w81 & P_w82 & P_w83 & P_w84 & P_w85 & P_w86 & P_w87 & \n    P_w90 & P_w91 & P_w92 & P_w93 & P_w94 & P_w95 & P_w96 & P_w97 & \n    P_wa0 & P_wa1 & P_wa2 & P_wa3 & P_wa4 & P_wa5 & P_wa6 & P_wa7 & \n    P_wb0 & P_wb1 & P_wb2 & P_wb3 & P_wb4 & P_wb5 & P_wb6 & P_wb7 & \n    P_wc0 & P_wc1 & P_wc2 & P_wc3 & P_wc4 & P_wc5 & P_wc6 & P_wc7 & H).\n  substs.\n  unfold right_win in *.\n  asserts_rewrite ((Z.to_nat 1) = 1%nat) in *. compute. auto.\n  unfold right_iter in *.\n  unfold right in *.\n  unfold left in *.\n  simpl in H0.\n  inverts H0.\n  simpl. auto.\nQed.\n\n\nLemma hold_context:\n  forall R R' F F',\n    f_context F->\n    right_win 1 (R,F) = (R',F') ->\n    f_context F'.\nProof.\n  intros.\n  unfold right_win in *.\n  asserts_rewrite ((Z.to_nat 1) = 1%nat) in *. compute. auto.\n  unfold right_iter in *.\n  unfolds in H.\n  destruct H as (\n    P_w00 & P_w01 & P_w02 & P_w03 & P_w04 & P_w05 & P_w06 & P_w07 &\n    P_w10 & P_w11 & P_w12 & P_w13 & P_w14 & P_w15 & P_w16 & P_w17 &\n    P_w20 & P_w21 & P_w22 & P_w23 & P_w24 & P_w25 & P_w26 & P_w27 &\n    P_w30 & P_w31 & P_w32 & P_w33 & P_w34 & P_w35 & P_w36 & P_w37 & \n    P_w40 & P_w41 & P_w42 & P_w43 & P_w44 & P_w45 & P_w46 & P_w47 & \n    P_w50 & P_w51 & P_w52 & P_w53 & P_w54 & P_w55 & P_w56 & P_w57 & \n    P_w60 & P_w61 & P_w62 & P_w63 & P_w64 & P_w65 & P_w66 & P_w67 & \n    P_w70 & P_w71 & P_w72 & P_w73 & P_w74 & P_w75 & P_w76 & P_w77 & \n    P_w80 & P_w81 & P_w82 & P_w83 & P_w84 & P_w85 & P_w86 & P_w87 & \n    P_w90 & P_w91 & P_w92 & P_w93 & P_w94 & P_w95 & P_w96 & P_w97 & \n    P_wa0 & P_wa1 & P_wa2 & P_wa3 & P_wa4 & P_wa5 & P_wa6 & P_wa7 & \n    P_wb0 & P_wb1 & P_wb2 & P_wb3 & P_wb4 & P_wb5 & P_wb6 & P_wb7 & \n    P_wc0 & P_wc1 & P_wc2 & P_wc3 & P_wc4 & P_wc5 & P_wc6 & P_wc7 & H).\n  substs.\n  unfold right in *.\n  unfold left in *.\n  unfold fench in *.\n  unfold replace in *.\n\n  inverts H0.\n  unfolds.\n  jauto.\nQed.\n\n(*\n  hold in local when save -restore :\n*)\nLemma right_then_left_il :\n  forall (i:GenReg) R F R' F' R'' F'' R''',\n      f_context F ->\n      right_win 1 (R,F) = (R',F') ->\n      left_win 1 (R'',F') = (R''',F'') ->\n      i = r16 \\/ i = r17 \\/ i = r18 \\/ i = r31 ->\n      R''' i = R i.\nProof.\n  intros.\n  unfolds in H.\n  destruct H as (\n    P_w00 & P_w01 & P_w02 & P_w03 & P_w04 & P_w05 & P_w06 & P_w07 &\n    P_w10 & P_w11 & P_w12 & P_w13 & P_w14 & P_w15 & P_w16 & P_w17 &\n    P_w20 & P_w21 & P_w22 & P_w23 & P_w24 & P_w25 & P_w26 & P_w27 &\n    P_w30 & P_w31 & P_w32 & P_w33 & P_w34 & P_w35 & P_w36 & P_w37 & \n    P_w40 & P_w41 & P_w42 & P_w43 & P_w44 & P_w45 & P_w46 & P_w47 & \n    P_w50 & P_w51 & P_w52 & P_w53 & P_w54 & P_w55 & P_w56 & P_w57 & \n    P_w60 & P_w61 & P_w62 & P_w63 & P_w64 & P_w65 & P_w66 & P_w67 & \n    P_w70 & P_w71 & P_w72 & P_w73 & P_w74 & P_w75 & P_w76 & P_w77 & \n    P_w80 & P_w81 & P_w82 & P_w83 & P_w84 & P_w85 & P_w86 & P_w87 & \n    P_w90 & P_w91 & P_w92 & P_w93 & P_w94 & P_w95 & P_w96 & P_w97 & \n    P_wa0 & P_wa1 & P_wa2 & P_wa3 & P_wa4 & P_wa5 & P_wa6 & P_wa7 & \n    P_wb0 & P_wb1 & P_wb2 & P_wb3 & P_wb4 & P_wb5 & P_wb6 & P_wb7 & \n    P_wc0 & P_wc1 & P_wc2 & P_wc3 & P_wc4 & P_wc5 & P_wc6 & P_wc7 & H).\n  substs.\n  unfold right_win in *.\n  asserts_rewrite ((Z.to_nat 1) = 1%nat) in *. compute. auto.\n  unfold right_iter in *.\n  unfold right in *.\n  unfold left in *.\n  simpl in H0.\n  inverts H0.\n  unfold left_win in *.\n  asserts_rewrite ((Z.to_nat 1) = 1%nat) in *. compute. auto.\n  unfold left_iter in *.\n  unfold left in *.\n  simpl in H1.\n  inverts H1.\n\n  destruct H2. substs. simpl. auto.\n  destruct H. substs. simpl. auto.\n  destruct H. substs. simpl. auto.\n  substs. simpl. auto.\nQed.\n\nLemma right_right_same :\n  forall (i:GenReg) R1 R2 F R1' R2' F1 F2,\n      f_context F ->\n      right_win 1 (R1,F) = (R1',F1) ->\n      right_win 1 (R2,F) = (R2',F2) ->\n      i = r8 \\/ i = r14 \\/ i = r23 ->\n      R1' i = R2' i.\nProof.\n  intros.\n  unfolds in H.\n  destruct H as (\n    P_w00 & P_w01 & P_w02 & P_w03 & P_w04 & P_w05 & P_w06 & P_w07 &\n    P_w10 & P_w11 & P_w12 & P_w13 & P_w14 & P_w15 & P_w16 & P_w17 &\n    P_w20 & P_w21 & P_w22 & P_w23 & P_w24 & P_w25 & P_w26 & P_w27 &\n    P_w30 & P_w31 & P_w32 & P_w33 & P_w34 & P_w35 & P_w36 & P_w37 & \n    P_w40 & P_w41 & P_w42 & P_w43 & P_w44 & P_w45 & P_w46 & P_w47 & \n    P_w50 & P_w51 & P_w52 & P_w53 & P_w54 & P_w55 & P_w56 & P_w57 & \n    P_w60 & P_w61 & P_w62 & P_w63 & P_w64 & P_w65 & P_w66 & P_w67 & \n    P_w70 & P_w71 & P_w72 & P_w73 & P_w74 & P_w75 & P_w76 & P_w77 & \n    P_w80 & P_w81 & P_w82 & P_w83 & P_w84 & P_w85 & P_w86 & P_w87 & \n    P_w90 & P_w91 & P_w92 & P_w93 & P_w94 & P_w95 & P_w96 & P_w97 & \n    P_wa0 & P_wa1 & P_wa2 & P_wa3 & P_wa4 & P_wa5 & P_wa6 & P_wa7 & \n    P_wb0 & P_wb1 & P_wb2 & P_wb3 & P_wb4 & P_wb5 & P_wb6 & P_wb7 & \n    P_wc0 & P_wc1 & P_wc2 & P_wc3 & P_wc4 & P_wc5 & P_wc6 & P_wc7 & H).\n  substs.\n  unfold right_win in *.\n  asserts_rewrite ((Z.to_nat 1) = 1%nat) in *. compute. auto.\n  unfold right_iter in *.\n  unfold right in *.\n  unfold left in *.\n  simpl in H0.\n  inverts H0.\n  simpl in H1.\n  inverts H1.\n\n  destruct H2. substs.\n  compute. auto.\n\n  destruct H. substs.\n  compute. auto.\n\n  substs.\n  compute. auto.\nQed.\n\n\n\nLemma hold_context_left:\n  forall R R' F F',\n    f_context F->\n    left_win 1 (R,F) = (R',F') ->\n    f_context F'.\nProof.\n  intros.\n  unfold left_win in *.\n  asserts_rewrite ((Z.to_nat 1) = 1%nat) in *. compute. auto.\n  unfold left_iter in *.\n  unfolds in H.\n  destruct H as (\n    P_w00 & P_w01 & P_w02 & P_w03 & P_w04 & P_w05 & P_w06 & P_w07 &\n    P_w10 & P_w11 & P_w12 & P_w13 & P_w14 & P_w15 & P_w16 & P_w17 &\n    P_w20 & P_w21 & P_w22 & P_w23 & P_w24 & P_w25 & P_w26 & P_w27 &\n    P_w30 & P_w31 & P_w32 & P_w33 & P_w34 & P_w35 & P_w36 & P_w37 & \n    P_w40 & P_w41 & P_w42 & P_w43 & P_w44 & P_w45 & P_w46 & P_w47 & \n    P_w50 & P_w51 & P_w52 & P_w53 & P_w54 & P_w55 & P_w56 & P_w57 & \n    P_w60 & P_w61 & P_w62 & P_w63 & P_w64 & P_w65 & P_w66 & P_w67 & \n    P_w70 & P_w71 & P_w72 & P_w73 & P_w74 & P_w75 & P_w76 & P_w77 & \n    P_w80 & P_w81 & P_w82 & P_w83 & P_w84 & P_w85 & P_w86 & P_w87 & \n    P_w90 & P_w91 & P_w92 & P_w93 & P_w94 & P_w95 & P_w96 & P_w97 & \n    P_wa0 & P_wa1 & P_wa2 & P_wa3 & P_wa4 & P_wa5 & P_wa6 & P_wa7 & \n    P_wb0 & P_wb1 & P_wb2 & P_wb3 & P_wb4 & P_wb5 & P_wb6 & P_wb7 & \n    P_wc0 & P_wc1 & P_wc2 & P_wc3 & P_wc4 & P_wc5 & P_wc6 & P_wc7 & H).\n  substs.\n  unfold left in *.\n  unfold fench in *.\n  unfold replace in *.\n\n  inverts H0.\n  unfolds.\n  jauto.\nQed.\n\n", "meta": {"author": "wangjwchn", "repo": "sparcv8-coq", "sha": "57ec0b86879adc02691f87dbade19de27cf4aebf", "save_path": "github-repos/coq/wangjwchn-sparcv8-coq", "path": "github-repos/coq/wangjwchn-sparcv8-coq/sparcv8-coq-57ec0b86879adc02691f87dbade19de27cf4aebf/Property.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.37387580881868493, "lm_q1q2_score": 0.2015127875743076}}
{"text": "From Coq Require Import Reals Bool Relations RelationClasses List ListSet Setoid Permutation EqdepFacts ChoiceFacts Classical.\nImport ListNotations.\n\nFrom CasperCBC.Lib Require Import Preamble ListExtras ListSetExtras RealsExtras Measurable.\nFrom CasperCBC Require Import VLSM.Equivocation VLSM.Decisions CBC.Common.\n\n(** * CBC State Definitions and Lemmas *)\n\nInductive state {C V : Type} : Type :=\n  | Empty : state\n  | Next : C ->  V -> state -> state -> state.\n\nDefinition state0 (C V : Type) : @state C V := Empty.\n\nNotation \"'add' ( c , v , j ) 'to' sigma\" :=\n  (Next c v j sigma)\n  (at level 20).\n\n(* Constructing a StrictlyComparable state type *)\nLemma state_inhabited\n  {C} {V} `{about_C : StrictlyComparable C} `{about_V : StrictlyComparable V}\n  : @state C V.\nProof.\n  exact (state0 C V).\nQed.\n\nFixpoint state_compare\n  {C} `{about_C : StrictlyComparable C} {V} `{about_V : StrictlyComparable V}\n  (sigma1 sigma2 : @state C V) : comparison\n  :=\n  match sigma1, sigma2 with\n  | Empty, Empty => Eq\n  | Empty, _ => Lt\n  | _, Empty => Gt\n  | add (c1, v1, j1) to sigma1, add (c2, v2, j2) to sigma2 =>\n    match compare c1 c2 with\n    | Eq =>\n      match compare v1 v2 with\n      | Eq =>\n        match state_compare j1 j2 with\n        | Eq => state_compare sigma1 sigma2\n        | cmp_j => cmp_j\n        end\n      | cmp_v => cmp_v\n      end\n    | cmp_c => cmp_c\n    end\n  end.\n\nLemma state_compare_reflexive\n  {C} `{about_C : StrictlyComparable C} {V} `{about_V : StrictlyComparable V}\n  : CompareReflexive (@state_compare C about_C V about_V).\nProof.\n  intro x. induction x; intros; destruct y; split; intros; try discriminate; try reflexivity.\n  - simpl in H.\n    destruct (compare c c0) eqn:Hcmp; try discriminate.\n    apply StrictOrder_Reflexive in Hcmp; subst.\n    destruct (compare v v0) eqn:Hcmp; try discriminate.\n    apply StrictOrder_Reflexive in Hcmp; subst.\n    destruct (state_compare x1 y1) eqn:Hcmp; try discriminate.\n    apply IHx1 in Hcmp. apply IHx2 in H. subst.\n    reflexivity.\n  - inversion H; subst. simpl.\n    repeat rewrite compare_eq_refl.\n    assert (state_compare y1 y1 = Eq).\n    { apply IHx1. reflexivity. }\n    assert (state_compare y2 y2 = Eq).\n    { apply IHx2. reflexivity. }\n    rewrite H0. assumption.\nQed.\n\nLemma state_compare_transitive\n  {C} `{about_C : StrictlyComparable C} {V} `{about_V : StrictlyComparable V}\n  : CompareTransitive (@state_compare C about_C V about_V).\nProof.\n  destruct (@compare_strictorder C about_C) as [Rc Tc].\n  destruct (@compare_strictorder V about_V) as [Rv Tv].\n  - intros x y. generalize dependent x.\n    induction y; intros; destruct x; destruct z; try assumption\n    ; destruct comp; try discriminate\n    ; simpl; simpl in H\n    ; destruct (compare c0 c) eqn:Hc0; try discriminate\n    ; simpl in H0\n    ; destruct (compare c c1) eqn:Hc1; try discriminate\n    ; try (apply (Tc c0 c c1 _ Hc0) in Hc1 ; destruct (compare c0 c1); try discriminate; reflexivity)\n    ; try (apply Rc in Hc1; subst; rewrite Hc0; try reflexivity)\n    ; try (apply Rc in Hc0; subst; rewrite Hc1; try reflexivity)\n    ; destruct (compare v0 v) eqn:Hv0; try discriminate\n    ; destruct (compare v v1) eqn:Hv1; try discriminate\n    ; try (apply (Tv v0 v v1 _ Hv0) in Hv1; destruct (compare v0 v1); try discriminate; reflexivity)\n    ; try (apply Rv in Hv0; subst; rewrite Hv1; try reflexivity)\n    ; try (apply Rv in Hv1; subst; rewrite Hv0; try reflexivity)\n    ; destruct (state_compare x1 y1) eqn:Hj0; try discriminate\n    ; destruct (state_compare y1 z1) eqn:Hj1; try discriminate\n    ; try (apply (IHy1 x1 z1 _ Hj0) in Hj1; rewrite Hj1; try reflexivity)\n    ; try (apply state_compare_reflexive in Hj0; subst; rewrite Hj1; try reflexivity)\n    ; try (apply state_compare_reflexive in Hj1; subst; rewrite Hj0; try reflexivity)\n    ; apply (IHy2 x2 z2 _ H) in H0; assumption.\nQed.\n\nLemma state_compare_strict_order\n  {C} `{about_C : StrictlyComparable C} {V} `{about_V : StrictlyComparable V}\n  : CompareStrictOrder (@state_compare C about_C V about_V).\nProof.\n  split.\n  - apply state_compare_reflexive.\n  - apply state_compare_transitive.\nQed.\n\nInstance state_type\n  {C} `{about_C : StrictlyComparable C} {V} `{about_V : StrictlyComparable V}\n  : StrictlyComparable state :=\n  {\n    inhabited := @state_inhabited C V _ _;\n    compare := state_compare;\n    compare_strictorder := state_compare_strict_order;\n  }.\n\n(* Constructing a StrictlyComparable message type *)\nDefinition message (C V : Type) : Type := (C * V * @state C V).\n\nLemma message_inhabited\n  {C} `{about_C : StrictlyComparable C} {V} `{about_V : StrictlyComparable V}\n  : message C V.\nProof.\n  assert (inhabitedC := about_C); destruct inhabitedC as [inhabitedC _ _ ].\n  assert (inhabitedV := about_V); destruct inhabitedV as [inhabitedV _ _ ].\n  exact (inhabitedC,inhabitedV,state0 C V).\nQed.\n\nDefinition estimate {C V} (msg : message C V ) : C :=\n  match msg with (c, _ , _) => c end.\n\nDefinition sender {C V} (msg : message C V) : V :=\n  match msg with (_, v, _) => v end.\n\nDefinition justification {C V} (msg : message C V) : state :=\n  match msg with (_, _, sigma) => sigma end.\n\nFixpoint get_messages {C V} (sigma : state) : list (message C V) :=\n  match sigma with\n  | Empty => []\n  | add (c, v, j) to sigma' => (c,v,j) :: get_messages sigma'\n  end.\n\nDefinition observed\n  {C V} `{StrictlyComparable V}\n  (sigma: @state C V) : list V :=\n  set_map compare_eq_dec sender (get_messages sigma).\n\nDefinition next {C V} (msg : message C V) (sigma : state) : state :=\n  match msg with\n  | (c, v, j) => add (c, v, j) to sigma\n  end.\n\nLemma get_messages_next {C V} : forall (msg : message C V) sigma,\n  get_messages (next msg sigma) = msg :: get_messages sigma.\nProof.\n  destruct msg as [(c, v) j]. simpl. reflexivity.\nQed.\n\nLemma add_is_next {C V} : forall (c : C) (v : V) j sigma,\n  add (c, v, j)to sigma = next (c, v, j) sigma.\nProof.\n  intros. unfold next. reflexivity.\nQed.\n\nLemma no_confusion_next {C V} : forall (msg1 msg2 : message C V) sigma1 sigma2,\n  next msg1 sigma1 = next msg2 sigma2 ->\n  msg1 = msg2 /\\ sigma1 = sigma2.\nProof.\n  intros.\n  destruct msg1 as [(c1, v1) j1].\n  destruct msg2 as [(c2, v2) j2].\n  inversion H; subst; clear H.\n  split; reflexivity.\nQed.\n\nLemma no_confusion_next_empty {C V} : forall (msg : message C V) sigma,\n  next msg sigma <> Empty.\nProof.\n  intros. intro. destruct msg as [(c, v) j]. inversion H.\nQed.\n\nDefinition message_compare\n  {C} `{about_C : StrictlyComparable C} {V} `{about_V : StrictlyComparable V}\n  (msg1 msg2 : message C V) : comparison :=\n  state_compare (next msg1 Empty) (next msg2 Empty).\n\nLemma message_compare_strict_order\n  {C} `{about_C : StrictlyComparable C} {V} `{about_V : StrictlyComparable V}\n  : CompareStrictOrder (@message_compare C about_C V about_V).\nProof.\n  split.\n  - intros msg1 msg2. unfold message_compare.\n    rewrite (state_compare_reflexive (next msg1 Empty) (next msg2 Empty)).\n    split; intros; subst; try reflexivity.\n    apply no_confusion_next in H. destruct H. assumption.\n  - intros msg1 msg2 msg3. unfold message_compare. apply state_compare_transitive.\nQed.\n\nInstance message_strictorder\n  {C} `{about_C : StrictlyComparable C} {V} `{about_V : StrictlyComparable V}\n  : CompareStrictOrder (@message_compare C about_C V about_V).\nProof.\n  split.\n  - intros msg1 msg2. unfold message_compare.\n    rewrite (state_compare_reflexive (next msg1 Empty) (next msg2 Empty)).\n    split; intros; subst; try reflexivity.\n    apply no_confusion_next in H. destruct H. assumption.\n  - intros msg1 msg2 msg3. unfold message_compare. apply state_compare_transitive.\nDefined.\n\nInstance message_type\n  {C} `{about_C : StrictlyComparable C} {V} `{about_V : StrictlyComparable V}\n  : StrictlyComparable (message C V) :=\n  { inhabited := message_inhabited;\n    compare := message_compare;\n    compare_strictorder := message_compare_strict_order;\n  }.\n\n(* Constructing a StrictOrder type for message_lt *)\n\nDefinition message_lt\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : message C V -> message C V -> Prop\n  :=\n  compare_lt compare.\n\nInstance message_lt_strictorder\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : StrictOrder (@message_lt C V about_M).\nProof.\n  split. apply compare_lt_irreflexive.\n  apply compare_lt_transitive.\nDefined.\n\n(* Defining state_union using messages *)\n\n(* Library for state type *)\n\n(* State membership *)\nDefinition in_state\n  {C V}\n  (msg : message C V) (sigma : state) : Prop\n  :=\n  In msg (get_messages sigma).\n\nDefinition syntactic_state_inclusion\n  {C V}\n  (sigma1 : @state C V) (sigma2 : state) : Prop\n  :=\n  incl (get_messages sigma1) (get_messages sigma2).\n\nLemma in_empty_state\n  {C V}\n  : forall (msg : message C V),\n  ~ in_state msg Empty.\nProof.\n  intros. intro. inversion H.\nQed.\n\nLemma in_state_dec\n  {C V} `{HscM : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma,\n  {in_state msg sigma} + {~ in_state msg sigma}.\nProof.\n  intros. apply in_dec. apply compare_eq_dec.\nQed.\n\nLemma in_state_dec_if_true\n  {C V} `{HscM : StrictlyComparable (message C V)}\n  {A}\n  : forall msg sigma (T E : A),\n  in_state msg sigma ->\n  (if in_state_dec msg sigma then T else E) = T.\nProof.\n  intros. destruct (in_state_dec msg sigma); try reflexivity.\n  exfalso. apply n. apply H.\nQed.\n\nLemma in_state_dec_if_false\n  {C V} `{HscM : StrictlyComparable (message C V)}\n  {A}\n  : forall msg sigma (T E : A),\n  ~ in_state msg sigma ->\n  (if in_state_dec msg sigma then T else E) = E.\nProof.\n  intros. destruct (in_state_dec msg sigma); try reflexivity.\n  exfalso. apply H. apply i.\nQed.\n\nDefinition in_state_fn\n  {C V} `{HscM : StrictlyComparable (message C V)}\n  (msg : message C V) (sigma : state) : bool\n  :=\n  match in_state_dec msg sigma with\n  | left _ => true\n  | right _ => false\n  end.\n\nLemma in_state_correct\n  {C V} `{HscM : StrictlyComparable (message C V)}\n  : forall (msg : message C V) s,\n    in_state_fn msg s = true <-> in_state msg s.\nProof.\n  intros msg sigma; split; intro; destruct (in_state_dec msg sigma) eqn:Hin;\n  unfold in_state_fn in *.\n  - assumption.\n  - exfalso. rewrite Hin in H. discriminate.\n  - rewrite Hin. reflexivity.\n  - exfalso; apply n; apply H.\nQed.\n\nLemma in_state_correct'\n  {C V} `{HscM : StrictlyComparable (message C V)}\n  : forall msg s,\n    in_state_fn msg s = false <-> ~ in_state msg s.\nProof.\n  intros; assert (H_useful := in_state_correct).\n  now apply mirror_reflect_curry.\nQed.\n\nLemma in_state_next_iff\n  {C V}\n  : forall (msg msg1 : message C V) sigma1,\n  in_state msg (next msg1 sigma1) <-> msg1 = msg \\/ in_state msg sigma1.\nProof.\n  unfold in_state. intros. rewrite get_messages_next. simpl.\n  split; intros; destruct H; (left; assumption) || (right; assumption).\nQed.\n\nLemma in_singleton_state\n  {C V}\n  : forall (msg msg' : message C V),\n  in_state msg (next msg' Empty) -> msg = msg'.\nProof.\n  intros. apply in_state_next_iff in H.\n  destruct H; subst; try reflexivity.\n  exfalso. apply (in_empty_state _ H).\nQed.\n\nLemma not_extx_in_x {C V} : forall (c : C) (v : V) j j',\n  syntactic_state_inclusion j' j ->\n   ~ in_state (c, v, j) j'.\nProof.\n  induction j'; intros;  unfold in_state; simpl; intro; try assumption.\n  destruct H0.\n  - inversion H0; subst; clear H0.\n    apply IHj'1; try apply incl_refl. apply H. left. reflexivity.\n  - apply IHj'2; try assumption.\n    intros msg Hin. apply H. right. assumption.\nQed.\n\n(* Ordering on states *)\nInductive locally_sorted\n  {C V} `{HscM : StrictlyComparable (message C V)}\n  : @state C V -> Prop :=\n  | LSorted_Empty : locally_sorted Empty\n  | LSorted_Singleton : forall c v j,\n          locally_sorted j ->\n          locally_sorted (next (c, v, j) Empty)\n  | LSorted_Next : forall c v j msg' sigma,\n          locally_sorted j  ->\n          message_lt (c, v, j) msg' ->\n          locally_sorted (next msg' sigma) ->\n          locally_sorted (next (c, v, j) (next msg' sigma))\n  .\n\nDefinition locally_sorted_msg\n  {C V} `{HscM : StrictlyComparable (message C V)}\n  (msg : message C V) : Prop\n  :=\n  @locally_sorted C V HscM (next msg Empty).\n\nLemma locally_sorted_message_justification\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (c : C) (v : V) j,\n  locally_sorted_msg (c,v,j) <-> locally_sorted j.\nProof.\n  intros; split; intro.\n  - inversion H; subst; assumption.\n  - apply LSorted_Singleton. assumption.\nQed.\n\nLemma locally_sorted_message_characterization\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma : @state C V,\n  locally_sorted sigma <->\n  sigma = Empty\n  \\/\n  (exists msg, locally_sorted_msg msg /\\ sigma = next msg Empty)\n  \\/\n  (exists msg1 msg2 sigma',\n    sigma = next msg1 (next msg2 sigma')\n    /\\ locally_sorted (next msg2 sigma')\n    /\\ locally_sorted_msg msg1\n    /\\ message_lt msg1 msg2\n  ).\nProof.\n  split; intros.\n  { inversion H; subst.\n    - left. reflexivity.\n    - right. left. exists (c,v,j).\n      split; try reflexivity.\n      apply locally_sorted_message_justification. assumption.\n    - right. right. exists (c, v, j). exists msg'. exists sigma0.\n      split; try reflexivity.\n      repeat (split; try assumption).\n      apply locally_sorted_message_justification. assumption.\n  }\n  { destruct H as [H | [H | H]]; subst; try constructor.\n    - destruct H as [msg [LSmsg EQ]]; subst.\n      destruct msg as [(c,v) j]. apply locally_sorted_message_justification in LSmsg.\n      constructor. assumption.\n    - destruct H as [msg1 [msg2 [sigma' [EQ [LS2' [LSmsg1 LT]]]]]]; subst.\n      destruct msg1 as [(c1,v1) j1]. apply locally_sorted_message_justification in LSmsg1.\n      constructor; assumption.\n  }\nQed.\n\nLemma locally_sorted_next_next\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg1 msg2 : message C V) sigma,\n  locally_sorted (next msg1 (next msg2 sigma)) ->\n  message_lt msg1 msg2.\nProof.\n  intros. apply locally_sorted_message_characterization in H.\n  destruct H as [H | [[msg [_ H]] | [msg1' [msg2' [sigma' [H [_ [_ Hlt]]]]]]]].\n  - exfalso. apply (no_confusion_next_empty _ _ H).\n  - apply no_confusion_next in H. destruct H as [_ H].\n    exfalso. apply (no_confusion_next_empty _ _ H).\n  - apply no_confusion_next in H. destruct H as [Heq H]; subst.\n    apply no_confusion_next in H. destruct H as [Heq H]; subst.\n    assumption.\nQed.\n\nLemma locally_sorted_remove_second\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg1 msg2 : message C V) sigma,\n  locally_sorted (next msg1 (next msg2 sigma)) ->\n  locally_sorted (next msg1 sigma).\nProof.\n  intros.\n  apply locally_sorted_message_characterization in H.\n  destruct H as [H | [[msg [_ H]] | [msg1' [msg2' [sigma' [Heq [H [Hj Hlt]]]]]]]].\n  - exfalso. apply (no_confusion_next_empty _ _ H).\n  - apply no_confusion_next in H. destruct H as [_ H].\n    exfalso. apply (no_confusion_next_empty _ _ H).\n  - apply no_confusion_next in Heq. destruct Heq as [Heq' Heq]; subst.\n    apply no_confusion_next in Heq. destruct Heq as [Heq' Heq]; subst.\n    apply locally_sorted_message_characterization in H.\n    destruct H as [H | [[msg [_ H]] | [msg2'' [msg3 [sigma'' [Heq [H [_ Hlt2]]]]]]]].\n    + exfalso. apply (no_confusion_next_empty _ _ H).\n    + apply no_confusion_next in H. destruct H; subst. apply Hj.\n    + apply no_confusion_next in Heq. destruct Heq; subst.\n      apply (compare_lt_transitive  _ _ _ Hlt) in Hlt2.\n      clear Hlt.\n      destruct msg1' as [(c1', v1') j1']. destruct msg3 as [(c3, v3) j3].\n      apply locally_sorted_message_justification in Hj.\n      apply LSorted_Next; assumption.\nQed.\n\nLemma locally_sorted_head\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma,\n  locally_sorted (next msg sigma) ->\n  locally_sorted_msg msg.\nProof.\n  intros [(c, v) j] sigma H. inversion H; subst; apply locally_sorted_message_justification; assumption.\nQed.\n\nLemma locally_sorted_tail\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma,\n  locally_sorted (next msg sigma) ->\n  locally_sorted sigma.\nProof.\n  intros.\n  apply locally_sorted_message_characterization in H.\n  destruct H as\n    [ Hcempty\n    | [[cmsg0 [LScmsg0 Hcnext]]\n    | [cmsg1 [cmsg2 [csigma' [Hcnext [LScnext [LScmsg1 LTc]]]]]]\n    ]]; subst\n    ; try (apply no_confusion_next in Hcnext; destruct Hcnext; subst)\n    .\n  - exfalso; apply (no_confusion_next_empty _ _ Hcempty).\n  - constructor.\n  - assumption.\nQed.\n\nLemma locally_sorted_all\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma : @state C V,\n  locally_sorted sigma ->\n  Forall locally_sorted_msg (get_messages sigma).\nProof.\n  intros. rewrite Forall_forall. induction H; simpl; intros msg Hin.\n  - inversion Hin.\n  - destruct Hin as [Hin | Hin] ; subst; try inversion Hin.\n    apply locally_sorted_message_justification. assumption.\n  - destruct Hin as [Heq | Hin]; subst.\n    + apply locally_sorted_message_justification. assumption.\n    + apply IHlocally_sorted2. assumption.\nQed.\n\nLemma locally_sorted_first\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma,\n  locally_sorted (next msg sigma) ->\n  forall msg',\n  in_state msg' sigma ->\n  message_lt msg msg'.\nProof.\n  intros msg sigma. generalize dependent msg. induction sigma; intros.\n  - inversion H0.\n  - rewrite (@add_is_next C V) in *. apply locally_sorted_next_next in H as H1.\n    rewrite in_state_next_iff in H0. destruct H0; subst.\n    + assumption.\n    + apply locally_sorted_remove_second in H. apply IHsigma2; assumption.\nQed.\n\nLemma sorted_syntactic_state_inclusion_first_equal\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma sigma' (msg : message C V),\n  locally_sorted (next msg sigma) ->\n  locally_sorted (next msg sigma') ->\n  syntactic_state_inclusion (next msg sigma) (next msg sigma') ->\n  syntactic_state_inclusion sigma sigma'.\nProof.\n  intros.\n  intros msg' Hin.\n  apply (locally_sorted_first msg) in Hin as Hlt; try assumption.\n  unfold syntactic_state_inclusion in H1.\n  assert (Hin' : In msg' (get_messages (next msg sigma))).\n  { rewrite get_messages_next. right. assumption. }\n  apply H1 in Hin'. rewrite get_messages_next in Hin'.\n  destruct Hin'; try assumption; subst.\n  exfalso.\n  apply (compare_lt_irreflexive _ Hlt).\nQed.\n\nLemma sorted_syntactic_state_inclusion\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma sigma' (msg msg' : message C V),\n  locally_sorted (next msg sigma) ->\n  locally_sorted (next msg' sigma') ->\n  syntactic_state_inclusion (next msg sigma) (next msg' sigma') ->\n  (msg = msg' /\\ syntactic_state_inclusion sigma sigma')\n  \\/\n  (message_lt msg' msg /\\ syntactic_state_inclusion (next msg sigma) sigma').\nProof.\n  intros. unfold syntactic_state_inclusion in H1.\n  assert (Hin : In msg (get_messages (next msg' sigma'))).\n  { apply H1. rewrite get_messages_next. left. reflexivity. }\n  rewrite get_messages_next in Hin.  simpl in Hin.\n  destruct Hin.\n  - left. subst. split; try reflexivity.\n    apply sorted_syntactic_state_inclusion_first_equal with msg; assumption.\n  - right. apply (locally_sorted_first msg') in H2 as Hlt; try assumption.\n    split; try assumption.\n    intros msg1 Hin1.\n    apply H1 in Hin1 as H1in'.\n    rewrite get_messages_next in H1in'.  simpl in H1in'.\n    rewrite get_messages_next in Hin1.  simpl in Hin1.\n    assert (Hlt1 : message_lt msg' msg1).\n    { destruct Hin1; subst; try assumption.\n      apply (locally_sorted_first msg) in H3; try assumption.\n      apply compare_lt_transitive with msg; assumption.\n    }\n    destruct H1in'; try assumption; subst.\n    exfalso. apply (compare_lt_irreflexive _ Hlt1).\nQed.\n\n\nLemma sorted_syntactic_state_inclusion_eq_ind\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma1 sigma2 (msg1 msg2 : message C V),\n  locally_sorted (next msg1 sigma1) ->\n  locally_sorted (next msg2 sigma2) ->\n  syntactic_state_inclusion (next msg1 sigma1) (next msg2 sigma2) ->\n  syntactic_state_inclusion (next msg2 sigma2) (next msg1 sigma1) ->\n  msg1 = msg2 /\\ syntactic_state_inclusion sigma1 sigma2 /\\ syntactic_state_inclusion sigma2 sigma1.\nProof.\n  intros.\n  apply sorted_syntactic_state_inclusion in H1; try assumption.\n  apply sorted_syntactic_state_inclusion in H2; try assumption.\n  destruct H1; destruct H2; destruct H1; destruct H2; subst.\n  - repeat (split; try reflexivity; try assumption).\n  - exfalso. apply (compare_lt_irreflexive _ H2).\n  - exfalso. apply (compare_lt_irreflexive _ H1).\n  - exfalso. apply (compare_lt_transitive _ _ _ H1) in H2.\n    apply (compare_lt_irreflexive _ H2).\nQed.\n\nLemma sorted_syntactic_state_inclusion_equality_predicate\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma1 sigma2 : @state C V,\n  locally_sorted sigma1 ->\n  locally_sorted sigma2 ->\n  syntactic_state_inclusion sigma1 sigma2 ->\n  syntactic_state_inclusion sigma2 sigma1 ->\n  sigma1 = sigma2.\nProof.\n  induction sigma1; intros; destruct sigma2; repeat rewrite add_is_next in *.\n  - reflexivity.\n  - unfold syntactic_state_inclusion in H2. rewrite get_messages_next in H2.\n    simpl in H2. apply incl_empty in H2. discriminate.\n  - unfold syntactic_state_inclusion in H1. rewrite get_messages_next in H1.\n    simpl in H1. apply incl_empty in H1. discriminate.\n  - apply sorted_syntactic_state_inclusion_eq_ind in H2; try assumption.\n    destruct H2 as [Heq [Hin12 Hin21]].\n    inversion Heq; subst; clear Heq.\n    apply locally_sorted_tail in H.\n    apply locally_sorted_tail in H0.\n    apply IHsigma1_2 in Hin21; try assumption.\n    subst.\n    reflexivity.\nQed.\n\n(* Constructing ordered states *)\nFixpoint add_in_sorted_fn\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  (msg: message C V) (sigma: @state C V) : @state C V\n  :=\n  match msg, sigma with\n  | _, Empty => next msg Empty\n  | msg, add (c, v, j) to sigma' =>\n    match compare msg (c, v, j) with\n    | Eq => sigma\n    | Lt => next msg sigma\n    | Gt => next (c, v, j) (add_in_sorted_fn msg sigma')\n    end\n  end.\n\nLemma set_eq_add_in_sorted\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma,\n  set_eq (get_messages (add_in_sorted_fn msg sigma)) (msg :: (get_messages sigma)).\nProof.\n  induction sigma.\n  - simpl. rewrite get_messages_next.\n    simpl. split; apply incl_refl.\n  - clear IHsigma1. simpl.\n    destruct (compare msg (c, v, sigma1)) eqn:Hcmp.\n    + simpl. apply StrictOrder_Reflexive in Hcmp. subst.\n      split; intros x H.\n      * right. assumption.\n      * destruct H; try assumption; subst. left. reflexivity.\n    + rewrite get_messages_next. simpl. split; apply incl_refl.\n    + simpl. split; intros x Hin.\n      * destruct Hin; try (right; left; assumption).\n        apply IHsigma2 in H. destruct H; try (left; assumption).\n        right; right; assumption.\n      * { destruct Hin as [Hmsg | [H1 | H2]]\n        ; (left; assumption) || (right; apply IHsigma2)\n        .\n        - left; assumption.\n        - right; assumption.\n        }\nQed.\n\nLemma add_preserves_inclusion\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  (sigma sigma' : @state C V)\n  (msg' : message C V)\n  (Hincl : syntactic_state_inclusion sigma sigma')\n  : syntactic_state_inclusion sigma (add_in_sorted_fn msg' sigma').\nProof.\n  apply incl_tran with (msg' :: get_messages sigma'); try apply set_eq_add_in_sorted.\n  apply incl_tl. assumption.\nQed.\n\nLemma in_state_add_in_sorted_iff\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg msg' : message C V) sigma',\n  in_state msg (add_in_sorted_fn msg' sigma') <->\n  msg = msg' \\/ in_state msg sigma'.\nProof.\n  intros.\n  destruct (set_eq_add_in_sorted msg' sigma') as [Hincl1 Hincl2].\n  split; intros.\n  - apply Hincl1 in H. destruct H.\n    + subst. left. reflexivity.\n    + right. assumption.\n  - apply Hincl2. destruct H; subst.\n    + left. reflexivity.\n    + right. assumption.\nQed.\n\nLemma add_in_sorted_next\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg1 msg2 : message C V) sigma,\n  add_in_sorted_fn msg1 (next msg2 sigma) =\n    match compare msg1 msg2 with\n    | Eq => next msg2 sigma\n    | Lt => next msg1 (next msg2 sigma)\n    | Gt => next msg2 (add_in_sorted_fn msg1 sigma)\n    end.\nProof.\n  intros msg1 [(c, v) j] sigma. reflexivity.\nQed.\n\nLemma add_in_sorted_non_empty\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma,\n  add_in_sorted_fn msg sigma <> Empty.\nProof.\n  intros. intro Hadd.\n  destruct sigma; inversion Hadd.\n  - apply (no_confusion_next_empty _ _ H0).\n  - destruct (compare msg (c, v, sigma1)); inversion H0.\n    apply (no_confusion_next_empty _ _ H0).\nQed.\n\nLemma add_preserves_message_membership\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) s,\n    in_state msg s ->\n    forall c v j,\n      in_state msg (add_in_sorted_fn (c,v,j) s).\nProof.\n  intros.\n  assert (H_useful := set_eq_add_in_sorted (c,v,j) s).\n  destruct H_useful as [_ H_useful].\n  spec H_useful msg; spec H_useful.\n  right; assumption.\n  assumption.\nQed.\n\nLemma add_in_sorted_inv1\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg msg' : message C V) sigma,\n  add_in_sorted_fn msg sigma = next msg' Empty -> msg = msg'.\nProof.\n  intros [(c, v) j] msg' sigma AddA.\n  destruct sigma.\n  - simpl in AddA. rewrite (@add_is_next C V) in AddA. apply no_confusion_next in AddA.\n    destruct AddA. assumption.\n  - simpl in AddA. destruct (@compare _ about_M (c, v, j) (c0, v0, sigma1)) eqn:Hcmp\n    ; rewrite add_is_next in AddA; apply no_confusion_next in AddA; destruct AddA; subst;\n    try reflexivity.\n    + apply StrictOrder_Reflexive in Hcmp; inversion Hcmp; subst; clear Hcmp.\n      reflexivity.\n    + exfalso. apply (add_in_sorted_non_empty _ _ H0).\nQed.\n\nLemma add_in_sorted_sorted\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall msg sigma,\n  locally_sorted sigma ->\n  locally_sorted_msg msg ->\n  locally_sorted (add_in_sorted_fn msg sigma).\nProof.\n  intros msg sigma. generalize dependent msg.\n  induction sigma; intros.\n  - simpl. assumption.\n  - clear IHsigma1; rename sigma1 into j; rename sigma2 into sigma; rename IHsigma2 into IHsigma.\n    simpl. destruct msg as [(mc, mv) mj].\n    apply locally_sorted_message_justification in H0 as Hmj.\n    repeat rewrite add_is_next in *.\n    apply locally_sorted_tail in H as Hsigma.\n    apply locally_sorted_head in H as Hcvj. apply locally_sorted_message_justification in Hcvj as Hj.\n    apply (IHsigma _ Hsigma) in H0 as HLSadd.\n    destruct (@compare _ about_M (mc, mv, mj) (c, v, j)) eqn:Hcmp.\n    + assumption.\n    + constructor; assumption.\n    + apply compare_asymmetric in Hcmp.\n      apply locally_sorted_message_characterization in HLSadd as Hadd.\n      destruct Hadd as [Hadd | [Hadd | Hadd]].\n      * exfalso. apply (add_in_sorted_non_empty _ _ Hadd).\n      * destruct Hadd as [msg' [Hmsg' Hadd]]. rewrite Hadd.\n        apply add_in_sorted_inv1 in Hadd; subst.\n        constructor; assumption.\n      * destruct Hadd as [msg1 [msg2 [sigma' [Hadd [HLS' [H1 Hlt12]]]]]].\n        rewrite Hadd in *. constructor; try assumption.\n        assert (Forall (message_lt (c, v, j)) (get_messages (add_in_sorted_fn (mc, mv, mj) sigma))).\n        { apply Forall_forall. intros. apply set_eq_add_in_sorted in H2.\n          destruct H2 as [Heq | Hin]; subst.\n          - unfold message_lt. unfold compare_lt. unfold Lib.Preamble.compare. assumption.\n          - apply locally_sorted_first with sigma; unfold in_state; assumption.\n        }\n        unfold add_in_sorted_fn in H2.\n        unfold add_in_sorted_fn in Hadd.\n        rewrite Hadd in H2. rewrite get_messages_next in H2. apply Forall_inv in H2. assumption.\nQed.\n\n(* Constructing an ordered state from messages *)\nDefinition list_to_state\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  (msgs : list (message C V)) : state :=\n  fold_right add_in_sorted_fn Empty msgs.\n\nLemma list_to_state_locally_sorted\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall msgs : list (message C V),\n  Forall locally_sorted_msg msgs ->\n  locally_sorted (list_to_state msgs).\nProof.\n  induction msgs; simpl; try constructor; intros.\n  apply add_in_sorted_sorted.\n  - apply IHmsgs. apply Forall_forall. intros msg Hin.\n    rewrite Forall_forall in H. apply H. right. assumption.\n  - apply Forall_inv with msgs. assumption.\nQed.\n\nLemma list_to_state_iff\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall msgs : list (message C V),\n  set_eq (get_messages (list_to_state msgs)) msgs.\nProof.\n  induction msgs; intros.\n  - simpl. split; apply incl_refl.\n  - simpl. apply set_eq_tran with (a :: (get_messages (list_to_state msgs))).\n    + apply set_eq_add_in_sorted.\n    + apply set_eq_cons. assumption.\nQed.\n\nLemma list_to_state_sorted\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma : @state C V,\n  locally_sorted sigma ->\n  list_to_state (get_messages sigma) = sigma.\nProof.\n  intros. induction H; try reflexivity.\n  rewrite get_messages_next. simpl. rewrite IHlocally_sorted2.\n  rewrite add_in_sorted_next. rewrite H0. reflexivity.\nQed.\n\n(* Defining state_union *)\nDefinition messages_union\n  {C V}\n  (m1 m2 : list (message C V))\n  :=\n  m1 ++ m2.\n\nDefinition state_union\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  (sigma1 sigma2 : @state C V) : state\n  :=\n  (list_to_state (messages_union (get_messages sigma1) (get_messages sigma2))).\n\nLemma add_in_sorted_ignore_repeat\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall msg (c : C) (v : V) j,\n    msg = (c, v, j) ->\n    forall s,\n      add_in_sorted_fn msg (add (c,v,j) to s) =\n      add (c,v,j) to s.\nProof.\n  intros.\n  simpl.\n  replace (compare msg (c,v,j)) with Eq.\n  reflexivity. subst. rewrite compare_eq_refl.\n  reflexivity.\nQed.\n\nLemma add_in_sorted_swap_base\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall x y : message C V,\n    add_in_sorted_fn y (add_in_sorted_fn x Empty) =\n    add_in_sorted_fn x (add_in_sorted_fn y Empty).\nProof.\n  intros x y.\n  destruct x; destruct p.\n  destruct y; destruct p.\n  simpl.\n  case_pair about_M (c0,v0,s0) (c,v,s).\n  - rewrite H_eq1, H_eq2.\n    apply compare_eq in H_eq2.\n    inversion H_eq2; subst. reflexivity.\n  - rewrite H_lt, H_gt. reflexivity.\n  - rewrite H_gt, H_lt. reflexivity.\nQed.\n\nLemma add_in_sorted_swap_succ\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (x y : message C V) s,\n    add_in_sorted_fn y (add_in_sorted_fn x s) =\n    add_in_sorted_fn x (add_in_sorted_fn y s).\nProof.\n  intros x y; induction s as [|c v j IHj prev IHs].\n  - apply add_in_sorted_swap_base.\n  - simpl.\n    destruct (@compare _ about_M x (c,v,j)) eqn:H_x.\n    apply compare_eq in H_x.\n    destruct (@compare _ about_M y (c,v,j)) eqn:H_y.\n    apply compare_eq in H_y. subst; reflexivity.\n    rewrite add_in_sorted_next.\n    assert (H_y_copy := H_y).\n    rewrite <- H_x in H_y.\n    apply compare_asymmetric in H_y. rewrite H_y.\n    simpl. rewrite H_y_copy.\n    rewrite H_x. rewrite compare_eq_refl. reflexivity.\n    simpl. rewrite H_y. rewrite H_x; rewrite compare_eq_refl; simpl; reflexivity.\n    destruct (@compare _ about_M y (c,v,j)) eqn:H_y.\n    simpl. rewrite H_x.\n    apply compare_eq in H_y. subst.\n    rewrite add_is_next.\n    rewrite add_in_sorted_next.\n    apply compare_asymmetric in H_x.\n    rewrite H_x. simpl. rewrite compare_eq_refl.\n    reflexivity. rewrite add_in_sorted_next.\n    destruct (@compare _ about_M y x) eqn:H_yx.\n    apply compare_eq in H_yx. subst.\n    rewrite add_in_sorted_next. rewrite compare_eq_refl.\n    reflexivity.\n    rewrite add_in_sorted_next.\n    apply compare_asymmetric in H_yx. rewrite H_yx.\n    simpl. rewrite H_x. reflexivity.\n    rewrite add_in_sorted_next.\n    apply compare_asymmetric in H_yx. rewrite H_yx.\n    simpl. rewrite H_y. reflexivity.\n    simpl. rewrite H_x.\n    rewrite add_in_sorted_next.\n     destruct (@compare _ about_M y x) eqn:H_yx.\n    apply compare_eq in H_yx. subst.\n    simpl. rewrite H_x in H_y; inversion H_y.\n    assert (@compare _ about_M y (c,v,j) = Lt). eapply StrictOrder_Transitive. exact H_yx. exact H_x. rewrite H_y in H; inversion H. simpl. rewrite H_y. reflexivity.\n    simpl.\n    destruct (@compare _ about_M y (c,v,j)) eqn:H_y.\n    apply compare_eq in H_y. subst. simpl. rewrite H_x.\n    reflexivity. rewrite add_in_sorted_next.\n    destruct (@compare _ about_M x y) eqn:H_xy.\n    apply compare_eq in H_xy. subst.\n    simpl. rewrite H_x in H_y; inversion H_y.\n    assert (@compare _ about_M x (c,v,j) = Lt).\n    eapply StrictOrder_Transitive. apply H_xy. assumption.\n    rewrite H_x in H; inversion H. simpl. rewrite H_x.\n    reflexivity. simpl.\n    rewrite H_x.\n    (* Finally, the induction hypothesis is used *)\n    rewrite IHs. reflexivity.\nQed.\n\nTactic Notation \"next\" :=\n  try rewrite add_is_next, add_in_sorted_next; simpl.\n\n(* The following is from adequacy's sort.v *)\nInductive add_in_sorted\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : @message C V -> state -> state -> Prop :=\n   | add_in_Empty : forall msg,\n          add_in_sorted msg Empty (next msg Empty)\n   | add_in_Next_eq : forall msg sigma,\n          add_in_sorted msg (next msg sigma) (next msg sigma)\n   | add_in_Next_lt : forall msg msg' sigma,\n          message_lt msg msg' ->\n          add_in_sorted msg (next msg' sigma) (next msg (next msg' sigma))\n   | add_in_Next_gt : forall msg msg' sigma sigma',\n          message_lt msg' msg ->\n          add_in_sorted msg sigma sigma' ->\n          add_in_sorted msg (next msg' sigma) (next msg' sigma').\n\nLemma add_in_empty\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma,\n  add_in_sorted msg Empty sigma -> sigma = (next msg Empty).\nProof.\n  intros [(c, v) j] sigma AddA.\n  inversion AddA as\n    [ [(ca, va) ja] A AEmpty C'\n    | [(ca, va) ja] sigmaA A ANext C'\n    | [(ca, va) ja] [(ca', va') ja'] sigmaA LTA smsg smsg' smsg1\n    | [(ca, va) ja] [(ca', va') ja'] sigmaA sigmaA' LTA AddA' A B C]\n  ; clear AddA.\n  subst. reflexivity.\nQed.\n\nLemma add_in_sorted_correct\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) s1 s2, add_in_sorted msg s1 s2 <-> add_in_sorted_fn msg s1 = s2.\nProof.\n  intros msg sigma1 sigma2; generalize dependent sigma2.\n  induction sigma1; intros; split; intros.\n  - apply add_in_empty in H. subst. reflexivity.\n  - simpl in H. subst. constructor.\n  - inversion H; subst; rewrite (@add_is_next C V) in *.\n    + apply no_confusion_next in H2; destruct H2; subst; simpl.\n      rewrite compare_eq_refl. reflexivity.\n    + apply no_confusion_next in H0; destruct H0; subst; simpl.\n      unfold message_lt in H2. unfold compare_lt in H2. rewrite H2. reflexivity.\n    + apply no_confusion_next in H0; destruct H0; subst; simpl.\n      unfold message_lt in H1. unfold compare_lt in H1.\n      apply compare_asymmetric in H1. rewrite H1.\n      apply IHsigma1_2 in H3. rewrite H3. reflexivity.\n  - simpl in H. destruct (@compare _ about_M msg (c, v, sigma1_1)) eqn:Hcmp; subst; repeat rewrite add_is_next.\n    + apply StrictOrder_Reflexive in Hcmp; subst.\n      apply add_in_Next_eq.\n    + apply add_in_Next_lt. assumption.\n    + apply add_in_Next_gt.\n      * apply compare_asymmetric in Hcmp. assumption.\n      * apply IHsigma1_2. reflexivity.\nQed.\n\nLemma add_in_sorted_sorted'\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma sigma',\n  locally_sorted sigma ->\n  locally_sorted_msg msg ->\n  add_in_sorted msg sigma sigma' ->\n  locally_sorted sigma'.\nProof.\n  intros. apply add_in_sorted_correct in H1; subst.\n  apply add_in_sorted_sorted; assumption.\nQed.\n\nLemma no_confusion_add_in_sorted_empty\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma,\n  ~ add_in_sorted msg sigma Empty.\nProof.\n  intros. intro.\n  apply add_in_sorted_correct in H.\n  destruct sigma.\n  - simpl in H. apply (no_confusion_next_empty _ _ H).\n  - simpl in H.\n    destruct (@compare _ about_M msg (c, v, sigma1))\n    ; rewrite (@add_is_next C V) in *\n    ; apply (no_confusion_next_empty _ _ H)\n    .\nQed.\n\nLemma add_in_sorted_functional\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma1 sigma2 sigma2',\n  add_in_sorted msg sigma1 sigma2 ->\n  add_in_sorted msg sigma1 sigma2' ->\n  sigma2 = sigma2'.\nProof.\n  intros; f_equal.\n  apply add_in_sorted_correct in H.\n  apply add_in_sorted_correct in H0.\n  subst. reflexivity.\nQed.\n\nLemma add_in_sorted_message_preservation\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma sigma',\n  add_in_sorted msg sigma sigma' ->\n  in_state msg sigma'.\nProof.\n  intros. unfold in_state.\n  induction H; rewrite get_messages_next; simpl; try (left; reflexivity).\n  right. assumption.\nQed.\n\nLemma add_in_sorted_no_junk\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma sigma',\n  add_in_sorted msg sigma sigma' ->\n  forall msg', in_state msg' sigma' -> msg' = msg \\/ in_state msg' sigma.\nProof.\n  intros msg sigma sigma' H.\n  induction H as\n  [ [(hc, hv) hj]\n  | [(hc, hv) hj] Hsigma\n  | [(hc, hv) hj] [(hc', hv') hj'] Hsigma HLT\n  | [(hc, hv) hj] [(hc', hv') hj'] Hsigma Hsigma' HGT HAdd H_H\n  ]; intros [(c', v') j'] HIn; rewrite in_state_next_iff in HIn\n  ; destruct HIn as [Hin1 | Hin2]\n  ; try (right; assumption)\n  ; try (inversion Hin1; subst; left; reflexivity)\n  .\n  - right. apply in_state_next_iff. right. assumption.\n  - right. apply in_state_next_iff. inversion Hin1; clear Hin1; subst. left. reflexivity.\n  - apply H_H in Hin2. destruct Hin2 as [HInEq | HIn'].\n    + left. assumption.\n    + right. apply in_state_next_iff. right. assumption.\nQed.\n\nLemma add_sorted\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma (msg : message C V),\n  locally_sorted sigma ->\n  in_state msg sigma ->\n  add_in_sorted msg sigma sigma.\nProof.\n  induction sigma; intros; repeat rewrite add_is_next in *.\n  - exfalso. apply (in_empty_state _ H0).\n  - rewrite in_state_next_iff in H0. destruct H0.\n    + subst. constructor.\n    + apply (locally_sorted_first (c, v, sigma1)) in H0 as Hlt; try assumption.\n      apply locally_sorted_tail in H.\n      apply IHsigma2 in H0; try assumption.\n      constructor; assumption.\nQed.\n(* End from adequacy, sort.v *)\n\nLemma add_in_sorted_ignore\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) (s : state),\n    locally_sorted s ->\n    in_state msg s ->\n    add_in_sorted_fn msg s = s.\nProof.\n  intros.\n  apply add_in_sorted_correct.\n  apply add_sorted.\n  destruct s; assumption.\n  assumption.\nQed.\n\nLemma add_in_sorted_fn_in\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (m : message C V) s,\n    add_in_sorted_fn m (next m s) = next m s.\nProof.\n  intros. destruct m as [(c, v) j].\n  simpl. rewrite compare_eq_refl. reflexivity.\nQed.\n\nFixpoint sort_state\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  (s : @state C V)\n  : @state C V\n  :=\n  match s with\n  | Empty => Empty\n  | Next C V j s => add_in_sorted_fn (C, V, sort_state j) (sort_state s)\n  end.\n\nLemma sort_state_locally_sorted\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  (s : @state C V)\n  : locally_sorted (sort_state s).\nProof.\n  induction s; try constructor. simpl.\n  apply add_in_sorted_sorted; try assumption.\n  constructor. assumption.\nQed.\n\nLemma sort_state_idempotent\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  (s : @state C V)\n  (Hs : locally_sorted s)\n  : sort_state s = s.\nProof.\n  induction Hs; try reflexivity.\n  - simpl. rewrite IHHs. reflexivity.\n  - simpl. rewrite IHHs1. rewrite IHHs2.\n    rewrite add_in_sorted_next.\n    rewrite H.\n    reflexivity.\nQed.\n\nLemma state_union_comm_swap\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (x y : message C V) s,\n    add_in_sorted_fn y (add_in_sorted_fn x s) =\n    add_in_sorted_fn x (add_in_sorted_fn y s).\nProof.\n  intros.\n  induction s.\n  - apply add_in_sorted_swap_base.\n  - apply add_in_sorted_swap_succ.\nQed.\n\nLemma state_union_comm_helper_helper\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (l1 l2 : list (message C V)),\n    Permutation l1 l2 ->\n    list_to_state l1 = list_to_state l2.\nProof.\n  intros.\n  induction H.\n  - reflexivity.\n  - simpl. rewrite IHPermutation.\n    reflexivity.\n  - simpl.\n    apply state_union_comm_swap.\n  - rewrite IHPermutation1, IHPermutation2.\n    reflexivity.\nQed.\n\nLemma state_union_messages\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma1 sigma2 : @state C V,\n  set_eq (get_messages (state_union sigma1 sigma2)) (messages_union (get_messages sigma1) (get_messages sigma2)).\nProof.\n  intros.\n  apply list_to_state_iff.\nQed.\n\nLemma state_union_incl_right\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma1 sigma2 : @state C V,\n  syntactic_state_inclusion sigma2 (state_union sigma1 sigma2).\nProof.\n  intros. intros msg Hin. apply state_union_messages.\n  unfold messages_union; apply in_app_iff; right; assumption.\nQed.\n\nLemma state_union_incl_left\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma1 sigma2 : @state C V,\n  syntactic_state_inclusion sigma1 (state_union sigma1 sigma2).\nProof.\n  intros. intros msg Hin. apply state_union_messages.\n  unfold messages_union; apply in_app_iff; left; assumption.\nQed.\n\nLemma state_union_iff\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma1 sigma2,\n  in_state msg (state_union sigma1 sigma2) <-> in_state msg sigma1 \\/ in_state msg sigma2.\nProof.\n  intros; unfold state_union; unfold in_state; split; intros.\n  - apply state_union_messages in H. unfold messages_union in H.\n    apply in_app_iff; assumption.\n  - apply state_union_messages. unfold messages_union.\n    rewrite in_app_iff; assumption.\nQed.\n\nLemma state_union_incl_iterated\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigmas (sigma : @state C V),\n  In sigma sigmas ->\n  syntactic_state_inclusion sigma (fold_right state_union Empty sigmas).\nProof.\n  induction sigmas; intros.\n  - inversion H.\n  - simpl. destruct H.\n    + subst. apply state_union_incl_left.\n    + apply IHsigmas in H. apply incl_tran with (get_messages (fold_right state_union Empty sigmas)); try assumption.\n      apply state_union_incl_right.\nQed.\n\nLemma state_union_sorted\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma1 sigma2 : @state C V,\n  locally_sorted sigma1 ->\n  locally_sorted sigma2 ->\n  locally_sorted (state_union sigma1 sigma2).\nProof.\n  intros.\n  apply locally_sorted_all in H as Hall1. rewrite Forall_forall in Hall1.\n  apply locally_sorted_all in H0 as Hall2. rewrite Forall_forall in Hall2.\n  apply list_to_state_locally_sorted. apply Forall_forall. intros msg Hin.\n  unfold messages_union in Hin.\n  rewrite in_app_iff in Hin. destruct Hin.\n  - apply Hall1. assumption.\n  - apply Hall2. assumption.\nQed.\n\nLemma state_union_add_in_sorted\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma1 (msg2 : message C V) sigma2,\n  locally_sorted sigma1 ->\n  locally_sorted sigma2 ->\n  locally_sorted_msg msg2 ->\n  state_union sigma1 (add_in_sorted_fn msg2 sigma2) = add_in_sorted_fn msg2 (state_union sigma1 sigma2).\nProof.\n  intros.\n  apply sorted_syntactic_state_inclusion_equality_predicate.\n  - apply state_union_sorted; try assumption.\n    apply add_in_sorted_sorted; assumption.\n  - apply add_in_sorted_sorted; try assumption.\n    apply state_union_sorted; assumption.\n  - intros msg Hin.\n    apply state_union_iff in Hin.\n    apply set_eq_add_in_sorted.\n    destruct Hin as [Hin | Hin].\n    + right. apply state_union_iff. left; assumption.\n    + apply set_eq_add_in_sorted in Hin. destruct Hin as [Heq | Hin]; subst.\n      * left; reflexivity.\n      * right.  apply state_union_iff. right; assumption.\n  - intros msg Hin.\n    apply set_eq_add_in_sorted in Hin.\n    apply state_union_iff.\n    destruct Hin as [Heq | Hin]; subst.\n    + right. apply set_eq_add_in_sorted. left; reflexivity.\n    + apply state_union_iff in Hin.\n      destruct Hin.\n      * left; assumption.\n      * right. apply set_eq_add_in_sorted.\n      right; assumption.\nQed.\n\nDefinition compare_strict_order_v\n  {C V} (HscM : StrictlyComparable (message C V))\n  : CompareStrictOrder (@triple_strictly_comparable_proj2_compare _ _ _ HscM)\n  := @compare_strictorder _ (triple_strictly_comparable_proj2 HscM).\n\nDefinition compare_eq_dec_v\n  {C V} (HscM : StrictlyComparable (message C V))\n  : forall x y : V, {x = y} + {x <> y}\n  :=\n  @compare_eq_dec _ _ (compare_strict_order_v HscM).\n\n(* Defining message equivocation, computationally and propositionally *)\nDefinition equivocating_messages\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  (msg1 msg2 : message C V) : bool :=\n  match compare_eq_dec msg1 msg2 with\n  | left _ => false\n  | _ => match msg1, msg2 with (c1, v1, j1), (c2, v2, j2) =>\n      match compare_eq_dec_v about_M v1 v2 with\n      | left _ => negb (in_state_fn msg1 j2) && negb (in_state_fn msg2 j1)\n      | right _ => false\n      end\n    end\n  end.\n\nDefinition equivocating_messages_prop\n  {C V}\n  (msg1 msg2 : message C V) : Prop\n  :=\n  msg1 <> msg2 /\\ sender msg1 = sender msg2 /\\ ~ in_state msg1 (justification msg2) /\\ ~ in_state msg2 (justification msg1).\n\nLemma equivocating_messages_sender\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall msg1 msg2 : message C V,\n  equivocating_messages msg1 msg2 = true -> sender msg1 = sender msg2.\nProof.\n  unfold equivocating_messages.\n  intros [(c1, v1) j1] [(c2, v2) j2] H.\n  simpl.\n  destruct (compare_eq_dec (c1, v1, j1) (c2, v2, j2)).\n  rewrite eq_dec_if_true in H.\n  inversion H.\n  assumption.\n  rewrite eq_dec_if_false in H.\n  destruct (compare_eq_dec_v about_M v1 v2).\n  assumption. inversion H. assumption.\nQed.\n\nLemma equivocating_messages_correct\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg1 msg2 : message C V),\n    equivocating_messages msg1 msg2 = true <-> equivocating_messages_prop msg1 msg2.\nProof.\n  intros [[c1 v1] j1] [[c2 v2] j2]; split; intro H.\n  - repeat split.\n    + (* Proving inequality obligation *)\n      intro H_absurd.\n      unfold equivocating_messages in H.\n      rewrite eq_dec_if_true in H.\n      inversion H. assumption.\n    + (* Proving sender obligation *)\n      now apply equivocating_messages_sender.\n    + (* Proving msg1 is not in msg2's justification *)\n      intro H_absurd.\n      apply in_state_correct in H_absurd.\n      unfold equivocating_messages in H.\n      simpl in H_absurd. rewrite H_absurd in H.\n      destruct (compare_eq_dec (c1,v1,j1) (c2,v2,j2)).\n      rewrite eq_dec_if_true in H. inversion H.\n      assumption. rewrite eq_dec_if_false in H.\n      destruct (compare_eq_dec_v about_M v1 v2).\n      simpl in H. inversion H.\n      inversion H. assumption.\n    + (* Proving msg2 is not in msg1's justification *)\n      intro H_absurd. apply in_state_correct in H_absurd.\n      unfold equivocating_messages in H.\n      simpl in H_absurd. rewrite H_absurd in H.\n      destruct (compare_eq_dec (c1,v1,j1) (c2,v2,j2)).\n      rewrite eq_dec_if_true in H. inversion H.\n      assumption. rewrite eq_dec_if_false in H.\n      destruct (compare_eq_dec_v about_M v1 v2).\n      rewrite andb_false_r in H. inversion H.\n      inversion H. assumption.\n  - destruct H as [H_neq [H_sender [H_in1 H_in2]]].\n    apply in_state_correct' in H_in1.\n    apply in_state_correct' in H_in2.\n    simpl in H_sender.\n    unfold equivocating_messages.\n    destruct (compare_eq_dec (c1,v1,j1) (c2,v2,j2)).\n    contradiction.\n    rewrite eq_dec_if_false.\n    destruct (compare_eq_dec_v about_M v1 v2).\n    simpl in H_in1. simpl in H_in2.\n    rewrite H_in1. rewrite H_in2.\n    tauto. contradiction. assumption.\nQed.\n\nLemma equivocating_messages_comm\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall msg1 msg2 : message C V,\n  equivocating_messages msg1 msg2 = equivocating_messages msg2 msg1.\nProof.\n  intros [(c1, v1) sigma1] [(c2, v2) sigma2].\n  unfold equivocating_messages.\n  destruct (compare_eq_dec (c1, v1, sigma1) (c2, v2, sigma2)).\n  subst. rewrite eq_dec_if_true.\n  rewrite eq_dec_if_true. reflexivity.\n  symmetry; assumption.\n  assumption.\n  rewrite (eq_dec_if_false compare_eq_dec).\n  destruct (compare_eq_dec_v about_M v1 v2).\n  rewrite eq_dec_if_false.\n  rewrite e. rewrite eq_dec_if_true.\n  rewrite andb_comm. reflexivity. reflexivity.\n  intro Hnot; symmetry in Hnot; tauto.\n  rewrite eq_dec_if_false.\n  rewrite eq_dec_if_false. reflexivity.\n  intro Hnot; symmetry in Hnot; tauto.\n  intro Hnot; symmetry in Hnot; tauto.\n  assumption.\nQed.\n\nLemma equivocating_messages_prop_swap\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall msg1 msg2 : message C V,\n    equivocating_messages_prop msg1 msg2 <-> equivocating_messages_prop msg2 msg1.\nProof.\n  intros; rewrite <- equivocating_messages_correct.\n  rewrite <- equivocating_messages_correct.\n  rewrite equivocating_messages_comm.\n  tauto.\nQed.\n\n(* The intuition is we can never satisfy that neither messages are contained in each other's justifications. *)\nLemma non_equivocating_messages_extend\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall msg sigma1 (c : C) (v : V),\n  In msg (get_messages sigma1) ->\n  equivocating_messages msg (c, v, sigma1) = false.\nProof.\n  intros [(c0, v0) sigma']; intros.\n  unfold equivocating_messages.\n  destruct (compare_eq_dec (c0, v0, sigma') (c, v, sigma1)).\n  - (* In the case that these two messages are equal, they cannot be equivocating *)\n    now rewrite eq_dec_if_true.\n  - (* In the case that these messages are not equal, *)\n    rewrite eq_dec_if_false.\n    (* When their senders are equal *)\n    destruct (compare_eq_dec_v about_M v0 v).\n    + subst. apply in_state_correct in H.\n      rewrite H. tauto.\n    + reflexivity.\n    + assumption.\nQed.\n\nLemma non_equivocating_messages_sender\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall msg1 msg2 : message C V,\n  sender msg1 <> sender msg2 ->\n  equivocating_messages msg1 msg2 = false.\nProof.\n  intros [(c1, v1) j1] [(c2, v2) j2] Hneq. simpl in Hneq.\n  unfold equivocating_messages.\n  rewrite eq_dec_if_false.\n  - rewrite eq_dec_if_false; try reflexivity. assumption.\n  - intro Heq. inversion Heq; subst; clear Heq. apply Hneq. reflexivity.\nQed.\n\nDefinition equivocating_in_state\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  (msg : message C V) (sigma : state) : bool :=\n  existsb (equivocating_messages msg) (get_messages sigma).\n\nDefinition equivocating_in_state_prop\n  {C V}\n  (msg : message C V) (s : state) : Prop\n  :=\n  exists msg', in_state msg' s /\\ equivocating_messages_prop msg msg'.\n\nLemma equivocating_in_state_correct\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) s,\n  equivocating_in_state msg s = true <-> equivocating_in_state_prop msg s.\nProof.\n  intros msg s.\n  split; intro H.\n  - unfold equivocating_in_state in H.\n    rewrite existsb_exists in H.\n    destruct H as [msg' [H_in H_equiv]].\n    exists msg'. split. assumption. rewrite <- equivocating_messages_correct. assumption.\n  - destruct H as [msg' [H_in H_equiv]].\n    apply existsb_exists.\n    exists msg'; split. assumption.\n    rewrite equivocating_messages_correct. assumption.\nQed.\n\nLemma equivocating_in_state_correct'\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) s,\n  equivocating_in_state msg s = false <-> ~ equivocating_in_state_prop msg s.\nProof.\n  intros.\n  apply mirror_reflect_curry.\n  exact equivocating_in_state_correct.\nQed.\n\nLemma equivocating_in_state_incl\n  {C V}\n  : forall sigma sigma' : @state C V,\n  syntactic_state_inclusion sigma sigma' ->\n  forall msg,\n    equivocating_in_state_prop msg sigma ->\n    equivocating_in_state_prop msg sigma'.\nProof.\n  intros. destruct H0 as [x [Hin Heq]]. exists x.\n  split; try assumption.\n  apply H. assumption.\nQed.\n\nLemma equivocating_in_state_not_seen\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma,\n  ~ In (sender msg) (set_map (compare_eq_dec_v about_M) sender (get_messages sigma)) ->\n  ~ equivocating_in_state_prop msg sigma.\nProof.\n  intros [(c, v) j] sigma Hnin.\n  rewrite (@set_map_exists _ _ (compare_eq_dec_v about_M)) in Hnin.\n  simpl in Hnin.\n  rewrite <- equivocating_in_state_correct'.\n  apply existsb_forall.\n  intros [(cx, vx) jx] Hin.\n  apply non_equivocating_messages_sender. simpl.\n  intro Heq. subst. apply Hnin.\n  exists (cx, vx, jx). split; try assumption. reflexivity.\nQed.\n\nDefinition equivocating_senders\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  (sigma : state) : set V\n  :=\n  set_map (compare_eq_dec_v about_M) sender\n    (filter (fun msg => equivocating_in_state msg sigma)\n      (get_messages sigma)).\n\nDefinition equivocating_senders_prop\n  {C V}\n  (s : @state C V) (lv : set V)\n  :=\n  forall v, In v lv <-> exists msg, in_state msg s /\\ sender msg = v /\\ equivocating_in_state_prop msg s.\n\nLemma equivocating_senders_correct\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall s : @state C V,\n  equivocating_senders_prop s (equivocating_senders s).\nProof.\n  intros s v; split; intro H.\n  - (* Left direction *)\n    apply set_map_exists in H.\n    destruct H as [msg [H_in H_sender]].\n    exists msg.\n    apply filter_In in H_in.\n    destruct H_in. repeat split; try assumption.\n    rewrite <- equivocating_in_state_correct.\n    assumption.\n  - destruct H as [msg [H_in [H_sender H_equiv]]].\n    unfold equivocating_senders.\n    rewrite <- H_sender.\n    apply set_map_in.\n    rewrite filter_In. split.\n    assumption. rewrite equivocating_in_state_correct.\n    assumption.\nQed.\n\nLemma equivocating_senders_incl\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma sigma' : @state C V,\n  syntactic_state_inclusion sigma sigma' ->\n  incl (equivocating_senders sigma) (equivocating_senders sigma').\nProof.\n  intros.\n  apply set_map_incl.\n  apply incl_tran with (filter (fun msg : message C V => equivocating_in_state msg sigma) (get_messages sigma')).\n  - apply filter_incl; assumption.\n  - intros v H_in.\n    rewrite filter_In in *.\n    destruct H_in. split. assumption.\n    rewrite equivocating_in_state_correct in *.\n    now apply equivocating_in_state_incl with sigma.\nQed.\n\nLemma equivocating_senders_extend\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma (c : C) (v : V),\n  equivocating_senders (add (c, v, sigma) to sigma) = equivocating_senders sigma.\nProof.\n  unfold equivocating_senders. intros.\n  (* Why doesn't the suff tactic work *)\n  assert (H_suff :\n    (filter (fun msg : message C V => equivocating_in_state msg (add (c, v, sigma)to sigma))\n      (get_messages (add (c, v, sigma)to sigma))) =\n    (filter (fun msg : message C V => equivocating_in_state msg sigma)\n      (get_messages sigma))); try (rewrite H_suff; reflexivity).\n  simpl.\n  assert\n    (Hequiv : equivocating_in_state (c, v, sigma) (add (c, v, sigma) to sigma) = false)\n  ; try rewrite Hequiv.\n  { apply existsb_forall. intros.\n    rewrite equivocating_messages_comm.\n    destruct H as [Heq | Hin].\n    - subst. unfold equivocating_messages.\n      rewrite eq_dec_if_true; reflexivity.\n    - apply non_equivocating_messages_extend. assumption.\n  }\n  apply filter_eq_fn. intros. unfold equivocating_in_state. split; intros\n  ; apply existsb_exists in H0; apply existsb_exists\n  ; destruct H0 as [msg [Hin Hmsg]]; exists msg; split; try assumption.\n  - simpl in Hin.\n    destruct Hin as [Heq | Hin]; try assumption.\n    exfalso. subst.\n    apply (non_equivocating_messages_extend _ _ c v) in H.\n    rewrite Hmsg in H. inversion H.\n  - right. assumption.\nQed.\n\nLemma equivocating_senders_unseen\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall sigma (c : C) (v : V) j,\n  ~ In v (set_map (compare_eq_dec_v about_M) sender (get_messages sigma)) ->\n  set_eq (equivocating_senders (add_in_sorted_fn (c, v, j) sigma)) (equivocating_senders sigma).\nProof.\n  intros.\n  unfold equivocating_senders. intros.\n  split; intros v' Hin\n  ; apply set_map_exists; apply set_map_exists in Hin\n  ; destruct Hin as [[(cx, vx) jx] [Hin Heq]]\n  ; simpl in Heq; subst\n  ; exists (cx, v', jx)\n  ; simpl; split; try reflexivity\n  ; apply filter_In; apply filter_In in Hin\n  ; destruct Hin as [Hin HEquiv]\n  ; unfold equivocating_in_state in HEquiv\n  ; apply existsb_exists in HEquiv\n  ; destruct HEquiv as [[(cy, vy) jy] [Hiny HEquiv]]\n  .\n  - apply in_state_add_in_sorted_iff in Hiny. apply in_state_add_in_sorted_iff in Hin.\n    destruct Hin.\n    + exfalso. inversion H0; subst; clear H0.\n      assert (Hnequiv : equivocating_messages (c, v, j) (cy, vy, jy) = false)\n      ;try (rewrite Hnequiv  in HEquiv; inversion HEquiv); clear HEquiv.\n      destruct Hiny.\n      * rewrite H0. unfold equivocating_messages. rewrite eq_dec_if_true; reflexivity.\n      * apply non_equivocating_messages_sender. simpl. intro; subst. apply H.\n        apply set_map_exists. exists (cy, vy, jy). split; try reflexivity; assumption.\n    + split; try assumption. unfold equivocating_in_state.\n      apply existsb_exists. exists (cy, vy, jy).\n      destruct Hiny.\n      * exfalso. inversion H1; subst; clear H1. apply H.\n        apply set_map_exists. exists (cx, v', jx). split; try assumption. simpl.\n        apply equivocating_messages_sender in HEquiv. simpl in HEquiv. assumption.\n      * split; assumption.\n  -  split.\n    + apply in_state_add_in_sorted_iff. right. assumption.\n    + unfold equivocating_in_state. apply existsb_exists.\n      exists (cy, vy, jy). split; try assumption.\n      apply in_state_add_in_sorted_iff. right. assumption.\nQed.\n\n(* Lifting parameterization from set V to states *)\nDefinition fault_weight_state\n  {C V} `{about_M : StrictlyComparable (message C V)} `{Measurable V}\n  (sigma : @state C V) : R\n  :=\n  sum_weights (equivocating_senders sigma).\n\nLemma fault_weight_state_incl\n  {C V} `{about_M : StrictlyComparable (message C V)} `{Measurable V}\n  : forall sigma sigma' : @state C V,\n  syntactic_state_inclusion sigma sigma' ->\n  (fault_weight_state sigma <= fault_weight_state sigma')%R.\nProof.\n  intros. apply @sum_weights_incl; try apply set_map_nodup.\n  - specialize (triple_strictly_comparable_proj2 about_M); intro Scv.\n    intros x y.\n    apply compare_eq_dec.\n  - apply equivocating_senders_incl. assumption.\nQed.\n\n(* Justification subset condition *)\nDefinition incl_messages\n  {C V}\n  (s1 s2 : @state C V) : Prop\n  :=\n  incl (get_messages s1) (get_messages s2).\n\n(* The not overweight condition *)\nDefinition not_heavy\n  {C V} `{about_M : StrictlyComparable (message C V)} `{ReachableThreshold V}\n  (sigma : @state C V) : Prop\n  :=\n  (fault_weight_state sigma <= proj1_sig threshold)%R.\n\n(* States following Empty states are never overweight *)\nLemma not_heavy_single\n  {C V} `{about_M : StrictlyComparable (message C V)} `{ReachableThreshold V}\n  : forall msg : message C V,\n  not_heavy (next msg Empty).\nProof.\n  intros [(c, v) j].\n  unfold not_heavy, fault_weight_state, equivocating_senders.\n  simpl. unfold equivocating_in_state. simpl.\n  unfold equivocating_messages.\n  rewrite eq_dec_if_true; try reflexivity. simpl.\n  apply Rge_le. destruct threshold.\n  simpl; auto.\nQed.\n\n(* If a state is not overweight, none of its subsets are *)\nLemma not_heavy_subset\n  {C V} `{about_M : StrictlyComparable (message C V)} `{ReachableThreshold V}\n  : forall s s' : @state C V,\n  syntactic_state_inclusion s s' ->\n  not_heavy s' ->\n  not_heavy s.\nProof.\n  red.\n  intros.\n  apply Rle_trans with (fault_weight_state s'); try assumption.\n  apply fault_weight_state_incl; assumption.\nQed.\n\nClass ProtocolState C V `{about_M : StrictlyComparable (message C V)} `{Hrt : ReachableThreshold V} `{He : Estimator (@state C V) C}.\n\n(* Valid protocol state definition *)\nInductive protocol_state\n  {C V} `{PS : ProtocolState C V}\n  : @state C V -> Prop\n  :=\n  | protocol_state_empty : protocol_state Empty\n  | protocol_state_next : forall s j, protocol_state s ->\n                                  protocol_state j ->\n                                  incl_messages j s ->\n                                  forall c v,\n                                    valid_estimate c j ->\n                                    not_heavy (add_in_sorted_fn (c,v,j) s) ->\n                                    protocol_state (add_in_sorted_fn (c,v,j) s).\n\nLemma nil_empty_state\n  {C V}\n  : forall s : @state C V, get_messages s = [] -> s = Empty.\nProof.\n  intros s H_nil.\n  induction s. reflexivity.\n  inversion H_nil.\nQed.\n\n(** Facts about protocol states as traces **)\n(* All protocol states are sorted by construction *)\nLemma protocol_state_sorted\n  {C V} `{PS : ProtocolState C V}\n  : forall state : @state C V,\n  protocol_state state ->\n  locally_sorted state.\nProof.\n  intros.\n  induction H.\n  - constructor.\n  - apply (add_in_sorted_sorted (c, v, j) s); try assumption.\n    apply locally_sorted_message_justification. assumption.\nQed.\n\n(* All protocol states are not too heavy *)\nLemma protocol_state_not_heavy\n  {C V} `{PS : ProtocolState C V}\n  : forall s : @state C V,\n  protocol_state s ->\n  not_heavy s.\nProof.\n  intros.\n  inversion H.\n  - unfold not_heavy. unfold fault_weight_state.\n    simpl. apply Rge_le. destruct threshold; simpl; auto.\n  - assumption.\nQed.\n\n(* All messages in protocol states are estimator approved *)\nLemma protocol_state_valid_estimate\n  {C V} `{PS : ProtocolState C V}\n  : forall s : @state C V,\n    protocol_state s ->\n    forall msg,\n      in_state msg s ->\n      valid_estimate (estimate msg) (justification msg).\nProof.\n  intros s H_ps msg H_in.\n  induction H_ps.\n  inversion H_in.\n  rewrite in_state_add_in_sorted_iff in H_in.\n  destruct H_in as [H_eq | H_in].\n  subst.\n  assumption.\n  now apply IHH_ps1.\nQed.\n\n(* All singleton states are protocol states *)\nLemma protocol_state_singleton\n  {C V} `{PS : ProtocolState C V}\n  : forall (c : C) (v : V),\n  estimator Empty c ->\n  protocol_state (next (c, v, Empty) Empty).\nProof.\n  intros.\n  assert (Heq : add_in_sorted_fn (c, v, Empty) Empty = (next (c, v, Empty) Empty)); try reflexivity.\n  rewrite <- Heq.\n  apply protocol_state_next; try assumption; try apply protocol_state_empty.\n  - apply incl_refl.\n  - simpl. rewrite add_is_next. apply not_heavy_single.\nQed.\n\n(* All protocol states are either empty or contain a message with an empty justification *)\nLemma protocol_state_start_from_empty\n  {C V} `{PS : ProtocolState C V}\n  : forall s : @state C V,\n  protocol_state s ->\n  s = Empty \\/ exists msg, in_state msg s /\\ justification msg = Empty.\nProof.\n  intros. induction H; try (left; reflexivity). right.\n  destruct s.\n  - exists (c, v, Empty). split; try reflexivity.\n    apply in_state_add_in_sorted_iff. left.\n    red in H1; simpl in H1.\n    apply incl_empty in H1.\n    apply nil_empty_state in H1.\n    subst; reflexivity.\n  - destruct IHprotocol_state2.\n    + subst. destruct IHprotocol_state1.\n      inversion H4.\n      destruct H4 as [msg [H_in H_empty]].\n      exists msg.\n      repeat split. apply in_state_add_in_sorted_iff.\n      right; assumption. assumption.\n    + destruct H4 as [msg [H_in H_empty]].\n      exists msg.\n      repeat split. apply in_state_add_in_sorted_iff.\n      right. apply H1. assumption. assumption.\nQed.\n\n(* Recording entire histories preserves protocol state-ness *)\nLemma copy_protocol_state\n  {C V} `{PS : ProtocolState C V}\n  : forall s : @state C V,\n  protocol_state s ->\n  forall c,\n    estimator s c->\n    forall v,\n      protocol_state (add_in_sorted_fn (c, v, s) s).\nProof.\n  intros sigma Hps c Hc v.\n  constructor; try assumption; try apply incl_refl.\n  unfold not_heavy.\n  apply not_heavy_subset with (add (c,v,sigma) to sigma).\n  - unfold syntactic_state_inclusion. apply set_eq_add_in_sorted.\n  - unfold not_heavy. unfold fault_weight_state.\n    rewrite equivocating_senders_extend.\n    apply protocol_state_not_heavy in Hps. assumption.\nQed.\n\n(* Two protocol states if not too heavy combined can be combined into a protocol state. *)\nLemma union_protocol_states\n  {C V} `{PS : ProtocolState C V}\n  : forall (s1 s2 : @state C V),\n    locally_sorted s1 ->\n    locally_sorted s2 ->\n    protocol_state s1 ->\n    protocol_state s2 ->\n    (fault_weight_state (state_union s1 s2) <= proj1_sig threshold)%R ->\n    protocol_state (state_union s1 s2).\nProof.\n  intros s1 s2 about_s1 about_s2 Hps1 Hps2.\n  induction Hps2; intros.\n  - unfold state_union. simpl.\n    unfold messages_union. rewrite app_nil_r.\n    rewrite list_to_state_sorted. assumption.\n    apply protocol_state_sorted. assumption.\n  - replace (state_union s1 (add_in_sorted_fn (c,v,j) s)) with (add_in_sorted_fn (c,v,j) (state_union s1 s)) in *.\n    2 : { rewrite (state_union_add_in_sorted s1 (c, v, j) s).\n          reflexivity.\n          now apply protocol_state_sorted.\n          now apply protocol_state_sorted.\n          apply (locally_sorted_message_justification c v j).\n          now apply protocol_state_sorted. }\n    apply protocol_state_next; try assumption.\n    apply IHHps2_1.\n    now apply protocol_state_sorted. apply not_heavy_subset with (add_in_sorted_fn (c, v, j) (state_union s1 s)); try assumption.\n    intros msg H_in. apply set_eq_add_in_sorted.\n    right; assumption.\n    intros msg H_in.\n    apply state_union_iff.\n    right. apply H. assumption.\nQed.\n\n(* All messages in a protocol state have correct subsetted justifications *)\nLemma message_subset_correct\n  {C V} `{PS : ProtocolState C V}\n  : forall s : @state C V, protocol_state s ->\n       forall msg, In msg (get_messages s) ->\n              incl_messages (justification msg) s.\nProof.\n  intros s H_ps msg H_in_msg m H_in.\n  induction H_ps; subst.\n  inversion H_in_msg.\n  assert (H_useful := in_state_add_in_sorted_iff m (c,v,j) s).\n  rewrite H_useful. clear H_useful.\n  apply in_state_add_in_sorted_iff in H_in_msg.\n  destruct H_in_msg as [H_eq | H_in_msg].\n  - right. subst; simpl in H_in.\n    spec H m H_in.\n    assert (H_useful := set_eq_add_in_sorted (c,v,j) s).\n    destruct H_useful as [H_left H_right].\n    spec H_right (c,v,j) (in_eq (c,v,j) (get_messages s)).\n    assumption.\n  - right; apply IHH_ps1.\n    assumption.\nQed.\n\n(** Lemmas about justifications of messages contained within protocol states, i.e. \"past\" protocol states **)\n(* Any justification of protocol state messages are themselves protocol states *)\nLemma protocol_state_justification\n  {C V} `{PS : ProtocolState C V}\n  : forall s : @state C V, protocol_state s ->\n       forall msg, in_state msg s ->\n              protocol_state (justification msg).\nProof.\n  intros s H_ps msg H_in.\n  induction H_ps.\n  - inversion H_in.\n  - apply in_state_add_in_sorted_iff in H_in.\n    destruct H_in as [left | right].\n    + subst. simpl. assumption.\n    + now apply IHH_ps1.\nQed.\n\n(* All justifications of protocol state messages are themselves protocol states *)\nLemma protocol_state_all_justifications\n  {C V} `{PS : ProtocolState C V}\n  : forall s, protocol_state s ->\n       Forall protocol_state (map justification (get_messages s)).\nProof.\n  intros s H_ps.\n  induction H_ps; apply Forall_forall; intros x H_in.\n  - inversion H_in.\n  - rewrite in_map_iff in H_in.\n    destruct H_in as [msg [H_justif H_justif_in]].\n    subst.\n    apply (protocol_state_justification (add_in_sorted_fn (c,v,j) s)); try constructor; assumption.\nQed.\n\n(* No protocol state can contain a message that contains itself as the justification *)\nTheorem no_self_justification\n  {C V} `{PS : ProtocolState C V}\n  : forall j : @state C V, protocol_state j ->\n       forall c v, in_state (c, v, j) j -> False.\nProof.\n  intros j H_prot c v H_in.\n  induction H_prot.\n  - inversion H_in.\n  - rewrite in_state_add_in_sorted_iff in H_in.\n    destruct H_in as [H_eq | H_in].\n    + inversion H_eq.\n      subst. apply IHH_prot2. rewrite <- H5 at 2.\n      unfold in_state.\n      assert (H_useful := set_eq_add_in_sorted (c0,v0,j) s).\n      red in H_useful. destruct H_useful as [H_left H_right].\n      spec H_right (c0,v0,j) (in_eq (c0,v0,j) (get_messages s)).\n      assumption.\n    + apply (not_extx_in_x c v (add_in_sorted_fn (c0,v0,j) s) s).\n      red. intros msg H_msg_in.\n      assert (H_useful := set_eq_add_in_sorted (c0,v0,j) s).\n      destruct H_useful as [_ H_useful].\n      spec H_useful msg. spec H_useful.\n      right; assumption. assumption.\n      assumption.\nQed.\n\nLemma messages_equivocating_senders_eq\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall s1 s2 : @state C V,\n    set_eq (get_messages s1) (get_messages s2) ->\n    set_eq (equivocating_senders s1) (equivocating_senders s2).\nProof.\n  intros s1 s2 [H_eq1 H_eq2].\n  apply set_map_eq.\n  assert (H_equiv1 := equivocating_in_state_incl s1 s2 H_eq1).\n  assert (H_equiv2 := equivocating_in_state_incl s2 s1 H_eq2).\n  split; intros msg H_msg_in.\n  - apply filter_in.\n    spec H_eq1 msg. spec H_eq1.\n    apply filter_In in H_msg_in.\n    destruct H_msg_in as [H_goal _]; assumption.\n    assumption.\n    apply filter_In in H_msg_in.\n    destruct H_msg_in as [_ H_useful].\n    rewrite equivocating_in_state_correct in H_useful.\n    spec H_equiv1 msg H_useful.\n    rewrite equivocating_in_state_correct.\n    assumption.\n  - apply filter_in.\n    spec H_eq2 msg. spec H_eq2.\n    apply filter_In in H_msg_in.\n    destruct H_msg_in as [H_goal _]; assumption.\n    assumption.\n    apply filter_In in H_msg_in.\n    destruct H_msg_in as [_ H_useful].\n    rewrite equivocating_in_state_correct in H_useful.\n    spec H_equiv2 msg H_useful.\n    rewrite equivocating_in_state_correct.\n    assumption.\nQed.\n\nLemma equivocating_senders_empty\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : equivocating_senders (@Empty C V) = [].\nProof.\n  unfold equivocating_senders.\n  simpl. reflexivity.\nQed.\n\nLemma equivocating_senders_extend'\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (s : state) (c : C) (v : V) (j : state),\n    In v (equivocating_senders s) ->\n    set_eq (equivocating_senders (add (c, v, j) to s))\n           (equivocating_senders s).\nProof.\n  intros.\n  unfold equivocating_senders.\n  split; intros v0 H_in; apply set_map_exists.\n  - (* Arbitrary v0 is an equivocating sender in the new state *)\n    apply set_map_exists in H_in.\n    (* Arbitrary v0 has sent an equivocating_in_state message in the new state *)\n    destruct H_in as [msg [H_in H_sender]].\n    apply filter_In in H_in.\n    simpl in H_in.\n    destruct H_in as [H_in H_equiv].\n    rewrite equivocating_in_state_correct in H_equiv.\n    destruct H_equiv as [msg' [H_in' H_equiv]].\n    (* This message has an equivocation partner *)\n    (* Both of these messages are in the new state - case analysis on each of them with the hd element *)\n    destruct H_in as [H_hd | H_tl].\n    + (* In the case that the first equivocating message is the hd  *)\n      subst.\n      destruct H_in' as [H_absurd | H_in'].\n      * (* In the case that the second equivocating message is also the hd, we have a contradiction *)\n        subst. inversion H_equiv; contradiction.\n      * (* In the case that the second equivocarting message is in the tl, *)\n        apply equivocating_senders_correct in H.\n        destruct H as [msg0 [H_in0 [H_sender0 H_equiv0]]].\n        exists msg0. rewrite filter_In.\n        repeat split; try assumption.\n        apply equivocating_in_state_correct.\n        assumption.\n    + (* In the case that the first equivocating message is in the tl, *)\n      destruct H_in' as [H_hd' | H_tl'].\n      * (* In the case that the second equivocating message is the hd, *)\n        subst.\n        apply equivocating_senders_correct in H.\n        destruct H as [msg0 [H_in0 [H_sender0 H_equiv0]]].\n        exists msg0. rewrite filter_In.\n        repeat split; try assumption.\n        apply equivocating_in_state_correct.\n        assumption. subst.\n        destruct H_equiv as [_ [H_sender _]].\n        simpl in H_sender. symmetry; assumption.\n      * (* In the case that the second equivocating message is in the tl, *)\n        exists msg.\n        rewrite filter_In.\n        repeat split; try assumption.\n        rewrite equivocating_in_state_correct.\n        exists msg'; split; try assumption.\n  - (* Arbitrary v0 is an equivocating sender in the old state *)\n    apply set_map_exists in H_in.\n    destruct H_in as [msg0 [H_in0 H_sender0]].\n    apply filter_In in H_in0.\n    destruct H_in0 as [H_in0 H_equiv0].\n    exists msg0. rewrite filter_In.\n    repeat split.\n    right. assumption.\n    apply equivocating_in_state_correct.\n    apply equivocating_in_state_incl with s.\n    { intros msg H_msg_in.\n      right; assumption. }\n    apply equivocating_in_state_correct.\n    assumption.\n    assumption.\nQed.\n\nLemma equivocating_senders_fault_weight_eq\n  {C V} `{about_M : StrictlyComparable (message C V)} `{Hm : Measurable V}\n  : forall s1 s2 : @state C V,\n    set_eq (equivocating_senders s1) (equivocating_senders s2) ->\n    fault_weight_state s1 = fault_weight_state s2.\nProof.\n  intros s1 s2 H_eq.\n  apply @set_eq_nodup_sum_weight_eq; try apply set_map_nodup; try assumption.\n  pose (triple_strictly_comparable_proj2 about_M) as Sc.\n  intros x y.\n  apply compare_eq_dec.\nQed.\n\nLemma messages_fault_weight_eq\n  {C V} `{about_M : StrictlyComparable (message C V)} `{Hm : Measurable V}\n  : forall s1 s2 : @state C V,\n    set_eq (get_messages s1) (get_messages s2) ->\n    fault_weight_state s1 = fault_weight_state s2.\nProof.\n  intros s1 s2 H_eq.\n  apply equivocating_senders_fault_weight_eq.\n  now apply messages_equivocating_senders_eq.\nQed.\n\nLemma add_next_equivocating_senders_eq\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (c : C) (v : V) j s,\n    set_eq (equivocating_senders (add_in_sorted_fn (c,v,j) s))\n           (equivocating_senders (next (c,v,j) s)).\nProof.\n  intros.\n  assert (H_obv : set_eq (get_messages (add_in_sorted_fn (c,v,j) s))\n                         (get_messages (next (c,v,j) s))).\n  { split; intros msg H_in.\n    - apply in_state_add_in_sorted_iff in H_in.\n      destruct H_in. subst. simpl. tauto.\n      right. assumption.\n    - apply in_state_add_in_sorted_iff.\n      inversion H_in. subst. tauto.\n      right; assumption. }\n  now apply messages_equivocating_senders_eq.\nQed.\n\n(* A new equivocation from a sender inducts it into the set of equivocating_senders *)\n(* This says nothing about protocol state validity *)\nLemma add_already_equivocating_sender\n  {C V} `{PS : ProtocolState C V}\n  : forall (s : @state C V),\n    protocol_state s ->\n    forall (msg : message C V),\n      In (sender msg) (equivocating_senders s) ->\n        set_eq (equivocating_senders s)\n               (equivocating_senders (add_in_sorted_fn msg s)).\nProof.\n  intros s about_s msg H_in.\n  split; intros v H_v_in.\n  - unfold equivocating_senders.\n    apply set_map_exists in H_v_in.\n    destruct H_v_in as [msg' [H_v_in H_msg'_sender]].\n    apply filter_In in H_v_in.\n    rewrite <- H_msg'_sender.\n    apply set_map_in.\n    apply filter_in. apply in_state_add_in_sorted_iff.\n    right.\n    tauto.\n    rewrite equivocating_in_state_correct.\n    destruct H_v_in.\n    rewrite equivocating_in_state_correct in H0.\n    destruct H0 as [msg'_partner H0].\n    red. exists msg'_partner. split.\n    destruct H0.\n    rewrite in_state_add_in_sorted_iff.\n    right; assumption.\n    tauto.\n  - destruct (classic (v = sender msg)).\n    + subst. assumption.\n    + unfold equivocating_senders in H_v_in.\n      apply set_map_exists in H_v_in.\n      destruct H_v_in as [msg' [H_v_in H_msg'_sender]].\n      apply filter_In in H_v_in.\n      destruct H_v_in as [H_v_in H_equiv].\n      rewrite equivocating_in_state_correct in H_equiv.\n      destruct H_equiv as [msg'_partner [H_msg'_partner_in H_equiv]].\n      rewrite <- H_msg'_sender.\n      apply set_map_in.\n      apply filter_in.\n      apply in_state_add_in_sorted_iff in H_v_in.\n      destruct H_v_in.\n      subst.\n      contradiction.\n      assumption.\n      rewrite equivocating_in_state_correct.\n      exists msg'_partner.\n      split. rewrite in_state_add_in_sorted_iff in H_msg'_partner_in. destruct H_msg'_partner_in.\n      subst. destruct H_equiv.\n      destruct H1. contradiction.\n      assumption. assumption.\nQed.\n\nLemma equivocating_sender_add_in_sorted_iff\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (s : state) (msg : message C V) (v : V),\n    In v (equivocating_senders (add_in_sorted_fn msg s)) <->\n    (v = sender msg /\\ equivocating_in_state_prop msg s) \\/\n    In v (equivocating_senders s).\nProof.\n  intros s msg v. split; intros.\n  -  apply equivocating_senders_correct in H.\n     destruct H as [msg' [H_in [H_sender H_equiv]]].\n     apply in_state_add_in_sorted_iff in H_in.\n     destruct H_in as [H_eq | H_noteq].\n     + subst.\n       destruct H_equiv as [msg_partner [H_msg_partner H_equiv]].\n       left. split. reflexivity.\n       exists msg_partner.\n       rewrite in_state_add_in_sorted_iff in H_msg_partner.\n       destruct H_msg_partner. subst. inversion H_equiv.\n       contradiction. tauto.\n     + destruct H_equiv as [msg'_partner [H_msg'_partner H_equiv]].\n       apply in_state_add_in_sorted_iff in H_msg'_partner.\n       destruct H_msg'_partner as [H_eq' | H_noteq'].\n       * subst. left. destruct H_equiv. split. tauto.\n         exists msg'. split.\n         assumption. split.\n         auto. split. easy. tauto.\n       * right.\n         apply equivocating_senders_correct.\n         exists msg'_partner. split. assumption.\n         destruct H_equiv. split. subst; symmetry; tauto.\n         red. exists msg'. split. assumption.\n         apply equivocating_messages_prop_swap.\n         red; tauto.\n  - destruct H as [[H_sender H_equiv] | H_noteq].\n    + subst.\n      apply equivocating_senders_correct.\n      destruct H_equiv as [msg_partner [H_msg_partner H_equiv]].\n      exists msg_partner.\n      split. apply in_state_add_in_sorted_iff.\n      right; assumption.\n      split. destruct H_equiv. symmetry; tauto.\n      exists msg. split. rewrite in_state_add_in_sorted_iff; tauto.\n      rewrite equivocating_messages_prop_swap. assumption.\n    + apply set_map_exists.\n      apply set_map_exists in H_noteq.\n      destruct H_noteq as [msg' [H_in H_sender]].\n      exists msg'. split.\n      rewrite filter_In.\n      apply filter_In in H_in.\n      split.\n      apply in_state_add_in_sorted_iff.\n      tauto. 2 : assumption.\n      destruct H_in.\n      apply equivocating_in_state_correct in H0.\n      destruct H0 as [msg'_partner about_msg'_partner].\n      apply equivocating_in_state_correct.\n      exists msg'_partner. split.\n      rewrite in_state_add_in_sorted_iff; tauto.\n      tauto.\nQed.\n\nLemma add_equivocating_sender\n  {C V} `{PS : ProtocolState C V}\n  : forall (s : state),\n    protocol_state s ->\n    forall (msg : message C V),\n      (exists msg',\n          in_state msg' s /\\\n          equivocating_messages_prop msg msg') ->\n      set_eq (equivocating_senders (add_in_sorted_fn msg s))\n             (set_add (compare_eq_dec_v about_M) (sender msg) (equivocating_senders s)).\nProof.\n  (* Because we're using set_add, we don't need to care about whether (sender msg) is already in (equivocating_senders s) *)\n  intros s about_s msg [msg' [H_in H_equiv]].\n  destruct (classic (in_state msg s)) as [H_msg_in | H_msg_out].\n  - (* In the case that msg is already in s, *)\n    (* Adding it does nothing to the state *)\n    assert (s_sorted := protocol_state_sorted s about_s).\n    assert (H_ignore := add_in_sorted_ignore msg s s_sorted H_msg_in).\n    simpl in *. rewrite H_ignore.\n    clear H_ignore s_sorted.\n    (* Adding the sender should do nothing to (equivocating_senders s) *)\n    split.\n    + intros v0 H_mem.\n      (* The following is winding and painful *)\n      unfold equivocating_senders in H_mem.\n      rewrite (@set_map_exists _ _ (compare_eq_dec_v about_M)) in H_mem.\n      destruct H_mem as [msg0 [H0_in H0_sender]].\n      rewrite filter_In in H0_in.\n      assert (H_senders := equivocating_senders_correct s).\n      red in H_senders.\n      destruct H0_in as [H0_in H0_equiv].\n      apply set_add_iff.\n      destruct (classic (msg = msg0)).\n      * subst.\n        left; reflexivity.\n      * right. spec H_senders v0.\n        apply H_senders.\n        rewrite equivocating_in_state_correct in H0_equiv.\n        destruct H0_equiv as [msg0_partner [H0_equivl H0_equivr]].\n        exists msg0_partner. repeat split; try assumption.\n        rewrite <- H0_sender.\n        destruct H0_equivr as [_ [H_goal _]].\n        symmetry; assumption.\n        red. exists msg0. split.\n        red; exact H0_in.\n        apply equivocating_messages_prop_swap.\n        assumption.\n    + intros v0 H_mem.\n      (* The following will also be winding and painful *)\n      destruct (classic (v0 = sender msg)).\n      * subst.\n        clear H_mem.\n        apply set_map_in.\n        apply filter_in.\n        assumption.\n        rewrite equivocating_in_state_correct.\n        exists msg'. split; assumption.\n      * rewrite set_add_iff in H_mem.\n        destruct H_mem.\n        contradiction. assumption.\n  - (* In the case that msg is not already in s, *)\n    (* For all we know (sender msg) could already be in (equivocating_senders s) *)\n    destruct (classic (In (sender msg) (equivocating_senders s))).\n    + (* If (sender msg) is already in there, then adding it again does nothing *)\n      assert (H_ignore : set_eq (set_add (compare_eq_dec_v about_M) (sender msg) (equivocating_senders s)) (equivocating_senders s)).\n      {  split; intros v H_v_in.\n         apply set_add_iff in H_v_in.\n         destruct H_v_in.\n         subst; assumption.\n         assumption.\n         apply set_add_iff. right; assumption. }\n      apply set_eq_comm in H_ignore.\n      eapply set_eq_tran.\n      2 : exact H_ignore.\n      apply set_eq_comm.\n      now apply add_already_equivocating_sender.\n    + (* If (sender msg) is not already in there *)\n      split; intros.\n      * intros v0 H_in0.\n        destruct (classic (v0 = sender msg)).\n        ** subst.\n           apply set_add_iff.\n           tauto.\n        ** apply set_add_iff.\n           right.\n           destruct msg as [[c v] j].\n           apply equivocating_sender_add_in_sorted_iff in H_in0.\n           destruct H_in0.\n           destruct H1; contradiction.\n           assumption.\n      * intros v0 H_in0.\n        destruct (classic (v0 = sender msg)).\n        ** subst.\n           apply set_add_iff in H_in0.\n           destruct H_in0.\n           apply set_map_in.\n           apply filter_in.\n           apply in_state_add_in_sorted_iff.\n           tauto.\n           rewrite equivocating_in_state_correct.\n           red. exists msg'.\n           split. rewrite in_state_add_in_sorted_iff.\n           tauto. assumption.\n           contradiction.\n        ** apply set_add_iff in H_in0.\n           destruct H_in0.\n           contradiction.\n           apply set_map_exists in H1.\n           destruct H1 as [msg0 [H_in0 H_sender0]].\n           apply set_map_exists. exists msg0.\n           split. 2 : assumption.\n           apply filter_in.\n           apply filter_In in H_in0.\n           destruct H_in0.\n           apply in_state_add_in_sorted_iff.\n           right; assumption.\n           apply filter_In in H_in0.\n           destruct H_in0.\n           rewrite equivocating_in_state_correct.\n           red. rewrite equivocating_in_state_correct in H2.\n           red in H2.\n           destruct H2 as [msg0_partner [H_in0 H_equiv0]].\n           exists msg0_partner.\n           split.\n           rewrite in_state_add_in_sorted_iff; right; assumption.\n           assumption.\nQed.\n\n\nDefinition valid_protocol_state\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  (sigma : state) (csigma cempty : C) (vs : list V) : state :=\n  fold_right\n    (fun v sigma' =>\n      add_in_sorted_fn (csigma, v, sigma) (add_in_sorted_fn (cempty, v, Empty) sigma'))\n    sigma\n    vs.\n\nLemma in_valid_protocol_state\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (msg : message C V) sigma csigma cempty vs,\n  in_state msg (valid_protocol_state sigma csigma cempty vs) ->\n  in_state msg sigma \\/\n  exists v, In v vs /\\ (msg = (csigma, v, sigma) \\/ (msg = (cempty, v, Empty))).\nProof.\n  intros. induction vs.\n  - simpl in H. left. assumption.\n  - simpl in H. rewrite in_state_add_in_sorted_iff in H. rewrite in_state_add_in_sorted_iff in H.\n    destruct H as [Heq | [Heq | Hin]];\n    try (right; exists a; split; try (left; reflexivity); (left; assumption) || (right; assumption)).\n    apply IHvs in Hin. destruct Hin; try (left; assumption). right.\n    destruct H as [v [Hin H]].\n    exists v. split; try assumption. right; assumption.\nQed.\n\nLemma in_valid_protocol_state_rev_sigma\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (sigma : @state C V) csigma cempty vs,\n  syntactic_state_inclusion sigma (valid_protocol_state sigma csigma cempty vs).\nProof.\n  intros. intros msg Hin.\n  induction vs.\n  - assumption.\n  - simpl. apply in_state_add_in_sorted_iff. right.\n    apply in_state_add_in_sorted_iff. right.\n    assumption.\nQed.\n\nLemma in_valid_protocol_state_rev_csigma\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (sigma : @state C V) csigma cempty vs,\n  forall v,\n  In v vs ->\n  in_state (csigma, v, sigma) (valid_protocol_state sigma csigma cempty vs).\nProof.\n  induction vs; intros.\n  - inversion H.\n  - destruct H as [Heq | Hin].\n    + subst. simpl. apply in_state_add_in_sorted_iff. left. reflexivity.\n    + simpl. apply in_state_add_in_sorted_iff. right.\n      apply in_state_add_in_sorted_iff. right.  apply IHvs. assumption.\nQed.\n\nLemma in_valid_protocol_state_rev_cempty\n  {C V} `{about_M : StrictlyComparable (message C V)}\n  : forall (sigma : @state C V) csigma cempty vs,\n  forall v,\n  In v vs ->\n  in_state (cempty, v, Empty) (valid_protocol_state sigma csigma cempty vs).\nProof.\n  induction vs; intros.\n  - inversion H.\n  - destruct H as [Heq | Hin].\n    + subst. simpl. apply in_state_add_in_sorted_iff. right.\n       apply in_state_add_in_sorted_iff. left. reflexivity.\n    + simpl. apply in_state_add_in_sorted_iff. right.\n      apply in_state_add_in_sorted_iff. right.  apply IHvs. assumption.\nQed.\n\nLemma valid_protocol_state_equivocating_senders\n  {C V} `{about_M : StrictlyComparable (message C V)} `{He : Estimator (@state C V) C}\n  : forall cempty : C,\n  estimator Empty cempty ->\n  forall (v : V) vs,\n  ~ In v vs ->\n  forall csigma,\n  estimator (next (cempty, v, Empty) Empty) csigma ->\n  set_eq (equivocating_senders (valid_protocol_state (next (cempty, v, Empty) Empty) csigma cempty vs)) vs.\nProof.\n  intros.\n  remember (next (cempty, v, Empty) Empty) as sigma.\n  remember (valid_protocol_state sigma csigma cempty vs) as sigma2.\n  unfold equivocating_senders. split; intros; intros x Hin.\n  - apply set_map_exists  in Hin.\n    destruct Hin as [[(cx, vx) jx] [Hin Hsend]].\n    simpl in Hsend. rewrite <- Hsend.\n    apply filter_In in Hin. destruct Hin as [Hin Hequiv].\n    apply existsb_exists in Hequiv.\n    destruct Hequiv as [[(cy, vy) jy] [Hiny Hequiv]].\n    rewrite Heqsigma2 in Hin.\n    apply in_valid_protocol_state in Hin.\n    destruct Hin as [Hin | [vv [Hin [Heq | Heq]]]]; try (inversion Heq; subst; assumption).\n    exfalso. unfold equivocating_messages in Hequiv.\n    rewrite Heqsigma in Hin. apply in_singleton_state in Hin.\n    rewrite Heqsigma2 in Hiny.\n    apply in_valid_protocol_state in Hiny.\n    destruct Hiny as [Hiny | [vv [Hiny [Heq | Heq]]]].\n    + rewrite Heqsigma in Hiny. apply in_singleton_state in Hiny.\n      rewrite Hin in Hequiv. rewrite Hiny in Hequiv.\n      rewrite eq_dec_if_true in Hequiv; try reflexivity.\n      inversion Hequiv.\n    + rewrite Hin in Hequiv. rewrite Heq in Hequiv.\n      rewrite eq_dec_if_false in Hequiv.\n      * rewrite eq_dec_if_false in Hequiv; try inversion Hequiv.\n        intro; subst. inversion Hin; subst; clear Hin. inversion Heq; subst; clear Heq.\n        apply H0. assumption.\n      * intro. inversion H2; subst; clear H2. apply H0. assumption.\n    + rewrite Hin in Hequiv. rewrite Heq in Hequiv.\n      rewrite eq_dec_if_false in Hequiv.\n      * rewrite eq_dec_if_false in Hequiv; try inversion Hequiv.\n        intro; subst. inversion Hin; subst; clear Hin. inversion Heq; subst; clear Heq.\n        apply H0. assumption.\n      * intro. inversion H2; subst; clear H2. apply H0. assumption.\n  - apply set_map_exists.\n    exists (cempty, x, Empty). simpl. split; try reflexivity.\n    apply filter_In. split.\n    + rewrite Heqsigma2. apply in_valid_protocol_state_rev_cempty. assumption.\n    + apply existsb_exists. exists (csigma, x, sigma). split.\n      * rewrite Heqsigma2. apply in_valid_protocol_state_rev_csigma. assumption.\n      * unfold equivocating_messages.\n        { rewrite eq_dec_if_false.\n          - rewrite eq_dec_if_true; try reflexivity. apply andb_true_iff. split.\n            + apply negb_true_iff. unfold in_state_fn.\n              rewrite in_state_dec_if_false; try reflexivity.\n              rewrite Heqsigma. intro. apply in_singleton_state in H2.\n              apply H0. inversion H2; subst; clear H2. assumption.\n            + apply negb_true_iff. unfold in_state_fn.\n              rewrite in_state_dec_if_false; try reflexivity.\n              apply in_empty_state.\n          - intro. inversion H2; subst. inversion H5.\n        }\nQed.\n\nLemma valid_protocol_state_ps\n  {C V} `{PS : ProtocolState C V}\n  : forall cempty : C,\n  estimator Empty cempty ->\n  forall vs,\n  NoDup vs ->\n  (sum_weights vs <= proj1_sig threshold)%R ->\n  forall v : V,\n  ~ In v vs ->\n  forall csigma,\n  estimator (next (cempty, v, Empty) Empty) csigma ->\n  protocol_state (valid_protocol_state (next (cempty, v, Empty) Empty) csigma cempty vs).\nProof.\n  pose (@strictly_comparable_eq_dec _ (triple_strictly_comparable_proj2 about_M)) as HEqDec.\n  intros. induction vs.\n  - simpl. apply protocol_state_singleton. assumption.\n  - simpl. constructor.\n    + constructor.\n      apply IHvs.\n      apply NoDup_cons_iff in H0.\n      tauto.\n      simpl in H1.\n      apply Rle_trans with (proj1_sig (weight a) + sum_weights vs)%R; try assumption.\n      rewrite <- (Rplus_0_l (sum_weights vs)) at 1.\n      apply Rplus_le_compat_r.\n      apply Rge_le. left. destruct (weight a). simpl.\n      auto.\n      intro. apply H2. right; assumption.\n      constructor.\n      intros m H_in. inversion H_in.\n      assumption.\n      red. unfold fault_weight_state.\n      apply Rle_trans with (sum_weights (a :: vs)); try assumption.\n      apply sum_weights_incl; try assumption; try apply set_map_nodup.\n      rewrite add_is_next.\n      remember (next (cempty, v, Empty) Empty) as sigma.\n      remember (valid_protocol_state sigma csigma cempty vs) as sigma2.\n      { apply incl_tran with (equivocating_senders sigma2).\n        - apply set_eq_proj1.\n          apply equivocating_senders_unseen.\n          intro. apply set_map_exists in H4.\n          destruct H4 as [[(cx, vx) jx] [Hin Heq]].\n          simpl in Heq. rewrite Heq in Hin. clear Heq.\n          rewrite Heqsigma2 in Hin. apply in_valid_protocol_state in Hin.\n          destruct Hin.\n          + rewrite Heqsigma in H4. apply in_singleton_state in H4.\n            apply H2. inversion H4. left; reflexivity.\n          + destruct H4 as [vv [Hin Heq]]. apply NoDup_cons_iff in H0.\n            destruct H0 as [Hnin Hnodup]. apply Hnin.\n            destruct Heq as [Heq | Heq]; inversion Heq; subst; assumption.\n        - apply incl_tran with vs.\n          + apply set_eq_proj1. subst.\n            apply valid_protocol_state_equivocating_senders; try assumption.\n            intro. apply H2. right. assumption.\n          + intros x Hin. right. assumption.\n        }\n    + apply protocol_state_singleton; assumption.\n    + intros msg Hin. simpl in Hin.\n      destruct Hin as [Heq | Hcontra]; try inversion Hcontra; subst.\n      apply in_state_add_in_sorted_iff. right.\n      rewrite add_is_next.\n      apply in_valid_protocol_state_rev_sigma. simpl. left. reflexivity.\n    + assumption.\n    + red; unfold fault_weight_state.\n      apply Rle_trans with (sum_weights (a :: vs)); try assumption.\n      apply sum_weights_incl; try assumption; try apply set_map_nodup.\n      apply incl_tran with (equivocating_senders (valid_protocol_state (next (cempty, v, Empty) Empty) csigma cempty (a :: vs)))\n      ; try  apply incl_refl.\n      apply set_eq_proj1.\n      apply valid_protocol_state_equivocating_senders; try assumption.\nQed.\n", "meta": {"author": "zunction", "repo": "casper-cbc-proofs", "sha": "92493810dd32a8301882f9eb8a0488a6ac9d0cd1", "save_path": "github-repos/coq/zunction-casper-cbc-proofs", "path": "github-repos/coq/zunction-casper-cbc-proofs/casper-cbc-proofs-92493810dd32a8301882f9eb8a0488a6ac9d0cd1/CBC/Definitions.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.2014708546986629}}
{"text": "Require Import MirrorCore.TypesI.\nRequire Import MirrorCore.SymI.\n\nRecord TypedValue {T : Set} {RT : RType T} : Type := mkTypedVal\n{ tv_type : T\n; tv_value : TypesI.typD tv_type }.\nArguments TypedValue _ {_} : clear implicits.\nArguments mkTypedVal {_ _} _ _ : clear implicits.\n\nSection Simple_RSym.\n  Context {T} {RT : RType T} {f : Set}\n             (fD : f -> option (TypedValue T))\n             (fdec : forall a b : f, {a = b} + {a <> b}).\n  Definition RSym_simple : RSym f :=\n  {| typeof_sym f := match fD f with\n                     | Some l => Some l.(tv_type)\n                     | None => None\n                     end\n   ; symD f := match fD f with\n               | Some l => l.(tv_value)\n               | None => tt\n               end\n   ; sym_eqb a b := Some match fdec a b with\n                         | left _ => true\n                         | right _ => false\n                         end |}.\n\n  Global Instance RSymOk_simple :  RSymOk RSym_simple.\n  Proof. constructor. intros. simpl.\n         destruct (fdec a b); auto.\n  Qed.\nEnd Simple_RSym.\n", "meta": {"author": "gmalecha", "repo": "mirror-core", "sha": "b962fbca15b0b5a4653f66d29d7115bb04ebd4f3", "save_path": "github-repos/coq/gmalecha-mirror-core", "path": "github-repos/coq/gmalecha-mirror-core/mirror-core-b962fbca15b0b5a4653f66d29d7115bb04ebd4f3/theories/syms/SymSimple.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2014708432525556}}
{"text": "(* Do not edit this file, it was generated automatically *)\nRequire Import VST.floyd.proofauto.\nRequire Import VST.progs64.union.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nImport Memdata.\n\nDefinition Gprog : funspecs := nil.\n\nDefinition g_spec :=\n DECLARE _g\n WITH i: Z\n PRE [ size_t]\n   PROP() PARAMS(Vptrofs (Ptrofs.repr i)) SEP()\n POST [ size_t ]\n   PROP() RETURN (Vptrofs (Ptrofs.repr i)) SEP().\n\nLemma body_g: semax_body Vprog Gprog f_g g_spec.\nProof.\nstart_function.\nforward.\nforward.\nforward.\ncancel.\nQed.\n\nDefinition unconst_spec :=\n DECLARE _unconst\n WITH p: val\n PRE [ tptr tschar ]\n   PROP() PARAMS(p) SEP()\n POST [ tptr tschar ]\n   PROP() RETURN (p) SEP().\n\nLemma unconst_aux:\n  forall (x: val) v, \n      data_at Tsh (Tunion _const_or_not noattr) (inl x) v =\n      data_at Tsh (Tunion _const_or_not noattr) (inr x) v.\nProof. reflexivity. Qed.\n\nLemma body_unconst: semax_body Vprog Gprog f_unconst unconst_spec.\nProof.\nstart_function.\nforward.\nrewrite unconst_aux.\nforward.\nforward.\ncancel.\nQed.\n\nLemma decode_float32_int32:\n  forall (bl: list memval) (x: float32),\n size_chunk Mfloat32 = Z.of_nat (Datatypes.length bl) ->\n decode_val Mfloat32 bl = Vsingle x ->\n decode_val Mint32 bl = Vint (Float32.to_bits x).\nProof.\nintros.\nunfold decode_val,decode_int,rev_if_be in *.\ndestruct (proj_bytes bl) eqn:?H.\ninv H0.\nrewrite Float32.to_of_bits. auto.\ninv H0.\nQed.\n\nLemma NOT_decode_int32_float32:\n  Archi.ptr64=false ->\n ~ (forall (bl: list memval) (x: float32),\n     size_chunk Mfloat32 = Z.of_nat (Datatypes.length bl) ->\n     decode_val Mint32 bl = Vint (Float32.to_bits x) ->\n     decode_val Mfloat32 bl = Vsingle x).\n(* This lemma illustrates a problem: it is NOT the case that\n   if (bl: list memval) decodes to Vint (Float32.to_bits x) \n  then it also decodes to  Vsingle x.   \n  See https://github.com/AbsInt/CompCert/issues/207  for a description\n  of the problem; and see https://github.com/PrincetonUniversity/VST/issues/429\n  for a description of the solution,  forward_store_union_hack  *)\nProof.\nintro Hp.\nintro.\nset (x := Float32.zero). (* nothing special about zero, any value would do *)\nset (i := Float32.to_bits x).\nset (bl := [Fragment (Vint i) Q32 3; Fragment (Vint i) Q32 2; Fragment (Vint i) Q32 1; Fragment (Vint i) Q32 0]).\nspecialize (H bl x).\nspecialize (H (eq_refl _)).\nassert (decode_val Mint32 bl = Vint (Float32.to_bits x)).\nunfold decode_val, bl.\nrewrite Hp.\nsimpl.\ndestruct (Val.eq (Vint i) (Vint i)); [ | congruence].\ndestruct (quantity_eq Q32 Q32); [ | congruence].\nsimpl.\nreflexivity.\nspecialize (H H0).\nclear - H. subst bl i.\nunfold decode_val in H.\nsimpl in H. inversion H.\nQed.\n\nModule FABS_STUFF.\n\nLemma shift_pos_succ:\n  forall k j, (shift_pos (Pos.succ k) j = (shift_pos k j)~0)%positive.\nProof.\nintros.\nchange ((shift_pos k j)~0)%positive\nwith (2 * (shift_pos k j))%positive.\napply Pos2Z.inj.\nrewrite Pos2Z.inj_mul.\nrewrite !shift_pos_correct.\nrewrite Z.mul_assoc.\nf_equal.\nrewrite <- !two_power_pos_correct.\nrewrite <- Pos.add_1_l.\nrewrite two_power_pos_is_exp.\nreflexivity.\nQed.\n\nLemma nan_pl_range:\n forall k p, Binary.nan_pl k p = true ->\n Z.pos p < 2 ^ (k-1).\nProof.\nintros.\nunfold Binary.nan_pl in H.\napply Z.ltb_lt in H.\nrevert k H; induction p; simpl; intros.\n-\nrewrite Pos2Z.inj_succ in H.\nspecialize (IHp (k-1)).\nspec IHp; [lia | ].\nreplace (2^(k-1)) with (2^1 * 2^(k-1-1)).\n2:{ rewrite <- Z.pow_add_r by lia. f_equal. lia. }\nrewrite Pos2Z.inj_xI.\nlia.\n-\nrewrite Pos2Z.inj_succ in H.\nspecialize (IHp (k-1)).\nspec IHp; [lia | ].\nreplace (2^(k-1)) with (2^1 * 2^(k-1-1)).\n2:{ rewrite <- Z.pow_add_r by lia. f_equal. lia. }\nrewrite Pos2Z.inj_xO.\nlia.\n-\nreplace (2^(k-1)) with (2^1 * 2^(k-1-1)).\n2:{ rewrite <- Z.pow_add_r by lia. f_equal. lia. }\nchange (2^1) with 2.\nassert (0 < 2 ^ (k-1-1)).\napply Z.pow_pos_nonneg; lia.\nlia.\nQed.\n\n\nDefinition abs_nan (any_nan: {x : Bits.binary32 | Binary.is_nan 24 128 x = true}) (f: Binary.binary_float 24 128)   :=\nmatch f with\n| @Binary.B754_nan _ _ _ p H =>\n    exist (fun x : Binary.binary_float 24 128 => Binary.is_nan 24 128 x = true)\n      (Binary.B754_nan 24 128 false p H) eq_refl\n| _ => any_nan\nend.\n\nLemma bounded_mantissa:\n  forall prec emax m e, Binary.bounded prec emax m e = true ->\n    Z.pos m < 2 ^ prec.\nProof.\nintros.\nunfold Binary.bounded in H.\nrewrite andb_true_iff in H.\ndestruct H as [H H0].\napply Z.leb_le in H0.\nunfold Binary.canonical_mantissa in H.\napply Zeq_bool_eq in H.\nunfold FLT.FLT_exp in H.\nrewrite Digits.Zpos_digits2_pos in H.\npose proof (Z.max_lub_l (Digits.Zdigits Zaux.radix2 (Z.pos m) + e - prec)\n      (3 - emax - prec) e).\nspec H1; [ lia | ].\nclear H.\nassert (Digits.Zdigits Zaux.radix2 (Z.pos m) <= prec) by lia.\nclear - H.\napply Digits.Zpower_gt_Zdigits in H.\napply H.\nQed.\n\nLemma binary32_abs_lemma:\n forall (x : Bits.binary32)\n      (any_nan : {x : Bits.binary32 | Binary.is_nan 24 128 x = true}),\n  Bits.b32_of_bits (Bits.bits_of_b32 x mod 2 ^ 31) =\n  Binary.Babs 24 128 (abs_nan any_nan) x.\nProof.\nintros.\ndestruct x.\n- (* B754_zero *)\ndestruct s; reflexivity.\n- (* B754_infinity *)\ndestruct s; reflexivity.\n- (* B754_nan *)\nassert (Hpl := nan_pl_range _ _ e).\nunfold Bits.b32_of_bits, Binary.Babs, Bits.bits_of_b32, Bits.bits_of_binary_float.\nassert (Bits.join_bits 23 8 s (Z.pos pl) (2 ^ 8 - 1) mod 2 ^ 31 =\n            Bits.join_bits 23 8 false (Z.pos pl) (2 ^ 8 - 1)).  {\n unfold Bits.join_bits.\nrewrite !Z.shiftl_mul_pow2 by computable.\nrewrite Z.add_0_l.\nrewrite Z.mul_add_distr_r.\nrewrite <- Z.add_assoc.\nrewrite Z.add_mod by (compute; lia).\nreplace (((if s then 2 ^ 8 else 0) * 2 ^ 23) mod 2 ^ 31) with 0\n  by (destruct s; reflexivity).\nrewrite Z.add_0_l.\nrewrite Z.mod_mod by lia.\napply Z.mod_small.\nlia.\n}\nrewrite H; clear H.\ntransitivity (Binary.B754_nan 24 128 false pl e); [ | reflexivity].\nclear.\nreplace (Bits.join_bits 23 8 false (Z.pos pl) (2 ^ 8 - 1))\n   with (Bits.bits_of_binary_float 23 8 (Binary.B754_nan 24 128 false pl e)).\napply (Bits.binary_float_of_bits_of_binary_float 23 8 eq_refl eq_refl eq_refl).\nreflexivity.\n- (* B754_finite *)\nunfold Binary.Babs.\nclear.\nunfold Bits.b32_of_bits, Binary.Babs, Bits.bits_of_b32, Bits.bits_of_binary_float.\npose proof (bounded_mantissa _ _ _ _ e0).\ndestruct (0 <=? Z.pos m - 2 ^ 23) eqn:?H.\n+\napply Z.leb_le in H0.\nassert (Z.pos m - 2^23 < 2^23) by lia.\nreplace (Bits.join_bits 23 8 s (Z.pos m - 2 ^ 23)\n                 (e - (3 - 2 ^ (8 - 1) - (23 + 1)) + 1) mod  2 ^ 31)\n   with (Bits.bits_of_binary_float 23 8 (Binary.B754_finite 24 128 false m e e0)).\napply (Bits.binary_float_of_bits_of_binary_float 23 8 eq_refl eq_refl eq_refl).\nunfold Bits.bits_of_binary_float.\npose proof H0.\napply Z.leb_le in H2. rewrite H2. clear H2.\nforget (Z.pos m - 2^23)  as i.\nunfold Binary.bounded in e0.\nrewrite andb_true_iff in e0.\ndestruct e0 as [H' ?H].\nassert (-149 <= e). {\n clear - H'.\n unfold Binary.canonical_mantissa in H'.\napply Zeq_bool_eq in H'.\nunfold FLT.FLT_exp in H'.\nrewrite Digits.Zpos_digits2_pos in H'.\npose proof (Z.max_lub_r (Digits.Zdigits Zaux.radix2 (Z.pos m) + e - 24)\n      (3 - 128 - 24) e).\nspec H; lia.\n}\nclear H'.\napply Z.leb_le in H2.\nsimpl Z.sub.\nreplace (e - -149 + 1) with (e+150) by lia.\nunfold Bits.join_bits.\nrewrite !Z.shiftl_mul_pow2 by lia.\nrewrite Z.add_0_l.\nset (e' := e+150).\nrewrite Z.mul_add_distr_r.\nrewrite <- Z.add_assoc.\nrewrite Z.add_mod by (compute; lia).\nreplace (((if s then 2 ^ 8 else 0) * 2 ^ 23) mod 2 ^ 31)\n  with 0 by (destruct s; reflexivity).\nrewrite Z.add_0_l.\nrewrite Z.mod_mod by lia.\nrewrite (Z.mod_small); auto.\nsubst e'.\nlia.\n+\nreplace (Bits.join_bits 23 8 s (Z.pos m) 0 mod 2 ^ 31)\n with (Bits.join_bits 23 8 false (Z.pos m) 0).\nreplace (Bits.join_bits 23 8 false (Z.pos m) 0)\n   with (Bits.bits_of_binary_float 23 8 (Binary.B754_finite 24 128 false m e e0)).\napply (Bits.binary_float_of_bits_of_binary_float 23 8 eq_refl eq_refl eq_refl).\nunfold Bits.bits_of_binary_float.\nrewrite H0. auto.\nclear H0.\nunfold Bits.join_bits.\nrewrite Z.add_mod by (compute; lia).\nrewrite (Z.mod_small (Z.pos m)) by lia.\nrewrite !Z.add_0_r.\nreplace (Z.shiftl (if s then 2 ^ 8 else 0) 23 mod 2 ^ 31) with 0 by (destruct s; reflexivity).\nsimpl Z.shiftl.\nsymmetry.\napply Z.mod_small.\nlia.\nQed.\n\n\nLemma fabs_float32_lemma:\n  forall x: float32,\n  Float32.of_bits (Int.and (Float32.to_bits x) (Int.repr 2147483647)) =\n  Float32.abs x.\nProof.\nintros.\nTransparent Float32.of_bits.\nTransparent Float32.to_bits.\nTransparent Float32.abs.\nunfold Float32.of_bits, Float32.to_bits, Float32.abs.\nOpaque Float32.of_bits.\nOpaque Float32.to_bits.\nOpaque Float32.abs.\nrewrite and_repr.\nchange 2147483647 with (Z.ones 31).\nrewrite Z.land_ones by computable.\nrewrite Int.unsigned_repr\n by (pose proof (Z_mod_lt (Bits.bits_of_b32 x) (2 ^ 31) (eq_refl _)); rep_lia).\napply binary32_abs_lemma.\nQed.\n\nEnd FABS_STUFF.\n\nModule Single.\n\nDefinition fabs_single_spec :=\n DECLARE _fabs_single\n WITH x: float32\n PRE [ Tfloat F32 noattr]\n   PROP() PARAMS (Vsingle x) SEP()\n POST [ Tfloat F32 noattr ]\n   PROP() RETURN (Vsingle (Float32.abs x)) SEP().\n\nLemma body_fabs_single: semax_body Vprog Gprog f_fabs_single fabs_single_spec.\nProof.\nstart_function.\nforward.\nforward.\nforward.\nforward.\nforward.\nentailer!.\nf_equal.\napply FABS_STUFF.fabs_float32_lemma.\nQed.\nEnd Single.\n\nModule Float.\n\n (* This experiment shows what kind of error message you get\n   if you put the wrong LOCAL precondition.\n   In fact, Vfloat x is wrong, leading to an unsatisfying precondition,\n   it must be Vsingle. *)\n\nDefinition fabs_single_spec :=\n DECLARE _fabs_single\n WITH x: float\n PRE [ Tfloat F32 noattr]\n   PROP() PARAMS (Vfloat x) SEP()\n POST [ Tfloat F32 noattr ]\n   PROP() RETURN (Vfloat (Float.abs x)) SEP().\n\nLemma body_fabs_single: semax_body Vprog Gprog f_fabs_single fabs_single_spec.\nProof.\ntry (start_function; fail 99).\nAbort.\n\nEnd Float.\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/progs64/verif_union.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.20146755281813863}}
{"text": "\nRequire Import Coq.Lists.List.\nImport ListNotations.\n\nRequire Import Tactics.\nRequire Import Sequence.\nRequire Import Syntax.\nRequire Import Subst.\nRequire Import SimpSub.\nRequire Import Promote.\nRequire Import Hygiene.\nRequire Import Rules.\nRequire Import DerivedRules.\nRequire Defs.\nRequire Import Obligations.\nRequire Import Morphism.\nRequire Import DefsEquiv.\nRequire Import Equivalence.\n\nRequire Import ValidationUtil.\n\n\nLemma futureKind_valid : futureKind_obligation.\n  unfoldtop. autounfold with valid_hint.\n  intros G i k triv0 triv1 H0 H1.\n  valid_rewrite. \n  constructor.\n  apply tr_fut_kind_formation; eauto using deq_intro.\n  Qed.\n\nLemma futureKindEq_valid : futureKindEq_obligation.\n  unfoldtop. autounfold with valid_hint.\n  intros G i k l triv0 triv1 H1 H2.\n  valid_rewrite. \n  constructor.\n  apply tr_fut_kind_formation; eauto using deq_intro; eauto using deq.\nQed.\n\nLemma futureForm_valid : futureForm_obligation.\n  unfoldtop. autounfold with valid_hint.\n  intros G a triv0 H.\n  valid_rewrite. \n  constructor; eauto using deqtype_intro.\n  Qed.\n\nLemma futureEq_valid : futureEq_obligation.\n  unfoldtop. autounfold with valid_hint.\n  intros G a b triv0 H.\n  valid_rewrite.\n  constructor; eauto using deqtype_intro.\n  Qed.\n\nLemma futureFormUniv_valid : futureFormUniv_obligation.\n  unfoldtop. autounfold with valid_hint.\n  intros G a i triv0 triv1 H1 H2.\n  valid_rewrite. \n  constructor.\n  eapply tr_fut_formation_univ; eauto using deq_intro.\n  Qed.\n\nLemma futureEqUniv_valid : futureEqUniv_obligation.\n  unfoldtop. autounfold with valid_hint.\n  intros G a b i triv0 triv1 H1 H2.\n  valid_rewrite. \n  constructor.\n  eapply tr_fut_formation_univ; eauto using deq_intro.\n  Qed.\n\nLemma futureIntroOf_valid : futureIntroOf_obligation. \n  unfoldtop. autounfold with valid_hint.\n  intros G  a m triv0 H.\n  valid_rewrite. \n  constructor.\n  eapply tr_fut_intro; eauto using deq_intro.\nQed.\n\nLemma futureIntroEq_valid : futureIntroEq_obligation. \n  unfoldtop. autounfold with valid_hint.\n  intros G  a m triv0 H.\n  valid_rewrite. \n  constructor.\n  eapply tr_fut_intro; eauto using deq_intro.\nQed.\n\nLemma futureIntro_valid : futureIntro_obligation. \n  unfoldtop. autounfold with valid_hint.\n  intros G a m H.\n  valid_rewrite. \n  eapply tr_fut_intro; eauto using deq_intro.\nQed.\n\nLemma futureElimOf_valid : futureElimOf_obligation.\n  unfoldtop. autounfold with valid_hint.\n  intros G a b m p triv0 triv1 triv2 H0 H1 H2.\n  valid_rewrite.\n  constructor.\n  eapply tr_fut_elim; eauto using deq_intro; eauto using deqtype_intro.\nQed.\n\nLemma futureElimEq_valid : futureElimEq_obligation. \n unfoldtop. autounfold with valid_hint.\n  intros G a b m n p q triv0 triv1 triv2 H0 H1 H2.\n  valid_rewrite.\n  constructor.\n  eapply tr_fut_elim; eauto using deq_intro; eauto using deqtype_intro.\nQed.\n\nLemma futureElimIstype_valid : futureElimIstype_obligation. \n unfoldtop. autounfold with valid_hint.\n  intros G a b m triv0 triv1 triv2 H0 H1 H2.\n  valid_rewrite.\n  eapply tr_fut_elim_eqtype; eauto using deq_intro; eauto using deqtype_intro.\nQed.\n\nLemma futureElimEqtype_valid : futureElimEqtype_obligation. \n unfoldtop. autounfold with valid_hint.\n  intros G a b c m n triv0 triv1 triv2 H0 H1 H2.\n  valid_rewrite.\n  eapply tr_fut_elim_eqtype; eauto using deq_intro; eauto using deqtype_intro.\nQed.\n\nLemma futureEta_valid : futureEta_obligation. \n  unfoldtop. autounfold with valid_hint.\n  intros G a m triv0 H.\n  valid_rewrite.\n  constructor.\n  eapply tr_fut_eta; eauto using deq_intro.\nQed.\n\nLemma futureLeft_valid : futureLeft_obligation. \n unfoldtop. autounfold with valid_hint.\n  intros G1 G2 a b triv0 m H0 H1.\n  valid_rewrite.\n  match goal with |- tr ?G ?J =>\n                  assert (equivctx G\n    (G2 ++\n     hyp_tm (fut a) :: G1)\n                         ) as Hctx end.\n\n  { apply equivctx_refl. }\n  apply tr_fut_eta_hyp; auto.\n  eauto using deqtype_intro.\nQed.\n\nLemma tr_future_sub :\n  forall G a b,\n    tr (promote G) (dsubtype a b)\n    -> tr G (dsubtype (fut a) (fut b)).\nProof.\nintros G a b Ha.\napply tr_subtype_intro.\n  {\n  apply tr_fut_formation.\n  eapply tr_subtype_istype1; eauto.\n  }\n\n  {\n  apply tr_fut_formation.\n  eapply tr_subtype_istype2; eauto.\n  }\nsimpsub.\napply (tr_fut_ext _ _ (subst sh1 a) (subst sh1 a)).\n  {\n  eapply hypothesis; eauto using index_0.\n  }\n\n  {\n  eapply hypothesis; eauto using index_0.\n  }\nreplace (next (prev (var 0))) with (@subst1 obj (prev (var 0)) (next (var 0))).\n2:{\n  simpsub.\n  auto.\n  }\nreplace (fut (subst sh1 b)) with (subst1 (prev (var 0)) (fut (subst (sh 2) b))).\n2:{\n  simpsub.\n  auto.\n  }\napply (tr_fut_elim _ (var 0) (var 0) (subst sh1 a) (next (var 0)) (next (var 0)) (fut (subst (sh 2) b))).\n  {\n  eapply hypothesis; eauto using index_0.\n  }\n\n  {\n  cbn.\n  fold (promote G).\n  eapply (weakening _ [_] []).\n    {\n    cbn [length Dots.unlift].\n    simpsub.\n    auto.\n    }\n  \n    {\n    cbn [length Dots.unlift].\n    simpsub.\n    auto.\n    }\n  cbn [length Dots.unlift].\n  simpsub.\n  cbn [List.app].\n  eapply tr_subtype_istype1; eauto.\n  }\napply tr_fut_intro.\ncbn.\nfold (promote G).\neapply (weakening _ [_] [_]).\n  {\n  cbn [length Dots.unlift].\n  simpsub.\n  auto.\n  }\n\n  {\n  cbn [length Dots.unlift].\n  simpsub.\n  auto.\n  }\ncbn [length Dots.unlift].\nsimpsub.\ncbn [List.app].\napply (tr_subtype_elim _ (subst sh1 a)).\n  {\n  eapply (weakening _ [_] []).\n    {\n    cbn [length Dots.unlift].\n    simpsub.\n    auto.\n    }\n  \n    {\n    cbn [length Dots.unlift].\n    simpsub.\n    auto.\n    }\n  cbn [length Dots.unlift].\n  simpsub.\n  cbn [List.app].\n  exact Ha.\n  }\n\n  {\n  eapply hypothesis; eauto using index_0.\n  }\nQed.\n \n\nHint Rewrite def_fut def_letnext : prepare.\n\n\nLemma futureSub_valid : futureSub_obligation.\nProof.\nprepare.\nintros G a b ext0 H.\napply tr_future_sub; auto.\nQed.\n\n\nLemma futureElimOfLetnext_valid : futureElimOfLetnext_obligation.\nProof.\nprepare.\nintros G a b m p ext2 ext1 ext0 Ha Hm Hp.\neapply tr_fut_elim; eauto.\nQed.\n\n\nLemma futureElimOfLetnextNondep_valid : futureElimOfLetnextNondep_obligation.\nProof.\nprepare.\nintros G a b m p ext2 ext1 ext0 Ha Hm Hp.\nreplace b with (subst1 (prev m) (subst sh1 b)) by (simpsub; reflexivity).\neapply tr_fut_elim; eauto.\nQed.\n\n\nLemma futureElimIstypeLetnext_valid : futureElimIstypeLetnext_obligation.\nProof.\nprepare.\nintros G a b m ext2 ext1 ext0 Ha Hm Hb.\neapply tr_fut_elim_eqtype; eauto.\nQed.\n\n\nLemma futureExt_valid : futureExt_obligation.\nProof.\nprepare.\nintros G a m n ext2 ext1 ext0 Hm Hn Hmn.\neapply tr_fut_ext; eauto.\napply tr_fut_intro; auto.\nQed.\n", "meta": {"author": "kcrary", "repo": "istari", "sha": "42e71bc3bfba08542d005f27d100aa7537b1012b", "save_path": "github-repos/coq/kcrary-istari", "path": "github-repos/coq/kcrary-istari/istari-42e71bc3bfba08542d005f27d100aa7537b1012b/coq/ValidationFuture.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2014675528181386}}
{"text": "Require Import compcert.lib.Coqlib.\nRequire Import compcert.lib.Maps.\nRequire Import compcert.lib.Integers.\n\nRequire Import compcert.common.AST.\nRequire Import compcert.common.Values.\nRequire Import compcert.common.Globalenvs.\nRequire Import compcert.common.Memory.\nRequire Import compcert.common.Events.\nRequire Import compcert.common.Errors.\nRequire Import compcert.common.Switch.\nRequire Import compcert.common.Smallstep.\n\nRequire Import List.\nImport ListNotations.\nRequire Import Arith.\nRequire Import Ring.\n\nRequire Import StructTact.StructTactics.\nRequire Import StructTact.Util.\n\nRequire Import oeuf.Metadata.\nRequire Import oeuf.OpaqueTypes.\nRequire Import oeuf.MemInjProps.\n\nRequire Import oeuf.EricTact.\nRequire Import oeuf.StuartTact.\n\n(* Computation will be over higher level values, i.e. Constr and Close *)\n(* We will need a way to relate those to lower level values *)\n(* That relation will have type hval -> rval -> mem -> Prop *)\n(* since high level values will have to live in memory *)\n\nDefinition function_name := ident.\n\nInductive value :=\n| Constr (tag : int) (args : list value) (* A constructor applied to some values *)\n(* At this level we have a Z tag  *)\n(* corresponds with lower level switch semantics nicely *)\n| Close (f : function_name) (free : list value) (* a closure value *)\n(* free is the list of values closed over, referred to inside as upvars *)\n| Opaque (ty : opaque_type_name) (v : opaque_type_denote ty)\n.\n\n(* Thanks Stuart *)\nDefinition value_rect_mut (P : value -> Type) (Pl : list value -> Type)\n           (HConstr : forall tag args, Pl args -> P (Constr tag args))\n           (HClose : forall fname args, Pl args -> P (Close fname args))\n           (HOpaque :  forall ty v, P (Opaque ty v))\n    (Hnil :     Pl [])\n    (Hcons :    forall e es, P e -> Pl es -> Pl (e :: es))\n    (v : value) : P v :=\n    let fix go v :=\n        let fix go_list vs :=\n            match vs as vs_ return Pl vs_ with\n            | [] => Hnil\n            | v :: vs => Hcons v vs (go v) (go_list vs)\n            end in\n        match v as v_ return P v_ with\n        | Constr tag args => HConstr tag args (go_list args)\n        | Close f args => HClose f args (go_list args)\n        | Opaque ty v => HOpaque ty v\n        end in go v.\n\nDefinition value_rect_mut'\n        (P : value -> Type)\n        (Pl : list value -> Type)\n    (HConstr :  forall tag args, Pl args -> P (Constr tag args))\n    (HClose :   forall fname free, Pl free -> P (Close fname free))\n    (HOpaque :  forall ty v, P (Opaque ty v))\n    (Hnil :     Pl [])\n    (Hcons :    forall v vs, P v -> Pl vs -> Pl (v :: vs)) :\n    (forall v, P v) * (forall vs, Pl vs) :=\n    let fix go v :=\n        let fix go_list vs :=\n            match vs as vs_ return Pl vs_ with\n            | [] => Hnil\n            | v :: vs => Hcons v vs (go v) (go_list vs)\n            end in\n        match v as v_ return P v_ with\n        | Constr tag args => HConstr tag args (go_list args)\n        | Close fname free => HClose fname free (go_list free)\n        | Opaque ty v => HOpaque ty v\n        end in\n    let fix go_list vs :=\n        match vs as vs_ return Pl vs_ with\n        | [] => Hnil\n        | v :: vs => Hcons v vs (go v) (go_list vs)\n        end in\n    (go, go_list).\n\n(* Useful wrapper for `expr_rect_mut with (Pl := Forall P)` *)\nDefinition value_ind' (P : value -> Prop) \n           (HConstr : forall tag args, Forall P args -> P (Constr tag args))\n           (HClose : forall fname args, Forall P args -> P (Close fname args))\n           (HOpaque :  forall ty v, P (Opaque ty v))\n    (v : value) : P v :=\n    ltac:(refine (@value_rect_mut P (Forall P)\n        HConstr HClose HOpaque _ _ v); eauto).\n\n\n(* given an address, addresses of the nested values *)\nFixpoint arg_addrs (b : block) (ofs : int) (l : list value) : list (value * val) :=\n  match l with\n  | nil => nil\n  | v :: vs =>\n    let ofs' := Int.add ofs (Int.repr 4) in\n    (v, Vptr b ofs) :: arg_addrs b ofs' vs\n  end.\n\nFixpoint load_all (l : list (value * val)) (m : mem) : option (list (value * val)) :=\n  match l with\n  | nil => Some nil\n  | (hval,vaddr) :: rest =>\n    match Mem.loadv Mint32 m vaddr with\n    | None => None\n    | Some v' =>\n      match load_all rest m with\n      | None => None\n      | Some res => Some ((hval,v') :: res)\n      end\n    end\n  end.\n                     \n\n(* mapping of high level values to low level values *)\n(* everything is one pointer *)\nInductive value_inject {A B} (ge : Genv.t A B) (m : mem) : value -> val -> Prop :=\n| inj_constr :\n    (* a constructor is a pointer to the correct tag *)\n    (* and every value following that in memory is a value for that constructor *)\n    (* *(b,ofs) = tag *)\n    (* *(b,ofs+4) = pointer to first field *)\n    forall b ofs n values l',\n      Mem.loadv Mint32 m (Vptr b ofs) = Some (Vint n) -> (* correct tag *)\n      load_all (arg_addrs b (Int.add ofs (Int.repr 4)) values) m = Some l' -> (* one more deref for args *)\n      (forall a b, In (a,b) l' -> value_inject ge m a b) -> (* all args inject *)\n      value_inject ge m (Constr n values) (Vptr b ofs)\n| inj_closure :\n    forall b ofs bcode f fname values l',\n      Mem.loadv Mint32 m (Vptr b ofs) = Some (Vptr bcode Int.zero) ->\n      Genv.find_funct_ptr ge bcode = Some f -> (* legit pointer to some code *)\n      Genv.find_symbol ge fname = Some bcode -> (* name we have points to same code *)\n      load_all (arg_addrs b (Int.add ofs (Int.repr 4)) values) m = Some l' -> (* one more deref for args *)\n      (forall a b, In (a,b) l' -> value_inject ge m a b) -> (* all args inject *)\n      value_inject ge m (Close fname values) (Vptr b ofs)\n| inj_opaque : forall oty ov cv,\n        opaque_type_value_inject oty ov cv m ->\n        value_inject ge m (Opaque oty ov) cv\n.\n\n\nLemma load_all_inject :\n    forall l b ofs k args b' mi m m',\n      load_all (arg_addrs b (Int.add ofs k) args) m = Some l ->\n      Mem.inject mi m m' ->\n      mi b = Some (b',0) ->\n      exists l',\n        load_all (arg_addrs b' (Int.add ofs k) args) m' = Some l' /\\ list_forall2 (fun x y => fst x = fst y /\\ Val.inject mi (snd x) (snd y)) l l'.\nProof.\n  induction l; intros.\n  destruct args; simpl in H; inv H. simpl.\n  exists nil. split; eauto. econstructor; eauto.\n  repeat (break_match_hyp; try congruence).\n  destruct args. simpl in H. inv H.\n  simpl in H. repeat (break_match_hyp; try congruence).\n  invc H.\n  simpl. app Mem.load_inject Mem.load. rewrite Z.add_0_r in *.\n  collapse_match.\n  eapply IHl in Heqo0; eauto.\n  break_exists; break_and.\n  collapse_match.\n  eexists; split; eauto.\n  econstructor; eauto.\nQed.\n\nLemma list_forall2_in_backwards :\n  forall {A B : Type} (P : A -> B -> Prop) l l',\n    list_forall2 P l l' ->\n    forall elem',\n      In elem' l' ->\n      exists elem,\n        In elem l /\\ P elem elem'.\nProof.\n  induction 1; intros.\n  simpl in H. inv H.\n  simpl in H1. destruct H1. subst b1. eexists; split; eauto. simpl. left. reflexivity.\n  simpl. apply IHlist_forall2 in H1. break_exists. break_and.\n  eexists; split; eauto; right; eauto.\nQed.\n\nLemma load_all_hval_in :\n  forall args l b ofs m,\n    load_all (arg_addrs b ofs args) m = Some l ->\n    forall a x,\n      In (a,x) l ->\n      In a args.\nProof.\n  induction args; intros.\n  simpl in H. inv H. simpl in H0. inv H0.\n  simpl in H. repeat break_match_hyp; try congruence.\n  inv H. simpl in H0. destruct H0. inv H0.\n  simpl; left; reflexivity.\n  simpl; right; eauto.\nQed.\n\nLemma value_val_inject :\n  forall {F} (ge : Genv.t F unit) m v v',\n    value_inject ge m v v' ->\n    forall mi m' v0,\n      Val.inject mi v' v0 ->\n      Mem.inject mi m m' ->\n      same_offsets mi ->\n      globals_inj_same ge mi ->\n      value_inject ge m' v v0.\nProof.\n  induction v using value_ind'; intros; cycle 2.\n\n  { on >@value_inject, invc. fix_existT.  subst. econstructor.\n    on >Mem.inject, invc.  eapply opaque_type_value_val_inject; eauto. }\n\n\n  all: try solve [inv H]; (* handle opaque *)\n    inv H0; inv H1;\n      app Mem.loadv_inject Mem.loadv;\n      inv H7; app H3 (mi b); subst delta;\n        app load_all_inject load_all; repeat break_and;\n          econstructor; eauto; repeat rewrite Int.add_zero in *; try eassumption.\n\n  Focus 2.\n  rewrite Int.add_commut in *.\n  repeat rewrite Int.add_zero in *.\n  unfold same_offsets in *.\n  app H3 (mi bcode). subst delta0.\n  erewrite H4 in H16; eauto. inv H16. assumption.\n\n\n  \n  intros.\n  eapply list_forall2_in_backwards in H12; eauto.\n  break_exists. repeat break_and. destruct x0. simpl in H14. subst.\n  eapply H10 in H12.\n  rewrite Forall_forall in H. simpl in H15. eapply H; eauto.\n  eapply load_all_hval_in; eauto.\n    \n  intros. \n  eapply list_forall2_in_backwards in H14; eauto.\n  break_exists. repeat break_and. destruct x0. simpl in H17. subst.\n  eapply H12 in H14.\n  rewrite Forall_forall in H. simpl in H18. eapply H; eauto.\n  eapply load_all_hval_in; eauto.\n\n  Grab Existential Variables.\n  repeat (econstructor; eauto).\nQed.\n\n\nLemma value_inject_swap_ge :\n  forall {F F' V} (ge1 : Genv.t F V) (ge2 : Genv.t F' V),\n    forall m v v',\n      value_inject ge1 m v v' ->\n    (forall b f,\n        Genv.find_funct_ptr ge1 b = Some f ->\n        exists f',\n          Genv.find_funct_ptr ge2 b = Some f') ->\n    (forall fname b,\n        Genv.find_symbol ge1 fname = Some b ->\n        Genv.find_symbol ge2 fname = Some b) ->\n      value_inject ge2 m v v'.\nProof.\n  induction 1; intros.\n  econstructor; eauto.\n  eapply H5 in H0.\n  break_exists.\n  econstructor; eauto.\n  econstructor; eauto.\nQed.\n\nDefinition global_blocks_valid {A B : Type} (ge : Genv.t A B) (b : block) :=\n  Plt (Genv.genv_next ge) b.\n\nLemma global_block_find_symbol :\n  forall {A B} (ge : Genv.t A B) id b m,\n    Genv.find_symbol ge id = Some b ->\n    global_blocks_valid ge (Mem.nextblock m) ->\n    Plt b (Mem.nextblock m).\nProof.\n  intros.\n  unfold global_blocks_valid in *.\n  unfold Genv.find_symbol in H.\n  eapply Genv.genv_symb_range in H.\n  eapply Plt_trans; eauto.\nQed.\n\nLemma genv_next_ind :\n  forall {A B V} l l',\n    length l = length l' ->\n    forall  (ge : Genv.t A V) (tge : Genv.t B V),\n      Genv.genv_next ge = Genv.genv_next tge ->\n      Genv.genv_next (Genv.add_globals ge l) = Genv.genv_next (Genv.add_globals tge l').\nProof.\n  induction l; intros;\n    destruct l' eqn:?; simpl in *; try omega;\n      eauto.\n  subst.\n  eapply IHl; eauto.\n  unfold Genv.add_global. simpl. congruence.\nQed.\n\nLemma genv_next_transf :\n  forall {A B V} (p : AST.program A V) (tp : AST.program B V) (tf : A -> B),\n    transform_program tf p = tp ->\n    Genv.genv_next (Genv.globalenv p) = Genv.genv_next (Genv.globalenv tp).\nProof.\n  intros. unfold Genv.globalenv.\n  erewrite genv_next_ind; try reflexivity.\n  unfold transform_program in *.\n  subst tp. simpl.\n  rewrite list_length_map; reflexivity.\nQed.\n\nLemma transf_globdefs_length :\n  forall {A B V W} l l' (tf : A -> Errors.res B) (tv : V -> Errors.res W),\n    transf_globdefs tf tv l = Errors.OK l' ->\n    length l = length l'.\nProof.\n  induction l; intros.\n  simpl in H. inv H. reflexivity.\n  simpl in *. repeat (break_match_hyp; try congruence; inv H).\n  eapply Errors.bind_inversion in H3. break_exists. break_and.\n  inv H3. simpl.\n  erewrite IHl; eauto.\n  eapply Errors.bind_inversion in H3. break_exists. break_and.\n  inv H3. simpl.\n  erewrite IHl; eauto.\nQed.    \n\nLemma genv_next_transf_partial :\n  forall {A B V} (p : AST.program A V) (tp : AST.program B V) (tf : A -> Errors.res B),\n    transform_partial_program tf p = Errors.OK tp ->\n    Genv.genv_next (Genv.globalenv p) = Genv.genv_next (Genv.globalenv tp).\nProof.\n  intros. unfold Genv.globalenv.\n  erewrite genv_next_ind; try reflexivity.\n  unfold transform_partial_program in *.\n  unfold transform_partial_program2 in *.\n  eapply Errors.bind_inversion in H.\n  break_exists. break_and.\n  inv H0. simpl.\n  eapply transf_globdefs_length; eauto.\nQed.\n\n(*Definition global_blocks_valid {A B} (ge : Genv.t A B) (m : mem) : Prop :=\n  forall b f v,\n    Genv.find_funct_ptr ge b = Some f \\/ Genv.find_var_info ge b = Some v -> Plt b (Mem.nextblock m).*)\n\nDefinition no_future_pointers (m : mem) : Prop :=\n  forall b ofs b' ofs' q n,\n    Plt b (Mem.nextblock m) ->\n    ZMap.get ofs (Mem.mem_contents m) !! b = Fragment (Vptr b' ofs') q n ->\n    Plt b' (Mem.nextblock m).\n\n\nLemma load_all_extends :\n  forall {F V} (ge : Genv.t F V) l m l',\n    load_all l m = Some l' ->\n    (forall a b, In (a,b) l' -> value_inject ge m a b) ->\n    forall m',\n      Mem.extends m m' ->\n      (forall a b, In (a,b) l' -> value_inject ge m' a b) ->\n      exists l0,\n        load_all l m' = Some l0 /\\ (forall a b, In (a,b) l0 -> value_inject ge m' a b).\nProof.\n    induction l; intros.\n  - simpl in H. inv H. exists nil.\n    simpl. split; auto. \n  - simpl in H.\n    repeat (break_match_hyp; try congruence).\n    subst.\n    invc H.\n    eapply IHl in Heqo0; eauto.\n\n    + app Mem.loadv_extends Mem.loadv.\n      break_exists; break_and. eexists; split.\n        { simpl. repeat collapse_match. reflexivity. }\n\n      intros. simpl in H7. destruct H7; cycle 1.\n        { eapply H6. assumption. }\n      invc H7.\n      assert (value_inject ge m' a v1). {\n        eapply H2. simpl. left. auto.\n      }\n      assert (v1 = b). {\n        inv H7; inv H5; try congruence.\n        - (* opaque case *)\n          on >@value_inject, invc.\n          fwd eapply opaque_type_inject_defined; eauto.  congruence.\n      } subst.\n      assumption.\n\n    + intros. eapply H0. simpl. right. assumption.\n\n    + intros. eapply H2. simpl. right. auto.\nQed.\n\nLemma load_all_result_decomp :\n  forall args b ofs m l,\n    load_all (arg_addrs b ofs args) m = Some l ->\n    exists r',\n      split l = (args,r') /\\ length args = length r'.\nProof.\n  induction args; intros.\n  simpl in *. inv H. simpl. eauto.\n  simpl in *. repeat (break_match_hyp; try congruence).\n  inv H. simpl.\n  eapply IHargs in Heqo0.\n  break_exists. break_and. rewrite H0.\n  eexists; split; eauto. simpl. eauto.\nQed.\n\nLemma list_forall2_combine :\n  forall {A B : Type}  l r,\n    length l = length r ->\n  forall (P : A -> B -> Prop),\n    (list_forall2 P l r <->\n    (forall (x : A) (y : B),\n      In (x,y) (combine l r) ->\n      P x y)).\nProof.\n  intros; split.\n  induction 1; intros.\n  simpl in H0. inversion H0. simpl.\n  simpl in H2. destruct H2; try inv H2;\n                 eauto.\n  generalize dependent r.\n  induction l; intros;\n  destruct r; simpl in H; try congruence;\n  econstructor; eauto.\n  eapply H0. simpl. left. auto.\n  eapply IHl. inv H. eauto.\n  intros. eapply H0. simpl. right. auto.\nQed.\n\nLemma value_inject_mem_extends :\n  forall {F V} (ge : Genv.t F V) m m' v v',\n    value_inject ge m v v' ->\n    Mem.extends m m' ->\n    value_inject ge m' v v'.\nProof.\n  intros until v.\n  induction v using value_rect_mut with (Pl := fun vs => forall vs',\n                                                   list_forall2 (value_inject ge m) vs vs' ->\n                                                   Mem.extends m m' ->\n                                                   list_forall2 (value_inject ge m') vs vs'\n                                        ); intros;\n    inv H;\n    try solve [econstructor; eauto].\n\n  Focus 3. {\n    on >Mem.extends, invc. on >@value_inject, invc. fix_existT. subst.\n    assert (same_offsets inject_id).\n      { unfold same_offsets, inject_id. simpl. intros. congruence. }\n    econstructor.\n    eapply opaque_type_value_val_inject; eauto.\n    - destruct v'; econstructor; eauto.\n      + reflexivity.\n      + rewrite Int.add_zero. reflexivity.\n  } Unfocus.\n\n  all: app Mem.loadv_extends Mem.loadv;\n    app (@load_all_extends F V) load_all;\n  try solve [econstructor; eauto;\n             inv H3; eauto].\n\n  intros.\n  eapply load_all_result_decomp in H5.\n  break_exists. break_and.\n  specialize (IHv x0).\n  copy (split_combine l').\n  rewrite H5 in H9. subst l'.\n  eapply list_forall2_combine; eauto. \n  eapply IHv; eauto.\n  erewrite list_forall2_combine; eauto. \n\n  intros.\n  eapply load_all_result_decomp in H6.\n  break_exists. break_and.\n  specialize (IHv x0).\n  copy (split_combine l').\n  rewrite H6 in H11. subst l'.\n  eapply list_forall2_combine; eauto. \n  eapply IHv; eauto.\n  erewrite list_forall2_combine; eauto. \nQed.\n\nDefinition env_inject {A B} (hlenv : PTree.t value) (llenv : PTree.t val) (ge : Genv.t A B)(m : mem) : Prop :=\n  forall id v,\n    PTree.get id hlenv = Some v ->\n    exists v',\n      PTree.get id llenv = Some v' /\\ value_inject ge m v v'.\n  \n\nLemma load_all_val :\n  forall l b ofs m l' n v,\n    nth_error l n = Some v ->\n    load_all (arg_addrs b ofs l) m = Some l' ->\n    exists v',\n      Mem.loadv Mint32 m (Vptr b (Int.add ofs (Int.repr (4 * Z.of_nat n)))) = Some v' /\\ In (v,v') l'.\nProof.\n  induction l; intros;\n    destruct n; simpl in H; inv H; subst.\n  * simpl in H0.\n    repeat break_match_hyp; try congruence.\n    simpl. replace (Int.add ofs (Int.repr 0)) with ofs by ring.\n    eexists; split; eauto. invc H0. simpl.\n    left. auto.\n  * simpl in H0. repeat break_match_hyp; try congruence.\n    inv H0.\n    eapply IHl in H; eauto.\n    repeat break_exists; repeat break_and.\n    replace (Int.add (Int.add ofs (Int.repr 4)) (Int.repr (4 * Z.of_nat n)))\n    with  (Int.add ofs (Int.repr (4 * Z.of_nat (S n)))) in H.\n    \n    eexists. split. eauto.\n    simpl. right. auto.\n\n    (* rest is annoying math over Z/nat/int *)\n    replace (4 * Z.of_nat (S n)) with (4 + 4 * Z.of_nat n)%Z.\n    rewrite Int.add_assoc.\n    f_equal.\n    rewrite Int.add_unsigned.\n    rewrite (Int.unsigned_repr 4).\n    rewrite Int.unsigned_repr_eq.\n    eapply Int.eqm_samerepr.\n    unfold Int.eqm.\n    assert (Int.modulus > 0).\n    unfold Int.modulus, two_power_nat, Int.wordsize, Wordsize_32.wordsize.\n    simpl. omega.\n    remember (Int.eqmod_mod Int.modulus H3) as ie.\n    eapply Int.eqmod_add. econstructor; eauto. instantiate (1 := 0).\n    omega.\n    eapply Int.eqmod_mod.\n    omega. unfold Int.max_unsigned.\n    simpl. omega.\n    rewrite Nat2Z.inj_succ.\n    omega.\nQed.\n\n(* (* number of bytes to store a value *) *)\nDefinition size_bytes (v : value) : Z :=\n  match v with\n  | Close _ l => (4 * Z.of_nat (length l)) + 4\n  | Constr _ l => (4 * Z.of_nat (length l)) + 4\n  | Opaque _ _ => 0\n  end.\n\nDefinition rest (v : value ) : list value :=\n  match v with\n  | Close _ l => l\n  | Constr _ l => l\n  | Opaque _ _ => []\n  end.\n\nFixpoint store_list (b : block) (ofs : Z) (l : list val) (m : mem) : option mem :=\n  match l with\n  | nil => Some m\n  | v :: vs =>\n    match Mem.storev Mint32 m (Vptr b (Int.repr ofs)) v with\n    | Some m' => store_list b (ofs + 4) vs m'\n    | None => None\n    end\n  end.\n\nDefinition first_byte {A B} (ge : Genv.t A B) (v : value) : option val :=\n  match v with\n  | Close fname _ =>\n    match Genv.find_symbol ge fname with\n    | Some b =>\n      match Genv.find_funct_ptr ge b with\n      | Some _ => Some (Vptr b Int.zero)\n      | None => None\n      end\n    | None => None\n    end\n  | Constr tag _ => Some (Vint tag)\n  | Opaque _ _ => None\n  end.\n\nDefinition store_value {A B} (ge : Genv.t A B) (v : value) (m : mem) (l : list val) : option (val * mem) :=\n  let sz := size_bytes v in (* find total size for value *)\n  let (m',b) := Mem.alloc m 0 sz in (* allocate that much space *)\n  match first_byte ge v with\n  | Some v' =>\n    match Mem.storev Mint32 m' (Vptr b Int.zero) v' with\n    | Some m'' =>\n      match store_list b 4 l m'' with\n      | Some m''' =>\n        Some (Vptr b Int.zero, m''')\n      | None => None\n      end\n    | None => None\n    end\n  | None => None\n  end.\n\nLtac clean :=\n  match goal with\n  | [ H : Some _ = Some _ |- _ ] => invc H\n  | [ H : False |- _ ] => inv H\n  end; try congruence.\n\n\n\nDefinition meta_map := list (ident * metadata).\n\nInductive public_value {F V} (P : AST.program F V) (M : meta_map) : value -> Prop :=\n| PvConstr : forall tag args,\n        Forall (public_value P M) args ->\n        public_value P M (Constr tag args)\n| PvClose : forall fname free m,\n        In fname (prog_public P) ->\n        Forall (public_value P M) free ->\n        In (fname, m) M ->\n        length free = m_nfree m ->\n        public_value P M (Close fname free)\n| PvOpaque : forall ty v, public_value P M (Opaque ty v).\n\nLemma prog_public_public_value : forall F V F' V'\n        (p : AST.program F V) (p' : AST.program F' V') M,\n    prog_public p = prog_public p' ->\n    forall v,\n    public_value p M v ->\n    public_value p' M v.\nintros until v.\ninduction v using value_rect_mut with\n    (Pl := fun vs =>\n        Forall (public_value p M) vs ->\n        Forall (public_value p' M) vs);\nintros Apub; invc Apub; econstructor; eauto.\n- find_rewrite. auto.\nQed.\n\nLemma prog_public_public_value' : forall F V F' V'\n        (p : AST.program F V) (p' : AST.program F' V') M,\n    prog_public p = prog_public p' ->\n    forall v,\n    public_value p' M v ->\n    public_value p M v.\nintros until v.\ninduction v using value_rect_mut with\n    (Pl := fun vs =>\n        Forall (public_value p' M) vs ->\n        Forall (public_value p M) vs);\nintros Bpub; invc Bpub; econstructor; eauto.\n- find_rewrite. auto.\nQed.\n\nLemma transf_public_value : forall A B V (f : A -> B) (p : AST.program A V) M v,\n    public_value p M v ->\n    public_value (AST.transform_program f p) M v.\nintros.\neapply prog_public_public_value; try eassumption; eauto.\nQed.\n\nLemma transf_public_value' : forall A B V (f : A -> B) (p : AST.program A V) M v,\n    public_value (AST.transform_program f p) M v ->\n    public_value p M v.\nintros.\neapply prog_public_public_value'; try eassumption; eauto.\nQed.\n\nLemma transf_partial_public_value : forall A B V (f : A -> res B)\n        (p : AST.program A V) p' M,\n    AST.transform_partial_program f p = OK p' ->\n    forall v,\n    public_value p M v ->\n    public_value p' M v.\nintros.\neapply prog_public_public_value; try eassumption.\nsymmetry. eauto using transform_partial_program_public.\nQed.\n\nLemma transf_partial_public_value' : forall A B V (f : A -> res B)\n        (p : AST.program A V) p' M,\n    AST.transform_partial_program f p = OK p' ->\n    forall v,\n    public_value p' M v ->\n    public_value p M v.\nintros.\neapply prog_public_public_value'; try eassumption.\nsymmetry. eauto using transform_partial_program_public.\nQed.\n\n\n\n\nDefinition change_only_fnames (P : function_name -> function_name -> Prop) :\n        value -> value -> Prop :=\n    let fix go v1 v2 :=\n        let fix go_list vs1 vs2 :=\n            match vs1, vs2 with\n            | [], [] => True\n            | v1 :: vs1, v2 :: vs2 => go v1 v2 /\\ go_list vs1 vs2\n            | _, _ => False\n            end in\n        match v1, v2 with\n        | Constr tag1 args1, Constr tag2 args2 =>\n                tag1 = tag2 /\\ go_list args1 args2\n        | Close f1 free1, Close f2 free2 =>\n                P f1 f2 /\\ go_list free1 free2\n        | Opaque oty1 ov1, Opaque oty2 ov2 =>\n                existT _ oty1 ov1 = existT _ oty2 ov2\n        | _, _ => False\n        end in go.\n\nDefinition change_only_fnames_list (P : function_name -> function_name -> Prop) :=\n    let go := change_only_fnames P in\n    let fix go_list vs1 vs2 :=\n        match vs1, vs2 with\n        | [], [] => True\n        | v1 :: vs1, v2 :: vs2 => go v1 v2 /\\ go_list vs1 vs2\n        | _, _ => False\n        end in go_list.\n\nLtac refold_change_only_fnames P := fold (change_only_fnames P) in *.\n\nLemma change_only_fnames_list_Forall : forall P vs1 vs2,\n    change_only_fnames_list P vs1 vs2 <->\n    Forall2 (change_only_fnames P) vs1 vs2.\ninduction vs1; destruct vs2; split; intro HH; invc HH.\n- constructor.\n- constructor.\n- constructor; eauto. firstorder.\n- constructor; eauto. firstorder.\nQed.\n\n\n\nLemma ptr_block_valid : forall A B (ge : Genv.t A B) m hv b ofs,\n    value_inject ge m hv (Vptr b ofs) ->\n    Mem.valid_block m b.\ninversion 1.\n\n- eapply Mem.valid_access_valid_block.\n  eapply Mem.valid_access_implies.\n  + eapply Mem.load_valid_access. eauto.\n  + constructor.\n\n- eapply Mem.valid_access_valid_block.\n  eapply Mem.valid_access_implies.\n  + eapply Mem.load_valid_access. eauto.\n  + constructor.\n\n- eapply opaque_type_ptr_block_valid; eauto.\nQed.\n\n", "meta": {"author": "uwplse", "repo": "oeuf", "sha": "f3e4d236465ba872d1f1b8229548fa0edf8f7a3f", "save_path": "github-repos/coq/uwplse-oeuf", "path": "github-repos/coq/uwplse-oeuf/oeuf-f3e4d236465ba872d1f1b8229548fa0edf8f7a3f/src/HighValues.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2014675528181386}}
{"text": "Require Import CoqlibC Errors.\nRequire Import Integers Floats AST Linking.\nRequire Import ValuesC Memory Events Globalenvs Smallstep.\nRequire Import Op Locations MachC Conventions ConventionsC AsmC.\nRequire Import Asmgen Asmgenproof0.\nRequire Import sflib.\n(* newly added *)\nRequire Export Asmgenproof.\nRequire Import SimModSem SimMemExt SimSymbId MemoryC ValuesC MemdataC LocationsC StoreArguments Conventions1C.\n\nRequire Import Skeleton Mod ModSem SimMod SimSymb SimMem AsmregsC MatchSimModSem.\nRequire Import JunkBlock StoreArgumentsProps.\nRequire SoundTop.\n\nLocal Opaque Z.mul.\nLocal Existing Instance main_args_some.\n\nSet Implicit Arguments.\n\nSection PRESERVATION.\n\nVariable skenv_link: SkEnv.t.\nVariable prog: Mach.program.\nVariable tprog: Asm.program.\nLet md_src: Mod.t := (MachC.module prog return_address_offset).\nLet md_tgt: Mod.t := (AsmC.module tprog).\nHypothesis (INCLSRC: SkEnv.includes skenv_link (Mod.sk md_src)).\nHypothesis (INCLTGT: SkEnv.includes skenv_link (Mod.sk md_tgt)).\nHypothesis (WF: SkEnv.wf skenv_link).\n\nHypothesis TRANSF: match_prog prog tprog.\n\nLet ge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_src)) prog).\nLet tge := (SkEnv.revive (SkEnv.project skenv_link (Mod.sk md_tgt)) tprog).\n\nVariable sm_link: SimMem.t.\n\nDefinition msp: ModSemPair.t :=\n  ModSemPair.mk (SM := SimMemExt)\n                (Mod.modsem (md_src) skenv_link)\n                (Mod.modsem (md_tgt) skenv_link)\n                (SimSymbId.mk md_src md_tgt) sm_link.\n\nDefinition get_rs (ms: Mach.state) : Mach.regset :=\n  match ms with\n  | Mach.State _ _ _ _ rs _ => rs\n  | Callstate _ _ rs _ => rs\n  | Returnstate _ rs _ => rs\n  end.\n\nRecord agree_eq (ms: Mach.regset) (sp: val) (rs: Asm.regset) (sg: signature): Prop :=\n  mkagree\n    { agree_sp: rs#SP = sp;\n      agree_sp_def: sp <> Vundef;\n      agree_mregs_less:\n        forall (r: mreg) (IN: In (R r) (regs_of_rpairs (loc_arguments sg))),\n          Val.lessdef (ms r) (rs#(preg_of r));\n      agree_mregs_eq:\n        forall (r: mreg) (NOTIN: ~ In (R r) (regs_of_rpairs (loc_arguments sg))),\n          (ms r) = (rs#(preg_of r));\n    }.\n\nDefinition set_regset (rs0 rs1: Mach.regset) (sg: signature) (mr: mreg) : val :=\n  if Loc.notin_dec (R mr) (regs_of_rpairs (loc_arguments sg)) then rs1 mr else rs0 mr.\n\nDefinition set_regset_undef (rs: Mach.regset) (sg: signature) (mr: mreg) : val :=\n  if Loc.notin_dec (R mr) (regs_of_rpairs (loc_arguments sg)) then Vundef else rs mr.\n\nInductive match_init_data init_sp init_ra\n          init_rs_src init_sg_src init_rs_tgt : Prop :=\n| match_init_data_intro\n    (INITRA: init_ra = init_rs_tgt RA)\n    (INITRAPTR: <<TPTR: Val.has_type (init_ra) Tptr>> /\\ <<RADEF: init_ra <> Vundef>>)\n    (INITRS: agree_eq init_rs_src init_sp init_rs_tgt init_sg_src )\n    (SIG: exists fd, (Genv.find_funct tge) (init_rs_tgt PC) = Some (Internal fd) /\\ fd.(fn_sig) = init_sg_src /\\ init_sg_src.(sig_cstyle)).\n\nInductive stack_base (initial_parent_sp initial_parent_ra: val): list Mach.stackframe -> Prop :=\n| stack_base_dummy:\n    stack_base initial_parent_sp initial_parent_ra\n      ((dummy_stack initial_parent_sp initial_parent_ra)::[])\n| stack_base_cons\n    fr ls\n    (TL: stack_base initial_parent_sp initial_parent_ra ls):\n    stack_base initial_parent_sp initial_parent_ra (fr::ls).\n\nInductive match_states\n          (idx: nat) (st_src0: MachC.state) (st_tgt0: AsmC.state)\n          (sm0: SimMem.t): Prop :=\n| match_states_intro\n    init_sp init_ra\n    (* (initial_parent_sp_ptr : ValuesC.is_real_ptr (init_sp)) *)\n    (initial_parent_ra_ptr: Val.has_type init_ra Tptr)\n    (initial_parent_ra_def: init_ra <> Vundef)\n    (initial_parent_ra_junk: forall blk ofs (RAVAL: init_ra = Vptr blk ofs),\n        ~ Plt blk (Genv.genv_next skenv_link))\n    (* (initial_parent_ra_junk1: tge.(Genv.find_funct) init_ra = None) *)\n    (STACKWF: stack_base init_sp init_ra (get_stack st_src0.(MachC.st)))\n    (INITDATA: match_init_data\n                 init_sp init_ra st_src0.(MachC.init_rs) st_src0.(init_sg) st_tgt0.(init_rs))\n    (MATCHST: Asmgenproof.match_states ge st_src0.(MachC.st) st_tgt0)\n    (* (SPPTR: ValuesC.is_real_ptr (st_tgt0.(init_rs) RSP)) *)\n    (MCOMPATSRC: (MachC.get_mem st_src0.(MachC.st)) = sm0.(SimMem.src))\n    (MCOMPATTGT: (get_mem st_tgt0) = sm0.(SimMem.tgt))\n    (IDX: measure st_src0.(MachC.st) = idx).\n\nLemma asm_step_dstep init_rs st0 st1 tr\n      (STEP: Asm.step skenv_link tge st0 tr st1):\n    Simulation.DStep (modsem skenv_link tprog) (mkstate init_rs st0) tr (mkstate init_rs st1).\nProof.\n  econs.\n  - eapply modsem_determinate; et.\n  - econs; auto.\nQed.\n\nLemma asm_star_dstar init_rs st0 st1 tr\n      (STEP: star Asm.step skenv_link tge st0 tr st1):\n    Simulation.DStar (modsem skenv_link tprog) (mkstate init_rs st0) tr (mkstate init_rs st1).\nProof.\n  induction STEP; econs; eauto. eapply asm_step_dstep; auto.\nQed.\n\nLemma asm_plus_dplus init_rs st0 st1 tr\n      (STEP: plus Asm.step skenv_link tge st0 tr st1):\n    Simulation.DPlus (modsem skenv_link tprog) (mkstate init_rs st0) tr (mkstate init_rs st1).\nProof.\n  inv STEP. econs; eauto.\n  - eapply asm_step_dstep; eauto.\n  - eapply asm_star_dstar; eauto.\nQed.\n\nTheorem make_match_genvs :\n  SimSymbId.sim_skenv (SkEnv.project skenv_link (Mod.sk md_src))\n                      (SkEnv.project skenv_link (Mod.sk md_tgt)) ->\n  Genv.match_genvs (match_globdef (fun _ f tf => transf_fundef f = OK tf) eq prog) ge tge.\nProof. subst_locals. eapply SimSymbId.sim_skenv_revive; eauto. Qed.\n\nLemma transf_function_sig\n      fd_src fd_tgt\n      (TRANS: transf_function fd_src = OK fd_tgt):\n  fd_src.(Mach.fn_sig) = fd_tgt.(fn_sig).\nProof. repeat unfold transf_function, bind, transl_function in *. des_ifs. Qed.\n\nTheorem sim_modsem: ModSemPair.sim msp.\nProof.\n  eapply match_states_sim with (match_states := match_states)\n                               (match_states_at := top4); eauto; ii; ss.\n\n  - apply lt_wf.\n  - eapply SoundTop.sound_state_local_preservation.\n\n  - inv INITTGT; cycle 1.\n    { ss. des_safe. inv SAFESRC. inv SIMARGS; ss. }\n    des. inv SAFESRC. destruct sm_arg, args_src; ss. inv SIMARGS; ss. clarify.\n    exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE. des.\n\n    assert (SRCSTORE: exists rs_src m_src,\n               StoreArguments.store_arguments src rs_src (typify_list vs_src (sig_args (fn_sig fd))) (fn_sig fd) m_src /\\\n           agree_eq rs_src (Vptr (Mem.nextblock src)\n                          Ptrofs.zero) rs (fn_sig fd) /\\ Mem.extends m_src m0).\n    { inv TYP.\n      exploit store_arguments_parallel_extends.\n      - eapply typify_has_type_list. eauto.\n      - exploit SkEnv.revive_incl_skenv; try eapply INCLTGT; eauto. i. des. inv WF.\n        eapply WFPARAM in H; eauto.\n      - instantiate (1:= typify_list vs_src (sig_args (fn_sig fd))).\n        eapply lessdef_list_typify_list; eauto. erewrite lessdef_list_length; eauto.\n      - eapply MWF.\n      - inv STORE. eauto.\n      - i. des. exists (set_regset rs_src (to_mregset rs) (fn_sig fd)).\n        esplits; eauto.\n        + clear - ARGTGT. inv ARGTGT. econs; eauto.\n          eapply extcall_arguments_same; eauto.\n          i. unfold set_regset. des_ifs.\n          eapply Loc.notin_not_in in n. contradiction.\n        + inv STORE. econs; eauto.\n          * inv MWF. rewrite mext_next. eauto.\n          * intros X. inv X.\n          * i. unfold set_regset. des_ifs.\n            eapply val_inject_id. eapply AGREE.\n          * i. unfold set_regset. des_ifs.\n            eapply LocationsC.Loc_not_in_notin_R in NOTIN. contradiction.\n    }\n\n    destruct SRCSTORE as [rs_src [m_src [SRCSTORE [AGREE EXTENDS]]]]. inv AGREE.\n    exists (MachC.mkstate\n              rs_src (fn_sig fd)\n              (Callstate\n                 [dummy_stack (Vptr (Mem.nextblock src) Ptrofs.zero) (rs RA)]\n                 fptr_src rs_src (assign_junk_blocks m_src n))).\n    inv FPTR; ss.\n    esplits; auto; ss.\n    + inv TYP0. clear_tac.\n      assert(SIG2: fn_sig fd = (Mach.fn_sig fd0)).\n      { hexploit (Genv.find_funct_transf_partial_genv SIMGE); eauto. i; des.\n        folder. ss; try unfold bind in *; des_ifs.\n        symmetry. eapply transf_function_sig; eauto.\n      }\n      econs; eauto; ss.\n      * econs; eauto; ss; eauto with congruence.\n      * ii. erewrite (agree_mregs_eq0 mr) in *; auto. unfold NW. apply NNPP. intro T.\n        exploit PTRFREE; eauto.\n        { instantiate (1:= preg_of mr). intro U. contradict T.\n          unfold is_junk_value in U. unfold is_junk_value. des_ifs. des. split; ss.\n          - erewrite Mem.valid_block_extends; eauto.\n          - erewrite Mem.valid_block_extends; eauto. eapply assign_junk_block_extends; et.\n        }\n        i. des; try (by destruct mr; clarify). rewrite Asm.to_preg_to_mreg in *. clarify.\n    + instantiate (1:= SimMemExt.mk (assign_junk_blocks m_src n) (assign_junk_blocks m0 n)).\n      econs; try eapply RADEF; ss; eauto.\n      * econs; eauto.\n      * econs; ss; eauto.\n      * econs; eauto; ss; try by (econs; eauto).\n        { eapply assign_junk_block_extends; et. }\n        econs; eauto. i.\n        destruct (classic (In (R r) (regs_of_rpairs (loc_arguments (fn_sig fd))))); eauto.\n        erewrite agree_mregs_eq0; auto.\n\n  - ss. des. inv SAFESRC. inv SIMARGS; ss. destruct sm_arg; ss. clarify.\n    exploit make_match_genvs; eauto. { apply SIMSKENV. } intro SIMGE.\n    hexploit (Genv.find_funct_transf_partial_genv SIMGE); eauto. i; des. ss; unfold bind in *; des_ifs. rename f into fd_tgt.\n    inv TYP.\n    assert(SIG: fn_sig fd_tgt = (Mach.fn_sig fd)).\n    { hexploit (Genv.find_funct_transf_partial_genv SIMGE); eauto. i; des.\n      folder. ss; try unfold bind in *; des_ifs.\n      symmetry. eapply transf_function_sig; eauto.\n    }\n    assert (exists rs_tgt m_tgt,\n               (<<STORE: AsmC.store_arguments tgt rs_tgt\n                                              (typify_list vs_tgt (sig_args (Mach.fn_sig fd)))\n                                              (* (Args.vs args_tgt) *)\n                                              (Mach.fn_sig fd) m_tgt>>) /\\\n               (<<RSPC: rs_tgt PC = fptr_tgt>>) /\\\n               (<<RSRA: rs_tgt RA = Vnullptr>>) /\\\n               (<<PTRFREE: forall pr (PTR: ~ is_junk_value m0 (assign_junk_blocks m0 n) (rs_tgt pr)),\n                   (<<INARG: exists mr,\n                       (<<MR: to_mreg pr = Some mr>>) /\\\n                       (<<ARG: In (R mr) (regs_of_rpairs (loc_arguments (Mach.fn_sig fd)))>>)>>) \\/\n                   (<<INPC: pr = PC>>) \\/\n                   (<<INRSP: pr = RSP>>)>>)).\n    { exploit StoreArgumentsProps.store_arguments_progress.\n      - instantiate (2:=typify_list vs_tgt (sig_args (Mach.fn_sig fd))).\n        eapply typify_has_type_list. erewrite <- lessdef_list_length; eauto.\n      - exploit SkEnv.revive_incl_skenv; try eapply INCLTGT; eauto. i. des. inv WF.\n        eapply WFPARAM in H0. eauto. ss. rewrite <- SIG. ss.\n      - instantiate (1:= n). i. des.\n        exists ((to_pregset (set_regset_undef rs0 (Mach.fn_sig fd)))\n                  #PC <- fptr_tgt\n                  #RA <- Vnullptr\n                  #RSP <- (Vptr (Mem.nextblock tgt) Ptrofs.zero)).\n        esplits; eauto.\n        + split; ss. inv STR. econs; eauto. eapply extcall_arguments_same; eauto. i.\n          { assert (NNIN: ~ Loc.notin (R r) (regs_of_rpairs (loc_arguments (Mach.fn_sig fd)))).\n            { intros X. eapply Loc.notin_not_in; eauto. }\n            unfold set_regset_undef, to_pregset, to_mregset, Pregmap.set, to_preg, preg_of, to_mreg in *.\n            destruct r; eauto; des_ifs; try contradiction.\n          }\n        + i.\n          assert (NNIN: forall mr, ~ Loc.notin (R mr) (regs_of_rpairs (loc_arguments (Mach.fn_sig fd))) -> In (R mr) (regs_of_rpairs (loc_arguments (Mach.fn_sig fd)))).\n          { intros mr NIN. clear - NIN.\n            eapply NNPP. intros X.\n            eapply LocationsC.Loc_not_in_notin_R in X. des. contradiction. }\n          clear - NNIN PTR. unfold set_regset_undef, to_pregset, to_mregset, Pregmap.set, to_preg, preg_of, to_mreg in *.\n          destruct pr; des_ifs; ss; eauto. exfalso. apply PTR. ss.\n    }\n    des. eexists. econs; eauto; swap 1 2.\n    + folder. inv FPTR; ss. eauto.\n    + congruence.\n    + rewrite RSRA. econs; ss.\n    + rewrite RSRA. ss.\n    + rewrite SIG. econs; eauto. rewrite <- LEN. symmetry. eapply lessdef_list_length. eauto.\n    + erewrite <- transf_function_sig; eauto.\n    + erewrite <- transf_function_sig; eauto. ii. hexploit PTRFREE0; et.\n      ii. apply PTR. unfold is_junk_value in *. des_ifs.\n      unfold Mem.valid_block. unfold Mem.valid_block in H0.\n      rewrite assign_junk_blocks_nextblock in *.\n      inv STORE. inv STORE0. inv H1. rewrite <- NB0. rewrite <- NB in *.\n      erewrite Mem.nextblock_alloc; eauto.\n      erewrite (Mem.nextblock_alloc src) in H0; eauto.\n      inv MWF. rewrite <- mext_next. des; esplits; eauto; try xomega.\n  - inv MATCH; ss. destruct st_src0, st_tgt0, sm0. ss. inv MATCHST; ss.\n\n  - ss. inv CALLSRC. inv MATCH. inv INITDATA. inv MATCHST. ss. destruct st_tgt0. ss. clarify. des.\n    inv FPTR; ss. destruct (rs0 PC) eqn:PCEQ; ss. des_ifs.\n\n    exploit Asmgenproof0.extcall_arguments_match; eauto. intros TGRARGS. des.\n    exploit Mem.free_parallel_extends; eauto. intros TGTFREE. des. esplits; ss.\n    + econs; eauto.\n      * r in TRANSF. r in TRANSF.\n        exploit (SimSymbId.sim_skenv_revive TRANSF); eauto.\n        { apply SIMSKENV. }\n        intro GE. apply (fsim_external_funct_id GE); ss.\n      * inv STACKS; ss.\n        -- inv STACKWF; [|inv TL]. inv ATLR; auto; exfalso; auto.\n        -- destruct ra; ss; try inv H0. inv ATLR. ss.\n      * inv AG. rewrite agree_sp0. clarify.\n    + instantiate (1:= SimMemExt.mk m1 m2'). econs; ss; eauto.\n    + ss.\n\n  - inv AFTERSRC. ss. des. clarify. destruct st_tgt0, st. inv MATCH. inv MATCHST.\n    inv INITDATA. inv SIMRET; ss. destruct sm_ret. ss. clarify.\n    exploit Mem_unfree_parallel_extends; try eapply UNFREE; eauto.\n    intros TGTUNFREE. des. esplits; auto.\n    + econs; ss; eauto.\n      * exists skd. esplits; eauto. replace (r PC) with fptr; auto. inv FPTR; ss.\n      * inv AG. rewrite agree_sp0. eauto.\n    + instantiate (1:= SimMemExt.mk m1 m2'). inv INITRS. inv AG.\n      econs; ss; eauto; econs; eauto.\n      * econs; eauto.\n      * unfold loc_external_result, regset_after_external, Mach.regset_after_external.\n        apply agree_set_other; auto. apply agree_set_pair; auto.\n        econstructor; ss; eauto. intros. rewrite to_preg_to_mreg.\n        destruct (Conventions1.is_callee_save r0) eqn:T; eauto.\n\n  - ss. inv FINALSRC. des. clarify. destruct st_tgt0, st. inv MATCH. inv MATCHST.\n    inv INITDATA. destruct sm0. ss. clarify.\n    inv STACKWF; [|inv TL]. inv STACKS; [|inv H7; ss]. inv INITRS.\n    exploit Mem.free_parallel_extends; eauto. intros TGTFREE. des.\n    esplits; auto.\n    + econs; ss; eauto.\n      * replace (r PC) with (init_rs0 RA).\n        { clear - initial_parent_ra_junk. unfold external_state. des_ifs.\n          exploit initial_parent_ra_junk; ss; eauto.\n          unfold Genv.find_funct_ptr, Genv.find_def in *. des_ifs.\n          eapply Genv.genv_defs_range in Heq1. ss.\n        }\n        inv ATPC; auto. exfalso. auto.\n      * inv ATPC; auto. exfalso. auto.\n      * unfold Genv.find_funct, Genv.find_funct_ptr. des_ifs.\n        exfalso. exploit Genv.genv_defs_range; eauto. eapply initial_parent_ra_junk; ss.\n      * inv AG. i.\n        { eapply Val.lessdef_trans.\n          - erewrite <- agree_mregs_eq0; auto. ii.\n            eapply loc_args_callee_save_disjoint; eauto.\n          - eauto.\n        }\n      * inv AG. rewrite agree_sp0. ss.\n    + econs; simpl; ss.\n      * ss. inv AG. auto.\n      * instantiate (1:= SimMemExt.mk _ _). ss.\n      * ss.\n    + ss.\n\n  - left; i. ss. esplits.\n    + eapply MachC.modsem_receptive; et.\n\n    + i. inv STEPSRC. inv MATCH. set (INITDATA0 := INITDATA). inv INITDATA0.\n      inv INITRAPTR. inv INITRS0. clarify.\n      exploit step_simulation; ss; try apply agree_sp_def0; eauto.\n      { eapply make_match_genvs; eauto. apply SIMSKENV. }\n      i. des; ss; esplits; auto; clarify.\n      * left. instantiate (1 := mkstate st_tgt0.(init_rs) S2'). ss.\n        destruct st_tgt0. eapply asm_plus_dplus; eauto.\n      * instantiate (1 := SimMemExt.mk (MachC.get_mem (MachC.st st_src1)) (get_mem S2')).\n        econs; ss; eauto.\n        { instantiate (1:=init_rs st_tgt0 RSP).\n          destruct st_src0, st_src1. clear - STEP STACKWF NOTDUMMY.\n          inv STEP; ss; clarify.\n          - econs. ss.\n          - inv STACKWF; ss.\n        }\n        rewrite <- INITRS. rewrite <- INITFPTR. auto.\n      * right. split; eauto. apply star_refl.\n      * instantiate (1 := SimMemExt.mk (MachC.get_mem (MachC.st st_src1)) (get_mem st_tgt0.(st))).\n        econs; ss; eauto.\n        { instantiate (1:=init_rs st_tgt0 RSP).\n          destruct st_src0, st_src1. clear - STEP STACKWF NOTDUMMY. inv STEP; ss; clarify.\n          - econs. ss.\n          - inv STACKWF; ss.\n        }\n        rewrite <- INITRS. rewrite <- INITFPTR. auto.\n\n  Unshelve.\n    all: ss.\nQed.\n\nEnd PRESERVATION.\n\n\n\nSection SIMMOD.\n\nVariable prog: Mach.program.\nVariable tprog: program.\nHypothesis TRANSL: match_prog prog tprog.\nDefinition mp: ModPair.t := mk_mp (MachC.module prog return_address_offset) (AsmC.module tprog).\n\nTheorem sim_mod: ModPair.sim mp.\nProof.\n  econs; ss.\n  - r. eapply Sk.match_program_eq; eauto. ii. destruct f1; ss.\n    + clarify. right. unfold bind in MATCH. des_ifs. esplits; eauto.\n      unfold transf_function, transl_function, bind in *. des_ifs.\n    + clarify. left. esplits; eauto.\n  - ii. inv SIMSKENVLINK. eapply sim_modsem; eauto.\nQed.\n\nEnd SIMMOD.\n", "meta": {"author": "snu-sf", "repo": "CompCertM", "sha": "1bf2113b2381df604a3abcce7711af1f154d1620", "save_path": "github-repos/coq/snu-sf-CompCertM", "path": "github-repos/coq/snu-sf-CompCertM/CompCertM-1bf2113b2381df604a3abcce7711af1f154d1620/x86/AsmgenproofC.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.20134094193311802}}
{"text": "Require Import VST.floyd.base2.\nRequire Import VST.floyd.client_lemmas.\nRequire Import VST.floyd.fieldlist.\nRequire Import VST.floyd.type_induction.\nRequire Import VST.floyd.nested_pred_lemmas.\nImport compcert.lib.Maps.\nOpen Scope Z.\n\nModule Type ACR_DEC.\n\n  Parameter align_compatible_rec_dec:\n    forall {cs: compspecs},\n      forall t z, {align_compatible_rec cenv_cs t z} + {~ align_compatible_rec cenv_cs t z}.\n\nEnd ACR_DEC.\n\nModule align_compatible_rec_dec: ACR_DEC.\n\nSection align_compatible_rec_dec.\n\nContext {cs: compspecs}.\n\nDefinition dec_type := sigT (fun P: Z -> Prop => forall z: Z, {P z} + {~ P z}).\n\nDefinition dec_by_value (ch: memory_chunk): dec_type :=\n  existT (fun P: Z -> Prop => forall z: Z, {P z} + {~ P z}) \n   (fun z => (Memdata.align_chunk ch | z))\n   (fun z => Zdivide_dec (Memdata.align_chunk ch) z (*Memdata.align_chunk_pos _*)).\n\nDefinition dec_False: dec_type :=\n  existT (fun P: Z -> Prop => forall z: Z, {P z} + {~ P z}) (fun z => False) (fun z => right (fun H => H)).\n\nDefinition dec_True: dec_type :=\n  existT (fun P: Z -> Prop => forall z: Z, {P z} + {~ P z}) (fun z => True) (fun z => left I).\n\nFixpoint cons_in_list {A} (a: A) (al' al: list A) (H: forall x, In x al' -> In x al) (bl: list {x:A| In x al'}) : list {x: A | In x al} :=\n  match bl with\n  | nil => nil\n  | exist x i :: bl0 =>exist _ x (H x i)  :: cons_in_list a al' al H bl0\n  end.\n\nFixpoint make_in_list {A} (al: list A) : list {x: A | In x al} := \n  match al as ax return (al = ax -> list {x : A | In x ax}) with\n           | nil => fun _ => nil\n           | a::al' => fun H: al = a::al' =>\n                      exist _ a (or_introl eq_refl) ::\n                         eq_rect al (fun l : list A => list {x : A | In x l}) \n                          (cons_in_list a al' al (fun (x : A) (H0 : In x al') =>\n                                 eq_ind_r (fun al0 : list A => In x al0) (in_cons _ _ _ H0) H)\n                               (make_in_list al'))\n                        (a :: al') H\n           end (eq_refl _).\n\nLemma in_make_in_list: forall {A} (a: A) (al: list A) H,\n   In (exist (fun x => In x al) a H) (make_in_list al).\nProof.\ninduction al; intros.\ninv H.\ndestruct H.\nsubst a0.\nsimpl.\nleft; auto.\nunfold make_in_list; fold @make_in_list.\nright.\nspecialize (IHal i).\nunfold eq_rect.\nforget (make_in_list al) as bl.\nunfold eq_ind_r.\nunfold eq_ind.\nsimpl.\ninduction bl.\ninv IHal.\ndestruct IHal.\nsubst a1.\nleft. \napply exist_ext; auto.\nspecialize (IHbl H).\nunfold cons_in_list; fold @cons_in_list.\ndestruct a1.\nright. auto.\nQed.\n\nLemma field_type_in_members_strong:\n forall i t m\n  (PLAIN: plain_members m = true),\n   Ctypes.field_type i m = Errors.OK t ->\n          In (Member_plain i t) m.\nProof.\ninduction m as [|[|]]; intros.\ninv H.\nsimpl in H.\nif_tac in H. subst. inv H. left; auto.\nright. apply IHm; auto.\ninv PLAIN.\nQed.\n\nLemma align_compatible_dec_aux:\n   forall n t, (rank_type cenv_cs t < n)%nat ->\n    forall z, {align_compatible_rec cenv_cs t z} + {~ align_compatible_rec cenv_cs t z}.\nProof.\ninduction n; intros; [ lia | ].\nrename H into Hrank.\ndestruct t  as [ | [ | | | ] [ | ]| [ | ] | [ | ] | | | | | ] eqn:Ht; intros;\ntry solve [\nclear IHn Hrank;\nmatch goal with |- context [align_compatible_rec _ ?t _] =>\nevar (ch: memory_chunk);\nassert (access_mode t = By_value ch) by (subst ch; reflexivity);\n(destruct (Zdivide_dec (Memdata.align_chunk ch) z);\n   [left; econstructor; try reflexivity; eassumption\n   |right;  contradict n; inv n; inv H0; auto])\nend];\ntry solve [right; intro H; inv H; inv H0].\n* (* Tarray *)\nspecialize (IHn t0).\nsimpl in Hrank. spec IHn; [lia | ]. clear Hrank.\npose proof (Zrange_pred_dec (fun ofs => align_compatible_rec cenv_cs t0 (z + sizeof t0 * ofs))).\nspec H.\nintro; apply IHn.\nspecialize (H 0 z0).\ndestruct H as [H|H]; [left|right].\n+\neapply align_compatible_rec_Tarray; intros.\napply H; auto.\n+\ncontradict H.\nintros.\neapply align_compatible_rec_Tarray_inv in H.\napply H.\nsplit; try lia.\n* (* Tstruct *)\ndestruct (cenv_cs ! i) eqn:?H;\n [ | right; intro H0; inv H0; [inv H1 | congruence]].\ndestruct (plain_members (co_members c)) eqn:?PLAIN;\n   [ | right; intro Hx; inv Hx; [ discriminate | congruence]].\nsimpl in Hrank. rewrite H in Hrank.\npose (FO id := match Ctypes.field_offset cenv_cs id (co_members c) with\n                      | Errors.OK (z0, Full) => z0 | _ => 0 end).\npose (D := fun x: {it: member | In it (co_members c)} =>\n                align_compatible_rec cenv_cs (type_member (proj1_sig x)) (z + FO (name_member (proj1_sig x)))).\nassert (H1: forall x, {D x} + {~ D x}). {\n subst D. intros. destruct x as [[id t0|] ?].\n2:{ exfalso. clear - i0 PLAIN. \n   induction (co_members c) as [|[|]]; simpl in *; try discriminate; auto. destruct i0; auto. discriminate.\n }\n simpl.\n apply IHn.\n assert (H1:= rank_union_member cenv_cs _ a _ _ cenv_consistent H i0).\n simpl in H1. rewrite H in H1. lia.\n}\ndestruct (Forall_dec D H1 (make_in_list (co_members c))) as [H2|H2]; clear H1; [left|right].\n+\n eapply align_compatible_rec_Tstruct.\n eassumption. auto.\n assert (H1 := proj1 (Forall_forall _ _) H2); clear H2.\n intros.\n specialize (H1 (exist _ (Member_plain i0 t0) (field_type_in_members_strong _ _ _ PLAIN H0))).\n specialize (H1 (in_make_in_list _ _ _)).\n subst D.\n simpl in H1.\n replace z0 with (FO i0).\n apply H1.\n unfold FO. rewrite H2. auto.\n+\n contradict H2.\n apply Forall_forall.\n intros.\n subst D. simpl.\n destruct x as [[id t0|] ?].\n2:{ exfalso. clear - i0 PLAIN. \n   induction (co_members c) as [|[|]]; simpl in *; try discriminate; auto. destruct i0; auto. discriminate.\n }\n eapply align_compatible_rec_Tstruct_inv in H2; try eassumption.\n instantiate (1:=id). simpl.\n pose proof (get_co_members_no_replicate i).\n unfold get_co in H1. rewrite H in H1. unfold members_no_replicate in H1.\n clear - i0 H1 PLAIN.\n induction (co_members c) as [|[|]]; [ | | discriminate]. inv i0. simpl.\n if_tac. subst. \n simpl in H1. destruct (id_in_list id0 (map name_member m)) eqn:?; try discriminate.\n destruct i0. inv H. auto.\n apply id_in_list_false in Heqb.\n exfalso. apply Heqb. apply (in_map name_member) in H. apply H.\n apply IHm. auto.\n destruct i0. inv H0. contradiction. auto.\n simpl in H1. destruct (id_in_list id0 (map name_member m)) eqn:?; try discriminate.\n auto.\n unfold FO; simpl.\n clear - i0 PLAIN.\n assert (in_members id (co_members c)). unfold in_members. apply (in_map name_member) in i0; auto.\n pose proof (plain_members_field_offset _ PLAIN _ _ H). rewrite H0. auto.\n* (* Tunion *)\ndestruct (cenv_cs ! i) eqn:?H;\n [ | right; intro H0; inv H0; [inv H1 | congruence]].\ndestruct (plain_members (co_members c)) eqn:?PLAIN;\n   [ | right; intro Hx; inv Hx; [ discriminate | congruence]].\nsimpl in Hrank. rewrite H in Hrank.\npose (D := fun x: {it: member | In it (co_members c)} =>\n                align_compatible_rec cenv_cs (type_member (proj1_sig x)) z).\nassert (H1: forall x, {D x} + {~ D x}). {\n subst D. intros. destruct x as [[id t0|] ?].\n2:{ exfalso. clear - i0 PLAIN. \n   induction (co_members c) as [|[|]]; simpl in *; try discriminate; auto. destruct i0; auto. discriminate.\n }\n simpl.\n apply IHn.\n assert (H1:= rank_union_member cenv_cs _ a _ _ cenv_consistent H i0).\n simpl in H1. rewrite H in H1. lia.\n}\ndestruct (Forall_dec D H1 (make_in_list (co_members c))) as [H2|H2]; clear H1; [left|right].\n+\n eapply align_compatible_rec_Tunion.\n eassumption. auto.\n assert (H1 := proj1 (Forall_forall _ _) H2); clear H2.\n intros.\n specialize (H1 (exist _ (Member_plain i0 t0) (field_type_in_members_strong _ _ _ PLAIN H0))).\n specialize (H1 (in_make_in_list _ _ _)).\n apply H1.\n+\n contradict H2.\n apply Forall_forall.\n intros.\n subst D. simpl.\n destruct x as [[id t0|] ?].\n2:{ exfalso. clear - i0 PLAIN. \n   induction (co_members c) as [|[|]]; simpl in *; try discriminate; auto. destruct i0; auto. discriminate.\n }\n eapply align_compatible_rec_Tunion_inv in H2; try eassumption.\n instantiate (1:=id). simpl.\n pose proof (get_co_members_no_replicate i).\n unfold get_co in H1. rewrite H in H1. unfold members_no_replicate in H1.\n clear - i0 H1 PLAIN.\n induction (co_members c) as [|[|]]; [ | | discriminate]. inv i0. simpl.\n if_tac. subst. \n simpl in H1. destruct (id_in_list id0 (map name_member m)) eqn:?; try discriminate.\n destruct i0. inv H. auto.\n apply id_in_list_false in Heqb.\n exfalso. apply Heqb. apply (in_map name_member) in H. apply H.\n apply IHm; auto.  \n destruct i0. inv H0. contradiction. auto.\n simpl in H1. destruct (id_in_list id0 (map name_member m)) eqn:?; try discriminate.\n auto.\nQed.\n\nLemma align_compatible_rec_dec: forall t z, {align_compatible_rec cenv_cs t z} + {~ align_compatible_rec cenv_cs t z}.\nProof.\nintros.\napply align_compatible_dec_aux with (S (rank_type cenv_cs t)).\nlia.\nQed.\n\nEnd align_compatible_rec_dec.\n\nEnd align_compatible_rec_dec.\n\nLemma align_compatible_dec: forall {cs: compspecs} t p, {align_compatible t p} + {~ align_compatible t p}.\nProof.\n  intros.\n  destruct p; try solve [left; unfold align_compatible; simpl; tauto].\n  simpl.\n  apply align_compatible_rec_dec.align_compatible_rec_dec.\nQed.", "meta": {"author": "PrincetonUniversity", "repo": "VST", "sha": "7d3133f3ff626e3c98bec2bd603ac74af2aff6d9", "save_path": "github-repos/coq/PrincetonUniversity-VST", "path": "github-repos/coq/PrincetonUniversity-VST/VST-7d3133f3ff626e3c98bec2bd603ac74af2aff6d9/floyd/align_compatible_dec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6548947290421276, "lm_q2_score": 0.3073580105206753, "lm_q1q2_score": 0.20128714101886508}}
{"text": "Require Import Core.Core Core.Notations Core.Tactics Types\n        Exec.Der_write_tags (* BCT.Exec *).\nFrom ExtLib.Structures Require Import Monad MonadWriter.\nFrom ExtLib.Data Require Import Monads.OptionMonad.\n\nRequire Export Types.\nRequire Export ExtLib.Structures.Monad.\nFrom ExtLib.Data Require Export Monads.OptionMonad.\n\nOpen Scope monad.\n\n(*Definition primitive_decoder td ls : option (list int * Z) :=\n    match ls with\n    | [] => None\n    | _ => ber_check_tags td ls >>=\n                        fun x => let c := tag_consumed x in \n                              let l := tag_length x in \n                              if (Zlength ls - c <? l)\n                              then None \n                              else let y := skipn (Z.to_nat c) ls in\n                                    Some (y, c + 1)    \n    end.*)\n\n(* writes tags, copies ls and outputs the number of encoded bytes *)\n(* Definition primitive_encoder td ls : errW1 asn_enc_rval :=\n  x <- der_write_tags td  ;; \n  tell ls ;;\n  ret (encode (Zlength ls + encoded x)). *)\n\nDefinition ZeroChar := Byte.repr 48.\n\nDefinition bool_of_byte (b : byte) := \n  if (b == default_byte)%byte then false else true.\nDefinition byte_of_bool (b : bool) := Byte.repr (if b then 255 else 0).\nDefinition int_of_bool (b : bool) := Int.repr (if b then 255 else 0).\nDefinition bool_of_int (i : int) := \n  if (i == 0)%int then false else true.\n\n(* Find composite *)\nFixpoint find_cs (id : ident) cs : option composite_definition :=\n  match cs with\n  | Composite i s_u m a :: css => if (i =? id)%positive\n                             then Some (Composite i s_u m a)\n                             else find_cs id css\n  | [] => None\n  end.\n\n", "meta": {"author": "asosyuk", "repo": "asn1verification", "sha": "55395d63c2dcd512a28d9cd42d788e12f91e7641", "save_path": "github-repos/coq/asosyuk-asn1verification", "path": "github-repos/coq/asosyuk-asn1verification/asn1verification-55395d63c2dcd512a28d9cd42d788e12f91e7641/src/Lib/Lib.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.2012557079716178}}
{"text": "From iris.program_logic Require Export weakestpre.\nFrom iris.heap_lang Require Export lang.\nFrom iris.algebra Require Import excl agree csum.\nFrom iris.heap_lang Require Import notation par proofmode.\nFrom iris.proofmode Require Import proofmode.\nFrom iris_examples.barrier Require Import proof specification.\nFrom iris.prelude Require Import options.\n\nDefinition one_shotR (Σ : gFunctors) (F : oFunctor) :=\n  csumR (exclR unitO) (agreeR $ laterO $ oFunctor_apply F (iPropO Σ)).\nDefinition Pending {Σ F} : one_shotR Σ F := Cinl (Excl ()).\nDefinition Shot {Σ} {F : oFunctor} (x : oFunctor_apply F (iPropO Σ)) : one_shotR Σ F :=\n  Cinr $ to_agree $ Next $ x.\n\nClass oneShotG (Σ : gFunctors) (F : oFunctor) :=\n  one_shot_inG :> inG Σ (one_shotR Σ F).\nDefinition oneShotΣ (F : oFunctor) : gFunctors :=\n  #[ GFunctor (csumRF (exclRF unitO) (agreeRF (▶ F))) ].\nGlobal Instance subG_oneShotΣ {Σ F} : subG (oneShotΣ F) Σ → oneShotG Σ F.\nProof. solve_inG. Qed.\n\nDefinition client : val :=\n  λ: \"fM\" \"fW1\" \"fW2\",\n  let: \"b\" := newbarrier #() in\n  (\"fM\" #() ;; signal \"b\") ||| ((wait \"b\" ;; \"fW1\" #()) ||| (wait \"b\" ;; \"fW2\" #())).\n\nSection proof.\nLocal Set Default Proof Using \"Type*\".\nContext `{!heapGS Σ, !barrierG Σ, !spawnG Σ, !oneShotG Σ F}.\nContext (N : namespace).\nLocal Notation X := (oFunctor_apply F (iPropO Σ)).\n\nDefinition barrier_res γ (Φ : X → iProp Σ) : iProp Σ :=\n  (∃ x, own γ (Shot x) ∗ Φ x)%I.\n\nLemma worker_spec e γ l (Φ Ψ : X → iProp Σ) :\n  recv N l (barrier_res γ Φ) -∗ (∀ x, Φ x -∗ WP e {{ _, Ψ x }}) -∗\n  WP wait #l ;; e {{ _, barrier_res γ Ψ }}.\nProof.\n  iIntros \"Hl He\". wp_apply (wait_spec with \"Hl\"); simpl.\n  iDestruct 1 as (x) \"[#Hγ Hx]\".\n  wp_seq. iApply (wp_wand with \"[Hx He]\"); [by iApply \"He\"|].\n  iIntros (v) \"?\"; iExists x; by iSplit.\nQed.\n\nContext (P : iProp Σ) (Φ Φ1 Φ2 Ψ Ψ1 Ψ2 : X -n> iPropO Σ).\nContext {Φ_split : ∀ x, Φ x -∗ (Φ1 x ∗ Φ2 x)}.\nContext {Ψ_join  : ∀ x, Ψ1 x -∗ Ψ2 x -∗ Ψ x}.\n\nLemma P_res_split γ : barrier_res γ Φ -∗ barrier_res γ Φ1 ∗ barrier_res γ Φ2.\nProof.\n  iDestruct 1 as (x) \"[#Hγ Hx]\".\n  iDestruct (Φ_split with \"Hx\") as \"[H1 H2]\". by iSplitL \"H1\"; iExists x; iSplit.\nQed.\n\nLemma Q_res_join γ : barrier_res γ Ψ1 -∗ barrier_res γ Ψ2 -∗ ▷ barrier_res γ Ψ.\nProof.\n  iDestruct 1 as (x) \"[#Hγ Hx]\"; iDestruct 1 as (x') \"[#Hγ' Hx']\".\n  iAssert (▷ (x ≡ x'))%I as \"Hxx\".\n  { iCombine \"Hγ\" \"Hγ'\" as \"Hγ2\". iClear \"Hγ Hγ'\".\n    rewrite own_valid csum_validI /= agree_validI agree_equivI later_equivI /=.\n    rewrite -{2}[x]oFunctor_map_id -{2}[x']oFunctor_map_id.\n    assert (HF : oFunctor_map F (cid, cid) ≡ oFunctor_map F (iProp_fold (Σ:=Σ) ◎\n        iProp_unfold, iProp_fold (Σ:=Σ) ◎ iProp_unfold)).\n    { apply ne_proper; first by apply _.\n      by split; intro; simpl; symmetry; apply iProp_fold_unfold. }\n    rewrite (HF x). rewrite (HF x').\n    rewrite !oFunctor_map_compose. iNext. by iRewrite \"Hγ2\". }\n  iNext. iRewrite -\"Hxx\" in \"Hx'\".\n  iExists x; iFrame \"Hγ\". iApply (Ψ_join with \"Hx Hx'\").\nQed.\n\nLemma client_spec_new (fM fW1 fW2 : val) :\n  WP fM #() {{ _, ∃ x, Φ x }} -∗\n  □ (∀ x, Φ1 x -∗ WP fW1 #() {{ _, Ψ1 x }}) -∗\n  □ (∀ x, Φ2 x -∗ WP fW2 #() {{ _, Ψ2 x }}) -∗\n  WP client fM fW1 fW2 {{ _, ∃ γ, barrier_res γ Ψ }}.\nProof using All.\n  iIntros \"/= Hf #Hf1 #Hf2\"; rewrite /client.\n  iMod (own_alloc (Pending : one_shotR Σ F)) as (γ) \"Hγ\"; first done.\n  wp_lam. wp_pures. wp_apply (newbarrier_spec N (barrier_res γ Φ)); auto.\n  iIntros (l) \"[Hr Hs]\".\n  set (workers_post (v : val) := (barrier_res γ Ψ1 ∗ barrier_res γ Ψ2)%I).\n  wp_smart_apply (par_spec  (λ _, True)%I workers_post with \"[Hf Hs Hγ] [Hr]\").\n  - wp_lam. wp_bind (fM #()). iApply (wp_wand with \"Hf\").\n    iIntros (v) \"HP\"; iDestruct \"HP\" as (x) \"HP\". wp_seq.\n    iMod (own_update with \"Hγ\") as \"Hx\".\n    { by apply (cmra_update_exclusive (Shot x)). }\n    iApply (signal_spec with \"[- $Hs]\"); last auto.\n    iExists x; auto.\n  - iDestruct (recv_weaken with \"[] Hr\") as \"Hr\"; first by iApply P_res_split.\n    iMod (recv_split with \"Hr\") as \"[H1 H2]\"; first done.\n    wp_smart_apply (par_spec (λ _, barrier_res γ Ψ1)%I\n                       (λ _, barrier_res γ Ψ2)%I with \"[H1] [H2]\").\n    + wp_smart_apply (worker_spec with \"H1\"); auto.\n    + wp_smart_apply (worker_spec with \"H2\"); auto.\n    + auto.\n  - iIntros (_ v) \"[_ [H1 H2]]\". iDestruct (Q_res_join with \"H1 H2\") as \"?\". auto.\nQed.\nEnd proof.\n", "meta": {"author": "pavel-ivanov-rnd", "repo": "iris-heaplang-experiments", "sha": "a283a53fe994672f7a6dbdaefa0d4eedd044b733", "save_path": "github-repos/coq/pavel-ivanov-rnd-iris-heaplang-experiments", "path": "github-repos/coq/pavel-ivanov-rnd-iris-heaplang-experiments/iris-heaplang-experiments-a283a53fe994672f7a6dbdaefa0d4eedd044b733/theories/barrier/example_joining_existentials.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.20125569650910097}}
{"text": "From Undecidability.L Require Import Tactics.LTactics.\nFrom Undecidability.L.Datatypes Require Import Lists LVector LSum LProd LFinType LNat.\nFrom Complexity.Complexity Require Import NP Definitions Monotonic Subtypes.\nFrom Undecidability.L.Functions Require Import EqBool.\nFrom Undecidability.L.TM Require Import TapeFuns.\nFrom Complexity.L.TM Require Import CompCode.\n\n\nFrom Undecidability.TM Require Import TM_facts CodeTM.\nFrom Undecidability.TM.Single Require Import EncodeTapes StepTM.\n\nFrom Complexity.TM Require Import M2MBounds PrettyBounds.SizeBounds.\nFrom Undecidability Require Import TM.Util.VectorPrelim.\nFrom Complexity.Libs Require Import PSLCompat.\n\nUnset Printing Coercions.\n\n(*Import EncodeTapes DecodeTapes Single.StepTM ProgrammingTools Combinators Decode.*)\n\n\n(*From Undecidability Require Import MultiUnivTimeSpaceSimulation. *)\nFrom Complexity.NP Require Import TMGenNP_fixed_mTM M_multi2mono.\n\nSet Default Proof Using \"Type\".\nSection LMGenNP_to_TMGenNP_mTM.\n\n\n  Context (sig:finType) (n:nat) `{R__sig : encodable sig}  (M : TM sig (S n)).\n  Let M__mono := M__mono M.\n  \n  Local Arguments Canonical_Rel : simpl never. \n  Local Arguments loopM : clear implicits.\n  Local Arguments loopM {_ _ } _ _ _.\n  Import L_facts.\n  Import EqBool.\n\n  (* From L/TM/Encoding.v *)\n  Lemma sizeOfTape_by_size (t:(tape sig)) :\n    sizeOfTape t <= size (enc t).\n  Proof.\n    unfold enc;cbn.\n    destruct t;cbn [tapeToList sizeOfTape length size].\n    all:rewrite ?app_length,?rev_length. all:cbn [length].\n    all:ring_simplify. all:try rewrite !size_list_enc_r. all:try nia.\n  Qed.\n  Lemma sizeOfmTapes_by_size (t:tapes sig n) :\n    sizeOfmTapes t <= size (enc t).\n  Proof.\n    setoid_rewrite enc_vector_eq. rewrite Lists.size_list.\n    erewrite <- sumn_map_le_pointwise with (f1:=fun _ => _). 2:{ intros. setoid_rewrite <- sizeOfTape_by_size. reflexivity. }\n    rewrite sizeOfmTapes_max_list_map. unfold MaxList.max_list_map. rewrite max_list_sumn.\n    etransitivity. 2:now apply Nat.le_add_r. apply sumn_map_le_pointwise. intros. apply Nat.le_add_r.\n  Qed.\n  \n  Lemma TMGenNP_mTM_to_TMGenNP_singleTM :\n    mTMGenNP_fixed M ⪯p TMGenNP_fixed (projT1 M__mono).\n  Proof.\n    subst M__mono.\n    evar (f__steps : nat*nat*nat -> nat). evar (f__nice : nat*nat*nat -> nat).\n    enough (Hf__nice : f__steps <=c f__nice).\n    unfold mTMGenNP_fixed,mTMGenNP_fixed',TMGenNP_fixed. cbn.\n    set (t__start:=fun (ts : tapes sig n) => inl START::concat (map (fun t => inr (sigList_cons)::map (fun s => inr (sigList_X s)) (encode_tape t)) (Vector.to_list ts))++[inr (sigList_cons)]).\n    set (t__size := fun maxSize => 3 + if eqb 0 maxSize then 0 else 1 + maxSize).\n    eapply reducesPolyMO_intro_restrictBy_in with\n        (f:=fun '(ts,maxSize,steps) => (t__start ts\n                                     ,t__size maxSize\n                                     ,  c__leUpToC (H:=Hf__nice) * f__nice (steps,sizeOfmTapes ts,maxSize)+ 3)).\n    2:{ unfold execTM.\n        intros [[v maxSize] steps]. unfold HaltsOrDiverges_mTM_fixed. intros H_HaltOrDiv.\n        split.\n        -intros (t1&Ht1&s__end&Hs__end).\n         eexists (map (fun c => inr (sigList_X c)) (encode_tape t1) ++ [inr sigList_nil;inl STOP]). \n         split. 1:{ cbn - [plus]. autorewrite with list. rewrite sizeOfTape_encodeTape. cbn - [Nat.eqb].\n                    destruct (Nat.eqb_spec 0 (sizeOfTape t1));\n                      destruct (eqb_spec 0 (maxSize)). all:try nia.\n         }\n         edestruct Terminates__mono as (?&?).\n         2:{ eexists. cbn. unfold execTM. rewrite H. easy. }\n         cbn. set (tin:=midtape _ _ _).\n         eexists (select (putFirstAtEnd n) (t1:::v)), _.\n         assert (Ht1v:contains_tapes tin (select (putFirstAtEnd n) (t1 ::: v))). \n         { hnf. subst tin. f_equal. unfold encode_tapes.\n           rewrite encode_list_concat.\n           autorewrite with list. cbn. rewrite !concat_map,!map_map.\n           rewrite putFirstAtEnd_to_list.\n           autorewrite with list. cbn. repeat setoid_rewrite map_map.\n           rewrite concat_app;cbn. autorewrite with list. easy.\n         } split. easy.\n         split. 2:easy. hnf.\n         (do 2 eexists). split.\n         +intros ? ?. cbn in H. replace v0 with ((select (putFirstAtEnd n) (t1 ::: v))) in * by now eapply contains_tapes_inj. clear v0 H.\n          split. 1: {hnf. rewrite putEnd_invL. eauto. }\n          assert (H':=proj2_sig M2MBounds.Loop_steps_nice). hnf in H'.\n          unfold PrettyBounds.dominatedWith in H'.\n          rewrite H'. rewrite putFirstAtEnd_to_list.\n          rewrite BaseCode.encodeList_size_app,size_list, Vector.length_to_list.\n          unfold Code.size. cbn - [mult plus]. \n          autorewrite with list. cbn [length]. rewrite sizeOfTape_encodeTape_le.\n          erewrite sumn_map_le_pointwise with (f2:=fun x => _).\n          2:{ intros. rewrite sizeOfTape_encodeTape_le. rewrite sizeOfmTapes_upperBound. 2:now eapply Vector.to_list_In. reflexivity. }\n          rewrite !sumn_map_c, Vector.length_to_list.\n          unshelve erewrite ( _ : (n * (2 + sizeOfmTapes v) + n + 1 + S (2 + sizeOfTape t1 + 1) + S n * steps)\n                                  <= ((steps + sizeOfmTapes v + 5)* S n + sizeOfTape t1)). nia.\n          reflexivity. \n         +cbn - [mult plus]. autorewrite with list; cbn - [plus mult].\n          rewrite length_concat,map_map;cbn - [plus mult];setoid_rewrite map_length.\n          rewrite sizeOfTape_encodeTape_le,Ht1.\n          rewrite sumn_le_bound.\n          2:{ intros ? (?&<-&?)%in_map_iff.\n              rewrite sizeOfTape_encodeTape_le, sizeOfmTapes_upperBound. 2:now apply Vector.to_list_In. reflexivity. }\n          rewrite map_length. rewrite Vector.length_to_list.\n          replace (1 + (2 + maxSize + 2)) with (maxSize + 5) by lia.\n          setoid_rewrite <- correct__leUpToC.\n          [f__steps]:refine (fun '(steps, sizeOfmTapes, maxSize) =>  _).\n          set (sizeOfmTapes _). unfold f__steps. reflexivity.\n        -intros (cert&Hsize&f'&Hf'). destruct @loopM as [f| ] eqn:Hf. all:cbn -[plus mult t__start] in *. 2:now inv Hf'. clear Hf' f'.\n         apply Realises__mono in Hf as (v0&v1&Hv0&Hv1&H__mono). cbn in Hv0.\n         hnf in H__mono;cbn in H__mono. unfold LiftTapes in H__mono;cbn in H__mono.\n         destruct H__mono as (outc&k&Hout&<-&_).\n         hnf in Hv0. revert Hv0. intros [= Htl].\n         unfold encode_tapes in Htl;rewrite encode_list_concat in Htl.\n         rewrite map_app,concat_map,map_map in Htl. cbn in Htl. \n         setoid_rewrite map_map in Htl. rewrite <- !app_assoc in Htl. cbn in Htl.\n         assert (H':=Htl). eapply concat_eq_inv_borderL with (isBorder := fun c => c = inr sigList_cons) in H'. rewrite map_length, Vector.length_to_list in H'.\n         5:easy. 4:now cbn;intuition subst.\n         2,3:intros _ (x&<-&Hinx)%in_map_iff. 2,3:eexists _,_;split;[reflexivity | ].\n         2,3:now split;[easy | intros ? (y&<-&Hiny)%in_map_iff;easy].\n         destruct H' as [Hinit Hlast]. rewrite skipn_map in Hlast.\n         destruct (split_vector v0 n) as (v'&vlst) eqn:Hsplit.\n         unshelve eassert (H':=split_vector_correct _ _). 6:rewrite Hsplit in H'. clear. abstract nia. \n         cbn [fst snd] in H'. apply (f_equal (@vector_to_list _ _ )) in H'. rewrite vector_to_list_cast in H'. clear Hsplit.\n         rewrite Vector.to_list_append in H'.  \n         revert v' vlst H'. replace (Init.Nat.min n (S n)) with n by nia. replace (S n - n) with 1 by nia.\n         intros v' vlst eq. destruct_vector (* vlst as h *). cbn in eq.\n         rewrite <- eq in Hlast,Hinit.\n         replace v' with v in *.\n         2:{ eapply VectorSpec.eq_nth_iff. intros i ? <-.\n             unshelve eassert (Htmp:=Hinit (proj1_sig (Fin.to_nat i)) _). { now destruct Fin.to_nat. }\n             destruct (Fin.to_nat i) eqn:Hi.\n             rewrite map_app,<-!Vector.to_list_map in Htmp. \n             rewrite nth_error_app1 in Htmp. 2:now rewrite Vector.length_to_list.\n             cbn in Htmp. rewrite !vector_nth_error_nat in Htmp.\n             destruct lt_dec. 2:easy. \n             rewrite !nth_map' in Htmp. revert Htmp. intros [= Htmp].\n             apply map_injective in Htmp. 2:congruence. apply DecodeTape.tape_encode_injective in Htmp.\n             rewrite <- (Fin.of_nat_to_nat_inv i).  rewrite Hi;cbn.\n             erewrite Fin.of_nat_ext. apply Htmp.\n         }\n         clear Hinit v'.\n         rewrite skipn_app in Hlast. 2:now rewrite Vector.length_to_list. cbn in Hlast.\n         autorewrite with list in Hlast. cbn in Hlast. revert Hlast. intros [= ->].\n         edestruct H_HaltOrDiv as (?&?&?&?).\n         2:now eauto.\n         assert (Hts__size : sizeOfTape h <= maxSize).\n         1:{ autorewrite with list in Hsize.  rewrite sizeOfTape_encodeTape in Hsize. unfold t__size in *.\n             destruct (eqb_spec 0 maxSize);destruct sizeOfTape. all:cbn in Hsize;try nia. }\n         clear Hsize. unfold initc in *. cbn in Hout.\n         unshelve eassert (Htmp := LiftTapes_lift _ _). 11:{ now rewrite Hout. } now apply putEndAtFirst_dupfree.\n         cbn in Htmp. unfold selectConf in Htmp. cbn in Htmp.\n\n         erewrite putEndAtFirst_to_list in Htmp. 2:exact eq. eassumption.\n    }\n    2:{\n      \n      unfold f__steps.\n      enough ((fun _ => 1) <=c f__nice).\n      smpl upToC.\n      1,2:smpl_upToC.\n      3:{ [f__nice]: exact (fun '(x,y,z) => (fun s => s*s*S x) (S x + y + z)).\n          subst f__nice.\n          set (c:= 5*(S n) + 1).\n          exists (c * c).\n          intros [[x y] z].\n          set (s:=S x+y+z).  \n          unshelve erewrite (_ : (x + y + 5) * S n + z <= c*s). 1:{ unfold s,c. nia. }\n          nia.\n      }\n      all:unfold f__nice. all:smpl_upToC_solve.\n    }\n\n    assert (polyTimeComputable f__nice).\n    { \n      evar (time : nat -> nat). [time]:intros n0.\n      eexists (fun x => time x).\n      { unfold f__nice. extract. solverec.\n        set (n0:=(L_facts.size (enc (a0, b0, b)))).\n        assert (a0+b0+b+1 <= n0). 1:{ unfold n0. rewrite !size_prod. cbn [fst snd]. rewrite !size_nat_enc. \n          unfold c__natsizeS, c__natsizeO; nia. }\n        unfold add_time, mult_time. \n        unshelve erewrite (_ : a0 <= n0). nia. unshelve erewrite (_ : b0 <= n0). nia. unshelve erewrite (_ : b <= n0). nia.\n        unfold time. reflexivity. }\n      1,2:unfold time;smpl_inO.\n      { evar (f__size : nat -> nat). [f__size]:intros n0. exists f__size.\n        { intros [[a0 b0] b]. unfold f__nice.\n          set (n0:=(L_facts.size (enc (a0, b0, b)))).\n          assert (a0+b0+b+1 <= n0). 1:{ unfold n0. rewrite !size_prod. cbn [fst snd]. rewrite !size_nat_enc. \n            unfold c__natsizeS, c__natsizeO; nia. }\n          rewrite size_nat_enc. \n          unshelve erewrite (_ : a0 <= n0). nia. unshelve erewrite (_ : b0 <= n0). nia. unshelve erewrite (_ : b <= n0). nia.\n          change S with (plus 1).\n          unfold f__size;reflexivity.\n        }\n        all:unfold f__size;smpl_inO.\n      }\n    }\n    clearbody f__nice.\n\n    assert (polyTimeComputable t__size).\n    { \n      evar (c0 : nat).\n      eexists (fun _ => c0).\n      { unfold t__size. extract. solverec. all:rewrite eqbTime_le_l.\n        all:set (c:=L_facts.size (enc 0)). all:cbv in c;subst c. all:subst c0. 2:easy. nia. }\n      1,2:smpl_inO.\n      { evar (f__size : nat -> nat). [f__size]:intros n0. exists f__size.\n        { intros x. unfold t__size.\n          set (n0:=(L_facts.size (enc x))).\n          assert (Hx:x<=n0) by apply size_nat_enc_r.\n          rewrite size_nat_enc. destruct _. 2:rewrite Hx;unfold f__size;reflexivity. unfold f__size. nia.\n        }\n        \n        all:unfold f__size;smpl_inO.\n      }\n    }clearbody t__size.\n\n    assert (polyTimeComputable t__start).\n    {\n      set (f:=fun s : sigTape sig => inr (sigList_X s)) in t__start.\n      assert ( {f__c:UpToC (fun _ => 1) & computableTime' f (fun _ _ => (f__c tt,tt))}) as [t__f comp__f].\n      {  evar (c:nat). exists_UpToC (fun _ => c). unfold f. clear_all. extract. solverec. [c]:exact 3. now unfold c. subst c. smpl_upToC_solve. }\n\n      set (g:= (fun t : tape sig => inr sigList_cons :: map f (encode_tape t))) in t__start.\n      assert ( {t__g:UpToC (fun t=> sizeOfTape t + 1) & computableTime' g (fun t _ => (t__g t,tt))}) as [t__g comp__g].\n      {  evar (t__c: tape sig -> nat). [t__c]:intro. exists_UpToC t__c. unfold g.\n         extract. solverec.\n         rewrite map_time_const,sizeOfTape_encodeTape_le. all:unfold t__c. reflexivity. smpl_upToC_solve.\n      } \n      \n      evar (time : nat -> nat). [time]:intros n0.\n      eexists (fun x => time x).\n      { unfold t__start. extract. solverec. rewrite (UpToC_le _).\n        rewrite (correct__leUpToC (mapTime_upTo _)). \n        rewrite length_concat,map_map. subst g. cbn -[plus mult]. setoid_rewrite map_length. rewrite Vector.length_to_list.\n        erewrite sumn_map_le_pointwise  with (f2:=fun _ => _).\n        2:{ intros;rewrite (UpToC_le t__g),sizeOfmTapes_upperBound;try reflexivity;now apply Vector.to_list_In. }\n        erewrite sumn_map_le_pointwise with (f1:=fun x1 : tape sig => S (| encode_tape x1 |)) (f2:=fun _ => _).\n        2:{ intros. setoid_rewrite sizeOfTape_encodeTape_le at 1. rewrite sizeOfmTapes_upperBound at 1. 2:now apply Vector.to_list_In.\n            reflexivity. }\n        rewrite sumn_map_c, Vector.length_to_list.\n        rewrite sumn_map_c, Vector.length_to_list.\n        rewrite sizeOfmTapes_by_size. set (L_facts.size _).\n        unfold time. reflexivity.\n      }\n      1,2:now unfold time;change S with (plus 1);smpl_inO.\n      { evar (f__size : nat -> nat). [f__size]:intros n0. exists f__size.\n        { intros x. unfold t__start.\n          rewrite size_list_cons. subst g f.\n          rewrite Lists.size_list. rewrite map_app,concat_map,map_map. cbn. setoid_rewrite map_map. rewrite sumn_app.\n          assert (H' : forall l, sumn (concat l) = sumn (map sumn l)). 1:{induction l;cbn;now autorewrite with list. }\n          rewrite H',map_map. cbn. set (tmp:=size (enc (inr sigList_cons)));cbv in tmp;subst tmp.\n          setoid_rewrite size_sum. rewrite size_boundary. setoid_rewrite size_sigList.\n          repeat setoid_rewrite <- Nat.add_assoc.  ring_simplify. ring_simplify (7 + (4 + 5)).\n          repeat setoid_rewrite sumn_map_add. repeat setoid_rewrite sumn_map_c. setoid_rewrite sumn_map_mult_c_r.\n          setoid_rewrite sumn_map_le_pointwise with (f2:=fun x => _) at  3 4 5.\n          2,3,4: (setoid_rewrite sizeOfTape_encodeTape_le;intros;rewrite sizeOfmTapes_upperBound at 1; [ | now apply Vector.to_list_In]; reflexivity).\n          rewrite sumn_map_c.\n          setoid_rewrite sumn_map_le_pointwise with (f2:=fun x => _).\n          2:{ intros. setoid_rewrite sumn_map_le_pointwise with (f2:=fun x => _).\n              2:{ intros. apply (correct__leUpToC (size_finType_any_le_c (X:=finType_CS (sigTape sig)))). }\n              rewrite sumn_map_c. rewrite sizeOfTape_encodeTape_le,  sizeOfmTapes_upperBound. 2:now apply Vector.to_list_In. reflexivity. }\n          rewrite sumn_map_c. rewrite Vector.length_to_list. setoid_rewrite sizeOfmTapes_by_size.\n          set (n0:= L_facts.size _). ring_simplify. unfold f__size. reflexivity.\n        }\n        all:unfold f__size;smpl_inO.\n      }\n    }\n    clearbody f__steps t__start.\n(*    assert (polyTimeComputable (@sizeOfmTapes sig n)) by apply ptc_sizeOfmtapes. *)\n\n    evar (time : nat -> nat). [time]:intros n0.\n      eexists (fun x => time x).\n      {\n        extract. solverec.\n        remember (L_facts.size (enc (a0, b0, b))) as n0 eqn:Hn0.\n        rewrite !size_prod in Hn0. cbn [fst snd] in Hn0.\n        erewrite (mono__polyTC X0 (x':=n0)). 2:{ subst n0. repeat set (L_facts.size _). nia. }\n        rewrite (mono__polyTC X1 (x':=n0)). 2:{ subst n0. repeat set (L_facts.size _). nia. } \n        set (c0 := 5+c__natsizeO +c__natsizeS). \n        assert (H'' : L_facts.size (enc (b, sizeOfmTapes a0, b0)) <= n0*c0).\n        {  rewrite !size_prod. cbn [fst snd]. setoid_rewrite size_nat_enc at 2.\n            rewrite sizeOfmTapes_by_size. subst n0. repeat set (L_facts.size _). nia. }\n        setoid_rewrite (mono__polyTC X (x':=n0*c0)). 2:exact H''. \n        specialize (bounds__rSP (f:=f__nice)) as H'. setoid_rewrite <- size_nat_enc_r in H'.\n        unfold mult_time, add_time. \n        unshelve rewrite H'. now apply resSize__polyTC.\n        setoid_rewrite mono__rSP. 2,3:exact H''.\n        rewrite sizeOfmTapes_by_size at 1. unshelve erewrite (_ : L_facts.size (enc a0) <= n0). now (subst n0;clear;repeat set (L_facts.size _);nia).\n        unfold time. reflexivity.\n      }\n      1,2:now unfold time;smpl_inO;apply inOPoly_comp;smpl_inO.\n      { evar (f__size : nat -> nat). [f__size]:intros n0. exists f__size.\n        { intros [[a0 b0] b]. remember (L_facts.size (enc (a0, b0, b))) as n0 eqn:Hn0.\n          rewrite !size_prod in Hn0|-*. cbn [fst snd] in Hn0|-*. rewrite !size_nat_enc.\n          assert (H'' : L_facts.size (enc (b, sizeOfmTapes a0, b0)) <= n0*(5 + c__natsizeS + c__natsizeO)).\n        {  rewrite !size_prod. cbn [fst snd]. setoid_rewrite size_nat_enc at 2.\n           rewrite sizeOfmTapes_by_size. subst n0. repeat set (L_facts.size _). nia. }\n        specialize (bounds__rSP (f:=f__nice)) as H'. setoid_rewrite <- size_nat_enc_r in H'.\n        unshelve rewrite H'. now apply resSize__polyTC.\n        setoid_rewrite mono__rSP. 2:exact H''.\n\n        specialize (bounds__rSP (f:=t__size)) as Hsize. setoid_rewrite <- size_nat_enc_r in Hsize at 1.\n        unshelve rewrite Hsize. now apply resSize__polyTC. \n        setoid_rewrite (mono__rSP _ (x':=n0)) at 1 . 2:nia.\n\n        specialize (bounds__rSP (f:=t__start)) as Hstart.\n        unshelve rewrite Hstart. now apply resSize__polyTC. \n        setoid_rewrite (mono__rSP _ (x':=n0)) at 1 . 2:subst;clear;repeat (set (L_facts.size _));nia.\n        unfold f__size. reflexivity.\n        }\n        1,2:unfold f__size;smpl_inO; apply inOPoly_comp;smpl_inO.\n\n      }\n    \n        \n  Qed.\n\n  (* Print Assumptions LMGenNP_to_TMGenNP_mTM. *)\n\nEnd LMGenNP_to_TMGenNP_mTM.\n", "meta": {"author": "uds-psl", "repo": "coq-library-complexity", "sha": "5a996877f16fd6fe16dc5f0c3b933486957869df", "save_path": "github-repos/coq/uds-psl-coq-library-complexity", "path": "github-repos/coq/uds-psl-coq-library-complexity/coq-library-complexity-5a996877f16fd6fe16dc5f0c3b933486957869df/theories/NP/TM/mTM_to_singleTapeTM.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3311197396289915, "lm_q1q2_score": 0.2012092705771947}}
{"text": "\n(*\n  This file is part of the verified smart contract project of SECBIT Labs.\n\n  Copyright 2018 SECBIT Labs\n\n  This program is free software: you can redistribute it and/or\n  modify it under the terms of the GNU Lesser General Public License\n  as published by the Free Software Foundation, either version 3 of\n  the License, or (at your option) any later version.\n\n  This program is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n  Lesser General Public License for more details.\n\n  You should have received a copy of the GNU Lesser General Public License\n  along with this program.  If not, see <https://www.gnu.org/licenses/>.\n*)\n\nRequire Export Model.\nRequire Export Lists.List.\n\n(*\n  A specification of a function consists of:\n    1) [spec_require] requirements via the `require()` calls\n    2) [spec_events ] events generated via event calls\n    3) [spec_trans  ] state transition done by the function\n*)\nRecord Spec: Type :=\n  mk_spec {\n      spec_require: state -> Prop;\n      spec_events: state -> eventlist -> Prop;\n      spec_trans: state -> state -> Prop\n    }.\n\n(*\n  This specification follows the smart contract as implemented in\n    https://github.com/ConsenSys/Tokens/blob/master/contracts/eip20/EIP20.sol\n*)\n\n(*\n    constructor(uint256 _initialAmount, string _name, string _symbol, uint8 _decimals, uint256 _unLockTime) public {\n\n        require (_unLockTime >= block.timestamp);\n        totalSupply = _initialAmount;\n        balances[msg.sender] = _initialAmount;\n        name = _name;\n        symbol = _symbol;\n        decimals = _decimals;\n        UnLockTime = _unLockTime;\n        emit Transfer(0x0, msg.sender, _initialAmount);\n    }\n*)\nDefinition funcspec_constructor (_initialAmount: uint256) (_tokenName: string) \n            (_tokenSymbol: string)(_decimalUnits: uint8)(_unLockTime: uint256) :=\n  fun (this: address) (env: env) (msg: message) =>\n    (mk_spec\n       (* No require in this function. *)\n       (fun S : state => _unLockTime >= env_time env)\n\n       (* Models an constructor event here. *)\n       (fun S E => E = ((ev_constructor (m_sender msg) _initialAmount _tokenName _tokenSymbol _decimalUnits _unLockTime):: (ev_Transfer (m_sender msg) 0  (m_sender msg) _initialAmount) :: nil))\n\n       (* State transition: *)\n       (fun S S' : state =>                  \n       (* totalSupply = _initialAmount;                        // Update total supply *)\n          st_totalSupply S' = _initialAmount /\\\n       (* Name = _tokenName;                                   // Set the name for display purposes *)\n          st_name S' = _tokenName /\\\n       (* decimals = _decimalUnits;                            // Amount of decimals for display purposes *)\n          st_decimals S' = _decimalUnits /\\\n       (* symbol = _tokenSymbol;                               // Set the symbol for display purposes *)\n          st_symbol S' =  _tokenSymbol /\\\n       (* balances[msg.sender] = _initialAmount;               // Give the creator all initial tokens *)\n          st_balances S' = $0 $+ {m_sender msg <- _initialAmount} /\\\n       (* Init to all zero. *)\n          st_allowed S' = $0 /\\\n       (* st_owner = msg.sender *)\n          st_owner S' = (m_sender msg) /\\\n       (* UnLockTime = _unLockTime *)\n          st_unLockTime S'= _unLockTime\n       )\n    ).\n\n(*\nfunction name() public view returns (string){\n   return name;\n}\n *)\nDefinition funcspec_name :=\n  fun (this: address)(env: env)(msg: message) =>\n    (mk_spec\n        (* No require in this function. *)\n       (fun S : state => True)\n       \n        (* return name; *)\n       (fun S E => E = (ev_return _ (st_name S)) :: nil)\n\n       (* Unchanged. *)\n       (fun S S' : state => S = S')  \n    ).\n\n(*\n    function symbol() public view returns (string){\n        return symbol;\n    }\n*)\nDefinition funcspec_symbol :=\n    fun (this: address)(env: env)(msg: message) =>\n    (mk_spec\n        (* No require in this function. *)\n       (fun S : state => True)\n       \n        (* return name; *)\n       (fun S E => E = (ev_return _ (st_symbol S)) :: nil)\n\n       (* Unchanged. *)\n       (fun S S' : state => S = S')  \n    ).\n\n(*\nfunction decimals() public view returns (uint8){\n   return decimals;\n}\n *)\nDefinition funcspec_decimals :=\n    fun (this: address)(env: env)(msg: message) =>\n    (mk_spec\n        (* No require in this function. *)\n       (fun S : state => True)\n       \n        (* return name; *)\n       (fun S E => E = (ev_return _ (st_decimals S)) :: nil)\n\n       (* Unchanged. *)\n       (fun S S' : state => S = S')  \n    ).\n\n(*\nfunction totalSupply() public view returns (uint256){\n        return totalSupply;\n    }\n*)\nDefinition funcspec_totalSupply :=\n  fun (this: address)(env: env)(msg:message) =>\n    (mk_spec\n       (* No require in this function. *)\n       (fun S : state => True)\n       \n        (* return totalSupply_; *)\n       (fun S E => E = (ev_return _ (st_totalSupply S)) :: nil)\n\n       (* Unchanged. *)\n       (fun S S' : state => S = S')  \n    ).\n\n(*\n    function balanceOf(address _owner) public view returns (uint256){\n        return balances[_owner];\n    }\n*)\nDefinition funcspec_balanceOf\n           (owner: address) :=\n  fun (this: address) (env: env) (msg: message) =>\n    (mk_spec\n       (* No requirement *)\n       (fun S : state => True)\n\n       (* return balances[_owner]; *)\n       (fun S E => E = (ev_return _ (st_balances S owner)) :: nil)\n\n       (* Unchanged. *)\n       (fun S S' : state => S = S')\n    ).\n\n(*\nfunction transfer(address _to, uint256 _value) isUnLocked public returns (bool success){\n        require (balances[_to] + _value >= balances[_to]);\n        require (balances[msg.sender] >= _value);\n        balances[_to] = balances[_to] + _value;\n        balances[msg.sender] = balances[_to] + _value;\n        emit Transfer(msg.sender, _to, _value);\n        return true;\n    }\n*)\nDefinition funcspec_transfer\n           (to: address)\n           (value: value) :=\n  fun (this: address) (env: env) (msg: message) =>\n    (mk_spec\n       (fun S : state =>\n            (* block.timestamp > UnLockTime *)\n           (env_time env >= st_unLockTime S /\\\n            (*  balances[msg.sender]>= _value *)\n            st_balances S (m_sender msg ) >= value /\\\n            (* balances[_to] + _value <= MAX_UINT256 *)\n           (st_balances S to <= MAX_UINT256 - value)))\n\n       (* emit Transfer(msg.sender, _to, _value); *)\n       (* return True; *)\n       (fun S E => E = (ev_Transfer (m_sender msg) (m_sender msg) to value) :: (ev_return _ True) :: nil)\n\n       (* State transition: *)\n       (fun S S' : state =>\n       (* Unchanged. *)\n          st_totalSupply S' = st_totalSupply S /\\\n          st_name S' = st_name S /\\\n          st_decimals S' = st_decimals S /\\\n          st_symbol S' = st_symbol S /\\\n       (* balances[msg.sender] -= _value; *)\n          st_balances S' = (st_balances S) $+{ (m_sender msg) <- -= value }\n       (* balances[_to] += _value; *)\n                                           $+{ to <- += value }\n       (* Unchanged. *)\n          /\\ st_allowed S' = st_allowed S\n          /\\ st_owner S' =  st_owner S\n          /\\ st_unLockTime S' = st_unLockTime S\n       )\n    ).\n\n\n(*\n    function transferFrom(address _from, address _to, uint256 _value) isUnLocked public returns (bool success){\n        uint256 allowance = allowed[_from][msg.sender];\n        require (balances[_to] + _value >= balances[_to]);\n        require (balances[_from] >= _value);\n        require (allowance >= _value);\n        balances[_to] = balances[_to] + _value;\n        balances[_from] = balances[_from] - _value;\n       \n        if (allowance < MAX_UINT256) {\n            allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value;\n        }\n        emit Transfer(_from, _to, _value);\n        return true;\n    }\n*)\nDefinition funcspec_transferFrom_1\n           (from: address)\n           (to: address)\n           (value: value) :=\n  fun (this: address) (env: env) (msg: message) =>\n    (mk_spec\n       (fun S : state =>\n        (* block.timestamp > UnLockTime *)\n       env_time env >= st_unLockTime S /\\\n       (* _value <= balances[_from] *)\n         st_balances S from >= value /\\\n       (* balances[_to] + _value <= MAX_UINT256 *)\n         st_balances S to <= MAX_UINT256 - value /\\\n        (* _value <= allowed[_from][msg.sender] *)\n         st_allowed S (from, m_sender msg) >= value /\\\n       st_allowed S (from, m_sender msg) < MAX_UINT256)\n       \n       (* emit Transfer(_from, _to, _value); *)\n       (* return True; *)\n       (fun S E => E = (ev_Transfer (m_sender msg) from to value) :: (ev_return _ True) :: nil)\n\n       (* State transition: *)\n       (fun S S' : state =>\n       (* Unchanged. *)\n          st_totalSupply S' = st_totalSupply S /\\\n          st_name S' = st_name S /\\\n          st_decimals S' = st_decimals S /\\\n          st_symbol S' = st_symbol S /\\\n       (* balances[_from] -= _value; *)\n          st_balances S' = (st_balances S) $+{ from <- -= value }\n       (* balances[_to] += _value; *)\n                                           $+{ to <- += value } /\\\n       (* allowed[_from][msg.sender] -= _value; *)\n          st_allowed S' = (st_allowed S) $+{ from, (m_sender msg) <-  -= value} /\\\n          st_owner S' = st_owner S /\\\n          st_unLockTime S' = st_unLockTime S\n           \n       )\n    ).\n\nDefinition funcspec_transferFrom_2\n           (from: address)\n           (to: address)\n           (value: value) :=\n  fun (this: address) (env: env) (msg: message) =>\n    (mk_spec\n       (fun S : state =>\n        (* block.timestamp > UnLockTime *)\n       env_time env >= st_unLockTime S /\\\n       (* _value <= balances[_from] *)\n         st_balances S from >= value /\\\n       (* balances[_to] + _value <= MAX_UINT256 *)\n         st_balances S to <= MAX_UINT256 - value /\\\n        (* _value <= allowed[_from][msg.sender] *)\n         st_allowed S (from, m_sender msg) >= value /\\\n       st_allowed S (from, m_sender msg) = MAX_UINT256)\n       \n       (* emit Transfer(_from, _to, _value); *)\n       (* return True; *)\n       (fun S E => E = (ev_Transfer (m_sender msg) from to value) :: (ev_return _ True) :: nil)\n\n       (* State transition: *)\n       (fun S S' : state =>\n       (* Unchanged. *)\n          st_totalSupply S' = st_totalSupply S /\\\n          st_name S' = st_name S /\\\n          st_decimals S' = st_decimals S /\\\n          st_symbol S' = st_symbol S /\\\n       (* balances[_from] -= _value; *)\n          st_balances S' = (st_balances S) $+{ from <- -= value }\n       (* balances[_to] += _value; *)\n                                           $+{ to <- += value } /\\\n       (* allowed[_from][msg.sender] -= _value; *)\n          st_allowed S' = st_allowed S /\\\n          st_owner S' = st_owner S /\\\n          st_unLockTime S' = st_unLockTime S\n           \n       )\n    ).\n\n(*\n function approve(address _spender, uint256 _value) isUnLocked public returns (bool){\n        allowed[msg.sender][_spender] = _value;\n        emit Approval(msg.sender, _spender, _value);\n        return true;\n    }\n*)\nDefinition funcspec_approve\n           (spender: address)\n           (value: value) :=\n  fun (this: address) (env: env) (msg: message) =>\n    (mk_spec\n       (* block.timestamp > UnLockTime *)\n       (fun S : state => (env_time env >= st_unLockTime S))\n\n       (* emit Approval(msg.sender, _spender, _value); *)\n       (* return True; *)\n       (fun S E => E = (ev_Approval (m_sender msg) (m_sender msg) spender value) :: (ev_return _ True) :: nil)\n\n       (* State transition: *)\n       (fun S S' : state =>\n       (* Unchanged. *)\n          st_totalSupply S' = st_totalSupply S /\\\n          st_name S' = st_name S /\\\n          st_decimals S' = st_decimals S /\\\n          st_symbol S' = st_symbol S /\\\n          st_balances S' = st_balances S /\\\n       (* allowed[msg.sender][_spender] = _value; *)\n          st_allowed S' = (st_allowed S) $+{ m_sender msg, spender <- value} /\\\n          st_owner S' = st_owner S /\\\n          st_unLockTime S' = st_unLockTime S\n       )\n    ).\n\n(*\nfunction allowance(address _owner, address _spender) public view returns (uint256){\n        return allowed[_owner][_spender];\n    }\n*)\nDefinition funcspec_allowance (owner: address) (spender: address) :=\n  fun (this: address) (env: env) (msg: message) =>\n    (mk_spec\n       (* No requirement *)\n       (fun S : state => True)\n\n       (* return allowed[_owner][_spender]; *)\n       (fun S E => E = (ev_return _ (st_allowed S (owner, spender))) :: nil)\n\n       (* Unchanged. *)\n       (fun S S' : state => S' = S)\n    ).\n\n(*\nfunction increaseApproval(address _spender, uint _addedValue) isUnLocked public returns (bool) {\n        \n        require (allowed[msg.sender][_spender]+ _addedValue >= allowed[msg.sender][_spender]);\n        allowed[msg.sender][_spender] = allowed[msg.sender][_spender]+ _addedValue;\n        emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);\n        return true;\n    }\n *)\nDefinition funcspec_increaseApproval (spender: address)(addValue: value):=\n  fun (this: address) (env: env) (msg: message) =>\n    (mk_spec\n       (fun S : state =>\n           (* block.timestamp > UnLockTime *)\n          (env_time env >= st_unLockTime S /\\\n           st_allowed S (m_sender msg , spender) + addValue <= MAX_UINT256)\n        )\n       \n       (* emit Approval(msg.sender, _spender, _value); *)\n       (* return True; *)\n       (fun S E => E = (ev_Approval (m_sender msg) (m_sender msg) spender (st_allowed S (m_sender msg, spender) )) :: (ev_return _ True) :: nil)\n\n       (* State transition: *)\n       (fun S S' : state =>\n       (* Unchanged. *)\n          st_totalSupply S' = st_totalSupply S /\\\n          st_name S' = st_name S /\\\n          st_decimals S' = st_decimals S /\\\n          st_symbol S' = st_symbol S /\\\n          st_balances S' = st_balances S /\\\n       (* allowed[msg.sender][_spender] = _value; *)\n          st_allowed S' = (st_allowed S) $+{ m_sender msg, spender <- += addValue} /\\\n          st_owner S' = st_owner S /\\\n          st_unLockTime S' = st_unLockTime S\n       )\n    ).\n\n(*\nfunction decreaseApproval(address _spender, uint _subtractedValue) isUnLocked public returns (bool success) {\n        \n        uint oldValue = allowed[msg.sender][_spender];\n        if (_subtractedValue > oldValue) {\n            allowed[msg.sender][_spender] = 0;\n        } else {\n            allowed[msg.sender][_spender] = oldValue - _subtractedValue;\n        }\n        emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);\n        return true;\n    }\n *)\nDefinition funcspec_decreaseApproval_1 (spender: address)(subValue: value) :=\n  fun (this: address)(env: env)(msg: message) =>\n    (mk_spec\n       (* !stopped  *)\n       (fun S : state =>\n          (* block.timestamp > UnLockTime *)\n          (env_time env >= st_unLockTime S /\\\n           (st_allowed S (m_sender msg, spender ) < subValue)))\n                          \n       (* emit Approval(msg.sender, _spender, 0); *)\n       (* return True; *)\n       (fun S E => E = (ev_Approval (m_sender msg) (m_sender msg) spender 0) :: (ev_return _ True) :: nil)\n\n       (* State transition: *)\n       (fun S S' : state =>\n       (* Unchanged. *)\n          st_totalSupply S' = st_totalSupply S /\\\n          st_name S' = st_name S /\\\n          st_decimals S' = st_decimals S /\\\n          st_symbol S' = st_symbol S /\\\n          st_balances S' = st_balances S /\\\n          (* allowed[msg.sender][_spender] = 0; *)\n          st_allowed S' = (st_allowed S) $+{ m_sender msg, spender <- 0} /\\\n          st_owner S' = st_owner S /\\\n          st_unLockTime S' = st_unLockTime S\n       ) \n  ).\n\nDefinition funcspec_decreaseApproval_2 (spender: address)(subValue: value) :=\n  fun (this: address)(env: env)(msg: message) =>\n    (mk_spec\n       (* !stopped  *)\n       (fun S : state =>  (* block.timestamp > UnLockTime *)\n          (env_time env >= st_unLockTime S /\\\n              (st_allowed S (m_sender msg, spender ) >= subValue)))\n                          \n       (* emit Approval(msg.sender, _spender, 0); *)\n       (* return True; *)\n       (fun S E => E = (ev_Approval (m_sender msg) (m_sender msg) spender (st_allowed S (m_sender msg, spender))) :: (ev_return _ True) :: nil)\n\n       (* State transition: *)\n       (fun S S' : state =>\n       (* Unchanged. *)\n          st_totalSupply S' = st_totalSupply S /\\\n          st_name S' = st_name S /\\\n          st_decimals S' = st_decimals S /\\\n          st_symbol S' = st_symbol S /\\\n          st_balances S' = st_balances S /\\\n          (* allowed[msg.sender][_spender] = 0; *)\n          st_allowed S' = (st_allowed S) $+{ m_sender msg, spender <- -= subValue } /\\\n          st_owner S' = st_owner S /\\\n           st_unLockTime S' = st_unLockTime S\n       ) \n    ).\n\n(*\nfuncspec transferOwnership(address newOwner){\n    requir: msg.sender = owner and newOwner != address(0)\n    {\n        pre: True\n        event: @OwnershipTransferred(owner, newOwner)\n        post: owner' = newOwner\n    }\n}\n*)\nDefinition funcspec_transferOwnership (newOwner: address) :=\n  fun (this: address)(env: env)(msg: message) =>\n    (mk_spec\n       (* msg.sender = owner and newOwner != address(0) *)\n       (fun S : state => (m_sender msg = st_owner S) /\\ (newOwner <> 0))\n       (* emit OwnershipTransferred(owner, newOwner); *)\n       (fun S E => E = (ev_OwnershipTransferred (st_owner S) newOwner):: nil)\n       (* State transition: *)\n       (fun S S': state =>\n          st_totalSupply S' = st_totalSupply S /\\\n          st_name S' = st_name S /\\\n          st_decimals S' = st_decimals S /\\\n          st_symbol S' = st_symbol S /\\\n          st_balances S' = st_balances S /\\\n          st_allowed S' =  st_allowed S /\\\n          st_owner S' = newOwner /\\\n           st_unLockTime S' = st_unLockTime S\n       )\n    ).\n  \n\n(* Constructor invocation. *)\nInductive create : env -> message -> contract -> eventlist -> Prop :=\n  | create_Constructor : forall env msg S C E sender _initialAmount _tokenName _tokenSymbol _decimalUnits _unLockTime spec preP evP postP,\n      msg = mk_msg sender (mc_constructor _initialAmount _tokenName _tokenSymbol _decimalUnits _unLockTime) 0\n      -> spec = funcspec_constructor _initialAmount _tokenName _tokenSymbol _decimalUnits _unLockTime (w_a C) env msg\n      -> _initialAmount <= MAX_UINT256\n      -> preP = spec_require spec\n      -> evP = spec_events spec\n      -> postP = spec_trans spec\n      -> evP S E /\\ postP S (w_st C)\n      -> create env msg C E.\n\n(* Evaluation step: any of the possible invocations. *)\nInductive step : env -> contract -> message -> contract -> eventlist -> Prop :=\n  | step_totalSupply: forall env sender msg spec C C' E' preP evP postP,\n      w_a C = w_a C'\n      -> msg = mk_msg sender (mc_totalSupply) 0\n      -> spec = funcspec_totalSupply  (w_a C) env msg\n      -> preP = spec_require spec\n      -> evP = spec_events spec\n      -> postP = spec_trans spec\n      -> preP (w_st C) /\\ evP (w_st C) E' /\\ postP (w_st C) (w_st C')\n      -> step env C msg C' E'                    \n\n  | step_transfer: forall env msg C C' E' sender  to v spec preP evP postP,\n      w_a C = w_a C'\n      -> msg = mk_msg sender (mc_transfer to v) 0\n      -> spec = funcspec_transfer to v (w_a C) env msg\n      -> preP = spec_require spec\n      -> evP = spec_events spec\n      -> postP = spec_trans spec\n      -> preP (w_st C) /\\ evP (w_st C) E' /\\ postP (w_st C) (w_st C')\n      -> step env C msg C' E'\n  \n  | step_balanceOf : forall env sender msg owner spec C C' E' ,\n      w_a C = w_a C'\n      -> msg = mk_msg sender (mc_balanceOf owner) 0\n      -> spec = funcspec_balanceOf owner (w_a C) env msg\n      -> (spec_require spec) (w_st C) /\\ (spec_events spec) (w_st C) E' /\\ (spec_trans spec) (w_st C) (w_st C')\n      -> step env C msg C' E'\n              \n  | step_transferFrom_1 : forall env sender msg from to v spec C C' E' ,\n      w_a C = w_a C'\n      -> msg = mk_msg sender (mc_transferFrom from to v) 0\n      -> spec = funcspec_transferFrom_1 from to v (w_a C) env msg\n      -> (spec_require spec) (w_st C) /\\ (spec_events spec) (w_st C) E' /\\ (spec_trans spec) (w_st C) (w_st C')\n      -> step env C msg C' E'\n\n  | step_transferFrom_2 : forall env sender msg from to v spec C C' E' ,\n      w_a C = w_a C'\n      -> msg = mk_msg sender (mc_transferFrom from to v) 0\n      -> spec = funcspec_transferFrom_2 from to v (w_a C) env msg\n      -> (spec_require spec) (w_st C) /\\ (spec_events spec) (w_st C) E' /\\ (spec_trans spec) (w_st C) (w_st C')\n      -> step env C msg C' E'\n\n  | step_approve : forall env sender msg spender v spec C C' E' ,\n      w_a C = w_a C'\n      -> msg = mk_msg sender (mc_approve spender v) 0\n      -> spec = funcspec_approve spender v (w_a C) env msg\n      -> (spec_require spec) (w_st C) /\\ (spec_events spec) (w_st C) E' /\\ (spec_trans spec) (w_st C) (w_st C')\n      -> step env C msg C' E'\n\n  | step_allowance : forall env sender msg owner spender spec C C' E' ,\n      w_a C = w_a C'\n      -> msg = mk_msg sender (mc_allowance owner spender) 0\n      -> spec = funcspec_allowance owner spender (w_a C) env msg\n      -> (spec_require spec) (w_st C) /\\ (spec_events spec) (w_st C) E' /\\ (spec_trans spec) (w_st C) (w_st C')\n      -> step env C msg C' E'\n\n  | step_increaseApproval: forall env sender msg spender addValue spec C C' E',\n       w_a C = w_a C'\n      -> msg = mk_msg sender (mc_approve spender addValue) 0\n      -> spec = funcspec_increaseApproval spender addValue (w_a C) env msg\n      -> (spec_require spec) (w_st C) /\\ (spec_events spec) (w_st C) E' /\\ (spec_trans spec) (w_st C) (w_st C')\n      -> step env C msg C' E'\n  \n  | step_decreaseApproval_1: forall env sender msg spender subValue spec C C' E',\n       w_a C = w_a C'\n      -> msg = mk_msg sender (mc_approve spender subValue) 0\n      -> spec = funcspec_decreaseApproval_1 spender subValue (w_a C) env msg\n      -> (spec_require spec) (w_st C) /\\ (spec_events spec) (w_st C) E' /\\ (spec_trans spec) (w_st C) (w_st C')\n      -> step env C msg C' E'\n\n  |  step_decreaseApproval_2: forall env sender msg spender subValue spec C C' E',\n       w_a C = w_a C'\n      -> msg = mk_msg sender (mc_approve spender subValue) 0\n      -> spec = funcspec_decreaseApproval_2 spender subValue (w_a C) env msg\n      -> (spec_require spec) (w_st C) /\\ (spec_events spec) (w_st C) E' /\\ (spec_trans spec) (w_st C) (w_st C')\n      -> step env C msg C' E'\n\n  | step_transferOwnership: forall env sender msg newOwner spec C C' E',\n      w_a C = w_a C'\n     -> msg = mk_msg sender (mc_OwnershipTransferred newOwner) 0\n     -> spec = funcspec_transferOwnership newOwner (w_a C) env msg\n     -> (spec_require spec) (w_st C) /\\ (spec_events spec) (w_st C) E' /\\ (spec_trans spec) (w_st C) (w_st C')\n     -> step env C msg C' E'\n.\n\n(* Evaluation step for the environment. *)\nDefinition env_step (env1: env) (env2: env) : Prop :=\n  env_time env2 >= env_time env1 /\\ env_bhash env2 <> env_bhash env1.\n\n(* Big step *)\nFixpoint steps (env: env) (C: contract) (ml: list message) (env': Model.env) (C': contract) (E: eventlist) :Prop :=\n  match ml with\n    | nil => C' = C /\\ E = nil /\\ env = env'\n    | cons msg ml => exists env'', exists C'', exists E'', exists E',\n                    step env C msg C'' E'' /\\ steps env'' C'' ml env' C' E'\n                    /\\ E = E'' ++ E'\n                    /\\ env_step env env''\n  end.\n\n(* Running a smart contract c in environment env over a list of messages. *)\nDefinition run (env: env) (C: contract) (ml: list message) (C': contract) (E: eventlist) :Prop :=\n  exists env',\n    steps env C ml env' C' E.\n", "meta": {"author": "sec-bit", "repo": "tokenlibs-with-proofs", "sha": "9dbe290171784ac833f2239c66b691f0c5e9f14e", "save_path": "github-repos/coq/sec-bit-tokenlibs-with-proofs", "path": "github-repos/coq/sec-bit-tokenlibs-with-proofs/tokenlibs-with-proofs-9dbe290171784ac833f2239c66b691f0c5e9f14e/erc20_lockable/Spec.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3415825061409754, "lm_q1q2_score": 0.20115422512685666}}
{"text": "Require Import VST.veric.juicy_extspec.\nRequire Import VST.floyd.proofauto.\nRequire Export VST.floyd.io_events.\nRequire Export ITree.ITree.\nRequire Export ITree.Eq.Eq.\nRequire Export ITree.Eq.SimUpToTaus.\n(* Import ITreeNotations. *) (* one piece conflicts with subp notation *)\nNotation \"x <- t1 ;; t2\" := (ITree.bind t1 (fun x => t2))\n  (at level 100, t1 at next level, right associativity) : itree_scope.\nNotation \"' p <- t1 ;; t2\" :=\n  (ITree.bind t1 (fun x_ => match x_ with p => t2 end))\n(at level 100, t1 at next level, p pattern, right associativity) : itree_scope.\n\nDefinition stdin := 0%nat.\nDefinition stdout := 1%nat.\n\nSection specs.\n\nContext {E : Type -> Type} `{IO_event(file_id := nat) -< E}.\n\nDefinition putchar_spec :=\n  WITH c : byte, k : IO_itree\n  PRE [ tint ]\n    PROP ()\n    PARAMS (Vubyte c) GLOBALS()\n    SEP (ITREE (write stdout c ;; k))\n  POST [ tint ]\n   EX i : int,\n    PROP (Int.signed i = -1 \\/ Int.signed i = Byte.unsigned c)\n    LOCAL (temp ret_temp (Vint i))\n    SEP (ITREE (if eq_dec (Int.signed i) (-1) then (write stdout c ;; k) else k)).\n\nDefinition getchar_spec :=\n  WITH k : byte -> IO_itree\n  PRE [ ]\n    PROP ()\n    PARAMS () GLOBALS()\n    SEP (ITREE (r <- read stdin ;; k r))\n  POST [ tint ]\n   EX i : int,\n    PROP (-1 <= Int.signed i <= Byte.max_unsigned)\n    LOCAL (temp ret_temp (Vint i))\n    SEP (ITREE (if eq_dec (Int.signed i) (-1) then (r <- read stdin ;; k r) else k (Byte.repr (Int.signed i)))).\n\n(* Build the external specification. *)\nProgram Definition IO_void_Espec : OracleKind := ok_void_spec (@IO_itree E).\n\nDefinition IO_specs (ext_link : string -> ident) :=\n  [(ext_link \"putchar\"%string, putchar_spec); (ext_link \"getchar\"%string, getchar_spec)].\n\nDefinition IO_Espec (ext_link : string -> ident) : OracleKind := add_funspecs IO_void_Espec ext_link (IO_specs ext_link).\n\nEnd specs.\n", "meta": {"author": "anshumanmohan", "repo": "CertiGraph-VST", "sha": "13a28072723615e48ced4182b9d7ca8b002e544f", "save_path": "github-repos/coq/anshumanmohan-CertiGraph-VST", "path": "github-repos/coq/anshumanmohan-CertiGraph-VST/CertiGraph-VST-13a28072723615e48ced4182b9d7ca8b002e544f/VST/progs/io_specs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20112811389726704}}
{"text": "Require Import Verdi.GhostSimulations.\nRequire Import VerdiRaft.Raft.\n\nLocal Arguments update {_} {_} _ _ _ _ _ : simpl never.\n\nRequire Import VerdiRaft.RaftRefinementInterface.\nRequire Import VerdiRaft.CommonTheorems.\nRequire Import VerdiRaft.SpecLemmas.\nRequire Import VerdiRaft.RefinementSpecLemmas.\n\nRequire Import VerdiRaft.LogsLeaderLogsInterface.\nRequire Import VerdiRaft.AppendEntriesRequestLeaderLogsInterface.\nRequire Import VerdiRaft.RefinedLogMatchingLemmasInterface.\nRequire Import VerdiRaft.AllEntriesLeaderLogsTermInterface.\nRequire Import VerdiRaft.LeaderLogsContiguousInterface.\nRequire Import VerdiRaft.OneLeaderLogPerTermInterface.\nRequire Import VerdiRaft.LeaderLogsSortedInterface.\nRequire Import VerdiRaft.TermSanityInterface.\nRequire Import VerdiRaft.AllEntriesTermSanityInterface.\n\nRequire Import VerdiRaft.AllEntriesLogInterface.\n\nSection AllEntriesLog.\n\n  Context {orig_base_params : BaseParams}.\n  Context {one_node_params : OneNodeParams orig_base_params}.\n  Context {raft_params : RaftParams orig_base_params}.\n\n  Context {llli : logs_leaderLogs_interface}.\n  Context {aerlli : append_entries_leaderLogs_interface}.\n  Context {rlmli : refined_log_matching_lemmas_interface}.\n  Context {aellti : allEntries_leaderLogs_term_interface}.\n  Context {llci : leaderLogs_contiguous_interface}.\n  Context {ollpti : one_leaderLog_per_term_interface}.\n  Context {llsi : leaderLogs_sorted_interface}.\n  Context {tsi : term_sanity_interface}.\n  Context {rri : raft_refinement_interface}.\n  Context {aetsi : allEntries_term_sanity_interface}.\n  \n\n  (* strategy : prove allEntries_log as inductive invariant, then\n     prove allEntries_leaderLogs inductive from that *)\n\n  Definition no_entries_past_current_term_host_lifted net :=\n    forall (h : name) e,\n      In e (log (snd (nwState net h))) ->\n      eTerm e <= currentTerm (snd (nwState net h)).\n\n  Lemma no_entries_past_current_term_host_lifted_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      no_entries_past_current_term_host_lifted net.\n  Proof using rri tsi. \n    unfold no_entries_past_current_term_host_lifted.\n    pose proof deghost_spec.\n    do 4 intro.\n    repeat find_reverse_higher_order_rewrite.\n    eapply lift_prop; eauto.\n    intros.\n    find_apply_lem_hyp no_entries_past_current_term_invariant; eauto.\n  Qed.\n  \n(** Succeed iff [x] is in the list [ls], represented with left-associated nested tuples. *)\nLtac inList x ls :=\n  match ls with\n    | x => idtac\n    | (_, x) => idtac\n    | (?LS, _) => inList x LS\n  end.\n\n(** Try calling tactic function [f] on every element of tupled list [ls], keeping the first call not to fail. *)\nLtac app f ls :=\n  match ls with\n    | (?LS, ?X) => f X || app f LS || fail 1\n    | _ => f ls\n  end.\n\n(** Run [f] on every element of [ls], not just the first that doesn't fail. *)\nLtac all f ls :=\n  match ls with\n    | (?LS, ?X) => f X; all f LS\n    | (_, _) => fail 1\n    | _ => f ls\n  end.\n\n\n  Lemma appendEntries_haveNewEntries_false :\n    forall net p t n pli plt es ci h e,\n      refined_raft_intermediate_reachable net ->\n      In p (nwPackets net) ->\n      pBody p = AppendEntries t n pli plt es ci ->\n      haveNewEntries (snd (nwState net h)) es = false ->\n      In e es ->\n      In e (log (snd (nwState net h))).\n  Proof using rlmli. \n    intros.\n    unfold haveNewEntries in *. do_bool. intuition;\n      [unfold not_empty in *; break_match; subst; simpl in *; intuition; congruence|].\n    break_match; try congruence.\n    do_bool. find_apply_lem_hyp findAtIndex_elim. intuition.\n    assert (es <> nil) by (destruct es; subst; simpl in *; intuition; congruence).\n    find_eapply_lem_hyp maxIndex_non_empty.\n    break_exists. intuition.\n    find_copy_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n    match goal with\n      | H : In e es |- _ => copy_eapply maxIndex_is_max H; eauto\n    end.\n    repeat find_rewrite.\n    find_eapply_lem_hyp entries_match_nw_host_invariant; eauto.\n  Qed.\n  \n  Lemma maxIndex_le :\n    forall l1 l2,\n      sorted l1 ->\n      contiguous_range_exact_lo l1 0 ->\n      findAtIndex l1 (maxIndex l2) = None ->\n      l2 = nil\n      \\/ (exists e, In e l2 /\\ eIndex e = 0)\n      \\/ maxIndex l1 <= maxIndex l2.\n  Proof using. \n    intros. destruct l2; intuition.\n    simpl in *. right.\n    destruct l1; intuition.\n    find_copy_eapply_lem_hyp findAtIndex_None; simpl in *; eauto.\n    unfold contiguous_range_exact_lo in *.\n    simpl in *. intuition.\n    destruct (lt_eq_lt_dec 0 (eIndex e)); intuition; eauto.\n    destruct (lt_eq_lt_dec (eIndex e0) (eIndex e)); intuition.\n    exfalso. repeat break_if; do_bool; intuition.\n    match goal with\n      | H : forall _, _ < _ <= _ -> _ |- _ =>\n        specialize (H (eIndex e))\n    end; conclude_using lia.\n    simpl in *. break_exists. intuition; subst; intuition.\n    eapply findAtIndex_None; eauto.\n  Qed.\n\n  Lemma maxIndex_le' :\n    forall l1 l2 i,\n      sorted l1 ->\n      contiguous_range_exact_lo l1 0 ->\n      l2 <> nil ->\n      contiguous_range_exact_lo l2 i ->\n      findAtIndex l1 (maxIndex l2) = None ->\n      maxIndex l1 <= maxIndex l2.\n  Proof using. \n    intros. find_eapply_lem_hyp maxIndex_le; intuition; eauto.\n    break_exists. intuition.\n    unfold contiguous_range_exact_lo in *.\n    intuition.\n    find_insterU. conclude_using eauto. lia.\n  Qed.\n                                 \n  Lemma sorted_app_in_in :\n    forall l1 l2 e e',\n      sorted (l1 ++ l2) ->\n      In e l1 ->\n      In e' l2 ->\n      eIndex e' < eIndex e.\n  Proof using. \n    induction l1; intros; simpl in *; intuition; eauto.\n    subst. find_insterU. conclude_using ltac:(apply in_app_iff; intuition eauto).\n    intuition.\n  Qed.\n  \n  Lemma sorted_app_sorted_app_in1_in2 :\n    forall l1 l2 l3 e e',\n      sorted (l1 ++ l3) ->\n      sorted (l2 ++ l3) ->\n      In e l1 ->\n      In e' (l2 ++ l3) ->\n      eIndex e' = eIndex e ->\n      In e' l2.\n  Proof using. \n    intros. do_in_app. intuition.\n    match goal with\n      | H : sorted (?l ++ ?l'), _ : In _ ?l, _ : In _ ?l' |- _ =>\n        eapply sorted_app_in_in in H\n    end; eauto.  lia.\n  Qed.\n\n  Lemma sorted_app_sorted_app_in1_in2_prefix :\n    forall l1 l2 l3 l4 e e',\n      sorted (l1 ++ l3) ->\n      sorted (l2 ++ l4) ->\n      Prefix l4 l3 ->\n      In e l1 ->\n      In e' (l2 ++ l4) ->\n      eIndex e' = eIndex e ->\n      In e' l2.\n  Proof using. \n    intros. do_in_app. intuition.\n    find_eapply_lem_hyp Prefix_In; [|eauto].\n    match goal with\n      | H : sorted (?l ++ ?l'), _ : In _ ?l, _ : In _ ?l' |- _ =>\n        eapply sorted_app_in_in in H\n    end; eauto. lia.\n  Qed.\n\n  Lemma sorted_app_in2_in2 :\n    forall l1 l2 e e',\n      sorted (l1 ++ l2) ->\n      In e' (l1 ++ l2) ->\n      In e l2 ->\n      eIndex e' = eIndex e ->\n      In e' l2.\n  Proof using. \n    intros. do_in_app. intuition.\n    match goal with\n      | H : sorted (?l ++ ?l'), _ : In _ ?l, _ : In _ ?l' |- _ =>\n        eapply sorted_app_in_in in H\n    end; eauto.  lia.\n  Qed.\n\n(*\n  Lemma sorted_app_in3_in4_prefix :\n    forall l1 l2 l3 l4 e e',\n      sorted (l1 ++ l3) ->\n      sorted (l2 ++ l4) ->\n      Prefix l4 l3 ->\n      In e l3 ->\n      In e' (l2 ++ l4) ->\n      eIndex e' = eIndex e ->\n      In e' l4.\n  Proof.\n    intros. do_in_app. intuition.\n    match goal with\n      | H : sorted (?l ++ ?l'), _ : In _ ?l, _ : In _ ?l' |- _ =>\n        eapply sorted_app_in_in in H\n    end; eauto.  lia.\n  Qed.\n*)\n  Lemma sorted_term_index_le :\n    forall l e e',\n      sorted l ->\n      In e l ->\n      In e' l ->\n      eTerm e' < eTerm e ->\n      eIndex e' <= eIndex e.\n  Proof using. \n    induction l; intros; simpl in *; intuition; subst_max; intuition.\n    - find_apply_hyp_hyp. intuition.\n    - find_apply_hyp_hyp. intuition.\n  Qed.\n  Lemma term_ne_in_l2 :\n    forall l e e' l1 l2,\n      sorted l ->\n      In e l ->\n      (forall e', In e' l -> eTerm e' <= eTerm e) ->\n      removeAfterIndex l (eIndex e) = l1 ++ l2 ->\n      (forall e', In e' l1 -> eTerm e' = eTerm e) ->\n      In e' l ->\n      eTerm e' <> eTerm e ->\n      In e' l2.\n  Proof using. \n    intros.\n    assert (eIndex e' <= eIndex e) by\n        (eapply sorted_term_index_le; eauto;\n         find_apply_hyp_hyp;\n         destruct (lt_eq_lt_dec (eTerm e') (eTerm e)); intuition).\n    find_eapply_lem_hyp removeAfterIndex_le_In; eauto.\n    repeat find_rewrite.\n    do_in_app. intuition.\n    find_apply_hyp_hyp. intuition.\n  Qed.\n\n  Lemma Prefix_maxIndex_eq :\n    forall l l',\n      Prefix l l' ->\n      l <> nil ->\n      maxIndex l = maxIndex l'.\n  Proof using. \n    intros.\n    induction l; simpl in *; intuition.\n    break_match; intuition. subst. simpl. auto.\n  Qed.\n\n  Lemma sorted_gt_maxIndex :\n    forall e l1 l2,\n      sorted (e :: l1 ++ l2) ->\n      l2 <> nil ->\n      maxIndex l2 < eIndex e.\n  Proof using. \n    intros; induction l1; simpl in *; intuition.\n    - destruct l2; simpl in *; intuition.\n      match goal with\n        | H : forall _, ?e = _ \\/ _ -> _ |- _ =>\n          specialize (H e)\n      end; intuition.\n  Qed.\n  \n  Lemma allEntries_log_append_entries :\n    refined_raft_net_invariant_append_entries allEntries_log.\n  Proof using aetsi rri tsi llsi ollpti llci aellti rlmli aerlli llli. \n    red. unfold allEntries_log in *. simpl in *. intros.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *;\n    [|find_apply_hyp_hyp; intuition;\n      right; break_exists_exists; intuition;\n      repeat find_higher_order_rewrite;\n      destruct_update; simpl in *;\n      eauto; rewrite update_elections_data_appendEntries_leaderLogs; eauto].\n    find_eapply_lem_hyp update_elections_data_appendEntries_allEntries_detailed; eauto.\n    intuition;\n      [|repeat find_rewrite;\n         find_eapply_lem_hyp appendEntries_haveNewEntries_false; eauto].\n    find_copy_apply_hyp_hyp. intuition;\n      [|right; break_exists_exists; intuition;\n        repeat find_higher_order_rewrite; destruct_update; simpl in *; eauto;\n        try rewrite update_elections_data_appendEntries_leaderLogs; eauto; subst;\n        find_apply_lem_hyp handleAppendEntries_currentTerm_leaderId; intuition;\n        repeat find_rewrite; auto].\n    destruct (in_dec entry_eq_dec e (log d)); intuition.\n    right.\n    find_copy_apply_lem_hyp handleAppendEntries_log_detailed.\n    intuition; repeat find_rewrite; intuition.\n    - subst.\n      find_copy_eapply_lem_hyp allEntries_term_sanity_invariant; eauto.\n      destruct (lt_eq_lt_dec t0 (currentTerm d)); intuition; unfold ghost_data in *; simpl in *; try lia.\n      + eapply append_entries_leaderLogs_invariant in H1; eauto.\n        break_exists. break_and.\n        match goal with\n          | H : In (?t, ?ll) (leaderLogs (fst (nwState _ ?leader))) |- _ =>\n            (exists t, leader, ll)\n        end.\n        split;\n          [repeat find_higher_order_rewrite;\n            destruct_update; simpl in *;\n            eauto; rewrite update_elections_data_appendEntries_leaderLogs; eauto|];\n          split; auto; intuition;\n          [break_exists; intuition;\n           find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto; lia|].\n          subst. repeat find_rewrite. intuition.\n      + subst.\n        find_eapply_lem_hyp allEntries_leaderLogs_term_invariant; eauto. intuition.\n        * subst. exfalso.\n          find_copy_eapply_lem_hyp logs_leaderLogs_invariant; eauto.\n          pose proof H1 as H1'.\n          eapply append_entries_leaderLogs_invariant in H1; eauto.\n          break_exists; intuition;\n          [break_exists; intuition;\n           find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto; lia|].\n          subst. clean.\n          repeat find_rewrite.\n          find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto;\n          conclude_using eauto. subst.\n          match goal with\n            | H : In _ _ -> False |- _ =>\n              apply H\n          end.\n          find_copy_eapply_lem_hyp entries_sorted_invariant; eauto.\n          unfold entries_sorted in *.\n          repeat find_rewrite.\n          match goal with\n            | _ : removeAfterIndex ?l (eIndex ?e) = _ |- _ =>\n              assert (In e (removeAfterIndex l (eIndex e))) by\n                  (eapply removeAfterIndex_le_In; eauto)\n          end.\n          repeat find_rewrite.\n          do_in_app; intuition.\n          assert (exists e', eIndex e' = eIndex e /\\ In e' (x1 ++ x4)) by\n              (eapply entries_contiguous_nw_invariant; eauto;\n               intuition; [eapply entries_contiguous_invariant; eauto|];\n               eapply Nat.le_trans; [eapply maxIndex_is_max; eauto|];\n               eapply maxIndex_le'; eauto;\n               [eapply entries_contiguous_invariant; eauto|\n                eapply entries_contiguous_nw_invariant; eauto]).\n          break_exists. intuition.\n          find_copy_eapply_lem_hyp sorted_app_sorted_app_in1_in2. 5: { eauto. } 4: { eauto. }\n          all:(try solve [eapply entries_sorted_nw_invariant; eauto]).\n          all:(try solve [repeat find_reverse_rewrite; eauto using removeAfterIndex_sorted]).\n          find_apply_hyp_hyp.\n          find_eapply_lem_hyp entries_match_nw_host_invariant; eauto; repeat conclude_using eauto.\n          match goal with\n            | H : eIndex _ = eIndex _ |- _ =>\n              eapply uniqueIndices_elim_eq in H\n          end; eauto using sorted_uniqueIndices.\n          subst. auto.\n        * exfalso.\n          pose proof H1 as H1'.\n          eapply append_entries_leaderLogs_invariant in H1; eauto.\n          break_exists; intuition;\n          [break_exists; intuition;\n           find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto; lia|].\n          subst. clean.\n          find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto;\n          conclude_using eauto. subst.\n          match goal with\n            | H : In _ _ -> False |- _ =>\n              apply H\n          end.\n          repeat find_rewrite. apply in_app_iff; intuition.\n    - subst.\n      find_copy_eapply_lem_hyp allEntries_term_sanity_invariant; eauto.\n      destruct (lt_eq_lt_dec t0 (currentTerm d)); intuition; unfold ghost_data in *; simpl in *; try lia.\n      + eapply append_entries_leaderLogs_invariant in H1; eauto.\n        break_exists. break_and.\n        match goal with\n          | H : In (?t, ?ll) (leaderLogs (fst (nwState _ ?leader))) |- _ =>\n            (exists t, leader, ll)\n        end. find_higher_order_rewrite.\n        split;\n          [subst; find_higher_order_rewrite;\n            destruct_update; simpl in *;\n            eauto; rewrite update_elections_data_appendEntries_leaderLogs; eauto|];\n          split; auto.\n        intuition;\n          [break_exists; intuition;\n           find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto; lia|].\n        subst. repeat find_rewrite. intuition.\n      + subst.\n        find_eapply_lem_hyp allEntries_leaderLogs_term_invariant; eauto. intuition.\n        * { subst. exfalso.\n            find_copy_eapply_lem_hyp logs_leaderLogs_invariant; eauto.\n            pose proof H1 as H1'.\n            eapply append_entries_leaderLogs_invariant in H1; eauto.\n            break_exists; intuition;\n            [break_exists; intuition;\n             find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto; lia|].\n            subst. clean.\n            repeat find_rewrite.\n            find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto;\n            conclude_using eauto. subst.\n            match goal with\n              | H : In _ _ -> False |- _ =>\n                apply H\n            end.\n            find_copy_eapply_lem_hyp entries_sorted_invariant; eauto.\n            unfold entries_sorted in *.\n            repeat find_rewrite.\n            match goal with\n              | _ : removeAfterIndex ?l (eIndex ?e) = _ |- _ =>\n                assert (In e (removeAfterIndex l (eIndex e))) by\n                    (eapply removeAfterIndex_le_In; eauto)\n            end.\n            repeat find_rewrite.\n            do_in_app; intuition.\n            find_apply_lem_hyp findAtIndex_elim. intuition.\n            find_copy_apply_lem_hyp maxIndex_non_empty.\n            break_exists.\n            intuition.\n            match goal with\n              | _ : In ?e' (log _), _ : maxIndex ?l = eIndex ?e' |- _ =>\n                destruct (le_lt_dec (eIndex e) (maxIndex l))\n            end.\n            - assert (exists e', eIndex e' = eIndex e /\\ In e' (x1 ++ x4)) by\n                  (eapply entries_contiguous_nw_invariant; eauto; intuition;\n                   eapply entries_gt_0_invariant; eauto).\n              break_exists. intuition.\n              find_copy_eapply_lem_hyp sorted_app_sorted_app_in1_in2. 5: { eauto. } 4: { eauto. }\n              all:(try solve [eapply entries_sorted_nw_invariant; eauto]).\n              all:(try solve [repeat find_reverse_rewrite; eauto using removeAfterIndex_sorted]).\n              find_apply_hyp_hyp.\n              find_eapply_lem_hyp entries_match_nw_host_invariant; eauto; repeat conclude_using eauto.\n              match goal with\n                | H : eIndex _ = eIndex _ |- _ =>\n                  eapply uniqueIndices_elim_eq in H\n              end; eauto using sorted_uniqueIndices.\n              subst. auto.\n            - exfalso.\n              repeat find_rewrite.\n              match goal with\n                | _ : eIndex ?e' = eIndex ?x,\n                  _ : eIndex ?x < ?i,\n                  _ : context [removeAfterIndex ?l ?i] |- _ =>\n                  assert (In e' (removeAfterIndex l i)) by\n                      (eapply removeAfterIndex_le_In; auto; lia)\n              end.\n              repeat find_rewrite.\n              do_in_app. intuition.\n              + find_copy_eapply_lem_hyp sorted_app_sorted_app_in1_in2. 4: { eauto. }\n                all:eauto.\n                all:(try solve [eapply entries_sorted_nw_invariant; eauto]).\n                all:(try solve [repeat find_reverse_rewrite; eauto using removeAfterIndex_sorted]).\n                repeat find_apply_hyp_hyp. repeat find_rewrite. intuition.\n              + find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                find_copy_eapply_lem_hyp sorted_app_in2_in2. 3: { eauto. }\n                all:eauto.\n                all:(try solve [eapply entries_sorted_nw_invariant; eauto]).\n                match goal with\n                  | H : eIndex ?e1 = eIndex ?e2, _ : In ?e1 ?ll, _ : In ?e2 ?ll |- _ =>\n                    eapply @uniqueIndices_elim_eq with (xs := ll) in H\n                end; eauto using sorted_uniqueIndices.\n                subst. intuition.\n          }\n        * exfalso.\n          pose proof H1 as H1'.\n          eapply append_entries_leaderLogs_invariant in H1; eauto.\n          break_exists; intuition;\n          [break_exists; intuition;\n           find_eapply_lem_hyp leaderLogs_contiguous_invariant; eauto; lia|].\n          subst. clean.\n          find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto;\n          conclude_using eauto. subst.\n          match goal with\n            | H : In _ _ -> False |- _ =>\n              apply H\n          end.\n          repeat find_rewrite. apply in_app_iff; intuition.\n    - find_copy_eapply_lem_hyp allEntries_term_sanity_invariant; eauto.\n      destruct (lt_eq_lt_dec t0 t); intuition; unfold ghost_data in *; simpl in *; try lia.\n      + match goal with\n          | H : context [pBody] |- _ =>\n            copy_eapply append_entries_leaderLogs_invariant H\n        end; eauto.\n        break_exists. break_and. subst.\n        match goal with\n          | H : In (?t, ?ll) (leaderLogs (fst (nwState _ ?leader))) |- _ =>\n            (exists t, leader, ll)\n        end.\n        split;\n          [find_higher_order_rewrite;\n            destruct_update; simpl in *;\n            eauto; rewrite update_elections_data_appendEntries_leaderLogs; eauto|];\n          split; auto. intuition; subst.\n        * contradict n0.\n          apply in_app_iff. right. eapply removeAfterIndex_le_In; eauto.\n          find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n          eapply Nat.le_trans; [eapply maxIndex_is_max; eauto|]. lia.\n        * {\n            break_exists. intuition. unfold Prefix_sane in *. intuition.\n            - destruct (le_lt_dec (eIndex e) (eIndex x3)).\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. right. apply removeAfterIndex_le_In; auto.\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. left.\n                apply in_app_iff. right.\n                find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                eapply prefix_contiguous; eauto.\n                find_copy_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n                eapply contiguous_app; eauto.\n                eapply entries_contiguous_nw_invariant; eauto.\n            - contradict n0.\n              repeat find_rewrite.\n              apply in_app_iff. right.\n              find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n              apply removeAfterIndex_le_In; auto.\n              eapply maxIndex_is_max; eauto.\n          }\n        * contradict n0. intuition.\n      + subst.\n        find_eapply_lem_hyp allEntries_leaderLogs_term_invariant; eauto. intuition.\n        * { subst. exfalso.\n            find_copy_eapply_lem_hyp logs_leaderLogs_invariant; eauto.\n            pose proof H1 as H1'.\n            eapply append_entries_leaderLogs_invariant in H1; eauto.\n            break_exists. break_and.\n            repeat find_rewrite.\n            find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto.\n            conclude_using eauto. subst. intuition.\n            - repeat find_rewrite.\n              destruct (le_lt_dec (eIndex e) (eIndex x6)).\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. right. apply removeAfterIndex_le_In; auto.\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. left.\n                find_copy_eapply_lem_hyp entries_sorted_invariant.\n                find_eapply_lem_hyp maxIndex_le'; eauto;\n                [|eapply entries_contiguous_invariant; eauto|eapply entries_contiguous_nw_invariant; eauto].\n                find_copy_eapply_lem_hyp entries_contiguous_nw_invariant; eauto.\n                unfold contiguous_range_exact_lo in *.\n                break_and.\n                find_copy_eapply_lem_hyp entries_sorted_invariant.\n                match goal with\n                  | H : forall _, _ < _ <= _ -> _ |- _ =>\n                    specialize (H (eIndex e));\n                      conclude_using ltac:(intuition; eapply Nat.le_trans; [eapply maxIndex_is_max; eauto|]; eauto)\n                end.\n                break_exists. break_and.\n                match goal with\n                  | H : eIndex ?x = eIndex e |- _ =>\n                    copy_eapply entries_match_nw_host_invariant H\n                end; eauto.\n                find_copy_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                conclude_using\n                  ltac:(match goal with\n                          | H : _ |- _ => apply H\n                        end; do_in_app; intuition;\n                        match goal with\n                          | H : In ?x _ |- In ?x _ =>\n                            copy_eapply Prefix_maxIndex H\n                        end; [|idtac|eauto]; eauto; lia).\n                conclude_using eauto. conclude_using auto.\n                match goal with\n                  | H : _ = _ |- _ =>\n                    eapply uniqueIndices_elim_eq in H\n                end; eauto; eauto using sorted_uniqueIndices.\n                subst. auto.\n            - break_exists. break_and.\n              destruct (le_lt_dec (eIndex e) (eIndex x6)).\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. right. apply removeAfterIndex_le_In; auto.\n              + match goal with\n                  | _ : removeAfterIndex _ (eIndex ?e) = ?l |- _ =>\n                    assert (In e l) by (repeat find_reverse_rewrite;\n                                        eapply removeAfterIndex_le_In; auto)\n                end.\n                find_copy_eapply_lem_hyp entries_sorted_invariant.\n                assert (exists e', eIndex e' = eIndex e /\\ In e' (x1 ++ x2)) by\n                      (eapply entries_contiguous_nw_invariant; eauto;\n                       intuition;\n                       eapply Nat.le_trans; [eapply maxIndex_is_max; eauto|];\n                       eapply maxIndex_le'; eauto;\n                       [eapply entries_contiguous_invariant; eauto|\n                        eapply entries_contiguous_nw_invariant; eauto]).\n                do_in_app. intuition.\n                * break_exists. break_and.\n                  match goal with\n                    | H : eIndex _ = eIndex _ |- _ =>\n                      copy_eapply sorted_app_sorted_app_in1_in2_prefix H\n                  end; eauto.\n                  all:try solve [repeat find_reverse_rewrite; eauto using removeAfterIndex_sorted].\n                  all:try solve [eapply entries_sorted_nw_invariant; eauto].\n                  find_apply_hyp_hyp.\n                  match goal with\n                    | H : In e _ -> False |- _ => apply H\n                  end.\n                  apply in_app_iff. left.\n                  match goal with\n                    | H : eIndex _ = eIndex _ |- _ =>\n                      copy_eapply entries_match_nw_host_invariant H\n                  end; eauto. concludes. repeat conclude_using eauto.\n                  match goal with\n                    | H : eIndex _ = eIndex _ |- _ =>\n                      copy_eapply uniqueIndices_elim_eq H\n                  end; eauto using sorted_uniqueIndices. subst. auto.\n                * find_copy_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                  unfold Prefix_sane in *.\n                  intuition; [|find_eapply_lem_hyp maxIndex_is_max; eauto; lia].\n                  find_eapply_lem_hyp prefix_contiguous. 2: { eauto. }\n                  all:eauto.\n                  all:try solve [eapply contiguous_app; [|eapply entries_contiguous_nw_invariant; eauto];\n                                 eapply entries_sorted_nw_invariant; eauto].\n                  match goal with\n                    | H : In e _ -> False |- _ => apply H\n                  end. intuition.\n            - subst.\n              destruct (le_lt_dec (eIndex e) (eIndex x6)).\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. right. apply removeAfterIndex_le_In; auto.\n              + match goal with\n                  | _ : removeAfterIndex _ (eIndex ?e) = ?l |- _ =>\n                    assert (In e l) by (repeat find_reverse_rewrite;\n                                        eapply removeAfterIndex_le_In; auto)\n                end.\n                find_copy_eapply_lem_hyp entries_sorted_invariant.\n                assert (exists e', eIndex e' = eIndex e /\\ In e' (x1 ++ x4)) by\n                      (eapply entries_contiguous_nw_invariant; eauto;\n                       intuition;\n                       eapply Nat.le_trans; [eapply maxIndex_is_max; eauto|];\n                       eapply maxIndex_le'; eauto;\n                       [eapply entries_contiguous_invariant; eauto|\n                        eapply entries_contiguous_nw_invariant; eauto]).\n                do_in_app. intuition.\n                * break_exists. break_and.\n                  match goal with\n                    | H : eIndex _ = eIndex _ |- _ =>\n                      copy_eapply sorted_app_sorted_app_in1_in2 H\n                  end; eauto.\n                  all:try solve [repeat find_reverse_rewrite; eauto using removeAfterIndex_sorted].\n                  all:try solve [eapply entries_sorted_nw_invariant; eauto].\n                  find_apply_hyp_hyp.\n                  match goal with\n                    | H : In e _ -> False |- _ => apply H\n                  end.\n                  apply in_app_iff. left.\n                  match goal with\n                    | H : eIndex _ = eIndex _ |- _ =>\n                      copy_eapply entries_match_nw_host_invariant H\n                  end; eauto. concludes. repeat conclude_using eauto.\n                  match goal with\n                    | H : eIndex _ = eIndex _ |- _ =>\n                      copy_eapply uniqueIndices_elim_eq H\n                  end; eauto using sorted_uniqueIndices. subst. auto.\n                * match goal with\n                    | H : In e _ -> False |- _ => apply H\n                  end. intuition.\n          }\n        * { exfalso.\n            find_copy_apply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n            break_exists; intuition.\n            copy_eapply_prop_hyp append_entries_leaderLogs pBody; eauto.\n            break_exists; break_and.\n            subst. \n            find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto;\n            conclude_using eauto. subst.\n            match goal with\n              | H : In _ _ -> False |- _ =>\n                apply H\n            end.\n            find_copy_apply_lem_hyp leaderLogs_sorted_invariant; auto.\n            find_copy_apply_lem_hyp maxIndex_is_max; auto. \n            destruct (le_lt_dec (eIndex e) (eIndex x1));\n              [apply in_app_iff; right; eapply removeAfterIndex_le_In; eauto|].\n            repeat find_rewrite. apply in_app_iff; intuition.\n            - lia.\n            - break_exists; break_and.\n              unfold Prefix_sane in *. break_or_hyp; try lia.\n              left; apply in_app_iff; right.\n              eapply prefix_contiguous; eauto.\n              eapply contiguous_app; [|eapply entries_contiguous_nw_invariant; eauto];\n              eapply entries_sorted_nw_invariant; eauto.\n            - subst. intuition.\n          }\n    - find_copy_eapply_lem_hyp allEntries_term_sanity_invariant; eauto.\n      destruct (lt_eq_lt_dec t0 t); intuition; unfold ghost_data in *; simpl in *; try lia.\n      + match goal with\n          | H : context [pBody] |- _ =>\n            copy_eapply append_entries_leaderLogs_invariant H\n        end; eauto.\n        break_exists. break_and. subst.\n        match goal with\n          | H : In (?t, ?ll) (leaderLogs (fst (nwState _ ?leader))) |- _ =>\n            (exists t, leader, ll)\n        end.\n        split;\n          [find_higher_order_rewrite;\n            destruct_update; simpl in *;\n            eauto; rewrite update_elections_data_appendEntries_leaderLogs; eauto|];\n          split; auto. intuition; subst.\n        * contradict n0.\n          apply in_app_iff. right. eapply removeAfterIndex_le_In; eauto.\n          find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n          eapply Nat.le_trans; [eapply maxIndex_is_max; eauto|]. lia.\n        * {\n            break_exists. intuition. unfold Prefix_sane in *. intuition.\n            - destruct (le_lt_dec (eIndex e) (eIndex x4)).\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. right. apply removeAfterIndex_le_In; auto.\n              + match goal with\n                  | H : In e _ -> False |- _ => apply H\n                end.\n                apply in_app_iff. left.\n                apply in_app_iff. right.\n                find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n                eapply prefix_contiguous; eauto.\n                find_copy_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n                eapply contiguous_app; eauto.\n                eapply entries_contiguous_nw_invariant; eauto.\n            - contradict n0.\n              repeat find_rewrite.\n              apply in_app_iff. right.\n              find_eapply_lem_hyp leaderLogs_sorted_invariant; eauto.\n              apply removeAfterIndex_le_In; auto.\n              eapply maxIndex_is_max; eauto.\n          }\n        * contradict n0. intuition.\n      + subst.\n        find_eapply_lem_hyp allEntries_leaderLogs_term_invariant; eauto. intuition.\n        * { subst. exfalso.\n            find_copy_eapply_lem_hyp logs_leaderLogs_invariant; eauto.\n            pose proof H1 as H1'.\n            eapply append_entries_leaderLogs_invariant in H1; eauto.\n            break_exists. break_and.\n            find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto.\n            repeat find_rewrite.\n            conclude_using eauto. subst.\n            find_eapply_lem_hyp Nat.le_antisymm; eauto.\n            destruct x1.\n            - simpl in *. destruct x2; simpl in *; auto.\n              break_match; auto.\n              match goal with\n                | H : _ \\/ (exists _, _) \\/ _ |- _ =>\n                  clear H\n              end.\n              break_and. subst.\n              cut (e1 = x6); intros; subst; auto.\n              find_apply_lem_hyp findAtIndex_elim.\n              break_and.\n              find_copy_apply_lem_hyp entries_sorted_invariant.\n              eapply uniqueIndices_elim_eq; eauto using sorted_uniqueIndices.\n              eapply removeAfterIndex_in with (i := (eIndex e)).\n              unfold raft_data, ghost_data in *; simpl in *.\n              unfold raft_data, ghost_data in *; simpl in *.\n              repeat find_rewrite. intuition.\n            - simpl in *.\n              match goal with\n                | H : forall _, ?e = _ \\/ _ -> _ |- _ =>\n                  specialize (H e)\n              end. conclude_using auto.\n              repeat find_rewrite.\n              find_apply_lem_hyp findAtIndex_elim. break_and.\n              find_eapply_lem_hyp term_ne_in_l2. 7: { eauto. } all:eauto.\n              all:try solve [eapply entries_sorted_invariant; eauto].\n              all:try solve [intros; find_eapply_lem_hyp no_entries_past_current_term_host_lifted_invariant; unfold ghost_data, raft_data in *; simpl in *;\n                             unfold ghost_data, raft_data in *; simpl in *;\n                             repeat find_rewrite; eauto].\n              assert (eIndex e0 <= maxIndex x4) by \n                  (repeat find_rewrite;\n                   eapply maxIndex_is_max; eauto;\n                   eapply leaderLogs_sorted_invariant; eauto).\n              assert (eIndex x7 < eIndex e0) by\n                  (eapply entries_contiguous_nw_invariant; eauto; intuition).\n              intuition.\n              + break_exists. break_and.\n                unfold Prefix_sane in *. intuition.\n                find_copy_eapply_lem_hyp Prefix_maxIndex_eq; eauto.\n                find_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n                find_eapply_lem_hyp sorted_gt_maxIndex; eauto; lia.\n              + subst.\n                find_eapply_lem_hyp entries_sorted_nw_invariant; eauto.\n                find_eapply_lem_hyp sorted_gt_maxIndex; eauto; try lia.\n                destruct x4; simpl in *; congruence.\n          }\n        * { exfalso.\n            find_copy_apply_lem_hyp append_entries_leaderLogs_invariant; eauto.\n            break_exists; intuition. subst.\n            copy_eapply_prop_hyp append_entries_leaderLogs pBody; eauto.\n            break_exists; break_and.\n            subst. \n            find_eapply_lem_hyp one_leaderLog_per_term_log_invariant; eauto;\n            conclude_using eauto. subst.\n            match goal with\n              | H : In _ _ -> False |- _ =>\n                apply H\n            end.\n            find_copy_apply_lem_hyp leaderLogs_sorted_invariant; auto.\n            find_copy_apply_lem_hyp maxIndex_is_max; auto. \n            destruct (le_lt_dec (eIndex e) (eIndex x2));\n              [apply in_app_iff; right; eapply removeAfterIndex_le_In; eauto|].\n            repeat find_rewrite. apply in_app_iff; intuition.\n            - lia.\n            - break_exists; break_and.\n              unfold Prefix_sane in *. break_or_hyp; try lia.\n              left; apply in_app_iff; right.\n              eapply prefix_contiguous; eauto.\n              eapply contiguous_app; [|eapply entries_contiguous_nw_invariant; eauto];\n              eapply entries_sorted_nw_invariant; eauto.\n            - subst. intuition.\n          }\n  Qed.\n\n  Lemma handleAppendEntriesReply_currentTerm_leaderId :\n    forall h st h' t es res st' m,\n      handleAppendEntriesReply h st h' t es res = (st', m) ->\n      currentTerm st < currentTerm st' \\/\n      (currentTerm st = currentTerm st' /\\ leaderId st' = leaderId st).\n  Proof using. \n    intros. unfold handleAppendEntriesReply, advanceCurrentTerm in *.\n    repeat (break_match; try find_inversion; simpl in *; do_bool; auto).\n  Qed.\n\n  Lemma allEntries_log_append_entries_reply :\n    refined_raft_net_invariant_append_entries_reply allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_copy_apply_lem_hyp handleAppendEntriesReply_log.\n    find_apply_lem_hyp handleAppendEntriesReply_currentTerm_leaderId.\n    destruct_update; simpl in *; eauto; find_apply_hyp_hyp; repeat find_rewrite; intuition;\n    right; break_exists_exists; repeat find_rewrite; intuition;\n    find_higher_order_rewrite;\n    destruct_update; simpl in *; auto.\n  Qed.\n\n  Lemma update_elections_data_requestVote_leaderLogs :\n    forall h h' t lli llt st,\n      leaderLogs (update_elections_data_requestVote h h' t h' lli llt st) =\n      leaderLogs (fst st).\n  Proof using. \n    unfold update_elections_data_requestVote.\n    intros.\n    repeat break_match; auto.\n  Qed.\n\n  Lemma update_elections_data_requestVoteReply_leaderLogs :\n    forall h h' t  st t' ll' r,\n      In (t', ll') (leaderLogs (fst st)) ->\n      In (t', ll') (leaderLogs (update_elections_data_requestVoteReply h h' t r st)).\n  Proof using. \n    unfold update_elections_data_requestVoteReply.\n    intros.\n    repeat break_match; auto.\n    simpl in *. intuition.\n  Qed.\n\n  Lemma allEntries_log_request_vote :\n    refined_raft_net_invariant_request_vote allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    find_copy_apply_lem_hyp handleRequestVote_log.\n    find_apply_lem_hyp handleRequestVote_currentTerm_leaderId.\n    destruct_update; simpl in *; eauto;\n    try find_rewrite_lem update_elections_data_requestVote_allEntries;\n    find_apply_hyp_hyp; repeat find_rewrite; intuition;\n    right; break_exists_exists; intuition; repeat find_higher_order_rewrite;\n    destruct_update; simpl in *; auto;\n    rewrite update_elections_data_requestVote_leaderLogs; auto.\n  Qed.\n\n  Lemma handleRequestVoteReply_log' :\n    forall h st h' t r,\n      log (handleRequestVoteReply h st h' t r) = log st.\n  Proof using. \n    eauto using handleRequestVoteReply_log.\n  Qed.\n\n  Lemma allEntries_log_request_vote_reply :\n    refined_raft_net_invariant_request_vote_reply allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    find_copy_apply_lem_hyp handleRequestVoteReply_currentTerm_leaderId.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *; eauto;\n    try rewrite handleRequestVoteReply_log';\n    try find_rewrite_lem update_elections_data_requestVoteReply_allEntries;\n    find_apply_hyp_hyp; repeat find_rewrite; intuition;\n    right; break_exists_exists; repeat find_rewrite; intuition;\n    find_higher_order_rewrite;\n    destruct_update; simpl in *; auto;\n    apply update_elections_data_requestVoteReply_leaderLogs; auto.\n  Qed.\n\n  Lemma update_elections_data_client_request_allEntries' :\n    forall h st client id c out st' ms t e,\n      handleClientRequest h (snd st) client id c = (out, st', ms) ->\n      In (t, e) (allEntries (update_elections_data_client_request h st client id c)) ->\n      In (t, e) (allEntries (fst st)) \\/\n      In e (log st').\n  Proof using. \n    intros.\n    unfold update_elections_data_client_request in *.\n    repeat break_match; repeat find_inversion; auto.\n    simpl in *. intuition.\n    find_inversion. repeat find_rewrite. intuition.\n  Qed.\n\n  Lemma handleClientRequest_currentTerm_leaderId :\n    forall h st client id c out st' ms,\n      handleClientRequest h st client id c = (out, st', ms) ->\n      currentTerm st' = currentTerm st /\\\n      leaderId st' = leaderId st.\n  Proof using. \n    intros. unfold handleClientRequest in *.\n    subst.\n    break_match; try find_inversion; simpl in *; auto.\n  Qed.\n  \n  Lemma allEntries_log_client_request :\n    refined_raft_net_invariant_client_request allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *;\n    try (find_copy_eapply_lem_hyp update_elections_data_client_request_allEntries'; eauto; [idtac]);\n    intuition;\n    find_copy_apply_lem_hyp handleClientRequest_log;\n    find_apply_lem_hyp handleClientRequest_currentTerm_leaderId;\n    intuition;\n    try break_exists; intuition; repeat find_rewrite; intuition; simpl in *;\n    find_apply_hyp_hyp; intuition; repeat right;\n    break_exists_exists; intuition;\n    repeat find_higher_order_rewrite;\n    destruct_update; simpl in *; auto;\n    rewrite update_elections_data_client_request_leaderLogs; auto.\n  Qed.\n\n  Lemma handleTimeout_currentTerm_leaderId :\n    forall h st out st' ms,\n      handleTimeout h st = (out, st', ms) ->\n      currentTerm st < currentTerm st' \\/\n      currentTerm st' = currentTerm st /\\ leaderId st' = leaderId st.\n  Proof using. \n    intros. unfold handleTimeout, tryToBecomeLeader in *.\n    subst.\n    break_match; try find_inversion; simpl in *; auto.\n  Qed.\n  \n  Lemma allEntries_log_timeout :\n    refined_raft_net_invariant_timeout allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    repeat find_higher_order_rewrite.\n    destruct_update; simpl in *;\n    try find_rewrite_lem update_elections_data_timeout_allEntries;\n    find_copy_apply_lem_hyp handleTimeout_log_same;\n    find_apply_lem_hyp handleTimeout_currentTerm_leaderId;\n    repeat find_rewrite;\n    find_apply_hyp_hyp; intuition;\n    right; break_exists_exists; intuition;\n    repeat find_higher_order_rewrite;\n    destruct_update; simpl in *; auto;\n    rewrite update_elections_data_timeout_leaderLogs; auto.\n  Qed.\n\n  Lemma doLeader_currentTerm_leaderId :\n    forall st h out st' m,\n      doLeader st h = (out, st', m) ->\n      currentTerm st' = currentTerm st /\\\n      leaderId st' = leaderId st.\n  Proof using. \n    intros. unfold doLeader, advanceCommitIndex in *.\n    repeat break_match; find_inversion; simpl in *; auto.\n  Qed.\n  \n  Lemma allEntries_log_do_leader :\n    refined_raft_net_invariant_do_leader allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    repeat find_higher_order_rewrite.\n    find_copy_apply_lem_hyp doLeader_log.\n    find_apply_lem_hyp doLeader_currentTerm_leaderId.\n    destruct_update; simpl in *; eauto; find_apply_hyp_hyp; repeat find_rewrite; intuition;\n    right; break_exists_exists; intuition; find_higher_order_rewrite;\n    destruct_update; simpl in *; auto.\n  Qed.\n\n\n  Lemma doGenericServer_currentTerm_leaderId :\n    forall st h out st' m,\n      doGenericServer h st = (out, st', m) ->\n      currentTerm st' = currentTerm st /\\\n      leaderId st' = leaderId st.\n  Proof using. \n    intros. unfold doGenericServer in *.\n    repeat break_match; find_inversion;\n    use_applyEntries_spec; subst; simpl in *;\n    auto.\n  Qed.\n  \n  Lemma allEntries_log_do_generic_server :\n    refined_raft_net_invariant_do_generic_server allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    repeat find_higher_order_rewrite.\n    find_copy_apply_lem_hyp doGenericServer_log.\n    find_apply_lem_hyp doGenericServer_currentTerm_leaderId.\n    destruct_update; simpl in *; eauto; find_apply_hyp_hyp; repeat find_rewrite; intuition;\n    right; break_exists_exists; intuition; find_higher_order_rewrite;\n    destruct_update; simpl in *; auto.\n  Qed.\n\n  Lemma allEntries_log_init :\n    refined_raft_net_invariant_init allEntries_log.\n  Proof using. \n    red. unfold allEntries_log. intros. simpl in *. intuition.\n  Qed.\n\n  Lemma allEntries_log_state_same_packet_subset :\n    refined_raft_net_invariant_state_same_packet_subset allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros.\n    repeat find_reverse_higher_order_rewrite.\n    find_apply_hyp_hyp. intuition. right.\n    break_exists_exists. repeat find_higher_order_rewrite. auto.\n  Qed.\n\n  Lemma allEntries_log_reboot :\n    refined_raft_net_invariant_reboot allEntries_log.\n  Proof using. \n    red. unfold allEntries_log in *. intros. simpl in *.\n    match goal with\n      | H : nwState ?net ?h = (?gd, ?d) |- _ =>\n        replace gd with (fst (nwState net h)) in * by (rewrite H; reflexivity);\n          replace d with (snd (nwState net h)) in * by (rewrite H; reflexivity);\n          clear H\n    end.\n    repeat find_higher_order_rewrite.\n    subst. unfold reboot in *.\n    destruct_update; simpl in *; eauto; find_apply_hyp_hyp; repeat find_rewrite; intuition;\n    right; break_exists_exists; intuition; find_higher_order_rewrite;\n    destruct_update; simpl in *; auto.\n  Qed.\n\n  Lemma allEntries_log_invariant :\n    forall net,\n      refined_raft_intermediate_reachable net ->\n      allEntries_log net.\n  Proof using aetsi rri tsi llsi ollpti llci aellti rlmli aerlli llli. \n    intros. apply refined_raft_net_invariant; auto.\n    - exact allEntries_log_init.\n    - exact allEntries_log_client_request.\n    - exact allEntries_log_timeout.\n    - exact allEntries_log_append_entries.\n    - exact allEntries_log_append_entries_reply.\n    - exact allEntries_log_request_vote.\n    - exact allEntries_log_request_vote_reply.\n    - exact allEntries_log_do_leader.\n    - exact allEntries_log_do_generic_server.\n    - exact allEntries_log_state_same_packet_subset.\n    - exact allEntries_log_reboot.\n  Qed.\n\n  Instance aeli : allEntries_log_interface.\n  split. eauto using allEntries_log_invariant.\n  Defined.\nEnd AllEntriesLog.\n", "meta": {"author": "uwplse", "repo": "verdi-raft", "sha": "7c8e4d53d27f7264ec4d3de72944dc0368e065f0", "save_path": "github-repos/coq/uwplse-verdi-raft", "path": "github-repos/coq/uwplse-verdi-raft/verdi-raft-7c8e4d53d27f7264ec4d3de72944dc0368e065f0/raft-proofs/AllEntriesLogProof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.20102337632245953}}
{"text": "Set Implicit Arguments.\n\nRequire Import Bedrock.Platform.AutoSep.\nRequire Import Bedrock.StructuredModule.\n\nRequire Import Bedrock.Labels.\nRequire Import Bedrock.LabelMap.\nRequire Bedrock.Platform.Cito.LabelMapFacts.\nRequire Import Bedrock.Platform.Cito.GLabel.\nRequire Import Bedrock.Platform.Cito.GLabelMap.\nImport GLabelMap.\nRequire Import Bedrock.Platform.Cito.GLabelMapFacts.\n\nRequire Import Bedrock.Platform.Cito.ListFacts1.\nRequire Import Bedrock.Platform.Cito.ListFacts2.\n\nSection TopSection.\n\n  Definition importsMap' (imports : list import) base :=\n    List.fold_left\n      (fun m p =>\n         let '(modl, f, pre) := p in\n         LabelMap.LabelMap.add (modl, Global f) pre m) imports base.\n\n  Require Import Bedrock.Platform.Cito.ConvertLabel.\n\n  Lemma importsMap_spec' :\n    forall imps2 imps1 base,\n      NoDupKey (imps1 ++ imps2) ->\n      (forall (k : glabel), LabelMap.LabelMap.find (k : label) base = find_list k imps1) ->\n      forall (k : glabel), LabelMap.LabelMap.find (k : label) (importsMap' imps2 base) = find_list k (imps1 ++ imps2).\n    induction imps2; simpl.\n    intros.\n    rewrite app_nil_r.\n    eauto.\n    intros.\n    rewrite <- DepList.pf_list_simpl.\n    eapply IHimps2.\n    rewrite DepList.pf_list_simpl.\n    eauto.\n    destruct a; simpl.\n    destruct k0; simpl.\n    intros.\n    destruct (LabelMap.LabelKey.eq_dec (k0 : Labels.label) (s, Global s0)).\n    unfold LabelKey.eq in *.\n    erewrite LabelMap.LabelMap.find_1.\n    Focus 2.\n    eapply LabelMap.LabelMap.add_1.\n    eauto.\n    destruct k0.\n    injection e; intros; subst.\n    erewrite In_find_list_Some_left.\n    eauto.\n    rewrite <- DepList.pf_list_simpl in H.\n    eapply NoDupKey_unapp1.\n    eauto.\n    eapply InA_eqke_In; intuition.\n    unfold LabelKey.eq in *.\n    erewrite LabelMapFacts.add_4.\n    rewrite H0.\n    erewrite find_list_neq.\n    eauto.\n    eapply NoDupKey_unapp1.\n    eauto.\n    intuition.\n    destruct k0.\n    injection H1; intros; subst; intuition.\n    eauto.\n  Qed.\n\n  Lemma importsMap_spec : forall imps (k : glabel), NoDupKey imps -> LabelMap.LabelMap.find (k : label) (importsMap imps) = find_list k imps.\n    intros.\n    unfold importsMap.\n    erewrite importsMap_spec'.\n    erewrite app_nil_l; eauto.\n    erewrite app_nil_l; eauto.\n    intros.\n    unfold find_list.\n    eauto.\n  Qed.\n\n  Definition fullImports' impsMap modName (functions : list (function modName)) : LabelMap.LabelMap.t assert :=\n    List.fold_left\n      (fun m p =>\n         let '(f, pre, _) := p in\n         LabelMap.LabelMap.add (modName, Global f) pre m) functions impsMap.\n\n  Definition func_to_import mn (f : function mn) : import:= ((mn, fst (fst f)), snd (fst f)).\n\n  Lemma fullImports_spec' :\n    forall mn (fns : list (function mn)) imps impsMap,\n      let fns' := List.map (@func_to_import _) fns in\n      let whole := imps ++ fns' in\n      NoDupKey whole ->\n      (forall (k : glabel), LabelMap.LabelMap.find (k : label) impsMap = find_list k imps) ->\n      forall (k : glabel), LabelMap.LabelMap.find (k : label) (fullImports' impsMap fns) = find_list k whole.\n  Proof.\n    unfold fullImports'.\n    unfold func_to_import.\n    induction fns; simpl; intros.\n    rewrite app_nil_r in *.\n    eauto.\n    rewrite <- DepList.pf_list_simpl.\n    eapply IHfns.\n    rewrite DepList.pf_list_simpl.\n    eauto.\n    destruct a; simpl.\n    destruct p; simpl.\n    intros.\n    destruct (LabelMap.LabelKey.eq_dec (k0 : Labels.label) (mn, Global s)).\n    unfold LabelKey.eq in *.\n    erewrite LabelMap.LabelMap.find_1.\n    Focus 2.\n    eapply LabelMap.LabelMap.add_1.\n    eauto.\n    destruct k0.\n    injection e; intros; subst.\n    erewrite In_find_list_Some_left.\n    eauto.\n    simpl in *.\n    rewrite <- DepList.pf_list_simpl in H.\n    eapply NoDupKey_unapp1.\n    eauto.\n    eapply InA_eqke_In; intuition.\n    unfold LabelKey.eq in *.\n    erewrite LabelMapFacts.add_4.\n    rewrite H0.\n    erewrite find_list_neq.\n    eauto.\n    eapply NoDupKey_unapp1.\n    eauto.\n    intuition.\n    destruct k0.\n    injection H1; intros; subst; intuition.\n    eauto.\n  Qed.\n\n  Lemma fullImports_spec :\n    forall (imps : list import) mn (fns : list (function mn)) (k : glabel),\n      let fns' := List.map (@func_to_import _) fns in\n      let whole := imps ++ fns' in\n      NoDupKey whole ->\n      LabelMap.LabelMap.find (k : label) (fullImports imps fns) = find_list k whole.\n  Proof.\n    unfold fullImports.\n    specialize fullImports_spec'; intros.\n    unfold fullImports' in *.\n    eapply H; eauto.\n    intros.\n    eapply importsMap_spec; eauto.\n    eapply NoDupKey_unapp1.\n    eauto.\n  Qed.\n\n  Require Import Bedrock.Platform.Cito.ConvertLabelMap.\n  Import Notations.\n  Open Scope clm_scope.\n\n  Require Import Bedrock.Platform.Cito.GeneralTactics.\n\n  Lemma importsMap_of_list : forall ls, NoDupKey ls -> importsMap ls === of_list ls.\n    intros.\n    hnf.\n    intros.\n    destruct y.\n    destruct l.\n    specialize importsMap_spec; intros.\n    unfold to_bedrock_label in *.\n    erewrite H0 with (k := (s, s0)); eauto.\n    unfold find_list.\n    rewrite <- of_list_1b; eauto.\n    symmetry.\n    rewrite <- to_blm_spec; eauto.\n    specialize importsMapGlobal; intros.\n    unfold importsGlobal in *.\n    eapply option_univalence.\n    split; intros.\n    eapply LabelMap.find_2 in H1.\n    eapply H0 in H1.\n    openhyp.\n    simpl in *.\n    discriminate.\n    rewrite to_blm_no_local in H1.\n    discriminate.\n  Qed.\n\n  Lemma exps_spec :\n    forall mn (fns : list (function mn)),\n      let fns' := List.map (@func_to_import _) fns in\n      exps fns === of_list fns'.\n    induction fns; simpl; intros.\n    eapply to_blm_empty.\n    simpl in *.\n    destruct a; simpl in *.\n    destruct p; simpl in *.\n    unfold uncurry; simpl in *.\n    rewrite IHfns.\n    rewrite to_blm_add.\n    eapply LabelMapFacts.add_m; eauto.\n    reflexivity.\n  Qed.\n\n  Lemma importsOk_Compat_left : forall m1 m2, importsOk m1 m2 -> LabelMapFacts.Compat m1 m2.\n    intros.\n    unfold LabelMapFacts.Compat.\n    intros.\n    eapply LabelMapFacts.In_MapsTo in H0.\n    openhyp.\n    eapply LabelMapFacts.In_MapsTo in H1.\n    openhyp.\n    assert (x = x0).\n    eapply use_importsOk; eauto.\n    eapply LabelMap.find_1; eauto.\n    subst.\n    eapply LabelMap.find_1 in H1.\n    eapply LabelMap.find_1 in H0.\n    congruence.\n  Qed.\n\n  Require Import Coq.Setoids.Setoid.\n  Require Import Coq.Classes.Morphisms.\n\n  Lemma importsOk_f_Proper :\n    forall m,\n      Proper (Logic.eq ==> Logic.eq ==> iff ==> iff)\n             (fun (l : LabelMap.LabelMap.key) (pre : assert) (P : Prop) =>\n                match LabelMap.LabelMap.find (elt:=assert) l m with\n                  | Some pre' => pre = pre' /\\ P\n                  | None => P\n                end).\n    intros.\n    unfold Proper.\n    unfold respectful.\n    intros.\n    subst.\n    destruct (LabelMap.find y m); intuition.\n  Qed.\n\n  Lemma importsOk_f_transpose_neqkey :\n    forall m,\n      LabelMapFacts.transpose_neqkey\n        iff\n        (fun (l : LabelMap.LabelMap.key) (pre : assert) (P : Prop) =>\n           match LabelMap.LabelMap.find (elt:=assert) l m with\n             | Some pre' => pre = pre' /\\ P\n             | None => P\n           end).\n    unfold LabelMapFacts.transpose_neqkey.\n    intros.\n    destruct (LabelMap.find k m); destruct (LabelMap.find k' m); intuition.\n  Qed.\n\n  Global Add Morphism importsOk\n      with signature LabelMap.Equal ==> Logic.eq ==> iff as importsOk_m.\n    intros.\n    unfold importsOk.\n    eapply LabelMapFacts.fold_Equal; eauto.\n    intuition.\n    eapply importsOk_f_Proper.\n    eapply importsOk_f_transpose_neqkey.\n  Qed.\n\n  Require Import Bedrock.Platform.Cito.Option.\n\n  Lemma importsOk_Compat_right : forall m1 m2, LabelMapFacts.Compat m1 m2 -> importsOk m1 m2.\n    induction m1 using LabelMapFacts.map_induction_bis.\n    intros.\n    rewrite <- H in H0.\n    rewrite <- H.\n    eauto.\n    intros.\n    unfold importsOk.\n    rewrite LabelMap.fold_1.\n    simpl.\n    eauto.\n    intros.\n    unfold importsOk.\n    rewrite LabelMapFacts.fold_add; eauto.\n    destruct (option_dec (LabelMap.find (elt:=assert) x m2)).\n    destruct s.\n    rewrite e0.\n    split.\n    eapply LabelMapFacts.Compat_eq; eauto.\n    eapply LabelMap.find_1.\n    eapply LabelMapFacts.add_mapsto_iff.\n    eauto.\n    eapply IHm1.\n    eapply LabelMapFacts.Compat_add_not_In; eauto.\n    rewrite e0.\n    eapply IHm1.\n    eapply LabelMapFacts.Compat_add_not_In; eauto.\n    intuition.\n    eapply importsOk_f_Proper.\n    eapply importsOk_f_transpose_neqkey.\n  Qed.\n\n  Lemma importsOk_Compat : forall m1 m2, importsOk m1 m2 <-> LabelMapFacts.Compat m1 m2.\n    split; intros.\n    eapply importsOk_Compat_left; eauto.\n    eapply importsOk_Compat_right; eauto.\n  Qed.\n\n  Lemma XCAP_union_update : forall elt m1 m2, LabelMap.Equal (@XCAP.union elt m1 m2) (LabelMapFacts.update m2 m1).\n    unfold XCAP.union.\n    unfold LabelMapFacts.update.\n    intros.\n    reflexivity.\n  Qed.\n\n  Lemma XCAP_diff_diff : forall elt m1 m2, @LabelMap.Equal elt (XCAP.diff m1 m2) (LabelMapFacts.diff m1 m2).\n    intros.\n    unfold LabelMap.Equal.\n    intros.\n    eapply option_univalence.\n    split; intros.\n    eapply LabelMap.find_2 in H.\n    eapply MapsTo_diff in H.\n    Focus 2.\n    instantiate (1 := @StructuredModule.bmodule_ nil \"\" nil).\n    instantiate (1 := @StructuredModule.bmodule_ nil \"\" nil).\n    simpl.\n    unfold importsMap.\n    simpl.\n    rewrite LabelMap.fold_1.\n    simpl.\n    eauto.\n    openhyp.\n    eapply LabelMap.find_1.\n    eapply LabelMapFacts.diff_mapsto_iff.\n    eauto.\n    eapply LabelMap.find_2 in H.\n    eapply LabelMapFacts.diff_mapsto_iff in H.\n    openhyp.\n    eapply LabelMap.find_1.\n    eapply MapsTo_diffr; eauto.\n    eapply LabelMap.elements_3w.\n  Qed.\n\nEnd TopSection.\n", "meta": {"author": "mit-plv", "repo": "bedrock", "sha": "e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd", "save_path": "github-repos/coq/mit-plv-bedrock", "path": "github-repos/coq/mit-plv-bedrock/bedrock-e3ff3c2cba9976ac4351caaabb4bf7278bb0dcbd/Bedrock/Platform/Cito/StructuredModuleFacts.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.38121955922604417, "lm_q1q2_score": 0.2010233726153686}}
{"text": "Require Import Eqdep Lia Framework FSParameters FileDiskLayer. (* LoggedDiskLayer TransactionCacheLayer TransactionalDiskLayer. *)\nRequire Import FileDiskNoninterference FileDiskRefinement.\nRequire Import ATC_ORS ATCDLayer ATC_Simulation HSS ATC_TransferProofs.\nRequire Import ATCD_Simulation ATCD_AOE.\nRequire Import Not_Init ATCD_ORS ATCD_TIE ATCD_HSS ATCD_Commit_Pre.\n\nImport FileDiskLayer.\nSet Nested Proofs Allowed.\n\n\nLemma AOE_explicit_to_AOE:\nforall O1 O2 (L1: Layer O1) (L2: Layer O2) (Ref: Refinement L1 L2) \nR u T (p: prog L2 T) rec l_grs,\n(forall l_o s1 s2,\nabstract_oracles_exist_wrt_explicit Ref R u p rec l_grs l_o s1 s2) ->\nabstract_oracles_exist_wrt Ref R u p rec l_grs.\nProof.\n  unfold abstract_oracles_exist_wrt_explicit, \n  abstract_oracles_exist_wrt; eauto.\nQed.\n\nDefinition compile_to_ATCD {T} (p: prog _ T) := \n  (Simulation.Definitions.compile ATCD_Refinement\n(Simulation.Definitions.compile ATC_Refinement\n   (Simulation.Definitions.compile FD.refinement p))).\n\nDefinition ATCD_log_equivalent (s1 s2: state ATCDLang) :=\n  (exists (hdr1 hdr2 : Log.header) (merged_disk1 merged_disk2 : total_mem),\n  (exists txns1 : list Log.txn,\n     fst (snd (snd s1)) =\n     Mem.list_upd_batch empty_mem (map Log.addr_list txns1)\n       (map Log.data_blocks txns1) /\\\n     Log.log_header_rep hdr1 txns1 (snd (snd (snd s1))) /\\\n     merged_disk1 =\n     total_mem_map fst\n       (shift (Nat.add data_start)\n          (list_upd_batch_set (snd (snd (snd (snd s1))))\n             (map Log.addr_list txns1) (map Log.data_blocks txns1))) /\\\n     (forall a : nat,\n      a >= data_start -> snd (snd (snd (snd (snd s1))) a) = [])) /\\\n  (exists txns2 : list Log.txn,\n     fst (snd (snd s2)) =\n     Mem.list_upd_batch empty_mem (map Log.addr_list txns2)\n       (map Log.data_blocks txns2) /\\\n     Log.log_header_rep hdr2 txns2 (snd (snd (snd s2))) /\\\n     merged_disk2 =\n     total_mem_map fst\n       (shift (Nat.add data_start)\n          (list_upd_batch_set (snd (snd (snd (snd s2))))\n             (map Log.addr_list txns2) (map Log.data_blocks txns2))) /\\\n     (forall a : nat,\n      a >= data_start -> snd (snd (snd (snd (snd s2))) a) = [])) /\\\n  Log.count (Log.current_part hdr1) = Log.count (Log.current_part hdr2) /\\\n  Forall2\n    (fun rec1 rec2 : Log.txn_record =>\n     Log.addr_count rec1 = Log.addr_count rec2)\n    (Log.records (Log.current_part hdr1))\n    (Log.records (Log.current_part hdr2)) /\\\n  Forall2\n    (fun rec1 rec2 : Log.txn_record =>\n     Log.data_count rec1 = Log.data_count rec2)\n    (Log.records (Log.current_part hdr1))\n    (Log.records (Log.current_part hdr2))).\n\n(********** Transfer Theorems ***********)\nOpaque File.read File.recover.\nTheorem ss_ATCD_read:\n  forall n inum off u u' lo s1 s2,\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD  (| Read inum off |))\n  (compile_to_ATCD (|Recover|)) lo s1 -> \n\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD  (| Read inum off |))\n  (compile_to_ATCD (|Recover|)) lo s2 -> \n\n  (forall s1',\n    exec ATCDLang u (hd [] lo) s1 (compile_to_ATCD  (| Read inum off |)) (Crashed s1') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s1'))))) ->\n  \n  (forall s2',\n    exec ATCDLang u (hd [] lo) s2 (compile_to_ATCD  (| Read inum off |)) (Crashed s2') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s2'))))) ->\n\n    ATCD_log_equivalent s1 s2 ->\n\n  RDNI_Weak_explicit u lo s1 s2\n    (compile_to_ATCD  (| Read inum off |))\n    (compile_to_ATCD  (| Read inum off |))\n    (compile_to_ATCD (|Recover|))\n    (refines_valid ATCD_Refinement (refines_valid ATC_Refinement AD_valid_state))\n    ((refines_related ATCD_Refinement (refines_related ATC_Refinement (AD_related_states u' None))))\n    (eq u') (ATCD_reboot_list n).\nProof.\n  intros.\n  eapply RDNIW_explicit_transfer.\n  - simpl.\n  apply ss_ATC_read.\n  - eapply ATCD_simulation.\n    shelve.\n  - eapply ATCD_simulation.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; eapply ATCD_ORS_transfer; simpl.\n    all: shelve.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  Unshelve.\n  all: simpl; try solve [try apply not_init_compile; apply not_init_read].\n  {\n    unfold refines_related; simpl; intros.\n    cleanup.\n    Transparent File.read.\n    unfold File.read.\n    eapply ATC_HSS_auth_then_exec; eauto.\n    intros.\n    eapply ATC_HSS_read_inner; eauto.\n    unfold  refines_related; eauto.\n    intros; eapply read_inner_commit_pre; eauto.\n    eapply have_same_structure_read; eauto.\n  }\n  all: try solve [ intros; cleanup; simpl in *; intuition eauto ].\nQed.\n\nOpaque File.write File.recover.\nTheorem ss_ATCD_write:\n  forall n inum off u u' v lo s1 s2,\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD (| Write inum off v |))\n  (compile_to_ATCD (|Recover|)) lo s1 -> \n\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD (| Write inum off v |))\n  (compile_to_ATCD (|Recover|)) lo s2 -> \n\n  (forall s1',\n    exec ATCDLang u (hd [] lo) s1 (compile_to_ATCD  (| Write inum off v |)) (Crashed s1') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s1'))))) ->\n  \n  (forall s2',\n    exec ATCDLang u (hd [] lo) s2 (compile_to_ATCD  (| Write inum off v |)) (Crashed s2') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s2'))))) ->\n\n    ATCD_log_equivalent s1 s2 ->\n\n  RDNI_Weak_explicit u lo s1 s2\n    (compile_to_ATCD (| Write inum off v |))\n    (compile_to_ATCD (| Write inum off v |))\n    (compile_to_ATCD (|Recover|))\n    (refines_valid ATCD_Refinement (refines_valid ATC_Refinement AD_valid_state))\n    (refines_related ATCD_Refinement (refines_related ATC_Refinement (AD_related_states u' None)))\n    (eq u') (ATCD_reboot_list n).\nProof.\n  intros.\n  eapply RDNIW_explicit_transfer.\n  - simpl.\n  eapply ss_ATC_write.\n  - eapply ATCD_simulation.\n    shelve.\n  - eapply ATCD_simulation.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; eapply ATCD_ORS_transfer; simpl.\n    all: shelve.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  Unshelve.\n  all: simpl; try solve [try apply not_init_compile; apply not_init_write].\n  {\n    unfold refines_related; simpl; intros.\n    cleanup.\n    Transparent File.write.\n    unfold File.write.\n    eapply ATC_HSS_auth_then_exec; eauto.\n    intros.\n    eapply ATC_HSS_write_inner; eauto.\n    unfold  refines_related; eauto.\n    intros; eapply write_inner_commit_pre; eauto.\n    eapply have_same_structure_write; eauto.\n    Opaque File.write.\n  }\n  all: try solve [ intros; cleanup; simpl in *; intuition eauto ].\nQed.\n\n\nTheorem ss_ATCD_write_input:\n  forall n inum off u u' v1 v2 lo s1 s2,\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD (| Write inum off v1 |))\n  (compile_to_ATCD (|Recover|)) lo s1 -> \n\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD (| Write inum off v2 |))\n  (compile_to_ATCD (|Recover|)) lo s2 -> \n\n  (forall s1',\n    exec ATCDLang u (hd [] lo) s1 (compile_to_ATCD  (| Write inum off v1 |)) (Crashed s1') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s1'))))) ->\n  \n  (forall s2',\n    exec ATCDLang u (hd [] lo) s2 (compile_to_ATCD  (| Write inum off v2 |)) (Crashed s2') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s2'))))) ->\n\n    ATCD_log_equivalent s1 s2 ->\n\n  RDNI_Weak_explicit u lo s1 s2\n    (compile_to_ATCD (| Write inum off v1 |))\n    (compile_to_ATCD (| Write inum off v2 |))\n    (compile_to_ATCD (|Recover|))\n    (refines_valid ATCD_Refinement (refines_valid ATC_Refinement AD_valid_state))\n    (refines_related ATCD_Refinement (refines_related ATC_Refinement (AD_related_states u' (Some inum))))\n    (eq u') (ATCD_reboot_list n).\nProof.\n  intros.\n  eapply RDNIW_explicit_transfer.\n  - simpl.\n  eapply ss_ATC_write_input.\n  - eapply ATCD_simulation.\n    shelve.\n  - eapply ATCD_simulation.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; eapply ATCD_ORS_transfer; simpl.\n    all: shelve.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  Unshelve.\n  all: simpl; try solve [try apply not_init_compile; apply not_init_write].\n  {\n    unfold refines_related; simpl; intros.\n    cleanup.\n    Transparent File.write.\n    unfold File.write.\n    eapply ATC_HSS_auth_then_exec; eauto.\n    intros.\n    eapply ATC_HSS_write_inner; eauto.\n    unfold  refines_related; eauto.\n    intros; eapply write_inner_commit_pre; eauto.\n    eapply have_same_structure_write_input; eauto.\n    Opaque File.write.\n  }\n  all: try solve [ intros; cleanup; simpl in *; intuition eauto ].\nQed.\n\n\nOpaque File.create File.recover.\nTheorem ss_ATCD_create:\n  forall n u u' v lo s1 s2,\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD (| Create v |))\n  (compile_to_ATCD (|Recover|)) lo s1 -> \n\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD (| Create v |))\n  (compile_to_ATCD (|Recover|)) lo s2 -> \n\n  (forall s1',\n    exec ATCDLang u (hd [] lo) s1 (compile_to_ATCD  (| Create v |)) (Crashed s1') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s1'))))) ->\n  \n  (forall s2',\n    exec ATCDLang u (hd [] lo) s2 (compile_to_ATCD  (| Create v |)) (Crashed s2') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s2'))))) ->\n\n    ATCD_log_equivalent s1 s2 ->\n\n    RDNI_Weak_explicit u lo s1 s2\n    (compile_to_ATCD (| Create v |))\n    (compile_to_ATCD (| Create v |))\n    (compile_to_ATCD (|Recover|))\n    (refines_valid ATCD_Refinement (refines_valid ATC_Refinement AD_valid_state))\n    (refines_related ATCD_Refinement (refines_related ATC_Refinement (AD_related_states u' None)))\n    (eq u') (ATCD_reboot_list n).\nProof.\n  intros.\n  eapply RDNIW_explicit_transfer.\n  - apply ss_ATC_create.\n  - eapply ATCD_simulation.\n    shelve.\n  - eapply ATCD_simulation.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; eapply ATCD_ORS_transfer; simpl.\n    all: shelve.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  Unshelve.\n  all: simpl; try solve [try apply not_init_compile; apply not_init_create].\n  {\n    unfold refines_related; simpl; intros.\n    cleanup.\n    eapply ATC_HSS_create; eauto.\n    eapply have_same_structure_create; eauto.\n  }\n  all: try solve [ intros; cleanup; simpl in *; intuition eauto ].\nQed.\n\nOpaque File.extend File.recover.\nTheorem ss_ATCD_extend:\n  forall n u u' inum v lo s1 s2,\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD(| Extend inum v |))\n  (compile_to_ATCD (|Recover|)) lo s1 -> \n\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD(| Extend inum v |))\n  (compile_to_ATCD (|Recover|))lo s2 -> \n\n  (forall s1',\n    exec ATCDLang u (hd [] lo) s1 (compile_to_ATCD  (| Extend inum v |)) (Crashed s1') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s1'))))) ->\n  \n  (forall s2',\n    exec ATCDLang u (hd [] lo) s2 (compile_to_ATCD  (| Extend inum v |)) (Crashed s2') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s2'))))) ->\n\n    ATCD_log_equivalent s1 s2 ->\n\n    RDNI_Weak_explicit u lo s1 s2\n    (compile_to_ATCD(| Extend inum v |))\n    (compile_to_ATCD(| Extend inum v |))\n    (compile_to_ATCD (|Recover|))\n    (refines_valid ATCD_Refinement (refines_valid ATC_Refinement AD_valid_state))\n    (refines_related ATCD_Refinement (refines_related ATC_Refinement (AD_related_states u' None)))\n    (eq u') (ATCD_reboot_list n).\nProof.\n  intros.\n  eapply RDNIW_explicit_transfer.\n  - apply ss_ATC_extend.\n  - eapply ATCD_simulation.\n    shelve.\n  - eapply ATCD_simulation.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; eapply ATCD_ORS_transfer; simpl.\n    all: shelve.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  Unshelve.\n  all: simpl; try solve [try apply not_init_compile; apply not_init_extend].\n  {\n    unfold refines_related; simpl; intros.\n    cleanup.\n    Transparent File.extend.\n    unfold File.extend.\n    eapply ATC_HSS_auth_then_exec; eauto.\n    intros.\n    eapply ATC_HSS_extend_inner; eauto.\n    unfold  refines_related; eauto.\n    intros; eapply extend_inner_commit_pre; eauto.\n    eapply have_same_structure_extend; eauto.\n    Opaque File.extend.\n  }\n  all: try solve [ intros; cleanup; simpl in *; intuition eauto ].\nQed.\n\nTheorem ss_ATCD_extend_input:\n  forall n u u' inum v1 v2 lo s1 s2,\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD(| Extend inum v1 |))\n  (compile_to_ATCD (|Recover|)) lo s1 -> \n\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD(| Extend inum v2 |))\n  (compile_to_ATCD (|Recover|))lo s2 -> \n\n  (forall s1',\n    exec ATCDLang u (hd [] lo) s1 (compile_to_ATCD  (| Extend inum v1 |)) (Crashed s1') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s1'))))) ->\n  \n  (forall s2',\n    exec ATCDLang u (hd [] lo) s2 (compile_to_ATCD  (| Extend inum v2 |)) (Crashed s2') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s2'))))) ->\n\n    ATCD_log_equivalent s1 s2 ->\n\n    RDNI_Weak_explicit u lo s1 s2\n    (compile_to_ATCD(| Extend inum v1 |))\n    (compile_to_ATCD(| Extend inum v2 |))\n    (compile_to_ATCD (|Recover|))\n    (refines_valid ATCD_Refinement (refines_valid ATC_Refinement AD_valid_state))\n    (refines_related ATCD_Refinement (refines_related ATC_Refinement (AD_related_states u' (Some inum))))\n    (eq u') (ATCD_reboot_list n).\nProof.\n  intros.\n  eapply RDNIW_explicit_transfer.\n  - apply ss_ATC_extend_input.\n  - eapply ATCD_simulation.\n    shelve.\n  - eapply ATCD_simulation.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; eapply ATCD_ORS_transfer; simpl.\n    all: shelve.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  Unshelve.\n  all: simpl; try solve [try apply not_init_compile; apply not_init_extend].\n  {\n    unfold refines_related; simpl; intros.\n    cleanup.\n    Transparent File.extend.\n    unfold File.extend.\n    eapply ATC_HSS_auth_then_exec; eauto.\n    intros.\n    eapply ATC_HSS_extend_inner; eauto.\n    unfold  refines_related; eauto.\n    intros; eapply extend_inner_commit_pre; eauto.\n    eapply have_same_structure_extend_input; eauto.\n    Opaque File.extend.\n  }\n  all: try solve [ intros; cleanup; simpl in *; intuition eauto ].\nQed.\n\n\nOpaque File.change_owner File.recover.\nTheorem ss_ATCD_change_owner:\n  forall n u u' inum v lo s1 s2,\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD (| ChangeOwner inum v |))\n  (compile_to_ATCD (|Recover|)) lo s1 -> \n\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD (| ChangeOwner inum v |))\n  (compile_to_ATCD (|Recover|)) lo s2 -> \n\n  (forall s1',\n    exec ATCDLang u (hd [] lo) s1 (compile_to_ATCD  (| ChangeOwner inum v |)) (Crashed s1') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s1'))))) ->\n  \n  (forall s2',\n    exec ATCDLang u (hd [] lo) s2 (compile_to_ATCD  (| ChangeOwner inum v |)) (Crashed s2') -> \n    no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s2'))))) ->\n\n    ATCD_log_equivalent s1 s2 ->\n\n    RDNI_Weak_explicit u lo s1 s2\n    (compile_to_ATCD (| ChangeOwner inum v |))\n    (compile_to_ATCD (| ChangeOwner inum v |))\n    (compile_to_ATCD (|Recover|))\n    (refines_valid ATCD_Refinement (refines_valid ATC_Refinement AD_valid_state))\n    (refines_related ATCD_Refinement\n    (refines_related ATC_Refinement (AD_related_states u' (Some inum))))\n    (eq u') (ATCD_reboot_list n).\nProof.\n  intros.\n  eapply RDNIW_explicit_transfer.\n  - apply ss_ATC_change_owner.\n  - eapply ATCD_simulation.\n    shelve.\n  - eapply ATCD_simulation.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; eapply ATCD_ORS_transfer; simpl.\n    all: shelve.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  Unshelve.\n  all: simpl; try solve [try apply not_init_compile; apply not_init_change_owner].\n  {\n    unfold refines_related; simpl; intros.\n    cleanup.\n    Transparent File.change_owner.\n    unfold File.change_owner.\n    eapply ATC_HSS_auth_then_exec; eauto.\n    intros.\n    eapply ATC_HSS_change_owner_inner; eauto.\n    unfold  refines_related; eauto.\n    intros; eapply change_owner_inner_commit_pre; eauto.\n    eapply have_same_structure_change_owner; eauto.\n    Opaque File.change_owner.\n  }\n  all: try solve [ intros; cleanup; simpl in *; intuition eauto ].\nQed.\n\n\nOpaque File.delete File.recover.\nTheorem ss_ATCD_delete:\n  forall n u u' inum lo s1 s2,\n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD (| Delete inum |))\n  (compile_to_ATCD (|Recover|)) lo s1 -> \n  non_colliding_selector_list u\n  (Simulation.Definitions.refines ATCD_Refinement)\n  (Simulation.Definitions.refines_reboot ATCD_Refinement) n\n  (compile_to_ATCD (| Delete inum |))\n  (compile_to_ATCD (|Recover|)) lo s2 -> \n\n  (forall s1',\n  exec ATCDLang u (hd [] lo) s1 (compile_to_ATCD  (| Delete inum |)) (Crashed s1') -> \n  no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s1'))))) ->\n\n(forall s2',\n  exec ATCDLang u (hd [] lo) s2 (compile_to_ATCD  (| Delete inum |)) (Crashed s2') -> \n  no_accidental_overlap (hd (fun _ => 0) n) (snd (snd (snd (snd s2'))))) ->\n\n  ATCD_log_equivalent s1 s2 ->\n\n  RDNI_Weak_explicit u lo s1 s2\n    (compile_to_ATCD (| Delete inum |))\n    (compile_to_ATCD (| Delete inum |))\n    (compile_to_ATCD (|Recover|))\n    (refines_valid ATCD_Refinement (refines_valid ATC_Refinement AD_valid_state))\n    (refines_related ATCD_Refinement\n    (refines_related ATC_Refinement (AD_related_states u' None)))\n    (eq u') (ATCD_reboot_list n).\nProof.\n  intros.\n  eapply RDNIW_explicit_transfer.\n  - apply ss_ATC_delete.\n  - eapply ATCD_simulation.\n    shelve.\n  - eapply ATCD_simulation.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; apply ATCD_AOE; eauto.\n    shelve.\n  - intros; eapply ATCD_ORS_transfer; simpl.\n    all: shelve.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  - unfold exec_compiled_preserves_validity, AD_valid_state, \n  refines_valid, FD_valid_state; \n  intros; simpl; eauto.\n  Unshelve.\n  all: simpl; try solve [try apply not_init_compile; apply not_init_delete].\n  {\n    unfold refines_related; simpl; intros.\n    cleanup.\n    Transparent File.delete.\n    unfold File.delete.\n    eapply ATC_HSS_auth_then_exec; eauto.\n    intros.\n    eapply ATC_HSS_delete_inner; eauto.\n    unfold  refines_related; eauto.\n    intros; eapply delete_inner_commit_pre; eauto.\n    eapply have_same_structure_delete; eauto.\n    Opaque File.delete.\n  }\n  all: try solve [ intros; cleanup; simpl in *; intuition eauto ].\nQed.\n\n\n\n(*\nOpaque File.recover.\nLemma ATCD_TS_read_inner:\n    forall n inum off u u' txns1 txns2 hdr1 hdr2,\n    Termination_Sensitive u\n    (Simulation.Definitions.compile\n    ATCD_Refinement\n   (Simulation.Definitions.compile\n    ATC_Refinement\n    (@lift_L2 AuthenticationOperation _ TD _\n    (File.read_inner off inum))))\n   (Simulation.Definitions.compile\n    ATCD_Refinement\n   (Simulation.Definitions.compile\n    ATC_Refinement\n    (@lift_L2 AuthenticationOperation _ TD _\n    (File.read_inner off inum))))\n    (Simulation.Definitions.compile\n    ATCD_Refinement\n    (Simulation.Definitions.compile\n    ATC_Refinement\n    File.recover))\n   (refines_valid ATCD_Refinement\n     (refines_valid ATC_Refinement\n    AD_valid_state))\n  (fun s1 s2 => refines_related ATCD_Refinement (refines_related ATC_Refinement ( (fun s1 s2  => exists s1a s2a, \n  File.files_inner_rep s1a (fst (snd (snd s1))) /\\ \n  File.files_inner_rep s2a (fst (snd (snd s2))) /\\ \n  FD_related_states u' None s1a s2a /\\\n  fst (snd s1) = Empty /\\ fst (snd s2) = Empty))) s1 s2 /\\\n  equivalent_for_recovery txns1 txns2 Log.Current_Part hdr1 hdr2 s1 s2)\n     (ATCD_reboot_list n).\n  Proof.\n    Transparent File.read_inner.\n    intros; unfold File.read_inner.\n    eapply ATCD_TS_compositional.\n    intros; eapply TS_eqv_impl.\n    eapply ATCD_TS_get_block_number.\n    simpl; intros; shelve.\n    2: intros; shelve.\n\n    intros; unfold refines_related in *; cleanup.\n    intros; unfold refines_related in *; cleanup.\n    eapply_fresh ATCD_oracle_refines_finished in H; eauto.\n    eapply_fresh ATCD_oracle_refines_finished in H0; eauto.\n    cleanup.\n\n    eapply_fresh ATCD_exec_lift_finished in H; eauto;\n    try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n    try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n    cleanup.\n    eapply_fresh ATCD_exec_lift_finished in H0; eauto;\n    try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n    try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n    cleanup.\n    simpl in *.\n    eapply_fresh ATCD_oracle_refines_impl_eq in H11; eauto.\n    2: shelve. (* eapply have_same_structure_get_owner; eauto. *)\n    2: apply TC_oracle_refines_operation_eq.\n    cleanup.\n\n    clear H H0.\n\n    eapply_fresh ATC_oracle_refines_finished in H13; eauto.\n    eapply_fresh ATC_oracle_refines_finished in H15; eauto.\n    cleanup.\n    eapply_fresh ATC_exec_lift_finished in H13; eauto;\n    try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n    try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n    cleanup.\n    eapply_fresh ATC_exec_lift_finished in H15; eauto;\n    try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n    try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n    cleanup.\n    simpl in *.\n    eapply ATC_oracle_refines_impl_eq in H; eauto.\n    2: shelve.\n    2: apply TD_oracle_refines_operation_eq.\n    cleanup.\n\n    clear H13 H15.\n\n    eapply lift2_invert_exec in H17;\n    eapply lift2_invert_exec in H19; cleanup.\n    apply HC_map_ext_eq in H; subst.\n\n    unfold File.files_inner_rep in *; cleanup.\n    eapply_fresh Inode.get_block_number_finished_oracle_eq in H21; eauto; subst.\n    cleanup; destruct r1, r2; try solve [intuition congruence].\n    2: intros; eapply TS_eqv_impl; [apply ATCD_TS_ret | shelve].\n    \n    eapply ATCD_TS_compositional.\n    2: intros; destruct r1, r2; (eapply TS_eqv_impl; [apply ATCD_TS_ret | shelve]).\n    2: shelve.\n    simpl; intros; repeat invert_exec; try congruence.\n    eapply TS_eqv_impl. \n    eapply ATCD_TS_DiskAllocator_read.\n    {\n      eapply Inode.get_block_number_finished in H21; eauto.\n      eapply Inode.get_block_number_finished in H17; eauto.\n      cleanup; repeat split_ors; cleanup; intuition eauto.\n      eapply SameRetType.all_block_numbers_in_bound in H.\n      3: eauto.\n      all: eauto.\n      eapply Forall_forall in H; eauto.\n      eapply in_seln; eauto.\n      \n      eapply SameRetType.all_block_numbers_in_bound in H6.\n      3: eauto.\n      all: eauto.\n      eapply Forall_forall in H6; eauto.\n      apply in_seln; eauto.\n    }\n    {\n      eapply Inode.get_block_number_finished in H21; eauto.\n      eapply Inode.get_block_number_finished in H17; eauto.\n\n      cleanup; repeat split_ors; cleanup; intuition eauto.\n      eapply data_block_inbounds; eauto.\n      eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n      intros; FileInnerSpecs.solve_bounds.\n\n      eapply data_block_inbounds.\n      4: eauto.\n      all: eauto.\n      eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n      intros; FileInnerSpecs.solve_bounds.\n    }\n    {\n      shelve. (*\n      instantiate (2:= refines_related ATCD_Refinement\n      (fun s1 s2  => \n      exists s1a s2a, \n      (Inode.inode_rep im1 (fst (snd (snd s1))) /\\\n          (exists file_block_map,\n              File.DiskAllocator.block_allocator_rep file_block_map\n                (fst (snd (snd s1))) /\\\n              File.file_map_rep s1a im1 file_block_map)) /\\\n        (Inode.inode_rep im2 (fst (snd (snd s2))) /\\\n          (exists file_block_map,\n              File.DiskAllocator.block_allocator_rep file_block_map\n                (fst (snd (snd s2))) /\\\n              File.file_map_rep s2a im2 file_block_map)) /\\\n      FD_related_states u' None s1a s2a /\\\n      fst (snd s1) = Empty /\\\n      fst (snd s2) = Empty)).\n        \n        simpl; intros.\n        unfold refines_related in *.\n        cleanup.\n        split.\n        unfold File.files_inner_rep.\n        do 2 eexists; intuition eauto.\n        do 2 eexists; intuition eauto.\n\n        simpl in *; unfold HC_refines in H12, H21; cleanup.\n        simpl in *; unfold TransactionToTransactionalDisk.Definitions.refines,\n        Transaction.transaction_rep  in *; cleanup; \n        repeat split_ors; cleanup; try congruence.\n      eapply txn_length_0_empty in H34;\n      eapply txn_length_0_empty in H38; subst.\n      setoid_rewrite H34;\n      setoid_rewrite H38.\n      simpl; intuition eauto.\n\n      rewrite H38, H34 in *; simpl in *.\n      eapply Inode.get_block_number_finished in H20; eauto.\n      eapply Inode.get_block_number_finished in H18; eauto.\n      cleanup; repeat split_ors; cleanup; intuition eauto.\n      repeat erewrite TSCommon.used_blocks_are_allocated_2; eauto.\n      *)\n    }\n    shelve.\n    shelve.\n    shelve.\n    shelve.\n    all: unfold Simulation.Definitions.refines in *; simpl in *; eauto.\n\n    Unshelve.\n    41: instantiate (5 := fun _ _ => _); simpl; eauto.\n    all: eauto.\n    {\n      simpl.\n      intros; unfold refines_related in *; cleanup.\n      simpl in *.\n      unfold File.files_inner_rep in *; cleanup. \n      do 2 eexists; intuition eauto.\n      do 2 eexists; intuition eauto.\n\n      do 2 eexists; intuition eauto. \n\n      unfold HC_refines in *; cleanup.\n      simpl in *.\n      unfold TransactionToTransactionalDisk.Definitions.refines,\n      Transaction.transaction_rep in *; simpl in *; cleanup.\n      repeat split_ors; cleanup; try congruence.\n      eapply txn_length_0_empty in H14;\n      setoid_rewrite H14.\n      simpl; eauto.\n\n      unfold HC_refines in *; cleanup.\n      simpl in *.\n      unfold TransactionToTransactionalDisk.Definitions.refines,\n      Transaction.transaction_rep in *; simpl in *; cleanup.\n      repeat split_ors; cleanup; try congruence.\n      eapply txn_length_0_empty in H18;\n      setoid_rewrite H18.\n      simpl; eauto.\n    }\n    {\n      simpl.\n      intros; unfold refines_related in *; cleanup.\n      eapply_fresh get_block_number_oracle_refines_exists in H; eauto.\n      eapply_fresh get_block_number_oracle_refines_exists in H0; eauto.\n      cleanup.\n\n      eapply_fresh ATCD_exec_lift_finished in H; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H0; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      simpl in *.\n      eapply ATCD_oracle_refines_impl_eq in H12; eauto.\n      2: eapply have_same_structure_get_block_number; eauto.\n      3: apply TD_oracle_refines_operation_eq.\n      cleanup.\n\n      eapply lift2_invert_exec in H14;\n      eapply lift2_invert_exec in H16; cleanup.\n      apply map_ext_eq in H12; cleanup.\n      2: intros; cleanup; intuition congruence.\n      unfold File.files_inner_rep in *; cleanup.\n      eapply Inode.get_block_number_finished in H20; eauto.\n      eapply Inode.get_block_number_finished in H18; eauto.\n      cleanup.\n      clear H12 H20.\n      do 2 eexists; intuition eauto.\n      do 2 eexists; intuition eauto.\n\n      eexists; intuition eauto. \n      eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n      intros; FileInnerSpecs.solve_bounds.\n      \n      eexists; intuition eauto. \n      eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n      intros; FileInnerSpecs.solve_bounds.\n\n      setoid_rewrite H26; eauto.\n      setoid_rewrite H22; eauto.\n\n      unfold File.files_inner_rep in *; cleanup. \n      do 2 eexists; intuition eauto.\n    }\n    all: try solve [exact (fun _ _ => True)].\n    all: simpl; eauto.\n    {\n      intros.\n      match goal with\n       | [H: _ ?inum = Some _,\n          H0: _ ?inum = Some _ |- _] =>\n       eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H; eauto; cleanup;\n       eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H0; eauto; cleanup\n       end.\n       unfold FD_related_states,\n       same_for_user_except in *; cleanup.\n       match goal with\n       | [H: ?fm1 ?inum = Some _,\n          H0: ?fm2 ?inum = Some _,\n          H1: forall (_: addr) (_ _: File), \n           ?fm1 _ = Some _ ->\n           ?fm2 _ = Some _ ->\n           _ = _ /\\ _ = _ |- _] =>\n           eapply_fresh H1 in H; eauto; cleanup\n      end.\n       unfold File.file_map_rep in *; cleanup.\n       match goal with\n       | [H: ?x1 ?inum = Some _,\n          H0: ?x2 ?inum = Some _,\n          H1: forall (_: Inode.Inum) _ _, \n          ?x1 _ = Some _ ->\n          _ _ = Some _ -> _,\n          H2: forall (_: Inode.Inum) _ _, \n          ?x2 _ = Some _ ->\n          _ _ = Some _ -> _ |- _] =>\n          eapply H1 in H; eauto; cleanup;\n          eapply H2 in H0; eauto; cleanup\n       end.\n       unfold File.file_rep in *; cleanup; eauto.\n    }\n    Unshelve.\n    all: eauto.\n  Qed.\n    Opaque File.read_inner.\n\n\nOpaque Inode.get_owner.\nLemma ATCD_TS_read:\n    forall n inum off u u' txns1 txns2 hdr1 hdr2 lo s1 s2,\n    Termination_Sensitive_explicit u lo s1 s2\n    (Simulation.Definitions.compile\n    ATCD_Refinement\n   (Simulation.Definitions.compile\n    ATC_Refinement\n    (File.read inum off)))\n   (Simulation.Definitions.compile\n    ATCD_Refinement\n   (Simulation.Definitions.compile\n    ATC_Refinement\n    (File.read inum off)))\n    (Simulation.Definitions.compile\n    ATCD_Refinement\n    (Simulation.Definitions.compile\n    ATC_Refinement\n    File.recover))\n   (refines_valid ATCD_Refinement\n     (refines_valid ATC_Refinement\n    AD_valid_state))\n  (fun s1 s2 => refines_related ATCD_Refinement (refines_related ATC_Refinement (AD_related_states u' None)) s1 s2 /\\\n  equivalent_for_recovery txns1 txns2 Log.Current_Part hdr1 hdr2 s1 s2)\n     (ATCD_reboot_list n).\n  Proof.\n    Opaque File.read_inner Transaction.commit.\n    intros; simpl.\n    eapply ATCD_TS_explicit_compositional.\n    {\n      intros; eapply TS_explicit_to_TS; \n      eapply TS_eqv_impl;\n      [apply ATCD_TS_get_owner | shelve].\n      (*\n      unfold refines_related, AD_related_states; \n      simpl. unfold refines_related; simpl.\n      unfold refines, File.files_rep; simpl. \n      intros; cleanup; intuition eauto.\n      do 2 eexists; intuition eauto.\n      rewrite H4, H6;\n      do 2 eexists; intuition eauto.\n      unfold HC_refines in *; cleanup.\n      simpl in *.\n      unfold TransactionToTransactionalDisk.Definitions.refines,\n      Transaction.transaction_rep in *; simpl in *; cleanup.\n      repeat split_ors; cleanup; try congruence.\n      eapply txn_length_0_empty in H12;\n      setoid_rewrite H12.\n      simpl; eauto.\n\n      unfold HC_refines in *; cleanup.\n      simpl in *.\n      unfold TransactionToTransactionalDisk.Definitions.refines,\n      Transaction.transaction_rep in *; simpl in *; cleanup.\n      repeat split_ors; cleanup; try congruence.\n      eapply txn_length_0_empty in H16;\n      setoid_rewrite H16.\n      simpl; eauto.\n      *)\n    }\n    {\n      intros; unfold refines_related in *; cleanup.\n      eapply_fresh ATCD_oracle_refines_finished in H0; eauto.\n      eapply_fresh ATCD_oracle_refines_finished in H1; eauto.\n      cleanup.\n\n      eapply_fresh ATCD_exec_lift_finished in H0; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H1; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      simpl in *.\n      eapply ATCD_oracle_refines_impl_eq in H8; eauto.\n      2: shelve. (* eapply have_same_structure_get_owner; eauto. *)\n      2: apply TC_oracle_refines_operation_eq.\n      cleanup.\n\n      eapply_fresh ATC_oracle_refines_finished in H10; eauto.\n      eapply_fresh ATC_oracle_refines_finished in H12; eauto.\n      cleanup.\n      eapply_fresh ATC_exec_lift_finished in H10; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      eapply_fresh ATC_exec_lift_finished in H12; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      simpl in *.\n      eapply ATC_oracle_refines_impl_eq in H8; eauto.\n      2: eapply have_same_structure_get_owner; eauto.\n      2: apply TD_oracle_refines_operation_eq.\n      cleanup.\n\n      repeat invert_lift2; cleanup.\n      apply HC_map_ext_eq in H8; cleanup.\n\n      eapply_fresh get_owner_related_ret_eq in H21; eauto; subst.\n      destruct r1.\n      2: intros; eapply TS_explicit_to_TS;\n      eapply TS_eqv_impl;\n      [ apply ATCD_TS_abort_then_ret| shelve].\n      \n      eapply ATCD_TS_explicit_compositional.\n      intros; eapply TS_explicit_to_TS; \n      eapply TS_eqv_impl; \n      [apply ATCD_TS_Authentication_auth | shelve].\n      2: shelve.\n      simpl; intros; repeat invert_exec; try congruence.\n      2: intros; eapply TS_explicit_to_TS;\n      eapply TS_eqv_impl;\n      [ apply ATCD_TS_abort_then_ret| shelve].\n      eapply ATCD_TS_explicit_compositional.\n\n      (**** This part varies in proofs ****)\n      intros; eapply ATCD_TS_read_inner.\n      intros.\n      {\n        instantiate (1:= refines_related ATCD_Refinement\n        (fun s3 s4 : state AD =>\n         exists s1a s2a : disk File,\n           File.files_inner_rep s1a (fst (snd (snd s3))) /\\\n           File.files_inner_rep s2a (fst (snd (snd s4))) /\\\n           FD_related_states u' None s1a s2a /\\\n           fst (snd s3) = Empty /\\ fst (snd s4) = Empty)) in H13; simpl in *; cleanup.\n           unfold refines_related, FD_related_states in *; simpl in *; cleanup.\n\n          eapply_fresh read_inner_oracle_refines_exists in H4; eauto.\n          eapply_fresh read_inner_oracle_refines_exists in H6; eauto.\n          cleanup.\n          eapply_fresh ATCD_exec_lift_finished in H4; eauto;\n          try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n          try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n          cleanup.\n          eapply_fresh ATCD_exec_lift_finished in H6; eauto;\n          try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n          try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n          cleanup.\n          simpl in *.\n\n          eapply lift2_invert_exec in H22;\n          eapply lift2_invert_exec in H24; cleanup.\n          \n          eapply ATCD_oracle_refines_impl_eq in H21.\n          2: apply H20.\n          all: simpl in *; eauto.\n          2: apply TD_oracle_refines_operation_eq.\n          apply map_ext_eq in H21; cleanup.\n          2: intros; cleanup; intuition congruence.\n          eapply SameRetType.read_inner_finished_oracle_eq in H27.\n          2: apply H29.\n          all: eauto.\n          cleanup.\n          destruct r1, r2; try solve [intuition congruence].\n          intros; apply ATCD_TS_commit_then_ret.\n          intros; apply ATCD_TS_abort_then_ret.\n          eapply have_same_structure_read_inner; eauto.\n          do 2 eexists; intuition eauto.\n          unfold FD_related_states; \n          apply TSCommon.same_for_user_except_symmetry; eauto.\n          apply not_init_read_inner.\n          apply not_init_read_inner.\n      }\n      (**************)\n      intros; shelve.\n    }\n    intros; shelve.\n    Unshelve.\n    all: try exact u'.\n    all: eauto.\n    all: try solve [exact (fun _ _ => True)].\n    all: try solve [simpl; eauto].\n    {\n      simpl; intros;\n      unfold AD_related_states, refines_related in *; \n      cleanup; simpl in *.\n      unfold refines, File.files_rep in *; simpl in *; cleanup.\n      repeat invert_exec; destruct s0, s3; simpl in *; eauto;\n        do 2 eexists; intuition eauto;\n        do 2 eexists; intuition eauto.\n    }\n    2:{\n      intros; unfold refines_related in *; cleanup.\n      eapply_fresh get_owner_oracle_refines_exists in H; eauto.\n      eapply_fresh get_owner_oracle_refines_exists in H0; eauto.\n      cleanup.\n\n      eapply_fresh ATCD_exec_lift_finished in H; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H0; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      simpl in *.\n      eapply ATCD_oracle_refines_impl_eq in H4; eauto.\n      2: eapply have_same_structure_get_owner; eauto.\n      2: apply TD_oracle_refines_operation_eq.\n      cleanup.\n\n      eapply lift2_invert_exec in H6;\n      eapply lift2_invert_exec in H8; cleanup.\n      apply map_ext_eq in H4; cleanup.\n      2: intros; cleanup; intuition congruence.\n      do 2 eexists; intuition eauto.\n\n      unfold AD_related_states, refines_related in *; \n      cleanup; simpl in *.\n      unfold refines, File.files_rep, File.files_inner_rep in *; simpl in *; cleanup.\n\n      eapply Inode.get_owner_finished in H12; eauto.\n      2: rewrite H17; eauto.\n      eapply Inode.get_owner_finished in H10; eauto.\n      2: rewrite H13; eauto.\n      cleanup.\n\n      clear H10 H12. (* clear ors*)\n      do 2 eexists; intuition eauto;\n      eexists; intuition eauto;\n      eexists; intuition eauto.\n      all:eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto;\n      intros; FileInnerSpecs.solve_bounds.\n    }\n    {\n      simpl.\n      unfold refines_related, FD_related_states in *; simpl in *; cleanup.\n\n      eapply_fresh read_inner_oracle_refines_exists in H4; eauto.\n      eapply_fresh read_inner_oracle_refines_exists in H6; eauto.\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H4; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H6; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      simpl in *.\n\n      eapply lift2_invert_exec in H29;\n      eapply lift2_invert_exec in H31; cleanup.\n\n      eapply FileInnerSpecs.read_inner_finished in H34; eauto.\n      eapply FileInnerSpecs.read_inner_finished in H36; eauto.\n      cleanup.\n\n      unfold HC_refines in *; cleanup; simpl in *.\n      unfold TransactionToTransactionalDisk.Definitions.refines,\n      Transaction.transaction_rep in *; logic_clean.\n      \n      clear H48 H52.\n      repeat split; intros.\n      eapply Forall_forall; intros.\n      apply Transaction.dedup_last_in in H52.\n      apply in_rev in H52.\n      eapply Forall_forall in H37; eauto.\n\n      eapply Forall_forall; intros.\n      apply Transaction.dedup_last_in in H52.\n      apply in_rev in H52.\n      eapply Forall_forall in H38; eauto.\n\n      edestruct dedup_by_list_length\n        with (AEQ := addr_dec)\n             (l1:= (rev (map fst (fst (snd s2'0)))))\n             (l2:= (rev (map snd (fst (snd s2'0))))).\n\n      repeat rewrite rev_length, map_length in *.\n      pose proof (dedup_last_length addr_dec (rev (map fst (fst (snd s2'0))))).\n      rewrite rev_length in *.\n      apply addr_list_to_blocks_length_le_preserve in H88.\n      eapply PeanoNat.Nat.le_trans.\n      2: apply H47.\n      apply PeanoNat.Nat.add_le_mono; eauto.\n\n      edestruct dedup_by_list_length\n        with (AEQ := addr_dec)\n             (l1:= (rev (map fst (fst (snd s1'0)))))\n             (l2:= (rev (map snd (fst (snd s1'0))))).\n\n      repeat rewrite rev_length, map_length in *.\n      pose proof (dedup_last_length addr_dec (rev (map fst (fst (snd s1'0))))).\n      rewrite rev_length in *.\n      apply addr_list_to_blocks_length_le_preserve in H88.\n      eapply PeanoNat.Nat.le_trans.\n      2: apply H51.\n      apply PeanoNat.Nat.add_le_mono; eauto.\n    }\n    Unshelve.\n    all: eauto.\n  Qed.\n\n\n\n\n\n\nLemma ATCD_TS_DiskAllocator_read:\n    forall n a1 a2 u u',\n    (a1 < File.DiskAllocatorParams.num_of_blocks <-> a2 < File.DiskAllocatorParams.num_of_blocks) ->\n    (File.DiskAllocatorParams.bitmap_addr + S a1 <\n    data_length <->\n    File.DiskAllocatorParams.bitmap_addr + S a2 <\n    data_length) ->\n    Termination_Sensitive u\n  (Simulation.Definitions.compile\n     ATCD_Refinement\n     (@lift_L2 AuthenticationOperation _ TD _\n     (File.DiskAllocator.read a1)))\n  (Simulation.Definitions.compile\n     ATCD_Refinement\n     (@lift_L2 AuthenticationOperation _ TD _\n     (File.DiskAllocator.read a2)))\n  (Simulation.Definitions.compile\n     ATCD_Refinement\n     (Simulation.Definitions.compile\n        FD.refinement\n        (| Recover |)))\n  (refines_valid ATCD_Refinement\n     AD_valid_state)\n  (fun s1 s2 => refines_related ATCD_Refinement\n  (fun s1 s2  => exists s1a s2a, \n  File.files_inner_rep s1a (fst (snd (snd s1))) /\\ \n  File.files_inner_rep s2a (fst (snd (snd s2))) /\\ \n  FD_related_states u' None s1a s2a) s1 s2 /\\\n  (forall a, \n     Transaction.get_first (fst (snd s1)) a = None <-> \n     Transaction.get_first (fst (snd s2)) a = None) /\\\n  (Transaction.get_first (fst (snd s1)) (File.DiskAllocatorParams.bitmap_addr + S a1) = None <-> \n   Transaction.get_first (fst (snd s2)) (File.DiskAllocatorParams.bitmap_addr + S a2) = None) /\\\n   nth_error\n            (value_to_bits\n               (upd_batch (snd (snd s1)) (rev (map fst (fst (snd s1))))\n               (rev (map snd (fst (snd s1)))) File.DiskAllocatorParams.bitmap_addr)) a1 =\n               nth_error\n            (value_to_bits\n               (upd_batch (snd (snd s2)) (rev (map fst (fst (snd s2))))\n               (rev (map snd (fst (snd s2)))) File.DiskAllocatorParams.bitmap_addr)) a2)\n  (ATCD_reboot_list n).\n  Proof.\n    unfold File.DiskAllocator.read; intros.\n    destruct (Compare_dec.lt_dec a1 File.DiskAllocatorParams.num_of_blocks);\n    destruct (Compare_dec.lt_dec a2 File.DiskAllocatorParams.num_of_blocks);\n    try lia.\n    2: intros; apply ATCD_TS_ret.\n    simpl.\n    eapply ATCD_TS_compositional.\n\n    intros; eapply TS_eqv_impl.\n    eapply ATCD_TS_Transaction_read.\n    shelve.\n    intros; cleanup; eauto.\n    2: intros; shelve.\n    intros.\n    eapply lift2_invert_exec in H1; cleanup.\n    eapply lift2_invert_exec in H2; cleanup.\n    unfold refines_related in *; simpl in *; cleanup.\n    unfold HC_refines in *; simpl in *; cleanup.\n    unfold TransactionToTransactionalDisk.Definitions.refines in *.\n    eapply Transaction.read_finished in H8; eauto.\n    eapply Transaction.read_finished in H9; eauto.\n    cleanup; repeat split_ors; cleanup; try lia.\n    unfold Transaction.transaction_rep in *; cleanup.\n    setoid_rewrite H6.\n    destruct_fresh (nth_error\n    (value_to_bits\n       (upd_batch (snd (snd s2)) (rev (map fst (fst (snd s2))))\n          (rev (map snd (fst (snd s2))))\n          File.DiskAllocatorParams.bitmap_addr)) a2); setoid_rewrite D.\n    2: intros; apply ATCD_TS_ret.\n    {\n      destruct b.\n      2: intros; apply ATCD_TS_ret.\n      eapply ATCD_TS_compositional.\n      2: intros; apply ATCD_TS_ret.\n      intros; simpl; eapply ATCD_TS_Transaction_read; eauto.\n      intros; shelve.\n    }\n    {\n      edestruct (block_allocator_empty a1);\n      edestruct (block_allocator_empty a2);\n      cleanup; apply ATCD_TS_ret.\n    }\n    Unshelve.\n    all: try solve [ exact (fun _ _ => True)].\n    all: simpl; eauto.\n    all: intuition.\n    unfold File.DiskAllocatorParams.bitmap_addr.\n    {\n      eapply lift2_invert_exec in H1; cleanup.\n      eapply lift2_invert_exec in H2; cleanup.\n      unfold refines_related in *; simpl in *; cleanup.\n      unfold HC_refines in *; simpl in *; cleanup.\n      unfold TransactionToTransactionalDisk.Definitions.refines in *.\n      eapply Transaction.read_finished in H5; eauto.\n      eapply Transaction.read_finished in H12; eauto.\n      cleanup; intuition.\n    }\n    {\n      eapply lift2_invert_exec in H1; cleanup.\n      eapply lift2_invert_exec in H2; cleanup.\n      unfold refines_related in *; simpl in *; cleanup.\n      unfold HC_refines in *; simpl in *; cleanup.\n      unfold TransactionToTransactionalDisk.Definitions.refines in *.\n      eapply Transaction.read_finished in H5; eauto.\n      eapply Transaction.read_finished in H12; eauto.\n      cleanup; intuition.\n    }\n  Qed.\n\n  Lemma ATCD_TS_explicit_inode_map:\n  forall n u u' inum off, \n  (forall im1 im2,\n  Termination_Sensitive u\n  (Simulation.Definitions.compile ATCD_Refinement \n  (@lift_L2 AuthenticationOperation _ TD _ (File.read_inner off inum)))\n  (Simulation.Definitions.compile ATCD_Refinement\n  (@lift_L2 AuthenticationOperation _ TD _ (File.read_inner off inum)))\n    (Simulation.Definitions.compile ATCD_Refinement File.recover)\n    (refines_valid ATCD_Refinement\n     AD_valid_state)\n     (refines_related ATCD_Refinement \n     (fun s1 s2  => exists s1a s2a, \n    (Inode.inode_rep im1 (fst (snd (snd s1))) /\\\n        (exists file_block_map : disk value,\n            File.DiskAllocator.block_allocator_rep file_block_map\n              (fst (snd (snd s1))) /\\\n            File.file_map_rep s1a im1 file_block_map)) /\\\n      (Inode.inode_rep im2 (fst (snd (snd s2))) /\\\n        (exists file_block_map : disk value,\n            File.DiskAllocator.block_allocator_rep file_block_map\n              (fst (snd (snd s2))) /\\\n            File.file_map_rep s2a im2 file_block_map)) /\\\n    FD_related_states u' None s1a s2a /\\\n    fst (snd s1) = Empty /\\\n    fst (snd s2) = Empty))\n    (ATCD_reboot_list n)) ->\n\n\n    Termination_Sensitive u\n(Simulation.Definitions.compile ATCD_Refinement \n(@lift_L2 AuthenticationOperation _ TD _ (File.read_inner off inum)))\n(Simulation.Definitions.compile ATCD_Refinement\n(@lift_L2 AuthenticationOperation _ TD _ (File.read_inner off inum)))\n  (Simulation.Definitions.compile ATCD_Refinement File.recover)\n(refines_valid ATCD_Refinement\n     AD_valid_state)\n(refines_related ATCD_Refinement\n(fun s1 s2  => exists s1a s2a, \nFile.files_inner_rep s1a (fst (snd (snd s1))) /\\ \nFile.files_inner_rep s2a (fst (snd (snd s2))) /\\ \nFD_related_states u' None s1a s2a /\\\nfst (snd s1) = Empty /\\\n  fst (snd s2) = Empty))\n  (ATCD_reboot_list n) .\nProof.\nunfold Termination_Sensitive; intros.\nunfold refines_related, File.files_inner_rep in *.\ncleanup.\neapply H.\n3: eauto.\nall: eauto.\ndo 2 eexists; intuition eauto.\ndo 2 eexists; intuition eauto.\nQed.\n\nLemma ATCD_TS_read_inner:\n    forall n inum off u u',\n    Termination_Sensitive u\n  (Simulation.Definitions.compile\n     ATCD_Refinement\n     (@lift_L2 AuthenticationOperation _ TD _\n     (File.read_inner off inum)))\n  (Simulation.Definitions.compile\n     ATCD_Refinement\n     (@lift_L2 AuthenticationOperation _ TD _\n     (File.read_inner off inum)))\n  (Simulation.Definitions.compile\n     ATCD_Refinement\n     (Simulation.Definitions.compile\n        FD.refinement\n        (| Recover |)))\n  (refines_valid ATCD_Refinement\n     AD_valid_state)\n  (refines_related ATCD_Refinement\n  (fun s1 s2  => exists s1a s2a, \n  File.files_inner_rep s1a (fst (snd (snd s1))) /\\ \n  File.files_inner_rep s2a (fst (snd (snd s2))) /\\ \n  FD_related_states u' None s1a s2a /\\\n  fst (snd s1) = Empty /\\ fst (snd s2) = Empty))\n  (ATCD_reboot_list n).\n  Proof.\n    Transparent File.read_inner.\n    intros; \n    eapply ATCD_TS_explicit_inode_map.\n    intros; unfold File.read_inner.\n    eapply ATCD_TS_compositional.\n    intros; eapply TS_eqv_impl.\n    eapply ATCD_TS_get_block_number.\n    simpl; intros; shelve.\n    2: intros; shelve.\n\n    intros; unfold refines_related in *; cleanup.\n      eapply_fresh get_block_number_oracle_refines_exists in H; eauto.\n      eapply_fresh get_block_number_oracle_refines_exists in H0; eauto.\n      cleanup.\n\n      eapply_fresh ATCD_exec_lift_finished in H; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H0; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      simpl in *.\n      eapply ATCD_oracle_refines_impl_eq in H12; eauto.\n      2: eapply have_same_structure_get_block_number; eauto.\n      3: apply TD_oracle_refines_operation_eq.\n      cleanup.\n\n      eapply lift2_invert_exec in H14;\n      eapply lift2_invert_exec in H16; cleanup.\n      apply map_ext_eq in H12; cleanup.\n      2: intros; cleanup; intuition congruence.\n\n      unfold File.files_inner_rep in *; cleanup.\n      eapply_fresh Inode.get_block_number_finished_oracle_eq in H20; eauto; subst.\n      cleanup; destruct r1, r2; try solve [intuition congruence].\n      2: intros; apply ATCD_TS_ret.\n      \n      eapply ATCD_TS_compositional.\n      2: intros; destruct r1, r2; apply ATCD_TS_ret.\n      2: intros; shelve.\n      simpl; intros; repeat invert_exec; try congruence.\n      eapply TS_eqv_impl. \n      eapply ATCD_TS_DiskAllocator_read.\n      {\n        eapply Inode.get_block_number_finished in H20; eauto.\n        eapply Inode.get_block_number_finished in H18; eauto.\n        cleanup; repeat split_ors; cleanup; intuition eauto.\n        eapply SameRetType.all_block_numbers_in_bound in H29.\n        3: eauto.\n        all: eauto.\n        eapply Forall_forall in H29; eauto.\n        apply in_seln; eauto.\n\n        eapply SameRetType.all_block_numbers_in_bound in H10.\n        3: eauto.\n        all: eauto.\n        eapply Forall_forall in H10; eauto.\n        apply in_seln; eauto.\n      }\n      {\n        eapply Inode.get_block_number_finished in H20; eauto.\n        eapply Inode.get_block_number_finished in H18; eauto.\n\n        cleanup; repeat split_ors; cleanup; intuition eauto.\n      eapply data_block_inbounds; eauto.\n      eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n      intros; FileInnerSpecs.solve_bounds.\n\n      eapply data_block_inbounds.\n      4: eauto.\n      all: eauto.\n      eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n      intros; FileInnerSpecs.solve_bounds.\n      }\n      {\n        instantiate (2:= refines_related ATCD_Refinement\n        (fun s1 s2  => \n        exists s1a s2a, \n        (Inode.inode_rep im1 (fst (snd (snd s1))) /\\\n            (exists file_block_map,\n                File.DiskAllocator.block_allocator_rep file_block_map\n                  (fst (snd (snd s1))) /\\\n                File.file_map_rep s1a im1 file_block_map)) /\\\n          (Inode.inode_rep im2 (fst (snd (snd s2))) /\\\n            (exists file_block_map,\n                File.DiskAllocator.block_allocator_rep file_block_map\n                  (fst (snd (snd s2))) /\\\n                File.file_map_rep s2a im2 file_block_map)) /\\\n        FD_related_states u' None s1a s2a /\\\n        fst (snd s1) = Empty /\\\n        fst (snd s2) = Empty)).\n         \n         simpl; intros.\n         unfold refines_related in *.\n         cleanup.\n         split.\n         unfold File.files_inner_rep.\n         do 2 eexists; intuition eauto.\n         do 2 eexists; intuition eauto.\n\n         simpl in *; unfold HC_refines in H12, H21; cleanup.\n         simpl in *; unfold TransactionToTransactionalDisk.Definitions.refines,\n         Transaction.transaction_rep  in *; cleanup; \n         repeat split_ors; cleanup; try congruence.\n        eapply txn_length_0_empty in H34;\n        eapply txn_length_0_empty in H38; subst.\n        setoid_rewrite H34;\n        setoid_rewrite H38.\n        simpl; intuition eauto.\n\n        rewrite H38, H34 in *; simpl in *.\n        eapply Inode.get_block_number_finished in H20; eauto.\n        eapply Inode.get_block_number_finished in H18; eauto.\n        cleanup; repeat split_ors; cleanup; intuition eauto.\n        repeat erewrite TSCommon.used_blocks_are_allocated_2; eauto.\n      }\n      shelve.\n      {\n        unfold File.files_inner_rep in *; cleanup. \n        do 2 eexists; intuition eauto.\n      }\n\n    Unshelve.\n    all: eauto.\n    {\n      simpl.\n      intros; unfold refines_related in *; cleanup.\n      simpl in *.\n      unfold File.files_inner_rep in *; cleanup. \n      do 2 eexists; intuition eauto.\n      do 2 eexists; intuition eauto.\n\n      do 2 eexists; intuition eauto. \n\n      unfold HC_refines in *; cleanup.\n      simpl in *.\n      unfold TransactionToTransactionalDisk.Definitions.refines,\n      Transaction.transaction_rep in *; simpl in *; cleanup.\n      repeat split_ors; cleanup; try congruence.\n      eapply txn_length_0_empty in H14;\n      setoid_rewrite H14.\n      simpl; eauto.\n\n      unfold HC_refines in *; cleanup.\n      simpl in *.\n      unfold TransactionToTransactionalDisk.Definitions.refines,\n      Transaction.transaction_rep in *; simpl in *; cleanup.\n      repeat split_ors; cleanup; try congruence.\n      eapply txn_length_0_empty in H18;\n      setoid_rewrite H18.\n      simpl; eauto.\n    }\n    {\n      simpl.\n      intros; unfold refines_related in *; cleanup.\n      eapply_fresh get_block_number_oracle_refines_exists in H; eauto.\n      eapply_fresh get_block_number_oracle_refines_exists in H0; eauto.\n      cleanup.\n\n      eapply_fresh ATCD_exec_lift_finished in H; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H0; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      simpl in *.\n      eapply ATCD_oracle_refines_impl_eq in H12; eauto.\n      2: eapply have_same_structure_get_block_number; eauto.\n      3: apply TD_oracle_refines_operation_eq.\n      cleanup.\n\n      eapply lift2_invert_exec in H14;\n      eapply lift2_invert_exec in H16; cleanup.\n      apply map_ext_eq in H12; cleanup.\n      2: intros; cleanup; intuition congruence.\n      unfold File.files_inner_rep in *; cleanup.\n      eapply Inode.get_block_number_finished in H20; eauto.\n      eapply Inode.get_block_number_finished in H18; eauto.\n      cleanup.\n      clear H12 H20.\n      do 2 eexists; intuition eauto.\n      do 2 eexists; intuition eauto.\n\n      eexists; intuition eauto. \n      eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n      intros; FileInnerSpecs.solve_bounds.\n      \n      eexists; intuition eauto. \n      eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto.\n      intros; FileInnerSpecs.solve_bounds.\n\n      setoid_rewrite H26; eauto.\n      setoid_rewrite H22; eauto.\n\n      unfold File.files_inner_rep in *; cleanup. \n      do 2 eexists; intuition eauto.\n    }\n    all: try solve [exact (fun _ _ => True)].\n    all: simpl; eauto.\n    {\n      intros.\n      match goal with\n       | [H: _ ?inum = Some _,\n          H0: _ ?inum = Some _ |- _] =>\n       eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H; eauto; cleanup;\n       eapply_fresh FileInnerSpecs.inode_exists_then_file_exists in H0; eauto; cleanup\n       end.\n       unfold FD_related_states,\n       same_for_user_except in *; cleanup.\n       match goal with\n       | [H: ?fm1 ?inum = Some _,\n          H0: ?fm2 ?inum = Some _,\n          H1: forall (_: addr) (_ _: File), \n           ?fm1 _ = Some _ ->\n           ?fm2 _ = Some _ ->\n           _ = _ /\\ _ = _ |- _] =>\n           eapply_fresh H1 in H; eauto; cleanup\n      end.\n       unfold File.file_map_rep in *; cleanup.\n       match goal with\n       | [H: ?x1 ?inum = Some _,\n          H0: ?x2 ?inum = Some _,\n          H1: forall (_: Inode.Inum) _ _, \n          ?x1 _ = Some _ ->\n          _ _ = Some _ -> _,\n          H2: forall (_: Inode.Inum) _ _, \n          ?x2 _ = Some _ ->\n          _ _ = Some _ -> _ |- _] =>\n          eapply H1 in H; eauto; cleanup;\n          eapply H2 in H0; eauto; cleanup\n       end.\n       unfold File.file_rep in *; cleanup; eauto.\n    }\n    Unshelve.\n    all: eauto.\n  Qed.\n    Opaque File.read_inner.\n\n    Lemma ATCD_TS_read:\n    forall n inum off u u',\n    Termination_Sensitive u\n  (Simulation.Definitions.compile\n     ATCD_Refinement\n     (Simulation.Definitions.compile\n        FD.refinement\n        (| Read inum off |)))\n  (Simulation.Definitions.compile\n     ATCD_Refinement\n     (Simulation.Definitions.compile\n        FD.refinement\n        (| Read inum off |)))\n  (Simulation.Definitions.compile\n     ATCD_Refinement\n     (Simulation.Definitions.compile\n        FD.refinement\n        (| Recover |)))\n  (refines_valid ATCD_Refinement\n     AD_valid_state)\n  (refines_related ATCD_Refinement\n     (AD_related_states u' None))\n  (ATCD_reboot_list n).\n  Proof.\n    intros; simpl.\n    eapply ATCD_TS_compositional.\n    {\n      intros; eapply TS_eqv_impl.\n      eapply ATCD_TS_get_owner.\n      unfold refines_related, AD_related_states; \n      simpl. unfold refines_related; simpl.\n      unfold refines, File.files_rep; simpl. \n      intros; cleanup; intuition eauto.\n      do 2 eexists; intuition eauto.\n      rewrite H4, H6;\n      do 2 eexists; intuition eauto.\n      unfold HC_refines in *; cleanup.\n      simpl in *.\n      unfold TransactionToTransactionalDisk.Definitions.refines,\n      Transaction.transaction_rep in *; simpl in *; cleanup.\n      repeat split_ors; cleanup; try congruence.\n      eapply txn_length_0_empty in H12;\n      setoid_rewrite H12.\n      simpl; eauto.\n\n      unfold HC_refines in *; cleanup.\n      simpl in *.\n      unfold TransactionToTransactionalDisk.Definitions.refines,\n      Transaction.transaction_rep in *; simpl in *; cleanup.\n      repeat split_ors; cleanup; try congruence.\n      eapply txn_length_0_empty in H16;\n      setoid_rewrite H16.\n      simpl; eauto.\n    }\n    {\n      intros; unfold refines_related in *; cleanup.\n      eapply_fresh get_owner_oracle_refines_exists in H; eauto.\n      eapply_fresh get_owner_oracle_refines_exists in H0; eauto.\n      cleanup.\n\n      eapply_fresh ATCD_exec_lift_finished in H; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H0; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      simpl in *.\n      eapply ATCD_oracle_refines_impl_eq in H4; eauto.\n      2: eapply have_same_structure_get_owner; eauto.\n      2: apply TD_oracle_refines_operation_eq.\n      cleanup.\n\n      eapply lift2_invert_exec in H6;\n      eapply lift2_invert_exec in H8; cleanup.\n      apply map_ext_eq in H4; cleanup.\n      2: intros; cleanup; intuition congruence.\n\n      eapply_fresh get_owner_related_ret_eq in H10; eauto; subst.\n      destruct r2.\n      2: intros; apply ATCD_TS_abort_then_ret.\n      \n      eapply ATCD_TS_compositional.\n      intros; apply ATCD_TS_auth.\n      2: shelve.\n      simpl; intros; repeat invert_exec; try congruence.\n      2: intros; apply ATCD_TS_abort_then_ret.\n      eapply ATCD_TS_compositional.\n      intros; eapply ATCD_TS_read_inner.\n      intros.\n      {\n        instantiate (1:= refines_related ATCD_Refinement\n        (fun s3 s4 : state AD =>\n         exists s1a s2a : disk File,\n           File.files_inner_rep s1a (fst (snd (snd s3))) /\\\n           File.files_inner_rep s2a (fst (snd (snd s4))) /\\\n           FD_related_states u' None s1a s2a /\\\n           fst (snd s3) = Empty /\\ fst (snd s4) = Empty)) in H13; simpl in *; cleanup.\n        unfold refines_related, FD_related_states in *; simpl in *; cleanup.\n\n      eapply_fresh read_inner_oracle_refines_exists in H4; eauto.\n      eapply_fresh read_inner_oracle_refines_exists in H6; eauto.\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H4; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H6; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      simpl in *.\n\n      eapply lift2_invert_exec in H22;\n      eapply lift2_invert_exec in H24; cleanup.\n      \n      eapply ATCD_oracle_refines_impl_eq in H21.\n      2: apply H20.\n      all: simpl in *; eauto.\n      2: apply TD_oracle_refines_operation_eq.\n      apply map_ext_eq in H21; cleanup.\n      2: intros; cleanup; intuition congruence.\n      eapply SameRetType.read_inner_finished_oracle_eq in H27.\n      2: apply H29.\n      all: eauto.\n      cleanup.\n      destruct r1, r2; try solve [intuition congruence].\n      intros; apply ATCD_TS_commit_then_ret.\n      intros; apply ATCD_TS_abort_then_ret.\n      eapply have_same_structure_read_inner; eauto.\n      do 2 eexists; intuition eauto.\n      unfold FD_related_states; \n      apply TSCommon.same_for_user_except_symmetry; eauto.\n      apply not_init_read_inner.\n      apply not_init_read_inner.\n      }\n      intros; shelve.\n    }\n    intros; shelve.\n    Unshelve.\n    all: try exact u'.\n    all: eauto.\n    all: try solve [exact (fun _ _ => True)].\n    all: try solve [simpl; eauto].\n    {\n      simpl; intros;\n      unfold AD_related_states, refines_related in *; \n      cleanup; simpl in *.\n      unfold refines, File.files_rep in *; simpl in *; cleanup.\n      repeat invert_exec; destruct s0, s3; simpl in *; eauto;\n        do 2 eexists; intuition eauto;\n        do 2 eexists; intuition eauto.\n    }\n    2:{\n      intros; unfold refines_related in *; cleanup.\n      eapply_fresh get_owner_oracle_refines_exists in H; eauto.\n      eapply_fresh get_owner_oracle_refines_exists in H0; eauto.\n      cleanup.\n\n      eapply_fresh ATCD_exec_lift_finished in H; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H0; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      simpl in *.\n      eapply ATCD_oracle_refines_impl_eq in H4; eauto.\n      2: eapply have_same_structure_get_owner; eauto.\n      2: apply TD_oracle_refines_operation_eq.\n      cleanup.\n\n      eapply lift2_invert_exec in H6;\n      eapply lift2_invert_exec in H8; cleanup.\n      apply map_ext_eq in H4; cleanup.\n      2: intros; cleanup; intuition congruence.\n      do 2 eexists; intuition eauto.\n\n      unfold AD_related_states, refines_related in *; \n      cleanup; simpl in *.\n      unfold refines, File.files_rep, File.files_inner_rep in *; simpl in *; cleanup.\n\n      eapply Inode.get_owner_finished in H12; eauto.\n      2: rewrite H17; eauto.\n      eapply Inode.get_owner_finished in H10; eauto.\n      2: rewrite H13; eauto.\n      cleanup.\n\n      clear H10 H12. (* clear ors*)\n      do 2 eexists; intuition eauto;\n      eexists; intuition eauto;\n      eexists; intuition eauto.\n      all:eapply File.DiskAllocator.block_allocator_rep_inbounds_eq; eauto;\n      intros; FileInnerSpecs.solve_bounds.\n    }\n    {\n      simpl.\n      unfold refines_related, FD_related_states in *; simpl in *; cleanup.\n\n      eapply_fresh read_inner_oracle_refines_exists in H4; eauto.\n      eapply_fresh read_inner_oracle_refines_exists in H6; eauto.\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H4; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      eapply_fresh ATCD_exec_lift_finished in H6; eauto;\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_finished];\n      try solve [apply TransactionToTransactionalDisk.Refinement.TC_to_TD_core_simulation_crashed].\n      cleanup.\n      simpl in *.\n\n      eapply lift2_invert_exec in H29;\n      eapply lift2_invert_exec in H31; cleanup.\n\n      eapply FileInnerSpecs.read_inner_finished in H34; eauto.\n      eapply FileInnerSpecs.read_inner_finished in H36; eauto.\n      cleanup.\n\n      unfold HC_refines in *; cleanup; simpl in *.\n      unfold TransactionToTransactionalDisk.Definitions.refines,\n      Transaction.transaction_rep in *; logic_clean.\n      \n      clear H48 H52.\n      repeat split; intros.\n      eapply Forall_forall; intros.\n      apply Transaction.dedup_last_in in H52.\n      apply in_rev in H52.\n      eapply Forall_forall in H37; eauto.\n\n      eapply Forall_forall; intros.\n      apply Transaction.dedup_last_in in H52.\n      apply in_rev in H52.\n      eapply Forall_forall in H38; eauto.\n\n      edestruct dedup_by_list_length\n        with (AEQ := addr_dec)\n             (l1:= (rev (map fst (fst (snd s2'0)))))\n             (l2:= (rev (map snd (fst (snd s2'0))))).\n\n      repeat rewrite rev_length, map_length in *.\n      pose proof (dedup_last_length addr_dec (rev (map fst (fst (snd s2'0))))).\n      rewrite rev_length in *.\n      apply addr_list_to_blocks_length_le_preserve in H88.\n      eapply PeanoNat.Nat.le_trans.\n      2: apply H47.\n      apply PeanoNat.Nat.add_le_mono; eauto.\n\n      edestruct dedup_by_list_length\n        with (AEQ := addr_dec)\n             (l1:= (rev (map fst (fst (snd s1'0)))))\n             (l2:= (rev (map snd (fst (snd s1'0))))).\n\n      repeat rewrite rev_length, map_length in *.\n      pose proof (dedup_last_length addr_dec (rev (map fst (fst (snd s1'0))))).\n      rewrite rev_length in *.\n      apply addr_list_to_blocks_length_le_preserve in H88.\n      eapply PeanoNat.Nat.le_trans.\n      2: apply H51.\n      apply PeanoNat.Nat.add_le_mono; eauto.\n    }\n    Unshelve.\n    all: eauto.\n  Qed.\n*)\n\n      ", "meta": {"author": "Atalay-Ileri", "repo": "ConFrm", "sha": "80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf", "save_path": "github-repos/coq/Atalay-Ileri-ConFrm", "path": "github-repos/coq/Atalay-Ileri-ConFrm/ConFrm-80ca2e8c1671f24c5e94462b3edf8bfd25faf1bf/src/Noninterference/LoggedDisk/ATCDTransferProofs.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20102337065880066}}
{"text": "(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)\n(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)\nFrom mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq.\nRequire Import Init_ext ssrZ ZArith_ext uniq_tac machine_int multi_int.\nRequire Import encode_decode integral_type.\nImport MachineInt.\nRequire Import mips_bipl mips_seplog mips_tactics mips_syntax mips_mint.\nImport mips_bipl.expr_m.\nRequire Import simu.\nImport simu.simu_m.\nRequire Import copy_u_u_prg copy_u_u_triple copy_u_u_termination.\n\nLocal Open Scope machine_int_scope.\nLocal Open Scope heap_scope.\nLocal Open Scope assoc_scope.\nLocal Open Scope uniq_scope.\nLocal Open Scope asm_expr_scope.\nLocal Open Scope asm_cmd_scope.\nLocal Open Scope zarith_ext_scope.\n\nLemma copy_u_u_safe_termination a0 a1 a2 rk rx x ru u d :\n  uniq(x, u) -> uniq(rk, rx, ru, a0, a1, a2, r0) ->\n  safe_termination\n  (state_mint (x |=> unsign rk rx \\U+ (u |=> unsign rk ru \\U+ d)))\n  (copy_u_u rk rx ru a0 a1 a2).\nProof.\nmove=> Hvars Hregs.\nrewrite /safe_termination.\nmove=> s st h s_st_h.\nset code := copy_u_u _ _ _ _ _ _.\nmove: (proj1 s_st_h x (unsign rk rx)).\nrewrite assoc.get_union_sing_eq.\ncase/(_ Logic.eq_refl) => rx_fit x_rk Hx.\nmove: (proj1 s_st_h u (unsign rk ru)).\nrewrite assoc.get_union_sing_neq; last by Uniq_neq.\nrewrite assoc.get_union_sing_eq.\ncase/(_ Logic.eq_refl) => ru_fit u_rk Hu.\ncase: (copy_u_u_termination st h _ _ _ _ _ _ Hregs) => si Hsi.\nmove: (copy_u_u_triple _ _ _ _ _ _ Hregs\n  (Z2ints 32 '|u2Z ([rk ]_ st)| ([u ]_ s)%pseudo_expr)\n  (Z2ints 32 '|u2Z ([rk ]_ st)| ([x ]_ s)%pseudo_expr)\n  '|u2Z ([rk ]_ st)|).\nrewrite 2!size_Z2ints.\nmove/(_ erefl erefl _ rx_fit) => hoare_triple.\napply constructive_indefinite_description'.\nmove: (triple_exec_precond _ _ _ hoare_triple _ _ _ Hsi (heap.dom (heap_mint (unsign rk ru) st h \\U heap_mint (unsign rk rx) st h))).\napply.\nsplit => //.\nsplit.\n  rewrite Z_of_nat_Zabs_nat //; exact/min_u2Z.\nsuff : h |P|\n        heap.dom\n           (heap_mint (unsign rk ru) st h \\U heap_mint (unsign rk rx) st h) =\nheap_mint (unsign rk ru) st h \\U heap_mint (unsign rk rx) st h.\n  move=> ->.\n  apply assert_m.con_cons => //.\n  apply (proj2 s_st_h u x) => //.\n  by Uniq_neq.\n  rewrite assoc.get_union_sing_neq; last by Uniq_neq.\n  by rewrite assoc.get_union_sing_eq.\n  by rewrite assoc.get_union_sing_eq.\nrewrite -heap.incluE.\napply heap_prop_m.inclu_union; by apply heap_inclu_heap_mint_unsign.\nQed.\n", "meta": {"author": "affeldt-aist", "repo": "seplog", "sha": "b08516d34f5dedd0aafbe77d8ef270fa838e8f85", "save_path": "github-repos/coq/affeldt-aist-seplog", "path": "github-repos/coq/affeldt-aist-seplog/seplog-b08516d34f5dedd0aafbe77d8ef270fa838e8f85/begcd/copy_u_u_safe_termination.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.200981777614515}}
{"text": "From iris.program_logic Require Export weakestpre.\nFrom iris.base_logic Require Import invariants lib.saved_prop.\nFrom iris.heap_lang Require Export lang.\nFrom iris.heap_lang Require Import proofmode.\nFrom iris.algebra Require Import auth gset.\nFrom iris_examples.barrier Require Export barrier.\nSet Default Proof Using \"Type\".\n\n(** The CMRAs/functors we need. *)\nClass barrierG Σ := BarrierG {\n  barrier_inG :> inG Σ (authR (gset_disjUR gname));\n  barrier_savedPropG :> savedPropG Σ;\n}.\nDefinition barrierΣ : gFunctors :=\n  #[ GFunctor (authRF (gset_disjUR gname)); savedPropΣ ].\n\nInstance subG_barrierΣ {Σ} : subG barrierΣ Σ → barrierG Σ.\nProof. solve_inG. Qed.\n\n(** Now we come to the Iris part of the proof. *)\nSection proof.\nContext `{!heapG Σ, !barrierG Σ} (N : namespace).\n\nDefinition barrier_inv (l : loc) (γ : gname) (P : iProp Σ) : iProp Σ :=\n  (∃ (b : bool) (γsps : gset gname),\n    l ↦ #b ∗\n    own γ (● (GSet γsps)) ∗\n    ((if b then True else P) -∗\n      ([∗ set] γsp ∈ γsps, ∃ R, saved_prop_own γsp R ∗ ▷ R)))%I.\n\nDefinition recv (l : loc) (R : iProp Σ) : iProp Σ :=\n  (∃ γ P R' γsp,\n    inv N (barrier_inv l γ P) ∗\n    ▷ (R' -∗ R) ∗\n    own γ (◯ GSet {[ γsp ]}) ∗\n    saved_prop_own γsp R')%I.\n\nDefinition send (l : loc) (P : iProp Σ) : iProp Σ :=\n  (∃ γ, inv N (barrier_inv l γ P))%I.\n\n(** Setoids *)\nInstance barrier_inv_ne l γ : NonExpansive (barrier_inv l γ).\nProof. solve_proper. Qed.\nGlobal Instance send_ne l : NonExpansive (send l).\nProof. solve_proper. Qed.\nGlobal Instance recv_ne l : NonExpansive (recv l).\nProof. solve_proper. Qed.\n\n(** Actual proofs *)\nLemma newbarrier_spec (P : iProp Σ) :\n  {{{ True }}} newbarrier #() {{{ l, RET #l; recv l P ∗ send l P }}}.\nProof.\n  iIntros (Φ) \"_ HΦ\". iApply wp_fupd. wp_lam. wp_alloc l as \"Hl\".\n  iApply (\"HΦ\" with \"[> -]\").\n  iMod (saved_prop_alloc P) as (γsp) \"#Hsp\".\n  iMod (own_alloc (● GSet {[ γsp ]} ⋅ ◯ GSet {[ γsp ]})) as (γ) \"[H● H◯]\".\n  { by apply auth_both_valid. }\n  iMod (inv_alloc N _ (barrier_inv l γ P) with \"[Hl H●]\") as \"#Hinv\".\n  { iExists false, {[ γsp ]}. iIntros \"{$Hl $H●} !> HP\".\n    rewrite big_sepS_singleton; eauto. }\n  iModIntro; iSplitL \"H◯\".\n  - iExists γ, P, P, γsp. iFrame; auto.\n  - by iExists γ.\nQed.\n\nLemma signal_spec l P :\n  {{{ send l P ∗ P }}} signal #l {{{ RET #(); True }}}.\nProof.\n  iIntros (Φ) \"[Hs HP] HΦ\". iDestruct \"Hs\" as (γ) \"#Hinv\". wp_lam.\n  iInv N as ([] γsps) \"(>Hl & H● & HRs)\".\n  { wp_store. iModIntro. iSplitR \"HΦ\"; last by iApply \"HΦ\".\n    iExists true, γsps. iFrame. }\n  wp_store. iDestruct (\"HRs\" with \"HP\") as \"HRs\".\n  iModIntro. iSplitR \"HΦ\"; last by iApply \"HΦ\".\n  iExists true, γsps. iFrame; eauto.\nQed.\n\nLemma wait_spec l P:\n  {{{ recv l P }}} wait #l {{{ RET #(); P }}}.\nProof.\n  rename P into R.\n  iIntros (Φ) \"HR HΦ\". iDestruct \"HR\" as (γ P R' γsp) \"(#Hinv & HR & H◯ & #Hsp)\".\n  iLöb as \"IH\". wp_rec. wp_bind (! _)%E.\n  iInv N as ([] γsps) \"(>Hl & >H● & HRs)\"; last first.\n  { wp_load. iModIntro. iSplitL \"Hl H● HRs\".\n    { iExists false, γsps. iFrame. }\n    by wp_apply (\"IH\" with \"[$] [$]\"). }\n  iSpecialize (\"HRs\" with \"[//]\"). wp_load.\n  iDestruct (own_valid_2 with \"H● H◯\")\n    as %[Hvalid%gset_disj_included%elem_of_subseteq_singleton _]%auth_both_valid.\n  iDestruct (big_sepS_delete with \"HRs\") as \"[HR'' HRs]\"; first done.\n  iDestruct \"HR''\" as (R'') \"[#Hsp' HR'']\".\n  iDestruct (saved_prop_agree with \"Hsp Hsp'\") as \"#Heq\".\n  iMod (own_update_2 with \"H● H◯\") as \"H●\".\n  { apply (auth_update_dealloc _ _ (GSet (γsps ∖ {[ γsp ]}))).\n    apply gset_disj_dealloc_local_update. }\n  iIntros \"!>\". iSplitL \"Hl H● HRs\".\n  { iDestruct (bi.later_intro with \"HRs\") as \"HRs\".\n    iModIntro. iExists true, (γsps ∖ {[ γsp ]}). iFrame; eauto. }\n  wp_if. iApply \"HΦ\". iApply \"HR\". by iRewrite \"Heq\".\nQed.\n\nLemma recv_split E l P1 P2 :\n  ↑N ⊆ E → recv l (P1 ∗ P2) ={E}=∗ recv l P1 ∗ recv l P2.\nProof.\n  rename P1 into R1; rename P2 into R2.\n  iIntros (?). iDestruct 1 as (γ P R' γsp) \"(#Hinv & HR & H◯ & #Hsp)\".\n  iInv N as (b γsps) \"(>Hl & >H● & HRs)\".\n  iDestruct (own_valid_2 with \"H● H◯\")\n    as %[Hvalid%gset_disj_included%elem_of_subseteq_singleton _]%auth_both_valid.\n  iMod (own_update_2 with \"H● H◯\") as \"H●\".\n  { apply (auth_update_dealloc _ _ (GSet (γsps ∖ {[ γsp ]}))).\n    apply gset_disj_dealloc_local_update. }\n  set (γsps' := γsps ∖ {[γsp]}).\n  iMod (saved_prop_alloc_cofinite γsps' R1) as (γsp1 Hγsp1) \"#Hsp1\".\n  iMod (saved_prop_alloc_cofinite (γsps' ∪ {[ γsp1 ]}) R2)\n    as (γsp2 [? ?%not_elem_of_singleton]%not_elem_of_union) \"#Hsp2\".\n  iMod (own_update _ _ (● _ ⋅ (◯ GSet {[ γsp1 ]} ⋅ ◯ (GSet {[ γsp2 ]})))\n    with \"H●\") as \"(H● & H◯1 & H◯2)\".\n  { rewrite -auth_frag_op gset_disj_union; last set_solver.\n    apply auth_update_alloc, (gset_disj_alloc_empty_local_update _ {[ γsp1; γsp2 ]}).\n    set_solver. }\n  iModIntro. iSplitL \"HR Hl HRs H●\".\n  { iModIntro. iExists b, ({[γsp1; γsp2]} ∪ γsps').\n    iIntros \"{$Hl $H●} HP\". iSpecialize (\"HRs\" with \"HP\").\n    iDestruct (big_sepS_delete with \"HRs\") as \"[HR'' HRs]\"; first done.\n    iDestruct \"HR''\" as (R'') \"[#Hsp' HR'']\".\n    iDestruct (saved_prop_agree with \"Hsp Hsp'\") as \"#Heq\".\n    iAssert (▷ R')%I with \"[HR'']\" as \"HR'\"; [iNext; by iRewrite \"Heq\"|].\n    iDestruct (\"HR\" with \"HR'\") as \"[HR1 HR2]\".\n    iApply big_sepS_union; [set_solver|iFrame \"HRs\"].\n    iApply big_sepS_union; [set_solver|].\n    iSplitL \"HR1\"; rewrite big_sepS_singleton; eauto. }\n  iModIntro; iSplitL \"H◯1\".\n  - iExists γ, P, R1, γsp1. iFrame; auto.\n  - iExists γ, P, R2, γsp2. iFrame; auto.\nQed.\n\nLemma recv_weaken l P1 P2 : (P1 -∗ P2) -∗ recv l P1 -∗ recv l P2.\nProof.\n  iIntros \"HP\". iDestruct 1 as (γ P R' i) \"(#Hinv & HR & H◯)\".\n  iExists γ, P, R', i. iIntros \"{$Hinv $H◯} !> HQ\". iApply \"HP\". by iApply \"HR\".\nQed.\n\nLemma recv_mono l P1 P2 : (P1 ⊢ P2) → recv l P1 ⊢ recv l P2.\nProof. iIntros (HP) \"H\". iApply (recv_weaken with \"[] H\"). iApply HP. Qed.\nEnd proof.\n\nTypeclasses Opaque send recv.\n", "meta": {"author": "anemoneflower", "repo": "IRIS-study", "sha": "63cbfee3959659074047682faeed7190b5be53df", "save_path": "github-repos/coq/anemoneflower-IRIS-study", "path": "github-repos/coq/anemoneflower-IRIS-study/IRIS-study-63cbfee3959659074047682faeed7190b5be53df/examples-master/theories/barrier/proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5428632683808532, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.20098176288984898}}
{"text": "Require Import VST.floyd.proofauto.\nRequire Import VST.progs.minexample.\nInstance CompSpecs : compspecs. make_compspecs prog. Defined.\nDefinition Vprog : varspecs. mk_varspecs prog. Defined.\n\nDefinition minexample_spec : ident * funspec :=\n DECLARE _minexample\n WITH a: val, b: val, c: val, d: val, sh : share\n PRE []                                            \n   PROP  ()\n   LOCAL () \n   SEP   (data_at sh tint Vzero a;\n          data_at sh tint Vzero a -* data_at sh tint Vzero b)\n  POST [ tint ]\n    PROP()\n    LOCAL (temp ret_temp Vzero)\n    SEP ().\n    \nDefinition Gprog : funspecs :=\n        ltac:(with_library prog [minexample_spec]).\n\nLemma body_minexample : semax_body Vprog Gprog f_minexample minexample_spec.\nProof.\n  start_function.\n  (* pattern-accepting behavior: *)\n  Fail\n    (gather_SEP\n       (data_at sh tint Vzero a)\n       (data_at sh tint Vzero a -* data_at sh tint Vzero b)).\n  (* equivalent numerical behavior: *)\n  gather_SEP 0 1.\nAbort.", "meta": {"author": "anshumanmohan", "repo": "gather_SEP_issue", "sha": "f7b53a39dda22859a11fc2190ec33f28c9bc2594", "save_path": "github-repos/coq/anshumanmohan-gather_SEP_issue", "path": "github-repos/coq/anshumanmohan-gather_SEP_issue/gather_SEP_issue-f7b53a39dda22859a11fc2190ec33f28c9bc2594/verif_minexample.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.3208213008246071, "lm_q1q2_score": 0.20087397301612112}}
{"text": "Require Import Common.Definitions.\nRequire Import Common.Util.\nRequire Export Common.Values.\nRequire Export Common.Linking.\nRequire Import Common.Memory.\nRequire Import Lib.Monads.\nRequire Import Lib.Extra.\n\nFrom mathcomp Require Import ssreflect ssrfun ssrbool seq eqtype.\nFrom extructures Require Import fmap.\n\nSet Implicit Arguments.\nUnset Strict Implicit.\nUnset Printing Implicit Defensive.\n\nSet Bullet Behavior \"Strict Subproofs\".\n\n(* NOTE: Technically a [Variant], i.e., there is no use for the [Inductive]\n   principle in proofs, but it is required to derive a QuickChick generator. *)\nInductive register : Type :=\n  R_ONE | R_COM | R_AUX1 | R_AUX2 | R_RA | R_SP | R_ARG.\n\nDefinition label := nat.\n\nVariant imvalue : Type :=\n| IInt : Z -> imvalue\n| IPtr : Pointer.t -> imvalue.\n\nDefinition imm_to_val (im : imvalue) : value :=\n  match im with\n  | IInt n => Int n\n  | IPtr p => Ptr p\n  end.\n\nVariant instr :=\n| INop : instr\n| ILabel : label -> instr\n(* register operations *)\n| IConst : imvalue -> register -> instr\n| IMov : register -> register -> instr\n| IBinOp : binop -> register -> register -> register -> instr\n(* memory operations *)\n| ILoad : register -> register -> instr\n| IStore : register -> register -> instr\n| IAlloc : register -> register -> instr\n(* conditional and unconditional jumps *)\n| IBnz : register -> label -> instr\n| IJump : register -> instr\n| IJal : label -> instr\n(* components interaction *)\n| ICall : Component.id -> Procedure.id -> instr\n| IReturn : instr\n(* termination *)\n| IHalt : instr.\n\nDefinition code := list instr.\n\nModule Intermediate.\n\nModule Register.\n  Definition t : Type := NMap value.\n\n  Definition to_nat (r : register) : nat :=\n    match r with\n    | R_ONE  => 0\n    | R_COM  => 1\n    | R_AUX1 => 2\n    | R_AUX2 => 3\n    | R_RA   => 4\n    | R_SP   => 5\n    | R_ARG  => 6\n    end.\n\n  Definition init :=\n    mkfmap [(to_nat R_ONE, Undef);\n            (to_nat R_COM, Undef);\n            (to_nat R_AUX1, Undef);\n            (to_nat R_AUX2, Undef);\n            (to_nat R_RA, Undef);\n            (to_nat R_SP, Undef);\n            (to_nat R_ARG, Undef)].\n\n  Definition get (r : register) (regs : t) : value :=\n    match getm regs (to_nat r) with\n    | Some val => val\n    (* this should never happen (i.e. regs should be well-formed) *)\n    | None => Undef\n    end.\n\n  Definition set (r : register) (val : value) (regs : t) : t :=\n    setm regs (to_nat r) val.\n\n  Definition invalidate (regs : t) : t :=\n    mkfmap [(to_nat R_ONE, Undef);\n            (to_nat R_COM, get R_COM regs);\n            (to_nat R_AUX1, Undef);\n            (to_nat R_AUX2, Undef);\n            (to_nat R_RA, Undef);\n            (to_nat R_SP, Undef);\n            (to_nat R_ARG, Undef)].\n\n  Lemma invalidate_eq : forall regs1 regs2,\n    get R_COM regs1 = get R_COM regs2 ->\n    invalidate regs1 = invalidate regs2.\n  Proof.\n    intros regs1 regs2 Hregs.\n    unfold invalidate.\n    congruence.\n  Qed.\nEnd Register.\n\nModule EntryPoint.\n  Definition t := NMap (NMap Block.id).\n\n  Definition get (C: Component.id) (P: Procedure.id) (E: t) : option Block.id :=\n    match getm E C with\n    | Some addrs => getm addrs P\n    | None => None\n    end.\n\n  Lemma get_some C P E b : get C P E = Some b -> C \\in domm E.\n  Proof.\n    unfold get. intros Hget.\n    destruct (E C) as [M |] eqn:Hcase; last discriminate.\n    apply /dommP. eauto.\n  Qed.\nEnd EntryPoint.\n\n(* programs *)\n\nRecord program := mkProg {\n  prog_interface: Program.interface;\n  prog_procedures: NMap (NMap code);\n  prog_buffers: NMap {fmap Block.id -> nat + list value};\n  prog_main: bool\n}.\n\n(* well-formedness of programs *)\n\nDefinition well_formed_instruction\n           (p: program) (C: Component.id) (P: Procedure.id) (i: instr) : Prop :=\n  match i with\n  | IBnz r l =>\n    (* the branch refers to a label inside the current procedure C.P *)\n    exists Cprocs Pcode,\n      getm (prog_procedures p) C = Some Cprocs /\\\n      getm Cprocs P = Some Pcode /\\\n      In (ILabel l) Pcode\n  | IJal l =>\n    (* the jump refers to a label inside the current component C *)\n    exists Cprocs P' P'code,\n      getm (prog_procedures p) C = Some Cprocs /\\\n      getm Cprocs P' = Some P'code /\\\n      In (ILabel l) P'code\n  | ICall C' P' =>\n    (* a call is well-formed only if it targets another component and the\n       interface is allowing it to happen *)\n    C <> C' /\\ imported_procedure (prog_interface p) C C' P'\n  | IConst (IPtr ptr) r =>\n    (* static pointers refers to static buffers *)\n    exists bufs,\n      getm (prog_buffers p) (Pointer.component ptr) = Some bufs /\\\n      In (Pointer.block ptr) (map fst bufs)\n  (* the other instruction are well-formed by construction *)\n  | IConst (IInt i) r => True\n  | ILabel l => True\n  | INop => True\n  | IMov r1 r2 => True\n  | IBinOp bop r1 r2 r3 => True\n  | ILoad r1 r2 => True\n  | IStore r1 r2 => True\n  | IAlloc r1 r2 => True\n  | IJump r => True\n  | IReturn => True\n  | IHalt => True\n  end.\n\nRecord well_formed_program (p: program) := {\n  (* the interface is sound (but maybe not closed)\n     RB: Currently not used in the proofs. *)\n  wfprog_interface_soundness:\n    sound_interface (prog_interface p);\n  (* there are procedures only for the declared components *)\n  wfprog_defined_procedures:\n    domm (prog_interface p) = domm (prog_procedures p);\n  (* each exported procedure actually exists *)\n  wfprog_exported_procedures_existence:\n    forall C CI,\n      getm (prog_interface p) C = Some CI ->\n    forall P,\n      Component.is_exporting CI P ->\n    exists Cprocs Pcode,\n      getm (prog_procedures p) C = Some Cprocs /\\\n      getm Cprocs P = Some Pcode;\n  (* each instruction of each procedure is well-formed *)\n  wfprog_well_formed_instructions:\n    forall C Cprocs,\n      getm (prog_procedures p) C = Some Cprocs ->\n    forall P Pcode,\n      getm Cprocs P = Some Pcode ->\n    forall i, In i Pcode -> well_formed_instruction p C P i;\n  (* there are buffers only for the declared components *)\n  wfprog_defined_buffers:\n    domm (prog_interface p) = domm (prog_buffers p);\n  (* if the main component exists, then the main procedure must exist as well *)\n  wfprog_main_existence:\n      prog_main p ->\n    exists main_procs,\n      getm (prog_procedures p) Component.main = Some main_procs /\\ Procedure.main \\in domm main_procs;\n  (* Iff the main component is in the interface, a main procedure is given. *)\n  wfprog_main_component:\n    (* (RB: Old-style fix, later changed from a simple implication.) *)\n    (* prog_main p = None -> *)\n    (* Component.main \\notin domm (prog_interface p) *)\n    Component.main \\in domm (prog_interface p) <->\n    prog_main p;\n  (* wfprog_main_id: *)\n  (*   forall mainP, *)\n  (*     prog_main p = Some mainP -> *)\n  (*     mainP = 0 *)\n}.\n\n(* a closed program is a program with a closed interface and an existing main\n   procedure *)\nRecord closed_program (p: program) := {\n  (* the interface must be closed (and consequently sound) *)\n  cprog_closed_interface:\n    closed_interface (prog_interface p);\n  (* the main procedure must exist *)\n  cprog_main_existence:\n    exists main_procs,\n      prog_main p /\\\n      getm (prog_procedures p) Component.main = Some main_procs /\\ 0 \\in domm main_procs\n}.\n\nDefinition linkable_mains (prog1 prog2 : program) : Prop :=\n  ~~ (prog_main prog1 && prog_main prog2).\n\nLemma linkable_mains_sym : forall (prog1 prog2 : program),\n  linkable_mains prog1 prog2 -> linkable_mains prog2 prog1.\nProof.\n  intros prog1 prog2.\n  unfold linkable_mains, andb, negb.\n  destruct (prog_main prog1);\n    destruct (prog_main prog2);\n    intuition.\nQed.\n\n(* RB: TODO: Remove superfluous linkable_main assumptions from development.\n   Observe the relation to PS.domm_partition_in_union_in_neither. *)\nTheorem linkable_implies_linkable_mains : forall (p1 p2 : program),\n  well_formed_program p1 ->\n  well_formed_program p2 ->\n  linkable (prog_interface p1) (prog_interface p2) ->\n  linkable_mains p1 p2.\nProof.\n  intros p1 p2 Hwf1 Hwf2 [_ Hdisjoint].\n  unfold linkable_mains.\n  destruct (prog_main p1) as [|] eqn:Hmain1;\n    destruct (prog_main p2) as [|] eqn:Hmain2;\n    try reflexivity.\n  (* All that remains is the contradictory case. *)\n  pose proof (proj2 (wfprog_main_component Hwf1)) as Hdomm1.\n  rewrite Hmain1 in Hdomm1. specialize (Hdomm1 isT).\n  pose proof (proj2 (wfprog_main_component Hwf2)) as Hdomm2.\n  rewrite Hmain2 in Hdomm2. specialize (Hdomm2 isT).\n  pose proof fdisjointP _ _ Hdisjoint _ Hdomm1 as Hcontra.\n  now rewrite Hdomm2 in Hcontra.\nQed.\n\nDefinition matching_mains (prog1 prog2 : program) : Prop :=\n  prog_main prog1 <-> prog_main prog2.\n\nDefinition program_link (p1 p2: program): program :=\n  {| prog_interface := unionm (prog_interface p1) (prog_interface p2);\n     prog_procedures := unionm (prog_procedures p1) (prog_procedures p2);\n     prog_buffers := unionm (prog_buffers p1) (prog_buffers p2);\n     prog_main := prog_main p1 || prog_main p2 |}.\n\nLemma program_linkC p1 p2 :\n  well_formed_program p1 ->\n  well_formed_program p2 ->\n  linkable (prog_interface p1) (prog_interface p2) ->\n  program_link p1 p2 = program_link p2 p1.\nProof.\n  case: p1 p2 => [i1 p1 b1 m1] [i2 p2 b2 m2] /= Hwf1 Hwf2 [_ Hdis_i].\n  have Hdis_p: fdisjoint (domm p1) (domm p2).\n    by rewrite -(wfprog_defined_procedures Hwf1) -(wfprog_defined_procedures Hwf2).\n  congr mkProg=> /=; try rewrite unionmC //.\n    by rewrite -(wfprog_defined_buffers Hwf1) -(wfprog_defined_buffers Hwf2).\n      by rewrite orb_comm.\nQed.\n\nTheorem linking_well_formedness:\n  forall p1 p2,\n    well_formed_program p1 ->\n    well_formed_program p2 ->\n    linkable (prog_interface p1) (prog_interface p2) ->\n    well_formed_program (program_link p1 p2).\nProof.\n  move=> p1 p2 Hwf1 Hwf2 [Hsound Hdis_i]; split=> //.\n  - simpl.\n    repeat rewrite domm_union.\n    by do 2![rewrite wfprog_defined_procedures //].\n  - move=> /= C CI H1 P H2.\n    rewrite unionmE -mem_domm -(wfprog_defined_procedures Hwf1) !mem_domm.\n    rewrite unionmE in H1.\n    case Hwhere: (prog_interface p1 C) H1 => [CI'|] //=.\n    + move=> [?]; subst CI'.\n      destruct (wfprog_exported_procedures_existence Hwf1 Hwhere H2)\n        as [Cprocs [Pcode [Hproc Hcode]]].\n      rewrite Hproc. simpl.\n      exists Cprocs. exists Pcode.\n      split; auto.\n    + suffices Hno_p1 : prog_procedures p1 C = None.\n        move=> H1.\n        destruct (wfprog_exported_procedures_existence Hwf2 H1 H2)\n          as [Cprocs [Pcode [Hproc Hcode]]].\n        exists Cprocs. exists Pcode.\n        split; auto.\n      now apply/dommPn; rewrite -(wfprog_defined_procedures Hwf1); apply/dommPn.\n  - move=> C Cprocs H1 P Pcode H2.\n    without loss H: p1 p2 Hwf1 Hwf2 Hsound Hdis_i H1 / prog_procedures p1 C = Some Cprocs.\n    { move: H1; rewrite /= unionmE.\n      case e: (prog_procedures p1 C)=> [Cprocs'|] //=.\n        move=> [<-]; apply=> //.\n        by rewrite unionmE e.\n      move=> Hp2_C Hgen i Hi; rewrite program_linkC //.\n      apply Hgen=> //.\n      + by rewrite unionmC // fdisjointC.\n      + by rewrite fdisjointC.\n      + by rewrite unionmE Hp2_C. }\n    move=> i Hi.\n    move: (wfprog_well_formed_instructions Hwf1 H H2 Hi).\n    case: i Hi=> //=.\n    + (* IConst *)\n      case=> // ptr r Hi [bufs [p1_bufs Hbufs]].\n      by exists bufs; rewrite unionmE p1_bufs.\n    + (* IBnz *)\n      move=> r l Hi [Cprocs' [Pcode']].\n      rewrite H=> - [[<-] {Cprocs'}].\n      rewrite H2=> - [[<-] {Pcode'}] Hl.\n      by exists Cprocs, Pcode; rewrite unionmE H.\n    + (* IJal *)\n      move=> l Hi [Cprocs' [P' [Pcode']]].\n      rewrite H=> - [[<-] {Cprocs'}].\n      case=> H2' Hl.\n      by exists Cprocs, P', Pcode'; rewrite unionmE H.\n    + (* ICall *)\n      move=> C' P' Hi [CC' [CI [p1_C Himport]]]; split=> //.\n      exists CI; split=> //.\n      by rewrite /Program.has_component unionmE p1_C.\n  - rewrite /= !domm_union.\n    by do 2![rewrite wfprog_defined_buffers //].\n  - rewrite /=. case /orP => [mainP | mainP].\n    + have Hmain1 := @wfprog_main_existence _ Hwf1 mainP.\n      case: Hmain1 => [main_procs [p1_main HmainP]] //=.\n        by exists main_procs; rewrite unionmE p1_main.\n    + have Hmain2 := @wfprog_main_existence _ Hwf2 mainP.\n      case: Hmain2 => [main_procs [p2_main HmainP]] //=.\n      exists main_procs; rewrite unionmC 1?unionmE 1?p2_main //.\n      by rewrite -(wfprog_defined_procedures Hwf1) -(wfprog_defined_procedures Hwf2).\n  - inversion Hwf1 as [_ _ _ _ _ _ Hmain_comp1].\n    inversion Hwf2 as [_ _ _ _ _ _ Hmain_comp2].\n    split;\n      intros Hprog_main1.\n    + assert (Hprog_main2 := Hprog_main1).\n      simpl in *.\n      destruct (Component.main \\in domm (prog_interface p1)) eqn:Hcase1;\n        destruct (Component.main \\in domm (prog_interface p2)) eqn:Hcase2.\n      * (* Contra/easy. *)\n        pose proof (proj1 Hmain_comp1 Hcase1) as Hmain1. now rewrite Hmain1.\n      * apply proj1 in Hmain_comp1.\n        specialize (Hmain_comp1 Hcase1). rewrite Hmain_comp1. by [].\n      * destruct (prog_main p1) as [main1 |] eqn:Hmain1.\n        -- reflexivity.\n        -- apply proj1 in Hmain_comp2.\n           specialize (Hmain_comp2 Hcase2). assumption.\n      * (* Contra. *)\n        destruct (@dommP _ _ _ _ Hprog_main1) as [CI HCI]. rewrite unionmE in HCI.\n        apply negb_true_iff in Hcase1. apply negb_true_iff in Hcase2.\n        now rewrite (@dommPn _ _ _ _ Hcase1) (@dommPn _ _ _ _ Hcase2) in HCI.\n    + inversion Hprog_main1 as [Hmain].\n      destruct (prog_main p1) as [main1 |] eqn:Hcase1;\n        destruct (prog_main p2) as [main2 |] eqn:Hcase2.\n      * (* Contra/easy. RB: NOTE: Three cases can be solved as instances of a\n           little lemma, or a tactic. Is it useful elsewhere? *)\n        apply proj2 in Hmain_comp1. specialize (Hmain_comp1 isT).\n        destruct (@dommP _ _ _ _ Hmain_comp1) as [CI HCI].\n        apply /dommP. exists CI. now rewrite unionmE HCI.\n      * apply proj2 in Hmain_comp1. specialize (Hmain_comp1 isT).\n        destruct (@dommP _ _ _ _ Hmain_comp1) as [CI HCI].\n        apply /dommP. exists CI. now rewrite unionmE HCI.\n      * apply proj2 in Hmain_comp2. specialize (Hmain_comp2 isT).\n        destruct (@dommP _ _ _ _ Hmain_comp2) as [CI HCI].\n        apply /dommP. exists CI. simpl. now rewrite (unionmC Hdis_i) unionmE HCI.\n      * discriminate.\nQed.\n\n(* Given a list of components, create the map that associates to\n   each component the preallocated buffers according to program p.\n   If no buffers are found, use the empty map as a default (this\n   will not happen in regular use!). *)\nDefinition alloc_static_buffers p comps :=\n  mkfmapf (fun C =>\n    ComponentMemory.prealloc (odflt emptym (prog_buffers p C))) comps.\n\nDefinition prepare_initial_memory (p: program) : Memory.t :=\n  alloc_static_buffers p (domm (prog_interface p)).\n\n(* RB: Are the names of reserve_[component|procedure]_blocks swapped? *)\n(* For each pair of procedure id and code in procs_code, build the triad of\n   component memory, procedure code map and component entry point map by\n   folding over them:\n    - Reserve a new block id in the component memory.\n    - Map that block id to the procedure code in the procedure block map.\n    - If the procedure is public, map the procedure id to the memory block id\n      in the component entry point map.\n   From the calling point, observe on the one hand that the initial values of\n   the accumulators are the existing component memory and two empty maps. On the\n   other hand, observe also that procs_code are the contents of a map in\n   associative list form, and each procedure is is therefore unique. *)\nDefinition reserve_component_blocks' p C acc procs_code\n  : ComponentMemory.t * NMap code * NMap Block.id :=\n  let is_main_proc comp_id proc_id :=\n      match prog_main p with\n      | true =>\n        (Component.main =? comp_id) && (Procedure.main =? proc_id)\n      | false => false\n      end in\n  let aux acc procs_code :=\n      let '(Cmem, Cprocs, Centrypoints) := acc in\n      let '(P, Pcode) := procs_code in\n    let (Cmem', b) := ComponentMemory.reserve_block Cmem in\n    let Cprocs' := setm Cprocs b Pcode in\n    (* if P is exported or is the main procedure, add an external entrypoint *)\n    match getm (prog_interface p) C with\n    | Some Ciface =>\n      if (P \\in Component.export Ciface) || is_main_proc C P then\n        let Centrypoints' := setm Centrypoints P b in\n        (Cmem', Cprocs', Centrypoints')\n      else\n        (Cmem', Cprocs', Centrypoints)\n    | None =>\n      (* this case shouldn't happen for well formed p *)\n      (Cmem', Cprocs', Centrypoints)\n    end\n  in fold_left aux procs_code acc.\n\n(* The simplified version substitutes the accumulator for the component memory.\n   It reserves as many new memory blocks as needed at once (one for each item in\n   procs_code) and in the process obtains the new component memory, exploiting\n   the independence of the operations on each item in procs_code in what follows.\n    - Zip the list of new blocks matching the list of procedure code and create a\n      new piecewise map from it.\n    - Zip the list of procedure ids and the list of new block ids and create a\n      partial map from it, refactoring the code handling entry points in the old\n      function.\n   If the new function to reserve a number of blocks does not present new blocks\n   in the same order as the sequential run, slightly different, but isomorphic,\n   maps may be produced. *)\nDefinition reserve_component_blocks p C Cmem procs_code\n  : ComponentMemory.t * NMap code * NMap Block.id :=\n  let is_main_proc comp_id proc_id :=\n      match prog_main p with\n      | true =>\n        (Component.main =? comp_id) && (Procedure.main =? proc_id)\n      | false => false\n      end in\n  (* if P is exported or is the main procedure, add an external entrypoint *)\n  let map_entrypoint '(P, b) :=\n      match getm (prog_interface p) C with\n      | Some Ciface =>\n        if (P \\in Component.export Ciface) || is_main_proc C P then Some (P, b)\n        else None\n      | None => None (* this case shouldn't happen for well formed p *)\n      end in\n  let (Cmem', bs) := ComponentMemoryExtra.reserve_blocks Cmem (length procs_code) in\n  let (procs, code) := (unzip1 procs_code, unzip2 procs_code) in\n  let Cprocs := mkfmap (zip bs code) in\n  let Centrypoints := mkfmap (pmap map_entrypoint (zip procs bs)) in\n  (Cmem', Cprocs, Centrypoints).\n\n(* In the foreseen, controlled use of this function, we always go on the Some\n   branch. For each component C, we read its (initial) memory and use it to\n   construct the initial state of C, recursing after we update its maps. Given\n   identical inputs (component memories, which we have by compositionality of\n   that piece of code) the outputs will be identical. *)\n(* For each pair of component id and component procedures in comps_code, build\n   the triad of program memory memory, component code map and entry point map by\n   folding over them. For each pair, reserve component blocks and update the maps\n   for the current component.\n     As in the function to reserve component blocks, from the calling point,\n   observe that the initial values of the accumulators are, again, the existing\n   memory, partially initialized, and two empty maps; and that, again, comps_proc\n   is an alternative representation of a map, and the procedure on each pair is\n   independent from all others. *)\nFixpoint reserve_procedure_blocks' p acc comps_code\n  : Memory.t * NMap (NMap code) * EntryPoint.t :=\n  let aux acc comps_code :=\n      let '(mem, procs, entrypoints) := acc in\n      let '(C, Cprocs) := comps_code in\n    match getm mem C with\n    | Some Cmem =>\n      let '(Cmem', Cprocs, Centrypoints) :=\n          reserve_component_blocks' p C (Cmem, emptym, emptym) (elementsm Cprocs) in\n      let mem' := setm mem C Cmem' in\n      let procs' := setm procs C Cprocs in\n      let entrypoints' := setm entrypoints C Centrypoints in\n      (mem', procs', entrypoints')\n    | None =>\n      (* this shouldn't happen if memory was initialized before the call *)\n      (* we just skip initialization for this component *)\n      (mem, procs, entrypoints)\n    end\n  in fold_left aux comps_code acc.\n\n(* The simplified function builds a partial map by applying the refactored\n   per-component process over each pair, noting that in some cases (which should\n   never occur!) initialization is skipped, then unpack the parts and repack them\n   in the expected map formats.\n     Note that we are creating a new memory instead of explicitly updating the\n   old memory. Both processes should be equivalent if the map is actually total,\n   as is expected. *)\nFixpoint reserve_procedure_blocks p (mem : Memory.t) comps_code\n  : Memory.t * NMap (NMap code) * EntryPoint.t :=\n  let map_component_memory '(C, Cprocs) :=\n    match getm mem C with\n    | Some Cmem => Some (C, reserve_component_blocks p C Cmem (elementsm Cprocs))\n      (* this shouldn't happen if memory was initialized before the call *)\n      (* we just skip initialization for this component *)\n    | None => None\n    end in\n  let acc := pmap map_component_memory comps_code in\n  let '(comps', mems, procs, eps) := (unzip1 acc, unzip1 (unzip1 (unzip2 acc)),\n                                      unzip2 (unzip1 (unzip2 acc)), unzip2 (unzip2 acc)) in\n  (mkfmap (zip comps' mems), mkfmap (zip comps' procs), mkfmap (zip comps' eps)).\n\n(* RB: TODO: Make sure these functions are only used with initial memories. *)\nDefinition prepare_procedures' (p: program) (mem: Memory.t)\n  : Memory.t * NMap (NMap code) * EntryPoint.t :=\n  reserve_procedure_blocks' p (mem, emptym, emptym) (elementsm (prog_procedures p)).\n\n(* The main function to prepare the procedures of a program from a memory simply\n   calls the helper, now without a trivial accumulator. *)\nDefinition prepare_procedures (p: program) (mem: Memory.t)\n  : Memory.t * NMap (NMap code) * EntryPoint.t :=\n  reserve_procedure_blocks p mem (elementsm (prog_procedures p)).\n\n(* For each component, integrate the (now separate) fetching of its procedures,\n   obtention of its initial component memory and then reserve_component_blocks.\n   The logic of reserve_procedure_blocks is implicit in the map-like nature of\n   its results. (By splitting the definition and proving some intermediate\n   results on the auxiliary, the composition of the parts will be easier.) *)\n(* Definition prepare_procedures_initial_memory_aux (p: program) := *)\n(*   mkfmapf *)\n(*     (fun C => *)\n(*        let Cprocs := odflt emptym ((prog_procedures p) C) in *)\n(*        let Cmem := ComponentMemory.prealloc (odflt emptym ((prog_buffers p) C)) in *)\n(*        reserve_component_blocks p C (Cmem, emptym, emptym) (elementsm Cprocs)) *)\n(*     (domm (prog_interface p)). *)\n\nDefinition prepare_procedures_initial_memory_aux' (p: program) :=\n  mkfmapf\n    (fun C =>\n       let Cprocs := odflt emptym ((prog_procedures p) C) in\n       let Cmem := ComponentMemory.prealloc (odflt emptym ((prog_buffers p) C)) in\n       reserve_component_blocks' p C (Cmem, emptym, emptym) (elementsm Cprocs))\n    (domm (prog_interface p)).\n\n(* As above, replace the old function with the new, and remove accumulators. *)\nDefinition prepare_procedures_initial_memory_aux (p: program) :=\n  mkfmapf\n    (fun C =>\n       let Cprocs := odflt emptym ((prog_procedures p) C) in\n       let Cmem := ComponentMemory.prealloc (odflt emptym ((prog_buffers p) C)) in\n       reserve_component_blocks p C Cmem (elementsm Cprocs))\n    (domm (prog_interface p)).\n\n(* Ultimately, we want this equivalence -- possibly modulo an isomorphism on\n   concrete block id values -- to hold. *)\nTheorem prepare_procedures_initial_memory_aux_equiv (p: program) :\n  prepare_procedures_initial_memory_aux p = (* New version. *)\n  prepare_procedures_initial_memory_aux' p. (* Old version. *)\nProof.\nAdmitted.\n\n(* Decompose the results of the auxiliary call, composed as a whole in the\n   result of reserving component blocks, turning a map of triples into a triple\n   of identically indexed maps *)\nDefinition prepare_procedures_initial_memory (p: program)\n  : Memory.t * NMap (NMap code) * EntryPoint.t :=\n  let m := prepare_procedures_initial_memory_aux p in\n  (mapm (fun x => x.1.1) m, mapm (fun x => x.1.2) m, mapm snd m).\n\n(* We want to ensure something like this:\n     Goal\n       forall p, prepare_procedures_initial_memory p =\n                 prepare_procedures p (prepare_initial_memory p).\n  Possibly assuming the well-formedness of the program. *)\nTheorem prepare_procedures_initial_memory_equiv :\n  forall p,\n    prepare_procedures_initial_memory p =\n    prepare_procedures p (prepare_initial_memory p).\nAdmitted.\n\n(* initialization of a linked program *)\n\nDefinition prepare_procedures_memory (p: program) : Memory.t :=\n  let '(mem, _, _) := prepare_procedures_initial_memory p in\n  mem.\n\n(* RB: TODO: Relocate these simple helpers, review names, etc.\n   For now, trying to keep cruft out of the higher-level proofs. *)\nLemma mapm_eq: forall (T : ordType) (S S' : Type) (m1 m2 : {fmap T -> S}) (f : S -> S'),\n  m1 = m2 -> (mapm f m1) = (mapm f m2).\nProof.\n  intros T S S' m1 m2 f Heq.\n  subst.\n  reflexivity.\nQed.\n\nLemma in_domm_program_link:\n  forall Cid p,\n    Cid \\in domm (prog_interface p) ->\n  forall c,\n    Cid \\in domm (prog_interface (program_link p c)).\nProof.\n  intros Cid p Hin c.\n  simpl.\n  rewrite mem_domm.\n  rewrite mem_domm in Hin.\n  rewrite unionmE.\n  rewrite Hin.\n  assumption.\nQed.\n\nLemma domm_partition_program_link_in_neither p c :\n  well_formed_program p ->\n  well_formed_program c ->\n  closed_program (program_link p c) ->\n  Component.main \\notin domm (prog_interface p) ->\n  Component.main \\notin domm (prog_interface c) ->\n  False.\nProof.\n  intros [_ _ _ _ _ _ [_ Hmainp]] [_ _ _ _ _ _ [_ Hmainc]]\n         [_ [main [Hmain [_ _]]]] Hmainp' Hmainc'.\n  destruct (prog_main p) as [|] eqn:Hcasep.\n  - specialize (Hmainp is_true_true).\n    rewrite Hmainp in Hmainp'.\n    discriminate.\n  - destruct (prog_main c) as [|] eqn:Hcasec.\n    +  specialize (Hmainc is_true_true).\n       rewrite Hmainc in Hmainc'.\n       discriminate.\n    + simpl in Hmain.\n      rewrite Hcasep Hcasec in Hmain.\n      discriminate.\nQed.\n\nLemma fsetid (T : ordType) (s: seq.seq T) :\n  fset (fset s) = fset s.\nProof. by apply /eq_fset => x; rewrite in_fset. Qed.\n\n(* First, prove domain preservation for all of the (already existing, plus\n   recent improvements) initialization code. *)\nLemma domm_prepare_procedures_initial_memory_aux: forall p,\n  (*well_formed_program p ->*)\n  domm (prepare_procedures_initial_memory_aux p) = domm (prog_interface p).\nProof.\n  intros p.\n  unfold prepare_procedures_initial_memory_aux.\n  rewrite domm_mkfmapf.\n  apply fsetid.\nQed.\n\n(* FG : maybe relocate this in extructures? (when rewritten in proper SSReflect) *)\nLemma fdisjoint_partition_notinboth (T: ordType) (s1 s2 : {fset T}) :\n  fdisjoint s1 s2 ->\n  forall x,\n    x \\in s2 ->\n    x \\in s1 ->\n    False.\nProof.\n  unfold fdisjoint. move => Hinter x Hs2 Hs1.\n  have H' : x \\in (s1 :&: s2)%fset by rewrite in_fsetI Hs1 Hs2.\n  have H'' : (s1 :&: s2)%fset = fset0 by apply /eqP.\n  rewrite H'' in H'. inversion H'.\nQed.\n\n(* Better name, maybe ? *)\n(* keeping it generic over program/context *)\nLemma prog_link_procedures_unionm :\n  forall p1 p2 Cid,\n    well_formed_program p1 ->\n    (* well_formed_program p2 -> *)\n    (Cid \\in domm (prog_interface p1)) = true ->\n    (Cid \\in domm (prog_interface p2)) = false -> (* not used, to remove  or keep as sanity check ? *)\n    (prog_procedures (program_link p1 p2)) Cid = (prog_procedures p1) Cid.\nProof.\n  intros p1 p2 Cid Hwfp Hp _.\n  rewrite unionmE. rewrite <- mem_domm. inversion Hwfp as [? Hproc _ _ _ _ _]. (* if no binding of 1st hypothesis : anomaly : \"make_elim_branch_assumptions\" *)\n  rewrite Hproc in Hp. rewrite Hp. reflexivity.\nQed.\n\n(* maybe write a tactic that does the core except the inversion ... ? *)\n(* or suppress the prog_smth part and keep it generic for all types of program_link ? *)\nLemma prog_link_buffers_unionm :\n  forall p1 p2 Cid,\n    well_formed_program p1 ->\n    (* well_formed_program p2 -> *)\n    (Cid \\in domm (prog_interface p1)) = true ->\n    (Cid \\in domm (prog_interface p2)) = false -> (* same *)\n    (prog_buffers (program_link p1 p2)) Cid = (prog_buffers p1) Cid.\nProof.\n  intros p1 p2 Cid Hwfp Hp _. simpl.\n  rewrite unionmE. rewrite <- mem_domm. inversion Hwfp as [? _ _ _ Hbuf _ _]. (* if no binding of 1st hypothesis : anomaly : \"make_elim_branch_assumptions\" *)\n  rewrite Hbuf in Hp. rewrite Hp. reflexivity.\nQed.\n\n(* RB: TODO: Simplify hypotheses if possible. *)\nLemma prepare_procedures_initial_memory_aux_after_linking:\n  forall p c,\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n    linkable_mains p c ->\n    prepare_procedures_initial_memory_aux (program_link p c) =\n    unionm (prepare_procedures_initial_memory_aux p)\n           (prepare_procedures_initial_memory_aux c).\nProof.\n  intros p c Hwfp Hwfc Hlinkable Hmains.\n  unfold prepare_procedures_initial_memory_aux.\n  apply eq_fmap. intros Cid.\n  (* Case analysis on component provenance after some common preprocessing. *)\n  destruct (Cid \\in domm (prog_interface p)) eqn:Hp;\n    destruct (Cid \\in domm (prog_interface c)) eqn:Hc.\n  - (* Contra. *)\n    inversion Hlinkable as [_ Hdisjoint].\n    have Hcontra : False by apply (fdisjoint_partition_notinboth Hdisjoint Hc Hp).\n    inversion Hcontra.\n  - rewrite unionmE.\n    rewrite !mkfmapfE.\n    rewrite Hp Hc.\n    have Hpc : Cid \\in domm (prog_interface (program_link p c))\n      by apply in_domm_program_link.\n    rewrite Hpc.\n    have Helts : (elementsm (odflt emptym ((prog_procedures (program_link p c)) Cid))) =\n            (elementsm (odflt emptym ((prog_procedures p) Cid)))\n      by rewrite (prog_link_procedures_unionm Hwfp Hp Hc).\n    rewrite Helts.\n    have Hprealloc : ComponentMemory.prealloc (odflt emptym ((prog_buffers (program_link p c)) Cid)) =\n            ComponentMemory.prealloc (odflt emptym ((prog_buffers p) Cid))\n      by rewrite (prog_link_buffers_unionm Hwfp Hp Hc).\n    rewrite Hprealloc.\n    simpl.\n    unfold reserve_component_blocks.\n    rewrite unionmE.\n    have [Cid_int Hp']: (exists x, (prog_interface p) Cid = Some x)\n      by  apply /dommP.\n    rewrite Hp'.\n    simpl.\n    destruct (prog_main p) as [|] eqn:Hmainp;\n      destruct (prog_main c) as [|] eqn:Hmainc.\n    + easy. (* Contra. *)\n    + reflexivity.\n    + destruct Cid as [| n].\n      * (* Contra. *)\n        inversion Hwfp as [_ _ _ _ _ _ Hmain_compp].\n        (* specialize (Hmain_compp Hmainp). *)\n        (* have Hp'' : (prog_interface p) 0 = None by apply /dommPn. *)\n        (* rewrite Hp'' in Hp'. *)\n        apply proj1 in Hmain_compp.\n        specialize (Hmain_compp Hp).\n        rewrite Hmainp in Hmain_compp.\n        discriminate.\n      * reflexivity.\n    + reflexivity. (* Easy case. *)\n  - (* RB: TODO: Refactor symmetric case to last one. *)\n    rewrite unionmE.\n    rewrite !mkfmapfE.\n    rewrite Hp Hc.\n    have Hpc : Cid \\in domm (prog_interface (program_link p c))\n      by rewrite (program_linkC Hwfp Hwfc Hlinkable) ;\n      apply in_domm_program_link.\n    rewrite Hpc.\n    have Helts: (elementsm (odflt emptym ((prog_procedures (program_link p c)) Cid))) =\n            (elementsm (odflt emptym ((prog_procedures c) Cid)))\n      by rewrite (program_linkC Hwfp Hwfc Hlinkable) (prog_link_procedures_unionm Hwfc Hc Hp).\n    rewrite Helts.\n    have Hprealloc : ComponentMemory.prealloc (odflt emptym ((prog_buffers (program_link p c)) Cid)) =\n            ComponentMemory.prealloc (odflt emptym ((prog_buffers c) Cid))\n      by rewrite (program_linkC Hwfp Hwfc Hlinkable) (prog_link_buffers_unionm Hwfc Hc Hp).\n    rewrite Hprealloc.\n    simpl.\n    unfold reserve_component_blocks.\n    rewrite unionmE.\n    have Hp': (prog_interface p) Cid = None\n      by apply /dommPn; rewrite Hp.\n    rewrite Hp'.\n    have [Cid_int Hc'] : exists x, (prog_interface c) Cid = Some x\n      by apply /dommP.\n    rewrite Hc'.\n    destruct (prog_main p) as [|] eqn:Hmainp;\n      destruct (prog_main c) as [|] eqn:Hmainc.\n    + (* Contra. *)\n      unfold linkable_mains in Hmains.\n      rewrite Hmainp Hmainc in Hmains.\n      discriminate.\n    + simpl. rewrite Hmainp Hmainc.\n      destruct Cid as [| n].\n      * (* Contra, *)\n        inversion Hwfc as [_ _ _ _ _ _ Hmain_compc].\n        (* specialize (Hmain_compc Hmainc). *)\n        (* have Hc'' : (prog_interface c) 0 = None by apply /dommPn. *)\n        (* rewrite Hc'' in Hc'. *)\n        apply proj1 in Hmain_compc.\n        specialize (Hmain_compc Hc).\n        rewrite Hmainc in Hmain_compc.\n        discriminate.\n      * reflexivity.\n    + simpl. rewrite Hmainp Hmainc. reflexivity.\n    + simpl. rewrite Hmainp Hmainc. reflexivity.\n  - (* in neither, pretty immediate *)\n    by rewrite unionmE !mkfmapfE domm_union in_fsetU Hp Hc.\nQed.\n\n(* Now it's easy to extend this to the parts of the final result. *)\nLemma domm_prepare_procedures_memory: forall p,\n  domm (prepare_procedures_memory p) = domm (prog_interface p).\nProof.\n  intros p.\n  unfold prepare_procedures_memory, prepare_procedures_initial_memory.\n  rewrite domm_map.\n  rewrite domm_prepare_procedures_initial_memory_aux.\n  reflexivity.\nQed.\n\nTheorem prepare_procedures_memory_after_linking:\n  forall p c,\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n    linkable_mains p c ->\n    prepare_procedures_memory (program_link p c) =\n    unionm (prepare_procedures_memory p) (prepare_procedures_memory c).\nProof.\n  intros p c Hwfp Hwfc Hlinkable Hmains.\n  unfold prepare_procedures_memory,\n         prepare_procedures_initial_memory, prepare_procedures_initial_memory_aux.\n  rewrite <- mapm_unionm. apply mapm_eq.\n  apply prepare_procedures_initial_memory_aux_after_linking; assumption.\nQed.\n\n(* Search _ prepare_procedures_memory. *)\n(* Search _ PS.to_partial_memory unionm. *)\nLemma prepare_procedures_memory_left p c :\n  linkable (prog_interface p) (prog_interface c) ->\n  to_partial_memory\n    (unionm (prepare_procedures_memory p) (prepare_procedures_memory c))\n    (domm (prog_interface c)) =\n  prepare_procedures_memory p.\nProof.\n  intros [_ Hdisjoint].\n  unfold to_partial_memory, merge_memories.\n  rewrite <- domm_prepare_procedures_memory,\n         -> filterm_union,\n         -> fdisjoint_filterm_full,\n         -> fdisjoint_filterm_empty, -> unionm0;\n    first reflexivity;\n    try rewrite -> !domm_prepare_procedures_memory; congruence.\nQed.\n\nLemma prepare_procedures_memory_right p c :\n  linkable (prog_interface p) (prog_interface c) ->\n  to_partial_memory\n    (unionm (prepare_procedures_memory p) (prepare_procedures_memory c))\n    (domm (prog_interface p)) =\n  prepare_procedures_memory c.\nProof.\n  intros Hlinkable.\n  rewrite unionmC; try assumption.\n  apply prepare_procedures_memory_left with (c := p) (p := c).\n  now apply linkable_sym.\n  inversion Hlinkable.\n  now rewrite !domm_prepare_procedures_memory.\nQed.\n\nDefinition prepare_procedures_procs (p: program) : NMap (NMap code) :=\n  let '(_, procs, _) := prepare_procedures_initial_memory p in\n  procs.\n\nTheorem prepare_procedures_procs_after_linking:\n  forall p c,\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n    linkable_mains p c ->\n    prepare_procedures_procs (program_link p c) =\n    unionm (prepare_procedures_procs p) (prepare_procedures_procs c).\nProof.\n  intros p c Hwfp Hwfc Hlinkable Hmains.\n  unfold prepare_procedures_procs,\n         prepare_procedures_initial_memory, prepare_procedures_initial_memory_aux.\n  rewrite <- mapm_unionm. apply mapm_eq.\n  apply prepare_procedures_initial_memory_aux_after_linking; assumption.\nQed.\n\nDefinition prepare_procedures_entrypoints (p: program) : EntryPoint.t :=\n  let '(_, _, entrypoints) := prepare_procedures_initial_memory p in\n  entrypoints.\n\nLemma domm_prepare_procedures_entrypoints: forall p,\n  domm (prepare_procedures_entrypoints p) = domm (prog_interface p).\nProof.\n  intros p.\n  unfold prepare_procedures_entrypoints, prepare_procedures_initial_memory.\n  rewrite domm_map.\n  rewrite domm_prepare_procedures_initial_memory_aux.\n  reflexivity.\nQed.\n\nTheorem prepare_procedures_entrypoints_after_linking:\n  forall p c,\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n    linkable_mains p c ->\n    prepare_procedures_entrypoints (program_link p c) =\n    unionm (prepare_procedures_entrypoints p)\n           (prepare_procedures_entrypoints c).\nProof.\n  intros p c Hwfp Hwfc Hlinkable Hmains.\n  unfold prepare_procedures_entrypoints,\n         prepare_procedures_initial_memory, prepare_procedures_initial_memory_aux.\n  rewrite <- mapm_unionm. apply mapm_eq.\n  apply prepare_procedures_initial_memory_aux_after_linking; assumption.\nQed.\n\nCorollary prepare_procedures_initial_memory_after_linking:\n  forall p c,\n    well_formed_program p ->\n    well_formed_program c ->\n    linkable (prog_interface p) (prog_interface c) ->\n    linkable_mains p c ->\n    prepare_procedures_initial_memory (program_link p c) =\n    (unionm (prepare_procedures_memory p)\n            (prepare_procedures_memory c),\n     unionm (prepare_procedures_procs p)\n            (prepare_procedures_procs c),\n     unionm (prepare_procedures_entrypoints p)\n            (prepare_procedures_entrypoints c)).\nProof.\n  intros p c Hwfp Hwfc Hlinkable Hmains.\n  rewrite <- prepare_procedures_memory_after_linking; try assumption.\n  rewrite <- prepare_procedures_procs_after_linking; try assumption.\n  rewrite <- prepare_procedures_entrypoints_after_linking; try assumption.\n  reflexivity.\nQed.\n\n(* RB: Slight \"misnomer\" because of the presence of matching_mains.\n   Closely connected to linkable, but not exactly the same at this\n   level. Is there a benefit to combining these two in a definition? *)\nLemma interface_preserves_closedness_r :\n  forall p1 p2 p2',\n    well_formed_program p1 ->\n    well_formed_program p2' ->\n    prog_interface p2 = prog_interface p2' ->\n    linkable (prog_interface p1) (prog_interface p2) ->\n    closed_program (program_link p1 p2) ->\n    linkable_mains p1 p2 ->\n    matching_mains p2 p2' ->\n    closed_program (program_link p1 p2').\nProof.\n  intros p1 p2 p2'\n         Hwf1 Hwf2' Hsame_int Hlinkable\n         [Hclosed [mainP [Hmain [Hprocs]]]]\n         Hlinkable_mains Hmatching_mains.\n  constructor.\n  - simpl in Hclosed.\n    rewrite Hsame_int in Hclosed.\n    apply Hclosed.\n  - destruct (prog_main p1) as [|] eqn:Hmain1;\n      destruct (prog_main p2) as [|] eqn:Hmain2.\n    + unfold linkable_mains in Hlinkable_mains.\n      rewrite Hmain1 Hmain2 in Hlinkable_mains.\n      discriminate.\n    + (* main is in p1.*)\n      (* unfold program_link in Hmain. *)\n      (* rewrite Hmain1 in Hmain. *)\n      (* simpl in Hmain. *)\n      (* inversion Hmain; subst mainP; clear Hmain. *)\n      (* Likewise main_procs (used only in second sub-goal). *)\n      unfold program_link in Hprocs; simpl in Hprocs.\n      destruct (wfprog_main_existence Hwf1 Hmain1)\n        as [main_procs1 [Hmain_procs1 Hin1]].\n      rewrite unionmE Hmain_procs1 in Hprocs.\n      (* inversion Hprocs; subst main_procs; clear Hprocs. *)\n      (* Instantiate and solve. *)\n      exists main_procs1. split; [| split].\n      * unfold program_link.\n        rewrite Hmain1.\n        reflexivity.\n      * unfold program_link; simpl.\n        rewrite unionmE Hmain_procs1.\n        reflexivity.\n      * assumption.\n    + (* main is in p2'. *)\n      destruct (prog_main p2') as [|] eqn:Hmain2';\n      last (destruct Hmatching_mains as [Hmatching_mains _];\n            rewrite Hmatching_mains in Hmain2';\n            last assumption;\n            inversion Hmain2').\n      (* Likewise main_procs (used only in second sub-goal). *)\n      destruct (wfprog_main_existence Hwf2' Hmain2')\n        as [main_procs2' [Hmain_procs2' Hin2']].\n      exists main_procs2'. split; [| split].\n      * unfold program_link.\n        rewrite Hmain1 Hmain2'.\n        reflexivity.\n      * unfold program_link; simpl.\n        inversion Hlinkable as [_ Hdisjoint].\n        inversion Hwf1 as [_ Hdomm1 _ _ _ _].\n        inversion Hwf2' as [_ Hdomm2' _ _ _ _].\n        rewrite Hsame_int Hdomm1 Hdomm2' in Hdisjoint.\n        rewrite (unionmC Hdisjoint) unionmE Hmain_procs2'.\n        reflexivity.\n      * assumption.\n    + simpl in Hmain.\n      rewrite Hmain1 in Hmain.\n      rewrite Hmain2 in Hmain.\n      discriminate.\nQed.\n\n(* RB: TODO: Revisit uses of matching_mains as hypotheses and see when they can\n   be removed due to their being derivable from this result. *)\nLemma interface_implies_matching_mains :\n  forall p1 p2,\n    well_formed_program p1 ->\n    well_formed_program p2 ->\n    prog_interface p1 = prog_interface p2 ->\n    matching_mains p1 p2.\nProof.\n  intros p1 p2 Hwf1 Hwf2 Hiface.\n  unfold matching_mains.\n  destruct (prog_main p1) as [|] eqn:Hcase1;\n    destruct (prog_main p2) as [|] eqn:Hcase2.\n  - easy.\n  - split; last easy.\n    exfalso.\n    inversion Hwf2 as [_ _ _ _ _ _ [Hmain2' _]].\n    inversion Hwf1 as [_ _ _ _ _ _ [_ Hmain1']].\n    rewrite Hcase1 in Hmain1'. specialize (Hmain1' is_true_true).\n    rewrite -> Hcase2, <- Hiface in Hmain2'. apply Hmain2' in  Hmain1'.\n    discriminate.\n  - split; first easy.\n    exfalso.\n    inversion Hwf1 as [_ _ _ _ _ _ [Hmain1' _]].\n    inversion Hwf2 as [_ _ _ _ _ _ [_ Hmain2']].\n    rewrite Hcase2 in Hmain2'. specialize (Hmain2' is_true_true).\n    rewrite -> Hcase1, -> Hiface in Hmain1'. apply Hmain1' in  Hmain2'.\n    discriminate.\n  - easy.\nQed.\n\nLemma closed_interface_union : forall p1 p2,\n  closed_interface (prog_interface (program_link p1 p2)) =\n  closed_interface (unionm (prog_interface p1) (prog_interface p2)).\nProof.\n  easy.\nQed.\n\nLemma compose_mergeable_interfaces : forall p1 p2,\n  linkable (prog_interface p1) (prog_interface p2) ->\n  closed_program (program_link p1 p2) ->\n  mergeable_interfaces (prog_interface p1) (prog_interface p2).\nProof.\n  intros p1 p2 Hlinkable Hclosed.\n  split.\n  - assumption.\n  - inversion Hclosed as [Hclosed_iface _].\n    rewrite closed_interface_union in Hclosed_iface.\n    assumption.\nQed.\n\nEnd Intermediate.\n", "meta": {"author": "secure-compilation", "repo": "when-good-components-go-bad", "sha": "7bef0fa18780f1e9699abcdadd61e15bf3aba95d", "save_path": "github-repos/coq/secure-compilation-when-good-components-go-bad", "path": "github-repos/coq/secure-compilation-when-good-components-go-bad/when-good-components-go-bad-7bef0fa18780f1e9699abcdadd61e15bf3aba95d/Intermediate/Machine.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.20076527063350746}}
{"text": "Require Import String.\nRequire Import Bool.\n\nRequire Import core.utils.Utils.\nRequire Import core.Model.\nRequire Import core.TransformationConfiguration.\nRequire Import core.SyntaxCertification.\nRequire Import core.Engine.\nRequire Import core.Semantics.\nRequire Import core.EqDec.\nRequire Import core.Metamodel.\nRequire Import core.Certification.\nRequire Import core.Syntax.\nRequire Import core.modeling.ModelingEngine.\nRequire Import core.modeling.ModelingMetamodel.\nRequire Import core.modeling.ConcreteExpressions.\nRequire Import core.modeling.ModelingSemantics.\nRequire Import core.modeling.ModelingTransformationConfiguration.\n\n\nSection ModelingCertification.\n\n(* Context {tc: TransformationConfiguration} {mtc: ModelingTransformationConfiguration tc}. *) \n\n(** * Resolve *)\n\n(* Theorem tr_resolveAll_in:\n  forall (tls: list TraceLink) (sm: SourceModel) (name: string)\n    (type: TargetModelClass) (sps: list(list SourceModelElement)),\n    resolveAll tls sm name type sps = resolveAllIter tls sm name type sps 0.\nProof.\n  crush.\nQed. *)\n\nTheorem tr_resolveAllIter_in:\n  forall \n     {tc: TransformationConfiguration} {mtc: ModelingTransformationConfiguration tc}\n    (tls: list TraceLink) (sm: SourceModel) (name: string)\n    (type: TargetModelClass) (sps: list(list SourceModelElement)) (iter: nat)\n    (te: denoteModelClass type),\n    (exists tes: list (denoteModelClass type),\n        resolveAllIter tls sm name type sps iter = Some tes /\\ In te tes) <->\n    (exists (sp: list SourceModelElement),\n        In sp sps /\\\n        resolveIter tls sm name type sp iter = Some te).\nProof.\n  intros.\n      intros.\n  split.\n  - intros.\n    destruct H. destruct H.\n    unfold resolveAllIter in H.\n    inversion H.\n    rewrite <- H2 in H0.\n    apply in_flat_map in H0.\n    destruct H0. destruct H0.\n    destruct ((toModelClass type x0)) eqn: type_cast_ca; simpl in H1.\n    + destruct H1.\n      ++ apply in_flat_map in H0.\n         destruct H0. destruct H0.\n         exists x1.\n         split.\n         * exact H0.\n         * unfold resolveIter.\n           destruct (Semantics.resolveIter tls sm name x1 iter); crush.\n      ++ contradiction.\n    + contradiction.\n  - intro.\n    destruct H. destruct H.\n    destruct (resolveAllIter tls sm name type sps iter) eqn: resolveAll.\n    --  exists l. split. auto.\n        unfold resolveAllIter in resolveAll.\n        inversion resolveAll.\n        apply in_flat_map.\n        unfold resolveIter in H0.\n        destruct (Semantics.resolveIter tls sm name x iter) eqn: resolve_ca; simpl in H0.\n        * exists t. \n          split.\n          ** apply in_flat_map.\n             exists x.\n             split.\n             *** auto.\n             *** rewrite resolve_ca. simpl. auto.\n          ** rewrite H0. simpl. left. auto. \n        * simpl in H0. inversion H0.\n    --  unfold resolveAllIter in resolveAll.\n        crush.\nQed.\n\n(* Theorem tr_resolve_in:\n  forall (tls: list TraceLink) (sm: SourceModel) (name: string)\n    (type: TargetModelClass) (sp: list SourceModelElement),\n    resolve tls sm name type sp = resolveIter tls sm name type sp 0.\nProof.\n  crush.\nQed. *)\n\n(* this one direction, the other one is not true since exists cannot gurantee uniqueness in find *)\nTheorem tr_resolveIter_leaf:\n  forall \n     {tc: TransformationConfiguration} {mtc: ModelingTransformationConfiguration tc}\n    (tls:list TraceLink) (sm : SourceModel) (name: string) (type: TargetModelClass)\n    (sp: list SourceModelElement) (iter: nat) (x: denoteModelClass type),\n    resolveIter tls sm name type sp iter = return x ->\n      (exists (tl : TraceLink),\n        In tl tls /\\\n        Is_true (list_beq SourceModelElement SourceElement_eqb (TraceLink_getSourcePattern tl) sp) /\\\n        ((TraceLink_getIterator tl) = iter) /\\ \n        ((TraceLink_getName tl) = name)%string /\\\n        (toModelClass type (TraceLink_getTargetElement tl) = Some x)). \nProof.\nintros.\nunfold resolveIter in H.\ndestruct (Semantics.resolveIter tls sm name sp iter) eqn: resolve_ca.\n- simpl in H.\n  unfold Semantics.resolveIter in resolve_ca.\n  destruct ( find\n               (fun tl : TraceLink =>\n                Semantics.list_beq SourceModelElement SourceElement_eqb\n                  (TraceLink_getSourcePattern tl) sp &&\n                (TraceLink_getIterator tl =? iter) &&\n                (TraceLink_getName tl =? name)%string)) eqn: find_ca.\n  -- apply find_some in find_ca.\n     destruct find_ca.\n     exists t0.\n     symmetry in H1.\n     apply andb_true_eq in H1.\n     destruct H1.\n     apply andb_true_eq in H1.\n     destruct H1.\n     crush.\n     --- apply beq_nat_true. crush.\n     --- apply String.eqb_eq. crush.\n  -- inversion resolve_ca.\n- simpl in H. inversion H.\nQed.\n\n\n(* Set Typeclasses Debug Verbosity 2. *)\n\n\nContext {SourceModelElement SourceModelLink: Type}.\nContext {eqdec_sme: EqDec SourceModelElement}. (* need decidable equality on source model elements *)\nContext {TargetModelElement TargetModelLink: Type}.\nContext {eqdec_tme: EqDec TargetModelElement}. (* need decidable equality on source model elements *)\n\nInstance smm : Metamodel := {\n  ModelElement := SourceModelElement;\n  ModelLink := SourceModelLink;\n  elements_eqdec := eqdec_sme;\n}.\n\nInstance tmm : Metamodel := {\n  ModelElement := TargetModelElement;\n  ModelLink := TargetModelLink;\n  elements_eqdec := eqdec_tme;\n}.\n\nInstance tc : TransformationConfiguration := {\n  SourceMetamodel := smm;\n  TargetMetamodel := tmm;\n}.\n\nContext {SourceModelClass SourceModelReference: Type}.\nContext {TargetModelClass TargetModelReference: Type}.\n\nContext {denoteSourceElemSubType : SourceModelClass -> Set}.\nContext {toSourceElemSubType: forall (t: SourceModelClass), SourceModelElement -> option (denoteSourceElemSubType t)}.\nContext {toSourceElemSumType: forall (t: SourceModelClass), (denoteSourceElemSubType t) -> SourceModelElement}.\n\nContext {denoteSourceLinkSubType : SourceModelReference -> Set}.\nContext {toSourceLinkSubType: forall (t: SourceModelReference), SourceModelLink -> option (denoteSourceLinkSubType t)}.\nContext {toSourceLinkSumType: forall (t: SourceModelReference), (denoteSourceLinkSubType t) -> SourceModelLink}.\n\nContext {denoteTargetElemSubType : TargetModelClass -> Set}.\nContext {toTargetElemSubType: forall (t: TargetModelClass), TargetModelElement -> option (denoteTargetElemSubType t)}.\nContext {toTargetElemSumType: forall (t: TargetModelClass), (denoteTargetElemSubType t) -> TargetModelElement}.\n\nContext {denoteTargetLinkSubType : TargetModelReference -> Set}.\nContext {toTargetLinkSubType: forall (t: TargetModelReference), TargetModelLink -> option (denoteTargetLinkSubType t)}.\nContext {toTargetLinkSumType: forall (t: TargetModelReference), (denoteTargetLinkSubType t) -> TargetModelLink}.\n\n\nInstance SourceElements : Sum SourceModelElement SourceModelClass := {\ndenoteSubType := denoteSourceElemSubType;\ntoSubType := toSourceElemSubType;\ntoSumType := toSourceElemSumType;\n}.\n\nInstance SourceLinks : Sum SourceModelLink SourceModelReference := {\ndenoteSubType := denoteSourceLinkSubType;\ntoSubType := toSourceLinkSubType;\ntoSumType := toSourceLinkSumType;\n}.\n\nInstance TargetElements : Sum TargetModelElement TargetModelClass:= {\ndenoteSubType := denoteTargetElemSubType;\ntoSubType := toTargetElemSubType;\ntoSumType := toTargetElemSumType;\n}.\n\nInstance TargetLinks : Sum TargetModelLink TargetModelReference:= {\ndenoteSubType := denoteTargetLinkSubType;\ntoSubType := toTargetLinkSubType;\ntoSumType := toTargetLinkSumType;\n}.\n\nInstance msmm: ModelingMetamodel SourceMetamodel:= {\n  ModelClass := SourceModelClass;\n  ModelReference := SourceModelReference;\n  elements := SourceElements;\n  links := SourceLinks;\n}.\n\nInstance mtmm: ModelingMetamodel TargetMetamodel := {\n  ModelClass := TargetModelClass;\n  ModelReference := TargetModelReference;\n  elements := TargetElements;\n  links := TargetLinks;\n}.\n\nInstance mtc : ModelingTransformationConfiguration tc := {\n  smm := msmm;\n  tmm := mtmm;\n}.\n\nInstance ModelingCoqTLEngine : @ModelingTransformationEngine _ _ _ CoqTLEngine.\nProof.\neexists.\nexact tr_resolveAllIter_in.\nexact tr_resolveIter_leaf.\nQed.\n\nEnd ModelingCertification.", "meta": {"author": "atlanmod", "repo": "coqtl", "sha": "5daf5d915b66328ae5ec48f55c44731372563c87", "save_path": "github-repos/coq/atlanmod-coqtl", "path": "github-repos/coq/atlanmod-coqtl/coqtl-5daf5d915b66328ae5ec48f55c44731372563c87/core/modeling/ModelingCertification.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3522017820478896, "lm_q1q2_score": 0.20070311933278095}}
{"text": "(****************************************************************************)\n(* Copyright 2020 The Project Oak Authors                                   *)\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\nFrom Coq Require Import NArith PeanoNat Strings.String Lists.List.\nFrom Cava Require Import Arrow.ArrowExport BitArithmetic VectorUtils.\n\nRequire Import Aes.Pkg Aes.MixColumns Aes.Sbox Aes.SubBytes Aes.ShiftRows\n        Aes.CipherRound Aes.KeyExpand Aes.AesTest.\n\nImport ListNotations.\nImport KappaNotation.\nOpen Scope kappa_scope.\n\nDefinition key_expand_and_round (sbox_impl: SboxImpl) :=\n  <[ fun \"key_expand_and_round\"\n    (op_i: _ Bit)\n    (round: _ (Vector Bit 4))\n    (data_i: _ (Vector (Vector (Vector Bit 8) 4) 4))\n    (key: _ (Vector (Vector (Vector Bit 8) 4) 8))\n    (step_i: _ Bit)\n    (clear_i: _ Bit)\n    : << Vector (Vector (Vector Bit 8) 4) 4 (* data *)\n      ,  Vector (Vector (Vector Bit 8) 4) 8 (* key *)\n      >> =>\n\n    let key_words = !aes_transpose\n      (if op_i == !CIPH_FWD\n      then key[:7:4]\n      else key[:3:0])\n      in\n    let round_key =\n      if op_i == !CIPH_FWD\n      then key_words\n      else !aes_mix_columns !CIPH_INV key_words in\n\n    let data_o =\n      !(cipher_round_combined sbox_impl) op_i data_i round_key (round == #0) (round == #14) in\n\n    let new_key = !(aes_key_expand sbox_impl) op_i step_i clear_i round key in\n    (data_o, new_key)\n  ]>.\n\nDefinition aes_cipher_core_mealy\n  (sbox_impl: SboxImpl) :=\n  <[ fun \"aes_cipher_core_mealy\" state input\n    : <<\n       (* state *)\n       << Bit (* op_s *)\n       , Vector (Vector (Vector Bit 8) 4) 4 (*data_s*)\n       , Vector (Vector (Vector Bit 8) 4) 8 (*key_s *)\n       , Vector Bit 4 (* next round *)\n       >>,\n\n       (* output *)\n       << Bit (* valid output *)\n       , Bit (* Accept data *)\n       , Bit (* Accept key *)\n       , Vector (Vector (Vector Bit 8) 4) 4 (*data_o*)\n       >>\n      >> =>\n\n    let '(op_s, data_s, key_s, current_round) = state in\n    let '(op_i, data_i, data_valid, key_i, key_valid, data_o_ready) = input in\n\n    let step = false' in\n    let clear = false' in\n\n    let round_inc = current_round +% #1 in\n\n    let done = (current_round == #14) || (current_round == #15) in\n    let reset = (current_round == #15) && data_o_ready in\n\n    let '(data_n, key_n) =\n      if current_round == #15\n      then (data_s, key_s)\n      else !(key_expand_and_round sbox_impl)\n        op_i current_round data_s key_s step clear in\n\n    let next_round =\n      if done then\n        if reset then #0\n        else #15\n      else round_inc in\n\n    ( ( op_s\n      , if done && data_valid then data_i else data_n\n      , if done && key_valid then key_i else key_n\n      , next_round )\n    , ( (current_round == #15)\n      , done\n      , done\n      , data_i )\n    )\n\n  ]>.\n\n(* TODO(#357): op_i needs valid flag and to be respected *)\nDefinition aes_cipher_core\n  (sbox_impl: SboxImpl) :=\n  <[ fun \"aes_cipher_core\"\n    (op_i: _ Bit)\n    (data_i: _ (Vector (Vector (Vector Bit 8) 4) 4))\n    (data_valid: _ Bit)\n    (key_i: _ (Vector (Vector (Vector Bit 8) 4) 8))\n    (key_valid: _ Bit)\n    (data_o_ready: _ Bit)\n\n    : <<\n         Bit (* valid output *)\n       , Bit (* Accept data *)\n       , Bit (* Accept key *)\n       , Vector (Vector (Vector Bit 8) 4) 4 (*data_o*)\n       >> =>\n\n    !(mealy_machine (aes_cipher_core_mealy sbox_impl))\n      (op_i, data_i, data_valid, key_i, key_valid, data_o_ready)\n  ]>.\n\nDefinition test_input : list\n  (bool *\n    (denote_kind << Vector (Vector (Vector Bit 8) 4) 4 >> * (bool *\n    (denote_kind << Vector (Vector (Vector Bit 8) 4) 8 >> * (bool * bool))))) :=\n  [\n    (false,\n      (@reshape _ 4 4 (reshape test_data), (false,\n      (@reshape _ 8 4 (reshape test_key), (false, false )))))\n  ].\n\n(*\n(* TODO(#357): evaluate *)\nEval vm_compute in\n  (interp_sequential (((aes_cipher_core SboxLut) : Kappa _ _) _) test_input).\n*)\n\n", "meta": {"author": "project-oak", "repo": "silveroak", "sha": "cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e", "save_path": "github-repos/coq/project-oak-silveroak", "path": "github-repos/coq/project-oak-silveroak/silveroak-cccfdb4e19c5906256d2ed4487bf1a0aa2fab99e/investigations/Arrow/aes/CipherCore.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.20064269775706875}}
{"text": "Require Import ContractSem.\nRequire Import ConcreteWord.\nRequire Import ZArith.\n\n\nModule ConcreteSem := (ContractSem.Make ConcreteWord.ConcreteWord).\nInclude ConcreteSem.\n\n\nDefinition example2_program : program :=\n  PUSH1 (word_of_N 0) ::\n        SLOAD ::\n        DUP1 ::\n        PUSH1 (word_of_N 2) ::\n        JUMPI ::\n        PUSH1 (word_of_N 1) ::\n        ADD ::\n        PUSH1 (word_of_N 0) ::\n        SSTORE ::\n        PUSH1 (word_of_N 0) ::\n        (* TODO: change some of these arguments to value, address *)\n        PUSH1 (word_of_N 0) ::\n        PUSH1 (word_of_N 0) ::\n        PUSH1 (word_of_N 0) ::\n        PUSH1 (word_of_N 0) ::\n        PUSH1 (word_of_N 0) ::\n        PUSH1 (word_of_N 0) ::\n        CALL ::\n        ISZERO ::\n        PUSH1 (word_of_N 0) ::\n        JUMPI ::\n        PUSH1 (word_of_N 0) ::\n        PUSH1 (word_of_N 0) ::\n        SSTORE ::\n        STOP ::\n        nil.\n\nVariable example2_address : address.\n\nDefinition example2_depth_n_state  (n : word) (st : account_state) :=\n  (n = 0%Z /\\\n   st.(account_address) = example2_address /\\\n   is_true (ST.equal word_eq (st.(account_storage)) empty_storage) /\\\n   st.(account_code) = example2_program /\\\n   st.(account_ongoing_calls) = nil ) \\/\n  (n = 1%Z /\\\n   st.(account_code) = example2_program /\\\n   storage_load 0%Z (account_storage st) = 1%Z /\\\n   st.(account_address) = example2_address /\\\n   is_true (ST.equal word_eq (storage_store 0%Z 0%Z st.(account_storage)) empty_storage)  /\\\n   exists ve, (st.(account_ongoing_calls) = ve :: nil /\\\n               ve.(venv_prg_sfx) =\n               ISZERO ::\n                      PUSH1 (word_of_N 0) ::\n                      JUMPI ::\n                      PUSH1 (word_of_N 0) ::\n                      PUSH1 (word_of_N 0) ::\n                      SSTORE ::\n                      STOP ::\n                      nil\n               /\\\n               is_true (ST.equal word_eq (storage_store 0%Z 0%Z ve.(venv_storage)) empty_storage) /\\\n               is_true (ST.equal word_eq (venv_storage_at_call ve) empty_storage))\n  )\n.\n\n\nDefinition something_to_call :=\n  {|\n    callarg_gaslimit := 0%Z;\n    callarg_code := address_of_word 0%Z;\n    callarg_recipient := address_of_word 0%Z;\n    callarg_value := 0%Z;\n    callarg_data := cut_memory 0%Z 0%Z empty_memory;\n    callarg_output_begin := 0%Z;\n    callarg_output_size := storage_load 0%Z empty_storage |}.\n\n(* TODO: remove duplicate somehow *)\nCoFixpoint call_but_fail_on_reentrance (depth : word) :=\n  if word_eq word_zero depth then\n    Respond\n      (fun _ =>\n         ContractAction (ContractCall something_to_call)\n                        (call_but_fail_on_reentrance word_one))\n      (fun _ => ContractAction ContractFail (call_but_fail_on_reentrance word_zero))\n      (ContractAction ContractFail (call_but_fail_on_reentrance word_zero))\n  else if word_eq word_one depth then\n         Respond\n           (fun _ => ContractAction ContractFail (call_but_fail_on_reentrance word_one))\n           (fun _ => ContractAction (ContractReturn nil) (call_but_fail_on_reentrance word_zero))\n           (ContractAction ContractFail (call_but_fail_on_reentrance word_zero))\n       else\n         Respond\n           (fun _ => ContractAction ContractFail (call_but_fail_on_reentrance depth))\n           (fun retval => ContractAction ContractFail (call_but_fail_on_reentrance (word_sub depth word_one)))\n           (ContractAction ContractFail (call_but_fail_on_reentrance (word_sub depth word_one))).\n\nLemma call_but_fail_on_reentrace_0_eq :\n  call_but_fail_on_reentrance 0%Z =\n  Respond\n    (fun _ =>\n       ContractAction (ContractCall something_to_call)\n                      (call_but_fail_on_reentrance word_one))\n    (fun _ => ContractAction ContractFail (call_but_fail_on_reentrance word_zero))\n    (ContractAction ContractFail (call_but_fail_on_reentrance word_zero)).\nProof.\n  rewrite (response_expander_eq (call_but_fail_on_reentrance 0%Z)).\n  auto.\nQed.\n\nLemma call_but_fail_on_reentrace_1_eq :\n  call_but_fail_on_reentrance 1%Z =\n  Respond\n    (fun _ => ContractAction ContractFail (call_but_fail_on_reentrance word_one))\n    (fun retval => ContractAction (ContractReturn nil) (call_but_fail_on_reentrance word_zero))\n    (ContractAction ContractFail (call_but_fail_on_reentrance word_zero)).\nProof.\n  rewrite (response_expander_eq (call_but_fail_on_reentrance 1%Z)).\n  auto.\nQed.\n\nDefinition example2_spec (depth: word) : response_to_world :=\n  call_but_fail_on_reentrance depth.\n\nLemma update_remove_eq :\n  forall orig,\n    is_true (ST.equal word_eq orig empty_storage) ->\n    is_true\n      (ST.equal word_eq\n                (storage_store 0%Z 0%Z (ST.add 0%Z 1%Z orig))\n                empty_storage).\nProof.\n  intros orig nst2.\n  apply ST.equal_1.\n  split.\n  {\n    intro k.\n    unfold storage_store.\n    simpl.\n    split.\n    { intro H.\n      apply False_ind.\n      case_eq (word_eq k 0%Z).\n      { intro k0.\n        apply ST.Raw.remove_1 in H; auto.\n        { apply ST.Raw.add_sorted.\n          apply ST.sorted. }\n        apply ST.E.eq_sym.\n        assumption.\n      }\n      {\n        intro neq.\n        unfold ST.Raw.PX.In in H.\n        case H as [e H].\n        apply ST.Raw.remove_3 in H.\n        {\n          apply ST.Raw.add_3 in H.\n          {\n            apply ST.equal_2 in nst2.\n            case nst2 as [I _].\n            generalize (I k).\n            unfold ST.Raw.PX.In.\n            intro I'.\n            case I' as [I0 _].\n            simpl in I0.\n            case I0.\n            {\n              exists e.\n              apply H.\n            }\n            {\n              intros x J.\n              eapply ST.Raw.empty_1.\n              apply J.\n            }\n          }\n          {\n            intro K.\n            apply ST.E.eq_sym in K.\n            congruence.\n          }\n        }\n        {\n          apply ST.Raw.add_sorted.\n          apply ST.sorted.\n        }\n      }\n    }\n    {\n      intro H.\n      apply False_ind.\n      case H.\n      intros x Hx.\n      apply (ST.Raw.empty_1 Hx).\n    }\n  }\n  {\n    intros k e e' H I.\n    apply False_ind.\n    generalize I.\n    unfold empty_storage.\n    generalize (ST.empty_1 I).\n    auto.\n  }\nQed.\n\nTheorem example2_spec_impl_match :\n  forall st n,\n    example2_depth_n_state n st ->\n    account_state_responds_to_world\n      st (example2_spec n%Z) (fun _ _ => True).\nProof.\n  unfold example2_spec.\n  cofix.\n  intros st n n_state.\n  case n_state.\n  {\n    intro nst.\n    destruct nst as [nst0 nst1].\n    case nst1 as [nst1 nst2].\n    case nst2 as [nst2 nst3].\n    case nst3 as [nst3 nst4].\n    subst.\n    clear n_state.\n    subst.\n    rewrite call_but_fail_on_reentrace_0_eq.\n    apply AccountStep.\n    {\n      unfold respond_to_call_correctly.\n      intros ce a con.\n      split; [ solve [auto] | ].\n      intros _ next.\n      intro s.\n      simpl.\n      rewrite nst3.\n      repeat (case s as [| s]; [ solve [left; auto] | ]).\n      assert (stl : forall idx, storage_load idx (account_storage st) = storage_load idx empty_storage).\n      {\n        intro idx.\n        unfold storage_load.\n        apply ST.equal_2 in nst2.\n        unfold ST.Equivb in nst2.\n        unfold ST.Raw.Equivb in nst2.\n        simpl.\n        case_eq (ST.find (elt:=word) idx (account_storage st)); auto.\n        intros w H.\n        apply ST.find_2 in H.\n        apply False_ind.\n        assert (ST.Raw.PX.In idx (ST.this (account_storage st))) as K.\n        {\n          unfold ST.Raw.PX.In.\n          exists w.\n          assumption.\n        }\n        case nst2 as [EE _].\n        rewrite EE in K.\n        unfold ST.Raw.PX.In in K.\n        case K.\n        intros content K'.\n        apply (@ST.Raw.empty_1 word idx content).\n        assumption.\n      }\n      simpl.\n      rewrite !stl.\n      unfold storage_load.\n      unfold empty_storage.\n      simpl.\n      repeat (case s as [| s]; [ solve [left; auto] | cbn ]).\n      right.\n      inversion next; subst.\n      clear next.\n      rewrite get_update_balance.\n      admit.\n      Admitted.\n(*\n\n      eexists.\n      eexists.\n      eexists.\n      split; try reflexivity.\n      simpl.\n(*      rewrite <- contract_action_expander_eq in next at 1. *)\n\n      apply example2_spec_impl_match.\n        unfold example2_depth_n_state.\n        right.\n        split; auto.\n        split; auto.\n        split.\n        {\n          unfold storage_load.\n          erewrite ST.find_1.\n          { eauto. }\n          apply ST.add_1.\n          auto.\n        }\n        split; auto.\n        split.\n        {\n          apply update_remove_eq.\n          assumption.\n        }\n        eexists; eauto.\n        split.\n        {\n          rewrite nst4.\n          intuition.\n        }\n        {\n          split; auto.\n          split; auto.\n          apply update_remove_eq.\n          assumption.\n        }\n      }\n    {\n      unfold respond_to_return_correctly.\n      intros ? ? ? ?.\n      simpl.\n      rewrite nst4.\n      congruence.\n    }\n    {\n      intros ? ? ?.\n      simpl.\n      rewrite nst4.\n      congruence.\n    }\n  }\n  {\n    intros H.\n    destruct H as [n1 st_code].\n    destruct st_code as [st_code st_load].\n    destruct st_load as [st_load st_ongoing].\n    subst.\n    unfold example2_spec.\n    rewrite call_but_fail_on_reentrace_1_eq.\n    apply AccountStep.\n    { (* call *)\n      intros callenv act continuation.\n      split; [solve [auto] | ].\n      intros _ H.\n      inversion H; subst.\n      clear H.\n        intro s.\n        repeat (case s as [| s]; [ solve [left; auto] | ]).\n        simpl.\n        rewrite st_code.\n        unfold example2_program.\n        cbn.\n        repeat (case s as [| s]; [ solve [left; auto] | ]).\n        cbn.\n        rewrite st_load.\n        simpl.\n        rewrite st_code.\n        simpl.\n        right.\n        eexists.\n        eexists.\n        eexists.\n        split; [ solve [eauto] | ].\n        unfold build_venv_called.\n        cbn.\n        apply example2_spec_impl_match.\n        unfold example2_depth_n_state.\n        intuition.\n      }\n    { (* return *)\n      unfold respond_to_return_correctly.\n      intros rr venv cont act.\n      elim st_ongoing.\n      intros prev prevH.\n      case prevH as [st_str prevH].\n      case prevH as [prevH prevH'].\n      case prevH' as [prevH' prevH''].\n      case prevH'' as [prevH'' prevH'''].\n      simpl.\n      rewrite prevH'.\n      intro H.\n      inversion H; subst.\n      clear H.\n      intros act_cont_eq.\n      intro s.\n      rewrite prevH''.\n      repeat (case s as [| s]; [ solve [left; auto] | ]).\n      simpl.\n      right.\n      f_equal.\n      inversion act_cont_eq; subst.\n\n      eexists.\n      eexists.\n      eexists.\n      split; [reflexivity | ].\n      inversion act_cont_eq; subst.\n      apply example2_spec_impl_match.\n      unfold example2_depth_n_state.\n      left.\n      repeat (split; auto); tauto.\n    }\n    {\n      unfold respond_to_fail_correctly.\n      intros venv cont act.\n      case st_ongoing as [st_addr st_ongoing].\n      case st_ongoing as [st_storage st_ongoing].\n      case st_ongoing as [ve veH].\n      case veH as [st_ongoing ve_sfx].\n      case ve_sfx as [ve_sfx ve_str].\n      simpl.\n      rewrite st_ongoing.\n      intro venvH.\n      inversion venvH; subst.\n      clear venvH.\n      intros act_cont_H.\n      inversion act_cont_H; subst.\n      clear act_cont_H.\n      intro s.\n      rewrite ve_sfx.\n      repeat (case s as [| s]; [ solve [left; auto] | ]).\n      simpl.\n      rewrite st_code.\n      simpl.\n      right.\n      f_equal.\n      eexists.\n      eexists.\n      eexists.\n      split; [reflexivity | ].\n      simpl.\n      apply example2_spec_impl_match.\n      unfold example2_depth_n_state.\n      left.\n      repeat split; auto; tauto.\n    }\n  }\nQed.\n********)", "meta": {"author": "pirapira", "repo": "evmverif", "sha": "cb1e478f73facb82b60f2d12c3c5bc34a23f2cf1", "save_path": "github-repos/coq/pirapira-evmverif", "path": "github-repos/coq/pirapira-evmverif/evmverif-cb1e478f73facb82b60f2d12c3c5bc34a23f2cf1/coq/example/call_but_fail_on_reentrance.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.20061075778115825}}
{"text": "From stdpp Require Export namespaces.\nFrom iris.algebra Require Import gmap_view namespace_map agree frac.\nFrom iris.algebra Require Export dfrac.\nFrom iris.bi.lib Require Import fractional.\nFrom iris.proofmode Require Import tactics.\nFrom iris.base_logic.lib Require Export own.\nFrom iris.prelude Require Import options.\nImport uPred.\n\n(** This file provides a generic mechanism for a language-level point-to\nconnective [l ↦{dq} v] reflecting the physical heap.  This library is designed to\nbe used as a singleton (i.e., with only a single instance existing in any\nproof), with the [gen_heapG] typeclass providing the ghost names of that unique\ninstance.  That way, [mapsto] does not need an explicit [gname] parameter.\nThis mechanism can be plugged into a language and related to the physical heap\nby using [gen_heap_interp σ] in the state interpretation of the weakest\nprecondition. See heap-lang for an example.\n\nIf you are looking for a library providing \"ghost heaps\" independent of the\nphysical state, you will likely want explicit ghost names and are thus better\noff using [algebra.lib.gmap_view] together with [base_logic.lib.own].\n\nThis library is generic in the types [L] for locations and [V] for values and\nsupports fractional permissions.  Next to the point-to connective [l ↦{dq} v],\nwhich keeps track of the value [v] of a location [l], this library also provides\na way to attach \"meta\" or \"ghost\" data to locations. This is done as follows:\n\n- When one allocates a location, in addition to the point-to connective [l ↦ v],\n  one also obtains the token [meta_token l ⊤]. This token is an exclusive\n  resource that denotes that no meta data has been associated with the\n  namespaces in the mask [⊤] for the location [l].\n- Meta data tokens can be split w.r.t. namespace masks, i.e.\n  [meta_token l (E1 ∪ E2) ⊣⊢ meta_token l E1 ∗ meta_token l E2] if [E1 ## E2].\n- Meta data can be set using the update [meta_token l E ==∗ meta l N x] provided\n  [↑N ⊆ E], and [x : A] for any countable [A]. The [meta l N x] connective is\n  persistent and denotes the knowledge that the meta data [x] has been\n  associated with namespace [N] to the location [l].\n\nTo make the mechanism as flexible as possible, the [x : A] in [meta l N x] can\nbe of any countable type [A]. This means that you can associate e.g. single\nghost names, but also tuples of ghost names, etc.\n\nTo further increase flexibility, the [meta l N x] and [meta_token l E]\nconnectives are annotated with a namespace [N] and mask [E]. That way, one can\nassign a map of meta information to a location. This is particularly useful when\nbuilding abstractions, then one can gradually assign more ghost information to a\nlocation instead of having to do all of this at once. We use namespaces so that\nthese can be matched up with the invariant namespaces. *)\n\n(** To implement this mechanism, we use three resource algebras:\n\n- A [gmap_view L V], which keeps track of the values of locations.\n- A [gmap_view L gname], which keeps track of the meta information of\n  locations. More specifically, this RA introduces an indirection: it keeps\n  track of a ghost name for each location.\n- The ghost names in the aforementioned authoritative RA refer to namespace maps\n  [namespace_map (agree positive)], which store the actual meta information.\n  This indirection is needed because we cannot perform frame preserving updates\n  in an authoritative fragment without owning the full authoritative element\n  (in other words, without the indirection [meta_set] would need [gen_heap_interp]\n  as a premise).\n *)\n\n(** The CMRAs we need, and the global ghost names we are using. *)\n\nClass gen_heapPreG (L V : Type) (Σ : gFunctors) `{Countable L} := {\n  gen_heap_preG_inG :> inG Σ (gmap_viewR L (leibnizO V));\n  gen_meta_preG_inG :> inG Σ (gmap_viewR L gnameO);\n  gen_meta_data_preG_inG :> inG Σ (namespace_mapR (agreeR positiveO));\n}.\n\nClass gen_heapG (L V : Type) (Σ : gFunctors) `{Countable L} := GenHeapG {\n  gen_heap_inG :> gen_heapPreG L V Σ;\n  gen_heap_name : gname;\n  gen_meta_name : gname\n}.\nGlobal Arguments GenHeapG L V Σ {_ _ _} _ _.\nGlobal Arguments gen_heap_name {L V Σ _ _} _ : assert.\nGlobal Arguments gen_meta_name {L V Σ _ _} _ : assert.\n\nDefinition gen_heapΣ (L V : Type) `{Countable L} : gFunctors := #[\n  GFunctor (gmap_viewR L (leibnizO V));\n  GFunctor (gmap_viewR L gnameO);\n  GFunctor (namespace_mapR (agreeR positiveO))\n].\n\nGlobal Instance subG_gen_heapPreG {Σ L V} `{Countable L} :\n  subG (gen_heapΣ L V) Σ → gen_heapPreG L V Σ.\nProof. solve_inG. Qed.\n\nSection definitions.\n  Context `{Countable L, hG : !gen_heapG L V Σ}.\n\n  Definition gen_heap_interp (σ : gmap L V) : iProp Σ := ∃ m : gmap L gname,\n    (* The [⊆] is used to avoid assigning ghost information to the locations in\n    the initial heap (see [gen_heap_init]). *)\n    ⌜ dom _ m ⊆ dom (gset L) σ ⌝ ∧\n    own (gen_heap_name hG) (gmap_view_auth 1 (σ : gmap L (leibnizO V))) ∗\n    own (gen_meta_name hG) (gmap_view_auth 1 (m : gmap L gnameO)).\n\n  Definition mapsto_def (l : L) (dq : dfrac) (v: V) : iProp Σ :=\n    own (gen_heap_name hG) (gmap_view_frag l dq (v : leibnizO V)).\n  Definition mapsto_aux : seal (@mapsto_def). Proof. by eexists. Qed.\n  Definition mapsto := mapsto_aux.(unseal).\n  Definition mapsto_eq : @mapsto = @mapsto_def := mapsto_aux.(seal_eq).\n\n  Definition meta_token_def (l : L) (E : coPset) : iProp Σ :=\n    ∃ γm, own (gen_meta_name hG) (gmap_view_frag l DfracDiscarded γm) ∗\n          own γm (namespace_map_token E).\n  Definition meta_token_aux : seal (@meta_token_def). Proof. by eexists. Qed.\n  Definition meta_token := meta_token_aux.(unseal).\n  Definition meta_token_eq : @meta_token = @meta_token_def := meta_token_aux.(seal_eq).\n\n  Definition meta_def `{Countable A} (l : L) (N : namespace) (x : A) : iProp Σ :=\n    ∃ γm, own (gen_meta_name hG) (gmap_view_frag l DfracDiscarded γm) ∗\n          own γm (namespace_map_data N (to_agree (encode x))).\n  Definition meta_aux : seal (@meta_def). Proof. by eexists. Qed.\n  Definition meta := meta_aux.(unseal).\n  Definition meta_eq : @meta = @meta_def := meta_aux.(seal_eq).\nEnd definitions.\nGlobal Arguments meta {L _ _ V Σ _ A _ _} l N x.\n\n(** FIXME: Refactor these notations using custom entries once Coq bug #13654\nhas been fixed. *)\nLocal Notation \"l ↦{ dq } v\" := (mapsto l dq v)\n  (at level 20, format \"l  ↦{ dq }  v\") : bi_scope.\nLocal Notation \"l ↦□ v\" := (mapsto l DfracDiscarded v)\n  (at level 20, format \"l  ↦□  v\") : bi_scope.\nLocal Notation \"l ↦{# q } v\" := (mapsto l (DfracOwn q) v)\n  (at level 20, format \"l  ↦{# q }  v\") : bi_scope.\nLocal Notation \"l ↦ v\" := (mapsto l (DfracOwn 1) v)\n  (at level 20, format \"l  ↦  v\") : bi_scope.\n\nSection gen_heap.\n  Context {L V} `{Countable L, !gen_heapG L V Σ}.\n  Implicit Types P Q : iProp Σ.\n  Implicit Types Φ : V → iProp Σ.\n  Implicit Types σ : gmap L V.\n  Implicit Types m : gmap L gname.\n  Implicit Types l : L.\n  Implicit Types v : V.\n\n  (** General properties of mapsto *)\n  Global Instance mapsto_timeless l dq v : Timeless (l ↦{dq} v).\n  Proof. rewrite mapsto_eq. apply _. Qed.\n  Global Instance mapsto_fractional l v : Fractional (λ q, l ↦{#q} v)%I.\n  Proof.\n    intros p q. rewrite mapsto_eq /mapsto_def -own_op gmap_view_frag_add //.\n  Qed.\n  Global Instance mapsto_as_fractional l q v :\n    AsFractional (l ↦{#q} v) (λ q, l ↦{#q} v)%I q.\n  Proof. split; [done|]. apply _. Qed.\n  Global Instance mapsto_persistent l v : Persistent (l ↦□ v).\n  Proof. rewrite mapsto_eq. apply _. Qed.\n\n  Lemma mapsto_valid l dq v : l ↦{dq} v -∗ ⌜✓ dq⌝%Qp.\n  Proof.\n    rewrite mapsto_eq. iIntros \"Hl\".\n    iDestruct (own_valid with \"Hl\") as %?%gmap_view_frag_valid. done.\n  Qed.\n  Lemma mapsto_valid_2 l dq1 dq2 v1 v2 : l ↦{dq1} v1 -∗ l ↦{dq2} v2 -∗ ⌜✓ (dq1 ⋅ dq2) ∧ v1 = v2⌝.\n  Proof.\n    rewrite mapsto_eq. iIntros \"H1 H2\".\n    iDestruct (own_valid_2 with \"H1 H2\") as %[??]%gmap_view_frag_op_valid_L.\n    auto.\n  Qed.\n  (** Almost all the time, this is all you really need. *)\n  Lemma mapsto_agree l dq1 dq2 v1 v2 : l ↦{dq1} v1 -∗ l ↦{dq2} v2 -∗ ⌜v1 = v2⌝.\n  Proof.\n    iIntros \"H1 H2\".\n    iDestruct (mapsto_valid_2 with \"H1 H2\") as %[_ ?].\n    done.\n  Qed.\n\n  Lemma mapsto_combine l dq1 dq2 v1 v2 :\n    l ↦{dq1} v1 -∗ l ↦{dq2} v2 -∗ l ↦{dq1 ⋅ dq2} v1 ∗ ⌜v1 = v2⌝.\n  Proof.\n    iIntros \"Hl1 Hl2\". iDestruct (mapsto_agree with \"Hl1 Hl2\") as %->.\n    iCombine \"Hl1 Hl2\" as \"Hl\".\n    rewrite mapsto_eq /mapsto_def -own_op gmap_view_frag_op.\n    auto.\n  Qed.\n\n  Lemma mapsto_frac_ne l1 l2 dq1 dq2 v1 v2 :\n    ¬ ✓(dq1 ⋅ dq2) → l1 ↦{dq1} v1 -∗ l2 ↦{dq2} v2 -∗ ⌜l1 ≠ l2⌝.\n  Proof.\n    iIntros (?) \"Hl1 Hl2\"; iIntros (->).\n    by iDestruct (mapsto_valid_2 with \"Hl1 Hl2\") as %[??].\n  Qed.\n  Lemma mapsto_ne l1 l2 dq2 v1 v2 : l1 ↦ v1 -∗ l2 ↦{dq2} v2 -∗ ⌜l1 ≠ l2⌝.\n  Proof. apply mapsto_frac_ne. intros ?%exclusive_l; [done|apply _]. Qed.\n\n  (** Permanently turn any points-to predicate into a persistent\n      points-to predicate. *)\n  Lemma mapsto_persist l dq v : l ↦{dq} v ==∗ l ↦□ v.\n  Proof. rewrite mapsto_eq. apply own_update, gmap_view_persist. Qed.\n\n  (** General properties of [meta] and [meta_token] *)\n  Global Instance meta_token_timeless l N : Timeless (meta_token l N).\n  Proof. rewrite meta_token_eq /meta_token_def. apply _. Qed.\n  Global Instance meta_timeless `{Countable A} l N (x : A) : Timeless (meta l N x).\n  Proof. rewrite meta_eq /meta_def. apply _. Qed.\n  Global Instance meta_persistent `{Countable A} l N (x : A) : Persistent (meta l N x).\n  Proof. rewrite meta_eq /meta_def. apply _. Qed.\n\n  Lemma meta_token_union_1 l E1 E2 :\n    E1 ## E2 → meta_token l (E1 ∪ E2) -∗ meta_token l E1 ∗ meta_token l E2.\n  Proof.\n    rewrite meta_token_eq /meta_token_def. intros ?. iDestruct 1 as (γm1) \"[#Hγm Hm]\".\n    rewrite namespace_map_token_union //. iDestruct \"Hm\" as \"[Hm1 Hm2]\".\n    iSplitL \"Hm1\"; eauto.\n  Qed.\n  Lemma meta_token_union_2 l E1 E2 :\n    meta_token l E1 -∗ meta_token l E2 -∗ meta_token l (E1 ∪ E2).\n  Proof.\n    rewrite meta_token_eq /meta_token_def.\n    iDestruct 1 as (γm1) \"[#Hγm1 Hm1]\". iDestruct 1 as (γm2) \"[#Hγm2 Hm2]\".\n    iDestruct (own_valid_2 with \"Hγm1 Hγm2\") as %[_ ->]%gmap_view_frag_op_valid_L.\n    iDestruct (own_valid_2 with \"Hm1 Hm2\") as %?%namespace_map_token_valid_op.\n    iExists γm2. iFrame \"Hγm2\". rewrite namespace_map_token_union //. by iSplitL \"Hm1\".\n  Qed.\n  Lemma meta_token_union l E1 E2 :\n    E1 ## E2 → meta_token l (E1 ∪ E2) ⊣⊢ meta_token l E1 ∗ meta_token l E2.\n  Proof.\n    intros; iSplit; first by iApply meta_token_union_1.\n    iIntros \"[Hm1 Hm2]\". by iApply (meta_token_union_2 with \"Hm1 Hm2\").\n  Qed.\n\n  Lemma meta_token_difference l E1 E2 :\n    E1 ⊆ E2 → meta_token l E2 ⊣⊢ meta_token l E1 ∗ meta_token l (E2 ∖ E1).\n  Proof.\n    intros. rewrite {1}(union_difference_L E1 E2) //.\n    by rewrite meta_token_union; last set_solver.\n  Qed.\n\n  Lemma meta_agree `{Countable A} l i (x1 x2 : A) :\n    meta l i x1 -∗ meta l i x2 -∗ ⌜x1 = x2⌝.\n  Proof.\n    rewrite meta_eq /meta_def.\n    iDestruct 1 as (γm1) \"[Hγm1 Hm1]\"; iDestruct 1 as (γm2) \"[Hγm2 Hm2]\".\n    iDestruct (own_valid_2 with \"Hγm1 Hγm2\") as %[_ ->]%gmap_view_frag_op_valid_L.\n    iDestruct (own_valid_2 with \"Hm1 Hm2\") as %Hγ; iPureIntro.\n    move: Hγ. rewrite -namespace_map_data_op namespace_map_data_valid.\n    move=> /to_agree_op_inv_L. naive_solver.\n  Qed.\n  Lemma meta_set `{Countable A} E l (x : A) N :\n    ↑ N ⊆ E → meta_token l E ==∗ meta l N x.\n  Proof.\n    rewrite meta_token_eq meta_eq /meta_token_def /meta_def.\n    iDestruct 1 as (γm) \"[Hγm Hm]\". iExists γm. iFrame \"Hγm\".\n    iApply (own_update with \"Hm\"). by apply namespace_map_alloc_update.\n  Qed.\n\n  (** Update lemmas *)\n  Lemma gen_heap_alloc σ l v :\n    σ !! l = None →\n    gen_heap_interp σ ==∗ gen_heap_interp (<[l:=v]>σ) ∗ l ↦ v ∗ meta_token l ⊤.\n  Proof.\n    iIntros (Hσl). rewrite /gen_heap_interp mapsto_eq /mapsto_def meta_token_eq /meta_token_def /=.\n    iDestruct 1 as (m Hσm) \"[Hσ Hm]\".\n    iMod (own_update with \"Hσ\") as \"[Hσ Hl]\".\n    { eapply (gmap_view_alloc _ l (DfracOwn 1)); done. }\n    iMod (own_alloc (namespace_map_token ⊤)) as (γm) \"Hγm\".\n    { apply namespace_map_token_valid. }\n    iMod (own_update with \"Hm\") as \"[Hm Hlm]\".\n    { eapply (gmap_view_alloc _ l DfracDiscarded); last done.\n      move: Hσl. rewrite -!(not_elem_of_dom (D:=gset L)). set_solver. }\n    iModIntro. iFrame \"Hl\". iSplitL \"Hσ Hm\"; last by eauto with iFrame.\n    iExists (<[l:=γm]> m). iFrame. iPureIntro.\n    rewrite !dom_insert_L. set_solver.\n  Qed.\n\n  Lemma gen_heap_alloc_big σ σ' :\n    σ' ##ₘ σ →\n    gen_heap_interp σ ==∗\n    gen_heap_interp (σ' ∪ σ) ∗ ([∗ map] l ↦ v ∈ σ', l ↦ v) ∗ ([∗ map] l ↦ _ ∈ σ', meta_token l ⊤).\n  Proof.\n    revert σ; induction σ' as [| l v σ' Hl IH] using map_ind; iIntros (σ Hdisj) \"Hσ\".\n    { rewrite left_id_L. auto. }\n    iMod (IH with \"Hσ\") as \"[Hσ'σ Hσ']\"; first by eapply map_disjoint_insert_l.\n    decompose_map_disjoint.\n    rewrite !big_opM_insert // -insert_union_l //.\n    by iMod (gen_heap_alloc with \"Hσ'σ\") as \"($ & $ & $)\";\n      first by apply lookup_union_None.\n  Qed.\n\n  Lemma gen_heap_valid σ l dq v : gen_heap_interp σ -∗ l ↦{dq} v -∗ ⌜σ !! l = Some v⌝.\n  Proof.\n    iDestruct 1 as (m Hσm) \"[Hσ _]\". iIntros \"Hl\".\n    rewrite /gen_heap_interp mapsto_eq.\n    by iDestruct (own_valid_2 with \"Hσ Hl\") as %[??]%gmap_view_both_valid_L.\n  Qed.\n\n  Lemma gen_heap_update σ l v1 v2 :\n    gen_heap_interp σ -∗ l ↦ v1 ==∗ gen_heap_interp (<[l:=v2]>σ) ∗ l ↦ v2.\n  Proof.\n    iDestruct 1 as (m Hσm) \"[Hσ Hm]\".\n    iIntros \"Hl\". rewrite /gen_heap_interp mapsto_eq /mapsto_def.\n    iDestruct (own_valid_2 with \"Hσ Hl\") as %[_ Hl]%gmap_view_both_valid_L.\n    iMod (own_update_2 with \"Hσ Hl\") as \"[Hσ Hl]\".\n    { eapply gmap_view_update. }\n    iModIntro. iFrame \"Hl\". iExists m. iFrame.\n    iPureIntro. apply (elem_of_dom_2 (D:=gset L)) in Hl.\n    rewrite dom_insert_L. set_solver.\n  Qed.\nEnd gen_heap.\n\n(** This variant of [gen_heap_init] should only be used when absolutely needed.\nThe key difference to [gen_heap_init] is that the [inG] instances in the new\n[gen_heapG] instance are related to the original [gen_heapPreG] instance,\nwhereas [gen_heap_init] forgets about that relation. *)\nLemma gen_heap_init_names `{Countable L, !gen_heapPreG L V Σ} σ :\n  ⊢ |==> ∃ γh γm : gname,\n    let hG := GenHeapG L V Σ γh γm in\n    gen_heap_interp σ ∗ ([∗ map] l ↦ v ∈ σ, l ↦ v) ∗ ([∗ map] l ↦ _ ∈ σ, meta_token l ⊤).\nProof.\n  iMod (own_alloc (gmap_view_auth 1 (∅ : gmap L (leibnizO V)))) as (γh) \"Hh\".\n  { exact: gmap_view_auth_valid. }\n  iMod (own_alloc (gmap_view_auth 1 (∅ : gmap L gnameO))) as (γm) \"Hm\".\n  { exact: gmap_view_auth_valid. }\n  iExists γh, γm.\n  iAssert (gen_heap_interp (hG:=GenHeapG _ _ _ γh γm) ∅) with \"[Hh Hm]\" as \"Hinterp\".\n  { iExists ∅; simpl. iFrame \"Hh Hm\". by rewrite dom_empty_L. }\n  iMod (gen_heap_alloc_big with \"Hinterp\") as \"(Hinterp & $ & $)\".\n  { apply map_disjoint_empty_r. }\n  rewrite right_id_L. done.\nQed.\n\nLemma gen_heap_init `{Countable L, !gen_heapPreG L V Σ} σ :\n  ⊢ |==> ∃ _ : gen_heapG L V Σ,\n    gen_heap_interp σ ∗ ([∗ map] l ↦ v ∈ σ, l ↦ v) ∗ ([∗ map] l ↦ _ ∈ σ, meta_token l ⊤).\nProof.\n  iMod (gen_heap_init_names σ) as (γh γm) \"Hinit\".\n  iExists (GenHeapG _ _ _ γh γm).\n  done.\nQed.\n", "meta": {"author": "gares", "repo": "iris", "sha": "7b4a04ce0d396cb27eeef22e883a9f3b738e83f4", "save_path": "github-repos/coq/gares-iris", "path": "github-repos/coq/gares-iris/iris-7b4a04ce0d396cb27eeef22e883a9f3b738e83f4/iris/base_logic/lib/gen_heap.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.34510526422232046, "lm_q1q2_score": 0.20061075669005723}}
{"text": "Require Import Coq.Lists.List.\nRequire Export ParDB.Spec.\nRequire Export ParDB.Lemmas.\nRequire Export ParDB.Inst.\n\nRequire Export SpecSyntax.\nRequire Export SpecTyping.\n\nArguments wkm _ {_ _} _.\nArguments comp _ _ {_ _ } _ _ _.\n\nRecord WtRen (Γ Δ: Env) (ζ: Sub Ix) : Prop :=\n  { wtr_tyvar : ∀ {α k},\n                  ⟨ α ∷ k ∈ Γ ⟩ →\n                  ⟨ ζ α ∷ k ∈ Δ ⟩;\n    wtr_covar : ∀ {c τ1 τ2 k},\n                  ⟨ c : τ1 ~ τ2 ∷ k ∈ Γ ⟩ →\n                  ⟨ ζ c : τ1[ζ] ~ τ2[ζ] ∷ k ∈ Δ ⟩;\n    wtr_tmvar : ∀ {x τ},\n                  ⟨ x : τ ∈ Γ ⟩ →\n                  ⟨ ζ x : τ[ζ] ∈ Δ ⟩\n  }.\n\nNotation \"⟨ ζ : Γ -> Δ ⟩\" := (WtRen Γ Δ ζ)\n  (at level 0,\n   ζ at level 98,\n   Γ at level 98,\n   Δ at level 98).\n\nArguments wtr_tyvar {_ _ _} _ {_ _} _.\nArguments wtr_covar {_ _ _} _ {_ _ _ _} _.\nArguments wtr_tmvar {_ _ _} _ {_ _} _.\n\nRecord WtSub (Γ Δ: Env) (ζ: Sub Exp) : Prop :=\n  { wts_tyvar : ∀ {α k},\n                  ⟨ α ∷ k ∈ Γ ⟩ →\n                  ⟨ Δ ⊢ ζ α ∷ k ⟩;\n    wts_covar : ∀ {c τ1 τ2 k},\n                  ⟨ c : τ1 ~ τ2 ∷ k ∈ Γ ⟩ →\n                  ⟨ Δ ⊢ ζ c : τ1[ζ] ~ τ2[ζ] ∷ k ⟩;\n    wts_tmvar : ∀ {x τ},\n                  ⟨ x : τ ∈ Γ ⟩ →\n                  ⟨ Δ ⊢ ζ x : τ[ζ] ⟩;\n  }.\nNotation \"⟨ ζ : Γ => Δ ⟩\" := (WtSub Γ Δ ζ)\n  (at level 0, ζ at level 98, Γ at level 98, Δ at level 98).\n\nArguments wts_tyvar {_ _ _} _ {_ _} _.\nArguments wts_covar {_ _ _} _ {_ _ _ _} _.\nArguments wts_tmvar {_ _ _} _ {_ _} _.\n\nHint Constructors Ty : ws.\nHint Constructors Co : ws.\nHint Constructors Red : ws.\nHint Constructors RedStar : ws.\nHint Constructors Tm : ws.\nHint Resolve wtr_tyvar : ws.\nHint Resolve wtr_covar : ws.\nHint Resolve wtr_tmvar : ws.\nHint Resolve wts_tyvar : ws.\nHint Resolve wts_covar : ws.\nHint Resolve wts_tmvar : ws.\n\n(* Lemma getEvarInvHere { Γ T U } : *)\n(*   ⟪ 0 : T ∈ (Γ ▻ U) ⟫ → T = U. *)\n(* Proof. inversion 1; auto. Qed. *)\n\n(* Lemma getEvarInvThere {Γ i T U} : *)\n(*   ⟪ (S i) : T ∈ Γ ▻ U ⟫ → ⟪ i : T ∈ Γ ⟫. *)\n(* Proof. inversion 1; auto. Qed. *)\n(* Hint Resolve getEvarInvThere : wsi. *)\n\nLtac crushTypingMatchH :=\n  match goal with\n    | [H: ⟨ 0 : _ ∈ _ ⟩                    |- _] => inversion H; clear H; subst*\n    | [H: ⟨ (S _) : _ ∈ _ ⟩                |- _] => inversion H; clear H; subst*\n    | [H: ⟨ 0 ∷ _ ∈ _ ⟩                    |- _] => inversion H; clear H; subst*\n    | [H: ⟨ (S _) ∷ _ ∈ _ ⟩                |- _] => inversion H; clear H; subst*\n    | [H: ⟨ 0 : _ ~ _ ∷ _ ∈ _ ⟩            |- _] => inversion H; clear H; subst*\n    | [H: ⟨ (S _) : _ ~ _ ∷ _ ∈ _ ⟩        |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ : _ ∈ nil ⟩                  |- _] => inversion H; clear H; subst*\n    (* Ty *)\n    | [H: ⟨ _ ⊢ var _ ∷ _ ⟩                |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ τabs _ _ ∷ _ ⟩             |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ τapp _ _ ∷ _ ⟩             |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ arr _ _ ∷ _ ⟩              |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ arrτ _ _ ∷ _ ⟩             |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ arrγ _ _ _ _ ∷ _ ⟩         |- _] => inversion H; clear H; subst*\n    (* Co *)\n    | [H: ⟨ _ ⊢ var _          : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ coτabs _ _     : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ coτapp _ _     : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ coarr _ _      : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ coarrτ _ _     : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ coarrγ _ _ _ _ : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ coinvarr₁ _    : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ coinvarr₂ _    : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ coinvarrτ _ _  : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ coinvarrγ₁ _   : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ coinvarrγ₂ _   : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ coinvarrγ₂ _   : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ cobeta _ _ _   : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ corefl _       : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ cosym _        : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ cotrans _ _    : _ ~ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    (* Red *)\n    | [H: ⟨ _ ⊢ var _ : _ ↝ _ ∷ _ ⟩        |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ coτabs _ _ : _ ↝ _ ∷ _ ⟩   |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ _ : arr _ _ ↝ _ ∷ _ ⟩      |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ _ : arrτ _ _ ↝ _ ∷ _ ⟩     |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ _ : arrγ _ _ _ _ ↝ _ ∷ _ ⟩ |- _] => inversion H; clear H; subst*\n    (* Tm *)\n    | [H: ⟨ _ ⊢ var _ : _        ⟩         |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ abs _ _ : _      ⟩         |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ absτ _ _ : _     ⟩         |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ absγ _ _ _ _ : _ ⟩         |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ app _ _ : _      ⟩         |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ appτ _ _ : _     ⟩         |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ appγ _ _ : _     ⟩         |- _] => inversion H; clear H; subst*\n    | [H: ⟨ _ ⊢ cast _ _ : _     ⟩         |- _] => inversion H; clear H; subst*\n\n    (* | [ wi : ⟪ ?i : _ ∈ (_ ▻ _) ⟫ *)\n    (*     |- context [match ?i with _ => _ end] *)\n    (*   ] => destruct i *)\n    | [ wi : ⟨ ?i : _ ∈ (_ ▻ _) ⟩ |- _] => destruct i eqn: ?; cbn in *\n    | [ wi : ⟨ ?i ∷ _ ∈ (_ ▻ _) ⟩ |- _] => destruct i eqn: ?; cbn in *\n    | [ wi : ⟨ ?i : _ ~ _ ∷ _ ∈ (_ ▻ _) ⟩ |- _] => destruct i eqn: ?; cbn in *\n    | [ wi : ⟨ ?i : _ ∈ (_ ► _) ⟩ |- _] => destruct i eqn: ?; cbn in *\n    | [ wi : ⟨ ?i ∷ _ ∈ (_ ► _) ⟩ |- _] => destruct i eqn: ?; cbn in *\n    | [ wi : ⟨ ?i : _ ~ _ ∷ _ ∈ (_ ► _) ⟩ |- _] => destruct i eqn: ?; cbn in *\n    | [ wi : ⟨ ?i : _ ∈ (_ ◅ _ ~ _ ∷ _) ⟩ |- _] => destruct i eqn: ?; cbn in *\n    | [ wi : ⟨ ?i ∷ _ ∈ (_ ◅ _ ~ _ ∷ _) ⟩ |- _] => destruct i eqn: ?; cbn in *\n    | [ wi : ⟨ ?i : _ ~ _ ∷ _ ∈ (_ ► _) ⟩ |- _] => inversion wi; clear wi\n    | [ wi : ⟨ ?i : _ ~ _ ∷ _ ∈ (_ ◅ _ ~ _ ∷ _) ⟩ |- _] => destruct i eqn: ?; cbn in *\n\n    | [ |- ⟨ _ ⊢ (_ :: _) : _ ↝* _ ∷ _ ⟩ ] => econstructor\n    | [ |- ⟨ _ ⊢ nil : _ ↝* _ ∷ _ ⟩ ] => econstructor\n    | [ |- ⟨ _ ⊢ coarrγ _ _ _ _ : _ ↝ _ ∷ _ ⟩ ] => econstructor\n    | [ |- ⟨ _ ⊢ _ : arrγ _ _ _ _ ↝ _ ∷ _ ⟩ ] => econstructor\n    | [ |- ⟨ _ ⊢ cotrans _ _ : _ ~ _ ∷ _ ⟩ ] => econstructor\n\n    (* | [ wi : ⟨ ?i : _ ∈ (_ ► _) ⟩ *)\n    (*     |- context [(_ · _) ?i] *)\n    (*   ] => destruct i eqn: ?; cbn in * *)\n    (* | [ wi : ⟨ ?i : _ ∈ (_ ◅ _ ~ _ ∷ _) ⟩ *)\n    (*     |- context [(_ · _) ?i] *)\n    (*   ] => destruct i eqn: ?; cbn in * *)\n    (* | [ |- ⟪ _ ⊢ var _ : _ ⟫         ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ abs _ _ : _ ⟫       ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ app _ _ : _ ⟫       ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ unit : _ ⟫          ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ true : _ ⟫          ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ false : _ ⟫         ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ ite _ _ _ : _ ⟫     ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ pair _ _ : _ ⟫      ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ proj₁ _ : _ ⟫       ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ proj₂ _ : _ ⟫       ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ inl _ : _ ⟫         ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ inr _ : _ ⟫         ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ caseof _ _ _ : _ ⟫  ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ seq _ _ : _ ⟫       ] => econstructor *)\n    (* | [ |- ⟪ _ ⊢ fixt _ _ _ : _ ⟫    ] => econstructor *)\n  end.\n\nHint Constructors GetTyVar : ws.\nHint Constructors GetCoVar : ws.\nHint Constructors GetTmVar : ws.\n\nLocal Ltac crush :=\n  intros;\n  repeat\n    (cbn in *;\n     repeat crushSyntaxMatch;\n     repeat crushDbSyntaxMatchH;\n     repeat crushDbLemmasRewriteH;\n     repeat crushSyntaxRefold;\n     (* repeat crushTypingMatchH; *)\n     subst*;\n     try discriminate;\n     eauto 200 with core ws;\n     idtac\n    ).\n\n(*************************************************************************)\n\nLemma wtRen_closed {ζ Δ} :\n  ⟨ ζ : nil -> Δ ⟩.\nProof. constructor; inversion 1. Qed.\nHint Resolve wtRen_closed : ws.\n\nLemma wtRen_idm Γ :\n  ⟨ idm Ix : Γ -> Γ ⟩.\nProof. constructor; crush. Qed.\nHint Resolve wtRen_idm : ws.\n\nLemma wtRen_comp {Γ₁ Γ₂ Γ₃ ξ₁ ξ₂} :\n  ⟨ ξ₁ : Γ₁ -> Γ₂ ⟩ →\n  ⟨ ξ₂ : Γ₂ -> Γ₃ ⟩ →\n  ⟨ ξ₁ >=> ξ₂ : Γ₁ -> Γ₃ ⟩.\nProof. constructor; crush. Qed.\nHint Resolve wtRen_comp : ws.\n\n(*************************************************************************)\n\nLemma wtRen_wkm_tyvar Γ k :\n  ⟨ wkm Ix : Γ -> Γ ► k ⟩.\nProof. constructor; intros; rewrite ?ap_wkm_ix; crush. Qed.\nHint Resolve wtRen_wkm_tyvar : ws.\n\nLemma wtRen_wkm_covar Γ τ1 τ2 k :\n  ⟨ wkm Ix : Γ -> Γ ◅ τ1 ~ τ2 ∷ k ⟩.\nProof. constructor; intros; rewrite ?ap_wkm_ix; crush. Qed.\nHint Resolve wtRen_wkm_covar : ws.\n\nLemma wtRen_wkm_tmvar Γ τ :\n  ⟨ wkm Ix : Γ -> Γ ▻ τ ⟩.\nProof. constructor; intros; rewrite ?ap_wkm_ix; crush. Qed.\nHint Resolve wtRen_wkm_tmvar : ws.\n\nLemma wtRen_snoc_tyvar {Γ Δ ζ α k} :\n  ⟨ ζ : Γ -> Δ ⟩ →\n  ⟨ α ∷ k ∈ Δ ⟩ →\n  ⟨ ζ · α : Γ ► k -> Δ ⟩.\nProof.\n  intros wζ wx; constructor; crush; repeat crushTypingMatchH;\n    rewrite <- ?ap_wkm_ix, ?ap_comp, ?wkm_snoc_cancel; crush.\nQed.\nHint Resolve wtRen_snoc_tyvar : ws.\n\nLemma wtRen_snoc_covar {Γ Δ ζ c τ1 τ2 k} :\n  ⟨ ζ : Γ -> Δ ⟩ →\n  ⟨ c : τ1[ζ] ~ τ2[ζ] ∷ k ∈ Δ ⟩ →\n  ⟨ ζ · c : Γ ◅ τ1 ~ τ2 ∷ k -> Δ ⟩.\nProof.\n  intros wζ wx; constructor; crush; repeat crushTypingMatchH;\n    rewrite <- ?ap_wkm_ix, ?ap_comp, ?wkm_snoc_cancel; crush.\nQed.\nHint Resolve wtRen_snoc_covar : ws.\n\nLemma wtRen_snoc_tmvar {Γ Δ ζ x τ} :\n  ⟨ ζ : Γ -> Δ ⟩ →\n  ⟨ x : τ[ζ] ∈ Δ ⟩ →\n  ⟨ ζ · x : Γ ▻ τ -> Δ ⟩.\nProof.\n  intros wζ wx; constructor; crush; repeat crushTypingMatchH;\n    rewrite <- ?ap_wkm_ix, ?ap_comp, ?wkm_snoc_cancel; crush.\nQed.\nHint Resolve wtRen_snoc_tmvar : ws.\n\nLemma wtRen_up_tyvar {Γ₁ Γ₂ ζ} (wζ: ⟨ ζ : Γ₁ -> Γ₂ ⟩) :\n  ∀ k, ⟨ ζ↑ : Γ₁ ► k -> Γ₂ ► k ⟩.\nProof. rewrite up_def. constructor; crush. Qed.\nHint Resolve wtRen_up_tyvar : ws.\n\nLemma wtRen_up_covar {Γ₁ Γ₂ ζ} (wζ: ⟨ ζ : Γ₁ -> Γ₂ ⟩) :\n  ∀ τ1 τ2 k, ⟨ ζ↑ : Γ₁ ◅ τ1 ~ τ2 ∷ k -> Γ₂ ◅ τ1[ζ] ~ τ2[ζ] ∷ k ⟩.\nProof.\n  rewrite up_def.\n  constructor; crush.\n  - inversion H; clear H; crush.\n  - inversion H; clear H; crush.\n    + rewrite <- ?(ap_wkm_ix (X:=Exp)), ?ap_comp.\n      rewrite ?wkm_snoc_cancel.\n      rewrite <- ?ap_comp, ?(ap_wkm_ix (X:=Exp)).\n      constructor.\n    + rewrite <- ?(ap_wkm_ix (X:=Exp)), ?ap_comp.\n      rewrite ?wkm_snoc_cancel.\n      rewrite <- ?ap_comp, ?(ap_wkm_ix (X:=Exp)).\n      constructor.\n      now apply (wtr_covar wζ).\n  - inversion H; clear H; crush.\n    rewrite <- (ap_wkm_ix (X:=Exp)), ap_comp.\n    rewrite wkm_snoc_cancel.\n    rewrite <- ap_comp, (ap_wkm_ix (X:=Exp)).\n    constructor.\n    now apply (wtr_tmvar wζ).\nQed.\nHint Resolve wtRen_up_covar : ws.\n\nLemma wtRen_up_tmvar {Γ₁ Γ₂ ζ} (wζ: ⟨ ζ : Γ₁ -> Γ₂ ⟩) :\n  ∀ τ, ⟨ ζ↑ : Γ₁ ▻ τ -> Γ₂ ▻ τ[ζ] ⟩.\nProof.\n  rewrite up_def.\n  constructor; crush.\n  - inversion H; clear H; crush.\n  - inversion H; clear H; crush.\n    rewrite <- ?(ap_wkm_ix (X:=Exp)), ?ap_comp.\n    rewrite ?wkm_snoc_cancel.\n    rewrite <- ?ap_comp, ?(ap_wkm_ix (X:=Exp)).\n    constructor.\n    now apply (wtr_covar wζ).\n  - inversion H; clear H; crush.\n    + rewrite <- ap_wkm_ix, ap_comp.\n      rewrite wkm_snoc_cancel.\n      rewrite <- ap_comp, ap_wkm_ix.\n      constructor.\n    + rewrite <- (ap_wkm_ix (X:=Exp)) , ap_comp.\n      rewrite wkm_snoc_cancel.\n      rewrite <- ap_comp, (ap_wkm_ix (X:=Exp)).\n      constructor.\n      now apply (wtr_tmvar wζ).\nQed.\nHint Resolve wtRen_up_tmvar : ws.\n\nLemma ty_ren {Γ τ k} (wτ: ⟨ Γ ⊢ τ ∷ k ⟩) :\n  ∀ Δ ζ, ⟨ ζ : Γ -> Δ ⟩ → ⟨ Δ ⊢ τ[ζ] ∷ k ⟩.\nProof. induction wτ; crush. Qed.\nHint Resolve ty_ren : ws.\n\nLemma co_ren {Γ γ τ1 τ2 k} (wγ: ⟨ Γ ⊢ γ : τ1 ~ τ2 ∷ k ⟩) :\n  ∀ Δ ζ, ⟨ ζ : Γ -> Δ ⟩ → ⟨ Δ ⊢ γ[ζ] : τ1[ζ] ~ τ2[ζ] ∷ k ⟩.\nProof.\n  induction wγ; intros ? ζ wζ; crush.\n  - rewrite <- ?ap_liftSub.\n    rewrite ?apply_beta1_comm.\n    rewrite ?up_liftSub.\n    rewrite ?ap_liftSub.\n    econstructor; eauto with ws.\n  - rewrite <- ?ap_liftSub.\n    rewrite ?apply_beta1_comm.\n    rewrite ?up_liftSub.\n    rewrite ?ap_liftSub.\n    econstructor; eauto with ws.\nQed.\nHint Resolve co_ren : ws.\n\nLemma red_ren {Γ γ τ1 τ2 k} (wγ: ⟨ Γ ⊢ γ : τ1 ↝ τ2 ∷ k ⟩) :\n  ∀ Δ ζ, ⟨ ζ : Γ -> Δ ⟩ → ⟨ Δ ⊢ γ[ζ] : τ1[ζ] ↝ τ2[ζ] ∷ k ⟩.\nProof.\n  induction wγ; intros ? ζ wζ; crush.\n  - rewrite <- ?ap_liftSub.\n    rewrite ?apply_beta1_comm.\n    rewrite ?up_liftSub.\n    rewrite ?ap_liftSub.\n    econstructor; eauto with ws.\nQed.\nHint Resolve red_ren : ws.\n\nLemma redstar_ren {Γ γs τ1 τ2 k} (wγ: ⟨ Γ ⊢ γs : τ1 ↝* τ2 ∷ k ⟩) :\n  ∀ Δ ζ, ⟨ ζ : Γ -> Δ ⟩ → ⟨ Δ ⊢ γs[ζ] : τ1[ζ] ↝* τ2[ζ] ∷ k ⟩.\nProof.\n  induction wγ; intros ? ζ wζ; crush.\nQed.\nHint Resolve redstar_ren : ws.\n\nLemma tm_ren {Γ s τ} (wt: ⟨ Γ ⊢ s : τ ⟩) :\n  ∀ Δ ζ, ⟨ ζ : Γ -> Δ ⟩ → ⟨ Δ ⊢ s[ζ] : τ[ζ] ⟩.\nProof.\n  induction wt; intros ? ζ wζ; crush.\n  - constructor; crush.\n    rewrite <- ap_wkm_ix.\n    rewrite apply_wkm_comm.\n    rewrite ap_wkm_ix.\n    apply IHwt; crush.\n  - constructor; crush.\n    rewrite <- ap_wkm_ix.\n    rewrite apply_wkm_comm.\n    rewrite ap_wkm_ix.\n    apply IHwt; crush.\n  - rewrite <- ?ap_liftSub.\n    rewrite apply_beta1_comm.\n    rewrite up_liftSub.\n    rewrite ?ap_liftSub.\n    crush.\n  - econstructor; crush.\nQed.\nHint Resolve tm_ren : ws.\n\n(*************************************************************************)\n\nLemma wtSub_closed ζ Δ : ⟨ ζ : nil => Δ ⟩.\nProof. constructor; inversion 1. Qed.\nHint Resolve wtSub_closed : ws.\n\nLemma wtSub_idm (Γ: Env) : ⟨ idm Exp : Γ => Γ ⟩.\nProof. constructor; crush. Qed.\nHint Resolve wtSub_idm : ws.\n\nLemma wtSub_wkm_tyvar Γ k :\n  ⟨ wkm Exp : Γ => Γ ► k ⟩.\nProof. constructor; crush. Qed.\nHint Resolve wtSub_wkm_tyvar : ws.\n\nLemma wtSub_wkm_covar Γ τ1 τ2 k :\n  ⟨ wkm Exp : Γ => Γ ◅ τ1 ~ τ2 ∷ k ⟩.\nProof. constructor; crush. Qed.\nHint Resolve wtSub_wkm_covar : ws.\n\nLemma wtSub_wkm_tmvar Γ τ :\n  ⟨ wkm Exp : Γ => Γ ▻ τ ⟩.\nProof. constructor; crush. Qed.\nHint Resolve wtSub_wkm_tmvar : ws.\n\nLemma wtSub_snoc_tyvar {Γ Δ ζ τ k} :\n  ⟨ ζ : Γ => Δ ⟩ →\n  ⟨ Δ ⊢ τ ∷ k ⟩ →\n  ⟨ ζ · τ : Γ ► k => Δ ⟩.\nProof.\n  intros wζ wx; constructor; crush; repeat crushTypingMatchH;\n    rewrite ?ap_comp, ?wkm_snoc_cancel; crush.\nQed.\nHint Resolve wtSub_snoc_tyvar : ws.\n\nLemma wtSub_snoc_covar {Γ Δ ζ γ τ1 τ2 k} :\n  ⟨ ζ : Γ => Δ ⟩ →\n  ⟨ Δ ⊢ γ : τ1[ζ] ~ τ2[ζ] ∷ k ⟩ →\n  ⟨ ζ · γ : Γ ◅ τ1 ~ τ2 ∷ k => Δ ⟩.\nProof.\n  intros wζ wx; constructor; crush; repeat crushTypingMatchH;\n    rewrite ?ap_comp, ?wkm_snoc_cancel; crush.\nQed.\nHint Resolve wtSub_snoc_covar : ws.\n\nLemma wtSub_snoc_tmvar {Γ Δ ζ s τ} :\n  ⟨ ζ : Γ => Δ ⟩ →\n  ⟨ Δ ⊢ s : τ[ζ] ⟩ →\n  ⟨ ζ · s : Γ ▻ τ => Δ ⟩.\nProof.\n  intros wζ wx; constructor; crush; repeat crushTypingMatchH;\n    rewrite ?ap_comp, ?wkm_snoc_cancel; crush.\nQed.\nHint Resolve wtSub_snoc_tmvar : ws.\n\nLemma wtSub_up_tyvar {Γ₁ Γ₂ ζ} (wζ: ⟨ ζ : Γ₁ => Γ₂ ⟩) :\n  ∀ k, ⟨ ζ↑ : Γ₁ ► k => Γ₂ ► k ⟩.\nProof.\n  rewrite up_def.\n  constructor; crush.\n  - inversion H; clear H; crush.\n    rewrite <- ap_wkm_ix; crush.\n  - inversion H; clear H; crush.\n    rewrite ?ap_comp.\n    rewrite ?wkm_snoc_cancel.\n    rewrite <- ?ap_comp.\n    rewrite <- ?(ap_wkm_ix (X:=Exp)).\n    crush.\n  - inversion H; clear H; crush.\n    rewrite ?ap_comp.\n    rewrite ?wkm_snoc_cancel.\n    rewrite <- ?ap_comp.\n    rewrite <- ?(ap_wkm_ix (X:=Exp)).\n    crush.\nQed.\nHint Resolve wtSub_up_tyvar : ws.\n\nLemma wtSub_up_covar {Γ₁ Γ₂ ζ} (wζ: ⟨ ζ : Γ₁ => Γ₂ ⟩) :\n  ∀ τ1 τ2 k, ⟨ ζ↑ : Γ₁ ◅ τ1 ~ τ2 ∷ k => Γ₂ ◅ τ1[ζ] ~ τ2[ζ] ∷ k ⟩.\nProof.\n  rewrite up_def.\n  constructor; crush.\n  - inversion H; clear H; crush.\n    rewrite <- ap_wkm_ix; crush.\n  - inversion H; clear H; crush.\n    + constructor.\n      rewrite ?ap_comp.\n      rewrite ?wkm_snoc_cancel.\n      rewrite <- ?ap_comp.\n      constructor.\n    + rewrite ?ap_comp.\n      rewrite ?wkm_snoc_cancel.\n      rewrite <- ?ap_comp.\n      rewrite <- ?(ap_wkm_ix (X:=Exp)).\n      crush.\n  - inversion H; clear H; crush.\n    rewrite ?ap_comp.\n    rewrite ?wkm_snoc_cancel.\n    rewrite <- ?ap_comp.\n    rewrite <- ?(ap_wkm_ix (X:=Exp)).\n    crush.\nQed.\nHint Resolve wtSub_up_covar : ws.\n\nLemma wtSub_up_tmvar {Γ₁ Γ₂ ζ} (wζ: ⟨ ζ : Γ₁ => Γ₂ ⟩) :\n  ∀ τ, ⟨ ζ↑ : Γ₁ ▻ τ => Γ₂ ▻ τ[ζ] ⟩.\nProof.\n  rewrite up_def.\n  constructor; crush.\n  - inversion H; clear H; crush.\n    rewrite <- ?(ap_wkm_ix (X:=Exp)).\n    crush.\n  - inversion H; clear H; crush.\n    rewrite ?ap_comp.\n    rewrite ?wkm_snoc_cancel.\n    rewrite <- ?ap_comp.\n    rewrite <- ?(ap_wkm_ix (X:=Exp)).\n    crush.\n  - inversion H; clear H; crush.\n    + rewrite ap_comp.\n      rewrite wkm_snoc_cancel.\n      rewrite <- ap_comp.\n      repeat constructor.\n    + rewrite ap_comp.\n      rewrite wkm_snoc_cancel.\n      rewrite <- ap_comp.\n      rewrite <- ?(ap_wkm_ix (X:=Exp)).\n      crush.\nQed.\nHint Resolve wtSub_up_tmvar : ws.\n\nLemma ty_sub {Γ τ k} (wτ: ⟨ Γ ⊢ τ ∷ k ⟩) :\n  ∀ Δ ζ, ⟨ ζ : Γ => Δ ⟩ → ⟨ Δ ⊢ τ[ζ] ∷ k ⟩.\nProof. induction wτ; crush. Qed.\nHint Resolve ty_sub : ws.\n\nLemma co_sub {Γ γ τ1 τ2 k} (wγ: ⟨ Γ ⊢ γ : τ1 ~ τ2 ∷ k ⟩) :\n  ∀ Δ ζ, ⟨ ζ : Γ => Δ ⟩ → ⟨ Δ ⊢ γ[ζ] : τ1[ζ] ~ τ2[ζ] ∷ k ⟩.\nProof. induction wγ; crush. Qed.\nHint Resolve co_sub : ws.\n\nLemma tm_sub {Γ s τ} (wt: ⟨ Γ ⊢ s : τ ⟩) :\n  ∀ Δ ζ, ⟨ ζ : Γ => Δ ⟩ → ⟨ Δ ⊢ s[ζ] : τ[ζ] ⟩.\nProof.\n  induction wt; intros ? ζ wζ; crush.\n  - constructor; crush.\n  - constructor; crush.\n  - econstructor; crush.\nQed.\nHint Resolve tm_sub : ws.\n", "meta": {"author": "skeuchel", "repo": "fomegac", "sha": "7a654d7c91d76caea9505090052046a51fbe9f3f", "save_path": "github-repos/coq/skeuchel-fomegac", "path": "github-repos/coq/skeuchel-fomegac/fomegac-7a654d7c91d76caea9505090052046a51fbe9f3f/FOmegaC/LemmasTyping.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2005531420953717}}
{"text": "Require Import RefProofDeps.\nRequire Import RData.\nRequire Import EventReplay.\nRequire Import MoverTypes.\nRequire Import Constants.\nRequire Import CommonLib.\nRequire Import RefTactics.\nRequire Import TableDataOpsIntro.Spec.\nRequire Import TableDataOpsRef2.Spec.\nRequire Import TableDataOpsRef3.Specs.data_destroy3.\nRequire Import TableDataOpsRef3.LowSpecs.data_destroy3.\nRequire Import TableDataOpsRef3.RefProof.RefRel.\n\nLocal Open Scope string_scope.\nLocal Open Scope Z_scope.\nLocal Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.\n\nSection Refine.\n\n  Hint Unfold\n       data_destroy_spec\n       data_destroy2_spec\n    .\n\n  Lemma data_destroy3_spec_exists:\n    forall habd habd'  labd g_rd map_addr res\n      (Hspec: data_destroy3_spec g_rd map_addr habd = Some (habd', res))\n      (Hrel: relate_RData habd labd),\n    exists labd', data_destroy3_spec0 g_rd map_addr labd = Some (labd', res) /\\ relate_RData habd' labd'.\n  Proof.\n    Local Opaque peq ptr_eq.\n    intros. duplicate Hrel. destruct D. clear hrepl lrepl. destruct g_rd.\n    unfold data_destroy3_spec, data_destroy3_spec0 in *.\n    unfold Assertion in *. rm_bind Hspec; rm_bind'. simpl in *.\n    unfold Assertion; rm_bind'; grewrite.\n    repeat simpl_hyp Hspec; extract_prop_dec; simpl_query_oracle; rm_bind'; grewrite.\n    - repeat destruct_con.\n      match type of Hcond6 with\n      | is_gidx ?gidx = true => remember gidx as lv1_gidx eqn:Hlv1_gidx; symmetry in Hlv1_gidx\n      end.\n      match type of Hcond3 with\n      | is_gidx ?gidx = true => remember gidx as lv2_gidx eqn:Hlv2_gidx; symmetry in Hlv2_gidx\n      end.\n      match type of Hcond0 with\n      | is_gidx ?gidx = true => remember gidx as llt_gidx eqn:Hllt_gidx; symmetry in Hllt_gidx\n      end.\n      match type of Prop0 with\n      | glock ?a @ ?gidx = None => remember gidx as data_gidx eqn:Hdata_gidx; symmetry in Hdata_gidx\n      end.\n      rewrite_oracle_rel rel_oracle C2; simpl in *.\n      repeat (grewrite; simpl).\n      assert(Hwalk: repl habd (oracle habd\n                                      (EVT CPU_ID (RTT_WALK (g_rtt (gnorm (gs (share habd)) @ z)) z0 3) :: oracle habd (log habd) ++ log habd))\n                         s {gs : (gs s) # llt_gidx == (((gs s) @ llt_gidx) {glock : Some CPU_ID})} =\n                    Some (s {gs : (gs s) # llt_gidx == (((gs s) @ llt_gidx) {glock : Some CPU_ID})})).\n      destruct Hrel. grewrite. destruct valid_ho0. rewrite Hright_log_nil. reflexivity.\n      eapply RightLogMover.\n      apply walk_right. omega. omega. apply RightLogOracle. simpl.\n      rewrite_oracle_rel rel_oracle Hwalk; simpl in *.\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n      rewrite <- Prop4. simpl_field.\n      assert(data_gidx <> llt_gidx). red; intro T; rewrite T in *. bool_rel. autounfold in *. omega.\n      repeat rewrite (zmap_comm _ _ H). repeat (try simpl_htarget; repeat simpl_field; repeat swap_fields).\n      reflexivity.\n    - repeat destruct_con.\n      match type of Hcond6 with\n      | is_gidx ?gidx = true => remember gidx as lv1_gidx eqn:Hlv1_gidx; symmetry in Hlv1_gidx\n      end.\n      match type of Hcond3 with\n      | is_gidx ?gidx = true => remember gidx as lv2_gidx eqn:Hlv2_gidx; symmetry in Hlv2_gidx\n      end.\n      match type of Hcond0 with\n      | is_gidx ?gidx = true => remember gidx as llt_gidx eqn:Hllt_gidx; symmetry in Hllt_gidx\n      end.\n      match type of Prop0 with\n      | glock ?a @ ?gidx = None => remember gidx as data_gidx eqn:Hdata_gidx; symmetry in Hdata_gidx\n      end.\n      rewrite_oracle_rel rel_oracle C2; simpl in *.\n      repeat (grewrite; simpl). simpl_htarget.\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity. simpl_htarget. reflexivity.\n    - repeat destruct_con.\n      match type of Hcond3 with\n      | is_gidx ?gidx = true => remember gidx as lv2_gidx eqn:Hlv2_gidx; symmetry in Hlv2_gidx\n      end.\n      match type of Hcond0 with\n      | is_gidx ?gidx = true => remember gidx as llt_gidx eqn:Hllt_gidx; symmetry in Hllt_gidx\n      end.\n      match type of Prop0 with\n      | glock ?a @ ?gidx = None => remember gidx as data_gidx eqn:Hdata_gidx; symmetry in Hdata_gidx\n      end.\n      rewrite_oracle_rel rel_oracle C2; simpl in *.\n      repeat (grewrite; simpl). simpl_htarget.\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n    - rewrite_oracle_rel rel_oracle C2.\n      repeat destruct_con.\n      match type of Hcond0 with\n      | is_gidx ?gidx = true => remember gidx as llt_gidx eqn:Hllt_gidx; symmetry in Hllt_gidx\n      end.\n      match type of Prop0 with\n      | glock ?a @ ?gidx = None => remember gidx as data_gidx eqn:Hdata_gidx; symmetry in Hdata_gidx\n      end.\n      repeat (grewrite; simpl).\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n    - rewrite_oracle_rel rel_oracle C2.\n      repeat (grewrite; simpl).\n      repeat (grewrite; try simpl_htarget; simpl).\n      inversion Hspec. eexists; split. reflexivity.\n      constructor; destruct Hrel; simpl; try assumption; try reflexivity.\n  Qed.\n\nEnd Refine.\n\n", "meta": {"author": "columbia", "repo": "osdi-paper196-ae", "sha": "6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496", "save_path": "github-repos/coq/columbia-osdi-paper196-ae", "path": "github-repos/coq/columbia-osdi-paper196-ae/osdi-paper196-ae-6df8f9e5b7b1e508a22327fd4a8c0c9be6c56496/proof/TableDataOpsRef3/RefProof/data_destroy3.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.20055314209537167}}
{"text": "From iris.algebra Require Import frac.\nFrom iris.proofmode Require Import tactics.\nRequire Import Eqdep_dec List.\nFrom cap_machine Require Import malloc macros.\nFrom cap_machine Require Import fundamental logrel macros_helpers rules proofmode.\nFrom cap_machine.examples Require Import template_adequacy.\nFrom cap_machine Require Import register_tactics.\nOpen Scope Z_scope.\n\n\n(** Exercise - the region is already allocated and the capability pointing to this\n    region is in R1. As a first step, the adversary code is known and just halts. *)\nSection base_program.\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ}\n          `{MP: MachineParameters}.\n\n  (** r_mem is the register that contains the capability pointing to\n      the allocated buffer\n      secret_off is the offset of the secret in the buffer\n      secret is the value stored in the buffer\n   *)\n  Definition prog_base_instrs r_mem (secret_off secret : Z) : list Word :=\n    encodeInstrsW [\n      Lea r_mem secret_off ;\n      Store r_mem secret ;\n      GetB r_t2 r_mem ;\n      GetE r_t3 r_mem ;\n      Add r_t2 r_t2 (secret_off + 1) ;\n      Subseg r_mem r_t2 r_t3\n      ].\n\n  (** Jump to the adversary in register r30 at the end of the program *)\n  Definition prog_code secret_off secret_val: list Word :=\n    prog_base_instrs r_t1 secret_off secret_val ++ encodeInstrsW [Jmp r_t30].\n\n  (** The adversary code is known --- it just halts *)\n  Definition adv_code : list Word :=\n    encodeInstrsW [ Halt ].\n\n  (** Specification of :\n      - executes the first part\n      - jump to the adversary\n      - halts\n   *)\n  Lemma prog_spec (a_adv: Addr)\n        p_pc b_pc e_pc a_prog (* pc *)\n        p_mem b_mem e_mem (* mem *)\n        secret_off secret_val\n        w2 w3 :\n    let secret := (b_mem^+secret_off)%a in\n    let len_p := (a_prog ^+ length (prog_code secret_off secret_val))%a in\n\n    ExecPCPerm p_pc ->\n    SubBounds b_pc e_pc a_prog len_p ->\n\n    (b_mem <= secret < e_mem)%a ->\n    writeAllowed p_mem = true ->\n\n    ⊢ ( (* PC points to prog_code*)\n        PC ↦ᵣ WCap p_pc b_pc e_pc a_prog\n        ∗ codefrag a_prog (prog_code secret_off secret_val)\n        (* r1 points to the allocated memory*)\n        ∗ r_t1 ↦ᵣ WCap p_mem b_mem e_mem b_mem\n        (* which is filled by zeroes *)\n        ∗ [[b_mem, e_mem]] ↦ₐ [[ region_addrs_zeroes b_mem e_mem ]]\n        (* r30 point to the adversary code *)\n        ∗ r_t30 ↦ᵣ WCap E a_adv (a_adv ^+ (length adv_code))%a a_adv\n        ∗ codefrag a_adv adv_code\n        ∗ r_t2 ↦ᵣ w2\n        ∗ r_t3 ↦ᵣ w3\n        -∗ WP Seq (Instr Executable) {{\n                λ v, ⌜v = HaltedV⌝ -∗ (* The machine is halted after the adversary *)\n                     r_t1 ↦ᵣ WCap p_mem (b_mem^+(secret_off+1))%a e_mem secret%a\n                     ∗ r_t2 ↦ᵣ WInt (b_mem+(secret_off +1))\n                     ∗ r_t3 ↦ᵣ WInt e_mem\n                     ∗ codefrag a_prog (prog_code secret_off secret_val)\n                     ∗ codefrag a_adv adv_code\n                     ∗ secret ↦ₐ WInt secret_val\n                     ∗ [[b_mem, secret]] ↦ₐ [[ region_addrs_zeroes b_mem secret]]\n                     ∗ [[(secret ^+1)%a, e_mem]] ↦ₐ [[ region_addrs_zeroes (secret^+1)%a e_mem ]]\n      }})%I.\n\n  Proof.\n    intros * Hpc_perm Hpc_bounds Hlen_mem Hp_mem.\n    iIntros \"(HPC& Hprog& Hr1& Hmem& Hr30& Hadv& Hr2& Hr3)\".\n\n    (* 1 - prepare the assertions for the proof *)\n    subst secret len_p.\n    (* Derives the facts from the codefrag *)\n    codefrag_facts \"Hprog\".\n    codefrag_facts \"Hadv\".\n    simpl in *.\n    rewrite /prog_code.\n    (* This assertion will be helpful seeral times during the proof *)\n    assert (Hp_mem': ~ p_mem = E)\n           by (intros -> ; simpl in Hp_mem ; discriminate).\n\n    (* 2 - Use the WP rules for each instructions *)\n    (* Lea r_t1 3 *)\n    iInstr \"Hprog\".\n    { transitivity (Some (b_mem ^+secret_off)%a) ; auto. solve_addr. }\n    (* Store r_t1 42 , where r_t1 = (RWX, b, e, secret) *)\n    (* The store requires the resource `secret ↦ₐ w` for some w,\n       we thus extract the resource from the memory buffer *)\n    rewrite (region_addrs_zeroes_split b_mem (b_mem ^+secret_off)%a e_mem)\n    ; [| solve_addr].\n    iDestruct (region_mapsto_split\n                 b_mem e_mem\n                 (b_mem ^+secret_off)%a\n                 (region_addrs_zeroes b_mem (b_mem ^+secret_off)%a)\n                 (region_addrs_zeroes (b_mem ^+secret_off)%a e_mem)\n                with \"Hmem\") as \"[Hmem Hmem']\".\n    { solve_addr. }\n    { unfold region_addrs_zeroes. by rewrite replicate_length. }\n    unfold region_addrs_zeroes at 2.\n    rewrite finz_dist_S ; [|solve_addr].\n    rewrite replicate_S.\n    iDestruct (region_mapsto_cons (b_mem ^+secret_off)%a _ e_mem (WInt 0)\n                                   (region_addrs_zeroes _ e_mem)\n                with \"Hmem'\") as \"[Hsecret Hmem']\".\n    { transitivity (Some (b_mem ^+(secret_off +1))%a) ; auto. solve_addr. }\n    { solve_addr. }\n    (* Now that we have the secret address, we can continue *)\n    iInstr \"Hprog\".\n    { solve_addr. }\n    (* getB, getE, add, subseg *)\n    iGo \"Hprog\".\n    { transitivity (Some (b_mem ^+(secret_off+1))%a) ; auto. solve_addr. }\n    { solve_addr. }\n    (* jmp *)\n    iInstr \"Hprog\".\n    (* halts in the adversary code *)\n    rewrite /adv_code.\n    iInstr \"Hadv\".\n\n    (* 3 - The machine is halted, prove that the post condition holds *)\n    wp_end.\n    iIntros \"_\".\n    replace ((b_mem ^+ secret_off) ^+ 1)%a with (b_mem ^+ (secret_off+1))%a by solve_addr.\n    iFrame.\n  Qed.\n\nEnd base_program.\n\n(** We use a CPS specification. We don't know the adversary code,\n    thus we stop the specification after the jump. We give only the necessary\n    ressources. *)\nSection base_program_CPS.\n\n  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ} {sealsg : sealStoreG Σ}\n          `{MP: MachineParameters}.\n\n  Local Ltac solve_addr' :=\n    repeat match goal with x := _ |- _ => subst x end\n    ; solve_addr.\n\n  Local Ltac iGo' hprog :=\n    repeat\n    (iGo hprog ;\n    try (\n    match goal with\n    | h: _ |- isCorrectPC _ =>\n        apply isCorrectPC_ExecPCPerm_InBounds ; auto; solve_addr'\n    end)\n    ; try solve_addr').\n\n  (** Specification of the program before the jump to the adversary.\n      The specification and the proof are essentially the same as the\n      previous one. *)\n  Lemma prog_base_spec\n        r_mem secret_off secret (* instantiation prog_base *)\n        p_pc b_pc e_pc s_prog (* pc *)\n        p_mem b_mem e_mem (* mem *)\n        w2 w3\n        φ :\n\n    let e_prog := (s_prog ^+ length (prog_base_instrs r_mem secret_off secret))%a in\n    let a_secret := (b_mem ^+ secret_off)%a in\n\n    (* Validity pc *)\n    ExecPCPerm p_pc ->\n    SubBounds b_pc e_pc s_prog e_prog ->\n\n    (* Validity buffer *)\n    ( b_mem <= a_secret < e_mem)%a ->\n    writeAllowed p_mem = true ->\n\n    (* Specification *)\n    ⊢ (( PC ↦ᵣ WCap p_pc b_pc e_pc s_prog\n         ∗ r_mem ↦ᵣ WCap p_mem b_mem e_mem b_mem\n         ∗ r_t2 ↦ᵣ w2\n         ∗ r_t3 ↦ᵣ w3\n         ∗ [[b_mem, e_mem]] ↦ₐ [[ region_addrs_zeroes b_mem e_mem ]]\n         ∗ codefrag s_prog (prog_base_instrs r_mem secret_off secret)\n         ∗ ▷ ( PC ↦ᵣ WCap p_pc b_pc e_pc e_prog\n               ∗ r_mem ↦ᵣ WCap p_mem (a_secret^+1)%a e_mem a_secret\n               ∗ r_t2 ↦ᵣ WInt (b_mem+secret_off+1)\n               ∗ r_t3 ↦ᵣ WInt e_mem\n               ∗ [[b_mem, a_secret]] ↦ₐ [[ region_addrs_zeroes b_mem a_secret ]]\n               ∗ a_secret ↦ₐ WInt secret\n               ∗ [[(a_secret ^+1)%a, e_mem]] ↦ₐ [[ region_addrs_zeroes (a_secret^+1)%a e_mem ]]\n               ∗ codefrag s_prog (prog_base_instrs r_mem secret_off secret)\n               -∗ WP Seq (Instr Executable) {{ φ }}))\n       -∗ WP Seq (Instr Executable) {{ φ }})%I.\n  Proof with (try solve_addr').\n    intros e_prog a_secret.\n    iIntros (Hpc_perm Hpc_bounds Hsecret_bounds Hp_mem)\n            \"(HPC & Hr_mem & Hr2 & Hr3 & Hmem & Hprog & Post)\".\n    rewrite /region_mapsto.\n    codefrag_facts \"Hprog\".\n    iGo' \"Hprog\".\n    { transitivity (Some (b_mem ^+ secret_off)%a) ; auto ; solve_addr'. }\n    { intros -> ; simpl in Hp_mem ; discriminate. }\n\n    rewrite (region_addrs_zeroes_split b_mem a_secret e_mem)...\n    iDestruct (region_mapsto_split\n                 b_mem e_mem\n                 a_secret\n                 (region_addrs_zeroes b_mem a_secret)\n                 (region_addrs_zeroes a_secret e_mem)\n                with \"Hmem\") as \"[Hmem Hmem']\"...\n    { unfold region_addrs_zeroes. by rewrite replicate_length. }\n    unfold region_addrs_zeroes at 4.\n    rewrite finz_dist_S...\n    rewrite replicate_S.\n    iDestruct (region_mapsto_cons a_secret (a_secret ^+1)%a e_mem (WInt 0)\n                                   (region_addrs_zeroes _ e_mem)\n                with \"Hmem'\") as \"[Hsecret Hmem']\"...\n    iGo' \"Hprog\".\n    (* getB getE add subseg *)\n    { transitivity (Some (b_mem ^+ (secret_off + 1))%a) ; auto... }\n    { intros -> ; simpl in Hp_mem ; discriminate. }\n    { solve_addr'. }\n\n    (* Post condition *)\n    iApply \"Post\".\n    subst e_prog; simpl in *.\n    replace (b_mem ^+ (secret_off + 1))%a with (a_secret ^+ 1)%a by solve_addr'.\n    replace (b_mem + secret_off + 1) with (b_mem + (secret_off + 1)) by lia.\n    iFrame.\n  Qed.\n    \n\n  (** Specification of the program until the jump to the unknown adversary code *)\n  Lemma prog_spec_CPS\n        wadv\n        p_pc b_pc e_pc a_prog (* pc *)\n        p_mem b_mem e_mem (* mem *)\n        w2 w3\n        secret_off secret_val\n        φ :\n    let secret := (b_mem^+secret_off)%a in\n    let len_p := (a_prog ^+ length (prog_code secret_off secret_val))%a in\n\n    ExecPCPerm p_pc ->\n    SubBounds b_pc e_pc a_prog len_p ->\n\n    (b_mem <= secret < e_mem)%a ->\n    writeAllowed p_mem = true ->\n\n    ⊢ ( (* PC points to prog_code*)\n        ( PC ↦ᵣ WCap p_pc b_pc e_pc a_prog\n        ∗ codefrag a_prog (prog_code secret_off secret_val)\n          (* r1 points to the allocated memory*)\n          ∗ r_t1 ↦ᵣ WCap p_mem b_mem e_mem b_mem\n          (* which is filled by zeroes *)\n          ∗ [[b_mem, e_mem]] ↦ₐ [[ region_addrs_zeroes b_mem e_mem ]]\n          (* r30 point to the adversary code *)\n          ∗ r_t30 ↦ᵣ wadv\n          ∗ r_t2 ↦ᵣ w2\n          ∗ r_t3 ↦ᵣ w3\n          ∗ ▷ ( PC ↦ᵣ updatePcPerm wadv (* The specification stops after the jump *)\n                ∗ r_t1 ↦ᵣ WCap p_mem (b_mem^+(secret_off+1))%a e_mem secret%a\n                ∗ r_t2 ↦ᵣ WInt (b_mem+(secret_off +1))\n                ∗ r_t3 ↦ᵣ WInt e_mem\n                ∗ r_t30 ↦ᵣ wadv\n                ∗ codefrag a_prog (prog_code secret_off secret_val)\n                ∗ [[(secret ^+1)%a, e_mem]] ↦ₐ [[ region_addrs_zeroes (secret^+1)%a e_mem ]]\n                -∗ WP Seq (Instr Executable) {{ φ }}))\n        -∗ WP Seq (Instr Executable) {{ φ }})%I.\n  Proof.\n    intros * Hpc_perm Hpc_bounds Hlen_mem Hp_mem.\n    iIntros \"(HPC& Hprog& Hr1& Hmem& Hr30& Hr2& Hr3& Post)\".\n    rewrite /prog_code.\n    codefrag_facts \"Hprog\".\n    focus_block_0 \"Hprog\" as \"Hprog\" \"Hcont\".\n    (* 1 - Specification from Lea to Subsug *)\n    iApply (prog_base_spec with \"[-]\")\n    ; try (iFrame ; iFrame \"#\")\n    ; eauto\n    ; try solve_addr'.\n    iNext ; iIntros \"(HPC & Hr1 & Hr2 & Hr3 & Hmem & Hsecret & Hmem' & Hprog)\".\n    unfocus_block \"Hprog\" \"Hcont\" as \"Hprog\".\n\n    (* 2 - Jump to the adversary *)\n    (* jmp *)\n    iInstr \"Hprog\".\n    (* 3 - Post condition *)\n    iApply \"Post\".\n    subst secret.\n    replace ((b_mem ^+ secret_off) ^+ 1)%a with (b_mem ^+ (secret_off+1))%a by solve_addr.\n    replace  (b_mem + secret_off + 1)%Z with (b_mem + (secret_off + 1))%Z by lia.\n    iFrame.\n  Qed.\n\n  Context {nainv: logrel_na_invs Σ}.\n\n  (** Assuming that the word of the adversary is safe to share,\n     the machine executes safely and completely.\n     The assumption makes sense, because we consider adversary programs containing\n     no capabilities. *)\n  Lemma prog_spec_CPS_full\n        p_pc b_pc e_pc a_prog (* pc *)\n        p_mem b_mem e_mem (* mem *)\n        w_adv\n        secret_off secret_val\n        rmap :\n\n    let secret := (b_mem^+secret_off)%a in\n    let len_p := (a_prog ^+ length (prog_code secret_off secret_val))%a in\n\n      (* Validity PC*)\n      ExecPCPerm p_pc ->\n      SubBounds b_pc e_pc a_prog len_p ->\n\n      (* Validity buffer *)\n      (b_mem <= secret < e_mem)%a ->\n      writeAllowed p_mem = true ->\n\n      (* Register map for the big_sep of registers *)\n      dom rmap = all_registers_s ∖ {[ PC; r_t1; r_t30 ]} →\n\n      ⊢ ( PC ↦ᵣ WCap p_pc b_pc e_pc a_prog\n          ∗ r_t1 ↦ᵣ WCap p_mem b_mem e_mem b_mem\n          ∗ r_t30 ↦ᵣ w_adv\n          ∗ codefrag a_prog (prog_code secret_off secret_val)\n          ∗ [[b_mem, e_mem]] ↦ₐ [[ region_addrs_zeroes b_mem e_mem ]]\n          (* All the registers contains integers *)\n          ∗ ([∗ map] r↦w ∈ rmap, r ↦ᵣ w ∗ ⌜is_z w = true⌝)\n          (* The NA token is required for the post condition *)\n          ∗ na_own logrel_nais ⊤\n          (* The adversary word is safe to share *)\n          ∗ interp w_adv\n          (* Post condition of the corollary of the FTLR *)\n          -∗ WP Seq (Instr Executable)\n                {{ v, ⌜v = HaltedV⌝ → (* if the machine halts *)\n                     (* we own all the registers *)\n                      ∃ r : Reg, full_map r ∧ registers_mapsto r\n                      (* all the NA invariants are closed*)\n                      ∗ na_own logrel_nais ⊤}})%I.\n\n  Proof.\n    intros * Hpc_perm Hpc_bounds Hvsecret Hp_mem Hrmap_dom.\n    iIntros \"(HPC & Hr1 & Hr30 & Hprog & Hregion & Hrmap & Hna & #Hadv)\".\n\n\n    (* Using the FLTR corollary, w_adv is safe to execute and we can specify\n       what happens after the jump: safe and complete execution *)\n    (* It is required to do it _before_ the specification, because it introduces a\n       later modality *)\n    iDestruct (jmp_to_unknown with \"Hadv\") as \"Cont\".\n\n    (* 1 - Specification of the known program *)\n    (* Extract the register r_t2 and r_t3, required for `prog_spec_CPS` *)\n\n    iExtractList \"Hrmap\" [r_t2;r_t3] as [\"[Hr2 _]\";\"[Hr3 _]\"].\n    (* extract_register r_t2 with \"Hrmap\" as (w2 Hw2) \"[[Hr2 _] Hrmap]\". *)\n    (* extract_register r_t3 with \"Hrmap\" as (w3 Hw3) \"[[Hr3 _] Hrmap]\". *)\n\n    iApply (prog_spec_CPS with \"[-]\") ; try eassumption.\n    iFrame \"HPC Hr1 Hr30 Hregion Hr2 Hr3 Hprog\".\n    iNext ; iIntros \"(HPC& Hr1& Hr2& Hr3 & Hr30 & Hprog & Hmem)\".\n\n    (* 2 - The continuation requires all the registers to be safe to share *)\n    (* Show that the contents of r1 are safe *)\n    replace ((b_mem ^+ secret_off) ^+ 1)%a\n      with (b_mem ^+ (secret_off+1))%a by (subst secret ; by solve_addr).\n    rewrite /region_mapsto.\n    iDestruct (region_integers_alloc' _ _ _ (b_mem ^+ secret_off)%a _ p_mem with \"Hmem\")\n      as \">#Hmem_safe\".\n    { rewrite /region_addrs_zeroes. apply Forall_replicate. auto. }\n\n    (* put the other registers back into the register map *)\n\n    iAssert ( ⌜is_z (WInt (b_mem + (secret_off + 1))) = true ⌝)%I as \"Hvr2\". auto.\n    iCombine \"Hr2 Hvr2\" as \"Hr2\".\n    iAssert ( ⌜is_z (WInt e_mem) = true ⌝)%I as \"Hvr3\". auto.\n    iCombine \"Hr3 Hvr3\" as \"Hr3\".\n    iInsertList \"Hrmap\" [r_t3;r_t2]. iClear \"Hvr2 Hvr3\".\n\n    (* Show that the contents of unused registers is safe *)\n    set (rmap' :=  <[r_t2:=WInt _]> (<[r_t3:= _]> rmap)).\n    iAssert ([∗ map] r↦w ∈ rmap', r ↦ᵣ w ∗ interp w)%I with \"[Hrmap]\" as \"Hrmap\".\n    { subst rmap'.\n      iApply (big_sepM_mono with \"Hrmap\"). intros r w Hr'. cbn. iIntros \"[? %Hw]\". iFrame.\n      destruct_word w; try by inversion Hw. rewrite fixpoint_interp1_eq //. }\n\n    (* put the registers with capability back into the register map *)\n    iCombine \"Hr1 Hmem_safe\" as \"Hr1\".\n    iCombine \"Hr30 Hadv\" as \"Hr30\".\n    subst rmap'; iInsertList \"Hrmap\" [r_t1;r_t30].\n\n    (* 3 - Use the continuation *)\n\n    (* Prepare the resources *)\n    iApply \"Cont\" ; eauto. 2 : iFrame.\n    iPureIntro. subst.\n    { do 2 (rewrite dom_insert_L).\n      assert (all_registers_s ∖ {[PC]} =\n                ({[r_t1; r_t30]} ∪ all_registers_s ∖ {[PC; r_t1; r_t30]})) as ->.\n      { rewrite - !difference_difference_L.\n        assert ( all_registers_s ∖ {[PC]} ∖ {[r_t1]} ∖ {[r_t30]} =\n                   all_registers_s ∖ {[PC]} ∖ {[r_t1; r_t30]})\n          as -> by (rewrite - !difference_difference_L ; set_solver).\n        rewrite -union_difference_L; auto.\n        apply subseteq_difference_r;[set_solver|].\n        apply all_registers_subseteq. }\n      set_solver. }\n\n    (* Alternative for (3) *)\n    (* iApply (wp_wand with \"[-]\"). *)\n    (* { iApply \"Cont\"; cycle 1. iFrame. iPureIntro. rewrite !dom_insert_L Hrmap_dom. *)\n    (*   rewrite !singleton_union_difference_L. set_solver+. } *)\n    (* iIntros (?) \"?\" ; done. *)\n  Qed.\n\n(** The encapsulation of the program is safe-to-share\n    By unfolding the definition of V(E,-,-,-) , we can use only persistent\n    proposition. Thus, all the required resources of the memory have to be\n    encapsulated in invariants. *)\n\n  Definition N : namespace := nroot .@ \"secret\".\n  Definition start_memN := (N.@\"start_mem\").\n  Definition secretN := (N.@\"secret\").\n  Definition end_memN := (N.@\"end_mem\").\n  Definition codeN := (N.@\"code\").\n\n  (* The first part of the buffer, before the secret, is always zeroes *)\n  Definition start_mem_inv (b_mem e_mem : Addr) secret_off:=\n    let secret_addr := (b_mem ^+ secret_off)%a in\n    na_inv logrel_nais start_memN\n           ([[b_mem, secret_addr]] ↦ₐ [[ region_addrs_zeroes b_mem secret_addr ]]).\n\n  (* The secret is either equal to 0 -- at the initialisation -- or equal to\n     42 -- after the secret was stored *)\n  Definition secret_inv (b_mem : Addr) secret_off secret :=\n    let secret_addr := (b_mem ^+ secret_off)%a in\n    na_inv logrel_nais secretN\n           ((secret_addr ↦ₐ WInt 0) ∨ (secret_addr ↦ₐ WInt secret)).\n\n  (* The code instruction is stored in an invariant as well *)\n  Definition code_inv a_prog secret_off secret :=\n    na_inv logrel_nais codeN (codefrag a_prog (prog_code secret_off secret)).\n\n  Definition end_mem_inv b_mem e_mem secret_off :=\n    let n_secret_addr := (b_mem ^+ (secret_off +1))%a in\n    na_inv logrel_nais end_memN\n           ([∗ list] a ∈ finz.seq_between n_secret_addr e_mem,\n            ∃ P, inv (logN .@ a) (interp_ref_inv a P) ∗ read_cond P interp\n                                                          ∗ write_cond P interp)%I.\n\n\n  (** Currently, we cannot prove the closure, because we need more information\n      about the buffer. Since the closure means \"called in any context\",\n      we cannot assume that the buffer is correctly set up in the context,\n      i.e. we cannot assume that the register r1 contains the capability\n      pointing to the buffer.\n\n      In order to get the right context, we may change our code. Here is 2\n      solutions:\n      - we assume that our program contains a capability pointing to our buffer,\n        we need to load the capability in R1 before our program. It corresponds\n        to a closure around the code and the buffer\n      - we dynamically allocate the buffer, by using the `malloc` macro.\n        It is different from the previous solution, because it allocates a new\n        buffer each time our program is called\n\n   *)\n  Lemma prog_CPS_safe_to_share b_pc e_pc a_prog b_mem e_mem secret_off secret :\n\n    (* The instructions of the code are in the memory closure of the PCC *)\n    SubBounds b_pc e_pc a_prog (a_prog ^+ length (prog_code secret_off secret))% a ->\n    (* The secret offset fits in the memory buffer *)\n    (b_mem <= b_mem ^+ secret_off < e_mem)%a ->\n\n    ⊢ ( code_inv a_prog secret_off secret\n       ∗ start_mem_inv b_mem e_mem secret_off\n       ∗ end_mem_inv b_mem e_mem secret_off\n       ∗ secret_inv b_mem secret_off secret)\n\n   -∗ interp (WCap E b_pc e_pc a_prog).\n  Abort.\n\nEnd base_program_CPS.\n", "meta": {"author": "logsem", "repo": "cerise", "sha": "a578f42e55e6beafdcdde27b533db6eaaef32920", "save_path": "github-repos/coq/logsem-cerise", "path": "github-repos/coq/logsem-cerise/cerise-a578f42e55e6beafdcdde27b533db6eaaef32920/theories/exercises/subseg_buffer.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.20055314209537164}}
{"text": "(**\n  This file contains an implementation of the example token that complies with the Concordium's CIS1 standard.\n  The development is inspired by the Rust implementation: https://github.com/Concordium/concordium-rust-smart-contracts/blob/b49a9f07131b2659de2f7b55eb5e8365d0ed4720/examples/cis1-wccd/src/lib.rs\n\n  We also show that the implementation of the token complies with our formalization of the CIS1 standard.\n*)\n\nFrom Coq Require Import ZArith.\nFrom Coq Require Import List.\nFrom Coq Require Import Logic.Eqdep_dec.\nFrom ConCert.Execution Require Import Monad.\nFrom ConCert.Execution Require Import Containers.\nFrom ConCert.Execution Require Import Serializable.\nFrom ConCert.Execution Require Import Blockchain.\nFrom ConCert.Execution Require Import ContractCommon.\nFrom ConCert.Examples.CIS1 Require Import CIS1Spec.\nFrom ConCert.Utils Require Import RecordUpdate.\nFrom ConCert.Utils Require Import Extras.\n\nImport ListNotations.\n\n\nDefinition requireTrue (cond : bool) :=\n  if cond then Some tt else None.\n\nSection WccdToken.\n  Context {BaseTypes : ChainBase}.\n  Set Nonrecursive Elimination Schemes.\n\n  (** Similarly to the Concordium implementation we use the smallest token id type, because\n      the contract hold tokens of only one type *)\n  Definition TokenID := unit.\n\n  Open Scope bool.\n\n  (** * Entry points *)\n\n  Record wccd_transfer_params :=\n    { wccd_td_token_id : TokenID;\n      wccd_td_amount   : TokenAmount;\n      wccd_td_from     : Address;\n      wccd_td_to       : Address }.\n\n  Inductive OpUpdateKind :=\n  | opAdd\n  | opDelete.\n\n  Inductive Msg :=\n  | wccd_msg_transfer (params : list wccd_transfer_params)\n  | wccd_msg_balanceOf (query : list Address) (send_results_to : Address)\n  | wccd_msg_updateOperator (params : list (OpUpdateKind * Address))\n  | wccd_msg_mint (receiver : Address)\n  | wccd_msg_burn (amount : TokenAmount).\n\n  (** * Contract's state *)\n\n  (** The state tracked for each address.*)\n  Record AddressState := {\n      wccd_balance   : TokenAmount;\n      wccd_operators : list Address\n    }.\n\n  (* begin hide *)\n  MetaCoq Run (make_setters AddressState).\n  (* end hide *)\n\n\n  (** The contract state: a mapping from addresses to [AddressState] *)\n\n  Definition State := AddressMap.AddrMap AddressState.\n\n  Section Serialization.\n\n    Global Instance OpUpdateKind_serializable : Serializable OpUpdateKind :=\n      Derive Serializable OpUpdateKind_rect <opAdd, opDelete>.\n\n    Global Instance state_serializable : Serializable AddressState :=\n      Derive Serializable AddressState_rect <Build_AddressState>.\n\n    Global Instance wccd_transfer_params_serializable : Serializable wccd_transfer_params :=\n      Derive Serializable wccd_transfer_params_rect <Build_wccd_transfer_params>.\n\n    Global Instance msg_serializable : Serializable Msg :=\n      Derive Serializable Msg_rect <wccd_msg_transfer, wccd_msg_balanceOf, wccd_msg_updateOperator, wccd_msg_mint, wccd_msg_burn>.\n\n  End Serialization.\n\n  (** * Transfer *)\n\n  Definition increment_balance (st : State) (addr : Address) (inc : TokenAmount) : State :=\n    match AddressMap.find addr st with\n    | Some old => AddressMap.add addr (old<| wccd_balance := old.(wccd_balance) + inc |>) st\n    | None => AddressMap.add addr {| wccd_balance := inc ; wccd_operators := [] |} st\n    end.\n\n  Definition decrement_balance (st : State) (addr : Address) (dec : TokenAmount) : option State :=\n    do old <- AddressMap.find addr st;\n    let old_balance := old.(wccd_balance) in\n    do requireTrue (dec <=? old_balance);\n    ret (AddressMap.add addr (old<| wccd_balance := old_balance - dec |>) st).\n\n\n  Definition is_operator (addr owner : Address)(st : State) : bool :=\n    match AddressMap.find owner st with\n    | Some v => existsb (fun x => (addr =? x)%address) v.(wccd_operators)\n    | None => false\n    end.\n\n  (** Single transfer of [amount] between [from] and [to] *)\n  Definition wccd_transfer_single\n             (token_id : TokenID)\n             (amount : TokenAmount)\n             (owner from to : Address)\n             (prev_st : State) : option State :=\n    do requireTrue ((owner =? from)%address || is_operator from owner prev_st);\n    do st <- decrement_balance prev_st from amount;\n    ret (increment_balance st to amount).\n\n  (** Batch execution of all transfers in the list. Note that the\n      operation succeeds only if all transfers in the batch succeed *)\n  Definition wccd_transfer (ctx : ContractCallContext) (transfers : list wccd_transfer_params) (prev_st : State)\n    : option State :=\n    monad_foldl (fun acc x =>\n                   let owner := ctx.(ctx_from) in\n                   wccd_transfer_single tt x.(wccd_td_amount) owner x.(wccd_td_from) x.(wccd_td_to) acc)\n                prev_st transfers.\n\n  (** * balanceOf *)\n\n  Definition get_balance_opt (addr : Address) (st : State) : option TokenAmount :=\n    match AddressMap.find addr st with\n    | Some data => Some data.(wccd_balance)\n    | None => None\n    end.\n\n  Definition wccd_balanceOf (query : list Address) (st : State)\n    : list (TokenID * Address * TokenAmount) :=\n    map (fun addr => (tt, addr, with_default 0 (get_balance_opt addr st))) query.\n\n  (** * updateOperator *)\n\n  Definition add_remove (operators : list Address) (param : OpUpdateKind * Address) :=\n    let '(updateKind,addr) := param in\n    match updateKind with\n    | opAdd => addr :: operators\n    | opDelete => remove address_eqdec addr operators\n    end.\n\n  (** NOTE: in contrast to the Concordium's implementation, we do not\n      allow adding operators to non-existing addresses *)\n  Definition wccd_updateOperator (owner : Address) (params : list (OpUpdateKind * Address)) (prev_st : State)\n    : option State :=\n    do owner_data <- AddressMap.find owner prev_st;\n    let updated_owner_data := owner_data<| wccd_operators := fold_left add_remove params owner_data.(wccd_operators) |> in\n    ret (AddressMap.add owner updated_owner_data prev_st).\n\n  (** * WCCD receive *)\n\n  (** We dispatch on a message of type [Msg] and call the corresponding functions with received parameters *)\n  Definition wccd_receive\n             (chain : Chain)\n             (ctx : ContractCallContext)\n             (prev_st : State)\n             (msg : option Msg)\n    : option (State * list ActionBody) :=\n    match msg with\n    | Some (wccd_msg_transfer params) =>\n        do next_st <- wccd_transfer ctx params prev_st;\n        let contract_accounts :=\n          filter (fun x => address_is_contract x.(wccd_td_to)) params in\n        let mk_callback x :=\n        (* NOTE: we assume that the receiving contract accepts messages of type\n           (TokenID * TokenAmount * Address) *)\n          act_call x.(wccd_td_to) 0 (serialize (tt,x.(wccd_td_amount), x.(wccd_td_from))) in\n        let ops := map mk_callback contract_accounts in\n        ret (next_st, ops)\n    | Some (wccd_msg_balanceOf query send_to) =>\n        let balances := wccd_balanceOf query prev_st in\n        do requireTrue (address_is_contract send_to);\n        ret (prev_st, [act_call send_to 0 (serialize balances)])\n    | Some (wccd_msg_updateOperator params) =>\n        do next_st <- wccd_updateOperator ctx.(ctx_from) params prev_st;\n        ret (next_st, [])\n    | Some (wccd_msg_mint receiver) =>\n        (* Check that the sender is not the receiver *)\n        do requireTrue (address_neqb receiver ctx.(ctx_from));\n        let next_st := increment_balance prev_st receiver (Z.to_nat ctx.(ctx_amount)) in\n        (* NOTE: we only update the state and do not notify the receiver *)\n        ret (next_st,[])\n    | Some (wccd_msg_burn amt) =>\n        (* Check that the sender is not the receiver *)\n        do next_st <- decrement_balance prev_st ctx.(ctx_from) amt;\n        ret (next_st, [act_transfer ctx.(ctx_from) (Z.of_nat amt)])\n    | None => None\n    end.\n\nEnd WccdToken.\n\n(** * WCCD complies with CIS1 *)\n\nModule WccdTypes <: CIS1Types.\n\n  Definition Msg `{ChainBase} := Msg.\n\n  Definition Storage `{ChainBase} := State.\n\n  Definition TokenID := TokenID.\n\n  Definition serializable_token_id : Serializable TokenID := _.\n\n  Definition token_id_eqb (id1 id2 : TokenID) := true.\n\n  Lemma token_id_eqb_spec :\n    forall (a b : TokenID), Bool.reflect (a = b) (token_id_eqb a b).\n  Proof. intros. constructor. now destruct a,b. Qed.\n\nEnd WccdTypes.\n\nModule WccdView <: CIS1View WccdTypes.\n\n  Import WccdTypes.\n\n  Section WccdViewDefs.\n\n    Context `{ChainBase}.\n\n    Definition get_balance_opt st (token_id : TokenID) addr :=\n      get_balance_opt addr st.\n\n    Definition get_operators (st : Storage) (addr : Address) :=\n      match AddressMap.find addr st with\n      | Some v => v.(wccd_operators)\n      | None => []\n      end.\n\n    Definition get_owners : Storage -> TokenID -> list Address :=\n      fun st token_id => FMap.keys st.\n\n    Lemma get_owners_no_dup : forall st token_id, NoDup (get_owners st token_id).\n    Proof.\n      intros. unfold get_owners; apply FMap.NoDup_keys.\n    Qed.\n\n    Lemma In_keys_In_elements_iff {K V : Type} `{countable.Countable K} (m : FMap K V) (k : K) :\n      In k (FMap.keys m) <-> exists v, In (k,v) (FMap.elements m).\n    Proof.\n      split.\n      - induction m using fin_maps.map_ind; intros Hin.\n        + easy.\n        + unfold FMap.keys in *.\n          rewrite FMap.elements_add in Hin by assumption.\n          cbn in *. destruct Hin.\n          * exists x. rewrite FMap.elements_add by assumption. now left.\n          * destruct (IHm H2) as [x0 Hx0]. exists x0.\n            rewrite FMap.elements_add by assumption.\n            now right.\n      - induction m using fin_maps.map_ind; intros Hex.\n        + now destruct Hex.\n        + destruct Hex as [v Hv].\n          unfold FMap.keys.\n          rewrite FMap.elements_add in * by assumption; cbn in *.\n          destruct Hv as [HH | HH]; try inversion HH; easy.\n    Qed.\n\n    Lemma get_owners_balances : forall st owner token_id,\n        In owner (get_owners st token_id) <->\n          exists balance, get_balance_opt st token_id owner = Some balance.\n    Proof.\n      split.\n      + intros Hin. unfold get_owners in *.\n        unfold get_balance_opt,Cis1wccd.get_balance_opt.\n        apply In_keys_In_elements_iff in Hin.\n        destruct Hin as [a_st HH].\n        exists a_st.(wccd_balance).\n        apply FMap.In_elements in HH.\n        unfold AddressMap.find,FMap.find in *.\n        now rewrite HH.\n      + intros Hex.\n        destruct Hex as [b Hb].\n        unfold get_owners, FMap.keys.\n        unfold get_balance_opt,Cis1wccd.get_balance_opt in *.\n        destruct (AddressMap.find owner st) eqn:Heq; try congruence.\n        unfold AddressMap.find in *.\n        apply FMap.In_elements in Heq.\n        apply In_keys_In_elements_iff.\n        eauto.\n    Qed.\n\n    Definition token_id_exists (st : Storage) (token_id : TokenID) : bool := true.\n\n  End WccdViewDefs.\nEnd WccdView.\n\nModule WccdReceiveSpec <: CIS1ReceiveSpec WccdTypes WccdView.\n\n  Module cis1_axioms := CIS1Axioms WccdTypes WccdView.\n  Import cis1_axioms.\n\n  Module BalancesFacts := CIS1Balances WccdTypes WccdView.\n  Import BalancesFacts.\n\n  Section WccdReceiveDefs.\n\n    Context `{ChainBase}.\n\n    (** Converting _to_ the CIS1 standard parameters *)\n    Definition to_cis1_transfer_data (p : wccd_transfer_params) : CIS1_transfer_data :=\n      let '(Build_wccd_transfer_params token_id amt from_addr to_addr) := p in\n      {| cis1_td_token_id := token_id;\n         cis1_td_amount := amt;\n         cis1_td_from := from_addr;\n         cis1_td_to := to_addr |}.\n\n    Definition to_cis1_updateOperator_kind (op : OpUpdateKind) : CIS1_updateOperator_kind :=\n      match op with\n      | opAdd => cis1_ou_add_operator\n      | opDelete => cis1_ou_remove_operator\n      end.\n\n    Definition to_cis1_balanceOf_params (query : list Address) (send_to : Address)\n      : option CIS1_balanceOf_params :=\n      match Bool.bool_dec (address_is_contract send_to) true with\n      | left p =>\n          Some {|cis1_bo_query := map (fun addr => Build_CIS1_balanceOf_query _ tt addr) query;\n                 cis1_bo_result_address := send_to;\n                 cis1_bo_result_address_is_contract := p |}\n      | right _ => None\n      end.\n\n    Definition get_CIS1_entry_point : Msg -> option CIS1_entry_points :=\n      fun msg => match msg with\n              | wccd_msg_transfer params =>\n                  let params :=\n                    {| cis_tr_transfers := map to_cis1_transfer_data params|} in\n                  Some (CIS1_transfer params)\n              | wccd_msg_balanceOf query send_results_to =>\n                  do p <- to_cis1_balanceOf_params query send_results_to;\n                  Some (CIS1_balanceOf p)\n              | wccd_msg_updateOperator params =>\n                  let upd_list :=\n                    map (fun '(upd_kind, addr) =>\n                           Build_CIS1_updateOperator_update _ (to_cis1_updateOperator_kind upd_kind) addr) params in\n                  Some (CIS1_updateOperator {| cis1_ou_params := upd_list |})\n              | wccd_msg_mint receiver => None\n              | wccd_msg_burn amount => None\n              end.\n\n    (** Converting _from_ the CIS1 standard parameters *)\n\n    Definition from_cis1_transfer_data (p : CIS1_transfer_data) : wccd_transfer_params :=\n      let '(Build_CIS1_transfer_data _ token_id amt from_addr to_addr) := p in\n      {| wccd_td_token_id := tt;\n         wccd_td_amount := amt;\n         wccd_td_from := from_addr;\n         wccd_td_to := to_addr |}.\n\n    Definition from_cis1_updateOperator_kind (op : CIS1_updateOperator_kind) : OpUpdateKind :=\n      match op with\n      | cis1_ou_remove_operator => opDelete\n      | cis1_ou_add_operator => opAdd\n      end.\n\n    Definition from_cis1_balanceOf_params (query : CIS1_balanceOf_params) : list Address :=\n      map cis1_bo_query_address query.(cis1_bo_query).\n\n    Definition get_contract_msg : CIS1_entry_points -> Msg :=\n      fun ep => match ep with\n             | CIS1_transfer params =>\n                 wccd_msg_transfer (map from_cis1_transfer_data params.(cis_tr_transfers))\n             | CIS1_updateOperator params =>\n                 let p := map (fun p => (from_cis1_updateOperator_kind p.(cis1_ou_update_kind), p.(cis1_ou_operator_address))) params.(cis1_ou_params) in\n                 wccd_msg_updateOperator p\n             | CIS1_balanceOf params =>\n                 wccd_msg_balanceOf (from_cis1_balanceOf_params params)\n                                    params.(cis1_bo_result_address)\n             end.\n\n    Lemma left_inverse_get_CIS1_entry_point (entry_point : CIS1_entry_points) :\n      get_CIS1_entry_point (get_contract_msg entry_point) = Some entry_point.\n    Proof.\n      destruct entry_point; cbn.\n      + destruct params as [xs]. repeat f_equal.\n        induction xs; auto.\n        cbn. destruct a as [tid ? ?]; cbn in *. destruct tid. repeat f_equal; auto.\n      + destruct params as [xs]. repeat f_equal.\n        rewrite map_map.\n        induction xs; auto.\n        destruct a as [ok ?]; cbn in *. destruct ok; repeat f_equal; auto.\n      + destruct params as [xs send_to p]; cbn in *.\n        unfold to_cis1_balanceOf_params.\n        destruct (Bool.bool_dec (address_is_contract send_to) true) eqn:Heq; repeat f_equal.\n        * induction xs; cbn in *; auto.\n          destruct a as [tid ?]; destruct tid; cbn; now repeat f_equal.\n        * apply UIP_dec. apply Bool.bool_dec.\n        * congruence.\n    Qed.\n\n    Lemma inctement_balance_find_ne st addr1 addr2 amt :\n      addr1 <> addr2 ->\n      AddressMap.find addr1 (increment_balance st addr2 amt) = AddressMap.find addr1 st.\n    Proof.\n      intros Hneq.\n      unfold increment_balance.\n      destruct (AddressMap.find addr2 _);\n        unfold AddressMap.add, AddressMap.find;\n        now rewrite fin_maps.lookup_insert_ne.\n    Qed.\n\n    Import Lia.\n\n    Lemma wccd_transfer_single_cis1 (token_id : TokenID)\n          (amt : TokenAmount) (owner_addr from_addr to_addr : Address)\n          (prev_st st : State) :\n      wccd_transfer_single token_id amt owner_addr from_addr to_addr prev_st = Some st ->\n      transfer_single_spec prev_st st token_id eq_refl eq_refl owner_addr from_addr to_addr amt.\n    Proof.\n      intros Haddr.\n      cbn in *.\n      destruct (requireTrue (_ || _)) eqn:Hpermissions; try congruence.\n      destruct (AddressMap.find _ _) as [v |] eqn:Hv; try congruence.\n      destruct (requireTrue (_ <=? _)) eqn:Hbalance; try congruence.\n      inversion Haddr; subst; clear Haddr.\n      destruct (amt <=? wccd_balance v) eqn:Hamt; cbn in *; try congruence.\n      apply leb_complete in Hamt.\n      repeat split; cbn.\n      + intros.\n        unfold setter_from_getter_AddressState_wccd_balance,set_AddressState_wccd_balance.\n        unfold WccdView.get_balance_opt, get_balance_opt.\n        rewrite inctement_balance_find_ne by assumption.\n        unfold AddressMap.find,AddressMap.add.\n        now erewrite fin_maps.lookup_insert_ne.\n      + intros. now destruct other_token_id,token_id.\n      + unfold requireTrue in *. destruct (orb _ _) eqn:Hp; try congruence.\n        rewrite Bool.orb_true_iff in *.\n        destruct Hp as [Hp | Hp].\n        * now destruct (address_eqb_spec owner_addr from_addr).\n        * right.\n          unfold is_operator in *.\n          unfold WccdView.get_operators.\n          destruct (AddressMap.find owner_addr prev_st) eqn:Hfind; try congruence.\n          apply existsb_exists in Hp.\n          destruct Hp as [addr0 [Hin Heq]].\n          now destruct (address_eqb_spec from_addr addr0).\n      + repeat rewrite get_balance_total_get_balance_default.\n        repeat unfold setter_from_getter_AddressState_wccd_balance,\n          set_AddressState_wccd_balance,increment_balance.\n        unfold get_balance_default,cis1_axioms.VExtra.get_balance in *. cbn.\n        unfold setter_from_getter_AddressState_wccd_balance,set_AddressState_wccd_balance.\n        destruct (AddressMap.find to_addr _) eqn:Haddr.\n        * unfold WccdView.get_balance_opt,get_balance_opt,AddressMap.find,AddressMap.add in *.\n          rewrite Hv.\n          rewrite FMap.add_commute with (m := prev_st) by auto.\n          rewrite FMap.find_add with (m := (FMap.add _ _ prev_st)); cbn.\n          lia.\n        * unfold WccdView.get_balance_opt,get_balance_opt,AddressMap.find,AddressMap.add in *.\n          rewrite FMap.add_commute with (m := prev_st) by auto.\n          rewrite FMap.find_add with (m := (FMap.add _ _ prev_st)).\n          cbn. rewrite Hv.\n          lia.\n      + repeat rewrite get_balance_total_get_balance_default.\n        repeat unfold setter_from_getter_AddressState_wccd_balance,\n          set_AddressState_wccd_balance,increment_balance.\n        unfold get_balance_default,cis1_axioms.VExtra.get_balance in *. cbn.\n        unfold setter_from_getter_AddressState_wccd_balance,set_AddressState_wccd_balance.\n        destruct (AddressMap.find to_addr _) eqn:Haddr.\n        * unfold WccdView.get_balance_opt,get_balance_opt,AddressMap.find,AddressMap.add in *.\n          rewrite FMap.find_add with (m := (FMap.add _ _ prev_st)); cbn.\n          rewrite FMap.find_add_ne with (m := prev_st) in Haddr by auto.\n          unfold FMap.find in *.\n          now rewrite Haddr.\n        * unfold WccdView.get_balance_opt,get_balance_opt,AddressMap.find,AddressMap.add in *.\n          rewrite FMap.find_add with (m := (FMap.add _ _ prev_st)); cbn.\n          rewrite FMap.find_add_ne with (m := prev_st) in Haddr by auto.\n          unfold FMap.find in *.\n          now rewrite Haddr.\n      + subst. repeat rewrite get_balance_total_get_balance_default.\n        repeat unfold setter_from_getter_AddressState_wccd_balance,\n          set_AddressState_wccd_balance,increment_balance.\n        unfold get_balance_default,cis1_axioms.VExtra.get_balance in *. cbn.\n        unfold setter_from_getter_AddressState_wccd_balance,set_AddressState_wccd_balance.\n        unfold WccdView.get_balance_opt,get_balance_opt. now rewrite Hv.\n      + subst.\n        repeat rewrite get_balance_total_get_balance_default.\n        repeat unfold setter_from_getter_AddressState_wccd_balance,\n          set_AddressState_wccd_balance,increment_balance.\n        unfold get_balance_default,cis1_axioms.VExtra.get_balance in *. cbn.\n        unfold WccdView.get_balance_opt,get_balance_opt.\n        rewrite Hv.\n        unfold AddressMap.find,AddressMap.add.\n        rewrite FMap.find_add with (m := prev_st); cbn.\n        rewrite FMap.find_add with (m := FMap.add _ _ prev_st); cbn.\n        lia.\n    Qed.\n\n    Definition contract_receive := wccd_receive.\n\n    Lemma get_balances_wccd_balanceOf next_st c query send_results_to :\n      to_cis1_balanceOf_params query send_results_to = Some c ->\n      get_balances next_st c = Some (wccd_balanceOf query next_st).\n    Proof.\n      intros Hparams.\n      unfold to_cis1_balanceOf_params in *.\n      destruct (Bool.bool_dec (address_is_contract send_results_to)) eqn:Haddr;\n        inversion Hparams; subst; clear Hparams.\n      cbn.\n      revert dependent next_st.\n      revert dependent send_results_to.\n      induction query.\n      - now intros ? ? ? Hparams; cbn in *.\n      - intros. cbn.\n        erewrite IHquery; eauto.\n        unfold WccdView.get_balance_opt.\n        now destruct (get_balance_opt _ _).\n    Qed.\n\n    (** ** Receive specification *)\n    Theorem receive_spec :\n    forall (chain : Chain)\n      (ctx : ContractCallContext)\n      (entry : CIS1_entry_points)\n      (msg : Msg)\n      (prev_st next_st : State)\n      (ops : list ActionBody),\n      get_CIS1_entry_point msg = Some entry ->\n      wccd_receive chain ctx prev_st (Some msg) = Some (next_st, ops) ->\n      match entry with\n      | CIS1_transfer params => transfer_spec ctx params prev_st next_st ops\n      | CIS1_updateOperator params => updateOperator_spec ctx params prev_st next_st ops\n      | CIS1_balanceOf params => balanceOf_spec params prev_st next_st ops\n      end.\n    Proof.\n      intros ? ? ? ? ? ? ? Hep Hreceive.\n      destruct msg; cbn; inversion Hep as [HH]; subst; clear Hep; try easy.\n      + simpl in *.\n        destruct (wccd_transfer _ _) eqn:Htr; try congruence.\n        inversion Hreceive; subst; clear Hreceive.\n        constructor.\n        * cbn.\n          revert dependent next_st.\n          revert dependent prev_st.\n          induction params.\n          ** cbn in *. congruence.\n          ** intros prev_st next_st Hreceive.\n             cbn -[wccd_transfer_single] in *.\n             destruct (wccd_transfer_single _ _ _ _ _) as [st |] eqn:Haddr; try congruence.\n             destruct a as [tid amt from_addr to_addr]; cbn.\n             simpl in *.\n             exists st, eq_refl, eq_refl.\n             split.\n             *** cbn in *. now apply wccd_transfer_single_cis1.\n             *** now eapply IHparams.\n        * cbn.\n          revert dependent prev_st.\n          revert dependent next_st.\n          induction params.\n          ** intros; cbn; auto.\n          ** intros; cbn -[wccd_transfer_single] in *.\n             destruct (wccd_transfer_single _ _ _ _ _) as [st |] eqn:Haddr; try congruence.\n             destruct a as [token_id amt addr]; cbn.\n             destruct (address_is_contract _).\n             *** constructor; simpl in *.\n                 eexists. split.\n                 **** reflexivity.\n                 **** destruct token_id.\n                      exists (TokenID * TokenAmount * Address)%type. exists _. exists id.\n                      eexists. split.\n                      apply deserialize_serialize.\n                      reflexivity.\n                 **** eapply IHparams; eauto.\n             *** eapply IHparams; eauto.\n      + simpl in *.\n        destruct (address_is_contract send_results_to) eqn:Haddr;\n          inversion Hreceive; subst; clear Hreceive; cbn in *.\n        destruct (to_cis1_balanceOf_params _ _) eqn:Hto_cis1; inversion HH; subst; clear HH.\n        constructor; subst; auto.\n        erewrite get_balances_wccd_balanceOf; eauto.\n        cbn. repeat f_equal.\n        unfold to_cis1_balanceOf_params in *.\n        destruct (Bool.bool_dec (address_is_contract send_results_to)) eqn:HH;\n          now inversion Hto_cis1.\n      + cbn in *.\n        unfold setter_from_getter_AddressState_wccd_operators,set_AddressState_wccd_operators in *.\n        constructor; intros; cbn in *; auto.\n        * unfold WccdView.get_balance_opt,get_balance_opt.\n          destruct (AddressMap.find _ _) eqn:Haddr; inversion Hreceive; subst; clear Hreceive.\n          destruct (address_eqb_spec addr ctx.(ctx_from)).\n          ** subst.\n             rewrite Haddr.\n             unfold AddressMap.find,AddressMap.add.\n             now rewrite FMap.find_add with (m := prev_st).\n          ** unfold AddressMap.find,AddressMap.add.\n             now rewrite fin_maps.lookup_insert_ne.\n        * destruct (AddressMap.find _ _) eqn:Haddr; inversion Hreceive; subst; clear Hreceive.\n          destruct a as [bal ops]; cbn in *.\n          revert dependent ops.\n          revert dependent prev_st.\n          induction params; intros prev_st ops Haddr.\n          ** cbn.\n             unfold AddressMap.add,AddressMap.find in *.\n             now symmetry; apply FMap.add_id.\n          ** cbn.\n             unfold AddressMap.add,AddressMap.find in *.\n             destruct a as [ok oaddr]; cbn in *.\n             unfold updateOperator_single_spec; cbn.\n             destruct ok; cbn in *.\n             *** set (st := FMap.add (ctx_from ctx)\n                                     {| wccd_balance := bal;\n                                       wccd_operators := oaddr :: ops |} prev_st).\n                 exists st. split.\n                 **** split.\n                      ***** intros.\n                      subst st. unfold WccdView.get_operators,AddressMap.find.\n                      rewrite Haddr. rewrite FMap.find_add with (m := prev_st).\n                      cbn.\n                      split; intros; auto. destruct H1; subst; congruence.\n                      ***** subst st. unfold WccdView.get_operators,AddressMap.find.\n                      now rewrite FMap.find_add with (m := prev_st); cbn.\n                 **** set (ops' := oaddr :: ops).\n                      specialize (IHparams st ops'). subst ops' st; cbn in *.\n                      repeat rewrite FMap.add_add with (m := prev_st)in IHparams.\n                      apply IHparams.\n                      now rewrite FMap.find_add with (m := prev_st).\n             *** set (st := FMap.add (ctx_from ctx)\n                                     {| wccd_balance := bal;\n                                        wccd_operators := remove address_eqdec oaddr ops |} prev_st).\n                 exists st. split.\n                 **** split.\n                      (* the cases are essentially just properties of [remove], which we\n                         prove using the [hint] database *)\n                      ***** intros.\n                      subst st. unfold WccdView.get_operators,AddressMap.find.\n                      rewrite Haddr. rewrite FMap.find_add with (m := prev_st).\n                      cbn.\n                      split; intros; eauto with hints.\n                      ***** subst st. unfold WccdView.get_operators,AddressMap.find.\n                      rewrite FMap.find_add with (m := prev_st); cbn; auto with hints.\n                 **** set (ops' := remove address_eqdec oaddr ops).\n                      specialize (IHparams st ops'). subst ops' st; cbn in *.\n                      repeat rewrite FMap.add_add with (m := prev_st)in IHparams.\n                      apply IHparams.\n                      now rewrite FMap.find_add with (m := prev_st).\n    Qed.\n  End WccdReceiveDefs.\nEnd WccdReceiveSpec.\n", "meta": {"author": "AU-COBRA", "repo": "ConCert", "sha": "55ffd996fe89d41677a2ff368d3a5e4be1e997b7", "save_path": "github-repos/coq/AU-COBRA-ConCert", "path": "github-repos/coq/AU-COBRA-ConCert/ConCert-55ffd996fe89d41677a2ff368d3a5e4be1e997b7/examples/cis1/Cis1wccd.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.3665897501624599, "lm_q1q2_score": 0.20042860795520623}}
{"text": "From machine_program_logic.program_logic Require Import weakestpre.\nFrom HypVeri.algebra Require Import base base_extra mem pagetable trans.\nFrom HypVeri.rules Require Import rules_base mov halt run yield ldr str br.\nFrom HypVeri.examples Require Import instr utils.\nFrom HypVeri.logrel Require Import logrel logrel_extra fundamental logrel_prim logrel_prim_extra fundamental_prim.\nFrom HypVeri Require Import proofmode machine_extra.\nRequire Import Setoid.\n\nProgram Instance up_vmconfig : HypervisorConstants :=\n    {vm_count := 4;\n     vm_count_pos := _;\n     valid_handles := {[W0]}}.\n\nSection up_proof.\n\nProgram Definition V1 : VMID := (@nat_to_fin 1 _ _).\nProgram Definition V2 : VMID := (@nat_to_fin 2 _ _).\nProgram Definition V3 : VMID := (@nat_to_fin 3 _ _).\n\nProgram Definition fortytwo : Imm := I (finz.FinZ 42 _ _) _.\n\n  Context `{hypparams: !HypervisorParameters}.\n  Context (pshare:PID) (pshare_i: Imm) (Hpshare_eq: of_pid pshare = pshare_i).\n  Context (pprog0 pprog1 pprog2 pprog3:PID).\n  Context (ptx1 ptx3 prx1 prx3 :PID).\n  Context (ptx0 ptx2 prx0 prx2 :PID).\n  Context (Hps_nd: NoDup [pprog0;pprog1;pprog2;pprog3;pshare;ptx0;ptx1;ptx2;ptx3;prx0;prx1;prx2;prx3]).\n  Context (pprog3_i : Imm) (Hpprog3_eq : of_pid pprog3 = pprog3_i).\n\n  Definition up_program1 (jump : Imm) : list Word :=\n    [\n      (* Store 42 to shared page *)\n      mov_word_I R1 fortytwo;\n      mov_word_I R2 pshare_i;\n      str_I R1 R2;\n      (* addr to jump *)\n      mov_word_I R2 jump;\n      mov_word_I R0 yield_I;\n      hvc_I;\n      br_I R2\n    ].\n\n\n  Definition up_program3 : list Word :=\n    [\n      (* read 42 from shared page *)\n      mov_word_I R2 pshare_i;\n      mov_word_I R0 pprog3_i;\n      ldr_I R1 R2;\n      cmp_word_I R1 fortytwo;\n      bne_I R0;\n      halt_I\n    ].\n\n  Class exclG Σ :=\n    excl_G :> inG Σ (exclR unitO).\n  Definition exclΣ : gFunctors :=\n    #[ GFunctor (exclR unitO)].\n\n  Instance subG_issuedΣ {Σ} : subG exclΣ Σ → exclG Σ.\n  Proof. solve_inG. Qed.\n\n\n  Context `{!gen_VMG Σ, !exclG Σ} (N : namespace).\n\n  Definition EXCL γ : iProp Σ := (own γ (Excl ()))%I.\n  Lemma excl_exclusive (γ : gname) : EXCL γ  -∗ EXCL γ  -∗ False.\n  Proof.\n    iDestruct 1 as  \"H1\". iDestruct 1 as  \"H2\".\n    iDestruct (own_valid_2 with \"H1 H2\") as %[].\n  Qed.\n\n\n  (* don't transfer anything if i,j = 1,3 or 3,1 *)\n  Definition up_slice_trans trans i j : iProp Σ :=\n    match (bool_decide (i = V1)), (bool_decide (j = V3)) with\n    | true, true => True\n    | _, _ => match (bool_decide (i = V3)), (bool_decide (j = V1)) with\n           | true, true => True\n           | _, _ => slice_transfer_all trans i j\n           end\n    end.\n\n  Definition up_slice_rxs i os j : iProp Σ :=\n    (match os with\n    | None => True\n    | Some (_, k) => if (bool_decide (k=V0)) then\n                       (if (bool_decide (j = V0)) then\n                          slice_rx_state i os\n                        else if (bool_decide (i = j)) then\n                               slice_rx_state i os\n                             else True)\n                     else slice_rx_state i os\n    end)%I.\n\n  Instance up_slice_trans_wf : SliceTransWf up_slice_trans.\n  Proof.\n    rewrite /up_slice_trans /=.\n    split.\n    intros.\n    case_bool_decide;\n    case_bool_decide;auto.\n    subst i. simpl. by apply slice_transfer_all_wf.\n    case_bool_decide;auto.\n    subst i. simpl. by apply slice_transfer_all_wf.\n    by apply slice_transfer_all_wf.\n  Qed.\n\n  Instance up_slice_rxs_wf : SliceRxsWf up_slice_rxs.\n  Proof.\n    rewrite /up_slice_rxs /=.\n    split. done.\n    intros.\n    destruct os;auto.\n    destruct p. intros.\n    case_bool_decide;auto.\n    case_bool_decide;auto.\n    done. done.\n  Qed.\n\n\n  Notation VMProp1 := (vmprop_unknown V1 up_slice_trans up_slice_rxs {[W0 := (V1, V3, {[pshare]}, Sharing, true)]}) (only parsing).\n  Notation VMProp3 := (vmprop_unknown V3 up_slice_trans up_slice_rxs {[W0 := (V1, V3, {[pshare]}, Sharing, true)]}) (only parsing).\n\n\n  Class SliceWfPrim Φ_t Φ_r :=\n    {\n     trans_wf_prim : ∀ i j trans, (i = V0 ∨ j = V0) -> Φ_t trans i j ⊣⊢ slice_transfer_all trans i j;\n     rxs_wf_prim_diag : ∀ i os, (match os with\n                 | None => True\n                 | Some (_,j) => j = V0 -> Φ_r i os i ⊣⊢ slice_rx_state i os\n                end);\n     rxs_wf_prim_eq: ∀ i os, match os with\n               | None => True\n               | Some (_ ,k) => k = V0\n               end -> Φ_r i os i ⊣⊢ Φ_r i os V0;\n     rxs_wf_prim_none : ∀ i j os, (match os with\n                 | None => True\n                 | Some (_,j) => j = V0\n                end) -> j ≠ i -> j ≠ V0 -> Φ_r i os j ⊣⊢ True;\n     rxs_wf_prim_zero: ∀ os, (match os with\n              | None => True\n              | _ => Φ_r V0 os V0 ⊣⊢ slice_rx_state V0 os\n              end);\n    }.\n\n  Global Instance up_slice_wf: SliceWfPrim up_slice_trans up_slice_rxs.\n  Proof.\n    split;rewrite /up_slice_trans /up_slice_rxs.\n    {\n      intros ? ? ? [|].\n      case_bool_decide. subst i. done.\n      case_bool_decide. subst i. done.\n      done.\n      case_bool_decide.\n      case_bool_decide. subst j. done.\n      case_bool_decide. subst j. done.\n      done.\n      case_bool_decide;auto.\n      case_bool_decide;auto.\n      subst j. done.\n    }\n    {\n      intros.\n      destruct os. destruct p. intro.\n      case_bool_decide;auto.\n      case_bool_decide;auto.\n      case_bool_decide;auto.\n      done. done.\n    }\n    {\n      intros.\n      destruct os;auto. destruct p.\n      case_bool_decide;auto.\n      case_bool_decide;auto.\n      case_bool_decide;auto.\n      done.\n    }\n    {\n      intros.\n      destruct os;auto. destruct p.\n      case_bool_decide;auto.\n      case_bool_decide;auto. done.\n      case_bool_decide;auto. done.\n      done.\n    }\n    {\n      intros.\n      destruct os;auto. destruct p.\n      case_bool_decide;auto.\n    }\n  Qed.\n\n  Definition inv_pshare γ pshare : iProp Σ:=\n   inv (N .@ \"shared\")\n     ((∃ w, pshare ->a w) ∨ EXCL γ ∗ pshare ->a (of_imm fortytwo)).\n\n\n  Lemma up_machine1 jump_i γ :\n    let program1 := up_program1 jump_i in\n    of_imm (jump_i) = (pprog1 ^+ 4)%f ->\n    seq_in_page (of_pid pprog1) (length program1) pprog1->\n    inv_pshare γ pshare ∗\n    EXCL γ ∗\n    (program (program1) (of_pid pprog1)) ∗\n    V1 -@A> {[pprog1;pshare;ptx1;prx1]} ∗\n    (* TX page *)\n    TX@ V1 := (tpa ptx1) ∗\n    RX@ V1 := (tpa prx1) ∗\n    PC @@ V1 ->r (of_pid pprog1) ∗\n    (* Work registers *)\n    (∃ r0, R0 @@ V1 ->r r0) ∗\n    (∃ r1, R1 @@ V1 ->r r1) ∗\n    (∃ r2, R2 @@ V1 ->r r2) ∗\n    VMProp V1 (VMProp1) (1/2)%Qp\n    ⊢ VMProp_holds V1 (1/2)%Qp -∗ WP ExecI @ V1\n          {{ (λ m, False)}}%I.\n  Proof.\n    intro. rewrite /program1.\n    iIntros (Hjump HIn) \"(#inv & excl1 & (p_1 & p_2 & p_3 & p_4 & p_5 & p_6 & p7 & _) & acc & tx & rx & pc & (%r0 & r0) & (%r1 & r1) & (%r2 & r2)\n                   & vmprop) holds\".\n    assert (pprog1 ≠ ptx1) as Hneqtx.\n    {\n      intro.\n      feed pose proof (NoDup_lookup _ 1 6 ptx1 Hps_nd).\n      simplify_eq /=. done.\n      simplify_eq /=. done.\n      lia.\n    }\n    rewrite to_pid_aligned_eq.\n    pose proof (seq_in_page_forall2 _ _ _ HIn) as Hforall.\n    clear HIn; rename Hforall into HIn.\n    rewrite wp_sswp.\n    iApply ((mov_word pprog1) with \"[p_1 pc acc tx r1]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n    set_solver.\n    iNext. iIntros \"(pc & _ & acc & tx & r1) _\".\n    rewrite wp_sswp.\n    iApply ((mov_word (pprog1 ^+ 1)%f) with \"[p_2 pc acc tx r2]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n    set_solver.\n    rewrite HIn. done.\n    set_solver +.\n    iNext. iIntros \"(pc & _ & acc & tx & r2) _\".\n    rewrite wp_sswp.\n    iApply (sswp_fupd_around _ ⊤ (⊤ ∖ ↑(N .@ \"shared\")) ⊤).\n    iInv (N .@ \"shared\") as \">Inv\" \"HIClose\".\n    iDestruct \"Inv\" as \"[(%w & share) | [excl1' share]]\".\n    2:{\n      iExFalso.\n      iApply (excl_exclusive with \"excl1 excl1'\").\n    }\n    iApply ((str ((pprog1 ^+ 1) ^+ 1)%f) with \"[p_3 pc acc tx rx r1 r2 share]\");\n      rewrite -?Hpshare_eq ?to_pid_aligned_eq; iFrameAutoSolve.\n    rewrite (HIn ((pprog1 ^+ 1) ^+ 1)%f).\n    rewrite to_pid_aligned_eq.\n    set_solver +.\n    set_solver +.\n    rewrite HIn. done.\n    set_solver +.\n    {\n      rewrite to_pid_aligned_eq.\n      intro.\n      feed pose proof (NoDup_lookup _ 4 10 prx1 Hps_nd).\n      simplify_eq /=. done.\n      simplify_eq /=. done.\n      lia.\n    }\n    iModIntro. iNext. iIntros \"(pc & _ & r2 & share & r1 & acc & tx & rx)\".\n    iDestruct (\"HIClose\" with \"[excl1 share]\") as \"HIClose\".\n    iNext;iRight;iFrame.\n    iMod \"HIClose\" as \"_\". iModIntro. iIntros \"_\".\n    rewrite wp_sswp.\n    iApply ((mov_word (((pprog1 ^+ 1) ^+ 1) ^+ 1)%f) with \"[p_4 pc acc tx r2]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n    rewrite HIn. set_solver +.\n    set_solver +.\n    rewrite HIn //. set_solver +.\n    iNext. iIntros \"(pc & _ & acc & tx & r2) _\".\n    iAssert (∃trans, VMProp V1 (vmprop_unknown V1 up_slice_trans up_slice_rxs trans) (1 / 2))%I with \"[vmprop]\" as \"vmprop\".\n    {\n      iExists _. iExact \"vmprop\".\n    }\n    iLöb as \"L\" forall (r0) \"r0\".\n    iApply wp_sswp.\n    iApply (mov_word ((((pprog1 ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f with \"[p_5 pc acc tx r0]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n    rewrite HIn. set_solver +.\n    set_solver +.\n    rewrite HIn //. set_solver +.\n    iNext. iIntros \"(pc & p5 & acc & tx & r0) _\".\n    iApply wp_sswp.\n    iDestruct \"vmprop\" as \"[% vmprop]\".\n    iDestruct (VMProp_holds_agree with \"[holds vmprop]\") as \"[P prop1]\".\n    iSplitR \"vmprop\".\n    iDestruct \"holds\" as \"[% [? vmprop]]\". iExists _. iSplitR \"vmprop\".\n    2: iExact \"vmprop\". done.\n    iExact \"vmprop\".\n    iDestruct (vmprop_unknown_eq with \"P\") as \"P\".\n    rewrite bi.later_exist. iDestruct \"P\" as \"[% P]\".\n    rewrite bi.later_exist. iDestruct \"P\" as \"[% P]\".\n    rewrite 9!bi.later_sep.\n    iDestruct \"P\" as \"(>P1 & >P2 & P3 & >[% [r0z _]] & >[% [r1z _]] & >P6 & P7 & >P8 & >%P9 & prop0)\".\n    pose proof (P9 V1). destruct H.\n    iApply (yield (((((pprog1 ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+1)%f (True) (vmprop_unknown V1 up_slice_trans up_slice_rxs a)\n             with \"[p_6 pc acc tx r0 prop1 r0z r1z prop0 P1 P2 P3 P6 P7 P8]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n    rewrite HIn. set_solver +.\n    set_solver +.\n    rewrite HIn //. set_solver +.\n    apply decode_encode_hvc_func.\n    iSplitL \"prop0\". iExact \"prop0\".\n    iSplitL \"prop1\". iExact \"prop1\".\n    iSplitL. iNext. iIntros \"[(pc & p_6 & acc & tx & r0 & r0z & r1z) [_ prop1]]\".\n    iSplitL \"P1 P2 P3 P6 P7 P8 prop1 r0z r1z\".\n    rewrite /vmprop_zero /vmprop_zero_pre.\n    iExists a, x.\n    iSplit. iPureIntro. apply only_except_disjoint.\n    rewrite only_except_union.\n    iSplit. iPureIntro. intros. done.\n    iFrame \"P2 P3\".\n    iDestruct (\"P7\" $! x H) as \"[$ P7]\".\n    iSplitL \"P7\".\n    destruct x. destruct p. destruct (decide (v = V0)).\n    rewrite rxs_wf_prim_eq //.\n    pose proof (slice_rxs_sym up_slice_rxs V1 V0 (i:= V1) (os:=(Some (f, v)))).\n    simpl in H0. pose proof n. apply H0 in n. case_bool_decide;auto.\n    pose proof (slice_rxs_empty up_slice_rxs V1 V0).\n    rewrite H0 //.\n    iSplitR \"prop1\";[|done].\n    rewrite /return_reg_rx.\n    iLeft. iSplitL \"r0z\". iLeft. done.\n    iFrame \"P8 P6 r1z\".\n    iCombine \"pc p_6 acc tx r0\" as \"R'\". iExact \"R'\".\n    done.\n    iNext. iIntros \"[(pc & p6 & acc & tx & r0) prop1] holds\".\n    iApply wp_sswp.\n    iApply (br ((((((pprog1 ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f with \"[p7 pc acc tx r2]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n    rewrite HIn. set_solver +.\n    set_solver +.\n    rewrite HIn //. set_solver +.\n    iNext. iIntros \"(pc & [p7 r2] & acc & tx) _\".\n    iApply (\"L\" with \"p5 p6 p7 holds r1 rx [pc] acc tx r2 [prop1] r0\").\n    assert (((((pprog1 ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f = jump_i) as ->.\n    solve_finz + Hjump.\n    done.\n    iExists _. iExact \"prop1\".\n   Qed.\n\n\n  Lemma up_machine3 γ :\n    let program3 := up_program3 in\n    (* Addresses-values connection *)\n    seq_in_page (of_pid pprog3) (length program3) pprog3 ->\n    inv_pshare γ pshare ∗\n    (* Mem for program *)\n    (program (program3) (of_pid pprog3)) ∗\n    V3 -@A> {[pprog3;pshare;ptx3;prx3]} ∗\n    TX@ V3 := (tpa ptx3) ∗\n    RX@ V3 := (tpa prx3) ∗\n    (* Program counter *)\n    PC @@ V3 ->r (of_pid pprog3) ∗\n    (∃ nz, NZ @@ V3 ->r nz) ∗\n    (* Work registers *)\n    (∃ r0, R0 @@ V3 ->r r0) ∗\n    (∃ r1, R1 @@ V3 ->r r1) ∗\n    (∃ r2, R2 @@ V3 ->r r2) ∗\n    VMProp V3 (VMProp3) (1/2)%Qp\n    ⊢ VMProp_holds V3 (1/2)%Qp -∗ WP ExecI @ V3\n           {{ (λ m, ⌜m = HaltI⌝ ∗ R1 @@ V3 ->r fortytwo)}}%I.\n  Proof.\n    intro. rewrite /program3.\n    iIntros (HIn) \"(#inv & (p_1 & p_2 & p_3 & p_4 & p_5 & p_6 & _) & acc & tx & rx & pc & (%nz & nz) & (%r0 & r0) & (%r1 & r1) & (%r2 & r2)\n                   & vmprop) holds\".\n    assert (pprog3 ≠ ptx3) as Hneqtx.\n    {\n      intro.\n      feed pose proof (NoDup_lookup _ 3 8 ptx3 Hps_nd).\n      simplify_eq /=. done.\n      simplify_eq /=. done.\n      lia.\n    }\n    rewrite to_pid_aligned_eq.\n    pose proof (seq_in_page_forall2 _ _ _ HIn) as Hforall.\n    clear HIn; rename Hforall into HIn.\n    iLöb as \"L\" forall (nz r0 r1 r2) \"nz r0 r1 r2\".\n    iApply wp_sswp.\n    iApply ((mov_word pprog3) with \"[p_1 pc acc tx r2]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n    set_solver.\n    iNext. iIntros \"(pc & p_1 & acc & tx & r2) _\".\n    iApply wp_sswp.\n    iApply ((mov_word (pprog3 ^+ 1)%f) with \"[p_2 pc acc tx r0]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n    set_solver.\n    rewrite HIn.\n    {\n      intro.\n      feed pose proof (NoDup_lookup _ 3 8 ptx3 Hps_nd).\n      simplify_eq /=. done.\n      simplify_eq /=.\n    }\n    set_solver +.\n    iNext. iIntros \"(pc & p_2 & acc & tx & r0) _\".\n    iApply wp_sswp.\n    iApply (sswp_fupd_around _ ⊤ (⊤ ∖ ↑(N .@ \"shared\")) ⊤).\n    iInv (N .@ \"shared\") as \">Inv\" \"HIClose\".\n    iDestruct \"Inv\" as \"[ (% & share) | [excl1' share]]\".\n    {\n      iApply ((ldr ((pprog3 ^+ 1) ^+ 1)%f) with \"[p_3 pc acc tx r1 r2 share]\"); rewrite -?Hpshare_eq ?to_pid_aligned_eq; iFrameAutoSolve.\n      rewrite (HIn ((pprog3 ^+ 1) ^+ 1)%f).\n      rewrite to_pid_aligned_eq.\n      set_solver +.\n      set_solver +.\n      {\n        rewrite to_pid_aligned_eq.\n        intro.\n        feed pose proof (NoDup_lookup _ 4 8 ptx3 Hps_nd).\n        simplify_eq /=. done.\n        simplify_eq /=. done.\n        lia.\n      }\n      rewrite HIn. done.\n      set_solver +. iModIntro.\n      iNext. iIntros \"(pc & p_3 & r2 & share & r1 & acc & tx)\".\n      iDestruct (\"HIClose\" with \"[share]\") as \">_\".\n      iNext;iLeft. iExists _; iFrame.\n      iModIntro. iIntros \"_\".\n      iApply wp_sswp.\n      iApply ((cmp.cmp_word (((pprog3 ^+ 1) ^+ 1) ^+ 1)%f) with \"[p_4 pc nz r1 acc tx]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n      rewrite (HIn (((pprog3 ^+ 1) ^+ 1) ^+ 1)%f).\n      set_solver +.\n      set_solver +.\n      rewrite (HIn (((pprog3 ^+ 1) ^+ 1) ^+ 1)%f).\n      {\n        intro.\n        feed pose proof (NoDup_lookup _ 3 8 ptx3 Hps_nd).\n        simplify_eq /=. done.\n        done.\n      }\n      set_solver +.\n      iNext. iIntros \"(pc & p_4 & r1 & acc & nz & tx)\".\n      (* destruct (decide (w = fortytwo)). *)\n      iIntros \"_\".\n      iApply wp_sswp.\n      iApply ((bne.bne ((((pprog3 ^+ 1) ^+ 1) ^+ 1) ^+1)%f) with \"[p_5 pc nz r0 acc tx]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n      rewrite HIn.\n      set_solver +.\n      set_solver +.\n      rewrite HIn.\n      {\n        intro.\n        feed pose proof (NoDup_lookup _ 3 8 ptx3 Hps_nd).\n        simplify_eq /=. done.\n        done.\n      }\n      set_solver +.\n      iNext. iIntros \"(pc & p_5 & r0 & acc & nz & tx)\".\n      iIntros \"_\".\n      destruct (decide (w = fortytwo)).\n      assert (w <? fortytwo = false)%f as ->.\n      solve_finz + e.\n      assert (fortytwo <? w = false)%f as ->.\n      solve_finz + e.\n      assert ((W1 =? W1)%f = true) as ->.\n      solve_finz.\n      iApply wp_sswp.\n      iApply ((halt (((((pprog3 ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f) with \"[p_6 pc acc tx]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n      rewrite HIn. set_solver +.\n      set_solver +.\n      rewrite HIn //. set_solver +.\n      iNext. iIntros \"(pc & _ & acc & tx) _\".\n      iApply wp_terminated. done.\n      rewrite e. iFrame \"r1\". done.\n      assert (((if w <? fortytwo then W2 else if fortytwo <? w then W0 else W1) =? W1) = false)%f as ->.\n      {\n        destruct (decide (w < fortytwo)%f).\n        assert (w <? fortytwo = true)%f as ->.\n        solve_finz + l.\n        solve_finz +.\n        assert (w <? fortytwo = false)%f as ->.\n        solve_finz + n n0.\n        assert (fortytwo <? w = true)%f as ->.\n        solve_finz + n n0.\n        solve_finz +.\n      }\n      iApply (\"L\" with \"p_1 p_2 p_3 p_4 p_5 p_6 acc tx rx [pc] [vmprop] [holds] nz r0 r1 r2\").\n      rewrite Hpprog3_eq. done.\n      done.\n      rewrite /VMProp_holds.\n      iDestruct \"holds\" as \"[% [H1 H2]]\".\n      iExists _. iSplitL \"H1\". 2:{ iExact \"H2\". }\n                             iNext. done.\n    }\n      iApply ((ldr ((pprog3 ^+ 1) ^+ 1)%f) with \"[p_3 pc acc tx r1 r2 share]\"); rewrite -?Hpshare_eq ?to_pid_aligned_eq; iFrameAutoSolve.\n      rewrite (HIn ((pprog3 ^+ 1) ^+ 1)%f).\n      rewrite to_pid_aligned_eq.\n      set_solver +.\n      set_solver +.\n      {\n        rewrite to_pid_aligned_eq.\n        intro.\n        feed pose proof (NoDup_lookup _ 4 8 ptx3 Hps_nd).\n        simplify_eq /=. done.\n        simplify_eq /=. done.\n        lia.\n      }\n      rewrite HIn. done.\n      set_solver +. iModIntro.\n      iNext. iIntros \"(pc & p_3 & r2 & share & r1 & acc & tx)\".\n      iDestruct (\"HIClose\" with \"[share]\") as \">_\".\n      iNext;iLeft. iExists _; iFrame.\n      iModIntro. iIntros \"_\".\n      iApply wp_sswp.\n      iApply ((cmp.cmp_word (((pprog3 ^+ 1) ^+ 1) ^+ 1)%f) with \"[p_4 pc nz r1 acc tx]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n      rewrite (HIn (((pprog3 ^+ 1) ^+ 1) ^+ 1)%f).\n      set_solver +.\n      set_solver +.\n      rewrite (HIn (((pprog3 ^+ 1) ^+ 1) ^+ 1)%f).\n      {\n        intro.\n        feed pose proof (NoDup_lookup _ 3 8 ptx3 Hps_nd).\n        simplify_eq /=. done.\n        done.\n      }\n      set_solver +.\n      iNext. iIntros \"(pc & p_4 & r1 & acc & nz & tx)\".\n      (* destruct (decide (w = fortytwo)). *)\n      iIntros \"_\".\n      iApply wp_sswp.\n      iApply ((bne.bne ((((pprog3 ^+ 1) ^+ 1) ^+ 1) ^+1)%f) with \"[p_5 pc nz r0 acc tx]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n      rewrite HIn.\n      set_solver +.\n      set_solver +.\n      rewrite HIn.\n      {\n        intro.\n        feed pose proof (NoDup_lookup _ 3 8 ptx3 Hps_nd).\n        simplify_eq /=. done.\n        done.\n      }\n      set_solver +.\n      iNext. iIntros \"(pc & p_5 & r0 & acc & nz & tx)\".\n      iIntros \"_\".\n      assert (fortytwo <? fortytwo = false)%f as ->.\n      solve_finz + .\n      assert ((W1 =? W1)%f = true) as ->.\n      solve_finz.\n      iApply wp_sswp.\n      iApply ((halt (((((pprog3 ^+ 1) ^+ 1) ^+ 1) ^+ 1) ^+ 1)%f) with \"[p_6 pc acc tx]\"); rewrite ?to_pid_aligned_eq; iFrameAutoSolve.\n      rewrite HIn. set_solver +.\n      set_solver +.\n      rewrite HIn //. set_solver +.\n      iNext. iIntros \"(pc & _ & acc & tx) _\".\n      iApply wp_terminated. done.\n      iFrame \"r1\". done.\n  Qed.\n\n  Definition up_interp_access2 := interp_access (V2 : leibnizO VMID) up_slice_trans up_slice_rxs ptx2 prx2 {[pprog2; ptx2; prx2]}\n                                    ({[W0 := (V1, V3, {[pshare]}, Sharing, true)]}).\n\n  Lemma up_ftlr2: up_interp_access2 ⊢ interp_execute V2.\n  Proof. iApply ftlr. Qed.\n\n  Definition up_interp_access0 rxs := interp_access_prim up_slice_trans up_slice_rxs ptx0 prx0 {[pprog0; ptx0; prx0]}\n                                    {[W0 := (V1, V3, {[pshare]}, Sharing, true)]} rxs.\n\n  Lemma up_ftlr0 rxs : up_interp_access0 rxs ⊢ interp_execute_prim.\n  Proof. iApply ftlr_p. Qed.\n\nEnd up_proof.\n", "meta": {"author": "logsem", "repo": "VMSL", "sha": "0a9b005b599a770e40c07abc9aa10a4ee9759315", "save_path": "github-repos/coq/logsem-VMSL", "path": "github-repos/coq/logsem-VMSL/VMSL-0a9b005b599a770e40c07abc9aa10a4ee9759315/theories/examples/unknown_primary/proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.20042859875681457}}
{"text": "(* *********************************************************************)\n(*                                                                     *)\n(*              The Compcert verified compiler                         *)\n(*                                                                     *)\n(*                 Xavier Leroy, INRIA Paris                           *)\n(*                                                                     *)\n(*  Copyright Institut National de Recherche en Informatique et en     *)\n(*  Automatique.  All rights reserved.  This file is distributed       *)\n(*  under the terms of the INRIA Non-Commercial License Agreement.     *)\n(*                                                                     *)\n(* *********************************************************************)\n\n(** Correctness of instruction selection for 64-bit integer operations *)\n\nRequire Import String Coqlib Maps Zbits Integers Floats Errors.\nRequire Archi.\nRequire Import AST Values Memory Globalenvs Events.\nRequire Import Cminor Op CminorSel.\nRequire Import SelectOp SelectOpproof SplitLong SplitLongproof.\nRequire Import SelectLong.\n\nLocal Open Scope cminorsel_scope.\nLocal Open Scope string_scope.\n\n(** * Correctness of the instruction selection functions for 64-bit operators *)\n\nSection CMCONSTR.\n\nVariable prog: program.\nVariable hf: helper_functions.\nHypothesis HELPERS: helper_functions_declared prog hf.\nLet ge := Genv.globalenv prog.\nVariable sp: val.\nVariable e: env.\nVariable m: mem.\n\nDefinition unary_constructor_sound (cstr: expr -> expr) (sem: val -> val) : Prop :=\n  forall le a x,\n  eval_expr ge sp e m le a x ->\n  exists v, eval_expr ge sp e m le (cstr a) v /\\ Val.lessdef (sem x) v.\n\nDefinition binary_constructor_sound (cstr: expr -> expr -> expr) (sem: val -> val -> val) : Prop :=\n  forall le a x b y,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  exists v, eval_expr ge sp e m le (cstr a b) v /\\ Val.lessdef (sem x y) v.\n\nDefinition partial_unary_constructor_sound (cstr: expr -> expr) (sem: val -> option val) : Prop :=\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  sem x = Some y ->\n  exists v, eval_expr ge sp e m le (cstr a) v /\\ Val.lessdef y v.\n\nDefinition partial_binary_constructor_sound (cstr: expr -> expr -> expr) (sem: val -> val -> option val) : Prop :=\n  forall le a x b y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  sem x y = Some z ->\n  exists v, eval_expr ge sp e m le (cstr a b) v /\\ Val.lessdef z v.\n\nTheorem eval_longconst:\n  forall le n, eval_expr ge sp e m le (longconst n) (Vlong n).\nProof.\n  unfold longconst; intros; destruct Archi.splitlong.\n  apply SplitLongproof.eval_longconst.\n  EvalOp.\nQed.\n\nLemma is_longconst_sound:\n  forall v a n le,\n  is_longconst a = Some n -> eval_expr ge sp e m le a v -> v = Vlong n.\nProof with (try discriminate).\n  intros. unfold is_longconst in *. destruct Archi.splitlong.\n  eapply SplitLongproof.is_longconst_sound; eauto.\n  assert (a = Eop (Olongconst n) Enil).\n  { destruct a... destruct o... destruct e0... congruence. }\n  subst a. InvEval. auto.\nQed.\n\nTheorem eval_intoflong: unary_constructor_sound intoflong Val.loword.\nProof.\n  unfold intoflong; destruct Archi.splitlong. apply SplitLongproof.eval_intoflong.\n  red; intros. destruct (is_longconst a) as [n|] eqn:C.\n- TrivialExists. simpl. erewrite (is_longconst_sound x) by eauto. auto.\n- TrivialExists.\nQed.\n\nTheorem eval_longofintu: unary_constructor_sound longofintu Val.longofintu.\nProof.\n  unfold longofintu; destruct Archi.splitlong. apply SplitLongproof.eval_longofintu.\n  red; intros. destruct (is_intconst a) as [n|] eqn:C.\n- econstructor; split. apply eval_longconst.\n  exploit is_intconst_sound; eauto. intros; subst x. auto.\n- TrivialExists.\nQed.\n\nTheorem eval_longofint: unary_constructor_sound longofint Val.longofint.\nProof.\n  unfold longofint; destruct Archi.splitlong. apply SplitLongproof.eval_longofint.\n  red; intros. destruct (is_intconst a) as [n|] eqn:C.\n- econstructor; split. apply eval_longconst.\n  exploit is_intconst_sound; eauto. intros; subst x. auto.\n- TrivialExists.\nQed.\n\nTheorem eval_notl: unary_constructor_sound notl Val.notl.\nProof.\n  unfold notl; destruct Archi.splitlong. apply SplitLongproof.eval_notl.\n  red; intros. destruct (notl_match a).\n- InvEval. econstructor; split. apply eval_longconst. auto.\n- InvEval. subst. exists v1; split; auto. destruct v1; simpl; auto. rewrite Int64.not_involutive; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_andlimm: forall n, unary_constructor_sound (andlimm n) (fun v => Val.andl v (Vlong n)).\nProof.\n  unfold andlimm; intros; red; intros.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero.\n  exists (Vlong Int64.zero); split. apply eval_longconst.\n  subst. destruct x; simpl; auto. rewrite Int64.and_zero; auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.mone.\n  exists x; split. assumption.\n  subst. destruct x; simpl; auto. rewrite Int64.and_mone; auto.\n  destruct (andlimm_match a); InvEval; subst.\n- econstructor; split. apply eval_longconst. simpl. rewrite Int64.and_commut; auto.\n- TrivialExists. simpl. rewrite Val.andl_assoc. rewrite Int64.and_commut; auto.\n- TrivialExists. simpl. destruct v1; simpl; auto. unfold Int64.rolm. rewrite Int64.and_assoc.\n  rewrite  (Int64.and_commut mask2 n). reflexivity.\n- TrivialExists.\nQed.\n\nTheorem eval_andl: binary_constructor_sound andl Val.andl.\nProof.\n  unfold andl; destruct Archi.splitlong. apply SplitLongproof.eval_andl.\n  red; intros. destruct (andl_match a b).\n- InvEval. rewrite Val.andl_commut. apply eval_andlimm; auto.\n- InvEval. apply eval_andlimm; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_orlimm: forall n, unary_constructor_sound (orlimm n) (fun v => Val.orl v (Vlong n)).\nProof.\n  unfold orlimm; intros; red; intros.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero.\n  exists x; split; auto. subst. destruct x; simpl; auto. rewrite Int64.or_zero; auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.mone.\n  econstructor; split. apply eval_longconst. subst. destruct x; simpl; auto. rewrite Int64.or_mone; auto.\n  destruct (orlimm_match a); InvEval; subst.\n- econstructor; split. apply eval_longconst. simpl. rewrite Int64.or_commut; auto.\n- TrivialExists. simpl. rewrite Val.orl_assoc. rewrite Int64.or_commut; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_orl: binary_constructor_sound orl Val.orl.\nProof.\n  unfold orl; destruct Archi.splitlong. apply SplitLongproof.eval_orl.\n  red; intros.\n  assert (DEFAULT: exists v, eval_expr ge sp e m le (Eop Oorl (a:::b:::Enil)) v /\\ Val.lessdef (Val.orl x y) v) by TrivialExists.\n  assert (ROLM: forall v n1 n2 m1 m2,\n             n1 = n2 ->\n             Val.lessdef (Val.orl (Val.rolml v n1 m1) (Val.rolml v n2 m2))\n                         (Val.rolml v n1 (Int64.or m1 m2))).\n  { intros. destruct v; simpl; auto. unfold Int64.rolm.\n    rewrite Int64.and_or_distrib. rewrite H1. auto. }\n  destruct (orl_match a b).\n- predSpec Int.eq Int.eq_spec amount1 amount2; simpl.\n   destruct (same_expr_pure t1 t2) eqn:?; auto. InvEval.\n   exploit eval_same_expr; eauto. intros [EQ1 EQ2]; subst.\n   exists (Val.rolml v0 amount2 (Int64.or mask1 mask2)); split. EvalOp.\n   apply ROLM; auto. auto.\n- InvEval. rewrite Val.orl_commut. apply eval_orlimm; auto.\n- InvEval. apply eval_orlimm; auto.\n- apply DEFAULT.\nQed.\n\nTheorem eval_xorlimm: forall n, unary_constructor_sound (xorlimm n) (fun v => Val.xorl v (Vlong n)).\nProof.\n  unfold xorlimm; intros; red; intros.\n  predSpec Int64.eq Int64.eq_spec n Int64.zero.\n  exists x; split; auto. subst. destruct x; simpl; auto. rewrite Int64.xor_zero; auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.mone.\n  replace (Val.xorl x (Vlong n)) with (Val.notl x). apply eval_notl; auto.\n  subst n. destruct x; simpl; auto.\n  destruct (xorlimm_match a); InvEval; subst.\n- econstructor; split. apply eval_longconst. simpl. rewrite Int64.xor_commut; auto.\n- TrivialExists. simpl. rewrite Val.xorl_assoc. rewrite Int64.xor_commut; auto.\n- TrivialExists. simpl. destruct v1; simpl; auto. unfold Int64.not.\n  rewrite Int64.xor_assoc. apply f_equal. apply f_equal. apply f_equal.\n  apply Int64.xor_commut.\n- TrivialExists.\nQed.\n\nTheorem eval_xorl: binary_constructor_sound xorl Val.xorl.\nProof.\n  unfold xorl; destruct Archi.splitlong. apply SplitLongproof.eval_xorl.\n  red; intros. destruct (xorl_match a b).\n- InvEval. rewrite Val.xorl_commut. apply eval_xorlimm; auto.\n- InvEval. apply eval_xorlimm; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_rolml: forall amount mask, unary_constructor_sound (fun v => rolml v amount mask) (fun v => Val.rolml v amount mask).\nProof.\n  unfold rolml. intros; red; intros.\n  predSpec Int.eq Int.eq_spec amount Int.zero.\n  rewrite H0.\n  exploit (eval_andlimm). eauto. intros (x0 & (H1 & H2)).\n  exists x0. split. apply H1. destruct x; auto. simpl. unfold Int64.rolm.\n  change (Int64.repr (Int.unsigned Int.zero)) with Int64.zero. rewrite Int64.rol_zero.\n  apply H2.\n  destruct (rolml_match a).\n- econstructor; split. apply eval_longconst. simpl. InvEval. unfold Val.rolml. auto.\n- InvEval. TrivialExists. simpl. rewrite <- H. \n  unfold Val.rolml; destruct v1; simpl; auto.\n  rewrite Int64.rolm_rolm by (exists (two_p (64-6)); auto).\n  f_equal. f_equal. f_equal.\n  unfold Int64.add. rewrite ! Int64.int_unsigned_repr. unfold Int.add. \n  set (a := Int.unsigned amount1 + Int.unsigned amount).\n  unfold Int.modu, Int64.modu. \n  change (Int.unsigned Int64.iwordsize') with 64.\n  change (Int64.unsigned Int64.iwordsize) with 64.\n  f_equal.\n  rewrite Int.unsigned_repr. \n  apply eqmod_mod_eq. lia. \n  apply eqmod_trans with a.\n  apply eqmod_divides with Int.modulus. apply Int.eqm_sym. apply Int.eqm_unsigned_repr.\n  exists (two_p (32-6)); auto.\n  apply eqmod_divides with Int64.modulus. apply Int64.eqm_unsigned_repr.\n  exists (two_p (64-6)); auto.\n  assert (0 <= Int.unsigned (Int.repr a) mod 64 < 64) by (apply Z_mod_lt; lia).\n  assert (64 < Int.max_unsigned) by (compute; auto).\n  lia.\n- InvEval. TrivialExists. simpl. rewrite <- H.\n  unfold Val.rolml; destruct v1; simpl; auto. unfold Int64.rolm.\n  rewrite Int64.rol_and. rewrite Int64.and_assoc. auto.\n- TrivialExists.\nQed.\n\nTheorem eval_shllimm: forall n, unary_constructor_sound (fun e => shllimm e n) (fun v => Val.shll v (Vint n)).\nProof.\n  intros; unfold shllimm. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shllimm; auto.\n  red; intros.\n  predSpec Int.eq Int.eq_spec n Int.zero.\n  exists x; split; auto. subst n; destruct x; simpl; auto.\n  destruct (Int.ltu Int.zero Int64.iwordsize'); auto.\n  change (Int64.shl' i Int.zero) with (Int64.shl i Int64.zero). rewrite Int64.shl_zero; auto.\n  destruct (Int.ltu n Int64.iwordsize') eqn:LT; simpl.\n- rewrite Val.shll_rolml by apply LT. apply eval_rolml. auto.\n- TrivialExists. constructor; eauto.  constructor. EvalOp. simpl; eauto. constructor.\n  constructor.\nQed.\n\nTheorem eval_shrluimm: forall n, unary_constructor_sound (fun e => shrluimm e n) (fun v => Val.shrlu v (Vint n)).\nProof.\n  unfold shrluimm; destruct Archi.splitlong. apply SplitLongproof.eval_shrluimm. auto.\n  red; intros.\n  predSpec Int.eq Int.eq_spec n Int.zero.\n  exists x. split. apply H. destruct x; simpl; auto. rewrite H0. rewrite Int64.shru'_zero. constructor.\n  destruct (Int.ltu n Int64.iwordsize') eqn:LT; simpl.\n- rewrite Val.shrlu_rolml by apply LT. apply eval_rolml. auto.\n- TrivialExists. constructor; eauto.  constructor. EvalOp. simpl; eauto. constructor.\n  constructor.\nQed.\n\nTheorem eval_shrlimm: forall n, unary_constructor_sound (fun e => shrlimm e n) (fun v => Val.shrl v (Vint n)).\nProof.\n  intros; unfold shrlimm. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shrlimm; auto.\n  red; intros.\n  predSpec Int.eq Int.eq_spec n Int.zero.\n  exists x; split; auto. subst n; destruct x; simpl; auto.\n  destruct (Int.ltu Int.zero Int64.iwordsize'); auto.\n  change (Int64.shr' i Int.zero) with (Int64.shr i Int64.zero). rewrite Int64.shr_zero; auto.\n  destruct (Int.ltu n Int64.iwordsize') eqn:LT; simpl.\n  assert (DEFAULT: exists v, eval_expr ge sp e m le (Eop (Oshrlimm n) (a:::Enil)) v\n                         /\\  Val.lessdef (Val.shrl x (Vint n)) v) by TrivialExists.\n  destruct (shrlimm_match a); InvEval.\n- TrivialExists. simpl; rewrite LT; auto.\n- destruct (Int.ltu (Int.add n n1) Int64.iwordsize') eqn:LT'; auto.\n  subst. econstructor; split. EvalOp. simpl; eauto.\n  destruct v1; simpl; auto. rewrite LT'.\n  destruct (Int.ltu n1 Int64.iwordsize') eqn:LT1; auto.\n  simpl; rewrite LT. rewrite Int.add_commut, Int64.shr'_shr'; auto. rewrite Int.add_commut; auto.\n- apply DEFAULT.\n- TrivialExists. constructor; eauto. constructor. EvalOp. simpl; eauto. constructor. auto.\nQed.\n\nTheorem eval_shll: binary_constructor_sound shll Val.shll.\nProof.\n  unfold shll. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shll; auto.\n  red; intros. destruct (is_intconst b) as [n2|] eqn:C.\n- exploit is_intconst_sound; eauto. intros EQ; subst y. apply eval_shllimm; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_shrlu: binary_constructor_sound shrlu Val.shrlu.\nProof.\n  unfold shrlu. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shrlu; auto.\n  red; intros. destruct (is_intconst b) as [n2|] eqn:C.\n- exploit is_intconst_sound; eauto. intros EQ; subst y. apply eval_shrluimm; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_shrl: binary_constructor_sound shrl Val.shrl.\nProof.\n  unfold shrl. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shrl; auto.\n  red; intros. destruct (is_intconst b) as [n2|] eqn:C.\n- exploit is_intconst_sound; eauto. intros EQ; subst y. apply eval_shrlimm; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_negl: unary_constructor_sound negl Val.negl.\nProof.\n  unfold negl. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_negl; auto.\n  red; intros. destruct (is_longconst a) as [n|] eqn:C.\n- exploit is_longconst_sound; eauto. intros EQ; subst x.\n  econstructor; split. apply eval_longconst. auto.\n- TrivialExists.\nQed.\n\nTheorem eval_addlimm: forall n, unary_constructor_sound (addlimm n) (fun v => Val.addl v (Vlong n)).\nProof.\n  unfold addlimm.\n  red; intros. predSpec Int64.eq Int64.eq_spec n Int64.zero.\n  exists x. split; auto. rewrite H0. destruct x; auto. simpl. rewrite Int64.add_zero. constructor.\n  destruct (addlimm_match a).\n- econstructor; split. apply eval_longconst. simpl. InvEval. unfold Val.rolml. auto.\n- InvEval. TrivialExists. simpl. rewrite <- H. rewrite Val.addl_assoc. reflexivity.\n- InvEval. TrivialExists.\nQed.\n\n\nTheorem eval_addl: binary_constructor_sound addl Val.addl.\nProof.\n  unfold addl. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_addl; auto.\n  red; intros. destruct (addl_match a b); InvEval; subst.\n- exploit (eval_addlimm n1); eauto. intros (n & (H1 & H2)). exists n. split; auto.\n  rewrite Val.addl_commut. exact H2.\n- exploit (eval_addlimm n2). apply H. auto.\n- rewrite Val.addl_permut_4. simpl.\n  apply eval_addlimm; EvalOp.\n- rewrite Val.addl_assoc. rewrite Val.addl_permut. rewrite Val.addl_commut.\n  apply eval_addlimm; EvalOp.\n- rewrite Val.addl_commut. rewrite Val.addl_assoc. rewrite Val.addl_permut.\n  rewrite Val.addl_commut. apply eval_addlimm; EvalOp. rewrite Val.addl_commut.\n  constructor.\n- TrivialExists.\nQed.\n\nTheorem eval_subl: binary_constructor_sound subl Val.subl.\nProof.\n  unfold subl. destruct Archi.splitlong eqn:SL.\n  apply SplitLongproof.eval_subl. apply Archi.splitlong_ptr32; auto.\n  red; intros; destruct (subl_match a b); InvEval.\n- rewrite Val.subl_addl_opp. apply eval_addlimm; auto.\n-  TrivialExists.\nQed.\n\nTheorem eval_mullimm_base: forall n, unary_constructor_sound (mullimm_base n) (fun v => Val.mull v (Vlong n)).\nProof.\n  intros; unfold mullimm_base. red. intros.\n  assert (DEFAULT: exists v : val, eval_expr ge sp e m le (Eop Omull (a ::: longconst n ::: Enil)) v\n                              /\\ Val.lessdef (Val.mull x (Vlong n)) v).\n  { TrivialExists. constructor. eauto. constructor. apply eval_longconst. constructor. auto. }\n  generalize (Int64.one_bits'_decomp n); intros D.\n  destruct (Int64.one_bits' n) as [ | i [ | j [ | ? ? ]]] eqn:B; auto.\n- replace (Val.mull x (Vlong n)) with (Val.shll x (Vint i)).\n  apply eval_shllimm; auto.\n  simpl in D. rewrite D, Int64.add_zero. destruct x; simpl; auto.\n  rewrite (Int64.one_bits'_range n) by (rewrite B; auto with coqlib).\n  rewrite Int64.shl'_mul; auto.\n- set (le' := x :: le).\n  assert (A0: eval_expr ge sp e m le' (Eletvar O) x) by (constructor; reflexivity).\n  exploit (eval_shllimm i). eexact A0. intros (v1 & A1 & B1).\n  exploit (eval_shllimm j). eexact A0. intros (v2 & A2 & B2).\n  exploit (eval_addl). eexact A1. eexact A2. intros (v3 & A3 & B3).\n  exists v3; split. econstructor; eauto.\n  rewrite D. simpl. rewrite Int64.add_zero. destruct x; auto.\n  simpl in *.\n  rewrite (Int64.one_bits'_range n) in B1 by (rewrite B; auto with coqlib).\n  rewrite (Int64.one_bits'_range n) in B2 by (rewrite B; auto with coqlib).\n  inv B1; inv B2. simpl in B3; inv B3.\n  rewrite Int64.mul_add_distr_r. rewrite <- ! Int64.shl'_mul. auto.\nQed.\n\nTheorem eval_mullimm: forall n, unary_constructor_sound (mullimm n) (fun v => Val.mull v (Vlong n)).\nProof.\n  unfold mullimm. intros.\n  destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_mullimm; eauto.\n  red; intros. predSpec Int64.eq Int64.eq_spec n Int64.zero.\n  exists (Vlong Int64.zero).\n  split. apply eval_longconst. destruct x; simpl; auto.\n  subst n; rewrite Int64.mul_zero; auto.\n  predSpec Int64.eq Int64.eq_spec n Int64.one.\n  exists x; split; auto.\n  destruct x; simpl; auto. subst n; rewrite Int64.mul_one; auto.\n  destruct (mullimm_match a); InvEval.\n- econstructor; split. apply eval_longconst. rewrite Int64.mul_commut; auto.\n- exploit (eval_mullimm_base n); eauto.\nQed.\n\nTheorem eval_mull: binary_constructor_sound mull Val.mull.\nProof.\n  unfold mull. destruct Archi.splitlong eqn:SL.\n  apply SplitLongproof.eval_mull; auto.\n  red; intros. destruct (mull_match a b).\n- exploit (eval_mullimm n1); eauto. intros (n & (H1 & H2)). InvEval. exists n. split; auto.\n  rewrite Val.mull_commut. exact H2.\n- exploit (eval_mullimm n2). apply H. InvEval. auto.\n- TrivialExists.\nQed.\n\nTheorem eval_mullhu:\n  forall n, unary_constructor_sound (fun a => mullhu a n) (fun v => Val.mullhu v (Vlong n)).\nProof.\n  unfold mullhu; intros. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_mullhu; auto.\n  red; intros. TrivialExists. constructor. eauto. constructor. apply eval_longconst. constructor. auto.\nQed.\n\nTheorem eval_mullhs:\n  forall n, unary_constructor_sound (fun a => mullhs a n) (fun v => Val.mullhs v (Vlong n)).\nProof.\n  unfold mullhs; intros. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_mullhs; auto.\n  red; intros. TrivialExists. constructor. eauto. constructor. apply eval_longconst. constructor. auto.\nQed.\n\nTheorem eval_shrxlimm:\n  forall le a n x z,\n  eval_expr ge sp e m le a x ->\n  Val.shrxl x (Vint n) = Some z ->\n  exists v, eval_expr ge sp e m le (shrxlimm a n) v /\\ Val.lessdef z v.\nProof.\n  unfold shrxlimm. intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_shrxlimm; eauto.\n  predSpec Int.eq Int.eq_spec n Int.zero.\n- subst n. destruct x; simpl in H0; inv H0. econstructor; split; eauto.\n  change (Int.ltu Int.zero (Int.repr 63)) with true. simpl. rewrite Int64.shrx'_zero; auto.\n- TrivialExists.\nQed.\n\nTheorem eval_divls_base: partial_binary_constructor_sound divls_base Val.divls.\nProof.\n  unfold divls_base; red; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_divls_base; eauto.\n  TrivialExists.\nQed.\n\nLemma eval_modl_aux:\n  forall divop semdivop,\n  (forall sp x y m, eval_operation ge sp divop (x :: y :: nil) m = semdivop x y) ->\n  forall le a b x y z,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  semdivop x y = Some z ->\n  eval_expr ge sp e m le (modl_aux divop a b) (Val.subl x (Val.mull z y)).\nProof.\n  intros; unfold modl_aux.\n  eapply eval_Elet. eexact H0. eapply eval_Elet.\n  apply eval_lift. eexact H1.\n  eapply eval_Eop. eapply eval_Econs.\n  eapply eval_Eletvar. simpl; reflexivity.\n  eapply eval_Econs. eapply eval_Eop.\n  eapply eval_Econs. eapply eval_Eop.\n  eapply eval_Econs. apply eval_Eletvar. simpl; reflexivity.\n  eapply eval_Econs. apply eval_Eletvar. simpl; reflexivity.\n  apply eval_Enil.\n  rewrite H. eauto.\n  eapply eval_Econs. apply eval_Eletvar. simpl; reflexivity.\n  apply eval_Enil.\n  simpl; reflexivity. apply eval_Enil.\n  reflexivity.\nQed.\n\nTheorem eval_modls_base: partial_binary_constructor_sound modls_base Val.modls.\nProof.\n  unfold modls_base. red; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_modls_base; eauto.\n  assert (DEFAULT: exists v : val, eval_expr ge sp e m le (modl_aux Odivl a b) v /\\ Val.lessdef z v).\n  exploit Val.modls_divls; eauto. intros [v [A B]].\n  { subst. econstructor; split; eauto.\n    apply eval_modl_aux with (semdivop := Val.divls); auto. }\n\n  destruct (is_longconst a) as [n1|] eqn:A. exploit is_longconst_sound. eauto. eauto. intros.\n  destruct (is_longconst b) as [n2|] eqn:B; auto. exploit is_longconst_sound. eauto. eauto. intros.\n  predSpec Int64.eq Int64.eq_spec Int64.zero n2; simpl.\n  (* n1 mod n2, n2 = 0 *)\n  auto.\n  predSpec Int64.eq Int64.eq_spec n1 (Int64.repr Int64.min_signed); predSpec Int64.eq Int64.eq_spec n2 Int64.mone; simpl; auto; subst.\n- (* signed_min mod n2 | n2 != 0, n2 !- =1 *)\n  econstructor; split. apply eval_longconst.\n  unfold Val.modls in H1.\n  rewrite Int64.eq_false in H1; auto.\n  rewrite (Int64.eq_false n2 Int64.mone H6) in H1.\n  inversion H1. auto.\n- (* n1 mod -1, n1 !- signed_min *)\n  econstructor; split. apply eval_longconst.\n  unfold Val.modls in H1.\n  rewrite Int64.eq_false in H1; auto.\n  rewrite Int64.eq_false in H1; auto.\n  inversion H1. auto.\n- (* other valid cases *)\n  econstructor; split. apply eval_longconst.\n  unfold Val.modls in H1.\n  rewrite Int64.eq_false in H1; auto.\n  rewrite Int64.eq_false in H1; auto.\n  inversion H1.\n  auto.\n- (* fallback *)\n  apply DEFAULT.\nQed.\n\n\nTheorem eval_divlu_base: partial_binary_constructor_sound divlu_base Val.divlu.\nProof.\n  unfold divlu_base; red; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_divlu_base; eauto.\n  TrivialExists.\nQed.\n\nTheorem eval_modlu_base: partial_binary_constructor_sound modlu_base Val.modlu.\nProof.\n  unfold modlu_base; red; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_modlu_base; eauto.\n  assert (DEFAULT: exists v : val, eval_expr ge sp e m le (modl_aux Odivlu a b) v /\\ Val.lessdef z v).\n  exploit Val.modlu_divlu; eauto. intros [v [A B]].\n  subst. econstructor; split; eauto.\n  apply eval_modl_aux with (semdivop := Val.divlu); auto.\n  (* n1 and n2 are longconsts *)\n  destruct (is_longconst a) as [n1|] eqn:A. exploit is_longconst_sound; eauto.\n  destruct (is_longconst b) as [n2|] eqn:B; auto. exploit is_longconst_sound; eauto. intros.\n  predSpec Int64.eq Int64.eq_spec Int64.zero n2; simpl.\n  (* n2 = 0 *)\n-  auto.\n  (* n2 != 0 *)\n-  econstructor; split. apply eval_longconst.\n  rewrite H2 in H1.\n  rewrite H3 in H1.\n  unfold Val.modlu in H1.\n  rewrite Int64.eq_false in H1; auto.\n  inversion H1. auto.\n-  (* n1 no longconst, n2 is longconst *)\n  destruct (is_longconst b) as [n2|] eqn:B; auto. exploit is_longconst_sound; eauto. intros.\n  destruct (Int64.is_power2 n2) eqn:C; auto.\n  (* n2 is power of 2 *)\n  exploit eval_andlimm. apply H. intros. destruct H3.\n  exists x0.  split. apply H3.\n  replace z with (Val.andl x (Vlong (Int64.sub n2 Int64.one))). apply H3.\n  apply (Val.modlu_pow2 x n2 i z); congruence.\nQed.\n\nTheorem eval_cmplu:\n  forall c le a x b y v,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.cmplu (Mem.valid_pointer m) c x y = Some v ->\n  eval_expr ge sp e m le (cmplu c a b) v.\nProof.\n  unfold cmplu; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_cmplu; eauto using Archi.splitlong_ptr32.\n  unfold Val.cmplu in H1.\n  destruct (Val.cmplu_bool (Mem.valid_pointer m) c x y) as [vb|] eqn:C; simpl in H1; inv H1.\n  destruct (is_longconst a) as [n1|] eqn:LC1; destruct (is_longconst b) as [n2|] eqn:LC2;\n  try (assert (x = Vlong n1) by (eapply is_longconst_sound; eauto));\n  try (assert (y = Vlong n2) by (eapply is_longconst_sound; eauto));\n  subst.\n- simpl in C; inv C. EvalOp. destruct (Int64.cmpu c n1 n2); reflexivity.\n- EvalOp. simpl. rewrite Val.swap_cmplu_bool. rewrite C; auto.\n- EvalOp. simpl; rewrite C; auto.\n- EvalOp. simpl; rewrite C; auto.\nQed.\n\nTheorem eval_cmpl:\n  forall c le a x b y v,\n  eval_expr ge sp e m le a x ->\n  eval_expr ge sp e m le b y ->\n  Val.cmpl c x y = Some v ->\n  eval_expr ge sp e m le (cmpl c a b) v.\nProof.\n  unfold cmpl; intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_cmpl; eauto.\n  unfold Val.cmpl in H1.\n  destruct (Val.cmpl_bool c x y) as [vb|] eqn:C; simpl in H1; inv H1.\n  destruct (is_longconst a) as [n1|] eqn:LC1; destruct (is_longconst b) as [n2|] eqn:LC2;\n  try (assert (x = Vlong n1) by (eapply is_longconst_sound; eauto));\n  try (assert (y = Vlong n2) by (eapply is_longconst_sound; eauto));\n  subst.\n- simpl in C; inv C. EvalOp. destruct (Int64.cmp c n1 n2); reflexivity.\n- EvalOp. simpl. rewrite Val.swap_cmpl_bool. rewrite C; auto.\n- EvalOp. simpl; rewrite C; auto.\n- EvalOp. simpl; rewrite C; auto.\nQed.\n\nTheorem eval_longoffloat:\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  Val.longoffloat x = Some y ->\n  exists v, eval_expr ge sp e m le (longoffloat a) v /\\ Val.lessdef y v.\nProof.\n  unfold longoffloat. intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_longoffloat; eauto.\n  TrivialExists.\nQed.\n\nTheorem eval_floatoflong:\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  Val.floatoflong x = Some y ->\n  exists v, eval_expr ge sp e m le (floatoflong a) v /\\ Val.lessdef y v.\nProof.\n  unfold floatoflong. intros. destruct Archi.splitlong eqn:SL.\n  eapply SplitLongproof.eval_floatoflong; eauto.\n  TrivialExists.\nQed.\n\nTheorem eval_longofsingle:\n  forall le a x y,\n  eval_expr ge sp e m le a x ->\n  Val.longofsingle x = Some y ->\n  exists v, eval_expr ge sp e m le (longofsingle a) v /\\ Val.lessdef y v.\nProof.\n  intros; unfold longofsingle.\n  destruct x; simpl in H0; inv H0. destruct (Float32.to_long f) as [n|] eqn:EQ; simpl in H2; inv H2.\n  exploit eval_floatofsingle; eauto. intros (v & A & B). simpl in B. inv B.\n  apply Float32.to_long_double in EQ.\n  eapply eval_longoffloat; eauto. simpl.\n  change (Float.of_single f) with (Float32.to_double f); rewrite EQ; auto.\nQed.\n\nEnd CMCONSTR.\n", "meta": {"author": "AbsInt", "repo": "CompCert", "sha": "f4ddce910894bf6dbdf83c0642c4b275854b60dd", "save_path": "github-repos/coq/AbsInt-CompCert", "path": "github-repos/coq/AbsInt-CompCert/CompCert-f4ddce910894bf6dbdf83c0642c4b275854b60dd/powerpc/SelectLongproof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2004285949733046}}
{"text": "(*********************************************************************************************************************************)\n(* HaskFlattener:                                                                                                                *)\n(*                                                                                                                               *)\n(*    The Flattening Functor.                                                                                                    *)\n(*                                                                                                                               *)\n(*********************************************************************************************************************************)\n\nGeneralizable All Variables.\nRequire Import Preamble.\nRequire Import General.\nRequire Import NaturalDeduction.\nRequire Import NaturalDeductionContext.\nRequire Import Coq.Strings.String.\nRequire Import Coq.Lists.List.\n\nRequire Import HaskKinds.\nRequire Import HaskCoreTypes.\nRequire Import HaskCoreVars.\nRequire Import HaskWeakTypes.\nRequire Import HaskWeakVars.\nRequire Import HaskLiterals.\nRequire Import HaskTyCons.\nRequire Import HaskStrongTypes.\nRequire Import HaskProof.\nRequire Import NaturalDeduction.\n\nRequire Import HaskStrongTypes.\nRequire Import HaskStrong.\nRequire Import HaskProof.\nRequire Import HaskStrongToProof.\nRequire Import HaskProofToStrong.\nRequire Import HaskWeakToStrong.\n\nRequire Import HaskSkolemizer.\n\nOpen Scope nd_scope.\nSet Printing Width 130.\n\n(*\n *  The flattening transformation.  Currently only TWO-level languages are\n *  supported, and the level-1 sublanguage is rather limited.\n *\n *  This file abuses terminology pretty badly.  For purposes of this file,\n *  \"PCF\" means \"the level-1 sublanguage\" and \"FC\" (aka System FC) means \n *  the whole language (level-0 language including bracketed level-1 terms)\n *)\nSection HaskFlattener.\n\n  Ltac eqd_dec_refl' :=\n    match goal with\n      | [ |- context[@eqd_dec ?T ?V ?X ?X] ] =>\n        destruct (@eqd_dec T V X X) as [eqd_dec1 | eqd_dec2];\n          [ clear eqd_dec1 | set (eqd_dec2 (refl_equal _)) as eqd_dec2'; inversion eqd_dec2' ]\n  end.\n\n  Definition v2t {Γ}(ec:HaskTyVar Γ ECKind) : HaskType Γ ECKind := fun TV ite => TVar (ec TV ite).\n\n  Definition levelMatch {Γ}(lev:HaskLevel Γ) : LeveledHaskType Γ ★ -> bool :=\n    fun t => match t with ttype@@tlev => if eqd_dec tlev lev then true else false end.\n\n  (* In a tree of types, replace any type at depth \"lev\" or greater None *)\n  Definition mkDropFlags {Γ}(lev:HaskLevel Γ)(tt:Tree ??(LeveledHaskType Γ ★)) : TreeFlags tt :=\n    mkFlags (liftBoolFunc false (levelMatch lev)) tt.\n\n  Definition drop_lev {Γ}(lev:HaskLevel Γ)(tt:Tree ??(LeveledHaskType Γ ★)) : Tree ??(LeveledHaskType Γ ★) :=\n    dropT (mkDropFlags lev tt).\n\n  (* The opposite: replace any type which is NOT at level \"lev\" with None *)\n  Definition mkTakeFlags {Γ}(lev:HaskLevel Γ)(tt:Tree ??(LeveledHaskType Γ ★)) : TreeFlags tt :=\n    mkFlags (liftBoolFunc true (bnot ○ levelMatch lev)) tt.\n\n  Definition take_lev {Γ}(lev:HaskLevel Γ)(tt:Tree ??(LeveledHaskType Γ ★)) : Tree ??(LeveledHaskType Γ ★) :=\n    dropT (mkTakeFlags lev tt).\n(*\n    mapOptionTree (fun x => flatten_type (unlev x))\n    (maybeTree (takeT tt (mkFlags (\n      fun t => match t with\n                 | Some (ttype @@ tlev) => if eqd_dec tlev lev then true else false\n                 | _                    => true\n               end\n    ) tt))).\n\n  Definition maybeTree {T}(t:??(Tree ??T)) : Tree ??T :=\n    match t with\n      | None   => []\n      | Some x => x\n    end.\n*)\n\n  Lemma drop_lev_lemma : forall Γ (lev:HaskLevel Γ) x, drop_lev lev [x @@  lev] = [].\n    intros; simpl.\n    Opaque eqd_dec.\n    unfold drop_lev.\n    simpl.\n    unfold mkDropFlags.\n    simpl.\n    Transparent eqd_dec.\n    eqd_dec_refl'.\n    auto.\n    Qed.\n\n  Lemma drop_lev_lemma_s : forall Γ (lev:HaskLevel Γ) ec x, drop_lev (ec::lev) [x @@  (ec :: lev)] = [].\n    intros; simpl.\n    Opaque eqd_dec.\n    unfold drop_lev.\n    unfold mkDropFlags.\n    simpl.\n    Transparent eqd_dec.\n    eqd_dec_refl'.\n    auto.\n    Qed.\n\n  Lemma take_lemma : forall Γ (lev:HaskLevel Γ) x, take_lev lev [x @@  lev] = [x @@ lev].\n    intros; simpl.\n    Opaque eqd_dec.\n    unfold take_lev.\n    unfold mkTakeFlags.\n    simpl.\n    Transparent eqd_dec.\n    eqd_dec_refl'.\n    auto.\n    Qed.\n\n  Lemma take_lemma' : forall Γ (lev:HaskLevel Γ) x, take_lev lev (x @@@ lev) = x @@@ lev.\n    intros.\n    induction x.\n    destruct a; simpl; try reflexivity.\n    apply take_lemma.\n    simpl.\n    rewrite <- IHx1 at 2.\n    rewrite <- IHx2 at 2.\n    reflexivity.\n    Qed.\n\n  Ltac drop_simplify :=\n    match goal with\n      | [ |- context[@drop_lev ?G ?L [ ?X @@ ?L ] ] ] =>\n        rewrite (drop_lev_lemma G L X)\n      | [ |- context[@drop_lev ?G (?E :: ?L) [ ?X @@ (?E :: ?L) ] ] ] =>\n        rewrite (drop_lev_lemma_s G L E X)\n      | [ |- context[@drop_lev ?G ?N (?A,,?B)] ] =>\n      change (@drop_lev G N (A,,B)) with ((@drop_lev G N A),,(@drop_lev G N B))\n      | [ |- context[@drop_lev ?G ?N (T_Leaf None)] ] =>\n      change (@drop_lev G N (T_Leaf (@None (LeveledHaskType G ★)))) with (T_Leaf (@None (LeveledHaskType G ★)))\n    end.\n\n  Ltac take_simplify :=\n    match goal with\n      | [ |- context[@take_lev ?G ?L [ ?X @@ ?L ] ] ] =>\n        rewrite (take_lemma G L X)\n      | [ |- context[@take_lev ?G ?L [ ?X @@@ ?L ] ] ] =>\n        rewrite (take_lemma' G L X)\n      | [ |- context[@take_lev ?G ?N (?A,,?B)] ] =>\n      change (@take_lev G N (A,,B)) with ((@take_lev G N A),,(@take_lev G N B))\n      | [ |- context[@take_lev ?G ?N (T_Leaf None)] ] =>\n      change (@take_lev G N (T_Leaf (@None (LeveledHaskType G ★)))) with (T_Leaf (@None (LeveledHaskType G ★)))\n    end.\n\n\n  (*******************************************************************************)\n\n\n  Context {unitTy : forall TV, RawHaskType TV ECKind  -> RawHaskType TV ★                                          }.\n  Context {prodTy : forall TV, RawHaskType TV ECKind  -> RawHaskType TV ★  -> RawHaskType TV ★ -> RawHaskType TV ★ }.\n  Context {gaTy   : forall TV, RawHaskType TV ECKind  -> RawHaskType TV ★ -> RawHaskType TV ★  -> RawHaskType TV ★ }.\n\n  Definition ga_mk_tree' {TV}(ec:RawHaskType TV ECKind)(tr:Tree ??(RawHaskType TV ★)) : RawHaskType TV ★ :=\n    reduceTree (unitTy TV ec) (prodTy TV ec) tr.\n\n  Definition ga_mk_tree {Γ}(ec:HaskType Γ ECKind)(tr:Tree ??(HaskType Γ ★)) : HaskType Γ ★ :=\n    fun TV ite => ga_mk_tree' (ec TV ite) (mapOptionTree (fun x => x TV ite) tr).\n\n  Definition ga_mk_raw {TV}(ec:RawHaskType TV ECKind)(ant suc:Tree ??(RawHaskType TV ★)) : RawHaskType TV ★ :=\n    gaTy TV ec\n    (ga_mk_tree' ec ant)\n    (ga_mk_tree' ec suc).\n\n  Definition ga_mk {Γ}(ec:HaskType Γ ECKind)(ant suc:Tree ??(HaskType Γ ★)) : HaskType Γ ★ :=\n    fun TV ite => gaTy TV (ec TV ite) (ga_mk_tree ec ant TV ite) (ga_mk_tree ec suc TV ite).\n\n  (*\n   *  The story:\n   *    - code types <[t]>@c                                                become garrows  c () t \n   *    - free variables of type t at a level lev deeper than the succedent become garrows  c () t\n   *    - free variables at the level of the succedent become \n   *)\n  Fixpoint flatten_rawtype {TV}{κ}(exp: RawHaskType TV κ) : RawHaskType TV κ :=\n    match exp with\n    | TVar    _  x          => TVar x\n    | TAll     _ y          => TAll   _  (fun v => flatten_rawtype (y v))\n    | TApp   _ _ x y        => TApp      (flatten_rawtype x) (flatten_rawtype y)\n    | TCon       tc         => TCon      tc\n    | TCoerc _ t1 t2 t      => TCoerc    (flatten_rawtype t1) (flatten_rawtype t2) (flatten_rawtype t)\n    | TArrow                => TArrow\n    | TCode     ec e        => let e' := flatten_rawtype e\n                               in  ga_mk_raw ec (unleaves_ (take_arg_types e')) [drop_arg_types e']\n    | TyFunApp  tfc kl k lt => TyFunApp tfc kl k (flatten_rawtype_list _ lt)\n    end\n    with flatten_rawtype_list {TV}(lk:list Kind)(exp:@RawHaskTypeList TV lk) : @RawHaskTypeList TV lk :=\n    match exp in @RawHaskTypeList _ LK return @RawHaskTypeList TV LK with\n    | TyFunApp_nil               => TyFunApp_nil\n    | TyFunApp_cons  κ kl t rest => TyFunApp_cons _ _ (flatten_rawtype t) (flatten_rawtype_list _ rest)\n    end.\n\n  Definition flatten_type {Γ}{κ}(ht:HaskType Γ κ) : HaskType Γ κ :=\n    fun TV ite => flatten_rawtype (ht TV ite).\n\n  Fixpoint levels_to_tcode {Γ}(ht:HaskType Γ ★)(lev:HaskLevel Γ) : HaskType Γ ★ :=\n    match lev with\n      | nil      => flatten_type ht\n      | ec::lev' => @ga_mk _ (v2t ec) [] [levels_to_tcode ht lev']\n    end.\n\n  Definition flatten_leveled_type {Γ}(ht:LeveledHaskType Γ ★) : LeveledHaskType Γ ★ :=\n    levels_to_tcode (unlev ht) (getlev ht) @@ nil.\n\n  (* AXIOMS *)\n\n  Axiom literal_types_unchanged : forall Γ l, flatten_type (literalType l) = literalType(Γ:=Γ) l.\n\n  Axiom flatten_coercion : forall Γ Δ κ (σ τ:HaskType Γ κ) (γ:HaskCoercion Γ Δ (σ ∼∼∼ τ)),\n    HaskCoercion Γ Δ (flatten_type σ ∼∼∼ flatten_type τ).\n\n  Axiom flatten_commutes_with_substT :\n    forall  κ Γ (Δ:CoercionEnv Γ) (σ:∀ TV, InstantiatedTypeEnv TV Γ → TV κ → RawHaskType TV ★) (τ:HaskType Γ κ),\n    flatten_type  (substT σ τ) = substT (fun TV ite v => flatten_rawtype  (σ TV ite v))\n      (flatten_type  τ).\n\n  Axiom flatten_commutes_with_HaskTAll :\n    forall  κ Γ (Δ:CoercionEnv Γ) (σ:∀ TV, InstantiatedTypeEnv TV Γ → TV κ → RawHaskType TV ★),\n    flatten_type  (HaskTAll κ σ) = HaskTAll κ (fun TV ite v => flatten_rawtype (σ TV ite v)).\n\n  Axiom flatten_commutes_with_HaskTApp :\n    forall n κ Γ (Δ:CoercionEnv Γ) (σ:∀ TV, InstantiatedTypeEnv TV Γ → TV κ → RawHaskType TV ★),\n    flatten_type  (HaskTApp (weakF_ σ) (FreshHaskTyVar_ κ)) =\n    HaskTApp (weakF_ (fun TV ite v => flatten_rawtype  (σ TV ite v))) (FreshHaskTyVar_(n:=n) κ).\n\n  Axiom flatten_commutes_with_weakLT : forall n (Γ:TypeEnv) κ t,\n    flatten_leveled_type  (weakLT_(n:=n)(Γ:=Γ)(κ:=κ) t) = weakLT_(n:=n)(Γ:=Γ)(κ:=κ) (flatten_leveled_type  t).\n\n  Axiom globals_do_not_have_code_types : forall (Γ:TypeEnv) (g:Global Γ) v,\n    flatten_type (g v) = g v.\n\n  (* \"n\" is the maximum depth remaining AFTER flattening *)\n  Definition flatten_judgment (j:Judg) :=\n    match j as J return Judg with\n      | Γ > Δ > ant |- suc @ nil        => Γ > Δ > mapOptionTree flatten_leveled_type ant\n                                                |- mapOptionTree flatten_type suc @ nil\n      | Γ > Δ > ant |- suc @ (ec::lev') => Γ > Δ > mapOptionTree flatten_leveled_type (drop_lev (ec::lev') ant)\n                                                |- [ga_mk (v2t ec)\n                                                  (mapOptionTree (flatten_type ○ unlev) (take_lev (ec::lev') ant))\n                                                  (mapOptionTree  flatten_type                               suc )\n                                                  ] @ nil\n    end.\n\n  Class garrow :=\n  { ga_id        : ∀ Γ Δ ec l a    , ND Rule [] [Γ > Δ >                          [] |- [@ga_mk Γ ec a a ]@l ]\n  ; ga_cancelr   : ∀ Γ Δ ec l a    , ND Rule [] [Γ > Δ >                          [] |- [@ga_mk Γ ec (a,,[]) a ]@l ]\n  ; ga_cancell   : ∀ Γ Δ ec l a    , ND Rule [] [Γ > Δ >                          [] |- [@ga_mk Γ ec ([],,a) a ]@l ]\n  ; ga_uncancelr : ∀ Γ Δ ec l a    , ND Rule [] [Γ > Δ >                          [] |- [@ga_mk Γ ec a (a,,[]) ]@l ]\n  ; ga_uncancell : ∀ Γ Δ ec l a    , ND Rule [] [Γ > Δ >                          [] |- [@ga_mk Γ ec a ([],,a) ]@l ]\n  ; ga_assoc     : ∀ Γ Δ ec l a b c, ND Rule [] [Γ > Δ >                          [] |- [@ga_mk Γ ec ((a,,b),,c) (a,,(b,,c)) ]@l ]\n  ; ga_unassoc   : ∀ Γ Δ ec l a b c, ND Rule [] [Γ > Δ >                          [] |- [@ga_mk Γ ec (a,,(b,,c)) ((a,,b),,c) ]@l ]\n  ; ga_swap      : ∀ Γ Δ ec l a b  , ND Rule [] [Γ > Δ >                          [] |- [@ga_mk Γ ec (a,,b) (b,,a) ]@l ]\n  ; ga_drop      : ∀ Γ Δ ec l a    , ND Rule [] [Γ > Δ >                          [] |- [@ga_mk Γ ec a [] ]@l ]\n  ; ga_copy      : ∀ Γ Δ ec l a    , ND Rule [] [Γ > Δ >                          [] |- [@ga_mk Γ ec a (a,,a) ]@l ]\n  ; ga_first     : ∀ Γ Δ ec l a b x, ND Rule [] [Γ > Δ >      [@ga_mk Γ ec a b @@l] |- [@ga_mk Γ ec (a,,x) (b,,x) ]@l ]\n  ; ga_second    : ∀ Γ Δ ec l a b x, ND Rule [] [Γ > Δ >      [@ga_mk Γ ec a b @@l] |- [@ga_mk Γ ec (x,,a) (x,,b) ]@l ]\n  ; ga_lit       : ∀ Γ Δ ec l lit  , ND Rule [] [Γ > Δ >                          [] |- [@ga_mk Γ ec [] [literalType lit] ]@l ]\n  ; ga_curry     : ∀ Γ Δ ec l a b c, ND Rule [] [Γ > Δ > [@ga_mk Γ ec (a,,[b]) [c] @@ l] |- [@ga_mk Γ ec a [b ---> c] ]@ l ]\n  ; ga_loopl     : ∀ Γ Δ ec l x y z, ND Rule [] [Γ > Δ > [@ga_mk Γ ec (z,,x) (z,,y) @@ l] |- [@ga_mk Γ ec x y ]@ l ]\n  ; ga_loopr     : ∀ Γ Δ ec l x y z, ND Rule [] [Γ > Δ > [@ga_mk Γ ec (x,,z) (y,,z) @@ l] |- [@ga_mk Γ ec x y ]@ l ]\n  ; ga_comp      : ∀ Γ Δ ec l a b c, ND Rule [] [Γ > Δ > [@ga_mk Γ ec a b @@ l],,[@ga_mk Γ ec b c @@ l] |- [@ga_mk Γ ec a c ]@l ] \n  ; ga_apply     : ∀ Γ Δ ec l a a' b c,\n                 ND Rule [] [Γ > Δ > [@ga_mk Γ ec a [b ---> c] @@ l],,[@ga_mk Γ ec a' [b] @@ l] |- [@ga_mk Γ ec (a,,a') [c] ]@l ]\n  ; ga_kappa     : ∀ Γ Δ ec l a b c Σ, ND Rule\n  [Γ > Δ > Σ,,[@ga_mk Γ ec [] a @@ l] |- [@ga_mk Γ ec b c      ]@l ]\n  [Γ > Δ > Σ                          |- [@ga_mk Γ ec (a,,b) c ]@l ]\n  }.\n  Context `(gar:garrow).\n\n  Notation \"a ~~~~> b\" := (@ga_mk _ _ a b) (at level 20).\n\n  Definition boost : forall Γ Δ ant x y {lev},\n    ND Rule []                         [ Γ > Δ > [x@@lev] |- [y]@lev ] ->\n    ND Rule [ Γ > Δ > ant |- [x]@lev ] [ Γ > Δ > ant      |- [y]@lev ].\n    intros.\n    eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply ACanR ].\n    eapply nd_comp; [ idtac | apply RLet ].\n    eapply nd_comp; [ apply nd_rlecnac | idtac ].\n    apply nd_prod.\n    apply nd_id.\n    eapply nd_comp.\n      apply X.\n      eapply nd_rule.\n      eapply RArrange.\n      apply AuCanR.\n    Defined.\n\n  Definition precompose Γ Δ ec : forall a x y z lev,\n    ND Rule\n      [ Γ > Δ > a                           |- [@ga_mk _ ec y z ]@lev ]\n      [ Γ > Δ > a,,[@ga_mk _ ec x y @@ lev] |- [@ga_mk _ ec x z ]@lev ].\n    intros.\n    eapply nd_comp; [ idtac | eapply RLet ].\n    eapply nd_comp; [ apply nd_rlecnac | idtac ].\n    apply nd_prod.\n    apply nd_id.\n    eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AExch ].\n    apply ga_comp.\n    Defined.\n\n  Definition precompose' Γ Δ ec : forall a b x y z lev,\n    ND Rule\n      [ Γ > Δ > a,,b                             |- [@ga_mk _ ec y z ]@lev ]\n      [ Γ > Δ > a,,([@ga_mk _ ec x y @@ lev],,b) |- [@ga_mk _ ec x z ]@lev ].\n    intros.\n    eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply ALeft; eapply AExch ].\n    eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AuAssoc ].\n    apply precompose.\n    Defined.\n\n  Definition postcompose_ Γ Δ ec : forall a x y z lev,\n    ND Rule\n      [ Γ > Δ > a                           |- [@ga_mk _ ec x y ]@lev ]\n      [ Γ > Δ > a,,[@ga_mk _ ec y z @@ lev] |- [@ga_mk _ ec x z ]@lev ].\n    intros.\n    eapply nd_comp; [ idtac | eapply RLet ].\n    eapply nd_comp; [ apply nd_rlecnac | idtac ].\n    apply nd_prod.\n    apply nd_id.\n    apply ga_comp.\n    Defined.\n\n  Definition postcompose  Γ Δ ec : forall x y z lev,\n    ND Rule [] [ Γ > Δ > []                       |- [@ga_mk _ ec x y ]@lev ] ->\n    ND Rule [] [ Γ > Δ > [@ga_mk _ ec y z @@ lev] |- [@ga_mk _ ec x z ]@lev ].\n    intros.\n    eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply ACanL ].\n    eapply nd_comp; [ idtac | eapply postcompose_ ].\n    apply X.\n    Defined.\n\n  Definition first_nd : ∀ Γ Δ ec lev a b c Σ,\n    ND Rule [ Γ > Δ > Σ                    |- [@ga_mk Γ ec a b ]@lev ]\n            [ Γ > Δ > Σ                    |- [@ga_mk Γ ec (a,,c) (b,,c) ]@lev ].\n    intros.\n    eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply ACanR ].\n    eapply nd_comp; [ idtac | apply RLet ].\n    eapply nd_comp; [ apply nd_rlecnac | idtac ].\n    apply nd_prod.\n    apply nd_id.\n    eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AuCanR ].\n    apply ga_first.\n    Defined.\n\n  Definition firstify : ∀ Γ Δ ec lev a b c Σ,\n    ND Rule [] [ Γ > Δ > Σ                    |- [@ga_mk Γ ec a b ]@lev ] ->\n    ND Rule [] [ Γ > Δ > Σ                    |- [@ga_mk Γ ec (a,,c) (b,,c) ]@lev ].\n    intros.\n    eapply nd_comp.\n    apply X.\n    apply first_nd.\n    Defined.\n\n  Definition second_nd : ∀ Γ Δ ec lev a b c Σ,\n     ND Rule\n     [ Γ > Δ > Σ                    |- [@ga_mk Γ ec a b ]@lev ]\n     [ Γ > Δ > Σ                    |- [@ga_mk Γ ec (c,,a) (c,,b) ]@lev ].\n    intros.\n    eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply ACanR ].\n    eapply nd_comp; [ idtac | apply RLet ].\n    eapply nd_comp; [ apply nd_rlecnac | idtac ].\n    apply nd_prod.\n    apply nd_id.\n    eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AuCanR ].\n    apply ga_second.\n    Defined.\n\n  Definition secondify : ∀ Γ Δ ec lev a b c Σ,\n     ND Rule [] [ Γ > Δ > Σ                    |- [@ga_mk Γ ec a b ]@lev ] ->\n     ND Rule [] [ Γ > Δ > Σ                    |- [@ga_mk Γ ec (c,,a) (c,,b) ]@lev ].\n    intros.\n    eapply nd_comp.\n    apply X.\n    apply second_nd.\n    Defined.\n\n   Lemma ga_unkappa     : ∀ Γ Δ ec l a b Σ x,\n     ND Rule\n     [Γ > Δ > Σ                          |- [@ga_mk Γ ec (a,,x)  b ]@l ] \n     [Γ > Δ > Σ,,[@ga_mk Γ ec [] a @@ l] |- [@ga_mk Γ ec x       b ]@l ].\n     intros.\n     eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AExch ].\n     eapply nd_comp; [ idtac | eapply RLet ].\n     eapply nd_comp; [ apply nd_llecnac | idtac ].\n     apply nd_prod.\n     apply ga_first.\n\n     eapply nd_comp; [ idtac | eapply RLet ].\n     eapply nd_comp; [ apply nd_llecnac | idtac ].\n     apply nd_prod.\n     apply postcompose.\n     apply ga_uncancell.\n     eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AExch ].\n     apply precompose.\n     Defined.\n\n\n\n\n  (* useful for cutting down on the pretty-printed noise\n  \n  Notation \"`  x\" := (take_lev _ x) (at level 20).\n  Notation \"`` x\" := (mapOptionTree unlev x) (at level 20).\n  Notation \"``` x\" := (drop_lev _ x) (at level 20).\n  *)\n  Definition flatten_arrangement' :\n    forall Γ (Δ:CoercionEnv Γ)\n      (ec:HaskTyVar Γ ECKind) (lev:HaskLevel Γ) (ant1 ant2:Tree ??(LeveledHaskType Γ ★)) (r:Arrange ant1 ant2),\n      ND Rule [] [Γ > Δ > [] |- [@ga_mk _ (v2t ec) (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) ant2))\n        (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) ant1)) ]@nil ].\n\n      intros Γ Δ ec lev.\n      refine (fix flatten ant1 ant2 (r:Arrange ant1 ant2):\n           ND Rule [] [Γ > Δ > [] |- [@ga_mk _ (v2t ec)\n             (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) ant2))\n             (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) ant1)) ]@nil] :=\n        match r as R in Arrange A B return\n          ND Rule [] [Γ > Δ > [] |- [@ga_mk _ (v2t ec)\n            (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) B))\n            (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) A)) ]@nil]\n          with\n          | AId  a               => let case_AId := tt    in ga_id _ _ _ _ _\n          | ACanL  a             => let case_ACanL := tt  in ga_uncancell _ _ _ _ _\n          | ACanR  a             => let case_ACanR := tt  in ga_uncancelr _ _ _ _ _\n          | AuCanL a             => let case_AuCanL := tt in ga_cancell _ _ _ _ _\n          | AuCanR a             => let case_AuCanR := tt in ga_cancelr _ _ _ _ _\n          | AAssoc a b c         => let case_AAssoc := tt in ga_assoc _ _ _ _ _ _ _\n          | AuAssoc a b c         => let case_AuAssoc := tt in ga_unassoc _ _ _ _ _ _ _\n          | AExch  a b           => let case_AExch := tt  in ga_swap  _ _ _ _ _ _\n          | AWeak  a             => let case_AWeak := tt  in ga_drop _ _ _ _ _ \n          | ACont  a             => let case_ACont := tt  in ga_copy  _ _ _ _ _ \n          | ALeft  a b c r'      => let case_ALeft := tt  in flatten _ _ r' ;; boost _ _ _ _ _ (ga_second _ _ _ _ _ _ _)\n          | ARight a b c r'      => let case_ARight := tt in flatten _ _ r' ;; boost _ _ _ _ _ (ga_first  _ _ _ _ _ _ _)\n          | AComp  c b a r1 r2   => let case_AComp := tt  in (fun r1' r2' => _) (flatten _ _ r1) (flatten _ _ r2)\n        end); clear flatten; repeat take_simplify; repeat drop_simplify; intros.\n\n        destruct case_AComp.\n          set (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) a)) as a' in *.\n          set (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) b)) as b' in *.\n          set (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) c)) as c' in *.\n          eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; apply ACanL ].\n          eapply nd_comp; [ idtac | apply\n             (@RLet Γ Δ [] [] (@ga_mk _ (v2t ec) a' b') (@ga_mk _ (v2t ec) a' c')) ].\n          eapply nd_comp; [ apply nd_llecnac | idtac ].\n          apply nd_prod.\n          apply r2'.\n          eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; apply AuCanR ].\n          eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; apply ACanL ].\n          eapply nd_comp; [ idtac | apply RLet ].\n          eapply nd_comp; [ apply nd_llecnac | idtac ].\n          eapply nd_prod.\n          apply r1'.\n          eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AExch ].\n          apply ga_comp.\n          Defined.\n\n  Definition flatten_arrangement :\n    forall Γ (Δ:CoercionEnv Γ) n\n      (ec:HaskTyVar Γ ECKind) (lev:HaskLevel Γ) (ant1 ant2:Tree ??(LeveledHaskType Γ ★)) (r:Arrange ant1 ant2) succ,\n      ND Rule\n      [Γ > Δ > mapOptionTree (flatten_leveled_type ) (drop_lev n ant1)\n        |- [@ga_mk _ (v2t ec)\n          (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) ant1))\n          (mapOptionTree (flatten_type ) succ) ]@nil]\n      [Γ > Δ > mapOptionTree (flatten_leveled_type ) (drop_lev n ant2)\n        |- [@ga_mk _ (v2t ec)\n          (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) ant2))\n          (mapOptionTree (flatten_type ) succ) ]@nil].\n      intros.\n      refine ( _ ;; (boost _ _ _ _ _ (postcompose _ _ _ _ _ _ _ (flatten_arrangement' Γ Δ ec lev ant1 ant2 r)))).\n      apply nd_rule.\n      apply RArrange.\n      refine ((fix flatten ant1 ant2 (r:Arrange ant1 ant2) :=\n        match r as R in Arrange A B return\n          Arrange (mapOptionTree (flatten_leveled_type ) (drop_lev _ A))\n          (mapOptionTree (flatten_leveled_type ) (drop_lev _ B)) with\n          | AId  a               => let case_AId := tt  in AId _\n          | ACanL  a             => let case_ACanL := tt  in ACanL _\n          | ACanR  a             => let case_ACanR := tt  in ACanR _\n          | AuCanL a             => let case_AuCanL := tt in AuCanL _\n          | AuCanR a             => let case_AuCanR := tt in AuCanR _\n          | AAssoc a b c         => let case_AAssoc := tt in AAssoc _ _ _\n          | AuAssoc a b c         => let case_AuAssoc := tt in AuAssoc _ _ _\n          | AExch  a b           => let case_AExch := tt  in AExch _ _\n          | AWeak  a             => let case_AWeak := tt  in AWeak _\n          | ACont  a             => let case_ACont := tt  in ACont _\n          | ALeft  a b c r'      => let case_ALeft := tt  in ALeft  _ (flatten _ _ r')\n          | ARight a b c r'      => let case_ARight := tt in ARight _ (flatten _ _ r')\n          | AComp  a b c r1 r2   => let case_AComp := tt  in AComp    (flatten _ _ r1) (flatten _ _ r2)\n        end) ant1 ant2 r); clear flatten; repeat take_simplify; repeat drop_simplify; intros.\n        Defined.\n\n  Definition flatten_arrangement'' :\n    forall  Γ Δ ant1 ant2 succ l (r:Arrange ant1 ant2),\n      ND Rule (mapOptionTree (flatten_judgment ) [Γ > Δ > ant1 |- succ @ l])\n      (mapOptionTree (flatten_judgment ) [Γ > Δ > ant2 |- succ @ l]).\n    intros.\n    simpl.\n    destruct l.\n      apply nd_rule.\n      apply RArrange.\n      induction r; simpl.\n        apply AId.\n        apply ACanL.\n        apply ACanR.\n        apply AuCanL.\n        apply AuCanR.\n        apply AAssoc.\n        apply AuAssoc.\n        apply AExch.    (* TO DO: check for all-leaf trees here *)\n        apply AWeak.\n        apply ACont.\n        apply ALeft; auto.\n        apply ARight; auto.\n        eapply AComp; [ apply IHr1 | apply IHr2 ].\n\n      apply flatten_arrangement.\n        apply r.\n        Defined.\n\n  Definition ga_join Γ Δ Σ₁ Σ₂ a b ec :\n    ND Rule [] [Γ > Δ > Σ₁     |- [@ga_mk _ ec [] a      ]@nil] ->\n    ND Rule [] [Γ > Δ > Σ₂     |- [@ga_mk _ ec [] b      ]@nil] ->\n    ND Rule [] [Γ > Δ > Σ₁,,Σ₂ |- [@ga_mk _ ec [] (a,,b) ]@nil].\n    intro pfa.\n    intro pfb.\n    apply secondify with (c:=a)  in pfb.\n    apply firstify  with (c:=[])  in pfa.\n    eapply nd_comp; [ idtac | eapply RLet ].\n    eapply nd_comp; [ eapply nd_llecnac | idtac ].\n    apply nd_prod.\n    apply pfa.\n    clear pfa.\n\n    eapply nd_comp; [ idtac | eapply RLet ].\n    eapply nd_comp; [ apply nd_llecnac | idtac ].\n    apply nd_prod.\n    eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply ACanL ].\n    eapply nd_comp; [ idtac | eapply postcompose_ ].\n    apply ga_uncancelr.\n\n    eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AExch ].\n    eapply nd_comp; [ idtac | eapply precompose ].\n    apply pfb.\n    Defined.\n\n  Definition arrange_brak : forall Γ Δ ec succ t,\n   ND Rule\n     [Γ > Δ > \n      [(@ga_mk _ (v2t ec) [] (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: nil) succ))) @@  nil],,\n      mapOptionTree (flatten_leveled_type ) (drop_lev (ec :: nil) succ) |- [t]@nil]\n     [Γ > Δ > mapOptionTree (flatten_leveled_type ) succ |- [t]@nil].\n\n    intros.\n    unfold drop_lev.\n    set (@arrangeUnPartition _ succ (levelMatch (ec::nil))) as q.\n    set (arrangeMap _ _ flatten_leveled_type q) as y.\n    eapply nd_comp.\n    Focus 2.\n    eapply nd_rule.\n    eapply RArrange.\n    apply y.\n    idtac.\n    clear y q.\n    eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AExch ].\n    simpl.\n    eapply nd_comp; [ apply nd_llecnac | idtac ].\n    eapply nd_comp; [ idtac | eapply RLet ].\n    apply nd_prod.\n    Focus 2.\n    apply nd_id.\n    idtac.\n    induction succ; try destruct a; simpl.\n    unfold take_lev.\n    unfold mkTakeFlags.\n    unfold mkFlags.\n    unfold bnot.\n    simpl.\n    destruct l as [t' lev'].\n    destruct lev' as [|ec' lev'].\n    simpl.\n    apply ga_id.\n    unfold levelMatch.\n    set (@eqd_dec (HaskLevel Γ) (haskLevelEqDecidable Γ) (ec' :: lev') (ec :: nil)) as q.\n    destruct q.\n    inversion e; subst.\n    simpl.\n    apply nd_rule.\n    unfold flatten_leveled_type.\n    simpl.\n    unfold flatten_type.\n    simpl.\n    unfold ga_mk.\n    simpl.\n    apply RVar.\n    simpl.\n    apply ga_id.\n    apply ga_id.\n    unfold take_lev.\n    simpl.\n    apply ga_join.\n      apply IHsucc1.\n      apply IHsucc2.\n    Defined.\n\n  Definition arrange_esc : forall Γ Δ ec succ t,\n   ND Rule\n     [Γ > Δ > mapOptionTree (flatten_leveled_type ) succ |- [t]@nil]\n     [Γ > Δ > \n      [(@ga_mk _ (v2t ec) [] (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: nil) succ))) @@  nil],,\n      mapOptionTree (flatten_leveled_type ) (drop_lev (ec :: nil) succ)  |- [t]@nil].\n    intros.\n    set (@arrangePartition _ succ (levelMatch (ec::nil))) as q.\n    set (@drop_lev Γ (ec::nil) succ) as q'.\n    assert (@drop_lev Γ (ec::nil) succ=q') as H.\n      reflexivity.\n    unfold drop_lev in H.\n    unfold mkDropFlags in H.\n    rewrite H in q.\n    clear H.\n    set (arrangeMap _ _ flatten_leveled_type q) as y.\n    eapply nd_comp.\n    eapply nd_rule.\n    eapply RArrange.\n    apply y.\n    clear y q.\n\n    set (mapOptionTree flatten_leveled_type (dropT (mkFlags (liftBoolFunc false (bnot ○ levelMatch (ec :: nil))) succ))) as q.\n    destruct (decide_tree_empty q).\n\n      destruct s.\n      simpl.\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; apply AExch ].\n      set (fun z z' => @RLet Γ Δ z (mapOptionTree flatten_leveled_type q') t z' nil) as q''.\n      eapply nd_comp; [ idtac | apply RLet ].\n      clear q''.\n      eapply nd_comp; [ apply nd_rlecnac | idtac ].\n      apply nd_prod.\n      apply nd_rule.\n      apply RArrange.\n      eapply AComp; [ idtac | apply ACanR ].\n      apply ALeft.\n      apply (@arrangeCancelEmptyTree _ _ _ _ e).\n   \n      eapply nd_comp.\n        eapply nd_rule.\n        eapply (@RVar Γ Δ t nil).\n      apply nd_rule.\n        apply RArrange.\n        eapply AComp.\n        apply AuCanR.\n        apply ALeft.\n        apply AWeak.\n\n      simpl.\n      clear q.\n      unfold q'.\n      clear q'.\n      apply nd_rule.\n      apply RArrange.\n      induction succ.\n      destruct a.\n      destruct l as [t' l']. \n      simpl.\n      Transparent drop_lev.\n      simpl.\n      unfold take_lev.\n      unfold mkTakeFlags.\n      simpl.\n      unfold drop_lev.\n      simpl.\n      unfold mkDropFlags.\n      simpl.\n      unfold flatten_leveled_type.\n      destruct (General.list_eq_dec l' (ec :: nil)); simpl.\n      rewrite e.\n      unfold levels_to_tcode.\n      eapply AComp.\n      apply ACanL.\n      apply AuCanR.\n      eapply AComp.\n      apply ACanR.\n      eapply AComp.\n      apply AuCanL.\n      apply ARight.\n      apply AWeak.\n      \n      simpl.\n      apply ARight.\n      apply AWeak.\n      \n      drop_simplify.\n      simpl.\n      set (mapOptionTree flatten_leveled_type (drop_lev (ec :: nil) succ2)) as d2 in *.\n      set (mapOptionTree flatten_leveled_type (drop_lev (ec :: nil) succ1)) as d1 in *.\n      set (mapOptionTree flatten_leveled_type (dropT (mkFlags\n        (liftBoolFunc false (bnot ○ levelMatch (ec :: nil))) succ1))) as s1 in *.\n      set (mapOptionTree flatten_leveled_type (dropT (mkFlags\n        (liftBoolFunc false (bnot ○ levelMatch (ec :: nil))) succ2))) as s2 in *.\n      set (mapOptionTree (flatten_type ○ unlev) (dropT (mkFlags\n        (liftBoolFunc true (bnot ○ levelMatch (ec :: nil))) succ1))) as s1' in *.\n      set (mapOptionTree (flatten_type ○ unlev) (dropT (mkFlags\n        (liftBoolFunc true (bnot ○ levelMatch (ec :: nil))) succ2))) as s2' in *.\n\n      eapply AComp.\n      apply arrangeSwapMiddle.\n      \n      eapply AComp.\n      eapply ALeft.\n      apply IHsucc2.\n      \n      eapply AComp.\n      eapply ARight.\n      apply IHsucc1.\n      \n      eapply AComp.\n      apply arrangeSwapMiddle.\n      apply ARight.\n      unfold take_lev.\n      unfold mkTakeFlags.\n      \n      unfold s1'.\n      unfold s2'.\n      clear s1' s2'.\n      set (mapOptionTree (flatten_type ○ unlev) (dropT (mkFlags\n        (liftBoolFunc true (bnot ○ levelMatch (ec :: nil))) succ1))) as s1' in *.\n      set (mapOptionTree (flatten_type ○ unlev) (dropT (mkFlags\n        (liftBoolFunc true (bnot ○ levelMatch (ec :: nil))) succ2))) as s2' in *.\n      \n      apply (Prelude_error \"almost there!\").\n    Defined.\n\n  Lemma unlev_relev : forall {Γ}(t:Tree ??(HaskType Γ ★)) lev, mapOptionTree unlev (t @@@ lev) = t.\n    intros.\n    induction t.\n    destruct a; reflexivity.\n    rewrite <- IHt1 at 2.\n    rewrite <- IHt2 at 2.\n    reflexivity.\n    Qed.\n\n  Lemma tree_of_nothing : forall Γ ec t,\n    Arrange (mapOptionTree flatten_leveled_type (drop_lev(Γ:=Γ) (ec :: nil) (t @@@ (ec :: nil)))) [].\n    intros.\n    induction t; try destruct o; try destruct a.\n    simpl.\n    drop_simplify.\n    simpl.\n    apply AId.\n    simpl.\n    apply AId.\n    eapply AComp; [ idtac | apply ACanL ].\n    eapply AComp; [ idtac | eapply ALeft; apply IHt2 ].\n    Opaque drop_lev.\n    simpl.\n    Transparent drop_lev.\n    idtac.\n    drop_simplify.\n    apply ARight.\n    apply IHt1.\n    Defined.\n\n  Lemma tree_of_nothing' : forall Γ ec t,\n    Arrange [] (mapOptionTree flatten_leveled_type (drop_lev(Γ:=Γ) (ec :: nil) (t @@@ (ec :: nil)))).\n    intros.\n    induction t; try destruct o; try destruct a.\n    simpl.\n    drop_simplify.\n    simpl.\n    apply AId.\n    simpl.\n    apply AId.\n    eapply AComp; [ apply AuCanL | idtac ].\n    eapply AComp; [ eapply ARight; apply IHt1 | idtac ].\n    Opaque drop_lev.\n    simpl.\n    Transparent drop_lev.\n    idtac.\n    drop_simplify.\n    apply ALeft.\n    apply IHt2.\n    Defined.\n\n  Lemma krunk : forall Γ (ec:HaskTyVar Γ ECKind) t,\n    flatten_type (<[ ec |- t ]>)\n    = @ga_mk Γ (v2t ec)\n    (mapOptionTree flatten_type (take_arg_types_as_tree t))\n    [ flatten_type (drop_arg_types_as_tree   t)].\n    intros.\n    unfold flatten_type at 1.\n    simpl.\n    unfold ga_mk.\n    apply phoas_extensionality.\n    intros.\n    unfold v2t.\n    unfold ga_mk_raw.\n    unfold ga_mk_tree.\n    rewrite <- mapOptionTree_compose.\n    unfold take_arg_types_as_tree.\n    simpl.\n    replace (flatten_type (drop_arg_types_as_tree t) tv ite)\n      with (drop_arg_types (flatten_rawtype (t tv ite))).\n    replace (unleaves_ (take_arg_types (flatten_rawtype (t tv ite))))\n      with ((mapOptionTree (fun x : HaskType Γ ★ => flatten_type x tv ite)\n           (unleaves_\n              (take_trustme (count_arg_types (t (fun _ : Kind => unit) (ite_unit Γ)))\n                 (fun TV : Kind → Type => take_arg_types ○ t TV))))).\n    reflexivity.\n    unfold flatten_type.\n    clear gar.\n    set (t tv ite) as x.\n    admit.\n    admit.\n    Qed.\n\n  Lemma drop_to_nothing : forall (Γ:TypeEnv) Σ (lev:HaskLevel Γ),\n    drop_lev lev (Σ @@@ lev) = mapTree (fun _ => None) (mapTree (fun _ => tt) Σ).\n    intros.\n    induction Σ.\n    destruct a; simpl.\n    drop_simplify.\n    auto.\n    drop_simplify.\n    auto.\n    simpl.\n    rewrite <- IHΣ1.\n    rewrite <- IHΣ2.\n    reflexivity.\n    Qed.\n\n  Definition flatten_skolemized_proof :\n    forall  {h}{c},\n      ND SRule h c ->\n      ND  Rule (mapOptionTree (flatten_judgment ) h) (mapOptionTree (flatten_judgment ) c).\n    intros.\n    eapply nd_map'; [ idtac | apply X ].\n    clear h c X.\n    intros.\n    simpl in *.\n\n    refine \n      (match X as R in SRule H C with\n      | SBrak    Γ Δ t ec succ lev           => let case_SBrak := tt         in _\n      | SEsc     Γ Δ t ec succ lev           => let case_SEsc := tt          in _\n      | SFlat    h c r                       => let case_SFlat := tt         in _\n      end).\n\n    destruct case_SFlat.\n    refine (match r as R in Rule H C with\n      | RArrange Γ Δ a b x l d         => let case_RArrange := tt      in _\n      | RNote    Γ Δ Σ τ l n           => let case_RNote := tt         in _\n      | RLit     Γ Δ l     _           => let case_RLit := tt          in _\n      | RVar     Γ Δ σ           lev   => let case_RVar := tt          in _\n      | RGlobal  Γ Δ σ l wev           => let case_RGlobal := tt       in _\n      | RLam     Γ Δ Σ tx te     lev   => let case_RLam := tt          in _\n      | RCast    Γ Δ Σ σ τ lev γ       => let case_RCast := tt         in _\n      | RAbsT    Γ Δ Σ κ σ lev n       => let case_RAbsT := tt         in _\n      | RAppT    Γ Δ Σ κ σ τ     lev   => let case_RAppT := tt         in _\n      | RAppCo   Γ Δ Σ κ σ₁ σ₂ γ σ lev => let case_RAppCo := tt        in _\n      | RAbsCo   Γ Δ Σ κ σ  σ₁ σ₂  lev => let case_RAbsCo := tt        in _\n      | RApp     Γ Δ Σ₁ Σ₂ tx te lev   => let case_RApp := tt          in _\n      | RCut     Γ Δ Σ Σ₁ Σ₁₂ Σ₂ Σ₃ l  => let case_RCut := tt          in _\n      | RLeft    Γ Δ Σ₁ Σ₂  Σ     l    => let case_RLeft := tt in _\n      | RRight   Γ Δ Σ₁ Σ₂  Σ     l    => let case_RRight := tt in _\n      | RVoid    _ _       l           => let case_RVoid := tt   in _\n      | RBrak    Γ Δ t ec succ lev           => let case_RBrak := tt         in _\n      | REsc     Γ Δ t ec succ lev           => let case_REsc := tt          in _\n      | RCase    Γ Δ lev tc Σ avars tbranches alts => let case_RCase := tt         in _\n      | RLetRec  Γ Δ lri x y t         => let case_RLetRec := tt       in _\n      end); clear X h c.\n\n    destruct case_RArrange.\n      apply (flatten_arrangement''  Γ Δ a b x _ d).\n\n    destruct case_RBrak.\n      apply (Prelude_error \"found unskolemized Brak rule; this shouldn't happen\").\n\n    destruct case_REsc.\n      apply (Prelude_error \"found unskolemized Esc rule; this shouldn't happen\").\n      \n    destruct case_RNote.\n      simpl.\n      destruct l; simpl.\n        apply nd_rule; apply RNote; auto.\n        apply nd_rule; apply RNote; auto.\n\n    destruct case_RLit.\n      simpl.\n      destruct l0; simpl.\n        unfold flatten_leveled_type.\n        simpl.\n        rewrite literal_types_unchanged.\n          apply nd_rule; apply RLit.\n        unfold take_lev; simpl.\n        unfold drop_lev; simpl.\n        simpl.\n        rewrite literal_types_unchanged.\n        apply ga_lit.\n\n    destruct case_RVar.\n      Opaque flatten_judgment.\n      simpl.\n      Transparent flatten_judgment.\n      idtac.\n      unfold flatten_judgment.\n      destruct lev.\n      apply nd_rule. apply RVar.\n      repeat drop_simplify.      \n      repeat take_simplify.\n      simpl.\n      apply ga_id.      \n\n    destruct case_RGlobal.\n      simpl.\n      rename l into g.\n      rename σ into l.\n      destruct l as [|ec lev]; simpl. \n        (*\n        destruct (eqd_dec (g:CoreVar) (hetmet_flatten:CoreVar)).\n          set (flatten_type (g wev)) as t.\n          set (RGlobal _ Δ nil (mkGlobal Γ t hetmet_id)) as q.\n          simpl in q.\n          apply nd_rule.\n          apply q.\n          apply INil.\n        destruct (eqd_dec (g:CoreVar) (hetmet_unflatten:CoreVar)).\n          set (flatten_type (g wev)) as t.\n          set (RGlobal _ Δ nil (mkGlobal Γ t hetmet_id)) as q.\n          simpl in q.\n          apply nd_rule.\n          apply q.\n          apply INil.\n          *)\n        unfold flatten_leveled_type. simpl.\n          apply nd_rule; rewrite globals_do_not_have_code_types.\n          apply RGlobal.\n      apply (Prelude_error \"found RGlobal at depth >0; globals should never appear inside code brackets unless escaped\").\n\n    destruct case_RLam.\n      Opaque drop_lev.\n      Opaque take_lev.\n      simpl.\n      destruct lev as [|ec lev]; simpl; [ apply nd_rule; apply RLam; auto | idtac ].\n      repeat drop_simplify.\n      repeat take_simplify.\n      eapply nd_comp.\n        eapply nd_rule.\n        eapply RArrange.\n        simpl.\n        apply ACanR.\n      apply boost.\n      simpl.\n      apply ga_curry.\n\n    destruct case_RCast.\n      simpl.\n      destruct lev as [|ec lev]; simpl; [ apply nd_rule; apply RCast; auto | idtac ].\n      simpl.\n      apply flatten_coercion; auto.\n      apply (Prelude_error \"RCast at level >0; casting inside of code brackets is currently not supported\").\n\n    destruct case_RApp.\n      simpl.\n\n      destruct lev as [|ec lev].\n        unfold flatten_type at 1.\n        simpl.\n        apply nd_rule.\n        apply RApp.\n\n        repeat drop_simplify.\n          repeat take_simplify.\n          rewrite mapOptionTree_distributes.\n          set (mapOptionTree (flatten_leveled_type ) (drop_lev (ec :: lev) Σ₁)) as Σ₁'.\n          set (mapOptionTree (flatten_leveled_type ) (drop_lev (ec :: lev) Σ₂)) as Σ₂'.\n          set (take_lev (ec :: lev) Σ₁) as Σ₁''.\n          set (take_lev (ec :: lev) Σ₂) as Σ₂''.\n          replace (flatten_type  (tx ---> te)) with ((flatten_type  tx) ---> (flatten_type  te)).\n          apply (Prelude_error \"FIXME: ga_apply\").\n          reflexivity.\n\n(*\n  Notation \"`  x\" := (take_lev _ x).\n  Notation \"`` x\" := (mapOptionTree unlev x) (at level 20).\n  Notation \"``` x\" := ((drop_lev _ x)) (at level 20).\n  Notation \"!<[]> x\" := (flatten_type _ x) (at level 1).\n  Notation \"!<[@]> x\" := (mapOptionTree flatten_leveled_type x) (at level 1).\n*)\n\n    destruct case_RCut.\n      simpl.\n      destruct l as [|ec lev]; simpl.\n        apply nd_rule.\n        replace (mapOptionTree flatten_leveled_type (Σ₁₂ @@@ nil)) with (mapOptionTree flatten_type Σ₁₂ @@@ nil).\n        apply RCut.\n        induction Σ₁₂; try destruct a; auto.\n        simpl.\n        rewrite <- IHΣ₁₂1.\n        rewrite <- IHΣ₁₂2.\n        reflexivity.\n      simpl; repeat drop_simplify.\n      simpl; repeat take_simplify.\n      simpl.\n      set (drop_lev (ec :: lev) (Σ₁₂ @@@ (ec :: lev))) as x1.\n      rewrite take_lemma'.\n      rewrite mapOptionTree_compose.\n      rewrite mapOptionTree_compose.\n      rewrite mapOptionTree_compose.\n      rewrite mapOptionTree_compose.\n      rewrite unlev_relev.\n      rewrite <- mapOptionTree_compose.\n      rewrite <- mapOptionTree_compose.\n      rewrite <- mapOptionTree_compose.\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RCut ]. \n      apply nd_prod.\n      apply nd_id.\n      eapply nd_comp.\n      eapply nd_rule.\n      eapply RArrange.\n      eapply ALeft.\n      eapply ARight.\n      unfold x1.\n      rewrite drop_to_nothing.\n      apply arrangeCancelEmptyTree with (q:=(mapTree (fun _ : ??(HaskType Γ ★) => tt) Σ₁₂)).\n        induction Σ₁₂; try destruct a; auto.\n        simpl.\n        rewrite <- IHΣ₁₂1 at 2.\n        rewrite <- IHΣ₁₂2 at 2.\n        reflexivity.\n      eapply nd_comp; [ eapply nd_rule; eapply RArrange; eapply ALeft; eapply ACanL | idtac ].\n      set (mapOptionTree flatten_type Σ₁₂) as a.\n      set (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) Σ₁)) as b.\n      set (mapOptionTree flatten_leveled_type (drop_lev (ec :: lev) Σ₂)) as c.\n      set (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) Σ₂)) as d.\n      set (mapOptionTree flatten_leveled_type (drop_lev (ec :: lev) Σ)) as e.\n      set (mapOptionTree (flatten_type ○ unlev) (take_lev (ec :: lev) Σ)) as f.\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RCut ].\n      eapply nd_comp; [ apply nd_llecnac | idtac ].\n      apply nd_prod.\n      simpl.\n      eapply secondify.\n      apply ga_first.\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply ALeft; eapply AExch ].\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AuAssoc ].\n      simpl.\n      apply precompose.\n\n    destruct case_RLeft.\n      simpl.\n      destruct l as [|ec lev].\n      simpl.\n        replace (mapOptionTree flatten_leveled_type (Σ @@@ nil)) with (mapOptionTree flatten_type Σ @@@ nil).\n        apply nd_rule.\n        apply RLeft.\n        induction Σ; try destruct a; auto.\n        simpl.\n        rewrite <- IHΣ1.\n        rewrite <- IHΣ2.\n        reflexivity.\n      repeat drop_simplify.\n        rewrite drop_to_nothing.\n        simpl.\n        eapply nd_comp.\n        Focus 2.\n        eapply nd_rule.\n        eapply RArrange.\n        eapply ARight.\n        apply arrangeUnCancelEmptyTree with (q:=(mapTree (fun _ : ??(HaskType Γ ★) => tt) Σ)).\n          induction Σ; try destruct a; auto.\n          simpl.\n          rewrite <- IHΣ1 at 2.\n          rewrite <- IHΣ2 at 2.\n          reflexivity.\n        idtac.\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AuCanL ].\n        apply boost.\n        take_simplify.\n        simpl.\n        replace (take_lev (ec :: lev) (Σ @@@ (ec :: lev))) with (Σ @@@ (ec::lev)).\n        rewrite mapOptionTree_compose.\n        rewrite mapOptionTree_compose.\n        rewrite unlev_relev.\n        apply ga_second.\n      rewrite take_lemma'.\n      reflexivity.\n        \n    destruct case_RRight.\n      simpl.\n      destruct l as [|ec lev].\n      simpl.\n        replace (mapOptionTree flatten_leveled_type (Σ @@@ nil)) with (mapOptionTree flatten_type Σ @@@ nil).\n        apply nd_rule.\n        apply RRight.\n        induction Σ; try destruct a; auto.\n        simpl.\n        rewrite <- IHΣ1.\n        rewrite <- IHΣ2.\n        reflexivity.\n      repeat drop_simplify.\n        rewrite drop_to_nothing.\n        simpl.\n        eapply nd_comp.\n        Focus 2.\n        eapply nd_rule.\n        eapply RArrange.\n        eapply ALeft.\n        apply arrangeUnCancelEmptyTree with (q:=(mapTree (fun _ : ??(HaskType Γ ★) => tt) Σ)).\n          induction Σ; try destruct a; auto.\n          simpl.\n          rewrite <- IHΣ1 at 2.\n          rewrite <- IHΣ2 at 2.\n          reflexivity.\n        idtac.\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AuCanR ].\n        apply boost.\n        take_simplify.\n        simpl.\n        replace (take_lev (ec :: lev) (Σ @@@ (ec :: lev))) with (Σ @@@ (ec::lev)).\n        rewrite mapOptionTree_compose.\n        rewrite mapOptionTree_compose.\n        rewrite unlev_relev.\n        apply ga_first.\n      rewrite take_lemma'.\n      reflexivity.\n\n    destruct case_RVoid.\n      simpl.\n      destruct l.\n      apply nd_rule.\n      apply RVoid.\n      drop_simplify.\n      take_simplify.\n      simpl.\n      apply ga_id.\n        \n    destruct case_RAppT.\n      simpl. destruct lev; simpl.\n      unfold flatten_leveled_type.\n      simpl.\n      rewrite flatten_commutes_with_HaskTAll.\n      rewrite flatten_commutes_with_substT.\n      apply nd_rule.\n      apply RAppT.\n      apply Δ.\n      apply Δ.\n      apply (Prelude_error \"found type application at level >0; this is not supported\").\n\n    destruct case_RAbsT.\n      simpl. destruct lev; simpl.\n      rewrite flatten_commutes_with_HaskTAll.\n      rewrite flatten_commutes_with_HaskTApp.\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RAbsT ].\n      simpl.\n      set (mapOptionTree (flatten_leveled_type ) (mapOptionTree (weakLT_(n:=n)(κ:=κ)) Σ)) as a.\n      set (mapOptionTree (weakLT_(n:=n)(κ:=κ)) (mapOptionTree (flatten_leveled_type ) Σ)) as q'.\n      assert (a=q').\n        unfold a.\n        unfold q'.\n        clear a q'.\n        induction Σ.\n          destruct a.\n          simpl.\n          rewrite flatten_commutes_with_weakLT.\n          reflexivity.\n          reflexivity.\n          simpl.\n          rewrite <- IHΣ1.\n          rewrite <- IHΣ2.\n          reflexivity.\n      rewrite H.\n      apply nd_id.\n      apply Δ.\n      apply Δ.\n      apply (Prelude_error \"found type abstraction at level >0; this is not supported\").\n\n    destruct case_RAppCo.\n      simpl. destruct lev; simpl.\n      unfold flatten_type.\n      simpl.\n      apply nd_rule.\n      apply RAppCo.\n      apply flatten_coercion.\n      apply γ.\n      apply (Prelude_error \"found coercion application at level >0; this is not supported\").\n\n    destruct case_RAbsCo.\n      simpl. destruct lev; simpl.\n      unfold flatten_type.\n      simpl.\n      apply (Prelude_error \"AbsCo not supported (FIXME)\").\n      apply (Prelude_error \"found coercion abstraction at level >0; this is not supported\").\n\n    destruct case_RLetRec.\n      rename t into lev.\n      simpl. destruct lev; simpl.\n      apply nd_rule.\n      set (@RLetRec Γ Δ (mapOptionTree flatten_leveled_type lri) (flatten_type x) (mapOptionTree flatten_type y) nil) as q.\n      replace (mapOptionTree flatten_leveled_type (y @@@ nil)) with (mapOptionTree flatten_type y @@@ nil).\n      apply q.\n        induction y; try destruct a; auto.\n        simpl.\n        rewrite IHy1.\n        rewrite IHy2.\n        reflexivity.\n      repeat drop_simplify.\n      repeat take_simplify.\n      simpl.\n      rewrite drop_to_nothing.\n      eapply nd_comp.\n        eapply nd_rule.\n        eapply RArrange.\n        eapply AComp.\n        eapply ARight.\n        apply arrangeCancelEmptyTree with (q:=y).\n          induction y; try destruct a; auto.\n          simpl.\n          rewrite <- IHy1.\n          rewrite <- IHy2.\n          reflexivity.\n        apply ACanL.\n        rewrite take_lemma'.\n        set (mapOptionTree (flatten_type ○ unlev) (take_lev (h :: lev) lri)) as lri'.\n        set (mapOptionTree flatten_leveled_type (drop_lev (h :: lev) lri)) as lri''.\n        replace (mapOptionTree (flatten_type ○ unlev) (y @@@ (h :: lev))) with (mapOptionTree flatten_type y).\n        apply boost.\n        apply ga_loopl.\n        rewrite <- mapOptionTree_compose.\n        simpl.\n        reflexivity.\n\n    destruct case_RCase.\n      destruct lev; [ idtac | apply (Prelude_error \"case at depth >0\") ]; simpl.\n      apply nd_rule.\n      rewrite <- mapOptionTree_compose.\n      replace (mapOptionTree\n        (fun x  => flatten_judgment (pcb_judg (snd x)))\n        alts,, [Γ > Δ > mapOptionTree flatten_leveled_type Σ |- [flatten_type (caseType tc avars)] @ nil])\n      with\n        (mapOptionTree\n           (fun x  => @pcb_judg tc Γ Δ nil (flatten_type tbranches) avars (fst x) (snd x))\n           alts,,\n           [Γ > Δ > mapOptionTree flatten_leveled_type Σ |- [caseType tc avars] @ nil]).\n      replace (mapOptionTree flatten_leveled_type\n        (mapOptionTreeAndFlatten\n           (fun x  => (snd x)) alts))\n      with (mapOptionTreeAndFlatten\n           (fun x =>\n            (snd x)) alts).\n      apply RCase.\n      admit.\n      admit.\n\n    destruct case_SBrak.\n      simpl.\n      destruct lev.\n      drop_simplify.\n      set (drop_lev (ec :: nil) (take_arg_types_as_tree t @@@ (ec :: nil))) as empty_tree.\n      take_simplify.\n      rewrite take_lemma'.\n      simpl.\n      rewrite mapOptionTree_compose.\n      rewrite mapOptionTree_compose.\n      rewrite unlev_relev.\n      rewrite <- mapOptionTree_compose.\n      simpl.\n      rewrite krunk.\n      set (mapOptionTree flatten_leveled_type (drop_lev (ec :: nil) succ)) as succ_host.\n      set (mapOptionTree (flatten_type ○ unlev)(take_lev (ec :: nil) succ)) as succ_guest.\n      set (mapOptionTree flatten_type (take_arg_types_as_tree t)) as succ_args.\n      unfold empty_tree.\n      eapply nd_comp; [ eapply nd_rule; eapply RArrange; eapply ALeft; apply tree_of_nothing | idtac ].\n      eapply nd_comp; [ eapply nd_rule; eapply RArrange; eapply ACanR | idtac ].\n      refine (ga_unkappa Γ Δ (v2t ec) nil _ _ _ _ ;; _).\n      eapply nd_comp; [ idtac | eapply arrange_brak ].\n      unfold succ_host.\n      unfold succ_guest.\n      eapply nd_rule.\n        eapply RArrange.\n        apply AExch.\n      apply (Prelude_error \"found Brak at depth >0 indicating 3-level code; only two-level code is currently supported\").\n\n    destruct case_SEsc.\n      simpl.\n      destruct lev.\n      simpl.\n      unfold flatten_leveled_type at 2.\n      simpl.\n      rewrite krunk.\n      rewrite mapOptionTree_compose.\n      take_simplify.\n      drop_simplify.\n      simpl.\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply ALeft; apply tree_of_nothing' ].\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply ACanR ].\n      simpl.\n      rewrite take_lemma'.\n      rewrite unlev_relev.\n      rewrite <- mapOptionTree_compose.\n      eapply nd_comp; [ apply (arrange_esc _ _ ec) | idtac ].\n\n      set (decide_tree_empty (take_lev (ec :: nil) succ)) as q'.\n      destruct q'.\n      destruct s.\n      rewrite e.\n      clear e.\n\n      set (mapOptionTree flatten_leveled_type (drop_lev (ec :: nil) succ)) as succ_host.\n      set (mapOptionTree flatten_type (take_arg_types_as_tree t)) as succ_args.\n\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; apply AuCanR ].\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; apply AuCanR ].\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; apply ACanL ].\n      eapply nd_comp; [ idtac | eapply RLet ].\n      eapply nd_comp; [ apply nd_llecnac | idtac ].\n      apply nd_prod; [ idtac | eapply boost ].\n      induction x.\n        apply ga_id.\n        eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply ACanL ].\n        simpl.\n        apply ga_join.\n          apply IHx1.\n          apply IHx2.\n          simpl.\n          apply postcompose.\n\n      refine ( _ ;; (boost _ _ _ _ _ (postcompose _ _ _ _ _ _ _ _))).\n      apply ga_cancell.\n      apply firstify.\n\n      induction x.\n        destruct a; simpl.\n        apply ga_id.\n        simpl.\n        refine ( _ ;; (boost _ _ _ _ _ (postcompose _ _ _ _ _ _ _ _))).\n        apply ga_cancell.\n        refine ( _ ;; (boost _ _ _ _ _ (postcompose _ _ _ _ _ _ _ _))).\n        eapply firstify.\n        apply IHx1.\n        apply secondify.\n        apply IHx2.\n\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AuCanR ].\n      eapply nd_comp; [ idtac | eapply nd_rule; eapply RArrange; eapply AuCanR ].\n\n      replace (mapOptionTree (fun ht => levels_to_tcode (unlev ht) (getlev ht) @@  nil) (drop_lev (ec :: nil) succ))\n        with (mapOptionTree flatten_leveled_type (drop_lev (ec :: nil) succ)).\n      eapply nd_comp; [ eapply nd_rule; eapply RArrange; eapply AExch | idtac ].\n      apply ga_kappa.\n      induction succ.\n        destruct a.\n        destruct l.\n        Transparent drop_lev.\n        simpl.\n        unfold drop_lev.\n        Opaque drop_lev.\n        unfold mkDropFlags.\n        simpl.\n        destruct (General.list_eq_dec h1 (ec :: nil)).\n        simpl.\n        auto.\n        simpl.\n        unfold flatten_leveled_type.\n        simpl.\n        auto.\n        simpl.\n        auto.\n        simpl.\n        drop_simplify.\n        simpl.\n        rewrite IHsucc1.\n        rewrite IHsucc2.\n        reflexivity.\n\n      (* nesting too deep *)\n      apply (Prelude_error \"found Esc at depth >0 indicating 3-level code; only two-level code is currently supported\").\n      Defined.\n\n  Definition flatten_proof :\n    forall  {h}{c},\n      ND  Rule h c ->\n      ND  Rule h c.\n    apply (Prelude_error \"sorry, non-skolemized flattening isn't implemented\").\n    Defined.\n\n  Definition skolemize_and_flatten_proof :\n    forall  {h}{c},\n      ND  Rule h c ->\n      ND  Rule\n           (mapOptionTree (flatten_judgment ○ skolemize_judgment) h)\n           (mapOptionTree (flatten_judgment ○ skolemize_judgment) c).\n    intros.\n    rewrite mapOptionTree_compose.\n    rewrite mapOptionTree_compose.\n    apply flatten_skolemized_proof.\n    apply skolemize_proof.\n    apply X.\n    Defined.\n\n\n  (* to do: establish some metric on judgments (max length of level of any succedent type, probably), show how to\n   * calculate it, and show that the flattening procedure above drives it down by one *)\n\n  (*\n  Instance FlatteningFunctor {Γ}{Δ}{ec} : Functor (JudgmentsL (PCF Γ Δ ec)) (TypesL (SystemFCa Γ Δ)) (obact) :=\n    { fmor := FlatteningFunctor_fmor }.\n\n  Definition ReificationFunctor Γ Δ : Functor (JudgmentsL _ _ (PCF n Γ Δ)) SystemFCa' (mapOptionTree brakifyJudg).\n    refine {| fmor := ReificationFunctor_fmor Γ Δ |}; unfold hom; unfold ob; simpl ; intros.\n\n  Definition PCF_SMME (n:nat)(Γ:TypeEnv)(Δ:CoercionEnv Γ) : ProgrammingLanguageSMME.\n    refine {| plsmme_pl := PCF n Γ Δ |}.\n    Defined.\n\n  Definition SystemFCa_SMME (n:nat)(Γ:TypeEnv)(Δ:CoercionEnv Γ) : ProgrammingLanguageSMME.\n    refine {| plsmme_pl := SystemFCa n Γ Δ |}.\n    Defined.\n\n  Definition ReificationFunctorMonoidal n : MonoidalFunctor (JudgmentsN n) (JudgmentsN (S n)) (ReificationFunctor n).\n    Defined.\n\n  (* 5.1.4 *)\n  Definition PCF_SystemFCa_two_level n Γ Δ : TwoLevelLanguage (PCF_SMME n Γ Δ) (SystemFCa_SMME (S n) Γ Δ).\n    Defined.\n  *)\n  (*  ... and the retraction exists *)\n\nEnd HaskFlattener.\n\nImplicit Arguments garrow [ ].\n", "meta": {"author": "cartazio", "repo": "coq-hetmet", "sha": "0a6fb1705e459370d0afab10fed55e4165bf0fa8", "save_path": "github-repos/coq/cartazio-coq-hetmet", "path": "github-repos/coq/cartazio-coq-hetmet/coq-hetmet-0a6fb1705e459370d0afab10fed55e4165bf0fa8/src/HaskFlattener.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199306096344, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2003791999637229}}
{"text": "Require Import HoareDef SimModSem.\nRequire Import Coqlib.\nRequire Import ImpPrelude.\nRequire Import Skeleton.\nRequire Import PCM.\nRequire Import ModSem Behavior.\nRequire Import Relation_Definitions.\n\n(*** TODO: export these in Coqlib or Universe ***)\nRequire Import Relation_Operators.\nRequire Import RelationPairs.\nFrom ITree Require Import\n     Events.MapDefault.\nFrom ExtLib Require Import\n     Core.RelDec\n     Structures.Maps\n     Data.Map.FMapAList.\nRequire Import HTactics ProofMode IPM.\nRequire Import OpenDef.\nRequire Import Mem1 MemOpen STB.\n\nRequire Import Imp.\nRequire Import ImpNotations.\nRequire Import ImpProofs.\n\nRequire Import Echo0 EchoImp.\n\nSet Implicit Arguments.\n\nLocal Open Scope nat_scope.\n\nSection SIMMODSEM.\n\n  Import ImpNotations.\n\n  Context `{Σ: GRA.t}.\n\n  Let W: Type := Any.t * Any.t.\n\n  Let wf: unit -> W -> Prop :=\n    fun _ '(mrps_src0, mrps_tgt0) =>\n      (<<SRC: mrps_src0 = tt↑>>) /\\\n      (<<TGT: mrps_tgt0 = tt↑>>)\n  .\n\n  Theorem correct:\n    refines2 [EchoImp.Echo] [Echo0.Echo].\n  Proof.\n    eapply adequacy_local2. econs; ss. i.\n    econstructor 1 with (wf:=wf) (le:=top2); et; ss.\n    econs; ss.\n    { init.\n      unfold echo_body, echo.\n      steps.\n      rewrite unfold_eval_imp. steps.\n      des_ifs.\n      2:{ exfalso; apply n. solve_NoDup. }\n      unfold ccallU. imp_steps.\n      red. esplits; et.\n    }\n    econs; ss.\n    { init.\n      unfold input_body, input.\n      steps.\n      rewrite unfold_eval_imp. steps.\n      des_ifs.\n      2:{ exfalso; apply n. solve_NoDup. }\n      unfold ccallU. imp_steps.\n      des. destruct v0; ss; clarify.\n      des_ifs.\n      - imp_steps. red. esplits; et. ss.\n      - rewrite Z.eqb_eq in Heq0. clarify.\n      - imp_steps. red. esplits; et.\n    }\n    econs; ss.\n    { init.\n      unfold output_body, output.\n      steps.\n      rewrite unfold_eval_imp. steps.\n      des_ifs.\n      2:{ exfalso; apply n. solve_NoDup. }\n      unfold ccallU. imp_steps.\n      des. destruct v0; ss; clarify.\n      des_ifs.\n      - imp_steps. red. esplits; et. ss.\n      - rewrite Z.eqb_eq in Heq0. clarify.\n      - imp_steps. red. esplits; et.\n    }\n    Unshelve. all: try exact 0. all: ss.\n  Qed.\n\nEnd SIMMODSEM.\n", "meta": {"author": "alxest", "repo": "CCR", "sha": "edcda8faae6580581e8e5b28050d755bcb29f55f", "save_path": "github-repos/coq/alxest-CCR", "path": "github-repos/coq/alxest-CCR/CCR-edcda8faae6580581e8e5b28050d755bcb29f55f/examples/echo/EchoImp0proof.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.20037919417851446}}
{"text": "(**************************************************************************)\n(*   Mechanised Framework for Local Interactions & Distributed Algorithms *)\n(*   P. Courtieu, L. Rieg, X. Urbain                                      *)\n(*   PACTOLE project                                                      *)\n(*                                                                        *)\n(*   This file is distributed under the terms of the CeCILL-C licence.    *)\n(*                                                                        *)\n(**************************************************************************)\n\n\nRequire Import Utf8_core.\nRequire Import Arith_base.\nRequire Import Lia.\nRequire Import SetoidList.\nRequire Import SetoidDec.\nRequire Import Pactole.Util.Preliminary.\nRequire Import Pactole.Core.Identifiers.\nRequire Import Pactole.Core.State.\nRequire Import Pactole.Core.Configuration.\nRequire Import Pactole.Observations.Definition.\nClose Scope R_scope.\nSet Implicit Arguments.\n\n\nSection CompositionObservation.\n\n(** **  Loosing information inside the state before building the observation  **)\nContext {Loc : Location}.\nContext {info1 info2 : Type}.\nContext {St1 : @State _ info1}.\nContext {St2 : @State _ info2}.\nContext {N : Names}.\nContext (Obs : @Observation _ _ St2 _).\n\nVariable f : info1 -> info2.\nHypothesis f_compat : Proper (equiv ==> equiv) f.\n\n(* TODO: find a better name *)\nInstance FObservation : @Observation _ _ St1 _.\nrefine {|\n  obs_from_config := fun config st => obs_from_config (map_config f config) (f st);\n  obs_is_ok := fun sp config st => obs_is_ok sp (map_config f config) (f st) |}.\nProof.\n(* BUG?: + forbidden here? *)\n+ autoclass.\n+ repeat intro. do 2 (f_equiv; trivial).\n+ intros. apply obs_from_config_spec.\nDefined.\n\nEnd CompositionObservation.\n\nArguments FObservation {_} {info1} {info2} {_} {_} {_} _ f {_}.\n", "meta": {"author": "MathisBD", "repo": "pactole_stage", "sha": "4b63da0898ae4f48956408dc31f7831d3ad8930f", "save_path": "github-repos/coq/MathisBD-pactole_stage", "path": "github-repos/coq/MathisBD-pactole_stage/pactole_stage-4b63da0898ae4f48956408dc31f7831d3ad8930f/Observations/PreCompositionObservation.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.3380771241500058, "lm_q1q2_score": 0.20036701482753047}}
{"text": "Require Import ExtLib.Core.Any.\n\nSet Implicit Arguments.\nSet Strict Implicit.\n\nPolymorphic Class Functor@{d c} (F : Type@{d} -> Type@{c}) : Type :=\n{ fmap : forall {A B : Type@{d}}, (A -> B) -> F A -> F B }.\n\nPolymorphic Definition ID@{d} {T : Type@{d}} (f : T -> T) : Prop :=\n  forall x : T, f x = x.\n\nModule FunctorNotation.\n  Notation \"f <$> x\" := (@fmap _ _ _ _ f x) (at level 52, left associativity).\nEnd FunctorNotation.\n", "meta": {"author": "coq-community", "repo": "coq-ext-lib", "sha": "4811a83db9ccd81f4dcbf77eeff0484dfb21a48b", "save_path": "github-repos/coq/coq-community-coq-ext-lib", "path": "github-repos/coq/coq-community-coq-ext-lib/coq-ext-lib-4811a83db9ccd81f4dcbf77eeff0484dfb21a48b/theories/Structures/Functor.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.20006036526661636}}
{"text": "Require Import AutoSep Malloc Bootstrap Factorial.\n\n\nModule Type S.\n  Variable heapSize : nat.\nEnd S.\n\nModule Make(M : S).\nImport M.\n\nSection boot.\n  Hypothesis heapSizeLowerBound : (3 <= heapSize)%nat.\n\n  Definition size := heapSize + 50 + 0.\n\n  Hypothesis mem_size : goodSize (size * 4)%nat.\n\n  Let heapSizeUpperBound : goodSize (heapSize * 4).\n    goodSize.\n  Qed.\n\n  Definition bootS := bootS heapSize 0.\n\n  Definition boot := bimport [[ \"malloc\"!\"init\" @ [Malloc.initS], \"top\"!\"top\" @ [topS] ]]\n    bmodule \"main\" {{\n      bfunctionNoRet \"main\"() [bootS]\n        Sp <- (heapSize * 4)%nat;;\n\n        Assert [PREonly[_] 0 =?> heapSize];;\n\n        Call \"malloc\"!\"init\"(0, heapSize)\n        [PREonly[_] mallocHeap 0];;\n\n        Call \"top\"!\"top\"()\n        [PREonly[_] [| False |] ]\n      end\n    }}.\n\n  Theorem ok : moduleOk boot.\n    vcgen; abstract genesis.\n  Qed.\n\n  Definition m0 := link Malloc.m boot.\n  Definition m1 := link all m0.\n\n  Lemma ok0 : moduleOk m0.\n    link Malloc.ok ok.\n  Qed.\n\n  Lemma ok1 : moduleOk m1.\n    link all_ok ok0.\n  Qed.\n\n  Variable stn : settings.\n  Variable prog : program.\n  \n  Hypothesis inj : forall l1 l2 w, Labels stn l1 = Some w\n    -> Labels stn l2 = Some w\n    -> l1 = l2.\n\n  Hypothesis agree : forall l pre bl,\n    LabelMap.MapsTo l (pre, bl) (XCAP.Blocks m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = Some bl.\n\n  Hypothesis agreeImp : forall l pre, LabelMap.MapsTo l pre (XCAP.Imports m1)\n    -> exists w, Labels stn l = Some w\n      /\\ prog w = None.\n\n  Hypothesis omitImp : forall l w,\n    Labels stn (\"sys\", l) = Some w\n    -> prog w = None.\n\n  Variable w : W.\n  Hypothesis at_start : Labels stn (\"main\", Global \"main\") = Some w.\n\n  Variable st : state.\n\n  Hypothesis mem_low : forall n, (n < size * 4)%nat -> st.(Mem) n <> None.\n  Hypothesis mem_high : forall w, ($(size * 4) <= w)%word -> st.(Mem) w = None.\n\n  Theorem safe : sys_safe stn prog (w, st).\n    safety ok1.\n  Qed.\nEnd boot.\n\nEnd Make.\n", "meta": {"author": "mmcco", "repo": "Verified-BPF", "sha": "f103ec2b08344c72e6d4fc6d08b8844f01748676", "save_path": "github-repos/coq/mmcco-Verified-BPF", "path": "github-repos/coq/mmcco-Verified-BPF/Verified-BPF-f103ec2b08344c72e6d4fc6d08b8844f01748676/bedrock/platform/cito/examples/FactorialDriver.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.20006035780038176}}
{"text": "(*\n\n\nAuthor:  Adam Petz, ampetz@ku.edu\n*)\n\nRequire Import ConcreteEvidence GenStMonad.\nRequire Import Maps. (*OptMonad*) (* MonadAM *)  (*StructTact.StructTactics. *)\n\nRequire Import StructTactics.\nRequire Import List.\nImport ListNotations.\n\nRequire Import Coq.Arith.EqNat.\n\n(*\nInductive App_Instr: Set :=\n| asp_app: ASP_ID -> BS -> App_Instr\n| g_app: Plc -> BS -> EvidenceC -> App_Instr\n| h_app: BS -> EvidenceC -> App_Instr\n| n_app: N_ID -> BS -> App_Instr.\n\nFixpoint app_compile (e:EvidenceC) : list App_Instr :=\n  match e with\n  | mtc => []\n  | uuc i bs e' => [asp_app i bs] ++ (app_compile e')\n  | ggc p bs e' => [g_app p bs e'] ++ (app_compile e')                   \n  | hhc bs e' => [h_app bs e'] ++ (app_compile e')\n  | nnc n_id bs e' => [n_app n_id bs] ++ (app_compile e')\n  | ssc e1 e2 => (app_compile e1) ++ (app_compile e2)\n  | ppc e1 e2 => (app_compile e1) ++ (app_compile e2)\n  end.\n\nNotation Pri_Key := nat (only parsing).\n\nDefinition pri_keys : Map Plc Pri_Key. Admitted.\nDefinition golden_measurements : Map ASP_ID BS. Admitted.\nDefinition nonce_map : Map N_ID BS. Admitted.\n\n(* params: id -> golden -> actual *)\nDefinition check_measurement : ASP_ID -> BS -> BS -> bool. Admitted.\nDefinition encode_ev : EvidenceC -> BS. Admitted.\n(* params: encoded payload -> private key -> signature *)\nDefinition check_sig : BS -> Pri_Key -> BS -> bool. Admitted.\n\nDefinition check_ev_sig (e:EvidenceC) (k:Pri_Key) (sig:BS) : bool :=\n  let payload := encode_ev e in\n  check_sig payload k sig.\n\n(*\nDefinition check_ev_pl (e:EvidenceC) (p:Plc) (sig:BS) : option bool :=\n  k <- map_get pri_keys p ;; \n    ret (check_ev_sig e k sig). *)\n\n(* params: payload -> hash *)\n(* TODO: incorporate hash algorithm choice (policy) here? *)\nDefinition check_hash : BS -> BS -> bool. Admitted.\n\nDefinition check_ev_hash (e:EvidenceC) (bs:BS) : bool :=\n  let payload := encode_ev e in\n  check_hash payload bs.\n\nCheck Nat.eqb.\n*)\n\n(*\nDefinition check_nonce (n : N_ID) (bs:BS) : option bool :=\n  g_bs <- map_get nonce_map n ;;\n       ret (Nat.eqb bs g_bs).   \n\n\nDefinition check_asp (x:ASP_ID) (m:BS) : option bool :=\n  g_bs <- (map_get golden_measurements x) ;;\n       ret (check_measurement x g_bs m).\n\nFixpoint appraise (e:EvidenceC) : option bool :=\n  match e with\n  | mtc => Some true\n  | uuc i bs e =>\n    b <- check_asp i bs ;;\n      res <- appraise e ;;\n      ret (andb b res)\n  | ggc p sig e =>\n    b <- check_ev_pl e p sig ;;\n      res <- appraise e ;;\n          ret (andb b res)\n  | hhc h e =>\n    let b := check_ev_hash e h in\n      res <- appraise e ;;\n          ret (andb b res)\n  | nnc n_id bs e =>\n    b <- check_nonce n_id bs ;;\n      res <- appraise e ;;\n      ret (andb b res)\n  | ssc e1 e2 =>\n    res1 <- appraise e1 ;;\n         res2 <- appraise e2 ;;\n         ret (andb res1 res2)\n  | ppc e1 e2 =>\n    res1 <- appraise e1 ;;\n         res2 <- appraise e2 ;;\n         ret (andb res1 res2)\n  end.\n\nDefinition appraiseI' (i:App_Instr): option bool :=\n  match i with\n  | asp_app x bs => check_asp x bs\n  | g_app p bs e' => check_ev_pl e' p bs\n  | h_app bs e' => Some (check_ev_hash e' bs)\n  | n_app nid bs => check_nonce nid bs\n  end.\n\nFixpoint appraiseI (o:option bool) (i:App_Instr): option bool :=\n  b <- o ;;\n    b' <- appraiseI' i ;;\n    ret (andb b b').\n    \nCheck fold_left.\nDefinition run_app (il:list App_Instr) : option bool :=\n  fold_left appraiseI il (Some true).\n    \n\nTheorem app_eq_appI: forall e,\n    let il := app_compile e in\n    appraise e = run_app il.\nAbort.\n\n\n\nRequire Import StVM Instr VmSemantics.\n\nDefinition mt_st := mk_st mtc [] [] 0 [].\n\nTheorem can_app: forall t,\n    let att_il := instr_compiler t in\n    let ev_res := run_vm_t t mt_st in\n    let app_il := app_compile (st_ev ev_res) in\n    let optB := run_app app_il in\n    exists b, optB = Some b.\nAbort.\n *)\n\n\n\n\n(* Specific APP monad state *)\nDefinition sig_map := MapC Plc ASP_ID.\nDefinition hsh_map := MapC Plc ASP_ID.\nDefinition asp_map := MapC (Plc * ASP_ID) ASP_ID.\nRecord app_st : Type := mk_app_st\n                         {st_sigmap :sig_map;\n                          st_hshmap :hsh_map; \n                          st_aspmap :asp_map;\n                          st_nonceCheck_asp :ASP_ID}.\n\nDefinition empty_app_st := mk_app_st [] [] [] 0.\nCheck empty_app_st.\n\n\nDefinition APP := St app_st.\n\n(*\nDefinition am_get_asp_asp (p:Plc) (i:ASP_ID) : APP ASP_ID :=\n  m <- gets asp_map ;;\n  let maybeId = M.lookup (p,i) m\n  case maybeId of\n   Just newI -> return newI\n   Nothing -> error $ \"appraisal asp for ASP_ID \" ++ (show i) ++ \" at place \" ++ (show p) ++ \" not registered.\"\n*)\n\nFixpoint gen_appraisal_term (e:EvidenceC) (et:Evidence) : APP Term :=\n  match e with\n  | mtc =>\n    match et with\n    | mt => ret (asp CPY)\n    | _ => failm\n    end\n  | uuc i bs e' =>\n    match et with \n    | uu i_t p e'_t =>\n      let app_id := 0 in (* app_id <- am_get_asp_asp p i_t *)\n      t2 <- gen_appraisal_term e' e'_t ;;\n      let t1 := (asp (ASPC app_id)) in\n      let res := (bpar (NONE,NONE) t1 t2) in\n                     ret res\n    | _ => failm\n    end\n  | ggc bs e' =>\n    match et with\n    | gg p e'_t =>\n        let sig_id := 42 in      (* sig_id <- am_get_sig_asp p *)\n        (* let evBits = encodeEv e' --BL.toStrict (DA.encode e)\n            evBitsArg = show evBits\n            sigArg = show bs *)\n        t2 <- gen_appraisal_term e' e'_t ;;\n        let t1 := (asp (ASPC sig_id)) in   (* (ASP sig_id [evBitsArg,sigArg]) *)\n        let res := (bpar (NONE,NONE) t1 t2) in   (* BRP (NONE,NONE) t1 t2 *)\n        ret res\n    | _ => failm\n    end\n  | hhc bs e' =>\n    match et with\n    | hh p e'_t =>\n        let hsh_id := 0 in      (* hsh_id <- am_get_hsh_asp p *)\n        (* let evBits = encodeEv e' --BL.toStrict (DA.encode e)\n            evBitsArg = show evBits\n            sigArg = show bs *)\n        t2 <- gen_appraisal_term e' e'_t ;;\n        let t1 := (asp (ASPC hsh_id)) in   (* (ASP sig_id [evBitsArg,sigArg]) *)\n        let res := (bpar (NONE,NONE) t1 t2) in   (* BRP (NONE,NONE) t1 t2 *)\n        ret res\n    | _ => failm\n    end\n  | ssc e1 e2 =>\n    match et with\n    | ss e1_t e2_t => \n      t1' <- (gen_appraisal_term e1 e1_t) ;;\n          t2' <- (gen_appraisal_term e2 e2_t) ;;\n          let res := (bpar (NONE,NONE) t1' t2') in (* BRP (NONE,NONE) t1' t2' *)\n          ret res\n    | _ => failm\n    end\n  | ppc e1 e2 =>\n    match et with\n    | pp e1_t e2_t => \n      t1' <- (gen_appraisal_term e1 e1_t) ;;\n          t2' <- (gen_appraisal_term e2 e2_t) ;;\n          let res := (bpar (NONE,NONE) t1' t2') in (* BRP (NONE,NONE) t1' t2' *)\n          ret res\n    | _ => failm\n    end      \n  | nnc _ _ _ =>  ret (asp CPY) (* Dummy nonce case for now.  TODO: robustify *)\n  end.\n    \n\n\n\n\n\n\n\n\n\n\n\n\n(*\nDefinition helper_gen_app (a:ASP) (p:Plc) (e:EvidenceC) : APP (Term * EvidenceC) :=\n  match a with\n  | CPY => ret (asp CPY,e)\n  | ASPC i =>\n    match e with\n    | uuc _ bs e' => ret (asp (ASPC 0),e')\n    | _ => failm\n    end\n  | SIG =>\n    match e with\n    | ggc _ _ e' => ret (asp (ASPC 0),e')\n    | _ => failm\n    end\n  | HSH =>\n    match e with\n    | hhc _ e' => ret (asp (ASPC 0),e')\n    | _ => failm\n    end\n  end.\n    \n               \n  \n\nFixpoint gen_appraisal_term' (t:Term) (p:Plc) (e:EvidenceC) : APP (Term * EvidenceC) :=\n  match t with\n  | asp a => helper_gen_app a p e\n  | att q t' => gen_appraisal_term' t' q e\n  | lseq t1 t2 =>\n   (* (t2', e2) *)v2 <- (gen_appraisal_term' t2 p e) ;;\n             (* (t1',e1) *) v1 <- (gen_appraisal_term' t1 p (snd v2)) ;;\n                     ret ((bpar (NONE,NONE) (fst v1) (fst v2)),(snd v1))\n  | bseq _ t1 t2 =>\n      match e with\n      | ssc e1 e2 =>   \n        (* (t1',_) *) v1 <- (gen_appraisal_term' t1 p e1) ;;\n        (* (t2',_) *) v2 <- (gen_appraisal_term' t2 p e2) ;;\n        ret ((bpar (NONE,NONE) (fst v1) (fst v2)),mtc)\n      |_ => failm (* error \"evidence mismath on BRS-SS\" *)\n      end\n  | bpar _ t1 t2 =>\n      match e with\n      | ppc e1 e2 =>   \n        (* (t1',_) *) v1 <- (gen_appraisal_term' t1 p e1) ;;\n        (* (t2',_) *) v2 <- (gen_appraisal_term' t2 p e2) ;;\n        ret ((bpar (NONE,NONE) (fst v1) (fst v2)),mtc)\n      |_ => failm (* error \"evidence mismath on BRP-PP\" *)\n      end\n  end.\n\n*)\n\nRequire Import MonadVM VmSemantics.\n\n(*\nLemma run_vm_good_ev : forall t tr tr' e e' s s' p p' o o',\n  run_vm (instr_compiler t)\n         {| st_ev := e;\n            st_stack := s;\n            st_trace := tr;\n            st_pl := p;\n            st_store := o |} =\n  {| st_ev := e';\n     st_stack := s';\n     st_trace := tr';\n     st_pl := p';\n     st_store := o' |} ->\n  EvcT (unanno t) e e'.\nProof.\nAdmitted.\n*)\n\n\nSet Nested Proofs Allowed.\n\n\n\n\n(*\nLemma EvcT_iff_eval : forall annt e e',\n    eval annt e = e' <-> EvcT annt e e'.\nAdmitted.\n*)\n\nRequire Import Coq.Program.Tactics.\n\nDefinition aterm := lseq (asp (ASPC 1)) (asp SIG).\n\nPrint anno.\n\nDefinition aev := (run_vm (annotated aterm)\n                          {| st_ev := mtc;\n                             st_trace := [];\n                             st_pl := 0;\n                             st_store := [] |}).\nCompute (st_ev aev).\nPrint signEv.\n\nCompute (gen_appraisal_term (st_ev aev) (gg 0 (uu 1 0 mt))).\n\nTheorem someEv_if_well_formed : forall e' app_st e't,\n  Ev_Shape e' e't -> \n  exists app_st' v,\n    runSt app_st (gen_appraisal_term e' e't) = (Some v,app_st').\nProof.\n  intros.\n  generalize dependent app_st0.\n  induction H; intros;\n    try (simpl; eexists; eexists; reflexivity).\n  - simpl.\n    edestruct IHEv_Shape.\n    destruct_conjs.\n    eexists; eexists.\n    simpl.\n    monad_unfold.\n    unfold runSt in *.\n    rewrite H1.\n    reflexivity.\n  - simpl.\n    edestruct IHEv_Shape.\n    destruct_conjs.\n    eexists; eexists.\n    monad_unfold.\n    unfold runSt in *.\n    rewrite H1.\n    reflexivity.\n  - simpl.\n    edestruct IHEv_Shape.\n    destruct_conjs.\n    eexists; eexists.\n    monad_unfold.\n    unfold runSt in *.\n    rewrite H1.\n    reflexivity.\n  - simpl.\n    edestruct IHEv_Shape1.\n    edestruct IHEv_Shape2.\n    destruct_conjs.\n    eexists; eexists.\n    monad_unfold.\n    unfold runSt in *.\n    rewrite H4.\n    rewrite H3.\n    reflexivity.\n  - simpl.\n    edestruct IHEv_Shape1.\n    edestruct IHEv_Shape2.\n    destruct_conjs.\n    eexists; eexists.\n    monad_unfold.\n    unfold runSt in *.\n    rewrite H4.\n    rewrite H3.\n    reflexivity.\nDefined.\n\n\n(* \nLemma eval_iff_evalR: forall t p e e',\n    evalR t p e e' <-> eval t p e = e'.\n *)\n\n(*\nLemma multi_ev_eval : forall t tr tr' e e' s s' p p' o o',\n    run_vm (instr_compiler t)\n           {| st_ev := e; st_stack := s;  st_trace := tr; st_pl := p; st_store := o |} =\n           {| st_ev := e'; st_stack := s'; st_trace := tr'; st_pl := p'; st_store := o' |}  ->\n    e' = eval (unanno t) e.\n *)\n\n(*\nTheorem someEv_if_well_formed : forall e' app_st e't,\n  Ev_Shape e' e't -> \n  exists app_st' v,\n    runSt app_st (gen_appraisal_term e' e't) = (Some v,app_st').\n *)\n\nAxiom para_eval_thread: forall e annt,\n    parallel_eval_thread annt e = eval annt e.\n\nLemma evShape_eval: forall e et p annt,\n    Ev_Shape e et ->\n    Ev_Shape (eval annt e) (Term.eval annt p et).\nProof.\n  intros.\n  generalize dependent p.\n  generalize dependent e.\n  generalize dependent et.\n  induction annt; intros.\n  - simpl.\n    destruct a; simpl; eauto.\n  - simpl.\n    rewrite <- remote_eval.\n    eauto.\n  - simpl.\n    eauto.\n  - destruct s.\n    destruct s; destruct s0; simpl; eauto.\n  - destruct s.\n    destruct s; destruct s0; simpl;\n    repeat rewrite para_eval_thread in *;\n    eauto.\nDefined.\n\n\nLemma someEv' : forall t tr tr' e e' p p' o o' et,\n  run_vm (t)\n         {| st_ev := e;\n            st_trace := tr;\n            st_pl := p;\n            st_store := o |} =\n  {| st_ev := e';\n     st_trace := tr';\n     st_pl := p';\n     st_store := o' |} ->\n\n  Ev_Shape e et ->\n  Ev_Shape e' (Term.eval (unanno t) p et).\nProof.\n  intros.\n  assert (Term.evalR (unanno t) p et (Term.eval (unanno t) p et)).\n  {\n    rewrite Term.eval_iff_evalR. reflexivity.\n  }\n  assert (e' = eval (unanno t) e) as hi.\n  {\n    eapply multi_ev_eval; eauto.\n  }\n  rewrite hi.\n  eapply evShape_eval; eauto.\nDefined.\n\n\nTheorem someEv : forall t tr tr' e e' p p' o o' app_st et,\n  run_vm (t)\n         {| st_ev := e;\n            st_trace := tr;\n            st_pl := p;\n            st_store := o |} =\n  {| st_ev := e';\n     st_trace := tr';\n     st_pl := p';\n     st_store := o' |} ->\n\n Ev_Shape e et ->\n (* evalR (unanno t) p et e't -> (* e't = Term.eval (unanno t) p mt -> *) *)\n  exists app_st' v,\n    runSt app_st (gen_appraisal_term e' (Term.eval (unanno t) p et)) = (Some v,app_st').\nProof.\n  intros.\n  assert (Ev_Shape e' (Term.eval (unanno t) p et)).\n  eapply someEv'; eauto.\n  eapply someEv_if_well_formed; eauto.\nQed.\n\n  \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n  \n    \n    \n    \n    \n(*    \n    \n\nTheorem someEv : forall t tr tr' e e' et s s' p p' o o' app_st e't,\n  run_vm (instr_compiler t)\n         {| st_ev := e;\n            st_stack := s;\n            st_trace := tr;\n            st_pl := p;\n            st_store := o |} =\n  {| st_ev := e';\n     st_stack := s';\n     st_trace := tr';\n     st_pl := p';\n     st_store := o' |} ->\n\n  ET e et ->\n  evalR (unanno t) p et e't -> (* e't = Term.eval (unanno t) p mt -> *)\n  exists app_st' v,\n    runSt app_st (gen_appraisal_term e' e't) = (Some v,app_st').\nProof.\n  intros.\n (* assert (EvcT (unanno t) mtc e').\n  eapply run_vm_good_ev; eauto. *)\n  generalize dependent p.\n  generalize dependent e'.\n  generalize dependent tr.\n  generalize dependent tr'.\n  generalize dependent o.\n  generalize dependent o'.\n  generalize dependent s.\n  generalize dependent s'.\n  generalize dependent p'.\n  generalize dependent app_st0.\n  generalize dependent e't.\n  generalize dependent e.\n  generalize dependent et.\n  induction t; intros.\n  - \n\n    (*\n    assert (EvcT  (unanno (aasp r a)) e e').\n    eapply run_vm_good_ev; eauto. *)\n\n    destruct a; simpl;\n      try (invc H1; invc H;\n           eapply wf_gen; (try econstructor); eauto).\n  -\n    (*\n     assert (EvcT (unanno (aatt r n t)) e e').\n     eapply run_vm_good_ev; eauto. *)\n\n    invc H1.\n    eapply IHt.\n    eassumption.\n\n    simpl in H.\n    monad_unfold.\n    unfold run_vm_step in H. monad_unfold.\n\n\n    rewrite run_at.\n\n\n    assert (eval (unanno t) e = e').\n    { erewrite remote_eval.\n      invc H.\n      destruct r.\n      simpl in *.\n      unfold run_vm_step in *. monad_unfold.\n      invc H2.\n      reflexivity. }\n\n    rewrite H1.\n    reflexivity.\n    eassumption.\n  -\n    invc H1.\n\n    edestruct destruct_compiled_appended.\n    eassumption. clear H.\n    destruct_conjs.\n    fold instr_compiler in *.\n\n    assert (H1 = eval (unanno t1) e) as hi.\n    {\n      admit.\n    }    \n    rewrite hi in *. clear hi.\n\n    (* assert (e'1 = eval (unanno t1) mtc). admit.\n    rewrite <- H13 in H6. *)\n\n    (*\n    edestruct IHt1.\n    eassumption.\n    eassumption.\n    eassumption.\n    destruct_conjs. *)\n\n    eapply IHt2.\n    assert (ET (eval (unanno t1) e) e'0) as hi.\n    { \n      admit.\n    }\n    \n    apply hi.\n    eassumption.\n    assert (p = H2) as hi.\n    {\n      admit.\n    }\n    \n    rewrite <- hi.\n    eassumption.\n  -\n    \n    \n\n\n    apply H10.\n\n\n\n    \n    apply H6.\n    eassumption.\n\n    eapply IHt2.\n    \n                                        \n    \n\n    \n    eassumption.\n    simpl in H6.\n    \n    \n      \n    reflexivity.\n\n    \n    invc H5\n    \n    \n  \n  \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n  intros.\n  assert (EvcT (unanno t) e e').\n  eapply run_vm_good_ev; eauto.\n  generalize dependent p.\n  generalize dependent e.\n  generalize dependent e'.\n  generalize dependent tr.\n  generalize dependent tr'.\n  generalize dependent o.\n  generalize dependent o'.\n  generalize dependent s.\n  generalize dependent s'.\n  generalize dependent p'.\n  induction t; intros.\n  - unfold unanno in *.\n    destruct a; simpl; eexists; eexists;\n      try (invc H0; reflexivity).\n  - Print unanno.\n    simpl.\n    eapply IHt.\n    simpl in H0.\n    invc H0.\n    eassumption.\n    admit.\n  - simpl.\n    invc H0.\n    monad_unfold.\n\n    edestruct destruct_compiled_appended.\n    eassumption.\n    destruct H0. destruct H0. destruct H0. destruct H0. destruct H0.\n\n    destruct H1. destruct H1.\n     assert (EvcT (unanno t2) x0 e'). {\n       eapply run_vm_good_ev. eauto. }\n\n     edestruct IHt2.\n     apply H4.\n     apply H1.\n     destruct H5.\n     assert (p = x2). admit.\n     rewrite H7.\n     rewrite H5.\n\n\n    \n    assert (EvcT (unanno t1) e x0). {\n      eapply run_vm_good_ev; eauto. }\n\n    edestruct IHt1.\n    apply H8.\n    eassumption.\n\n    destruct H9.\n    destruct x6.\n    destruct x8.\n    simpl.\n    rewrite <- H7.\n\n    assert (x0 = e0). admit. (* Interesting symmetry:  t1(e) = x0, gen_app_term t2(e') = e0 *)\n    assert (app_st0 = x5). admit. (* TODO: st immutable *)\n\n    rewrite <- H10.\n    rewrite <- H11.\n    rewrite H9.\n    eexists. eexists. reflexivity.\n  - simpl.\n    invc H0.\n    monad_unfold.\n\n    unfold run_vm_step in H.\n    simpl in H.\n    monad_unfold.\n    \n    edestruct destruct_compiled_appended.\n    eassumption.\n    destruct H0. destruct H0. destruct H0. destruct H0. destruct H0.\n\n    destruct H1. destruct H1.\n\n    do_run.\n    monad_unfold.\n    simpl in H4.\n    monad_unfold.\n    unfold pop_stackm in H4.\n    monad_unfold.\n    simpl in H4.\n\n    edestruct destruct_compiled_appended.\n    eapply H4.\n\n\n\n    \n     assert (EvcT (unanno t2) x0 e'). {\n       eapply run_vm_good_ev; eauto. }\n\n     edestruct IHt2.\n     apply H7.\n     apply H1.\n     destruct H8.\n     destruct H4.\n\n      \n      \n\n\n      }\n    eassumption.\n    admit.\n    \n  \n  *)\n", "meta": {"author": "ku-sldg", "repo": "copland-avm", "sha": "6c08b0e3df96a22cc675bcea309fe99ea7deca65", "save_path": "github-repos/coq/ku-sldg-copland-avm", "path": "github-repos/coq/ku-sldg-copland-avm/copland-avm-6c08b0e3df96a22cc675bcea309fe99ea7deca65/src/extra/Appraisal_old.v", "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.20000828473851012}}
